From 63db2a178b9c069619aabf079713cca2ed5ec569 Mon Sep 17 00:00:00 2001 From: etienne Date: Tue, 17 Apr 2018 14:28:21 -0400 Subject: [PATCH] 1.36.0 --- dist/README.md | 52 +- dist/plot-schema.json | 24423 +++---- dist/plotly-basic.js | 54277 +++++++-------- dist/plotly-basic.min.js | 4 +- dist/plotly-cartesian.js | 64790 +++++++++--------- dist/plotly-cartesian.min.js | 4 +- dist/plotly-finance.js | 56852 ++++++++-------- dist/plotly-finance.min.js | 4 +- dist/plotly-geo-assets.js | 4 +- dist/plotly-geo.js | 20561 +++--- dist/plotly-geo.min.js | 4 +- dist/plotly-gl2d.js | 115128 +++++++++++++++++--------------- dist/plotly-gl2d.min.js | 4 +- dist/plotly-gl3d.js | 25447 +++---- dist/plotly-gl3d.min.js | 4 +- dist/plotly-locale-cs.js | 2 +- dist/plotly-locale-ja.js | 2 +- dist/plotly-mapbox.js | 25279 +++---- dist/plotly-mapbox.min.js | 4 +- dist/plotly-with-meta.js | 55473 ++++++++------- dist/plotly.js | 55216 ++++++++------- dist/plotly.min.js | 4 +- dist/translation-keys.txt | 30 +- package-lock.json | 2 +- package.json | 2 +- src/assets/geo_assets.js | 2 +- src/core.js | 2 +- 27 files changed, 256888 insertions(+), 240688 deletions(-) diff --git a/dist/README.md b/dist/README.md index 5910f7e4121..a679e7e5510 100644 --- a/dist/README.md +++ b/dist/README.md @@ -38,7 +38,7 @@ You can grab the relevant MathJax files in `./dist/extras/mathjax/`. Plotly.js defaults to US English (en-US) and includes British English (en) in the standard bundle. Many other localizations are available - here is an example using Swiss-German (de-CH), see the contents of this directory for the full list. -They are also available on our CDN as https://cdn.plot.ly/plotly-locale-de-ch-latest.js OR https://cdn.plot.ly/plotly-locale-de-ch-1.35.2.js +They are also available on our CDN as https://cdn.plot.ly/plotly-locale-de-ch-latest.js OR https://cdn.plot.ly/plotly-locale-de-ch-1.36.0.js Note that the file names are all lowercase, even though the region is uppercase when you apply a locale. *After* the plotly.js script tag, add: @@ -61,11 +61,11 @@ The main plotly.js bundle includes all the official (non-beta) trace modules. It be can imported as minified javascript - using dist file `dist/plotly.min.js` -- using CDN URL https://cdn.plot.ly/plotly-latest.min.js OR https://cdn.plot.ly/plotly-1.35.2.min.js +- using CDN URL https://cdn.plot.ly/plotly-latest.min.js OR https://cdn.plot.ly/plotly-1.36.0.min.js or as raw javascript: - using dist file `dist/plotly.js` -- using CDN URL https://cdn.plot.ly/plotly-latest.js OR https://cdn.plot.ly/plotly-1.35.2.js +- using CDN URL https://cdn.plot.ly/plotly-latest.js OR https://cdn.plot.ly/plotly-1.36.0.js - using CommonJS with `require('plotly.js')` If you would like to have access to the attribute meta information (including attribute descriptions as on the [schema reference page](https://plot.ly/javascript/reference/)), use dist file `dist/plotly-with-meta.js` @@ -74,7 +74,7 @@ The main plotly.js bundle weights in at: | plotly.js | plotly.min.js | plotly.min.js + gzip | plotly-with-meta.js | |-----------|---------------|----------------------|---------------------| -| 6.1 MB | 2.4 MB | 739.9 kB | 6.3 MB | +| 6.2 MB | 2.4 MB | 754.8 kB | 6.4 MB | ## Partial bundles @@ -98,13 +98,13 @@ The `basic` partial bundle contains the `scatter`, `bar` and `pie` trace modules | dist bundle (minified) | `dist/plotly-basic.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-basic-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-basic-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-basic-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-basic-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-basic-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-basic-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-basic')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 2 MB | 685.4 kB | 229.5 kB | +| 2.1 MB | 691 kB | 231.9 kB | ### plotly.js cartesian @@ -116,13 +116,13 @@ The `cartesian` partial bundle contains the `scatter`, `bar`, `box`, `heatmap`, | dist bundle (minified) | `dist/plotly-cartesian.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-cartesian-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-cartesian-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-cartesian-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-cartesian-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-cartesian-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-cartesian-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-cartesian')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 2.3 MB | 774.3 kB | 260.8 kB | +| 2.4 MB | 779.8 kB | 263.2 kB | ### plotly.js geo @@ -134,13 +134,13 @@ The `geo` partial bundle contains the `scatter`, `scattergeo` and `choropleth` t | dist bundle (minified) | `dist/plotly-geo.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-geo-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-geo-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-geo-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-geo-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-geo-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-geo-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-geo')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 2.1 MB | 707.5 kB | 238.7 kB | +| 2.1 MB | 713.2 kB | 241 kB | ### plotly.js gl3d @@ -152,17 +152,17 @@ The `gl3d` partial bundle contains the `scatter`, `scatter3d`, `surface` and `me | dist bundle (minified) | `dist/plotly-gl3d.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-gl3d-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-gl3d-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-gl3d-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-gl3d-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-gl3d-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-gl3d-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-gl3d')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 3 MB | 1.1 MB | 361.7 kB | +| 3 MB | 1.1 MB | 364.2 kB | ### plotly.js gl2d -The `gl2d` partial bundle contains the `scatter`, `scattergl`, `pointcloud`, `heatmapgl`, `contourgl` and `parcoords` trace modules. +The `gl2d` partial bundle contains the `scatter`, `scattergl`, `splom`, `pointcloud`, `heatmapgl`, `contourgl` and `parcoords` trace modules. | Way to import | Location | |---------------|----------| @@ -170,13 +170,13 @@ The `gl2d` partial bundle contains the `scatter`, `scattergl`, `pointcloud`, `he | dist bundle (minified) | `dist/plotly-gl2d.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-gl2d-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-gl2d-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-gl2d-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-gl2d-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-gl2d-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-gl2d-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-gl2d')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 3 MB | 1.1 MB | 379.7 kB | +| 3.1 MB | 1.2 MB | 393.6 kB | ### plotly.js mapbox @@ -188,13 +188,13 @@ The `mapbox` partial bundle contains the `scatter` and `scattermapbox` trace mod | dist bundle (minified) | `dist/plotly-mapbox.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-mapbox-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-mapbox-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-mapbox-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-mapbox-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-mapbox-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-mapbox-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-mapbox')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 3.3 MB | 1.3 MB | 382.1 kB | +| 3.4 MB | 1.3 MB | 384.5 kB | ### plotly.js finance @@ -206,13 +206,13 @@ The `finance` partial bundle contains the `scatter`, `bar`, `histogram`, `pie`, | dist bundle (minified) | `dist/plotly-finance.min.js` | | CDN URL (latest) | https://cdn.plot.ly/plotly-finance-latest.js | | CDN URL (latest minified) | https://cdn.plot.ly/plotly-finance-latest.min.js | -| CDN URL (tagged) | https://cdn.plot.ly/plotly-finance-1.35.2.js | -| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-finance-1.35.2.min.js | +| CDN URL (tagged) | https://cdn.plot.ly/plotly-finance-1.36.0.js | +| CDN URL (tagged minified) | https://cdn.plot.ly/plotly-finance-1.36.0.min.js | | CommonJS | `require('plotly.js/lib/index-finance')` | | Raw size | Minified size | Minified + gzip size | |------|-----------------|------------------------| -| 2.1 MB | 715.9 kB | 240 kB | +| 2.1 MB | 714.9 kB | 239.9 kB | ---------------- diff --git a/dist/plot-schema.json b/dist/plot-schema.json index 65003a6f6b3..d30f20fe724 100644 --- a/dist/plot-schema.json +++ b/dist/plot-schema.json @@ -91,7 +91,9 @@ "requiredOpts": [ "dflt" ], - "otherOpts": [] + "otherOpts": [ + "regex" + ] }, "flaglist": { "description": "A string representing a combination of flags (order does not matter here). Combine any of the available `flags` with *+*. (e.g. ('lines+markers')). Values in `extras` cannot be combined.", @@ -162,13 +164,14 @@ "plot", "legend", "ticks", + "axrange", "margins", "layoutstyle", "modebar", "camera", "arraydraw" ], - "description": "layout attributes should include an `editType` string matching this flaglist. *calc* is the most extensive: a full `Plotly.plot` starting by clearing `gd.calcdata` to force it to be regenerated *calcIfAutorange* does a full `Plotly.plot`, but only clears and redoes `gd.calcdata` if there is at least one autoranged axis. *plot* calls `Plotly.plot` but without first clearing `gd.calcdata`. *legend* only redraws the legend. *ticks* only redraws axis ticks, labels, and gridlines. *margins* recomputes ticklabel automargins. *layoutstyle* reapplies global and SVG cartesian axis styles. *modebar* just updates the modebar. *camera* just updates the camera settings for gl3d scenes. *arraydraw* allows component arrays to invoke the redraw routines just for the component(s) that changed." + "description": "layout attributes should include an `editType` string matching this flaglist. *calc* is the most extensive: a full `Plotly.plot` starting by clearing `gd.calcdata` to force it to be regenerated *calcIfAutorange* does a full `Plotly.plot`, but only clears and redoes `gd.calcdata` if there is at least one autoranged axis. *plot* calls `Plotly.plot` but without first clearing `gd.calcdata`. *legend* only redraws the legend. *ticks* only redraws axis ticks, labels, and gridlines. *margins* recomputes ticklabel automargins. *axrange* minimal sequence when updating axis ranges. *layoutstyle* reapplies global and SVG cartesian axis styles. *modebar* just updates the modebar. *camera* just updates the camera settings for gl3d scenes. *arraydraw* allows component arrays to invoke the redraw routines just for the component(s) that changed." } }, "impliedEdits": { @@ -176,12 +179,12 @@ } }, "traces": { - "box": { + "scatter": { "meta": { - "description": "In vertical (horizontal) box plots, statistics are computed using `y` (`x`) values. By supplying an `x` (`y`) array, one box per distinct x (y) value is drawn If no `x` (`y`) {array} is provided, a single box is drawn. That box position is then positioned with with `name` or with `x0` (`y0`) if provided. Each box spans from quartile 1 (Q1) to quartile 3 (Q3). The second quartile (Q2) is marked by a line inside the box. By default, the whiskers correspond to the box' edges +/- 1.5 times the interquartile range (IQR = Q3-Q1), see *boxpoints* for other options." + "description": "The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts. The data visualized as scatter point or lines is set in `x` and `y`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays." }, "attributes": { - "type": "box", + "type": "scatter", "visible": { "valType": "enumerated", "values": [ @@ -220,8 +223,8 @@ "name": { "valType": "string", "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Sets the trace name. The trace name appear as the legend item and on hover. For box traces, the name will also be used for the position coordinate, if `x` and `x0` (`y` and `y0` if horizontal) are missing and the position axis is categorical" + "editType": "style", + "description": "Sets the trace name. The trace name appear as the legend item and on hover." }, "uid": { "valType": "string", @@ -377,29 +380,45 @@ "editType": "calc", "role": "object" }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y sample data or coordinates. See overview for more info.", - "role": "data" - }, "x": { "valType": "data_array", "editType": "calc+clearAxisTypes", - "description": "Sets the x sample data or coordinates. See overview for more info.", + "description": "Sets the x coordinates.", "role": "data" }, "x0": { "valType": "any", + "dflt": 0, "role": "info", "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinate of the box. See overview for more info." + "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step." + }, + "dx": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the x coordinate step. See `x0` for more info." + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinates.", + "role": "data" }, "y0": { "valType": "any", + "dflt": 0, "role": "info", "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinate of the box. See overview for more info." + "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step." + }, + "dy": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the y coordinate step. See `y0` for more info." }, "text": { "valType": "string", @@ -407,91 +426,141 @@ "dflt": "", "arrayOk": true, "editType": "calc", - "description": "Sets the text elements associated with each sample value. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." - }, - "whiskerwidth": { - "valType": "number", - "min": 0, - "max": 1, - "dflt": 0.5, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the width of the whiskers relative to the box' width. For example, with 1, the whiskers are as wide as the box(es)." - }, - "notched": { - "valType": "boolean", - "role": "style", - "editType": "calcIfAutorange", - "description": "Determines whether or not notches should be drawn." + "description": "Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." }, - "notchwidth": { - "valType": "number", - "min": 0, - "max": 0.5, - "dflt": 0.25, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the width of the notches relative to the box' width. For example, with 0, the notches are as wide as the box(es)." + "hovertext": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "style", + "description": "Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." }, - "boxpoints": { - "valType": "enumerated", - "values": [ - "all", - "outliers", - "suspectedoutliers", - false + "mode": { + "valType": "flaglist", + "flags": [ + "lines", + "markers", + "text" ], - "dflt": "outliers", - "role": "style", - "editType": "calcIfAutorange", - "description": "If *outliers*, only the sample points lying outside the whiskers are shown If *suspectedoutliers*, the outlier points are shown and points either less than 4*Q1-3*Q3 or greater than 4*Q3-3*Q1 are highlighted (see `outliercolor`) If *all*, all sample points are shown If *false*, only the box(es) are shown with no sample points" + "extras": [ + "none" + ], + "role": "info", + "editType": "calc", + "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*." }, - "boxmean": { - "valType": "enumerated", - "values": [ - true, - "sd", - false + "hoveron": { + "valType": "flaglist", + "flags": [ + "points", + "fills" ], - "dflt": false, - "role": "style", - "editType": "calcIfAutorange", - "description": "If *true*, the mean of the box(es)' underlying distribution is drawn as a dashed line inside the box(es). If *sd* the standard deviation is also drawn." + "role": "info", + "editType": "style", + "description": "Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is *toself* or *tonext* and there are no markers or text, then the default is *fills*, otherwise it is *points*." }, - "jitter": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the amount of jitter in the sample points drawn. If *0*, the sample points align along the distribution axis. If *1*, the sample points are drawn in a random jitter of width equal to the width of the box(es)." + "line": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the line color." + }, + "width": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "style", + "description": "Sets the line width (in px)." + }, + "shape": { + "valType": "enumerated", + "values": [ + "linear", + "spline", + "hv", + "vh", + "hvh", + "vhv" + ], + "dflt": "linear", + "role": "style", + "editType": "plot", + "description": "Determines the line shape. With *spline* the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes." + }, + "smoothing": { + "valType": "number", + "min": 0, + "max": 1.3, + "dflt": 1, + "role": "style", + "editType": "plot", + "description": "Has an effect only if `shape` is set to *spline* Sets the amount of smoothing. *0* corresponds to no smoothing (equivalent to a *linear* shape)." + }, + "dash": { + "valType": "string", + "values": [ + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" + ], + "dflt": "solid", + "role": "style", + "editType": "style", + "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." + }, + "simplify": { + "valType": "boolean", + "dflt": true, + "role": "info", + "editType": "plot", + "description": "Simplifies lines by removing nearly-collinear points. When transitioning lines, it may be desirable to disable this so that the number of points along the resulting SVG path is unaffected." + }, + "editType": "plot", + "role": "object" }, - "pointpos": { - "valType": "number", - "min": -2, - "max": 2, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the position of the sample points in relation to the box(es). If *0*, the sample points are places over the center of the box(es). Positive (negative) values correspond to positions to the right (left) for vertical boxes and above (below) for horizontal boxes" + "connectgaps": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." }, - "orientation": { + "cliponaxis": { + "valType": "boolean", + "dflt": true, + "role": "info", + "editType": "plot", + "description": "Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + }, + "fill": { "valType": "enumerated", "values": [ - "v", - "h" + "none", + "tozeroy", + "tozerox", + "tonexty", + "tonextx", + "toself", + "tonext" ], + "dflt": "none", "role": "style", - "editType": "calc+clearAxisTypes", - "description": "Sets the orientation of the box(es). If *v* (*h*), the distribution is visualized along the vertical (horizontal)." + "editType": "calc", + "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. *tozerox* and *tozeroy* fill to x=0 and y=0 respectively. *tonextx* and *tonexty* fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like *tozerox* and *tozeroy*. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. *tonext* fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like *toself* if there is no trace before it. *tonext* should not be used if one trace does not enclose the other." + }, + "fillcolor": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." }, "marker": { - "outliercolor": { - "valType": "color", - "dflt": "rgba(0, 0, 0, 0)", - "role": "style", - "editType": "style", - "description": "Sets the color of the outlier sample points." - }, "symbol": { "valType": "enumerated", "values": [ @@ -781,186 +850,1103 @@ "line-nw-open" ], "dflt": "circle", - "arrayOk": false, + "arrayOk": true, "role": "style", - "editType": "plot", + "editType": "style", "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." }, "opacity": { "valType": "number", "min": 0, "max": 1, - "arrayOk": false, + "arrayOk": true, "role": "style", "editType": "style", - "description": "Sets the marker opacity.", - "dflt": 1 + "description": "Sets the marker opacity." }, "size": { "valType": "number", "min": 0, "dflt": 6, - "arrayOk": false, + "arrayOk": true, "role": "style", "editType": "calcIfAutorange", "description": "Sets the marker size (in px)." }, - "color": { - "valType": "color", - "arrayOk": false, + "maxdisplayed": { + "valType": "number", + "min": 0, + "dflt": 0, "role": "style", - "editType": "style", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "editType": "plot", + "description": "Sets a maximum number of points to be drawn on the graph. *0* corresponds to no limit." }, - "line": { - "color": { - "valType": "color", - "arrayOk": false, + "sizeref": { + "valType": "number", + "dflt": 1, + "role": "style", + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." + }, + "sizemin": { + "valType": "number", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." + }, + "sizemode": { + "valType": "enumerated", + "values": [ + "diameter", + "area" + ], + "dflt": "diameter", + "role": "info", + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." + }, + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." + }, + "colorbar": { + "thicknessmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], "role": "style", - "editType": "style", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set.", - "dflt": "#444" + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "colorbars" }, - "width": { + "thickness": { "valType": "number", - "min": 0, - "arrayOk": false, "role": "style", - "editType": "style", - "description": "Sets the width (in px) of the lines bounding the marker points.", - "dflt": 0 + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "colorbars" }, - "outliercolor": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the border line color of the outlier sample points. Defaults to marker.color" + "lenmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "info", + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "colorbars" }, - "outlierwidth": { + "len": { "valType": "number", "min": 0, "dflt": 1, "role": "style", - "editType": "style", - "description": "Sets the border line width (in px) of the outlier sample points." + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "colorbars" }, - "editType": "style", - "role": "object" - }, - "editType": "plot", - "role": "object" - }, - "line": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the color of line bounding the box(es)." - }, - "width": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 2, - "editType": "style", - "description": "Sets the width (in px) of line bounding the box(es)." - }, - "editType": "plot", - "role": "object" - }, - "fillcolor": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." - }, - "selected": { - "marker": { - "opacity": { + "x": { + "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", + "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", + "editType": "colorbars" + }, + "xpad": { "valType": "number", + "role": "style", "min": 0, - "max": 1, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "colorbars" + }, + "y": { + "valType": "number", "role": "style", - "editType": "style", - "description": "Sets the marker opacity of selected points." + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "colorbars" }, - "color": { - "valType": "color", + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], "role": "style", - "editType": "style", - "description": "Sets the marker color of selected points." + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "colorbars" }, - "size": { + "ypad": { "valType": "number", + "role": "style", "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "colorbars" + }, + "outlinecolor": { + "valType": "color", + "dflt": "#444", "role": "style", - "editType": "style", - "description": "Sets the marker size of selected points." + "editType": "colorbars", + "description": "Sets the axis line color." }, - "editType": "style", - "role": "object" - }, - "editType": "style", - "role": "object" - }, - "unselected": { - "marker": { - "opacity": { + "outlinewidth": { "valType": "number", "min": 0, - "max": 1, + "dflt": 1, "role": "style", - "editType": "style", - "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + "editType": "colorbars", + "description": "Sets the width (in px) of the axis line." }, - "color": { + "bordercolor": { "valType": "color", + "dflt": "#444", "role": "style", - "editType": "style", - "description": "Sets the marker color of unselected points, applied only when a selection exists." + "editType": "colorbars", + "description": "Sets the axis line color." }, - "size": { + "borderwidth": { "valType": "number", + "role": "style", "min": 0, + "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "colorbars" + }, + "bgcolor": { + "valType": "color", "role": "style", - "editType": "style", - "description": "Sets the marker size of unselected points, applied only when a selection exists." + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" }, - "editType": "style", - "role": "object" - }, - "editType": "style", - "role": "object" - }, - "hoveron": { - "valType": "flaglist", - "flags": [ - "boxes", - "points" - ], - "dflt": "boxes+points", - "role": "info", - "editType": "style", - "description": "Do the hover effects highlight individual boxes or sample points or both?" - }, - "xcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], + "role": "info", + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + }, + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + }, + "tick0": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" + }, + "ticktext": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" + }, + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" + }, + "ticklen": { + "valType": "number", + "min": 0, + "dflt": 5, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick length (in px)." + }, + "tickwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick width (in px)." + }, + "tickcolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick color." + }, + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + }, + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label prefix." + }, + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + }, + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." + }, + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." + }, + "separatethousands": { + "valType": "boolean", + "dflt": false, + "role": "style", + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" + }, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + }, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + }, + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", + "editType": "colorbars" + }, + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" + }, + "editType": "colorbars", + "role": "object", + "tickvalssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for tickvals .", + "editType": "none" + }, + "ticktextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ticktext .", + "editType": "none" + } + }, + "line": { + "width": { + "valType": "number", + "min": 0, + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the width (in px) of the lines bounding the marker points." + }, + "editType": "calc", + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "role": "object", + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "gradient": { + "type": { + "valType": "enumerated", + "values": [ + "radial", + "horizontal", + "vertical", + "none" + ], + "arrayOk": true, + "dflt": "none", + "role": "style", + "editType": "calc", + "description": "Sets the type of gradient used to fill the markers" + }, + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical." + }, + "editType": "calc", + "role": "object", + "typesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for type .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "editType": "calc", + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "role": "object", + "symbolsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for symbol .", + "editType": "none" + }, + "opacitysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for opacity .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "selected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of selected points." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of selected points." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "style", + "description": "Sets the marker size of selected points." + }, + "editType": "style", + "role": "object" + }, + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the text font color of selected points." + }, + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" + }, + "unselected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of unselected points, applied only when a selection exists." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "style", + "description": "Sets the marker size of unselected points, applied only when a selection exists." + }, + "editType": "style", + "role": "object" + }, + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the text font color of unselected points, applied only when a selection exists." + }, + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" + }, + "textposition": { + "valType": "enumerated", + "values": [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right" + ], + "dflt": "middle center", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." + }, + "textfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "calc", + "arrayOk": true + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "arrayOk": true + }, + "editType": "calc", + "description": "Sets the text font.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "r": { + "valType": "data_array", + "editType": "calc", + "description": "For legacy polar chart only.Please switch to *scatterpolar* trace type.Sets the radial coordinates.", + "role": "data" + }, + "t": { + "valType": "data_array", + "editType": "calc", + "description": "For legacy polar chart only.Please switch to *scatterpolar* trace type.Sets the angular coordinates.", + "role": "data" + }, + "error_x": { + "visible": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." + }, + "type": { + "valType": "enumerated", + "values": [ + "percent", + "constant", + "sqrt", + "data" + ], + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." + }, + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + }, + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" + }, + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" + }, + "value": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + }, + "valueminus": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + }, + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "style" + }, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "style" + }, + "copy_ystyle": { + "valType": "boolean", + "role": "style", + "editType": "plot" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the stoke color of the error bars." + }, + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "style", + "description": "Sets the thickness (in px) of the error bars." + }, + "width": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + }, + "editType": "calc", + "_deprecated": { + "opacity": { + "valType": "number", + "role": "style", + "editType": "style", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } + }, + "role": "object", + "arraysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" + }, + "arrayminussrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } + }, + "error_y": { + "visible": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." + }, + "type": { + "valType": "enumerated", + "values": [ + "percent", + "constant", + "sqrt", + "data" + ], + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." + }, + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + }, + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" + }, + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" + }, + "value": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + }, + "valueminus": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + }, + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "style" + }, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "style" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the stoke color of the error bars." + }, + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "style", + "description": "Sets the thickness (in px) of the error bars." + }, + "width": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + }, + "editType": "calc", + "_deprecated": { + "opacity": { + "valType": "number", + "role": "style", + "editType": "style", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } + }, + "role": "object", + "arraysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" + }, + "arrayminussrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } + }, + "xcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", "ummalqura" ], "role": "info", @@ -1005,7 +1991,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -1016,72 +2002,65 @@ "customdatasrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for customdata .", + "description": "Sets the source reference on plot.ly for customdata .", + "editType": "none" + }, + "hoverinfosrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hoverinfo .", + "editType": "none" + }, + "xsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for x .", + "editType": "none" + }, + "ysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for y .", + "editType": "none" + }, + "textsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for text .", "editType": "none" }, - "hoverinfosrc": { + "hovertextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for hoverinfo .", + "description": "Sets the source reference on plot.ly for hovertext .", "editType": "none" }, - "ysrc": { + "textpositionsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for y .", + "description": "Sets the source reference on plot.ly for textposition .", "editType": "none" }, - "xsrc": { + "rsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for x .", + "description": "Sets the source reference on plot.ly for r .", "editType": "none" }, - "textsrc": { + "tsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for text .", + "description": "Sets the source reference on plot.ly for t .", "editType": "none" } - }, - "layoutAttributes": { - "boxmode": { - "valType": "enumerated", - "values": [ - "group", - "overlay" - ], - "dflt": "overlay", - "role": "info", - "editType": "calc", - "description": "Determines how boxes at the same location coordinate are displayed on the graph. If *group*, the boxes are plotted next to one another centered around the shared location. If *overlay*, the boxes are plotted over one another, you might need to set *opacity* to see them multiple boxes." - }, - "boxgap": { - "valType": "number", - "min": 0, - "max": 1, - "dflt": 0.3, - "role": "style", - "editType": "calc", - "description": "Sets the gap (in plot fraction) between boxes of adjacent location coordinates." - }, - "boxgroupgap": { - "valType": "number", - "min": 0, - "max": 1, - "dflt": 0.3, - "role": "style", - "editType": "calc", - "description": "Sets the gap (in plot fraction) between boxes of the same location coordinate." - } } }, - "scatter": { + "bar": { "meta": { - "description": "The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts. The data visualized as scatter point or lines is set in `x` and `y`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays." + "description": "The data visualized by the span of the bars is set in `y` if `orientation` is set th *v* (the default) and the labels are set in `x`. By setting `orientation` to *h*, the roles are interchanged." }, "attributes": { - "type": "scatter", + "type": "bar", "visible": { "valType": "enumerated", "values": [ @@ -1291,518 +2270,396 @@ "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step." }, "dx": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the x coordinate step. See `x0` for more info." - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinates.", - "role": "data" - }, - "y0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step." - }, - "dy": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the y coordinate step. See `y0` for more info." - }, - "text": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "calc", - "description": "Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." - }, - "hovertext": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "style", - "description": "Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." - }, - "mode": { - "valType": "flaglist", - "flags": [ - "lines", - "markers", - "text" - ], - "extras": [ - "none" - ], - "role": "info", - "editType": "calc", - "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*." - }, - "hoveron": { - "valType": "flaglist", - "flags": [ - "points", - "fills" - ], - "role": "info", - "editType": "style", - "description": "Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is *toself* or *tonext* and there are no markers or text, then the default is *fills*, otherwise it is *points*." - }, - "line": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the line color." - }, - "width": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "style", - "description": "Sets the line width (in px)." - }, - "shape": { - "valType": "enumerated", - "values": [ - "linear", - "spline", - "hv", - "vh", - "hvh", - "vhv" - ], - "dflt": "linear", - "role": "style", - "editType": "plot", - "description": "Determines the line shape. With *spline* the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes." - }, - "smoothing": { - "valType": "number", - "min": 0, - "max": 1.3, - "dflt": 1, - "role": "style", - "editType": "plot", - "description": "Has an effect only if `shape` is set to *spline* Sets the amount of smoothing. *0* corresponds to no smoothing (equivalent to a *linear* shape)." - }, - "dash": { - "valType": "string", - "values": [ - "solid", - "dot", - "dash", - "longdash", - "dashdot", - "longdashdot" - ], - "dflt": "solid", - "role": "style", - "editType": "style", - "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." - }, - "simplify": { - "valType": "boolean", - "dflt": true, - "role": "info", - "editType": "plot", - "description": "Simplifies lines by removing nearly-collinear points. When transitioning lines, it may be desirable to disable this so that the number of points along the resulting SVG path is unaffected." - }, - "editType": "plot", - "role": "object" - }, - "connectgaps": { - "valType": "boolean", - "dflt": false, - "role": "info", - "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." - }, - "cliponaxis": { - "valType": "boolean", - "dflt": true, - "role": "info", - "editType": "plot", - "description": "Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." - }, - "fill": { - "valType": "enumerated", - "values": [ - "none", - "tozeroy", - "tozerox", - "tonexty", - "tonextx", - "toself", - "tonext" - ], - "dflt": "none", - "role": "style", - "editType": "calc", - "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. *tozerox* and *tozeroy* fill to x=0 and y=0 respectively. *tonextx* and *tonexty* fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like *tozerox* and *tozeroy*. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. *tonext* fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like *toself* if there is no trace before it. *tonext* should not be used if one trace does not enclose the other." - }, - "fillcolor": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." - }, - "marker": { - "symbol": { - "valType": "enumerated", - "values": [ - 0, - "circle", - 100, - "circle-open", - 200, - "circle-dot", - 300, - "circle-open-dot", - 1, - "square", - 101, - "square-open", - 201, - "square-dot", - 301, - "square-open-dot", - 2, - "diamond", - 102, - "diamond-open", - 202, - "diamond-dot", - 302, - "diamond-open-dot", - 3, - "cross", - 103, - "cross-open", - 203, - "cross-dot", - 303, - "cross-open-dot", - 4, - "x", - 104, - "x-open", - 204, - "x-dot", - 304, - "x-open-dot", - 5, - "triangle-up", - 105, - "triangle-up-open", - 205, - "triangle-up-dot", - 305, - "triangle-up-open-dot", - 6, - "triangle-down", - 106, - "triangle-down-open", - 206, - "triangle-down-dot", - 306, - "triangle-down-open-dot", - 7, - "triangle-left", - 107, - "triangle-left-open", - 207, - "triangle-left-dot", - 307, - "triangle-left-open-dot", - 8, - "triangle-right", - 108, - "triangle-right-open", - 208, - "triangle-right-dot", - 308, - "triangle-right-open-dot", - 9, - "triangle-ne", - 109, - "triangle-ne-open", - 209, - "triangle-ne-dot", - 309, - "triangle-ne-open-dot", - 10, - "triangle-se", - 110, - "triangle-se-open", - 210, - "triangle-se-dot", - 310, - "triangle-se-open-dot", - 11, - "triangle-sw", - 111, - "triangle-sw-open", - 211, - "triangle-sw-dot", - 311, - "triangle-sw-open-dot", - 12, - "triangle-nw", - 112, - "triangle-nw-open", - 212, - "triangle-nw-dot", - 312, - "triangle-nw-open-dot", - 13, - "pentagon", - 113, - "pentagon-open", - 213, - "pentagon-dot", - 313, - "pentagon-open-dot", - 14, - "hexagon", - 114, - "hexagon-open", - 214, - "hexagon-dot", - 314, - "hexagon-open-dot", - 15, - "hexagon2", - 115, - "hexagon2-open", - 215, - "hexagon2-dot", - 315, - "hexagon2-open-dot", - 16, - "octagon", - 116, - "octagon-open", - 216, - "octagon-dot", - 316, - "octagon-open-dot", - 17, - "star", - 117, - "star-open", - 217, - "star-dot", - 317, - "star-open-dot", - 18, - "hexagram", - 118, - "hexagram-open", - 218, - "hexagram-dot", - 318, - "hexagram-open-dot", - 19, - "star-triangle-up", - 119, - "star-triangle-up-open", - 219, - "star-triangle-up-dot", - 319, - "star-triangle-up-open-dot", - 20, - "star-triangle-down", - 120, - "star-triangle-down-open", - 220, - "star-triangle-down-dot", - 320, - "star-triangle-down-open-dot", - 21, - "star-square", - 121, - "star-square-open", - 221, - "star-square-dot", - 321, - "star-square-open-dot", - 22, - "star-diamond", - 122, - "star-diamond-open", - 222, - "star-diamond-dot", - 322, - "star-diamond-open-dot", - 23, - "diamond-tall", - 123, - "diamond-tall-open", - 223, - "diamond-tall-dot", - 323, - "diamond-tall-open-dot", - 24, - "diamond-wide", - 124, - "diamond-wide-open", - 224, - "diamond-wide-dot", - 324, - "diamond-wide-open-dot", - 25, - "hourglass", - 125, - "hourglass-open", - 26, - "bowtie", - 126, - "bowtie-open", - 27, - "circle-cross", - 127, - "circle-cross-open", - 28, - "circle-x", - 128, - "circle-x-open", - 29, - "square-cross", - 129, - "square-cross-open", - 30, - "square-x", - 130, - "square-x-open", - 31, - "diamond-cross", - 131, - "diamond-cross-open", - 32, - "diamond-x", - 132, - "diamond-x-open", - 33, - "cross-thin", - 133, - "cross-thin-open", - 34, - "x-thin", - 134, - "x-thin-open", - 35, - "asterisk", - 135, - "asterisk-open", - 36, - "hash", - 136, - "hash-open", - 236, - "hash-dot", - 336, - "hash-open-dot", - 37, - "y-up", - 137, - "y-up-open", - 38, - "y-down", - 138, - "y-down-open", - 39, - "y-left", - 139, - "y-left-open", - 40, - "y-right", - 140, - "y-right-open", - 41, - "line-ew", - 141, - "line-ew-open", - 42, - "line-ns", - 142, - "line-ns-open", - 43, - "line-ne", - 143, - "line-ne-open", - 44, - "line-nw", - 144, - "line-nw-open" - ], - "dflt": "circle", - "arrayOk": true, + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the x coordinate step. See `x0` for more info." + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinates.", + "role": "data" + }, + "y0": { + "valType": "any", + "dflt": 0, + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step." + }, + "dy": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the y coordinate step. See `y0` for more info." + }, + "text": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "calc", + "description": "Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + }, + "hovertext": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "style", + "description": "Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." + }, + "textposition": { + "valType": "enumerated", + "role": "info", + "values": [ + "inside", + "outside", + "auto", + "none" + ], + "dflt": "none", + "arrayOk": true, + "editType": "calc", + "description": "Specifies the location of the `text`. *inside* positions `text` inside, next to the bar end (rotated and scaled if needed). *outside* positions `text` outside, next to the bar end (scaled if needed). *auto* positions `text` inside or outside so that `text` size is maximized." + }, + "textfont": { + "family": { + "valType": "string", "role": "style", - "editType": "style", - "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, - "opacity": { + "size": { "valType": "number", - "min": 0, - "max": 1, - "arrayOk": true, "role": "style", - "editType": "style", - "description": "Sets the marker opacity." + "min": 1, + "editType": "calc", + "arrayOk": true + }, + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "arrayOk": true + }, + "editType": "calc", + "description": "Sets the font used for `text`.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "insidetextfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, "size": { "valType": "number", - "min": 0, - "dflt": 6, - "arrayOk": true, "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the marker size (in px)." + "min": 1, + "editType": "calc", + "arrayOk": true }, - "maxdisplayed": { - "valType": "number", - "min": 0, - "dflt": 0, + "color": { + "valType": "color", "role": "style", - "editType": "plot", - "description": "Sets a maximum number of points to be drawn on the graph. *0* corresponds to no limit." + "editType": "calc", + "arrayOk": true }, - "sizeref": { - "valType": "number", - "dflt": 1, + "editType": "calc", + "description": "Sets the font used for `text` lying inside the bar.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "outsidetextfont": { + "family": { + "valType": "string", "role": "style", + "noBlank": true, + "strict": true, "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, - "sizemin": { + "size": { "valType": "number", - "min": 0, - "dflt": 0, "role": "style", + "min": 1, "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." + "arrayOk": true }, - "sizemode": { - "valType": "enumerated", - "values": [ - "diameter", - "area" - ], - "dflt": "diameter", + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "arrayOk": true + }, + "editType": "calc", + "description": "Sets the font used for `text` lying outside the bar.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "constraintext": { + "valType": "enumerated", + "values": [ + "inside", + "outside", + "both", + "none" + ], + "role": "info", + "dflt": "both", + "editType": "calc", + "description": "Constrain the size of text inside or outside a bar to be no larger than the bar itself." + }, + "cliponaxis": { + "valType": "boolean", + "dflt": true, + "role": "info", + "editType": "plot", + "description": "Determines whether the text nodes are clipped about the subplot axes. To show the text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + }, + "orientation": { + "valType": "enumerated", + "role": "info", + "values": [ + "v", + "h" + ], + "editType": "calc+clearAxisTypes", + "description": "Sets the orientation of the bars. With *v* (*h*), the value of the each bar spans along the vertical (horizontal)." + }, + "base": { + "valType": "any", + "dflt": null, + "arrayOk": true, + "role": "info", + "editType": "calc", + "description": "Sets where the bar base is drawn (in position axis units). In *stack* or *relative* barmode, traces that set *base* will be excluded and drawn in *overlay* mode instead." + }, + "offset": { + "valType": "number", + "dflt": null, + "arrayOk": true, + "role": "info", + "editType": "calc", + "description": "Shifts the position where the bar is drawn (in position axis units). In *group* barmode, traces that set *offset* will be excluded and drawn in *overlay* mode instead." + }, + "width": { + "valType": "number", + "dflt": null, + "min": 0, + "arrayOk": true, + "role": "info", + "editType": "calc", + "description": "Sets the bar width (in position axis units)." + }, + "marker": { + "line": { + "width": { + "valType": "number", + "min": 0, + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the width (in px) of the lines bounding the marker points.", + "dflt": 0 + }, + "editType": "calc", + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "role": "object", + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "editType": "calc", + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", "role": "info", + "dflt": true, "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." }, "showscale": { "valType": "boolean", @@ -2207,223 +3064,53 @@ "valType": "color", "role": "style", "editType": "colorbars" - }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" - }, - "editType": "colorbars", - "role": "object", - "tickvalssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", - "editType": "none" - }, - "ticktextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", - "editType": "none" - } - }, - "line": { - "width": { - "valType": "number", - "min": 0, - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the width (in px) of the lines bounding the marker points." - }, - "editType": "calc", - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "role": "object", - "widthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for width .", - "editType": "none" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "gradient": { - "type": { + "titleside": { "valType": "enumerated", "values": [ - "radial", - "horizontal", - "vertical", - "none" + "right", + "top", + "bottom" ], - "arrayOk": true, - "dflt": "none", - "role": "style", - "editType": "calc", - "description": "Sets the type of gradient used to fill the markers" - }, - "color": { - "valType": "color", - "arrayOk": true, "role": "style", - "editType": "calc", - "description": "Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical." + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" }, - "editType": "calc", + "editType": "colorbars", "role": "object", - "typesrc": { + "tickvalssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for type .", + "description": "Sets the source reference on plot.ly for tickvals .", "editType": "none" }, - "colorsrc": { + "ticktextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for ticktext .", "editType": "none" } }, - "editType": "calc", - "color": { - "valType": "color", + "opacity": { + "valType": "number", "arrayOk": true, + "dflt": 1, + "min": 0, + "max": 1, "role": "style", "editType": "style", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + "description": "Sets the opacity of the bars." }, "role": "object", - "symbolsrc": { + "colorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for symbol .", + "description": "Sets the source reference on plot.ly for color .", "editType": "none" }, "opacitysrc": { @@ -2431,18 +3118,6 @@ "role": "info", "description": "Sets the source reference on plot.ly for opacity .", "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" } }, "selected": { @@ -2461,13 +3136,6 @@ "editType": "style", "description": "Sets the marker color of selected points." }, - "size": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "style", - "description": "Sets the marker size of selected points." - }, "editType": "style", "role": "object" }, @@ -2500,13 +3168,6 @@ "editType": "style", "description": "Sets the marker color of unselected points, applied only when a selection exists." }, - "size": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "style", - "description": "Sets the marker size of unselected points, applied only when a selection exists." - }, "editType": "style", "role": "object" }, @@ -2523,70 +3184,6 @@ "editType": "style", "role": "object" }, - "textposition": { - "valType": "enumerated", - "values": [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right" - ], - "dflt": "middle center", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." - }, - "textfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "arrayOk": true - }, - "editType": "calc", - "description": "Sets the text font.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, "r": { "valType": "data_array", "editType": "calc", @@ -2599,6 +3196,18 @@ "description": "For legacy polar chart only.Please switch to *scatterpolar* trace type.Sets the angular coordinates.", "role": "data" }, + "_deprecated": { + "bardir": { + "valType": "enumerated", + "role": "info", + "editType": "calc", + "values": [ + "v", + "h" + ], + "description": "Renamed to `orientation`." + } + }, "error_x": { "visible": { "valType": "boolean", @@ -2888,7 +3497,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -2938,6 +3547,24 @@ "description": "Sets the source reference on plot.ly for textposition .", "editType": "none" }, + "basesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for base .", + "editType": "none" + }, + "offsetsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for offset .", + "editType": "none" + }, + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + }, "rsrc": { "valType": "string", "role": "info", @@ -2950,14 +3577,58 @@ "description": "Sets the source reference on plot.ly for t .", "editType": "none" } + }, + "layoutAttributes": { + "barmode": { + "valType": "enumerated", + "values": [ + "stack", + "group", + "overlay", + "relative" + ], + "dflt": "group", + "role": "info", + "editType": "calc", + "description": "Determines how bars at the same location coordinate are displayed on the graph. With *stack*, the bars are stacked on top of one another With *relative*, the bars are stacked on top of one another, with negative values below the axis, positive values above With *group*, the bars are plotted next to one another centered around the shared location. With *overlay*, the bars are plotted over one another, you might need to an *opacity* to see multiple bars." + }, + "barnorm": { + "valType": "enumerated", + "values": [ + "", + "fraction", + "percent" + ], + "dflt": "", + "role": "info", + "editType": "calc", + "description": "Sets the normalization for bar traces on the graph. With *fraction*, the value of each bar is divide by the sum of the values at the location coordinate. With *percent*, the results form *fraction* are presented in percents." + }, + "bargap": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between bars of adjacent location coordinates." + }, + "bargroupgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between bars of the same location coordinate." + } } }, - "bar": { + "box": { "meta": { - "description": "The data visualized by the span of the bars is set in `y` if `orientation` is set th *v* (the default) and the labels are set in `x`. By setting `orientation` to *h*, the roles are interchanged." + "description": "In vertical (horizontal) box plots, statistics are computed using `y` (`x`) values. By supplying an `x` (`y`) array, one box per distinct x (y) value is drawn If no `x` (`y`) {array} is provided, a single box is drawn. That box position is then positioned with with `name` or with `x0` (`y0`) if provided. Each box spans from quartile 1 (Q1) to quartile 3 (Q3). The second quartile (Q2) is marked by a line inside the box. By default, the whiskers correspond to the box' edges +/- 1.5 times the interquartile range (IQR = Q3-Q1), see *boxpoints* for other options." }, "attributes": { - "type": "bar", + "type": "box", "visible": { "valType": "enumerated", "values": [ @@ -2996,8 +3667,8 @@ "name": { "valType": "string", "role": "info", - "editType": "style", - "description": "Sets the trace name. The trace name appear as the legend item and on hover." + "editType": "calc+clearAxisTypes", + "description": "Sets the trace name. The trace name appear as the legend item and on hover. For box traces, the name will also be used for the position coordinate, if `x` and `x0` (`y` and `y0` if horizontal) are missing and the position axis is categorical" }, "uid": { "valType": "string", @@ -3108,1227 +3779,1574 @@ "min": -1, "arrayOk": true, "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." - }, - "editType": "calc", - "role": "object", - "bgcolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", - "editType": "none" - }, - "bordercolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", - "editType": "none" - }, - "namelengthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", - "editType": "none" - } - }, - "stream": { - "token": { - "valType": "string", - "noBlank": true, - "strict": true, - "role": "info", - "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." - }, - "maxpoints": { - "valType": "number", - "min": 0, - "max": 10000, - "dflt": 500, - "role": "info", - "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." - }, - "editType": "calc", - "role": "object" - }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinates.", - "role": "data" - }, - "x0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step." - }, - "dx": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the x coordinate step. See `x0` for more info." - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinates.", - "role": "data" - }, - "y0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step." - }, - "dy": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the y coordinate step. See `y0` for more info." - }, - "text": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "calc", - "description": "Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." - }, - "hovertext": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "style", - "description": "Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." - }, - "textposition": { - "valType": "enumerated", - "role": "info", - "values": [ - "inside", - "outside", - "auto", - "none" - ], - "dflt": "none", - "arrayOk": true, - "editType": "calc", - "description": "Specifies the location of the `text`. *inside* positions `text` inside, next to the bar end (rotated and scaled if needed). *outside* positions `text` outside, next to the bar end (scaled if needed). *auto* positions `text` inside or outside so that `text` size is maximized." - }, - "textfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "arrayOk": true - }, - "editType": "calc", - "description": "Sets the font used for `text`.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "insidetextfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "arrayOk": true - }, - "editType": "calc", - "description": "Sets the font used for `text` lying inside the bar.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "outsidetextfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "arrayOk": true + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." }, "editType": "calc", - "description": "Sets the font used for `text` lying outside the bar.", "role": "object", - "familysrc": { + "bgcolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for family .", + "description": "Sets the source reference on plot.ly for bgcolor .", "editType": "none" }, - "sizesrc": { + "bordercolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for size .", + "description": "Sets the source reference on plot.ly for bordercolor .", "editType": "none" }, - "colorsrc": { + "namelengthsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for namelength .", "editType": "none" } }, - "constraintext": { - "valType": "enumerated", - "values": [ - "inside", - "outside", - "both", - "none" - ], - "role": "info", - "dflt": "both", + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { + "valType": "number", + "min": 0, + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, "editType": "calc", - "description": "Constrain the size of text inside or outside a bar to be no larger than the bar itself." + "role": "object" }, - "cliponaxis": { - "valType": "boolean", - "dflt": true, - "role": "info", - "editType": "plot", - "description": "Determines whether the text nodes are clipped about the subplot axes. To show the text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the y sample data or coordinates. See overview for more info.", + "role": "data" }, - "orientation": { - "valType": "enumerated", + "x": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the x sample data or coordinates. See overview for more info.", + "role": "data" + }, + "x0": { + "valType": "any", "role": "info", - "values": [ - "v", - "h" - ], "editType": "calc+clearAxisTypes", - "description": "Sets the orientation of the bars. With *v* (*h*), the value of the each bar spans along the vertical (horizontal)." + "description": "Sets the x coordinate of the box. See overview for more info." }, - "base": { + "y0": { "valType": "any", - "dflt": null, - "arrayOk": true, "role": "info", - "editType": "calc", - "description": "Sets where the bar base is drawn (in position axis units). In *stack* or *relative* barmode, traces that set *base* will be excluded and drawn in *overlay* mode instead." + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinate of the box. See overview for more info." }, - "offset": { - "valType": "number", - "dflt": null, - "arrayOk": true, + "text": { + "valType": "string", "role": "info", + "dflt": "", + "arrayOk": true, "editType": "calc", - "description": "Shifts the position where the bar is drawn (in position axis units). In *group* barmode, traces that set *offset* will be excluded and drawn in *overlay* mode instead." + "description": "Sets the text elements associated with each sample value. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." }, - "width": { + "whiskerwidth": { "valType": "number", - "dflt": null, "min": 0, - "arrayOk": true, - "role": "info", - "editType": "calc", - "description": "Sets the bar width (in position axis units)." + "max": 1, + "dflt": 0.5, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the width of the whiskers relative to the box' width. For example, with 1, the whiskers are as wide as the box(es)." + }, + "notched": { + "valType": "boolean", + "role": "style", + "editType": "calcIfAutorange", + "description": "Determines whether or not notches should be drawn." + }, + "notchwidth": { + "valType": "number", + "min": 0, + "max": 0.5, + "dflt": 0.25, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the width of the notches relative to the box' width. For example, with 0, the notches are as wide as the box(es)." + }, + "boxpoints": { + "valType": "enumerated", + "values": [ + "all", + "outliers", + "suspectedoutliers", + false + ], + "dflt": "outliers", + "role": "style", + "editType": "calcIfAutorange", + "description": "If *outliers*, only the sample points lying outside the whiskers are shown If *suspectedoutliers*, the outlier points are shown and points either less than 4*Q1-3*Q3 or greater than 4*Q3-3*Q1 are highlighted (see `outliercolor`) If *all*, all sample points are shown If *false*, only the box(es) are shown with no sample points" + }, + "boxmean": { + "valType": "enumerated", + "values": [ + true, + "sd", + false + ], + "dflt": false, + "role": "style", + "editType": "calcIfAutorange", + "description": "If *true*, the mean of the box(es)' underlying distribution is drawn as a dashed line inside the box(es). If *sd* the standard deviation is also drawn." + }, + "jitter": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the amount of jitter in the sample points drawn. If *0*, the sample points align along the distribution axis. If *1*, the sample points are drawn in a random jitter of width equal to the width of the box(es)." + }, + "pointpos": { + "valType": "number", + "min": -2, + "max": 2, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the position of the sample points in relation to the box(es). If *0*, the sample points are places over the center of the box(es). Positive (negative) values correspond to positions to the right (left) for vertical boxes and above (below) for horizontal boxes" + }, + "orientation": { + "valType": "enumerated", + "values": [ + "v", + "h" + ], + "role": "style", + "editType": "calc+clearAxisTypes", + "description": "Sets the orientation of the box(es). If *v* (*h*), the distribution is visualized along the vertical (horizontal)." }, "marker": { - "line": { - "width": { - "valType": "number", - "min": 0, - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the width (in px) of the lines bounding the marker points.", - "dflt": 0 - }, - "editType": "calc", - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "role": "object", - "widthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for width .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "editType": "calc", - "color": { + "outliercolor": { "valType": "color", - "arrayOk": true, + "dflt": "rgba(0, 0, 0, 0)", "role": "style", "editType": "style", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "description": "Sets the color of the outlier sample points." }, - "colorscale": { - "valType": "colorscale", + "symbol": { + "valType": "enumerated", + "values": [ + 0, + "circle", + 100, + "circle-open", + 200, + "circle-dot", + 300, + "circle-open-dot", + 1, + "square", + 101, + "square-open", + 201, + "square-dot", + 301, + "square-open-dot", + 2, + "diamond", + 102, + "diamond-open", + 202, + "diamond-dot", + 302, + "diamond-open-dot", + 3, + "cross", + 103, + "cross-open", + 203, + "cross-dot", + 303, + "cross-open-dot", + 4, + "x", + 104, + "x-open", + 204, + "x-dot", + 304, + "x-open-dot", + 5, + "triangle-up", + 105, + "triangle-up-open", + 205, + "triangle-up-dot", + 305, + "triangle-up-open-dot", + 6, + "triangle-down", + 106, + "triangle-down-open", + 206, + "triangle-down-dot", + 306, + "triangle-down-open-dot", + 7, + "triangle-left", + 107, + "triangle-left-open", + 207, + "triangle-left-dot", + 307, + "triangle-left-open-dot", + 8, + "triangle-right", + 108, + "triangle-right-open", + 208, + "triangle-right-dot", + 308, + "triangle-right-open-dot", + 9, + "triangle-ne", + 109, + "triangle-ne-open", + 209, + "triangle-ne-dot", + 309, + "triangle-ne-open-dot", + 10, + "triangle-se", + 110, + "triangle-se-open", + 210, + "triangle-se-dot", + 310, + "triangle-se-open-dot", + 11, + "triangle-sw", + 111, + "triangle-sw-open", + 211, + "triangle-sw-dot", + 311, + "triangle-sw-open-dot", + 12, + "triangle-nw", + 112, + "triangle-nw-open", + 212, + "triangle-nw-dot", + 312, + "triangle-nw-open-dot", + 13, + "pentagon", + 113, + "pentagon-open", + 213, + "pentagon-dot", + 313, + "pentagon-open-dot", + 14, + "hexagon", + 114, + "hexagon-open", + 214, + "hexagon-dot", + 314, + "hexagon-open-dot", + 15, + "hexagon2", + 115, + "hexagon2-open", + 215, + "hexagon2-dot", + 315, + "hexagon2-open-dot", + 16, + "octagon", + 116, + "octagon-open", + 216, + "octagon-dot", + 316, + "octagon-open-dot", + 17, + "star", + 117, + "star-open", + 217, + "star-dot", + 317, + "star-open-dot", + 18, + "hexagram", + 118, + "hexagram-open", + 218, + "hexagram-dot", + 318, + "hexagram-open-dot", + 19, + "star-triangle-up", + 119, + "star-triangle-up-open", + 219, + "star-triangle-up-dot", + 319, + "star-triangle-up-open-dot", + 20, + "star-triangle-down", + 120, + "star-triangle-down-open", + 220, + "star-triangle-down-dot", + 320, + "star-triangle-down-open-dot", + 21, + "star-square", + 121, + "star-square-open", + 221, + "star-square-dot", + 321, + "star-square-open-dot", + 22, + "star-diamond", + 122, + "star-diamond-open", + 222, + "star-diamond-dot", + 322, + "star-diamond-open-dot", + 23, + "diamond-tall", + 123, + "diamond-tall-open", + 223, + "diamond-tall-dot", + 323, + "diamond-tall-open-dot", + 24, + "diamond-wide", + 124, + "diamond-wide-open", + 224, + "diamond-wide-dot", + 324, + "diamond-wide-open-dot", + 25, + "hourglass", + 125, + "hourglass-open", + 26, + "bowtie", + 126, + "bowtie-open", + 27, + "circle-cross", + 127, + "circle-cross-open", + 28, + "circle-x", + 128, + "circle-x-open", + 29, + "square-cross", + 129, + "square-cross-open", + 30, + "square-x", + 130, + "square-x-open", + 31, + "diamond-cross", + 131, + "diamond-cross-open", + 32, + "diamond-x", + 132, + "diamond-x-open", + 33, + "cross-thin", + 133, + "cross-thin-open", + 34, + "x-thin", + 134, + "x-thin-open", + 35, + "asterisk", + 135, + "asterisk-open", + 36, + "hash", + 136, + "hash-open", + 236, + "hash-dot", + 336, + "hash-open-dot", + 37, + "y-up", + 137, + "y-up-open", + 38, + "y-down", + 138, + "y-down-open", + 39, + "y-left", + 139, + "y-left-open", + 40, + "y-right", + 140, + "y-right-open", + 41, + "line-ew", + 141, + "line-ew-open", + 42, + "line-ns", + 142, + "line-ns-open", + 43, + "line-ne", + 143, + "line-ne-open", + 44, + "line-nw", + 144, + "line-nw-open" + ], + "dflt": "circle", + "arrayOk": false, "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." }, - "cmin": { + "opacity": { "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", + "min": 0, + "max": 1, + "arrayOk": false, "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "editType": "style", + "description": "Sets the marker opacity.", + "dflt": 1 }, - "reversescale": { - "valType": "boolean", + "size": { + "valType": "number", + "min": 0, + "dflt": 6, + "arrayOk": false, "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + "editType": "calcIfAutorange", + "description": "Sets the marker size (in px)." }, - "showscale": { - "valType": "boolean", - "role": "info", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." + "color": { + "valType": "color", + "arrayOk": false, + "role": "style", + "editType": "style", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], + "line": { + "color": { + "valType": "color", + "arrayOk": false, "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set.", + "dflt": "#444" }, - "thickness": { + "width": { "valType": "number", - "role": "style", "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "colorbars" + "arrayOk": false, + "role": "style", + "editType": "style", + "description": "Sets the width (in px) of the lines bounding the marker points.", + "dflt": 0 }, - "lenmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "colorbars" + "outliercolor": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the border line color of the outlier sample points. Defaults to marker.color" }, - "len": { + "outlierwidth": { "valType": "number", "min": 0, "dflt": 1, "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "colorbars" - }, - "x": { - "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, - "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "colorbars" - }, - "xanchor": { - "valType": "enumerated", - "values": [ - "left", - "center", - "right" - ], - "dflt": "left", - "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "colorbars" + "editType": "style", + "description": "Sets the border line width (in px) of the outlier sample points." }, - "xpad": { + "editType": "style", + "role": "object" + }, + "editType": "plot", + "role": "object" + }, + "line": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the color of line bounding the box(es)." + }, + "width": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 2, + "editType": "style", + "description": "Sets the width (in px) of line bounding the box(es)." + }, + "editType": "plot", + "role": "object" + }, + "fillcolor": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + }, + "selected": { + "marker": { + "opacity": { "valType": "number", - "role": "style", "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "colorbars" - }, - "y": { - "valType": "number", + "max": 1, "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker opacity of selected points." }, - "yanchor": { - "valType": "enumerated", - "values": [ - "top", - "middle", - "bottom" - ], + "color": { + "valType": "color", "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker color of selected points." }, - "ypad": { + "size": { "valType": "number", - "role": "style", "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "colorbars" - }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "editType": "style", + "description": "Sets the marker size of selected points." }, - "outlinewidth": { + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" + }, + "unselected": { + "marker": { + "opacity": { "valType": "number", "min": 0, - "dflt": 1, + "max": 1, "role": "style", - "editType": "colorbars", - "description": "Sets the width (in px) of the axis line." + "editType": "style", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." }, - "bordercolor": { + "color": { "valType": "color", - "dflt": "#444", "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "editType": "style", + "description": "Sets the marker color of unselected points, applied only when a selection exists." }, - "borderwidth": { + "size": { "valType": "number", - "role": "style", - "min": 0, - "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "colorbars" - }, - "bgcolor": { - "valType": "color", - "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "colorbars" - }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], - "role": "info", - "editType": "colorbars", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." - }, - "nticks": { - "valType": "integer", "min": 0, - "dflt": 0, - "role": "style", - "editType": "colorbars", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" - }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], "role": "style", - "editType": "colorbars", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" + "editType": "style", + "description": "Sets the marker size of unselected points, applied only when a selection exists." }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" + }, + "hoveron": { + "valType": "flaglist", + "flags": [ + "boxes", + "points" + ], + "dflt": "boxes+points", + "role": "info", + "editType": "style", + "description": "Do the hover effects highlight individual boxes or sample points or both?" + }, + "xcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `x` date data." + }, + "ycalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `y` date data." + }, + "xaxis": { + "valType": "subplotid", + "role": "info", + "dflt": "x", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." + }, + "yaxis": { + "valType": "subplotid", + "role": "info", + "dflt": "y", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." + }, + "idssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ids .", + "editType": "none" + }, + "customdatasrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for customdata .", + "editType": "none" + }, + "hoverinfosrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hoverinfo .", + "editType": "none" + }, + "ysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for y .", + "editType": "none" + }, + "xsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for x .", + "editType": "none" + }, + "textsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for text .", + "editType": "none" + } + }, + "layoutAttributes": { + "boxmode": { + "valType": "enumerated", + "values": [ + "group", + "overlay" + ], + "dflt": "overlay", + "role": "info", + "editType": "calc", + "description": "Determines how boxes at the same location coordinate are displayed on the graph. If *group*, the boxes are plotted next to one another centered around the shared location. If *overlay*, the boxes are plotted over one another, you might need to set *opacity* to see them multiple boxes." + }, + "boxgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.3, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between boxes of adjacent location coordinates." + }, + "boxgroupgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.3, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between boxes of the same location coordinate." + } + } + }, + "heatmap": { + "meta": { + "description": "The data that describes the heatmap value-to-color mapping is set in `z`. Data in `z` can either be a {2D array} of values (ragged or not) or a 1D array of values. In the case where `z` is a {2D array}, say that `z` has N rows and M columns. Then, by default, the resulting heatmap will have N partitions along the y axis and M partitions along the x axis. In other words, the i-th row/ j-th column cell in `z` is mapped to the i-th partition of the y axis (starting from the bottom of the plot) and the j-th partition of the x-axis (starting from the left of the plot). This behavior can be flipped by using `transpose`. Moreover, `x` (`y`) can be provided with M or M+1 (N or N+1) elements. If M (N), then the coordinates correspond to the center of the heatmap cells and the cells have equal width. If M+1 (N+1), then the coordinates correspond to the edges of the heatmap cells. In the case where `z` is a 1D {array}, the x and y coordinates must be provided in `x` and `y` respectively to form data triplets." + }, + "attributes": { + "type": "heatmap", + "visible": { + "valType": "enumerated", + "values": [ + true, + false, + "legendonly" + ], + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." + }, + "showlegend": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "style", + "description": "Determines whether or not an item corresponding to this trace is shown in the legend." + }, + "legendgroup": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "style", + "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." + }, + "opacity": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 1, + "editType": "style", + "description": "Sets the opacity of the trace." + }, + "name": { + "valType": "string", + "role": "info", + "editType": "style", + "description": "Sets the trace name. The trace name appear as the legend item and on hover." + }, + "uid": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "calc" + }, + "ids": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", + "role": "data" + }, + "customdata": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", + "role": "data" + }, + "selectedpoints": { + "valType": "any", + "role": "info", + "editType": "calc", + "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." + }, + "hoverinfo": { + "valType": "flaglist", + "role": "info", + "flags": [ + "x", + "y", + "z", + "text", + "name" + ], + "extras": [ + "all", + "none", + "skip" + ], + "arrayOk": true, + "dflt": "all", + "editType": "none", + "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." + }, + "hoverlabel": { + "bgcolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" + }, + "bordercolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." + }, + "font": { + "family": { + "valType": "string", "role": "style", - "editType": "colorbars", - "description": "Sets the tick length (in px)." + "noBlank": true, + "strict": true, + "editType": "none", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, - "tickwidth": { + "size": { "valType": "number", - "min": 0, - "dflt": 1, "role": "style", - "editType": "colorbars", - "description": "Sets the tick width (in px)." + "min": 1, + "editType": "none", + "arrayOk": true }, - "tickcolor": { + "color": { "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "colorbars", - "description": "Determines whether or not the tick labels are drawn." - }, - "tickfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets the color bar's tick label font", - "editType": "colorbars", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "colorbars", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." - }, - "tickformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "colorbars" - }, - { - "valType": "any", - "editType": "colorbars" - } - ], - "editType": "colorbars", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "colorbars", - "role": "object" - } - }, - "role": "object" - }, - "tickprefix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label prefix." - }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." - }, - "ticksuffix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label suffix." - }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "Same as `showtickprefix` but for tick suffixes." - }, - "separatethousands": { - "valType": "boolean", - "dflt": false, - "role": "style", - "editType": "colorbars", - "description": "If \"true\", even 4-digit integers are separated" - }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", - "role": "style", - "editType": "colorbars", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." - }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", "role": "style", - "editType": "colorbars", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + "editType": "none", + "arrayOk": true }, - "title": { + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { "valType": "string", "role": "info", - "description": "Sets the title of the color bar.", - "editType": "colorbars" - }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" }, - "editType": "colorbars", - "role": "object", - "tickvalssrc": { + "sizesrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", + "description": "Sets the source reference on plot.ly for size .", "editType": "none" }, - "ticktextsrc": { + "colorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", + "description": "Sets the source reference on plot.ly for color .", "editType": "none" } }, - "opacity": { - "valType": "number", + "namelength": { + "valType": "integer", + "min": -1, "arrayOk": true, - "dflt": 1, - "min": 0, - "max": 1, "role": "style", - "editType": "style", - "description": "Sets the opacity of the bars." + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." }, + "editType": "calc", "role": "object", - "colorsrc": { + "bgcolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for bgcolor .", "editType": "none" }, - "opacitysrc": { + "bordercolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for opacity .", + "description": "Sets the source reference on plot.ly for bordercolor .", + "editType": "none" + }, + "namelengthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for namelength .", "editType": "none" } }, - "selected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of selected points." - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of selected points." - }, - "editType": "style", - "role": "object" - }, - "textfont": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the text font color of selected points." - }, - "editType": "style", - "role": "object" + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { + "valType": "number", + "min": 0, + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, + "editType": "calc", + "role": "object" + }, + "z": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the z data.", + "role": "data" + }, + "x": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the x coordinates.", + "impliedEdits": { + "xtype": "array" + }, + "role": "data" + }, + "x0": { + "valType": "any", + "dflt": 0, + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step.", + "impliedEdits": { + "xtype": "scaled" + } + }, + "dx": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the x coordinate step. See `x0` for more info.", + "impliedEdits": { + "xtype": "scaled" + } + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinates.", + "impliedEdits": { + "ytype": "array" + }, + "role": "data" + }, + "y0": { + "valType": "any", + "dflt": 0, + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step.", + "impliedEdits": { + "ytype": "scaled" + } + }, + "dy": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the y coordinate step. See `y0` for more info.", + "impliedEdits": { + "ytype": "scaled" + } + }, + "text": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the text elements associated with each z value.", + "role": "data" + }, + "transpose": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Transposes the z data." + }, + "xtype": { + "valType": "enumerated", + "values": [ + "array", + "scaled" + ], + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "If *array*, the heatmap's x coordinates are given by *x* (the default behavior when `x` is provided). If *scaled*, the heatmap's x coordinates are given by *x0* and *dx* (the default behavior when `x` is not provided)." + }, + "ytype": { + "valType": "enumerated", + "values": [ + "array", + "scaled" + ], + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "If *array*, the heatmap's y coordinates are given by *y* (the default behavior when `y` is provided) If *scaled*, the heatmap's y coordinates are given by *y0* and *dy* (the default behavior when `y` is not provided)" + }, + "zsmooth": { + "valType": "enumerated", + "values": [ + "fast", + "best", + false + ], + "dflt": false, + "role": "style", + "editType": "calc", + "description": "Picks a smoothing algorithm use to smooth `z` data." + }, + "connectgaps": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in." + }, + "xgap": { + "valType": "number", + "dflt": 0, + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the horizontal gap (in pixels) between bricks." + }, + "ygap": { + "valType": "number", + "dflt": 0, + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the vertical gap (in pixels) between bricks." + }, + "zhoverformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "none", + "description": "Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-format/blob/master/README.md#locale_format" + }, + "zauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Determines the whether or not the color domain is computed with respect to the input data." + }, + "zmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "zauto": false }, - "editType": "style", - "role": "object" + "description": "Sets the lower bound of color domain." }, - "unselected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of unselected points, applied only when a selection exists." - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of unselected points, applied only when a selection exists." - }, - "editType": "style", - "role": "object" + "zmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "zauto": false }, - "textfont": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the text font color of unselected points, applied only when a selection exists." - }, - "editType": "style", - "role": "object" + "description": "Sets the upper bound of color domain." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false }, - "editType": "style", - "role": "object" + "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" }, - "r": { - "valType": "data_array", + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": false, "editType": "calc", - "description": "For legacy polar chart only.Please switch to *scatterpolar* trace type.Sets the radial coordinates.", - "role": "data" + "impliedEdits": {}, + "description": "Determines whether or not the colorscale is picked using the sign of the input z values." }, - "t": { - "valType": "data_array", + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, "editType": "calc", - "description": "For legacy polar chart only.Please switch to *scatterpolar* trace type.Sets the angular coordinates.", - "role": "data" + "description": "Reverses the colorscale." }, - "_deprecated": { - "bardir": { + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not a colorbar is displayed for this trace." + }, + "colorbar": { + "thicknessmode": { "valType": "enumerated", - "role": "info", - "editType": "calc", "values": [ - "v", - "h" + "fraction", + "pixels" ], - "description": "Renamed to `orientation`." - } - }, - "error_x": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "colorbars" }, - "type": { + "thickness": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "colorbars" + }, + "lenmode": { "valType": "enumerated", "values": [ - "percent", - "constant", - "sqrt", - "data" + "fraction", + "pixels" ], "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." - }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." - }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" - }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "colorbars" }, - "value": { + "len": { "valType": "number", "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + "dflt": 1, + "role": "style", + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "colorbars" }, - "valueminus": { + "x": { "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "colorbars" }, - "traceref": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "style" + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", + "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", + "editType": "colorbars" }, - "tracerefminus": { - "valType": "integer", + "xpad": { + "valType": "number", + "role": "style", "min": 0, - "dflt": 0, - "role": "info", - "editType": "style" + "dflt": 10, + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "colorbars" }, - "copy_ystyle": { - "valType": "boolean", + "y": { + "valType": "number", "role": "style", - "editType": "plot" + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "colorbars" }, - "color": { - "valType": "color", + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], "role": "style", - "editType": "style", - "description": "Sets the stoke color of the error bars." + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "colorbars" }, - "thickness": { + "ypad": { "valType": "number", + "role": "style", "min": 0, - "dflt": 2, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "colorbars" + }, + "outlinecolor": { + "valType": "color", + "dflt": "#444", "role": "style", - "editType": "style", - "description": "Sets the thickness (in px) of the error bars." + "editType": "colorbars", + "description": "Sets the axis line color." }, - "width": { + "outlinewidth": { "valType": "number", "min": 0, + "dflt": 1, "role": "style", - "editType": "plot", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + "editType": "colorbars", + "description": "Sets the width (in px) of the axis line." }, - "editType": "calc", - "_deprecated": { - "opacity": { - "valType": "number", - "role": "style", - "editType": "style", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } + "bordercolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." }, - "role": "object", - "arraysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for array .", - "editType": "none" + "borderwidth": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "colorbars" }, - "arrayminussrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", - "editType": "none" - } - }, - "error_y": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" }, - "type": { + "tickmode": { "valType": "enumerated", "values": [ - "percent", - "constant", - "sqrt", - "data" + "auto", + "linear", + "array" ], "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." }, - "array": { + "tick0": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", "role": "data" }, - "arrayminus": { + "ticktext": { "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", "role": "data" }, - "value": { + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" + }, + "ticklen": { "valType": "number", "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + "dflt": 5, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick length (in px)." }, - "valueminus": { + "tickwidth": { "valType": "number", "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick width (in px)." + }, + "tickcolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick color." + }, + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + }, + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label prefix." + }, + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." }, - "traceref": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "style" + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." }, - "tracerefminus": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "style" + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." }, - "color": { - "valType": "color", + "separatethousands": { + "valType": "boolean", + "dflt": false, "role": "style", - "editType": "style", - "description": "Sets the stoke color of the error bars." + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" }, - "thickness": { - "valType": "number", - "min": 0, - "dflt": 2, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", "role": "style", - "editType": "style", - "description": "Sets the thickness (in px) of the error bars." + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." }, - "width": { - "valType": "number", - "min": 0, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", "role": "style", - "editType": "plot", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." }, - "editType": "calc", - "_deprecated": { - "opacity": { + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", + "editType": "colorbars" + }, + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { "valType": "number", "role": "style", - "editType": "style", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" }, + "editType": "colorbars", "role": "object", - "arraysrc": { + "tickvalssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for array .", + "description": "Sets the source reference on plot.ly for tickvals .", "editType": "none" }, - "arrayminussrc": { + "ticktextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", + "description": "Sets the source reference on plot.ly for ticktext .", "editType": "none" } }, @@ -4394,7 +5412,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -4414,6 +5432,12 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, + "zsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for z .", + "editType": "none" + }, "xsrc": { "valType": "string", "role": "info", @@ -4431,919 +5455,1314 @@ "role": "info", "description": "Sets the source reference on plot.ly for text .", "editType": "none" + } + } + }, + "histogram": { + "meta": { + "description": "The sample data from which statistics are computed is set in `x` for vertically spanning histograms and in `y` for horizontally spanning histograms. Binning options are set `xbins` and `ybins` respectively if no aggregation data is provided." + }, + "attributes": { + "type": "histogram", + "visible": { + "valType": "enumerated", + "values": [ + true, + false, + "legendonly" + ], + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." }, - "hovertextsrc": { - "valType": "string", + "showlegend": { + "valType": "boolean", "role": "info", - "description": "Sets the source reference on plot.ly for hovertext .", - "editType": "none" + "dflt": true, + "editType": "style", + "description": "Determines whether or not an item corresponding to this trace is shown in the legend." }, - "textpositionsrc": { + "legendgroup": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for textposition .", - "editType": "none" + "dflt": "", + "editType": "style", + "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." }, - "basesrc": { + "opacity": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 1, + "editType": "style", + "description": "Sets the opacity of the trace." + }, + "name": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for base .", - "editType": "none" + "editType": "style", + "description": "Sets the trace name. The trace name appear as the legend item and on hover." }, - "offsetsrc": { + "uid": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for offset .", - "editType": "none" + "dflt": "", + "editType": "calc" }, - "widthsrc": { - "valType": "string", + "ids": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", + "role": "data" + }, + "customdata": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", + "role": "data" + }, + "selectedpoints": { + "valType": "any", "role": "info", - "description": "Sets the source reference on plot.ly for width .", - "editType": "none" + "editType": "calc", + "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." }, - "rsrc": { - "valType": "string", + "hoverinfo": { + "valType": "flaglist", "role": "info", - "description": "Sets the source reference on plot.ly for r .", - "editType": "none" + "flags": [ + "x", + "y", + "z", + "text", + "name" + ], + "extras": [ + "all", + "none", + "skip" + ], + "arrayOk": true, + "dflt": "all", + "editType": "none", + "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." }, - "tsrc": { + "hoverlabel": { + "bgcolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" + }, + "bordercolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." + }, + "font": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "none", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "none", + "arrayOk": true + }, + "color": { + "valType": "color", + "role": "style", + "editType": "none", + "arrayOk": true + }, + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "namelength": { + "valType": "integer", + "min": -1, + "arrayOk": true, + "role": "style", + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." + }, + "editType": "calc", + "role": "object", + "bgcolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bgcolor .", + "editType": "none" + }, + "bordercolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bordercolor .", + "editType": "none" + }, + "namelengthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for namelength .", + "editType": "none" + } + }, + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { + "valType": "number", + "min": 0, + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, + "editType": "calc", + "role": "object" + }, + "x": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the sample data to be binned on the x axis.", + "role": "data" + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the sample data to be binned on the y axis.", + "role": "data" + }, + "text": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for t .", - "editType": "none" - } - }, - "layoutAttributes": { - "barmode": { + "dflt": "", + "arrayOk": true, + "editType": "calc", + "description": "Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + }, + "orientation": { "valType": "enumerated", + "role": "info", "values": [ - "stack", - "group", - "overlay", - "relative" + "v", + "h" ], - "dflt": "group", - "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Sets the orientation of the bars. With *v* (*h*), the value of the each bar spans along the vertical (horizontal)." + }, + "histfunc": { + "valType": "enumerated", + "values": [ + "count", + "sum", + "avg", + "min", + "max" + ], + "role": "style", + "dflt": "count", "editType": "calc", - "description": "Determines how bars at the same location coordinate are displayed on the graph. With *stack*, the bars are stacked on top of one another With *relative*, the bars are stacked on top of one another, with negative values below the axis, positive values above With *group*, the bars are plotted next to one another centered around the shared location. With *overlay*, the bars are plotted over one another, you might need to an *opacity* to see multiple bars." + "description": "Specifies the binning function used for this histogram trace. If *count*, the histogram values are computed by counting the number of values lying inside each bin. If *sum*, *avg*, *min*, *max*, the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively." }, - "barnorm": { + "histnorm": { "valType": "enumerated", "values": [ "", - "fraction", - "percent" + "percent", + "probability", + "density", + "probability density" ], "dflt": "", - "role": "info", + "role": "style", "editType": "calc", - "description": "Sets the normalization for bar traces on the graph. With *fraction*, the value of each bar is divide by the sum of the values at the location coordinate. With *percent*, the results form *fraction* are presented in percents." + "description": "Specifies the type of normalization used for this histogram trace. If **, the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If *percent* / *probability*, the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If *density*, the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1)." }, - "bargap": { - "valType": "number", - "min": 0, - "max": 1, + "cumulative": { + "enabled": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "If true, display the cumulative distribution by summing the binned values. Use the `direction` and `centralbin` attributes to tune the accumulation method. Note: in this mode, the *density* `histnorm` settings behave the same as their equivalents without *density*: ** and *density* both rise to the number of data points, and *probability* and *probability density* both rise to the number of sample points." + }, + "direction": { + "valType": "enumerated", + "values": [ + "increasing", + "decreasing" + ], + "dflt": "increasing", + "role": "info", + "editType": "calc", + "description": "Only applies if cumulative is enabled. If *increasing* (default) we sum all prior bins, so the result increases from left to right. If *decreasing* we sum later bins so the result decreases from left to right." + }, + "currentbin": { + "valType": "enumerated", + "values": [ + "include", + "exclude", + "half" + ], + "dflt": "include", + "role": "info", + "editType": "calc", + "description": "Only applies if cumulative is enabled. Sets whether the current bin is included, excluded, or has half of its value included in the current cumulative value. *include* is the default for compatibility with various other tools, however it introduces a half-bin bias to the results. *exclude* makes the opposite half-bin bias, and *half* removes it." + }, + "editType": "calc", + "role": "object" + }, + "autobinx": { + "valType": "boolean", + "dflt": null, "role": "style", "editType": "calc", - "description": "Sets the gap (in plot fraction) between bars of adjacent location coordinates." + "impliedEdits": {}, + "description": "Determines whether or not the x axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in xbins." }, - "bargroupgap": { - "valType": "number", + "nbinsx": { + "valType": "integer", "min": 0, - "max": 1, "dflt": 0, "role": "style", "editType": "calc", - "description": "Sets the gap (in plot fraction) between bars of the same location coordinate." - } - } - }, - "heatmap": { - "meta": { - "description": "The data that describes the heatmap value-to-color mapping is set in `z`. Data in `z` can either be a {2D array} of values (ragged or not) or a 1D array of values. In the case where `z` is a {2D array}, say that `z` has N rows and M columns. Then, by default, the resulting heatmap will have N partitions along the y axis and M partitions along the x axis. In other words, the i-th row/ j-th column cell in `z` is mapped to the i-th partition of the y axis (starting from the bottom of the plot) and the j-th partition of the x-axis (starting from the left of the plot). This behavior can be flipped by using `transpose`. Moreover, `x` (`y`) can be provided with M or M+1 (N or N+1) elements. If M (N), then the coordinates correspond to the center of the heatmap cells and the cells have equal width. If M+1 (N+1), then the coordinates correspond to the edges of the heatmap cells. In the case where `z` is a 1D {array}, the x and y coordinates must be provided in `x` and `y` respectively to form data triplets." - }, - "attributes": { - "type": "heatmap", - "visible": { - "valType": "enumerated", - "values": [ - true, - false, - "legendonly" - ], - "role": "info", - "dflt": true, + "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." + }, + "xbins": { + "start": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobinx": false + }, + "description": "Sets the starting value for the x axis bins." + }, + "end": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobinx": false + }, + "description": "Sets the end value for the x axis bins." + }, + "size": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobinx": false + }, + "description": "Sets the step in-between value each x axis bin." + }, "editType": "calc", - "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." + "impliedEdits": { + "autobinx": false, + "role": "object" + }, + "role": "object" }, - "showlegend": { + "autobiny": { "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this trace is shown in the legend." - }, - "legendgroup": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "style", - "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." - }, - "opacity": { - "valType": "number", + "dflt": null, "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "editType": "style", - "description": "Sets the opacity of the trace." - }, - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the trace name. The trace name appear as the legend item and on hover." - }, - "uid": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "calc" - }, - "ids": { - "valType": "data_array", "editType": "calc", - "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", - "role": "data" + "impliedEdits": {}, + "description": "Determines whether or not the y axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in ybins." }, - "customdata": { - "valType": "data_array", + "nbinsy": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", "editType": "calc", - "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", - "role": "data" + "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." }, - "selectedpoints": { - "valType": "any", - "role": "info", + "ybins": { + "start": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false + }, + "description": "Sets the starting value for the y axis bins." + }, + "end": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false + }, + "description": "Sets the end value for the y axis bins." + }, + "size": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false + }, + "description": "Sets the step in-between value each y axis bin." + }, "editType": "calc", - "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." - }, - "hoverinfo": { - "valType": "flaglist", - "role": "info", - "flags": [ - "x", - "y", - "z", - "text", - "name" - ], - "extras": [ - "all", - "none", - "skip" - ], - "arrayOk": true, - "dflt": "all", - "editType": "none", - "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." + "impliedEdits": { + "autobiny": false, + "role": "object" + }, + "role": "object" }, - "hoverlabel": { - "bgcolor": { + "marker": { + "line": { + "width": { + "valType": "number", + "min": 0, + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the width (in px) of the lines bounding the marker points.", + "dflt": 0 + }, + "editType": "calc", + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "role": "object", + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "editType": "calc", + "color": { "valType": "color", - "role": "style", "arrayOk": true, - "editType": "none", - "description": "Sets the background color of the hover labels for this trace" + "role": "style", + "editType": "style", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, - "bordercolor": { - "valType": "color", + "colorscale": { + "valType": "colorscale", "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the border color of the hover labels for this trace." + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" }, - "font": { - "family": { + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." + }, + "colorbar": { + "thicknessmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "colorbars" + }, + "thickness": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "colorbars" + }, + "lenmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "info", + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "colorbars" + }, + "len": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "colorbars" + }, + "x": { + "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", + "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", + "editType": "colorbars" + }, + "xpad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "colorbars" + }, + "y": { + "valType": "number", + "role": "style", + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], + "role": "style", + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "colorbars" + }, + "ypad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "colorbars" + }, + "outlinecolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "outlinewidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the width (in px) of the axis line." + }, + "bordercolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "borderwidth": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "colorbars" + }, + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" + }, + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], + "role": "info", + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + }, + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + }, + "tick0": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" + }, + "ticktext": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" + }, + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" + }, + "ticklen": { + "valType": "number", + "min": 0, + "dflt": 5, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick length (in px)." + }, + "tickwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick width (in px)." + }, + "tickcolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick color." + }, + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { "valType": "string", + "dflt": "", "role": "style", - "noBlank": true, - "strict": true, - "editType": "none", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" }, - "size": { - "valType": "number", + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", "role": "style", - "min": 1, - "editType": "none", - "arrayOk": true + "editType": "colorbars", + "description": "Sets a tick label prefix." }, - "color": { - "valType": "color", + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", "role": "style", - "editType": "none", - "arrayOk": true + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." }, - "editType": "none", - "description": "Sets the font used in hover labels.", - "role": "object", - "familysrc": { + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." + }, + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." + }, + "separatethousands": { + "valType": "boolean", + "dflt": false, + "role": "style", + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" + }, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + }, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + }, + "title": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" + "description": "Sets the title of the color bar.", + "editType": "colorbars" }, - "sizesrc": { + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" + }, + "editType": "colorbars", + "role": "object", + "tickvalssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for size .", + "description": "Sets the source reference on plot.ly for tickvals .", "editType": "none" }, - "colorsrc": { + "ticktextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for ticktext .", "editType": "none" } }, - "namelength": { - "valType": "integer", - "min": -1, + "opacity": { + "valType": "number", "arrayOk": true, + "dflt": 1, + "min": 0, + "max": 1, "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." + "editType": "style", + "description": "Sets the opacity of the bars." }, - "editType": "calc", "role": "object", - "bgcolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", - "editType": "none" - }, - "bordercolorsrc": { + "colorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", + "description": "Sets the source reference on plot.ly for color .", "editType": "none" }, - "namelengthsrc": { + "opacitysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", + "description": "Sets the source reference on plot.ly for opacity .", "editType": "none" } }, - "stream": { - "token": { - "valType": "string", - "noBlank": true, - "strict": true, - "role": "info", - "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + "selected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of selected points." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of selected points." + }, + "editType": "style", + "role": "object" }, - "maxpoints": { - "valType": "number", - "min": 0, - "max": 10000, - "dflt": 500, - "role": "info", - "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the text font color of selected points." + }, + "editType": "style", + "role": "object" }, - "editType": "calc", + "editType": "style", "role": "object" }, - "z": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the z data.", - "role": "data" - }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinates.", - "impliedEdits": { - "xtype": "array" - }, - "role": "data" - }, - "x0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step.", - "impliedEdits": { - "xtype": "scaled" - } - }, - "dx": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the x coordinate step. See `x0` for more info.", - "impliedEdits": { - "xtype": "scaled" - } - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinates.", - "impliedEdits": { - "ytype": "array" - }, - "role": "data" - }, - "y0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step.", - "impliedEdits": { - "ytype": "scaled" - } - }, - "dy": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the y coordinate step. See `y0` for more info.", - "impliedEdits": { - "ytype": "scaled" - } - }, - "text": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the text elements associated with each z value.", - "role": "data" - }, - "transpose": { - "valType": "boolean", - "dflt": false, - "role": "info", - "editType": "calc", - "description": "Transposes the z data." - }, - "xtype": { - "valType": "enumerated", - "values": [ - "array", - "scaled" - ], - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "If *array*, the heatmap's x coordinates are given by *x* (the default behavior when `x` is provided). If *scaled*, the heatmap's x coordinates are given by *x0* and *dx* (the default behavior when `x` is not provided)." - }, - "ytype": { - "valType": "enumerated", - "values": [ - "array", - "scaled" - ], - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "If *array*, the heatmap's y coordinates are given by *y* (the default behavior when `y` is provided) If *scaled*, the heatmap's y coordinates are given by *y0* and *dy* (the default behavior when `y` is not provided)" - }, - "zsmooth": { - "valType": "enumerated", - "values": [ - "fast", - "best", - false - ], - "dflt": false, - "role": "style", - "editType": "calc", - "description": "Picks a smoothing algorithm use to smooth `z` data." - }, - "connectgaps": { - "valType": "boolean", - "dflt": false, - "role": "info", - "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in." - }, - "xgap": { - "valType": "number", - "dflt": 0, - "min": 0, - "role": "style", - "editType": "plot", - "description": "Sets the horizontal gap (in pixels) between bricks." - }, - "ygap": { - "valType": "number", - "dflt": 0, - "min": 0, - "role": "style", - "editType": "plot", - "description": "Sets the vertical gap (in pixels) between bricks." - }, - "zhoverformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "none", - "description": "Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-format/blob/master/README.md#locale_format" - }, - "zauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Determines the whether or not the color domain is computed with respect to the input data." - }, - "zmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the lower bound of color domain." - }, - "zmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the upper bound of color domain." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the colorscale is picked using the sign of the input z values." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Reverses the colorscale." - }, - "showscale": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "description": "Determines whether or not a colorbar is displayed for this trace." - }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "colorbars" + "unselected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of unselected points, applied only when a selection exists." + }, + "editType": "style", + "role": "object" }, - "thickness": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "colorbars" + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the text font color of unselected points, applied only when a selection exists." + }, + "editType": "style", + "role": "object" }, - "lenmode": { + "editType": "style", + "role": "object" + }, + "_deprecated": { + "bardir": { "valType": "enumerated", + "role": "info", + "editType": "calc", "values": [ - "fraction", - "pixels" + "v", + "h" ], + "description": "Renamed to `orientation`." + } + }, + "error_x": { + "visible": { + "valType": "boolean", "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "colorbars" - }, - "len": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "colorbars" - }, - "x": { - "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, - "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "colorbars" + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." }, - "xanchor": { + "type": { "valType": "enumerated", "values": [ - "left", - "center", - "right" + "percent", + "constant", + "sqrt", + "data" ], - "dflt": "left", - "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "colorbars" + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." }, - "xpad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "colorbars" + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." }, - "y": { - "valType": "number", - "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "colorbars" + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" }, - "yanchor": { - "valType": "enumerated", - "values": [ - "top", - "middle", - "bottom" - ], - "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "colorbars" + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" }, - "ypad": { + "value": { "valType": "number", - "role": "style", "min": 0, "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "colorbars" - }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." }, - "outlinewidth": { + "valueminus": { "valType": "number", "min": 0, - "dflt": 1, - "role": "style", - "editType": "colorbars", - "description": "Sets the width (in px) of the axis line." - }, - "bordercolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" }, - "borderwidth": { - "valType": "number", - "role": "style", + "traceref": { + "valType": "integer", "min": 0, "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "colorbars" - }, - "bgcolor": { - "valType": "color", - "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "colorbars" - }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], "role": "info", - "editType": "colorbars", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + "editType": "style" }, - "nticks": { + "tracerefminus": { "valType": "integer", "min": 0, "dflt": 0, - "role": "style", - "editType": "colorbars", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + "role": "info", + "editType": "style" }, - "dtick": { - "valType": "any", + "copy_ystyle": { + "valType": "boolean", "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" + "editType": "plot" }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], + "color": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" + "editType": "style", + "description": "Sets the stoke color of the error bars." }, - "ticklen": { + "thickness": { "valType": "number", "min": 0, - "dflt": 5, + "dflt": 2, "role": "style", - "editType": "colorbars", - "description": "Sets the tick length (in px)." + "editType": "style", + "description": "Sets the thickness (in px) of the error bars." }, - "tickwidth": { + "width": { "valType": "number", "min": 0, - "dflt": 1, "role": "style", - "editType": "colorbars", - "description": "Sets the tick width (in px)." - }, - "tickcolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "colorbars", - "description": "Determines whether or not the tick labels are drawn." + "editType": "plot", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." }, - "tickfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { + "editType": "calc", + "_deprecated": { + "opacity": { "valType": "number", "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets the color bar's tick label font", - "editType": "colorbars", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "colorbars", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + "editType": "style", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } }, - "tickformat": { + "role": "object", + "arraysrc": { "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "colorbars" - }, - { - "valType": "any", - "editType": "colorbars" - } - ], - "editType": "colorbars", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "colorbars", - "role": "object" - } - }, - "role": "object" + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" }, - "tickprefix": { + "arrayminussrc": { "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label prefix." + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } + }, + "error_y": { + "visible": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." }, - "showtickprefix": { + "type": { "valType": "enumerated", "values": [ - "all", - "first", - "last", - "none" + "percent", + "constant", + "sqrt", + "data" ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." }, - "ticksuffix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label suffix." + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "Same as `showtickprefix` but for tick suffixes." + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" }, - "separatethousands": { - "valType": "boolean", - "dflt": false, - "role": "style", - "editType": "colorbars", - "description": "If \"true\", even 4-digit integers are separated" + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", + "value": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + }, + "valueminus": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + }, + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "style" + }, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "style" + }, + "color": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + "editType": "style", + "description": "Sets the stoke color of the error bars." }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, "role": "style", - "editType": "colorbars", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + "editType": "style", + "description": "Sets the thickness (in px) of the error bars." }, - "title": { - "valType": "string", - "role": "info", - "description": "Sets the title of the color bar.", - "editType": "colorbars" + "width": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { + "editType": "calc", + "_deprecated": { + "opacity": { "valType": "number", "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" + "editType": "style", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } }, - "editType": "colorbars", "role": "object", - "tickvalssrc": { + "arraysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", + "description": "Sets the source reference on plot.ly for array .", "editType": "none" }, - "ticktextsrc": { + "arrayminussrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", + "description": "Sets the source reference on plot.ly for arrayminus .", "editType": "none" } }, @@ -5409,7 +6828,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -5429,12 +6848,6 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "zsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for z .", - "editType": "none" - }, "xsrc": { "valType": "string", "role": "info", @@ -5453,14 +6866,59 @@ "description": "Sets the source reference on plot.ly for text .", "editType": "none" } + }, + "layoutAttributes": { + "barmode": { + "valType": "enumerated", + "values": [ + "stack", + "group", + "overlay", + "relative" + ], + "dflt": "group", + "role": "info", + "editType": "calc", + "description": "Determines how bars at the same location coordinate are displayed on the graph. With *stack*, the bars are stacked on top of one another With *relative*, the bars are stacked on top of one another, with negative values below the axis, positive values above With *group*, the bars are plotted next to one another centered around the shared location. With *overlay*, the bars are plotted over one another, you might need to an *opacity* to see multiple bars." + }, + "barnorm": { + "valType": "enumerated", + "values": [ + "", + "fraction", + "percent" + ], + "dflt": "", + "role": "info", + "editType": "calc", + "description": "Sets the normalization for bar traces on the graph. With *fraction*, the value of each bar is divide by the sum of the values at the location coordinate. With *percent*, the results form *fraction* are presented in percents." + }, + "bargap": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between bars of adjacent location coordinates." + }, + "bargroupgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between bars of the same location coordinate." + } } }, - "histogram": { + "histogram2d": { "meta": { - "description": "The sample data from which statistics are computed is set in `x` for vertically spanning histograms and in `y` for horizontally spanning histograms. Binning options are set `xbins` and `ybins` respectively if no aggregation data is provided." + "hrName": "histogram_2d", + "description": "The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a heatmap." }, "attributes": { - "type": "histogram", + "type": "histogram2d", "visible": { "valType": "enumerated", "values": [ @@ -5535,1231 +6993,816 @@ "z", "text", "name" - ], - "extras": [ - "all", - "none", - "skip" - ], - "arrayOk": true, - "dflt": "all", - "editType": "none", - "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." - }, - "hoverlabel": { - "bgcolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the background color of the hover labels for this trace" - }, - "bordercolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the border color of the hover labels for this trace." - }, - "font": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "none", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "none", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "none", - "arrayOk": true - }, - "editType": "none", - "description": "Sets the font used in hover labels.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "namelength": { - "valType": "integer", - "min": -1, - "arrayOk": true, - "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." - }, - "editType": "calc", - "role": "object", - "bgcolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", - "editType": "none" - }, - "bordercolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", - "editType": "none" - }, - "namelengthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", - "editType": "none" - } - }, - "stream": { - "token": { - "valType": "string", - "noBlank": true, - "strict": true, - "role": "info", - "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." - }, - "maxpoints": { - "valType": "number", - "min": 0, - "max": 10000, - "dflt": 500, - "role": "info", - "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." - }, - "editType": "calc", - "role": "object" - }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the sample data to be binned on the x axis.", - "role": "data" - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the sample data to be binned on the y axis.", - "role": "data" - }, - "text": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "calc", - "description": "Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." - }, - "orientation": { - "valType": "enumerated", - "role": "info", - "values": [ - "v", - "h" - ], - "editType": "calc+clearAxisTypes", - "description": "Sets the orientation of the bars. With *v* (*h*), the value of the each bar spans along the vertical (horizontal)." - }, - "histfunc": { - "valType": "enumerated", - "values": [ - "count", - "sum", - "avg", - "min", - "max" - ], - "role": "style", - "dflt": "count", - "editType": "calc", - "description": "Specifies the binning function used for this histogram trace. If *count*, the histogram values are computed by counting the number of values lying inside each bin. If *sum*, *avg*, *min*, *max*, the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively." - }, - "histnorm": { - "valType": "enumerated", - "values": [ - "", - "percent", - "probability", - "density", - "probability density" - ], - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Specifies the type of normalization used for this histogram trace. If **, the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If *percent* / *probability*, the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If *density*, the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1)." - }, - "cumulative": { - "enabled": { - "valType": "boolean", - "dflt": false, - "role": "info", - "editType": "calc", - "description": "If true, display the cumulative distribution by summing the binned values. Use the `direction` and `centralbin` attributes to tune the accumulation method. Note: in this mode, the *density* `histnorm` settings behave the same as their equivalents without *density*: ** and *density* both rise to the number of data points, and *probability* and *probability density* both rise to the number of sample points." - }, - "direction": { - "valType": "enumerated", - "values": [ - "increasing", - "decreasing" - ], - "dflt": "increasing", - "role": "info", - "editType": "calc", - "description": "Only applies if cumulative is enabled. If *increasing* (default) we sum all prior bins, so the result increases from left to right. If *decreasing* we sum later bins so the result decreases from left to right." - }, - "currentbin": { - "valType": "enumerated", - "values": [ - "include", - "exclude", - "half" - ], - "dflt": "include", - "role": "info", - "editType": "calc", - "description": "Only applies if cumulative is enabled. Sets whether the current bin is included, excluded, or has half of its value included in the current cumulative value. *include* is the default for compatibility with various other tools, however it introduces a half-bin bias to the results. *exclude* makes the opposite half-bin bias, and *half* removes it." - }, - "editType": "calc", - "role": "object" - }, - "autobinx": { - "valType": "boolean", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the x axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in xbins." - }, - "nbinsx": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "calc", - "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." - }, - "xbins": { - "start": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobinx": false - }, - "description": "Sets the starting value for the x axis bins." - }, - "end": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobinx": false - }, - "description": "Sets the end value for the x axis bins." - }, - "size": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobinx": false - }, - "description": "Sets the step in-between value each x axis bin." - }, - "editType": "calc", - "impliedEdits": { - "autobinx": false, - "role": "object" - }, - "role": "object" - }, - "autobiny": { - "valType": "boolean", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the y axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in ybins." - }, - "nbinsy": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "calc", - "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." - }, - "ybins": { - "start": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the starting value for the y axis bins." - }, - "end": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the end value for the y axis bins." - }, - "size": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the step in-between value each y axis bin." - }, - "editType": "calc", - "impliedEdits": { - "autobiny": false, - "role": "object" - }, - "role": "object" - }, - "marker": { - "line": { - "width": { - "valType": "number", - "min": 0, - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the width (in px) of the lines bounding the marker points.", - "dflt": 0 - }, - "editType": "calc", - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "role": "object", - "widthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for width .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "editType": "calc", - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", + ], + "extras": [ + "all", + "none", + "skip" + ], + "arrayOk": true, + "dflt": "all", + "editType": "none", + "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." + }, + "hoverlabel": { + "bgcolor": { + "valType": "color", "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "arrayOk": true, + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" }, - "reversescale": { - "valType": "boolean", + "bordercolor": { + "valType": "color", "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "showscale": { - "valType": "boolean", - "role": "info", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "colorbars" - }, - "thickness": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "colorbars" - }, - "lenmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "colorbars" - }, - "len": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "colorbars" - }, - "x": { - "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, - "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "colorbars" - }, - "xanchor": { - "valType": "enumerated", - "values": [ - "left", - "center", - "right" - ], - "dflt": "left", - "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "colorbars" - }, - "xpad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "colorbars" - }, - "y": { - "valType": "number", - "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "colorbars" - }, - "yanchor": { - "valType": "enumerated", - "values": [ - "top", - "middle", - "bottom" - ], - "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "colorbars" - }, - "ypad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "colorbars" - }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." - }, - "outlinewidth": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "colorbars", - "description": "Sets the width (in px) of the axis line." - }, - "bordercolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." - }, - "borderwidth": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "colorbars" - }, - "bgcolor": { - "valType": "color", - "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "colorbars" - }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], - "role": "info", - "editType": "colorbars", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." - }, - "nticks": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "colorbars", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" - }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], - "role": "style", - "editType": "colorbars", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" - }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, + "font": { + "family": { + "valType": "string", "role": "style", - "editType": "colorbars", - "description": "Sets the tick length (in px)." + "noBlank": true, + "strict": true, + "editType": "none", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, - "tickwidth": { + "size": { "valType": "number", - "min": 0, - "dflt": 1, "role": "style", - "editType": "colorbars", - "description": "Sets the tick width (in px)." + "min": 1, + "editType": "none", + "arrayOk": true }, - "tickcolor": { + "color": { "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "colorbars", - "description": "Determines whether or not the tick labels are drawn." - }, - "tickfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets the color bar's tick label font", - "editType": "colorbars", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "colorbars", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." - }, - "tickformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "colorbars" - }, - { - "valType": "any", - "editType": "colorbars" - } - ], - "editType": "colorbars", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "colorbars", - "role": "object" - } - }, - "role": "object" - }, - "tickprefix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label prefix." - }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." - }, - "ticksuffix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label suffix." - }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "Same as `showtickprefix` but for tick suffixes." - }, - "separatethousands": { - "valType": "boolean", - "dflt": false, "role": "style", - "editType": "colorbars", - "description": "If \"true\", even 4-digit integers are separated" - }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", - "role": "style", - "editType": "colorbars", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." - }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + "editType": "none", + "arrayOk": true }, - "title": { + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { "valType": "string", "role": "info", - "description": "Sets the title of the color bar.", - "editType": "colorbars" - }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" }, - "editType": "colorbars", - "role": "object", - "tickvalssrc": { + "sizesrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", + "description": "Sets the source reference on plot.ly for size .", "editType": "none" }, - "ticktextsrc": { + "colorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", + "description": "Sets the source reference on plot.ly for color .", "editType": "none" } }, - "opacity": { - "valType": "number", + "namelength": { + "valType": "integer", + "min": -1, "arrayOk": true, - "dflt": 1, + "role": "style", + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." + }, + "editType": "calc", + "role": "object", + "bgcolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bgcolor .", + "editType": "none" + }, + "bordercolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bordercolor .", + "editType": "none" + }, + "namelengthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for namelength .", + "editType": "none" + } + }, + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { + "valType": "number", "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the opacity of the bars." + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, + "editType": "calc", + "role": "object" + }, + "x": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the sample data to be binned on the x axis.", + "role": "data" + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the sample data to be binned on the y axis.", + "role": "data" + }, + "z": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the aggregation data.", + "role": "data" + }, + "marker": { + "color": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the aggregation data.", + "role": "data" }, + "editType": "calc", "role": "object", "colorsrc": { "valType": "string", "role": "info", "description": "Sets the source reference on plot.ly for color .", "editType": "none" - }, - "opacitysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for opacity .", - "editType": "none" } }, - "selected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of selected points." + "histnorm": { + "valType": "enumerated", + "values": [ + "", + "percent", + "probability", + "density", + "probability density" + ], + "dflt": "", + "role": "style", + "editType": "calc", + "description": "Specifies the type of normalization used for this histogram trace. If **, the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If *percent* / *probability*, the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If *density*, the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1)." + }, + "histfunc": { + "valType": "enumerated", + "values": [ + "count", + "sum", + "avg", + "min", + "max" + ], + "role": "style", + "dflt": "count", + "editType": "calc", + "description": "Specifies the binning function used for this histogram trace. If *count*, the histogram values are computed by counting the number of values lying inside each bin. If *sum*, *avg*, *min*, *max*, the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively." + }, + "autobinx": { + "valType": "boolean", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": {}, + "description": "Determines whether or not the x axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in xbins." + }, + "nbinsx": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." + }, + "xbins": { + "start": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobinx": false }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of selected points." + "description": "Sets the starting value for the x axis bins." + }, + "end": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobinx": false }, - "editType": "style", - "role": "object" + "description": "Sets the end value for the x axis bins." }, - "textfont": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the text font color of selected points." + "size": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobinx": false }, - "editType": "style", + "description": "Sets the step in-between value each x axis bin." + }, + "editType": "calc", + "impliedEdits": { + "autobinx": false, "role": "object" }, - "editType": "style", "role": "object" }, - "unselected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + "autobiny": { + "valType": "boolean", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": {}, + "description": "Determines whether or not the y axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in ybins." + }, + "nbinsy": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." + }, + "ybins": { + "start": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of unselected points, applied only when a selection exists." + "description": "Sets the starting value for the y axis bins." + }, + "end": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false }, - "editType": "style", - "role": "object" + "description": "Sets the end value for the y axis bins." }, - "textfont": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the text font color of unselected points, applied only when a selection exists." + "size": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false }, - "editType": "style", + "description": "Sets the step in-between value each y axis bin." + }, + "editType": "calc", + "impliedEdits": { + "autobiny": false, "role": "object" }, - "editType": "style", "role": "object" }, - "_deprecated": { - "bardir": { + "xgap": { + "valType": "number", + "dflt": 0, + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the horizontal gap (in pixels) between bricks." + }, + "ygap": { + "valType": "number", + "dflt": 0, + "min": 0, + "role": "style", + "editType": "plot", + "description": "Sets the vertical gap (in pixels) between bricks." + }, + "zsmooth": { + "valType": "enumerated", + "values": [ + "fast", + "best", + false + ], + "dflt": false, + "role": "style", + "editType": "calc", + "description": "Picks a smoothing algorithm use to smooth `z` data." + }, + "zhoverformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "none", + "description": "Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-format/blob/master/README.md#locale_format" + }, + "zauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Determines the whether or not the color domain is computed with respect to the input data." + }, + "zmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "zauto": false + }, + "description": "Sets the lower bound of color domain." + }, + "zmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "zauto": false + }, + "description": "Sets the upper bound of color domain." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "impliedEdits": {}, + "description": "Determines whether or not the colorscale is picked using the sign of the input z values." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Reverses the colorscale." + }, + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not a colorbar is displayed for this trace." + }, + "colorbar": { + "thicknessmode": { "valType": "enumerated", - "role": "info", - "editType": "calc", "values": [ - "v", - "h" + "fraction", + "pixels" ], - "description": "Renamed to `orientation`." - } - }, - "error_x": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "colorbars" }, - "type": { + "thickness": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "colorbars" + }, + "lenmode": { "valType": "enumerated", "values": [ - "percent", - "constant", - "sqrt", - "data" + "fraction", + "pixels" ], "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "colorbars" }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + "len": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "colorbars" }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" + "x": { + "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "colorbars" }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", + "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", + "editType": "colorbars" }, - "value": { + "xpad": { "valType": "number", + "role": "style", "min": 0, "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "colorbars" }, - "valueminus": { + "y": { + "valType": "number", + "role": "style", + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], + "role": "style", + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "colorbars" + }, + "ypad": { "valType": "number", + "role": "style", "min": 0, "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "colorbars" }, - "traceref": { - "valType": "integer", + "outlinecolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "outlinewidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the width (in px) of the axis line." + }, + "bordercolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "borderwidth": { + "valType": "number", + "role": "style", "min": 0, "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "colorbars" + }, + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" + }, + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], "role": "info", - "editType": "style" + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." }, - "tracerefminus": { + "nticks": { "valType": "integer", "min": 0, "dflt": 0, - "role": "info", - "editType": "style" + "role": "style", + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." }, - "copy_ystyle": { - "valType": "boolean", + "tick0": { + "valType": "any", "role": "style", - "editType": "plot" + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" + }, + "ticktext": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" }, - "color": { - "valType": "color", + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], "role": "style", - "editType": "style", - "description": "Sets the stoke color of the error bars." + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" }, - "thickness": { + "ticklen": { "valType": "number", "min": 0, - "dflt": 2, + "dflt": 5, "role": "style", - "editType": "style", - "description": "Sets the thickness (in px) of the error bars." + "editType": "colorbars", + "description": "Sets the tick length (in px)." }, - "width": { + "tickwidth": { "valType": "number", "min": 0, + "dflt": 1, "role": "style", - "editType": "plot", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + "editType": "colorbars", + "description": "Sets the tick width (in px)." }, - "editType": "calc", - "_deprecated": { - "opacity": { + "tickcolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick color." + }, + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { "valType": "number", "role": "style", - "editType": "style", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" }, - "role": "object", - "arraysrc": { + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for array .", - "editType": "none" + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" }, - "arrayminussrc": { + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", - "editType": "none" - } - }, - "error_y": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label prefix." }, - "type": { + "showtickprefix": { "valType": "enumerated", "values": [ - "percent", - "constant", - "sqrt", - "data" + "all", + "first", + "last", + "none" ], - "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." - }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." - }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" - }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" - }, - "value": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." - }, - "valueminus": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." }, - "traceref": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "style" + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." }, - "tracerefminus": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "style" + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." }, - "color": { - "valType": "color", + "separatethousands": { + "valType": "boolean", + "dflt": false, "role": "style", - "editType": "style", - "description": "Sets the stoke color of the error bars." + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" }, - "thickness": { - "valType": "number", - "min": 0, - "dflt": 2, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", "role": "style", - "editType": "style", - "description": "Sets the thickness (in px) of the error bars." + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." }, - "width": { - "valType": "number", - "min": 0, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", "role": "style", - "editType": "plot", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." }, - "editType": "calc", - "_deprecated": { - "opacity": { + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", + "editType": "colorbars" + }, + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { "valType": "number", "role": "style", - "editType": "style", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" }, + "editType": "colorbars", "role": "object", - "arraysrc": { + "tickvalssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for array .", + "description": "Sets the source reference on plot.ly for tickvals .", "editType": "none" }, - "arrayminussrc": { + "ticktextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", + "description": "Sets the source reference on plot.ly for ticktext .", "editType": "none" } }, @@ -6825,7 +7868,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -6857,65 +7900,21 @@ "description": "Sets the source reference on plot.ly for y .", "editType": "none" }, - "textsrc": { + "zsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for text .", + "description": "Sets the source reference on plot.ly for z .", "editType": "none" } - }, - "layoutAttributes": { - "barmode": { - "valType": "enumerated", - "values": [ - "stack", - "group", - "overlay", - "relative" - ], - "dflt": "group", - "role": "info", - "editType": "calc", - "description": "Determines how bars at the same location coordinate are displayed on the graph. With *stack*, the bars are stacked on top of one another With *relative*, the bars are stacked on top of one another, with negative values below the axis, positive values above With *group*, the bars are plotted next to one another centered around the shared location. With *overlay*, the bars are plotted over one another, you might need to an *opacity* to see multiple bars." - }, - "barnorm": { - "valType": "enumerated", - "values": [ - "", - "fraction", - "percent" - ], - "dflt": "", - "role": "info", - "editType": "calc", - "description": "Sets the normalization for bar traces on the graph. With *fraction*, the value of each bar is divide by the sum of the values at the location coordinate. With *percent*, the results form *fraction* are presented in percents." - }, - "bargap": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "calc", - "description": "Sets the gap (in plot fraction) between bars of adjacent location coordinates." - }, - "bargroupgap": { - "valType": "number", - "min": 0, - "max": 1, - "dflt": 0, - "role": "style", - "editType": "calc", - "description": "Sets the gap (in plot fraction) between bars of the same location coordinate." - } } }, - "histogram2d": { + "histogram2dcontour": { "meta": { - "hrName": "histogram_2d", - "description": "The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a heatmap." + "hrName": "histogram_2d_contour", + "description": "The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a contour plot." }, "attributes": { - "type": "histogram2d", + "type": "histogram2dcontour", "visible": { "valType": "enumerated", "values": [ @@ -7259,55 +8258,222 @@ "dflt": null, "role": "style", "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the end value for the y axis bins." + "impliedEdits": { + "^autobiny": false + }, + "description": "Sets the end value for the y axis bins." + }, + "size": { + "valType": "any", + "dflt": null, + "role": "style", + "editType": "calc", + "impliedEdits": { + "^autobiny": false + }, + "description": "Sets the step in-between value each y axis bin." + }, + "editType": "calc", + "impliedEdits": { + "autobiny": false, + "role": "object" + }, + "role": "object" + }, + "autocontour": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "calc", + "impliedEdits": {}, + "description": "Determines whether or not the contour level attributes are picked by an algorithm. If *true*, the number of contour levels can be set in `ncontours`. If *false*, set the contour level attributes in `contours`." + }, + "ncontours": { + "valType": "integer", + "dflt": 15, + "min": 1, + "role": "style", + "editType": "calc", + "description": "Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is *true* or if `contours.size` is missing." + }, + "contours": { + "type": { + "valType": "enumerated", + "values": [ + "levels", + "constraint" + ], + "dflt": "levels", + "role": "info", + "editType": "calc", + "description": "If `levels`, the data is represented as a contour plot with multiple levels displayed. If `constraint`, the data is represented as constraints with the invalid region shaded as specified by the `operation` and `value` parameters." + }, + "start": { + "valType": "number", + "dflt": null, + "role": "style", + "editType": "plot", + "impliedEdits": { + "^autocontour": false + }, + "description": "Sets the starting contour level value. Must be less than `contours.end`" + }, + "end": { + "valType": "number", + "dflt": null, + "role": "style", + "editType": "plot", + "impliedEdits": { + "^autocontour": false + }, + "description": "Sets the end contour level value. Must be more than `contours.start`" + }, + "size": { + "valType": "number", + "dflt": null, + "min": 0, + "role": "style", + "editType": "plot", + "impliedEdits": { + "^autocontour": false + }, + "description": "Sets the step between each contour level. Must be positive." + }, + "coloring": { + "valType": "enumerated", + "values": [ + "fill", + "heatmap", + "lines", + "none" + ], + "dflt": "fill", + "role": "style", + "editType": "calc", + "description": "Determines the coloring method showing the contour values. If *fill*, coloring is done evenly between each contour level If *heatmap*, a heatmap gradient coloring is applied between each contour level. If *lines*, coloring is done on the contour lines. If *none*, no coloring is applied on this trace." + }, + "showlines": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "plot", + "description": "Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to *fill*." + }, + "showlabels": { + "valType": "boolean", + "dflt": false, + "role": "style", + "editType": "plot", + "description": "Determines whether to label the contour lines with their values." + }, + "labelfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "plot", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "plot" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style" + }, + "editType": "plot", + "description": "Sets the font used for labeling the contour levels. The default color comes from the lines, if shown. The default family and size come from `layout.font`.", + "role": "object" + }, + "labelformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "plot", + "description": "Sets the contour label formatting rule using d3 formatting mini-language which is very similar to Python, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format." + }, + "operation": { + "valType": "enumerated", + "values": [ + "=", + "<", + ">=", + ">", + "<=", + "[]", + "()", + "[)", + "(]", + "][", + ")(", + "](", + ")[" + ], + "role": "info", + "dflt": "=", + "editType": "calc", + "description": "Sets the constraint operation. *=* keeps regions equal to `value` *<* and *<=* keep regions less than `value` *>* and *>=* keep regions greater than `value` *[]*, *()*, *[)*, and *(]* keep regions inside `value[0]` to `value[1]` *][*, *)(*, *](*, *)[* keep regions outside `value[0]` to value[1]` Open vs. closed intervals make no difference to constraint display, but all versions are allowed for consistency with filter transforms." }, - "size": { + "value": { "valType": "any", - "dflt": null, - "role": "style", + "dflt": 0, + "role": "info", "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the step in-between value each y axis bin." + "description": "Sets the value or values of the constraint boundary. When `operation` is set to one of the comparison values (=,<,>=,>,<=) *value* is expected to be a number. When `operation` is set to one of the interval values ([],(),[),(],][,)(,](,)[) *value* is expected to be an array of two numbers where the first is the lower bound and the second is the upper bound." }, "editType": "calc", "impliedEdits": { - "autobiny": false, + "autocontour": false, "role": "object" }, "role": "object" }, - "xgap": { - "valType": "number", - "dflt": 0, - "min": 0, - "role": "style", - "editType": "plot", - "description": "Sets the horizontal gap (in pixels) between bricks." - }, - "ygap": { - "valType": "number", - "dflt": 0, - "min": 0, - "role": "style", + "line": { + "color": { + "valType": "color", + "role": "style", + "editType": "style+colorbars", + "description": "Sets the color of the contour level. Has no effect if `contours.coloring` is set to *lines*." + }, + "width": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "style+colorbars", + "description": "Sets the line width (in px)." + }, + "dash": { + "valType": "string", + "values": [ + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" + ], + "dflt": "solid", + "role": "style", + "editType": "style", + "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." + }, + "smoothing": { + "valType": "number", + "min": 0, + "max": 1.3, + "dflt": 1, + "role": "style", + "editType": "plot", + "description": "Sets the amount of smoothing for the contour lines, where *0* corresponds to no smoothing." + }, "editType": "plot", - "description": "Sets the vertical gap (in pixels) between bricks." - }, - "zsmooth": { - "valType": "enumerated", - "values": [ - "fast", - "best", - false - ], - "dflt": false, - "role": "style", - "editType": "calc", - "description": "Picks a smoothing algorithm use to smooth `z` data." + "role": "object" }, "zhoverformat": { "valType": "string", @@ -7328,7 +8494,7 @@ "valType": "number", "role": "info", "dflt": null, - "editType": "plot", + "editType": "calc", "impliedEdits": { "zauto": false }, @@ -7338,7 +8504,7 @@ "valType": "number", "role": "info", "dflt": null, - "editType": "plot", + "editType": "calc", "impliedEdits": { "zauto": false }, @@ -7356,7 +8522,7 @@ "autocolorscale": { "valType": "boolean", "role": "style", - "dflt": false, + "dflt": true, "editType": "calc", "impliedEdits": {}, "description": "Determines whether or not the colorscale is picked using the sign of the input z values." @@ -7505,367 +8671,917 @@ "bgcolor": { "valType": "color", "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "colorbars" - }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], - "role": "info", - "editType": "colorbars", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." - }, - "nticks": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "colorbars", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" - }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], - "role": "style", - "editType": "colorbars", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" - }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, - "role": "style", - "editType": "colorbars", - "description": "Sets the tick length (in px)." - }, - "tickwidth": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "colorbars", - "description": "Sets the tick width (in px)." + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" + }, + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], + "role": "info", + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + }, + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + }, + "tick0": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" + }, + "ticktext": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" + }, + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" + }, + "ticklen": { + "valType": "number", + "min": 0, + "dflt": 5, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick length (in px)." + }, + "tickwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick width (in px)." + }, + "tickcolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick color." + }, + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + }, + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label prefix." + }, + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + }, + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." + }, + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." + }, + "separatethousands": { + "valType": "boolean", + "dflt": false, + "role": "style", + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" + }, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + }, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + }, + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", + "editType": "colorbars" + }, + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" + }, + "editType": "colorbars", + "role": "object", + "tickvalssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for tickvals .", + "editType": "none" + }, + "ticktextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ticktext .", + "editType": "none" + } + }, + "xcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `x` date data." + }, + "ycalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `y` date data." + }, + "xaxis": { + "valType": "subplotid", + "role": "info", + "dflt": "x", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." + }, + "yaxis": { + "valType": "subplotid", + "role": "info", + "dflt": "y", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." + }, + "idssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ids .", + "editType": "none" + }, + "customdatasrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for customdata .", + "editType": "none" + }, + "hoverinfosrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hoverinfo .", + "editType": "none" + }, + "xsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for x .", + "editType": "none" + }, + "ysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for y .", + "editType": "none" + }, + "zsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for z .", + "editType": "none" + } + } + }, + "pie": { + "meta": { + "description": "A data visualized by the sectors of the pie is set in `values`. The sector labels are set in `labels`. The sector colors are set in `marker.colors`" + }, + "attributes": { + "type": "pie", + "visible": { + "valType": "enumerated", + "values": [ + true, + false, + "legendonly" + ], + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." + }, + "showlegend": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "style", + "description": "Determines whether or not an item corresponding to this trace is shown in the legend." + }, + "legendgroup": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "style", + "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." + }, + "opacity": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 1, + "editType": "style", + "description": "Sets the opacity of the trace." + }, + "name": { + "valType": "string", + "role": "info", + "editType": "style", + "description": "Sets the trace name. The trace name appear as the legend item and on hover." + }, + "uid": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "calc" + }, + "ids": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", + "role": "data" + }, + "customdata": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", + "role": "data" + }, + "selectedpoints": { + "valType": "any", + "role": "info", + "editType": "calc", + "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." + }, + "hoverinfo": { + "valType": "flaglist", + "role": "info", + "flags": [ + "label", + "text", + "value", + "percent", + "name" + ], + "extras": [ + "all", + "none", + "skip" + ], + "arrayOk": true, + "dflt": "all", + "editType": "none", + "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." + }, + "hoverlabel": { + "bgcolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" }, - "tickcolor": { + "bordercolor": { "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, "role": "style", - "editType": "colorbars", - "description": "Determines whether or not the tick labels are drawn." + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." }, - "tickfont": { + "font": { "family": { "valType": "string", "role": "style", "noBlank": true, "strict": true, + "editType": "none", "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" + "arrayOk": true }, "size": { "valType": "number", "role": "style", "min": 1, - "editType": "colorbars" + "editType": "none", + "arrayOk": true }, "color": { "valType": "color", "role": "style", - "editType": "colorbars" + "editType": "none", + "arrayOk": true }, - "description": "Sets the color bar's tick label font", - "editType": "colorbars", - "role": "object" + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } }, - "tickangle": { - "valType": "angle", - "dflt": "auto", + "namelength": { + "valType": "integer", + "min": -1, + "arrayOk": true, "role": "style", - "editType": "colorbars", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." }, - "tickformat": { + "editType": "calc", + "role": "object", + "bgcolorsrc": { "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + "role": "info", + "description": "Sets the source reference on plot.ly for bgcolor .", + "editType": "none" }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "colorbars" - }, - { - "valType": "any", - "editType": "colorbars" - } - ], - "editType": "colorbars", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "colorbars", - "role": "object" - } + "bordercolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bordercolor .", + "editType": "none" + }, + "namelengthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for namelength .", + "editType": "none" + } + }, + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { + "valType": "number", + "min": 0, + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, + "editType": "calc", + "role": "object" + }, + "labels": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the sector labels. If `labels` entries are duplicated, we sum associated `values` or simply count occurrences if `values` is not provided. For other array attributes (including color) we use the first non-empty entry among all occurrences of the label.", + "role": "data" + }, + "label0": { + "valType": "number", + "role": "info", + "dflt": 0, + "editType": "calc", + "description": "Alternate to `labels`. Builds a numeric set of labels. Use with `dlabel` where `label0` is the starting label and `dlabel` the step." + }, + "dlabel": { + "valType": "number", + "role": "info", + "dflt": 1, + "editType": "calc", + "description": "Sets the label step. See `label0` for more info." + }, + "values": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the values of the sectors of this pie chart. If omitted, we count occurrences of each label.", + "role": "data" + }, + "marker": { + "colors": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the color of each sector of this pie chart. If not specified, the default trace color set is used to pick the sector colors.", + "role": "data" + }, + "line": { + "color": { + "valType": "color", + "role": "style", + "dflt": "#444", + "arrayOk": true, + "editType": "style", + "description": "Sets the color of the line enclosing each sector." }, - "role": "object" + "width": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 0, + "arrayOk": true, + "editType": "style", + "description": "Sets the width (in px) of the line enclosing each sector." + }, + "editType": "calc", + "role": "object", + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + }, + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + } }, - "tickprefix": { + "editType": "calc", + "role": "object", + "colorssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for colors .", + "editType": "none" + } + }, + "text": { + "valType": "data_array", + "editType": "calc", + "description": "Sets text elements associated with each sector. If trace `textinfo` contains a *text* flag, these elements will seen on the chart. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels.", + "role": "data" + }, + "hovertext": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "style", + "description": "Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a *text* flag." + }, + "scalegroup": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "calc", + "description": "If there are multiple pies that should be sized according to their totals, link them by providing a non-empty group id here shared by every trace in the same group." + }, + "textinfo": { + "valType": "flaglist", + "role": "info", + "flags": [ + "label", + "text", + "value", + "percent" + ], + "extras": [ + "none" + ], + "editType": "calc", + "description": "Determines which trace information appear on the graph." + }, + "textposition": { + "valType": "enumerated", + "role": "info", + "values": [ + "inside", + "outside", + "auto", + "none" + ], + "dflt": "auto", + "arrayOk": true, + "editType": "calc", + "description": "Specifies the location of the `textinfo`." + }, + "textfont": { + "family": { "valType": "string", - "dflt": "", "role": "style", - "editType": "colorbars", - "description": "Sets a tick label prefix." + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "size": { + "valType": "number", "role": "style", - "editType": "colorbars", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + "min": 1, + "editType": "calc" }, - "ticksuffix": { + "color": { + "valType": "color", + "role": "style", + "editType": "style" + }, + "editType": "calc", + "description": "Sets the font used for `textinfo`.", + "role": "object" + }, + "insidetextfont": { + "family": { "valType": "string", - "dflt": "", "role": "style", - "editType": "colorbars", - "description": "Sets a tick label suffix." + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "size": { + "valType": "number", "role": "style", - "editType": "colorbars", - "description": "Same as `showtickprefix` but for tick suffixes." + "min": 1, + "editType": "calc" }, - "separatethousands": { - "valType": "boolean", - "dflt": false, + "color": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "If \"true\", even 4-digit integers are separated" + "editType": "style" + }, + "editType": "calc", + "description": "Sets the font used for `textinfo` lying inside the pie.", + "role": "object" + }, + "outsidetextfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", + "size": { + "valType": "number", "role": "style", - "editType": "colorbars", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + "min": 1, + "editType": "calc" }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "color": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + "editType": "style" }, - "title": { - "valType": "string", + "editType": "calc", + "description": "Sets the font used for `textinfo` lying outside the pie.", + "role": "object" + }, + "domain": { + "x": { + "valType": "info_array", "role": "info", - "description": "Sets the title of the color bar.", - "editType": "colorbars" - }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", - "role": "object" + "editType": "calc", + "items": [ + { + "valType": "number", + "min": 0, + "max": 1, + "editType": "calc" + }, + { + "valType": "number", + "min": 0, + "max": 1, + "editType": "calc" + } + ], + "dflt": [ + 0, + 1 + ], + "description": "Sets the horizontal domain of this pie trace (in plot fraction)." }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" + "y": { + "valType": "info_array", + "role": "info", + "editType": "calc", + "items": [ + { + "valType": "number", + "min": 0, + "max": 1, + "editType": "calc" + }, + { + "valType": "number", + "min": 0, + "max": 1, + "editType": "calc" + } ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" + "dflt": [ + 0, + 1 + ], + "description": "Sets the vertical domain of this pie trace (in plot fraction)." }, - "editType": "colorbars", - "role": "object", - "tickvalssrc": { - "valType": "string", + "editType": "calc", + "row": { + "valType": "integer", + "min": 0, + "dflt": 0, "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", - "editType": "none" + "editType": "calc", + "description": "If there is a layout grid, use the domain for this row in the grid for this pie trace ." }, - "ticktextsrc": { - "valType": "string", + "column": { + "valType": "integer", + "min": 0, + "dflt": 0, "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", - "editType": "none" - } + "editType": "calc", + "description": "If there is a layout grid, use the domain for this column in the grid for this pie trace ." + }, + "role": "object" }, - "xcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", + "hole": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 0, "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `x` date data." + "description": "Sets the fraction of the radius to cut out of the pie. Use this to make a donut chart." }, - "ycalendar": { + "sort": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not the sectors are reordered from largest to smallest." + }, + "direction": { "valType": "enumerated", "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" + "clockwise", + "counterclockwise" ], - "role": "info", + "role": "style", + "dflt": "counterclockwise", "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `y` date data." + "description": "Specifies the direction at which succeeding sectors follow one another." }, - "xaxis": { - "valType": "subplotid", - "role": "info", - "dflt": "x", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." + "rotation": { + "valType": "number", + "role": "style", + "min": -360, + "max": 360, + "dflt": 0, + "editType": "calc", + "description": "Instead of the first slice starting at 12 o'clock, rotate to some other angle." }, - "yaxis": { - "valType": "subplotid", - "role": "info", - "dflt": "y", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "pull": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 0, + "arrayOk": true, + "editType": "calc", + "description": "Sets the fraction of larger radius to pull the sectors out from the center. This can be a constant to pull all slices apart from each other equally or an array to highlight one or more slices." }, "idssrc": { "valType": "string", @@ -7885,33 +9601,63 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "xsrc": { + "labelssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for x .", + "description": "Sets the source reference on plot.ly for labels .", "editType": "none" }, - "ysrc": { + "valuessrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for y .", + "description": "Sets the source reference on plot.ly for values .", "editType": "none" }, - "zsrc": { + "textsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for z .", + "description": "Sets the source reference on plot.ly for text .", + "editType": "none" + }, + "hovertextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hovertext .", + "editType": "none" + }, + "textpositionsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for textposition .", + "editType": "none" + }, + "pullsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for pull .", + "editType": "none" + } + }, + "layoutAttributes": { + "hiddenlabels": { + "valType": "data_array", + "editType": "calc", + "role": "data" + }, + "hiddenlabelssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hiddenlabels .", "editType": "none" } } }, - "histogram2dcontour": { + "contour": { "meta": { - "hrName": "histogram_2d_contour", - "description": "The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a contour plot." + "description": "The data from which contour lines are computed is set in `z`. Data in `z` must be a {2D array} of numbers. Say that `z` has N rows and M columns, then by default, these N rows correspond to N y coordinates (set in `y` or auto-generated) and the M columns correspond to M x coordinates (set in `x` or auto-generated). By setting `transpose` to *true*, the above behavior is flipped." }, "attributes": { - "type": "histogram2dcontour", + "type": "contour", "visible": { "valType": "enumerated", "values": [ @@ -8107,175 +9853,122 @@ "editType": "calc", "role": "object" }, + "z": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the z data.", + "role": "data" + }, "x": { "valType": "data_array", "editType": "calc+clearAxisTypes", - "description": "Sets the sample data to be binned on the x axis.", + "description": "Sets the x coordinates.", + "impliedEdits": { + "xtype": "array" + }, "role": "data" }, + "x0": { + "valType": "any", + "dflt": 0, + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step.", + "impliedEdits": { + "xtype": "scaled" + } + }, + "dx": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the x coordinate step. See `x0` for more info.", + "impliedEdits": { + "xtype": "scaled" + } + }, "y": { "valType": "data_array", "editType": "calc+clearAxisTypes", - "description": "Sets the sample data to be binned on the y axis.", + "description": "Sets the y coordinates.", + "impliedEdits": { + "ytype": "array" + }, "role": "data" }, - "z": { + "y0": { + "valType": "any", + "dflt": 0, + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step.", + "impliedEdits": { + "ytype": "scaled" + } + }, + "dy": { + "valType": "number", + "dflt": 1, + "role": "info", + "editType": "calc", + "description": "Sets the y coordinate step. See `y0` for more info.", + "impliedEdits": { + "ytype": "scaled" + } + }, + "text": { "valType": "data_array", "editType": "calc", - "description": "Sets the aggregation data.", + "description": "Sets the text elements associated with each z value.", "role": "data" }, - "marker": { - "color": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the aggregation data.", - "role": "data" - }, + "transpose": { + "valType": "boolean", + "dflt": false, + "role": "info", "editType": "calc", - "role": "object", - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } + "description": "Transposes the z data." }, - "histnorm": { + "xtype": { "valType": "enumerated", "values": [ - "", - "percent", - "probability", - "density", - "probability density" + "array", + "scaled" ], - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Specifies the type of normalization used for this histogram trace. If **, the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If *percent* / *probability*, the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If *density*, the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1)." + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "If *array*, the heatmap's x coordinates are given by *x* (the default behavior when `x` is provided). If *scaled*, the heatmap's x coordinates are given by *x0* and *dx* (the default behavior when `x` is not provided)." }, - "histfunc": { + "ytype": { "valType": "enumerated", "values": [ - "count", - "sum", - "avg", - "min", - "max" + "array", + "scaled" ], - "role": "style", - "dflt": "count", - "editType": "calc", - "description": "Specifies the binning function used for this histogram trace. If *count*, the histogram values are computed by counting the number of values lying inside each bin. If *sum*, *avg*, *min*, *max*, the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively." - }, - "autobinx": { - "valType": "boolean", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the x axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in xbins." + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "If *array*, the heatmap's y coordinates are given by *y* (the default behavior when `y` is provided) If *scaled*, the heatmap's y coordinates are given by *y0* and *dy* (the default behavior when `y` is not provided)" }, - "nbinsx": { - "valType": "integer", - "min": 0, - "dflt": 0, + "zhoverformat": { + "valType": "string", + "dflt": "", "role": "style", - "editType": "calc", - "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." - }, - "xbins": { - "start": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobinx": false - }, - "description": "Sets the starting value for the x axis bins." - }, - "end": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobinx": false - }, - "description": "Sets the end value for the x axis bins." - }, - "size": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobinx": false - }, - "description": "Sets the step in-between value each x axis bin." - }, - "editType": "calc", - "impliedEdits": { - "autobinx": false, - "role": "object" - }, - "role": "object" + "editType": "none", + "description": "Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-format/blob/master/README.md#locale_format" }, - "autobiny": { + "connectgaps": { "valType": "boolean", - "dflt": null, - "role": "style", + "dflt": false, + "role": "info", "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the y axis bin attributes are picked by an algorithm. Note that this should be set to false if you want to manually set the number of bins using the attributes in ybins." + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in." }, - "nbinsy": { - "valType": "integer", - "min": 0, - "dflt": 0, + "fillcolor": { + "valType": "color", "role": "style", "editType": "calc", - "description": "Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data." - }, - "ybins": { - "start": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the starting value for the y axis bins." - }, - "end": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the end value for the y axis bins." - }, - "size": { - "valType": "any", - "dflt": null, - "role": "style", - "editType": "calc", - "impliedEdits": { - "^autobiny": false - }, - "description": "Sets the step in-between value each y axis bin." - }, - "editType": "calc", - "impliedEdits": { - "autobiny": false, - "role": "object" - }, - "role": "object" + "description": "Sets the fill color if `contours.type` is *constraint*. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." }, "autocontour": { "valType": "boolean", @@ -8472,13 +10165,6 @@ "editType": "plot", "role": "object" }, - "zhoverformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "none", - "description": "Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-format/blob/master/README.md#locale_format" - }, "zauto": { "valType": "boolean", "role": "info", @@ -8519,7 +10205,7 @@ "autocolorscale": { "valType": "boolean", "role": "style", - "dflt": true, + "dflt": false, "editType": "calc", "impliedEdits": {}, "description": "Determines whether or not the colorscale is picked using the sign of the input z values." @@ -9028,7 +10714,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -9048,6 +10734,12 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, + "zsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for z .", + "editType": "none" + }, "xsrc": { "valType": "string", "role": "info", @@ -9060,20 +10752,21 @@ "description": "Sets the source reference on plot.ly for y .", "editType": "none" }, - "zsrc": { + "textsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for z .", + "description": "Sets the source reference on plot.ly for text .", "editType": "none" } } }, - "pie": { + "scatterternary": { "meta": { - "description": "A data visualized by the sectors of the pie is set in `values`. The sector labels are set in `labels`. The sector colors are set in `marker.colors`" + "hrName": "scatter_ternary", + "description": "Provides similar functionality to the *scatter* type but on a ternary phase diagram. The data is provided by at least two arrays out of `a`, `b`, `c` triplets." }, "attributes": { - "type": "pie", + "type": "scatterternary", "visible": { "valType": "enumerated", "values": [ @@ -9143,10 +10836,10 @@ "valType": "flaglist", "role": "info", "flags": [ - "label", + "a", + "b", + "c", "text", - "value", - "percent", "name" ], "extras": [ @@ -9164,1540 +10857,2322 @@ "valType": "color", "role": "style", "arrayOk": true, - "editType": "none", - "description": "Sets the background color of the hover labels for this trace" - }, - "bordercolor": { - "valType": "color", + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" + }, + "bordercolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." + }, + "font": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "none", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "none", + "arrayOk": true + }, + "color": { + "valType": "color", + "role": "style", + "editType": "none", + "arrayOk": true + }, + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "namelength": { + "valType": "integer", + "min": -1, + "arrayOk": true, + "role": "style", + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." + }, + "editType": "calc", + "role": "object", + "bgcolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bgcolor .", + "editType": "none" + }, + "bordercolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bordercolor .", + "editType": "none" + }, + "namelengthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for namelength .", + "editType": "none" + } + }, + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { + "valType": "number", + "min": 0, + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, + "editType": "calc", + "role": "object" + }, + "a": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary.sum`.", + "role": "data" + }, + "b": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary.sum`.", + "role": "data" + }, + "c": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary.sum`.", + "role": "data" + }, + "sum": { + "valType": "number", + "role": "info", + "dflt": 0, + "min": 0, + "editType": "calc", + "description": "The number each triplet should sum to, if only two of `a`, `b`, and `c` are provided. This overrides `ternary.sum` to normalize this specific trace, but does not affect the values displayed on the axes. 0 (or missing) means to use ternary.sum" + }, + "mode": { + "valType": "flaglist", + "flags": [ + "lines", + "markers", + "text" + ], + "extras": [ + "none" + ], + "role": "info", + "editType": "calc", + "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*.", + "dflt": "markers" + }, + "text": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "calc", + "description": "Sets text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + }, + "hovertext": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "style", + "description": "Sets hover text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). To be seen, trace `hoverinfo` must contain a *text* flag." + }, + "line": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the line color." + }, + "width": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "style", + "description": "Sets the line width (in px)." + }, + "dash": { + "valType": "string", + "values": [ + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" + ], + "dflt": "solid", + "role": "style", + "editType": "style", + "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." + }, + "shape": { + "valType": "enumerated", + "values": [ + "linear", + "spline" + ], + "dflt": "linear", + "role": "style", + "editType": "plot", + "description": "Determines the line shape. With *spline* the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes." + }, + "smoothing": { + "valType": "number", + "min": 0, + "max": 1.3, + "dflt": 1, + "role": "style", + "editType": "plot", + "description": "Has an effect only if `shape` is set to *spline* Sets the amount of smoothing. *0* corresponds to no smoothing (equivalent to a *linear* shape)." + }, + "editType": "calc", + "role": "object" + }, + "connectgaps": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." + }, + "cliponaxis": { + "valType": "boolean", + "dflt": true, + "role": "info", + "editType": "plot", + "description": "Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + }, + "fill": { + "valType": "enumerated", + "values": [ + "none", + "toself", + "tonext" + ], + "dflt": "none", + "role": "style", + "editType": "calc", + "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. scatterternary has a subset of the options available to scatter. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. *tonext* fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like *toself* if there is no trace before it. *tonext* should not be used if one trace does not enclose the other." + }, + "fillcolor": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + }, + "marker": { + "symbol": { + "valType": "enumerated", + "values": [ + 0, + "circle", + 100, + "circle-open", + 200, + "circle-dot", + 300, + "circle-open-dot", + 1, + "square", + 101, + "square-open", + 201, + "square-dot", + 301, + "square-open-dot", + 2, + "diamond", + 102, + "diamond-open", + 202, + "diamond-dot", + 302, + "diamond-open-dot", + 3, + "cross", + 103, + "cross-open", + 203, + "cross-dot", + 303, + "cross-open-dot", + 4, + "x", + 104, + "x-open", + 204, + "x-dot", + 304, + "x-open-dot", + 5, + "triangle-up", + 105, + "triangle-up-open", + 205, + "triangle-up-dot", + 305, + "triangle-up-open-dot", + 6, + "triangle-down", + 106, + "triangle-down-open", + 206, + "triangle-down-dot", + 306, + "triangle-down-open-dot", + 7, + "triangle-left", + 107, + "triangle-left-open", + 207, + "triangle-left-dot", + 307, + "triangle-left-open-dot", + 8, + "triangle-right", + 108, + "triangle-right-open", + 208, + "triangle-right-dot", + 308, + "triangle-right-open-dot", + 9, + "triangle-ne", + 109, + "triangle-ne-open", + 209, + "triangle-ne-dot", + 309, + "triangle-ne-open-dot", + 10, + "triangle-se", + 110, + "triangle-se-open", + 210, + "triangle-se-dot", + 310, + "triangle-se-open-dot", + 11, + "triangle-sw", + 111, + "triangle-sw-open", + 211, + "triangle-sw-dot", + 311, + "triangle-sw-open-dot", + 12, + "triangle-nw", + 112, + "triangle-nw-open", + 212, + "triangle-nw-dot", + 312, + "triangle-nw-open-dot", + 13, + "pentagon", + 113, + "pentagon-open", + 213, + "pentagon-dot", + 313, + "pentagon-open-dot", + 14, + "hexagon", + 114, + "hexagon-open", + 214, + "hexagon-dot", + 314, + "hexagon-open-dot", + 15, + "hexagon2", + 115, + "hexagon2-open", + 215, + "hexagon2-dot", + 315, + "hexagon2-open-dot", + 16, + "octagon", + 116, + "octagon-open", + 216, + "octagon-dot", + 316, + "octagon-open-dot", + 17, + "star", + 117, + "star-open", + 217, + "star-dot", + 317, + "star-open-dot", + 18, + "hexagram", + 118, + "hexagram-open", + 218, + "hexagram-dot", + 318, + "hexagram-open-dot", + 19, + "star-triangle-up", + 119, + "star-triangle-up-open", + 219, + "star-triangle-up-dot", + 319, + "star-triangle-up-open-dot", + 20, + "star-triangle-down", + 120, + "star-triangle-down-open", + 220, + "star-triangle-down-dot", + 320, + "star-triangle-down-open-dot", + 21, + "star-square", + 121, + "star-square-open", + 221, + "star-square-dot", + 321, + "star-square-open-dot", + 22, + "star-diamond", + 122, + "star-diamond-open", + 222, + "star-diamond-dot", + 322, + "star-diamond-open-dot", + 23, + "diamond-tall", + 123, + "diamond-tall-open", + 223, + "diamond-tall-dot", + 323, + "diamond-tall-open-dot", + 24, + "diamond-wide", + 124, + "diamond-wide-open", + 224, + "diamond-wide-dot", + 324, + "diamond-wide-open-dot", + 25, + "hourglass", + 125, + "hourglass-open", + 26, + "bowtie", + 126, + "bowtie-open", + 27, + "circle-cross", + 127, + "circle-cross-open", + 28, + "circle-x", + 128, + "circle-x-open", + 29, + "square-cross", + 129, + "square-cross-open", + 30, + "square-x", + 130, + "square-x-open", + 31, + "diamond-cross", + 131, + "diamond-cross-open", + 32, + "diamond-x", + 132, + "diamond-x-open", + 33, + "cross-thin", + 133, + "cross-thin-open", + 34, + "x-thin", + 134, + "x-thin-open", + 35, + "asterisk", + 135, + "asterisk-open", + 36, + "hash", + 136, + "hash-open", + 236, + "hash-dot", + 336, + "hash-open-dot", + 37, + "y-up", + 137, + "y-up-open", + 38, + "y-down", + 138, + "y-down-open", + 39, + "y-left", + 139, + "y-left-open", + 40, + "y-right", + 140, + "y-right-open", + 41, + "line-ew", + 141, + "line-ew-open", + 42, + "line-ns", + 142, + "line-ns-open", + 43, + "line-ne", + 143, + "line-ne-open", + 44, + "line-nw", + 144, + "line-nw-open" + ], + "dflt": "circle", + "arrayOk": true, "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the border color of the hover labels for this trace." - }, - "font": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "none", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "none", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "none", - "arrayOk": true - }, - "editType": "none", - "description": "Sets the font used in hover labels.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } + "editType": "style", + "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." }, - "namelength": { - "valType": "integer", - "min": -1, + "opacity": { + "valType": "number", + "min": 0, + "max": 1, "arrayOk": true, "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." + "editType": "style", + "description": "Sets the marker opacity." }, - "editType": "calc", - "role": "object", - "bgcolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", - "editType": "none" + "maxdisplayed": { + "valType": "number", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "plot", + "description": "Sets a maximum number of points to be drawn on the graph. *0* corresponds to no limit." }, - "bordercolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", - "editType": "none" + "size": { + "valType": "number", + "min": 0, + "dflt": 6, + "arrayOk": true, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the marker size (in px)." }, - "namelengthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", - "editType": "none" - } - }, - "stream": { - "token": { - "valType": "string", - "noBlank": true, - "strict": true, - "role": "info", + "sizeref": { + "valType": "number", + "dflt": 1, + "role": "style", "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." }, - "maxpoints": { + "sizemin": { "valType": "number", "min": 0, - "max": 10000, - "dflt": 500, - "role": "info", + "dflt": 0, + "role": "style", "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." }, - "editType": "calc", - "role": "object" - }, - "labels": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the sector labels. If `labels` entries are duplicated, we sum associated `values` or simply count occurrences if `values` is not provided. For other array attributes (including color) we use the first non-empty entry among all occurrences of the label.", - "role": "data" - }, - "label0": { - "valType": "number", - "role": "info", - "dflt": 0, - "editType": "calc", - "description": "Alternate to `labels`. Builds a numeric set of labels. Use with `dlabel` where `label0` is the starting label and `dlabel` the step." - }, - "dlabel": { - "valType": "number", - "role": "info", - "dflt": 1, - "editType": "calc", - "description": "Sets the label step. See `label0` for more info." - }, - "values": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the values of the sectors of this pie chart. If omitted, we count occurrences of each label.", - "role": "data" - }, - "marker": { - "colors": { - "valType": "data_array", + "sizemode": { + "valType": "enumerated", + "values": [ + "diameter", + "area" + ], + "dflt": "diameter", + "role": "info", "editType": "calc", - "description": "Sets the color of each sector of this pie chart. If not specified, the default trace color set is used to pick the sector colors.", - "role": "data" + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." }, "line": { + "width": { + "valType": "number", + "min": 0, + "arrayOk": true, + "role": "style", + "editType": "style", + "description": "Sets the width (in px) of the lines bounding the marker points." + }, + "editType": "calc", "color": { "valType": "color", - "role": "style", - "dflt": "#444", "arrayOk": true, + "role": "style", "editType": "style", - "description": "Sets the color of the line enclosing each sector." + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, - "width": { + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + }, + "cmin": { "valType": "number", + "role": "info", + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", "role": "style", - "min": 0, - "dflt": 0, - "arrayOk": true, - "editType": "style", - "description": "Sets the width (in px) of the line enclosing each sector." + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." }, - "editType": "calc", "role": "object", - "colorsrc": { + "widthsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for width .", "editType": "none" }, - "widthsrc": { + "colorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for width .", + "description": "Sets the source reference on plot.ly for color .", "editType": "none" } }, - "editType": "calc", - "role": "object", - "colorssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for colors .", - "editType": "none" - } - }, - "text": { - "valType": "data_array", - "editType": "calc", - "description": "Sets text elements associated with each sector. If trace `textinfo` contains a *text* flag, these elements will seen on the chart. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels.", - "role": "data" - }, - "hovertext": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "style", - "description": "Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a *text* flag." - }, - "scalegroup": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "calc", - "description": "If there are multiple pies that should be sized according to their totals, link them by providing a non-empty group id here shared by every trace in the same group." - }, - "textinfo": { - "valType": "flaglist", - "role": "info", - "flags": [ - "label", - "text", - "value", - "percent" - ], - "extras": [ - "none" - ], - "editType": "calc", - "description": "Determines which trace information appear on the graph." - }, - "textposition": { - "valType": "enumerated", - "role": "info", - "values": [ - "inside", - "outside", - "auto", - "none" - ], - "dflt": "auto", - "arrayOk": true, - "editType": "calc", - "description": "Specifies the location of the `textinfo`." - }, - "textfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style" - }, - "editType": "calc", - "description": "Sets the font used for `textinfo`.", - "role": "object" - }, - "insidetextfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc" + "gradient": { + "type": { + "valType": "enumerated", + "values": [ + "radial", + "horizontal", + "vertical", + "none" + ], + "arrayOk": true, + "dflt": "none", + "role": "style", + "editType": "calc", + "description": "Sets the type of gradient used to fill the markers" + }, + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical." + }, + "editType": "calc", + "role": "object", + "typesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for type .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } }, + "editType": "calc", "color": { "valType": "color", + "arrayOk": true, "role": "style", - "editType": "style" + "editType": "style", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, - "editType": "calc", - "description": "Sets the font used for `textinfo` lying inside the pie.", - "role": "object" - }, - "outsidetextfont": { - "family": { - "valType": "string", + "colorscale": { + "valType": "colorscale", "role": "style", - "noBlank": true, - "strict": true, "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style" + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" }, - "editType": "calc", - "description": "Sets the font used for `textinfo` lying outside the pie.", - "role": "object" - }, - "domain": { - "x": { - "valType": "info_array", + "cauto": { + "valType": "boolean", "role": "info", + "dflt": true, "editType": "calc", - "items": [ - { - "valType": "number", - "min": 0, - "max": 1, - "editType": "calc" - }, - { - "valType": "number", - "min": 0, - "max": 1, - "editType": "calc" - } - ], - "dflt": [ - 0, - 1 - ], - "description": "Sets the horizontal domain of this pie trace (in plot fraction)." + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." }, - "y": { - "valType": "info_array", + "cmax": { + "valType": "number", "role": "info", - "editType": "calc", - "items": [ - { - "valType": "number", - "min": 0, - "max": 1, - "editType": "calc" - }, - { - "valType": "number", - "min": 0, - "max": 1, - "editType": "calc" - } - ], - "dflt": [ - 0, - 1 - ], - "description": "Sets the vertical domain of this pie trace (in plot fraction)." + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." }, - "editType": "calc", - "row": { - "valType": "integer", - "min": 0, - "dflt": 0, + "cmin": { + "valType": "number", "role": "info", - "editType": "calc", - "description": "If there is a layout grid, use the domain for this row in the grid for this pie trace ." + "dflt": null, + "editType": "plot", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." }, - "column": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, "editType": "calc", - "description": "If there is a layout grid, use the domain for this column in the grid for this pie trace ." + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." }, - "role": "object" - }, - "hole": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0, - "editType": "calc", - "description": "Sets the fraction of the radius to cut out of the pie. Use this to make a donut chart." - }, - "sort": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "description": "Determines whether or not the sectors are reordered from largest to smallest." - }, - "direction": { - "valType": "enumerated", - "values": [ - "clockwise", - "counterclockwise" - ], - "role": "style", - "dflt": "counterclockwise", - "editType": "calc", - "description": "Specifies the direction at which succeeding sectors follow one another." - }, - "rotation": { - "valType": "number", - "role": "style", - "min": -360, - "max": 360, - "dflt": 0, - "editType": "calc", - "description": "Instead of the first slice starting at 12 o'clock, rotate to some other angle." - }, - "pull": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0, - "arrayOk": true, - "editType": "calc", - "description": "Sets the fraction of larger radius to pull the sectors out from the center. This can be a constant to pull all slices apart from each other equally or an array to highlight one or more slices." - }, - "idssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ids .", - "editType": "none" - }, - "customdatasrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for customdata .", - "editType": "none" - }, - "hoverinfosrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hoverinfo .", - "editType": "none" - }, - "labelssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for labels .", - "editType": "none" - }, - "valuessrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for values .", - "editType": "none" - }, - "textsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for text .", - "editType": "none" - }, - "hovertextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hovertext .", - "editType": "none" - }, - "textpositionsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for textposition .", - "editType": "none" - }, - "pullsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for pull .", - "editType": "none" - } - }, - "layoutAttributes": { - "hiddenlabels": { - "valType": "data_array", - "editType": "calc", - "role": "data" - }, - "hiddenlabelssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hiddenlabels .", - "editType": "none" - } - } - }, - "contour": { - "meta": { - "description": "The data from which contour lines are computed is set in `z`. Data in `z` must be a {2D array} of numbers. Say that `z` has N rows and M columns, then by default, these N rows correspond to N y coordinates (set in `y` or auto-generated) and the M columns correspond to M x coordinates (set in `x` or auto-generated). By setting `transpose` to *true*, the above behavior is flipped." - }, - "attributes": { - "type": "contour", - "visible": { - "valType": "enumerated", - "values": [ - true, - false, - "legendonly" - ], - "role": "info", - "dflt": true, - "editType": "calc", - "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this trace is shown in the legend." - }, - "legendgroup": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "style", - "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." - }, - "opacity": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "editType": "style", - "description": "Sets the opacity of the trace." - }, - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the trace name. The trace name appear as the legend item and on hover." - }, - "uid": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "calc" - }, - "ids": { - "valType": "data_array", - "editType": "calc", - "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", - "role": "data" - }, - "customdata": { - "valType": "data_array", - "editType": "calc", - "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", - "role": "data" - }, - "selectedpoints": { - "valType": "any", - "role": "info", - "editType": "calc", - "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." - }, - "hoverinfo": { - "valType": "flaglist", - "role": "info", - "flags": [ - "x", - "y", - "z", - "text", - "name" - ], - "extras": [ - "all", - "none", - "skip" - ], - "arrayOk": true, - "dflt": "all", - "editType": "none", - "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." - }, - "hoverlabel": { - "bgcolor": { - "valType": "color", + "reversescale": { + "valType": "boolean", "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the background color of the hover labels for this trace" + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." }, - "bordercolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the border color of the hover labels for this trace." + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." }, - "font": { - "family": { - "valType": "string", + "colorbar": { + "thicknessmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "colorbars" + }, + "thickness": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "colorbars" + }, + "lenmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "info", + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "colorbars" + }, + "len": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "colorbars" + }, + "x": { + "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", + "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", + "editType": "colorbars" + }, + "xpad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "colorbars" + }, + "y": { + "valType": "number", + "role": "style", + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], + "role": "style", + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "colorbars" + }, + "ypad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "colorbars" + }, + "outlinecolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "outlinewidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the width (in px) of the axis line." + }, + "bordercolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "borderwidth": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "colorbars" + }, + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" + }, + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], + "role": "info", + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + }, + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, "role": "style", - "noBlank": true, - "strict": true, - "editType": "none", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." }, - "size": { + "tick0": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" + }, + "ticktext": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" + }, + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" + }, + "ticklen": { "valType": "number", + "min": 0, + "dflt": 5, "role": "style", - "min": 1, - "editType": "none", - "arrayOk": true + "editType": "colorbars", + "description": "Sets the tick length (in px)." }, - "color": { + "tickwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick width (in px)." + }, + "tickcolor": { "valType": "color", + "dflt": "#444", "role": "style", - "editType": "none", - "arrayOk": true + "editType": "colorbars", + "description": "Sets the tick color." }, - "editType": "none", - "description": "Sets the font used in hover labels.", - "role": "object", - "familysrc": { + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + }, + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label prefix." + }, + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + }, + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." + }, + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." + }, + "separatethousands": { + "valType": "boolean", + "dflt": false, + "role": "style", + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" + }, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + }, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + }, + "title": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" + "description": "Sets the title of the color bar.", + "editType": "colorbars" }, - "sizesrc": { + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" + }, + "editType": "colorbars", + "role": "object", + "tickvalssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for size .", + "description": "Sets the source reference on plot.ly for tickvals .", "editType": "none" }, - "colorsrc": { + "ticktextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for ticktext .", "editType": "none" } }, - "namelength": { - "valType": "integer", - "min": -1, - "arrayOk": true, - "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." - }, - "editType": "calc", "role": "object", - "bgcolorsrc": { + "symbolsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", + "description": "Sets the source reference on plot.ly for symbol .", "editType": "none" }, - "bordercolorsrc": { + "opacitysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", + "description": "Sets the source reference on plot.ly for opacity .", "editType": "none" }, - "namelengthsrc": { + "sizesrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", "editType": "none" } }, - "stream": { - "token": { + "textfont": { + "family": { "valType": "string", + "role": "style", "noBlank": true, "strict": true, - "role": "info", "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, - "maxpoints": { + "size": { "valType": "number", - "min": 0, - "max": 10000, - "dflt": 500, - "role": "info", + "role": "style", + "min": 1, "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + "arrayOk": true + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "arrayOk": true }, "editType": "calc", - "role": "object" + "description": "Sets the text font.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } }, - "z": { - "valType": "data_array", + "textposition": { + "valType": "enumerated", + "values": [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right" + ], + "dflt": "middle center", + "arrayOk": true, + "role": "style", "editType": "calc", - "description": "Sets the z data.", - "role": "data" + "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinates.", - "impliedEdits": { - "xtype": "array" + "selected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of selected points." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of selected points." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "style", + "description": "Sets the marker size of selected points." + }, + "editType": "style", + "role": "object" }, - "role": "data" + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the text font color of selected points." + }, + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" }, - "x0": { - "valType": "any", - "dflt": 0, + "unselected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of unselected points, applied only when a selection exists." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "style", + "description": "Sets the marker size of unselected points, applied only when a selection exists." + }, + "editType": "style", + "role": "object" + }, + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the text font color of unselected points, applied only when a selection exists." + }, + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" + }, + "hoveron": { + "valType": "flaglist", + "flags": [ + "points", + "fills" + ], "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step.", - "impliedEdits": { - "xtype": "scaled" - } + "editType": "style", + "description": "Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is *toself* or *tonext* and there are no markers or text, then the default is *fills*, otherwise it is *points*." }, - "dx": { - "valType": "number", - "dflt": 1, + "subplot": { + "valType": "subplotid", "role": "info", + "dflt": "ternary", "editType": "calc", - "description": "Sets the x coordinate step. See `x0` for more info.", - "impliedEdits": { - "xtype": "scaled" - } + "description": "Sets a reference between this trace's data coordinates and a ternary subplot. If *ternary* (the default value), the data refer to `layout.ternary`. If *ternary2*, the data refer to `layout.ternary2`, and so on." }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinates.", - "impliedEdits": { - "ytype": "array" - }, - "role": "data" + "idssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ids .", + "editType": "none" + }, + "customdatasrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for customdata .", + "editType": "none" + }, + "hoverinfosrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hoverinfo .", + "editType": "none" }, - "y0": { - "valType": "any", - "dflt": 0, + "asrc": { + "valType": "string", "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step.", - "impliedEdits": { - "ytype": "scaled" - } + "description": "Sets the source reference on plot.ly for a .", + "editType": "none" }, - "dy": { - "valType": "number", - "dflt": 1, + "bsrc": { + "valType": "string", "role": "info", - "editType": "calc", - "description": "Sets the y coordinate step. See `y0` for more info.", - "impliedEdits": { - "ytype": "scaled" - } + "description": "Sets the source reference on plot.ly for b .", + "editType": "none" }, - "text": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the text elements associated with each z value.", - "role": "data" + "csrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for c .", + "editType": "none" }, - "transpose": { - "valType": "boolean", - "dflt": false, + "textsrc": { + "valType": "string", "role": "info", - "editType": "calc", - "description": "Transposes the z data." + "description": "Sets the source reference on plot.ly for text .", + "editType": "none" }, - "xtype": { - "valType": "enumerated", - "values": [ - "array", - "scaled" - ], + "hovertextsrc": { + "valType": "string", "role": "info", - "editType": "calc+clearAxisTypes", - "description": "If *array*, the heatmap's x coordinates are given by *x* (the default behavior when `x` is provided). If *scaled*, the heatmap's x coordinates are given by *x0* and *dx* (the default behavior when `x` is not provided)." + "description": "Sets the source reference on plot.ly for hovertext .", + "editType": "none" }, - "ytype": { + "textpositionsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for textposition .", + "editType": "none" + } + } + }, + "violin": { + "meta": { + "description": "In vertical (horizontal) violin plots, statistics are computed using `y` (`x`) values. By supplying an `x` (`y`) array, one violin per distinct x (y) value is drawn If no `x` (`y`) {array} is provided, a single violin is drawn. That violin position is then positioned with with `name` or with `x0` (`y0`) if provided." + }, + "attributes": { + "type": "violin", + "visible": { "valType": "enumerated", "values": [ - "array", - "scaled" + true, + false, + "legendonly" ], "role": "info", - "editType": "calc+clearAxisTypes", - "description": "If *array*, the heatmap's y coordinates are given by *y* (the default behavior when `y` is provided) If *scaled*, the heatmap's y coordinates are given by *y0* and *dy* (the default behavior when `y` is not provided)" + "dflt": true, + "editType": "calc", + "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." }, - "zhoverformat": { + "showlegend": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "style", + "description": "Determines whether or not an item corresponding to this trace is shown in the legend." + }, + "legendgroup": { "valType": "string", + "role": "info", "dflt": "", + "editType": "style", + "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." + }, + "opacity": { + "valType": "number", "role": "style", - "editType": "none", - "description": "Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-format/blob/master/README.md#locale_format" + "min": 0, + "max": 1, + "dflt": 1, + "editType": "style", + "description": "Sets the opacity of the trace." }, - "connectgaps": { - "valType": "boolean", - "dflt": false, + "name": { + "valType": "string", "role": "info", - "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in." + "editType": "calc+clearAxisTypes", + "description": "Sets the trace name. The trace name appear as the legend item and on hover. For box traces, the name will also be used for the position coordinate, if `x` and `x0` (`y` and `y0` if horizontal) are missing and the position axis is categorical" }, - "fillcolor": { - "valType": "color", - "role": "style", + "uid": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "calc" + }, + "ids": { + "valType": "data_array", "editType": "calc", - "description": "Sets the fill color if `contours.type` is *constraint*. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", + "role": "data" }, - "autocontour": { - "valType": "boolean", - "dflt": true, - "role": "style", + "customdata": { + "valType": "data_array", "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the contour level attributes are picked by an algorithm. If *true*, the number of contour levels can be set in `ncontours`. If *false*, set the contour level attributes in `contours`." + "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", + "role": "data" }, - "ncontours": { - "valType": "integer", - "dflt": 15, - "min": 1, - "role": "style", + "selectedpoints": { + "valType": "any", + "role": "info", "editType": "calc", - "description": "Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is *true* or if `contours.size` is missing." + "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." }, - "contours": { - "type": { - "valType": "enumerated", - "values": [ - "levels", - "constraint" - ], - "dflt": "levels", - "role": "info", - "editType": "calc", - "description": "If `levels`, the data is represented as a contour plot with multiple levels displayed. If `constraint`, the data is represented as constraints with the invalid region shaded as specified by the `operation` and `value` parameters." - }, - "start": { - "valType": "number", - "dflt": null, - "role": "style", - "editType": "plot", - "impliedEdits": { - "^autocontour": false - }, - "description": "Sets the starting contour level value. Must be less than `contours.end`" - }, - "end": { - "valType": "number", - "dflt": null, - "role": "style", - "editType": "plot", - "impliedEdits": { - "^autocontour": false - }, - "description": "Sets the end contour level value. Must be more than `contours.start`" - }, - "size": { - "valType": "number", - "dflt": null, - "min": 0, - "role": "style", - "editType": "plot", - "impliedEdits": { - "^autocontour": false - }, - "description": "Sets the step between each contour level. Must be positive." - }, - "coloring": { - "valType": "enumerated", - "values": [ - "fill", - "heatmap", - "lines", - "none" - ], - "dflt": "fill", - "role": "style", - "editType": "calc", - "description": "Determines the coloring method showing the contour values. If *fill*, coloring is done evenly between each contour level If *heatmap*, a heatmap gradient coloring is applied between each contour level. If *lines*, coloring is done on the contour lines. If *none*, no coloring is applied on this trace." - }, - "showlines": { - "valType": "boolean", - "dflt": true, + "hoverinfo": { + "valType": "flaglist", + "role": "info", + "flags": [ + "x", + "y", + "z", + "text", + "name" + ], + "extras": [ + "all", + "none", + "skip" + ], + "arrayOk": true, + "dflt": "all", + "editType": "none", + "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." + }, + "hoverlabel": { + "bgcolor": { + "valType": "color", "role": "style", - "editType": "plot", - "description": "Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to *fill*." + "arrayOk": true, + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" }, - "showlabels": { - "valType": "boolean", - "dflt": false, + "bordercolor": { + "valType": "color", "role": "style", - "editType": "plot", - "description": "Determines whether to label the contour lines with their values." + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." }, - "labelfont": { + "font": { "family": { "valType": "string", "role": "style", "noBlank": true, "strict": true, - "editType": "plot", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*." + "editType": "none", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, "size": { "valType": "number", "role": "style", "min": 1, - "editType": "plot" + "editType": "none", + "arrayOk": true }, "color": { "valType": "color", "role": "style", - "editType": "style" + "editType": "none", + "arrayOk": true }, - "editType": "plot", - "description": "Sets the font used for labeling the contour levels. The default color comes from the lines, if shown. The default family and size come from `layout.font`.", - "role": "object" - }, - "labelformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "plot", - "description": "Sets the contour label formatting rule using d3 formatting mini-language which is very similar to Python, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format." - }, - "operation": { - "valType": "enumerated", - "values": [ - "=", - "<", - ">=", - ">", - "<=", - "[]", - "()", - "[)", - "(]", - "][", - ")(", - "](", - ")[" - ], - "role": "info", - "dflt": "=", - "editType": "calc", - "description": "Sets the constraint operation. *=* keeps regions equal to `value` *<* and *<=* keep regions less than `value` *>* and *>=* keep regions greater than `value` *[]*, *()*, *[)*, and *(]* keep regions inside `value[0]` to `value[1]` *][*, *)(*, *](*, *)[* keep regions outside `value[0]` to value[1]` Open vs. closed intervals make no difference to constraint display, but all versions are allowed for consistency with filter transforms." - }, - "value": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc", - "description": "Sets the value or values of the constraint boundary. When `operation` is set to one of the comparison values (=,<,>=,>,<=) *value* is expected to be a number. When `operation` is set to one of the interval values ([],(),[),(],][,)(,](,)[) *value* is expected to be an array of two numbers where the first is the lower bound and the second is the upper bound." - }, - "editType": "calc", - "impliedEdits": { - "autocontour": false, - "role": "object" - }, - "role": "object" - }, - "line": { - "color": { - "valType": "color", - "role": "style", - "editType": "style+colorbars", - "description": "Sets the color of the contour level. Has no effect if `contours.coloring` is set to *lines*." - }, - "width": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "style+colorbars", - "description": "Sets the line width (in px)." - }, - "dash": { - "valType": "string", - "values": [ - "solid", - "dot", - "dash", - "longdash", - "dashdot", - "longdashdot" - ], - "dflt": "solid", - "role": "style", - "editType": "style", - "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." - }, - "smoothing": { - "valType": "number", - "min": 0, - "max": 1.3, - "dflt": 1, - "role": "style", - "editType": "plot", - "description": "Sets the amount of smoothing for the contour lines, where *0* corresponds to no smoothing." - }, - "editType": "plot", - "role": "object" - }, - "zauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Determines the whether or not the color domain is computed with respect to the input data." - }, - "zmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the lower bound of color domain." - }, - "zmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the upper bound of color domain." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the colorscale is picked using the sign of the input z values." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Reverses the colorscale." - }, - "showscale": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "description": "Determines whether or not a colorbar is displayed for this trace." - }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "colorbars" - }, - "thickness": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "colorbars" - }, - "lenmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "colorbars" - }, - "len": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "colorbars" - }, - "x": { - "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, - "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "colorbars" - }, - "xanchor": { - "valType": "enumerated", - "values": [ - "left", - "center", - "right" - ], - "dflt": "left", - "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "colorbars" - }, - "xpad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "colorbars" - }, - "y": { - "valType": "number", - "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "colorbars" - }, - "yanchor": { - "valType": "enumerated", - "values": [ - "top", - "middle", - "bottom" - ], - "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "colorbars" + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } }, - "ypad": { - "valType": "number", + "namelength": { + "valType": "integer", + "min": -1, + "arrayOk": true, "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "colorbars" + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "editType": "calc", + "role": "object", + "bgcolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bgcolor .", + "editType": "none" }, - "outlinewidth": { + "bordercolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for bordercolor .", + "editType": "none" + }, + "namelengthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for namelength .", + "editType": "none" + } + }, + "stream": { + "token": { + "valType": "string", + "noBlank": true, + "strict": true, + "role": "info", + "editType": "calc", + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + }, + "maxpoints": { "valType": "number", "min": 0, - "dflt": 1, - "role": "style", - "editType": "colorbars", - "description": "Sets the width (in px) of the axis line." + "max": 10000, + "dflt": 500, + "role": "info", + "editType": "calc", + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." }, - "bordercolor": { + "editType": "calc", + "role": "object" + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the y sample data or coordinates. See overview for more info.", + "role": "data" + }, + "x": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the x sample data or coordinates. See overview for more info.", + "role": "data" + }, + "x0": { + "valType": "any", + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Sets the x coordinate of the box. See overview for more info." + }, + "y0": { + "valType": "any", + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinate of the box. See overview for more info." + }, + "orientation": { + "valType": "enumerated", + "values": [ + "v", + "h" + ], + "role": "style", + "editType": "calc+clearAxisTypes", + "description": "Sets the orientation of the violin(s). If *v* (*h*), the distribution is visualized along the vertical (horizontal)." + }, + "bandwidth": { + "valType": "number", + "min": 0, + "role": "info", + "editType": "calc", + "description": "Sets the bandwidth used to compute the kernel density estimate. By default, the bandwidth is determined by Silverman's rule of thumb." + }, + "scalegroup": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "calc", + "description": "If there are multiple violins that should be sized according to to some metric (see `scalemode`), link them by providing a non-empty group id here shared by every trace in the same group." + }, + "scalemode": { + "valType": "enumerated", + "values": [ + "width", + "count" + ], + "dflt": "width", + "role": "info", + "editType": "calc", + "description": "Sets the metric by which the width of each violin is determined.*width* means each violin has the same (max) width*count* means the violins are scaled by the number of sample points makingup each violin." + }, + "spanmode": { + "valType": "enumerated", + "values": [ + "soft", + "hard", + "manual" + ], + "dflt": "soft", + "role": "info", + "editType": "calc", + "description": "Sets the method by which the span in data space where the density function will be computed. *soft* means the span goes from the sample's minimum value minus two bandwidths to the sample's maximum value plus two bandwidths. *hard* means the span goes from the sample's minimum to its maximum value. For custom span settings, use mode *manual* and fill in the `span` attribute." + }, + "span": { + "valType": "info_array", + "items": [ + { + "valType": "any", + "editType": "calc" + }, + { + "valType": "any", + "editType": "calc" + } + ], + "role": "info", + "editType": "calc", + "description": "Sets the span in data space for which the density function will be computed. Has an effect only when `spanmode` is set to *manual*." + }, + "line": { + "color": { "valType": "color", - "dflt": "#444", "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "editType": "style", + "description": "Sets the color of line bounding the violin(s)." }, - "borderwidth": { + "width": { "valType": "number", "role": "style", "min": 0, - "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "colorbars" + "dflt": 2, + "editType": "style", + "description": "Sets the width (in px) of line bounding the violin(s)." }, - "bgcolor": { + "editType": "plot", + "role": "object" + }, + "fillcolor": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + }, + "points": { + "valType": "enumerated", + "values": [ + "all", + "outliers", + "suspectedoutliers", + false + ], + "dflt": "outliers", + "role": "style", + "editType": "calcIfAutorange", + "description": "If *outliers*, only the sample points lying outside the whiskers are shown If *suspectedoutliers*, the outlier points are shown and points either less than 4*Q1-3*Q3 or greater than 4*Q3-3*Q1 are highlighted (see `outliercolor`) If *all*, all sample points are shown If *false*, only the violins are shown with no sample points" + }, + "jitter": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the amount of jitter in the sample points drawn. If *0*, the sample points align along the distribution axis. If *1*, the sample points are drawn in a random jitter of width equal to the width of the violins." + }, + "pointpos": { + "valType": "number", + "min": -2, + "max": 2, + "role": "style", + "editType": "calcIfAutorange", + "description": "Sets the position of the sample points in relation to the violins. If *0*, the sample points are places over the center of the violins. Positive (negative) values correspond to positions to the right (left) for vertical violins and above (below) for horizontal violins." + }, + "marker": { + "outliercolor": { "valType": "color", + "dflt": "rgba(0, 0, 0, 0)", "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "colorbars" - }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], - "role": "info", - "editType": "colorbars", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." - }, - "nticks": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "colorbars", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" + "editType": "style", + "description": "Sets the color of the outlier sample points." }, - "ticks": { + "symbol": { "valType": "enumerated", "values": [ - "outside", - "inside", - "" + 0, + "circle", + 100, + "circle-open", + 200, + "circle-dot", + 300, + "circle-open-dot", + 1, + "square", + 101, + "square-open", + 201, + "square-dot", + 301, + "square-open-dot", + 2, + "diamond", + 102, + "diamond-open", + 202, + "diamond-dot", + 302, + "diamond-open-dot", + 3, + "cross", + 103, + "cross-open", + 203, + "cross-dot", + 303, + "cross-open-dot", + 4, + "x", + 104, + "x-open", + 204, + "x-dot", + 304, + "x-open-dot", + 5, + "triangle-up", + 105, + "triangle-up-open", + 205, + "triangle-up-dot", + 305, + "triangle-up-open-dot", + 6, + "triangle-down", + 106, + "triangle-down-open", + 206, + "triangle-down-dot", + 306, + "triangle-down-open-dot", + 7, + "triangle-left", + 107, + "triangle-left-open", + 207, + "triangle-left-dot", + 307, + "triangle-left-open-dot", + 8, + "triangle-right", + 108, + "triangle-right-open", + 208, + "triangle-right-dot", + 308, + "triangle-right-open-dot", + 9, + "triangle-ne", + 109, + "triangle-ne-open", + 209, + "triangle-ne-dot", + 309, + "triangle-ne-open-dot", + 10, + "triangle-se", + 110, + "triangle-se-open", + 210, + "triangle-se-dot", + 310, + "triangle-se-open-dot", + 11, + "triangle-sw", + 111, + "triangle-sw-open", + 211, + "triangle-sw-dot", + 311, + "triangle-sw-open-dot", + 12, + "triangle-nw", + 112, + "triangle-nw-open", + 212, + "triangle-nw-dot", + 312, + "triangle-nw-open-dot", + 13, + "pentagon", + 113, + "pentagon-open", + 213, + "pentagon-dot", + 313, + "pentagon-open-dot", + 14, + "hexagon", + 114, + "hexagon-open", + 214, + "hexagon-dot", + 314, + "hexagon-open-dot", + 15, + "hexagon2", + 115, + "hexagon2-open", + 215, + "hexagon2-dot", + 315, + "hexagon2-open-dot", + 16, + "octagon", + 116, + "octagon-open", + 216, + "octagon-dot", + 316, + "octagon-open-dot", + 17, + "star", + 117, + "star-open", + 217, + "star-dot", + 317, + "star-open-dot", + 18, + "hexagram", + 118, + "hexagram-open", + 218, + "hexagram-dot", + 318, + "hexagram-open-dot", + 19, + "star-triangle-up", + 119, + "star-triangle-up-open", + 219, + "star-triangle-up-dot", + 319, + "star-triangle-up-open-dot", + 20, + "star-triangle-down", + 120, + "star-triangle-down-open", + 220, + "star-triangle-down-dot", + 320, + "star-triangle-down-open-dot", + 21, + "star-square", + 121, + "star-square-open", + 221, + "star-square-dot", + 321, + "star-square-open-dot", + 22, + "star-diamond", + 122, + "star-diamond-open", + 222, + "star-diamond-dot", + 322, + "star-diamond-open-dot", + 23, + "diamond-tall", + 123, + "diamond-tall-open", + 223, + "diamond-tall-dot", + 323, + "diamond-tall-open-dot", + 24, + "diamond-wide", + 124, + "diamond-wide-open", + 224, + "diamond-wide-dot", + 324, + "diamond-wide-open-dot", + 25, + "hourglass", + 125, + "hourglass-open", + 26, + "bowtie", + 126, + "bowtie-open", + 27, + "circle-cross", + 127, + "circle-cross-open", + 28, + "circle-x", + 128, + "circle-x-open", + 29, + "square-cross", + 129, + "square-cross-open", + 30, + "square-x", + 130, + "square-x-open", + 31, + "diamond-cross", + 131, + "diamond-cross-open", + 32, + "diamond-x", + 132, + "diamond-x-open", + 33, + "cross-thin", + 133, + "cross-thin-open", + 34, + "x-thin", + 134, + "x-thin-open", + 35, + "asterisk", + 135, + "asterisk-open", + 36, + "hash", + 136, + "hash-open", + 236, + "hash-dot", + 336, + "hash-open-dot", + 37, + "y-up", + 137, + "y-up-open", + 38, + "y-down", + 138, + "y-down-open", + 39, + "y-left", + 139, + "y-left-open", + 40, + "y-right", + 140, + "y-right-open", + 41, + "line-ew", + 141, + "line-ew-open", + 42, + "line-ns", + 142, + "line-ns-open", + 43, + "line-ne", + 143, + "line-ne-open", + 44, + "line-nw", + 144, + "line-nw-open" ], + "dflt": "circle", + "arrayOk": false, "role": "style", - "editType": "colorbars", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" + "editType": "plot", + "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." }, - "ticklen": { + "opacity": { "valType": "number", "min": 0, - "dflt": 5, + "max": 1, + "arrayOk": false, "role": "style", - "editType": "colorbars", - "description": "Sets the tick length (in px)." + "editType": "style", + "description": "Sets the marker opacity.", + "dflt": 1 }, - "tickwidth": { + "size": { "valType": "number", "min": 0, - "dflt": 1, + "dflt": 6, + "arrayOk": false, "role": "style", - "editType": "colorbars", - "description": "Sets the tick width (in px)." + "editType": "calcIfAutorange", + "description": "Sets the marker size (in px)." }, - "tickcolor": { + "color": { "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, + "arrayOk": false, "role": "style", - "editType": "colorbars", - "description": "Determines whether or not the tick labels are drawn." + "editType": "style", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, - "tickfont": { - "family": { - "valType": "string", + "line": { + "color": { + "valType": "color", + "arrayOk": false, "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set.", + "dflt": "#444" }, - "size": { + "width": { "valType": "number", + "min": 0, + "arrayOk": false, "role": "style", - "min": 1, - "editType": "colorbars" + "editType": "style", + "description": "Sets the width (in px) of the lines bounding the marker points.", + "dflt": 0 }, - "color": { + "outliercolor": { "valType": "color", "role": "style", - "editType": "colorbars" + "editType": "style", + "description": "Sets the border line color of the outlier sample points. Defaults to marker.color" }, - "description": "Sets the color bar's tick label font", - "editType": "colorbars", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "colorbars", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." - }, - "tickformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "colorbars" - }, - { - "valType": "any", - "editType": "colorbars" - } - ], - "editType": "colorbars", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "colorbars", - "role": "object" - } + "outlierwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "style", + "description": "Sets the border line width (in px) of the outlier sample points." }, + "editType": "style", "role": "object" }, - "tickprefix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label prefix." + "editType": "plot", + "role": "object" + }, + "text": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "calc", + "description": "Sets the text elements associated with each sample value. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." + }, + "box": { + "visible": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "plot", + "description": "Determines if an miniature box plot is drawn inside the violins. " }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + "width": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.25, + "role": "info", + "editType": "plot", + "description": "Sets the width of the inner box plots relative to the violins' width. For example, with 1, the inner box plots are as wide as the violins." }, - "ticksuffix": { - "valType": "string", - "dflt": "", + "fillcolor": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "Sets a tick label suffix." + "editType": "style", + "description": "Sets the inner box plot fill color." }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "Same as `showtickprefix` but for tick suffixes." + "line": { + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the inner box plot bounding line color." + }, + "width": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "style", + "description": "Sets the inner box plot bounding line width." + }, + "editType": "style", + "role": "object" }, - "separatethousands": { + "editType": "plot", + "role": "object" + }, + "meanline": { + "visible": { "valType": "boolean", "dflt": false, - "role": "style", - "editType": "colorbars", - "description": "If \"true\", even 4-digit integers are separated" + "role": "info", + "editType": "plot", + "description": "Determines if a line corresponding to the sample's mean is shown inside the violins. If `box.visible` is turned on, the mean line is drawn inside the inner box. Otherwise, the mean line is drawn from one side of the violin to other." }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", + "color": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + "editType": "style", + "description": "Sets the mean line color." }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "width": { + "valType": "number", + "min": 0, "role": "style", - "editType": "colorbars", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." - }, - "title": { - "valType": "string", - "role": "info", - "description": "Sets the title of the color bar.", - "editType": "colorbars" + "editType": "style", + "description": "Sets the mean line width." }, - "titlefont": { - "family": { - "valType": "string", + "editType": "plot", + "role": "object" + }, + "side": { + "valType": "enumerated", + "values": [ + "both", + "positive", + "negative" + ], + "dflt": "both", + "role": "info", + "editType": "plot", + "description": "Determines on which side of the position value the density function making up one half of a violin is plotted. Useful when comparing two violin traces under *overlay* mode, where one trace has `side` set to *positive* and the other to *negative*." + }, + "selected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker opacity of selected points." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "style", + "description": "Sets the marker color of selected points." }, "size": { "valType": "number", + "min": 0, "role": "style", - "min": 1, - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker size of selected points." + }, + "editType": "style", + "role": "object" + }, + "editType": "style", + "role": "object" + }, + "unselected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "style", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." }, "color": { "valType": "color", "role": "style", - "editType": "colorbars" + "editType": "style", + "description": "Sets the marker color of unselected points, applied only when a selection exists." }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "style", + "description": "Sets the marker size of unselected points, applied only when a selection exists." + }, + "editType": "style", "role": "object" }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" - }, - "editType": "colorbars", - "role": "object", - "tickvalssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", - "editType": "none" - }, - "ticktextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", - "editType": "none" - } + "editType": "style", + "role": "object" }, - "xcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" + "hoveron": { + "valType": "flaglist", + "flags": [ + "violins", + "points", + "kde" ], - "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `x` date data." - }, - "ycalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" + "dflt": "violins+points+kde", + "extras": [ + "all" ], "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `y` date data." + "editType": "style", + "description": "Do the hover effects highlight individual violins or sample points or the kernel density estimate or any combination of them?" }, "xaxis": { "valType": "subplotid", @@ -10711,7 +13186,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -10731,10 +13206,10 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "zsrc": { + "ysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for z .", + "description": "Sets the source reference on plot.ly for y .", "editType": "none" }, "xsrc": { @@ -10743,27 +13218,52 @@ "description": "Sets the source reference on plot.ly for x .", "editType": "none" }, - "ysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for y .", - "editType": "none" - }, "textsrc": { "valType": "string", "role": "info", "description": "Sets the source reference on plot.ly for text .", "editType": "none" } + }, + "layoutAttributes": { + "violinmode": { + "valType": "enumerated", + "values": [ + "group", + "overlay" + ], + "dflt": "overlay", + "role": "info", + "editType": "calc", + "description": "Determines how violins at the same location coordinate are displayed on the graph. If *group*, the violins are plotted next to one another centered around the shared location. If *overlay*, the violins are plotted over one another, you might need to set *opacity* to see them multiple violins." + }, + "violingap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.3, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between violins of adjacent location coordinates." + }, + "violingroupgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.3, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between violins of the same location coordinate." + } } }, - "scatterternary": { + "scatter3d": { "meta": { - "hrName": "scatter_ternary", - "description": "Provides similar functionality to the *scatter* type but on a ternary phase diagram. The data is provided by at least two arrays out of `a`, `b`, `c` triplets." + "hrName": "scatter_3d", + "description": "The data visualized as scatter point or lines in 3D dimension is set in `x`, `y`, `z`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` Projections are achieved via `projection`. Surface fills are achieved via `surfaceaxis`." }, "attributes": { - "type": "scatterternary", + "type": "scatter3d", "visible": { "valType": "enumerated", "values": [ @@ -10833,9 +13333,9 @@ "valType": "flaglist", "role": "info", "flags": [ - "a", - "b", - "c", + "x", + "y", + "z", "text", "name" ], @@ -10846,7 +13346,7 @@ ], "arrayOk": true, "dflt": "all", - "editType": "none", + "editType": "calc", "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." }, "hoverlabel": { @@ -10959,622 +13459,209 @@ "editType": "calc", "role": "object" }, - "a": { + "x": { "valType": "data_array", - "editType": "calc", - "description": "Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary.sum`.", + "editType": "calc+clearAxisTypes", + "description": "Sets the x coordinates.", "role": "data" }, - "b": { + "y": { "valType": "data_array", - "editType": "calc", - "description": "Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary.sum`.", + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinates.", "role": "data" }, - "c": { + "z": { "valType": "data_array", - "editType": "calc", - "description": "Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary.sum`.", + "description": "Sets the z coordinates.", + "editType": "calc+clearAxisTypes", "role": "data" }, - "sum": { - "valType": "number", - "role": "info", - "dflt": 0, - "min": 0, - "editType": "calc", - "description": "The number each triplet should sum to, if only two of `a`, `b`, and `c` are provided. This overrides `ternary.sum` to normalize this specific trace, but does not affect the values displayed on the axes. 0 (or missing) means to use ternary.sum" - }, - "mode": { - "valType": "flaglist", - "flags": [ - "lines", - "markers", - "text" - ], - "extras": [ - "none" - ], - "role": "info", - "editType": "calc", - "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*.", - "dflt": "markers" - }, "text": { "valType": "string", "role": "info", "dflt": "", "arrayOk": true, "editType": "calc", - "description": "Sets text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + "description": "Sets text elements associated with each (x,y,z) triplet. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y,z) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." }, "hovertext": { "valType": "string", "role": "info", "dflt": "", "arrayOk": true, - "editType": "style", - "description": "Sets hover text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). To be seen, trace `hoverinfo` must contain a *text* flag." - }, - "line": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the line color." - }, - "width": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "style", - "description": "Sets the line width (in px)." - }, - "dash": { - "valType": "string", - "values": [ - "solid", - "dot", - "dash", - "longdash", - "dashdot", - "longdashdot" - ], - "dflt": "solid", - "role": "style", - "editType": "style", - "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." - }, - "shape": { - "valType": "enumerated", - "values": [ - "linear", - "spline" - ], - "dflt": "linear", - "role": "style", - "editType": "plot", - "description": "Determines the line shape. With *spline* the lines are drawn using spline interpolation. The other available values correspond to step-wise line shapes." - }, - "smoothing": { - "valType": "number", - "min": 0, - "max": 1.3, - "dflt": 1, - "role": "style", - "editType": "plot", - "description": "Has an effect only if `shape` is set to *spline* Sets the amount of smoothing. *0* corresponds to no smoothing (equivalent to a *linear* shape)." - }, "editType": "calc", - "role": "object" + "description": "Sets text elements associated with each (x,y,z) triplet. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y,z) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." }, - "connectgaps": { - "valType": "boolean", - "dflt": false, + "mode": { + "valType": "flaglist", + "flags": [ + "lines", + "markers", + "text" + ], + "extras": [ + "none" + ], "role": "info", "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." - }, - "cliponaxis": { - "valType": "boolean", - "dflt": true, - "role": "info", - "editType": "plot", - "description": "Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*.", + "dflt": "lines+markers" }, - "fill": { + "surfaceaxis": { "valType": "enumerated", + "role": "info", "values": [ - "none", - "toself", - "tonext" + -1, + 0, + 1, + 2 ], - "dflt": "none", - "role": "style", - "editType": "calc", - "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. scatterternary has a subset of the options available to scatter. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. *tonext* fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like *toself* if there is no trace before it. *tonext* should not be used if one trace does not enclose the other." + "dflt": -1, + "description": "If *-1*, the scatter points are not fill with a surface If *0*, *1*, *2*, the scatter points are filled with a Delaunay surface about the x, y, z respectively.", + "editType": "calc" }, - "fillcolor": { + "surfacecolor": { "valType": "color", "role": "style", - "editType": "style", - "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + "description": "Sets the surface fill color.", + "editType": "calc" }, - "marker": { - "symbol": { - "valType": "enumerated", - "values": [ - 0, - "circle", - 100, - "circle-open", - 200, - "circle-dot", - 300, - "circle-open-dot", - 1, - "square", - 101, - "square-open", - 201, - "square-dot", - 301, - "square-open-dot", - 2, - "diamond", - 102, - "diamond-open", - 202, - "diamond-dot", - 302, - "diamond-open-dot", - 3, - "cross", - 103, - "cross-open", - 203, - "cross-dot", - 303, - "cross-open-dot", - 4, - "x", - 104, - "x-open", - 204, - "x-dot", - 304, - "x-open-dot", - 5, - "triangle-up", - 105, - "triangle-up-open", - 205, - "triangle-up-dot", - 305, - "triangle-up-open-dot", - 6, - "triangle-down", - 106, - "triangle-down-open", - 206, - "triangle-down-dot", - 306, - "triangle-down-open-dot", - 7, - "triangle-left", - 107, - "triangle-left-open", - 207, - "triangle-left-dot", - 307, - "triangle-left-open-dot", - 8, - "triangle-right", - 108, - "triangle-right-open", - 208, - "triangle-right-dot", - 308, - "triangle-right-open-dot", - 9, - "triangle-ne", - 109, - "triangle-ne-open", - 209, - "triangle-ne-dot", - 309, - "triangle-ne-open-dot", - 10, - "triangle-se", - 110, - "triangle-se-open", - 210, - "triangle-se-dot", - 310, - "triangle-se-open-dot", - 11, - "triangle-sw", - 111, - "triangle-sw-open", - 211, - "triangle-sw-dot", - 311, - "triangle-sw-open-dot", - 12, - "triangle-nw", - 112, - "triangle-nw-open", - 212, - "triangle-nw-dot", - 312, - "triangle-nw-open-dot", - 13, - "pentagon", - 113, - "pentagon-open", - 213, - "pentagon-dot", - 313, - "pentagon-open-dot", - 14, - "hexagon", - 114, - "hexagon-open", - 214, - "hexagon-dot", - 314, - "hexagon-open-dot", - 15, - "hexagon2", - 115, - "hexagon2-open", - 215, - "hexagon2-dot", - 315, - "hexagon2-open-dot", - 16, - "octagon", - 116, - "octagon-open", - 216, - "octagon-dot", - 316, - "octagon-open-dot", - 17, - "star", - 117, - "star-open", - 217, - "star-dot", - 317, - "star-open-dot", - 18, - "hexagram", - 118, - "hexagram-open", - 218, - "hexagram-dot", - 318, - "hexagram-open-dot", - 19, - "star-triangle-up", - 119, - "star-triangle-up-open", - 219, - "star-triangle-up-dot", - 319, - "star-triangle-up-open-dot", - 20, - "star-triangle-down", - 120, - "star-triangle-down-open", - 220, - "star-triangle-down-dot", - 320, - "star-triangle-down-open-dot", - 21, - "star-square", - 121, - "star-square-open", - 221, - "star-square-dot", - 321, - "star-square-open-dot", - 22, - "star-diamond", - 122, - "star-diamond-open", - 222, - "star-diamond-dot", - 322, - "star-diamond-open-dot", - 23, - "diamond-tall", - 123, - "diamond-tall-open", - 223, - "diamond-tall-dot", - 323, - "diamond-tall-open-dot", - 24, - "diamond-wide", - 124, - "diamond-wide-open", - 224, - "diamond-wide-dot", - 324, - "diamond-wide-open-dot", - 25, - "hourglass", - 125, - "hourglass-open", - 26, - "bowtie", - 126, - "bowtie-open", - 27, - "circle-cross", - 127, - "circle-cross-open", - 28, - "circle-x", - 128, - "circle-x-open", - 29, - "square-cross", - 129, - "square-cross-open", - 30, - "square-x", - 130, - "square-x-open", - 31, - "diamond-cross", - 131, - "diamond-cross-open", - 32, - "diamond-x", - 132, - "diamond-x-open", - 33, - "cross-thin", - 133, - "cross-thin-open", - 34, - "x-thin", - 134, - "x-thin-open", - 35, - "asterisk", - 135, - "asterisk-open", - 36, - "hash", - 136, - "hash-open", - 236, - "hash-dot", - 336, - "hash-open-dot", - 37, - "y-up", - 137, - "y-up-open", - 38, - "y-down", - 138, - "y-down-open", - 39, - "y-left", - 139, - "y-left-open", - 40, - "y-right", - 140, - "y-right-open", - 41, - "line-ew", - 141, - "line-ew-open", - 42, - "line-ns", - 142, - "line-ns-open", - 43, - "line-ne", - 143, - "line-ne-open", - 44, - "line-nw", - 144, - "line-nw-open" - ], - "dflt": "circle", - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." - }, - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity." - }, - "maxdisplayed": { - "valType": "number", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "plot", - "description": "Sets a maximum number of points to be drawn on the graph. *0* corresponds to no limit." - }, - "size": { - "valType": "number", - "min": 0, - "dflt": 6, - "arrayOk": true, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the marker size (in px)." - }, - "sizeref": { - "valType": "number", - "dflt": 1, - "role": "style", - "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." - }, - "sizemin": { - "valType": "number", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." - }, - "sizemode": { - "valType": "enumerated", - "values": [ - "diameter", - "area" - ], - "dflt": "diameter", - "role": "info", - "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." - }, - "line": { - "width": { - "valType": "number", - "min": 0, - "arrayOk": true, - "role": "style", - "editType": "style", - "description": "Sets the width (in px) of the lines bounding the marker points." + "projection": { + "x": { + "show": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Sets whether or not projections are shown along the x axis.", + "editType": "calc" }, - "editType": "calc", - "color": { - "valType": "color", - "arrayOk": true, + "opacity": { + "valType": "number", "role": "style", - "editType": "style", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "min": 0, + "max": 1, + "dflt": 1, + "description": "Sets the projection color.", + "editType": "calc" }, - "colorscale": { - "valType": "colorscale", + "scale": { + "valType": "number", "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + "min": 0, + "max": 10, + "dflt": 0.6666666666666666, + "description": "Sets the scale factor determining the size of the projection marker points.", + "editType": "calc" }, - "cauto": { + "editType": "calc", + "role": "object" + }, + "y": { + "show": { "valType": "boolean", "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + "dflt": false, + "description": "Sets whether or not projections are shown along the y axis.", + "editType": "calc" }, - "cmax": { + "opacity": { "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + "role": "style", + "min": 0, + "max": 1, + "dflt": 1, + "description": "Sets the projection color.", + "editType": "calc" }, - "cmin": { + "scale": { "valType": "number", - "role": "info", - "dflt": null, - "editType": "plot", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "min": 0, + "max": 10, + "dflt": 0.6666666666666666, + "description": "Sets the scale factor determining the size of the projection marker points.", + "editType": "calc" }, - "reversescale": { + "editType": "calc", + "role": "object" + }, + "z": { + "show": { "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "role": "object", - "widthsrc": { - "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for width .", - "editType": "none" + "dflt": false, + "description": "Sets whether or not projections are shown along the z axis.", + "editType": "calc" }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "gradient": { - "type": { - "valType": "enumerated", - "values": [ - "radial", - "horizontal", - "vertical", - "none" - ], - "arrayOk": true, - "dflt": "none", + "opacity": { + "valType": "number", "role": "style", - "editType": "calc", - "description": "Sets the type of gradient used to fill the markers" + "min": 0, + "max": 1, + "dflt": 1, + "description": "Sets the projection color.", + "editType": "calc" }, - "color": { - "valType": "color", - "arrayOk": true, + "scale": { + "valType": "number", "role": "style", - "editType": "calc", - "description": "Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical." + "min": 0, + "max": 10, + "dflt": 0.6666666666666666, + "description": "Sets the scale factor determining the size of the projection marker points.", + "editType": "calc" }, "editType": "calc", - "role": "object", - "typesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for type .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } + "role": "object" }, "editType": "calc", + "role": "object" + }, + "connectgaps": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." + }, + "line": { + "width": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "calc", + "description": "Sets the line width (in px)." + }, + "dash": { + "valType": "enumerated", + "values": [ + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" + ], + "dflt": "solid", + "role": "style", + "description": "Sets the dash style of the lines.", + "editType": "calc" + }, + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Has an effect only if `line.color` is set to a numerical array. Determines whether or not a colorbar is displayed.", + "editType": "calc" + }, "color": { "valType": "color", "arrayOk": true, "role": "style", - "editType": "style", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "editType": "calc", + "description": "Sets the line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, "colorscale": { "valType": "colorscale", @@ -11583,7 +13670,7 @@ "impliedEdits": { "autocolorscale": false }, - "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + "description": "Sets the colorscale and only has an effect if `line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `line.cmin` and `line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" }, "cauto": { "valType": "boolean", @@ -11591,27 +13678,27 @@ "dflt": true, "editType": "calc", "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + "description": "Has an effect only if `line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." }, "cmax": { "valType": "number", "role": "info", "dflt": null, - "editType": "plot", + "editType": "calc", "impliedEdits": { "cauto": false }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + "description": "Has an effect only if `line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `line.color` array index, and if set, `line.cmin` must be set as well." }, "cmin": { "valType": "number", "role": "info", "dflt": null, - "editType": "plot", + "editType": "calc", "impliedEdits": { "cauto": false }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + "description": "Has an effect only if `line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `line.color` array index, and if set, `line.cmax` must be set as well." }, "autocolorscale": { "valType": "boolean", @@ -11619,14 +13706,86 @@ "dflt": true, "editType": "calc", "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "description": "Has an effect only if `line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." }, "reversescale": { "valType": "boolean", "role": "style", "dflt": false, "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + "description": "Has an effect only if `line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "editType": "calc", + "role": "object", + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "marker": { + "symbol": { + "valType": "enumerated", + "values": [ + "circle", + "circle-open", + "square", + "square-open", + "diamond", + "diamond-open", + "cross", + "x" + ], + "role": "style", + "dflt": "circle", + "arrayOk": true, + "description": "Sets the marker symbol type.", + "editType": "calc" + }, + "size": { + "valType": "number", + "min": 0, + "dflt": 8, + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker size (in px)." + }, + "sizeref": { + "valType": "number", + "dflt": 1, + "role": "style", + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." + }, + "sizemin": { + "valType": "number", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." + }, + "sizemode": { + "valType": "enumerated", + "values": [ + "diameter", + "area" + ], + "dflt": "diameter", + "role": "info", + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." + }, + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "arrayOk": false, + "role": "style", + "editType": "calc", + "description": "Sets the marker opacity. Note that the marker opacity for scatter3d traces must be a scalar value for performance reasons. To set a blending opacity value (i.e. which is not transparent), set *marker.color* to an rgba color and use its alpha channel." }, "showscale": { "valType": "boolean", @@ -11645,7 +13804,7 @@ "role": "style", "dflt": "pixels", "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "colorbars" + "editType": "calc" }, "thickness": { "valType": "number", @@ -11653,7 +13812,7 @@ "min": 0, "dflt": 30, "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "colorbars" + "editType": "calc" }, "lenmode": { "valType": "enumerated", @@ -11664,7 +13823,7 @@ "role": "info", "dflt": "fraction", "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "colorbars" + "editType": "calc" }, "len": { "valType": "number", @@ -11672,7 +13831,7 @@ "dflt": 1, "role": "style", "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "colorbars" + "editType": "calc" }, "x": { "valType": "number", @@ -11681,7 +13840,7 @@ "max": 3, "role": "style", "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "colorbars" + "editType": "calc" }, "xanchor": { "valType": "enumerated", @@ -11693,7 +13852,7 @@ "dflt": "left", "role": "style", "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "colorbars" + "editType": "calc" }, "xpad": { "valType": "number", @@ -11701,7 +13860,7 @@ "min": 0, "dflt": 10, "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "colorbars" + "editType": "calc" }, "y": { "valType": "number", @@ -11710,7 +13869,7 @@ "min": -2, "max": 3, "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "colorbars" + "editType": "calc" }, "yanchor": { "valType": "enumerated", @@ -11722,7 +13881,7 @@ "role": "style", "dflt": "middle", "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "colorbars" + "editType": "calc" }, "ypad": { "valType": "number", @@ -11730,13 +13889,13 @@ "min": 0, "dflt": 10, "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "colorbars" + "editType": "calc" }, "outlinecolor": { "valType": "color", "dflt": "#444", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the axis line color." }, "outlinewidth": { @@ -11744,14 +13903,14 @@ "min": 0, "dflt": 1, "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the width (in px) of the axis line." }, "bordercolor": { "valType": "color", "dflt": "#444", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the axis line color." }, "borderwidth": { @@ -11760,14 +13919,14 @@ "min": 0, "dflt": 0, "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "colorbars" + "editType": "calc" }, "bgcolor": { "valType": "color", "role": "style", "dflt": "rgba(0,0,0,0)", "description": "Sets the color of padded area.", - "editType": "colorbars" + "editType": "calc" }, "tickmode": { "valType": "enumerated", @@ -11777,7 +13936,7 @@ "array" ], "role": "info", - "editType": "colorbars", + "editType": "calc", "impliedEdits": {}, "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." }, @@ -11786,13 +13945,13 @@ "min": 0, "dflt": 0, "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." }, "tick0": { "valType": "any", "role": "style", - "editType": "colorbars", + "editType": "calc", "impliedEdits": { "tickmode": "linear" }, @@ -11801,7 +13960,7 @@ "dtick": { "valType": "any", "role": "style", - "editType": "colorbars", + "editType": "calc", "impliedEdits": { "tickmode": "linear" }, @@ -11809,13 +13968,13 @@ }, "tickvals": { "valType": "data_array", - "editType": "colorbars", + "editType": "calc", "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", "role": "data" }, "ticktext": { "valType": "data_array", - "editType": "colorbars", + "editType": "calc", "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", "role": "data" }, @@ -11827,7 +13986,7 @@ "" ], "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", "dflt": "" }, @@ -11836,7 +13995,7 @@ "min": 0, "dflt": 5, "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the tick length (in px)." }, "tickwidth": { @@ -11844,21 +14003,21 @@ "min": 0, "dflt": 1, "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the tick width (in px)." }, "tickcolor": { "valType": "color", "dflt": "#444", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the tick color." }, "showticklabels": { "valType": "boolean", "dflt": true, "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Determines whether or not the tick labels are drawn." }, "tickfont": { @@ -11868,35 +14027,35 @@ "noBlank": true, "strict": true, "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" + "editType": "calc" }, "size": { "valType": "number", "role": "style", "min": 1, - "editType": "colorbars" + "editType": "calc" }, "color": { "valType": "color", "role": "style", - "editType": "colorbars" + "editType": "calc" }, "description": "Sets the color bar's tick label font", - "editType": "colorbars", + "editType": "calc", "role": "object" }, "tickangle": { "valType": "angle", "dflt": "auto", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." }, "tickformat": { "valType": "string", "dflt": "", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" }, "tickformatstops": { @@ -11908,24 +14067,24 @@ "items": [ { "valType": "any", - "editType": "colorbars" + "editType": "calc" }, { "valType": "any", - "editType": "colorbars" + "editType": "calc" } ], - "editType": "colorbars", + "editType": "calc", "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" }, "value": { "valType": "string", "dflt": "", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "string - dtickformat for described zoom level, the same as *tickformat*" }, - "editType": "colorbars", + "editType": "calc", "role": "object" } }, @@ -11935,7 +14094,7 @@ "valType": "string", "dflt": "", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets a tick label prefix." }, "showtickprefix": { @@ -11948,14 +14107,14 @@ ], "dflt": "all", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." }, "ticksuffix": { "valType": "string", "dflt": "", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Sets a tick label suffix." }, "showticksuffix": { @@ -11968,14 +14127,14 @@ ], "dflt": "all", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Same as `showtickprefix` but for tick suffixes." }, "separatethousands": { "valType": "boolean", "dflt": false, "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "If \"true\", even 4-digit integers are separated" }, "exponentformat": { @@ -11990,7 +14149,7 @@ ], "dflt": "B", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." }, "showexponent": { @@ -12003,14 +14162,14 @@ ], "dflt": "all", "role": "style", - "editType": "colorbars", + "editType": "calc", "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." }, "title": { "valType": "string", "role": "info", "description": "Sets the title of the color bar.", - "editType": "colorbars" + "editType": "calc" }, "titlefont": { "family": { @@ -12019,21 +14178,21 @@ "noBlank": true, "strict": true, "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" + "editType": "calc" }, "size": { "valType": "number", "role": "style", "min": 1, - "editType": "colorbars" + "editType": "calc" }, "color": { "valType": "color", "role": "style", - "editType": "colorbars" + "editType": "calc" }, "description": "Sets this color bar's title font.", - "editType": "colorbars", + "editType": "calc", "role": "object" }, "titleside": { @@ -12046,9 +14205,9 @@ "role": "style", "dflt": "top", "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" + "editType": "calc" }, - "editType": "colorbars", + "editType": "calc", "role": "object", "tickvalssrc": { "valType": "string", @@ -12063,6 +14222,143 @@ "editType": "none" } }, + "line": { + "width": { + "valType": "number", + "min": 0, + "arrayOk": false, + "role": "style", + "editType": "calc", + "description": "Sets the width (in px) of the lines bounding the marker points." + }, + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "editType": "calc", + "role": "object", + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "editType": "calc", "role": "object", "symbolsrc": { "valType": "string", @@ -12070,12 +14366,6 @@ "description": "Sets the source reference on plot.ly for symbol .", "editType": "none" }, - "opacitysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for opacity .", - "editType": "none" - }, "sizesrc": { "valType": "string", "role": "info", @@ -12089,6 +14379,25 @@ "editType": "none" } }, + "textposition": { + "valType": "enumerated", + "values": [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right" + ], + "dflt": "top center", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." + }, "textfont": { "family": { "valType": "string", @@ -12109,7 +14418,7 @@ "color": { "valType": "color", "role": "style", - "editType": "style", + "editType": "calc", "arrayOk": true }, "editType": "calc", @@ -12134,1056 +14443,430 @@ "editType": "none" } }, - "textposition": { - "valType": "enumerated", - "values": [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right" - ], - "dflt": "middle center", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." - }, - "selected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of selected points." - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of selected points." - }, - "size": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "style", - "description": "Sets the marker size of selected points." - }, - "editType": "style", - "role": "object" - }, - "textfont": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the text font color of selected points." - }, - "editType": "style", - "role": "object" - }, - "editType": "style", - "role": "object" - }, - "unselected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of unselected points, applied only when a selection exists." - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of unselected points, applied only when a selection exists." - }, - "size": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "style", - "description": "Sets the marker size of unselected points, applied only when a selection exists." - }, - "editType": "style", - "role": "object" - }, - "textfont": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the text font color of unselected points, applied only when a selection exists." - }, - "editType": "style", - "role": "object" - }, - "editType": "style", - "role": "object" - }, - "hoveron": { - "valType": "flaglist", - "flags": [ - "points", - "fills" - ], - "role": "info", - "editType": "style", - "description": "Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is *toself* or *tonext* and there are no markers or text, then the default is *fills*, otherwise it is *points*." - }, - "subplot": { - "valType": "subplotid", - "role": "info", - "dflt": "ternary", - "editType": "calc", - "description": "Sets a reference between this trace's data coordinates and a ternary subplot. If *ternary* (the default value), the data refer to `layout.ternary`. If *ternary2*, the data refer to `layout.ternary2`, and so on." - }, - "idssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ids .", - "editType": "none" - }, - "customdatasrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for customdata .", - "editType": "none" - }, - "hoverinfosrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hoverinfo .", - "editType": "none" - }, - "asrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for a .", - "editType": "none" - }, - "bsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for b .", - "editType": "none" - }, - "csrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for c .", - "editType": "none" - }, - "textsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for text .", - "editType": "none" - }, - "hovertextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hovertext .", - "editType": "none" - }, - "textpositionsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for textposition .", - "editType": "none" - } - } - }, - "violin": { - "meta": { - "description": "In vertical (horizontal) violin plots, statistics are computed using `y` (`x`) values. By supplying an `x` (`y`) array, one violin per distinct x (y) value is drawn If no `x` (`y`) {array} is provided, a single violin is drawn. That violin position is then positioned with with `name` or with `x0` (`y0`) if provided." - }, - "attributes": { - "type": "violin", - "visible": { - "valType": "enumerated", - "values": [ - true, - false, - "legendonly" - ], - "role": "info", - "dflt": true, - "editType": "calc", - "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this trace is shown in the legend." - }, - "legendgroup": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "style", - "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." - }, - "opacity": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "editType": "style", - "description": "Sets the opacity of the trace." - }, - "name": { - "valType": "string", - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Sets the trace name. The trace name appear as the legend item and on hover. For box traces, the name will also be used for the position coordinate, if `x` and `x0` (`y` and `y0` if horizontal) are missing and the position axis is categorical" - }, - "uid": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "calc" - }, - "ids": { - "valType": "data_array", - "editType": "calc", - "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", - "role": "data" - }, - "customdata": { - "valType": "data_array", - "editType": "calc", - "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", - "role": "data" - }, - "selectedpoints": { - "valType": "any", - "role": "info", - "editType": "calc", - "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." - }, - "hoverinfo": { - "valType": "flaglist", - "role": "info", - "flags": [ - "x", - "y", - "z", - "text", - "name" - ], - "extras": [ - "all", - "none", - "skip" - ], - "arrayOk": true, - "dflt": "all", - "editType": "none", - "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." - }, - "hoverlabel": { - "bgcolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the background color of the hover labels for this trace" - }, - "bordercolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the border color of the hover labels for this trace." - }, - "font": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "none", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "none", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "none", - "arrayOk": true - }, - "editType": "none", - "description": "Sets the font used in hover labels.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "namelength": { - "valType": "integer", - "min": -1, - "arrayOk": true, - "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." - }, - "editType": "calc", - "role": "object", - "bgcolorsrc": { - "valType": "string", + "error_x": { + "visible": { + "valType": "boolean", "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", - "editType": "none" + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." }, - "bordercolorsrc": { - "valType": "string", + "type": { + "valType": "enumerated", + "values": [ + "percent", + "constant", + "sqrt", + "data" + ], "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", - "editType": "none" + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." }, - "namelengthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", - "editType": "none" - } - }, - "stream": { - "token": { - "valType": "string", - "noBlank": true, - "strict": true, + "symmetric": { + "valType": "boolean", "role": "info", "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." }, - "maxpoints": { + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" + }, + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" + }, + "value": { "valType": "number", "min": 0, - "max": 10000, - "dflt": 500, + "dflt": 10, "role": "info", "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + }, + "valueminus": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + }, + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" + }, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" + }, + "copy_zstyle": { + "valType": "boolean", + "role": "style", + "editType": "calc" }, - "editType": "calc", - "role": "object" - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y sample data or coordinates. See overview for more info.", - "role": "data" - }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the x sample data or coordinates. See overview for more info.", - "role": "data" - }, - "x0": { - "valType": "any", - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinate of the box. See overview for more info." - }, - "y0": { - "valType": "any", - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinate of the box. See overview for more info." - }, - "orientation": { - "valType": "enumerated", - "values": [ - "v", - "h" - ], - "role": "style", - "editType": "calc+clearAxisTypes", - "description": "Sets the orientation of the violin(s). If *v* (*h*), the distribution is visualized along the vertical (horizontal)." - }, - "bandwidth": { - "valType": "number", - "min": 0, - "role": "info", - "editType": "calc", - "description": "Sets the bandwidth used to compute the kernel density estimate. By default, the bandwidth is determined by Silverman's rule of thumb." - }, - "scalegroup": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "calc", - "description": "If there are multiple violins that should be sized according to to some metric (see `scalemode`), link them by providing a non-empty group id here shared by every trace in the same group." - }, - "scalemode": { - "valType": "enumerated", - "values": [ - "width", - "count" - ], - "dflt": "width", - "role": "info", - "editType": "calc", - "description": "Sets the metric by which the width of each violin is determined.*width* means each violin has the same (max) width*count* means the violins are scaled by the number of sample points makingup each violin." - }, - "spanmode": { - "valType": "enumerated", - "values": [ - "soft", - "hard", - "manual" - ], - "dflt": "soft", - "role": "info", - "editType": "calc", - "description": "Sets the method by which the span in data space where the density function will be computed. *soft* means the span goes from the sample's minimum value minus two bandwidths to the sample's maximum value plus two bandwidths. *hard* means the span goes from the sample's minimum to its maximum value. For custom span settings, use mode *manual* and fill in the `span` attribute." - }, - "span": { - "valType": "info_array", - "items": [ - { - "valType": "any", - "editType": "calc" - }, - { - "valType": "any", - "editType": "calc" - } - ], - "role": "info", - "editType": "calc", - "description": "Sets the span in data space for which the density function will be computed. Has an effect only when `spanmode` is set to *manual*." - }, - "line": { "color": { "valType": "color", "role": "style", - "editType": "style", - "description": "Sets the color of line bounding the violin(s)." + "editType": "calc", + "description": "Sets the stoke color of the error bars." }, - "width": { + "thickness": { "valType": "number", - "role": "style", "min": 0, "dflt": 2, - "editType": "style", - "description": "Sets the width (in px) of line bounding the violin(s)." + "role": "style", + "editType": "calc", + "description": "Sets the thickness (in px) of the error bars." }, - "editType": "plot", - "role": "object" - }, - "fillcolor": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." - }, - "points": { - "valType": "enumerated", - "values": [ - "all", - "outliers", - "suspectedoutliers", - false - ], - "dflt": "outliers", - "role": "style", - "editType": "calcIfAutorange", - "description": "If *outliers*, only the sample points lying outside the whiskers are shown If *suspectedoutliers*, the outlier points are shown and points either less than 4*Q1-3*Q3 or greater than 4*Q3-3*Q1 are highlighted (see `outliercolor`) If *all*, all sample points are shown If *false*, only the violins are shown with no sample points" - }, - "jitter": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the amount of jitter in the sample points drawn. If *0*, the sample points align along the distribution axis. If *1*, the sample points are drawn in a random jitter of width equal to the width of the violins." - }, - "pointpos": { - "valType": "number", - "min": -2, - "max": 2, - "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the position of the sample points in relation to the violins. If *0*, the sample points are places over the center of the violins. Positive (negative) values correspond to positions to the right (left) for vertical violins and above (below) for horizontal violins." - }, - "marker": { - "outliercolor": { - "valType": "color", - "dflt": "rgba(0, 0, 0, 0)", + "width": { + "valType": "number", + "min": 0, "role": "style", - "editType": "style", - "description": "Sets the color of the outlier sample points." + "editType": "calc", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." }, - "symbol": { + "editType": "calc", + "_deprecated": { + "opacity": { + "valType": "number", + "role": "style", + "editType": "calc", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } + }, + "role": "object", + "arraysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" + }, + "arrayminussrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } + }, + "error_y": { + "visible": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." + }, + "type": { "valType": "enumerated", "values": [ - 0, - "circle", - 100, - "circle-open", - 200, - "circle-dot", - 300, - "circle-open-dot", - 1, - "square", - 101, - "square-open", - 201, - "square-dot", - 301, - "square-open-dot", - 2, - "diamond", - 102, - "diamond-open", - 202, - "diamond-dot", - 302, - "diamond-open-dot", - 3, - "cross", - 103, - "cross-open", - 203, - "cross-dot", - 303, - "cross-open-dot", - 4, - "x", - 104, - "x-open", - 204, - "x-dot", - 304, - "x-open-dot", - 5, - "triangle-up", - 105, - "triangle-up-open", - 205, - "triangle-up-dot", - 305, - "triangle-up-open-dot", - 6, - "triangle-down", - 106, - "triangle-down-open", - 206, - "triangle-down-dot", - 306, - "triangle-down-open-dot", - 7, - "triangle-left", - 107, - "triangle-left-open", - 207, - "triangle-left-dot", - 307, - "triangle-left-open-dot", - 8, - "triangle-right", - 108, - "triangle-right-open", - 208, - "triangle-right-dot", - 308, - "triangle-right-open-dot", - 9, - "triangle-ne", - 109, - "triangle-ne-open", - 209, - "triangle-ne-dot", - 309, - "triangle-ne-open-dot", - 10, - "triangle-se", - 110, - "triangle-se-open", - 210, - "triangle-se-dot", - 310, - "triangle-se-open-dot", - 11, - "triangle-sw", - 111, - "triangle-sw-open", - 211, - "triangle-sw-dot", - 311, - "triangle-sw-open-dot", - 12, - "triangle-nw", - 112, - "triangle-nw-open", - 212, - "triangle-nw-dot", - 312, - "triangle-nw-open-dot", - 13, - "pentagon", - 113, - "pentagon-open", - 213, - "pentagon-dot", - 313, - "pentagon-open-dot", - 14, - "hexagon", - 114, - "hexagon-open", - 214, - "hexagon-dot", - 314, - "hexagon-open-dot", - 15, - "hexagon2", - 115, - "hexagon2-open", - 215, - "hexagon2-dot", - 315, - "hexagon2-open-dot", - 16, - "octagon", - 116, - "octagon-open", - 216, - "octagon-dot", - 316, - "octagon-open-dot", - 17, - "star", - 117, - "star-open", - 217, - "star-dot", - 317, - "star-open-dot", - 18, - "hexagram", - 118, - "hexagram-open", - 218, - "hexagram-dot", - 318, - "hexagram-open-dot", - 19, - "star-triangle-up", - 119, - "star-triangle-up-open", - 219, - "star-triangle-up-dot", - 319, - "star-triangle-up-open-dot", - 20, - "star-triangle-down", - 120, - "star-triangle-down-open", - 220, - "star-triangle-down-dot", - 320, - "star-triangle-down-open-dot", - 21, - "star-square", - 121, - "star-square-open", - 221, - "star-square-dot", - 321, - "star-square-open-dot", - 22, - "star-diamond", - 122, - "star-diamond-open", - 222, - "star-diamond-dot", - 322, - "star-diamond-open-dot", - 23, - "diamond-tall", - 123, - "diamond-tall-open", - 223, - "diamond-tall-dot", - 323, - "diamond-tall-open-dot", - 24, - "diamond-wide", - 124, - "diamond-wide-open", - 224, - "diamond-wide-dot", - 324, - "diamond-wide-open-dot", - 25, - "hourglass", - 125, - "hourglass-open", - 26, - "bowtie", - 126, - "bowtie-open", - 27, - "circle-cross", - 127, - "circle-cross-open", - 28, - "circle-x", - 128, - "circle-x-open", - 29, - "square-cross", - 129, - "square-cross-open", - 30, - "square-x", - 130, - "square-x-open", - 31, - "diamond-cross", - 131, - "diamond-cross-open", - 32, - "diamond-x", - 132, - "diamond-x-open", - 33, - "cross-thin", - 133, - "cross-thin-open", - 34, - "x-thin", - 134, - "x-thin-open", - 35, - "asterisk", - 135, - "asterisk-open", - 36, - "hash", - 136, - "hash-open", - 236, - "hash-dot", - 336, - "hash-open-dot", - 37, - "y-up", - 137, - "y-up-open", - 38, - "y-down", - 138, - "y-down-open", - 39, - "y-left", - 139, - "y-left-open", - 40, - "y-right", - 140, - "y-right-open", - 41, - "line-ew", - 141, - "line-ew-open", - 42, - "line-ns", - 142, - "line-ns-open", - 43, - "line-ne", - 143, - "line-ne-open", - 44, - "line-nw", - 144, - "line-nw-open" + "percent", + "constant", + "sqrt", + "data" ], - "dflt": "circle", - "arrayOk": false, - "role": "style", - "editType": "plot", - "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." }, - "opacity": { + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + }, + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" + }, + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" + }, + "value": { "valType": "number", "min": 0, - "max": 1, - "arrayOk": false, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity.", - "dflt": 1 + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." }, - "size": { + "valueminus": { "valType": "number", "min": 0, - "dflt": 6, - "arrayOk": false, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + }, + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" + }, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" + }, + "copy_zstyle": { + "valType": "boolean", "role": "style", - "editType": "calcIfAutorange", - "description": "Sets the marker size (in px)." + "editType": "calc" }, "color": { "valType": "color", - "arrayOk": false, "role": "style", - "editType": "style", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "editType": "calc", + "description": "Sets the stoke color of the error bars." }, - "line": { - "color": { - "valType": "color", - "arrayOk": false, - "role": "style", - "editType": "style", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set.", - "dflt": "#444" - }, - "width": { - "valType": "number", - "min": 0, - "arrayOk": false, - "role": "style", - "editType": "style", - "description": "Sets the width (in px) of the lines bounding the marker points.", - "dflt": 0 - }, - "outliercolor": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the border line color of the outlier sample points. Defaults to marker.color" - }, - "outlierwidth": { + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "calc", + "description": "Sets the thickness (in px) of the error bars." + }, + "width": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "calc", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + }, + "editType": "calc", + "_deprecated": { + "opacity": { "valType": "number", - "min": 0, - "dflt": 1, "role": "style", - "editType": "style", - "description": "Sets the border line width (in px) of the outlier sample points." - }, - "editType": "style", - "role": "object" + "editType": "calc", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } }, - "editType": "plot", - "role": "object" - }, - "text": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "calc", - "description": "Sets the text elements associated with each sample value. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." + "role": "object", + "arraysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" + }, + "arrayminussrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } }, - "box": { + "error_z": { "visible": { "valType": "boolean", - "dflt": false, "role": "info", - "editType": "plot", - "description": "Determines if an miniature box plot is drawn inside the violins. " + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." }, - "width": { + "type": { + "valType": "enumerated", + "values": [ + "percent", + "constant", + "sqrt", + "data" + ], + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." + }, + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + }, + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" + }, + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" + }, + "value": { "valType": "number", "min": 0, - "max": 1, - "dflt": 0.25, + "dflt": 10, "role": "info", - "editType": "plot", - "description": "Sets the width of the inner box plots relative to the violins' width. For example, with 1, the inner box plots are as wide as the violins." + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." }, - "fillcolor": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the inner box plot fill color." + "valueminus": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" }, - "line": { - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the inner box plot bounding line color." - }, - "width": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "style", - "description": "Sets the inner box plot bounding line width." - }, - "editType": "style", - "role": "object" + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" }, - "editType": "plot", - "role": "object" - }, - "meanline": { - "visible": { - "valType": "boolean", - "dflt": false, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, "role": "info", - "editType": "plot", - "description": "Determines if a line corresponding to the sample's mean is shown inside the violins. If `box.visible` is turned on, the mean line is drawn inside the inner box. Otherwise, the mean line is drawn from one side of the violin to other." + "editType": "calc" }, "color": { "valType": "color", "role": "style", - "editType": "style", - "description": "Sets the mean line color." + "editType": "calc", + "description": "Sets the stoke color of the error bars." + }, + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, + "role": "style", + "editType": "calc", + "description": "Sets the thickness (in px) of the error bars." }, "width": { "valType": "number", "min": 0, "role": "style", - "editType": "style", - "description": "Sets the mean line width." + "editType": "calc", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." }, - "editType": "plot", - "role": "object" - }, - "side": { - "valType": "enumerated", - "values": [ - "both", - "positive", - "negative" - ], - "dflt": "both", - "role": "info", - "editType": "plot", - "description": "Determines on which side of the position value the density function making up one half of a violin is plotted. Useful when comparing two violin traces under *overlay* mode, where one trace has `side` set to *positive* and the other to *negative*." - }, - "selected": { - "marker": { + "editType": "calc", + "_deprecated": { "opacity": { "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of selected points." - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of selected points." - }, - "size": { - "valType": "number", - "min": 0, "role": "style", - "editType": "style", - "description": "Sets the marker size of selected points." - }, - "editType": "style", - "role": "object" + "editType": "calc", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } }, - "editType": "style", - "role": "object" - }, - "unselected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "role": "style", - "editType": "style", - "description": "Sets the marker opacity of unselected points, applied only when a selection exists." - }, - "color": { - "valType": "color", - "role": "style", - "editType": "style", - "description": "Sets the marker color of unselected points, applied only when a selection exists." - }, - "size": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "style", - "description": "Sets the marker size of unselected points, applied only when a selection exists." - }, - "editType": "style", - "role": "object" + "role": "object", + "arraysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" }, - "editType": "style", - "role": "object" + "arrayminussrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } }, - "hoveron": { - "valType": "flaglist", - "flags": [ - "violins", - "points", - "kde" + "xcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" ], - "dflt": "violins+points+kde", - "extras": [ - "all" + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `x` date data." + }, + "ycalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" ], "role": "info", - "editType": "style", - "description": "Do the hover effects highlight individual violins or sample points or the kernel density estimate or any combination of them?" + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `y` date data." }, - "xaxis": { - "valType": "subplotid", + "zcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], "role": "info", - "dflt": "x", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `z` date data." }, - "yaxis": { + "scene": { "valType": "subplotid", "role": "info", - "dflt": "y", + "dflt": "scene", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's 3D coordinate system and a 3D scene. If *scene* (the default value), the (x,y,z) coordinates refer to `layout.scene`. If *scene2*, the (x,y,z) coordinates refer to `layout.scene2`, and so on." }, "idssrc": { "valType": "string", @@ -13203,16 +14886,22 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, + "xsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for x .", + "editType": "none" + }, "ysrc": { "valType": "string", "role": "info", "description": "Sets the source reference on plot.ly for y .", "editType": "none" }, - "xsrc": { + "zsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for x .", + "description": "Sets the source reference on plot.ly for z .", "editType": "none" }, "textsrc": { @@ -13220,47 +14909,27 @@ "role": "info", "description": "Sets the source reference on plot.ly for text .", "editType": "none" - } - }, - "layoutAttributes": { - "violinmode": { - "valType": "enumerated", - "values": [ - "group", - "overlay" - ], - "dflt": "overlay", - "role": "info", - "editType": "calc", - "description": "Determines how violins at the same location coordinate are displayed on the graph. If *group*, the violins are plotted next to one another centered around the shared location. If *overlay*, the violins are plotted over one another, you might need to set *opacity* to see them multiple violins." }, - "violingap": { - "valType": "number", - "min": 0, - "max": 1, - "dflt": 0.3, - "role": "style", - "editType": "calc", - "description": "Sets the gap (in plot fraction) between violins of adjacent location coordinates." + "hovertextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hovertext .", + "editType": "none" }, - "violingroupgap": { - "valType": "number", - "min": 0, - "max": 1, - "dflt": 0.3, - "role": "style", - "editType": "calc", - "description": "Sets the gap (in plot fraction) between violins of the same location coordinate." + "textpositionsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for textposition .", + "editType": "none" } } }, - "scatter3d": { + "surface": { "meta": { - "hrName": "scatter_3d", - "description": "The data visualized as scatter point or lines in 3D dimension is set in `x`, `y`, `z`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` Projections are achieved via `projection`. Surface fills are achieved via `surfaceaxis`." + "description": "The data the describes the coordinates of the surface is set in `z`. Data in `z` should be a {2D array}. Coordinates in `x` and `y` can either be 1D {arrays} or {2D arrays} (e.g. to graph parametric surfaces). If not provided in `x` and `y`, the x and y coordinates are assumed to be linear starting at 0 with a unit step. The color scale corresponds to the `z` values by default. For custom color scales, use `surfacecolor` which should be a {2D array}, where its bounds can be controlled using `cmin` and `cmax`." }, "attributes": { - "type": "scatter3d", + "type": "surface", "visible": { "valType": "enumerated", "values": [ @@ -13293,8 +14962,8 @@ "min": 0, "max": 1, "dflt": 1, - "editType": "style", - "description": "Sets the opacity of the trace." + "editType": "calc", + "description": "Sets the opacity of the surface." }, "name": { "valType": "string", @@ -13456,21 +15125,21 @@ "editType": "calc", "role": "object" }, - "x": { + "z": { "valType": "data_array", + "description": "Sets the z coordinates.", "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinates.", "role": "data" }, - "y": { + "x": { "valType": "data_array", + "description": "Sets the x coordinates.", "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinates.", "role": "data" }, - "z": { + "y": { "valType": "data_array", - "description": "Sets the z coordinates.", + "description": "Sets the y coordinates.", "editType": "calc+clearAxisTypes", "role": "data" }, @@ -13479,1309 +15148,1907 @@ "role": "info", "dflt": "", "arrayOk": true, + "description": "Sets the text elements associated with each z value. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels.", + "editType": "calc" + }, + "surfacecolor": { + "valType": "data_array", + "description": "Sets the surface color values, used for setting a color scale independent of `z`.", "editType": "calc", - "description": "Sets text elements associated with each (x,y,z) triplet. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y,z) coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + "role": "data" }, - "hovertext": { - "valType": "string", + "cauto": { + "valType": "boolean", "role": "info", - "dflt": "", - "arrayOk": true, + "dflt": true, "editType": "calc", - "description": "Sets text elements associated with each (x,y,z) triplet. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y,z) coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." + "impliedEdits": {}, + "description": "Determines the whether or not the color domain is computed with respect to the input data." }, - "mode": { - "valType": "flaglist", - "flags": [ - "lines", - "markers", - "text" - ], - "extras": [ - "none" - ], + "cmin": { + "valType": "number", "role": "info", + "dflt": null, "editType": "calc", - "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*.", - "dflt": "lines+markers" + "impliedEdits": { + "zauto": false + }, + "description": "Sets the lower bound of color domain." }, - "surfaceaxis": { - "valType": "enumerated", + "cmax": { + "valType": "number", "role": "info", - "values": [ - -1, - 0, - 1, - 2 - ], - "dflt": -1, - "description": "If *-1*, the scatter points are not fill with a surface If *0*, *1*, *2*, the scatter points are filled with a Delaunay surface about the x, y, z respectively.", - "editType": "calc" - }, - "surfacecolor": { - "valType": "color", - "role": "style", - "description": "Sets the surface fill color.", - "editType": "calc" - }, - "projection": { - "x": { - "show": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Sets whether or not projections are shown along the x axis.", - "editType": "calc" - }, - "opacity": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "description": "Sets the projection color.", - "editType": "calc" - }, - "scale": { - "valType": "number", - "role": "style", - "min": 0, - "max": 10, - "dflt": 0.6666666666666666, - "description": "Sets the scale factor determining the size of the projection marker points.", - "editType": "calc" - }, - "editType": "calc", - "role": "object" - }, - "y": { - "show": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Sets whether or not projections are shown along the y axis.", - "editType": "calc" - }, - "opacity": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "description": "Sets the projection color.", - "editType": "calc" - }, - "scale": { - "valType": "number", - "role": "style", - "min": 0, - "max": 10, - "dflt": 0.6666666666666666, - "description": "Sets the scale factor determining the size of the projection marker points.", - "editType": "calc" - }, - "editType": "calc", - "role": "object" + "dflt": null, + "editType": "calc", + "impliedEdits": { + "zauto": false }, - "z": { - "show": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Sets whether or not projections are shown along the z axis.", - "editType": "calc" - }, - "opacity": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "description": "Sets the projection color.", - "editType": "calc" - }, - "scale": { - "valType": "number", - "role": "style", - "min": 0, - "max": 10, - "dflt": 0.6666666666666666, - "description": "Sets the scale factor determining the size of the projection marker points.", - "editType": "calc" - }, - "editType": "calc", - "role": "object" + "description": "Sets the upper bound of color domain." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false }, + "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": false, "editType": "calc", - "role": "object" + "impliedEdits": {}, + "description": "Determines whether or not the colorscale is picked using the sign of the input z values." }, - "connectgaps": { + "reversescale": { "valType": "boolean", + "role": "style", "dflt": false, + "editType": "calc", + "description": "Reverses the colorscale." + }, + "showscale": { + "valType": "boolean", "role": "info", + "dflt": true, "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." + "description": "Determines whether or not a colorbar is displayed for this trace." }, - "line": { - "width": { + "colorbar": { + "thicknessmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "calc" + }, + "thickness": { "valType": "number", + "role": "style", "min": 0, - "dflt": 2, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "calc" + }, + "lenmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "info", + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "calc" + }, + "len": { + "valType": "number", + "min": 0, + "dflt": 1, "role": "style", - "editType": "calc", - "description": "Sets the line width (in px)." + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "calc" }, - "dash": { + "x": { + "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "calc" + }, + "xanchor": { "valType": "enumerated", "values": [ - "solid", - "dot", - "dash", - "longdash", - "dashdot", - "longdashdot" + "left", + "center", + "right" ], - "dflt": "solid", + "dflt": "left", "role": "style", - "description": "Sets the dash style of the lines.", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", "editType": "calc" }, - "showscale": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Has an effect only if `line.color` is set to a numerical array. Determines whether or not a colorbar is displayed.", + "xpad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the x direction.", "editType": "calc" }, - "color": { + "y": { + "valType": "number", + "role": "style", + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "calc" + }, + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], + "role": "style", + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "calc" + }, + "ypad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "calc" + }, + "outlinecolor": { "valType": "color", - "arrayOk": true, + "dflt": "#444", "role": "style", "editType": "calc", - "description": "Sets the line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "description": "Sets the axis line color." }, - "colorscale": { - "valType": "colorscale", + "outlinewidth": { + "valType": "number", + "min": 0, + "dflt": 1, "role": "style", "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `line.cmin` and `line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + "description": "Sets the width (in px) of the axis line." }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, + "bordercolor": { + "valType": "color", + "dflt": "#444", + "role": "style", "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + "description": "Sets the axis line color." }, - "cmax": { + "borderwidth": { "valType": "number", + "role": "style", + "min": 0, + "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "calc" + }, + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "calc" + }, + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], "role": "info", - "dflt": null, + "editType": "calc", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + }, + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + }, + "tick0": { + "valType": "any", + "role": "style", "editType": "calc", "impliedEdits": { - "cauto": false + "tickmode": "linear" }, - "description": "Has an effect only if `line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `line.color` array index, and if set, `line.cmin` must be set as well." + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, + "dtick": { + "valType": "any", + "role": "style", "editType": "calc", "impliedEdits": { - "cauto": false + "tickmode": "linear" }, - "description": "Has an effect only if `line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `line.color` array index, and if set, `line.cmax` must be set as well." + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, + "tickvals": { + "valType": "data_array", "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, + "ticktext": { + "valType": "data_array", "editType": "calc", - "description": "Has an effect only if `line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" }, - "editType": "calc", - "role": "object", - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "marker": { - "symbol": { + "ticks": { "valType": "enumerated", "values": [ - "circle", - "circle-open", - "square", - "square-open", - "diamond", - "diamond-open", - "cross", - "x" + "outside", + "inside", + "" ], "role": "style", - "dflt": "circle", - "arrayOk": true, - "description": "Sets the marker symbol type.", - "editType": "calc" - }, - "size": { - "valType": "number", - "min": 0, - "dflt": 8, - "arrayOk": true, - "role": "style", "editType": "calc", - "description": "Sets the marker size (in px)." + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" }, - "sizeref": { + "ticklen": { "valType": "number", - "dflt": 1, + "min": 0, + "dflt": 5, "role": "style", "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." + "description": "Sets the tick length (in px)." }, - "sizemin": { + "tickwidth": { "valType": "number", "min": 0, - "dflt": 0, + "dflt": 1, "role": "style", "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." - }, - "sizemode": { - "valType": "enumerated", - "values": [ - "diameter", - "area" - ], - "dflt": "diameter", - "role": "info", - "editType": "calc", - "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." + "description": "Sets the tick width (in px)." }, - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "arrayOk": false, + "tickcolor": { + "valType": "color", + "dflt": "#444", "role": "style", "editType": "calc", - "description": "Sets the marker opacity. Note that the marker opacity for scatter3d traces must be a scalar value for performance reasons. To set a blending opacity value (i.e. which is not transparent), set *marker.color* to an rgba color and use its alpha channel." + "description": "Sets the tick color." }, - "showscale": { + "showticklabels": { "valType": "boolean", - "role": "info", - "dflt": false, + "dflt": true, + "role": "style", "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." + "description": "Determines whether or not the tick labels are drawn." }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], + "tickfont": { + "family": { + "valType": "string", "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", "editType": "calc" }, - "thickness": { + "size": { "valType": "number", "role": "style", - "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "min": 1, "editType": "calc" }, - "lenmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "color": { + "valType": "color", + "role": "style", "editType": "calc" }, - "len": { - "valType": "number", - "min": 0, - "dflt": 1, + "description": "Sets the color bar's tick label font", + "editType": "calc", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", + "role": "style", + "editType": "calc", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + }, + "tickformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + }, + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "calc" + }, + { + "valType": "any", + "editType": "calc" + } + ], + "editType": "calc", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "calc", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "Sets a tick label prefix." + }, + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + }, + "ticksuffix": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "Sets a tick label suffix." + }, + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "Same as `showtickprefix` but for tick suffixes." + }, + "separatethousands": { + "valType": "boolean", + "dflt": false, + "role": "style", + "editType": "calc", + "description": "If \"true\", even 4-digit integers are separated" + }, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "calc", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + }, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + }, + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", + "editType": "calc" + }, + "titlefont": { + "family": { + "valType": "string", "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", "editType": "calc" }, - "x": { + "size": { "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", + "min": 1, "editType": "calc" }, - "xanchor": { - "valType": "enumerated", - "values": [ - "left", - "center", - "right" - ], - "dflt": "left", + "color": { + "valType": "color", "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", "editType": "calc" }, - "xpad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", + "description": "Sets this color bar's title font.", + "editType": "calc", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "calc" + }, + "editType": "calc", + "role": "object", + "tickvalssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for tickvals .", + "editType": "none" + }, + "ticktextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ticktext .", + "editType": "none" + } + }, + "contours": { + "x": { + "show": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not contour lines about the x dimension are drawn.", "editType": "calc" }, - "y": { - "valType": "number", - "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "calc" + "project": { + "x": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the x plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "editType": "calc" + }, + "y": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the y plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "editType": "calc" + }, + "z": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the z plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "editType": "calc" + }, + "editType": "calc", + "role": "object" }, - "yanchor": { - "valType": "enumerated", - "values": [ - "top", - "middle", - "bottom" - ], + "color": { + "valType": "color", "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "dflt": "#444", + "description": "Sets the color of the contour lines.", "editType": "calc" }, - "ypad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", + "usecolormap": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "An alternate to *color*. Determines whether or not the contour lines are colored using the trace *colorscale*.", "editType": "calc" }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "calc", - "description": "Sets the axis line color." - }, - "outlinewidth": { + "width": { "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the axis line." - }, - "bordercolor": { - "valType": "color", - "dflt": "#444", "role": "style", - "editType": "calc", - "description": "Sets the axis line color." + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the contour lines.", + "editType": "calc" }, - "borderwidth": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", + "highlight": { + "valType": "boolean", + "role": "info", + "dflt": true, + "description": "Determines whether or not contour lines about the x dimension are highlighted on hover.", "editType": "calc" }, - "bgcolor": { + "highlightcolor": { "valType": "color", "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", + "dflt": "#444", + "description": "Sets the color of the highlighted contour lines.", "editType": "calc" }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], - "role": "info", - "editType": "calc", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." - }, - "nticks": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", - "editType": "calc", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "calc", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "calc", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" - }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], - "role": "style", - "editType": "calc", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" - }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, - "role": "style", - "editType": "calc", - "description": "Sets the tick length (in px)." - }, - "tickwidth": { + "highlightwidth": { "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "calc", - "description": "Sets the tick width (in px)." - }, - "tickcolor": { - "valType": "color", - "dflt": "#444", "role": "style", - "editType": "calc", - "description": "Sets the tick color." + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the highlighted contour lines.", + "editType": "calc" }, - "showticklabels": { + "editType": "calc", + "role": "object" + }, + "y": { + "show": { "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "calc", - "description": "Determines whether or not the tick labels are drawn." + "role": "info", + "dflt": false, + "description": "Determines whether or not contour lines about the y dimension are drawn.", + "editType": "calc" }, - "tickfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "project": { + "x": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the x plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", "editType": "calc" }, - "size": { - "valType": "number", - "role": "style", - "min": 1, + "y": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the y plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", "editType": "calc" }, - "color": { - "valType": "color", - "role": "style", + "z": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the z plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", "editType": "calc" }, - "description": "Sets the color bar's tick label font", - "editType": "calc", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", "editType": "calc", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." - }, - "tickformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "calc" - }, - { - "valType": "any", - "editType": "calc" - } - ], - "editType": "calc", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "calc", - "role": "object" - } - }, "role": "object" }, - "tickprefix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets a tick label prefix." - }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." - }, - "ticksuffix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets a tick label suffix." - }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "color": { + "valType": "color", "role": "style", - "editType": "calc", - "description": "Same as `showtickprefix` but for tick suffixes." + "dflt": "#444", + "description": "Sets the color of the contour lines.", + "editType": "calc" }, - "separatethousands": { + "usecolormap": { "valType": "boolean", + "role": "info", "dflt": false, - "role": "style", - "editType": "calc", - "description": "If \"true\", even 4-digit integers are separated" - }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", - "role": "style", - "editType": "calc", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + "description": "An alternate to *color*. Determines whether or not the contour lines are colored using the trace *colorscale*.", + "editType": "calc" }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "width": { + "valType": "number", "role": "style", - "editType": "calc", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the contour lines.", + "editType": "calc" }, - "title": { - "valType": "string", + "highlight": { + "valType": "boolean", "role": "info", - "description": "Sets the title of the color bar.", + "dflt": true, + "description": "Determines whether or not contour lines about the y dimension are highlighted on hover.", "editType": "calc" }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "calc" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc" - }, - "description": "Sets this color bar's title font.", - "editType": "calc", - "role": "object" + "highlightcolor": { + "valType": "color", + "role": "style", + "dflt": "#444", + "description": "Sets the color of the highlighted contour lines.", + "editType": "calc" }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], + "highlightwidth": { + "valType": "number", "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the highlighted contour lines.", "editType": "calc" }, "editType": "calc", - "role": "object", - "tickvalssrc": { - "valType": "string", + "role": "object" + }, + "z": { + "show": { + "valType": "boolean", "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", - "editType": "none" + "dflt": false, + "description": "Determines whether or not contour lines about the z dimension are drawn.", + "editType": "calc" }, - "ticktextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", - "editType": "none" - } - }, - "line": { - "width": { - "valType": "number", - "min": 0, - "arrayOk": false, - "role": "style", + "project": { + "x": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the x plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "editType": "calc" + }, + "y": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the y plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "editType": "calc" + }, + "z": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not these contour lines are projected on the z plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "editType": "calc" + }, "editType": "calc", - "description": "Sets the width (in px) of the lines bounding the marker points." + "role": "object" }, "color": { "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + "dflt": "#444", + "description": "Sets the color of the contour lines.", + "editType": "calc" }, - "cauto": { + "usecolormap": { "valType": "boolean", "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + "dflt": false, + "description": "An alternate to *color*. Determines whether or not the contour lines are colored using the trace *colorscale*.", + "editType": "calc" }, - "cmax": { + "width": { "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + "role": "style", + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the contour lines.", + "editType": "calc" }, - "cmin": { - "valType": "number", + "highlight": { + "valType": "boolean", "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + "dflt": true, + "description": "Determines whether or not contour lines about the z dimension are highlighted on hover.", + "editType": "calc" }, - "autocolorscale": { - "valType": "boolean", + "highlightcolor": { + "valType": "color", "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "dflt": "#444", + "description": "Sets the color of the highlighted contour lines.", + "editType": "calc" }, - "reversescale": { - "valType": "boolean", + "highlightwidth": { + "valType": "number", "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the highlighted contour lines.", + "editType": "calc" }, "editType": "calc", - "role": "object", - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } + "role": "object" }, - "color": { - "valType": "color", - "arrayOk": true, + "editType": "calc", + "role": "object" + }, + "hidesurface": { + "valType": "boolean", + "role": "info", + "dflt": false, + "description": "Determines whether or not a surface is drawn. For example, set `hidesurface` to *false* `contours.x.show` to *true* and `contours.y.show` to *true* to draw a wire frame plot.", + "editType": "calc" + }, + "lightposition": { + "x": { + "valType": "number", "role": "style", - "editType": "calc", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + "min": -100000, + "max": 100000, + "dflt": 10, + "description": "Numeric vector, representing the X coordinate for each vertex.", + "editType": "calc" }, - "colorscale": { - "valType": "colorscale", + "y": { + "valType": "number", "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + "min": -100000, + "max": 100000, + "dflt": 10000, + "description": "Numeric vector, representing the Y coordinate for each vertex.", + "editType": "calc" }, - "cauto": { + "z": { + "valType": "number", + "role": "style", + "min": -100000, + "max": 100000, + "dflt": 0, + "description": "Numeric vector, representing the Z coordinate for each vertex.", + "editType": "calc" + }, + "editType": "calc", + "role": "object" + }, + "lighting": { + "ambient": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 0.8, + "description": "Ambient light increases overall color visibility but can wash out the image.", + "editType": "calc" + }, + "diffuse": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 0.8, + "description": "Represents the extent that incident rays are reflected in a range of angles.", + "editType": "calc" + }, + "specular": { + "valType": "number", + "role": "style", + "min": 0, + "max": 2, + "dflt": 0.05, + "description": "Represents the level that incident rays are reflected in a single direction, causing shine.", + "editType": "calc" + }, + "roughness": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 0.5, + "description": "Alters specular reflection; the rougher the surface, the wider and less contrasty the shine.", + "editType": "calc" + }, + "fresnel": { + "valType": "number", + "role": "style", + "min": 0, + "max": 5, + "dflt": 0.2, + "description": "Represents the reflectance as a dependency of the viewing angle; e.g. paper is reflective when viewing it from the edge of the paper (almost 90 degrees), causing shine.", + "editType": "calc" + }, + "editType": "calc", + "role": "object" + }, + "_deprecated": { + "zauto": { "valType": "boolean", "role": "info", "dflt": true, "editType": "calc", "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + "description": "Obsolete. Use `cauto` instead." }, - "cmax": { + "zmin": { "valType": "number", "role": "info", "dflt": null, "editType": "calc", "impliedEdits": { - "cauto": false + "zauto": false }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + "description": "Obsolete. Use `cmin` instead." }, - "cmin": { + "zmax": { "valType": "number", "role": "info", "dflt": null, "editType": "calc", "impliedEdits": { - "cauto": false + "zauto": false }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + "description": "Obsolete. Use `cmax` instead." + } + }, + "xcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `x` date data." + }, + "ycalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `y` date data." + }, + "zcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `z` date data." + }, + "scene": { + "valType": "subplotid", + "role": "info", + "dflt": "scene", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's 3D coordinate system and a 3D scene. If *scene* (the default value), the (x,y,z) coordinates refer to `layout.scene`. If *scene2*, the (x,y,z) coordinates refer to `layout.scene2`, and so on." + }, + "idssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ids .", + "editType": "none" + }, + "customdatasrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for customdata .", + "editType": "none" + }, + "hoverinfosrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for hoverinfo .", + "editType": "none" + }, + "zsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for z .", + "editType": "none" + }, + "xsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for x .", + "editType": "none" + }, + "ysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for y .", + "editType": "none" + }, + "textsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for text .", + "editType": "none" + }, + "surfacecolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for surfacecolor .", + "editType": "none" + } + } + }, + "mesh3d": { + "meta": { + "description": "Draws sets of triangles with coordinates given by three 1-dimensional arrays in `x`, `y`, `z` and (1) a sets of `i`, `j`, `k` indices (2) Delaunay triangulation or (3) the Alpha-shape algorithm or (4) the Convex-hull algorithm" + }, + "attributes": { + "type": "mesh3d", + "visible": { + "valType": "enumerated", + "values": [ + true, + false, + "legendonly" + ], + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." + }, + "showlegend": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "style", + "description": "Determines whether or not an item corresponding to this trace is shown in the legend." + }, + "legendgroup": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "style", + "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." + }, + "opacity": { + "valType": "number", + "role": "style", + "min": 0, + "max": 1, + "dflt": 1, + "editType": "calc", + "description": "Sets the opacity of the surface." + }, + "name": { + "valType": "string", + "role": "info", + "editType": "style", + "description": "Sets the trace name. The trace name appear as the legend item and on hover." + }, + "uid": { + "valType": "string", + "role": "info", + "dflt": "", + "editType": "calc" + }, + "ids": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", + "role": "data" + }, + "customdata": { + "valType": "data_array", + "editType": "calc", + "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", + "role": "data" + }, + "selectedpoints": { + "valType": "any", + "role": "info", + "editType": "calc", + "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." + }, + "hoverinfo": { + "valType": "flaglist", + "role": "info", + "flags": [ + "x", + "y", + "z", + "text", + "name" + ], + "extras": [ + "all", + "none", + "skip" + ], + "arrayOk": true, + "dflt": "all", + "editType": "calc", + "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." + }, + "hoverlabel": { + "bgcolor": { + "valType": "color", + "role": "style", + "arrayOk": true, + "editType": "none", + "description": "Sets the background color of the hover labels for this trace" }, - "autocolorscale": { - "valType": "boolean", + "bordercolor": { + "valType": "color", "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + "arrayOk": true, + "editType": "none", + "description": "Sets the border color of the hover labels for this trace." }, - "reversescale": { - "valType": "boolean", + "font": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "editType": "none", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "none", + "arrayOk": true + }, + "color": { + "valType": "color", + "role": "style", + "editType": "none", + "arrayOk": true + }, + "editType": "none", + "description": "Sets the font used in hover labels.", + "role": "object", + "familysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "namelength": { + "valType": "integer", + "min": -1, + "arrayOk": true, "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + "editType": "none", + "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." }, "editType": "calc", "role": "object", - "symbolsrc": { + "bgcolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for symbol .", + "description": "Sets the source reference on plot.ly for bgcolor .", "editType": "none" }, - "sizesrc": { + "bordercolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for size .", + "description": "Sets the source reference on plot.ly for bordercolor .", "editType": "none" }, - "colorsrc": { + "namelengthsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", + "description": "Sets the source reference on plot.ly for namelength .", "editType": "none" } }, - "textposition": { - "valType": "enumerated", - "values": [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right" - ], - "dflt": "top center", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." - }, - "textfont": { - "family": { + "stream": { + "token": { "valType": "string", - "role": "style", "noBlank": true, "strict": true, + "role": "info", "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true + "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." }, - "size": { + "maxpoints": { "valType": "number", - "role": "style", - "min": 1, + "min": 0, + "max": 10000, + "dflt": 500, + "role": "info", "editType": "calc", - "arrayOk": true + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "arrayOk": true + "editType": "calc", + "role": "object" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the color of the whole mesh" + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false }, + "description": "Sets the colorscale and only has an effect if `color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, "editType": "calc", - "description": "Sets the text font.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" + "impliedEdits": {}, + "description": "Has an effect only if `color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" + "description": "Has an effect only if `color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `color` array index, and if set, `cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } + "description": "Has an effect only if `color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `color` array index, and if set, `cmax` must be set as well." }, - "error_x": { - "visible": { + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "x": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the X coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex.", + "role": "data" + }, + "y": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the Y coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex.", + "role": "data" + }, + "z": { + "valType": "data_array", + "editType": "calc+clearAxisTypes", + "description": "Sets the Z coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex.", + "role": "data" + }, + "i": { + "valType": "data_array", + "editType": "calc", + "description": "A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the *first* vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `i[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `i` represents a point in space, which is the first vertex of a triangle.", + "role": "data" + }, + "j": { + "valType": "data_array", + "editType": "calc", + "description": "A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the *second* vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `j[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `j` represents a point in space, which is the second vertex of a triangle.", + "role": "data" + }, + "k": { + "valType": "data_array", + "editType": "calc", + "description": "A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the *third* vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `k[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `k` represents a point in space, which is the third vertex of a triangle.", + "role": "data" + }, + "text": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, + "editType": "calc", + "description": "Sets the text elements associated with the vertices. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + }, + "delaunayaxis": { + "valType": "enumerated", + "role": "info", + "values": [ + "x", + "y", + "z" + ], + "dflt": "z", + "editType": "calc", + "description": "Sets the Delaunay axis, which is the axis that is perpendicular to the surface of the Delaunay triangulation. It has an effect if `i`, `j`, `k` are not provided and `alphahull` is set to indicate Delaunay triangulation." + }, + "alphahull": { + "valType": "number", + "role": "style", + "dflt": -1, + "editType": "calc", + "description": "Determines how the mesh surface triangles are derived from the set of vertices (points) represented by the `x`, `y` and `z` arrays, if the `i`, `j`, `k` arrays are not supplied. For general use of `mesh3d` it is preferred that `i`, `j`, `k` are supplied. If *-1*, Delaunay triangulation is used, which is mainly suitable if the mesh is a single, more or less layer surface that is perpendicular to `delaunayaxis`. In case the `delaunayaxis` intersects the mesh surface at more than one point it will result triangles that are very long in the dimension of `delaunayaxis`. If *>0*, the alpha-shape algorithm is used. In this case, the positive `alphahull` value signals the use of the alpha-shape algorithm, _and_ its value acts as the parameter for the mesh fitting. If *0*, the convex-hull algorithm is used. It is suitable for convex bodies or if the intention is to enclose the `x`, `y` and `z` point set into a convex hull." + }, + "intensity": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the vertex intensity values, used for plotting fields on meshes", + "role": "data" + }, + "vertexcolor": { + "valType": "data_array", + "role": "data", + "editType": "calc", + "description": "Sets the color of each vertex Overrides *color*." + }, + "facecolor": { + "valType": "data_array", + "role": "data", + "editType": "calc", + "description": "Sets the color of each face Overrides *color* and *vertexcolor*." + }, + "flatshading": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low-poly look via flat reflections." + }, + "contour": { + "show": { "valType": "boolean", "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." + "dflt": false, + "description": "Sets whether or not dynamic contours are shown on hover", + "editType": "calc" }, - "type": { + "color": { + "valType": "color", + "role": "style", + "dflt": "#444", + "description": "Sets the color of the contour lines.", + "editType": "calc" + }, + "width": { + "valType": "number", + "role": "style", + "min": 1, + "max": 16, + "dflt": 2, + "description": "Sets the width of the contour lines.", + "editType": "calc" + }, + "editType": "calc", + "role": "object" + }, + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not a colorbar is displayed for this trace." + }, + "colorbar": { + "thicknessmode": { "valType": "enumerated", "values": [ - "percent", - "constant", - "sqrt", - "data" + "fraction", + "pixels" ], - "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "colorbars" }, - "symmetric": { - "valType": "boolean", + "thickness": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "colorbars" + }, + "lenmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "colorbars" }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" + "len": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", + "editType": "colorbars" }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" + "x": { + "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, + "role": "style", + "description": "Sets the x position of the color bar (in plot fraction).", + "editType": "colorbars" }, - "value": { + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", + "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", + "editType": "colorbars" + }, + "xpad": { "valType": "number", + "role": "style", "min": 0, "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "colorbars" }, - "valueminus": { + "y": { + "valType": "number", + "role": "style", + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", + "editType": "colorbars" + }, + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], + "role": "style", + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "colorbars" + }, + "ypad": { "valType": "number", + "role": "style", "min": 0, "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + "description": "Sets the amount of padding (in px) along the y direction.", + "editType": "colorbars" }, - "traceref": { - "valType": "integer", + "outlinecolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "outlinewidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the width (in px) of the axis line." + }, + "bordercolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the axis line color." + }, + "borderwidth": { + "valType": "number", + "role": "style", "min": 0, "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", + "editType": "colorbars" + }, + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", + "editType": "colorbars" + }, + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], "role": "info", - "editType": "calc" + "editType": "colorbars", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." }, - "tracerefminus": { + "nticks": { "valType": "integer", "min": 0, "dflt": 0, - "role": "info", - "editType": "calc" + "role": "style", + "editType": "colorbars", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + }, + "tick0": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "colorbars", + "impliedEdits": { + "tickmode": "linear" + }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" + }, + "ticktext": { + "valType": "data_array", + "editType": "colorbars", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" + }, + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "colorbars", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" + }, + "ticklen": { + "valType": "number", + "min": 0, + "dflt": 5, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick length (in px)." + }, + "tickwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "colorbars", + "description": "Sets the tick width (in px)." + }, + "tickcolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "colorbars", + "description": "Sets the tick color." + }, + "showticklabels": { + "valType": "boolean", + "dflt": true, + "role": "style", + "editType": "colorbars", + "description": "Determines whether or not the tick labels are drawn." + }, + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets the color bar's tick label font", + "editType": "colorbars", + "role": "object" }, - "copy_zstyle": { - "valType": "boolean", + "tickangle": { + "valType": "angle", + "dflt": "auto", "role": "style", - "editType": "calc" + "editType": "colorbars", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." }, - "color": { - "valType": "color", + "tickformat": { + "valType": "string", + "dflt": "", "role": "style", - "editType": "calc", - "description": "Sets the stoke color of the error bars." + "editType": "colorbars", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" }, - "thickness": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "calc", - "description": "Sets the thickness (in px) of the error bars." + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "colorbars" + }, + { + "valType": "any", + "editType": "colorbars" + } + ], + "editType": "colorbars", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "colorbars", + "role": "object" + } + }, + "role": "object" }, - "width": { - "valType": "number", - "min": 0, + "tickprefix": { + "valType": "string", + "dflt": "", "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." - }, - "editType": "calc", - "_deprecated": { - "opacity": { - "valType": "number", - "role": "style", - "editType": "calc", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } + "editType": "colorbars", + "description": "Sets a tick label prefix." }, - "role": "object", - "arraysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for array .", - "editType": "none" + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." }, - "arrayminussrc": { + "ticksuffix": { "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", - "editType": "none" - } - }, - "error_y": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." + "dflt": "", + "role": "style", + "editType": "colorbars", + "description": "Sets a tick label suffix." }, - "type": { + "showticksuffix": { "valType": "enumerated", "values": [ - "percent", - "constant", - "sqrt", - "data" + "all", + "first", + "last", + "none" ], - "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." - }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." - }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" - }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" - }, - "value": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." - }, - "valueminus": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" - }, - "traceref": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "calc" - }, - "tracerefminus": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "calc" + "dflt": "all", + "role": "style", + "editType": "colorbars", + "description": "Same as `showtickprefix` but for tick suffixes." }, - "copy_zstyle": { + "separatethousands": { "valType": "boolean", + "dflt": false, "role": "style", - "editType": "calc" + "editType": "colorbars", + "description": "If \"true\", even 4-digit integers are separated" }, - "color": { - "valType": "color", + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", "role": "style", - "editType": "calc", - "description": "Sets the stoke color of the error bars." + "editType": "colorbars", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." }, - "thickness": { - "valType": "number", - "min": 0, - "dflt": 2, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", "role": "style", - "editType": "calc", - "description": "Sets the thickness (in px) of the error bars." + "editType": "colorbars", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." }, - "width": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", + "editType": "colorbars" }, - "editType": "calc", - "_deprecated": { - "opacity": { + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "colorbars" + }, + "size": { "valType": "number", "role": "style", - "editType": "calc", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } + "min": 1, + "editType": "colorbars" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "colorbars" + }, + "description": "Sets this color bar's title font.", + "editType": "colorbars", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "colorbars" }, + "editType": "colorbars", "role": "object", - "arraysrc": { + "tickvalssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for array .", + "description": "Sets the source reference on plot.ly for tickvals .", "editType": "none" }, - "arrayminussrc": { + "ticktextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", + "description": "Sets the source reference on plot.ly for ticktext .", "editType": "none" } }, - "error_z": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." - }, - "type": { - "valType": "enumerated", - "values": [ - "percent", - "constant", - "sqrt", - "data" - ], - "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." - }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." + "lightposition": { + "x": { + "valType": "number", + "role": "style", + "min": -100000, + "max": 100000, + "dflt": 100000, + "description": "Numeric vector, representing the X coordinate for each vertex.", + "editType": "calc" }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" + "y": { + "valType": "number", + "role": "style", + "min": -100000, + "max": 100000, + "dflt": 100000, + "description": "Numeric vector, representing the Y coordinate for each vertex.", + "editType": "calc" }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" + "z": { + "valType": "number", + "role": "style", + "min": -100000, + "max": 100000, + "dflt": 0, + "description": "Numeric vector, representing the Z coordinate for each vertex.", + "editType": "calc" }, - "value": { + "editType": "calc", + "role": "object" + }, + "lighting": { + "vertexnormalsepsilon": { "valType": "number", + "role": "style", "min": 0, - "dflt": 10, - "role": "info", + "max": 1, + "dflt": 1e-12, "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + "description": "Epsilon for vertex normals calculation avoids math issues arising from degenerate geometry." }, - "valueminus": { + "facenormalsepsilon": { "valType": "number", + "role": "style", "min": 0, - "dflt": 10, - "role": "info", + "max": 1, + "dflt": 0.000001, "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + "description": "Epsilon for face normals calculation avoids math issues arising from degenerate geometry." }, - "traceref": { - "valType": "integer", + "editType": "calc", + "ambient": { + "valType": "number", + "role": "style", "min": 0, - "dflt": 0, - "role": "info", + "max": 1, + "dflt": 0.8, + "description": "Ambient light increases overall color visibility but can wash out the image.", "editType": "calc" }, - "tracerefminus": { - "valType": "integer", + "diffuse": { + "valType": "number", + "role": "style", "min": 0, - "dflt": 0, - "role": "info", + "max": 1, + "dflt": 0.8, + "description": "Represents the extent that incident rays are reflected in a range of angles.", "editType": "calc" }, - "color": { - "valType": "color", + "specular": { + "valType": "number", "role": "style", - "editType": "calc", - "description": "Sets the stoke color of the error bars." + "min": 0, + "max": 2, + "dflt": 0.05, + "description": "Represents the level that incident rays are reflected in a single direction, causing shine.", + "editType": "calc" }, - "thickness": { + "roughness": { "valType": "number", - "min": 0, - "dflt": 2, "role": "style", - "editType": "calc", - "description": "Sets the thickness (in px) of the error bars." + "min": 0, + "max": 1, + "dflt": 0.5, + "description": "Alters specular reflection; the rougher the surface, the wider and less contrasty the shine.", + "editType": "calc" }, - "width": { + "fresnel": { "valType": "number", - "min": 0, "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." - }, - "editType": "calc", - "_deprecated": { - "opacity": { - "valType": "number", - "role": "style", - "editType": "calc", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } - }, - "role": "object", - "arraysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for array .", - "editType": "none" + "min": 0, + "max": 5, + "dflt": 0.2, + "description": "Represents the reflectance as a dependency of the viewing angle; e.g. paper is reflective when viewing it from the edge of the paper (almost 90 degrees), causing shine.", + "editType": "calc" }, - "arrayminussrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", - "editType": "none" - } + "role": "object" }, "xcalendar": { "valType": "enumerated", @@ -14901,32 +17168,57 @@ "description": "Sets the source reference on plot.ly for z .", "editType": "none" }, + "isrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for i .", + "editType": "none" + }, + "jsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for j .", + "editType": "none" + }, + "ksrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for k .", + "editType": "none" + }, "textsrc": { "valType": "string", "role": "info", "description": "Sets the source reference on plot.ly for text .", "editType": "none" }, - "hovertextsrc": { + "intensitysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for hovertext .", + "description": "Sets the source reference on plot.ly for intensity .", "editType": "none" }, - "textpositionsrc": { + "vertexcolorsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for textposition .", + "description": "Sets the source reference on plot.ly for vertexcolor .", + "editType": "none" + }, + "facecolorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for facecolor .", "editType": "none" } } }, - "surface": { + "scattergeo": { "meta": { - "description": "The data the describes the coordinates of the surface is set in `z`. Data in `z` should be a {2D array}. Coordinates in `x` and `y` can either be 1D {arrays} or {2D arrays} (e.g. to graph parametric surfaces). If not provided in `x` and `y`, the x and y coordinates are assumed to be linear starting at 0 with a unit step. The color scale corresponds to the `z` values by default. For custom color scales, use `surfacecolor` which should be a {2D array}, where its bounds can be controlled using `cmin` and `cmax`." + "hrName": "scatter_geo", + "description": "The data visualized as scatter point or lines on a geographic map is provided either by longitude/latitude pairs in `lon` and `lat` respectively or by geographic location IDs or names in `locations`." }, "attributes": { - "type": "surface", + "type": "scattergeo", "visible": { "valType": "enumerated", "values": [ @@ -14959,8 +17251,8 @@ "min": 0, "max": 1, "dflt": 1, - "editType": "calc", - "description": "Sets the opacity of the surface." + "editType": "style", + "description": "Sets the opacity of the trace." }, "name": { "valType": "string", @@ -14996,9 +17288,9 @@ "valType": "flaglist", "role": "info", "flags": [ - "x", - "y", - "z", + "lon", + "lat", + "location", "text", "name" ], @@ -15117,978 +17409,1257 @@ "dflt": 500, "role": "info", "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." - }, - "editType": "calc", - "role": "object" - }, - "z": { - "valType": "data_array", - "description": "Sets the z coordinates.", - "editType": "calc+clearAxisTypes", - "role": "data" - }, - "x": { - "valType": "data_array", - "description": "Sets the x coordinates.", - "editType": "calc+clearAxisTypes", - "role": "data" - }, - "y": { - "valType": "data_array", - "description": "Sets the y coordinates.", - "editType": "calc+clearAxisTypes", - "role": "data" - }, - "text": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "description": "Sets the text elements associated with each z value. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels.", - "editType": "calc" + "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." + }, + "editType": "calc", + "role": "object" }, - "surfacecolor": { + "lon": { "valType": "data_array", - "description": "Sets the surface color values, used for setting a color scale independent of `z`.", + "description": "Sets the longitude coordinates (in degrees East).", "editType": "calc", "role": "data" }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, + "lat": { + "valType": "data_array", + "description": "Sets the latitude coordinates (in degrees North).", "editType": "calc", - "impliedEdits": {}, - "description": "Determines the whether or not the color domain is computed with respect to the input data." + "role": "data" }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, + "locations": { + "valType": "data_array", + "description": "Sets the coordinates via location IDs or names. Coordinates correspond to the centroid of each location given. See `locationmode` for more info.", "editType": "calc", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the lower bound of color domain." + "role": "data" }, - "cmax": { - "valType": "number", + "locationmode": { + "valType": "enumerated", + "values": [ + "ISO-3", + "USA-states", + "country names" + ], "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the upper bound of color domain." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" + "dflt": "ISO-3", + "description": "Determines the set of locations used to match entries in `locations` to regions on the map.", + "editType": "calc" }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": false, + "mode": { + "valType": "flaglist", + "flags": [ + "lines", + "markers", + "text" + ], + "extras": [ + "none" + ], + "role": "info", "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the colorscale is picked using the sign of the input z values." + "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*.", + "dflt": "markers" }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, + "text": { + "valType": "string", + "role": "info", + "dflt": "", + "arrayOk": true, "editType": "calc", - "description": "Reverses the colorscale." + "description": "Sets text elements associated with each (lon,lat) pair or item in `locations`. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) or `locations` coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." }, - "showscale": { - "valType": "boolean", + "hovertext": { + "valType": "string", "role": "info", - "dflt": true, + "dflt": "", + "arrayOk": true, "editType": "calc", - "description": "Determines whether or not a colorbar is displayed for this trace." + "description": "Sets hover text elements associated with each (lon,lat) pair or item in `locations`. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) or `locations` coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], + "textfont": { + "family": { + "valType": "string", "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "calc" + "noBlank": true, + "strict": true, + "editType": "calc", + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "arrayOk": true }, - "thickness": { + "size": { "valType": "number", "role": "style", - "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "calc" + "min": 1, + "editType": "calc", + "arrayOk": true }, - "lenmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "arrayOk": true + }, + "editType": "calc", + "description": "Sets the text font.", + "role": "object", + "familysrc": { + "valType": "string", "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "calc" + "description": "Sets the source reference on plot.ly for family .", + "editType": "none" }, - "len": { - "valType": "number", - "min": 0, - "dflt": 1, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } + }, + "textposition": { + "valType": "enumerated", + "values": [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right" + ], + "dflt": "middle center", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." + }, + "line": { + "color": { + "valType": "color", "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "calc" + "editType": "calc", + "description": "Sets the line color." }, - "x": { + "width": { "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, + "min": 0, + "dflt": 2, "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "calc" + "editType": "calc", + "description": "Sets the line width (in px)." }, - "xanchor": { - "valType": "enumerated", + "dash": { + "valType": "string", "values": [ - "left", - "center", - "right" + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" ], - "dflt": "left", - "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "calc" - }, - "xpad": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "calc" - }, - "y": { - "valType": "number", + "dflt": "solid", "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "calc" + "editType": "calc", + "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." }, - "yanchor": { + "editType": "calc", + "role": "object" + }, + "connectgaps": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." + }, + "marker": { + "symbol": { "valType": "enumerated", "values": [ - "top", - "middle", - "bottom" + 0, + "circle", + 100, + "circle-open", + 200, + "circle-dot", + 300, + "circle-open-dot", + 1, + "square", + 101, + "square-open", + 201, + "square-dot", + 301, + "square-open-dot", + 2, + "diamond", + 102, + "diamond-open", + 202, + "diamond-dot", + 302, + "diamond-open-dot", + 3, + "cross", + 103, + "cross-open", + 203, + "cross-dot", + 303, + "cross-open-dot", + 4, + "x", + 104, + "x-open", + 204, + "x-dot", + 304, + "x-open-dot", + 5, + "triangle-up", + 105, + "triangle-up-open", + 205, + "triangle-up-dot", + 305, + "triangle-up-open-dot", + 6, + "triangle-down", + 106, + "triangle-down-open", + 206, + "triangle-down-dot", + 306, + "triangle-down-open-dot", + 7, + "triangle-left", + 107, + "triangle-left-open", + 207, + "triangle-left-dot", + 307, + "triangle-left-open-dot", + 8, + "triangle-right", + 108, + "triangle-right-open", + 208, + "triangle-right-dot", + 308, + "triangle-right-open-dot", + 9, + "triangle-ne", + 109, + "triangle-ne-open", + 209, + "triangle-ne-dot", + 309, + "triangle-ne-open-dot", + 10, + "triangle-se", + 110, + "triangle-se-open", + 210, + "triangle-se-dot", + 310, + "triangle-se-open-dot", + 11, + "triangle-sw", + 111, + "triangle-sw-open", + 211, + "triangle-sw-dot", + 311, + "triangle-sw-open-dot", + 12, + "triangle-nw", + 112, + "triangle-nw-open", + 212, + "triangle-nw-dot", + 312, + "triangle-nw-open-dot", + 13, + "pentagon", + 113, + "pentagon-open", + 213, + "pentagon-dot", + 313, + "pentagon-open-dot", + 14, + "hexagon", + 114, + "hexagon-open", + 214, + "hexagon-dot", + 314, + "hexagon-open-dot", + 15, + "hexagon2", + 115, + "hexagon2-open", + 215, + "hexagon2-dot", + 315, + "hexagon2-open-dot", + 16, + "octagon", + 116, + "octagon-open", + 216, + "octagon-dot", + 316, + "octagon-open-dot", + 17, + "star", + 117, + "star-open", + 217, + "star-dot", + 317, + "star-open-dot", + 18, + "hexagram", + 118, + "hexagram-open", + 218, + "hexagram-dot", + 318, + "hexagram-open-dot", + 19, + "star-triangle-up", + 119, + "star-triangle-up-open", + 219, + "star-triangle-up-dot", + 319, + "star-triangle-up-open-dot", + 20, + "star-triangle-down", + 120, + "star-triangle-down-open", + 220, + "star-triangle-down-dot", + 320, + "star-triangle-down-open-dot", + 21, + "star-square", + 121, + "star-square-open", + 221, + "star-square-dot", + 321, + "star-square-open-dot", + 22, + "star-diamond", + 122, + "star-diamond-open", + 222, + "star-diamond-dot", + 322, + "star-diamond-open-dot", + 23, + "diamond-tall", + 123, + "diamond-tall-open", + 223, + "diamond-tall-dot", + 323, + "diamond-tall-open-dot", + 24, + "diamond-wide", + 124, + "diamond-wide-open", + 224, + "diamond-wide-dot", + 324, + "diamond-wide-open-dot", + 25, + "hourglass", + 125, + "hourglass-open", + 26, + "bowtie", + 126, + "bowtie-open", + 27, + "circle-cross", + 127, + "circle-cross-open", + 28, + "circle-x", + 128, + "circle-x-open", + 29, + "square-cross", + 129, + "square-cross-open", + 30, + "square-x", + 130, + "square-x-open", + 31, + "diamond-cross", + 131, + "diamond-cross-open", + 32, + "diamond-x", + 132, + "diamond-x-open", + 33, + "cross-thin", + 133, + "cross-thin-open", + 34, + "x-thin", + 134, + "x-thin-open", + 35, + "asterisk", + 135, + "asterisk-open", + 36, + "hash", + 136, + "hash-open", + 236, + "hash-dot", + 336, + "hash-open-dot", + 37, + "y-up", + 137, + "y-up-open", + 38, + "y-down", + 138, + "y-down-open", + 39, + "y-left", + 139, + "y-left-open", + 40, + "y-right", + 140, + "y-right-open", + 41, + "line-ew", + 141, + "line-ew-open", + 42, + "line-ns", + 142, + "line-ns-open", + 43, + "line-ne", + 143, + "line-ne-open", + 44, + "line-nw", + 144, + "line-nw-open" ], + "dflt": "circle", + "arrayOk": true, "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "calc" + "editType": "calc", + "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." }, - "ypad": { + "opacity": { "valType": "number", - "role": "style", "min": 0, - "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "calc" - }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", + "max": 1, + "arrayOk": true, "role": "style", "editType": "calc", - "description": "Sets the axis line color." + "description": "Sets the marker opacity." }, - "outlinewidth": { + "size": { "valType": "number", "min": 0, - "dflt": 1, + "dflt": 6, + "arrayOk": true, "role": "style", "editType": "calc", - "description": "Sets the width (in px) of the axis line." + "description": "Sets the marker size (in px)." }, - "bordercolor": { - "valType": "color", - "dflt": "#444", + "sizeref": { + "valType": "number", + "dflt": 1, "role": "style", "editType": "calc", - "description": "Sets the axis line color." + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`." }, - "borderwidth": { + "sizemin": { "valType": "number", - "role": "style", "min": 0, "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "calc" - }, - "bgcolor": { - "valType": "color", "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "calc" + "editType": "calc", + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points." }, - "tickmode": { + "sizemode": { "valType": "enumerated", "values": [ - "auto", - "linear", - "array" + "diameter", + "area" ], + "dflt": "diameter", "role": "info", "editType": "calc", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." }, - "nticks": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "style", + "showscale": { + "valType": "boolean", + "role": "info", + "dflt": false, "editType": "calc", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether or not a colorbar is displayed." }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "calc", - "impliedEdits": { - "tickmode": "linear" + "colorbar": { + "thicknessmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "style", + "dflt": "pixels", + "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", + "editType": "calc" }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "calc", - "impliedEdits": { - "tickmode": "linear" + "thickness": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 30, + "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", + "editType": "calc" }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" - }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], - "role": "style", - "editType": "calc", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" - }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, - "role": "style", - "editType": "calc", - "description": "Sets the tick length (in px)." - }, - "tickwidth": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "calc", - "description": "Sets the tick width (in px)." - }, - "tickcolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "calc", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "calc", - "description": "Determines whether or not the tick labels are drawn." - }, - "tickfont": { - "family": { - "valType": "string", + "lenmode": { + "valType": "enumerated", + "values": [ + "fraction", + "pixels" + ], + "role": "info", + "dflt": "fraction", + "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", + "editType": "calc" + }, + "len": { + "valType": "number", + "min": 0, + "dflt": 1, "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", "editType": "calc" }, - "size": { + "x": { "valType": "number", + "dflt": 1.02, + "min": -2, + "max": 3, "role": "style", - "min": 1, + "description": "Sets the x position of the color bar (in plot fraction).", "editType": "calc" }, - "color": { - "valType": "color", + "xanchor": { + "valType": "enumerated", + "values": [ + "left", + "center", + "right" + ], + "dflt": "left", "role": "style", + "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", "editType": "calc" }, - "description": "Sets the color bar's tick label font", - "editType": "calc", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "calc", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." - }, - "tickformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "calc" - }, - { - "valType": "any", - "editType": "calc" - } - ], - "editType": "calc", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "calc", - "role": "object" - } + "xpad": { + "valType": "number", + "role": "style", + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the x direction.", + "editType": "calc" }, - "role": "object" - }, - "tickprefix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets a tick label prefix." - }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." - }, - "ticksuffix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets a tick label suffix." - }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "Same as `showtickprefix` but for tick suffixes." - }, - "separatethousands": { - "valType": "boolean", - "dflt": false, - "role": "style", - "editType": "calc", - "description": "If \"true\", even 4-digit integers are separated" - }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", - "role": "style", - "editType": "calc", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." - }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." - }, - "title": { - "valType": "string", - "role": "info", - "description": "Sets the title of the color bar.", - "editType": "calc" - }, - "titlefont": { - "family": { - "valType": "string", + "y": { + "valType": "number", "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "dflt": 0.5, + "min": -2, + "max": 3, + "description": "Sets the y position of the color bar (in plot fraction).", "editType": "calc" }, - "size": { + "yanchor": { + "valType": "enumerated", + "values": [ + "top", + "middle", + "bottom" + ], + "role": "style", + "dflt": "middle", + "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", + "editType": "calc" + }, + "ypad": { "valType": "number", "role": "style", - "min": 1, + "min": 0, + "dflt": 10, + "description": "Sets the amount of padding (in px) along the y direction.", "editType": "calc" }, - "color": { + "outlinecolor": { + "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "calc", + "description": "Sets the axis line color." + }, + "outlinewidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "calc", + "description": "Sets the width (in px) of the axis line." + }, + "bordercolor": { "valType": "color", + "dflt": "#444", + "role": "style", + "editType": "calc", + "description": "Sets the axis line color." + }, + "borderwidth": { + "valType": "number", "role": "style", + "min": 0, + "dflt": 0, + "description": "Sets the width (in px) or the border enclosing this color bar.", "editType": "calc" }, - "description": "Sets this color bar's title font.", - "editType": "calc", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "calc" - }, - "editType": "calc", - "role": "object", - "tickvalssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", - "editType": "none" - }, - "ticktextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", - "editType": "none" - } - }, - "contours": { - "x": { - "show": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not contour lines about the x dimension are drawn.", + "bgcolor": { + "valType": "color", + "role": "style", + "dflt": "rgba(0,0,0,0)", + "description": "Sets the color of padded area.", "editType": "calc" }, - "project": { - "x": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the x plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", - "editType": "calc" - }, - "y": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the y plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", - "editType": "calc" + "tickmode": { + "valType": "enumerated", + "values": [ + "auto", + "linear", + "array" + ], + "role": "info", + "editType": "calc", + "impliedEdits": {}, + "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + }, + "nticks": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "style", + "editType": "calc", + "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." + }, + "tick0": { + "valType": "any", + "role": "style", + "editType": "calc", + "impliedEdits": { + "tickmode": "linear" }, - "z": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the z plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", - "editType": "calc" + "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." + }, + "dtick": { + "valType": "any", + "role": "style", + "editType": "calc", + "impliedEdits": { + "tickmode": "linear" }, + "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" + }, + "tickvals": { + "valType": "data_array", "editType": "calc", - "role": "object" + "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", + "role": "data" }, - "color": { - "valType": "color", - "role": "style", - "dflt": "#444", - "description": "Sets the color of the contour lines.", - "editType": "calc" + "ticktext": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", + "role": "data" }, - "usecolormap": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "An alternate to *color*. Determines whether or not the contour lines are colored using the trace *colorscale*.", - "editType": "calc" + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], + "role": "style", + "editType": "calc", + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" }, - "width": { + "ticklen": { "valType": "number", + "min": 0, + "dflt": 5, "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Sets the tick length (in px)." }, - "highlight": { - "valType": "boolean", - "role": "info", - "dflt": true, - "description": "Determines whether or not contour lines about the x dimension are highlighted on hover.", - "editType": "calc" + "tickwidth": { + "valType": "number", + "min": 0, + "dflt": 1, + "role": "style", + "editType": "calc", + "description": "Sets the tick width (in px)." }, - "highlightcolor": { + "tickcolor": { "valType": "color", - "role": "style", "dflt": "#444", - "description": "Sets the color of the highlighted contour lines.", - "editType": "calc" - }, - "highlightwidth": { - "valType": "number", "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the highlighted contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Sets the tick color." }, - "editType": "calc", - "role": "object" - }, - "y": { - "show": { + "showticklabels": { "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not contour lines about the y dimension are drawn.", - "editType": "calc" + "dflt": true, + "role": "style", + "editType": "calc", + "description": "Determines whether or not the tick labels are drawn." }, - "project": { - "x": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the x plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", "editType": "calc" }, - "y": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the y plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "size": { + "valType": "number", + "role": "style", + "min": 1, "editType": "calc" }, - "z": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the z plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "color": { + "valType": "color", + "role": "style", "editType": "calc" }, + "description": "Sets the color bar's tick label font", "editType": "calc", "role": "object" }, - "color": { - "valType": "color", + "tickangle": { + "valType": "angle", + "dflt": "auto", "role": "style", - "dflt": "#444", - "description": "Sets the color of the contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." }, - "usecolormap": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "An alternate to *color*. Determines whether or not the contour lines are colored using the trace *colorscale*.", - "editType": "calc" + "tickformat": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" }, - "width": { - "valType": "number", + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "calc" + }, + { + "valType": "any", + "editType": "calc" + } + ], + "editType": "calc", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "calc", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Sets a tick label prefix." }, - "highlight": { - "valType": "boolean", - "role": "info", - "dflt": true, - "description": "Determines whether or not contour lines about the y dimension are highlighted on hover.", - "editType": "calc" + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." }, - "highlightcolor": { - "valType": "color", + "ticksuffix": { + "valType": "string", + "dflt": "", "role": "style", - "dflt": "#444", - "description": "Sets the color of the highlighted contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Sets a tick label suffix." }, - "highlightwidth": { - "valType": "number", + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the highlighted contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Same as `showtickprefix` but for tick suffixes." }, - "editType": "calc", - "role": "object" - }, - "z": { - "show": { + "separatethousands": { "valType": "boolean", - "role": "info", "dflt": false, - "description": "Determines whether or not contour lines about the z dimension are drawn.", + "role": "style", + "editType": "calc", + "description": "If \"true\", even 4-digit integers are separated" + }, + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "calc", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + }, + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + }, + "title": { + "valType": "string", + "role": "info", + "description": "Sets the title of the color bar.", "editType": "calc" }, - "project": { - "x": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the x plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", "editType": "calc" }, - "y": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the y plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "size": { + "valType": "number", + "role": "style", + "min": 1, "editType": "calc" }, - "z": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not these contour lines are projected on the z plane. If `highlight` is set to *true* (the default), the projected lines are shown on hover. If `show` is set to *true*, the projected lines are shown in permanence.", + "color": { + "valType": "color", + "role": "style", "editType": "calc" }, + "description": "Sets this color bar's title font.", "editType": "calc", "role": "object" }, - "color": { - "valType": "color", + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], "role": "style", - "dflt": "#444", - "description": "Sets the color of the contour lines.", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", "editType": "calc" }, - "usecolormap": { - "valType": "boolean", + "editType": "calc", + "role": "object", + "tickvalssrc": { + "valType": "string", "role": "info", - "dflt": false, - "description": "An alternate to *color*. Determines whether or not the contour lines are colored using the trace *colorscale*.", - "editType": "calc" + "description": "Sets the source reference on plot.ly for tickvals .", + "editType": "none" }, + "ticktextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ticktext .", + "editType": "none" + } + }, + "line": { "width": { "valType": "number", + "min": 0, + "arrayOk": true, "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the contour lines.", - "editType": "calc" + "editType": "calc", + "description": "Sets the width (in px) of the lines bounding the marker points." }, - "highlight": { + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { "valType": "boolean", "role": "info", "dflt": true, - "description": "Determines whether or not contour lines about the z dimension are highlighted on hover.", - "editType": "calc" + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." }, - "highlightcolor": { - "valType": "color", - "role": "style", - "dflt": "#444", - "description": "Sets the color of the highlighted contour lines.", - "editType": "calc" + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." }, - "highlightwidth": { + "cmin": { "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the highlighted contour lines.", - "editType": "calc" + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." }, "editType": "calc", - "role": "object" - }, - "editType": "calc", - "role": "object" - }, - "hidesurface": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Determines whether or not a surface is drawn. For example, set `hidesurface` to *false* `contours.x.show` to *true* and `contours.y.show` to *true* to draw a wire frame plot.", - "editType": "calc" - }, - "lightposition": { - "x": { - "valType": "number", - "role": "style", - "min": -100000, - "max": 100000, - "dflt": 10, - "description": "Numeric vector, representing the X coordinate for each vertex.", - "editType": "calc" - }, - "y": { - "valType": "number", - "role": "style", - "min": -100000, - "max": 100000, - "dflt": 10000, - "description": "Numeric vector, representing the Y coordinate for each vertex.", - "editType": "calc" - }, - "z": { - "valType": "number", - "role": "style", - "min": -100000, - "max": 100000, - "dflt": 0, - "description": "Numeric vector, representing the Z coordinate for each vertex.", - "editType": "calc" - }, - "editType": "calc", - "role": "object" - }, - "lighting": { - "ambient": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0.8, - "description": "Ambient light increases overall color visibility but can wash out the image.", - "editType": "calc" - }, - "diffuse": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0.8, - "description": "Represents the extent that incident rays are reflected in a range of angles.", - "editType": "calc" + "role": "object", + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } }, - "specular": { - "valType": "number", - "role": "style", - "min": 0, - "max": 2, - "dflt": 0.05, - "description": "Represents the level that incident rays are reflected in a single direction, causing shine.", - "editType": "calc" + "gradient": { + "type": { + "valType": "enumerated", + "values": [ + "radial", + "horizontal", + "vertical", + "none" + ], + "arrayOk": true, + "dflt": "none", + "role": "style", + "editType": "calc", + "description": "Sets the type of gradient used to fill the markers" + }, + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical." + }, + "editType": "calc", + "role": "object", + "typesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for type .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + } }, - "roughness": { - "valType": "number", + "color": { + "valType": "color", + "arrayOk": true, "role": "style", - "min": 0, - "max": 1, - "dflt": 0.5, - "description": "Alters specular reflection; the rougher the surface, the wider and less contrasty the shine.", - "editType": "calc" + "editType": "calc", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, - "fresnel": { - "valType": "number", + "colorscale": { + "valType": "colorscale", "role": "style", - "min": 0, - "max": 5, - "dflt": 0.2, - "description": "Represents the reflectance as a dependency of the viewing angle; e.g. paper is reflective when viewing it from the edge of the paper (almost 90 degrees), causing shine.", - "editType": "calc" + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" }, - "editType": "calc", - "role": "object" - }, - "_deprecated": { - "zauto": { + "cauto": { "valType": "boolean", "role": "info", "dflt": true, "editType": "calc", "impliedEdits": {}, - "description": "Obsolete. Use `cauto` instead." + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." }, - "zmin": { + "cmax": { "valType": "number", "role": "info", "dflt": null, "editType": "calc", "impliedEdits": { - "zauto": false + "cauto": false }, - "description": "Obsolete. Use `cmin` instead." + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." }, - "zmax": { + "cmin": { "valType": "number", "role": "info", "dflt": null, "editType": "calc", "impliedEdits": { - "zauto": false + "cauto": false }, - "description": "Obsolete. Use `cmax` instead." + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, + "editType": "calc", + "role": "object", + "symbolsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for symbol .", + "editType": "none" + }, + "opacitysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for opacity .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" } }, - "xcalendar": { + "fill": { "valType": "enumerated", "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" + "none", + "toself" ], - "role": "info", + "dflt": "none", + "role": "style", + "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape.", + "editType": "calc" + }, + "fillcolor": { + "valType": "color", + "role": "style", "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `x` date data." + "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." }, - "ycalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", + "selected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calc", + "description": "Sets the marker opacity of selected points." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the marker color of selected points." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "calc", + "description": "Sets the marker size of selected points." + }, + "editType": "calc", + "role": "object" + }, + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the text font color of selected points." + }, + "editType": "calc", + "role": "object" + }, "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `y` date data." + "role": "object" }, - "zcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", + "unselected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calc", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + }, + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the marker color of unselected points, applied only when a selection exists." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "calc", + "description": "Sets the marker size of unselected points, applied only when a selection exists." + }, + "editType": "calc", + "role": "object" + }, + "textfont": { + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the text font color of unselected points, applied only when a selection exists." + }, + "editType": "calc", + "role": "object" + }, "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `z` date data." + "role": "object" }, - "scene": { + "geo": { "valType": "subplotid", "role": "info", - "dflt": "scene", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's 3D coordinate system and a 3D scene. If *scene* (the default value), the (x,y,z) coordinates refer to `layout.scene`. If *scene2*, the (x,y,z) coordinates refer to `layout.scene2`, and so on." + "dflt": "geo", + "editType": "calc", + "description": "Sets a reference between this trace's geospatial coordinates and a geographic map. If *geo* (the default value), the geospatial coordinates refer to `layout.geo`. If *geo2*, the geospatial coordinates refer to `layout.geo2`, and so on." }, "idssrc": { "valType": "string", @@ -16108,22 +18679,22 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "zsrc": { + "lonsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for z .", + "description": "Sets the source reference on plot.ly for lon .", "editType": "none" }, - "xsrc": { + "latsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for x .", + "description": "Sets the source reference on plot.ly for lat .", "editType": "none" }, - "ysrc": { + "locationssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for y .", + "description": "Sets the source reference on plot.ly for locations .", "editType": "none" }, "textsrc": { @@ -16132,20 +18703,26 @@ "description": "Sets the source reference on plot.ly for text .", "editType": "none" }, - "surfacecolorsrc": { + "hovertextsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for surfacecolor .", + "description": "Sets the source reference on plot.ly for hovertext .", + "editType": "none" + }, + "textpositionsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for textposition .", "editType": "none" } } }, - "mesh3d": { + "choropleth": { "meta": { - "description": "Draws sets of triangles with coordinates given by three 1-dimensional arrays in `x`, `y`, `z` and (1) a sets of `i`, `j`, `k` indices (2) Delaunay triangulation or (3) the Alpha-shape algorithm or (4) the Convex-hull algorithm" + "description": "The data that describes the choropleth value-to-color mapping is set in `z`. The geographic locations corresponding to each value in `z` are set in `locations`." }, "attributes": { - "type": "mesh3d", + "type": "choropleth", "visible": { "valType": "enumerated", "values": [ @@ -16178,8 +18755,8 @@ "min": 0, "max": 1, "dflt": 1, - "editType": "calc", - "description": "Sets the opacity of the surface." + "editType": "style", + "description": "Sets the opacity of the trace." }, "name": { "valType": "string", @@ -16215,10 +18792,10 @@ "valType": "flaglist", "role": "info", "flags": [ - "x", - "y", + "location", "z", "text", + "name", "name" ], "extras": [ @@ -16341,98 +18918,28 @@ "editType": "calc", "role": "object" }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "description": "Sets the color of the whole mesh" - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `color` array index, and if set, `cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `color` array index, and if set, `cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the X coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex.", - "role": "data" - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the Y coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex.", - "role": "data" - }, - "z": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the Z coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex.", - "role": "data" - }, - "i": { + "locations": { "valType": "data_array", "editType": "calc", - "description": "A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the *first* vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `i[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `i` represents a point in space, which is the first vertex of a triangle.", + "description": "Sets the coordinates via location IDs or names. See `locationmode` for more info.", "role": "data" }, - "j": { - "valType": "data_array", - "editType": "calc", - "description": "A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the *second* vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `j[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `j` represents a point in space, which is the second vertex of a triangle.", - "role": "data" + "locationmode": { + "valType": "enumerated", + "values": [ + "ISO-3", + "USA-states", + "country names" + ], + "role": "info", + "dflt": "ISO-3", + "description": "Determines the set of locations used to match entries in `locations` to regions on the map.", + "editType": "calc" }, - "k": { + "z": { "valType": "data_array", "editType": "calc", - "description": "A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the *third* vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `k[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `k` represents a point in space, which is the third vertex of a triangle.", + "description": "Sets the color values.", "role": "data" }, "text": { @@ -16441,78 +18948,143 @@ "dflt": "", "arrayOk": true, "editType": "calc", - "description": "Sets the text elements associated with the vertices. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." + "description": "Sets the text elements associated with each location." }, - "delaunayaxis": { - "valType": "enumerated", - "role": "info", - "values": [ - "x", - "y", - "z" - ], - "dflt": "z", + "marker": { + "line": { + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "width": { + "valType": "number", + "min": 0, + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the width (in px) of the lines bounding the marker points.", + "dflt": 1 + }, + "editType": "calc", + "role": "object", + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + }, + "widthsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for width .", + "editType": "none" + } + }, + "opacity": { + "valType": "number", + "arrayOk": true, + "min": 0, + "max": 1, + "dflt": 1, + "role": "style", + "editType": "style", + "description": "Sets the opacity of the locations." + }, "editType": "calc", - "description": "Sets the Delaunay axis, which is the axis that is perpendicular to the surface of the Delaunay triangulation. It has an effect if `i`, `j`, `k` are not provided and `alphahull` is set to indicate Delaunay triangulation." + "role": "object", + "opacitysrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for opacity .", + "editType": "none" + } }, - "alphahull": { - "valType": "number", - "role": "style", - "dflt": -1, + "selected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calc", + "description": "Sets the marker opacity of selected points." + }, + "editType": "plot", + "role": "object" + }, + "editType": "plot", + "role": "object" + }, + "unselected": { + "marker": { + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "role": "style", + "editType": "calc", + "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + }, + "editType": "plot", + "role": "object" + }, + "editType": "plot", + "role": "object" + }, + "zauto": { + "valType": "boolean", + "role": "info", + "dflt": true, "editType": "calc", - "description": "Determines how the mesh surface triangles are derived from the set of vertices (points) represented by the `x`, `y` and `z` arrays, if the `i`, `j`, `k` arrays are not supplied. For general use of `mesh3d` it is preferred that `i`, `j`, `k` are supplied. If *-1*, Delaunay triangulation is used, which is mainly suitable if the mesh is a single, more or less layer surface that is perpendicular to `delaunayaxis`. In case the `delaunayaxis` intersects the mesh surface at more than one point it will result triangles that are very long in the dimension of `delaunayaxis`. If *>0*, the alpha-shape algorithm is used. In this case, the positive `alphahull` value signals the use of the alpha-shape algorithm, _and_ its value acts as the parameter for the mesh fitting. If *0*, the convex-hull algorithm is used. It is suitable for convex bodies or if the intention is to enclose the `x`, `y` and `z` point set into a convex hull." + "impliedEdits": {}, + "description": "Determines the whether or not the color domain is computed with respect to the input data." }, - "intensity": { - "valType": "data_array", + "zmin": { + "valType": "number", + "role": "info", + "dflt": null, "editType": "calc", - "description": "Sets the vertex intensity values, used for plotting fields on meshes", - "role": "data" + "impliedEdits": { + "zauto": false + }, + "description": "Sets the lower bound of color domain." }, - "vertexcolor": { - "valType": "data_array", - "role": "data", + "zmax": { + "valType": "number", + "role": "info", + "dflt": null, "editType": "calc", - "description": "Sets the color of each vertex Overrides *color*." + "impliedEdits": { + "zauto": false + }, + "description": "Sets the upper bound of color domain." }, - "facecolor": { - "valType": "data_array", - "role": "data", + "colorscale": { + "valType": "colorscale", + "role": "style", "editType": "calc", - "description": "Sets the color of each face Overrides *color* and *vertexcolor*." + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" }, - "flatshading": { + "autocolorscale": { "valType": "boolean", "role": "style", - "dflt": false, + "dflt": true, "editType": "calc", - "description": "Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low-poly look via flat reflections." + "impliedEdits": {}, + "description": "Determines whether or not the colorscale is picked using the sign of the input z values." }, - "contour": { - "show": { - "valType": "boolean", - "role": "info", - "dflt": false, - "description": "Sets whether or not dynamic contours are shown on hover", - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "dflt": "#444", - "description": "Sets the color of the contour lines.", - "editType": "calc" - }, - "width": { - "valType": "number", - "role": "style", - "min": 1, - "max": 16, - "dflt": 2, - "description": "Sets the width of the contour lines.", - "editType": "calc" - }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, "editType": "calc", - "role": "object" + "description": "Reverses the colorscale." }, "showscale": { "valType": "boolean", @@ -16949,185 +19521,12 @@ "editType": "none" } }, - "lightposition": { - "x": { - "valType": "number", - "role": "style", - "min": -100000, - "max": 100000, - "dflt": 100000, - "description": "Numeric vector, representing the X coordinate for each vertex.", - "editType": "calc" - }, - "y": { - "valType": "number", - "role": "style", - "min": -100000, - "max": 100000, - "dflt": 100000, - "description": "Numeric vector, representing the Y coordinate for each vertex.", - "editType": "calc" - }, - "z": { - "valType": "number", - "role": "style", - "min": -100000, - "max": 100000, - "dflt": 0, - "description": "Numeric vector, representing the Z coordinate for each vertex.", - "editType": "calc" - }, - "editType": "calc", - "role": "object" - }, - "lighting": { - "vertexnormalsepsilon": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1e-12, - "editType": "calc", - "description": "Epsilon for vertex normals calculation avoids math issues arising from degenerate geometry." - }, - "facenormalsepsilon": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0.000001, - "editType": "calc", - "description": "Epsilon for face normals calculation avoids math issues arising from degenerate geometry." - }, - "editType": "calc", - "ambient": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0.8, - "description": "Ambient light increases overall color visibility but can wash out the image.", - "editType": "calc" - }, - "diffuse": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0.8, - "description": "Represents the extent that incident rays are reflected in a range of angles.", - "editType": "calc" - }, - "specular": { - "valType": "number", - "role": "style", - "min": 0, - "max": 2, - "dflt": 0.05, - "description": "Represents the level that incident rays are reflected in a single direction, causing shine.", - "editType": "calc" - }, - "roughness": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 0.5, - "description": "Alters specular reflection; the rougher the surface, the wider and less contrasty the shine.", - "editType": "calc" - }, - "fresnel": { - "valType": "number", - "role": "style", - "min": 0, - "max": 5, - "dflt": 0.2, - "description": "Represents the reflectance as a dependency of the viewing angle; e.g. paper is reflective when viewing it from the edge of the paper (almost 90 degrees), causing shine.", - "editType": "calc" - }, - "role": "object" - }, - "xcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `x` date data." - }, - "ycalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `y` date data." - }, - "zcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `z` date data." - }, - "scene": { + "geo": { "valType": "subplotid", "role": "info", - "dflt": "scene", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's 3D coordinate system and a 3D scene. If *scene* (the default value), the (x,y,z) coordinates refer to `layout.scene`. If *scene2*, the (x,y,z) coordinates refer to `layout.scene2`, and so on." + "dflt": "geo", + "editType": "calc", + "description": "Sets a reference between this trace's geospatial coordinates and a geographic map. If *geo* (the default value), the geospatial coordinates refer to `layout.geo`. If *geo2*, the geospatial coordinates refer to `layout.geo2`, and so on." }, "idssrc": { "valType": "string", @@ -17147,16 +19546,10 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "xsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for x .", - "editType": "none" - }, - "ysrc": { + "locationssrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for y .", + "description": "Sets the source reference on plot.ly for locations .", "editType": "none" }, "zsrc": { @@ -17165,57 +19558,21 @@ "description": "Sets the source reference on plot.ly for z .", "editType": "none" }, - "isrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for i .", - "editType": "none" - }, - "jsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for j .", - "editType": "none" - }, - "ksrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for k .", - "editType": "none" - }, "textsrc": { "valType": "string", "role": "info", "description": "Sets the source reference on plot.ly for text .", "editType": "none" - }, - "intensitysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for intensity .", - "editType": "none" - }, - "vertexcolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for vertexcolor .", - "editType": "none" - }, - "facecolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for facecolor .", - "editType": "none" } } }, - "scattergeo": { + "scattergl": { "meta": { - "hrName": "scatter_geo", - "description": "The data visualized as scatter point or lines on a geographic map is provided either by longitude/latitude pairs in `lon` and `lat` respectively or by geographic location IDs or names in `locations`." + "hrName": "scatter_gl", + "description": "The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays." }, "attributes": { - "type": "scattergeo", + "type": "scattergl", "visible": { "valType": "enumerated", "values": [ @@ -17248,7 +19605,7 @@ "min": 0, "max": 1, "dflt": 1, - "editType": "style", + "editType": "calc", "description": "Sets the opacity of the trace." }, "name": { @@ -17285,9 +19642,9 @@ "valType": "flaglist", "role": "info", "flags": [ - "lon", - "lat", - "location", + "x", + "y", + "z", "text", "name" ], @@ -17298,7 +19655,7 @@ ], "arrayOk": true, "dflt": "all", - "editType": "calc", + "editType": "none", "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." }, "hoverlabel": { @@ -17411,50 +19768,45 @@ "editType": "calc", "role": "object" }, - "lon": { + "x": { "valType": "data_array", - "description": "Sets the longitude coordinates (in degrees East).", - "editType": "calc", + "editType": "calc+clearAxisTypes", + "description": "Sets the x coordinates.", "role": "data" }, - "lat": { - "valType": "data_array", - "description": "Sets the latitude coordinates (in degrees North).", + "x0": { + "valType": "any", + "dflt": 0, + "role": "info", + "editType": "calc+clearAxisTypes", + "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step." + }, + "dx": { + "valType": "number", + "dflt": 1, + "role": "info", "editType": "calc", - "role": "data" + "description": "Sets the x coordinate step. See `x0` for more info." }, - "locations": { + "y": { "valType": "data_array", - "description": "Sets the coordinates via location IDs or names. Coordinates correspond to the centroid of each location given. See `locationmode` for more info.", - "editType": "calc", + "editType": "calc+clearAxisTypes", + "description": "Sets the y coordinates.", "role": "data" }, - "locationmode": { - "valType": "enumerated", - "values": [ - "ISO-3", - "USA-states", - "country names" - ], + "y0": { + "valType": "any", + "dflt": 0, "role": "info", - "dflt": "ISO-3", - "description": "Determines the set of locations used to match entries in `locations` to regions on the map.", - "editType": "calc" + "editType": "calc+clearAxisTypes", + "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step." }, - "mode": { - "valType": "flaglist", - "flags": [ - "lines", - "markers", - "text" - ], - "extras": [ - "none" - ], + "dy": { + "valType": "number", + "dflt": 1, "role": "info", "editType": "calc", - "description": "Determines the drawing mode for this scatter trace. If the provided `mode` includes *text* then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points, then the default is *lines+markers*. Otherwise, *lines*.", - "dflt": "markers" + "description": "Sets the y coordinate step. See `y0` for more info." }, "text": { "valType": "string", @@ -17462,79 +19814,20 @@ "dflt": "", "arrayOk": true, "editType": "calc", - "description": "Sets text elements associated with each (lon,lat) pair or item in `locations`. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) or `locations` coordinates. If trace `hoverinfo` contains a *text* flag and *hovertext* is not set, these elements will be seen in the hover labels." - }, - "hovertext": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "calc", - "description": "Sets hover text elements associated with each (lon,lat) pair or item in `locations`. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) or `locations` coordinates. To be seen, trace `hoverinfo` must contain a *text* flag." - }, - "textfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "editType": "calc", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc", - "arrayOk": true - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "arrayOk": true - }, - "editType": "calc", - "description": "Sets the text font.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } + "description": "Sets text elements associated with each (x,y) pair to appear on hover. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates." }, - "textposition": { - "valType": "enumerated", - "values": [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right" + "mode": { + "valType": "flaglist", + "flags": [ + "lines", + "markers" ], - "dflt": "middle center", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the positions of the `text` elements with respects to the (x,y) coordinates." + "extras": [ + "none" + ], + "role": "info", + "description": "Determines the drawing mode for this scatter trace.", + "editType": "calc" }, "line": { "color": { @@ -17552,7 +19845,7 @@ "description": "Sets the line width (in px)." }, "dash": { - "valType": "string", + "valType": "enumerated", "values": [ "solid", "dot", @@ -17563,20 +19856,72 @@ ], "dflt": "solid", "role": "style", + "description": "Sets the style of the lines.", + "editType": "calc" + }, + "editType": "calc", + "role": "object" + }, + "marker": { + "color": { + "valType": "color", + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." + }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, "editType": "calc", - "description": "Sets the dash style of lines. Set to a dash type string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." + "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." }, - "editType": "calc", - "role": "object" - }, - "connectgaps": { - "valType": "boolean", - "dflt": false, - "role": "info", - "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." - }, - "marker": { "symbol": { "valType": "enumerated", "values": [ @@ -17871,15 +20216,6 @@ "editType": "calc", "description": "Sets the marker symbol type. Adding 100 is equivalent to appending *-open* to a symbol name. Adding 200 is equivalent to appending *-dot* to a symbol name. Adding 300 is equivalent to appending *-open-dot* or *dot-open* to a symbol name." }, - "opacity": { - "valType": "number", - "min": 0, - "max": 1, - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the marker opacity." - }, "size": { "valType": "number", "min": 0, @@ -17915,6 +20251,15 @@ "editType": "calc", "description": "Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels." }, + "opacity": { + "valType": "number", + "min": 0, + "max": 1, + "arrayOk": true, + "role": "style", + "editType": "calc", + "description": "Sets the marker opacity." + }, "showscale": { "valType": "boolean", "role": "info", @@ -18106,848 +20451,250 @@ "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", "role": "data" }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], - "role": "style", - "editType": "calc", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" - }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, - "role": "style", - "editType": "calc", - "description": "Sets the tick length (in px)." - }, - "tickwidth": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "calc", - "description": "Sets the tick width (in px)." - }, - "tickcolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "calc", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "calc", - "description": "Determines whether or not the tick labels are drawn." - }, - "tickfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "calc" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc" - }, - "description": "Sets the color bar's tick label font", - "editType": "calc", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "calc", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." - }, - "tickformat": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" - }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "calc" - }, - { - "valType": "any", - "editType": "calc" - } - ], - "editType": "calc", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "calc", - "role": "object" - } - }, - "role": "object" - }, - "tickprefix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets a tick label prefix." - }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." - }, - "ticksuffix": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "calc", - "description": "Sets a tick label suffix." - }, - "showticksuffix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "Same as `showtickprefix` but for tick suffixes." - }, - "separatethousands": { - "valType": "boolean", - "dflt": false, - "role": "style", - "editType": "calc", - "description": "If \"true\", even 4-digit integers are separated" - }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", - "role": "style", - "editType": "calc", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." - }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", - "role": "style", - "editType": "calc", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." - }, - "title": { - "valType": "string", - "role": "info", - "description": "Sets the title of the color bar.", - "editType": "calc" - }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "calc" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc" - }, - "description": "Sets this color bar's title font.", - "editType": "calc", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "calc" - }, - "editType": "calc", - "role": "object", - "tickvalssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", - "editType": "none" - }, - "ticktextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", - "editType": "none" - } - }, - "line": { - "width": { - "valType": "number", - "min": 0, - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the lines bounding the marker points." - }, - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "editType": "calc", - "role": "object", - "widthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for width .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "gradient": { - "type": { - "valType": "enumerated", - "values": [ - "radial", - "horizontal", - "vertical", - "none" - ], - "arrayOk": true, - "dflt": "none", - "role": "style", - "editType": "calc", - "description": "Sets the type of gradient used to fill the markers" - }, - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the final color of the gradient fill: the center color for radial, the right for horizontal, or the bottom for vertical." - }, - "editType": "calc", - "role": "object", - "typesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for type .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "color": { - "valType": "color", - "arrayOk": true, - "role": "style", - "editType": "calc", - "description": "Sets the marker color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale and only has an effect if `marker.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" - }, - "cauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." - }, - "cmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmin` must be set as well." - }, - "cmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "cauto": false - }, - "description": "Has an effect only if `marker.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.color` array index, and if set, `marker.cmax` must be set as well." - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Has an effect only if `marker.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Has an effect only if `marker.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." - }, - "editType": "calc", - "role": "object", - "symbolsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for symbol .", - "editType": "none" - }, - "opacitysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for opacity .", - "editType": "none" - }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" - }, - "colorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "fill": { - "valType": "enumerated", - "values": [ - "none", - "toself" - ], - "dflt": "none", - "role": "style", - "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape.", - "editType": "calc" - }, - "fillcolor": { - "valType": "color", - "role": "style", - "editType": "calc", - "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." - }, - "selected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, + "ticks": { + "valType": "enumerated", + "values": [ + "outside", + "inside", + "" + ], "role": "style", "editType": "calc", - "description": "Sets the marker opacity of selected points." + "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", + "dflt": "" }, - "color": { - "valType": "color", + "ticklen": { + "valType": "number", + "min": 0, + "dflt": 5, "role": "style", "editType": "calc", - "description": "Sets the marker color of selected points." + "description": "Sets the tick length (in px)." }, - "size": { + "tickwidth": { "valType": "number", "min": 0, + "dflt": 1, "role": "style", "editType": "calc", - "description": "Sets the marker size of selected points." + "description": "Sets the tick width (in px)." }, - "editType": "calc", - "role": "object" - }, - "textfont": { - "color": { + "tickcolor": { "valType": "color", + "dflt": "#444", "role": "style", "editType": "calc", - "description": "Sets the text font color of selected points." + "description": "Sets the tick color." }, - "editType": "calc", - "role": "object" - }, - "editType": "calc", - "role": "object" - }, - "unselected": { - "marker": { - "opacity": { - "valType": "number", - "min": 0, - "max": 1, + "showticklabels": { + "valType": "boolean", + "dflt": true, "role": "style", "editType": "calc", - "description": "Sets the marker opacity of unselected points, applied only when a selection exists." + "description": "Determines whether or not the tick labels are drawn." }, - "color": { - "valType": "color", + "tickfont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "calc" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "calc" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "calc" + }, + "description": "Sets the color bar's tick label font", + "editType": "calc", + "role": "object" + }, + "tickangle": { + "valType": "angle", + "dflt": "auto", "role": "style", "editType": "calc", - "description": "Sets the marker color of unselected points, applied only when a selection exists." + "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." }, - "size": { - "valType": "number", - "min": 0, + "tickformat": { + "valType": "string", + "dflt": "", "role": "style", "editType": "calc", - "description": "Sets the marker size of unselected points, applied only when a selection exists." + "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" }, - "editType": "calc", - "role": "object" - }, - "textfont": { - "color": { - "valType": "color", + "tickformatstops": { + "items": { + "tickformatstop": { + "dtickrange": { + "valType": "info_array", + "role": "info", + "items": [ + { + "valType": "any", + "editType": "calc" + }, + { + "valType": "any", + "editType": "calc" + } + ], + "editType": "calc", + "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" + }, + "value": { + "valType": "string", + "dflt": "", + "role": "style", + "editType": "calc", + "description": "string - dtickformat for described zoom level, the same as *tickformat*" + }, + "editType": "calc", + "role": "object" + } + }, + "role": "object" + }, + "tickprefix": { + "valType": "string", + "dflt": "", "role": "style", "editType": "calc", - "description": "Sets the text font color of unselected points, applied only when a selection exists." + "description": "Sets a tick label prefix." }, - "editType": "calc", - "role": "object" - }, - "editType": "calc", - "role": "object" - }, - "geo": { - "valType": "subplotid", - "role": "info", - "dflt": "geo", - "editType": "calc", - "description": "Sets a reference between this trace's geospatial coordinates and a geographic map. If *geo* (the default value), the geospatial coordinates refer to `layout.geo`. If *geo2*, the geospatial coordinates refer to `layout.geo2`, and so on." - }, - "idssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for ids .", - "editType": "none" - }, - "customdatasrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for customdata .", - "editType": "none" - }, - "hoverinfosrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hoverinfo .", - "editType": "none" - }, - "lonsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for lon .", - "editType": "none" - }, - "latsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for lat .", - "editType": "none" - }, - "locationssrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for locations .", - "editType": "none" - }, - "textsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for text .", - "editType": "none" - }, - "hovertextsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for hovertext .", - "editType": "none" - }, - "textpositionsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for textposition .", - "editType": "none" - } - } - }, - "choropleth": { - "meta": { - "description": "The data that describes the choropleth value-to-color mapping is set in `z`. The geographic locations corresponding to each value in `z` are set in `locations`." - }, - "attributes": { - "type": "choropleth", - "visible": { - "valType": "enumerated", - "values": [ - true, - false, - "legendonly" - ], - "role": "info", - "dflt": true, - "editType": "calc", - "description": "Determines whether or not this trace is visible. If *legendonly*, the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible)." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this trace is shown in the legend." - }, - "legendgroup": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "style", - "description": "Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items." - }, - "opacity": { - "valType": "number", - "role": "style", - "min": 0, - "max": 1, - "dflt": 1, - "editType": "style", - "description": "Sets the opacity of the trace." - }, - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the trace name. The trace name appear as the legend item and on hover." - }, - "uid": { - "valType": "string", - "role": "info", - "dflt": "", - "editType": "calc" - }, - "ids": { - "valType": "data_array", - "editType": "calc", - "description": "Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type.", - "role": "data" - }, - "customdata": { - "valType": "data_array", - "editType": "calc", - "description": "Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, *scatter* traces also appends customdata items in the markers DOM elements", - "role": "data" - }, - "selectedpoints": { - "valType": "any", - "role": "info", - "editType": "calc", - "description": "Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect." - }, - "hoverinfo": { - "valType": "flaglist", - "role": "info", - "flags": [ - "location", - "z", - "text", - "name", - "name" - ], - "extras": [ - "all", - "none", - "skip" - ], - "arrayOk": true, - "dflt": "all", - "editType": "calc", - "description": "Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired." - }, - "hoverlabel": { - "bgcolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the background color of the hover labels for this trace" - }, - "bordercolor": { - "valType": "color", - "role": "style", - "arrayOk": true, - "editType": "none", - "description": "Sets the border color of the hover labels for this trace." - }, - "font": { - "family": { + "showtickprefix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + }, + "ticksuffix": { "valType": "string", + "dflt": "", "role": "style", - "noBlank": true, - "strict": true, - "editType": "none", - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "arrayOk": true + "editType": "calc", + "description": "Sets a tick label suffix." }, - "size": { - "valType": "number", + "showticksuffix": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", "role": "style", - "min": 1, - "editType": "none", - "arrayOk": true + "editType": "calc", + "description": "Same as `showtickprefix` but for tick suffixes." }, - "color": { - "valType": "color", + "separatethousands": { + "valType": "boolean", + "dflt": false, "role": "style", - "editType": "none", - "arrayOk": true + "editType": "calc", + "description": "If \"true\", even 4-digit integers are separated" }, - "editType": "none", - "description": "Sets the font used in hover labels.", - "role": "object", - "familysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for family .", - "editType": "none" + "exponentformat": { + "valType": "enumerated", + "values": [ + "none", + "e", + "E", + "power", + "SI", + "B" + ], + "dflt": "B", + "role": "style", + "editType": "calc", + "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." }, - "sizesrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for size .", - "editType": "none" + "showexponent": { + "valType": "enumerated", + "values": [ + "all", + "first", + "last", + "none" + ], + "dflt": "all", + "role": "style", + "editType": "calc", + "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." }, - "colorsrc": { + "title": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for color .", - "editType": "none" - } - }, - "namelength": { - "valType": "integer", - "min": -1, - "arrayOk": true, - "role": "style", - "editType": "none", - "description": "Sets the length (in number of characters) of the trace name in the hover labels for this trace. -1 shows the whole name regardless of length. 0-3 shows the first 0-3 characters, and an integer >3 will show the whole name if it is less than that many characters, but if it is longer, will truncate to `namelength - 3` characters and add an ellipsis." - }, - "editType": "calc", - "role": "object", - "bgcolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bgcolor .", - "editType": "none" - }, - "bordercolorsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for bordercolor .", - "editType": "none" - }, - "namelengthsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for namelength .", - "editType": "none" - } - }, - "stream": { - "token": { - "valType": "string", - "noBlank": true, - "strict": true, - "role": "info", - "editType": "calc", - "description": "The stream id number links a data trace on a plot with a stream. See https://plot.ly/settings for more details." - }, - "maxpoints": { - "valType": "number", - "min": 0, - "max": 10000, - "dflt": 500, - "role": "info", - "editType": "calc", - "description": "Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to *50*, only the newest 50 points will be displayed on the plot." - }, - "editType": "calc", - "role": "object" - }, - "locations": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the coordinates via location IDs or names. See `locationmode` for more info.", - "role": "data" - }, - "locationmode": { - "valType": "enumerated", - "values": [ - "ISO-3", - "USA-states", - "country names" - ], - "role": "info", - "dflt": "ISO-3", - "description": "Determines the set of locations used to match entries in `locations` to regions on the map.", - "editType": "calc" - }, - "z": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the color values.", - "role": "data" - }, - "text": { - "valType": "string", - "role": "info", - "dflt": "", - "arrayOk": true, - "editType": "calc", - "description": "Sets the text elements associated with each location." - }, - "marker": { + "description": "Sets the title of the color bar.", + "editType": "calc" + }, + "titlefont": { + "family": { + "valType": "string", + "role": "style", + "noBlank": true, + "strict": true, + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", + "editType": "calc" + }, + "size": { + "valType": "number", + "role": "style", + "min": 1, + "editType": "calc" + }, + "color": { + "valType": "color", + "role": "style", + "editType": "calc" + }, + "description": "Sets this color bar's title font.", + "editType": "calc", + "role": "object" + }, + "titleside": { + "valType": "enumerated", + "values": [ + "right", + "top", + "bottom" + ], + "role": "style", + "dflt": "top", + "description": "Determines the location of the colorbar title with respect to the color bar.", + "editType": "calc" + }, + "editType": "calc", + "role": "object", + "tickvalssrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for tickvals .", + "editType": "none" + }, + "ticktextsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for ticktext .", + "editType": "none" + } + }, "line": { "color": { "valType": "color", @@ -18956,14 +20703,65 @@ "editType": "calc", "description": "Sets the marker.line color. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `cmin` and `cmax` if set." }, + "colorscale": { + "valType": "colorscale", + "role": "style", + "editType": "calc", + "impliedEdits": { + "autocolorscale": false + }, + "description": "Sets the colorscale and only has an effect if `marker.line.color` is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `marker.line.cmin` and `marker.line.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, Cividis" + }, + "cauto": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array and `cmin`, `cmax` are set by the user. In this case, it controls whether the range of colors in `colorscale` is mapped to the range of values in the `color` array (`cauto: true`), or the `cmin`/`cmax` values (`cauto: false`). Defaults to `false` when `cmin`, `cmax` are set by the user." + }, + "cmax": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the upper bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmin` must be set as well." + }, + "cmin": { + "valType": "number", + "role": "info", + "dflt": null, + "editType": "calc", + "impliedEdits": { + "cauto": false + }, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Sets the lower bound of the color domain. Value should be associated to the `marker.line.color` array index, and if set, `marker.line.cmax` must be set as well." + }, + "autocolorscale": { + "valType": "boolean", + "role": "style", + "dflt": true, + "editType": "calc", + "impliedEdits": {}, + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.line.colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed." + }, + "reversescale": { + "valType": "boolean", + "role": "style", + "dflt": false, + "editType": "calc", + "description": "Has an effect only if `marker.line.color` is set to a numerical array. Reverses the color mapping if true (`cmin` will correspond to the last color in the array and `cmax` will correspond to the first color)." + }, "width": { "valType": "number", "min": 0, "arrayOk": true, "role": "style", "editType": "calc", - "description": "Sets the width (in px) of the lines bounding the marker points.", - "dflt": 1 + "description": "Sets the width (in px) of the lines bounding the marker points." }, "editType": "calc", "role": "object", @@ -18980,18 +20778,26 @@ "editType": "none" } }, - "opacity": { - "valType": "number", - "arrayOk": true, - "min": 0, - "max": 1, - "dflt": 1, - "role": "style", - "editType": "style", - "description": "Sets the opacity of the locations." - }, "editType": "calc", "role": "object", + "colorsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for color .", + "editType": "none" + }, + "symbolsrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for symbol .", + "editType": "none" + }, + "sizesrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for size .", + "editType": "none" + }, "opacitysrc": { "valType": "string", "role": "info", @@ -18999,6 +20805,45 @@ "editType": "none" } }, + "connectgaps": { + "valType": "boolean", + "dflt": false, + "role": "info", + "editType": "calc", + "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." + }, + "fill": { + "valType": "enumerated", + "values": [ + "none", + "tozeroy", + "tozerox", + "tonexty", + "tonextx", + "toself", + "tonext" + ], + "dflt": "none", + "role": "style", + "editType": "calc", + "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. *tozerox* and *tozeroy* fill to x=0 and y=0 respectively. *tonextx* and *tonexty* fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like *tozerox* and *tozeroy*. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. *tonext* fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like *toself* if there is no trace before it. *tonext* should not be used if one trace does not enclose the other." + }, + "fillcolor": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + }, + "hoveron": { + "valType": "flaglist", + "flags": [ + "points", + "fills" + ], + "role": "info", + "editType": "calc", + "description": "Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is *toself* or *tonext* and there are no markers or text, then the default is *fills*, otherwise it is *points*." + }, "selected": { "marker": { "opacity": { @@ -19009,10 +20854,23 @@ "editType": "calc", "description": "Sets the marker opacity of selected points." }, - "editType": "plot", + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the marker color of selected points." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "calc", + "description": "Sets the marker size of selected points." + }, + "editType": "calc", "role": "object" }, - "editType": "plot", + "editType": "calc", "role": "object" }, "unselected": { @@ -19025,505 +20883,315 @@ "editType": "calc", "description": "Sets the marker opacity of unselected points, applied only when a selection exists." }, - "editType": "plot", + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the marker color of unselected points, applied only when a selection exists." + }, + "size": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "calc", + "description": "Sets the marker size of unselected points, applied only when a selection exists." + }, + "editType": "calc", "role": "object" }, - "editType": "plot", - "role": "object" - }, - "zauto": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Determines the whether or not the color domain is computed with respect to the input data." - }, - "zmin": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the lower bound of color domain." - }, - "zmax": { - "valType": "number", - "role": "info", - "dflt": null, - "editType": "calc", - "impliedEdits": { - "zauto": false - }, - "description": "Sets the upper bound of color domain." - }, - "colorscale": { - "valType": "colorscale", - "role": "style", - "editType": "calc", - "impliedEdits": { - "autocolorscale": false - }, - "description": "Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)', [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in z space, use zmin and zmax" - }, - "autocolorscale": { - "valType": "boolean", - "role": "style", - "dflt": true, - "editType": "calc", - "impliedEdits": {}, - "description": "Determines whether or not the colorscale is picked using the sign of the input z values." - }, - "reversescale": { - "valType": "boolean", - "role": "style", - "dflt": false, - "editType": "calc", - "description": "Reverses the colorscale." - }, - "showscale": { - "valType": "boolean", - "role": "info", - "dflt": true, "editType": "calc", - "description": "Determines whether or not a colorbar is displayed for this trace." + "role": "object" }, - "colorbar": { - "thicknessmode": { - "valType": "enumerated", - "values": [ - "fraction", - "pixels" - ], - "role": "style", - "dflt": "pixels", - "description": "Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot *fraction* or in *pixels*. Use `thickness` to set the value.", - "editType": "colorbars" - }, - "thickness": { - "valType": "number", - "role": "style", - "min": 0, - "dflt": 30, - "description": "Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels.", - "editType": "colorbars" + "error_x": { + "visible": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." }, - "lenmode": { + "type": { "valType": "enumerated", "values": [ - "fraction", - "pixels" + "percent", + "constant", + "sqrt", + "data" ], "role": "info", - "dflt": "fraction", - "description": "Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot *fraction* or in *pixels. Use `len` to set the value.", - "editType": "colorbars" + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." }, - "len": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "description": "Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends.", - "editType": "colorbars" + "symmetric": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." }, - "x": { - "valType": "number", - "dflt": 1.02, - "min": -2, - "max": 3, - "role": "style", - "description": "Sets the x position of the color bar (in plot fraction).", - "editType": "colorbars" + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" }, - "xanchor": { - "valType": "enumerated", - "values": [ - "left", - "center", - "right" - ], - "dflt": "left", - "role": "style", - "description": "Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the *left*, *center* or *right* of the color bar.", - "editType": "colorbars" + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" }, - "xpad": { + "value": { "valType": "number", - "role": "style", "min": 0, "dflt": 10, - "description": "Sets the amount of padding (in px) along the x direction.", - "editType": "colorbars" - }, - "y": { - "valType": "number", - "role": "style", - "dflt": 0.5, - "min": -2, - "max": 3, - "description": "Sets the y position of the color bar (in plot fraction).", - "editType": "colorbars" - }, - "yanchor": { - "valType": "enumerated", - "values": [ - "top", - "middle", - "bottom" - ], - "role": "style", - "dflt": "middle", - "description": "Sets this color bar's vertical position anchor This anchor binds the `y` position to the *top*, *middle* or *bottom* of the color bar.", - "editType": "colorbars" + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." }, - "ypad": { + "valueminus": { "valType": "number", - "role": "style", "min": 0, "dflt": 10, - "description": "Sets the amount of padding (in px) along the y direction.", - "editType": "colorbars" - }, - "outlinecolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." - }, - "outlinewidth": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "colorbars", - "description": "Sets the width (in px) of the axis line." - }, - "bordercolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the axis line color." + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" }, - "borderwidth": { - "valType": "number", - "role": "style", + "traceref": { + "valType": "integer", "min": 0, "dflt": 0, - "description": "Sets the width (in px) or the border enclosing this color bar.", - "editType": "colorbars" - }, - "bgcolor": { - "valType": "color", - "role": "style", - "dflt": "rgba(0,0,0,0)", - "description": "Sets the color of padded area.", - "editType": "colorbars" - }, - "tickmode": { - "valType": "enumerated", - "values": [ - "auto", - "linear", - "array" - ], "role": "info", - "editType": "colorbars", - "impliedEdits": {}, - "description": "Sets the tick mode for this axis. If *auto*, the number of ticks is set via `nticks`. If *linear*, the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` (*linear* is the default value if `tick0` and `dtick` are provided). If *array*, the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. (*array* is the default value if `tickvals` is provided)." + "editType": "calc" }, - "nticks": { + "tracerefminus": { "valType": "integer", "min": 0, "dflt": 0, - "role": "style", - "editType": "colorbars", - "description": "Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to *auto*." - }, - "tick0": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is *log*, then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L* (see `dtick` for more info). If the axis `type` is *date*, it should be a date string, like date data. If the axis `type` is *category*, it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears." - }, - "dtick": { - "valType": "any", - "role": "style", - "editType": "colorbars", - "impliedEdits": { - "tickmode": "linear" - }, - "description": "Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to *log* and *date* axes. If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. *log* has several special values; *L*, where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5). `tick0` is ignored for *D1* and *D2*. If the axis `type` is *date*, then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. *date* also has special values *M* gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*. To set ticks every 4 years, set `dtick` to *M48*" - }, - "tickvals": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to *array*. Used with `ticktext`.", - "role": "data" - }, - "ticktext": { - "valType": "data_array", - "editType": "colorbars", - "description": "Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to *array*. Used with `tickvals`.", - "role": "data" - }, - "ticks": { - "valType": "enumerated", - "values": [ - "outside", - "inside", - "" - ], - "role": "style", - "editType": "colorbars", - "description": "Determines whether ticks are drawn or not. If **, this axis' ticks are not drawn. If *outside* (*inside*), this axis' are drawn outside (inside) the axis lines.", - "dflt": "" - }, - "ticklen": { - "valType": "number", - "min": 0, - "dflt": 5, - "role": "style", - "editType": "colorbars", - "description": "Sets the tick length (in px)." - }, - "tickwidth": { - "valType": "number", - "min": 0, - "dflt": 1, - "role": "style", - "editType": "colorbars", - "description": "Sets the tick width (in px)." - }, - "tickcolor": { - "valType": "color", - "dflt": "#444", - "role": "style", - "editType": "colorbars", - "description": "Sets the tick color." - }, - "showticklabels": { - "valType": "boolean", - "dflt": true, - "role": "style", - "editType": "colorbars", - "description": "Determines whether or not the tick labels are drawn." - }, - "tickfont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { - "valType": "number", - "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets the color bar's tick label font", - "editType": "colorbars", - "role": "object" - }, - "tickangle": { - "valType": "angle", - "dflt": "auto", - "role": "style", - "editType": "colorbars", - "description": "Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically." + "role": "info", + "editType": "calc" }, - "tickformat": { - "valType": "string", - "dflt": "", + "copy_ystyle": { + "valType": "boolean", "role": "style", - "editType": "colorbars", - "description": "Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to d3's date formatter: *%{n}f* for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat *%H~%M~%S.%2f* would display *09~15~23.46*" + "editType": "calc" }, - "tickformatstops": { - "items": { - "tickformatstop": { - "dtickrange": { - "valType": "info_array", - "role": "info", - "items": [ - { - "valType": "any", - "editType": "colorbars" - }, - { - "valType": "any", - "editType": "colorbars" - } - ], - "editType": "colorbars", - "description": "range [*min*, *max*], where *min*, *max* - dtick values which describe some zoom level, it is possible to omit *min* or *max* value by passing *null*" - }, - "value": { - "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "string - dtickformat for described zoom level, the same as *tickformat*" - }, - "editType": "colorbars", - "role": "object" - } - }, - "role": "object" + "color": { + "valType": "color", + "role": "style", + "editType": "calc", + "description": "Sets the stoke color of the error bars." }, - "tickprefix": { - "valType": "string", - "dflt": "", + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, "role": "style", - "editType": "colorbars", - "description": "Sets a tick label prefix." + "editType": "calc", + "description": "Sets the thickness (in px) of the error bars." }, - "showtickprefix": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "width": { + "valType": "number", + "min": 0, "role": "style", - "editType": "colorbars", - "description": "If *all*, all tick labels are displayed with a prefix. If *first*, only the first tick is displayed with a prefix. If *last*, only the last tick is displayed with a suffix. If *none*, tick prefixes are hidden." + "editType": "calc", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." }, - "ticksuffix": { + "editType": "calc", + "_deprecated": { + "opacity": { + "valType": "number", + "role": "style", + "editType": "calc", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } + }, + "role": "object", + "arraysrc": { "valType": "string", - "dflt": "", - "role": "style", - "editType": "colorbars", - "description": "Sets a tick label suffix." + "role": "info", + "description": "Sets the source reference on plot.ly for array .", + "editType": "none" }, - "showticksuffix": { + "arrayminussrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for arrayminus .", + "editType": "none" + } + }, + "error_y": { + "visible": { + "valType": "boolean", + "role": "info", + "editType": "calc", + "description": "Determines whether or not this set of error bars is visible." + }, + "type": { "valType": "enumerated", "values": [ - "all", - "first", - "last", - "none" + "percent", + "constant", + "sqrt", + "data" ], - "dflt": "all", - "role": "style", - "editType": "colorbars", - "description": "Same as `showtickprefix` but for tick suffixes." + "role": "info", + "editType": "calc", + "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." }, - "separatethousands": { + "symmetric": { "valType": "boolean", - "dflt": false, - "role": "style", - "editType": "colorbars", - "description": "If \"true\", even 4-digit integers are separated" + "role": "info", + "editType": "calc", + "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." }, - "exponentformat": { - "valType": "enumerated", - "values": [ - "none", - "e", - "E", - "power", - "SI", - "B" - ], - "dflt": "B", + "array": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", + "role": "data" + }, + "arrayminus": { + "valType": "data_array", + "editType": "calc", + "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", + "role": "data" + }, + "value": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." + }, + "valueminus": { + "valType": "number", + "min": 0, + "dflt": 10, + "role": "info", + "editType": "calc", + "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" + }, + "traceref": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" + }, + "tracerefminus": { + "valType": "integer", + "min": 0, + "dflt": 0, + "role": "info", + "editType": "calc" + }, + "color": { + "valType": "color", "role": "style", - "editType": "colorbars", - "description": "Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If *none*, it appears as 1,000,000,000. If *e*, 1e+9. If *E*, 1E+9. If *power*, 1x10^9 (with 9 in a super script). If *SI*, 1G. If *B*, 1B." + "editType": "calc", + "description": "Sets the stoke color of the error bars." }, - "showexponent": { - "valType": "enumerated", - "values": [ - "all", - "first", - "last", - "none" - ], - "dflt": "all", + "thickness": { + "valType": "number", + "min": 0, + "dflt": 2, "role": "style", - "editType": "colorbars", - "description": "If *all*, all exponents are shown besides their significands. If *first*, only the exponent of the first tick is shown. If *last*, only the exponent of the last tick is shown. If *none*, no exponents appear." + "editType": "calc", + "description": "Sets the thickness (in px) of the error bars." }, - "title": { - "valType": "string", - "role": "info", - "description": "Sets the title of the color bar.", - "editType": "colorbars" + "width": { + "valType": "number", + "min": 0, + "role": "style", + "editType": "calc", + "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." }, - "titlefont": { - "family": { - "valType": "string", - "role": "style", - "noBlank": true, - "strict": true, - "description": "HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The plotly service (at https://plot.ly or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include *Arial*, *Balto*, *Courier New*, *Droid Sans*,, *Droid Serif*, *Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*, *PT Sans Narrow*, *Raleway*, *Times New Roman*.", - "editType": "colorbars" - }, - "size": { + "editType": "calc", + "_deprecated": { + "opacity": { "valType": "number", "role": "style", - "min": 1, - "editType": "colorbars" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "colorbars" - }, - "description": "Sets this color bar's title font.", - "editType": "colorbars", - "role": "object" - }, - "titleside": { - "valType": "enumerated", - "values": [ - "right", - "top", - "bottom" - ], - "role": "style", - "dflt": "top", - "description": "Determines the location of the colorbar title with respect to the color bar.", - "editType": "colorbars" + "editType": "calc", + "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." + } }, - "editType": "colorbars", "role": "object", - "tickvalssrc": { + "arraysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for tickvals .", + "description": "Sets the source reference on plot.ly for array .", "editType": "none" }, - "ticktextsrc": { + "arrayminussrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for ticktext .", + "description": "Sets the source reference on plot.ly for arrayminus .", "editType": "none" } }, - "geo": { - "valType": "subplotid", + "xcalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], "role": "info", - "dflt": "geo", "editType": "calc", - "description": "Sets a reference between this trace's geospatial coordinates and a geographic map. If *geo* (the default value), the geospatial coordinates refer to `layout.geo`. If *geo2*, the geospatial coordinates refer to `layout.geo2`, and so on." + "dflt": "gregorian", + "description": "Sets the calendar system to use with `x` date data." + }, + "ycalendar": { + "valType": "enumerated", + "values": [ + "gregorian", + "chinese", + "coptic", + "discworld", + "ethiopian", + "hebrew", + "islamic", + "julian", + "mayan", + "nanakshahi", + "nepali", + "persian", + "jalali", + "taiwan", + "thai", + "ummalqura" + ], + "role": "info", + "editType": "calc", + "dflt": "gregorian", + "description": "Sets the calendar system to use with `y` date data." + }, + "xaxis": { + "valType": "subplotid", + "role": "info", + "dflt": "x", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." + }, + "yaxis": { + "valType": "subplotid", + "role": "info", + "dflt": "y", + "editType": "calc+clearAxisTypes", + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -19543,16 +21211,16 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "locationssrc": { + "xsrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for locations .", + "description": "Sets the source reference on plot.ly for x .", "editType": "none" }, - "zsrc": { + "ysrc": { "valType": "string", "role": "info", - "description": "Sets the source reference on plot.ly for z .", + "description": "Sets the source reference on plot.ly for y .", "editType": "none" }, "textsrc": { @@ -19563,13 +21231,12 @@ } } }, - "scattergl": { + "splom": { "meta": { - "hrName": "scatter_gl", - "description": "The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays." + "description": "Splom traces generate scatter plot matrix visualizations. Each splom `dimensions` items correspond to a generated axis. Values for each of those dimensions are set in `dimensions[i].values`. Splom traces support all `scattergl` marker style attributes. Specify `layout.grid` attributes and/or layout x-axis and y-axis attributes for more control over the axis positioning and style. " }, "attributes": { - "type": "scattergl", + "type": "splom", "visible": { "valType": "enumerated", "values": [ @@ -19765,45 +21432,39 @@ "editType": "calc", "role": "object" }, - "x": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the x coordinates.", - "role": "data" - }, - "x0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step." - }, - "dx": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the x coordinate step. See `x0` for more info." - }, - "y": { - "valType": "data_array", - "editType": "calc+clearAxisTypes", - "description": "Sets the y coordinates.", - "role": "data" - }, - "y0": { - "valType": "any", - "dflt": 0, - "role": "info", - "editType": "calc+clearAxisTypes", - "description": "Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step." - }, - "dy": { - "valType": "number", - "dflt": 1, - "role": "info", - "editType": "calc", - "description": "Sets the y coordinate step. See `y0` for more info." + "dimensions": { + "items": { + "dimension": { + "visible": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not this dimension is shown on the graph. Note that even visible false dimension contribute to the default grid generate by this splom trace." + }, + "label": { + "valType": "string", + "role": "info", + "editType": "calc", + "description": "Sets the label corresponding to this splom dimension." + }, + "values": { + "valType": "data_array", + "role": "data", + "editType": "calc+clearAxisTypes", + "description": "Sets the dimension values to be plotted." + }, + "editType": "calc+clearAxisTypes", + "role": "object", + "valuessrc": { + "valType": "string", + "role": "info", + "description": "Sets the source reference on plot.ly for values .", + "editType": "none" + } + } + }, + "role": "object" }, "text": { "valType": "string", @@ -19813,52 +21474,6 @@ "editType": "calc", "description": "Sets text elements associated with each (x,y) pair to appear on hover. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates." }, - "mode": { - "valType": "flaglist", - "flags": [ - "lines", - "markers" - ], - "extras": [ - "none" - ], - "role": "info", - "description": "Determines the drawing mode for this scatter trace.", - "editType": "calc" - }, - "line": { - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "description": "Sets the line color." - }, - "width": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "calc", - "description": "Sets the line width (in px)." - }, - "dash": { - "valType": "enumerated", - "values": [ - "solid", - "dot", - "dash", - "longdash", - "dashdot", - "longdashdot" - ], - "dflt": "solid", - "role": "style", - "description": "Sets the style of the lines.", - "editType": "calc" - }, - "editType": "calc", - "role": "object" - }, "marker": { "color": { "valType": "color", @@ -20802,44 +22417,54 @@ "editType": "none" } }, - "connectgaps": { - "valType": "boolean", - "dflt": false, + "xaxes": { + "valType": "info_array", + "freeLength": true, "role": "info", "editType": "calc", - "description": "Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected." + "items": { + "valType": "subplotid", + "regex": "/^x([2-9]|[1-9][0-9]+)?$/", + "editType": "plot" + }, + "description": "Sets the list of x axes corresponding to this splom trace. By default, a splom will match the first N xaxes where N is the number of input dimensions." }, - "fill": { - "valType": "enumerated", - "values": [ - "none", - "tozeroy", - "tozerox", - "tonexty", - "tonextx", - "toself", - "tonext" - ], - "dflt": "none", - "role": "style", + "yaxes": { + "valType": "info_array", + "freeLength": true, + "role": "info", "editType": "calc", - "description": "Sets the area to fill with a solid color. Use with `fillcolor` if not *none*. *tozerox* and *tozeroy* fill to x=0 and y=0 respectively. *tonextx* and *tonexty* fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like *tozerox* and *tozeroy*. *toself* connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. *tonext* fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like *toself* if there is no trace before it. *tonext* should not be used if one trace does not enclose the other." + "items": { + "valType": "subplotid", + "regex": "/^y([2-9]|[1-9][0-9]+)?$/", + "editType": "plot" + }, + "description": "Sets the list of y axes corresponding to this splom trace. By default, a splom will match the first N yaxes where N is the number of input dimensions." }, - "fillcolor": { - "valType": "color", - "role": "style", + "diagonal": { + "visible": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not subplots on the diagonal are displayed." + }, "editType": "calc", - "description": "Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available." + "role": "object" }, - "hoveron": { - "valType": "flaglist", - "flags": [ - "points", - "fills" - ], + "showupperhalf": { + "valType": "boolean", "role": "info", + "dflt": true, "editType": "calc", - "description": "Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is *toself* or *tonext* and there are no markers or text, then the default is *fills*, otherwise it is *points*." + "description": "Determines whether or not subplots on the upper half from the diagonal are displayed." + }, + "showlowerhalf": { + "valType": "boolean", + "role": "info", + "dflt": true, + "editType": "calc", + "description": "Determines whether or not subplots on the lower half from the diagonal are displayed." }, "selected": { "marker": { @@ -20899,297 +22524,6 @@ "editType": "calc", "role": "object" }, - "error_x": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." - }, - "type": { - "valType": "enumerated", - "values": [ - "percent", - "constant", - "sqrt", - "data" - ], - "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." - }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." - }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" - }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" - }, - "value": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." - }, - "valueminus": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" - }, - "traceref": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "calc" - }, - "tracerefminus": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "calc" - }, - "copy_ystyle": { - "valType": "boolean", - "role": "style", - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "description": "Sets the stoke color of the error bars." - }, - "thickness": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "calc", - "description": "Sets the thickness (in px) of the error bars." - }, - "width": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." - }, - "editType": "calc", - "_deprecated": { - "opacity": { - "valType": "number", - "role": "style", - "editType": "calc", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } - }, - "role": "object", - "arraysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for array .", - "editType": "none" - }, - "arrayminussrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", - "editType": "none" - } - }, - "error_y": { - "visible": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not this set of error bars is visible." - }, - "type": { - "valType": "enumerated", - "values": [ - "percent", - "constant", - "sqrt", - "data" - ], - "role": "info", - "editType": "calc", - "description": "Determines the rule used to generate the error bars. If *constant`, the bar lengths are of a constant value. Set this constant in `value`. If *percent*, the bar lengths correspond to a percentage of underlying data. Set this percentage in `value`. If *sqrt*, the bar lengths correspond to the sqaure of the underlying data. If *array*, the bar lengths are set with data set `array`." - }, - "symmetric": { - "valType": "boolean", - "role": "info", - "editType": "calc", - "description": "Determines whether or not the error bars have the same length in both direction (top/bottom for vertical bars, left/right for horizontal bars." - }, - "array": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar. Values are plotted relative to the underlying data.", - "role": "data" - }, - "arrayminus": { - "valType": "data_array", - "editType": "calc", - "description": "Sets the data corresponding the length of each error bar in the bottom (left) direction for vertical (horizontal) bars Values are plotted relative to the underlying data.", - "role": "data" - }, - "value": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars." - }, - "valueminus": { - "valType": "number", - "min": 0, - "dflt": 10, - "role": "info", - "editType": "calc", - "description": "Sets the value of either the percentage (if `type` is set to *percent*) or the constant (if `type` is set to *constant*) corresponding to the lengths of the error bars in the bottom (left) direction for vertical (horizontal) bars" - }, - "traceref": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "calc" - }, - "tracerefminus": { - "valType": "integer", - "min": 0, - "dflt": 0, - "role": "info", - "editType": "calc" - }, - "color": { - "valType": "color", - "role": "style", - "editType": "calc", - "description": "Sets the stoke color of the error bars." - }, - "thickness": { - "valType": "number", - "min": 0, - "dflt": 2, - "role": "style", - "editType": "calc", - "description": "Sets the thickness (in px) of the error bars." - }, - "width": { - "valType": "number", - "min": 0, - "role": "style", - "editType": "calc", - "description": "Sets the width (in px) of the cross-bar at both ends of the error bars." - }, - "editType": "calc", - "_deprecated": { - "opacity": { - "valType": "number", - "role": "style", - "editType": "calc", - "description": "Obsolete. Use the alpha channel in error bar `color` to set the opacity." - } - }, - "role": "object", - "arraysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for array .", - "editType": "none" - }, - "arrayminussrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for arrayminus .", - "editType": "none" - } - }, - "xcalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `x` date data." - }, - "ycalendar": { - "valType": "enumerated", - "values": [ - "gregorian", - "chinese", - "coptic", - "discworld", - "ethiopian", - "hebrew", - "islamic", - "julian", - "mayan", - "nanakshahi", - "nepali", - "persian", - "jalali", - "taiwan", - "thai", - "ummalqura" - ], - "role": "info", - "editType": "calc", - "dflt": "gregorian", - "description": "Sets the calendar system to use with `y` date data." - }, - "xaxis": { - "valType": "subplotid", - "role": "info", - "dflt": "x", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If *x* (the default value), the x coordinates refer to `layout.xaxis`. If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." - }, - "yaxis": { - "valType": "subplotid", - "role": "info", - "dflt": "y", - "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." - }, "idssrc": { "valType": "string", "role": "info", @@ -21208,18 +22542,6 @@ "description": "Sets the source reference on plot.ly for hoverinfo .", "editType": "none" }, - "xsrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for x .", - "editType": "none" - }, - "ysrc": { - "valType": "string", - "role": "info", - "description": "Sets the source reference on plot.ly for y .", - "editType": "none" - }, "textsrc": { "valType": "string", "role": "info", @@ -21550,7 +22872,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -22411,7 +23733,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -22852,6 +24174,8 @@ "constraintrange": { "valType": "info_array", "role": "info", + "freeLength": true, + "dimensions": "1-2", "items": [ { "valType": "number", @@ -22863,7 +24187,14 @@ } ], "editType": "calc", - "description": "The domain range to which the filter on the dimension is constrained. Must be an array of `[fromValue, toValue]` with finite numbers as elements." + "description": "The domain range to which the filter on the dimension is constrained. Must be an array of `[fromValue, toValue]` with `fromValue <= toValue`, or if `multiselect` is not disabled, you may give an array of arrays, where each inner array is `[fromValue, toValue]`." + }, + "multiselect": { + "valType": "boolean", + "dflt": true, + "role": "info", + "editType": "calc", + "description": "Do we allow multiple selection ranges or just a single range?" }, "values": { "valType": "data_array", @@ -27034,7 +28365,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -28553,7 +29884,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -29603,7 +30934,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -29651,7 +30982,7 @@ }, "ohlc": { "meta": { - "description": "The ohlc (short for Open-High-Low-Close) is a style of financial chart describing open, high, low and close for a given `x` coordinate (most likely time). The tip of the lines represent the `low` and `high` values and the horizontal segments represent the `open` and `close` values. Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). By default, increasing candles are drawn in green whereas decreasing are drawn in red." + "description": "The ohlc (short for Open-High-Low-Close) is a style of financial chart describing open, high, low and close for a given `x` coordinate (most likely time). The tip of the lines represent the `low` and `high` values and the horizontal segments represent the `open` and `close` values. Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). By default, increasing items are drawn in green whereas decreasing are drawn in red." }, "attributes": { "type": "ohlc", @@ -29858,28 +31189,24 @@ }, "open": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the open values.", "role": "data" }, "high": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the high values.", "role": "data" }, "low": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the low values.", "role": "data" }, "close": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the close values.", "role": "data" @@ -29912,19 +31239,6 @@ "role": "object" }, "increasing": { - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the segment name. The segment name appear as the legend item and on hover." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this segment is shown in the legend." - }, "line": { "color": { "valType": "color", @@ -29963,19 +31277,6 @@ "role": "object" }, "decreasing": { - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the segment name. The segment name appear as the legend item and on hover." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this segment is shown in the legend." - }, "line": { "color": { "valType": "color", @@ -30067,7 +31368,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -30334,28 +31635,24 @@ }, "open": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the open values.", "role": "data" }, "high": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the high values.", "role": "data" }, "low": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the low values.", "role": "data" }, "close": { "valType": "data_array", - "dflt": [], "editType": "calc", "description": "Sets the close values.", "role": "data" @@ -30373,19 +31670,6 @@ "role": "object" }, "increasing": { - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the segment name. The segment name appear as the legend item and on hover." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this segment is shown in the legend." - }, "line": { "color": { "valType": "color", @@ -30415,19 +31699,6 @@ "role": "object" }, "decreasing": { - "name": { - "valType": "string", - "role": "info", - "editType": "style", - "description": "Sets the segment name. The segment name appear as the legend item and on hover." - }, - "showlegend": { - "valType": "boolean", - "role": "info", - "dflt": true, - "editType": "style", - "description": "Determines whether or not an item corresponding to this segment is shown in the legend." - }, "line": { "color": { "valType": "color", @@ -30510,7 +31781,7 @@ "role": "info", "dflt": "y", "editType": "calc+clearAxisTypes", - "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.xaxis2`, and so on." + "description": "Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If *y* (the default value), the y coordinates refer to `layout.yaxis`. If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." }, "idssrc": { "valType": "string", @@ -30566,6 +31837,37 @@ "description": "Sets the source reference on plot.ly for text .", "editType": "none" } + }, + "layoutAttributes": { + "boxmode": { + "valType": "enumerated", + "values": [ + "group", + "overlay" + ], + "dflt": "overlay", + "role": "info", + "editType": "calc", + "description": "Determines how boxes at the same location coordinate are displayed on the graph. If *group*, the boxes are plotted next to one another centered around the shared location. If *overlay*, the boxes are plotted over one another, you might need to set *opacity* to see them multiple boxes." + }, + "boxgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.3, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between boxes of adjacent location coordinates." + }, + "boxgroupgap": { + "valType": "number", + "min": 0, + "max": 1, + "dflt": 0.3, + "role": "style", + "editType": "calc", + "description": "Sets the gap (in plot fraction) between boxes of the same location coordinate." + } } }, "scatterpolar": { @@ -34365,6 +35667,19 @@ "editType": "none", "role": "object" }, + "selectdirection": { + "valType": "enumerated", + "role": "info", + "values": [ + "h", + "v", + "d", + "any" + ], + "dflt": "any", + "description": "When \"dragmode\" is set to \"select\", this limits the selection of the drag to horizontal, vertical or diagonal. \"h\" only allows horizontal selection, \"v\" only vertical, \"d\" only diagonal and \"any\" sets no limit.", + "editType": "none" + }, "grid": { "rows": { "valType": "integer", @@ -34526,7 +35841,7 @@ ], "dflt": "bottom plot", "role": "info", - "editType": "ticks", + "editType": "plot", "description": "Sets where the x axis labels and titles go. *bottom* means the very bottom of the grid. *bottom plot* is the lowest plot that each x axis is used in. *top* and *top plot* are similar." }, "yside": { @@ -34539,7 +35854,7 @@ ], "dflt": "left plot", "role": "info", - "editType": "ticks", + "editType": "plot", "description": "Sets where the y axis labels and titles go. *left* means the very left edge of the grid. *left plot* is the leftmost plot that each y axis is used in. *right* and *right plot* are similar." }, "editType": "plot", @@ -34659,20 +35974,20 @@ "items": [ { "valType": "any", - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "^autorange": false } }, { "valType": "any", - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "^autorange": false } } ], - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "autorange": false }, @@ -35618,20 +36933,20 @@ "items": [ { "valType": "any", - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "^autorange": false } }, { "valType": "any", - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "^autorange": false } } ], - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "autorange": false }, @@ -40514,20 +41829,20 @@ "items": [ { "valType": "any", - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "^autorange": false } }, { "valType": "any", - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "^autorange": false } } ], - "editType": "plot+margins", + "editType": "axrange+margins", "impliedEdits": { "autorange": false }, @@ -42123,7 +43438,7 @@ ], "role": "info", "editType": "calcIfAutorange+arraydraw", - "description": "Specifies the shape type to be drawn. If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`) If *circle*, a circle is drawn from ((`x0`+`x1`)/2, (`y0`+`y1`)/2)) with radius (|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|) If *rect*, a rectangle is drawn linking (`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`) If *path*, draw a custom SVG path using `path`." + "description": "Specifies the shape type to be drawn. If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`) with respect to the axes' sizing mode. If *circle*, a circle is drawn from ((`x0`+`x1`)/2, (`y0`+`y1`)/2)) with radius (|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|) with respect to the axes' sizing mode. If *rect*, a rectangle is drawn linking (`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`) with respect to the axes' sizing mode. If *path*, draw a custom SVG path using `path`. with respect to the axes' sizing mode." }, "layer": { "valType": "enumerated", @@ -42144,19 +43459,36 @@ ], "role": "info", "editType": "calc", - "description": "Sets the shape's x coordinate axis. If set to an x axis id (e.g. *x* or *x2*), the `x` position refers to an x coordinate If set to *paper*, the `x` position refers to the distance from the left side of the plotting area in normalized coordinates where *0* (*1*) corresponds to the left (right) side. If the axis `type` is *log*, then you must take the log of your desired range. If the axis `type` is *date*, then you must convert the date to unix time in milliseconds." + "description": "Sets the shape's x coordinate axis. If set to an x axis id (e.g. *x* or *x2*), the `x` position refers to an x coordinate. If set to *paper*, the `x` position refers to the distance from the left side of the plotting area in normalized coordinates where *0* (*1*) corresponds to the left (right) side. If the axis `type` is *log*, then you must take the log of your desired range. If the axis `type` is *date*, then you must convert the date to unix time in milliseconds." + }, + "xsizemode": { + "valType": "enumerated", + "values": [ + "scaled", + "pixel" + ], + "dflt": "scaled", + "role": "info", + "editType": "calcIfAutorange+arraydraw", + "description": "Sets the shapes's sizing mode along the x axis. If set to *scaled*, `x0`, `x1` and x coordinates within `path` refer to data values on the x axis or a fraction of the plot area's width (`xref` set to *paper*). If set to *pixel*, `xanchor` specifies the x position in terms of data or plot fraction but `x0`, `x1` and x coordinates within `path` are pixels relative to `xanchor`. This way, the shape can have a fixed width while maintaining a position relative to data or plot fraction." + }, + "xanchor": { + "valType": "any", + "role": "info", + "editType": "calcIfAutorange+arraydraw", + "description": "Only relevant in conjunction with `xsizemode` set to *pixel*. Specifies the anchor point on the x axis to which `x0`, `x1` and x coordinates within `path` are relative to. E.g. useful to attach a pixel sized shape to a certain data value. No effect when `xsizemode` not set to *pixel*." }, "x0": { "valType": "any", "role": "info", "editType": "calcIfAutorange+arraydraw", - "description": "Sets the shape's starting x position. See `type` for more info." + "description": "Sets the shape's starting x position. See `type` and `xsizemode` for more info." }, "x1": { "valType": "any", "role": "info", "editType": "calcIfAutorange+arraydraw", - "description": "Sets the shape's end x position. See `type` for more info." + "description": "Sets the shape's end x position. See `type` and `xsizemode` for more info." }, "yref": { "valType": "enumerated", @@ -42168,23 +43500,40 @@ "editType": "calc", "description": "Sets the annotation's y coordinate axis. If set to an y axis id (e.g. *y* or *y2*), the `y` position refers to an y coordinate If set to *paper*, the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where *0* (*1*) corresponds to the bottom (top)." }, + "ysizemode": { + "valType": "enumerated", + "values": [ + "scaled", + "pixel" + ], + "dflt": "scaled", + "role": "info", + "editType": "calcIfAutorange+arraydraw", + "description": "Sets the shapes's sizing mode along the y axis. If set to *scaled*, `y0`, `y1` and y coordinates within `path` refer to data values on the y axis or a fraction of the plot area's height (`yref` set to *paper*). If set to *pixel*, `yanchor` specifies the y position in terms of data or plot fraction but `y0`, `y1` and y coordinates within `path` are pixels relative to `yanchor`. This way, the shape can have a fixed height while maintaining a position relative to data or plot fraction." + }, + "yanchor": { + "valType": "any", + "role": "info", + "editType": "calcIfAutorange+arraydraw", + "description": "Only relevant in conjunction with `ysizemode` set to *pixel*. Specifies the anchor point on the y axis to which `y0`, `y1` and y coordinates within `path` are relative to. E.g. useful to attach a pixel sized shape to a certain data value. No effect when `ysizemode` not set to *pixel*." + }, "y0": { "valType": "any", "role": "info", "editType": "calcIfAutorange+arraydraw", - "description": "Sets the shape's starting y position. See `type` for more info." + "description": "Sets the shape's starting y position. See `type` and `ysizemode` for more info." }, "y1": { "valType": "any", "role": "info", "editType": "calcIfAutorange+arraydraw", - "description": "Sets the shape's end y position. See `type` for more info." + "description": "Sets the shape's end y position. See `type` and `ysizemode` for more info." }, "path": { "valType": "string", "role": "info", "editType": "calcIfAutorange+arraydraw", - "description": "For `type` *path* - a valid SVG path but with the pixel values replaced by data values. There are a few restrictions / quirks only absolute instructions, not relative. So the allowed segments are: M, L, H, V, Q, C, T, S, and Z arcs (A) are not allowed because radius rx and ry are relative. In the future we could consider supporting relative commands, but we would have to decide on how to handle date and log axes. Note that even as is, Q and C Bezier paths that are smooth on linear axes may not be smooth on log, and vice versa. no chained \"polybezier\" commands - specify the segment type for each one. On category axes, values are numbers scaled to the serial numbers of categories because using the categories themselves there would be no way to describe fractional positions On data axes: because space and T are both normal components of path strings, we can't use either to separate date from time parts. Therefore we'll use underscore for this purpose: 2015-02-21_13:45:56.789" + "description": "For `type` *path* - a valid SVG path with the pixel values replaced by data values in `xsizemode`/`ysizemode` being *scaled* and taken unmodified as pixels relative to `xanchor` and `yanchor` in case of *pixel* size mode. There are a few restrictions / quirks only absolute instructions, not relative. So the allowed segments are: M, L, H, V, Q, C, T, S, and Z arcs (A) are not allowed because radius rx and ry are relative. In the future we could consider supporting relative commands, but we would have to decide on how to handle date and log axes. Note that even as is, Q and C Bezier paths that are smooth on linear axes may not be smooth on log, and vice versa. no chained \"polybezier\" commands - specify the segment type for each one. On category axes, values are numbers scaled to the serial numbers of categories because using the categories themselves there would be no way to describe fractional positions On data axes: because space and T are both normal components of path strings, we can't use either to separate date from time parts. Therefore we'll use underscore for this purpose: 2015-02-21_13:45:56.789" }, "opacity": { "valType": "number", @@ -42999,12 +44348,6 @@ } }, "transforms": { - "candlestick": { - "attributes": {} - }, - "ohlc": { - "attributes": {} - }, "aggregate": { "attributes": { "enabled": { diff --git a/dist/plotly-basic.js b/dist/plotly-basic.js index 1e0815e03a1..7ebccc5a531 100644 --- a/dist/plotly-basic.js +++ b/dist/plotly-basic.js @@ -1,5 +1,5 @@ /** -* plotly.js (basic) v1.35.2 +* plotly.js (basic) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -11218,7 +11218,7 @@ var _$interactions_144 = { DESELECTDIM: 0.2 }; -var _$is_array_163 = {}; +var _$is_array_164 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11239,12 +11239,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_163.isTypedArray = function(a) { +_$is_array_164.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_163.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_163.isTypedArray(a); +_$is_array_164.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_164.isTypedArray(a); }; /** @@ -11259,7 +11259,7 @@ _$is_array_163.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_164 = function isPlainObject(obj) { +var _$isPlainObject_165 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11275,7 +11275,7 @@ var _$isPlainObject_164 = function isPlainObject(obj) { ); }; -var _$extend_156 = {}; +var _$extend_157 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11287,7 +11287,7 @@ var _$extend_156 = {}; 'use strict'; -/* removed: var _$isPlainObject_164 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_165 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11304,19 +11304,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_156.extendFlat = function() { +_$extend_157.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_156.extendDeep = function() { +_$extend_157.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_156.extendDeepAll = function() { +_$extend_157.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_156.extendDeepNoArrays = function() { +_$extend_157.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11369,12 +11369,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_164(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_165(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_164(src) ? src : {}; + clone = src && _$isPlainObject_165(src) ? src : {}; } // never move original objects, clone them @@ -11409,7 +11409,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_194 = { +var _$plot_config_195 = { // no interactivity, for export or image generation staticPlot: false, @@ -11577,7 +11577,7 @@ var _$plot_config_194 = { locales: {} }; -var _$loggers_167 = {}; +var _$loggers_168 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11590,9 +11590,9 @@ var _$loggers_167 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_194 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_195 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_167 = {}; +var loggers = _$loggers_168 = {}; /** * ------------------------------------------ @@ -11601,7 +11601,7 @@ var loggers = _$loggers_167 = {}; */ loggers.log = function() { - if(_$plot_config_194.logging > 1) { + if(_$plot_config_195.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11613,7 +11613,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_194.logging > 0) { + if(_$plot_config_195.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11625,7 +11625,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_194.logging > 0) { + if(_$plot_config_195.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11664,7 +11664,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_171 = function noop() {}; +var _$noop_172 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11689,7 +11689,7 @@ var _$noop_171 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_175 = function pushUnique(array, item) { +var _$pushUnique_176 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11826,7 +11826,7 @@ var _$attributes_77 = { /* removed: var _$attributes_77 = require('../components/fx/attributes'); */; -var _$attributes_201 = { +var _$attributes_202 = { type: { valType: 'enumerated', @@ -12132,7 +12132,7 @@ var _$layout_attributes_235 = { } }; -var _$registry_244 = {}; +var _$registry_245 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12143,29 +12143,29 @@ var _$registry_244 = {}; 'use strict'; -/* removed: var _$loggers_167 = require('./lib/loggers'); */; -/* removed: var _$noop_171 = require('./lib/noop'); */; -/* removed: var _$pushUnique_175 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_164 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_156 = require('./lib/extend'); */; +/* removed: var _$loggers_168 = require('./lib/loggers'); */; +/* removed: var _$noop_172 = require('./lib/noop'); */; +/* removed: var _$pushUnique_176 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_165 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_157 = require('./lib/extend'); */; -/* removed: var _$attributes_201 = require('./plots/attributes'); */; +/* removed: var _$attributes_202 = require('./plots/attributes'); */; /* removed: var _$layout_attributes_235 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_156.extendFlat; -var extendDeepAll = _$extend_156.extendDeepAll; - -_$registry_244.modules = {}; -_$registry_244.allCategories = {}; -_$registry_244.allTypes = []; -_$registry_244.subplotsRegistry = {}; -_$registry_244.transformsRegistry = {}; -_$registry_244.componentsRegistry = {}; -_$registry_244.layoutArrayContainers = []; -_$registry_244.layoutArrayRegexes = []; -_$registry_244.traceLayoutAttributes = {}; -_$registry_244.localeRegistry = {}; -_$registry_244.apiMethodRegistry = {}; +var extendFlat = _$extend_157.extendFlat; +var extendDeepAll = _$extend_157.extendDeepAll; + +_$registry_245.modules = {}; +_$registry_245.allCategories = {}; +_$registry_245.allTypes = []; +_$registry_245.subplotsRegistry = {}; +_$registry_245.transformsRegistry = {}; +_$registry_245.componentsRegistry = {}; +_$registry_245.layoutArrayContainers = []; +_$registry_245.layoutArrayRegexes = []; +_$registry_245.traceLayoutAttributes = {}; +_$registry_245.localeRegistry = {}; +_$registry_245.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12206,7 +12206,7 @@ _$registry_244.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_244.register = function register(_modules) { +_$registry_245.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12235,7 +12235,7 @@ _$registry_244.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_244.apiMethodRegistry[name] = newModule.fn; + _$registry_245.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12251,8 +12251,8 @@ _$registry_244.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_244.getModule = function(trace) { - var _module = _$registry_244.modules[getTraceType(trace)]; +_$registry_245.getModule = function(trace) { + var _module = _$registry_245.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12266,20 +12266,20 @@ _$registry_244.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_244.traceIs = function(traceType, category) { +_$registry_245.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_244.modules[traceType]; + var _module = _$registry_245.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_167.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_168.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_244.modules[_$attributes_201.type.dflt]; + _module = _$registry_245.modules[_$attributes_202.type.dflt]; } return !!_module.categories[category]; @@ -12296,7 +12296,7 @@ _$registry_244.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_244.getTransformIndices = function(data, type) { +_$registry_245.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12316,7 +12316,7 @@ _$registry_244.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_244.hasTransform = function(data, type) { +_$registry_245.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12336,11 +12336,11 @@ _$registry_244.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_244.getComponentMethod = function(name, method) { - var _module = _$registry_244.componentsRegistry[name]; +_$registry_245.getComponentMethod = function(name, method) { + var _module = _$registry_245.componentsRegistry[name]; - if(!_module) return _$noop_171; - return _module[method] || _$noop_171; + if(!_module) return _$noop_172; + return _module[method] || _$noop_172; }; /** @@ -12350,10 +12350,10 @@ _$registry_244.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_244.call = function() { +_$registry_245.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_244.apiMethodRegistry[name].apply(null, args); + return _$registry_245.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12361,33 +12361,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_244.modules[thisType]) { - _$loggers_167.log('Type ' + thisType + ' already registered'); + if(_$registry_245.modules[thisType]) { + _$loggers_168.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_244.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_245.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_244.allCategories[categoriesIn[i]] = true; + _$registry_245.allCategories[categoriesIn[i]] = true; } - _$registry_244.modules[thisType] = { + _$registry_245.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_244.modules[thisType].meta = meta; + _$registry_245.modules[thisType].meta = meta; } - _$registry_244.allTypes.push(thisType); + _$registry_245.allTypes.push(thisType); - for(var componentName in _$registry_244.componentsRegistry) { + for(var componentName in _$registry_245.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12397,15 +12397,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_244.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_245.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_244.subplotsRegistry[plotType]) { - _$loggers_167.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_245.subplotsRegistry[plotType]) { + _$loggers_168.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12415,9 +12415,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_244.subplotsRegistry[plotType] = _module; + _$registry_245.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_244.componentsRegistry) { + for(var componentName in _$registry_245.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12428,24 +12428,24 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_244.componentsRegistry[name] = _module; + _$registry_245.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_175(_$registry_244.layoutArrayContainers, name); + _$pushUnique_176(_$registry_245.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_244.modules) { + for(var traceType in _$registry_245.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_244.subplotsRegistry) { + for(var subplotName in _$registry_245.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_244.transformsRegistry) { + for(var transformType in _$registry_245.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } @@ -12467,22 +12467,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_167.log([ + _$loggers_168.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_164(_module.attributes)) { - _$loggers_167.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_165(_module.attributes)) { + _$loggers_168.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_167.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_168.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_244.transformsRegistry[_module.name] = _module; + _$registry_245.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_244.componentsRegistry) { + for(var componentName in _$registry_245.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12496,7 +12496,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_244.localeRegistry; + var locales = _$registry_245.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12528,37 +12528,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_175(_$registry_244.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_176(_$registry_245.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_244.componentsRegistry[componentName].schema; + var componentSchema = _$registry_245.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_244.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_245.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_244.componentsRegistry[componentName].schema; + var componentSchema = _$registry_245.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_244.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_245.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_244.componentsRegistry[componentName].schema; + var componentSchema = _$registry_245.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_244.subplotsRegistry[subplotName]; + var subplotModule = _$registry_245.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12585,7 +12585,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_244 = require('../registry'); */; +/* removed: var _$registry_245 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12600,9 +12600,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_188 = function containerArrayMatch(astr) { - var rootContainers = _$registry_244.layoutArrayContainers, - regexpContainers = _$registry_244.layoutArrayRegexes, +var _$containerArrayMatch_189 = function containerArrayMatch(astr) { + var rootContainers = _$registry_245.layoutArrayContainers, + regexpContainers = _$registry_245.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12643,9 +12643,9 @@ var _$containerArrayMatch_188 = function containerArrayMatch(astr) { 'use strict'; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_163.isArrayOrTypedArray; -/* removed: var _$isPlainObject_164 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_188 = require('../plot_api/container_array_match'); */; +var isArrayOrTypedArray = _$is_array_164.isArrayOrTypedArray; +/* removed: var _$isPlainObject_165 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_189 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12661,7 +12661,7 @@ var isArrayOrTypedArray = _$is_array_163.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_170 = function nestedProperty(container, propStr) { +var _$nestedProperty_171 = function nestedProperty(container, propStr) { if(_$fastIsnumeric_10(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { @@ -12772,7 +12772,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_164(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_165(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12781,7 +12781,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_188(propStr); + var match = _$containerArrayMatch_189(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12934,7 +12934,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_177 = {}; +var _$regex_178 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12954,7 +12954,7 @@ var _$regex_177 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_177.counter = function(head, tail, openEnded) { +_$regex_178.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12962,7 +12962,7 @@ _$regex_177.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_152 = {}; +var _$coerce_153 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12977,16 +12977,16 @@ var _$coerce_152 = {}; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$attributes_201 = require('../plots/attributes'); */; +/* removed: var _$attributes_202 = require('../plots/attributes'); */; /* removed: var _$getScale_56 = require('../components/colorscale/get_scale'); */; var colorscaleNames = Object.keys(_$scales_62); -/* removed: var _$nestedProperty_170 = require('./nested_property'); */; -var counterRegex = _$regex_177.counter; +/* removed: var _$nestedProperty_171 = require('./nested_property'); */; +var counterRegex = _$regex_178.counter; var DESELECTDIM = _$interactions_144.DESELECTDIM; var wrap180 = _$angles_150.wrap180; -var __isArrayOrTypedArray_152 = _$is_array_163.isArrayOrTypedArray; +var __isArrayOrTypedArray_153 = _$is_array_164.isArrayOrTypedArray; -_$coerce_152.valObjectMeta = { +_$coerce_153.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12994,7 +12994,7 @@ _$coerce_152.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_152(v)) propOut.set(v); + if(__isArrayOrTypedArray_153(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13117,8 +13117,9 @@ _$coerce_152.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13172,9 +13173,11 @@ _$coerce_152.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13185,12 +13188,12 @@ _$coerce_152.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_152.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_153.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13200,19 +13203,28 @@ _$coerce_152.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13243,12 +13255,12 @@ _$coerce_152.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_152.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_153.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_152.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_153.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13268,10 +13280,10 @@ _$coerce_152.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_152.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_170(attributes, attribute).get(), - propIn = _$nestedProperty_170(containerIn, attribute), - propOut = _$nestedProperty_170(containerOut, attribute), +_$coerce_153.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_171(attributes, attribute).get(), + propIn = _$nestedProperty_171(containerIn, attribute), + propOut = _$nestedProperty_171(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13282,12 +13294,12 @@ _$coerce_152.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_152(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_153(v)) { propOut.set(v); return v; } - _$coerce_152.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_153.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13299,9 +13311,9 @@ _$coerce_152.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_152.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_170(containerIn, attribute), - propOut = _$coerce_152.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_153.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_171(containerIn, attribute), + propOut = _$coerce_153.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13312,7 +13324,7 @@ _$coerce_152.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_152.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_153.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13332,11 +13344,9 @@ _$coerce_152.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_152.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_153.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_201; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_202; var valObj = attrs.hoverinfo; var dflt; @@ -13350,7 +13360,7 @@ _$coerce_152.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_152.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_153.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13364,7 +13374,7 @@ _$coerce_152.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_152.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_153.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13379,7 +13389,7 @@ _$coerce_152.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_152(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_153(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13388,10 +13398,10 @@ _$coerce_152.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_152.validate = function(value, opts) { - var valObjectDef = _$coerce_152.valObjectMeta[opts.valType]; +_$coerce_153.validate = function(value, opts) { + var valObjectDef = _$coerce_153.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_152(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_153(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13421,12 +13431,12 @@ _$coerce_152.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_169 = function mod(v, d) { +var _$mod_170 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_153 = {}; +var _$dates_154 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13441,18 +13451,18 @@ var _$dates_153 = {}; /* removed: var _$d3_7 = require('d3'); */; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$loggers_167 = require('./loggers'); */; -/* removed: var _$mod_169 = require('./mod'); */; +/* removed: var _$loggers_168 = require('./loggers'); */; +/* removed: var _$mod_170 = require('./mod'); */; /* removed: var _$numerical_145 = require('../constants/numerical'); */; -var __BADNUM_153 = _$numerical_145.BADNUM; +var __BADNUM_154 = _$numerical_145.BADNUM; var ONEDAY = _$numerical_145.ONEDAY; var ONEHOUR = _$numerical_145.ONEHOUR; var ONEMIN = _$numerical_145.ONEMIN; var ONESEC = _$numerical_145.ONESEC; var EPOCHJD = _$numerical_145.EPOCHJD; -/* removed: var _$registry_244 = require('../registry'); */; +/* removed: var _$registry_245 = require('../registry'); */; var utcFormat = _$d3_7.time.format.utc; @@ -13466,7 +13476,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_244.componentsRegistry.calendars && + _$registry_245.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13476,11 +13486,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_153.dateTick0 = function(calendar, sunday) { +_$dates_154.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_244.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_244.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_245.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_245.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13490,9 +13500,9 @@ _$dates_153.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_153.dfltRange = function(calendar) { +_$dates_154.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_244.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_245.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13500,7 +13510,7 @@ _$dates_153.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_153.isJSDate = function(v) { +_$dates_154.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13562,17 +13572,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_153.dateTime2ms = function(s, calendar) { +_$dates_154.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_153.isJSDate(s)) { + if(_$dates_154.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_153; + return __BADNUM_154; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_153; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_154; s = String(s); @@ -13589,7 +13599,7 @@ _$dates_153.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_153; + if(!match) return __BADNUM_154; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13599,12 +13609,12 @@ _$dates_153.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_153; + if(y.length === 2) return __BADNUM_154; y = Number(y); var cDate; try { - var calInstance = _$registry_244.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_245.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13614,9 +13624,9 @@ _$dates_153.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_153; } // Invalid ... date + catch(e) { return __BADNUM_154; } // Invalid ... date - if(!cDate) return __BADNUM_153; + if(!cDate) return __BADNUM_154; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13637,18 +13647,18 @@ _$dates_153.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_153; - if(date.getUTCDate() !== d) return __BADNUM_153; + if(date.getUTCMonth() !== m) return __BADNUM_154; + if(date.getUTCDate() !== d) return __BADNUM_154; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_153.MIN_MS = _$dates_153.dateTime2ms('-9999'); -MAX_MS = _$dates_153.MAX_MS = _$dates_153.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_154.MIN_MS = _$dates_154.dateTime2ms('-9999'); +MAX_MS = _$dates_154.MAX_MS = _$dates_154.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_153.isDateTime = function(s, calendar) { - return (_$dates_153.dateTime2ms(s, calendar) !== __BADNUM_153); +_$dates_154.isDateTime = function(s, calendar) { + return (_$dates_154.dateTime2ms(s, calendar) !== __BADNUM_154); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13667,20 +13677,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_153.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_153; +_$dates_154.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_154; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_169(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_170(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_169(ms, ONEDAY)); + timeMs = Math.floor(_$mod_170(ms, ONEDAY)); try { - dateStr = _$registry_244.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_245.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13728,10 +13738,10 @@ _$dates_153.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_153.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_153; +_$dates_154.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_154; - var msecTenths = Math.floor(_$mod_169(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_170(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), dateStr = _$d3_7.time.format('%Y-%m-%d')(d), h = d.getHours(), @@ -13764,23 +13774,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_153.cleanDate = function(v, dflt, calendar) { - if(_$dates_153.isJSDate(v) || typeof v === 'number') { +_$dates_154.cleanDate = function(v, dflt, calendar) { + if(_$dates_154.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_167.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_168.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 = _$dates_153.ms2DateTimeLocal(+v); + v = _$dates_154.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_153.isDateTime(v, calendar)) { - _$loggers_167.error('unrecognized date', v); + else if(!_$dates_154.isDateTime(v, calendar)) { + _$loggers_168.error('unrecognized date', v); return dflt; } return v; @@ -13810,7 +13820,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_244.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_245.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13827,10 +13837,10 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_169(x + 0.05, ONEDAY); + var timePart = _$mod_170(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_169(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_170(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { if(!_$fastIsnumeric_10(tr)) tr = 0; // should only be 'S' @@ -13850,7 +13860,7 @@ function formatTime(x, tr) { * 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_169(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_170(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13879,7 +13889,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_153.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_154.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13923,19 +13933,19 @@ _$dates_153.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_153.incrementMonth = function(ms, dMonth, calendar) { +_$dates_154.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_169(ms, ONEDAY); + var timeMs = _$mod_170(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_244.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_245.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13944,7 +13954,7 @@ _$dates_153.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_167.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_168.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13959,7 +13969,7 @@ _$dates_153.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_153.findExactDates = function(data, calendar) { +_$dates_154.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13969,7 +13979,7 @@ _$dates_153.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_244.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_245.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { @@ -14036,7 +14046,7 @@ _$dates_153.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_154 = function ensureArray(out, n) { +var _$ensureArray_155 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14079,7 +14089,7 @@ var _$ensureArray_154 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_157 = function filterUnique(array) { +var _$filterUnique_158 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14113,7 +14123,7 @@ var _$filterUnique_157 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_158 = function filterVisible(container) { +var _$filterVisible_159 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14142,7 +14152,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_159 = {}; +var _$geometry2d_160 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14153,13 +14163,13 @@ var _$geometry2d_159 = {}; 'use strict'; -/* removed: var _$mod_169 = require('./mod'); */; +/* removed: var _$mod_170 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_159.segmentsIntersect = segmentsIntersect; +_$geometry2d_160.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14182,7 +14192,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_159.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_160.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 @@ -14235,7 +14245,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_159.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_160.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14247,13 +14257,13 @@ _$geometry2d_159.getTextLocation = function getTextLocation(path, totalPathLen, // 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_169(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_169(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_170(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_170(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_169(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_170(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14262,7 +14272,7 @@ _$geometry2d_159.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_159.clearLocationCache = function() { +_$geometry2d_160.clearLocationCache = function() { workingPath = null; }; @@ -14290,7 +14300,7 @@ _$geometry2d_159.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_159.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_160.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14351,7 +14361,7 @@ _$geometry2d_159.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_159.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_160.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14406,7 +14416,7 @@ _$geometry2d_159.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_160 = function(gd) { +var _$get_graph_div_161 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14438,7 +14448,7 @@ var _$get_graph_div_160 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_161 = function identity(d) { return d; }; +var _$identity_162 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14450,7 +14460,7 @@ var _$identity_161 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_170 = require('./nested_property'); */; +/* removed: var _$nestedProperty_171 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14472,13 +14482,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_170(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_171(baseObj, path).get(); } else { arr = baseObj; } @@ -14504,7 +14514,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_170(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_171(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14514,7 +14524,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_170(newValue, valueName).set(value); + _$nestedProperty_171(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14535,7 +14545,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_170(arr[idx], valueName).get(); + return _$nestedProperty_171(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14576,7 +14586,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value } 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_170(object, valueName).set(null); + _$nestedProperty_171(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, @@ -14603,7 +14613,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_170(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_171(arr[idx], valueName).get(); } } } else { @@ -14629,7 +14639,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_244 = require('../registry'); */; +/* removed: var _$registry_245 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14640,7 +14650,7 @@ var _$keyedContainer_165 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_166 = function localize(gd, s) { +var _$localize_167 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14662,7 +14672,7 @@ var _$localize_166 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_244.localeRegistry; + locales = _$registry_245.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14673,7 +14683,7 @@ var _$localize_166 = function localize(gd, s) { return s; }; -var _$matrix_168 = {}; +var _$matrix_169 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14686,7 +14696,7 @@ var _$matrix_168 = {}; 'use strict'; -_$matrix_168.init2dArray = function(rowLength, colLength) { +_$matrix_169.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14697,7 +14707,7 @@ _$matrix_168.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_168.transposeRagged = function(z) { +_$matrix_169.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14715,7 +14725,7 @@ _$matrix_168.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_168.dot = function(x, y) { +_$matrix_169.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14725,13 +14735,13 @@ _$matrix_168.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_168.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_169.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_168.transposeRagged(y); + var yTranspose = _$matrix_169.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_168.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_169.dot(x, yTranspose[i]); } else { // vec-vec @@ -14743,12 +14753,12 @@ _$matrix_168.dot = function(x, y) { }; // translate by (x,y) -_$matrix_168.translationMatrix = function(x, y) { +_$matrix_169.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_168.rotationMatrix = function(alpha) { +_$matrix_169.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14756,28 +14766,28 @@ _$matrix_168.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_168.rotationXYMatrix = function(a, x, y) { - return _$matrix_168.dot( - _$matrix_168.dot(_$matrix_168.translationMatrix(x, y), - _$matrix_168.rotationMatrix(a)), - _$matrix_168.translationMatrix(-x, -y)); +_$matrix_169.rotationXYMatrix = function(a, x, y) { + return _$matrix_169.dot( + _$matrix_169.dot(_$matrix_169.translationMatrix(x, y), + _$matrix_169.rotationMatrix(a)), + _$matrix_169.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_168.apply2DTransform = function(transform) { +_$matrix_169.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_168.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_169.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_168.apply2DTransform2 = function(transform) { - var at = _$matrix_168.apply2DTransform(transform); +_$matrix_169.apply2DTransform2 = function(transform) { + var at = _$matrix_169.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14806,7 +14816,7 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_172 = function(text, displayLength) { +var _$notifier_173 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); @@ -14898,7 +14908,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_178 = function(baseAttr, relativeAttr) { +var _$relative_attr_179 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14927,8 +14937,8 @@ var _$relative_attr_178 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_179 = _$is_array_163.isArrayOrTypedArray; -/* removed: var _$isPlainObject_164 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_180 = _$is_array_164.isArrayOrTypedArray; +/* removed: var _$isPlainObject_165 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14937,7 +14947,7 @@ var __isArrayOrTypedArray_179 = _$is_array_163.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_179 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_180 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14953,7 +14963,7 @@ var _$relinkPrivateKeys_179 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_179(fromVal) && __isArrayOrTypedArray_179(toVal) && _$isPlainObject_164(fromVal[0])) { + else if(__isArrayOrTypedArray_180(fromVal) && __isArrayOrTypedArray_180(toVal) && _$isPlainObject_165(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14963,12 +14973,12 @@ var _$relinkPrivateKeys_179 = function relinkPrivateKeys(toContainer, fromContai // 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_164(fromVal[j]) && _$isPlainObject_164(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_165(fromVal[j]) && _$isPlainObject_165(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_164(fromVal) && _$isPlainObject_164(toVal)) { + else if(_$isPlainObject_165(fromVal) && _$isPlainObject_165(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14978,7 +14988,7 @@ var _$relinkPrivateKeys_179 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_180 = {}; +var _$search_181 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14991,7 +15001,7 @@ var _$search_180 = {}; 'use strict'; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$loggers_167 = require('./loggers'); */; +/* removed: var _$loggers_168 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -15009,7 +15019,7 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_180.findBin = function(val, bins, linelow) { +_$search_181.findBin = function(val, bins, linelow) { if(_$fastIsnumeric_10(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : @@ -15033,7 +15043,7 @@ _$search_180.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_167.log('Long binary search...'); + if(c > 90) _$loggers_168.log('Long binary search...'); return n1 - 1; } }; @@ -15043,17 +15053,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_180.sorterAsc = function(a, b) { return a - b; }; -_$search_180.sorterDes = function(a, b) { return b - a; }; +_$search_181.sorterAsc = function(a, b) { return a - b; }; +_$search_181.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_180.distinctVals = function(valsIn) { +_$search_181.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_180.sorterAsc); + vals.sort(_$search_181.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15078,7 +15088,7 @@ _$search_180.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_180.roundUp = function(val, arrayIn, reverse) { +_$search_181.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15095,7 +15105,7 @@ _$search_180.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_182 = {}; +var _$stats_183 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15108,7 +15118,7 @@ var _$stats_182 = {}; 'use strict'; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_182 = _$is_array_163.isArrayOrTypedArray; +var __isArrayOrTypedArray_183 = _$is_array_164.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15123,14 +15133,14 @@ var __isArrayOrTypedArray_182 = _$is_array_163.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_182.aggNums = function(f, v, a, len) { +_$stats_183.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; if(!_$fastIsnumeric_10(v)) v = false; - if(__isArrayOrTypedArray_182(a[0])) { + if(__isArrayOrTypedArray_183(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_182.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_183.aggNums(f, v, a[i]); a = b; } @@ -15145,26 +15155,26 @@ _$stats_182.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_182.len = function(data) { - return _$stats_182.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_183.len = function(data) { + return _$stats_183.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_182.mean = function(data, len) { - if(!len) len = _$stats_182.len(data); - return _$stats_182.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_183.mean = function(data, len) { + if(!len) len = _$stats_183.len(data); + return _$stats_183.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_182.variance = function(data, len, mean) { - if(!len) len = _$stats_182.len(data); - if(!_$fastIsnumeric_10(mean)) mean = _$stats_182.mean(data, len); +_$stats_183.variance = function(data, len, mean) { + if(!len) len = _$stats_183.len(data); + if(!_$fastIsnumeric_10(mean)) mean = _$stats_183.mean(data, len); - return _$stats_182.aggNums(function(a, b) { + return _$stats_183.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_182.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_182.variance(data, len, mean)); +_$stats_183.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_183.variance(data, len, mean)); }; /** @@ -15182,7 +15192,7 @@ _$stats_182.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_182.interp = function(arr, n) { +_$stats_183.interp = function(arr, n) { if(!_$fastIsnumeric_10(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; @@ -15191,7 +15201,7 @@ _$stats_182.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_184 = {}; +var _$throttle_185 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15218,7 +15228,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_184.throttle = function throttle(id, minInterval, callback) { +_$throttle_185.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15258,7 +15268,7 @@ _$throttle_184.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_184.done = function(id) { +_$throttle_185.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15278,13 +15288,13 @@ _$throttle_184.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_184.clear = function(id) { +_$throttle_185.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_184.clear(idi); + for(var idi in timerCache) _$throttle_185.clear(idi); } }; @@ -15311,7 +15321,7 @@ function _clearTimeout(cache) { * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_185 = function toLogRange(val, range) { +var _$toLogRange_186 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the @@ -15322,7 +15332,7 @@ var _$toLogRange_185 = function toLogRange(val, range) { return newVal; }; -var _$lib_162 = {}; +var _$lib_163 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15339,71 +15349,71 @@ var _$lib_162 = {}; /* removed: var _$numerical_145 = require('../constants/numerical'); */; var FP_SAFE = _$numerical_145.FP_SAFE; -var __BADNUM_162 = _$numerical_145.BADNUM; - -var lib = _$lib_162 = {}; - -lib.nestedProperty = _$nestedProperty_170; -lib.keyedContainer = _$keyedContainer_165; -lib.relativeAttr = _$relative_attr_178; -lib.isPlainObject = _$isPlainObject_164; -lib.mod = _$mod_169; -lib.toLogRange = _$toLogRange_185; -lib.relinkPrivateKeys = _$relinkPrivateKeys_179; -lib.ensureArray = _$ensureArray_154; - -/* removed: var _$is_array_163 = require('./is_array'); */; -lib.isTypedArray = _$is_array_163.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_163.isArrayOrTypedArray; - -/* removed: var _$coerce_152 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_152.valObjectMeta; -lib.coerce = _$coerce_152.coerce; -lib.coerce2 = _$coerce_152.coerce2; -lib.coerceFont = _$coerce_152.coerceFont; -lib.coerceHoverinfo = _$coerce_152.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_152.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_152.validate; - -/* removed: var _$dates_153 = require('./dates'); */; -lib.dateTime2ms = _$dates_153.dateTime2ms; -lib.isDateTime = _$dates_153.isDateTime; -lib.ms2DateTime = _$dates_153.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_153.ms2DateTimeLocal; -lib.cleanDate = _$dates_153.cleanDate; -lib.isJSDate = _$dates_153.isJSDate; -lib.formatDate = _$dates_153.formatDate; -lib.incrementMonth = _$dates_153.incrementMonth; -lib.dateTick0 = _$dates_153.dateTick0; -lib.dfltRange = _$dates_153.dfltRange; -lib.findExactDates = _$dates_153.findExactDates; -lib.MIN_MS = _$dates_153.MIN_MS; -lib.MAX_MS = _$dates_153.MAX_MS; - -/* removed: var _$search_180 = require('./search'); */; -lib.findBin = _$search_180.findBin; -lib.sorterAsc = _$search_180.sorterAsc; -lib.sorterDes = _$search_180.sorterDes; -lib.distinctVals = _$search_180.distinctVals; -lib.roundUp = _$search_180.roundUp; - -/* removed: var _$stats_182 = require('./stats'); */; -lib.aggNums = _$stats_182.aggNums; -lib.len = _$stats_182.len; -lib.mean = _$stats_182.mean; -lib.variance = _$stats_182.variance; -lib.stdev = _$stats_182.stdev; -lib.interp = _$stats_182.interp; - -/* removed: var _$matrix_168 = require('./matrix'); */; -lib.init2dArray = _$matrix_168.init2dArray; -lib.transposeRagged = _$matrix_168.transposeRagged; -lib.dot = _$matrix_168.dot; -lib.translationMatrix = _$matrix_168.translationMatrix; -lib.rotationMatrix = _$matrix_168.rotationMatrix; -lib.rotationXYMatrix = _$matrix_168.rotationXYMatrix; -lib.apply2DTransform = _$matrix_168.apply2DTransform; -lib.apply2DTransform2 = _$matrix_168.apply2DTransform2; +var __BADNUM_163 = _$numerical_145.BADNUM; + +var lib = _$lib_163 = {}; + +lib.nestedProperty = _$nestedProperty_171; +lib.keyedContainer = _$keyedContainer_166; +lib.relativeAttr = _$relative_attr_179; +lib.isPlainObject = _$isPlainObject_165; +lib.mod = _$mod_170; +lib.toLogRange = _$toLogRange_186; +lib.relinkPrivateKeys = _$relinkPrivateKeys_180; +lib.ensureArray = _$ensureArray_155; + +/* removed: var _$is_array_164 = require('./is_array'); */; +lib.isTypedArray = _$is_array_164.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_164.isArrayOrTypedArray; + +/* removed: var _$coerce_153 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_153.valObjectMeta; +lib.coerce = _$coerce_153.coerce; +lib.coerce2 = _$coerce_153.coerce2; +lib.coerceFont = _$coerce_153.coerceFont; +lib.coerceHoverinfo = _$coerce_153.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_153.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_153.validate; + +/* removed: var _$dates_154 = require('./dates'); */; +lib.dateTime2ms = _$dates_154.dateTime2ms; +lib.isDateTime = _$dates_154.isDateTime; +lib.ms2DateTime = _$dates_154.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_154.ms2DateTimeLocal; +lib.cleanDate = _$dates_154.cleanDate; +lib.isJSDate = _$dates_154.isJSDate; +lib.formatDate = _$dates_154.formatDate; +lib.incrementMonth = _$dates_154.incrementMonth; +lib.dateTick0 = _$dates_154.dateTick0; +lib.dfltRange = _$dates_154.dfltRange; +lib.findExactDates = _$dates_154.findExactDates; +lib.MIN_MS = _$dates_154.MIN_MS; +lib.MAX_MS = _$dates_154.MAX_MS; + +/* removed: var _$search_181 = require('./search'); */; +lib.findBin = _$search_181.findBin; +lib.sorterAsc = _$search_181.sorterAsc; +lib.sorterDes = _$search_181.sorterDes; +lib.distinctVals = _$search_181.distinctVals; +lib.roundUp = _$search_181.roundUp; + +/* removed: var _$stats_183 = require('./stats'); */; +lib.aggNums = _$stats_183.aggNums; +lib.len = _$stats_183.len; +lib.mean = _$stats_183.mean; +lib.variance = _$stats_183.variance; +lib.stdev = _$stats_183.stdev; +lib.interp = _$stats_183.interp; + +/* removed: var _$matrix_169 = require('./matrix'); */; +lib.init2dArray = _$matrix_169.init2dArray; +lib.transposeRagged = _$matrix_169.transposeRagged; +lib.dot = _$matrix_169.dot; +lib.translationMatrix = _$matrix_169.translationMatrix; +lib.rotationMatrix = _$matrix_169.rotationMatrix; +lib.rotationXYMatrix = _$matrix_169.rotationXYMatrix; +lib.apply2DTransform = _$matrix_169.apply2DTransform; +lib.apply2DTransform2 = _$matrix_169.apply2DTransform2; /* removed: var _$angles_150 = require('./angles'); */; lib.deg2rad = _$angles_150.deg2rad; @@ -15411,54 +15421,54 @@ lib.rad2deg = _$angles_150.rad2deg; lib.wrap360 = _$angles_150.wrap360; lib.wrap180 = _$angles_150.wrap180; -/* removed: var _$geometry2d_159 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_159.segmentsIntersect; -lib.segmentDistance = _$geometry2d_159.segmentDistance; -lib.getTextLocation = _$geometry2d_159.getTextLocation; -lib.clearLocationCache = _$geometry2d_159.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_159.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_159.findPointOnPath; +/* removed: var _$geometry2d_160 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_160.segmentsIntersect; +lib.segmentDistance = _$geometry2d_160.segmentDistance; +lib.getTextLocation = _$geometry2d_160.getTextLocation; +lib.clearLocationCache = _$geometry2d_160.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_160.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_160.findPointOnPath; -/* removed: var _$extend_156 = require('./extend'); */; -lib.extendFlat = _$extend_156.extendFlat; -lib.extendDeep = _$extend_156.extendDeep; -lib.extendDeepAll = _$extend_156.extendDeepAll; -lib.extendDeepNoArrays = _$extend_156.extendDeepNoArrays; +/* removed: var _$extend_157 = require('./extend'); */; +lib.extendFlat = _$extend_157.extendFlat; +lib.extendDeep = _$extend_157.extendDeep; +lib.extendDeepAll = _$extend_157.extendDeepAll; +lib.extendDeepNoArrays = _$extend_157.extendDeepNoArrays; -/* removed: var _$loggers_167 = require('./loggers'); */; -lib.log = _$loggers_167.log; -lib.warn = _$loggers_167.warn; -lib.error = _$loggers_167.error; +/* removed: var _$loggers_168 = require('./loggers'); */; +lib.log = _$loggers_168.log; +lib.warn = _$loggers_168.warn; +lib.error = _$loggers_168.error; -/* removed: var _$regex_177 = require('./regex'); */; -lib.counterRegex = _$regex_177.counter; +/* removed: var _$regex_178 = require('./regex'); */; +lib.counterRegex = _$regex_178.counter; -/* removed: var _$throttle_184 = require('./throttle'); */; -lib.throttle = _$throttle_184.throttle; -lib.throttleDone = _$throttle_184.done; -lib.clearThrottle = _$throttle_184.clear; +/* removed: var _$throttle_185 = require('./throttle'); */; +lib.throttle = _$throttle_185.throttle; +lib.throttleDone = _$throttle_185.done; +lib.clearThrottle = _$throttle_185.clear; -lib.getGraphDiv = _$get_graph_div_160; +lib.getGraphDiv = _$get_graph_div_161; -lib._ = _$localize_166; +lib._ = _$localize_167; -lib.notifier = _$notifier_172; +lib.notifier = _$notifier_173; -lib.filterUnique = _$filterUnique_157; -lib.filterVisible = _$filterVisible_158; -lib.pushUnique = _$pushUnique_175; +lib.filterUnique = _$filterUnique_158; +lib.filterVisible = _$filterVisible_159; +lib.pushUnique = _$pushUnique_176; lib.cleanNumber = _$cleanNumber_151; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_10(v)) return __BADNUM_162; + if(!_$fastIsnumeric_10(v)) return __BADNUM_163; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_162; - return _$fastIsnumeric_10(v) ? Number(v) : __BADNUM_162; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_163; + return _$fastIsnumeric_10(v) ? Number(v) : __BADNUM_163; }; -lib.noop = _$noop_171; -lib.identity = _$identity_161; +lib.noop = _$noop_172; +lib.identity = _$identity_162; /** * swap x and y of the same attribute in container cont @@ -15957,6 +15967,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16150,7 +16217,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_162 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_163 = /^\w*$/; /* * Substitute values from an object into a string @@ -16171,7 +16238,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_162.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_163.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16232,7 +16299,7 @@ lib.pseudoRandom = function() { 'use strict'; -var _$attributes_202 = { +var _$attributes_203 = { xaxis: { valType: 'subplotid', @@ -16258,21 +16325,21 @@ var _$attributes_202 = { */ 'use strict'; -var __counterRegex_209 = _$regex_177.counter; +var __counterRegex_210 = _$regex_178.counter; -var _$constants_209 = { +var _$constants_210 = { idRegex: { - x: __counterRegex_209('x'), - y: __counterRegex_209('y') + x: __counterRegex_210('x'), + y: __counterRegex_210('y') }, - attrRegex: __counterRegex_209('[xy]axis'), + attrRegex: __counterRegex_210('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_209('xaxis'), - yAxisMatch: __counterRegex_209('yaxis'), + xAxisMatch: __counterRegex_210('xaxis'), + yAxisMatch: __counterRegex_210('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -16319,6 +16386,7 @@ var _$constants_209 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -16328,7 +16396,7 @@ var _$constants_209 = { } }; -var _$axis_ids_207 = {}; +var _$axis_ids_208 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16339,30 +16407,30 @@ var _$axis_ids_207 = {}; 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; +/* removed: var _$registry_245 = require('../../registry'); */; -/* removed: var _$constants_209 = require('./constants'); */; +/* removed: var _$constants_210 = require('./constants'); */; // 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. -_$axis_ids_207.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_209.AX_ID_PATTERN)) return; +_$axis_ids_208.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_210.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_207.name2id = function name2id(name) { - if(!name.match(_$constants_209.AX_NAME_PATTERN)) return; +_$axis_ids_208.name2id = function name2id(name) { + if(!name.match(_$constants_210.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_207.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_209.AX_ID_PATTERN)) return; +_$axis_ids_208.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_210.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -16371,11 +16439,11 @@ _$axis_ids_207.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_207.list = function(gd, axLetter, only2d) { +_$axis_ids_208.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_207.listIds(gd, axLetter); + var idList = _$axis_ids_208.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -16400,7 +16468,7 @@ _$axis_ids_207.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_207.listIds = function(gd, axLetter) { +_$axis_ids_208.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -16411,42 +16479,110 @@ _$axis_ids_207.listIds = function(gd, axLetter) { // 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 -_$axis_ids_207.getFromId = function(gd, id, type) { +_$axis_ids_208.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[_$axis_ids_207.id2name(id)]; + return fullLayout[_$axis_ids_208.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_207.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_208.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_244.traceIs(fullTrace, 'gl3d')) { + if(_$registry_245.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_207.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_208.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_207.idSort = function(id1, id2) { +_$axis_ids_208.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); }; -var _$attributes_67 = {}; +var _$client_14 = true; +var _$hasHover_12 = {}; +(function (global){ +'use strict' + +/* removed: var _$client_14 = require('is-browser') */; +var hasHover + +if (typeof global.matchMedia === 'function') { + hasHover = !global.matchMedia('(hover: none)').matches +} +else { + hasHover = _$client_14 +} + +_$hasHover_12 = hasHover + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + +/* removed: var _$client_14 = require('is-browser') */; + +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 +} + +var _$hasPassiveEvents_13 = _$client_14 && detect() + +var rootPosition = { left: 0, top: 0 } + +var _$mouseEventOffset_15 = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16458,17 +16594,25 @@ var _$attributes_67 = {}; 'use strict'; -_$attributes_67.dash = { - valType: 'string', - // string type usually doesn't take values... this one should really be - // a special type or at least a special coercion function, from the GUI - // you only get these values but elsewhere the user can supply a list of - // dash lengths in px, and it will be honored - values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], - dflt: 'solid', - - editType: 'style', - + +// 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 +var _$align_63 = function align(v, dv, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0), + vmax = vmin + dv / (v1 - v0), + 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; }; /** @@ -16479,512 +16623,35 @@ _$attributes_67.dash = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$font_attributes_231 = require('../font_attributes'); */; -/* removed: var _$attributes_42 = require('../../components/color/attributes'); */; -var dash = _$attributes_67.dash; -var __extendFlat_216 = _$extend_156.extendFlat; +/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$constants_209 = require('./constants'); */; +// 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'] +]; -var _$layout_attributes_216 = { - visible: { - valType: 'boolean', - - editType: 'plot', - - }, - color: { - valType: 'color', - dflt: _$attributes_42.defaultLine, - - editType: 'ticks', - - }, - title: { - valType: 'string', - - editType: 'ticks+margins', - - }, - titlefont: _$font_attributes_231({ - editType: 'ticks+margins', - - }), - type: { - valType: 'enumerated', - // '-' means we haven't yet run autotype or couldn't find any data - // it gets turned into linear in gd._fullLayout but not copied back - // to gd.data like the others are. - values: ['-', 'linear', 'log', 'date', 'category'], - dflt: '-', - - editType: 'calc', - - }, - autorange: { - valType: 'enumerated', - values: [true, false, 'reversed'], - dflt: true, - - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, - - }, - rangemode: { - valType: 'enumerated', - values: ['normal', 'tozero', 'nonnegative'], - dflt: 'normal', - - editType: 'plot', - - }, - range: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} - ], - editType: 'plot+margins', - impliedEdits: {'autorange': false}, - - }, - fixedrange: { - valType: 'boolean', - dflt: false, - - editType: 'calc', - - }, - // scaleanchor: not used directly, just put here for reference - // values are any opposite-letter axis id - scaleanchor: { - valType: 'enumerated', - values: [ - _$constants_209.idRegex.x.toString(), - _$constants_209.idRegex.y.toString() - ], - - editType: 'plot', - - }, - scaleratio: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'plot', - - }, - constrain: { - valType: 'enumerated', - values: ['range', 'domain'], - dflt: 'range', - - editType: 'plot', - - }, - // constraintoward: not used directly, just put here for reference - constraintoward: { - valType: 'enumerated', - values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], - - editType: 'plot', - - }, - // ticks - tickmode: { - valType: 'enumerated', - values: ['auto', 'linear', 'array'], - - editType: 'ticks+margins', - impliedEdits: {tick0: undefined, dtick: undefined}, - - }, - nticks: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'ticks+margins', - - }, - tick0: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - dtick: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - tickvals: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticktext: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticks: { - valType: 'enumerated', - values: ['outside', 'inside', ''], - - editType: 'ticks+margins', - - }, - mirror: { - valType: 'enumerated', - values: [true, 'ticks', false, 'all', 'allticks'], - dflt: false, - - editType: 'ticks+layoutstyle', - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: 5, - - editType: 'ticks', - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - tickcolor: { - valType: 'color', - dflt: _$attributes_42.defaultLine, - - editType: 'ticks', - - }, - showticklabels: { - valType: 'boolean', - dflt: true, - - editType: 'ticks+margins', - - }, - automargin: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - showspikes: { - valType: 'boolean', - dflt: false, - - editType: 'modebar', - - }, - spikecolor: { - valType: 'color', - dflt: null, - - editType: 'none', - - }, - spikethickness: { - valType: 'number', - dflt: 3, - - editType: 'none', - - }, - spikedash: __extendFlat_216({}, dash, {dflt: 'dash', editType: 'none'}), - spikemode: { - valType: 'flaglist', - flags: ['toaxis', 'across', 'marker'], - - dflt: 'toaxis', - editType: 'none', - - }, - spikesnap: { - valType: 'enumerated', - values: ['data', 'cursor'], - dflt: 'data', - - editType: 'none', - - }, - tickfont: _$font_attributes_231({ - editType: 'ticks+margins', - - }), - tickangle: { - valType: 'angle', - dflt: 'auto', - - editType: 'ticks+margins', - - }, - tickprefix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showtickprefix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - ticksuffix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showticksuffix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - showexponent: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - exponentformat: { - valType: 'enumerated', - values: ['none', 'e', 'E', 'power', 'SI', 'B'], - dflt: 'B', - - editType: 'ticks+margins', - - }, - separatethousands: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - tickformat: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - tickformatstops: { - _isLinkedToArray: 'tickformatstop', +var _$getCursor_64 = 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_163.constrain(Math.floor(x * 3), 0, 2); - dtickrange: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'ticks+margins'}, - {valType: 'any', editType: 'ticks+margins'} - ], - editType: 'ticks+margins', - - }, - value: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - editType: 'ticks+margins' - }, - hoverformat: { - valType: 'string', - dflt: '', - - editType: 'none', - - }, - // lines and grids - showline: { - valType: 'boolean', - dflt: false, - - editType: 'layoutstyle', - - }, - linecolor: { - valType: 'color', - dflt: _$attributes_42.defaultLine, - - editType: 'layoutstyle', - - }, - linewidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks+layoutstyle', - - }, - showgrid: { - valType: 'boolean', - - editType: 'ticks', - - }, - gridcolor: { - valType: 'color', - dflt: _$attributes_42.lightLine, - - editType: 'ticks', - - }, - gridwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - zeroline: { - valType: 'boolean', - - editType: 'ticks', - - }, - zerolinecolor: { - valType: 'color', - dflt: _$attributes_42.defaultLine, - - editType: 'ticks', - - }, - zerolinewidth: { - valType: 'number', - dflt: 1, - - editType: 'ticks', - - }, - // positioning attributes - // anchor: not used directly, just put here for reference - // values are any opposite-letter axis id - anchor: { - valType: 'enumerated', - values: [ - 'free', - _$constants_209.idRegex.x.toString(), - _$constants_209.idRegex.y.toString() - ], - - editType: 'plot+margins', - - }, - // side: not used directly, as values depend on direction - // values are top, bottom for x axes, and left, right for y - side: { - valType: 'enumerated', - values: ['top', 'bottom', 'left', 'right'], - - editType: 'plot+margins', - - }, - // overlaying: not used directly, just put here for reference - // values are false and any other same-letter axis id that's not - // itself overlaying anything - overlaying: { - valType: 'enumerated', - values: [ - 'free', - _$constants_209.idRegex.x.toString(), - _$constants_209.idRegex.y.toString() - ], - - editType: 'plot', - - }, - layer: { - valType: 'enumerated', - values: ['above traces', 'below traces'], - dflt: 'above traces', - - editType: 'plot', - - }, - domain: { - valType: 'info_array', - - items: [ - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} - ], - dflt: [0, 1], - editType: 'plot+margins', - - }, - position: { - valType: 'number', - min: 0, - max: 1, - dflt: 0, - - editType: 'plot+margins', - - }, - categoryorder: { - valType: 'enumerated', - values: [ - 'trace', 'category ascending', 'category descending', 'array' - /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later - ], - dflt: 'trace', - - editType: 'calc', - - }, - categoryarray: { - valType: 'data_array', - - editType: 'calc', - - }, - editType: 'calc', + if(yanchor === 'bottom') y = 0; + else if(yanchor === 'middle') y = 1; + else if(yanchor === 'top') y = 2; + else y = _$lib_163.constrain(Math.floor(y * 3), 0, 2); - _deprecated: { - autotick: { - valType: 'boolean', - - editType: 'ticks+margins', - - } - } + return cursorset[y][x]; }; -var _$color_43 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16993,342 +16660,331 @@ var _$color_43 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; - -var color = _$color_43 = {}; - -/* removed: var _$attributes_42 = require('./attributes'); */; -color.defaults = _$attributes_42.defaults; -var defaultLine = color.defaultLine = _$attributes_42.defaultLine; -color.lightLine = _$attributes_42.lightLine; -var background = color.background = _$attributes_42.background; +var _$constants_80 = { + // hover labels for multiple horizontal bars get tilted by this angle + YANGLE: 60, -/* - * tinyRGB: turn a tinycolor into an rgb string, but - * unlike the built-in tinycolor.toRgbString this never includes alpha - */ -color.tinyRGB = function(tc) { - var c = tc.toRgb(); - return 'rgb(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ')'; -}; + // size and display constants for hover text -color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_25(cstr)); }; + // pixel size of hover arrows + HOVERARROWSIZE: 6, + // pixels padding around text + HOVERTEXTPAD: 3, + // hover font + HOVERFONTSIZE: 13, + HOVERFONT: 'Arial, sans-serif', -color.opacity = function(cstr) { return cstr ? _$tinycolor_25(cstr).getAlpha() : 0; }; + // minimum time (msec) between hover calls + HOVERMINTIME: 50, -color.addOpacity = function(cstr, op) { - var c = _$tinycolor_25(cstr).toRgb(); - return 'rgba(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; + // ID suffix (with fullLayout._uid) for hover events in the throttle cache + HOVERID: '-hover' }; -// combine two colors into one apparent color -// if back has transparency or is missing, -// color.background is assumed behind it -color.combine = function(front, back) { - var fc = _$tinycolor_25(front).toRgb(); - if(fc.a === 1) return _$tinycolor_25(front).toRgbString(); +// 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 bc = _$tinycolor_25(back || background).toRgb(), - bcflat = bc.a === 1 ? bc : { - r: 255 * (1 - bc.a) + bc.r * bc.a, - g: 255 * (1 - bc.a) + bc.g * bc.a, - b: 255 * (1 - bc.a) + bc.b * bc.a - }, - fcflat = { - r: bcflat.r * (1 - fc.a) + fc.r * fc.a, - g: bcflat.g * (1 - fc.a) + fc.g * fc.a, - b: bcflat.b * (1 - fc.a) + fc.b * fc.a - }; - return _$tinycolor_25(fcflat).toRgbString(); -}; +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +var _$EventEmitter_9 = EventEmitter; -/* - * Create a color that contrasts with cstr. - * - * If cstr is a dark color, we lighten it; if it's light, we darken. - * - * If lightAmount / darkAmount are used, we adjust by these percentages, - * otherwise we go all the way to white or black. - */ -color.contrast = function(cstr, lightAmount, darkAmount) { - var tc = _$tinycolor_25(cstr); +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - if(tc.getAlpha() !== 1) tc = _$tinycolor_25(color.combine(cstr, background)); +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - var newColor = tc.isDark() ? - (lightAmount ? tc.lighten(lightAmount) : background) : - (darkAmount ? tc.darken(darkAmount) : defaultLine); +// 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. +EventEmitter.defaultMaxListeners = 10; - return newColor.toString(); +// 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(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; }; -color.stroke = function(s, c) { - var tc = _$tinycolor_25(c); - s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); -}; +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; -color.fill = function(s, c) { - var tc = _$tinycolor_25(c); - s.style({ - 'fill': color.tinyRGB(tc), - 'fill-opacity': tc.getAlpha() - }); -}; + if (!this._events) + this._events = {}; -// search container for colors with the deprecated rgb(fractions) format -// and convert them to rgb(0-255 values) -color.clean = function(container) { - if(!container || typeof container !== 'object') return; + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - var keys = Object.keys(container), - i, - j, - key, - val; + handler = this._events[type]; - for(i = 0; i < keys.length; i++) { - key = keys[i]; - val = container[key]; + if (isUndefined(handler)) + return false; - // only sanitize keys that end in "color" or "colorscale" - if(key.substr(key.length - 5) === 'color') { - if(Array.isArray(val)) { - for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); - } - else container[key] = cleanOne(val); - } - else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { - // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] - for(j = 0; j < val.length; j++) { - if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); - } - } - // recurse into arrays of objects, and plain objects - else if(Array.isArray(val)) { - var el0 = val[0]; - if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { - for(j = 0; j < val.length; j++) color.clean(val[j]); - } - } - else if(val && typeof val === 'object') color.clean(val); + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; }; -function cleanOne(val) { - if(_$fastIsnumeric_10(val) || typeof val !== 'string') return val; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - var valTrim = val.trim(); - if(valTrim.substr(0, 3) !== 'rgb') return val; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); - if(!match) return val; + if (!this._events) + this._events = {}; - var parts = match[1].trim().split(/\s*[\s,]\s*/), - rgba = valTrim.charAt(3) === 'a' && parts.length === 4; - if(!rgba && parts.length !== 3) return val; + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - for(var i = 0; i < parts.length; i++) { - if(!parts[i].length) return val; - parts[i] = Number(parts[i]); + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - // all parts must be non-negative numbers - if(!(parts[i] >= 0)) return val; - // alpha>1 gets clipped to 1 - if(i === 3) { - if(parts[i] > 1) parts[i] = 1; - } - // r, g, b must be < 1 (ie 1 itself is not allowed) - else if(parts[i] >= 1) return val; + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; } - var rgbStr = Math.round(parts[0] * 255) + ', ' + - Math.round(parts[1] * 255) + ', ' + - Math.round(parts[2] * 255); - - if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; - return 'rgb(' + rgbStr + ')'; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + return this; +}; -var _$handleCategoryOrderDefaults_208 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - var arrayIn = containerIn.categoryarray, - orderDefault; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + var fired = false; - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; + function g() { + this.removeListener(type, g); - var order = coerce('categoryorder', orderDefault); + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + g.listener = listener; + this.on(type, g); - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } + return this; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; -'use strict'; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -var colorMix = _$tinycolor_25.mix; -var lightFraction = _$attributes_42.lightFraction; -/* removed: var _$lib_162 = require('../../lib'); */; + if (!this._events || !this._events[type]) + return this; -/** - * @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 - */ -var _$handleLineGridDefaults_218 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; + list = this._events[type]; + length = list.length; + position = -1; - var dfltColor = opts.dfltColor; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - function coerce2(attr, dflt) { - return _$lib_162.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - var lineColor = coerce2('linecolor', dfltColor); - var lineWidth = coerce2('linewidth'); - var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); + if (position < 0) + return this; - if(!showLine) { - delete containerOut.linecolor; - delete containerOut.linewidth; + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } - 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 (this._events.removeListener) + this.emit('removeListener', type, listener); + } - if(!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } + return this; +}; - if(!opts.noZeroLine) { - var zeroLineColor = coerce2('zerolinecolor', dfltColor); - var zeroLineWidth = coerce2('zerolinewidth'); - var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } -}; + if (!this._events) + return this; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_7 = require('d3'); */; - -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { - - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. - - var categoryArray = []; - - var traceLines = data.map(function(d) {return d[axisLetter];}); - - var i, j, tracePoints, category, insertionIndex; - - var bisector = _$d3_7.bisector(sortFunction).left; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - for(i = 0; i < traceLines.length; i++) { + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - tracePoints = traceLines[i]; + listeners = this._events[type]; - for(j = 0; j < tracePoints.length; j++) { + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - category = tracePoints[j]; + return this; +}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - insertionIndex = bisector(categoryArray, category); +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } - } +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; - return categoryArray; +function isFunction(arg) { + return typeof arg === 'function'; } +function isNumber(arg) { + return typeof arg === 'number'; +} -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ - -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_219 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_7.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_7.descending, data); - case 'trace': return []; - default: return []; - } -}; +function isUndefined(arg) { + return arg === void 0; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -17341,593 +16997,507 @@ var _$orderedCategories_219 = function orderedCategories(axisLetter, categoryord 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; - -/* removed: var _$lib_162 = require('../../lib'); */; -var cleanNumber = _$lib_162.cleanNumber; -var ms2DateTime = _$lib_162.ms2DateTime; -var dateTime2ms = _$lib_162.dateTime2ms; -var ensureNumber = _$lib_162.ensureNumber; +/* global jQuery:false */ -/* removed: var _$numerical_145 = require('../../constants/numerical'); */; -var __FP_SAFE_223 = _$numerical_145.FP_SAFE; -var __BADNUM_223 = _$numerical_145.BADNUM; +var __EventEmitter_156 = _$EventEmitter_9.EventEmitter; -/* removed: var _$constants_209 = require('./constants'); */; -/* removed: var _$axis_ids_207 = require('./axis_ids'); */; +var Events = { -function fromLog(v) { - return Math.pow(10, v); -} + init: function(plotObj) { -/** - * 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 autorange bounds ._min and ._max - * and the autotick constraints ._minDtick, ._forceTick0 - */ -var _$setConvert_223 = function setConvert(ax, fullLayout) { - fullLayout = fullLayout || {}; + /* + * If we have already instantiated an emitter for this plot + * return early. + */ + if(plotObj._ev instanceof __EventEmitter_156) return plotObj; - var axLetter = (ax._id || 'x').charAt(0); + var ev = new __EventEmitter_156(); + var internalEv = new __EventEmitter_156(); - // clipMult: how many axis lengths past the edge do we render? - // for panning, 1-2 would suffice, but for zooming more is nice. - // also, clipping can affect the direction of lines off the edge... - var clipMult = 10; + /* + * Assign to plot._ev while we still live in a land + * where plot is a DOM element with stuff attached to it. + * In the future we can make plot the event emitter itself. + */ + plotObj._ev = ev; - function toLog(v, clip) { - if(v > 0) return Math.log(v) / Math.LN10; + /* + * Create a second event handler that will manage events *internally*. + * This allows parts of plotly to respond to thing like relayout without + * having to use the user-facing event handler. They cannot peacefully + * coexist on the same handler because a user invoking + * plotObj.removeAllListeners() would detach internal events, breaking + * plotly. + */ + plotObj._internalEv = internalEv; - else if(v <= 0 && clip && ax.range && ax.range.length === 2) { - // clip NaN (ie past negative infinity) to clipMult axis - // length past the negative edge - var r0 = ax.range[0], - r1 = ax.range[1]; - return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); - } + /* + * Assign bound methods from the ev to the plot object. These methods + * will reference the 'this' of plot._ev even though they are methods + * of plot. This will keep the event machinery away from the plot object + * which currently is often a DOM element but presents an API that will + * continue to function when plot becomes an emitter. Not all EventEmitter + * methods have been bound to `plot` as some do not currently add value to + * the Plotly event API. + */ + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - else return __BADNUM_223; - } + /* + * Create funtions for managing internal events. These are *only* triggered + * by the mirroring of external events via the emit function. + */ + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); - /* - * 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_223) { - if(_$fastIsnumeric_10(v)) ms = dateTime2ms(new Date(+v)); - else return __BADNUM_223; - } - return ms; - } + /* + * We must wrap emit to continue to support JQuery events. The idea + * is to check to see if the user is using JQuery events, if they are + * we emit JQuery events to trigger user handlers as well as the EventEmitter + * events. + */ + plotObj.emit = function(event, data) { + if(typeof jQuery !== 'undefined') { + jQuery(plotObj).trigger(event, data); + } - // wrapped ms2DateTime to insert default ax.calendar - function ms2dt(v, r, calendar) { - return ms2DateTime(v, r, calendar || ax.calendar); - } + ev.emit(event, data); + internalEv.emit(event, data); + }; - function getCategoryName(v) { - return ax._categories[Math.round(v)]; - } + return plotObj; + }, /* - * 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. + * This function behaves like jQueries triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. * - * 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 + * Note: triggerHandler has been recommended for deprecation in v2.0.0, + * so the additional behavior of triggerHandler triggering internal events + * is deliberate excluded in order to avoid reinforcing more usage. */ - function setCategoryIndex(v) { - if(v !== null && v !== undefined) { - if(ax._categoriesMap === undefined) { - ax._categoriesMap = {}; - } + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + /* + * If Jquery exists run all its handlers for this event and + * collect the return value of the LAST handler function + */ + if(typeof jQuery !== 'undefined') { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } - if(ax._categoriesMap[v] !== undefined) { - return ax._categoriesMap[v]; - } else { - ax._categories.push(v); + /* + * Now run all the node style event handlers + */ + var ev = plotObj._ev; + if(!ev) return jQueryHandlerValue; - var curLength = ax._categories.length - 1; - ax._categoriesMap[v] = curLength; + var handlers = ev._events[event]; + if(!handlers) return jQueryHandlerValue; - return curLength; - } - } - return __BADNUM_223; - } + /* + * handlers can be function or an array of functions + */ + if(typeof handlers === 'function') handlers = [handlers]; + var lastHandler = handlers.pop(); - function getCategoryIndex(v) { - // d2l/d2c variant that that won't add categories but will also - // allow numbers to be mapped to the linearized axis positions - if(ax._categoriesMap) { - var index = ax._categoriesMap[v]; - if(index !== undefined) return index; + /* + * Call all the handlers except the last one. + */ + for(var i = 0; i < handlers.length; i++) { + handlers[i](data); } - if(_$fastIsnumeric_10(v)) return +v; - } - - function l2p(v) { - if(!_$fastIsnumeric_10(v)) return __BADNUM_223; - - // include 2 fractional digits on pixel, for PDF zooming etc - return _$d3_7.round(ax._b + ax._m * v, 2); - } + /* + * Now call the final handler and collect its value + */ + nodeEventHandlerValue = lastHandler(data); - function p2l(px) { return (px - ax._b) / ax._m; } + /* + * Return either the jquery handler value if it exists or the + * nodeEventHandler value. Jquery event value superceeds nodejs + * events for backwards compatability reasons. + */ + return jQueryHandlerValue !== undefined ? jQueryHandlerValue : + nodeEventHandlerValue; + }, - // 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; + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; - ax.l2p = l2p; - ax.p2l = p2l; + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; - 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; + return plotObj; + } - /* - * 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; +var _$Events_156 = Events; - 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)); }; +var _$unhover_66 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ax.d2c = ax.r2l = cleanNumber; - ax.c2d = ax.l2r = ensureNumber; - ax.c2r = toLog; - ax.l2d = fromLog; +'use strict'; - 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; +/* removed: var _$Events_156 = require('../../lib/events'); */; +/* removed: var _$throttle_185 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_161 = require('../../lib/get_graph_div'); */; - ax.cleanPos = ensureNumber; - } - else if(ax.type === 'date') { - // r and d are date strings, l and c are ms +/* removed: var _$constants_80 = require('../fx/constants'); */; - /* - * 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_162.identity; +var unhover = _$unhover_66 = {}; - 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); }; +unhover.wrapped = function(gd, evt, subplot) { + gd = _$get_graph_div_161(gd); - ax.cleanPos = function(v) { return _$lib_162.cleanDate(v, __BADNUM_223, ax.calendar); }; + // Important, clear any queued hovers + if(gd._fullLayout) { + _$throttle_185.clear(gd._fullLayout._uid + _$constants_80.HOVERID); } - 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; + unhover.raw(gd, evt, subplot); +}; - ax.d2r = ax.d2l_noadd = getCategoryIndex; - ax.r2c = function(v) { - var index = getCategoryIndex(v); - return index !== undefined ? index : ax.fraction2r(0.5); - }; +// remove hover effects on mouse out, and emit unhover event +unhover.raw = function unhoverRaw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; - ax.l2r = ax.c2r = ensureNumber; - ax.r2l = getCategoryIndex; + if(!evt) evt = {}; + if(evt.target && + _$Events_156.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - 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; + fullLayout._hoverlayer.selectAll('g').remove(); + fullLayout._hoverlayer.selectAll('line').remove(); + fullLayout._hoverlayer.selectAll('circle').remove(); + gd._hoverdata = undefined; - ax.cleanPos = function(v) { - if(typeof v === 'string' && v !== '') return v; - return ensureNumber(v); - }; + if(evt.target && oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } +}; - // find the range value at the specified (linear) fraction of the axis - ax.fraction2r = function(v) { - var rl0 = ax.r2l(ax.range[0]), - 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]), - rl1 = ax.r2l(ax.range[1]); - return (ax.r2l(v) - rl0) / (rl1 - rl0); - }; +var _$dragelement_65 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* - * 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_162.nestedProperty(ax, rangeAttr).get(); - var i, dflt; +'use strict'; - if(ax.type === 'date') dflt = _$lib_162.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_209.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_209.DFLTRANGEX; +/* removed: var _$mouseEventOffset_15 = require('mouse-event-offset'); */; +/* removed: var _$hasHover_12 = require('has-hover'); */; +/* removed: var _$hasPassiveEvents_13 = require('has-passive-events'); */; - // make sure we don't later mutate the defaults - dflt = dflt.slice(); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; - if(!range || range.length !== 2) { - _$lib_162.nestedProperty(ax, rangeAttr).set(dflt); - return; - } +/* removed: var _$constants_210 = require('../../plots/cartesian/constants'); */; +/* removed: var _$interactions_144 = require('../../constants/interactions'); */; - if(ax.type === 'date') { - // check if milliseconds or js date objects are provided for range - // and convert to date strings - range[0] = _$lib_162.cleanDate(range[0], __BADNUM_223, ax.calendar); - range[1] = _$lib_162.cleanDate(range[1], __BADNUM_223, ax.calendar); - } +var dragElement = _$dragelement_65 = {}; - for(i = 0; i < 2; i++) { - if(ax.type === 'date') { - if(!_$lib_162.isDateTime(range[i], ax.calendar)) { - ax[rangeAttr] = dflt; - break; - } +dragElement.align = _$align_63; +dragElement.getCursor = _$getCursor_64; - if(ax.r2l(range[0]) === ax.r2l(range[1])) { - // split by +/- 1 second - var linCenter = _$lib_162.constrain(ax.r2l(range[0]), - _$lib_162.MIN_MS + 1000, _$lib_162.MAX_MS - 1000); - range[0] = ax.l2r(linCenter - 1000); - range[1] = ax.l2r(linCenter + 1000); - break; - } - } - else { - if(!_$fastIsnumeric_10(range[i])) { - if(_$fastIsnumeric_10(range[1 - i])) { - range[i] = range[1 - i] * (i ? 10 : 0.1); - } - else { - ax[rangeAttr] = dflt; - break; - } - } +/* removed: var _$unhover_66 = require('./unhover'); */; +dragElement.unhover = _$unhover_66.wrapped; +dragElement.unhoverRaw = _$unhover_66.raw; - if(range[i] < -__FP_SAFE_223) range[i] = -__FP_SAFE_223; - else if(range[i] > __FP_SAFE_223) range[i] = __FP_SAFE_223; - 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; - - // TODO cleaner way to handle this case - if(!ax._categories) ax._categories = []; - // Add a map to optimize the performance of category collection - if(!ax._categoriesMap) ax._categoriesMap = {}; +/** + * 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 DBLCLICKDELAY = _$interactions_144.DBLCLICKDELAY; + var element = options.element; - // make sure we have a domain (pull it in from the axis - // this one is overlaying if necessary) - if(ax.overlaying) { - var ax2 = _$axis_ids_207.getFromId({ _fullLayout: fullLayout }, ax.overlaying); - ax.domain = ax2.domain; - } + var startX, + startY, + newMouseDownTime, + cursor, + dragCover, + initialEvent, + initialTarget, + rightClick; - // 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', - calendar = ax.calendar; - ax.cleanRange(rangeAttr); + if(!gd._mouseDownTime) gd._mouseDownTime = 0; - var rl0 = ax.r2l(ax[rangeAttr][0], calendar), - rl1 = ax.r2l(ax[rangeAttr][1], calendar); + element.style.pointerEvents = 'all'; - 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; - } + element.onmousedown = onStart; - if(!isFinite(ax._m) || !isFinite(ax._b)) { - fullLayout._replotting = false; - throw new Error('Something went wrong with axis scaling'); + if(!_$hasPassiveEvents_13) { + element.ontouchstart = onStart; + } + else { + if(element._ontouchstart) { + element.removeEventListener('touchstart', element._ontouchstart); } - }; + element._ontouchstart = onStart; + element.addEventListener('touchstart', onStart, {passive: false}); + } - // 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; + function _clampFn(dx, dy, minDrag) { + if(Math.abs(dx) < minDrag) dx = 0; + if(Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } - var axType = ax.type; - var cal = axType === 'date' && trace[axLetter + 'calendar']; + var clampFn = options.clampFn || _clampFn; - if(axLetter in trace) { - arrayIn = trace[axLetter]; - len = trace._length || arrayIn.length; + function onStart(e) { + e.preventDefault(); - if(_$lib_162.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { - if(len === arrayIn.length) { - return arrayIn; - } else if(arrayIn.subarray) { - return arrayIn.subarray(0, len); - } - } + // 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; - arrayOut = new Array(len); - for(i = 0; i < len; i++) { - arrayOut[i] = ax.d2c(arrayIn[i], 0, cal); - } + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { + // in a click train + numClicks += 1; } 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; - } + // new click train + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; } - return arrayOut; - }; + if(options.prepFn) options.prepFn(e, startX, startY); - ax.isValidRange = function(range) { - return ( - Array.isArray(range) && - range.length === 2 && - _$fastIsnumeric_10(ax.r2l(range[0])) && - _$fastIsnumeric_10(ax.r2l(range[1])) - ); - }; + if(_$hasHover_12 && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } + else if(!_$hasHover_12) { + // 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; + } - ax.isPtWithinRange = function(d, calendar) { - var coord = ax.c2l(d[axLetter], null, calendar); + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onDone); + document.addEventListener('touchmove', onMove); + document.addEventListener('touchend', onDone); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); - }; + return; + } - ax.clearCalc = function() { - // for autoranging: arrays of objects: - // { - // val: axis value, - // pad: pixel padding, - // extrapad: boolean, should this val get 5% additional padding - // } - ax._min = []; - ax._max = []; + function onMove(e) { + e.preventDefault(); - // initialize the category list, if there is one, so we start over - // to be filled in later by ax.d2c - ax._categories = (ax._initialCategories || []).slice(); + var offset = pointerOffset(e); + var minDrag = options.minDrag || _$constants_210.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; - // Build the lookup map for initialized categories - ax._categoriesMap = {}; - for(var j = 0; j < ax._categories.length; j++) { - ax._categoriesMap[ax._categories[j]] = j; + if(dx || dy) { + gd._dragged = true; + dragElement.unhover(gd); } - }; - // 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_7.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_7.format; + if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); - // and for bar charts and box plots: reset forced minimum tick spacing - delete ax._minDtick; - delete ax._forceTick0; -}; + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function onDone(e) { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onDone); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onDone); + e.preventDefault(); -'use strict'; + if(_$hasHover_12) { + _$lib_163.removeElement(dragCover); + } + else if(cursor) { + dragCover.documentElement.style.cursor = cursor; + cursor = null; + } -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$layout_attributes_216 = require('./layout_attributes'); */; + if(!gd._dragging) { + gd._dragged = false; + return; + } + gd._dragging = false; -var _$handleTickLabelDefaults_224 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { - var showAttrDflt = getShowAttrDflt(containerIn); + // don't count as a dblClick unless the mouseUp is also within + // the dblclick delay + if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - var tickPrefix = coerce('tickprefix'); - if(tickPrefix) coerce('showtickprefix', showAttrDflt); + if(gd._dragged) { + if(options.doneFn) options.doneFn(e); + } + else { + if(options.clickFn) options.clickFn(numClicks, initialEvent); - var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); - if(tickSuffix) coerce('showticksuffix', showAttrDflt); + // 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; - var showTickLabels = coerce('showticklabels'); - if(showTickLabels) { - var font = options.font || {}; - // as with titlefont.color, inherit axis.color only if one was - // explicitly provided - var dfltFontColor = (containerOut.color === containerIn.color) ? - containerOut.color : font.color; - _$lib_162.coerceFont(coerce, 'tickfont', { - family: font.family, - size: font.size, - color: dfltFontColor - }); - coerce('tickangle'); + 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); + } - if(axType !== 'category') { - var tickFormat = coerce('tickformat'); - tickformatstopsDefaults(containerIn, containerOut); - if(!tickFormat && axType !== 'date') { - coerce('showexponent', showAttrDflt); - coerce('exponentformat'); - coerce('separatethousands'); + initialTarget.dispatchEvent(e2); } } - } -}; -/* - * 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'], - showAttrs = showAttrsAll.filter(function(a) { - return containerIn[a] !== undefined; - }), - sameVal = function(a) { - return containerIn[a] === containerIn[showAttrs[0]]; - }; + finishDrag(gd); - if(showAttrs.every(sameVal) || showAttrs.length === 1) { - return containerIn[showAttrs[0]]; + gd._dragged = false; + + return; } -} +}; -function tickformatstopsDefaults(tickformatIn, tickformatOut) { - var valuesIn = tickformatIn.tickformatstops; - var valuesOut = tickformatOut.tickformatstops = []; +function coverSlip() { + var cover = document.createElement('div'); - if(!Array.isArray(valuesIn)) return; + 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'; - var valueIn, valueOut; + document.body.appendChild(cover); - function coerce(attr, dflt) { - return _$lib_162.coerce(valueIn, valueOut, _$layout_attributes_216.tickformatstops, attr, dflt); - } + return cover; +} - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; +dragElement.coverSlip = coverSlip; - coerce('dtickrange'); - coerce('value'); +function finishDrag(gd) { + gd._dragging = false; + if(gd._replotPending) _$registry_245.call('plot', gd); +} - valuesOut.push(valueOut); - } +function pointerOffset(e) { + return _$mouseEventOffset_15( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); } /** @@ -17938,30 +17508,54 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_245 = require('../../registry'); */; -/* removed: var _$layout_attributes_216 = require('./layout_attributes'); */; +var _$calc_78 = function calc(gd) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; + function makeCoerceHoverInfo(trace) { + return function(val) { + return _$lib_163.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + }; + } -/** - * options: inherits outerTicks from axes.handleAxisDefaults - */ -var _$handleTickDefaults_225 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_162.coerce2(containerIn, containerOut, _$layout_attributes_216, 'ticklen'), - tickWidth = _$lib_162.coerce2(containerIn, containerOut, _$layout_attributes_216, 'tickwidth'), - tickColor = _$lib_162.coerce2(containerIn, containerOut, _$layout_attributes_216, 'tickcolor', containerOut.color), - showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; - if(!showTicks) { - delete containerOut.ticklen; - delete containerOut.tickwidth; - delete containerOut.tickcolor; + // 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_245.traceIs(trace, 'pie')) continue; + + var fillFn = _$registry_245.traceIs(trace, '2dMap') ? paste : _$lib_163.fillArray; + + fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + + 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'); } }; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || _$lib_163.identity; + + if(Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} + +var _$color_43 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17973,178 +17567,164 @@ var _$handleTickDefaults_225 = function handleTickDefaults(containerIn, containe 'use strict'; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -var __ONEDAY_226 = _$numerical_145.ONEDAY; +var color = _$color_43 = {}; -var _$handleTickValueDefaults_226 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { - var tickmodeDefault = 'auto'; +/* removed: var _$attributes_42 = require('./attributes'); */; +color.defaults = _$attributes_42.defaults; +var defaultLine = color.defaultLine = _$attributes_42.defaultLine; +color.lightLine = _$attributes_42.lightLine; +var background = color.background = _$attributes_42.background; - if(containerIn.tickmode === 'array' && - (axType === 'log' || axType === 'date')) { - containerIn.tickmode = 'auto'; - } +/* + * tinyRGB: turn a tinycolor into an rgb string, but + * unlike the built-in tinycolor.toRgbString this never includes alpha + */ +color.tinyRGB = function(tc) { + var c = tc.toRgb(); + return 'rgb(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ')'; +}; - if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; - else if(containerIn.dtick) { - tickmodeDefault = 'linear'; - } - var tickmode = coerce('tickmode', tickmodeDefault); +color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_25(cstr)); }; - if(tickmode === 'auto') coerce('nticks'); - else if(tickmode === 'linear') { - // dtick is usually a positive number, but there are some - // special strings available for log or date axes - // default is 1 day for dates, otherwise 1 - var dtickDflt = (axType === 'date') ? __ONEDAY_226 : 1; - var dtick = coerce('dtick', dtickDflt); - if(_$fastIsnumeric_10(dtick)) { - containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; - } - else if(typeof dtick !== 'string') { - containerOut.dtick = dtickDflt; - } - else { - // date and log special cases are all one character plus a number - var prefix = dtick.charAt(0), - dtickNum = dtick.substr(1); +color.opacity = function(cstr) { return cstr ? _$tinycolor_25(cstr).getAlpha() : 0; }; - dtickNum = _$fastIsnumeric_10(dtickNum) ? Number(dtickNum) : 0; - if((dtickNum <= 0) || !( - // "M" gives ticks every (integer) n months - (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || - // "L" gives ticks linearly spaced in data (not in position) every (float) f - (axType === 'log' && prefix === 'L') || - // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 - (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) - )) { - containerOut.dtick = dtickDflt; - } - } - - // tick0 can have different valType for different axis types, so - // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_162.dateTick0(containerOut.calendar) : 0; - var tick0 = coerce('tick0', tick0Dflt); - if(axType === 'date') { - containerOut.tick0 = _$lib_162.cleanDate(tick0, tick0Dflt); - } - // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely - else if(_$fastIsnumeric_10(tick0) && dtick !== 'D1' && dtick !== 'D2') { - containerOut.tick0 = Number(tick0); - } - else { - containerOut.tick0 = tick0Dflt; - } - } - else { - var tickvals = coerce('tickvals'); - if(tickvals === undefined) containerOut.tickmode = 'auto'; - else coerce('ticktext'); - } +color.addOpacity = function(cstr, op) { + var c = _$tinycolor_25(cstr).toRgb(); + return 'rgba(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; +// combine two colors into one apparent color +// if back has transparency or is missing, +// color.background is assumed behind it +color.combine = function(front, back) { + var fc = _$tinycolor_25(front).toRgb(); + if(fc.a === 1) return _$tinycolor_25(front).toRgbString(); -/* removed: var _$layout_attributes_216 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_226 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_225 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_224 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_208 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_218 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_223 = require('./set_convert'); */; -/* removed: var _$orderedCategories_219 = require('./ordered_categories'); */; + var bc = _$tinycolor_25(back || background).toRgb(), + bcflat = bc.a === 1 ? bc : { + r: 255 * (1 - bc.a) + bc.r * bc.a, + g: 255 * (1 - bc.a) + bc.g * bc.a, + b: 255 * (1 - bc.a) + bc.b * bc.a + }, + fcflat = { + r: bcflat.r * (1 - fc.a) + fc.r * fc.a, + g: bcflat.g * (1 - fc.a) + fc.g * fc.a, + b: bcflat.b * (1 - fc.a) + fc.b * fc.a + }; + return _$tinycolor_25(fcflat).toRgbString(); +}; -/** - * options: object containing: +/* + * Create a color that contrasts with cstr. * - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors + * If cstr is a dark color, we lighten it; if it's light, we darken. + * + * If lightAmount / darkAmount are used, we adjust by these percentages, + * otherwise we go all the way to white or black. */ -var _$handleAxisDefaults_206 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; - - var visible = coerce('visible', !options.cheateronly); +color.contrast = function(cstr, lightAmount, darkAmount) { + var tc = _$tinycolor_25(cstr); - var axType = containerOut.type; + if(tc.getAlpha() !== 1) tc = _$tinycolor_25(color.combine(cstr, background)); - if(axType === 'date') { - var handleCalendarDefaults = _$registry_244.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } + var newColor = tc.isDark() ? + (lightAmount ? tc.lighten(lightAmount) : background) : + (darkAmount ? tc.darken(darkAmount) : defaultLine); - _$setConvert_223(containerOut, layoutOut); + return newColor.toString(); +}; - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); +color.stroke = function(s, c) { + var tc = _$tinycolor_25(c); + s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); +}; - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; +color.fill = function(s, c) { + var tc = _$tinycolor_25(c); + s.style({ + 'fill': color.tinyRGB(tc), + 'fill-opacity': tc.getAlpha() + }); +}; - if(autoRange) coerce('rangemode'); +// search container for colors with the deprecated rgb(fractions) format +// and convert them to rgb(0-255 values) +color.clean = function(container) { + if(!container || typeof container !== 'object') return; - coerce('range'); - containerOut.cleanRange(); + var keys = Object.keys(container), + i, + j, + key, + val; - _$handleCategoryOrderDefaults_208(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_219(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + for(i = 0; i < keys.length; i++) { + key = keys[i]; + val = container[key]; + // only sanitize keys that end in "color" or "colorscale" + if(key.substr(key.length - 5) === 'color') { + if(Array.isArray(val)) { + for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); + } + else container[key] = cleanOne(val); + } + else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { + // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] + for(j = 0; j < val.length; j++) { + if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); + } + } + // recurse into arrays of objects, and plain objects + else if(Array.isArray(val)) { + var el0 = val[0]; + if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { + for(j = 0; j < val.length; j++) color.clean(val[j]); + } + } + else if(val && typeof val === 'object') color.clean(val); + } +}; - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); +function cleanOne(val) { + if(_$fastIsnumeric_10(val) || typeof val !== 'string') return val; - if(!visible) return containerOut; + var valTrim = val.trim(); + if(valTrim.substr(0, 3) !== 'rgb') return val; - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); + if(!match) return val; - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_162.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + var parts = match[1].trim().split(/\s*[\s,]\s*/), + rgba = valTrim.charAt(3) === 'a' && parts.length === 4; + if(!rgba && parts.length !== 3) return val; - _$handleTickValueDefaults_226(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_224(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_225(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_218(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_216 - }); + for(var i = 0; i < parts.length; i++) { + if(!parts[i].length) return val; + parts[i] = Number(parts[i]); - if(containerOut.showline || containerOut.ticks) coerce('mirror'); + // all parts must be non-negative numbers + if(!(parts[i] >= 0)) return val; + // alpha>1 gets clipped to 1 + if(i === 3) { + if(parts[i] > 1) parts[i] = 1; + } + // r, g, b must be < 1 (ie 1 itself is not allowed) + else if(parts[i] >= 1) return val; + } - if(options.automargin) coerce('automargin'); + var rgbStr = Math.round(parts[0] * 255) + ', ' + + Math.round(parts[1] * 255) + ', ' + + Math.round(parts[2] * 255); - return containerOut; -}; + if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; + return 'rgb(' + rgbStr + ')'; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -18154,150 +17734,87 @@ var _$handleAxisDefaults_206 = function handleAxisDefaults(containerIn, containe * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -var id2name = _$axis_ids_207.id2name; - - -var _$handleConstraintDefaults_210 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); - - if(containerOut.fixedrange) return; - - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_162.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); - - if(!containerIn.scaleanchor) return; - - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - - var scaleanchor = _$lib_162.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); - - 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, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_162.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.'); +var _$attributes_49 = { + zauto: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + impliedEdits: {zmin: undefined, zmax: undefined}, + + }, + zmin: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + zmax: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + colorscale: { + valType: 'colorscale', + + editType: 'calc', + impliedEdits: {autocolorscale: false}, + + }, + autocolorscale: { + valType: 'boolean', + + dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. + editType: 'calc', + impliedEdits: {colorscale: undefined}, + + }, + reversescale: { + valType: 'boolean', + + dflt: false, + editType: 'calc', + + }, + showscale: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + } }; -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. - - 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 && !axj.fixedrange) linkableAxes.push(idj); - } - - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[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}; -} - +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * 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); - } +'use strict'; - var thisGroupKeys = Object.keys(thisGroup); +var _$flipScale_55 = function flipScale(scl) { + var N = scl.length, + sclNew = new Array(N), + si; - // 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; - } + for(var i = N - 1, j = 0; i >= 0; i--, j++) { + si = scl[i]; + sclNew[j] = [1 - si[0], si[1]]; } - // 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; -} + return sclNew; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -18310,76 +17827,71 @@ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor 'use strict'; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; - -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$scales_62 = require('./scales'); */; +/* removed: var _$flipScale_55 = require('./flip_scale'); */; -var _$handlePositionDefaults_220 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; +var _$calc_50 = function calc(trace, vals, containerStr, cLetter) { + var container, inputContainer; - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } + if(containerStr) { + container = _$lib_163.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_163.nestedProperty(trace._input, containerStr).get(); + } + else { + container = trace; + inputContainer = trace._input; } - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_10(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; - - var anchor = _$lib_162.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); - - if(anchor === 'free') coerce('position', dfltPosition); + var autoAttr = cLetter + 'auto', + minAttr = cLetter + 'min', + maxAttr = cLetter + 'max', + auto = container[autoAttr], + min = container[minAttr], + max = container[maxAttr], + scl = container.colorscale; - _$lib_162.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); + if(auto !== false || min === undefined) { + min = _$lib_163.aggNums(Math.min, null, vals); + } - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_162.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); + if(auto !== false || max === undefined) { + max = _$lib_163.aggNums(Math.max, null, vals); } - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_162.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + if(min === max) { + min -= 0.5; + max += 0.5; } - coerce('layer'); + container[minAttr] = min; + container[maxAttr] = max; - return containerOut; + inputContainer[minAttr] = min; + inputContainer[maxAttr] = max; + + /* + * If auto was explicitly false but min or max was missing, + * we filled in the missing piece here but later the trace does + * not look auto. + * Otherwise make sure the trace still looks auto as far as later + * changes are concerned. + */ + inputContainer[autoAttr] = (auto !== false || + (min === undefined && max === undefined)); + + if(container.autocolorscale) { + if(min * max < 0) scl = _$scales_62.RdBu; + else if(min >= 0) scl = _$scales_62.Reds; + else scl = _$scales_62.Blues; + + // reversescale is handled at the containerOut level + inputContainer.colorscale = scl; + if(container.reversescale) scl = _$flipScale_55(scl); + container.colorscale = scl; + } }; /** @@ -18390,199 +17902,124 @@ var _$handlePositionDefaults_220 = function handlePositionDefaults(containerIn, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; - -/* removed: var _$lib_162 = require('../../lib'); */; -var __BADNUM_205 = _$numerical_145.BADNUM; +/* removed: var _$lib_163 = require('../lib'); */; +var __extendFlat_190 = _$lib_163.extendFlat; +var __isPlainObject_190 = _$lib_163.isPlainObject; -var _$autoType_205 = function autoType(array, calendar) { - if(moreDates(array, calendar)) return 'date'; - if(category(array)) return 'category'; - if(linearOK(array)) return 'linear'; - else return '-'; +var traceOpts = { + valType: 'flaglist', + extras: ['none'], + flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'], + }; -// is there at least one number in array? If not, we should leave -// ax.type empty so it can be autoset later -function linearOK(array) { - if(!array) return false; - - for(var i = 0; i < array.length; i++) { - if(_$fastIsnumeric_10(array[i])) return true; - } +var layoutOpts = { + valType: 'flaglist', + extras: ['none'], + flags: [ + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', + 'layoutstyle', 'modebar', 'camera', 'arraydraw' + ], + +}; - return false; -} +// flags for inside restyle/relayout include a few extras +// that shouldn't be used in attributes, to deal with certain +// combinations and conditionals efficiently +var traceEditTypeFlags = traceOpts.flags.slice() + .concat(['clearCalc', 'fullReplot']); -// does the array a have mostly dates rather than numbers? -// note: some values can be neither (such as blanks, text) -// 2- or 4-digit integers can be both, so require twice as many -// dates as non-dates, to exclude cases with mostly 2 & 4 digit -// numbers and a few dates -function moreDates(a, calendar) { - var dcnt = 0, - ncnt = 0, - // test at most 1000 points, evenly spaced - inc = Math.max(1, (a.length - 1) / 1000), - ai; +var layoutEditTypeFlags = layoutOpts.flags.slice() + .concat('layoutReplot'); - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_162.isDateTime(ai, calendar)) dcnt += 1; - if(_$fastIsnumeric_10(ai)) ncnt += 1; - } +var _$edit_types_190 = { + traces: traceOpts, + layout: layoutOpts, + /* + * default (all false) edit flags for restyle (traces) + * creates a new object each call, so the caller can mutate freely + */ + traceFlags: function() { return falseObj(traceEditTypeFlags); }, - return (dcnt > ncnt * 2); -} + /* + * default (all false) edit flags for relayout + * creates a new object each call, so the caller can mutate freely + */ + layoutFlags: function() { return falseObj(layoutEditTypeFlags); }, -// are the (x,y)-values in gd.data mostly text? -// require twice as many categories as numbers -function category(a) { - // test at most 1000 points - var inc = Math.max(1, (a.length - 1) / 1000), - curvenums = 0, - curvecats = 0, - ai; + /* + * update `flags` with the `editType` values found in `attr` + */ + update: function(flags, attr) { + var editType = attr.editType; + if(editType && editType !== 'none') { + var editTypeParts = editType.split('+'); + for(var i = 0; i < editTypeParts.length; i++) { + flags[editTypeParts[i]] = true; + } + } + }, - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_162.cleanNumber(ai) !== __BADNUM_205) curvenums++; - else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; - } + overrideAll: overrideAll +}; - return curvecats > curvenums * 2; +function falseObj(keys) { + var out = {}; + for(var i = 0; i < keys.length; i++) out[keys[i]] = false; + return out; } /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$autoType_205 = require('./axis_autotype'); */; -var name2id = _$axis_ids_207.name2id; - -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored + * For attributes that are largely copied from elsewhere into a plot type that doesn't + * support partial redraws - overrides the editType field of all attributes in the object + * + * @param {object} attrs: the attributes to override. Will not be mutated. + * @param {string} editTypeOverride: the new editType to use + * @param {'nested'|'from-root'} overrideContainers: + * - 'nested' will override editType for nested containers but not the root. + * - 'from-root' will also override editType of the root container. + * Containers below the absolute top level (trace or layout root) DO need an + * editType even if they are not `valObject`s themselves (eg `scatter.marker`) + * to handle the case where you edit the whole container. + * + * @return {object} a new attributes object with `editType` modified as directed */ -var _$handleTypeDefaults_228 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } - - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; +function overrideAll(attrs, editTypeOverride, overrideContainers) { + var out = __extendFlat_190({}, attrs); + for(var key in out) { + var attr = out[key]; + if(__isPlainObject_190(attr)) { + out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } -}; - -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; - - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } - - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; - - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; - - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_244.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; - - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); - - if(trace[calAttr] !== calendar) calendar = undefined; - } + if(overrideContainers === 'from-root') out.editType = editTypeOverride; - ax.type = _$autoType_205(boxPositions, calendar); - } - else { - ax.type = _$autoType_205(d0[axLetter] || [d0[axLetter + '0']], calendar); - } + return out; } -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; +function overrideOne(attr, editTypeOverride, overrideContainers, key) { + if(attr.valType) { + var out = __extendFlat_190({}, attr); + out.editType = editTypeOverride; - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; + if(Array.isArray(attr.items)) { + out.items = new Array(attr.items.length); + for(var i = 0; i < attr.items.length; i++) { + out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root'); } } + return out; + } + else { + // don't provide an editType for the _deprecated container + return overrideAll(attr, editTypeOverride, + (key.charAt(0) === '_') ? 'nested' : 'from-root'); } } -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_244.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_244.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} - +var _$attributes_67 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18594,226 +18031,17 @@ function isBoxWithoutPositionCoords(trace, axLetter) { 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$layout_attributes_235 = require('../layout_attributes'); */; - -/* removed: var _$layout_attributes_216 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_228 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_206 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_210 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_220 = require('./position_defaults'); */; -/* removed: var _$axis_ids_207 = require('./axis_ids'); */; - - -var _$supplyLayoutDefaults_217 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; - - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - - if(!_$registry_244.traceIs(trace, 'cartesian') && !_$registry_244.traceIs(trace, 'gl2d')) { - continue; - } - - var xaName = _$axis_ids_207.id2name(trace.xaxis); - var yaName = _$axis_ids_207.id2name(trace.yaxis); - - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_244.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } - - // 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) xaCheater[xaName] = 1; - } - - // check for default formatting tweaks - if(_$registry_244.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } - - if(_$registry_244.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_162.simpleMap(xIds, _$axis_ids_207.id2name); - var yNames = _$lib_162.simpleMap(yIds, _$axis_ids_207.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 plot_bgcolor = _$color_43.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_162.coerce(layoutIn, layoutOut, _$layout_attributes_235, 'plot_bgcolor'); - } - - var bgColor = _$color_43.combine(plot_bgcolor, layoutOut.paper_bgcolor); - - var axName, axLetter, axLayoutIn, axLayoutOut; - - function coerce(attr, dflt) { - return _$lib_162.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_216, attr, dflt); - } - - function coerce2(attr, dflt) { - return _$lib_162.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_216, attr, dflt); - } - - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; - } - - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('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(_$axis_ids_207.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]; - - if(!_$lib_162.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; - - _$handleTypeDefaults_228(axLayoutIn, axLayoutOut, coerce, fullData, axName); - - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); - - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; - - _$handleAxisDefaults_206(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; - } - - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; - - _$handlePositionDefaults_220(axLayoutIn, axLayoutOut, coerce, positioningOptions); - - axLayoutOut._input = axLayoutIn; - } - - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_244.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_244.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[_$axis_ids_207.id2name(axLayoutOut.anchor)]; - - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); - - coerce('fixedrange', fixedRangeDflt); - } - - // Finally, handle scale constraints. 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 - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); - - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; - - _$handleConstraintDefaults_210(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } +_$attributes_67.dash = { + valType: 'string', + // string type usually doesn't take values... this one should really be + // a special type or at least a special coercion function, from the GUI + // you only get these values but elsewhere the user can supply a list of + // dash lengths in px, and it will be honored + values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], + dflt: 'solid', + + editType: 'style', + }; /** @@ -18826,509 +18054,507 @@ var _$supplyLayoutDefaults_217 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -var _$attributes_49 = { - zauto: { +/* removed: var _$font_attributes_231 = require('../font_attributes'); */; +/* removed: var _$attributes_42 = require('../../components/color/attributes'); */; +var dash = _$attributes_67.dash; +var __extendFlat_217 = _$extend_157.extendFlat; + +/* removed: var _$constants_210 = require('./constants'); */; + + +var _$layout_attributes_217 = { + visible: { valType: 'boolean', - dflt: true, - editType: 'calc', - impliedEdits: {zmin: undefined, zmax: undefined}, + editType: 'plot', }, - zmin: { - valType: 'number', + color: { + valType: 'color', + dflt: _$attributes_42.defaultLine, - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks', }, - zmax: { - valType: 'number', + title: { + valType: 'string', - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks+margins', }, - colorscale: { - valType: 'colorscale', + titlefont: _$font_attributes_231({ + editType: 'ticks+margins', + + }), + type: { + valType: 'enumerated', + // '-' means we haven't yet run autotype or couldn't find any data + // it gets turned into linear in gd._fullLayout but not copied back + // to gd.data like the others are. + values: ['-', 'linear', 'log', 'date', 'category'], + dflt: '-', editType: 'calc', - impliedEdits: {autocolorscale: false}, }, - autocolorscale: { - valType: 'boolean', + autorange: { + valType: 'enumerated', + values: [true, false, 'reversed'], + dflt: true, - dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. editType: 'calc', - impliedEdits: {colorscale: undefined}, + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - reversescale: { - valType: 'boolean', + rangemode: { + valType: 'enumerated', + values: ['normal', 'tozero', 'nonnegative'], + dflt: 'normal', - dflt: false, - editType: 'calc', + editType: 'plot', }, - showscale: { + range: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} + ], + editType: 'axrange+margins', + impliedEdits: {'autorange': false}, + + }, + fixedrange: { valType: 'boolean', + dflt: false, - dflt: true, editType: 'calc', - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var _$flipScale_55 = function flipScale(scl) { - var N = scl.length, - sclNew = new Array(N), - si; - - for(var i = N - 1, j = 0; i >= 0; i--, j++) { - si = scl[i]; - sclNew[j] = [1 - si[0], si[1]]; - } - - return sclNew; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_162 = require('../../lib'); */; - -/* removed: var _$scales_62 = require('./scales'); */; -/* removed: var _$flipScale_55 = require('./flip_scale'); */; - - -var _$calc_50 = function calc(trace, vals, containerStr, cLetter) { - var container, inputContainer; - - if(containerStr) { - container = _$lib_162.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_162.nestedProperty(trace._input, containerStr).get(); - } - else { - container = trace; - inputContainer = trace._input; - } - - var autoAttr = cLetter + 'auto', - minAttr = cLetter + 'min', - maxAttr = cLetter + 'max', - auto = container[autoAttr], - min = container[minAttr], - max = container[maxAttr], - scl = container.colorscale; - - if(auto !== false || min === undefined) { - min = _$lib_162.aggNums(Math.min, null, vals); - } - - if(auto !== false || max === undefined) { - max = _$lib_162.aggNums(Math.max, null, vals); - } - - if(min === max) { - min -= 0.5; - max += 0.5; - } - - container[minAttr] = min; - container[maxAttr] = max; - - inputContainer[minAttr] = min; - inputContainer[maxAttr] = max; - - /* - * If auto was explicitly false but min or max was missing, - * we filled in the missing piece here but later the trace does - * not look auto. - * Otherwise make sure the trace still looks auto as far as later - * changes are concerned. - */ - inputContainer[autoAttr] = (auto !== false || - (min === undefined && max === undefined)); - - if(container.autocolorscale) { - if(min * max < 0) scl = _$scales_62.RdBu; - else if(min >= 0) scl = _$scales_62.Reds; - else scl = _$scales_62.Blues; - - // reversescale is handled at the containerOut level - inputContainer.colorscale = scl; - if(container.reversescale) scl = _$flipScale_55(scl); - container.colorscale = scl; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_162 = require('../lib'); */; -var __extendFlat_189 = _$lib_162.extendFlat; -var __isPlainObject_189 = _$lib_162.isPlainObject; - -var traceOpts = { - valType: 'flaglist', - extras: ['none'], - flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'], - -}; - -var layoutOpts = { - valType: 'flaglist', - extras: ['none'], - flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', - 'layoutstyle', 'modebar', 'camera', 'arraydraw' - ], - -}; - -// flags for inside restyle/relayout include a few extras -// that shouldn't be used in attributes, to deal with certain -// combinations and conditionals efficiently -var traceEditTypeFlags = traceOpts.flags.slice() - .concat(['clearCalc', 'fullReplot']); - -var layoutEditTypeFlags = layoutOpts.flags.slice() - .concat('layoutReplot'); - -var _$edit_types_189 = { - traces: traceOpts, - layout: layoutOpts, - /* - * default (all false) edit flags for restyle (traces) - * creates a new object each call, so the caller can mutate freely - */ - traceFlags: function() { return falseObj(traceEditTypeFlags); }, - - /* - * default (all false) edit flags for relayout - * creates a new object each call, so the caller can mutate freely - */ - layoutFlags: function() { return falseObj(layoutEditTypeFlags); }, - - /* - * update `flags` with the `editType` values found in `attr` - */ - update: function(flags, attr) { - var editType = attr.editType; - if(editType && editType !== 'none') { - var editTypeParts = editType.split('+'); - for(var i = 0; i < editTypeParts.length; i++) { - flags[editTypeParts[i]] = true; - } - } }, - - overrideAll: overrideAll -}; - -function falseObj(keys) { - var out = {}; - for(var i = 0; i < keys.length; i++) out[keys[i]] = false; - return out; -} - -/** - * For attributes that are largely copied from elsewhere into a plot type that doesn't - * support partial redraws - overrides the editType field of all attributes in the object - * - * @param {object} attrs: the attributes to override. Will not be mutated. - * @param {string} editTypeOverride: the new editType to use - * @param {'nested'|'from-root'} overrideContainers: - * - 'nested' will override editType for nested containers but not the root. - * - 'from-root' will also override editType of the root container. - * Containers below the absolute top level (trace or layout root) DO need an - * editType even if they are not `valObject`s themselves (eg `scatter.marker`) - * to handle the case where you edit the whole container. - * - * @return {object} a new attributes object with `editType` modified as directed - */ -function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_189({}, attrs); - for(var key in out) { - var attr = out[key]; - if(__isPlainObject_189(attr)) { - out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); - } - } - if(overrideContainers === 'from-root') out.editType = editTypeOverride; - - return out; -} - -function overrideOne(attr, editTypeOverride, overrideContainers, key) { - if(attr.valType) { - var out = __extendFlat_189({}, attr); - out.editType = editTypeOverride; - - if(Array.isArray(attr.items)) { - out.items = new Array(attr.items.length); - for(var i = 0; i < attr.items.length; i++) { - out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root'); - } - } - return out; - } - else { - // don't provide an editType for the _deprecated container - return overrideAll(attr, editTypeOverride, - (key.charAt(0) === '_') ? 'nested' : 'from-root'); - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$layout_attributes_216 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -var __extendFlat_44 = _$extend_156.extendFlat; -var __overrideAll_44 = _$edit_types_189.overrideAll; - - -var _$attributes_44 = __overrideAll_44({ -// TODO: only right is supported currently -// orient: { -// valType: 'enumerated', -// -// values: ['left', 'right', 'top', 'bottom'], -// dflt: 'right', -// -// }, - thicknessmode: { + // scaleanchor: not used directly, just put here for reference + // values are any opposite-letter axis id + scaleanchor: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: [ + _$constants_210.idRegex.x.toString(), + _$constants_210.idRegex.y.toString() + ], - dflt: 'pixels', + editType: 'plot', }, - thickness: { + scaleratio: { valType: 'number', - min: 0, - dflt: 30, + dflt: 1, + + editType: 'plot', }, - lenmode: { + constrain: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: ['range', 'domain'], + dflt: 'range', - dflt: 'fraction', + editType: 'plot', }, - len: { - valType: 'number', + // constraintoward: not used directly, just put here for reference + constraintoward: { + valType: 'enumerated', + values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], + + editType: 'plot', + + }, + // ticks + tickmode: { + valType: 'enumerated', + values: ['auto', 'linear', 'array'], + + editType: 'ticks+margins', + impliedEdits: {tick0: undefined, dtick: undefined}, + + }, + nticks: { + valType: 'integer', min: 0, - dflt: 1, + dflt: 0, + editType: 'ticks+margins', }, - x: { - valType: 'number', - dflt: 1.02, - min: -2, - max: 3, + tick0: { + valType: 'any', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', + dtick: { + valType: 'any', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - xpad: { - valType: 'number', + tickvals: { + valType: 'data_array', + editType: 'ticks+margins', - min: 0, - dflt: 10, + }, + ticktext: { + valType: 'data_array', + editType: 'ticks+margins', }, - y: { - valType: 'number', + ticks: { + valType: 'enumerated', + values: ['outside', 'inside', ''], - dflt: 0.5, - min: -2, - max: 3, + editType: 'ticks+margins', }, - yanchor: { + mirror: { valType: 'enumerated', - values: ['top', 'middle', 'bottom'], + values: [true, 'ticks', false, 'all', 'allticks'], + dflt: false, - dflt: 'middle', + editType: 'ticks+layoutstyle', }, - ypad: { + ticklen: { valType: 'number', - min: 0, - dflt: 10, + dflt: 5, + + editType: 'ticks', }, - // a possible line around the bar itself - outlinecolor: _$layout_attributes_216.linecolor, - outlinewidth: _$layout_attributes_216.linewidth, - // Should outlinewidth have {dflt: 0} ? - // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_216.linecolor, - borderwidth: { + tickwidth: { valType: 'number', - min: 0, - dflt: 0, + dflt: 1, + + editType: 'ticks', }, - bgcolor: { + tickcolor: { valType: 'color', + dflt: _$attributes_42.defaultLine, - dflt: 'rgba(0,0,0,0)', + editType: 'ticks', + + }, + showticklabels: { + valType: 'boolean', + dflt: true, + + editType: 'ticks+margins', + + }, + automargin: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + showspikes: { + valType: 'boolean', + dflt: false, + + editType: 'modebar', + + }, + spikecolor: { + valType: 'color', + dflt: null, + + editType: 'none', + + }, + spikethickness: { + valType: 'number', + dflt: 3, + + editType: 'none', + + }, + spikedash: __extendFlat_217({}, dash, {dflt: 'dash', editType: 'none'}), + spikemode: { + valType: 'flaglist', + flags: ['toaxis', 'across', 'marker'], + + dflt: 'toaxis', + editType: 'none', + + }, + spikesnap: { + valType: 'enumerated', + values: ['data', 'cursor'], + dflt: 'data', + + editType: 'none', }, - // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_216.tickmode, - nticks: _$layout_attributes_216.nticks, - tick0: _$layout_attributes_216.tick0, - dtick: _$layout_attributes_216.dtick, - tickvals: _$layout_attributes_216.tickvals, - ticktext: _$layout_attributes_216.ticktext, - ticks: __extendFlat_44({}, _$layout_attributes_216.ticks, {dflt: ''}), - ticklen: _$layout_attributes_216.ticklen, - tickwidth: _$layout_attributes_216.tickwidth, - tickcolor: _$layout_attributes_216.tickcolor, - showticklabels: _$layout_attributes_216.showticklabels, tickfont: _$font_attributes_231({ + editType: 'ticks+margins', }), - tickangle: _$layout_attributes_216.tickangle, - tickformat: _$layout_attributes_216.tickformat, - tickformatstops: _$layout_attributes_216.tickformatstops, - tickprefix: _$layout_attributes_216.tickprefix, - showtickprefix: _$layout_attributes_216.showtickprefix, - ticksuffix: _$layout_attributes_216.ticksuffix, - showticksuffix: _$layout_attributes_216.showticksuffix, - separatethousands: _$layout_attributes_216.separatethousands, - exponentformat: _$layout_attributes_216.exponentformat, - showexponent: _$layout_attributes_216.showexponent, - title: { + tickangle: { + valType: 'angle', + dflt: 'auto', + + editType: 'ticks+margins', + + }, + tickprefix: { valType: 'string', + dflt: '', + editType: 'ticks+margins', }, - titlefont: _$font_attributes_231({ + showtickprefix: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - }), - titleside: { + editType: 'ticks+margins', + + }, + ticksuffix: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + showticksuffix: { valType: 'enumerated', - values: ['right', 'top', 'bottom'], + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - dflt: 'top', + editType: 'ticks+margins', - } -}, 'colorbars', 'from-root'); - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_226 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_225 = require('../../plots/cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_224 = require('../../plots/cartesian/tick_label_defaults'); */; - -/* removed: var _$attributes_44 = require('./attributes'); */; - - -var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, layout) { - var colorbarOut = containerOut.colorbar = {}, - colorbarIn = containerIn.colorbar || {}; - - function coerce(attr, dflt) { - return _$lib_162.coerce(colorbarIn, colorbarOut, _$attributes_44, attr, dflt); - } - - var thicknessmode = coerce('thicknessmode'); - coerce('thickness', (thicknessmode === 'fraction') ? - 30 / (layout.width - layout.margin.l - layout.margin.r) : - 30 - ); - - var lenmode = coerce('lenmode'); - coerce('len', (lenmode === 'fraction') ? - 1 : - layout.height - layout.margin.t - layout.margin.b - ); - - coerce('x'); - coerce('xanchor'); - coerce('xpad'); - coerce('y'); - coerce('yanchor'); - coerce('ypad'); - _$lib_162.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); - - coerce('outlinecolor'); - coerce('outlinewidth'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('bgcolor'); - - _$handleTickValueDefaults_226(colorbarIn, colorbarOut, coerce, 'linear'); + }, + showexponent: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', + + editType: 'ticks+margins', + + }, + exponentformat: { + valType: 'enumerated', + values: ['none', 'e', 'E', 'power', 'SI', 'B'], + dflt: 'B', + + editType: 'ticks+margins', + + }, + separatethousands: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + tickformat: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + tickformatstops: { + _isLinkedToArray: 'tickformatstop', - var opts = {outerTicks: false, font: layout.font}; - _$handleTickLabelDefaults_224(colorbarIn, colorbarOut, coerce, 'linear', opts); - _$handleTickDefaults_225(colorbarIn, colorbarOut, coerce, 'linear', opts); + dtickrange: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'ticks+margins'}, + {valType: 'any', editType: 'ticks+margins'} + ], + editType: 'ticks+margins', + + }, + value: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + editType: 'ticks+margins' + }, + hoverformat: { + valType: 'string', + dflt: '', + + editType: 'none', + + }, + // lines and grids + showline: { + valType: 'boolean', + dflt: false, + + editType: 'layoutstyle', + + }, + linecolor: { + valType: 'color', + dflt: _$attributes_42.defaultLine, + + editType: 'layoutstyle', + + }, + linewidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks+layoutstyle', + + }, + showgrid: { + valType: 'boolean', + + editType: 'ticks', + + }, + gridcolor: { + valType: 'color', + dflt: _$attributes_42.lightLine, + + editType: 'ticks', + + }, + gridwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks', + + }, + zeroline: { + valType: 'boolean', + + editType: 'ticks', + + }, + zerolinecolor: { + valType: 'color', + dflt: _$attributes_42.defaultLine, + + editType: 'ticks', + + }, + zerolinewidth: { + valType: 'number', + dflt: 1, + + editType: 'ticks', + + }, + // positioning attributes + // anchor: not used directly, just put here for reference + // values are any opposite-letter axis id + anchor: { + valType: 'enumerated', + values: [ + 'free', + _$constants_210.idRegex.x.toString(), + _$constants_210.idRegex.y.toString() + ], + + editType: 'plot+margins', + + }, + // side: not used directly, as values depend on direction + // values are top, bottom for x axes, and left, right for y + side: { + valType: 'enumerated', + values: ['top', 'bottom', 'left', 'right'], + + editType: 'plot+margins', + + }, + // overlaying: not used directly, just put here for reference + // values are false and any other same-letter axis id that's not + // itself overlaying anything + overlaying: { + valType: 'enumerated', + values: [ + 'free', + _$constants_210.idRegex.x.toString(), + _$constants_210.idRegex.y.toString() + ], + + editType: 'plot', + + }, + layer: { + valType: 'enumerated', + values: ['above traces', 'below traces'], + dflt: 'above traces', + + editType: 'plot', + + }, + domain: { + valType: 'info_array', + + items: [ + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} + ], + dflt: [0, 1], + editType: 'plot+margins', + + }, + position: { + valType: 'number', + min: 0, + max: 1, + dflt: 0, + + editType: 'plot+margins', + + }, + categoryorder: { + valType: 'enumerated', + values: [ + 'trace', 'category ascending', 'category descending', 'array' + /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later + ], + dflt: 'trace', + + editType: 'calc', + + }, + categoryarray: { + valType: 'data_array', + + editType: 'calc', + + }, + editType: 'calc', - coerce('title', layout._dfltTitle.colorbar); - _$lib_162.coerceFont(coerce, 'titlefont', layout.font); - coerce('titleside'); + _deprecated: { + autotick: { + valType: 'boolean', + + editType: 'ticks+margins', + + } + } }; /** @@ -19339,15 +18565,155 @@ var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$layout_attributes_217 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; +var __extendFlat_44 = _$extend_157.extendFlat; +var __overrideAll_44 = _$edit_types_190.overrideAll; -var _$hasColorbar_48 = function hasColorbar(container) { - return _$lib_162.isPlainObject(container.colorbar); -}; +var _$attributes_44 = __overrideAll_44({ +// 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: _$layout_attributes_217.linecolor, + outlinewidth: _$layout_attributes_217.linewidth, + // Should outlinewidth have {dflt: 0} ? + // another possible line outside the padding and tick labels + bordercolor: _$layout_attributes_217.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: _$layout_attributes_217.tickmode, + nticks: _$layout_attributes_217.nticks, + tick0: _$layout_attributes_217.tick0, + dtick: _$layout_attributes_217.dtick, + tickvals: _$layout_attributes_217.tickvals, + ticktext: _$layout_attributes_217.ticktext, + ticks: __extendFlat_44({}, _$layout_attributes_217.ticks, {dflt: ''}), + ticklen: _$layout_attributes_217.ticklen, + tickwidth: _$layout_attributes_217.tickwidth, + tickcolor: _$layout_attributes_217.tickcolor, + showticklabels: _$layout_attributes_217.showticklabels, + tickfont: _$font_attributes_231({ + + }), + tickangle: _$layout_attributes_217.tickangle, + tickformat: _$layout_attributes_217.tickformat, + tickformatstops: _$layout_attributes_217.tickformatstops, + tickprefix: _$layout_attributes_217.tickprefix, + showtickprefix: _$layout_attributes_217.showtickprefix, + ticksuffix: _$layout_attributes_217.ticksuffix, + showticksuffix: _$layout_attributes_217.showticksuffix, + separatethousands: _$layout_attributes_217.separatethousands, + exponentformat: _$layout_attributes_217.exponentformat, + showexponent: _$layout_attributes_217.showexponent, + title: { + valType: 'string', + + + }, + titlefont: _$font_attributes_231({ + + }), + titleside: { + valType: 'enumerated', + values: ['right', 'top', 'bottom'], + + dflt: 'top', + + } +}, 'colorbars', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -19360,77 +18726,96 @@ var _$hasColorbar_48 = function hasColorbar(container) { 'use strict'; -/* removed: var _$scales_62 = require('./scales'); */; -/* removed: var _$isValidScaleArray_60 = require('./is_valid_scale_array'); */; - - -var _$isValidScale_59 = function isValidScale(scl) { - if(_$scales_62[scl] !== undefined) return true; - else return _$isValidScaleArray_60(scl); -}; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$handleTickLabelDefaults_224 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { + var showAttrDflt = getShowAttrDflt(containerIn); + var tickPrefix = coerce('tickprefix'); + if(tickPrefix) coerce('showtickprefix', showAttrDflt); -'use strict'; + var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); + if(tickSuffix) coerce('showticksuffix', showAttrDflt); -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; + var showTickLabels = coerce('showticklabels'); + if(showTickLabels) { + var font = options.font || {}; + // as with titlefont.color, inherit axis.color only if one was + // explicitly provided + var dfltFontColor = (containerOut.color === containerIn.color) ? + containerOut.color : font.color; + _$lib_163.coerceFont(coerce, 'tickfont', { + family: font.family, + size: font.size, + color: dfltFontColor + }); + coerce('tickangle'); -/* removed: var _$lib_162 = require('../../lib'); */; + if(axType !== 'category') { + var tickFormat = coerce('tickformat'); + tickformatstopsDefaults(containerIn, containerOut); + if(!tickFormat && axType !== 'date') { + coerce('showexponent', showAttrDflt); + coerce('exponentformat'); + coerce('separatethousands'); + } + } + } +}; -/* removed: var _$hasColorbar_48 = require('../colorbar/has_colorbar'); */; -/* removed: var _$colorbarDefaults_46 = require('../colorbar/defaults'); */; -/* removed: var _$isValidScale_59 = require('./is_valid_scale'); */; -/* removed: var _$flipScale_55 = require('./flip_scale'); */; +/* + * 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'], + showAttrs = showAttrsAll.filter(function(a) { + return containerIn[a] !== undefined; + }), + sameVal = function(a) { + return containerIn[a] === containerIn[showAttrs[0]]; + }; + if(showAttrs.every(sameVal) || showAttrs.length === 1) { + return containerIn[showAttrs[0]]; + } +} -var _$colorScaleDefaults_53 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { - var prefix = opts.prefix, - cLetter = opts.cLetter, - containerStr = prefix.slice(0, prefix.length - 1), - containerIn = prefix ? - _$lib_162.nestedProperty(traceIn, containerStr).get() || {} : - traceIn, - containerOut = prefix ? - _$lib_162.nestedProperty(traceOut, containerStr).get() || {} : - traceOut, - minIn = containerIn[cLetter + 'min'], - maxIn = containerIn[cLetter + 'max'], - sclIn = containerIn.colorscale; +function tickformatstopsDefaults(tickformatIn, tickformatOut) { + var valuesIn = tickformatIn.tickformatstops; + var valuesOut = tickformatOut.tickformatstops = []; - var validMinMax = _$fastIsnumeric_10(minIn) && _$fastIsnumeric_10(maxIn) && (minIn < maxIn); - coerce(prefix + cLetter + 'auto', !validMinMax); - coerce(prefix + cLetter + 'min'); - coerce(prefix + cLetter + 'max'); + if(!Array.isArray(valuesIn)) return; - // handles both the trace case (autocolorscale is false by default) and - // the marker and marker.line case (autocolorscale is true by default) - var autoColorscaleDftl; - if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_59(sclIn); - coerce(prefix + 'autocolorscale', autoColorscaleDftl); - var sclOut = coerce(prefix + 'colorscale'); + var valueIn, valueOut; - // reversescale is handled at the containerOut level - var reverseScale = coerce(prefix + 'reversescale'); - if(reverseScale) containerOut.colorscale = _$flipScale_55(sclOut); + function coerce(attr, dflt) { + return _$lib_163.coerce(valueIn, valueOut, _$layout_attributes_217.tickformatstops, attr, dflt); + } - // ... until Scatter.colorbar can handle marker line colorbars - if(prefix === 'marker.line.') return; + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; - // handle both the trace case where the dflt is listed in attributes and - // the marker case where the dflt is determined by hasColorbar - var showScaleDftl; - if(prefix) showScaleDftl = _$hasColorbar_48(containerIn); - var showScale = coerce(prefix + 'showscale', showScaleDftl); + coerce('dtickrange'); + coerce('value'); - if(showScale) _$colorbarDefaults_46(containerIn, containerOut, layout); -}; + valuesOut.push(valueOut); + } +} /** * Copyright 2012-2018, Plotly, Inc. @@ -19443,70 +18828,25 @@ var _$colorScaleDefaults_53 = function colorScaleDefaults(traceIn, traceOut, lay 'use strict'; -/** - * Extract colorscale into numeric domain and color range. - * - * @param {array} scl colorscale array of arrays - * @param {number} cmin minimum color value (used to clamp scale) - * @param {number} cmax maximum color value (used to clamp scale) - */ -var _$extractScale_54 = function extractScale(scl, cmin, cmax) { - var N = scl.length, - domain = new Array(N), - range = new Array(N); - - for(var i = 0; i < N; i++) { - var si = scl[i]; +/* removed: var _$lib_163 = require('../../lib'); */; - domain[i] = cmin + si[0] * (cmax - cmin); - range[i] = si[1]; - } +/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; - return { - domain: domain, - range: range - }; -}; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$isValidScale_59 = require('./is_valid_scale'); */; - -var _$hasColorscale_57 = function hasColorscale(trace, containerStr) { - var container = containerStr ? - _$lib_162.nestedProperty(trace, containerStr).get() || {} : - trace; - var color = container.color; + * options: inherits outerTicks from axes.handleAxisDefaults + */ +var _$handleTickDefaults_225 = function handleTickDefaults(containerIn, containerOut, coerce, options) { + var tickLen = _$lib_163.coerce2(containerIn, containerOut, _$layout_attributes_217, 'ticklen'), + tickWidth = _$lib_163.coerce2(containerIn, containerOut, _$layout_attributes_217, 'tickwidth'), + tickColor = _$lib_163.coerce2(containerIn, containerOut, _$layout_attributes_217, 'tickcolor', containerOut.color), + showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); - var isArrayWithOneNumber = false; - if(_$lib_162.isArrayOrTypedArray(color)) { - for(var i = 0; i < color.length; i++) { - if(_$fastIsnumeric_10(color[i])) { - isArrayWithOneNumber = true; - break; - } - } + if(!showTicks) { + delete containerOut.ticklen; + delete containerOut.tickwidth; + delete containerOut.tickcolor; } - - return ( - _$lib_162.isPlainObject(container) && ( - isArrayWithOneNumber || - container.showscale === true || - (_$fastIsnumeric_10(container.cmin) && _$fastIsnumeric_10(container.cmax)) || - _$isValidScale_59(container.colorscale) || - _$lib_162.isPlainObject(container.colorbar) - ) - ); }; /** @@ -19520,32 +18860,357 @@ var _$hasColorscale_57 = function hasColorscale(trace, containerStr) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +var __ONEDAY_226 = _$numerical_145.ONEDAY; -/* removed: var _$color_43 = require('../color'); */; -/** - * 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} - */ -var _$makeColorScaleFunc_61 = function makeColorScaleFunc(specs, opts) { - opts = opts || {}; +var _$handleTickValueDefaults_226 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { + var tickmodeDefault = 'auto'; - var domain = specs.domain, - range = specs.range, - N = range.length, - _range = new Array(N); + if(containerIn.tickmode === 'array' && + (axType === 'log' || axType === 'date')) { + containerIn.tickmode = 'auto'; + } + + if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; + else if(containerIn.dtick) { + tickmodeDefault = 'linear'; + } + var tickmode = coerce('tickmode', tickmodeDefault); + + if(tickmode === 'auto') coerce('nticks'); + else if(tickmode === 'linear') { + // dtick is usually a positive number, but there are some + // special strings available for log or date axes + // default is 1 day for dates, otherwise 1 + var dtickDflt = (axType === 'date') ? __ONEDAY_226 : 1; + var dtick = coerce('dtick', dtickDflt); + if(_$fastIsnumeric_10(dtick)) { + containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; + } + else if(typeof dtick !== 'string') { + containerOut.dtick = dtickDflt; + } + else { + // date and log special cases are all one character plus a number + var prefix = dtick.charAt(0), + dtickNum = dtick.substr(1); + + dtickNum = _$fastIsnumeric_10(dtickNum) ? Number(dtickNum) : 0; + if((dtickNum <= 0) || !( + // "M" gives ticks every (integer) n months + (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || + // "L" gives ticks linearly spaced in data (not in position) every (float) f + (axType === 'log' && prefix === 'L') || + // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 + (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) + )) { + containerOut.dtick = dtickDflt; + } + } + + // tick0 can have different valType for different axis types, so + // validate that now. Also for dates, change milliseconds to date strings + var tick0Dflt = (axType === 'date') ? _$lib_163.dateTick0(containerOut.calendar) : 0; + var tick0 = coerce('tick0', tick0Dflt); + if(axType === 'date') { + containerOut.tick0 = _$lib_163.cleanDate(tick0, tick0Dflt); + } + // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely + else if(_$fastIsnumeric_10(tick0) && dtick !== 'D1' && dtick !== 'D2') { + containerOut.tick0 = Number(tick0); + } + else { + containerOut.tick0 = tick0Dflt; + } + } + else { + var tickvals = coerce('tickvals'); + if(tickvals === undefined) containerOut.tickmode = 'auto'; + else coerce('ticktext'); + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_226 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_225 = require('../../plots/cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_224 = require('../../plots/cartesian/tick_label_defaults'); */; + +/* removed: var _$attributes_44 = require('./attributes'); */; + + +var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, layout) { + var colorbarOut = containerOut.colorbar = {}, + colorbarIn = containerIn.colorbar || {}; + + function coerce(attr, dflt) { + return _$lib_163.coerce(colorbarIn, colorbarOut, _$attributes_44, attr, dflt); + } + + var thicknessmode = coerce('thicknessmode'); + coerce('thickness', (thicknessmode === 'fraction') ? + 30 / (layout.width - layout.margin.l - layout.margin.r) : + 30 + ); + + var lenmode = coerce('lenmode'); + coerce('len', (lenmode === 'fraction') ? + 1 : + layout.height - layout.margin.t - layout.margin.b + ); + + coerce('x'); + coerce('xanchor'); + coerce('xpad'); + coerce('y'); + coerce('yanchor'); + coerce('ypad'); + _$lib_163.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + + coerce('outlinecolor'); + coerce('outlinewidth'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('bgcolor'); + + _$handleTickValueDefaults_226(colorbarIn, colorbarOut, coerce, 'linear'); + + var opts = {outerTicks: false, font: layout.font}; + _$handleTickLabelDefaults_224(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickDefaults_225(colorbarIn, colorbarOut, coerce, 'linear', opts); + + coerce('title', layout._dfltTitle.colorbar); + _$lib_163.coerceFont(coerce, 'titlefont', layout.font); + coerce('titleside'); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_163 = require('../../lib'); */; + + +var _$hasColorbar_48 = function hasColorbar(container) { + return _$lib_163.isPlainObject(container.colorbar); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$scales_62 = require('./scales'); */; +/* removed: var _$isValidScaleArray_60 = require('./is_valid_scale_array'); */; + + +var _$isValidScale_59 = function isValidScale(scl) { + if(_$scales_62[scl] !== undefined) return true; + else return _$isValidScaleArray_60(scl); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; + +/* removed: var _$lib_163 = require('../../lib'); */; + +/* removed: var _$hasColorbar_48 = require('../colorbar/has_colorbar'); */; +/* removed: var _$colorbarDefaults_46 = require('../colorbar/defaults'); */; +/* removed: var _$isValidScale_59 = require('./is_valid_scale'); */; +/* removed: var _$flipScale_55 = require('./flip_scale'); */; + + +var _$colorScaleDefaults_53 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { + var prefix = opts.prefix, + cLetter = opts.cLetter, + containerStr = prefix.slice(0, prefix.length - 1), + containerIn = prefix ? + _$lib_163.nestedProperty(traceIn, containerStr).get() || {} : + traceIn, + containerOut = prefix ? + _$lib_163.nestedProperty(traceOut, containerStr).get() || {} : + traceOut, + minIn = containerIn[cLetter + 'min'], + maxIn = containerIn[cLetter + 'max'], + sclIn = containerIn.colorscale; + + var validMinMax = _$fastIsnumeric_10(minIn) && _$fastIsnumeric_10(maxIn) && (minIn < maxIn); + coerce(prefix + cLetter + 'auto', !validMinMax); + 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 autoColorscaleDftl; + if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_59(sclIn); + coerce(prefix + 'autocolorscale', autoColorscaleDftl); + var sclOut = coerce(prefix + 'colorscale'); + + // reversescale is handled at the containerOut level + var reverseScale = coerce(prefix + 'reversescale'); + if(reverseScale) containerOut.colorscale = _$flipScale_55(sclOut); + + // ... until Scatter.colorbar can handle marker line colorbars + if(prefix === 'marker.line.') return; + + // handle both the trace case where the dflt is listed in attributes and + // the marker case where the dflt is determined by hasColorbar + var showScaleDftl; + if(prefix) showScaleDftl = _$hasColorbar_48(containerIn); + var showScale = coerce(prefix + 'showscale', showScaleDftl); + + if(showScale) _$colorbarDefaults_46(containerIn, containerOut, layout); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/** + * Extract colorscale into numeric domain and color range. + * + * @param {array} scl colorscale array of arrays + * @param {number} cmin minimum color value (used to clamp scale) + * @param {number} cmax maximum color value (used to clamp scale) + */ +var _$extractScale_54 = function extractScale(scl, cmin, cmax) { + var N = scl.length, + domain = new Array(N), + range = new Array(N); + + for(var i = 0; i < N; i++) { + var si = scl[i]; + + domain[i] = cmin + si[0] * (cmax - cmin); + range[i] = si[1]; + } + + return { + domain: domain, + range: range + }; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$isValidScale_59 = require('./is_valid_scale'); */; + +var _$hasColorscale_57 = function hasColorscale(trace, containerStr) { + var container = containerStr ? + _$lib_163.nestedProperty(trace, containerStr).get() || {} : + trace; + var color = container.color; + + var isArrayWithOneNumber = false; + if(_$lib_163.isArrayOrTypedArray(color)) { + for(var i = 0; i < color.length; i++) { + if(_$fastIsnumeric_10(color[i])) { + isArrayWithOneNumber = true; + break; + } + } + } + + return ( + _$lib_163.isPlainObject(container) && ( + isArrayWithOneNumber || + container.showscale === true || + (_$fastIsnumeric_10(container.cmin) && _$fastIsnumeric_10(container.cmax)) || + _$isValidScale_59(container.colorscale) || + _$lib_163.isPlainObject(container.colorbar) + ) + ); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; + +/* removed: var _$color_43 = require('../color'); */; + +/** + * 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} + */ +var _$makeColorScaleFunc_61 = function makeColorScaleFunc(specs, opts) { + opts = opts || {}; + + var domain = specs.domain, + range = specs.range, + N = range.length, + _range = new Array(N); for(var i = 0; i < N; i++) { var rgba = _$tinycolor_25(range[i]).toRgb(); @@ -20226,7 +19891,7 @@ var _$string_mappings_146 = { } }; -var _$svg_text_utils_183 = {}; +var _$svg_text_utils_184 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -20242,7 +19907,7 @@ var _$svg_text_utils_183 = {}; /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$lib_163 = require('../lib'); */; /* removed: var _$xmlns_namespaces_147 = require('../constants/xmlns_namespaces'); */; /* removed: var _$string_mappings_146 = require('../constants/string_mappings'); */; var LINE_SPACING = _$alignment_143.LINE_SPACING; @@ -20255,7 +19920,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_183.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_184.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) @@ -20298,7 +19963,7 @@ _$svg_text_utils_183.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_183.positionText(_context); + _$svg_text_utils_184.positionText(_context); if(_callback) _callback.call(_context); } @@ -20393,7 +20058,7 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_162.randstr([], 64); + var randomID = 'math-output-' + _$lib_163.randstr([], 64); var tmpDiv = _$d3_7.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) @@ -20404,7 +20069,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = _$d3_7.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_162.log('There was an error in the tex syntax.', _texString); + _$lib_163.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -20499,7 +20164,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_183.plainText = function(_str) { +_$svg_text_utils_184.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -20632,14 +20297,14 @@ function buildSVGText(containerNode, str) { // 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_162.log('Ignoring unexpected end tag .', str); + _$lib_163.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_162.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_163.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -20698,7 +20363,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -20713,11 +20381,11 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_183.lineCount = function lineCount(s) { +_$svg_text_utils_184.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_183.positionText = function positionText(s, x, y) { +_$svg_text_utils_184.positionText = function positionText(s, x, y) { return s.each(function() { var text = _$d3_7.select(this); @@ -20793,7 +20461,7 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_183.makeEditable = function(context, options) { +_$svg_text_utils_184.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; var dispatch = _$d3_7.dispatch('edit', 'input', 'cancel'); @@ -20916,7 +20584,7 @@ _$svg_text_utils_183.makeEditable = function(context, options) { // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_297 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_298 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -20952,17 +20620,20 @@ var _$makeBubbleSizeFn_297 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; -var _$subtypes_302 = { +var _$subtypes_303 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -20971,8 +20642,8 @@ var _$subtypes_302 = { }, isBubble: function(trace) { - return _$lib_162.isPlainObject(trace.marker) && - _$lib_162.isArrayOrTypedArray(trace.marker.size); + return _$lib_163.isPlainObject(trace.marker) && + _$lib_163.isArrayOrTypedArray(trace.marker.size); } }; @@ -20992,19 +20663,19 @@ var _$drawing_68 = {}; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$registry_244 = require('../../registry'); */; +/* removed: var _$registry_245 = require('../../registry'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$colorscale_58 = require('../colorscale'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; /* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; /* removed: var _$alignment_143 = require('../../constants/alignment'); */; var __LINE_SPACING_68 = _$alignment_143.LINE_SPACING; var __DESELECTDIM_68 = _$interactions_144.DESELECTDIM; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_297 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_298 = require('../../traces/scatter/make_bubble_size_func'); */; var drawing = _$drawing_68 = {}; @@ -21014,7 +20685,7 @@ var drawing = _$drawing_68 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_162.isPlainObject(family)) { + if(_$lib_163.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; @@ -21182,7 +20853,7 @@ drawing.fillGroupStyle = function(s) { shape.call(_$color_43.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_162.error(e, s); + _$lib_163.error(e, s); shape.remove(); } }); @@ -21245,8 +20916,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_244.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_297(trace); + if(_$registry_245.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_298(trace); sel.attr('d', function(d) { var r; @@ -21255,7 +20926,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_302.isBubble(trace) ? + r = _$subtypes_303.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -21295,10 +20966,10 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_162.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_43.defaultLine; + else if(_$lib_163.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_43.defaultLine; else lineColor = markerLine.color; - if(_$lib_162.isArrayOrTypedArray(marker.color)) { + if(_$lib_163.isArrayOrTypedArray(marker.color)) { fillColor = _$color_43.defaultLine; perPointGradient = true; } @@ -21351,7 +21022,7 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_162.identity); + .data([type + color1 + color2], _$lib_163.identity); gradient.exit().remove(); @@ -21394,9 +21065,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_163.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -21502,7 +21171,7 @@ drawing.selectedPointStyle = function(s, trace) { }); } - if(_$registry_244.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_245.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { var pt = _$d3_7.select(this); var mx = d.mx || marker.symbol || 0; @@ -21517,16 +21186,16 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_162.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_163.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_162.isArrayOrTypedArray(colorArray)) { + if(scl && _$lib_163.isArrayOrTypedArray(colorArray)) { return _$colorscale_58.makeColorScaleFunc( _$colorscale_58.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_162.identity; + else return _$lib_163.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; @@ -21546,7 +21215,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_183.lineCount(s) - 1) * __LINE_SPACING_68 + 1; + var numLines = (_$svg_text_utils_184.lineCount(s) - 1) * __LINE_SPACING_68 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -21565,7 +21234,7 @@ function extracTextFontSize(d, trace) { drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { var p = _$d3_7.select(this); - var text = _$lib_162.extractOption(d, trace, 'tx', 'text'); + var text = _$lib_163.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -21580,7 +21249,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_183.convertToTspans, gd) + .call(_$svg_text_utils_184.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -21708,33 +21377,28 @@ drawing.steps = function(shape) { // 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 = _$d3_7.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_147.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_163.ensureSingleById(_$d3_7.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_147.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_163.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; @@ -21779,7 +21443,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_162.extendFlat({}, out); + if(out) return _$lib_163.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -21823,7 +21487,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_162.extendFlat({}, out); + if(out) return _$lib_163.extendFlat({}, out); } } var testNode, tester; @@ -21841,7 +21505,7 @@ drawing.bBox = function(node, inTester, hash) { // standardize its position (and newline tspans if any) _$d3_7.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_183.positionText, 0, 0); + .call(_$svg_text_utils_184.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -21871,7 +21535,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_162.extendFlat({}, bb); + return _$lib_163.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -21896,15 +21560,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_7.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_7.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -22042,6 +21712,319 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { }); }; +var _$helpers_82 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_163 = require('../../lib'); */; + +// look for either subplot or xaxis and yaxis attributes +// does not handle splom case +_$helpers_82.getSubplot = function getSubplot(trace) { + return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +}; + +// is trace in given list of subplots? +// does handle splom case +_$helpers_82.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_82.getSubplot(trace)) !== -1; +}; + +// convenience functions for mapping all relevant axes +_$helpers_82.flat = function flat(subplots, v) { + var out = new Array(subplots.length); + for(var i = 0; i < subplots.length; i++) { + out[i] = v; + } + return out; +}; + +_$helpers_82.p2c = function p2c(axArray, v) { + var out = new Array(axArray.length); + for(var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); + } + return out; +}; + +_$helpers_82.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { + if(mode === 'closest') return dxy || _$helpers_82.quadrature(dx, dy); + return mode === 'x' ? dx : dy; +}; + +_$helpers_82.getClosest = function getClosest(cd, distfn, pointData) { + // do we already have a point number? (array mode only) + if(pointData.index !== false) { + if(pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; + } + else pointData.index = false; + } + else { + // apply the distance function to each data point + // this is the longest loop... if this bogs down, we may need + // to create pre-sorted data (by x or y), not sure how to + // do this for 'closest' + for(var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if(newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; + } + } + } + return pointData; +}; + +/* + * pseudo-distance function for hover effects on areas: inside the region + * distance is finite (`passVal`), outside it's Infinity. + * + * @param {number} v0: signed difference between the current position and the left edge + * @param {number} v1: signed difference between the current position and the right edge + * @param {number} passVal: the value to return on success + */ +_$helpers_82.inbox = function inbox(v0, v1, passVal) { + return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; +}; + +_$helpers_82.quadrature = function quadrature(dx, dy) { + return function(di) { + var x = dx(di), + y = dy(di); + return Math.sqrt(x * x + y * y); + }; +}; + +/** Fill event data point object for hover and selection. + * Invokes _module.eventData if present. + * + * N.B. note that point 'index' corresponds to input data array index + * whereas 'number' is its post-transform version. + * + * If the hovered/selected pt corresponds to an multiple input points + * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' + * are include in the event data. + * + * @param {object} pt + * @param {object} trace + * @param {object} cd + * @return {object} + */ +_$helpers_82.makeEventData = function makeEventData(pt, trace, cd) { + // hover uses 'index', select uses 'pointNumber' + var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber: pointNumber + }; + + if(trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; + + if(pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; + } else { + out.pointIndices = pointIndices; + } + } else { + out.pointIndex = pointNumber; + } + + if(trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if('xVal' in pt) out.x = pt.xVal; + else if('x' in pt) out.x = pt.x; + + if('yVal' in pt) out.y = pt.yVal; + else if('y' in pt) out.y = pt.y; + + if(pt.xa) out.xaxis = pt.xa; + if(pt.ya) out.yaxis = pt.ya; + if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; + } + + _$helpers_82.appendArrayPointValue(out, trace, pointNumber); + + return out; +}; + +/** Appends values inside array attributes corresponding to given point number + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {number|Array(number)} pointNumber : point number. May be a length-2 array + * [row, col] to dig into 2D arrays + */ +_$helpers_82.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_163.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); + + if(pointVal !== undefined) pointData[key] = pointVal; + } + } +}; + +/** + * Appends values inside array attributes corresponding to given point number array + * For use when pointData references a plot entity that arose (or potentially arose) + * from multiple points in the input data + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. + * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays + */ +_$helpers_82.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_163.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); + + for(var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); + } + pointData[key] = keyVal; + } + } +}; + +var pointKeyMap = { + ids: 'id', + locations: 'location', + labels: 'label', + values: 'value', + 'marker.colors': 'color' +}; + +function getPointKey(astr) { + return pointKeyMap[astr] || astr; +} + +function getPointData(val, pointNumber) { + if(Array.isArray(pointNumber)) { + if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; + } + } else { + return val[pointNumber]; + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +// works with our CSS cursor classes (see css/_cursor.scss) +// to apply cursors to d3 single-element selections. +// omit cursor to revert to the default. +var _$setCursor_182 = function setCursor(el3, csr) { + (el3.attr('class') || '').split(' ').forEach(function(cls) { + if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); + }); + + if(csr) el3.classed('cursor-' + csr, true); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$setCursor_182 = require('./setcursor'); */; + +var STASHATTR = 'data-savedcursor'; +var NO_CURSOR = '!!'; + +/* + * works with our CSS cursor classes (see css/_cursor.scss) + * to override a previous cursor set on d3 single-element selections, + * by moving the name of the original cursor to the data-savedcursor attr. + * omit cursor to revert to the previously set value. + */ +var _$overrideCursor_174 = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if(csr) { + if(!savedCursor) { + var classes = (el3.attr('class') || '').split(' '); + for(var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if(cls.indexOf('cursor-') === 0) { + el3.attr(STASHATTR, cls.substr(7)) + .classed(cls, false); + } + } + if(!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); + } + } + _$setCursor_182(el3, csr); + } + else if(savedCursor) { + el3.attr(STASHATTR, null); + + if(savedCursor === NO_CURSOR) _$setCursor_182(el3); + else _$setCursor_182(el3, savedCursor); + } +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22052,7 +22035,7 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -var _$animation_attributes_199 = { +var _$animation_attributes_200 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -22199,7 +22182,7 @@ var _$frame_attributes_232 = { 'use strict'; /* removed: var _$attributes_49 = require('./attributes'); */; -var __extendFlat_51 = _$extend_156.extendFlat; +var __extendFlat_51 = _$extend_157.extendFlat; /* removed: var _$scales_62 = require('./scales.js'); */; /* @@ -22265,7 +22248,7 @@ var _$makeColorScaleAttributes_51 = function makeColorScaleAttributes(context, e 'use strict'; -var _$constants_286 = { +var _$constants_287 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -22293,13 +22276,13 @@ var _$constants_286 = { /* removed: var _$makeColorScaleAttributes_51 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_44 = require('../../components/colorbar/attributes'); */; /* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -var __dash_280 = _$attributes_67.dash; +var __dash_281 = _$attributes_67.dash; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$constants_286 = require('./constants'); */; -var __extendFlat_280 = _$extend_156.extendFlat; +/* removed: var _$constants_287 = require('./constants'); */; +var __extendFlat_281 = _$extend_157.extendFlat; -var _$attributes_280 = { +var _$attributes_281 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -22401,7 +22384,7 @@ var _$attributes_280 = { editType: 'plot', }, - dash: __extendFlat_280({}, __dash_280, {editType: 'style'}), + dash: __extendFlat_281({}, __dash_281, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -22441,7 +22424,7 @@ var _$attributes_280 = { editType: 'style', }, - marker: __extendFlat_280({ + marker: __extendFlat_281({ symbol: { valType: 'enumerated', values: _$drawing_68.symbolList, @@ -22510,7 +22493,7 @@ var _$attributes_280 = { }, colorbar: _$attributes_44, - line: __extendFlat_280({ + line: __extendFlat_281({ width: { valType: 'number', min: 0, @@ -22661,12 +22644,12 @@ var _$attributes_280 = { 'use strict'; -/* removed: var _$attributes_280 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_280.marker; +/* removed: var _$attributes_281 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_281.marker; var _$area_attributes_238 = { - r: _$attributes_280.r, - t: _$attributes_280.t, + r: _$attributes_281.r, + t: _$attributes_281.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -22687,11 +22670,11 @@ var _$area_attributes_238 = { 'use strict'; -/* removed: var _$layout_attributes_216 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_239 = _$extend_156.extendFlat; -var __overrideAll_239 = _$edit_types_189.overrideAll; +/* removed: var _$layout_attributes_217 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_239 = _$extend_157.extendFlat; +var __overrideAll_239 = _$edit_types_190.overrideAll; -var domainAttr = __extendFlat_239({}, _$layout_attributes_216.domain, { +var domainAttr = __extendFlat_239({}, _$layout_attributes_217.domain, { }); @@ -22791,7 +22774,7 @@ var _$axis_attributes_239 = __overrideAll_239({ } }, 'plot', 'nested'); -var _$plot_schema_195 = {}; +var _$plot_schema_196 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22803,22 +22786,23 @@ var _$plot_schema_195 = {}; 'use strict'; -/* removed: var _$registry_244 = require('../registry'); */; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$registry_245 = require('../registry'); */; +/* removed: var _$lib_163 = require('../lib'); */; -/* removed: var _$attributes_201 = require('../plots/attributes'); */; +/* removed: var _$attributes_202 = require('../plots/attributes'); */; /* removed: var _$layout_attributes_235 = require('../plots/layout_attributes'); */; /* removed: var _$frame_attributes_232 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_199 = require('../plots/animation_attributes'); */; +/* removed: var _$animation_attributes_200 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet /* removed: var _$area_attributes_238 = require('../plots/polar/legacy/area_attributes'); */; /* removed: var _$axis_attributes_239 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_189 = require('./edit_types'); */; +/* removed: var _$edit_types_190 = require('./edit_types'); */; -var __extendFlat_195 = _$lib_162.extendFlat; -var __extendDeepAll_195 = _$lib_162.extendDeepAll; +var __extendFlat_196 = _$lib_163.extendFlat; +var __extendDeepAll_196 = _$lib_163.extendDeepAll; +var __isPlainObject_196 = _$lib_163.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -22826,10 +22810,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_195.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_195.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_195.DEPRECATED = DEPRECATED; -_$plot_schema_195.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_196.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_196.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_196.DEPRECATED = DEPRECATED; +_$plot_schema_196.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -22842,26 +22826,26 @@ _$plot_schema_195.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_195.get = function() { +_$plot_schema_196.get = function() { var traces = {}; - _$registry_244.allTypes.concat('area').forEach(function(type) { + _$registry_245.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_244.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_245.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_162.valObjectMeta, + valObjects: _$lib_163.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_189.traces, - layout: _$edit_types_189.layout + traces: _$edit_types_190.traces, + layout: _$edit_types_190.layout }, impliedEdits: { @@ -22874,7 +22858,7 @@ _$plot_schema_195.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_199) + animation: formatAttributes(_$animation_attributes_200) }; }; @@ -22905,7 +22889,7 @@ _$plot_schema_195.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_195.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_196.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -22917,10 +22901,10 @@ _$plot_schema_195.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_195.isValObject(attr)) return; + if(_$plot_schema_196.isValObject(attr)) return; - if(_$lib_162.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_195.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_196(attr) && attrName !== 'impliedEdits') { + _$plot_schema_196.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -22932,7 +22916,7 @@ _$plot_schema_195.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_195.isValObject = function(obj) { +_$plot_schema_196.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -22946,7 +22930,7 @@ _$plot_schema_195.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_195.findArrayAttributes = function(trace) { +_$plot_schema_196.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -22969,8 +22953,8 @@ _$plot_schema_195.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_162.nestedProperty(trace, astr).get(); - if(!_$lib_162.isArrayOrTypedArray(val)) return; + var val = _$lib_163.nestedProperty(trace, astr).get(); + if(!_$lib_163.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -22979,9 +22963,9 @@ _$plot_schema_195.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_195.crawl(_$attributes_201, callback); + _$plot_schema_196.crawl(_$attributes_202, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_195.crawl(trace._module.attributes, callback); + _$plot_schema_196.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -22994,7 +22978,7 @@ _$plot_schema_195.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_195.crawl(module.attributes, callback, 1); + _$plot_schema_196.crawl(module.attributes, callback, 1); } } } @@ -23006,8 +22990,8 @@ _$plot_schema_195.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_195.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_162.filterUnique(arrayAttributes); + _$plot_schema_196.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_163.filterUnique(arrayAttributes); } return arrayAttributes; @@ -23028,18 +23012,19 @@ _$plot_schema_195.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_195.getTraceValObject = function(trace, parts) { +_$plot_schema_196.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_244.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_245.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } @@ -23050,7 +23035,7 @@ _$plot_schema_195.getTraceValObject = function(trace, parts) { // 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_244.modules[trace.type || _$attributes_201.type.dflt] || {})._module; + if(!_module) _module = (_$registry_245.modules[trace.type || _$attributes_202.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -23065,7 +23050,7 @@ _$plot_schema_195.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_201[head]; + if(!valObject) valObject = _$attributes_202[head]; } return recurseIntoValObject(valObject, parts, i); @@ -23084,7 +23069,7 @@ _$plot_schema_195.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_195.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_196.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -23135,8 +23120,8 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_244.componentsRegistry) { - _module = _$registry_244.componentsRegistry[key]; + for(key in _$registry_245.componentsRegistry) { + _module = _$registry_245.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } @@ -23166,7 +23151,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_162.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_196(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -23213,7 +23198,7 @@ function getTraceAttributes(type) { basePlotModule = {}; } else { - _module = _$registry_244.modules[type]._module, + _module = _$registry_245.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -23223,14 +23208,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_195(attributes, _$attributes_201); + __extendDeepAll_196(attributes, _$attributes_202); // module attributes - __extendDeepAll_195(attributes, _module.attributes); + __extendDeepAll_196(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_195(attributes, basePlotModule.attributes); + __extendDeepAll_196(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -23245,7 +23230,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_195(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_196(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -23257,21 +23242,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_195(layoutAttributes, _$layout_attributes_235); + __extendDeepAll_196(layoutAttributes, _$layout_attributes_235); // add base plot module layout attributes - for(key in _$registry_244.subplotsRegistry) { - _module = _$registry_244.subplotsRegistry[key]; + for(key in _$registry_245.subplotsRegistry) { + _module = _$registry_245.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -23280,8 +23264,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_244.componentsRegistry) { - _module = _$registry_244.componentsRegistry[key]; + for(key in _$registry_245.componentsRegistry) { + _module = _$registry_245.componentsRegistry[key]; var schema = _module.schema; /* @@ -23312,12 +23296,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_244.transformsRegistry[type]; - var attributes = __extendDeepAll_195({}, _module.attributes); + var _module = _$registry_245.transformsRegistry[type]; + var attributes = __extendDeepAll_196({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_244.componentsRegistry).forEach(function(k) { - var _module = _$registry_244.componentsRegistry[k]; + Object.keys(_$registry_245.componentsRegistry).forEach(function(k) { + var _module = _$registry_245.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -23333,7 +23317,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_162.extendDeepAll({}, _$frame_attributes_232) + frames: _$lib_163.extendDeepAll({}, _$frame_attributes_232) }; formatAttributes(attrs); @@ -23344,6 +23328,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -23360,7 +23345,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_195.isValObject(attr)) { + if(_$plot_schema_196.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -23372,13 +23357,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_162.isPlainObject(attr)) { + else if(__isPlainObject_196(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_195.crawl(attrs, callback); + _$plot_schema_196.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -23397,32 +23382,55 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_195.crawl(attrs, callback); + _$plot_schema_196.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_196(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_195(layoutAttributes, { + __extendFlat_196(layoutAttributes, { radialaxis: _$axis_attributes_239.radialaxis, angularaxis: _$axis_attributes_239.angularaxis }); - __extendFlat_195(layoutAttributes, _$axis_attributes_239.layout); + __extendFlat_196(layoutAttributes, _$axis_attributes_239.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_162.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_195({}, _module.layoutAttributes); + var np = _$lib_163.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_196({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_162.nestedProperty(baseAttrs, astr); + var np = _$lib_163.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_195(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_196(np.get() || {}, newAttrs)); } var _$command_229 = {}; @@ -23436,8 +23444,8 @@ var _$command_229 = {}; 'use strict'; -/* removed: var _$registry_244 = require('../registry'); */; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$registry_245 = require('../registry'); */; +/* removed: var _$lib_163 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -23541,7 +23549,7 @@ _$command_229.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_162.log('Unable to automatically bind plot updates to API command'); + _$lib_163.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -23659,7 +23667,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_162.nestedProperty(container, binding.prop).get(); + value = _$lib_163.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -23691,7 +23699,7 @@ function bindingValueHasChanged(gd, binding, cache) { _$command_229.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_244.apiMethodRegistry[method]; + var _method = _$registry_245.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -23700,7 +23708,7 @@ _$command_229.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_162.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_163.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; @@ -23750,7 +23758,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_162.isPlainObject(astr)) { + } else if(_$lib_163.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -23774,7 +23782,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_162.isPlainObject(astr)) { + } else if(_$lib_163.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -23840,7 +23848,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_162.isPlainObject(attr)) { + if(_$lib_163.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -23849,6 +23857,32 @@ function crawl(attrs, callback, path, depth) { }); } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_244 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + var _$plots_237 = {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -23864,25 +23898,27 @@ var _$plots_237 = {}; /* removed: var _$d3_7 = require('d3'); */; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$registry_244 = require('../registry'); */; -/* removed: var _$plot_schema_195 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_207 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_162 = require('../lib'); */; -var _ = _$lib_162._; +/* removed: var _$registry_245 = require('../registry'); */; +/* removed: var _$plot_schema_196 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_163 = require('../lib'); */; /* removed: var _$color_43 = require('../components/color'); */; var __BADNUM_237 = _$numerical_145.BADNUM; -var plots = _$plots_237 = {}; +/* removed: var _$axis_ids_208 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_237 = _$sort_modules_244.sortBasePlotModules; -/* removed: var _$animation_attributes_199 = require('./animation_attributes'); */; +/* removed: var _$animation_attributes_200 = require('./animation_attributes'); */; /* removed: var _$frame_attributes_232 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_162.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_163.relinkPrivateKeys; +var _ = _$lib_163._; + +var plots = _$plots_237 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_162.extendFlat(plots, _$registry_244); +_$lib_163.extendFlat(plots, _$registry_245); -plots.attributes = _$attributes_201; +plots.attributes = _$attributes_202; plots.attributes.type.values = plots.allTypes; plots.fontAttrs = _$font_attributes_231; plots.layoutAttributes = _$layout_attributes_235; @@ -23902,15 +23938,15 @@ plots.hasSimpleAPICommandBindings = _$command_229.hasSimpleAPICommandBindings; // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_162.getGraphDiv(gd); + gd = _$lib_163.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_244.getComponentMethod('annotations', 'draw')(gd); - _$registry_244.getComponentMethod('legend', 'draw')(gd); + _$registry_245.getComponentMethod('annotations', 'draw')(gd); + _$registry_245.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -23923,7 +23959,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_162.getGraphDiv(gd); + gd = _$lib_163.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -23954,7 +23990,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_244.call('relayout', gd, {autosize: true}).then(function() { + _$registry_245.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -23984,12 +24020,8 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_163.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', 'fill': _$color_43.defaultLine, @@ -24001,12 +24033,11 @@ plots.addLinks = function(gd) { links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -24144,6 +24175,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -24178,7 +24211,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -24221,12 +24253,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_245.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_163.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_163.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_163.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -24237,7 +24295,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -24246,6 +24304,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -24256,7 +24325,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -24268,17 +24337,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_207.list(gd); + var axList = _$axis_ids_208.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -24288,6 +24357,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_237); }; /** @@ -24306,7 +24378,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_244.subplotsRegistry; + var subplotsRegistry = _$registry_245.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -24319,7 +24391,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_162.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_163.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -24340,14 +24412,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_162.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_163.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_162.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_163.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -24392,7 +24464,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_244.localeRegistry; + locales = _$registry_245.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -24401,7 +24473,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_244.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_245.localeRegistry.en.format); return formatObj; } @@ -24453,30 +24525,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_245.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -24484,7 +24554,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -24556,8 +24626,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_207.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_207.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_208.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_208.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -24602,13 +24672,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_207.list(mockGd, null, true); + var axList = _$axis_ids_208.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_207.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_208.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -24630,7 +24700,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_207.getFromId(mockGd, ax.anchor); + _$axis_ids_208.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -24659,7 +24729,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_207.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_208.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -24700,17 +24770,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_195.crawl( + _$plot_schema_196.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_162.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_163.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_162.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_163.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -24732,8 +24802,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_162.pushUnique(modules, _module); - _$lib_162.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_163.pushUnique(modules, _module); + _$lib_163.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -24793,11 +24863,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_244.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_245.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_244.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_245.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -24826,7 +24896,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_162.coerce(opts || {}, optsOut, _$animation_attributes_199, attr, dflt); + return _$lib_163.coerce(opts || {}, optsOut, _$animation_attributes_200, attr, dflt); } coerce('mode'); @@ -24858,7 +24928,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_162.coerce(opts || {}, optsOut, _$animation_attributes_199.frame, attr, dflt); + return _$lib_163.coerce(opts || {}, optsOut, _$animation_attributes_200.frame, attr, dflt); } coerce('duration'); @@ -24871,7 +24941,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_162.coerce(opts || {}, optsOut, _$animation_attributes_199.transition, attr, dflt); + return _$lib_163.coerce(opts || {}, optsOut, _$animation_attributes_200.transition, attr, dflt); } coerce('duration'); @@ -24884,7 +24954,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_162.coerce(frameIn, frameOut, _$frame_attributes_232, attr, dflt); + return _$lib_163.coerce(frameIn, frameOut, _$frame_attributes_232, attr, dflt); } coerce('group'); @@ -24905,7 +24975,7 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) var i; function coerce(attr, dflt) { - return _$lib_162.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_163.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -24921,9 +24991,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -24933,18 +25003,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_162.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_163.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_162.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_163.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_162.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_163.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_162.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_163.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -24954,12 +25024,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_244.traceIs(traceOut, 'showLegend')) { + if(_$registry_245.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_244.getComponentMethod( + _$registry_245.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -24968,12 +25038,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_162.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_163.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_244.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_245.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_244.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_245.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -25017,17 +25087,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_162.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_163.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_162.pushUnique(transformModules, _module); + _$lib_163.pushUnique(transformModules, _module); } else { - transformOut = _$lib_162.extendFlat({}, transformIn); + transformOut = _$lib_163.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -25059,14 +25129,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_162.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_163.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_162.coerceFont(coerce, 'font'); + var globalFont = _$lib_163.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_162.coerceFont(coerce, 'titlefont', { + _$lib_163.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -25094,7 +25164,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_244.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_245.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -25105,12 +25175,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_244.getComponentMethod( + _$registry_245.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_244.getComponentMethod( + _$registry_245.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -25122,7 +25192,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_162.isPlotDiv(gd); + var isPlotDiv = _$lib_163.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -25210,11 +25280,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_244.componentsRegistry; + var componentsRegistry = _$registry_245.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_244.subplotsRegistry.cartesian; + var Cartesian = _$registry_245.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -25233,13 +25303,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_244.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_245.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_162.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_163.subplotSort); } // base plot module layout defaults @@ -25311,7 +25381,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_162.clearThrottle(); + _$lib_163.clearThrottle(); // data and layout delete gd.data; @@ -25367,7 +25437,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_162.pushUnique(styleModules, _module.style); + _$lib_163.pushUnique(styleModules, _module.style); } } @@ -25522,7 +25592,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_244.call('plot', gd); + return _$registry_245.call('plot', gd); } }; @@ -25563,7 +25633,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_162.isPlainObject(d)) { + if(_$lib_163.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -25586,7 +25656,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_162.isPlainObject(d.stream)) { + if(!_$lib_163.isPlainObject(d.stream)) { continue; } } @@ -25612,7 +25682,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_162.isJSDate(d)) return _$lib_162.ms2DateTimeLocal(+d); + if(_$lib_163.isJSDate(d)) return _$lib_163.ms2DateTimeLocal(+d); return d; } @@ -25809,8 +25879,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_162.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_162.expandObjectPaths(copy); + var copy = _$lib_163.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_163.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -25818,29 +25888,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_162.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_163.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_162.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_163.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_162.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_163.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_162.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_163.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_162.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_163.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_162.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_163.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -25865,7 +25935,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_244.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_245.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -25939,7 +26009,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_162.expandObjectPaths(_$lib_162.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_163.expandObjectPaths(_$lib_163.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -25966,7 +26036,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_244.getComponentMethod('errorbars', 'calc')(gd); + _$registry_245.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -26014,7 +26084,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_244.call('redraw', gd); + return _$registry_245.call('redraw', gd); }); } @@ -26046,7 +26116,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_162.expandObjectPaths(layout); + var newLayout = _$lib_163.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -26056,7 +26126,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_162.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_163.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -26086,7 +26156,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_244.call('redraw', gd); + return _$registry_245.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -26121,7 +26191,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_162.syncOrAsync(seq, gd); + var transitionStarting = _$lib_163.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -26133,7 +26203,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_207.list(gd), + var axList = _$axis_ids_208.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -26177,7 +26247,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_195.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_196.findArrayAttributes(trace); } // add polar axes to axis list @@ -26221,14 +26291,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -26263,7 +26334,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_244.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_245.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -26314,7 +26390,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_162.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_163.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -26336,11 +26412,11 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; /* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$color_43 = require('../color'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; /* removed: var _$interactions_144 = require('../../constants/interactions'); */; var _$titles_136 = { @@ -26421,10 +26497,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_163.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -26442,7 +26515,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_162.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_163.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -26470,7 +26543,7 @@ function draw(gd, titleClass, options) { 'font-weight': _$plots_237.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_183.convertToTspans, gd); + .call(_$svg_text_utils_184.convertToTspans, gd); return _$plots_237.previousPromises(gd); } @@ -26520,7 +26593,7 @@ function draw(gd, titleClass, options) { avoid.selection.each(function() { var avoidbb = _$drawing_68.bBox(this); - if(_$lib_162.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_163.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -26560,12 +26633,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_183.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_184.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_244.call('restyle', gd, prop, text, traceIndex); + _$registry_245.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_244.call('relayout', gd, prop, text); + _$registry_245.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -26574,7 +26647,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_183.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_184.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -26595,10 +26668,10 @@ function draw(gd, titleClass, options) { /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -var __FP_SAFE_203 = _$numerical_145.FP_SAFE; +/* removed: var _$lib_163 = require('../../lib'); */; +var __FP_SAFE_204 = _$numerical_145.FP_SAFE; -var _$autorange_203 = { +var _$autorange_204 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -26643,7 +26716,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_162.simpleMap(ax.range, ax.r2l); + var rng = _$lib_163.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -26736,7 +26809,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_162.simpleMap(newRange, ax.l2r || Number); + return _$lib_163.simpleMap(newRange, ax.l2r || Number); } /* @@ -26768,7 +26841,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_162.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_163.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -26790,7 +26863,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_162.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_163.extendFlat({}, axeRangeOpts); } } @@ -26803,6 +26876,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -26863,14 +26938,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_203) vmax = v; + if(v > vmax && v < __FP_SAFE_204) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_203) vmin = v; - if(v > vmax && v < __FP_SAFE_203) vmax = v; + if(v < vmin && v > -__FP_SAFE_204) vmin = v; + if(v > vmax && v < __FP_SAFE_204) vmax = v; } } @@ -26904,7 +26979,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_203 : __lessOrEqual_203; + var atLeastAsExtreme = k ? __greaterOrEqual_204 : __lessOrEqual_204; includeThis = true; /* @@ -26955,13 +27030,12 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_10(v) && Math.abs(v) < __FP_SAFE_203; + return _$fastIsnumeric_10(v) && Math.abs(v) < __FP_SAFE_204; } -function __lessOrEqual_203(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_203(v0, v1) { return v0 >= v1; } +function __lessOrEqual_204(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_204(v0, v1) { return v0 >= v1; } -var _$axes_204 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -26973,2784 +27047,2933 @@ var _$axes_204 = {}; 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$titles_136 = require('../../components/titles'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$drawing_68 = require('../../components/drawing'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +var __BADNUM_206 = _$numerical_145.BADNUM; -/* removed: var _$numerical_145 = require('../../constants/numerical'); */; -var ONEAVGYEAR = _$numerical_145.ONEAVGYEAR; -var ONEAVGMONTH = _$numerical_145.ONEAVGMONTH; -var __ONEDAY_204 = _$numerical_145.ONEDAY; -var __ONEHOUR_204 = _$numerical_145.ONEHOUR; -var __ONEMIN_204 = _$numerical_145.ONEMIN; -var __ONESEC_204 = _$numerical_145.ONESEC; -var MINUS_SIGN = _$numerical_145.MINUS_SIGN; -var __BADNUM_204 = _$numerical_145.BADNUM; +var _$autoType_206 = function autoType(array, calendar) { + if(moreDates(array, calendar)) return 'date'; + if(category(array)) return 'category'; + if(linearOK(array)) return 'linear'; + else return '-'; +}; -var MID_SHIFT = _$alignment_143.MID_SHIFT; -var __LINE_SPACING_204 = _$alignment_143.LINE_SPACING; +// is there at least one number in array? If not, we should leave +// ax.type empty so it can be autoset later +function linearOK(array) { + if(!array) return false; -var axes = _$axes_204 = {}; + for(var i = 0; i < array.length; i++) { + if(_$fastIsnumeric_10(array[i])) return true; + } -axes.setConvert = _$setConvert_223; -/* removed: var _$autoType_205 = require('./axis_autotype'); */; + return false; +} -/* removed: var _$axis_ids_207 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_207.id2name; -axes.name2id = _$axis_ids_207.name2id; -axes.cleanId = _$axis_ids_207.cleanId; -axes.list = _$axis_ids_207.list; -axes.listIds = _$axis_ids_207.listIds; -axes.getFromId = _$axis_ids_207.getFromId; -axes.getFromTrace = _$axis_ids_207.getFromTrace; +// does the array a have mostly dates rather than numbers? +// note: some values can be neither (such as blanks, text) +// 2- or 4-digit integers can be both, so require twice as many +// dates as non-dates, to exclude cases with mostly 2 & 4 digit +// numbers and a few dates +function moreDates(a, calendar) { + var dcnt = 0, + ncnt = 0, + // test at most 1000 points, evenly spaced + inc = Math.max(1, (a.length - 1) / 1000), + ai; -/* removed: var _$autorange_203 = require('./autorange'); */; -axes.expand = _$autorange_203.expand; -axes.getAutoRange = _$autorange_203.getAutoRange; + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_163.isDateTime(ai, calendar)) dcnt += 1; + if(_$fastIsnumeric_10(ai)) ncnt += 1; + } -/* - * 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 = {}; + return (dcnt > ncnt * 2); +} - if(!dflt) dflt = axlist[0] || extraOption; - if(!extraOption) extraOption = dflt; +// are the (x,y)-values in gd.data mostly text? +// require twice as many categories as numbers +function category(a) { + // test at most 1000 points + var inc = Math.max(1, (a.length - 1) / 1000), + curvenums = 0, + curvecats = 0, + ai; - // data-ref annotations are not supported in gl2d yet + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_163.cleanNumber(ai) !== __BADNUM_206) curvenums++; + else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; + } - attrDef[refAttr] = { - valType: 'enumerated', - values: axlist.concat(extraOption ? [extraOption] : []), - dflt: dflt - }; + return curvecats > curvenums * 2; +} - // xref, yref - return _$lib_162.coerce(containerIn, containerOut, attrDef, refAttr); -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * 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 + +'use strict'; + +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; + +/* removed: var _$lib_163 = require('../../lib'); */; +var cleanNumber = _$lib_163.cleanNumber; +var ms2DateTime = _$lib_163.ms2DateTime; +var dateTime2ms = _$lib_163.dateTime2ms; +var ensureNumber = _$lib_163.ensureNumber; + +/* removed: var _$numerical_145 = require('../../constants/numerical'); */; +var __FP_SAFE_223 = _$numerical_145.FP_SAFE; +var __BADNUM_223 = _$numerical_145.BADNUM; + +/* removed: var _$constants_210 = require('./constants'); */; +/* removed: var _$axis_ids_208 = require('./axis_ids'); */; + +function fromLog(v) { + return Math.pow(10, v); +} + +/** + * Define the conversion functions for an axis data is used in 5 ways: * - * 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 + * 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. * - * 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 + * Creates/updates these conversion functions, and a few more utilities + * like cleanRange, and makeCalcdata + * + * also clears the autorange bounds ._min and ._max + * and the autotick constraints ._minDtick, ._forceTick0 */ -axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { - var cleanPos, pos; +var _$setConvert_223 = function setConvert(ax, fullLayout) { + fullLayout = fullLayout || {}; - if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_162.ensureNumber; - pos = coerce(attr, dflt); - } else { - var ax = axes.getFromId(gd, axRef); - dflt = ax.fraction2r(dflt); - pos = coerce(attr, dflt); - cleanPos = ax.cleanPos; + var axLetter = (ax._id || 'x').charAt(0); + + // clipMult: how many axis lengths past the edge do we render? + // for panning, 1-2 would suffice, but for zooming more is nice. + // also, clipping can affect the direction of lines off the edge... + var clipMult = 10; + + 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 clipMult axis + // length past the negative edge + var r0 = ax.range[0], + r1 = ax.range[1]; + return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); + } + + else return __BADNUM_223; } - containerOut[attr] = cleanPos(pos); -}; + /* + * 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_223) { + if(_$fastIsnumeric_10(v)) ms = dateTime2ms(new Date(+v)); + else return __BADNUM_223; + } + return ms; + } -axes.cleanPosition = function(pos, gd, axRef) { - var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_162.ensureNumber : - axes.getFromId(gd, axRef).cleanPos; + // wrapped ms2DateTime to insert default ax.calendar + function ms2dt(v, r, calendar) { + return ms2DateTime(v, r, calendar || ax.calendar); + } - return cleanPos(pos); -}; + function getCategoryName(v) { + return ax._categories[Math.round(v)]; + } -var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { - var ax; + /* + * 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(v !== null && v !== undefined) { + if(ax._categoriesMap === undefined) { + ax._categoriesMap = {}; + } - // 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; + if(ax._categoriesMap[v] !== undefined) { + return ax._categoriesMap[v]; + } else { + ax._categories.push(v); - // 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_205(targetArray), - _categories: [] - }; - axes.setConvert(ax); + var curLength = ax._categories.length - 1; + ax._categoriesMap[v] = curLength; - // 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]); + return curLength; } } - } else { - ax = axes.getFromTrace(gd, trace, d2cTarget); + return __BADNUM_223; } - // 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}; + function getCategoryIndex(v) { + // d2l/d2c variant that that won't add categories but will also + // allow numbers to be mapped to the linearized axis positions + if(ax._categoriesMap) { + var index = ax._categoriesMap[v]; + if(index !== undefined) return index; + } - // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size') - // -> cast to Number + if(_$fastIsnumeric_10(v)) return +v; + } - return {d2c: toNum, c2d: toNum}; -}; + function l2p(v) { + if(!_$fastIsnumeric_10(v)) return __BADNUM_223; -function toNum(v) { return +v; } -function toString(v) { return String(v); } + // include 2 fractional digits on pixel, for PDF zooming etc + return _$d3_7.round(ax._b + ax._m * v, 2); + } -axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { - return getDataConversions(gd, trace, target, targetArray).d2c; -}; + function p2l(px) { return (px - ax._b) / ax._m; } -// 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'; -}; + // 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; -// 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'].indexOf(ax.type) !== -1 || !allow) { - ax._minDtick = 0; - } - // undefined means there's nothing there yet - else if(ax._minDtick === undefined) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - else if(ax._minDtick) { - // existing minDtick is an integer multiple of newDiff - // (within rounding err) - // and forceTick0 can be shifted to newFirst - if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && - (((newFirst - ax._forceTick0) / newDiff % 1) + - 1.000001) % 1 < 2e-6) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - // 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 - else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || - (((newFirst - ax._forceTick0) / ax._minDtick % 1) + - 1.000001) % 1 > 2e-6) { - ax._minDtick = 0; - } - } -}; + ax.l2p = l2p; + ax.p2l = p2l; -// 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), - hasOneAxisChanged = false; + 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; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + /* + * 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; - var isNew = (ax._rangeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.range[0] === ax._rangeInitial[0] && - ax.range[1] === ax._rangeInitial[1] - ) - ); + ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2d = ax.p2r = p2l; - if((isNew && ax.autorange === false) || (overwrite && hasChanged)) { - ax._rangeInitial = ax.range.slice(); - hasOneAxisChanged = true; - } + 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)); }; - return hasOneAxisChanged; -}; + ax.d2c = ax.r2l = cleanNumber; + ax.c2d = ax.l2r = ensureNumber; -// save a copy of the initial spike visibility -axes.saveShowSpikeInitial = function(gd, overwrite) { - var axList = axes.list(gd, '', true), - hasOneAxisChanged = false, - allSpikesEnabled = 'on'; + ax.c2r = toLog; + ax.l2d = fromLog; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); }; + ax.p2d = function(px) { return fromLog(p2l(px)); }; - var isNew = (ax._showSpikeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.showspikes === ax._showspikes - ) - ); + ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2r = p2l; - if((isNew) || (overwrite && hasChanged)) { - ax._showSpikeInitial = ax.showspikes; - hasOneAxisChanged = true; - } + ax.cleanPos = ensureNumber; + } + else if(ax.type === 'date') { + // r and d are date strings, l and c are ms - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } + /* + * 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_163.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_163.cleanDate(v, __BADNUM_223, ax.calendar); }; } - gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - return hasOneAxisChanged; -}; + else if(ax.type === 'category') { + // d is categories (string) + // c and l are indices (numbers) + // r is categories or numbers -axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_162.aggNums(Math.min, null, data), - dataMax = _$lib_162.aggNums(Math.max, null, data); + ax.d2c = ax.d2l = setCategoryIndex; + ax.r2d = ax.c2d = ax.l2d = getCategoryName; - if(!calendar) calendar = ax.calendar; + ax.d2r = ax.d2l_noadd = getCategoryIndex; - if(ax.type === 'category') { - return { - start: dataMin - 0.5, - end: dataMax + 0.5, - size: 1, - _dataSpan: dataMax - dataMin, + ax.r2c = function(v) { + var index = getCategoryIndex(v); + return index !== undefined ? index : ax.fraction2r(0.5); }; - } - 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_162.distinctVals(data), - msexp = Math.pow(10, Math.floor( - Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_162.roundUp( - distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_162.stdev(data) / - Math.pow(data.length, is2d ? 0.25 : 0.4)); + ax.l2r = ax.c2r = ensureNumber; + ax.r2l = getCategoryIndex; - // fallback if ax.d2c output BADNUMs - // e.g. when user try to plot categorical bins - // on a layout.xaxis.type: 'linear' - if(!_$fastIsnumeric_10(size0)) size0 = 1; - } + 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; - // piggyback off autotick code to make "nice" bin sizes - var dummyAx; - if(ax.type === 'log') { - dummyAx = { - type: 'linear', - range: [dataMin, dataMax] - }; - } - else { - dummyAx = { - type: ax.type, - range: _$lib_162.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), - calendar: calendar + ax.cleanPos = function(v) { + if(typeof v === 'string' && v !== '') return v; + return ensureNumber(v); }; } - axes.setConvert(dummyAx); - axes.autoTicks(dummyAx, size0); - var binStart = axes.tickIncrement( - axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); - var binEnd, bincount; + // find the range value at the specified (linear) fraction of the axis + ax.fraction2r = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return ax.l2r(rl0 + v * (rl1 - rl0)); + }; - // 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 dummyAx.dtick === 'number') { - binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + // find the fraction of the range at the specified range value + ax.r2fraction = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return (ax.r2l(v) - rl0) / (rl1 - rl0); + }; - bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); - binEnd = binStart + bincount * dummyAx.dtick; - } - 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, dummyAx.dtick, dataMin, calendar); + /* + * 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_163.nestedProperty(ax, rangeAttr).get(); + var i, dflt; + + if(ax.type === 'date') dflt = _$lib_163.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_210.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_210.DFLTRANGEX; + + // make sure we don't later mutate the defaults + dflt = dflt.slice(); + + if(!range || range.length !== 2) { + _$lib_163.nestedProperty(ax, rangeAttr).set(dflt); + return; } - // 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, dummyAx.dtick, false, calendar); - bincount++; + if(ax.type === 'date') { + // check if milliseconds or js date objects are provided for range + // and convert to date strings + range[0] = _$lib_163.cleanDate(range[0], __BADNUM_223, ax.calendar); + range[1] = _$lib_163.cleanDate(range[1], __BADNUM_223, ax.calendar); } - } - return { - start: ax.c2r(binStart, 0, calendar), - end: ax.c2r(binEnd, 0, calendar), - size: dummyAx.dtick, - _dataSpan: dataMax - dataMin - }; -}; + for(i = 0; i < 2; i++) { + if(ax.type === 'date') { + if(!_$lib_163.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_163.constrain(ax.r2l(range[0]), + _$lib_163.MIN_MS + 1000, _$lib_163.MAX_MS - 1000); + range[0] = ax.l2r(linCenter - 1000); + range[1] = ax.l2r(linCenter + 1000); + break; + } + } + else { + if(!_$fastIsnumeric_10(range[i])) { + if(_$fastIsnumeric_10(range[1 - i])) { + range[i] = range[1 - i] * (i ? 10 : 0.1); + } + else { + ax[rangeAttr] = dflt; + break; + } + } -function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { - var edgecount = 0, - midcount = 0, - intcount = 0, - blankCount = 0; + if(range[i] < -__FP_SAFE_223) range[i] = -__FP_SAFE_223; + else if(range[i] > __FP_SAFE_223) range[i] = __FP_SAFE_223; - function nearEdge(v) { - // is a value within 1% of a bin edge? - return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; - } + 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; + } + } + } + }; - for(var i = 0; i < data.length; i++) { - if(data[i] % 1 === 0) intcount++; - else if(!_$fastIsnumeric_10(data[i])) blankCount++; + // set scaling to pixels + ax.setScale = function(usePrivateRange) { + var gs = fullLayout._size; - if(nearEdge(data[i])) edgecount++; - if(nearEdge(data[i] + ax.dtick / 2)) midcount++; - } - var dataCount = data.length - blankCount; + // TODO cleaner way to handle this case + if(!ax._categories) ax._categories = []; + // Add a map to optimize the performance of category collection + if(!ax._categoriesMap) ax._categoriesMap = {}; - if(intcount === dataCount && ax.type !== 'date') { - // 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 - if(ax.dtick < 1) { - binStart = dataMin - 0.5 * ax.dtick; - } - // 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. - else { - 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; + // make sure we have a domain (pull it in from the axis + // this one is overlaying if necessary) + if(ax.overlaying) { + var ax2 = _$axis_ids_208.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + ax.domain = ax2.domain; } - } - return binStart; -} + // 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', + calendar = ax.calendar; + ax.cleanRange(rangeAttr); -function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_162.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)); + var rl0 = ax.r2l(ax[rangeAttr][0], calendar), + rl1 = ax.r2l(ax[rangeAttr][1], calendar); - 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_204 * 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_204 * 15.5; + 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 { - // 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_204 / 2; + 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; } - var nextBinStart = axes.tickIncrement(binStart, dtick); - if(nextBinStart <= dataMin) return nextBinStart; - } - return binStart; -} + if(!isFinite(ax._m) || !isFinite(ax._b)) { + fullLayout._replotting = false; + throw new Error('Something went wrong with axis scaling'); + } + }; -// ---------------------------------------------------- -// Ticks and grids -// ---------------------------------------------------- + // 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; -// ensure we have tick0, dtick, and tick rounding calculated -axes.prepTicks = function(ax) { - var rng = _$lib_162.simpleMap(ax.range, ax.r2l); + var axType = ax.type; + var cal = axType === 'date' && trace[axLetter + 'calendar']; - // calculate max number of (auto) ticks to display based on plot size - if(ax.tickmode === 'auto' || !ax.dtick) { - var nt = ax.nticks, - minPx; - if(!nt) { - if(ax.type === 'category') { - 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_162.constrain(ax._length / minPx, 4, 9) + 1; + if(axLetter in trace) { + arrayIn = trace[axLetter]; + len = trace._length || arrayIn.length; + + if(_$lib_163.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(len === arrayIn.length) { + return arrayIn; + } else if(arrayIn.subarray) { + return arrayIn.subarray(0, len); + } } - // radial axes span half their domain, - // multiply nticks value by two to get correct number of auto ticks. - if(ax._name === 'radialaxis') nt *= 2; + 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; - // add a couple of extra digits for filling in ticks when we - // have explicit tickvals without tick text - if(ax.tickmode === 'array') nt *= 100; + // 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); - 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); + for(i = 0; i < len; i++) { + arrayOut[i] = v0 + i * dv; + } } - } - // check for missing tick0 - if(!ax.tick0) { - ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; - } + return arrayOut; + }; - // now figure out rounding of tick values - autoTickRound(ax); -}; + ax.isValidRange = function(range) { + return ( + Array.isArray(range) && + range.length === 2 && + _$fastIsnumeric_10(ax.r2l(range[0])) && + _$fastIsnumeric_10(ax.r2l(range[1])) + ); + }; -// 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_162.simpleMap(ax.range, ax.r2l); + 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]); - // 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); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } + }; - // find the first tick - ax._tmin = axes.tickFirst(ax); + ax.clearCalc = function() { + // for autoranging: arrays of objects: + // { + // val: axis value, + // pad: pixel padding, + // extrapad: boolean, should this val get 5% additional padding + // } + ax._min = []; + ax._max = []; - // 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]); + // initialize the category list, if there is one, so we start over + // to be filled in later by ax.d2c + ax._categories = (ax._initialCategories || []).slice(); - // No visible ticks? Quit. - // I've only seen this on category axes with all categories off the edge. - if((ax._tmin < startTick) !== axrev) return []; + // Build the lookup map for initialized categories + ax._categoriesMap = {}; + for(var j = 0; j < ax._categories.length; j++) { + ax._categoriesMap[ax._categories[j]] = j; + } + }; - // return the full set of tick vals - var vals = []; - if(ax.type === 'category') { - endTick = (axrev) ? Math.max(-0.5, endTick) : - Math.min(ax._categories.length - 0.5, endTick); + // 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_7.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_7.format; - 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(vals.length > maxTicks || x === xPrevious) break; - xPrevious = x; + // and for bar charts and box plots: reset forced minimum tick spacing + delete ax._minDtick; + delete ax._forceTick0; +}; - vals.push(x); - } +var _$axes_205 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // If same angle over a full circle, the last tick vals is a duplicate. - // TODO must do something similar for angular date axes. - if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { - vals.pop(); - } - // save the last tick as well as first, so we can - // show the exponent only on the last one - ax._tmax = vals[vals.length - 1]; +'use strict'; - // 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; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; - var ticksOut = new Array(vals.length); - for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$titles_136 = require('../../components/titles'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$drawing_68 = require('../../components/drawing'); */; - ax._inCalcTicks = false; +/* removed: var _$numerical_145 = require('../../constants/numerical'); */; +var ONEAVGYEAR = _$numerical_145.ONEAVGYEAR; +var ONEAVGMONTH = _$numerical_145.ONEAVGMONTH; +var __ONEDAY_205 = _$numerical_145.ONEDAY; +var __ONEHOUR_205 = _$numerical_145.ONEHOUR; +var __ONEMIN_205 = _$numerical_145.ONEMIN; +var __ONESEC_205 = _$numerical_145.ONESEC; +var MINUS_SIGN = _$numerical_145.MINUS_SIGN; +var __BADNUM_205 = _$numerical_145.BADNUM; - return ticksOut; -}; +var MID_SHIFT = _$alignment_143.MID_SHIFT; +var __LINE_SPACING_205 = _$alignment_143.LINE_SPACING; -function arrayTicks(ax) { - var vals = ax.tickvals, - text = ax.ticktext, - ticksOut = new Array(vals.length), - rng = _$lib_162.simpleMap(ax.range, ax.r2l), - r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, - r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, - tickMin = Math.min(r0expanded, r1expanded), - tickMax = Math.max(r0expanded, r1expanded), - vali, - i, - j = 0; +var axes = _$axes_205 = {}; - // 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 = []; +axes.setConvert = _$setConvert_223; +/* removed: var _$autoType_206 = require('./axis_autotype'); */; - // make sure showing ticks doesn't accidentally add new categories - var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; +/* removed: var _$axis_ids_208 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_208.id2name; +axes.name2id = _$axis_ids_208.name2id; +axes.cleanId = _$axis_ids_208.cleanId; +axes.list = _$axis_ids_208.list; +axes.listIds = _$axis_ids_208.listIds; +axes.getFromId = _$axis_ids_208.getFromId; +axes.getFromTrace = _$axis_ids_208.getFromTrace; - // 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); - } +/* removed: var _$autorange_204 = require('./autorange'); */; +axes.expand = _$autorange_204.expand; +axes.getAutoRange = _$autorange_204.getAutoRange; - for(i = 0; i < vals.length; i++) { - 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++; - } - } +/* + * 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(j < vals.length) ticksOut.splice(j, vals.length - j); + if(!dflt) dflt = axlist[0] || extraOption; + if(!extraOption) extraOption = dflt; - return ticksOut; -} + // data-ref annotations are not supported in gl2d yet -var roundBase10 = [2, 5, 10], - roundBase24 = [1, 2, 3, 6, 12], - roundBase60 = [1, 2, 5, 10, 15, 30], - // 2&3 day ticks are weird, but need something btwn 1&7 - 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 - roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], - roundLog2 = [-0.301, 0, 0.301, 0.699, 1], - // N.B. `thetaunit; 'radians' angular axes must be converted to degrees - roundAngles = [15, 30, 45, 90, 180]; + attrDef[refAttr] = { + valType: 'enumerated', + values: axlist.concat(extraOption ? [extraOption] : []), + dflt: dflt + }; -function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_162.roundUp(roughDTick / base, roundingSet); -} + // xref, yref + return _$lib_163.coerce(containerIn, containerOut, attrDef, refAttr); +}; -// 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; +/* + * 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; - function getBase(v) { - return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); + if(axRef === 'paper' || axRef === 'pixel') { + cleanPos = _$lib_163.ensureNumber; + pos = coerce(attr, dflt); + } else { + var ax = axes.getFromId(gd, axRef); + dflt = ax.fraction2r(dflt); + pos = coerce(attr, dflt); + cleanPos = ax.cleanPos; } - if(ax.type === 'date') { - ax.tick0 = _$lib_162.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; + containerOut[attr] = cleanPos(pos); +}; - 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_204) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_204, 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_162.dateTick0(ax.calendar, true); - } - else if(roughX2 > __ONEHOUR_204) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_204, roundBase24); - } - else if(roughX2 > __ONEMIN_204) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_204, roundBase60); - } - else if(roughX2 > __ONESEC_204) { - ax.dtick = roundDTick(roughDTick, __ONESEC_204, roundBase60); - } - else { - // milliseconds - base = getBase(10); - ax.dtick = roundDTick(roughDTick, base, roundBase10); - } - } - else if(ax.type === 'log') { - ax.tick0 = 0; - var rng = _$lib_162.simpleMap(ax.range, ax.r2l); +axes.cleanPosition = function(pos, gd, axRef) { + var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? + _$lib_163.ensureNumber : + axes.getFromId(gd, axRef).cleanPos; - 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); + return cleanPos(pos); +}; - // 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'; +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_206(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]); + } } - } - else if(ax.type === 'category') { - ax.tick0 = 0; - ax.dtick = Math.ceil(Math.max(roughDTick, 1)); - } - else if(ax._id === 'angular') { - 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); + } else { + ax = axes.getFromTrace(gd, trace, d2cTarget); } - // prevent infinite loops - if(ax.dtick === 0) ax.dtick = 1; + // if 'target' has corresponding axis + // -> use setConvert method + if(ax) return {d2c: ax.d2c, c2d: ax.c2d}; - // TODO: this is from log axis histograms with autorange off - if(!_$fastIsnumeric_10(ax.dtick) && typeof ax.dtick !== 'string') { - var olddtick = ax.dtick; - ax.dtick = 1; - throw 'ax.dtick error: ' + String(olddtick); - } + // 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}; }; -// 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; +function toNum(v) { return +v; } +function toString(v) { return String(v); } - ax._tickexponent = 0; - if(!_$fastIsnumeric_10(dtick) && typeof dtick !== 'string') { - dtick = 1; - } +axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { + return getDataConversions(gd, trace, target, targetArray).d2c; +}; - if(ax.type === 'category') { - 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), - tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), - tick0len = tick0str.length; +// 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'; +}; - 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'; +// 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'].indexOf(ax.type) !== -1 || !allow) { + ax._minDtick = 0; + } + // undefined means there's nothing there yet + else if(ax._minDtick === undefined) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } + else if(ax._minDtick) { + // existing minDtick is an integer multiple of newDiff + // (within rounding err) + // and forceTick0 can be shifted to newFirst + if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && + (((newFirst - ax._forceTick0) / newDiff % 1) + + 1.000001) % 1 < 2e-6) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; } - else if((dtick >= __ONEDAY_204 && tick0len <= 10) || (dtick >= __ONEDAY_204 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_204 && tick0len <= 16) || (dtick >= __ONEHOUR_204)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_204 && tick0len <= 19) || (dtick >= __ONEMIN_204)) 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; + // 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 + else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || + (((newFirst - ax._forceTick0) / ax._minDtick % 1) + + 1.000001) % 1 > 2e-6) { + ax._minDtick = 0; } } - else if(_$fastIsnumeric_10(dtick) || dtick.charAt(0) === 'L') { - // linear or log (except D1, D2) - var rng = ax.range.map(ax.r2d || Number); - if(!_$fastIsnumeric_10(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])); +// 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), + hasOneAxisChanged = false; - 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; + 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; } } - // D1 or D2 (log) - else 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(_$fastIsnumeric_10(dtick)) return x + axSign * dtick; + return hasOneAxisChanged; +}; - // everything else is a string, one character plus a number - var tType = dtick.charAt(0), - dtSigned = axSign * Number(dtick.substr(1)); +// save a copy of the initial spike visibility +axes.saveShowSpikeInitial = function(gd, overwrite) { + var axList = axes.list(gd, '', true), + hasOneAxisChanged = false, + allSpikesEnabled = 'on'; - // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_162.incrementMonth(x, dtSigned, calendar); + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; - // Log scales: Linear, Digits - else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; + var isNew = (ax._showSpikeInitial === undefined); + var hasChanged = ( + isNew || !( + ax.showspikes === ax._showspikes + ) + ); - // 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, - x2 = x + axSign * 0.01, - frac = _$lib_162.roundUp(_$lib_162.mod(x2, 1), tickset, axrev); + if((isNew) || (overwrite && hasChanged)) { + ax._showSpikeInitial = ax.showspikes; + hasOneAxisChanged = true; + } - return Math.floor(x2) + - Math.log(_$d3_7.round(Math.pow(10, frac), 1)) / Math.LN10; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } - else throw 'unrecognized dtick ' + String(dtick); + gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + return hasOneAxisChanged; }; -// calculate the first tick on an axis -axes.tickFirst = function(ax) { - var r2l = ax.r2l || Number, - rng = _$lib_162.simpleMap(ax.range, r2l), - axrev = rng[1] < rng[0], - sRound = axrev ? Math.floor : Math.ceil, - // add a tiny extra bit to make sure we get ticks - // that may have been rounded out - r0 = rng[0] * 1.0001 - rng[1] * 0.0001, - dtick = ax.dtick, - tick0 = r2l(ax.tick0); +axes.autoBin = function(data, ax, nbins, is2d, calendar) { + var dataMin = _$lib_163.aggNums(Math.min, null, data), + dataMax = _$lib_163.aggNums(Math.max, null, data); - if(_$fastIsnumeric_10(dtick)) { - var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; + if(!calendar) calendar = ax.calendar; - // make sure no ticks outside the category list - if(ax.type === 'category') { - tmin = _$lib_162.constrain(tmin, 0, ax._categories.length - 1); - } - return tmin; + if(ax.type === 'category') { + return { + start: dataMin - 0.5, + end: dataMax + 0.5, + size: 1, + _dataSpan: dataMax - dataMin, + }; } - var tType = dtick.charAt(0), - dtNum = Number(dtick.substr(1)); - - // Dates: months (or years) - if(tType === 'M') { - var cnt = 0, - t0 = tick0, - t1, - mult, - newDTick; + 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_163.distinctVals(data), + msexp = Math.pow(10, Math.floor( + Math.log(distinctData.minDiff) / Math.LN10)), + minSize = msexp * _$lib_163.roundUp( + distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); + size0 = Math.max(minSize, 2 * _$lib_163.stdev(data) / + Math.pow(data.length, is2d ? 0.25 : 0.4)); - // 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_162.error('tickFirst did not converge', ax); - return t0; + // fallback if ax.d2c output BADNUMs + // e.g. when user try to plot categorical bins + // on a layout.xaxis.type: 'linear' + if(!_$fastIsnumeric_10(size0)) size0 = 1; } - // Log scales: Linear, Digits - else if(tType === 'L') { - return Math.log(sRound( - (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + // piggyback off autotick code to make "nice" bin sizes + var dummyAx; + if(ax.type === 'log') { + dummyAx = { + type: 'linear', + range: [dataMin, dataMax] + }; } - else if(tType === 'D') { - var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_162.roundUp(_$lib_162.mod(r0, 1), tickset, axrev); - - return Math.floor(r0) + - Math.log(_$d3_7.round(Math.pow(10, frac), 1)) / Math.LN10; + else { + dummyAx = { + type: ax.type, + range: _$lib_163.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + calendar: calendar + }; } - else throw 'unrecognized dtick ' + String(dtick); -}; + axes.setConvert(dummyAx); -// 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) { - var out = tickTextObj(ax, x), - hideexp, - arrayMode = ax.tickmode === 'array', - extraPrecision = hover || arrayMode, - i, - tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; + axes.autoTicks(dummyAx, size0); + var binStart = axes.tickIncrement( + axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); + var binEnd, bincount; - if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_162.simpleMap(ax.range, ax.r2l), - 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; + // 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 dummyAx.dtick === 'number') { + binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + + bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); + binEnd = binStart + bincount * dummyAx.dtick; + } + 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, dummyAx.dtick, dataMin, calendar); } - if(i < ax.ticktext.length) { - out.text = String(ax.ticktext[i]); - return out; + + // 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, dummyAx.dtick, false, calendar); + bincount++; } } - function isHidden(showAttr) { - var first_or_last; - - if(showAttr === undefined) return true; - if(hover) return showAttr === 'none'; + return { + start: ax.c2r(binStart, 0, calendar), + end: ax.c2r(binEnd, 0, calendar), + size: dummyAx.dtick, + _dataSpan: dataMax - dataMin + }; +}; - first_or_last = { - first: ax._tmin, - last: ax._tmax - }[showAttr]; - return showAttr !== 'all' && x !== first_or_last; - } +function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { + var edgecount = 0, + midcount = 0, + intcount = 0, + blankCount = 0; - if(hover) { - hideexp = 'never'; - } else { - hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; + function nearEdge(v) { + // is a value within 1% of a bin edge? + return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; } - if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); - else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); - else if(ax.type === 'category') formatCategory(ax, out); - else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); - else formatLinear(ax, out, hover, extraPrecision, hideexp); - - // add prefix and suffix - if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; - if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; + for(var i = 0; i < data.length; i++) { + if(data[i] % 1 === 0) intcount++; + else if(!_$fastIsnumeric_10(data[i])) blankCount++; - return out; -}; + if(nearEdge(data[i])) edgecount++; + if(nearEdge(data[i] + ax.dtick / 2)) midcount++; + } + var dataCount = data.length - blankCount; -/** - * 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_204 && val2 !== val) { - return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); + if(intcount === dataCount && ax.type !== 'date') { + // 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 + if(ax.dtick < 1) { + binStart = dataMin - 0.5 * ax.dtick; + } + // 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. + else { + binStart -= 0.5; + if(binStart + ax.dtick < dataMin) binStart += ax.dtick; + } } - - 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; + 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; +} - // 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 || {}; +function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { + var stats = _$lib_163.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; - return { - x: x, - dx: 0, - dy: 0, - text: text || '', - fontSize: tf.size, - font: tf.family, - fontColor: tf.color - }; -} + if(stats.exactDays > threshold) { + var numMonths = Number(dtick.substr(1)); -function formatDate(ax, out, hover, extraPrecision) { - var tr = ax._tickround, - fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); + 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_205 * 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_205 * 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_205 / 2; + } + var nextBinStart = axes.tickIncrement(binStart, dtick); - if(extraPrecision) { - // second or sub-second precision: extra always shows max digits. - // for other fields, extra precision just adds one field. - if(_$fastIsnumeric_10(tr)) tr = 4; - else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + if(nextBinStart <= dataMin) return nextBinStart; } + return binStart; +} - var dateStr = _$lib_162.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), - headStr; +// ---------------------------------------------------- +// Ticks and grids +// ---------------------------------------------------- - var splitIndex = dateStr.indexOf('\n'); - if(splitIndex !== -1) { - headStr = dateStr.substr(splitIndex + 1); - dateStr = dateStr.substr(0, splitIndex); - } +// ensure we have tick0, dtick, and tick rounding calculated +axes.prepTicks = function(ax) { + var rng = _$lib_163.simpleMap(ax.range, ax.r2l); - 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!) + // calculate max number of (auto) ticks to display based on plot size + if(ax.tickmode === 'auto' || !ax.dtick) { + var nt = ax.nticks, + minPx; + if(!nt) { + if(ax.type === 'category') { + 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_163.constrain(ax._length / minPx, 4, 9) + 1; + } - // can we remove the whole time part? - if(dateStr === '00:00:00' || dateStr === '00:00') { - dateStr = headStr; - headStr = ''; + // radial axes span half their domain, + // multiply nticks value by two to get correct number of auto ticks. + if(ax._name === 'radialaxis') nt *= 2; } - 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$/, ''); + + // 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); } } - 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; - } + // check for missing tick0 + if(!ax.tick0) { + ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; } - out.text = dateStr; -} + // now figure out rounding of tick values + autoTickRound(ax); +}; -function formatLog(ax, out, hover, extraPrecision, hideexp) { - var dtick = ax.dtick, - x = out.x, - tickformat = ax.tickformat; +// 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_163.simpleMap(ax.range, ax.r2l); - 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 = ''; - } + // 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); - if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; + // find the first tick + ax._tmin = axes.tickFirst(ax); - if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { - out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); - } - else if(_$fastIsnumeric_10(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_162.mod(x + 0.01, 1) < 0.1))) { - var p = Math.round(x); - if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || - (isSIFormat(ax.exponentformat) && beyondSI(p))) { - if(p === 0) out.text = 1; - else if(p === 1) out.text = '10'; - else if(p > 1) out.text = '10' + p + ''; - else out.text = '10' + MINUS_SIGN + -p + ''; + // 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]); - out.fontSize *= 1.25; - } - else { - out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover'); - if(dtick === 'D1' && ax._id.charAt(0) === 'y') { - out.dy -= out.fontSize / 6; - } - } + // 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 vals = []; + if(ax.type === 'category') { + endTick = (axrev) ? Math.max(-0.5, endTick) : + Math.min(ax._categories.length - 0.5, endTick); } - else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_162.mod(x, 1)))); - out.fontSize *= 0.75; + + 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(vals.length > maxTicks || x === xPrevious) break; + xPrevious = x; + + vals.push(x); } - 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); - } - } + // If same angle over a full circle, the last tick vals is a duplicate. + // TODO must do something similar for angular date axes. + if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { + vals.pop(); } -} -function formatCategory(ax, out) { - var tt = ax._categories[Math.round(out.x)]; - if(tt === undefined) tt = ''; - out.text = String(tt); -} + // save the last tick as well as first, so we can + // show the exponent only on the last one + ax._tmax = vals[vals.length - 1]; -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); -} + // 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; -function formatAngle(ax, out, hover, extraPrecision, hideexp) { - if(ax.thetaunit === 'radians' && !hover) { - var num = out.x / 180; + var ticksOut = new Array(vals.length); + for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); - if(num === 0) { - out.text = '0'; - } else { - var frac = num2frac(num); + ax._inCalcTicks = false; - if(frac[1] >= 100) { - out.text = numFormat(_$lib_162.deg2rad(out.x), ax, hideexp, extraPrecision); - } else { - var isNeg = out.x < 0; + return ticksOut; +}; - if(frac[1] === 1) { - if(frac[0] === 1) out.text = 'π'; - else out.text = frac[0] + 'π'; - } else { - out.text = [ - '', frac[0], '', - '⁄', - '', frac[1], '', - 'π' - ].join(''); - } +function arrayTicks(ax) { + var vals = ax.tickvals, + text = ax.ticktext, + ticksOut = new Array(vals.length), + rng = _$lib_163.simpleMap(ax.range, ax.r2l), + r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, + r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, + tickMin = Math.min(r0expanded, r1expanded), + tickMax = Math.max(r0expanded, r1expanded), + vali, + i, + j = 0; - if(isNeg) out.text = MINUS_SIGN + out.text; - } - } - } else { - out.text = numFormat(out.x, ax, hideexp, extraPrecision); - } -} + // 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 = []; -// 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; - } + // make sure showing ticks doesn't accidentally add new categories + var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - function findGCD(a, b) { - return almostEq(b, 0) ? a : findGCD(b, a % b); + // 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); } - function findPrecision(n) { - var e = 1; - while(!almostEq(Math.round(n * e) / e, n)) { - e *= 10; + for(i = 0; i < vals.length; i++) { + 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++; } - return e; } - var precision = findPrecision(num); - var number = num * precision; - var gcd = Math.abs(findGCD(number, precision)); + if(j < vals.length) ticksOut.splice(j, vals.length - j); - return [ - // numerator - Math.round(number / gcd), - // denominator - Math.round(precision / gcd) - ]; + return ticksOut; } -// 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'; -} +var roundBase10 = [2, 5, 10], + roundBase24 = [1, 2, 3, 6, 12], + roundBase60 = [1, 2, 5, 10, 15, 30], + // 2&3 day ticks are weird, but need something btwn 1&7 + 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 + roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], + roundLog2 = [-0.301, 0, 0.301, 0.699, 1], + // N.B. `thetaunit; 'radians' angular axes must be converted to degrees + roundAngles = [15, 30, 45, 90, 180]; -// 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 roundDTick(roughDTick, base, roundingSet) { + return base * _$lib_163.roundUp(roughDTick / base, roundingSet); } -function numFormat(v, ax, fmtoverride, hover) { - // negative? - var isNeg = v < 0, - // max number of digits past decimal point to show - tickRound = ax._tickround, - exponentFormat = fmtoverride || ax.exponentformat || 'B', - exponent = ax._tickexponent, - tickformat = axes.getTickFormat(ax), - separatethousands = ax.separatethousands; +// 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; - // 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 : - (_$fastIsnumeric_10(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; + function getBase(v) { + return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); } - 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; + if(ax.type === 'date') { + ax.tick0 = _$lib_163.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; - // 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; + if(roughX2 > ONEAVGYEAR) { + roughDTick /= ONEAVGYEAR; + base = getBase(10); + ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10)); } - // 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 if(roughX2 > ONEAVGMONTH) { + roughDTick /= ONEAVGMONTH; + ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); + } + else if(roughX2 > __ONEDAY_205) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_205, 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_163.dateTick0(ax.calendar, true); + } + else if(roughX2 > __ONEHOUR_205) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_205, roundBase24); + } + else if(roughX2 > __ONEMIN_205) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_205, roundBase60); + } + else if(roughX2 > __ONESEC_205) { + ax.dtick = roundDTick(roughDTick, __ONESEC_205, roundBase60); } else { - v = String(v); - var dp = v.indexOf('.') + 1; - if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); + // milliseconds + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); } - // insert appropriate decimal point and thousands separator - v = _$lib_162.numSeparate(v, ax._separators, separatethousands); } + else if(ax.type === 'log') { + ax.tick0 = 0; + var rng = _$lib_163.simpleMap(ax.range, ax.r2l); - // add exponent - if(exponent && exponentFormat !== 'hide') { - if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; + 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); - var signedExponent; - if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; - else if(exponentFormat !== 'power') signedExponent = '+' + exponent; - else signedExponent = String(exponent); - - if(exponentFormat === 'e') { - v += 'e' + signedExponent; - } - else if(exponentFormat === 'E') { - v += 'E' + signedExponent; - } - else if(exponentFormat === 'power') { - v += '×10' + signedExponent + ''; - } - else if(exponentFormat === 'B' && exponent === 9) { - v += 'B'; + // 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 if(isSIFormat(exponentFormat)) { - v += SIPREFIXES[exponent / 3 + 5]; + 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.tick0 = 0; + ax.dtick = Math.ceil(Math.max(roughDTick, 1)); + } + else if(ax._id === 'angular') { + 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); + } - // 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; + // prevent infinite loops + if(ax.dtick === 0) ax.dtick = 1; - function convertToMs(dtick) { - return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH; + // TODO: this is from log axis histograms with autorange off + if(!_$fastIsnumeric_10(ax.dtick) && typeof ax.dtick !== 'string') { + var olddtick = ax.dtick; + ax.dtick = 1; + throw 'ax.dtick error: ' + String(olddtick); } +}; - 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; - } +// 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(!_$fastIsnumeric_10(dtick) && typeof dtick !== 'string') { + dtick = 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)); + if(ax.type === 'category') { + 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), + tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), + tick0len = tick0str.length; - 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); + 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_205 && tick0len <= 10) || (dtick >= __ONEDAY_205 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_205 && tick0len <= 16) || (dtick >= __ONEHOUR_205)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_205 && tick0len <= 19) || (dtick >= __ONEMIN_205)) 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; + } } + else if(_$fastIsnumeric_10(dtick) || dtick.charAt(0) === 'L') { + // linear or log (except D1, D2) + var rng = ax.range.map(ax.r2d || Number); + if(!_$fastIsnumeric_10(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 tickstop; - if(ax.tickformatstops && ax.tickformatstops.length > 0) { - switch(ax.type) { - case 'date': - case 'linear': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; - } - case 'log': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; + 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); } - default: + else ax._tickexponent = rangeexp; } } - return tickstop ? tickstop.value : ax.tickformat; -}; + // D1 or D2 (log) + else ax._tickround = null; +} -// 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 -axes.getSubplots = function(gd, ax) { - var subplotObj = gd._fullLayout._subplots; - var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); +// 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; - var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; + // includes linear, all dates smaller than month, and pure 10^n in log + if(_$fastIsnumeric_10(dtick)) return x + axSign * dtick; - out.sort(function(a, b) { - var aParts = a.substr(1).split('y'); - var bParts = b.substr(1).split('y'); + // everything else is a string, one character plus a number + var tType = dtick.charAt(0), + dtSigned = axSign * Number(dtick.substr(1)); - if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; - return +aParts[0] - +bParts[0]; - }); + // Dates: months (or years - see Lib.incrementMonth) + if(tType === 'M') return _$lib_163.incrementMonth(x, dtSigned, calendar); - return out; -}; + // Log scales: Linear, Digits + else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; -// find all subplots with axis 'ax' -axes.findSubplotsWithAxis = function(subplots, ax) { - var axMatch = new RegExp( - (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') - ); - var subplotsWithAxis = []; + // 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, + x2 = x + axSign * 0.01, + frac = _$lib_163.roundUp(_$lib_163.mod(x2, 1), tickset, axrev); - for(var i = 0; i < subplots.length; i++) { - var sp = subplots[i]; - if(axMatch.test(sp)) subplotsWithAxis.push(sp); + return Math.floor(x2) + + Math.log(_$d3_7.round(Math.pow(10, frac), 1)) / Math.LN10; } - - return subplotsWithAxis; + else throw 'unrecognized dtick ' + String(dtick); }; -// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings -axes.makeClipPaths = function(gd) { - var fullLayout = gd._fullLayout; - 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; +// calculate the first tick on an axis +axes.tickFirst = function(ax) { + var r2l = ax.r2l || Number, + rng = _$lib_163.simpleMap(ax.range, r2l), + axrev = rng[1] < rng[0], + sRound = axrev ? Math.floor : Math.ceil, + // add a tiny extra bit to make sure we get ticks + // that may have been rounded out + r0 = rng[0] * 1.0001 - rng[1] * 0.0001, + dtick = ax.dtick, + tick0 = r2l(ax.tick0); - 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]}); + if(_$fastIsnumeric_10(dtick)) { + var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; + + // make sure no ticks outside the category list + if(ax.type === 'category') { + tmin = _$lib_163.constrain(tmin, 0, ax._categories.length - 1); } + return tmin; } - // 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'); + var tType = dtick.charAt(0), + dtNum = Number(dtick.substr(1)); - axClips.exit().remove(); + // Dates: months (or years) + if(tType === 'M') { + var cnt = 0, + t0 = tick0, + t1, + mult, + newDTick; - axClips.each(function(d) { - _$d3_7.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 - }); - }); -}; + // 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_163.error('tickFirst did not converge', ax); + return t0; + } -// doTicks: draw ticks, grids, and tick labels -// axid: 'x', 'y', 'x2' etc, -// blank to do all, -// 'redraw' to force full redraw, and reset: -// ax._r (stored range for use by zoom/pan) -// ax._rl (stored linearized range for use by zoom/pan) -// or can pass in an axis object directly -axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + // Log scales: Linear, Digits + else if(tType === 'L') { + return Math.log(sRound( + (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + } + else if(tType === 'D') { + var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, + frac = _$lib_163.roundUp(_$lib_163.mod(r0, 1), tickset, axrev); - // allow passing an independent axis object instead of id - if(typeof axid === 'object') { - ax = axid; - axid = ax._id; - independent = true; + return Math.floor(r0) + + Math.log(_$d3_7.round(Math.pow(10, frac), 1)) / Math.LN10; } - else { - ax = axes.getFromId(gd, axid); + else throw 'unrecognized dtick ' + String(dtick); +}; - if(axid === 'redraw') { - fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); - fullLayout._infolayer.select('.g-' + xa._id + 'title').remove(); - fullLayout._infolayer.select('.g-' + ya._id + 'title').remove(); - }); - } +// 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) { + var out = tickTextObj(ax, x), + hideexp, + arrayMode = ax.tickmode === 'array', + extraPrecision = hover || arrayMode, + i, + tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - if(!axid || axid === 'redraw') { - return _$lib_162.syncOrAsync(axes.list(gd, '', true).map(function(ax) { - return function() { - if(!ax._id) return; - var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_162.simpleMap(ax._r, ax.r2l); - } - return axDone; - }; - })); + if(arrayMode && Array.isArray(ax.ticktext)) { + var rng = _$lib_163.simpleMap(ax.range, ax.r2l), + 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; } } - // set scaling to pixels - ax.setScale(); + function isHidden(showAttr) { + var first_or_last; - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_68.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_68.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_68.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + if(showAttr === undefined) return true; + if(hover) return showAttr === 'none'; - if(ax._counterangle && ax.ticks === 'outside') { - var caRad = ax._counterangle * Math.PI / 180; - labelStandoff = ax.ticklen * Math.cos(caRad) + 1; - labelShift = ax.ticklen * Math.sin(caRad); - } + first_or_last = { + first: ax._tmin, + last: ax._tmax + }[showAttr]; - if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { - labelStandoff += 0.2 * ax.tickfont.size; + return showAttr !== 'all' && x !== first_or_last; } - // positioning arguments for x vs y axes - if(axLetter === 'x') { - sides = ['bottom', 'top']; - transfn = ax._transfn || function(d) { - return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); - } - else return 'M0,' + shift + 'v' + len; - }; - } - else if(axLetter === 'y') { - sides = ['left', 'right']; - transfn = ax._transfn || function(d) { - return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); - } - else return 'M' + shift + ',0h' + len; - }; - } - else if(axid === 'angular') { - sides = ['left', 'right']; - transfn = ax._transfn; - tickpathfn = function(shift, len) { - return 'M' + shift + ',0h' + len; - }; - } - else { - _$lib_162.warn('Unrecognized doTicks axis:', axid); - return; - } - var axside = ax.side || sides[0], - // which direction do the side[0], side[1], and free ticks go? - // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; - if((ax.ticks !== 'inside') === (axLetter === 'x')) { - ticksign = ticksign.map(function(v) { return -v; }); + if(hover) { + hideexp = 'never'; + } else { + hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; } - if(!ax.visible) return; + if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); + else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); + else if(ax.type === 'category') formatCategory(ax, out); + else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); + else formatLinear(ax, out, hover, extraPrecision, hideexp); - if(ax._tickFilter) { - vals = vals.filter(ax._tickFilter); - } + // add prefix and suffix + if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; + if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; - // remove zero lines, grid lines, and inside ticks if they're within - // 1 pixel of the end - // The key case here is removing zero lines when the axis bound is zero. - function clipEnds(d) { - var p = ax.l2p(d.x); - return (p > 1 && p < ax._length - 1); - } - var valsClipped = vals.filter(clipEnds); + return out; +}; - // don't clip angular values - if(ax._id === 'angular') { - valsClipped = vals; +/** + * 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_205 && val2 !== val) { + return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } - function drawTicks(container, tickpath) { - var ticks = container.selectAll('path.' + tcls) - .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); - if(tickpath && ax.ticks) { - ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) - .classed('crisp', 1) - .call(_$color_43.stroke, ax.tickcolor) - .style('stroke-width', tickWidth + 'px') - .attr('d', tickpath); - ticks.attr('transform', transfn); - ticks.exit().remove(); - } - else ticks.remove(); + 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; } - function drawLabels(container, position) { - // tick labels - for now just the main labels. - // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + // 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; +}; - if(!_$fastIsnumeric_10(position)) { - tickLabels.remove(); - drawAxTitle(); - return; - } - if(!ax.showticklabels) { - tickLabels.remove(); - drawAxTitle(); - calcBoundingBox(); - return; - } +function tickTextObj(ax, x, text) { + var tf = ax.tickfont || {}; - var labelx, labely, labelanchor, labelpos0, flipit; - if(axLetter === 'x') { - flipit = (axside === 'bottom') ? 1 : -1; - labelx = function(d) { return d.dx + labelShift * flipit; }; - labelpos0 = position + (labelStandoff + pad) * flipit; - labely = function(d) { - return d.dy + labelpos0 + d.fontSize * - ((axside === 'bottom') ? 1 : -0.2); - }; - labelanchor = function(angle) { - if(!_$fastIsnumeric_10(angle) || angle === 0 || angle === 180) { - return 'middle'; - } - return (angle * flipit < 0) ? 'end' : 'start'; - }; - } - else if(axLetter === 'y') { - flipit = (axside === 'right') ? 1 : -1; - labely = function(d) { - return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; - }; - labelx = function(d) { - return d.dx + position + (labelStandoff + pad + - ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; - }; - labelanchor = function(angle) { - if(_$fastIsnumeric_10(angle) && Math.abs(angle) === 90) { - return 'middle'; - } - return axside === 'right' ? 'start' : 'end'; - }; - } - else if(axid === 'angular') { - ax._labelShift = labelShift; - ax._labelStandoff = labelStandoff; - ax._pad = pad; + return { + x: x, + dx: 0, + dy: 0, + text: text || '', + fontSize: tf.size, + font: tf.family, + fontColor: tf.color + }; +} - labelx = ax._labelx; - labely = ax._labely; - labelanchor = ax._labelanchor; - } +function formatDate(ax, out, hover, extraPrecision) { + var tr = ax._tickround, + fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); - var maxFontSize = 0, - autoangle = 0, - labelsReady = []; - tickLabels.enter().append('g').classed(tcls, 1) - .append('text') - // only so tex has predictable alignment that we can - // alter later - .attr('text-anchor', 'middle') - .each(function(d) { - var thisLabel = _$d3_7.select(this), - newPromise = gd._promises.length; - thisLabel - .call(_$svg_text_utils_183.positionText, labelx(d), labely(d)) - .call(_$drawing_68.font, d.font, d.fontSize, d.fontColor) - .text(d.text) - .call(_$svg_text_utils_183.convertToTspans, gd); - newPromise = gd._promises[newPromise]; - if(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, ax.tickangle); - })); - } - else { - // sync label: just position it now. - positionLabels(thisLabel, ax.tickangle); - } - }); - tickLabels.exit().remove(); + if(extraPrecision) { + // second or sub-second precision: extra always shows max digits. + // for other fields, extra precision just adds one field. + if(_$fastIsnumeric_10(tr)) tr = 4; + else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + } - tickLabels.each(function(d) { - maxFontSize = Math.max(maxFontSize, d.fontSize); - }); + var dateStr = _$lib_163.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + headStr; - if(axid === 'angular') { - tickLabels.each(function(d) { - _$d3_7.select(this).select('text') - .call(_$svg_text_utils_183.positionText, labelx(d), labely(d)); - }); - } + var splitIndex = dateStr.indexOf('\n'); + if(splitIndex !== -1) { + headStr = dateStr.substr(splitIndex + 1); + dateStr = dateStr.substr(0, splitIndex); + } - // How much to shift a multi-line label to center it vertically. - function getAnchorHeight(lineCount, lineHeight, angle) { - var h = (lineCount - 1) * lineHeight; - if(axLetter === 'x') { - if(angle < -60 || 60 < angle) { - return -0.5 * h; - } else if(axside === 'top') { - return -h; - } - } else { - angle *= axside === 'left' ? 1 : -1; - if(angle < -30) { - return -h; - } else if(angle < 30) { - return -0.5 * h; - } - } - return 0; + 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$/, ''); } + } - function positionLabels(s, angle) { - s.each(function(d) { - var anchor = labelanchor(angle, d); - var thisLabel = _$d3_7.select(this), - mathjaxGroup = thisLabel.select('.text-math-group'), - transform = transfn.call(thisLabel.node(), d) + - ((_$fastIsnumeric_10(angle) && +angle !== 0) ? - (' rotate(' + angle + ',' + labelx(d) + ',' + - (labely(d) - d.fontSize / 2) + ')') : - ''); - var anchorHeight = getAnchorHeight( - _$svg_text_utils_183.lineCount(thisLabel), - __LINE_SPACING_204 * d.fontSize, - _$fastIsnumeric_10(angle) ? +angle : 0); - if(anchorHeight) { - transform += ' translate(0, ' + anchorHeight + ')'; - } - if(mathjaxGroup.empty()) { - thisLabel.select('text').attr({ - transform: transform, - 'text-anchor': anchor - }); - } - else { - var mjShift = - _$drawing_68.bBox(mathjaxGroup.node()).width * - {end: -0.5, start: 0.5}[anchor]; - mathjaxGroup.attr('transform', transform + - (mjShift ? 'translate(' + mjShift + ',0)' : '')); - } - }); + 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; } + } - // 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, ax._lastangle || ax.tickangle); + out.text = dateStr; +} - function allLabelsReady() { - return labelsReady.length && Promise.all(labelsReady); - } +function formatLog(ax, out, hover, extraPrecision, hideexp) { + var dtick = ax.dtick, + x = out.x, + tickformat = ax.tickformat; - function fixLabelOverlaps() { - positionLabels(tickLabels, ax.tickangle); + 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 = ''; + } - // check for auto-angling if x labels overlap - // don't auto-angle at all for log axes with - // base and digit format - if(axLetter === 'x' && !_$fastIsnumeric_10(ax.tickangle) && - (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { - var lbbArray = []; - tickLabels.each(function(d) { - var s = _$d3_7.select(this), - thisLabel = s.select('.text-math-group'), - x = ax.l2p(d.x); - if(thisLabel.empty()) thisLabel = s.select('text'); + if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; - var bb = _$drawing_68.bBox(thisLabel.node()); + if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { + out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); + } + else if(_$fastIsnumeric_10(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_163.mod(x + 0.01, 1) < 0.1))) { + var p = Math.round(x); + if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || + (isSIFormat(ax.exponentformat) && beyondSI(p))) { + if(p === 0) out.text = 1; + else if(p === 1) out.text = '10'; + else if(p > 1) out.text = '10' + p + ''; + else out.text = '10' + MINUS_SIGN + -p + ''; - 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 - }); - }); - for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_162.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { - // any overlap at all - set 30 degrees - autoangle = 30; - break; - } - } - if(autoangle) { - var tickspacing = Math.abs( - (vals[vals.length - 1].x - vals[0].x) * ax._m - ) / (vals.length - 1); - if(tickspacing < maxFontSize * 2.5) { - autoangle = 90; - } - positionLabels(tickLabels, autoangle); - } - ax._lastangle = autoangle; + out.fontSize *= 1.25; + } + 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(dtick.charAt(0) === 'D') { + out.text = String(Math.round(Math.pow(10, _$lib_163.mod(x, 1)))); + out.fontSize *= 0.75; + } + else throw 'unrecognized dtick ' + String(dtick); - // update the axis title - // (so it can move out of the way if needed) - // TODO: separate out scoot so we don't need to do - // a full redraw of the title (mostly relevant for MathJax) - drawAxTitle(); - return axid + ' done'; + // 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 calcBoundingBox() { - if(ax.showticklabels) { - var gdBB = gd.getBoundingClientRect(); - var bBox = container.node().getBoundingClientRect(); +function formatCategory(ax, out) { + var tt = ax._categories[Math.round(out.x)]; + if(tt === undefined) tt = ''; + out.text = String(tt); +} - /* - * the way we're going to use this, the positioning that matters - * is relative to the origin of gd. This is important particularly - * if gd is scrollable, and may have been scrolled between the time - * we calculate this and the time we use it - */ +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); +} - ax._boundingBox = { - width: bBox.width, - height: bBox.height, - left: bBox.left - gdBB.left, - right: bBox.right - gdBB.left, - top: bBox.top - gdBB.top, - bottom: bBox.bottom - gdBB.top - }; - } else { - var gs = fullLayout._size; - var pos; +function formatAngle(ax, out, hover, extraPrecision, hideexp) { + if(ax.thetaunit === 'radians' && !hover) { + var num = out.x / 180; - // set dummy bbox for ticklabel-less axes + if(num === 0) { + out.text = '0'; + } else { + var frac = num2frac(num); - if(axLetter === 'x') { - pos = ax.anchor === 'free' ? - gs.t + gs.h * (1 - ax.position) : - gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); + if(frac[1] >= 100) { + out.text = numFormat(_$lib_163.deg2rad(out.x), ax, hideexp, extraPrecision); + } else { + var isNeg = out.x < 0; - ax._boundingBox = { - top: pos, - bottom: pos, - left: ax._offset, - right: ax._offset + ax._length, - width: ax._length, - height: 0 - }; + if(frac[1] === 1) { + if(frac[0] === 1) out.text = 'π'; + else out.text = frac[0] + 'π'; } else { - pos = ax.anchor === 'free' ? - gs.l + gs.w * ax.position : - gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - - ax._boundingBox = { - left: pos, - right: pos, - bottom: ax._offset + ax._length, - top: ax._offset, - height: ax._length, - width: 0 - }; - } - } - - /* - * for spikelines: what's the full domain of positions in the - * opposite direction that are associated with this axis? - * This means any axes that we make a subplot with, plus the - * position of the axis itself if it's free. - */ - if(subplots) { - var fullRange = ax._counterSpan = [Infinity, -Infinity]; - - for(i = 0; i < subplots.length; i++) { - var subplot = fullLayout._plots[subplots[i]]; - var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - - extendRange(fullRange, [ - counterAxis._offset, - counterAxis._offset + counterAxis._length - ]); - } - - if(ax.anchor === 'free') { - extendRange(fullRange, (axLetter === 'x') ? - [ax._boundingBox.bottom, ax._boundingBox.top] : - [ax._boundingBox.right, ax._boundingBox.left]); + out.text = [ + '', frac[0], '', + '⁄', + '', frac[1], '', + 'π' + ].join(''); } - } - function extendRange(range, newRange) { - range[0] = Math.min(range[0], newRange[0]); - range[1] = Math.max(range[1], newRange[1]); + if(isNeg) out.text = MINUS_SIGN + out.text; } } + } else { + out.text = numFormat(out.x, ax, hideexp, extraPrecision); + } +} - function doAutoMargins() { - if(!ax.automargin) { return; } - if(axLetter !== 'x' && axLetter !== 'y') { return; } +// 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; + } - var s = ax.side[0]; - var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; + function findGCD(a, b) { + return almostEq(b, 0) ? a : findGCD(b, a % b); + } - if(axLetter === 'x') { - push.y = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 't' ? 1 : 0]); - push[s] += ax._boundingBox.height; - } - else { - push.x = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 'r' ? 1 : 0]); - push[s] += ax._boundingBox.width; - } + function findPrecision(n) { + var e = 1; + while(!almostEq(Math.round(n * e) / e, n)) { + e *= 10; + } + return e; + } - if(ax.title !== fullLayout._dfltTitle[axLetter]) { - push[s] += ax.titlefont.size; - } + var precision = findPrecision(num); + var number = num * precision; + var gcd = Math.abs(findGCD(number, precision)); - var pushKey = ax._name + '.automargin'; - var prevPush = fullLayout._pushmargin[pushKey]; - if(!prevPush || prevPush[s].size < push[s]) { - _$plots_237.autoMargin(gd, pushKey, push); - } - } + return [ + // numerator + Math.round(number / gcd), + // denominator + Math.round(precision / gcd) + ]; +} - var done = _$lib_162.syncOrAsync([ - allLabelsReady, - fixLabelOverlaps, - calcBoundingBox, - doAutoMargins - ]); - if(done && done.then) gd._promises.push(done); - return done; - } +// 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 drawAxTitle() { - if(skipTitle) return; +function isSIFormat(exponentFormat) { + return exponentFormat === 'SI' || exponentFormat === 'B'; +} - // now this only applies to regular cartesian axes; colorbars and - // others ALWAYS call doTicks with skipTitle=true so they can - // configure their own titles. - var ax = _$axis_ids_207.getFromId(gd, axid); +// 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; +} - // rangeslider takes over a bottom title so drop it here - if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; +function numFormat(v, ax, fmtoverride, hover) { + // negative? + var isNeg = v < 0, + // max number of digits past decimal point to show + tickRound = ax._tickround, + exponentFormat = fmtoverride || ax.exponentformat || 'B', + exponent = ax._tickexponent, + tickformat = axes.getTickFormat(ax), + separatethousands = ax.separatethousands; - var avoidSelection = _$d3_7.select(gd).selectAll('g.' + axid + 'tick'); - var avoid = { - selection: avoidSelection, - side: ax.side + // 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 : + (_$fastIsnumeric_10(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] }; - var axLetter = axid.charAt(0); - var gs = gd._fullLayout._size; - var offsetBase = 1.5; - var fontSize = ax.titlefont.size; - - var transform, counterAxis, x, y; + autoTickRound(ah); + tickRound = (Number(ah._tickround) || 0) + 4; + exponent = ah._tickexponent; + if(ax.hoverformat) tickformat = ax.hoverformat; + } - if(avoidSelection.size()) { - var translation = _$drawing_68.getTranslate(avoidSelection.node().parentNode); - avoid.offsetLeft = translation.x; - avoid.offsetTop = translation.y; - } + if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); - var titleStandoff = 10 + fontSize * offsetBase + - (ax.linewidth ? ax.linewidth - 1 : 0); - - if(axLetter === 'x') { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_207.getFromId(gd, ax.anchor); - - x = ax._offset + ax._length / 2; + // 'epsilon' - rounding increment + var e = Math.pow(10, -tickRound) / 2; - if(ax.side === 'top') { - y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); - } - else { - y = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1.5 : 0.5); - } - y += counterAxis._offset; + // 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; - if(!avoid.side) avoid.side = 'bottom'; + // 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 { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_207.getFromId(gd, ax.anchor); + 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_163.numSeparate(v, ax._separators, separatethousands); + } - y = ax._offset + ax._length / 2; - if(ax.side === 'right') { - x = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1 : 0.5); - } - else { - x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); - } - x += counterAxis._offset; + // add exponent + if(exponent && exponentFormat !== 'hide') { + if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; - transform = {rotate: '-90', offset: 0}; - if(!avoid.side) avoid.side = 'left'; - } + var signedExponent; + if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; + else if(exponentFormat !== 'power') signedExponent = '+' + exponent; + else signedExponent = String(exponent); - _$titles_136.draw(gd, axid + 'title', { - propContainer: ax, - propName: ax._name + '.title', - placeholder: fullLayout._dfltTitle[axLetter], - avoid: avoid, - transform: transform, - attributes: {x: x, y: y, 'text-anchor': 'middle'} - }); + if(exponentFormat === 'e') { + v += 'e' + signedExponent; + } + else if(exponentFormat === 'E') { + v += 'E' + 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]; + } } - function traceHasBarsOrFill(trace, subplot) { - if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_244.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; - return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; - } + // 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; +} - function drawGrid(plotinfo, counteraxis, subplot) { - var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); - var zlcontainer = plotinfo.zerolinelayer; - var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; - var gridpath = ax._gridpath || ((axLetter === 'x' ? - ('M0,' + counteraxis._offset + 'v') : - ('M' + counteraxis._offset + ',0h') - ) + counteraxis._length); - var grid = gridcontainer.selectAll('path.' + gcls) - .data((ax.showgrid === false) ? [] : gridvals, datafn); - grid.enter().append('path').classed(gcls, 1) - .classed('crisp', 1) - .attr('d', gridpath) - .each(function(d) { - if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && - Math.abs(d.x) < ax.dtick / 100) { - _$d3_7.select(this).remove(); - } - }); - grid.attr('transform', transfn) - .call(_$color_43.stroke, ax.gridcolor || '#ddd') - .style('stroke-width', gridWidth + 'px'); - if(typeof gridpath === 'function') grid.attr('d', gridpath); - grid.exit().remove(); +axes.getTickFormat = function(ax) { + var i; - // zero line - if(zlcontainer) { - var hasBarsOrFill = false; - for(var i = 0; i < gd._fullData.length; i++) { - if(traceHasBarsOrFill(gd._fullData[i], subplot)) { - hasBarsOrFill = true; - break; + 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; } } - var rng = _$lib_162.simpleMap(ax.range, ax.r2l), - showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && - (ax.type === 'linear' || ax.type === '-') && gridvals.length && - (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); - var zl = zlcontainer.selectAll('path.' + zcls) - .data(showZl ? [{x: 0, id: axid}] : []); - zl.enter().append('path').classed(zcls, 1).classed('zl', 1) - .classed('crisp', 1) - .attr('d', gridpath) - .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. - zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_207.idSort(da.id, db.id); - }); - }); - zl.attr('transform', transfn) - .call(_$color_43.stroke, ax.zerolinecolor || _$color_43.defaultLine) - .style('stroke-width', zeroLineWidth + 'px'); - zl.exit().remove(); + } else { + return typeof left === 'number' ? 1 : -1; } } - if(independent) { - drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); - if(ax._counteraxis) { - var fictionalPlotinfo = { - gridlayer: ax._gridlayer, - zerolinelayer: ax._zerolinelayer - }; - drawGrid(fictionalPlotinfo, ax._counteraxis); - } - return drawLabels(ax._axislayer, ax._pos); + 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)); } - else if(fullLayout._has('cartesian')) { - subplots = axes.getSubplots(gd, ax); - - // keep track of which subplots (by main conteraxis) we've already - // drawn grids for, so we don't overdraw overlaying subplots - var finishedGrids = {}; - - subplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; - var counterAxis = plotinfo[counterLetter + 'axis']; - - var mainCounterID = counterAxis._mainAxis._id; - if(finishedGrids[mainCounterID]) return; - finishedGrids[mainCounterID] = 1; - - drawGrid(plotinfo, counterAxis, subplot); - }); - var mainSubplot = ax._mainSubplot; - var mainPlotinfo = fullLayout._plots[mainSubplot]; - var tickSubplots = []; + 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); + } - if(ax.ticks) { - var mainSign = ticksign[2]; - var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); - if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { - tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + var tickstop; + if(ax.tickformatstops && ax.tickformatstops.length > 0) { + switch(ax.type) { + case 'date': + case 'linear': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; } - drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - - tickSubplots = Object.keys(ax._linepositions); + case 'log': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; + } + default: } + } + return tickstop ? tickstop.value : ax.tickformat; +}; - tickSubplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; +// 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 +axes.getSubplots = function(gd, ax) { + var subplotObj = gd._fullLayout._subplots; + var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); - var container = plotinfo[axLetter + 'axislayer']; + var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; - // [bottom or left, top or right] - // free and main are handled above - var linepositions = ax._linepositions[subplot] || []; + out.sort(function(a, b) { + var aParts = a.substr(1).split('y'); + var bParts = b.substr(1).split('y'); - function tickPathSide(sidei) { - var tsign = ticksign[sidei]; - return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); - } + if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; + return +aParts[0] - +bParts[0]; + }); - drawTicks(container, tickPathSide(0) + tickPathSide(1)); - }); + return out; +}; - var mainContainer = mainPlotinfo[axLetter + 'axislayer']; +// find all subplots with axis 'ax' +axes.findSubplotsWithAxis = function(subplots, ax) { + var axMatch = new RegExp( + (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') + ); + var subplotsWithAxis = []; - return drawLabels(mainContainer, ax._mainLinePosition); + for(var i = 0; i < subplots.length; i++) { + var sp = subplots[i]; + if(axMatch.test(sp)) subplotsWithAxis.push(sp); } + + return subplotsWithAxis; }; -// swap all the presentation attributes of the axes showing these traces -axes.swap = function(gd, traces) { - var axGroups = makeAxisGroups(gd, traces); +// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings +axes.makeClipPaths = function(gd) { + var fullLayout = gd._fullLayout; + 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(var i = 0; i < axGroups.length; i++) { - swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + 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]}); + } } -}; -function makeAxisGroups(gd, traces) { - var groups = [], - i, - 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; }); - for(i = 0; i < traces.length; i++) { - var groupsi = [], - xi = gd._fullData[traces[i]].xaxis, - yi = gd._fullData[traces[i]].yaxis; - if(!xi || !yi) continue; // not a 2D cartesian trace? + axClips.enter().append('clipPath') + .classed('axesclip', true) + .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; }) + .append('rect'); - for(j = 0; j < groups.length; j++) { - if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { - groupsi.push(j); - } - } + axClips.exit().remove(); - if(!groupsi.length) { - groups.push({x: [xi], y: [yi]}); - continue; - } + axClips.each(function(d) { + _$d3_7.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 + }); + }); +}; - var group0 = groups[groupsi[0]], - groupj; +// doTicks: draw ticks, grids, and tick labels +// axid: 'x', 'y', 'x2' etc, +// blank to do all, +// 'redraw' to force full redraw, and reset: +// ax._r (stored range for use by zoom/pan) +// ax._rl (stored linearized range for use by zoom/pan) +// or can pass in an axis object directly +axes.doTicks = function(gd, axid, skipTitle) { + var fullLayout = gd._fullLayout; + var ax; + var independent = false; - 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]); + // allow passing an independent axis object instead of id + if(typeof axid === 'object') { + ax = axid; + axid = ax._id; + independent = true; } + else { + ax = axes.getFromId(gd, axid); - return groups; -} + if(axid === 'redraw') { + fullLayout._paper.selectAll('g.subplot').each(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -function mergeAxisGroups(intoSet, fromSet) { - for(var i = 0; i < fromSet.length; i++) { - if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); + }); + } + + if(!axid || axid === 'redraw') { + return _$lib_163.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return function() { + if(!ax._id) return; + var axDone = axes.doTicks(gd, ax._id); + ax._r = ax.range.slice(); + ax._rl = _$lib_163.simpleMap(ax._r, ax.r2l); + return axDone; + }; + })); + } } -} -function swapAxisGroup(gd, xIds, yIds) { - var i, - j, - xFullAxes = [], - yFullAxes = [], - layout = gd.layout; + // set scaling to pixels + ax.setScale(); - 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 axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_68.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_68.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_68.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; - var allAxKeys = Object.keys(xFullAxes[0]), - noSwapAttrs = [ - 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' - ], - numericTypes = ['linear', 'log']; + if(ax._counterangle && ax.ticks === 'outside') { + var caRad = ax._counterangle * Math.PI / 180; + labelStandoff = ax.ticklen * Math.cos(caRad) + 1; + labelShift = ax.ticklen * Math.sin(caRad); + } - for(i = 0; i < allAxKeys.length; i++) { - var keyi = allAxKeys[i], - xVal = xFullAxes[0][keyi], - yVal = yFullAxes[0][keyi], - allEqual = true, - coerceLinearX = false, - 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; + if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { + labelStandoff += 0.2 * ax.tickfont.size; + } + + // positioning arguments for x vs y axes + if(axLetter === 'x') { + sides = ['bottom', 'top']; + transfn = ax._transfn || function(d) { + return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); } - 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 return 'M0,' + shift + 'v' + len; + }; + } + else if(axLetter === 'y') { + sides = ['left', 'right']; + transfn = ax._transfn || function(d) { + return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); } - 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); - } + else return 'M' + shift + ',0h' + len; + }; + } + else if(axid === 'angular') { + sides = ['left', 'right']; + transfn = ax._transfn; + tickpathfn = function(shift, len) { + return 'M' + shift + ',0h' + len; + }; + } + else { + _$lib_163.warn('Unrecognized doTicks axis:', axid); + return; } - // 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_162.swapAttrs(layout.annotations[i], ['?']); - } + var axside = ax.side || sides[0]; + // which direction do the side[0], side[1], and free ticks go? + // then we flip if outside XOR y axis + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + if((ax.ticks !== 'inside') === (axLetter === 'x')) { + ticksign = ticksign.map(function(v) { return -v; }); } -} -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_162.nestedProperty, - xVal = np(layout[xFullAxes[0]._name], key).get(), - yVal = np(layout[yFullAxes[0]._name], key).get(), - i; - if(key === 'title') { - // special handling of placeholder titles - if(xVal === dfltTitle.x) { - xVal = dfltTitle.y; - } - if(yVal === dfltTitle.y) { - yVal = dfltTitle.x; - } - } + if(!ax.visible) return; - for(i = 0; i < xFullAxes.length; i++) { - np(layout, xFullAxes[i]._name + '.' + key).set(yVal); + if(ax._tickFilter) { + vals = vals.filter(ax._tickFilter); } - for(i = 0; i < yFullAxes.length; i++) { - np(layout, yFullAxes[i]._name + '.' + key).set(xVal); + + // remove zero lines, grid lines, and inside ticks if they're within + // 1 pixel of the end + // The key case here is removing zero lines when the axis bound is zero. + function clipEnds(d) { + var p = ax.l2p(d.x); + return (p > 1 && p < ax._length - 1); } -} + var valsClipped = vals.filter(clipEnds); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // don't clip angular values + if(ax._id === 'angular') { + valsClipped = vals; + } -'use strict'; + function drawTicks(container, tickpath) { + var ticks = container.selectAll('path.' + tcls) + .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); -/* removed: var _$d3_7 = require('d3'); */; + if(tickpath && ax.ticks) { + ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) + .classed('crisp', 1) + .call(_$color_43.stroke, ax.tickcolor) + .style('stroke-width', tickWidth + 'px') + .attr('d', tickpath); + ticks.attr('transform', transfn); + ticks.exit().remove(); + } + else ticks.remove(); + } -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$axes_204 = require('./axes'); */; -var axisRegex = _$constants_209.attrRegex; + function drawLabels(container, position) { + // tick labels - for now just the main labels. + // TODO: mirror labels, esp for subplots + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); -var _$transitionAxes_227 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; + if(!_$fastIsnumeric_10(position)) { + tickLabels.remove(); + drawAxTitle(); + return; + } + if(!ax.showticklabels) { + tickLabels.remove(); + drawAxTitle(); + calcBoundingBox(); + return; + } - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + var labelx, labely, labelanchor, labelpos0, flipit; + if(axLetter === 'x') { + flipit = (axside === 'bottom') ? 1 : -1; + labelx = function(d) { return d.dx + labelShift * flipit; }; + labelpos0 = position + (labelStandoff + pad) * flipit; + labely = function(d) { + return d.dy + labelpos0 + d.fontSize * + ((axside === 'bottom') ? 1 : -0.2); + }; + labelanchor = function(angle) { + if(!_$fastIsnumeric_10(angle) || angle === 0 || angle === 180) { + return 'middle'; + } + return (angle * flipit < 0) ? 'end' : 'start'; + }; + } + else if(axLetter === 'y') { + flipit = (axside === 'right') ? 1 : -1; + labely = function(d) { + return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; + }; + labelx = function(d) { + return d.dx + position + (labelStandoff + pad + + ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; + }; + labelanchor = function(angle) { + if(_$fastIsnumeric_10(angle) && Math.abs(angle) === 90) { + return 'middle'; + } + return axside === 'right' ? 'start' : 'end'; + }; + } + else if(axid === 'angular') { + ax._labelShift = labelShift; + ax._labelStandoff = labelStandoff; + ax._pad = pad; - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + labelx = ax._labelx; + labely = ax._labely; + labelanchor = ax._labelanchor; + } - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); + var maxFontSize = 0, + autoangle = 0, + labelsReady = []; + tickLabels.enter().append('g').classed(tcls, 1) + .append('text') + // only so tex has predictable alignment that we can + // alter later + .attr('text-anchor', 'middle') + .each(function(d) { + var thisLabel = _$d3_7.select(this), + newPromise = gd._promises.length; + thisLabel + .call(_$svg_text_utils_184.positionText, labelx(d), labely(d)) + .call(_$drawing_68.font, d.font, d.fontSize, d.fontColor) + .text(d.text) + .call(_$svg_text_utils_184.convertToTspans, gd); + newPromise = gd._promises[newPromise]; + if(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, ax.tickangle); + })); } - } - if(!update.to) continue; + else { + // sync label: just position it now. + positionLabels(thisLabel, ax.tickangle); + } + }); + tickLabels.exit().remove(); - update.axisName = axisName; - update.length = axis._length; + tickLabels.each(function(d) { + maxFontSize = Math.max(maxFontSize, d.fontSize); + }); - axes.push(axisLetter); + if(axid === 'angular') { + tickLabels.each(function(d) { + _$d3_7.select(this).select('text') + .call(_$svg_text_utils_184.positionText, labelx(d), labely(d)); + }); + } - updates[axisLetter] = update; + // How much to shift a multi-line label to center it vertically. + function getAnchorHeight(lineCount, lineHeight, angle) { + var h = (lineCount - 1) * lineHeight; + if(axLetter === 'x') { + if(angle < -60 || 60 < angle) { + return -0.5 * h; + } else if(axside === 'top') { + return -h; + } + } else { + angle *= axside === 'left' ? 1 : -1; + if(angle < -30) { + return -h; + } else if(angle < 30) { + return -0.5 * h; + } } + return 0; } - return updates; - } + function positionLabels(s, angle) { + s.each(function(d) { + var anchor = labelanchor(angle, d); + var thisLabel = _$d3_7.select(this), + mathjaxGroup = thisLabel.select('.text-math-group'), + transform = transfn.call(thisLabel.node(), d) + + ((_$fastIsnumeric_10(angle) && +angle !== 0) ? + (' rotate(' + angle + ',' + labelx(d) + ',' + + (labely(d) - d.fontSize / 2) + ')') : + ''); + var anchorHeight = getAnchorHeight( + _$svg_text_utils_184.lineCount(thisLabel), + __LINE_SPACING_205 * d.fontSize, + _$fastIsnumeric_10(angle) ? +angle : 0); + if(anchorHeight) { + transform += ' translate(0, ' + anchorHeight + ')'; + } + if(mathjaxGroup.empty()) { + thisLabel.select('text').attr({ + transform: transform, + 'text-anchor': anchor + }); + } + else { + var mjShift = + _$drawing_68.bBox(mathjaxGroup.node()).width * + {end: -0.5, start: 0.5}[anchor]; + mathjaxGroup.attr('transform', transform + + (mjShift ? 'translate(' + mjShift + ',0)' : '')); + } + }); + } - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; + // 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, ax._lastangle || ax.tickangle); - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; + function allLabelsReady() { + return labelsReady.length && Promise.all(labelsReady); + } - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + function fixLabelOverlaps() { + positionLabels(tickLabels, ax.tickangle); - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; + // check for auto-angling if x labels overlap + // don't auto-angle at all for log axes with + // base and digit format + if(axLetter === 'x' && !_$fastIsnumeric_10(ax.tickangle) && + (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { + var lbbArray = []; + tickLabels.each(function(d) { + var s = _$d3_7.select(this), + thisLabel = s.select('.text-math-group'), + x = ax.l2p(d.x); + if(thisLabel.empty()) thisLabel = s.select('text'); - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + var bb = _$drawing_68.bBox(thisLabel.node()); - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; + 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 + }); + }); + for(i = 0; i < lbbArray.length - 1; i++) { + if(_$lib_163.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + // any overlap at all - set 30 degrees + autoangle = 30; + break; + } + } + if(autoangle) { + var tickspacing = Math.abs( + (vals[vals.length - 1].x - vals[0].x) * ax._m + ) / (vals.length - 1); + if(tickspacing < maxFontSize * 2.5) { + autoangle = 90; + } + positionLabels(tickLabels, autoangle); + } + ax._lastangle = autoangle; } - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; - - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); - } + // update the axis title + // (so it can move out of the way if needed) + // TODO: separate out scoot so we don't need to do + // a full redraw of the title (mostly relevant for MathJax) + drawAxTitle(); + return axid + ' done'; } - return affectedSubplots; - } + function calcBoundingBox() { + if(ax.showticklabels) { + var gdBB = gd.getBoundingClientRect(); + var bBox = container.node().getBoundingClientRect(); - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); + /* + * the way we're going to use this, the positioning that matters + * is relative to the origin of gd. This is important particularly + * if gd is scrollable, and may have been scrolled between the time + * we calculate this and the time we use it + */ - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); + ax._boundingBox = { + width: bBox.width, + height: bBox.height, + left: bBox.left - gdBB.left, + right: bBox.right - gdBB.left, + top: bBox.top - gdBB.top, + bottom: bBox.bottom - gdBB.top + }; + } else { + var gs = fullLayout._size; + var pos; - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } + // set dummy bbox for ticklabel-less axes - redrawObjs(fullLayout.annotations || [], _$registry_244.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_244.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_244.getComponentMethod('images', 'draw'), true); - } + if(axLetter === 'x') { + pos = ax.anchor === 'free' ? + gs.t + gs.h * (1 - ax.position) : + gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; - } + ax._boundingBox = { + top: pos, + bottom: pos, + left: ax._offset, + right: ax._offset + ax._length, + width: ax._length, + height: 0 + }; + } else { + pos = ax.anchor === 'free' ? + gs.l + gs.w * ax.position : + gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; + ax._boundingBox = { + left: pos, + right: pos, + bottom: ax._offset + ax._length, + top: ax._offset, + height: ax._length, + width: 0 + }; + } + } - activeAxIds = [xa._id, ya._id]; + /* + * for spikelines: what's the full domain of positions in the + * opposite direction that are associated with this axis? + * This means any axes that we make a subplot with, plus the + * position of the axis itself if it's free. + */ + if(subplots) { + var fullRange = ax._counterSpan = [Infinity, -Infinity]; - for(i = 0; i < activeAxIds.length; i++) { - _$axes_204.doTicks(gd, activeAxIds[i], true); - } + for(i = 0; i < subplots.length; i++) { + var subplot = fullLayout._plots[subplots[i]]; + var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; + extendRange(fullRange, [ + counterAxis._offset, + counterAxis._offset + counterAxis._length + ]); + } - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); + if(ax.anchor === 'free') { + extendRange(fullRange, (axLetter === 'x') ? + [ax._boundingBox.bottom, ax._boundingBox.top] : + [ax._boundingBox.right, ax._boundingBox.left]); } + } - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + function extendRange(range, newRange) { + range[0] = Math.min(range[0], newRange[0]); + range[1] = Math.max(range[1], newRange[1]); } } - redrawObjs(fullLayout.annotations || [], _$registry_244.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_244.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_244.getComponentMethod('images', 'draw'), true); - } + function doAutoMargins() { + if(!ax.automargin) { return; } + if(axLetter !== 'x' && axLetter !== 'y') { return; } - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + var s = ax.side[0]; + var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_68.setTranslate, 0, 0) - .call(_$drawing_68.setScale, 1, 1); + if(axLetter === 'x') { + push.y = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 't' ? 1 : 0]); + push[s] += ax._boundingBox.height; + } + else { + push.x = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 'r' ? 1 : 0]); + push[s] += ax._boundingBox.width; + } - subplot.plot - .call(_$drawing_68.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_68.setScale, 1, 1); + if(ax.title !== fullLayout._dfltTitle[axLetter]) { + push[s] += ax.titlefont.size; + } - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + var pushKey = ax._name + '.automargin'; + var prevPush = fullLayout._pushmargin[pushKey]; + if(!prevPush || prevPush[s].size < push[s]) { + _$plots_237.autoMargin(gd, pushKey, push); + } + } - // 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_68.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_68.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_68.hideOutsideRangePoints, subplot); + var done = _$lib_163.syncOrAsync([ + allLabelsReady, + fixLabelOverlaps, + calcBoundingBox, + doAutoMargins + ]); + if(done && done.then) gd._promises.push(done); + return done; } - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; + function drawAxTitle() { + if(skipTitle) return; - var viewBox = []; + // now this only applies to regular cartesian axes; colorbars and + // others ALWAYS call doTicks with skipTitle=true so they can + // configure their own titles. - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + // rangeslider takes over a bottom title so drop it here + if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + var avoid = { + selection: tickLabels, + side: ax.side + }; + var axLetter = axid.charAt(0); + var gs = gd._fullLayout._size; + var offsetBase = 1.5; + var fontSize = ax.titlefont.size; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; + var transform, counterAxis, x, y; + + if(tickLabels.size()) { + var translation = _$drawing_68.getTranslate(tickLabels.node().parentNode); + avoid.offsetLeft = translation.x; + avoid.offsetTop = translation.y; } - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + var titleStandoff = 10 + fontSize * offsetBase + + (ax.linewidth ? ax.linewidth - 1 : 0); - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + if(axLetter === 'x') { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : + _$axis_ids_208.getFromId(gd, ax.anchor); - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; - } - - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + x = ax._offset + ax._length / 2; - var editX = !!xUpdate; - var editY = !!yUpdate; + if(ax.side === 'top') { + y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); + } + else { + y = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1.5 : 0.5); + } + y += counterAxis._offset; - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + if(!avoid.side) avoid.side = 'bottom'; + } + else { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : + _$axis_ids_208.getFromId(gd, ax.anchor); - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + y = ax._offset + ax._length / 2; + if(ax.side === 'right') { + x = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1 : 0.5); + } + else { + x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); + } + x += counterAxis._offset; - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + transform = {rotate: '-90', offset: 0}; + if(!avoid.side) avoid.side = 'left'; + } - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + _$titles_136.draw(gd, axid + 'title', { + propContainer: ax, + propName: ax._name + '.title', + placeholder: fullLayout._dfltTitle[axLetter], + avoid: avoid, + transform: transform, + attributes: {x: x, y: y, 'text-anchor': 'middle'} + }); + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_68.setTranslate, clipDx, clipDy) - .call(_$drawing_68.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + function traceHasBarsOrFill(trace, subplot) { + if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; + if(_$registry_245.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; + } - subplot.plot - .call(_$drawing_68.setTranslate, plotDx, plotDy) - .call(_$drawing_68.setScale, xScaleFactor, yScaleFactor) + function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_68.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); + var zlcontainer = plotinfo.zerolinelayer; + var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; + var gridpath = ax._gridpath || ((axLetter === 'x' ? + ('M0,' + counteraxis._offset + 'v') : + ('M' + counteraxis._offset + ',0h') + ) + counteraxis._length); + var grid = gridcontainer.selectAll('path.' + gcls) + .data((ax.showgrid === false) ? [] : gridvals, datafn); + grid.enter().append('path').classed(gcls, 1) + .classed('crisp', 1) + .attr('d', gridpath) + .each(function(d) { + if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && + Math.abs(d.x) < ax.dtick / 100) { + _$d3_7.select(this).remove(); + } + }); + grid.attr('transform', transfn) + .call(_$color_43.stroke, ax.gridcolor || '#ddd') + .style('stroke-width', gridWidth + 'px'); + if(typeof gridpath === 'function') grid.attr('d', gridpath); + grid.exit().remove(); - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_68.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + // zero line + if(zlcontainer) { + var hasBarsOrFill = false; + for(var i = 0; i < gd._fullData.length; i++) { + if(traceHasBarsOrFill(gd._fullData[i], subplot)) { + hasBarsOrFill = true; + break; + } + } + var rng = _$lib_163.simpleMap(ax.range, ax.r2l), + showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && + (ax.type === 'linear' || ax.type === '-') && gridvals.length && + (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); + var zl = zlcontainer.selectAll('path.' + zcls) + .data(showZl ? [{x: 0, id: axid}] : []); + zl.enter().append('path').classed(zcls, 1).classed('zl', 1) + .classed('crisp', 1) + .attr('d', gridpath) + .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. + zlcontainer.selectAll('path').sort(function(da, db) { + return _$axis_ids_208.idSort(da.id, db.id); + }); + }); + zl.attr('transform', transfn) + .call(_$color_43.stroke, ax.zerolinecolor || _$color_43.defaultLine) + .style('stroke-width', zeroLineWidth + 'px'); + zl.exit().remove(); + } } - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); + if(independent) { + drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); + if(ax._counteraxis) { + var fictionalPlotinfo = { + gridlayer: ax._gridlayer, + zerolinelayer: ax._zerolinelayer + }; + drawGrid(fictionalPlotinfo, ax._counteraxis); + } + return drawLabels(ax._axislayer, ax._pos); } + else if(fullLayout._has('cartesian')) { + subplots = axes.getSubplots(gd, ax); - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; + // keep track of which subplots (by main conteraxis) we've already + // drawn grids for, so we don't overdraw overlaying subplots + var finishedGrids = {}; - axi.range = to.slice(); - } + subplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var counterAxis = plotinfo[counterLetter + 'axis']; - // Signal that this transition has completed: - onComplete && onComplete(); + var mainCounterID = counterAxis._mainAxis._id; + if(finishedGrids[mainCounterID]) return; + finishedGrids[mainCounterID] = 1; - return _$registry_244.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } + drawGrid(plotinfo, counterAxis, subplot); }); - } - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; + var mainSubplot = ax._mainSubplot; + var mainPlotinfo = fullLayout._plots[mainSubplot]; + var tickSubplots = []; - axi.range = axi._r.slice(); + if(ax.ticks) { + var mainSign = ticksign[2]; + var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); + if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { + tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + } + drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); + + tickSubplots = Object.keys(ax._linepositions || {}); } - return _$registry_244.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); - } + tickSubplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; - var t1, t2, raf; - var easeFn = _$d3_7.ease(transitionOpts.easing); + var container = plotinfo[axLetter + 'axislayer']; - gd._transitionData._interruptCallbacks.push(function() { - window.cancelAnimationFrame(raf); - raf = null; - return transitionInterrupt(); - }); + // [bottom or left, top or right] + // free and main are handled above + var linepositions = ax._linepositions[subplot] || []; - function doFrame() { - t2 = Date.now(); + function tickPathSide(sidei) { + var tsign = ticksign[sidei]; + return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); + } - var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); - var progress = easeFn(tInterp); + drawTicks(container, tickPathSide(0) + tickPathSide(1)); + }); - for(var i = 0; i < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } + var mainContainer = mainPlotinfo[axLetter + 'axislayer']; - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); - } + return drawLabels(mainContainer, ax._mainLinePosition); } +}; - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); +// swap all the presentation attributes of the axes showing these traces +axes.swap = function(gd, traces) { + var axGroups = makeAxisGroups(gd, traces); - return Promise.resolve(); + for(var i = 0; i < axGroups.length; i++) { + swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + } }; -var _$get_data_233 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +function makeAxisGroups(gd, traces) { + var groups = [], + i, + j; -/* removed: var _$registry_244 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_209.SUBPLOT_PATTERN; + for(i = 0; i < traces.length; i++) { + var groupsi = [], + xi = gd._fullData[traces[i]].xaxis, + yi = gd._fullData[traces[i]].yaxis; + if(!xi || !yi) continue; // not a 2D cartesian trace? -/** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces - */ -_$get_data_233.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_244.subplotsRegistry[type]; - if(!basePlotModule) return []; + for(j = 0; j < groups.length; j++) { + if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { + groupsi.push(j); + } + } - var attr = basePlotModule.attr; - var subplotCalcData = []; + if(!groupsi.length) { + groups.push({x: [xi], y: [yi]}); + continue; + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; + var group0 = groups[groupsi[0]], + groupj; - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + 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 subplotCalcData; -}; - -_$get_data_233.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_244.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + return groups; +} - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); +function mergeAxisGroups(intoSet, fromSet) { + for(var i = 0; i < fromSet.length; i++) { + if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); } +} - return moduleCalcData; -}; +function swapAxisGroup(gd, xIds, yIds) { + var i, + j, + xFullAxes = [], + yFullAxes = [], + layout = gd.layout; -/** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. - * - * @return {array} list of trace objects. - * - */ -_$get_data_233.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_244.subplotsRegistry[type]) return []; + 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 attr = _$registry_244.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; + var allAxKeys = Object.keys(xFullAxes[0]), + noSwapAttrs = [ + 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' + ], + numericTypes = ['linear', 'log']; - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; + for(i = 0; i < allAxKeys.length; i++) { + var keyi = allAxKeys[i], + xVal = xFullAxes[0][keyi], + yVal = yFullAxes[0][keyi], + allEqual = true, + coerceLinearX = false, + 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); + } } - for(var i = 0; i < data.length; i++) { - trace = data[i]; + // 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_163.swapAttrs(layout.annotations[i], ['?']); + } + } +} - if(type === 'gl2d' && _$registry_244.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); - } +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_163.nestedProperty, + xVal = np(layout[xFullAxes[0]._name], key).get(), + yVal = np(layout[yFullAxes[0]._name], key).get(), + i; + if(key === 'title') { + // special handling of placeholder titles + if(xVal === dfltTitle.x) { + xVal = dfltTitle.y; } - else { - if(trace[attr] === subplotId) subplotData.push(trace); + if(yVal === dfltTitle.y) { + yVal = dfltTitle.x; } } - return subplotData; -}; + 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); + } +} -var _$cartesian_215 = {}; +var _$hover_83 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29759,1087 +29982,1453 @@ var _$cartesian_215 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$plots_237 = require('../plots'); */; -var getModuleCalcData = _$get_data_233.getModuleCalcData; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$axis_ids_207 = require('./axis_ids'); */; -/* removed: var _$constants_209 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$Events_156 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_174 = require('../../lib/override_cursor'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_245 = require('../../registry'); */; -_$cartesian_215.name = 'cartesian'; +/* removed: var _$helpers_82 = require('./helpers'); */; +/* removed: var _$constants_80 = require('./constants'); */; -_$cartesian_215.attr = ['xaxis', 'yaxis']; +// hover labels for multiple horizontal bars get tilted by some angle, +// then need to be offset differently if they overlap +var YANGLE = _$constants_80.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; -_$cartesian_215.idRoot = ['x', 'y']; +// expansion of projected height +var YFACTOR = 1 / Math.sin(YA_RADIANS); -_$cartesian_215.idRegex = _$constants_209.idRegex; +// to make the appropriate post-rotation x offset, +// you need both x and y offsets +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); -_$cartesian_215.attrRegex = _$constants_209.attrRegex; +// size and display constants for hover text +var HOVERARROWSIZE = _$constants_80.HOVERARROWSIZE; +var HOVERTEXTPAD = _$constants_80.HOVERTEXTPAD; -_$cartesian_215.attributes = _$attributes_202; +// fx.hover: highlight data on hover +// evt can be a mousemove event, or an object with data about what points +// to hover on +// {xpx,ypx[,hovermode]} - pixel locations from top left +// (with optional overriding hovermode) +// {xval,yval[,hovermode]} - data values +// [{curveNumber,(pointNumber|xval and/or yval)}] - +// array of specific points to highlight +// pointNumber is a single integer if gd.data[curveNumber] is 1D, +// or a two-element array if it's 2D +// xval and yval are data values, +// 1D data may specify either or both, +// 2D data must specify both +// subplot is an id string (default "xy") +// makes use of gl.hovermode, which can be: +// x (find the points with the closest x values, ie a column), +// closest (find the single closest point) +// internally there are two more that occasionally get used: +// y (pick out a row - only used for multiple horizontal bar charts) +// array (used when the user specifies an explicit +// array of points to hover on) +// +// We wrap the hovers in a timer, to limit their frequency. +// The actual rendering is done by private function _hover. +_$hover_83.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = _$lib_163.getGraphDiv(gd); -_$cartesian_215.layoutAttributes = _$layout_attributes_216; + _$lib_163.throttle( + gd._fullLayout._uid + _$constants_80.HOVERID, + _$constants_80.HOVERMINTIME, + function() { _hover(gd, evt, subplot, noHoverEvent); } + ); +}; -_$cartesian_215.supplyLayoutDefaults = _$supplyLayoutDefaults_217; +/* + * Draw a single hover item in a pre-existing svg container somewhere + * hoverItem should have keys: + * - x and y (or x0, x1, y0, and y1): + * the pixel position to mark, relative to opts.container + * - xLabel, yLabel, zLabel, text, and name: + * info to go in the label + * - color: + * the background color for the label. + * - idealAlign (optional): + * 'left' or 'right' for which side of the x/y box to try to put this on first + * - borderColor (optional): + * color for the border, defaults to strongest contrast with color + * - fontFamily (optional): + * string, the font for this label, defaults to constants.HOVERFONT + * - fontSize (optional): + * the label font size, defaults to constants.HOVERFONTSIZE + * - fontColor (optional): + * defaults to borderColor + * opts should have keys: + * - bgColor: + * the background color this is against, used if the trace is + * non-opaque, and for the name, which goes outside the box + * - container: + * a or element to add the hover label to + * - outerContainer: + * normally a parent of `container`, sets the bounding box to use to + * constrain the hover label and determine whether to show it on the left or right + */ +_$hover_83.loneHover = function loneHover(hoverItem, opts) { + var pointData = { + color: hoverItem.color || _$color_43.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, -_$cartesian_215.transitionAxes = _$transitionAxes_227; + // optional extra bits of styling + borderColor: hoverItem.borderColor, + fontFamily: hoverItem.fontFamily, + fontSize: hoverItem.fontSize, + fontColor: hoverItem.fontColor, -_$cartesian_215.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; - - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } - - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_207.id2name(xi)] || {}).anchor; - if(!_$constants_209.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + // filler to make createHoverText happy + trace: { + index: 0, + hoverinfo: '' + }, + xa: {_offset: 0}, + ya: {_offset: 0}, + index: 0 + }; - if(!allY[yi]) { - allY[yi] = 1; - _$lib_162.pushUnique(yList, yi); - } - } - } + var container3 = _$d3_7.select(opts.container), + outerContainer3 = opts.outerContainer ? + _$d3_7.select(opts.outerContainer) : container3; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_207.id2name(yi)] || {}).anchor; - if(!_$constants_209.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var fullOpts = { + hovermode: 'closest', + rotateLabels: false, + bgColor: opts.bgColor || _$color_43.background, + container: container3, + outerContainer: outerContainer3 + }; - if(!allX[xi]) { - allX[xi] = 1; - _$lib_162.pushUnique(xList, xi); - } - } - } + var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); + alignHoverText(hoverLabel, fullOpts.rotateLabels); - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_209.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_207.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_207.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } + return hoverLabel.node(); }; -_$cartesian_215.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; +// The actual implementation is here: +function _hover(gd, evt, subplot, noHoverEvent) { + if(!subplot) subplot = 'xy'; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + // if the user passed in an array of subplots, + // use those instead of finding overlayed plots + var subplots = Array.isArray(subplot) ? subplot : [subplot]; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var fullLayout = gd._fullLayout; + var plots = fullLayout._plots || []; + var plotinfo = plots[subplot]; + var hasCartesian = fullLayout._has('cartesian'); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } + // list of all overlaid subplots to look at + if(plotinfo) { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; }); - } - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + subplots = subplots.concat(overlayedSubplots); + } - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; + var len = subplots.length; + var xaArray = new Array(len); + var yaArray = new Array(len); + var supportsCompare = false; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + for(var i = 0; i < len; i++) { + var spId = subplots[i]; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + // 'cartesian' case + var plotObj = plots[spId]; + if(plotObj) { + supportsCompare = true; - cdSubplot.push(cd); - } + // TODO make sure that fullLayout_plots axis refs + // get updated properly so that we don't have + // to use Axes.getFromId in general. - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; - } + xaArray[i] = _$axes_205.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_205.getFromId(gd, plotObj.yaxis._id); + continue; } - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + // other subplot types + var _subplot = fullLayout[spId]._subplot; + xaArray[i] = _subplot.xaxis; + yaArray[i] = _subplot.yaxis; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; + var hovermode = evt.hovermode || fullLayout.hovermode; - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + if(hovermode && !supportsCompare) hovermode = 'closest'; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || + gd.querySelector('.zoombox') || gd._dragging) { + return _$dragelement_65.unhoverRaw(gd, evt); } -} -_$cartesian_215.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; + var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + // hoverData: the set of candidate points we've found to highlight + var hoverData = [], + // searchData: the data to search in. Mostly this is just a copy of + // gd.calcdata, filtered to the subplot and overlays we're on + // but if a point array is supplied it will be a mapping + // of indicated curves + searchData = [], - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; - } + // [x|y]valArray: the axis values of the hover event + // mapped onto each of the currently selected overlaid subplots + xvalArray, + yvalArray, - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + // used in loops + itemnum, + curvenum, + cd, + trace, + subplotId, + subploti, + mode, + xval, + yval, + pointData, + closedataPreviousLength, - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // spikePoints: the set of candidate points we've found to draw spikes to + spikePoints = { + hLinePoint: null, + vLinePoint: null + }; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + // Figure out what we're hovering on: + // mouse location or user-supplied data - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + if(Array.isArray(evt)) { + // user specified an array of points to highlight + hovermode = 'array'; + for(itemnum = 0; itemnum < evt.length; itemnum++) { + cd = gd.calcdata[evt[itemnum].curveNumber||0]; + if(cd[0].trace.hoverinfo !== 'skip') { + searchData.push(cd); } } - - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); } + else { + for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { + cd = gd.calcdata[curvenum]; + trace = cd[0].trace; + if(trace.hoverinfo !== 'skip' && _$helpers_82.isTraceInSubplots(trace, subplots)) { + searchData.push(cd); + } + } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // [x|y]px: the pixels (from top left) of the mouse location + // on the currently selected plot area + // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation + var hasUserCalledHover = !evt.target, + xpx, ypx; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(hasUserCalledHover) { + if('xpx' in evt) xpx = evt.xpx; + else xpx = xaArray[0]._length / 2; + evt.pointerX = xpx + xaArray[0]._offset; - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } + if('ypx' in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + evt.pointerY = ypx + yaArray[0]._offset; } - } + else { + // fire the beforehover event and quit if it returns false + // note that we're only calling this on real mouse events, so + // manual calls to fx.hover will always run. + if(_$Events_156.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + var dbb = evt.target.getBoundingClientRect(); - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // in case hover was called from mouseout into hovertext, + // it's possible you're not actually over the plot anymore + if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { + return _$dragelement_65.unhoverRaw(gd, evt); } + evt.pointerX = evt.offsetX; + evt.pointerY = evt.offsetY; } - } - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + if('xval' in evt) xvalArray = _$helpers_82.flat(subplots, evt.xval); + else xvalArray = _$helpers_82.p2c(xaArray, xpx); - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } + if('yval' in evt) yvalArray = _$helpers_82.flat(subplots, evt.yval); + else yvalArray = _$helpers_82.p2c(yaArray, ypx); + + if(!_$fastIsnumeric_10(xvalArray[0]) || !_$fastIsnumeric_10(yvalArray[0])) { + _$lib_163.warn('Fx.hover failed', evt, gd); + return _$dragelement_65.unhoverRaw(gd, evt); } } -}; -_$cartesian_215.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); + // the pixel distance to beat as a matching point + // in 'x' or 'y' mode this resets for each trace + var distance = Infinity; - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_162.identity); + // find the closest point in each trace + // this is minimum dx and/or dy, depending on mode + // and the pixel position for the label (labelXpx, labelYpx) + for(curvenum = 0; curvenum < searchData.length; curvenum++) { + cd = searchData[curvenum]; - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + // filter out invisible or broken data + if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; - subplotLayers.order(); + trace = cd[0].trace; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + // Explicitly bail out for these two. I don't know how to otherwise prevent + // the rest of this function from running and failing + if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_82.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } - // keep ref to plot group - plotinfo.plotgroup = _$d3_7.select(this); + // within one trace mode can sometimes be overridden + mode = hovermode; - // initialize list of overlay subplots - plotinfo.overlays = []; + // container for new point, also used to pass info into module.hoverPoints + pointData = { + // trace properties + cd: cd, + trace: trace, + xa: xaArray[subploti], + ya: yaArray[subploti], - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); - } + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + // point properties - override all of these + index: false, // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance -_$cartesian_215.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_237.style(gd); -}; + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: undefined, + ySpike: undefined, - var subplotData = [], - overlays = []; + // where and how to display the hover label + color: _$color_43.defaultLine, // trace color + name: trace.name, + x0: undefined, + x1: undefined, + y0: undefined, + y1: undefined, + xLabelVal: undefined, + yLabelVal: undefined, + zLabelVal: undefined, + text: undefined + }; - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + // add ref to subplot object (non-cartesian case) + if(fullLayout[subplotId]) { + pointData.subplot = fullLayout[subplotId]._subplot; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + closedataPreviousLength = hoverData.length; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); + // for a highlighting array, figure out what + // we're searching for with this element + if(mode === 'array') { + var selection = evt[curvenum]; + if('pointNumber' in selection) { + pointData.index = selection.pointNumber; + mode = 'closest'; + } + else { + mode = ''; + if('xval' in selection) { + xval = selection.xval; + mode = 'x'; + } + if('yval' in selection) { + yval = selection.yval; + mode = mode ? 'closest' : 'y'; + } + } } else { - subplotData.push(subplot); + xval = xvalArray[subploti]; + yval = yvalArray[subploti]; } - } - - // main subplots before overlays - subplotData = subplotData.concat(overlays); - return subplotData; -} - -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_209.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_209.layerValue2layerClass[plotinfo.yaxis.layer]; - - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); - - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); - - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); - - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); - - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); - - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + // Now if there is range to look in, find the points to hover. + if(hoverdistance !== 0) { + if(trace._module && trace._module.hoverPoints) { + var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); + if(newPoints) { + var newPoint; + for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { + newPoint = newPoints[newPointNum]; + if(_$fastIsnumeric_10(newPoint.x0) && _$fastIsnumeric_10(newPoint.y0)) { + hoverData.push(cleanPoint(newPoint, hovermode)); + } + } + } + } + else { + _$lib_163.log('Unrecognized trace type in hover:', trace); + } + } - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + // in closest mode, remove any existing (farther) points + // and don't look any farther than this latest point (or points, some + // traces like box & violin make multiple hover labels at once) + if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + // Now if there is range to look in, find the points to draw the spikelines + // Do it only if there is no hoverData + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); + if(closestPoints) { + closestPoints = closestPoints.filter(function(point) { + // some hover points, like scatter fills, do not allow spikes, + // so will generate a hover point but without a valid spikeDistance + return point.spikeDistance <= spikedistance; + }); + } + if(closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes; + }); + if(closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if(_$fastIsnumeric_10(closestVPt.x0) && _$fastIsnumeric_10(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.vLinePoint = tmpPoint; + } + } + } - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes; + }); + if(closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if(_$fastIsnumeric_10(closestHPt.x0) && _$fastIsnumeric_10(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } } - else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + function selectClosestPoint(pointsData, spikedistance) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for(var i = 0; i < pointsData.length; i++) { + thisSpikeDistance = pointsData[i].spikeDistance; + if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { + resultPoint = pointsData[i]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + function fillSpikePoint(point) { + if(!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + var spikelineOpts = { + fullLayout: fullLayout, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + event: evt + }; + var oldspikepoints = gd._spikepoints, + newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); + // Now if it is not restricted by spikedistance option, set the points to draw the spikelines + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_207.idSort); - - // common attributes for all subplots, overlays or not + // if hoverData is empty check for the spikes to draw and quit if there are none + if(hoverData.length === 0) { + var result = _$dragelement_65.unhoverRaw(gd, evt); + if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } + return result; + } - for(var i = 0; i < _$constants_209.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_209.traceLayerClasses[i]); + if(hasCartesian) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } } - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); -} + // lastly, emit custom hover/unhover events + var oldhoverdata = gd._hoverdata, + newhoverdata = []; -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; + // pull out just the data that's useful to + // other people and send it to the event + for(itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + newhoverdata.push(_$helpers_82.makeEventData(pt, pt.trace, pt.cd)); + } - var overlayIdsToRemove = {}; + gd._hoverdata = newhoverdata; - layers.each(function(subplotId) { - var plotgroup = _$d3_7.select(this); + // if there's more than one horz bar trace, + // rotate the labels so they don't overlap + var rotateLabels = hovermode === 'y' && searchData.length > 1; - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + var bgColor = _$color_43.combine( + fullLayout.plot_bgcolor || _$color_43.background, + fullLayout.paper_bgcolor + ); - overlayIdsToRemove[subplotId] = true; + var labelOpts = { + hovermode: hovermode, + rotateLabels: rotateLabels, + bgColor: bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }; - // do not remove individual axis s here - // as other subplots may need them - }); + var hoverLabels = createHoverText(hoverData, labelOpts, gd); - // must remove overlaid subplot trace layers 'manually' + hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + alignHoverText(hoverLabels, rotateLabels); - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true + // we should improve the "fx" API so other plots can use it without these hack. + if(evt.target && evt.target.tagName) { + var hasClickToShow = _$registry_245.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_174(_$d3_7.select(evt.target), hasClickToShow ? 'pointer' : ''); + } - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; + // don't emit events if called manually + if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); - } - } + if(oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); + gd.emit('plotly_hover', { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray + }); } -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); +function createHoverText(hoverData, opts, gd) { + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; - layer.enter().append(nodeType) - .classed(className, true); + // opts.fontFamily/Size are used for the common label + // and as defaults for each hover label, though the individual labels + // can override this. + var fontFamily = opts.fontFamily || _$constants_80.HOVERFONT; + var fontSize = opts.fontSize || _$constants_80.HOVERFONTSIZE; - return layer; -} + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; + var t0 = c0[commonAttr]; + var t00 = (String(t0) || '').split(' ')[0]; + var outerContainerBB = outerContainer.node().getBoundingClientRect(); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; -_$cartesian_215.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_7.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); + // show the common label, if any, on the axis + // never show a common label in array mode, + // even if sometimes there could be one + var showCommonLabel = ( + (t0 !== undefined) && + (c0.distance <= opts.hoverdistance) && + (hovermode === 'x' || hovermode === 'y') + ); - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); + // all hover traces hoverinfo must contain the hovermode + // to have common labels + if(showCommonLabel) { + var i, traceHoverinfo; + var allHaveZ = true; + for(i = 0; i < hoverData.length; i++) { + if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; - image.attr({ - xmlns: _$xmlns_namespaces_147.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); + traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; + var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); + if(parts.indexOf('all') === -1 && + parts.indexOf(hovermode) === -1) { + showCommonLabel = false; + break; + } + } + + // xyz labels put all info in their main label, so have no need of a common label + if(allHaveZ) showCommonLabel = false; } - canvases.each(canvasToImage); -}; + var commonLabel = container.selectAll('g.axistext') + .data(showCommonLabel ? [0] : []); + commonLabel.enter().append('g') + .classed('axistext', true); + commonLabel.exit().remove(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + commonLabel.each(function() { + var label = _$d3_7.select(this); + var lpath = _$lib_163.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_163.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); + lpath.style({ + fill: commonLabelOpts.bgcolor || _$color_43.defaultLine, + stroke: commonLabelOpts.bordercolor || _$color_43.background, + }); -'use strict'; + ltext.text(t0) + .call(_$drawing_68.font, + commonLabelOpts.font.family || fontFamily, + commonLabelOpts.font.size || fontSize, + commonLabelOpts.font.color || _$color_43.background + ) + .call(_$svg_text_utils_184.positionText, 0, 0) + .call(_$svg_text_utils_184.convertToTspans, gd); -var mergeArray = _$lib_162.mergeArray; + label.attr('transform', ''); + var tbb = ltext.node().getBoundingClientRect(); + if(hovermode === 'x') { + ltext.attr('text-anchor', 'middle') + .call(_$svg_text_utils_184.positionText, 0, (xa.side === 'top' ? + (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : + (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); -// arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_253 = function arraysToCalcdata(cd, trace) { - for(var i = 0; i < cd.length; i++) cd[i].i = i; + var topsign = xa.side === 'top' ? '-' : ''; + lpath.attr('d', 'M0,0' + + 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + + 'H' + (HOVERTEXTPAD + tbb.width / 2) + + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + + 'H-' + (HOVERTEXTPAD + tbb.width / 2) + + 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); - mergeArray(trace.text, cd, 'tx'); - mergeArray(trace.hovertext, cd, 'htx'); + label.attr('transform', 'translate(' + + (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + + (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + } + else { + ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') + .call(_$svg_text_utils_184.positionText, + (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), + outerTop - tbb.top - tbb.height / 2); - var marker = trace.marker; - if(marker) { - mergeArray(marker.opacity, cd, 'mo'); - mergeArray(marker.color, cd, 'mc'); + var leftsign = ya.side === 'right' ? '' : '-'; + lpath.attr('d', 'M0,0' + + 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + + 'V' + (HOVERTEXTPAD + tbb.height / 2) + + 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + + 'V-' + (HOVERTEXTPAD + tbb.height / 2) + + 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); - var markerLine = marker.line; - if(markerLine) { - mergeArray(markerLine.color, cd, 'mlc'); - mergeArray(markerLine.width, cd, 'mlw'); + label.attr('transform', 'translate(' + + (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + + (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 the "close but not quite" points + // because of error bars, only take up to a space + hoverData = hoverData.filter(function(d) { + return (d.zLabelVal !== undefined) || + (d[commonAttr] || '').split(' ')[0] === t00; + }); + }); -'use strict'; + // show all the individual labels -/* removed: var _$attributes_280 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_51 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_44 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; + // first create the objects + var hoverLabels = container.selectAll('g.hovertext') + .data(hoverData, function(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); + }); + hoverLabels.enter().append('g') + .classed('hovertext', true) + .each(function() { + var g = _$d3_7.select(this); + // trace name label (rect and text.name) + g.append('rect') + .call(_$color_43.fill, _$color_43.addOpacity(bgColor, 0.8)); + g.append('text').classed('name', true); + // trace data label (path and text.nums) + g.append('path') + .style('stroke-width', '1px'); + g.append('text').classed('nums', true) + .call(_$drawing_68.font, fontFamily, fontSize); + }); + hoverLabels.exit().remove(); -var __extendFlat_254 = _$extend_156.extendFlat; + // then put the text in, position the pointer to the data, + // and figure out sizes + hoverLabels.each(function(d) { + var g = _$d3_7.select(this).attr('transform', ''), + name = '', + text = ''; -var textFontAttrs = _$font_attributes_231({ - editType: 'calc', - arrayOk: true, - -}); + // combine possible non-opaque trace color with bgColor + var baseColor = _$color_43.opacity(d.color) ? d.color : _$color_43.defaultLine; + var traceColor = _$color_43.combine(baseColor, bgColor); -var __scatterMarkerAttrs_254 = _$attributes_280.marker; -var scatterMarkerLineAttrs = __scatterMarkerAttrs_254.line; + // find a contrasting color for border and text + var contrastColor = d.borderColor || _$color_43.contrast(traceColor); -var markerLineWidth = __extendFlat_254({}, - scatterMarkerLineAttrs.width, { dflt: 0 }); + // to get custom 'name' labels pass cleanPoint + if(d.nameOverride !== undefined) d.name = d.nameOverride; -var markerLine = __extendFlat_254({ - width: markerLineWidth, - editType: 'calc' -}, _$makeColorScaleAttributes_51('marker.line')); + if(d.name) { + // strip out our pseudo-html elements from d.name (if it exists at all) + name = _$svg_text_utils_184.plainText(d.name || ''); -var marker = __extendFlat_254({ - line: markerLine, - editType: 'calc' -}, _$makeColorScaleAttributes_51('marker'), { - showscale: __scatterMarkerAttrs_254.showscale, - colorbar: _$attributes_44, - opacity: { - valType: 'number', - arrayOk: true, - dflt: 1, - min: 0, - max: 1, - - editType: 'style', - - } -}); + var nameLength = Math.round(d.nameLength); -var _$attributes_254 = { - x: _$attributes_280.x, - x0: _$attributes_280.x0, - dx: _$attributes_280.dx, - y: _$attributes_280.y, - y0: _$attributes_280.y0, - dy: _$attributes_280.dy, + if(nameLength > -1 && name.length > nameLength) { + if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; + else name = name.substr(0, nameLength); + } + } - text: _$attributes_280.text, - hovertext: _$attributes_280.hovertext, + if(d.zLabel !== undefined) { + if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; + if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; + text += (text ? 'z: ' : '') + d.zLabel; + } + else if(showCommonLabel && d[hovermode + 'Label'] === t0) { + text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; + } + else if(d.xLabel === undefined) { + if(d.yLabel !== undefined) text = d.yLabel; + } + else if(d.yLabel === undefined) text = d.xLabel; + else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; - textposition: { - valType: 'enumerated', - - values: ['inside', 'outside', 'auto', 'none'], - dflt: 'none', - arrayOk: true, - editType: 'calc', - - }, + if(d.text && !Array.isArray(d.text)) { + text += (text ? '
' : '') + d.text; + } - textfont: __extendFlat_254({}, textFontAttrs, { - - }), + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; - insidetextfont: __extendFlat_254({}, textFontAttrs, { - - }), + // if 'text' is empty at this point, + // put 'name' in main label and don't show secondary label + if(text === '') { + // if 'name' is also empty, remove entire label + if(name === '') g.remove(); + text = name; + } - outsidetextfont: __extendFlat_254({}, textFontAttrs, { - - }), + // main label + var tx = g.select('text.nums') + .call(_$drawing_68.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + d.fontColor || contrastColor) + .text(text) + .attr('data-notex', 1) + .call(_$svg_text_utils_184.positionText, 0, 0) + .call(_$svg_text_utils_184.convertToTspans, gd); - constraintext: { - valType: 'enumerated', - values: ['inside', 'outside', 'both', 'none'], - - dflt: 'both', - editType: 'calc', - - }, + var tx2 = g.select('text.name'), + tx2width = 0; - cliponaxis: __extendFlat_254({}, _$attributes_280.cliponaxis, { - - }), + // secondary label for non-empty 'name' + if(name && name !== text) { + tx2.call(_$drawing_68.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + traceColor) + .text(name) + .attr('data-notex', 1) + .call(_$svg_text_utils_184.positionText, 0, 0) + .call(_$svg_text_utils_184.convertToTspans, gd); + tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; + } + else { + tx2.remove(); + g.select('rect').remove(); + } - orientation: { - valType: 'enumerated', - - values: ['v', 'h'], - editType: 'calc+clearAxisTypes', - - }, + g.select('path') + .style({ + fill: traceColor, + stroke: contrastColor + }); + var tbb = tx.node().getBoundingClientRect(), + htx = d.xa._offset + (d.x0 + d.x1) / 2, + hty = d.ya._offset + (d.y0 + d.y1) / 2, + dx = Math.abs(d.x1 - d.x0), + dy = Math.abs(d.y1 - d.y0), + txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, + anchorStartOK, + anchorEndOK; - base: { - valType: 'any', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, + d.ty0 = outerTop - tbb.top; + d.bx = tbb.width + 2 * HOVERTEXTPAD; + d.by = tbb.height + 2 * HOVERTEXTPAD; + d.anchor = 'start'; + d.txwidth = tbb.width; + d.tx2width = tx2width; + d.offset = 0; - offset: { - valType: 'number', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, - - width: { - valType: 'number', - dflt: null, - min: 0, - arrayOk: true, - - editType: 'calc', - - }, - - marker: marker, - - selected: { - marker: { - opacity: _$attributes_280.selected.marker.opacity, - color: _$attributes_280.selected.marker.color, - editType: 'style' - }, - textfont: _$attributes_280.selected.textfont, - editType: 'style' - }, - unselected: { - marker: { - opacity: _$attributes_280.unselected.marker.opacity, - color: _$attributes_280.unselected.marker.color, - editType: 'style' - }, - textfont: _$attributes_280.unselected.textfont, - editType: 'style' - }, - - r: _$attributes_280.r, - t: _$attributes_280.t, - - _deprecated: { - bardir: { - valType: 'enumerated', - - editType: 'calc', - values: ['v', 'h'], - + if(rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + hty += dy / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } + else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + htx += dx / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_162 = require('../../lib'); */; - -var _$calcSelection_282 = function calcSelection(cd, trace) { - if(_$lib_162.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_162.tagSelected(cd, trace); - } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + tx.attr('text-anchor', d.anchor); + if(tx2width) tx2.attr('text-anchor', d.anchor); + g.attr('transform', 'translate(' + htx + ',' + hty + ')' + + (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); + }); + return hoverLabels; +} -'use strict'; +// Make groups of touching points, and within each group +// move each point so that no labels overlap, but the average +// label position is the same as it was before moving. Indicentally, +// this is equivalent to saying all the labels are on equal linear +// springs about their initial position. Initially, each point is +// its own group, but as we find overlaps we will clump the points. +// +// Also, there are hard constraints at the edges of the graphs, +// that push all groups to the middle so they are visible. I don't +// know what happens if the group spans all the way from one edge to +// the other, though it hardly matters - there's just too much +// information then. +function hoverAvoidOverlaps(hoverData, ax, fullLayout) { + var nummoves = 0, -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_255 = _$lib_162.isArrayOrTypedArray; + // make groups of touching points + pointgroups = hoverData + .map(function(d, i) { + var axis = d[ax]; + return [{ + i: i, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, + pmin: 0, + pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) + }]; + }) + .sort(function(a, b) { return a[0].posref - b[0].posref; }), + donepositioning, + topOverlap, + bottomOverlap, + i, j, + pti, + sumdp; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_50 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_253 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_282 = require('../scatter/calc_selection'); */; + function constrainGroup(grp) { + var minPt = grp[0], + maxPt = grp[grp.length - 1]; -var _$calc_255 = function calc(gd, trace) { - // depending on bar direction, set position and size axes - // and data ranges - // note: this logic for choosing orientation is - // duplicated in graph_obj->setstyles + // overlap with the top - positive vals are overlaps + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; - var xa = _$axes_204.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_204.getFromId(gd, trace.yaxis || 'y'), - orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), - sa, pos, size, i, scalendar; + // overlap with the bottom - positive vals are overlaps + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; - if(orientation === 'h') { - sa = xa; - size = xa.makeCalcdata(trace, 'x'); - pos = ya.makeCalcdata(trace, 'y'); + // check for min overlap first, so that we always + // see the largest labels + // allow for .01px overlap, so we don't get an + // infinite loop from rounding errors + if(topOverlap > 0.01) { + for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; + donepositioning = false; + } + if(bottomOverlap < 0.01) return; + if(topOverlap < -0.01) { + // make sure we're not pushing back and forth + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + donepositioning = false; + } + if(!donepositioning) return; - // 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. - scalendar = trace.xcalendar; - } - else { - sa = ya; - size = ya.makeCalcdata(trace, 'y'); - pos = xa.makeCalcdata(trace, 'x'); - scalendar = trace.ycalendar; - } + // no room to fix positioning, delete off-screen points - // create the "calculated data" to plot - var serieslen = Math.min(pos.length, size.length); - var cd = new Array(serieslen); + // first see how many points we need to delete + var deleteCount = 0; + for(i = 0; i < grp.length; i++) { + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } - // set position and size - for(i = 0; i < serieslen; i++) { - cd[i] = { p: pos[i], s: size[i] }; + // start by deleting points whose data is off screen + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; - if(trace.ids) { - cd[i].id = String(trace.ids[i]); + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } } - } + for(i = 0; i < grp.length; i++) { + if(deleteCount <= 0) break; + pti = grp[i]; - // set base - var base = trace.base, - b; + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; - if(__isArrayOrTypedArray_255(base)) { - for(i = 0; i < Math.min(base.length, cd.length); i++) { - b = sa.d2c(base[i], 0, scalendar); - if(_$fastIsnumeric_10(b)) { - cd[i].b = +b; - cd[i].hasB = 1; + // shift the whole group minus into this new space + bottomOverlap = pti.size * 2; + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; } - else cd[i].b = 0; - } - for(; i < cd.length; i++) { - cd[i].b = 0; } - } - else { - b = sa.d2c(base, 0, scalendar); - var hasBase = _$fastIsnumeric_10(b); - b = hasBase ? b : 0; - for(i = 0; i < cd.length; i++) { - cd[i].b = b; - if(hasBase) cd[i].hasB = 1; + // then delete points that go off the bottom + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } } } - // auto-z and autocolorscale if applicable - if(_$hasColorscale_57(trace, 'marker')) { - _$calc_50(trace, trace.marker.color, 'marker', 'c'); - } - if(_$hasColorscale_57(trace, 'marker.line')) { - _$calc_50(trace, trace.marker.line.color, 'marker.line', 'c'); - } - - _$arraysToCalcdata_253(cd, trace); - _$calcSelection_282(cd, trace); - - return cd; -}; + // loop through groups, combining them if they overlap, + // until nothing moves + while(!donepositioning && nummoves <= hoverData.length) { + // to avoid infinite loops, don't move more times + // than there are traces + nummoves++; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // assume nothing will move in this iteration, + // reverse this if it does + donepositioning = true; + i = 0; + while(i < pointgroups.length - 1) { + // the higher (g0) and lower (g1) point group + var g0 = pointgroups[i], + g1 = pointgroups[i + 1], + // the lowest point in the higher group (p0) + // the highest point in the lower group (p1) + p0 = g0[g0.length - 1], + p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; -'use strict'; + // Only group points that lie on the same axes + if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { + // push the new point(s) added to this group out of the way + for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_53 = require('../../components/colorscale/defaults'); */; + // add them to the group + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); -var _$handleStyleDefaults_266 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { - coerce('marker.color', defaultColor); + // adjust for minimum average movement + sumdp = 0; + for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } + else i++; + } - if(_$hasColorscale_57(traceIn, 'marker')) { - _$colorScaleDefaults_53( - traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} - ); + // check if we're going off the plot on either side and fix + pointgroups.forEach(constrainGroup); } - coerce('marker.line.color', _$color_43.defaultLine); - - if(_$hasColorscale_57(traceIn, 'marker.line')) { - _$colorScaleDefaults_53( - traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} - ); + // now put these offsets into hoverData + for(i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for(j = grp.length - 1; j >= 0; j--) { + var pt = grp[j], + hoverPt = hoverData[pt.i]; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } } +} - coerce('marker.line.width'); - coerce('marker.opacity'); - coerce('selected.marker.color'); - coerce('unselected.marker.color'); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; +function alignHoverText(hoverLabels, rotateLabels) { + // finally set the text positioning relative to the data and draw the + // box around it + hoverLabels.each(function(d) { + var g = _$d3_7.select(this); + if(d.del) { + g.remove(); + return; + } + var horzSign = d.anchor === 'end' ? -1 : 1, + tx = g.select('text.nums'), + alignShift = {start: 1, end: -1, middle: 0}[d.anchor], + txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), + tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), + offsetX = 0, + offsetY = d.offset; + if(d.anchor === 'middle') { + txx -= d.tx2width / 2; + tx2x += d.txwidth / 2 + HOVERTEXTPAD; + } + if(rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = d.offset * YSHIFTX; + } -/* removed: var _$registry_244 = require('../../registry'); */; + g.select('path').attr('d', d.anchor === 'middle' ? + // middle aligned: rect centered on data + ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + + 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : + // left or right aligned: side rect with arrow to data + ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + + 'v' + (d.by / 2 - HOVERARROWSIZE) + + 'h' + (horzSign * d.bx) + + 'v-' + d.by + + 'H' + (horzSign * HOVERARROWSIZE + offsetX) + + 'V' + (offsetY - HOVERARROWSIZE) + + 'Z')); + tx.call(_$svg_text_utils_184.positionText, + txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); -var _$handleXYDefaults_304 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { - var len, - x = coerce('x'), - y = coerce('y'); + if(d.tx2width) { + g.select('text.name') + .call(_$svg_text_utils_184.positionText, + tx2x + alignShift * HOVERTEXTPAD + offsetX, + offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + g.select('rect') + .call(_$drawing_68.setRect, + tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, + offsetY - d.by / 2 - 1, + d.tx2width, d.by + 2); + } + }); +} - var handleCalendarDefaults = _$registry_244.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); +function cleanPoint(d, hovermode) { + var index = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index] || {}; - if(x) { - if(y) { - len = Math.min(x.length, y.length); - } - else { - len = x.length; - coerce('y0'); - coerce('dy'); - } - } - else { - if(!y) return 0; + var getVal = Array.isArray(index) ? + function(calcKey, traceKey) { + return _$lib_163.castOption(cd0, index, calcKey) || + _$lib_163.extractOption({}, trace, '', traceKey); + } : + function(calcKey, traceKey) { + return _$lib_163.extractOption(cd, trace, calcKey, traceKey); + }; - len = traceOut.y.length; - coerce('x0'); - coerce('dx'); + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if(val) d[key] = val; } - traceOut._length = len; + fill('hoverinfo', 'hi', 'hoverinfo'); + fill('color', 'hbg', 'hoverlabel.bgcolor'); + fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); + fill('fontFamily', 'htf', 'hoverlabel.font.family'); + fill('fontSize', 'hts', 'hoverlabel.font.size'); + fill('fontColor', 'htc', 'hoverlabel.font.color'); + fill('nameLength', 'hnl', 'hoverlabel.namelength'); - return len; -}; + d.posref = hovermode === 'y' ? + (d.xa._offset + (d.x0 + d.x1) / 2) : + (d.ya._offset + (d.y0 + d.y1) / 2); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // then constrain all the positions to be on the plot + d.x0 = _$lib_163.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_163.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_163.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_163.constrain(d.y1, 0, d.ya._length); + // and convert the x and y label values into formatted text + if(d.xLabelVal !== undefined) { + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_205.hoverLabelText(d.xa, d.xLabelVal); + d.xVal = d.xa.c2d(d.xLabelVal); + } + if(d.yLabelVal !== undefined) { + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_205.hoverLabelText(d.ya, d.yLabelVal); + d.yVal = d.ya.c2d(d.yLabelVal); + } -'use strict'; + // Traces like heatmaps generate the zLabel in their hoverPoints function + if(d.zLabelVal !== undefined && d.zLabel === undefined) { + d.zLabel = String(d.zLabelVal); + } -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$registry_244 = require('../../registry'); */; + // for box means and error bars, add the range to the label + if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { + var xeText = _$axes_205.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + if(d.xerrneg !== undefined) { + d.xLabel += ' +' + xeText + ' / -' + + _$axes_205.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + else d.xLabel += ' ± ' + xeText; -/* removed: var _$handleXYDefaults_304 = require('../scatter/xy_defaults'); */; -/* removed: var _$handleStyleDefaults_266 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_254 = require('./attributes'); */; + // small distance penalty for error bars, so that if there are + // traces with errors and some without, the error bar label will + // hoist up to the point + if(hovermode === 'x') d.distance += 1; + } + if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { + var yeText = _$axes_205.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + if(d.yerrneg !== undefined) { + d.yLabel += ' +' + yeText + ' / -' + + _$axes_205.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + } + else d.yLabel += ' ± ' + yeText; -var _$supplyDefaults_256 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_162.coerce(traceIn, traceOut, _$attributes_254, attr, dflt); + if(hovermode === 'y') d.distance += 1; } - var coerceFont = _$lib_162.coerceFont; + var infomode = d.hoverinfo || d.trace.hoverinfo; - var len = _$handleXYDefaults_304(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; + if(infomode !== 'all') { + infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); + if(infomode.indexOf('x') === -1) d.xLabel = undefined; + if(infomode.indexOf('y') === -1) d.yLabel = undefined; + if(infomode.indexOf('z') === -1) d.zLabel = undefined; + if(infomode.indexOf('text') === -1) d.text = undefined; + if(infomode.indexOf('name') === -1) d.name = undefined; } - coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); - coerce('base'); - coerce('offset'); - coerce('width'); + return d; +} - coerce('text'); - coerce('hovertext'); +function createSpikelines(closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var evt = opts.event; + var xa, + ya; - var textPosition = coerce('textposition'); + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; - var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', - hasInside = hasBoth || textPosition === 'inside', - hasOutside = hasBoth || textPosition === 'outside'; + // Remove old spikeline items + container.selectAll('.spikeline').remove(); - if(hasInside || hasOutside) { - var textFont = coerceFont(coerce, 'textfont', layout.font); - if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); - if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); - coerce('constraintext'); - coerce('selected.textfont.color'); - coerce('unselected.textfont.color'); - coerce('cliponaxis'); - } + if(!(showX || showY)) return; - _$handleStyleDefaults_266(traceIn, traceOut, coerce, defaultColor, layout); + var contrastColor = _$color_43.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); - // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_244.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_43.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_43.defaultLine, {axis: 'x', inherit: 'y'}); + // Horizontal line (to y-axis) + if(showY) { + var hLinePoint = closestPoints.hLinePoint, + hLinePointX, + hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; - _$lib_162.coerceSelectionMarkerOpacity(traceOut, coerce); -}; + if(ySnap === 'cursor') { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = _$tinycolor_25.readability(hLinePoint.color, contrastColor) < 1.5 ? + _$color_43.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode, + yThickness = ya.spikethickness, + yColor = ya.spikecolor || dfltHLineColor, + yBB = ya._boundingBox, + xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, + xBase, + xEndSpike; -var _$client_14 = true; -var _$hasHover_12 = {}; -(function (global){ -'use strict' - -/* removed: var _$client_14 = require('is-browser') */; -var hasHover - -if (typeof global.matchMedia === 'function') { - hasHover = !global.matchMedia('(hover: none)').matches -} -else { - hasHover = _$client_14 -} - -_$hasHover_12 = hasHover + if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { + if(yMode.indexOf('toaxis') !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; + } + if(yMode.indexOf('across') !== -1) { + xBase = ya._counterSpan[0]; + xEndSpike = ya._counterSpan[1]; + } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -'use strict' - -/* removed: var _$client_14 = require('is-browser') */; - -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 -} - -var _$hasPassiveEvents_13 = _$client_14 && detect() + // Foreground horizontal line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness, + 'stroke': yColor, + 'stroke-dasharray': _$drawing_68.dashStyle(ya.spikedash, yThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); -var rootPosition = { left: 0, top: 0 } + // Background horizontal Line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + // Y axis marker + if(yMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), + 'cy': hLinePointY, + 'r': yThickness, + 'fill': yColor + }) + .classed('spikeline', true); + } + } -var _$mouseEventOffset_15 = mouseEventOffset -function mouseEventOffset (ev, target, out) { - target = target || ev.currentTarget || ev.srcElement - if (!Array.isArray(out)) { - out = [ 0, 0 ] - } - var cx = ev.clientX || 0 - var cy = ev.clientY || 0 - var rect = getBoundingClientOffset(target) - out[0] = cx - rect.left - out[1] = cy - rect.top - return out + if(showX) { + var vLinePoint = closestPoints.vLinePoint, + vLinePointX, + vLinePointY; + + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; + + if(xSnap === 'cursor') { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; + } + var dfltVLineColor = _$tinycolor_25.readability(vLinePoint.color, contrastColor) < 1.5 ? + _$color_43.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode, + xThickness = xa.spikethickness, + xColor = xa.spikecolor || dfltVLineColor, + xBB = xa._boundingBox, + yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, + yBase, + yEndSpike; + + if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { + if(xMode.indexOf('toaxis') !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if(xMode.indexOf('across') !== -1) { + yBase = xa._counterSpan[0]; + yEndSpike = xa._counterSpan[1]; + } + + // Foreground vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness, + 'stroke': xColor, + 'stroke-dasharray': _$drawing_68.dashStyle(xa.spikedash, xThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + + // X axis marker + if(xMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': vLinePointX, + 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), + 'r': xThickness, + 'fill': xColor + }) + .classed('spikeline', true); + } + } } -function getBoundingClientOffset (element) { - if (element === window || - element === document || - element === document.body) { - return rootPosition - } else { - return element.getBoundingClientRect() - } +function hoverChanged(gd, evt, oldhoverdata) { + // don't emit any events if nothing changed + if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + + for(var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i], + newPt = gd._hoverdata[i]; + if(oldPt.curveNumber !== newPt.curveNumber || + String(oldPt.pointNumber) !== String(newPt.pointNumber)) { + return true; + } + } + return false; +} + +function spikesChanged(gd, oldspikepoints) { + // don't relayout the plot because of new spikelines if spikelines points didn't change + if(!oldspikepoints) return true; + if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || + oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint + ) return true; + return false; } /** @@ -30850,28 +31439,33 @@ function getBoundingClientOffset (element) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$registry_245 = require('../../registry'); */; +var hover = _$hover_83.hover; -// 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 -var _$align_63 = function align(v, dv, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0), - vmax = vmin + dv / (v1 - v0), - vc = (vmin + vmax) / 2; +var _$click_79 = function click(gd, evt, subplot) { + var annotationsDone = _$registry_245.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); - // explicitly specified anchor - if(anchor === 'left' || anchor === 'bottom') return vmin; - if(anchor === 'center' || anchor === 'middle') return vc; - if(anchor === 'right' || anchor === 'top') return vmax; + // 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); + } - // automatic based on position - if(vmin < (2 / 3) - vc) return vmin; - if(vmax > (4 / 3) - vc) return vmax; - return vc; + 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(); + } }; /** @@ -30882,33 +31476,39 @@ var _$align_63 = function align(v, dv, v0, v1, anchor) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +var _$handleHoverLabelDefaults_84 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { + opts = opts || {}; -// 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'] -]; + coerce('hoverlabel.bgcolor', opts.bgcolor); + coerce('hoverlabel.bordercolor', opts.bordercolor); + coerce('hoverlabel.namelength', opts.namelength); + _$lib_163.coerceFont(coerce, 'hoverlabel.font', opts.font); +}; -var _$getCursor_64 = 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_162.constrain(Math.floor(x * 3), 0, 2); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(yanchor === 'bottom') y = 0; - else if(yanchor === 'middle') y = 1; - else if(yanchor === 'top') y = 2; - else y = _$lib_162.constrain(Math.floor(y * 3), 0, 2); +'use strict'; - return cursorset[y][x]; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$attributes_77 = require('./attributes'); */; +/* removed: var _$handleHoverLabelDefaults_84 = require('./hoverlabel_defaults'); */; + +var _$supplyDefaults_81 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_163.coerce(traceIn, traceOut, _$attributes_77, attr, dflt); + } + + _$handleHoverLabelDefaults_84(traceIn, traceOut, coerce, layout.hoverlabel); }; /** @@ -30921,330 +31521,169 @@ var _$getCursor_64 = function getCursor(x, y, xanchor, yanchor) { 'use strict'; -var _$constants_80 = { - // hover labels for multiple horizontal bars get tilted by this angle - YANGLE: 60, +/* removed: var _$constants_80 = require('./constants'); */; - // size and display constants for hover text +var __fontAttrs_86 = _$font_attributes_231({ + editType: 'none', + +}); +__fontAttrs_86.family.dflt = _$constants_80.HOVERFONT; +__fontAttrs_86.size.dflt = _$constants_80.HOVERFONTSIZE; - // pixel size of hover arrows - HOVERARROWSIZE: 6, - // pixels padding around text - HOVERTEXTPAD: 3, - // hover font - HOVERFONTSIZE: 13, - HOVERFONT: 'Arial, sans-serif', +var _$layout_attributes_86 = { + dragmode: { + valType: 'enumerated', + + values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], + dflt: 'zoom', + editType: 'modebar', + + }, + hovermode: { + valType: 'enumerated', + + values: ['x', 'y', 'closest', false], + editType: 'modebar', + + }, + hoverdistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + spikedistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'none', + + }, + bordercolor: { + valType: 'color', + + editType: 'none', + + }, + font: __fontAttrs_86, + namelength: { + valType: 'integer', + min: -1, + dflt: 15, + + editType: 'none', + + }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + + editType: 'none' + } +}; - // minimum time (msec) between hover calls - HOVERMINTIME: 50, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // ID suffix (with fullLayout._uid) for hover events in the throttle cache - HOVERID: '-hover' -}; +'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. +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -var _$EventEmitter_9 = EventEmitter; +var _$supplyLayoutDefaults_87 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); + } -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; + var hovermodeDflt; + if(layoutOut._has('cartesian')) { + // flag for 'horizontal' plots: + // determines the state of the mode bar 'compare' hovermode button + layoutOut._isHoriz = isHoriz(fullData); + hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + } + else hovermodeDflt = 'closest'; -// 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. -EventEmitter.defaultMaxListeners = 10; + var hoverMode = coerce('hovermode', hovermodeDflt); + if(hoverMode) { + coerce('hoverdistance'); + coerce('spikedistance'); + } -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; + // if only mapbox or geo subplots is present on graph, + // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, + // so that the correct modebar button is active + var hasMapbox = layoutOut._has('mapbox'); + var hasGeo = layoutOut._has('geo'); + var len = layoutOut._basePlotModules.length; + + if(layoutOut.dragmode === 'zoom' && ( + ((hasMapbox || hasGeo) && len === 1) || + (hasMapbox && hasGeo && len === 2) + )) { + layoutOut.dragmode = 'pan'; + } }; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; +function isHoriz(fullData) { + var out = true; - if (!this._events) - this._events = {}; + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } + if(trace.orientation !== 'h') { + out = false; + break; + } } - } - handler = this._events[type]; + return out; +} - if (isUndefined(handler)) - return false; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; +'use strict'; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$handleHoverLabelDefaults_84 = require('./hoverlabel_defaults'); */; +/* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); +var _$supplyLayoutGlobalDefaults_88 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce(attr, dflt) { + return _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); + _$handleHoverLabelDefaults_84(layoutIn, layoutOut, coerce); }; -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31253,164 +31692,75 @@ function isUndefined(arg) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* global jQuery:false */ - -var __EventEmitter_155 = _$EventEmitter_9.EventEmitter; - -var Events = { - - init: function(plotObj) { - - /* - * If we have already instantiated an emitter for this plot - * return early. - */ - if(plotObj._ev instanceof __EventEmitter_155) return plotObj; - - var ev = new __EventEmitter_155(); - var internalEv = new __EventEmitter_155(); - - /* - * Assign to plot._ev while we still live in a land - * where plot is a DOM element with stuff attached to it. - * In the future we can make plot the event emitter itself. - */ - plotObj._ev = ev; - - /* - * Create a second event handler that will manage events *internally*. - * This allows parts of plotly to respond to thing like relayout without - * having to use the user-facing event handler. They cannot peacefully - * coexist on the same handler because a user invoking - * plotObj.removeAllListeners() would detach internal events, breaking - * plotly. - */ - plotObj._internalEv = internalEv; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$helpers_82 = require('./helpers'); */; +/* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; - /* - * Assign bound methods from the ev to the plot object. These methods - * will reference the 'this' of plot._ev even though they are methods - * of plot. This will keep the event machinery away from the plot object - * which currently is often a DOM element but presents an API that will - * continue to function when plot becomes an emitter. Not all EventEmitter - * methods have been bound to `plot` as some do not currently add value to - * the Plotly event API. - */ - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); +var _$fx_85 = { + moduleType: 'component', + name: 'fx', - /* - * Create funtions for managing internal events. These are *only* triggered - * by the mirroring of external events via the emit function. - */ - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); + constants: _$constants_80, + schema: { + layout: _$layout_attributes_86 + }, - /* - * We must wrap emit to continue to support JQuery events. The idea - * is to check to see if the user is using JQuery events, if they are - * we emit JQuery events to trigger user handlers as well as the EventEmitter - * events. - */ - plotObj.emit = function(event, data) { - if(typeof jQuery !== 'undefined') { - jQuery(plotObj).trigger(event, data); - } + attributes: _$attributes_77, + layoutAttributes: _$layout_attributes_86, - ev.emit(event, data); - internalEv.emit(event, data); - }; + supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_88, + supplyDefaults: _$supplyDefaults_81, + supplyLayoutDefaults: _$supplyLayoutDefaults_87, - return plotObj; - }, + calc: _$calc_78, - /* - * This function behaves like jQueries triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - * - * Note: triggerHandler has been recommended for deprecation in v2.0.0, - * so the additional behavior of triggerHandler triggering internal events - * is deliberate excluded in order to avoid reinforcing more usage. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - /* - * If Jquery exists run all its handlers for this event and - * collect the return value of the LAST handler function - */ - if(typeof jQuery !== 'undefined') { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); - } + getDistanceFunction: _$helpers_82.getDistanceFunction, + getClosest: _$helpers_82.getClosest, + inbox: _$helpers_82.inbox, + quadrature: _$helpers_82.quadrature, + appendArrayPointValue: _$helpers_82.appendArrayPointValue, - /* - * Now run all the node style event handlers - */ - var ev = plotObj._ev; - if(!ev) return jQueryHandlerValue; + castHoverOption: castHoverOption, + castHoverinfo: castHoverinfo, - var handlers = ev._events[event]; - if(!handlers) return jQueryHandlerValue; + hover: _$hover_83.hover, + unhover: _$dragelement_65.unhover, - /* - * handlers can be function or an array of functions - */ - if(typeof handlers === 'function') handlers = [handlers]; - var lastHandler = handlers.pop(); + loneHover: _$hover_83.loneHover, + loneUnhover: loneUnhover, - /* - * Call all the handlers except the last one. - */ - for(var i = 0; i < handlers.length; i++) { - handlers[i](data); - } + click: _$click_79 +}; - /* - * Now call the final handler and collect its value - */ - nodeEventHandlerValue = lastHandler(data); +function loneUnhover(containerOrSelection) { + // duck type whether the arg is a d3 selection because ie9 doesn't + // handle instanceof like modern browsers do. + var selection = _$lib_163.isD3Selection(containerOrSelection) ? + containerOrSelection : + _$d3_7.select(containerOrSelection); - /* - * Return either the jquery handler value if it exists or the - * nodeEventHandler value. Jquery event value superceeds nodejs - * events for backwards compatability reasons. - */ - return jQueryHandlerValue !== undefined ? jQueryHandlerValue : - nodeEventHandlerValue; - }, + selection.selectAll('g.hovertext').remove(); + selection.selectAll('.spikeline').remove(); +} - purge: function(plotObj) { - delete plotObj._ev; - delete plotObj.on; - delete plotObj.once; - delete plotObj.removeListener; - delete plotObj.removeAllListeners; - delete plotObj.emit; +// helpers for traces that use Fx.loneHover - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; +function castHoverOption(trace, ptNumber, attr) { + return _$lib_163.castOption(trace, ptNumber, 'hoverlabel.' + attr); +} - return plotObj; +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return _$lib_163.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } -}; - -var _$Events_155 = Events; + return _$lib_163.castOption(trace, ptNumber, 'hoverinfo', _coerce); +} -var _$unhover_66 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31419,56 +31769,25 @@ var _$unhover_66 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; - -/* removed: var _$Events_155 = require('../../lib/events'); */; -/* removed: var _$throttle_184 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_160 = require('../../lib/get_graph_div'); */; - -/* removed: var _$constants_80 = require('../fx/constants'); */; - -var unhover = _$unhover_66 = {}; - - -unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_160(gd); - - // Important, clear any queued hovers - if(gd._fullLayout) { - _$throttle_184.clear(gd._fullLayout._uid + _$constants_80.HOVERID); - } - - unhover.raw(gd, evt, subplot); -}; - - -// remove hover effects on mouse out, and emit unhover event -unhover.raw = function unhoverRaw(gd, evt) { +/** + * 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 + */ +var _$clearGlCanvases_152 = function clearGlCanvases(gd) { var fullLayout = gd._fullLayout; - var oldhoverdata = gd._hoverdata; - - if(!evt) evt = {}; - if(evt.target && - _$Events_155.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 + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); }); } }; -var _$dragelement_65 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31480,2142 +31799,2402 @@ var _$dragelement_65 = {}; 'use strict'; -/* removed: var _$mouseEventOffset_15 = require('mouse-event-offset'); */; -/* removed: var _$hasHover_12 = require('has-hover'); */; -/* removed: var _$hasPassiveEvents_13 = require('has-passive-events'); */; +var FROM_BL = _$alignment_143.FROM_BL; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; +var _$scaleZoom_221 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } -/* removed: var _$constants_209 = require('../../plots/cartesian/constants'); */; -/* removed: var _$interactions_144 = require('../../constants/interactions'); */; + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; -var dragElement = _$dragelement_65 = {}; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; -dragElement.align = _$align_63; -dragElement.getCursor = _$getCursor_64; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$unhover_66 = require('./unhover'); */; -dragElement.unhover = _$unhover_66.wrapped; -dragElement.unhoverRaw = _$unhover_66.raw; +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; -/** - * 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 DBLCLICKDELAY = _$interactions_144.DBLCLICKDELAY; - var element = options.element; - - var startX, - startY, - newMouseDownTime, - cursor, - dragCover, - initialEvent, - initialTarget, - rightClick; - - if(!gd._mouseDownTime) gd._mouseDownTime = 0; + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - element.style.pointerEvents = 'all'; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; +} - element.onmousedown = onStart; +var _$BuildLog_17 = BuildLog; - if(!_$hasPassiveEvents_13) { - element.ontouchstart = onStart; - } - else { - if(element._ontouchstart) { - element.removeEventListener('touchstart', element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener('touchstart', onStart, {passive: false}); - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - function _clampFn(dx, dy, minDrag) { - if(Math.abs(dx) < minDrag) dx = 0; - if(Math.abs(dy) < minDrag) dy = 0; - return [dx, dy]; - } +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// - var clampFn = options.clampFn || _clampFn; +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; - function onStart(e) { - e.preventDefault(); + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; - // 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; + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { - // in a click train - numClicks += 1; - } - else { - // new click train - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; - if(options.prepFn) options.prepFn(e, startX, startY); + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - if(_$hasHover_12 && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } - else if(!_$hasHover_12) { - // 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; - } + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - document.addEventListener('mousemove', onMove); - document.addEventListener('mouseup', onDone); - document.addEventListener('touchmove', onMove); - document.addEventListener('touchend', onDone); + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; - return; - } + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; - function onMove(e) { - e.preventDefault(); + // categorize where intersection point is along A and B - var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_209.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - if(dx || dy) { - gd._dragged = true; - dragElement.unhover(gd); - } + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; - return; - } + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside - function onDone(e) { - document.removeEventListener('mousemove', onMove); - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchmove', onMove); - document.removeEventListener('touchend', onDone); + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} - e.preventDefault(); +var _$Epsilon_18 = Epsilon; - if(_$hasHover_12) { - _$lib_162.removeElement(dragCover); - } - else if(cursor) { - dragCover.documentElement.style.cursor = cursor; - cursor = null; - } +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if(!gd._dragging) { - gd._dragged = false; - return; - } - gd._dragging = false; +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// - // don't count as a dblClick unless the mouseUp is also within - // the dblclick delay - if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - if(gd._dragged) { - if(options.doneFn) options.doneFn(e); - } - else { - if(options.clickFn) options.clickFn(numClicks, initialEvent); + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - // 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; + // 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] }); + } - 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); - } + // the first LineString is considered the outside + var out = LineString(coords[0]); - initialTarget.dispatchEvent(e2); - } - } + // 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]))); - finishDrag(gd); + return out; + } - gd._dragged = false; + 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'); + }, - return; - } -}; + // 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)); -function coverSlip() { - var cover = document.createElement('div'); + // 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); + } - 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'; + // calculate inside heirarchy + // + // _____________________ _______ roots -> A -> F + // | A | | F | | | + // | _______ _______ | | ___ | +-- B +-- G + // | | B | | C | | | | | | | | + // | | ___ | | ___ | | | | | | | +-- D + // | | | D | | | | E | | | | | G | | | + // | | |___| | | |___| | | | | | | +-- C + // | |_______| |_______| | | |___| | | + // |_____________________| |_______| +-- E - document.body.appendChild(cover); + function newNode(region){ + return { + region: region, + children: [] + }; + } - return cover; -} + var roots = newNode(null); -dragElement.coverSlip = coverSlip; + 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; + } + } -function finishDrag(gd) { - gd._dragging = false; - if(gd._replotPending) _$registry_244.call('plot', gd); -} - -function pointerOffset(e) { - return _$mouseEventOffset_15( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); -} + // 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--; + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // now we can add ourselves + root.children.push(node); + } -'use strict'; + // 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); + } -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$registry_244 = require('../../registry'); */; + // 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 -var _$calc_78 = function calc(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - function makeCoerceHoverInfo(trace) { - return function(val) { - return _$lib_162.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); - }; - } + 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; + } - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + var geopolys = []; - // 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_244.traceIs(trace, 'pie')) continue; + 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])); + } - var fillFn = _$registry_244.traceIs(trace, '2dMap') ? paste : _$lib_162.fillArray; + 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); + } - fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - if(!trace.hoverlabel) continue; + // lastly, construct the approrpriate GeoJSON object - 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'); - } + 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 + }; + } }; -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_162.identity; - - if(Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); - } -} - -var _$helpers_82 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$GeoJSON_19 = GeoJSON; -'use strict'; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$lib_162 = require('../../lib'); */; +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// -// look for either subplot or xaxis and yaxis attributes -_$helpers_82.getSubplot = function getSubplot(trace) { - return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } }; -// convenience functions for mapping all relevant axes -_$helpers_82.flat = function flat(subplots, v) { - var out = new Array(subplots.length); - for(var i = 0; i < subplots.length; i++) { - out[i] = v; - } - return out; -}; +var _$LinkedList_21 = LinkedList; -_$helpers_82.p2c = function p2c(axArray, v) { - var out = new Array(axArray.length); - for(var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); - } - return out; -}; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -_$helpers_82.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { - if(mode === 'closest') return dxy || _$helpers_82.quadrature(dx, dy); - return mode === 'x' ? dx : dy; -}; +// +// this is the core work-horse +// -_$helpers_82.getClosest = function getClosest(cd, distfn, pointData) { - // do we already have a point number? (array mode only) - if(pointData.index !== false) { - if(pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } - else pointData.index = false; - } - else { - // apply the distance function to each data point - // this is the longest loop... if this bogs down, we may need - // to create pre-sorted data (by x or y), not sure how to - // do this for 'closest' - for(var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if(newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } - } - } - return pointData; -}; +/* removed: var _$LinkedList_21 = require('./linked-list'); */; -/* - * pseudo-distance function for hover effects on areas: inside the region - * distance is finite (`passVal`), outside it's Infinity. - * - * @param {number} v0: signed difference between the current position and the left edge - * @param {number} v1: signed difference between the current position and the right edge - * @param {number} passVal: the value to return on success - */ -_$helpers_82.inbox = function inbox(v0, v1, passVal) { - return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; -}; +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm -_$helpers_82.quadrature = function quadrature(dx, dy) { - return function(di) { - var x = dx(di), - y = dy(di); - return Math.sqrt(x * x + y * y); - }; -}; + // + // segment creation + // -/** Fill event data point object for hover and selection. - * Invokes _module.eventData if present. - * - * N.B. note that point 'index' corresponds to input data array index - * whereas 'number' is its post-transform version. - * - * If the hovered/selected pt corresponds to an multiple input points - * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' - * are include in the event data. - * - * @param {object} pt - * @param {object} trace - * @param {object} cd - * @return {object} - */ -_$helpers_82.makeEventData = function makeEventData(pt, trace, cd) { - // hover uses 'index', select uses 'pointNumber' - var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber: pointNumber - }; + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } - if(trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; + // + // event logic + // - if(pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; - } + var event_root = _$LinkedList_21.create(); - if(trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if('xVal' in pt) out.x = pt.xVal; - else if('x' in pt) out.x = pt.x; + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same - if('yVal' in pt) out.y = pt.yVal; - else if('y' in pt) out.y = pt.y; + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - if(pt.xa) out.xaxis = pt.xa; - if(pt.ya) out.yaxis = pt.ya; - if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; - } + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start - _$helpers_82.appendArrayPointValue(out, trace, pointNumber); + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } - return out; -}; + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } -/** Appends values inside array attributes corresponding to given point number - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {number|Array(number)} pointNumber : point number. May be a length-2 array - * [row, col] to dig into 2D arrays - */ -_$helpers_82.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_21.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } - if(!arrayAttrs) { - return; - } + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_21.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } - if(pointData[key] === undefined) { - var val = _$lib_162.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) - if(pointVal !== undefined) pointData[key] = pointVal; - } - } -}; + if (buildLog) + buildLog.segmentChop(ev.seg, end); -/** - * Appends values inside array attributes corresponding to given point number array - * For use when pointData references a plot entity that arose (or potentially arose) - * from multiple points in the input data - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. - * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays - */ -_$helpers_82.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } - if(!arrayAttrs) { - return; - } + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used - if(pointData[key] === undefined) { - var val = _$lib_162.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); + // + // status logic + // - for(var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); - } - pointData[key] = keyVal; - } - } -}; + var status_root = _$LinkedList_21.create(); -var pointKeyMap = { - ids: 'id', - locations: 'location', - labels: 'label', - values: 'value', - 'marker.colors': 'color' -}; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; -function getPointKey(astr) { - return pointKeyMap[astr] || astr; -} + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } -function getPointData(val, pointNumber) { - if(Array.isArray(pointNumber)) { - if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; - } - } else { - return val[pointNumber]; - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } -// works with our CSS cursor classes (see css/_cursor.scss) -// to apply cursors to d3 single-element selections. -// omit cursor to revert to the default. -var _$setCursor_181 = function setCursor(el3, csr) { - (el3.attr('class') || '').split(' ').forEach(function(cls) { - if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); - }); + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal - if(csr) el3.classed('cursor-' + csr, true); -}; + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (buildLog) + buildLog.checkIntersection(seg1, seg2); + var i = eps.linesIntersect(a1, a2, b1, b2); -'use strict'; + if (i === false){ + // segments are parallel or coincident -/* removed: var _$setCursor_181 = require('./setcursor'); */; + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) -var STASHATTR = 'data-savedcursor'; -var NO_CURSOR = '!!'; + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection -/* - * works with our CSS cursor classes (see css/_cursor.scss) - * to override a previous cursor set on d3 single-element selections, - * by moving the name of the original cursor to the data-savedcursor attr. - * omit cursor to revert to the previously set value. - */ -var _$overrideCursor_173 = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if(csr) { - if(!savedCursor) { - var classes = (el3.attr('class') || '').split(' '); - for(var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if(cls.indexOf('cursor-') === 0) { - el3.attr(STASHATTR, cls.substr(7)) - .classed(cls, false); - } - } - if(!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); - } - } - _$setCursor_181(el3, csr); - } - else if(savedCursor) { - el3.attr(STASHATTR, null); + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); - if(savedCursor === NO_CURSOR) _$setCursor_181(el3); - else _$setCursor_181(el3, savedCursor); - } -}; + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal -var _$hover_83 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); -'use strict'; + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$Events_155 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_173 = require('../../lib/override_cursor'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_244 = require('../../registry'); */; + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints -/* removed: var _$helpers_82 = require('./helpers'); */; -/* removed: var _$constants_80 = require('./constants'); */; + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } -// hover labels for multiple horizontal bars get tilted by some angle, -// then need to be offset differently if they overlap -var YANGLE = _$constants_80.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } -// expansion of projected height -var YFACTOR = 1 / Math.sin(YA_RADIANS); + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); -// to make the appropriate post-rotation x offset, -// you need both x and y offsets -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); + if (buildLog) + buildLog.vert(ev.pt[0]); -// size and display constants for hover text -var HOVERARROWSIZE = _$constants_80.HOVERARROWSIZE; -var HOVERTEXTPAD = _$constants_80.HOVERTEXTPAD; + if (ev.isStart){ -// fx.hover: highlight data on hover -// evt can be a mousemove event, or an object with data about what points -// to hover on -// {xpx,ypx[,hovermode]} - pixel locations from top left -// (with optional overriding hovermode) -// {xval,yval[,hovermode]} - data values -// [{curveNumber,(pointNumber|xval and/or yval)}] - -// array of specific points to highlight -// pointNumber is a single integer if gd.data[curveNumber] is 1D, -// or a two-element array if it's 2D -// xval and yval are data values, -// 1D data may specify either or both, -// 2D data must specify both -// subplot is an id string (default "xy") -// makes use of gl.hovermode, which can be: -// x (find the points with the closest x values, ie a column), -// closest (find the single closest point) -// internally there are two more that occasionally get used: -// y (pick out a row - only used for multiple horizontal bar charts) -// array (used when the user specifies an explicit -// array of points to hover on) -// -// We wrap the hovers in a timer, to limit their frequency. -// The actual rendering is done by private function _hover. -_$hover_83.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_162.getGraphDiv(gd); + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); - _$lib_162.throttle( - gd._fullLayout._uid + _$constants_80.HOVERID, - _$constants_80.HOVERMINTIME, - function() { _hover(gd, evt, subplot, noHoverEvent); } - ); -}; + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; -/* - * Draw a single hover item in a pre-existing svg container somewhere - * hoverItem should have keys: - * - x and y (or x0, x1, y0, and y1): - * the pixel position to mark, relative to opts.container - * - xLabel, yLabel, zLabel, text, and name: - * info to go in the label - * - color: - * the background color for the label. - * - idealAlign (optional): - * 'left' or 'right' for which side of the x/y box to try to put this on first - * - borderColor (optional): - * color for the border, defaults to strongest contrast with color - * - fontFamily (optional): - * string, the font for this label, defaults to constants.HOVERFONT - * - fontSize (optional): - * the label font size, defaults to constants.HOVERFONTSIZE - * - fontColor (optional): - * defaults to borderColor - * opts should have keys: - * - bgColor: - * the background color this is against, used if the trace is - * non-opaque, and for the name, which goes outside the box - * - container: - * a or element to add the hover label to - * - outerContainer: - * normally a parent of `container`, sets the bounding box to use to - * constrain the hover label and determine whether to show it on the left or right - */ -_$hover_83.loneHover = function loneHover(hoverItem, opts) { - var pointData = { - color: hoverItem.color || _$color_43.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } - // filler to make createHoverText happy - trace: { - index: 0, - hoverinfo: '' - }, - xa: {_offset: 0}, - ya: {_offset: 0}, - index: 0 - }; + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev - var container3 = _$d3_7.select(opts.container), - outerContainer3 = opts.outerContainer ? - _$d3_7.select(opts.outerContainer) : container3; + // merge ev.seg's fill information into eve.seg - var fullOpts = { - hovermode: 'closest', - rotateLabels: false, - bgColor: opts.bgColor || _$color_43.background, - container: container3, - outerContainer: outerContainer3 - }; + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); - alignHoverText(hoverLabel, fullOpts.rotateLabels); + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } - return hoverLabel.node(); -}; + if (buildLog) + buildLog.segmentUpdate(eve.seg); -// The actual implementation is here: -function _hover(gd, evt, subplot, noHoverEvent) { - if(!subplot) subplot = 'xy'; + ev.other.remove(); + ev.remove(); + } - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } - var fullLayout = gd._fullLayout; - var plots = fullLayout._plots || []; - var plotinfo = plots[subplot]; - var hasCartesian = fullLayout._has('cartesian'); + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } - subplots = subplots.concat(overlayedSubplots); - } + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point - var len = subplots.length; - var xaArray = new Array(len); - var yaArray = new Array(len); - var supportsCompare = false; + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } - for(var i = 0; i < len; i++) { - var spId = subplots[i]; + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // 'cartesian' case - var plotObj = plots[spId]; - if(plotObj) { - supportsCompare = true; + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_21.node({ ev: ev })); + } + else{ + var st = ev.status; - // TODO make sure that fullLayout_plots axis refs - // get updated properly so that we don't have - // to use Axes.getFromId in general. + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } - xaArray[i] = _$axes_204.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_204.getFromId(gd, plotObj.yaxis._id); - continue; - } + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); - // other subplot types - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; - } + if (buildLog) + buildLog.statusRemove(st.ev.seg); - var hovermode = evt.hovermode || fullLayout.hovermode; + // remove the status + st.remove(); - if(hovermode && !supportsCompare) hovermode = 'closest'; + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } - if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || - gd.querySelector('.zoombox') || gd._dragging) { - return _$dragelement_65.unhoverRaw(gd, evt); - } + // remove the event and continue + event_root.getHead().remove(); + } - var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; - var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; + if (buildLog) + buildLog.done(); - // hoverData: the set of candidate points we've found to highlight - var hoverData = [], + return segments; + } - // searchData: the data to search in. Mostly this is just a copy of - // gd.calcdata, filtered to the subplot and overlays we're on - // but if a point array is supplied it will be a mapping - // of indicated curves - searchData = [], + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } - // [x|y]valArray: the axis values of the hover event - // mapped onto each of the currently selected overlaid subplots - xvalArray, - yvalArray, + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; - // used in loops - itemnum, - curvenum, - cd, - trace, - subplotId, - subploti, - mode, - xval, - yval, - pointData, - closedataPreviousLength, + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it - // spikePoints: the set of candidate points we've found to draw spikes to - spikePoints = { - hLinePoint: null, - vLinePoint: null - }; + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} - // Figure out what we're hovering on: - // mouse location or user-supplied data +var _$Intersecter_20 = Intersecter; - if(Array.isArray(evt)) { - // user specified an array of points to highlight - hovermode = 'array'; - for(itemnum = 0; itemnum < evt.length; itemnum++) { - cd = gd.calcdata[evt[itemnum].curveNumber||0]; - if(cd[0].trace.hoverinfo !== 'skip') { - searchData.push(cd); - } - } - } - else { - for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { - cd = gd.calcdata[curvenum]; - trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_82.getSubplot(trace)) !== -1) { - searchData.push(cd); - } - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // [x|y]px: the pixels (from top left) of the mouse location - // on the currently selected plot area - // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation - var hasUserCalledHover = !evt.target, - xpx, ypx; +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// - if(hasUserCalledHover) { - if('xpx' in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - evt.pointerX = xpx + xaArray[0]._offset; +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; - if('ypx' in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - evt.pointerY = ypx + yaArray[0]._offset; - } - else { - // fire the beforehover event and quit if it returns false - // note that we're only calling this on real mouse events, so - // manual calls to fx.hover will always run. - if(_$Events_155.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } - var dbb = evt.target.getBoundingClientRect(); + if (buildLog) + buildLog.chainStart(seg); - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } - // in case hover was called from mouseout into hovertext, - // it's possible you're not actually over the plot anymore - if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { - return _$dragelement_65.unhoverRaw(gd, evt); - } - evt.pointerX = evt.offsetX; - evt.pointerY = evt.offsetY; - } + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } - if('xval' in evt) xvalArray = _$helpers_82.flat(subplots, evt.xval); - else xvalArray = _$helpers_82.p2c(xaArray, xpx); + if (next_match === second_match){ + // we matched a single chain - if('yval' in evt) yvalArray = _$helpers_82.flat(subplots, evt.yval); - else yvalArray = _$helpers_82.p2c(yaArray, ypx); + if (buildLog) + buildLog.chainMatch(first_match.index); - if(!_$fastIsnumeric_10(xvalArray[0]) || !_$fastIsnumeric_10(yvalArray[0])) { - _$lib_162.warn('Fx.hover failed', evt, gd); - return _$dragelement_65.unhoverRaw(gd, evt); - } - } + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop - // the pixel distance to beat as a matching point - // in 'x' or 'y' mode this resets for each trace - var distance = Infinity; + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head - // find the closest point in each trace - // this is minimum dx and/or dy, depending on mode - // and the pixel position for the label (labelXpx, labelYpx) - for(curvenum = 0; curvenum < searchData.length; curvenum++) { - cd = searchData[curvenum]; + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - // filter out invisible or broken data - if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } - trace = cd[0].trace; + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); - // Explicitly bail out for these two. I don't know how to otherwise prevent - // the rest of this function from running and failing - if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } - subplotId = _$helpers_82.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if (buildLog) + buildLog.chainClose(first_match.index); - // within one trace mode can sometimes be overridden - mode = hovermode; + // we have a closed chain! + regions.push(chain); + return; + } - // container for new point, also used to pass info into module.hoverPoints - pointData = { - // trace properties - cd: cd, - trace: trace, - xa: xaArray[subploti], - ya: yaArray[subploti], + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } - // max distances for hover and spikes - for points that want to show but do not - // want to override other points, set distance/spikeDistance equal to max*Distance - // and it will not get filtered out but it will be guaranteed to have a greater - // distance than any point that calculated a real distance. - maxHoverDistance: hoverdistance, - maxSpikeDistance: spikedistance, + // otherwise, we matched two chains, so we need to combine those chains together - // point properties - override all of these - index: false, // point index in trace - only used by plotly.js hoverdata consumers - distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } - // distance/pseudo-distance for spikes. This distance should always be calculated - // as if in "closest" mode, and should only be set if this point should - // generate a spike. - spikeDistance: Infinity, + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; - // in some cases the spikes have different positioning from the hover label - // they don't need x0/x1, just one position - xSpike: undefined, - ySpike: undefined, + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } - // where and how to display the hover label - color: _$color_43.defaultLine, // trace color - name: trace.name, - x0: undefined, - x1: undefined, - y0: undefined, - y1: undefined, - xLabelVal: undefined, - yLabelVal: undefined, - zLabelVal: undefined, - text: undefined - }; + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } - // add ref to subplot object (non-cartesian case) - if(fullLayout[subplotId]) { - pointData.subplot = fullLayout[subplotId]._subplot; - } + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } - closedataPreviousLength = hoverData.length; + var F = first_match.index; + var S = second_match.index; - // for a highlighting array, figure out what - // we're searching for with this element - if(mode === 'array') { - var selection = evt[curvenum]; - if('pointNumber' in selection) { - pointData.index = selection.pointNumber; - mode = 'closest'; - } - else { - mode = ''; - if('xval' in selection) { - xval = selection.xval; - mode = 'x'; - } - if('yval' in selection) { - yval = selection.yval; - mode = mode ? 'closest' : 'y'; - } - } - } - else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; - } + if (buildLog) + buildLog.chainConnect(F, S); - // Now if there is range to look in, find the points to hover. - if(hoverdistance !== 0) { - if(trace._module && trace._module.hoverPoints) { - var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); - if(newPoints) { - var newPoint; - for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { - newPoint = newPoints[newPointNum]; - if(_$fastIsnumeric_10(newPoint.x0) && _$fastIsnumeric_10(newPoint.y0)) { - hoverData.push(cleanPoint(newPoint, hovermode)); - } - } - } - } - else { - _$lib_162.log('Unrecognized trace type in hover:', trace); - } - } + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); - // in closest mode, remove any existing (farther) points - // and don't look any farther than this latest point (or points, some - // traces like box & violin make multiple hover labels at once) - if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; - } + return regions; +} - // Now if there is range to look in, find the points to draw the spikelines - // Do it only if there is no hoverData - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length === 0) { - pointData.distance = spikedistance; - pointData.index = false; - var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); - if(closestPoints) { - closestPoints = closestPoints.filter(function(point) { - // some hover points, like scatter fills, do not allow spikes, - // so will generate a hover point but without a valid spikeDistance - return point.spikeDistance <= spikedistance; - }); - } - if(closestPoints && closestPoints.length) { - var tmpPoint; - var closestVPoints = closestPoints.filter(function(point) { - return point.xa.showspikes; - }); - if(closestVPoints.length) { - var closestVPt = closestVPoints[0]; - if(_$fastIsnumeric_10(closestVPt.x0) && _$fastIsnumeric_10(closestVPt.y0)) { - tmpPoint = fillSpikePoint(closestVPt); - if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.vLinePoint = tmpPoint; - } - } - } +var _$SegmentChainer_22 = SegmentChainer; - var closestHPoints = closestPoints.filter(function(point) { - return point.ya.showspikes; - }); - if(closestHPoints.length) { - var closestHPt = closestHPoints[0]; - if(_$fastIsnumeric_10(closestHPt.x0) && _$fastIsnumeric_10(closestHPt.y0)) { - tmpPoint = fillSpikePoint(closestHPt); - if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } - } - } - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - function selectClosestPoint(pointsData, spikedistance) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for(var i = 0; i < pointsData.length; i++) { - thisSpikeDistance = pointsData[i].spikeDistance; - if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { - resultPoint = pointsData[i]; - minDistance = thisSpikeDistance; - } - } - return resultPoint; - } +// +// filter a list of segments based on boolean operations +// - function fillSpikePoint(point) { - if(!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; - } +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); - var spikelineOpts = { - fullLayout: fullLayout, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - event: evt - }; - var oldspikepoints = gd._spikepoints, - newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; + if (buildLog) + buildLog.selected(result); - // Now if it is not restricted by spikedistance option, set the points to draw the spikelines - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); + return result; +} - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); - } - } +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; - // if hoverData is empty check for the spikes to draw and quit if there are none - if(hoverData.length === 0) { - var result = _$dragelement_65.unhoverRaw(gd, evt); - if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } - return result; - } +var _$SegmentSelector_23 = SegmentSelector; - if(hasCartesian) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ - hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); +/* removed: var _$BuildLog_17 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_18 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_20 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_22 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_23 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_19 = require('./lib/geojson'); */; - // lastly, emit custom hover/unhover events - var oldhoverdata = gd._hoverdata, - newhoverdata = []; +var buildLog = false; +var epsilon = _$Epsilon_18(); - // pull out just the data that's useful to - // other people and send it to the event - for(itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - newhoverdata.push(_$helpers_82.makeEventData(pt, pt.trace, pt.cd)); - } +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_17(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v){ + return epsilon.epsilon(v); + }, - gd._hoverdata = newhoverdata; + // core API + segments: function(poly){ + var i = _$Intersecter_20(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_20(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_23.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_23.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_23.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_23.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_23.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_22(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, - // if there's more than one horz bar trace, - // rotate the labels so they don't overlap - var rotateLabels = hovermode === 'y' && searchData.length > 1; + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_19.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_19.fromPolygon(PolyBool, epsilon, poly); + }, - var bgColor = _$color_43.combine( - fullLayout.plot_bgcolor || _$color_43.background, - fullLayout.paper_bgcolor - ); + // 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); + } +}; - var labelOpts = { - hovermode: hovermode, - rotateLabels: rotateLabels, - bgColor: bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }; +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); +} - var hoverLabels = createHoverText(hoverData, labelOpts, gd); +if (typeof window === 'object') + window.PolyBool = PolyBool; - hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); +var _$PolyBool_16 = PolyBool; - alignHoverText(hoverLabels, rotateLabels); +var _$polygon_175 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true - // we should improve the "fx" API so other plots can use it without these hack. - if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_244.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_173(_$d3_7.select(evt.target), hasClickToShow ? 'pointer' : ''); - } - // don't emit events if called manually - if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; +'use strict'; - if(oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } +var dot = _$matrix_169.dot; +var __BADNUM_175 = _$numerical_145.BADNUM; - gd.emit('plotly_hover', { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); -} +var polygon = _$polygon_175 = {}; -function createHoverText(hoverData, opts, gd) { - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - // opts.fontFamily/Size are used for the common label - // and as defaults for each hover label, though the individual labels - // can override this. - var fontFamily = opts.fontFamily || _$constants_80.HOVERFONT; - var fontSize = opts.fontSize || _$constants_80.HOVERFONTSIZE; + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; - var t0 = c0[commonAttr]; - var t00 = (String(t0) || '').split(' ')[0]; - var outerContainerBB = outerContainer.node().getBoundingClientRect(); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); + } - // show the common label, if any, on the axis - // never show a common label in array mode, - // even if sometimes there could be one - var showCommonLabel = ( - (t0 !== undefined) && - (c0.distance <= opts.hoverdistance) && - (hovermode === 'x' || hovermode === 'y') - ); + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed - // all hover traces hoverinfo must contain the hovermode - // to have common labels - if(showCommonLabel) { - var i, traceHoverinfo; - var allHaveZ = true; - for(i = 0; i < hoverData.length; i++) { - if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + var isRect = false, + rectFirstEdgeTest; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); - if(parts.indexOf('all') === -1 && - parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; } } - - // xyz labels put all info in their main label, so have no need of a common label - if(allHaveZ) showCommonLabel = false; } - var commonLabel = container.selectAll('g.axistext') - .data(showCommonLabel ? [0] : []); - commonLabel.enter().append('g') - .classed('axistext', true); - commonLabel.exit().remove(); + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - commonLabel.each(function() { - var label = _$d3_7.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); + if(x === __BADNUM_175 || x < xmin || x > xmax || y === __BADNUM_175 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; - lpath.enter().append('path') - .style({'stroke-width': '1px'}); + return true; + } - lpath.style({ - fill: commonLabelOpts.bgcolor || _$color_43.defaultLine, - stroke: commonLabelOpts.bordercolor || _$color_43.background, - }); + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); + if(x === __BADNUM_175 || x < xmin || x > xmax || y === __BADNUM_175 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } - ltext.text(t0) - .call(_$drawing_68.font, - commonLabelOpts.font.family || fontFamily, - commonLabelOpts.font.size || fontSize, - commonLabelOpts.font.color || _$color_43.background - ) - .call(_$svg_text_utils_183.positionText, 0, 0) - .call(_$svg_text_utils_183.convertToTspans, gd); + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; - label.attr('transform', ''); + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); - var tbb = ltext.node().getBoundingClientRect(); - if(hovermode === 'x') { - ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_183.positionText, 0, (xa.side === 'top' ? - (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : - (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - var topsign = xa.side === 'top' ? '-' : ''; - lpath.attr('d', 'M0,0' + - 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + - 'H' + (HOVERTEXTPAD + tbb.width / 2) + - 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + - 'H-' + (HOVERTEXTPAD + tbb.width / 2) + - 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } - label.attr('transform', 'translate(' + - (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + - (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + if(y <= ycross && x !== xmini) crossings++; + } } - else { - ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_183.positionText, - (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), - outerTop - tbb.top - tbb.height / 2); - var leftsign = ya.side === 'right' ? '' : '-'; - lpath.attr('d', 'M0,0' + - 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + - 'V' + (HOVERTEXTPAD + tbb.height / 2) + - 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + - 'V-' + (HOVERTEXTPAD + tbb.height / 2) + - 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; + } - label.attr('transform', 'translate(' + - (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + - (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; } - // remove the "close but not quite" points - // because of error bars, only take up to a space - hoverData = hoverData.filter(function(d) { - return (d.zLabelVal !== undefined) || - (d[commonAttr] || '').split(' ')[0] === t00; - }); - }); + } - // show all the individual labels + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; +}; - // first create the objects - var hoverLabels = container.selectAll('g.hovertext') - .data(hoverData, function(d) { - return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); - }); - hoverLabels.enter().append('g') - .classed('hovertext', true) - .each(function() { - var g = _$d3_7.select(this); - // trace name label (rect and text.name) - g.append('rect') - .call(_$color_43.fill, _$color_43.addOpacity(bgColor, 0.8)); - g.append('text').classed('name', true); - // trace data label (path and text.nums) - g.append('path') - .style('stroke-width', '1px'); - g.append('text').classed('nums', true) - .call(_$drawing_68.font, fontFamily, fontSize); - }); - hoverLabels.exit().remove(); +/** + * Test multiple polygons + */ +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; - // then put the text in, position the pointer to the data, - // and figure out sizes - hoverLabels.each(function(d) { - var g = _$d3_7.select(this).attr('transform', ''), - name = '', - text = ''; + for(var i = 0; i < list.length; i++) { + 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); + } - // combine possible non-opaque trace color with bgColor - var baseColor = _$color_43.opacity(d.color) ? d.color : _$color_43.defaultLine; - var traceColor = _$color_43.combine(baseColor, bgColor); + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } - // find a contrasting color for border and text - var contrastColor = d.borderColor || _$color_43.contrast(traceColor); + return yes; + } - // to get custom 'name' labels pass cleanPoint - if(d.nameOverride !== undefined) d.name = d.nameOverride; + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; +}; - if(d.name) { - // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_183.plainText(d.name || ''); +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; - var nameLength = Math.round(d.nameLength); + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); - if(nameLength > -1 && name.length > nameLength) { - if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; - else name = name.substr(0, nameLength); - } - } + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; + } + return false; +}; - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; +/** + * Make a filtering polygon, to minimize the number of segments + * + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon + * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs + */ +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; - if(d.zLabel !== undefined) { - if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; - if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; - text += (text ? 'z: ' : '') + d.zLabel; - } - else if(showCommonLabel && d[hovermode + 'Label'] === t0) { - text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; - } - else if(d.xLabel === undefined) { - if(d.yLabel !== undefined) text = d.yLabel; - } - else if(d.yLabel === undefined) text = d.xLabel; - else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); - if(d.text && !Array.isArray(d.text)) { - text += (text ? '
' : '') + d.text; + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } } + } - // if 'text' is empty at this point, - // put 'name' in main label and don't show secondary label - if(text === '') { - // if 'name' is also empty, remove entire label - if(name === '') g.remove(); - text = name; - } + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } - // main label - var tx = g.select('text.nums') - .call(_$drawing_68.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - d.fontColor || contrastColor) - .text(text) - .attr('data-notex', 1) - .call(_$svg_text_utils_183.positionText, 0, 0) - .call(_$svg_text_utils_183.convertToTspans, gd); + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; +}; - var tx2 = g.select('text.name'), - tx2width = 0; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // secondary label for non-empty 'name' - if(name && name !== text) { - tx2.call(_$drawing_68.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - traceColor) - .text(name) - .attr('data-notex', 1) - .call(_$svg_text_utils_183.positionText, 0, 0) - .call(_$svg_text_utils_183.convertToTspans, gd); - tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; - } - else { - tx2.remove(); - g.select('rect').remove(); - } - g.select('path') - .style({ - fill: traceColor, - stroke: contrastColor - }); - var tbb = tx.node().getBoundingClientRect(), - htx = d.xa._offset + (d.x0 + d.x1) / 2, - hty = d.ya._offset + (d.y0 + d.y1) / 2, - dx = Math.abs(d.x1 - d.x0), - dy = Math.abs(d.y1 - d.y0), - txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, - anchorStartOK, - anchorEndOK; +'use strict'; - d.ty0 = outerTop - tbb.top; - d.bx = tbb.width + 2 * HOVERTEXTPAD; - d.by = tbb.height + 2 * HOVERTEXTPAD; - d.anchor = 'start'; - d.txwidth = tbb.width; - d.tx2width = tx2width; - d.offset = 0; +/* removed: var _$PolyBool_16 = require('polybooljs'); */; - if(rotateLabels) { - d.pos = htx; - anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; - anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - hty += dy / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } - else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - htx += dx / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$fx_85 = require('../../components/fx'); */; - tx.attr('text-anchor', d.anchor); - if(tx2width) tx2.attr('text-anchor', d.anchor); - g.attr('transform', 'translate(' + htx + ',' + hty + ')' + - (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); - }); +/* removed: var _$polygon_175 = require('../../lib/polygon'); */; +/* removed: var _$throttle_185 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_82.makeEventData; +var getFromId = _$axis_ids_208.getFromId; +var __sortModules_222 = _$sort_modules_244.sortModules; - return hoverLabels; -} +/* removed: var _$constants_210 = require('./constants'); */; +var MINSELECT = _$constants_210.MINSELECT; -// Make groups of touching points, and within each group -// move each point so that no labels overlap, but the average -// label position is the same as it was before moving. Indicentally, -// this is equivalent to saying all the labels are on equal linear -// springs about their initial position. Initially, each point is -// its own group, but as we find overlaps we will clump the points. -// -// Also, there are hard constraints at the edges of the graphs, -// that push all groups to the middle so they are visible. I don't -// know what happens if the group spans all the way from one edge to -// the other, though it hardly matters - there's just too much -// information then. -function hoverAvoidOverlaps(hoverData, ax, fullLayout) { - var nummoves = 0, +var filteredPolygon = _$polygon_175.filter; +var polygonTester = _$polygon_175.tester; +var multipolygonTester = _$polygon_175.multitester; - // make groups of touching points - pointgroups = hoverData - .map(function(d, i) { - var axis = d[ax]; - return [{ - i: i, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, - pmin: 0, - pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) - }]; - }) - .sort(function(a, b) { return a[0].posref - b[0].posref; }), - donepositioning, - topOverlap, - bottomOverlap, - i, j, - pti, - sumdp; +function getAxId(ax) { return ax._id; } - function constrainGroup(grp) { - var minPt = grp[0], - maxPt = grp[grp.length - 1]; +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; - // overlap with the top - positive vals are overlaps - topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); - // overlap with the bottom - positive vals are overlaps - bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + } - // check for min overlap first, so that we always - // see the largest labels - // allow for .01px overlap, so we don't get an - // infinite loop from rounding errors - if(topOverlap > 0.01) { - for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; - donepositioning = false; - } - if(bottomOverlap < 0.01) return; - if(topOverlap < -0.01) { - // make sure we're not pushing back and forth - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - donepositioning = false; - } - if(!donepositioning) return; + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } - // no room to fix positioning, delete off-screen points + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_210.BENDPX); + } - // first see how many points we need to delete - var deleteCount = 0; - for(i = 0; i < grp.length; i++) { - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; - } + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); - // start by deleting points whose data is off screen - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; + 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'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; - } - } - for(i = 0; i < grp.length; i++) { - if(deleteCount <= 0) break; - pti = grp[i]; + var corners = zoomLayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_43.background, + stroke: _$color_43.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; - // shift the whole group minus into this new space - bottomOverlap = pti.size * 2; - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - } - } - // then delete points that go off the bottom - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; - } - } - } + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_210.SELECTID; + var selection = []; - // loop through groups, combining them if they overlap, - // until nothing moves - while(!donepositioning && nummoves <= hoverData.length) { - // to avoid infinite loops, don't move more times - // than there are traces - nummoves++; + for(i = 0; i < gd.calcdata.length; i++) { + cd = gd.calcdata[i]; + trace = cd[0].trace; - // assume nothing will move in this iteration, - // reverse this if it does - donepositioning = true; - i = 0; - while(i < pointgroups.length - 1) { - // the higher (g0) and lower (g1) point group - var g0 = pointgroups[i], - g1 = pointgroups[i + 1], + if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; - // the lowest point in the higher group (p0) - // the highest point in the lower group (p1) - p0 = g0[g0.length - 1], - p1 = g1[0]; - topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; - - // Only group points that lie on the same axes - if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { - // push the new point(s) added to this group out of the way - for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; - - // add them to the group - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); - - // adjust for minimum average movement - sumdp = 0; - for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; + if(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); } - else i++; - } - - // check if we're going off the plot on either side and fix - pointgroups.forEach(constrainGroup); - } + } 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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; - // now put these offsets into hoverData - for(i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for(j = grp.length - 1; j >= 0; j--) { - var pt = grp[j], - hoverPt = hoverData[pt.i]; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); } } -} -function alignHoverText(hoverLabels, rotateLabels) { - // finally set the text positioning relative to the data and draw the - // box around it - hoverLabels.each(function(d) { - var g = _$d3_7.select(this); - if(d.del) { - g.remove(); - return; - } - var horzSign = d.anchor === 'end' ? -1 : 1, - tx = g.select('text.nums'), - alignShift = {start: 1, end: -1, middle: 0}[d.anchor], - txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), - tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), - offsetX = 0, - offsetY = d.offset; - if(d.anchor === 'middle') { - txx -= d.tx2width / 2; - tx2x += d.txwidth / 2 + HOVERTEXTPAD; - } - if(rotateLabels) { - offsetY *= -YSHIFTY; - offsetX = d.offset * YSHIFTX; - } + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(v[index]); }; + } - g.select('path').attr('d', d.anchor === 'middle' ? - // middle aligned: rect centered on data - ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + - 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : - // left or right aligned: side rect with arrow to data - ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + - 'v' + (d.by / 2 - HOVERARROWSIZE) + - 'h' + (horzSign * d.bx) + - 'v-' + d.by + - 'H' + (horzSign * HOVERARROWSIZE + offsetX) + - 'V' + (offsetY - HOVERARROWSIZE) + - 'Z')); + function ascending(a, b) { return a - b; } - tx.call(_$svg_text_utils_183.positionText, - txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + // allow subplots to override fillRangeItems routine + var fillRangeItems; - if(d.tx2width) { - g.select('text.name') - .call(_$svg_text_utils_183.positionText, - tx2x + alignShift * HOVERTEXTPAD + offsetX, - offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); - g.select('rect') - .call(_$drawing_68.setRect, - tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, - offsetY - d.by / 2 - 1, - d.tx2width, d.by + 2); - } - }); -} + if(plotinfo.fillRangeItems) { + fillRangeItems = plotinfo.fillRangeItems; + } else { + if(mode === 'select') { + fillRangeItems = function(eventData, poly) { + var ranges = eventData.range = {}; -function cleanPoint(d, hovermode) { - var index = d.index; - var trace = d.trace || {}; - var cd0 = d.cd[0]; - var cd = d.cd[index] || {}; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + var axLetter = ax._id.charAt(0); - var getVal = Array.isArray(index) ? - function(calcKey, traceKey) { - return _$lib_162.castOption(cd0, index, calcKey) || - _$lib_162.extractOption({}, trace, '', traceKey); - } : - function(calcKey, traceKey) { - return _$lib_162.extractOption(cd, trace, calcKey, traceKey); - }; + ranges[ax._id] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(poly[axLetter + 'max']) + ].sort(ascending); + } + }; + } else { + fillRangeItems = function(eventData, poly, filterPoly) { + var dataPts = eventData.lassoPoints = {}; - function fill(key, calcKey, traceKey) { - var val = getVal(calcKey, traceKey); - if(val) d[key] = val; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); + } + }; + } } - fill('hoverinfo', 'hi', 'hoverinfo'); - fill('color', 'hbg', 'hoverlabel.bgcolor'); - fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); - fill('fontFamily', 'htf', 'hoverlabel.font.family'); - fill('fontSize', 'hts', 'hoverlabel.font.size'); - fill('fontColor', 'htc', 'hoverlabel.font.color'); - fill('nameLength', 'hnl', 'hoverlabel.namelength'); + dragOptions.moveFn = function(dx0, dy0) { + x1 = Math.max(0, Math.min(pw, dx0 + x0)); + y1 = Math.max(0, Math.min(ph, dy0 + y0)); - d.posref = hovermode === 'y' ? - (d.xa._offset + (d.x0 + d.x1) / 2) : - (d.ya._offset + (d.y0 + d.y1) / 2); + var dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - // then constrain all the positions to be on the plot - d.x0 = _$lib_162.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_162.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_162.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_162.constrain(d.y1, 0, d.ya._length); + if(mode === 'select') { + var direction = fullLayout.selectdirection; - // and convert the x and y label values into formatted text - if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_204.hoverLabelText(d.xa, d.xLabelVal); - d.xVal = d.xa.c2d(d.xLabelVal); - } - if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_204.hoverLabelText(d.ya, d.yLabelVal); - d.yVal = d.ya.c2d(d.yLabelVal); - } + 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; + } - // Traces like heatmaps generate the zLabel in their hoverPoints function - if(d.zLabelVal !== undefined && d.zLabel === undefined) { - d.zLabel = String(d.zLabelVal); - } + 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'); - // for box means and error bars, add the range to the label - if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_204.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; - if(d.xerrneg !== undefined) { - d.xLabel += ' +' + xeText + ' / -' + - _$axes_204.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + 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 d.xLabel += ' ± ' + xeText; - - // small distance penalty for error bars, so that if there are - // traces with errors and some without, the error bar label will - // hoist up to the point - if(hovermode === 'x') d.distance += 1; - } - if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_204.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; - if(d.yerrneg !== undefined) { - d.yLabel += ' +' + yeText + ' / -' + - _$axes_204.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + else if(mode === 'lasso') { + filterPoly.addPt([x1, y1]); + currentPolygon = filterPoly.filtered; } - else d.yLabel += ' ± ' + yeText; - - if(hovermode === 'y') d.distance += 1; - } - var infomode = d.hoverinfo || d.trace.hoverinfo; + // create outline & tester + if(dragOptions.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } - if(infomode !== 'all') { - infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); - if(infomode.indexOf('x') === -1) d.xLabel = undefined; - if(infomode.indexOf('y') === -1) d.yLabel = undefined; - if(infomode.indexOf('z') === -1) d.zLabel = undefined; - if(infomode.indexOf('text') === -1) d.text = undefined; - if(infomode.indexOf('name') === -1) d.name = undefined; - } + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); + } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); - return d; -} + _$throttle_185.throttle( + throttleID, + _$constants_210.SELECTDELAY, + function() { + selection = []; -function createSpikelines(closestPoints, opts) { - var container = opts.container; - var fullLayout = opts.fullLayout; - var evt = opts.event; - var xa, - ya; + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - var showY = !!closestPoints.hLinePoint; - var showX = !!closestPoints.vLinePoint; + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + traceSelections.push(traceSelection); - // Remove old spikeline items - container.selectAll('.spikeline').remove(); + thisSelection = fillSelectionItem(traceSelection, searchInfo); - if(!(showX || showY)) return; + if(selection.length) { + for(var j = 0; j < thisSelection.length; j++) { + selection.push(thisSelection[j]); + } + } + else selection = thisSelection; + } - var contrastColor = _$color_43.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + eventData = {points: selection}; + updateSelectedState(gd, searchTraces, eventData); + fillRangeItems(eventData, currentPolygon, filterPoly); + dragOptions.gd.emit('plotly_selecting', eventData); + } + ); + }; - // Horizontal line (to y-axis) - if(showY) { - var hLinePoint = closestPoints.hLinePoint, - hLinePointX, - hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; + dragOptions.clickFn = function(numClicks, evt) { + corners.remove(); - if(ySnap === 'cursor') { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; - } - var dfltHLineColor = _$tinycolor_25.readability(hLinePoint.color, contrastColor) < 1.5 ? - _$color_43.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode, - yThickness = ya.spikethickness, - yColor = ya.spikecolor || dfltHLineColor, - yBB = ya._boundingBox, - xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, - xBase, - xEndSpike; + _$throttle_185.done(throttleID).then(function() { + _$throttle_185.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); + } - if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { - if(yMode.indexOf('toaxis') !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; + updateSelectedState(gd, searchTraces); + gd.emit('plotly_deselect', null); } - if(yMode.indexOf('across') !== -1) { - xBase = ya._counterSpan[0]; - xEndSpike = ya._counterSpan[1]; + else { + // 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. + gd.emit('plotly_selected', undefined); } - // Foreground horizontal line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness, - 'stroke': yColor, - 'stroke-dasharray': _$drawing_68.dashStyle(ya.spikedash, yThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + _$fx_85.click(gd, evt); + }); + }; - // Background horizontal Line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } - // Y axis marker - if(yMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), - 'cy': hLinePointY, - 'r': yThickness, - 'fill': yColor - }) - .classed('spikeline', true); - } - } + dragOptions.doneFn = function() { + corners.remove(); - if(showX) { - var vLinePoint = closestPoints.vLinePoint, - vLinePointX, - vLinePointY; + _$throttle_185.done(throttleID).then(function() { + _$throttle_185.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); - if(xSnap === 'cursor') { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} + +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; + + if(eventData) { + var pts = eventData.points || []; + + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.selectedpoints = []; } - var dfltVLineColor = _$tinycolor_25.readability(vLinePoint.color, contrastColor) < 1.5 ? - _$color_43.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode, - xThickness = xa.spikethickness, - xColor = xa.spikecolor || dfltVLineColor, - xBB = xa._boundingBox, - yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, - yBase, - yEndSpike; - if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { - if(xMode.indexOf('toaxis') !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if(xMode.indexOf('across') !== -1) { - yBase = xa._counterSpan[0]; - yEndSpike = xa._counterSpan[1]; + 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); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + 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; + } + } - // Foreground vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness, - 'stroke': xColor, - 'stroke-dasharray': _$drawing_68.dashStyle(xa.spikedash, xThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + // group searchInfo traces by trace modules + var lookup = {}; - // Background vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - // X axis marker - if(xMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': vLinePointX, - 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), - 'r': xThickness, - 'fill': xColor - }) - .classed('spikeline', true); + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; } } -} -function hoverChanged(gd, evt, oldhoverdata) { - // don't emit any events if nothing changed - if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + var keys = Object.keys(lookup).sort(__sortModules_222); - for(var i = oldhoverdata.length - 1; i >= 0; i--) { - var oldPt = oldhoverdata[i], - newPt = gd._hoverdata[i]; - if(oldPt.curveNumber !== newPt.curveNumber || - String(oldPt.pointNumber) !== String(newPt.pointNumber)) { - return true; + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_245.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } } } - return false; } -function spikesChanged(gd, oldspikepoints) { - // don't relayout the plot because of new spikelines if spikelines points didn't change - if(!oldspikepoints) return true; - if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || - oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint - ) return true; - return false; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function mergePolygons(list, poly, subtract) { + var res; -'use strict'; + if(subtract) { + res = _$PolyBool_16.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); -/* removed: var _$registry_244 = require('../../registry'); */; -var hover = _$hover_83.hover; + return res.regions; + } -var _$click_79 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_244.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); + res = _$PolyBool_16.union({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); - // 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); - } + return res.regions; +} - function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } +function fillSelectionItem(selection, searchInfo) { + if(Array.isArray(selection)) { + var cd = searchInfo.cd; + var trace = searchInfo.cd[0].trace; - if(gd._hoverdata && evt && evt.target) { - if(annotationsDone && annotationsDone.then) { - annotationsDone.then(emitClick); + for(var i = 0; i < selection.length; i++) { + selection[i] = makeEventData(selection[i], trace, cd); } - else emitClick(); - - // why do we get a double event without this??? - if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; - -/* removed: var _$lib_162 = require('../../lib'); */; + return selection; +} -var _$handleHoverLabelDefaults_84 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { - opts = opts || {}; +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); +} - coerce('hoverlabel.bgcolor', opts.bgcolor); - coerce('hoverlabel.bordercolor', opts.bordercolor); - coerce('hoverlabel.namelength', opts.namelength); - _$lib_162.coerceFont(coerce, 'hoverlabel.font', opts.font); +var _$select_222 = { + prepSelect: prepSelect, + clearSelect: clearSelect }; /** @@ -33626,1093 +34205,1414 @@ var _$handleHoverLabelDefaults_84 = function handleHoverLabelDefaults(contIn, co * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$attributes_77 = require('./attributes'); */; -/* removed: var _$handleHoverLabelDefaults_84 = require('./hoverlabel_defaults'); */; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_13 = require('has-passive-events'); */; -var _$supplyDefaults_81 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_162.coerce(traceIn, traceOut, _$attributes_77, attr, dflt); - } +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_152 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$drawing_68 = require('../../components/drawing'); */; +/* removed: var _$fx_85 = require('../../components/fx'); */; +/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; +var FROM_TL = _$alignment_143.FROM_TL; - _$handleHoverLabelDefaults_84(traceIn, traceOut, coerce, layout.hoverlabel); -}; +/* removed: var _$plots_237 = require('../plots'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 doTicks = _$axes_205.doTicks; +var __getFromId_213 = _$axis_ids_208.getFromId; +var __prepSelect_213 = _$select_222.prepSelect; +var __clearSelect_213 = _$select_222.clearSelect; +/* removed: var _$scaleZoom_221 = require('./scale_zoom'); */; -'use strict'; +/* removed: var _$constants_210 = require('./constants'); */; +var MINDRAG = _$constants_210.MINDRAG; +var MINZOOM = _$constants_210.MINZOOM; -/* removed: var _$constants_80 = require('./constants'); */; -var __fontAttrs_86 = _$font_attributes_231({ - editType: 'none', - -}); -__fontAttrs_86.family.dflt = _$constants_80.HOVERFONT; -__fontAttrs_86.size.dflt = _$constants_80.HOVERFONTSIZE; +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; -var _$layout_attributes_86 = { - dragmode: { - valType: 'enumerated', - - values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], - dflt: 'zoom', - editType: 'modebar', - - }, - hovermode: { - valType: 'enumerated', - - values: ['x', 'y', 'closest', false], - editType: 'modebar', - - }, - hoverdistance: { - valType: 'integer', - min: -1, - dflt: 20, - - editType: 'none', - - }, - spikedistance: { - valType: 'integer', - min: -1, - dflt: 20, - - editType: 'none', - - }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'none', - - }, - bordercolor: { - valType: 'color', - - editType: 'none', - - }, - font: __fontAttrs_86, - namelength: { - valType: 'integer', - min: -1, - dflt: 15, - - editType: 'none', - - }, - editType: 'none' - } -}; +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; -'use strict'; + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; -var _$supplyLayoutDefaults_87 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_162.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); - } + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } - coerce('dragmode'); + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; - var hovermodeDflt; - if(layoutOut._has('cartesian')) { - // flag for 'horizontal' plots: - // determines the state of the mode bar 'compare' hovermode button - layoutOut._isHoriz = isHoriz(fullData); - hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; } - else hovermodeDflt = 'closest'; - var hoverMode = coerce('hovermode', hovermodeDflt); - if(hoverMode) { - coerce('hoverdistance'); - coerce('spikedistance'); - } + recomputeAxisLists(); - // if only mapbox or geo subplots is present on graph, - // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, - // so that the correct modebar button is active - var hasMapbox = layoutOut._has('mapbox'); - var hasGeo = layoutOut._has('geo'); - var len = layoutOut._basePlotModules.length; + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - if(layoutOut.dragmode === 'zoom' && ( - ((hasMapbox || hasGeo) && len === 1) || - (hasMapbox && hasGeo && len === 2) - )) { - layoutOut.dragmode = 'pan'; + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; } -}; - -function isHoriz(fullData) { - var out = true; - - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(trace.orientation !== 'h') { - out = false; - break; - } - } + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; - return out; -} + recomputeAxisLists(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } -'use strict'; + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$handleHoverLabelDefaults_84 = require('./hoverlabel_defaults'); */; -/* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_213(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_213(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; -var _$supplyLayoutGlobalDefaults_88 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { - function coerce(attr, dflt) { - return _$lib_162.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); - } + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; - _$handleHoverLabelDefaults_84(layoutIn, layoutOut, coerce); -}; + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_213(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(numClicks === 2 && !singleEnd) doubleClick(); -'use strict'; + if(isMainDrag) { + _$fx_85.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$helpers_82 = require('./helpers'); */; -/* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; + if(ax.fixedrange) return; -var _$fx_85 = { - moduleType: 'component', - name: 'fx', + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; - constants: _$constants_80, - schema: { - layout: _$layout_attributes_86 - }, + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_7.select(dragger) + .call(_$svg_text_utils_184.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_245.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; - attributes: _$attributes_77, - layoutAttributes: _$layout_attributes_86, + _$dragelement_65.init(dragOptions); - supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_88, - supplyDefaults: _$supplyDefaults_81, - supplyLayoutDefaults: _$supplyLayoutDefaults_87, + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; - calc: _$calc_78, + // collected changes to be made to the plot by relayout at the end + var updates = {}; - getDistanceFunction: _$helpers_82.getDistanceFunction, - getClosest: _$helpers_82.getClosest, - inbox: _$helpers_82.inbox, - quadrature: _$helpers_82.quadrature, - appendArrayPointValue: _$helpers_82.appendArrayPointValue, + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_25(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; - castHoverOption: castHoverOption, - castHoverinfo: castHoverinfo, + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - hover: _$hover_83.hover, - unhover: _$dragelement_65.unhover, + corners = makeCorners(zoomlayer, xs, ys); - loneHover: _$hover_83.loneHover, - loneUnhover: loneUnhover, + __clearSelect_213(zoomlayer); + } - click: _$click_79 -}; + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } -function loneUnhover(containerOrSelection) { - // duck type whether the arg is a d3 selection because ie9 doesn't - // handle instanceof like modern browsers do. - var selection = _$lib_162.isD3Selection(containerOrSelection) ? - containerOrSelection : - _$d3_7.select(containerOrSelection); + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - selection.selectAll('g.hovertext').remove(); - selection.selectAll('.spikeline').remove(); -} + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); -// helpers for traces that use Fx.loneHover + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); + } -function castHoverOption(trace, ptNumber, attr) { - return _$lib_162.castOption(trace, ptNumber, 'hoverlabel.' + attr); -} + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; -function castHoverinfo(trace, fullLayout, ptNumber) { - function _coerce(val) { - return _$lib_162.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; } - return _$lib_162.castOption(trace, ptNumber, 'hoverinfo', _coerce); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } -'use strict'; + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } -/* removed: var _$lib_162 = require('../../lib'); */; + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } -/** Fill hover 'pointData' container with 'correct' hover text value - * - * - If trace hoverinfo contains a 'text' flag and hovertext is not set, - * the text elements will be seen in the hover labels. - * - * - If trace hoverinfo contains a 'text' flag and hovertext is set, - * hovertext takes precedence over text - * i.e. the hoverinfo elements will be seen in the hover labels - * - * @param {object} calcPt - * @param {object} trace - * @param {object || array} contOut (mutated here) - */ -var _$fillHoverText_288 = function fillHoverText(calcPt, trace, contOut) { - var fill = Array.isArray(contOut) ? - function(v) { contOut.push(v); } : - function(v) { contOut.text = v; }; + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_210.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - var htx = _$lib_162.extractOption(calcPt, trace, 'htx', 'hovertext'); - if(isValid(htx)) return fill(htx); + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } - var tx = _$lib_162.extractOption(calcPt, trace, 'tx', 'text'); - if(isValid(tx)) return fill(tx); -}; + if(redrawTimer === null) { + __clearSelect_213(zoomlayer); + } -// accept all truthy values and 0 (which gets cast to '0' in the hover labels) -function isValid(v) { - return v || v === 0; -} + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 pc = gd.querySelector('.plotly'); + recomputeAxisLists(); -'use strict'; + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } -/* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$fillHoverText_288 = require('../scatter/fill_hover_text'); */; + clearTimeout(redrawTimer); -var _$hoverPoints_257 = function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - var t = cd[0].t; - var isClosest = (hovermode === 'closest'); - var maxHoverDistance = pointData.maxHoverDistance; - var maxSpikeDistance = pointData.maxSpikeDistance; + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_163.log('Did not find wheel motion attributes: ', e); + return; + } - var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; - function thisBarMinPos(di) { return di[posLetter] - di.w / 2; } - function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; } + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; - var minPos = isClosest ? - thisBarMinPos : - function(di) { - /* - * In compare mode, accept a bar if you're on it *or* its group. - * Nearly always it's the group that matters, but in case the bar - * was explicitly set wider than its group we'd better accept the - * whole bar. - * - * use `bardelta` instead of `bargroupwidth` so we accept hover - * in the gap. That way hover doesn't flash on and off as you - * mouse over the plot in compare modes. - * In 'closest' mode though the flashing seems inevitable, - * without far more complex logic - */ - return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2); - }; + var axRange = _$lib_163.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } - var maxPos = isClosest ? - thisBarMaxPos : - function(di) { - return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2); - }; + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; - function _positionFn(_minPos, _maxPos) { - // add a little to the pseudo-distance for wider bars, so that like scatter, - // if you are over two overlapping bars, the narrower one wins. - return _$fx_85.inbox(_minPos - posVal, _maxPos - posVal, - maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); - } + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } - function positionFn(di) { - return _positionFn(minPos(di), maxPos(di)); - } + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; - function thisBarPositionFn(di) { - return _positionFn(thisBarMinPos(di), thisBarMaxPos(di)); - } + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } - function sizeFn(di) { - // add a gradient so hovering near the end of a - // bar makes it a little closer match - return _$fx_85.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, - maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); - } + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } - if(trace.orientation === 'h') { - posVal = yval; - sizeVal = xval; - posLetter = 'y'; - sizeLetter = 'x'; - dx = sizeFn; - dy = positionFn; + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); + + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; + + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + + dragTail(zoomMode); + }, REDRAWDELAY); + + e.preventDefault(); + return; } - else { - posVal = xval; - sizeVal = yval; - posLetter = 'x'; - sizeLetter = 'y'; - dy = sizeFn; - dx = positionFn; + + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); } - var pa = pointData[posLetter + 'a']; - var sa = pointData[sizeLetter + 'a']; + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_85.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_85.getClosest(cd, distfn, pointData); + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); - // skip the rest (for this trace) if we didn't find a close point - if(pointData.index === false) return; + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } - // if we get here and we're not in 'closest' mode, push min/max pos back - // onto the group - even though that means occasionally the mouse will be - // over the hover label. - if(!isClosest) { - minPos = function(di) { - return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2); - }; - maxPos = function(di) { - return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2); - }; - } + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - // the closest data point - var index = pointData.index; - var di = cd[index]; - var mc = di.mcc || trace.marker.color; - var mlc = di.mlcc || trace.marker.line.color; - var mlw = di.mlw || trace.marker.line.width; + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - if(_$color_43.opacity(mc)) pointData.color = mc; - else if(_$color_43.opacity(mlc) && mlw) pointData.color = mlc; + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - var size = (trace.base) ? di.b + di.s : di.s; - pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); - pointData[sizeLetter + 'LabelVal'] = size; + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; - var extent = t.extents[t.extents.round(di.p)]; - pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true); - pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true); - pointData[posLetter + 'LabelVal'] = di.p; + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_221(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_221(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } - // spikelines always want "closest" distance regardless of hovermode - pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance; - // they also want to point to the data value, regardless of where the label goes - // in case of bars shifted within groups - pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } - _$fillHoverText_288(di, trace, pointData); - _$registry_244.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; - return [pointData]; -}; + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } -'use strict'; + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_213(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; -var _$layout_attributes_259 = { - 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', - + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // 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 + + redrawObjs(gd._fullLayout.annotations || [], _$registry_245.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_245.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_245.getComponentMethod('images', 'draw'), true); } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function doubleClick() { + if(gd._transitioningWithDuration) return; + + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; + var ax, i, rangeInitial; -'use strict'; + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { + + doubleClickConfig = 'autosize'; + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_162 = require('../../lib'); */; + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); -/* removed: var _$layout_attributes_259 = require('./layout_attributes'); */; + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } + for(i = 0; i < axList.length; i++) { + ax = axList[i]; -var _$layout_defaults_260 = function(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_162.coerce(layoutIn, layoutOut, _$layout_attributes_259, attr, dflt); + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } + + gd.emit('plotly_doubleclick', null); + _$registry_245.call('relayout', gd, attrs); } - var hasBars = false, - shouldBeGapless = false, - gappedAnyway = false, - usedSubplots = {}; + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(_$registry_244.traceIs(trace, 'bar')) hasBars = true; - else continue; + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_163.syncOrAsync([ + _$plots_237.previousPromises, + function() { _$registry_245.call('relayout', gd, updates); } + ], gd); + } - // if we have at least 2 grouped bar traces on the same subplot, - // we should default to a gap anyway, even if the data is histograms - if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') { - var subploti = trace.xaxis + trace.yaxis; - if(usedSubplots[subploti]) gappedAnyway = true; - usedSubplots[subploti] = true; + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; + + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); + + var i, sp, xa, ya; + + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_152(gd); } - if(trace.visible && trace.type === 'histogram') { - var pa = _$axes_204.getFromId({_fullLayout: layoutOut}, - trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); - if(pa.type !== 'category') shouldBeGapless = true; + if(hasSplom) { + _$registry_245.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; } - } - if(!hasBars) return; + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_163.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_163.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } - var mode = coerce('barmode'); - if(mode !== 'overlay') coerce('barnorm'); + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; - coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2); - coerce('bargroupgap'); -}; + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; -'use strict'; + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$registry_244 = require('../../registry'); */; + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_68.setTranslate, clipDx, clipDy) + .call(_$drawing_68.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_68.setTranslate, plotDx, plotDy) + .call(_$drawing_68.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_68.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_68.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_68.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_68.hideOutsideRangePoints, sp, '.bartext'); + } + } + } + } -var __dummy_261$0 = 0, - attributeText = _$attributes_254.text, - attributeTextPosition = _$attributes_254.textposition, - attributeTextFont = _$attributes_254.textfont, - attributeInsideTextFont = _$attributes_254.insidetextfont, - attributeOutsideTextFont = _$attributes_254.outsidetextfont; + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; -// padding in pixels around text -var TEXTPAD = 3; + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } -var _$plot_261 = function plot(gd, plotinfo, cdbar) { - var xa = plotinfo.xaxis, - ya = plotinfo.yaxis, - fullLayout = gd._fullLayout; + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_221(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } - var bartraces = plotinfo.plot.select('.barlayer') - .selectAll('g.trace.bars') - .data(cdbar); + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle']; + } - bartraces.enter().append('g') - .attr('class', 'trace bars'); + return dragger; +} - bartraces.each(function(d) { - d[0].node3 = _$d3_7.select(this); +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_163.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); }); - bartraces.append('g') - .attr('class', 'points') - .each(function(d) { - var sel = _$d3_7.select(this); - var t = d[0].t; - var trace = d[0].trace; - var poffset = t.poffset; - var poffsetIsArray = Array.isArray(poffset); - - sel.selectAll('g.point') - .data(_$lib_162.identity) - .enter().append('g').classed('point', true) - .each(function(di, i) { - // now display the bar - // clipped xf/yf (2nd arg true): non-positive - // log values go off-screen by plotwidth - // so you see them continue if you drag the plot - var p0 = di.p + ((poffsetIsArray) ? poffset[i] : poffset), - p1 = p0 + di.w, - s0 = di.b, - s1 = s0 + di.s; + dragger3.call(_$setCursor_182, cursor); - var x0, x1, y0, y1; - if(trace.orientation === 'h') { - y0 = ya.c2p(p0, true); - y1 = ya.c2p(p1, true); - x0 = xa.c2p(s0, true); - x1 = xa.c2p(s1, true); + return dragger3.node(); +} - // for selections - di.ct = [x1, (y0 + y1) / 2]; - } - else { - x0 = xa.c2p(p0, true); - x1 = xa.c2p(p1, true); - y0 = ya.c2p(s0, true); - y1 = ya.c2p(s1, true); +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_7.select(dragger).call(_$drawing_68.setRect, x, y, w, h); + return dragger; +} - // for selections - di.ct = [(x0 + x1) / 2, y1]; - } +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} - if(!_$fastIsnumeric_10(x0) || !_$fastIsnumeric_10(x1) || - !_$fastIsnumeric_10(y0) || !_$fastIsnumeric_10(y1) || - x0 === x1 || y0 === y1) { - _$d3_7.select(this).remove(); - return; - } +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - var lw = (di.mlw + 1 || trace.marker.line.width + 1 || - (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, - offset = _$d3_7.round((lw / 2) % 1, 2); + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_7.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_7.format('.' + String(dig) + 'g')(initialVal); + } +} - function roundWithLine(v) { - // if there are explicit gaps, don't round, - // it can make the gaps look crappy - return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? - _$d3_7.round(Math.round(v) - offset, 2) : v; - } +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; - function expandToVisible(v, vc) { - // if it's not in danger of disappearing entirely, - // round more precisely - return Math.abs(v - vc) >= 2 ? roundWithLine(v) : - // but if it's very thin, expand it so it's - // necessarily visible, even if it might overlap - // its neighbor - (v > vc ? Math.ceil(v) : Math.floor(v)); - } + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; - if(!gd._context.staticPlot) { - // if bars are not fully opaque or they have a line - // around them, round to integer pixels, mainly for - // safari so we prevent overlaps from its expansive - // pixelation. if the bars ARE fully opaque and have - // no line, expand to a full pixel to make sure we - // can see them - var op = _$color_43.opacity(di.mc || trace.marker.color), - fixpx = (op < 1 || lw > 0.01) ? - roundWithLine : expandToVisible; - x0 = fixpx(x0, x1); - x1 = fixpx(x1, x0); - y0 = fixpx(y0, y1); - y1 = fixpx(y1, y0); - } + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } - // append bar path and text - var bar = _$d3_7.select(this); + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - bar.append('path') - .style('vector-effect', 'non-scaling-stroke') - .attr('d', - 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') - .call(_$drawing_68.setClipUrl, plotinfo.layerClipId); + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} - appendBarText(gd, bar, d, i, x0, x1, y0, y1); +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} - if(plotinfo.layerClipId) { - _$drawing_68.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); - } - }); - }); +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} - // error bars are on the top - _$registry_244.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} - // lastly, clip points groups of `cliponaxis !== false` traces - // on `plotinfo._hasClipOnAxisFalse === true` subplots - bartraces.each(function(d) { - var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_68.setClipUrl(_$d3_7.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); - }); -}; +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} -function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { - var textPosition; +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_43.background, + stroke: _$color_43.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} - function appendTextNode(bar, text, textFont) { - var textSelection = bar.append('text') - .text(text) - .attr({ - 'class': 'bartext bartext-' + textPosition, - transform: '', - 'text-anchor': 'middle', - // prohibit tex interpretation until we can handle - // tex and regular text together - 'data-notex': 1 - }) - .call(_$drawing_68.font, textFont) - .call(_$svg_text_utils_183.convertToTspans, gd); +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} - return textSelection; +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); } +} - // get trace attributes - var trace = calcTrace[0].trace, - orientation = trace.orientation; - - var text = getText(trace, i); - if(!text) return; - - textPosition = getTextPosition(trace, i); - if(textPosition === 'none') return; - - var textFont = getTextFont(trace, i, gd._fullLayout.font), - insideTextFont = getInsideTextFont(trace, i, textFont), - outsideTextFont = getOutsideTextFont(trace, i, textFont); +function removeZoombox(gd) { + _$d3_7.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} - // compute text position - var barmode = gd._fullLayout.barmode, - inStackMode = (barmode === 'stack'), - inRelativeMode = (barmode === 'relative'), - inStackOrRelativeMode = inStackMode || inRelativeMode, +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_163.notifier(_$lib_163._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} - calcBar = calcTrace[i], - isOutmostBar = !inStackOrRelativeMode || calcBar._outmost, +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} - barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD, // padding excluded - barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD, // padding excluded +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} - textSelection, - textBB, - textWidth, - textHeight; +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} - if(textPosition === 'outside') { - if(!isOutmostBar) textPosition = 'inside'; - } +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - if(textPosition === 'auto') { - if(isOutmostBar) { - // draw text using insideTextFont and check if it fits inside bar - textPosition = 'inside'; - textSelection = appendTextNode(bar, text, insideTextFont); +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; - textBB = _$drawing_68.bBox(textSelection.node()), - textWidth = textBB.width, - textHeight = textBB.height; + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } - var textHasSize = (textWidth > 0 && textHeight > 0), - fitsInside = - (textWidth <= barWidth && textHeight <= barHeight), - fitsInsideIfRotated = - (textWidth <= barHeight && textHeight <= barWidth), - fitsInsideIfShrunk = (orientation === 'h') ? - (barWidth >= textWidth * (barHeight / textHeight)) : - (barHeight >= textHeight * (barWidth / textWidth)); - if(textHasSize && - (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) { - textPosition = 'inside'; - } - else { - textPosition = 'outside'; - textSelection.remove(); - textSelection = null; + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } } } - else textPosition = 'inside'; - } - - if(!textSelection) { - textSelection = appendTextNode(bar, text, - (textPosition === 'outside') ? - outsideTextFont : insideTextFont); - textBB = _$drawing_68.bBox(textSelection.node()), - textWidth = textBB.width, - textHeight = textBB.height; - - if(textWidth <= 0 || textHeight <= 0) { - textSelection.remove(); - return; + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } } } - // compute text transform - var transform, constrained; - if(textPosition === 'outside') { - constrained = trace.constraintext === 'both' || trace.constraintext === 'outside'; - transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, - orientation, constrained); - } - else { - constrained = trace.constraintext === 'both' || trace.constraintext === 'inside'; - transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, - orientation, constrained); + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_163.extendFlat(xLinks, yLinks); + yLinks = {}; } - textSelection.attr('transform', transform); -} - -function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { - // compute text and target positions - var textWidth = textBB.width, - textHeight = textBB.height, - textX = (textBB.left + textBB.right) / 2, - textY = (textBB.top + textBB.bottom) / 2, - barWidth = Math.abs(x1 - x0), - barHeight = Math.abs(y1 - y0), - targetWidth, - targetHeight, - targetX, - targetY; - - // apply text padding - var textpad; - if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) { - textpad = TEXTPAD; - barWidth -= 2 * textpad; - barHeight -= 2 * textpad; + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_213(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; } - else textpad = 0; - - // compute rotation and scale - var rotate, - scale; - if(textWidth <= barWidth && textHeight <= barHeight) { - // no scale or rotation is required - rotate = false; - scale = 1; - } - else if(textWidth <= barHeight && textHeight <= barWidth) { - // only rotation is required - rotate = true; - scale = 1; - } - else if((textWidth < textHeight) === (barWidth < barHeight)) { - // only scale is required - rotate = false; - scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1; - } - else { - // both scale and rotation are required - rotate = true; - scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1; + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_213(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; } - if(rotate) rotate = 90; // rotate clockwise + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} - // compute text and target positions - if(rotate) { - targetWidth = scale * textHeight; - targetHeight = scale * textWidth; +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_13) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; } else { - targetWidth = scale * textWidth; - targetHeight = scale * textHeight; - } + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - if(orientation === 'h') { - if(x1 < x0) { - // bar end is on the left hand side - targetX = x1 + textpad + targetWidth / 2; - targetY = (y0 + y1) / 2; - } - else { - targetX = x1 - textpad - targetWidth / 2; - targetY = (y0 + y1) / 2; - } - } - else { - if(y1 > y0) { - // bar end is on the bottom - targetX = (x0 + x1) / 2; - targetY = y1 - textpad - targetHeight / 2; - } - else { - targetX = (x0 + x1) / 2; - targetY = y1 + textpad + targetHeight / 2; + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); } +} - return getTransform(textX, textY, targetX, targetY, scale, rotate); +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; } -function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { - var barWidth = (orientation === 'h') ? - Math.abs(y1 - y0) : - Math.abs(x1 - x0), - textpad; +var _$dragbox_213 = { + makeDragBox: makeDragBox, - // Keep the padding so the text doesn't sit right against - // the bars, but don't factor it into barWidth - if(barWidth > 2 * TEXTPAD) { - textpad = TEXTPAD; - } + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, - // compute rotation and scale - var scale = 1; - if(constrained) { - scale = (orientation === 'h') ? - Math.min(1, barWidth / textBB.height) : - Math.min(1, barWidth / textBB.width); - } + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, - // compute text and target positions - var textX = (textBB.left + textBB.right) / 2, - textY = (textBB.top + textBB.bottom) / 2, - targetWidth, - targetHeight, - targetX, - targetY; + attachWheelEventHandler: attachWheelEventHandler +}; - targetWidth = scale * textBB.width; - targetHeight = scale * textBB.height; +var _$graph_interact_214 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(orientation === 'h') { - if(x1 < x0) { - // bar end is on the left hand side - targetX = x1 - textpad - targetWidth / 2; - targetY = (y0 + y1) / 2; - } - else { - targetX = x1 + textpad + targetWidth / 2; - targetY = (y0 + y1) / 2; - } - } - else { - if(y1 > y0) { - // bar end is on the bottom - targetX = (x0 + x1) / 2; - targetY = y1 + textpad + targetHeight / 2; - } - else { - targetX = (x0 + x1) / 2; - targetY = y1 - textpad - targetHeight / 2; - } - } - return getTransform(textX, textY, targetX, targetY, scale, false); -} +'use strict'; -function getTransform(textX, textY, targetX, targetY, scale, rotate) { - var transformScale, - transformRotate, - transformTranslate; +/* removed: var _$d3_7 = require('d3'); */; - if(scale < 1) transformScale = 'scale(' + scale + ') '; - else { - scale = 1; - transformScale = ''; +/* removed: var _$fx_85 = require('../../components/fx'); */; +/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; + +var __makeDragBox_214 = _$dragbox_213.makeDragBox; +var DRAGGERSIZE = _$constants_210.DRAGGERSIZE; + +_$graph_interact_214.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; + + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_7.select(gd).selectAll('.drag').remove(); + return; } - transformRotate = (rotate) ? - 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : ''; + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - // Note that scaling also affects the center of the text box - var translateX = (targetX - scale * textX), - translateY = (targetY - scale * textY); - transformTranslate = 'translate(' + translateX + ' ' + translateY + ')'; + 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'), + 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; + }); - return transformTranslate + transformScale + transformRotate; -} + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -function getText(trace, index) { - var value = getValue(trace.text, index); - return coerceString(attributeText, value); -} + // 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_214(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); -function getTextPosition(trace, index) { - var value = getValue(trace.textposition, index); - return coerceEnumerated(attributeTextPosition, value); -} + 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) { + _$fx_85.hover(gd, evt, subplot); + } + }; -function getTextFont(trace, index, defaultValue) { - return getFontValue( - attributeTextFont, trace.textfont, index, defaultValue); -} + _$fx_85.hover(gd, evt, subplot); -function getInsideTextFont(trace, index, defaultValue) { - return getFontValue( - attributeInsideTextFont, trace.insidetextfont, index, defaultValue); -} + // 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; + }; -function getOutsideTextFont(trace, index, defaultValue) { - return getFontValue( - attributeOutsideTextFont, trace.outsidetextfont, index, defaultValue); -} + /* + * 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; -function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { - attributeValue = attributeValue || {}; + // 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; - var familyValue = getValue(attributeValue.family, index), - sizeValue = getValue(attributeValue.size, index), - colorValue = getValue(attributeValue.color, index); + _$dragelement_65.unhover(gd, evt); + }; - return { - family: coerceString( - attributeDefinition.family, familyValue, defaultValue.family), - size: coerceNumber( - attributeDefinition.size, sizeValue, defaultValue.size), - color: coerceColor( - attributeDefinition.color, colorValue, defaultValue.color) + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_214(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_214(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_214(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_214(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_214(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_214(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_214(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_214(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_214(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_214(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_85.hover(gd, evt, fullLayout._hoversubplot); }; -} -function getValue(arrayOrScalar, index) { - var value; - if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar; - else if(index < arrayOrScalar.length) value = arrayOrScalar[index]; - return value; -} + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_85.click(gd, evt); + }; -function coerceString(attributeDefinition, value, defaultValue) { - if(typeof value === 'string') { - if(value || !attributeDefinition.noBlank) return value; - } - else if(typeof value === 'number') { - if(!attributeDefinition.strict) return String(value); - } + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} + _$graph_interact_214.updateFx(fullLayout); +}; -function coerceEnumerated(attributeDefinition, value, defaultValue) { - if(attributeDefinition.coerceNumber) value = +value; +// 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. +_$graph_interact_214.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_182(fullLayout._draggers, cursor); +}; - if(attributeDefinition.values.indexOf(value) !== -1) return value; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} +'use strict'; -function coerceNumber(attributeDefinition, value, defaultValue) { - if(_$fastIsnumeric_10(value)) { - value = +value; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; - var min = attributeDefinition.min, - max = attributeDefinition.max, - isOutOfBounds = (min !== undefined && value < min) || - (max !== undefined && value > max); + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } - if(!isOutOfBounds) return value; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } } - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; + return Object.keys(lookup); } -function coerceColor(attributeDefinition, value, defaultValue) { - if(_$tinycolor_25(value).isValid()) return value; +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_209 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; + + var order = coerce('categoryorder', orderDefault); + var array; + + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); + } + + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; + } + + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -34724,36 +35624,58 @@ function coerceColor(attributeDefinition, value, defaultValue) { 'use strict'; -var _$selectPoints_262 = function selectPoints(searchInfo, polygon) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var i; +var colorMix = _$tinycolor_25.mix; +var lightFraction = _$attributes_42.lightFraction; +/* removed: var _$lib_163 = require('../../lib'); */; - if(polygon === 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]; +/** + * @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 + */ +var _$handleLineGridDefaults_219 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; - if(polygon.contains(di.ct)) { - selection.push({ - pointNumber: i, - x: xa.c2d(di.x), - y: ya.c2d(di.y) - }); - di.selected = 1; - } else { - di.selected = 0; - } - } + var dfltColor = opts.dfltColor; + + function coerce2(attr, dflt) { + return _$lib_163.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } - return selection; + 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; + } + } }; /** @@ -34766,102 +35688,93 @@ var _$selectPoints_262 = function selectPoints(searchInfo, polygon) { 'use strict'; -var _$Sieve_264 = Sieve; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -var __BADNUM_264 = _$numerical_145.BADNUM; +/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_226 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_225 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_224 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_209 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_219 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_223 = require('./set_convert'); */; /** - * Helper class to sieve data from traces into bins + * options: object containing: * - * @class - * @param {Array} traces - * Array of calculated traces - * @param {boolean} [separateNegativeValues] - * If true, then split data at the same position into a bar - * for positive values and another for negative values - * @param {boolean} [dontMergeOverlappingData] - * If true, then don't merge overlapping bars into a single bar + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors */ -function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { - this.traces = traces; - this.separateNegativeValues = separateNegativeValues; - this.dontMergeOverlappingData = dontMergeOverlappingData; +var _$handleAxisDefaults_207 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; - // for single-bin histograms - see histogram/calc - var width1 = Infinity; + var visible = coerce('visible', !options.cheateronly); - var positions = []; - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; - if(bar.p !== __BADNUM_264) positions.push(bar.p); - } - if(trace[0] && trace[0].width1) { - width1 = Math.min(trace[0].width1, width1); - } + var axType = containerOut.type; + + if(axType === 'date') { + var handleCalendarDefaults = _$registry_245.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } - this.positions = positions; - var dv = _$lib_162.distinctVals(positions); - this.distinctPositions = dv.vals; - if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; - else this.minDiff = Math.min(dv.minDiff, width1); + _$setConvert_223(containerOut, layoutOut); - this.binWidth = this.minDiff; + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - this.bins = {}; -} + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; -/** - * Sieve datum - * - * @method - * @param {number} position - * @param {number} value - * @returns {number} Previous bin value - */ -Sieve.prototype.put = function put(position, value) { - var label = this.getLabel(position, value), - oldValue = this.bins[label] || 0; + if(autoRange) coerce('rangemode'); - this.bins[label] = oldValue + value; + coerce('range'); + containerOut.cleanRange(); - return oldValue; -}; + _$handleCategoryOrderDefaults_209(containerIn, containerOut, coerce, options); -/** - * Get current bin value for a given datum - * - * @method - * @param {number} position Position of datum - * @param {number} [value] Value of datum - * (required if this.separateNegativeValues is true) - * @returns {number} Current bin value - */ -Sieve.prototype.get = function put(position, value) { - var label = this.getLabel(position, value); - return this.bins[label] || 0; -}; + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); -/** - * Get bin label for a given datum - * - * @method - * @param {number} position Position of datum - * @param {number} [value] Value of datum - * (required if this.separateNegativeValues is true) - * @returns {string} Bin label - * (prefixed with a 'v' if value is negative and this.separateNegativeValues is - * true; otherwise prefixed with '^') - */ -Sieve.prototype.getLabel = function getLabel(position, value) { - var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^', - label = (this.dontMergeOverlappingData) ? - position : - Math.round(position / this.binWidth); - return prefix + label; + if(!visible) return containerOut; + + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; + + coerce('title', dfltTitle); + _$lib_163.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); + + _$handleTickValueDefaults_226(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_224(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_225(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_219(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_217 + }); + + if(containerOut.showline || containerOut.ticks) coerce('mirror'); + + if(options.automargin) coerce('automargin'); + + return containerOut; }; /** @@ -34875,647 +35788,607 @@ Sieve.prototype.getLabel = function getLabel(position, value) { 'use strict'; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_263 = _$lib_162.isArrayOrTypedArray; -var __BADNUM_263 = _$numerical_145.BADNUM; +/* removed: var _$lib_163 = require('../../lib'); */; +var id2name = _$axis_ids_208.id2name; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$Sieve_264 = require('./sieve.js'); */; -/* - * 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 - */ +var _$handleConstraintDefaults_211 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); -var _$setPositions_263 = function setPositions(gd, plotinfo) { - var xa = plotinfo.xaxis, - ya = plotinfo.yaxis; + if(containerOut.fixedrange) return; - var fullTraces = gd._fullData, - calcTraces = gd.calcdata, - calcTracesHorizontal = [], - calcTracesVertical = [], - i; - for(i = 0; i < fullTraces.length; i++) { - var fullTrace = fullTraces[i]; - if( - fullTrace.visible === true && - _$registry_244.traceIs(fullTrace, 'bar') && - fullTrace.xaxis === xa._id && - fullTrace.yaxis === ya._id - ) { - if(fullTrace.orientation === 'h') { - calcTracesHorizontal.push(calcTraces[i]); - } - else { - calcTracesVertical.push(calcTraces[i]); - } + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_163.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' } - } - - setGroupPositions(gd, xa, ya, calcTracesVertical); - setGroupPositions(gd, ya, xa, calcTracesHorizontal); -}; + }, 'constraintoward'); + if(!containerIn.scaleanchor) return; -function setGroupPositions(gd, pa, sa, calcTraces) { - if(!calcTraces.length) return; + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - var barmode = gd._fullLayout.barmode, - overlay = (barmode === 'overlay'), - group = (barmode === 'group'), - excluded, - included, - i, calcTrace, fullTrace; - - if(overlay) { - setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces); - } - else if(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); - } - if(excluded.length) { - setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + var scaleanchor = _$lib_163.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes } - } - else { - // 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; + }, 'scaleanchor'); - if(fullTrace.base === undefined) included.push(calcTrace); - else excluded.push(calcTrace); - } + 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; - if(included.length) { - setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included); - } - if(excluded.length) { - setGroupPositionsInOverlayMode(gd, pa, sa, excluded); - } + updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_163.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.'); } +}; - collectExtents(calcTraces, pa); -} +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. + var thisType = layoutOut[id2name(thisID)].type; -function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { - var barnorm = gd._fullLayout.barnorm, - separateNegativeValues = false, - dontMergeOverlappingData = !barnorm; + var i, j, idj, axj; - // update position axis and set bar offsets and widths - for(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; + var linkableAxes = []; + for(j = 0; j < allAxisIds.length; j++) { + idj = allAxisIds[j]; + if(idj === thisID) continue; - var sieve = new _$Sieve_264( - [calcTrace], separateNegativeValues, dontMergeOverlappingData - ); + axj = layoutOut[id2name(idj)]; + if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); + } - // set bar offsets and widths, and update position axis - setOffsetAndWidth(gd, pa, sieve); + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; - // 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(barnorm) { - sieveBars(gd, sa, sieve); - normalizeBars(gd, sa, sieve); - } - else { - setBaseAndTop(gd, sa, sieve); + 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}; +} -function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { - var fullLayout = gd._fullLayout, - barnorm = fullLayout.barnorm, - separateNegativeValues = false, - dontMergeOverlappingData = !barnorm, - sieve = new _$Sieve_264( - calcTraces, separateNegativeValues, dontMergeOverlappingData - ); - // set bar offsets and widths, and update position axis - setOffsetAndWidthInGroupMode(gd, pa, sieve); +/* + * 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; - // set bar bases and sizes, and update size axis - if(barnorm) { - sieveBars(gd, sa, sieve); - normalizeBars(gd, sa, sieve); + if(thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); } else { - setBaseAndTop(gd, sa, sieve); + thisGroupIndex = constraintGroups.indexOf(thisGroup); } -} - - -function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { - var fullLayout = gd._fullLayout, - barmode = fullLayout.barmode, - stack = (barmode === 'stack'), - relative = (barmode === 'relative'), - barnorm = gd._fullLayout.barnorm, - separateNegativeValues = relative, - dontMergeOverlappingData = !(barnorm || stack || relative), - sieve = new _$Sieve_264( - calcTraces, separateNegativeValues, dontMergeOverlappingData - ); - - // set bar offsets and widths, and update position axis - setOffsetAndWidth(gd, pa, sieve); - - // set bar bases and sizes, and update size axis - stackBars(gd, sa, sieve); - // 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_263) continue; + var thisGroupKeys = Object.keys(thisGroup); - var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); - if(isOutmostBar) bar._outmost = true; + // 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; } } - // Note that marking the outmost bars has to be done - // before `normalizeBars` changes `bar.b` and `bar.s`. - if(barnorm) normalizeBars(gd, sa, sieve); + // 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; } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function setOffsetAndWidth(gd, pa, sieve) { - var fullLayout = gd._fullLayout, - bargap = fullLayout.bargap, - bargroupgap = fullLayout.bargroupgap, - minDiff = sieve.minDiff, - calcTraces = sieve.traces, - i, calcTrace, calcTrace0, - t; - - // set bar offsets and widths - var barGroupWidth = minDiff * (1 - bargap), - barWidthPlusGap = barGroupWidth, - barWidth = barWidthPlusGap * (1 - bargroupgap); - - // computer bar group center and bar offset - var offsetFromCenter = -barWidth / 2; - for(i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; +'use strict'; - // store bar width and offset for this trace - t = calcTrace0.t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; - } +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; - // stack bars that only differ by rounding - sieve.binWidth = calcTraces[0][0].t.barwidth / 100; +/* removed: var _$lib_163 = require('../../lib'); */; - // if defined, apply trace offset and width - applyAttributes(sieve); - // store the bar center in each calcdata item - setBarCenterAndWidth(gd, pa, sieve); +var _$handlePositionDefaults_220 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; - // update position axes - updatePositionAxis(gd, pa, sieve); -} + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; + } + } -function setOffsetAndWidthInGroupMode(gd, pa, sieve) { - var fullLayout = gd._fullLayout, - bargap = fullLayout.bargap, - bargroupgap = fullLayout.bargroupgap, - positions = sieve.positions, - distinctPositions = sieve.distinctPositions, - minDiff = sieve.minDiff, - calcTraces = sieve.traces, - i, calcTrace, calcTrace0, - t; + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_10(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; - // if there aren't any overlapping positions, - // let them have full width even if mode is group - var overlap = (positions.length !== distinctPositions.length); + var anchor = _$lib_163.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor + } + }, 'anchor'); - var nTraces = calcTraces.length, - barGroupWidth = minDiff * (1 - bargap), - barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth, - barWidth = barWidthPlusGap * (1 - bargroupgap); + if(anchor === 'free') coerce('position', dfltPosition); - for(i = 0; i < nTraces; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; + _$lib_163.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide + } + }, 'side'); - // computer bar group center and bar offset - var offsetFromCenter = (overlap) ? - ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : - -barWidth / 2; + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_163.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); + } - // store bar width and offset for this trace - t = calcTrace0.t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_163.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } - // stack bars that only differ by rounding - sieve.binWidth = calcTraces[0][0].t.barwidth / 100; + coerce('layer'); - // if defined, apply trace width - applyAttributes(sieve); + return containerOut; +}; - // store the bar center in each calcdata item - setBarCenterAndWidth(gd, pa, sieve); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // update position axes - updatePositionAxis(gd, pa, sieve, overlap); -} +'use strict'; -function applyAttributes(sieve) { - var calcTraces = sieve.traces, - i, calcTrace, calcTrace0, fullTrace, - j, - t; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$autoType_206 = require('./axis_autotype'); */; +var name2id = _$axis_ids_208.name2id; - for(i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; - fullTrace = calcTrace0.trace; - t = calcTrace0.t; +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_228 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); + } - var offset = fullTrace.offset, - initialPoffset = t.poffset, - newPoffset; + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - if(__isArrayOrTypedArray_263(offset)) { - // if offset is an array, then clone it into t.poffset. - newPoffset = offset.slice(0, calcTrace.length); + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; + } + } +}; - // guard against non-numeric items - for(j = 0; j < newPoffset.length; j++) { - if(!_$fastIsnumeric_10(newPoffset[j])) { - newPoffset[j] = initialPoffset; - } - } +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - // 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); - } + var id = ax._id; + var axLetter = id.charAt(0); - t.poffset = newPoffset; - } - else if(offset !== undefined) { - t.poffset = offset; - } + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; - var width = fullTrace.width, - initialBarwidth = t.barwidth; + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; - if(__isArrayOrTypedArray_263(width)) { - // if width is an array, then clone it into t.barwidth. - var newBarwidth = width.slice(0, calcTrace.length); + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } - // guard against non-numeric items - for(j = 0; j < newBarwidth.length; j++) { - if(!_$fastIsnumeric_10(newBarwidth[j])) newBarwidth[j] = initialBarwidth; - } + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; - // 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); - } + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - t.barwidth = newBarwidth; + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_245.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; - // 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; - } + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); + + if(trace[calAttr] !== calendar) calendar = undefined; } - 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; + ax.type = _$autoType_206(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_206(dim.values, calendar); + break; } } } + else { + ax.type = _$autoType_206(d0[axLetter] || [d0[axLetter + '0']], calendar); + } } +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; -function setBarCenterAndWidth(gd, pa, sieve) { - var calcTraces = sieve.traces, - pLetter = getAxisLetter(pa); - - for(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i], - t = calcTrace[0].t, - poffset = t.poffset, - poffsetIsArray = Array.isArray(poffset), - barwidth = t.barwidth, - 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; - + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } } } } +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} -function updatePositionAxis(gd, pa, sieve, allowMinDtick) { - var calcTraces = sieve.traces, - distinctPositions = sieve.distinctPositions, - distinctPositions0 = distinctPositions[0], - minDiff = sieve.minDiff, - vpad = minDiff / 2; +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_245.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_245.traceIs(trace._fullInput || {}, 'candlestick'); - _$axes_204.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); +} - // If the user set the bar width or the offset, - // then bars can be shifted away from their positions - // and widths can be larger than minDiff. - // - // Here, we compute pMin and pMax to expand the position axis, - // so that all bars are fully within the axis range. - var pMin = Math.min.apply(Math, distinctPositions) - vpad, - pMax = Math.max.apply(Math, distinctPositions) + vpad; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i], - calcTrace0 = calcTrace[0], - fullTrace = calcTrace0.trace; - if(fullTrace.width === undefined && fullTrace.offset === undefined) { - continue; - } +'use strict'; - var t = calcTrace0.t, - poffset = t.poffset, - barwidth = t.barwidth, - poffsetIsArray = Array.isArray(poffset), - barwidthIsArray = Array.isArray(barwidth); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$layout_attributes_235 = require('../layout_attributes'); */; - for(var j = 0; j < calcTrace.length; j++) { - var calcBar = calcTrace[j], - calcBarOffset = (poffsetIsArray) ? poffset[j] : poffset, - calcBarWidth = (barwidthIsArray) ? barwidth[j] : barwidth, - p = calcBar.p, - l = p + calcBarOffset, - r = l + calcBarWidth; +/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_228 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_207 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_211 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_220 = require('./position_defaults'); */; +/* removed: var _$axis_ids_208 = require('./axis_ids'); */; - pMin = Math.min(pMin, l); - pMax = Math.max(pMax, r); - } - } - _$axes_204.expand(pa, [pMin, pMax], {padded: false}); -} +var _$supplyLayoutDefaults_218 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -function expandRange(range, newValue) { - if(_$fastIsnumeric_10(range[0])) range[0] = Math.min(range[0], newValue); - else range[0] = newValue; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - if(_$fastIsnumeric_10(range[1])) range[1] = Math.max(range[1], newValue); - else range[1] = newValue; -} + if(!_$registry_245.traceIs(trace, 'cartesian') && !_$registry_245.traceIs(trace, 'gl2d')) { + continue; + } -function setBaseAndTop(gd, sa, sieve) { - // 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. - var traces = sieve.traces, - sLetter = getAxisLetter(sa), - sRange = [null, null]; + var xaName = _$axis_ids_208.id2name(trace.xaxis); + var yaName = _$axis_ids_208.id2name(trace.yaxis); - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_245.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - for(var j = 0; j < trace.length; j++) { - var bar = trace[j], - barBase = bar.b, - barTop = barBase + bar.s; + // 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) xaCheater[xaName] = 1; + } - bar[sLetter] = barTop; + // check for default formatting tweaks + if(_$registry_245.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } - if(_$fastIsnumeric_10(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_10(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$registry_245.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; } } - _$axes_204.expand(sa, sRange, {tozero: true, padded: true}); -} + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_163.simpleMap(xIds, _$axis_ids_208.id2name); + var yNames = _$lib_163.simpleMap(yIds, _$axis_ids_208.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 plot_bgcolor = _$color_43.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_235, 'plot_bgcolor'); + } -function stackBars(gd, sa, sieve) { - var fullLayout = gd._fullLayout, - barnorm = fullLayout.barnorm, - sLetter = getAxisLetter(sa), - traces = sieve.traces, - i, trace, - j, bar; + var bgColor = _$color_43.combine(plot_bgcolor, layoutOut.paper_bgcolor); - var sRange = [null, null]; + var axName, axLetter, axLayoutIn, axLayoutOut; - for(i = 0; i < traces.length; i++) { - trace = traces[i]; + function coerce(attr, dflt) { + return _$lib_163.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_217, attr, dflt); + } - for(j = 0; j < trace.length; j++) { - bar = trace[j]; + function coerce2(attr, dflt) { + return _$lib_163.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_217, attr, dflt); + } - if(bar.s === __BADNUM_263) continue; + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } - // stack current bar and get previous sum - var barBase = sieve.put(bar.p, bar.b + bar.s), - barTop = barBase + bar.b + bar.s; + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - // store the bar base and top in each calcdata item - bar.b = barBase; - bar[sLetter] = barTop; + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; - if(!barnorm) { - if(_$fastIsnumeric_10(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_10(sa.c2l(barBase))) expandRange(sRange, barBase); + for(var j = 0; j < list.length; j++) { + var axName2 = list[j]; + + if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { + out.push(_$axis_ids_208.name2id(axName2)); } } - } - // if barnorm is set, let normalizeBars update the axis range - if(!barnorm) _$axes_204.expand(sa, sRange, {tozero: true, padded: true}); -} + 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]; -function sieveBars(gd, sa, sieve) { - var traces = sieve.traces; + if(!_$lib_163.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; + _$handleTypeDefaults_228(axLayoutIn, axLayoutOut, coerce, fullData, axName); - if(bar.s !== __BADNUM_263) sieve.put(bar.p, bar.b + bar.s); - } - } -} + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; -function normalizeBars(gd, sa, sieve) { - // Note: - // - // normalizeBars requires that either sieveBars or stackBars has been - // previously invoked. + _$handleAxisDefaults_207(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - var traces = sieve.traces, - sLetter = getAxisLetter(sa), - sTop = (gd._fullLayout.barnorm === 'fraction') ? 1 : 100, - sTiny = sTop / 1e9, // in case of rounding error in sum - sMin = sa.l2c(sa.c2l(0)), - sMax = (gd._fullLayout.barmode === 'stack') ? sTop : sMin, - sRange = [sMin, sMax], - padded = false; + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - function maybeExpand(newValue) { - if(_$fastIsnumeric_10(sa.c2l(newValue)) && - ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_10(sMin)) - ) { - padded = true; - expandRange(sRange, newValue); + if(!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; } - } - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; + _$handlePositionDefaults_220(axLayoutIn, axLayoutOut, coerce, positioningOptions); - if(bar.s === __BADNUM_263) continue; + axLayoutOut._input = axLayoutIn; + } - var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); - bar.b *= scale; - bar.s *= scale; + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_245.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_245.getComponentMethod('rangeselector', 'handleDefaults'); - var barBase = bar.b, - barTop = barBase + bar.s; - bar[sLetter] = barTop; + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - maybeExpand(barTop); - if(bar.hasB) maybeExpand(barBase); + rangeSliderDefaults(layoutIn, layoutOut, axName); + + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); } - } - // update range of size axis - _$axes_204.expand(sa, sRange, {tozero: true, padded: padded}); -} + coerce('fixedrange'); + } + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; -function getAxisLetter(ax) { - return ax._id.charAt(0); -} + var anchoredAxis = layoutOut[_$axis_ids_208.id2name(axLayoutOut.anchor)]; -// 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 posLetter = pa._id.charAt(0); - var extents = {}; - var pMin = Infinity; - var pMax = -Infinity; + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - var i, j, cd; - for(i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - for(j = 0; j < cd.length; j++) { - var p = cd[j].p; - if(_$fastIsnumeric_10(p)) { - pMin = Math.min(pMin, p); - pMax = Math.max(pMax, p); - } - } + coerce('fixedrange', fixedRangeDflt); } - // 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))); - }; + // Finally, handle scale constraints. 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). - for(i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - cd[0].t.extents = extents; - for(j = 0; j < cd.length; j++) { - var di = cd[j]; - var p0 = di[posLetter] - di.w / 2; - if(_$fastIsnumeric_10(p0)) { - var p1 = di[posLetter] + 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]; - } - } - } + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); + + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + + _$handleConstraintDefaults_211(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); } -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -35525,738 +36398,444 @@ function collectExtents(calcTraces, pa) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_7 = require('d3'); */; + +/* removed: var _$registry_245 = require('../../registry'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$registry_244 = require('../../registry'); */; +/* removed: var _$axes_205 = require('./axes'); */; +var axisRegex = _$constants_210.attrRegex; -var _$style_265 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_7.select(gd).selectAll('g.trace.bars'); - var barcount = s.size(); +var _$transitionAxes_227 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { var fullLayout = gd._fullLayout; + var axes = []; - // trace styling - s.style('opacity', function(d) { return d[0].trace.opacity; }) + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - // for gapless (either stacked or neighboring grouped) bars use - // crispEdges to turn off antialiasing so an artificial gap - // isn't introduced. - .each(function(d) { - if((fullLayout.barmode === 'stack' && barcount > 1) || - (fullLayout.bargap === 0 && - fullLayout.bargroupgap === 0 && - !d[0].trace.marker.line.width)) { - _$d3_7.select(this).attr('shape-rendering', 'crispEdges'); + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; + + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; + + update.axisName = axisName; + update.length = axis._length; + + axes.push(axisLetter); + + updates[axisLetter] = update; + } } - }); - s.selectAll('g.points').each(function(d) { - var sel = _$d3_7.select(this); - var pts = sel.selectAll('path'); - var txs = sel.selectAll('text'); - var trace = d[0].trace; + return updates; + } - _$drawing_68.pointStyle(pts, trace, gd); - _$drawing_68.selectedPointStyle(pts, trace); + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - txs.each(function(d) { - var tx = _$d3_7.select(this); - var textFont; + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - if(tx.classed('bartext-inside')) { - textFont = trace.insidetextfont; - } else if(tx.classed('bartext-outside')) { - textFont = trace.outsidetextfont; + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; + + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; } - if(!textFont) textFont = trace.textfont; - function cast(k) { - var cont = textFont[k]; - return Array.isArray(cont) ? cont[d.i] : cont; + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); } + } - _$drawing_68.font(tx, cast('family'), cast('size'), cast('color')); - }); + return affectedSubplots; + } - _$drawing_68.selectedTextStyle(txs, trace); - }); + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - _$registry_244.getComponentMethod('errorbars', 'style')(s); -}; + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -'use strict'; + redrawObjs(fullLayout.annotations || [], _$registry_245.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_245.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_245.getComponentMethod('images', 'draw'), true); + } -var _$constants_45 = { - cn: { - colorbar: 'colorbar', - cbbg: 'cbbg', - cbfill: 'cbfill', - cbfills: 'cbfills', - cbline: 'cbline', - cblines: 'cblines', - cbaxis: 'cbaxis', - cbtitleunshift: 'cbtitleunshift', - cbtitle: 'cbtitle', - cboutline: 'cboutline', - crisp: 'crisp', - jsPlaceholder: 'js-placeholder' + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; + activeAxIds = [xa._id, ya._id]; -'use strict'; + for(i = 0; i < activeAxIds.length; i++) { + _$axes_205.doTicks(gd, activeAxIds[i], true); + } -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -var __extendFlat_47 = _$extend_156.extendFlat; -/* removed: var _$setCursor_181 = require('../../lib/setcursor'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$titles_136 = require('../titles'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -var __LINE_SPACING_47 = _$alignment_143.LINE_SPACING; + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } -/* removed: var _$handleAxisDefaults_206 = require('../../plots/cartesian/axis_defaults'); */; -/* removed: var _$handlePositionDefaults_220 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_216 = require('../../plots/cartesian/layout_attributes'); */; + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -/* removed: var _$attributes_44 = require('./attributes'); */; -var cn = _$constants_45.cn; + redrawObjs(fullLayout.annotations || [], _$registry_245.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_245.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_245.getComponentMethod('images', 'draw'), true); + } -var _$draw_47 = function draw(gd, id) { - // opts: options object, containing everything from attributes - // plus a few others that are the equivalent of the colorbar "data" - var opts = {}; - Object.keys(_$attributes_44).forEach(function(k) { - opts[k] = null; - }); - // fillcolor can be a d3 scale, domain is z values, range is colors - // or leave it out for no fill, - // or set to a string constant for single-color fill - opts.fillcolor = null; - // line.color has the same options as fillcolor - opts.line = {color: null, width: null, dash: null}; - // levels of lines to draw. - // note that this DOES NOT determine the extent of the bar - // that's given by the domain of fillcolor - // (or line.color if no fillcolor domain) - opts.levels = {start: null, end: null, size: null}; - // separate fill levels (for example, heatmap coloring of a - // contour map) if this is omitted, fillcolors will be - // evaluated halfway between levels - opts.filllevels = null; + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - function component() { - var fullLayout = gd._fullLayout, - gs = fullLayout._size; - if((typeof opts.fillcolor !== 'function') && - (typeof opts.line.color !== 'function')) { - fullLayout._infolayer.selectAll('g.' + id).remove(); - return; - } - var zrange = _$d3_7.extent(((typeof opts.fillcolor === 'function') ? - opts.fillcolor : opts.line.color).domain()); - var linelevels = []; - var filllevels = []; - var linecolormap = typeof opts.line.color === 'function' ? - opts.line.color : function() { return opts.line.color; }; - var fillcolormap = typeof opts.fillcolor === 'function' ? - opts.fillcolor : function() { return opts.fillcolor; }; - var l; - var i; + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_68.setTranslate, 0, 0) + .call(_$drawing_68.setScale, 1, 1); - var l0 = opts.levels.end + opts.levels.size / 100, - ls = opts.levels.size, - zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), - zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); - for(i = 0; i < 1e5; i++) { - l = opts.levels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zr0 && l < zr1) linelevels.push(l); - } + subplot.plot + .call(_$drawing_68.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_68.setScale, 1, 1); - if(typeof opts.fillcolor === 'function') { - if(opts.filllevels) { - l0 = opts.filllevels.end + opts.filllevels.size / 100; - ls = opts.filllevels.size; - for(i = 0; i < 1e5; i++) { - l = opts.filllevels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zrange[0] && l < zrange[1]) filllevels.push(l); - } - } - else { - filllevels = linelevels.map(function(v) { - return v - opts.levels.size / 2; - }); - filllevels.push(filllevels[filllevels.length - 1] + - opts.levels.size); - } - } - else if(opts.fillcolor && typeof opts.fillcolor === 'string') { - // doesn't matter what this value is, with a single value - // we'll make a single fill rect covering the whole bar - filllevels = [0]; - } + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); - if(opts.levels.size < 0) { - linelevels.reverse(); - filllevels.reverse(); - } + // 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_68.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_68.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_68.hideOutsideRangePoints, subplot); + } - // now make a Plotly Axes object to scale with and draw ticks - // TODO: does not support orientation other than right + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - // we calculate pixel sizes based on the specified graph size, - // not the actual (in case something pushed the margins around) - // which is a little odd but avoids an odd iterative effect - // when the colorbar itself is pushing the margins. - // but then the fractional size is calculated based on the - // actual graph size, so that the axes will size correctly. - var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, - originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, - thickPx = Math.round(opts.thickness * - (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), - thickFrac = thickPx / gs.w, - lenPx = Math.round(opts.len * - (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), - lenFrac = lenPx / gs.h, - xpadFrac = opts.xpad / gs.w, - yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, - ypadFrac = opts.ypad / gs.h, + var viewBox = []; - // x positioning: do it initially just for left anchor, - // then fix at the end (since we don't know the width yet) - xLeft = Math.round(opts.x * gs.w + opts.xpad), - // for dragging... this is getting a little muddled... - xLeftFrac = opts.x - thickFrac * - ({middle: 0.5, right: 1}[opts.xanchor]||0), + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - // y positioning we can do correctly from the start - yBottomFrac = opts.y + lenFrac * - (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), - yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), - yTopPx = yBottomPx - lenPx, - titleEl, - cbAxisIn = { - type: 'linear', - range: zrange, - tickmode: opts.tickmode, - nticks: opts.nticks, - tick0: opts.tick0, - dtick: opts.dtick, - tickvals: opts.tickvals, - ticktext: opts.ticktext, - ticks: opts.ticks, - ticklen: opts.ticklen, - tickwidth: opts.tickwidth, - tickcolor: opts.tickcolor, - showticklabels: opts.showticklabels, - tickfont: opts.tickfont, - tickangle: opts.tickangle, - tickformat: opts.tickformat, - exponentformat: opts.exponentformat, - separatethousands: opts.separatethousands, - showexponent: opts.showexponent, - showtickprefix: opts.showtickprefix, - tickprefix: opts.tickprefix, - showticksuffix: opts.showticksuffix, - ticksuffix: opts.ticksuffix, - title: opts.title, - titlefont: opts.titlefont, - showline: true, - anchor: 'free', - position: 1 - }, - cbAxisOut = { - type: 'linear', - _id: 'y' + id - }, - axisOptions = { - letter: 'y', - font: fullLayout.font, - noHover: true, - calendar: fullLayout.calendar // not really necessary (yet?) - }; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - // Coerce w.r.t. Axes layoutAttributes: - // re-use axes.js logic without updating _fullData - function coerce(attr, dflt) { - return _$lib_162.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_216, attr, dflt); + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; } - // Prepare the Plotly axis object - _$handleAxisDefaults_206(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); - _$handlePositionDefaults_220(cbAxisIn, cbAxisOut, coerce, axisOptions); - - // position can't go in through supplyDefaults - // because that restricts it to [0,1] - cbAxisOut.position = opts.x + xpadFrac + thickFrac; + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // save for other callers to access this axis - component.axis = cbAxisOut; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - cbAxisOut.titleside = opts.titleside; - cbAxisOut.titlex = opts.x + xpadFrac; - cbAxisOut.titley = yBottomFrac + - (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; } - if(opts.line.color && opts.tickmode === 'auto') { - cbAxisOut.tickmode = 'linear'; - cbAxisOut.tick0 = opts.levels.start; - var dtick = opts.levels.size; - // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_162.constrain( - (yBottomPx - yTopPx) / 50, 4, 15) + 1, - dtFactor = (zrange[1] - zrange[0]) / - ((opts.nticks || autoNtick) * dtick); - if(dtFactor > 1) { - var dtexp = Math.pow(10, Math.floor( - Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_162.roundUp(dtFactor / dtexp, [2, 5, 10]); - // if the contours are at round multiples, reset tick0 - // so they're still at round multiples. Otherwise, - // keep the first label on the first contour level - if((Math.abs(opts.levels.start) / - opts.levels.size + 1e-6) % 1 < 2e-6) { - cbAxisOut.tick0 = 0; - } - } - cbAxisOut.dtick = dtick; - } + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - // set domain after init, because we may want to - // allow it outside [0,1] - cbAxisOut.domain = [ - yBottomFrac + ypadFrac, - yBottomFrac + lenFrac - ypadFrac - ]; - cbAxisOut.setScale(); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_7.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); - container.attr('transform', 'translate(' + Math.round(gs.l) + - ',' + Math.round(gs.t) + ')'); - // TODO: this opposite transform is a hack until we make it - // more rational which items get this offset - var titleCont = container.select('.cbtitleunshift') - .attr('transform', 'translate(-' + - Math.round(gs.l) + ',-' + - Math.round(gs.t) + ')'); + var editX = !!xUpdate; + var editY = !!yUpdate; - cbAxisOut._axislayer = container.select('.cbaxis'); - var titleHeight = 0; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // draw the title so we know how much room it needs - // when we squish the axis. This one only applies to - // top or bottom titles, not right side. - var x = gs.l + (opts.x + xpadFrac) * gs.w, - fontSize = cbAxisOut.titlefont.size, - y; + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - if(opts.titleside === 'top') { - y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + - gs.t + 3 + fontSize * 0.75; - } - else { - y = (1 - (yBottomFrac + ypadFrac)) * gs.h + - gs.t - 3 - fontSize * 0.25; - } - drawTitle(cbAxisOut._id + 'title', { - attributes: {x: x, y: y, 'text-anchor': 'start'} - }); - } + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - function drawAxis() { - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // squish the axis top to make room for the title - var titleGroup = container.select('.cbtitle'), - titleText = titleGroup.select('text'), - titleTrans = - [-opts.outlinewidth / 2, opts.outlinewidth / 2], - mathJaxNode = titleGroup - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - lineSize = 15.6; - if(titleText.node()) { - lineSize = - parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_47; - } - if(mathJaxNode) { - titleHeight = _$drawing_68.bBox(mathJaxNode).height; - if(titleHeight > lineSize) { - // not entirely sure how mathjax is doing - // vertical alignment, but this seems to work. - titleTrans[1] -= (titleHeight - lineSize) / 2; - } - } - else if(titleText.node() && - !titleText.classed(cn.jsPlaceholder)) { - titleHeight = _$drawing_68.bBox(titleText.node()).height; - } - if(titleHeight) { - // buffer btwn colorbar and title - // TODO: configurable - titleHeight += 5; + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - if(opts.titleside === 'top') { - cbAxisOut.domain[1] -= titleHeight / gs.h; - titleTrans[1] *= -1; - } - else { - cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_183.lineCount(titleText); - titleTrans[1] += (1 - nlines) * lineSize; - } + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - titleGroup.attr('transform', - 'translate(' + titleTrans + ')'); + subplot.clipRect + .call(_$drawing_68.setTranslate, clipDx, clipDy) + .call(_$drawing_68.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - cbAxisOut.setScale(); - } - } + subplot.plot + .call(_$drawing_68.setTranslate, plotDx, plotDy) + .call(_$drawing_68.setScale, xScaleFactor, yScaleFactor) - container.selectAll('.cbfills,.cblines') - .attr('transform', 'translate(0,' + - Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_68.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - cbAxisOut._axislayer.attr('transform', 'translate(0,' + - Math.round(-gs.t) + ')'); + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_68.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + } - var fills = container.select('.cbfills') - .selectAll('rect.cbfill') - .data(filllevels); - fills.enter().append('rect') - .classed(cn.cbfill, true) - .style('stroke', 'none'); - fills.exit().remove(); - fills.each(function(d, i) { - var z = [ - (i === 0) ? zrange[0] : - (filllevels[i] + filllevels[i - 1]) / 2, - (i === filllevels.length - 1) ? zrange[1] : - (filllevels[i] + filllevels[i + 1]) / 2 - ] - .map(cbAxisOut.c2p) - .map(Math.round); + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } - // offset the side adjoining the next rectangle so they - // overlap, to prevent antialiasing gaps - if(i !== filllevels.length - 1) { - z[1] += (z[1] > z[0]) ? 1 : -1; - } + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; + axi.range = to.slice(); + } - // Tinycolor can't handle exponents and - // at this scale, removing it makes no difference. - var colorString = fillcolormap(d).replace('e-', ''), - opaqueColor = _$tinycolor_25(colorString).toHexString(); + // Signal that this transition has completed: + onComplete && onComplete(); - // Colorbar cannot currently support opacities so we - // use an opaque fill even when alpha channels present - _$d3_7.select(this).attr({ - x: xLeft, - width: Math.max(thickPx, 2), - y: _$d3_7.min(z), - height: Math.max(_$d3_7.max(z) - _$d3_7.min(z), 2), - fill: opaqueColor - }); - }); + return _$registry_245.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var lines = container.select('.cblines') - .selectAll('path.cbline') - .data(opts.line.color && opts.line.width ? - linelevels : []); - lines.enter().append('path') - .classed(cn.cbline, true); - lines.exit().remove(); - lines.each(function(d) { - _$d3_7.select(this) - .attr('d', 'M' + xLeft + ',' + - (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + - 'h' + thickPx) - .call(_$drawing_68.lineGroupStyle, - opts.line.width, linecolormap(d), opts.line.dash); - }); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; - // force full redraw of labels and ticks - cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') - .remove(); + axi.range = axi._r.slice(); + } - cbAxisOut._pos = xLeft + thickPx + - (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); - cbAxisOut.side = 'right'; + return _$registry_245.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - // separate out axis and title drawing, - // so we don't need such complicated logic in Titles.draw - // if title is on the top or bottom, we've already drawn it - // this title call only handles side=right - return _$lib_162.syncOrAsync([ - function() { - return _$axes_204.doTicks(gd, cbAxisOut, true); - }, - function() { - if(['top', 'bottom'].indexOf(opts.titleside) === -1) { - var fontSize = cbAxisOut.titlefont.size, - y = cbAxisOut._offset + cbAxisOut._length / 2, - x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? - 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : - -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); + var t1, t2, raf; + var easeFn = _$d3_7.ease(transitionOpts.easing); - // the 'h' + is a hack to get around the fact that - // convertToTspans rotates any 'y...' class by 90 degrees. - // TODO: find a better way to control this. - drawTitle('h' + cbAxisOut._id + 'title', { - avoid: { - selection: _$d3_7.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), - side: opts.titleside, - offsetLeft: gs.l, - offsetTop: 0, - maxShift: fullLayout.width - }, - attributes: {x: x, y: y, 'text-anchor': 'middle'}, - transform: {rotate: '-90', offset: 0} - }); - } - }]); - } + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); - function drawTitle(titleClass, titleOpts) { - var trace = getTrace(), - propName; - if(_$registry_244.traceIs(trace, 'markerColorscale')) { - propName = 'marker.colorbar.title'; - } - else propName = 'colorbar.title'; + function doFrame() { + t2 = Date.now(); - var dfltTitleOpts = { - propContainer: cbAxisOut, - propName: propName, - traceIndex: trace.index, - placeholder: fullLayout._dfltTitle.colorbar, - containerGroup: container.select('.cbtitle') - }; + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); - // this class-to-rotate thing with convertToTspans is - // getting hackier and hackier... delete groups with the - // wrong class (in case earlier the colorbar was drawn on - // a different side, I think?) - var otherClass = titleClass.charAt(0) === 'h' ? - titleClass.substr(1) : ('h' + titleClass); - container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') - .remove(); + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } - _$titles_136.draw(gd, titleClass, - __extendFlat_47(dfltTitleOpts, titleOpts || {})); + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); } + } - function positionCB() { - // wait for the axis & title to finish rendering before - // continuing positioning - // TODO: why are we redrawing multiple times now with this? - // I guess autoMargin doesn't like being post-promise? - var innerWidth = thickPx + opts.outlinewidth / 2 + - _$drawing_68.bBox(cbAxisOut._axislayer.node()).width; - titleEl = titleCont.select('text'); - if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { - var mathJaxNode = titleCont - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - titleWidth; - if(mathJaxNode && - ['top', 'bottom'].indexOf(opts.titleside) !== -1) { - titleWidth = _$drawing_68.bBox(mathJaxNode).width; - } - else { - // note: the formula below works for all titlesides, - // (except for top/bottom mathjax, above) - // but the weird gs.l is because the titleunshift - // transform gets removed by Drawing.bBox - titleWidth = - _$drawing_68.bBox(titleCont.node()).right - - xLeft - gs.l; - } - innerWidth = Math.max(innerWidth, titleWidth); - } - - var outerwidth = 2 * opts.xpad + innerWidth + - opts.borderwidth + opts.outlinewidth / 2, - outerheight = yBottomPx - yTopPx; + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - container.select('.cbbg').attr({ - x: xLeft - opts.xpad - - (opts.borderwidth + opts.outlinewidth) / 2, - y: yTopPx - yExtraPx, - width: Math.max(outerwidth, 2), - height: Math.max(outerheight + 2 * yExtraPx, 2) - }) - .call(_$color_43.fill, opts.bgcolor) - .call(_$color_43.stroke, opts.bordercolor) - .style({'stroke-width': opts.borderwidth}); + return Promise.resolve(); +}; - container.selectAll('.cboutline').attr({ - x: xLeft, - y: yTopPx + opts.ypad + - (opts.titleside === 'top' ? titleHeight : 0), - width: Math.max(thickPx, 2), - height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) - }) - .call(_$color_43.stroke, opts.outlinecolor) - .style({ - fill: 'None', - 'stroke-width': opts.outlinewidth - }); +var _$get_data_233 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // fix positioning for xanchor!='left' - var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * - outerwidth; - container.attr('transform', - 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); +'use strict'; - // auto margin adjustment - _$plots_237.autoMargin(gd, id, { - x: opts.x, - y: opts.y, - l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), - r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), - t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), - b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) - }); - } +/* removed: var _$registry_245 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_210.SUBPLOT_PATTERN; - var cbDone = _$lib_162.syncOrAsync([ - _$plots_237.previousPromises, - drawAxis, - _$plots_237.previousPromises, - positionCB - ], gd); +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_233.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_245.subplotsRegistry[type]; + if(!basePlotModule) return []; - if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); + var attr = basePlotModule.attr; + var subplotCalcData = []; - // dragging... - if(gd._context.edits.colorbarPosition) { - var t0, - xf, - yf; + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; - _$dragelement_65.init({ - element: container.node(), - gd: gd, - prepFn: function() { - t0 = container.attr('transform'); - _$setCursor_181(container); - }, - moveFn: function(dx, dy) { - container.attr('transform', - t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + } - xf = _$dragelement_65.align(xLeftFrac + (dx / gs.w), thickFrac, - 0, 1, opts.xanchor); - yf = _$dragelement_65.align(yBottomFrac - (dy / gs.h), lenFrac, - 0, 1, opts.yanchor); + return subplotCalcData; +}; +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_233.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_245.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; - var csr = _$dragelement_65.getCursor(xf, yf, - opts.xanchor, opts.yanchor); - _$setCursor_181(container, csr); - }, - doneFn: function() { - _$setCursor_181(container); + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; - if(xf !== undefined && yf !== undefined) { - _$registry_244.call('restyle', - gd, - {'colorbar.x': xf, 'colorbar.y': yf}, - getTrace().index - ); - } - } - }); + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); } - return cbDone; - } - - function getTrace() { - var idNum = id.substr(2), - i, - trace; - for(i = 0; i < gd._fullData.length; i++) { - trace = gd._fullData[i]; - if(trace.uid === idNum) return trace; + else { + remainingCalcData.push(cd); } } - // setter/getters for every item defined in opts - Object.keys(opts).forEach(function(name) { - component[name] = function(v) { - // getter - if(!arguments.length) return opts[name]; + return [moduleCalcData, remainingCalcData]; +}; - // setter - for multi-part properties, - // set only the parts that are provided - opts[name] = _$lib_162.isPlainObject(opts[name]) ? - _$lib_162.extendFlat(opts[name], v) : - v; +/** + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_233.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_245.subplotsRegistry[type]) return []; - return component; - }; - }); + var attr = _$registry_245.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; - // or use .options to set multiple options at once via a dictionary - component.options = function(o) { - Object.keys(o).forEach(function(name) { - // in case something random comes through - // that's not an option, ignore it - if(typeof component[name] === 'function') { - component[name](o[name]); - } - }); - return component; - }; + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } - component._opts = opts; + for(var i = 0; i < data.length; i++) { + trace = data[i]; - return component; + if(type === 'gl2d' && _$registry_245.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); + } + } + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } + } + + return subplotData; }; +var _$cartesian_216 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -36268,1701 +36847,1223 @@ var _$draw_47 = function draw(gd, id) { 'use strict'; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$plots_237 = require('../plots'); */; +var getModuleCalcData = _$get_data_233.getModuleCalcData; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$colorscale_58 = require('../../components/colorscale'); */; -/* removed: var _$draw_47 = require('../../components/colorbar/draw'); */; +/* removed: var _$axis_ids_208 = require('./axis_ids'); */; +/* removed: var _$constants_210 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; +var ensureSingle = _$lib_163.ensureSingle; -var _$colorbar_284 = function colorbar(gd, cd) { - var trace = cd[0].trace, - marker = trace.marker, - cbId = 'cb' + trace.uid; +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_163.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} - gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); +_$cartesian_216.name = 'cartesian'; - // TODO make Colorbar.draw support multiple colorbar per trace +_$cartesian_216.attr = ['xaxis', 'yaxis']; - if((marker === undefined) || !marker.showscale) { - _$plots_237.autoMargin(gd, cbId); - return; - } +_$cartesian_216.idRoot = ['x', 'y']; - var vals = marker.color, - cmin = marker.cmin, - cmax = marker.cmax; +_$cartesian_216.idRegex = _$constants_210.idRegex; - if(!_$fastIsnumeric_10(cmin)) cmin = _$lib_162.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_10(cmax)) cmax = _$lib_162.aggNums(Math.max, null, vals); +_$cartesian_216.attrRegex = _$constants_210.attrRegex; - var cb = cd[0].t.cb = _$draw_47(gd, cbId); - var sclFunc = _$colorscale_58.makeColorScaleFunc( - _$colorscale_58.extractScale( - marker.colorscale, - cmin, - cmax - ), - { noNumericCheck: true } - ); +_$cartesian_216.attributes = _$attributes_203; - cb.fillcolor(sclFunc) - .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) - .options(marker.colorbar)(); -}; +_$cartesian_216.layoutAttributes = _$layout_attributes_217; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +_$cartesian_216.supplyLayoutDefaults = _$supplyLayoutDefaults_218; +_$cartesian_216.transitionAxes = _$transitionAxes_227; -'use strict'; +_$cartesian_216.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; -var Bar = {}; + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; + } -Bar.attributes = _$attributes_254; -Bar.layoutAttributes = _$layout_attributes_259; -Bar.supplyDefaults = _$supplyDefaults_256; -Bar.supplyLayoutDefaults = _$layout_defaults_260; -Bar.calc = _$calc_255; -Bar.setPositions = _$setPositions_263; -Bar.colorbar = _$colorbar_284; -Bar.arraysToCalcdata = _$arraysToCalcdata_253; -Bar.plot = _$plot_261; -Bar.style = _$style_265; -Bar.hoverPoints = _$hoverPoints_257; -Bar.selectPoints = _$selectPoints_262; + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_208.id2name(xi)] || {}).anchor; + if(!_$constants_210.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); -Bar.moduleType = 'trace'; -Bar.name = 'bar'; -Bar.basePlotModule = _$cartesian_215; -Bar.categories = ['cartesian', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend']; -Bar.meta = { - + if(!allY[yi]) { + allY[yi] = 1; + _$lib_163.pushUnique(yList, yi); + } + } + } + + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_208.id2name(yi)] || {}).anchor; + if(!_$constants_210.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); + + if(!allX[xi]) { + allX[xi] = 1; + _$lib_163.pushUnique(xList, xi); + } + } + } + + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_210.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } + } + xi = xi ? _$axis_ids_208.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_208.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } }; -var _$Bar_258 = Bar; +_$cartesian_216.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; -'use strict'; + for(i = 0; i < calcdata.length; i++) { + traces.push(i); + } + } -var _$bar_3 = _$Bar_258; + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; -var _$plotcss_1 = {}; -'use strict'; + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; -/* removed: var _$lib_162 = require('../src/lib'); */; -var rules = { - "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", - "X .modebar--hover": "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": "opacity:1;", - "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", - "X .modebar-group:first-child": "margin-left:0px;", - "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", - "X .modebar-btn svg": "position:relative;top:2px;", - "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", - "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", - "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", - "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", - "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 .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 j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; + + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } + + cdSubplot.push(cd); + } + + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } + } + + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + } }; -for(var selector in rules) { - var fullSelector = selector.replace(/^,/,' ,') - .replace(/X/g, '.js-plotly-plot .plotly') - .replace(/Y/g, '.plotly-notifier'); - _$lib_162.addStyleRule(fullSelector, rules[selector]); +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; + + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); + } + + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; + + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; + + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; + + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + } } -'use strict'; +_$cartesian_216.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; -var _$ploticon_2 = { - 'undo': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'home': { - 'width': 928.6, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'camera-retro': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoombox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'pan': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_plus': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_minus': { - 'width': 1000, - 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', - 'ascent': 850, - 'descent': -150 - }, - 'autoscale': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_basic': { - 'width': 1500, - 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_compare': { - 'width': 1125, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'plotlylogo': { - 'width': 1542, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'z-axis': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - '3d_rotate': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'camera': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'movie': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'question': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'disk': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'lasso': { - 'width': 1031, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'selectbox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'spikeline': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - } -}; - -var _$browser_24 = {}; -// shim for using process in browser -var process = _$browser_24 = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } + + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; } + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } + + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); } } + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } } -} -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); } } - queueIndex = -1; - len = queue.length; } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } } }; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; +_$cartesian_216.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); -function __noop_24() {} + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_163.identity); -process.on = __noop_24; -process.addListener = __noop_24; -process.once = __noop_24; -process.off = __noop_24; -process.removeListener = __noop_24; -process.removeAllListeners = __noop_24; -process.emit = __noop_24; -process.prependListener = __noop_24; -process.prependOnceListener = __noop_24; + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); -process.listeners = function (name) { return [] } + subplotLayers.order(); -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; -var _$es6Promise_8 = { exports: {} }; -(function (process,global){ -/*! - * @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 - */ + // keep ref to plot group + plotinfo.plotgroup = _$d3_7.select(this); -(function (global, factory) { - typeof _$es6Promise_8.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_8.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ES6Promise = factory()); -}(this, (function () { 'use strict'; + // initialize list of overlay subplots + plotinfo.overlays = []; -function objectOrFunction(x) { - return typeof x === 'function' || typeof x === 'object' && x !== null; -} + makeSubplotLayer(gd, plotinfo); -function isFunction(x) { - return typeof x === 'function'; -} + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); + } -var _isArray = undefined; -if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} else { - _isArray = Array.isArray; -} + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; -var isArray = _isArray; +_$cartesian_216.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_237.style(gd); +}; -var len = 0; -var vertxNext = undefined; -var customSchedulerFn = undefined; +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; -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(); + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; + + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; + } } - } -}; -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; -} + // main subplots before overlays + subplotData = subplotData.concat(overlays); -function setAsap(asapFn) { - asap = asapFn; + return subplotData; } -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'; +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_210.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_210.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; -// 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); - }; -} + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); -// vertx -function useVertxTimer() { - return function () { - vertxNext(flush); - }; -} + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - return function () { - node.data = iterations = ++iterations % 2; - }; -} + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); - }; -} + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); -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); - }; -} + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); - callback(arg); + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } + } + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - queue[i] = undefined; - queue[i + 1] = undefined; - } + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. - len = 0; -} + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; -function attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); -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 && typeof require === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); -} + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); -function then(onFulfillment, onRejection) { - var _arguments = arguments; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - var parent = this; + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + } - var child = new this.constructor(noop); + // common attributes for all subplots, overlays or not - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_208.idSort); - var _state = parent._state; + for(var i = 0; i < _$constants_210.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_210.traceLayerClasses[i]); + } + } - if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - return child; + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); } -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - ```javascript - let promise = new Promise(function(resolve, reject){ - resolve(1); - }); + var overlayIdsToRemove = {}; - promise.then(function(value){ - // value === 1 - }); - ``` + layers.each(function(subplotId) { + var plotgroup = _$d3_7.select(this); - Instead of writing the above, your code now simply becomes the following: + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - ```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); + overlayIdsToRemove[subplotId] = true; -function noop() {} + // do not remove individual axis s here + // as other subplots may need them + }); -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; + // must remove overlaid subplot trace layers 'manually' -var GET_THEN_ERROR = new ErrorObject(); + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; -function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } + } + } } -function tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); } -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; +_$cartesian_216.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_7.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - _reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); - if (!sealed && error) { - sealed = true; - _reject(promise, error); + image.attr({ + xmlns: _$xmlns_namespaces_147.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); } - }, 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); - }); - } -} + canvases.each(canvasToImage); +}; -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); - } - } -} +_$cartesian_216.updateFx = _$graph_interact_214.updateFx; -function _resolve(promise, value) { - if (promise === value) { - _reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - publish(promise); -} +'use strict'; -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } +var mergeArray = _$lib_163.mergeArray; - promise._result = value; - promise._state = FULFILLED; - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} +// arrayOk attributes, merge them into calcdata array +var _$arraysToCalcdata_254 = function arraysToCalcdata(cd, trace) { + for(var i = 0; i < cd.length; i++) cd[i].i = i; -function _reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; + mergeArray(trace.text, cd, 'tx'); + mergeArray(trace.hovertext, cd, 'htx'); - asap(publishRejection, promise); -} + var marker = trace.marker; + if(marker) { + mergeArray(marker.opacity, cd, 'mo'); + mergeArray(marker.color, cd, 'mc'); -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; + var markerLine = marker.line; + if(markerLine) { + mergeArray(markerLine.color, cd, 'mlc'); + mergeArray(markerLine.width, cd, 'mlw'); + } + } +}; - parent._onerror = null; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; +'use strict'; - if (length === 0 && parent._state) { - asap(publish, parent); - } -} +/* removed: var _$attributes_281 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_51 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_44 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; +var __extendFlat_255 = _$extend_157.extendFlat; - if (subscribers.length === 0) { - return; - } +var textFontAttrs = _$font_attributes_231({ + editType: 'calc', + arrayOk: true, + +}); - var child = undefined, - callback = undefined, - detail = promise._result; +var __scatterMarkerAttrs_255 = _$attributes_281.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_255.line; - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; +var markerLineWidth = __extendFlat_255({}, + scatterMarkerLineAttrs.width, { dflt: 0 }); - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } +var markerLine = __extendFlat_255({ + width: markerLineWidth, + editType: 'calc' +}, _$makeColorScaleAttributes_51('marker.line')); - promise._subscribers.length = 0; -} +var marker = __extendFlat_255({ + line: markerLine, + editType: 'calc' +}, _$makeColorScaleAttributes_51('marker'), { + showscale: __scatterMarkerAttrs_255.showscale, + colorbar: _$attributes_44, + opacity: { + valType: 'number', + arrayOk: true, + dflt: 1, + min: 0, + max: 1, + + editType: 'style', + + } +}); -function ErrorObject() { - this.error = null; -} +var _$attributes_255 = { + x: _$attributes_281.x, + x0: _$attributes_281.x0, + dx: _$attributes_281.dx, + y: _$attributes_281.y, + y0: _$attributes_281.y0, + dy: _$attributes_281.dy, -var TRY_CATCH_ERROR = new ErrorObject(); + text: _$attributes_281.text, + hovertext: _$attributes_281.hovertext, -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} + textposition: { + valType: 'enumerated', + + values: ['inside', 'outside', 'auto', 'none'], + dflt: 'none', + arrayOk: true, + editType: 'calc', + + }, -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; + textfont: __extendFlat_255({}, textFontAttrs, { + + }), - if (hasCallback) { - value = tryCatch(callback, detail); + insidetextfont: __extendFlat_255({}, textFontAttrs, { + + }), - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } + outsidetextfont: __extendFlat_255({}, textFontAttrs, { + + }), - if (promise === value) { - _reject(promise, cannotReturnOwn()); - return; - } - } else { - value = detail; - succeeded = true; - } + constraintext: { + valType: 'enumerated', + values: ['inside', 'outside', 'both', 'none'], + + dflt: 'both', + editType: 'calc', + + }, - 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); - } -} + cliponaxis: __extendFlat_255({}, _$attributes_281.cliponaxis, { + + }), -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value) { - _resolve(promise, value); - }, function rejectPromise(reason) { - _reject(promise, reason); - }); - } catch (e) { - _reject(promise, e); - } -} + orientation: { + valType: 'enumerated', + + values: ['v', 'h'], + editType: 'calc+clearAxisTypes', + + }, -var id = 0; -function nextId() { - return id++; -} + base: { + valType: 'any', + dflt: null, + arrayOk: true, + + editType: 'calc', + + }, -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; -} + offset: { + valType: 'number', + dflt: null, + arrayOk: true, + + editType: 'calc', + + }, -function Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); + width: { + valType: 'number', + dflt: null, + min: 0, + arrayOk: true, + + editType: 'calc', + + }, - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } + marker: marker, - if (isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; + selected: { + marker: { + opacity: _$attributes_281.selected.marker.opacity, + color: _$attributes_281.selected.marker.color, + editType: 'style' + }, + textfont: _$attributes_281.selected.textfont, + editType: 'style' + }, + unselected: { + marker: { + opacity: _$attributes_281.unselected.marker.opacity, + color: _$attributes_281.unselected.marker.color, + editType: 'style' + }, + textfont: _$attributes_281.unselected.textfont, + editType: 'style' + }, - this._result = new Array(this.length); + r: _$attributes_281.r, + t: _$attributes_281.t, - 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); - } + _deprecated: { + bardir: { + valType: 'enumerated', + + editType: 'calc', + values: ['v', 'h'], + + } } - } 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); - } -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -Enumerator.prototype._eachEntry = function (entry, i) { - var c = this._instanceConstructor; - var resolve$$ = c.resolve; +'use strict'; - if (resolve$$ === resolve) { - var _then = getThen(entry); +/* removed: var _$lib_163 = require('../../lib'); */; - 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); +var _$calcSelection_283 = function calcSelection(cd, trace) { + if(_$lib_163.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_163.tagSelected(cd, trace); } - } else { - this._willSettleAt(resolve$$(entry), i); - } }; -Enumerator.prototype._settledAt = function (state, i, value) { - var promise = this.promise; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (promise._state === PENDING) { - this._remaining--; - if (state === REJECTED) { - _reject(promise, value); - } else { - this._result[i] = value; - } - } +'use strict'; - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_256 = _$lib_163.isArrayOrTypedArray; -Enumerator.prototype._willSettleAt = function (promise, i) { - var enumerator = this; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_50 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_254 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_283 = require('../scatter/calc_selection'); */; - subscribe(promise, undefined, function (value) { - return enumerator._settledAt(FULFILLED, i, value); - }, function (reason) { - return enumerator._settledAt(REJECTED, i, reason); - }); -}; +var _$calc_256 = function calc(gd, trace) { + // depending on bar direction, set position and size axes + // and data ranges + // note: this logic for choosing orientation is + // duplicated in graph_obj->setstyles -/** - `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. + var xa = _$axes_205.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_205.getFromId(gd, trace.yaxis || 'y'), + orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), + sa, pos, size, i, scalendar; - Example: + if(orientation === 'h') { + sa = xa; + size = xa.makeCalcdata(trace, 'x'); + pos = ya.makeCalcdata(trace, 'y'); - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; + // 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. + scalendar = trace.xcalendar; + } + else { + sa = ya; + size = ya.makeCalcdata(trace, 'y'); + pos = xa.makeCalcdata(trace, 'x'); + scalendar = trace.ycalendar; + } - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` + // create the "calculated data" to plot + var serieslen = Math.min(pos.length, size.length); + var cd = new Array(serieslen); - 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: + // set position and size + for(i = 0; i < serieslen; i++) { + cd[i] = { p: pos[i], s: size[i] }; - Example: + if(trace.ids) { + cd[i].id = String(trace.ids[i]); + } + } - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; + // set base + var base = trace.base, + b; - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` + if(__isArrayOrTypedArray_256(base)) { + for(i = 0; i < Math.min(base.length, cd.length); i++) { + b = sa.d2c(base[i], 0, scalendar); + if(_$fastIsnumeric_10(b)) { + cd[i].b = +b; + cd[i].hasB = 1; + } + else cd[i].b = 0; + } + for(; i < cd.length; i++) { + cd[i].b = 0; + } + } + else { + b = sa.d2c(base, 0, scalendar); + var hasBase = _$fastIsnumeric_10(b); + b = hasBase ? b : 0; + for(i = 0; i < cd.length; i++) { + cd[i].b = b; + if(hasBase) cd[i].hasB = 1; + } + } - @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; -} + // auto-z and autocolorscale if applicable + if(_$hasColorscale_57(trace, 'marker')) { + _$calc_50(trace, trace.marker.color, 'marker', 'c'); + } + if(_$hasColorscale_57(trace, 'marker.line')) { + _$calc_50(trace, trace.marker.line.color, 'marker.line', 'c'); + } -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. + _$arraysToCalcdata_254(cd, trace); + _$calcSelection_283(cd, trace); - Example: + return cd; +}; - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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. - }); - ``` +'use strict'; - `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: +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_53 = require('../../components/colorscale/defaults'); */; - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); +var _$handleStyleDefaults_267 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { + coerce('marker.color', defaultColor); - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); + if(_$hasColorscale_57(traceIn, 'marker')) { + _$colorScaleDefaults_53( + traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} + ); + } - 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 - }); - ``` + coerce('marker.line.color', _$color_43.defaultLine); - An example real-world use case is implementing timeouts: + if(_$hasColorscale_57(traceIn, 'marker.line')) { + _$colorScaleDefaults_53( + traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} + ); + } - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` + coerce('marker.line.width'); + coerce('marker.opacity'); + coerce('selected.marker.color'); + coerce('unselected.marker.color'); +}; - @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. +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. */ -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: +'use strict'; - ```javascript - let promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); +/* removed: var _$registry_245 = require('../../registry'); */; - 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: +var _$handleXYDefaults_305 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { + var len, + x = coerce('x'), + y = coerce('y'); - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); + var handleCalendarDefaults = _$registry_245.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + if(x) { + if(y) { + len = Math.min(x.length, y.length); + } + else { + len = x.length; + coerce('y0'); + coerce('dy'); + } + } + else { + if(!y) return 0; - @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; -} + len = traceOut.y.length; + coerce('x0'); + coerce('dx'); + } -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} + traceOut._length = len; -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} + return len; +}; /** - 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. +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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. +'use strict'; - A promise can be in one of three states: pending, fulfilled, or rejected. +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$registry_245 = require('../../registry'); */; - 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. +/* removed: var _$handleXYDefaults_305 = require('../scatter/xy_defaults'); */; +/* removed: var _$handleStyleDefaults_267 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_255 = require('./attributes'); */; - 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. +var _$supplyDefaults_257 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_163.coerce(traceIn, traceOut, _$attributes_255, attr, dflt); + } + var coerceFont = _$lib_163.coerceFont; - Basic Usage: - ------------ + var len = _$handleXYDefaults_305(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; + } - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); + coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); + coerce('base'); + coerce('offset'); + coerce('width'); - // on failure - reject(reason); - }); + coerce('text'); + coerce('hovertext'); - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + var textPosition = coerce('textposition'); - Advanced Usage: - --------------- + var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', + hasInside = hasBoth || textPosition === 'inside', + hasOutside = hasBoth || textPosition === 'outside'; - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + if(hasInside || hasOutside) { + var textFont = coerceFont(coerce, 'textfont', layout.font); + if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); + if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); + coerce('constraintext'); + coerce('selected.textfont.color'); + coerce('unselected.textfont.color'); + coerce('cliponaxis'); + } - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); + _$handleStyleDefaults_267(traceIn, traceOut, coerce, defaultColor, layout); - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + // override defaultColor for error bars with defaultLine + var errorBarsSupplyDefaults = _$registry_245.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_43.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_43.defaultLine, {axis: 'x', inherit: 'y'}); - 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 + ']')); - } - } - }; - }); - } + _$lib_163.coerceSelectionMarkerOpacity(traceOut, coerce); +}; - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - Unlike callbacks, promises are great composable primitives. +'use strict'; - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON +/* removed: var _$lib_163 = require('../../lib'); */; - return values; - }); - ``` +/** Fill hover 'pointData' container with 'correct' hover text value + * + * - If trace hoverinfo contains a 'text' flag and hovertext is not set, + * the text elements will be seen in the hover labels. + * + * - If trace hoverinfo contains a 'text' flag and hovertext is set, + * hovertext takes precedence over text + * i.e. the hoverinfo elements will be seen in the hover labels + * + * @param {object} calcPt + * @param {object} trace + * @param {object || array} contOut (mutated here) + */ +var _$fillHoverText_289 = function fillHoverText(calcPt, trace, contOut) { + var fill = Array.isArray(contOut) ? + function(v) { contOut.push(v); } : + function(v) { contOut.text = v; }; - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; + var htx = _$lib_163.extractOption(calcPt, trace, 'htx', 'hovertext'); + if(isValid(htx)) return fill(htx); - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise ? initializePromise(this, resolver) : needsNew(); - } + var tx = _$lib_163.extractOption(calcPt, trace, 'tx', 'text'); + if(isValid(tx)) return fill(tx); +}; + +// accept all truthy values and 0 (which gets cast to '0' in the hover labels) +function isValid(v) { + return v || v === 0; } -Promise.all = all; -Promise.race = race; -Promise.resolve = resolve; -Promise.reject = reject; -Promise._setScheduler = setScheduler; -Promise._setAsap = setAsap; -Promise._asap = asap; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -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 +'use strict'; + +/* removed: var _$fx_85 = require('../../components/fx'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$fillHoverText_289 = require('../scatter/fill_hover_text'); */; + +var _$hoverPoints_258 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var trace = cd[0].trace; + var t = cd[0].t; + var isClosest = (hovermode === 'closest'); + var maxHoverDistance = pointData.maxHoverDistance; + var maxSpikeDistance = pointData.maxSpikeDistance; + + var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; + + function thisBarMinPos(di) { return di[posLetter] - di.w / 2; } + function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; } + + var minPos = isClosest ? + thisBarMinPos : + function(di) { + /* + * In compare mode, accept a bar if you're on it *or* its group. + * Nearly always it's the group that matters, but in case the bar + * was explicitly set wider than its group we'd better accept the + * whole bar. + * + * use `bardelta` instead of `bargroupwidth` so we accept hover + * in the gap. That way hover doesn't flash on and off as you + * mouse over the plot in compare modes. + * In 'closest' mode though the flashing seems inevitable, + * without far more complex logic + */ + return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2); + }; + + var maxPos = isClosest ? + thisBarMaxPos : + function(di) { + return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2); + }; + + function _positionFn(_minPos, _maxPos) { + // add a little to the pseudo-distance for wider bars, so that like scatter, + // if you are over two overlapping bars, the narrower one wins. + return _$fx_85.inbox(_minPos - posVal, _maxPos - posVal, + maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); } - ``` - - 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 + + function positionFn(di) { + return _positionFn(minPos(di), maxPos(di)); } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - + + function thisBarPositionFn(di) { + return _positionFn(thisBarMinPos(di), thisBarMaxPos(di)); } - - function failure(reason) { - + + function sizeFn(di) { + // add a gradient so hovering near the end of a + // bar makes it a little closer match + return _$fx_85.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, + maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); } - - 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'); + if(trace.orientation === 'h') { + posVal = yval; + sizeVal = xval; + posLetter = 'y'; + sizeLetter = 'x'; + dx = sizeFn; + dy = positionFn; } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong + else { + posVal = xval; + sizeVal = yval; + posLetter = 'x'; + sizeLetter = 'y'; + dy = sizeFn; + dx = positionFn; } - - // 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; + var pa = pointData[posLetter + 'a']; + var sa = pointData[sizeLetter + 'a']; - 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'); - } - } + pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); - var P = local.Promise; + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_85.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_85.getClosest(cd, distfn, pointData); - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } + // skip the rest (for this trace) if we didn't find a close point + if(pointData.index === false) return; - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } + // if we get here and we're not in 'closest' mode, push min/max pos back + // onto the group - even though that means occasionally the mouse will be + // over the hover label. + if(!isClosest) { + minPos = function(di) { + return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2); + }; + maxPos = function(di) { + return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2); + }; } - local.Promise = Promise; -} + // the closest data point + var index = pointData.index; + var di = cd[index]; + var mc = di.mcc || trace.marker.color; + var mlc = di.mlcc || trace.marker.line.color; + var mlw = di.mlw || trace.marker.line.width; -polyfill(); -// Strange compat.. -Promise.polyfill = polyfill; -Promise.Promise = Promise; + if(_$color_43.opacity(mc)) pointData.color = mc; + else if(_$color_43.opacity(mlc) && mlw) pointData.color = mlc; -return Promise; + var size = (trace.base) ? di.b + di.s : di.s; + pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); + pointData[sizeLetter + 'LabelVal'] = size; -}))); -//# sourceMappingURL=es6-promise.map -}).call(this,_$browser_24,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$es6Promise_8 = _$es6Promise_8.exports -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 extent = t.extents[t.extents.round(di.p)]; + pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true); + pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true); + pointData[posLetter + 'LabelVal'] = di.p; -'use strict'; + // spikelines always want "closest" distance regardless of hovermode + pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance; + // they also want to point to the data value, regardless of where the label goes + // in case of bars shifted within groups + pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); -/** - * All paths are tuned for maximum scalability of the arrowhead, - * ie throughout arrowwidth=0.3..3 the head is joined smoothly - * to the line, with the line coming from the left and ending at (0, 0). - * - * `backoff` is the distance to move the arrowhead and the end of the line, - * in order that the arrowhead points to the desired place, either at - * the tip of the arrow or (in the case of circle or square) - * the center of the symbol. - * - * `noRotate`, if truthy, says that this arrowhead should not rotate with the - * arrow. That's the case for squares, which should always be straight, and - * circles, for which it's irrelevant. - */ + _$fillHoverText_289(di, trace, pointData); + _$registry_245.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); -var _$arrow_paths_27 = [ - // no arrow - { - path: '', - backoff: 0 - }, - // wide with flat back - { - path: 'M-2.4,-3V3L0.6,0Z', - backoff: 0.6 - }, - // narrower with flat back - { - path: 'M-3.7,-2.5V2.5L1.3,0Z', - backoff: 1.3 - }, - // barbed - { - path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', - backoff: 1.55 - }, - // wide line-drawn - { - path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', - backoff: 1.6 - }, - // narrower line-drawn - { - path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', - backoff: 2 - }, - // circle - { - path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', - backoff: 0, - noRotate: true - }, - // square - { - path: 'M2,2V-2H-2V2Z', - backoff: 0, - noRotate: true - } -]; + return [pointData]; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -37974,348 +38075,40 @@ var _$arrow_paths_27 = [ 'use strict'; -/* removed: var _$arrow_paths_27 = require('./arrow_paths'); */; -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_209 = require('../../plots/cartesian/constants'); */; - - -var _$attributes_28 = { - _isLinkedToArray: 'annotation', - - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, - text: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, - textangle: { - valType: 'angle', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - font: _$font_attributes_231({ - editType: 'calcIfAutorange+arraydraw', - colorEditType: 'arraydraw', - - }), - width: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - height: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - align: { +var _$layout_attributes_260 = { + barmode: { valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'center', + values: ['stack', 'group', 'overlay', 'relative'], + dflt: 'group', - editType: 'arraydraw', + editType: 'calc', }, - valign: { + barnorm: { valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'middle', - - editType: 'arraydraw', - - }, - bgcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', + values: ['', 'fraction', 'percent'], + dflt: '', - editType: 'arraydraw', + editType: 'calc', }, - borderpad: { + bargap: { valType: 'number', min: 0, - dflt: 1, + max: 1, - editType: 'calcIfAutorange+arraydraw', + editType: 'calc', }, - borderwidth: { + bargroupgap: { valType: 'number', min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - // arrow - showarrow: { - valType: 'boolean', - dflt: true, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - arrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_27.length, - dflt: 1, - - editType: 'arraydraw', - - }, - startarrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_27.length, - dflt: 1, - - editType: 'arraydraw', - - }, - arrowside: { - valType: 'flaglist', - flags: ['end', 'start'], - extras: ['none'], - dflt: 'end', - - editType: 'arraydraw', + max: 1, + dflt: 0, - }, - arrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, + editType: 'calc', - editType: 'calcIfAutorange+arraydraw', - - }, - startarrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowwidth: { - valType: 'number', - min: 0.1, - - editType: 'calcIfAutorange+arraydraw', - - }, - standoff: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - startstandoff: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - ax: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - ay: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - axref: { - valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_209.idRegex.x.toString() - ], - - editType: 'calc', - - }, - ayref: { - valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_209.idRegex.y.toString() - ], - - editType: 'calc', - - }, - // positioning - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_209.idRegex.x.toString() - ], - - editType: 'calc', - - }, - x: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - - }, - xshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_209.idRegex.y.toString() - ], - - editType: 'calc', - - }, - y: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - - }, - yshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - clicktoshow: { - valType: 'enumerated', - values: [false, 'onoff', 'onout'], - dflt: false, - - editType: 'arraydraw', - - }, - xclick: { - valType: 'any', - - editType: 'arraydraw', - - }, - yclick: { - valType: 'any', - - editType: 'arraydraw', - - }, - hovertext: { - valType: 'string', - - editType: 'arraydraw', - - }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - font: _$font_attributes_231({ - editType: 'arraydraw', - - }), - editType: 'arraydraw' - }, - captureevents: { - valType: 'boolean', - - editType: 'arraydraw', - - }, - editType: 'calc', - - _deprecated: { - ref: { - valType: 'string', - - editType: 'calc', - - } } }; @@ -38330,146 +38123,50 @@ var _$attributes_28 = { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; - -/* removed: var _$color_43 = require('../color'); */; - -/* removed: var _$arrow_paths_27 = require('./arrow_paths'); */; - -/** - * 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. - */ -var _$drawArrowHead_35 = function drawArrowHead(el3, ends, options) { - var el = el3.node(); - var headStyle = _$arrow_paths_27[options.arrowhead || 0]; - var startHeadStyle = _$arrow_paths_27[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; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_163 = require('../../lib'); */; - 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), - backOffY = backOff * Math.sin(startRot); +/* removed: var _$layout_attributes_260 = require('./layout_attributes'); */; - end.x += backOffX; - end.y += backOffY; - el3.attr({x2: end.x, y2: end.y}); - } +var _$layout_defaults_261 = function(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_260, attr, dflt); + } - if(startBackOff) { - if(startBackOff * startBackOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var startBackOffX = startBackOff * Math.cos(startRot), - startbackOffY = startBackOff * Math.sin(startRot); + var hasBars = false, + shouldBeGapless = false, + gappedAnyway = false, + usedSubplots = {}; - start.x -= startBackOffX; - start.y -= startbackOffY; - el3.attr({x1: start.x, y1: start.y}); + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if(_$registry_245.traceIs(trace, 'bar')) hasBars = true; + else continue; + // if we have at least 2 grouped bar traces on the same subplot, + // we should default to a gap anyway, even if the data is histograms + if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') { + var subploti = trace.xaxis + trace.yaxis; + if(usedSubplots[subploti]) gappedAnyway = true; + usedSubplots[subploti] = true; } - } - 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 - dashArray = ''; - if(pathlen < backOff + startBackOff) { - hideLine(); - return; + if(trace.visible && trace.type === 'histogram') { + var pa = _$axes_205.getFromId({_fullLayout: layoutOut}, + trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); + if(pa.type !== 'category') shouldBeGapless = true; } - - - 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; + if(!hasBars) return; - _$d3_7.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_43.rgb(options.arrowcolor), - 'stroke-width': 0 - }); - } + var mode = coerce('barmode'); + if(mode !== 'overlay') coerce('barnorm'); - if(doStart) drawhead(startHeadStyle, start, startRot, startScale); - if(doEnd) drawhead(headStyle, end, endRot, scale); + coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2); + coerce('bargroupgap'); }; /** @@ -38480,702 +38177,538 @@ var _$drawArrowHead_35 = function drawArrowHead(el3, ends, options) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; /* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$fx_85 = require('../fx'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_181 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$drawArrowHead_35 = require('./draw_arrow_head'); */; - -// Annotations are stored in gd.layout.annotations, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one - -var _$draw_34 = { - draw: __draw_34, - drawOne: drawOne, - drawRaw: drawRaw -}; - -/* - * draw: draw all annotations without any new modifications - */ -function __draw_34(gd) { - var fullLayout = gd._fullLayout; - - fullLayout._infolayer.selectAll('.annotation').remove(); +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; - for(var i = 0; i < fullLayout.annotations.length; i++) { - if(fullLayout.annotations[i].visible) { - drawOne(gd, i); - } - } +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$drawing_68 = require('../../components/drawing'); */; +/* removed: var _$registry_245 = require('../../registry'); */; - return _$plots_237.previousPromises(gd); -} +var __dummy_262$0 = 0, + attributeText = _$attributes_255.text, + attributeTextPosition = _$attributes_255.textposition, + attributeTextFont = _$attributes_255.textfont, + attributeInsideTextFont = _$attributes_255.insidetextfont, + attributeOutsideTextFont = _$attributes_255.outsidetextfont; -/* - * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications - * - * index (int): the annotation to draw - */ -function drawOne(gd, index) { - var fullLayout = gd._fullLayout; - var options = fullLayout.annotations[index] || {}; - var xa = _$axes_204.getFromId(gd, options.xref); - var ya = _$axes_204.getFromId(gd, options.yref); +// padding in pixels around text +var TEXTPAD = 3; - drawRaw(gd, options, index, false, xa, ya); -} +var _$plot_262 = function plot(gd, plotinfo, cdbar) { + var xa = plotinfo.xaxis, + ya = plotinfo.yaxis, + fullLayout = gd._fullLayout; -/** - * drawRaw: draw a single annotation, potentially with modifications - * - * @param {DOM element} gd - * @param {object} options : this annotation's fullLayout options - * @param {integer} index : index in 'annotations' container of the annotation to draw - * @param {string} subplotId : id of the annotation's subplot - * - use false for 2d (i.e. cartesian or paper-ref) annotations - * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px - * @param {object | undefined} ya : ... y-axis - */ -function drawRaw(gd, options, index, subplotId, xa, ya) { - var fullLayout = gd._fullLayout; - var gs = gd._fullLayout._size; - var edits = gd._context.edits; + var bartraces = plotinfo.plot.select('.barlayer') + .selectAll('g.trace.bars') + .data(cdbar); - var className; - var annbase; + bartraces.enter().append('g') + .attr('class', 'trace bars'); - if(subplotId) { - className = 'annotation-' + subplotId; - annbase = subplotId + '.annotations[' + index + ']'; - } else { - className = 'annotation'; - annbase = 'annotations[' + index + ']'; + if(!plotinfo.isRangePlot) { + bartraces.each(function(d) { + d[0].node3 = _$d3_7.select(this); + }); } - // remove the existing annotation if there is one - fullLayout._infolayer - .selectAll('.' + className + '[data-index="' + index + '"]') - .remove(); - - var annClipID = 'clip' + fullLayout._uid + '_ann' + index; + bartraces.append('g') + .attr('class', 'points') + .each(function(d) { + var sel = _$d3_7.select(this); + var t = d[0].t; + var trace = d[0].trace; + var poffset = t.poffset; + var poffsetIsArray = Array.isArray(poffset); - // this annotation is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!options._input || options.visible === false) { - _$d3_7.selectAll('#' + annClipID).remove(); - return; - } + sel.selectAll('g.point') + .data(_$lib_163.identity) + .enter().append('g').classed('point', true) + .each(function(di, i) { + // now display the bar + // clipped xf/yf (2nd arg true): non-positive + // log values go off-screen by plotwidth + // so you see them continue if you drag the plot + var p0 = di.p + ((poffsetIsArray) ? poffset[i] : poffset), + p1 = p0 + di.w, + s0 = di.b, + s1 = s0 + di.s; - // calculated pixel positions - // x & y each will get text, head, and tail as appropriate - var annPosPx = {x: {}, y: {}}, - textangle = +options.textangle || 0; + var x0, x1, y0, y1; + if(trace.orientation === 'h') { + y0 = ya.c2p(p0, true); + y1 = ya.c2p(p1, true); + x0 = xa.c2p(s0, true); + x1 = xa.c2p(s1, true); - // create the components - // made a single group to contain all, so opacity can work right - // with border/arrow together this could handle a whole bunch of - // cleanup at this point, but works for now - var annGroup = fullLayout._infolayer.append('g') - .classed(className, true) - .attr('data-index', String(index)) - .style('opacity', options.opacity); + // for selections + di.ct = [x1, (y0 + y1) / 2]; + } + else { + x0 = xa.c2p(p0, true); + x1 = xa.c2p(p1, true); + y0 = ya.c2p(s0, true); + y1 = ya.c2p(s1, true); - // another group for text+background so that they can rotate together - var annTextGroup = annGroup.append('g') - .classed('annotation-text-g', true); + // for selections + di.ct = [(x0 + x1) / 2, y1]; + } - var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; - var textEvents = options.captureevents || edits.annotationText || editTextPosition; + if(!_$fastIsnumeric_10(x0) || !_$fastIsnumeric_10(x1) || + !_$fastIsnumeric_10(y0) || !_$fastIsnumeric_10(y1) || + x0 === x1 || y0 === y1) { + _$d3_7.select(this).remove(); + return; + } - var annTextGroupInner = annTextGroup.append('g') - .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_181, 'default') - .on('click', function() { - gd._dragging = false; + var lw = (di.mlw + 1 || trace.marker.line.width + 1 || + (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, + offset = _$d3_7.round((lw / 2) % 1, 2); - var eventData = { - index: index, - annotation: options._input, - fullAnnotation: options, - event: _$d3_7.event - }; + function roundWithLine(v) { + // if there are explicit gaps, don't round, + // it can make the gaps look crappy + return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? + _$d3_7.round(Math.round(v) - offset, 2) : v; + } - if(subplotId) { - eventData.subplotId = subplotId; - } + function expandToVisible(v, vc) { + // if it's not in danger of disappearing entirely, + // round more precisely + return Math.abs(v - vc) >= 2 ? roundWithLine(v) : + // but if it's very thin, expand it so it's + // necessarily visible, even if it might overlap + // its neighbor + (v > vc ? Math.ceil(v) : Math.floor(v)); + } - gd.emit('plotly_clickannotation', eventData); - }); + if(!gd._context.staticPlot) { + // if bars are not fully opaque or they have a line + // around them, round to integer pixels, mainly for + // safari so we prevent overlaps from its expansive + // pixelation. if the bars ARE fully opaque and have + // no line, expand to a full pixel to make sure we + // can see them + var op = _$color_43.opacity(di.mc || trace.marker.color), + fixpx = (op < 1 || lw > 0.01) ? + roundWithLine : expandToVisible; + x0 = fixpx(x0, x1); + x1 = fixpx(x1, x0); + y0 = fixpx(y0, y1); + y1 = fixpx(y1, y0); + } - if(options.hovertext) { - annTextGroupInner - .on('mouseover', function() { - var hoverOptions = options.hoverlabel; - var hoverFont = hoverOptions.font; - var bBox = this.getBoundingClientRect(); - var bBoxRef = gd.getBoundingClientRect(); + // append bar path and text + var bar = _$d3_7.select(this); - _$fx_85.loneHover({ - x0: bBox.left - bBoxRef.left, - x1: bBox.right - bBoxRef.left, - y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, - text: options.hovertext, - color: hoverOptions.bgcolor, - borderColor: hoverOptions.bordercolor, - fontFamily: hoverFont.family, - fontSize: hoverFont.size, - fontColor: hoverFont.color - }, { - container: fullLayout._hoverlayer.node(), - outerContainer: fullLayout._paper.node(), - gd: gd - }); - }) - .on('mouseout', function() { - _$fx_85.loneUnhover(fullLayout._hoverlayer.node()); - }); - } + bar.append('path') + .style('vector-effect', 'non-scaling-stroke') + .attr('d', + 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') + .call(_$drawing_68.setClipUrl, plotinfo.layerClipId); - var borderwidth = options.borderwidth, - borderpad = options.borderpad, - borderfull = borderwidth + borderpad; + appendBarText(gd, bar, d, i, x0, x1, y0, y1); - var annTextBG = annTextGroupInner.append('rect') - .attr('class', 'bg') - .style('stroke-width', borderwidth + 'px') - .call(_$color_43.stroke, options.bordercolor) - .call(_$color_43.fill, options.bgcolor); + if(plotinfo.layerClipId) { + _$drawing_68.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); + } + }); + }); - var isSizeConstrained = options.width || options.height; + // error bars are on the top + _$registry_245.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); - var annTextClip = fullLayout._topclips - .selectAll('#' + annClipID) - .data(isSizeConstrained ? [0] : []); + // lastly, clip points groups of `cliponaxis !== false` traces + // on `plotinfo._hasClipOnAxisFalse === true` subplots + bartraces.each(function(d) { + var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; + _$drawing_68.setClipUrl(_$d3_7.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + }); +}; - annTextClip.enter().append('clipPath') - .classed('annclip', true) - .attr('id', annClipID) - .append('rect'); - annTextClip.exit().remove(); +function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { + var textPosition; - var font = options.font; + function appendTextNode(bar, text, textFont) { + var textSelection = bar.append('text') + .text(text) + .attr({ + 'class': 'bartext bartext-' + textPosition, + transform: '', + 'text-anchor': 'middle', + // prohibit tex interpretation until we can handle + // tex and regular text together + 'data-notex': 1 + }) + .call(_$drawing_68.font, textFont) + .call(_$svg_text_utils_184.convertToTspans, gd); - var annText = annTextGroupInner.append('text') - .classed('annotation-text', true) - .text(options.text); + return textSelection; + } - function textLayout(s) { - s.call(_$drawing_68.font, font) - .attr({ - 'text-anchor': { - left: 'start', - right: 'end' - }[options.align] || 'middle' - }); + // get trace attributes + var trace = calcTrace[0].trace, + orientation = trace.orientation; - _$svg_text_utils_183.convertToTspans(s, gd, drawGraphicalElements); - return s; - } + var text = getText(trace, i); + if(!text) return; - function drawGraphicalElements() { - // if the text has *only* a link, make the whole box into a link - var anchor3 = annText.selectAll('a'); - if(anchor3.size() === 1 && anchor3.text() === annText.text()) { - var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ - 'xlink:xlink:href': anchor3.attr('xlink:href'), - 'xlink:xlink:show': anchor3.attr('xlink:show') - }) - .style({cursor: 'pointer'}); + textPosition = getTextPosition(trace, i); + if(textPosition === 'none') return; - wholeLink.node().appendChild(annTextBG.node()); - } + var textFont = getTextFont(trace, i, gd._fullLayout.font), + insideTextFont = getInsideTextFont(trace, i, textFont), + outsideTextFont = getOutsideTextFont(trace, i, textFont); - var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); - var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = _$drawing_68.bBox( - (hasMathjax ? mathjaxGroup : annText).node()); - var textWidth = anntextBB.width; - var textHeight = anntextBB.height; - var annWidth = options.width || textWidth; - var annHeight = options.height || textHeight; - var outerWidth = Math.round(annWidth + 2 * borderfull); - var outerHeight = Math.round(annHeight + 2 * borderfull); + // compute text position + var barmode = gd._fullLayout.barmode, + inStackMode = (barmode === 'stack'), + inRelativeMode = (barmode === 'relative'), + inStackOrRelativeMode = inStackMode || inRelativeMode, + calcBar = calcTrace[i], + isOutmostBar = !inStackOrRelativeMode || calcBar._outmost, - // save size in the annotation object for use by autoscale - options._w = annWidth; - options._h = annHeight; + barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD, // padding excluded + barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD, // padding excluded - function shiftFraction(v, anchor) { - if(anchor === 'auto') { - if(v < 1 / 3) anchor = 'left'; - else if(v > 2 / 3) anchor = 'right'; - else anchor = 'center'; - } - return { - center: 0, - middle: 0, - left: 0.5, - bottom: -0.5, - right: -0.5, - top: 0.5 - }[anchor]; - } + textSelection, + textBB, + textWidth, + textHeight; - var annotationIsOffscreen = false; - var letters = ['x', 'y']; + if(textPosition === 'outside') { + if(!isOutmostBar) textPosition = 'inside'; + } - for(var i = 0; i < letters.length; i++) { - var axLetter = letters[i], - axRef = options[axLetter + 'ref'] || axLetter, - tailRef = options['a' + axLetter + 'ref'], - ax = {x: xa, y: ya}[axLetter], - dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, - // note that these two can be either positive or negative - annSizeFromWidth = outerWidth * Math.cos(dimAngle), - annSizeFromHeight = outerHeight * Math.sin(dimAngle), - // but this one is the positive total size - annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), - anchor = options[axLetter + 'anchor'], - overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), - posPx = annPosPx[axLetter], - basePx, - textPadShift, - alignPosition, - autoAlignFraction, - textShift; + if(textPosition === 'auto') { + if(isOutmostBar) { + // draw text using insideTextFont and check if it fits inside bar + textPosition = 'inside'; + textSelection = appendTextNode(bar, text, insideTextFont); - /* - * calculate the *primary* pixel position - * which is the arrowhead if there is one, - * otherwise the text anchor point - */ - if(ax) { - /* - * hide the annotation if it's pointing outside the visible plot - * as long as the axis isn't autoranged - then we need to draw it - * anyway to get its bounding box. When we're dragging, an axis can - * still look autoranged even though it won't be when the drag finishes. - */ - var posFraction = ax.r2fraction(options[axLetter]); - if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { - if(tailRef === axRef) { - posFraction = ax.r2fraction(options['a' + axLetter]); - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - } - } - else { - annotationIsOffscreen = true; - } + textBB = _$drawing_68.bBox(textSelection.node()), + textWidth = textBB.width, + textHeight = textBB.height; - if(annotationIsOffscreen) continue; - } - basePx = ax._offset + ax.r2p(options[axLetter]); - autoAlignFraction = 0.5; + var textHasSize = (textWidth > 0 && textHeight > 0), + fitsInside = + (textWidth <= barWidth && textHeight <= barHeight), + fitsInsideIfRotated = + (textWidth <= barHeight && textHeight <= barWidth), + fitsInsideIfShrunk = (orientation === 'h') ? + (barWidth >= textWidth * (barHeight / textHeight)) : + (barHeight >= textHeight * (barWidth / textWidth)); + if(textHasSize && + (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) { + textPosition = 'inside'; } 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; + textPosition = 'outside'; + textSelection.remove(); + textSelection = null; } + } + else textPosition = 'inside'; + } - // 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]; + if(!textSelection) { + textSelection = appendTextNode(bar, text, + (textPosition === 'outside') ? + outsideTextFont : insideTextFont); - // with an arrow, the text rotates around the anchor point - textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - - annSizeFromHeight * shiftFraction(0.5, options.yanchor); + textBB = _$drawing_68.bBox(textSelection.node()), + textWidth = textBB.width, + textHeight = textBB.height; - 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; - } + if(textWidth <= 0 || textHeight <= 0) { + textSelection.remove(); + return; + } + } - posPx.text = posPx.tail + textShift; + // compute text transform + var transform, constrained; + if(textPosition === 'outside') { + constrained = trace.constraintext === 'both' || trace.constraintext === 'outside'; + transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, + orientation, constrained); + } + else { + constrained = trace.constraintext === 'both' || trace.constraintext === 'inside'; + transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, + orientation, constrained); + } - // 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_162.constrain(posPx.head, 1, maxPx - 1); - } - if(tailRef === 'pixel') { - var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), - 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; - } - } + textSelection.attr('transform', transform); +} - 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; - } +function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { + // compute text and target positions + var textWidth = textBB.width, + textHeight = textBB.height, + textX = (textBB.left + textBB.right) / 2, + textY = (textBB.top + textBB.bottom) / 2, + barWidth = Math.abs(x1 - x0), + barHeight = Math.abs(y1 - y0), + targetWidth, + targetHeight, + targetX, + targetY; - posPx.text += overallShift; - textShift += overallShift; - textPadShift += overallShift; + // apply text padding + var textpad; + if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) { + textpad = TEXTPAD; + barWidth -= 2 * textpad; + barHeight -= 2 * textpad; + } + else textpad = 0; - // padplus/minus are used by autorange - options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift; - options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift; + // compute rotation and scale + var rotate, + scale; - // size/shift are used during dragging - options['_' + axLetter + 'size'] = annSize; - options['_' + axLetter + 'shift'] = textShift; - } + if(textWidth <= barWidth && textHeight <= barHeight) { + // no scale or rotation is required + rotate = false; + scale = 1; + } + else if(textWidth <= barHeight && textHeight <= barWidth) { + // only rotation is required + rotate = true; + scale = 1; + } + else if((textWidth < textHeight) === (barWidth < barHeight)) { + // only scale is required + rotate = false; + scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1; + } + else { + // both scale and rotation are required + rotate = true; + scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1; + } - if(annotationIsOffscreen) { - annTextGroupInner.remove(); - return; - } + if(rotate) rotate = 90; // rotate clockwise - var xShift = 0; - var yShift = 0; + // compute text and target positions + if(rotate) { + targetWidth = scale * textHeight; + targetHeight = scale * textWidth; + } + else { + targetWidth = scale * textWidth; + targetHeight = scale * textHeight; + } - if(options.align !== 'left') { - xShift = (annWidth - textWidth) * (options.align === 'center' ? 0.5 : 1); + if(orientation === 'h') { + if(x1 < x0) { + // bar end is on the left hand side + targetX = x1 + textpad + targetWidth / 2; + targetY = (y0 + y1) / 2; } - if(options.valign !== 'top') { - yShift = (annHeight - textHeight) * (options.valign === 'middle' ? 0.5 : 1); + else { + targetX = x1 - textpad - targetWidth / 2; + targetY = (y0 + y1) / 2; } - - if(hasMathjax) { - mathjaxGroup.select('svg').attr({ - x: borderfull + xShift - 1, - y: borderfull + yShift - }) - .call(_$drawing_68.setClipUrl, isSizeConstrained ? annClipID : null); + } + else { + if(y1 > y0) { + // bar end is on the bottom + targetX = (x0 + x1) / 2; + targetY = y1 - textpad - targetHeight / 2; } else { - var texty = borderfull + yShift - anntextBB.top; - var textx = borderfull + xShift - anntextBB.left; - - annText.call(_$svg_text_utils_183.positionText, textx, texty) - .call(_$drawing_68.setClipUrl, isSizeConstrained ? annClipID : null); + targetX = (x0 + x1) / 2; + targetY = y1 + textpad + targetHeight / 2; } + } - annTextClip.select('rect').call(_$drawing_68.setRect, borderfull, borderfull, - annWidth, annHeight); - - annTextBG.call(_$drawing_68.setRect, borderwidth / 2, borderwidth / 2, - outerWidth - borderwidth, outerHeight - borderwidth); + return getTransform(textX, textY, targetX, targetY, scale, rotate); +} - annTextGroupInner.call(_$drawing_68.setTranslate, - Math.round(annPosPx.x.text - outerWidth / 2), - Math.round(annPosPx.y.text - outerHeight / 2)); +function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { + var barWidth = (orientation === 'h') ? + Math.abs(y1 - y0) : + Math.abs(x1 - x0), + textpad; - /* - * 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 + ')'}); + // Keep the padding so the text doesn't sit right against + // the bars, but don't factor it into barWidth + if(barWidth > 2 * TEXTPAD) { + textpad = TEXTPAD; + } - /* - * 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(); + // compute rotation and scale + var scale = 1; + if(constrained) { + scale = (orientation === 'h') ? + Math.min(1, barWidth / textBB.height) : + Math.min(1, barWidth / textBB.width); + } - var headX = annPosPx.x.head, - headY = annPosPx.y.head, - tailX = annPosPx.x.tail + dx, - tailY = annPosPx.y.tail + dy, - textX = annPosPx.x.text + dx, - textY = annPosPx.y.text + dy, + // compute text and target positions + var textX = (textBB.left + textBB.right) / 2, + textY = (textBB.top + textBB.bottom) / 2, + targetWidth, + targetHeight, + targetX, + targetY; - // find the edge of the text box, where we'll start the arrow: - // create transform matrix to rotate the text box corners - transform = _$lib_162.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_162.apply2DTransform(transform), - applyTransform2 = _$lib_162.apply2DTransform2(transform), + targetWidth = scale * textBB.width; + targetHeight = scale * textBB.height; - // calculate and transform bounding box - width = +annTextBG.attr('width'), - height = +annTextBG.attr('height'), - xLeft = textX - 0.5 * width, - xRight = xLeft + width, - yTop = textY - 0.5 * height, - yBottom = yTop + height, - 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_162.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_162.segmentsIntersect(tailX, tailY, headX, headY, - x[0], x[1], x[2], x[3]); - if(p) { - tailX = p.x; - tailY = p.y; - } - }); + if(orientation === 'h') { + if(x1 < x0) { + // bar end is on the left hand side + targetX = x1 - textpad - targetWidth / 2; + targetY = (y0 + y1) / 2; + } + else { + targetX = x1 + textpad + targetWidth / 2; + targetY = (y0 + y1) / 2; + } + } + else { + if(y1 > y0) { + // bar end is on the bottom + targetX = (x0 + x1) / 2; + targetY = y1 + textpad + targetHeight / 2; + } + else { + targetX = (x0 + x1) / 2; + targetY = y1 - textpad - targetHeight / 2; + } + } - var strokewidth = options.arrowwidth, - arrowColor = options.arrowcolor, - arrowSide = options.arrowside; + return getTransform(textX, textY, targetX, targetY, scale, false); +} - var arrowGroup = annGroup.append('g') - .style({opacity: _$color_43.opacity(arrowColor)}) - .classed('annotation-arrow-g', true); +function getTransform(textX, textY, targetX, targetY, scale, rotate) { + var transformScale, + transformRotate, + transformTranslate; - var arrow = arrowGroup.append('path') - .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY) - .style('stroke-width', strokewidth + 'px') - .call(_$color_43.stroke, _$color_43.rgb(arrowColor)); + if(scale < 1) transformScale = 'scale(' + scale + ') '; + else { + scale = 1; + transformScale = ''; + } - _$drawArrowHead_35(arrow, arrowSide, options); + transformRotate = (rotate) ? + 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : ''; - // 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) - .attr({ - d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), - transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' - }) - .style('stroke-width', (strokewidth + 6) + 'px') - .call(_$color_43.stroke, 'rgba(0,0,0,0)') - .call(_$color_43.fill, 'rgba(0,0,0,0)'); + // Note that scaling also affects the center of the text box + var translateX = (targetX - scale * textX), + translateY = (targetY - scale * textY); + transformTranslate = 'translate(' + translateX + ' ' + translateY + ')'; - var update, - annx0, - anny0; + return transformTranslate + transformScale + transformRotate; +} - // dragger for the arrow & head: translates the whole thing - // (head/tail/text) all together - _$dragelement_65.init({ - element: arrowDrag.node(), - gd: gd, - prepFn: function() { - var pos = _$drawing_68.getTranslate(annTextGroupInner); +function getText(trace, index) { + var value = getValue(trace.text, index); + return coerceString(attributeText, value); +} - annx0 = pos.x; - anny0 = pos.y; - update = {}; - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } - }, - moveFn: function(dx, dy) { - var annxy0 = applyTransform(annx0, anny0), - xcenter = annxy0[0] + dx, - ycenter = annxy0[1] + dy; - annTextGroupInner.call(_$drawing_68.setTranslate, xcenter, ycenter); +function getTextPosition(trace, index) { + var value = getValue(trace.textposition, index); + return coerceEnumerated(attributeTextPosition, value); +} - update[annbase + '.x'] = xa ? - xa.p2r(xa.r2p(options.x) + dx) : - (options.x + (dx / gs.w)); - update[annbase + '.y'] = ya ? - ya.p2r(ya.r2p(options.y) + dy) : - (options.y - (dy / gs.h)); +function getTextFont(trace, index, defaultValue) { + return getFontValue( + attributeTextFont, trace.textfont, index, defaultValue); +} - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } +function getInsideTextFont(trace, index, defaultValue) { + return getFontValue( + attributeInsideTextFont, trace.insidetextfont, index, defaultValue); +} - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } +function getOutsideTextFont(trace, index, defaultValue) { + return getFontValue( + attributeOutsideTextFont, trace.outsidetextfont, index, defaultValue); +} - arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); - annTextGroup.attr({ - transform: 'rotate(' + textangle + ',' + - xcenter + ',' + ycenter + ')' - }); - }, - doneFn: function() { - _$registry_244.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } - }; +function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { + attributeValue = attributeValue || {}; - if(options.showarrow) drawArrow(0, 0); + var familyValue = getValue(attributeValue.family, index), + sizeValue = getValue(attributeValue.size, index), + colorValue = getValue(attributeValue.color, index); - // user dragging the annotation (text, not arrow) - if(editTextPosition) { - var update, - baseTextTransform; + return { + family: coerceString( + attributeDefinition.family, familyValue, defaultValue.family), + size: coerceNumber( + attributeDefinition.size, sizeValue, defaultValue.size), + color: coerceColor( + attributeDefinition.color, colorValue, defaultValue.color) + }; +} - // dragger for the textbox: if there's an arrow, just drag the - // textbox and tail, leave the head untouched - _$dragelement_65.init({ - element: annTextGroupInner.node(), - gd: gd, - prepFn: function() { - baseTextTransform = annTextGroup.attr('transform'); - update = {}; - }, - moveFn: function(dx, dy) { - var csr = 'pointer'; - if(options.showarrow) { - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } else { - update[annbase + '.ax'] = options.ax + dx; - } +function getValue(arrayOrScalar, index) { + var value; + if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar; + else if(index < arrayOrScalar.length) value = arrayOrScalar[index]; + return value; +} - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } else { - update[annbase + '.ay'] = options.ay + dy; - } +function coerceString(attributeDefinition, value, defaultValue) { + if(typeof value === 'string') { + if(value || !attributeDefinition.noBlank) return value; + } + else if(typeof value === 'number') { + if(!attributeDefinition.strict) return String(value); + } - drawArrow(dx, dy); - } - else if(!subplotId) { - if(xa) { - update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} - } else { - var widthFraction = options._xsize / gs.w, - xLeft = options.x + (options._xshift - options.xshift) / gs.w - - widthFraction / 2; +function coerceEnumerated(attributeDefinition, value, defaultValue) { + if(attributeDefinition.coerceNumber) value = +value; - update[annbase + '.x'] = _$dragelement_65.align(xLeft + dx / gs.w, - widthFraction, 0, 1, options.xanchor); - } + if(attributeDefinition.values.indexOf(value) !== -1) return value; - if(ya) { - update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); - } else { - var heightFraction = options._ysize / gs.h, - yBottom = options.y - (options._yshift + options.yshift) / gs.h - - heightFraction / 2; + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} - update[annbase + '.y'] = _$dragelement_65.align(yBottom - dy / gs.h, - heightFraction, 0, 1, options.yanchor); - } - if(!xa || !ya) { - csr = _$dragelement_65.getCursor( - xa ? 0.5 : update[annbase + '.x'], - ya ? 0.5 : update[annbase + '.y'], - options.xanchor, options.yanchor - ); - } - } - else return; +function coerceNumber(attributeDefinition, value, defaultValue) { + if(_$fastIsnumeric_10(value)) { + value = +value; - annTextGroup.attr({ - transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform - }); + var min = attributeDefinition.min, + max = attributeDefinition.max, + isOutOfBounds = (min !== undefined && value < min) || + (max !== undefined && value > max); - _$setCursor_181(annTextGroupInner, csr); - }, - doneFn: function() { - _$setCursor_181(annTextGroupInner); - _$registry_244.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } + if(!isOutOfBounds) return value; } - if(edits.annotationText) { - annText.call(_$svg_text_utils_183.makeEditable, {delegate: annTextGroupInner, gd: gd}) - .call(textLayout) - .on('edit', function(_text) { - options.text = _text; - this.call(textLayout); - - var update = {}; - update[annbase + '.text'] = options.text; + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } +function coerceColor(attributeDefinition, value, defaultValue) { + if(_$tinycolor_25(value).isValid()) return value; - _$registry_244.call('relayout', gd, update); - }); - } - else annText.call(textLayout); + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; } /** @@ -39186,108 +38719,39 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; - -var __draw_29 = _$draw_34.draw; - - -var _$calcAutorange_29 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - annotationList = _$lib_162.filterVisible(fullLayout.annotations); - - if(!annotationList.length || !gd._fullData.length) return; - - var annotationAxes = {}; - annotationList.forEach(function(ann) { - annotationAxes[ann.xref] = 1; - annotationAxes[ann.yref] = 1; - }); +var _$selectPoints_263 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; - for(var axId in annotationAxes) { - var ax = _$axes_204.getFromId(gd, axId); - if(ax && ax.autorange) { - return _$lib_162.syncOrAsync([ - __draw_29, - annAutorange - ], gd); + if(polygon === false) { + // clear selection + for(i = 0; i < cd.length; i++) { + cd[i].selected = 0; } - } -}; - -function annAutorange(gd) { - var fullLayout = gd._fullLayout; - - // find the bounding boxes for each of these annotations' - // relative to their anchor points - // use the arrow and the text bg rectangle, - // as the whole anno may include hidden text in its bbox - _$lib_162.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_204.getFromId(gd, ann.xref), - ya = _$axes_204.getFromId(gd, ann.yref), - headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, - startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - - var headPlus, headMinus, startHeadPlus, startHeadMinus; - - if(xa && xa.autorange) { - headPlus = headSize + ann.xshift; - headMinus = headSize - ann.xshift; - startHeadPlus = startHeadSize + ann.xshift; - startHeadMinus = startHeadSize - ann.xshift; + } else { + for(i = 0; i < cd.length; i++) { + var di = cd[i]; - if(ann.axref === ann.xref) { - // expand for the arrowhead (padded by arrowhead) - _$axes_204.expand(xa, [xa.r2c(ann.x)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - // again for the textbox (padded by textbox) - _$axes_204.expand(xa, [xa.r2c(ann.ax)], { - ppadplus: Math.max(ann._xpadplus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, startHeadMinus) - }); - } - else { - startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; - startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_204.expand(xa, [xa.r2c(ann.x)], { - ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) + if(polygon.contains(di.ct)) { + selection.push({ + pointNumber: i, + x: xa.c2d(di.x), + y: ya.c2d(di.y) }); + di.selected = 1; + } else { + di.selected = 0; } } + } - if(ya && ya.autorange) { - headPlus = headSize - ann.yshift; - headMinus = headSize + ann.yshift; - startHeadPlus = startHeadSize - ann.yshift; - startHeadMinus = startHeadSize + ann.yshift; - - if(ann.ayref === ann.yref) { - _$axes_204.expand(ya, [ya.r2c(ann.y)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - _$axes_204.expand(ya, [ya.r2c(ann.ay)], { - ppadplus: Math.max(ann._ypadplus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, startHeadMinus) - }); - } - else { - startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; - startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_204.expand(ya, [ya.r2c(ann.y)], { - ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) - }); - } - } - }); -} + return selection; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -39299,126 +38763,103 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; - -var _$click_30 = { - hasClickToShow: hasClickToShow, - onClick: onClick -}; +var _$Sieve_265 = Sieve; -/* - * 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; -} +/* removed: var _$lib_163 = require('../../lib'); */; +var __BADNUM_265 = _$numerical_145.BADNUM; -/* - * 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 +/** + * Helper class to sieve data from traces into bins * - * returns: Promise that the update is complete + * @class + * @param {Array} traces + * Array of calculated traces + * @param {boolean} [separateNegativeValues] + * If true, then split data at the same position into a bar + * for positive values and another for negative values + * @param {boolean} [dontMergeOverlappingData] + * If true, then don't merge overlapping bars into a single bar */ -function onClick(gd, hoverData) { - var toggleSets = getToggleSets(gd, hoverData), - onSet = toggleSets.on, - offSet = toggleSets.off.concat(toggleSets.explicitOff), - update = {}, - i; +function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { + this.traces = traces; + this.separateNegativeValues = separateNegativeValues; + this.dontMergeOverlappingData = dontMergeOverlappingData; - if(!(onSet.length || offSet.length)) return; + // for single-bin histograms - see histogram/calc + var width1 = Infinity; - for(i = 0; i < onSet.length; i++) { - update['annotations[' + onSet[i] + '].visible'] = true; + var positions = []; + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; + if(bar.p !== __BADNUM_265) positions.push(bar.p); + } + if(trace[0] && trace[0].width1) { + width1 = Math.min(trace[0].width1, width1); + } } + this.positions = positions; - for(i = 0; i < offSet.length; i++) { - update['annotations[' + offSet[i] + '].visible'] = false; - } + var dv = _$lib_163.distinctVals(positions); + this.distinctPositions = dv.vals; + if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; + else this.minDiff = Math.min(dv.minDiff, width1); + + this.binWidth = this.minDiff; - return _$registry_244.call('update', gd, {}, update); + this.bins = {}; } -/* - * 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 +/** + * Sieve datum * - * 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) - * } + * @method + * @param {number} position + * @param {number} value + * @returns {number} Previous bin value */ -function getToggleSets(gd, hoverData) { - var annotations = gd._fullLayout.annotations, - onSet = [], - offSet = [], - explicitOffSet = [], - hoverLen = (hoverData || []).length; +Sieve.prototype.put = function put(position, value) { + var label = this.getLabel(position, value), + oldValue = this.bins[label] || 0; - var i, j, anni, showMode, pointj, xa, ya, toggleType; + this.bins[label] = oldValue + value; - 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 oldValue; +}; - return {on: onSet, off: offSet, explicitOff: explicitOffSet}; -} +/** + * Get current bin value for a given datum + * + * @method + * @param {number} position Position of datum + * @param {number} [value] Value of datum + * (required if this.separateNegativeValues is true) + * @returns {number} Current bin value + */ +Sieve.prototype.get = function put(position, value) { + var label = this.getLabel(position, value); + return this.bins[label] || 0; +}; -// to handle log axes until v2 -function clickData2r(d, ax) { - return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); -} +/** + * Get bin label for a given datum + * + * @method + * @param {number} position Position of datum + * @param {number} [value] Value of datum + * (required if this.separateNegativeValues is true) + * @returns {string} Bin label + * (prefixed with a 'v' if value is negative and this.separateNegativeValues is + * true; otherwise prefixed with '^') + */ +Sieve.prototype.getLabel = function getLabel(position, value) { + var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^', + label = (this.dontMergeOverlappingData) ? + position : + Math.round(position / this.binWidth); + return prefix + label; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -39432,703 +38873,647 @@ function clickData2r(d, ax) { 'use strict'; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_185 = require('../../lib/to_log_range'); */; +var __isArrayOrTypedArray_264 = _$lib_163.isArrayOrTypedArray; +var __BADNUM_264 = _$numerical_145.BADNUM; + +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$Sieve_265 = require('./sieve.js'); */; /* - * 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. + * 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 */ -var _$convertCoords_32 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); +var _$setPositions_264 = function setPositions(gd, plotinfo) { + var xa = plotinfo.xaxis, + ya = plotinfo.yaxis; - if(!(toLog || fromLog)) return; + var fullTraces = gd._fullData, + calcTraces = gd.calcdata, + calcTracesHorizontal = [], + calcTracesVertical = [], + i; + for(i = 0; i < fullTraces.length; i++) { + var fullTrace = fullTraces[i]; + if( + fullTrace.visible === true && + _$registry_245.traceIs(fullTrace, 'bar') && + fullTrace.xaxis === xa._id && + fullTrace.yaxis === ya._id + ) { + if(fullTrace.orientation === 'h') { + calcTracesHorizontal.push(calcTraces[i]); + } + else { + calcTracesVertical.push(calcTraces[i]); + } + } + } - var annotations = gd._fullLayout.annotations, - axLetter = ax._id.charAt(0), - ann, - attrPrefix; + setGroupPositions(gd, xa, ya, calcTracesVertical); + setGroupPositions(gd, ya, xa, calcTracesHorizontal); +}; - function convert(attr) { - var currentVal = ann[attr], - newVal = null; - if(toLog) newVal = _$toLogRange_185(currentVal, ax.range); - else newVal = Math.pow(10, currentVal); +function setGroupPositions(gd, pa, sa, calcTraces) { + if(!calcTraces.length) return; - // if conversion failed, delete the value so it gets a default value - if(!_$fastIsnumeric_10(newVal)) newVal = null; + var barmode = gd._fullLayout.barmode, + overlay = (barmode === 'overlay'), + group = (barmode === 'group'), + excluded, + included, + i, calcTrace, fullTrace; - doExtra(attrPrefix + attr, newVal); + if(overlay) { + setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces); } + else if(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; - for(var i = 0; i < annotations.length; i++) { - ann = annotations[i]; - attrPrefix = 'annotations[' + i + '].'; + if(fullTrace.offset === undefined) included.push(calcTrace); + else excluded.push(calcTrace); + } - if(ann[axLetter + 'ref'] === ax._id) convert(axLetter); - if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter); + if(included.length) { + setGroupPositionsInGroupMode(gd, pa, sa, included); + } + if(excluded.length) { + setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + } } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$color_43 = require('../color'); */; + else { + // 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; -// defaults common to 'annotations' and 'annotations3d' -var _$handleAnnotationCommonDefaults_31 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { - coerce('opacity'); - var bgColor = coerce('bgcolor'); + if(fullTrace.base === undefined) included.push(calcTrace); + else excluded.push(calcTrace); + } - var borderColor = coerce('bordercolor'); - var borderOpacity = _$color_43.opacity(borderColor); + if(included.length) { + setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included); + } + if(excluded.length) { + setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + } + } - coerce('borderpad'); + collectExtents(calcTraces, pa); +} - var borderWidth = coerce('borderwidth'); - var showArrow = coerce('showarrow'); - coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); - coerce('textangle'); - _$lib_162.coerceFont(coerce, 'font', fullLayout.font); +function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { + var barnorm = gd._fullLayout.barnorm, + separateNegativeValues = false, + dontMergeOverlappingData = !barnorm; - coerce('width'); - coerce('align'); + // update position axis and set bar offsets and widths + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; - var h = coerce('height'); - if(h) coerce('valign'); + var sieve = new _$Sieve_265( + [calcTrace], separateNegativeValues, dontMergeOverlappingData + ); - if(showArrow) { - var arrowside = coerce('arrowside'); - var arrowhead; - var arrowsize; + // set bar offsets and widths, and update position axis + setOffsetAndWidth(gd, pa, sieve); - if(arrowside.indexOf('end') !== -1) { - arrowhead = coerce('arrowhead'); - arrowsize = coerce('arrowsize'); + // 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(barnorm) { + sieveBars(gd, sa, sieve); + normalizeBars(gd, sa, sieve); } - - if(arrowside.indexOf('start') !== -1) { - coerce('startarrowhead', arrowhead); - coerce('startarrowsize', arrowsize); + else { + setBaseAndTop(gd, sa, sieve); } - coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_43.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_43.opacity(bgColor) ? _$color_43.rgb(bgColor) : _$color_43.defaultLine) - ); +function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { + var fullLayout = gd._fullLayout, + barnorm = fullLayout.barnorm, + separateNegativeValues = false, + dontMergeOverlappingData = !barnorm, + sieve = new _$Sieve_265( + calcTraces, separateNegativeValues, dontMergeOverlappingData + ); - var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || - _$color_43.contrast(hoverBG) - ); + // set bar offsets and widths, and update position axis + setOffsetAndWidthInGroupMode(gd, pa, sieve); - _$lib_162.coerceFont(coerce, 'hoverlabel.font', { - family: globalHoverLabel.font.family, - size: globalHoverLabel.font.size, - color: globalHoverLabel.font.color || hoverBorder - }); + // set bar bases and sizes, and update size axis + if(barnorm) { + sieveBars(gd, sa, sieve); + normalizeBars(gd, sa, sieve); + } + else { + setBaseAndTop(gd, sa, sieve); } +} - coerce('captureevents', !!hoverText); -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { + var fullLayout = gd._fullLayout, + barmode = fullLayout.barmode, + stack = (barmode === 'stack'), + relative = (barmode === 'relative'), + barnorm = gd._fullLayout.barnorm, + separateNegativeValues = relative, + dontMergeOverlappingData = !(barnorm || stack || relative), + sieve = new _$Sieve_265( + calcTraces, separateNegativeValues, dontMergeOverlappingData + ); + // set bar offsets and widths, and update position axis + setOffsetAndWidth(gd, pa, sieve); -'use strict'; + // set bar bases and sizes, and update size axis + stackBars(gd, sa, sieve); -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleAnnotationCommonDefaults_31 = require('./common_defaults'); */; -/* removed: var _$attributes_28 = require('./attributes'); */; + // 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]; -var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + if(bar.s === __BADNUM_264) continue; - function coerce(attr, dflt) { - return _$lib_162.coerce(annIn, annOut, _$attributes_28, attr, dflt); + var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); + if(isOutmostBar) bar._outmost = true; + } } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - var clickToShow = coerce('clicktoshow'); - - if(!(visible || clickToShow)) return annOut; + // Note that marking the outmost bars has to be done + // before `normalizeBars` changes `bar.b` and `bar.s`. + if(barnorm) normalizeBars(gd, sa, sieve); +} - _$handleAnnotationCommonDefaults_31(annIn, annOut, fullLayout, coerce); - var showArrow = annOut.showarrow; +function setOffsetAndWidth(gd, pa, sieve) { + var fullLayout = gd._fullLayout, + bargap = fullLayout.bargap, + bargroupgap = fullLayout.bargroupgap, + minDiff = sieve.minDiff, + calcTraces = sieve.traces, + i, calcTrace, calcTrace0, + t; - // positioning - var axLetters = ['x', 'y'], - arrowPosDflt = [-10, -30], - gdMock = {_fullLayout: fullLayout}; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i]; + // set bar offsets and widths + var barGroupWidth = minDiff * (1 - bargap), + barWidthPlusGap = barGroupWidth, + barWidth = barWidthPlusGap * (1 - bargroupgap); - // xref, yref - var axRef = _$axes_204.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + // computer bar group center and bar offset + var offsetFromCenter = -barWidth / 2; - // x, y - _$axes_204.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + for(i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; - if(showArrow) { - var arrowPosAttr = 'a' + axLetter, - // axref, ayref - aaxRef = _$axes_204.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + // store bar width and offset for this trace + t = calcTrace0.t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; + } - // for now the arrow can only be on the same axis or specified as pixels - // TODO: sometime it might be interesting to allow it to be on *any* axis - // but that would require updates to drawing & autorange code and maybe more - if(aaxRef !== 'pixel' && aaxRef !== axRef) { - aaxRef = annOut[arrowPosAttr] = 'pixel'; - } + // stack bars that only differ by rounding + sieve.binWidth = calcTraces[0][0].t.barwidth / 100; - // ax, ay - var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_204.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); - } + // if defined, apply trace offset and width + applyAttributes(sieve); - // xanchor, yanchor - coerce(axLetter + 'anchor'); + // store the bar center in each calcdata item + setBarCenterAndWidth(gd, pa, sieve); - // xshift, yshift - coerce(axLetter + 'shift'); - } + // update position axes + updatePositionAxis(gd, pa, sieve); +} - // if you have one coordinate you should have both - _$lib_162.noneOrAll(annIn, annOut, ['x', 'y']); - // if you have one part of arrow length you should have both - if(showArrow) { - _$lib_162.noneOrAll(annIn, annOut, ['ax', 'ay']); - } +function setOffsetAndWidthInGroupMode(gd, pa, sieve) { + var fullLayout = gd._fullLayout, + bargap = fullLayout.bargap, + bargroupgap = fullLayout.bargroupgap, + positions = sieve.positions, + distinctPositions = sieve.distinctPositions, + minDiff = sieve.minDiff, + calcTraces = sieve.traces, + i, calcTrace, calcTrace0, + t; - if(clickToShow) { - var xClick = coerce('xclick'); - var yClick = coerce('yclick'); + // if there aren't any overlapping positions, + // let them have full width even if mode is group + var overlap = (positions.length !== distinctPositions.length); - // put the actual click data to bind to into private attributes - // so we don't have to do this little bit of logic on every hover event - annOut._xclick = (xClick === undefined) ? - annOut.x : - _$axes_204.cleanPosition(xClick, gdMock, annOut.xref); - annOut._yclick = (yClick === undefined) ? - annOut.y : - _$axes_204.cleanPosition(yClick, gdMock, annOut.yref); - } + var nTraces = calcTraces.length, + barGroupWidth = minDiff * (1 - bargap), + barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth, + barWidth = barWidthPlusGap * (1 - bargroupgap); - return annOut; -}; + for(i = 0; i < nTraces; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // computer bar group center and bar offset + var offsetFromCenter = (overlap) ? + ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : + -barWidth / 2; -'use strict'; + // store bar width and offset for this trace + t = calcTrace0.t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; + } -/* removed: var _$lib_162 = require('../lib'); */; + // stack bars that only differ by rounding + sieve.binWidth = calcTraces[0][0].t.barwidth / 100; -/** Convenience wrapper for making array container logic DRY and consistent - * - * @param {object} parentObjIn - * user input object where the container in question is linked - * (i.e. either a user trace object or the user layout object) - * - * @param {object} parentObjOut - * full object where the coerced container will be linked - * (i.e. either a full trace object or the full layout object) - * - * @param {object} opts - * options object: - * - name {string} - * name of the key linking the container in question - * - handleItemDefaults {function} - * defaults method to be called on each item in the array container in question - * - * Its arguments are: - * - itemIn {object} item in user layout - * - itemOut {object} item in full layout - * - parentObj {object} (as in closure) - * - opts {object} (as in closure) - * - itemOpts {object} - * - itemIsNotPlainObject {boolean} - * N.B. - * - * - opts is passed to handleItemDefaults so it can also store - * links to supplementary data (e.g. fullData for layout components) - * - */ -var _$handleArrayContainerDefaults_200 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { - var name = opts.name; + // if defined, apply trace width + applyAttributes(sieve); - var previousContOut = parentObjOut[name]; + // store the bar center in each calcdata item + setBarCenterAndWidth(gd, pa, sieve); - var contIn = _$lib_162.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], - contOut = parentObjOut[name] = [], - i; + // update position axes + updatePositionAxis(gd, pa, sieve, overlap); +} - for(i = 0; i < contIn.length; i++) { - var itemIn = contIn[i], - itemOut = {}, - itemOpts = {}; - if(!_$lib_162.isPlainObject(itemIn)) { - itemOpts.itemIsNotPlainObject = true; - itemIn = {}; - } +function applyAttributes(sieve) { + var calcTraces = sieve.traces, + i, calcTrace, calcTrace0, fullTrace, + j, + t; - opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); + for(i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; + fullTrace = calcTrace0.trace; + t = calcTrace0.t; - itemOut._input = itemIn; - itemOut._index = i; + var offset = fullTrace.offset, + initialPoffset = t.poffset, + newPoffset; - contOut.push(itemOut); - } - - // in case this array gets its defaults rebuilt independent of the whole layout, - // relink the private keys just for this array. - if(_$lib_162.isArrayOrTypedArray(previousContOut)) { - var len = Math.min(previousContOut.length, contOut.length); - for(i = 0; i < len; i++) { - _$lib_162.relinkPrivateKeys(contOut[i], previousContOut[i]); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$handleArrayContainerDefaults_200 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationDefaults_26 = require('./annotation_defaults'); */; - - -var _$supplyLayoutDefaults_33 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'annotations', - handleItemDefaults: _$handleAnnotationDefaults_26 - }; - - _$handleArrayContainerDefaults_200(layoutIn, layoutOut, opts); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(__isArrayOrTypedArray_264(offset)) { + // if offset is an array, then clone it into t.poffset. + newPoffset = offset.slice(0, calcTrace.length); + // guard against non-numeric items + for(j = 0; j < newPoffset.length; j++) { + if(!_$fastIsnumeric_10(newPoffset[j])) { + newPoffset[j] = initialPoffset; + } + } -'use strict'; + // 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); + } -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; + t.poffset = newPoffset; + } + else if(offset !== undefined) { + t.poffset = offset; + } -/** - * 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 - */ -var _$makeIncludeComponents_214 = function makeIncludeComponents(containerArrayName) { - return function includeComponents(layoutIn, layoutOut) { - var array = layoutIn[containerArrayName]; - if(!Array.isArray(array)) return; + var width = fullTrace.width, + initialBarwidth = t.barwidth; - var Cartesian = _$registry_244.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'); + if(__isArrayOrTypedArray_264(width)) { + // if width is an array, then clone it into t.barwidth. + var newBarwidth = width.slice(0, calcTrace.length); - for(var i = 0; i < array.length; i++) { - var itemi = array[i]; - if(!_$lib_162.isPlainObject(itemi)) continue; + // guard against non-numeric items + for(j = 0; j < newBarwidth.length; j++) { + if(!_$fastIsnumeric_10(newBarwidth[j])) newBarwidth[j] = initialBarwidth; + } - var xref = itemi.xref; - var yref = itemi.yref; + // 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); + } - var hasXref = idRegex.x.test(xref); - var hasYref = idRegex.y.test(yref); - if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_162.pushUnique(layoutOut._basePlotModules, Cartesian); + t.barwidth = newBarwidth; - 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; + // 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; - /* - * 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); - } + // if user didn't set offset, + // then correct t.poffset to ensure bars remain centered + if(offset === undefined) { + t.poffset = initialPoffset + (initialBarwidth - width) / 2; } } - }; -}; + } +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setBarCenterAndWidth(gd, pa, sieve) { + var calcTraces = sieve.traces, + pLetter = getAxisLetter(pa); -'use strict'; + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i], + t = calcTrace[0].t, + poffset = t.poffset, + poffsetIsArray = Array.isArray(poffset), + barwidth = t.barwidth, + barwidthIsArray = Array.isArray(barwidth); -/* removed: var _$draw_34 = require('./draw'); */; -/* removed: var _$click_30 = require('./click'); */; + for(var j = 0; j < calcTrace.length; j++) { + var calcBar = calcTrace[j]; -var _$annotations_36 = { - moduleType: 'component', - name: 'annotations', + // 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; - layoutAttributes: _$attributes_28, - supplyLayoutDefaults: _$supplyLayoutDefaults_33, - includeBasePlot: _$makeIncludeComponents_214('annotations'), - calcAutorange: _$calcAutorange_29, - draw: _$draw_34.draw, - drawOne: _$draw_34.drawOne, - drawRaw: _$draw_34.drawRaw, + } + } +} - hasClickToShow: _$click_30.hasClickToShow, - onClick: _$click_30.onClick, - convertCoords: _$convertCoords_32 -}; +function updatePositionAxis(gd, pa, sieve, allowMinDtick) { + var calcTraces = sieve.traces, + distinctPositions = sieve.distinctPositions, + distinctPositions0 = distinctPositions[0], + minDiff = sieve.minDiff, + vpad = minDiff / 2; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + _$axes_205.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + // If the user set the bar width or the offset, + // then bars can be shifted away from their positions + // and widths can be larger than minDiff. + // + // Here, we compute pMin and pMax to expand the position axis, + // so that all bars are fully within the axis range. + var pMin = Math.min.apply(Math, distinctPositions) - vpad, + pMax = Math.max.apply(Math, distinctPositions) + vpad; -'use strict'; + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i], + calcTrace0 = calcTrace[0], + fullTrace = calcTrace0.trace; -/* removed: var _$attributes_28 = require('../annotations/attributes'); */; -var __overrideAll_37 = _$edit_types_189.overrideAll; + if(fullTrace.width === undefined && fullTrace.offset === undefined) { + continue; + } -var _$attributes_37 = __overrideAll_37({ - _isLinkedToArray: 'annotation', + var t = calcTrace0.t, + poffset = t.poffset, + barwidth = t.barwidth, + poffsetIsArray = Array.isArray(poffset), + barwidthIsArray = Array.isArray(barwidth); - visible: _$attributes_28.visible, - x: { - valType: 'any', - - - }, - y: { - valType: 'any', - - - }, - z: { - valType: 'any', - - - }, - ax: { - valType: 'number', - - - }, - ay: { - valType: 'number', - - - }, + for(var j = 0; j < calcTrace.length; j++) { + var calcBar = calcTrace[j], + calcBarOffset = (poffsetIsArray) ? poffset[j] : poffset, + calcBarWidth = (barwidthIsArray) ? barwidth[j] : barwidth, + p = calcBar.p, + l = p + calcBarOffset, + r = l + calcBarWidth; - xanchor: _$attributes_28.xanchor, - xshift: _$attributes_28.xshift, - yanchor: _$attributes_28.yanchor, - yshift: _$attributes_28.yshift, + pMin = Math.min(pMin, l); + pMax = Math.max(pMax, r); + } + } - text: _$attributes_28.text, - textangle: _$attributes_28.textangle, - font: _$attributes_28.font, - width: _$attributes_28.width, - height: _$attributes_28.height, - opacity: _$attributes_28.opacity, - align: _$attributes_28.align, - valign: _$attributes_28.valign, - bgcolor: _$attributes_28.bgcolor, - bordercolor: _$attributes_28.bordercolor, - borderpad: _$attributes_28.borderpad, - borderwidth: _$attributes_28.borderwidth, - showarrow: _$attributes_28.showarrow, - arrowcolor: _$attributes_28.arrowcolor, - arrowhead: _$attributes_28.arrowhead, - startarrowhead: _$attributes_28.startarrowhead, - arrowside: _$attributes_28.arrowside, - arrowsize: _$attributes_28.arrowsize, - startarrowsize: _$attributes_28.startarrowsize, - arrowwidth: _$attributes_28.arrowwidth, - standoff: _$attributes_28.standoff, - startstandoff: _$attributes_28.startstandoff, - hovertext: _$attributes_28.hovertext, - hoverlabel: _$attributes_28.hoverlabel, - captureevents: _$attributes_28.captureevents, + _$axes_205.expand(pa, [pMin, pMax], {padded: false}); +} - // maybes later? - // clicktoshow: annAtts.clicktoshow, - // xclick: annAtts.xclick, - // yclick: annAtts.yclick, +function expandRange(range, newValue) { + if(_$fastIsnumeric_10(range[0])) range[0] = Math.min(range[0], newValue); + else range[0] = newValue; - // not needed! - // axref: 'pixel' - // ayref: 'pixel' - // xref: 'x' - // yref: 'y - // zref: 'z' -}, 'calc', 'from-root'); + if(_$fastIsnumeric_10(range[1])) range[1] = Math.max(range[1], newValue); + else range[1] = newValue; +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setBaseAndTop(gd, sa, sieve) { + // 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. + var traces = sieve.traces, + sLetter = getAxisLetter(sa), + sRange = [null, null]; -'use strict'; + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j], + barBase = bar.b, + barTop = barBase + bar.s; -var _$convert_38 = function convert(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var anns = fullSceneLayout.annotations; + bar[sLetter] = barTop; - for(var i = 0; i < anns.length; i++) { - mockAnnAxes(anns[i], scene); + if(_$fastIsnumeric_10(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_10(sa.c2l(barBase))) expandRange(sRange, barBase); + } } - scene.fullLayout._infolayer - .selectAll('.annotation-' + scene.id) - .remove(); -}; + _$axes_205.expand(sa, sRange, {tozero: true, padded: true}); +} -function mockAnnAxes(ann, scene) { - var fullSceneLayout = scene.fullSceneLayout; - var domain = fullSceneLayout.domain; - var size = scene.fullLayout._size; - var base = { - // this gets fill in on render - pdata: null, +function stackBars(gd, sa, sieve) { + var fullLayout = gd._fullLayout, + barnorm = fullLayout.barnorm, + sLetter = getAxisLetter(sa), + traces = sieve.traces, + i, trace, + j, bar; - // to get setConvert to not execute cleanly - type: 'linear', + var sRange = [null, null]; - // don't try to update them on `editable: true` - autorange: false, + for(i = 0; i < traces.length; i++) { + trace = traces[i]; - // set infinite range so that annotation draw routine - // does not try to remove 'outside-range' annotations, - // this case is handled in the render loop - range: [-Infinity, Infinity] - }; + for(j = 0; j < trace.length; j++) { + bar = trace[j]; - ann._xa = {}; - _$lib_162.extendFlat(ann._xa, base); - _$axes_204.setConvert(ann._xa); - ann._xa._offset = size.l + domain.x[0] * size.w; - ann._xa.l2p = function() { - return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); - }; + if(bar.s === __BADNUM_264) continue; - ann._ya = {}; - _$lib_162.extendFlat(ann._ya, base); - _$axes_204.setConvert(ann._ya); - ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; - ann._ya.l2p = function() { - return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); - }; -} + // stack current bar and get previous sum + var barBase = sieve.put(bar.p, bar.b + bar.s), + barTop = barBase + bar.b + bar.s; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // store the bar base and top in each calcdata item + bar.b = barBase; + bar[sLetter] = barTop; -'use strict'; + if(!barnorm) { + if(_$fastIsnumeric_10(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_10(sa.c2l(barBase))) expandRange(sRange, barBase); + } + } + } -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_200 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationCommonDefaults_31 = require('../annotations/common_defaults'); */; -/* removed: var _$attributes_37 = require('./attributes'); */; + // if barnorm is set, let normalizeBars update the axis range + if(!barnorm) _$axes_205.expand(sa, sRange, {tozero: true, padded: true}); +} -var _$handleDefaults_39 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_200(sceneLayoutIn, sceneLayoutOut, { - name: 'annotations', - handleItemDefaults: __handleAnnotationDefaults_39, - fullLayout: opts.fullLayout - }); -}; -function __handleAnnotationDefaults_39(annIn, annOut, sceneLayout, opts, itemOpts) { - function coerce(attr, dflt) { - return _$lib_162.coerce(annIn, annOut, _$attributes_37, attr, dflt); - } +function sieveBars(gd, sa, sieve) { + var traces = sieve.traces; - function coercePosition(axLetter) { - var axName = axLetter + 'axis'; + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; - // mock in such way that getFromId grabs correct 3D axis - var gdMock = { _fullLayout: {} }; - gdMock._fullLayout[axName] = sceneLayout[axName]; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; - return _$axes_204.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + if(bar.s !== __BADNUM_264) sieve.put(bar.p, bar.b + bar.s); + } } +} - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - if(!visible) return annOut; +function normalizeBars(gd, sa, sieve) { + // Note: + // + // normalizeBars requires that either sieveBars or stackBars has been + // previously invoked. - _$handleAnnotationCommonDefaults_31(annIn, annOut, opts.fullLayout, coerce); + var traces = sieve.traces, + sLetter = getAxisLetter(sa), + sTop = (gd._fullLayout.barnorm === 'fraction') ? 1 : 100, + sTiny = sTop / 1e9, // in case of rounding error in sum + sMin = sa.l2c(sa.c2l(0)), + sMax = (gd._fullLayout.barmode === 'stack') ? sTop : sMin, + sRange = [sMin, sMax], + padded = false; - coercePosition('x'); - coercePosition('y'); - coercePosition('z'); + function maybeExpand(newValue) { + if(_$fastIsnumeric_10(sa.c2l(newValue)) && + ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_10(sMin)) + ) { + padded = true; + expandRange(sRange, newValue); + } + } - // if you have one coordinate you should all three - _$lib_162.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; - // hard-set here for completeness - annOut.xref = 'x'; - annOut.yref = 'y'; - annOut.zref = 'z'; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; - coerce('xanchor'); - coerce('yanchor'); - coerce('xshift'); - coerce('yshift'); + if(bar.s === __BADNUM_264) continue; - if(annOut.showarrow) { - annOut.axref = 'pixel'; - annOut.ayref = 'pixel'; + var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); + bar.b *= scale; + bar.s *= scale; - // TODO maybe default values should be bigger than the 2D case? - coerce('ax', -10); - coerce('ay', -30); + var barBase = bar.b, + barTop = barBase + bar.s; + bar[sLetter] = barTop; - // if you have one part of arrow length you should have both - _$lib_162.noneOrAll(annIn, annOut, ['ax', 'ay']); + maybeExpand(barTop); + if(bar.hasB) maybeExpand(barBase); + } } - return annOut; + // update range of size axis + _$axes_205.expand(sa, sRange, {tozero: true, padded: padded}); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +function getAxisLetter(ax) { + return ax._id.charAt(0); +} -function xformMatrix(m, v) { - var out = [0, 0, 0, 0]; - var i, j; +// 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 posLetter = pa._id.charAt(0); + var extents = {}; + var pMin = Infinity; + var pMax = -Infinity; - for(i = 0; i < 4; ++i) { - for(j = 0; j < 4; ++j) { - out[j] += m[4 * i + j] * v[i]; + var i, j, cd; + for(i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + for(j = 0; j < cd.length; j++) { + var p = cd[j].p; + if(_$fastIsnumeric_10(p)) { + pMin = Math.min(pMin, p); + pMax = Math.max(pMax, p); + } } } - return out; -} + // 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))); + }; -function project(camera, v) { - var p = xformMatrix(camera.projection, - xformMatrix(camera.view, - xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); - return p; + for(i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + cd[0].t.extents = extents; + for(j = 0; j < cd.length; j++) { + var di = cd[j]; + var p0 = di[posLetter] - di.w / 2; + if(_$fastIsnumeric_10(p0)) { + var p1 = di[posLetter] + 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]; + } + } + } + } } -var _$project_234 = project; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40137,96 +39522,67 @@ var _$project_234 = project; * LICENSE file in the root directory of this source tree. */ -'use strict'; -var __drawRaw_40 = _$draw_34.drawRaw; -/* removed: var _$project_234 = require('../../plots/gl3d/project'); */; -var axLetters = ['x', 'y', 'z']; +'use strict'; -var _$draw_40 = function draw(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var dataScale = scene.dataScale; - var anns = fullSceneLayout.annotations; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$drawing_68 = require('../../components/drawing'); */; +/* removed: var _$registry_245 = require('../../registry'); */; - for(var i = 0; i < anns.length; i++) { - var ann = anns[i]; - var annotationIsOffscreen = false; +var _$style_266 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_7.select(gd).selectAll('g.trace.bars'); + var barcount = s.size(); + var fullLayout = gd._fullLayout; - for(var j = 0; j < 3; j++) { - var axLetter = axLetters[j]; - var pos = ann[axLetter]; - var ax = fullSceneLayout[axLetter + 'axis']; - var posFraction = ax.r2fraction(pos); + // trace styling + s.style('opacity', function(d) { return d[0].trace.opacity; }) - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - break; - } + // for gapless (either stacked or neighboring grouped) bars use + // crispEdges to turn off antialiasing so an artificial gap + // isn't introduced. + .each(function(d) { + if((fullLayout.barmode === 'stack' && barcount > 1) || + (fullLayout.bargap === 0 && + fullLayout.bargroupgap === 0 && + !d[0].trace.marker.line.width)) { + _$d3_7.select(this).attr('shape-rendering', 'crispEdges'); } + }); - if(annotationIsOffscreen) { - scene.fullLayout._infolayer - .select('.annotation-' + scene.id + '[data-index="' + i + '"]') - .remove(); - } else { - ann._pdata = _$project_234(scene.glplot.cameraParams, [ - fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], - fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], - fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] - ]); - - __drawRaw_40(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); - } - } -}; + s.selectAll('g.points').each(function(d) { + var sel = _$d3_7.select(this); + var pts = sel.selectAll('path'); + var txs = sel.selectAll('text'); + var trace = d[0].trace; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + _$drawing_68.pointStyle(pts, trace, gd); + _$drawing_68.selectedPointStyle(pts, trace); -'use strict'; + txs.each(function(d) { + var tx = _$d3_7.select(this); + var textFont; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; + if(tx.classed('bartext-inside')) { + textFont = trace.insidetextfont; + } else if(tx.classed('bartext-outside')) { + textFont = trace.outsidetextfont; + } + if(!textFont) textFont = trace.textfont; -var _$annotations3d_41 = { - moduleType: 'component', - name: 'annotations3d', + function cast(k) { + var cont = textFont[k]; + return Array.isArray(cont) ? cont[d.i] : cont; + } - schema: { - subplots: { - scene: {annotations: _$attributes_37} - } - }, + _$drawing_68.font(tx, cast('family'), cast('size'), cast('color')); + }); - layoutAttributes: _$attributes_37, - handleDefaults: _$handleDefaults_39, - includeBasePlot: includeGL3D, + _$drawing_68.selectedTextStyle(txs, trace); + }); - convert: _$convert_38, - draw: _$draw_40 + _$registry_245.getComponentMethod('errorbars', 'style')(s); }; -function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_244.subplotsRegistry.gl3d; - if(!GL3D) return; - - var attrRegex = GL3D.attrRegex; - - var keys = Object.keys(layoutIn); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; - if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_162.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_162.pushUnique(layoutOut._subplots.gl3d, k); - } - } -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40237,107 +39593,20 @@ function includeGL3D(layoutIn, layoutOut) { 'use strict'; - -var _$attributes_70 = { - visible: { - valType: 'boolean', - - editType: 'calc', - - }, - type: { - valType: 'enumerated', - values: ['percent', 'constant', 'sqrt', 'data'], - - editType: 'calc', - - }, - symmetric: { - valType: 'boolean', - - editType: 'calc', - - }, - array: { - valType: 'data_array', - editType: 'calc', - - }, - arrayminus: { - valType: 'data_array', - editType: 'calc', - - }, - value: { - valType: 'number', - min: 0, - dflt: 10, - - editType: 'calc', - - }, - valueminus: { - valType: 'number', - min: 0, - dflt: 10, - - editType: 'calc', - - }, - traceref: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'style' - }, - tracerefminus: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'style' - }, - copy_ystyle: { - valType: 'boolean', - - editType: 'plot' - }, - copy_zstyle: { - valType: 'boolean', - - editType: 'style' - }, - color: { - valType: 'color', - - editType: 'style', - - }, - thickness: { - valType: 'number', - min: 0, - dflt: 2, - - editType: 'style', - - }, - width: { - valType: 'number', - min: 0, - - editType: 'plot', - - }, - editType: 'calc', - - _deprecated: { - opacity: { - valType: 'number', - - editType: 'style', - - } +var _$constants_45 = { + cn: { + colorbar: 'colorbar', + cbbg: 'cbbg', + cbfill: 'cbfill', + cbfills: 'cbfills', + cbline: 'cbline', + cblines: 'cblines', + cbaxis: 'cbaxis', + cbtitleunshift: 'cbtitleunshift', + cbtitle: 'cbtitle', + cboutline: 'cboutline', + crisp: 'crisp', + jsPlaceholder: 'js-placeholder' } }; @@ -40352,232 +39621,638 @@ var _$attributes_70 = { 'use strict'; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/** - * 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 " - */ -var _$makeComputeError_72 = function makeComputeError(opts) { - var type = opts.type, - symmetric = opts.symmetric; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +var __extendFlat_47 = _$extend_157.extendFlat; +/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$titles_136 = require('../titles'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +var __LINE_SPACING_47 = _$alignment_143.LINE_SPACING; - if(type === 'data') { - var array = opts.array || []; +/* removed: var _$handleAxisDefaults_207 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handlePositionDefaults_220 = require('../../plots/cartesian/position_defaults'); */; +/* removed: var _$layout_attributes_217 = require('../../plots/cartesian/layout_attributes'); */; - if(symmetric) { - return function computeError(dataPt, index) { - var val = +(array[index]); - return [val, val]; - }; +/* removed: var _$attributes_44 = require('./attributes'); */; +var cn = _$constants_45.cn; + +var _$draw_47 = function draw(gd, id) { + // opts: options object, containing everything from attributes + // plus a few others that are the equivalent of the colorbar "data" + var opts = {}; + Object.keys(_$attributes_44).forEach(function(k) { + opts[k] = null; + }); + // fillcolor can be a d3 scale, domain is z values, range is colors + // or leave it out for no fill, + // or set to a string constant for single-color fill + opts.fillcolor = null; + // line.color has the same options as fillcolor + opts.line = {color: null, width: null, dash: null}; + // levels of lines to draw. + // note that this DOES NOT determine the extent of the bar + // that's given by the domain of fillcolor + // (or line.color if no fillcolor domain) + opts.levels = {start: null, end: null, size: null}; + // separate fill levels (for example, heatmap coloring of a + // contour map) if this is omitted, fillcolors will be + // evaluated halfway between levels + opts.filllevels = null; + + function component() { + var fullLayout = gd._fullLayout, + gs = fullLayout._size; + if((typeof opts.fillcolor !== 'function') && + (typeof opts.line.color !== 'function')) { + fullLayout._infolayer.selectAll('g.' + id).remove(); + return; } - 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]; - }; + var zrange = _$d3_7.extent(((typeof opts.fillcolor === 'function') ? + opts.fillcolor : opts.line.color).domain()); + var linelevels = []; + var filllevels = []; + var linecolormap = typeof opts.line.color === 'function' ? + opts.line.color : function() { return opts.line.color; }; + var fillcolormap = typeof opts.fillcolor === 'function' ? + opts.fillcolor : function() { return opts.fillcolor; }; + var l; + var i; + + var l0 = opts.levels.end + opts.levels.size / 100, + ls = opts.levels.size, + zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), + zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); + for(i = 0; i < 1e5; i++) { + l = opts.levels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zr0 && l < zr1) linelevels.push(l); } - } - else { - var computeErrorValue = makeComputeErrorValue(type, opts.value), - computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); - if(symmetric || opts.valueminus === undefined) { - return function computeError(dataPt) { - var val = computeErrorValue(dataPt); - return [val, val]; - }; + if(typeof opts.fillcolor === 'function') { + if(opts.filllevels) { + l0 = opts.filllevels.end + opts.filllevels.size / 100; + ls = opts.filllevels.size; + for(i = 0; i < 1e5; i++) { + l = opts.filllevels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zrange[0] && l < zrange[1]) filllevels.push(l); + } + } + else { + filllevels = linelevels.map(function(v) { + return v - opts.levels.size / 2; + }); + filllevels.push(filllevels[filllevels.length - 1] + + opts.levels.size); + } } - else { - return function computeError(dataPt) { - return [ - computeErrorValueMinus(dataPt), - computeErrorValue(dataPt) - ]; - }; + else if(opts.fillcolor && typeof opts.fillcolor === 'string') { + // doesn't matter what this value is, with a single value + // we'll make a single fill rect covering the whole bar + filllevels = [0]; } - } -}; - -/** - * 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)); - }; - } -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(opts.levels.size < 0) { + linelevels.reverse(); + filllevels.reverse(); + } + // now make a Plotly Axes object to scale with and draw ticks + // TODO: does not support orientation other than right -'use strict'; + // we calculate pixel sizes based on the specified graph size, + // not the actual (in case something pushed the margins around) + // which is a little odd but avoids an odd iterative effect + // when the colorbar itself is pushing the margins. + // but then the fractional size is calculated based on the + // actual graph size, so that the axes will size correctly. + var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, + originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, + thickPx = Math.round(opts.thickness * + (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), + thickFrac = thickPx / gs.w, + lenPx = Math.round(opts.len * + (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), + lenFrac = lenPx / gs.h, + xpadFrac = opts.xpad / gs.w, + yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, + ypadFrac = opts.ypad / gs.h, -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; + // x positioning: do it initially just for left anchor, + // then fix at the end (since we don't know the width yet) + xLeft = Math.round(opts.x * gs.w + opts.xpad), + // for dragging... this is getting a little muddled... + xLeftFrac = opts.x - thickFrac * + ({middle: 0.5, right: 1}[opts.xanchor]||0), -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; + // y positioning we can do correctly from the start + yBottomFrac = opts.y + lenFrac * + (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), + yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), + yTopPx = yBottomPx - lenPx, + titleEl, + cbAxisIn = { + type: 'linear', + range: zrange, + tickmode: opts.tickmode, + nticks: opts.nticks, + tick0: opts.tick0, + dtick: opts.dtick, + tickvals: opts.tickvals, + ticktext: opts.ticktext, + ticks: opts.ticks, + ticklen: opts.ticklen, + tickwidth: opts.tickwidth, + tickcolor: opts.tickcolor, + showticklabels: opts.showticklabels, + tickfont: opts.tickfont, + tickangle: opts.tickangle, + tickformat: opts.tickformat, + exponentformat: opts.exponentformat, + separatethousands: opts.separatethousands, + showexponent: opts.showexponent, + showtickprefix: opts.showtickprefix, + tickprefix: opts.tickprefix, + showticksuffix: opts.showticksuffix, + ticksuffix: opts.ticksuffix, + title: opts.title, + titlefont: opts.titlefont, + showline: true, + anchor: 'free', + position: 1 + }, + cbAxisOut = { + type: 'linear', + _id: 'y' + id + }, + axisOptions = { + letter: 'y', + font: fullLayout.font, + noHover: true, + calendar: fullLayout.calendar // not really necessary (yet?) + }; -/* removed: var _$makeComputeError_72 = require('./compute_error'); */; + // Coerce w.r.t. Axes layoutAttributes: + // re-use axes.js logic without updating _fullData + function coerce(attr, dflt) { + return _$lib_163.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_217, attr, dflt); + } + // Prepare the Plotly axis object + _$handleAxisDefaults_207(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handlePositionDefaults_220(cbAxisIn, cbAxisOut, coerce, axisOptions); -var _$calc_71 = function calc(gd) { - var calcdata = gd.calcdata; + // position can't go in through supplyDefaults + // because that restricts it to [0,1] + cbAxisOut.position = opts.x + xpadFrac + thickFrac; - for(var i = 0; i < calcdata.length; i++) { - var calcTrace = calcdata[i], - trace = calcTrace[0].trace; + // save for other callers to access this axis + component.axis = cbAxisOut; - if(!_$registry_244.traceIs(trace, 'errorBarsOK')) continue; + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + cbAxisOut.titleside = opts.titleside; + cbAxisOut.titlex = opts.x + xpadFrac; + cbAxisOut.titley = yBottomFrac + + (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + } - var xa = _$axes_204.getFromId(gd, trace.xaxis), - ya = _$axes_204.getFromId(gd, trace.yaxis); + if(opts.line.color && opts.tickmode === 'auto') { + cbAxisOut.tickmode = 'linear'; + cbAxisOut.tick0 = opts.levels.start; + var dtick = opts.levels.size; + // expand if too many contours, so we don't get too many ticks + var autoNtick = _$lib_163.constrain( + (yBottomPx - yTopPx) / 50, 4, 15) + 1, + dtFactor = (zrange[1] - zrange[0]) / + ((opts.nticks || autoNtick) * dtick); + if(dtFactor > 1) { + var dtexp = Math.pow(10, Math.floor( + Math.log(dtFactor) / Math.LN10)); + dtick *= dtexp * _$lib_163.roundUp(dtFactor / dtexp, [2, 5, 10]); + // if the contours are at round multiples, reset tick0 + // so they're still at round multiples. Otherwise, + // keep the first label on the first contour level + if((Math.abs(opts.levels.start) / + opts.levels.size + 1e-6) % 1 < 2e-6) { + cbAxisOut.tick0 = 0; + } + } + cbAxisOut.dtick = dtick; + } - calcOneAxis(calcTrace, trace, xa, 'x'); - calcOneAxis(calcTrace, trace, ya, 'y'); - } -}; + // set domain after init, because we may want to + // allow it outside [0,1] + cbAxisOut.domain = [ + yBottomFrac + ypadFrac, + yBottomFrac + lenFrac - ypadFrac + ]; + cbAxisOut.setScale(); -function calcOneAxis(calcTrace, trace, axis, coord) { - var opts = trace['error_' + coord] || {}, - isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), - vals = []; + // now draw the elements + var container = _$lib_163.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_7.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); - if(!isVisible) return; + container.attr('transform', 'translate(' + Math.round(gs.l) + + ',' + Math.round(gs.t) + ')'); + // TODO: this opposite transform is a hack until we make it + // more rational which items get this offset + var titleCont = container.select('.cbtitleunshift') + .attr('transform', 'translate(-' + + Math.round(gs.l) + ',-' + + Math.round(gs.t) + ')'); - var computeError = _$makeComputeError_72(opts); + cbAxisOut._axislayer = container.select('.cbaxis'); + var titleHeight = 0; + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // draw the title so we know how much room it needs + // when we squish the axis. This one only applies to + // top or bottom titles, not right side. + var x = gs.l + (opts.x + xpadFrac) * gs.w, + fontSize = cbAxisOut.titlefont.size, + y; - for(var i = 0; i < calcTrace.length; i++) { - var calcPt = calcTrace[i], - calcCoord = calcPt[coord]; + if(opts.titleside === 'top') { + y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + + gs.t + 3 + fontSize * 0.75; + } + else { + y = (1 - (yBottomFrac + ypadFrac)) * gs.h + + gs.t - 3 - fontSize * 0.25; + } + drawTitle(cbAxisOut._id + 'title', { + attributes: {x: x, y: y, 'text-anchor': 'start'} + }); + } - if(!_$fastIsnumeric_10(axis.c2l(calcCoord))) continue; + function drawAxis() { + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // squish the axis top to make room for the title + var titleGroup = container.select('.cbtitle'), + titleText = titleGroup.select('text'), + titleTrans = + [-opts.outlinewidth / 2, opts.outlinewidth / 2], + mathJaxNode = titleGroup + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + lineSize = 15.6; + if(titleText.node()) { + lineSize = + parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_47; + } + if(mathJaxNode) { + titleHeight = _$drawing_68.bBox(mathJaxNode).height; + if(titleHeight > lineSize) { + // not entirely sure how mathjax is doing + // vertical alignment, but this seems to work. + titleTrans[1] -= (titleHeight - lineSize) / 2; + } + } + else if(titleText.node() && + !titleText.classed(cn.jsPlaceholder)) { + titleHeight = _$drawing_68.bBox(titleText.node()).height; + } + if(titleHeight) { + // buffer btwn colorbar and title + // TODO: configurable + titleHeight += 5; - var errors = computeError(calcCoord, i); - if(_$fastIsnumeric_10(errors[0]) && _$fastIsnumeric_10(errors[1])) { - var shoe = calcPt[coord + 's'] = calcCoord - errors[0], - hat = calcPt[coord + 'h'] = calcCoord + errors[1]; - vals.push(shoe, hat); + if(opts.titleside === 'top') { + cbAxisOut.domain[1] -= titleHeight / gs.h; + titleTrans[1] *= -1; + } + else { + cbAxisOut.domain[0] += titleHeight / gs.h; + var nlines = _$svg_text_utils_184.lineCount(titleText); + titleTrans[1] += (1 - nlines) * lineSize; + } + + titleGroup.attr('transform', + 'translate(' + titleTrans + ')'); + + cbAxisOut.setScale(); + } + } + + container.selectAll('.cbfills,.cblines') + .attr('transform', 'translate(0,' + + Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); + + cbAxisOut._axislayer.attr('transform', 'translate(0,' + + Math.round(-gs.t) + ')'); + + var fills = container.select('.cbfills') + .selectAll('rect.cbfill') + .data(filllevels); + fills.enter().append('rect') + .classed(cn.cbfill, true) + .style('stroke', 'none'); + fills.exit().remove(); + fills.each(function(d, i) { + var z = [ + (i === 0) ? zrange[0] : + (filllevels[i] + filllevels[i - 1]) / 2, + (i === filllevels.length - 1) ? zrange[1] : + (filllevels[i] + filllevels[i + 1]) / 2 + ] + .map(cbAxisOut.c2p) + .map(Math.round); + + // offset the side adjoining the next rectangle so they + // overlap, to prevent antialiasing gaps + if(i !== filllevels.length - 1) { + z[1] += (z[1] > z[0]) ? 1 : -1; + } + + + // Tinycolor can't handle exponents and + // at this scale, removing it makes no difference. + var colorString = fillcolormap(d).replace('e-', ''), + opaqueColor = _$tinycolor_25(colorString).toHexString(); + + // Colorbar cannot currently support opacities so we + // use an opaque fill even when alpha channels present + _$d3_7.select(this).attr({ + x: xLeft, + width: Math.max(thickPx, 2), + y: _$d3_7.min(z), + height: Math.max(_$d3_7.max(z) - _$d3_7.min(z), 2), + fill: opaqueColor + }); + }); + + var lines = container.select('.cblines') + .selectAll('path.cbline') + .data(opts.line.color && opts.line.width ? + linelevels : []); + lines.enter().append('path') + .classed(cn.cbline, true); + lines.exit().remove(); + lines.each(function(d) { + _$d3_7.select(this) + .attr('d', 'M' + xLeft + ',' + + (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + + 'h' + thickPx) + .call(_$drawing_68.lineGroupStyle, + opts.line.width, linecolormap(d), opts.line.dash); + }); + + // force full redraw of labels and ticks + cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') + .remove(); + + cbAxisOut._pos = xLeft + thickPx + + (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); + cbAxisOut.side = 'right'; + + // separate out axis and title drawing, + // so we don't need such complicated logic in Titles.draw + // if title is on the top or bottom, we've already drawn it + // this title call only handles side=right + return _$lib_163.syncOrAsync([ + function() { + return _$axes_205.doTicks(gd, cbAxisOut, true); + }, + function() { + if(['top', 'bottom'].indexOf(opts.titleside) === -1) { + var fontSize = cbAxisOut.titlefont.size, + y = cbAxisOut._offset + cbAxisOut._length / 2, + x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? + 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : + -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); + + // the 'h' + is a hack to get around the fact that + // convertToTspans rotates any 'y...' class by 90 degrees. + // TODO: find a better way to control this. + drawTitle('h' + cbAxisOut._id + 'title', { + avoid: { + selection: _$d3_7.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), + side: opts.titleside, + offsetLeft: gs.l, + offsetTop: 0, + maxShift: fullLayout.width + }, + attributes: {x: x, y: y, 'text-anchor': 'middle'}, + transform: {rotate: '-90', offset: 0} + }); + } + }]); } - } - _$axes_204.expand(axis, vals, {padded: true}); -} + function drawTitle(titleClass, titleOpts) { + var trace = getTrace(), + propName; + if(_$registry_245.traceIs(trace, 'markerColorscale')) { + propName = 'marker.colorbar.title'; + } + else propName = 'colorbar.title'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 dfltTitleOpts = { + propContainer: cbAxisOut, + propName: propName, + traceIndex: trace.index, + placeholder: fullLayout._dfltTitle.colorbar, + containerGroup: container.select('.cbtitle') + }; -'use strict'; + // this class-to-rotate thing with convertToTspans is + // getting hackier and hackier... delete groups with the + // wrong class (in case earlier the colorbar was drawn on + // a different side, I think?) + var otherClass = titleClass.charAt(0) === 'h' ? + titleClass.substr(1) : ('h' + titleClass); + container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') + .remove(); -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; + _$titles_136.draw(gd, titleClass, + __extendFlat_47(dfltTitleOpts, titleOpts || {})); + } -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; + function positionCB() { + // wait for the axis & title to finish rendering before + // continuing positioning + // TODO: why are we redrawing multiple times now with this? + // I guess autoMargin doesn't like being post-promise? + var innerWidth = thickPx + opts.outlinewidth / 2 + + _$drawing_68.bBox(cbAxisOut._axislayer.node()).width; + titleEl = titleCont.select('text'); + if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { + var mathJaxNode = titleCont + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + titleWidth; + if(mathJaxNode && + ['top', 'bottom'].indexOf(opts.titleside) !== -1) { + titleWidth = _$drawing_68.bBox(mathJaxNode).width; + } + else { + // note: the formula below works for all titlesides, + // (except for top/bottom mathjax, above) + // but the weird gs.l is because the titleunshift + // transform gets removed by Drawing.bBox + titleWidth = + _$drawing_68.bBox(titleCont.node()).right - + xLeft - gs.l; + } + innerWidth = Math.max(innerWidth, titleWidth); + } -/* removed: var _$attributes_70 = require('./attributes'); */; + var outerwidth = 2 * opts.xpad + innerWidth + + opts.borderwidth + opts.outlinewidth / 2, + outerheight = yBottomPx - yTopPx; + container.select('.cbbg').attr({ + x: xLeft - opts.xpad - + (opts.borderwidth + opts.outlinewidth) / 2, + y: yTopPx - yExtraPx, + width: Math.max(outerwidth, 2), + height: Math.max(outerheight + 2 * yExtraPx, 2) + }) + .call(_$color_43.fill, opts.bgcolor) + .call(_$color_43.stroke, opts.bordercolor) + .style({'stroke-width': opts.borderwidth}); -var _$defaults_73 = function(traceIn, traceOut, defaultColor, opts) { - var objName = 'error_' + opts.axis, - containerOut = traceOut[objName] = {}, - containerIn = traceIn[objName] || {}; + container.selectAll('.cboutline').attr({ + x: xLeft, + y: yTopPx + opts.ypad + + (opts.titleside === 'top' ? titleHeight : 0), + width: Math.max(thickPx, 2), + height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) + }) + .call(_$color_43.stroke, opts.outlinecolor) + .style({ + fill: 'None', + 'stroke-width': opts.outlinewidth + }); - function coerce(attr, dflt) { - return _$lib_162.coerce(containerIn, containerOut, _$attributes_70, attr, dflt); - } + // fix positioning for xanchor!='left' + var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * + outerwidth; + container.attr('transform', + 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); - var hasErrorBars = ( - containerIn.array !== undefined || - containerIn.value !== undefined || - containerIn.type === 'sqrt' - ); + // auto margin adjustment + _$plots_237.autoMargin(gd, id, { + x: opts.x, + y: opts.y, + l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), + r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), + t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), + b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) + }); + } - var visible = coerce('visible', hasErrorBars); + var cbDone = _$lib_163.syncOrAsync([ + _$plots_237.previousPromises, + drawAxis, + _$plots_237.previousPromises, + positionCB + ], gd); - if(visible === false) return; + if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); - var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), - symmetric = true; + // dragging... + if(gd._context.edits.colorbarPosition) { + var t0, + xf, + yf; - if(type !== 'sqrt') { - symmetric = coerce('symmetric', - !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); - } + _$dragelement_65.init({ + element: container.node(), + gd: gd, + prepFn: function() { + t0 = container.attr('transform'); + _$setCursor_182(container); + }, + moveFn: function(dx, dy) { + container.attr('transform', + t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); - if(type === 'data') { - coerce('array'); - coerce('traceref'); - if(!symmetric) { - coerce('arrayminus'); - coerce('tracerefminus'); + xf = _$dragelement_65.align(xLeftFrac + (dx / gs.w), thickFrac, + 0, 1, opts.xanchor); + yf = _$dragelement_65.align(yBottomFrac - (dy / gs.h), lenFrac, + 0, 1, opts.yanchor); + + var csr = _$dragelement_65.getCursor(xf, yf, + opts.xanchor, opts.yanchor); + _$setCursor_182(container, csr); + }, + doneFn: function() { + _$setCursor_182(container); + + if(xf !== undefined && yf !== undefined) { + _$registry_245.call('restyle', + gd, + {'colorbar.x': xf, 'colorbar.y': yf}, + getTrace().index + ); + } + } + }); } - } - else if(type === 'percent' || type === 'constant') { - coerce('value'); - if(!symmetric) coerce('valueminus'); + return cbDone; } - var copyAttr = 'copy_' + opts.inherit + 'style'; - if(opts.inherit) { - var inheritObj = traceOut['error_' + opts.inherit]; - if((inheritObj || {}).visible) { - coerce(copyAttr, !(containerIn.color || - _$fastIsnumeric_10(containerIn.thickness) || - _$fastIsnumeric_10(containerIn.width))); + function getTrace() { + var idNum = id.substr(2), + i, + trace; + for(i = 0; i < gd._fullData.length; i++) { + trace = gd._fullData[i]; + if(trace.uid === idNum) return trace; } } - if(!opts.inherit || !containerOut[copyAttr]) { - coerce('color', defaultColor); - coerce('thickness'); - coerce('width', _$registry_244.traceIs(traceOut, 'gl3d') ? 0 : 4); - } + + // setter/getters for every item defined in opts + Object.keys(opts).forEach(function(name) { + component[name] = function(v) { + // getter + if(!arguments.length) return opts[name]; + + // setter - for multi-part properties, + // set only the parts that are provided + opts[name] = _$lib_163.isPlainObject(opts[name]) ? + _$lib_163.extendFlat(opts[name], v) : + v; + + return component; + }; + }); + + // or use .options to set multiple options at once via a dictionary + component.options = function(o) { + Object.keys(o).forEach(function(name) { + // in case something random comes through + // that's not an option, ignore it + if(typeof component[name] === 'function') { + component[name](o[name]); + } + }); + return component; + }; + + component._opts = opts; + + return component; }; /** @@ -40591,168 +40266,50 @@ var _$defaults_73 = function(traceIn, traceOut, defaultColor, opts) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; - -var _$plot_75 = function plot(traces, plotinfo, transitionOpts) { - var isNew; - - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - - var hasAnimation = transitionOpts && transitionOpts.duration > 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 - xObj = trace.error_x || {}, - yObj = trace.error_y || {}; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$colorscale_58 = require('../../components/colorscale'); */; +/* removed: var _$draw_47 = require('../../components/colorbar/draw'); */; - var keyFunc; - if(trace.ids) { - keyFunc = function(d) {return d.id;}; - } +var _$colorbar_285 = function colorbar(gd, cd) { + var trace = cd[0].trace, + marker = trace.marker, + cbId = 'cb' + trace.uid; - var sparse = ( - _$subtypes_302.hasMarkers(trace) && - trace.marker.maxdisplayed > 0 - ); + gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); - if(!yObj.visible && !xObj.visible) d = []; + // TODO make Colorbar.draw support multiple colorbar per trace - var errorbars = _$d3_7.select(this).selectAll('g.errorbar') - .data(d, keyFunc); + if((marker === undefined) || !marker.showscale) { + _$plots_237.autoMargin(gd, cbId); + return; + } - errorbars.exit().remove(); + var vals = marker.color, + cmin = marker.cmin, + cmax = marker.cmax; - if(!d.length) return; + if(!_$fastIsnumeric_10(cmin)) cmin = _$lib_163.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_10(cmax)) cmax = _$lib_163.aggNums(Math.max, null, vals); - 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_68.setClipUrl(errorbars, plotinfo.layerClipId); - - errorbars.each(function(d) { - var errorbar = _$d3_7.select(this); - var coords = errorCoords(d, xa, ya); - - if(sparse && !d.vis) return; - - var path; - - var yerror = errorbar.select('path.yerror'); - if(yObj.visible && _$fastIsnumeric_10(coords.x) && - _$fastIsnumeric_10(coords.yh) && - _$fastIsnumeric_10(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 && _$fastIsnumeric_10(coords.y) && - _$fastIsnumeric_10(coords.xh) && - _$fastIsnumeric_10(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); - } + var cb = cd[0].t.cb = _$draw_47(gd, cbId); + var sclFunc = _$colorscale_58.makeColorScaleFunc( + _$colorscale_58.extractScale( + marker.colorscale, + cmin, + cmax + ), + { noNumericCheck: true } + ); - xerror.attr('d', path); - } - else xerror.remove(); - }); - }); + cb.fillcolor(sclFunc) + .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) + .options(marker.colorbar)(); }; -// 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(!_$fastIsnumeric_10(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(!_$fastIsnumeric_10(out.xs)) { - out.noXS = true; - out.xs = xa.c2p(d.xs, true); - } - } - - return out; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40764,31 +40321,31 @@ function errorCoords(d, xa, ya) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; - -/* removed: var _$color_43 = require('../color'); */; - - -var _$style_76 = function style(traces) { - traces.each(function(d) { - var trace = d[0].trace, - yObj = trace.error_y || {}, - xObj = trace.error_x || {}; - - var s = _$d3_7.select(this); - - s.selectAll('path.yerror') - .style('stroke-width', yObj.thickness + 'px') - .call(_$color_43.stroke, yObj.color); +var Bar = {}; - if(xObj.copy_ystyle) xObj = yObj; +Bar.attributes = _$attributes_255; +Bar.layoutAttributes = _$layout_attributes_260; +Bar.supplyDefaults = _$supplyDefaults_257; +Bar.supplyLayoutDefaults = _$layout_defaults_261; +Bar.calc = _$calc_256; +Bar.setPositions = _$setPositions_264; +Bar.colorbar = _$colorbar_285; +Bar.arraysToCalcdata = _$arraysToCalcdata_254; +Bar.plot = _$plot_262; +Bar.style = _$style_266; +Bar.hoverPoints = _$hoverPoints_258; +Bar.selectPoints = _$selectPoints_263; - s.selectAll('path.xerror') - .style('stroke-width', xObj.thickness + 'px') - .call(_$color_43.stroke, xObj.color); - }); +Bar.moduleType = 'trace'; +Bar.name = 'bar'; +Bar.basePlotModule = _$cartesian_216; +Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend', 'draggedPts']; +Bar.meta = { + }; +var _$Bar_259 = Bar; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40799,1204 +40356,1965 @@ var _$style_76 = function style(traces) { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -var __overrideAll_74 = _$edit_types_189.overrideAll; +var _$bar_3 = _$Bar_259; -/* removed: var _$attributes_70 = require('./attributes'); */; -/* removed: var _$calc_71 = require('./calc'); */; +var _$plotcss_1 = {}; +'use strict'; -var xyAttrs = { - error_x: _$lib_162.extendFlat({}, _$attributes_70), - error_y: _$lib_162.extendFlat({}, _$attributes_70) +/* removed: var _$lib_163 = require('../src/lib'); */; +var rules = { + "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", + "X .modebar--hover": "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": "opacity:1;", + "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", + "X .modebar-group:first-child": "margin-left:0px;", + "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", + "X .modebar-btn svg": "position:relative;top:2px;", + "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", + "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", + "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", + "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", + "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 .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;" }; -delete xyAttrs.error_x.copy_zstyle; -delete xyAttrs.error_y.copy_zstyle; -delete xyAttrs.error_y.copy_ystyle; -var xyzAttrs = { - error_x: _$lib_162.extendFlat({}, _$attributes_70), - error_y: _$lib_162.extendFlat({}, _$attributes_70), - error_z: _$lib_162.extendFlat({}, _$attributes_70) -}; -delete xyzAttrs.error_x.copy_ystyle; -delete xyzAttrs.error_y.copy_ystyle; -delete xyzAttrs.error_z.copy_ystyle; -delete xyzAttrs.error_z.copy_zstyle; +for(var selector in rules) { + var fullSelector = selector.replace(/^,/,' ,') + .replace(/X/g, '.js-plotly-plot .plotly') + .replace(/Y/g, '.plotly-notifier'); + _$lib_163.addStyleRule(fullSelector, rules[selector]); +} -var _$errorbars_74 = { - moduleType: 'component', - name: 'errorbars', +'use strict'; - schema: { - traces: { - scatter: xyAttrs, - bar: xyAttrs, - histogram: xyAttrs, - scatter3d: __overrideAll_74(xyzAttrs, 'calc', 'nested'), - scattergl: __overrideAll_74(xyAttrs, 'calc', 'nested') - } +var _$ploticon_2 = { + 'undo': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'home': { + 'width': 928.6, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'camera-retro': { + 'width': 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', + 'ascent': 850, + 'descent': -150 }, + 'zoombox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'pan': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoom_plus': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoom_minus': { + 'width': 1000, + 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', + 'ascent': 850, + 'descent': -150 + }, + 'autoscale': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'tooltip_basic': { + 'width': 1500, + 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', + 'ascent': 850, + 'descent': -150 + }, + 'tooltip_compare': { + 'width': 1125, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'plotlylogo': { + 'width': 1542, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'z-axis': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + '3d_rotate': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'camera': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'movie': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'question': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'disk': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'lasso': { + 'width': 1031, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'selectbox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'spikeline': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + } +}; - supplyDefaults: _$defaults_73, +var _$browser_24 = {}; +// shim for using process in browser +var process = _$browser_24 = {}; - calc: _$calc_71, - calcFromTrace: calcFromTrace, +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - plot: _$plot_75, - style: _$style_76, - hoverInfo: hoverInfo -}; +var cachedSetTimeout; +var cachedClearTimeout; -function calcFromTrace(trace, layout) { - var x = trace.x || [], - y = trace.y || [], - len = x.length || y.length; +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - var calcdataMock = new Array(len); - for(var i = 0; i < len; i++) { - calcdataMock[i] = { - x: x[i], - y: y[i] - }; +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } } - calcdataMock[0].trace = trace; - _$calc_71({ - calcdata: [calcdataMock], - _fullLayout: layout - }); - return calcdataMock; } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -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; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - if((trace.error_x || {}).visible) { - hoverPoint.xerr = calcPoint.xh - calcPoint.x; - if(!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs; + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } } -var _$domain_230 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __extendFlat_230 = _$extend_156.extendFlat; +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; -/** - * 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 - */ -_$domain_230.attributes = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} - 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] - }; +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; - var namePart = opts.name ? opts.name + ' ' : ''; - var contPart = opts.trace ? 'trace ' : 'subplot '; - var descPart = extra.description ? ' ' + extra.description : ''; +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; - var out = { - x: __extendFlat_230({}, base, { - - }), - y: __extendFlat_230({}, base, { - - }), - editType: opts.editType - }; +function __noop_24() {} - 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, - - }; - } +process.on = __noop_24; +process.addListener = __noop_24; +process.once = __noop_24; +process.off = __noop_24; +process.removeListener = __noop_24; +process.removeAllListeners = __noop_24; +process.emit = __noop_24; +process.prependListener = __noop_24; +process.prependOnceListener = __noop_24; - return out; +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); }; -_$domain_230.defaults = function(containerOut, layout, coerce, dfltDomains) { - var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; - var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - 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 _$es6Promise_8 = { exports: {} }; +(function (process,global){ +/*! + * @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 + */ - var row = coerce('domain.row'); - if(row !== undefined) { - if(row < grid.rows) dfltY = grid._domains.y[row]; - else delete containerOut.domain.row; - } - } +(function (global, factory) { + typeof _$es6Promise_8.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_8.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; - coerce('domain.x', dfltX); - coerce('domain.y', dfltY); -}; +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function isFunction(x) { + return typeof x === 'function'; +} -'use strict'; +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} -/* removed: var _$lib_162 = require('../../lib'); */; -var __counterRegex_89 = _$regex_177.counter; -var domainAttrs = _$domain_230.attributes; -var cartesianIdRegex = _$constants_209.idRegex; +var isArray = _isArray; -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_89('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: 'ticks', - - }, - yside: { - valType: 'enumerated', - values: ['left', 'left plot', 'right plot', 'right'], - dflt: 'left plot', - - editType: 'ticks', - - }, - editType: 'plot' +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(); + } + } }; -// 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; - if(!gridIn) return; +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} - var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]); - var hasXaxes = Array.isArray(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); +function setAsap(asapFn) { + asap = asapFn; +} - var dfltRows, dfltColumns; +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]'; - if(hasSubplotGrid) { - dfltRows = gridIn.subplots.length; - dfltColumns = gridIn.subplots[0].length; - } - else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; - } +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; - var gridOut = layoutOut.grid = {}; +// 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); + }; +} - function coerce(attr, dflt) { - return _$lib_162.coerce(gridIn, gridOut, gridAttrs, attr, dflt); - } +// vertx +function useVertxTimer() { + return function () { + vertxNext(flush); + }; +} - var rows = coerce('rows', dfltRows); - var columns = coerce('columns', dfltColumns); +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); - if(!(rows * columns > 1)) return; + return function () { + node.data = iterations = ++iterations % 2; + }; +} - if(!hasSubplotGrid && !hasXaxes && !hasYaxes) { - var useDefaultSubplots = coerce('pattern') === 'independent'; - if(useDefaultSubplots) hasSubplotGrid = true; - } - gridOut._hasSubplotGrid = hasSubplotGrid; +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} - var rowOrder = coerce('roworder'); - var reversed = rowOrder === 'top to bottom'; +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); + }; +} - gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) - }; +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; } -// coerce x or y sizing attributes and return an array of domains for this direction -function fillGridPositions(axLetter, coerce, dfltGap, len, reversed) { - var dirGap = coerce(axLetter + 'gap', dfltGap); - var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} - 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; +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 && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); } -// 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; +function then(onFulfillment, onRejection) { + var _arguments = arguments; - 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 parent = this; - var i, j, xId, yId, subplotId, subplotsOut, yPos; + var child = new this.constructor(noop); - var axisMap = gridOut._axisMap = {}; + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } - if(hasSubplotGrid) { - var subplotsIn = gridIn.subplots || []; - subplotsOut = gridOut.subplots = new Array(rows); - var index = 1; + var _state = parent._state; - 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]; + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } - rowOut[j] = ''; + return child; +} - 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; - } +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: - rowOut[j] = subplotId; - axisMap[xId] = j; - axisMap[yId] = i; - } - } - } - } - else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); - } + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); - var anchors = gridOut._anchors = {}; - var reversed = gridOut.roworder === 'top to bottom'; + promise.then(function(value){ + // value === 1 + }); + ``` - for(var axisId in axisMap) { - var axLetter = axisId.charAt(0); - var side = gridOut[axLetter + 'side']; + Instead of writing the above, your code now simply becomes the following: - var i0, inc, iFinal; + ```javascript + let promise = Promise.resolve(1); - 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; + promise.then(function(value){ + // value === 1 + }); + ``` - function fillOneAxis(i, axisId) { - if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) { - out[i] = axisId; - axisMap[axisId] = i; - } - else out[i] = ''; - } + @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(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)); - } - } + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } - return out; + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; } -var _$grid_89 = { - moduleType: 'component', - name: 'grid', - - schema: { - layout: {grid: gridAttrs} - }, - - layoutAttributes: gridAttrs, - sizeDefaults: sizeDefaults, - contentDefaults: contentDefaults -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$constants_209 = require('../../plots/cartesian/constants'); */; +var PROMISE_ID = Math.random().toString(36).substring(16); +function noop() {} -var _$attributes_90 = { - _isLinkedToArray: 'image', +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; - visible: { - valType: 'boolean', - - dflt: true, - editType: 'arraydraw', - - }, +var GET_THEN_ERROR = new ErrorObject(); - source: { - valType: 'string', - - editType: 'arraydraw', - - }, +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} - sizex: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} - sizey: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} - sizing: { - valType: 'enumerated', - values: ['fill', 'contain', 'stretch'], - dflt: 'contain', - - editType: 'arraydraw', - - }, +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; - opacity: { - valType: 'number', - - min: 0, - max: 1, - dflt: 1, - editType: 'arraydraw', - - }, + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); - x: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} - y: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, +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); + }); + } +} - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - editType: 'arraydraw', - - }, +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); + } + } +} - yanchor: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'top', - - editType: 'arraydraw', - - }, +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_209.idRegex.x.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_209.idRegex.y.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; + publish(promise); +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + promise._result = value; + promise._state = FULFILLED; -'use strict'; + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_185 = require('../../lib/to_log_range'); */; +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; -/* - * convertCoords: when converting an axis between log and linear - * you need to alter any images on that axis to keep them - * pointing at the same data point. - * In v2.0 this will become obsolete (or perhaps size will still need conversion?) - * we convert size by declaring that the maximum extent *in data units* should be - * the same, assuming the image is anchored by its center (could remove that restriction - * if we think it's important) even though the actual left and right values will not be - * quite the same since the scale becomes nonlinear (and central anchor means the pixel - * center of the image, not the data units center) - * - * gd: the plot div - * ax: the axis being changed - * newType: the type it's getting - * doExtra: function(attr, val) from inside relayout that sets the attribute. - * Use this to make the changes as it's aware if any other changes in the - * same relayout call should override this conversion. - */ -var _$convertCoords_91 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; + asap(publishRejection, promise); +} - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; - if(!(toLog || fromLog)) return; + parent._onerror = null; - var images = gd._fullLayout.images, - axLetter = ax._id.charAt(0), - image, - attrPrefix; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; - for(var i = 0; i < images.length; i++) { - image = images[i]; - attrPrefix = 'images[' + i + '].'; + if (length === 0 && parent._state) { + asap(publish, parent); + } +} - if(image[axLetter + 'ref'] === ax._id) { - var currentPos = image[axLetter], - currentSize = image['size' + axLetter], - newPos = null, - newSize = null; +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; - if(toLog) { - newPos = _$toLogRange_185(currentPos, ax.range); + if (subscribers.length === 0) { + return; + } - // this is the inverse of the conversion we do in fromLog below - // so that the conversion is reversible (notice the fromLog conversion - // is like sinh, and this one looks like arcsinh) - var dx = currentSize / Math.pow(10, newPos) / 2; - newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; - } - else { - newPos = Math.pow(10, currentPos); - newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); - } + var child = undefined, + callback = undefined, + detail = promise._result; - // if conversion failed, delete the value so it can get a default later on - if(!_$fastIsnumeric_10(newPos)) { - newPos = null; - newSize = null; - } - else if(!_$fastIsnumeric_10(newSize)) newSize = null; + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; - doExtra(attrPrefix + axLetter, newPos); - doExtra(attrPrefix + 'size' + axLetter, newSize); - } + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); } -}; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + promise._subscribers.length = 0; +} -'use strict'; +function ErrorObject() { + this.error = null; +} -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_200 = require('../../plots/array_container_defaults'); */; +var TRY_CATCH_ERROR = new ErrorObject(); -/* removed: var _$attributes_90 = require('./attributes'); */; -var name = 'images'; +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} -var _$supplyLayoutDefaults_92 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: name, - handleItemDefaults: imageDefaults - }; +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; - _$handleArrayContainerDefaults_200(layoutIn, layoutOut, opts); -}; + if (hasCallback) { + value = tryCatch(callback, detail); + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } -function imageDefaults(imageIn, imageOut, fullLayout) { + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } - function coerce(attr, dflt) { - return _$lib_162.coerce(imageIn, imageOut, _$attributes_90, attr, dflt); + 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); } +} - var source = coerce('source'); - var visible = coerce('visible', !!source); +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} - if(!visible) return imageOut; +var id = 0; +function nextId() { + return id++; +} - coerce('layer'); - coerce('xanchor'); - coerce('yanchor'); - coerce('sizex'); - coerce('sizey'); - coerce('sizing'); - coerce('opacity'); +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} - var gdMock = { _fullLayout: fullLayout }, - axLetters = ['x', 'y']; +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); - for(var i = 0; i < 2; i++) { - // 'paper' is the fallback axref - var axLetter = axLetters[i], - axRef = _$axes_204.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - _$axes_204.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); - } + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; - return imageOut; -} + this._result = new Array(this.length); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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()); + } +} -'use strict'; +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; -var _$draw_93 = function draw(gd) { - var fullLayout = gd._fullLayout, - imageDataAbove = [], - imageDataSubplot = {}, - imageDataBelow = [], - subplot, - i; + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; - // Sort into top, subplot, and bottom layers - for(i = 0; i < fullLayout.images.length; i++) { - var img = fullLayout.images[i]; +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; - if(img.visible) { - if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { - subplot = img.xref + img.yref; + if (resolve$$ === resolve) { + var _then = getThen(entry); - var plotinfo = fullLayout._plots[subplot]; + 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); + } +}; - if(!plotinfo) { - // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the image to an x / y axis combination - // that doesn't have any data on it (and layer is below) - imageDataBelow.push(img); - continue; - } +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; - if(plotinfo.mainplot) { - subplot = plotinfo.mainplot.id; - } + if (promise._state === PENDING) { + this._remaining--; - if(!imageDataSubplot[subplot]) { - imageDataSubplot[subplot] = []; - } - imageDataSubplot[subplot].push(img); - } else if(img.layer === 'above') { - imageDataAbove.push(img); - } else { - imageDataBelow.push(img); - } - } + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; } + } + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; - var anchors = { - x: { - left: { sizing: 'xMin', offset: 0 }, - center: { sizing: 'xMid', offset: -1 / 2 }, - right: { sizing: 'xMax', offset: -1 } - }, - y: { - top: { sizing: 'YMin', offset: 0 }, - middle: { sizing: 'YMid', offset: -1 / 2 }, - bottom: { sizing: 'YMax', offset: -1 } - } - }; +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); + }); +}; - // Images must be converted to dataURL's for exporting. - function setImage(d) { - var thisImage = _$d3_7.select(this); +/** + `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. - if(this.img && this.img.src === d.source) { - return; - } + Example: - thisImage.attr('xmlns', _$xmlns_namespaces_147.svg); + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; - var imagePromise = new Promise(function(resolve) { + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` - var img = new Image(); - this.img = img; + 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: - // If not set, a `tainted canvas` error is thrown - img.setAttribute('crossOrigin', 'anonymous'); - img.onerror = errorHandler; - img.onload = function() { - var canvas = document.createElement('canvas'); - canvas.width = this.width; - canvas.height = this.height; + Example: - var ctx = canvas.getContext('2d'); - ctx.drawImage(this, 0, 0); + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; - var dataURL = canvas.toDataURL('image/png'); + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` - thisImage.attr('xlink:href', dataURL); + @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; +} - // resolve promise in onload handler instead of on 'load' to support IE11 - // see https://github.com/plotly/plotly.js/issues/1685 - // for more details - resolve(); - }; +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + Example: - thisImage.on('error', errorHandler); + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - img.src = d.source; + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); - function errorHandler() { - thisImage.remove(); - resolve(); - } - }.bind(this)); + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` - gd._promises.push(imagePromise); - } + `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: - function applyAttributes(d) { - var thisImage = _$d3_7.select(this); + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - // Axes if specified - var xa = _$axes_204.getFromId(gd, d.xref), - ya = _$axes_204.getFromId(gd, d.yref); + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); - var size = fullLayout._size, - width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, - height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; + 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 + }); + ``` - // Offsets for anchor positioning - var xOffset = width * anchors.x[d.xanchor].offset, - yOffset = height * anchors.y[d.yanchor].offset; + An example real-world use case is implementing timeouts: - var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` - // Final positions - var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, - yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; + @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); + } + }); + } +} - // Construct the proper aspectRatio attribute - switch(d.sizing) { - case 'fill': - sizing += ' slice'; - break; +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: - case 'stretch': - sizing = 'none'; - break; - } + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); - thisImage.attr({ - x: xPos, - y: yPos, - width: width, - height: height, - preserveAspectRatio: sizing, - opacity: d.opacity - }); + 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: - // Set proper clipping on images - var xId = xa ? xa._id : '', - yId = ya ? ya._id : '', - clipAxes = xId + yId; + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); - thisImage.call(_$drawing_68.setClipUrl, clipAxes ? - ('clip' + fullLayout._uid + clipAxes) : - null - ); - } + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` - var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') - .data(imageDataBelow), - imagesAbove = fullLayout._imageUpperLayer.selectAll('image') - .data(imageDataAbove); + @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; +} - imagesBelow.enter().append('image'); - imagesAbove.enter().append('image'); +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} - imagesBelow.exit().remove(); - imagesAbove.exit().remove(); +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} - imagesBelow.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - imagesAbove.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); +/** + 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. - var allSubplots = Object.keys(fullLayout._plots); - for(i = 0; i < allSubplots.length; i++) { - subplot = allSubplots[i]; - var subplotObj = fullLayout._plots[subplot]; + Terminology + ----------- - // filter out overlaid plots (which havd their images on the main plot) - // and gl2d plots (which don't support below images, at least not yet) - if(!subplotObj.imagelayer) continue; + - `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. - var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') - // even if there are no images on this subplot, we need to run - // enter and exit in case there were previously - .data(imageDataSubplot[subplot] || []); + A promise can be in one of three states: pending, fulfilled, or rejected. - imagesOnSubplot.enter().append('image'); - imagesOnSubplot.exit().remove(); + 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. - imagesOnSubplot.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - } -}; + 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. -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; + Basic Usage: + ------------ -var _$images_94 = { - moduleType: 'component', - name: 'images', + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); - layoutAttributes: _$attributes_90, - supplyLayoutDefaults: _$supplyLayoutDefaults_92, - includeBasePlot: _$makeIncludeComponents_214('images'), + // on failure + reject(reason); + }); - draw: _$draw_93, + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` - convertCoords: _$convertCoords_91 -}; + Advanced Usage: + --------------- -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. -'use strict'; + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_42 = require('../color/attributes'); */; + 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 + ']')); + } + } + }; + }); + } -var _$attributes_96 = { - bgcolor: { - valType: 'color', + 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 +}).call(this,_$browser_24,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +_$es6Promise_8 = _$es6Promise_8.exports +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/** + * All paths are tuned for maximum scalability of the arrowhead, + * ie throughout arrowwidth=0.3..3 the head is joined smoothly + * to the line, with the line coming from the left and ending at (0, 0). + * + * `backoff` is the distance to move the arrowhead and the end of the line, + * in order that the arrowhead points to the desired place, either at + * the tip of the arrow or (in the case of circle or square) + * the center of the symbol. + * + * `noRotate`, if truthy, says that this arrowhead should not rotate with the + * arrow. That's the case for squares, which should always be straight, and + * circles, for which it's irrelevant. + */ + +var _$arrow_paths_27 = [ + // no arrow + { + path: '', + backoff: 0 + }, + // wide with flat back + { + path: 'M-2.4,-3V3L0.6,0Z', + backoff: 0.6 + }, + // narrower with flat back + { + path: 'M-3.7,-2.5V2.5L1.3,0Z', + backoff: 1.3 + }, + // barbed + { + path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', + backoff: 1.55 + }, + // wide line-drawn + { + path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', + backoff: 1.6 + }, + // narrower line-drawn + { + path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', + backoff: 2 + }, + // circle + { + path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', + backoff: 0, + noRotate: true + }, + // square + { + path: 'M2,2V-2H-2V2Z', + backoff: 0, + noRotate: true + } +]; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$arrow_paths_27 = require('./arrow_paths'); */; +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; +/* removed: var _$constants_210 = require('../../plots/cartesian/constants'); */; + + +var _$attributes_28 = { + _isLinkedToArray: 'annotation', + + visible: { + valType: 'boolean', - editType: 'legend', + dflt: true, + editType: 'calcIfAutorange+arraydraw', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_42.defaultLine, + + text: { + valType: 'string', - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', }, - borderwidth: { - valType: 'number', - min: 0, + textangle: { + valType: 'angle', dflt: 0, - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', }, font: _$font_attributes_231({ - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', + colorEditType: 'arraydraw', }), - orientation: { - valType: 'enumerated', - values: ['v', 'h'], - dflt: 'v', + width: { + valType: 'number', + min: 1, + dflt: null, - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', }, - traceorder: { - valType: 'flaglist', - flags: ['reversed', 'grouped'], - extras: ['normal'], + height: { + valType: 'number', + min: 1, + dflt: null, - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', }, - tracegroupgap: { + opacity: { valType: 'number', min: 0, - dflt: 10, + max: 1, + dflt: 1, - editType: 'legend', + editType: 'arraydraw', }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 1.02, + align: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'center', - editType: 'legend', + editType: 'arraydraw', }, - xanchor: { + valign: { valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', + values: ['top', 'middle', 'bottom'], + dflt: 'middle', - editType: 'legend', + editType: 'arraydraw', }, - y: { + bgcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + bordercolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + borderpad: { valType: 'number', - min: -2, - max: 3, + min: 0, dflt: 1, - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, - editType: 'legend', + editType: 'calcIfAutorange+arraydraw', }, - editType: 'legend' -}; - -var _$helpers_102 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -_$helpers_102.legendGetsTrace = function legendGetsTrace(trace) { - // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? - // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. - - // Note that we explicitly include showlegend: false, so a trace that *could* be - // in the legend but is not shown still counts toward the two traces you need to - // ensure the legend is shown by default, because this can still help disambiguate. - return trace.visible && (trace.showlegend !== undefined); -}; - -_$helpers_102.isGrouped = function isGrouped(legendLayout) { - return (legendLayout.traceorder || '').indexOf('grouped') !== -1; -}; - -_$helpers_102.isVertical = function isVertical(legendLayout) { - return legendLayout.orientation !== 'h'; -}; + // arrow + showarrow: { + valType: 'boolean', + dflt: true, + + editType: 'calcIfAutorange+arraydraw', + + }, + arrowcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + arrowhead: { + valType: 'integer', + min: 0, + max: _$arrow_paths_27.length, + dflt: 1, + + editType: 'arraydraw', + + }, + startarrowhead: { + valType: 'integer', + min: 0, + max: _$arrow_paths_27.length, + dflt: 1, + + editType: 'arraydraw', + + }, + arrowside: { + valType: 'flaglist', + flags: ['end', 'start'], + extras: ['none'], + dflt: 'end', + + editType: 'arraydraw', + + }, + arrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', + + }, + startarrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', + + }, + arrowwidth: { + valType: 'number', + min: 0.1, + + editType: 'calcIfAutorange+arraydraw', + + }, + standoff: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + startstandoff: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + ax: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + ay: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + axref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_210.idRegex.x.toString() + ], + + editType: 'calc', + + }, + ayref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_210.idRegex.y.toString() + ], + + editType: 'calc', + + }, + // positioning + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_210.idRegex.x.toString() + ], + + editType: 'calc', + + }, + x: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + xshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_210.idRegex.y.toString() + ], + + editType: 'calc', + + }, + y: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + yshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + clicktoshow: { + valType: 'enumerated', + values: [false, 'onoff', 'onout'], + dflt: false, + + editType: 'arraydraw', + + }, + xclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + yclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + hovertext: { + valType: 'string', + + editType: 'arraydraw', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + bordercolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + font: _$font_attributes_231({ + editType: 'arraydraw', + + }), + editType: 'arraydraw' + }, + captureevents: { + valType: 'boolean', + + editType: 'arraydraw', + + }, + editType: 'calc', -_$helpers_102.isReversed = function isReversed(legendLayout) { - return (legendLayout.traceorder || '').indexOf('reversed') !== -1; + _deprecated: { + ref: { + valType: 'string', + + editType: 'calc', + + } + } }; /** @@ -42010,151 +42328,146 @@ _$helpers_102.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; - -/* removed: var _$attributes_96 = require('./attributes'); */; -/* removed: var _$layout_attributes_235 = require('../../plots/layout_attributes'); */; -/* removed: var _$helpers_102 = require('./helpers'); */; - +/* removed: var _$d3_7 = require('d3'); */; -var _$legendDefaults_98 = function legendDefaults(layoutIn, layoutOut, fullData) { - var containerIn = layoutIn.legend || {}; - var containerOut = {}; +/* removed: var _$color_43 = require('../color'); */; - var visibleTraces = 0; - var defaultOrder = 'normal'; +/* removed: var _$arrow_paths_27 = require('./arrow_paths'); */; - var defaultX, defaultY, defaultXAnchor, defaultYAnchor; +/** + * 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. + */ +var _$drawArrowHead_35 = function drawArrowHead(el3, ends, options) { + var el = el3.node(); + var headStyle = _$arrow_paths_27[options.arrowhead || 0]; + var startHeadStyle = _$arrow_paths_27[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; - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + var start, end, startRot, endRot; - if(_$helpers_102.legendGetsTrace(trace)) { - visibleTraces++; - // always show the legend by default if there's a pie - if(_$registry_244.traceIs(trace, 'pie')) visibleTraces++; - } + if(el.nodeName === 'line') { + start = {x: +el3.attr('x1'), y: +el3.attr('y1')}; + end = {x: +el3.attr('x2'), y: +el3.attr('y2')}; - if((_$registry_244.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || - ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { - defaultOrder = _$helpers_102.isGrouped({traceorder: defaultOrder}) ? - 'grouped+reversed' : 'reversed'; - } + var dx = start.x - end.x; + var dy = start.y - end.y; - if(trace.legendgroup !== undefined && trace.legendgroup !== '') { - defaultOrder = _$helpers_102.isReversed({traceorder: defaultOrder}) ? - 'reversed+grouped' : 'grouped'; + startRot = Math.atan2(dy, dx); + endRot = startRot + Math.PI; + if(backOff && startBackOff) { + if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) { + hideLine(); + return; + } } - } - function coerce(attr, dflt) { - return _$lib_162.coerce(containerIn, containerOut, _$attributes_96, attr, dflt); - } + if(backOff) { + if(backOff * backOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var backOffX = backOff * Math.cos(startRot), + backOffY = backOff * Math.sin(startRot); - var showLegend = _$lib_162.coerce(layoutIn, layoutOut, - _$layout_attributes_235, 'showlegend', visibleTraces > 1); + end.x += backOffX; + end.y += backOffY; + el3.attr({x2: end.x, y2: end.y}); - if(showLegend === false) return; + } - layoutOut.legend = containerOut; + if(startBackOff) { + if(startBackOff * startBackOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var startBackOffX = startBackOff * Math.cos(startRot), + startbackOffY = startBackOff * Math.sin(startRot); - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - _$lib_162.coerceFont(coerce, 'font', layoutOut.font); + start.x -= startBackOffX; + start.y -= startbackOffY; + el3.attr({x1: start.x, y1: start.y}); - coerce('orientation'); - if(containerOut.orientation === 'h') { - var xaxis = layoutIn.xaxis; - if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = 1.1; - defaultYAnchor = 'bottom'; - } - else { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = -0.1; - defaultYAnchor = 'top'; } } + 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 + dashArray = ''; - coerce('traceorder', defaultOrder); - if(_$helpers_102.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); - - coerce('x', defaultX); - coerce('xanchor', defaultXAnchor); - coerce('y', defaultY); - coerce('yanchor', defaultYAnchor); - _$lib_162.noneOrAll(containerIn, containerOut, ['x', 'y']); -}; + if(pathlen < backOff + startBackOff) { + hideLine(); + return; + } -var _$anchor_utils_95 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 start0 = el.getPointAtLength(0); + var dstart = el.getPointAtLength(0.1); -'use strict'; + startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); + start = el.getPointAtLength(Math.min(startBackOff, pathlen)); + dashArray = '0px,' + startBackOff + 'px,'; -/** - * 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. - */ + var end0 = el.getPointAtLength(pathlen); + var dend = el.getPointAtLength(pathlen - 0.1); -_$anchor_utils_95.isRightAnchor = function isRightAnchor(opts) { - return ( - opts.xanchor === 'right' || - (opts.xanchor === 'auto' && opts.x >= 2 / 3) - ); -}; + endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); + end = el.getPointAtLength(Math.max(0, pathlen - backOff)); -_$anchor_utils_95.isCenterAnchor = function isCenterAnchor(opts) { - return ( - opts.xanchor === 'center' || - (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) - ); -}; + var shortening = dashArray ? startBackOff + backOff : backOff; + dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px'; -_$anchor_utils_95.isBottomAnchor = function isBottomAnchor(opts) { - return ( - opts.yanchor === 'bottom' || - (opts.yanchor === 'auto' && opts.y <= 1 / 3) - ); -}; + el3.style('stroke-dasharray', dashArray); + } -_$anchor_utils_95.isMiddleAnchor = function isMiddleAnchor(opts) { - return ( - opts.yanchor === 'middle' || - (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) - ); -}; + function hideLine() { el3.style('stroke-dasharray', '0px,100px'); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function drawhead(arrowHeadStyle, p, rot, arrowScale) { + if(!arrowHeadStyle.path) return; + if(arrowHeadStyle.noRotate) rot = 0; -'use strict'; + _$d3_7.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_43.rgb(options.arrowcolor), + 'stroke-width': 0 + }); + } -var _$constants_97 = { - scrollBarWidth: 6, - scrollBarMinHeight: 20, - scrollBarColor: '#808BA4', - scrollBarMargin: 4 + if(doStart) drawhead(startHeadStyle, start, startRot, startScale); + if(doEnd) drawhead(headStyle, end, endRot, scale); }; /** @@ -42165,622 +42478,703 @@ var _$constants_97 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$helpers_102 = require('./helpers'); */; +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$fx_85 = require('../fx'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$drawArrowHead_35 = require('./draw_arrow_head'); */; -var _$getLegendData_100 = function getLegendData(calcdata, opts) { - var lgroupToTraces = {}, - lgroups = [], - hasOneNonBlankGroup = false, - slicesShown = {}, - lgroupi = 0; +// Annotations are stored in gd.layout.annotations, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - var i, j; +var _$draw_34 = { + draw: __draw_34, + drawOne: drawOne, + drawRaw: drawRaw +}; - function addOneItem(legendGroup, legendItem) { - // each '' legend group is treated as a separate group - if(legendGroup === '' || !_$helpers_102.isGrouped(opts)) { - var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? +/* + * draw: draw all annotations without any new modifications + */ +function __draw_34(gd) { + var fullLayout = gd._fullLayout; - lgroups.push(uniqueGroup); - lgroupToTraces[uniqueGroup] = [[legendItem]]; - lgroupi++; - } - else if(lgroups.indexOf(legendGroup) === -1) { - lgroups.push(legendGroup); - hasOneNonBlankGroup = true; - lgroupToTraces[legendGroup] = [[legendItem]]; + fullLayout._infolayer.selectAll('.annotation').remove(); + + for(var i = 0; i < fullLayout.annotations.length; i++) { + if(fullLayout.annotations[i].visible) { + drawOne(gd, i); } - else lgroupToTraces[legendGroup].push([legendItem]); } - // build an { legendgroup: [cd0, cd0], ... } object - for(i = 0; i < calcdata.length; i++) { - var cd = calcdata[i], - cd0 = cd[0], - trace = cd0.trace, - lgroup = trace.legendgroup; - - if(!_$helpers_102.legendGetsTrace(trace) || !trace.showlegend) continue; + return _$plots_237.previousPromises(gd); +} - if(_$registry_244.traceIs(trace, 'pie')) { - if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; +/* + * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications + * + * index (int): the annotation to draw + */ +function drawOne(gd, index) { + var fullLayout = gd._fullLayout; + var options = fullLayout.annotations[index] || {}; + var xa = _$axes_205.getFromId(gd, options.xref); + var ya = _$axes_205.getFromId(gd, options.yref); - for(j = 0; j < cd.length; j++) { - var labelj = cd[j].label; + drawRaw(gd, options, index, false, xa, ya); +} - if(!slicesShown[lgroup][labelj]) { - addOneItem(lgroup, { - label: labelj, - color: cd[j].color, - i: cd[j].i, - trace: trace - }); +/** + * drawRaw: draw a single annotation, potentially with modifications + * + * @param {DOM element} gd + * @param {object} options : this annotation's fullLayout options + * @param {integer} index : index in 'annotations' container of the annotation to draw + * @param {string} subplotId : id of the annotation's subplot + * - use false for 2d (i.e. cartesian or paper-ref) annotations + * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px + * @param {object | undefined} ya : ... y-axis + */ +function drawRaw(gd, options, index, subplotId, xa, ya) { + var fullLayout = gd._fullLayout; + var gs = gd._fullLayout._size; + var edits = gd._context.edits; - slicesShown[lgroup][labelj] = true; - } - } - } + var className; + var annbase; - else addOneItem(lgroup, cd0); + if(subplotId) { + className = 'annotation-' + subplotId; + annbase = subplotId + '.annotations[' + index + ']'; + } else { + className = 'annotation'; + annbase = 'annotations[' + index + ']'; } - // won't draw a legend in this case - if(!lgroups.length) return []; - - // rearrange lgroupToTraces into a d3-friendly array of arrays - var lgroupsLength = lgroups.length, - ltraces, - legendData; - - if(hasOneNonBlankGroup && _$helpers_102.isGrouped(opts)) { - legendData = new Array(lgroupsLength); + // remove the existing annotation if there is one + fullLayout._infolayer + .selectAll('.' + className + '[data-index="' + index + '"]') + .remove(); - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]]; - legendData[i] = _$helpers_102.isReversed(opts) ? ltraces.reverse() : ltraces; - } - } - else { - // collapse all groups into one if all groups are blank - legendData = [new Array(lgroupsLength)]; + var annClipID = 'clip' + fullLayout._uid + '_ann' + index; - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]][0]; - legendData[0][_$helpers_102.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; - } - lgroupsLength = 1; + // this annotation is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!options._input || options.visible === false) { + _$d3_7.selectAll('#' + annClipID).remove(); + return; } - // needed in repositionLegend - opts._lgroupsLength = lgroupsLength; - return legendData; -}; + // calculated pixel positions + // x & y each will get text, head, and tail as appropriate + var annPosPx = {x: {}, y: {}}, + textangle = +options.textangle || 0; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // create the components + // made a single group to contain all, so opacity can work right + // with border/arrow together this could handle a whole bunch of + // cleanup at this point, but works for now + var annGroup = fullLayout._infolayer.append('g') + .classed(className, true) + .attr('data-index', String(index)) + .style('opacity', options.opacity); -'use strict'; + // another group for text+background so that they can rotate together + var annTextGroup = annGroup.append('g') + .classed('annotation-text-g', true); -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$registry_244 = require('../../registry'); */; + var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; + var textEvents = options.captureevents || edits.annotationText || editTextPosition; -var SHOWISOLATETIP = true; + var annTextGroupInner = annTextGroup.append('g') + .style('pointer-events', textEvents ? 'all' : null) + .call(_$setCursor_182, 'default') + .on('click', function() { + gd._dragging = false; -var _$handleClick_101 = function handleClick(g, gd, numClicks) { - if(gd._dragged || gd._editing) return; + var eventData = { + index: index, + annotation: options._input, + fullAnnotation: options, + event: _$d3_7.event + }; - var hiddenSlices = gd._fullLayout.hiddenlabels ? - gd._fullLayout.hiddenlabels.slice() : - []; + if(subplotId) { + eventData.subplotId = subplotId; + } - var legendItem = g.data()[0][0]; - var fullData = gd._fullData; - var fullTrace = legendItem.trace; - var legendgroup = fullTrace.legendgroup; + gd.emit('plotly_clickannotation', eventData); + }); - var i, j, kcont, key, keys, val; - var attrUpdate = {}; - var attrIndices = []; - var carrs = []; - var carrIdx = []; + if(options.hovertext) { + annTextGroupInner + .on('mouseover', function() { + var hoverOptions = options.hoverlabel; + var hoverFont = hoverOptions.font; + var bBox = this.getBoundingClientRect(); + var bBoxRef = gd.getBoundingClientRect(); - function insertUpdate(traceIndex, key, value) { - var attrIndex = attrIndices.indexOf(traceIndex); - var valueArray = attrUpdate[key]; - if(!valueArray) { - valueArray = attrUpdate[key] = []; - } + _$fx_85.loneHover({ + x0: bBox.left - bBoxRef.left, + x1: bBox.right - bBoxRef.left, + y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, + text: options.hovertext, + color: hoverOptions.bgcolor, + borderColor: hoverOptions.bordercolor, + fontFamily: hoverFont.family, + fontSize: hoverFont.size, + fontColor: hoverFont.color + }, { + container: fullLayout._hoverlayer.node(), + outerContainer: fullLayout._paper.node(), + gd: gd + }); + }) + .on('mouseout', function() { + _$fx_85.loneUnhover(fullLayout._hoverlayer.node()); + }); + } - if(attrIndices.indexOf(traceIndex) === -1) { - attrIndices.push(traceIndex); - attrIndex = attrIndices.length - 1; - } + var borderwidth = options.borderwidth, + borderpad = options.borderpad, + borderfull = borderwidth + borderpad; - valueArray[attrIndex] = value; + var annTextBG = annTextGroupInner.append('rect') + .attr('class', 'bg') + .style('stroke-width', borderwidth + 'px') + .call(_$color_43.stroke, options.bordercolor) + .call(_$color_43.fill, options.bgcolor); - return attrIndex; - } + var isSizeConstrained = options.width || options.height; - function setVisibility(fullTrace, visibility) { - var fullInput = fullTrace._fullInput; - if(_$registry_244.hasTransform(fullInput, 'groupby')) { - var kcont = carrs[fullInput.index]; - if(!kcont) { - var groupbyIndices = _$registry_244.getTransformIndices(fullInput, 'groupby'); - var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_162.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); - carrs[fullInput.index] = kcont; - } + var annTextClip = fullLayout._topclips + .selectAll('#' + annClipID) + .data(isSizeConstrained ? [0] : []); - var curState = kcont.get(fullTrace._group); + annTextClip.enter().append('clipPath') + .classed('annclip', true) + .attr('id', annClipID) + .append('rect'); + annTextClip.exit().remove(); - // 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; - } + var font = options.font; - 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; + var annText = annTextGroupInner.append('text') + .classed('annotation-text', true) + .text(options.text); - insertUpdate(fullInput.index, 'visible', nextVisibility); - } - } + function textLayout(s) { + s.call(_$drawing_68.font, font) + .attr({ + 'text-anchor': { + left: 'start', + right: 'end' + }[options.align] || 'middle' + }); - if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_162.notifier(_$lib_162._(gd, 'Double-click on legend to isolate one trace'), 'long'); - SHOWISOLATETIP = false; - } else { - SHOWISOLATETIP = false; + _$svg_text_utils_184.convertToTspans(s, gd, drawGraphicalElements); + return s; } - if(_$registry_244.traceIs(fullTrace, 'pie')) { - var thisLabel = legendItem.label, - thisLabelIndex = hiddenSlices.indexOf(thisLabel); + function drawGraphicalElements() { + // if the text has *only* a link, make the whole box into a link + var anchor3 = annText.selectAll('a'); + if(anchor3.size() === 1 && anchor3.text() === annText.text()) { + var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ + 'xlink:xlink:href': anchor3.attr('xlink:href'), + 'xlink:xlink:show': anchor3.attr('xlink:show') + }) + .style({cursor: 'pointer'}); - if(numClicks === 1) { - if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); - else hiddenSlices.splice(thisLabelIndex, 1); - } else if(numClicks === 2) { - 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 = []; - } + wholeLink.node().appendChild(annTextBG.node()); } - _$registry_244.call('relayout', 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); - } + var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); + var hasMathjax = !mathjaxGroup.empty(); + var anntextBB = _$drawing_68.bBox( + (hasMathjax ? mathjaxGroup : annText).node()); + var textWidth = anntextBB.width; + var textHeight = anntextBB.height; + var annWidth = options.width || textWidth; + var annHeight = options.height || textHeight; + var outerWidth = Math.round(annWidth + 2 * borderfull); + var outerHeight = Math.round(annHeight + 2 * borderfull); + + + // save size in the annotation object for use by autoscale + options._w = annWidth; + options._h = annHeight; + + function shiftFraction(v, anchor) { + if(anchor === 'auto') { + if(v < 1 / 3) anchor = 'left'; + else if(v > 2 / 3) anchor = 'right'; + else anchor = 'center'; } + return { + center: 0, + middle: 0, + left: 0.5, + bottom: -0.5, + right: -0.5, + top: 0.5 + }[anchor]; } - if(numClicks === 1) { - var nextVisibility; + var annotationIsOffscreen = false; + var letters = ['x', 'y']; - switch(fullTrace.visible) { - case true: - nextVisibility = 'legendonly'; - break; - case false: - nextVisibility = false; - break; - case 'legendonly': - nextVisibility = true; - break; - } + for(var i = 0; i < letters.length; i++) { + var axLetter = letters[i], + axRef = options[axLetter + 'ref'] || axLetter, + tailRef = options['a' + axLetter + 'ref'], + ax = {x: xa, y: ya}[axLetter], + dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, + // note that these two can be either positive or negative + annSizeFromWidth = outerWidth * Math.cos(dimAngle), + annSizeFromHeight = outerHeight * Math.sin(dimAngle), + // but this one is the positive total size + annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), + anchor = options[axLetter + 'anchor'], + overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), + posPx = annPosPx[axLetter], + basePx, + textPadShift, + alignPosition, + autoAlignFraction, + textShift; - if(hasLegendgroup) { - for(i = 0; i < fullData.length; i++) { - if(fullData[i].visible !== false && fullData[i].legendgroup === legendgroup) { - setVisibility(fullData[i], nextVisibility); + /* + * calculate the *primary* pixel position + * which is the arrowhead if there is one, + * otherwise the text anchor point + */ + if(ax) { + /* + * hide the annotation if it's pointing outside the visible plot + * as long as the axis isn't autoranged - then we need to draw it + * anyway to get its bounding box. When we're dragging, an axis can + * still look autoranged even though it won't be when the drag finishes. + */ + var posFraction = ax.r2fraction(options[axLetter]); + if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { + if(tailRef === axRef) { + posFraction = ax.r2fraction(options['a' + axLetter]); + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + } + } + else { + annotationIsOffscreen = true; } + + if(annotationIsOffscreen) continue; } - } else { - setVisibility(fullTrace, nextVisibility); + basePx = ax._offset + ax.r2p(options[axLetter]); + autoAlignFraction = 0.5; } - } else if(numClicks === 2) { - // 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, otherState; - var isIsolated = true; - for(i = 0; i < fullData.length; i++) { - isClicked = fullData[i] === fullTrace; - if(isClicked) continue; - - isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - - if(!isInGroup && fullData[i].visible === true && !_$registry_244.traceIs(fullData[i], 'notLegendIsolatable')) { - isIsolated = false; - break; + 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; } - for(i = 0; i < fullData.length; i++) { - // False is sticky; we don't change it. - if(fullData[i].visible === false) continue; + // now translate this into pixel positions of head, tail, and text + // as well as paddings for autorange + if(options.showarrow) { + posPx.head = basePx; - if(_$registry_244.traceIs(fullData[i], 'notLegendIsolatable')) { - continue; + 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; } - switch(fullTrace.visible) { - case 'legendonly': - setVisibility(fullData[i], true); - break; - case true: - otherState = isIsolated ? true : 'legendonly'; - isClicked = fullData[i] === fullTrace; - isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); - setVisibility(fullData[i], isInGroup ? true : otherState); - break; + 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_163.constrain(posPx.head, 1, maxPx - 1); + } + if(tailRef === 'pixel') { + var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), + 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; } - } - for(i = 0; i < carrs.length; i++) { - kcont = carrs[i]; - if(!kcont) continue; - var update = kcont.constructUpdate(); + posPx.text += overallShift; + textShift += overallShift; + textPadShift += overallShift; - 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]; - } + // 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; } - // 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; - } - } + if(annotationIsOffscreen) { + annTextGroupInner.remove(); + return; } - _$registry_244.call('restyle', gd, attrUpdate, attrIndices); - } -}; - -var _$helpers_272 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_162 = require('../../lib'); */; - -_$helpers_272.formatPiePercent = function formatPiePercent(v, separators) { - var vRounded = (v * 100).toPrecision(3); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_162.numSeparate(vRounded, separators) + '%'; -}; - -_$helpers_272.formatPieValue = function formatPieValue(v, separators) { - var vRounded = v.toPrecision(10); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_162.numSeparate(vRounded, separators); -}; - -_$helpers_272.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) return v; - } -}; - -_$helpers_272.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_272.getFirstFilled(item, indices); - else if(item) return item; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; + var xShift = 0; + var yShift = 0; -/* removed: var _$color_43 = require('../../components/color'); */; -var castOption = _$helpers_272.castOption; + 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); + } -var _$styleOne_278 = function styleOne(s, pt, trace) { - var line = trace.marker.line; - var lineColor = castOption(line.color, pt.pts) || _$color_43.defaultLine; - var lineWidth = castOption(line.width, pt.pts) || 0; + if(hasMathjax) { + mathjaxGroup.select('svg').attr({ + x: borderfull + xShift - 1, + y: borderfull + yShift + }) + .call(_$drawing_68.setClipUrl, isSizeConstrained ? annClipID : null); + } + else { + var texty = borderfull + yShift - anntextBB.top; + var textx = borderfull + xShift - anntextBB.left; - s.style({'stroke-width': lineWidth}) - .call(_$color_43.fill, pt.color) - .call(_$color_43.stroke, lineColor); -}; + annText.call(_$svg_text_utils_184.positionText, textx, texty) + .call(_$drawing_68.setClipUrl, isSizeConstrained ? annClipID : null); + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + annTextClip.select('rect').call(_$drawing_68.setRect, borderfull, borderfull, + annWidth, annHeight); + annTextBG.call(_$drawing_68.setRect, borderwidth / 2, borderwidth / 2, + outerWidth - borderwidth, outerHeight - borderwidth); -'use strict'; + annTextGroupInner.call(_$drawing_68.setTranslate, + Math.round(annPosPx.x.text - outerWidth / 2), + Math.round(annPosPx.y.text - outerHeight / 2)); -/* removed: var _$d3_7 = require('d3'); */; + /* + * 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 + ')'}); -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$color_43 = require('../color'); */; + /* + * 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(); -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_278 = require('../../traces/pie/style_one'); */; + var headX = annPosPx.x.head, + headY = annPosPx.y.head, + tailX = annPosPx.x.tail + dx, + tailY = annPosPx.y.tail + dy, + textX = annPosPx.x.text + dx, + 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 + transform = _$lib_163.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_163.apply2DTransform(transform), + applyTransform2 = _$lib_163.apply2DTransform2(transform), -var _$style_104 = function style(s, gd) { - s.each(function(d) { - var traceGroup = _$d3_7.select(this); + // calculate and transform bounding box + width = +annTextBG.attr('width'), + height = +annTextBG.attr('height'), + xLeft = textX - 0.5 * width, + xRight = xLeft + width, + yTop = textY - 0.5 * height, + yBottom = yTop + height, + edges = [ + [xLeft, yTop, xLeft, yBottom], + [xLeft, yBottom, xRight, yBottom], + [xRight, yBottom, xRight, yTop], + [xRight, yTop, xLeft, yTop] + ].map(applyTransform2); - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); - layers.style('opacity', d[0].trace.opacity); + // 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_163.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; + } - var fill = layers - .selectAll('g.legendfill') - .data([d]); - fill.enter().append('g') - .classed('legendfill', true); + edges.forEach(function(x) { + var p = _$lib_163.segmentsIntersect(tailX, tailY, headX, headY, + x[0], x[1], x[2], x[3]); + if(p) { + tailX = p.x; + tailY = p.y; + } + }); - var line = layers - .selectAll('g.legendlines') - .data([d]); - line.enter().append('g') - .classed('legendlines', true); + var strokewidth = options.arrowwidth, + arrowColor = options.arrowcolor, + arrowSide = options.arrowside; - var symbol = layers - .selectAll('g.legendsymbols') - .data([d]); - symbol.enter().append('g') - .classed('legendsymbols', true); + var arrowGroup = annGroup.append('g') + .style({opacity: _$color_43.opacity(arrowColor)}) + .classed('annotation-arrow-g', true); - symbol.selectAll('g.legendpoints') - .data([d]) - .enter().append('g') - .classed('legendpoints', true); - }) - .each(styleBars) - .each(styleBoxes) - .each(stylePies) - .each(styleLines) - .each(stylePoints); + var arrow = arrowGroup.append('path') + .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY) + .style('stroke-width', strokewidth + 'px') + .call(_$color_43.stroke, _$color_43.rgb(arrowColor)); - function styleLines(d) { - var trace = d[0].trace; - var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_302.hasLines(trace); - var contours = trace.contours; + _$drawArrowHead_35(arrow, arrowSide, options); - if(contours && contours.type === 'constraint') { - showLine = contours.showlines; - showFill = contours._operation !== '='; - } + // 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) + .attr({ + d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), + transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' + }) + .style('stroke-width', (strokewidth + 6) + 'px') + .call(_$color_43.stroke, 'rgba(0,0,0,0)') + .call(_$color_43.fill, 'rgba(0,0,0,0)'); - var fill = _$d3_7.select(this).select('.legendfill').selectAll('path') - .data(showFill ? [d] : []); - fill.enter().append('path').classed('js-fill', true); - fill.exit().remove(); - fill.attr('d', 'M5,0h30v6h-30z') - .call(_$drawing_68.fillGroupStyle); + var update, + annx0, + anny0; - var line = _$d3_7.select(this).select('.legendlines').selectAll('path') - .data(showLine ? [d] : []); - line.enter().append('path').classed('js-line', true) - .attr('d', 'M5,0h30'); - line.exit().remove(); - line.call(_$drawing_68.lineGroupStyle); - } + // dragger for the arrow & head: translates the whole thing + // (head/tail/text) all together + _$dragelement_65.init({ + element: arrowDrag.node(), + gd: gd, + prepFn: function() { + var pos = _$drawing_68.getTranslate(annTextGroupInner); - function stylePoints(d) { - var d0 = d[0], - trace = d0.trace, - showMarkers = _$subtypes_302.hasMarkers(trace), - showText = _$subtypes_302.hasText(trace), - showLines = _$subtypes_302.hasLines(trace); + annx0 = pos.x; + anny0 = pos.y; + update = {}; + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + }, + moveFn: function(dx, dy) { + var annxy0 = applyTransform(annx0, anny0), + xcenter = annxy0[0] + dx, + ycenter = annxy0[1] + dy; + annTextGroupInner.call(_$drawing_68.setTranslate, xcenter, ycenter); - var dMod, tMod; + update[annbase + '.x'] = xa ? + xa.p2r(xa.r2p(options.x) + dx) : + (options.x + (dx / gs.w)); + update[annbase + '.y'] = ya ? + ya.p2r(ya.r2p(options.y) + dy) : + (options.y - (dy / gs.h)); - // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; - // use d0.trace to infer arrayOk attributes + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } - function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_162.nestedProperty(trace, attrIn).get(), - valToBound = (Array.isArray(valIn) && arrayToValFn) ? - arrayToValFn(valIn) : valIn; + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } - if(bounds) { - if(valToBound < bounds[0]) return bounds[0]; - else if(valToBound > bounds[1]) return bounds[1]; + arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); + annTextGroup.attr({ + transform: 'rotate(' + textangle + ',' + + xcenter + ',' + ycenter + ')' + }); + }, + doneFn: function() { + _$registry_245.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); } - return valToBound; - } - - function pickFirst(array) { return array[0]; } - - // constrain text, markers, etc so they'll fit on the legend - if(showMarkers || showText || showLines) { - var dEdit = {}, - tEdit = {}; + }; - if(showMarkers) { - dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_162.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_162.mean, [2, 16]); - dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_162.mean, [0, 5]); - tEdit.marker = { - sizeref: 1, - sizemin: 1, - sizemode: 'diameter' - }; - } + if(options.showarrow) drawArrow(0, 0); - if(showLines) { - tEdit.line = { - width: boundVal('line.width', pickFirst, [0, 10]) - }; - } + // user dragging the annotation (text, not arrow) + if(editTextPosition) { + var update, + baseTextTransform; - if(showText) { - dEdit.tx = 'Aa'; - dEdit.tp = boundVal('textposition', pickFirst); - dEdit.ts = 10; - dEdit.tc = boundVal('textfont.color', pickFirst); - dEdit.tf = boundVal('textfont.family', pickFirst); - } + // dragger for the textbox: if there's an arrow, just drag the + // textbox and tail, leave the head untouched + _$dragelement_65.init({ + element: annTextGroupInner.node(), + gd: gd, + prepFn: function() { + baseTextTransform = annTextGroup.attr('transform'); + update = {}; + }, + moveFn: function(dx, dy) { + var csr = 'pointer'; + if(options.showarrow) { + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } else { + update[annbase + '.ax'] = options.ax + dx; + } - dMod = [_$lib_162.minExtend(d0, dEdit)]; - tMod = _$lib_162.minExtend(trace, tEdit); - } + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } else { + update[annbase + '.ay'] = options.ay + dy; + } - var ptgroup = _$d3_7.select(this).select('g.legendpoints'); + drawArrow(dx, dy); + } + else if(!subplotId) { + if(xa) { + update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); - var pts = ptgroup.selectAll('path.scatterpts') - .data(showMarkers ? dMod : []); - pts.enter().append('path').classed('scatterpts', true) - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.call(_$drawing_68.pointStyle, tMod, gd); + } else { + var widthFraction = options._xsize / gs.w, + xLeft = options.x + (options._xshift - options.xshift) / gs.w - + widthFraction / 2; - // 'mrc' is set in pointStyle and used in textPointStyle: - // constrain it here - if(showMarkers) dMod[0].mrc = 3; + update[annbase + '.x'] = _$dragelement_65.align(xLeft + dx / gs.w, + widthFraction, 0, 1, options.xanchor); + } - var txt = ptgroup.selectAll('g.pointtext') - .data(showText ? dMod : []); - txt.enter() - .append('g').classed('pointtext', true) - .append('text').attr('transform', 'translate(20,0)'); - txt.exit().remove(); - txt.selectAll('text').call(_$drawing_68.textPointStyle, tMod, gd); - } + if(ya) { + update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); + } else { + var heightFraction = options._ysize / gs.h, + yBottom = options.y - (options._yshift + options.yshift) / gs.h - + heightFraction / 2; - function styleBars(d) { - var trace = d[0].trace, - marker = trace.marker || {}, - markerLine = marker.line || {}, - barpath = _$d3_7.select(this).select('g.legendpoints') - .selectAll('path.legendbar') - .data(_$registry_244.traceIs(trace, 'bar') ? [d] : []); - barpath.enter().append('path').classed('legendbar', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - barpath.exit().remove(); - barpath.each(function(d) { - var p = _$d3_7.select(this), - d0 = d[0], - w = (d0.mlw + 1 || markerLine.width + 1) - 1; + update[annbase + '.y'] = _$dragelement_65.align(yBottom - dy / gs.h, + heightFraction, 0, 1, options.yanchor); + } + if(!xa || !ya) { + csr = _$dragelement_65.getCursor( + xa ? 0.5 : update[annbase + '.x'], + ya ? 0.5 : update[annbase + '.y'], + options.xanchor, options.yanchor + ); + } + } + else return; - p.style('stroke-width', w + 'px') - .call(_$color_43.fill, d0.mc || marker.color); + annTextGroup.attr({ + transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform + }); - if(w) { - p.call(_$color_43.stroke, d0.mlc || markerLine.color); - } - }); + _$setCursor_182(annTextGroupInner, csr); + }, + doneFn: function() { + _$setCursor_182(annTextGroupInner); + _$registry_245.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } } - function styleBoxes(d) { - var trace = d[0].trace, - pts = _$d3_7.select(this).select('g.legendpoints') - .selectAll('path.legendbox') - .data(_$registry_244.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendbox', true) - // if we want the median bar, prepend M6,0H-6 - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.each(function() { - var w = trace.line.width, - p = _$d3_7.select(this); - - p.style('stroke-width', w + 'px') - .call(_$color_43.fill, trace.fillcolor); + if(edits.annotationText) { + annText.call(_$svg_text_utils_184.makeEditable, {delegate: annTextGroupInner, gd: gd}) + .call(textLayout) + .on('edit', function(_text) { + options.text = _text; + this.call(textLayout); - if(w) { - p.call(_$color_43.stroke, trace.line.color); - } - }); - } + var update = {}; + update[annbase + '.text'] = options.text; - function stylePies(d) { - var trace = d[0].trace, - pts = _$d3_7.select(this).select('g.legendpoints') - .selectAll('path.legendpie') - .data(_$registry_244.traceIs(trace, 'pie') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendpie', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } - if(pts.size()) pts.call(_$styleOne_278, d[0], trace); + _$registry_245.call('relayout', gd, update); + }); } -}; + else annText.call(textLayout); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -42790,730 +43184,653 @@ var _$style_104 = function style(s, gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$handleClick_101 = require('./handle_click'); */; +var __draw_29 = _$draw_34.draw; -/* removed: var _$constants_97 = require('./constants'); */; -/* removed: var _$interactions_144 = require('../../constants/interactions'); */; -/* removed: var _$alignment_143 = require('../../constants/alignment'); */; -var __LINE_SPACING_99 = _$alignment_143.LINE_SPACING; -var FROM_TL = _$alignment_143.FROM_TL; -var FROM_BR = _$alignment_143.FROM_BR; -/* removed: var _$getLegendData_100 = require('./get_legend_data'); */; -/* removed: var _$style_104 = require('./style'); */; -/* removed: var _$helpers_102 = require('./helpers'); */; -/* removed: var _$anchor_utils_95 = require('./anchor_utils'); */; +var _$calcAutorange_29 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + annotationList = _$lib_163.filterVisible(fullLayout.annotations); -var DBLCLICKDELAY = _$interactions_144.DBLCLICKDELAY; + if(!annotationList.length || !gd._fullData.length) return; -var _$draw_99 = function draw(gd) { - var fullLayout = gd._fullLayout; - var clipId = 'legend' + fullLayout._uid; + var annotationAxes = {}; + annotationList.forEach(function(ann) { + annotationAxes[ann.xref] = 1; + annotationAxes[ann.yref] = 1; + }); - if(!fullLayout._infolayer || !gd.calcdata) return; + for(var axId in annotationAxes) { + var ax = _$axes_205.getFromId(gd, axId); + if(ax && ax.autorange) { + return _$lib_163.syncOrAsync([ + __draw_29, + annAutorange + ], gd); + } + } +}; - if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; +function annAutorange(gd) { + var fullLayout = gd._fullLayout; - var opts = fullLayout.legend, - legendData = fullLayout.showlegend && _$getLegendData_100(gd.calcdata, opts), - hiddenSlices = fullLayout.hiddenlabels || []; + // find the bounding boxes for each of these annotations' + // relative to their anchor points + // use the arrow and the text bg rectangle, + // as the whole anno may include hidden text in its bbox + _$lib_163.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_205.getFromId(gd, ann.xref), + ya = _$axes_205.getFromId(gd, ann.yref), + headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, + startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - if(!fullLayout.showlegend || !legendData.length) { - fullLayout._infolayer.selectAll('.legend').remove(); - fullLayout._topdefs.select('#' + clipId).remove(); + var headPlus, headMinus, startHeadPlus, startHeadMinus; - _$plots_237.autoMargin(gd, 'legend'); - return; - } + if(xa && xa.autorange) { + headPlus = headSize + ann.xshift; + headMinus = headSize - ann.xshift; + startHeadPlus = startHeadSize + ann.xshift; + startHeadMinus = startHeadSize - ann.xshift; - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); + if(ann.axref === ann.xref) { + // expand for the arrowhead (padded by arrowhead) + _$axes_205.expand(xa, [xa.r2c(ann.x)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + // again for the textbox (padded by textbox) + _$axes_205.expand(xa, [xa.r2c(ann.ax)], { + ppadplus: Math.max(ann._xpadplus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, startHeadMinus) + }); + } + else { + startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; + startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; + _$axes_205.expand(xa, [xa.r2c(ann.x)], { + ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) + }); + } + } - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); + if(ya && ya.autorange) { + headPlus = headSize - ann.yshift; + headMinus = headSize + ann.yshift; + startHeadPlus = startHeadSize - ann.yshift; + startHeadMinus = startHeadSize + ann.yshift; - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); + if(ann.ayref === ann.yref) { + _$axes_205.expand(ya, [ya.r2c(ann.y)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + _$axes_205.expand(ya, [ya.r2c(ann.ay)], { + ppadplus: Math.max(ann._ypadplus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, startHeadMinus) + }); + } + else { + startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; + startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; + _$axes_205.expand(ya, [ya.r2c(ann.y)], { + ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) + }); + } + } + }); +} - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 bg = legend.selectAll('rect.bg') - .data([0]); +'use strict'; - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' - }); +/* removed: var _$registry_245 = require('../../registry'); */; - bg.call(_$color_43.stroke, opts.bordercolor) - .call(_$color_43.fill, opts.bgcolor) - .style('stroke-width', opts.borderwidth + 'px'); +var _$click_30 = { + hasClickToShow: hasClickToShow, + onClick: onClick +}; - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); +/* + * 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), + onSet = toggleSets.on, + offSet = toggleSets.off.concat(toggleSets.explicitOff), + update = {}, + i; - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); + if(!(onSet.length || offSet.length)) return; - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); + for(i = 0; i < onSet.length; i++) { + update['annotations[' + onSet[i] + '].visible'] = true; + } - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', - rx: 20, - ry: 3, - width: 0, - height: 0 - }) - .call(_$color_43.fill, '#808BA4'); + for(i = 0; i < offSet.length; i++) { + update['annotations[' + offSet[i] + '].visible'] = false; + } - var groups = scrollBox.selectAll('g.groups') - .data(legendData); + return _$registry_245.call('update', gd, {}, update); +} - groups.enter().append('g') - .attr('class', 'groups'); +/* + * 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, + onSet = [], + offSet = [], + explicitOffSet = [], + hoverLen = (hoverData || []).length; - groups.exit().remove(); + var i, j, anni, showMode, pointj, xa, ya, toggleType; - var traces = groups.selectAll('g.traces') - .data(_$lib_162.identity); + for(i = 0; i < annotations.length; i++) { + anni = annotations[i]; + showMode = anni.clicktoshow; - traces.enter().append('g').attr('class', 'traces'); - traces.exit().remove(); + if(showMode) { + for(j = 0; j < hoverLen; j++) { + pointj = hoverData[j]; + xa = pointj.xaxis; + ya = pointj.yaxis; - traces.call(_$style_104, gd) - .style('opacity', function(d) { - var trace = d[0].trace; - if(_$registry_244.traceIs(trace, 'pie')) { - return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; - } else { - return trace.visible === 'legendonly' ? 0.5 : 1; + 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; + } } - }) - .each(function() { - _$d3_7.select(this) - .call(drawTexts, gd) - .call(setupTraceToggle, gd); - }); - var firstRender = legend.enter().size() !== 0; - if(firstRender) { - computeLegendDimensions(gd, groups, traces); - expandMargin(gd); + if(j === hoverLen) { + // no match - only turn this annotation OFF, and only if + // showmode is 'onout' + if(anni.visible && showMode === 'onout') offSet.push(i); + } + } } - // Position and size the legend - var lxMin = 0, - lxMax = fullLayout.width, - lyMin = 0, - lyMax = fullLayout.height; - - computeLegendDimensions(gd, groups, traces); + return {on: onSet, off: offSet, explicitOff: explicitOffSet}; +} - if(opts._height > lyMax) { - // If the legend doesn't fit in the plot area, - // do not expand the vertical margins. - expandHorizontalMargin(gd); - } else { - expandMargin(gd); - } +// to handle log axes until v2 +function clickData2r(d, ax) { + return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); +} - // Scroll section must be executed after repositionLegend. - // It requires the legend width, height, x and y to position the scrollbox - // and these values are mutated in repositionLegend. - var gs = fullLayout._size, - lx = gs.l + gs.w * opts.x, - ly = gs.t + gs.h * (1 - opts.y); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(_$anchor_utils_95.isRightAnchor(opts)) { - lx -= opts._width; - } - else if(_$anchor_utils_95.isCenterAnchor(opts)) { - lx -= opts._width / 2; - } - if(_$anchor_utils_95.isBottomAnchor(opts)) { - ly -= opts._height; - } - else if(_$anchor_utils_95.isMiddleAnchor(opts)) { - ly -= opts._height / 2; - } +'use strict'; - // Make sure the legend left and right sides are visible - var legendWidth = opts._width, - legendWidthMax = gs.w; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_186 = require('../../lib/to_log_range'); */; - if(legendWidth > legendWidthMax) { - lx = gs.l; - legendWidth = legendWidthMax; - } - else { - if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; - if(lx < lxMin) lx = lxMin; - legendWidth = Math.min(lxMax - lx, opts._width); - } +/* + * 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. + */ +var _$convertCoords_32 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; - // Make sure the legend top and bottom are visible - // (legends with a scroll bar are not allowed to stretch beyond the extended - // margins) - var legendHeight = opts._height, - legendHeightMax = gs.h; + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); - if(legendHeight > legendHeightMax) { - ly = gs.t; - legendHeight = legendHeightMax; - } - else { - if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; - if(ly < lyMin) ly = lyMin; - legendHeight = Math.min(lyMax - ly, opts._height); - } + if(!(toLog || fromLog)) return; - // Set size and position of all the elements that make up a legend: - // legend, background and border, scroll box and scroll bar - _$drawing_68.setTranslate(legend, lx, ly); + var annotations = gd._fullLayout.annotations, + axLetter = ax._id.charAt(0), + ann, + attrPrefix; - // to be safe, remove previous listeners - scrollBar.on('.drag', null); - legend.on('wheel', null); + function convert(attr) { + var currentVal = ann[attr], + newVal = null; - if(opts._height <= legendHeight || gd._context.staticPlot) { - // if scrollbar should not be shown. - bg.attr({ - width: legendWidth - opts.borderwidth, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); + if(toLog) newVal = _$toLogRange_186(currentVal, ax.range); + else newVal = Math.pow(10, currentVal); - _$drawing_68.setTranslate(scrollBox, 0, 0); + // if conversion failed, delete the value so it gets a default value + if(!_$fastIsnumeric_10(newVal)) newVal = null; - clipPath.select('rect').attr({ - width: legendWidth - 2 * opts.borderwidth, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth - }); + doExtra(attrPrefix + attr, newVal); + } - _$drawing_68.setClipUrl(scrollBox, clipId); + for(var i = 0; i < annotations.length; i++) { + ann = annotations[i]; + attrPrefix = 'annotations[' + i + '].'; - _$drawing_68.setRect(scrollBar, 0, 0, 0, 0); - delete opts._scrollY; + if(ann[axLetter + 'ref'] === ax._id) convert(axLetter); + if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter); } - else { - var scrollBarHeight = Math.max(_$constants_97.scrollBarMinHeight, - legendHeight * legendHeight / opts._height); - var scrollBarYMax = legendHeight - - scrollBarHeight - - 2 * _$constants_97.scrollBarMargin; - var scrollBoxYMax = opts._height - legendHeight; - var scrollRatio = scrollBarYMax / scrollBoxYMax; +}; - var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // increase the background and clip-path width - // by the scrollbar width and margin - bg.attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_97.scrollBarWidth + - _$constants_97.scrollBarMargin, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); +'use strict'; - clipPath.select('rect').attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_97.scrollBarWidth + - _$constants_97.scrollBarMargin, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth + scrollBoxY - }); +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$color_43 = require('../color'); */; - _$drawing_68.setClipUrl(scrollBox, clipId); +// defaults common to 'annotations' and 'annotations3d' +var _$handleAnnotationCommonDefaults_31 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { + coerce('opacity'); + var bgColor = coerce('bgcolor'); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + var borderColor = coerce('bordercolor'); + var borderOpacity = _$color_43.opacity(borderColor); - legend.on('wheel', function() { - scrollBoxY = _$lib_162.constrain( - opts._scrollY + - _$d3_7.event.deltaY / scrollBarYMax * scrollBoxYMax, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - _$d3_7.event.preventDefault(); - } - }); + coerce('borderpad'); - var eventY0, scrollBoxY0; + var borderWidth = coerce('borderwidth'); + var showArrow = coerce('showarrow'); - var drag = _$d3_7.behavior.drag() - .on('dragstart', function() { - eventY0 = _$d3_7.event.sourceEvent.clientY; - scrollBoxY0 = scrollBoxY; - }) - .on('drag', function() { - var e = _$d3_7.event.sourceEvent; - if(e.buttons === 2 || e.ctrlKey) return; + coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); + coerce('textangle'); + _$lib_163.coerceFont(coerce, 'font', fullLayout.font); - scrollBoxY = _$lib_162.constrain( - (e.clientY - eventY0) / scrollRatio + scrollBoxY0, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - }); + 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_43.defaultLine); + coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); + coerce('standoff'); + coerce('startstandoff'); - scrollBar.call(drag); } + var hoverText = coerce('hovertext'); + var globalHoverLabel = fullLayout.hoverlabel || {}; - function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { - opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; - _$drawing_68.setTranslate(scrollBox, 0, -scrollBoxY); + if(hoverText) { + var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || + (_$color_43.opacity(bgColor) ? _$color_43.rgb(bgColor) : _$color_43.defaultLine) + ); - _$drawing_68.setRect( - scrollBar, - legendWidth, - _$constants_97.scrollBarMargin + scrollBoxY * scrollRatio, - _$constants_97.scrollBarWidth, - scrollBarHeight + var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || + _$color_43.contrast(hoverBG) ); - clipPath.select('rect').attr({ - y: opts.borderwidth + scrollBoxY + + _$lib_163.coerceFont(coerce, 'hoverlabel.font', { + family: globalHoverLabel.font.family, + size: globalHoverLabel.font.size, + color: globalHoverLabel.font.color || hoverBorder }); } - if(gd._context.edits.legendPosition) { - var xf, yf, x0, y0; + coerce('captureevents', !!hoverText); +}; - legend.classed('cursor-move', true); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - _$dragelement_65.init({ - element: legend.node(), - gd: gd, - prepFn: function() { - var transform = _$drawing_68.getTranslate(legend); - x0 = transform.x; - y0 = transform.y; - }, - moveFn: function(dx, dy) { - var newX = x0 + dx, - newY = y0 + dy; +'use strict'; - _$drawing_68.setTranslate(legend, newX, newY); +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleAnnotationCommonDefaults_31 = require('./common_defaults'); */; +/* removed: var _$attributes_28 = require('./attributes'); */; - xf = _$dragelement_65.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); - yf = _$dragelement_65.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); - }, - doneFn: function() { - if(xf !== undefined && yf !== undefined) { - _$registry_244.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); - } - }, - clickFn: function(numClicks, e) { - var clickedTrace = - fullLayout._infolayer.selectAll('g.traces').filter(function() { - var bbox = this.getBoundingClientRect(); - return (e.clientX >= bbox.left && e.clientX <= bbox.right && - e.clientY >= bbox.top && e.clientY <= bbox.bottom); - }); - if(clickedTrace.size() > 0) { - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { - _$handleClick_101(clickedTrace, gd, numClicks); - }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - _$handleClick_101(clickedTrace, gd, numClicks); - } - } - } - }); - } -}; - -function drawTexts(g, gd) { - var legendItem = g.data()[0][0], - fullLayout = gd._fullLayout, - trace = legendItem.trace, - isPie = _$registry_244.traceIs(trace, 'pie'), - traceIndex = trace.index, - name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); - - text.attr('text-anchor', 'start') - .classed('user-select-none', true) - .call(_$drawing_68.font, fullLayout.legend.font) - .text(name); +var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; - function textLayout(s) { - _$svg_text_utils_183.convertToTspans(s, gd, function() { - computeTextDimensions(g, gd); - }); + function coerce(attr, dflt) { + return _$lib_163.coerce(annIn, annOut, _$attributes_28, attr, dflt); } - if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_183.makeEditable, {gd: gd}) - .call(textLayout) - .on('edit', function(text) { - this.text(text) - .call(textLayout); - - var origText = text; - - if(!this.text()) text = ' \u0020\u0020 '; - - var transforms, direction; - var fullInput = legendItem.trace._fullInput || {}; - var update = {}; - - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_244.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_244.getTransformIndices(fullInput, 'groupby'); - var index = groupbyIndices[groupbyIndices.length - 1]; - - var kcont = _$lib_162.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); - - if(origText === '') { - kcont.remove(legendItem.trace._group); - } else { - kcont.set(legendItem.trace._group, text); - } - - update = kcont.constructUpdate(); - } else { - update.name = text; - } + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + var clickToShow = coerce('clicktoshow'); - return _$registry_244.call('restyle', gd, update, traceIndex); - }); - } else { - textLayout(text); - } -} + if(!(visible || clickToShow)) return annOut; -function setupTraceToggle(g, gd) { - var newMouseDownTime, - numClicks = 1; + _$handleAnnotationCommonDefaults_31(annIn, annOut, fullLayout, coerce); - var traceToggle = g.selectAll('rect') - .data([0]); + var showArrow = annOut.showarrow; - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_43.fill, 'rgba(0,0,0,0)'); + // positioning + var axLetters = ['x', 'y'], + arrowPosDflt = [-10, -30], + gdMock = {_fullLayout: fullLayout}; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i]; + // xref, yref + var axRef = _$axes_205.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); - traceToggle.on('mousedown', function() { - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { - // 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; + // x, y + _$axes_205.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); - if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } + if(showArrow) { + var arrowPosAttr = 'a' + axLetter, + // axref, ayref + aaxRef = _$axes_205.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { _$handleClick_101(g, gd, numClicks); }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); + // for now the arrow can only be on the same axis or specified as pixels + // TODO: sometime it might be interesting to allow it to be on *any* axis + // but that would require updates to drawing & autorange code and maybe more + if(aaxRef !== 'pixel' && aaxRef !== axRef) { + aaxRef = annOut[arrowPosAttr] = 'pixel'; } - gd._legendMouseDownTime = 0; - _$handleClick_101(g, gd, numClicks); + + // ax, ay + var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; + _$axes_205.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } - }); -} -function computeTextDimensions(g, gd) { - var legendItem = g.data()[0][0]; + // xanchor, yanchor + coerce(axLetter + 'anchor'); - if(!legendItem.trace.showlegend) { - g.remove(); - return; + // xshift, yshift + coerce(axLetter + 'shift'); } - var mathjaxGroup = g.select('g[class*=math-group]'); - var mathjaxNode = mathjaxGroup.node(); - var opts = gd._fullLayout.legend; - var lineHeight = opts.font.size * __LINE_SPACING_99; - var height, width; - - if(mathjaxNode) { - var mathjaxBB = _$drawing_68.bBox(mathjaxNode); - - height = mathjaxBB.height; - width = mathjaxBB.width; + // if you have one coordinate you should have both + _$lib_163.noneOrAll(annIn, annOut, ['x', 'y']); - _$drawing_68.setTranslate(mathjaxGroup, 0, (height / 4)); + // if you have one part of arrow length you should have both + if(showArrow) { + _$lib_163.noneOrAll(annIn, annOut, ['ax', 'ay']); } - else { - var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_183.lineCount(text); - var textNode = text.node(); - height = lineHeight * textLines; - width = textNode ? _$drawing_68.bBox(textNode).width : 0; + if(clickToShow) { + var xClick = coerce('xclick'); + var yClick = coerce('yclick'); - // approximation to height offset to center the font - // to avoid getBoundingClientRect - var textY = lineHeight * (0.3 + (1 - textLines) / 2); - // TODO: this 40 should go in a constants file (along with other - // values related to the legend symbol size) - _$svg_text_utils_183.positionText(text, 40, textY); + // put the actual click data to bind to into private attributes + // so we don't have to do this little bit of logic on every hover event + annOut._xclick = (xClick === undefined) ? + annOut.x : + _$axes_205.cleanPosition(xClick, gdMock, annOut.xref); + annOut._yclick = (yClick === undefined) ? + annOut.y : + _$axes_205.cleanPosition(yClick, gdMock, annOut.yref); } - height = Math.max(height, 16) + 3; - - legendItem.height = height; - legendItem.width = width; -} - -function computeLegendDimensions(gd, groups, traces) { - var fullLayout = gd._fullLayout; - var opts = fullLayout.legend; - var borderwidth = opts.borderwidth; - var isGrouped = _$helpers_102.isGrouped(opts); + return annOut; +}; - var extraWidth = 0; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - opts._width = 0; - opts._height = 0; +'use strict'; - if(_$helpers_102.isVertical(opts)) { - if(isGrouped) { - groups.each(function(d, i) { - _$drawing_68.setTranslate(this, 0, i * opts.tracegroupgap); - }); - } +/* removed: var _$lib_163 = require('../lib'); */; - traces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height, - textWidth = legendItem.width; +/** Convenience wrapper for making array container logic DRY and consistent + * + * @param {object} parentObjIn + * user input object where the container in question is linked + * (i.e. either a user trace object or the user layout object) + * + * @param {object} parentObjOut + * full object where the coerced container will be linked + * (i.e. either a full trace object or the full layout object) + * + * @param {object} opts + * options object: + * - name {string} + * name of the key linking the container in question + * - handleItemDefaults {function} + * defaults method to be called on each item in the array container in question + * + * Its arguments are: + * - itemIn {object} item in user layout + * - itemOut {object} item in full layout + * - parentObj {object} (as in closure) + * - opts {object} (as in closure) + * - itemOpts {object} + * - itemIsNotPlainObject {boolean} + * N.B. + * + * - opts is passed to handleItemDefaults so it can also store + * links to supplementary data (e.g. fullData for layout components) + * + */ +var _$handleArrayContainerDefaults_201 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { + var name = opts.name; - _$drawing_68.setTranslate(this, - borderwidth, - (5 + borderwidth + opts._height + textHeight / 2)); + var previousContOut = parentObjOut[name]; - opts._height += textHeight; - opts._width = Math.max(opts._width, textWidth); - }); + var contIn = _$lib_163.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + contOut = parentObjOut[name] = [], + i; - opts._width += 45 + borderwidth * 2; - opts._height += 10 + borderwidth * 2; + for(i = 0; i < contIn.length; i++) { + var itemIn = contIn[i], + itemOut = {}, + itemOpts = {}; - if(isGrouped) { - opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; + if(!_$lib_163.isPlainObject(itemIn)) { + itemOpts.itemIsNotPlainObject = true; + itemIn = {}; } - extraWidth = 40; - } - else if(isGrouped) { - var groupXOffsets = [opts._width], - groupData = groups.data(); - - for(var i = 0, n = groupData.length; i < n; i++) { - var textWidths = groupData[i].map(function(legendItemArray) { - return legendItemArray[0].width; - }); + opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); - var groupWidth = 40 + Math.max.apply(null, textWidths); + itemOut._input = itemIn; + itemOut._index = i; - opts._width += opts.tracegroupgap + groupWidth; + contOut.push(itemOut); + } - groupXOffsets.push(opts._width); + // in case this array gets its defaults rebuilt independent of the whole layout, + // relink the private keys just for this array. + if(_$lib_163.isArrayOrTypedArray(previousContOut)) { + var len = Math.min(previousContOut.length, contOut.length); + for(i = 0; i < len; i++) { + _$lib_163.relinkPrivateKeys(contOut[i], previousContOut[i]); } - - groups.each(function(d, i) { - _$drawing_68.setTranslate(this, groupXOffsets[i], 0); - }); - - groups.each(function() { - var group = _$d3_7.select(this), - groupTraces = group.selectAll('g.traces'), - groupHeight = 0; - - groupTraces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height; - - _$drawing_68.setTranslate(this, - 0, - (5 + borderwidth + groupHeight + textHeight / 2)); - - groupHeight += textHeight; - }); - - opts._height = Math.max(opts._height, groupHeight); - }); - - opts._height += 10 + borderwidth * 2; - opts._width += borderwidth * 2; } - else { - var rowHeight = 0, - maxTraceHeight = 0, - maxTraceWidth = 0, - offsetX = 0, - fullTracesWidth = 0, - traceGap = opts.tracegroupgap || 5, - oneRowLegend; +}; - // calculate largest width for traces and use for width of all legend items - traces.each(function(d) { - maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); - fullTracesWidth += 40 + d[0].width + traceGap; - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // check if legend fits in one row - oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; - traces.each(function(d) { - var legendItem = d[0], - traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; - if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { - offsetX = 0; - rowHeight = rowHeight + maxTraceHeight; - opts._height = opts._height + maxTraceHeight; - // reset for next row - maxTraceHeight = 0; - } +'use strict'; - _$drawing_68.setTranslate(this, - (borderwidth + offsetX), - (5 + borderwidth + legendItem.height / 2) + rowHeight); +/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationDefaults_26 = require('./annotation_defaults'); */; - opts._width += traceGap + traceWidth; - opts._height = Math.max(opts._height, legendItem.height); - // keep track of tallest trace in group - offsetX += traceGap + traceWidth; - maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); - }); +var _$supplyLayoutDefaults_33 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'annotations', + handleItemDefaults: _$handleAnnotationDefaults_26 + }; - opts._width += borderwidth * 2; - opts._height += 10 + borderwidth * 2; + _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); +}; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // make sure we're only getting full pixels - opts._width = Math.ceil(opts._width); - opts._height = Math.ceil(opts._height); - traces.each(function(d) { - var legendItem = d[0], - bg = _$d3_7.select(this).select('.legendtoggle'); +'use strict'; - _$drawing_68.setRect(bg, - 0, - -legendItem.height / 2, - (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, - legendItem.height - ); - }); -} +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; -function expandMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; +/** + * 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 + */ +var _$makeIncludeComponents_215 = function makeIncludeComponents(containerArrayName) { + return function includeComponents(layoutIn, layoutOut) { + var array = layoutIn[containerArrayName]; + if(!Array.isArray(array)) return; - var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_95.isCenterAnchor(opts)) { - xanchor = 'center'; - } + var Cartesian = _$registry_245.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'); - var yanchor = 'top'; - if(_$anchor_utils_95.isBottomAnchor(opts)) { - yanchor = 'bottom'; - } - else if(_$anchor_utils_95.isMiddleAnchor(opts)) { - yanchor = 'middle'; - } + for(var i = 0; i < array.length; i++) { + var itemi = array[i]; + if(!_$lib_163.isPlainObject(itemi)) continue; - // lastly check if the margin auto-expand has changed - _$plots_237.autoMargin(gd, 'legend', { - x: opts.x, - y: opts.y, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: opts._height * (FROM_BR[yanchor]), - t: opts._height * (FROM_TL[yanchor]) - }); -} + var xref = itemi.xref; + var yref = itemi.yref; -function expandHorizontalMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; + var hasXref = idRegex.x.test(xref); + var hasYref = idRegex.y.test(yref); + if(hasXref || hasYref) { + if(!hasCartesianOrGL2D) _$lib_163.pushUnique(layoutOut._basePlotModules, Cartesian); - var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_95.isCenterAnchor(opts)) { - xanchor = 'center'; - } + 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; + } - // lastly check if the margin auto-expand has changed - _$plots_237.autoMargin(gd, 'legend', { - x: opts.x, - y: 0.5, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: 0, - t: 0 - }); -} + /* + * 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); + } + } + } + }; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -43526,16 +43843,26 @@ function expandHorizontalMargin(gd) { 'use strict'; +/* removed: var _$draw_34 = require('./draw'); */; +/* removed: var _$click_30 = require('./click'); */; -var _$legend_103 = { +var _$annotations_36 = { moduleType: 'component', - name: 'legend', + name: 'annotations', - layoutAttributes: _$attributes_96, - supplyLayoutDefaults: _$legendDefaults_98, + layoutAttributes: _$attributes_28, + supplyLayoutDefaults: _$supplyLayoutDefaults_33, + includeBasePlot: _$makeIncludeComponents_215('annotations'), - draw: _$draw_99, - style: _$style_104 + calcAutorange: _$calcAutorange_29, + draw: _$draw_34.draw, + drawOne: _$draw_34.drawOne, + drawRaw: _$draw_34.drawRaw, + + hasClickToShow: _$click_30.hasClickToShow, + onClick: _$click_30.onClick, + + convertCoords: _$convertCoords_32 }; /** @@ -43546,142 +43873,85 @@ var _$legend_103 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; +/* removed: var _$attributes_28 = require('../annotations/attributes'); */; +var __overrideAll_37 = _$edit_types_190.overrideAll; -var _$button_attributes_110 = { - step: { - valType: 'enumerated', +var _$attributes_37 = __overrideAll_37({ + _isLinkedToArray: 'annotation', + + visible: _$attributes_28.visible, + x: { + valType: 'any', - values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], - dflt: 'month', - editType: 'plot', }, - stepmode: { - valType: 'enumerated', + y: { + valType: 'any', - values: ['backward', 'todate'], - dflt: 'backward', - editType: 'plot', - - }, - count: { - valType: 'number', - - min: 0, - dflt: 1, - editType: 'plot', - - }, - label: { - valType: 'string', - - editType: 'plot', }, - editType: 'plot' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_42 = require('../color/attributes'); */; -var __extendFlat_109 = _$extend_156.extendFlat; -/* removed: var _$button_attributes_110 = require('./button_attributes'); */; - -_$button_attributes_110 = __extendFlat_109(_$button_attributes_110, { - _isLinkedToArray: 'button', - - -}); - -var _$attributes_109 = { - visible: { - valType: 'boolean', + z: { + valType: 'any', - editType: 'plot', }, - - buttons: _$button_attributes_110, - - x: { + ax: { valType: 'number', - min: -2, - max: 3, - - editType: 'plot', - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - editType: 'plot', }, - y: { + ay: { valType: 'number', - min: -2, - max: 3, - editType: 'plot', - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'bottom', - - editType: 'plot', }, - font: _$font_attributes_231({ - editType: 'plot', - - }), + xanchor: _$attributes_28.xanchor, + xshift: _$attributes_28.xshift, + yanchor: _$attributes_28.yanchor, + yshift: _$attributes_28.yshift, - bgcolor: { - valType: 'color', - dflt: _$attributes_42.lightLine, - - editType: 'plot', - - }, - activecolor: { - valType: 'color', - - editType: 'plot', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_42.defaultLine, - - editType: 'plot', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'plot', - - }, - editType: 'plot' -}; + text: _$attributes_28.text, + textangle: _$attributes_28.textangle, + font: _$attributes_28.font, + width: _$attributes_28.width, + height: _$attributes_28.height, + opacity: _$attributes_28.opacity, + align: _$attributes_28.align, + valign: _$attributes_28.valign, + bgcolor: _$attributes_28.bgcolor, + bordercolor: _$attributes_28.bordercolor, + borderpad: _$attributes_28.borderpad, + borderwidth: _$attributes_28.borderwidth, + showarrow: _$attributes_28.showarrow, + arrowcolor: _$attributes_28.arrowcolor, + arrowhead: _$attributes_28.arrowhead, + startarrowhead: _$attributes_28.startarrowhead, + arrowside: _$attributes_28.arrowside, + arrowsize: _$attributes_28.arrowsize, + startarrowsize: _$attributes_28.startarrowsize, + arrowwidth: _$attributes_28.arrowwidth, + standoff: _$attributes_28.standoff, + startstandoff: _$attributes_28.startstandoff, + hovertext: _$attributes_28.hovertext, + hoverlabel: _$attributes_28.hoverlabel, + captureevents: _$attributes_28.captureevents, + + // maybes later? + // clicktoshow: annAtts.clicktoshow, + // xclick: annAtts.xclick, + // yclick: annAtts.yclick, + + // not needed! + // axref: 'pixel' + // ayref: 'pixel' + // xref: 'x' + // yref: 'y + // zref: 'z' +}, 'calc', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -43693,23 +43963,59 @@ var _$attributes_109 = { 'use strict'; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -var _$constants_111 = { +var _$convert_38 = function convert(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var anns = fullSceneLayout.annotations; - // 'y' position pad above counter axis domain - yPad: 0.02, + for(var i = 0; i < anns.length; i++) { + mockAnnAxes(anns[i], scene); + } - // minimum button width (regardless of text size) - minButtonWidth: 30, + scene.fullLayout._infolayer + .selectAll('.annotation-' + scene.id) + .remove(); +}; - // buttons rect radii - rx: 3, - ry: 3, +function mockAnnAxes(ann, scene) { + var fullSceneLayout = scene.fullSceneLayout; + var domain = fullSceneLayout.domain; + var size = scene.fullLayout._size; - // light fraction used to compute the 'activecolor' default - lightAmount: 25, - darkAmount: 10 -}; + var base = { + // this gets fill in on render + pdata: null, + + // to get setConvert to not execute cleanly + type: 'linear', + + // don't try to update them on `editable: true` + autorange: false, + + // set infinite range so that annotation draw routine + // does not try to remove 'outside-range' annotations, + // this case is handled in the render loop + range: [-Infinity, Infinity] + }; + + ann._xa = {}; + _$lib_163.extendFlat(ann._xa, base); + _$axes_205.setConvert(ann._xa); + ann._xa._offset = size.l + domain.x[0] * size.w; + ann._xa.l2p = function() { + return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); + }; + + ann._ya = {}; + _$lib_163.extendFlat(ann._ya, base); + _$axes_205.setConvert(ann._ya); + ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; + ann._ya.l2p = function() { + return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); + }; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -43721,92 +44027,71 @@ var _$constants_111 = { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$color_43 = require('../color'); */; - -/* removed: var _$attributes_109 = require('./attributes'); */; -/* removed: var _$button_attributes_110 = require('./button_attributes'); */; -/* removed: var _$constants_111 = require('./constants'); */; - +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationCommonDefaults_31 = require('../annotations/common_defaults'); */; +/* removed: var _$attributes_37 = require('./attributes'); */; -var _$handleDefaults_112 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { - var selectorIn = containerIn.rangeselector || {}, - selectorOut = containerOut.rangeselector = {}; +var _$handleDefaults_39 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + _$handleArrayContainerDefaults_201(sceneLayoutIn, sceneLayoutOut, { + name: 'annotations', + handleItemDefaults: __handleAnnotationDefaults_39, + fullLayout: opts.fullLayout + }); +}; +function __handleAnnotationDefaults_39(annIn, annOut, sceneLayout, opts, itemOpts) { function coerce(attr, dflt) { - return _$lib_162.coerce(selectorIn, selectorOut, _$attributes_109, attr, dflt); + return _$lib_163.coerce(annIn, annOut, _$attributes_37, attr, dflt); } - var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - - var posDflt = getPosDflt(containerOut, layout, counterAxes); - coerce('x', posDflt[0]); - coerce('y', posDflt[1]); - _$lib_162.noneOrAll(containerIn, containerOut, ['x', 'y']); - - coerce('xanchor'); - coerce('yanchor'); - - _$lib_162.coerceFont(coerce, 'font', layout.font); - - var bgColor = coerce('bgcolor'); - coerce('activecolor', _$color_43.contrast(bgColor, _$constants_111.lightAmount, _$constants_111.darkAmount)); - coerce('bordercolor'); - coerce('borderwidth'); -}; - -function buttonsDefaults(containerIn, containerOut, calendar) { - var buttonsIn = containerIn.buttons || [], - buttonsOut = containerOut.buttons = []; + function coercePosition(axLetter) { + var axName = axLetter + 'axis'; - var buttonIn, buttonOut; + // mock in such way that getFromId grabs correct 3D axis + var gdMock = { _fullLayout: {} }; + gdMock._fullLayout[axName] = sceneLayout[axName]; - function coerce(attr, dflt) { - return _$lib_162.coerce(buttonIn, buttonOut, _$button_attributes_110, attr, dflt); + return _$axes_205.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; - if(!_$lib_162.isPlainObject(buttonIn)) continue; + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + if(!visible) return annOut; - var step = coerce('step'); - if(step !== 'all') { - if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { - buttonOut.stepmode = 'backward'; - } - else { - coerce('stepmode'); - } + _$handleAnnotationCommonDefaults_31(annIn, annOut, opts.fullLayout, coerce); - coerce('count'); - } + coercePosition('x'); + coercePosition('y'); + coercePosition('z'); - coerce('label'); + // if you have one coordinate you should all three + _$lib_163.noneOrAll(annIn, annOut, ['x', 'y', 'z']); - buttonOut._index = i; - buttonsOut.push(buttonOut); - } + // hard-set here for completeness + annOut.xref = 'x'; + annOut.yref = 'y'; + annOut.zref = 'z'; - return buttonsOut; -} + coerce('xanchor'); + coerce('yanchor'); + coerce('xshift'); + coerce('yshift'); -function getPosDflt(containerOut, layout, counterAxes) { - var anchoredList = counterAxes.filter(function(ax) { - return layout[ax].anchor === containerOut._id; - }); + if(annOut.showarrow) { + annOut.axref = 'pixel'; + annOut.ayref = 'pixel'; - var posY = 0; - for(var i = 0; i < anchoredList.length; i++) { - var domain = layout[anchoredList[i]].domain; - if(domain) posY = Math.max(domain[1], posY); + // TODO maybe default values should be bigger than the 2D case? + coerce('ax', -10); + coerce('ay', -30); + + // if you have one part of arrow length you should have both + _$lib_163.noneOrAll(annIn, annOut, ['ax', 'ay']); } - return [containerOut.domain[0], posY + _$constants_111.yPad]; + return annOut; } /** @@ -43820,51 +44105,28 @@ function getPosDflt(containerOut, layout, counterAxes) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; - -var _$getUpdateObject_114 = function getUpdateObject(axisLayout, buttonLayout) { - var axName = axisLayout._name; - var update = {}; - - if(buttonLayout.step === 'all') { - update[axName + '.autorange'] = true; - } - else { - var xrange = getXRange(axisLayout, buttonLayout); - - update[axName + '.range[0]'] = xrange[0]; - update[axName + '.range[1]'] = xrange[1]; - } - - return update; -}; - -function getXRange(axisLayout, buttonLayout) { - var currentRange = axisLayout.range; - var base = new Date(axisLayout.r2l(currentRange[1])); - - var step = buttonLayout.step, - count = buttonLayout.count; - - var range0; - - switch(buttonLayout.stepmode) { - case 'backward': - range0 = axisLayout.l2r(+_$d3_7.time[step].utc.offset(base, -count)); - break; - - case 'todate': - var base2 = _$d3_7.time[step].utc.offset(base, -count); +function xformMatrix(m, v) { + var out = [0, 0, 0, 0]; + var i, j; - range0 = axisLayout.l2r(+_$d3_7.time[step].utc.ceil(base2)); - break; + for(i = 0; i < 4; ++i) { + for(j = 0; j < 4; ++j) { + out[j] += m[4 * i + j] * v[i]; + } } - var range1 = currentRange[1]; + return out; +} - return [range0, range1]; +function project(camera, v) { + var p = xformMatrix(camera.projection, + xformMatrix(camera.view, + xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); + return p; } +var _$project_234 = project; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -43875,356 +44137,206 @@ function getXRange(axisLayout, buttonLayout) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; - -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_207 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; - -/* removed: var _$alignment_143 = require('../../constants/alignment'); */; -var __LINE_SPACING_113 = _$alignment_143.LINE_SPACING; -var __FROM_TL_113 = _$alignment_143.FROM_TL; -var __FROM_BR_113 = _$alignment_143.FROM_BR; - -/* removed: var _$constants_111 = require('./constants'); */; -/* removed: var _$getUpdateObject_114 = require('./get_update_object'); */; - - -var _$draw_113 = function draw(gd) { - var fullLayout = gd._fullLayout; - - var selectors = fullLayout._infolayer.selectAll('.rangeselector') - .data(makeSelectorData(gd), selectorKeyFunc); - - selectors.enter().append('g') - .classed('rangeselector', true); - - selectors.exit().remove(); - - selectors.style({ - cursor: 'pointer', - 'pointer-events': 'all' - }); +var __drawRaw_40 = _$draw_34.drawRaw; +/* removed: var _$project_234 = require('../../plots/gl3d/project'); */; +var axLetters = ['x', 'y', 'z']; - selectors.each(function(d) { - var selector = _$d3_7.select(this), - axisLayout = d, - selectorLayout = axisLayout.rangeselector; +var _$draw_40 = function draw(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var dataScale = scene.dataScale; + var anns = fullSceneLayout.annotations; - var buttons = selector.selectAll('g.button') - .data(selectorLayout.buttons); + for(var i = 0; i < anns.length; i++) { + var ann = anns[i]; + var annotationIsOffscreen = false; - buttons.enter().append('g') - .classed('button', true); + for(var j = 0; j < 3; j++) { + var axLetter = axLetters[j]; + var pos = ann[axLetter]; + var ax = fullSceneLayout[axLetter + 'axis']; + var posFraction = ax.r2fraction(pos); - buttons.exit().remove(); + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + break; + } + } - buttons.each(function(d) { - var button = _$d3_7.select(this); - var update = _$getUpdateObject_114(axisLayout, d); + if(annotationIsOffscreen) { + scene.fullLayout._infolayer + .select('.annotation-' + scene.id + '[data-index="' + i + '"]') + .remove(); + } else { + ann._pdata = _$project_234(scene.glplot.cameraParams, [ + fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], + fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], + fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] + ]); - d._isActive = isActive(axisLayout, d, update); + __drawRaw_40(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + } + } +}; - button.call(drawButtonRect, selectorLayout, d); - button.call(drawButtonText, selectorLayout, d, gd); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - button.on('click', function() { - if(gd._dragged) return; +'use strict'; - _$registry_244.call('relayout', gd, update); - }); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; - button.on('mouseover', function() { - d._isHovered = true; - button.call(drawButtonRect, selectorLayout, d); - }); +var _$annotations3d_41 = { + moduleType: 'component', + name: 'annotations3d', - button.on('mouseout', function() { - d._isHovered = false; - button.call(drawButtonRect, selectorLayout, d); - }); - }); + schema: { + subplots: { + scene: {annotations: _$attributes_37} + } + }, - reposition(gd, buttons, selectorLayout, axisLayout._name, selector); - }); + layoutAttributes: _$attributes_37, + handleDefaults: _$handleDefaults_39, + includeBasePlot: includeGL3D, + convert: _$convert_38, + draw: _$draw_40 }; -function makeSelectorData(gd) { - var axes = _$axis_ids_207.list(gd, 'x', true); - var data = []; +function includeGL3D(layoutIn, layoutOut) { + var GL3D = _$registry_245.subplotsRegistry.gl3d; + if(!GL3D) return; - for(var i = 0; i < axes.length; i++) { - var axis = axes[i]; + var attrRegex = GL3D.attrRegex; - if(axis.rangeselector && axis.rangeselector.visible) { - data.push(axis); + var keys = Object.keys(layoutIn); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { + _$lib_163.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_163.pushUnique(layoutOut._subplots.gl3d, k); } } - - return data; } -function selectorKeyFunc(d) { - return d._id; -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function isActive(axisLayout, opts, update) { - if(opts.step === 'all') { - return axisLayout.autorange === true; - } - else { - var keys = Object.keys(update); +'use strict'; - return ( - axisLayout.range[0] === update[keys[0]] && - axisLayout.range[1] === update[keys[1]] - ); - } -} -function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - - rect.attr('shape-rendering', 'crispEdges'); - - rect.attr({ - 'rx': _$constants_111.rx, - 'ry': _$constants_111.ry - }); - - rect.call(_$color_43.stroke, selectorLayout.bordercolor) - .call(_$color_43.fill, getFillColor(selectorLayout, d)) - .style('stroke-width', selectorLayout.borderwidth + 'px'); -} - -function getFillColor(selectorLayout, d) { - return (d._isActive || d._isHovered) ? - selectorLayout.activecolor : - selectorLayout.bgcolor; -} - -function drawButtonText(button, selectorLayout, d, gd) { - function textLayout(s) { - _$svg_text_utils_183.convertToTspans(s, gd); - } - - var text = button.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - - text.attr('text-anchor', 'middle'); - - text.call(_$drawing_68.font, selectorLayout.font) - .text(getLabel(d)) - .call(textLayout); -} - -function getLabel(opts) { - if(opts.label) return opts.label; - - if(opts.step === 'all') return 'all'; - - return opts.count + opts.step.charAt(0); -} - -function reposition(gd, buttons, opts, axName, selector) { - var width = 0; - var height = 0; - - var borderWidth = opts.borderwidth; - - buttons.each(function() { - var button = _$d3_7.select(this); - var text = button.select('.selector-text'); - - var tHeight = opts.font.size * __LINE_SPACING_113; - var hEff = Math.max(tHeight * _$svg_text_utils_183.lineCount(text), 16) + 3; - - height = Math.max(height, hEff); - }); - - buttons.each(function() { - var button = _$d3_7.select(this); - var rect = button.select('.selector-rect'); - var text = button.select('.selector-text'); - - var tWidth = text.node() && _$drawing_68.bBox(text.node()).width; - var tHeight = opts.font.size * __LINE_SPACING_113; - var tLines = _$svg_text_utils_183.lineCount(text); - - var wEff = Math.max(tWidth + 10, _$constants_111.minButtonWidth); - - // TODO add MathJax support - - // TODO add buttongap attribute - - button.attr('transform', 'translate(' + - (borderWidth + width) + ',' + borderWidth + - ')'); - - rect.attr({ - x: 0, - y: 0, - width: wEff, - height: height - }); - - _$svg_text_utils_183.positionText(text, wEff / 2, - height / 2 - ((tLines - 1) * tHeight / 2) + 3); - - width += wEff + 5; - }); - - var graphSize = gd._fullLayout._size; - var lx = graphSize.l + graphSize.w * opts.x; - var ly = graphSize.t + graphSize.h * (1 - opts.y); - - var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(opts)) { - lx -= width; - xanchor = 'right'; - } - if(_$anchor_utils_95.isCenterAnchor(opts)) { - lx -= width / 2; - xanchor = 'center'; - } - - var yanchor = 'top'; - if(_$anchor_utils_95.isBottomAnchor(opts)) { - ly -= height; - yanchor = 'bottom'; - } - if(_$anchor_utils_95.isMiddleAnchor(opts)) { - ly -= height / 2; - yanchor = 'middle'; - } - - width = Math.ceil(width); - height = Math.ceil(height); - lx = Math.round(lx); - ly = Math.round(ly); - - _$plots_237.autoMargin(gd, axName + '-range-selector', { - x: opts.x, - y: opts.y, - l: width * __FROM_TL_113[xanchor], - r: width * __FROM_BR_113[xanchor], - b: height * __FROM_BR_113[yanchor], - t: height * __FROM_TL_113[yanchor] - }); - - selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$rangeselector_115 = { - moduleType: 'component', - name: 'rangeselector', - - schema: { - subplots: { - xaxis: {rangeselector: _$attributes_109} - } +var _$attributes_70 = { + visible: { + valType: 'boolean', + + editType: 'calc', + }, - - layoutAttributes: _$attributes_109, - handleDefaults: _$handleDefaults_112, - - draw: _$draw_113 -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_42 = require('../color/attributes'); */; - -var _$attributes_116 = { - bgcolor: { - valType: 'color', - dflt: _$attributes_42.background, + type: { + valType: 'enumerated', + values: ['percent', 'constant', 'sqrt', 'data'], - editType: 'plot', + editType: 'calc', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_42.defaultLine, + symmetric: { + valType: 'boolean', - editType: 'plot', + editType: 'calc', }, - borderwidth: { + array: { + valType: 'data_array', + editType: 'calc', + + }, + arrayminus: { + valType: 'data_array', + editType: 'calc', + + }, + value: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'calc', + + }, + valueminus: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'calc', + + }, + traceref: { valType: 'integer', - dflt: 0, min: 0, + dflt: 0, - editType: 'plot', + editType: 'style' + }, + tracerefminus: { + valType: 'integer', + min: 0, + dflt: 0, + editType: 'style' }, - autorange: { + copy_ystyle: { valType: 'boolean', - dflt: true, - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, + editType: 'plot' + }, + copy_zstyle: { + valType: 'boolean', + editType: 'style' }, - range: { - valType: 'info_array', + color: { + valType: 'color', - items: [ - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} - ], - editType: 'calc', - impliedEdits: {'autorange': false}, + editType: 'style', }, thickness: { valType: 'number', - dflt: 0.15, min: 0, - max: 1, + dflt: 2, - editType: 'plot', + editType: 'style', }, - visible: { - valType: 'boolean', - dflt: true, + width: { + valType: 'number', + min: 0, - editType: 'calc', + editType: 'plot', }, - editType: 'calc' + editType: 'calc', + + _deprecated: { + opacity: { + valType: 'number', + + editType: 'style', + + } + } }; /** @@ -44235,53 +44347,101 @@ var _$attributes_116 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -var _$constants_118 = { - - // attribute container name - name: 'rangeslider', - - // class names - - containerClassName: 'rangeslider-container', - bgClassName: 'rangeslider-bg', - rangePlotClassName: 'rangeslider-rangeplot', - - maskMinClassName: 'rangeslider-mask-min', - maskMaxClassName: 'rangeslider-mask-max', - slideBoxClassName: 'rangeslider-slidebox', - - grabberMinClassName: 'rangeslider-grabber-min', - grabAreaMinClassName: 'rangeslider-grabarea-min', - handleMinClassName: 'rangeslider-handle-min', - - grabberMaxClassName: 'rangeslider-grabber-max', - grabAreaMaxClassName: 'rangeslider-grabarea-max', - handleMaxClassName: 'rangeslider-handle-max', - - maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', - maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', - // style constants +'use strict'; - maskColor: 'rgba(0,0,0,0.4)', - maskOppAxisColor: 'rgba(0,0,0,0.2)', - slideBoxFill: 'transparent', - slideBoxCursor: 'ew-resize', +/** + * 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 " + */ +var _$makeComputeError_72 = function makeComputeError(opts) { + var type = opts.type, + symmetric = opts.symmetric; - grabAreaFill: 'transparent', - grabAreaCursor: 'col-resize', - grabAreaWidth: 10, + if(type === 'data') { + var array = opts.array || []; - handleWidth: 4, - handleRadius: 1, - handleStrokeWidth: 1, + 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), + computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); - extraPad: 15 + 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)); + }; + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44290,70 +44450,59 @@ var _$constants_118 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var listAxes = _$axis_ids_207.list; -var __getAutoRange_117 = _$autorange_203.getAutoRange; -/* removed: var _$constants_118 = require('./constants'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var _$calcAutorange_117 = function calcAutorange(gd) { - var axes = listAxes(gd, 'x', true); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; - // 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. +/* removed: var _$makeComputeError_72 = require('./compute_error'); */; - for(var i = 0; i < axes.length; i++) { - var ax = axes[i], - opts = ax[_$constants_118.name]; - // Don't try calling getAutoRange if _min and _max are filled in. - // This happens on updates where the calc step is skipped. +var _$calc_71 = function calc(gd) { + var calcdata = gd.calcdata; - if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { - opts._input.autorange = true; - opts._input.range = opts.range = __getAutoRange_117(ax); - } + for(var i = 0; i < calcdata.length; i++) { + var calcTrace = calcdata[i], + trace = calcTrace[0].trace; + + if(!_$registry_245.traceIs(trace, 'errorBarsOK')) continue; + + var xa = _$axes_205.getFromId(gd, trace.xaxis), + ya = _$axes_205.getFromId(gd, trace.yaxis); + + calcOneAxis(calcTrace, trace, xa, 'x'); + calcOneAxis(calcTrace, trace, ya, 'y'); } }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function calcOneAxis(calcTrace, trace, axis, coord) { + var opts = trace['error_' + coord] || {}, + isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), + vals = []; -'use strict'; + if(!isVisible) return; -var _$oppaxis_attributes_122 = { - // not really a 'subplot' attribute container, - // but this is the flag we use to denote attributes that - // support yaxis, yaxis2, yaxis3, ... counters - _isSubplotObj: true, + var computeError = _$makeComputeError_72(opts); - 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' -}; + for(var i = 0; i < calcTrace.length; i++) { + var calcPt = calcTrace[i], + calcCoord = calcPt[coord]; + + if(!_$fastIsnumeric_10(axis.c2l(calcCoord))) continue; + + var errors = computeError(calcCoord, i); + if(_$fastIsnumeric_10(errors[0]) && _$fastIsnumeric_10(errors[1])) { + var shoe = calcPt[coord + 's'] = calcCoord - errors[0], + hat = calcPt[coord + 'h'] = calcCoord + errors[1]; + vals.push(shoe, hat); + } + } + + _$axes_205.expand(axis, vals, {padded: true}); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -44365,75 +44514,68 @@ var _$oppaxis_attributes_122 = { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$attributes_116 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_207 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var _$handleDefaults_119 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; - // not super proud of this (maybe store _ in axis object instead - if(!_$lib_162.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; - } +/* removed: var _$attributes_70 = require('./attributes'); */; - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; + +var _$defaults_73 = function(traceIn, traceOut, defaultColor, opts) { + var objName = 'error_' + opts.axis, + containerOut = traceOut[objName] = {}, + containerIn = traceIn[objName] || {}; function coerce(attr, dflt) { - return _$lib_162.coerce(containerIn, containerOut, _$attributes_116, attr, dflt); + return _$lib_163.coerce(containerIn, containerOut, _$attributes_70, attr, dflt); } - function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_162.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_122, attr, dflt); - } + var hasErrorBars = ( + containerIn.array !== undefined || + containerIn.value !== undefined || + containerIn.type === 'sqrt' + ); - var visible = coerce('visible'); - if(!visible) return; + var visible = coerce('visible', hasErrorBars); - coerce('bgcolor', layoutOut.plot_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('thickness'); + if(visible === false) return; - axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); - coerce('range'); + var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), + symmetric = true; - var subplots = layoutOut._subplots; - if(subplots) { - var yIds = subplots.cartesian - .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_207.name2id(axName); - }) - .map(function(subplotId) { - return subplotId.substr(subplotId.indexOf('y'), subplotId.length); - }); - var yNames = _$lib_162.simpleMap(yIds, _$axis_ids_207.id2name); - for(var i = 0; i < yNames.length; i++) { - var yName = yNames[i]; - - var rangeContainerIn = containerIn[yName] || {}; - var rangeContainerOut = containerOut[yName] = {}; - - var yAxOut = layoutOut[yName]; - - var rangemodeDflt; - if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { - rangemodeDflt = 'fixed'; - } + if(type !== 'sqrt') { + symmetric = coerce('symmetric', + !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); + } - var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); - if(rangeMode !== 'match') { - coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); - } - yAxOut._rangesliderAutorange = (rangeMode === 'auto'); + 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'); + } - // to map back range slider (auto) range - containerOut._input = containerIn; + var copyAttr = 'copy_' + opts.inherit + 'style'; + if(opts.inherit) { + var inheritObj = traceOut['error_' + opts.inherit]; + if((inheritObj || {}).visible) { + coerce(copyAttr, !(containerIn.color || + _$fastIsnumeric_10(containerIn.thickness) || + _$fastIsnumeric_10(containerIn.width))); + } + } + if(!opts.inherit || !containerOut[copyAttr]) { + coerce('color', defaultColor); + coerce('thickness'); + coerce('width', _$registry_245.traceIs(traceOut, 'gl3d') ? 0 : 4); + } }; /** @@ -44444,679 +44586,406 @@ var _$handleDefaults_119 = function handleDefaults(layoutIn, layoutOut, axName) * LICENSE file in the root directory of this source tree. */ + 'use strict'; /* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; - -/* removed: var _$lib_162 = require('../../lib'); */; /* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$titles_136 = require('../titles'); */; - -/* removed: var _$cartesian_215 = require('../../plots/cartesian'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$setCursor_181 = require('../../lib/setcursor'); */; - -/* removed: var _$constants_118 = require('./constants'); */; - -var _$draw_120 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); - - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; - function keyFunction(axisOpts) { - return axisOpts._name; - } +var _$plot_75 = function plot(traces, plotinfo, transitionOpts) { + var isNew; - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_118.containerClassName) - .data(rangeSliderData, keyFunction); + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - rangeSliders.enter().append('g') - .classed(_$constants_118.containerClassName, true) - .attr('pointer-events', 'all'); + var hasAnimation = transitionOpts && transitionOpts.duration > 0; - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_7.select(this), - opts = axisOpts[_$constants_118.name]; + 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 + xObj = trace.error_x || {}, + yObj = trace.error_y || {}; - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); + var keyFunc; - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); + if(trace.ids) { + keyFunc = function(d) {return d.id;}; + } - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; + var sparse = ( + _$subtypes_303.hasMarkers(trace) && + trace.marker.maxdisplayed > 0 + ); - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_7.select(this), - opts = axisOpts[_$constants_118.name], - oppAxisOpts = fullLayout[_$axes_204.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_204.id2name(axisOpts.anchor)]; + if(!yObj.visible && !xObj.visible) d = []; - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; + var errorbars = _$d3_7.select(this).selectAll('g.errorbar') + .data(d, keyFunc); - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } + errorbars.exit().remove(); - axisOpts.cleanRange('rangeslider.range'); + if(!d.length) return; + if(!xObj.visible) errorbars.selectAll('path.xerror').remove(); + if(!yObj.visible) errorbars.selectAll('path.yerror').remove(); - // update range slider dimensions + errorbars.style('opacity', 1); - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; + var enter = errorbars.enter().append('g') + .classed('errorbar', true); - var oppBottom = Infinity; - var subplotData = _$axes_204.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_204.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); + if(hasAnimation) { + enter.style('opacity', 0).transition() + .duration(transitionOpts.duration) + .style('opacity', 1); } - opts._id = _$constants_118.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; - - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); + _$drawing_68.setClipUrl(errorbars, plotinfo.layerClipId); - var x = Math.round(margin.l + (graphSize.w * domain[0])); + errorbars.each(function(d) { + var errorbar = _$d3_7.select(this); + var coords = errorCoords(d, xa, ya); - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_118.extraPad - ); + if(sparse && !d.vis) return; - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); + var path; - // update data <--> pixel coordinate conversion methods + var yerror = errorbar.select('path.yerror'); + if(yObj.visible && _$fastIsnumeric_10(coords.x) && + _$fastIsnumeric_10(coords.yh) && + _$fastIsnumeric_10(coords.ys)) { + var yw = yObj.width; - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; + path = 'M' + (coords.x - yw) + ',' + + coords.yh + 'h' + (2 * yw) + // hat + 'm-' + yw + ',0V' + coords.ys; // bar - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; - }; + if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe - opts._rl = [range0, range1]; + isNew = !yerror.size(); - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; + 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); + } - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; - } + yerror.attr('d', path); + } + else yerror.remove(); - // update inner nodes + var xerror = errorbar.select('path.xerror'); + if(xObj.visible && _$fastIsnumeric_10(coords.y) && + _$fastIsnumeric_10(coords.xh) && + _$fastIsnumeric_10(coords.xs)) { + var xw = (xObj.copy_ystyle ? yObj : xObj).width; - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); + path = 'M' + coords.xh + ',' + + (coords.y - xw) + 'v' + (2 * xw) + // hat + 'm0,-' + xw + 'H' + coords.xs; // bar - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); + if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + isNew = !xerror.size(); - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_136.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' + 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); } - }); - } - // update margins - _$plots_237.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_118.extraPad + opts._offsetShift * 2 + xerror.attr('d', path); + } + else xerror.remove(); }); }); }; -function makeRangeSliderData(fullLayout) { - var axes = _$axes_204.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_118.name, - out = []; +// 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) + }; - if(fullLayout._has('gl2d')) return out; + // 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); - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; + // if the shoes go off-scale (ie log scale, error bars past zero) + // clip the bar and hide the shoes + if(!_$fastIsnumeric_10(out.ys)) { + out.noYS = true; + out.ys = ya.c2p(d.ys, true); + } + } - if(ax[name] && ax[name].visible) out.push(ax); + if(d.xh !== undefined) { + out.xh = xa.c2p(d.xh); + out.xs = xa.c2p(d.xs); + + if(!_$fastIsnumeric_10(out.xs)) { + out.noXS = true; + out.xs = xa.c2p(d.xs, true); + } } return out; } -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_118.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_118.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_118.grabAreaMaxClassName).node(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - rangeSlider.on('mousedown', function() { - var event = _$d3_7.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); - var dragCover = _$dragelement_65.coverSlip(); +'use strict'; - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); +/* removed: var _$d3_7 = require('d3'); */; - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; +/* removed: var _$color_43 = require('../color'); */; - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; +var _$style_76 = function style(traces) { + traces.each(function(d) { + var trace = d[0].trace, + yObj = trace.error_y || {}, + xObj = trace.error_x || {}; - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; + var s = _$d3_7.select(this); - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } + s.selectAll('path.yerror') + .style('stroke-width', yObj.thickness + 'px') + .call(_$color_43.stroke, yObj.color); - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } + if(xObj.copy_ystyle) xObj = yObj; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; + s.selectAll('path.xerror') + .style('stroke-width', xObj.thickness + 'px') + .call(_$color_43.stroke, xObj.color); + }); +}; - _$setCursor_181(_$d3_7.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_162.removeElement(dragCover); - } - }); -} +'use strict'; -function setDataRange(rangeSlider, gd, axisOpts, opts) { +/* removed: var _$lib_163 = require('../../lib'); */; +var __overrideAll_74 = _$edit_types_190.overrideAll; - function clamp(v) { - return axisOpts.l2r(_$lib_162.constrain(v, opts._rl[0], opts._rl[1])); - } +/* removed: var _$attributes_70 = require('./attributes'); */; +/* removed: var _$calc_71 = require('./calc'); */; - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); +var xyAttrs = { + error_x: _$lib_163.extendFlat({}, _$attributes_70), + error_y: _$lib_163.extendFlat({}, _$attributes_70) +}; +delete xyAttrs.error_x.copy_zstyle; +delete xyAttrs.error_y.copy_zstyle; +delete xyAttrs.error_y.copy_ystyle; - window.requestAnimationFrame(function() { - _$registry_244.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} +var xyzAttrs = { + error_x: _$lib_163.extendFlat({}, _$attributes_70), + error_y: _$lib_163.extendFlat({}, _$attributes_70), + error_z: _$lib_163.extendFlat({}, _$attributes_70) +}; +delete xyzAttrs.error_x.copy_ystyle; +delete xyzAttrs.error_y.copy_ystyle; +delete xyzAttrs.error_z.copy_ystyle; +delete xyzAttrs.error_z.copy_zstyle; -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_118.handleWidth / 2; +var _$errorbars_74 = { + moduleType: 'component', + name: 'errorbars', - function clamp(v) { - return _$lib_162.constrain(v, 0, opts._width); - } + schema: { + traces: { + scatter: xyAttrs, + bar: xyAttrs, + histogram: xyAttrs, + scatter3d: __overrideAll_74(xyzAttrs, 'calc', 'nested'), + scattergl: __overrideAll_74(xyAttrs, 'calc', 'nested') + } + }, - function clampOppAxis(v) { - return _$lib_162.constrain(v, 0, opts._height); - } + supplyDefaults: _$defaults_73, - function clampHandle(v) { - return _$lib_162.constrain(v, -hw2, opts._width + hw2); - } + calc: _$calc_71, + calcFromTrace: calcFromTrace, - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + plot: _$plot_75, + style: _$style_76, + hoverInfo: hoverInfo +}; - rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); +function calcFromTrace(trace, layout) { + var x = trace.x || [], + y = trace.y || [], + len = x.length || y.length; - rangeSlider.select('rect.' + _$constants_118.maskMinClassName) - .attr('width', pixelMin); + var calcdataMock = new Array(len); - rangeSlider.select('rect.' + _$constants_118.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + for(var i = 0; i < len; i++) { + calcdataMock[i] = { + x: x[i], + y: y[i] + }; + } - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + calcdataMock[0].trace = trace; - rangeSlider.select('rect.' + _$constants_118.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + _$calc_71({ + calcdata: [calcdataMock], + _fullLayout: layout + }); - rangeSlider.select('rect.' + _$constants_118.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); + return calcdataMock; +} - rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); +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; } +} - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; +var _$domain_230 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; +'use strict'; - rangeSlider.select('g.' + _$constants_118.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); +var __extendFlat_230 = _$extend_157.extendFlat; - rangeSlider.select('g.' + _$constants_118.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} - -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_118.bgClassName) - .data([0]); - - bg.enter().append('rect') - .classed(_$constants_118.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); - - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; - - var offsetShift = -opts._offsetShift; - var lw = _$drawing_68.crispRound(gd, opts.borderwidth); - - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} - -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; - - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); - - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); -} - -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_204.getSubplots(gd, axisOpts), - calcData = gd.calcdata; - - var rangePlots = rangeSlider.selectAll('g.' + _$constants_118.rangePlotClassName) - .data(subplotData, _$lib_162.identity); - - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_118.rangePlotClassName + ' ' + id; }) - .call(_$drawing_68.setClipUrl, opts._clipId); - - rangePlots.order(); - - rangePlots.exit().remove(); - - var mainplotinfo; +/** + * 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 + */ +_$domain_230.attributes = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; - rangePlots.each(function(id, i) { - var plotgroup = _$d3_7.select(this), - isMainPlot = (i === 0); + 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 oppAxisOpts = _$axes_204.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; + var namePart = opts.name ? opts.name + ' ' : ''; + var contPart = opts.trace ? 'trace ' : 'subplot '; + var descPart = extra.description ? ' ' + extra.description : ''; - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + var out = { + x: __extendFlat_230({}, base, { + + }), + y: __extendFlat_230({}, base, { + + }), + editType: opts.editType + }; - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar + if(!opts.noGridCell) { + out.row = { + valType: 'integer', + min: 0, + dflt: 0, + + editType: opts.editType, + }; - - _$plots_237.supplyDefaults(mockFigure); - - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; - - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya + out.column = { + valType: 'integer', + min: 0, + dflt: 0, + + editType: opts.editType, + }; - - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; - } - - _$cartesian_215.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); -} - -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; - - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; - - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); - } } return out; -} - -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_118.maskMinClassName) - .data([0]); - - maskMin.enter().append('rect') - .classed(_$constants_118.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); - - maskMin - .attr('height', opts._height) - .call(_$color_43.fill, _$constants_118.maskColor); - - var maskMax = rangeSlider.selectAll('rect.' + _$constants_118.maskMaxClassName) - .data([0]); - - maskMax.enter().append('rect') - .classed(_$constants_118.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); - - maskMax - .attr('height', opts._height) - .call(_$color_43.fill, _$constants_118.maskColor); - - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_118.maskMinOppAxisClassName) - .data([0]); - - maskMinOppAxis.enter().append('rect') - .classed(_$constants_118.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); - - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_43.fill, _$constants_118.maskOppAxisColor); - - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_118.maskMaxOppAxisClassName) - .data([0]); - - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_118.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); - - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_118.maskOppBorder) - .call(_$color_43.fill, _$constants_118.maskOppAxisColor); - } -} - -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; - - var slideBox = rangeSlider.selectAll('rect.' + _$constants_118.slideBoxClassName) - .data([0]); - - slideBox.enter().append('rect') - .classed(_$constants_118.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_118.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); - - slideBox.attr({ - height: opts._height, - fill: _$constants_118.slideBoxFill - }); -} - -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { - - // - - var grabberMin = rangeSlider.selectAll('g.' + _$constants_118.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_118.grabberMinClassName, true); - - var grabberMax = rangeSlider.selectAll('g.' + _$constants_118.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_118.grabberMaxClassName, true); - - // - - var handleFixAttrs = { - x: 0, - width: _$constants_118.handleWidth, - rx: _$constants_118.handleRadius, - fill: _$color_43.background, - stroke: _$color_43.defaultLine, - 'stroke-width': _$constants_118.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; - - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; - - var handleMin = grabberMin.selectAll('rect.' + _$constants_118.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_118.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); - - var handleMax = grabberMax.selectAll('rect.' + _$constants_118.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_118.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); - - // - - if(gd._context.staticPlot) return; - - var grabAreaFixAttrs = { - width: _$constants_118.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_118.grabAreaFill, - cursor: _$constants_118.grabAreaCursor - }; - - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_118.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_118.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); - - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_118.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_118.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); -} - -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); +}; - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; +_$domain_230.defaults = function(containerOut, layout, coerce, dfltDomains) { + var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; + var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; - if(k.indexOf(_$constants_118.name) !== -1) { - _$plots_237.autoMargin(gd, k); + 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; } - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$attributes_116 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; - -var _$rangeslider_121 = { - moduleType: 'component', - name: 'rangeslider', - - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_162.extendFlat({}, _$attributes_116, { - yaxis: _$oppaxis_attributes_122 - }) - } + var row = coerce('domain.row'); + if(row !== undefined) { + if(row < grid.rows) dfltY = grid._domains.y[row]; + else delete containerOut.domain.row; } - }, + } - layoutAttributes: _$attributes_116, - handleDefaults: _$handleDefaults_119, - calcAutorange: _$calcAutorange_117, - draw: _$draw_120 + coerce('domain.x', dfltX); + coerce('domain.y', dfltY); }; /** @@ -45129,246 +44998,374 @@ var _$rangeslider_121 = { 'use strict'; -/* removed: var _$attributes_28 = require('../annotations/attributes'); */; -var scatterLineAttrs = _$attributes_280.line; -var __dash_123 = _$attributes_67.dash; -var __extendFlat_123 = _$extend_156.extendFlat; - -var _$attributes_123 = { - _isLinkedToArray: 'shape', +/* removed: var _$lib_163 = require('../../lib'); */; +var __counterRegex_89 = _$regex_178.counter; +var domainAttrs = _$domain_230.attributes; +var cartesianIdRegex = _$constants_210.idRegex; - visible: { - valType: 'boolean', +var gridAttrs = { + rows: { + valType: 'integer', + min: 1, - dflt: true, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - type: { + roworder: { valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], + values: ['top to bottom', 'bottom to top'], + dflt: 'top to bottom', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', + columns: { + valType: 'integer', + min: 1, - editType: 'arraydraw', + editType: 'plot', }, - - xref: __extendFlat_123({}, _$attributes_28.xref, { - - }), - x0: { - valType: 'any', + subplots: { + valType: 'info_array', + freeLength: true, + dimensions: 2, + items: {valType: 'enumerated', values: [__counterRegex_89('xy').toString(), ''], editType: 'plot'}, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - x1: { - valType: 'any', + xaxes: { + valType: 'info_array', + freeLength: true, + items: {valType: 'enumerated', values: [cartesianIdRegex.x.toString(), ''], editType: 'plot'}, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - yref: __extendFlat_123({}, _$attributes_28.yref, { - - }), - y0: { - valType: 'any', + yaxes: { + valType: 'info_array', + freeLength: true, + items: {valType: 'enumerated', values: [cartesianIdRegex.y.toString(), ''], editType: 'plot'}, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - y1: { - valType: 'any', + pattern: { + valType: 'enumerated', + values: ['independent', 'coupled'], + dflt: 'coupled', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - path: { - valType: 'string', + xgap: { + valType: 'number', + min: 0, + max: 1, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - opacity: { + ygap: { valType: 'number', min: 0, max: 1, - dflt: 1, - editType: 'arraydraw', + editType: 'plot', }, - line: { - color: __extendFlat_123({}, scatterLineAttrs.color, {editType: 'arraydraw'}), - width: __extendFlat_123({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_123({}, __dash_123, {editType: 'arraydraw'}), + domain: domainAttrs({name: 'grid', editType: 'plot', noGridCell: true}, { + + }), + xside: { + valType: 'enumerated', + values: ['bottom', 'bottom plot', 'top plot', 'top'], + dflt: 'bottom plot', + + editType: 'plot', - editType: 'calcIfAutorange+arraydraw' }, - fillcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', + yside: { + valType: 'enumerated', + values: ['left', 'left plot', 'right plot', 'right'], + dflt: 'left plot', - editType: 'arraydraw', + editType: 'plot', }, - editType: 'arraydraw' + editType: 'plot' }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - +function getAxes(layout, grid, axLetter) { + var gridVal = grid[axLetter + 'axes']; + var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {}); -'use strict'; + 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'); -var _$constants_125 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, + if(!layoutIn.grid && !xAxes && !yAxes) return; - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, + 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 + ); - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} - }, + var dfltRows, dfltColumns; - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 + if(hasSubplotGrid) { + dfltRows = gridIn.subplots.length; + dfltColumns = gridIn.subplots[0].length; + } + else { + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } -}; - -var _$helpers_128 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 gridOut = layoutOut.grid = {}; -'use strict'; + function coerce(attr, dflt) { + return _$lib_163.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + } -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. + var rows = coerce('rows', dfltRows); + var columns = coerce('columns', dfltColumns); -_$helpers_128.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; + if(!(rows * columns > 1)) return; -_$helpers_128.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; + if(!hasSubplotGrid && !hasXaxes && !hasYaxes) { + var useDefaultSubplots = coerce('pattern') === 'independent'; + if(useDefaultSubplots) hasSubplotGrid = true; + } + gridOut._hasSubplotGrid = hasSubplotGrid; -_$helpers_128.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; + var rowOrder = coerce('roworder'); + var reversed = rowOrder === 'top to bottom'; -_$helpers_128.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; + var dfltGapX = hasSubplotGrid ? 0.2 : 0.1; + var dfltGapY = hasSubplotGrid ? 0.3 : 0.1; -_$helpers_128.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; + var dfltSideX, dfltSideY; + if(isSplomGenerated) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } - if(axis) { - var d2r = _$helpers_128.shapePositionToRange(axis); + gridOut._domains = { + x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns), + y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed) + }; +} - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; +// 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); - if(axis.type === 'date') dataToPixel = _$helpers_128.decodeDate(dataToPixel); + 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]; } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + 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 { - dataToPixel = function(v) { return gs.l + gs.w * v; }; + 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'); } - return dataToPixel; -}; + var anchors = gridOut._anchors = {}; + var reversed = gridOut.roworder === 'top to bottom'; -_$helpers_128.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; + for(var axisId in axisMap) { + var axLetter = axisId.charAt(0); + var side = gridOut[axLetter + 'side']; - if(axis) { - var r2d = _$helpers_128.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + 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; + } + } + } + } } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; +} + +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 { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; + // default axis list is the first `len` axis ids + fillOneAxis(0, axLetter); + for(i = 1; i < len; i++) { + fillOneAxis(i, axLetter + (i + 1)); + } } - return pixelToData; + return out; +} + +var _$grid_89 = { + moduleType: 'component', + name: 'grid', + + schema: { + layout: {grid: gridAttrs} + }, + + layoutAttributes: gridAttrs, + sizeDefaults: sizeDefaults, + contentDefaults: contentDefaults }; /** @@ -45379,73 +45376,132 @@ _$helpers_128.getPixelToData = function(gd, axis, isVertical) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; +/* removed: var _$constants_210 = require('../../plots/cartesian/constants'); */; -/* removed: var _$constants_125 = require('./constants'); */; -/* removed: var _$helpers_128 = require('./helpers'); */; +var _$attributes_90 = { + _isLinkedToArray: 'image', -var _$calcAutorange_124 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_162.filterVisible(fullLayout.shapes); + visible: { + valType: 'boolean', + + dflt: true, + editType: 'arraydraw', + + }, - if(!shapeList.length || !gd._fullData.length) return; + source: { + valType: 'string', + + editType: 'arraydraw', + + }, - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, - var ax, bounds; + sizex: { + valType: 'number', + + dflt: 0, + editType: 'arraydraw', + + }, - if(shape.xref !== 'paper') { - ax = _$axes_204.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_125.paramIsX); - if(bounds) _$axes_204.expand(ax, bounds, {ppad: ppad}); - } + sizey: { + valType: 'number', + + dflt: 0, + editType: 'arraydraw', + + }, - if(shape.yref !== 'paper') { - ax = _$axes_204.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_125.paramIsY); - if(bounds) _$axes_204.expand(ax, bounds, {ppad: ppad}); - } - } -}; + sizing: { + valType: 'enumerated', + values: ['fill', 'contain', 'stretch'], + dflt: 'contain', + + editType: 'arraydraw', + + }, -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; + opacity: { + valType: 'number', + + min: 0, + max: 1, + dflt: 1, + editType: 'arraydraw', + + }, - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; + x: { + valType: 'any', + + dflt: 0, + editType: 'arraydraw', + + }, - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_125.segmentRE), - i, - segment, - drawnParam, - params, - val; + y: { + valType: 'any', + + dflt: 0, + editType: 'arraydraw', + + }, - if(ax.type === 'date') convertVal = _$helpers_128.decodeDate(convertVal); + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + editType: 'arraydraw', + + }, - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; + yanchor: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'top', + + editType: 'arraydraw', + + }, - params = segments[i].substr(1).match(_$constants_125.paramRE); - if(!params || params.length < drawnParam) continue; + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_210.idRegex.x.toString() + ], + dflt: 'paper', + + editType: 'arraydraw', + + }, - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; - } - if(max >= min) return [min, max]; -} + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_210.idRegex.y.toString() + ], + dflt: 'paper', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45458,91 +45514,75 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$attributes_123 = require('./attributes'); */; -/* removed: var _$helpers_128 = require('./helpers'); */; - - -var _$handleShapeDefaults_130 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; - - function coerce(attr, dflt) { - return _$lib_162.coerce(shapeIn, shapeOut, _$attributes_123, attr, dflt); - } +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_186 = require('../../lib/to_log_range'); */; - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); +/* + * convertCoords: when converting an axis between log and linear + * you need to alter any images on that axis to keep them + * pointing at the same data point. + * In v2.0 this will become obsolete (or perhaps size will still need conversion?) + * we convert size by declaring that the maximum extent *in data units* should be + * the same, assuming the image is anchored by its center (could remove that restriction + * if we think it's important) even though the actual left and right values will not be + * quite the same since the scale becomes nonlinear (and central anchor means the pixel + * center of the image, not the data units center) + * + * gd: the plot div + * ax: the axis being changed + * newType: the type it's getting + * doExtra: function(attr, val) from inside relayout that sets the attribute. + * Use this to make the changes as it's aware if any other changes in the + * same relayout call should override this conversion. + */ +var _$convertCoords_91 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; - if(!visible) return shapeOut; + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); + if(!(toLog || fromLog)) return; - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + var images = gd._fullLayout.images, + axLetter = ax._id.charAt(0), + image, + attrPrefix; - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + for(var i = 0; i < images.length; i++) { + image = images[i]; + attrPrefix = 'images[' + i + '].'; - // xref, yref - var axRef = _$axes_204.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + if(image[axLetter + 'ref'] === ax._id) { + var currentPos = image[axLetter], + currentSize = image['size' + axLetter], + newPos = null, + newSize = null; - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + if(toLog) { + newPos = _$toLogRange_186(currentPos, ax.range); - if(axRef !== 'paper') { - ax = _$axes_204.getFromId(gdMock, axRef); - r2pos = _$helpers_128.rangeToShapePosition(ax); - pos2r = _$helpers_128.shapePositionToRange(ax); + // this is the inverse of the conversion we do in fromLog below + // so that the conversion is reversible (notice the fromLog conversion + // is like sinh, and this one looks like arcsinh) + var dx = currentSize / Math.pow(10, newPos) / 2; + newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; } else { - pos2r = r2pos = _$lib_162.identity; + newPos = Math.pow(10, currentPos); + newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); } - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); - - // x0, x1 (and y0, y1) - _$axes_204.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_204.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + // if conversion failed, delete the value so it can get a default later on + if(!_$fastIsnumeric_10(newPos)) { + newPos = null; + newSize = null; + } + else if(!_$fastIsnumeric_10(newSize)) newSize = null; - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; + doExtra(attrPrefix + axLetter, newPos); + doExtra(attrPrefix + 'size' + axLetter, newSize); } } - - if(shapeType === 'path') { - coerce('path'); - } - else { - _$lib_162.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); - } - - return shapeOut; }; /** @@ -45553,395 +45593,277 @@ var _$handleShapeDefaults_130 = function handleShapeDefaults(shapeIn, shapeOut, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$handleArrayContainerDefaults_200 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_130 = require('./shape_defaults'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$attributes_90 = require('./attributes'); */; +var name = 'images'; -var _$supplyLayoutDefaults_126 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_92 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_130 + name: name, + handleItemDefaults: imageDefaults }; - _$handleArrayContainerDefaults_200(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function imageDefaults(imageIn, imageOut, fullLayout) { -'use strict'; - -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; - -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$setCursor_181 = require('../../lib/setcursor'); */; - -/* removed: var _$constants_125 = require('./constants'); */; -/* removed: var _$helpers_128 = require('./helpers'); */; + function coerce(attr, dflt) { + return _$lib_163.coerce(imageIn, imageOut, _$attributes_90, attr, dflt); + } + var source = coerce('source'); + var visible = coerce('visible', !!source); -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one + if(!visible) return imageOut; -var _$draw_127 = { - draw: __draw_127, - drawOne: __drawOne_127 -}; + coerce('layer'); + coerce('xanchor'); + coerce('yanchor'); + coerce('sizex'); + coerce('sizey'); + coerce('sizing'); + coerce('opacity'); -function __draw_127(gd) { - var fullLayout = gd._fullLayout; + var gdMock = { _fullLayout: fullLayout }, + axLetters = ['x', 'y']; - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + for(var i = 0; i < 2; i++) { + // 'paper' is the fallback axref + var axLetter = axLetters[i], + axRef = _$axes_205.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_127(gd, i); - } + _$axes_205.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); } - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); + return imageOut; } -function __drawOne_127(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); - - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; +'use strict'; - if(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); - } - else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } - } +/* removed: var _$d3_7 = require('d3'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; +var _$draw_93 = function draw(gd) { + var fullLayout = gd._fullLayout, + imageDataAbove = [], + imageDataSubplot = {}, + imageDataBelow = [], + subplot, + i; - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_43.stroke, lineColor) - .call(_$color_43.fill, options.fillcolor) - .call(_$drawing_68.dashLine, options.line.dash, options.line.width); + // Sort into top, subplot, and bottom layers + for(i = 0; i < fullLayout.images.length; i++) { + var img = fullLayout.images[i]; - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); + if(img.visible) { + if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { + subplot = img.xref + img.yref; - path.call(_$drawing_68.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); + var plotinfo = fullLayout._plots[subplot]; - if(gd._context.edits.shapePosition) __setupDragElement_127(gd, path, options, index); - } -} + if(!plotinfo) { + // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the image to an x / y axis combination + // that doesn't have any data on it (and layer is below) + imageDataBelow.push(img); + continue; + } -function __setupDragElement_127(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; + if(plotinfo.mainplot) { + subplot = plotinfo.mainplot.id; + } - var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; + if(!imageDataSubplot[subplot]) { + imageDataSubplot[subplot] = []; + } + imageDataSubplot[subplot].push(img); + } else if(img.layer === 'above') { + imageDataAbove.push(img); + } else { + imageDataBelow.push(img); + } + } + } - var xa, ya, x2p, y2p, p2x, p2y; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag + var anchors = { + x: { + left: { sizing: 'xMin', offset: 0 }, + center: { sizing: 'xMid', offset: -1 / 2 }, + right: { sizing: 'xMax', offset: -1 } }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; - - _$dragelement_65.init(dragOptions); + y: { + top: { sizing: 'YMin', offset: 0 }, + middle: { sizing: 'YMid', offset: -1 / 2 }, + bottom: { sizing: 'YMax', offset: -1 } + } + }; - shapePath.node().onmousemove = updateDragMode; - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_65.getCursor(x / w, 1 - y / h) : - 'move'; + // Images must be converted to dataURL's for exporting. + function setImage(d) { + var thisImage = _$d3_7.select(this); - _$setCursor_181(shapePath, cursor); + if(this.img && this.img.src === d.source) { + return; + } - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; - } + thisImage.attr('xmlns', _$xmlns_namespaces_147.svg); - function startDrag(evt) { - // setup conversion functions - xa = _$axes_204.getFromId(gd, shapeOptions.xref); - ya = _$axes_204.getFromId(gd, shapeOptions.yref); + var imagePromise = new Promise(function(resolve) { - x2p = _$helpers_128.getDataToPixel(gd, xa); - y2p = _$helpers_128.getDataToPixel(gd, ya, true); - p2x = _$helpers_128.getPixelToData(gd, xa); - p2y = _$helpers_128.getPixelToData(gd, ya, true); + var img = new Image(); + this.img = img; - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; - } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + // If not set, a `tainted canvas` error is thrown + img.setAttribute('crossOrigin', 'anonymous'); + img.onerror = errorHandler; + img.onload = function() { + var canvas = document.createElement('canvas'); + canvas.width = this.width; + canvas.height = this.height; - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } + var ctx = canvas.getContext('2d'); + ctx.drawImage(this, 0, 0); - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; - } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; - } + var dataURL = canvas.toDataURL('image/png'); - update = {}; + thisImage.attr('xlink:href', dataURL); - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; - } + // resolve promise in onload handler instead of on 'load' to support IE11 + // see https://github.com/plotly/plotly.js/issues/1685 + // for more details + resolve(); + }; - function endDrag() { - _$setCursor_181(shapePath); - _$registry_244.call('relayout', gd, update); - } - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); + thisImage.on('error', errorHandler); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + img.src = d.source; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } + function errorHandler() { + thisImage.remove(); + resolve(); + } + }.bind(this)); - shapePath.attr('d', getPathString(gd, shapeOptions)); + gd._promises.push(imagePromise); } - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); - - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + function applyAttributes(d) { + var thisImage = _$d3_7.select(this); - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; + // Axes if specified + var xa = _$axes_205.getFromId(gd, d.xref), + ya = _$axes_205.getFromId(gd, d.yref); - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + var size = fullLayout._size, + width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, + height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); - } - } + // Offsets for anchor positioning + var xOffset = width * anchors.x[d.xanchor].offset, + yOffset = height * anchors.y[d.yanchor].offset; - shapePath.attr('d', getPathString(gd, shapeOptions)); - } -} + var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_204.getFromId(gd, options.xref), - ya = _$axes_204.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; + // Final positions + var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, + yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; - if(xa) { - x2r = _$helpers_128.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_128.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + // Construct the proper aspectRatio attribute + switch(d.sizing) { + case 'fill': + sizing += ' slice'; + break; - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_128.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_128.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); - } + case 'stretch': + sizing = 'none'; + break; + } - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), - y1 = y2p(options.y1); + thisImage.attr({ + x: xPos, + y: yPos, + width: width, + height: height, + preserveAspectRatio: sizing, + opacity: d.opacity + }); - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; -} + // Set proper clipping on images + var xId = xa ? xa._id : '', + yId = ya ? ya._id : '', + clipAxes = xId + yId; -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_125.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_125.paramIsX[segmentType], - yParams = _$constants_125.paramIsY[segmentType], - nParams = _$constants_125.numParams[segmentType]; + thisImage.call(_$drawing_68.setClipUrl, clipAxes ? + ('clip' + fullLayout._uid + clipAxes) : + null + ); + } - var paramString = segment.substr(1).replace(_$constants_125.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; + var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') + .data(imageDataBelow), + imagesAbove = fullLayout._imageUpperLayer.selectAll('image') + .data(imageDataAbove); - if(paramNumber > nParams) param = 'X'; - return param; - }); + imagesBelow.enter().append('image'); + imagesAbove.enter().append('image'); - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_162.log('Ignoring extra params in segment ' + segment); - } + imagesBelow.exit().remove(); + imagesAbove.exit().remove(); - return segmentType + paramString; + imagesBelow.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); + }); + imagesAbove.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); }); -} -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_125.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_125.paramIsX[segmentType], - yParams = _$constants_125.paramIsY[segmentType], - nParams = _$constants_125.numParams[segmentType]; + var allSubplots = Object.keys(fullLayout._plots); + for(i = 0; i < allSubplots.length; i++) { + subplot = allSubplots[i]; + var subplotObj = fullLayout._plots[subplot]; - var paramString = segment.substr(1).replace(_$constants_125.paramRE, function(param) { - if(paramNumber >= nParams) return param; + // filter out overlaid plots (which havd their images on the main plot) + // and gl2d plots (which don't support below images, at least not yet) + if(!subplotObj.imagelayer) continue; - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); + var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') + // even if there are no images on this subplot, we need to run + // enter and exit in case there were previously + .data(imageDataSubplot[subplot] || []); - paramNumber++; + imagesOnSubplot.enter().append('image'); + imagesOnSubplot.exit().remove(); - return param; + imagesOnSubplot.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); }); - - return segmentType + paramString; - }); -} + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45951,22 +45873,19 @@ function movePath(pathIn, moveX, moveY) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$draw_127 = require('./draw'); */; - -var _$shapes_129 = { +var _$images_94 = { moduleType: 'component', - name: 'shapes', + name: 'images', - layoutAttributes: _$attributes_123, - supplyLayoutDefaults: _$supplyLayoutDefaults_126, - includeBasePlot: _$makeIncludeComponents_214('shapes'), + layoutAttributes: _$attributes_90, + supplyLayoutDefaults: _$supplyLayoutDefaults_92, + includeBasePlot: _$makeIncludeComponents_215('images'), - calcAutorange: _$calcAutorange_124, - draw: _$draw_127.draw, - drawOne: _$draw_127.drawOne + draw: _$draw_93, + + convertCoords: _$convertCoords_91 }; /** @@ -45977,375 +45896,100 @@ var _$shapes_129 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_42 = require('../color/attributes'); */; -var _$constants_132 = { - - // layout attribute name - name: 'sliders', - - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', - - railHeight: 5, - - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', - - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', - - // min item width / height - minWidth: 30, - minHeight: 30, - - // padding around item text - textPadX: 40, - - // arrow offset off right edge - arrowOffsetX: 4, - - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', - - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, - - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, - - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', - labelPadding: 8, - labelOffset: 0, - - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, - - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, - - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_236 = { - t: { - valType: 'number', - dflt: 0, +var _$attributes_96 = { + bgcolor: { + valType: 'color', - editType: 'arraydraw', + editType: 'legend', }, - r: { - valType: 'number', - dflt: 0, + bordercolor: { + valType: 'color', + dflt: _$attributes_42.defaultLine, - editType: 'arraydraw', + editType: 'legend', }, - b: { + borderwidth: { valType: 'number', + min: 0, dflt: 0, - editType: 'arraydraw', + editType: 'legend', }, - l: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', + font: _$font_attributes_231({ + editType: 'legend', - }, - editType: 'arraydraw' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_236 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_131 = _$extend_156.extendDeepAll; -var __overrideAll_131 = _$edit_types_189.overrideAll; -/* removed: var _$animation_attributes_199 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_132 = require('./constants'); */; - -var stepsAttrs = { - _isLinkedToArray: 'step', - - method: { + }), + orientation: { valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], - - }, - label: { - valType: 'string', - - - }, - value: { - valType: 'string', - - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; - -var _$attributes_131 = __overrideAll_131({ - _isLinkedToArray: 'slider', - - visible: { - valType: 'boolean', - - dflt: true, - - }, - - active: { - valType: 'number', + values: ['v', 'h'], + dflt: 'v', - min: 0, - dflt: 0, + editType: 'legend', }, - - steps: stepsAttrs, - - lenmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], + traceorder: { + valType: 'flaglist', + flags: ['reversed', 'grouped'], + extras: ['normal'], - dflt: 'fraction', + editType: 'legend', }, - len: { + tracegroupgap: { valType: 'number', min: 0, - dflt: 1, + dflt: 10, + editType: 'legend', }, x: { valType: 'number', min: -2, max: 3, - dflt: 0, + dflt: 1.02, + editType: 'legend', }, - pad: __extendDeepAll_131({}, _$pad_attributes_236, { - - }, {t: {dflt: 20}}), xanchor: { valType: 'enumerated', values: ['auto', 'left', 'center', 'right'], dflt: 'left', + editType: 'legend', }, y: { valType: 'number', min: -2, max: 3, - dflt: 0, + dflt: 1, + editType: 'legend', }, yanchor: { valType: 'enumerated', values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, - - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_199.transition.easing.values, - - dflt: 'cubic-in-out', - - } - }, - - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, - - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, - - offset: { - valType: 'number', - dflt: 10, - - - }, - - prefix: { - valType: 'string', - - - }, - - suffix: { - valType: 'string', - - - }, - - font: _$font_attributes_231({ - - }) - }, - - font: _$font_attributes_231({ - - }), - - activebgcolor: { - valType: 'color', - - dflt: _$constants_132.gripBgActiveColor, - - }, - bgcolor: { - valType: 'color', - - dflt: _$constants_132.railBgColor, - - }, - bordercolor: { - valType: 'color', - dflt: _$constants_132.railBorderColor, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: _$constants_132.railBorderWidth, - - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_132.tickLength, - - - }, - tickcolor: { - valType: 'color', - dflt: _$constants_132.tickColor, - - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, + dflt: 'auto', + editType: 'legend', }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_132.minorTickLength, - - - } -}, 'arraydraw', 'from-root'); + editType: 'legend' +}; +var _$helpers_102 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46354,112 +45998,124 @@ var _$attributes_131 = __overrideAll_131({ * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_200 = require('../../plots/array_container_defaults'); */; +'use strict'; -/* removed: var _$attributes_131 = require('./attributes'); */; -/* removed: var _$constants_132 = require('./constants'); */; +_$helpers_102.legendGetsTrace = function legendGetsTrace(trace) { + // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? + // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. -var __name_133 = _$constants_132.name; -var stepAttrs = _$attributes_131.steps; + // Note that we explicitly include showlegend: false, so a trace that *could* be + // in the legend but is not shown still counts toward the two traces you need to + // ensure the legend is shown by default, because this can still help disambiguate. + return trace.visible && (trace.showlegend !== undefined); +}; +_$helpers_102.isGrouped = function isGrouped(legendLayout) { + return (legendLayout.traceorder || '').indexOf('grouped') !== -1; +}; -var _$slidersDefaults_133 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_133, - handleItemDefaults: sliderDefaults - }; +_$helpers_102.isVertical = function isVertical(legendLayout) { + return legendLayout.orientation !== 'h'; +}; - _$handleArrayContainerDefaults_200(layoutIn, layoutOut, opts); +_$helpers_102.isReversed = function isReversed(legendLayout) { + return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; -function sliderDefaults(sliderIn, sliderOut, layoutOut) { +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function coerce(attr, dflt) { - return _$lib_162.coerce(sliderIn, sliderOut, _$attributes_131, attr, dflt); - } - var steps = stepsDefaults(sliderIn, sliderOut); +'use strict'; - var visible = coerce('visible', steps.length > 0); - if(!visible) return; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; - coerce('active'); +/* removed: var _$attributes_96 = require('./attributes'); */; +/* removed: var _$layout_attributes_235 = require('../../plots/layout_attributes'); */; +/* removed: var _$helpers_102 = require('./helpers'); */; - coerce('x'); - coerce('y'); - _$lib_162.noneOrAll(sliderIn, sliderOut, ['x', 'y']); - coerce('xanchor'); - coerce('yanchor'); +var _$legendDefaults_98 = function legendDefaults(layoutIn, layoutOut, fullData) { + var containerIn = layoutIn.legend || {}; + var containerOut = {}; - coerce('len'); - coerce('lenmode'); + var visibleTraces = 0; + var defaultOrder = 'normal'; - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + var defaultX, defaultY, defaultXAnchor, defaultYAnchor; - _$lib_162.coerceFont(coerce, 'font', layoutOut.font); + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - var currentValueIsVisible = coerce('currentvalue.visible'); + if(_$helpers_102.legendGetsTrace(trace)) { + visibleTraces++; + // always show the legend by default if there's a pie + if(_$registry_245.traceIs(trace, 'pie')) visibleTraces++; + } - if(currentValueIsVisible) { - coerce('currentvalue.xanchor'); - coerce('currentvalue.prefix'); - coerce('currentvalue.suffix'); - coerce('currentvalue.offset'); + if((_$registry_245.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { + defaultOrder = _$helpers_102.isGrouped({traceorder: defaultOrder}) ? + 'grouped+reversed' : 'reversed'; + } - _$lib_162.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + if(trace.legendgroup !== undefined && trace.legendgroup !== '') { + defaultOrder = _$helpers_102.isReversed({traceorder: defaultOrder}) ? + 'reversed+grouped' : 'grouped'; + } } - coerce('transition.duration'); - coerce('transition.easing'); - - coerce('bgcolor'); - coerce('activebgcolor'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('ticklen'); - coerce('tickwidth'); - coerce('tickcolor'); - coerce('minorticklen'); -} - -function stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; - - var valueIn, valueOut; - function coerce(attr, dflt) { - return _$lib_162.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + return _$lib_163.coerce(containerIn, containerOut, _$attributes_96, attr, dflt); } - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; + var showLegend = _$lib_163.coerce(layoutIn, layoutOut, + _$layout_attributes_235, 'showlegend', visibleTraces > 1); - coerce('method'); + if(showLegend === false) return; - if(!_$lib_162.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; - } + layoutOut.legend = containerOut; - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); + _$lib_163.coerceFont(coerce, 'font', layoutOut.font); - valuesOut.push(valueOut); + coerce('orientation'); + if(containerOut.orientation === 'h') { + var xaxis = layoutIn.xaxis; + if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = 1.1; + defaultYAnchor = 'bottom'; + } + else { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = -0.1; + defaultYAnchor = 'top'; + } } - return valuesOut; -} + coerce('traceorder', defaultOrder); + if(_$helpers_102.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); + + coerce('x', defaultX); + coerce('xanchor', defaultXAnchor); + coerce('y', defaultY); + coerce('yanchor', defaultYAnchor); + _$lib_163.noneOrAll(containerIn, containerOut, ['x', 'y']); +}; +var _$anchor_utils_95 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46471,625 +46127,735 @@ function stepsDefaults(sliderIn, sliderOut) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; +/** + * 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. + */ -/* removed: var _$constants_132 = require('./constants'); */; -/* removed: var _$alignment_143 = require('../../constants/alignment'); */; -var __LINE_SPACING_134 = _$alignment_143.LINE_SPACING; -var __FROM_TL_134 = _$alignment_143.FROM_TL; -var __FROM_BR_134 = _$alignment_143.FROM_BR; +_$anchor_utils_95.isRightAnchor = function isRightAnchor(opts) { + return ( + opts.xanchor === 'right' || + (opts.xanchor === 'auto' && opts.x >= 2 / 3) + ); +}; +_$anchor_utils_95.isCenterAnchor = function isCenterAnchor(opts) { + return ( + opts.xanchor === 'center' || + (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) + ); +}; -var _$draw_134 = function draw(gd) { - var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); +_$anchor_utils_95.isBottomAnchor = function isBottomAnchor(opts) { + return ( + opts.yanchor === 'bottom' || + (opts.yanchor === 'auto' && opts.y <= 1 / 3) + ); +}; - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_132.containerClassName) - .data(sliderData.length > 0 ? [0] : []); +_$anchor_utils_95.isMiddleAnchor = function isMiddleAnchor(opts) { + return ( + opts.yanchor === 'middle' || + (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) + ); +}; - sliders.enter().append('g') - .classed(_$constants_132.containerClassName, true) - .style('cursor', 'ew-resize'); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - sliders.exit().remove(); +'use strict'; - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_134(gd); +var _$constants_97 = { + scrollBarWidth: 6, + scrollBarMinHeight: 20, + scrollBarColor: '#808BA4', + scrollBarMargin: 4 +}; - // Return early if no menus visible: - if(sliderData.length === 0) return; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 sliderGroups = sliders.selectAll('g.' + _$constants_132.groupClassName) - .data(sliderData, keyFunction); - sliderGroups.enter().append('g') - .classed(_$constants_132.groupClassName, true); +'use strict'; - sliderGroups.exit().each(function(sliderOpts) { - _$d3_7.select(this).remove(); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$helpers_102 = require('./helpers'); */; - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; - _$plots_237.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index); - }); +var _$getLegendData_100 = function getLegendData(calcdata, opts) { + var lgroupToTraces = {}, + lgroups = [], + hasOneNonBlankGroup = false, + slicesShown = {}, + lgroupi = 0; - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); - } + var i, j; - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; + function addOneItem(legendGroup, legendItem) { + // each '' legend group is treated as a separate group + if(legendGroup === '' || !_$helpers_102.isGrouped(opts)) { + var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? - var gSlider = _$d3_7.select(this); + lgroups.push(uniqueGroup); + lgroupToTraces[uniqueGroup] = [[legendItem]]; + lgroupi++; + } + else if(lgroups.indexOf(legendGroup) === -1) { + lgroups.push(legendGroup); + hasOneNonBlankGroup = true; + lgroupToTraces[legendGroup] = [[legendItem]]; + } + else lgroupToTraces[legendGroup].push([legendItem]); + } - computeLabelSteps(sliderOpts); + // build an { legendgroup: [cd0, cd0], ... } object + for(i = 0; i < calcdata.length; i++) { + var cd = calcdata[i], + cd0 = cd[0], + trace = cd0.trace, + lgroup = trace.legendgroup; - _$plots_237.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; + if(!_$helpers_102.legendGetsTrace(trace) || !trace.showlegend) continue; - if(opts.active === data.index) return; - if(opts._dragging) return; + if(_$registry_245.traceIs(trace, 'pie')) { + if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; - setActive(gd, gSlider, opts, data.index, false, true); - }); + for(j = 0; j < cd.length; j++) { + var labelj = cd[j].label; - drawSlider(gd, _$d3_7.select(this), sliderOpts); - }); -}; + if(!slicesShown[lgroup][labelj]) { + addOneItem(lgroup, { + label: labelj, + color: cd[j].color, + i: cd[j].i, + trace: trace + }); -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_132.name], - sliderData = []; + slicesShown[lgroup][labelj] = true; + } + } + } - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); + else addOneItem(lgroup, cd0); } - return sliderData; -} - -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; -} - -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_68.tester.selectAll('g.' + _$constants_132.labelGroupClass) - .data(sliderOpts.steps); + // won't draw a legend in this case + if(!lgroups.length) return []; - sliderLabels.enter().append('g') - .classed(_$constants_132.labelGroupClass, true); + // rearrange lgroupToTraces into a d3-friendly array of arrays + var lgroupsLength = lgroups.length, + ltraces, + legendData; - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_7.select(this); + if(hasOneNonBlankGroup && _$helpers_102.isGrouped(opts)) { + legendData = new Array(lgroupsLength); - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]]; + legendData[i] = _$helpers_102.isReversed(opts) ? ltraces.reverse() : ltraces; + } + } + else { + // collapse all groups into one if all groups are blank + legendData = [new Array(lgroupsLength)]; - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_68.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]][0]; + legendData[0][_$helpers_102.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; } - }); + lgroupsLength = 1; + } - sliderLabels.remove(); + // needed in repositionLegend + opts._lgroupsLength = lgroupsLength; + return legendData; +}; - var dims = sliderOpts._dims = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - dims.inputAreaWidth = Math.max( - _$constants_132.railWidth, - _$constants_132.gripHeight - ); +'use strict'; - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_245 = require('../../registry'); */; - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; - } +var SHOWISOLATETIP = true; - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); +var _$handleClick_101 = function handleClick(g, gd, numClicks) { + if(gd._dragged || gd._editing) return; - var textableInputLength = dims.inputAreaLength - 2 * _$constants_132.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_132.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; + var hiddenSlices = gd._fullLayout.hiddenlabels ? + gd._fullLayout.hiddenlabels.slice() : + []; - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; + var legendItem = g.data()[0][0]; + var fullData = gd._fullData; + var fullTrace = legendItem.trace; + var legendgroup = fullTrace.legendgroup; - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_68.tester.append('g'); + var i, j, kcont, key, keys, val; + var attrUpdate = {}; + var attrIndices = []; + var carrs = []; + var carrIdx = []; - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_68.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_183.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); + function insertUpdate(traceIndex, key, value) { + var attrIndex = attrIndices.indexOf(traceIndex); + var valueArray = attrUpdate[key]; + if(!valueArray) { + valueArray = attrUpdate[key] = []; + } - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + if(attrIndices.indexOf(traceIndex) === -1) { + attrIndices.push(traceIndex); + attrIndex = attrIndices.length - 1; + } - dummyGroup.remove(); + valueArray[attrIndex] = value; + + return attrIndex; } - dims.height = dims.currentValueTotalHeight + _$constants_132.tickOffset + sliderOpts.ticklen + _$constants_132.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + function setVisibility(fullTrace, visibility) { + var fullInput = fullTrace._fullInput; + if(_$registry_245.hasTransform(fullInput, 'groupby')) { + var kcont = carrs[fullInput.index]; + if(!kcont) { + var groupbyIndices = _$registry_245.getTransformIndices(fullInput, 'groupby'); + var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; + kcont = _$lib_163.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + carrs[fullInput.index] = kcont; + } - var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_95.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } + var curState = kcont.get(fullTrace._group); - var yanchor = 'top'; - if(_$anchor_utils_95.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_95.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; - } + // 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; + } - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + 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; - _$plots_237.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_134[xanchor], - r: dims.outerLength * __FROM_BR_134[xanchor], - b: dims.height * __FROM_BR_134[yanchor], - t: dims.height * __FROM_TL_134[yanchor] - }); -} + insertUpdate(fullInput.index, 'visible', nextVisibility); + } + } -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; + if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { + _$lib_163.notifier(_$lib_163._(gd, 'Double-click on legend to isolate one trace'), 'long'); + SHOWISOLATETIP = false; + } else { + SHOWISOLATETIP = false; } - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); + if(_$registry_245.traceIs(fullTrace, 'pie')) { + var thisLabel = legendItem.label, + thisLabelIndex = hiddenSlices.indexOf(thisLabel); - var dims = sliderOpts._dims; + if(numClicks === 1) { + if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); + else hiddenSlices.splice(thisLabelIndex, 1); + } else if(numClicks === 2) { + 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 = []; + } + } - // Position the rectangle: - _$drawing_68.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + _$registry_245.call('relayout', 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); + } + } + } - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); + if(numClicks === 1) { + var nextVisibility; -} + switch(fullTrace.visible) { + case true: + nextVisibility = 'legendonly'; + break; + case false: + nextVisibility = false; + break; + case 'legendonly': + nextVisibility = true; + break; + } -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; + 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(numClicks === 2) { + // 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, otherState; + var isIsolated = true; + for(i = 0; i < fullData.length; i++) { + isClicked = fullData[i] === fullTrace; + if(isClicked) continue; - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; + isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_132.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; - break; - default: - x0 = _$constants_132.currentValueInset; - textAnchor = 'left'; - } + if(!isInGroup && fullData[i].visible === true && !_$registry_245.traceIs(fullData[i], 'notLegendIsolatable')) { + isIsolated = false; + break; + } + } - text.enter().append('text') - .classed(_$constants_132.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); + for(i = 0; i < fullData.length; i++) { + // False is sticky; we don't change it. + if(fullData[i].visible === false) continue; - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; + if(_$registry_245.traceIs(fullData[i], 'notLegendIsolatable')) { + continue; + } - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } + switch(fullTrace.visible) { + case 'legendonly': + setVisibility(fullData[i], true); + break; + case true: + otherState = isIsolated ? true : 'legendonly'; + isClicked = fullData[i] === fullTrace; + isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); + setVisibility(fullData[i], isInGroup ? true : otherState); + break; + } + } + } - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; - } + for(i = 0; i < carrs.length; i++) { + kcont = carrs[i]; + if(!kcont) continue; + var update = kcont.constructUpdate(); - text.call(_$drawing_68.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_183.convertToTspans, sliderOpts._gd); + 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]; + } + } - var lines = _$svg_text_utils_183.lineCount(text); + // 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; + } + } + } - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_134; + _$registry_245.call('restyle', gd, attrUpdate, attrIndices); + } +}; - _$svg_text_utils_183.positionText(text, x0, y0); +var _$helpers_273 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 text; -} +'use strict'; -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_132.gripRectClass) - .data([0]); +/* removed: var _$lib_163 = require('../../lib'); */; - grip.enter().append('rect') - .classed(_$constants_132.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); +_$helpers_273.formatPiePercent = function formatPiePercent(v, separators) { + var vRounded = (v * 100).toPrecision(3); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_163.numSeparate(vRounded, separators) + '%'; +}; - grip.attr({ - width: _$constants_132.gripWidth, - height: _$constants_132.gripHeight, - rx: _$constants_132.gripRadius, - ry: _$constants_132.gripRadius, - }) - .call(_$color_43.stroke, sliderOpts.bordercolor) - .call(_$color_43.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); -} +_$helpers_273.formatPieValue = function formatPieValue(v, separators) { + var vRounded = v.toPrecision(10); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_163.numSeparate(vRounded, separators); +}; -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); +_$helpers_273.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) return v; + } +}; - text.enter().append('text') - .classed(_$constants_132.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); +_$helpers_273.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_273.getFirstFilled(item, indices); + else if(item) return item; +}; - text.call(_$drawing_68.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_183.convertToTspans, sliderOpts._gd); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 text; -} +'use strict'; -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_132.labelsClass) - .data([0]); - var dims = sliderOpts._dims; +/* removed: var _$color_43 = require('../../components/color'); */; +var castOption = _$helpers_273.castOption; - labels.enter().append('g') - .classed(_$constants_132.labelsClass, true); +var _$styleOne_279 = function styleOne(s, pt, trace) { + var line = trace.marker.line; + var lineColor = castOption(line.color, pt.pts) || _$color_43.defaultLine; + var lineWidth = castOption(line.width, pt.pts) || 0; - var labelItems = labels.selectAll('g.' + _$constants_132.labelGroupClass) - .data(dims.labelSteps); + s.style({'stroke-width': lineWidth}) + .call(_$color_43.fill, pt.color) + .call(_$color_43.stroke, lineColor); +}; - labelItems.enter().append('g') - .classed(_$constants_132.labelGroupClass, true); - - labelItems.exit().remove(); - - labelItems.each(function(d) { - var item = _$d3_7.select(this); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - item.call(drawLabel, d, sliderOpts); +'use strict'; - _$drawing_68.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_132.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_134 + - _$constants_132.labelOffset + - dims.currentValueTotalHeight - ); - }); +/* removed: var _$d3_7 = require('d3'); */; -} +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$color_43 = require('../color'); */; -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_279 = require('../../traces/pie/style_one'); */; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); - } -} +var _$style_104 = function style(s, gd) { + s.each(function(d) { + var traceGroup = _$d3_7.select(this); -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; + var layers = _$lib_163.ensureSingle(traceGroup, 'g', 'layers'); + layers.style('opacity', d[0].trace.opacity); - var step = sliderOpts.steps[sliderOpts.active]; + var fill = layers + .selectAll('g.legendfill') + .data([d]); + fill.enter().append('g') + .classed('legendfill', true); - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + var line = layers + .selectAll('g.legendlines') + .data([d]); + line.enter().append('g') + .classed('legendlines', true); - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive - }); + var symbol = layers + .selectAll('g.legendsymbols') + .data([d]); + symbol.enter().append('g') + .classed('legendsymbols', true); - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; + symbol.selectAll('g.legendpoints') + .data([d]) + .enter().append('g') + .classed('legendpoints', true); + }) + .each(styleBars) + .each(styleBoxes) + .each(stylePies) + .each(styleLines) + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); - if(_step.execute) { - _$plots_237.executeAPICommand(gd, _step.method, _step.args); - } + function styleLines(d) { + var trace = d[0].trace; + var showFill = trace.visible && trace.fill && trace.fill !== 'none'; + var showLine = _$subtypes_303.hasLines(trace); + var contours = trace.contours; - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); + if(contours && contours.type === 'constraint') { + showLine = contours.showlines; + showFill = contours._operation !== '='; } - } -} -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_7.select(gd); + var fill = _$d3_7.select(this).select('.legendfill').selectAll('path') + .data(showFill ? [d] : []); + fill.enter().append('path').classed('js-fill', true); + fill.exit().remove(); + fill.attr('d', 'M5,0h30v6h-30z') + .call(_$drawing_68.fillGroupStyle); - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; + var line = _$d3_7.select(this).select('.legendlines').selectAll('path') + .data(showLine ? [d] : []); + line.enter().append('path').classed('js-line', true) + .attr('d', 'M5,0h30'); + line.exit().remove(); + line.call(_$drawing_68.lineGroupStyle); } - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); - - var grip = sliderGroup.select('.' + _$constants_132.gripRectClass); - - _$d3_7.event.stopPropagation(); - _$d3_7.event.preventDefault(); - grip.call(_$color_43.fill, sliderOpts.activebgcolor); + function stylePoints(d) { + var d0 = d[0], + trace = d0.trace, + showMarkers = _$subtypes_303.hasMarkers(trace), + showText = _$subtypes_303.hasText(trace), + showLines = _$subtypes_303.hasLines(trace); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_7.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; + var dMod, tMod; - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_7.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; + // use d0.trace to infer arrayOk attributes - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_43.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + function boundVal(attrIn, arrayToValFn, bounds) { + var valIn = _$lib_163.nestedProperty(trace, attrIn).get(), + valToBound = (Array.isArray(valIn) && arrayToValFn) ? + arrayToValFn(valIn) : valIn; - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); -} + if(bounds) { + if(valToBound < bounds[0]) return bounds[0]; + else if(valToBound > bounds[1]) return bounds[1]; + } + return valToBound; + } -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_132.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; + function pickFirst(array) { return array[0]; } - tick.enter().append('rect') - .classed(_$constants_132.tickRectClass, true); + // constrain text, markers, etc so they'll fit on the legend + if(showMarkers || showText || showLines) { + var dEdit = {}, + tEdit = {}; - tick.exit().remove(); + if(showMarkers) { + dEdit.mc = boundVal('marker.color', pickFirst); + dEdit.mo = boundVal('marker.opacity', _$lib_163.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_163.mean, [2, 16]); + dEdit.mlc = boundVal('marker.line.color', pickFirst); + dEdit.mlw = boundVal('marker.line.width', _$lib_163.mean, [0, 5]); + tEdit.marker = { + sizeref: 1, + sizemin: 1, + sizemode: 'diameter' + }; + } - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' - }); + if(showLines) { + tEdit.line = { + width: boundVal('line.width', pickFirst, [0, 10]) + }; + } - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_7.select(this); + if(showText) { + dEdit.tx = 'Aa'; + dEdit.tp = boundVal('textposition', pickFirst); + dEdit.ts = 10; + dEdit.tc = boundVal('textfont.color', pickFirst); + dEdit.tf = boundVal('textfont.family', pickFirst); + } - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_43.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + dMod = [_$lib_163.minExtend(d0, dEdit)]; + tMod = _$lib_163.minExtend(trace, tEdit); + } - _$drawing_68.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_132.tickOffset : _$constants_132.minorTickOffset) + dims.currentValueTotalHeight - ); - }); + var ptgroup = _$d3_7.select(this).select('g.legendpoints'); -} + var pts = ptgroup.selectAll('path.scatterpts') + .data(showMarkers ? dMod : []); + pts.enter().append('path').classed('scatterpts', true) + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.call(_$drawing_68.pointStyle, tMod, gd); -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; + // 'mrc' is set in pointStyle and used in textPointStyle: + // constrain it here + if(showMarkers) dMod[0].mrc = 3; - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); + var txt = ptgroup.selectAll('g.pointtext') + .data(showText ? dMod : []); + txt.enter() + .append('g').classed('pointtext', true) + .append('text').attr('transform', 'translate(20,0)'); + txt.exit().remove(); + txt.selectAll('text').call(_$drawing_68.textPointStyle, tMod, gd); } -} -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_132.gripRectClass); - - var x = normalizedValueToPosition(sliderOpts, position); + function styleBars(d) { + var trace = d[0].trace, + marker = trace.marker || {}, + markerLine = marker.line || {}, + barpath = _$d3_7.select(this).select('g.legendpoints') + .selectAll('path.legendbar') + .data(_$registry_245.traceIs(trace, 'bar') ? [d] : []); + barpath.enter().append('path').classed('legendbar', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + barpath.exit().remove(); + barpath.each(function(d) { + var p = _$d3_7.select(this), + d0 = d[0], + w = (d0.mlw + 1 || markerLine.width + 1) - 1; - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; + p.style('stroke-width', w + 'px') + .call(_$color_43.fill, d0.mc || marker.color); - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); + if(w) { + p.call(_$color_43.stroke, d0.mlc || markerLine.color); + } + }); } - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_132.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); -} - -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_132.stepInset + - (dims.inputAreaLength - 2 * _$constants_132.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} - -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_132.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_132.stepInset - 2 * dims.inputAreaStart))); -} - -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_132.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; - - rect.enter().append('rect') - .classed(_$constants_132.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + function styleBoxes(d) { + var trace = d[0].trace, + pts = _$d3_7.select(this).select('g.legendpoints') + .selectAll('path.legendbox') + .data(_$registry_245.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendbox', true) + // if we want the median bar, prepend M6,0H-6 + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.each(function() { + var w = trace.line.width, + p = _$d3_7.select(this); - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_132.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_43.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + p.style('stroke-width', w + 'px') + .call(_$color_43.fill, trace.fillcolor); - _$drawing_68.setTranslate(rect, 0, dims.currentValueTotalHeight); -} + if(w) { + _$color_43.stroke(p, trace.line.color); + } + }); + } -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_132.railRectClass) - .data([0]); - var dims = sliderOpts._dims; + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_7.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_7.select(this); - rect.enter().append('rect') - .classed(_$constants_132.railRectClass, true); + p.style('stroke-width', w + 'px') + .call(_$color_43.fill, container.fillcolor); - var computedLength = dims.inputAreaLength - _$constants_132.railInset * 2; + if(w) { + _$color_43.stroke(p, container.line.color); + } + }); + } - rect.attr({ - width: computedLength, - height: _$constants_132.railWidth, - rx: _$constants_132.railRadius, - ry: _$constants_132.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_43.stroke, sliderOpts.bordercolor) - .call(_$color_43.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_7.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_7.select(this); - _$drawing_68.setTranslate(rect, - _$constants_132.railInset, - (dims.inputAreaWidth - _$constants_132.railWidth) * 0.5 + dims.currentValueTotalHeight - ); -} + p.style('fill', 'none') + .call(_$drawing_68.dashLine, container.line.dash, w); -function __clearPushMargins_134(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + if(w) { + _$color_43.stroke(p, container.line.color); + } + }); + } - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + function stylePies(d) { + var trace = d[0].trace, + pts = _$d3_7.select(this).select('g.legendpoints') + .selectAll('path.legendpie') + .data(_$registry_245.traceIs(trace, 'pie') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendpie', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); - if(k.indexOf(_$constants_132.autoMarginIdRoot) !== -1) { - _$plots_237.autoMargin(gd, k); - } + if(pts.size()) pts.call(_$styleOne_279, d[0], trace); } -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -47101,815 +46867,860 @@ function __clearPushMargins_134(gd) { 'use strict'; -/* removed: var _$constants_132 = require('./constants'); */; +/* removed: var _$d3_7 = require('d3'); */; -var _$sliders_135 = { - moduleType: 'component', - name: _$constants_132.name, +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$handleClick_101 = require('./handle_click'); */; - layoutAttributes: _$attributes_131, - supplyLayoutDefaults: _$slidersDefaults_133, +/* removed: var _$constants_97 = require('./constants'); */; +/* removed: var _$interactions_144 = require('../../constants/interactions'); */; +/* removed: var _$alignment_143 = require('../../constants/alignment'); */; +var __LINE_SPACING_99 = _$alignment_143.LINE_SPACING; +var __FROM_TL_99 = _$alignment_143.FROM_TL; +var FROM_BR = _$alignment_143.FROM_BR; - draw: _$draw_134 -}; +/* removed: var _$getLegendData_100 = require('./get_legend_data'); */; +/* removed: var _$style_104 = require('./style'); */; +/* removed: var _$helpers_102 = require('./helpers'); */; +/* removed: var _$anchor_utils_95 = require('./anchor_utils'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 DBLCLICKDELAY = _$interactions_144.DBLCLICKDELAY; -'use strict'; +var _$draw_99 = function draw(gd) { + var fullLayout = gd._fullLayout; + var clipId = 'legend' + fullLayout._uid; -/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_42 = require('../color/attributes'); */; -var __extendFlat_137 = _$extend_156.extendFlat; -var __overrideAll_137 = _$edit_types_189.overrideAll; -/* removed: var _$pad_attributes_236 = require('../../plots/pad_attributes'); */; + if(!fullLayout._infolayer || !gd.calcdata) return; -var buttonsAttrs = { - _isLinkedToArray: 'button', + if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} - ], - - }, - label: { - valType: 'string', - - dflt: '', - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; + var opts = fullLayout.legend, + legendData = fullLayout.showlegend && _$getLegendData_100(gd.calcdata, opts), + hiddenSlices = fullLayout.hiddenlabels || []; -var _$attributes_137 = __overrideAll_137({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], + if(!fullLayout.showlegend || !legendData.length) { + fullLayout._infolayer.selectAll('.legend').remove(); + fullLayout._topdefs.select('#' + clipId).remove(); - visible: { - valType: 'boolean', - - - }, + _$plots_237.autoMargin(gd, 'legend'); + return; + } - type: { - valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', - - - }, + var firstRender = false; + var legend = _$lib_163.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - direction: { - valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', - - - }, + var clipPath = _$lib_163.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - active: { - valType: 'integer', - - min: -1, - dflt: 0, - - }, + var bg = _$lib_163.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); - showactive: { - valType: 'boolean', - - dflt: true, - - }, + bg.call(_$color_43.stroke, opts.bordercolor) + .call(_$color_43.fill, opts.bgcolor) + .style('stroke-width', opts.borderwidth + 'px'); - buttons: buttonsAttrs, + var scrollBox = _$lib_163.ensureSingle(legend, 'g', 'scrollbox'); - x: { - valType: 'number', - min: -2, - max: 3, - dflt: -0.05, - - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'right', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, - - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, + var scrollBar = _$lib_163.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ + rx: 20, + ry: 3, + width: 0, + height: 0 + }) + .call(_$color_43.fill, '#808BA4'); + }); - pad: __extendFlat_137({}, _$pad_attributes_236, { - - }), + var groups = scrollBox.selectAll('g.groups') + .data(legendData); - font: _$font_attributes_231({ - - }), + groups.enter().append('g') + .attr('class', 'groups'); - bgcolor: { - valType: 'color', - - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_42.borderLine, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'arraydraw', - - } -}, 'arraydraw', 'from-root'); + groups.exit().remove(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 traces = groups.selectAll('g.traces') + .data(_$lib_163.identity); + traces.enter().append('g').attr('class', 'traces'); + traces.exit().remove(); -'use strict'; + traces.call(_$style_104, gd) + .style('opacity', function(d) { + var trace = d[0].trace; + if(_$registry_245.traceIs(trace, 'pie')) { + return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; + } else { + return trace.visible === 'legendonly' ? 0.5 : 1; + } + }) + .each(function() { + _$d3_7.select(this) + .call(drawTexts, gd) + .call(setupTraceToggle, gd); + }); + if(firstRender) { + computeLegendDimensions(gd, groups, traces); + expandMargin(gd); + } -var _$constants_138 = { + // Position and size the legend + var lxMin = 0, + lxMax = fullLayout.width, + lyMin = 0, + lyMax = fullLayout.height; - // layout attribute name - name: 'updatemenus', + computeLegendDimensions(gd, groups, traces); - // 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', + if(opts._height > lyMax) { + // If the legend doesn't fit in the plot area, + // do not expand the vertical margins. + expandHorizontalMargin(gd); + } else { + expandMargin(gd); + } - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'updatemenu-active-index', + // Scroll section must be executed after repositionLegend. + // It requires the legend width, height, x and y to position the scrollbox + // and these values are mutated in repositionLegend. + var gs = fullLayout._size, + lx = gs.l + gs.w * opts.x, + ly = gs.t + gs.h * (1 - opts.y); - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'updatemenu-', + if(_$anchor_utils_95.isRightAnchor(opts)) { + lx -= opts._width; + } + else if(_$anchor_utils_95.isCenterAnchor(opts)) { + lx -= opts._width / 2; + } - // options when 'active: -1' - blankHeaderOpts: { label: ' ' }, + if(_$anchor_utils_95.isBottomAnchor(opts)) { + ly -= opts._height; + } + else if(_$anchor_utils_95.isMiddleAnchor(opts)) { + ly -= opts._height / 2; + } - // min item width / height - minWidth: 30, - minHeight: 30, + // Make sure the legend left and right sides are visible + var legendWidth = opts._width, + legendWidthMax = gs.w; - // padding around item text - textPadX: 24, - arrowPadX: 16, + if(legendWidth > legendWidthMax) { + lx = gs.l; + legendWidth = legendWidthMax; + } + else { + if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; + if(lx < lxMin) lx = lxMin; + legendWidth = Math.min(lxMax - lx, opts._width); + } - // item rect radii - rx: 2, - ry: 2, + // Make sure the legend top and bottom are visible + // (legends with a scroll bar are not allowed to stretch beyond the extended + // margins) + var legendHeight = opts._height, + legendHeightMax = gs.h; - // item text x offset off left edge - textOffsetX: 12, + if(legendHeight > legendHeightMax) { + ly = gs.t; + legendHeight = legendHeightMax; + } + else { + if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; + if(ly < lyMin) ly = lyMin; + legendHeight = Math.min(lyMax - ly, opts._height); + } - // item text y offset (w.r.t. middle) - textOffsetY: 3, + // Set size and position of all the elements that make up a legend: + // legend, background and border, scroll box and scroll bar + _$drawing_68.setTranslate(legend, lx, ly); - // arrow offset off right edge - arrowOffsetX: 4, + // to be safe, remove previous listeners + scrollBar.on('.drag', null); + legend.on('wheel', null); - // gap between header and buttons - gapButtonHeader: 5, + if(opts._height <= legendHeight || gd._context.staticPlot) { + // if scrollbar should not be shown. + bg.attr({ + width: legendWidth - opts.borderwidth, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - // gap between between buttons - gapButton: 2, + _$drawing_68.setTranslate(scrollBox, 0, 0); - // color given to active buttons - activeColor: '#F4FAFF', + clipPath.select('rect').attr({ + width: legendWidth - 2 * opts.borderwidth, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + }); - // color given to hovered buttons - hoverColor: '#F4FAFF', + _$drawing_68.setClipUrl(scrollBox, clipId); - // symbol for menu open arrow - arrowSymbol: { - left: '◄', - right: '►', - up: '▲', - down: '▼' + _$drawing_68.setRect(scrollBar, 0, 0, 0, 0); + delete opts._scrollY; } -}; + else { + var scrollBarHeight = Math.max(_$constants_97.scrollBarMinHeight, + legendHeight * legendHeight / opts._height); + var scrollBarYMax = legendHeight - + scrollBarHeight - + 2 * _$constants_97.scrollBarMargin; + var scrollBoxYMax = opts._height - legendHeight; + var scrollRatio = scrollBarYMax / scrollBoxYMax; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); -'use strict'; + // increase the background and clip-path width + // by the scrollbar width and margin + bg.attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_97.scrollBarWidth + + _$constants_97.scrollBarMargin, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_200 = require('../../plots/array_container_defaults'); */; + clipPath.select('rect').attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_97.scrollBarWidth + + _$constants_97.scrollBarMargin, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + scrollBoxY + }); -/* removed: var _$attributes_137 = require('./attributes'); */; -/* removed: var _$constants_138 = require('./constants'); */; + _$drawing_68.setClipUrl(scrollBox, clipId); -var __name_139 = _$constants_138.name; -var __buttonAttrs_139 = _$attributes_137.buttons; + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + legend.on('wheel', function() { + scrollBoxY = _$lib_163.constrain( + opts._scrollY + + _$d3_7.event.deltaY / scrollBarYMax * scrollBoxYMax, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { + _$d3_7.event.preventDefault(); + } + }); -var _$updateMenusDefaults_139 = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_139, - handleItemDefaults: menuDefaults - }; + var eventY0, scrollBoxY0; - _$handleArrayContainerDefaults_200(layoutIn, layoutOut, opts); -}; + var drag = _$d3_7.behavior.drag() + .on('dragstart', function() { + eventY0 = _$d3_7.event.sourceEvent.clientY; + scrollBoxY0 = scrollBoxY; + }) + .on('drag', function() { + var e = _$d3_7.event.sourceEvent; + if(e.buttons === 2 || e.ctrlKey) return; -function menuDefaults(menuIn, menuOut, layoutOut) { + scrollBoxY = _$lib_163.constrain( + (e.clientY - eventY0) / scrollRatio + scrollBoxY0, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + }); - function coerce(attr, dflt) { - return _$lib_162.coerce(menuIn, menuOut, _$attributes_137, attr, dflt); + scrollBar.call(drag); } - var buttons = __buttonsDefaults_139(menuIn, menuOut); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - - coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); - coerce('x'); - coerce('y'); - _$lib_162.noneOrAll(menuIn, menuOut, ['x', 'y']); + function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { + opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; + _$drawing_68.setTranslate(scrollBox, 0, -scrollBoxY); - coerce('xanchor'); - coerce('yanchor'); + _$drawing_68.setRect( + scrollBar, + legendWidth, + _$constants_97.scrollBarMargin + scrollBoxY * scrollRatio, + _$constants_97.scrollBarWidth, + scrollBarHeight + ); + clipPath.select('rect').attr({ + y: opts.borderwidth + scrollBoxY + }); + } - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + if(gd._context.edits.legendPosition) { + var xf, yf, x0, y0; - _$lib_162.coerceFont(coerce, 'font', layoutOut.font); + legend.classed('cursor-move', true); - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); -} + _$dragelement_65.init({ + element: legend.node(), + gd: gd, + prepFn: function() { + var transform = _$drawing_68.getTranslate(legend); -function __buttonsDefaults_139(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; + x0 = transform.x; + y0 = transform.y; + }, + moveFn: function(dx, dy) { + var newX = x0 + dx, + newY = y0 + dy; - var buttonIn, buttonOut; + _$drawing_68.setTranslate(legend, newX, newY); - function coerce(attr, dflt) { - return _$lib_162.coerce(buttonIn, buttonOut, __buttonAttrs_139, attr, dflt); + xf = _$dragelement_65.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); + yf = _$dragelement_65.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); + }, + doneFn: function() { + if(xf !== undefined && yf !== undefined) { + _$registry_245.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + } + }, + clickFn: function(numClicks, e) { + var clickedTrace = + fullLayout._infolayer.selectAll('g.traces').filter(function() { + var bbox = this.getBoundingClientRect(); + return (e.clientX >= bbox.left && e.clientX <= bbox.right && + e.clientY >= bbox.top && e.clientY <= bbox.bottom); + }); + if(clickedTrace.size() > 0) { + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { + _$handleClick_101(clickedTrace, gd, numClicks); + }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + _$handleClick_101(clickedTrace, gd, numClicks); + } + } + } + }); } +}; - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; - - coerce('method'); +function drawTexts(g, gd) { + var legendItem = g.data()[0][0], + fullLayout = gd._fullLayout, + trace = legendItem.trace, + isPie = _$registry_245.traceIs(trace, 'pie'), + traceIndex = trace.index, + name = isPie ? legendItem.label : trace.name; - if(!_$lib_162.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { - continue; - } + var text = _$lib_163.ensureSingle(g, 'text', 'legendtext'); - coerce('args'); - coerce('label'); - coerce('execute'); + text.attr('text-anchor', 'start') + .classed('user-select-none', true) + .call(_$drawing_68.font, fullLayout.legend.font) + .text(name); - buttonOut._index = i; - buttonsOut.push(buttonOut); + function textLayout(s) { + _$svg_text_utils_184.convertToTspans(s, gd, function() { + computeTextDimensions(g, gd); + }); } - return buttonsOut; -} + if(gd._context.edits.legendText && !isPie) { + text.call(_$svg_text_utils_184.makeEditable, {gd: gd}) + .call(textLayout) + .on('edit', function(text) { + this.text(text) + .call(textLayout); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 origText = text; -'use strict'; + if(!this.text()) text = ' \u0020\u0020 '; -var _$ScrollBox_142 = ScrollBox; + var fullInput = legendItem.trace._fullInput || {}; + var update = {}; -/* removed: var _$d3_7 = require('d3'); */; + if(_$registry_245.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_245.getTransformIndices(fullInput, 'groupby'); + var index = groupbyIndices[groupbyIndices.length - 1]; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; + var kcont = _$lib_163.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); -/* removed: var _$lib_162 = require('../../lib'); */; + if(origText === '') { + kcont.remove(legendItem.trace._group); + } else { + kcont.set(legendItem.trace._group, text); + } -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; + update = kcont.constructUpdate(); + } else { + update.name = text; + } - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection + return _$registry_245.call('restyle', gd, update, traceIndex); + }); + } else { + textLayout(text); + } +} - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); +function setupTraceToggle(g, gd) { + var newMouseDownTime, + numClicks = 1; - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); + var traceToggle = _$lib_163.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_43.fill, 'rgba(0,0,0,0)'); + }); - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} + traceToggle.on('mousedown', function() { + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { + // 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; -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; + if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; - - // compute position of scrollbox - this.position = position; + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { _$handleClick_101(g, gd, numClicks); }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + gd._legendMouseDownTime = 0; + _$handleClick_101(g, gd, numClicks); + } + }); +} - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; +function computeTextDimensions(g, gd) { + var legendItem = g.data()[0][0]; - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; + if(!legendItem.trace.showlegend) { + g.remove(); + return; } - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; + var mathjaxGroup = g.select('g[class*=math-group]'); + var mathjaxNode = mathjaxGroup.node(); + var opts = gd._fullLayout.legend; + var lineHeight = opts.font.size * __LINE_SPACING_99; + var height, width; - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } + if(mathjaxNode) { + var mathjaxBB = _$drawing_68.bBox(mathjaxNode); + + height = mathjaxBB.height; + width = mathjaxBB.width; + + _$drawing_68.setTranslate(mathjaxGroup, 0, (height / 4)); } else { - boxT = t; - boxB = boxT + boxH; + var text = g.select('.legendtext'); + var textLines = _$svg_text_utils_184.lineCount(text); + var textNode = text.node(); - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; - } + height = lineHeight * textLines; + width = textNode ? _$drawing_68.bBox(textNode).width : 0; + + // approximation to height offset to center the font + // to avoid getBoundingClientRect + var textY = lineHeight * (0.3 + (1 - textLines) / 2); + // TODO: this 40 should go in a constants file (along with other + // values related to the legend symbol size) + _$svg_text_utils_184.positionText(text, 40, textY); } - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; + height = Math.max(height, 16) + 3; - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; + legendItem.height = height; + legendItem.width = width; +} - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; +function computeLegendDimensions(gd, groups, traces) { + var fullLayout = gd._fullLayout; + var opts = fullLayout.legend; + var borderwidth = opts.borderwidth; + var isGrouped = _$helpers_102.isGrouped(opts); - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); + var extraWidth = 0; - hbar.exit() - .on('.drag', null) - .remove(); + opts._width = 0; + opts._height = 0; - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_43.fill, ScrollBox.barColor); + if(_$helpers_102.isVertical(opts)) { + if(isGrouped) { + groups.each(function(d, i) { + _$drawing_68.setTranslate(this, 0, i * opts.tracegroupgap); + }); + } - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH - }); + traces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height, + textWidth = legendItem.width; - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } + _$drawing_68.setTranslate(this, + borderwidth, + (5 + borderwidth + opts._height + textHeight / 2)); - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; + opts._height += textHeight; + opts._width = Math.max(opts._width, textWidth); + }); - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + opts._width += 45 + borderwidth * 2; + opts._height += 10 + borderwidth * 2; - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); + if(isGrouped) { + opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; + } - vbar.exit() - .on('.drag', null) - .remove(); + extraWidth = 40; + } + else if(isGrouped) { + var groupXOffsets = [opts._width], + groupData = groups.data(); - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_43.fill, ScrollBox.barColor); + for(var i = 0, n = groupData.length; i < n; i++) { + var textWidths = groupData[i].map(function(legendItemArray) { + return legendItemArray[0].width; + }); - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH - }); + var groupWidth = 40 + Math.max.apply(null, textWidths); - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } + opts._width += opts.tracegroupgap + groupWidth; - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + groupXOffsets.push(opts._width); + } - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + groups.each(function(d, i) { + _$drawing_68.setTranslate(this, groupXOffsets[i], 0); + }); - clipPath.exit().remove(); + groups.each(function() { + var group = _$d3_7.select(this), + groupTraces = group.selectAll('g.traces'), + groupHeight = 0; - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + groupTraces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height; - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + _$drawing_68.setTranslate(this, + 0, + (5 + borderwidth + groupHeight + textHeight / 2)); - this.container.call(_$drawing_68.setClipUrl, clipId); + groupHeight += textHeight; + }); - this.bg.attr({ - x: l, - y: t, - width: w, - height: h + opts._height = Math.max(opts._height, groupHeight); }); + + opts._height += 10 + borderwidth * 2; + opts._width += borderwidth * 2; } else { - this.bg.attr({ - width: 0, - height: 0 + var rowHeight = 0, + maxTraceHeight = 0, + maxTraceWidth = 0, + offsetX = 0, + fullTracesWidth = 0, + traceGap = opts.tracegroupgap || 5, + oneRowLegend; + + // calculate largest width for traces and use for width of all legend items + traces.each(function(d) { + maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); + fullTracesWidth += 40 + d[0].width + traceGap; }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_68.setClipUrl, null); - delete this._clipRect; - } - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_7.behavior.drag() - .on('dragstart', function() { - _$d3_7.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + // check if legend fits in one row + oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; + traces.each(function(d) { + var legendItem = d[0], + traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { + offsetX = 0; + rowHeight = rowHeight + maxTraceHeight; + opts._height = opts._height + maxTraceHeight; + // reset for next row + maxTraceHeight = 0; + } - var onBarDrag = _$d3_7.behavior.drag() - .on('dragstart', function() { - _$d3_7.event.sourceEvent.preventDefault(); - _$d3_7.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + _$drawing_68.setTranslate(this, + (borderwidth + offsetX), + (5 + borderwidth + legendItem.height / 2) + rowHeight); - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); - } + opts._width += traceGap + traceWidth; + opts._height = Math.max(opts._height, legendItem.height); - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); - } - } + // keep track of tallest trace in group + offsetX += traceGap + traceWidth; + maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); + }); - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + opts._width += borderwidth * 2; + opts._height += 10 + borderwidth * 2; -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_68.setClipUrl, null); - delete this._clipRect; } - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } + // make sure we're only getting full pixels + opts._width = Math.ceil(opts._width); + opts._height = Math.ceil(opts._height); - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } -}; + traces.each(function(d) { + var legendItem = d[0], + bg = _$d3_7.select(this).select('.legendtoggle'); -/** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + _$drawing_68.setRect(bg, + 0, + -legendItem.height / 2, + (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, + legendItem.height + ); + }); +} - if(this.hbar) { - translateX -= _$d3_7.event.dx; +function expandMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; + + var xanchor = 'left'; + if(_$anchor_utils_95.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_95.isCenterAnchor(opts)) { + xanchor = 'center'; } - if(this.vbar) { - translateY -= _$d3_7.event.dy; + var yanchor = 'top'; + if(_$anchor_utils_95.isBottomAnchor(opts)) { + yanchor = 'bottom'; + } + else if(_$anchor_utils_95.isMiddleAnchor(opts)) { + yanchor = 'middle'; } - this.setTranslate(translateX, translateY); -}; + // lastly check if the margin auto-expand has changed + _$plots_237.autoMargin(gd, 'legend', { + x: opts.x, + y: opts.y, + l: opts._width * (__FROM_TL_99[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: opts._height * (FROM_BR[yanchor]), + t: opts._height * (__FROM_TL_99[yanchor]) + }); +} -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; +function expandHorizontalMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - if(this.hbar) { - translateX += _$d3_7.event.deltaY; + var xanchor = 'left'; + if(_$anchor_utils_95.isRightAnchor(opts)) { + xanchor = 'right'; } - - if(this.vbar) { - translateY += _$d3_7.event.deltaY; + else if(_$anchor_utils_95.isCenterAnchor(opts)) { + xanchor = 'center'; } - this.setTranslate(translateX, translateY); -}; + // lastly check if the margin auto-expand has changed + _$plots_237.autoMargin(gd, 'legend', { + x: opts.x, + y: 0.5, + l: opts._width * (__FROM_TL_99[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: 0, + t: 0 + }); +} /** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; - - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_162.constrain(_$d3_7.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); +* Copyright 2012-2018, Plotly, Inc. +* All 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 translateXMax = this.position.w - this._box.w; - translateX = xf * translateXMax; - } +'use strict'; - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_162.constrain(_$d3_7.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); - var translateYMax = this.position.h - this._box.h; +var _$legend_103 = { + moduleType: 'component', + name: 'legend', - translateY = yf * translateYMax; - } + layoutAttributes: _$attributes_96, + supplyLayoutDefaults: _$legendDefaults_98, - this.setTranslate(translateX, translateY); + draw: _$draw_99, + style: _$style_104 }; /** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - translateX = _$lib_162.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_162.constrain(translateY || 0, 0, translateYMax); +'use strict'; - this.translateX = translateX; - this.translateY = translateY; - this.container.call(_$drawing_68.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); +var _$button_attributes_110 = { + step: { + valType: 'enumerated', + + values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], + dflt: 'month', + editType: 'plot', + + }, + stepmode: { + valType: 'enumerated', + + values: ['backward', 'todate'], + dflt: 'backward', + editType: 'plot', + + }, + count: { + valType: 'number', + + min: 0, + dflt: 1, + editType: 'plot', + + }, + label: { + valType: 'string', + + editType: 'plot', + + }, + editType: 'plot' +}; - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) - }); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(this.hbar) { - var xf = translateX / translateXMax; +'use strict'; - this.hbar.call(_$drawing_68.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); - } +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_42 = require('../color/attributes'); */; +var __extendFlat_109 = _$extend_157.extendFlat; +/* removed: var _$button_attributes_110 = require('./button_attributes'); */; - if(this.vbar) { - var yf = translateY / translateYMax; +_$button_attributes_110 = __extendFlat_109(_$button_attributes_110, { + _isLinkedToArray: 'button', - this.vbar.call(_$drawing_68.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); - } + +}); + +var _$attributes_109 = { + visible: { + valType: 'boolean', + + editType: 'plot', + + }, + + buttons: _$button_attributes_110, + + x: { + valType: 'number', + min: -2, + max: 3, + + editType: 'plot', + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + editType: 'plot', + + }, + y: { + valType: 'number', + min: -2, + max: 3, + + editType: 'plot', + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'bottom', + + editType: 'plot', + + }, + + font: _$font_attributes_231({ + editType: 'plot', + + }), + + bgcolor: { + valType: 'color', + dflt: _$attributes_42.lightLine, + + editType: 'plot', + + }, + activecolor: { + valType: 'color', + + editType: 'plot', + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_42.defaultLine, + + editType: 'plot', + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'plot', + + }, + editType: 'plot' }; /** @@ -47920,684 +47731,434 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; - -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; -var __LINE_SPACING_140 = _$alignment_143.LINE_SPACING; +var _$constants_111 = { -/* removed: var _$constants_138 = require('./constants'); */; -/* removed: var _$ScrollBox_142 = require('./scrollbox'); */; + // 'y' position pad above counter axis domain + yPad: 0.02, -var _$draw_140 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); + // minimum button width (regardless of text size) + minButtonWidth: 30, - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ + // buttons rect radii + rx: 3, + ry: 3, - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_138.containerClassName) - .data(menuData.length > 0 ? [0] : []); + // light fraction used to compute the 'activecolor' default + lightAmount: 25, + darkAmount: 10 +}; - menus.enter().append('g') - .classed(_$constants_138.containerClassName, true) - .style('cursor', 'pointer'); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - menus.exit().remove(); +'use strict'; - // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_140(gd); +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$color_43 = require('../color'); */; - // return early if no update menus are visible - if(menuData.length === 0) return; +/* removed: var _$attributes_109 = require('./attributes'); */; +/* removed: var _$button_attributes_110 = require('./button_attributes'); */; +/* removed: var _$constants_111 = require('./constants'); */; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_138.headerGroupClassName) - .data(menuData, __keyFunction_140); - headerGroups.enter().append('g') - .classed(_$constants_138.headerGroupClassName, true); +var _$handleDefaults_112 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { + var selectorIn = containerIn.rangeselector || {}, + selectorOut = containerOut.rangeselector = {}; - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_138.dropdownButtonGroupClassName) - .data([0]); + function coerce(attr, dflt) { + return _$lib_163.coerce(selectorIn, selectorOut, _$attributes_109, attr, dflt); + } - gButton.enter().append('g') - .classed(_$constants_138.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_140(gd, menuOpts); - } + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_142(gd, gButton, scrollBoxId); + var posDflt = getPosDflt(containerOut, layout, counterAxes); + coerce('x', posDflt[0]); + coerce('y', posDflt[1]); + _$lib_163.noneOrAll(containerIn, containerOut, ['x', 'y']); - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); + coerce('xanchor'); + coerce('yanchor'); - gButton - .call(removeAllButtons) - .attr(_$constants_138.menuIndexAttrName, '-1'); - } + _$lib_163.coerceFont(coerce, 'font', layout.font); - headerGroups.exit().each(function(menuOpts) { - _$d3_7.select(this).remove(); + var bgColor = coerce('bgcolor'); + coerce('activecolor', _$color_43.contrast(bgColor, _$constants_111.lightAmount, _$constants_111.darkAmount)); + coerce('bordercolor'); + coerce('borderwidth'); +}; - gButton - .call(removeAllButtons) - .attr(_$constants_138.menuIndexAttrName, '-1'); +function buttonsDefaults(containerIn, containerOut, calendar) { + var buttonsIn = containerIn.buttons || [], + buttonsOut = containerOut.buttons = []; - _$plots_237.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index); - }); + var buttonIn, buttonOut; - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_7.select(this); + function coerce(attr, dflt) { + return _$lib_163.coerce(buttonIn, buttonOut, _$button_attributes_110, attr, dflt); + } - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_237.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_140(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); - }); + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + if(!_$lib_163.isPlainObject(buttonIn)) continue; - // if this menu is active, update the dropdown container - if(__isActive_140(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + var step = coerce('step'); + if(step !== 'all') { + if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { + buttonOut.stepmode = 'backward'; } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); + else { + coerce('stepmode'); + } + + coerce('count'); } - }); -}; + coerce('label'); -/** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_138.name]; - var menuData = []; + buttonOut._index = i; + buttonsOut.push(buttonOut); + } - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; + return buttonsOut; +} - if(item.visible) menuData.push(item); +function getPosDflt(containerOut, layout, counterAxes) { + var anchoredList = counterAxes.filter(function(ax) { + return layout[ax].anchor === containerOut._id; + }); + + var posY = 0; + for(var i = 0; i < anchoredList.length; i++) { + var domain = layout[anchoredList[i]].domain; + if(domain) posY = Math.max(domain[1], posY); } - return menuData; + return [containerOut.domain[0], posY + _$constants_111.yPad]; } -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_140(menuOpts) { - return menuOpts._index; -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function isFolded(gButton) { - return +gButton.attr(_$constants_138.menuIndexAttrName) === -1; -} -function __isActive_140(gButton, menuOpts) { - return +gButton.attr(_$constants_138.menuIndexAttrName) === menuOpts._index; -} +'use strict'; -function __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; +/* removed: var _$d3_7 = require('d3'); */; - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_138.menuIndexAttrName, '-1'); +var _$getUpdateObject_114 = function getUpdateObject(axisLayout, buttonLayout) { + var axName = axisLayout._name; + var update = {}; - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + if(buttonLayout.step === 'all') { + update[axName + '.autorange'] = true; + } + else { + var xrange = getXRange(axisLayout, buttonLayout); - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } + update[axName + '.range[0]'] = xrange[0]; + update[axName + '.range[1]'] = xrange[1]; } -} -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_138.headerClassName) - .data([0]); - var dims = menuOpts._dims; + return update; +}; - header.enter().append('g') - .classed(_$constants_138.headerClassName, true) - .style('pointer-events', 'all'); +function getXRange(axisLayout, buttonLayout) { + var currentRange = axisLayout.range; + var base = new Date(axisLayout.r2l(currentRange[1])); - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_138.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; + var step = buttonLayout.step, + count = buttonLayout.count; - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); + var range0; - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_138.headerArrowClassName) - .data([0]); + switch(buttonLayout.stepmode) { + case 'backward': + range0 = axisLayout.l2r(+_$d3_7.time[step].utc.offset(base, -count)); + break; - arrow.enter().append('text') - .classed(_$constants_138.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_68.font, menuOpts.font) - .text(_$constants_138.arrowSymbol[menuOpts.direction]); + case 'todate': + var base2 = _$d3_7.time[step].utc.offset(base, -count); - arrow.attr({ - x: dims.headerWidth - _$constants_138.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_138.textOffsetY + menuOpts.pad.t - }); + range0 = axisLayout.l2r(+_$d3_7.time[step].utc.ceil(base2)); + break; + } - header.on('click', function() { - gButton.call(removeAllButtons); + var range1 = currentRange[1]; + return [range0, range1]; +} - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_138.menuIndexAttrName, - __isActive_140(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - }); +'use strict'; - header.on('mouseover', function() { - header.call(styleOnMouseOver); - }); +/* removed: var _$d3_7 = require('d3'); */; - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; - // translate header group - _$drawing_68.setTranslate(gHeader, dims.lx, dims.ly); -} +/* removed: var _$alignment_143 = require('../../constants/alignment'); */; +var __LINE_SPACING_113 = _$alignment_143.LINE_SPACING; +var __FROM_TL_113 = _$alignment_143.FROM_TL; +var __FROM_BR_113 = _$alignment_143.FROM_BR; -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); - } +/* removed: var _$constants_111 = require('./constants'); */; +/* removed: var _$getUpdateObject_114 = require('./get_update_object'); */; - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; - var klass = menuOpts.type === 'dropdown' ? _$constants_138.dropdownButtonClassName : _$constants_138.buttonClassName; +var _$draw_113 = function draw(gd) { + var fullLayout = gd._fullLayout; - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); + var selectors = fullLayout._infolayer.selectAll('.rangeselector') + .data(makeSelectorData(gd), selectorKeyFunc); - var enter = buttons.enter().append('g') - .classed(klass, true); + selectors.enter().append('g') + .classed('rangeselector', true); - var exit = buttons.exit(); + selectors.exit().remove(); - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + selectors.style({ + cursor: 'pointer', + 'pointer-events': 'all' + }); - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); - } + selectors.each(function(d) { + var selector = _$d3_7.select(this), + axisLayout = d, + selectorLayout = axisLayout.rangeselector; - var x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; + var buttons = selector.selectAll('g.button') + .data(selectorLayout.buttons); - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + buttons.enter().append('g') + .classed('button', true); - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_138.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_138.gapButtonHeader; - } - } + buttons.exit().remove(); - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openHeight; - } + buttons.each(function(d) { + var button = _$d3_7.select(this); + var update = _$getUpdateObject_114(axisLayout, d); - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openWidth; - } - - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_138.gapButton, - xPad: _$constants_138.gapButton, - index: 0, - }; - - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; - - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_7.select(this); - - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); + d._isActive = isActive(axisLayout, d, update); - button.on('click', function() { - // skip `dragend` events - if(_$d3_7.event.defaultPrevented) return; + button.call(drawButtonRect, selectorLayout, d); + button.call(drawButtonText, selectorLayout, d, gd); - __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + button.on('click', function() { + if(gd._dragged) return; - if(buttonOpts.execute) { - _$plots_237.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); - } + _$registry_245.call('relayout', gd, update); + }); - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); - }); + button.on('mouseover', function() { + d._isHovered = true; + button.call(drawButtonRect, selectorLayout, d); + }); - button.on('mouseover', function() { - button.call(styleOnMouseOver); + button.on('mouseout', function() { + d._isHovered = false; + button.call(drawButtonRect, selectorLayout, d); + }); }); - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); + reposition(gd, buttons, selectorLayout, axisLayout._name, selector); }); - buttons.call(styleButtons, menuOpts); +}; - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); - } +function makeSelectorData(gd) { + var axes = _$axis_ids_208.list(gd, 'x', true); + var data = []; - scrollBoxPosition.direction = menuOpts.direction; + for(var i = 0; i < axes.length; i++) { + var axis = axes[i]; - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); + if(axis.rangeselector && axis.rangeselector.visible) { + data.push(axis); } } + + return data; } -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; +function selectorKeyFunc(d) { + return d._id; +} - var active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_138.gapButton; - } +function isActive(axisLayout, opts, update) { + if(opts.step === 'all') { + return axisLayout.autorange === true; } else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_138.gapButton; - } - } - - scrollBox.enable(position, translateX, translateY); - - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } + var keys = Object.keys(update); - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); + return ( + axisLayout.range[0] === update[keys[0]] && + axisLayout.range[1] === update[keys[1]] + ); } } -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; - - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } +function drawButtonRect(button, selectorLayout, d) { + var rect = _$lib_163.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); - } -} + rect.attr({ + 'rx': _$constants_111.rx, + 'ry': _$constants_111.ry + }); -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); + rect.call(_$color_43.stroke, selectorLayout.bordercolor) + .call(_$color_43.fill, getFillColor(selectorLayout, d)) + .style('stroke-width', selectorLayout.borderwidth + 'px'); } -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed(_$constants_138.itemRectClassName, true) - .attr({ - rx: _$constants_138.rx, - ry: _$constants_138.ry, - 'shape-rendering': 'crispEdges' - }); - - rect.call(_$color_43.stroke, menuOpts.bordercolor) - .call(_$color_43.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); +function getFillColor(selectorLayout, d) { + return (d._isActive || d._isHovered) ? + selectorLayout.activecolor : + selectorLayout.bgcolor; } -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); +function drawButtonText(button, selectorLayout, d, gd) { + function textLayout(s) { + _$svg_text_utils_184.convertToTspans(s, gd); + } - text.enter().append('text') - .classed(_$constants_138.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + var text = _$lib_163.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); - text.call(_$drawing_68.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_183.convertToTspans, gd); + text.call(_$drawing_68.font, selectorLayout.font) + .text(getLabel(d)) + .call(textLayout); } -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; - - buttons.each(function(buttonOpts, i) { - var button = _$d3_7.select(this); +function getLabel(opts) { + if(opts.label) return opts.label; - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_138.itemRectClassName) - .call(_$color_43.fill, _$constants_138.activeColor); - } - }); -} + if(opts.step === 'all') return 'all'; -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_138.itemRectClassName) - .call(_$color_43.fill, _$constants_138.hoverColor); + return opts.count + opts.step.charAt(0); } -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_138.itemRectClassName) - .call(_$color_43.fill, menuOpts.bgcolor); -} +function reposition(gd, buttons, opts, axName, selector) { + var width = 0; + var height = 0; -// find item dimensions (this mutates menuOpts) -function __findDimensions_140(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; + var borderWidth = opts.borderwidth; - var fakeButtons = _$drawing_68.tester.selectAll('g.' + _$constants_138.dropdownButtonClassName) - .data(menuOpts.buttons); + buttons.each(function() { + var button = _$d3_7.select(this); + var text = button.select('.selector-text'); - fakeButtons.enter().append('g') - .classed(_$constants_138.dropdownButtonClassName, true); + var tHeight = opts.font.size * __LINE_SPACING_113; + var hEff = Math.max(tHeight * _$svg_text_utils_184.lineCount(text), 16) + 3; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + height = Math.max(height, hEff); + }); - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { + buttons.each(function() { var button = _$d3_7.select(this); + var rect = button.select('.selector-rect'); + var text = button.select('.selector-text'); - button.call(drawItem, menuOpts, buttonOpts, gd); - - var text = button.select('.' + _$constants_138.itemTextClassName); - - // width is given by max width of all buttons var tWidth = text.node() && _$drawing_68.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_138.textPadX, _$constants_138.minWidth); - - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_140; - var tLines = _$svg_text_utils_183.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_138.minHeight) + _$constants_138.textOffsetY; - - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); - - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; - - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); + var tHeight = opts.font.size * __LINE_SPACING_113; + var tLines = _$svg_text_utils_184.lineCount(text); - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_138.gapButton; - dims.openHeight += hEff + _$constants_138.gapButton; - } else { - dims.totalWidth += wEff + _$constants_138.gapButton; - dims.openWidth += wEff + _$constants_138.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; - } - }); + var wEff = Math.max(tWidth + 10, _$constants_111.minButtonWidth); - if(isVertical) { - dims.totalHeight -= _$constants_138.gapButton; - } else { - dims.totalWidth -= _$constants_138.gapButton; - } + // TODO add MathJax support + // TODO add buttongap attribute - dims.headerWidth = dims.width1 + _$constants_138.arrowPadX; - dims.headerHeight = dims.height1; + button.attr('transform', 'translate(' + + (borderWidth + width) + ',' + borderWidth + + ')'); - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_138.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_138.arrowPadX; - } + rect.attr({ + x: 0, + y: 0, + width: wEff, + height: height + }); - fakeButtons.remove(); + _$svg_text_utils_184.positionText(text, wEff / 2, + height / 2 - ((tLines - 1) * tHeight / 2) + 3); - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; + width += wEff + 5; + }); var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); + var lx = graphSize.l + graphSize.w * opts.x; + var ly = graphSize.t + graphSize.h * (1 - opts.y); var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; + if(_$anchor_utils_95.isRightAnchor(opts)) { + lx -= width; xanchor = 'right'; } - if(_$anchor_utils_95.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; + if(_$anchor_utils_95.isCenterAnchor(opts)) { + lx -= width / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_95.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; + if(_$anchor_utils_95.isBottomAnchor(opts)) { + ly -= height; yanchor = 'bottom'; } - if(_$anchor_utils_95.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; + if(_$anchor_utils_95.isMiddleAnchor(opts)) { + ly -= height / 2; yanchor = 'middle'; } - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); - - _$plots_237.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); -} - -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_138.itemRectClassName); - var text = item.select('.' + _$constants_138.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; - - _$drawing_68.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); - - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); + width = Math.ceil(width); + height = Math.ceil(height); + lx = Math.round(lx); + ly = Math.round(ly); - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight + _$plots_237.autoMargin(gd, axName + '-range-selector', { + x: opts.x, + y: opts.y, + l: width * __FROM_TL_113[xanchor], + r: width * __FROM_BR_113[xanchor], + b: height * __FROM_BR_113[yanchor], + t: height * __FROM_TL_113[yanchor] }); - var tHeight = menuOpts.font.size * __LINE_SPACING_140; - var tLines = _$svg_text_utils_183.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); - - _$svg_text_utils_183.positionText(text, _$constants_138.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_138.textOffsetY); - - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; - } - - posOpts.index++; -} - -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_138.dropdownButtonClassName).remove(); -} - -function __clearPushMargins_140(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); - - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; - - if(k.indexOf(_$constants_138.autoMarginIdRoot) !== -1) { - _$plots_237.autoMargin(gd, k); - } - } + selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); } /** @@ -48610,19 +48171,22 @@ function __clearPushMargins_140(gd) { 'use strict'; -/* removed: var _$constants_138 = require('./constants'); */; - -var _$updatemenus_141 = { +var _$rangeselector_115 = { moduleType: 'component', - name: _$constants_138.name, + name: 'rangeselector', - layoutAttributes: _$attributes_137, - supplyLayoutDefaults: _$updateMenusDefaults_139, + schema: { + subplots: { + xaxis: {rangeselector: _$attributes_109} + } + }, - draw: _$draw_140 + layoutAttributes: _$attributes_109, + handleDefaults: _$handleDefaults_112, + + draw: _$draw_113 }; -var _$mathjax_config_149 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48633,27 +48197,68 @@ var _$mathjax_config_149 = {}; 'use strict'; -/* global MathJax:false */ - -/** - * Check and configure MathJax - */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_149.MathJax = true; - - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] - } - }); +/* removed: var _$attributes_42 = require('../color/attributes'); */; - MathJax.Hub.Configured(); -} else { - _$mathjax_config_149.MathJax = false; -} +var _$attributes_116 = { + bgcolor: { + valType: 'color', + dflt: _$attributes_42.background, + + editType: 'plot', + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_42.defaultLine, + + editType: 'plot', + + }, + borderwidth: { + valType: 'integer', + dflt: 0, + min: 0, + + editType: 'plot', + + }, + autorange: { + valType: 'boolean', + dflt: true, + + editType: 'calc', + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, + + }, + range: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} + ], + editType: 'calc', + impliedEdits: {'autorange': false}, + + }, + thickness: { + valType: 'number', + dflt: 0.15, + min: 0, + max: 1, + + editType: 'plot', + + }, + visible: { + valType: 'boolean', + dflt: true, + + editType: 'calc', + + }, + editType: 'calc' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -48663,208 +48268,89 @@ if(typeof MathJax !== 'undefined') { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_162 = require('../lib'); */; -/* removed: var _$plot_config_194 = require('../plot_api/plot_config'); */; +var _$constants_118 = { + // attribute container name + name: 'rangeslider', -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; - - for(var i = 0; i < args.length; i++) { - arg = args[i]; - - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_162.extendDeep([], arg) : - _$lib_162.extendDeepAll({}, arg); - } - else copy[i] = arg; - } - - return copy; -} - - -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + // class names + containerClassName: 'rangeslider-container', + bgClassName: 'rangeslider-bg', + rangePlotClassName: 'rangeslider-rangeplot', -var __queue_176 = {}; + maskMinClassName: 'rangeslider-mask-min', + maskMaxClassName: 'rangeslider-mask-max', + slideBoxClassName: 'rangeslider-slidebox', -// TODO: disable/enable undo and redo buttons appropriately + grabberMinClassName: 'rangeslider-grabber-min', + grabAreaMinClassName: 'rangeslider-grabarea-min', + handleMinClassName: 'rangeslider-handle-min', -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_176.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + grabberMaxClassName: 'rangeslider-grabber-max', + grabAreaMaxClassName: 'rangeslider-grabarea-max', + handleMaxClassName: 'rangeslider-handle-max', - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', + maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } + // style constants - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; - } - gd.undoQueue.beginSequence = false; + maskColor: 'rgba(0,0,0,0.4)', + maskOppAxisColor: 'rgba(0,0,0,0.2)', - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); - } + slideBoxFill: 'transparent', + slideBoxCursor: 'ew-resize', - if(gd.undoQueue.queue.length > _$plot_config_194.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; - } -}; + grabAreaFill: 'transparent', + grabAreaCursor: 'col-resize', + grabAreaWidth: 10, -/** - * Begin a sequence of undoQueue changes - * - * @param gd - */ -__queue_176.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; + handleWidth: 4, + handleRadius: 1, + handleStrokeWidth: 1, -/** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended - * - * @param gd - */ -__queue_176.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; + extraPad: 15 }; /** - * Move one step back in the undo queue, and undo the object there. - * - * @param gd - */ -__queue_176.undo = function undo(gd) { - var queueObj, i; - - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; - } +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; +'use strict'; - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; +var listAxes = _$axis_ids_208.list; +var __getAutoRange_117 = _$autorange_204.getAutoRange; +/* removed: var _$constants_118 = require('./constants'); */; - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_176.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); - } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; +var _$calcAutorange_117 = function calcAutorange(gd) { + var axes = listAxes(gd, 'x', true); -/** - * Redo the current object in the undo, then move forward in the queue. - * - * @param gd - */ -__queue_176.redo = function redo(gd) { - var queueObj, i; + // 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. - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; - } + for(var i = 0; i < axes.length; i++) { + var ax = axes[i], + opts = ax[_$constants_118.name]; - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + // Don't try calling getAutoRange if _min and _max are filled in. + // This happens on updates where the calc step is skipped. - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_176.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { + opts._input.autorange = true; + opts._input.range = opts.range = __getAutoRange_117(ax); + } } - gd.undoQueue.inSequence = false; - gd.autoplay = false; - - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; -}; - -/** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. - * - * @param gd - * @param func - * @param args - */ -__queue_176.plotDo = function(gd, func, args) { - gd.autoplay = true; - - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); - - // call the supplied function - func.apply(null, args); }; -var _$queue_176 = __queue_176; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48875,15 +48361,31 @@ var _$queue_176 = __queue_176; 'use strict'; -var _$localeEnUs_186 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' +var _$oppaxis_attributes_122 = { + // 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', + }, - format: { - date: '%m/%d/%Y' - } + range: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'plot'}, + {valType: 'any', editType: 'plot'} + ], + editType: 'plot', + + }, + editType: 'calc' }; /** @@ -48896,86 +48398,79 @@ var _$localeEnUs_186 = { 'use strict'; -var _$localeEn_187 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$attributes_116 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; +/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; + +var _$handleDefaults_119 = 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_163.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; } -}; -var _$fromQuat_11 = fromQuat; + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; -/** - * 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, + function coerce(attr, dflt) { + return _$lib_163.coerce(containerIn, containerOut, _$attributes_116, attr, dflt); + } - 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; + function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { + return _$lib_163.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_122, attr, dflt); + } - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; + var visible = coerce('visible'); + if(!visible) return; - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + coerce('bgcolor', layoutOut.plot_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('thickness'); - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); + coerce('range'); - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + var subplots = layoutOut._subplots; + if(subplots) { + var yIds = subplots.cartesian + .filter(function(subplotId) { + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_208.name2id(axName); + }) + .map(function(subplotId) { + return subplotId.substr(subplotId.indexOf('y'), subplotId.length); + }); + var yNames = _$lib_163.simpleMap(yIds, _$axis_ids_208.id2name); + for(var i = 0; i < yNames.length; i++) { + var yName = yNames[i]; - return out; + var rangeContainerIn = containerIn[yName] || {}; + var rangeContainerOut = containerOut[yName] = {}; + + var yAxOut = layoutOut[yName]; + + var rangemodeDflt; + if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { + rangemodeDflt = 'fixed'; + } + + var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); + if(rangeMode !== 'match') { + coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); + } + yAxOut._rangesliderAutorange = (rangeMode === 'auto'); + } + } + + // to map back range slider (auto) range + containerOut._input = containerIn; }; -var _$helpers_190 = {}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48984,786 +48479,616 @@ var _$helpers_190 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_11 = require('gl-mat4/fromQuat'); */; +/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$registry_244 = require('../registry'); */; -/* removed: var _$lib_162 = require('../lib'); */; -/* removed: var _$plots_237 = require('../plots/plots'); */; -/* removed: var _$axis_ids_207 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_207.cleanId; -var getFromTrace = _$axis_ids_207.getFromTrace; -/* removed: var _$color_43 = require('../components/color'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$titles_136 = require('../titles'); */; -// clear the promise queue if one of them got rejected -_$helpers_190.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_162.log('Clearing previous rejected promises from queue.'); - } +/* removed: var _$cartesian_216 = require('../../plots/cartesian'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; - gd._promises = []; -}; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_190.cleanLayout = function(layout) { - var i, j; +/* removed: var _$constants_118 = require('./constants'); */; - if(!layout) layout = {}; +var _$draw_120 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; - } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ + + function keyFunction(axisOpts) { + return axisOpts._name; } - var axisAttrRegex = (_$plots_237.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_237.subplotsRegistry.gl3d || {}).attrRegex; + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_118.containerClassName) + .data(rangeSliderData, keyFunction); - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; + rangeSliders.enter().append('g') + .classed(_$constants_118.containerClassName, true) + .attr('pointer-events', 'all'); - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_7.select(this), + opts = axisOpts[_$constants_118.name]; - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); + }); - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; - } - } + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_7.select(this), + opts = axisOpts[_$constants_118.name], + oppAxisOpts = fullLayout[_$axes_205.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_205.id2name(axisOpts.anchor)]; - // clean old Camera coords - var cameraposition = scene.cameraposition; + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_11([], rotation), - eye = []; + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); + } - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } + axisOpts.cleanRange('rangeslider.range'); - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; - delete scene.cameraposition; - } - } - } + // update range slider dimensions - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; - if(!_$lib_162.isPlainObject(ann)) continue; + var oppBottom = Infinity; + var subplotData = _$axes_205.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_205.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); + } - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } - - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); - } - - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; - - if(!_$lib_162.isPlainObject(shape)) continue; + opts._id = _$constants_118.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); - } + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } + var x = Math.round(margin.l + (graphSize.w * domain[0])); - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; - } - } + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_118.extraPad + ); - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_43.clean(layout); + // update data <--> pixel coordinate conversion methods - return layout; -}; + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); - } -} + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_190.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; + opts._rl = [range0, range1]; - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; - for(i = 0; i < 100; i++) { - newUid = _$lib_162.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_162.randstr(uids); - uids.push(trace.uid); + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); - // BACKWARD COMPATIBILITY FIXES + // update inner nodes - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_43.defaults, - yeColor = trace.error_y.color || - (_$registry_244.traceIs(trace, 'bar') ? _$color_43.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_43.addOpacity( - _$color_43.rgb(yeColor), - _$color_43.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_244.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_190.swapXYData(trace); - } - delete trace.bardir; - } + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_190.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_136.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); } - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } + // update margins + _$plots_237.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_118.extraPad + opts._offsetShift * 2 + }); + }); +}; - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); +function makeRangeSliderData(fullLayout) { + var axes = _$axes_205.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_118.name, + out = []; - // scene ids scene1 -> scene - if(_$registry_244.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_237.subplotsRegistry.gl3d.cleanId(trace.scene); - } + if(fullLayout._has('gl2d')) return out; - if(!_$registry_244.traceIs(trace, 'pie') && !_$registry_244.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - // fix typo in colorscale definition - if(_$registry_244.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_244.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } + if(ax[name] && ax[name].visible) out.push(ax); + } - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_162.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + return out; +} - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_118.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_118.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_118.grabAreaMaxClassName).node(); - if(!_$lib_162.isPlainObject(opts)) continue; + rangeSlider.on('mousedown', function() { + var event = _$d3_7.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } + var dragCover = _$dragelement_65.coverSlip(); - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } - } + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; - if(!_$lib_162.isPlainObject(transform)) continue; + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } + _$setCursor_182(_$d3_7.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); } - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_163.removeElement(dragCover); } + }); +} - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_43.clean(trace); - } -}; - -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; +function setDataRange(rangeSlider, gd, axisOpts, opts) { - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + function clamp(v) { + return axisOpts.l2r(_$lib_163.constrain(v, opts._rl[0], opts._rl[1])); + } - return posY + ' ' + posX; -} + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); + window.requestAnimationFrame(function() { + _$registry_245.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); } +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_118.handleWidth / 2; -// swap all the data and data attributes associated with x and y -_$helpers_190.swapXYData = function(trace) { - var i; - _$lib_162.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_162.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_162.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); - } - } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; - } - trace.hoverinfo = hoverInfoParts.join('+'); + function clamp(v) { + return _$lib_163.constrain(v, 0, opts._width); } -}; -// coerce traceIndices input to array of trace indices -_$helpers_190.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_10(traceIndices)) { - return [traceIndices]; + function clampOppAxis(v) { + return _$lib_163.constrain(v, 0, opts._height); } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); + + function clampHandle(v) { + return _$lib_163.constrain(v, -hw2, opts._width + hw2); } - return traceIndices; -}; + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); -/** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_190.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; + rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); - var pLastIsNumber = _$fastIsnumeric_10(pLast); + rangeSlider.select('rect.' + _$constants_118.maskMinClassName) + .attr('width', pixelMin); - // delete item - if(pLastIsNumber && newVal === null) { + rangeSlider.select('rect.' + _$constants_118.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_162.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - // Note that nested property clears null / undefined at end of - // array container, but not within them. - } - // create item - else if(pLastIsNumber && np.get() === undefined) { + rangeSlider.select('rect.' + _$constants_118.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; + rangeSlider.select('rect.' + _$constants_118.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - np.set(newVal); + rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); } - // update item - else { - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); - } -}; + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); + rangeSlider.select('g.' + _$constants_118.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + + rangeSlider.select('g.' + _$constants_118.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); } -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_190.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; -}; +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_163.ensureSingle(rangeSlider, 'rect', _$constants_118.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_190 = ['x', 'y', 'z']; -_$helpers_190.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_190[j]); + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; + var offsetShift = -opts._offsetShift; + var lw = _$drawing_68.crispRound(gd, opts.borderwidth); - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_162.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } -}; + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw + }); +} -_$helpers_190.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; - } - } -}; +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; -var _$manage_arrays_192 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 clipPath = _$lib_163.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); +} -'use strict'; +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_205.getSubplots(gd, axisOpts), + calcData = gd.calcdata; -/* removed: var _$nestedProperty_170 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_164 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_171 = require('../lib/noop'); */; -/* removed: var _$loggers_167 = require('../lib/loggers'); */; -var sorterAsc = _$search_180.sorterAsc; -/* removed: var _$registry_244 = require('../registry'); */; + var rangePlots = rangeSlider.selectAll('g.' + _$constants_118.rangePlotClassName) + .data(subplotData, _$lib_163.identity); + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_118.rangePlotClassName + ' ' + id; }) + .call(_$drawing_68.setClipUrl, opts._clipId); -_$manage_arrays_192.containerArrayMatch = _$containerArrayMatch_188; + rangePlots.order(); -var isAddVal = _$manage_arrays_192.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_164(val); -}; + rangePlots.exit().remove(); -var isRemoveVal = _$manage_arrays_192.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; + var mainplotinfo; -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_192.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_244.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_244.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_244.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_171) || - (draw === _$noop_171), - layout = gd.layout, - fullLayout = gd._fullLayout; + rangePlots.each(function(id, i) { + var plotgroup = _$d3_7.select(this), + isMainPlot = (i === 0); - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_167.warn('Full array edits are incompatible with other edits', - componentType); - } + var oppAxisOpts = _$axes_205.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; - var fullVal = edits['']['']; + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; + + _$plots_237.supplyDefaults(mockFigure); + + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; + + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; + + if(isMainPlot) mainplotinfo = plotinfo; else { - _$loggers_167.warn('Unrecognized full array edit value', componentType, fullVal); - return true; + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; } - if(replotLater) return false; + _$cartesian_216.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + }); +} - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; + + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; + + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } } - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_170(fullLayout, componentType).get(); + return out; +} - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_163.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + maskMin + .attr('height', opts._height) + .call(_$color_43.fill, _$constants_118.maskColor); - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_167.warn('index out of range', componentType, componentNum); - continue; - } + var maskMax = _$lib_163.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_167.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } + maskMax + .attr('height', opts._height) + .call(_$color_43.fill, _$constants_118.maskColor); - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_167.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_163.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_170(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } - } + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_43.fill, _$constants_118.maskOppAxisColor); - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); + var maskMaxOppAxis = _$lib_163.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); + + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_118.maskOppBorder) + .call(_$color_43.fill, _$constants_118.maskOppAxisColor); } +} - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; - if(replotLater) return false; + var slideBox = _$lib_163.ensureSingle(rangeSlider, 'rect', _$constants_118.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_118.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); - supplyComponentDefaults(layout, fullLayout); + slideBox.attr({ + height: opts._height, + fill: _$constants_118.slideBoxFill + }); +} - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_171) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_163.ensureSingle(rangeSlider, 'g', _$constants_118.grabberMinClassName); + var grabberMax = _$lib_163.ensureSingle(rangeSlider, 'g', _$constants_118.grabberMaxClassName); + + // + var handleFixAttrs = { + x: 0, + width: _$constants_118.handleWidth, + rx: _$constants_118.handleRadius, + fill: _$color_43.background, + stroke: _$color_43.defaultLine, + 'stroke-width': _$constants_118.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_163.ensureSingle(grabberMin, 'rect', _$constants_118.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMin.attr(handleDynamicAttrs); + + var handleMax = _$lib_163.ensureSingle(grabberMax, 'rect', _$constants_118.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); + + // + if(gd._context.staticPlot) return; + + var grabAreaFixAttrs = { + width: _$constants_118.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_118.grabAreaFill, + cursor: _$constants_118.grabAreaCursor + }; + + var grabAreaMin = _$lib_163.ensureSingle(grabberMin, 'rect', _$constants_118.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMin.attr('height', opts._height); + + var grabAreaMax = _$lib_163.ensureSingle(grabberMax, 'rect', _$constants_118.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMax.attr('height', opts._height); +} + +function clearPushMargins(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); + + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + + if(k.indexOf(_$constants_118.name) !== -1) { + _$plots_237.autoMargin(gd, k); } } - else draw(gd); - - return true; -}; +} -var _$buttons_105 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49772,602 +49097,440 @@ var _$buttons_105 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$plots_237 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_207 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - -var ____105 = _$lib_162._; - -var modeBarButtons = _$buttons_105 = {}; - -/** - * 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) { return ____105(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$attributes_116 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; - _$lib_162.notifier(____105(gd, 'Taking snapshot - this may take a few seconds'), 'long'); +var _$rangeslider_121 = { + moduleType: 'component', + name: 'rangeslider', - if(_$lib_162.isIE()) { - _$lib_162.notifier(____105(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_163.extendFlat({}, _$attributes_116, { + yaxis: _$oppaxis_attributes_122 + }) + } } + }, - _$registry_244.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_162.notifier(____105(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_162.notifier(____105(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); - } + layoutAttributes: _$attributes_116, + handleDefaults: _$handleDefaults_119, + calcAutorange: _$calcAutorange_117, + draw: _$draw_120 }; -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____105(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_237.sendDataToCloud(gd); - } -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____105(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian -}; +'use strict'; -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____105(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian -}; +/* removed: var _$attributes_28 = require('../annotations/attributes'); */; +var scatterLineAttrs = _$attributes_281.line; +var __dash_123 = _$attributes_67.dash; +var __extendFlat_123 = _$extend_157.extendFlat; -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____105(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; +var _$attributes_123 = { + _isLinkedToArray: 'shape', -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____105(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian -}; + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calcIfAutorange+arraydraw', + + }, -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____105(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian -}; + type: { + valType: 'enumerated', + values: ['circle', 'rect', 'path', 'line'], + + editType: 'calcIfAutorange+arraydraw', + + }, -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____105(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian -}; + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____105(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian -}; + xref: __extendFlat_123({}, _$attributes_28.xref, { + + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____105(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian -}; + yref: __extendFlat_123({}, _$attributes_28.yref, { + + }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____105(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian -}; + path: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____105(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian + line: { + color: __extendFlat_123({}, scatterLineAttrs.color, {editType: 'arraydraw'}), + width: __extendFlat_123({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_123({}, __dash_123, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' }; -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 = _$axis_ids_207.list(gd, null, true); - var allSpikesEnabled = 'on'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 ax, i; - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; +'use strict'; - var axName; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +var _$constants_125 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, - 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]; - } - 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]), - ]; + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, - aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); - aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); - } - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } +}; - aobj[astr] = val; - } +var _$helpers_128 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - _$registry_244.call('relayout', gd, aobj); -} -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____105(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d +'use strict'; + +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. + +_$helpers_128.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; }; -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____105(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d +_$helpers_128.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; }; -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____105(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d +_$helpers_128.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); + }; }; -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____105(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['z-axis'], - click: handleDrag3d +_$helpers_128.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; }; -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 = {}; +_$helpers_128.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; - var parts = attr.split('.'); + if(axis) { + var d2r = _$helpers_128.shapePositionToRange(axis); - for(var i = 0; i < sceneIds.length; i++) { - layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; + + if(axis.type === 'date') dataToPixel = _$helpers_128.decodeDate(dataToPixel); + } + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + } + else { + dataToPixel = function(v) { return gs.l + gs.w * v; }; } - // for multi-type subplots - var val2d = (val === 'pan') ? val : 'zoom'; - layoutUpdate.dragmode = val2d; + return dataToPixel; +}; - _$registry_244.call('relayout', gd, layoutUpdate); -} +_$helpers_128.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____105(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; + if(axis) { + var r2d = _$helpers_128.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + } + else { + pixelToData = function(p) { return (p - gs.l) / gs.w; }; + } -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____105(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d + return pixelToData; }; -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 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; - if(attr === 'resetDefault') { - aobj[key] = null; - } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_162.extendDeep({}, scene.cameraInitial); - } - } +'use strict'; - _$registry_244.call('relayout', gd, aobj); -} +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; +/* removed: var _$constants_125 = require('./constants'); */; +/* removed: var _$helpers_128 = require('./helpers'); */; -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; +var _$calcAutorange_124 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + shapeList = _$lib_163.filterVisible(fullLayout.shapes); - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; + if(!shapeList.length || !gd._fullData.length) return; - if(val) { - layoutUpdate = _$lib_162.extendDeep(layout, val); - button._previousVal = null; - } - else { - layoutUpdate = { - 'allaxes.showspikes': false - }; + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + var ax, bounds; - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_205.getFromId(gd, shape.xref); - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_125.paramIsX); - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; - } - } + if(bounds) _$axes_205.expand(ax, bounds, calcXPaddingOptions(shape)); } - button._previousVal = _$lib_162.extendDeep({}, currentSpikes); - } - - _$registry_244.call('relayout', gd, layoutUpdate); -} - -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____105(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; - -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____105(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_205.getFromId(gd, shape.yref); -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____105(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_125.paramIsY); + if(bounds) _$axes_205.expand(ax, bounds, calcYPaddingOptions(shape)); + } + } }; -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} -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; +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} - for(var i = 0; i < geoIds.length; i++) { - var id = geoIds[i]; - var geoLayout = fullLayout[id]; +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - if(attr === 'zoom') { - var scale = geoLayout.projection.scale; - var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_125.paramIsY : _$constants_125.paramIsX) : + [v0, v1]; + var maxValue = _$lib_163.aggNums(Math.max, null, coords), + minValue = _$lib_163.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - _$registry_244.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); - } + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; } } -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; - -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; -function toggleHover(gd) { - var fullLayout = gd._fullLayout; + var segments = path.match(_$constants_125.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; - } - else onHoverVal = 'closest'; + var params = segment.substr(1).match(_$constants_125.paramRE); + if(!params || params.length < relevantParamIdx) return; - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; + extractedCoordinates.push(params[relevantParamIdx]); + }); - _$registry_244.call('relayout', gd, 'hovermode', newHover); + return extractedCoordinates; } -// buttons when more then one plot types are present - -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); - - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); - } -}; - -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____105(gd, 'Reset views'); }, - icon: _$ploticon_2.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 ____105(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; - - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - - var aobj = setSpikelineVisibility(gd); - - _$registry_244.call('relayout', gd, aobj); - } -}; - -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_207.list(gd, null, true); - var aobj = {}; - - var ax, axName; +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; - } + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; - return aobj; -} + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_125.segmentRE), + i, + segment, + drawnParam, + params, + val; -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____105(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); - } -}; + if(ax.type === 'date') convertVal = _$helpers_128.decodeDate(convertVal); -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - 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); + params = segments[i].substr(1).match(_$constants_125.paramRE); + if(!params || params.length < drawnParam) continue; - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; - } + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; } - - _$registry_244.call('relayout', gd, aObj); + if(max >= min) return [min, max]; } /** @@ -50381,546 +49544,601 @@ function resetView(gd, subplotType) { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; - -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -/** - * 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'); +/* removed: var _$attributes_123 = require('./attributes'); */; +/* removed: var _$helpers_128 = require('./helpers'); */; - this.update(opts.graphInfo, opts.buttons); - this.container.appendChild(this.element); -} +var _$handleShapeDefaults_130 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; -var proto = ModeBar.prototype; + function coerce(attr, dflt) { + return _$lib_163.coerce(shapeIn, shapeOut, _$attributes_123, attr, dflt); + } -/** - * 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 visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - var context = this.graphInfo._context; + if(!visible) return shapeOut; - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; - } - else this.element.className = 'modebar'; + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - this.updateButtons(buttons); + // xref, yref + var axRef = _$axes_205.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; + if(axRef !== 'paper') { + ax = _$axes_205.getFromId(gdMock, axRef); + r2pos = _$helpers_128.rangeToShapePosition(ax); + pos2r = _$helpers_128.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_163.identity; } - } - this.updateActiveButton(); -}; + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; -proto.updateButtons = function(buttons) { - var _this = this; + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); - this.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_205.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_205.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); + // hack part 2 + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } - 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); + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); + _$axes_205.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); - _this.element.appendChild(group); - }); -}; + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; + } + } -/** - * Empty div for containing a group of buttons - * @Return {HTMLelement} - */ -proto.createGroup = function() { - var group = document.createElement('div'); - group.className = 'modebar-group'; + if(shapeType === 'path') { + coerce('path'); + } + else { + _$lib_163.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + } - return group; + return shapeOut; }; /** - * 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, - 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); +* Copyright 2012-2018, Plotly, Inc. +* All 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 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); +'use strict'; - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); - } +/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_130 = require('./shape_defaults'); */; - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_7.select(button).classed('active', true); - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - button.setAttribute('data-gravity', config.gravity || 'n'); +var _$supplyLayoutDefaults_126 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_130 + }; - return button; + _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); }; /** - * Add an icon to a button - * @Param {object} thisIcon - * @Param {number} thisIcon.width - * @Param {string} thisIcon.path - * @Return {HTMLelement} - */ -proto.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); - - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); +* Copyright 2012-2018, Plotly, Inc. +* All 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 transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); +'use strict'; - return icon; -}; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; -/** - * 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, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_7.select(button); +/* removed: var _$constants_125 = require('./constants'); */; +/* removed: var _$helpers_128 = require('./helpers'); */; - // 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_162.nestedProperty(fullLayout, dataAttr).get(); - button3.classed('active', val === thisval); - } +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - }); +var _$draw_127 = { + draw: __draw_127, + drawOne: __drawOne_127 }; -/** - * 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; +function __draw_127(gd) { + var fullLayout = gd._fullLayout; - if(!currentButtons) return false; + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); - if(buttons.length !== currentButtons.length) return false; + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); + } - 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; + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_127(gd, i); } } - return true; -}; - -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -proto.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); +} - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_162._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; +function __drawOne_127(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; - group.appendChild(a); - return group; -}; + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; -proto.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); + } } - this.hasLogo = false; -}; + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; -proto.destroy = function() { - _$lib_162.removeElement(this.container.querySelector('.modebar')); -}; + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_43.stroke, lineColor) + .call(_$color_43.fill, options.fillcolor) + .call(_$drawing_68.dashLine, options.line.dash, options.line.width); -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); + path.call(_$drawing_68.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null + ); - if(fullLayout._privateplot) { - _$d3_7.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); + if(gd._context.edits.shapePosition) __setupDragElement_127(gd, path, options, index); } - - return modeBar; } -var _$createModeBar_108 = createModeBar; +function __setupDragElement_127(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; -'use strict'; + var xa, ya, x2p, y2p, p2x, p2y; -/* removed: var _$axis_ids_207 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_244 = require('../../registry'); */; + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; -/* removed: var _$createModeBar_108 = require('./modebar'); */; -/* removed: var _$buttons_105 = require('./buttons'); */; + _$dragelement_65.init(dragOptions); -/** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object - * - */ -var _$manageModeBar_107 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } + shapePath.node().onmousemove = updateDragMode; - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } + function updateDragMode(evt) { + // element might not be on screen at time of setup, + // so obtain bounding box here + var dragBBox = dragOptions.element.getBoundingClientRect(); - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } + // choose 'move' or 'resize' + // based on initial position of cursor within the drag element + var w = dragBBox.right - dragBBox.left, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_65.getCursor(x / w, 1 - y / h) : + 'move'; - var customButtons = context.modeBarButtons; - var buttonGroups; + _$setCursor_182(shapePath, cursor); - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; } - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_108(gd, buttonGroups); -}; - -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; + function startDrag(evt) { + // setup conversion functions + xa = _$axes_205.getFromId(gd, shapeOptions.xref); + ya = _$axes_205.getFromId(gd, shapeOptions.yref); - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); + x2p = _$helpers_128.getDataToPixel(gd, xa); + y2p = _$helpers_128.getDataToPixel(gd, ya, true); + p2x = _$helpers_128.getPixelToData(gd, xa); + p2y = _$helpers_128.getPixelToData(gd, ya, true); - var groups = []; + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; - function addGroup(newGroup) { - if(!newGroup.length) return; + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } - var out = []; + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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); - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_105[button]); + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; } - groups.push(out); - } + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.x0'; optE = 'x0'; + } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); + // 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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + } - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; + update = {}; - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; + + function endDrag() { + _$setCursor_182(shapePath); + _$registry_245.call('relayout', gd, update); } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; + + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; + + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + } + + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; + + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; + + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + } + + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; +} + +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_205.getFromId(gd, options.xref), + ya = _$axes_205.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; + + if(xa) { + x2r = _$helpers_128.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; + else { + x2p = function(v) { return gs.l + gs.w * v; }; } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; + + if(ya) { + y2r = _$helpers_128.shapePositionToRange(ya); + y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + else { + y2p = function(v) { return gs.t + gs.h * (1 - v); }; } - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_128.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_128.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; + if(options.xsizemode === 'pixel') { + var xAnchorPos = x2p(options.xanchor); + x0 = xAnchorPos + options.x0; + x1 = xAnchorPos + options.x1; } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); + else { + x0 = x2p(options.x0); + x1 = x2p(options.x1); } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); - - return appendButtonsToGroups(groups, buttonsToAdd); -} - -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_207.list({_fullLayout: fullLayout}, null, true); - - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } + 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); } - return true; + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; } -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; - var trace = fullData[i]; - if(!trace._module || !trace._module.selectPoints) continue; + return pathIn.replace(_$constants_125.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_125.paramIsX[segmentType], + yParams = _$constants_125.paramIsY[segmentType], + nParams = _$constants_125.numParams[segmentType]; - if(_$registry_244.traceIs(trace, 'scatter-like')) { - if(_$subtypes_302.hasMarkers(trace) || _$subtypes_302.hasText(trace)) { - selectable = true; + var paramString = segment.substr(1).replace(_$constants_125.paramRE, function(param) { + if(xParams[paramNumber]) { + if(xSizemode === 'pixel') param = x2p(xAnchor) + Number(param); + else param = x2p(param); } - } else if(_$registry_244.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; + else if(yParams[paramNumber]) { + if(ySizemode === 'pixel') param = y2p(yAnchor) - Number(param); + else param = y2p(param); } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; - } + paramNumber++; - return selectable; -} + if(paramNumber > nParams) param = 'X'; + return param; + }); -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } + if(paramNumber > nParams) { + paramString = paramString.replace(/[\s,]*X.*/, ''); + _$lib_163.log('Ignoring extra params in segment ' + segment); } - else groups.push(buttons); - } - return groups; + return segmentType + paramString; + }); } -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_125.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_125.paramIsX[segmentType], + yParams = _$constants_125.paramIsY[segmentType], + nParams = _$constants_125.numParams[segmentType]; - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + var paramString = segment.substr(1).replace(_$constants_125.paramRE, function(param) { + if(paramNumber >= nParams) return param; - if(typeof button === 'string') { - if(_$buttons_105[button] !== undefined) { - customButtons[i][j] = _$buttons_105[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } - } + if(xParams[paramNumber]) param = moveX(param); + else if(yParams[paramNumber]) param = moveY(param); - return customButtons; + paramNumber++; + + return param; + }); + + return segmentType + paramString; + }); } -var _$modebar_106 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -50932,7 +50150,20 @@ var _$modebar_106 = {}; 'use strict'; -_$modebar_106.manage = _$manageModeBar_107; +/* removed: var _$draw_127 = require('./draw'); */; + +var _$shapes_129 = { + moduleType: 'component', + name: 'shapes', + + layoutAttributes: _$attributes_123, + supplyLayoutDefaults: _$supplyLayoutDefaults_126, + includeBasePlot: _$makeIncludeComponents_215('shapes'), + + calcAutorange: _$calcAutorange_124, + draw: _$draw_127.draw, + drawOne: _$draw_127.drawOne +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -50945,1632 +50176,3599 @@ _$modebar_106.manage = _$manageModeBar_107; 'use strict'; -var FROM_BL = _$alignment_143.FROM_BL; -var _$scaleZoom_221 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } +var _$constants_132 = { - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; + // layout attribute name + name: 'sliders', - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + railHeight: 5, -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + // min item width / height + minWidth: 30, + minHeight: 30, - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + // padding around item text + textPadX: 40, -var _$BuildLog_17 = BuildLog; + // arrow offset off right edge + arrowOffsetX: 4, -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', + + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, + + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, + + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', + + labelPadding: 8, + labelOffset: 0, + + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, + + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, + + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_236 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_236 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_131 = _$extend_157.extendDeepAll; +var __overrideAll_131 = _$edit_types_190.overrideAll; +/* removed: var _$animation_attributes_200 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_132 = require('./constants'); */; + +var stepsAttrs = { + _isLinkedToArray: 'step', + + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } + ], + + }, + label: { + valType: 'string', + + + }, + value: { + valType: 'string', + + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; + +var _$attributes_131 = __overrideAll_131({ + _isLinkedToArray: 'slider', + + visible: { + valType: 'boolean', + + dflt: true, + + }, + + active: { + valType: 'number', + + min: 0, + dflt: 0, + + }, + + steps: stepsAttrs, + + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], + + dflt: 'fraction', + + }, + len: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + pad: __extendDeepAll_131({}, _$pad_attributes_236, { + + }, {t: {dflt: 20}}), + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, + + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_200.transition.easing.values, + + dflt: 'cubic-in-out', + + } + }, + + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, + + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, + + offset: { + valType: 'number', + dflt: 10, + + + }, + + prefix: { + valType: 'string', + + + }, + + suffix: { + valType: 'string', + + + }, + + font: _$font_attributes_231({ + + }) + }, + + font: _$font_attributes_231({ + + }), + + activebgcolor: { + valType: 'color', + + dflt: _$constants_132.gripBgActiveColor, + + }, + bgcolor: { + valType: 'color', + + dflt: _$constants_132.railBgColor, + + }, + bordercolor: { + valType: 'color', + dflt: _$constants_132.railBorderColor, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_132.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_132.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_132.tickColor, + + + }, + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_132.minorTickLength, + + + } +}, 'arraydraw', 'from-root'); + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; + +/* removed: var _$attributes_131 = require('./attributes'); */; +/* removed: var _$constants_132 = require('./constants'); */; + +var __name_133 = _$constants_132.name; +var stepAttrs = _$attributes_131.steps; + + +var _$slidersDefaults_133 = function slidersDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_133, + handleItemDefaults: sliderDefaults + }; + + _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); +}; + +function sliderDefaults(sliderIn, sliderOut, layoutOut) { + + function coerce(attr, dflt) { + return _$lib_163.coerce(sliderIn, sliderOut, _$attributes_131, attr, dflt); + } + + var steps = stepsDefaults(sliderIn, sliderOut); + + var visible = coerce('visible', steps.length > 0); + if(!visible) return; + + coerce('active'); + + coerce('x'); + coerce('y'); + _$lib_163.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_163.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_163.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 stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; + + var valueIn, valueOut; + + function coerce(attr, dflt) { + return _$lib_163.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + } + + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; + + coerce('method'); + + if(!_$lib_163.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + continue; + } + + coerce('args'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); + coerce('execute'); + + valuesOut.push(valueOut); + } + + return valuesOut; +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$d3_7 = require('d3'); */; + +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; + +/* removed: var _$constants_132 = require('./constants'); */; +/* removed: var _$alignment_143 = require('../../constants/alignment'); */; +var __LINE_SPACING_134 = _$alignment_143.LINE_SPACING; +var __FROM_TL_134 = _$alignment_143.FROM_TL; +var __FROM_BR_134 = _$alignment_143.FROM_BR; + +var _$draw_134 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); + + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_132.containerClassName) + .data(sliderData.length > 0 ? [0] : []); + + sliders.enter().append('g') + .classed(_$constants_132.containerClassName, true) + .style('cursor', 'ew-resize'); + + sliders.exit().remove(); + + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_134(gd); + + // Return early if no menus visible: + if(sliderData.length === 0) return; + + var sliderGroups = sliders.selectAll('g.' + _$constants_132.groupClassName) + .data(sliderData, keyFunction); + + sliderGroups.enter().append('g') + .classed(_$constants_132.groupClassName, true); + + sliderGroups.exit().each(function(sliderOpts) { + _$d3_7.select(this).remove(); + + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; + + _$plots_237.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index); + }); + + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); + } + + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; + + var gSlider = _$d3_7.select(this); + + computeLabelSteps(sliderOpts); + + _$plots_237.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; + + if(opts.active === data.index) return; + if(opts._dragging) return; + + setActive(gd, gSlider, opts, data.index, false, true); + }); + + drawSlider(gd, _$d3_7.select(this), sliderOpts); + }); +}; + +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_132.name], + sliderData = []; + + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); + } + + return sliderData; +} + +// This is set in the defaults step: +function keyFunction(opts) { + return opts._index; +} + +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_68.tester.selectAll('g.' + _$constants_132.labelGroupClass) + .data(sliderOpts.steps); + + sliderLabels.enter().append('g') + .classed(_$constants_132.labelGroupClass, true); + + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_7.select(this); + + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_68.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + } + }); + + sliderLabels.remove(); + + var dims = sliderOpts._dims = {}; + + dims.inputAreaWidth = Math.max( + _$constants_132.railWidth, + _$constants_132.gripHeight + ); + + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; + } + + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + + var textableInputLength = dims.inputAreaLength - 2 * _$constants_132.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_132.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; + + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; + + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_68.tester.append('g'); + + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_68.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_184.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); + + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + + dummyGroup.remove(); + } + + dims.height = dims.currentValueTotalHeight + _$constants_132.tickOffset + sliderOpts.ticklen + _$constants_132.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + + var xanchor = 'left'; + if(_$anchor_utils_95.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; + } + if(_$anchor_utils_95.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; + } + + var yanchor = 'top'; + if(_$anchor_utils_95.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_95.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; + } + + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); + + _$plots_237.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_134[xanchor], + r: dims.outerLength * __FROM_BR_134[xanchor], + b: dims.height * __FROM_BR_134[yanchor], + t: dims.height * __FROM_TL_134[yanchor] + }); +} + +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; + } + + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); + + var dims = sliderOpts._dims; + + // Position the rectangle: + _$drawing_68.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); + +} + +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; + + var dims = sliderOpts._dims; + var x0, textAnchor; + + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_132.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_132.currentValueInset; + textAnchor = 'left'; + } + + var text = _$lib_163.ensureSingle(sliderGroup, 'text', _$constants_132.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); + + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; + + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; + } + + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; + } + + text.call(_$drawing_68.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_184.convertToTspans, sliderOpts._gd); + + var lines = _$svg_text_utils_184.lineCount(text); + + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_134; + + _$svg_text_utils_184.positionText(text, x0, y0); + + return text; +} + +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_163.ensureSingle(sliderGroup, 'rect', _$constants_132.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); + + grip.attr({ + width: _$constants_132.gripWidth, + height: _$constants_132.gripHeight, + rx: _$constants_132.gripRadius, + ry: _$constants_132.gripRadius, + }) + .call(_$color_43.stroke, sliderOpts.bordercolor) + .call(_$color_43.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); +} + +function drawLabel(item, data, sliderOpts) { + var text = _$lib_163.ensureSingle(item, 'text', _$constants_132.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); + + text.call(_$drawing_68.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_184.convertToTspans, sliderOpts._gd); + + return text; +} + +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_163.ensureSingle(sliderGroup, 'g', _$constants_132.labelsClass); + var dims = sliderOpts._dims; + + var labelItems = labels.selectAll('g.' + _$constants_132.labelGroupClass) + .data(dims.labelSteps); + + labelItems.enter().append('g') + .classed(_$constants_132.labelGroupClass, true); + + labelItems.exit().remove(); + + labelItems.each(function(d) { + var item = _$d3_7.select(this); + + item.call(drawLabel, d, sliderOpts); + + _$drawing_68.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_132.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_134 + + _$constants_132.labelOffset + + dims.currentValueTotalHeight + ); + }); + +} + +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); + } +} + +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; + + var step = sliderOpts.steps[sliderOpts.active]; + + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); + + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); + + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; + + if(_step.execute) { + _$plots_237.executeAPICommand(gd, _step.method, _step.args); + } + + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } + } +} + +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_7.select(gd); + + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; + } + + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); + + var grip = sliderGroup.select('.' + _$constants_132.gripRectClass); + + _$d3_7.event.stopPropagation(); + _$d3_7.event.preventDefault(); + grip.call(_$color_43.fill, sliderOpts.activebgcolor); + + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_7.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; + + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_7.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); + }); + + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_43.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); + + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); + }); +} + +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_132.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; + + tick.enter().append('rect') + .classed(_$constants_132.tickRectClass, true); + + tick.exit().remove(); + + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); + + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_7.select(this); + + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_43.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + + _$drawing_68.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_132.tickOffset : _$constants_132.minorTickOffset) + dims.currentValueTotalHeight + ); + }); + +} + +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; + + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); + } +} + +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_132.gripRectClass); + + var x = normalizedValueToPosition(sliderOpts, position); + + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; + + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); + } + + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_132.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); +} + +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_132.stepInset + + (dims.inputAreaLength - 2 * _$constants_132.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} + +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_132.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_132.stepInset - 2 * dims.inputAreaStart))); +} + +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_163.ensureSingle(sliderGroup, 'rect', _$constants_132.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); + + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_132.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_43.fill, sliderOpts.bgcolor) + .attr('opacity', 0); + + _$drawing_68.setTranslate(rect, 0, dims.currentValueTotalHeight); +} + +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_132.railInset * 2; + var rect = _$lib_163.ensureSingle(sliderGroup, 'rect', _$constants_132.railRectClass); + + rect.attr({ + width: computedLength, + height: _$constants_132.railWidth, + rx: _$constants_132.railRadius, + ry: _$constants_132.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_43.stroke, sliderOpts.bordercolor) + .call(_$color_43.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); + + _$drawing_68.setTranslate(rect, + _$constants_132.railInset, + (dims.inputAreaWidth - _$constants_132.railWidth) * 0.5 + dims.currentValueTotalHeight + ); +} + +function __clearPushMargins_134(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); + + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + + if(k.indexOf(_$constants_132.autoMarginIdRoot) !== -1) { + _$plots_237.autoMargin(gd, k); + } + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$constants_132 = require('./constants'); */; + +var _$sliders_135 = { + moduleType: 'component', + name: _$constants_132.name, + + layoutAttributes: _$attributes_131, + supplyLayoutDefaults: _$slidersDefaults_133, + + draw: _$draw_134 +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_42 = require('../color/attributes'); */; +var __extendFlat_137 = _$extend_157.extendFlat; +var __overrideAll_137 = _$edit_types_190.overrideAll; +/* removed: var _$pad_attributes_236 = require('../../plots/pad_attributes'); */; + +var buttonsAttrs = { + _isLinkedToArray: 'button', + + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; + +var _$attributes_137 = __overrideAll_137({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], + + visible: { + valType: 'boolean', + + + }, + + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, + + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, + + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, + + showactive: { + valType: 'boolean', + + dflt: true, + + }, + + buttons: buttonsAttrs, + + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, + + pad: __extendFlat_137({}, _$pad_attributes_236, { + + }), + + font: _$font_attributes_231({ + + }), + + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_42.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + + } +}, 'arraydraw', 'from-root'); + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + + +var _$constants_138 = { + + // 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: '▼' + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; + +/* removed: var _$attributes_137 = require('./attributes'); */; +/* removed: var _$constants_138 = require('./constants'); */; + +var __name_139 = _$constants_138.name; +var __buttonAttrs_139 = _$attributes_137.buttons; + + +var _$updateMenusDefaults_139 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_139, + handleItemDefaults: menuDefaults + }; + + _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); +}; + +function menuDefaults(menuIn, menuOut, layoutOut) { + + function coerce(attr, dflt) { + return _$lib_163.coerce(menuIn, menuOut, _$attributes_137, attr, dflt); + } + + var buttons = __buttonsDefaults_139(menuIn, menuOut); + + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; + + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); + + coerce('x'); + coerce('y'); + _$lib_163.noneOrAll(menuIn, menuOut, ['x', 'y']); + + coerce('xanchor'); + coerce('yanchor'); + + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); + + _$lib_163.coerceFont(coerce, 'font', layoutOut.font); + + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} + +function __buttonsDefaults_139(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; + + var buttonIn, buttonOut; + + function coerce(attr, dflt) { + return _$lib_163.coerce(buttonIn, buttonOut, __buttonAttrs_139, attr, dflt); + } + + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; + + coerce('method'); + + if(!_$lib_163.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } + + coerce('args'); + coerce('label'); + coerce('execute'); + + buttonOut._index = i; + buttonsOut.push(buttonOut); + } + + return buttonsOut; +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$ScrollBox_142 = ScrollBox; + +/* removed: var _$d3_7 = require('d3'); */; + +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; + +/* removed: var _$lib_163 = require('../../lib'); */; + +/** + * Helper class to setup a scroll box + * + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box + */ +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; + + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection + + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); + + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} + +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; + +/** + * If needed, setup a clip path and scrollbars + * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; + + // compute position of scrollbox + this.position = position; + + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; + + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; + } + + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; + + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; + } + } + else { + boxT = t; + boxB = boxT + boxH; + + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; + } + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; + } + } + + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; + + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; + + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); + + hbar.exit() + .on('.drag', null) + .remove(); + + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_43.fill, ScrollBox.barColor); + + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); + + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; + } + else { + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } + + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; + + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); + + vbar.exit() + .on('.drag', null) + .remove(); + + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_43.fill, ScrollBox.barColor); + + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); + + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; + } + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } + + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + + clipPath.exit().remove(); + + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); + + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); + + this.container.call(_$drawing_68.setClipUrl, clipId); + + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); + } + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_68.setClipUrl, null); + delete this._clipRect; + } + + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_7.behavior.drag() + .on('dragstart', function() { + _$d3_7.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); + + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); + + var onBarDrag = _$d3_7.behavior.drag() + .on('dragstart', function() { + _$d3_7.event.sourceEvent.preventDefault(); + _$d3_7.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); + + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } + + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } + } + + // set scrollbox translation + this.setTranslate(translateX, translateY); +}; + +/** + * If present, remove clip-path and scrollbars + * + * @method + */ +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_68.setClipUrl, null); + delete this._clipRect; + } + + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } + + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } +}; + +/** + * Handles scroll box drag events + * + * @method + */ +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX -= _$d3_7.event.dx; + } + + if(this.vbar) { + translateY -= _$d3_7.event.dy; + } + + this.setTranslate(translateX, translateY); +}; + +/** + * Handles scroll box wheel events + * + * @method + */ +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX += _$d3_7.event.deltaY; + } + + if(this.vbar) { + translateY += _$d3_7.event.deltaY; + } + + this.setTranslate(translateX, translateY); +}; + +/** + * Handles scroll bar drag events + * + * @method + */ +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_163.constrain(_$d3_7.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); + + var translateXMax = this.position.w - this._box.w; + + translateX = xf * translateXMax; + } + + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_163.constrain(_$d3_7.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); + + var translateYMax = this.position.h - this._box.h; + + translateY = yf * translateYMax; + } + + this.setTranslate(translateX, translateY); +}; + +/** + * Set clip path and scroll bar translate transform + * + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; + + translateX = _$lib_163.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_163.constrain(translateY || 0, 0, translateYMax); + + this.translateX = translateX; + this.translateY = translateY; + + this.container.call(_$drawing_68.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); + + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } + + if(this.hbar) { + var xf = translateX / translateXMax; + + this.hbar.call(_$drawing_68.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); + } + + if(this.vbar) { + var yf = translateY / translateYMax; + + this.vbar.call(_$drawing_68.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_7 = require('d3'); */; + +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; + +var __LINE_SPACING_140 = _$alignment_143.LINE_SPACING; + +/* removed: var _$constants_138 = require('./constants'); */; +/* removed: var _$ScrollBox_142 = require('./scrollbox'); */; + +var _$draw_140 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); + + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ + + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_138.containerClassName) + .data(menuData.length > 0 ? [0] : []); + + menus.enter().append('g') + .classed(_$constants_138.containerClassName, true) + .style('cursor', 'pointer'); + + menus.exit().remove(); + + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_140(gd); + + // return early if no update menus are visible + if(menuData.length === 0) return; + + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_138.headerGroupClassName) + .data(menuData, __keyFunction_140); + + headerGroups.enter().append('g') + .classed(_$constants_138.headerGroupClassName, true); + + // draw dropdown button container + var gButton = _$lib_163.ensureSingle(menus, 'g', _$constants_138.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); + + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_140(gd, menuOpts); + } + + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_142(gd, gButton, scrollBoxId); + + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); + + gButton + .call(removeAllButtons) + .attr(_$constants_138.menuIndexAttrName, '-1'); + } + + headerGroups.exit().each(function(menuOpts) { + _$d3_7.select(this).remove(); + + gButton + .call(removeAllButtons) + .attr(_$constants_138.menuIndexAttrName, '-1'); + + _$plots_237.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index); + }); -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_7.select(this); -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_237.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_140(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + // if this menu is active, update the dropdown container + if(__isActive_140(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); + } - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; + }); +}; + +/** + * get only visible menus for display + */ +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_138.name]; + var menuData = []; + + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + + if(item.visible) menuData.push(item); + } + + return menuData; +} + +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_140(menuOpts) { + return menuOpts._index; +} + +function isFolded(gButton) { + return +gButton.attr(_$constants_138.menuIndexAttrName) === -1; +} + +function __isActive_140(gButton, menuOpts) { + return +gButton.attr(_$constants_138.menuIndexAttrName) === menuOpts._index; +} + +function __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; + + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); + } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_138.menuIndexAttrName, '-1'); + + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } +} + +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_163.ensureSingle(gHeader, 'g', _$constants_138.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); + + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_138.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; + + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); + + // draw drop arrow at the right edge + var arrow = _$lib_163.ensureSingle(gHeader, 'text', _$constants_138.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_68.font, menuOpts.font) + .text(_$constants_138.arrowSymbol[menuOpts.direction]); + }); + + arrow.attr({ + x: dims.headerWidth - _$constants_138.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_138.textOffsetY + menuOpts.pad.t + }); + + header.on('click', function() { + gButton.call(removeAllButtons); + + + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_138.menuIndexAttrName, + __isActive_140(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); + + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); + + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); + + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); + + // translate header group + _$drawing_68.setTranslate(gHeader, dims.lx, dims.ly); +} + +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } + + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; + + var klass = menuOpts.type === 'dropdown' ? _$constants_138.dropdownButtonClassName : _$constants_138.buttonClassName; + + var buttons = gButton.selectAll('g.' + klass) + .data(buttonData); + + var enter = buttons.enter().append('g') + .classed(klass, true); + + var exit = buttons.exit(); + + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); + + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); + } + + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; + + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_138.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_138.gapButtonHeader; + } + } + + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openHeight; + } + + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openWidth; + } + + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_138.gapButton, + xPad: _$constants_138.gapButton, + index: 0, + }; + + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; + + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_7.select(this); + + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); + + button.on('click', function() { + // skip `dragend` events + if(_$d3_7.event.defaultPrevented) return; + + __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + + if(buttonOpts.execute) { + _$plots_237.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } + + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); + + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); + + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); + + buttons.call(styleButtons, menuOpts); + + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + } + + scrollBoxPosition.direction = menuOpts.direction; + + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } +} + +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; + + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_138.gapButton; + } + } + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_138.gapButton; + } + } + + scrollBox.enable(position, translateX, translateY); + + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } + + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } +} + +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; + + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } + + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); + } +} + +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); +} + +function drawItemRect(item, menuOpts) { + var rect = _$lib_163.ensureSingle(item, 'rect', _$constants_138.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_138.rx, + ry: _$constants_138.ry, + 'shape-rendering': 'crispEdges' + }); + }); + + rect.call(_$color_43.stroke, menuOpts.bordercolor) + .call(_$color_43.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} + +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_163.ensureSingle(item, 'text', _$constants_138.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); + + text.call(_$drawing_68.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_184.convertToTspans, gd); +} + +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; + + buttons.each(function(buttonOpts, i) { + var button = _$d3_7.select(this); + + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_138.itemRectClassName) + .call(_$color_43.fill, _$constants_138.activeColor); + } + }); +} + +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_138.itemRectClassName) + .call(_$color_43.fill, _$constants_138.hoverColor); +} + +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_138.itemRectClassName) + .call(_$color_43.fill, menuOpts.bgcolor); +} + +// find item dimensions (this mutates menuOpts) +function __findDimensions_140(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; + + var fakeButtons = _$drawing_68.tester.selectAll('g.' + _$constants_138.dropdownButtonClassName) + .data(menuOpts.buttons); + + fakeButtons.enter().append('g') + .classed(_$constants_138.dropdownButtonClassName, true); + + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_7.select(this); + + button.call(drawItem, menuOpts, buttonOpts, gd); + + var text = button.select('.' + _$constants_138.itemTextClassName); + + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_68.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_138.textPadX, _$constants_138.minWidth); + + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_140; + var tLines = _$svg_text_utils_184.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_138.minHeight) + _$constants_138.textOffsetY; + + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); + + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; + + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); + + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_138.gapButton; + dims.openHeight += hEff + _$constants_138.gapButton; + } else { + dims.totalWidth += wEff + _$constants_138.gapButton; + dims.openWidth += wEff + _$constants_138.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); + + if(isVertical) { + dims.totalHeight -= _$constants_138.gapButton; + } else { + dims.totalWidth -= _$constants_138.gapButton; + } - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; + dims.headerWidth = dims.width1 + _$constants_138.arrowPadX; + dims.headerHeight = dims.height1; - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_138.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_138.arrowPadX; + } - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; + fakeButtons.remove(); - // categorize where intersection point is along A and B + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + var xanchor = 'left'; + if(_$anchor_utils_95.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_95.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + var yanchor = 'top'; + if(_$anchor_utils_95.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_95.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; + } - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; + _$plots_237.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); } -var _$Epsilon_18 = Epsilon; +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_138.itemRectClassName); + var text = item.select('.' + _$constants_138.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + _$drawing_68.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + var tHeight = menuOpts.font.size * __LINE_SPACING_140; + var tLines = _$svg_text_utils_184.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); - // 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] }); - } + _$svg_text_utils_184.positionText(text, _$constants_138.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_138.textOffsetY); - // the first LineString is considered the outside - var out = LineString(coords[0]); + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; + } - // 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]))); + posOpts.index++; +} - return out; - } +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_138.dropdownButtonClassName).remove(); +} - 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'); - }, +function __clearPushMargins_140(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - // 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)); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - // 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); - } + if(k.indexOf(_$constants_138.autoMarginIdRoot) !== -1) { + _$plots_237.autoMargin(gd, k); + } + } +} - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function newNode(region){ - return { - region: region, - children: [] - }; - } +'use strict'; - var roots = newNode(null); +/* removed: var _$constants_138 = require('./constants'); */; - 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; - } - } +var _$updatemenus_141 = { + moduleType: 'component', + name: _$constants_138.name, - // 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--; - } - } + layoutAttributes: _$attributes_137, + supplyLayoutDefaults: _$updateMenusDefaults_139, - // now we can add ourselves - root.children.push(node); - } + draw: _$draw_140 +}; - // 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); - } +var _$mathjax_config_149 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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 +'use strict'; - // while we're at it, exteriors are counter-clockwise, and interiors are clockwise +/* global MathJax:false */ - 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; - } +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_149.MathJax = true; - var geopolys = []; + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); - 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])); - } + MathJax.Hub.Configured(); +} else { + _$mathjax_config_149.MathJax = false; +} - 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); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); - // lastly, construct the approrpriate GeoJSON object +'use strict'; - 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 - }; - } -}; +/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$plot_config_195 = require('../plot_api/plot_config'); */; -var _$GeoJSON_19 = GeoJSON; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + for(var i = 0; i < args.length; i++) { + arg = args[i]; -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_163.extendDeep([], arg) : + _$lib_163.extendDeepAll({}, arg); + } + else copy[i] = arg; + } -var _$LinkedList_21 = LinkedList; + return copy; +} -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs -// -// this is the core work-horse -// +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- + + +var __queue_177 = {}; + +// TODO: disable/enable undo and redo buttons appropriately + +/** + * Add an item to the undoQueue for a graphDiv + * + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with + */ +__queue_177.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; + + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; + + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } + + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; + + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } + + if(gd.undoQueue.queue.length > _$plot_config_195.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; -/* removed: var _$LinkedList_21 = require('./linked-list'); */; +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_177.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_177.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; +}; - // - // segment creation - // +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_177.undo = function undo(gd) { + var queueObj, i; - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; - // - // event logic - // + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - var event_root = _$LinkedList_21.create(); + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_177.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd + */ +__queue_177.redo = function redo(gd) { + var queueObj, i; - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_177.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; +}; - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_21.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_177.plotDo = function(gd, func, args) { + gd.autoplay = true; - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_21.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + // call the supplied function + func.apply(null, args); +}; - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) +var _$queue_177 = __queue_177; - if (buildLog) - buildLog.segmentChop(ev.seg, end); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } +'use strict'; - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } +var _$localeEnUs_187 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } +}; - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // - // status logic - // +'use strict'; - var status_root = _$LinkedList_21.create(); +var _$localeEn_188 = { + 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' + } +}; - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; +var _$fromQuat_11 = fromQuat; - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } +/** + * 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, - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + 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; - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; - if (buildLog) - buildLog.checkIntersection(seg1, seg2); + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; - var i = eps.linesIntersect(a1, a2, b1, b2); + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; - if (i === false){ - // segments are parallel or coincident + return out; +}; +var _$helpers_191 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection +'use strict'; - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); +/* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_11 = require('gl-mat4/fromQuat'); */; - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal +/* removed: var _$registry_245 = require('../registry'); */; +/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$plots_237 = require('../plots/plots'); */; +/* removed: var _$axis_ids_208 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_208.cleanId; +var getFromTrace = _$axis_ids_208.getFromTrace; +/* removed: var _$color_43 = require('../components/color'); */; - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); +// clear the promise queue if one of them got rejected +_$helpers_191.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_163.log('Clearing previous rejected promises from queue.'); + } - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } + gd._promises = []; +}; - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_191.cleanLayout = function(layout) { + var i, j; - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + if(!layout) layout = {}; - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); + var axisAttrRegex = (_$plots_237.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_237.subplotsRegistry.gl3d || {}).attrRegex; - if (buildLog) - buildLog.vert(ev.pt[0]); + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[i]; - if (ev.isStart){ + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; + } + delete ax.autotick; + } + } - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev + // clean old Camera coords + var cameraposition = scene.cameraposition; - // merge ev.seg's fill information into eve.seg + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_11([], rotation), + eye = []; - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; - if (buildLog) - buildLog.segmentUpdate(eve.seg); + delete scene.cameraposition; + } + } + } - ev.other.remove(); - ev.remove(); - } + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } + if(!_$lib_163.isPlainObject(ann)) continue; - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; + } + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; + } - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); + } - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + if(!_$lib_163.isPlainObject(shape)) continue; - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); + } - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_21.node({ ev: ev })); - } - else{ - var st = ev.status; + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; - if (buildLog) - buildLog.statusRemove(st.ev.seg); + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_43.clean(layout); - // remove the status - st.remove(); + return layout; +}; - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); + } +} - // remove the event and continue - event_root.getHead().remove(); - } +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_191.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); - if (buildLog) - buildLog.done(); + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; - return segments; - } + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } + for(i = 0; i < 100; i++) { + newUid = _$lib_163.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_163.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; + // BACKWARD COMPATIBILITY FIXES - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; -} + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_43.defaults, + yeColor = trace.error_y.color || + (_$registry_245.traceIs(trace, 'bar') ? _$color_43.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_43.addOpacity( + _$color_43.rgb(yeColor), + _$color_43.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; + } -var _$Intersecter_20 = Intersecter; + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_245.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_191.swapXYData(trace); + } + delete trace.bardir; + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_191.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } + // scene ids scene1 -> scene + if(_$registry_245.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_237.subplotsRegistry.gl3d.cleanId(trace.scene); + } - if (buildLog) - buildLog.chainStart(seg); + if(!_$registry_245.traceIs(trace, 'pie') && !_$registry_245.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + // fix typo in colorscale definition + if(_$registry_245.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_245.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_163.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; - if (next_match === second_match){ - // we matched a single chain + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; - if (buildLog) - buildLog.chainMatch(first_match.index); + if(!_$lib_163.isPlainObject(opts)) continue; - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } + } - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; - if (buildLog) - buildLog.chainClose(first_match.index); + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; - // we have a closed chain! - regions.push(chain); - return; - } + if(!_$lib_163.isPlainObject(transform)) continue; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } - // otherwise, we matched two chains, so we need to combine those chains together + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } + } - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_43.clean(trace); + } +}; - var F = first_match.index; - var S = second_match.index; +function cleanFinanceDir(dirContainer) { + if(!_$lib_163.isPlainObject(dirContainer)) return false; - if (buildLog) - buildLog.chainConnect(F, S); + var dirName = dirContainer.name; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); + delete dirContainer.name; + delete dirContainer.showlegend; - return regions; + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); } -var _$SegmentChainer_22 = SegmentChainer; +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; -// -// filter a list of segments based on boolean operations -// + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + var out = name1.substr(0, i); + return out.trim(); +} - if (buildLog) - buildLog.selected(result); +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; - return result; + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; + + return posY + ' ' + posX; } -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} + + +// swap all the data and data attributes associated with x and y +_$helpers_191.swapXYData = function(trace) { + var i; + _$lib_163.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_163.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_163.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); + } }; -var _$SegmentSelector_23 = SegmentSelector; +// coerce traceIndices input to array of trace indices +_$helpers_191.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_10(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); + } -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs + return traceIndices; +}; + +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * */ +_$helpers_191.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; -/* removed: var _$BuildLog_17 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_18 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_20 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_22 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_23 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_19 = require('./lib/geojson'); */; + var pLastIsNumber = _$fastIsnumeric_10(pLast); -var buildLog = false; -var epsilon = _$Epsilon_18(); + // delete item + if(pLastIsNumber && newVal === null) { -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_17(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_163.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); - // core API - segments: function(poly){ - var i = _$Intersecter_20(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_20(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_23.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_23.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_23.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_23.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_23.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_22(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_19.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_19.fromPolygon(PolyBool, epsilon, poly); - }, + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; - // 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); - } + np.set(newVal); + } + // update item + else { + + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); + } }; -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); +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); } -if (typeof window === 'object') - window.PolyBool = PolyBool; +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_191.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; +}; + +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_191 = ['x', 'y', 'z']; +_$helpers_191.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_191[j]); + + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; + } + var typeAttr = axAttr + '.type'; -var _$PolyBool_16 = PolyBool; + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_163.nestedProperty(gd.layout, typeAttr).set(null); + } + } + } + } +}; + +_$helpers_191.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; + } + } +}; -var _$polygon_174 = {}; +var _$manage_arrays_193 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -52582,293 +53780,209 @@ var _$polygon_174 = {}; 'use strict'; -var dot = _$matrix_168.dot; -var __BADNUM_174 = _$numerical_145.BADNUM; - -var polygon = _$polygon_174 = {}; +/* removed: var _$nestedProperty_171 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_165 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_172 = require('../lib/noop'); */; +/* removed: var _$loggers_168 = require('../lib/loggers'); */; +var sorterAsc = _$search_181.sorterAsc; +/* removed: var _$registry_245 = require('../registry'); */; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; +_$manage_arrays_193.containerArrayMatch = _$containerArrayMatch_189; - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } +var isAddVal = _$manage_arrays_193.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_165(val); +}; - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed +var isRemoveVal = _$manage_arrays_193.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; - var isRect = false, - rectFirstEdgeTest; +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. + * + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items + * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. + */ +_$manage_arrays_193.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_245.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_245.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_245.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_172) || + (draw === _$noop_172), + layout = gd.layout, + fullLayout = gd._fullLayout; - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_168.warn('Full array edits are incompatible with other edits', + componentType); } - } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var fullVal = edits['']['']; - if(x === __BADNUM_174 || x < xmin || x > xmax || y === __BADNUM_174 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_168.warn('Unrecognized full array edit value', componentType, fullVal); + return true; } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + if(replotLater) return false; + + supplyComponentDefaults(layout, fullLayout); + draw(gd); return true; } - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_171(fullLayout, componentType).get(); - if(x === __BADNUM_174 || x < xmin || x > xmax || y === __BADNUM_174 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_168.warn('index out of range', componentType, componentNum); + continue; + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_168.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; + + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } - // inside the bounding box, check the actual line intercept else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } - - if(y <= ycross && x !== xmini) crossings++; + _$loggers_168.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); } - } - - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; + if(firstIndexChange === -1) firstIndexChange = componentNum; } - } - - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; - -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; - - for(var i = 0; i < list.length; i++) { - 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); - } - - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_171(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } - - return yes; } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; - -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; - - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); - - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - return false; -}; -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); + if(replotLater) return false; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; + supplyComponentDefaults(layout, fullLayout); + + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_172) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); } } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); + } } + else draw(gd); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); - } - - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; + return true; }; +var _$buttons_105 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -52880,1483 +53994,1166 @@ polygon.filter = function filter(pts, tolerance) { 'use strict'; -/* removed: var _$PolyBool_16 = require('polybooljs'); */; -/* removed: var _$polygon_174 = require('../../lib/polygon'); */; -/* removed: var _$throttle_184 = require('../../lib/throttle'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -var makeEventData = _$helpers_82.makeEventData; -/* removed: var _$fx_85 = require('../../components/fx'); */; - -/* removed: var _$axes_204 = require('./axes'); */; -/* removed: var _$constants_209 = require('./constants'); */; - -var filteredPolygon = _$polygon_174.filter; -var polygonTester = _$polygon_174.tester; -var multipolygonTester = _$polygon_174.multitester; -var MINSELECT = _$constants_209.MINSELECT; - -function getAxId(ax) { return ax._id; } - -var _$prepSelect_222 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } - - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_209.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'); +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$plots_237 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_43.background, - stroke: _$color_43.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +var ____105 = _$lib_163._; +var modeBarButtons = _$buttons_105 = {}; - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_209.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; +/** + * 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? + */ - 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; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____105(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + _$lib_163.notifier(____105(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_204.getFromId(gd, trace.xaxis), - yaxis: _$axes_204.getFromId(gd, trace.yaxis) - }); + if(_$lib_163.isIE()) { + _$lib_163.notifier(____105(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; } - } - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + _$registry_245.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_163.notifier(____105(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_163.notifier(____105(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); } +}; - function ascending(a, b) { return a - b; } +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____105(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_237.sendDataToCloud(gd); + } +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____105(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____105(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____105(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian +}; - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____105(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } - } +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____105(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian +}; - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____105(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian +}; - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____105(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____105(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____105(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____105(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +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 = _$axis_ids_208.list(gd, null, true); + var allSpikesEnabled = 'on'; - _$throttle_184.throttle( - throttleID, - _$constants_209.SELECTDELAY, - function() { - selection = []; + var ax, i; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); + var axName; - thisSelection = fillSelectionItem(traceSelection, searchInfo); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); + 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]; + } + if(ax._showSpikeInitial !== undefined) { + aobj[axName + '.showspikes'] = ax._showSpikeInitial; + if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) { + allSpikesEnabled = 'off'; } } - else selection = thisSelection; } + else { + var rangeNow = [ + ax.r2l(ax.range[0]), + ax.r2l(ax.range[1]), + ]; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; - - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - _$throttle_184.done(throttleID).then(function() { - _$throttle_184.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); } - - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); } - else { - // 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. - gd.emit('plotly_selected', undefined); + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } - _$fx_85.click(gd, evt); - }); - }; - - dragOptions.doneFn = function() { - corners.remove(); + aobj[astr] = val; + } - _$throttle_184.done(throttleID).then(function() { - _$throttle_184.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); + _$registry_245.call('relayout', gd, aobj); +} - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____105(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d +}; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____105(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____105(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - if(eventData) { - var pts = eventData.points || []; +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____105(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['z-axis'], + click: handleDrag3d +}; - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +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 = {}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; + var parts = attr.split('.'); - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); - } - } + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - else { - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; + + _$registry_245.call('relayout', gd, layoutUpdate); +} + +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____105(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; + +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____105(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.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], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; + + if(attr === 'resetDefault') { + aobj[key] = null; + } + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_163.extendDeep({}, scene.cameraInitial); } } - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } + _$registry_245.call('relayout', gd, aobj); } -function mergePolygons(list, poly, subtract) { - var res; +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - if(subtract) { - res = _$PolyBool_16.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - return res.regions; + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; + + if(val) { + layoutUpdate = _$lib_163.extendDeep(layout, val); + button._previousVal = null; } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - res = _$PolyBool_16.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; - return res.regions; -} + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; -function fillSelectionItem(selection, searchInfo) { - if(Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - for(var i = 0; i < selection.length; i++) { - selection[i] = makeEventData(selection[i], trace, cd); + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + } + } } + + button._previousVal = _$lib_163.extendDeep({}, currentSpikes); } - return selection; + _$registry_245.call('relayout', gd, layoutUpdate); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____105(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____105(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; -'use strict'; +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____105(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; -/* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_13 = require('has-passive-events'); */; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$setCursor_181 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; -var __FROM_TL_212 = _$alignment_143.FROM_TL; +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; -/* removed: var _$plots_237 = require('../plots'); */; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; -var doTicks = _$axes_204.doTicks; -var getFromId = _$axis_ids_207.getFromId; -/* removed: var _$prepSelect_222 = require('./select'); */; -/* removed: var _$scaleZoom_221 = require('./scale_zoom'); */; + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; -/* removed: var _$constants_209 = require('./constants'); */; -var MINDRAG = _$constants_209.MINDRAG; -var MINZOOM = _$constants_209.MINZOOM; + _$registry_245.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); + } + } +} +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px +function toggleHover(gd) { var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + } + else onHoverVal = 'closest'; - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$registry_245.call('relayout', gd, 'hovermode', newHover); +} - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); +// buttons when more then one plot types are present - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____105(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); } +}; - recomputeAxisLists(); +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____105(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - var allFixedRanges = !yActive && !xActive; + var aobj = setSpikelineVisibility(gd); - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; + _$registry_245.call('relayout', gd, aobj); } +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_222(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_208.list(gd, null, true); + var aobj = {}; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + var ax, axName; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - if(numClicks === 2 && !singleEnd) doubleClick(); + return aobj; +} - if(isMainDrag) { - _$fx_85.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____105(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if(ax.fixedrange) return; +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; + 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); - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_7.select(dragger) - .call(_$svg_text_utils_183.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_244.call('relayout', gd, attrStr, v); - } - }); - } - } + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; } - }; - - _$dragelement_65.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + } - // collected changes to be made to the plot by relayout at the end - var updates = {}; + _$registry_245.call('relayout', gd, aObj); +} - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_25(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); +'use strict'; - clearSelect(zoomlayer); - } +/* removed: var _$d3_7 = require('d3'); */; - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +/** + * 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'); - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } + this.update(opts.graphInfo, opts.buttons); - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; + this.container.appendChild(this.element); +} - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } +var proto = ModeBar.prototype; - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } +/** + * 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; - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); + var context = this.graphInfo._context; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; } + else this.element.className = 'modebar'; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_209.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - var pc = gd.querySelector('.plotly'); + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - recomputeAxisLists(); + this.updateButtons(buttons); - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - clearTimeout(redrawTimer); + this.updateActiveButton(); +}; - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_162.log('Did not find wheel motion attributes: ', e); - return; - } +proto.updateButtons = function(buttons) { + var _this = this; - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - var axRange = _$lib_162.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + 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); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +proto.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * 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, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_7.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +proto.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_221(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_221(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * 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, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_7.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_163.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * 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((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_244.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_244.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_244.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +proto.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_163._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +proto.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +proto.destroy = function() { + _$lib_163.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_244.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_7.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_162.syncOrAsync([ - _$plots_237.previousPromises, - function() { _$registry_244.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_108 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_245 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_221(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_108 = require('./modebar'); */; +/* removed: var _$buttons_105 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_212[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_107 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_162.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_162.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_108(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_68.setTranslate, clipDx, clipDy) - .call(_$drawing_68.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_68.setTranslate, plotDx, plotDy) - .call(_$drawing_68.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_68.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_68.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_68.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_68.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_105[button]); } - } - - return dragger; -} - -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - dragger3.call(_$setCursor_181, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_7.select(dragger).call(_$drawing_68.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_7.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_7.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_208.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_43.background, - stroke: _$color_43.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_245.traceIs(trace, 'scatter-like')) { + if(_$subtypes_303.hasMarkers(trace) || _$subtypes_303.hasText(trace)) { + selectable = true; + } + } else if(_$registry_245.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_7.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_162.notifier(_$lib_162._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_105[button] !== undefined) { + customButtons[i][j] = _$buttons_105[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_162.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_13) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_212 = { - makeDragBox: makeDragBox, +var _$modebar_106 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_106.manage = _$manageModeBar_107; +var _$constraints_212 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -54368,152 +55165,202 @@ var _$dragbox_212 = { 'use strict'; -/* removed: var _$d3_7 = require('d3'); */; +var __id2name_212 = _$axis_ids_208.id2name; +/* removed: var _$scaleZoom_221 = require('./scale_zoom'); */; +var __makePadFn_212 = _$autorange_204.makePadFn; -/* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_145.ALMOST_EQUAL; -/* removed: var _$constants_209 = require('./constants'); */; -var __makeDragBox_213 = _$dragbox_212.makeDragBox; +var __FROM_BL_212 = _$alignment_143.FROM_BL; -var _$initInteractions_213 = function initInteractions(gd) { + +_$constraints_212.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_7.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - 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'), - 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)); + 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_212(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_209.DRAGGERSIZE; + // 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; - // 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_213(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + if(mode === 'range') { + _$scaleZoom_221(ax, factor); + } + else { + // mode === 'domain' - 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) { - _$fx_85.hover(gd, evt, subplot); + 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_221(ax, factor); + continue; } - }; - _$fx_85.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_212(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_65.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_213(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_213(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_213(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_213(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_213(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_213(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_213(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_213(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_213(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_213(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_212.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_85.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_85.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_212[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_196 = {}; +var _$subroutines_197 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -54525,21 +55372,27 @@ var _$subroutines_196 = {}; 'use strict'; /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$registry_244 = require('../registry'); */; +/* removed: var _$registry_245 = require('../registry'); */; /* removed: var _$plots_237 = require('../plots/plots'); */; -/* removed: var _$lib_162 = require('../lib'); */; + +/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$clearGlCanvases_152 = require('../lib/clear_gl_canvases'); */; /* removed: var _$color_43 = require('../components/color'); */; /* removed: var _$drawing_68 = require('../components/drawing'); */; /* removed: var _$titles_136 = require('../components/titles'); */; /* removed: var _$modebar_106 = require('../components/modebar'); */; -/* removed: var _$axes_204 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_213 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_209 = require('../plots/cartesian/constants'); */; + +/* removed: var _$axes_205 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_210 = require('../plots/cartesian/constants'); */; /* removed: var _$alignment_143 = require('../constants/alignment'); */; +/* removed: var _$constraints_212 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_212.enforce; +var cleanAxisConstraints = _$constraints_212.clean; +var __doAutoRange_197 = _$autorange_204.doAutoRange; -_$subroutines_196.layoutStyles = function(gd) { - return _$lib_162.syncOrAsync([_$plots_237.doAutoMargin, _$subroutines_196.lsInner], gd); +_$subroutines_197.layoutStyles = function(gd) { + return _$lib_163.syncOrAsync([_$plots_237.doAutoMargin, _$subroutines_197.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -54557,11 +55410,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_196.lsInner = function(gd) { +_$subroutines_197.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_204.list(gd); + var axList = _$axes_205.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -54640,31 +55493,17 @@ _$subroutines_196.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_163.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -54696,23 +55535,17 @@ _$subroutines_196.lsInner = function(gd) { } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_163.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); _$drawing_68.setTranslate(plotinfo.plot, xa._offset, ya._offset); @@ -54721,16 +55554,16 @@ _$subroutines_196.lsInner = function(gd) { if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } _$drawing_68.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_209.traceLayerClasses.length; i++) { - var layer = _$constants_209.traceLayerClasses[i]; + for(i = 0; i < _$constants_210.traceLayerClasses.length; i++) { + var layer = _$constants_210.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { plotinfo.plot.selectAll('g.' + layer).call(_$drawing_68.setClipUrl, layerClipId); } @@ -54854,8 +55687,8 @@ _$subroutines_196.lsInner = function(gd) { plotinfo.ylines.attr('d', yPath); }); - _$axes_204.makeClipPaths(gd); - _$subroutines_196.drawMainTitle(gd); + _$axes_205.makeClipPaths(gd); + _$subroutines_197.drawMainTitle(gd); _$modebar_106.manage(gd); return gd._promises.length && Promise.all(gd._promises); @@ -54912,7 +55745,7 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_196.drawMainTitle = function(gd) { +_$subroutines_197.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; _$titles_136.draw(gd, 'gtitle', { @@ -54931,7 +55764,7 @@ _$subroutines_196.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_196.doTraceStyle = function(gd) { +_$subroutines_197.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -54941,12 +55774,12 @@ _$subroutines_196.doTraceStyle = function(gd) { } _$plots_237.style(gd); - _$registry_244.getComponentMethod('legend', 'draw')(gd); + _$registry_245.getComponentMethod('legend', 'draw')(gd); return _$plots_237.previousPromises(gd); }; -_$subroutines_196.doColorBars = function(gd) { +_$subroutines_197.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -54954,7 +55787,7 @@ _$subroutines_196.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_244.traceIs(trace, 'contour')) { + if(_$registry_245.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -54963,7 +55796,7 @@ _$subroutines_196.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_244.traceIs(trace, 'markerColorscale')) { + if(_$registry_245.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); @@ -54974,28 +55807,33 @@ _$subroutines_196.doColorBars = function(gd) { }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_196.layoutReplot = function(gd) { +_$subroutines_197.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_244.call('plot', gd, '', layout); + return _$registry_245.call('plot', gd, '', layout); }; -_$subroutines_196.doLegend = function(gd) { - _$registry_244.getComponentMethod('legend', 'draw')(gd); +_$subroutines_197.doLegend = function(gd) { + _$registry_245.getComponentMethod('legend', 'draw')(gd); return _$plots_237.previousPromises(gd); }; -_$subroutines_196.doTicksRelayout = function(gd) { - _$axes_204.doTicks(gd, 'redraw'); - _$subroutines_196.drawMainTitle(gd); +_$subroutines_197.doTicksRelayout = function(gd) { + _$axes_205.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_152(gd); + _$registry_245.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_197.drawMainTitle(gd); return _$plots_237.previousPromises(gd); }; -_$subroutines_196.doModeBar = function(gd) { +_$subroutines_197.doModeBar = function(gd) { var fullLayout = gd._fullLayout; _$modebar_106.manage(gd); - _$initInteractions_213(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; @@ -55005,7 +55843,7 @@ _$subroutines_196.doModeBar = function(gd) { return _$plots_237.previousPromises(gd); }; -_$subroutines_196.doCamera = function(gd) { +_$subroutines_197.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -55017,212 +55855,86 @@ _$subroutines_196.doCamera = function(gd) { } }; -var _$constraints_211 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_211 = _$axis_ids_207.id2name; -/* removed: var _$scaleZoom_221 = require('./scale_zoom'); */; -var __makePadFn_211 = _$autorange_203.makePadFn; - -var ALMOST_EQUAL = _$numerical_145.ALMOST_EQUAL; - -var __FROM_BL_211 = _$alignment_143.FROM_BL; - - -_$constraints_211.enforce = function enforceAxisConstraints(gd) { +_$subroutines_197.drawData = function(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_211(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_245.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_221(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_221(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_152(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_211(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_237.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_245.getComponentMethod('shapes', 'draw')(gd); + _$registry_245.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_237.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_197.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_205.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_197(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_211.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_211[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_197.finalDraw = function(gd) { + _$registry_245.getComponentMethod('shapes', 'draw')(gd); + _$registry_245.getComponentMethod('images', 'draw')(gd); + _$registry_245.getComponentMethod('annotations', 'draw')(gd); + _$registry_245.getComponentMethod('legend', 'draw')(gd); + _$registry_245.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_245.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_245.getComponentMethod('sliders', 'draw')(gd); + _$registry_245.getComponentMethod('updatemenus', 'draw')(gd); +}; var _$micropolar_241 = {}; /** @@ -55234,8 +55946,8 @@ var _$micropolar_241 = {}; */ /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$lib_162 = require('../../../lib'); */; -var __extendDeepAll_241 = _$lib_162.extendDeepAll; +/* removed: var _$lib_163 = require('../../../lib'); */; +var __extendDeepAll_241 = _$lib_163.extendDeepAll; var __MID_SHIFT_241 = _$alignment_143.MID_SHIFT; var µ = _$micropolar_241 = { version: '0.2.2' }; @@ -56723,12 +57435,12 @@ var _$micropolar_manager_242 = {}; 'use strict'; /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$lib_162 = require('../../../lib'); */; +/* removed: var _$lib_163 = require('../../../lib'); */; /* removed: var _$color_43 = require('../../../components/color'); */; /* removed: var _$micropolar_241 = require('./micropolar'); */; /* removed: var _$UndoManager_243 = require('./undo_manager'); */; -var __extendDeepAll_242 = _$lib_162.extendDeepAll; +var __extendDeepAll_242 = _$lib_163.extendDeepAll; var manager = _$micropolar_manager_242 = {}; @@ -56810,7 +57522,7 @@ var Polar = _$legacy_240 = _$micropolar_241; Polar.manager = _$micropolar_manager_242; -var _$plot_api_193 = {}; +var _$plot_api_194 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -56827,33 +57539,29 @@ var _$plot_api_193 = {}; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; /* removed: var _$hasHover_12 = require('has-hover'); */; -/* removed: var _$lib_162 = require('../lib'); */; -/* removed: var _$Events_155 = require('../lib/events'); */; -/* removed: var _$queue_176 = require('../lib/queue'); */; +/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$Events_156 = require('../lib/events'); */; +/* removed: var _$queue_177 = require('../lib/queue'); */; -/* removed: var _$registry_244 = require('../registry'); */; -/* removed: var _$plot_schema_195 = require('./plot_schema'); */; +/* removed: var _$registry_245 = require('../registry'); */; +/* removed: var _$plot_schema_196 = require('./plot_schema'); */; /* removed: var _$plots_237 = require('../plots/plots'); */; /* removed: var _$legacy_240 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_213 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$axes_204 = require('../plots/cartesian/axes'); */; +/* removed: var _$axes_205 = require('../plots/cartesian/axes'); */; /* removed: var _$drawing_68 = require('../components/drawing'); */; /* removed: var _$color_43 = require('../components/color'); */; +var initInteractions = _$graph_interact_214.initInteractions; /* removed: var _$xmlns_namespaces_147 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_183 = require('../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_184 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_194 = require('./plot_config'); */; -/* removed: var _$manage_arrays_192 = require('./manage_arrays'); */; -/* removed: var _$helpers_190 = require('./helpers'); */; -/* removed: var _$subroutines_196 = require('./subroutines'); */; -/* removed: var _$edit_types_189 = require('./edit_types'); */; +/* removed: var _$plot_config_195 = require('./plot_config'); */; +/* removed: var _$manage_arrays_193 = require('./manage_arrays'); */; +/* removed: var _$helpers_191 = require('./helpers'); */; +/* removed: var _$subroutines_197 = require('./subroutines'); */; +/* removed: var _$edit_types_190 = require('./edit_types'); */; -/* removed: var _$constants_209 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_211 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_211.enforce; -var cleanAxisConstraints = _$constraints_211.clean; -var __doAutoRange_193 = _$autorange_203.doAutoRange; +var AX_NAME_PATTERN = _$constants_210.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -56879,15 +57587,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_193.plot = function(gd, data, layout, config) { +_$plot_api_194.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_162.getGraphDiv(gd); + gd = _$lib_163.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_155.init(gd); + _$Events_156.init(gd); - if(_$lib_162.isPlainObject(data)) { + if(_$lib_163.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -56895,19 +57603,19 @@ _$plot_api_193.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_155.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_156.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_162.isPlotDiv(gd)) { - _$lib_162.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_163.isPlotDiv(gd)) { + _$lib_163.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_193.addFrames(gd, frames); + return _$plot_api_194.addFrames(gd, frames); } } @@ -56926,6 +57634,9 @@ _$plot_api_193.plot = function(gd, data, layout, config) { // so we can share cached text across tabs _$drawing_68.makeTester(); + // clear stashed base url + delete _$drawing_68.baseUrl; + // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all @@ -56937,7 +57648,7 @@ _$plot_api_193.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_190.cleanData(data, gd.data); + _$helpers_191.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -56948,7 +57659,7 @@ _$plot_api_193.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_190.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_191.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -56970,7 +57681,7 @@ _$plot_api_193.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_162.log('Legacy polar charts are deprecated!'); + _$lib_163.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -56991,7 +57702,7 @@ _$plot_api_193.plot = function(gd, data, layout, config) { _$drawing_68.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_204.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_205.saveShowSpikeInitial(gd); // prepare the data and find the autorange @@ -57058,9 +57769,7 @@ _$plot_api_193.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_162.syncOrAsync([ - _$subroutines_196.layoutStyles - ], gd); + return _$plots_237.previousPromises(gd); } // draw anything that can affect margins. @@ -57068,10 +57777,10 @@ _$plot_api_193.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_244.getComponentMethod('legend', 'draw')(gd); - _$registry_244.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_244.getComponentMethod('sliders', 'draw')(gd); - _$registry_244.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_245.getComponentMethod('legend', 'draw')(gd); + _$registry_245.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_245.getComponentMethod('sliders', 'draw')(gd); + _$registry_245.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; @@ -57090,9 +57799,9 @@ _$plot_api_193.plot = function(gd, data, layout, config) { function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_162.syncOrAsync([ + return _$lib_163.syncOrAsync([ marginPushers, - _$subroutines_196.layoutStyles + _$subroutines_197.layoutStyles ], gd); } @@ -57113,7 +57822,7 @@ _$plot_api_193.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_162.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_163.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -57127,113 +57836,31 @@ _$plot_api_193.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_244.getComponentMethod('errorbars', 'calc')(gd); + _$registry_245.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_162.syncOrAsync([ - _$registry_244.getComponentMethod('shapes', 'calcAutorange'), - _$registry_244.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_163.syncOrAsync([ + _$registry_245.getComponentMethod('shapes', 'calcAutorange'), + _$registry_245.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_244.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_245.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_204.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_193(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_197.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_204.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_205.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_204.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_244.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_237.style(gd); - - // show annotations and shapes - _$registry_244.getComponentMethod('shapes', 'draw')(gd); - _$registry_244.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_237.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_237.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_244.getComponentMethod('shapes', 'draw')(gd); - _$registry_244.getComponentMethod('images', 'draw')(gd); - _$registry_244.getComponentMethod('annotations', 'draw')(gd); - _$registry_244.getComponentMethod('legend', 'draw')(gd); - _$registry_244.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_244.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_244.getComponentMethod('sliders', 'draw')(gd); - _$registry_244.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_205.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ @@ -57244,19 +57871,20 @@ _$plot_api_193.plot = function(gd, data, layout, config) { marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_196.layoutStyles); + seq.push(_$subroutines_197.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_213, + _$subroutines_197.drawData, + _$subroutines_197.finalDraw, + initInteractions, + _$plots_237.addLinks, _$plots_237.rehover, _$plots_237.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_162.syncOrAsync(seq, gd); + var plotDone = _$lib_163.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -57265,15 +57893,15 @@ _$plot_api_193.plot = function(gd, data, layout, config) { }); }; -_$plot_api_193.setPlotConfig = function setPlotConfig(obj) { - return _$lib_162.extendFlat(_$plot_config_194, obj); +_$plot_api_194.setPlotConfig = function setPlotConfig(obj) { + return _$lib_163.extendFlat(_$plot_config_195, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_162.error(e); + _$lib_163.error(e); } } @@ -57283,7 +57911,7 @@ function opaqueSetBackground(gd, bgColor) { } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_162.extendDeep({}, _$plot_config_194); + if(!gd._context) gd._context = _$lib_163.extendDeep({}, _$plot_config_195); var context = gd._context; var i, keys, key; @@ -57399,7 +58027,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_183.convertToTspans, gd); + this.call(_$svg_text_utils_184.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -57408,7 +58036,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_162._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_163._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -57427,7 +58055,7 @@ function plotPolar(gd, data, layout) { } var setContenteditable = function() { - this.call(_$svg_text_utils_183.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_184.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -57449,18 +58077,18 @@ function plotPolar(gd, data, layout) { } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_193.redraw = function(gd) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.redraw = function(gd) { + gd = _$lib_163.getGraphDiv(gd); - if(!_$lib_162.isPlotDiv(gd)) { + if(!_$lib_163.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_190.cleanData(gd.data, gd.data); - _$helpers_190.cleanLayout(gd.layout); + _$helpers_191.cleanData(gd.data, gd.data); + _$helpers_191.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_193.plot(gd).then(function() { + return _$plot_api_194.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -57474,14 +58102,14 @@ _$plot_api_193.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_193.newPlot = function(gd, data, layout, config) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.newPlot = function(gd, data, layout, config) { + gd = _$lib_163.getGraphDiv(gd); // remove gl contexts - _$plots_237.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_237.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); _$plots_237.purge(gd); - return _$plot_api_193.plot(gd, data, layout, config); + return _$plot_api_194.plot(gd, data, layout, config); }; /** @@ -57634,12 +58262,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_162.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_163.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_162.isPlainObject(update)) { + if(!_$lib_163.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -57682,7 +58310,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_162.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_163.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -57702,7 +58330,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_162.nestedProperty(trace, key); + prop = _$lib_163.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -57711,10 +58339,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_162.isArrayOrTypedArray(insert)) { + if(!_$lib_163.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_162.isArrayOrTypedArray(target)) { + if(!_$lib_163.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -57809,13 +58437,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_193.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_163.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_162.isTypedArray(target)) { + if(_$lib_163.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -57860,20 +58488,20 @@ _$plot_api_193.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_193.redraw(gd); + var promise = _$plot_api_194.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_176.add(gd, _$plot_api_193.prependTraces, undoArgs, extendTraces, arguments); + _$queue_177.add(gd, _$plot_api_194.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_193.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_163.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_162.isTypedArray(target)) { + if(_$lib_163.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -57917,9 +58545,9 @@ _$plot_api_193.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_193.redraw(gd); + var promise = _$plot_api_194.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_176.add(gd, _$plot_api_193.extendTraces, undoArgs, prependTraces, arguments); + _$queue_177.add(gd, _$plot_api_194.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -57933,11 +58561,11 @@ _$plot_api_193.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_193.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_163.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_193.deleteTraces, + undoFunc = _$plot_api_194.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -57954,10 +58582,10 @@ _$plot_api_193.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_162.extendFlat({}, trace); + return _$lib_163.extendFlat({}, trace); }); - _$helpers_190.cleanData(traces, gd.data); + _$helpers_191.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -57972,8 +58600,8 @@ _$plot_api_193.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_193.redraw(gd); - _$queue_176.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_194.redraw(gd); + _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -57996,10 +58624,10 @@ _$plot_api_193.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_176.startSequence(gd); - _$queue_176.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_193.moveTraces(gd, currentIndices, newIndices); - _$queue_176.stopSequence(gd); + _$queue_177.startSequence(gd); + _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_194.moveTraces(gd, currentIndices, newIndices); + _$queue_177.stopSequence(gd); return promise; }; @@ -58010,11 +58638,11 @@ _$plot_api_193.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_193.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_163.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_193.addTraces, + undoFunc = _$plot_api_194.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -58033,14 +58661,14 @@ _$plot_api_193.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_162.sorterDes); + indices.sort(_$lib_163.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_193.redraw(gd); - _$queue_176.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_194.redraw(gd); + _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -58076,8 +58704,8 @@ _$plot_api_193.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_193.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_163.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -58137,8 +58765,8 @@ _$plot_api_193.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_193.redraw(gd); - _$queue_176.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_194.redraw(gd); + _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -58173,55 +58801,55 @@ _$plot_api_193.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_193.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_162.getGraphDiv(gd); - _$helpers_190.clearPromiseQueue(gd); +_$plot_api_194.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_163.getGraphDiv(gd); + _$helpers_191.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_162.isPlainObject(astr)) { + else if(_$lib_163.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_162.extendFlat({}, astr); + aobj = _$lib_163.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_162.warn('Restyle fail.', astr, val, _traces); + _$lib_163.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_190.coerceTraceIndices(gd, _traces); + var traces = _$helpers_191.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_190.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_191.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_193.plot); + seq.push(_$plot_api_194.plot); } else { seq.push(_$plots_237.previousPromises); _$plots_237.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_196.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_196.doColorBars); + if(flags.style) seq.push(_$subroutines_197.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_197.doColorBars); } seq.push(_$plots_237.rehover); - _$queue_176.add(gd, + _$queue_177.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_162.syncOrAsync(seq, gd); + var plotDone = _$lib_163.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -58244,7 +58872,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_189.traceFlags(); + var flags = _$edit_types_190.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -58257,7 +58885,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_204.id2name(axid); + var axName = _$axes_205.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -58276,13 +58904,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_190.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_191.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_162.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_163.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_162.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_163.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -58299,7 +58927,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_190.hasParent(aobj, ai)) { + if(_$helpers_191.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -58314,7 +58942,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_162.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_163.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -58330,17 +58958,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_162.nestedProperty(cont, ai); + param = _$lib_163.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_195.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_196.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_162.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_163.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -58380,19 +59008,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_162.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_162.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_162.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_163.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_163.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_163.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_162.nestedProperty(cont, 'marker.color') - .set(_$lib_162.nestedProperty(cont, 'marker.colors').get()); + _$lib_163.nestedProperty(cont, 'marker.color') + .set(_$lib_163.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_244.traceIs(cont, 'cartesian')) { - _$lib_162.nestedProperty(cont, 'marker.colors') - .set(_$lib_162.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_245.traceIs(cont, 'cartesian')) { + _$lib_163.nestedProperty(cont, 'marker.colors') + .set(_$lib_163.nestedProperty(cont, 'marker.color').get()); } } @@ -58421,23 +59049,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_190.swapXYData(cont); + _$helpers_191.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(_$plots_237.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_190.manageArrayContainers(param, newVal, undoit); + _$helpers_191.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_162.isArrayOrTypedArray(newVal) || _$lib_162.isArrayOrTypedArray(oldVal)) + _$lib_163.isArrayOrTypedArray(newVal) || _$lib_163.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_189.update(flags, valObject); + else _$edit_types_190.update(flags, valObject); } else { /* @@ -58456,12 +59084,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_204.swap(gd, traces); + _$axes_205.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_162.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_163.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -58476,7 +59104,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_244.traceIs(trace, 'cartesian')) { + if(_$registry_245.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -58493,7 +59121,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_204.list(gd); + var axList = _$axes_205.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -58514,7 +59142,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_162.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_163.extendDeepNoArrays([], [redoit, traces]) }; } @@ -58538,9 +59166,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_193.relayout = function relayout(gd, astr, val) { - gd = _$lib_162.getGraphDiv(gd); - _$helpers_190.clearPromiseQueue(gd); +_$plot_api_194.relayout = function relayout(gd, astr, val) { + gd = _$lib_163.getGraphDiv(gd); + _$helpers_191.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -58549,21 +59177,21 @@ _$plot_api_193.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_162.isPlainObject(astr)) { - aobj = _$lib_162.extendFlat({}, astr); + } else if(_$lib_163.isPlainObject(astr)) { + aobj = _$lib_163.extendFlat({}, astr); } else { - _$lib_162.warn('Relayout fail.', astr, val); + _$lib_163.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_190.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_191.clearAxisAutomargins(gd); // fill in redraw sequence @@ -58573,26 +59201,50 @@ _$plot_api_193.relayout = function relayout(gd, astr, val) { var seq = [_$plots_237.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_196.layoutReplot); + seq.push(_$subroutines_197.layoutReplot); } else if(Object.keys(aobj).length) { _$plots_237.supplyDefaults(gd); - if(flags.legend) seq.push(_$subroutines_196.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_196.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_196.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_196.doModeBar); - if(flags.camera) seq.push(_$subroutines_196.doCamera); + if(flags.legend) seq.push(_$subroutines_197.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_197.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_197.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_197.doTicksRelayout, + _$subroutines_197.drawData, + _$subroutines_197.finalDraw + ); + } + + if(flags.ticks) seq.push(_$subroutines_197.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_197.doModeBar); + if(flags.camera) seq.push(_$subroutines_197.doCamera); } seq.push(_$plots_237.rehover); - _$queue_176.add(gd, + _$queue_177.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_162.syncOrAsync(seq, gd); + var plotDone = _$lib_163.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -58605,7 +59257,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_204.list(gd), + axes = _$axes_205.list(gd), arrayEdits = {}, arrayStr, i, @@ -58628,7 +59280,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_189.layoutFlags(); + var flags = _$edit_types_190.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -58647,9 +59299,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_190.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_191.hasParent(aobj, attr)) return; - var p = _$lib_162.nestedProperty(layout, attr); + var p = _$lib_163.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -58663,18 +59315,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_204.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_205.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_190.hasParent(aobj, ai)) { + if(_$helpers_191.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_162.nestedProperty(layout, ai); + var p = _$lib_163.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -58686,8 +59338,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_162.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_162.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_163.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_163.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -58698,11 +59350,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_195.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_196.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_162.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_163.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -58716,12 +59368,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_162.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_162.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_162.nestedProperty(fullLayout, ptrunk).get(); + _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_163.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -58729,7 +59381,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_162.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -58789,8 +59441,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_244.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_244.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_245.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_245.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -58798,18 +59450,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_162.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_209.AX_NAME_PATTERN)) { - var fullProp = _$lib_162.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_163.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_244.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_244.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_245.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_245.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -58818,12 +59470,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_192.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_193.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_162.nestedProperty(layout, arrayStr); + var componentArray = _$lib_163.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -58833,28 +59485,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_189.update(flags, updateValObject); + else _$edit_types_190.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_192.isAddVal(vi)) { + if(_$manage_arrays_193.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_192.isRemoveVal(vi)) { + else if(_$manage_arrays_193.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_162.warn('unrecognized full object value', aobj); + else _$lib_163.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_189.update(flags, updateValObject); - + else { + _$edit_types_190.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -58883,7 +59536,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_189.update(flags, valObject); + else if(valObject) _$edit_types_190.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -58892,8 +59545,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_192.applyContainerArrayChanges(gd, - _$lib_162.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_193.applyContainerArrayChanges(gd, + _$lib_163.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -58911,7 +59564,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_204.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_205.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -58935,7 +59588,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_162.extendDeep({}, redoit) + eventData: _$lib_163.extendDeep({}, redoit) }; } @@ -58957,9 +59610,9 @@ function updateAutosize(gd) { // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_162.isPlainObject(obj)) return false; + if(!_$lib_163.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_204.getFromId(gd, axRef); + ax = _$axes_205.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -58969,7 +59622,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_204.getFromId(gd, axLetter); + ax = _$axes_205.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -58989,32 +59642,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_193.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_162.getGraphDiv(gd); - _$helpers_190.clearPromiseQueue(gd); +_$plot_api_194.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_163.getGraphDiv(gd); + _$helpers_191.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_162.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_162.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_163.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_163.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_190.coerceTraceIndices(gd, _traces); + var traces = _$helpers_191.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_162.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_163.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_162.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_163.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_190.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_190.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_191.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_191.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -59028,35 +59681,43 @@ _$plot_api_193.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_193.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_194.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_193.plot); + seq.push(_$plot_api_194.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_196.layoutReplot); + seq.push(_$subroutines_197.layoutReplot); } else { seq.push(_$plots_237.previousPromises); _$plots_237.supplyDefaults(gd); - if(restyleFlags.style) seq.push(_$subroutines_196.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_196.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_196.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_196.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_196.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_196.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_196.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_197.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_197.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_197.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_197.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_197.doAutoRangeAndConstraints, + _$subroutines_197.doTicksRelayout, + _$subroutines_197.drawData, + _$subroutines_197.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_197.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_197.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_197.doCamera); } seq.push(_$plots_237.rehover); - _$queue_176.add(gd, + _$queue_177.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_162.syncOrAsync(seq, gd); + var plotDone = _$lib_163.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -59092,23 +59753,23 @@ _$plot_api_193.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_193.react = function(gd, data, layout, config) { +_$plot_api_194.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_193.addFrames(gd, frames); } + function addFrames() { return _$plot_api_194.addFrames(gd, frames); } - gd = _$lib_162.getGraphDiv(gd); + gd = _$lib_163.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_162.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_193.newPlot(gd, data, layout, config); + if(!_$lib_163.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_194.newPlot(gd, data, layout, config); } else { - if(_$lib_162.isPlainObject(data)) { + if(_$lib_163.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -59120,16 +59781,16 @@ _$plot_api_193.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_162.extendDeep({}, gd._context); + var oldConfig = _$lib_163.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_190.cleanData(gd.data, []); + _$helpers_191.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_190.cleanLayout(gd.layout); + _$helpers_191.cleanLayout(gd.layout); _$plots_237.supplyDefaults(gd); @@ -59153,7 +59814,7 @@ _$plot_api_193.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_190.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_191.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -59169,21 +59830,21 @@ _$plot_api_193.react = function(gd, data, layout, config) { if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_193.plot); + seq.push(_$plot_api_194.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_244.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_162.noop) { + var drawOne = _$registry_245.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_163.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_244.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_162.noop) { + var draw = _$registry_245.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_163.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -59192,18 +59853,26 @@ _$plot_api_193.react = function(gd, data, layout, config) { } seq.push(_$plots_237.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_196.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_196.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_196.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_196.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_196.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_196.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_196.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_197.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_197.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_197.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_197.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_197.doAutoRangeAndConstraints, + _$subroutines_197.doTicksRelayout, + _$subroutines_197.drawData, + _$subroutines_197.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_197.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_197.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_197.doCamera); } seq.push(_$plots_237.rehover); - plotDone = _$lib_162.syncOrAsync(seq, gd); + plotDone = _$lib_163.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -59226,12 +59895,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_189.traceFlags(); + var flags = _$edit_types_190.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_195.getTraceValObject(trace, parts); + return _$plot_schema_196.getTraceValObject(trace, parts); } var diffOpts = { @@ -59241,11 +59910,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_204.getFromId(gd, trace.xaxis).autorange || - _$axes_204.getFromId(gd, trace.yaxis).autorange + _$axes_205.getFromId(gd, trace.xaxis).autorange || + _$axes_205.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -59258,11 +59933,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_189.layoutFlags(); + var flags = _$edit_types_190.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_195.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_196.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -59301,10 +59976,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_162.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_163.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_189.update(flags, valObject); + _$edit_types_190.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -59384,7 +60059,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_162.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_163.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -59396,7 +60071,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_162.isPlainObject(oldVal)) { + else if(!valType && _$lib_163.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -59450,7 +60125,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_162.isPlainObject(oldVal) && _$lib_162.isPlainObject(newVal)) { + if(_$lib_163.isPlainObject(oldVal) && _$lib_163.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -59461,7 +60136,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_162.isPlainObject(oldVal[i]) && _$lib_162.isPlainObject(newVal[i])) { + if(_$lib_163.isPlainObject(oldVal[i]) && _$lib_163.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -59506,10 +60181,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_193.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_163.getGraphDiv(gd); - if(!_$lib_162.isPlotDiv(gd)) { + if(!_$lib_163.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -59683,7 +60358,7 @@ _$plot_api_193.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts _$plots_237.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_190.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_191.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -59753,13 +60428,13 @@ _$plot_api_193.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_162.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_163.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_162.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_163.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -59788,10 +60463,10 @@ _$plot_api_193.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_162.isPlainObject(frameOrName)) { + } else if(_$lib_163.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_162.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_163.extendFlat({}, frameOrName)) }); } } @@ -59801,7 +60476,7 @@ _$plot_api_193.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_162.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_163.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -59870,14 +60545,14 @@ _$plot_api_193.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_193.addFrames = function(gd, frameList, indices) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.addFrames = function(gd, frameList, indices) { + gd = _$lib_163.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_162.isPlotDiv(gd)) { + if(!_$lib_163.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -59904,7 +60579,7 @@ _$plot_api_193.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_162.isPlainObject(frameList[i])) continue; + if(!_$lib_163.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -59916,14 +60591,14 @@ _$plot_api_193.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_162.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_163.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_162.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_163.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -59952,7 +60627,7 @@ _$plot_api_193.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_162.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_163.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -59985,7 +60660,7 @@ _$plot_api_193.addFrames = function(gd, frameList, indices) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_176) _$queue_176.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_177) _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_237.modifyFrames(gd, ops); }; @@ -59999,10 +60674,10 @@ _$plot_api_193.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_193.deleteFrames = function(gd, frameList) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.deleteFrames = function(gd, frameList) { + gd = _$lib_163.getGraphDiv(gd); - if(!_$lib_162.isPlotDiv(gd)) { + if(!_$lib_163.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -60032,7 +60707,7 @@ _$plot_api_193.deleteFrames = function(gd, frameList) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_176) _$queue_176.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_177) _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_237.modifyFrames(gd, ops); }; @@ -60043,20 +60718,21 @@ _$plot_api_193.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_193.purge = function purge(gd) { - gd = _$lib_162.getGraphDiv(gd); +_$plot_api_194.purge = function purge(gd) { + gd = _$lib_163.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_237.cleanPlot([], {}, fullData, fullLayout); + _$plots_237.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties _$plots_237.purge(gd); // purge event emitter methods - _$Events_155.purge(gd); + _$Events_156.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -60114,7 +60790,7 @@ function makePlotFramework(gd) { _$d3_7.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_162.randstr(otherUids); + fullLayout._uid = _$lib_163.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') @@ -60190,7 +60866,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_248 = {}; +var _$helpers_249 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -60202,7 +60878,7 @@ var _$helpers_248 = {}; 'use strict'; -_$helpers_248.getDelay = function(fullLayout) { +_$helpers_249.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -60212,7 +60888,7 @@ _$helpers_248.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_248.getRedrawFunc = function(gd) { +_$helpers_249.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -60237,11 +60913,11 @@ _$helpers_248.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_162 = require('../lib'); */; -var __EventEmitter_250 = _$EventEmitter_9.EventEmitter; +/* removed: var _$lib_163 = require('../lib'); */; +var __EventEmitter_251 = _$EventEmitter_9.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_250(); + var ev = opts.emitter || new __EventEmitter_251(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -60249,7 +60925,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_162.isIE() && format !== 'svg') { + if(_$lib_163.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -60340,7 +61016,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_250 = svgToImg; +var _$svgToImg_251 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -60355,7 +61031,7 @@ var _$svgToImg_250 = svgToImg; /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$lib_163 = require('../lib'); */; /* removed: var _$drawing_68 = require('../components/drawing'); */; /* removed: var _$color_43 = require('../components/color'); */; @@ -60380,7 +61056,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_252 = function toSVG(gd, format, scale) { +var _$toSVG_253 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -60503,7 +61179,7 @@ var _$toSVG_252 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_162.isIE()) { + if(_$lib_163.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -60528,14 +61204,14 @@ var _$toSVG_252 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_193 = require('./plot_api'); */; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$plot_api_194 = require('./plot_api'); */; +/* removed: var _$lib_163 = require('../lib'); */; -/* removed: var _$helpers_248 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_252 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_250 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_249 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_253 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_251 = require('../snapshot/svgtoimg'); */; -var __attrs_197 = { +var __attrs_198 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -60588,19 +61264,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_162.isPlainObject(gd)) { + if(_$lib_163.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_162.getGraphDiv(gd); - data = _$lib_162.extendDeep([], gd.data); - layout = _$lib_162.extendDeep({}, gd.layout); + gd = _$lib_163.getGraphDiv(gd); + data = _$lib_163.extendDeep([], gd.data); + layout = _$lib_163.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_162.validate(opts[attr], __attrs_197[attr]); + return !(attr in opts) || _$lib_163.validate(opts[attr], __attrs_198[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -60614,7 +61290,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_162.coerce(opts, fullOpts, __attrs_197, attr, dflt); + return _$lib_163.coerce(opts, fullOpts, __attrs_198, attr, dflt); } var format = coerce('format'); @@ -60631,31 +61307,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_162.extendFlat({}, layout); + var layoutImage = _$lib_163.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_162.extendFlat({}, config, { + var configImage = _$lib_163.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_248.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_249.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_248.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_249.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_252(clonedGd, format, scale); + var svg = _$toSVG_253(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_193.purge(clonedGd); + _$plot_api_194.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -60667,9 +61343,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_162.randstr(); + canvas.id = _$lib_163.randstr(); - _$svgToImg_250({ + _$svgToImg_251({ format: format, width: width, height: height, @@ -60696,7 +61372,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_193.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_194.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -60705,7 +61381,7 @@ function toImage(gd, opts) { }); } -var _$toImage_197 = toImage; +var _$toImage_198 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -60717,14 +61393,14 @@ var _$toImage_197 = toImage; 'use strict'; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$lib_163 = require('../lib'); */; /* removed: var _$plots_237 = require('../plots/plots'); */; -/* removed: var _$plot_schema_195 = require('./plot_schema'); */; -/* removed: var _$plot_config_194 = require('./plot_config'); */; +/* removed: var _$plot_schema_196 = require('./plot_schema'); */; +/* removed: var _$plot_config_195 = require('./plot_config'); */; -var __isPlainObject_198 = _$lib_162.isPlainObject; -var __isArray_198 = Array.isArray; -var __isArrayOrTypedArray_198 = _$lib_162.isArrayOrTypedArray; +var __isPlainObject_199 = _$lib_163.isPlainObject; +var __isArray_199 = Array.isArray; +var __isArrayOrTypedArray_199 = _$lib_163.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -60747,15 +61423,15 @@ var __isArrayOrTypedArray_198 = _$lib_162.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_198 = function valiate(data, layout) { - var schema = _$plot_schema_195.get(); +var _$valiate_199 = function valiate(data, layout) { + var schema = _$plot_schema_196.get(); var errorList = []; - var gd = {_context: _$lib_162.extendFlat({}, _$plot_config_194)}; + var gd = {_context: _$lib_163.extendFlat({}, _$plot_config_195)}; var dataIn, layoutIn; - if(__isArray_198(data)) { - gd.data = _$lib_162.extendDeep([], data); + if(__isArray_199(data)) { + gd.data = _$lib_163.extendDeep([], data); dataIn = data; } else { @@ -60764,8 +61440,8 @@ var _$valiate_198 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_198(layout)) { - gd.layout = _$lib_162.extendDeep({}, layout); + if(__isPlainObject_199(layout)) { + gd.layout = _$lib_163.extendDeep({}, layout); layoutIn = layout; } else { @@ -60789,7 +61465,7 @@ var _$valiate_198 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_198(traceIn)) { + if(!__isPlainObject_199(traceIn)) { errorList.push(format('object', base)); continue; } @@ -60809,13 +61485,13 @@ var _$valiate_198 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_198(traceIn, traceOut, traceSchema, errorList, base); + __crawl_199(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_198(transformsIn)) { + if(!__isArray_199(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -60825,7 +61501,7 @@ var _$valiate_198 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_198(transformsIn[j])) { + if(!__isPlainObject_199(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -60840,7 +61516,7 @@ var _$valiate_198 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_198(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_199(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -60848,13 +61524,13 @@ var _$valiate_198 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_198(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_199(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_198(objIn, objOut, schema, list, base, path) { +function __crawl_199(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -60879,10 +61555,10 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_198(valIn) && __isPlainObject_198(valOut)) { - __crawl_198(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_199(valIn) && __isPlainObject_199(valOut)) { + __crawl_199(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_198(valIn)) { + else if(isInfoArray && __isArray_199(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -60892,7 +61568,7 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_198(valIn[n])) { + if(__isArray_199(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -60901,7 +61577,7 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_162.validate(valInPart, item)) { + if(!_$lib_163.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -60919,7 +61595,7 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_162.validate(valInPart, item)) { + if(!_$lib_163.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -60928,7 +61604,7 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_198(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_199(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -60942,9 +61618,9 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_198(valIn[_index]) && __isPlainObject_198(valOut[j])) { + if(__isPlainObject_199(valIn[_index]) && __isPlainObject_199(valOut[j])) { indexList.push(_index); - __crawl_198(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_199(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -60953,7 +61629,7 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_198(valIn[j])) { + if(!__isPlainObject_199(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -60961,16 +61637,16 @@ function __crawl_198(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_198(valIn) && __isPlainObject_198(valOut)) { + else if(!__isPlainObject_199(valIn) && __isPlainObject_199(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_198(valIn) && __isArrayOrTypedArray_198(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_199(valIn) && __isArrayOrTypedArray_199(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_162.validate(valIn, nestedSchema)) { + else if(!_$lib_163.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -60990,7 +61666,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_162.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_163.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -61022,7 +61698,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_198(valIn) ? 'container' : 'key'; + var target = __isPlainObject_199(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -61048,7 +61724,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_198(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_199(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -61061,7 +61737,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_198(base)) { + if(__isArray_199(base)) { container = base[0]; trace = base[1]; } @@ -61074,7 +61750,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_162.log(msg); + _$lib_163.log(msg); return { code: code, @@ -61104,7 +61780,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_162.counterRegex('([a-z]+)'); +var idRegex = _$lib_163.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -61116,7 +61792,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_198(path)) return String(path); + if(!__isArray_199(path)) return String(path); var astr = ''; @@ -61205,7 +61881,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_247 = fileSaver; +var _$fileSaver_248 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -61218,9 +61894,9 @@ var _$fileSaver_247 = fileSaver; 'use strict'; -/* removed: var _$toImage_197 = require('../plot_api/to_image'); */; -/* removed: var _$lib_162 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_247 = require('./filesaver'); */; +/* removed: var _$toImage_198 = require('../plot_api/to_image'); */; +/* removed: var _$lib_163 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_248 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -61248,19 +61924,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_162.isIE() && opts.format !== 'svg') { + if(_$lib_163.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_197(gd, opts); + var promise = _$toImage_198(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_247(result, filename); + return _$fileSaver_248(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -61270,9 +61946,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_246 = downloadImage; +var _$downloadImage_247 = downloadImage; -var _$plot_api_191 = {}; +var _$plot_api_192 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -61283,29 +61959,29 @@ var _$plot_api_191 = {}; 'use strict'; -/* removed: var _$plot_api_193 = require('./plot_api'); */; - -_$plot_api_191.plot = _$plot_api_193.plot; -_$plot_api_191.newPlot = _$plot_api_193.newPlot; -_$plot_api_191.restyle = _$plot_api_193.restyle; -_$plot_api_191.relayout = _$plot_api_193.relayout; -_$plot_api_191.redraw = _$plot_api_193.redraw; -_$plot_api_191.update = _$plot_api_193.update; -_$plot_api_191.react = _$plot_api_193.react; -_$plot_api_191.extendTraces = _$plot_api_193.extendTraces; -_$plot_api_191.prependTraces = _$plot_api_193.prependTraces; -_$plot_api_191.addTraces = _$plot_api_193.addTraces; -_$plot_api_191.deleteTraces = _$plot_api_193.deleteTraces; -_$plot_api_191.moveTraces = _$plot_api_193.moveTraces; -_$plot_api_191.purge = _$plot_api_193.purge; -_$plot_api_191.addFrames = _$plot_api_193.addFrames; -_$plot_api_191.deleteFrames = _$plot_api_193.deleteFrames; -_$plot_api_191.animate = _$plot_api_193.animate; -_$plot_api_191.setPlotConfig = _$plot_api_193.setPlotConfig; - -_$plot_api_191.toImage = _$toImage_197; -_$plot_api_191.validate = _$valiate_198; -_$plot_api_191.downloadImage = _$downloadImage_246; +/* removed: var _$plot_api_194 = require('./plot_api'); */; + +_$plot_api_192.plot = _$plot_api_194.plot; +_$plot_api_192.newPlot = _$plot_api_194.newPlot; +_$plot_api_192.restyle = _$plot_api_194.restyle; +_$plot_api_192.relayout = _$plot_api_194.relayout; +_$plot_api_192.redraw = _$plot_api_194.redraw; +_$plot_api_192.update = _$plot_api_194.update; +_$plot_api_192.react = _$plot_api_194.react; +_$plot_api_192.extendTraces = _$plot_api_194.extendTraces; +_$plot_api_192.prependTraces = _$plot_api_194.prependTraces; +_$plot_api_192.addTraces = _$plot_api_194.addTraces; +_$plot_api_192.deleteTraces = _$plot_api_194.deleteTraces; +_$plot_api_192.moveTraces = _$plot_api_194.moveTraces; +_$plot_api_192.purge = _$plot_api_194.purge; +_$plot_api_192.addFrames = _$plot_api_194.addFrames; +_$plot_api_192.deleteFrames = _$plot_api_194.deleteFrames; +_$plot_api_192.animate = _$plot_api_194.animate; +_$plot_api_192.setPlotConfig = _$plot_api_194.setPlotConfig; + +_$plot_api_192.toImage = _$toImage_198; +_$plot_api_192.validate = _$valiate_199; +_$plot_api_192.downloadImage = _$downloadImage_247; /** * Copyright 2012-2018, Plotly, Inc. @@ -61318,10 +61994,10 @@ _$plot_api_191.downloadImage = _$downloadImage_246; 'use strict'; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$lib_163 = require('../lib'); */; -var __extendFlat_245 = _$lib_162.extendFlat; -var extendDeep = _$lib_162.extendDeep; +var __extendFlat_246 = _$lib_163.extendFlat; +var extendDeep = _$lib_163.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -61366,7 +62042,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_245 = function clonePlot(graphObj, options) { +var _$clonePlot_246 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -61439,9 +62115,9 @@ var _$clonePlot_245 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_245(scene.xaxis, axesImageOverride); - __extendFlat_245(scene.yaxis, axesImageOverride); - __extendFlat_245(scene.zaxis, axesImageOverride); + __extendFlat_246(scene.xaxis, axesImageOverride); + __extendFlat_246(scene.yaxis, axesImageOverride); + __extendFlat_246(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -61490,27 +62166,27 @@ var _$clonePlot_245 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_251 = _$EventEmitter_9.EventEmitter; +var __EventEmitter_252 = _$EventEmitter_9.EventEmitter; -/* removed: var _$registry_244 = require('../registry'); */; -/* removed: var _$lib_162 = require('../lib'); */; +/* removed: var _$registry_245 = require('../registry'); */; +/* removed: var _$lib_163 = require('../lib'); */; -/* removed: var _$helpers_248 = require('./helpers'); */; -/* removed: var _$clonePlot_245 = require('./cloneplot'); */; -/* removed: var _$toSVG_252 = require('./tosvg'); */; -/* removed: var _$svgToImg_250 = require('./svgtoimg'); */; +/* removed: var _$helpers_249 = require('./helpers'); */; +/* removed: var _$clonePlot_246 = require('./cloneplot'); */; +/* removed: var _$toSVG_253 = require('./tosvg'); */; +/* removed: var _$svgToImg_251 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_251(gd, opts) { +function __toImage_252(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_251(); + var ev = new __EventEmitter_252(); - var clone = _$clonePlot_245(gd, {format: 'png'}); + var clone = _$clonePlot_246(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -61519,15 +62195,15 @@ function __toImage_251(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_248.getDelay(clonedGd._fullLayout); + var delay = _$helpers_249.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_252(clonedGd); + var svg = _$toSVG_253(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_162.randstr(); + canvas.id = _$lib_163.randstr(); - ev = _$svgToImg_250({ + ev = _$svgToImg_251({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -61543,9 +62219,9 @@ function __toImage_251(gd, opts) { }, delay); } - var redrawFunc = _$helpers_248.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_249.getRedrawFunc(clonedGd); - _$registry_244.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_245.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -61556,7 +62232,7 @@ function __toImage_251(gd, opts) { return ev; } -var _$toImage_251 = __toImage_251; +var _$toImage_252 = __toImage_252; /** * Copyright 2012-2018, Plotly, Inc. @@ -61569,19 +62245,19 @@ var _$toImage_251 = __toImage_251; 'use strict'; -/* removed: var _$helpers_248 = require('./helpers'); */; +/* removed: var _$helpers_249 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_248.getDelay, - getRedrawFunc: _$helpers_248.getRedrawFunc, - clone: _$clonePlot_245, - toSVG: _$toSVG_252, - svgToImg: _$svgToImg_250, - toImage: _$toImage_251, - downloadImage: _$downloadImage_246 + getDelay: _$helpers_249.getDelay, + getRedrawFunc: _$helpers_249.getRedrawFunc, + clone: _$clonePlot_246, + toSVG: _$toSVG_253, + svgToImg: _$svgToImg_251, + toImage: _$toImage_252, + downloadImage: _$downloadImage_247 }; -var _$Snapshot_249 = Snapshot; +var _$Snapshot_250 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -61594,42 +62270,42 @@ var _$Snapshot_249 = Snapshot; 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_279 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_280 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_162.mergeArray(trace.text, cd, 'tx'); - _$lib_162.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_162.mergeArray(trace.customdata, cd, 'data'); - _$lib_162.mergeArray(trace.textposition, cd, 'tp'); + _$lib_163.mergeArray(trace.text, cd, 'tx'); + _$lib_163.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_163.mergeArray(trace.customdata, cd, 'data'); + _$lib_163.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_162.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_162.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_162.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_163.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_163.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_163.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_162.mergeArray(marker.size, cd, 'ms'); - _$lib_162.mergeArray(marker.opacity, cd, 'mo'); - _$lib_162.mergeArray(marker.symbol, cd, 'mx'); - _$lib_162.mergeArray(marker.color, cd, 'mc'); + _$lib_163.mergeArray(marker.size, cd, 'ms'); + _$lib_163.mergeArray(marker.opacity, cd, 'mo'); + _$lib_163.mergeArray(marker.symbol, cd, 'mx'); + _$lib_163.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_162.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_162.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_163.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_163.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_162.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_162.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_163.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_163.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -61648,15 +62324,15 @@ var _$arraysToCalcdata_279 = function arraysToCalcdata(cd, trace) { /* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$calc_50 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; -var _$calcMarkerColorscale_285 = function calcMarkerColorscale(trace) { - if(_$subtypes_302.hasLines(trace) && _$hasColorscale_57(trace, 'line')) { +var _$calcMarkerColorscale_286 = function calcMarkerColorscale(trace) { + if(_$subtypes_303.hasLines(trace) && _$hasColorscale_57(trace, 'line')) { _$calc_50(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_302.hasMarkers(trace)) { + if(_$subtypes_303.hasMarkers(trace)) { if(_$hasColorscale_57(trace, 'marker')) { _$calc_50(trace, trace.marker.color, 'marker', 'c'); } @@ -61677,19 +62353,19 @@ var _$calcMarkerColorscale_285 = function calcMarkerColorscale(trace) { 'use strict'; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_281 = _$lib_162.isArrayOrTypedArray; +var __isArrayOrTypedArray_282 = _$lib_163.isArrayOrTypedArray; -/* removed: var _$axes_204 = require('../../plots/cartesian/axes'); */; -var __BADNUM_281 = _$numerical_145.BADNUM; +/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +var __BADNUM_282 = _$numerical_145.BADNUM; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_285 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_279 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_282 = require('./calc_selection'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_286 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_280 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_283 = require('./calc_selection'); */; -function __calc_281(gd, trace) { - var xa = _$axes_204.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_204.getFromId(gd, trace.yaxis || 'y'); +function __calc_282(gd, trace) { + var xa = _$axes_205.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_205.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -61701,16 +62377,16 @@ function __calc_281(gd, trace) { for(var i = 0; i < serieslen; i++) { cd[i] = (_$fastIsnumeric_10(x[i]) && _$fastIsnumeric_10(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_281, y: __BADNUM_281}; + {x: __BADNUM_282, y: __BADNUM_282}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_279(cd, trace); - _$calcMarkerColorscale_285(trace); - _$calcSelection_282(cd, trace); + _$arraysToCalcdata_280(cd, trace); + _$calcMarkerColorscale_286(trace); + _$calcSelection_283(cd, trace); gd.firstscatter = false; return cd; @@ -61743,9 +62419,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_302.hasMarkers(trace) && !_$subtypes_302.hasText(trace)) + (!_$subtypes_303.hasMarkers(trace) && !_$subtypes_303.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -61764,12 +62440,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_204.expand(xa, x, xOptions); - _$axes_204.expand(ya, y, yOptions); + _$axes_205.expand(xa, x, xOptions); + _$axes_205.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_302.hasMarkers(trace)) return; + if(!_$subtypes_303.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -61787,10 +62463,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_281(marker.size)) { + if(__isArrayOrTypedArray_282(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_204.setConvert(ax); + _$axes_205.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -61805,8 +62481,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_281 = { - calc: __calc_281, +var _$calc_282 = { + calc: __calc_282, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -61824,7 +62500,7 @@ var _$calc_281 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_283 = function cleanData(fullData) { +var _$cleanData_284 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -61861,9 +62537,9 @@ var _$cleanData_283 = function cleanData(fullData) { 'use strict'; /* removed: var _$color_43 = require('../../components/color'); */; -var __isArrayOrTypedArray_289 = _$lib_162.isArrayOrTypedArray; +var __isArrayOrTypedArray_290 = _$lib_163.isArrayOrTypedArray; -var _$fillColorDefaults_289 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_290 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -61871,10 +62547,10 @@ var _$fillColorDefaults_289 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_289(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_290(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_289(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_290(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } @@ -61896,11 +62572,11 @@ var _$fillColorDefaults_289 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_293 = _$lib_162.isArrayOrTypedArray; +var __isArrayOrTypedArray_294 = _$lib_163.isArrayOrTypedArray; /* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_53 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_293 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_294 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); @@ -61909,7 +62585,7 @@ var _$lineDefaults_293 = function lineDefaults(traceIn, traceOut, defaultColor, _$colorScaleDefaults_53(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_293(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_294(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -61930,7 +62606,7 @@ var _$lineDefaults_293 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_295 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_296 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -61950,7 +62626,7 @@ var _$handleLineShapeDefaults_295 = function handleLineShapeDefaults(traceIn, tr /* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_53 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -61958,8 +62634,8 @@ var _$handleLineShapeDefaults_295 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_298 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_302.isBubble(traceIn), +var _$markerDefaults_299 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_303.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -62028,17 +62704,17 @@ var _$markerDefaults_298 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_303 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_304 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_162.coerceFont(coerce, 'textfont', layout.font); + _$lib_163.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -62056,27 +62732,27 @@ var _$text_defaults_303 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$registry_244 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_245 = require('../../registry'); */; -/* removed: var _$attributes_280 = require('./attributes'); */; -/* removed: var _$constants_286 = require('./constants'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_304 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_298 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_293 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_295 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_303 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_289 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_281 = require('./attributes'); */; +/* removed: var _$constants_287 = require('./constants'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_305 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_299 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_294 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_296 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_304 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_290 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_288 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_162.coerce(traceIn, traceOut, _$attributes_280, attr, dflt); + return _$lib_163.coerce(traceIn, traceOut, _$attributes_281, attr, dflt); } - var len = _$handleXYDefaults_304(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_305(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_286.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_287.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -62086,24 +62762,24 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_302.hasLines(traceOut)) { - _$lineDefaults_293(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_295(traceIn, traceOut, coerce); + if(_$subtypes_303.hasLines(traceOut)) { + _$lineDefaults_294(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_296(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_302.hasMarkers(traceOut)) { - _$markerDefaults_298(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_303.hasMarkers(traceOut)) { + _$markerDefaults_299(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_302.hasText(traceOut)) { - _$text_defaults_303(traceIn, traceOut, layout, coerce); + if(_$subtypes_303.hasText(traceOut)) { + _$text_defaults_304(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_302.hasMarkers(traceOut) || _$subtypes_302.hasText(traceOut)) { + if(_$subtypes_303.hasMarkers(traceOut) || _$subtypes_303.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -62111,8 +62787,8 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_289(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_302.hasLines(traceOut)) _$handleLineShapeDefaults_295(traceIn, traceOut, coerce); + _$fillColorDefaults_290(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_303.hasLines(traceOut)) _$handleLineShapeDefaults_296(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -62120,11 +62796,11 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_244.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_245.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_162.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_163.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -62139,10 +62815,10 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; /* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; -var _$getTraceColor_290 = function getTraceColor(trace, di) { +var _$getTraceColor_291 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes @@ -62173,7 +62849,7 @@ var _$getTraceColor_290 = function getTraceColor(trace, di) { else { lc = (trace.line || {}).color; return (lc && _$color_43.opacity(lc) && - _$subtypes_302.hasLines(trace) && trace.line.width) ? + _$subtypes_303.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -62189,14 +62865,14 @@ var _$getTraceColor_290 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; /* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$getTraceColor_290 = require('./get_trace_color'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$getTraceColor_291 = require('./get_trace_color'); */; /* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$fillHoverText_288 = require('./fill_hover_text'); */; +/* removed: var _$fillHoverText_289 = require('./fill_hover_text'); */; -var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_292 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -62249,8 +62925,8 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_162.extendFlat(pointData, { - color: _$getTraceColor_290(trace, di), + _$lib_163.extendFlat(pointData, { + color: _$getTraceColor_291(trace, di), x0: xc - rad, x1: xc + rad, @@ -62263,8 +62939,8 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_288(di, trace, pointData); - _$registry_244.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_289(di, trace, pointData); + _$registry_245.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -62336,7 +63012,7 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { color = trace.line.color; } - _$lib_162.extendFlat(pointData, { + _$lib_163.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -62370,14 +63046,14 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_294 = _$numerical_145.BADNUM; -/* removed: var _$lib_162 = require('../../lib'); */; -var __segmentsIntersect_294 = _$lib_162.segmentsIntersect; -var constrain = _$lib_162.constrain; -/* removed: var _$constants_286 = require('./constants'); */; +var __BADNUM_295 = _$numerical_145.BADNUM; +/* removed: var _$lib_163 = require('../../lib'); */; +var __segmentsIntersect_295 = _$lib_163.segmentsIntersect; +var constrain = _$lib_163.constrain; +/* removed: var _$constants_287 = require('./constants'); */; -var _$linePoints_294 = function linePoints(d, opts) { +var _$linePoints_295 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -62386,7 +63062,7 @@ var _$linePoints_294 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_286.minTolerance; + var minTolerance = _$constants_287.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -62424,7 +63100,7 @@ var _$linePoints_294 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_294 || y === __BADNUM_294) return di.intoCenter || false; + if(x === __BADNUM_295 || y === __BADNUM_295) return di.intoCenter || false; return [x, y]; } @@ -62432,7 +63108,7 @@ var _$linePoints_294 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_286.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_287.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -62444,7 +63120,7 @@ var _$linePoints_294 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_286.maxScreensAway; + var maxScreensAway = _$constants_287.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -62473,7 +63149,7 @@ var _$linePoints_294 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_294(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_295(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -62527,7 +63203,7 @@ var _$linePoints_294 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_162.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_163.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -62780,7 +63456,7 @@ var _$linePoints_294 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_296 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_297 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -62822,17 +63498,17 @@ var _$linkTraces_296 = function linkTraces(gd, plotinfo, cdscatter) { /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$registry_244 = require('../../registry'); */; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$registry_245 = require('../../registry'); */; +/* removed: var _$lib_163 = require('../../lib'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -/* removed: var _$linePoints_294 = require('./line_points'); */; -/* removed: var _$linkTraces_296 = require('./link_traces'); */; -var __polygonTester_299 = _$polygon_174.tester; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +/* removed: var _$linePoints_295 = require('./line_points'); */; +/* removed: var _$linkTraces_297 = require('./link_traces'); */; +var __polygonTester_300 = _$polygon_175.tester; -var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_300 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -62841,9 +63517,8 @@ var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -62855,7 +63530,7 @@ var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_296(gd, plotinfo, cdscatter); + _$linkTraces_297(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -62894,12 +63569,12 @@ var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_299(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_300(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_299(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_300(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -62954,7 +63629,7 @@ function createFills(gd, scatterlayer, plotinfo) { }); } -function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_300(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -62976,7 +63651,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran tr = _$d3_7.select(element); // error bars are at the bottom - _$registry_244.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_245.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -62988,7 +63663,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -63014,11 +63689,11 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_162.noop; + makeUpdate = _$lib_163.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_302.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_303.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -63055,7 +63730,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_294(cdscatter, { + segments = _$linePoints_295(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -63070,7 +63745,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_299(segments[i]); + trace._polygons[i] = __polygonTester_300(segments[i]); } if(segments.length) { @@ -63096,7 +63771,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_302.hasLines(trace) && pts.length > 1) { + if(_$subtypes_303.hasLines(trace) && pts.length > 1) { var el = _$d3_7.select(this); // This makes the coloring work correctly: @@ -63223,19 +63898,19 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = d[0].trace, s = _$d3_7.select(this), - showMarkers = _$subtypes_302.hasMarkers(trace), - showText = _$subtypes_302.hasText(trace); + showMarkers = _$subtypes_303.hasMarkers(trace), + showText = _$subtypes_303.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_162.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_163.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_162.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_163.identity; } // marker points @@ -63356,11 +64031,11 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_7.extent(_$lib_162.simpleMap(xa.range, xa.r2c)), - yr = _$d3_7.extent(_$lib_162.simpleMap(ya.range, ya.r2c)); + xr = _$d3_7.extent(_$lib_163.simpleMap(xa.range, xa.r2c)), + yr = _$d3_7.extent(_$lib_163.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_302.hasMarkers(trace)) return; + if(!_$subtypes_303.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -63375,7 +64050,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_302.hasMarkers(tracei) && + if(_$subtypes_303.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -63406,9 +64081,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; -var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_301 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -63419,7 +64094,7 @@ var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_302.hasMarkers(trace) && !_$subtypes_302.hasText(trace)); + var hasOnlyLines = (!_$subtypes_303.hasMarkers(trace) && !_$subtypes_303.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -63462,9 +64137,9 @@ var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { /* removed: var _$d3_7 = require('d3'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$registry_244 = require('../../registry'); */; +/* removed: var _$registry_245 = require('../../registry'); */; -function __style_301(gd, cd) { +function __style_302(gd, cd) { var s = cd ? cd[0].node3 : _$d3_7.select(gd).selectAll('g.trace.scatter'); s.style('opacity', function(d) { @@ -63483,7 +64158,7 @@ function __style_301(gd, cd) { s.selectAll('g.trace path.js-fill') .call(_$drawing_68.fillGroupStyle); - _$registry_244.getComponentMethod('errorbars', 'style')(s); + _$registry_245.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { @@ -63496,8 +64171,8 @@ function stylePoints(sel, trace, gd) { _$drawing_68.selectedTextStyle(txs, trace); } -var _$style_301 = { - style: __style_301, +var _$style_302 = { + style: __style_302, stylePoints: stylePoints }; @@ -63514,35 +64189,35 @@ var _$style_301 = { var Scatter = {}; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_302.hasLines; -Scatter.hasMarkers = _$subtypes_302.hasMarkers; -Scatter.hasText = _$subtypes_302.hasText; -Scatter.isBubble = _$subtypes_302.isBubble; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_303.hasLines; +Scatter.hasMarkers = _$subtypes_303.hasMarkers; +Scatter.hasText = _$subtypes_303.hasText; +Scatter.isBubble = _$subtypes_303.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_280; -Scatter.supplyDefaults = _$supplyDefaults_287; -Scatter.cleanData = _$cleanData_283; -Scatter.calc = _$calc_281.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_279; -Scatter.plot = _$plot_299; -Scatter.colorbar = _$colorbar_284; -Scatter.style = _$style_301.style; -Scatter.hoverPoints = _$hoverPoints_291; -Scatter.selectPoints = _$selectPoints_300; +Scatter.attributes = _$attributes_281; +Scatter.supplyDefaults = _$supplyDefaults_288; +Scatter.cleanData = _$cleanData_284; +Scatter.calc = _$calc_282.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_280; +Scatter.plot = _$plot_300; +Scatter.colorbar = _$colorbar_285; +Scatter.style = _$style_302.style; +Scatter.hoverPoints = _$hoverPoints_292; +Scatter.selectPoints = _$selectPoints_301; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_215; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_216; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_292 = Scatter; +var _$Scatter_293 = Scatter; var _$core_148 = {}; /** @@ -63556,7 +64231,7 @@ var _$core_148 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_148.version = '1.35.2'; +_$core_148.version = '1.36.0'; // inject promise polyfill _$es6Promise_8.polyfill(); @@ -63568,24 +64243,24 @@ _$plotcss_1; _$mathjax_config_149; // include registry module and expose register method -/* removed: var _$registry_244 = require('./registry'); */; -var register = _$core_148.register = _$registry_244.register; +/* removed: var _$registry_245 = require('./registry'); */; +var register = _$core_148.register = _$registry_245.register; // expose plot api methods -/* removed: var _$plot_api_191 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_191); +/* removed: var _$plot_api_192 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_192); for(var i = 0; i < methodNames.length; i++) { var __name_148 = methodNames[i]; - _$core_148[__name_148] = _$plot_api_191[__name_148]; + _$core_148[__name_148] = _$plot_api_192[__name_148]; register({ moduleType: 'apiMethod', name: __name_148, - fn: _$plot_api_191[__name_148] + fn: _$plot_api_192[__name_148] }); } // scatter is the only trace included by default -register(_$Scatter_292); +register(_$Scatter_293); // register all registrable components modules register([ @@ -63605,8 +64280,8 @@ register([ // locales en and en-US are required for default behavior register([ - _$localeEn_187, - _$localeEnUs_186 + _$localeEn_188, + _$localeEnUs_187 ]); // plot icons @@ -63615,9 +64290,9 @@ _$core_148.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk _$core_148.Plots = _$plots_237; _$core_148.Fx = _$fx_85; -_$core_148.Snapshot = _$Snapshot_249; -_$core_148.PlotSchema = _$plot_schema_195; -_$core_148.Queue = _$queue_176; +_$core_148.Snapshot = _$Snapshot_250; +_$core_148.PlotSchema = _$plot_schema_196; +_$core_148.Queue = _$queue_177; // export d3 used in the bundle _$core_148.d3 = _$d3_7; @@ -63646,18 +64321,18 @@ var _$core_4 = _$core_148; /* removed: var _$attributes_42 = require('../../components/color/attributes'); */; /* removed: var _$font_attributes_231 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_201 = require('../../plots/attributes'); */; -var __domainAttrs_267 = _$domain_230.attributes; +/* removed: var _$attributes_202 = require('../../plots/attributes'); */; +var __domainAttrs_268 = _$domain_230.attributes; -var __extendFlat_267 = _$extend_156.extendFlat; +var __extendFlat_268 = _$extend_157.extendFlat; -var __textFontAttrs_267 = _$font_attributes_231({ +var __textFontAttrs_268 = _$font_attributes_231({ editType: 'calc', colorEditType: 'style', }); -var _$attributes_267 = { +var _$attributes_268 = { labels: { valType: 'data_array', editType: 'calc', @@ -63750,7 +64425,7 @@ var _$attributes_267 = { editType: 'calc', }, - hoverinfo: __extendFlat_267({}, _$attributes_201.hoverinfo, { + hoverinfo: __extendFlat_268({}, _$attributes_202.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'] }), textposition: { @@ -63763,18 +64438,18 @@ var _$attributes_267 = { }, // TODO make those arrayOk? - textfont: __extendFlat_267({}, __textFontAttrs_267, { + textfont: __extendFlat_268({}, __textFontAttrs_268, { }), - insidetextfont: __extendFlat_267({}, __textFontAttrs_267, { + insidetextfont: __extendFlat_268({}, __textFontAttrs_268, { }), - outsidetextfont: __extendFlat_267({}, __textFontAttrs_267, { + outsidetextfont: __extendFlat_268({}, __textFontAttrs_268, { }), // position and shape - domain: __domainAttrs_267({name: 'pie', trace: true, editType: 'calc'}), + domain: __domainAttrs_268({name: 'pie', trace: true, editType: 'calc'}), hole: { valType: 'number', @@ -63831,7 +64506,7 @@ var _$attributes_267 = { } }; -var _$base_plot_268 = {}; +var _$base_plot_269 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -63842,19 +64517,19 @@ var _$base_plot_268 = {}; 'use strict'; -/* removed: var _$registry_244 = require('../../registry'); */; - +/* removed: var _$registry_245 = require('../../registry'); */; +var __getModuleCalcData_269 = _$get_data_233.getModuleCalcData; -_$base_plot_268.name = 'pie'; +_$base_plot_269.name = 'pie'; -_$base_plot_268.plot = function(gd) { - var Pie = _$registry_244.getModule('pie'); - var cdPie = getCdModule(gd.calcdata, Pie); +_$base_plot_269.plot = function(gd) { + var Pie = _$registry_245.getModule('pie'); + var cdPie = __getModuleCalcData_269(gd.calcdata, Pie)[0]; if(cdPie.length) Pie.plot(gd, cdPie); }; -_$base_plot_268.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_269.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPie = (oldFullLayout._has && oldFullLayout._has('pie')); var hasPie = (newFullLayout._has && newFullLayout._has('pie')); @@ -63863,21 +64538,6 @@ _$base_plot_268.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -function getCdModule(calcdata, _module) { - var cdModule = []; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - - if((trace._module === _module) && (trace.visible === true)) { - cdModule.push(cd); - } - } - - return cdModule; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -63889,15 +64549,15 @@ function getCdModule(calcdata, _module) { 'use strict'; /* removed: var _$fastIsnumeric_10 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_269 = _$lib_162.isArrayOrTypedArray; +var __isArrayOrTypedArray_270 = _$lib_163.isArrayOrTypedArray; /* removed: var _$tinycolor_25 = require('tinycolor2'); */; /* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$helpers_272 = require('./helpers'); */; +/* removed: var _$helpers_273 = require('./helpers'); */; -var _$calc_269 = function calc(gd, trace) { +var _$calc_270 = function calc(gd, trace) { var vals = trace.values; - var hasVals = __isArrayOrTypedArray_269(vals) && vals.length; + var hasVals = __isArrayOrTypedArray_270(vals) && vals.length; var labels = trace.labels; var colors = trace.marker.colors || []; var cd = []; @@ -64019,11 +64679,11 @@ var _$calc_269 = function calc(gd, trace) { pt = cd[i]; thisText = hasLabel ? [pt.label] : []; if(hasText) { - var texti = _$helpers_272.getFirstFilled(trace.text, pt.pts); + var texti = _$helpers_273.getFirstFilled(trace.text, pt.pts); if(texti) thisText.push(texti); } - if(hasValue) thisText.push(_$helpers_272.formatPieValue(pt.v, separators)); - if(hasPercent) thisText.push(_$helpers_272.formatPiePercent(pt.v / vTotal, separators)); + if(hasValue) thisText.push(_$helpers_273.formatPieValue(pt.v, separators)); + if(hasPercent) thisText.push(_$helpers_273.formatPiePercent(pt.v / vTotal, separators)); pt.text = thisText.join('
'); } } @@ -64074,21 +64734,21 @@ function generateDefaultColors(colorList) { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; -/* removed: var _$attributes_267 = require('./attributes'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$attributes_268 = require('./attributes'); */; var handleDomainDefaults = _$domain_230.defaults; -var _$supplyDefaults_270 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_271 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_162.coerce(traceIn, traceOut, _$attributes_267, attr, dflt); + return _$lib_163.coerce(traceIn, traceOut, _$attributes_268, attr, dflt); } - var coerceFont = _$lib_162.coerceFont; + var coerceFont = _$lib_163.coerceFont; var vals = coerce('values'); var labels = coerce('labels'); if(!Array.isArray(labels)) { - if(!_$lib_162.isArrayOrTypedArray(vals) || !vals.length) { + if(!_$lib_163.isArrayOrTypedArray(vals) || !vals.length) { // must have at least one of vals or labels traceOut.visible = false; return; @@ -64144,7 +64804,7 @@ var _$supplyDefaults_270 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$layout_attributes_274 = { +var _$layout_attributes_275 = { /** * hiddenlabels is the pie chart analog of visible:'legendonly' * but it can contain many labels, and can hide slices @@ -64166,13 +64826,13 @@ var _$layout_attributes_274 = { 'use strict'; -/* removed: var _$lib_162 = require('../../lib'); */; +/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$layout_attributes_274 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_275 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_275 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_276 = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_162.coerce(layoutIn, layoutOut, _$layout_attributes_274, attr, dflt); + return _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_275, attr, dflt); } coerce('hiddenlabels'); }; @@ -64194,7 +64854,7 @@ var appendArrayMultiPointValues = _$helpers_82.appendArrayMultiPointValues; // Note: like other eventData routines, this creates the data for hover/unhover/click events // but it has a different API and goes through a totally different pathway. // So to ensure it doesn't get misused, it's not attached to the Pie module. -var _$eventData_271 = function eventData(pt, trace) { +var _$eventData_272 = function eventData(pt, trace) { var out = { curveNumber: trace.index, pointNumbers: pt.pts, @@ -64234,12 +64894,13 @@ var _$eventData_271 = function eventData(pt, trace) { /* removed: var _$fx_85 = require('../../components/fx'); */; /* removed: var _$color_43 = require('../../components/color'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_183 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$helpers_272 = require('./helpers'); */; -/* removed: var _$eventData_271 = require('./event_data'); */; +/* removed: var _$helpers_273 = require('./helpers'); */; +/* removed: var _$eventData_272 = require('./event_data'); */; -var _$plot_276 = function plot(gd, cdpie) { +var _$plot_277 = function plot(gd, cdpie) { var fullLayout = gd._fullLayout; scalePies(cdpie, fullLayout._size); @@ -64316,7 +64977,7 @@ var _$plot_276 = function plot(gd, cdpie) { // TODO: do we want to have Fx.castHoverinfo somehow handle this? // it already takes an array for index, for 2D, so this seems tricky. hoverinfo = _$fx_85.castHoverinfo({ - hoverinfo: [_$helpers_272.castOption(hoverinfo, pt.pts)], + hoverinfo: [_$helpers_273.castOption(hoverinfo, pt.pts)], _module: trace._module }, fullLayout2, 0); } @@ -64334,11 +64995,11 @@ var _$plot_276 = function plot(gd, cdpie) { if(hoverinfo.indexOf('label') !== -1) thisText.push(pt.label); if(hoverinfo.indexOf('text') !== -1) { - var texti = _$helpers_272.castOption(trace2.hovertext || trace2.text, pt.pts); + var texti = _$helpers_273.castOption(trace2.hovertext || trace2.text, pt.pts); if(texti) thisText.push(texti); } - if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_272.formatPieValue(pt.v, separators)); - if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_272.formatPiePercent(pt.v / cd0.vTotal, separators)); + if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_273.formatPieValue(pt.v, separators)); + if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_273.formatPiePercent(pt.v / cd0.vTotal, separators)); var hoverLabel = trace.hoverlabel; var hoverFont = hoverLabel.font; @@ -64350,11 +65011,11 @@ var _$plot_276 = function plot(gd, cdpie) { text: thisText.join('
'), name: hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined, idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right', - color: _$helpers_272.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, - borderColor: _$helpers_272.castOption(hoverLabel.bordercolor, pt.pts), - fontFamily: _$helpers_272.castOption(hoverFont.family, pt.pts), - fontSize: _$helpers_272.castOption(hoverFont.size, pt.pts), - fontColor: _$helpers_272.castOption(hoverFont.color, pt.pts) + color: _$helpers_273.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, + borderColor: _$helpers_273.castOption(hoverLabel.bordercolor, pt.pts), + fontFamily: _$helpers_273.castOption(hoverFont.family, pt.pts), + fontSize: _$helpers_273.castOption(hoverFont.size, pt.pts), + fontColor: _$helpers_273.castOption(hoverFont.color, pt.pts) }, { container: fullLayout2._hoverlayer.node(), outerContainer: fullLayout2._paper.node(), @@ -64365,7 +65026,7 @@ var _$plot_276 = function plot(gd, cdpie) { } gd.emit('plotly_hover', { - points: [_$eventData_271(pt, trace2)], + points: [_$eventData_272(pt, trace2)], event: _$d3_7.event }); hasHoverEvent = true; @@ -64378,7 +65039,7 @@ var _$plot_276 = function plot(gd, cdpie) { if(hasHoverEvent) { evt.originalEvent = _$d3_7.event; gd.emit('plotly_unhover', { - points: [_$eventData_271(pt, trace2)], + points: [_$eventData_272(pt, trace2)], event: _$d3_7.event }); hasHoverEvent = false; @@ -64401,7 +65062,7 @@ var _$plot_276 = function plot(gd, cdpie) { if(gd._dragging || fullLayout2.hovermode === false) return; - gd._hoverdata = [_$eventData_271(pt, trace2)]; + gd._hoverdata = [_$eventData_272(pt, trace2)]; _$fx_85.click(gd, _$d3_7.event); } @@ -64417,7 +65078,7 @@ var _$plot_276 = function plot(gd, cdpie) { .on('click', handleClick); if(trace.pull) { - var pull = +_$helpers_272.castOption(trace.pull, pt.pts) || 0; + var pull = +_$helpers_273.castOption(trace.pull, pt.pts) || 0; if(pull > 0) { cx += pull * pt.pxmid[0]; cy += pull * pt.pxmid[1]; @@ -64468,7 +65129,7 @@ var _$plot_276 = function plot(gd, cdpie) { } // add text - var textPosition = _$helpers_272.castOption(trace.textposition, pt.pts); + var textPosition = _$helpers_273.castOption(trace.textposition, pt.pts); var sliceTextGroup = sliceTop.selectAll('g.slicetext') .data(pt.text && (textPosition !== 'none') ? [0] : []); @@ -64477,13 +65138,11 @@ var _$plot_276 = function plot(gd, cdpie) { sliceTextGroup.exit().remove(); sliceTextGroup.each(function() { - var sliceText = _$d3_7.select(this).selectAll('text').data([0]); - - sliceText.enter().append('text') + var sliceText = _$lib_163.ensureSingle(_$d3_7.select(this), 'text', '', function(s) { // prohibit tex interpretation until we can handle // tex and regular text together - .attr('data-notex', 1); - sliceText.exit().remove(); + s.attr('data-notex', 1); + }); sliceText.text(pt.text) .attr({ @@ -64493,7 +65152,7 @@ var _$plot_276 = function plot(gd, cdpie) { }) .call(_$drawing_68.font, textPosition === 'outside' ? trace.outsidetextfont : trace.insidetextfont) - .call(_$svg_text_utils_183.convertToTspans, gd); + .call(_$svg_text_utils_184.convertToTspans, gd); // position the text relative to the slice var textBB = _$drawing_68.bBox(sliceText.node()); @@ -64714,8 +65373,8 @@ function scootLabels(quadrants, trace) { // overlap can only happen if the other point is pulled more than this one if(otherPt === thisPt || ( - (_$helpers_272.castOption(trace.pull, thisPt.pts) || 0) >= - (_$helpers_272.castOption(trace.pull, otherPt.pts) || 0)) + (_$helpers_273.castOption(trace.pull, thisPt.pts) || 0) >= + (_$helpers_273.castOption(trace.pull, otherPt.pts) || 0)) ) { continue; } @@ -64902,9 +65561,9 @@ function setCoords(cd) { /* removed: var _$d3_7 = require('d3'); */; -/* removed: var _$styleOne_278 = require('./style_one'); */; +/* removed: var _$styleOne_279 = require('./style_one'); */; -var _$style_277 = function style(gd) { +var _$style_278 = function style(gd) { gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) { var cd0 = cd[0]; var trace = cd0.trace; @@ -64913,7 +65572,7 @@ var _$style_277 = function style(gd) { traceSelection.style({opacity: trace.opacity}); traceSelection.selectAll('path.surface').each(function(pt) { - _$d3_7.select(this).call(_$styleOne_278, pt, trace); + _$d3_7.select(this).call(_$styleOne_279, pt, trace); }); }); }; @@ -64930,24 +65589,24 @@ var _$style_277 = function style(gd) { var Pie = {}; -Pie.attributes = _$attributes_267; -Pie.supplyDefaults = _$supplyDefaults_270; -Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_275; -Pie.layoutAttributes = _$layout_attributes_274; -Pie.calc = _$calc_269; -Pie.plot = _$plot_276; -Pie.style = _$style_277; -Pie.styleOne = _$styleOne_278; +Pie.attributes = _$attributes_268; +Pie.supplyDefaults = _$supplyDefaults_271; +Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_276; +Pie.layoutAttributes = _$layout_attributes_275; +Pie.calc = _$calc_270; +Pie.plot = _$plot_277; +Pie.style = _$style_278; +Pie.styleOne = _$styleOne_279; Pie.moduleType = 'trace'; Pie.name = 'pie'; -Pie.basePlotModule = _$base_plot_268; +Pie.basePlotModule = _$base_plot_269; Pie.categories = ['pie', 'showLegend']; Pie.meta = { }; -var _$Pie_273 = Pie; +var _$Pie_274 = Pie; /** * Copyright 2012-2018, Plotly, Inc. @@ -64959,7 +65618,7 @@ var _$Pie_273 = Pie; 'use strict'; -var _$pie_6 = _$Pie_273; +var _$pie_6 = _$Pie_274; /** * Copyright 2012-2018, Plotly, Inc. diff --git a/dist/plotly-basic.min.js b/dist/plotly-basic.min.js index 852135d8333..0e660ede1db 100644 --- a/dist/plotly-basic.min.js +++ b/dist/plotly-basic.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (basic - minified) v1.35.2 +* plotly.js (basic - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},r=[].slice,n=function(e){return r.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{n(a.documentElement.childNodes)[0].nodeType}catch(e){n=function(e){for(var t=e.length,r=new Array(t);t--;)r[t]=e[t];return r}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,r){c.call(this,e,t,r+"")},u.setProperty=function(e,t,r){f.call(this,e,t+"",r)}}function d(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=t.length);n>>1;e(t[i],r)<0?n=i+1:a=i}return n},right:function(t,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=t.length);n>>1;e(t[i],r)>0?a=i:n=i+1}return n}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var r,n,a=-1,i=e.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++an&&(r=n)}else{for(;++a=n){r=n;break}for(;++an&&(r=n)}return r},t.max=function(e,t){var r,n,a=-1,i=e.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++ar&&(r=n)}else{for(;++a=n){r=n;break}for(;++ar&&(r=n)}return r},t.extent=function(e,t){var r,n,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=n){r=a=n;break}for(;++in&&(r=n),a=n){r=a=n;break}for(;++in&&(r=n),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,r){return d(e(t),r)}:e)},t.shuffle=function(e,t,r){(i=arguments.length)<3&&(r=e.length,i<2&&(t=0));for(var n,a,i=r-t;i;)a=Math.random()*i--|0,n=e[i+t],e[i+t]=e[a+t],e[a+t]=n;return e},t.permute=function(e,t){for(var r=t.length,n=new Array(r);r--;)n[r]=e[t[r]];return n},t.pairs=function(e){for(var t=0,r=e.length-1,n=e[0],a=new Array(r<0?0:r);t=0;)for(t=(n=e[a]).length;--t>=0;)r[--o]=n[t];return r};var m=Math.abs;function x(e,t){for(var r in t)Object.defineProperty(e.prototype,r,{value:t[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,r){if(arguments.length<3&&(r=1,arguments.length<2&&(t=e,e=0)),(t-e)/r==1/0)throw new Error("infinite range");var n,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(r)),o=-1;if(e*=i,t*=i,(r*=i)<0)for(;(n=e+r*++o)>t;)a.push(n/i);else for(;(n=e+r*++o)=a.length)return r?r.call(n,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var n=[],o=i[r++];return t.forEach(function(t,a){n.push({key:t,values:e(a,r)})}),o?n.sort(function(e,t){return o(e.key,t.key)}):n}(o(t.map,e,0),0)},n.key=function(e){return a.push(e),n},n.sortKeys=function(e){return i[a.length-1]=e,n},n.sortValues=function(t){return e=t,n},n.rollup=function(e){return r=e,n},n},t.set=function(e){var t=new O;if(e)for(var r=0,n=e.length;r=0&&(n=e.slice(r+1),e=e.slice(0,r)),e)return arguments.length<2?this[e].on(n):this[e].on(n,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(n,null);return this}},t.event=null,t.requote=function(e){return e.replace(H,"\\$&")};var H=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var r in t)e[r]=t[r]};function V(e){return q(e,X),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var r=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return r.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}X.select=function(e){var t,r,n,a,i=[];e=Z(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(r=e.slice(0,t))&&(e=e.slice(t+1)),J.hasOwnProperty(r)?{space:J[r],local:e}:e}},X.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each($(r,e[r]));return this}return this.each($(e,r))},X.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var r=this.node(),n=(e=te(e)).length,a=-1;if(t=r.classList){for(;++a=0;)(r=n[a])&&(i&&i!==r.nextSibling&&i.parentNode.insertBefore(r,i),i=r);return this},X.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,r){return t&&r?e(t.__data__,r.__data__):!t-!r}}.apply(this,arguments);for(var t=-1,r=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?r?function(){var t=l(r,n(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=r}:c:r?N:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(r=a.match(n)){var i=this[a];this.removeEventListener(r[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=X.append,de.empty=X.empty,de.node=X.node,de.call=X.call,de.size=X.size,de.select=function(e){for(var t,r,n,a,i,o=[],l=-1,s=this.length;++l=n&&(n=t+1);!(o=l[n])&&++n0?1:e<0?-1:0}function ze(e,t,r){return(t[0]-e[0])*(r[1]-e[1])-(t[1]-e[1])*(r[0]-e[0])}function De(e){return e>1?0:e<-1?Ae:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Ne(e){return((e=Math.exp(e))+1/e)/2}function Ie(e){return(e=Math.sin(e/2))*e}var Re=Math.SQRT2;t.interpolateZoom=function(e,t){var r,n,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function O(e){--v||(e({type:"zoomend"}),r=null)}function P(){var e=this,r=_.of(e,arguments),n=0,a=t.select(o(e)).on(m,function(){n=1,A(t.mouse(e),i),S(r)}).on(x,function(){a.on(m,null).on(x,null),l(n),O(r)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(r)}function z(){var e,r=this,n=_.of(r,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(r),h=xe(r);function p(){var n=t.touches(r);return e=d.k,n.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),n}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var n=t.event.changedTouches,o=0,f=n.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(r);ll.call(r);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?n+(a-n)*e/60:e<180?a:e<240?n+(a-n)*(240-e)/60:n}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,n=2*(r=r<0?0:r>1?1:r)-(a=r<=.5?r*(1+t):r+t-r*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,r,n){return this instanceof Ge?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Ze?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,r,n)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new He;function Xe(e,t,r){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Ze(r,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Ze(e,t,r){return this instanceof Ze?(this.l=+e,this.a=+t,void(this.b=+r)):arguments.length<2?e instanceof Ze?new Ze(e.l,e.a,e.b):e instanceof Ge?Xe(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Ze(e,t,r)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Xe(this.h,this.c,this.l).rgb()},t.lab=Ze;var We=18,Qe=.95047,Je=1,$e=1.08883,Ke=Ze.prototype=new He;function et(e,t,r){var n=(e+16)/116,a=n+t/500,i=n-r/200;return new it(at(3.2404542*(a=rt(a)*Qe)-1.5371385*(n=rt(n)*Je)-.4985314*(i=rt(i)*$e)),at(-.969266*a+1.8760108*n+.041556*i),at(.0556434*a-.2040259*n+1.0572252*i))}function tt(e,t,r){return e>0?new Ge(Math.atan2(r,t)*Oe,Math.sqrt(t*t+r*r),e):new Ge(NaN,NaN,e)}function rt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function nt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,r){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~r)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,r)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Ze(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Ze(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new He;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,r){var n,a,i,o=0,l=0,s=0;if(n=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=n[2].split(","),n[1]){case"hsl":return r(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,r){var n,a,i=Math.min(e/=255,t/=255,r/=255),o=Math.max(e,t,r),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),n=e==o?(t-r)/l+(t0&&s<1?0:n),new qe(n,a,s)}function dt(e,t,r){var n=nt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(r=ht(r)))/Qe),a=nt((.2126729*e+.7151522*t+.072175*r)/Je);return Ze(116*a-16,500*(n-a),200*(a-nt((.0193339*e+.119192*t+.9503041*r)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,r=this.g,n=this.b,a=30;return t||r||n?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var r=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=r}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(r=null==e?null:e+"",o):r},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(n(arguments)))}}),o.send=function(t,n,a){if(2===arguments.length&&"function"==typeof n&&(a=n,n=null),c.open(t,e,!0),null==r||"accept"in s||(s.accept=r+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=r&&c.overrideMimeType&&c.overrideMimeType(r),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==n?null:n),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,r){e(null==t?r:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(P),t.dsv=function(e,t){var r=new RegExp('["'+e+"\n]"),n=e.charCodeAt(0);function a(e,r,n){arguments.length<3&&(n=r,r=null);var a=mt(e,t,null==r?i:o(r),n);return a.row=function(e){return arguments.length?a.response(null==(r=e)?i:o(e)):r},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return r.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var r;return a.parseRows(e,function(e,n){if(r)return r(e,n-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");r=t?function(e,r){return t(a(e),r)}:a})},a.parseRows=function(e,t){var r,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var r=t;r++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(At,t)),_t=0):(_t=1,kt(At))}function Tt(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,r=1/0;t;)t.c?(t.t8?function(e){return e/r}:function(e){return e*r},symbol:e}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ct(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),St[8+n/3]};var Ot=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pt=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,r){return(e=t.round(e,Ct(e,r))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),r))))}});function zt(e){return e+""}var Dt=t.time={},Et=Date;function Nt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Nt.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(){It.setUTCDate.apply(this._,arguments)},setDay:function(){It.setUTCDay.apply(this._,arguments)},setFullYear:function(){It.setUTCFullYear.apply(this._,arguments)},setHours:function(){It.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){It.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){It.setUTCMinutes.apply(this._,arguments)},setMonth:function(){It.setUTCMonth.apply(this._,arguments)},setSeconds:function(){It.setUTCSeconds.apply(this._,arguments)},setTime:function(){It.setTime.apply(this._,arguments)}};var It=Date.prototype;function Rt(e,t,r){function n(t){var r=e(t),n=i(r,1);return t-r1)for(;o68?1900:2e3),r+a[0].length):-1}function Qt(e,t,r){return/^[+-]\d{4}$/.test(t=t.slice(r,r+5))?(e.Z=-t,r+5):-1}function Jt(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function $t(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function Kt(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+3));return n?(e.j=+n[0],r+n[0].length):-1}function er(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function tr(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function rr(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function nr(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function ar(e){var t=e.getTimezoneOffset(),r=t>0?"-":"+",n=m(t)/60|0,a=m(t)%60;return r+qt(n,"0",2)+qt(a,"0",2)}function ir(e,t,r){Ht.lastIndex=0;var n=Ht.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function or(e){for(var t=e.length,r=-1;++r0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(r-=l,r+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(n)}:P;return function(e){var n=Ot.exec(e),a=n[1]||" ",l=n[2]||">",s=n[3]||"-",c=n[4]||"",u=n[5],f=+n[6],d=n[7],h=n[8],p=n[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=Pt.get(p)||zt;var b=u&&d;return function(e){var n=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),n=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=r+e.substring(k+1);!u&&d&&(_=o(_,1/0));var A=v.length+_.length+w.length+(b?0:i.length),T=A"===l?T+i+e:"^"===l?T.substring(0,A>>=1)+i+e+T.substring(A):i+(b?e:T+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function r(r){for(var n,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in jt?t.charAt(l++):o])||(n=i(e,r,n))<0)return-1}else if(a!=r.charCodeAt(n++))return-1}return n}u.utc=function(e){var t=u(e);function r(e){try{var r=new(Et=Nt);return r._=e,t(r)}finally{Et=Date}}return r.parse=function(e){try{Et=Nt;var r=t.parse(e);return r&&r._}finally{Et=Date}},r.toString=t.toString,r},u.multi=u.utc.multi=or;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(r),d:function(e,t){return qt(e.getDate(),t,2)},e:function(e,t){return qt(e.getDate(),t,2)},H:function(e,t){return qt(e.getHours(),t,2)},I:function(e,t){return qt(e.getHours()%12||12,t,2)},j:function(e,t){return qt(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return qt(e.getMilliseconds(),t,3)},m:function(e,t){return qt(e.getMonth()+1,t,2)},M:function(e,t){return qt(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return qt(e.getSeconds(),t,2)},U:function(e,t){return qt(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return qt(Dt.mondayOfYear(e),t,2)},x:u(n),X:u(a),y:function(e,t){return qt(e.getFullYear()%100,t,2)},Y:function(e,t){return qt(e.getFullYear()%1e4,t,4)},Z:ar,"%":function(){return"%"}},w={a:function(e,t,r){g.lastIndex=0;var n=g.exec(t.slice(r));return n?(e.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(e,t,r){h.lastIndex=0;var n=h.exec(t.slice(r));return n?(e.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(e,t,r){x.lastIndex=0;var n=x.exec(t.slice(r));return n?(e.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(e,t,r){y.lastIndex=0;var n=y.exec(t.slice(r));return n?(e.m=m.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(e,t,r){return f(e,_.c.toString(),t,r)},d:$t,e:$t,H:er,I:er,j:Kt,L:nr,m:Jt,M:tr,p:function(e,t,r){var n=d.get(t.slice(r,r+=2).toLowerCase());return null==n?-1:(e.p=n,r)},S:rr,U:Yt,w:Gt,W:Xt,x:function(e,t,r){return f(e,_.x.toString(),t,r)},X:function(e,t,r){return f(e,_.X.toString(),t,r)},y:Wt,Y:Zt,Z:Qt,"%":ir};return u}(e)}};var lr=t.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"]});function sr(){}t.format=lr.numberFormat,t.geo={},sr.prototype={s:0,t:0,add:function(e){ur(e,this.t,cr),ur(cr.s,this.s,this),this.s?this.t+=cr.t:this.s=cr.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cr=new sr;function ur(e,t,r){var n=r.s=e+t,a=n-e,i=n-a;r.t=e-i+(t-a)}function fr(e,t){e&&hr.hasOwnProperty(e.type)&&hr[e.type](e,t)}t.geo.stream=function(e,t){e&&dr.hasOwnProperty(e.type)?dr[e.type](e,t):fr(e,t)};var dr={Feature:function(e,t){fr(e.geometry,t)},FeatureCollection:function(e,t){for(var r=e.features,n=-1,a=r.length;++n=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=n*s+u*Math.cos(l),d=u*o*Math.sin(l);Cr.add(Math.atan2(d,f)),r=e,n=s,a=c}Sr.point=function(o,l){Sr.point=i,r=(e=o)*Se,n=Math.cos(l=(t=l)*Se/2+Ae/4),a=Math.sin(l)},Sr.lineEnd=function(){i(e,t)}}function Pr(e){var t=e[0],r=e[1],n=Math.cos(r);return[n*Math.cos(t),n*Math.sin(t),Math.sin(r)]}function zr(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Dr(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Er(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Nr(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Ir(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Rr(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function Fr(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(r=-90),f[0]=e,f[1]=n}};function h(t,i){u.push(f=[e=t,n=t]),ia&&(a=i)}function p(t,o){var l=Pr([t*Se,o*Se]);if(s){var c=Dr(s,l),u=Dr([c[1],-c[0],0],c);Ir(u),u=Rr(u);var f=t-i,d=f>0?1:-1,p=u[0]*Oe*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(tn&&(n=t)):t>i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=n,d.point=h,s=null}function y(e,t){if(s){var r=e-i;c+=m(r)>180?r+(r>0?360:-360):r}else o=e,l=t;Sr.point(e,t),p(e,t)}function x(){Sr.lineStart()}function b(){y(o,l),Sr.lineEnd(),m(c)>ke&&(e=-(n=180)),f[0]=e,f[1]=n,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],n=g[1])}return u=f=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,a]]}}(),t.geo.centroid=function(e){yr=mr=xr=br=_r=wr=kr=Mr=Ar=Tr=Lr=0,t.geo.stream(e,jr);var r=Ar,n=Tr,a=Lr,i=r*r+n*n+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else n(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Zr(e){if(t=e.length){for(var t,r,n=0,a=e[0];++n=0?1:-1,k=w*_,M=k>Ae,A=p*x;if(Cr.add(Math.atan2(A*w*Math.sin(k),g*b+A*Math.cos(k))),i+=M?_+w*Te:_,M^d>=r^y>=r){var T=Dr(Pr(f),Pr(e));Ir(T);var L=Dr(a,T);Ir(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(n>C||n===C&&(T[0]||T[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&r.push(r.pop().concat(r.shift())),l.push(r.filter(Jr))}return u}}function Jr(e){return e.length>1}function $r(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,r){e.push([t,r])},lineEnd:N,buffer:function(){var r=t;return t=[],e=null,r},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Kr(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var en=Qr(Yr,function(e){var t,r=NaN,n=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Ae:-Ae,s=m(i-r);m(s-Ae)0?Ce:-Ce),e.point(a,n),e.lineEnd(),e.lineStart(),e.point(l,n),e.point(i,n),t=0):a!==l&&s>=Ae&&(m(r-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(n))*Math.sin(r)-Math.sin(n)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+n)/2}(r,n,i,o),e.point(a,n),e.lineEnd(),e.lineStart(),e.point(l,n),t=0),e.point(r=i,n=o),a=l},lineEnd:function(){e.lineEnd(),r=n=NaN},clean:function(){return 2-t}}},function(e,t,r,n){var a;if(null==e)a=r*Ce,n.point(-Ae,a),n.point(0,a),n.point(Ae,a),n.point(Ae,0),n.point(Ae,-a),n.point(0,-a),n.point(-Ae,-a),n.point(-Ae,0),n.point(-Ae,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rn=1e9;function nn(e,r,n,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=$r(),w=tn(e,r,n,a),k={point:T,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=T,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var r=function(e){for(var t=0,r=u.length,n=e[1],a=0;an&&ze(c,i,e)>0&&++t:i[1]<=n&&ze(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),n=x&&r,i=c.length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Xr(c,o,r,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:n,u>1?a:r)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function A(t,i){return e<=t&&t<=n&&r<=i&&i<=a}function T(e,t){A(e,t)&&s.point(e,t)}function L(e,t){var r=A(e=Math.max(-rn,Math.min(rn,e)),t=Math.max(-rn,Math.min(rn,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=r,m=!1,r&&(s.lineStart(),s.point(e,t));else if(r&&y)s.point(e,t);else{var n={a:{x:g,y:v},b:{x:e,y:t}};w(n)?(y||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),x=!1):r&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=r}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-n)0?2:1:m(t[1]-r)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var r=i(e,1),n=i(t,1);return r!==n?r-n:0===r?t[1]-e[1]:1===r?e[0]-t[0]:2===r?e[1]-t[1]:t[0]-e[0]}}function an(e){var t=0,r=Ae/3,n=Ln(e),a=n(t,r);return a.parallels=function(e){return arguments.length?n(t=e[0]*Ae/180,r=e[1]*Ae/180):[t/Ae*180,r/Ae*180]},a}function on(e,t){var r=Math.sin(e),n=(r+Math.sin(t))/2,a=1+r*(2*n-r),i=Math.sqrt(a)/n;function o(e,t){var r=Math.sqrt(a-2*n*Math.sin(t))/n;return[r*Math.sin(e*=n),i-r*Math.cos(e)]}return o.invert=function(e,t){var r=i-t;return[Math.atan2(e,r)/n,Ee((a-(e*e+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var e,t,r,n,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=nn(e=+l[0][0],t=+l[0][1],r=+l[1][0],n=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,r){e=[t,r]}};function c(t){var i=t[0],o=t[1];return e=null,r(i,o),e||(n(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),r=i.translate(),n=(e[0]-r[0])/t,a=(e[1]-r[1])/t;return(a>=.12&&a<.234&&n>=-.425&&n<-.214?o:a>=.166&&a<.234&&n>=-.214&&n<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),r=o.stream(e),n=l.stream(e);return{point:function(e,a){t.point(e,a),r.point(e,a),n.point(e,a)},sphere:function(){t.sphere(),r.sphere(),n.sphere()},lineStart:function(){t.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){t.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){t.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){t.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return r=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,n=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var ln,sn,cn,un,fn,dn,hn={point:N,lineStart:N,lineEnd:N,polygonStart:function(){sn=0,hn.lineStart=pn},polygonEnd:function(){hn.lineStart=hn.lineEnd=hn.point=N,ln+=m(sn/2)}};function pn(){var e,t,r,n;function a(e,t){sn+=n*e-r*t,r=e,n=t}hn.point=function(i,o){hn.point=a,e=r=i,t=n=o},hn.lineEnd=function(){a(e,t)}}var gn={point:function(e,t){efn&&(fn=e);tdn&&(dn=t)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vn(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yn,mn={point:xn,lineStart:bn,lineEnd:_n,polygonStart:function(){mn.lineStart=wn},polygonEnd:function(){mn.point=xn,mn.lineStart=bn,mn.lineEnd=_n}};function xn(e,t){xr+=e,br+=t,++_r}function bn(){var e,t;function r(r,n){var a=r-e,i=n-t,o=Math.sqrt(a*a+i*i);wr+=o*(e+r)/2,kr+=o*(t+n)/2,Mr+=o,xn(e=r,t=n)}mn.point=function(n,a){mn.point=r,xn(e=n,t=a)}}function _n(){mn.point=xn}function wn(){var e,t,r,n;function a(e,t){var a=e-r,i=t-n,o=Math.sqrt(a*a+i*i);wr+=o*(r+e)/2,kr+=o*(n+t)/2,Mr+=o,Ar+=(o=n*e-r*t)*(r+e),Tr+=o*(n+t),Lr+=3*o,xn(r=e,n=t)}mn.point=function(i,o){mn.point=a,xn(e=r=i,t=n=o)},mn.lineEnd=function(){a(e,t)}}function kn(e){var t=.5,r=Math.cos(30*Se),n=16;function a(t){return(n?function(t){var r,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(r,n){r=e(r,n),t.point(r[0],r[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(r,a){var o=Pr([r,a]),l=e(r,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=r,h=o[0],p=o[1],g=o[2],n,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(r=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,r,l,s,c,n,t),v.lineEnd=b,b()}return v}:function(t){return An(t,function(r,n){r=e(r,n),t.point(r[0],r[1])})})(t)}function i(n,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-n,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,A=Math.sqrt(w*w+k*k+M*M),T=Math.asin(M/=A),L=m(m(M)-1)t||m((x*P+b*z)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mn(e){this.stream=e}function An(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Tn(e){return Ln(function(){return e})()}function Ln(e){var r,n,a,i,o,l,s=kn(function(e,t){return[(e=r(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=en,x=P,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Oe,e[1]*Oe]}function M(){a=Gr(n=Pn(p,g,v),r);var e=r(d,h);return i=u-e[0]*c,o=f+e[1]*c,A()}function A(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cn(y(n,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,en):function(e){var t=Math.cos(e),r=t>0,n=m(t)>ke;return Qr(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=r?g?0:o(f,d):g?o(f+(f<0?Ae:-Ae),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(Fr(t,h)||Fr(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(n&&t&&r^g){var y;v&l||!(y=i(p,t,!0))||(u=0,r?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&Fr(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Nn(e,6*Se),r?[0,-e]:[-Ae,e-Ae]);function a(e,r){return Math.cos(e)*Math.cos(r)>t}function i(e,r,n){var a=[1,0,0],i=Dr(Pr(e),Pr(r)),o=zr(i,i),l=i[0],s=o-l*l;if(!s)return!n&&e;var c=t*o/s,u=-t*l/s,f=Dr(a,i),d=Nr(a,c);Er(d,Nr(i,u));var h=f,p=zr(d,h),g=zr(h,h),v=p*p-g*(zr(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=Nr(h,(-p-y)/g);if(Er(x,d),x=Rr(x),!n)return x;var b,_=e[0],w=r[0],k=e[1],M=r[1];w<_&&(b=_,_=w,w=b);var A=w-_,T=m(A-Ae)0^x[1]<(m(x[0]-_)Ae^(_<=x[0]&&x[0]<=w)){var L=Nr(h,(-p+y)/g);return Er(L,d),[x,Rr(L)]}}}function o(t,n){var a=r?e:Ae-e,i=0;return t<-a?i|=1:t>a&&(i|=2),n<-a?i|=4:n>a&&(i|=8),i}}((b=+e)*Se),A()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?nn(e[0][0],e[0][1],e[1][0],e[1][1]):P,A()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Se,h=e[1]%360*Se,M()):[d*Oe,h*Oe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*Oe,g*Oe,v*Oe]},t.rebind(w,s,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&k,M()}}function Cn(e){return An(e,function(t,r){e.point(t*Se,r*Se)})}function Sn(e,t){return[e,t]}function On(e,t){return[e>Ae?e-Te:e<-Ae?e+Te:e,t]}function Pn(e,t,r){return e?t||r?Gr(Dn(e),En(t,r)):Dn(e):t||r?En(t,r):On}function zn(e){return function(t,r){return[(t+=e)>Ae?t-Te:t<-Ae?t+Te:t,r]}}function Dn(e){var t=zn(e);return t.invert=zn(-e),t}function En(e,t){var r=Math.cos(e),n=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*r+l*n;return[Math.atan2(s*a-u*i,l*r-c*n),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*r+u*n),Ee(u*r-l*n)]},o}function Nn(e,t){var r=Math.cos(e),n=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=In(r,a),i=In(r,i),(o>0?ai)&&(a+=o*Te)):(a=e+o*Te,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=Oe,t[1]*=Oe,t},t},On.invert=Sn,t.geo.circle=function(){var e,t,r=[0,0],n=6;function a(){var e="function"==typeof r?r.apply(this,arguments):r,n=Pn(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=n(e,t)),e[0]*=Oe,e[1]*=Oe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(r=e,a):r},a.angle=function(r){return arguments.length?(t=Nn((e=+r)*Se,n*Se),a):e},a.precision=function(r){return arguments.length?(t=Nn(e*Se,(n=+r)*Se),a):n},a.angle(90)},t.geo.distance=function(e,t){var r,n=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(n),l=Math.cos(n),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-s*f*l)*r),s*u+c*f*l)},t.geo.graticule=function(){var e,r,n,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,n,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(r/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(n).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],n=+e[1][0],s=+e[0][1],l=+e[1][1],a>n&&(e=a,a=n,n=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[n,l]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],r>e&&(t=r,r=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[r,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Rn(o,i,90),u=Fn(r,e,y),f=Rn(s,l,90),d=Fn(a,n,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,r,n=jn,a=Bn;function i(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||a.apply(this,arguments))},i.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,i):n},i.target=function(e){return arguments.length?(a=e,r="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return r=e[0]*Se,n=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(n),l=Math.sin(n),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(r),f=o*Math.sin(r),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ie(i-n)+o*s*Ie(a-r))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,r=Math.sin(p-e)*g,n=r*u+t*d,a=r*f+t*h,i=r*l+t*c;return[Math.atan2(a,n)*Oe,Math.atan2(i,Math.sqrt(n*n+a*a))*Oe]}:function(){return[r*Oe,n*Oe]}).distance=p,v;var r,n,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yn=0,t.geo.stream(e,Hn),yn};var Hn={sphere:N,point:N,lineStart:function(){var e,t,r;function n(n,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((n*=Se)-e),s=Math.cos(l);yn+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=r*i-t*o*s)*l),t*i+r*o*s),e=n,t=i,r=o}Hn.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),r=Math.cos(i),Hn.point=n},Hn.lineEnd=function(){Hn.point=Hn.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function qn(e,t){function r(t,r){var n=Math.cos(t),a=Math.cos(r),i=e(n*a);return[i*a*Math.sin(t),i*Math.sin(r)]}return r.invert=function(e,r){var n=Math.sqrt(e*e+r*r),a=t(n),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,n*o),Math.asin(n&&r*i/n)]},r}var Vn=qn(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Tn(Vn)}).raw=Vn;var Un=qn(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},P);function Gn(e,t){var r=Math.cos(e),n=function(e){return Math.tan(Ae/4+e/2)},a=e===t?Math.sin(e):Math.log(r/Math.cos(t))/Math.log(n(t)/n(e)),i=r*Math.pow(n(e),a)/a;if(!a)return Zn;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var r=i/Math.pow(n(t),a);return[r*Math.sin(a*e),i-r*Math.cos(a*e)]}return o.invert=function(e,t){var r=i-t,n=Pe(a)*Math.sqrt(e*e+r*r);return[Math.atan2(e,r)/a,2*Math.atan(Math.pow(i/n,1/a))-Ce]},o}function Yn(e,t){var r=Math.cos(e),n=e===t?Math.sin(e):(r-Math.cos(t))/(t-e),a=r/n+e;if(m(n)1&&ze(e[r[n-2]],e[r[n-1]],e[a])<=0;)--n;r[n++]=a}return r.slice(0,n)}function ra(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Tn(Jn)}).raw=Jn,$n.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wn($n),t=e.center,r=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?r([e[0],e[1],e.length>2?e[2]+90:90]):[(e=r())[0],e[1],e[2]-90]},r([0,0,90])}).raw=$n,t.geom={},t.geom.hull=function(e){var t=Kn,r=ea;if(arguments.length)return n(e);function n(e){if(e.length<3)return[];var n,a=vt(t),i=vt(r),o=e.length,l=[],s=[];for(n=0;n=0;--n)h.push(e[l[c[n]][2]]);for(n=+f;nke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){n>-ke?(t=l.P,r=l):a>-ke?(t=l,r=l.N):t=r=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||r){if(t===r)return ka(t),r=pa(t.site),ca.insert(s,r),s.edge=r.edge=Ta(t.site,s.site),wa(t),void wa(r);if(r){ka(t),ka(r);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=r.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(r.edge,c,p,b),s.edge=Ta(c,e,null,b),r.edge=Ta(e,p,null,b),wa(t),wa(r)}else s.edge=Ta(t.site,s.site)}}function ma(e,t){var r=e.site,n=r.x,a=r.y,i=a-t;if(!i)return n;var o=e.P;if(!o)return-1/0;var l=(r=o.site).x,s=r.y,c=s-t;if(!c)return l;var u=l-n,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+n:(n+l)/2}function xa(e,t){var r=e.N;if(r)return ma(r,t);var n=e.site;return n.y===t?n.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,r=e.N;if(t&&r){var n=t.site,a=e.site,i=r.site;if(n!==i){var o=a.x,l=a.y,s=n.x-o,c=n.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){Oa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};r={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/n,y:s};r={x:(c-a)/n,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:n*o+a};r={x:l,y:n*l+a}}else{if(i){if(i.xke||m(a-r)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(n-f)ke?{x:f,y:m(t-f)ke?{x:m(r-p)ke?{x:d,y:m(t-d)ke?{x:m(r-h)=r&&c.x<=a&&c.y>=n&&c.y<=o?[[r,o],[a,o],[a,n],[r,n]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(n(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(r,n){for(var a,i,o,l,s=r.site,c=r.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(r=r[0])===(n=n[0])?l[o]?l[o]+=n:l[++o]=n:(l[++o]=null,s.push({i:o,x:Ha(r,n)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,r,n,a,i,o,l){if(!isNaN(r)&&!isNaN(n))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-r)+m(c-n)<.01)A(e,t,r,n,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,A(e,u,s,c,a,i,o,l),A(e,t,r,n,a,i,o,l)}else e.x=r,e.y=n,e.point=t}else A(e,t,r,n,a,i,o,l)}function A(e,t,r,n,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=r>=s,f=n>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,r,n,a,i,o,l)}w>k?v=p+w:g=h+k;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(T.visit=function(e){!function e(t,r,n,a,i,o){if(!t(r,n,a,i,o)){var l=.5*(n+i),s=.5*(a+o),c=r.nodes;c[0]&&e(t,c[0],n,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],n,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,T,h,p,g,v)},T.find=function(e){return function(e,t,r,n,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(n=t.interpolators[a](e,r)););return n}function Ya(e,t){var r,n=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(r=0;r=1)return 1;var t=e*e,r=t*e;return 4*(e<.5?r:3*(e-t)+r-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ri(e){return Math.pow(2,10*(e-1))}function ni(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(r){return Math.round(e+t*r)}}function oi(e){var t,r,n,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(n=-l)*(r=a)[0],t[1]+=n*r[1],t))||0;a[0]*i[1]=0?e.slice(0,n):e,i=n>=0?e.slice(n+1):"in";return a=Za.get(a)||Xa,i=Wa.get(i)||P,t=i(a.apply(null,r.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,a=e.c,i=e.l,o=r.h-n,l=r.c-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.c:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(e){return Xe(n+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,a=e.s,i=e.l,o=r.h-n,l=r.s-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.s:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(n+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,a=e.a,i=e.b,o=r.l-n,l=r.a-a,s=r.b-i;return function(e){return et(n+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var r=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){r.setAttribute("transform",e);var t=r.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,r){var n=[],a=[];return e=t.transform(e),r=t.transform(r),function(e,t,r,n){if(e[0]!==t[0]||e[1]!==t[1]){var a=r.push("translate(",null,",",null,")");n.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else(t[0]||t[1])&&r.push("translate("+t+")")}(e.translate,r.translate,n,a),function(e,t,r,n){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),n.push({i:r.push(ui(r)+"rotate(",null,")")-2,x:Ha(e,t)})):t&&r.push(ui(r)+"rotate("+t+")")}(e.rotate,r.rotate,n,a),function(e,t,r,n){e!==t?n.push({i:r.push(ui(r)+"skewX(",null,")")-2,x:Ha(e,t)}):t&&r.push(ui(r)+"skewX("+t+")")}(e.skew,r.skew,n,a),function(e,t,r,n){if(e[0]!==t[0]||e[1]!==t[1]){var a=r.push(ui(r)+"scale(",null,",",null,")");n.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else 1===t[0]&&1===t[1]||r.push(ui(r)+"scale("+t+")")}(e.scale,r.scale,n,a),e=r=null,function(e){for(var t,r=-1,i=a.length;++r0?n=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:n=0})):t>0&&(s.start({type:"start",alpha:n=t}),e=Mt(l.tick)),l):n},l.start=function(){var e,t,r,n=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)r.push(a[n])}function Ai(e,t){for(var r=[e],n=[];null!=(e=r.pop());)if(n.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;r&&(i.value=0),i.children=c}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Ai(a,function(t){var n,a;e&&(n=t.children)&&n.sort(e),r&&(a=t.parent)&&(a.value+=t.value)}),l}return n.sort=function(t){return arguments.length?(e=t,n):e},n.children=function(e){return arguments.length?(t=e,n):t},n.value=function(e){return arguments.length?(r=e,n):r},n.revalue=function(e){return r&&(Mi(e,function(e){e.children&&(e.value=0)}),Ai(e,function(e){var t;e.children||(e.value=+r.call(n,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var a=e.call(this,t,n);return function e(t,r,n,a){var i=t.children;if(t.x=r,t.y=t.depth*a,t.dx=n,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(n=t.value?n/t.value:0;++cl&&(l=n),o.push(n)}for(r=0;ra&&(n=r,a=t);return n}function ji(e){return e.reduce(Bi,0)}function Bi(e,t){return e+t[1]}function Hi(e,t){return qi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function qi(e,t){for(var r=-1,n=+e[0],a=(e[1]-n)/t,i=[];++r<=t;)i[r]=a*r+n;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var r=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=r,r._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Xi(e,t){var r=t.x-e.x,n=t.y-e.y,a=e.r+t.r;return.999*a*a>r*r+n*n}function Zi(e){if((t=e.children)&&(s=t.length)){var t,r,n,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(r=t[0]).x=-r.r,r.y=0,x(r),s>1&&((n=t[1]).x=n.r,n.y=0,x(n),s>2))for(Ji(r,n,a=t[2]),x(a),Gi(r,a),r._pack_prev=a,Gi(a,n),n=r._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(r=e,i):r},i.range=function(e){return arguments.length?(n=vt(e),i):n},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return qi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Ui),n=0,a=[1,1];function i(t,i){var o=r.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ai(l,function(e){e.r=+u(e.value)}),Ai(l,Zi),n){var f=n*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ai(l,function(e){e.r+=f}),Ai(l,Zi),Ai(l,function(e){e.r-=f})}return function e(t,r,n,a){var i=t.children;t.x=r+=a*t.x;t.y=n+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=r(d,h)/2-d.x,v=n[0]/(h.x+r(h,d)/2+g),y=n[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,n=e.parent.children,a=e.i?n[e.i-1]:null;if(t.length){!function(e){var t,r=0,n=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=r,t.m+=r,r+=t.s+(n+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+r(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+r(e._,a._));e.parent.A=function(e,t,n){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+r(l._,i._))>0&&(to(ro(l,e,n),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,n=e)}return n}(e,a,e.parent.A||n[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=n[0],e.y=e.depth*n[1]}return i.separation=function(e){return arguments.length?(r=e,i):r},i.size=function(e){return arguments.length?(a=null==(n=e)?s:null,i):a?null:n},i.nodeSize=function(e){return arguments.length?(a=null==(n=e)?null:s,i):a?n:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=$i,n=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ai(c,function(e){var n=e.children;n&&n.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(n),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(n)):(e.x=l?u+=r(e,l):0,e.y=0,l=e)});var f=function e(t){var r=t.children;return r&&r.length?e(r[0]):t}(c),d=function e(t){var r,n=t.children;return n&&(r=n.length)?e(n[r-1]):t}(c),h=f.x-r(f,d)/2,p=d.x+r(d,f)/2;return Ai(c,a?function(e){e.x=(e.x-c.x)*n[0],e.y=(c.y-e.y)*n[1]}:function(e){e.x=(e.x-h)/(p-h)*n[0],e.y=(1-(c.y?e.y/c.y:1))*n[1]}),s}return i.separation=function(e){return arguments.length?(r=e,i):r},i.size=function(e){return arguments.length?(a=null==(n=e),i):a?null:n},i.nodeSize=function(e){return arguments.length?(a=null!=(n=e),i):a?n:null},ki(i,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,a=[1,1],i=null,o=no,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var r,n,a=-1,i=e.length;++a0;)l.push(r=c[a-1]),l.area+=r.area,"squarify"!==s||(n=h(l,g))<=d?(c.pop(),d=n):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var r,n=o(e),a=t.slice(),i=[];for(u(a,n.dx*n.dy/e.value),i.area=0;r=a.pop();)i.push(r),i.area+=r.area,null!=r.z&&(p(i,r.z?n.dx:n.dy,n,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var r,n=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=r));return t*=t,(n*=n)?Math.max(t*a*c/n,n/(t*i*c)):1/0}function p(e,t,r,a){var i,o=-1,l=e.length,s=r.x,c=r.y,u=t?n(e.area/t):0;if(t==r.dx){for((a||u>r.dy)&&(u=r.dy);++or.dx)&&(u=r.dx);++o1);return e+t*r*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(e){return function(){for(var t=0,r=0;r2?fo:lo,l=a?hi:di;return i=e(t,r,l,n),o=e(r,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(r=e,l()):r};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(n=e,l()):n};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,r){return yo(t,e,r)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,r,n,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(n)}function l(e){return a?Math.pow(n,e):-Math.pow(n,-e)}function s(e){return r(o(e))}s.invert=function(e){return l(r.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,r.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(n=+e,r.domain(i.map(o)),s):n};s.nice=function(){var e=so(i.map(o),a?Math:_o);return r.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],r=e[0],s=e[1],c=Math.floor(o(r)),u=Math.ceil(o(s)),f=n%1?2:n;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,r){if(!arguments.length)return bo;arguments.length<2?r=bo:"function"!=typeof r&&(r=t.format(r));var a=Math.max(1,n*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*n0?a[e-1]:r[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,A,T=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=n===Co?Math.sqrt(l*l+c*c):+n.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(T=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Ae?0:1;if(L&&Eo(m,x,b,_)===h^S){var O=(u+f)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-T),k=l*Math.sin(f-T),M=l*Math.cos(u+T),A=l*Math.sin(u+T);var P=Math.abs(u-f+2*T)<=Ae?0:1;if(T&&Eo(w,k,M,A)===1-h^P){var z=(u+f)/2;w=l*Math.cos(z),k=l*Math.sin(z),M=A=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+r.apply(this,arguments)))>.001){g=l0?0:1}function No(e,t,r,n,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?n:-n)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=r-n,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,A=(-b*v+y*_)/m,T=w-p,L=k-g,C=M-p,S=A-g;return T*T+L*L>C*C+S*S&&(w=M,k=A),[[w-s,k-c],[w*r/x,k*r/x]]}function Io(e){var t=Kn,r=ea,n=Yr,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(r);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",n[0]);return a.join("")},"step-before":Bo,"step-after":Ho,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,r=[],n=-1,a=e.length,i=[0],o=[0];for(;++n<3;)t=e[n],i.push(t[0]),o.push(t[1]);r.push(Go(Zo,i)+","+Go(Zo,o)),--n;for(;++n9&&(a=3*t/Math.sqrt(a),o[l]=a*r,o[l+1]=a*n));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function jo(e){return e.join("L")+"Z"}function Bo(e){for(var t=0,r=e.length,n=e[0],a=[n[0],",",n[1]];++t1){l=t[1],i=e[s],s++,n+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cAe)+",1 "+t}function s(e,t,r,n){return"Q 0,0 "+n}return i.radius=function(e){return arguments.length?(r=vt(e),i):r},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(n=vt(e),i):n},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=jn,t=Bn,r=el;function n(n,a){var i=e.call(this,n,a),o=t.call(this,n,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(r))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return n.source=function(t){return arguments.length?(e=vt(t),n):e},n.target=function(e){return arguments.length?(t=vt(e),n):t},n.projection=function(e){return arguments.length?(r=e,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=el,n=e.projection;return e.projection=function(e){return arguments.length?n(function(e){return function(){var t=e.apply(this,arguments),r=t[0],n=t[1]-Ce;return[r*Math.cos(n),r*Math.sin(n)]}}(r=e)):r},e},t.svg.symbol=function(){var e=rl,t=tl;function r(r,n){return(al.get(e.call(this,r,n))||nl)(t.call(this,r,n))}return r.type=function(t){return arguments.length?(e=vt(t),r):e},r.size=function(e){return arguments.length?(t=vt(e),r):t},r};var al=t.map({circle:nl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),r=t*ol;return"M0,"+-t+"L"+r+",0 0,"+t+" "+-r+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),r=t*il/2;return"M0,"+r+"L"+t+","+-r+" "+-t+","+-r+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),r=t*il/2;return"M0,"+-r+"L"+t+","+r+" "+-t+","+r+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);X.transition=function(e){for(var t,r,n=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[n]:delete e[r],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[n]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=X.call,dl.empty=X.empty,dl.node=X.node,dl.size=X.size,t.transition=function(e,r){return e&&e.transition?ul?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,r,n,a=this.id,i=this.namespace,o=[];e=Z(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=n.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),A=xe(y),T=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,T[0]-=l[1],T[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(T[0]+=l[1],T[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",z):L.on("mousemove.brush",O).on("mouseup.brush",z),b.interrupt().selectAll("*").interrupt(),M)T[0]=l[0]-T[0],T[1]=s[0]-T[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-T[0],s[1-S]-T[1]],T[0]=l[C],T[1]=s[S]}else t.event.altKey&&(f=T.slice());function O(){var e=t.mouse(y),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),T[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var r=io(a.domain()),n=null==e?i(r,10):"number"==typeof e?i(r,e):!e.range&&[{range:e},t];return n&&(e=n[0],t=n[1]),e.range(r[0],Sl(+r[1]+1),t<1?1:t)},a.tickFormat=function(){return n},a.copy=function(){return Cl(e.copy(),r,n)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Tl,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Tl.toString,Dt.second=Rt(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=Rt(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=Rt(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=Rt(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Pl=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],zl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Yr]]),Dl={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Sl)},floor:P,ceil:P};Pl.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),Pl,zl)};var El=Pl.map(function(e){return[e[0].utc,e[1]]}),Nl=Al.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Yr]]);function Il(e){return JSON.parse(e.responseText)}function Rl(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Nl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Il,t)},t.html=function(e,t){return mt(e,"text/html",Rl,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t={};t.xmlns="http://www.w3.org/2000/xmlns/",t.svg="http://www.w3.org/2000/svg",t.xlink="http://www.w3.org/1999/xlink",t.svgAttrs={xmlns:t.svg,"xmlns:xlink":t.xlink};var r=function(e){var t=typeof e;if("string"===t){var r=e;if(0===(e=+e)&&function(e){for(var t,r=e.length,n=0;n13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(r))return!1}else if("number"!==t)return!1;return e-e<1},n={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},a={},i=Math.PI;a.deg2rad=function(e){return e/180*i},a.rad2deg=function(e){return e/i*180},a.wrap360=function(e){var t=e%360;return t<0?t+360:t},a.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var o=n.BADNUM,l=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(e){var t=/^\s+/,r=/\s+$/,n=0,a=e.round,i=e.min,o=e.max,l=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(n){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof n&&(n=function(e){e=e.replace(t,"").replace(r,"").toLowerCase();var n,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(n=B.rgb.exec(e))return{r:n[1],g:n[2],b:n[3]};if(n=B.rgba.exec(e))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=B.hsl.exec(e))return{h:n[1],s:n[2],l:n[3]};if(n=B.hsla.exec(e))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=B.hsv.exec(e))return{h:n[1],s:n[2],v:n[3]};if(n=B.hsva.exec(e))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=B.hex8.exec(e))return{r:z(n[1]),g:z(n[2]),b:z(n[3]),a:I(n[4]),format:a?"name":"hex8"};if(n=B.hex6.exec(e))return{r:z(n[1]),g:z(n[2]),b:z(n[3]),format:a?"name":"hex"};if(n=B.hex4.exec(e))return{r:z(n[1]+""+n[1]),g:z(n[2]+""+n[2]),b:z(n[3]+""+n[3]),a:I(n[4]+""+n[4]),format:a?"name":"hex8"};if(n=B.hex3.exec(e))return{r:z(n[1]+""+n[1]),g:z(n[2]+""+n[2]),b:z(n[3]+""+n[3]),format:a?"name":"hex"};return!1}(n));"object"==typeof n&&(H(n.r)&&H(n.g)&&H(n.b)?(h=n.r,p=n.g,g=n.b,a={r:255*O(h,255),g:255*O(p,255),b:255*O(g,255)},f=!0,d="%"===String(n.r).substr(-1)?"prgb":"rgb"):H(n.h)&&H(n.s)&&H(n.v)?(s=E(n.s),c=E(n.v),a=function(t,r,n){t=6*O(t,360),r=O(r,100),n=O(n,100);var a=e.floor(t),i=t-a,o=n*(1-r),l=n*(1-i*r),s=n*(1-(1-i)*r),c=a%6;return{r:255*[n,l,o,o,s,n][c],g:255*[s,n,n,l,o,o][c],b:255*[o,o,s,n,n,l][c]}}(n.h,s,c),f=!0,d="hsv"):H(n.h)&&H(n.s)&&H(n.l)&&(s=E(n.s),u=E(n.l),a=function(e,t,r){var n,a,i;function o(e,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?e+6*(t-e)*r:r<.5?t:r<2/3?e+(t-e)*(2/3-r)*6:e}if(e=O(e,360),t=O(t,100),r=O(r,100),0===t)n=a=i=r;else{var l=r<.5?r*(1+t):r+t-r*t,s=2*r-l;n=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*n,g:255*a,b:255*i}}(n.h,s,u),f=!0,d="hsl"),n.hasOwnProperty("a")&&(l=n.a));var h,p,g;return l=S(l),{ok:f,format:n.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=n++}function u(e,t,r){e=O(e,255),t=O(t,255),r=O(r,255);var n,a,l=o(e,t,r),s=i(e,t,r),c=(l+s)/2;if(l==s)n=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:n=(t-r)/u+(t>1)+720)%360;--t;)n.h=(n.h+a)%360,i.push(c(n));return i}function T(e,t){t=t||6;for(var r=c(e).toHsv(),n=r.h,a=r.s,i=r.v,o=[],l=1/t;t--;)o.push(c({h:n,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,r,n,a=this.toRgb();return t=a.r/255,r=a.g/255,n=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),r=a(100*e.s),n=a(100*e.v);return 1==this._a?"hsv("+t+", "+r+"%, "+n+"%)":"hsva("+t+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),r=a(100*e.s),n=a(100*e.l);return 1==this._a?"hsl("+t+", "+r+"%, "+n+"%)":"hsla("+t+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,r,n,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(r).toString(16)),D(N(n))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*O(this._r,255))+"%",g:a(100*O(this._g,255))+"%",b:a(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%)":"rgba("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),r=t,n=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);r="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+t+",endColorstr="+r+")"},toString:function(e){var t=!!e;e=e||this._format;var r=!1,n=this._a<1&&this._a>=0;return t||!n||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(r=this.toRgbString()),"prgb"===e&&(r=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(r=this.toHexString()),"hex3"===e&&(r=this.toHexString(!0)),"hex4"===e&&(r=this.toHex8String(!0)),"hex8"===e&&(r=this.toHex8String()),"name"===e&&(r=this.toName()),"hsl"===e&&(r=this.toHslString()),"hsv"===e&&(r=this.toHsvString()),r||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var r=e.apply(null,[this].concat([].slice.call(t)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(A,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var r={};for(var n in e)e.hasOwnProperty(n)&&(r[n]="a"===n?e[n]:E(e[n]));e=r}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(e,t,r){r=0===r?0:r||50;var n=c(e).toRgb(),a=c(t).toRgb(),i=r/100;return c({r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a})},c.readability=function(t,r){var n=c(t),a=c(r);return(e.max(n.getLuminance(),a.getLuminance())+.05)/(e.min(n.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,r){var n,a,i=c.readability(e,t);switch(a=!1,(n=function(e){var t,r;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==r&&"large"!==r&&(r="small");return{level:t,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,r){var n,a,i,o,l=null,s=0;a=(r=r||{}).includeFallbackColors,i=r.level,o=r.size;for(var u=0;us&&(s=n,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(r.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],r))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[e[r]]=r);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function O(t,r){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(r,o(0,parseFloat(t))),n&&(t=parseInt(t*r,10)/100),e.abs(t-r)<1e-6?1:t%r/parseFloat(r)}function P(e){return i(1,o(0,e))}function z(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function N(t){return e.round(255*parseFloat(t)).toString(16)}function I(e){return z(e)/255}var R,F,j,B=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",j="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function H(e){return!!B.CSS_UNIT.exec(e)}s.exports?s.exports=c:window.tinycolor=c}(Math),s=s.exports;var c={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=c.RdBu,f=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var r=0;r1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(n=e[t][0],a=e[t][1],o=!1,Y(n))for(r=n.length-1;r>=0;r--)Q(n[r],$(a,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(i=Object.keys(n),o=!1,r=i.length-1;r>=0;r--)Q(n[i[r]],$(a,i[r]))?delete n[i[r]]:o=!0;if(o)return}}(s)):o[t[i]]=n}}function $(e,t){var n=t;return r(t)?n="["+t+"]":e&&(n="."+t),e+n}function K(e,t,r,n){var a,i=Y(r),o=!0,l=r,s=n.replace("-1",0),c=!i&&Q(r,s),u=t[0];for(a=0;aa.max?t.set(n):t.set(+e)}},integer:{coerceFunction:function(e,t,n,a){e%1||!r(e)||void 0!==a.min&&ea.max?t.set(n):t.set(+e)}},string:{coerceFunction:function(e,t,r,n){if("string"!=typeof e){var a="number"==typeof e;!0!==n.strict&&a?t.set(String(e)):t.set(r)}else n.noBlank&&!e?t.set(r):t.set(e)}},color:{coerceFunction:function(e,t,r){s(e).isValid()?t.set(e):t.set(r)}},colorlist:{coerceFunction:function(e,t,r){Array.isArray(e)&&e.length&&e.every(function(e){return s(e).isValid()})?t.set(e):t.set(r)}},colorscale:{coerceFunction:function(e,t,r){t.set(d(e,r))}},angle:{coerceFunction:function(e,t,n){"auto"===e?t.set("auto"):r(e)?t.set(ie(+e)):t.set(n)}},subplotid:{coerceFunction:function(e,t,r){"string"==typeof e&&ne(r).test(e)?t.set(e):t.set(r)},validateFunction:function(e,t){var r=t.dflt;return e===r||"string"==typeof e&&!!ne(r).test(e)}},flaglist:{coerceFunction:function(e,t,r,n){if("string"==typeof e)if(-1===(n.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=le&&e<=se?e:fe;if("string"!=typeof e&&"number"!=typeof e)return fe;e=String(e);var r=_e(t),n=e.charAt(0);!r||"G"!==n&&"g"!==n||(e=e.substr(1),t="");var a=r&&"chinese"===t.substr(0,7),i=e.match(a?xe:me);if(!i)return fe;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(r){if(2===o.length)return fe;var d;o=Number(o);try{var h=D.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return fe}return d?(d.toJD()-ve)*de+c*he+u*pe+f*ge:fe}o=2===o.length?(Number(o)+2e3-be)%100+be:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?fe:g.getUTCDate()!==s?fe:g.getTime()+f*ge},le=ue.MIN_MS=ue.dateTime2ms("-9999"),se=ue.MAX_MS=ue.dateTime2ms("9999-12-31 23:59:59.9999"),ue.isDateTime=function(e,t){return ue.dateTime2ms(e,t)!==fe};var ke=90*de,Me=3*he,Ae=5*pe;function Te(e,t,r,n,a){if((t||r||n||a)&&(e+=" "+we(t,2)+":"+we(r,2),(n||a)&&(e+=":"+we(n,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+we(a,i)}return e}ue.ms2DateTime=function(e,t,r){if("number"!=typeof e||!(e>=le&&e<=se))return fe;t||(t=0);var n,a,i,o,l,s,c=Math.floor(10*ce(e+.05,1)),u=Math.round(e-c/10);if(_e(r)){var f=Math.floor(u/de)+ve,d=Math.floor(ce(e,de));try{n=D.getComponentMethod("calendars","getCal")(r).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){n=ye("G%Y-%m-%d")(new Date(u))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;a=t=le+de&&t<=se-de))return fe;var r=Math.floor(10*ce(t+.05,1)),n=new Date(Math.round(t-r/10));return Te(e.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ue.cleanDate=function(e,t,r){if(ue.isJSDate(e)||"number"==typeof e){if(_e(r))return w.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ue.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ue.isDateTime(e,r))return w.error("unrecognized date",e),t;return e};var Le=/%\d?f/g;function Ce(e,t,r,n){e=e.replace(Le,function(e){var r=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(_e(n))try{e=D.getComponentMethod("calendars","worldCalFmt")(e,t,n)}catch(e){return"Invalid"}return r(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ue.formatDate=function(e,t,n,a,i,o){if(i=_e(i)&&i,!t)if("y"===n)t=o.year;else if("m"===n)t=o.month;else{if("d"!==n)return function(e,t){var n=ce(e+.05,de),a=we(Math.floor(n/he),2)+":"+we(ce(Math.floor(n/pe),60),2);if("M"!==t){r(t)||(t=0);var i=(100+Math.min(ce(e/ge,60),Se[t])).toFixed(t).substr(1);t>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,n)+"\n"+Ce(o.dayMonthYear,e,a,i);t=o.dayMonth+"\n"+o.year}return Ce(t,e,a,i)};var Oe=3*de;ue.incrementMonth=function(e,t,r){r=_e(r)&&r;var n=ce(e,de);if(e=Math.round(e-n),r)try{var a=Math.round(e/de)+ve,i=D.getComponentMethod("calendars","getCal")(r),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ve)*de+n}catch(t){w.error("invalid ms "+e+" in calendar "+r)}var l=new Date(e+Oe);return l.setUTCMonth(l.getUTCMonth()+t)+n-Oe},ue.findExactDates=function(e,t){for(var n,a,i=0,o=0,l=0,s=0,c=_e(t)&&D.getComponentMethod("calendars","getCal")(t),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Fe(e,t,r,n,a){var i=n*e+a*t;if(i<0)return n*n+a*a;if(i>r){var o=n-e,l=a-t;return o*o+l*l}var s=n*t-a*e;return s*s/r}Ie.segmentsIntersect=Re,Ie.segmentDistance=function(e,t,r,n,a,i,o,l){if(Re(e,t,r,n,a,i,o,l))return 0;var s=r-e,c=n-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Fe(s,c,d,a-e,i-t),Fe(s,c,d,o-e,l-t),Fe(u,f,h,e-a,t-i),Fe(u,f,h,r-a,n-i));return Math.sqrt(p)},Ie.getTextLocation=function(e,t,r,n){if(e===Ee&&n===Ne||(De={},Ee=e,Ne=n),De[r])return De[r];var a=e.getPointAtLength(ce(r-n/2,t)),i=e.getPointAtLength(ce(r+n/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(ce(r,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return De[r]=s,s},Ie.clearLocationCache=function(){Ee=null},Ie.getVisibleSegment=function(e,t,r){var n,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var r=e.getPointAtLength(t);0===t?n=r:t===u&&(a=r);var c=r.xo?r.x-o:0,f=r.ys?r.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+r)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+r))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(n.x-a.x)<.1&&Math.abs(n.y-a.y)<.1}},Ie.findPointOnPath=function(e,t,r,n){for(var a,i,o,l=(n=n||{}).pathLength||e.getTotalLength(),s=n.tolerance||.001,c=n.iterationLimit||30,u=e.getPointAtLength(0)[r]>e.getPointAtLength(l)[r]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var je=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},Be=/^\w*$/,He={init2dArray:function(e,t){for(var r=new Array(e),n=0;nt}function Qe(e,t){return e>=t}Ye.findBin=function(e,t,n){if(r(t.start))return n?Math.ceil((e-t.start)/t.size-1e-9)-1:Math.floor((e-t.start)/t.size+1e-9);var a,i,o=0,l=t.length,s=0,c=l>1?(t[l-1]-t[0])/(l-1):1;for(i=c>=0?n?Xe:Ze:n?Qe:We,e+=1e-9*c*(n?-1:1)*(c>=0?1:-1);o90&&w.log("Long binary search..."),o-1},Ye.sorterAsc=function(e,t){return e-t},Ye.sorterDes=function(e,t){return t-e},Ye.distinctVals=function(e){var t=e.slice();t.sort(Ye.sorterAsc);for(var r=t.length-1,n=t[r]-t[0]||1,a=n/(r||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(n=Math.min(n,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:n}},Ye.roundUp=function(e,t,r){for(var n,a=0,i=t.length-1,o=0,l=r?0:1,s=r?1:0,c=r?Math.ceil:Math.floor;an.length)&&(a=n.length),r(t)||(t=!1),$e(n[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var n=t%1;return n*e[Math.ceil(t)]+(1-n)*e[Math.floor(t)]};var Ke={},et={};function tt(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}Ke.throttle=function(e,t,r){var n=et[e],a=Date.now();if(!n){for(var i in et)et[i].tsn.ts+t?o():n.timer=setTimeout(function(){o(),n.timer=null},t)},Ke.done=function(e){var t=et[e];return t&&t.timer?new Promise(function(e){var r=t.onDone;t.onDone=function(){r&&r(),e(),t.onDone=null}}):Promise.resolve()},Ke.clear=function(e){if(e)tt(et[e]),delete et[e];else for(var t in et)Ke.clear(t)};var rt=function(e,t){if(e>0)return Math.log(e)/Math.LN10;var n=Math.log(Math.min(t[0],t[1]))/Math.LN10;return r(n)||(n=Math.log(Math.max(t[0],t[1]))/Math.LN10-6),n},nt={},at=n.FP_SAFE,it=n.BADNUM,ot=nt={};ot.nestedProperty=X,ot.keyedContainer=function(e,t,r,n){var a,i;r=r||"name",n=n||"value";var o={};i=t&&t.length?X(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lat?it:r(e)?Number(e):it:it},ot.noop=A,ot.identity=function(e){return e},ot.swapAttrs=function(e,t,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(t,e)):Math.max(t,Math.min(r,e))},ot.bBoxIntersect=function(e,t,r){return r=r||0,e.left<=t.right+r&&t.left<=e.right+r&&e.top<=t.bottom+r&&t.top<=e.bottom+r},ot.simpleMap=function(e,t,r,n){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,r)?e(t,r,n):l},ot.OptionControl=function(e,t){e||(e={}),t||(t="opt");var r={optionList:[],_newoption:function(n){n[t]=e,r[n.name]=n,r.optionList.push(n)}};return r["_"+t]=e,r},ot.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var r,n,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(r=0;r=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[n];u[r]=i}return u},ot.syncOrAsync=function(e,t,r){var n;function a(){return ot.syncOrAsync(e,t,r)}for(;e.length;)if((n=(0,e.splice(0,1)[0])(t))&&n.then)return n.then(a).then(void 0,ot.promiseError);return r&&r(t)},ot.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},ot.noneOrAll=function(e,t,r){if(e){var n,a,i=!1,o=!0;for(n=0;n=0&&i%1==0){var p=a?a[h]:h,g=n?n[p]:p;f(g)&&(e[g].selected=1)}}},ot.getTargetArray=function(e,t){var r=t.target;if("string"==typeof r&&r){var n=ot.nestedProperty(e,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ot.minExtend=function(e,t){var r={};"object"!=typeof t&&(t={});var n,a,i,o=Object.keys(e);for(n=0;n1?a+o[1]:"";if(i&&(o.length>1||l.length>4||r))for(;n.test(l);)l=l.replace(n,"$1"+i+"$2");return l+s};var ct=/%{([^\s%{}]*)}/g,ut=/^\w*$/;ot.templateString=function(e,t){var r={};return e.replace(ct,function(e,n){return ut.test(n)?t[n]||"":(r[n]=r[n]||ot.nestedProperty(t,n).get,r[n]()||"")})};ot.subplotSort=function(e,t){for(var r=Math.min(e.length,t.length)+1,n=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(n=10*n+o-48),c&&(a=10*a+l-48),!s||!c){if(n!==a)return n-a;if(o!==l)return o-l}}return a-n};var ft=2e9;ot.seedPseudoRandom=function(){ft=2e9},ot.pseudoRandom=function(){var e=ft;return ft=(69069*ft+1)%4294967296,Math.abs(ft-e)<429496729?ot.pseudoRandom():ft/4294967296};var dt=te.counter,ht={idRegex:{x:dt("x"),y:dt("y")},attrRegex:dt("[xy]axis"),xAxisMatch:dt("xaxis"),yAxisMatch:dt("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}},pt={id2name:function(e){if("string"==typeof e&&e.match(ht.AX_ID_PATTERN)){var t=e.substr(1);return"1"===t&&(t=""),e.charAt(0)+"axis"+t}},name2id:function(e){if(e.match(ht.AX_NAME_PATTERN)){var t=e.substr(5);return"1"===t&&(t=""),e.charAt(0)+t}},cleanId:function(e,t){if(e.match(ht.AX_ID_PATTERN)&&(!t||e.charAt(0)===t)){var r=e.substr(1).replace(/^0+/,"");return"1"===r&&(r=""),e.charAt(0)+r}},list:function(e,t,r){var n=e._fullLayout;if(!n)return[];var a,i=pt.listIds(e,t),o=new Array(i.length);for(a=0;an?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},gt={dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},vt=gt.dash,yt=m.extendFlat,mt={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:O.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks+margins"},titlefont:L({editType:"ticks+margins"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}}],editType:"plot+margins",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks+margins",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks+margins"},tick0:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks+margins"},ticktext:{valType:"data_array",editType:"ticks+margins"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks+margins"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:O.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks+margins"},automargin:{valType:"boolean",dflt:!1,editType:"ticks+margins"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:yt({},vt,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:L({editType:"ticks+margins"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks+margins"},tickprefix:{valType:"string",dflt:"",editType:"ticks+margins"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},ticksuffix:{valType:"string",dflt:"",editType:"ticks+margins"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks+margins"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks+margins"},tickformat:{valType:"string",dflt:"",editType:"ticks+margins"},tickformatstops:{_isLinkedToArray:"tickformatstop",dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks+margins"},{valType:"any",editType:"ticks+margins"}],editType:"ticks+margins"},value:{valType:"string",dflt:"",editType:"ticks+margins"},editType:"ticks+margins"},hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:O.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:O.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:O.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot+margins"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot+margins"},overlaying:{valType:"enumerated",values:["free",ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot+margins"},{valType:"number",min:0,max:1,editType:"plot+margins"}],dflt:[0,1],editType:"plot+margins"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot+margins"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks+margins"}}},xt={},bt=xt={};bt.defaults=O.defaults;var _t=bt.defaultLine=O.defaultLine;bt.lightLine=O.lightLine;var wt=bt.background=O.background;function kt(e){if(r(e)||"string"!=typeof e)return e;var t=e.trim();if("rgb"!==t.substr(0,3))return e;var n=t.match(/^rgba?\s*\(([^()]*)\)$/);if(!n)return e;var a=n[1].trim().split(/\s*[\s,]\s*/),i="a"===t.charAt(3)&&4===a.length;if(!i&&3!==a.length)return e;for(var o=0;o=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}bt.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},bt.rgb=function(e){return bt.tinyRGB(s(e))},bt.opacity=function(e){return e?s(e).getAlpha():0},bt.addOpacity=function(e,t){var r=s(e).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+t+")"},bt.combine=function(e,t){var r=s(e).toRgb();if(1===r.a)return s(e).toRgbString();var n=s(t||wt).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},i={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return s(i).toRgbString()},bt.contrast=function(e,t,r){var n=s(e);return 1!==n.getAlpha()&&(n=s(bt.combine(e,wt))),(n.isDark()?t?n.lighten(t):wt:r?n.darken(r):_t).toString()},bt.stroke=function(e,t){var r=s(t);e.style({stroke:bt.tinyRGB(r),"stroke-opacity":r.getAlpha()})},bt.fill=function(e,t){var r=s(t);e.style({fill:bt.tinyRGB(r),"fill-opacity":r.getAlpha()})},bt.clean=function(e){if(e&&"object"==typeof e){var t,r,n,a,i=Object.keys(e);for(t=0;t0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],a=t.range[1];return.5*(n+a-3*i*Math.abs(n-a))}return zt}function l(e,n,a){var i=St(e,a||t.calendar);if(i===zt){if(!r(e))return zt;i=St(new Date(+e))}return i}function s(e,r,n){return Ct(e,r,n||t.calendar)}function c(e){return t._categories[Math.round(e)]}function u(e){if(t._categoriesMap){var n=t._categoriesMap[e];if(void 0!==n)return n}if(r(e))return+e}function f(n){return r(n)?e.round(t._b+t._m*n,2):zt}function d(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:Ot,t.l2c="log"===t.type?Dt:Ot,t.l2p=f,t.p2l=d,t.c2p="log"===t.type?function(e,t){return f(o(e,t))}:f,t.p2c="log"===t.type?function(e){return Dt(d(e))}:d,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Lt,t.c2d=t.c2r=t.l2d=t.l2r=Ot,t.d2p=t.r2p=function(e){return t.l2p(Lt(e))},t.p2d=t.p2r=d,t.cleanPos=Ot):"log"===t.type?(t.d2r=t.d2l=function(e,t){return o(Lt(e),t)},t.r2d=t.r2c=function(e){return Dt(Lt(e))},t.d2c=t.r2l=Lt,t.c2d=t.l2r=Ot,t.c2r=o,t.l2d=Dt,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(e){return Dt(d(e))},t.r2p=function(e){return t.l2p(Lt(e))},t.p2r=d,t.cleanPos=Ot):"date"===t.type?(t.d2r=t.r2d=nt.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,r,n){return t.l2p(l(e,0,n))},t.p2d=t.p2r=function(e,t,r){return s(d(e),t,r)},t.cleanPos=function(e){return nt.cleanDate(e,zt,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return zt},t.r2d=t.c2d=t.l2d=c,t.d2r=t.d2l_noadd=u,t.r2c=function(e){var r=u(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=Ot,t.r2l=u,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(e){return c(d(e))},t.r2p=t.d2p,t.p2r=d,t.cleanPos=function(e){return"string"==typeof e&&""!==e?e:Ot(e)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var i,o,l=nt.nestedProperty(t,e).get();if(o=(o="date"===t.type?nt.dfltRange(t.calendar):"y"===a?ht.DFLTRANGEY:n.dfltRange||ht.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=nt.cleanDate(l[0],zt,t.calendar),l[1]=nt.cleanDate(l[1],zt,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!nt.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=nt.constrain(t.r2l(l[0]),nt.MIN_MS+1e3,nt.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!r(l[i])){if(!r(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Pt?l[i]=-Pt:l[i]>Pt&&(l[i]=Pt),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else nt.nestedProperty(t,e).set(o)},t.setScale=function(e){var r=n._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=pt.getFromId({_fullLayout:n},t.overlaying);t.domain=i.domain}var o=e&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===a?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,a,i,o,l=t.type,s="date"===l&&e[r+"calendar"];if(r in e){if(n=e[r],o=e._length||n.length,nt.isTypedArray(n)&&("linear"===l||"log"===l)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(a=new Array(o),i=0;i=t.r2l(t.range[0])&&n<=t.r2l(t.range[1])},t.clearCalc=function(){t._min=[],t._max=[],t._categories=(t._initialCategories||[]).slice(),t._categoriesMap={};for(var e=0;e0?Number(s):l;else if("string"!=typeof s)t.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=r(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(t.dtick=l)}var f="date"===a?nt.dateTick0(t.calendar):0,d=n("tick0",f);"date"===a?t.tick0=nt.cleanDate(d,f):r(d)&&"D1"!==s&&"D2"!==s?t.tick0=Number(d):t.tick0=f}else{void 0===n("tickvals")?t.tickmode="auto":n("ticktext")}},jt=function(t,r,n,a,i){var o=a.letter,l=a.font||{},s=n("visible",!a.cheateronly),c=r.type;"date"===c&&D.getComponentMethod("calendars","handleDefaults")(t,r,"calendar",a.calendar);Et(r,i);var u=n("autorange",!r.isValidRange(t.range));if(r._rangesliderAutorange=!1,u&&n("rangemode"),n("range"),r.cleanRange(),function(e,t,r){if("category"===t.type){var n,a=e.categoryarray,i=Array.isArray(a)&&a.length>0;i&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),i||"array"!==o||(t.categoryorder="trace")}}(t,r,n),r._initialCategories="category"===c?function(t,r,n,a){switch(r){case"array":return Array.isArray(n)?n.slice():[];case"category ascending":return Tt(t,e.ascending,a);case"category descending":return Tt(t,e.descending,a);case"trace":default:return[]}}(o,r.categoryorder,r.categoryarray,a.data):[],"category"===c||a.noHover||n("hoverformat"),!s)return r;var f=n("color"),d=f===t.color?f:l.color;return n("title",i._dfltTitle[o]),nt.coerceFont(n,"titlefont",{family:l.family,size:Math.round(1.2*l.size),color:d}),Ft(t,r,n,c),Nt(t,r,n,c,a),It(t,r,n,a),function(e,t,r,n){var a=(n=n||{}).dfltColor;function i(r,a){return nt.coerce2(e,t,n.attributes,r,a)}var o=i("linecolor",a),l=i("linewidth");r("showline",n.showLine||!!o||!!l)||(delete t.linecolor,delete t.linewidth);var s=i("gridcolor",Mt(a,n.bgColor,n.blend||At).toRgbString()),c=i("gridwidth");if(r("showgrid",n.showGrid||!!s||!!c)||(delete t.gridcolor,delete t.gridwidth),!n.noZeroLine){var u=i("zerolinecolor",a),f=i("zerolinewidth");r("zeroline",n.showGrid||!!u||!!f)||(delete t.zerolinecolor,delete t.zerolinewidth)}}(t,r,n,{dfltColor:f,bgColor:a.bgColor,showGrid:a.showGrid,attributes:mt}),(r.showline||r.ticks)&&n("mirror"),a.automargin&&n("automargin"),r},Bt=pt.id2name,Ht=function(e,t,r,n,a){var i=a._axisConstraintGroups,o=t._id,l=o.charAt(0);if(!t.fixedrange&&(r("constrain"),nt.coerce(e,t,{constraintoward:{valType:"enumerated",values:"x"===l?["left","center","right"]:["bottom","middle","top"],dflt:"x"===l?"center":"middle"}},"constraintoward"),e.scaleanchor)){var s=function(e,t,r,n){var a,i,o,l,s=n[Bt(t)].type,c=[];for(i=0;ip[1]-.01&&(t.domain=o),nt.noneOrAll(e.domain,t.domain,o)}return n("layer"),t},Vt=n.BADNUM,Ut=function(e,t){return function(e,t){for(var n,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,t)?"date":function(e){for(var t,r=Math.max(1,(e.length-1)/1e3),n=0,a=0,i=0;i2*n}(e)?"category":function(e){if(!e)return!1;for(var t=0;t=0;a--,i++)t=e[a],n[i]=[1-t[0],t[1]];return n},Jt=function(e,t,r,n){var a,i;r?(a=nt.nestedProperty(e,r).get(),i=nt.nestedProperty(e._input,r).get()):(a=e,i=e._input);var o=n+"auto",l=n+"min",s=n+"max",u=a[o],f=a[l],d=a[s],h=a.colorscale;!1===u&&void 0!==f||(f=nt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=nt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[s]=d,i[l]=f,i[s]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?c.RdBu:f>=0?c.Reds:c.Blues,i.colorscale=h,a.reversescale&&(h=Qt(h)),a.colorscale=h)},$t=nt.extendFlat,Kt=nt.isPlainObject,er={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},tr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},rr=er.flags.slice().concat(["clearCalc","fullReplot"]),nr=tr.flags.slice().concat("layoutReplot"),ar={traces:er,layout:tr,traceFlags:function(){return ir(rr)},layoutFlags:function(){return ir(nr)},update:function(e,t){var r=t.editType;if(r&&"none"!==r)for(var n=r.split("+"),a=0;a","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},mr={},xr=vr.LINE_SPACING;function br(e,t){return e.node().getBoundingClientRect()[t]}var _r=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;mr.convertToTspans=function(r,n,a){var i=r.text(),o=!r.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(_r),l=e.select(r.node().parentNode);if(!l.empty()){var s=r.attr("class")?r.attr("class").split(" ")[0]:"text";return s+="-math",l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove(),r.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(n&&n._promises||[]).push(new Promise(function(t){r.style("display","none");var n=parseInt(r.node().style.fontSize,10),u={fontSize:n};!function(t,r,n){var a="math-output-"+nt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=t,o.replace(wr,"\\lt ").replace(kr,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var r=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())nt.log("There was an error in the tex syntax.",t),n();else{var a=i.select("svg").node().getBoundingClientRect();n(i.select(".MathJax_SVG"),r,a)}i.remove()})}(o[2],u,function(e,o,u){l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return c(),void t();var d=l.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});d.node().appendChild(f.node()),o&&o.node()&&f.node().insertBefore(o.node().cloneNode(!0),f.node().firstChild),f.attr({class:s,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=r.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=br(f,"width"),g=br(f,"height"),v=+r.attr("x")-p*{start:0,middle:.5,end:1}[r.attr("text-anchor")||"start"],y=-(n||br(r,"height"))/4;"y"===s[0]?(d.attr({transform:"rotate("+[-90,+r.attr("x"),+r.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+r.attr("x"),y:+r.attr("y")})):"l"===s[0]?f.attr({x:r.attr("x"),y:y-g/2}):"a"===s[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+r.attr("y")+y-g/2}),a&&a.call(r,d),t(d)})})):c(),r}function c(){l.empty()||(s=r.attr("class")+"-math",l.select("svg."+s).remove()),r.text("").style("white-space","pre"),function(r,n){n=(a=n,function(e,t){if(!e)return"";for(var r=0;r1)for(var o=1;o doesnt match end tag <"+e+">. Pretending it did match.",n),i=l[l.length-1].node}else nt.log("Ignoring unexpected end tag .",n)}Er.test(n)?c():(i=r,l=[{node:r}]);for(var h=n.split(zr),p=0;p|>|>)/g;var Mr={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"},Ar={sub:"0.3em",sup:"-0.6em"},Tr={sub:"-0.21em",sup:"0.42em"},Lr="\u200b",Cr=["http:","https:","mailto:","",void 0,":"],Sr=new RegExp("]*)?/?>","g"),Or=Object.keys(yr.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:yr.entityToUnicode[e]}}),Pr=/(\r\n?|\n)/g,zr=/(<[^<>]*>)/,Dr=/<(\/?)([^ >]*)(\s+(.*))?>/i,Er=//i,Nr=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Ir=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Rr=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Fr=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function jr(e,t){if(!e)return null;var r=e.match(t);return r&&(r[3]||r[4])}var Br=/(^|;)\s*color:/;function Hr(e,t,r){var n,a,i,o=r.horizontalAlign,l=r.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-n.height}:"middle"===l?function(){return s.top+(s.height-n.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-n.width}:"center"===o?function(){return s.left+(s.width-n.width)/2}:function(){return s.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}mr.plainText=function(e){return(e||"").replace(Sr," ")},mr.lineCount=function(e){return e.selectAll("tspan.line").size()||1},mr.positionText=function(t,r,n){return t.each(function(){var t=e.select(this);function a(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var i=a("x",r),o=a("y",n);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},mr.makeEditable=function(t,r){var n=r.gd,a=r.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(n).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:r.fill||c.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||t.attr("data-unformatted")).call(Hr(t,a,r)).on("blur",function(){n._editing=!1,t.text(this.textContent).style({opacity:1});var r,a=e.select(this).attr("class");(r=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(r).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;n._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(n._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Hr(t,a,r)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),r=document.createRange();r.selectNodeContents(t);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),t.focus()}return r.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var qr=function(e){var t=e.marker,n=t.sizeref||1,a=t.sizemin||0,i="area"===t.sizemode?function(e){return Math.sqrt(e/n)}:function(e){return e/n};return function(e){var t=i(e/2);return r(t)&&t>0?Math.max(t,a):0}},Vr={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("markers")},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return nt.isPlainObject(e.marker)&&nt.isArrayOrTypedArray(e.marker.size)}},Ur={},Gr=vr.LINE_SPACING,Yr=h.DESELECTDIM,Xr=Ur={};Xr.font=function(e,t,r,n){nt.isPlainObject(t)&&(n=t.color,r=t.size,t=t.family),t&&e.style("font-family",t),r+1&&e.style("font-size",r+"px"),n&&e.call(xt.fill,n)},Xr.setPosition=function(e,t,r){e.attr("x",t).attr("y",r)},Xr.setSize=function(e,t,r){e.attr("width",t).attr("height",r)},Xr.setRect=function(e,t,r,n,a){e.call(Xr.setPosition,t,r).call(Xr.setSize,n,a)},Xr.translatePoint=function(e,t,n,a){var i=n.c2p(e.x),o=a.c2p(e.y);return!!(r(i)&&r(o)&&t.node())&&("text"===t.node().nodeName?t.attr("x",i).attr("y",o):t.attr("transform","translate("+i+","+o+")"),!0)},Xr.translatePoints=function(t,r,n){t.each(function(t){var a=e.select(this);Xr.translatePoint(t,a,r,n)})},Xr.hideOutsideRangePoint=function(e,t,r,n,a,i){t.attr("display",r.isPtWithinRange(e,a)&&n.isPtWithinRange(e,i)?null:"none")},Xr.hideOutsideRangePoints=function(t,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var a=r.xaxis,i=r.yaxis;t.each(function(r){var o=r[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(n).each(function(t){Xr.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Xr.crispRound=function(e,t,n){return t&&r(t)?e._context.staticPlot?t:t<1?1:Math.round(t):n||0},Xr.singleLineStyle=function(e,t,r,n,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";xt.stroke(t,n||i.color),Xr.dashLine(t,l,o)},Xr.lineGroupStyle=function(t,r,n,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";e.select(this).call(xt.stroke,n||i.color).call(Xr.dashLine,l,o)})},Xr.dashLine=function(e,t,r){r=+r||0,t=Xr.dashStyle(t,r),e.style({"stroke-dasharray":t,"stroke-width":r+"px"})},Xr.dashStyle=function(e,t){t=+t||1;var r=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=r+"px,"+r+"px":"dash"===e?e=3*r+"px,"+3*r+"px":"longdash"===e?e=5*r+"px,"+5*r+"px":"dashdot"===e?e=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===e&&(e=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),e},Xr.singleFillStyle=function(t){var r=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&t.call(xt.fill,r)},Xr.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(r){var n=e.select(this);try{n.call(xt.fill,r[0].trace.fillcolor)}catch(e){nt.error(e,t),n.remove()}})},Xr.symbolNames=[],Xr.symbolFuncs=[],Xr.symbolNeedLines={},Xr.symbolNoDot={},Xr.symbolNoFill={},Xr.symbolList=[],Object.keys(gr).forEach(function(e){var t=gr[e];Xr.symbolList=Xr.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Xr.symbolNames[t.n]=e,Xr.symbolFuncs[t.n]=t.f,t.needLine&&(Xr.symbolNeedLines[t.n]=!0),t.noDot?Xr.symbolNoDot[t.n]=!0:Xr.symbolList=Xr.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Xr.symbolNoFill[t.n]=!0)});var Zr=Xr.symbolNames.length,Wr="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Qr(e,t){var r=e%100;return Xr.symbolFuncs[r](t)+(e>=200?Wr:"")}Xr.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Xr.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Zr||e>=400?0:Math.floor(Math.max(e,0))};var Jr={x1:1,x2:0,y1:0,y2:0},$r={x1:0,x2:0,y1:1,y2:0};Xr.gradient=function(t,r,n,a,i,o){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([a+i+o],nt.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jr):"vertical"===a&&t.attr($r),t.attr("id",n);var r=s(i),l=s(o);t.append("stop").attr({offset:"0%","stop-color":xt.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":xt.tinyRGB(r),"stop-opacity":r.getAlpha()})}),t.style({fill:"url(#"+n+")","fill-opacity":null})},Xr.initGradients=function(e){var t=e._fullLayout._defs.selectAll(".gradients").data([0]);t.enter().append("g").classed("gradients",!0),t.selectAll("linearGradient,radialGradient").remove()},Xr.singlePointStyle=function(e,t,r,n,a,i){var o=r.marker;!function(e,t,r,n,a,i,o,l){if(D.traceIs(r,"symbols")){var s=qr(r);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Vr.isBubble(r)?s(e.ms):(i.size||6)/2,e.mrc=t;var n=Xr.symbolNumber(e.mx||i.symbol)||0;return e.om=n%200>=100,Qr(n,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):nt.isArrayOrTypedArray(o.color)?xt.defaultLine:o.color,nt.isArrayOrTypedArray(i.color)&&(c=xt.defaultLine,d=!0),c="mc"in e?e.mcc=n(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(xt.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+r.uid;d&&(v+="-"+e.i),t.call(Xr.gradient,l,v,p,c,g)}else t.call(xt.fill,c);f&&t.call(xt.stroke,u)}}(e,t,r,n,a,o,o.line,i)},Xr.pointStyle=function(t,r,n){if(t.size()){var a=r.marker,i=Xr.tryColorscale(a,""),o=Xr.tryColorscale(a,"line");t.each(function(t){Xr.singlePointStyle(t,e.select(this),r,i,o,n)})}},Xr.makeSelectedPointStyleFns=function(e){var t={},r=e.selected||{},n=e.unselected||{},a=e.marker||{},i=r.marker||{},o=n.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,r=void 0!==t;if(r||u||f){if(!e.selected)return f?c:Yr*(r?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Xr.selectedPointStyle=function(t,r){if(t.size()&&r.selectedpoints){var n=Xr.makeSelectedPointStyleFns(r),a=r.marker||{};t.each(function(t){var r=e.select(this),a=n.opacityFn(t);void 0!==a&&r.style("opacity",a)}),n.colorFn&&t.each(function(t){var r=e.select(this),a=n.colorFn(t);a&&xt.fill(r,a)}),D.traceIs(r,"symbols")&&n.sizeFn&&t.each(function(t){var r=e.select(this),i=t.mx||a.symbol||0,o=n.sizeFn(t);r.attr("d",Qr(Xr.symbolNumber(i),o)),t.mrc2=o})}},Xr.tryColorscale=function(e,t){var r=t?nt.nestedProperty(e,t).get():e,n=r.colorscale,a=r.color;return n&&nt.isArrayOrTypedArray(a)?pr.makeColorScaleFunc(pr.extractScale(n,r.cmin,r.cmax)):nt.identity};var Kr={start:1,end:-1,middle:0,bottom:1,top:-1};function en(t,r,n,a){var i=e.select(t.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",l=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(mr.lineCount(t)-1)*Gr+1,u=Kr[l]*s,f=.75*n+Kr[o]*s+(Kr[o]-1)*c*n/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function tn(e,t){var n=e.ts||t.textfont.size;return r(n)&&n>0?n:0}Xr.textPointStyle=function(t,r,n){t.each(function(t){var a=e.select(this),i=nt.extractOption(t,r,"tx","text");if(i){var o=t.tp||r.textposition,l=tn(t,r);a.call(Xr.font,t.tf||r.textfont.family,l,t.tc||r.textfont.color).text(i).call(mr.convertToTspans,n).call(en,o,l,t.mrc)}else a.remove()})},Xr.selectedTextStyle=function(t,r){if(t.size()&&r.selectedpoints){var n=r.selected||{},a=r.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||r.textfont.color,s=t.tp||r.textposition,c=tn(t,r),u=(n.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=xt.addOpacity(l,Yr)),i&&xt.fill(o,i),en(o,s,c,t.mrc2||t.mrc)})}};var rn=.5;function nn(t,r,n,a){var i=t[0]-r[0],o=t[1]-r[1],l=n[0]-r[0],s=n[1]-r[1],c=Math.pow(i*i+o*o,rn/2),u=Math.pow(l*l+s*s,rn/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(r[0]+(h&&f/h),2),e.round(r[1]+(h&&d/h),2)],[e.round(r[0]-(p&&f/p),2),e.round(r[1]-(p&&d/p),2)]]}Xr.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var r,n="M"+e[0],a=[];for(r=1;r=1e4&&(Xr.savedBBoxes={},ln=0),n&&(Xr.savedBBoxes[n]=p),ln++,nt.extendFlat({},p)},Xr.setClipUrl=function(t,r){if(r){var n="#"+r,a=e.select("base");a.size()&&a.attr("href")&&(n=window.location.href.split("#")[0]+n),t.attr("clip-path","url("+n+")")}else t.attr("clip-path",null)},Xr.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,r){return[t,r].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Xr.setTranslate=function(e,t,r){var n=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[n]("transform")||"";return t=t||0,r=r||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+r+")").trim(),e[a]("transform",i),i},Xr.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,r){return[t,r].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Xr.setScale=function(e,t,r){var n=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[n]("transform")||"";return t=t||1,r=r||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+r+")").trim(),e[a]("transform",i),i},Xr.setPointGroupScale=function(e,t,r){var n,a,i;return t=t||1,r=r||1,a=1===t&&1===r?"":" scale("+t+","+r+")",i=/\s*sc.*/,e.each(function(){n=(this.getAttribute("transform")||"").replace(i,""),n=(n+=a).trim(),this.setAttribute("transform",n)}),a};var cn=/translate\([^)]*\)\s*$/;Xr.setTextPointsScale=function(t,r,n){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(cn);t=1===r&&1===n?[]:["translate("+o+","+l+")","scale("+r+","+n+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var un={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500},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"]}}},fn={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}},dn=m.extendFlat,hn=function(e,t,r){return{color:{valType:"color",arrayOk:!0,editType:t||"style"},colorscale:dn({},Wt.colorscale,{}),cauto:dn({},Wt.zauto,{impliedEdits:{cmin:void 0,cmax:void 0}}),cmax:dn({},Wt.zmax,{editType:t||Wt.zmax.editType,impliedEdits:{cauto:!1}}),cmin:dn({},Wt.zmin,{editType:t||Wt.zmin.editType,impliedEdits:{cauto:!1}}),autocolorscale:dn({},Wt.autocolorscale,{dflt:!1===r?r:Wt.autocolorscale.dflt}),reversescale:dn({},Wt.reversescale,{})}},pn={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20},gn=gt.dash,vn=m.extendFlat,yn={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:vn({},gn,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:vn({symbol:{valType:"enumerated",values:Ur.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},showscale:{valType:"boolean",dflt:!1,editType:"calc"},colorbar:cr,line:vn({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},hn()),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},hn()),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:L({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}},mn=yn.marker,xn={r:yn.r,t:yn.t,marker:{color:mn.color,size:mn.size,symbol:mn.symbol,opacity:mn.opacity,editType:"calc"}},bn=m.extendFlat,_n=ar.overrideAll,wn=bn({},mt.domain,{});function kn(e,t){return bn({},t,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}var Mn=_n({radialaxis:kn(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:wn,orientation:{valType:"number"}}),angularaxis:kn(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:wn}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested"),An={},Tn=nt.extendFlat,Ln=nt.extendDeepAll,Cn="_isSubplotObj",Sn="_isLinkedToArray",On=[Cn,Sn,"_arrayAttrRegexps","_deprecated"];function Pn(e,t,r){if(!e)return!1;if(e._isLinkedToArray)if(zn(t[r]))r++;else if(r=i.length)return!1;if(2===e.dimensions){if(r++,t.length===r)return e;var o=t[r];if(!zn(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function zn(e){return e===Math.round(e)&&e>=0}function Dn(e){return function(e){An.crawl(e,function(e,t,r){An.isValObject(e)?"data_array"===e.valType?(e.role="data",r[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(r[t+"src"]={valType:"string",editType:"none"}):nt.isPlainObject(e)&&(e.role="object")})}(e),function(e){An.crawl(e,function(e,t,r){if(!e)return;var n=e[Sn];if(!n)return;delete e[Sn],r[t]={items:{}},r[t].items[n]=e,r[t].role="object"})}(e),e}function En(e,t,r){var n=nt.nestedProperty(e,r),a=Ln({},t.layoutAttributes);a[Cn]=!0,n.set(a)}function Nn(e,t,r){var n=nt.nestedProperty(e,r);n.set(Ln(n.get()||{},t))}An.IS_SUBPLOT_OBJ=Cn,An.IS_LINKED_TO_ARRAY=Sn,An.DEPRECATED="_deprecated",An.UNDERSCORE_ATTRS=On,An.get=function(){var e={};D.allTypes.concat("area").forEach(function(t){e[t]=function(e){var t,r;"area"===e?(t={attributes:xn},r={}):(t=D.modules[e]._module,r=t.basePlotModule);var n={type:null};Ln(n,S),Ln(n,t.attributes),r.attributes&&Ln(n,r.attributes);n.type=e;var a={meta:t.meta||{},attributes:Dn(n)};if(t.layoutAttributes){var i={};Ln(i,t.layoutAttributes),a.layoutAttributes=Dn(i)}return a}(t)});var t,r={};return Object.keys(D.transformsRegistry).forEach(function(e){r[e]=function(e){var t=D.transformsRegistry[e],r=Ln({},t.attributes);return Object.keys(D.componentsRegistry).forEach(function(t){var n=D.componentsRegistry[t];n.schema&&n.schema.transforms&&n.schema.transforms[e]&&Object.keys(n.schema.transforms[e]).forEach(function(t){Nn(r,n.schema.transforms[e][t],t)})}),{attributes:Dn(r)}}(e)}),{defs:{valObjects:nt.valObjectMeta,metaKeys:On.concat(["description","role","editType","impliedEdits"]),editType:{traces:ar.traces,layout:ar.layout},impliedEdits:{}},traces:e,layout:function(){var e,t,r={};for(e in Ln(r,z),D.subplotsRegistry)if((t=D.subplotsRegistry[e]).layoutAttributes)if("cartesian"===t.name)En(r,t,"xaxis"),En(r,t,"yaxis");else{var n="subplot"===t.attr?t.name:t.attr;En(r,t,n)}for(e in r=function(e){return Tn(e,{radialaxis:Mn.radialaxis,angularaxis:Mn.angularaxis}),Tn(e,Mn.layout),e}(r),D.componentsRegistry){var a=(t=D.componentsRegistry[e]).schema;if(a&&(a.subplots||a.layout)){var i=a.subplots;if(i&&i.xaxis&&!i.yaxis)for(var o in i.xaxis)delete r.yaxis[o]}else t.layoutAttributes&&Nn(r,t.layoutAttributes,t.name)}return{layoutAttributes:Dn(r)}}(),transforms:r,frames:(t={frames:nt.extendDeepAll({},fn)},Dn(t),t.frames),animation:Dn(un)}},An.crawl=function(e,t,r,n){var a=r||0;n=n||"",Object.keys(e).forEach(function(r){var i=e[r];if(-1===On.indexOf(r)){var o=(n?n+".":"")+r;t(i,r,e,a,o),An.isValObject(i)||nt.isPlainObject(i)&&"impliedEdits"!==r&&An.crawl(i,t,a+1,o)}})},An.isValObject=function(e){return e&&void 0!==e.valType},An.findArrayAttributes=function(e){var t=[],r=[];function n(n,a,i,o){if(r=r.slice(0,o).concat([a]),n&&("data_array"===n.valType||!0===n.arrayOk)&&!("colorbar"===r[o-1]&&("ticktext"===a||"tickvals"===a))){var l=function(e){return e.join(".")}(r),s=nt.nestedProperty(e,l).get();nt.isArrayOrTypedArray(s)&&t.push(l)}}if(An.crawl(S,n),e._module&&e._module.attributes&&An.crawl(e._module.attributes,n),e.transforms)for(var a=e.transforms,i=0;i=e.transforms.length)return!1;n=(r=(D.transformsRegistry[e.transforms[o].type]||{}).attributes)&&r[t[2]],i=3}else if("area"===e.type)n=xn[a];else{var l=e._module;if(l||(l=(D.modules[e.type||S.type.dflt]||{})._module),!l)return!1;if(!(n=(r=l.attributes)&&r[a])){var s=l.basePlotModule;s&&s.attributes&&(n=s.attributes[a])}n||(n=S[a])}return Pn(n,t,i)},An.getLayoutValObject=function(e,t){return Pn(function(e,t){var r,n,a,i,o=e._basePlotModules;if(o){var l;for(r=0;r0?".":"")+a;nt.isPlainObject(i)?Bn(i,t,o,n+1):t(o,a,i)}})}In.manageCommandObserver=function(e,t,r,n){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=In.hasSimpleAPICommandBindings(e,r,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Rn(e,o,a.cache),a.check=function(){if(i){var t=Rn(e,o,a.cache);return t.changed&&n&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(n({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=r.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=r._paper.attr("width")-7),n.attr(i);var o=n.select(".js-link-to-tool"),l=n.select(".js-link-spacer"),s=n.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var r=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)r.on("click",function(){Un.sendDataToCloud(e)});else{var n=window.location.pathname.split("/"),a=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},Un.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=Un.graphJson(t,!1,"keepdata"),a.node().submit(),n.remove(),t.emit("plotly_afterexport"),!1};var Xn,Zn=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Wn=["year","month","dayMonth","dayMonthYear"];function Qn(e,t){var r,n,a=e.trace,i=a._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},Un.cleanPlot=function(e,t,r,n){var a,i,o=n._basePlotModules||[];for(a=0;a0){var c=function(e){var t,r={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(r.left+=e[t].left||0,r.right+=e[t].right||0,r.bottom+=e[t].bottom||0,r.top+=e[t].top||0);return r}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||n.width,i=parseFloat(p.height)||n.height}var g=Un.layoutAttributes.width.min,v=Un.layoutAttributes.height.min;a1,m=!t.height&&Math.abs(n.height-i)>1;(m||y)&&(y&&(n.width=a),m&&(n.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),Un.sanitizeMargins(n)},Un.supplyLayoutModuleDefaults=function(e,t,r,n){var a,i,o,l=D.componentsRegistry,s=t._basePlotModules,c=D.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(D.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(nt.subplotSort);for(i=0;i.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[t]={l:{val:r.x,size:r.l+a},r:{val:r.x,size:r.r+a},b:{val:r.y,size:r.b+a},t:{val:r.y,size:r.t+a}}}else delete n._pushmargin[t];n._replotting||Un.doAutoMargin(e)}},Un.doAutoMargin=function(e){var t=e._fullLayout;t._size||(t._size={}),t._pushmargin||(t._pushmargin={});var n=t._size,a=JSON.stringify(n),i=Math.max(t.margin.l||0,0),o=Math.max(t.margin.r||0,0),l=Math.max(t.margin.t||0,0),s=Math.max(t.margin.b||0,0),c=t._pushmargin;if(!1!==t.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(r(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-t.width)*h)/(m-h),_=(x*(1-h)+(p-t.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(r(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-t.height)*g)/(w-g),A=(k*(1-g)+(v-t.height)*(1-w))/(w-g);M>=0&&A>=0&&M+A>s+l&&(s=M,l=A)}}}}if(n.l=Math.round(i),n.r=Math.round(o),n.t=Math.round(l),n.b=Math.round(s),n.p=Math.round(t.margin.pad),n.w=Math.round(t.width)-n.l-n.r,n.h=Math.round(t.height)-n.t-n.b,!t._replotting&&"{}"!==a&&a!==JSON.stringify(t._size))return D.call("plot",e)},Un.graphJson=function(e,t,r,n,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&Un.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(nt.isPlainObject(e)){var t,n,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===r){if("src"===t.substr(t.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=e[t+"src"])&&n.indexOf(":")>0&&!nt.isPlainObject(e.stream))continue}else if("keepall"!==r&&"string"==typeof(n=e[t+"src"])&&n.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):nt.isJSDate(e)?nt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var r=s(e);return t&&delete r.fit,r})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===n?c:JSON.stringify(c)},Un.modifyFrames=function(e,t){var r,n,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(r=0;r0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return D.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var n,o,l=0,s=0;function c(){return l++,function(){var r;f||++s!==l||(r=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return D.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(r)))}}var d=e._fullLayout._basePlotModules,h=!1;if(r)for(o=0;o=0;i--)if(g[i].enabled){r._indexToPoints=g[i]._indexToPoints;break}n&&n.calc&&(p=n.calc(e,r))}Array.isArray(p)&&p[0]||(p=[{x:Vn,y:Vn}]),p[0].t||(p[0].t={}),p[0].trace=r,c[a]=p}D.getComponentMethod("fx","calc")(e)},Un.rehover=function(e){e._fullLayout._rehover&&e._fullLayout._rehover()},Un.generalUpdatePerTraceModule=function(e,t,r,n){var a,i=t.traceHash,o={};for(a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];n.attr("transform","translate("+p+")")}}}A.call(T),k&&(w?A.on(".opacity",null):(b=0,_=!0,A.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),A.call(mr.makeEditable,{gd:t}).on("edit",function(e){void 0!==c?D.call("restyle",t,l,e,c):D.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(T)}).on("input",function(e){this.text(e||" ").call(mr.positionText,f.x,f.y)}));return A.classed("js-placeholder",_),p}},ta=/ [XY][0-9]* /;var ra=n.FP_SAFE,na=la,aa=sa,ia=function(e){e._length||e.setScale();var t,r=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&r&&(e.range=la(e),e._r=e.range.slice(),e._rl=nt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var n=e._anchorAxis.rangeslider[e._name];n&&"auto"===n.rangemode&&(n.range=r?la(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=nt.extendFlat({},n)}},oa=function(e,t,n){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!t)return;e._min||(e._min=[]);e._max||(e._max=[]);n||(n={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=t.length,y=n.padded||!1,m=n.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),k=_((e._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),M=_(n.vpadplus||n.vpad),A=_(n.vpadminus||n.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-ra&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var T=m&&0===a;v.push({val:a,pad:T?0:b,extrapad:!T&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)T(a)};function la(e){var t,r,n,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=sa(e);for(t=1;t0&&l>0&&s/l>d&&(i=n,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),nt.simpleMap(c,e.l2r||Number)}function sa(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function ca(e){return r(e)&&Math.abs(e)=t}var da={},ha=n.ONEAVGYEAR,pa=n.ONEAVGMONTH,ga=n.ONEDAY,va=n.ONEHOUR,ya=n.ONEMIN,ma=n.ONESEC,xa=n.MINUS_SIGN,ba=n.BADNUM,_a=vr.MID_SHIFT,wa=vr.LINE_SPACING,ka=da={};ka.setConvert=Et,ka.id2name=pt.id2name,ka.name2id=pt.name2id,ka.cleanId=pt.cleanId,ka.list=pt.list,ka.listIds=pt.listIds,ka.getFromId=pt.getFromId,ka.getFromTrace=pt.getFromTrace,ka.expand=oa,ka.getAutoRange=na,ka.coerceRef=function(e,t,r,n,a,i){var o=n.charAt(n.length-1),l=r._fullLayout._subplots[o+"axis"],s=n+"ref",c={};return a||(a=l[0]||i),i||(i=a),c[s]={valType:"enumerated",values:l.concat(i?[i]:[]),dflt:a},nt.coerce(e,t,c,s)},ka.coercePosition=function(e,t,r,n,a,i){var o,l;if("paper"===n||"pixel"===n)o=nt.ensureNumber,l=r(a,i);else{var s=ka.getFromId(t,n);l=r(a,i=s.fraction2r(i)),o=s.cleanPos}e[a]=o(l)},ka.cleanPosition=function(e,t,r){return("paper"===r||"pixel"===r?nt.ensureNumber:ka.getFromId(t,r).cleanPos)(e)};var Ma=ka.getDataConversions=function(e,t,r,n){var a,i="x"===r||"y"===r||"z"===r?r:n;if(Array.isArray(i)){if(a={type:Ut(n),_categories:[]},ka.setConvert(a),"category"===a.type)for(var o=0;o2e-6||((r-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},ka.saveRangeInitial=function(e,t){for(var r=ka.list(e,"",!0),n=!1,a=0;a.3*d||u(a)||u(i))){var h=n.dtick/2;e+=e+h.8){var o=Number(r.substr(1));i.exactYears>.8&&o%12==0?e=ka.tickIncrement(e,"M6","reverse")+1.5*ga:i.exactMonths>.8?e=ka.tickIncrement(e,"M1","reverse")+15.5*ga:e-=ga/2;var l=ka.tickIncrement(e,r);if(l<=n)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=ka.tickIncrement(h,l.dtick,!1,i),0;return{start:t.c2r(p,0,i),end:t.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},ka.prepTicks=function(e){var t=nt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var r,n=e.nticks;n||("category"===e.type?(r=e.tickfont?1.2*(e.tickfont.size||12):15,n=e._length/r):(r="y"===e._id.charAt(0)?40:80,n=nt.constrain(e._length/r,4,9)+1),"radialaxis"===e._name&&(n*=2)),"array"===e.tickmode&&(n*=100),ka.autoTicks(e,Math.abs(t[1]-t[0])/n),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),Na(e)},ka.calcTicks=function(e){ka.prepTicks(e);var t=nt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,r,n=e.tickvals,a=e.ticktext,i=new Array(n.length),o=nt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(r=0;rc&&t=n:s<=n)&&!(i.length>l||s===o);s=ka.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+t.substr(1)%12==0?"y":"m";else if(t>=ga&&i<=10||t>=15*ga)e._tickround="d";else if(t>=ya&&i<=16||t>=va)e._tickround="M";else if(t>=ma&&i<=19||t>=ya)e._tickround="S";else{var o=e.l2r(n+t).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(r(t)||"L"===t.charAt(0)){var l=e.range.map(e.r2d||Number);r(t)||(t=Number(t.substr(1))),e._tickround=2-Math.floor(Math.log(t)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(Fa(e.exponentformat)&&!ja(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function Ia(e,t,r){var n=e.tickfont||{};return{x:t,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}ka.autoTicks=function(e,t){var n;function a(e){return Math.pow(e,Math.floor(Math.log(t)/Math.LN10))}if("date"===e.type){e.tick0=nt.dateTick0(e.calendar);var i=2*t;i>ha?(t/=ha,n=a(10),e.dtick="M"+12*Ea(t,n,La)):i>pa?(t/=pa,e.dtick="M"+Ea(t,1,Ca)):i>ga?(e.dtick=Ea(t,ga,Oa),e.tick0=nt.dateTick0(e.calendar,!0)):i>va?e.dtick=Ea(t,va,Ca):i>ya?e.dtick=Ea(t,ya,Sa):i>ma?e.dtick=Ea(t,ma,Sa):(n=a(10),e.dtick=Ea(t,n,La))}else if("log"===e.type){e.tick0=0;var o=nt.simpleMap(e.range,e.r2l);if(t>.7)e.dtick=Math.ceil(t);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/t);t=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,n=a(10),e.dtick="L"+Ea(t,n,La)}else e.dtick=t>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(t,1))):"angular"===e._id?(e.tick0=0,n=1,e.dtick=Ea(t,n,Da)):(e.tick0=0,n=a(10),e.dtick=Ea(t,n,La));if(0===e.dtick&&(e.dtick=1),!r(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},ka.tickIncrement=function(t,n,a,i){var o=a?-1:1;if(r(n))return t+o*n;var l=n.charAt(0),s=o*Number(n.substr(1));if("M"===l)return nt.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var c="D2"===n?za:Pa,u=t+.01*o,f=nt.roundUp(nt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(n)},ka.tickFirst=function(t){var n=t.r2l||Number,a=nt.simpleMap(t.range,n),i=a[1]"+l,e._prevDateHead=l));t.text=s}(e,o,n,s):"log"===e.type?function(e,t,n,a,i){var o=e.dtick,l=t.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))t.text=Ba(Math.pow(10,l),e,i,a);else if(r(o)||"D"===o.charAt(0)&&nt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||Fa(e.exponentformat)&&ja(c)?(t.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+xa+-c+"",t.fontSize*=1.25):(t.text=Ba(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(t.dy-=t.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);t.text=String(Math.round(Math.pow(10,nt.mod(l,1)))),t.fontSize*=.75}if("D1"===e.dtick){var u=String(t.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?t.dx-=t.fontSize/4:(t.dy+=t.fontSize/2,t.dx+=(e.range[1]>e.range[0]?1:-1)*t.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var r=e._categories[Math.round(t.x)];void 0===r&&(r="");t.text=String(r)}(e,o):"angular"===e._id?function(e,t,r,n,a){if("radians"!==e.thetaunit||r)t.text=Ba(t.x,e,a,n);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var r=function(e){var r=1;for(;!t(Math.round(e*r)/r,e);)r*=10;return r}(e),n=e*r,a=Math.abs(function e(r,n){return t(n,0)?r:e(n,r%n)}(n,r));return[Math.round(n/a),Math.round(r/a)]}(i);if(o[1]>=100)t.text=Ba(nt.deg2rad(t.x),e,a,n);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=xa+t.text)}}}}(e,o,n,s,a):function(e,t,r,n,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=Ba(t.x,e,a,n)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},ka.hoverLabelText=function(e,t,r){if(r!==ba&&r!==t)return ka.hoverLabelText(e,t)+" - "+ka.hoverLabelText(e,r);var n="log"===e.type&&t<=0,a=ka.tickText(e,e.c2l(n?-t:t),"hover").text;return n?0===t?"0":xa+a:a};var Ra=["f","p","n","\u03bc","m","","k","M","G","T"];function Fa(e){return"SI"===e||"B"===e}function ja(e){return e>14||e<-15}function Ba(e,t,n,a){var i=e<0,o=t._tickround,l=n||t.exponentformat||"B",s=t._tickexponent,c=ka.getTickFormat(t),u=t.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===t.showexponent?t.dtick:r(e)&&Math.abs(e)||1,range:"none"===t.showexponent?t.range.map(t.r2d):[0,e||1]};Na(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,t.hoverformat&&(c=t.hoverformat)}if(c)return t._numFormat(c)(e).replace(/-/g,xa);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":Fa(l)&&(e+=Ra[s/3+5]));return i?xa+e:e}function Ha(e,t){for(var r=0;r=0,i=c(e,t[1])<=0;return(r||a)&&(n||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(n))){r=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(n=1;n rect").call(Ur.setTranslate,0,0).call(Ur.setScale,1,1),e.plot.call(Ur.setTranslate,t._offset,r._offset).call(Ur.setScale,1,1);var n=e.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(Ur.setPointGroupScale,1,1),n.selectAll(".textpoint").call(Ur.setTextPointsScale,1,1),n.call(Ur.hideOutsideRangePoints,e)}function g(e,r){var n,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(n=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-r)+r*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],c[2]=e.xaxis._length*(1-r+r*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(n=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-r)+r*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],c[3]=e.yaxis._length*(1-r+r*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,r){var n,a=[];for(a=[e._id,r._id],n=0;n rect").call(Ur.setTranslate,_,w).call(Ur.setScale,1/x,1/b),e.plot.call(Ur.setTranslate,A,T).call(Ur.setScale,x,b).selectAll(".points").selectAll(".point").call(Ur.setPointGroupScale,1/x,1/b),e.plot.selectAll(".points").selectAll(".textpoint").call(Ur.setTextPointsScale,1/x,1/b)}a&&(l=a());var v=e.ease(n.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(u),u=null,function(){for(var e={},r=0;rn.duration?(function(){for(var e={},r=0;r0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},vi.prototype.on=vi.prototype.addListener,vi.prototype.once=function(e,t){if(!mi(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},vi.prototype.removeListener=function(e,t){var r,n,a,i;if(!mi(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,n=-1,r===t||mi(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(xi(r)){for(i=a;i-- >0;)if(r[i]===t||r[i].listener&&r[i].listener===t){n=i;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},vi.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(mi(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},vi.prototype.listeners=function(e){return this._events&&this._events[e]?mi(this._events[e])?[this._events[e]]:this._events[e].slice():[]},vi.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(mi(t))return 1;if(t)return t.length}return 0},vi.listenerCount=function(e,t){return e.listenerCount(t)};var _i,wi=yi.EventEmitter,ki={init:function(e){if(e._ev instanceof wi)return e;var t=new wi,r=new wi;return e._ev=t,e._internalEv=r,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=r.on.bind(r),e._internalOnce=r.once.bind(r),e._removeInternalListener=r.removeListener.bind(r),e._removeAllInternalListeners=r.removeAllListeners.bind(r),e.emit=function(n,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(n,a),t.emit(n,a),r.emit(n,a)},e},triggerHandler:function(e,t,r){var n,a;"undefined"!=typeof jQuery&&(n=jQuery(e).triggerHandler(t,r));var i=e._ev;if(!i)return n;var o=i._events[t];if(!o)return n;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Ti.getCursor=function(e,t,r,n){return e="left"===r?0:"center"===r?1:"right"===r?2:nt.constrain(Math.floor(3*e),0,2),t="bottom"===n?0:"middle"===n?1:"top"===n?2:nt.constrain(Math.floor(3*t),0,2),pi[t][e]},Ti.unhover=_i.wrapped,Ti.unhoverRaw=_i.raw,Ti.init=function(e){var t,r,n,a,i,o,l,s,c=e.gd,u=1,f=h.DBLCLICKDELAY,d=e.element;c._mouseDownTime||(c._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,fi?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=e.clampFn||function(e,t,r){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var r;try{r=new MouseEvent("click",t)}catch(e){var n=Ci(t);(r=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,n[0],n[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(r)}!function(e){e._dragging=!1,e._replotPending&&D.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Ti.coverSlip=Li;function Si(e,t,r,n){n=n||nt.identity,Array.isArray(e)&&(t[0][r]=n(e))}var Oi={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},flat:function(e,t){for(var r=new Array(e.length),n=0;n=0&&r.index-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.extraText&&(s+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),""===s&&(""===l&&r.remove(),s=l);var g=r.select("text.nums").call(Ur.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(mr.positionText,0,0).call(mr.convertToTspans,n),y=r.select("text.name"),m=0;l&&l!==s?(y.call(Ur.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(mr.positionText,0,0).call(mr.convertToTspans,n),m=y.node().getBoundingClientRect().width+2*Ui):(y.remove(),r.select("rect").remove()),r.select("path").style({fill:d,stroke:h});var k,M,A=g.node().getBoundingClientRect(),T=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),O=A.width+Vi+Ui+m;t.ty0=x-A.top,t.bx=A.width+2*Ui,t.by=A.height+2*Ui,t.anchor="start",t.txwidth=A.width,t.tx2width=m,t.offset=0,i?(t.pos=T,k=L+S/2+O<=_,M=L-S/2-O>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=T+C/2+O<=b,M=T-C/2-O>=0,"left"!==t.idealAlign&&k||!M?k?(T+=C/2,t.anchor="start"):t.anchor="middle":(T-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),r.attr("transform","translate("+T+","+L+")"+(i?"rotate("+Fi+")":""))}),C}function Yi(t,r){t.each(function(t){var n=e.select(this);if(t.del)n.remove();else{var a="end"===t.anchor?-1:1,i=n.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(Vi+Ui),s=l+o*(t.txwidth+Ui),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+Ui),r&&(u*=-qi,c=t.offset*Hi),n.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*Vi+c)+","+(Vi+u)+"v"+(t.by/2-Vi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*Vi+c)+"V"+(u-Vi)+"Z"),i.call(mr.positionText,l+c,u+t.ty0-t.by/2+Ui),t.tx2width&&(n.select("text.name").call(mr.positionText,s+o*Ui+c,u+t.ty0-t.by/2+Ui),n.select("rect").call(Ur.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function Xi(e,t){var r=e.index,n=e.trace||{},a=e.cd[0],i=e.cd[r]||{},o=Array.isArray(r)?function(e,t){return nt.castOption(a,r,e)||nt.extractOption({},n,"",t)}:function(e,t){return nt.extractOption(i,n,e,t)};function l(t,r,n){var a=o(r,n);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=nt.constrain(e.x0,0,e.xa._length),e.x1=nt.constrain(e.x1,0,e.xa._length),e.y0=nt.constrain(e.y0,0,e.ya._length),e.y1=nt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:da.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:da.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=da.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+da.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=da.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+da.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function Zi(e,t){var r,n,a=t.container,i=t.fullLayout,o=t.event,l=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||l){var u=xt.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var f,d,h=e.hLinePoint;r=h&&h.xa,"cursor"===(n=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=r._offset+h.x,d=n._offset+h.y);var p,g,v=s.readability(h.color,u)<1.5?xt.contrast(u):h.color,y=n.spikemode,m=n.spikethickness,x=n.spikecolor||v,b=n._boundingBox,_=(b.left+b.right)/2V.width||H<0||H>V.height)return Ai.unhoverRaw(t,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(_="xval"in n?Oi.flat(o,n.xval):Oi.p2c(h,B),w="yval"in n?Oi.flat(o,n.yval):Oi.p2c(p,H),!r(_[0])||!r(w[0]))return nt.warn("Fx.hover failed",n,t),Ai.unhoverRaw(t,n)}var U=1/0;for(M=0;ME&&(R.splice(0,E),U=R[0].distance),u&&0!==I&&0===R.length){z.distance=I,z.index=!1;var W=T._module.hoverPoints(z,O,P,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=I})),W&&W.length){var Q,J=W.filter(function(e){return e.xa.showspikes});if(J.length){var $=J[0];r($.x0)&&r($.y0)&&(Q=re($),(!j.vLinePoint||j.vLinePoint.spikeDistance>Q.spikeDistance)&&(j.vLinePoint=Q))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];r(ee.x0)&&r(ee.y0)&&(Q=re(ee),(!j.hLinePoint||j.hLinePoint.spikeDistance>Q.spikeDistance)&&(j.hLinePoint=Q))}}}}function te(e,t){for(var r,n=null,a=1/0,i=0;i1,ge=xt.combine(l.plot_bgcolor||xt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=Gi(R,ve,t);if(function(e,t,r){var n,a,i,o,l,s,c,u=0,f=e.map(function(e,n){var a=e[t];return[{i:n,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?Bi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?r.width:r.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],r=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=r.pos+r.dp+r.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;n=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;n=!1}if(n){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!n&&u<=e.length;){for(u++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;n=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(R,pe?"xa":"ya",l),Yi(ye,pe),n.target&&n.target.tagName){var me=D.getComponentMethod("annotations","hasClickToShow")(t,de);Ii(e.select(n.target),me?"pointer":"")}if(!n.target||i||!function(e,t,r){if(!r||r.length!==e._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var a=r[n],i=e._hoverdata[n];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,fe))return;fe&&t.emit("plotly_unhover",{event:n,points:fe});t.emit("plotly_hover",{event:n,points:t._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(t,n,a,i)})},Ri.loneHover=function(t,r){var n={color:t.color||xt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(r.container),i=r.outerContainer?e.select(r.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||xt.background,container:a,outerContainer:i},l=Gi([n],o,r.gd);return Yi(l,o.rotateLabels),l.node()};var Qi=Ri.hover,Ji=function(e,t,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),nt.coerceFont(r,"hoverlabel.font",n.font)},$i=L({editType:"none"});$i.family.dflt=gi.HOVERFONT,$i.size.dflt=gi.HOVERFONTSIZE;var Ki={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:$i,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var eo={moduleType:"component",name:"fx",constants:gi,schema:{layout:Ki},attributes:C,layoutAttributes:Ki,supplyLayoutGlobalDefaults:function(e,t){Ji(0,0,function(r,n){return nt.coerce(e,t,Ki,r,n)})},supplyDefaults:function(e,t,r,n){Ji(0,0,function(r,n){return nt.coerce(e,t,C,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(e,t,r){function n(r,n){return nt.coerce(e,t,Ki,r,n)}var a;n("dragmode"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,r=0;ri;if(!o)return t}return void 0!==n?n:e.dflt}(e.size,o,a.size),color:function(e,t,r){return s(t).isValid()?t:void 0!==r?r:e.dflt}(e.color,l,a.color)}}function ho(e,t){var r;return Array.isArray(e)?tc+l||!r(s))&&(f=!0,To(u,e))}for(var h=0;h0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var q=Math.pow(10,Math.floor(Math.log(H)/Math.LN10));j*=q*nt.roundUp(H/q,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(R.tick0=0)}R.dtick=j}R.domain=[z+S,z+T-S],R.setScale();var V=o._infolayer.selectAll("g."+r).data([0]);V.enter().append("g").classed(r,!0).classed(Do.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(Do.cbbg,!0),t.append("g").classed(Do.cbfills,!0),t.append("g").classed(Do.cblines,!0),t.append("g").classed(Do.cbaxis,!0).classed(Do.crisp,!0),t.append("g").classed(Do.cbtitleunshift,!0).append("g").classed(Do.cbtitle,!0),t.append("rect").classed(Do.cboutline,!0),t.select(".cbtitle").datum(0)}),V.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");R._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var Y,X=l.l+(n.x+L)*l.w,Z=R.titlefont.size;Y="top"===n.titleside?(1-(z+T-S))*l.h+l.t+3+.75*Z:(1-(z+S))*l.h+l.t-3-.25*Z,ee(R._id+"title",{attributes:{x:X,y:Y,"text-anchor":"start"}})}var W,Q,J,$=nt.syncOrAsync([Hn.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=V.select(".cbtitle"),a=r.select("text"),i=[-n.outlinewidth/2,n.outlinewidth/2],c=r.select(".h"+R._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*zo),c?(G=Ur.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(Do.jsPlaceholder)&&(G=Ur.bBox(a.node()).height),G){if(G+=5,"top"===n.titleside)R.domain[1]-=G/l.h,i[1]*=-1;else{R.domain[0]+=G/l.h;var v=mr.lineCount(a);i[1]+=(1-v)*u}r.attr("transform","translate("+i+")"),R.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-R.domain[1]))+")"),R._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(Do.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,r){var n=[0===r?f[0]:(h[r]+h[r-1])/2,r===h.length-1?f[1]:(h[r]+h[r+1])/2].map(R.c2p).map(Math.round);r!==h.length-1&&(n[1]+=n[1]>n[0]?1:-1);var a=g(t).replace("e-",""),i=s(a).toHexString();e.select(this).attr({x:O,width:Math.max(k,2),y:e.min(n),height:Math.max(e.max(n)-e.min(n),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?d:[]);return m.enter().append("path").classed(Do.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+O+","+(Math.round(R.c2p(t))+n.line.width/2%1)+"h"+k).call(Ur.lineGroupStyle,n.line.width,p(t),n.line.dash)}),R._axislayer.selectAll("g."+R._id+"tick,path").remove(),R._pos=O+k+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),R.side="right",nt.syncOrAsync([function(){return da.doTicks(t,R,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=R.titlefont.size,a=R._offset+R._length/2,i=l.l+(R.position||0)*l.w+("right"===R.side?10+r*(R.showticklabels?1:.5):-10-r*(R.showticklabels?.5:0));ee("h"+R._id+"title",{avoid:{selection:e.select(t).selectAll("g."+R._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Hn.previousPromises,function(){var e=k+n.outlinewidth/2+Ur.bBox(R._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(Do.jsPlaceholder)){var a,i=U.select(".h"+R._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(n.titleside)?Ur.bBox(i).width:Ur.bBox(U.node()).right-O-l.l,e=Math.max(e,a)}var o=2*n.xpad+e+n.borderwidth+n.outlinewidth/2,s=E-N;V.select(".cbbg").attr({x:O-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:N-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(xt.fill,n.bgcolor).call(xt.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),V.selectAll(".cboutline").attr({x:O,y:N+n.ypad+("top"===n.titleside?G:0),width:Math.max(k,2),height:Math.max(s-2*n.ypad-G,2)}).call(xt.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var c=({center:.5,right:1}[n.xanchor]||0)*o;V.attr("transform","translate("+(l.l-c)+","+l.t+")"),Hn.autoMargin(t,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],t);return $&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition&&Ai.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),Ei(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),Q=Ai.align(P+e/l.w,M,0,1,n.xanchor),J=Ai.align(z-t/l.h,T,0,1,n.yanchor);var r=Ai.getCursor(Q,J,n.xanchor,n.yanchor);Ei(V,r)},doneFn:function(){Ei(V),void 0!==Q&&void 0!==J&&D.call("restyle",t,{"colorbar.x":Q,"colorbar.y":J},i().index)}}),$}function K(e,t){return nt.coerce(I,R,mt,e,t)}function ee(e,r){var n,a=i();n=D.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:R,propName:n,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),ea.draw(t,e,Po(l,r||{}))}o._infolayer.selectAll("g."+r).remove()}function i(){var e,n,a=r.substr(2);for(e=0;e.01?A:function(e,t){return Math.abs(e-t)>=2?A(e):e>t?Math.ceil(e):Math.floor(e)};p=k(p,h=k(h,p)),v=k(v,g=k(g,v))}var M=e.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+h+","+g+"V"+v+"H"+p+"V"+g+"Z").call(Ur.setClipUrl,n.layerClipId),function(e,t,r,n,a,i,o,l){var s;function c(t,r,n){var a=t.append("text").text(r).attr({class:"bartext bartext-"+s,transform:"","text-anchor":"middle","data-notex":1}).call(Ur.font,n).call(mr.convertToTspans,e);return a}var u=r[0].trace,f=u.orientation,d=function(e,t){var r=ho(e.text,t);return po(ao,r)}(u,n);if(d&&"none"!==(s=function(e,t){var r=ho(e.textposition,t);return function(e,t,r){return e.coerceNumber&&(t=+t),-1!==e.values.indexOf(t)?t:void 0!==r?r:e.dflt}(io,r)}(u,n))){var h,p,g,v,y,m,x=function(e,t,r){return fo(oo,e.textfont,t,r)}(u,n,e._fullLayout.font),b=function(e,t,r){return fo(lo,e.insidetextfont,t,r)}(u,n,x),_=function(e,t,r){return fo(so,e.outsidetextfont,t,r)}(u,n,x),w=e._fullLayout.barmode,k="stack"===w||"relative"===w,M=r[n],A=!k||M._outmost,T=Math.abs(i-a)-2*co,L=Math.abs(l-o)-2*co;if("outside"===s&&(A||(s="inside")),"auto"===s)if(A){s="inside",h=c(t,d,b),p=Ur.bBox(h.node()),g=p.width,v=p.height;var C=g>0&&v>0,S=g<=T&&v<=L,O=g<=L&&v<=T,P="h"===f?T>=g*(L/v):L>=v*(T/g);C&&(S||O||P)?s="inside":(s="outside",h.remove(),h=null)}else s="inside";!h&&(h=c(t,d,"outside"===s?_:b),p=Ur.bBox(h.node()),g=p.width,v=p.height,g<=0||v<=0)?h.remove():("outside"===s?(m="both"===u.constraintext||"outside"===u.constraintext,y=function(e,t,r,n,a,i,o){var l,s="h"===i?Math.abs(n-r):Math.abs(t-e);s>2*co&&(l=co);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,h,p=(a.left+a.right)/2,g=(a.top+a.bottom)/2;return u=c*a.width,f=c*a.height,"h"===i?tr?(d=(e+t)/2,h=n+l+f/2):(d=(e+t)/2,h=n-l-f/2),uo(p,g,d,h,c,!1)}(a,i,o,l,p,f,m)):(m="both"===u.constraintext||"inside"===u.constraintext,y=function(e,t,r,n,a,i,o){var l,s,c,u,f,d,h,p=a.width,g=a.height,v=(a.left+a.right)/2,y=(a.top+a.bottom)/2,m=Math.abs(t-e),x=Math.abs(n-r);return m>2*co&&x>2*co?(m-=2*(f=co),x-=2*f):f=0,p<=m&&g<=x?(d=!1,h=1):p<=x&&g<=m?(d=!0,h=1):pr?(c=(e+t)/2,u=n-f-s/2):(c=(e+t)/2,u=n+f+s/2),uo(v,y,c,u,h,d)}(a,i,o,l,p,f,m)),h.attr("transform",y))}}(t,M,a,c,h,p,g,v),n.layerClipId&&Ur.hideOutsideRangePoint(a[c],M.select("text"),i,o,u.xcalendar,u.ycalendar)}else e.select(this).remove();function A(t){return 0===l.bargap&&0===l.bargroupgap?e.round(Math.round(t)-w,2):t}})}),D.getComponentMethod("errorbars","plot")(s,n),s.each(function(t){var r=!1===t[0].trace.cliponaxis;Ur.setClipUrl(e.select(this),r?null:n.layerClipId)})},No.style=function(t,r){var n=r?r[0].node3:e.select(t).selectAll("g.trace.bars"),a=n.size(),i=t._fullLayout;n.style("opacity",function(e){return e[0].trace.opacity}).each(function(t){("stack"===i.barmode&&a>1||0===i.bargap&&0===i.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),n.selectAll("g.points").each(function(r){var n=e.select(this),a=n.selectAll("path"),i=n.selectAll("text"),o=r[0].trace;Ur.pointStyle(a,o,t),Ur.selectedPointStyle(a,o),i.each(function(t){var r,n=e.select(this);function a(e){var n=r[e];return Array.isArray(n)?n[t.i]:n}n.classed("bartext-inside")?r=o.insidetextfont:n.classed("bartext-outside")&&(r=o.outsidetextfont),r||(r=o.textfont),Ur.font(n,a("family"),a("size"),a("color"))}),Ur.selectedTextStyle(i,o)}),D.getComponentMethod("errorbars","style")(n)},No.hoverPoints=function(e,t,r,n){var a,i,o,l,s,c,u,f=e.cd,d=f[0].trace,h=f[0].t,p="closest"===n,g=e.maxHoverDistance,v=e.maxSpikeDistance;function y(e){return e[o]-e.w/2}function m(e){return e[o]+e.w/2}var x=p?y:function(e){return Math.min(y(e),e.p-h.bardelta/2)},b=p?m:function(e){return Math.max(m(e),e.p+h.bardelta/2)};function _(e,t){return eo.inbox(e-a,t-a,g+Math.min(1,Math.abs(t-e)/u)-1)}function w(e){return _(x(e),b(e))}function k(e){return eo.inbox(e.b-i,e[l]-i,g+(e[l]-i)/(e[l]-e.b)-1)}"h"===d.orientation?(a=r,i=t,o="y",l="x",s=k,c=w):(a=t,i=r,o="x",l="y",c=k,s=w);var M=e[o+"a"],A=e[l+"a"];u=Math.abs(M.r2c(M.range[1])-M.r2c(M.range[0]));var T=eo.getDistanceFunction(n,s,c,function(e){return(s(e)+c(e))/2});if(eo.getClosest(f,T,e),!1!==e.index){p||(x=function(e){return Math.min(y(e),e.p-h.bargroupwidth/2)},b=function(e){return Math.max(m(e),e.p+h.bargroupwidth/2)});var L=f[e.index],C=L.mcc||d.marker.color,S=L.mlcc||d.marker.line.color,O=L.mlw||d.marker.line.width;xt.opacity(C)?e.color=C:xt.opacity(S)&&O&&(e.color=S);var P=d.base?L.b+L.s:L.s;e[l+"0"]=e[l+"1"]=A.c2p(L[l],!0),e[l+"LabelVal"]=P;var z=h.extents[h.extents.round(L.p)];return e[o+"0"]=M.c2p(p?x(L):z[0],!0),e[o+"1"]=M.c2p(p?b(L):z[1],!0),e[o+"LabelVal"]=L.p,e.spikeDistance=(k(L)+function(e){return _(y(e),m(e))}(L))/2+v-g,e[o+"Spike"]=M.c2p(L.p,!0),to(L,d,e),D.getComponentMethod("errorbars","hoverInfo")(L,d,e),[e]}},No.selectPoints=function(e,t){var r,n=e.cd,a=e.xaxis,i=e.yaxis,o=[];if(!1===t)for(r=0;r1)for(var r=1;r=0,p=r.indexOf("end")>=0,g=c.backoff*f+n.standoff,v=u.backoff*d+n.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}r._w=C,r._h=S;for(var E=!1,N=["x","y"],I=0;I1)&&(U===V?((K=G.r2fraction(r["a"+q]))<0||K>1)&&(E=!0):E=!0,E))continue;R=G._offset+G.r2p(r[q]),B=.5}else"x"===q?(j=r[q],R=u.l+u.w*j):(j=1-r[q],R=u.t+u.h*j),B=r.showarrow?.5:j;if(r.showarrow){$.head=R;var ee=r["a"+q];H=X*z(.5,r.xanchor)-Z*z(.5,r.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=H):($.tail=R+ee,F=H+ee),$.text=$.tail+H;var te=c["x"===q?"width":"height"];if("paper"===V&&($.head=nt.constrain($.head,1,te-1)),"pixel"===U){var re=-Math.max($.tail-3,$.text),ne=Math.min($.tail+3,$.text)-te;re>0?($.tail+=re,$.text+=re):ne>0&&($.tail-=ne,$.text-=ne)}$.tail+=J,$.head+=J}else F=H=W*z(B,Q),$.text=R+H;$.text+=J,H+=J,F+=J,r["_"+q+"padplus"]=W/2+F,r["_"+q+"padminus"]=W/2-F,r["_"+q+"size"]=W,r["_"+q+"shift"]=H}if(E)x.remove();else{var ae=0,ie=0;if("left"!==r.align&&(ae=(C-_)*("center"===r.align?.5:1)),"top"!==r.valign&&(ie=(S-T)*("middle"===r.valign?.5:1)),l)n.select("svg").attr({x:w+ae-1,y:w+ie}).call(Ur.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(mr.positionText,le,oe).call(Ur.setClipUrl,M?d:null)}A.select("rect").call(Ur.setRect,w,w,C,S),k.call(Ur.setRect,b/2,b/2,O-b,P-b),x.call(Ur.setTranslate,Math.round(h.x.text-O/2),Math.round(h.y.text-P/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,n){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+n,m=h.x.text+e,b=h.y.text+n,_=nt.rotationXYMatrix(p,m,b),w=nt.apply2DTransform(_),M=nt.apply2DTransform2(_),A=+k.attr("width"),T=+k.attr("height"),L=m-.5*A,C=L+A,S=b-.5*T,O=S+T,P=[[L,S,L,O],[L,O,C,O],[C,O,C,S],[C,S,L,S]].map(M);if(!P.reduce(function(e,t){return e^!!nt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){P.forEach(function(e){var t=nt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var z=r.arrowwidth,E=r.arrowcolor,N=r.arrowside,I=g.append("g").style({opacity:xt.opacity(E)}).classed("annotation-arrow-g",!0),R=I.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",z+"px").call(xt.stroke,xt.rgb(E));if(il(R,N,r),f.annotationPosition&&R.node().parentNode&&!a){var F=l,j=c;if(r.standoff){var B=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=r.standoff*(d-l)/B,j+=r.standoff*(y-c)/B}var H,q,V,U=I.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-j),transform:"translate("+F+","+j+")"}).style("stroke-width",z+6+"px").call(xt.stroke,"rgba(0,0,0,0)").call(xt.fill,"rgba(0,0,0,0)");Ai.init({element:U.node(),gd:t,prepFn:function(){var e=Ur.getTranslate(x);q=e.x,V=e.y,H={},i&&i.autorange&&(H[i._name+".autorange"]=!0),o&&o.autorange&&(H[o._name+".autorange"]=!0)},moveFn:function(e,t){var n=w(q,V),a=n[0]+e,l=n[1]+t;x.call(Ur.setTranslate,a,l),H[s+".x"]=i?i.p2r(i.r2p(r.x)+e):r.x+e/u.w,H[s+".y"]=o?o.p2r(o.r2p(r.y)+t):r.y-t/u.h,r.axref===r.xref&&(H[s+".ax"]=i.p2r(i.r2p(r.ax)+e)),r.ayref===r.yref&&(H[s+".ay"]=o.p2r(o.r2p(r.ay)+t)),I.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){D.call("relayout",t,H);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(r.showarrow&&ue(0,0),y)Ai.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var n="pointer";if(r.showarrow)r.axref===r.xref?se[s+".ax"]=i.p2r(i.r2p(r.ax)+e):se[s+".ax"]=r.ax+e,r.ayref===r.yref?se[s+".ay"]=o.p2r(o.r2p(r.ay)+t):se[s+".ay"]=r.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(r.x)+e);else{var l=r._xsize/u.w,c=r.x+(r._xshift-r.xshift)/u.w-l/2;se[s+".x"]=Ai.align(c+e/u.w,l,0,1,r.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(r.y)+t);else{var f=r._ysize/u.h,d=r.y-(r._yshift+r.yshift)/u.h-f/2;se[s+".y"]=Ai.align(d-t/u.h,f,0,1,r.yanchor)}i&&o||(n=Ai.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],r.xanchor,r.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),Ei(x,n)},doneFn:function(){Ei(x),D.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var cl=ol.draw;function ul(e){var t=e._fullLayout;nt.filterVisible(t.annotations).forEach(function(t){var r,n,a,i,o=da.getFromId(e,t.xref),l=da.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(r=s+t.xshift,n=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(da.expand(o,[o.r2c(t.x)],{ppadplus:r,ppadminus:n}),da.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,da.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,r,a),ppadminus:Math.max(t._xpadminus,n,i)}))),l&&l.autorange&&(r=s-t.yshift,n=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(da.expand(l,[l.r2c(t.y)],{ppadplus:r,ppadminus:n}),da.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,da.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,r,a),ppadminus:Math.max(t._ypadminus,n,i)})))})}var fl={hasClickToShow:function(e,t){var r=dl(e,t);return r.on.length>0||r.explicitOff.length>0},onClick:function(e,t){var r,n=dl(e,t),a=n.on,i=n.off.concat(n.explicitOff),o={};if(!a.length&&!i.length)return;for(r=0;r1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=kl(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*r[0],t.yaxis.r2l(i.y)*r[1],t.zaxis.r2l(i.z)*r[2]]),Ml(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var Ll={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},Cl=function(e){var t=e.type,r=e.symmetric;if("data"===t){var n=e.array||[];if(r)return function(e,t){var r=+n[t];return[r,r]};var a=e.arrayminus||[];return function(e,t){var r=+n[t],i=+a[t];return isNaN(r)&&isNaN(i)?[NaN,NaN]:[i||0,r||0]}}var i=Sl(t,e.value),o=Sl(t,e.valueminus);return r||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function Sl(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var Ol=function(e){for(var t=e.calcdata,r=0;r0;t.each(function(t){var s,c=t[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Vr.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(t=[]);var h=e.select(this).selectAll("g.errorbar").data(t,s);if(h.exit().remove(),t.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Ur.setClipUrl(h,n.layerClipId),h.each(function(t){var n=e.select(this),s=function(e,t,n){var a={x:t.c2p(e.x),y:n.c2p(e.y)};return void 0!==e.yh&&(a.yh=n.c2p(e.yh),a.ys=n.c2p(e.ys),r(a.ys)||(a.noYS=!0,a.ys=n.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=t.c2p(e.xh),a.xs=t.c2p(e.xs),r(a.xs)||(a.noXS=!0,a.xs=t.c2p(e.xs,!0))),a}(t,i,o);if(!d||t.vis){var c,h=n.select("path.yerror");if(f.visible&&r(s.x)&&r(s.yh)&&r(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=n.select("path.xerror");if(u.visible&&r(s.y)&&r(s.xh)&&r(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var r=t[0].trace,n=r.error_y||{},a=r.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(xt.stroke,n.color),a.copy_ystyle&&(a=n),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(xt.stroke,a.color)})},hoverInfo:function(e,t,r){(t.error_y||{}).visible&&(r.yerr=e.yh-e.y,t.error_y.symmetric||(r.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(r.xerr=e.xh-e.x,t.error_x.symmetric||(r.xerrneg=e.x-e.xs))}};var Il={},Rl=m.extendFlat;Il.attributes=function(e,t){e=e||{},t=t||{};var r={valType:"info_array",editType:e.editType,items:[{valType:"number",min:0,max:1,editType:e.editType},{valType:"number",min:0,max:1,editType:e.editType}],dflt:[0,1]},n=(e.name&&e.name,e.trace,t.description&&t.description,{x:Rl({},r,{}),y:Rl({},r,{}),editType:e.editType});return e.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:e.editType},n.column={valType:"integer",min:0,dflt:0,editType:e.editType}),n},Il.defaults=function(e,t,r,n){var a=n&&n.x||[0,1],i=n&&n.y||[0,1],o=t.grid;if(o){var l=r("domain.column");void 0!==l&&(l1){i||o||l||"independent"===d("pattern")&&(i=!0),s._hasSubplotGrid=i;var f="top to bottom"===d("roworder");s._domains={x:ql("x",d,i?.2:.1,u),y:ql("y",d,i?.3:.1,c,f)}}}function d(e,t){return nt.coerce(r,s,Hl,e,t)}},contentDefaults:function(e,t){var r=t.grid;if(r&&r._domains){var n,a,i,o,l,s,c,u=e.grid,f=t._subplots,d=r._hasSubplotGrid,h=r.rows,p=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(d){var y=u.subplots||[];s=r.subplots=new Array(h);var m=1;for(n=0;n=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},Jl={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},$l=!0,Kl=function(e,t,r){if(!t._dragged&&!t._editing){var n,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===r&&$l&&t.data&&t._context.showTips?(nt.notifier(nt._(t,"Double-click on legend to isolate one trace"),"long"),$l=!1):$l=!1,D.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===r?-1===m?s.push(y):s.splice(m,1):2===r&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),D.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(n=0;nr[1])return r[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",nt.mean,[.2,1]),d.ms=u("marker.size",nt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",nt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),n=[nt.minExtend(i,d)],a=nt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?n:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Ur.pointStyle,a,r),l&&(n[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?n:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Ur.textPointStyle,a,r)})},as=vr.LINE_SPACING,is=vr.FROM_TL,os=vr.FROM_BR,ls=h.DBLCLICKDELAY;function ss(e,t){var r=e.data()[0][0],n=t._fullLayout,a=r.trace,i=D.traceIs(a,"pie"),o=a.index,l=i?r.label:a.name,s=e.selectAll("text.legendtext").data([0]);function c(r){mr.convertToTspans(r,t,function(){!function(e,t){var r=e.data()[0][0];if(!r.trace.showlegend)return void e.remove();var n,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*as;if(o){var s=Ur.bBox(o);n=s.height,a=s.width,Ur.setTranslate(i,0,n/4)}else{var c=e.select(".legendtext"),u=mr.lineCount(c),f=c.node();n=l*u,a=f?Ur.bBox(f).width:0;var d=l*(.3+(1-u)/2);mr.positionText(c,40,d)}n=Math.max(n,16)+3,r.height=n,r.width=a}(e,t)})}s.enter().append("text").classed("legendtext",!0),s.attr("text-anchor","start").classed("user-select-none",!0).call(Ur.font,n.legend.font).text(l),t._context.edits.legendText&&!i?s.call(mr.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var n,a=e;this.text()||(e=" ");var i=r.trace._fullInput||{},l={};if(-1!==["ohlc","candlestick"].indexOf(i.type))l[(n=r.trace.transforms)[n.length-1].direction+".name"]=e;else if(D.hasTransform(i,"groupby")){var s=D.getTransformIndices(i,"groupby"),u=s[s.length-1],f=nt.keyedContainer(i,"transforms["+u+"].styles","target","value.name");""===a?f.remove(r.trace._group):f.set(r.trace._group,e),l=f.constructUpdate()}else l.name=e;return D.call("restyle",t,l,o)}):c(s)}function cs(e,t){var r,n=1,a=e.selectAll("rect").data([0]);a.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(xt.fill,"rgba(0,0,0,0)"),a.on("mousedown",function(){(r=(new Date).getTime())-t._legendMouseDownTimels&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Kl(e,t,n)},ls):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),t._legendMouseDownTime=0,Kl(e,t,n))}})}function us(t,r,n){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=Wl.isGrouped(i),s=0;if(i._width=0,i._height=0,Wl.isVertical(i))l&&r.each(function(e,t){Ur.setTranslate(this,0,t*i.tracegroupgap)}),n.each(function(e){var t=e[0],r=t.height,n=t.width;Ur.setTranslate(this,o,5+o+i._height+r/2),i._height+=r,i._width=Math.max(i._width,n)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=r.data(),f=0,d=u.length;fo+b-_,n.each(function(e){var t=e[0],r=g?40+e[0].width:m;o+x+_+r>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Ur.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+r,i._height=Math.max(i._height,t.height),x+=_+r,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),n.each(function(r){var n=r[0],a=e.select(this).select(".legendtoggle");Ur.setRect(a,0,-n.height/2,(t._context.edits.legendText?0:i._width)+s,n.height)})}function fs(e){var t=e._fullLayout.legend,r="left";Ql.isRightAnchor(t)?r="right":Ql.isCenterAnchor(t)&&(r="center");var n="top";Ql.isBottomAnchor(t)?n="bottom":Ql.isMiddleAnchor(t)&&(n="middle"),Hn.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*is[r],r:t._width*os[r],b:t._height*os[n],t:t._height*is[n]})}var ds={moduleType:"component",name:"legend",layoutAttributes:Zl,supplyLayoutDefaults:function(e,t,r){for(var n,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),nt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(n=0,i="left",a=1.1,o="bottom"):(n=0,i="left",a=-.1,o="top")}h("traceorder",u),Wl.isGrouped(t.legend)&&h("tracegroupgap"),h("x",n),h("xanchor",i),h("y",a),h("yanchor",o),nt.noneOrAll(l,s,["x","y"])}},draw:function(t){var r=t._fullLayout,n="legend"+r._uid;if(r._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=r.legend,i=r.showlegend&&function(e,t){var r,n,a={},i=[],o=!1,l={},s=0;function c(e,r){if(""!==e&&Wl.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[r]]):a[e].push([r]);else{var n="~~i"+s;i.push(n),a[n]=[[r]],s++}}for(r=0;rg?function(e){var t=e._fullLayout.legend,r="left";Ql.isRightAnchor(t)?r="right":Ql.isCenterAnchor(t)&&(r="center"),Hn.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*is[r],r:t._width*os[r],b:0,t:0})}(t):fs(t);var v=r._size,y=v.l+v.w*a.x,m=v.t+v.h*(1-a.y);Ql.isRightAnchor(a)?y-=a._width:Ql.isCenterAnchor(a)&&(y-=a._width/2),Ql.isBottomAnchor(a)?m-=a._height:Ql.isMiddleAnchor(a)&&(m-=a._height/2);var x=a._width,b=v.w;x>b?(y=v.l,x=b):(y+x>p&&(y=p-x),y<0&&(y=0),x=Math.min(p-y,a._width));var _,w,k,M,A=a._height,T=v.h;if(A>T?(m=v.t,A=T):(m+A>g&&(m=g-A),m<0&&(m=0),A=Math.min(g-m,a._height)),Ur.setTranslate(l,y,m),f.on(".drag",null),l.on("wheel",null),a._height<=A||t._context.staticPlot)c.attr({width:x-a.borderwidth,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Ur.setTranslate(u,0,0),s.select("rect").attr({width:x-2*a.borderwidth,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Ur.setClipUrl(u,n),Ur.setRect(f,0,0,0,0),delete a._scrollY;else{var L,C,S=Math.max(Jl.scrollBarMinHeight,A*A/a._height),O=A-S-2*Jl.scrollBarMargin,P=a._height-A,z=O/P,E=Math.min(a._scrollY||0,P);c.attr({width:x-2*a.borderwidth+Jl.scrollBarWidth+Jl.scrollBarMargin,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),s.select("rect").attr({width:x-2*a.borderwidth+Jl.scrollBarWidth+Jl.scrollBarMargin,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+E}),Ur.setClipUrl(u,n),I(E,S,z),l.on("wheel",function(){I(E=nt.constrain(a._scrollY+e.event.deltaY/O*P,0,P),S,z),0!==E&&E!==P&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){L=e.event.sourceEvent.clientY,C=E}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||I(E=nt.constrain((t.clientY-L)/z+C,0,P),S,z)});f.call(N)}t._context.edits.legendPosition&&(l.classed("cursor-move",!0),Ai.init({element:l.node(),gd:t,prepFn:function(){var e=Ur.getTranslate(l);k=e.x,M=e.y},moveFn:function(e,t){var r=k+e,n=M+t;Ur.setTranslate(l,r,n),_=Ai.align(r,0,v.l,v.l+v.w,a.xanchor),w=Ai.align(n,0,v.t+v.h,v.t,a.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&D.call("relayout",t,{"legend.x":_,"legend.y":w})},clickFn:function(e,n){var a=r._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return n.clientX>=e.left&&n.clientX<=e.right&&n.clientY>=e.top&&n.clientY<=e.bottom});a.size()>0&&(1===e?l._clickTimeout=setTimeout(function(){Kl(a,t,e)},ls):2===e&&(l._clickTimeout&&clearTimeout(l._clickTimeout),Kl(a,t,e)))}}))}function I(e,r,n){a._scrollY=t._fullLayout.legend._scrollY=e,Ur.setTranslate(u,0,-e),Ur.setRect(f,x,Jl.scrollBarMargin+e*n,Jl.scrollBarWidth,r),s.select("rect").attr({y:a.borderwidth+e})}},style:ns},hs={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},ps=m.extendFlat,gs={visible:{valType:"boolean",editType:"plot"},buttons:hs=ps(hs,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:L({editType:"plot"}),bgcolor:{valType:"color",dflt:O.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:O.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},vs={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var ys=function(t,r){var n=t._name,a={};if("all"===r.step)a[n+".autorange"]=!0;else{var i=function(t,r){var n,a=t.range,i=new Date(t.r2l(a[1])),o=r.step,l=r.count;switch(r.stepmode){case"backward":n=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);n=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[n,c]}(t,r);a[n+".range[0]"]=i[0],a[n+".range[1]"]=i[1]}return a};var ms=vr.LINE_SPACING,xs=vr.FROM_TL,bs=vr.FROM_BR;function _s(e){return e._id}function ws(e,t,r){var n=e.selectAll("rect").data([0]);n.enter().append("rect").classed("selector-rect",!0),n.attr("shape-rendering","crispEdges"),n.attr({rx:vs.rx,ry:vs.ry}),n.call(xt.stroke,t.bordercolor).call(xt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,r)).style("stroke-width",t.borderwidth+"px")}function ks(e,t,r,n){var a,i=e.selectAll("text").data([0]);i.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),i.attr("text-anchor","middle"),i.call(Ur.font,t.font).text((a=r,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){mr.convertToTspans(e,n)})}var Ms={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:gs}}},layoutAttributes:gs,handleDefaults:function(e,t,r,n,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return nt.coerce(i,o,gs,e,t)}if(l("visible",function(e,t,r){var n,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return nt.coerce(n,a,hs,e,t)}for(var s=0;s0)){var s=function(e,t,r){for(var n=r.filter(function(r){return t[r].anchor===e._id}),a=0,i=0;if&&(f=c)));return f>=u?[u,f]:void 0}}var Us=function(e,t,r,n,a){function i(r,n){return nt.coerce(e,t,Bs,r,n)}if(n=n||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=["x","y"],s=0;s<2;s++){var c=l[s],u={_fullLayout:r},f=da.coerceRef(e,t,u,c,"","paper");if("path"!==o){var d,h,p;"paper"!==f?(d=da.getFromId(u,f),p=qs.rangeToShapePosition(d),h=qs.shapePositionToRange(d)):h=p=nt.identity;var g=c+"0",v=c+"1",y=e[g],m=e[v];e[g]=h(e[g],!0),e[v]=h(e[v],!0),da.coercePosition(t,u,i,f,g,.25),da.coercePosition(t,u,i,f,v,.75),t[g]=p(t[g]),t[v]=p(t[v]),e[g]=y,e[v]=m}}return"path"===o?i("path"):nt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},Gs={draw:function(e){var t=e._fullLayout;t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._shapeSubplotLayers.selectAll("path").remove();for(var r=0;rN&&n>I&&!e.shiftKey?Ai.getCursor(a/r,1-i/n):"move";Ei(t,o),E=o.split("-")[0]}function B(n,h){if("path"===r.type){var p=function(e){return P(S(e)+n)};L&&"date"===L.type&&(p=qs.encodeDate(p));var g=function(e){return z(O(e)+h)};C&&"date"===C.type&&(g=qs.encodeDate(g)),r.path=Zs(A,p,g),a[T]=r.path}else a[c]=r.x0=P(i+n),a[u]=r.y0=z(o+h),a[f]=r.x1=P(l+n),a[d]=r.y1=z(s+h);t.attr("d",Xs(e,r))}function H(n,i){if("path"===r.type){var o=function(e){return P(S(e)+n)};L&&"date"===L.type&&(o=qs.encodeDate(o));var l=function(e){return z(O(e)+i)};C&&"date"===C.type&&(l=qs.encodeDate(l)),r.path=Zs(A,o,l),a[T]=r.path}else{var s=~E.indexOf("n")?h+i:h,c=~E.indexOf("s")?p+i:p,u=~E.indexOf("w")?g+n:g,f=~E.indexOf("e")?v+n:v;c-s>I&&(a[y]=r[_]=z(s),a[m]=r[w]=z(c)),f-u>N&&(a[x]=r[k]=P(u),a[b]=r[M]=P(f))}t.attr("d",Xs(e,r))}Ai.init(R),t.node().onmousemove=j}(e,o,n,t)}}function Xs(e,t){var r,n,a,i,o=t.type,l=da.getFromId(e,t.xref),s=da.getFromId(e,t.yref),c=e._fullLayout._size;if(l?(r=qs.shapePositionToRange(l),n=function(e){return l._offset+l.r2p(r(e,!0))}):n=function(e){return c.l+c.w*e},s?(a=qs.shapePositionToRange(s),i=function(e){return s._offset+s.r2p(a(e,!0))}):i=function(e){return c.t+c.h*(1-e)},"path"===o)return l&&"date"===l.type&&(n=qs.decodeDate(n)),s&&"date"===s.type&&(i=qs.decodeDate(i)),function(e,t,r){return e.replace(Hs.segmentRE,function(e){var n=0,a=e.charAt(0),i=Hs.paramIsX[a],o=Hs.paramIsY[a],l=Hs.numParams[a],s=e.substr(1).replace(Hs.paramRE,function(e){return i[n]?e=t(e):o[n]&&(e=r(e)),++n>l&&(e="X"),e});return n>l&&(s=s.replace(/[\s,]*X.*/,""),nt.log("Ignoring extra params in segment "+e)),a+s})}(t.path,n,i);var u=n(t.x0),f=n(t.x1),d=i(t.y0),h=i(t.y1);if("line"===o)return"M"+u+","+d+"L"+f+","+h;if("rect"===o)return"M"+u+","+d+"H"+f+"V"+h+"H"+u+"Z";var p=(u+f)/2,g=(d+h)/2,v=Math.abs(p-u),y=Math.abs(g-d),m="A"+v+","+y,x=p+v+","+g;return"M"+x+m+" 0 1,1 "+(p+","+(g-y))+m+" 0 0,1 "+x+"Z"}function Zs(e,t,r){return e.replace(Hs.segmentRE,function(e){var n=0,a=e.charAt(0),i=Hs.paramIsX[a],o=Hs.paramIsY[a],l=Hs.numParams[a];return a+e.substr(1).replace(Hs.paramRE,function(e){return n>=l?e:(i[n]?e=t(e):o[n]&&(e=r(e)),n++,e)})})}var Ws={moduleType:"component",name:"shapes",layoutAttributes:Bs,supplyLayoutDefaults:function(e,t){vl(e,t,{name:"shapes",handleItemDefaults:Us})},includeBasePlot:yl("shapes"),calcAutorange:function(e){var t=e._fullLayout,r=nt.filterVisible(t.shapes);if(r.length&&e._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),nt.noneOrAll(e,t,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),nt.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),nt.coerceFont(n,"currentvalue.font",t.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var nc=vr.LINE_SPACING,ac=vr.FROM_TL,ic=vr.FROM_BR;function oc(e){return e._index}function lc(t,r){var n=Ur.tester.selectAll("g."+Qs.labelGroupClass).data(r.steps);n.enter().append("g").classed(Qs.labelGroupClass,!0);var a=0,i=0;n.each(function(t){var n=uc(e.select(this),{step:t},r).node();if(n){var o=Ur.bBox(n);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(Qs.railWidth,Qs.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*r.x,o.ly=l.t+l.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(l.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var s=(o.inputAreaLength-2*Qs.stepInset)/(r.steps.length-1),c=a+Qs.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var u=Ur.tester.append("g");n.each(function(e){var t=sc(u,r,e.label),n=t.node()&&Ur.bBox(t.node())||{width:0,height:0},a=mr.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+Qs.tickOffset+r.ticklen+Qs.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var f="left";Ql.isRightAnchor(r)&&(o.lx-=o.outerLength,f="right"),Ql.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,f="center");var d="top";Ql.isBottomAnchor(r)&&(o.ly-=o.height,d="bottom"),Ql.isMiddleAnchor(r)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Hn.autoMargin(t,Qs.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*ac[f],r:o.outerLength*ic[f],b:o.height*ic[d],t:o.height*ac[d]})}function sc(e,t,r){if(t.currentvalue.visible){var n,a,i=e.selectAll("text").data([0]),o=t._dims;switch(t.currentvalue.xanchor){case"right":n=o.inputAreaLength-Qs.currentValueInset-o.currentValueMaxWidth,a="left";break;case"center":n=.5*o.inputAreaLength,a="middle";break;default:n=Qs.currentValueInset,a="left"}i.enter().append("text").classed(Qs.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1});var l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof r)l+=r;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),i.call(Ur.font,t.currentvalue.font).text(l).call(mr.convertToTspans,t._gd);var s=mr.lineCount(i),c=(o.currentValueMaxLines+1-s)*t.currentvalue.font.size*nc;return mr.positionText(i,n,c),i}}function cc(e,t,r){var n=e.selectAll("rect."+Qs.gripRectClass).data([0]);n.enter().append("rect").classed(Qs.gripRectClass,!0).call(pc,t,e,r).style("pointer-events","all"),n.attr({width:Qs.gripWidth,height:Qs.gripHeight,rx:Qs.gripRadius,ry:Qs.gripRadius}).call(xt.stroke,r.bordercolor).call(xt.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function uc(e,t,r){var n=e.selectAll("text").data([0]);return n.enter().append("text").classed(Qs.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(Ur.font,r.font).text(t.step.label).call(mr.convertToTspans,r._gd),n}function fc(t,r){var n=t.selectAll("g."+Qs.labelsClass).data([0]),a=r._dims;n.enter().append("g").classed(Qs.labelsClass,!0);var i=n.selectAll("g."+Qs.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(Qs.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var n=e.select(this);n.call(uc,t,r),Ur.setTranslate(n,yc(r,t.fraction),Qs.tickOffset+r.ticklen+r.font.size*nc+Qs.labelOffset+a.currentValueTotalHeight)})}function dc(e,t,r,n,a){var i=Math.round(n*(r.steps.length-1));i!==r.active&&hc(e,t,r,i,!0,a)}function hc(e,t,r,n,a,i){var o=r.active;r._input.active=r.active=n;var l=r.steps[r.active];t.call(vc,r,r.active/(r.steps.length-1),i),t.call(sc,r),e.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var r=t._nextMethod.step;r.method&&(r.execute&&Hn.executeAPICommand(e,r.method,r.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function pc(t,r,n){var a=n.node(),i=e.select(r);function o(){return n.data()[0]}t.on("mousedown",function(){var t=o();r.emit("plotly_sliderstart",{slider:t});var l=n.select("."+Qs.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(xt.fill,t.activebgcolor);var s=mc(t,e.mouse(a)[0]);dc(r,n,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=mc(t,e.mouse(a)[0]);dc(r,n,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(xt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),r.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function gc(t,r){var n=t.selectAll("rect."+Qs.tickRectClass).data(r.steps),a=r._dims;n.enter().append("rect").classed(Qs.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(t,n){var i=n%a.labelStride==0,o=e.select(this);o.attr({height:i?r.ticklen:r.minorticklen}).call(xt.fill,r.tickcolor),Ur.setTranslate(o,yc(r,n/(r.steps.length-1))-.5*r.tickwidth,(i?Qs.tickOffset:Qs.minorTickOffset)+a.currentValueTotalHeight)})}function vc(e,t,r,n){var a=e.select("rect."+Qs.gripRectClass),i=yc(t,r);if(!t._invokingCommand){var o=a;n&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*Qs.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function yc(e,t){var r=e._dims;return r.inputAreaStart+Qs.stepInset+(r.inputAreaLength-2*Qs.stepInset)*Math.min(1,Math.max(0,t))}function mc(e,t){var r=e._dims;return Math.min(1,Math.max(0,(t-Qs.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*Qs.stepInset-2*r.inputAreaStart)))}function xc(e,t,r){var n=e.selectAll("rect."+Qs.railTouchRectClass).data([0]),a=r._dims;n.enter().append("rect").classed(Qs.railTouchRectClass,!0).call(pc,t,e,r).style("pointer-events","all"),n.attr({width:a.inputAreaLength,height:Math.max(a.inputAreaWidth,Qs.tickOffset+r.ticklen+a.labelHeight)}).call(xt.fill,r.bgcolor).attr("opacity",0),Ur.setTranslate(n,0,a.currentValueTotalHeight)}function bc(e,t){var r=e.selectAll("rect."+Qs.railRectClass).data([0]),n=t._dims;r.enter().append("rect").classed(Qs.railRectClass,!0);var a=n.inputAreaLength-2*Qs.railInset;r.attr({width:a,height:Qs.railWidth,rx:Qs.railRadius,ry:Qs.railRadius,"shape-rendering":"crispEdges"}).call(xt.stroke,t.bordercolor).call(xt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Ur.setTranslate(r,Qs.railInset,.5*(n.inputAreaWidth-Qs.railWidth)+n.currentValueTotalHeight)}var _c={moduleType:"component",name:Qs.name,layoutAttributes:Ks,supplyLayoutDefaults:function(e,t){vl(e,t,{name:ec,handleItemDefaults:rc})},draw:function(t){var r=t._fullLayout,n=function(e,t){for(var r=e[Qs.name],n=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(Qs.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},r=Object.keys(t),n=0;n=r.steps.length&&(r.active=0),t.call(sc,r).call(bc,r).call(fc,r).call(gc,r).call(xc,e,r).call(cc,e,r);var n=r._dims;Ur.setTranslate(t,n.lx+r.pad.l,n.ly+r.pad.t),t.call(vc,r,r.active/(r.steps.length-1),!1),t.call(sc,r)}(t,e.select(this),r)}})}}},wc=m.extendFlat,kc=(0,ar.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:wc({},Js,{}),font:L({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:O.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Mc={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Ac=Mc.name,Tc=kc.buttons;function Lc(e,t,r){function n(r,n){return nt.coerce(e,t,kc,r,n)}n("visible",function(e,t){var r,n,a=e.buttons||[],i=t.buttons=[];function o(e,t){return nt.coerce(r,n,Tc,e,t)}for(var l=0;l0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),nt.noneOrAll(e,t,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),nt.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var Cc=Sc;function Sc(e,t,r){this.gd=e,this.container=t,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Sc.barWidth=2,Sc.barLength=20,Sc.barRadius=2,Sc.barPad=1,Sc.barColor="#808BA4",Sc.prototype.enable=function(t,r,n){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=Sc.barLength+2*Sc.barPad,k=Sc.barWidth+2*Sc.barPad,M=f,A=h+p;A+k>o&&(A=o-k);var T=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);T.exit().on(".drag",null).remove(),T.enter().append("rect").classed("scrollbar-horizontal",!0).call(xt.fill,Sc.barColor),_?(this.hbar=T.attr({rx:Sc.barRadius,ry:Sc.barRadius,x:M,y:A,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=Sc.barWidth+2*Sc.barPad,S=Sc.barLength+2*Sc.barPad,O=f+d,P=h;O+C>i&&(O=i-C);var z=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);z.exit().on(".drag",null).remove(),z.enter().append("rect").classed("scrollbar-vertical",!0).call(xt.fill,Sc.barColor),L?(this.vbar=z.attr({rx:Sc.barRadius,ry:Sc.barRadius,x:O,y:P,width:C,height:S}),this._vbarYMin=P+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,N=L?s+C+.5:s+.5,I=c-.5,R=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(I),width:Math.ceil(N)-Math.floor(E),height:Math.ceil(R)-Math.floor(I)}),this.container.call(Ur.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Ur.setClipUrl,null),delete this._clipRect),_||L){var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),L&&this.vbar.on(".drag",null).call(B)}this.setTranslate(r,n)},Sc.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Ur.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Sc.prototype._onBoxDrag=function(){var t=this.translateX,r=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(r-=e.event.dy),this.setTranslate(t,r)},Sc.prototype._onBoxWheel=function(){var t=this.translateX,r=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(r+=e.event.deltaY),this.setTranslate(t,r)},Sc.prototype._onBarDrag=function(){var t=this.translateX,r=this.translateY;if(this.hbar){var n=t+this._hbarXMin,a=n+this._hbarTranslateMax;t=(nt.constrain(e.event.x,n,a)-n)/(a-n)*(this.position.w-this._box.w)}if(this.vbar){var i=r+this._vbarYMin,o=i+this._vbarTranslateMax;r=(nt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,r)},Sc.prototype.setTranslate=function(e,t){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(e=nt.constrain(e||0,0,r),t=nt.constrain(t||0,0,n),this.translateX=e,this.translateY=t,this.container.call(Ur.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/r;this.hbar.call(Ur.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/n;this.vbar.call(Ur.setTranslate,e,t+i*this._vbarTranslateMax)}};var Oc=vr.LINE_SPACING;function Pc(e){return e._index}function zc(e,t){return+e.attr(Mc.menuIndexAttrName)===t._index}function Dc(e,t,r,n,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?Nc(e,n,null,null,t):"dropdown"===t.type&&(a.attr(Mc.menuIndexAttrName,"-1"),Ec(e,n,a,i,t),l||Nc(e,n,a,i,t))}function Ec(e,t,r,n,a){var i=t.selectAll("g."+Mc.headerClassName).data([0]),o=a._dims;i.enter().append("g").classed(Mc.headerClassName,!0).style("pointer-events","all");var l=a.active,s=a.buttons[l]||Mc.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(Ic,a,s,e).call(Vc,a,c,u);var f=t.selectAll("text."+Mc.headerArrowClassName).data([0]);f.enter().append("text").classed(Mc.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(Ur.font,a.font).text(Mc.arrowSymbol[a.direction]),f.attr({x:o.headerWidth-Mc.arrowOffsetX+a.pad.l,y:o.headerHeight/2+Mc.textOffsetY+a.pad.t}),i.on("click",function(){r.call(Uc),r.attr(Mc.menuIndexAttrName,zc(r,a)?-1:String(a._index)),Nc(e,t,r,n,a)}),i.on("mouseover",function(){i.call(Bc)}),i.on("mouseout",function(){i.call(Hc,a)}),Ur.setTranslate(t,o.lx,o.ly)}function Nc(t,r,n,a,i){n||(n=r).attr("pointer-events","all");var o=function(e){return-1==+e.attr(Mc.menuIndexAttrName)}(n)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?Mc.dropdownButtonClassName:Mc.buttonClassName,s=n.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+Mc.gapButtonHeader:f=h.headerWidth+Mc.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-Mc.gapButtonHeader+Mc.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-Mc.gapButtonHeader+Mc.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:Mc.gapButton,xPad:Mc.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(Ic,i,o,t).call(Vc,i,g),c.on("click",function(){e.event.defaultPrevented||(Dc(t,i,0,r,n,a,l),o.execute&&Hn.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(Bc)}),c.on("mouseout",function(){c.call(Hc,i),s.call(jc,i)})}),s.call(jc,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,r,n,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(Mc.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},r=Object.keys(t),n=0;n_.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,r;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,r=0;r=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,r=0;r0&&nt.log("Clearing previous rejected promises from queue."),e._promises=[]},Qc.cleanLayout=function(e){var t,r;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var n=(Hn.subplotsRegistry.cartesian||{}).attrRegex,a=(Hn.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),xt.clean(e),e},Qc.cleanData=function(e,t){for(var r=[],n=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}Qc.hasParent=function(e,t){for(var r=nu(t);r;){if(r in e)return!0;r=nu(r)}return!1};var au=["x","y","z"];Qc.clearAxisTypes=function(e,t,r){for(var n=0;n1&&w.warn("Full array edits are incompatible with other edits",a);var f=r[""][""];if(su(f))t.set(null);else{if(!Array.isArray(f))return w.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(r).map(Number).sort(ou),b=t.get(),_=b||[],k=X(u,a).get(),M=[],T=-1,L=_.length;for(d=0;d_.length-(m?0:1))w.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&w.warn("Insertion & removal are incompatible with edits to the same index.",a,p),su(y)?M.push(p):m?("add"===y&&(y={}),_.splice(p,0,y),k&&k.splice(p,0,{})):w.warn("Unrecognized full object edit value",a,p,y),-1===T&&(T=p);else for(h=0;h=0;d--)_.splice(M[d],1),k&&k.splice(M[d],1);if(_.length?b||t.set(_):t.set(null),s)return!1;if(i(c,u),l!==A){var C;if(-1===T)C=x;else{for(L=Math.max(_.length,L),C=[],d=0;d=T);d++)C.push(p);for(d=T;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,r=0;r0})}function c(e,n){var a=e.seg,i=n.seg,o=a.start,s=a.end,c=i.start,u=i.end;r&&r.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return n;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(n,s):l(e,u),n;p&&(h||(g?l(n,s):l(e,u)),l(n,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(n,o):0===f.alongA?l(n,f.pt):1===f.alongA&&l(n,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(r&&r.vert(f.pt[0]),f.isStart){r&&r.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}r&&r.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,r&&r.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){r&&r.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:n,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:n,f.seg.otherFill={above:v,below:v}),r&&r.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(Lu.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return r&&r.done(),u}return e?{addRegion:function(e){for(var n,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,r,n){var a=t[1]-r[1],i=n[0]-r[0],o=t[0]-r[0],l=n[1]-r[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,r){return Math.abs(t[0]-r[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-n>e&&(l=!l),i=c,o=u}return l}};return t}();function Nu(e,t,r){var n=Pu.segments(e),a=Pu.segments(t),i=r(Pu.combine(n,a));return Pu.polygon(i)}Pu={buildLog:function(e){return!0===e?Du=Au():!1===e&&(Du=!1),!1!==Du&&Du.list},epsilon:function(e){return Eu.epsilon(e)},segments:function(e){var t=Cu(!0,Eu,Du);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Cu(!1,Eu,Du).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:zu.union(e.combined,Du),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:zu.intersect(e.combined,Du),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:zu.difference(e.combined,Du),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:zu.differenceRev(e.combined,Du),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:zu.xor(e.combined,Du),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Su(e.segments,Eu,Du),inverted:e.inverted}},polygonFromGeoJSON:function(e){return Tu.toPolygon(Pu,e)},polygonToGeoJSON:function(e){return Tu.fromPolygon(Pu,Eu,e)},union:function(e,t){return Nu(e,t,Pu.selectUnion)},intersect:function(e,t){return Nu(e,t,Pu.selectIntersect)},difference:function(e,t){return Nu(e,t,Pu.selectDifference)},differenceRev:function(e,t){return Nu(e,t,Pu.selectDifferenceRev)},xor:function(e,t){return Nu(e,t,Pu.selectXor)}},"object"==typeof window&&(window.PolyBool=Pu);var Iu,Ru=Pu,Fu=He.dot,ju=n.BADNUM,Bu=Iu={};Bu.tester=function(e){if(Array.isArray(e[0][0]))return Bu.multitester(e);var t,r=e.slice(),n=r[0][0],a=n,i=r[0][1],o=i;for(r.push(r[0]),t=1;ta||s===ju||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===ju||la||s===ju||so)return!1;var c,u,f,d,h,p=r.length,g=r[0][0],v=r[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(Fu(i,f))>n)return!0;return!1};Bu.filter=function(e,t){var r=[e[0]],n=0,a=0;function i(i){e.push(i);var o=r.length,l=n;r.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:r}};var qu=Oi.makeEventData,Vu=Iu.filter,Uu=Iu.tester,Gu=Iu.multitester,Yu=ht.MINSELECT;function Xu(e){return e._id}var Zu=function(e,t,r,n,a){var i,o,l,s,c=n.gd,u=c._fullLayout,f=u._zoomlayer,d=n.element.getBoundingClientRect(),h=n.plotinfo,p=h.xaxis._offset,g=h.yaxis._offset,v=t-d.left,y=r-d.top,m=v,x=y,b="M"+v+","+y,_=n.xaxes[0]._length,w=n.yaxes[0]._length,k=n.xaxes.map(Xu),M=n.yaxes.map(Xu),A=n.xaxes.concat(n.yaxes),T=e.altKey;(e.shiftKey||e.altKey)&&h.selection&&h.selection.polygons&&!n.polygons?(n.polygons=h.selection.polygons,n.mergedPolygons=h.selection.mergedPolygons):(!e.shiftKey&&!e.altKey||(e.shiftKey||e.altKey)&&!h.selection)&&(h.selection={},h.selection.polygons=n.polygons=[],h.selection.mergedPolygons=n.mergedPolygons=[]),"lasso"===a&&(i=Vu([[v,y]],ht.BENDPX));var L=f.selectAll("path.select-outline-"+h.id).data([1,2]);L.enter().append("path").attr("class",function(e){return"select-outline select-outline-"+e+" select-outline-"+h.id}).attr("transform","translate("+p+", "+g+")").attr("d",b+"Z");var C,S,O,P,z,D,E=f.append("path").attr("class","zoombox-corners").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1}).attr("transform","translate("+p+", "+g+")").attr("d","M0,0Z"),N=[],I=u._uid+ht.SELECTID,R=[];for(C=0;C=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function uf(e,t,r,n,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",a+"Z")}function ff(e,t,r){return e.append("path").attr("class","zoombox-corners").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+r+")").attr("d","M0,0Z")}function df(e){e.selectAll(".select-outline").remove()}function hf(e,t,r,n,a,i){e.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),pf(e,t,a,i)}function pf(e,t,r,n){r||(e.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function gf(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function vf(e){rf&&e.data&&e._context.showTips&&(nt.notifier(nt._(e,"Double-click to zoom back out"),"long"),rf=!1)}function yf(e){return"lasso"===e||"select"===e}function mf(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,tf)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function xf(e,t){if(fi){var r=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(r,e._onwheel),e._onwheel=t,e.addEventListener(r,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}var bf=function(t,r,n,a,i,o,l,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k=t._fullLayout,M=t._fullLayout._zoomlayer,A=l+c==="nsew",T=1===(l+c).length;function L(){f=[r.xaxis],d=[r.yaxis];var e=f[0],n=d[0];g=e._length,v=n._length;var a,i,o=k._axisConstraintGroups,s=[e._id],M=[n._id];u=[r].concat(l&&c?r.overlays:[]);for(var A=1;Atf||o>tf?(R="xy",i/g>o/v?(o=i*v/g,P>a?z.t=P-o:z.b=P+o):(i=o*g/v,O>n?z.l=O-i:z.r=O+i),j.attr("d",mf(z))):l():!m||o rect").call(Ur.setTranslate,a,i).call(Ur.setScale,r,n);var z=x.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");x.plot.call(Ur.setTranslate,O,P).call(Ur.setScale,1/r,1/n),z.selectAll(".point").call(Ur.setPointGroupScale,r,n),z.selectAll(".textpoint").call(Ur.setTextPointsScale,r,n),z.call(Ur.hideOutsideRangePoints,x),x.plot.selectAll(".barlayer .trace").call(Ur.hideOutsideRangePoints,x,".bartext")}}}return l.length*c.length!=1&&xf(C,function(e){if(t._context.scrollZoom||k._enablescrollzoom){if(null===G&&df(M),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var r=t.querySelector(".plotly");if(L(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(G);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var a,i=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=X.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(c||b){for(c||(s=.5),a=0;a=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(r,a,h)?(d.push(e),h.push([r,a])):i=[0];var o=t.plotgroup.selectAll(".bg").data(i);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){t.bg=o;var e=t.plotgroup.node();e.insertBefore(this,e.childNodes[0])})});var p=n._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){n._plots[t].bg=e.select(this)}),f.each(function(e){var t=n._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Ur.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(xt.fill,n.plot_bgcolor).style("stroke-width",0),t.clipId="clip"+n._uid+e+"plot";var u,f,d=n._clips.selectAll("#"+t.clipId).data([0]);for(d.enter().append("clipPath").attr({class:"plotclip",id:t.clipId}).append("rect"),d.selectAll("rect").attr({width:a._length,height:c._length}),Ur.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=t.clipId):(u=t.clipId,f=null),Ur.setClipUrl(t.plot,u),r=0;rSf*h)||y)for(r=0;rL&&OA&&(A=O);l/=(A-M)/(2*T),M=a.l2r(M),A=a.l2r(A),a.range=a._input.range=_=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var A=k.slice();w&&b&&(A[1]+=M);var T=c.angularAxis.ticksCount||4;T>8&&(T=T/(T/8)+T%8),c.angularAxis.ticksStep&&(T=(A[1]-A[0])/T);var L=c.angularAxis.ticksStep||(A[1]-A[0])/(T*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),A[2]||(A[2]=L);var C=e.range.apply(this,A);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(A.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),O=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(O)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var P,z=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){P=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var N=u.map(function(e,t){var r=Nf.util.cloneJson(e);return r.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",r.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,r.color="LinePlot"===e.geometry?e.strokeColor:e.color,r});Nf.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:Df({},Nf.Legend.defaultConfig().legendConfig,{container:P,elements:N,reverseOrder:c.legend.reverseOrder})})();var I=P.node().getBBox();g=Math.min(c.width-I.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],n.range([0,g]),l.layout.radialAxis.domain=n.domain(),P.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else P=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),z.attr("transform","translate("+y+")").style({cursor:"crosshair"});var R=[(c.width-(c.margin.left+c.margin.right+2*g+(I?I.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(R[0]=Math.max(0,R[0]),R[1]=Math.max(0,R[1]),t.select(".outer-group").attr("transform","translate("+R+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),j=F.node().getBBox();F.attr({x:y[0]-j.width/2,y:y[1]-g-20})}var B=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var H=B.selectAll("circle.grid-circle").data(n.ticks(5));H.enter().append("circle").attr({class:"grid-circle"}).style(D),H.attr("r",n),H.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(D);var q=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(n).ticks(5).tickSize(5);B.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),B.selectAll(".domain").style(D),B.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var X=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:Ef+"em",transform:function(e,t){var r=V(e),n=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-r+" "+n+" 0)":"radial"==a?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&X.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var Z=e.max(z.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));P.attr({transform:"translate("+[g+Z,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,Q=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(Q.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),Q.exit().remove(),u[0]||W){var J=[];u.forEach(function(e,t){var r={};r.radialScale=n,r.angularScale=a,r.container=Q.filter(function(e,r){return r==t}),r.geometry=e.geometry,r.orientation=c.orientation,r.direction=c.direction,r.index=t,J.push({data:e,geometryConfig:r})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(J).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var r;r=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var n=e.map(function(e,t){return Df(Nf[r].defaultConfig(),e)});Nf[r]().config(n)()})}var K,ee,te=t.select(".guides-group"),re=t.select(".tooltips-group"),ne=Nf.tooltipPanel().config({container:re,fontSize:8})(),ae=Nf.tooltipPanel().config({container:re,fontSize:8})(),ie=Nf.tooltipPanel().config({container:re,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});z.on("mousemove.angular-guide",function(e,t){var r=Nf.util.getMousePos(q).angle;oe.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-c.orientation)%360;K=a.invert(n);var i=Nf.util.convertToCartesian(g+12,r+180);ne.text(Nf.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});z.on("mousemove.radial-guide",function(e,t){var r=Nf.util.getMousePos(q).radius;le.attr({r:r}).style({opacity:.5}),ee=n.invert(Nf.util.getMousePos(q).radius);var a=Nf.util.convertToCartesian(r,c.radialAxis.orientation);ae.text(Nf.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),ne.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:Nf.util.round(r[0]),r:Nf.util.round(r[1])};b&&(s.t=m[r[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-R[0]-f.left,u.top+u.height/2-R[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,r){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,r){ie.hide();var n=e.select(this),a=n.attr("data-fill");a?n.style({fill:a,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=Nf.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),Df(i.data[t],Nf.Axis.defaultConfig().data[0]),Df(i.data[t],e)}),Df(i.layout,Nf.Axis.defaultConfig().layout),Df(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return n},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},Nf.Axis.defaultConfig=function(t,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Nf.util={},Nf.DATAEXTENT="dataExtent",Nf.AREA="AreaChart",Nf.LINE="LinePlot",Nf.DOT="DotPlot",Nf.BAR="BarChart",Nf.util._override=function(e,t){for(var r in e)r in t&&(t[r]=e[r])},Nf.util._extend=function(e,t){for(var r in e)t[r]=e[r]},Nf.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Nf.util.dataFromEquation2=function(t,r){var n=r||6;return e.range(0,360+n,n).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},Nf.util.dataFromEquation=function(t,r,n){var a=r||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,r){var n=e*Math.PI/180,a=t(n);i.push(e),o.push(a)});var l={t:i,r:o};return n&&(l.name=n),l},Nf.util.ensureArray=function(t,r){if(void 0===t)return null;var n=[].concat(t);return e.range(r).map(function(e,t){return n[t]||n[0]})},Nf.util.fillArrays=function(e,t,r){return t.forEach(function(t,n){e[t]=Nf.util.ensureArray(e[t],r)}),e},Nf.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},Nf.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var r=t.shift();return e[r]&&(!t.length||objHasKeys(e[r],t))},Nf.util.sumArrays=function(t,r){return e.zip(t,r).map(function(t,r){return e.sum(t)})},Nf.util.arrayLast=function(e){return e[e.length-1]},Nf.util.arrayEqual=function(e,t){for(var r=Math.max(e.length,t.length,1);r-- >=0&&e[r]===t[r];);return-2===r},Nf.util.flattenArray=function(e){for(var t=[];!Nf.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},Nf.util.deduplicate=function(e){return e.filter(function(e,t,r){return r.indexOf(e)==t})},Nf.util.convertToCartesian=function(e,t){var r=t*Math.PI/180;return[e*Math.cos(r),e*Math.sin(r)]},Nf.util.round=function(e,t){var r=t||2,n=Math.pow(10,r);return Math.round(e*n)/n},Nf.util.getMousePos=function(t){var r=e.mouse(t.node()),n=r[0],a=r[1],i={};return i.x=n,i.y=a,i.pos=r,i.angle=180*(Math.atan2(a,n)+Math.PI)/Math.PI,i.radius=Math.sqrt(n*n+a*a),i},Nf.util.duplicatesCount=function(e){for(var t,r={},n={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(n,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(n,a,i)},"stroke-width":function(e,t){return p["stroke-width"](n,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](n,a,i)},opacity:function(e,t){return p.opacity(n,a,i)},display:function(e,t){return p.display(n,a,i)}})}};var f=r.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return r.radialScale(s+(e[2]||0))}).outerRadius(function(e){return r.radialScale(s+(e[2]||0))+r.radialScale(e[1])});c.arc=function(t,n,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(r.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,r,a){return n[t[a].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return void 0===t[n].data.visible||t[n].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[r.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),Df(t[r],Nf.PolyChart.defaultConfig()),Df(t[r],e)}),this):t},a.getColorScale=function(){},e.rebind(a,r,"on"),a},Nf.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},Nf.BarChart=function(){return Nf.PolyChart()},Nf.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Nf.AreaChart=function(){return Nf.PolyChart()},Nf.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Nf.DotPlot=function(){return Nf.PolyChart()},Nf.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Nf.LinePlot=function(){return Nf.PolyChart()},Nf.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Nf.Legend=function(){var t=Nf.Legend.defaultConfig(),r=e.dispatch("hover");function n(){var r=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,n){var a=Df({},r.elements[t]);return a.name=e,a.color=[].concat(r.elements[t].color)[n],a})}),i=e.merge(a);i=i.filter(function(e,t){return r.elements[t]&&(r.elements[t].visibleInLegend||void 0===r.elements[t].visibleInLegend)}),r.reverseOrder&&(i=i.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=r.fontSize,c=null==r.isContinuous?"number"==typeof i[0]:r.isContinuous,u=c?r.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,r){var n,a,i,o=t.symbol;return i=3*(a=s),"line"===(n=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(n)?e.svg.symbol().type(n).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?r.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?r.textColor:"none"}),x.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(e,t){return i[t].name}),n}return n.config=function(e){return arguments.length?(Df(t,e),this):t},e.rebind(n,r,"on"),n},Nf.Legend.defaultConfig=function(e,t){return{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:!1}}},Nf.tooltipPanel=function(){var t,r,n,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+Nf.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return n=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";r.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=r.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return n.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return Df(a,e),l},l},Nf.tooltipPanel.uid=1,Nf.adapter={},Nf.adapter.plotly=function(){var t={convert:function(t,r){var n={};if(t.data&&(n.data=t.data.map(function(e,t){var n=Df({},e);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(e,t){Nf.util.translator.apply(null,e.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&t.layout&&"stack"===t.layout.barmode)){var a=Nf.util.duplicates(n.data.map(function(e,t){return e.geometry}));n.data.forEach(function(e,t){var r=a.indexOf(e.geometry);-1!=r&&(n.data[t].groupId=r)})}if(t.layout){var i=Df({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){Nf.util.translator.apply(null,e.concat(r))}),r?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}r&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),n.layout=i}return n}};return t};var If,Rf=nt.extendDeepAll,Ff=If={};Ff.framework=function(t){var r,n,a,i,o,l=new function(){var e,t=[],r=-1,n=!1;function a(e,t){return e?(n=!0,e[t](),n=!1,this):this}return{add:function(e){return n?this:(t.splice(r+1,t.length-r),t.push(e),r=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var n=t[r];return n?(a(n,"undo"),r-=1,e&&e(n.undo),this):this},redo:function(){var n=t[r+1];return n?(a(n,"redo"),r+=1,e&&e(n.redo),this):this},clear:function(){t=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?Rf(r,n):n,a||(a=zf.Axis()),i=zf.adapter.plotly().convert(r),a.config(i).render(o),t.data=r.data,t.layout=r.layout,Ff.fillLayout(t),r}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return r},s.getLiveConfig=function(){return zf.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=zf.util.cloneJson(r);e=i,t=n,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),n=zf.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},Ff.fillLayout=function(t){var r=e.select(t).selectAll(".plot-container"),n=r.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:xt.background,_container:r,_paperdiv:n,_paper:a};t._fullLayout=Rf(i,t.layout)};var jf={};(jf=zf).manager=If;var Bf={},Hf=Tf.enforce,qf=Tf.clean,Vf=ia,Uf=0;function Gf(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){nt.error(e)}}function Yf(e,t){Gf(e,xt.combine(t,"white"))}function Xf(e,t){e._context||(e._context=nt.extendDeep({},_));var r,n,a,i=e._context;if(t){for(n=Object.keys(t),r=0;r=e.data.length||a<-e.data.length)throw new Error(r+" must be valid indices for gd.data.");if(t.indexOf(a,n+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+r+" must be unique.")}}function Qf(e,t,r){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),Wf(e,t,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&Wf(e,r,"newIndices"),void 0!==r&&t.length!==r.length)throw new Error("current and new indices must be of equal length.")}function Jf(e,t,n,a,i){!function(e,t,r,n){var a=nt.isPlainObject(n);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!nt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var i in Wf(e,r,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==r.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in n)||!Array.isArray(n[i])||n[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,t,n,a);for(var o=function(e,t,n,a){var i,o,l,s,c,u=nt.isPlainObject(a),f=[];for(var d in Array.isArray(n)||(n=[n]),n=Zf(n,e.data.length-1),t)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var A=_.parts[M],T=_.parts[M-1]+"."+A,L=_.parts.slice(0,M).join("."),C=nt.nestedProperty(e.layout,L).get(),S=nt.nestedProperty(o,L).get(),O=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===A?w:Kf(O);var P=An.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var z in P.impliedEdits)v(nt.relativeAttr(b,z),P.impliedEdits[z]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(T.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(T),nt.nestedProperty(o,L+"._inputRange").set(null);else if(T.match(/^[xyz]axis[0-9]*\.autorange$/)){x(T),nt.nestedProperty(o,L+"._inputRange").set(null);var E=nt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else T.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&nt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===A){var N=C,I="linear"===S.type&&"log"===w,R="log"===S.type&&"linear"===w;if(I||R){if(N&&N.range)if(S.autorange)I&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],j=N.range[1];I?(F<=0&&j<=0&&v(L+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(j)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,j)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],D.getComponentMethod("annotations","convertCoords")(e,S,w,v),D.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);nt.nestedProperty(o,L+"._inputRange").set(null)}else if(A.match(ht.AX_NAME_PATTERN)){var B=nt.nestedProperty(o,b).get(),H=(w||{}).type;H&&"-"!==H||(H="linear"),D.getComponentMethod("annotations","convertCoords")(e,B,H,v),D.getComponentMethod("images","convertCoords")(e,B,H,v)}var q=iu.containerArrayMatch(b);if(q){r=q.array,n=q.index;var V=q.property,U=(nt.nestedProperty(i,r)||[])[n]||{},G=U,Y=P||{editType:"calc"},X=-1!==Y.editType.indexOf("calcIfAutorange");""===n?(X?h.calc=!0:ar.update(h,Y),X=!1):""===V&&(G=w,iu.isAddVal(w)?g[b]=null:iu.isRemoveVal(w)?(g[b]=U,G=U):nt.warn("unrecognized full object value",t)),X&&(nd(e,G,"x")||nd(e,G,"y"))?h.calc=!0:ar.update(h,Y),c[r]||(c[r]={});var Z=c[r][n];Z||(Z=c[r][n]={}),Z[V]=w,delete t[b]}else"reverse"===A?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==O&&"select"!==O?h.plot=!0:P?ar.update(h,P):h.calc=!0,_.set(w))}}for(r in c){iu.applyContainerArrayChanges(e,nt.nestedProperty(i,r),c[r],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(n=0;n=0&&r=0&&r=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var r=0;return function(){if(e&&++r===t)return e()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(i,c){function u(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var t=n._currentFrame=n._frameQueue.shift();if(t){var r=t.name?t.name.toString():null;e._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=t.frameOpts.duration,Hn.transition(e,t.frame.data,t.frame.layout,Qc.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:r,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function f(){e.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var t=function(){n._animationRaf=window.requestAnimationFrame(t),Date.now()-n._lastFrameAt>n._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&nt.isPlainObject(t))v.push({type:"object",data:g(nt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;n--)if(nt.isPlainObject(t[n])){var d=t[n].name,h=(s[d]||f[d]||{}).name,p=t[n].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&Uf<5&&(Uf++,nt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===Uf&&nt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:Hn.supplyFrameDefaults(t[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:c+n})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;n--){if("number"==typeof(a=u[n].frame).name&&nt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;r--)n=t[r],i.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:a[n]});var l=Hn.modifyFrames,s=Hn.modifyFrames,c=[e,o],u=[e,i];return Zc&&Zc.add(e,l,c,s,u),Hn.modifyFrames(e,i)},Bf.purge=function(e){var t=(e=nt.getGraphDiv(e))._fullLayout||{},r=e._fullData||[];return Hn.cleanPlot([],{},r,t),Hn.purge(e),ki.purge(e),t._container&&t._container.remove(),delete e._context,e};var od={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},ld=yi.EventEmitter;var sd=function(e){var t=e.emitter||new ld,r=new Promise(function(n,a){var i=window.Image,o=e.svg,l=e.format||"png";if(nt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?r:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var r;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":r=c.toDataURL("image/jpeg");break;case"png":r=c.toDataURL("image/png");break;case"webp":r=c.toDataURL("image/webp");break;case"svg":r=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}n(r),e.promise||t.emit("success",r)},p.onerror=function(r){if(a(r),!e.promise)return t.emit("error",r)},p.src=g});return e.promise?r:t},cd=/"/g,ud=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var fd=function(r,n,a){var i,o=r._fullLayout,l=o._paper,s=o._toppaper,c=o.width,u=o.height;l.insert("rect",":first-child").call(Ur.setRect,0,0,c,u).call(xt.fill,o.paper_bgcolor);var f=o._basePlotModules||[];for(i=0;i")?"":r.html(e).text()});return r.remove(),n}(v),v=(v=v.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(ud,"'"),nt.isIE()&&(v=(v=(v=v.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),v},dd={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},hd=/^data:image\/\w+;base64,/;var pd=function(e,t){var r,n,a;function i(e){return!(e in t)||nt.validate(t[e],dd[e])}if(t=t||{},nt.isPlainObject(e)?(r=e.data||[],n=e.layout||{},a=e.config||{}):(e=nt.getGraphDiv(e),r=nt.extendDeep([],e.data),n=nt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,r){return nt.coerce(t,o,dd,e,r)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=nt.extendFlat({},n);c&&(g.width=c),u&&(g.height=u);var v=nt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=od.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,od.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var r=fd(p,s,f),n=p._fullLayout.width,a=p._fullLayout.height;if(Bf.purge(p),document.body.removeChild(p),"svg"===s)return e(h?r:"data:image/svg+xml,"+encodeURIComponent(r));var i=document.createElement("canvas");i.id=nt.randstr(),sd({format:s,width:n,height:a,scale:f,canvas:i,svg:r,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){Bf.plot(p,r,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(hd,""):e}(t))}).catch(function(e){t(e)})})},gd=nt.isPlainObject,vd=Array.isArray,yd=nt.isArrayOrTypedArray;function md(e,t,r,n,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&n.push(_d("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(vd(u[y])){u[y].length>f[y].length&&n.push(_d("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],nt.validate(x,m)?b!==x&&b!==+x&&n.push(_d("dynamic",a,c.concat(y,v),x,b)):n.push(_d("value",a,c.concat(y,v),x))}else n.push(_d("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],nt.validate(x,m)?b!==x&&b!==+x&&n.push(_d("dynamic",a,c.concat(y),x,b)):n.push(_d("value",a,c.concat(y),x))}else if(d.items&&!h&&vd(u)){var M,A,T=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(_d("object","layout"))),Hn.supplyDefaults(o);for(var l=o._fullData,s=r.length,c=0;c-1&&(l[c[r]].title="");for(r=0;rH||e[1]V)return[Zd(e[0],B,H),Zd(e[1],q,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===B||e[0]===H)||(e[1]===t[1]&&(e[1]===q||e[1]===V)||void 0)}function X(e,t,r){return function(n,a){var i=G(n),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*nt.constrain((n[e]+a[e])/2,t,r)-((i||n)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function Z(e){var t=e[0],r=e[1],n=t===L[C-1][0],a=r===L[C-1][1];if(!n||!a)if(C>1){var i=t===L[C-2][0],o=r===L[C-2][1];n&&(t===B||t===H)&&i?o?C--:L[C-1]=e:a&&(r===q||r===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&Z([E,N]),Z(e),I=null,E=N=0}function Q(e){if(z=e[0]H?H:0,D=e[1]V?V:0,z||D){if(C)if(I){var t=F(I,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else R=F(L[C-1],e)[0],L[C++]=R;else L[C++]=[z||e[0],D||e[1]];var r=L[C-1];z&&D&&(r[0]!==z||r[1]!==D)?(I&&(E!==z&&N!==D?Z(E&&N?(n=I,i=(a=e)[0]-n[0],o=(a[1]-n[1])/i,(n[1]*a[0]-a[1]*n[0])/i>0?[o>0?B:H,V]:[o>0?H:B,q]):[E||z,N||D]):E&&N&&Z([E,N])),Z([z,D])):E-z&&N-D&&Z([z||E,D||N]),I=e,E=z,N=D}else I&&W(F(I,e)[0]),L[C++]=e;var n,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var r=[],n=0,a=0;a<4;a++){var i=U[a],o=Xd(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&P(o,e)O(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;Q(l),n=l}}else Q(i)}I&&Z([E||I[0],N||I[1]]),A.push(L.slice(0,C))}return A},Qd=Iu.tester;function Jd(t,r,n,a,i,o,l){var s,c;!function(t,r,n,a,i){var o=n.xaxis,l=n.yaxis,s=e.extent(nt.simpleMap(o.range,o.r2c)),c=e.extent(nt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Vr.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var n=e[0].trace;Vr.hasMarkers(n)&&n.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=n.xaxis,h=n.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(D.getComponentMethod("errorbars","plot")(v,n,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),a[0].node3=v;var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,A,T,L,C,S,O,P,z="",E="",N=[],I=nt.noop;if(y=p._ownFill,Vr.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(A=Ur.steps(g.shape),T=Ur.steps(g.shape.split("").reverse().join(""))):A=T="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Ur.smoothclosed(e.slice(1),g.smoothing):Ur.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return T(e.reverse())},N=Wd(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=p._polygons=new Array(N.length),c=0;c1){var n=e.select(this);if(n.datum(a),t)f(n.style("opacity",0).attr("d",k).call(Ur.lineGroupStyle)).style("opacity",1);else{var i=f(n);i.attr("d",k),Ur.singleLineStyle(a,i)}}}}}var R=v.selectAll(".js-line").data(N);f(R.exit()).style("opacity",0).remove(),R.each(I(!1)),R.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Ur.lineGroupStyle).each(I(!0)),Ur.setClipUrl(R,n.layerClipId),N.length?(y?C&&O&&(x?("y"===x?C[1]=O[1]=h.c2p(0,!0):"x"===x&&(C[0]=O[0]=d.c2p(0,!0)),f(y).attr("d","M"+O+"L"+C+"L"+z.substr(1)).call(Ur.singleFillStyle)):f(y).attr("d",z+"Z").call(Ur.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&z&&b?("tonext"===p.fill?f(m).attr("d",z+"Z"+b+"Z").call(Ur.singleFillStyle):f(m).attr("d",z+"L"+b.substr(1)+"Z").call(Ur.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=P):(y?j(y):m&&j(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var r=!1===t[0].trace.cliponaxis;Ur.setClipUrl(e.select(this),r?null:n.layerClipId)})}function j(e){f(e).attr("d","M0,0Z")}function B(e){return e.filter(function(e){return e.vis})}function H(e){return e.id}function q(e){if(e.ids)return H}function V(){return!1}function U(r){var a,i=r[0].trace,o=e.select(this),l=Vr.hasMarkers(i),s=Vr.hasText(i),c=q(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?B:nt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?B:nt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Ur.pointStyle,i,t).call(Ur.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Ur.tryColorscale(i.marker,""),m=l&&Ur.tryColorscale(i.marker,"line");a.order(),a.each(function(r){var a=e.select(this),o=f(a);Ur.translatePoint(r,o,d,h)?(Ur.singlePointStyle(r,o,i,y,m,t),n.layerClipId&&Ur.hideOutsideRangePoint(r,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var r=e.select(this),a=f(r.select("text"));Ur.translatePoint(t,a,d,h)?n.layerClipId&&Ur.hideOutsideRangePoint(t,r,d,h,i.xcalendar,i.ycalendar):r.remove()}),a.selectAll("text").call(Ur.textPointStyle,i,t).each(function(t){var r=d.c2p(t.x),n=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:r,y:n})})}),a.exit().remove()}}function $d(e,t,r){var n=e.selectAll("path.point"),a=e.selectAll("text");Ur.pointStyle(n,t,r),Ur.textPointStyle(a,t,r),Ur.selectedPointStyle(n,t),Ur.selectedTextStyle(a,t)}var Kd=function(t,r){var n=r?r[0].node3:e.select(t).selectAll("g.trace.scatter");n.style("opacity",function(e){return e[0].trace.opacity}),n.selectAll("g.points").each(function(r){$d(e.select(this),r.trace||r[0].trace,t)}),n.selectAll("g.trace path.js-line").call(Ur.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(Ur.fillGroupStyle),D.getComponentMethod("errorbars","style")(n)},eh={};eh.hasLines=Vr.hasLines,eh.hasMarkers=Vr.hasMarkers,eh.hasText=Vr.hasText,eh.isBubble=Vr.isBubble,eh.attributes=yn,eh.supplyDefaults=function(e,t,r,n){function a(r,n){return nt.coerce(e,t,yn,r,n)}var i=ci(e,t,n,a),o=i=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===r.xaxis&&i.yaxis===r.yaxis){i.opacity=void 0;break}}}}},eh.calc=qd,eh.arraysToCalcdata=Id,eh.plot=function(t,r,n,a,i){var o,l,s,c,u=r.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(n,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,r){var n,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){Jd(t,i,r,e,n,this,a)})})):u.selectAll("g.trace").each(function(e,i){Jd(t,i,r,e,n,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()},eh.colorbar=Eo,eh.style=Kd,eh.hoverPoints=function(e,t,r,n){var a=e.cd,i=a[0].trace,o=e.xa,l=e.ya,s=o.c2p(t),c=l.c2p(r),u=[s,c],f=i.hoveron||"",d=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var h=function(e){var t=Math.max(d,e.mrc||0),r=o.c2p(e.x)-s,n=l.c2p(e.y)-c;return Math.max(Math.sqrt(r*r+n*n)-t,1-d/t)},p=eo.getDistanceFunction(n,function(e){var t=Math.max(3,e.mrc||0),r=1-1/t,n=Math.abs(o.c2p(e.x)-s);return nI!=(L=w[b][1])>=I&&(M=w[b-1][0],A=w[b][0],L-T&&(k=M+(A-M)*(I-T)/(L-T),P=Math.min(P,k),z=Math.max(z,k)));P=Math.max(P,0),z=Math.min(z,o._length);var R=xt.defaultLine;return xt.opacity(i.fillcolor)?R=i.fillcolor:xt.opacity((i.line||{}).color)&&(R=i.line.color),nt.extendFlat(e,{distance:e.maxHoverDistance,x0:P,x1:z,y0:I,y1:I,color:R}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},eh.selectPoints=function(e,t){var r,n,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Vr.hasMarkers(u)&&!Vr.hasText(u))return[];if(!1===t)for(r=0;r0?1:-1)/2,y:i/(1+r*r/(n*n)),outside:!0}}var kh={};kh.attributes=fh,kh.supplyDefaults=function(e,t,r,n){function a(r,n){return nt.coerce(e,t,fh,r,n)}var i=nt.coerceFont,o=a("values"),l=a("labels");if(!Array.isArray(l)){if(!nt.isArrayOrTypedArray(o)||!o.length)return void(t.visible=!1);a("label0"),a("dlabel")}a("marker.line.width")&&a("marker.line.color"),a("marker.colors"),a("scalegroup");var s=a("text"),c=a("textinfo",Array.isArray(s)?"text+percent":"percent");if(a("hovertext"),c&&"none"!==c){var u=a("textposition"),f=Array.isArray(u)||"auto"===u,d=f||"inside"===u,h=f||"outside"===u;if(d||h){var p=i(a,"textfont",n.font);d&&i(a,"insidetextfont",p),h&&i(a,"outsidetextfont",p)}}yh(t,n,a),a("hole"),a("sort"),a("direction"),a("rotation"),a("pull")},kh.supplyLayoutDefaults=function(e,t){var r,n;r="hiddenlabels",nt.coerce(e,t,mh,r,n)},kh.layoutAttributes=mh,kh.calc=function(e,t){var n,a,i,o,l,c=t.values,u=ph(c)&&c.length,f=t.labels,d=t.marker.colors||[],h=[],p=e._fullLayout,g=p.colorway,v=p._piecolormap,y={},m=0,x=p.hiddenlabels||[];if(p._piecolorway||g===xt.defaults||(p._piecolorway=vh(g)),t.dlabel)for(f=new Array(c.length),n=0;n")}}return h},kh.plot=function(t,r){var n=t._fullLayout;!function(e,t){var r,n,a,i,o,l,s,c,u,f=[];for(a=0;as&&(s=l.pull[i]);o.r=Math.min(r,n)/(2+2*s),o.cx=t.l+t.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=t.t+t.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;ia.vTotal/2?1:0)}(r),a.each(function(){var a=e.select(this).selectAll("g.slice").data(r);a.enter().append("g").classed("slice",!0),a.exit().remove();var l=[[[],[]],[[],[]]],s=!1;a.each(function(r){if(r.hidden)e.select(this).selectAll("path,g").remove();else{r.pointNumber=r.i,r.curveNumber=o.index,l[r.pxmid[1]<0?0:1][r.pxmid[0]<0?0:1].push(r);var a=i.cx,c=i.cy,u=e.select(this),f=u.selectAll("path.surface").data([r]),d=!1,h=!1;if(f.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),u.select("path.textline").remove(),u.on("mouseover",function(){var l=t._fullLayout,s=t._fullData[o.index];if(!t._dragging&&!1!==l.hovermode){var u=s.hoverinfo;if(Array.isArray(u)&&(u=eo.castHoverinfo({hoverinfo:[es.castOption(u,r.pts)],_module:o._module},l,0)),"all"===u&&(u="label+text+value+percent+name"),"none"!==u&&"skip"!==u&&u){var f=_h(r,i),p=a+r.pxmid[0]*(1-f),g=c+r.pxmid[1]*(1-f),v=n.separators,y=[];if(-1!==u.indexOf("label")&&y.push(r.label),-1!==u.indexOf("text")){var m=es.castOption(s.hovertext||s.text,r.pts);m&&y.push(m)}-1!==u.indexOf("value")&&y.push(es.formatPieValue(r.v,v)),-1!==u.indexOf("percent")&&y.push(es.formatPiePercent(r.v/i.vTotal,v));var x=o.hoverlabel,b=x.font;eo.loneHover({x0:p-f*i.r,x1:p+f*i.r,y:g,text:y.join("
"),name:-1!==u.indexOf("name")?s.name:void 0,idealAlign:r.pxmid[0]<0?"left":"right",color:es.castOption(x.bgcolor,r.pts)||r.color,borderColor:es.castOption(x.bordercolor,r.pts),fontFamily:es.castOption(b.family,r.pts),fontSize:es.castOption(b.size,r.pts),fontColor:es.castOption(b.color,r.pts)},{container:l._hoverlayer.node(),outerContainer:l._paper.node(),gd:t}),d=!0}t.emit("plotly_hover",{points:[bh(r,s)],event:e.event}),h=!0}}).on("mouseout",function(n){var a=t._fullLayout,i=t._fullData[o.index];h&&(n.originalEvent=e.event,t.emit("plotly_unhover",{points:[bh(r,i)],event:e.event}),h=!1),d&&(eo.loneUnhover(a._hoverlayer.node()),d=!1)}).on("click",function(){var n=t._fullLayout,a=t._fullData[o.index];t._dragging||!1===n.hovermode||(t._hoverdata=[bh(r,a)],eo.click(t,e.event))}),o.pull){var p=+es.castOption(o.pull,r.pts)||0;p>0&&(a+=p*r.pxmid[0],c+=p*r.pxmid[1])}r.cxFinal=a,r.cyFinal=c;var g=o.hole;if(r.v===i.vTotal){var v="M"+(a+r.px0[0])+","+(c+r.px0[1])+_(r.px0,r.pxmid,!0,1)+_(r.pxmid,r.px0,!0,1)+"Z";g?f.attr("d","M"+(a+g*r.px0[0])+","+(c+g*r.px0[1])+_(r.px0,r.pxmid,!1,g)+_(r.pxmid,r.px0,!1,g)+"Z"+v):f.attr("d",v)}else{var y=_(r.px0,r.px1,!0,1);if(g){var m=1-g;f.attr("d","M"+(a+g*r.px1[0])+","+(c+g*r.px1[1])+_(r.px1,r.px0,!1,g)+"l"+m*r.px0[0]+","+m*r.px0[1]+y+"Z")}else f.attr("d","M"+a+","+c+"l"+r.px0[0]+","+r.px0[1]+y+"Z")}var x=es.castOption(o.textposition,r.pts),b=u.selectAll("g.slicetext").data(r.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var n=e.select(this).selectAll("text").data([0]);n.enter().append("text").attr("data-notex",1),n.exit().remove(),n.text(r.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Ur.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(mr.convertToTspans,t);var l,u=Ur.bBox(n.node());"outside"===x?l=wh(u,r):(l=function(e,t,r){var n=Math.sqrt(e.width*e.width+e.height*e.height),a=e.width/e.height,i=Math.PI*Math.min(t.v/r.vTotal,.5),o=1-r.trace.hole,l=_h(t,r),s={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),f={scale:2*u/e.height,rCenter:Math.cos(u/r.r)-u*a/r.r,rotate:(180/Math.PI*t.midangle+720)%180-90},d=1/a,h=d+1/(2*Math.tan(i)),p=r.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(d*d+o/2)+d)),g={scale:2*p/e.width,rCenter:Math.cos(p/r.r)-p/a/r.r,rotate:(180/Math.PI*t.midangle+810)%180-90},v=g.scale>f.scale?g:f;return s.scale<1&&v.scale>s.scale?v:s}(u,r,i),"auto"===x&&l.scale<1&&(n.call(Ur.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(u=Ur.bBox(n.node())),l=wh(u,r)));var f=a+r.pxmid[0]*l.rCenter+(l.x||0),d=c+r.pxmid[1]*l.rCenter+(l.y||0);l.outside&&(r.yLabelMin=d-u.height/2,r.yLabelMid=d,r.yLabelMax=d+u.height/2,r.labelExtraX=0,r.labelExtraY=0,s=!0),n.attr("transform","translate("+f+","+d+")"+(l.scale<1?"scale("+l.scale+")":"")+(l.rotate?"rotate("+l.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function _(e,t,n,a){return"a"+a*i.r+","+a*i.r+" 0 "+r.largeArc+(n?" 1 ":" 0 ")+a*(t[0]-e[0])+","+a*(t[1]-e[1])}}),s&&function(e,t){var r,n,a,i,o,l,s,c,u,f,d,h,p;function g(e,t){return e.pxmid[1]-t.pxmid[1]}function v(e,t){return t.pxmid[1]-e.pxmid[1]}function y(e,r){r||(r={});var a,c,u,d,h,p,g=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),v=n?e.yLabelMin:e.yLabelMax,y=n?e.yLabelMax:e.yLabelMin,m=e.cyFinal+o(e.px0[1],e.px1[1]),x=g-v;if(x*s>0&&(e.labelExtraY=x),Array.isArray(t.pull))for(c=0;c=(es.castOption(t.pull,u.pts)||0)||((e.pxmid[1]-u.pxmid[1])*s>0?(d=u.cyFinal+o(u.px0[1],u.px1[1]),(x=d-v-e.labelExtraY)*s>0&&(e.labelExtraY+=x)):(y+e.labelExtraY-m)*s>0&&(a=3*l*Math.abs(c-f.indexOf(e)),h=u.cxFinal+i(u.px0[0],u.px1[0]),(p=h+a-(e.cxFinal+e.pxmid[0])-e.labelExtraX)*l>0&&(e.labelExtraX+=p)))}for(n=0;n<2;n++)for(a=n?g:v,o=n?Math.max:Math.min,s=n?1:-1,r=0;r<2;r++){for(i=r?Math.max:Math.min,l=r?1:-1,(c=e[n][r]).sort(a),u=e[1-n][r],f=u.concat(c),h=[],d=0;dMath.abs(c)?i+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):i+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else i+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;r.append("path").classed("textline",!0).call(xt.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:i,fill:"none"})}})})}),setTimeout(function(){a.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},kh.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var r=t[0].trace,n=e.select(this);n.style({opacity:r.opacity}),n.selectAll("path.surface").each(function(t){e.select(this).call(rs,t,r)})})},kh.styleOne=rs,kh.moduleType="trace",kh.name="pie",kh.basePlotModule=dh,kh.categories=["pie","showLegend"],kh.meta={};var Mh=kh;return lh.register([Io,Mh]),lh}); \ No newline at end of file +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},n=[].slice,r=function(e){return n.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{r(a.documentElement.childNodes)[0].nodeType}catch(e){r=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,n){c.call(this,e,t,n+"")},u.setProperty=function(e,t,n){f.call(this,e,t+"",n)}}function d(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},t.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},t.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,n){return d(e(t),n)}:e)},t.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},t.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},t.pairs=function(e){for(var t=0,n=e.length-1,r=e[0],a=new Array(n<0?0:n);t=0;)for(t=(r=e[a]).length;--t>=0;)n[--o]=r[t];return n};var m=Math.abs;function x(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n==1/0)throw new Error("infinite range");var r,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(n)),o=-1;if(e*=i,t*=i,(n*=i)<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=a.length)return n?n.call(r,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var r=[],o=i[n++];return t.forEach(function(t,a){r.push({key:t,values:e(a,n)})}),o?r.sort(function(e,t){return o(e.key,t.key)}):r}(o(t.map,e,0),0)},r.key=function(e){return a.push(e),r},r.sortKeys=function(e){return i[a.length-1]=e,r},r.sortValues=function(t){return e=t,r},r.rollup=function(e){return n=e,r},r},t.set=function(e){var t=new O;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},t.event=null,t.requote=function(e){return e.replace(H,"\\$&")};var H=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]};function V(e){return q(e,X),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var n=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}X.select=function(e){var t,n,r,a,i=[];e=Z(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),J.hasOwnProperty(n)?{space:J[n],local:e}:e}},X.attr=function(e,n){if(arguments.length<2){if("string"==typeof e){var r=this.node();return(e=t.ns.qualify(e)).local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}for(n in e)this.each($(n,e[n]));return this}return this.each($(e,n))},X.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=te(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},X.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?n?function(){var t=l(n,r(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:c:n?R:function(){var n,r=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(n=a.match(r)){var i=this[a];this.removeEventListener(n[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=X.append,de.empty=X.empty,de.node=X.node,de.call=X.call,de.size=X.size,de.select=function(e){for(var t,n,r,a,i,o=[],l=-1,s=this.length;++l=r&&(r=t+1);!(o=l[r])&&++r0?1:e<0?-1:0}function ze(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function De(e){return e>1?0:e<-1?Ae:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Re(e){return((e=Math.exp(e))+1/e)/2}function Ne(e){return(e=Math.sin(e/2))*e}var Ie=Math.SQRT2;t.interpolateZoom=function(e,t){var n,r,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function O(e){--v||(e({type:"zoomend"}),n=null)}function P(){var e=this,n=_.of(e,arguments),r=0,a=t.select(o(e)).on(m,function(){r=1,A(t.mouse(e),i),S(n)}).on(x,function(){a.on(m,null).on(x,null),l(r),O(n)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(n)}function z(){var e,n=this,r=_.of(n,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(n),h=xe(n);function p(){var r=t.touches(n);return e=d.k,r.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),r}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var r=t.event.changedTouches,o=0,f=r.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(n);ll.call(n);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?r+(a-r)*e/60:e<180?a:e<240?r+(a-r)*(240-e)/60:r}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,r=2*(n=n<0?0:n>1?1:n)-(a=n<=.5?n*(1+t):n+t-n*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,n,r){return this instanceof Ge?(this.h=+e,this.c=+n,void(this.l=+r)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Ze?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,n,r)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new He;function Xe(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Ze(n,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Ze(e,t,n){return this instanceof Ze?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof Ze?new Ze(e.l,e.a,e.b):e instanceof Ge?Xe(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Ze(e,t,n)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Xe(this.h,this.c,this.l).rgb()},t.lab=Ze;var We=18,Qe=.95047,Je=1,$e=1.08883,Ke=Ze.prototype=new He;function et(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return new it(at(3.2404542*(a=nt(a)*Qe)-1.5371385*(r=nt(r)*Je)-.4985314*(i=nt(i)*$e)),at(-.969266*a+1.8760108*r+.041556*i),at(.0556434*a-.2040259*r+1.0572252*i))}function tt(e,t,n){return e>0?new Ge(Math.atan2(n,t)*Oe,Math.sqrt(t*t+n*n),e):new Ge(NaN,NaN,e)}function nt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function rt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,n){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,n)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Ze(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Ze(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new He;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new qe(r,a,s)}function dt(e,t,n){var r=rt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(n=ht(n)))/Qe),a=rt((.2126729*e+.7151522*t+.072175*n)/Je);return Ze(116*a-16,500*(r-a),200*(a-rt((.0193339*e+.119192*t+.9503041*n)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,a=30;return t||n||r?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var n=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=n}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(n=null==e?null:e+"",o):n},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),c.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=n&&c.overrideMimeType&&c.overrideMimeType(n),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==r?null:r),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(P),t.dsv=function(e,t){var n=new RegExp('["'+e+"\n]"),r=e.charCodeAt(0);function a(e,n,r){arguments.length<3&&(r=n,n=null);var a=mt(e,t,null==n?i:o(n),r);return a.row=function(e){return arguments.length?a.response(null==(n=e)?i:o(e)):n},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return n.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var n;return a.parseRows(e,function(e,r){if(n)return n(e,r-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(a(e),n)}:a})},a.parseRows=function(e,t){var n,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(At,t)),_t=0):(_t=1,kt(At))}function Tt(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}});t.formatPrefix=function(e,n){var r=0;return(e=+e)&&(e<0&&(e*=-1),n&&(e=t.round(e,Ct(e,n))),r=1+Math.floor(1e-12+Math.log(e)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),St[8+r/3]};var Ot=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pt=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,n){return(e=t.round(e,Ct(e,n))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),n))))}});function zt(e){return e+""}var Dt=t.time={},Et=Date;function Rt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Rt.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(){Nt.setUTCDate.apply(this._,arguments)},setDay:function(){Nt.setUTCDay.apply(this._,arguments)},setFullYear:function(){Nt.setUTCFullYear.apply(this._,arguments)},setHours:function(){Nt.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Nt.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Nt.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Nt.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Nt.setUTCSeconds.apply(this._,arguments)},setTime:function(){Nt.setTime.apply(this._,arguments)}};var Nt=Date.prototype;function It(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o68?1900:2e3),n+a[0].length):-1}function Qt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Jt(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function $t(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Kt(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function en(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function tn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function nn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function rn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function an(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=m(t)/60|0,a=m(t)%60;return n+qt(r,"0",2)+qt(a,"0",2)}function on(e,t,n){Ht.lastIndex=0;var r=Ht.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ln(e){for(var t=e.length,n=-1;++n0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(n-=l,n+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(r)}:P;return function(e){var r=Ot.exec(e),a=r[1]||" ",l=r[2]||">",s=r[3]||"-",c=r[4]||"",u=r[5],f=+r[6],d=r[7],h=r[8],p=r[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=Pt.get(p)||zt;var b=u&&d;return function(e){var r=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),r=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=n+e.substring(k+1);!u&&d&&(_=o(_,1/0));var A=v.length+_.length+w.length+(b?0:i.length),T=A"===l?T+i+e:"^"===l?T.substring(0,A>>=1)+i+e+T.substring(A):i+(b?e:T+e))+r}}}(e),timeFormat:function(e){var n=e.dateTime,r=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function n(n){for(var r,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in jt?t.charAt(l++):o])||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}u.utc=function(e){var t=u(e);function n(e){try{var n=new(Et=Rt);return n._=e,t(n)}finally{Et=Date}}return n.parse=function(e){try{Et=Rt;var n=t.parse(e);return n&&n._}finally{Et=Date}},n.toString=t.toString,n},u.multi=u.utc.multi=ln;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(n),d:function(e,t){return qt(e.getDate(),t,2)},e:function(e,t){return qt(e.getDate(),t,2)},H:function(e,t){return qt(e.getHours(),t,2)},I:function(e,t){return qt(e.getHours()%12||12,t,2)},j:function(e,t){return qt(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return qt(e.getMilliseconds(),t,3)},m:function(e,t){return qt(e.getMonth()+1,t,2)},M:function(e,t){return qt(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return qt(e.getSeconds(),t,2)},U:function(e,t){return qt(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return qt(Dt.mondayOfYear(e),t,2)},x:u(r),X:u(a),y:function(e,t){return qt(e.getFullYear()%100,t,2)},Y:function(e,t){return qt(e.getFullYear()%1e4,t,4)},Z:an,"%":function(){return"%"}},w={a:function(e,t,n){g.lastIndex=0;var r=g.exec(t.slice(n));return r?(e.w=v.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(e,t,n){h.lastIndex=0;var r=h.exec(t.slice(n));return r?(e.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.m=m.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(e,t,n){return f(e,_.c.toString(),t,n)},d:$t,e:$t,H:en,I:en,j:Kt,L:rn,m:Jt,M:tn,p:function(e,t,n){var r=d.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)},S:nn,U:Yt,w:Gt,W:Xt,x:function(e,t,n){return f(e,_.x.toString(),t,n)},X:function(e,t,n){return f(e,_.X.toString(),t,n)},y:Wt,Y:Zt,Z:Qt,"%":on};return u}(e)}};var sn=t.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"]});function cn(){}t.format=sn.numberFormat,t.geo={},cn.prototype={s:0,t:0,add:function(e){fn(e,this.t,un),fn(un.s,this.s,this),this.s?this.t+=un.t:this.s=un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var un=new cn;function fn(e,t,n){var r=n.s=e+t,a=r-e,i=r-a;n.t=e-i+(t-a)}function dn(e,t){e&&pn.hasOwnProperty(e.type)&&pn[e.type](e,t)}t.geo.stream=function(e,t){e&&hn.hasOwnProperty(e.type)?hn[e.type](e,t):dn(e,t)};var hn={Feature:function(e,t){dn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++r=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=r*s+u*Math.cos(l),d=u*o*Math.sin(l);Sn.add(Math.atan2(d,f)),n=e,r=s,a=c}On.point=function(o,l){On.point=i,n=(e=o)*Se,r=Math.cos(l=(t=l)*Se/2+Ae/4),a=Math.sin(l)},On.lineEnd=function(){i(e,t)}}function zn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function Dn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function En(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Rn(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Nn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function In(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Fn(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function jn(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(n=-90),f[0]=e,f[1]=r}};function h(t,i){u.push(f=[e=t,r=t]),ia&&(a=i)}function p(t,o){var l=zn([t*Se,o*Se]);if(s){var c=En(s,l),u=En([c[1],-c[0],0],c);In(u),u=Fn(u);var f=t-i,d=f>0?1:-1,p=u[0]*Oe*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t):r>=e?(tr&&(r=t)):t>i?_(e,t)>_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=r,d.point=h,s=null}function y(e,t){if(s){var n=e-i;c+=m(n)>180?n+(n>0?360:-360):n}else o=e,l=t;On.point(e,t),p(e,t)}function x(){On.lineStart()}function b(){y(o,l),On.lineEnd(),m(c)>ke&&(e=-(r=180)),f[0]=e,f[1]=r,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],r=g[1])}return u=f=null,e===1/0||n===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,n],[r,a]]}}(),t.geo.centroid=function(e){mn=xn=bn=_n=wn=kn=Mn=An=Tn=Ln=Cn=0,t.geo.stream(e,Bn);var n=Tn,r=Ln,a=Cn,i=n*n+r*r+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else r(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Wn(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r=0?1:-1,k=w*_,M=k>Ae,A=p*x;if(Sn.add(Math.atan2(A*w*Math.sin(k),g*b+A*Math.cos(k))),i+=M?_+w*Te:_,M^d>=n^y>=n){var T=En(zn(f),zn(e));In(T);var L=En(a,T);In(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(r>C||r===C&&(T[0]||T[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&n.push(n.pop().concat(n.shift())),l.push(n.filter($n))}return u}}function $n(e){return e.length>1}function Kn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:R,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function er(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var tr=Jn(Xn,function(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Ae:-Ae,s=m(i-n);m(s-Ae)0?Ce:-Ce),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Ae&&(m(n-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}(n,r,i,o),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),t=0),e.point(n=i,r=o),a=l},lineEnd:function(){e.lineEnd(),n=r=NaN},clean:function(){return 2-t}}},function(e,t,n,r){var a;if(null==e)a=n*Ce,r.point(-Ae,a),r.point(0,a),r.point(Ae,a),r.point(Ae,0),r.point(Ae,-a),r.point(0,-a),r.point(-Ae,-a),r.point(-Ae,0),r.point(-Ae,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rr=1e9;function ar(e,n,r,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=Kn(),w=nr(e,n,r,a),k={point:T,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=T,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var n=function(e){for(var t=0,n=u.length,r=e[1],a=0;ar&&ze(c,i,e)>0&&++t:i[1]<=r&&ze(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),r=x&&n,i=c.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Zn(c,o,n,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:r,u>1?a:n)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function A(t,i){return e<=t&&t<=r&&n<=i&&i<=a}function T(e,t){A(e,t)&&s.point(e,t)}function L(e,t){var n=A(e=Math.max(-rr,Math.min(rr,e)),t=Math.max(-rr,Math.min(rr,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=n,m=!1,n&&(s.lineStart(),s.point(e,t));else if(n&&y)s.point(e,t);else{var r={a:{x:g,y:v},b:{x:e,y:t}};w(r)?(y||(s.lineStart(),s.point(r.a.x,r.a.y)),s.point(r.b.x,r.b.y),n||s.lineEnd(),x=!1):n&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=n}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-r)0?2:1:m(t[1]-n)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}}function ir(e){var t=0,n=Ae/3,r=Lr(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Ae/180,n=e[1]*Ae/180):[t/Ae*180,n/Ae*180]},a}function or(e,t){var n=Math.sin(e),r=(n+Math.sin(t))/2,a=1+n*(2*r-n),i=Math.sqrt(a)/r;function o(e,t){var n=Math.sqrt(a-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),i-n*Math.cos(e)]}return o.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,Ee((a-(e*e+n*n)*r*r)/(2*r))]},o}t.geo.clipExtent=function(){var e,t,n,r,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=ar(e=+l[0][0],t=+l[0][1],n=+l[1][0],r=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return ir(or)}).raw=or,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,n,r,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,n){e=[t,n]}};function c(t){var i=t[0],o=t[1];return e=null,n(i,o),e||(r(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),n=i.translate(),r=(e[0]-n[0])/t,a=(e[1]-n[1])/t;return(a>=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return n=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,r=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var lr,sr,cr,ur,fr,dr,hr={point:R,lineStart:R,lineEnd:R,polygonStart:function(){sr=0,hr.lineStart=pr},polygonEnd:function(){hr.lineStart=hr.lineEnd=hr.point=R,lr+=m(sr/2)}};function pr(){var e,t,n,r;function a(e,t){sr+=r*e-n*t,n=e,r=t}hr.point=function(i,o){hr.point=a,e=n=i,t=r=o},hr.lineEnd=function(){a(e,t)}}var gr={point:function(e,t){efr&&(fr=e);tdr&&(dr=t)},lineStart:R,lineEnd:R,polygonStart:R,polygonEnd:R};function vr(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yr,mr={point:xr,lineStart:br,lineEnd:_r,polygonStart:function(){mr.lineStart=wr},polygonEnd:function(){mr.point=xr,mr.lineStart=br,mr.lineEnd=_r}};function xr(e,t){bn+=e,_n+=t,++wn}function br(){var e,t;function n(n,r){var a=n-e,i=r-t,o=Math.sqrt(a*a+i*i);kn+=o*(e+n)/2,Mn+=o*(t+r)/2,An+=o,xr(e=n,t=r)}mr.point=function(r,a){mr.point=n,xr(e=r,t=a)}}function _r(){mr.point=xr}function wr(){var e,t,n,r;function a(e,t){var a=e-n,i=t-r,o=Math.sqrt(a*a+i*i);kn+=o*(n+e)/2,Mn+=o*(r+t)/2,An+=o,Tn+=(o=r*e-n*t)*(n+e),Ln+=o*(r+t),Cn+=3*o,xr(n=e,r=t)}mr.point=function(i,o){mr.point=a,xr(e=n=i,t=r=o)},mr.lineEnd=function(){a(e,t)}}function kr(e){var t=.5,n=Math.cos(30*Se),r=16;function a(t){return(r?function(t){var n,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(n,r){n=e(n,r),t.point(n[0],n[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(n,a){var o=zn([n,a]),l=e(n,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=n,h=o[0],p=o[1],g=o[2],r,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(n=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,n,l,s,c,r,t),v.lineEnd=b,b()}return v}:function(t){return Ar(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})})(t)}function i(r,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-r,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,A=Math.sqrt(w*w+k*k+M*M),T=Math.asin(M/=A),L=m(m(M)-1)t||m((x*P+b*z)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mr(e){this.stream=e}function Ar(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Tr(e){return Lr(function(){return e})()}function Lr(e){var n,r,a,i,o,l,s=kr(function(e,t){return[(e=n(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=tr,x=P,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Oe,e[1]*Oe]}function M(){a=Yn(r=Pr(p,g,v),n);var e=n(d,h);return i=u-e[0]*c,o=f+e[1]*c,A()}function A(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cr(y(r,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,tr):function(e){var t=Math.cos(e),n=t>0,r=m(t)>ke;return Jn(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=n?g?0:o(f,d):g?o(f+(f<0?Ae:-Ae),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(jn(t,h)||jn(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(r&&t&&n^g){var y;v&l||!(y=i(p,t,!0))||(u=0,n?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&jn(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Rr(e,6*Se),n?[0,-e]:[-Ae,e-Ae]);function a(e,n){return Math.cos(e)*Math.cos(n)>t}function i(e,n,r){var a=[1,0,0],i=En(zn(e),zn(n)),o=Dn(i,i),l=i[0],s=o-l*l;if(!s)return!r&&e;var c=t*o/s,u=-t*l/s,f=En(a,i),d=Nn(a,c);Rn(d,Nn(i,u));var h=f,p=Dn(d,h),g=Dn(h,h),v=p*p-g*(Dn(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=Nn(h,(-p-y)/g);if(Rn(x,d),x=Fn(x),!r)return x;var b,_=e[0],w=n[0],k=e[1],M=n[1];w<_&&(b=_,_=w,w=b);var A=w-_,T=m(A-Ae)0^x[1]<(m(x[0]-_)Ae^(_<=x[0]&&x[0]<=w)){var L=Nn(h,(-p+y)/g);return Rn(L,d),[x,Fn(L)]}}}function o(t,r){var a=n?e:Ae-e,i=0;return t<-a?i|=1:t>a&&(i|=2),r<-a?i|=4:r>a&&(i|=8),i}}((b=+e)*Se),A()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?ar(e[0][0],e[0][1],e[1][0],e[1][1]):P,A()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Se,h=e[1]%360*Se,M()):[d*Oe,h*Oe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*Oe,g*Oe,v*Oe]},t.rebind(w,s,"precision"),function(){return n=e.apply(this,arguments),w.invert=n.invert&&k,M()}}function Cr(e){return Ar(e,function(t,n){e.point(t*Se,n*Se)})}function Sr(e,t){return[e,t]}function Or(e,t){return[e>Ae?e-Te:e<-Ae?e+Te:e,t]}function Pr(e,t,n){return e?t||n?Yn(Dr(e),Er(t,n)):Dr(e):t||n?Er(t,n):Or}function zr(e){return function(t,n){return[(t+=e)>Ae?t-Te:t<-Ae?t+Te:t,n]}}function Dr(e){var t=zr(e);return t.invert=zr(-e),t}function Er(e,t){var n=Math.cos(e),r=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*n+l*r;return[Math.atan2(s*a-u*i,l*n-c*r),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*n+u*r),Ee(u*n-l*r)]},o}function Rr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=Nr(n,a),i=Nr(n,i),(o>0?ai)&&(a+=o*Te)):(a=e+o*Te,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=Oe,t[1]*=Oe,t},t},Or.invert=Sr,t.geo.circle=function(){var e,t,n=[0,0],r=6;function a(){var e="function"==typeof n?n.apply(this,arguments):n,r=Pr(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=r(e,t)),e[0]*=Oe,e[1]*=Oe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(n=e,a):n},a.angle=function(n){return arguments.length?(t=Rr((e=+n)*Se,r*Se),a):e},a.precision=function(n){return arguments.length?(t=Rr(e*Se,(r=+n)*Se),a):r},a.angle(90)},t.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((n=f*o)*n+(n=c*u-s*f*l)*n),s*u+c*f*l)},t.geo.graticule=function(){var e,n,r,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,r,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(n/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(r).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],r=+e[1][0],s=+e[0][1],l=+e[1][1],a>r&&(e=a,a=r,r=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[r,l]]},x.minorExtent=function(t){return arguments.length?(n=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],n>e&&(t=n,n=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[n,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Ir(o,i,90),u=Fr(n,e,y),f=Ir(s,l,90),d=Fr(a,r,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,n,r=jr,a=Br;function i(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||r.apply(this,arguments),n||a.apply(this,arguments))},i.source=function(t){return arguments.length?(r=t,e="function"==typeof t?null:t,i):r},i.target=function(e){return arguments.length?(a=e,n="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return n=e[0]*Se,r=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(r),l=Math.sin(r),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(n),f=o*Math.sin(n),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ne(i-r)+o*s*Ne(a-n))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,n=Math.sin(p-e)*g,r=n*u+t*d,a=n*f+t*h,i=n*l+t*c;return[Math.atan2(a,r)*Oe,Math.atan2(i,Math.sqrt(r*r+a*a))*Oe]}:function(){return[n*Oe,r*Oe]}).distance=p,v;var n,r,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yr=0,t.geo.stream(e,Hr),yr};var Hr={sphere:R,point:R,lineStart:function(){var e,t,n;function r(r,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((r*=Se)-e),s=Math.cos(l);yr+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=n*i-t*o*s)*l),t*i+n*o*s),e=r,t=i,n=o}Hr.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),n=Math.cos(i),Hr.point=r},Hr.lineEnd=function(){Hr.point=Hr.lineEnd=R}},lineEnd:R,polygonStart:R,polygonEnd:R};function qr(e,t){function n(t,n){var r=Math.cos(t),a=Math.cos(n),i=e(r*a);return[i*a*Math.sin(t),i*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),a=t(r),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,r*o),Math.asin(r&&n*i/r)]},n}var Vr=qr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Tr(Vr)}).raw=Vr;var Ur=qr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},P);function Gr(e,t){var n=Math.cos(e),r=function(e){return Math.tan(Ae/4+e/2)},a=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),i=n*Math.pow(r(e),a)/a;if(!a)return Zr;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var n=i/Math.pow(r(t),a);return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}return o.invert=function(e,t){var n=i-t,r=Pe(a)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/a,2*Math.atan(Math.pow(i/r,1/a))-Ce]},o}function Yr(e,t){var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),a=n/r+e;if(m(r)1&&ze(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function na(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Tr(Jr)}).raw=Jr,$r.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wr($r),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):[(e=n())[0],e[1],e[2]-90]},n([0,0,90])}).raw=$r,t.geom={},t.geom.hull=function(e){var t=Kr,n=ea;if(arguments.length)return r(e);function r(e){if(e.length<3)return[];var r,a=vt(t),i=vt(n),o=e.length,l=[],s=[];for(r=0;r=0;--r)h.push(e[l[c[r]][2]]);for(r=+f;rke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){r>-ke?(t=l.P,n=l):a>-ke?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||n){if(t===n)return ka(t),n=pa(t.site),ca.insert(s,n),s.edge=n.edge=Ta(t.site,s.site),wa(t),void wa(n);if(n){ka(t),ka(n);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=n.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(n.edge,c,p,b),s.edge=Ta(c,e,null,b),n.edge=Ta(e,p,null,b),wa(t),wa(n)}else s.edge=Ta(t.site,s.site)}}function ma(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-1/0;var l=(n=o.site).x,s=n.y,c=s-t;if(!c)return l;var u=l-r,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+r:(r+l)/2}function xa(e,t){var n=e.N;if(n)return ma(n,t);var r=e.site;return r.y===t?r.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,a=e.site,i=n.site;if(r!==i){var o=a.x,l=a.y,s=r.x-o,c=r.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){Oa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};n={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/r,y:s};n={x:(c-a)/r,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xke||m(a-n)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(r-f)ke?{x:f,y:m(t-f)ke?{x:m(n-p)ke?{x:d,y:m(t-d)ke?{x:m(n-h)=n&&c.x<=a&&c.y>=r&&c.y<=o?[[n,o],[a,o],[a,r],[n,r]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(n,r){for(var a,i,o,l,s=n.site,c=n.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:Ha(n,r)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,n,r,a,i,o,l){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-n)+m(c-r)<.01)A(e,t,n,r,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,A(e,u,s,c,a,i,o,l),A(e,t,n,r,a,i,o,l)}else e.x=n,e.y=r,e.point=t}else A(e,t,n,r,a,i,o,l)}function A(e,t,n,r,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=n>=s,f=r>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,n,r,a,i,o,l)}w>k?v=p+w:g=h+k;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(T.visit=function(e){!function e(t,n,r,a,i,o){if(!t(n,r,a,i,o)){var l=.5*(r+i),s=.5*(a+o),c=n.nodes;c[0]&&e(t,c[0],r,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],r,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,T,h,p,g,v)},T.find=function(e){return function(e,t,n,r,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(r=t.interpolators[a](e,n)););return r}function Ya(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ni(e){return Math.pow(2,10*(e-1))}function ri(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function oi(e){var t,n,r,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(r=-l)*(n=a)[0],t[1]+=r*n[1],t))||0;a[0]*i[1]=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"in";return a=Za.get(a)||Xa,i=Wa.get(i)||P,t=i(a.apply(null,n.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,n){e=t.hcl(e),n=t.hcl(n);var r=e.h,a=e.c,i=e.l,o=n.h-r,l=n.c-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.c:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Xe(r+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,n){e=t.hsl(e),n=t.hsl(n);var r=e.h,a=e.s,i=e.l,o=n.h-r,l=n.s-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.s:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(r+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,n){e=t.lab(e),n=t.lab(n);var r=e.l,a=e.a,i=e.b,o=n.l-r,l=n.a-a,s=n.b-i;return function(e){return et(r+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var n=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,n){var r=[],a=[];return e=t.transform(e),n=t.transform(n),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push("translate(",null,",",null,")");r.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else(t[0]||t[1])&&n.push("translate("+t+")")}(e.translate,n.translate,r,a),function(e,t,n,r){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(ui(n)+"rotate(",null,")")-2,x:Ha(e,t)})):t&&n.push(ui(n)+"rotate("+t+")")}(e.rotate,n.rotate,r,a),function(e,t,n,r){e!==t?r.push({i:n.push(ui(n)+"skewX(",null,")")-2,x:Ha(e,t)}):t&&n.push(ui(n)+"skewX("+t+")")}(e.skew,n.skew,r,a),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(ui(n)+"scale(",null,",",null,")");r.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(ui(n)+"scale("+t+")")}(e.scale,n.scale,r,a),e=n=null,function(e){for(var t,n=-1,i=a.length;++n0?r=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:r=0})):t>0&&(s.start({type:"start",alpha:r=t}),e=Mt(l.tick)),l):r},l.start=function(){var e,t,n,r=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)n.push(a[r])}function Ai(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;n&&(i.value=0),i.children=c}else n&&(i.value=+n.call(r,i,i.depth)||0),delete i.children;return Ai(a,function(t){var r,a;e&&(r=t.children)&&r.sort(e),n&&(a=t.parent)&&(a.value+=t.value)}),l}return r.sort=function(t){return arguments.length?(e=t,r):e},r.children=function(e){return arguments.length?(t=e,r):t},r.value=function(e){return arguments.length?(n=e,r):n},r.revalue=function(e){return n&&(Mi(e,function(e){e.children&&(e.value=0)}),Ai(e,function(e){var t;e.children||(e.value=+n.call(r,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},r},t.layout.partition=function(){var e=t.layout.hierarchy(),n=[1,1];function r(t,r){var a=e.call(this,t,r);return function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(r=t.value?r/t.value:0;++cl&&(l=r),o.push(r)}for(n=0;na&&(r=n,a=t);return r}function ji(e){return e.reduce(Bi,0)}function Bi(e,t){return e+t[1]}function Hi(e,t){return qi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function qi(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Xi(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function Zi(e){if((t=e.children)&&(s=t.length)){var t,n,r,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(n=t[0]).x=-n.r,n.y=0,x(n),s>1&&((r=t[1]).x=r.r,r.y=0,x(r),s>2))for(Ji(n,r,a=t[2]),x(a),Gi(n,a),n._pack_prev=a,Gi(a,r),r=n._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(n=e,i):n},i.range=function(e){return arguments.length?(r=vt(e),i):r},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return qi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,n=t.layout.hierarchy().sort(Ui),r=0,a=[1,1];function i(t,i){var o=n.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ai(l,function(e){e.r=+u(e.value)}),Ai(l,Zi),r){var f=r*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ai(l,function(e){e.r+=f}),Ai(l,Zi),Ai(l,function(e){e.r-=f})}return function e(t,n,r,a){var i=t.children;t.x=n+=a*t.x;t.y=r+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=n(d,h)/2-d.x,v=r[0]/(h.x+n(h,d)/2+g),y=r[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,r=e.parent.children,a=e.i?r[e.i-1]:null;if(t.length){!function(e){var t,n=0,r=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=n,t.m+=n,n+=t.s+(r+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+n(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+n(e._,a._));e.parent.A=function(e,t,r){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+n(l._,i._))>0&&(to(no(l,e,r),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,r=e)}return r}(e,a,e.parent.A||r[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=r[0],e.y=e.depth*r[1]}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e)?s:null,i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null==(r=e)?null:s,i):a?r:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),n=$i,r=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ai(c,function(e){var r=e.children;r&&r.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(r),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(r)):(e.x=l?u+=n(e,l):0,e.y=0,l=e)});var f=function e(t){var n=t.children;return n&&n.length?e(n[0]):t}(c),d=function e(t){var n,r=t.children;return r&&(n=r.length)?e(r[n-1]):t}(c),h=f.x-n(f,d)/2,p=d.x+n(d,f)/2;return Ai(c,a?function(e){e.x=(e.x-c.x)*r[0],e.y=(c.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(c.y?e.y/c.y:1))*r[1]}),s}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e),i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null!=(r=e),i):a?r:null},ki(i,e)},t.layout.treemap=function(){var e,n=t.layout.hierarchy(),r=Math.round,a=[1,1],i=null,o=ro,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var n,r,a=-1,i=e.length;++a0;)l.push(n=c[a-1]),l.area+=n.area,"squarify"!==s||(r=h(l,g))<=d?(c.pop(),d=r):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var n,r=o(e),a=t.slice(),i=[];for(u(a,r.dx*r.dy/e.value),i.area=0;n=a.pop();)i.push(n),i.area+=n.area,null!=n.z&&(p(i,n.z?r.dx:r.dy,r,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return t*=t,(r*=r)?Math.max(t*a*c/r,r/(t*i*c)):1/0}function p(e,t,n,a){var i,o=-1,l=e.length,s=n.x,c=n.y,u=t?r(e.area/t):0;if(t==n.dx){for((a||u>n.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++o1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var n=t.random.irwinHall(e);return function(){return n()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;n2?fo:lo,l=a?hi:di;return i=e(t,n,l,r),o=e(n,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(n=e,l()):n};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(r=e,l()):r};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,n){return yo(t,e,n)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,n,r,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(n,r,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(r)}function l(e){return a?Math.pow(r,e):-Math.pow(r,-e)}function s(e){return n(o(e))}s.invert=function(e){return l(n.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,n.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(r=+e,n.domain(i.map(o)),s):r};s.nice=function(){var e=so(i.map(o),a?Math:_o);return n.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],n=e[0],s=e[1],c=Math.floor(o(n)),u=Math.ceil(o(s)),f=r%1?2:r;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,n){if(!arguments.length)return bo;arguments.length<2?n=bo:"function"!=typeof n&&(n=t.format(n));var a=Math.max(1,r*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*r0?a[e-1]:n[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,A,T=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=r===Co?Math.sqrt(l*l+c*c):+r.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(T=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Ae?0:1;if(L&&Eo(m,x,b,_)===h^S){var O=(u+f)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-T),k=l*Math.sin(f-T),M=l*Math.cos(u+T),A=l*Math.sin(u+T);var P=Math.abs(u-f+2*T)<=Ae?0:1;if(T&&Eo(w,k,M,A)===1-h^P){var z=(u+f)/2;w=l*Math.cos(z),k=l*Math.sin(z),M=A=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+n.apply(this,arguments)))>.001){g=l0?0:1}function Ro(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=n-r,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,A=(-b*v+y*_)/m,T=w-p,L=k-g,C=M-p,S=A-g;return T*T+L*L>C*C+S*S&&(w=M,k=A),[[w-s,k-c],[w*n/x,k*n/x]]}function No(e){var t=Kr,n=ea,r=Xn,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(n);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",r[0]);return a.join("")},"step-before":Bo,"step-after":Ho,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,n=[],r=-1,a=e.length,i=[0],o=[0];for(;++r<3;)t=e[r],i.push(t[0]),o.push(t[1]);n.push(Go(Zo,i)+","+Go(Zo,o)),--r;for(;++r9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function jo(e){return e.join("L")+"Z"}function Bo(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cAe)+",1 "+t}function s(e,t,n,r){return"Q 0,0 "+r}return i.radius=function(e){return arguments.length?(n=vt(e),i):n},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(r=vt(e),i):r},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=jr,t=Br,n=el;function r(r,a){var i=e.call(this,r,a),o=t.call(this,r,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(n))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return r.source=function(t){return arguments.length?(e=vt(t),r):e},r.target=function(e){return arguments.length?(t=vt(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),n=el,r=e.projection;return e.projection=function(e){return arguments.length?r(function(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Ce;return[n*Math.cos(r),n*Math.sin(r)]}}(n=e)):n},e},t.svg.symbol=function(){var e=nl,t=tl;function n(n,r){return(al.get(e.call(this,n,r))||rl)(t.call(this,n,r))}return n.type=function(t){return arguments.length?(e=vt(t),n):e},n.size=function(e){return arguments.length?(t=vt(e),n):t},n};var al=t.map({circle:rl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),n=t*ol;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);X.transition=function(e){for(var t,n,r=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[r]:delete e[n],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[r]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=X.call,dl.empty=X.empty,dl.node=X.node,dl.size=X.size,t.transition=function(e,n){return e&&e.transition?ul?e.transition(n):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,n,r,a=this.id,i=this.namespace,o=[];e=Z(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=r.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),A=xe(y),T=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,T[0]-=l[1],T[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(T[0]+=l[1],T[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",z):L.on("mousemove.brush",O).on("mouseup.brush",z),b.interrupt().selectAll("*").interrupt(),M)T[0]=l[0]-T[0],T[1]=s[0]-T[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-T[0],s[1-S]-T[1]],T[0]=l[C],T[1]=s[S]}else t.event.altKey&&(f=T.slice());function O(){var e=t.mouse(y),n=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),T[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var n=io(a.domain()),r=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],Sl(+n[1]+1),t<1?1:t)},a.tickFormat=function(){return r},a.copy=function(){return Cl(e.copy(),n,r)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Tl,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Tl.toString,Dt.second=It(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=It(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=It(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=It(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Pl=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],zl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Xn]]),Dl={range:function(e,n,r){return t.range(Math.ceil(e/r)*r,+n,r).map(Sl)},floor:P,ceil:P};Pl.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),Pl,zl)};var El=Pl.map(function(e){return[e[0].utc,e[1]]}),Rl=Al.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Xn]]);function Nl(e){return JSON.parse(e.responseText)}function Il(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Rl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Nl,t)},t.html=function(e,t){return mt(e,"text/html",Il,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t={};t.xmlns="http://www.w3.org/2000/xmlns/",t.svg="http://www.w3.org/2000/svg",t.xlink="http://www.w3.org/1999/xlink",t.svgAttrs={xmlns:t.svg,"xmlns:xlink":t.xlink};var n=function(e){var t=typeof e;if("string"===t){var n=e;if(0===(e=+e)&&function(e){for(var t,n=e.length,r=0;r13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(n))return!1}else if("number"!==t)return!1;return e-e<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},a={},i=Math.PI;a.deg2rad=function(e){return e/180*i},a.rad2deg=function(e){return e/i*180},a.wrap360=function(e){var t=e%360;return t<0?t+360:t},a.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var o=r.BADNUM,l=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(e){var t=/^\s+/,n=/\s+$/,r=0,a=e.round,i=e.min,o=e.max,l=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(r){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof r&&(r=function(e){e=e.replace(t,"").replace(n,"").toLowerCase();var r,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(r=B.rgb.exec(e))return{r:r[1],g:r[2],b:r[3]};if(r=B.rgba.exec(e))return{r:r[1],g:r[2],b:r[3],a:r[4]};if(r=B.hsl.exec(e))return{h:r[1],s:r[2],l:r[3]};if(r=B.hsla.exec(e))return{h:r[1],s:r[2],l:r[3],a:r[4]};if(r=B.hsv.exec(e))return{h:r[1],s:r[2],v:r[3]};if(r=B.hsva.exec(e))return{h:r[1],s:r[2],v:r[3],a:r[4]};if(r=B.hex8.exec(e))return{r:z(r[1]),g:z(r[2]),b:z(r[3]),a:N(r[4]),format:a?"name":"hex8"};if(r=B.hex6.exec(e))return{r:z(r[1]),g:z(r[2]),b:z(r[3]),format:a?"name":"hex"};if(r=B.hex4.exec(e))return{r:z(r[1]+""+r[1]),g:z(r[2]+""+r[2]),b:z(r[3]+""+r[3]),a:N(r[4]+""+r[4]),format:a?"name":"hex8"};if(r=B.hex3.exec(e))return{r:z(r[1]+""+r[1]),g:z(r[2]+""+r[2]),b:z(r[3]+""+r[3]),format:a?"name":"hex"};return!1}(r));"object"==typeof r&&(H(r.r)&&H(r.g)&&H(r.b)?(h=r.r,p=r.g,g=r.b,a={r:255*O(h,255),g:255*O(p,255),b:255*O(g,255)},f=!0,d="%"===String(r.r).substr(-1)?"prgb":"rgb"):H(r.h)&&H(r.s)&&H(r.v)?(s=E(r.s),c=E(r.v),a=function(t,n,r){t=6*O(t,360),n=O(n,100),r=O(r,100);var a=e.floor(t),i=t-a,o=r*(1-n),l=r*(1-i*n),s=r*(1-(1-i)*n),c=a%6;return{r:255*[r,l,o,o,s,r][c],g:255*[s,r,r,l,o,o][c],b:255*[o,o,s,r,r,l][c]}}(r.h,s,c),f=!0,d="hsv"):H(r.h)&&H(r.s)&&H(r.l)&&(s=E(r.s),u=E(r.l),a=function(e,t,n){var r,a,i;function o(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=O(e,360),t=O(t,100),n=O(n,100),0===t)r=a=i=n;else{var l=n<.5?n*(1+t):n+t-n*t,s=2*n-l;r=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*r,g:255*a,b:255*i}}(r.h,s,u),f=!0,d="hsl"),r.hasOwnProperty("a")&&(l=r.a));var h,p,g;return l=S(l),{ok:f,format:r.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=r++}function u(e,t,n){e=O(e,255),t=O(t,255),n=O(n,255);var r,a,l=o(e,t,n),s=i(e,t,n),c=(l+s)/2;if(l==s)r=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:r=(t-n)/u+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,i.push(c(r));return i}function T(e,t){t=t||6;for(var n=c(e).toHsv(),r=n.h,a=n.s,i=n.v,o=[],l=1/t;t--;)o.push(c({h:r,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,n,r,a=this.toRgb();return t=a.r/255,n=a.g/255,r=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(n).toString(16)),D(R(r))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*O(this._r,255))+"%",g:a(100*O(this._g,255))+"%",b:a(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%)":"rgba("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);n="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(A,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:E(e[r]));e=n}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(e,t,n){n=0===n?0:n||50;var r=c(e).toRgb(),a=c(t).toRgb(),i=n/100;return c({r:(a.r-r.r)*i+r.r,g:(a.g-r.g)*i+r.g,b:(a.b-r.b)*i+r.b,a:(a.a-r.a)*i+r.a})},c.readability=function(t,n){var r=c(t),a=c(n);return(e.max(r.getLuminance(),a.getLuminance())+.05)/(e.min(r.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,n){var r,a,i=c.readability(e,t);switch(a=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,n){var r,a,i,o,l=null,s=0;a=(n=n||{}).includeFallbackColors,i=n.level,o=n.size;for(var u=0;us&&(s=r,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(n.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],n))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function O(t,n){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var r=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(n,o(0,parseFloat(t))),r&&(t=parseInt(t*n,10)/100),e.abs(t-n)<1e-6?1:t%n/parseFloat(n)}function P(e){return i(1,o(0,e))}function z(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function R(t){return e.round(255*parseFloat(t)).toString(16)}function N(e){return z(e)/255}var I,F,j,B=(F="[\\s|\\(]+("+(I="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+I+")[,|\\s]+("+I+")\\s*\\)?",j="[\\s|\\(]+("+I+")[,|\\s]+("+I+")[,|\\s]+("+I+")[,|\\s]+("+I+")\\s*\\)?",{CSS_UNIT:new RegExp(I),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function H(e){return!!B.CSS_UNIT.exec(e)}s.exports?s.exports=c:window.tinycolor=c}(Math),s=s.exports;var c={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=c.RdBu,f=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var n=0;n1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(r=e[t][0],a=e[t][1],o=!1,Y(r))for(n=r.length-1;n>=0;n--)Q(r[n],$(a,n))?o?r[n]=void 0:r.pop():o=!0;else if("object"==typeof r&&null!==r)for(i=Object.keys(r),o=!1,n=i.length-1;n>=0;n--)Q(r[i[n]],$(a,i[n]))?delete r[i[n]]:o=!0;if(o)return}}(s)):o[t[i]]=r}}function $(e,t){var r=t;return n(t)?r="["+t+"]":e&&(r="."+t),e+r}function K(e,t,n,r){var a,i=Y(n),o=!0,l=n,s=r.replace("-1",0),c=!i&&Q(n,s),u=t[0];for(a=0;aa.max?t.set(r):t.set(+e)}},integer:{coerceFunction:function(e,t,r,a){e%1||!n(e)||void 0!==a.min&&ea.max?t.set(r):t.set(+e)}},string:{coerceFunction:function(e,t,n,r){if("string"!=typeof e){var a="number"==typeof e;!0!==r.strict&&a?t.set(String(e)):t.set(n)}else r.noBlank&&!e?t.set(n):t.set(e)}},color:{coerceFunction:function(e,t,n){s(e).isValid()?t.set(e):t.set(n)}},colorlist:{coerceFunction:function(e,t,n){Array.isArray(e)&&e.length&&e.every(function(e){return s(e).isValid()})?t.set(e):t.set(n)}},colorscale:{coerceFunction:function(e,t,n){t.set(d(e,n))}},angle:{coerceFunction:function(e,t,r){"auto"===e?t.set("auto"):n(e)?t.set(ie(+e)):t.set(r)}},subplotid:{coerceFunction:function(e,t,n,r){var a=r.regex||re(n);"string"==typeof e&&a.test(e)?t.set(e):t.set(n)},validateFunction:function(e,t){var n=t.dflt;return e===n||"string"==typeof e&&!!re(n).test(e)}},flaglist:{coerceFunction:function(e,t,n,r){if("string"==typeof e)if(-1===(r.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=le&&e<=se?e:fe;if("string"!=typeof e&&"number"!=typeof e)return fe;e=String(e);var n=_e(t),r=e.charAt(0);!n||"G"!==r&&"g"!==r||(e=e.substr(1),t="");var a=n&&"chinese"===t.substr(0,7),i=e.match(a?xe:me);if(!i)return fe;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(n){if(2===o.length)return fe;var d;o=Number(o);try{var h=D.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return fe}return d?(d.toJD()-ve)*de+c*he+u*pe+f*ge:fe}o=2===o.length?(Number(o)+2e3-be)%100+be:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?fe:g.getUTCDate()!==s?fe:g.getTime()+f*ge},le=ue.MIN_MS=ue.dateTime2ms("-9999"),se=ue.MAX_MS=ue.dateTime2ms("9999-12-31 23:59:59.9999"),ue.isDateTime=function(e,t){return ue.dateTime2ms(e,t)!==fe};var ke=90*de,Me=3*he,Ae=5*pe;function Te(e,t,n,r,a){if((t||n||r||a)&&(e+=" "+we(t,2)+":"+we(n,2),(r||a)&&(e+=":"+we(r,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+we(a,i)}return e}ue.ms2DateTime=function(e,t,n){if("number"!=typeof e||!(e>=le&&e<=se))return fe;t||(t=0);var r,a,i,o,l,s,c=Math.floor(10*ce(e+.05,1)),u=Math.round(e-c/10);if(_e(n)){var f=Math.floor(u/de)+ve,d=Math.floor(ce(e,de));try{r=D.getComponentMethod("calendars","getCal")(n).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){r=ye("G%Y-%m-%d")(new Date(u))}if("-"===r.charAt(0))for(;r.length<11;)r="-0"+r.substr(1);else for(;r.length<10;)r="0"+r;a=t=le+de&&t<=se-de))return fe;var n=Math.floor(10*ce(t+.05,1)),r=new Date(Math.round(t-n/10));return Te(e.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+n)},ue.cleanDate=function(e,t,n){if(ue.isJSDate(e)||"number"==typeof e){if(_e(n))return w.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ue.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ue.isDateTime(e,n))return w.error("unrecognized date",e),t;return e};var Le=/%\d?f/g;function Ce(e,t,n,r){e=e.replace(Le,function(e){var n=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(n).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(_e(r))try{e=D.getComponentMethod("calendars","worldCalFmt")(e,t,r)}catch(e){return"Invalid"}return n(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ue.formatDate=function(e,t,r,a,i,o){if(i=_e(i)&&i,!t)if("y"===r)t=o.year;else if("m"===r)t=o.month;else{if("d"!==r)return function(e,t){var r=ce(e+.05,de),a=we(Math.floor(r/he),2)+":"+we(ce(Math.floor(r/pe),60),2);if("M"!==t){n(t)||(t=0);var i=(100+Math.min(ce(e/ge,60),Se[t])).toFixed(t).substr(1);t>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,r)+"\n"+Ce(o.dayMonthYear,e,a,i);t=o.dayMonth+"\n"+o.year}return Ce(t,e,a,i)};var Oe=3*de;ue.incrementMonth=function(e,t,n){n=_e(n)&&n;var r=ce(e,de);if(e=Math.round(e-r),n)try{var a=Math.round(e/de)+ve,i=D.getComponentMethod("calendars","getCal")(n),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ve)*de+r}catch(t){w.error("invalid ms "+e+" in calendar "+n)}var l=new Date(e+Oe);return l.setUTCMonth(l.getUTCMonth()+t)+r-Oe},ue.findExactDates=function(e,t){for(var r,a,i=0,o=0,l=0,s=0,c=_e(t)&&D.getComponentMethod("calendars","getCal")(t),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Fe(e,t,n,r,a){var i=r*e+a*t;if(i<0)return r*r+a*a;if(i>n){var o=r-e,l=a-t;return o*o+l*l}var s=r*t-a*e;return s*s/n}Ne.segmentsIntersect=Ie,Ne.segmentDistance=function(e,t,n,r,a,i,o,l){if(Ie(e,t,n,r,a,i,o,l))return 0;var s=n-e,c=r-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Fe(s,c,d,a-e,i-t),Fe(s,c,d,o-e,l-t),Fe(u,f,h,e-a,t-i),Fe(u,f,h,n-a,r-i));return Math.sqrt(p)},Ne.getTextLocation=function(e,t,n,r){if(e===Ee&&r===Re||(De={},Ee=e,Re=r),De[n])return De[n];var a=e.getPointAtLength(ce(n-r/2,t)),i=e.getPointAtLength(ce(n+r/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(ce(n,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return De[n]=s,s},Ne.clearLocationCache=function(){Ee=null},Ne.getVisibleSegment=function(e,t,n){var r,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var n=e.getPointAtLength(t);0===t?r=n:t===u&&(a=n);var c=n.xo?n.x-o:0,f=n.ys?n.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+n)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+n))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(r.x-a.x)<.1&&Math.abs(r.y-a.y)<.1}},Ne.findPointOnPath=function(e,t,n,r){for(var a,i,o,l=(r=r||{}).pathLength||e.getTotalLength(),s=r.tolerance||.001,c=r.iterationLimit||30,u=e.getPointAtLength(0)[n]>e.getPointAtLength(l)[n]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var je=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},Be=/^\w*$/,He={init2dArray:function(e,t){for(var n=new Array(e),r=0;rt}function Qe(e,t){return e>=t}Ye.findBin=function(e,t,r){if(n(t.start))return r?Math.ceil((e-t.start)/t.size-1e-9)-1:Math.floor((e-t.start)/t.size+1e-9);var a,i,o=0,l=t.length,s=0,c=l>1?(t[l-1]-t[0])/(l-1):1;for(i=c>=0?r?Xe:Ze:r?Qe:We,e+=1e-9*c*(r?-1:1)*(c>=0?1:-1);o90&&w.log("Long binary search..."),o-1},Ye.sorterAsc=function(e,t){return e-t},Ye.sorterDes=function(e,t){return t-e},Ye.distinctVals=function(e){var t=e.slice();t.sort(Ye.sorterAsc);for(var n=t.length-1,r=t[n]-t[0]||1,a=r/(n||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(r=Math.min(r,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:r}},Ye.roundUp=function(e,t,n){for(var r,a=0,i=t.length-1,o=0,l=n?0:1,s=n?1:0,c=n?Math.ceil:Math.floor;ar.length)&&(a=r.length),n(t)||(t=!1),$e(r[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var r=t%1;return r*e[Math.ceil(t)]+(1-r)*e[Math.floor(t)]};var Ke={},et={};function tt(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}Ke.throttle=function(e,t,n){var r=et[e],a=Date.now();if(!r){for(var i in et)et[i].tsr.ts+t?o():r.timer=setTimeout(function(){o(),r.timer=null},t)},Ke.done=function(e){var t=et[e];return t&&t.timer?new Promise(function(e){var n=t.onDone;t.onDone=function(){n&&n(),e(),t.onDone=null}}):Promise.resolve()},Ke.clear=function(e){if(e)tt(et[e]),delete et[e];else for(var t in et)Ke.clear(t)};var nt=function(e,t){if(e>0)return Math.log(e)/Math.LN10;var r=Math.log(Math.min(t[0],t[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(t[0],t[1]))/Math.LN10-6),r},rt={},at=r.FP_SAFE,it=r.BADNUM,ot=rt={};ot.nestedProperty=X,ot.keyedContainer=function(e,t,n,r){var a,i;n=n||"name",r=r||"value";var o={};i=t&&t.length?X(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lat?it:n(e)?Number(e):it:it},ot.noop=A,ot.identity=function(e){return e},ot.swapAttrs=function(e,t,n,r){n||(n="x"),r||(r="y");for(var a=0;an?Math.max(n,Math.min(t,e)):Math.max(t,Math.min(n,e))},ot.bBoxIntersect=function(e,t,n){return n=n||0,e.left<=t.right+n&&t.left<=e.right+n&&e.top<=t.bottom+n&&t.top<=e.bottom+n},ot.simpleMap=function(e,t,n,r){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,n)?e(t,n,r):l},ot.OptionControl=function(e,t){e||(e={}),t||(t="opt");var n={optionList:[],_newoption:function(r){r[t]=e,n[r.name]=r,n.optionList.push(r)}};return n["_"+t]=e,n},ot.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var n,r,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(n=0;n=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[r];u[n]=i}return u},ot.syncOrAsync=function(e,t,n){var r;function a(){return ot.syncOrAsync(e,t,n)}for(;e.length;)if((r=(0,e.splice(0,1)[0])(t))&&r.then)return r.then(a).then(void 0,ot.promiseError);return n&&n(t)},ot.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},ot.noneOrAll=function(e,t,n){if(e){var r,a,i=!1,o=!0;for(r=0;r=0&&i%1==0){var p=a?a[h]:h,g=r?r[p]:p;f(g)&&(e[g].selected=1)}}},ot.getTargetArray=function(e,t){var n=t.target;if("string"==typeof n&&n){var r=ot.nestedProperty(e,n).get();return!!Array.isArray(r)&&r}return!!Array.isArray(n)&&n},ot.minExtend=function(e,t){var n={};"object"!=typeof t&&(t={});var r,a,i,o=Object.keys(e);for(r=0;r1?a+o[1]:"";if(i&&(o.length>1||l.length>4||n))for(;r.test(l);)l=l.replace(r,"$1"+i+"$2");return l+s};var ct=/%{([^\s%{}]*)}/g,ut=/^\w*$/;ot.templateString=function(e,t){var n={};return e.replace(ct,function(e,r){return ut.test(r)?t[r]||"":(n[r]=n[r]||ot.nestedProperty(t,r).get,n[r]()||"")})};ot.subplotSort=function(e,t){for(var n=Math.min(e.length,t.length)+1,r=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(r=10*r+o-48),c&&(a=10*a+l-48),!s||!c){if(r!==a)return r-a;if(o!==l)return o-l}}return a-r};var ft=2e9;ot.seedPseudoRandom=function(){ft=2e9},ot.pseudoRandom=function(){var e=ft;return ft=(69069*ft+1)%4294967296,Math.abs(ft-e)<429496729?ot.pseudoRandom():ft/4294967296};var dt=te.counter,ht={idRegex:{x:dt("x"),y:dt("y")},attrRegex:dt("[xy]axis"),xAxisMatch:dt("xaxis"),yAxisMatch:dt("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","ohlclayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}},pt={id2name:function(e){if("string"==typeof e&&e.match(ht.AX_ID_PATTERN)){var t=e.substr(1);return"1"===t&&(t=""),e.charAt(0)+"axis"+t}},name2id:function(e){if(e.match(ht.AX_NAME_PATTERN)){var t=e.substr(5);return"1"===t&&(t=""),e.charAt(0)+t}},cleanId:function(e,t){if(e.match(ht.AX_ID_PATTERN)&&(!t||e.charAt(0)===t)){var n=e.substr(1).replace(/^0+/,"");return"1"===n&&(n=""),e.charAt(0)+n}},list:function(e,t,n){var r=e._fullLayout;if(!r)return[];var a,i=pt.listIds(e,t),o=new Array(i.length);for(a=0;ar?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},gt={};(function(e){"use strict";var t;t="function"!=typeof e.matchMedia||!e.matchMedia("(hover: none)").matches,gt=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var vt=function(){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(t){e=!1}return e}(),yt={left:0,top:0},mt=function(e,t,n){t=t||e.currentTarget||e.srcElement,Array.isArray(n)||(n=[0,0]);var r=e.clientX||0,a=e.clientY||0,i=(o=t,o===window||o===document||o===document.body?yt:o.getBoundingClientRect());var o;return n[0]=r-i.left,n[1]=a-i.top,n};var xt=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]],bt={YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,HOVERID:"-hover"};function _t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var wt=_t;function kt(e){return"function"==typeof e}function Mt(e){return"object"==typeof e&&null!==e}function At(e){return void 0===e}_t.EventEmitter=_t,_t.prototype._events=void 0,_t.prototype._maxListeners=void 0,_t.defaultMaxListeners=10,_t.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},_t.prototype.emit=function(e){var t,n,r,a,i,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||Mt(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(At(n=this._events[e]))return!1;if(kt(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(Mt(n))for(a=Array.prototype.slice.call(arguments,1),r=(o=n.slice()).length,i=0;i0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},_t.prototype.on=_t.prototype.addListener,_t.prototype.once=function(e,t){if(!kt(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},_t.prototype.removeListener=function(e,t){var n,r,a,i;if(!kt(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||kt(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(Mt(n)){for(i=a;i-- >0;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},_t.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(kt(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},_t.prototype.listeners=function(e){return this._events&&this._events[e]?kt(this._events[e])?[this._events[e]]:this._events[e].slice():[]},_t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(kt(t))return 1;if(t)return t.length}return 0},_t.listenerCount=function(e,t){return e.listenerCount(t)};var Tt,Lt=wt.EventEmitter,Ct={init:function(e){if(e._ev instanceof Lt)return e;var t=new Lt,n=new Lt;return e._ev=t,e._internalEv=n,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=n.on.bind(n),e._internalOnce=n.once.bind(n),e._removeInternalListener=n.removeListener.bind(n),e._removeAllInternalListeners=n.removeAllListeners.bind(n),e.emit=function(r,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(r,a),t.emit(r,a),n.emit(r,a)},e},triggerHandler:function(e,t,n){var r,a;"undefined"!=typeof jQuery&&(r=jQuery(e).triggerHandler(t,n));var i=e._ev;if(!i)return r;var o=i._events[t];if(!o)return r;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Pt.getCursor=function(e,t,n,r){return e="left"===n?0:"center"===n?1:"right"===n?2:rt.constrain(Math.floor(3*e),0,2),t="bottom"===r?0:"middle"===r?1:"top"===r?2:rt.constrain(Math.floor(3*t),0,2),xt[t][e]},Pt.unhover=Tt.wrapped,Pt.unhoverRaw=Tt.raw,Pt.init=function(e){var t,n,r,a,i,o,l,s,c=e.gd,u=1,f=h.DBLCLICKDELAY,d=e.element;c._mouseDownTime||(c._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,vt?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=e.clampFn||function(e,t,n){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var n;try{n=new MouseEvent("click",t)}catch(e){var r=Dt(t);(n=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,r[0],r[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(n)}!function(e){e._dragging=!1,e._replotPending&&D.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Pt.coverSlip=zt;function Et(e,t,n,r){r=r||rt.identity,Array.isArray(e)&&(t[0][n]=r(e))}var Rt={},Nt=Rt={};Nt.defaults=O.defaults;var It=Nt.defaultLine=O.defaultLine;Nt.lightLine=O.lightLine;var Ft=Nt.background=O.background;function jt(e){if(n(e)||"string"!=typeof e)return e;var t=e.trim();if("rgb"!==t.substr(0,3))return e;var r=t.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return e;var a=r[1].trim().split(/\s*[\s,]\s*/),i="a"===t.charAt(3)&&4===a.length;if(!i&&3!==a.length)return e;for(var o=0;o=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}Nt.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},Nt.rgb=function(e){return Nt.tinyRGB(s(e))},Nt.opacity=function(e){return e?s(e).getAlpha():0},Nt.addOpacity=function(e,t){var n=s(e).toRgb();return"rgba("+Math.round(n.r)+", "+Math.round(n.g)+", "+Math.round(n.b)+", "+t+")"},Nt.combine=function(e,t){var n=s(e).toRgb();if(1===n.a)return s(e).toRgbString();var r=s(t||Ft).toRgb(),a=1===r.a?r:{r:255*(1-r.a)+r.r*r.a,g:255*(1-r.a)+r.g*r.a,b:255*(1-r.a)+r.b*r.a},i={r:a.r*(1-n.a)+n.r*n.a,g:a.g*(1-n.a)+n.g*n.a,b:a.b*(1-n.a)+n.b*n.a};return s(i).toRgbString()},Nt.contrast=function(e,t,n){var r=s(e);return 1!==r.getAlpha()&&(r=s(Nt.combine(e,Ft))),(r.isDark()?t?r.lighten(t):Ft:n?r.darken(n):It).toString()},Nt.stroke=function(e,t){var n=s(t);e.style({stroke:Nt.tinyRGB(n),"stroke-opacity":n.getAlpha()})},Nt.fill=function(e,t){var n=s(t);e.style({fill:Nt.tinyRGB(n),"fill-opacity":n.getAlpha()})},Nt.clean=function(e){if(e&&"object"==typeof e){var t,n,r,a,i=Object.keys(e);for(t=0;t=0;a--,i++)t=e[a],r[i]=[1-t[0],t[1]];return r},qt=function(e,t,n,r){var a,i;n?(a=rt.nestedProperty(e,n).get(),i=rt.nestedProperty(e._input,n).get()):(a=e,i=e._input);var o=r+"auto",l=r+"min",s=r+"max",u=a[o],f=a[l],d=a[s],h=a.colorscale;!1===u&&void 0!==f||(f=rt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=rt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[s]=d,i[l]=f,i[s]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?c.RdBu:f>=0?c.Reds:c.Blues,i.colorscale=h,a.reversescale&&(h=Ht(h)),a.colorscale=h)},Vt=rt.extendFlat,Ut=rt.isPlainObject,Gt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},Yt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},Xt=Gt.flags.slice().concat(["clearCalc","fullReplot"]),Zt=Yt.flags.slice().concat("layoutReplot"),Wt={traces:Gt,layout:Yt,traceFlags:function(){return Qt(Xt)},layoutFlags:function(){return Qt(Zt)},update:function(e,t){var n=t.editType;if(n&&"none"!==n)for(var r=n.split("+"),a=0;a0?Number(s):l;else if("string"!=typeof s)t.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=n(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(t.dtick=l)}var f="date"===a?rt.dateTick0(t.calendar):0,d=r("tick0",f);"date"===a?t.tick0=rt.cleanDate(d,f):n(d)&&"D1"!==s&&"D2"!==s?t.tick0=Number(d):t.tick0=f}else{void 0===r("tickvals")?t.tickmode="auto":r("ticktext")}},un=function(e){return void 0!==c[e]||f(e)},fn=function(e,t,r,a,i){var o,l=i.prefix,s=i.cLetter,c=l.slice(0,l.length-1),u=l?rt.nestedProperty(e,c).get()||{}:e,f=l?rt.nestedProperty(t,c).get()||{}:t,d=u[s+"min"],h=u[s+"max"],p=u.colorscale;a(l+s+"auto",!(n(d)&&n(h)&&d","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},mn={},xn=vn.LINE_SPACING;function bn(e,t){return e.node().getBoundingClientRect()[t]}var _n=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;mn.convertToTspans=function(n,r,a){var i=n.text(),o=!n.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(_n),l=e.select(n.node().parentNode);if(!l.empty()){var s=n.attr("class")?n.attr("class").split(" ")[0]:"text";return s+="-math",l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove(),n.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(r&&r._promises||[]).push(new Promise(function(t){n.style("display","none");var r=parseInt(n.node().style.fontSize,10),u={fontSize:r};!function(t,n,r){var a="math-output-"+rt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":n.fontSize+"px"}).text((o=t,o.replace(wn,"\\lt ").replace(kn,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var n=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())rt.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),n,a)}i.remove()})}(o[2],u,function(e,o,u){l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return c(),void t();var d=l.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});d.node().appendChild(f.node()),o&&o.node()&&f.node().insertBefore(o.node().cloneNode(!0),f.node().firstChild),f.attr({class:s,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=n.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=bn(f,"width"),g=bn(f,"height"),v=+n.attr("x")-p*{start:0,middle:.5,end:1}[n.attr("text-anchor")||"start"],y=-(r||bn(n,"height"))/4;"y"===s[0]?(d.attr({transform:"rotate("+[-90,+n.attr("x"),+n.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+n.attr("x"),y:+n.attr("y")})):"l"===s[0]?f.attr({x:n.attr("x"),y:y-g/2}):"a"===s[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+n.attr("y")+y-g/2}),a&&a.call(n,d),t(d)})})):c(),n}function c(){l.empty()||(s=n.attr("class")+"-math",l.select("svg."+s).remove()),n.text("").style("white-space","pre"),function(n,r){r=(a=r,function(e,t){if(!e)return"";for(var n=0;n1)for(var o=1;o doesnt match end tag <"+e+">. Pretending it did match.",r),i=l[l.length-1].node}else rt.log("Ignoring unexpected end tag .",r)}En.test(r)?c():(i=n,l=[{node:n}]);for(var h=r.split(zn),p=0;p|>|>)/g;var Mn={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"},An={sub:"0.3em",sup:"-0.6em"},Tn={sub:"-0.21em",sup:"0.42em"},Ln="\u200b",Cn=["http:","https:","mailto:","",void 0,":"],Sn=new RegExp("]*)?/?>","g"),On=Object.keys(yn.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:yn.entityToUnicode[e]}}),Pn=/(\r\n?|\n)/g,zn=/(<[^<>]*>)/,Dn=/<(\/?)([^ >]*)(\s+(.*))?>/i,En=//i,Rn=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Nn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,In=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Fn=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function jn(e,t){if(!e)return null;var n=e.match(t);return n&&(n[3]||n[4])}var Bn=/(^|;)\s*color:/;function Hn(e,t,n){var r,a,i,o=n.horizontalAlign,l=n.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-r.height}:"middle"===l?function(){return s.top+(s.height-r.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-r.width}:"center"===o?function(){return s.left+(s.width-r.width)/2}:function(){return s.left},function(){return r=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}mn.plainText=function(e){return(e||"").replace(Sn," ")},mn.lineCount=function(e){return e.selectAll("tspan.line").size()||1},mn.positionText=function(t,n,r){return t.each(function(){var t=e.select(this);function a(e,n){return void 0===n?null===(n=t.attr(e))&&(t.attr(e,0),n=0):t.attr(e,n),n}var i=a("x",n),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},mn.makeEditable=function(t,n){var r=n.gd,a=n.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(r).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:n.fill||c.fill||"black",opacity:1,"background-color":n.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(n.text||t.attr("data-unformatted")).call(Hn(t,a,n)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var n,a=e.select(this).attr("class");(n=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(n).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(r._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Hn(t,a,n)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),n=document.createRange();n.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(n),t.focus()}return n.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var qn=function(e){var t=e.marker,r=t.sizeref||1,a=t.sizemin||0,i="area"===t.sizemode?function(e){return Math.sqrt(e/r)}:function(e){return e/r};return function(e){var t=i(e/2);return n(t)&&t>0?Math.max(t,a):0}},Vn={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&(e.mode&&-1!==e.mode.indexOf("markers")||"splom"===e.type)},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return rt.isPlainObject(e.marker)&&rt.isArrayOrTypedArray(e.marker.size)}},Un={},Gn=vn.LINE_SPACING,Yn=h.DESELECTDIM,Xn=Un={};Xn.font=function(e,t,n,r){rt.isPlainObject(t)&&(r=t.color,n=t.size,t=t.family),t&&e.style("font-family",t),n+1&&e.style("font-size",n+"px"),r&&e.call(Rt.fill,r)},Xn.setPosition=function(e,t,n){e.attr("x",t).attr("y",n)},Xn.setSize=function(e,t,n){e.attr("width",t).attr("height",n)},Xn.setRect=function(e,t,n,r,a){e.call(Xn.setPosition,t,n).call(Xn.setSize,r,a)},Xn.translatePoint=function(e,t,r,a){var i=r.c2p(e.x),o=a.c2p(e.y);return!!(n(i)&&n(o)&&t.node())&&("text"===t.node().nodeName?t.attr("x",i).attr("y",o):t.attr("transform","translate("+i+","+o+")"),!0)},Xn.translatePoints=function(t,n,r){t.each(function(t){var a=e.select(this);Xn.translatePoint(t,a,n,r)})},Xn.hideOutsideRangePoint=function(e,t,n,r,a,i){t.attr("display",n.isPtWithinRange(e,a)&&r.isPtWithinRange(e,i)?null:"none")},Xn.hideOutsideRangePoints=function(t,n,r){if(n._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=n.xaxis,i=n.yaxis;t.each(function(n){var o=n[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Xn.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Xn.crispRound=function(e,t,r){return t&&n(t)?e._context.staticPlot?t:t<1?1:Math.round(t):r||0},Xn.singleLineStyle=function(e,t,n,r,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";Rt.stroke(t,r||i.color),Xn.dashLine(t,l,o)},Xn.lineGroupStyle=function(t,n,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";e.select(this).call(Rt.stroke,r||i.color).call(Xn.dashLine,l,o)})},Xn.dashLine=function(e,t,n){n=+n||0,t=Xn.dashStyle(t,n),e.style({"stroke-dasharray":t,"stroke-width":n+"px"})},Xn.dashStyle=function(e,t){t=+t||1;var n=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),e},Xn.singleFillStyle=function(t){var n=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;n&&t.call(Rt.fill,n)},Xn.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(n){var r=e.select(this);try{r.call(Rt.fill,n[0].trace.fillcolor)}catch(e){rt.error(e,t),r.remove()}})},Xn.symbolNames=[],Xn.symbolFuncs=[],Xn.symbolNeedLines={},Xn.symbolNoDot={},Xn.symbolNoFill={},Xn.symbolList=[],Object.keys(gn).forEach(function(e){var t=gn[e];Xn.symbolList=Xn.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Xn.symbolNames[t.n]=e,Xn.symbolFuncs[t.n]=t.f,t.needLine&&(Xn.symbolNeedLines[t.n]=!0),t.noDot?Xn.symbolNoDot[t.n]=!0:Xn.symbolList=Xn.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Xn.symbolNoFill[t.n]=!0)});var Zn=Xn.symbolNames.length,Wn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Qn(e,t){var n=e%100;return Xn.symbolFuncs[n](t)+(e>=200?Wn:"")}Xn.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Xn.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Zn||e>=400?0:Math.floor(Math.max(e,0))};var Jn={x1:1,x2:0,y1:0,y2:0},$n={x1:0,x2:0,y1:1,y2:0};Xn.gradient=function(t,n,r,a,i,o){var l=n._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],rt.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jn):"vertical"===a&&t.attr($n),t.attr("id",r);var n=s(i),l=s(o);t.append("stop").attr({offset:"0%","stop-color":Rt.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":Rt.tinyRGB(n),"stop-opacity":n.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Xn.initGradients=function(e){rt.ensureSingle(e._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},Xn.singlePointStyle=function(e,t,n,r,a,i){var o=n.marker;!function(e,t,n,r,a,i,o,l){if(D.traceIs(n,"symbols")){var s=qn(n);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Vn.isBubble(n)?s(e.ms):(i.size||6)/2,e.mrc=t;var r=Xn.symbolNumber(e.mx||i.symbol)||0;return e.om=r%200>=100,Qn(r,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):rt.isArrayOrTypedArray(o.color)?Rt.defaultLine:o.color,rt.isArrayOrTypedArray(i.color)&&(c=Rt.defaultLine,d=!0),c="mc"in e?e.mcc=r(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(Rt.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+n.uid;d&&(v+="-"+e.i),t.call(Xn.gradient,l,v,p,c,g)}else t.call(Rt.fill,c);f&&t.call(Rt.stroke,u)}}(e,t,n,r,a,o,o.line,i)},Xn.pointStyle=function(t,n,r){if(t.size()){var a=n.marker,i=Xn.tryColorscale(a,""),o=Xn.tryColorscale(a,"line");t.each(function(t){Xn.singlePointStyle(t,e.select(this),n,i,o,r)})}},Xn.makeSelectedPointStyleFns=function(e){var t={},n=e.selected||{},r=e.unselected||{},a=e.marker||{},i=n.marker||{},o=r.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,n=void 0!==t;if(n||u||f){if(!e.selected)return f?c:Yn*(n?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Xn.selectedPointStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=Xn.makeSelectedPointStyleFns(n),a=n.marker||{};t.each(function(t){var n=e.select(this),a=r.opacityFn(t);void 0!==a&&n.style("opacity",a)}),r.colorFn&&t.each(function(t){var n=e.select(this),a=r.colorFn(t);a&&Rt.fill(n,a)}),D.traceIs(n,"symbols")&&r.sizeFn&&t.each(function(t){var n=e.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);n.attr("d",Qn(Xn.symbolNumber(i),o)),t.mrc2=o})}},Xn.tryColorscale=function(e,t){var n=t?rt.nestedProperty(e,t).get():e,r=n.colorscale,a=n.color;return r&&rt.isArrayOrTypedArray(a)?pn.makeColorScaleFunc(pn.extractScale(r,n.cmin,n.cmax)):rt.identity};var Kn={start:1,end:-1,middle:0,bottom:1,top:-1};function er(t,n,r,a){var i=e.select(t.node().parentNode),o=-1!==n.indexOf("top")?"top":-1!==n.indexOf("bottom")?"bottom":"middle",l=-1!==n.indexOf("left")?"end":-1!==n.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(mn.lineCount(t)-1)*Gn+1,u=Kn[l]*s,f=.75*r+Kn[o]*s+(Kn[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function tr(e,t){var r=e.ts||t.textfont.size;return n(r)&&r>0?r:0}Xn.textPointStyle=function(t,n,r){t.each(function(t){var a=e.select(this),i=rt.extractOption(t,n,"tx","text");if(i){var o=t.tp||n.textposition,l=tr(t,n);a.call(Xn.font,t.tf||n.textfont.family,l,t.tc||n.textfont.color).text(i).call(mn.convertToTspans,r).call(er,o,l,t.mrc)}else a.remove()})},Xn.selectedTextStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=n.selected||{},a=n.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||n.textfont.color,s=t.tp||n.textposition,c=tr(t,n),u=(r.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=Rt.addOpacity(l,Yn)),i&&Rt.fill(o,i),er(o,s,c,t.mrc2||t.mrc)})}};var nr=.5;function rr(t,n,r,a){var i=t[0]-n[0],o=t[1]-n[1],l=r[0]-n[0],s=r[1]-n[1],c=Math.pow(i*i+o*o,nr/2),u=Math.pow(l*l+s*s,nr/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(n[0]+(h&&f/h),2),e.round(n[1]+(h&&d/h),2)],[e.round(n[0]-(p&&f/p),2),e.round(n[1]-(p&&d/p),2)]]}Xn.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var n,r="M"+e[0],a=[];for(n=1;n=1e4&&(Xn.savedBBoxes={},or=0),r&&(Xn.savedBBoxes[r]=p),or++,rt.extendFlat({},p)},Xn.setClipUrl=function(t,n){if(n){if(void 0===Xn.baseUrl){var r=e.select("base");r.size()&&r.attr("href")?Xn.baseUrl=window.location.href.split("#")[0]:Xn.baseUrl=""}t.attr("clip-path","url("+Xn.baseUrl+"#"+n+")")}else t.attr("clip-path",null)},Xn.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Xn.setTranslate=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||0,n=n||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+n+")").trim(),e[a]("transform",i),i},Xn.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Xn.setScale=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||1,n=n||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+n+")").trim(),e[a]("transform",i),i},Xn.setPointGroupScale=function(e,t,n){var r,a,i;return t=t||1,n=n||1,a=1===t&&1===n?"":" scale("+t+","+n+")",i=/\s*sc.*/,e.each(function(){r=(this.getAttribute("transform")||"").replace(i,""),r=(r+=a).trim(),this.setAttribute("transform",r)}),a};var sr=/translate\([^)]*\)\s*$/;Xn.setTextPointsScale=function(t,n,r){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(sr);t=1===n&&1===r?[]:["translate("+o+","+l+")","scale("+n+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var cr={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},isTraceInSubplots:function(e,t){if("splom"===e.type){for(var n=e.xaxes||[],r=e.yaxes||[],a=0;a=0&&n.index=i.length)return!1;if(2===e.dimensions){if(n++,t.length===n)return e;var o=t[n];if(!jr(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function jr(e){return e===Math.round(e)&&e>=0}function Br(e){return function(e){Pr.crawl(e,function(e,t,n){Pr.isValObject(e)?"data_array"===e.valType?(e.role="data",n[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(n[t+"src"]={valType:"string",editType:"none"}):Er(e)&&(e.role="object")})}(e),function(e){Pr.crawl(e,function(e,t,n){if(!e)return;var r=e[Nr];if(!r)return;delete e[Nr],n[t]={items:{}},n[t].items[r]=e,n[t].role="object"})}(e),function(e){!function e(t){for(var n in t)if(Er(t[n]))e(t[n]);else if(Array.isArray(t[n]))for(var r=0;r=o.length)return!1;r=(n=(D.transformsRegistry[o[l].type]||{}).attributes)&&n[t[2]],i=3}else if("area"===e.type)r=Ar[a];else{var s=e._module;if(s||(s=(D.modules[e.type||S.type.dflt]||{})._module),!s)return!1;if(!(r=(n=s.attributes)&&n[a])){var c=s.basePlotModule;c&&c.attributes&&(r=c.attributes[a])}r||(r=S[a])}return Fr(r,t,i)},Pr.getLayoutValObject=function(e,t){return Fr(function(e,t){var n,r,a,i,o=e._basePlotModules;if(o){var l;for(n=0;n0?".":"")+a;rt.isPlainObject(i)?Xr(i,t,o,r+1):t(o,a,i)}})}function Zr(e,t){return"splom"===e?-1:"splom"===t?1:0}Vr.manageCommandObserver=function(e,t,n,r){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Vr.hasSimpleAPICommandBindings(e,n,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Ur(e,o,a.cache),a.check=function(){if(i){var t=Ur(e,o,a.cache);return t.changed&&r&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(r({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=n.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=n._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var n=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)n.on("click",function(){ta.sendDataToCloud(e)});else{var r=window.location.pathname.split("/"),a=window.location.search;n.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+r[2].split(".")[0]+"/"+r[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},ta.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var n=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:n+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=ta.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var ra,aa=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],ia=["year","month","dayMonth","dayMonthYear"];function oa(e,t){var n,r,a=e.trace,i=a._arrayAttrs,o={};for(n=0;n1&&_.length>1){for(D.getComponentMethod("grid","sizeDefaults")(i,a),r=0;r15&&_.length>15&&0===a.shapes.length&&0===a.images.length,a._hasCartesian=a._has("cartesian"),a._hasGeo=a._has("geo"),a._hasGL3D=a._has("gl3d"),a._hasGL2D=a._has("gl2d"),a._hasTernary=a._has("ternary"),a._hasPie=a._has("pie"),ta.cleanPlot(l,a,o,n,c),ta.linkSubplots(l,a,o,n),Kr(a,n),ta.doAutoMargin(t);var A=pt.list(t);for(r=0;r0){var c=function(e){var t,n={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(n.left+=e[t].left||0,n.right+=e[t].right||0,n.bottom+=e[t].bottom||0,n.top+=e[t].top||0);return n}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=ta.layoutAttributes.width.min,v=ta.layoutAttributes.height.min;a1,m=!t.height&&Math.abs(r.height-i)>1;(m||y)&&(y&&(r.width=a),m&&(r.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),ta.sanitizeMargins(r)},ta.supplyLayoutModuleDefaults=function(e,t,n,r){var a,i,o,l=D.componentsRegistry,s=t._basePlotModules,c=D.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(D.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(rt.subplotSort);for(i=0;i.5*r.width&&(n.l=n.r=0),n.b+n.t>.5*r.height&&(n.b=n.t=0),r._pushmargin[t]={l:{val:n.x,size:n.l+a},r:{val:n.x,size:n.r+a},b:{val:n.y,size:n.b+a},t:{val:n.y,size:n.t+a}}}else delete r._pushmargin[t];r._replotting||ta.doAutoMargin(e)}},ta.doAutoMargin=function(e){var t=e._fullLayout;t._size||(t._size={}),t._pushmargin||(t._pushmargin={});var r=t._size,a=JSON.stringify(r),i=Math.max(t.margin.l||0,0),o=Math.max(t.margin.r||0,0),l=Math.max(t.margin.t||0,0),s=Math.max(t.margin.b||0,0),c=t._pushmargin;if(!1!==t.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(n(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-t.width)*h)/(m-h),_=(x*(1-h)+(p-t.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(n(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-t.height)*g)/(w-g),A=(k*(1-g)+(v-t.height)*(1-w))/(w-g);M>=0&&A>=0&&M+A>s+l&&(s=M,l=A)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(t.margin.pad),r.w=Math.round(t.width)-r.l-r.r,r.h=Math.round(t.height)-r.t-r.b,!t._replotting&&"{}"!==a&&a!==JSON.stringify(t._size))return D.call("plot",e)},ta.graphJson=function(e,t,n,r,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&ta.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(rt.isPlainObject(e)){var t,r,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===n){if("src"===t.substr(t.length-3))continue}else if("keepstream"===n){if("string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0&&!rt.isPlainObject(e.stream))continue}else if("keepall"!==n&&"string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):rt.isJSDate(e)?rt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var n=s(e);return t&&delete n.fit,n})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===r?c:JSON.stringify(c)},ta.modifyFrames=function(e,t){var n,r,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(n=0;n0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return D.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var r,o,l=0,s=0;function c(){return l++,function(){var n;f||++s!==l||(n=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return D.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(n)))}}var d=e._fullLayout._basePlotModules,h=!1;if(n)for(o=0;o=0;i--)if(s[i].enabled){n._indexToPoints=s[i]._indexToPoints;break}r&&r.calc&&(o=r.calc(e,n))}Array.isArray(o)&&o[0]||(o=[{x:Jr,y:Jr}]),o[0].t||(o[0].t={}),o[0].trace=n,c[t]=o}}for(d&&ca(o),a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];r.attr("transform","translate("+p+")")}}}A.call(T),k&&(w?A.on(".opacity",null):(b=0,_=!0,A.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),A.call(mn.makeEditable,{gd:t}).on("edit",function(e){void 0!==c?D.call("restyle",t,l,e,c):D.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(T)}).on("input",function(e){this.text(e||" ").call(mn.positionText,f.x,f.y)}));return A.classed("js-placeholder",_),p}},fa=/ [XY][0-9]* /;var da=r.FP_SAFE,ha=ya,pa=ma,ga=function(e){e._length||e.setScale();var t,n=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&n&&(e.range=ya(e),e._r=e.range.slice(),e._rl=rt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var r=e._anchorAxis.rangeslider[e._name];r&&"auto"===r.rangemode&&(r.range=n?ya(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=rt.extendFlat({},r)}},va=function(e,t,r){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!t)return;e._min||(e._min=[]);e._max||(e._max=[]);r||(r={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=t.length,y=r.padded||!1,m=r.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((e._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),A=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-da&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var T=m&&0===a;v.push({val:a,pad:T?0:b,extrapad:!T&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)T(a)};function ya(e){var t,n,r,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=ma(e);for(t=1;t0&&l>0&&s/l>d&&(i=r,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),rt.simpleMap(c,e.l2r||Number)}function ma(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function xa(e){return n(e)&&Math.abs(e)=t}var wa=r.BADNUM,ka=function(e,t){return function(e,t){for(var r,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,t)?"date":function(e){for(var t,n=Math.max(1,(e.length-1)/1e3),r=0,a=0,i=0;i2*r}(e)?"category":function(e){if(!e)return!1;for(var t=0;t0)return Math.log(e)/Math.LN10;if(e<=0&&n&&t.range&&2===t.range.length){var r=t.range[0],a=t.range[1];return.5*(r+a-3*i*Math.abs(r-a))}return Sa}function l(e,r,a){var i=Ta(e,a||t.calendar);if(i===Sa){if(!n(e))return Sa;i=Ta(new Date(+e))}return i}function s(e,n,r){return Aa(e,n,r||t.calendar)}function c(e){return t._categories[Math.round(e)]}function u(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(n(e))return+e}function f(r){return n(r)?e.round(t._b+t._m*r,2):Sa}function d(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:La,t.l2c="log"===t.type?Oa:La,t.l2p=f,t.p2l=d,t.c2p="log"===t.type?function(e,t){return f(o(e,t))}:f,t.p2c="log"===t.type?function(e){return Oa(d(e))}:d,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Ma,t.c2d=t.c2r=t.l2d=t.l2r=La,t.d2p=t.r2p=function(e){return t.l2p(Ma(e))},t.p2d=t.p2r=d,t.cleanPos=La):"log"===t.type?(t.d2r=t.d2l=function(e,t){return o(Ma(e),t)},t.r2d=t.r2c=function(e){return Oa(Ma(e))},t.d2c=t.r2l=Ma,t.c2d=t.l2r=La,t.c2r=o,t.l2d=Oa,t.d2p=function(e,n){return t.l2p(t.d2r(e,n))},t.p2d=function(e){return Oa(d(e))},t.r2p=function(e){return t.l2p(Ma(e))},t.p2r=d,t.cleanPos=La):"date"===t.type?(t.d2r=t.r2d=rt.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,n,r){return t.l2p(l(e,0,r))},t.p2d=t.p2r=function(e,t,n){return s(d(e),t,n)},t.cleanPos=function(e){return rt.cleanDate(e,Sa,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var n=t._categories.length-1;return t._categoriesMap[e]=n,n}return Sa},t.r2d=t.c2d=t.l2d=c,t.d2r=t.d2l_noadd=u,t.r2c=function(e){var n=u(e);return void 0!==n?n:t.fraction2r(.5)},t.l2r=t.c2r=La,t.r2l=u,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(e){return c(d(e))},t.r2p=t.d2p,t.p2r=d,t.cleanPos=function(e){return"string"==typeof e&&""!==e?e:La(e)}),t.fraction2r=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return t.l2r(n+e*(r-n))},t.r2fraction=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return(t.r2l(e)-n)/(r-n)},t.cleanRange=function(e,r){r||(r={}),e||(e="range");var i,o,l=rt.nestedProperty(t,e).get();if(o=(o="date"===t.type?rt.dfltRange(t.calendar):"y"===a?ht.DFLTRANGEY:r.dfltRange||ht.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=rt.cleanDate(l[0],Sa,t.calendar),l[1]=rt.cleanDate(l[1],Sa,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!rt.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=rt.constrain(t.r2l(l[0]),rt.MIN_MS+1e3,rt.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!n(l[i])){if(!n(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Ca?l[i]=-Ca:l[i]>Ca&&(l[i]=Ca),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else rt.nestedProperty(t,e).set(o)},t.setScale=function(e){var n=r._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=pt.getFromId({_fullLayout:r},t.overlaying);t.domain=i.domain}var o=e&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===a?(t._offset=n.t+(1-t.domain[1])*n.h,t._length=n.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=n.l+t.domain[0]*n.w,t._length=n.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw r._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,n){var r,a,i,o,l=t.type,s="date"===l&&e[n+"calendar"];if(n in e){if(r=e[n],o=e._length||r.length,rt.isTypedArray(r)&&("linear"===l||"log"===l)){if(o===r.length)return r;if(r.subarray)return r.subarray(0,o)}for(a=new Array(o),i=0;i2e-6||((n-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},Va.saveRangeInitial=function(e,t){for(var n=Va.list(e,"",!0),r=!1,a=0;a.3*d||u(a)||u(i))){var h=r.dtick/2;e+=e+h.8){var o=Number(n.substr(1));i.exactYears>.8&&o%12==0?e=Va.tickIncrement(e,"M6","reverse")+1.5*Ra:i.exactMonths>.8?e=Va.tickIncrement(e,"M1","reverse")+15.5*Ra:e-=Ra/2;var l=Va.tickIncrement(e,n);if(l<=r)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=Va.tickIncrement(h,l.dtick,!1,i),0;return{start:t.c2r(p,0,i),end:t.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},Va.prepTicks=function(e){var t=rt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var n,r=e.nticks;r||("category"===e.type?(n=e.tickfont?1.2*(e.tickfont.size||12):15,r=e._length/n):(n="y"===e._id.charAt(0)?40:80,r=rt.constrain(e._length/n,4,9)+1),"radialaxis"===e._name&&(r*=2)),"array"===e.tickmode&&(r*=100),Va.autoTicks(e,Math.abs(t[1]-t[0])/r),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),ti(e)},Va.calcTicks=function(e){Va.prepTicks(e);var t=rt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,n,r=e.tickvals,a=e.ticktext,i=new Array(r.length),o=rt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(n=0;nc&&t=r:s<=r)&&!(i.length>l||s===o);s=Va.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+t.substr(1)%12==0?"y":"m";else if(t>=Ra&&i<=10||t>=15*Ra)e._tickround="d";else if(t>=Ia&&i<=16||t>=Na)e._tickround="M";else if(t>=Fa&&i<=19||t>=Ia)e._tickround="S";else{var o=e.l2r(r+t).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(n(t)||"L"===t.charAt(0)){var l=e.range.map(e.r2d||Number);n(t)||(t=Number(t.substr(1))),e._tickround=2-Math.floor(Math.log(t)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(ai(e.exponentformat)&&!ii(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function ni(e,t,n){var r=e.tickfont||{};return{x:t,dx:0,dy:0,text:n||"",fontSize:r.size,font:r.family,fontColor:r.color}}Va.autoTicks=function(e,t){var r;function a(e){return Math.pow(e,Math.floor(Math.log(t)/Math.LN10))}if("date"===e.type){e.tick0=rt.dateTick0(e.calendar);var i=2*t;i>Da?(t/=Da,r=a(10),e.dtick="M"+12*ei(t,r,Xa)):i>Ea?(t/=Ea,e.dtick="M"+ei(t,1,Za)):i>Ra?(e.dtick=ei(t,Ra,Qa),e.tick0=rt.dateTick0(e.calendar,!0)):i>Na?e.dtick=ei(t,Na,Za):i>Ia?e.dtick=ei(t,Ia,Wa):i>Fa?e.dtick=ei(t,Fa,Wa):(r=a(10),e.dtick=ei(t,r,Xa))}else if("log"===e.type){e.tick0=0;var o=rt.simpleMap(e.range,e.r2l);if(t>.7)e.dtick=Math.ceil(t);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/t);t=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=a(10),e.dtick="L"+ei(t,r,Xa)}else e.dtick=t>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(t,1))):"angular"===e._id?(e.tick0=0,r=1,e.dtick=ei(t,r,Ka)):(e.tick0=0,r=a(10),e.dtick=ei(t,r,Xa));if(0===e.dtick&&(e.dtick=1),!n(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},Va.tickIncrement=function(t,r,a,i){var o=a?-1:1;if(n(r))return t+o*r;var l=r.charAt(0),s=o*Number(r.substr(1));if("M"===l)return rt.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var c="D2"===r?$a:Ja,u=t+.01*o,f=rt.roundUp(rt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(r)},Va.tickFirst=function(t){var r=t.r2l||Number,a=rt.simpleMap(t.range,r),i=a[1]"+l,e._prevDateHead=l));t.text=s}(e,o,r,s):"log"===e.type?function(e,t,r,a,i){var o=e.dtick,l=t.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))t.text=oi(Math.pow(10,l),e,i,a);else if(n(o)||"D"===o.charAt(0)&&rt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||ai(e.exponentformat)&&ii(c)?(t.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+ja+-c+"",t.fontSize*=1.25):(t.text=oi(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(t.dy-=t.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);t.text=String(Math.round(Math.pow(10,rt.mod(l,1)))),t.fontSize*=.75}if("D1"===e.dtick){var u=String(t.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?t.dx-=t.fontSize/4:(t.dy+=t.fontSize/2,t.dx+=(e.range[1]>e.range[0]?1:-1)*t.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var n=e._categories[Math.round(t.x)];void 0===n&&(n="");t.text=String(n)}(e,o):"angular"===e._id?function(e,t,n,r,a){if("radians"!==e.thetaunit||n)t.text=oi(t.x,e,a,r);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var n=function(e){var n=1;for(;!t(Math.round(e*n)/n,e);)n*=10;return n}(e),r=e*n,a=Math.abs(function e(n,r){return t(r,0)?n:e(r,n%r)}(r,n));return[Math.round(r/a),Math.round(n/a)]}(i);if(o[1]>=100)t.text=oi(rt.deg2rad(t.x),e,a,r);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=ja+t.text)}}}}(e,o,r,s,a):function(e,t,n,r,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=oi(t.x,e,a,r)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},Va.hoverLabelText=function(e,t,n){if(n!==Ba&&n!==t)return Va.hoverLabelText(e,t)+" - "+Va.hoverLabelText(e,n);var r="log"===e.type&&t<=0,a=Va.tickText(e,e.c2l(r?-t:t),"hover").text;return r?0===t?"0":ja+a:a};var ri=["f","p","n","\u03bc","m","","k","M","G","T"];function ai(e){return"SI"===e||"B"===e}function ii(e){return e>14||e<-15}function oi(e,t,r,a){var i=e<0,o=t._tickround,l=r||t.exponentformat||"B",s=t._tickexponent,c=Va.getTickFormat(t),u=t.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===t.showexponent?t.dtick:n(e)&&Math.abs(e)||1,range:"none"===t.showexponent?t.range.map(t.r2d):[0,e||1]};ti(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,t.hoverformat&&(c=t.hoverformat)}if(c)return t._numFormat(c)(e).replace(/-/g,ja);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":ai(l)&&(e+=ri[s/3+5]));return i?ja+e:e}function li(e,t){for(var n=0;n=0,i=c(e,t[1])<=0;return(n||a)&&(r||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(r))){n=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(r=1;r-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),void 0!==t.extraText&&(s+=(s?"
":"")+t.extraText),""===s&&(""===l&&n.remove(),s=l);var g=n.select("text.nums").call(Un.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(mn.positionText,0,0).call(mn.convertToTspans,r),y=n.select("text.name"),m=0;l&&l!==s?(y.call(Un.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(mn.positionText,0,0).call(mn.convertToTspans,r),m=y.node().getBoundingClientRect().width+2*yi):(y.remove(),n.select("rect").remove()),n.select("path").style({fill:d,stroke:h});var k,M,A=g.node().getBoundingClientRect(),T=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),O=A.width+vi+yi+m;t.ty0=x-A.top,t.bx=A.width+2*yi,t.by=A.height+2*yi,t.anchor="start",t.txwidth=A.width,t.tx2width=m,t.offset=0,i?(t.pos=T,k=L+S/2+O<=_,M=L-S/2-O>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=T+C/2+O<=b,M=T-C/2-O>=0,"left"!==t.idealAlign&&k||!M?k?(T+=C/2,t.anchor="start"):t.anchor="middle":(T-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),n.attr("transform","translate("+T+","+L+")"+(i?"rotate("+fi+")":""))}),C}function xi(t,n){t.each(function(t){var r=e.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(vi+yi),s=l+o*(t.txwidth+yi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+yi),n&&(u*=-gi,c=t.offset*pi),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*vi+c)+","+(vi+u)+"v"+(t.by/2-vi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*vi+c)+"V"+(u-vi)+"Z"),i.call(mn.positionText,l+c,u+t.ty0-t.by/2+yi),t.tx2width&&(r.select("text.name").call(mn.positionText,s+o*yi+c,u+t.ty0-t.by/2+yi),r.select("rect").call(Un.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function bi(e,t){var n=e.index,r=e.trace||{},a=e.cd[0],i=e.cd[n]||{},o=Array.isArray(n)?function(e,t){return rt.castOption(a,n,e)||rt.extractOption({},r,"",t)}:function(e,t){return rt.extractOption(i,r,e,t)};function l(t,n,r){var a=o(n,r);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=rt.constrain(e.x0,0,e.xa._length),e.x1=rt.constrain(e.x1,0,e.xa._length),e.y0=rt.constrain(e.y0,0,e.ya._length),e.y1=rt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:za.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:za.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=za.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+za.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=za.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+za.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function _i(e,t){var n,r,a=t.container,i=t.fullLayout,o=t.event,l=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||l){var u=Rt.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var f,d,h=e.hLinePoint;n=h&&h.xa,"cursor"===(r=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=n._offset+h.x,d=r._offset+h.y);var p,g,v=s.readability(h.color,u)<1.5?Rt.contrast(u):h.color,y=r.spikemode,m=r.spikethickness,x=r.spikecolor||v,b=r._boundingBox,_=(b.left+b.right)/2V.width||H<0||H>V.height)return Ot.unhoverRaw(t,r);r.pointerX=r.offsetX,r.pointerY=r.offsetY}if(_="xval"in r?cr.flat(o,r.xval):cr.p2c(h,B),w="yval"in r?cr.flat(o,r.yval):cr.p2c(p,H),!n(_[0])||!n(w[0]))return rt.warn("Fx.hover failed",r,t),Ot.unhoverRaw(t,r)}var U=1/0;for(M=0;ME&&(I.splice(0,E),U=I[0].distance),u&&0!==N&&0===I.length){z.distance=N,z.index=!1;var W=T._module.hoverPoints(z,O,P,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=N})),W&&W.length){var Q,J=W.filter(function(e){return e.xa.showspikes});if(J.length){var $=J[0];n($.x0)&&n($.y0)&&(Q=ne($),(!j.vLinePoint||j.vLinePoint.spikeDistance>Q.spikeDistance)&&(j.vLinePoint=Q))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];n(ee.x0)&&n(ee.y0)&&(Q=ne(ee),(!j.hLinePoint||j.hLinePoint.spikeDistance>Q.spikeDistance)&&(j.hLinePoint=Q))}}}}function te(e,t){for(var n,r=null,a=1/0,i=0;i1,ge=Rt.combine(l.plot_bgcolor||Rt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=mi(I,ve,t);if(function(e,t,n){var r,a,i,o,l,s,c,u=0,f=e.map(function(e,r){var a=e[t];return[{i:r,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?hi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?n.width:n.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],n=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=n.pos+n.dp+n.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;r=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;r=!1}if(r){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!r&&u<=e.length;){for(u++,r=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;r=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(I,pe?"xa":"ya",l),xi(ye,pe),r.target&&r.target.tagName){var me=D.getComponentMethod("annotations","hasClickToShow")(t,de);gr(e.select(r.target),me?"pointer":"")}if(!r.target||i||!function(e,t,n){if(!n||n.length!==e._hoverdata.length)return!0;for(var r=n.length-1;r>=0;r--){var a=n[r],i=e._hoverdata[r];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,fe))return;fe&&t.emit("plotly_unhover",{event:r,points:fe});t.emit("plotly_hover",{event:r,points:t._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(t,r,a,i)})},ui.loneHover=function(t,n){var r={color:t.color||Rt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(n.container),i=n.outerContainer?e.select(n.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:n.bgColor||Rt.background,container:a,outerContainer:i},l=mi([r],o,n.gd);return xi(l,o.rotateLabels),l.node()};var ki=ui.hover,Mi=function(e,t,n,r){n("hoverlabel.bgcolor",(r=r||{}).bgcolor),n("hoverlabel.bordercolor",r.bordercolor),n("hoverlabel.namelength",r.namelength),rt.coerceFont(n,"hoverlabel.font",r.font)},Ai=L({editType:"none"});Ai.family.dflt=bt.HOVERFONT,Ai.size.dflt=bt.HOVERFONTSIZE;var Ti={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Ai,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var Li={moduleType:"component",name:"fx",constants:bt,schema:{layout:Ti},attributes:C,layoutAttributes:Ti,supplyLayoutGlobalDefaults:function(e,t){Mi(0,0,function(n,r){return rt.coerce(e,t,Ti,n,r)})},supplyDefaults:function(e,t,n,r){Mi(0,0,function(n,r){return rt.coerce(e,t,C,n,r)},r.hoverlabel)},supplyLayoutDefaults:function(e,t,n){function r(n,r){return rt.coerce(e,t,Ti,n,r)}var a;"select"===r("dragmode")&&r("selectdirection"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,n=0;n0})}function c(e,r){var a=e.seg,i=r.seg,o=a.start,s=a.end,c=i.start,u=i.end;n&&n.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return r;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(r,s):l(e,u),r;p&&(h||(g?l(r,s):l(e,u)),l(r,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(r,o):0===f.alongA?l(r,f.pt):1===f.alongA&&l(r,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(n&&n.vert(f.pt[0]),f.isStart){n&&n.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}n&&n.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,n&&n.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){n&&n.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:r,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:r,f.seg.otherFill={above:v,below:v}),n&&n.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(Di.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),n&&n.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return n&&n.done(),u}return e?{addRegion:function(e){for(var r,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,n,r){var a=t[1]-n[1],i=r[0]-n[0],o=t[0]-n[0],l=r[1]-n[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,n){return Math.abs(t[0]-n[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-r>e&&(l=!l),i=c,o=u}return l}};return t}();function Hi(e,t,n){var r=Ii.segments(e),a=Ii.segments(t),i=n(Ii.combine(r,a));return Ii.polygon(i)}Ii={buildLog:function(e){return!0===e?ji=Pi():!1===e&&(ji=!1),!1!==ji&&ji.list},epsilon:function(e){return Bi.epsilon(e)},segments:function(e){var t=Ei(!0,Bi,ji);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Ei(!1,Bi,ji).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:Fi.union(e.combined,ji),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:Fi.intersect(e.combined,ji),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:Fi.difference(e.combined,ji),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:Fi.differenceRev(e.combined,ji),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:Fi.xor(e.combined,ji),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Ri(e.segments,Bi,ji),inverted:e.inverted}},polygonFromGeoJSON:function(e){return zi.toPolygon(Ii,e)},polygonToGeoJSON:function(e){return zi.fromPolygon(Ii,Bi,e)},union:function(e,t){return Hi(e,t,Ii.selectUnion)},intersect:function(e,t){return Hi(e,t,Ii.selectIntersect)},difference:function(e,t){return Hi(e,t,Ii.selectDifference)},differenceRev:function(e,t){return Hi(e,t,Ii.selectDifferenceRev)},xor:function(e,t){return Hi(e,t,Ii.selectXor)}},"object"==typeof window&&(window.PolyBool=Ii);var qi,Vi=Ii,Ui=He.dot,Gi=r.BADNUM,Yi=qi={};Yi.tester=function(e){if(Array.isArray(e[0][0]))return Yi.multitester(e);var t,n=e.slice(),r=n[0][0],a=r,i=n[0][1],o=i;for(n.push(n[0]),t=1;ta||s===Gi||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===Gi||la||s===Gi||so)return!1;var c,u,f,d,h,p=n.length,g=n[0][0],v=n[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(Ui(i,f))>r)return!0;return!1};Yi.filter=function(e,t){var n=[e[0]],r=0,a=0;function i(i){e.push(i);var o=n.length,l=r;n.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:n}};var Zi=cr.makeEventData,Wi=pt.getFromId,Qi=Wr,Ji=ht.MINSELECT,$i=qi.filter,Ki=qi.tester,eo=qi.multitester;function to(e){return e._id}function no(e,t,n){var r,a,i,o;if(n){var l=n.points||[];for(r=0;r=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function wo(e,t,n,r,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+n+", "+r+")").attr("d",a+"Z")}function ko(e,t,n){return e.append("path").attr("class","zoombox-corners").style({fill:Rt.background,stroke:Rt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+n+")").attr("d","M0,0Z")}function Mo(e,t,n,r,a,i){e.attr("d",r+"M"+n.l+","+n.t+"v"+n.h+"h"+n.w+"v-"+n.h+"h-"+n.w+"Z"),Ao(e,t,a,i)}function Ao(e,t,n,r){n||(e.transition().style("fill",r>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function To(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Lo(e){go&&e.data&&e._context.showTips&&(rt.notifier(rt._(e,"Double-click to zoom back out"),"long"),go=!1)}function Co(e){return"lasso"===e||"select"===e}function So(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,po)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function Oo(e,t){if(vt){var n=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(n,e._onwheel),e._onwheel=t,e.addEventListener(n,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}function Po(e){var t=[];for(var n in e)t.push(e[n]);return t}var zo={},Do=function(t,n,r,a,i,o,l,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k,M,A,T,L=t._fullLayout._zoomlayer,C=l+c==="nsew",S=1===(l+c).length;function O(){if(u=n.xaxis,f=n.yaxis,m=u._length,x=f._length,v=u._offset,y=f._offset,(d={})[u._id]=u,(h={})[f._id]=f,l&&c)for(var e=n.overlays,r=0;rpo||o>po?(B="xy",i/m>o/x?(o=i*x/m,R>a?N.t=R-o:N.b=R+o):(i=o*m/x,E>r?N.l=E-i:N.r=E+i),q.attr("d",So(N))):l():!w||o10||n.scrollWidth-n.clientWidth>10)){clearTimeout(Z);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var a,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),o=Q.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(A){for(c||(s=.5),a=0;a0;o&&(a="array");var l,s=n("categoryorder",a);"array"===s&&(l=n("categoryarray")),o||"array"!==s||(s=t.categoryorder="trace"),"trace"===s?t._initialCategories=[]:"array"===s?t._initialCategories=l.slice():(l=function(e,t){var n,r,a,i=t.dataAttr||e._id.charAt(0),o={};if(t.axData)n=t.axData;else for(n=[],r=0;rp[1]-.01&&(t.domain=o),rt.noneOrAll(e.domain,t.domain,o)}return r("layer"),t},qo=pt.name2id,Vo=function(e,t,n,r,a){a&&(t._name=a,t._id=qo(a)),"-"===n("type")&&(!function(e,t){if("-"!==e.type)return;var n=e._id,r=n.charAt(0);-1!==n.indexOf("scene")&&(n=r);var a=function(e,t,n){for(var r=0;r0&&a["_"+n+"axes"][t])return a;if((a[n+"axis"]||n)===t){if(Go(a,n))return a;if((a[n]||[]).length||a[n+"0"])return a}}}(t,n,r);if(!a)return;if("histogram"===a.type&&r==={v:"y",h:"x"}[a.orientation||"v"])return void(e.type="linear");var i,o=r+"calendar",l=a[o];if(Go(a,r)){var s=Uo(a),c=[];for(i=0;i rect").call(Un.setTranslate,0,0).call(Un.setScale,1,1),e.plot.call(Un.setTranslate,t._offset,n._offset).call(Un.setScale,1,1);var r=e.plot.selectAll(".scatterlayer .trace");r.selectAll(".point").call(Un.setPointGroupScale,1,1),r.selectAll(".textpoint").call(Un.setTextPointsScale,1,1),r.call(Un.hideOutsideRangePoints,e)}function g(e,n){var r,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(r=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-n)+n*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[2]=e.xaxis._length*(1-n+n*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(r=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-n)+n*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[3]=e.yaxis._length*(1-n+n*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,n){var r,a=[];for(a=[e._id,n._id],r=0;rr.duration?(function(){for(var e={},n=0;ni;if(!o)return t}return void 0!==r?r:e.dflt}(e.size,o,a.size),color:function(e,t,n){return s(t).isValid()?t:void 0!==n?n:e.dflt}(e.color,l,a.color)}}function Ml(e,t){var n;return Array.isArray(e)?tc+l||!n(s))&&(f=!0,Il(u,e))}for(var h=0;h0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var q=Math.pow(10,Math.floor(Math.log(H)/Math.LN10));j*=q*rt.roundUp(H/q,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(I.tick0=0)}I.dtick=j}I.domain=[z+S,z+T-S],I.setScale();var V=rt.ensureSingle(o._infolayer,"g",n,function(t){t.classed(Ul.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(Ul.cbbg,!0),t.append("g").classed(Ul.cbfills,!0),t.append("g").classed(Ul.cblines,!0),t.append("g").classed(Ul.cbaxis,!0).classed(Ul.crisp,!0),t.append("g").classed(Ul.cbtitleunshift,!0).append("g").classed(Ul.cbtitle,!0),t.append("rect").classed(Ul.cboutline,!0),t.select(".cbtitle").datum(0)})});V.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");I._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var Y,X=l.l+(r.x+L)*l.w,Z=I.titlefont.size;Y="top"===r.titleside?(1-(z+T-S))*l.h+l.t+3+.75*Z:(1-(z+S))*l.h+l.t-3-.25*Z,ee(I._id+"title",{attributes:{x:X,y:Y,"text-anchor":"start"}})}var W,Q,J,$=rt.syncOrAsync([Qr.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var n=V.select(".cbtitle"),a=n.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],c=n.select(".h"+I._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*Vl),c?(G=Un.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(Ul.jsPlaceholder)&&(G=Un.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)I.domain[1]-=G/l.h,i[1]*=-1;else{I.domain[0]+=G/l.h;var v=mn.lineCount(a);i[1]+=(1-v)*u}n.attr("transform","translate("+i+")"),I.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-I.domain[1]))+")"),I._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(Ul.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,n){var r=[0===n?f[0]:(h[n]+h[n-1])/2,n===h.length-1?f[1]:(h[n]+h[n+1])/2].map(I.c2p).map(Math.round);n!==h.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=s(a).toHexString();e.select(this).attr({x:O,width:Math.max(k,2),y:e.min(r),height:Math.max(e.max(r)-e.min(r),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?d:[]);return m.enter().append("path").classed(Ul.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+O+","+(Math.round(I.c2p(t))+r.line.width/2%1)+"h"+k).call(Un.lineGroupStyle,r.line.width,p(t),r.line.dash)}),I._axislayer.selectAll("g."+I._id+"tick,path").remove(),I._pos=O+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),I.side="right",rt.syncOrAsync([function(){return za.doTicks(t,I,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var n=I.titlefont.size,a=I._offset+I._length/2,i=l.l+(I.position||0)*l.w+("right"===I.side?10+n*(I.showticklabels?1:.5):-10-n*(I.showticklabels?.5:0));ee("h"+I._id+"title",{avoid:{selection:e.select(t).selectAll("g."+I._id+"tick"),side:r.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Qr.previousPromises,function(){var e=k+r.outlinewidth/2+Un.bBox(I._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(Ul.jsPlaceholder)){var a,i=U.select(".h"+I._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Un.bBox(i).width:Un.bBox(U.node()).right-O-l.l,e=Math.max(e,a)}var o=2*r.xpad+e+r.borderwidth+r.outlinewidth/2,s=E-R;V.select(".cbbg").attr({x:O-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:R-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(Rt.fill,r.bgcolor).call(Rt.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),V.selectAll(".cboutline").attr({x:O,y:R+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(s-2*r.ypad-G,2)}).call(Rt.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*o;V.attr("transform","translate("+(l.l-c)+","+l.t+")"),Qr.autoMargin(t,n,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:s*({bottom:1,middle:.5}[r.yanchor]||0),b:s*({top:1,middle:.5}[r.yanchor]||0)})}],t);return $&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition&&Ot.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),hr(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),Q=Ot.align(P+e/l.w,M,0,1,r.xanchor),J=Ot.align(z-t/l.h,T,0,1,r.yanchor);var n=Ot.getCursor(Q,J,r.xanchor,r.yanchor);hr(V,n)},doneFn:function(){hr(V),void 0!==Q&&void 0!==J&&D.call("restyle",t,{"colorbar.x":Q,"colorbar.y":J},i().index)}}),$}function K(e,t){return rt.coerce(N,I,nn,e,t)}function ee(e,n){var r,a=i();r=D.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:I,propName:r,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),ua.draw(t,e,ql(l,n||{}))}o._infolayer.selectAll("g."+n).remove()}function i(){var e,r,a=n.substr(2);for(e=0;e.01?A:function(e,t){return Math.abs(e-t)>=2?A(e):e>t?Math.ceil(e):Math.floor(e)};p=k(p,h=k(h,p)),v=k(v,g=k(g,v))}var M=e.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+h+","+g+"V"+v+"H"+p+"V"+g+"Z").call(Un.setClipUrl,r.layerClipId),function(e,t,n,r,a,i,o,l){var s;function c(t,n,r){var a=t.append("text").text(n).attr({class:"bartext bartext-"+s,transform:"","text-anchor":"middle","data-notex":1}).call(Un.font,r).call(mn.convertToTspans,e);return a}var u=n[0].trace,f=u.orientation,d=function(e,t){var n=Ml(e.text,t);return Al(vl,n)}(u,r);if(d&&"none"!==(s=function(e,t){var n=Ml(e.textposition,t);return function(e,t,n){return e.coerceNumber&&(t=+t),-1!==e.values.indexOf(t)?t:void 0!==n?n:e.dflt}(yl,n)}(u,r))){var h,p,g,v,y,m,x=function(e,t,n){return kl(ml,e.textfont,t,n)}(u,r,e._fullLayout.font),b=function(e,t,n){return kl(xl,e.insidetextfont,t,n)}(u,r,x),_=function(e,t,n){return kl(bl,e.outsidetextfont,t,n)}(u,r,x),w=e._fullLayout.barmode,k="stack"===w||"relative"===w,M=n[r],A=!k||M._outmost,T=Math.abs(i-a)-2*_l,L=Math.abs(l-o)-2*_l;if("outside"===s&&(A||(s="inside")),"auto"===s)if(A){s="inside",h=c(t,d,b),p=Un.bBox(h.node()),g=p.width,v=p.height;var C=g>0&&v>0,S=g<=T&&v<=L,O=g<=L&&v<=T,P="h"===f?T>=g*(L/v):L>=v*(T/g);C&&(S||O||P)?s="inside":(s="outside",h.remove(),h=null)}else s="inside";!h&&(h=c(t,d,"outside"===s?_:b),p=Un.bBox(h.node()),g=p.width,v=p.height,g<=0||v<=0)?h.remove():("outside"===s?(m="both"===u.constraintext||"outside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s="h"===i?Math.abs(r-n):Math.abs(t-e);s>2*_l&&(l=_l);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,h,p=(a.left+a.right)/2,g=(a.top+a.bottom)/2;return u=c*a.width,f=c*a.height,"h"===i?tn?(d=(e+t)/2,h=r+l+f/2):(d=(e+t)/2,h=r-l-f/2),wl(p,g,d,h,c,!1)}(a,i,o,l,p,f,m)):(m="both"===u.constraintext||"inside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s,c,u,f,d,h,p=a.width,g=a.height,v=(a.left+a.right)/2,y=(a.top+a.bottom)/2,m=Math.abs(t-e),x=Math.abs(r-n);return m>2*_l&&x>2*_l?(m-=2*(f=_l),x-=2*f):f=0,p<=m&&g<=x?(d=!1,h=1):p<=x&&g<=m?(d=!0,h=1):pn?(c=(e+t)/2,u=r-f-s/2):(c=(e+t)/2,u=r+f+s/2),wl(v,y,c,u,h,d)}(a,i,o,l,p,f,m)),h.attr("transform",y))}}(t,M,a,c,h,p,g,v),r.layerClipId&&Un.hideOutsideRangePoint(a[c],M.select("text"),i,o,u.xcalendar,u.ycalendar)}else e.select(this).remove();function A(t){return 0===l.bargap&&0===l.bargroupgap?e.round(Math.round(t)-w,2):t}})}),D.getComponentMethod("errorbars","plot")(s,r),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Un.setClipUrl(e.select(this),n?null:r.layerClipId)})},Yl.style=function(t,n){var r=n?n[0].node3:e.select(t).selectAll("g.trace.bars"),a=r.size(),i=t._fullLayout;r.style("opacity",function(e){return e[0].trace.opacity}).each(function(t){("stack"===i.barmode&&a>1||0===i.bargap&&0===i.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(n){var r=e.select(this),a=r.selectAll("path"),i=r.selectAll("text"),o=n[0].trace;Un.pointStyle(a,o,t),Un.selectedPointStyle(a,o),i.each(function(t){var n,r=e.select(this);function a(e){var r=n[e];return Array.isArray(r)?r[t.i]:r}r.classed("bartext-inside")?n=o.insidetextfont:r.classed("bartext-outside")&&(n=o.outsidetextfont),n||(n=o.textfont),Un.font(r,a("family"),a("size"),a("color"))}),Un.selectedTextStyle(i,o)}),D.getComponentMethod("errorbars","style")(r)},Yl.hoverPoints=function(e,t,n,r){var a,i,o,l,s,c,u,f=e.cd,d=f[0].trace,h=f[0].t,p="closest"===r,g=e.maxHoverDistance,v=e.maxSpikeDistance;function y(e){return e[o]-e.w/2}function m(e){return e[o]+e.w/2}var x=p?y:function(e){return Math.min(y(e),e.p-h.bardelta/2)},b=p?m:function(e){return Math.max(m(e),e.p+h.bardelta/2)};function _(e,t){return Li.inbox(e-a,t-a,g+Math.min(1,Math.abs(t-e)/u)-1)}function w(e){return _(x(e),b(e))}function k(e){return Li.inbox(e.b-i,e[l]-i,g+(e[l]-i)/(e[l]-e.b)-1)}"h"===d.orientation?(a=n,i=t,o="y",l="x",s=k,c=w):(a=t,i=n,o="x",l="y",c=k,s=w);var M=e[o+"a"],A=e[l+"a"];u=Math.abs(M.r2c(M.range[1])-M.r2c(M.range[0]));var T=Li.getDistanceFunction(r,s,c,function(e){return(s(e)+c(e))/2});if(Li.getClosest(f,T,e),!1!==e.index){p||(x=function(e){return Math.min(y(e),e.p-h.bargroupwidth/2)},b=function(e){return Math.max(m(e),e.p+h.bargroupwidth/2)});var L=f[e.index],C=L.mcc||d.marker.color,S=L.mlcc||d.marker.line.color,O=L.mlw||d.marker.line.width;Rt.opacity(C)?e.color=C:Rt.opacity(S)&&O&&(e.color=S);var P=d.base?L.b+L.s:L.s;e[l+"0"]=e[l+"1"]=A.c2p(L[l],!0),e[l+"LabelVal"]=P;var z=h.extents[h.extents.round(L.p)];return e[o+"0"]=M.c2p(p?x(L):z[0],!0),e[o+"1"]=M.c2p(p?b(L):z[1],!0),e[o+"LabelVal"]=L.p,e.spikeDistance=(k(L)+function(e){return _(y(e),m(e))}(L))/2+v-g,e[o+"Spike"]=M.c2p(L.p,!0),hl(L,d,e),D.getComponentMethod("errorbars","hoverInfo")(L,d,e),[e]}},Yl.selectPoints=function(e,t){var n,r=e.cd,a=e.xaxis,i=e.yaxis,o=[];if(!1===t)for(n=0;n1)for(var n=1;n=0,p=n.indexOf("end")>=0,g=c.backoff*f+r.standoff,v=u.backoff*d+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}n._w=C,n._h=S;for(var E=!1,R=["x","y"],N=0;N1)&&(U===V?((K=G.r2fraction(n["a"+q]))<0||K>1)&&(E=!0):E=!0,E))continue;I=G._offset+G.r2p(n[q]),B=.5}else"x"===q?(j=n[q],I=u.l+u.w*j):(j=1-n[q],I=u.t+u.h*j),B=n.showarrow?.5:j;if(n.showarrow){$.head=I;var ee=n["a"+q];H=X*z(.5,n.xanchor)-Z*z(.5,n.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=H):($.tail=I+ee,F=H+ee),$.text=$.tail+H;var te=c["x"===q?"width":"height"];if("paper"===V&&($.head=rt.constrain($.head,1,te-1)),"pixel"===U){var ne=-Math.max($.tail-3,$.text),re=Math.min($.tail+3,$.text)-te;ne>0?($.tail+=ne,$.text+=ne):re>0&&($.tail-=re,$.text-=re)}$.tail+=J,$.head+=J}else F=H=W*z(B,Q),$.text=I+H;$.text+=J,H+=J,F+=J,n["_"+q+"padplus"]=W/2+F,n["_"+q+"padminus"]=W/2-F,n["_"+q+"size"]=W,n["_"+q+"shift"]=H}if(E)x.remove();else{var ae=0,ie=0;if("left"!==n.align&&(ae=(C-_)*("center"===n.align?.5:1)),"top"!==n.valign&&(ie=(S-T)*("middle"===n.valign?.5:1)),l)r.select("svg").attr({x:w+ae-1,y:w+ie}).call(Un.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(mn.positionText,le,oe).call(Un.setClipUrl,M?d:null)}A.select("rect").call(Un.setRect,w,w,C,S),k.call(Un.setRect,b/2,b/2,O-b,P-b),x.call(Un.setTranslate,Math.round(h.x.text-O/2),Math.round(h.y.text-P/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,r){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+r,m=h.x.text+e,b=h.y.text+r,_=rt.rotationXYMatrix(p,m,b),w=rt.apply2DTransform(_),M=rt.apply2DTransform2(_),A=+k.attr("width"),T=+k.attr("height"),L=m-.5*A,C=L+A,S=b-.5*T,O=S+T,P=[[L,S,L,O],[L,O,C,O],[C,O,C,S],[C,S,L,S]].map(M);if(!P.reduce(function(e,t){return e^!!rt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){P.forEach(function(e){var t=rt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var z=n.arrowwidth,E=n.arrowcolor,R=n.arrowside,N=g.append("g").style({opacity:Rt.opacity(E)}).classed("annotation-arrow-g",!0),I=N.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",z+"px").call(Rt.stroke,Rt.rgb(E));if(vs(I,R,n),f.annotationPosition&&I.node().parentNode&&!a){var F=l,j=c;if(n.standoff){var B=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=n.standoff*(d-l)/B,j+=n.standoff*(y-c)/B}var H,q,V,U=N.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-j),transform:"translate("+F+","+j+")"}).style("stroke-width",z+6+"px").call(Rt.stroke,"rgba(0,0,0,0)").call(Rt.fill,"rgba(0,0,0,0)");Ot.init({element:U.node(),gd:t,prepFn:function(){var e=Un.getTranslate(x);q=e.x,V=e.y,H={},i&&i.autorange&&(H[i._name+".autorange"]=!0),o&&o.autorange&&(H[o._name+".autorange"]=!0)},moveFn:function(e,t){var r=w(q,V),a=r[0]+e,l=r[1]+t;x.call(Un.setTranslate,a,l),H[s+".x"]=i?i.p2r(i.r2p(n.x)+e):n.x+e/u.w,H[s+".y"]=o?o.p2r(o.r2p(n.y)+t):n.y-t/u.h,n.axref===n.xref&&(H[s+".ax"]=i.p2r(i.r2p(n.ax)+e)),n.ayref===n.yref&&(H[s+".ay"]=o.p2r(o.r2p(n.ay)+t)),N.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){D.call("relayout",t,H);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(n.showarrow&&ue(0,0),y)Ot.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var r="pointer";if(n.showarrow)n.axref===n.xref?se[s+".ax"]=i.p2r(i.r2p(n.ax)+e):se[s+".ax"]=n.ax+e,n.ayref===n.yref?se[s+".ay"]=o.p2r(o.r2p(n.ay)+t):se[s+".ay"]=n.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(n.x)+e);else{var l=n._xsize/u.w,c=n.x+(n._xshift-n.xshift)/u.w-l/2;se[s+".x"]=Ot.align(c+e/u.w,l,0,1,n.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(n.y)+t);else{var f=n._ysize/u.h,d=n.y-(n._yshift+n.yshift)/u.h-f/2;se[s+".y"]=Ot.align(d-t/u.h,f,0,1,n.yanchor)}i&&o||(r=Ot.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],n.xanchor,n.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),hr(x,r)},doneFn:function(){hr(x),D.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var bs=ys.draw;function _s(e){var t=e._fullLayout;rt.filterVisible(t.annotations).forEach(function(t){var n,r,a,i,o=za.getFromId(e,t.xref),l=za.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(n=s+t.xshift,r=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(za.expand(o,[o.r2c(t.x)],{ppadplus:n,ppadminus:r}),za.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,za.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,n,a),ppadminus:Math.max(t._xpadminus,r,i)}))),l&&l.autorange&&(n=s-t.yshift,r=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(za.expand(l,[l.r2c(t.y)],{ppadplus:n,ppadminus:r}),za.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,za.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,n,a),ppadminus:Math.max(t._ypadminus,r,i)})))})}var ws={hasClickToShow:function(e,t){var n=ks(e,t);return n.on.length>0||n.explicitOff.length>0},onClick:function(e,t){var n,r=ks(e,t),a=r.on,i=r.off.concat(r.explicitOff),o={};if(!a.length&&!i.length)return;for(n=0;n1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=Es(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*n[0],t.yaxis.r2l(i.y)*n[1],t.zaxis.r2l(i.z)*n[2]]),Rs(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var Fs={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},js=function(e){var t=e.type,n=e.symmetric;if("data"===t){var r=e.array||[];if(n)return function(e,t){var n=+r[t];return[n,n]};var a=e.arrayminus||[];return function(e,t){var n=+r[t],i=+a[t];return isNaN(n)&&isNaN(i)?[NaN,NaN]:[i||0,n||0]}}var i=Bs(t,e.value),o=Bs(t,e.valueminus);return n||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function Bs(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var Hs=function(e){for(var t=e.calcdata,n=0;n0;t.each(function(t){var s,c=t[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Vn.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(t=[]);var h=e.select(this).selectAll("g.errorbar").data(t,s);if(h.exit().remove(),t.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Un.setClipUrl(h,r.layerClipId),h.each(function(t){var r=e.select(this),s=function(e,t,r){var a={x:t.c2p(e.x),y:r.c2p(e.y)};return void 0!==e.yh&&(a.yh=r.c2p(e.yh),a.ys=r.c2p(e.ys),n(a.ys)||(a.noYS=!0,a.ys=r.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=t.c2p(e.xh),a.xs=t.c2p(e.xs),n(a.xs)||(a.noXS=!0,a.xs=t.c2p(e.xs,!0))),a}(t,i,o);if(!d||t.vis){var c,h=r.select("path.yerror");if(f.visible&&n(s.x)&&n(s.yh)&&n(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=r.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=r.select("path.xerror");if(u.visible&&n(s.y)&&n(s.xh)&&n(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=r.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var n=t[0].trace,r=n.error_y||{},a=n.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(Rt.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(Rt.stroke,a.color)})},hoverInfo:function(e,t,n){(t.error_y||{}).visible&&(n.yerr=e.yh-e.y,t.error_y.symmetric||(n.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(n.xerr=e.xh-e.x,t.error_x.symmetric||(n.xerrneg=e.x-e.xs))}};var Xs={},Zs=m.extendFlat;Xs.attributes=function(e,t){e=e||{},t=t||{};var n={valType:"info_array",editType:e.editType,items:[{valType:"number",min:0,max:1,editType:e.editType},{valType:"number",min:0,max:1,editType:e.editType}],dflt:[0,1]},r=(e.name&&e.name,e.trace,t.description&&t.description,{x:Zs({},n,{}),y:Zs({},n,{}),editType:e.editType});return e.noGridCell||(r.row={valType:"integer",min:0,dflt:0,editType:e.editType},r.column={valType:"integer",min:0,dflt:0,editType:e.editType}),r},Xs.defaults=function(e,t,n,r){var a=r&&r.x||[0,1],i=r&&r.y||[0,1],o=t.grid;if(o){var l=n("domain.column");void 0!==l&&(l1){l||s||c||"independent"===x("pattern")&&(l=!0),f._hasSubplotGrid=l;var p,g,v="top to bottom"===x("roworder"),y=l?.2:.1,m=l?.3:.1;u&&(p="bottom",g="left"),f._domains={x:ec("x",x,y,p,h),y:ec("y",x,m,g,d,v)}}}function x(e,t){return rt.coerce(n,f,$s,e,t)}},contentDefaults:function(e,t){var n=t.grid;if(n&&n._domains){var r,a,i,o,l,s,c,u=e.grid||{},f=t._subplots,d=n._hasSubplotGrid,h=n.rows,p=n.columns,g="independent"===n.pattern,v=n._axisMap={};if(d){var y=u.subplots||[];s=n.subplots=new Array(h);var m=1;for(r=0;r=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},cc={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},uc=!0,fc=function(e,t,n){if(!t._dragged&&!t._editing){var r,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===n&&uc&&t.data&&t._context.showTips?(rt.notifier(rt._(t,"Double-click on legend to isolate one trace"),"long"),uc=!1):uc=!1,D.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===n?-1===m?s.push(y):s.splice(m,1):2===n&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),D.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(r=0;rn[1])return n[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",rt.mean,[.2,1]),d.ms=u("marker.size",rt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",rt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),r=[rt.minExtend(i,d)],a=rt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Un.pointStyle,a,n),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Un.textPointStyle,a,n)}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(e,t){return t?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("stroke-width",i+"px").call(Rt.fill,a.fillcolor),i&&Rt.stroke(o,a.line.color)})}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(e,t){return t?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("fill","none").call(Un.dashLine,a.line.dash,i),i&&Rt.stroke(o,a.line.color)})})},vc=vn.LINE_SPACING,yc=vn.FROM_TL,mc=vn.FROM_BR,xc=h.DBLCLICKDELAY;function bc(e,t){var n=e.data()[0][0],r=t._fullLayout,a=n.trace,i=D.traceIs(a,"pie"),o=a.index,l=i?n.label:a.name,s=rt.ensureSingle(e,"text","legendtext");function c(n){mn.convertToTspans(n,t,function(){!function(e,t){var n=e.data()[0][0];if(!n.trace.showlegend)return void e.remove();var r,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*vc;if(o){var s=Un.bBox(o);r=s.height,a=s.width,Un.setTranslate(i,0,r/4)}else{var c=e.select(".legendtext"),u=mn.lineCount(c),f=c.node();r=l*u,a=f?Un.bBox(f).width:0;var d=l*(.3+(1-u)/2);mn.positionText(c,40,d)}r=Math.max(r,16)+3,n.height=r,n.width=a}(e,t)})}s.attr("text-anchor","start").classed("user-select-none",!0).call(Un.font,r.legend.font).text(l),t._context.edits.legendText&&!i?s.call(mn.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var r=e;this.text()||(e=" ");var a=n.trace._fullInput||{},i={};if(D.hasTransform(a,"groupby")){var l=D.getTransformIndices(a,"groupby"),s=l[l.length-1],u=rt.keyedContainer(a,"transforms["+s+"].styles","target","value.name");""===r?u.remove(n.trace._group):u.set(n.trace._group,e),i=u.constructUpdate()}else i.name=e;return D.call("restyle",t,i,o)}):c(s)}function _c(e,t){var n,r=1,a=rt.ensureSingle(e,"rect","legendtoggle",function(e){e.style("cursor","pointer").attr("pointer-events","all").call(Rt.fill,"rgba(0,0,0,0)")});a.on("mousedown",function(){(n=(new Date).getTime())-t._legendMouseDownTimexc&&(r=Math.max(r-1,1)),1===r?n._clickTimeout=setTimeout(function(){fc(e,t,r)},xc):2===r&&(n._clickTimeout&&clearTimeout(n._clickTimeout),t._legendMouseDownTime=0,fc(e,t,r))}})}function wc(t,n,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=lc.isGrouped(i),s=0;if(i._width=0,i._height=0,lc.isVertical(i))l&&n.each(function(e,t){Un.setTranslate(this,0,t*i.tracegroupgap)}),r.each(function(e){var t=e[0],n=t.height,r=t.width;Un.setTranslate(this,o,5+o+i._height+n/2),i._height+=n,i._width=Math.max(i._width,r)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=n.data(),f=0,d=u.length;fo+b-_,r.each(function(e){var t=e[0],n=g?40+e[0].width:m;o+x+_+n>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Un.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+n,i._height=Math.max(i._height,t.height),x+=_+n,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(n){var r=n[0],a=e.select(this).select(".legendtoggle");Un.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function kc(e){var t=e._fullLayout.legend,n="left";sc.isRightAnchor(t)?n="right":sc.isCenterAnchor(t)&&(n="center");var r="top";sc.isBottomAnchor(t)?r="bottom":sc.isMiddleAnchor(t)&&(r="middle"),Qr.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*yc[n],r:t._width*mc[n],b:t._height*mc[r],t:t._height*yc[r]})}var Mc={moduleType:"component",name:"legend",layoutAttributes:oc,supplyLayoutDefaults:function(e,t,n){for(var r,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),rt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(r=0,i="left",a=1.1,o="bottom"):(r=0,i="left",a=-.1,o="top")}h("traceorder",u),lc.isGrouped(t.legend)&&h("tracegroupgap"),h("x",r),h("xanchor",i),h("y",a),h("yanchor",o),rt.noneOrAll(l,s,["x","y"])}},draw:function(t){var n=t._fullLayout,r="legend"+n._uid;if(n._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=n.legend,i=n.showlegend&&function(e,t){var n,r,a={},i=[],o=!1,l={},s=0;function c(e,n){if(""!==e&&lc.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[n]]):a[e].push([n]);else{var r="~~i"+s;i.push(r),a[r]=[[n]],s++}}for(n=0;nv?function(e){var t=e._fullLayout.legend,n="left";sc.isRightAnchor(t)?n="right":sc.isCenterAnchor(t)&&(n="center"),Qr.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*yc[n],r:t._width*mc[n],b:0,t:0})}(t):kc(t);var y=n._size,m=y.l+y.w*a.x,x=y.t+y.h*(1-a.y);sc.isRightAnchor(a)?m-=a._width:sc.isCenterAnchor(a)&&(m-=a._width/2),sc.isBottomAnchor(a)?x-=a._height:sc.isMiddleAnchor(a)&&(x-=a._height/2);var b=a._width,_=y.w;b>_?(m=y.l,b=_):(m+b>g&&(m=g-b),m<0&&(m=0),b=Math.min(g-m,a._width));var w,k,M,A,T=a._height,L=y.h;if(T>L?(x=y.t,T=L):(x+T>v&&(x=v-T),x<0&&(x=0),T=Math.min(v-x,a._height)),Un.setTranslate(s,m,x),d.on(".drag",null),s.on("wheel",null),a._height<=T||t._context.staticPlot)u.attr({width:b-a.borderwidth,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Un.setTranslate(f,0,0),c.select("rect").attr({width:b-2*a.borderwidth,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Un.setClipUrl(f,r),Un.setRect(d,0,0,0,0),delete a._scrollY;else{var C,S,O=Math.max(cc.scrollBarMinHeight,T*T/a._height),P=T-O-2*cc.scrollBarMargin,z=a._height-T,E=P/z,R=Math.min(a._scrollY||0,z);u.attr({width:b-2*a.borderwidth+cc.scrollBarWidth+cc.scrollBarMargin,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),c.select("rect").attr({width:b-2*a.borderwidth+cc.scrollBarWidth+cc.scrollBarMargin,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+R}),Un.setClipUrl(f,r),I(R,O,E),s.on("wheel",function(){I(R=rt.constrain(a._scrollY+e.event.deltaY/P*z,0,z),O,E),0!==R&&R!==z&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){C=e.event.sourceEvent.clientY,S=R}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||I(R=rt.constrain((t.clientY-C)/E+S,0,z),O,E)});d.call(N)}t._context.edits.legendPosition&&(s.classed("cursor-move",!0),Ot.init({element:s.node(),gd:t,prepFn:function(){var e=Un.getTranslate(s);M=e.x,A=e.y},moveFn:function(e,t){var n=M+e,r=A+t;Un.setTranslate(s,n,r),w=Ot.align(n,0,y.l,y.l+y.w,a.xanchor),k=Ot.align(r,0,y.t+y.h,y.t,a.yanchor)},doneFn:function(){void 0!==w&&void 0!==k&&D.call("relayout",t,{"legend.x":w,"legend.y":k})},clickFn:function(e,r){var a=n._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return r.clientX>=e.left&&r.clientX<=e.right&&r.clientY>=e.top&&r.clientY<=e.bottom});a.size()>0&&(1===e?s._clickTimeout=setTimeout(function(){fc(a,t,e)},xc):2===e&&(s._clickTimeout&&clearTimeout(s._clickTimeout),fc(a,t,e)))}}))}function I(e,n,r){a._scrollY=t._fullLayout.legend._scrollY=e,Un.setTranslate(f,0,-e),Un.setRect(d,b,cc.scrollBarMargin+e*r,cc.scrollBarWidth,n),c.select("rect").attr({y:a.borderwidth+e})}},style:gc},Ac={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},Tc=m.extendFlat,Lc={visible:{valType:"boolean",editType:"plot"},buttons:Ac=Tc(Ac,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:L({editType:"plot"}),bgcolor:{valType:"color",dflt:O.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:O.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},Cc={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var Sc=function(t,n){var r=t._name,a={};if("all"===n.step)a[r+".autorange"]=!0;else{var i=function(t,n){var r,a=t.range,i=new Date(t.r2l(a[1])),o=n.step,l=n.count;switch(n.stepmode){case"backward":r=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);r=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,n);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var Oc=vn.LINE_SPACING,Pc=vn.FROM_TL,zc=vn.FROM_BR;function Dc(e){return e._id}function Ec(e,t,n){var r=rt.ensureSingle(e,"rect","selector-rect",function(e){e.attr("shape-rendering","crispEdges")});r.attr({rx:Cc.rx,ry:Cc.ry}),r.call(Rt.stroke,t.bordercolor).call(Rt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,n)).style("stroke-width",t.borderwidth+"px")}function Rc(e,t,n,r){var a;rt.ensureSingle(e,"text","selector-text",function(e){e.classed("user-select-none",!0).attr("text-anchor","middle")}).call(Un.font,t.font).text((a=n,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){mn.convertToTspans(e,r)})}var Nc={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:Lc}}},layoutAttributes:Lc,handleDefaults:function(e,t,n,r,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return rt.coerce(i,o,Lc,e,t)}if(l("visible",function(e,t,n){var r,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return rt.coerce(r,a,Ac,e,t)}for(var s=0;s0)){var s=function(e,t,n){for(var r=n.filter(function(n){return t[n].anchor===e._id}),a=0,i=0;i0?c+o:o;return{ppad:o,ppadplus:l?f:d,ppadminus:l?d:f}}return{ppad:o}}function au(e,t,n,r,a){var i="category"===e.type?e.r2c:e.d2c;if(void 0!==t)return[i(t),i(n)];if(r){var o,l,s,c,u=1/0,f=-1/0,d=r.match(Kc.segmentRE);for("date"===e.type&&(i=eu.decodeDate(i)),o=0;of&&(f=c)));return f>=u?[u,f]:void 0}}var iu=function(e,t,n,r,a){function i(n,r){return rt.coerce(e,t,$c,n,r)}if(r=r||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=i("xsizemode"),s=i("ysizemode"),c=["x","y"],u=0;u<2;u++){var f,d,h,p=c[u],g=p+"anchor",v="x"===p?l:s,y={_fullLayout:n},m=za.coerceRef(e,t,y,p,"","paper");if("paper"!==m?(f=za.getFromId(y,m),h=eu.rangeToShapePosition(f),d=eu.shapePositionToRange(f)):d=h=rt.identity,"path"!==o){var x=p+"0",b=p+"1",_=e[x],w=e[b];e[x]=d(e[x],!0),e[b]=d(e[b],!0),"pixel"===v?(i(x,0),i(b,10)):(za.coercePosition(t,y,i,m,x,.25),za.coercePosition(t,y,i,m,b,.75)),t[x]=h(t[x]),t[b]=h(t[b]),e[x]=_,e[b]=w}if("pixel"===v){var k=e[g];e[g]=d(e[g],!0),za.coercePosition(t,y,i,m,g,.25),t[g]=h(t[g]),e[g]=k}}return"path"===o?i("path"):rt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},ou={draw:function(e){var t=e._fullLayout;for(var n in t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._plots){var r=t._plots[n].shapelayer;r&&r.selectAll("path").remove()}for(var a=0;as?(y=o,_=D+".y0",A="y0",m=s,w=D+".y1",T="y1"):(y=s,_=D+".y1",A="y1",m=o,w=D+".y0",T="y0");a={},U(t),V.moveFn="move"===F?G:Y},doneFn:function(){hr(t),D.call("relayout",e,a)}};function U(e){var n=V.element.getBoundingClientRect(),r=n.right-n.left,a=n.bottom-n.top,i=e.clientX-n.left,o=e.clientY-n.top,l=r>j&&a>B&&!e.shiftKey?Ot.getCursor(i/r,1-o/a):"move";hr(t,l),F=l.split("-")[0]}function G(r,y){if("path"===n.type){var m=function(e){return e},x=m,b=m;H?a[g]=n.xanchor=N(c+r):(x=function(e){return N(E(e)+r)},P&&"date"===P.type&&(x=eu.encodeDate(x))),q?a[v]=n.yanchor=I(u+y):(b=function(e){return I(R(e)+y)},z&&"date"===z.type&&(b=eu.encodeDate(b))),n.path=cu(S,x,b),a[O]=n.path}else H?a[g]=n.xanchor=N(c+r):(a[f]=n.x0=N(i+r),a[h]=n.x1=N(l+r)),q?a[v]=n.yanchor=I(u+y):(a[d]=n.y0=I(o+y),a[p]=n.y1=I(s+y));t.attr("d",su(e,n))}function Y(r,i){if("path"===n.type){var o=function(e){return e},l=o,s=o;H?a[g]=n.xanchor=N(c+r):(l=function(e){return N(E(e)+r)},P&&"date"===P.type&&(l=eu.encodeDate(l))),q?a[v]=n.yanchor=I(u+i):(s=function(e){return I(R(e)+i)},z&&"date"===z.type&&(s=eu.encodeDate(s))),n.path=cu(S,l,s),a[O]=n.path}else{var f=~F.indexOf("n")?y+i:y,d=~F.indexOf("s")?m+i:m,h=~F.indexOf("w")?x+r:x,p=~F.indexOf("e")?b+r:b;~F.indexOf("n")&&q&&(f=y-i),~F.indexOf("s")&&q&&(d=m-i),(!q&&d-f>B||q&&f-d>B)&&(a[_]=n[A]=q?f:I(f),a[w]=n[T]=q?d:I(d)),p-h>j&&(a[k]=n[L]=H?h:N(h),a[M]=n[C]=H?p:N(p))}t.attr("d",su(e,n))}Ot.init(V),t.node().onmousemove=U}(e,o,r,t)}}function su(e,t){var n,r,a,i,o,l,s,c,u=t.type,f=za.getFromId(e,t.xref),d=za.getFromId(e,t.yref),h=e._fullLayout._size;if(f?(n=eu.shapePositionToRange(f),r=function(e){return f._offset+f.r2p(n(e,!0))}):r=function(e){return h.l+h.w*e},d?(a=eu.shapePositionToRange(d),i=function(e){return d._offset+d.r2p(a(e,!0))}):i=function(e){return h.t+h.h*(1-e)},"path"===u)return f&&"date"===f.type&&(r=eu.decodeDate(r)),d&&"date"===d.type&&(i=eu.decodeDate(i)),function(e,t,n){var r=e.path,a=e.xsizemode,i=e.ysizemode,o=e.xanchor,l=e.yanchor;return r.replace(Kc.segmentRE,function(e){var r=0,s=e.charAt(0),c=Kc.paramIsX[s],u=Kc.paramIsY[s],f=Kc.numParams[s],d=e.substr(1).replace(Kc.paramRE,function(e){return c[r]?e="pixel"===a?t(o)+Number(e):t(e):u[r]&&(e="pixel"===i?n(l)-Number(e):n(e)),++r>f&&(e="X"),e});return r>f&&(d=d.replace(/[\s,]*X.*/,""),rt.log("Ignoring extra params in segment "+e)),s+d})}(t,r,i);if("pixel"===t.xsizemode){var p=r(t.xanchor);o=p+t.x0,l=p+t.x1}else o=r(t.x0),l=r(t.x1);if("pixel"===t.ysizemode){var g=i(t.yanchor);s=g-t.y0,c=g-t.y1}else s=i(t.y0),c=i(t.y1);if("line"===u)return"M"+o+","+s+"L"+l+","+c;if("rect"===u)return"M"+o+","+s+"H"+l+"V"+c+"H"+o+"Z";var v=(o+l)/2,y=(s+c)/2,m=Math.abs(v-o),x=Math.abs(y-s),b="A"+m+","+x,_=v+m+","+y;return"M"+_+b+" 0 1,1 "+(v+","+(y-x))+b+" 0 0,1 "+_+"Z"}function cu(e,t,n){return e.replace(Kc.segmentRE,function(e){var r=0,a=e.charAt(0),i=Kc.paramIsX[a],o=Kc.paramIsY[a],l=Kc.numParams[a];return a+e.substr(1).replace(Kc.paramRE,function(e){return r>=l?e:(i[r]?e=t(e):o[r]&&(e=n(e)),r++,e)})})}var uu={moduleType:"component",name:"shapes",layoutAttributes:$c,supplyLayoutDefaults:function(e,t){Ls(e,t,{name:"shapes",handleItemDefaults:iu})},includeBasePlot:Cs("shapes"),calcAutorange:function(e){var t=e._fullLayout,n=rt.filterVisible(t.shapes);if(n.length&&e._fullData.length)for(var r=0;r0)&&(r("active"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("len"),r("lenmode"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("currentvalue.visible")&&(r("currentvalue.xanchor"),r("currentvalue.prefix"),r("currentvalue.suffix"),r("currentvalue.offset"),rt.coerceFont(r,"currentvalue.font",t.font)),r("transition.duration"),r("transition.easing"),r("bgcolor"),r("activebgcolor"),r("bordercolor"),r("borderwidth"),r("ticklen"),r("tickwidth"),r("tickcolor"),r("minorticklen"))}var mu=vn.LINE_SPACING,xu=vn.FROM_TL,bu=vn.FROM_BR;function _u(e){return e._index}function wu(t,n){var r=Un.tester.selectAll("g."+fu.labelGroupClass).data(n.steps);r.enter().append("g").classed(fu.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=Au(e.select(this),{step:t},n).node();if(r){var o=Un.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=n._dims={};o.inputAreaWidth=Math.max(fu.railWidth,fu.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*n.x,o.ly=l.t+l.h*(1-n.y),"fraction"===n.lenmode?o.outerLength=Math.round(l.w*n.len):o.outerLength=n.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-n.pad.l-n.pad.r);var s=(o.inputAreaLength-2*fu.stepInset)/(n.steps.length-1),c=a+fu.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,n.currentvalue.visible){var u=Un.tester.append("g");r.each(function(e){var t=ku(u,n,e.label),r=t.node()&&Un.bBox(t.node())||{width:0,height:0},a=mn.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(r.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(r.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+n.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+fu.tickOffset+n.ticklen+fu.labelOffset+o.labelHeight+n.pad.t+n.pad.b;var f="left";sc.isRightAnchor(n)&&(o.lx-=o.outerLength,f="right"),sc.isCenterAnchor(n)&&(o.lx-=o.outerLength/2,f="center");var d="top";sc.isBottomAnchor(n)&&(o.ly-=o.height,d="bottom"),sc.isMiddleAnchor(n)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Qr.autoMargin(t,fu.autoMarginIdRoot+n._index,{x:n.x,y:n.y,l:o.outerLength*xu[f],r:o.outerLength*bu[f],b:o.height*bu[d],t:o.height*xu[d]})}function ku(e,t,n){if(t.currentvalue.visible){var r,a,i=t._dims;switch(t.currentvalue.xanchor){case"right":r=i.inputAreaLength-fu.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":r=.5*i.inputAreaLength,a="middle";break;default:r=fu.currentValueInset,a="left"}var o=rt.ensureSingle(e,"text",fu.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof n)l+=n;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),o.call(Un.font,t.currentvalue.font).text(l).call(mn.convertToTspans,t._gd);var s=mn.lineCount(o),c=(i.currentValueMaxLines+1-s)*t.currentvalue.font.size*mu;return mn.positionText(o,r,c),o}}function Mu(e,t,n){rt.ensureSingle(e,"rect",fu.gripRectClass,function(r){r.call(Su,t,e,n).style("pointer-events","all")}).attr({width:fu.gripWidth,height:fu.gripHeight,rx:fu.gripRadius,ry:fu.gripRadius}).call(Rt.stroke,n.bordercolor).call(Rt.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px")}function Au(e,t,n){var r=rt.ensureSingle(e,"text",fu.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return r.call(Un.font,n.font).text(t.step.label).call(mn.convertToTspans,n._gd),r}function Tu(t,n){var r=rt.ensureSingle(t,"g",fu.labelsClass),a=n._dims,i=r.selectAll("g."+fu.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(fu.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=e.select(this);r.call(Au,t,n),Un.setTranslate(r,zu(n,t.fraction),fu.tickOffset+n.ticklen+n.font.size*mu+fu.labelOffset+a.currentValueTotalHeight)})}function Lu(e,t,n,r,a){var i=Math.round(r*(n.steps.length-1));i!==n.active&&Cu(e,t,n,i,!0,a)}function Cu(e,t,n,r,a,i){var o=n.active;n._input.active=n.active=r;var l=n.steps[n.active];t.call(Pu,n,n.active/(n.steps.length-1),i),t.call(ku,n),e.emit("plotly_sliderchange",{slider:n,step:n.steps[n.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var n=t._nextMethod.step;n.method&&(n.execute&&Qr.executeAPICommand(e,n.method,n.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function Su(t,n,r){var a=r.node(),i=e.select(n);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();n.emit("plotly_sliderstart",{slider:t});var l=r.select("."+fu.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(Rt.fill,t.activebgcolor);var s=Du(t,e.mouse(a)[0]);Lu(n,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=Du(t,e.mouse(a)[0]);Lu(n,r,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(Rt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),n.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function Ou(t,n){var r=t.selectAll("rect."+fu.tickRectClass).data(n.steps),a=n._dims;r.enter().append("rect").classed(fu.tickRectClass,!0),r.exit().remove(),r.attr({width:n.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=e.select(this);o.attr({height:i?n.ticklen:n.minorticklen}).call(Rt.fill,n.tickcolor),Un.setTranslate(o,zu(n,r/(n.steps.length-1))-.5*n.tickwidth,(i?fu.tickOffset:fu.minorTickOffset)+a.currentValueTotalHeight)})}function Pu(e,t,n,r){var a=e.select("rect."+fu.gripRectClass),i=zu(t,n);if(!t._invokingCommand){var o=a;r&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*fu.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function zu(e,t){var n=e._dims;return n.inputAreaStart+fu.stepInset+(n.inputAreaLength-2*fu.stepInset)*Math.min(1,Math.max(0,t))}function Du(e,t){var n=e._dims;return Math.min(1,Math.max(0,(t-fu.stepInset-n.inputAreaStart)/(n.inputAreaLength-2*fu.stepInset-2*n.inputAreaStart)))}function Eu(e,t,n){var r=n._dims,a=rt.ensureSingle(e,"rect",fu.railTouchRectClass,function(r){r.call(Su,t,e,n).style("pointer-events","all")});a.attr({width:r.inputAreaLength,height:Math.max(r.inputAreaWidth,fu.tickOffset+n.ticklen+r.labelHeight)}).call(Rt.fill,n.bgcolor).attr("opacity",0),Un.setTranslate(a,0,r.currentValueTotalHeight)}function Ru(e,t){var n=t._dims,r=n.inputAreaLength-2*fu.railInset,a=rt.ensureSingle(e,"rect",fu.railRectClass);a.attr({width:r,height:fu.railWidth,rx:fu.railRadius,ry:fu.railRadius,"shape-rendering":"crispEdges"}).call(Rt.stroke,t.bordercolor).call(Rt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Un.setTranslate(a,fu.railInset,.5*(n.inputAreaWidth-fu.railWidth)+n.currentValueTotalHeight)}var Nu={moduleType:"component",name:fu.name,layoutAttributes:pu,supplyLayoutDefaults:function(e,t){Ls(e,t,{name:gu,handleItemDefaults:yu})},draw:function(t){var n=t._fullLayout,r=function(e,t){for(var n=e[fu.name],r=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(fu.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r=n.steps.length&&(n.active=0),t.call(ku,n).call(Ru,n).call(Tu,n).call(Ou,n).call(Eu,e,n).call(Mu,e,n);var r=n._dims;Un.setTranslate(t,r.lx+n.pad.l,r.ly+n.pad.t),t.call(Pu,n,n.active/(n.steps.length-1),!1),t.call(ku,n)}(t,e.select(this),n)}})}}},Iu=m.extendFlat,Fu=(0,Wt.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Iu({},du,{}),font:L({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:O.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),ju={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Bu=ju.name,Hu=Fu.buttons;function qu(e,t,n){function r(n,r){return rt.coerce(e,t,Fu,n,r)}r("visible",function(e,t){var n,r,a=e.buttons||[],i=t.buttons=[];function o(e,t){return rt.coerce(n,r,Hu,e,t)}for(var l=0;l0)&&(r("active"),r("direction"),r("type"),r("showactive"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("bgcolor",n.paper_bgcolor),r("bordercolor"),r("borderwidth"))}var Vu=Uu;function Uu(e,t,n){this.gd=e,this.container=t,this.id=n,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Uu.barWidth=2,Uu.barLength=20,Uu.barRadius=2,Uu.barPad=1,Uu.barColor="#808BA4",Uu.prototype.enable=function(t,n,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=Uu.barLength+2*Uu.barPad,k=Uu.barWidth+2*Uu.barPad,M=f,A=h+p;A+k>o&&(A=o-k);var T=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);T.exit().on(".drag",null).remove(),T.enter().append("rect").classed("scrollbar-horizontal",!0).call(Rt.fill,Uu.barColor),_?(this.hbar=T.attr({rx:Uu.barRadius,ry:Uu.barRadius,x:M,y:A,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=Uu.barWidth+2*Uu.barPad,S=Uu.barLength+2*Uu.barPad,O=f+d,P=h;O+C>i&&(O=i-C);var z=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);z.exit().on(".drag",null).remove(),z.enter().append("rect").classed("scrollbar-vertical",!0).call(Rt.fill,Uu.barColor),L?(this.vbar=z.attr({rx:Uu.barRadius,ry:Uu.barRadius,x:O,y:P,width:C,height:S}),this._vbarYMin=P+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,R=L?s+C+.5:s+.5,N=c-.5,I=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(N),width:Math.ceil(R)-Math.floor(E),height:Math.ceil(I)-Math.floor(N)}),this.container.call(Un.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Un.setClipUrl,null),delete this._clipRect),_||L){var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),L&&this.vbar.on(".drag",null).call(B)}this.setTranslate(n,r)},Uu.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Un.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Uu.prototype._onBoxDrag=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(n-=e.event.dy),this.setTranslate(t,n)},Uu.prototype._onBoxWheel=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(n+=e.event.deltaY),this.setTranslate(t,n)},Uu.prototype._onBarDrag=function(){var t=this.translateX,n=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(rt.constrain(e.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=n+this._vbarYMin,o=i+this._vbarTranslateMax;n=(rt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,n)},Uu.prototype.setTranslate=function(e,t){var n=this.position.w-this._box.w,r=this.position.h-this._box.h;if(e=rt.constrain(e||0,0,n),t=rt.constrain(t||0,0,r),this.translateX=e,this.translateY=t,this.container.call(Un.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/n;this.hbar.call(Un.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/r;this.vbar.call(Un.setTranslate,e,t+i*this._vbarTranslateMax)}};var Gu=vn.LINE_SPACING;function Yu(e){return e._index}function Xu(e,t){return+e.attr(ju.menuIndexAttrName)===t._index}function Zu(e,t,n,r,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?Qu(e,r,null,null,t):"dropdown"===t.type&&(a.attr(ju.menuIndexAttrName,"-1"),Wu(e,r,a,i,t),l||Qu(e,r,a,i,t))}function Wu(e,t,n,r,a){var i=rt.ensureSingle(t,"g",ju.headerClassName,function(e){e.style("pointer-events","all")}),o=a._dims,l=a.active,s=a.buttons[l]||ju.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(Ju,a,s,e).call(af,a,c,u),rt.ensureSingle(t,"text",ju.headerArrowClassName,function(e){e.classed("user-select-none",!0).attr("text-anchor","end").call(Un.font,a.font).text(ju.arrowSymbol[a.direction])}).attr({x:o.headerWidth-ju.arrowOffsetX+a.pad.l,y:o.headerHeight/2+ju.textOffsetY+a.pad.t}),i.on("click",function(){n.call(of),n.attr(ju.menuIndexAttrName,Xu(n,a)?-1:String(a._index)),Qu(e,t,n,r,a)}),i.on("mouseover",function(){i.call(tf)}),i.on("mouseout",function(){i.call(nf,a)}),Un.setTranslate(t,o.lx,o.ly)}function Qu(t,n,r,a,i){r||(r=n).attr("pointer-events","all");var o=function(e){return-1==+e.attr(ju.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?ju.dropdownButtonClassName:ju.buttonClassName,s=r.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+ju.gapButtonHeader:f=h.headerWidth+ju.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-ju.gapButtonHeader+ju.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-ju.gapButtonHeader+ju.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:ju.gapButton,xPad:ju.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(Ju,i,o,t).call(af,i,g),c.on("click",function(){e.event.defaultPrevented||(Zu(t,i,0,n,r,a,l),o.execute&&Qr.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(tf)}),c.on("mouseout",function(){c.call(nf,i),s.call(ef,i)})}),s.call(ef,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,n,r,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(ju.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r_.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,n;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n0&&rt.log("Clearing previous rejected promises from queue."),e._promises=[]},df.cleanLayout=function(e){var t,n;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var r=(Qr.subplotsRegistry.cartesian||{}).attrRegex,a=(Qr.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),Rt.clean(e),e},df.cleanData=function(e,t){for(var n=[],r=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}df.hasParent=function(e,t){for(var n=_f(t);n;){if(n in e)return!0;n=_f(n)}return!1};var wf=["x","y","z"];df.clearAxisTypes=function(e,t,n){for(var r=0;r1&&w.warn("Full array edits are incompatible with other edits",a);var f=n[""][""];if(Tf(f))t.set(null);else{if(!Array.isArray(f))return w.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(n).map(Number).sort(Mf),b=t.get(),_=b||[],k=X(u,a).get(),M=[],T=-1,L=_.length;for(d=0;d_.length-(m?0:1))w.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&w.warn("Insertion & removal are incompatible with edits to the same index.",a,p),Tf(y)?M.push(p):m?("add"===y&&(y={}),_.splice(p,0,y),k&&k.splice(p,0,{})):w.warn("Unrecognized full object edit value",a,p,y),-1===T&&(T=p);else for(h=0;h=0;d--)_.splice(M[d],1),k&&k.splice(M[d],1);if(_.length?b||t.set(_):t.set(null),s)return!1;if(i(c,u),l!==A){var C;if(-1===T)C=x;else{for(L=Math.max(_.length,L),C=[],d=0;d=T);d++)C.push(p);for(d=T;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,n=0;nUf*h)||y)for(n=0;nL&&OA&&(A=O);l/=(A-M)/(2*T),M=a.l2r(M),A=a.l2r(A),a.range=a._input.range=_=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(n,a,h)){var o=i.node(),l=t.bg=rt.ensureSingle(i,"rect","bg");o.insertBefore(l.node(),o.childNodes[0])}else i.select("rect.bg").remove(),d.push(e),h.push([n,a])});var p=r._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=e.select(this)}),f.each(function(e){var t=r._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Un.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(Rt.fill,r.plot_bgcolor).style("stroke-width",0);var u,f,d=t.clipId="clip"+r._uid+e+"plot",h=rt.ensureSingleById(r._clips,"clipPath",d,function(e){e.classed("plotclip",!0).append("rect")});for(t.clipRect=h.select("rect").attr({width:a._length,height:c._length}),Un.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=d):(u=d,f=null),Un.setClipUrl(t.plot,u),n=0;n=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var A=k.slice();w&&b&&(A[1]+=M);var T=c.angularAxis.ticksCount||4;T>8&&(T=T/(T/8)+T%8),c.angularAxis.ticksStep&&(T=(A[1]-A[0])/T);var L=c.angularAxis.ticksStep||(A[1]-A[0])/(T*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),A[2]||(A[2]=L);var C=e.range.apply(this,A);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(A.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),O=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(O)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var P,z=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){P=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var R=u.map(function(e,t){var n=rd.util.cloneJson(e);return n.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",n.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,n.color="LinePlot"===e.geometry?e.strokeColor:e.color,n});rd.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:td({},rd.Legend.defaultConfig().legendConfig,{container:P,elements:R,reverseOrder:c.legend.reverseOrder})})();var N=P.node().getBBox();g=Math.min(c.width-N.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),P.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else P=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),z.attr("transform","translate("+y+")").style({cursor:"crosshair"});var I=[(c.width-(c.margin.left+c.margin.right+2*g+(N?N.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(I[0]=Math.max(0,I[0]),I[1]=Math.max(0,I[1]),t.select(".outer-group").attr("transform","translate("+I+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),j=F.node().getBBox();F.attr({x:y[0]-j.width/2,y:y[1]-g-20})}var B=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var H=B.selectAll("circle.grid-circle").data(r.ticks(5));H.enter().append("circle").attr({class:"grid-circle"}).style(D),H.attr("r",r),H.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(D);var q=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(r).ticks(5).tickSize(5);B.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),B.selectAll(".domain").style(D),B.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var X=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:nd+"em",transform:function(e,t){var n=V(e),r=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-n+" "+r+" 0)":"radial"==a?n<270&&n>90?"rotate(180 "+r+" 0)":null:"rotate("+(n<=180&&n>0?-90:90)+" "+r+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&X.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var Z=e.max(z.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));P.attr({transform:"translate("+[g+Z,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,Q=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(Q.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),Q.exit().remove(),u[0]||W){var J=[];u.forEach(function(e,t){var n={};n.radialScale=r,n.angularScale=a,n.container=Q.filter(function(e,n){return n==t}),n.geometry=e.geometry,n.orientation=c.orientation,n.direction=c.direction,n.index=t,J.push({data:e,geometryConfig:n})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(J).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var n;n=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var r=e.map(function(e,t){return td(rd[n].defaultConfig(),e)});rd[n]().config(r)()})}var K,ee,te=t.select(".guides-group"),ne=t.select(".tooltips-group"),re=rd.tooltipPanel().config({container:ne,fontSize:8})(),ae=rd.tooltipPanel().config({container:ne,fontSize:8})(),ie=rd.tooltipPanel().config({container:ne,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});z.on("mousemove.angular-guide",function(e,t){var n=rd.util.getMousePos(q).angle;oe.attr({x2:-g,transform:"rotate("+n+")"}).style({opacity:.5});var r=(n+180+360-c.orientation)%360;K=a.invert(r);var i=rd.util.convertToCartesian(g+12,n+180);re.text(rd.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});z.on("mousemove.radial-guide",function(e,t){var n=rd.util.getMousePos(q).radius;le.attr({r:n}).style({opacity:.5}),ee=r.invert(rd.util.getMousePos(q).radius);var a=rd.util.convertToCartesian(n,c.radialAxis.orientation);ae.text(rd.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),re.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(n,r){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:rd.util.round(n[0]),r:rd.util.round(n[1])};b&&(s.t=m[n[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-I[0]-f.left,u.top+u.height/2-I[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,n){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,n){ie.hide();var r=e.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=rd.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),td(i.data[t],rd.Axis.defaultConfig().data[0]),td(i.data[t],e)}),td(i.layout,rd.Axis.defaultConfig().layout),td(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return r},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},rd.Axis.defaultConfig=function(t,n){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},rd.util={},rd.DATAEXTENT="dataExtent",rd.AREA="AreaChart",rd.LINE="LinePlot",rd.DOT="DotPlot",rd.BAR="BarChart",rd.util._override=function(e,t){for(var n in e)n in t&&(t[n]=e[n])},rd.util._extend=function(e,t){for(var n in e)t[n]=e[n]},rd.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},rd.util.dataFromEquation2=function(t,n){var r=n||6;return e.range(0,360+r,r).map(function(e,n){var r=e*Math.PI/180;return[e,t(r)]})},rd.util.dataFromEquation=function(t,n,r){var a=n||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,n){var r=e*Math.PI/180,a=t(r);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},rd.util.ensureArray=function(t,n){if(void 0===t)return null;var r=[].concat(t);return e.range(n).map(function(e,t){return r[t]||r[0]})},rd.util.fillArrays=function(e,t,n){return t.forEach(function(t,r){e[t]=rd.util.ensureArray(e[t],n)}),e},rd.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},rd.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var n=t.shift();return e[n]&&(!t.length||objHasKeys(e[n],t))},rd.util.sumArrays=function(t,n){return e.zip(t,n).map(function(t,n){return e.sum(t)})},rd.util.arrayLast=function(e){return e[e.length-1]},rd.util.arrayEqual=function(e,t){for(var n=Math.max(e.length,t.length,1);n-- >=0&&e[n]===t[n];);return-2===n},rd.util.flattenArray=function(e){for(var t=[];!rd.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},rd.util.deduplicate=function(e){return e.filter(function(e,t,n){return n.indexOf(e)==t})},rd.util.convertToCartesian=function(e,t){var n=t*Math.PI/180;return[e*Math.cos(n),e*Math.sin(n)]},rd.util.round=function(e,t){var n=t||2,r=Math.pow(10,n);return Math.round(e*r)/r},rd.util.getMousePos=function(t){var n=e.mouse(t.node()),r=n[0],a=n[1],i={};return i.x=r,i.y=a,i.pos=n,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},rd.util.duplicatesCount=function(e){for(var t,n={},r={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(n.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(r,a,i)},"stroke-width":function(e,t){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](r,a,i)},opacity:function(e,t){return p.opacity(r,a,i)},display:function(e,t){return p.display(r,a,i)}})}};var f=n.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return n.radialScale(s+(e[2]||0))}).outerRadius(function(e){return n.radialScale(s+(e[2]||0))+n.radialScale(e[1])});c.arc=function(t,r,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(n.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,n,r){return t[r].data.color},stroke:function(e,n,r){return t[r].data.strokeColor},"stroke-width":function(e,n,r){return t[r].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,n,r){return t[r].data.opacity},display:function(e,n,r){return void 0===t[r].data.visible||t[r].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[n.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,n){t[n]||(t[n]={}),td(t[n],rd.PolyChart.defaultConfig()),td(t[n],e)}),this):t},a.getColorScale=function(){},e.rebind(a,n,"on"),a},rd.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},rd.BarChart=function(){return rd.PolyChart()},rd.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},rd.AreaChart=function(){return rd.PolyChart()},rd.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},rd.DotPlot=function(){return rd.PolyChart()},rd.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},rd.LinePlot=function(){return rd.PolyChart()},rd.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},rd.Legend=function(){var t=rd.Legend.defaultConfig(),n=e.dispatch("hover");function r(){var n=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,r){var a=td({},n.elements[t]);return a.name=e,a.color=[].concat(n.elements[t].color)[r],a})}),i=e.merge(a);i=i.filter(function(e,t){return n.elements[t]&&(n.elements[t].visibleInLegend||void 0===n.elements[t].visibleInLegend)}),n.reverseOrder&&(i=i.reverse());var o=n.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=n.fontSize,c=null==n.isContinuous?"number"==typeof i[0]:n.isContinuous,u=c?n.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:n.height,width:n.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,n){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(r)?e.svg.symbol().type(r).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?n.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?n.textColor:"none"}),x.selectAll("text").style({fill:n.textColor,"font-size":n.fontSize}).text(function(e,t){return i[t].name}),r}return r.config=function(e){return arguments.length?(td(t,e),this):t},e.rebind(r,n,"on"),r},rd.Legend.defaultConfig=function(e,t){return{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:!1}}},rd.tooltipPanel=function(){var t,n,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+rd.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),n=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";n.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=n.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return td(a,e),l},l},rd.tooltipPanel.uid=1,rd.adapter={},rd.adapter.plotly=function(){var t={convert:function(t,n){var r={};if(t.data&&(r.data=t.data.map(function(e,t){var r=td({},e);return[[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"]]].forEach(function(e,t){rd.util.translator.apply(null,e.concat(n))}),n||delete r.marker,n&&delete r.groupId,n?("LinePlot"===r.geometry?(r.type="scatter",!0===r.dotVisible?(delete r.dotVisible,r.mode="lines+markers"):r.mode="lines"):"DotPlot"===r.geometry?(r.type="scatter",r.mode="markers"):"AreaChart"===r.geometry?r.type="area":"BarChart"===r.geometry&&(r.type="bar"),delete r.geometry):("scatter"===r.type?"lines"===r.mode?r.geometry="LinePlot":"markers"===r.mode?r.geometry="DotPlot":"lines+markers"===r.mode&&(r.geometry="LinePlot",r.dotVisible=!0):"area"===r.type?r.geometry="AreaChart":"bar"===r.type&&(r.geometry="BarChart"),delete r.mode,delete r.type),r}),!n&&t.layout&&"stack"===t.layout.barmode)){var a=rd.util.duplicates(r.data.map(function(e,t){return e.geometry}));r.data.forEach(function(e,t){var n=a.indexOf(e.geometry);-1!=n&&(r.data[t].groupId=n)})}if(t.layout){var i=td({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){rd.util.translator.apply(null,e.concat(n))}),n?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}n&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var ad,id=rt.extendDeepAll,od=ad={};od.framework=function(t){var n,r,a,i,o,l=new function(){var e,t=[],n=-1,r=!1;function a(e,t){return e?(r=!0,e[t](),r=!1,this):this}return{add:function(e){return r?this:(t.splice(n+1,t.length-n),t.push(e),n=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var r=t[n];return r?(a(r,"undo"),n-=1,e&&e(r.undo),this):this},redo:function(){var r=t[n+1];return r?(a(r,"redo"),n+=1,e&&e(r.redo),this):this},clear:function(){t=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n*:not(.chart-root)").remove(),n=n?id(n,r):r,a||(a=ed.Axis()),i=ed.adapter.plotly().convert(n),a.config(i).render(o),t.data=n.data,t.layout=n.layout,od.fillLayout(t),n}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return n},s.getLiveConfig=function(){return ed.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=ed.util.cloneJson(n);e=i,t=r,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),r=ed.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},od.fillLayout=function(t){var n=e.select(t).selectAll(".plot-container"),r=n.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:Rt.background,_container:n,_paperdiv:r,_paper:a};t._fullLayout=id(i,t.layout)};var ld={};(ld=ed).manager=ad;var sd={},cd=zo.initInteractions,ud=ht.AX_NAME_PATTERN,fd=0;function dd(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){rt.error(e)}}function hd(e,t){dd(e,Rt.combine(t,"white"))}function pd(e,t){e._context||(e._context=rt.extendDeep({},_));var n,r,a,i=e._context;if(t){for(r=Object.keys(t),n=0;n=e.data.length||a<-e.data.length)throw new Error(n+" must be valid indices for gd.data.");if(t.indexOf(a,r+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+n+" must be unique.")}}function yd(e,t,n){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),vd(e,t,"currentIndices"),void 0===n||Array.isArray(n)||(n=[n]),void 0!==n&&vd(e,n,"newIndices"),void 0!==n&&t.length!==n.length)throw new Error("current and new indices must be of equal length.")}function md(e,t,r,a,i){!function(e,t,n,r){var a=rt.isPlainObject(r);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!rt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===n)throw new Error("indices must be an integer or array of integers");for(var i in vd(e,n,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==n.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in r)||!Array.isArray(r[i])||r[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,t,r,a);for(var o=function(e,t,r,a){var i,o,l,s,c,u=rt.isPlainObject(a),f=[];for(var d in Array.isArray(r)||(r=[r]),r=gd(r,e.data.length-1),t)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var A=_.parts[M],T=_.parts[M-1]+"."+A,L=_.parts.slice(0,M).join("."),C=rt.nestedProperty(e.layout,L).get(),S=rt.nestedProperty(o,L).get(),O=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===A?w:bd(O);var P=Pr.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var z in P.impliedEdits)v(rt.relativeAttr(b,z),P.impliedEdits[z]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(T.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(T),rt.nestedProperty(o,L+"._inputRange").set(null);else if(T.match(/^[xyz]axis[0-9]*\.autorange$/)){x(T),rt.nestedProperty(o,L+"._inputRange").set(null);var E=rt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else T.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&rt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===A){var R=C,N="linear"===S.type&&"log"===w,I="log"===S.type&&"linear"===w;if(N||I){if(R&&R.range)if(S.autorange)N&&(R.range=R.range[1]>R.range[0]?[1,2]:[2,1]);else{var F=R.range[0],j=R.range[1];N?(F<=0&&j<=0&&v(L+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(j)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,j)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],D.getComponentMethod("annotations","convertCoords")(e,S,w,v),D.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);rt.nestedProperty(o,L+"._inputRange").set(null)}else if(A.match(ud)){var B=rt.nestedProperty(o,b).get(),H=(w||{}).type;H&&"-"!==H||(H="linear"),D.getComponentMethod("annotations","convertCoords")(e,B,H,v),D.getComponentMethod("images","convertCoords")(e,B,H,v)}var q=kf.containerArrayMatch(b);if(q){n=q.array,r=q.index;var V=q.property,U=(rt.nestedProperty(i,n)||[])[r]||{},G=U,Y=P||{editType:"calc"},X=-1!==Y.editType.indexOf("calcIfAutorange");""===r?(X?h.calc=!0:Wt.update(h,Y),X=!1):""===V&&(G=w,kf.isAddVal(w)?g[b]=null:kf.isRemoveVal(w)?(g[b]=U,G=U):rt.warn("unrecognized full object value",t)),X&&(Md(e,G,"x")||Md(e,G,"y"))?h.calc=!0:Wt.update(h,Y),c[n]||(c[n]={});var Z=c[n][r];Z||(Z=c[n][r]={}),Z[V]=w,delete t[b]}else"reverse"===A?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==O&&"select"!==O?h.plot=!0:P?Wt.update(h,P):h.calc=!0,_.set(w))}}for(n in c){kf.applyContainerArrayChanges(e,rt.nestedProperty(i,n),c[n],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(r=0;r=0&&n=0&&n=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var n=0;return function(){if(e&&++n===t)return e()}}return void 0===r._frameWaitingCnt&&(r._frameWaitingCnt=0),new Promise(function(i,c){function u(){r._currentFrame&&r._currentFrame.onComplete&&r._currentFrame.onComplete();var t=r._currentFrame=r._frameQueue.shift();if(t){var n=t.name?t.name.toString():null;e._fullLayout._currentFrame=n,r._lastFrameAt=Date.now(),r._timeToNext=t.frameOpts.duration,Qr.transition(e,t.frame.data,t.frame.layout,df.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:n,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(r._animationRaf),r._animationRaf=null}function f(){e.emit("plotly_animating"),r._lastFrameAt=-1/0,r._timeToNext=0,r._runningTransitions=0,r._currentFrame=null;var t=function(){r._animationRaf=window.requestAnimationFrame(t),Date.now()-r._lastFrameAt>r._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&rt.isPlainObject(t))v.push({type:"object",data:g(rt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;r--)if(rt.isPlainObject(t[r])){var d=t[r].name,h=(s[d]||f[d]||{}).name,p=t[r].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&fd<5&&(fd++,rt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===fd&&rt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:Qr.supplyFrameDefaults(t[r]),index:n&&void 0!==n[r]&&null!==n[r]?n[r]:c+r})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;r--){if("number"==typeof(a=u[r].frame).name&&rt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;n--)r=t[n],i.push({type:"delete",index:r}),o.unshift({type:"insert",index:r,value:a[r]});var l=Qr.modifyFrames,s=Qr.modifyFrames,c=[e,o],u=[e,i];return uf&&uf.add(e,l,c,s,u),Qr.modifyFrames(e,i)},sd.purge=function(e){var t=(e=rt.getGraphDiv(e))._fullLayout||{},n=e._fullData||[],r=e.calcdata||[];return Qr.cleanPlot([],{},n,t,r),Qr.purge(e),Ct.purge(e),t._container&&t._container.remove(),delete e._context,e};var Ld={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},Cd=wt.EventEmitter;var Sd=function(e){var t=e.emitter||new Cd,n=new Promise(function(r,a){var i=window.Image,o=e.svg,l=e.format||"png";if(rt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?n:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var n;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":n=c.toDataURL("image/jpeg");break;case"png":n=c.toDataURL("image/png");break;case"webp":n=c.toDataURL("image/webp");break;case"svg":n=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}r(n),e.promise||t.emit("success",n)},p.onerror=function(n){if(a(n),!e.promise)return t.emit("error",n)},p.src=g});return e.promise?n:t},Od=/"/g,Pd=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var zd=function(n,r,a){var i,o=n._fullLayout,l=o._paper,s=o._toppaper,c=o.width,u=o.height;l.insert("rect",":first-child").call(Un.setRect,0,0,c,u).call(Rt.fill,o.paper_bgcolor);var f=o._basePlotModules||[];for(i=0;i")?"":n.html(e).text()});return n.remove(),r}(v),v=(v=v.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(Pd,"'"),rt.isIE()&&(v=(v=(v=v.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),v},Dd={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},Ed=/^data:image\/\w+;base64,/;var Rd=function(e,t){var n,r,a;function i(e){return!(e in t)||rt.validate(t[e],Dd[e])}if(t=t||{},rt.isPlainObject(e)?(n=e.data||[],r=e.layout||{},a=e.config||{}):(e=rt.getGraphDiv(e),n=rt.extendDeep([],e.data),r=rt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,n){return rt.coerce(t,o,Dd,e,n)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=rt.extendFlat({},r);c&&(g.width=c),u&&(g.height=u);var v=rt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=Ld.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,Ld.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var n=zd(p,s,f),r=p._fullLayout.width,a=p._fullLayout.height;if(sd.purge(p),document.body.removeChild(p),"svg"===s)return e(h?n:"data:image/svg+xml,"+encodeURIComponent(n));var i=document.createElement("canvas");i.id=rt.randstr(),Sd({format:s,width:r,height:a,scale:f,canvas:i,svg:n,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){sd.plot(p,n,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(Ed,""):e}(t))}).catch(function(e){t(e)})})},Nd=rt.isPlainObject,Id=Array.isArray,Fd=rt.isArrayOrTypedArray;function jd(e,t,n,r,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&r.push(qd("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(Id(u[y])){u[y].length>f[y].length&&r.push(qd("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],rt.validate(x,m)?b!==x&&b!==+x&&r.push(qd("dynamic",a,c.concat(y,v),x,b)):r.push(qd("value",a,c.concat(y,v),x))}else r.push(qd("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],rt.validate(x,m)?b!==x&&b!==+x&&r.push(qd("dynamic",a,c.concat(y),x,b)):r.push(qd("value",a,c.concat(y),x))}else if(d.items&&!h&&Id(u)){var M,A,T=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(qd("object","layout"))),Qr.supplyDefaults(o);for(var l=o._fullData,s=n.length,c=0;c-1&&(l[c[n]].title="");for(n=0;nH||e[1]V)return[gh(e[0],B,H),gh(e[1],q,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===B||e[0]===H)||(e[1]===t[1]&&(e[1]===q||e[1]===V)||void 0)}function X(e,t,n){return function(r,a){var i=G(r),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*rt.constrain((r[e]+a[e])/2,t,n)-((i||r)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function Z(e){var t=e[0],n=e[1],r=t===L[C-1][0],a=n===L[C-1][1];if(!r||!a)if(C>1){var i=t===L[C-2][0],o=n===L[C-2][1];r&&(t===B||t===H)&&i?o?C--:L[C-1]=e:a&&(n===q||n===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&Z([E,R]),Z(e),N=null,E=R=0}function Q(e){if(z=e[0]H?H:0,D=e[1]V?V:0,z||D){if(C)if(N){var t=F(N,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else I=F(L[C-1],e)[0],L[C++]=I;else L[C++]=[z||e[0],D||e[1]];var n=L[C-1];z&&D&&(n[0]!==z||n[1]!==D)?(N&&(E!==z&&R!==D?Z(E&&R?(r=N,i=(a=e)[0]-r[0],o=(a[1]-r[1])/i,(r[1]*a[0]-a[1]*r[0])/i>0?[o>0?B:H,V]:[o>0?H:B,q]):[E||z,R||D]):E&&R&&Z([E,R])),Z([z,D])):E-z&&R-D&&Z([z||E,D||R]),N=e,E=z,R=D}else N&&W(F(N,e)[0]),L[C++]=e;var r,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var n=[],r=0,a=0;a<4;a++){var i=U[a],o=ph(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!r||Math.abs(o.x-n[0][0])>1||Math.abs(o.y-n[0][1])>1)&&(o=[o.x,o.y],r&&P(o,e)O(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;Q(l),r=l}}else Q(i)}N&&Z([E||N[0],R||N[1]]),A.push(L.slice(0,C))}return A},yh=qi.tester;function mh(t,n,r,a,i,o,l){var s,c;!function(t,n,r,a,i){var o=r.xaxis,l=r.yaxis,s=e.extent(rt.simpleMap(o.range,o.r2c)),c=e.extent(rt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Vn.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var r=e[0].trace;Vn.hasMarkers(r)&&r.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=r.xaxis,h=r.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(D.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),r.isRangePlot||(a[0].node3=v);var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,A,T,L,C,S,O,P,z="",E="",R=[],N=rt.noop;if(y=p._ownFill,Vn.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(A=Un.steps(g.shape),T=Un.steps(g.shape.split("").reverse().join(""))):A=T="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Un.smoothclosed(e.slice(1),g.smoothing):Un.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return T(e.reverse())},R=vh(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=p._polygons=new Array(R.length),c=0;c1){var r=e.select(this);if(r.datum(a),t)f(r.style("opacity",0).attr("d",k).call(Un.lineGroupStyle)).style("opacity",1);else{var i=f(r);i.attr("d",k),Un.singleLineStyle(a,i)}}}}}var I=v.selectAll(".js-line").data(R);f(I.exit()).style("opacity",0).remove(),I.each(N(!1)),I.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Un.lineGroupStyle).each(N(!0)),Un.setClipUrl(I,r.layerClipId),R.length?(y?C&&O&&(x?("y"===x?C[1]=O[1]=h.c2p(0,!0):"x"===x&&(C[0]=O[0]=d.c2p(0,!0)),f(y).attr("d","M"+O+"L"+C+"L"+z.substr(1)).call(Un.singleFillStyle)):f(y).attr("d",z+"Z").call(Un.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&z&&b?("tonext"===p.fill?f(m).attr("d",z+"Z"+b+"Z").call(Un.singleFillStyle):f(m).attr("d",z+"L"+b.substr(1)+"Z").call(Un.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=P):(y?j(y):m&&j(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Un.setClipUrl(e.select(this),n?null:r.layerClipId)})}function j(e){f(e).attr("d","M0,0Z")}function B(e){return e.filter(function(e){return e.vis})}function H(e){return e.id}function q(e){if(e.ids)return H}function V(){return!1}function U(n){var a,i=n[0].trace,o=e.select(this),l=Vn.hasMarkers(i),s=Vn.hasText(i),c=q(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?B:rt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?B:rt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Un.pointStyle,i,t).call(Un.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Un.tryColorscale(i.marker,""),m=l&&Un.tryColorscale(i.marker,"line");a.order(),a.each(function(n){var a=e.select(this),o=f(a);Un.translatePoint(n,o,d,h)?(Un.singlePointStyle(n,o,i,y,m,t),r.layerClipId&&Un.hideOutsideRangePoint(n,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==n.data&&void 0!==n.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var n=e.select(this),a=f(n.select("text"));Un.translatePoint(t,a,d,h)?r.layerClipId&&Un.hideOutsideRangePoint(t,n,d,h,i.xcalendar,i.ycalendar):n.remove()}),a.selectAll("text").call(Un.textPointStyle,i,t).each(function(t){var n=d.c2p(t.x),r=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:n,y:r})})}),a.exit().remove()}}function xh(e,t,n){var r=e.selectAll("path.point"),a=e.selectAll("text");Un.pointStyle(r,t,n),Un.textPointStyle(a,t,n),Un.selectedPointStyle(r,t),Un.selectedTextStyle(a,t)}var bh=function(t,n){var r=n?n[0].node3:e.select(t).selectAll("g.trace.scatter");r.style("opacity",function(e){return e[0].trace.opacity}),r.selectAll("g.points").each(function(n){xh(e.select(this),n.trace||n[0].trace,t)}),r.selectAll("g.trace path.js-line").call(Un.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(Un.fillGroupStyle),D.getComponentMethod("errorbars","style")(r)},_h={};_h.hasLines=Vn.hasLines,_h.hasMarkers=Vn.hasMarkers,_h.hasText=Vn.hasText,_h.isBubble=Vn.isBubble,_h.attributes=kr,_h.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,kr,n,r)}var i=dl(e,t,r,a),o=i=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===n.xaxis&&i.yaxis===n.yaxis){i.opacity=void 0;break}}}}},_h.calc=ch,_h.arraysToCalcdata=rh,_h.plot=function(t,n,r,a,i){var o,l,s,c,u=n.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(r,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,n){var r,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){mh(t,i,n,e,r,this,a)})})):u.selectAll("g.trace").each(function(e,i){mh(t,i,n,e,r,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()},_h.colorbar=Gl,_h.style=bh,_h.hoverPoints=function(e,t,n,r){var a=e.cd,i=a[0].trace,o=e.xa,l=e.ya,s=o.c2p(t),c=l.c2p(n),u=[s,c],f=i.hoveron||"",d=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var h=function(e){var t=Math.max(d,e.mrc||0),n=o.c2p(e.x)-s,r=l.c2p(e.y)-c;return Math.max(Math.sqrt(n*n+r*r)-t,1-d/t)},p=Li.getDistanceFunction(r,function(e){var t=Math.max(3,e.mrc||0),n=1-1/t,r=Math.abs(o.c2p(e.x)-s);return rN!=(L=w[b][1])>=N&&(M=w[b-1][0],A=w[b][0],L-T&&(k=M+(A-M)*(N-T)/(L-T),P=Math.min(P,k),z=Math.max(z,k)));P=Math.max(P,0),z=Math.min(z,o._length);var I=Rt.defaultLine;return Rt.opacity(i.fillcolor)?I=i.fillcolor:Rt.opacity((i.line||{}).color)&&(I=i.line.color),rt.extendFlat(e,{distance:e.maxHoverDistance,x0:P,x1:z,y0:N,y1:N,color:I}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},_h.selectPoints=function(e,t){var n,r,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Vn.hasMarkers(u)&&!Vn.hasText(u))return[];if(!1===t)for(n=0;n0?1:-1)/2,y:i/(1+n*n/(r*r)),outside:!0}}var Gh={};Gh.attributes=zh,Gh.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,zh,n,r)}var i=rt.coerceFont,o=a("values"),l=a("labels");if(!Array.isArray(l)){if(!rt.isArrayOrTypedArray(o)||!o.length)return void(t.visible=!1);a("label0"),a("dlabel")}a("marker.line.width")&&a("marker.line.color"),a("marker.colors"),a("scalegroup");var s=a("text"),c=a("textinfo",Array.isArray(s)?"text+percent":"percent");if(a("hovertext"),c&&"none"!==c){var u=a("textposition"),f=Array.isArray(u)||"auto"===u,d=f||"inside"===u,h=f||"outside"===u;if(d||h){var p=i(a,"textfont",r.font);d&&i(a,"insidetextfont",p),h&&i(a,"outsidetextfont",p)}}jh(t,r,a),a("hole"),a("sort"),a("direction"),a("rotation"),a("pull")},Gh.supplyLayoutDefaults=function(e,t){var n,r;n="hiddenlabels",rt.coerce(e,t,Bh,n,r)},Gh.layoutAttributes=Bh,Gh.calc=function(e,t){var r,a,i,o,l,c=t.values,u=Nh(c)&&c.length,f=t.labels,d=t.marker.colors||[],h=[],p=e._fullLayout,g=p.colorway,v=p._piecolormap,y={},m=0,x=p.hiddenlabels||[];if(p._piecolorway||g===Rt.defaults||(p._piecolorway=Fh(g)),t.dlabel)for(f=new Array(c.length),r=0;r")}}return h},Gh.plot=function(t,n){var r=t._fullLayout;!function(e,t){var n,r,a,i,o,l,s,c,u,f=[];for(a=0;as&&(s=l.pull[i]);o.r=Math.min(n,r)/(2+2*s),o.cx=t.l+t.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=t.t+t.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;ia.vTotal/2?1:0)}(n),a.each(function(){var a=e.select(this).selectAll("g.slice").data(n);a.enter().append("g").classed("slice",!0),a.exit().remove();var l=[[[],[]],[[],[]]],s=!1;a.each(function(n){if(n.hidden)e.select(this).selectAll("path,g").remove();else{n.pointNumber=n.i,n.curveNumber=o.index,l[n.pxmid[1]<0?0:1][n.pxmid[0]<0?0:1].push(n);var a=i.cx,c=i.cy,u=e.select(this),f=u.selectAll("path.surface").data([n]),d=!1,h=!1;if(f.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),u.select("path.textline").remove(),u.on("mouseover",function(){var l=t._fullLayout,s=t._fullData[o.index];if(!t._dragging&&!1!==l.hovermode){var u=s.hoverinfo;if(Array.isArray(u)&&(u=Li.castHoverinfo({hoverinfo:[dc.castOption(u,n.pts)],_module:o._module},l,0)),"all"===u&&(u="label+text+value+percent+name"),"none"!==u&&"skip"!==u&&u){var f=Vh(n,i),p=a+n.pxmid[0]*(1-f),g=c+n.pxmid[1]*(1-f),v=r.separators,y=[];if(-1!==u.indexOf("label")&&y.push(n.label),-1!==u.indexOf("text")){var m=dc.castOption(s.hovertext||s.text,n.pts);m&&y.push(m)}-1!==u.indexOf("value")&&y.push(dc.formatPieValue(n.v,v)),-1!==u.indexOf("percent")&&y.push(dc.formatPiePercent(n.v/i.vTotal,v));var x=o.hoverlabel,b=x.font;Li.loneHover({x0:p-f*i.r,x1:p+f*i.r,y:g,text:y.join("
"),name:-1!==u.indexOf("name")?s.name:void 0,idealAlign:n.pxmid[0]<0?"left":"right",color:dc.castOption(x.bgcolor,n.pts)||n.color,borderColor:dc.castOption(x.bordercolor,n.pts),fontFamily:dc.castOption(b.family,n.pts),fontSize:dc.castOption(b.size,n.pts),fontColor:dc.castOption(b.color,n.pts)},{container:l._hoverlayer.node(),outerContainer:l._paper.node(),gd:t}),d=!0}t.emit("plotly_hover",{points:[qh(n,s)],event:e.event}),h=!0}}).on("mouseout",function(r){var a=t._fullLayout,i=t._fullData[o.index];h&&(r.originalEvent=e.event,t.emit("plotly_unhover",{points:[qh(n,i)],event:e.event}),h=!1),d&&(Li.loneUnhover(a._hoverlayer.node()),d=!1)}).on("click",function(){var r=t._fullLayout,a=t._fullData[o.index];t._dragging||!1===r.hovermode||(t._hoverdata=[qh(n,a)],Li.click(t,e.event))}),o.pull){var p=+dc.castOption(o.pull,n.pts)||0;p>0&&(a+=p*n.pxmid[0],c+=p*n.pxmid[1])}n.cxFinal=a,n.cyFinal=c;var g=o.hole;if(n.v===i.vTotal){var v="M"+(a+n.px0[0])+","+(c+n.px0[1])+_(n.px0,n.pxmid,!0,1)+_(n.pxmid,n.px0,!0,1)+"Z";g?f.attr("d","M"+(a+g*n.px0[0])+","+(c+g*n.px0[1])+_(n.px0,n.pxmid,!1,g)+_(n.pxmid,n.px0,!1,g)+"Z"+v):f.attr("d",v)}else{var y=_(n.px0,n.px1,!0,1);if(g){var m=1-g;f.attr("d","M"+(a+g*n.px1[0])+","+(c+g*n.px1[1])+_(n.px1,n.px0,!1,g)+"l"+m*n.px0[0]+","+m*n.px0[1]+y+"Z")}else f.attr("d","M"+a+","+c+"l"+n.px0[0]+","+n.px0[1]+y+"Z")}var x=dc.castOption(o.textposition,n.pts),b=u.selectAll("g.slicetext").data(n.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var r=rt.ensureSingle(e.select(this),"text","",function(e){e.attr("data-notex",1)});r.text(n.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Un.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(mn.convertToTspans,t);var l,u=Un.bBox(r.node());"outside"===x?l=Uh(u,n):(l=function(e,t,n){var r=Math.sqrt(e.width*e.width+e.height*e.height),a=e.width/e.height,i=Math.PI*Math.min(t.v/n.vTotal,.5),o=1-n.trace.hole,l=Vh(t,n),s={scale:l*n.r*2/r,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=n.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),f={scale:2*u/e.height,rCenter:Math.cos(u/n.r)-u*a/n.r,rotate:(180/Math.PI*t.midangle+720)%180-90},d=1/a,h=d+1/(2*Math.tan(i)),p=n.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(d*d+o/2)+d)),g={scale:2*p/e.width,rCenter:Math.cos(p/n.r)-p/a/n.r,rotate:(180/Math.PI*t.midangle+810)%180-90},v=g.scale>f.scale?g:f;return s.scale<1&&v.scale>s.scale?v:s}(u,n,i),"auto"===x&&l.scale<1&&(r.call(Un.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(u=Un.bBox(r.node())),l=Uh(u,n)));var f=a+n.pxmid[0]*l.rCenter+(l.x||0),d=c+n.pxmid[1]*l.rCenter+(l.y||0);l.outside&&(n.yLabelMin=d-u.height/2,n.yLabelMid=d,n.yLabelMax=d+u.height/2,n.labelExtraX=0,n.labelExtraY=0,s=!0),r.attr("transform","translate("+f+","+d+")"+(l.scale<1?"scale("+l.scale+")":"")+(l.rotate?"rotate("+l.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function _(e,t,r,a){return"a"+a*i.r+","+a*i.r+" 0 "+n.largeArc+(r?" 1 ":" 0 ")+a*(t[0]-e[0])+","+a*(t[1]-e[1])}}),s&&function(e,t){var n,r,a,i,o,l,s,c,u,f,d,h,p;function g(e,t){return e.pxmid[1]-t.pxmid[1]}function v(e,t){return t.pxmid[1]-e.pxmid[1]}function y(e,n){n||(n={});var a,c,u,d,h,p,g=n.labelExtraY+(r?n.yLabelMax:n.yLabelMin),v=r?e.yLabelMin:e.yLabelMax,y=r?e.yLabelMax:e.yLabelMin,m=e.cyFinal+o(e.px0[1],e.px1[1]),x=g-v;if(x*s>0&&(e.labelExtraY=x),Array.isArray(t.pull))for(c=0;c=(dc.castOption(t.pull,u.pts)||0)||((e.pxmid[1]-u.pxmid[1])*s>0?(d=u.cyFinal+o(u.px0[1],u.px1[1]),(x=d-v-e.labelExtraY)*s>0&&(e.labelExtraY+=x)):(y+e.labelExtraY-m)*s>0&&(a=3*l*Math.abs(c-f.indexOf(e)),h=u.cxFinal+i(u.px0[0],u.px1[0]),(p=h+a-(e.cxFinal+e.pxmid[0])-e.labelExtraX)*l>0&&(e.labelExtraX+=p)))}for(r=0;r<2;r++)for(a=r?g:v,o=r?Math.max:Math.min,s=r?1:-1,n=0;n<2;n++){for(i=n?Math.max:Math.min,l=n?1:-1,(c=e[r][n]).sort(a),u=e[1-r][n],f=u.concat(c),h=[],d=0;dMath.abs(c)?i+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):i+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else i+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;n.append("path").classed("textline",!0).call(Rt.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:i,fill:"none"})}})})}),setTimeout(function(){a.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},Gh.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var n=t[0].trace,r=e.select(this);r.style({opacity:n.opacity}),r.selectAll("path.surface").each(function(t){e.select(this).call(pc,t,n)})})},Gh.styleOne=pc,Gh.moduleType="trace",Gh.name="pie",Gh.basePlotModule=Dh,Gh.categories=["pie","showLegend"],Gh.meta={};var Yh=Gh;return Ch.register([Xl,Yh]),Ch}); \ No newline at end of file diff --git a/dist/plotly-cartesian.js b/dist/plotly-cartesian.js index 71fd485830e..7293ff9a624 100644 --- a/dist/plotly-cartesian.js +++ b/dist/plotly-cartesian.js @@ -1,5 +1,5 @@ /** -* plotly.js (cartesian) v1.35.2 +* plotly.js (cartesian) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -11218,7 +11218,7 @@ var _$interactions_153 = { DESELECTDIM: 0.2 }; -var _$is_array_172 = {}; +var _$is_array_173 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11239,12 +11239,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_172.isTypedArray = function(a) { +_$is_array_173.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_172.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_172.isTypedArray(a); +_$is_array_173.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_173.isTypedArray(a); }; /** @@ -11259,7 +11259,7 @@ _$is_array_172.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_173 = function isPlainObject(obj) { +var _$isPlainObject_174 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11275,7 +11275,7 @@ var _$isPlainObject_173 = function isPlainObject(obj) { ); }; -var _$extend_165 = {}; +var _$extend_166 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11287,7 +11287,7 @@ var _$extend_165 = {}; 'use strict'; -/* removed: var _$isPlainObject_173 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_174 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11304,19 +11304,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_165.extendFlat = function() { +_$extend_166.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_165.extendDeep = function() { +_$extend_166.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_165.extendDeepAll = function() { +_$extend_166.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_165.extendDeepNoArrays = function() { +_$extend_166.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11369,12 +11369,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_173(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_174(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_173(src) ? src : {}; + clone = src && _$isPlainObject_174(src) ? src : {}; } // never move original objects, clone them @@ -11409,7 +11409,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_203 = { +var _$plot_config_204 = { // no interactivity, for export or image generation staticPlot: false, @@ -11577,7 +11577,7 @@ var _$plot_config_203 = { locales: {} }; -var _$loggers_176 = {}; +var _$loggers_177 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11590,9 +11590,9 @@ var _$loggers_176 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_203 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_204 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_176 = {}; +var loggers = _$loggers_177 = {}; /** * ------------------------------------------ @@ -11601,7 +11601,7 @@ var loggers = _$loggers_176 = {}; */ loggers.log = function() { - if(_$plot_config_203.logging > 1) { + if(_$plot_config_204.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11613,7 +11613,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_203.logging > 0) { + if(_$plot_config_204.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11625,7 +11625,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_203.logging > 0) { + if(_$plot_config_204.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11664,7 +11664,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_180 = function noop() {}; +var _$noop_181 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11689,7 +11689,7 @@ var _$noop_180 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_184 = function pushUnique(array, item) { +var _$pushUnique_185 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11826,7 +11826,7 @@ var _$attributes_85 = { /* removed: var _$attributes_85 = require('../components/fx/attributes'); */; -var _$attributes_210 = { +var _$attributes_211 = { type: { valType: 'enumerated', @@ -12132,7 +12132,7 @@ var _$layout_attributes_244 = { } }; -var _$registry_261 = {}; +var _$registry_262 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12143,29 +12143,29 @@ var _$registry_261 = {}; 'use strict'; -/* removed: var _$loggers_176 = require('./lib/loggers'); */; -/* removed: var _$noop_180 = require('./lib/noop'); */; -/* removed: var _$pushUnique_184 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_173 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_165 = require('./lib/extend'); */; +/* removed: var _$loggers_177 = require('./lib/loggers'); */; +/* removed: var _$noop_181 = require('./lib/noop'); */; +/* removed: var _$pushUnique_185 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_174 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_166 = require('./lib/extend'); */; -/* removed: var _$attributes_210 = require('./plots/attributes'); */; +/* removed: var _$attributes_211 = require('./plots/attributes'); */; /* removed: var _$layout_attributes_244 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_165.extendFlat; -var extendDeepAll = _$extend_165.extendDeepAll; +var extendFlat = _$extend_166.extendFlat; +var extendDeepAll = _$extend_166.extendDeepAll; -_$registry_261.modules = {}; -_$registry_261.allCategories = {}; -_$registry_261.allTypes = []; -_$registry_261.subplotsRegistry = {}; -_$registry_261.transformsRegistry = {}; -_$registry_261.componentsRegistry = {}; -_$registry_261.layoutArrayContainers = []; -_$registry_261.layoutArrayRegexes = []; -_$registry_261.traceLayoutAttributes = {}; -_$registry_261.localeRegistry = {}; -_$registry_261.apiMethodRegistry = {}; +_$registry_262.modules = {}; +_$registry_262.allCategories = {}; +_$registry_262.allTypes = []; +_$registry_262.subplotsRegistry = {}; +_$registry_262.transformsRegistry = {}; +_$registry_262.componentsRegistry = {}; +_$registry_262.layoutArrayContainers = []; +_$registry_262.layoutArrayRegexes = []; +_$registry_262.traceLayoutAttributes = {}; +_$registry_262.localeRegistry = {}; +_$registry_262.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12206,7 +12206,7 @@ _$registry_261.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_261.register = function register(_modules) { +_$registry_262.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12235,7 +12235,7 @@ _$registry_261.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_261.apiMethodRegistry[name] = newModule.fn; + _$registry_262.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12251,8 +12251,8 @@ _$registry_261.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_261.getModule = function(trace) { - var _module = _$registry_261.modules[getTraceType(trace)]; +_$registry_262.getModule = function(trace) { + var _module = _$registry_262.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12266,20 +12266,20 @@ _$registry_261.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_261.traceIs = function(traceType, category) { +_$registry_262.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_261.modules[traceType]; + var _module = _$registry_262.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_176.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_177.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_261.modules[_$attributes_210.type.dflt]; + _module = _$registry_262.modules[_$attributes_211.type.dflt]; } return !!_module.categories[category]; @@ -12296,7 +12296,7 @@ _$registry_261.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_261.getTransformIndices = function(data, type) { +_$registry_262.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12316,7 +12316,7 @@ _$registry_261.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_261.hasTransform = function(data, type) { +_$registry_262.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12336,11 +12336,11 @@ _$registry_261.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_261.getComponentMethod = function(name, method) { - var _module = _$registry_261.componentsRegistry[name]; +_$registry_262.getComponentMethod = function(name, method) { + var _module = _$registry_262.componentsRegistry[name]; - if(!_module) return _$noop_180; - return _module[method] || _$noop_180; + if(!_module) return _$noop_181; + return _module[method] || _$noop_181; }; /** @@ -12350,10 +12350,10 @@ _$registry_261.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_261.call = function() { +_$registry_262.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_261.apiMethodRegistry[name].apply(null, args); + return _$registry_262.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12361,33 +12361,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_261.modules[thisType]) { - _$loggers_176.log('Type ' + thisType + ' already registered'); + if(_$registry_262.modules[thisType]) { + _$loggers_177.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_261.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_262.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_261.allCategories[categoriesIn[i]] = true; + _$registry_262.allCategories[categoriesIn[i]] = true; } - _$registry_261.modules[thisType] = { + _$registry_262.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_261.modules[thisType].meta = meta; + _$registry_262.modules[thisType].meta = meta; } - _$registry_261.allTypes.push(thisType); + _$registry_262.allTypes.push(thisType); - for(var componentName in _$registry_261.componentsRegistry) { + for(var componentName in _$registry_262.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12397,15 +12397,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_261.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_262.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_261.subplotsRegistry[plotType]) { - _$loggers_176.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_262.subplotsRegistry[plotType]) { + _$loggers_177.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12415,9 +12415,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_261.subplotsRegistry[plotType] = _module; + _$registry_262.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_261.componentsRegistry) { + for(var componentName in _$registry_262.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12428,24 +12428,24 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_261.componentsRegistry[name] = _module; + _$registry_262.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_184(_$registry_261.layoutArrayContainers, name); + _$pushUnique_185(_$registry_262.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_261.modules) { + for(var traceType in _$registry_262.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_261.subplotsRegistry) { + for(var subplotName in _$registry_262.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_261.transformsRegistry) { + for(var transformType in _$registry_262.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } @@ -12467,22 +12467,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_176.log([ + _$loggers_177.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_173(_module.attributes)) { - _$loggers_176.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_174(_module.attributes)) { + _$loggers_177.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_176.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_177.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_261.transformsRegistry[_module.name] = _module; + _$registry_262.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_261.componentsRegistry) { + for(var componentName in _$registry_262.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12496,7 +12496,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_261.localeRegistry; + var locales = _$registry_262.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12528,37 +12528,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_184(_$registry_261.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_185(_$registry_262.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_261.componentsRegistry[componentName].schema; + var componentSchema = _$registry_262.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_261.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_262.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_261.componentsRegistry[componentName].schema; + var componentSchema = _$registry_262.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_261.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_262.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_261.componentsRegistry[componentName].schema; + var componentSchema = _$registry_262.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_261.subplotsRegistry[subplotName]; + var subplotModule = _$registry_262.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12585,7 +12585,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_261 = require('../registry'); */; +/* removed: var _$registry_262 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12600,9 +12600,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_197 = function containerArrayMatch(astr) { - var rootContainers = _$registry_261.layoutArrayContainers, - regexpContainers = _$registry_261.layoutArrayRegexes, +var _$containerArrayMatch_198 = function containerArrayMatch(astr) { + var rootContainers = _$registry_262.layoutArrayContainers, + regexpContainers = _$registry_262.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12643,9 +12643,9 @@ var _$containerArrayMatch_197 = function containerArrayMatch(astr) { 'use strict'; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_172.isArrayOrTypedArray; -/* removed: var _$isPlainObject_173 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_197 = require('../plot_api/container_array_match'); */; +var isArrayOrTypedArray = _$is_array_173.isArrayOrTypedArray; +/* removed: var _$isPlainObject_174 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_198 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12661,7 +12661,7 @@ var isArrayOrTypedArray = _$is_array_172.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_179 = function nestedProperty(container, propStr) { +var _$nestedProperty_180 = function nestedProperty(container, propStr) { if(_$fastIsnumeric_18(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { @@ -12772,7 +12772,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_173(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_174(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12781,7 +12781,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_197(propStr); + var match = _$containerArrayMatch_198(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12934,7 +12934,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_186 = {}; +var _$regex_187 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12954,7 +12954,7 @@ var _$regex_186 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_186.counter = function(head, tail, openEnded) { +_$regex_187.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12962,7 +12962,7 @@ _$regex_186.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_161 = {}; +var _$coerce_162 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12977,16 +12977,16 @@ var _$coerce_161 = {}; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$attributes_210 = require('../plots/attributes'); */; +/* removed: var _$attributes_211 = require('../plots/attributes'); */; /* removed: var _$getScale_64 = require('../components/colorscale/get_scale'); */; var colorscaleNames = Object.keys(_$scales_70); -/* removed: var _$nestedProperty_179 = require('./nested_property'); */; -var counterRegex = _$regex_186.counter; +/* removed: var _$nestedProperty_180 = require('./nested_property'); */; +var counterRegex = _$regex_187.counter; var DESELECTDIM = _$interactions_153.DESELECTDIM; var wrap180 = _$angles_159.wrap180; -var __isArrayOrTypedArray_161 = _$is_array_172.isArrayOrTypedArray; +var __isArrayOrTypedArray_162 = _$is_array_173.isArrayOrTypedArray; -_$coerce_161.valObjectMeta = { +_$coerce_162.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12994,7 +12994,7 @@ _$coerce_161.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_161(v)) propOut.set(v); + if(__isArrayOrTypedArray_162(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13117,8 +13117,9 @@ _$coerce_161.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13172,9 +13173,11 @@ _$coerce_161.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13185,12 +13188,12 @@ _$coerce_161.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_161.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_162.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13200,19 +13203,28 @@ _$coerce_161.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13243,12 +13255,12 @@ _$coerce_161.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_161.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_162.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_161.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_162.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13268,10 +13280,10 @@ _$coerce_161.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_161.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_179(attributes, attribute).get(), - propIn = _$nestedProperty_179(containerIn, attribute), - propOut = _$nestedProperty_179(containerOut, attribute), +_$coerce_162.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_180(attributes, attribute).get(), + propIn = _$nestedProperty_180(containerIn, attribute), + propOut = _$nestedProperty_180(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13282,12 +13294,12 @@ _$coerce_161.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_161(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_162(v)) { propOut.set(v); return v; } - _$coerce_161.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_162.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13299,9 +13311,9 @@ _$coerce_161.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_161.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_179(containerIn, attribute), - propOut = _$coerce_161.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_162.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_180(containerIn, attribute), + propOut = _$coerce_162.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13312,7 +13324,7 @@ _$coerce_161.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_161.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_162.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13332,11 +13344,9 @@ _$coerce_161.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_161.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_162.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_210; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_211; var valObj = attrs.hoverinfo; var dflt; @@ -13350,7 +13360,7 @@ _$coerce_161.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_161.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_162.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13364,7 +13374,7 @@ _$coerce_161.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_161.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_162.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13379,7 +13389,7 @@ _$coerce_161.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_161(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_162(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13388,10 +13398,10 @@ _$coerce_161.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_161.validate = function(value, opts) { - var valObjectDef = _$coerce_161.valObjectMeta[opts.valType]; +_$coerce_162.validate = function(value, opts) { + var valObjectDef = _$coerce_162.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_161(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_162(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13421,12 +13431,12 @@ _$coerce_161.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_178 = function mod(v, d) { +var _$mod_179 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_162 = {}; +var _$dates_163 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13441,18 +13451,18 @@ var _$dates_162 = {}; /* removed: var _$d3_15 = require('d3'); */; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$loggers_176 = require('./loggers'); */; -/* removed: var _$mod_178 = require('./mod'); */; +/* removed: var _$loggers_177 = require('./loggers'); */; +/* removed: var _$mod_179 = require('./mod'); */; /* removed: var _$numerical_154 = require('../constants/numerical'); */; -var __BADNUM_162 = _$numerical_154.BADNUM; +var __BADNUM_163 = _$numerical_154.BADNUM; var ONEDAY = _$numerical_154.ONEDAY; var ONEHOUR = _$numerical_154.ONEHOUR; var ONEMIN = _$numerical_154.ONEMIN; var ONESEC = _$numerical_154.ONESEC; var EPOCHJD = _$numerical_154.EPOCHJD; -/* removed: var _$registry_261 = require('../registry'); */; +/* removed: var _$registry_262 = require('../registry'); */; var utcFormat = _$d3_15.time.format.utc; @@ -13466,7 +13476,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_261.componentsRegistry.calendars && + _$registry_262.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13476,11 +13486,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_162.dateTick0 = function(calendar, sunday) { +_$dates_163.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_261.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_261.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_262.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_262.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13490,9 +13500,9 @@ _$dates_162.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_162.dfltRange = function(calendar) { +_$dates_163.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_261.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_262.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13500,7 +13510,7 @@ _$dates_162.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_162.isJSDate = function(v) { +_$dates_163.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13562,17 +13572,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_162.dateTime2ms = function(s, calendar) { +_$dates_163.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_162.isJSDate(s)) { + if(_$dates_163.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_162; + return __BADNUM_163; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_162; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_163; s = String(s); @@ -13589,7 +13599,7 @@ _$dates_162.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_162; + if(!match) return __BADNUM_163; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13599,12 +13609,12 @@ _$dates_162.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_162; + if(y.length === 2) return __BADNUM_163; y = Number(y); var cDate; try { - var calInstance = _$registry_261.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_262.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13614,9 +13624,9 @@ _$dates_162.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_162; } // Invalid ... date + catch(e) { return __BADNUM_163; } // Invalid ... date - if(!cDate) return __BADNUM_162; + if(!cDate) return __BADNUM_163; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13637,18 +13647,18 @@ _$dates_162.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_162; - if(date.getUTCDate() !== d) return __BADNUM_162; + if(date.getUTCMonth() !== m) return __BADNUM_163; + if(date.getUTCDate() !== d) return __BADNUM_163; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_162.MIN_MS = _$dates_162.dateTime2ms('-9999'); -MAX_MS = _$dates_162.MAX_MS = _$dates_162.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_163.MIN_MS = _$dates_163.dateTime2ms('-9999'); +MAX_MS = _$dates_163.MAX_MS = _$dates_163.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_162.isDateTime = function(s, calendar) { - return (_$dates_162.dateTime2ms(s, calendar) !== __BADNUM_162); +_$dates_163.isDateTime = function(s, calendar) { + return (_$dates_163.dateTime2ms(s, calendar) !== __BADNUM_163); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13667,20 +13677,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_162.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_162; +_$dates_163.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_163; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_178(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_179(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_178(ms, ONEDAY)); + timeMs = Math.floor(_$mod_179(ms, ONEDAY)); try { - dateStr = _$registry_261.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_262.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13728,10 +13738,10 @@ _$dates_162.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_162.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_162; +_$dates_163.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_163; - var msecTenths = Math.floor(_$mod_178(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_179(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), dateStr = _$d3_15.time.format('%Y-%m-%d')(d), h = d.getHours(), @@ -13764,23 +13774,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_162.cleanDate = function(v, dflt, calendar) { - if(_$dates_162.isJSDate(v) || typeof v === 'number') { +_$dates_163.cleanDate = function(v, dflt, calendar) { + if(_$dates_163.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_176.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_177.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 = _$dates_162.ms2DateTimeLocal(+v); + v = _$dates_163.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_162.isDateTime(v, calendar)) { - _$loggers_176.error('unrecognized date', v); + else if(!_$dates_163.isDateTime(v, calendar)) { + _$loggers_177.error('unrecognized date', v); return dflt; } return v; @@ -13810,7 +13820,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_261.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_262.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13827,10 +13837,10 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_178(x + 0.05, ONEDAY); + var timePart = _$mod_179(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_178(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_179(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { if(!_$fastIsnumeric_18(tr)) tr = 0; // should only be 'S' @@ -13850,7 +13860,7 @@ function formatTime(x, tr) { * 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_178(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_179(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13879,7 +13889,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_162.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_163.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13923,19 +13933,19 @@ _$dates_162.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_162.incrementMonth = function(ms, dMonth, calendar) { +_$dates_163.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_178(ms, ONEDAY); + var timeMs = _$mod_179(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_261.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_262.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13944,7 +13954,7 @@ _$dates_162.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_176.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_177.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13959,7 +13969,7 @@ _$dates_162.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_162.findExactDates = function(data, calendar) { +_$dates_163.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13969,7 +13979,7 @@ _$dates_162.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_261.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_262.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { @@ -14036,7 +14046,7 @@ _$dates_162.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_163 = function ensureArray(out, n) { +var _$ensureArray_164 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14079,7 +14089,7 @@ var _$ensureArray_163 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_166 = function filterUnique(array) { +var _$filterUnique_167 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14113,7 +14123,7 @@ var _$filterUnique_166 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_167 = function filterVisible(container) { +var _$filterVisible_168 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14142,7 +14152,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_168 = {}; +var _$geometry2d_169 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14153,13 +14163,13 @@ var _$geometry2d_168 = {}; 'use strict'; -/* removed: var _$mod_178 = require('./mod'); */; +/* removed: var _$mod_179 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_168.segmentsIntersect = segmentsIntersect; +_$geometry2d_169.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14182,7 +14192,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_168.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_169.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 @@ -14235,7 +14245,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_168.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_169.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14247,13 +14257,13 @@ _$geometry2d_168.getTextLocation = function getTextLocation(path, totalPathLen, // 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_178(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_178(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_179(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_179(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_178(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_179(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14262,7 +14272,7 @@ _$geometry2d_168.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_168.clearLocationCache = function() { +_$geometry2d_169.clearLocationCache = function() { workingPath = null; }; @@ -14290,7 +14300,7 @@ _$geometry2d_168.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_168.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_169.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14351,7 +14361,7 @@ _$geometry2d_168.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_168.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_169.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14406,7 +14416,7 @@ _$geometry2d_168.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_169 = function(gd) { +var _$get_graph_div_170 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14438,7 +14448,7 @@ var _$get_graph_div_169 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_170 = function identity(d) { return d; }; +var _$identity_171 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14450,7 +14460,7 @@ var _$identity_170 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_179 = require('./nested_property'); */; +/* removed: var _$nestedProperty_180 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14472,13 +14482,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_175 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_179(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_180(baseObj, path).get(); } else { arr = baseObj; } @@ -14504,7 +14514,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_179(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_180(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14514,7 +14524,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_179(newValue, valueName).set(value); + _$nestedProperty_180(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14535,7 +14545,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_179(arr[idx], valueName).get(); + return _$nestedProperty_180(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14576,7 +14586,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value } 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_179(object, valueName).set(null); + _$nestedProperty_180(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, @@ -14603,7 +14613,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_179(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_180(arr[idx], valueName).get(); } } } else { @@ -14629,7 +14639,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_261 = require('../registry'); */; +/* removed: var _$registry_262 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14640,7 +14650,7 @@ var _$keyedContainer_174 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_175 = function localize(gd, s) { +var _$localize_176 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14662,7 +14672,7 @@ var _$localize_175 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_261.localeRegistry; + locales = _$registry_262.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14673,7 +14683,7 @@ var _$localize_175 = function localize(gd, s) { return s; }; -var _$matrix_177 = {}; +var _$matrix_178 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14686,7 +14696,7 @@ var _$matrix_177 = {}; 'use strict'; -_$matrix_177.init2dArray = function(rowLength, colLength) { +_$matrix_178.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14697,7 +14707,7 @@ _$matrix_177.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_177.transposeRagged = function(z) { +_$matrix_178.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14715,7 +14725,7 @@ _$matrix_177.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_177.dot = function(x, y) { +_$matrix_178.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14725,13 +14735,13 @@ _$matrix_177.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_177.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_178.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_177.transposeRagged(y); + var yTranspose = _$matrix_178.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_177.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_178.dot(x, yTranspose[i]); } else { // vec-vec @@ -14743,12 +14753,12 @@ _$matrix_177.dot = function(x, y) { }; // translate by (x,y) -_$matrix_177.translationMatrix = function(x, y) { +_$matrix_178.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_177.rotationMatrix = function(alpha) { +_$matrix_178.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14756,28 +14766,28 @@ _$matrix_177.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_177.rotationXYMatrix = function(a, x, y) { - return _$matrix_177.dot( - _$matrix_177.dot(_$matrix_177.translationMatrix(x, y), - _$matrix_177.rotationMatrix(a)), - _$matrix_177.translationMatrix(-x, -y)); +_$matrix_178.rotationXYMatrix = function(a, x, y) { + return _$matrix_178.dot( + _$matrix_178.dot(_$matrix_178.translationMatrix(x, y), + _$matrix_178.rotationMatrix(a)), + _$matrix_178.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_177.apply2DTransform = function(transform) { +_$matrix_178.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_177.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_178.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_177.apply2DTransform2 = function(transform) { - var at = _$matrix_177.apply2DTransform(transform); +_$matrix_178.apply2DTransform2 = function(transform) { + var at = _$matrix_178.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14806,7 +14816,7 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_181 = function(text, displayLength) { +var _$notifier_182 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); @@ -14898,7 +14908,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_187 = function(baseAttr, relativeAttr) { +var _$relative_attr_188 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14927,8 +14937,8 @@ var _$relative_attr_187 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_188 = _$is_array_172.isArrayOrTypedArray; -/* removed: var _$isPlainObject_173 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_189 = _$is_array_173.isArrayOrTypedArray; +/* removed: var _$isPlainObject_174 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14937,7 +14947,7 @@ var __isArrayOrTypedArray_188 = _$is_array_172.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_188 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_189 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14953,7 +14963,7 @@ var _$relinkPrivateKeys_188 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_188(fromVal) && __isArrayOrTypedArray_188(toVal) && _$isPlainObject_173(fromVal[0])) { + else if(__isArrayOrTypedArray_189(fromVal) && __isArrayOrTypedArray_189(toVal) && _$isPlainObject_174(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14963,12 +14973,12 @@ var _$relinkPrivateKeys_188 = function relinkPrivateKeys(toContainer, fromContai // 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_173(fromVal[j]) && _$isPlainObject_173(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_174(fromVal[j]) && _$isPlainObject_174(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_173(fromVal) && _$isPlainObject_173(toVal)) { + else if(_$isPlainObject_174(fromVal) && _$isPlainObject_174(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14978,7 +14988,7 @@ var _$relinkPrivateKeys_188 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_189 = {}; +var _$search_190 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14991,7 +15001,7 @@ var _$search_189 = {}; 'use strict'; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$loggers_176 = require('./loggers'); */; +/* removed: var _$loggers_177 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -15009,7 +15019,7 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_189.findBin = function(val, bins, linelow) { +_$search_190.findBin = function(val, bins, linelow) { if(_$fastIsnumeric_18(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : @@ -15033,7 +15043,7 @@ _$search_189.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_176.log('Long binary search...'); + if(c > 90) _$loggers_177.log('Long binary search...'); return n1 - 1; } }; @@ -15043,17 +15053,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_189.sorterAsc = function(a, b) { return a - b; }; -_$search_189.sorterDes = function(a, b) { return b - a; }; +_$search_190.sorterAsc = function(a, b) { return a - b; }; +_$search_190.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_189.distinctVals = function(valsIn) { +_$search_190.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_189.sorterAsc); + vals.sort(_$search_190.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15078,7 +15088,7 @@ _$search_189.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_189.roundUp = function(val, arrayIn, reverse) { +_$search_190.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15095,7 +15105,7 @@ _$search_189.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_191 = {}; +var _$stats_192 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15108,7 +15118,7 @@ var _$stats_191 = {}; 'use strict'; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_191 = _$is_array_172.isArrayOrTypedArray; +var __isArrayOrTypedArray_192 = _$is_array_173.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15123,14 +15133,14 @@ var __isArrayOrTypedArray_191 = _$is_array_172.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_191.aggNums = function(f, v, a, len) { +_$stats_192.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; if(!_$fastIsnumeric_18(v)) v = false; - if(__isArrayOrTypedArray_191(a[0])) { + if(__isArrayOrTypedArray_192(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_191.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_192.aggNums(f, v, a[i]); a = b; } @@ -15145,26 +15155,26 @@ _$stats_191.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_191.len = function(data) { - return _$stats_191.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_192.len = function(data) { + return _$stats_192.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_191.mean = function(data, len) { - if(!len) len = _$stats_191.len(data); - return _$stats_191.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_192.mean = function(data, len) { + if(!len) len = _$stats_192.len(data); + return _$stats_192.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_191.variance = function(data, len, mean) { - if(!len) len = _$stats_191.len(data); - if(!_$fastIsnumeric_18(mean)) mean = _$stats_191.mean(data, len); +_$stats_192.variance = function(data, len, mean) { + if(!len) len = _$stats_192.len(data); + if(!_$fastIsnumeric_18(mean)) mean = _$stats_192.mean(data, len); - return _$stats_191.aggNums(function(a, b) { + return _$stats_192.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_191.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_191.variance(data, len, mean)); +_$stats_192.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_192.variance(data, len, mean)); }; /** @@ -15182,7 +15192,7 @@ _$stats_191.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_191.interp = function(arr, n) { +_$stats_192.interp = function(arr, n) { if(!_$fastIsnumeric_18(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; @@ -15191,7 +15201,7 @@ _$stats_191.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_193 = {}; +var _$throttle_194 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15218,7 +15228,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_193.throttle = function throttle(id, minInterval, callback) { +_$throttle_194.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15258,7 +15268,7 @@ _$throttle_193.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_193.done = function(id) { +_$throttle_194.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15278,13 +15288,13 @@ _$throttle_193.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_193.clear = function(id) { +_$throttle_194.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_193.clear(idi); + for(var idi in timerCache) _$throttle_194.clear(idi); } }; @@ -15311,7 +15321,7 @@ function _clearTimeout(cache) { * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_194 = function toLogRange(val, range) { +var _$toLogRange_195 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the @@ -15322,7 +15332,7 @@ var _$toLogRange_194 = function toLogRange(val, range) { return newVal; }; -var _$lib_171 = {}; +var _$lib_172 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15339,71 +15349,71 @@ var _$lib_171 = {}; /* removed: var _$numerical_154 = require('../constants/numerical'); */; var FP_SAFE = _$numerical_154.FP_SAFE; -var __BADNUM_171 = _$numerical_154.BADNUM; - -var lib = _$lib_171 = {}; - -lib.nestedProperty = _$nestedProperty_179; -lib.keyedContainer = _$keyedContainer_174; -lib.relativeAttr = _$relative_attr_187; -lib.isPlainObject = _$isPlainObject_173; -lib.mod = _$mod_178; -lib.toLogRange = _$toLogRange_194; -lib.relinkPrivateKeys = _$relinkPrivateKeys_188; -lib.ensureArray = _$ensureArray_163; - -/* removed: var _$is_array_172 = require('./is_array'); */; -lib.isTypedArray = _$is_array_172.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_172.isArrayOrTypedArray; - -/* removed: var _$coerce_161 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_161.valObjectMeta; -lib.coerce = _$coerce_161.coerce; -lib.coerce2 = _$coerce_161.coerce2; -lib.coerceFont = _$coerce_161.coerceFont; -lib.coerceHoverinfo = _$coerce_161.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_161.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_161.validate; - -/* removed: var _$dates_162 = require('./dates'); */; -lib.dateTime2ms = _$dates_162.dateTime2ms; -lib.isDateTime = _$dates_162.isDateTime; -lib.ms2DateTime = _$dates_162.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_162.ms2DateTimeLocal; -lib.cleanDate = _$dates_162.cleanDate; -lib.isJSDate = _$dates_162.isJSDate; -lib.formatDate = _$dates_162.formatDate; -lib.incrementMonth = _$dates_162.incrementMonth; -lib.dateTick0 = _$dates_162.dateTick0; -lib.dfltRange = _$dates_162.dfltRange; -lib.findExactDates = _$dates_162.findExactDates; -lib.MIN_MS = _$dates_162.MIN_MS; -lib.MAX_MS = _$dates_162.MAX_MS; - -/* removed: var _$search_189 = require('./search'); */; -lib.findBin = _$search_189.findBin; -lib.sorterAsc = _$search_189.sorterAsc; -lib.sorterDes = _$search_189.sorterDes; -lib.distinctVals = _$search_189.distinctVals; -lib.roundUp = _$search_189.roundUp; - -/* removed: var _$stats_191 = require('./stats'); */; -lib.aggNums = _$stats_191.aggNums; -lib.len = _$stats_191.len; -lib.mean = _$stats_191.mean; -lib.variance = _$stats_191.variance; -lib.stdev = _$stats_191.stdev; -lib.interp = _$stats_191.interp; - -/* removed: var _$matrix_177 = require('./matrix'); */; -lib.init2dArray = _$matrix_177.init2dArray; -lib.transposeRagged = _$matrix_177.transposeRagged; -lib.dot = _$matrix_177.dot; -lib.translationMatrix = _$matrix_177.translationMatrix; -lib.rotationMatrix = _$matrix_177.rotationMatrix; -lib.rotationXYMatrix = _$matrix_177.rotationXYMatrix; -lib.apply2DTransform = _$matrix_177.apply2DTransform; -lib.apply2DTransform2 = _$matrix_177.apply2DTransform2; +var __BADNUM_172 = _$numerical_154.BADNUM; + +var lib = _$lib_172 = {}; + +lib.nestedProperty = _$nestedProperty_180; +lib.keyedContainer = _$keyedContainer_175; +lib.relativeAttr = _$relative_attr_188; +lib.isPlainObject = _$isPlainObject_174; +lib.mod = _$mod_179; +lib.toLogRange = _$toLogRange_195; +lib.relinkPrivateKeys = _$relinkPrivateKeys_189; +lib.ensureArray = _$ensureArray_164; + +/* removed: var _$is_array_173 = require('./is_array'); */; +lib.isTypedArray = _$is_array_173.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_173.isArrayOrTypedArray; + +/* removed: var _$coerce_162 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_162.valObjectMeta; +lib.coerce = _$coerce_162.coerce; +lib.coerce2 = _$coerce_162.coerce2; +lib.coerceFont = _$coerce_162.coerceFont; +lib.coerceHoverinfo = _$coerce_162.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_162.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_162.validate; + +/* removed: var _$dates_163 = require('./dates'); */; +lib.dateTime2ms = _$dates_163.dateTime2ms; +lib.isDateTime = _$dates_163.isDateTime; +lib.ms2DateTime = _$dates_163.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_163.ms2DateTimeLocal; +lib.cleanDate = _$dates_163.cleanDate; +lib.isJSDate = _$dates_163.isJSDate; +lib.formatDate = _$dates_163.formatDate; +lib.incrementMonth = _$dates_163.incrementMonth; +lib.dateTick0 = _$dates_163.dateTick0; +lib.dfltRange = _$dates_163.dfltRange; +lib.findExactDates = _$dates_163.findExactDates; +lib.MIN_MS = _$dates_163.MIN_MS; +lib.MAX_MS = _$dates_163.MAX_MS; + +/* removed: var _$search_190 = require('./search'); */; +lib.findBin = _$search_190.findBin; +lib.sorterAsc = _$search_190.sorterAsc; +lib.sorterDes = _$search_190.sorterDes; +lib.distinctVals = _$search_190.distinctVals; +lib.roundUp = _$search_190.roundUp; + +/* removed: var _$stats_192 = require('./stats'); */; +lib.aggNums = _$stats_192.aggNums; +lib.len = _$stats_192.len; +lib.mean = _$stats_192.mean; +lib.variance = _$stats_192.variance; +lib.stdev = _$stats_192.stdev; +lib.interp = _$stats_192.interp; + +/* removed: var _$matrix_178 = require('./matrix'); */; +lib.init2dArray = _$matrix_178.init2dArray; +lib.transposeRagged = _$matrix_178.transposeRagged; +lib.dot = _$matrix_178.dot; +lib.translationMatrix = _$matrix_178.translationMatrix; +lib.rotationMatrix = _$matrix_178.rotationMatrix; +lib.rotationXYMatrix = _$matrix_178.rotationXYMatrix; +lib.apply2DTransform = _$matrix_178.apply2DTransform; +lib.apply2DTransform2 = _$matrix_178.apply2DTransform2; /* removed: var _$angles_159 = require('./angles'); */; lib.deg2rad = _$angles_159.deg2rad; @@ -15411,54 +15421,54 @@ lib.rad2deg = _$angles_159.rad2deg; lib.wrap360 = _$angles_159.wrap360; lib.wrap180 = _$angles_159.wrap180; -/* removed: var _$geometry2d_168 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_168.segmentsIntersect; -lib.segmentDistance = _$geometry2d_168.segmentDistance; -lib.getTextLocation = _$geometry2d_168.getTextLocation; -lib.clearLocationCache = _$geometry2d_168.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_168.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_168.findPointOnPath; +/* removed: var _$geometry2d_169 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_169.segmentsIntersect; +lib.segmentDistance = _$geometry2d_169.segmentDistance; +lib.getTextLocation = _$geometry2d_169.getTextLocation; +lib.clearLocationCache = _$geometry2d_169.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_169.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_169.findPointOnPath; -/* removed: var _$extend_165 = require('./extend'); */; -lib.extendFlat = _$extend_165.extendFlat; -lib.extendDeep = _$extend_165.extendDeep; -lib.extendDeepAll = _$extend_165.extendDeepAll; -lib.extendDeepNoArrays = _$extend_165.extendDeepNoArrays; +/* removed: var _$extend_166 = require('./extend'); */; +lib.extendFlat = _$extend_166.extendFlat; +lib.extendDeep = _$extend_166.extendDeep; +lib.extendDeepAll = _$extend_166.extendDeepAll; +lib.extendDeepNoArrays = _$extend_166.extendDeepNoArrays; -/* removed: var _$loggers_176 = require('./loggers'); */; -lib.log = _$loggers_176.log; -lib.warn = _$loggers_176.warn; -lib.error = _$loggers_176.error; +/* removed: var _$loggers_177 = require('./loggers'); */; +lib.log = _$loggers_177.log; +lib.warn = _$loggers_177.warn; +lib.error = _$loggers_177.error; -/* removed: var _$regex_186 = require('./regex'); */; -lib.counterRegex = _$regex_186.counter; +/* removed: var _$regex_187 = require('./regex'); */; +lib.counterRegex = _$regex_187.counter; -/* removed: var _$throttle_193 = require('./throttle'); */; -lib.throttle = _$throttle_193.throttle; -lib.throttleDone = _$throttle_193.done; -lib.clearThrottle = _$throttle_193.clear; +/* removed: var _$throttle_194 = require('./throttle'); */; +lib.throttle = _$throttle_194.throttle; +lib.throttleDone = _$throttle_194.done; +lib.clearThrottle = _$throttle_194.clear; -lib.getGraphDiv = _$get_graph_div_169; +lib.getGraphDiv = _$get_graph_div_170; -lib._ = _$localize_175; +lib._ = _$localize_176; -lib.notifier = _$notifier_181; +lib.notifier = _$notifier_182; -lib.filterUnique = _$filterUnique_166; -lib.filterVisible = _$filterVisible_167; -lib.pushUnique = _$pushUnique_184; +lib.filterUnique = _$filterUnique_167; +lib.filterVisible = _$filterVisible_168; +lib.pushUnique = _$pushUnique_185; lib.cleanNumber = _$cleanNumber_160; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_18(v)) return __BADNUM_171; + if(!_$fastIsnumeric_18(v)) return __BADNUM_172; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_171; - return _$fastIsnumeric_18(v) ? Number(v) : __BADNUM_171; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_172; + return _$fastIsnumeric_18(v) ? Number(v) : __BADNUM_172; }; -lib.noop = _$noop_180; -lib.identity = _$identity_170; +lib.noop = _$noop_181; +lib.identity = _$identity_171; /** * swap x and y of the same attribute in container cont @@ -15957,6 +15967,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16150,7 +16217,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_171 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_172 = /^\w*$/; /* * Substitute values from an object into a string @@ -16171,7 +16238,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_171.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_172.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16232,7 +16299,7 @@ lib.pseudoRandom = function() { 'use strict'; -var _$attributes_211 = { +var _$attributes_212 = { xaxis: { valType: 'subplotid', @@ -16258,21 +16325,21 @@ var _$attributes_211 = { */ 'use strict'; -var __counterRegex_218 = _$regex_186.counter; +var __counterRegex_219 = _$regex_187.counter; -var _$constants_218 = { +var _$constants_219 = { idRegex: { - x: __counterRegex_218('x'), - y: __counterRegex_218('y') + x: __counterRegex_219('x'), + y: __counterRegex_219('y') }, - attrRegex: __counterRegex_218('[xy]axis'), + attrRegex: __counterRegex_219('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_218('xaxis'), - yAxisMatch: __counterRegex_218('yaxis'), + xAxisMatch: __counterRegex_219('xaxis'), + yAxisMatch: __counterRegex_219('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -16319,6 +16386,7 @@ var _$constants_218 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -16328,7 +16396,7 @@ var _$constants_218 = { } }; -var _$axis_ids_216 = {}; +var _$axis_ids_217 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16339,30 +16407,30 @@ var _$axis_ids_216 = {}; 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -/* removed: var _$constants_218 = require('./constants'); */; +/* removed: var _$constants_219 = require('./constants'); */; // 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. -_$axis_ids_216.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_218.AX_ID_PATTERN)) return; +_$axis_ids_217.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_219.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_216.name2id = function name2id(name) { - if(!name.match(_$constants_218.AX_NAME_PATTERN)) return; +_$axis_ids_217.name2id = function name2id(name) { + if(!name.match(_$constants_219.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_216.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_218.AX_ID_PATTERN)) return; +_$axis_ids_217.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_219.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -16371,11 +16439,11 @@ _$axis_ids_216.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_216.list = function(gd, axLetter, only2d) { +_$axis_ids_217.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_216.listIds(gd, axLetter); + var idList = _$axis_ids_217.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -16400,7 +16468,7 @@ _$axis_ids_216.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_216.listIds = function(gd, axLetter) { +_$axis_ids_217.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -16411,42 +16479,110 @@ _$axis_ids_216.listIds = function(gd, axLetter) { // 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 -_$axis_ids_216.getFromId = function(gd, id, type) { +_$axis_ids_217.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[_$axis_ids_216.id2name(id)]; + return fullLayout[_$axis_ids_217.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_216.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_217.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_261.traceIs(fullTrace, 'gl3d')) { + if(_$registry_262.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_216.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_217.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_216.idSort = function(id1, id2) { +_$axis_ids_217.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); }; -var _$attributes_75 = {}; +var _$client_22 = true; +var _$hasHover_20 = {}; +(function (global){ +'use strict' + +/* removed: var _$client_22 = require('is-browser') */; +var hasHover + +if (typeof global.matchMedia === 'function') { + hasHover = !global.matchMedia('(hover: none)').matches +} +else { + hasHover = _$client_22 +} + +_$hasHover_20 = hasHover + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + +/* removed: var _$client_22 = require('is-browser') */; + +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 +} + +var _$hasPassiveEvents_21 = _$client_22 && detect() + +var rootPosition = { left: 0, top: 0 } + +var _$mouseEventOffset_23 = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16458,17 +16594,25 @@ var _$attributes_75 = {}; 'use strict'; -_$attributes_75.dash = { - valType: 'string', - // string type usually doesn't take values... this one should really be - // a special type or at least a special coercion function, from the GUI - // you only get these values but elsewhere the user can supply a list of - // dash lengths in px, and it will be honored - values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], - dflt: 'solid', - - editType: 'style', - + +// 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 +var _$align_71 = function align(v, dv, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0), + vmax = vmin + dv / (v1 - v0), + 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; }; /** @@ -16479,512 +16623,35 @@ _$attributes_75.dash = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$font_attributes_240 = require('../font_attributes'); */; -/* removed: var _$attributes_50 = require('../../components/color/attributes'); */; -var dash = _$attributes_75.dash; -var __extendFlat_225 = _$extend_165.extendFlat; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$constants_218 = require('./constants'); */; +// 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'] +]; -var _$layout_attributes_225 = { - visible: { - valType: 'boolean', - - editType: 'plot', - - }, - color: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'ticks', - - }, - title: { - valType: 'string', - - editType: 'ticks+margins', - - }, - titlefont: _$font_attributes_240({ - editType: 'ticks+margins', - - }), - type: { - valType: 'enumerated', - // '-' means we haven't yet run autotype or couldn't find any data - // it gets turned into linear in gd._fullLayout but not copied back - // to gd.data like the others are. - values: ['-', 'linear', 'log', 'date', 'category'], - dflt: '-', - - editType: 'calc', - - }, - autorange: { - valType: 'enumerated', - values: [true, false, 'reversed'], - dflt: true, - - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, - - }, - rangemode: { - valType: 'enumerated', - values: ['normal', 'tozero', 'nonnegative'], - dflt: 'normal', - - editType: 'plot', - - }, - range: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} - ], - editType: 'plot+margins', - impliedEdits: {'autorange': false}, - - }, - fixedrange: { - valType: 'boolean', - dflt: false, - - editType: 'calc', - - }, - // scaleanchor: not used directly, just put here for reference - // values are any opposite-letter axis id - scaleanchor: { - valType: 'enumerated', - values: [ - _$constants_218.idRegex.x.toString(), - _$constants_218.idRegex.y.toString() - ], - - editType: 'plot', - - }, - scaleratio: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'plot', - - }, - constrain: { - valType: 'enumerated', - values: ['range', 'domain'], - dflt: 'range', - - editType: 'plot', - - }, - // constraintoward: not used directly, just put here for reference - constraintoward: { - valType: 'enumerated', - values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], - - editType: 'plot', - - }, - // ticks - tickmode: { - valType: 'enumerated', - values: ['auto', 'linear', 'array'], - - editType: 'ticks+margins', - impliedEdits: {tick0: undefined, dtick: undefined}, - - }, - nticks: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'ticks+margins', - - }, - tick0: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - dtick: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - tickvals: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticktext: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticks: { - valType: 'enumerated', - values: ['outside', 'inside', ''], - - editType: 'ticks+margins', - - }, - mirror: { - valType: 'enumerated', - values: [true, 'ticks', false, 'all', 'allticks'], - dflt: false, - - editType: 'ticks+layoutstyle', - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: 5, - - editType: 'ticks', - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - tickcolor: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'ticks', - - }, - showticklabels: { - valType: 'boolean', - dflt: true, - - editType: 'ticks+margins', - - }, - automargin: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - showspikes: { - valType: 'boolean', - dflt: false, - - editType: 'modebar', - - }, - spikecolor: { - valType: 'color', - dflt: null, - - editType: 'none', - - }, - spikethickness: { - valType: 'number', - dflt: 3, - - editType: 'none', - - }, - spikedash: __extendFlat_225({}, dash, {dflt: 'dash', editType: 'none'}), - spikemode: { - valType: 'flaglist', - flags: ['toaxis', 'across', 'marker'], - - dflt: 'toaxis', - editType: 'none', - - }, - spikesnap: { - valType: 'enumerated', - values: ['data', 'cursor'], - dflt: 'data', - - editType: 'none', - - }, - tickfont: _$font_attributes_240({ - editType: 'ticks+margins', - - }), - tickangle: { - valType: 'angle', - dflt: 'auto', - - editType: 'ticks+margins', - - }, - tickprefix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showtickprefix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - ticksuffix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showticksuffix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - showexponent: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - exponentformat: { - valType: 'enumerated', - values: ['none', 'e', 'E', 'power', 'SI', 'B'], - dflt: 'B', - - editType: 'ticks+margins', - - }, - separatethousands: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - tickformat: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - tickformatstops: { - _isLinkedToArray: 'tickformatstop', +var _$getCursor_72 = 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_172.constrain(Math.floor(x * 3), 0, 2); - dtickrange: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'ticks+margins'}, - {valType: 'any', editType: 'ticks+margins'} - ], - editType: 'ticks+margins', - - }, - value: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - editType: 'ticks+margins' - }, - hoverformat: { - valType: 'string', - dflt: '', - - editType: 'none', - - }, - // lines and grids - showline: { - valType: 'boolean', - dflt: false, - - editType: 'layoutstyle', - - }, - linecolor: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'layoutstyle', - - }, - linewidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks+layoutstyle', - - }, - showgrid: { - valType: 'boolean', - - editType: 'ticks', - - }, - gridcolor: { - valType: 'color', - dflt: _$attributes_50.lightLine, - - editType: 'ticks', - - }, - gridwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - zeroline: { - valType: 'boolean', - - editType: 'ticks', - - }, - zerolinecolor: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'ticks', - - }, - zerolinewidth: { - valType: 'number', - dflt: 1, - - editType: 'ticks', - - }, - // positioning attributes - // anchor: not used directly, just put here for reference - // values are any opposite-letter axis id - anchor: { - valType: 'enumerated', - values: [ - 'free', - _$constants_218.idRegex.x.toString(), - _$constants_218.idRegex.y.toString() - ], - - editType: 'plot+margins', - - }, - // side: not used directly, as values depend on direction - // values are top, bottom for x axes, and left, right for y - side: { - valType: 'enumerated', - values: ['top', 'bottom', 'left', 'right'], - - editType: 'plot+margins', - - }, - // overlaying: not used directly, just put here for reference - // values are false and any other same-letter axis id that's not - // itself overlaying anything - overlaying: { - valType: 'enumerated', - values: [ - 'free', - _$constants_218.idRegex.x.toString(), - _$constants_218.idRegex.y.toString() - ], - - editType: 'plot', - - }, - layer: { - valType: 'enumerated', - values: ['above traces', 'below traces'], - dflt: 'above traces', - - editType: 'plot', - - }, - domain: { - valType: 'info_array', - - items: [ - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} - ], - dflt: [0, 1], - editType: 'plot+margins', - - }, - position: { - valType: 'number', - min: 0, - max: 1, - dflt: 0, - - editType: 'plot+margins', - - }, - categoryorder: { - valType: 'enumerated', - values: [ - 'trace', 'category ascending', 'category descending', 'array' - /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later - ], - dflt: 'trace', - - editType: 'calc', - - }, - categoryarray: { - valType: 'data_array', - - editType: 'calc', - - }, - editType: 'calc', + if(yanchor === 'bottom') y = 0; + else if(yanchor === 'middle') y = 1; + else if(yanchor === 'top') y = 2; + else y = _$lib_172.constrain(Math.floor(y * 3), 0, 2); - _deprecated: { - autotick: { - valType: 'boolean', - - editType: 'ticks+margins', - - } - } + return cursorset[y][x]; }; -var _$color_51 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16993,342 +16660,331 @@ var _$color_51 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -var color = _$color_51 = {}; - -/* removed: var _$attributes_50 = require('./attributes'); */; -color.defaults = _$attributes_50.defaults; -var defaultLine = color.defaultLine = _$attributes_50.defaultLine; -color.lightLine = _$attributes_50.lightLine; -var background = color.background = _$attributes_50.background; +var _$constants_88 = { + // hover labels for multiple horizontal bars get tilted by this angle + YANGLE: 60, -/* - * tinyRGB: turn a tinycolor into an rgb string, but - * unlike the built-in tinycolor.toRgbString this never includes alpha - */ -color.tinyRGB = function(tc) { - var c = tc.toRgb(); - return 'rgb(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ')'; -}; + // size and display constants for hover text -color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_33(cstr)); }; + // pixel size of hover arrows + HOVERARROWSIZE: 6, + // pixels padding around text + HOVERTEXTPAD: 3, + // hover font + HOVERFONTSIZE: 13, + HOVERFONT: 'Arial, sans-serif', -color.opacity = function(cstr) { return cstr ? _$tinycolor_33(cstr).getAlpha() : 0; }; + // minimum time (msec) between hover calls + HOVERMINTIME: 50, -color.addOpacity = function(cstr, op) { - var c = _$tinycolor_33(cstr).toRgb(); - return 'rgba(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; + // ID suffix (with fullLayout._uid) for hover events in the throttle cache + HOVERID: '-hover' }; -// combine two colors into one apparent color -// if back has transparency or is missing, -// color.background is assumed behind it -color.combine = function(front, back) { - var fc = _$tinycolor_33(front).toRgb(); - if(fc.a === 1) return _$tinycolor_33(front).toRgbString(); +// 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 bc = _$tinycolor_33(back || background).toRgb(), - bcflat = bc.a === 1 ? bc : { - r: 255 * (1 - bc.a) + bc.r * bc.a, - g: 255 * (1 - bc.a) + bc.g * bc.a, - b: 255 * (1 - bc.a) + bc.b * bc.a - }, - fcflat = { - r: bcflat.r * (1 - fc.a) + fc.r * fc.a, - g: bcflat.g * (1 - fc.a) + fc.g * fc.a, - b: bcflat.b * (1 - fc.a) + fc.b * fc.a - }; - return _$tinycolor_33(fcflat).toRgbString(); -}; +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +var _$EventEmitter_17 = EventEmitter; -/* - * Create a color that contrasts with cstr. - * - * If cstr is a dark color, we lighten it; if it's light, we darken. - * - * If lightAmount / darkAmount are used, we adjust by these percentages, - * otherwise we go all the way to white or black. - */ -color.contrast = function(cstr, lightAmount, darkAmount) { - var tc = _$tinycolor_33(cstr); +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - if(tc.getAlpha() !== 1) tc = _$tinycolor_33(color.combine(cstr, background)); +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - var newColor = tc.isDark() ? - (lightAmount ? tc.lighten(lightAmount) : background) : - (darkAmount ? tc.darken(darkAmount) : defaultLine); +// 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. +EventEmitter.defaultMaxListeners = 10; - return newColor.toString(); +// 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(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; }; -color.stroke = function(s, c) { - var tc = _$tinycolor_33(c); - s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); -}; +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; -color.fill = function(s, c) { - var tc = _$tinycolor_33(c); - s.style({ - 'fill': color.tinyRGB(tc), - 'fill-opacity': tc.getAlpha() - }); -}; + if (!this._events) + this._events = {}; -// search container for colors with the deprecated rgb(fractions) format -// and convert them to rgb(0-255 values) -color.clean = function(container) { - if(!container || typeof container !== 'object') return; + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - var keys = Object.keys(container), - i, - j, - key, - val; + handler = this._events[type]; - for(i = 0; i < keys.length; i++) { - key = keys[i]; - val = container[key]; + if (isUndefined(handler)) + return false; - // only sanitize keys that end in "color" or "colorscale" - if(key.substr(key.length - 5) === 'color') { - if(Array.isArray(val)) { - for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); - } - else container[key] = cleanOne(val); - } - else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { - // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] - for(j = 0; j < val.length; j++) { - if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); - } - } - // recurse into arrays of objects, and plain objects - else if(Array.isArray(val)) { - var el0 = val[0]; - if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { - for(j = 0; j < val.length; j++) color.clean(val[j]); - } - } - else if(val && typeof val === 'object') color.clean(val); + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; }; -function cleanOne(val) { - if(_$fastIsnumeric_18(val) || typeof val !== 'string') return val; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - var valTrim = val.trim(); - if(valTrim.substr(0, 3) !== 'rgb') return val; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); - if(!match) return val; + if (!this._events) + this._events = {}; - var parts = match[1].trim().split(/\s*[\s,]\s*/), - rgba = valTrim.charAt(3) === 'a' && parts.length === 4; - if(!rgba && parts.length !== 3) return val; + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - for(var i = 0; i < parts.length; i++) { - if(!parts[i].length) return val; - parts[i] = Number(parts[i]); + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - // all parts must be non-negative numbers - if(!(parts[i] >= 0)) return val; - // alpha>1 gets clipped to 1 - if(i === 3) { - if(parts[i] > 1) parts[i] = 1; - } - // r, g, b must be < 1 (ie 1 itself is not allowed) - else if(parts[i] >= 1) return val; + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; } - var rgbStr = Math.round(parts[0] * 255) + ', ' + - Math.round(parts[1] * 255) + ', ' + - Math.round(parts[2] * 255); - - if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; - return 'rgb(' + rgbStr + ')'; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + return this; +}; -var _$handleCategoryOrderDefaults_217 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - var arrayIn = containerIn.categoryarray, - orderDefault; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + var fired = false; - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; + function g() { + this.removeListener(type, g); - var order = coerce('categoryorder', orderDefault); + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + g.listener = listener; + this.on(type, g); - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } + return this; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; -'use strict'; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -var colorMix = _$tinycolor_33.mix; -var lightFraction = _$attributes_50.lightFraction; -/* removed: var _$lib_171 = require('../../lib'); */; + if (!this._events || !this._events[type]) + return this; -/** - * @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 - */ -var _$handleLineGridDefaults_227 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; + list = this._events[type]; + length = list.length; + position = -1; - var dfltColor = opts.dfltColor; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - function coerce2(attr, dflt) { - return _$lib_171.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - var lineColor = coerce2('linecolor', dfltColor); - var lineWidth = coerce2('linewidth'); - var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); + if (position < 0) + return this; - if(!showLine) { - delete containerOut.linecolor; - delete containerOut.linewidth; + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } - 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 (this._events.removeListener) + this.emit('removeListener', type, listener); + } - if(!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } + return this; +}; - if(!opts.noZeroLine) { - var zeroLineColor = coerce2('zerolinecolor', dfltColor); - var zeroLineWidth = coerce2('zerolinewidth'); - var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } -}; + if (!this._events) + return this; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_15 = require('d3'); */; - -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { - - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. - - var categoryArray = []; - - var traceLines = data.map(function(d) {return d[axisLetter];}); - - var i, j, tracePoints, category, insertionIndex; - - var bisector = _$d3_15.bisector(sortFunction).left; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - for(i = 0; i < traceLines.length; i++) { + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - tracePoints = traceLines[i]; + listeners = this._events[type]; - for(j = 0; j < tracePoints.length; j++) { + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - category = tracePoints[j]; + return this; +}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - insertionIndex = bisector(categoryArray, category); +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } - } +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; - return categoryArray; +function isFunction(arg) { + return typeof arg === 'function'; } +function isNumber(arg) { + return typeof arg === 'number'; +} -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ - -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_228 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_15.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_15.descending, data); - case 'trace': return []; - default: return []; - } -}; +function isUndefined(arg) { + return arg === void 0; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -17341,593 +16997,507 @@ var _$orderedCategories_228 = function orderedCategories(axisLetter, categoryord 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -/* removed: var _$lib_171 = require('../../lib'); */; -var cleanNumber = _$lib_171.cleanNumber; -var ms2DateTime = _$lib_171.ms2DateTime; -var dateTime2ms = _$lib_171.dateTime2ms; -var ensureNumber = _$lib_171.ensureNumber; +/* global jQuery:false */ -/* removed: var _$numerical_154 = require('../../constants/numerical'); */; -var __FP_SAFE_232 = _$numerical_154.FP_SAFE; -var __BADNUM_232 = _$numerical_154.BADNUM; +var __EventEmitter_165 = _$EventEmitter_17.EventEmitter; -/* removed: var _$constants_218 = require('./constants'); */; -/* removed: var _$axis_ids_216 = require('./axis_ids'); */; +var Events = { -function fromLog(v) { - return Math.pow(10, v); -} + init: function(plotObj) { -/** - * 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 autorange bounds ._min and ._max - * and the autotick constraints ._minDtick, ._forceTick0 - */ -var _$setConvert_232 = function setConvert(ax, fullLayout) { - fullLayout = fullLayout || {}; + /* + * If we have already instantiated an emitter for this plot + * return early. + */ + if(plotObj._ev instanceof __EventEmitter_165) return plotObj; - var axLetter = (ax._id || 'x').charAt(0); + var ev = new __EventEmitter_165(); + var internalEv = new __EventEmitter_165(); - // clipMult: how many axis lengths past the edge do we render? - // for panning, 1-2 would suffice, but for zooming more is nice. - // also, clipping can affect the direction of lines off the edge... - var clipMult = 10; + /* + * Assign to plot._ev while we still live in a land + * where plot is a DOM element with stuff attached to it. + * In the future we can make plot the event emitter itself. + */ + plotObj._ev = ev; - function toLog(v, clip) { - if(v > 0) return Math.log(v) / Math.LN10; + /* + * Create a second event handler that will manage events *internally*. + * This allows parts of plotly to respond to thing like relayout without + * having to use the user-facing event handler. They cannot peacefully + * coexist on the same handler because a user invoking + * plotObj.removeAllListeners() would detach internal events, breaking + * plotly. + */ + plotObj._internalEv = internalEv; - else if(v <= 0 && clip && ax.range && ax.range.length === 2) { - // clip NaN (ie past negative infinity) to clipMult axis - // length past the negative edge - var r0 = ax.range[0], - r1 = ax.range[1]; - return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); - } + /* + * Assign bound methods from the ev to the plot object. These methods + * will reference the 'this' of plot._ev even though they are methods + * of plot. This will keep the event machinery away from the plot object + * which currently is often a DOM element but presents an API that will + * continue to function when plot becomes an emitter. Not all EventEmitter + * methods have been bound to `plot` as some do not currently add value to + * the Plotly event API. + */ + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - else return __BADNUM_232; - } + /* + * Create funtions for managing internal events. These are *only* triggered + * by the mirroring of external events via the emit function. + */ + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); - /* - * 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_232) { - if(_$fastIsnumeric_18(v)) ms = dateTime2ms(new Date(+v)); - else return __BADNUM_232; - } - return ms; - } + /* + * We must wrap emit to continue to support JQuery events. The idea + * is to check to see if the user is using JQuery events, if they are + * we emit JQuery events to trigger user handlers as well as the EventEmitter + * events. + */ + plotObj.emit = function(event, data) { + if(typeof jQuery !== 'undefined') { + jQuery(plotObj).trigger(event, data); + } - // wrapped ms2DateTime to insert default ax.calendar - function ms2dt(v, r, calendar) { - return ms2DateTime(v, r, calendar || ax.calendar); - } + ev.emit(event, data); + internalEv.emit(event, data); + }; - function getCategoryName(v) { - return ax._categories[Math.round(v)]; - } + return plotObj; + }, /* - * 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. + * This function behaves like jQueries triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. * - * 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 + * Note: triggerHandler has been recommended for deprecation in v2.0.0, + * so the additional behavior of triggerHandler triggering internal events + * is deliberate excluded in order to avoid reinforcing more usage. */ - function setCategoryIndex(v) { - if(v !== null && v !== undefined) { - if(ax._categoriesMap === undefined) { - ax._categoriesMap = {}; - } + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + /* + * If Jquery exists run all its handlers for this event and + * collect the return value of the LAST handler function + */ + if(typeof jQuery !== 'undefined') { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } - if(ax._categoriesMap[v] !== undefined) { - return ax._categoriesMap[v]; - } else { - ax._categories.push(v); + /* + * Now run all the node style event handlers + */ + var ev = plotObj._ev; + if(!ev) return jQueryHandlerValue; - var curLength = ax._categories.length - 1; - ax._categoriesMap[v] = curLength; + var handlers = ev._events[event]; + if(!handlers) return jQueryHandlerValue; - return curLength; - } - } - return __BADNUM_232; - } + /* + * handlers can be function or an array of functions + */ + if(typeof handlers === 'function') handlers = [handlers]; + var lastHandler = handlers.pop(); - function getCategoryIndex(v) { - // d2l/d2c variant that that won't add categories but will also - // allow numbers to be mapped to the linearized axis positions - if(ax._categoriesMap) { - var index = ax._categoriesMap[v]; - if(index !== undefined) return index; + /* + * Call all the handlers except the last one. + */ + for(var i = 0; i < handlers.length; i++) { + handlers[i](data); } - if(_$fastIsnumeric_18(v)) return +v; - } - - function l2p(v) { - if(!_$fastIsnumeric_18(v)) return __BADNUM_232; - - // include 2 fractional digits on pixel, for PDF zooming etc - return _$d3_15.round(ax._b + ax._m * v, 2); - } + /* + * Now call the final handler and collect its value + */ + nodeEventHandlerValue = lastHandler(data); - function p2l(px) { return (px - ax._b) / ax._m; } + /* + * Return either the jquery handler value if it exists or the + * nodeEventHandler value. Jquery event value superceeds nodejs + * events for backwards compatability reasons. + */ + return jQueryHandlerValue !== undefined ? jQueryHandlerValue : + nodeEventHandlerValue; + }, - // 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; + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; - ax.l2p = l2p; - ax.p2l = p2l; + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; - 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; + return plotObj; + } - /* - * 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; +var _$Events_165 = Events; - 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)); }; +var _$unhover_74 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ax.d2c = ax.r2l = cleanNumber; - ax.c2d = ax.l2r = ensureNumber; - ax.c2r = toLog; - ax.l2d = fromLog; +'use strict'; - 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; +/* removed: var _$Events_165 = require('../../lib/events'); */; +/* removed: var _$throttle_194 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_170 = require('../../lib/get_graph_div'); */; - ax.cleanPos = ensureNumber; - } - else if(ax.type === 'date') { - // r and d are date strings, l and c are ms +/* removed: var _$constants_88 = require('../fx/constants'); */; - /* - * 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_171.identity; +var unhover = _$unhover_74 = {}; - 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); }; +unhover.wrapped = function(gd, evt, subplot) { + gd = _$get_graph_div_170(gd); - ax.cleanPos = function(v) { return _$lib_171.cleanDate(v, __BADNUM_232, ax.calendar); }; + // Important, clear any queued hovers + if(gd._fullLayout) { + _$throttle_194.clear(gd._fullLayout._uid + _$constants_88.HOVERID); } - 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; + unhover.raw(gd, evt, subplot); +}; - ax.d2r = ax.d2l_noadd = getCategoryIndex; - ax.r2c = function(v) { - var index = getCategoryIndex(v); - return index !== undefined ? index : ax.fraction2r(0.5); - }; +// remove hover effects on mouse out, and emit unhover event +unhover.raw = function unhoverRaw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; - ax.l2r = ax.c2r = ensureNumber; - ax.r2l = getCategoryIndex; + if(!evt) evt = {}; + if(evt.target && + _$Events_165.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - 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; + fullLayout._hoverlayer.selectAll('g').remove(); + fullLayout._hoverlayer.selectAll('line').remove(); + fullLayout._hoverlayer.selectAll('circle').remove(); + gd._hoverdata = undefined; - ax.cleanPos = function(v) { - if(typeof v === 'string' && v !== '') return v; - return ensureNumber(v); - }; + if(evt.target && oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } +}; - // find the range value at the specified (linear) fraction of the axis - ax.fraction2r = function(v) { - var rl0 = ax.r2l(ax.range[0]), - 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]), - rl1 = ax.r2l(ax.range[1]); - return (ax.r2l(v) - rl0) / (rl1 - rl0); - }; +var _$dragelement_73 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* - * 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_171.nestedProperty(ax, rangeAttr).get(); - var i, dflt; +'use strict'; - if(ax.type === 'date') dflt = _$lib_171.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_218.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_218.DFLTRANGEX; +/* removed: var _$mouseEventOffset_23 = require('mouse-event-offset'); */; +/* removed: var _$hasHover_20 = require('has-hover'); */; +/* removed: var _$hasPassiveEvents_21 = require('has-passive-events'); */; - // make sure we don't later mutate the defaults - dflt = dflt.slice(); +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; - if(!range || range.length !== 2) { - _$lib_171.nestedProperty(ax, rangeAttr).set(dflt); - return; - } +/* removed: var _$constants_219 = require('../../plots/cartesian/constants'); */; +/* removed: var _$interactions_153 = require('../../constants/interactions'); */; - if(ax.type === 'date') { - // check if milliseconds or js date objects are provided for range - // and convert to date strings - range[0] = _$lib_171.cleanDate(range[0], __BADNUM_232, ax.calendar); - range[1] = _$lib_171.cleanDate(range[1], __BADNUM_232, ax.calendar); - } +var dragElement = _$dragelement_73 = {}; - for(i = 0; i < 2; i++) { - if(ax.type === 'date') { - if(!_$lib_171.isDateTime(range[i], ax.calendar)) { - ax[rangeAttr] = dflt; - break; - } +dragElement.align = _$align_71; +dragElement.getCursor = _$getCursor_72; - if(ax.r2l(range[0]) === ax.r2l(range[1])) { - // split by +/- 1 second - var linCenter = _$lib_171.constrain(ax.r2l(range[0]), - _$lib_171.MIN_MS + 1000, _$lib_171.MAX_MS - 1000); - range[0] = ax.l2r(linCenter - 1000); - range[1] = ax.l2r(linCenter + 1000); - break; - } - } - else { - if(!_$fastIsnumeric_18(range[i])) { - if(_$fastIsnumeric_18(range[1 - i])) { - range[i] = range[1 - i] * (i ? 10 : 0.1); - } - else { - ax[rangeAttr] = dflt; - break; - } - } +/* removed: var _$unhover_74 = require('./unhover'); */; +dragElement.unhover = _$unhover_74.wrapped; +dragElement.unhoverRaw = _$unhover_74.raw; - if(range[i] < -__FP_SAFE_232) range[i] = -__FP_SAFE_232; - else if(range[i] > __FP_SAFE_232) range[i] = __FP_SAFE_232; - 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; - - // TODO cleaner way to handle this case - if(!ax._categories) ax._categories = []; - // Add a map to optimize the performance of category collection - if(!ax._categoriesMap) ax._categoriesMap = {}; +/** + * 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 DBLCLICKDELAY = _$interactions_153.DBLCLICKDELAY; + var element = options.element; - // make sure we have a domain (pull it in from the axis - // this one is overlaying if necessary) - if(ax.overlaying) { - var ax2 = _$axis_ids_216.getFromId({ _fullLayout: fullLayout }, ax.overlaying); - ax.domain = ax2.domain; - } + var startX, + startY, + newMouseDownTime, + cursor, + dragCover, + initialEvent, + initialTarget, + rightClick; - // 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', - calendar = ax.calendar; - ax.cleanRange(rangeAttr); + if(!gd._mouseDownTime) gd._mouseDownTime = 0; - var rl0 = ax.r2l(ax[rangeAttr][0], calendar), - rl1 = ax.r2l(ax[rangeAttr][1], calendar); + element.style.pointerEvents = 'all'; - 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; - } + element.onmousedown = onStart; - if(!isFinite(ax._m) || !isFinite(ax._b)) { - fullLayout._replotting = false; - throw new Error('Something went wrong with axis scaling'); + if(!_$hasPassiveEvents_21) { + element.ontouchstart = onStart; + } + else { + if(element._ontouchstart) { + element.removeEventListener('touchstart', element._ontouchstart); } - }; + element._ontouchstart = onStart; + element.addEventListener('touchstart', onStart, {passive: false}); + } - // 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; + function _clampFn(dx, dy, minDrag) { + if(Math.abs(dx) < minDrag) dx = 0; + if(Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } - var axType = ax.type; - var cal = axType === 'date' && trace[axLetter + 'calendar']; + var clampFn = options.clampFn || _clampFn; - if(axLetter in trace) { - arrayIn = trace[axLetter]; - len = trace._length || arrayIn.length; + function onStart(e) { + e.preventDefault(); - if(_$lib_171.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { - if(len === arrayIn.length) { - return arrayIn; - } else if(arrayIn.subarray) { - return arrayIn.subarray(0, len); - } - } + // 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; - arrayOut = new Array(len); - for(i = 0; i < len; i++) { - arrayOut[i] = ax.d2c(arrayIn[i], 0, cal); - } + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { + // in a click train + numClicks += 1; } 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; - } + // new click train + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; } - return arrayOut; - }; + if(options.prepFn) options.prepFn(e, startX, startY); - ax.isValidRange = function(range) { - return ( - Array.isArray(range) && - range.length === 2 && - _$fastIsnumeric_18(ax.r2l(range[0])) && - _$fastIsnumeric_18(ax.r2l(range[1])) - ); - }; + if(_$hasHover_20 && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } + else if(!_$hasHover_20) { + // 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; + } - ax.isPtWithinRange = function(d, calendar) { - var coord = ax.c2l(d[axLetter], null, calendar); + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onDone); + document.addEventListener('touchmove', onMove); + document.addEventListener('touchend', onDone); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); - }; + return; + } - ax.clearCalc = function() { - // for autoranging: arrays of objects: - // { - // val: axis value, - // pad: pixel padding, - // extrapad: boolean, should this val get 5% additional padding - // } - ax._min = []; - ax._max = []; + function onMove(e) { + e.preventDefault(); - // initialize the category list, if there is one, so we start over - // to be filled in later by ax.d2c - ax._categories = (ax._initialCategories || []).slice(); + var offset = pointerOffset(e); + var minDrag = options.minDrag || _$constants_219.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; - // Build the lookup map for initialized categories - ax._categoriesMap = {}; - for(var j = 0; j < ax._categories.length; j++) { - ax._categoriesMap[ax._categories[j]] = j; + if(dx || dy) { + gd._dragged = true; + dragElement.unhover(gd); } - }; - // 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_15.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_15.format; + if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); - // and for bar charts and box plots: reset forced minimum tick spacing - delete ax._minDtick; - delete ax._forceTick0; -}; + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function onDone(e) { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onDone); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onDone); + e.preventDefault(); -'use strict'; + if(_$hasHover_20) { + _$lib_172.removeElement(dragCover); + } + else if(cursor) { + dragCover.documentElement.style.cursor = cursor; + cursor = null; + } -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$layout_attributes_225 = require('./layout_attributes'); */; + if(!gd._dragging) { + gd._dragged = false; + return; + } + gd._dragging = false; -var _$handleTickLabelDefaults_233 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { - var showAttrDflt = getShowAttrDflt(containerIn); + // don't count as a dblClick unless the mouseUp is also within + // the dblclick delay + if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - var tickPrefix = coerce('tickprefix'); - if(tickPrefix) coerce('showtickprefix', showAttrDflt); + if(gd._dragged) { + if(options.doneFn) options.doneFn(e); + } + else { + if(options.clickFn) options.clickFn(numClicks, initialEvent); - var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); - if(tickSuffix) coerce('showticksuffix', showAttrDflt); + // 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; - var showTickLabels = coerce('showticklabels'); - if(showTickLabels) { - var font = options.font || {}; - // as with titlefont.color, inherit axis.color only if one was - // explicitly provided - var dfltFontColor = (containerOut.color === containerIn.color) ? - containerOut.color : font.color; - _$lib_171.coerceFont(coerce, 'tickfont', { - family: font.family, - size: font.size, - color: dfltFontColor - }); - coerce('tickangle'); + 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); + } - if(axType !== 'category') { - var tickFormat = coerce('tickformat'); - tickformatstopsDefaults(containerIn, containerOut); - if(!tickFormat && axType !== 'date') { - coerce('showexponent', showAttrDflt); - coerce('exponentformat'); - coerce('separatethousands'); + initialTarget.dispatchEvent(e2); } } - } -}; -/* - * 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'], - showAttrs = showAttrsAll.filter(function(a) { - return containerIn[a] !== undefined; - }), - sameVal = function(a) { - return containerIn[a] === containerIn[showAttrs[0]]; - }; + finishDrag(gd); - if(showAttrs.every(sameVal) || showAttrs.length === 1) { - return containerIn[showAttrs[0]]; + gd._dragged = false; + + return; } -} +}; -function tickformatstopsDefaults(tickformatIn, tickformatOut) { - var valuesIn = tickformatIn.tickformatstops; - var valuesOut = tickformatOut.tickformatstops = []; +function coverSlip() { + var cover = document.createElement('div'); - if(!Array.isArray(valuesIn)) return; + 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'; - var valueIn, valueOut; + document.body.appendChild(cover); - function coerce(attr, dflt) { - return _$lib_171.coerce(valueIn, valueOut, _$layout_attributes_225.tickformatstops, attr, dflt); - } + return cover; +} - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; +dragElement.coverSlip = coverSlip; - coerce('dtickrange'); - coerce('value'); +function finishDrag(gd) { + gd._dragging = false; + if(gd._replotPending) _$registry_262.call('plot', gd); +} - valuesOut.push(valueOut); - } +function pointerOffset(e) { + return _$mouseEventOffset_23( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); } /** @@ -17938,30 +17508,54 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -/* removed: var _$layout_attributes_225 = require('./layout_attributes'); */; +var _$calc_86 = function calc(gd) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; + function makeCoerceHoverInfo(trace) { + return function(val) { + return _$lib_172.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + }; + } -/** - * options: inherits outerTicks from axes.handleAxisDefaults - */ -var _$handleTickDefaults_234 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_171.coerce2(containerIn, containerOut, _$layout_attributes_225, 'ticklen'), - tickWidth = _$lib_171.coerce2(containerIn, containerOut, _$layout_attributes_225, 'tickwidth'), - tickColor = _$lib_171.coerce2(containerIn, containerOut, _$layout_attributes_225, 'tickcolor', containerOut.color), - showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; - if(!showTicks) { - delete containerOut.ticklen; - delete containerOut.tickwidth; - delete containerOut.tickcolor; + // 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_262.traceIs(trace, 'pie')) continue; + + var fillFn = _$registry_262.traceIs(trace, '2dMap') ? paste : _$lib_172.fillArray; + + fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + + 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'); } }; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || _$lib_172.identity; + + if(Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} + +var _$color_51 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17973,178 +17567,164 @@ var _$handleTickDefaults_234 = function handleTickDefaults(containerIn, containe 'use strict'; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -var __ONEDAY_235 = _$numerical_154.ONEDAY; +var color = _$color_51 = {}; -var _$handleTickValueDefaults_235 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { - var tickmodeDefault = 'auto'; +/* removed: var _$attributes_50 = require('./attributes'); */; +color.defaults = _$attributes_50.defaults; +var defaultLine = color.defaultLine = _$attributes_50.defaultLine; +color.lightLine = _$attributes_50.lightLine; +var background = color.background = _$attributes_50.background; - if(containerIn.tickmode === 'array' && - (axType === 'log' || axType === 'date')) { - containerIn.tickmode = 'auto'; - } +/* + * tinyRGB: turn a tinycolor into an rgb string, but + * unlike the built-in tinycolor.toRgbString this never includes alpha + */ +color.tinyRGB = function(tc) { + var c = tc.toRgb(); + return 'rgb(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ')'; +}; - if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; - else if(containerIn.dtick) { - tickmodeDefault = 'linear'; - } - var tickmode = coerce('tickmode', tickmodeDefault); +color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_33(cstr)); }; - if(tickmode === 'auto') coerce('nticks'); - else if(tickmode === 'linear') { - // dtick is usually a positive number, but there are some - // special strings available for log or date axes - // default is 1 day for dates, otherwise 1 - var dtickDflt = (axType === 'date') ? __ONEDAY_235 : 1; - var dtick = coerce('dtick', dtickDflt); - if(_$fastIsnumeric_18(dtick)) { - containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; - } - else if(typeof dtick !== 'string') { - containerOut.dtick = dtickDflt; - } - else { - // date and log special cases are all one character plus a number - var prefix = dtick.charAt(0), - dtickNum = dtick.substr(1); +color.opacity = function(cstr) { return cstr ? _$tinycolor_33(cstr).getAlpha() : 0; }; - dtickNum = _$fastIsnumeric_18(dtickNum) ? Number(dtickNum) : 0; - if((dtickNum <= 0) || !( - // "M" gives ticks every (integer) n months - (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || - // "L" gives ticks linearly spaced in data (not in position) every (float) f - (axType === 'log' && prefix === 'L') || - // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 - (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) - )) { - containerOut.dtick = dtickDflt; - } - } - - // tick0 can have different valType for different axis types, so - // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_171.dateTick0(containerOut.calendar) : 0; - var tick0 = coerce('tick0', tick0Dflt); - if(axType === 'date') { - containerOut.tick0 = _$lib_171.cleanDate(tick0, tick0Dflt); - } - // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely - else if(_$fastIsnumeric_18(tick0) && dtick !== 'D1' && dtick !== 'D2') { - containerOut.tick0 = Number(tick0); - } - else { - containerOut.tick0 = tick0Dflt; - } - } - else { - var tickvals = coerce('tickvals'); - if(tickvals === undefined) containerOut.tickmode = 'auto'; - else coerce('ticktext'); - } +color.addOpacity = function(cstr, op) { + var c = _$tinycolor_33(cstr).toRgb(); + return 'rgba(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +// combine two colors into one apparent color +// if back has transparency or is missing, +// color.background is assumed behind it +color.combine = function(front, back) { + var fc = _$tinycolor_33(front).toRgb(); + if(fc.a === 1) return _$tinycolor_33(front).toRgbString(); -/* removed: var _$layout_attributes_225 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_235 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_234 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_233 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_217 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_227 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_232 = require('./set_convert'); */; -/* removed: var _$orderedCategories_228 = require('./ordered_categories'); */; + var bc = _$tinycolor_33(back || background).toRgb(), + bcflat = bc.a === 1 ? bc : { + r: 255 * (1 - bc.a) + bc.r * bc.a, + g: 255 * (1 - bc.a) + bc.g * bc.a, + b: 255 * (1 - bc.a) + bc.b * bc.a + }, + fcflat = { + r: bcflat.r * (1 - fc.a) + fc.r * fc.a, + g: bcflat.g * (1 - fc.a) + fc.g * fc.a, + b: bcflat.b * (1 - fc.a) + fc.b * fc.a + }; + return _$tinycolor_33(fcflat).toRgbString(); +}; -/** - * options: object containing: +/* + * Create a color that contrasts with cstr. * - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors + * If cstr is a dark color, we lighten it; if it's light, we darken. + * + * If lightAmount / darkAmount are used, we adjust by these percentages, + * otherwise we go all the way to white or black. */ -var _$handleAxisDefaults_215 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; - - var visible = coerce('visible', !options.cheateronly); +color.contrast = function(cstr, lightAmount, darkAmount) { + var tc = _$tinycolor_33(cstr); - var axType = containerOut.type; + if(tc.getAlpha() !== 1) tc = _$tinycolor_33(color.combine(cstr, background)); - if(axType === 'date') { - var handleCalendarDefaults = _$registry_261.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } + var newColor = tc.isDark() ? + (lightAmount ? tc.lighten(lightAmount) : background) : + (darkAmount ? tc.darken(darkAmount) : defaultLine); - _$setConvert_232(containerOut, layoutOut); + return newColor.toString(); +}; - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); +color.stroke = function(s, c) { + var tc = _$tinycolor_33(c); + s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); +}; - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; +color.fill = function(s, c) { + var tc = _$tinycolor_33(c); + s.style({ + 'fill': color.tinyRGB(tc), + 'fill-opacity': tc.getAlpha() + }); +}; - if(autoRange) coerce('rangemode'); +// search container for colors with the deprecated rgb(fractions) format +// and convert them to rgb(0-255 values) +color.clean = function(container) { + if(!container || typeof container !== 'object') return; - coerce('range'); - containerOut.cleanRange(); + var keys = Object.keys(container), + i, + j, + key, + val; - _$handleCategoryOrderDefaults_217(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_228(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + for(i = 0; i < keys.length; i++) { + key = keys[i]; + val = container[key]; + // only sanitize keys that end in "color" or "colorscale" + if(key.substr(key.length - 5) === 'color') { + if(Array.isArray(val)) { + for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); + } + else container[key] = cleanOne(val); + } + else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { + // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] + for(j = 0; j < val.length; j++) { + if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); + } + } + // recurse into arrays of objects, and plain objects + else if(Array.isArray(val)) { + var el0 = val[0]; + if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { + for(j = 0; j < val.length; j++) color.clean(val[j]); + } + } + else if(val && typeof val === 'object') color.clean(val); + } +}; - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); +function cleanOne(val) { + if(_$fastIsnumeric_18(val) || typeof val !== 'string') return val; - if(!visible) return containerOut; + var valTrim = val.trim(); + if(valTrim.substr(0, 3) !== 'rgb') return val; - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); + if(!match) return val; - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_171.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + var parts = match[1].trim().split(/\s*[\s,]\s*/), + rgba = valTrim.charAt(3) === 'a' && parts.length === 4; + if(!rgba && parts.length !== 3) return val; - _$handleTickValueDefaults_235(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_233(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_234(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_227(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_225 - }); + for(var i = 0; i < parts.length; i++) { + if(!parts[i].length) return val; + parts[i] = Number(parts[i]); - if(containerOut.showline || containerOut.ticks) coerce('mirror'); + // all parts must be non-negative numbers + if(!(parts[i] >= 0)) return val; + // alpha>1 gets clipped to 1 + if(i === 3) { + if(parts[i] > 1) parts[i] = 1; + } + // r, g, b must be < 1 (ie 1 itself is not allowed) + else if(parts[i] >= 1) return val; + } - if(options.automargin) coerce('automargin'); + var rgbStr = Math.round(parts[0] * 255) + ', ' + + Math.round(parts[1] * 255) + ', ' + + Math.round(parts[2] * 255); - return containerOut; -}; + if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; + return 'rgb(' + rgbStr + ')'; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -18154,150 +17734,87 @@ var _$handleAxisDefaults_215 = function handleAxisDefaults(containerIn, containe * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -var id2name = _$axis_ids_216.id2name; - - -var _$handleConstraintDefaults_219 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); - - if(containerOut.fixedrange) return; - - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_171.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); - - if(!containerIn.scaleanchor) return; - - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - - var scaleanchor = _$lib_171.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); - - 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, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_171.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.'); +var _$attributes_57 = { + zauto: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + impliedEdits: {zmin: undefined, zmax: undefined}, + + }, + zmin: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + zmax: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + colorscale: { + valType: 'colorscale', + + editType: 'calc', + impliedEdits: {autocolorscale: false}, + + }, + autocolorscale: { + valType: 'boolean', + + dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. + editType: 'calc', + impliedEdits: {colorscale: undefined}, + + }, + reversescale: { + valType: 'boolean', + + dflt: false, + editType: 'calc', + + }, + showscale: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + } }; -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. - - 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 && !axj.fixedrange) linkableAxes.push(idj); - } - - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[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}; -} - +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * 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); - } +'use strict'; - var thisGroupKeys = Object.keys(thisGroup); +var _$flipScale_63 = function flipScale(scl) { + var N = scl.length, + sclNew = new Array(N), + si; - // 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; - } + for(var i = N - 1, j = 0; i >= 0; i--, j++) { + si = scl[i]; + sclNew[j] = [1 - si[0], si[1]]; } - // 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; -} + return sclNew; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -18310,76 +17827,71 @@ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor 'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$scales_70 = require('./scales'); */; +/* removed: var _$flipScale_63 = require('./flip_scale'); */; -var _$handlePositionDefaults_229 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; +var _$calc_58 = function calc(trace, vals, containerStr, cLetter) { + var container, inputContainer; - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } + if(containerStr) { + container = _$lib_172.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_172.nestedProperty(trace._input, containerStr).get(); + } + else { + container = trace; + inputContainer = trace._input; } - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_18(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; - - var anchor = _$lib_171.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); - - if(anchor === 'free') coerce('position', dfltPosition); + var autoAttr = cLetter + 'auto', + minAttr = cLetter + 'min', + maxAttr = cLetter + 'max', + auto = container[autoAttr], + min = container[minAttr], + max = container[maxAttr], + scl = container.colorscale; - _$lib_171.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); + if(auto !== false || min === undefined) { + min = _$lib_172.aggNums(Math.min, null, vals); + } - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_171.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); + if(auto !== false || max === undefined) { + max = _$lib_172.aggNums(Math.max, null, vals); } - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_171.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + if(min === max) { + min -= 0.5; + max += 0.5; } - coerce('layer'); + container[minAttr] = min; + container[maxAttr] = max; - return containerOut; + inputContainer[minAttr] = min; + inputContainer[maxAttr] = max; + + /* + * If auto was explicitly false but min or max was missing, + * we filled in the missing piece here but later the trace does + * not look auto. + * Otherwise make sure the trace still looks auto as far as later + * changes are concerned. + */ + inputContainer[autoAttr] = (auto !== false || + (min === undefined && max === undefined)); + + if(container.autocolorscale) { + if(min * max < 0) scl = _$scales_70.RdBu; + else if(min >= 0) scl = _$scales_70.Reds; + else scl = _$scales_70.Blues; + + // reversescale is handled at the containerOut level + inputContainer.colorscale = scl; + if(container.reversescale) scl = _$flipScale_63(scl); + container.colorscale = scl; + } }; /** @@ -18390,199 +17902,124 @@ var _$handlePositionDefaults_229 = function handlePositionDefaults(containerIn, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -/* removed: var _$lib_171 = require('../../lib'); */; -var __BADNUM_214 = _$numerical_154.BADNUM; +/* removed: var _$lib_172 = require('../lib'); */; +var __extendFlat_199 = _$lib_172.extendFlat; +var __isPlainObject_199 = _$lib_172.isPlainObject; -var _$autoType_214 = function autoType(array, calendar) { - if(moreDates(array, calendar)) return 'date'; - if(category(array)) return 'category'; - if(linearOK(array)) return 'linear'; - else return '-'; +var traceOpts = { + valType: 'flaglist', + extras: ['none'], + flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'], + }; -// is there at least one number in array? If not, we should leave -// ax.type empty so it can be autoset later -function linearOK(array) { - if(!array) return false; - - for(var i = 0; i < array.length; i++) { - if(_$fastIsnumeric_18(array[i])) return true; - } +var layoutOpts = { + valType: 'flaglist', + extras: ['none'], + flags: [ + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', + 'layoutstyle', 'modebar', 'camera', 'arraydraw' + ], + +}; - return false; -} +// flags for inside restyle/relayout include a few extras +// that shouldn't be used in attributes, to deal with certain +// combinations and conditionals efficiently +var traceEditTypeFlags = traceOpts.flags.slice() + .concat(['clearCalc', 'fullReplot']); -// does the array a have mostly dates rather than numbers? -// note: some values can be neither (such as blanks, text) -// 2- or 4-digit integers can be both, so require twice as many -// dates as non-dates, to exclude cases with mostly 2 & 4 digit -// numbers and a few dates -function moreDates(a, calendar) { - var dcnt = 0, - ncnt = 0, - // test at most 1000 points, evenly spaced - inc = Math.max(1, (a.length - 1) / 1000), - ai; +var layoutEditTypeFlags = layoutOpts.flags.slice() + .concat('layoutReplot'); - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_171.isDateTime(ai, calendar)) dcnt += 1; - if(_$fastIsnumeric_18(ai)) ncnt += 1; - } +var _$edit_types_199 = { + traces: traceOpts, + layout: layoutOpts, + /* + * default (all false) edit flags for restyle (traces) + * creates a new object each call, so the caller can mutate freely + */ + traceFlags: function() { return falseObj(traceEditTypeFlags); }, - return (dcnt > ncnt * 2); -} + /* + * default (all false) edit flags for relayout + * creates a new object each call, so the caller can mutate freely + */ + layoutFlags: function() { return falseObj(layoutEditTypeFlags); }, -// are the (x,y)-values in gd.data mostly text? -// require twice as many categories as numbers -function category(a) { - // test at most 1000 points - var inc = Math.max(1, (a.length - 1) / 1000), - curvenums = 0, - curvecats = 0, - ai; + /* + * update `flags` with the `editType` values found in `attr` + */ + update: function(flags, attr) { + var editType = attr.editType; + if(editType && editType !== 'none') { + var editTypeParts = editType.split('+'); + for(var i = 0; i < editTypeParts.length; i++) { + flags[editTypeParts[i]] = true; + } + } + }, - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_171.cleanNumber(ai) !== __BADNUM_214) curvenums++; - else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; - } + overrideAll: overrideAll +}; - return curvecats > curvenums * 2; +function falseObj(keys) { + var out = {}; + for(var i = 0; i < keys.length; i++) out[keys[i]] = false; + return out; } /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$autoType_214 = require('./axis_autotype'); */; -var name2id = _$axis_ids_216.name2id; - -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored + * For attributes that are largely copied from elsewhere into a plot type that doesn't + * support partial redraws - overrides the editType field of all attributes in the object + * + * @param {object} attrs: the attributes to override. Will not be mutated. + * @param {string} editTypeOverride: the new editType to use + * @param {'nested'|'from-root'} overrideContainers: + * - 'nested' will override editType for nested containers but not the root. + * - 'from-root' will also override editType of the root container. + * Containers below the absolute top level (trace or layout root) DO need an + * editType even if they are not `valObject`s themselves (eg `scatter.marker`) + * to handle the case where you edit the whole container. + * + * @return {object} a new attributes object with `editType` modified as directed */ -var _$handleTypeDefaults_237 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } - - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; +function overrideAll(attrs, editTypeOverride, overrideContainers) { + var out = __extendFlat_199({}, attrs); + for(var key in out) { + var attr = out[key]; + if(__isPlainObject_199(attr)) { + out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } -}; - -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; - - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } - - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; - - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; - - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_261.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; - - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); - - if(trace[calAttr] !== calendar) calendar = undefined; - } + if(overrideContainers === 'from-root') out.editType = editTypeOverride; - ax.type = _$autoType_214(boxPositions, calendar); - } - else { - ax.type = _$autoType_214(d0[axLetter] || [d0[axLetter + '0']], calendar); - } + return out; } -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; +function overrideOne(attr, editTypeOverride, overrideContainers, key) { + if(attr.valType) { + var out = __extendFlat_199({}, attr); + out.editType = editTypeOverride; - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; + if(Array.isArray(attr.items)) { + out.items = new Array(attr.items.length); + for(var i = 0; i < attr.items.length; i++) { + out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root'); } } + return out; + } + else { + // don't provide an editType for the _deprecated container + return overrideAll(attr, editTypeOverride, + (key.charAt(0) === '_') ? 'nested' : 'from-root'); } } -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_261.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_261.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} - +var _$attributes_75 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18594,226 +18031,17 @@ function isBoxWithoutPositionCoords(trace, axLetter) { 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$layout_attributes_244 = require('../layout_attributes'); */; - -/* removed: var _$layout_attributes_225 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_237 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_215 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_219 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_229 = require('./position_defaults'); */; -/* removed: var _$axis_ids_216 = require('./axis_ids'); */; - - -var _$supplyLayoutDefaults_226 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; - - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - - if(!_$registry_261.traceIs(trace, 'cartesian') && !_$registry_261.traceIs(trace, 'gl2d')) { - continue; - } - - var xaName = _$axis_ids_216.id2name(trace.xaxis); - var yaName = _$axis_ids_216.id2name(trace.yaxis); - - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_261.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } - - // 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) xaCheater[xaName] = 1; - } - - // check for default formatting tweaks - if(_$registry_261.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } - - if(_$registry_261.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_171.simpleMap(xIds, _$axis_ids_216.id2name); - var yNames = _$lib_171.simpleMap(yIds, _$axis_ids_216.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 plot_bgcolor = _$color_51.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_244, 'plot_bgcolor'); - } - - var bgColor = _$color_51.combine(plot_bgcolor, layoutOut.paper_bgcolor); - - var axName, axLetter, axLayoutIn, axLayoutOut; - - function coerce(attr, dflt) { - return _$lib_171.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_225, attr, dflt); - } - - function coerce2(attr, dflt) { - return _$lib_171.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_225, attr, dflt); - } - - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; - } - - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('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(_$axis_ids_216.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]; - - if(!_$lib_171.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; - - _$handleTypeDefaults_237(axLayoutIn, axLayoutOut, coerce, fullData, axName); - - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); - - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; - - _$handleAxisDefaults_215(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; - } - - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; - - _$handlePositionDefaults_229(axLayoutIn, axLayoutOut, coerce, positioningOptions); - - axLayoutOut._input = axLayoutIn; - } - - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_261.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_261.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[_$axis_ids_216.id2name(axLayoutOut.anchor)]; - - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); - - coerce('fixedrange', fixedRangeDflt); - } - - // Finally, handle scale constraints. 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 - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); - - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; - - _$handleConstraintDefaults_219(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } +_$attributes_75.dash = { + valType: 'string', + // string type usually doesn't take values... this one should really be + // a special type or at least a special coercion function, from the GUI + // you only get these values but elsewhere the user can supply a list of + // dash lengths in px, and it will be honored + values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], + dflt: 'solid', + + editType: 'style', + }; /** @@ -18826,509 +18054,507 @@ var _$supplyLayoutDefaults_226 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -var _$attributes_57 = { - zauto: { +/* removed: var _$font_attributes_240 = require('../font_attributes'); */; +/* removed: var _$attributes_50 = require('../../components/color/attributes'); */; +var dash = _$attributes_75.dash; +var __extendFlat_226 = _$extend_166.extendFlat; + +/* removed: var _$constants_219 = require('./constants'); */; + + +var _$layout_attributes_226 = { + visible: { valType: 'boolean', - dflt: true, - editType: 'calc', - impliedEdits: {zmin: undefined, zmax: undefined}, + editType: 'plot', }, - zmin: { - valType: 'number', + color: { + valType: 'color', + dflt: _$attributes_50.defaultLine, - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks', }, - zmax: { - valType: 'number', + title: { + valType: 'string', - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks+margins', }, - colorscale: { - valType: 'colorscale', + titlefont: _$font_attributes_240({ + editType: 'ticks+margins', + + }), + type: { + valType: 'enumerated', + // '-' means we haven't yet run autotype or couldn't find any data + // it gets turned into linear in gd._fullLayout but not copied back + // to gd.data like the others are. + values: ['-', 'linear', 'log', 'date', 'category'], + dflt: '-', editType: 'calc', - impliedEdits: {autocolorscale: false}, }, - autocolorscale: { - valType: 'boolean', + autorange: { + valType: 'enumerated', + values: [true, false, 'reversed'], + dflt: true, - dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. editType: 'calc', - impliedEdits: {colorscale: undefined}, + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - reversescale: { - valType: 'boolean', + rangemode: { + valType: 'enumerated', + values: ['normal', 'tozero', 'nonnegative'], + dflt: 'normal', - dflt: false, - editType: 'calc', + editType: 'plot', }, - showscale: { + range: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} + ], + editType: 'axrange+margins', + impliedEdits: {'autorange': false}, + + }, + fixedrange: { valType: 'boolean', + dflt: false, - dflt: true, editType: 'calc', - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var _$flipScale_63 = function flipScale(scl) { - var N = scl.length, - sclNew = new Array(N), - si; - - for(var i = N - 1, j = 0; i >= 0; i--, j++) { - si = scl[i]; - sclNew[j] = [1 - si[0], si[1]]; - } - - return sclNew; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_171 = require('../../lib'); */; - -/* removed: var _$scales_70 = require('./scales'); */; -/* removed: var _$flipScale_63 = require('./flip_scale'); */; - - -var _$calc_58 = function calc(trace, vals, containerStr, cLetter) { - var container, inputContainer; - - if(containerStr) { - container = _$lib_171.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_171.nestedProperty(trace._input, containerStr).get(); - } - else { - container = trace; - inputContainer = trace._input; - } - - var autoAttr = cLetter + 'auto', - minAttr = cLetter + 'min', - maxAttr = cLetter + 'max', - auto = container[autoAttr], - min = container[minAttr], - max = container[maxAttr], - scl = container.colorscale; - - if(auto !== false || min === undefined) { - min = _$lib_171.aggNums(Math.min, null, vals); - } - - if(auto !== false || max === undefined) { - max = _$lib_171.aggNums(Math.max, null, vals); - } - - if(min === max) { - min -= 0.5; - max += 0.5; - } - - container[minAttr] = min; - container[maxAttr] = max; - - inputContainer[minAttr] = min; - inputContainer[maxAttr] = max; - - /* - * If auto was explicitly false but min or max was missing, - * we filled in the missing piece here but later the trace does - * not look auto. - * Otherwise make sure the trace still looks auto as far as later - * changes are concerned. - */ - inputContainer[autoAttr] = (auto !== false || - (min === undefined && max === undefined)); - - if(container.autocolorscale) { - if(min * max < 0) scl = _$scales_70.RdBu; - else if(min >= 0) scl = _$scales_70.Reds; - else scl = _$scales_70.Blues; - - // reversescale is handled at the containerOut level - inputContainer.colorscale = scl; - if(container.reversescale) scl = _$flipScale_63(scl); - container.colorscale = scl; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_171 = require('../lib'); */; -var __extendFlat_198 = _$lib_171.extendFlat; -var __isPlainObject_198 = _$lib_171.isPlainObject; - -var traceOpts = { - valType: 'flaglist', - extras: ['none'], - flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'], - -}; - -var layoutOpts = { - valType: 'flaglist', - extras: ['none'], - flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', - 'layoutstyle', 'modebar', 'camera', 'arraydraw' - ], - -}; - -// flags for inside restyle/relayout include a few extras -// that shouldn't be used in attributes, to deal with certain -// combinations and conditionals efficiently -var traceEditTypeFlags = traceOpts.flags.slice() - .concat(['clearCalc', 'fullReplot']); - -var layoutEditTypeFlags = layoutOpts.flags.slice() - .concat('layoutReplot'); - -var _$edit_types_198 = { - traces: traceOpts, - layout: layoutOpts, - /* - * default (all false) edit flags for restyle (traces) - * creates a new object each call, so the caller can mutate freely - */ - traceFlags: function() { return falseObj(traceEditTypeFlags); }, - - /* - * default (all false) edit flags for relayout - * creates a new object each call, so the caller can mutate freely - */ - layoutFlags: function() { return falseObj(layoutEditTypeFlags); }, - - /* - * update `flags` with the `editType` values found in `attr` - */ - update: function(flags, attr) { - var editType = attr.editType; - if(editType && editType !== 'none') { - var editTypeParts = editType.split('+'); - for(var i = 0; i < editTypeParts.length; i++) { - flags[editTypeParts[i]] = true; - } - } }, - - overrideAll: overrideAll -}; - -function falseObj(keys) { - var out = {}; - for(var i = 0; i < keys.length; i++) out[keys[i]] = false; - return out; -} - -/** - * For attributes that are largely copied from elsewhere into a plot type that doesn't - * support partial redraws - overrides the editType field of all attributes in the object - * - * @param {object} attrs: the attributes to override. Will not be mutated. - * @param {string} editTypeOverride: the new editType to use - * @param {'nested'|'from-root'} overrideContainers: - * - 'nested' will override editType for nested containers but not the root. - * - 'from-root' will also override editType of the root container. - * Containers below the absolute top level (trace or layout root) DO need an - * editType even if they are not `valObject`s themselves (eg `scatter.marker`) - * to handle the case where you edit the whole container. - * - * @return {object} a new attributes object with `editType` modified as directed - */ -function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_198({}, attrs); - for(var key in out) { - var attr = out[key]; - if(__isPlainObject_198(attr)) { - out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); - } - } - if(overrideContainers === 'from-root') out.editType = editTypeOverride; - - return out; -} - -function overrideOne(attr, editTypeOverride, overrideContainers, key) { - if(attr.valType) { - var out = __extendFlat_198({}, attr); - out.editType = editTypeOverride; - - if(Array.isArray(attr.items)) { - out.items = new Array(attr.items.length); - for(var i = 0; i < attr.items.length; i++) { - out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root'); - } - } - return out; - } - else { - // don't provide an editType for the _deprecated container - return overrideAll(attr, editTypeOverride, - (key.charAt(0) === '_') ? 'nested' : 'from-root'); - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$layout_attributes_225 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -var __extendFlat_52 = _$extend_165.extendFlat; -var __overrideAll_52 = _$edit_types_198.overrideAll; - - -var _$attributes_52 = __overrideAll_52({ -// TODO: only right is supported currently -// orient: { -// valType: 'enumerated', -// -// values: ['left', 'right', 'top', 'bottom'], -// dflt: 'right', -// -// }, - thicknessmode: { + // scaleanchor: not used directly, just put here for reference + // values are any opposite-letter axis id + scaleanchor: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: [ + _$constants_219.idRegex.x.toString(), + _$constants_219.idRegex.y.toString() + ], - dflt: 'pixels', + editType: 'plot', }, - thickness: { + scaleratio: { valType: 'number', - min: 0, - dflt: 30, + dflt: 1, + + editType: 'plot', }, - lenmode: { + constrain: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: ['range', 'domain'], + dflt: 'range', - dflt: 'fraction', + editType: 'plot', }, - len: { - valType: 'number', + // constraintoward: not used directly, just put here for reference + constraintoward: { + valType: 'enumerated', + values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], + + editType: 'plot', + + }, + // ticks + tickmode: { + valType: 'enumerated', + values: ['auto', 'linear', 'array'], + + editType: 'ticks+margins', + impliedEdits: {tick0: undefined, dtick: undefined}, + + }, + nticks: { + valType: 'integer', min: 0, - dflt: 1, + dflt: 0, + editType: 'ticks+margins', }, - x: { - valType: 'number', - dflt: 1.02, - min: -2, - max: 3, + tick0: { + valType: 'any', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', + dtick: { + valType: 'any', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - xpad: { - valType: 'number', + tickvals: { + valType: 'data_array', + editType: 'ticks+margins', - min: 0, - dflt: 10, + }, + ticktext: { + valType: 'data_array', + editType: 'ticks+margins', }, - y: { - valType: 'number', + ticks: { + valType: 'enumerated', + values: ['outside', 'inside', ''], - dflt: 0.5, - min: -2, - max: 3, + editType: 'ticks+margins', }, - yanchor: { + mirror: { valType: 'enumerated', - values: ['top', 'middle', 'bottom'], + values: [true, 'ticks', false, 'all', 'allticks'], + dflt: false, - dflt: 'middle', + editType: 'ticks+layoutstyle', }, - ypad: { + ticklen: { valType: 'number', - min: 0, - dflt: 10, + dflt: 5, + + editType: 'ticks', }, - // a possible line around the bar itself - outlinecolor: _$layout_attributes_225.linecolor, - outlinewidth: _$layout_attributes_225.linewidth, - // Should outlinewidth have {dflt: 0} ? - // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_225.linecolor, - borderwidth: { + tickwidth: { valType: 'number', - min: 0, - dflt: 0, + dflt: 1, + + editType: 'ticks', }, - bgcolor: { + tickcolor: { valType: 'color', + dflt: _$attributes_50.defaultLine, - dflt: 'rgba(0,0,0,0)', + editType: 'ticks', + + }, + showticklabels: { + valType: 'boolean', + dflt: true, + + editType: 'ticks+margins', + + }, + automargin: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + showspikes: { + valType: 'boolean', + dflt: false, + + editType: 'modebar', + + }, + spikecolor: { + valType: 'color', + dflt: null, + + editType: 'none', + + }, + spikethickness: { + valType: 'number', + dflt: 3, + + editType: 'none', + + }, + spikedash: __extendFlat_226({}, dash, {dflt: 'dash', editType: 'none'}), + spikemode: { + valType: 'flaglist', + flags: ['toaxis', 'across', 'marker'], + + dflt: 'toaxis', + editType: 'none', + + }, + spikesnap: { + valType: 'enumerated', + values: ['data', 'cursor'], + dflt: 'data', + + editType: 'none', }, - // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_225.tickmode, - nticks: _$layout_attributes_225.nticks, - tick0: _$layout_attributes_225.tick0, - dtick: _$layout_attributes_225.dtick, - tickvals: _$layout_attributes_225.tickvals, - ticktext: _$layout_attributes_225.ticktext, - ticks: __extendFlat_52({}, _$layout_attributes_225.ticks, {dflt: ''}), - ticklen: _$layout_attributes_225.ticklen, - tickwidth: _$layout_attributes_225.tickwidth, - tickcolor: _$layout_attributes_225.tickcolor, - showticklabels: _$layout_attributes_225.showticklabels, tickfont: _$font_attributes_240({ + editType: 'ticks+margins', }), - tickangle: _$layout_attributes_225.tickangle, - tickformat: _$layout_attributes_225.tickformat, - tickformatstops: _$layout_attributes_225.tickformatstops, - tickprefix: _$layout_attributes_225.tickprefix, - showtickprefix: _$layout_attributes_225.showtickprefix, - ticksuffix: _$layout_attributes_225.ticksuffix, - showticksuffix: _$layout_attributes_225.showticksuffix, - separatethousands: _$layout_attributes_225.separatethousands, - exponentformat: _$layout_attributes_225.exponentformat, - showexponent: _$layout_attributes_225.showexponent, - title: { + tickangle: { + valType: 'angle', + dflt: 'auto', + + editType: 'ticks+margins', + + }, + tickprefix: { valType: 'string', + dflt: '', + editType: 'ticks+margins', }, - titlefont: _$font_attributes_240({ + showtickprefix: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - }), - titleside: { + editType: 'ticks+margins', + + }, + ticksuffix: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + showticksuffix: { valType: 'enumerated', - values: ['right', 'top', 'bottom'], + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - dflt: 'top', + editType: 'ticks+margins', - } -}, 'colorbars', 'from-root'); - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_235 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_234 = require('../../plots/cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_233 = require('../../plots/cartesian/tick_label_defaults'); */; - -/* removed: var _$attributes_52 = require('./attributes'); */; - - -var _$colorbarDefaults_54 = function colorbarDefaults(containerIn, containerOut, layout) { - var colorbarOut = containerOut.colorbar = {}, - colorbarIn = containerIn.colorbar || {}; - - function coerce(attr, dflt) { - return _$lib_171.coerce(colorbarIn, colorbarOut, _$attributes_52, attr, dflt); - } - - var thicknessmode = coerce('thicknessmode'); - coerce('thickness', (thicknessmode === 'fraction') ? - 30 / (layout.width - layout.margin.l - layout.margin.r) : - 30 - ); - - var lenmode = coerce('lenmode'); - coerce('len', (lenmode === 'fraction') ? - 1 : - layout.height - layout.margin.t - layout.margin.b - ); - - coerce('x'); - coerce('xanchor'); - coerce('xpad'); - coerce('y'); - coerce('yanchor'); - coerce('ypad'); - _$lib_171.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); - - coerce('outlinecolor'); - coerce('outlinewidth'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('bgcolor'); - - _$handleTickValueDefaults_235(colorbarIn, colorbarOut, coerce, 'linear'); - - var opts = {outerTicks: false, font: layout.font}; - _$handleTickLabelDefaults_233(colorbarIn, colorbarOut, coerce, 'linear', opts); - _$handleTickDefaults_234(colorbarIn, colorbarOut, coerce, 'linear', opts); + }, + showexponent: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', + + editType: 'ticks+margins', + + }, + exponentformat: { + valType: 'enumerated', + values: ['none', 'e', 'E', 'power', 'SI', 'B'], + dflt: 'B', + + editType: 'ticks+margins', + + }, + separatethousands: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + tickformat: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + tickformatstops: { + _isLinkedToArray: 'tickformatstop', - coerce('title', layout._dfltTitle.colorbar); - _$lib_171.coerceFont(coerce, 'titlefont', layout.font); - coerce('titleside'); + dtickrange: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'ticks+margins'}, + {valType: 'any', editType: 'ticks+margins'} + ], + editType: 'ticks+margins', + + }, + value: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + editType: 'ticks+margins' + }, + hoverformat: { + valType: 'string', + dflt: '', + + editType: 'none', + + }, + // lines and grids + showline: { + valType: 'boolean', + dflt: false, + + editType: 'layoutstyle', + + }, + linecolor: { + valType: 'color', + dflt: _$attributes_50.defaultLine, + + editType: 'layoutstyle', + + }, + linewidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks+layoutstyle', + + }, + showgrid: { + valType: 'boolean', + + editType: 'ticks', + + }, + gridcolor: { + valType: 'color', + dflt: _$attributes_50.lightLine, + + editType: 'ticks', + + }, + gridwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks', + + }, + zeroline: { + valType: 'boolean', + + editType: 'ticks', + + }, + zerolinecolor: { + valType: 'color', + dflt: _$attributes_50.defaultLine, + + editType: 'ticks', + + }, + zerolinewidth: { + valType: 'number', + dflt: 1, + + editType: 'ticks', + + }, + // positioning attributes + // anchor: not used directly, just put here for reference + // values are any opposite-letter axis id + anchor: { + valType: 'enumerated', + values: [ + 'free', + _$constants_219.idRegex.x.toString(), + _$constants_219.idRegex.y.toString() + ], + + editType: 'plot+margins', + + }, + // side: not used directly, as values depend on direction + // values are top, bottom for x axes, and left, right for y + side: { + valType: 'enumerated', + values: ['top', 'bottom', 'left', 'right'], + + editType: 'plot+margins', + + }, + // overlaying: not used directly, just put here for reference + // values are false and any other same-letter axis id that's not + // itself overlaying anything + overlaying: { + valType: 'enumerated', + values: [ + 'free', + _$constants_219.idRegex.x.toString(), + _$constants_219.idRegex.y.toString() + ], + + editType: 'plot', + + }, + layer: { + valType: 'enumerated', + values: ['above traces', 'below traces'], + dflt: 'above traces', + + editType: 'plot', + + }, + domain: { + valType: 'info_array', + + items: [ + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} + ], + dflt: [0, 1], + editType: 'plot+margins', + + }, + position: { + valType: 'number', + min: 0, + max: 1, + dflt: 0, + + editType: 'plot+margins', + + }, + categoryorder: { + valType: 'enumerated', + values: [ + 'trace', 'category ascending', 'category descending', 'array' + /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later + ], + dflt: 'trace', + + editType: 'calc', + + }, + categoryarray: { + valType: 'data_array', + + editType: 'calc', + + }, + editType: 'calc', + + _deprecated: { + autotick: { + valType: 'boolean', + + editType: 'ticks+margins', + + } + } }; /** @@ -19339,15 +18565,155 @@ var _$colorbarDefaults_54 = function colorbarDefaults(containerIn, containerOut, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$layout_attributes_226 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +var __extendFlat_52 = _$extend_166.extendFlat; +var __overrideAll_52 = _$edit_types_199.overrideAll; -var _$hasColorbar_56 = function hasColorbar(container) { - return _$lib_171.isPlainObject(container.colorbar); -}; +var _$attributes_52 = __overrideAll_52({ +// 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: _$layout_attributes_226.linecolor, + outlinewidth: _$layout_attributes_226.linewidth, + // Should outlinewidth have {dflt: 0} ? + // another possible line outside the padding and tick labels + bordercolor: _$layout_attributes_226.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: _$layout_attributes_226.tickmode, + nticks: _$layout_attributes_226.nticks, + tick0: _$layout_attributes_226.tick0, + dtick: _$layout_attributes_226.dtick, + tickvals: _$layout_attributes_226.tickvals, + ticktext: _$layout_attributes_226.ticktext, + ticks: __extendFlat_52({}, _$layout_attributes_226.ticks, {dflt: ''}), + ticklen: _$layout_attributes_226.ticklen, + tickwidth: _$layout_attributes_226.tickwidth, + tickcolor: _$layout_attributes_226.tickcolor, + showticklabels: _$layout_attributes_226.showticklabels, + tickfont: _$font_attributes_240({ + + }), + tickangle: _$layout_attributes_226.tickangle, + tickformat: _$layout_attributes_226.tickformat, + tickformatstops: _$layout_attributes_226.tickformatstops, + tickprefix: _$layout_attributes_226.tickprefix, + showtickprefix: _$layout_attributes_226.showtickprefix, + ticksuffix: _$layout_attributes_226.ticksuffix, + showticksuffix: _$layout_attributes_226.showticksuffix, + separatethousands: _$layout_attributes_226.separatethousands, + exponentformat: _$layout_attributes_226.exponentformat, + showexponent: _$layout_attributes_226.showexponent, + title: { + valType: 'string', + + + }, + titlefont: _$font_attributes_240({ + + }), + titleside: { + valType: 'enumerated', + values: ['right', 'top', 'bottom'], + + dflt: 'top', + + } +}, 'colorbars', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -19360,77 +18726,96 @@ var _$hasColorbar_56 = function hasColorbar(container) { 'use strict'; -/* removed: var _$scales_70 = require('./scales'); */; -/* removed: var _$isValidScaleArray_68 = require('./is_valid_scale_array'); */; - +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$layout_attributes_226 = require('./layout_attributes'); */; -var _$isValidScale_67 = function isValidScale(scl) { - if(_$scales_70[scl] !== undefined) return true; - else return _$isValidScaleArray_68(scl); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$handleTickLabelDefaults_233 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { + var showAttrDflt = getShowAttrDflt(containerIn); + var tickPrefix = coerce('tickprefix'); + if(tickPrefix) coerce('showtickprefix', showAttrDflt); -'use strict'; + var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); + if(tickSuffix) coerce('showticksuffix', showAttrDflt); -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + var showTickLabels = coerce('showticklabels'); + if(showTickLabels) { + var font = options.font || {}; + // as with titlefont.color, inherit axis.color only if one was + // explicitly provided + var dfltFontColor = (containerOut.color === containerIn.color) ? + containerOut.color : font.color; + _$lib_172.coerceFont(coerce, 'tickfont', { + family: font.family, + size: font.size, + color: dfltFontColor + }); + coerce('tickangle'); -/* removed: var _$lib_171 = require('../../lib'); */; + if(axType !== 'category') { + var tickFormat = coerce('tickformat'); + tickformatstopsDefaults(containerIn, containerOut); + if(!tickFormat && axType !== 'date') { + coerce('showexponent', showAttrDflt); + coerce('exponentformat'); + coerce('separatethousands'); + } + } + } +}; -/* removed: var _$hasColorbar_56 = require('../colorbar/has_colorbar'); */; -/* removed: var _$colorbarDefaults_54 = require('../colorbar/defaults'); */; -/* removed: var _$isValidScale_67 = require('./is_valid_scale'); */; -/* removed: var _$flipScale_63 = require('./flip_scale'); */; +/* + * 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'], + showAttrs = showAttrsAll.filter(function(a) { + return containerIn[a] !== undefined; + }), + sameVal = function(a) { + return containerIn[a] === containerIn[showAttrs[0]]; + }; + if(showAttrs.every(sameVal) || showAttrs.length === 1) { + return containerIn[showAttrs[0]]; + } +} -var _$colorScaleDefaults_61 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { - var prefix = opts.prefix, - cLetter = opts.cLetter, - containerStr = prefix.slice(0, prefix.length - 1), - containerIn = prefix ? - _$lib_171.nestedProperty(traceIn, containerStr).get() || {} : - traceIn, - containerOut = prefix ? - _$lib_171.nestedProperty(traceOut, containerStr).get() || {} : - traceOut, - minIn = containerIn[cLetter + 'min'], - maxIn = containerIn[cLetter + 'max'], - sclIn = containerIn.colorscale; +function tickformatstopsDefaults(tickformatIn, tickformatOut) { + var valuesIn = tickformatIn.tickformatstops; + var valuesOut = tickformatOut.tickformatstops = []; - var validMinMax = _$fastIsnumeric_18(minIn) && _$fastIsnumeric_18(maxIn) && (minIn < maxIn); - coerce(prefix + cLetter + 'auto', !validMinMax); - coerce(prefix + cLetter + 'min'); - coerce(prefix + cLetter + 'max'); + if(!Array.isArray(valuesIn)) return; - // handles both the trace case (autocolorscale is false by default) and - // the marker and marker.line case (autocolorscale is true by default) - var autoColorscaleDftl; - if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_67(sclIn); - coerce(prefix + 'autocolorscale', autoColorscaleDftl); - var sclOut = coerce(prefix + 'colorscale'); + var valueIn, valueOut; - // reversescale is handled at the containerOut level - var reverseScale = coerce(prefix + 'reversescale'); - if(reverseScale) containerOut.colorscale = _$flipScale_63(sclOut); + function coerce(attr, dflt) { + return _$lib_172.coerce(valueIn, valueOut, _$layout_attributes_226.tickformatstops, attr, dflt); + } - // ... until Scatter.colorbar can handle marker line colorbars - if(prefix === 'marker.line.') return; + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; - // handle both the trace case where the dflt is listed in attributes and - // the marker case where the dflt is determined by hasColorbar - var showScaleDftl; - if(prefix) showScaleDftl = _$hasColorbar_56(containerIn); - var showScale = coerce(prefix + 'showscale', showScaleDftl); + coerce('dtickrange'); + coerce('value'); - if(showScale) _$colorbarDefaults_54(containerIn, containerOut, layout); -}; + valuesOut.push(valueOut); + } +} /** * Copyright 2012-2018, Plotly, Inc. @@ -19443,70 +18828,25 @@ var _$colorScaleDefaults_61 = function colorScaleDefaults(traceIn, traceOut, lay 'use strict'; -/** - * Extract colorscale into numeric domain and color range. - * - * @param {array} scl colorscale array of arrays - * @param {number} cmin minimum color value (used to clamp scale) - * @param {number} cmax maximum color value (used to clamp scale) - */ -var _$extractScale_62 = function extractScale(scl, cmin, cmax) { - var N = scl.length, - domain = new Array(N), - range = new Array(N); - - for(var i = 0; i < N; i++) { - var si = scl[i]; +/* removed: var _$lib_172 = require('../../lib'); */; - domain[i] = cmin + si[0] * (cmax - cmin); - range[i] = si[1]; - } +/* removed: var _$layout_attributes_226 = require('./layout_attributes'); */; - return { - domain: domain, - range: range - }; -}; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$isValidScale_67 = require('./is_valid_scale'); */; - -var _$hasColorscale_65 = function hasColorscale(trace, containerStr) { - var container = containerStr ? - _$lib_171.nestedProperty(trace, containerStr).get() || {} : - trace; - var color = container.color; + * options: inherits outerTicks from axes.handleAxisDefaults + */ +var _$handleTickDefaults_234 = function handleTickDefaults(containerIn, containerOut, coerce, options) { + var tickLen = _$lib_172.coerce2(containerIn, containerOut, _$layout_attributes_226, 'ticklen'), + tickWidth = _$lib_172.coerce2(containerIn, containerOut, _$layout_attributes_226, 'tickwidth'), + tickColor = _$lib_172.coerce2(containerIn, containerOut, _$layout_attributes_226, 'tickcolor', containerOut.color), + showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); - var isArrayWithOneNumber = false; - if(_$lib_171.isArrayOrTypedArray(color)) { - for(var i = 0; i < color.length; i++) { - if(_$fastIsnumeric_18(color[i])) { - isArrayWithOneNumber = true; - break; - } - } + if(!showTicks) { + delete containerOut.ticklen; + delete containerOut.tickwidth; + delete containerOut.tickcolor; } - - return ( - _$lib_171.isPlainObject(container) && ( - isArrayWithOneNumber || - container.showscale === true || - (_$fastIsnumeric_18(container.cmin) && _$fastIsnumeric_18(container.cmax)) || - _$isValidScale_67(container.colorscale) || - _$lib_171.isPlainObject(container.colorbar) - ) - ); }; /** @@ -19520,31 +18860,356 @@ var _$hasColorscale_65 = function hasColorscale(trace, containerStr) { 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var __ONEDAY_235 = _$numerical_154.ONEDAY; -/* removed: var _$color_51 = require('../color'); */; -/** - * 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} - */ -var _$makeColorScaleFunc_69 = function makeColorScaleFunc(specs, opts) { - opts = opts || {}; +var _$handleTickValueDefaults_235 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { + var tickmodeDefault = 'auto'; - var domain = specs.domain, - range = specs.range, - N = range.length, + if(containerIn.tickmode === 'array' && + (axType === 'log' || axType === 'date')) { + containerIn.tickmode = 'auto'; + } + + if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; + else if(containerIn.dtick) { + tickmodeDefault = 'linear'; + } + var tickmode = coerce('tickmode', tickmodeDefault); + + if(tickmode === 'auto') coerce('nticks'); + else if(tickmode === 'linear') { + // dtick is usually a positive number, but there are some + // special strings available for log or date axes + // default is 1 day for dates, otherwise 1 + var dtickDflt = (axType === 'date') ? __ONEDAY_235 : 1; + var dtick = coerce('dtick', dtickDflt); + if(_$fastIsnumeric_18(dtick)) { + containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; + } + else if(typeof dtick !== 'string') { + containerOut.dtick = dtickDflt; + } + else { + // date and log special cases are all one character plus a number + var prefix = dtick.charAt(0), + dtickNum = dtick.substr(1); + + dtickNum = _$fastIsnumeric_18(dtickNum) ? Number(dtickNum) : 0; + if((dtickNum <= 0) || !( + // "M" gives ticks every (integer) n months + (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || + // "L" gives ticks linearly spaced in data (not in position) every (float) f + (axType === 'log' && prefix === 'L') || + // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 + (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) + )) { + containerOut.dtick = dtickDflt; + } + } + + // tick0 can have different valType for different axis types, so + // validate that now. Also for dates, change milliseconds to date strings + var tick0Dflt = (axType === 'date') ? _$lib_172.dateTick0(containerOut.calendar) : 0; + var tick0 = coerce('tick0', tick0Dflt); + if(axType === 'date') { + containerOut.tick0 = _$lib_172.cleanDate(tick0, tick0Dflt); + } + // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely + else if(_$fastIsnumeric_18(tick0) && dtick !== 'D1' && dtick !== 'D2') { + containerOut.tick0 = Number(tick0); + } + else { + containerOut.tick0 = tick0Dflt; + } + } + else { + var tickvals = coerce('tickvals'); + if(tickvals === undefined) containerOut.tickmode = 'auto'; + else coerce('ticktext'); + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_235 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_234 = require('../../plots/cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_233 = require('../../plots/cartesian/tick_label_defaults'); */; + +/* removed: var _$attributes_52 = require('./attributes'); */; + + +var _$colorbarDefaults_54 = function colorbarDefaults(containerIn, containerOut, layout) { + var colorbarOut = containerOut.colorbar = {}, + colorbarIn = containerIn.colorbar || {}; + + function coerce(attr, dflt) { + return _$lib_172.coerce(colorbarIn, colorbarOut, _$attributes_52, attr, dflt); + } + + var thicknessmode = coerce('thicknessmode'); + coerce('thickness', (thicknessmode === 'fraction') ? + 30 / (layout.width - layout.margin.l - layout.margin.r) : + 30 + ); + + var lenmode = coerce('lenmode'); + coerce('len', (lenmode === 'fraction') ? + 1 : + layout.height - layout.margin.t - layout.margin.b + ); + + coerce('x'); + coerce('xanchor'); + coerce('xpad'); + coerce('y'); + coerce('yanchor'); + coerce('ypad'); + _$lib_172.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + + coerce('outlinecolor'); + coerce('outlinewidth'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('bgcolor'); + + _$handleTickValueDefaults_235(colorbarIn, colorbarOut, coerce, 'linear'); + + var opts = {outerTicks: false, font: layout.font}; + _$handleTickLabelDefaults_233(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickDefaults_234(colorbarIn, colorbarOut, coerce, 'linear', opts); + + coerce('title', layout._dfltTitle.colorbar); + _$lib_172.coerceFont(coerce, 'titlefont', layout.font); + coerce('titleside'); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; + + +var _$hasColorbar_56 = function hasColorbar(container) { + return _$lib_172.isPlainObject(container.colorbar); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$scales_70 = require('./scales'); */; +/* removed: var _$isValidScaleArray_68 = require('./is_valid_scale_array'); */; + + +var _$isValidScale_67 = function isValidScale(scl) { + if(_$scales_70[scl] !== undefined) return true; + else return _$isValidScaleArray_68(scl); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + +/* removed: var _$lib_172 = require('../../lib'); */; + +/* removed: var _$hasColorbar_56 = require('../colorbar/has_colorbar'); */; +/* removed: var _$colorbarDefaults_54 = require('../colorbar/defaults'); */; +/* removed: var _$isValidScale_67 = require('./is_valid_scale'); */; +/* removed: var _$flipScale_63 = require('./flip_scale'); */; + + +var _$colorScaleDefaults_61 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { + var prefix = opts.prefix, + cLetter = opts.cLetter, + containerStr = prefix.slice(0, prefix.length - 1), + containerIn = prefix ? + _$lib_172.nestedProperty(traceIn, containerStr).get() || {} : + traceIn, + containerOut = prefix ? + _$lib_172.nestedProperty(traceOut, containerStr).get() || {} : + traceOut, + minIn = containerIn[cLetter + 'min'], + maxIn = containerIn[cLetter + 'max'], + sclIn = containerIn.colorscale; + + var validMinMax = _$fastIsnumeric_18(minIn) && _$fastIsnumeric_18(maxIn) && (minIn < maxIn); + coerce(prefix + cLetter + 'auto', !validMinMax); + 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 autoColorscaleDftl; + if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_67(sclIn); + coerce(prefix + 'autocolorscale', autoColorscaleDftl); + var sclOut = coerce(prefix + 'colorscale'); + + // reversescale is handled at the containerOut level + var reverseScale = coerce(prefix + 'reversescale'); + if(reverseScale) containerOut.colorscale = _$flipScale_63(sclOut); + + // ... until Scatter.colorbar can handle marker line colorbars + if(prefix === 'marker.line.') return; + + // handle both the trace case where the dflt is listed in attributes and + // the marker case where the dflt is determined by hasColorbar + var showScaleDftl; + if(prefix) showScaleDftl = _$hasColorbar_56(containerIn); + var showScale = coerce(prefix + 'showscale', showScaleDftl); + + if(showScale) _$colorbarDefaults_54(containerIn, containerOut, layout); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/** + * Extract colorscale into numeric domain and color range. + * + * @param {array} scl colorscale array of arrays + * @param {number} cmin minimum color value (used to clamp scale) + * @param {number} cmax maximum color value (used to clamp scale) + */ +var _$extractScale_62 = function extractScale(scl, cmin, cmax) { + var N = scl.length, + domain = new Array(N), + range = new Array(N); + + for(var i = 0; i < N; i++) { + var si = scl[i]; + + domain[i] = cmin + si[0] * (cmax - cmin); + range[i] = si[1]; + } + + return { + domain: domain, + range: range + }; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$isValidScale_67 = require('./is_valid_scale'); */; + +var _$hasColorscale_65 = function hasColorscale(trace, containerStr) { + var container = containerStr ? + _$lib_172.nestedProperty(trace, containerStr).get() || {} : + trace; + var color = container.color; + + var isArrayWithOneNumber = false; + if(_$lib_172.isArrayOrTypedArray(color)) { + for(var i = 0; i < color.length; i++) { + if(_$fastIsnumeric_18(color[i])) { + isArrayWithOneNumber = true; + break; + } + } + } + + return ( + _$lib_172.isPlainObject(container) && ( + isArrayWithOneNumber || + container.showscale === true || + (_$fastIsnumeric_18(container.cmin) && _$fastIsnumeric_18(container.cmax)) || + _$isValidScale_67(container.colorscale) || + _$lib_172.isPlainObject(container.colorbar) + ) + ); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + +/* removed: var _$color_51 = require('../color'); */; + +/** + * 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} + */ +var _$makeColorScaleFunc_69 = function makeColorScaleFunc(specs, opts) { + opts = opts || {}; + + var domain = specs.domain, + range = specs.range, + N = range.length, _range = new Array(N); for(var i = 0; i < N; i++) { @@ -20226,7 +19891,7 @@ var _$string_mappings_155 = { } }; -var _$svg_text_utils_192 = {}; +var _$svg_text_utils_193 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -20242,7 +19907,7 @@ var _$svg_text_utils_192 = {}; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$lib_172 = require('../lib'); */; /* removed: var _$xmlns_namespaces_156 = require('../constants/xmlns_namespaces'); */; /* removed: var _$string_mappings_155 = require('../constants/string_mappings'); */; var LINE_SPACING = _$alignment_151.LINE_SPACING; @@ -20255,7 +19920,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_192.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_193.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) @@ -20298,7 +19963,7 @@ _$svg_text_utils_192.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_192.positionText(_context); + _$svg_text_utils_193.positionText(_context); if(_callback) _callback.call(_context); } @@ -20393,7 +20058,7 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_171.randstr([], 64); + var randomID = 'math-output-' + _$lib_172.randstr([], 64); var tmpDiv = _$d3_15.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) @@ -20404,7 +20069,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = _$d3_15.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_171.log('There was an error in the tex syntax.', _texString); + _$lib_172.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -20499,7 +20164,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_192.plainText = function(_str) { +_$svg_text_utils_193.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -20632,14 +20297,14 @@ function buildSVGText(containerNode, str) { // 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_171.log('Ignoring unexpected end tag .', str); + _$lib_172.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_171.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_172.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -20698,7 +20363,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -20713,11 +20381,11 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_192.lineCount = function lineCount(s) { +_$svg_text_utils_193.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_192.positionText = function positionText(s, x, y) { +_$svg_text_utils_193.positionText = function positionText(s, x, y) { return s.each(function() { var text = _$d3_15.select(this); @@ -20793,7 +20461,7 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_192.makeEditable = function(context, options) { +_$svg_text_utils_193.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; var dispatch = _$d3_15.dispatch('edit', 'input', 'cancel'); @@ -20916,7 +20584,7 @@ _$svg_text_utils_192.makeEditable = function(context, options) { // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_385 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_386 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -20952,17 +20620,20 @@ var _$makeBubbleSizeFn_385 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -var _$subtypes_390 = { +var _$subtypes_391 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -20971,8 +20642,8 @@ var _$subtypes_390 = { }, isBubble: function(trace) { - return _$lib_171.isPlainObject(trace.marker) && - _$lib_171.isArrayOrTypedArray(trace.marker.size); + return _$lib_172.isPlainObject(trace.marker) && + _$lib_172.isArrayOrTypedArray(trace.marker.size); } }; @@ -20992,19 +20663,19 @@ var _$drawing_76 = {}; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$registry_261 = require('../../registry'); */; +/* removed: var _$registry_262 = require('../../registry'); */; /* removed: var _$color_51 = require('../color'); */; /* removed: var _$colorscale_66 = require('../colorscale'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; /* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; /* removed: var _$alignment_151 = require('../../constants/alignment'); */; var __LINE_SPACING_76 = _$alignment_151.LINE_SPACING; var __DESELECTDIM_76 = _$interactions_153.DESELECTDIM; -/* removed: var _$subtypes_390 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_385 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_391 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_386 = require('../../traces/scatter/make_bubble_size_func'); */; var drawing = _$drawing_76 = {}; @@ -21014,7 +20685,7 @@ var drawing = _$drawing_76 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_171.isPlainObject(family)) { + if(_$lib_172.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; @@ -21182,7 +20853,7 @@ drawing.fillGroupStyle = function(s) { shape.call(_$color_51.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_171.error(e, s); + _$lib_172.error(e, s); shape.remove(); } }); @@ -21245,8 +20916,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_261.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_385(trace); + if(_$registry_262.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_386(trace); sel.attr('d', function(d) { var r; @@ -21255,7 +20926,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_390.isBubble(trace) ? + r = _$subtypes_391.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -21295,10 +20966,10 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_171.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_51.defaultLine; + else if(_$lib_172.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_51.defaultLine; else lineColor = markerLine.color; - if(_$lib_171.isArrayOrTypedArray(marker.color)) { + if(_$lib_172.isArrayOrTypedArray(marker.color)) { fillColor = _$color_51.defaultLine; perPointGradient = true; } @@ -21351,7 +21022,7 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_171.identity); + .data([type + color1 + color2], _$lib_172.identity); gradient.exit().remove(); @@ -21394,9 +21065,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_172.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -21502,7 +21171,7 @@ drawing.selectedPointStyle = function(s, trace) { }); } - if(_$registry_261.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_262.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { var pt = _$d3_15.select(this); var mx = d.mx || marker.symbol || 0; @@ -21517,16 +21186,16 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_171.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_172.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_171.isArrayOrTypedArray(colorArray)) { + if(scl && _$lib_172.isArrayOrTypedArray(colorArray)) { return _$colorscale_66.makeColorScaleFunc( _$colorscale_66.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_171.identity; + else return _$lib_172.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; @@ -21546,7 +21215,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_192.lineCount(s) - 1) * __LINE_SPACING_76 + 1; + var numLines = (_$svg_text_utils_193.lineCount(s) - 1) * __LINE_SPACING_76 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -21565,7 +21234,7 @@ function extracTextFontSize(d, trace) { drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { var p = _$d3_15.select(this); - var text = _$lib_171.extractOption(d, trace, 'tx', 'text'); + var text = _$lib_172.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -21580,7 +21249,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_192.convertToTspans, gd) + .call(_$svg_text_utils_193.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -21708,33 +21377,28 @@ drawing.steps = function(shape) { // 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 = _$d3_15.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_156.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_172.ensureSingleById(_$d3_15.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_156.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_172.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; @@ -21779,7 +21443,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_171.extendFlat({}, out); + if(out) return _$lib_172.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -21823,7 +21487,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_171.extendFlat({}, out); + if(out) return _$lib_172.extendFlat({}, out); } } var testNode, tester; @@ -21841,7 +21505,7 @@ drawing.bBox = function(node, inTester, hash) { // standardize its position (and newline tspans if any) _$d3_15.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_192.positionText, 0, 0); + .call(_$svg_text_utils_193.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -21871,7 +21535,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_171.extendFlat({}, bb); + return _$lib_172.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -21896,15 +21560,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_15.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_15.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -22042,6 +21712,319 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { }); }; +var _$helpers_90 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; + +// look for either subplot or xaxis and yaxis attributes +// does not handle splom case +_$helpers_90.getSubplot = function getSubplot(trace) { + return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +}; + +// is trace in given list of subplots? +// does handle splom case +_$helpers_90.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_90.getSubplot(trace)) !== -1; +}; + +// convenience functions for mapping all relevant axes +_$helpers_90.flat = function flat(subplots, v) { + var out = new Array(subplots.length); + for(var i = 0; i < subplots.length; i++) { + out[i] = v; + } + return out; +}; + +_$helpers_90.p2c = function p2c(axArray, v) { + var out = new Array(axArray.length); + for(var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); + } + return out; +}; + +_$helpers_90.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { + if(mode === 'closest') return dxy || _$helpers_90.quadrature(dx, dy); + return mode === 'x' ? dx : dy; +}; + +_$helpers_90.getClosest = function getClosest(cd, distfn, pointData) { + // do we already have a point number? (array mode only) + if(pointData.index !== false) { + if(pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; + } + else pointData.index = false; + } + else { + // apply the distance function to each data point + // this is the longest loop... if this bogs down, we may need + // to create pre-sorted data (by x or y), not sure how to + // do this for 'closest' + for(var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if(newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; + } + } + } + return pointData; +}; + +/* + * pseudo-distance function for hover effects on areas: inside the region + * distance is finite (`passVal`), outside it's Infinity. + * + * @param {number} v0: signed difference between the current position and the left edge + * @param {number} v1: signed difference between the current position and the right edge + * @param {number} passVal: the value to return on success + */ +_$helpers_90.inbox = function inbox(v0, v1, passVal) { + return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; +}; + +_$helpers_90.quadrature = function quadrature(dx, dy) { + return function(di) { + var x = dx(di), + y = dy(di); + return Math.sqrt(x * x + y * y); + }; +}; + +/** Fill event data point object for hover and selection. + * Invokes _module.eventData if present. + * + * N.B. note that point 'index' corresponds to input data array index + * whereas 'number' is its post-transform version. + * + * If the hovered/selected pt corresponds to an multiple input points + * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' + * are include in the event data. + * + * @param {object} pt + * @param {object} trace + * @param {object} cd + * @return {object} + */ +_$helpers_90.makeEventData = function makeEventData(pt, trace, cd) { + // hover uses 'index', select uses 'pointNumber' + var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber: pointNumber + }; + + if(trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; + + if(pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; + } else { + out.pointIndices = pointIndices; + } + } else { + out.pointIndex = pointNumber; + } + + if(trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if('xVal' in pt) out.x = pt.xVal; + else if('x' in pt) out.x = pt.x; + + if('yVal' in pt) out.y = pt.yVal; + else if('y' in pt) out.y = pt.y; + + if(pt.xa) out.xaxis = pt.xa; + if(pt.ya) out.yaxis = pt.ya; + if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; + } + + _$helpers_90.appendArrayPointValue(out, trace, pointNumber); + + return out; +}; + +/** Appends values inside array attributes corresponding to given point number + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {number|Array(number)} pointNumber : point number. May be a length-2 array + * [row, col] to dig into 2D arrays + */ +_$helpers_90.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_172.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); + + if(pointVal !== undefined) pointData[key] = pointVal; + } + } +}; + +/** + * Appends values inside array attributes corresponding to given point number array + * For use when pointData references a plot entity that arose (or potentially arose) + * from multiple points in the input data + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. + * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays + */ +_$helpers_90.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_172.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); + + for(var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); + } + pointData[key] = keyVal; + } + } +}; + +var pointKeyMap = { + ids: 'id', + locations: 'location', + labels: 'label', + values: 'value', + 'marker.colors': 'color' +}; + +function getPointKey(astr) { + return pointKeyMap[astr] || astr; +} + +function getPointData(val, pointNumber) { + if(Array.isArray(pointNumber)) { + if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; + } + } else { + return val[pointNumber]; + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +// works with our CSS cursor classes (see css/_cursor.scss) +// to apply cursors to d3 single-element selections. +// omit cursor to revert to the default. +var _$setCursor_191 = function setCursor(el3, csr) { + (el3.attr('class') || '').split(' ').forEach(function(cls) { + if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); + }); + + if(csr) el3.classed('cursor-' + csr, true); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$setCursor_191 = require('./setcursor'); */; + +var STASHATTR = 'data-savedcursor'; +var NO_CURSOR = '!!'; + +/* + * works with our CSS cursor classes (see css/_cursor.scss) + * to override a previous cursor set on d3 single-element selections, + * by moving the name of the original cursor to the data-savedcursor attr. + * omit cursor to revert to the previously set value. + */ +var _$overrideCursor_183 = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if(csr) { + if(!savedCursor) { + var classes = (el3.attr('class') || '').split(' '); + for(var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if(cls.indexOf('cursor-') === 0) { + el3.attr(STASHATTR, cls.substr(7)) + .classed(cls, false); + } + } + if(!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); + } + } + _$setCursor_191(el3, csr); + } + else if(savedCursor) { + el3.attr(STASHATTR, null); + + if(savedCursor === NO_CURSOR) _$setCursor_191(el3); + else _$setCursor_191(el3, savedCursor); + } +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22052,7 +22035,7 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -var _$animation_attributes_208 = { +var _$animation_attributes_209 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -22199,7 +22182,7 @@ var _$frame_attributes_241 = { 'use strict'; /* removed: var _$attributes_57 = require('./attributes'); */; -var __extendFlat_59 = _$extend_165.extendFlat; +var __extendFlat_59 = _$extend_166.extendFlat; /* removed: var _$scales_70 = require('./scales.js'); */; /* @@ -22265,7 +22248,7 @@ var _$makeColorScaleAttributes_59 = function makeColorScaleAttributes(context, e 'use strict'; -var _$constants_374 = { +var _$constants_375 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -22293,13 +22276,13 @@ var _$constants_374 = { /* removed: var _$makeColorScaleAttributes_59 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; /* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -var __dash_368 = _$attributes_75.dash; +var __dash_369 = _$attributes_75.dash; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$constants_374 = require('./constants'); */; -var __extendFlat_368 = _$extend_165.extendFlat; +/* removed: var _$constants_375 = require('./constants'); */; +var __extendFlat_369 = _$extend_166.extendFlat; -var _$attributes_368 = { +var _$attributes_369 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -22401,7 +22384,7 @@ var _$attributes_368 = { editType: 'plot', }, - dash: __extendFlat_368({}, __dash_368, {editType: 'style'}), + dash: __extendFlat_369({}, __dash_369, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -22441,7 +22424,7 @@ var _$attributes_368 = { editType: 'style', }, - marker: __extendFlat_368({ + marker: __extendFlat_369({ symbol: { valType: 'enumerated', values: _$drawing_76.symbolList, @@ -22510,7 +22493,7 @@ var _$attributes_368 = { }, colorbar: _$attributes_52, - line: __extendFlat_368({ + line: __extendFlat_369({ width: { valType: 'number', min: 0, @@ -22661,12 +22644,12 @@ var _$attributes_368 = { 'use strict'; -/* removed: var _$attributes_368 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_368.marker; +/* removed: var _$attributes_369 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_369.marker; var _$area_attributes_247 = { - r: _$attributes_368.r, - t: _$attributes_368.t, + r: _$attributes_369.r, + t: _$attributes_369.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -22687,11 +22670,11 @@ var _$area_attributes_247 = { 'use strict'; -/* removed: var _$layout_attributes_225 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_248 = _$extend_165.extendFlat; -var __overrideAll_248 = _$edit_types_198.overrideAll; +/* removed: var _$layout_attributes_226 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_248 = _$extend_166.extendFlat; +var __overrideAll_248 = _$edit_types_199.overrideAll; -var domainAttr = __extendFlat_248({}, _$layout_attributes_225.domain, { +var domainAttr = __extendFlat_248({}, _$layout_attributes_226.domain, { }); @@ -22791,7 +22774,7 @@ var _$axis_attributes_248 = __overrideAll_248({ } }, 'plot', 'nested'); -var _$plot_schema_204 = {}; +var _$plot_schema_205 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22803,22 +22786,23 @@ var _$plot_schema_204 = {}; 'use strict'; -/* removed: var _$registry_261 = require('../registry'); */; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$registry_262 = require('../registry'); */; +/* removed: var _$lib_172 = require('../lib'); */; -/* removed: var _$attributes_210 = require('../plots/attributes'); */; +/* removed: var _$attributes_211 = require('../plots/attributes'); */; /* removed: var _$layout_attributes_244 = require('../plots/layout_attributes'); */; /* removed: var _$frame_attributes_241 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_208 = require('../plots/animation_attributes'); */; +/* removed: var _$animation_attributes_209 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet /* removed: var _$area_attributes_247 = require('../plots/polar/legacy/area_attributes'); */; /* removed: var _$axis_attributes_248 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_198 = require('./edit_types'); */; +/* removed: var _$edit_types_199 = require('./edit_types'); */; -var __extendFlat_204 = _$lib_171.extendFlat; -var __extendDeepAll_204 = _$lib_171.extendDeepAll; +var __extendFlat_205 = _$lib_172.extendFlat; +var __extendDeepAll_205 = _$lib_172.extendDeepAll; +var __isPlainObject_205 = _$lib_172.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -22826,10 +22810,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_204.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_204.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_204.DEPRECATED = DEPRECATED; -_$plot_schema_204.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_205.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_205.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_205.DEPRECATED = DEPRECATED; +_$plot_schema_205.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -22842,26 +22826,26 @@ _$plot_schema_204.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_204.get = function() { +_$plot_schema_205.get = function() { var traces = {}; - _$registry_261.allTypes.concat('area').forEach(function(type) { + _$registry_262.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_261.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_262.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_171.valObjectMeta, + valObjects: _$lib_172.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_198.traces, - layout: _$edit_types_198.layout + traces: _$edit_types_199.traces, + layout: _$edit_types_199.layout }, impliedEdits: { @@ -22874,7 +22858,7 @@ _$plot_schema_204.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_208) + animation: formatAttributes(_$animation_attributes_209) }; }; @@ -22905,7 +22889,7 @@ _$plot_schema_204.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_204.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_205.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -22917,10 +22901,10 @@ _$plot_schema_204.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_204.isValObject(attr)) return; + if(_$plot_schema_205.isValObject(attr)) return; - if(_$lib_171.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_204.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_205(attr) && attrName !== 'impliedEdits') { + _$plot_schema_205.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -22932,7 +22916,7 @@ _$plot_schema_204.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_204.isValObject = function(obj) { +_$plot_schema_205.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -22946,7 +22930,7 @@ _$plot_schema_204.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_204.findArrayAttributes = function(trace) { +_$plot_schema_205.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -22969,8 +22953,8 @@ _$plot_schema_204.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_171.nestedProperty(trace, astr).get(); - if(!_$lib_171.isArrayOrTypedArray(val)) return; + var val = _$lib_172.nestedProperty(trace, astr).get(); + if(!_$lib_172.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -22979,9 +22963,9 @@ _$plot_schema_204.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_204.crawl(_$attributes_210, callback); + _$plot_schema_205.crawl(_$attributes_211, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_204.crawl(trace._module.attributes, callback); + _$plot_schema_205.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -22994,7 +22978,7 @@ _$plot_schema_204.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_204.crawl(module.attributes, callback, 1); + _$plot_schema_205.crawl(module.attributes, callback, 1); } } } @@ -23006,8 +22990,8 @@ _$plot_schema_204.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_204.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_171.filterUnique(arrayAttributes); + _$plot_schema_205.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_172.filterUnique(arrayAttributes); } return arrayAttributes; @@ -23028,18 +23012,19 @@ _$plot_schema_204.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_204.getTraceValObject = function(trace, parts) { +_$plot_schema_205.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_261.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_262.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } @@ -23050,7 +23035,7 @@ _$plot_schema_204.getTraceValObject = function(trace, parts) { // 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_261.modules[trace.type || _$attributes_210.type.dflt] || {})._module; + if(!_module) _module = (_$registry_262.modules[trace.type || _$attributes_211.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -23065,7 +23050,7 @@ _$plot_schema_204.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_210[head]; + if(!valObject) valObject = _$attributes_211[head]; } return recurseIntoValObject(valObject, parts, i); @@ -23084,7 +23069,7 @@ _$plot_schema_204.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_204.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_205.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -23135,8 +23120,8 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_261.componentsRegistry) { - _module = _$registry_261.componentsRegistry[key]; + for(key in _$registry_262.componentsRegistry) { + _module = _$registry_262.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } @@ -23166,7 +23151,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_171.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_205(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -23213,7 +23198,7 @@ function getTraceAttributes(type) { basePlotModule = {}; } else { - _module = _$registry_261.modules[type]._module, + _module = _$registry_262.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -23223,14 +23208,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_204(attributes, _$attributes_210); + __extendDeepAll_205(attributes, _$attributes_211); // module attributes - __extendDeepAll_204(attributes, _module.attributes); + __extendDeepAll_205(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_204(attributes, basePlotModule.attributes); + __extendDeepAll_205(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -23245,7 +23230,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_204(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_205(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -23257,21 +23242,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_204(layoutAttributes, _$layout_attributes_244); + __extendDeepAll_205(layoutAttributes, _$layout_attributes_244); // add base plot module layout attributes - for(key in _$registry_261.subplotsRegistry) { - _module = _$registry_261.subplotsRegistry[key]; + for(key in _$registry_262.subplotsRegistry) { + _module = _$registry_262.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -23280,8 +23264,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_261.componentsRegistry) { - _module = _$registry_261.componentsRegistry[key]; + for(key in _$registry_262.componentsRegistry) { + _module = _$registry_262.componentsRegistry[key]; var schema = _module.schema; /* @@ -23312,12 +23296,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_261.transformsRegistry[type]; - var attributes = __extendDeepAll_204({}, _module.attributes); + var _module = _$registry_262.transformsRegistry[type]; + var attributes = __extendDeepAll_205({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_261.componentsRegistry).forEach(function(k) { - var _module = _$registry_261.componentsRegistry[k]; + Object.keys(_$registry_262.componentsRegistry).forEach(function(k) { + var _module = _$registry_262.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -23333,7 +23317,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_171.extendDeepAll({}, _$frame_attributes_241) + frames: _$lib_172.extendDeepAll({}, _$frame_attributes_241) }; formatAttributes(attrs); @@ -23344,6 +23328,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -23360,7 +23345,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_204.isValObject(attr)) { + if(_$plot_schema_205.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -23372,13 +23357,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_171.isPlainObject(attr)) { + else if(__isPlainObject_205(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_204.crawl(attrs, callback); + _$plot_schema_205.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -23397,32 +23382,55 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_204.crawl(attrs, callback); + _$plot_schema_205.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_205(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_204(layoutAttributes, { + __extendFlat_205(layoutAttributes, { radialaxis: _$axis_attributes_248.radialaxis, angularaxis: _$axis_attributes_248.angularaxis }); - __extendFlat_204(layoutAttributes, _$axis_attributes_248.layout); + __extendFlat_205(layoutAttributes, _$axis_attributes_248.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_171.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_204({}, _module.layoutAttributes); + var np = _$lib_172.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_205({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_171.nestedProperty(baseAttrs, astr); + var np = _$lib_172.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_204(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_205(np.get() || {}, newAttrs)); } var _$command_238 = {}; @@ -23436,8 +23444,8 @@ var _$command_238 = {}; 'use strict'; -/* removed: var _$registry_261 = require('../registry'); */; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$registry_262 = require('../registry'); */; +/* removed: var _$lib_172 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -23541,7 +23549,7 @@ _$command_238.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_171.log('Unable to automatically bind plot updates to API command'); + _$lib_172.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -23659,7 +23667,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_171.nestedProperty(container, binding.prop).get(); + value = _$lib_172.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -23691,7 +23699,7 @@ function bindingValueHasChanged(gd, binding, cache) { _$command_238.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_261.apiMethodRegistry[method]; + var _method = _$registry_262.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -23700,7 +23708,7 @@ _$command_238.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_171.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_172.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; @@ -23750,7 +23758,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_171.isPlainObject(astr)) { + } else if(_$lib_172.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -23774,7 +23782,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_171.isPlainObject(astr)) { + } else if(_$lib_172.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -23840,7 +23848,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_171.isPlainObject(attr)) { + if(_$lib_172.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -23849,6 +23857,32 @@ function crawl(attrs, callback, path, depth) { }); } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_253 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + var _$plots_246 = {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -23864,25 +23898,27 @@ var _$plots_246 = {}; /* removed: var _$d3_15 = require('d3'); */; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$registry_261 = require('../registry'); */; -/* removed: var _$plot_schema_204 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_216 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_171 = require('../lib'); */; -var _ = _$lib_171._; +/* removed: var _$registry_262 = require('../registry'); */; +/* removed: var _$plot_schema_205 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_172 = require('../lib'); */; /* removed: var _$color_51 = require('../components/color'); */; var __BADNUM_246 = _$numerical_154.BADNUM; -var plots = _$plots_246 = {}; +/* removed: var _$axis_ids_217 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_246 = _$sort_modules_253.sortBasePlotModules; -/* removed: var _$animation_attributes_208 = require('./animation_attributes'); */; +/* removed: var _$animation_attributes_209 = require('./animation_attributes'); */; /* removed: var _$frame_attributes_241 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_171.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_172.relinkPrivateKeys; +var _ = _$lib_172._; + +var plots = _$plots_246 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_171.extendFlat(plots, _$registry_261); +_$lib_172.extendFlat(plots, _$registry_262); -plots.attributes = _$attributes_210; +plots.attributes = _$attributes_211; plots.attributes.type.values = plots.allTypes; plots.fontAttrs = _$font_attributes_240; plots.layoutAttributes = _$layout_attributes_244; @@ -23902,15 +23938,15 @@ plots.hasSimpleAPICommandBindings = _$command_238.hasSimpleAPICommandBindings; // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_171.getGraphDiv(gd); + gd = _$lib_172.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_261.getComponentMethod('annotations', 'draw')(gd); - _$registry_261.getComponentMethod('legend', 'draw')(gd); + _$registry_262.getComponentMethod('annotations', 'draw')(gd); + _$registry_262.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -23923,7 +23959,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_171.getGraphDiv(gd); + gd = _$lib_172.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -23954,7 +23990,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_261.call('relayout', gd, {autosize: true}).then(function() { + _$registry_262.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -23984,12 +24020,8 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_172.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', 'fill': _$color_51.defaultLine, @@ -24001,12 +24033,11 @@ plots.addLinks = function(gd) { links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -24144,6 +24175,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -24178,7 +24211,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -24221,12 +24253,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_262.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_172.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_172.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_172.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -24237,7 +24295,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -24246,6 +24304,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -24256,7 +24325,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -24268,17 +24337,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_216.list(gd); + var axList = _$axis_ids_217.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -24288,6 +24357,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_246); }; /** @@ -24306,7 +24378,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_261.subplotsRegistry; + var subplotsRegistry = _$registry_262.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -24319,7 +24391,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_171.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_172.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -24340,14 +24412,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_171.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_172.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_171.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_172.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -24392,7 +24464,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_261.localeRegistry; + locales = _$registry_262.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -24401,7 +24473,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_261.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_262.localeRegistry.en.format); return formatObj; } @@ -24453,30 +24525,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_262.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -24484,7 +24554,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -24556,8 +24626,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_216.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_216.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_217.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_217.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -24602,13 +24672,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_216.list(mockGd, null, true); + var axList = _$axis_ids_217.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_216.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_217.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -24630,7 +24700,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_216.getFromId(mockGd, ax.anchor); + _$axis_ids_217.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -24659,7 +24729,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_216.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_217.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -24700,17 +24770,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_204.crawl( + _$plot_schema_205.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_171.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_172.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_171.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_172.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -24732,8 +24802,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_171.pushUnique(modules, _module); - _$lib_171.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_172.pushUnique(modules, _module); + _$lib_172.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -24793,11 +24863,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_261.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_262.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_261.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_262.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -24826,7 +24896,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_171.coerce(opts || {}, optsOut, _$animation_attributes_208, attr, dflt); + return _$lib_172.coerce(opts || {}, optsOut, _$animation_attributes_209, attr, dflt); } coerce('mode'); @@ -24858,7 +24928,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_171.coerce(opts || {}, optsOut, _$animation_attributes_208.frame, attr, dflt); + return _$lib_172.coerce(opts || {}, optsOut, _$animation_attributes_209.frame, attr, dflt); } coerce('duration'); @@ -24871,7 +24941,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_171.coerce(opts || {}, optsOut, _$animation_attributes_208.transition, attr, dflt); + return _$lib_172.coerce(opts || {}, optsOut, _$animation_attributes_209.transition, attr, dflt); } coerce('duration'); @@ -24884,7 +24954,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_171.coerce(frameIn, frameOut, _$frame_attributes_241, attr, dflt); + return _$lib_172.coerce(frameIn, frameOut, _$frame_attributes_241, attr, dflt); } coerce('group'); @@ -24905,7 +24975,7 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) var i; function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -24921,9 +24991,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -24933,18 +25003,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_171.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_172.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_171.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_172.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_171.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_172.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_171.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_172.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -24954,12 +25024,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_261.traceIs(traceOut, 'showLegend')) { + if(_$registry_262.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_261.getComponentMethod( + _$registry_262.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -24968,12 +25038,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_171.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_172.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_261.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_262.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_261.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_262.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -25017,17 +25087,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_171.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_172.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_171.pushUnique(transformModules, _module); + _$lib_172.pushUnique(transformModules, _module); } else { - transformOut = _$lib_171.extendFlat({}, transformIn); + transformOut = _$lib_172.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -25059,14 +25129,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_172.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_171.coerceFont(coerce, 'font'); + var globalFont = _$lib_172.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_171.coerceFont(coerce, 'titlefont', { + _$lib_172.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -25094,7 +25164,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_261.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_262.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -25105,12 +25175,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_261.getComponentMethod( + _$registry_262.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_261.getComponentMethod( + _$registry_262.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -25122,7 +25192,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_171.isPlotDiv(gd); + var isPlotDiv = _$lib_172.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -25210,11 +25280,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_261.componentsRegistry; + var componentsRegistry = _$registry_262.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_261.subplotsRegistry.cartesian; + var Cartesian = _$registry_262.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -25233,13 +25303,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_261.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_262.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_171.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_172.subplotSort); } // base plot module layout defaults @@ -25311,7 +25381,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_171.clearThrottle(); + _$lib_172.clearThrottle(); // data and layout delete gd.data; @@ -25367,7 +25437,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_171.pushUnique(styleModules, _module.style); + _$lib_172.pushUnique(styleModules, _module.style); } } @@ -25522,7 +25592,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_261.call('plot', gd); + return _$registry_262.call('plot', gd); } }; @@ -25563,7 +25633,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_171.isPlainObject(d)) { + if(_$lib_172.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -25586,7 +25656,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_171.isPlainObject(d.stream)) { + if(!_$lib_172.isPlainObject(d.stream)) { continue; } } @@ -25612,7 +25682,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_171.isJSDate(d)) return _$lib_171.ms2DateTimeLocal(+d); + if(_$lib_172.isJSDate(d)) return _$lib_172.ms2DateTimeLocal(+d); return d; } @@ -25809,8 +25879,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_171.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_171.expandObjectPaths(copy); + var copy = _$lib_172.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_172.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -25818,29 +25888,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_171.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_172.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_171.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_172.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_171.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_172.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_171.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_172.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_171.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_172.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_171.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_172.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -25865,7 +25935,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_261.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_262.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -25939,7 +26009,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_171.expandObjectPaths(_$lib_171.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_172.expandObjectPaths(_$lib_172.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -25966,7 +26036,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_261.getComponentMethod('errorbars', 'calc')(gd); + _$registry_262.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -26014,7 +26084,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_261.call('redraw', gd); + return _$registry_262.call('redraw', gd); }); } @@ -26046,7 +26116,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_171.expandObjectPaths(layout); + var newLayout = _$lib_172.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -26056,7 +26126,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_171.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_172.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -26086,7 +26156,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_261.call('redraw', gd); + return _$registry_262.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -26121,7 +26191,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_171.syncOrAsync(seq, gd); + var transitionStarting = _$lib_172.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -26133,7 +26203,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_216.list(gd), + var axList = _$axis_ids_217.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -26177,7 +26247,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_204.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_205.findArrayAttributes(trace); } // add polar axes to axis list @@ -26221,14 +26291,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -26263,7 +26334,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_261.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_262.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -26314,7 +26390,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_171.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_172.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -26336,11 +26412,11 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; /* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$drawing_76 = require('../drawing'); */; /* removed: var _$color_51 = require('../color'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; /* removed: var _$interactions_153 = require('../../constants/interactions'); */; var _$titles_144 = { @@ -26421,10 +26497,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_172.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -26442,7 +26515,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_171.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_172.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -26470,7 +26543,7 @@ function draw(gd, titleClass, options) { 'font-weight': _$plots_246.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_192.convertToTspans, gd); + .call(_$svg_text_utils_193.convertToTspans, gd); return _$plots_246.previousPromises(gd); } @@ -26520,7 +26593,7 @@ function draw(gd, titleClass, options) { avoid.selection.each(function() { var avoidbb = _$drawing_76.bBox(this); - if(_$lib_171.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_172.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -26560,12 +26633,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_192.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_193.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_261.call('restyle', gd, prop, text, traceIndex); + _$registry_262.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_261.call('relayout', gd, prop, text); + _$registry_262.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -26574,7 +26647,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_192.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_193.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -26595,10 +26668,10 @@ function draw(gd, titleClass, options) { /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -var __FP_SAFE_212 = _$numerical_154.FP_SAFE; +/* removed: var _$lib_172 = require('../../lib'); */; +var __FP_SAFE_213 = _$numerical_154.FP_SAFE; -var _$autorange_212 = { +var _$autorange_213 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -26643,7 +26716,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_171.simpleMap(ax.range, ax.r2l); + var rng = _$lib_172.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -26736,7 +26809,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_171.simpleMap(newRange, ax.l2r || Number); + return _$lib_172.simpleMap(newRange, ax.l2r || Number); } /* @@ -26768,7 +26841,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_171.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_172.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -26790,7 +26863,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_171.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_172.extendFlat({}, axeRangeOpts); } } @@ -26803,6 +26876,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -26863,14 +26938,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_212) vmax = v; + if(v > vmax && v < __FP_SAFE_213) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_212) vmin = v; - if(v > vmax && v < __FP_SAFE_212) vmax = v; + if(v < vmin && v > -__FP_SAFE_213) vmin = v; + if(v > vmax && v < __FP_SAFE_213) vmax = v; } } @@ -26904,7 +26979,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_212 : __lessOrEqual_212; + var atLeastAsExtreme = k ? __greaterOrEqual_213 : __lessOrEqual_213; includeThis = true; /* @@ -26955,13 +27030,12 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_18(v) && Math.abs(v) < __FP_SAFE_212; + return _$fastIsnumeric_18(v) && Math.abs(v) < __FP_SAFE_213; } -function __lessOrEqual_212(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_212(v0, v1) { return v0 >= v1; } +function __lessOrEqual_213(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_213(v0, v1) { return v0 >= v1; } -var _$axes_213 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -26973,2784 +27047,2933 @@ var _$axes_213 = {}; 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$titles_144 = require('../../components/titles'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var __BADNUM_215 = _$numerical_154.BADNUM; -/* removed: var _$numerical_154 = require('../../constants/numerical'); */; -var ONEAVGYEAR = _$numerical_154.ONEAVGYEAR; -var ONEAVGMONTH = _$numerical_154.ONEAVGMONTH; -var __ONEDAY_213 = _$numerical_154.ONEDAY; -var __ONEHOUR_213 = _$numerical_154.ONEHOUR; -var __ONEMIN_213 = _$numerical_154.ONEMIN; -var __ONESEC_213 = _$numerical_154.ONESEC; -var MINUS_SIGN = _$numerical_154.MINUS_SIGN; -var __BADNUM_213 = _$numerical_154.BADNUM; +var _$autoType_215 = function autoType(array, calendar) { + if(moreDates(array, calendar)) return 'date'; + if(category(array)) return 'category'; + if(linearOK(array)) return 'linear'; + else return '-'; +}; -var MID_SHIFT = _$alignment_151.MID_SHIFT; -var __LINE_SPACING_213 = _$alignment_151.LINE_SPACING; +// is there at least one number in array? If not, we should leave +// ax.type empty so it can be autoset later +function linearOK(array) { + if(!array) return false; -var axes = _$axes_213 = {}; + for(var i = 0; i < array.length; i++) { + if(_$fastIsnumeric_18(array[i])) return true; + } -axes.setConvert = _$setConvert_232; -/* removed: var _$autoType_214 = require('./axis_autotype'); */; + return false; +} -/* removed: var _$axis_ids_216 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_216.id2name; -axes.name2id = _$axis_ids_216.name2id; -axes.cleanId = _$axis_ids_216.cleanId; -axes.list = _$axis_ids_216.list; -axes.listIds = _$axis_ids_216.listIds; -axes.getFromId = _$axis_ids_216.getFromId; -axes.getFromTrace = _$axis_ids_216.getFromTrace; +// does the array a have mostly dates rather than numbers? +// note: some values can be neither (such as blanks, text) +// 2- or 4-digit integers can be both, so require twice as many +// dates as non-dates, to exclude cases with mostly 2 & 4 digit +// numbers and a few dates +function moreDates(a, calendar) { + var dcnt = 0, + ncnt = 0, + // test at most 1000 points, evenly spaced + inc = Math.max(1, (a.length - 1) / 1000), + ai; -/* removed: var _$autorange_212 = require('./autorange'); */; -axes.expand = _$autorange_212.expand; -axes.getAutoRange = _$autorange_212.getAutoRange; + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_172.isDateTime(ai, calendar)) dcnt += 1; + if(_$fastIsnumeric_18(ai)) ncnt += 1; + } -/* - * 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 = {}; + return (dcnt > ncnt * 2); +} - if(!dflt) dflt = axlist[0] || extraOption; - if(!extraOption) extraOption = dflt; +// are the (x,y)-values in gd.data mostly text? +// require twice as many categories as numbers +function category(a) { + // test at most 1000 points + var inc = Math.max(1, (a.length - 1) / 1000), + curvenums = 0, + curvecats = 0, + ai; - // data-ref annotations are not supported in gl2d yet + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_172.cleanNumber(ai) !== __BADNUM_215) curvenums++; + else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; + } - attrDef[refAttr] = { - valType: 'enumerated', - values: axlist.concat(extraOption ? [extraOption] : []), - dflt: dflt - }; + return curvecats > curvenums * 2; +} - // xref, yref - return _$lib_171.coerce(containerIn, containerOut, attrDef, refAttr); -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * 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 + +'use strict'; + +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + +/* removed: var _$lib_172 = require('../../lib'); */; +var cleanNumber = _$lib_172.cleanNumber; +var ms2DateTime = _$lib_172.ms2DateTime; +var dateTime2ms = _$lib_172.dateTime2ms; +var ensureNumber = _$lib_172.ensureNumber; + +/* removed: var _$numerical_154 = require('../../constants/numerical'); */; +var __FP_SAFE_232 = _$numerical_154.FP_SAFE; +var __BADNUM_232 = _$numerical_154.BADNUM; + +/* removed: var _$constants_219 = require('./constants'); */; +/* removed: var _$axis_ids_217 = require('./axis_ids'); */; + +function fromLog(v) { + return Math.pow(10, v); +} + +/** + * Define the conversion functions for an axis data is used in 5 ways: * - * 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 + * 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. * - * 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 + * Creates/updates these conversion functions, and a few more utilities + * like cleanRange, and makeCalcdata + * + * also clears the autorange bounds ._min and ._max + * and the autotick constraints ._minDtick, ._forceTick0 */ -axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { - var cleanPos, pos; +var _$setConvert_232 = function setConvert(ax, fullLayout) { + fullLayout = fullLayout || {}; - if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_171.ensureNumber; - pos = coerce(attr, dflt); - } else { - var ax = axes.getFromId(gd, axRef); - dflt = ax.fraction2r(dflt); - pos = coerce(attr, dflt); - cleanPos = ax.cleanPos; + var axLetter = (ax._id || 'x').charAt(0); + + // clipMult: how many axis lengths past the edge do we render? + // for panning, 1-2 would suffice, but for zooming more is nice. + // also, clipping can affect the direction of lines off the edge... + var clipMult = 10; + + 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 clipMult axis + // length past the negative edge + var r0 = ax.range[0], + r1 = ax.range[1]; + return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); + } + + else return __BADNUM_232; } - containerOut[attr] = cleanPos(pos); -}; + /* + * 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_232) { + if(_$fastIsnumeric_18(v)) ms = dateTime2ms(new Date(+v)); + else return __BADNUM_232; + } + return ms; + } -axes.cleanPosition = function(pos, gd, axRef) { - var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_171.ensureNumber : - axes.getFromId(gd, axRef).cleanPos; + // wrapped ms2DateTime to insert default ax.calendar + function ms2dt(v, r, calendar) { + return ms2DateTime(v, r, calendar || ax.calendar); + } - return cleanPos(pos); -}; + function getCategoryName(v) { + return ax._categories[Math.round(v)]; + } -var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { - var ax; + /* + * 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(v !== null && v !== undefined) { + if(ax._categoriesMap === undefined) { + ax._categoriesMap = {}; + } - // 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; + if(ax._categoriesMap[v] !== undefined) { + return ax._categoriesMap[v]; + } else { + ax._categories.push(v); - // 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_214(targetArray), - _categories: [] - }; - axes.setConvert(ax); + var curLength = ax._categories.length - 1; + ax._categoriesMap[v] = curLength; - // 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]); + return curLength; } } - } else { - ax = axes.getFromTrace(gd, trace, d2cTarget); + return __BADNUM_232; } - // 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}; + function getCategoryIndex(v) { + // d2l/d2c variant that that won't add categories but will also + // allow numbers to be mapped to the linearized axis positions + if(ax._categoriesMap) { + var index = ax._categoriesMap[v]; + if(index !== undefined) return index; + } - // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size') - // -> cast to Number + if(_$fastIsnumeric_18(v)) return +v; + } - return {d2c: toNum, c2d: toNum}; -}; + function l2p(v) { + if(!_$fastIsnumeric_18(v)) return __BADNUM_232; -function toNum(v) { return +v; } -function toString(v) { return String(v); } + // include 2 fractional digits on pixel, for PDF zooming etc + return _$d3_15.round(ax._b + ax._m * v, 2); + } -axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { - return getDataConversions(gd, trace, target, targetArray).d2c; -}; + function p2l(px) { return (px - ax._b) / ax._m; } -// 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'; -}; + // 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; -// 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'].indexOf(ax.type) !== -1 || !allow) { - ax._minDtick = 0; - } - // undefined means there's nothing there yet - else if(ax._minDtick === undefined) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - else if(ax._minDtick) { - // existing minDtick is an integer multiple of newDiff - // (within rounding err) - // and forceTick0 can be shifted to newFirst - if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && - (((newFirst - ax._forceTick0) / newDiff % 1) + - 1.000001) % 1 < 2e-6) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - // 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 - else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || - (((newFirst - ax._forceTick0) / ax._minDtick % 1) + - 1.000001) % 1 > 2e-6) { - ax._minDtick = 0; - } - } -}; + ax.l2p = l2p; + ax.p2l = p2l; -// 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), - hasOneAxisChanged = false; + 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; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + /* + * 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; - var isNew = (ax._rangeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.range[0] === ax._rangeInitial[0] && - ax.range[1] === ax._rangeInitial[1] - ) - ); + ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2d = ax.p2r = p2l; - if((isNew && ax.autorange === false) || (overwrite && hasChanged)) { - ax._rangeInitial = ax.range.slice(); - hasOneAxisChanged = true; - } + 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)); }; - return hasOneAxisChanged; -}; + ax.d2c = ax.r2l = cleanNumber; + ax.c2d = ax.l2r = ensureNumber; -// save a copy of the initial spike visibility -axes.saveShowSpikeInitial = function(gd, overwrite) { - var axList = axes.list(gd, '', true), - hasOneAxisChanged = false, - allSpikesEnabled = 'on'; + ax.c2r = toLog; + ax.l2d = fromLog; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); }; + ax.p2d = function(px) { return fromLog(p2l(px)); }; - var isNew = (ax._showSpikeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.showspikes === ax._showspikes - ) - ); + ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2r = p2l; - if((isNew) || (overwrite && hasChanged)) { - ax._showSpikeInitial = ax.showspikes; - hasOneAxisChanged = true; - } + ax.cleanPos = ensureNumber; + } + else if(ax.type === 'date') { + // r and d are date strings, l and c are ms - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } + /* + * 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_172.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_172.cleanDate(v, __BADNUM_232, ax.calendar); }; } - gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - return hasOneAxisChanged; -}; + else if(ax.type === 'category') { + // d is categories (string) + // c and l are indices (numbers) + // r is categories or numbers -axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_171.aggNums(Math.min, null, data), - dataMax = _$lib_171.aggNums(Math.max, null, data); + ax.d2c = ax.d2l = setCategoryIndex; + ax.r2d = ax.c2d = ax.l2d = getCategoryName; - if(!calendar) calendar = ax.calendar; + ax.d2r = ax.d2l_noadd = getCategoryIndex; - if(ax.type === 'category') { - return { - start: dataMin - 0.5, - end: dataMax + 0.5, - size: 1, - _dataSpan: dataMax - dataMin, + ax.r2c = function(v) { + var index = getCategoryIndex(v); + return index !== undefined ? index : ax.fraction2r(0.5); }; - } - 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_171.distinctVals(data), - msexp = Math.pow(10, Math.floor( - Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_171.roundUp( - distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_171.stdev(data) / - Math.pow(data.length, is2d ? 0.25 : 0.4)); + ax.l2r = ax.c2r = ensureNumber; + ax.r2l = getCategoryIndex; - // fallback if ax.d2c output BADNUMs - // e.g. when user try to plot categorical bins - // on a layout.xaxis.type: 'linear' - if(!_$fastIsnumeric_18(size0)) size0 = 1; - } + 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; - // piggyback off autotick code to make "nice" bin sizes - var dummyAx; - if(ax.type === 'log') { - dummyAx = { - type: 'linear', - range: [dataMin, dataMax] - }; - } - else { - dummyAx = { - type: ax.type, - range: _$lib_171.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), - calendar: calendar + ax.cleanPos = function(v) { + if(typeof v === 'string' && v !== '') return v; + return ensureNumber(v); }; } - axes.setConvert(dummyAx); - axes.autoTicks(dummyAx, size0); - var binStart = axes.tickIncrement( - axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); - var binEnd, bincount; + // find the range value at the specified (linear) fraction of the axis + ax.fraction2r = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return ax.l2r(rl0 + v * (rl1 - rl0)); + }; - // 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 dummyAx.dtick === 'number') { - binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + // find the fraction of the range at the specified range value + ax.r2fraction = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return (ax.r2l(v) - rl0) / (rl1 - rl0); + }; - bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); - binEnd = binStart + bincount * dummyAx.dtick; - } - 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, dummyAx.dtick, dataMin, calendar); + /* + * 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_172.nestedProperty(ax, rangeAttr).get(); + var i, dflt; + + if(ax.type === 'date') dflt = _$lib_172.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_219.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_219.DFLTRANGEX; + + // make sure we don't later mutate the defaults + dflt = dflt.slice(); + + if(!range || range.length !== 2) { + _$lib_172.nestedProperty(ax, rangeAttr).set(dflt); + return; } - // 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, dummyAx.dtick, false, calendar); - bincount++; + if(ax.type === 'date') { + // check if milliseconds or js date objects are provided for range + // and convert to date strings + range[0] = _$lib_172.cleanDate(range[0], __BADNUM_232, ax.calendar); + range[1] = _$lib_172.cleanDate(range[1], __BADNUM_232, ax.calendar); } - } - return { - start: ax.c2r(binStart, 0, calendar), - end: ax.c2r(binEnd, 0, calendar), - size: dummyAx.dtick, - _dataSpan: dataMax - dataMin - }; -}; + for(i = 0; i < 2; i++) { + if(ax.type === 'date') { + if(!_$lib_172.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_172.constrain(ax.r2l(range[0]), + _$lib_172.MIN_MS + 1000, _$lib_172.MAX_MS - 1000); + range[0] = ax.l2r(linCenter - 1000); + range[1] = ax.l2r(linCenter + 1000); + break; + } + } + else { + if(!_$fastIsnumeric_18(range[i])) { + if(_$fastIsnumeric_18(range[1 - i])) { + range[i] = range[1 - i] * (i ? 10 : 0.1); + } + else { + ax[rangeAttr] = dflt; + break; + } + } -function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { - var edgecount = 0, - midcount = 0, - intcount = 0, - blankCount = 0; + if(range[i] < -__FP_SAFE_232) range[i] = -__FP_SAFE_232; + else if(range[i] > __FP_SAFE_232) range[i] = __FP_SAFE_232; - function nearEdge(v) { - // is a value within 1% of a bin edge? - return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; - } + 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; + } + } + } + }; - for(var i = 0; i < data.length; i++) { - if(data[i] % 1 === 0) intcount++; - else if(!_$fastIsnumeric_18(data[i])) blankCount++; + // set scaling to pixels + ax.setScale = function(usePrivateRange) { + var gs = fullLayout._size; - if(nearEdge(data[i])) edgecount++; - if(nearEdge(data[i] + ax.dtick / 2)) midcount++; - } - var dataCount = data.length - blankCount; + // TODO cleaner way to handle this case + if(!ax._categories) ax._categories = []; + // Add a map to optimize the performance of category collection + if(!ax._categoriesMap) ax._categoriesMap = {}; - if(intcount === dataCount && ax.type !== 'date') { - // 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 - if(ax.dtick < 1) { - binStart = dataMin - 0.5 * ax.dtick; - } - // 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. - else { - 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; + // make sure we have a domain (pull it in from the axis + // this one is overlaying if necessary) + if(ax.overlaying) { + var ax2 = _$axis_ids_217.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + ax.domain = ax2.domain; } - } - return binStart; -} + // 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', + calendar = ax.calendar; + ax.cleanRange(rangeAttr); -function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_171.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)); + var rl0 = ax.r2l(ax[rangeAttr][0], calendar), + rl1 = ax.r2l(ax[rangeAttr][1], calendar); - 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_213 * 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_213 * 15.5; + 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 { - // 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_213 / 2; + 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; } - var nextBinStart = axes.tickIncrement(binStart, dtick); - if(nextBinStart <= dataMin) return nextBinStart; - } - return binStart; -} + if(!isFinite(ax._m) || !isFinite(ax._b)) { + fullLayout._replotting = false; + throw new Error('Something went wrong with axis scaling'); + } + }; -// ---------------------------------------------------- -// Ticks and grids -// ---------------------------------------------------- + // 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; -// ensure we have tick0, dtick, and tick rounding calculated -axes.prepTicks = function(ax) { - var rng = _$lib_171.simpleMap(ax.range, ax.r2l); + var axType = ax.type; + var cal = axType === 'date' && trace[axLetter + 'calendar']; - // calculate max number of (auto) ticks to display based on plot size - if(ax.tickmode === 'auto' || !ax.dtick) { - var nt = ax.nticks, - minPx; - if(!nt) { - if(ax.type === 'category') { - 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_171.constrain(ax._length / minPx, 4, 9) + 1; + if(axLetter in trace) { + arrayIn = trace[axLetter]; + len = trace._length || arrayIn.length; + + if(_$lib_172.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(len === arrayIn.length) { + return arrayIn; + } else if(arrayIn.subarray) { + return arrayIn.subarray(0, len); + } } - // radial axes span half their domain, - // multiply nticks value by two to get correct number of auto ticks. - if(ax._name === 'radialaxis') nt *= 2; + 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; - // add a couple of extra digits for filling in ticks when we - // have explicit tickvals without tick text - if(ax.tickmode === 'array') nt *= 100; + // 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); - 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); + for(i = 0; i < len; i++) { + arrayOut[i] = v0 + i * dv; + } } - } - // check for missing tick0 - if(!ax.tick0) { - ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; - } + return arrayOut; + }; - // now figure out rounding of tick values - autoTickRound(ax); -}; + ax.isValidRange = function(range) { + return ( + Array.isArray(range) && + range.length === 2 && + _$fastIsnumeric_18(ax.r2l(range[0])) && + _$fastIsnumeric_18(ax.r2l(range[1])) + ); + }; -// 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_171.simpleMap(ax.range, ax.r2l); + 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]); - // 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); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } + }; - // find the first tick - ax._tmin = axes.tickFirst(ax); + ax.clearCalc = function() { + // for autoranging: arrays of objects: + // { + // val: axis value, + // pad: pixel padding, + // extrapad: boolean, should this val get 5% additional padding + // } + ax._min = []; + ax._max = []; - // 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]); + // initialize the category list, if there is one, so we start over + // to be filled in later by ax.d2c + ax._categories = (ax._initialCategories || []).slice(); - // No visible ticks? Quit. - // I've only seen this on category axes with all categories off the edge. - if((ax._tmin < startTick) !== axrev) return []; + // Build the lookup map for initialized categories + ax._categoriesMap = {}; + for(var j = 0; j < ax._categories.length; j++) { + ax._categoriesMap[ax._categories[j]] = j; + } + }; - // return the full set of tick vals - var vals = []; - if(ax.type === 'category') { - endTick = (axrev) ? Math.max(-0.5, endTick) : - Math.min(ax._categories.length - 0.5, endTick); + // 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_15.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_15.format; - 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(vals.length > maxTicks || x === xPrevious) break; - xPrevious = x; + // and for bar charts and box plots: reset forced minimum tick spacing + delete ax._minDtick; + delete ax._forceTick0; +}; - vals.push(x); - } +var _$axes_214 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // If same angle over a full circle, the last tick vals is a duplicate. - // TODO must do something similar for angular date axes. - if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { - vals.pop(); - } - // save the last tick as well as first, so we can - // show the exponent only on the last one - ax._tmax = vals[vals.length - 1]; +'use strict'; - // 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; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; - var ticksOut = new Array(vals.length); - for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$titles_144 = require('../../components/titles'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$drawing_76 = require('../../components/drawing'); */; - ax._inCalcTicks = false; +/* removed: var _$numerical_154 = require('../../constants/numerical'); */; +var ONEAVGYEAR = _$numerical_154.ONEAVGYEAR; +var ONEAVGMONTH = _$numerical_154.ONEAVGMONTH; +var __ONEDAY_214 = _$numerical_154.ONEDAY; +var __ONEHOUR_214 = _$numerical_154.ONEHOUR; +var __ONEMIN_214 = _$numerical_154.ONEMIN; +var __ONESEC_214 = _$numerical_154.ONESEC; +var MINUS_SIGN = _$numerical_154.MINUS_SIGN; +var __BADNUM_214 = _$numerical_154.BADNUM; - return ticksOut; -}; +var MID_SHIFT = _$alignment_151.MID_SHIFT; +var __LINE_SPACING_214 = _$alignment_151.LINE_SPACING; -function arrayTicks(ax) { - var vals = ax.tickvals, - text = ax.ticktext, - ticksOut = new Array(vals.length), - rng = _$lib_171.simpleMap(ax.range, ax.r2l), - r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, - r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, - tickMin = Math.min(r0expanded, r1expanded), - tickMax = Math.max(r0expanded, r1expanded), - vali, - i, - j = 0; +var axes = _$axes_214 = {}; - // 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 = []; +axes.setConvert = _$setConvert_232; +/* removed: var _$autoType_215 = require('./axis_autotype'); */; - // make sure showing ticks doesn't accidentally add new categories - var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; +/* removed: var _$axis_ids_217 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_217.id2name; +axes.name2id = _$axis_ids_217.name2id; +axes.cleanId = _$axis_ids_217.cleanId; +axes.list = _$axis_ids_217.list; +axes.listIds = _$axis_ids_217.listIds; +axes.getFromId = _$axis_ids_217.getFromId; +axes.getFromTrace = _$axis_ids_217.getFromTrace; - // 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); - } +/* removed: var _$autorange_213 = require('./autorange'); */; +axes.expand = _$autorange_213.expand; +axes.getAutoRange = _$autorange_213.getAutoRange; - for(i = 0; i < vals.length; i++) { - 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++; - } - } +/* + * 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(j < vals.length) ticksOut.splice(j, vals.length - j); + if(!dflt) dflt = axlist[0] || extraOption; + if(!extraOption) extraOption = dflt; - return ticksOut; -} + // data-ref annotations are not supported in gl2d yet -var roundBase10 = [2, 5, 10], - roundBase24 = [1, 2, 3, 6, 12], - roundBase60 = [1, 2, 5, 10, 15, 30], - // 2&3 day ticks are weird, but need something btwn 1&7 - 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 - roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], - roundLog2 = [-0.301, 0, 0.301, 0.699, 1], - // N.B. `thetaunit; 'radians' angular axes must be converted to degrees - roundAngles = [15, 30, 45, 90, 180]; + attrDef[refAttr] = { + valType: 'enumerated', + values: axlist.concat(extraOption ? [extraOption] : []), + dflt: dflt + }; -function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_171.roundUp(roughDTick / base, roundingSet); -} + // xref, yref + return _$lib_172.coerce(containerIn, containerOut, attrDef, refAttr); +}; -// 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; +/* + * 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; - function getBase(v) { - return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); + if(axRef === 'paper' || axRef === 'pixel') { + cleanPos = _$lib_172.ensureNumber; + pos = coerce(attr, dflt); + } else { + var ax = axes.getFromId(gd, axRef); + dflt = ax.fraction2r(dflt); + pos = coerce(attr, dflt); + cleanPos = ax.cleanPos; } - if(ax.type === 'date') { - ax.tick0 = _$lib_171.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; + containerOut[attr] = cleanPos(pos); +}; - 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_213) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_213, 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_171.dateTick0(ax.calendar, true); - } - else if(roughX2 > __ONEHOUR_213) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_213, roundBase24); - } - else if(roughX2 > __ONEMIN_213) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_213, roundBase60); - } - else if(roughX2 > __ONESEC_213) { - ax.dtick = roundDTick(roughDTick, __ONESEC_213, roundBase60); - } - else { - // milliseconds - base = getBase(10); - ax.dtick = roundDTick(roughDTick, base, roundBase10); - } - } - else if(ax.type === 'log') { - ax.tick0 = 0; - var rng = _$lib_171.simpleMap(ax.range, ax.r2l); +axes.cleanPosition = function(pos, gd, axRef) { + var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? + _$lib_172.ensureNumber : + axes.getFromId(gd, axRef).cleanPos; - 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); + return cleanPos(pos); +}; - // 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'; +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_215(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]); + } } - } - else if(ax.type === 'category') { - ax.tick0 = 0; - ax.dtick = Math.ceil(Math.max(roughDTick, 1)); - } - else if(ax._id === 'angular') { - 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); + } else { + ax = axes.getFromTrace(gd, trace, d2cTarget); } - // prevent infinite loops - if(ax.dtick === 0) ax.dtick = 1; + // if 'target' has corresponding axis + // -> use setConvert method + if(ax) return {d2c: ax.d2c, c2d: ax.c2d}; - // TODO: this is from log axis histograms with autorange off - if(!_$fastIsnumeric_18(ax.dtick) && typeof ax.dtick !== 'string') { - var olddtick = ax.dtick; - ax.dtick = 1; - throw 'ax.dtick error: ' + String(olddtick); - } + // 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}; }; -// 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; +function toNum(v) { return +v; } +function toString(v) { return String(v); } - ax._tickexponent = 0; - if(!_$fastIsnumeric_18(dtick) && typeof dtick !== 'string') { - dtick = 1; - } +axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { + return getDataConversions(gd, trace, target, targetArray).d2c; +}; - if(ax.type === 'category') { - 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), - tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), - tick0len = tick0str.length; +// 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'; +}; - 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'; +// 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'].indexOf(ax.type) !== -1 || !allow) { + ax._minDtick = 0; + } + // undefined means there's nothing there yet + else if(ax._minDtick === undefined) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } + else if(ax._minDtick) { + // existing minDtick is an integer multiple of newDiff + // (within rounding err) + // and forceTick0 can be shifted to newFirst + if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && + (((newFirst - ax._forceTick0) / newDiff % 1) + + 1.000001) % 1 < 2e-6) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; } - else if((dtick >= __ONEDAY_213 && tick0len <= 10) || (dtick >= __ONEDAY_213 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_213 && tick0len <= 16) || (dtick >= __ONEHOUR_213)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_213 && tick0len <= 19) || (dtick >= __ONEMIN_213)) 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; + // 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 + else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || + (((newFirst - ax._forceTick0) / ax._minDtick % 1) + + 1.000001) % 1 > 2e-6) { + ax._minDtick = 0; } } - else if(_$fastIsnumeric_18(dtick) || dtick.charAt(0) === 'L') { - // linear or log (except D1, D2) - var rng = ax.range.map(ax.r2d || Number); - if(!_$fastIsnumeric_18(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])); +// 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), + hasOneAxisChanged = false; - 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; + 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; } } - // D1 or D2 (log) - else 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(_$fastIsnumeric_18(dtick)) return x + axSign * dtick; + return hasOneAxisChanged; +}; - // everything else is a string, one character plus a number - var tType = dtick.charAt(0), - dtSigned = axSign * Number(dtick.substr(1)); +// save a copy of the initial spike visibility +axes.saveShowSpikeInitial = function(gd, overwrite) { + var axList = axes.list(gd, '', true), + hasOneAxisChanged = false, + allSpikesEnabled = 'on'; - // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_171.incrementMonth(x, dtSigned, calendar); + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; - // Log scales: Linear, Digits - else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; + var isNew = (ax._showSpikeInitial === undefined); + var hasChanged = ( + isNew || !( + ax.showspikes === ax._showspikes + ) + ); - // 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, - x2 = x + axSign * 0.01, - frac = _$lib_171.roundUp(_$lib_171.mod(x2, 1), tickset, axrev); + if((isNew) || (overwrite && hasChanged)) { + ax._showSpikeInitial = ax.showspikes; + hasOneAxisChanged = true; + } - return Math.floor(x2) + - Math.log(_$d3_15.round(Math.pow(10, frac), 1)) / Math.LN10; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } - else throw 'unrecognized dtick ' + String(dtick); + gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + return hasOneAxisChanged; }; -// calculate the first tick on an axis -axes.tickFirst = function(ax) { - var r2l = ax.r2l || Number, - rng = _$lib_171.simpleMap(ax.range, r2l), - axrev = rng[1] < rng[0], - sRound = axrev ? Math.floor : Math.ceil, - // add a tiny extra bit to make sure we get ticks - // that may have been rounded out - r0 = rng[0] * 1.0001 - rng[1] * 0.0001, - dtick = ax.dtick, - tick0 = r2l(ax.tick0); +axes.autoBin = function(data, ax, nbins, is2d, calendar) { + var dataMin = _$lib_172.aggNums(Math.min, null, data), + dataMax = _$lib_172.aggNums(Math.max, null, data); - if(_$fastIsnumeric_18(dtick)) { - var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; + if(!calendar) calendar = ax.calendar; - // make sure no ticks outside the category list - if(ax.type === 'category') { - tmin = _$lib_171.constrain(tmin, 0, ax._categories.length - 1); - } - return tmin; + if(ax.type === 'category') { + return { + start: dataMin - 0.5, + end: dataMax + 0.5, + size: 1, + _dataSpan: dataMax - dataMin, + }; } - var tType = dtick.charAt(0), - dtNum = Number(dtick.substr(1)); - - // Dates: months (or years) - if(tType === 'M') { - var cnt = 0, - t0 = tick0, - t1, - mult, - newDTick; + 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_172.distinctVals(data), + msexp = Math.pow(10, Math.floor( + Math.log(distinctData.minDiff) / Math.LN10)), + minSize = msexp * _$lib_172.roundUp( + distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); + size0 = Math.max(minSize, 2 * _$lib_172.stdev(data) / + Math.pow(data.length, is2d ? 0.25 : 0.4)); - // 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_171.error('tickFirst did not converge', ax); - return t0; + // fallback if ax.d2c output BADNUMs + // e.g. when user try to plot categorical bins + // on a layout.xaxis.type: 'linear' + if(!_$fastIsnumeric_18(size0)) size0 = 1; } - // Log scales: Linear, Digits - else if(tType === 'L') { - return Math.log(sRound( - (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + // piggyback off autotick code to make "nice" bin sizes + var dummyAx; + if(ax.type === 'log') { + dummyAx = { + type: 'linear', + range: [dataMin, dataMax] + }; } - else if(tType === 'D') { - var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_171.roundUp(_$lib_171.mod(r0, 1), tickset, axrev); - - return Math.floor(r0) + - Math.log(_$d3_15.round(Math.pow(10, frac), 1)) / Math.LN10; + else { + dummyAx = { + type: ax.type, + range: _$lib_172.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + calendar: calendar + }; } - else throw 'unrecognized dtick ' + String(dtick); -}; + axes.setConvert(dummyAx); -// 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) { - var out = tickTextObj(ax, x), - hideexp, - arrayMode = ax.tickmode === 'array', - extraPrecision = hover || arrayMode, - i, - tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; + axes.autoTicks(dummyAx, size0); + var binStart = axes.tickIncrement( + axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); + var binEnd, bincount; - if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_171.simpleMap(ax.range, ax.r2l), - 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; + // 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 dummyAx.dtick === 'number') { + binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + + bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); + binEnd = binStart + bincount * dummyAx.dtick; + } + 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, dummyAx.dtick, dataMin, calendar); } - if(i < ax.ticktext.length) { - out.text = String(ax.ticktext[i]); - return out; + + // 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, dummyAx.dtick, false, calendar); + bincount++; } } - function isHidden(showAttr) { - var first_or_last; - - if(showAttr === undefined) return true; - if(hover) return showAttr === 'none'; + return { + start: ax.c2r(binStart, 0, calendar), + end: ax.c2r(binEnd, 0, calendar), + size: dummyAx.dtick, + _dataSpan: dataMax - dataMin + }; +}; - first_or_last = { - first: ax._tmin, - last: ax._tmax - }[showAttr]; - return showAttr !== 'all' && x !== first_or_last; - } +function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { + var edgecount = 0, + midcount = 0, + intcount = 0, + blankCount = 0; - if(hover) { - hideexp = 'never'; - } else { - hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; + function nearEdge(v) { + // is a value within 1% of a bin edge? + return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; } - if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); - else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); - else if(ax.type === 'category') formatCategory(ax, out); - else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); - else formatLinear(ax, out, hover, extraPrecision, hideexp); - - // add prefix and suffix - if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; - if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; + for(var i = 0; i < data.length; i++) { + if(data[i] % 1 === 0) intcount++; + else if(!_$fastIsnumeric_18(data[i])) blankCount++; - return out; -}; + if(nearEdge(data[i])) edgecount++; + if(nearEdge(data[i] + ax.dtick / 2)) midcount++; + } + var dataCount = data.length - blankCount; -/** - * 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_213 && val2 !== val) { - return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); + if(intcount === dataCount && ax.type !== 'date') { + // 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 + if(ax.dtick < 1) { + binStart = dataMin - 0.5 * ax.dtick; + } + // 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. + else { + binStart -= 0.5; + if(binStart + ax.dtick < dataMin) binStart += ax.dtick; + } } - - 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; + 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; +} - // 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 || {}; +function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { + var stats = _$lib_172.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; - return { - x: x, - dx: 0, - dy: 0, - text: text || '', - fontSize: tf.size, - font: tf.family, - fontColor: tf.color - }; -} + if(stats.exactDays > threshold) { + var numMonths = Number(dtick.substr(1)); -function formatDate(ax, out, hover, extraPrecision) { - var tr = ax._tickround, - fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); + 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_214 * 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_214 * 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_214 / 2; + } + var nextBinStart = axes.tickIncrement(binStart, dtick); - if(extraPrecision) { - // second or sub-second precision: extra always shows max digits. - // for other fields, extra precision just adds one field. - if(_$fastIsnumeric_18(tr)) tr = 4; - else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + if(nextBinStart <= dataMin) return nextBinStart; } + return binStart; +} - var dateStr = _$lib_171.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), - headStr; +// ---------------------------------------------------- +// Ticks and grids +// ---------------------------------------------------- - var splitIndex = dateStr.indexOf('\n'); - if(splitIndex !== -1) { - headStr = dateStr.substr(splitIndex + 1); - dateStr = dateStr.substr(0, splitIndex); - } +// ensure we have tick0, dtick, and tick rounding calculated +axes.prepTicks = function(ax) { + var rng = _$lib_172.simpleMap(ax.range, ax.r2l); - 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!) + // calculate max number of (auto) ticks to display based on plot size + if(ax.tickmode === 'auto' || !ax.dtick) { + var nt = ax.nticks, + minPx; + if(!nt) { + if(ax.type === 'category') { + 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_172.constrain(ax._length / minPx, 4, 9) + 1; + } - // can we remove the whole time part? - if(dateStr === '00:00:00' || dateStr === '00:00') { - dateStr = headStr; - headStr = ''; + // radial axes span half their domain, + // multiply nticks value by two to get correct number of auto ticks. + if(ax._name === 'radialaxis') nt *= 2; } - 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$/, ''); + + // 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); } } - 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; - } + // check for missing tick0 + if(!ax.tick0) { + ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; } - out.text = dateStr; -} + // now figure out rounding of tick values + autoTickRound(ax); +}; -function formatLog(ax, out, hover, extraPrecision, hideexp) { - var dtick = ax.dtick, - x = out.x, - tickformat = ax.tickformat; +// 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_172.simpleMap(ax.range, ax.r2l); - 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 = ''; - } + // 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); - if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; + // find the first tick + ax._tmin = axes.tickFirst(ax); - if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { - out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); - } - else if(_$fastIsnumeric_18(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_171.mod(x + 0.01, 1) < 0.1))) { - var p = Math.round(x); - if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || - (isSIFormat(ax.exponentformat) && beyondSI(p))) { - if(p === 0) out.text = 1; - else if(p === 1) out.text = '10'; - else if(p > 1) out.text = '10' + p + ''; - else out.text = '10' + MINUS_SIGN + -p + ''; + // 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]); - out.fontSize *= 1.25; - } - else { - out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover'); - if(dtick === 'D1' && ax._id.charAt(0) === 'y') { - out.dy -= out.fontSize / 6; - } - } + // 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 vals = []; + if(ax.type === 'category') { + endTick = (axrev) ? Math.max(-0.5, endTick) : + Math.min(ax._categories.length - 0.5, endTick); } - else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_171.mod(x, 1)))); - out.fontSize *= 0.75; + + 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(vals.length > maxTicks || x === xPrevious) break; + xPrevious = x; + + vals.push(x); } - 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); - } - } + // If same angle over a full circle, the last tick vals is a duplicate. + // TODO must do something similar for angular date axes. + if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { + vals.pop(); } -} -function formatCategory(ax, out) { - var tt = ax._categories[Math.round(out.x)]; - if(tt === undefined) tt = ''; - out.text = String(tt); -} + // save the last tick as well as first, so we can + // show the exponent only on the last one + ax._tmax = vals[vals.length - 1]; -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); -} + // 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; -function formatAngle(ax, out, hover, extraPrecision, hideexp) { - if(ax.thetaunit === 'radians' && !hover) { - var num = out.x / 180; + var ticksOut = new Array(vals.length); + for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); - if(num === 0) { - out.text = '0'; - } else { - var frac = num2frac(num); + ax._inCalcTicks = false; - if(frac[1] >= 100) { - out.text = numFormat(_$lib_171.deg2rad(out.x), ax, hideexp, extraPrecision); - } else { - var isNeg = out.x < 0; + return ticksOut; +}; - if(frac[1] === 1) { - if(frac[0] === 1) out.text = 'π'; - else out.text = frac[0] + 'π'; - } else { - out.text = [ - '', frac[0], '', - '⁄', - '', frac[1], '', - 'π' - ].join(''); - } +function arrayTicks(ax) { + var vals = ax.tickvals, + text = ax.ticktext, + ticksOut = new Array(vals.length), + rng = _$lib_172.simpleMap(ax.range, ax.r2l), + r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, + r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, + tickMin = Math.min(r0expanded, r1expanded), + tickMax = Math.max(r0expanded, r1expanded), + vali, + i, + j = 0; - if(isNeg) out.text = MINUS_SIGN + out.text; - } - } - } else { - out.text = numFormat(out.x, ax, hideexp, extraPrecision); - } -} + // 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 = []; -// 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; - } + // make sure showing ticks doesn't accidentally add new categories + var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - function findGCD(a, b) { - return almostEq(b, 0) ? a : findGCD(b, a % b); + // 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); } - function findPrecision(n) { - var e = 1; - while(!almostEq(Math.round(n * e) / e, n)) { - e *= 10; + for(i = 0; i < vals.length; i++) { + 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++; } - return e; } - var precision = findPrecision(num); - var number = num * precision; - var gcd = Math.abs(findGCD(number, precision)); + if(j < vals.length) ticksOut.splice(j, vals.length - j); - return [ - // numerator - Math.round(number / gcd), - // denominator - Math.round(precision / gcd) - ]; + return ticksOut; } -// 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'; -} +var roundBase10 = [2, 5, 10], + roundBase24 = [1, 2, 3, 6, 12], + roundBase60 = [1, 2, 5, 10, 15, 30], + // 2&3 day ticks are weird, but need something btwn 1&7 + 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 + roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], + roundLog2 = [-0.301, 0, 0.301, 0.699, 1], + // N.B. `thetaunit; 'radians' angular axes must be converted to degrees + roundAngles = [15, 30, 45, 90, 180]; -// 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 roundDTick(roughDTick, base, roundingSet) { + return base * _$lib_172.roundUp(roughDTick / base, roundingSet); } -function numFormat(v, ax, fmtoverride, hover) { - // negative? - var isNeg = v < 0, - // max number of digits past decimal point to show - tickRound = ax._tickround, - exponentFormat = fmtoverride || ax.exponentformat || 'B', - exponent = ax._tickexponent, - tickformat = axes.getTickFormat(ax), - separatethousands = ax.separatethousands; +// 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; - // 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 : - (_$fastIsnumeric_18(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; + function getBase(v) { + return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); } - 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; + if(ax.type === 'date') { + ax.tick0 = _$lib_172.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; - // 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; + if(roughX2 > ONEAVGYEAR) { + roughDTick /= ONEAVGYEAR; + base = getBase(10); + ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10)); } - // 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 if(roughX2 > ONEAVGMONTH) { + roughDTick /= ONEAVGMONTH; + ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); + } + else if(roughX2 > __ONEDAY_214) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_214, 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_172.dateTick0(ax.calendar, true); + } + else if(roughX2 > __ONEHOUR_214) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_214, roundBase24); + } + else if(roughX2 > __ONEMIN_214) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_214, roundBase60); + } + else if(roughX2 > __ONESEC_214) { + ax.dtick = roundDTick(roughDTick, __ONESEC_214, roundBase60); } else { - v = String(v); - var dp = v.indexOf('.') + 1; - if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); + // milliseconds + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); } - // insert appropriate decimal point and thousands separator - v = _$lib_171.numSeparate(v, ax._separators, separatethousands); } + else if(ax.type === 'log') { + ax.tick0 = 0; + var rng = _$lib_172.simpleMap(ax.range, ax.r2l); - // add exponent - if(exponent && exponentFormat !== 'hide') { - if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; + 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); - var signedExponent; - if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; - else if(exponentFormat !== 'power') signedExponent = '+' + exponent; - else signedExponent = String(exponent); - - if(exponentFormat === 'e') { - v += 'e' + signedExponent; - } - else if(exponentFormat === 'E') { - v += 'E' + signedExponent; - } - else if(exponentFormat === 'power') { - v += '×10' + signedExponent + ''; - } - else if(exponentFormat === 'B' && exponent === 9) { - v += 'B'; + // 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 if(isSIFormat(exponentFormat)) { - v += SIPREFIXES[exponent / 3 + 5]; + 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.tick0 = 0; + ax.dtick = Math.ceil(Math.max(roughDTick, 1)); + } + else if(ax._id === 'angular') { + 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); + } - // 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; + // prevent infinite loops + if(ax.dtick === 0) ax.dtick = 1; - function convertToMs(dtick) { - return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH; + // TODO: this is from log axis histograms with autorange off + if(!_$fastIsnumeric_18(ax.dtick) && typeof ax.dtick !== 'string') { + var olddtick = ax.dtick; + ax.dtick = 1; + throw 'ax.dtick error: ' + String(olddtick); } +}; - 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; - } +// 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(!_$fastIsnumeric_18(dtick) && typeof dtick !== 'string') { + dtick = 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)); + if(ax.type === 'category') { + 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), + tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), + tick0len = tick0str.length; - 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); + 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_214 && tick0len <= 10) || (dtick >= __ONEDAY_214 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_214 && tick0len <= 16) || (dtick >= __ONEHOUR_214)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_214 && tick0len <= 19) || (dtick >= __ONEMIN_214)) 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; + } } + else if(_$fastIsnumeric_18(dtick) || dtick.charAt(0) === 'L') { + // linear or log (except D1, D2) + var rng = ax.range.map(ax.r2d || Number); + if(!_$fastIsnumeric_18(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 tickstop; - if(ax.tickformatstops && ax.tickformatstops.length > 0) { - switch(ax.type) { - case 'date': - case 'linear': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; - } - case 'log': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; + 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); } - default: + else ax._tickexponent = rangeexp; } } - return tickstop ? tickstop.value : ax.tickformat; -}; + // D1 or D2 (log) + else ax._tickround = null; +} -// 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 -axes.getSubplots = function(gd, ax) { - var subplotObj = gd._fullLayout._subplots; - var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); +// 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; - var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; + // includes linear, all dates smaller than month, and pure 10^n in log + if(_$fastIsnumeric_18(dtick)) return x + axSign * dtick; - out.sort(function(a, b) { - var aParts = a.substr(1).split('y'); - var bParts = b.substr(1).split('y'); + // everything else is a string, one character plus a number + var tType = dtick.charAt(0), + dtSigned = axSign * Number(dtick.substr(1)); - if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; - return +aParts[0] - +bParts[0]; - }); + // Dates: months (or years - see Lib.incrementMonth) + if(tType === 'M') return _$lib_172.incrementMonth(x, dtSigned, calendar); - return out; -}; + // Log scales: Linear, Digits + else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; -// find all subplots with axis 'ax' -axes.findSubplotsWithAxis = function(subplots, ax) { - var axMatch = new RegExp( - (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') - ); - var subplotsWithAxis = []; + // 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, + x2 = x + axSign * 0.01, + frac = _$lib_172.roundUp(_$lib_172.mod(x2, 1), tickset, axrev); - for(var i = 0; i < subplots.length; i++) { - var sp = subplots[i]; - if(axMatch.test(sp)) subplotsWithAxis.push(sp); + return Math.floor(x2) + + Math.log(_$d3_15.round(Math.pow(10, frac), 1)) / Math.LN10; } - - return subplotsWithAxis; + else throw 'unrecognized dtick ' + String(dtick); }; -// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings -axes.makeClipPaths = function(gd) { - var fullLayout = gd._fullLayout; - 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; +// calculate the first tick on an axis +axes.tickFirst = function(ax) { + var r2l = ax.r2l || Number, + rng = _$lib_172.simpleMap(ax.range, r2l), + axrev = rng[1] < rng[0], + sRound = axrev ? Math.floor : Math.ceil, + // add a tiny extra bit to make sure we get ticks + // that may have been rounded out + r0 = rng[0] * 1.0001 - rng[1] * 0.0001, + dtick = ax.dtick, + tick0 = r2l(ax.tick0); - 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]}); + if(_$fastIsnumeric_18(dtick)) { + var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; + + // make sure no ticks outside the category list + if(ax.type === 'category') { + tmin = _$lib_172.constrain(tmin, 0, ax._categories.length - 1); } + return tmin; } - // 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'); + var tType = dtick.charAt(0), + dtNum = Number(dtick.substr(1)); - axClips.exit().remove(); + // Dates: months (or years) + if(tType === 'M') { + var cnt = 0, + t0 = tick0, + t1, + mult, + newDTick; - axClips.each(function(d) { - _$d3_15.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 - }); - }); -}; + // 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_172.error('tickFirst did not converge', ax); + return t0; + } -// doTicks: draw ticks, grids, and tick labels -// axid: 'x', 'y', 'x2' etc, -// blank to do all, -// 'redraw' to force full redraw, and reset: -// ax._r (stored range for use by zoom/pan) -// ax._rl (stored linearized range for use by zoom/pan) -// or can pass in an axis object directly -axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + // Log scales: Linear, Digits + else if(tType === 'L') { + return Math.log(sRound( + (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + } + else if(tType === 'D') { + var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, + frac = _$lib_172.roundUp(_$lib_172.mod(r0, 1), tickset, axrev); - // allow passing an independent axis object instead of id - if(typeof axid === 'object') { - ax = axid; - axid = ax._id; - independent = true; + return Math.floor(r0) + + Math.log(_$d3_15.round(Math.pow(10, frac), 1)) / Math.LN10; } - else { - ax = axes.getFromId(gd, axid); + else throw 'unrecognized dtick ' + String(dtick); +}; - if(axid === 'redraw') { - fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); - fullLayout._infolayer.select('.g-' + xa._id + 'title').remove(); - fullLayout._infolayer.select('.g-' + ya._id + 'title').remove(); - }); - } +// 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) { + var out = tickTextObj(ax, x), + hideexp, + arrayMode = ax.tickmode === 'array', + extraPrecision = hover || arrayMode, + i, + tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - if(!axid || axid === 'redraw') { - return _$lib_171.syncOrAsync(axes.list(gd, '', true).map(function(ax) { - return function() { - if(!ax._id) return; - var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_171.simpleMap(ax._r, ax.r2l); - } - return axDone; - }; - })); + if(arrayMode && Array.isArray(ax.ticktext)) { + var rng = _$lib_172.simpleMap(ax.range, ax.r2l), + 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; } } - // set scaling to pixels - ax.setScale(); + function isHidden(showAttr) { + var first_or_last; - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_76.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_76.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_76.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + if(showAttr === undefined) return true; + if(hover) return showAttr === 'none'; - if(ax._counterangle && ax.ticks === 'outside') { - var caRad = ax._counterangle * Math.PI / 180; - labelStandoff = ax.ticklen * Math.cos(caRad) + 1; - labelShift = ax.ticklen * Math.sin(caRad); - } + first_or_last = { + first: ax._tmin, + last: ax._tmax + }[showAttr]; - if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { - labelStandoff += 0.2 * ax.tickfont.size; + return showAttr !== 'all' && x !== first_or_last; } - // positioning arguments for x vs y axes - if(axLetter === 'x') { - sides = ['bottom', 'top']; - transfn = ax._transfn || function(d) { - return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); - } - else return 'M0,' + shift + 'v' + len; - }; - } - else if(axLetter === 'y') { - sides = ['left', 'right']; - transfn = ax._transfn || function(d) { - return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); - } - else return 'M' + shift + ',0h' + len; - }; - } - else if(axid === 'angular') { - sides = ['left', 'right']; - transfn = ax._transfn; - tickpathfn = function(shift, len) { - return 'M' + shift + ',0h' + len; - }; - } - else { - _$lib_171.warn('Unrecognized doTicks axis:', axid); - return; - } - var axside = ax.side || sides[0], - // which direction do the side[0], side[1], and free ticks go? - // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; - if((ax.ticks !== 'inside') === (axLetter === 'x')) { - ticksign = ticksign.map(function(v) { return -v; }); + if(hover) { + hideexp = 'never'; + } else { + hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; } - if(!ax.visible) return; + if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); + else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); + else if(ax.type === 'category') formatCategory(ax, out); + else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); + else formatLinear(ax, out, hover, extraPrecision, hideexp); - if(ax._tickFilter) { - vals = vals.filter(ax._tickFilter); - } + // add prefix and suffix + if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; + if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; - // remove zero lines, grid lines, and inside ticks if they're within - // 1 pixel of the end - // The key case here is removing zero lines when the axis bound is zero. - function clipEnds(d) { - var p = ax.l2p(d.x); - return (p > 1 && p < ax._length - 1); - } - var valsClipped = vals.filter(clipEnds); + return out; +}; - // don't clip angular values - if(ax._id === 'angular') { - valsClipped = vals; +/** + * 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_214 && val2 !== val) { + return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } - function drawTicks(container, tickpath) { - var ticks = container.selectAll('path.' + tcls) - .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); - if(tickpath && ax.ticks) { - ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) - .classed('crisp', 1) - .call(_$color_51.stroke, ax.tickcolor) - .style('stroke-width', tickWidth + 'px') - .attr('d', tickpath); - ticks.attr('transform', transfn); - ticks.exit().remove(); - } - else ticks.remove(); + 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; } - function drawLabels(container, position) { - // tick labels - for now just the main labels. - // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + // 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; +}; - if(!_$fastIsnumeric_18(position)) { - tickLabels.remove(); - drawAxTitle(); - return; - } - if(!ax.showticklabels) { - tickLabels.remove(); - drawAxTitle(); - calcBoundingBox(); - return; - } +function tickTextObj(ax, x, text) { + var tf = ax.tickfont || {}; - var labelx, labely, labelanchor, labelpos0, flipit; - if(axLetter === 'x') { - flipit = (axside === 'bottom') ? 1 : -1; - labelx = function(d) { return d.dx + labelShift * flipit; }; - labelpos0 = position + (labelStandoff + pad) * flipit; - labely = function(d) { - return d.dy + labelpos0 + d.fontSize * - ((axside === 'bottom') ? 1 : -0.2); - }; - labelanchor = function(angle) { - if(!_$fastIsnumeric_18(angle) || angle === 0 || angle === 180) { - return 'middle'; - } - return (angle * flipit < 0) ? 'end' : 'start'; - }; - } - else if(axLetter === 'y') { - flipit = (axside === 'right') ? 1 : -1; - labely = function(d) { - return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; - }; - labelx = function(d) { - return d.dx + position + (labelStandoff + pad + - ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; - }; - labelanchor = function(angle) { - if(_$fastIsnumeric_18(angle) && Math.abs(angle) === 90) { - return 'middle'; - } - return axside === 'right' ? 'start' : 'end'; - }; - } - else if(axid === 'angular') { - ax._labelShift = labelShift; - ax._labelStandoff = labelStandoff; - ax._pad = pad; + return { + x: x, + dx: 0, + dy: 0, + text: text || '', + fontSize: tf.size, + font: tf.family, + fontColor: tf.color + }; +} - labelx = ax._labelx; - labely = ax._labely; - labelanchor = ax._labelanchor; - } +function formatDate(ax, out, hover, extraPrecision) { + var tr = ax._tickround, + fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); - var maxFontSize = 0, - autoangle = 0, - labelsReady = []; - tickLabels.enter().append('g').classed(tcls, 1) - .append('text') - // only so tex has predictable alignment that we can - // alter later - .attr('text-anchor', 'middle') - .each(function(d) { - var thisLabel = _$d3_15.select(this), - newPromise = gd._promises.length; - thisLabel - .call(_$svg_text_utils_192.positionText, labelx(d), labely(d)) - .call(_$drawing_76.font, d.font, d.fontSize, d.fontColor) - .text(d.text) - .call(_$svg_text_utils_192.convertToTspans, gd); - newPromise = gd._promises[newPromise]; - if(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, ax.tickangle); - })); - } - else { - // sync label: just position it now. - positionLabels(thisLabel, ax.tickangle); - } - }); - tickLabels.exit().remove(); + if(extraPrecision) { + // second or sub-second precision: extra always shows max digits. + // for other fields, extra precision just adds one field. + if(_$fastIsnumeric_18(tr)) tr = 4; + else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + } - tickLabels.each(function(d) { - maxFontSize = Math.max(maxFontSize, d.fontSize); - }); + var dateStr = _$lib_172.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + headStr; - if(axid === 'angular') { - tickLabels.each(function(d) { - _$d3_15.select(this).select('text') - .call(_$svg_text_utils_192.positionText, labelx(d), labely(d)); - }); - } + var splitIndex = dateStr.indexOf('\n'); + if(splitIndex !== -1) { + headStr = dateStr.substr(splitIndex + 1); + dateStr = dateStr.substr(0, splitIndex); + } - // How much to shift a multi-line label to center it vertically. - function getAnchorHeight(lineCount, lineHeight, angle) { - var h = (lineCount - 1) * lineHeight; - if(axLetter === 'x') { - if(angle < -60 || 60 < angle) { - return -0.5 * h; - } else if(axside === 'top') { - return -h; - } - } else { - angle *= axside === 'left' ? 1 : -1; - if(angle < -30) { - return -h; - } else if(angle < 30) { - return -0.5 * h; - } - } - return 0; + 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$/, ''); } + } - function positionLabels(s, angle) { - s.each(function(d) { - var anchor = labelanchor(angle, d); - var thisLabel = _$d3_15.select(this), - mathjaxGroup = thisLabel.select('.text-math-group'), - transform = transfn.call(thisLabel.node(), d) + - ((_$fastIsnumeric_18(angle) && +angle !== 0) ? - (' rotate(' + angle + ',' + labelx(d) + ',' + - (labely(d) - d.fontSize / 2) + ')') : - ''); - var anchorHeight = getAnchorHeight( - _$svg_text_utils_192.lineCount(thisLabel), - __LINE_SPACING_213 * d.fontSize, - _$fastIsnumeric_18(angle) ? +angle : 0); - if(anchorHeight) { - transform += ' translate(0, ' + anchorHeight + ')'; - } - if(mathjaxGroup.empty()) { - thisLabel.select('text').attr({ - transform: transform, - 'text-anchor': anchor - }); - } - else { - var mjShift = - _$drawing_76.bBox(mathjaxGroup.node()).width * - {end: -0.5, start: 0.5}[anchor]; - mathjaxGroup.attr('transform', transform + - (mjShift ? 'translate(' + mjShift + ',0)' : '')); - } - }); + 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; } + } - // 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, ax._lastangle || ax.tickangle); + out.text = dateStr; +} - function allLabelsReady() { - return labelsReady.length && Promise.all(labelsReady); - } +function formatLog(ax, out, hover, extraPrecision, hideexp) { + var dtick = ax.dtick, + x = out.x, + tickformat = ax.tickformat; - function fixLabelOverlaps() { - positionLabels(tickLabels, ax.tickangle); + 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 = ''; + } - // check for auto-angling if x labels overlap - // don't auto-angle at all for log axes with - // base and digit format - if(axLetter === 'x' && !_$fastIsnumeric_18(ax.tickangle) && - (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { - var lbbArray = []; - tickLabels.each(function(d) { - var s = _$d3_15.select(this), - thisLabel = s.select('.text-math-group'), - x = ax.l2p(d.x); - if(thisLabel.empty()) thisLabel = s.select('text'); + if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; - var bb = _$drawing_76.bBox(thisLabel.node()); + if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { + out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); + } + else if(_$fastIsnumeric_18(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_172.mod(x + 0.01, 1) < 0.1))) { + var p = Math.round(x); + if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || + (isSIFormat(ax.exponentformat) && beyondSI(p))) { + if(p === 0) out.text = 1; + else if(p === 1) out.text = '10'; + else if(p > 1) out.text = '10' + p + ''; + else out.text = '10' + MINUS_SIGN + -p + ''; - 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 - }); - }); - for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_171.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { - // any overlap at all - set 30 degrees - autoangle = 30; - break; - } - } - if(autoangle) { - var tickspacing = Math.abs( - (vals[vals.length - 1].x - vals[0].x) * ax._m - ) / (vals.length - 1); - if(tickspacing < maxFontSize * 2.5) { - autoangle = 90; - } - positionLabels(tickLabels, autoangle); - } - ax._lastangle = autoangle; + out.fontSize *= 1.25; + } + 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(dtick.charAt(0) === 'D') { + out.text = String(Math.round(Math.pow(10, _$lib_172.mod(x, 1)))); + out.fontSize *= 0.75; + } + else throw 'unrecognized dtick ' + String(dtick); - // update the axis title - // (so it can move out of the way if needed) - // TODO: separate out scoot so we don't need to do - // a full redraw of the title (mostly relevant for MathJax) - drawAxTitle(); - return axid + ' done'; + // 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 calcBoundingBox() { - if(ax.showticklabels) { - var gdBB = gd.getBoundingClientRect(); - var bBox = container.node().getBoundingClientRect(); +function formatCategory(ax, out) { + var tt = ax._categories[Math.round(out.x)]; + if(tt === undefined) tt = ''; + out.text = String(tt); +} - /* - * the way we're going to use this, the positioning that matters - * is relative to the origin of gd. This is important particularly - * if gd is scrollable, and may have been scrolled between the time - * we calculate this and the time we use it - */ +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); +} - ax._boundingBox = { - width: bBox.width, - height: bBox.height, - left: bBox.left - gdBB.left, - right: bBox.right - gdBB.left, - top: bBox.top - gdBB.top, - bottom: bBox.bottom - gdBB.top - }; - } else { - var gs = fullLayout._size; - var pos; +function formatAngle(ax, out, hover, extraPrecision, hideexp) { + if(ax.thetaunit === 'radians' && !hover) { + var num = out.x / 180; - // set dummy bbox for ticklabel-less axes + if(num === 0) { + out.text = '0'; + } else { + var frac = num2frac(num); - if(axLetter === 'x') { - pos = ax.anchor === 'free' ? - gs.t + gs.h * (1 - ax.position) : - gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); + if(frac[1] >= 100) { + out.text = numFormat(_$lib_172.deg2rad(out.x), ax, hideexp, extraPrecision); + } else { + var isNeg = out.x < 0; - ax._boundingBox = { - top: pos, - bottom: pos, - left: ax._offset, - right: ax._offset + ax._length, - width: ax._length, - height: 0 - }; + if(frac[1] === 1) { + if(frac[0] === 1) out.text = 'π'; + else out.text = frac[0] + 'π'; } else { - pos = ax.anchor === 'free' ? - gs.l + gs.w * ax.position : - gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - - ax._boundingBox = { - left: pos, - right: pos, - bottom: ax._offset + ax._length, - top: ax._offset, - height: ax._length, - width: 0 - }; - } - } - - /* - * for spikelines: what's the full domain of positions in the - * opposite direction that are associated with this axis? - * This means any axes that we make a subplot with, plus the - * position of the axis itself if it's free. - */ - if(subplots) { - var fullRange = ax._counterSpan = [Infinity, -Infinity]; - - for(i = 0; i < subplots.length; i++) { - var subplot = fullLayout._plots[subplots[i]]; - var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - - extendRange(fullRange, [ - counterAxis._offset, - counterAxis._offset + counterAxis._length - ]); - } - - if(ax.anchor === 'free') { - extendRange(fullRange, (axLetter === 'x') ? - [ax._boundingBox.bottom, ax._boundingBox.top] : - [ax._boundingBox.right, ax._boundingBox.left]); + out.text = [ + '', frac[0], '', + '⁄', + '', frac[1], '', + 'π' + ].join(''); } - } - function extendRange(range, newRange) { - range[0] = Math.min(range[0], newRange[0]); - range[1] = Math.max(range[1], newRange[1]); + if(isNeg) out.text = MINUS_SIGN + out.text; } } + } else { + out.text = numFormat(out.x, ax, hideexp, extraPrecision); + } +} - function doAutoMargins() { - if(!ax.automargin) { return; } - if(axLetter !== 'x' && axLetter !== 'y') { return; } +// 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; + } - var s = ax.side[0]; - var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; + function findGCD(a, b) { + return almostEq(b, 0) ? a : findGCD(b, a % b); + } - if(axLetter === 'x') { - push.y = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 't' ? 1 : 0]); - push[s] += ax._boundingBox.height; - } - else { - push.x = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 'r' ? 1 : 0]); - push[s] += ax._boundingBox.width; - } + function findPrecision(n) { + var e = 1; + while(!almostEq(Math.round(n * e) / e, n)) { + e *= 10; + } + return e; + } - if(ax.title !== fullLayout._dfltTitle[axLetter]) { - push[s] += ax.titlefont.size; - } + var precision = findPrecision(num); + var number = num * precision; + var gcd = Math.abs(findGCD(number, precision)); - var pushKey = ax._name + '.automargin'; - var prevPush = fullLayout._pushmargin[pushKey]; - if(!prevPush || prevPush[s].size < push[s]) { - _$plots_246.autoMargin(gd, pushKey, push); - } - } + return [ + // numerator + Math.round(number / gcd), + // denominator + Math.round(precision / gcd) + ]; +} - var done = _$lib_171.syncOrAsync([ - allLabelsReady, - fixLabelOverlaps, - calcBoundingBox, - doAutoMargins - ]); - if(done && done.then) gd._promises.push(done); - return done; - } +// 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 drawAxTitle() { - if(skipTitle) return; +function isSIFormat(exponentFormat) { + return exponentFormat === 'SI' || exponentFormat === 'B'; +} - // now this only applies to regular cartesian axes; colorbars and - // others ALWAYS call doTicks with skipTitle=true so they can - // configure their own titles. - var ax = _$axis_ids_216.getFromId(gd, axid); +// 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; +} - // rangeslider takes over a bottom title so drop it here - if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; +function numFormat(v, ax, fmtoverride, hover) { + // negative? + var isNeg = v < 0, + // max number of digits past decimal point to show + tickRound = ax._tickround, + exponentFormat = fmtoverride || ax.exponentformat || 'B', + exponent = ax._tickexponent, + tickformat = axes.getTickFormat(ax), + separatethousands = ax.separatethousands; - var avoidSelection = _$d3_15.select(gd).selectAll('g.' + axid + 'tick'); - var avoid = { - selection: avoidSelection, - side: ax.side + // 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 : + (_$fastIsnumeric_18(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] }; - var axLetter = axid.charAt(0); - var gs = gd._fullLayout._size; - var offsetBase = 1.5; - var fontSize = ax.titlefont.size; - - var transform, counterAxis, x, y; + autoTickRound(ah); + tickRound = (Number(ah._tickround) || 0) + 4; + exponent = ah._tickexponent; + if(ax.hoverformat) tickformat = ax.hoverformat; + } - if(avoidSelection.size()) { - var translation = _$drawing_76.getTranslate(avoidSelection.node().parentNode); - avoid.offsetLeft = translation.x; - avoid.offsetTop = translation.y; - } + if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); - var titleStandoff = 10 + fontSize * offsetBase + - (ax.linewidth ? ax.linewidth - 1 : 0); - - if(axLetter === 'x') { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_216.getFromId(gd, ax.anchor); - - x = ax._offset + ax._length / 2; + // 'epsilon' - rounding increment + var e = Math.pow(10, -tickRound) / 2; - if(ax.side === 'top') { - y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); - } - else { - y = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1.5 : 0.5); - } - y += counterAxis._offset; + // 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; - if(!avoid.side) avoid.side = 'bottom'; + // 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 { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_216.getFromId(gd, ax.anchor); + 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_172.numSeparate(v, ax._separators, separatethousands); + } - y = ax._offset + ax._length / 2; - if(ax.side === 'right') { - x = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1 : 0.5); - } - else { - x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); - } - x += counterAxis._offset; + // add exponent + if(exponent && exponentFormat !== 'hide') { + if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; - transform = {rotate: '-90', offset: 0}; - if(!avoid.side) avoid.side = 'left'; - } + var signedExponent; + if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; + else if(exponentFormat !== 'power') signedExponent = '+' + exponent; + else signedExponent = String(exponent); - _$titles_144.draw(gd, axid + 'title', { - propContainer: ax, - propName: ax._name + '.title', - placeholder: fullLayout._dfltTitle[axLetter], - avoid: avoid, - transform: transform, - attributes: {x: x, y: y, 'text-anchor': 'middle'} - }); + if(exponentFormat === 'e') { + v += 'e' + signedExponent; + } + else if(exponentFormat === 'E') { + v += 'E' + 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]; + } } - function traceHasBarsOrFill(trace, subplot) { - if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_261.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; - return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; - } + // 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; +} - function drawGrid(plotinfo, counteraxis, subplot) { - var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); - var zlcontainer = plotinfo.zerolinelayer; - var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; - var gridpath = ax._gridpath || ((axLetter === 'x' ? - ('M0,' + counteraxis._offset + 'v') : - ('M' + counteraxis._offset + ',0h') - ) + counteraxis._length); - var grid = gridcontainer.selectAll('path.' + gcls) - .data((ax.showgrid === false) ? [] : gridvals, datafn); - grid.enter().append('path').classed(gcls, 1) - .classed('crisp', 1) - .attr('d', gridpath) - .each(function(d) { - if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && - Math.abs(d.x) < ax.dtick / 100) { - _$d3_15.select(this).remove(); - } - }); - grid.attr('transform', transfn) - .call(_$color_51.stroke, ax.gridcolor || '#ddd') - .style('stroke-width', gridWidth + 'px'); - if(typeof gridpath === 'function') grid.attr('d', gridpath); - grid.exit().remove(); +axes.getTickFormat = function(ax) { + var i; - // zero line - if(zlcontainer) { - var hasBarsOrFill = false; - for(var i = 0; i < gd._fullData.length; i++) { - if(traceHasBarsOrFill(gd._fullData[i], subplot)) { - hasBarsOrFill = true; - break; + 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; } } - var rng = _$lib_171.simpleMap(ax.range, ax.r2l), - showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && - (ax.type === 'linear' || ax.type === '-') && gridvals.length && - (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); - var zl = zlcontainer.selectAll('path.' + zcls) - .data(showZl ? [{x: 0, id: axid}] : []); - zl.enter().append('path').classed(zcls, 1).classed('zl', 1) - .classed('crisp', 1) - .attr('d', gridpath) - .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. - zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_216.idSort(da.id, db.id); - }); - }); - zl.attr('transform', transfn) - .call(_$color_51.stroke, ax.zerolinecolor || _$color_51.defaultLine) - .style('stroke-width', zeroLineWidth + 'px'); - zl.exit().remove(); + } else { + return typeof left === 'number' ? 1 : -1; } } - if(independent) { - drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); - if(ax._counteraxis) { - var fictionalPlotinfo = { - gridlayer: ax._gridlayer, - zerolinelayer: ax._zerolinelayer - }; - drawGrid(fictionalPlotinfo, ax._counteraxis); - } - return drawLabels(ax._axislayer, ax._pos); + 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)); } - else if(fullLayout._has('cartesian')) { - subplots = axes.getSubplots(gd, ax); - - // keep track of which subplots (by main conteraxis) we've already - // drawn grids for, so we don't overdraw overlaying subplots - var finishedGrids = {}; - - subplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; - var counterAxis = plotinfo[counterLetter + 'axis']; - - var mainCounterID = counterAxis._mainAxis._id; - if(finishedGrids[mainCounterID]) return; - finishedGrids[mainCounterID] = 1; - - drawGrid(plotinfo, counterAxis, subplot); - }); - var mainSubplot = ax._mainSubplot; - var mainPlotinfo = fullLayout._plots[mainSubplot]; - var tickSubplots = []; + 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); + } - if(ax.ticks) { - var mainSign = ticksign[2]; - var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); - if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { - tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + var tickstop; + if(ax.tickformatstops && ax.tickformatstops.length > 0) { + switch(ax.type) { + case 'date': + case 'linear': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; } - drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - - tickSubplots = Object.keys(ax._linepositions); + case 'log': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; + } + default: } + } + return tickstop ? tickstop.value : ax.tickformat; +}; - tickSubplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; +// 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 +axes.getSubplots = function(gd, ax) { + var subplotObj = gd._fullLayout._subplots; + var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); - var container = plotinfo[axLetter + 'axislayer']; + var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; - // [bottom or left, top or right] - // free and main are handled above - var linepositions = ax._linepositions[subplot] || []; + out.sort(function(a, b) { + var aParts = a.substr(1).split('y'); + var bParts = b.substr(1).split('y'); - function tickPathSide(sidei) { - var tsign = ticksign[sidei]; - return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); - } + if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; + return +aParts[0] - +bParts[0]; + }); - drawTicks(container, tickPathSide(0) + tickPathSide(1)); - }); + return out; +}; - var mainContainer = mainPlotinfo[axLetter + 'axislayer']; +// find all subplots with axis 'ax' +axes.findSubplotsWithAxis = function(subplots, ax) { + var axMatch = new RegExp( + (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') + ); + var subplotsWithAxis = []; - return drawLabels(mainContainer, ax._mainLinePosition); + for(var i = 0; i < subplots.length; i++) { + var sp = subplots[i]; + if(axMatch.test(sp)) subplotsWithAxis.push(sp); } + + return subplotsWithAxis; }; -// swap all the presentation attributes of the axes showing these traces -axes.swap = function(gd, traces) { - var axGroups = makeAxisGroups(gd, traces); +// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings +axes.makeClipPaths = function(gd) { + var fullLayout = gd._fullLayout; + 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(var i = 0; i < axGroups.length; i++) { - swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + 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]}); + } } -}; -function makeAxisGroups(gd, traces) { - var groups = [], - i, - 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; }); - for(i = 0; i < traces.length; i++) { - var groupsi = [], - xi = gd._fullData[traces[i]].xaxis, - yi = gd._fullData[traces[i]].yaxis; - if(!xi || !yi) continue; // not a 2D cartesian trace? + axClips.enter().append('clipPath') + .classed('axesclip', true) + .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; }) + .append('rect'); - for(j = 0; j < groups.length; j++) { - if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { - groupsi.push(j); - } - } + axClips.exit().remove(); - if(!groupsi.length) { - groups.push({x: [xi], y: [yi]}); - continue; - } + axClips.each(function(d) { + _$d3_15.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 + }); + }); +}; - var group0 = groups[groupsi[0]], - groupj; +// doTicks: draw ticks, grids, and tick labels +// axid: 'x', 'y', 'x2' etc, +// blank to do all, +// 'redraw' to force full redraw, and reset: +// ax._r (stored range for use by zoom/pan) +// ax._rl (stored linearized range for use by zoom/pan) +// or can pass in an axis object directly +axes.doTicks = function(gd, axid, skipTitle) { + var fullLayout = gd._fullLayout; + var ax; + var independent = false; - 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]); + // allow passing an independent axis object instead of id + if(typeof axid === 'object') { + ax = axid; + axid = ax._id; + independent = true; } + else { + ax = axes.getFromId(gd, axid); - return groups; -} + if(axid === 'redraw') { + fullLayout._paper.selectAll('g.subplot').each(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -function mergeAxisGroups(intoSet, fromSet) { - for(var i = 0; i < fromSet.length; i++) { - if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); + }); + } + + if(!axid || axid === 'redraw') { + return _$lib_172.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return function() { + if(!ax._id) return; + var axDone = axes.doTicks(gd, ax._id); + ax._r = ax.range.slice(); + ax._rl = _$lib_172.simpleMap(ax._r, ax.r2l); + return axDone; + }; + })); + } } -} -function swapAxisGroup(gd, xIds, yIds) { - var i, - j, - xFullAxes = [], - yFullAxes = [], - layout = gd.layout; + // set scaling to pixels + ax.setScale(); - 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 axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_76.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_76.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_76.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; - var allAxKeys = Object.keys(xFullAxes[0]), - noSwapAttrs = [ - 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' - ], - numericTypes = ['linear', 'log']; + if(ax._counterangle && ax.ticks === 'outside') { + var caRad = ax._counterangle * Math.PI / 180; + labelStandoff = ax.ticklen * Math.cos(caRad) + 1; + labelShift = ax.ticklen * Math.sin(caRad); + } - for(i = 0; i < allAxKeys.length; i++) { - var keyi = allAxKeys[i], - xVal = xFullAxes[0][keyi], - yVal = yFullAxes[0][keyi], - allEqual = true, - coerceLinearX = false, - 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; + if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { + labelStandoff += 0.2 * ax.tickfont.size; + } + + // positioning arguments for x vs y axes + if(axLetter === 'x') { + sides = ['bottom', 'top']; + transfn = ax._transfn || function(d) { + return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); } - 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 return 'M0,' + shift + 'v' + len; + }; + } + else if(axLetter === 'y') { + sides = ['left', 'right']; + transfn = ax._transfn || function(d) { + return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); } - 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); - } + else return 'M' + shift + ',0h' + len; + }; + } + else if(axid === 'angular') { + sides = ['left', 'right']; + transfn = ax._transfn; + tickpathfn = function(shift, len) { + return 'M' + shift + ',0h' + len; + }; + } + else { + _$lib_172.warn('Unrecognized doTicks axis:', axid); + return; } - // 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_171.swapAttrs(layout.annotations[i], ['?']); - } + var axside = ax.side || sides[0]; + // which direction do the side[0], side[1], and free ticks go? + // then we flip if outside XOR y axis + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + if((ax.ticks !== 'inside') === (axLetter === 'x')) { + ticksign = ticksign.map(function(v) { return -v; }); } -} -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_171.nestedProperty, - xVal = np(layout[xFullAxes[0]._name], key).get(), - yVal = np(layout[yFullAxes[0]._name], key).get(), - i; - if(key === 'title') { - // special handling of placeholder titles - if(xVal === dfltTitle.x) { - xVal = dfltTitle.y; - } - if(yVal === dfltTitle.y) { - yVal = dfltTitle.x; - } - } + if(!ax.visible) return; - for(i = 0; i < xFullAxes.length; i++) { - np(layout, xFullAxes[i]._name + '.' + key).set(yVal); + if(ax._tickFilter) { + vals = vals.filter(ax._tickFilter); } - for(i = 0; i < yFullAxes.length; i++) { - np(layout, yFullAxes[i]._name + '.' + key).set(xVal); + + // remove zero lines, grid lines, and inside ticks if they're within + // 1 pixel of the end + // The key case here is removing zero lines when the axis bound is zero. + function clipEnds(d) { + var p = ax.l2p(d.x); + return (p > 1 && p < ax._length - 1); } -} + var valsClipped = vals.filter(clipEnds); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // don't clip angular values + if(ax._id === 'angular') { + valsClipped = vals; + } -'use strict'; + function drawTicks(container, tickpath) { + var ticks = container.selectAll('path.' + tcls) + .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); -/* removed: var _$d3_15 = require('d3'); */; + if(tickpath && ax.ticks) { + ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) + .classed('crisp', 1) + .call(_$color_51.stroke, ax.tickcolor) + .style('stroke-width', tickWidth + 'px') + .attr('d', tickpath); + ticks.attr('transform', transfn); + ticks.exit().remove(); + } + else ticks.remove(); + } -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$axes_213 = require('./axes'); */; -var axisRegex = _$constants_218.attrRegex; + function drawLabels(container, position) { + // tick labels - for now just the main labels. + // TODO: mirror labels, esp for subplots + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); -var _$transitionAxes_236 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; + if(!_$fastIsnumeric_18(position)) { + tickLabels.remove(); + drawAxTitle(); + return; + } + if(!ax.showticklabels) { + tickLabels.remove(); + drawAxTitle(); + calcBoundingBox(); + return; + } - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + var labelx, labely, labelanchor, labelpos0, flipit; + if(axLetter === 'x') { + flipit = (axside === 'bottom') ? 1 : -1; + labelx = function(d) { return d.dx + labelShift * flipit; }; + labelpos0 = position + (labelStandoff + pad) * flipit; + labely = function(d) { + return d.dy + labelpos0 + d.fontSize * + ((axside === 'bottom') ? 1 : -0.2); + }; + labelanchor = function(angle) { + if(!_$fastIsnumeric_18(angle) || angle === 0 || angle === 180) { + return 'middle'; + } + return (angle * flipit < 0) ? 'end' : 'start'; + }; + } + else if(axLetter === 'y') { + flipit = (axside === 'right') ? 1 : -1; + labely = function(d) { + return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; + }; + labelx = function(d) { + return d.dx + position + (labelStandoff + pad + + ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; + }; + labelanchor = function(angle) { + if(_$fastIsnumeric_18(angle) && Math.abs(angle) === 90) { + return 'middle'; + } + return axside === 'right' ? 'start' : 'end'; + }; + } + else if(axid === 'angular') { + ax._labelShift = labelShift; + ax._labelStandoff = labelStandoff; + ax._pad = pad; - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + labelx = ax._labelx; + labely = ax._labely; + labelanchor = ax._labelanchor; + } - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); + var maxFontSize = 0, + autoangle = 0, + labelsReady = []; + tickLabels.enter().append('g').classed(tcls, 1) + .append('text') + // only so tex has predictable alignment that we can + // alter later + .attr('text-anchor', 'middle') + .each(function(d) { + var thisLabel = _$d3_15.select(this), + newPromise = gd._promises.length; + thisLabel + .call(_$svg_text_utils_193.positionText, labelx(d), labely(d)) + .call(_$drawing_76.font, d.font, d.fontSize, d.fontColor) + .text(d.text) + .call(_$svg_text_utils_193.convertToTspans, gd); + newPromise = gd._promises[newPromise]; + if(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, ax.tickangle); + })); } - } - if(!update.to) continue; + else { + // sync label: just position it now. + positionLabels(thisLabel, ax.tickangle); + } + }); + tickLabels.exit().remove(); - update.axisName = axisName; - update.length = axis._length; + tickLabels.each(function(d) { + maxFontSize = Math.max(maxFontSize, d.fontSize); + }); - axes.push(axisLetter); + if(axid === 'angular') { + tickLabels.each(function(d) { + _$d3_15.select(this).select('text') + .call(_$svg_text_utils_193.positionText, labelx(d), labely(d)); + }); + } - updates[axisLetter] = update; + // How much to shift a multi-line label to center it vertically. + function getAnchorHeight(lineCount, lineHeight, angle) { + var h = (lineCount - 1) * lineHeight; + if(axLetter === 'x') { + if(angle < -60 || 60 < angle) { + return -0.5 * h; + } else if(axside === 'top') { + return -h; + } + } else { + angle *= axside === 'left' ? 1 : -1; + if(angle < -30) { + return -h; + } else if(angle < 30) { + return -0.5 * h; + } } + return 0; } - return updates; - } + function positionLabels(s, angle) { + s.each(function(d) { + var anchor = labelanchor(angle, d); + var thisLabel = _$d3_15.select(this), + mathjaxGroup = thisLabel.select('.text-math-group'), + transform = transfn.call(thisLabel.node(), d) + + ((_$fastIsnumeric_18(angle) && +angle !== 0) ? + (' rotate(' + angle + ',' + labelx(d) + ',' + + (labely(d) - d.fontSize / 2) + ')') : + ''); + var anchorHeight = getAnchorHeight( + _$svg_text_utils_193.lineCount(thisLabel), + __LINE_SPACING_214 * d.fontSize, + _$fastIsnumeric_18(angle) ? +angle : 0); + if(anchorHeight) { + transform += ' translate(0, ' + anchorHeight + ')'; + } + if(mathjaxGroup.empty()) { + thisLabel.select('text').attr({ + transform: transform, + 'text-anchor': anchor + }); + } + else { + var mjShift = + _$drawing_76.bBox(mathjaxGroup.node()).width * + {end: -0.5, start: 0.5}[anchor]; + mathjaxGroup.attr('transform', transform + + (mjShift ? 'translate(' + mjShift + ',0)' : '')); + } + }); + } - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; + // 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, ax._lastangle || ax.tickangle); - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; + function allLabelsReady() { + return labelsReady.length && Promise.all(labelsReady); + } - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + function fixLabelOverlaps() { + positionLabels(tickLabels, ax.tickangle); - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; + // check for auto-angling if x labels overlap + // don't auto-angle at all for log axes with + // base and digit format + if(axLetter === 'x' && !_$fastIsnumeric_18(ax.tickangle) && + (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { + var lbbArray = []; + tickLabels.each(function(d) { + var s = _$d3_15.select(this), + thisLabel = s.select('.text-math-group'), + x = ax.l2p(d.x); + if(thisLabel.empty()) thisLabel = s.select('text'); - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + var bb = _$drawing_76.bBox(thisLabel.node()); - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; + 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 + }); + }); + for(i = 0; i < lbbArray.length - 1; i++) { + if(_$lib_172.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + // any overlap at all - set 30 degrees + autoangle = 30; + break; + } + } + if(autoangle) { + var tickspacing = Math.abs( + (vals[vals.length - 1].x - vals[0].x) * ax._m + ) / (vals.length - 1); + if(tickspacing < maxFontSize * 2.5) { + autoangle = 90; + } + positionLabels(tickLabels, autoangle); + } + ax._lastangle = autoangle; } - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; - - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); - } + // update the axis title + // (so it can move out of the way if needed) + // TODO: separate out scoot so we don't need to do + // a full redraw of the title (mostly relevant for MathJax) + drawAxTitle(); + return axid + ' done'; } - return affectedSubplots; - } + function calcBoundingBox() { + if(ax.showticklabels) { + var gdBB = gd.getBoundingClientRect(); + var bBox = container.node().getBoundingClientRect(); - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); + /* + * the way we're going to use this, the positioning that matters + * is relative to the origin of gd. This is important particularly + * if gd is scrollable, and may have been scrolled between the time + * we calculate this and the time we use it + */ - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); + ax._boundingBox = { + width: bBox.width, + height: bBox.height, + left: bBox.left - gdBB.left, + right: bBox.right - gdBB.left, + top: bBox.top - gdBB.top, + bottom: bBox.bottom - gdBB.top + }; + } else { + var gs = fullLayout._size; + var pos; - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } + // set dummy bbox for ticklabel-less axes - redrawObjs(fullLayout.annotations || [], _$registry_261.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_261.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_261.getComponentMethod('images', 'draw'), true); - } + if(axLetter === 'x') { + pos = ax.anchor === 'free' ? + gs.t + gs.h * (1 - ax.position) : + gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; - } + ax._boundingBox = { + top: pos, + bottom: pos, + left: ax._offset, + right: ax._offset + ax._length, + width: ax._length, + height: 0 + }; + } else { + pos = ax.anchor === 'free' ? + gs.l + gs.w * ax.position : + gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; + ax._boundingBox = { + left: pos, + right: pos, + bottom: ax._offset + ax._length, + top: ax._offset, + height: ax._length, + width: 0 + }; + } + } - activeAxIds = [xa._id, ya._id]; + /* + * for spikelines: what's the full domain of positions in the + * opposite direction that are associated with this axis? + * This means any axes that we make a subplot with, plus the + * position of the axis itself if it's free. + */ + if(subplots) { + var fullRange = ax._counterSpan = [Infinity, -Infinity]; - for(i = 0; i < activeAxIds.length; i++) { - _$axes_213.doTicks(gd, activeAxIds[i], true); - } + for(i = 0; i < subplots.length; i++) { + var subplot = fullLayout._plots[subplots[i]]; + var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; + extendRange(fullRange, [ + counterAxis._offset, + counterAxis._offset + counterAxis._length + ]); + } - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); + if(ax.anchor === 'free') { + extendRange(fullRange, (axLetter === 'x') ? + [ax._boundingBox.bottom, ax._boundingBox.top] : + [ax._boundingBox.right, ax._boundingBox.left]); } + } - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + function extendRange(range, newRange) { + range[0] = Math.min(range[0], newRange[0]); + range[1] = Math.max(range[1], newRange[1]); } } - redrawObjs(fullLayout.annotations || [], _$registry_261.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_261.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_261.getComponentMethod('images', 'draw'), true); - } + function doAutoMargins() { + if(!ax.automargin) { return; } + if(axLetter !== 'x' && axLetter !== 'y') { return; } - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + var s = ax.side[0]; + var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_76.setTranslate, 0, 0) - .call(_$drawing_76.setScale, 1, 1); + if(axLetter === 'x') { + push.y = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 't' ? 1 : 0]); + push[s] += ax._boundingBox.height; + } + else { + push.x = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 'r' ? 1 : 0]); + push[s] += ax._boundingBox.width; + } - subplot.plot - .call(_$drawing_76.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_76.setScale, 1, 1); + if(ax.title !== fullLayout._dfltTitle[axLetter]) { + push[s] += ax.titlefont.size; + } - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + var pushKey = ax._name + '.automargin'; + var prevPush = fullLayout._pushmargin[pushKey]; + if(!prevPush || prevPush[s].size < push[s]) { + _$plots_246.autoMargin(gd, pushKey, push); + } + } - // 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_76.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_76.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_76.hideOutsideRangePoints, subplot); + var done = _$lib_172.syncOrAsync([ + allLabelsReady, + fixLabelOverlaps, + calcBoundingBox, + doAutoMargins + ]); + if(done && done.then) gd._promises.push(done); + return done; } - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; + function drawAxTitle() { + if(skipTitle) return; - var viewBox = []; + // now this only applies to regular cartesian axes; colorbars and + // others ALWAYS call doTicks with skipTitle=true so they can + // configure their own titles. - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + // rangeslider takes over a bottom title so drop it here + if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + var avoid = { + selection: tickLabels, + side: ax.side + }; + var axLetter = axid.charAt(0); + var gs = gd._fullLayout._size; + var offsetBase = 1.5; + var fontSize = ax.titlefont.size; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; + var transform, counterAxis, x, y; + + if(tickLabels.size()) { + var translation = _$drawing_76.getTranslate(tickLabels.node().parentNode); + avoid.offsetLeft = translation.x; + avoid.offsetTop = translation.y; } - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + var titleStandoff = 10 + fontSize * offsetBase + + (ax.linewidth ? ax.linewidth - 1 : 0); - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + if(axLetter === 'x') { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : + _$axis_ids_217.getFromId(gd, ax.anchor); - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; - } - - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + x = ax._offset + ax._length / 2; - var editX = !!xUpdate; - var editY = !!yUpdate; + if(ax.side === 'top') { + y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); + } + else { + y = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1.5 : 0.5); + } + y += counterAxis._offset; - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + if(!avoid.side) avoid.side = 'bottom'; + } + else { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : + _$axis_ids_217.getFromId(gd, ax.anchor); - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + y = ax._offset + ax._length / 2; + if(ax.side === 'right') { + x = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1 : 0.5); + } + else { + x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); + } + x += counterAxis._offset; - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + transform = {rotate: '-90', offset: 0}; + if(!avoid.side) avoid.side = 'left'; + } - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + _$titles_144.draw(gd, axid + 'title', { + propContainer: ax, + propName: ax._name + '.title', + placeholder: fullLayout._dfltTitle[axLetter], + avoid: avoid, + transform: transform, + attributes: {x: x, y: y, 'text-anchor': 'middle'} + }); + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_76.setTranslate, clipDx, clipDy) - .call(_$drawing_76.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + function traceHasBarsOrFill(trace, subplot) { + if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; + if(_$registry_262.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; + } - subplot.plot - .call(_$drawing_76.setTranslate, plotDx, plotDy) - .call(_$drawing_76.setScale, xScaleFactor, yScaleFactor) + function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_76.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); + var zlcontainer = plotinfo.zerolinelayer; + var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; + var gridpath = ax._gridpath || ((axLetter === 'x' ? + ('M0,' + counteraxis._offset + 'v') : + ('M' + counteraxis._offset + ',0h') + ) + counteraxis._length); + var grid = gridcontainer.selectAll('path.' + gcls) + .data((ax.showgrid === false) ? [] : gridvals, datafn); + grid.enter().append('path').classed(gcls, 1) + .classed('crisp', 1) + .attr('d', gridpath) + .each(function(d) { + if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && + Math.abs(d.x) < ax.dtick / 100) { + _$d3_15.select(this).remove(); + } + }); + grid.attr('transform', transfn) + .call(_$color_51.stroke, ax.gridcolor || '#ddd') + .style('stroke-width', gridWidth + 'px'); + if(typeof gridpath === 'function') grid.attr('d', gridpath); + grid.exit().remove(); - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_76.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + // zero line + if(zlcontainer) { + var hasBarsOrFill = false; + for(var i = 0; i < gd._fullData.length; i++) { + if(traceHasBarsOrFill(gd._fullData[i], subplot)) { + hasBarsOrFill = true; + break; + } + } + var rng = _$lib_172.simpleMap(ax.range, ax.r2l), + showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && + (ax.type === 'linear' || ax.type === '-') && gridvals.length && + (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); + var zl = zlcontainer.selectAll('path.' + zcls) + .data(showZl ? [{x: 0, id: axid}] : []); + zl.enter().append('path').classed(zcls, 1).classed('zl', 1) + .classed('crisp', 1) + .attr('d', gridpath) + .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. + zlcontainer.selectAll('path').sort(function(da, db) { + return _$axis_ids_217.idSort(da.id, db.id); + }); + }); + zl.attr('transform', transfn) + .call(_$color_51.stroke, ax.zerolinecolor || _$color_51.defaultLine) + .style('stroke-width', zeroLineWidth + 'px'); + zl.exit().remove(); + } } - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); + if(independent) { + drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); + if(ax._counteraxis) { + var fictionalPlotinfo = { + gridlayer: ax._gridlayer, + zerolinelayer: ax._zerolinelayer + }; + drawGrid(fictionalPlotinfo, ax._counteraxis); + } + return drawLabels(ax._axislayer, ax._pos); } + else if(fullLayout._has('cartesian')) { + subplots = axes.getSubplots(gd, ax); - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; + // keep track of which subplots (by main conteraxis) we've already + // drawn grids for, so we don't overdraw overlaying subplots + var finishedGrids = {}; - axi.range = to.slice(); - } + subplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var counterAxis = plotinfo[counterLetter + 'axis']; - // Signal that this transition has completed: - onComplete && onComplete(); + var mainCounterID = counterAxis._mainAxis._id; + if(finishedGrids[mainCounterID]) return; + finishedGrids[mainCounterID] = 1; - return _$registry_261.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } + drawGrid(plotinfo, counterAxis, subplot); }); - } - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; + var mainSubplot = ax._mainSubplot; + var mainPlotinfo = fullLayout._plots[mainSubplot]; + var tickSubplots = []; - axi.range = axi._r.slice(); + if(ax.ticks) { + var mainSign = ticksign[2]; + var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); + if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { + tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + } + drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); + + tickSubplots = Object.keys(ax._linepositions || {}); } - return _$registry_261.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); - } + tickSubplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; - var t1, t2, raf; - var easeFn = _$d3_15.ease(transitionOpts.easing); + var container = plotinfo[axLetter + 'axislayer']; - gd._transitionData._interruptCallbacks.push(function() { - window.cancelAnimationFrame(raf); - raf = null; - return transitionInterrupt(); - }); + // [bottom or left, top or right] + // free and main are handled above + var linepositions = ax._linepositions[subplot] || []; - function doFrame() { - t2 = Date.now(); + function tickPathSide(sidei) { + var tsign = ticksign[sidei]; + return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); + } - var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); - var progress = easeFn(tInterp); + drawTicks(container, tickPathSide(0) + tickPathSide(1)); + }); - for(var i = 0; i < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } + var mainContainer = mainPlotinfo[axLetter + 'axislayer']; - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); - } + return drawLabels(mainContainer, ax._mainLinePosition); } +}; - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); +// swap all the presentation attributes of the axes showing these traces +axes.swap = function(gd, traces) { + var axGroups = makeAxisGroups(gd, traces); - return Promise.resolve(); + for(var i = 0; i < axGroups.length; i++) { + swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + } }; -var _$get_data_242 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +function makeAxisGroups(gd, traces) { + var groups = [], + i, + j; -/* removed: var _$registry_261 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_218.SUBPLOT_PATTERN; + for(i = 0; i < traces.length; i++) { + var groupsi = [], + xi = gd._fullData[traces[i]].xaxis, + yi = gd._fullData[traces[i]].yaxis; + if(!xi || !yi) continue; // not a 2D cartesian trace? -/** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces - */ -_$get_data_242.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_261.subplotsRegistry[type]; - if(!basePlotModule) return []; + for(j = 0; j < groups.length; j++) { + if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { + groupsi.push(j); + } + } - var attr = basePlotModule.attr; - var subplotCalcData = []; + if(!groupsi.length) { + groups.push({x: [xi], y: [yi]}); + continue; + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; + var group0 = groups[groupsi[0]], + groupj; - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + 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 subplotCalcData; -}; - -_$get_data_242.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_261.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + return groups; +} - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); +function mergeAxisGroups(intoSet, fromSet) { + for(var i = 0; i < fromSet.length; i++) { + if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); } +} - return moduleCalcData; -}; +function swapAxisGroup(gd, xIds, yIds) { + var i, + j, + xFullAxes = [], + yFullAxes = [], + layout = gd.layout; -/** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. - * - * @return {array} list of trace objects. - * - */ -_$get_data_242.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_261.subplotsRegistry[type]) return []; + 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 attr = _$registry_261.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; + var allAxKeys = Object.keys(xFullAxes[0]), + noSwapAttrs = [ + 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' + ], + numericTypes = ['linear', 'log']; - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; + for(i = 0; i < allAxKeys.length; i++) { + var keyi = allAxKeys[i], + xVal = xFullAxes[0][keyi], + yVal = yFullAxes[0][keyi], + allEqual = true, + coerceLinearX = false, + 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); + } } - for(var i = 0; i < data.length; i++) { - trace = data[i]; + // 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_172.swapAttrs(layout.annotations[i], ['?']); + } + } +} - if(type === 'gl2d' && _$registry_261.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); - } +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_172.nestedProperty, + xVal = np(layout[xFullAxes[0]._name], key).get(), + yVal = np(layout[yFullAxes[0]._name], key).get(), + i; + if(key === 'title') { + // special handling of placeholder titles + if(xVal === dfltTitle.x) { + xVal = dfltTitle.y; } - else { - if(trace[attr] === subplotId) subplotData.push(trace); + if(yVal === dfltTitle.y) { + yVal = dfltTitle.x; } } - return subplotData; -}; + 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); + } +} -var _$cartesian_224 = {}; +var _$hover_91 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29759,1087 +29982,1453 @@ var _$cartesian_224 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$plots_246 = require('../plots'); */; -var getModuleCalcData = _$get_data_242.getModuleCalcData; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$axis_ids_216 = require('./axis_ids'); */; -/* removed: var _$constants_218 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$Events_165 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_183 = require('../../lib/override_cursor'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -_$cartesian_224.name = 'cartesian'; +/* removed: var _$helpers_90 = require('./helpers'); */; +/* removed: var _$constants_88 = require('./constants'); */; -_$cartesian_224.attr = ['xaxis', 'yaxis']; +// hover labels for multiple horizontal bars get tilted by some angle, +// then need to be offset differently if they overlap +var YANGLE = _$constants_88.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; -_$cartesian_224.idRoot = ['x', 'y']; +// expansion of projected height +var YFACTOR = 1 / Math.sin(YA_RADIANS); -_$cartesian_224.idRegex = _$constants_218.idRegex; +// to make the appropriate post-rotation x offset, +// you need both x and y offsets +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); -_$cartesian_224.attrRegex = _$constants_218.attrRegex; +// size and display constants for hover text +var HOVERARROWSIZE = _$constants_88.HOVERARROWSIZE; +var HOVERTEXTPAD = _$constants_88.HOVERTEXTPAD; -_$cartesian_224.attributes = _$attributes_211; +// fx.hover: highlight data on hover +// evt can be a mousemove event, or an object with data about what points +// to hover on +// {xpx,ypx[,hovermode]} - pixel locations from top left +// (with optional overriding hovermode) +// {xval,yval[,hovermode]} - data values +// [{curveNumber,(pointNumber|xval and/or yval)}] - +// array of specific points to highlight +// pointNumber is a single integer if gd.data[curveNumber] is 1D, +// or a two-element array if it's 2D +// xval and yval are data values, +// 1D data may specify either or both, +// 2D data must specify both +// subplot is an id string (default "xy") +// makes use of gl.hovermode, which can be: +// x (find the points with the closest x values, ie a column), +// closest (find the single closest point) +// internally there are two more that occasionally get used: +// y (pick out a row - only used for multiple horizontal bar charts) +// array (used when the user specifies an explicit +// array of points to hover on) +// +// We wrap the hovers in a timer, to limit their frequency. +// The actual rendering is done by private function _hover. +_$hover_91.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = _$lib_172.getGraphDiv(gd); -_$cartesian_224.layoutAttributes = _$layout_attributes_225; + _$lib_172.throttle( + gd._fullLayout._uid + _$constants_88.HOVERID, + _$constants_88.HOVERMINTIME, + function() { _hover(gd, evt, subplot, noHoverEvent); } + ); +}; -_$cartesian_224.supplyLayoutDefaults = _$supplyLayoutDefaults_226; +/* + * Draw a single hover item in a pre-existing svg container somewhere + * hoverItem should have keys: + * - x and y (or x0, x1, y0, and y1): + * the pixel position to mark, relative to opts.container + * - xLabel, yLabel, zLabel, text, and name: + * info to go in the label + * - color: + * the background color for the label. + * - idealAlign (optional): + * 'left' or 'right' for which side of the x/y box to try to put this on first + * - borderColor (optional): + * color for the border, defaults to strongest contrast with color + * - fontFamily (optional): + * string, the font for this label, defaults to constants.HOVERFONT + * - fontSize (optional): + * the label font size, defaults to constants.HOVERFONTSIZE + * - fontColor (optional): + * defaults to borderColor + * opts should have keys: + * - bgColor: + * the background color this is against, used if the trace is + * non-opaque, and for the name, which goes outside the box + * - container: + * a or element to add the hover label to + * - outerContainer: + * normally a parent of `container`, sets the bounding box to use to + * constrain the hover label and determine whether to show it on the left or right + */ +_$hover_91.loneHover = function loneHover(hoverItem, opts) { + var pointData = { + color: hoverItem.color || _$color_51.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, -_$cartesian_224.transitionAxes = _$transitionAxes_236; + // optional extra bits of styling + borderColor: hoverItem.borderColor, + fontFamily: hoverItem.fontFamily, + fontSize: hoverItem.fontSize, + fontColor: hoverItem.fontColor, -_$cartesian_224.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; - - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } - - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_216.id2name(xi)] || {}).anchor; - if(!_$constants_218.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + // filler to make createHoverText happy + trace: { + index: 0, + hoverinfo: '' + }, + xa: {_offset: 0}, + ya: {_offset: 0}, + index: 0 + }; - if(!allY[yi]) { - allY[yi] = 1; - _$lib_171.pushUnique(yList, yi); - } - } - } + var container3 = _$d3_15.select(opts.container), + outerContainer3 = opts.outerContainer ? + _$d3_15.select(opts.outerContainer) : container3; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_216.id2name(yi)] || {}).anchor; - if(!_$constants_218.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var fullOpts = { + hovermode: 'closest', + rotateLabels: false, + bgColor: opts.bgColor || _$color_51.background, + container: container3, + outerContainer: outerContainer3 + }; - if(!allX[xi]) { - allX[xi] = 1; - _$lib_171.pushUnique(xList, xi); - } - } - } + var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); + alignHoverText(hoverLabel, fullOpts.rotateLabels); - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_218.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_216.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_216.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } + return hoverLabel.node(); }; -_$cartesian_224.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; +// The actual implementation is here: +function _hover(gd, evt, subplot, noHoverEvent) { + if(!subplot) subplot = 'xy'; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + // if the user passed in an array of subplots, + // use those instead of finding overlayed plots + var subplots = Array.isArray(subplot) ? subplot : [subplot]; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var fullLayout = gd._fullLayout; + var plots = fullLayout._plots || []; + var plotinfo = plots[subplot]; + var hasCartesian = fullLayout._has('cartesian'); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } + // list of all overlaid subplots to look at + if(plotinfo) { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; }); - } - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + subplots = subplots.concat(overlayedSubplots); + } - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; + var len = subplots.length; + var xaArray = new Array(len); + var yaArray = new Array(len); + var supportsCompare = false; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + for(var i = 0; i < len; i++) { + var spId = subplots[i]; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + // 'cartesian' case + var plotObj = plots[spId]; + if(plotObj) { + supportsCompare = true; - cdSubplot.push(cd); - } + // TODO make sure that fullLayout_plots axis refs + // get updated properly so that we don't have + // to use Axes.getFromId in general. - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; - } + xaArray[i] = _$axes_214.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_214.getFromId(gd, plotObj.yaxis._id); + continue; } - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + // other subplot types + var _subplot = fullLayout[spId]._subplot; + xaArray[i] = _subplot.xaxis; + yaArray[i] = _subplot.yaxis; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; + var hovermode = evt.hovermode || fullLayout.hovermode; - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + if(hovermode && !supportsCompare) hovermode = 'closest'; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || + gd.querySelector('.zoombox') || gd._dragging) { + return _$dragelement_73.unhoverRaw(gd, evt); } -} -_$cartesian_224.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; + var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + // hoverData: the set of candidate points we've found to highlight + var hoverData = [], + // searchData: the data to search in. Mostly this is just a copy of + // gd.calcdata, filtered to the subplot and overlays we're on + // but if a point array is supplied it will be a mapping + // of indicated curves + searchData = [], - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; - } + // [x|y]valArray: the axis values of the hover event + // mapped onto each of the currently selected overlaid subplots + xvalArray, + yvalArray, - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + // used in loops + itemnum, + curvenum, + cd, + trace, + subplotId, + subploti, + mode, + xval, + yval, + pointData, + closedataPreviousLength, - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // spikePoints: the set of candidate points we've found to draw spikes to + spikePoints = { + hLinePoint: null, + vLinePoint: null + }; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + // Figure out what we're hovering on: + // mouse location or user-supplied data - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + if(Array.isArray(evt)) { + // user specified an array of points to highlight + hovermode = 'array'; + for(itemnum = 0; itemnum < evt.length; itemnum++) { + cd = gd.calcdata[evt[itemnum].curveNumber||0]; + if(cd[0].trace.hoverinfo !== 'skip') { + searchData.push(cd); } } - - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); } + else { + for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { + cd = gd.calcdata[curvenum]; + trace = cd[0].trace; + if(trace.hoverinfo !== 'skip' && _$helpers_90.isTraceInSubplots(trace, subplots)) { + searchData.push(cd); + } + } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // [x|y]px: the pixels (from top left) of the mouse location + // on the currently selected plot area + // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation + var hasUserCalledHover = !evt.target, + xpx, ypx; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(hasUserCalledHover) { + if('xpx' in evt) xpx = evt.xpx; + else xpx = xaArray[0]._length / 2; + evt.pointerX = xpx + xaArray[0]._offset; - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } + if('ypx' in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + evt.pointerY = ypx + yaArray[0]._offset; } - } + else { + // fire the beforehover event and quit if it returns false + // note that we're only calling this on real mouse events, so + // manual calls to fx.hover will always run. + if(_$Events_165.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + var dbb = evt.target.getBoundingClientRect(); - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // in case hover was called from mouseout into hovertext, + // it's possible you're not actually over the plot anymore + if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { + return _$dragelement_73.unhoverRaw(gd, evt); } + evt.pointerX = evt.offsetX; + evt.pointerY = evt.offsetY; } - } - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + if('xval' in evt) xvalArray = _$helpers_90.flat(subplots, evt.xval); + else xvalArray = _$helpers_90.p2c(xaArray, xpx); - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } + if('yval' in evt) yvalArray = _$helpers_90.flat(subplots, evt.yval); + else yvalArray = _$helpers_90.p2c(yaArray, ypx); + + if(!_$fastIsnumeric_18(xvalArray[0]) || !_$fastIsnumeric_18(yvalArray[0])) { + _$lib_172.warn('Fx.hover failed', evt, gd); + return _$dragelement_73.unhoverRaw(gd, evt); } } -}; -_$cartesian_224.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); + // the pixel distance to beat as a matching point + // in 'x' or 'y' mode this resets for each trace + var distance = Infinity; - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_171.identity); + // find the closest point in each trace + // this is minimum dx and/or dy, depending on mode + // and the pixel position for the label (labelXpx, labelYpx) + for(curvenum = 0; curvenum < searchData.length; curvenum++) { + cd = searchData[curvenum]; - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + // filter out invisible or broken data + if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; - subplotLayers.order(); + trace = cd[0].trace; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + // Explicitly bail out for these two. I don't know how to otherwise prevent + // the rest of this function from running and failing + if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_90.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } - // keep ref to plot group - plotinfo.plotgroup = _$d3_15.select(this); + // within one trace mode can sometimes be overridden + mode = hovermode; - // initialize list of overlay subplots - plotinfo.overlays = []; + // container for new point, also used to pass info into module.hoverPoints + pointData = { + // trace properties + cd: cd, + trace: trace, + xa: xaArray[subploti], + ya: yaArray[subploti], - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); - } + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + // point properties - override all of these + index: false, // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance -_$cartesian_224.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_246.style(gd); -}; + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: undefined, + ySpike: undefined, - var subplotData = [], - overlays = []; + // where and how to display the hover label + color: _$color_51.defaultLine, // trace color + name: trace.name, + x0: undefined, + x1: undefined, + y0: undefined, + y1: undefined, + xLabelVal: undefined, + yLabelVal: undefined, + zLabelVal: undefined, + text: undefined + }; - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + // add ref to subplot object (non-cartesian case) + if(fullLayout[subplotId]) { + pointData.subplot = fullLayout[subplotId]._subplot; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + closedataPreviousLength = hoverData.length; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); + // for a highlighting array, figure out what + // we're searching for with this element + if(mode === 'array') { + var selection = evt[curvenum]; + if('pointNumber' in selection) { + pointData.index = selection.pointNumber; + mode = 'closest'; + } + else { + mode = ''; + if('xval' in selection) { + xval = selection.xval; + mode = 'x'; + } + if('yval' in selection) { + yval = selection.yval; + mode = mode ? 'closest' : 'y'; + } + } } else { - subplotData.push(subplot); + xval = xvalArray[subploti]; + yval = yvalArray[subploti]; } - } - - // main subplots before overlays - subplotData = subplotData.concat(overlays); - return subplotData; -} - -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_218.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_218.layerValue2layerClass[plotinfo.yaxis.layer]; - - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); - - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); - - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); - - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); - - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); - - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + // Now if there is range to look in, find the points to hover. + if(hoverdistance !== 0) { + if(trace._module && trace._module.hoverPoints) { + var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); + if(newPoints) { + var newPoint; + for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { + newPoint = newPoints[newPointNum]; + if(_$fastIsnumeric_18(newPoint.x0) && _$fastIsnumeric_18(newPoint.y0)) { + hoverData.push(cleanPoint(newPoint, hovermode)); + } + } + } + } + else { + _$lib_172.log('Unrecognized trace type in hover:', trace); + } + } - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + // in closest mode, remove any existing (farther) points + // and don't look any farther than this latest point (or points, some + // traces like box & violin make multiple hover labels at once) + if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + // Now if there is range to look in, find the points to draw the spikelines + // Do it only if there is no hoverData + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); + if(closestPoints) { + closestPoints = closestPoints.filter(function(point) { + // some hover points, like scatter fills, do not allow spikes, + // so will generate a hover point but without a valid spikeDistance + return point.spikeDistance <= spikedistance; + }); + } + if(closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes; + }); + if(closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if(_$fastIsnumeric_18(closestVPt.x0) && _$fastIsnumeric_18(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.vLinePoint = tmpPoint; + } + } + } - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes; + }); + if(closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if(_$fastIsnumeric_18(closestHPt.x0) && _$fastIsnumeric_18(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } } - else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + function selectClosestPoint(pointsData, spikedistance) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for(var i = 0; i < pointsData.length; i++) { + thisSpikeDistance = pointsData[i].spikeDistance; + if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { + resultPoint = pointsData[i]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + function fillSpikePoint(point) { + if(!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + var spikelineOpts = { + fullLayout: fullLayout, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + event: evt + }; + var oldspikepoints = gd._spikepoints, + newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); + // Now if it is not restricted by spikedistance option, set the points to draw the spikelines + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_216.idSort); - - // common attributes for all subplots, overlays or not + // if hoverData is empty check for the spikes to draw and quit if there are none + if(hoverData.length === 0) { + var result = _$dragelement_73.unhoverRaw(gd, evt); + if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } + return result; + } - for(var i = 0; i < _$constants_218.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_218.traceLayerClasses[i]); + if(hasCartesian) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } } - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); -} + // lastly, emit custom hover/unhover events + var oldhoverdata = gd._hoverdata, + newhoverdata = []; -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; + // pull out just the data that's useful to + // other people and send it to the event + for(itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + newhoverdata.push(_$helpers_90.makeEventData(pt, pt.trace, pt.cd)); + } - var overlayIdsToRemove = {}; + gd._hoverdata = newhoverdata; - layers.each(function(subplotId) { - var plotgroup = _$d3_15.select(this); + // if there's more than one horz bar trace, + // rotate the labels so they don't overlap + var rotateLabels = hovermode === 'y' && searchData.length > 1; - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + var bgColor = _$color_51.combine( + fullLayout.plot_bgcolor || _$color_51.background, + fullLayout.paper_bgcolor + ); - overlayIdsToRemove[subplotId] = true; + var labelOpts = { + hovermode: hovermode, + rotateLabels: rotateLabels, + bgColor: bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }; - // do not remove individual axis s here - // as other subplots may need them - }); + var hoverLabels = createHoverText(hoverData, labelOpts, gd); - // must remove overlaid subplot trace layers 'manually' + hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + alignHoverText(hoverLabels, rotateLabels); - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true + // we should improve the "fx" API so other plots can use it without these hack. + if(evt.target && evt.target.tagName) { + var hasClickToShow = _$registry_262.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_183(_$d3_15.select(evt.target), hasClickToShow ? 'pointer' : ''); + } - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; + // don't emit events if called manually + if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); - } - } + if(oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); + gd.emit('plotly_hover', { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray + }); } -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); +function createHoverText(hoverData, opts, gd) { + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; - layer.enter().append(nodeType) - .classed(className, true); + // opts.fontFamily/Size are used for the common label + // and as defaults for each hover label, though the individual labels + // can override this. + var fontFamily = opts.fontFamily || _$constants_88.HOVERFONT; + var fontSize = opts.fontSize || _$constants_88.HOVERFONTSIZE; - return layer; -} + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; + var t0 = c0[commonAttr]; + var t00 = (String(t0) || '').split(' ')[0]; + var outerContainerBB = outerContainer.node().getBoundingClientRect(); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; -_$cartesian_224.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_15.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); + // show the common label, if any, on the axis + // never show a common label in array mode, + // even if sometimes there could be one + var showCommonLabel = ( + (t0 !== undefined) && + (c0.distance <= opts.hoverdistance) && + (hovermode === 'x' || hovermode === 'y') + ); - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); + // all hover traces hoverinfo must contain the hovermode + // to have common labels + if(showCommonLabel) { + var i, traceHoverinfo; + var allHaveZ = true; + for(i = 0; i < hoverData.length; i++) { + if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; - image.attr({ - xmlns: _$xmlns_namespaces_156.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); + traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; + var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); + if(parts.indexOf('all') === -1 && + parts.indexOf(hovermode) === -1) { + showCommonLabel = false; + break; + } + } + + // xyz labels put all info in their main label, so have no need of a common label + if(allHaveZ) showCommonLabel = false; } - canvases.each(canvasToImage); -}; + var commonLabel = container.selectAll('g.axistext') + .data(showCommonLabel ? [0] : []); + commonLabel.enter().append('g') + .classed('axistext', true); + commonLabel.exit().remove(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + commonLabel.each(function() { + var label = _$d3_15.select(this); + var lpath = _$lib_172.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_172.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); + lpath.style({ + fill: commonLabelOpts.bgcolor || _$color_51.defaultLine, + stroke: commonLabelOpts.bordercolor || _$color_51.background, + }); -'use strict'; + ltext.text(t0) + .call(_$drawing_76.font, + commonLabelOpts.font.family || fontFamily, + commonLabelOpts.font.size || fontSize, + commonLabelOpts.font.color || _$color_51.background + ) + .call(_$svg_text_utils_193.positionText, 0, 0) + .call(_$svg_text_utils_193.convertToTspans, gd); -var mergeArray = _$lib_171.mergeArray; + label.attr('transform', ''); + var tbb = ltext.node().getBoundingClientRect(); + if(hovermode === 'x') { + ltext.attr('text-anchor', 'middle') + .call(_$svg_text_utils_193.positionText, 0, (xa.side === 'top' ? + (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : + (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); -// arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_270 = function arraysToCalcdata(cd, trace) { - for(var i = 0; i < cd.length; i++) cd[i].i = i; + var topsign = xa.side === 'top' ? '-' : ''; + lpath.attr('d', 'M0,0' + + 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + + 'H' + (HOVERTEXTPAD + tbb.width / 2) + + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + + 'H-' + (HOVERTEXTPAD + tbb.width / 2) + + 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); - mergeArray(trace.text, cd, 'tx'); - mergeArray(trace.hovertext, cd, 'htx'); + label.attr('transform', 'translate(' + + (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + + (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + } + else { + ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') + .call(_$svg_text_utils_193.positionText, + (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), + outerTop - tbb.top - tbb.height / 2); - var marker = trace.marker; - if(marker) { - mergeArray(marker.opacity, cd, 'mo'); - mergeArray(marker.color, cd, 'mc'); + var leftsign = ya.side === 'right' ? '' : '-'; + lpath.attr('d', 'M0,0' + + 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + + 'V' + (HOVERTEXTPAD + tbb.height / 2) + + 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + + 'V-' + (HOVERTEXTPAD + tbb.height / 2) + + 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); - var markerLine = marker.line; - if(markerLine) { - mergeArray(markerLine.color, cd, 'mlc'); - mergeArray(markerLine.width, cd, 'mlw'); + label.attr('transform', 'translate(' + + (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + + (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 the "close but not quite" points + // because of error bars, only take up to a space + hoverData = hoverData.filter(function(d) { + return (d.zLabelVal !== undefined) || + (d[commonAttr] || '').split(' ')[0] === t00; + }); + }); -'use strict'; + // show all the individual labels -/* removed: var _$attributes_368 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_59 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; + // first create the objects + var hoverLabels = container.selectAll('g.hovertext') + .data(hoverData, function(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); + }); + hoverLabels.enter().append('g') + .classed('hovertext', true) + .each(function() { + var g = _$d3_15.select(this); + // trace name label (rect and text.name) + g.append('rect') + .call(_$color_51.fill, _$color_51.addOpacity(bgColor, 0.8)); + g.append('text').classed('name', true); + // trace data label (path and text.nums) + g.append('path') + .style('stroke-width', '1px'); + g.append('text').classed('nums', true) + .call(_$drawing_76.font, fontFamily, fontSize); + }); + hoverLabels.exit().remove(); -var __extendFlat_271 = _$extend_165.extendFlat; + // then put the text in, position the pointer to the data, + // and figure out sizes + hoverLabels.each(function(d) { + var g = _$d3_15.select(this).attr('transform', ''), + name = '', + text = ''; -var textFontAttrs = _$font_attributes_240({ - editType: 'calc', - arrayOk: true, - -}); + // combine possible non-opaque trace color with bgColor + var baseColor = _$color_51.opacity(d.color) ? d.color : _$color_51.defaultLine; + var traceColor = _$color_51.combine(baseColor, bgColor); -var __scatterMarkerAttrs_271 = _$attributes_368.marker; -var scatterMarkerLineAttrs = __scatterMarkerAttrs_271.line; + // find a contrasting color for border and text + var contrastColor = d.borderColor || _$color_51.contrast(traceColor); -var markerLineWidth = __extendFlat_271({}, - scatterMarkerLineAttrs.width, { dflt: 0 }); + // to get custom 'name' labels pass cleanPoint + if(d.nameOverride !== undefined) d.name = d.nameOverride; -var markerLine = __extendFlat_271({ - width: markerLineWidth, - editType: 'calc' -}, _$makeColorScaleAttributes_59('marker.line')); + if(d.name) { + // strip out our pseudo-html elements from d.name (if it exists at all) + name = _$svg_text_utils_193.plainText(d.name || ''); -var marker = __extendFlat_271({ - line: markerLine, - editType: 'calc' -}, _$makeColorScaleAttributes_59('marker'), { - showscale: __scatterMarkerAttrs_271.showscale, - colorbar: _$attributes_52, - opacity: { - valType: 'number', - arrayOk: true, - dflt: 1, - min: 0, - max: 1, - - editType: 'style', - - } -}); + var nameLength = Math.round(d.nameLength); -var _$attributes_271 = { - x: _$attributes_368.x, - x0: _$attributes_368.x0, - dx: _$attributes_368.dx, - y: _$attributes_368.y, - y0: _$attributes_368.y0, - dy: _$attributes_368.dy, + if(nameLength > -1 && name.length > nameLength) { + if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; + else name = name.substr(0, nameLength); + } + } - text: _$attributes_368.text, - hovertext: _$attributes_368.hovertext, + if(d.zLabel !== undefined) { + if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; + if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; + text += (text ? 'z: ' : '') + d.zLabel; + } + else if(showCommonLabel && d[hovermode + 'Label'] === t0) { + text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; + } + else if(d.xLabel === undefined) { + if(d.yLabel !== undefined) text = d.yLabel; + } + else if(d.yLabel === undefined) text = d.xLabel; + else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; - textposition: { - valType: 'enumerated', - - values: ['inside', 'outside', 'auto', 'none'], - dflt: 'none', - arrayOk: true, - editType: 'calc', - - }, + if(d.text && !Array.isArray(d.text)) { + text += (text ? '
' : '') + d.text; + } - textfont: __extendFlat_271({}, textFontAttrs, { - - }), + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; - insidetextfont: __extendFlat_271({}, textFontAttrs, { - - }), + // if 'text' is empty at this point, + // put 'name' in main label and don't show secondary label + if(text === '') { + // if 'name' is also empty, remove entire label + if(name === '') g.remove(); + text = name; + } - outsidetextfont: __extendFlat_271({}, textFontAttrs, { - - }), + // main label + var tx = g.select('text.nums') + .call(_$drawing_76.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + d.fontColor || contrastColor) + .text(text) + .attr('data-notex', 1) + .call(_$svg_text_utils_193.positionText, 0, 0) + .call(_$svg_text_utils_193.convertToTspans, gd); - constraintext: { - valType: 'enumerated', - values: ['inside', 'outside', 'both', 'none'], - - dflt: 'both', - editType: 'calc', - - }, + var tx2 = g.select('text.name'), + tx2width = 0; - cliponaxis: __extendFlat_271({}, _$attributes_368.cliponaxis, { - - }), + // secondary label for non-empty 'name' + if(name && name !== text) { + tx2.call(_$drawing_76.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + traceColor) + .text(name) + .attr('data-notex', 1) + .call(_$svg_text_utils_193.positionText, 0, 0) + .call(_$svg_text_utils_193.convertToTspans, gd); + tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; + } + else { + tx2.remove(); + g.select('rect').remove(); + } - orientation: { - valType: 'enumerated', - - values: ['v', 'h'], - editType: 'calc+clearAxisTypes', - - }, + g.select('path') + .style({ + fill: traceColor, + stroke: contrastColor + }); + var tbb = tx.node().getBoundingClientRect(), + htx = d.xa._offset + (d.x0 + d.x1) / 2, + hty = d.ya._offset + (d.y0 + d.y1) / 2, + dx = Math.abs(d.x1 - d.x0), + dy = Math.abs(d.y1 - d.y0), + txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, + anchorStartOK, + anchorEndOK; - base: { - valType: 'any', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, + d.ty0 = outerTop - tbb.top; + d.bx = tbb.width + 2 * HOVERTEXTPAD; + d.by = tbb.height + 2 * HOVERTEXTPAD; + d.anchor = 'start'; + d.txwidth = tbb.width; + d.tx2width = tx2width; + d.offset = 0; - offset: { - valType: 'number', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, - - width: { - valType: 'number', - dflt: null, - min: 0, - arrayOk: true, - - editType: 'calc', - - }, - - marker: marker, - - selected: { - marker: { - opacity: _$attributes_368.selected.marker.opacity, - color: _$attributes_368.selected.marker.color, - editType: 'style' - }, - textfont: _$attributes_368.selected.textfont, - editType: 'style' - }, - unselected: { - marker: { - opacity: _$attributes_368.unselected.marker.opacity, - color: _$attributes_368.unselected.marker.color, - editType: 'style' - }, - textfont: _$attributes_368.unselected.textfont, - editType: 'style' - }, - - r: _$attributes_368.r, - t: _$attributes_368.t, - - _deprecated: { - bardir: { - valType: 'enumerated', - - editType: 'calc', - values: ['v', 'h'], - + if(rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + hty += dy / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } + else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + htx += dx / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_171 = require('../../lib'); */; - -var _$calcSelection_370 = function calcSelection(cd, trace) { - if(_$lib_171.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_171.tagSelected(cd, trace); - } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + tx.attr('text-anchor', d.anchor); + if(tx2width) tx2.attr('text-anchor', d.anchor); + g.attr('transform', 'translate(' + htx + ',' + hty + ')' + + (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); + }); + return hoverLabels; +} -'use strict'; +// Make groups of touching points, and within each group +// move each point so that no labels overlap, but the average +// label position is the same as it was before moving. Indicentally, +// this is equivalent to saying all the labels are on equal linear +// springs about their initial position. Initially, each point is +// its own group, but as we find overlaps we will clump the points. +// +// Also, there are hard constraints at the edges of the graphs, +// that push all groups to the middle so they are visible. I don't +// know what happens if the group spans all the way from one edge to +// the other, though it hardly matters - there's just too much +// information then. +function hoverAvoidOverlaps(hoverData, ax, fullLayout) { + var nummoves = 0, -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_272 = _$lib_171.isArrayOrTypedArray; + // make groups of touching points + pointgroups = hoverData + .map(function(d, i) { + var axis = d[ax]; + return [{ + i: i, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, + pmin: 0, + pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) + }]; + }) + .sort(function(a, b) { return a[0].posref - b[0].posref; }), + donepositioning, + topOverlap, + bottomOverlap, + i, j, + pti, + sumdp; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_58 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_270 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_370 = require('../scatter/calc_selection'); */; + function constrainGroup(grp) { + var minPt = grp[0], + maxPt = grp[grp.length - 1]; -var _$calc_272 = function calc(gd, trace) { - // depending on bar direction, set position and size axes - // and data ranges - // note: this logic for choosing orientation is - // duplicated in graph_obj->setstyles + // overlap with the top - positive vals are overlaps + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; - var xa = _$axes_213.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_213.getFromId(gd, trace.yaxis || 'y'), - orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), - sa, pos, size, i, scalendar; + // overlap with the bottom - positive vals are overlaps + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; - if(orientation === 'h') { - sa = xa; - size = xa.makeCalcdata(trace, 'x'); - pos = ya.makeCalcdata(trace, 'y'); + // check for min overlap first, so that we always + // see the largest labels + // allow for .01px overlap, so we don't get an + // infinite loop from rounding errors + if(topOverlap > 0.01) { + for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; + donepositioning = false; + } + if(bottomOverlap < 0.01) return; + if(topOverlap < -0.01) { + // make sure we're not pushing back and forth + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + donepositioning = false; + } + if(!donepositioning) return; - // 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. - scalendar = trace.xcalendar; - } - else { - sa = ya; - size = ya.makeCalcdata(trace, 'y'); - pos = xa.makeCalcdata(trace, 'x'); - scalendar = trace.ycalendar; - } + // no room to fix positioning, delete off-screen points - // create the "calculated data" to plot - var serieslen = Math.min(pos.length, size.length); - var cd = new Array(serieslen); + // first see how many points we need to delete + var deleteCount = 0; + for(i = 0; i < grp.length; i++) { + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } - // set position and size - for(i = 0; i < serieslen; i++) { - cd[i] = { p: pos[i], s: size[i] }; + // start by deleting points whose data is off screen + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; - if(trace.ids) { - cd[i].id = String(trace.ids[i]); + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } } - } + for(i = 0; i < grp.length; i++) { + if(deleteCount <= 0) break; + pti = grp[i]; - // set base - var base = trace.base, - b; + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; - if(__isArrayOrTypedArray_272(base)) { - for(i = 0; i < Math.min(base.length, cd.length); i++) { - b = sa.d2c(base[i], 0, scalendar); - if(_$fastIsnumeric_18(b)) { - cd[i].b = +b; - cd[i].hasB = 1; + // shift the whole group minus into this new space + bottomOverlap = pti.size * 2; + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; } - else cd[i].b = 0; - } - for(; i < cd.length; i++) { - cd[i].b = 0; } - } - else { - b = sa.d2c(base, 0, scalendar); - var hasBase = _$fastIsnumeric_18(b); - b = hasBase ? b : 0; - for(i = 0; i < cd.length; i++) { - cd[i].b = b; - if(hasBase) cd[i].hasB = 1; + // then delete points that go off the bottom + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } } } - // auto-z and autocolorscale if applicable - if(_$hasColorscale_65(trace, 'marker')) { - _$calc_58(trace, trace.marker.color, 'marker', 'c'); - } - if(_$hasColorscale_65(trace, 'marker.line')) { - _$calc_58(trace, trace.marker.line.color, 'marker.line', 'c'); - } - - _$arraysToCalcdata_270(cd, trace); - _$calcSelection_370(cd, trace); - - return cd; -}; + // loop through groups, combining them if they overlap, + // until nothing moves + while(!donepositioning && nummoves <= hoverData.length) { + // to avoid infinite loops, don't move more times + // than there are traces + nummoves++; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // assume nothing will move in this iteration, + // reverse this if it does + donepositioning = true; + i = 0; + while(i < pointgroups.length - 1) { + // the higher (g0) and lower (g1) point group + var g0 = pointgroups[i], + g1 = pointgroups[i + 1], + // the lowest point in the higher group (p0) + // the highest point in the lower group (p1) + p0 = g0[g0.length - 1], + p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; -'use strict'; + // Only group points that lie on the same axes + if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { + // push the new point(s) added to this group out of the way + for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; + // add them to the group + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); -var _$handleStyleDefaults_283 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { - coerce('marker.color', defaultColor); + // adjust for minimum average movement + sumdp = 0; + for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } + else i++; + } - if(_$hasColorscale_65(traceIn, 'marker')) { - _$colorScaleDefaults_61( - traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} - ); + // check if we're going off the plot on either side and fix + pointgroups.forEach(constrainGroup); } - coerce('marker.line.color', _$color_51.defaultLine); - - if(_$hasColorscale_65(traceIn, 'marker.line')) { - _$colorScaleDefaults_61( - traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} - ); + // now put these offsets into hoverData + for(i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for(j = grp.length - 1; j >= 0; j--) { + var pt = grp[j], + hoverPt = hoverData[pt.i]; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } } +} - coerce('marker.line.width'); - coerce('marker.opacity'); - coerce('selected.marker.color'); - coerce('unselected.marker.color'); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; +function alignHoverText(hoverLabels, rotateLabels) { + // finally set the text positioning relative to the data and draw the + // box around it + hoverLabels.each(function(d) { + var g = _$d3_15.select(this); + if(d.del) { + g.remove(); + return; + } + var horzSign = d.anchor === 'end' ? -1 : 1, + tx = g.select('text.nums'), + alignShift = {start: 1, end: -1, middle: 0}[d.anchor], + txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), + tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), + offsetX = 0, + offsetY = d.offset; + if(d.anchor === 'middle') { + txx -= d.tx2width / 2; + tx2x += d.txwidth / 2 + HOVERTEXTPAD; + } + if(rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = d.offset * YSHIFTX; + } -/* removed: var _$registry_261 = require('../../registry'); */; + g.select('path').attr('d', d.anchor === 'middle' ? + // middle aligned: rect centered on data + ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + + 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : + // left or right aligned: side rect with arrow to data + ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + + 'v' + (d.by / 2 - HOVERARROWSIZE) + + 'h' + (horzSign * d.bx) + + 'v-' + d.by + + 'H' + (horzSign * HOVERARROWSIZE + offsetX) + + 'V' + (offsetY - HOVERARROWSIZE) + + 'Z')); + tx.call(_$svg_text_utils_193.positionText, + txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); -var _$handleXYDefaults_392 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { - var len, - x = coerce('x'), - y = coerce('y'); + if(d.tx2width) { + g.select('text.name') + .call(_$svg_text_utils_193.positionText, + tx2x + alignShift * HOVERTEXTPAD + offsetX, + offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + g.select('rect') + .call(_$drawing_76.setRect, + tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, + offsetY - d.by / 2 - 1, + d.tx2width, d.by + 2); + } + }); +} - var handleCalendarDefaults = _$registry_261.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); +function cleanPoint(d, hovermode) { + var index = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index] || {}; - if(x) { - if(y) { - len = Math.min(x.length, y.length); - } - else { - len = x.length; - coerce('y0'); - coerce('dy'); - } - } - else { - if(!y) return 0; + var getVal = Array.isArray(index) ? + function(calcKey, traceKey) { + return _$lib_172.castOption(cd0, index, calcKey) || + _$lib_172.extractOption({}, trace, '', traceKey); + } : + function(calcKey, traceKey) { + return _$lib_172.extractOption(cd, trace, calcKey, traceKey); + }; - len = traceOut.y.length; - coerce('x0'); - coerce('dx'); + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if(val) d[key] = val; } - traceOut._length = len; + fill('hoverinfo', 'hi', 'hoverinfo'); + fill('color', 'hbg', 'hoverlabel.bgcolor'); + fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); + fill('fontFamily', 'htf', 'hoverlabel.font.family'); + fill('fontSize', 'hts', 'hoverlabel.font.size'); + fill('fontColor', 'htc', 'hoverlabel.font.color'); + fill('nameLength', 'hnl', 'hoverlabel.namelength'); - return len; -}; + d.posref = hovermode === 'y' ? + (d.xa._offset + (d.x0 + d.x1) / 2) : + (d.ya._offset + (d.y0 + d.y1) / 2); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // then constrain all the positions to be on the plot + d.x0 = _$lib_172.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_172.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_172.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_172.constrain(d.y1, 0, d.ya._length); + // and convert the x and y label values into formatted text + if(d.xLabelVal !== undefined) { + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_214.hoverLabelText(d.xa, d.xLabelVal); + d.xVal = d.xa.c2d(d.xLabelVal); + } + if(d.yLabelVal !== undefined) { + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_214.hoverLabelText(d.ya, d.yLabelVal); + d.yVal = d.ya.c2d(d.yLabelVal); + } -'use strict'; + // Traces like heatmaps generate the zLabel in their hoverPoints function + if(d.zLabelVal !== undefined && d.zLabel === undefined) { + d.zLabel = String(d.zLabelVal); + } -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$registry_261 = require('../../registry'); */; + // for box means and error bars, add the range to the label + if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { + var xeText = _$axes_214.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + if(d.xerrneg !== undefined) { + d.xLabel += ' +' + xeText + ' / -' + + _$axes_214.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + else d.xLabel += ' ± ' + xeText; -/* removed: var _$handleXYDefaults_392 = require('../scatter/xy_defaults'); */; -/* removed: var _$handleStyleDefaults_283 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_271 = require('./attributes'); */; + // small distance penalty for error bars, so that if there are + // traces with errors and some without, the error bar label will + // hoist up to the point + if(hovermode === 'x') d.distance += 1; + } + if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { + var yeText = _$axes_214.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + if(d.yerrneg !== undefined) { + d.yLabel += ' +' + yeText + ' / -' + + _$axes_214.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + } + else d.yLabel += ' ± ' + yeText; -var _$supplyDefaults_273 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_271, attr, dflt); + if(hovermode === 'y') d.distance += 1; } - var coerceFont = _$lib_171.coerceFont; + var infomode = d.hoverinfo || d.trace.hoverinfo; - var len = _$handleXYDefaults_392(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; + if(infomode !== 'all') { + infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); + if(infomode.indexOf('x') === -1) d.xLabel = undefined; + if(infomode.indexOf('y') === -1) d.yLabel = undefined; + if(infomode.indexOf('z') === -1) d.zLabel = undefined; + if(infomode.indexOf('text') === -1) d.text = undefined; + if(infomode.indexOf('name') === -1) d.name = undefined; } - coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); - coerce('base'); - coerce('offset'); - coerce('width'); + return d; +} - coerce('text'); - coerce('hovertext'); +function createSpikelines(closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var evt = opts.event; + var xa, + ya; - var textPosition = coerce('textposition'); + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; - var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', - hasInside = hasBoth || textPosition === 'inside', - hasOutside = hasBoth || textPosition === 'outside'; + // Remove old spikeline items + container.selectAll('.spikeline').remove(); - if(hasInside || hasOutside) { - var textFont = coerceFont(coerce, 'textfont', layout.font); - if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); - if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); - coerce('constraintext'); - coerce('selected.textfont.color'); - coerce('unselected.textfont.color'); - coerce('cliponaxis'); - } + if(!(showX || showY)) return; - _$handleStyleDefaults_283(traceIn, traceOut, coerce, defaultColor, layout); + var contrastColor = _$color_51.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); - // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_261.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_51.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_51.defaultLine, {axis: 'x', inherit: 'y'}); + // Horizontal line (to y-axis) + if(showY) { + var hLinePoint = closestPoints.hLinePoint, + hLinePointX, + hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; - _$lib_171.coerceSelectionMarkerOpacity(traceOut, coerce); -}; + if(ySnap === 'cursor') { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = _$tinycolor_33.readability(hLinePoint.color, contrastColor) < 1.5 ? + _$color_51.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode, + yThickness = ya.spikethickness, + yColor = ya.spikecolor || dfltHLineColor, + yBB = ya._boundingBox, + xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, + xBase, + xEndSpike; -var _$client_22 = true; -var _$hasHover_20 = {}; -(function (global){ -'use strict' - -/* removed: var _$client_22 = require('is-browser') */; -var hasHover - -if (typeof global.matchMedia === 'function') { - hasHover = !global.matchMedia('(hover: none)').matches -} -else { - hasHover = _$client_22 -} - -_$hasHover_20 = hasHover + if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { + if(yMode.indexOf('toaxis') !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; + } + if(yMode.indexOf('across') !== -1) { + xBase = ya._counterSpan[0]; + xEndSpike = ya._counterSpan[1]; + } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -'use strict' - -/* removed: var _$client_22 = require('is-browser') */; - -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 -} - -var _$hasPassiveEvents_21 = _$client_22 && detect() + // Foreground horizontal line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness, + 'stroke': yColor, + 'stroke-dasharray': _$drawing_76.dashStyle(ya.spikedash, yThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); -var rootPosition = { left: 0, top: 0 } + // Background horizontal Line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + // Y axis marker + if(yMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), + 'cy': hLinePointY, + 'r': yThickness, + 'fill': yColor + }) + .classed('spikeline', true); + } + } -var _$mouseEventOffset_23 = mouseEventOffset -function mouseEventOffset (ev, target, out) { - target = target || ev.currentTarget || ev.srcElement - if (!Array.isArray(out)) { - out = [ 0, 0 ] - } - var cx = ev.clientX || 0 - var cy = ev.clientY || 0 - var rect = getBoundingClientOffset(target) - out[0] = cx - rect.left - out[1] = cy - rect.top - return out + if(showX) { + var vLinePoint = closestPoints.vLinePoint, + vLinePointX, + vLinePointY; + + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; + + if(xSnap === 'cursor') { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; + } + var dfltVLineColor = _$tinycolor_33.readability(vLinePoint.color, contrastColor) < 1.5 ? + _$color_51.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode, + xThickness = xa.spikethickness, + xColor = xa.spikecolor || dfltVLineColor, + xBB = xa._boundingBox, + yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, + yBase, + yEndSpike; + + if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { + if(xMode.indexOf('toaxis') !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if(xMode.indexOf('across') !== -1) { + yBase = xa._counterSpan[0]; + yEndSpike = xa._counterSpan[1]; + } + + // Foreground vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness, + 'stroke': xColor, + 'stroke-dasharray': _$drawing_76.dashStyle(xa.spikedash, xThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + + // X axis marker + if(xMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': vLinePointX, + 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), + 'r': xThickness, + 'fill': xColor + }) + .classed('spikeline', true); + } + } } -function getBoundingClientOffset (element) { - if (element === window || - element === document || - element === document.body) { - return rootPosition - } else { - return element.getBoundingClientRect() - } +function hoverChanged(gd, evt, oldhoverdata) { + // don't emit any events if nothing changed + if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + + for(var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i], + newPt = gd._hoverdata[i]; + if(oldPt.curveNumber !== newPt.curveNumber || + String(oldPt.pointNumber) !== String(newPt.pointNumber)) { + return true; + } + } + return false; +} + +function spikesChanged(gd, oldspikepoints) { + // don't relayout the plot because of new spikelines if spikelines points didn't change + if(!oldspikepoints) return true; + if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || + oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint + ) return true; + return false; } /** @@ -30850,28 +31439,33 @@ function getBoundingClientOffset (element) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$registry_262 = require('../../registry'); */; +var hover = _$hover_91.hover; -// 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 -var _$align_71 = function align(v, dv, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0), - vmax = vmin + dv / (v1 - v0), - vc = (vmin + vmax) / 2; +var _$click_87 = function click(gd, evt, subplot) { + var annotationsDone = _$registry_262.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); - // explicitly specified anchor - if(anchor === 'left' || anchor === 'bottom') return vmin; - if(anchor === 'center' || anchor === 'middle') return vc; - if(anchor === 'right' || anchor === 'top') return vmax; + // 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); + } - // automatic based on position - if(vmin < (2 / 3) - vc) return vmin; - if(vmax > (4 / 3) - vc) return vmax; - return vc; + 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(); + } }; /** @@ -30882,33 +31476,39 @@ var _$align_71 = function align(v, dv, v0, v1, anchor) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var _$handleHoverLabelDefaults_92 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { + opts = opts || {}; -// 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'] -]; + coerce('hoverlabel.bgcolor', opts.bgcolor); + coerce('hoverlabel.bordercolor', opts.bordercolor); + coerce('hoverlabel.namelength', opts.namelength); + _$lib_172.coerceFont(coerce, 'hoverlabel.font', opts.font); +}; -var _$getCursor_72 = 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_171.constrain(Math.floor(x * 3), 0, 2); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(yanchor === 'bottom') y = 0; - else if(yanchor === 'middle') y = 1; - else if(yanchor === 'top') y = 2; - else y = _$lib_171.constrain(Math.floor(y * 3), 0, 2); +'use strict'; - return cursorset[y][x]; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$attributes_85 = require('./attributes'); */; +/* removed: var _$handleHoverLabelDefaults_92 = require('./hoverlabel_defaults'); */; + +var _$supplyDefaults_89 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_172.coerce(traceIn, traceOut, _$attributes_85, attr, dflt); + } + + _$handleHoverLabelDefaults_92(traceIn, traceOut, coerce, layout.hoverlabel); }; /** @@ -30921,330 +31521,169 @@ var _$getCursor_72 = function getCursor(x, y, xanchor, yanchor) { 'use strict'; -var _$constants_88 = { - // hover labels for multiple horizontal bars get tilted by this angle - YANGLE: 60, +/* removed: var _$constants_88 = require('./constants'); */; - // size and display constants for hover text +var __fontAttrs_94 = _$font_attributes_240({ + editType: 'none', + +}); +__fontAttrs_94.family.dflt = _$constants_88.HOVERFONT; +__fontAttrs_94.size.dflt = _$constants_88.HOVERFONTSIZE; - // pixel size of hover arrows - HOVERARROWSIZE: 6, - // pixels padding around text - HOVERTEXTPAD: 3, - // hover font - HOVERFONTSIZE: 13, - HOVERFONT: 'Arial, sans-serif', +var _$layout_attributes_94 = { + dragmode: { + valType: 'enumerated', + + values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], + dflt: 'zoom', + editType: 'modebar', + + }, + hovermode: { + valType: 'enumerated', + + values: ['x', 'y', 'closest', false], + editType: 'modebar', + + }, + hoverdistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + spikedistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'none', + + }, + bordercolor: { + valType: 'color', + + editType: 'none', + + }, + font: __fontAttrs_94, + namelength: { + valType: 'integer', + min: -1, + dflt: 15, + + editType: 'none', + + }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + + editType: 'none' + } +}; - // minimum time (msec) between hover calls - HOVERMINTIME: 50, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // ID suffix (with fullLayout._uid) for hover events in the throttle cache - HOVERID: '-hover' -}; +'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. +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$layout_attributes_94 = require('./layout_attributes'); */; -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -var _$EventEmitter_17 = EventEmitter; +var _$supplyLayoutDefaults_95 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_94, attr, dflt); + } -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; + var hovermodeDflt; + if(layoutOut._has('cartesian')) { + // flag for 'horizontal' plots: + // determines the state of the mode bar 'compare' hovermode button + layoutOut._isHoriz = isHoriz(fullData); + hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + } + else hovermodeDflt = 'closest'; -// 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. -EventEmitter.defaultMaxListeners = 10; + var hoverMode = coerce('hovermode', hovermodeDflt); + if(hoverMode) { + coerce('hoverdistance'); + coerce('spikedistance'); + } -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; + // if only mapbox or geo subplots is present on graph, + // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, + // so that the correct modebar button is active + var hasMapbox = layoutOut._has('mapbox'); + var hasGeo = layoutOut._has('geo'); + var len = layoutOut._basePlotModules.length; + + if(layoutOut.dragmode === 'zoom' && ( + ((hasMapbox || hasGeo) && len === 1) || + (hasMapbox && hasGeo && len === 2) + )) { + layoutOut.dragmode = 'pan'; + } }; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; +function isHoriz(fullData) { + var out = true; - if (!this._events) - this._events = {}; + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } + if(trace.orientation !== 'h') { + out = false; + break; + } } - } - handler = this._events[type]; + return out; +} - if (isUndefined(handler)) - return false; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; +'use strict'; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$handleHoverLabelDefaults_92 = require('./hoverlabel_defaults'); */; +/* removed: var _$layout_attributes_94 = require('./layout_attributes'); */; - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); +var _$supplyLayoutGlobalDefaults_96 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce(attr, dflt) { + return _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_94, attr, dflt); } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); + _$handleHoverLabelDefaults_92(layoutIn, layoutOut, coerce); }; -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31253,164 +31692,75 @@ function isUndefined(arg) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* global jQuery:false */ - -var __EventEmitter_164 = _$EventEmitter_17.EventEmitter; - -var Events = { - - init: function(plotObj) { - - /* - * If we have already instantiated an emitter for this plot - * return early. - */ - if(plotObj._ev instanceof __EventEmitter_164) return plotObj; - - var ev = new __EventEmitter_164(); - var internalEv = new __EventEmitter_164(); - - /* - * Assign to plot._ev while we still live in a land - * where plot is a DOM element with stuff attached to it. - * In the future we can make plot the event emitter itself. - */ - plotObj._ev = ev; - - /* - * Create a second event handler that will manage events *internally*. - * This allows parts of plotly to respond to thing like relayout without - * having to use the user-facing event handler. They cannot peacefully - * coexist on the same handler because a user invoking - * plotObj.removeAllListeners() would detach internal events, breaking - * plotly. - */ - plotObj._internalEv = internalEv; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$helpers_90 = require('./helpers'); */; +/* removed: var _$layout_attributes_94 = require('./layout_attributes'); */; - /* - * Assign bound methods from the ev to the plot object. These methods - * will reference the 'this' of plot._ev even though they are methods - * of plot. This will keep the event machinery away from the plot object - * which currently is often a DOM element but presents an API that will - * continue to function when plot becomes an emitter. Not all EventEmitter - * methods have been bound to `plot` as some do not currently add value to - * the Plotly event API. - */ - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); +var _$fx_93 = { + moduleType: 'component', + name: 'fx', - /* - * Create funtions for managing internal events. These are *only* triggered - * by the mirroring of external events via the emit function. - */ - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); + constants: _$constants_88, + schema: { + layout: _$layout_attributes_94 + }, - /* - * We must wrap emit to continue to support JQuery events. The idea - * is to check to see if the user is using JQuery events, if they are - * we emit JQuery events to trigger user handlers as well as the EventEmitter - * events. - */ - plotObj.emit = function(event, data) { - if(typeof jQuery !== 'undefined') { - jQuery(plotObj).trigger(event, data); - } + attributes: _$attributes_85, + layoutAttributes: _$layout_attributes_94, - ev.emit(event, data); - internalEv.emit(event, data); - }; + supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_96, + supplyDefaults: _$supplyDefaults_89, + supplyLayoutDefaults: _$supplyLayoutDefaults_95, - return plotObj; - }, + calc: _$calc_86, - /* - * This function behaves like jQueries triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - * - * Note: triggerHandler has been recommended for deprecation in v2.0.0, - * so the additional behavior of triggerHandler triggering internal events - * is deliberate excluded in order to avoid reinforcing more usage. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - /* - * If Jquery exists run all its handlers for this event and - * collect the return value of the LAST handler function - */ - if(typeof jQuery !== 'undefined') { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); - } + getDistanceFunction: _$helpers_90.getDistanceFunction, + getClosest: _$helpers_90.getClosest, + inbox: _$helpers_90.inbox, + quadrature: _$helpers_90.quadrature, + appendArrayPointValue: _$helpers_90.appendArrayPointValue, - /* - * Now run all the node style event handlers - */ - var ev = plotObj._ev; - if(!ev) return jQueryHandlerValue; + castHoverOption: castHoverOption, + castHoverinfo: castHoverinfo, - var handlers = ev._events[event]; - if(!handlers) return jQueryHandlerValue; + hover: _$hover_91.hover, + unhover: _$dragelement_73.unhover, - /* - * handlers can be function or an array of functions - */ - if(typeof handlers === 'function') handlers = [handlers]; - var lastHandler = handlers.pop(); + loneHover: _$hover_91.loneHover, + loneUnhover: loneUnhover, - /* - * Call all the handlers except the last one. - */ - for(var i = 0; i < handlers.length; i++) { - handlers[i](data); - } + click: _$click_87 +}; - /* - * Now call the final handler and collect its value - */ - nodeEventHandlerValue = lastHandler(data); +function loneUnhover(containerOrSelection) { + // duck type whether the arg is a d3 selection because ie9 doesn't + // handle instanceof like modern browsers do. + var selection = _$lib_172.isD3Selection(containerOrSelection) ? + containerOrSelection : + _$d3_15.select(containerOrSelection); - /* - * Return either the jquery handler value if it exists or the - * nodeEventHandler value. Jquery event value superceeds nodejs - * events for backwards compatability reasons. - */ - return jQueryHandlerValue !== undefined ? jQueryHandlerValue : - nodeEventHandlerValue; - }, + selection.selectAll('g.hovertext').remove(); + selection.selectAll('.spikeline').remove(); +} - purge: function(plotObj) { - delete plotObj._ev; - delete plotObj.on; - delete plotObj.once; - delete plotObj.removeListener; - delete plotObj.removeAllListeners; - delete plotObj.emit; +// helpers for traces that use Fx.loneHover - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; +function castHoverOption(trace, ptNumber, attr) { + return _$lib_172.castOption(trace, ptNumber, 'hoverlabel.' + attr); +} - return plotObj; +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return _$lib_172.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } -}; - -var _$Events_164 = Events; + return _$lib_172.castOption(trace, ptNumber, 'hoverinfo', _coerce); +} -var _$unhover_74 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31419,56 +31769,25 @@ var _$unhover_74 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; - -/* removed: var _$Events_164 = require('../../lib/events'); */; -/* removed: var _$throttle_193 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_169 = require('../../lib/get_graph_div'); */; - -/* removed: var _$constants_88 = require('../fx/constants'); */; - -var unhover = _$unhover_74 = {}; - - -unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_169(gd); - - // Important, clear any queued hovers - if(gd._fullLayout) { - _$throttle_193.clear(gd._fullLayout._uid + _$constants_88.HOVERID); - } - - unhover.raw(gd, evt, subplot); -}; - - -// remove hover effects on mouse out, and emit unhover event -unhover.raw = function unhoverRaw(gd, evt) { +/** + * 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 + */ +var _$clearGlCanvases_161 = function clearGlCanvases(gd) { var fullLayout = gd._fullLayout; - var oldhoverdata = gd._hoverdata; - - if(!evt) evt = {}; - if(evt.target && - _$Events_164.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 + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); }); } }; -var _$dragelement_73 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31480,2142 +31799,2402 @@ var _$dragelement_73 = {}; 'use strict'; -/* removed: var _$mouseEventOffset_23 = require('mouse-event-offset'); */; -/* removed: var _$hasHover_20 = require('has-hover'); */; -/* removed: var _$hasPassiveEvents_21 = require('has-passive-events'); */; +var FROM_BL = _$alignment_151.FROM_BL; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +var _$scaleZoom_230 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } -/* removed: var _$constants_218 = require('../../plots/cartesian/constants'); */; -/* removed: var _$interactions_153 = require('../../constants/interactions'); */; + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; -var dragElement = _$dragelement_73 = {}; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; -dragElement.align = _$align_71; -dragElement.getCursor = _$getCursor_72; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$unhover_74 = require('./unhover'); */; -dragElement.unhover = _$unhover_74.wrapped; -dragElement.unhoverRaw = _$unhover_74.raw; +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; -/** - * 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 DBLCLICKDELAY = _$interactions_153.DBLCLICKDELAY; - var element = options.element; - - var startX, - startY, - newMouseDownTime, - cursor, - dragCover, - initialEvent, - initialTarget, - rightClick; - - if(!gd._mouseDownTime) gd._mouseDownTime = 0; + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - element.style.pointerEvents = 'all'; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; +} - element.onmousedown = onStart; +var _$BuildLog_25 = BuildLog; - if(!_$hasPassiveEvents_21) { - element.ontouchstart = onStart; - } - else { - if(element._ontouchstart) { - element.removeEventListener('touchstart', element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener('touchstart', onStart, {passive: false}); - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - function _clampFn(dx, dy, minDrag) { - if(Math.abs(dx) < minDrag) dx = 0; - if(Math.abs(dy) < minDrag) dy = 0; - return [dx, dy]; - } +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// - var clampFn = options.clampFn || _clampFn; +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; - function onStart(e) { - e.preventDefault(); + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; - // 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; + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { - // in a click train - numClicks += 1; - } - else { - // new click train - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; - if(options.prepFn) options.prepFn(e, startX, startY); + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - if(_$hasHover_20 && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } - else if(!_$hasHover_20) { - // 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; - } + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - document.addEventListener('mousemove', onMove); - document.addEventListener('mouseup', onDone); - document.addEventListener('touchmove', onMove); - document.addEventListener('touchend', onDone); + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; - return; - } + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; - function onMove(e) { - e.preventDefault(); + // categorize where intersection point is along A and B - var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_218.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - if(dx || dy) { - gd._dragged = true; - dragElement.unhover(gd); - } + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; - return; - } + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside - function onDone(e) { - document.removeEventListener('mousemove', onMove); - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchmove', onMove); - document.removeEventListener('touchend', onDone); + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} - e.preventDefault(); +var _$Epsilon_26 = Epsilon; - if(_$hasHover_20) { - _$lib_171.removeElement(dragCover); - } - else if(cursor) { - dragCover.documentElement.style.cursor = cursor; - cursor = null; - } +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if(!gd._dragging) { - gd._dragged = false; - return; - } - gd._dragging = false; +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// - // don't count as a dblClick unless the mouseUp is also within - // the dblclick delay - if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - if(gd._dragged) { - if(options.doneFn) options.doneFn(e); - } - else { - if(options.clickFn) options.clickFn(numClicks, initialEvent); + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - // 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; + // 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] }); + } - 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); - } + // the first LineString is considered the outside + var out = LineString(coords[0]); - initialTarget.dispatchEvent(e2); - } - } + // 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]))); - finishDrag(gd); + return out; + } - gd._dragged = false; + 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'); + }, - return; - } -}; + // 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)); -function coverSlip() { - var cover = document.createElement('div'); + // 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); + } - 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'; + // calculate inside heirarchy + // + // _____________________ _______ roots -> A -> F + // | A | | F | | | + // | _______ _______ | | ___ | +-- B +-- G + // | | B | | C | | | | | | | | + // | | ___ | | ___ | | | | | | | +-- D + // | | | D | | | | E | | | | | G | | | + // | | |___| | | |___| | | | | | | +-- C + // | |_______| |_______| | | |___| | | + // |_____________________| |_______| +-- E - document.body.appendChild(cover); + function newNode(region){ + return { + region: region, + children: [] + }; + } - return cover; -} + var roots = newNode(null); -dragElement.coverSlip = coverSlip; + 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; + } + } -function finishDrag(gd) { - gd._dragging = false; - if(gd._replotPending) _$registry_261.call('plot', gd); -} - -function pointerOffset(e) { - return _$mouseEventOffset_23( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); -} + // 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--; + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // now we can add ourselves + root.children.push(node); + } -'use strict'; + // 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); + } -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$registry_261 = require('../../registry'); */; + // 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 -var _$calc_86 = function calc(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - function makeCoerceHoverInfo(trace) { - return function(val) { - return _$lib_171.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); - }; - } + 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; + } - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + var geopolys = []; - // 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_261.traceIs(trace, 'pie')) continue; + 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])); + } - var fillFn = _$registry_261.traceIs(trace, '2dMap') ? paste : _$lib_171.fillArray; + 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); + } - fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - if(!trace.hoverlabel) continue; + // lastly, construct the approrpriate GeoJSON object - 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'); - } + 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 + }; + } }; -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_171.identity; - - if(Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); - } -} - -var _$helpers_90 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$GeoJSON_27 = GeoJSON; -'use strict'; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$lib_171 = require('../../lib'); */; +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// -// look for either subplot or xaxis and yaxis attributes -_$helpers_90.getSubplot = function getSubplot(trace) { - return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } }; -// convenience functions for mapping all relevant axes -_$helpers_90.flat = function flat(subplots, v) { - var out = new Array(subplots.length); - for(var i = 0; i < subplots.length; i++) { - out[i] = v; - } - return out; -}; +var _$LinkedList_29 = LinkedList; -_$helpers_90.p2c = function p2c(axArray, v) { - var out = new Array(axArray.length); - for(var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); - } - return out; -}; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -_$helpers_90.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { - if(mode === 'closest') return dxy || _$helpers_90.quadrature(dx, dy); - return mode === 'x' ? dx : dy; -}; +// +// this is the core work-horse +// -_$helpers_90.getClosest = function getClosest(cd, distfn, pointData) { - // do we already have a point number? (array mode only) - if(pointData.index !== false) { - if(pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } - else pointData.index = false; - } - else { - // apply the distance function to each data point - // this is the longest loop... if this bogs down, we may need - // to create pre-sorted data (by x or y), not sure how to - // do this for 'closest' - for(var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if(newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } - } - } - return pointData; -}; +/* removed: var _$LinkedList_29 = require('./linked-list'); */; -/* - * pseudo-distance function for hover effects on areas: inside the region - * distance is finite (`passVal`), outside it's Infinity. - * - * @param {number} v0: signed difference between the current position and the left edge - * @param {number} v1: signed difference between the current position and the right edge - * @param {number} passVal: the value to return on success - */ -_$helpers_90.inbox = function inbox(v0, v1, passVal) { - return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; -}; +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm -_$helpers_90.quadrature = function quadrature(dx, dy) { - return function(di) { - var x = dx(di), - y = dy(di); - return Math.sqrt(x * x + y * y); - }; -}; + // + // segment creation + // -/** Fill event data point object for hover and selection. - * Invokes _module.eventData if present. - * - * N.B. note that point 'index' corresponds to input data array index - * whereas 'number' is its post-transform version. - * - * If the hovered/selected pt corresponds to an multiple input points - * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' - * are include in the event data. - * - * @param {object} pt - * @param {object} trace - * @param {object} cd - * @return {object} - */ -_$helpers_90.makeEventData = function makeEventData(pt, trace, cd) { - // hover uses 'index', select uses 'pointNumber' - var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber: pointNumber - }; + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } - if(trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; + // + // event logic + // - if(pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; - } + var event_root = _$LinkedList_29.create(); - if(trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if('xVal' in pt) out.x = pt.xVal; - else if('x' in pt) out.x = pt.x; + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same - if('yVal' in pt) out.y = pt.yVal; - else if('y' in pt) out.y = pt.y; + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - if(pt.xa) out.xaxis = pt.xa; - if(pt.ya) out.yaxis = pt.ya; - if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; - } + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start - _$helpers_90.appendArrayPointValue(out, trace, pointNumber); + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } - return out; -}; + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } -/** Appends values inside array attributes corresponding to given point number - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {number|Array(number)} pointNumber : point number. May be a length-2 array - * [row, col] to dig into 2D arrays - */ -_$helpers_90.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_29.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } - if(!arrayAttrs) { - return; - } + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_29.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } - if(pointData[key] === undefined) { - var val = _$lib_171.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) - if(pointVal !== undefined) pointData[key] = pointVal; - } - } -}; + if (buildLog) + buildLog.segmentChop(ev.seg, end); -/** - * Appends values inside array attributes corresponding to given point number array - * For use when pointData references a plot entity that arose (or potentially arose) - * from multiple points in the input data - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. - * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays - */ -_$helpers_90.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } - if(!arrayAttrs) { - return; - } + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used - if(pointData[key] === undefined) { - var val = _$lib_171.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); + // + // status logic + // - for(var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); - } - pointData[key] = keyVal; - } - } -}; + var status_root = _$LinkedList_29.create(); -var pointKeyMap = { - ids: 'id', - locations: 'location', - labels: 'label', - values: 'value', - 'marker.colors': 'color' -}; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; -function getPointKey(astr) { - return pointKeyMap[astr] || astr; -} + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } -function getPointData(val, pointNumber) { - if(Array.isArray(pointNumber)) { - if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; - } - } else { - return val[pointNumber]; - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } -// works with our CSS cursor classes (see css/_cursor.scss) -// to apply cursors to d3 single-element selections. -// omit cursor to revert to the default. -var _$setCursor_190 = function setCursor(el3, csr) { - (el3.attr('class') || '').split(' ').forEach(function(cls) { - if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); - }); + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal - if(csr) el3.classed('cursor-' + csr, true); -}; + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (buildLog) + buildLog.checkIntersection(seg1, seg2); + var i = eps.linesIntersect(a1, a2, b1, b2); -'use strict'; + if (i === false){ + // segments are parallel or coincident -/* removed: var _$setCursor_190 = require('./setcursor'); */; + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) -var STASHATTR = 'data-savedcursor'; -var NO_CURSOR = '!!'; + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection -/* - * works with our CSS cursor classes (see css/_cursor.scss) - * to override a previous cursor set on d3 single-element selections, - * by moving the name of the original cursor to the data-savedcursor attr. - * omit cursor to revert to the previously set value. - */ -var _$overrideCursor_182 = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if(csr) { - if(!savedCursor) { - var classes = (el3.attr('class') || '').split(' '); - for(var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if(cls.indexOf('cursor-') === 0) { - el3.attr(STASHATTR, cls.substr(7)) - .classed(cls, false); - } - } - if(!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); - } - } - _$setCursor_190(el3, csr); - } - else if(savedCursor) { - el3.attr(STASHATTR, null); + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); - if(savedCursor === NO_CURSOR) _$setCursor_190(el3); - else _$setCursor_190(el3, savedCursor); - } -}; + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal -var _$hover_91 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); -'use strict'; + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$Events_164 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_182 = require('../../lib/override_cursor'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_261 = require('../../registry'); */; + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints -/* removed: var _$helpers_90 = require('./helpers'); */; -/* removed: var _$constants_88 = require('./constants'); */; + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } -// hover labels for multiple horizontal bars get tilted by some angle, -// then need to be offset differently if they overlap -var YANGLE = _$constants_88.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } -// expansion of projected height -var YFACTOR = 1 / Math.sin(YA_RADIANS); + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); -// to make the appropriate post-rotation x offset, -// you need both x and y offsets -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); + if (buildLog) + buildLog.vert(ev.pt[0]); -// size and display constants for hover text -var HOVERARROWSIZE = _$constants_88.HOVERARROWSIZE; -var HOVERTEXTPAD = _$constants_88.HOVERTEXTPAD; + if (ev.isStart){ -// fx.hover: highlight data on hover -// evt can be a mousemove event, or an object with data about what points -// to hover on -// {xpx,ypx[,hovermode]} - pixel locations from top left -// (with optional overriding hovermode) -// {xval,yval[,hovermode]} - data values -// [{curveNumber,(pointNumber|xval and/or yval)}] - -// array of specific points to highlight -// pointNumber is a single integer if gd.data[curveNumber] is 1D, -// or a two-element array if it's 2D -// xval and yval are data values, -// 1D data may specify either or both, -// 2D data must specify both -// subplot is an id string (default "xy") -// makes use of gl.hovermode, which can be: -// x (find the points with the closest x values, ie a column), -// closest (find the single closest point) -// internally there are two more that occasionally get used: -// y (pick out a row - only used for multiple horizontal bar charts) -// array (used when the user specifies an explicit -// array of points to hover on) -// -// We wrap the hovers in a timer, to limit their frequency. -// The actual rendering is done by private function _hover. -_$hover_91.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_171.getGraphDiv(gd); + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); - _$lib_171.throttle( - gd._fullLayout._uid + _$constants_88.HOVERID, - _$constants_88.HOVERMINTIME, - function() { _hover(gd, evt, subplot, noHoverEvent); } - ); -}; + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; -/* - * Draw a single hover item in a pre-existing svg container somewhere - * hoverItem should have keys: - * - x and y (or x0, x1, y0, and y1): - * the pixel position to mark, relative to opts.container - * - xLabel, yLabel, zLabel, text, and name: - * info to go in the label - * - color: - * the background color for the label. - * - idealAlign (optional): - * 'left' or 'right' for which side of the x/y box to try to put this on first - * - borderColor (optional): - * color for the border, defaults to strongest contrast with color - * - fontFamily (optional): - * string, the font for this label, defaults to constants.HOVERFONT - * - fontSize (optional): - * the label font size, defaults to constants.HOVERFONTSIZE - * - fontColor (optional): - * defaults to borderColor - * opts should have keys: - * - bgColor: - * the background color this is against, used if the trace is - * non-opaque, and for the name, which goes outside the box - * - container: - * a or element to add the hover label to - * - outerContainer: - * normally a parent of `container`, sets the bounding box to use to - * constrain the hover label and determine whether to show it on the left or right - */ -_$hover_91.loneHover = function loneHover(hoverItem, opts) { - var pointData = { - color: hoverItem.color || _$color_51.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } - // filler to make createHoverText happy - trace: { - index: 0, - hoverinfo: '' - }, - xa: {_offset: 0}, - ya: {_offset: 0}, - index: 0 - }; + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev - var container3 = _$d3_15.select(opts.container), - outerContainer3 = opts.outerContainer ? - _$d3_15.select(opts.outerContainer) : container3; + // merge ev.seg's fill information into eve.seg - var fullOpts = { - hovermode: 'closest', - rotateLabels: false, - bgColor: opts.bgColor || _$color_51.background, - container: container3, - outerContainer: outerContainer3 - }; + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); - alignHoverText(hoverLabel, fullOpts.rotateLabels); + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } - return hoverLabel.node(); -}; + if (buildLog) + buildLog.segmentUpdate(eve.seg); -// The actual implementation is here: -function _hover(gd, evt, subplot, noHoverEvent) { - if(!subplot) subplot = 'xy'; + ev.other.remove(); + ev.remove(); + } - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } - var fullLayout = gd._fullLayout; - var plots = fullLayout._plots || []; - var plotinfo = plots[subplot]; - var hasCartesian = fullLayout._has('cartesian'); + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } - subplots = subplots.concat(overlayedSubplots); - } + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point - var len = subplots.length; - var xaArray = new Array(len); - var yaArray = new Array(len); - var supportsCompare = false; + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } - for(var i = 0; i < len; i++) { - var spId = subplots[i]; + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // 'cartesian' case - var plotObj = plots[spId]; - if(plotObj) { - supportsCompare = true; + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_29.node({ ev: ev })); + } + else{ + var st = ev.status; - // TODO make sure that fullLayout_plots axis refs - // get updated properly so that we don't have - // to use Axes.getFromId in general. + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } - xaArray[i] = _$axes_213.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_213.getFromId(gd, plotObj.yaxis._id); - continue; - } + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); - // other subplot types - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; - } + if (buildLog) + buildLog.statusRemove(st.ev.seg); - var hovermode = evt.hovermode || fullLayout.hovermode; + // remove the status + st.remove(); - if(hovermode && !supportsCompare) hovermode = 'closest'; + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } - if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || - gd.querySelector('.zoombox') || gd._dragging) { - return _$dragelement_73.unhoverRaw(gd, evt); - } + // remove the event and continue + event_root.getHead().remove(); + } - var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; - var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; + if (buildLog) + buildLog.done(); - // hoverData: the set of candidate points we've found to highlight - var hoverData = [], + return segments; + } - // searchData: the data to search in. Mostly this is just a copy of - // gd.calcdata, filtered to the subplot and overlays we're on - // but if a point array is supplied it will be a mapping - // of indicated curves - searchData = [], + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } - // [x|y]valArray: the axis values of the hover event - // mapped onto each of the currently selected overlaid subplots - xvalArray, - yvalArray, + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; - // used in loops - itemnum, - curvenum, - cd, - trace, - subplotId, - subploti, - mode, - xval, - yval, - pointData, - closedataPreviousLength, + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it - // spikePoints: the set of candidate points we've found to draw spikes to - spikePoints = { - hLinePoint: null, - vLinePoint: null - }; + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} - // Figure out what we're hovering on: - // mouse location or user-supplied data +var _$Intersecter_28 = Intersecter; - if(Array.isArray(evt)) { - // user specified an array of points to highlight - hovermode = 'array'; - for(itemnum = 0; itemnum < evt.length; itemnum++) { - cd = gd.calcdata[evt[itemnum].curveNumber||0]; - if(cd[0].trace.hoverinfo !== 'skip') { - searchData.push(cd); - } - } - } - else { - for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { - cd = gd.calcdata[curvenum]; - trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_90.getSubplot(trace)) !== -1) { - searchData.push(cd); - } - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // [x|y]px: the pixels (from top left) of the mouse location - // on the currently selected plot area - // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation - var hasUserCalledHover = !evt.target, - xpx, ypx; +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// - if(hasUserCalledHover) { - if('xpx' in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - evt.pointerX = xpx + xaArray[0]._offset; +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; - if('ypx' in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - evt.pointerY = ypx + yaArray[0]._offset; - } - else { - // fire the beforehover event and quit if it returns false - // note that we're only calling this on real mouse events, so - // manual calls to fx.hover will always run. - if(_$Events_164.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } - var dbb = evt.target.getBoundingClientRect(); + if (buildLog) + buildLog.chainStart(seg); - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } - // in case hover was called from mouseout into hovertext, - // it's possible you're not actually over the plot anymore - if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { - return _$dragelement_73.unhoverRaw(gd, evt); - } - evt.pointerX = evt.offsetX; - evt.pointerY = evt.offsetY; - } + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } - if('xval' in evt) xvalArray = _$helpers_90.flat(subplots, evt.xval); - else xvalArray = _$helpers_90.p2c(xaArray, xpx); + if (next_match === second_match){ + // we matched a single chain - if('yval' in evt) yvalArray = _$helpers_90.flat(subplots, evt.yval); - else yvalArray = _$helpers_90.p2c(yaArray, ypx); + if (buildLog) + buildLog.chainMatch(first_match.index); - if(!_$fastIsnumeric_18(xvalArray[0]) || !_$fastIsnumeric_18(yvalArray[0])) { - _$lib_171.warn('Fx.hover failed', evt, gd); - return _$dragelement_73.unhoverRaw(gd, evt); - } - } + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop - // the pixel distance to beat as a matching point - // in 'x' or 'y' mode this resets for each trace - var distance = Infinity; + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head - // find the closest point in each trace - // this is minimum dx and/or dy, depending on mode - // and the pixel position for the label (labelXpx, labelYpx) - for(curvenum = 0; curvenum < searchData.length; curvenum++) { - cd = searchData[curvenum]; + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - // filter out invisible or broken data - if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } - trace = cd[0].trace; + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); - // Explicitly bail out for these two. I don't know how to otherwise prevent - // the rest of this function from running and failing - if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } - subplotId = _$helpers_90.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if (buildLog) + buildLog.chainClose(first_match.index); - // within one trace mode can sometimes be overridden - mode = hovermode; + // we have a closed chain! + regions.push(chain); + return; + } - // container for new point, also used to pass info into module.hoverPoints - pointData = { - // trace properties - cd: cd, - trace: trace, - xa: xaArray[subploti], - ya: yaArray[subploti], + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } - // max distances for hover and spikes - for points that want to show but do not - // want to override other points, set distance/spikeDistance equal to max*Distance - // and it will not get filtered out but it will be guaranteed to have a greater - // distance than any point that calculated a real distance. - maxHoverDistance: hoverdistance, - maxSpikeDistance: spikedistance, + // otherwise, we matched two chains, so we need to combine those chains together - // point properties - override all of these - index: false, // point index in trace - only used by plotly.js hoverdata consumers - distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } - // distance/pseudo-distance for spikes. This distance should always be calculated - // as if in "closest" mode, and should only be set if this point should - // generate a spike. - spikeDistance: Infinity, + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; - // in some cases the spikes have different positioning from the hover label - // they don't need x0/x1, just one position - xSpike: undefined, - ySpike: undefined, + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } - // where and how to display the hover label - color: _$color_51.defaultLine, // trace color - name: trace.name, - x0: undefined, - x1: undefined, - y0: undefined, - y1: undefined, - xLabelVal: undefined, - yLabelVal: undefined, - zLabelVal: undefined, - text: undefined - }; + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } - // add ref to subplot object (non-cartesian case) - if(fullLayout[subplotId]) { - pointData.subplot = fullLayout[subplotId]._subplot; - } + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } - closedataPreviousLength = hoverData.length; + var F = first_match.index; + var S = second_match.index; - // for a highlighting array, figure out what - // we're searching for with this element - if(mode === 'array') { - var selection = evt[curvenum]; - if('pointNumber' in selection) { - pointData.index = selection.pointNumber; - mode = 'closest'; - } - else { - mode = ''; - if('xval' in selection) { - xval = selection.xval; - mode = 'x'; - } - if('yval' in selection) { - yval = selection.yval; - mode = mode ? 'closest' : 'y'; - } - } - } - else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; - } + if (buildLog) + buildLog.chainConnect(F, S); - // Now if there is range to look in, find the points to hover. - if(hoverdistance !== 0) { - if(trace._module && trace._module.hoverPoints) { - var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); - if(newPoints) { - var newPoint; - for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { - newPoint = newPoints[newPointNum]; - if(_$fastIsnumeric_18(newPoint.x0) && _$fastIsnumeric_18(newPoint.y0)) { - hoverData.push(cleanPoint(newPoint, hovermode)); - } - } - } - } - else { - _$lib_171.log('Unrecognized trace type in hover:', trace); - } - } + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); - // in closest mode, remove any existing (farther) points - // and don't look any farther than this latest point (or points, some - // traces like box & violin make multiple hover labels at once) - if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; - } + return regions; +} - // Now if there is range to look in, find the points to draw the spikelines - // Do it only if there is no hoverData - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length === 0) { - pointData.distance = spikedistance; - pointData.index = false; - var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); - if(closestPoints) { - closestPoints = closestPoints.filter(function(point) { - // some hover points, like scatter fills, do not allow spikes, - // so will generate a hover point but without a valid spikeDistance - return point.spikeDistance <= spikedistance; - }); - } - if(closestPoints && closestPoints.length) { - var tmpPoint; - var closestVPoints = closestPoints.filter(function(point) { - return point.xa.showspikes; - }); - if(closestVPoints.length) { - var closestVPt = closestVPoints[0]; - if(_$fastIsnumeric_18(closestVPt.x0) && _$fastIsnumeric_18(closestVPt.y0)) { - tmpPoint = fillSpikePoint(closestVPt); - if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.vLinePoint = tmpPoint; - } - } - } +var _$SegmentChainer_30 = SegmentChainer; - var closestHPoints = closestPoints.filter(function(point) { - return point.ya.showspikes; - }); - if(closestHPoints.length) { - var closestHPt = closestHPoints[0]; - if(_$fastIsnumeric_18(closestHPt.x0) && _$fastIsnumeric_18(closestHPt.y0)) { - tmpPoint = fillSpikePoint(closestHPt); - if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } - } - } - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - function selectClosestPoint(pointsData, spikedistance) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for(var i = 0; i < pointsData.length; i++) { - thisSpikeDistance = pointsData[i].spikeDistance; - if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { - resultPoint = pointsData[i]; - minDistance = thisSpikeDistance; - } - } - return resultPoint; - } +// +// filter a list of segments based on boolean operations +// - function fillSpikePoint(point) { - if(!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; - } +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); - var spikelineOpts = { - fullLayout: fullLayout, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - event: evt - }; - var oldspikepoints = gd._spikepoints, - newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; + if (buildLog) + buildLog.selected(result); - // Now if it is not restricted by spikedistance option, set the points to draw the spikelines - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); + return result; +} - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); - } - } +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; - // if hoverData is empty check for the spikes to draw and quit if there are none - if(hoverData.length === 0) { - var result = _$dragelement_73.unhoverRaw(gd, evt); - if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } - return result; - } +var _$SegmentSelector_31 = SegmentSelector; - if(hasCartesian) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ - hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); +/* removed: var _$BuildLog_25 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_26 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_28 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_30 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_31 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_27 = require('./lib/geojson'); */; - // lastly, emit custom hover/unhover events - var oldhoverdata = gd._hoverdata, - newhoverdata = []; +var buildLog = false; +var epsilon = _$Epsilon_26(); - // pull out just the data that's useful to - // other people and send it to the event - for(itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - newhoverdata.push(_$helpers_90.makeEventData(pt, pt.trace, pt.cd)); - } +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_25(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v){ + return epsilon.epsilon(v); + }, - gd._hoverdata = newhoverdata; + // core API + segments: function(poly){ + var i = _$Intersecter_28(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_28(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_31.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_31.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_31.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_31.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_31.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_30(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, - // if there's more than one horz bar trace, - // rotate the labels so they don't overlap - var rotateLabels = hovermode === 'y' && searchData.length > 1; + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_27.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_27.fromPolygon(PolyBool, epsilon, poly); + }, - var bgColor = _$color_51.combine( - fullLayout.plot_bgcolor || _$color_51.background, - fullLayout.paper_bgcolor - ); + // 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); + } +}; - var labelOpts = { - hovermode: hovermode, - rotateLabels: rotateLabels, - bgColor: bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }; +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); +} - var hoverLabels = createHoverText(hoverData, labelOpts, gd); +if (typeof window === 'object') + window.PolyBool = PolyBool; - hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); +var _$PolyBool_24 = PolyBool; - alignHoverText(hoverLabels, rotateLabels); +var _$polygon_184 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true - // we should improve the "fx" API so other plots can use it without these hack. - if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_261.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_182(_$d3_15.select(evt.target), hasClickToShow ? 'pointer' : ''); - } - // don't emit events if called manually - if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; +'use strict'; - if(oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } +var dot = _$matrix_178.dot; +var __BADNUM_184 = _$numerical_154.BADNUM; - gd.emit('plotly_hover', { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); -} +var polygon = _$polygon_184 = {}; -function createHoverText(hoverData, opts, gd) { - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - // opts.fontFamily/Size are used for the common label - // and as defaults for each hover label, though the individual labels - // can override this. - var fontFamily = opts.fontFamily || _$constants_88.HOVERFONT; - var fontSize = opts.fontSize || _$constants_88.HOVERFONTSIZE; + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; - var t0 = c0[commonAttr]; - var t00 = (String(t0) || '').split(' ')[0]; - var outerContainerBB = outerContainer.node().getBoundingClientRect(); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); + } - // show the common label, if any, on the axis - // never show a common label in array mode, - // even if sometimes there could be one - var showCommonLabel = ( - (t0 !== undefined) && - (c0.distance <= opts.hoverdistance) && - (hovermode === 'x' || hovermode === 'y') - ); + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed - // all hover traces hoverinfo must contain the hovermode - // to have common labels - if(showCommonLabel) { - var i, traceHoverinfo; - var allHaveZ = true; - for(i = 0; i < hoverData.length; i++) { - if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + var isRect = false, + rectFirstEdgeTest; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); - if(parts.indexOf('all') === -1 && - parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; } } - - // xyz labels put all info in their main label, so have no need of a common label - if(allHaveZ) showCommonLabel = false; } - var commonLabel = container.selectAll('g.axistext') - .data(showCommonLabel ? [0] : []); - commonLabel.enter().append('g') - .classed('axistext', true); - commonLabel.exit().remove(); + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - commonLabel.each(function() { - var label = _$d3_15.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); + if(x === __BADNUM_184 || x < xmin || x > xmax || y === __BADNUM_184 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; - lpath.enter().append('path') - .style({'stroke-width': '1px'}); + return true; + } - lpath.style({ - fill: commonLabelOpts.bgcolor || _$color_51.defaultLine, - stroke: commonLabelOpts.bordercolor || _$color_51.background, - }); + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); + if(x === __BADNUM_184 || x < xmin || x > xmax || y === __BADNUM_184 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } - ltext.text(t0) - .call(_$drawing_76.font, - commonLabelOpts.font.family || fontFamily, - commonLabelOpts.font.size || fontSize, - commonLabelOpts.font.color || _$color_51.background - ) - .call(_$svg_text_utils_192.positionText, 0, 0) - .call(_$svg_text_utils_192.convertToTspans, gd); + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; - label.attr('transform', ''); + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); - var tbb = ltext.node().getBoundingClientRect(); - if(hovermode === 'x') { - ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_192.positionText, 0, (xa.side === 'top' ? - (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : - (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - var topsign = xa.side === 'top' ? '-' : ''; - lpath.attr('d', 'M0,0' + - 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + - 'H' + (HOVERTEXTPAD + tbb.width / 2) + - 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + - 'H-' + (HOVERTEXTPAD + tbb.width / 2) + - 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } - label.attr('transform', 'translate(' + - (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + - (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + if(y <= ycross && x !== xmini) crossings++; + } } - else { - ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_192.positionText, - (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), - outerTop - tbb.top - tbb.height / 2); - var leftsign = ya.side === 'right' ? '' : '-'; - lpath.attr('d', 'M0,0' + - 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + - 'V' + (HOVERTEXTPAD + tbb.height / 2) + - 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + - 'V-' + (HOVERTEXTPAD + tbb.height / 2) + - 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; + } - label.attr('transform', 'translate(' + - (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + - (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; } - // remove the "close but not quite" points - // because of error bars, only take up to a space - hoverData = hoverData.filter(function(d) { - return (d.zLabelVal !== undefined) || - (d[commonAttr] || '').split(' ')[0] === t00; - }); - }); + } - // show all the individual labels + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; +}; - // first create the objects - var hoverLabels = container.selectAll('g.hovertext') - .data(hoverData, function(d) { - return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); - }); - hoverLabels.enter().append('g') - .classed('hovertext', true) - .each(function() { - var g = _$d3_15.select(this); - // trace name label (rect and text.name) - g.append('rect') - .call(_$color_51.fill, _$color_51.addOpacity(bgColor, 0.8)); - g.append('text').classed('name', true); - // trace data label (path and text.nums) - g.append('path') - .style('stroke-width', '1px'); - g.append('text').classed('nums', true) - .call(_$drawing_76.font, fontFamily, fontSize); - }); - hoverLabels.exit().remove(); +/** + * Test multiple polygons + */ +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; - // then put the text in, position the pointer to the data, - // and figure out sizes - hoverLabels.each(function(d) { - var g = _$d3_15.select(this).attr('transform', ''), - name = '', - text = ''; + for(var i = 0; i < list.length; i++) { + 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); + } - // combine possible non-opaque trace color with bgColor - var baseColor = _$color_51.opacity(d.color) ? d.color : _$color_51.defaultLine; - var traceColor = _$color_51.combine(baseColor, bgColor); + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } - // find a contrasting color for border and text - var contrastColor = d.borderColor || _$color_51.contrast(traceColor); + return yes; + } - // to get custom 'name' labels pass cleanPoint - if(d.nameOverride !== undefined) d.name = d.nameOverride; + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; +}; - if(d.name) { - // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_192.plainText(d.name || ''); +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; - var nameLength = Math.round(d.nameLength); + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); - if(nameLength > -1 && name.length > nameLength) { - if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; - else name = name.substr(0, nameLength); - } - } + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; + } + return false; +}; - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; +/** + * Make a filtering polygon, to minimize the number of segments + * + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon + * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs + */ +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; - if(d.zLabel !== undefined) { - if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; - if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; - text += (text ? 'z: ' : '') + d.zLabel; - } - else if(showCommonLabel && d[hovermode + 'Label'] === t0) { - text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; - } - else if(d.xLabel === undefined) { - if(d.yLabel !== undefined) text = d.yLabel; - } - else if(d.yLabel === undefined) text = d.xLabel; - else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); - if(d.text && !Array.isArray(d.text)) { - text += (text ? '
' : '') + d.text; + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } } + } - // if 'text' is empty at this point, - // put 'name' in main label and don't show secondary label - if(text === '') { - // if 'name' is also empty, remove entire label - if(name === '') g.remove(); - text = name; - } + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } - // main label - var tx = g.select('text.nums') - .call(_$drawing_76.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - d.fontColor || contrastColor) - .text(text) - .attr('data-notex', 1) - .call(_$svg_text_utils_192.positionText, 0, 0) - .call(_$svg_text_utils_192.convertToTspans, gd); + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; +}; - var tx2 = g.select('text.name'), - tx2width = 0; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // secondary label for non-empty 'name' - if(name && name !== text) { - tx2.call(_$drawing_76.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - traceColor) - .text(name) - .attr('data-notex', 1) - .call(_$svg_text_utils_192.positionText, 0, 0) - .call(_$svg_text_utils_192.convertToTspans, gd); - tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; - } - else { - tx2.remove(); - g.select('rect').remove(); - } - g.select('path') - .style({ - fill: traceColor, - stroke: contrastColor - }); - var tbb = tx.node().getBoundingClientRect(), - htx = d.xa._offset + (d.x0 + d.x1) / 2, - hty = d.ya._offset + (d.y0 + d.y1) / 2, - dx = Math.abs(d.x1 - d.x0), - dy = Math.abs(d.y1 - d.y0), - txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, - anchorStartOK, - anchorEndOK; +'use strict'; - d.ty0 = outerTop - tbb.top; - d.bx = tbb.width + 2 * HOVERTEXTPAD; - d.by = tbb.height + 2 * HOVERTEXTPAD; - d.anchor = 'start'; - d.txwidth = tbb.width; - d.tx2width = tx2width; - d.offset = 0; +/* removed: var _$PolyBool_24 = require('polybooljs'); */; - if(rotateLabels) { - d.pos = htx; - anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; - anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - hty += dy / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } - else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - htx += dx / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$fx_93 = require('../../components/fx'); */; - tx.attr('text-anchor', d.anchor); - if(tx2width) tx2.attr('text-anchor', d.anchor); - g.attr('transform', 'translate(' + htx + ',' + hty + ')' + - (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); - }); +/* removed: var _$polygon_184 = require('../../lib/polygon'); */; +/* removed: var _$throttle_194 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_90.makeEventData; +var getFromId = _$axis_ids_217.getFromId; +var __sortModules_231 = _$sort_modules_253.sortModules; - return hoverLabels; -} +/* removed: var _$constants_219 = require('./constants'); */; +var MINSELECT = _$constants_219.MINSELECT; -// Make groups of touching points, and within each group -// move each point so that no labels overlap, but the average -// label position is the same as it was before moving. Indicentally, -// this is equivalent to saying all the labels are on equal linear -// springs about their initial position. Initially, each point is -// its own group, but as we find overlaps we will clump the points. -// -// Also, there are hard constraints at the edges of the graphs, -// that push all groups to the middle so they are visible. I don't -// know what happens if the group spans all the way from one edge to -// the other, though it hardly matters - there's just too much -// information then. -function hoverAvoidOverlaps(hoverData, ax, fullLayout) { - var nummoves = 0, +var filteredPolygon = _$polygon_184.filter; +var polygonTester = _$polygon_184.tester; +var multipolygonTester = _$polygon_184.multitester; - // make groups of touching points - pointgroups = hoverData - .map(function(d, i) { - var axis = d[ax]; - return [{ - i: i, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, - pmin: 0, - pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) - }]; - }) - .sort(function(a, b) { return a[0].posref - b[0].posref; }), - donepositioning, - topOverlap, - bottomOverlap, - i, j, - pti, - sumdp; +function getAxId(ax) { return ax._id; } - function constrainGroup(grp) { - var minPt = grp[0], - maxPt = grp[grp.length - 1]; +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; - // overlap with the top - positive vals are overlaps - topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); - // overlap with the bottom - positive vals are overlaps - bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + } - // check for min overlap first, so that we always - // see the largest labels - // allow for .01px overlap, so we don't get an - // infinite loop from rounding errors - if(topOverlap > 0.01) { - for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; - donepositioning = false; - } - if(bottomOverlap < 0.01) return; - if(topOverlap < -0.01) { - // make sure we're not pushing back and forth - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - donepositioning = false; - } - if(!donepositioning) return; + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } - // no room to fix positioning, delete off-screen points + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_219.BENDPX); + } - // first see how many points we need to delete - var deleteCount = 0; - for(i = 0; i < grp.length; i++) { - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; - } + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); - // start by deleting points whose data is off screen - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; + 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'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; - } - } - for(i = 0; i < grp.length; i++) { - if(deleteCount <= 0) break; - pti = grp[i]; + var corners = zoomLayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_51.background, + stroke: _$color_51.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; - // shift the whole group minus into this new space - bottomOverlap = pti.size * 2; - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - } - } - // then delete points that go off the bottom - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; - } - } - } + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_219.SELECTID; + var selection = []; - // loop through groups, combining them if they overlap, - // until nothing moves - while(!donepositioning && nummoves <= hoverData.length) { - // to avoid infinite loops, don't move more times - // than there are traces - nummoves++; + for(i = 0; i < gd.calcdata.length; i++) { + cd = gd.calcdata[i]; + trace = cd[0].trace; - // assume nothing will move in this iteration, - // reverse this if it does - donepositioning = true; - i = 0; - while(i < pointgroups.length - 1) { - // the higher (g0) and lower (g1) point group - var g0 = pointgroups[i], - g1 = pointgroups[i + 1], + if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; - // the lowest point in the higher group (p0) - // the highest point in the lower group (p1) - p0 = g0[g0.length - 1], - p1 = g1[0]; - topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; - - // Only group points that lie on the same axes - if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { - // push the new point(s) added to this group out of the way - for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; - - // add them to the group - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); - - // adjust for minimum average movement - sumdp = 0; - for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; + if(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); } - else i++; - } - - // check if we're going off the plot on either side and fix - pointgroups.forEach(constrainGroup); - } + } 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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; - // now put these offsets into hoverData - for(i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for(j = grp.length - 1; j >= 0; j--) { - var pt = grp[j], - hoverPt = hoverData[pt.i]; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); } } -} -function alignHoverText(hoverLabels, rotateLabels) { - // finally set the text positioning relative to the data and draw the - // box around it - hoverLabels.each(function(d) { - var g = _$d3_15.select(this); - if(d.del) { - g.remove(); - return; - } - var horzSign = d.anchor === 'end' ? -1 : 1, - tx = g.select('text.nums'), - alignShift = {start: 1, end: -1, middle: 0}[d.anchor], - txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), - tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), - offsetX = 0, - offsetY = d.offset; - if(d.anchor === 'middle') { - txx -= d.tx2width / 2; - tx2x += d.txwidth / 2 + HOVERTEXTPAD; - } - if(rotateLabels) { - offsetY *= -YSHIFTY; - offsetX = d.offset * YSHIFTX; - } + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(v[index]); }; + } - g.select('path').attr('d', d.anchor === 'middle' ? - // middle aligned: rect centered on data - ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + - 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : - // left or right aligned: side rect with arrow to data - ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + - 'v' + (d.by / 2 - HOVERARROWSIZE) + - 'h' + (horzSign * d.bx) + - 'v-' + d.by + - 'H' + (horzSign * HOVERARROWSIZE + offsetX) + - 'V' + (offsetY - HOVERARROWSIZE) + - 'Z')); + function ascending(a, b) { return a - b; } - tx.call(_$svg_text_utils_192.positionText, - txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + // allow subplots to override fillRangeItems routine + var fillRangeItems; - if(d.tx2width) { - g.select('text.name') - .call(_$svg_text_utils_192.positionText, - tx2x + alignShift * HOVERTEXTPAD + offsetX, - offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); - g.select('rect') - .call(_$drawing_76.setRect, - tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, - offsetY - d.by / 2 - 1, - d.tx2width, d.by + 2); - } - }); -} + if(plotinfo.fillRangeItems) { + fillRangeItems = plotinfo.fillRangeItems; + } else { + if(mode === 'select') { + fillRangeItems = function(eventData, poly) { + var ranges = eventData.range = {}; -function cleanPoint(d, hovermode) { - var index = d.index; - var trace = d.trace || {}; - var cd0 = d.cd[0]; - var cd = d.cd[index] || {}; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + var axLetter = ax._id.charAt(0); - var getVal = Array.isArray(index) ? - function(calcKey, traceKey) { - return _$lib_171.castOption(cd0, index, calcKey) || - _$lib_171.extractOption({}, trace, '', traceKey); - } : - function(calcKey, traceKey) { - return _$lib_171.extractOption(cd, trace, calcKey, traceKey); - }; + ranges[ax._id] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(poly[axLetter + 'max']) + ].sort(ascending); + } + }; + } else { + fillRangeItems = function(eventData, poly, filterPoly) { + var dataPts = eventData.lassoPoints = {}; - function fill(key, calcKey, traceKey) { - var val = getVal(calcKey, traceKey); - if(val) d[key] = val; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); + } + }; + } } - fill('hoverinfo', 'hi', 'hoverinfo'); - fill('color', 'hbg', 'hoverlabel.bgcolor'); - fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); - fill('fontFamily', 'htf', 'hoverlabel.font.family'); - fill('fontSize', 'hts', 'hoverlabel.font.size'); - fill('fontColor', 'htc', 'hoverlabel.font.color'); - fill('nameLength', 'hnl', 'hoverlabel.namelength'); + dragOptions.moveFn = function(dx0, dy0) { + x1 = Math.max(0, Math.min(pw, dx0 + x0)); + y1 = Math.max(0, Math.min(ph, dy0 + y0)); - d.posref = hovermode === 'y' ? - (d.xa._offset + (d.x0 + d.x1) / 2) : - (d.ya._offset + (d.y0 + d.y1) / 2); + var dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - // then constrain all the positions to be on the plot - d.x0 = _$lib_171.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_171.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_171.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_171.constrain(d.y1, 0, d.ya._length); + if(mode === 'select') { + var direction = fullLayout.selectdirection; - // and convert the x and y label values into formatted text - if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_213.hoverLabelText(d.xa, d.xLabelVal); - d.xVal = d.xa.c2d(d.xLabelVal); - } - if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_213.hoverLabelText(d.ya, d.yLabelVal); - d.yVal = d.ya.c2d(d.yLabelVal); - } + 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; + } - // Traces like heatmaps generate the zLabel in their hoverPoints function - if(d.zLabelVal !== undefined && d.zLabel === undefined) { - d.zLabel = String(d.zLabelVal); - } + 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'); - // for box means and error bars, add the range to the label - if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_213.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; - if(d.xerrneg !== undefined) { - d.xLabel += ' +' + xeText + ' / -' + - _$axes_213.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + 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 d.xLabel += ' ± ' + xeText; - - // small distance penalty for error bars, so that if there are - // traces with errors and some without, the error bar label will - // hoist up to the point - if(hovermode === 'x') d.distance += 1; - } - if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_213.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; - if(d.yerrneg !== undefined) { - d.yLabel += ' +' + yeText + ' / -' + - _$axes_213.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + else if(mode === 'lasso') { + filterPoly.addPt([x1, y1]); + currentPolygon = filterPoly.filtered; } - else d.yLabel += ' ± ' + yeText; - - if(hovermode === 'y') d.distance += 1; - } - var infomode = d.hoverinfo || d.trace.hoverinfo; + // create outline & tester + if(dragOptions.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } - if(infomode !== 'all') { - infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); - if(infomode.indexOf('x') === -1) d.xLabel = undefined; - if(infomode.indexOf('y') === -1) d.yLabel = undefined; - if(infomode.indexOf('z') === -1) d.zLabel = undefined; - if(infomode.indexOf('text') === -1) d.text = undefined; - if(infomode.indexOf('name') === -1) d.name = undefined; - } + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); + } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); - return d; -} + _$throttle_194.throttle( + throttleID, + _$constants_219.SELECTDELAY, + function() { + selection = []; -function createSpikelines(closestPoints, opts) { - var container = opts.container; - var fullLayout = opts.fullLayout; - var evt = opts.event; - var xa, - ya; + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - var showY = !!closestPoints.hLinePoint; - var showX = !!closestPoints.vLinePoint; + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + traceSelections.push(traceSelection); - // Remove old spikeline items - container.selectAll('.spikeline').remove(); + thisSelection = fillSelectionItem(traceSelection, searchInfo); - if(!(showX || showY)) return; + if(selection.length) { + for(var j = 0; j < thisSelection.length; j++) { + selection.push(thisSelection[j]); + } + } + else selection = thisSelection; + } - var contrastColor = _$color_51.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + eventData = {points: selection}; + updateSelectedState(gd, searchTraces, eventData); + fillRangeItems(eventData, currentPolygon, filterPoly); + dragOptions.gd.emit('plotly_selecting', eventData); + } + ); + }; - // Horizontal line (to y-axis) - if(showY) { - var hLinePoint = closestPoints.hLinePoint, - hLinePointX, - hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; + dragOptions.clickFn = function(numClicks, evt) { + corners.remove(); - if(ySnap === 'cursor') { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; - } - var dfltHLineColor = _$tinycolor_33.readability(hLinePoint.color, contrastColor) < 1.5 ? - _$color_51.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode, - yThickness = ya.spikethickness, - yColor = ya.spikecolor || dfltHLineColor, - yBB = ya._boundingBox, - xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, - xBase, - xEndSpike; + _$throttle_194.done(throttleID).then(function() { + _$throttle_194.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); + } - if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { - if(yMode.indexOf('toaxis') !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; + updateSelectedState(gd, searchTraces); + gd.emit('plotly_deselect', null); } - if(yMode.indexOf('across') !== -1) { - xBase = ya._counterSpan[0]; - xEndSpike = ya._counterSpan[1]; + else { + // 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. + gd.emit('plotly_selected', undefined); } - // Foreground horizontal line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness, - 'stroke': yColor, - 'stroke-dasharray': _$drawing_76.dashStyle(ya.spikedash, yThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + _$fx_93.click(gd, evt); + }); + }; - // Background horizontal Line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } - // Y axis marker - if(yMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), - 'cy': hLinePointY, - 'r': yThickness, - 'fill': yColor - }) - .classed('spikeline', true); - } - } + dragOptions.doneFn = function() { + corners.remove(); - if(showX) { - var vLinePoint = closestPoints.vLinePoint, - vLinePointX, - vLinePointY; + _$throttle_194.done(throttleID).then(function() { + _$throttle_194.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); - if(xSnap === 'cursor') { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} + +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; + + if(eventData) { + var pts = eventData.points || []; + + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.selectedpoints = []; } - var dfltVLineColor = _$tinycolor_33.readability(vLinePoint.color, contrastColor) < 1.5 ? - _$color_51.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode, - xThickness = xa.spikethickness, - xColor = xa.spikecolor || dfltVLineColor, - xBB = xa._boundingBox, - yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, - yBase, - yEndSpike; - if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { - if(xMode.indexOf('toaxis') !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if(xMode.indexOf('across') !== -1) { - yBase = xa._counterSpan[0]; - yEndSpike = xa._counterSpan[1]; + 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); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + 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; + } + } - // Foreground vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness, - 'stroke': xColor, - 'stroke-dasharray': _$drawing_76.dashStyle(xa.spikedash, xThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + // group searchInfo traces by trace modules + var lookup = {}; - // Background vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - // X axis marker - if(xMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': vLinePointX, - 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), - 'r': xThickness, - 'fill': xColor - }) - .classed('spikeline', true); + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; } } -} -function hoverChanged(gd, evt, oldhoverdata) { - // don't emit any events if nothing changed - if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + var keys = Object.keys(lookup).sort(__sortModules_231); - for(var i = oldhoverdata.length - 1; i >= 0; i--) { - var oldPt = oldhoverdata[i], - newPt = gd._hoverdata[i]; - if(oldPt.curveNumber !== newPt.curveNumber || - String(oldPt.pointNumber) !== String(newPt.pointNumber)) { - return true; + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_262.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } } } - return false; } -function spikesChanged(gd, oldspikepoints) { - // don't relayout the plot because of new spikelines if spikelines points didn't change - if(!oldspikepoints) return true; - if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || - oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint - ) return true; - return false; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function mergePolygons(list, poly, subtract) { + var res; -'use strict'; + if(subtract) { + res = _$PolyBool_24.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); -/* removed: var _$registry_261 = require('../../registry'); */; -var hover = _$hover_91.hover; + return res.regions; + } -var _$click_87 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_261.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); + res = _$PolyBool_24.union({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); - // 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); - } + return res.regions; +} - function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } +function fillSelectionItem(selection, searchInfo) { + if(Array.isArray(selection)) { + var cd = searchInfo.cd; + var trace = searchInfo.cd[0].trace; - if(gd._hoverdata && evt && evt.target) { - if(annotationsDone && annotationsDone.then) { - annotationsDone.then(emitClick); + for(var i = 0; i < selection.length; i++) { + selection[i] = makeEventData(selection[i], trace, cd); } - else emitClick(); - - // why do we get a double event without this??? - if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; - -/* removed: var _$lib_171 = require('../../lib'); */; + return selection; +} -var _$handleHoverLabelDefaults_92 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { - opts = opts || {}; +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); +} - coerce('hoverlabel.bgcolor', opts.bgcolor); - coerce('hoverlabel.bordercolor', opts.bordercolor); - coerce('hoverlabel.namelength', opts.namelength); - _$lib_171.coerceFont(coerce, 'hoverlabel.font', opts.font); +var _$select_231 = { + prepSelect: prepSelect, + clearSelect: clearSelect }; /** @@ -33626,1093 +34205,1414 @@ var _$handleHoverLabelDefaults_92 = function handleHoverLabelDefaults(contIn, co * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$attributes_85 = require('./attributes'); */; -/* removed: var _$handleHoverLabelDefaults_92 = require('./hoverlabel_defaults'); */; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_21 = require('has-passive-events'); */; -var _$supplyDefaults_89 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_85, attr, dflt); - } +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_161 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$fx_93 = require('../../components/fx'); */; +/* removed: var _$setCursor_191 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_73 = require('../../components/dragelement'); */; +var FROM_TL = _$alignment_151.FROM_TL; - _$handleHoverLabelDefaults_92(traceIn, traceOut, coerce, layout.hoverlabel); -}; +/* removed: var _$plots_246 = require('../plots'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 doTicks = _$axes_214.doTicks; +var __getFromId_222 = _$axis_ids_217.getFromId; +var __prepSelect_222 = _$select_231.prepSelect; +var __clearSelect_222 = _$select_231.clearSelect; +/* removed: var _$scaleZoom_230 = require('./scale_zoom'); */; -'use strict'; +/* removed: var _$constants_219 = require('./constants'); */; +var MINDRAG = _$constants_219.MINDRAG; +var MINZOOM = _$constants_219.MINZOOM; -/* removed: var _$constants_88 = require('./constants'); */; -var __fontAttrs_94 = _$font_attributes_240({ - editType: 'none', - -}); -__fontAttrs_94.family.dflt = _$constants_88.HOVERFONT; -__fontAttrs_94.size.dflt = _$constants_88.HOVERFONTSIZE; +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; -var _$layout_attributes_94 = { - dragmode: { - valType: 'enumerated', - - values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], - dflt: 'zoom', - editType: 'modebar', - - }, - hovermode: { - valType: 'enumerated', - - values: ['x', 'y', 'closest', false], - editType: 'modebar', - - }, - hoverdistance: { - valType: 'integer', - min: -1, - dflt: 20, - - editType: 'none', - - }, - spikedistance: { - valType: 'integer', - min: -1, - dflt: 20, - - editType: 'none', - - }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'none', - - }, - bordercolor: { - valType: 'color', - - editType: 'none', - - }, - font: __fontAttrs_94, - namelength: { - valType: 'integer', - min: -1, - dflt: 15, - - editType: 'none', - - }, - editType: 'none' - } -}; +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; -'use strict'; + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$layout_attributes_94 = require('./layout_attributes'); */; + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; -var _$supplyLayoutDefaults_95 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_94, attr, dflt); - } + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } - coerce('dragmode'); + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; - var hovermodeDflt; - if(layoutOut._has('cartesian')) { - // flag for 'horizontal' plots: - // determines the state of the mode bar 'compare' hovermode button - layoutOut._isHoriz = isHoriz(fullData); - hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; } - else hovermodeDflt = 'closest'; - var hoverMode = coerce('hovermode', hovermodeDflt); - if(hoverMode) { - coerce('hoverdistance'); - coerce('spikedistance'); - } + recomputeAxisLists(); - // if only mapbox or geo subplots is present on graph, - // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, - // so that the correct modebar button is active - var hasMapbox = layoutOut._has('mapbox'); - var hasGeo = layoutOut._has('geo'); - var len = layoutOut._basePlotModules.length; + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - if(layoutOut.dragmode === 'zoom' && ( - ((hasMapbox || hasGeo) && len === 1) || - (hasMapbox && hasGeo && len === 2) - )) { - layoutOut.dragmode = 'pan'; + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; } -}; - -function isHoriz(fullData) { - var out = true; - - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(trace.orientation !== 'h') { - out = false; - break; - } - } + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; - return out; -} + recomputeAxisLists(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } -'use strict'; + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$handleHoverLabelDefaults_92 = require('./hoverlabel_defaults'); */; -/* removed: var _$layout_attributes_94 = require('./layout_attributes'); */; + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_222(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_222(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; -var _$supplyLayoutGlobalDefaults_96 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { - function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_94, attr, dflt); - } + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; - _$handleHoverLabelDefaults_92(layoutIn, layoutOut, coerce); -}; + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_222(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(numClicks === 2 && !singleEnd) doubleClick(); -'use strict'; + if(isMainDrag) { + _$fx_93.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$helpers_90 = require('./helpers'); */; -/* removed: var _$layout_attributes_94 = require('./layout_attributes'); */; + if(ax.fixedrange) return; -var _$fx_93 = { - moduleType: 'component', - name: 'fx', + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; - constants: _$constants_88, - schema: { - layout: _$layout_attributes_94 - }, + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_15.select(dragger) + .call(_$svg_text_utils_193.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_262.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; - attributes: _$attributes_85, - layoutAttributes: _$layout_attributes_94, + _$dragelement_73.init(dragOptions); - supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_96, - supplyDefaults: _$supplyDefaults_89, - supplyLayoutDefaults: _$supplyLayoutDefaults_95, + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; - calc: _$calc_86, + // collected changes to be made to the plot by relayout at the end + var updates = {}; - getDistanceFunction: _$helpers_90.getDistanceFunction, - getClosest: _$helpers_90.getClosest, - inbox: _$helpers_90.inbox, - quadrature: _$helpers_90.quadrature, - appendArrayPointValue: _$helpers_90.appendArrayPointValue, + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_33(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; - castHoverOption: castHoverOption, - castHoverinfo: castHoverinfo, + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - hover: _$hover_91.hover, - unhover: _$dragelement_73.unhover, + corners = makeCorners(zoomlayer, xs, ys); - loneHover: _$hover_91.loneHover, - loneUnhover: loneUnhover, + __clearSelect_222(zoomlayer); + } - click: _$click_87 -}; + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } -function loneUnhover(containerOrSelection) { - // duck type whether the arg is a d3 selection because ie9 doesn't - // handle instanceof like modern browsers do. - var selection = _$lib_171.isD3Selection(containerOrSelection) ? - containerOrSelection : - _$d3_15.select(containerOrSelection); + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - selection.selectAll('g.hovertext').remove(); - selection.selectAll('.spikeline').remove(); -} + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); -// helpers for traces that use Fx.loneHover + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); + } -function castHoverOption(trace, ptNumber, attr) { - return _$lib_171.castOption(trace, ptNumber, 'hoverlabel.' + attr); -} + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; -function castHoverinfo(trace, fullLayout, ptNumber) { - function _coerce(val) { - return _$lib_171.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; } - return _$lib_171.castOption(trace, ptNumber, 'hoverinfo', _coerce); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } -'use strict'; + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } -/* removed: var _$lib_171 = require('../../lib'); */; + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } -/** Fill hover 'pointData' container with 'correct' hover text value - * - * - If trace hoverinfo contains a 'text' flag and hovertext is not set, - * the text elements will be seen in the hover labels. - * - * - If trace hoverinfo contains a 'text' flag and hovertext is set, - * hovertext takes precedence over text - * i.e. the hoverinfo elements will be seen in the hover labels - * - * @param {object} calcPt - * @param {object} trace - * @param {object || array} contOut (mutated here) - */ -var _$fillHoverText_376 = function fillHoverText(calcPt, trace, contOut) { - var fill = Array.isArray(contOut) ? - function(v) { contOut.push(v); } : - function(v) { contOut.text = v; }; + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_219.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - var htx = _$lib_171.extractOption(calcPt, trace, 'htx', 'hovertext'); - if(isValid(htx)) return fill(htx); + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } - var tx = _$lib_171.extractOption(calcPt, trace, 'tx', 'text'); - if(isValid(tx)) return fill(tx); -}; + if(redrawTimer === null) { + __clearSelect_222(zoomlayer); + } -// accept all truthy values and 0 (which gets cast to '0' in the hover labels) -function isValid(v) { - return v || v === 0; -} + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 pc = gd.querySelector('.plotly'); + recomputeAxisLists(); -'use strict'; + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } -/* removed: var _$fx_93 = require('../../components/fx'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$fillHoverText_376 = require('../scatter/fill_hover_text'); */; + clearTimeout(redrawTimer); -var _$hoverPoints_274 = function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - var t = cd[0].t; - var isClosest = (hovermode === 'closest'); - var maxHoverDistance = pointData.maxHoverDistance; - var maxSpikeDistance = pointData.maxSpikeDistance; + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_172.log('Did not find wheel motion attributes: ', e); + return; + } - var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; - function thisBarMinPos(di) { return di[posLetter] - di.w / 2; } - function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; } + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; - var minPos = isClosest ? - thisBarMinPos : - function(di) { - /* - * In compare mode, accept a bar if you're on it *or* its group. - * Nearly always it's the group that matters, but in case the bar - * was explicitly set wider than its group we'd better accept the - * whole bar. - * - * use `bardelta` instead of `bargroupwidth` so we accept hover - * in the gap. That way hover doesn't flash on and off as you - * mouse over the plot in compare modes. - * In 'closest' mode though the flashing seems inevitable, - * without far more complex logic - */ - return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2); - }; + var axRange = _$lib_172.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } - var maxPos = isClosest ? - thisBarMaxPos : - function(di) { - return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2); - }; + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; - function _positionFn(_minPos, _maxPos) { - // add a little to the pseudo-distance for wider bars, so that like scatter, - // if you are over two overlapping bars, the narrower one wins. - return _$fx_93.inbox(_minPos - posVal, _maxPos - posVal, - maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); - } + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } - function positionFn(di) { - return _positionFn(minPos(di), maxPos(di)); - } + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; - function thisBarPositionFn(di) { - return _positionFn(thisBarMinPos(di), thisBarMaxPos(di)); - } + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } - function sizeFn(di) { - // add a gradient so hovering near the end of a - // bar makes it a little closer match - return _$fx_93.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, - maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); - } + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } - if(trace.orientation === 'h') { - posVal = yval; - sizeVal = xval; - posLetter = 'y'; - sizeLetter = 'x'; - dx = sizeFn; - dy = positionFn; + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); + + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; + + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + + dragTail(zoomMode); + }, REDRAWDELAY); + + e.preventDefault(); + return; } - else { - posVal = xval; - sizeVal = yval; - posLetter = 'x'; - sizeLetter = 'y'; - dy = sizeFn; - dx = positionFn; + + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); } - var pa = pointData[posLetter + 'a']; - var sa = pointData[sizeLetter + 'a']; + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_93.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_93.getClosest(cd, distfn, pointData); + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); - // skip the rest (for this trace) if we didn't find a close point - if(pointData.index === false) return; + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } - // if we get here and we're not in 'closest' mode, push min/max pos back - // onto the group - even though that means occasionally the mouse will be - // over the hover label. - if(!isClosest) { - minPos = function(di) { - return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2); - }; - maxPos = function(di) { - return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2); - }; - } + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - // the closest data point - var index = pointData.index; - var di = cd[index]; - var mc = di.mcc || trace.marker.color; - var mlc = di.mlcc || trace.marker.line.color; - var mlw = di.mlw || trace.marker.line.width; + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - if(_$color_51.opacity(mc)) pointData.color = mc; - else if(_$color_51.opacity(mlc) && mlw) pointData.color = mlc; + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - var size = (trace.base) ? di.b + di.s : di.s; - pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); - pointData[sizeLetter + 'LabelVal'] = size; + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; - var extent = t.extents[t.extents.round(di.p)]; - pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true); - pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true); - pointData[posLetter + 'LabelVal'] = di.p; + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_230(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_230(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } - // spikelines always want "closest" distance regardless of hovermode - pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance; - // they also want to point to the data value, regardless of where the label goes - // in case of bars shifted within groups - pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } - _$fillHoverText_376(di, trace, pointData); - _$registry_261.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; - return [pointData]; -}; + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } -'use strict'; + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_222(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; -var _$layout_attributes_276 = { - 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', - + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // 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 + + redrawObjs(gd._fullLayout.annotations || [], _$registry_262.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_262.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_262.getComponentMethod('images', 'draw'), true); } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function doubleClick() { + if(gd._transitioningWithDuration) return; + + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; + var ax, i, rangeInitial; -'use strict'; + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { + + doubleClickConfig = 'autosize'; + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_171 = require('../../lib'); */; + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); -/* removed: var _$layout_attributes_276 = require('./layout_attributes'); */; + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } + for(i = 0; i < axList.length; i++) { + ax = axList[i]; -var _$layout_defaults_277 = function(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_276, attr, dflt); + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } + + gd.emit('plotly_doubleclick', null); + _$registry_262.call('relayout', gd, attrs); } - var hasBars = false, - shouldBeGapless = false, - gappedAnyway = false, - usedSubplots = {}; + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(_$registry_261.traceIs(trace, 'bar')) hasBars = true; - else continue; + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_172.syncOrAsync([ + _$plots_246.previousPromises, + function() { _$registry_262.call('relayout', gd, updates); } + ], gd); + } - // if we have at least 2 grouped bar traces on the same subplot, - // we should default to a gap anyway, even if the data is histograms - if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') { - var subploti = trace.xaxis + trace.yaxis; - if(usedSubplots[subploti]) gappedAnyway = true; - usedSubplots[subploti] = true; + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; + + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); + + var i, sp, xa, ya; + + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_161(gd); } - if(trace.visible && trace.type === 'histogram') { - var pa = _$axes_213.getFromId({_fullLayout: layoutOut}, - trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); - if(pa.type !== 'category') shouldBeGapless = true; + if(hasSplom) { + _$registry_262.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; } - } - if(!hasBars) return; + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_172.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_172.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } - var mode = coerce('barmode'); - if(mode !== 'overlay') coerce('barnorm'); + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; - coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2); - coerce('bargroupgap'); -}; + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; -'use strict'; + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$registry_261 = require('../../registry'); */; + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_76.setTranslate, clipDx, clipDy) + .call(_$drawing_76.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_76.setTranslate, plotDx, plotDy) + .call(_$drawing_76.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_76.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_76.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_76.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_76.hideOutsideRangePoints, sp, '.bartext'); + } + } + } + } -var __dummy_278$0 = 0, - attributeText = _$attributes_271.text, - attributeTextPosition = _$attributes_271.textposition, - attributeTextFont = _$attributes_271.textfont, - attributeInsideTextFont = _$attributes_271.insidetextfont, - attributeOutsideTextFont = _$attributes_271.outsidetextfont; + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; -// padding in pixels around text -var TEXTPAD = 3; + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } -var _$plot_278 = function plot(gd, plotinfo, cdbar) { - var xa = plotinfo.xaxis, - ya = plotinfo.yaxis, - fullLayout = gd._fullLayout; + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_230(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } - var bartraces = plotinfo.plot.select('.barlayer') - .selectAll('g.trace.bars') - .data(cdbar); + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle']; + } - bartraces.enter().append('g') - .attr('class', 'trace bars'); + return dragger; +} - bartraces.each(function(d) { - d[0].node3 = _$d3_15.select(this); +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_172.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); }); - bartraces.append('g') - .attr('class', 'points') - .each(function(d) { - var sel = _$d3_15.select(this); - var t = d[0].t; - var trace = d[0].trace; - var poffset = t.poffset; - var poffsetIsArray = Array.isArray(poffset); - - sel.selectAll('g.point') - .data(_$lib_171.identity) - .enter().append('g').classed('point', true) - .each(function(di, i) { - // now display the bar - // clipped xf/yf (2nd arg true): non-positive - // log values go off-screen by plotwidth - // so you see them continue if you drag the plot - var p0 = di.p + ((poffsetIsArray) ? poffset[i] : poffset), - p1 = p0 + di.w, - s0 = di.b, - s1 = s0 + di.s; + dragger3.call(_$setCursor_191, cursor); - var x0, x1, y0, y1; - if(trace.orientation === 'h') { - y0 = ya.c2p(p0, true); - y1 = ya.c2p(p1, true); - x0 = xa.c2p(s0, true); - x1 = xa.c2p(s1, true); + return dragger3.node(); +} - // for selections - di.ct = [x1, (y0 + y1) / 2]; - } - else { - x0 = xa.c2p(p0, true); - x1 = xa.c2p(p1, true); - y0 = ya.c2p(s0, true); - y1 = ya.c2p(s1, true); +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_15.select(dragger).call(_$drawing_76.setRect, x, y, w, h); + return dragger; +} - // for selections - di.ct = [(x0 + x1) / 2, y1]; - } +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} - if(!_$fastIsnumeric_18(x0) || !_$fastIsnumeric_18(x1) || - !_$fastIsnumeric_18(y0) || !_$fastIsnumeric_18(y1) || - x0 === x1 || y0 === y1) { - _$d3_15.select(this).remove(); - return; - } +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - var lw = (di.mlw + 1 || trace.marker.line.width + 1 || - (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, - offset = _$d3_15.round((lw / 2) % 1, 2); + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_15.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_15.format('.' + String(dig) + 'g')(initialVal); + } +} - function roundWithLine(v) { - // if there are explicit gaps, don't round, - // it can make the gaps look crappy - return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? - _$d3_15.round(Math.round(v) - offset, 2) : v; - } +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; - function expandToVisible(v, vc) { - // if it's not in danger of disappearing entirely, - // round more precisely - return Math.abs(v - vc) >= 2 ? roundWithLine(v) : - // but if it's very thin, expand it so it's - // necessarily visible, even if it might overlap - // its neighbor - (v > vc ? Math.ceil(v) : Math.floor(v)); - } + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; - if(!gd._context.staticPlot) { - // if bars are not fully opaque or they have a line - // around them, round to integer pixels, mainly for - // safari so we prevent overlaps from its expansive - // pixelation. if the bars ARE fully opaque and have - // no line, expand to a full pixel to make sure we - // can see them - var op = _$color_51.opacity(di.mc || trace.marker.color), - fixpx = (op < 1 || lw > 0.01) ? - roundWithLine : expandToVisible; - x0 = fixpx(x0, x1); - x1 = fixpx(x1, x0); - y0 = fixpx(y0, y1); - y1 = fixpx(y1, y0); - } + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } - // append bar path and text - var bar = _$d3_15.select(this); + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - bar.append('path') - .style('vector-effect', 'non-scaling-stroke') - .attr('d', - 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') - .call(_$drawing_76.setClipUrl, plotinfo.layerClipId); + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} - appendBarText(gd, bar, d, i, x0, x1, y0, y1); +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} - if(plotinfo.layerClipId) { - _$drawing_76.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); - } - }); - }); +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} - // error bars are on the top - _$registry_261.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} - // lastly, clip points groups of `cliponaxis !== false` traces - // on `plotinfo._hasClipOnAxisFalse === true` subplots - bartraces.each(function(d) { - var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_76.setClipUrl(_$d3_15.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); - }); -}; +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} -function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { - var textPosition; +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_51.background, + stroke: _$color_51.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} - function appendTextNode(bar, text, textFont) { - var textSelection = bar.append('text') - .text(text) - .attr({ - 'class': 'bartext bartext-' + textPosition, - transform: '', - 'text-anchor': 'middle', - // prohibit tex interpretation until we can handle - // tex and regular text together - 'data-notex': 1 - }) - .call(_$drawing_76.font, textFont) - .call(_$svg_text_utils_192.convertToTspans, gd); +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} - return textSelection; +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); } +} - // get trace attributes - var trace = calcTrace[0].trace, - orientation = trace.orientation; - - var text = getText(trace, i); - if(!text) return; - - textPosition = getTextPosition(trace, i); - if(textPosition === 'none') return; - - var textFont = getTextFont(trace, i, gd._fullLayout.font), - insideTextFont = getInsideTextFont(trace, i, textFont), - outsideTextFont = getOutsideTextFont(trace, i, textFont); +function removeZoombox(gd) { + _$d3_15.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} - // compute text position - var barmode = gd._fullLayout.barmode, - inStackMode = (barmode === 'stack'), - inRelativeMode = (barmode === 'relative'), - inStackOrRelativeMode = inStackMode || inRelativeMode, +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_172.notifier(_$lib_172._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} - calcBar = calcTrace[i], - isOutmostBar = !inStackOrRelativeMode || calcBar._outmost, +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} - barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD, // padding excluded - barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD, // padding excluded +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} - textSelection, - textBB, - textWidth, - textHeight; +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} - if(textPosition === 'outside') { - if(!isOutmostBar) textPosition = 'inside'; - } +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - if(textPosition === 'auto') { - if(isOutmostBar) { - // draw text using insideTextFont and check if it fits inside bar - textPosition = 'inside'; - textSelection = appendTextNode(bar, text, insideTextFont); +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; - textBB = _$drawing_76.bBox(textSelection.node()), - textWidth = textBB.width, - textHeight = textBB.height; + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } - var textHasSize = (textWidth > 0 && textHeight > 0), - fitsInside = - (textWidth <= barWidth && textHeight <= barHeight), - fitsInsideIfRotated = - (textWidth <= barHeight && textHeight <= barWidth), - fitsInsideIfShrunk = (orientation === 'h') ? - (barWidth >= textWidth * (barHeight / textHeight)) : - (barHeight >= textHeight * (barWidth / textWidth)); - if(textHasSize && - (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) { - textPosition = 'inside'; - } - else { - textPosition = 'outside'; - textSelection.remove(); - textSelection = null; + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } } } - else textPosition = 'inside'; - } - - if(!textSelection) { - textSelection = appendTextNode(bar, text, - (textPosition === 'outside') ? - outsideTextFont : insideTextFont); - textBB = _$drawing_76.bBox(textSelection.node()), - textWidth = textBB.width, - textHeight = textBB.height; - - if(textWidth <= 0 || textHeight <= 0) { - textSelection.remove(); - return; + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } } } - // compute text transform - var transform, constrained; - if(textPosition === 'outside') { - constrained = trace.constraintext === 'both' || trace.constraintext === 'outside'; - transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, - orientation, constrained); - } - else { - constrained = trace.constraintext === 'both' || trace.constraintext === 'inside'; - transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, - orientation, constrained); + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_172.extendFlat(xLinks, yLinks); + yLinks = {}; } - textSelection.attr('transform', transform); -} - -function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { - // compute text and target positions - var textWidth = textBB.width, - textHeight = textBB.height, - textX = (textBB.left + textBB.right) / 2, - textY = (textBB.top + textBB.bottom) / 2, - barWidth = Math.abs(x1 - x0), - barHeight = Math.abs(y1 - y0), - targetWidth, - targetHeight, - targetX, - targetY; - - // apply text padding - var textpad; - if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) { - textpad = TEXTPAD; - barWidth -= 2 * textpad; - barHeight -= 2 * textpad; + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_222(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; } - else textpad = 0; - - // compute rotation and scale - var rotate, - scale; - if(textWidth <= barWidth && textHeight <= barHeight) { - // no scale or rotation is required - rotate = false; - scale = 1; - } - else if(textWidth <= barHeight && textHeight <= barWidth) { - // only rotation is required - rotate = true; - scale = 1; - } - else if((textWidth < textHeight) === (barWidth < barHeight)) { - // only scale is required - rotate = false; - scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1; - } - else { - // both scale and rotation are required - rotate = true; - scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1; + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_222(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; } - if(rotate) rotate = 90; // rotate clockwise + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} - // compute text and target positions - if(rotate) { - targetWidth = scale * textHeight; - targetHeight = scale * textWidth; +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_21) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; } else { - targetWidth = scale * textWidth; - targetHeight = scale * textHeight; - } + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - if(orientation === 'h') { - if(x1 < x0) { - // bar end is on the left hand side - targetX = x1 + textpad + targetWidth / 2; - targetY = (y0 + y1) / 2; - } - else { - targetX = x1 - textpad - targetWidth / 2; - targetY = (y0 + y1) / 2; - } - } - else { - if(y1 > y0) { - // bar end is on the bottom - targetX = (x0 + x1) / 2; - targetY = y1 - textpad - targetHeight / 2; - } - else { - targetX = (x0 + x1) / 2; - targetY = y1 + textpad + targetHeight / 2; + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); } +} - return getTransform(textX, textY, targetX, targetY, scale, rotate); +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; } -function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { - var barWidth = (orientation === 'h') ? - Math.abs(y1 - y0) : - Math.abs(x1 - x0), - textpad; +var _$dragbox_222 = { + makeDragBox: makeDragBox, - // Keep the padding so the text doesn't sit right against - // the bars, but don't factor it into barWidth - if(barWidth > 2 * TEXTPAD) { - textpad = TEXTPAD; - } + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, - // compute rotation and scale - var scale = 1; - if(constrained) { - scale = (orientation === 'h') ? - Math.min(1, barWidth / textBB.height) : - Math.min(1, barWidth / textBB.width); - } + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, - // compute text and target positions - var textX = (textBB.left + textBB.right) / 2, - textY = (textBB.top + textBB.bottom) / 2, - targetWidth, - targetHeight, - targetX, - targetY; + attachWheelEventHandler: attachWheelEventHandler +}; - targetWidth = scale * textBB.width; - targetHeight = scale * textBB.height; +var _$graph_interact_223 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(orientation === 'h') { - if(x1 < x0) { - // bar end is on the left hand side - targetX = x1 - textpad - targetWidth / 2; - targetY = (y0 + y1) / 2; - } - else { - targetX = x1 + textpad + targetWidth / 2; - targetY = (y0 + y1) / 2; - } - } - else { - if(y1 > y0) { - // bar end is on the bottom - targetX = (x0 + x1) / 2; - targetY = y1 + textpad + targetHeight / 2; - } - else { - targetX = (x0 + x1) / 2; - targetY = y1 - textpad - targetHeight / 2; - } - } - return getTransform(textX, textY, targetX, targetY, scale, false); -} +'use strict'; -function getTransform(textX, textY, targetX, targetY, scale, rotate) { - var transformScale, - transformRotate, - transformTranslate; +/* removed: var _$d3_15 = require('d3'); */; - if(scale < 1) transformScale = 'scale(' + scale + ') '; - else { - scale = 1; - transformScale = ''; +/* removed: var _$fx_93 = require('../../components/fx'); */; +/* removed: var _$dragelement_73 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_191 = require('../../lib/setcursor'); */; + +var __makeDragBox_223 = _$dragbox_222.makeDragBox; +var DRAGGERSIZE = _$constants_219.DRAGGERSIZE; + +_$graph_interact_223.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; + + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_15.select(gd).selectAll('.drag').remove(); + return; } - transformRotate = (rotate) ? - 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : ''; + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - // Note that scaling also affects the center of the text box - var translateX = (targetX - scale * textX), - translateY = (targetY - scale * textY); - transformTranslate = 'translate(' + translateX + ' ' + translateY + ')'; + 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'), + 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; + }); - return transformTranslate + transformScale + transformRotate; -} + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -function getText(trace, index) { - var value = getValue(trace.text, index); - return coerceString(attributeText, value); -} + // 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_223(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); -function getTextPosition(trace, index) { - var value = getValue(trace.textposition, index); - return coerceEnumerated(attributeTextPosition, value); -} + 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) { + _$fx_93.hover(gd, evt, subplot); + } + }; -function getTextFont(trace, index, defaultValue) { - return getFontValue( - attributeTextFont, trace.textfont, index, defaultValue); -} + _$fx_93.hover(gd, evt, subplot); -function getInsideTextFont(trace, index, defaultValue) { - return getFontValue( - attributeInsideTextFont, trace.insidetextfont, index, defaultValue); -} + // 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; + }; -function getOutsideTextFont(trace, index, defaultValue) { - return getFontValue( - attributeOutsideTextFont, trace.outsidetextfont, index, defaultValue); -} + /* + * 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; -function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { - attributeValue = attributeValue || {}; + // 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; - var familyValue = getValue(attributeValue.family, index), - sizeValue = getValue(attributeValue.size, index), - colorValue = getValue(attributeValue.color, index); + _$dragelement_73.unhover(gd, evt); + }; - return { - family: coerceString( - attributeDefinition.family, familyValue, defaultValue.family), - size: coerceNumber( - attributeDefinition.size, sizeValue, defaultValue.size), - color: coerceColor( - attributeDefinition.color, colorValue, defaultValue.color) + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_223(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_223(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_223(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_223(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_223(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_223(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_223(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_223(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_223(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_223(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_93.hover(gd, evt, fullLayout._hoversubplot); }; -} -function getValue(arrayOrScalar, index) { - var value; - if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar; - else if(index < arrayOrScalar.length) value = arrayOrScalar[index]; - return value; -} + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_93.click(gd, evt); + }; -function coerceString(attributeDefinition, value, defaultValue) { - if(typeof value === 'string') { - if(value || !attributeDefinition.noBlank) return value; - } - else if(typeof value === 'number') { - if(!attributeDefinition.strict) return String(value); - } + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} + _$graph_interact_223.updateFx(fullLayout); +}; -function coerceEnumerated(attributeDefinition, value, defaultValue) { - if(attributeDefinition.coerceNumber) value = +value; +// 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. +_$graph_interact_223.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_191(fullLayout._draggers, cursor); +}; - if(attributeDefinition.values.indexOf(value) !== -1) return value; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} +'use strict'; -function coerceNumber(attributeDefinition, value, defaultValue) { - if(_$fastIsnumeric_18(value)) { - value = +value; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; - var min = attributeDefinition.min, - max = attributeDefinition.max, - isOutOfBounds = (min !== undefined && value < min) || - (max !== undefined && value > max); + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } - if(!isOutOfBounds) return value; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } } - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; + return Object.keys(lookup); } -function coerceColor(attributeDefinition, value, defaultValue) { - if(_$tinycolor_33(value).isValid()) return value; +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_218 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; + + var order = coerce('categoryorder', orderDefault); + var array; + + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); + } + + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; + } + + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -34724,36 +35624,58 @@ function coerceColor(attributeDefinition, value, defaultValue) { 'use strict'; -var _$selectPoints_279 = function selectPoints(searchInfo, polygon) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var i; +var colorMix = _$tinycolor_33.mix; +var lightFraction = _$attributes_50.lightFraction; +/* removed: var _$lib_172 = require('../../lib'); */; - if(polygon === 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]; +/** + * @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 + */ +var _$handleLineGridDefaults_228 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; - if(polygon.contains(di.ct)) { - selection.push({ - pointNumber: i, - x: xa.c2d(di.x), - y: ya.c2d(di.y) - }); - di.selected = 1; - } else { - di.selected = 0; - } - } + var dfltColor = opts.dfltColor; + + function coerce2(attr, dflt) { + return _$lib_172.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } - return selection; + 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; + } + } }; /** @@ -34766,102 +35688,93 @@ var _$selectPoints_279 = function selectPoints(searchInfo, polygon) { 'use strict'; -var _$Sieve_281 = Sieve; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -var __BADNUM_281 = _$numerical_154.BADNUM; +/* removed: var _$layout_attributes_226 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_235 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_234 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_233 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_218 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_228 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_232 = require('./set_convert'); */; /** - * Helper class to sieve data from traces into bins + * options: object containing: * - * @class - * @param {Array} traces - * Array of calculated traces - * @param {boolean} [separateNegativeValues] - * If true, then split data at the same position into a bar - * for positive values and another for negative values - * @param {boolean} [dontMergeOverlappingData] - * If true, then don't merge overlapping bars into a single bar + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors */ -function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { - this.traces = traces; - this.separateNegativeValues = separateNegativeValues; - this.dontMergeOverlappingData = dontMergeOverlappingData; +var _$handleAxisDefaults_216 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; - // for single-bin histograms - see histogram/calc - var width1 = Infinity; + var visible = coerce('visible', !options.cheateronly); - var positions = []; - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; - if(bar.p !== __BADNUM_281) positions.push(bar.p); - } - if(trace[0] && trace[0].width1) { - width1 = Math.min(trace[0].width1, width1); - } + var axType = containerOut.type; + + if(axType === 'date') { + var handleCalendarDefaults = _$registry_262.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } - this.positions = positions; - var dv = _$lib_171.distinctVals(positions); - this.distinctPositions = dv.vals; - if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; - else this.minDiff = Math.min(dv.minDiff, width1); + _$setConvert_232(containerOut, layoutOut); - this.binWidth = this.minDiff; + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - this.bins = {}; -} + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; -/** - * Sieve datum - * - * @method - * @param {number} position - * @param {number} value - * @returns {number} Previous bin value - */ -Sieve.prototype.put = function put(position, value) { - var label = this.getLabel(position, value), - oldValue = this.bins[label] || 0; + if(autoRange) coerce('rangemode'); - this.bins[label] = oldValue + value; + coerce('range'); + containerOut.cleanRange(); - return oldValue; -}; + _$handleCategoryOrderDefaults_218(containerIn, containerOut, coerce, options); -/** - * Get current bin value for a given datum - * - * @method - * @param {number} position Position of datum - * @param {number} [value] Value of datum - * (required if this.separateNegativeValues is true) - * @returns {number} Current bin value - */ -Sieve.prototype.get = function put(position, value) { - var label = this.getLabel(position, value); - return this.bins[label] || 0; -}; + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); -/** - * Get bin label for a given datum - * - * @method - * @param {number} position Position of datum - * @param {number} [value] Value of datum - * (required if this.separateNegativeValues is true) - * @returns {string} Bin label - * (prefixed with a 'v' if value is negative and this.separateNegativeValues is - * true; otherwise prefixed with '^') - */ -Sieve.prototype.getLabel = function getLabel(position, value) { - var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^', - label = (this.dontMergeOverlappingData) ? - position : - Math.round(position / this.binWidth); - return prefix + label; + if(!visible) return containerOut; + + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; + + coerce('title', dfltTitle); + _$lib_172.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); + + _$handleTickValueDefaults_235(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_233(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_234(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_228(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_226 + }); + + if(containerOut.showline || containerOut.ticks) coerce('mirror'); + + if(options.automargin) coerce('automargin'); + + return containerOut; }; /** @@ -34875,647 +35788,607 @@ Sieve.prototype.getLabel = function getLabel(position, value) { 'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_280 = _$lib_171.isArrayOrTypedArray; -var __BADNUM_280 = _$numerical_154.BADNUM; +/* removed: var _$lib_172 = require('../../lib'); */; +var id2name = _$axis_ids_217.id2name; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$Sieve_281 = require('./sieve.js'); */; -/* - * 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 - */ +var _$handleConstraintDefaults_220 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); -var _$setPositions_280 = function setPositions(gd, plotinfo) { - var xa = plotinfo.xaxis, - ya = plotinfo.yaxis; + if(containerOut.fixedrange) return; - var fullTraces = gd._fullData, - calcTraces = gd.calcdata, - calcTracesHorizontal = [], - calcTracesVertical = [], - i; - for(i = 0; i < fullTraces.length; i++) { - var fullTrace = fullTraces[i]; - if( - fullTrace.visible === true && - _$registry_261.traceIs(fullTrace, 'bar') && - fullTrace.xaxis === xa._id && - fullTrace.yaxis === ya._id - ) { - if(fullTrace.orientation === 'h') { - calcTracesHorizontal.push(calcTraces[i]); - } - else { - calcTracesVertical.push(calcTraces[i]); - } + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_172.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' } - } - - setGroupPositions(gd, xa, ya, calcTracesVertical); - setGroupPositions(gd, ya, xa, calcTracesHorizontal); -}; + }, 'constraintoward'); + if(!containerIn.scaleanchor) return; -function setGroupPositions(gd, pa, sa, calcTraces) { - if(!calcTraces.length) return; + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - var barmode = gd._fullLayout.barmode, - overlay = (barmode === 'overlay'), - group = (barmode === 'group'), - excluded, - included, - i, calcTrace, fullTrace; - - if(overlay) { - setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces); - } - else if(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); - } - if(excluded.length) { - setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + var scaleanchor = _$lib_172.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes } - } - else { - // 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; + }, 'scaleanchor'); - if(fullTrace.base === undefined) included.push(calcTrace); - else excluded.push(calcTrace); - } + 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; - if(included.length) { - setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included); - } - if(excluded.length) { - setGroupPositionsInOverlayMode(gd, pa, sa, excluded); - } + updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_172.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.'); } +}; - collectExtents(calcTraces, pa); -} +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. + var thisType = layoutOut[id2name(thisID)].type; -function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { - var barnorm = gd._fullLayout.barnorm, - separateNegativeValues = false, - dontMergeOverlappingData = !barnorm; + var i, j, idj, axj; - // update position axis and set bar offsets and widths - for(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; + var linkableAxes = []; + for(j = 0; j < allAxisIds.length; j++) { + idj = allAxisIds[j]; + if(idj === thisID) continue; - var sieve = new _$Sieve_281( - [calcTrace], separateNegativeValues, dontMergeOverlappingData - ); + axj = layoutOut[id2name(idj)]; + if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); + } - // set bar offsets and widths, and update position axis - setOffsetAndWidth(gd, pa, sieve); + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; - // 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(barnorm) { - sieveBars(gd, sa, sieve); - normalizeBars(gd, sa, sieve); - } - else { - setBaseAndTop(gd, sa, sieve); + 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}; +} -function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { - var fullLayout = gd._fullLayout, - barnorm = fullLayout.barnorm, - separateNegativeValues = false, - dontMergeOverlappingData = !barnorm, - sieve = new _$Sieve_281( - calcTraces, separateNegativeValues, dontMergeOverlappingData - ); - // set bar offsets and widths, and update position axis - setOffsetAndWidthInGroupMode(gd, pa, sieve); +/* + * 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; - // set bar bases and sizes, and update size axis - if(barnorm) { - sieveBars(gd, sa, sieve); - normalizeBars(gd, sa, sieve); + if(thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); } else { - setBaseAndTop(gd, sa, sieve); + thisGroupIndex = constraintGroups.indexOf(thisGroup); } -} - - -function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { - var fullLayout = gd._fullLayout, - barmode = fullLayout.barmode, - stack = (barmode === 'stack'), - relative = (barmode === 'relative'), - barnorm = gd._fullLayout.barnorm, - separateNegativeValues = relative, - dontMergeOverlappingData = !(barnorm || stack || relative), - sieve = new _$Sieve_281( - calcTraces, separateNegativeValues, dontMergeOverlappingData - ); - - // set bar offsets and widths, and update position axis - setOffsetAndWidth(gd, pa, sieve); - - // set bar bases and sizes, and update size axis - stackBars(gd, sa, sieve); - // 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_280) continue; + var thisGroupKeys = Object.keys(thisGroup); - var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); - if(isOutmostBar) bar._outmost = true; + // 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; } } - // Note that marking the outmost bars has to be done - // before `normalizeBars` changes `bar.b` and `bar.s`. - if(barnorm) normalizeBars(gd, sa, sieve); + // 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; } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function setOffsetAndWidth(gd, pa, sieve) { - var fullLayout = gd._fullLayout, - bargap = fullLayout.bargap, - bargroupgap = fullLayout.bargroupgap, - minDiff = sieve.minDiff, - calcTraces = sieve.traces, - i, calcTrace, calcTrace0, - t; - - // set bar offsets and widths - var barGroupWidth = minDiff * (1 - bargap), - barWidthPlusGap = barGroupWidth, - barWidth = barWidthPlusGap * (1 - bargroupgap); - - // computer bar group center and bar offset - var offsetFromCenter = -barWidth / 2; - for(i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; +'use strict'; - // store bar width and offset for this trace - t = calcTrace0.t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; - } +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - // stack bars that only differ by rounding - sieve.binWidth = calcTraces[0][0].t.barwidth / 100; +/* removed: var _$lib_172 = require('../../lib'); */; - // if defined, apply trace offset and width - applyAttributes(sieve); - // store the bar center in each calcdata item - setBarCenterAndWidth(gd, pa, sieve); +var _$handlePositionDefaults_229 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; - // update position axes - updatePositionAxis(gd, pa, sieve); -} + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; + } + } -function setOffsetAndWidthInGroupMode(gd, pa, sieve) { - var fullLayout = gd._fullLayout, - bargap = fullLayout.bargap, - bargroupgap = fullLayout.bargroupgap, - positions = sieve.positions, - distinctPositions = sieve.distinctPositions, - minDiff = sieve.minDiff, - calcTraces = sieve.traces, - i, calcTrace, calcTrace0, - t; + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_18(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; - // if there aren't any overlapping positions, - // let them have full width even if mode is group - var overlap = (positions.length !== distinctPositions.length); + var anchor = _$lib_172.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor + } + }, 'anchor'); - var nTraces = calcTraces.length, - barGroupWidth = minDiff * (1 - bargap), - barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth, - barWidth = barWidthPlusGap * (1 - bargroupgap); + if(anchor === 'free') coerce('position', dfltPosition); - for(i = 0; i < nTraces; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; + _$lib_172.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide + } + }, 'side'); - // computer bar group center and bar offset - var offsetFromCenter = (overlap) ? - ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : - -barWidth / 2; + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_172.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); + } - // store bar width and offset for this trace - t = calcTrace0.t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_172.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } - // stack bars that only differ by rounding - sieve.binWidth = calcTraces[0][0].t.barwidth / 100; + coerce('layer'); - // if defined, apply trace width - applyAttributes(sieve); + return containerOut; +}; - // store the bar center in each calcdata item - setBarCenterAndWidth(gd, pa, sieve); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // update position axes - updatePositionAxis(gd, pa, sieve, overlap); -} +'use strict'; -function applyAttributes(sieve) { - var calcTraces = sieve.traces, - i, calcTrace, calcTrace0, fullTrace, - j, - t; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$autoType_215 = require('./axis_autotype'); */; +var name2id = _$axis_ids_217.name2id; - for(i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; - fullTrace = calcTrace0.trace; - t = calcTrace0.t; +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_237 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); + } - var offset = fullTrace.offset, - initialPoffset = t.poffset, - newPoffset; + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - if(__isArrayOrTypedArray_280(offset)) { - // if offset is an array, then clone it into t.poffset. - newPoffset = offset.slice(0, calcTrace.length); + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; + } + } +}; - // guard against non-numeric items - for(j = 0; j < newPoffset.length; j++) { - if(!_$fastIsnumeric_18(newPoffset[j])) { - newPoffset[j] = initialPoffset; - } - } +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - // 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); - } + var id = ax._id; + var axLetter = id.charAt(0); - t.poffset = newPoffset; - } - else if(offset !== undefined) { - t.poffset = offset; - } + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; - var width = fullTrace.width, - initialBarwidth = t.barwidth; + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; - if(__isArrayOrTypedArray_280(width)) { - // if width is an array, then clone it into t.barwidth. - var newBarwidth = width.slice(0, calcTrace.length); + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } - // guard against non-numeric items - for(j = 0; j < newBarwidth.length; j++) { - if(!_$fastIsnumeric_18(newBarwidth[j])) newBarwidth[j] = initialBarwidth; - } + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; - // 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); - } + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - t.barwidth = newBarwidth; + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_262.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; - // 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; - } + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); + + if(trace[calAttr] !== calendar) calendar = undefined; } - 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; + ax.type = _$autoType_215(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_215(dim.values, calendar); + break; } } } + else { + ax.type = _$autoType_215(d0[axLetter] || [d0[axLetter + '0']], calendar); + } } +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; -function setBarCenterAndWidth(gd, pa, sieve) { - var calcTraces = sieve.traces, - pLetter = getAxisLetter(pa); - - for(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i], - t = calcTrace[0].t, - poffset = t.poffset, - poffsetIsArray = Array.isArray(poffset), - barwidth = t.barwidth, - 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; - + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } } } } +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} -function updatePositionAxis(gd, pa, sieve, allowMinDtick) { - var calcTraces = sieve.traces, - distinctPositions = sieve.distinctPositions, - distinctPositions0 = distinctPositions[0], - minDiff = sieve.minDiff, - vpad = minDiff / 2; +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_262.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_262.traceIs(trace._fullInput || {}, 'candlestick'); - _$axes_213.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); +} - // If the user set the bar width or the offset, - // then bars can be shifted away from their positions - // and widths can be larger than minDiff. - // - // Here, we compute pMin and pMax to expand the position axis, - // so that all bars are fully within the axis range. - var pMin = Math.min.apply(Math, distinctPositions) - vpad, - pMax = Math.max.apply(Math, distinctPositions) + vpad; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i], - calcTrace0 = calcTrace[0], - fullTrace = calcTrace0.trace; - if(fullTrace.width === undefined && fullTrace.offset === undefined) { - continue; - } +'use strict'; - var t = calcTrace0.t, - poffset = t.poffset, - barwidth = t.barwidth, - poffsetIsArray = Array.isArray(poffset), - barwidthIsArray = Array.isArray(barwidth); +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$layout_attributes_244 = require('../layout_attributes'); */; - for(var j = 0; j < calcTrace.length; j++) { - var calcBar = calcTrace[j], - calcBarOffset = (poffsetIsArray) ? poffset[j] : poffset, - calcBarWidth = (barwidthIsArray) ? barwidth[j] : barwidth, - p = calcBar.p, - l = p + calcBarOffset, - r = l + calcBarWidth; +/* removed: var _$layout_attributes_226 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_237 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_216 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_220 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_229 = require('./position_defaults'); */; +/* removed: var _$axis_ids_217 = require('./axis_ids'); */; - pMin = Math.min(pMin, l); - pMax = Math.max(pMax, r); - } - } - _$axes_213.expand(pa, [pMin, pMax], {padded: false}); -} +var _$supplyLayoutDefaults_227 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -function expandRange(range, newValue) { - if(_$fastIsnumeric_18(range[0])) range[0] = Math.min(range[0], newValue); - else range[0] = newValue; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - if(_$fastIsnumeric_18(range[1])) range[1] = Math.max(range[1], newValue); - else range[1] = newValue; -} + if(!_$registry_262.traceIs(trace, 'cartesian') && !_$registry_262.traceIs(trace, 'gl2d')) { + continue; + } -function setBaseAndTop(gd, sa, sieve) { - // 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. - var traces = sieve.traces, - sLetter = getAxisLetter(sa), - sRange = [null, null]; + var xaName = _$axis_ids_217.id2name(trace.xaxis); + var yaName = _$axis_ids_217.id2name(trace.yaxis); - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_262.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - for(var j = 0; j < trace.length; j++) { - var bar = trace[j], - barBase = bar.b, - barTop = barBase + bar.s; + // 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) xaCheater[xaName] = 1; + } - bar[sLetter] = barTop; + // check for default formatting tweaks + if(_$registry_262.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } - if(_$fastIsnumeric_18(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_18(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$registry_262.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; } } - _$axes_213.expand(sa, sRange, {tozero: true, padded: true}); -} + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_172.simpleMap(xIds, _$axis_ids_217.id2name); + var yNames = _$lib_172.simpleMap(yIds, _$axis_ids_217.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 plot_bgcolor = _$color_51.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_244, 'plot_bgcolor'); + } -function stackBars(gd, sa, sieve) { - var fullLayout = gd._fullLayout, - barnorm = fullLayout.barnorm, - sLetter = getAxisLetter(sa), - traces = sieve.traces, - i, trace, - j, bar; + var bgColor = _$color_51.combine(plot_bgcolor, layoutOut.paper_bgcolor); - var sRange = [null, null]; + var axName, axLetter, axLayoutIn, axLayoutOut; - for(i = 0; i < traces.length; i++) { - trace = traces[i]; + function coerce(attr, dflt) { + return _$lib_172.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_226, attr, dflt); + } - for(j = 0; j < trace.length; j++) { - bar = trace[j]; + function coerce2(attr, dflt) { + return _$lib_172.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_226, attr, dflt); + } - if(bar.s === __BADNUM_280) continue; + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } - // stack current bar and get previous sum - var barBase = sieve.put(bar.p, bar.b + bar.s), - barTop = barBase + bar.b + bar.s; + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - // store the bar base and top in each calcdata item - bar.b = barBase; - bar[sLetter] = barTop; + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; - if(!barnorm) { - if(_$fastIsnumeric_18(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_18(sa.c2l(barBase))) expandRange(sRange, barBase); + for(var j = 0; j < list.length; j++) { + var axName2 = list[j]; + + if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { + out.push(_$axis_ids_217.name2id(axName2)); } } - } - // if barnorm is set, let normalizeBars update the axis range - if(!barnorm) _$axes_213.expand(sa, sRange, {tozero: true, padded: true}); -} + 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]; -function sieveBars(gd, sa, sieve) { - var traces = sieve.traces; + if(!_$lib_172.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; + _$handleTypeDefaults_237(axLayoutIn, axLayoutOut, coerce, fullData, axName); - if(bar.s !== __BADNUM_280) sieve.put(bar.p, bar.b + bar.s); - } - } -} + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; -function normalizeBars(gd, sa, sieve) { - // Note: - // - // normalizeBars requires that either sieveBars or stackBars has been - // previously invoked. + _$handleAxisDefaults_216(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - var traces = sieve.traces, - sLetter = getAxisLetter(sa), - sTop = (gd._fullLayout.barnorm === 'fraction') ? 1 : 100, - sTiny = sTop / 1e9, // in case of rounding error in sum - sMin = sa.l2c(sa.c2l(0)), - sMax = (gd._fullLayout.barmode === 'stack') ? sTop : sMin, - sRange = [sMin, sMax], - padded = false; + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - function maybeExpand(newValue) { - if(_$fastIsnumeric_18(sa.c2l(newValue)) && - ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_18(sMin)) - ) { - padded = true; - expandRange(sRange, newValue); + if(!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; } - } - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; + _$handlePositionDefaults_229(axLayoutIn, axLayoutOut, coerce, positioningOptions); - if(bar.s === __BADNUM_280) continue; + axLayoutOut._input = axLayoutIn; + } - var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); - bar.b *= scale; - bar.s *= scale; + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_262.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_262.getComponentMethod('rangeselector', 'handleDefaults'); - var barBase = bar.b, - barTop = barBase + bar.s; - bar[sLetter] = barTop; + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - maybeExpand(barTop); - if(bar.hasB) maybeExpand(barBase); + rangeSliderDefaults(layoutIn, layoutOut, axName); + + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); } - } - // update range of size axis - _$axes_213.expand(sa, sRange, {tozero: true, padded: padded}); -} + coerce('fixedrange'); + } + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; -function getAxisLetter(ax) { - return ax._id.charAt(0); -} + var anchoredAxis = layoutOut[_$axis_ids_217.id2name(axLayoutOut.anchor)]; -// 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 posLetter = pa._id.charAt(0); - var extents = {}; - var pMin = Infinity; - var pMax = -Infinity; + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - var i, j, cd; - for(i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - for(j = 0; j < cd.length; j++) { - var p = cd[j].p; - if(_$fastIsnumeric_18(p)) { - pMin = Math.min(pMin, p); - pMax = Math.max(pMax, p); - } - } + coerce('fixedrange', fixedRangeDflt); } - // 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))); - }; + // Finally, handle scale constraints. 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). - for(i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - cd[0].t.extents = extents; - for(j = 0; j < cd.length; j++) { - var di = cd[j]; - var p0 = di[posLetter] - di.w / 2; - if(_$fastIsnumeric_18(p0)) { - var p1 = di[posLetter] + 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]; - } - } - } + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); + + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + + _$handleConstraintDefaults_220(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); } -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -35525,738 +36398,330 @@ function collectExtents(calcTraces, pa) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_15 = require('d3'); */; + +/* removed: var _$registry_262 = require('../../registry'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$registry_261 = require('../../registry'); */; +/* removed: var _$axes_214 = require('./axes'); */; +var axisRegex = _$constants_219.attrRegex; -var _$style_282 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_15.select(gd).selectAll('g.trace.bars'); - var barcount = s.size(); +var _$transitionAxes_236 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { var fullLayout = gd._fullLayout; + var axes = []; - // trace styling - s.style('opacity', function(d) { return d[0].trace.opacity; }) + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - // for gapless (either stacked or neighboring grouped) bars use - // crispEdges to turn off antialiasing so an artificial gap - // isn't introduced. - .each(function(d) { - if((fullLayout.barmode === 'stack' && barcount > 1) || - (fullLayout.bargap === 0 && - fullLayout.bargroupgap === 0 && - !d[0].trace.marker.line.width)) { - _$d3_15.select(this).attr('shape-rendering', 'crispEdges'); + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; + + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; + + update.axisName = axisName; + update.length = axis._length; + + axes.push(axisLetter); + + updates[axisLetter] = update; + } } - }); - s.selectAll('g.points').each(function(d) { - var sel = _$d3_15.select(this); - var pts = sel.selectAll('path'); - var txs = sel.selectAll('text'); - var trace = d[0].trace; + return updates; + } - _$drawing_76.pointStyle(pts, trace, gd); - _$drawing_76.selectedPointStyle(pts, trace); + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - txs.each(function(d) { - var tx = _$d3_15.select(this); - var textFont; + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - if(tx.classed('bartext-inside')) { - textFont = trace.insidetextfont; - } else if(tx.classed('bartext-outside')) { - textFont = trace.outsidetextfont; + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; + + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; } - if(!textFont) textFont = trace.textfont; - function cast(k) { - var cont = textFont[k]; - return Array.isArray(cont) ? cont[d.i] : cont; + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); } + } - _$drawing_76.font(tx, cast('family'), cast('size'), cast('color')); - }); + return affectedSubplots; + } - _$drawing_76.selectedTextStyle(txs, trace); - }); + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - _$registry_261.getComponentMethod('errorbars', 'style')(s); -}; + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -'use strict'; + redrawObjs(fullLayout.annotations || [], _$registry_262.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_262.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_262.getComponentMethod('images', 'draw'), true); + } -var _$constants_53 = { - cn: { - colorbar: 'colorbar', - cbbg: 'cbbg', - cbfill: 'cbfill', - cbfills: 'cbfills', - cbline: 'cbline', - cblines: 'cblines', - cbaxis: 'cbaxis', - cbtitleunshift: 'cbtitleunshift', - cbtitle: 'cbtitle', - cboutline: 'cboutline', - crisp: 'crisp', - jsPlaceholder: 'js-placeholder' + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; + activeAxIds = [xa._id, ya._id]; -'use strict'; + for(i = 0; i < activeAxIds.length; i++) { + _$axes_214.doTicks(gd, activeAxIds[i], true); + } -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -var __extendFlat_55 = _$extend_165.extendFlat; -/* removed: var _$setCursor_190 = require('../../lib/setcursor'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$titles_144 = require('../titles'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -var __LINE_SPACING_55 = _$alignment_151.LINE_SPACING; + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } -/* removed: var _$handleAxisDefaults_215 = require('../../plots/cartesian/axis_defaults'); */; -/* removed: var _$handlePositionDefaults_229 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_225 = require('../../plots/cartesian/layout_attributes'); */; + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -/* removed: var _$attributes_52 = require('./attributes'); */; -var cn = _$constants_53.cn; + redrawObjs(fullLayout.annotations || [], _$registry_262.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_262.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_262.getComponentMethod('images', 'draw'), true); + } -var _$draw_55 = function draw(gd, id) { - // opts: options object, containing everything from attributes - // plus a few others that are the equivalent of the colorbar "data" - var opts = {}; - Object.keys(_$attributes_52).forEach(function(k) { - opts[k] = null; - }); - // fillcolor can be a d3 scale, domain is z values, range is colors - // or leave it out for no fill, - // or set to a string constant for single-color fill - opts.fillcolor = null; - // line.color has the same options as fillcolor - opts.line = {color: null, width: null, dash: null}; - // levels of lines to draw. - // note that this DOES NOT determine the extent of the bar - // that's given by the domain of fillcolor - // (or line.color if no fillcolor domain) - opts.levels = {start: null, end: null, size: null}; - // separate fill levels (for example, heatmap coloring of a - // contour map) if this is omitted, fillcolors will be - // evaluated halfway between levels - opts.filllevels = null; + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - function component() { - var fullLayout = gd._fullLayout, - gs = fullLayout._size; - if((typeof opts.fillcolor !== 'function') && - (typeof opts.line.color !== 'function')) { - fullLayout._infolayer.selectAll('g.' + id).remove(); - return; - } - var zrange = _$d3_15.extent(((typeof opts.fillcolor === 'function') ? - opts.fillcolor : opts.line.color).domain()); - var linelevels = []; - var filllevels = []; - var linecolormap = typeof opts.line.color === 'function' ? - opts.line.color : function() { return opts.line.color; }; - var fillcolormap = typeof opts.fillcolor === 'function' ? - opts.fillcolor : function() { return opts.fillcolor; }; - var l; - var i; + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_76.setTranslate, 0, 0) + .call(_$drawing_76.setScale, 1, 1); - var l0 = opts.levels.end + opts.levels.size / 100, - ls = opts.levels.size, - zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), - zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); - for(i = 0; i < 1e5; i++) { - l = opts.levels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zr0 && l < zr1) linelevels.push(l); - } + subplot.plot + .call(_$drawing_76.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_76.setScale, 1, 1); - if(typeof opts.fillcolor === 'function') { - if(opts.filllevels) { - l0 = opts.filllevels.end + opts.filllevels.size / 100; - ls = opts.filllevels.size; - for(i = 0; i < 1e5; i++) { - l = opts.filllevels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zrange[0] && l < zrange[1]) filllevels.push(l); - } - } - else { - filllevels = linelevels.map(function(v) { - return v - opts.levels.size / 2; - }); - filllevels.push(filllevels[filllevels.length - 1] + - opts.levels.size); - } - } - else if(opts.fillcolor && typeof opts.fillcolor === 'string') { - // doesn't matter what this value is, with a single value - // we'll make a single fill rect covering the whole bar - filllevels = [0]; - } + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); - if(opts.levels.size < 0) { - linelevels.reverse(); - filllevels.reverse(); - } + // 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_76.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_76.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_76.hideOutsideRangePoints, subplot); + } - // now make a Plotly Axes object to scale with and draw ticks - // TODO: does not support orientation other than right + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - // we calculate pixel sizes based on the specified graph size, - // not the actual (in case something pushed the margins around) - // which is a little odd but avoids an odd iterative effect - // when the colorbar itself is pushing the margins. - // but then the fractional size is calculated based on the - // actual graph size, so that the axes will size correctly. - var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, - originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, - thickPx = Math.round(opts.thickness * - (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), - thickFrac = thickPx / gs.w, - lenPx = Math.round(opts.len * - (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), - lenFrac = lenPx / gs.h, - xpadFrac = opts.xpad / gs.w, - yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, - ypadFrac = opts.ypad / gs.h, + var viewBox = []; - // x positioning: do it initially just for left anchor, - // then fix at the end (since we don't know the width yet) - xLeft = Math.round(opts.x * gs.w + opts.xpad), - // for dragging... this is getting a little muddled... - xLeftFrac = opts.x - thickFrac * - ({middle: 0.5, right: 1}[opts.xanchor]||0), + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - // y positioning we can do correctly from the start - yBottomFrac = opts.y + lenFrac * - (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), - yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), - yTopPx = yBottomPx - lenPx, - titleEl, - cbAxisIn = { - type: 'linear', - range: zrange, - tickmode: opts.tickmode, - nticks: opts.nticks, - tick0: opts.tick0, - dtick: opts.dtick, - tickvals: opts.tickvals, - ticktext: opts.ticktext, - ticks: opts.ticks, - ticklen: opts.ticklen, - tickwidth: opts.tickwidth, - tickcolor: opts.tickcolor, - showticklabels: opts.showticklabels, - tickfont: opts.tickfont, - tickangle: opts.tickangle, - tickformat: opts.tickformat, - exponentformat: opts.exponentformat, - separatethousands: opts.separatethousands, - showexponent: opts.showexponent, - showtickprefix: opts.showtickprefix, - tickprefix: opts.tickprefix, - showticksuffix: opts.showticksuffix, - ticksuffix: opts.ticksuffix, - title: opts.title, - titlefont: opts.titlefont, - showline: true, - anchor: 'free', - position: 1 - }, - cbAxisOut = { - type: 'linear', - _id: 'y' + id - }, - axisOptions = { - letter: 'y', - font: fullLayout.font, - noHover: true, - calendar: fullLayout.calendar // not really necessary (yet?) - }; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - // Coerce w.r.t. Axes layoutAttributes: - // re-use axes.js logic without updating _fullData - function coerce(attr, dflt) { - return _$lib_171.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_225, attr, dflt); + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; } - // Prepare the Plotly axis object - _$handleAxisDefaults_215(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); - _$handlePositionDefaults_229(cbAxisIn, cbAxisOut, coerce, axisOptions); - - // position can't go in through supplyDefaults - // because that restricts it to [0,1] - cbAxisOut.position = opts.x + xpadFrac + thickFrac; + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // save for other callers to access this axis - component.axis = cbAxisOut; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - cbAxisOut.titleside = opts.titleside; - cbAxisOut.titlex = opts.x + xpadFrac; - cbAxisOut.titley = yBottomFrac + - (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; } - if(opts.line.color && opts.tickmode === 'auto') { - cbAxisOut.tickmode = 'linear'; - cbAxisOut.tick0 = opts.levels.start; - var dtick = opts.levels.size; - // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_171.constrain( - (yBottomPx - yTopPx) / 50, 4, 15) + 1, - dtFactor = (zrange[1] - zrange[0]) / - ((opts.nticks || autoNtick) * dtick); - if(dtFactor > 1) { - var dtexp = Math.pow(10, Math.floor( - Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_171.roundUp(dtFactor / dtexp, [2, 5, 10]); - // if the contours are at round multiples, reset tick0 - // so they're still at round multiples. Otherwise, - // keep the first label on the first contour level - if((Math.abs(opts.levels.start) / - opts.levels.size + 1e-6) % 1 < 2e-6) { - cbAxisOut.tick0 = 0; - } - } - cbAxisOut.dtick = dtick; - } + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - // set domain after init, because we may want to - // allow it outside [0,1] - cbAxisOut.domain = [ - yBottomFrac + ypadFrac, - yBottomFrac + lenFrac - ypadFrac - ]; - cbAxisOut.setScale(); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_15.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); - container.attr('transform', 'translate(' + Math.round(gs.l) + - ',' + Math.round(gs.t) + ')'); - // TODO: this opposite transform is a hack until we make it - // more rational which items get this offset - var titleCont = container.select('.cbtitleunshift') - .attr('transform', 'translate(-' + - Math.round(gs.l) + ',-' + - Math.round(gs.t) + ')'); + var editX = !!xUpdate; + var editY = !!yUpdate; - cbAxisOut._axislayer = container.select('.cbaxis'); - var titleHeight = 0; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // draw the title so we know how much room it needs - // when we squish the axis. This one only applies to - // top or bottom titles, not right side. - var x = gs.l + (opts.x + xpadFrac) * gs.w, - fontSize = cbAxisOut.titlefont.size, - y; + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - if(opts.titleside === 'top') { - y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + - gs.t + 3 + fontSize * 0.75; - } - else { - y = (1 - (yBottomFrac + ypadFrac)) * gs.h + - gs.t - 3 - fontSize * 0.25; - } - drawTitle(cbAxisOut._id + 'title', { - attributes: {x: x, y: y, 'text-anchor': 'start'} - }); - } + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - function drawAxis() { - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // squish the axis top to make room for the title - var titleGroup = container.select('.cbtitle'), - titleText = titleGroup.select('text'), - titleTrans = - [-opts.outlinewidth / 2, opts.outlinewidth / 2], - mathJaxNode = titleGroup - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - lineSize = 15.6; - if(titleText.node()) { - lineSize = - parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_55; - } - if(mathJaxNode) { - titleHeight = _$drawing_76.bBox(mathJaxNode).height; - if(titleHeight > lineSize) { - // not entirely sure how mathjax is doing - // vertical alignment, but this seems to work. - titleTrans[1] -= (titleHeight - lineSize) / 2; - } - } - else if(titleText.node() && - !titleText.classed(cn.jsPlaceholder)) { - titleHeight = _$drawing_76.bBox(titleText.node()).height; - } - if(titleHeight) { - // buffer btwn colorbar and title - // TODO: configurable - titleHeight += 5; + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - if(opts.titleside === 'top') { - cbAxisOut.domain[1] -= titleHeight / gs.h; - titleTrans[1] *= -1; - } - else { - cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_192.lineCount(titleText); - titleTrans[1] += (1 - nlines) * lineSize; - } + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - titleGroup.attr('transform', - 'translate(' + titleTrans + ')'); + subplot.clipRect + .call(_$drawing_76.setTranslate, clipDx, clipDy) + .call(_$drawing_76.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - cbAxisOut.setScale(); - } - } + subplot.plot + .call(_$drawing_76.setTranslate, plotDx, plotDy) + .call(_$drawing_76.setScale, xScaleFactor, yScaleFactor) - container.selectAll('.cbfills,.cblines') - .attr('transform', 'translate(0,' + - Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_76.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - cbAxisOut._axislayer.attr('transform', 'translate(0,' + - Math.round(-gs.t) + ')'); + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_76.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + } - var fills = container.select('.cbfills') - .selectAll('rect.cbfill') - .data(filllevels); - fills.enter().append('rect') - .classed(cn.cbfill, true) - .style('stroke', 'none'); - fills.exit().remove(); - fills.each(function(d, i) { - var z = [ - (i === 0) ? zrange[0] : - (filllevels[i] + filllevels[i - 1]) / 2, - (i === filllevels.length - 1) ? zrange[1] : - (filllevels[i] + filllevels[i + 1]) / 2 - ] - .map(cbAxisOut.c2p) - .map(Math.round); + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } - // offset the side adjoining the next rectangle so they - // overlap, to prevent antialiasing gaps - if(i !== filllevels.length - 1) { - z[1] += (z[1] > z[0]) ? 1 : -1; - } + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; + axi.range = to.slice(); + } - // Tinycolor can't handle exponents and - // at this scale, removing it makes no difference. - var colorString = fillcolormap(d).replace('e-', ''), - opaqueColor = _$tinycolor_33(colorString).toHexString(); + // Signal that this transition has completed: + onComplete && onComplete(); - // Colorbar cannot currently support opacities so we - // use an opaque fill even when alpha channels present - _$d3_15.select(this).attr({ - x: xLeft, - width: Math.max(thickPx, 2), - y: _$d3_15.min(z), - height: Math.max(_$d3_15.max(z) - _$d3_15.min(z), 2), - fill: opaqueColor - }); - }); + return _$registry_262.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var lines = container.select('.cblines') - .selectAll('path.cbline') - .data(opts.line.color && opts.line.width ? - linelevels : []); - lines.enter().append('path') - .classed(cn.cbline, true); - lines.exit().remove(); - lines.each(function(d) { - _$d3_15.select(this) - .attr('d', 'M' + xLeft + ',' + - (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + - 'h' + thickPx) - .call(_$drawing_76.lineGroupStyle, - opts.line.width, linecolormap(d), opts.line.dash); - }); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; - // force full redraw of labels and ticks - cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') - .remove(); + axi.range = axi._r.slice(); + } - cbAxisOut._pos = xLeft + thickPx + - (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); - cbAxisOut.side = 'right'; + return _$registry_262.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - // separate out axis and title drawing, - // so we don't need such complicated logic in Titles.draw - // if title is on the top or bottom, we've already drawn it - // this title call only handles side=right - return _$lib_171.syncOrAsync([ - function() { - return _$axes_213.doTicks(gd, cbAxisOut, true); - }, - function() { - if(['top', 'bottom'].indexOf(opts.titleside) === -1) { - var fontSize = cbAxisOut.titlefont.size, - y = cbAxisOut._offset + cbAxisOut._length / 2, - x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? - 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : - -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); + var t1, t2, raf; + var easeFn = _$d3_15.ease(transitionOpts.easing); - // the 'h' + is a hack to get around the fact that - // convertToTspans rotates any 'y...' class by 90 degrees. - // TODO: find a better way to control this. - drawTitle('h' + cbAxisOut._id + 'title', { - avoid: { - selection: _$d3_15.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), - side: opts.titleside, - offsetLeft: gs.l, - offsetTop: 0, - maxShift: fullLayout.width - }, - attributes: {x: x, y: y, 'text-anchor': 'middle'}, - transform: {rotate: '-90', offset: 0} - }); - } - }]); - } + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); - function drawTitle(titleClass, titleOpts) { - var trace = getTrace(), - propName; - if(_$registry_261.traceIs(trace, 'markerColorscale')) { - propName = 'marker.colorbar.title'; - } - else propName = 'colorbar.title'; + function doFrame() { + t2 = Date.now(); - var dfltTitleOpts = { - propContainer: cbAxisOut, - propName: propName, - traceIndex: trace.index, - placeholder: fullLayout._dfltTitle.colorbar, - containerGroup: container.select('.cbtitle') - }; + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); - // this class-to-rotate thing with convertToTspans is - // getting hackier and hackier... delete groups with the - // wrong class (in case earlier the colorbar was drawn on - // a different side, I think?) - var otherClass = titleClass.charAt(0) === 'h' ? - titleClass.substr(1) : ('h' + titleClass); - container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') - .remove(); + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } - _$titles_144.draw(gd, titleClass, - __extendFlat_55(dfltTitleOpts, titleOpts || {})); + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); } + } - function positionCB() { - // wait for the axis & title to finish rendering before - // continuing positioning - // TODO: why are we redrawing multiple times now with this? - // I guess autoMargin doesn't like being post-promise? - var innerWidth = thickPx + opts.outlinewidth / 2 + - _$drawing_76.bBox(cbAxisOut._axislayer.node()).width; - titleEl = titleCont.select('text'); - if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { - var mathJaxNode = titleCont - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - titleWidth; - if(mathJaxNode && - ['top', 'bottom'].indexOf(opts.titleside) !== -1) { - titleWidth = _$drawing_76.bBox(mathJaxNode).width; - } - else { - // note: the formula below works for all titlesides, - // (except for top/bottom mathjax, above) - // but the weird gs.l is because the titleunshift - // transform gets removed by Drawing.bBox - titleWidth = - _$drawing_76.bBox(titleCont.node()).right - - xLeft - gs.l; - } - innerWidth = Math.max(innerWidth, titleWidth); - } - - var outerwidth = 2 * opts.xpad + innerWidth + - opts.borderwidth + opts.outlinewidth / 2, - outerheight = yBottomPx - yTopPx; - - container.select('.cbbg').attr({ - x: xLeft - opts.xpad - - (opts.borderwidth + opts.outlinewidth) / 2, - y: yTopPx - yExtraPx, - width: Math.max(outerwidth, 2), - height: Math.max(outerheight + 2 * yExtraPx, 2) - }) - .call(_$color_51.fill, opts.bgcolor) - .call(_$color_51.stroke, opts.bordercolor) - .style({'stroke-width': opts.borderwidth}); - - container.selectAll('.cboutline').attr({ - x: xLeft, - y: yTopPx + opts.ypad + - (opts.titleside === 'top' ? titleHeight : 0), - width: Math.max(thickPx, 2), - height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) - }) - .call(_$color_51.stroke, opts.outlinecolor) - .style({ - fill: 'None', - 'stroke-width': opts.outlinewidth - }); - - // fix positioning for xanchor!='left' - var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * - outerwidth; - container.attr('transform', - 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); - - // auto margin adjustment - _$plots_246.autoMargin(gd, id, { - x: opts.x, - y: opts.y, - l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), - r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), - t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), - b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) - }); - } - - var cbDone = _$lib_171.syncOrAsync([ - _$plots_246.previousPromises, - drawAxis, - _$plots_246.previousPromises, - positionCB - ], gd); - - if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); - - // dragging... - if(gd._context.edits.colorbarPosition) { - var t0, - xf, - yf; - - _$dragelement_73.init({ - element: container.node(), - gd: gd, - prepFn: function() { - t0 = container.attr('transform'); - _$setCursor_190(container); - }, - moveFn: function(dx, dy) { - container.attr('transform', - t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); - - xf = _$dragelement_73.align(xLeftFrac + (dx / gs.w), thickFrac, - 0, 1, opts.xanchor); - yf = _$dragelement_73.align(yBottomFrac - (dy / gs.h), lenFrac, - 0, 1, opts.yanchor); - - var csr = _$dragelement_73.getCursor(xf, yf, - opts.xanchor, opts.yanchor); - _$setCursor_190(container, csr); - }, - doneFn: function() { - _$setCursor_190(container); - - if(xf !== undefined && yf !== undefined) { - _$registry_261.call('restyle', - gd, - {'colorbar.x': xf, 'colorbar.y': yf}, - getTrace().index - ); - } - } - }); - } - return cbDone; - } - - function getTrace() { - var idNum = id.substr(2), - i, - trace; - for(i = 0; i < gd._fullData.length; i++) { - trace = gd._fullData[i]; - if(trace.uid === idNum) return trace; - } - } - - // setter/getters for every item defined in opts - Object.keys(opts).forEach(function(name) { - component[name] = function(v) { - // getter - if(!arguments.length) return opts[name]; - - // setter - for multi-part properties, - // set only the parts that are provided - opts[name] = _$lib_171.isPlainObject(opts[name]) ? - _$lib_171.extendFlat(opts[name], v) : - v; - - return component; - }; - }); - - // or use .options to set multiple options at once via a dictionary - component.options = function(o) { - Object.keys(o).forEach(function(name) { - // in case something random comes through - // that's not an option, ignore it - if(typeof component[name] === 'function') { - component[name](o[name]); - } - }); - return component; - }; - - component._opts = opts; + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - return component; + return Promise.resolve(); }; +var _$get_data_242 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -36265,89 +36730,112 @@ var _$draw_55 = function draw(gd, id) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$colorscale_66 = require('../../components/colorscale'); */; -/* removed: var _$draw_55 = require('../../components/colorbar/draw'); */; - +/* removed: var _$registry_262 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_219.SUBPLOT_PATTERN; -var _$colorbar_372 = function colorbar(gd, cd) { - var trace = cd[0].trace, - marker = trace.marker, - cbId = 'cb' + trace.uid; +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_242.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_262.subplotsRegistry[type]; + if(!basePlotModule) return []; - gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); + var attr = basePlotModule.attr; + var subplotCalcData = []; - // TODO make Colorbar.draw support multiple colorbar per trace + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; - if((marker === undefined) || !marker.showscale) { - _$plots_246.autoMargin(gd, cbId); - return; + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); } - var vals = marker.color, - cmin = marker.cmin, - cmax = marker.cmax; + return subplotCalcData; +}; +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_242.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_262.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; - if(!_$fastIsnumeric_18(cmin)) cmin = _$lib_171.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_18(cmax)) cmax = _$lib_171.aggNums(Math.max, null, vals); + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; - var cb = cd[0].t.cb = _$draw_55(gd, cbId); - var sclFunc = _$colorscale_66.makeColorScaleFunc( - _$colorscale_66.extractScale( - marker.colorscale, - cmin, - cmax - ), - { noNumericCheck: true } - ); + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } + } - cb.fillcolor(sclFunc) - .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) - .options(marker.colorbar)(); + return [moduleCalcData, remainingCalcData]; }; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_242.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_262.subplotsRegistry[type]) return []; + var attr = _$registry_262.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; -'use strict'; + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } -var Bar = {}; + for(var i = 0; i < data.length; i++) { + trace = data[i]; -Bar.attributes = _$attributes_271; -Bar.layoutAttributes = _$layout_attributes_276; -Bar.supplyDefaults = _$supplyDefaults_273; -Bar.supplyLayoutDefaults = _$layout_defaults_277; -Bar.calc = _$calc_272; -Bar.setPositions = _$setPositions_280; -Bar.colorbar = _$colorbar_372; -Bar.arraysToCalcdata = _$arraysToCalcdata_270; -Bar.plot = _$plot_278; -Bar.style = _$style_282; -Bar.hoverPoints = _$hoverPoints_274; -Bar.selectPoints = _$selectPoints_279; + if(type === 'gl2d' && _$registry_262.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); + } + } + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } + } -Bar.moduleType = 'trace'; -Bar.name = 'bar'; -Bar.basePlotModule = _$cartesian_224; -Bar.categories = ['cartesian', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend']; -Bar.meta = { - + return subplotData; }; -var _$Bar_275 = Bar; - +var _$cartesian_225 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -36356,805 +36844,597 @@ var _$Bar_275 = Bar; * LICENSE file in the root directory of this source tree. */ -'use strict'; -var _$bar_3 = _$Bar_275; +'use strict'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$plots_246 = require('../plots'); */; +var getModuleCalcData = _$get_data_242.getModuleCalcData; -'use strict'; +/* removed: var _$axis_ids_217 = require('./axis_ids'); */; +/* removed: var _$constants_219 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$attributes_368 = require('../scatter/attributes'); */; -/* removed: var _$attributes_50 = require('../../components/color/attributes'); */; -var __extendFlat_284 = _$extend_165.extendFlat; +var ensureSingle = _$lib_172.ensureSingle; -var __scatterMarkerAttrs_284 = _$attributes_368.marker; -var __scatterMarkerLineAttrs_284 = __scatterMarkerAttrs_284.line; +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_172.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} -var _$attributes_284 = { - 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', - - }, - name: { - valType: 'string', - - editType: 'calc+clearAxisTypes', - - }, - text: __extendFlat_284({}, _$attributes_368.text, { - - }), - whiskerwidth: { - valType: 'number', - min: 0, - max: 1, - dflt: 0.5, - - editType: 'calcIfAutorange', - - }, - notched: { - valType: 'boolean', - - editType: 'calcIfAutorange', - - }, - notchwidth: { - valType: 'number', - min: 0, - max: 0.5, - dflt: 0.25, - - editType: 'calcIfAutorange', - - }, - boxpoints: { - valType: 'enumerated', - values: ['all', 'outliers', 'suspectedoutliers', false], - dflt: 'outliers', - - editType: 'calcIfAutorange', - - }, - boxmean: { - valType: 'enumerated', - values: [true, 'sd', false], - dflt: false, - - editType: 'calcIfAutorange', - - }, - jitter: { - valType: 'number', - min: 0, - max: 1, - - editType: 'calcIfAutorange', - - }, - pointpos: { - valType: 'number', - min: -2, - max: 2, - - editType: 'calcIfAutorange', - - }, - orientation: { - valType: 'enumerated', - values: ['v', 'h'], - - editType: 'calc+clearAxisTypes', - - }, - marker: { - outliercolor: { - valType: 'color', - dflt: 'rgba(0, 0, 0, 0)', - - editType: 'style', - - }, - symbol: __extendFlat_284({}, __scatterMarkerAttrs_284.symbol, - {arrayOk: false, editType: 'plot'}), - opacity: __extendFlat_284({}, __scatterMarkerAttrs_284.opacity, - {arrayOk: false, dflt: 1, editType: 'style'}), - size: __extendFlat_284({}, __scatterMarkerAttrs_284.size, - {arrayOk: false, editType: 'calcIfAutorange'}), - color: __extendFlat_284({}, __scatterMarkerAttrs_284.color, - {arrayOk: false, editType: 'style'}), - line: { - color: __extendFlat_284({}, __scatterMarkerLineAttrs_284.color, - {arrayOk: false, dflt: _$attributes_50.defaultLine, editType: 'style'} - ), - width: __extendFlat_284({}, __scatterMarkerLineAttrs_284.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: _$attributes_368.fillcolor, +_$cartesian_225.name = 'cartesian'; - selected: { - marker: _$attributes_368.selected.marker, - editType: 'style' - }, - unselected: { - marker: _$attributes_368.unselected.marker, - editType: 'style' - }, +_$cartesian_225.attr = ['xaxis', 'yaxis']; - hoveron: { - valType: 'flaglist', - flags: ['boxes', 'points'], - dflt: 'boxes+points', - - editType: 'style', - - } -}; +_$cartesian_225.idRoot = ['x', 'y']; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +_$cartesian_225.idRegex = _$constants_219.idRegex; -'use strict'; +_$cartesian_225.attrRegex = _$constants_219.attrRegex; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +_$cartesian_225.attributes = _$attributes_212; -/* removed: var _$lib_171 = require('../../lib'); */; -var ____285 = _$lib_171._; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; +_$cartesian_225.layoutAttributes = _$layout_attributes_226; -// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html -var _$calc_285 = function calc(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = _$axes_213.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_213.getFromId(gd, trace.yaxis || 'y'); - var cd = []; +_$cartesian_225.supplyLayoutDefaults = _$supplyLayoutDefaults_227; - // N.B. violin reuses same Box.calc - var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes'; +_$cartesian_225.transitionAxes = _$transitionAxes_236; - var i; - var valAxis, valLetter; - var posAxis, posLetter; +_$cartesian_225.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - if(trace.orientation === 'h') { - valAxis = xa; - valLetter = 'x'; - posAxis = ya; - posLetter = 'y'; - } else { - valAxis = ya; - valLetter = 'y'; - posAxis = xa; - posLetter = 'x'; + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; } - var val = valAxis.makeCalcdata(trace, valLetter); - var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]); - - var dv = _$lib_171.distinctVals(pos); - var posDistinct = dv.vals; - var dPos = dv.minDiff / 2; - var posBins = makeBins(posDistinct, dPos); + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_217.id2name(xi)] || {}).anchor; + if(!_$constants_219.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - var vLen = val.length; - var pLen = posDistinct.length; - var ptsPerBin = initNestedArray(pLen); + if(!allY[yi]) { + allY[yi] = 1; + _$lib_172.pushUnique(yList, yi); + } + } + } - // bin pts info per position bins - for(i = 0; i < vLen; i++) { - var v = val[i]; - if(!_$fastIsnumeric_18(v)) continue; + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_217.id2name(yi)] || {}).anchor; + if(!_$constants_219.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - var n = _$lib_171.findBin(pos[i], posBins); - if(n >= 0 && n < pLen) { - var pt = {v: v, i: i}; - __arraysToCalcdata_285(pt, trace, i); - ptsPerBin[n].push(pt); + if(!allX[xi]) { + allX[xi] = 1; + _$lib_172.pushUnique(xList, xi); + } } } - // build calcdata trace items, one item per distinct position - for(i = 0; i < pLen; i++) { - if(ptsPerBin[i].length > 0) { - var pts = ptsPerBin[i].sort(sortByVal); - var boxVals = pts.map(extractVal); - var bvLen = boxVals.length; - - var cdi = { - pos: posDistinct[i], - pts: pts - }; + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_219.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } + } + xi = xi ? _$axis_ids_217.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_217.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; - cdi.min = boxVals[0]; - cdi.max = boxVals[bvLen - 1]; - cdi.mean = _$lib_171.mean(boxVals, bvLen); - cdi.sd = _$lib_171.stdev(boxVals, bvLen, cdi.mean); +_$cartesian_225.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; - // first quartile - cdi.q1 = _$lib_171.interp(boxVals, 0.25); - // median - cdi.med = _$lib_171.interp(boxVals, 0.5); - // third quartile - cdi.q3 = _$lib_171.interp(boxVals, 0.75); + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; - // lower and upper fences - last point inside - // 1.5 interquartile ranges from quartiles - cdi.lf = Math.min( - cdi.q1, - boxVals[Math.min( - _$lib_171.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, - bvLen - 1 - )] - ); - cdi.uf = Math.max( - cdi.q3, - boxVals[Math.max( - _$lib_171.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), - 0 - )] - ); + for(i = 0; i < calcdata.length; i++) { + traces.push(i); + } + } - // lower and upper outliers - 3 IQR out (don't clip to max/min, - // this is only for discriminating suspected & far outliers) - cdi.lo = 4 * cdi.q1 - 3 * cdi.q3; - cdi.uo = 4 * cdi.q3 - 3 * cdi.q1; + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; - // lower and upper notches ~95% Confidence Intervals for median - var iqr = cdi.q3 - cdi.q1; - var mci = 1.57 * iqr / Math.sqrt(bvLen); - cdi.ln = cdi.med - mci; - cdi.un = cdi.med + mci; + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; - cd.push(cdi); - } - } + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - __calcSelection_285(cd, trace); - _$axes_213.expand(valAxis, val, {padded: true}); + cdSubplot.push(cd); + } - if(cd.length > 0) { - cd[0].t = { - num: fullLayout[numKey], - dPos: dPos, - posLetter: posLetter, - valLetter: valLetter, - labels: { - med: ____285(gd, 'median:'), - min: ____285(gd, 'min:'), - q1: ____285(gd, 'q1:'), - q3: ____285(gd, 'q3:'), - max: ____285(gd, 'max:'), - mean: trace.boxmean === 'sd' ? ____285(gd, 'mean ± σ:') : ____285(gd, 'mean:'), - lf: ____285(gd, 'lower fence:'), - uf: ____285(gd, 'upper fence:') + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; } - }; - - // don't show labels in candlestick hover labels - if(trace._fullInput && trace._fullInput.type === 'candlestick') { - delete cd[0].t.labels; } - fullLayout[numKey]++; - return cd; - } else { - return [{t: {empty: true}}]; + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); } }; -// 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, val, num) { - if(posLetter in trace) { - return posAxis.makeCalcdata(trace, posLetter); - } - - var pos0; +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; - if(posLetter + '0' in trace) { - pos0 = trace[posLetter + '0']; - } else if('name' in trace && ( - posAxis.type === 'category' || ( - _$fastIsnumeric_18(trace.name) && - ['linear', 'log'].indexOf(posAxis.type) !== -1 - ) || ( - _$lib_171.isDateTime(trace.name) && - posAxis.type === 'date' - ) - )) { - pos0 = trace.name; - } else { - pos0 = num; + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); } - var pos0c = posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']); - return val.map(function() { return pos0c; }); -} - -function makeBins(x, dx) { - var len = x.length; - var bins = new Array(len + 1); + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; - for(var i = 0; i < len; i++) { - bins[i] = x[i] - dx; - } - bins[len] = x[len - 1] + dx; + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; - return bins; -} + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; -function initNestedArray(len) { - var arr = new Array(len); - for(var i = 0; i < len; i++) { - arr[i] = []; + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); } - return arr; } -function __arraysToCalcdata_285(pt, trace, i) { - var trace2calc = { - text: 'tx' - }; +_$cartesian_225.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; - for(var k in trace2calc) { - if(Array.isArray(trace[k])) { - pt[trace2calc[k]] = trace[k][i]; + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; + + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); } } -} -function __calcSelection_285(cd, trace) { - if(_$lib_171.isArrayOrTypedArray(trace.selectedpoints)) { - for(var i = 0; i < cd.length; i++) { - var pts = cd[i].pts || []; - var ptNumber2cdIndex = {}; + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } - for(var j = 0; j < pts.length; j++) { - ptNumber2cdIndex[pts[j].i] = j; + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } + + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); + + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } } - _$lib_171.tagSelected(pts, trace, ptNumber2cdIndex); + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); } } -} -function sortByVal(a, b) { return a.v - b.v; } + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; -function extractVal(o) { return o.v; } + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; -'use strict'; + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$color_51 = require('../../components/color'); */; + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + } + } + } -/* removed: var _$attributes_284 = require('./attributes'); */; + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); -function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_284, attr, dflt); + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } + } +}; - handleSampleDefaults(traceIn, traceOut, coerce, layout); - if(traceOut.visible === false) return; - - coerce('line.color', (traceIn.marker || {}).color || defaultColor); - coerce('line.width'); - coerce('fillcolor', _$color_51.addOpacity(traceOut.line.color, 0.5)); +_$cartesian_225.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); - coerce('whiskerwidth'); - coerce('boxmean'); + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_172.identity); - var notched = coerce('notched', traceIn.notchwidth !== undefined); - if(notched) coerce('notchwidth'); + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); - handlePointsDefaults(traceIn, traceOut, coerce, {prefix: 'box'}); -} + subplotLayers.order(); -function handleSampleDefaults(traceIn, traceOut, coerce, layout) { - var y = coerce('y'); - var x = coerce('x'); + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - var defaultOrientation; + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; - if(y && y.length) { - defaultOrientation = 'v'; - if(!x) coerce('x0'); - } else if(x && x.length) { - defaultOrientation = 'h'; - coerce('y0'); - } else { - traceOut.visible = false; - return; - } + // keep ref to plot group + plotinfo.plotgroup = _$d3_15.select(this); - var handleCalendarDefaults = _$registry_261.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); + // initialize list of overlay subplots + plotinfo.overlays = []; - coerce('orientation', defaultOrientation); -} + makeSubplotLayer(gd, plotinfo); -function handlePointsDefaults(traceIn, traceOut, coerce, opts) { - var prefix = opts.prefix; + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); + } - var outlierColorDflt = _$lib_171.coerce2(traceIn, traceOut, _$attributes_284, 'marker.outliercolor'); - var lineoutliercolor = coerce('marker.line.outliercolor'); + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; - var points = coerce( - prefix + 'points', - (outlierColorDflt || lineoutliercolor) ? 'suspectedoutliers' : undefined - ); +_$cartesian_225.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_246.style(gd); +}; - if(points) { - coerce('jitter', points === 'all' ? 0.3 : 0); - coerce('pointpos', points === 'all' ? -1.5 : 0); +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; - coerce('marker.symbol'); - coerce('marker.opacity'); - coerce('marker.size'); - coerce('marker.color', traceOut.line.color); - coerce('marker.line.color'); - coerce('marker.line.width'); + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; - if(points === 'suspectedoutliers') { - coerce('marker.line.outliercolor', traceOut.marker.color); - coerce('marker.line.outlierwidth'); + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; } - - coerce('selected.marker.color'); - coerce('unselected.marker.color'); - coerce('selected.marker.size'); - coerce('unselected.marker.size'); - - coerce('text'); - } else { - delete traceOut.marker; } - coerce('hoveron'); + // main subplots before overlays + subplotData = subplotData.concat(overlays); - _$lib_171.coerceSelectionMarkerOpacity(traceOut, coerce); + return subplotData; } -var _$defaults_286 = { - supplyDefaults: supplyDefaults, - handleSampleDefaults: handleSampleDefaults, - handlePointsDefaults: handlePointsDefaults -}; +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_219.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_219.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); -'use strict'; + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$fx_93 = require('../../components/fx'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$fillHoverText_376 = require('../scatter/fill_hover_text'); */; + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); -function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - var hoveron = trace.hoveron; - var closeBoxData = []; - var closePtData; + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - if(hoveron.indexOf('boxes') !== -1) { - closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode)); - } + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); - if(hoveron.indexOf('points') !== -1) { - closePtData = hoverOnPoints(pointData, xval, yval); - } + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); - // If there's a point in range and hoveron has points, show the best single point only. - // If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats. - if(hovermode === 'closest') { - if(closePtData) return [closePtData]; - return closeBoxData; - } + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); - // Otherwise in compare mode, allow a point AND the box stats to be labeled - // If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them. - if(closePtData) { - closeBoxData.push(closePtData); - return closeBoxData; + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } - return closeBoxData; -} + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; -function hoverOnBoxes(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var xa = pointData.xa; - var ya = pointData.ya; - var trace = cd[0].trace; - var t = cd[0].t; - var isViolin = trace.type === 'violin'; - var closeBoxData = []; + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. - var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos, - hoverPseudoDistance, spikePseudoDistance; + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - var boxDelta = t.bdPos; - var shiftPos = function(di) { return di.pos + t.bPos - pVal; }; + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - if(isViolin && trace.side !== 'both') { - if(trace.side === 'positive') { - dPos = function(di) { - var pos = shiftPos(di); - return _$fx_93.inbox(pos, pos + boxDelta, hoverPseudoDistance); - }; - } - if(trace.side === 'negative') { - dPos = function(di) { - var pos = shiftPos(di); - return _$fx_93.inbox(pos - boxDelta, pos, hoverPseudoDistance); - }; - } - } else { - dPos = function(di) { - var pos = shiftPos(di); - return _$fx_93.inbox(pos - boxDelta, pos + boxDelta, hoverPseudoDistance); - }; - } + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - var dVal; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - if(isViolin) { - dVal = function(di) { - return _$fx_93.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); - }; - } else { - dVal = function(di) { - return _$fx_93.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); - }; + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); } - if(trace.orientation === 'h') { - vVal = xval; - pVal = yval; - dx = dVal; - dy = dPos; - pLetter = 'y'; - pAxis = ya; - vLetter = 'x'; - vAxis = xa; - } else { - vVal = yval; - pVal = xval; - dx = dPos; - dy = dVal; - pLetter = 'x'; - pAxis = xa; - vLetter = 'y'; - vAxis = ya; + // common attributes for all subplots, overlays or not + + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_217.idSort); + + for(var i = 0; i < _$constants_219.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_219.traceLayerClasses[i]); + } } - // if two boxes are overlaying, let the narrowest one win - var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0]))); - hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; - spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_93.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_93.getClosest(cd, distfn, pointData); + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - // skip the rest (for this trace) if we didn't find a close point - // and create the item(s) in closedata for this point - if(pointData.index === false) return []; +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - var di = cd[pointData.index]; - var lc = trace.line.color; - var mc = (trace.marker || {}).color; + var overlayIdsToRemove = {}; - if(_$color_51.opacity(lc) && trace.line.width) pointData.color = lc; - else if(_$color_51.opacity(mc) && trace.boxpoints) pointData.color = mc; - else pointData.color = trace.fillcolor; + layers.each(function(subplotId) { + var plotgroup = _$d3_15.select(this); - pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - t.bdPos, true); - pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + t.bdPos, true); + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - _$axes_213.tickText(pAxis, pAxis.c2l(di.pos), 'hover').text; - pointData[pLetter + 'LabelVal'] = di.pos; + overlayIdsToRemove[subplotId] = true; - var spikePosAttr = pLetter + 'Spike'; - pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; - pointData[spikePosAttr] = pAxis.c2p(di.pos, true); + // do not remove individual axis s here + // as other subplots may need them + }); - // box plots: each "point" gets many labels - var usedVals = {}; - var attrs = ['med', 'min', 'q1', 'q3', 'max']; + // must remove overlaid subplot trace layers 'manually' - if(trace.boxmean || (trace.meanline || {}).visible) { - attrs.push('mean'); - } - if(trace.boxpoints || trace.points) { - attrs.push('lf', 'uf'); - } - - for(var i = 0; i < attrs.length; i++) { - var attr = attrs[i]; - - if(!(attr in di) || (di[attr] in usedVals)) continue; - usedVals[di[attr]] = true; + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); - // copy out to a new object for each value to label - var val = di[attr]; - var valPx = vAxis.c2p(val, true); - var pointData2 = _$lib_171.extendFlat({}, pointData); + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx; - pointData2[vLetter + 'LabelVal'] = val; - pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_213.hoverLabelText(vAxis, val); + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; - if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') { - pointData2[vLetter + 'err'] = di.sd; + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } } - // only keep name and spikes on the first item (median) - pointData.name = ''; - pointData.spikeDistance = undefined; - pointData[spikePosAttr] = undefined; - - closeBoxData.push(pointData2); } +} - return closeBoxData; +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); } -function hoverOnPoints(pointData, xval, yval) { - var cd = pointData.cd; - var xa = pointData.xa; - var ya = pointData.ya; - var trace = cd[0].trace; - var xPx = xa.c2p(xval); - var yPx = ya.c2p(yval); - var closePtData; +_$cartesian_225.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_15.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - var dx = function(di) { - var rad = Math.max(3, di.mrc || 0); - return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad); - }; - var dy = function(di) { - var rad = Math.max(3, di.mrc || 0); - return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad); - }; - var distfn = _$fx_93.quadrature(dx, dy); + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); - // show one point per trace - var ijClosest = false; - var di, pt; + image.attr({ + xmlns: _$xmlns_namespaces_156.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); + } - for(var i = 0; i < cd.length; i++) { - di = cd[i]; + canvases.each(canvasToImage); +}; - for(var j = 0; j < (di.pts || []).length; j++) { - pt = di.pts[j]; +_$cartesian_225.updateFx = _$graph_interact_223.updateFx; - var newDistance = distfn(pt); - if(newDistance <= pointData.distance) { - pointData.distance = newDistance; - ijClosest = [i, j]; - } - } - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!ijClosest) return false; - di = cd[ijClosest[0]]; - pt = di.pts[ijClosest[1]]; +'use strict'; - var xc = xa.c2p(pt.x, true); - var yc = ya.c2p(pt.y, true); - var rad = pt.mrc || 1; +var mergeArray = _$lib_172.mergeArray; - closePtData = _$lib_171.extendFlat({}, pointData, { - // corresponds to index in x/y input data array - index: pt.i, - color: (trace.marker || {}).color, - name: trace.name, - x0: xc - rad, - x1: xc + rad, - xLabelVal: pt.x, - y0: yc - rad, - y1: yc + rad, - yLabelVal: pt.y, - spikeDistance: pointData.distance - }); - var pLetter = trace.orientation === 'h' ? 'y' : 'x'; - var pa = trace.orientation === 'h' ? ya : xa; - closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true); - _$fillHoverText_376(pt, trace, closePtData); - return closePtData; -} +// arrayOk attributes, merge them into calcdata array +var _$arraysToCalcdata_271 = function arraysToCalcdata(cd, trace) { + for(var i = 0; i < cd.length; i++) cd[i].i = i; -var _$hover_287 = { - hoverPoints: hoverPoints, - hoverOnBoxes: hoverOnBoxes, - hoverOnPoints: hoverOnPoints + mergeArray(trace.text, cd, 'tx'); + mergeArray(trace.hovertext, cd, 'htx'); + + var marker = trace.marker; + if(marker) { + mergeArray(marker.opacity, cd, 'mo'); + mergeArray(marker.color, cd, 'mc'); + + var markerLine = marker.line; + if(markerLine) { + mergeArray(markerLine.color, cd, 'mlc'); + mergeArray(markerLine.width, cd, 'mlw'); + } + } }; /** @@ -37167,33 +37447,162 @@ var _$hover_287 = { 'use strict'; +/* removed: var _$attributes_369 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_59 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -var _$layout_attributes_289 = { - boxmode: { +var __extendFlat_272 = _$extend_166.extendFlat; + +var textFontAttrs = _$font_attributes_240({ + editType: 'calc', + arrayOk: true, + +}); + +var __scatterMarkerAttrs_272 = _$attributes_369.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_272.line; + +var markerLineWidth = __extendFlat_272({}, + scatterMarkerLineAttrs.width, { dflt: 0 }); + +var markerLine = __extendFlat_272({ + width: markerLineWidth, + editType: 'calc' +}, _$makeColorScaleAttributes_59('marker.line')); + +var marker = __extendFlat_272({ + line: markerLine, + editType: 'calc' +}, _$makeColorScaleAttributes_59('marker'), { + showscale: __scatterMarkerAttrs_272.showscale, + colorbar: _$attributes_52, + opacity: { + valType: 'number', + arrayOk: true, + dflt: 1, + min: 0, + max: 1, + + editType: 'style', + + } +}); + +var _$attributes_272 = { + x: _$attributes_369.x, + x0: _$attributes_369.x0, + dx: _$attributes_369.dx, + y: _$attributes_369.y, + y0: _$attributes_369.y0, + dy: _$attributes_369.dy, + + text: _$attributes_369.text, + hovertext: _$attributes_369.hovertext, + + textposition: { valType: 'enumerated', - values: ['group', 'overlay'], - dflt: 'overlay', + values: ['inside', 'outside', 'auto', 'none'], + dflt: 'none', + arrayOk: true, editType: 'calc', }, - boxgap: { + + textfont: __extendFlat_272({}, textFontAttrs, { + + }), + + insidetextfont: __extendFlat_272({}, textFontAttrs, { + + }), + + outsidetextfont: __extendFlat_272({}, textFontAttrs, { + + }), + + constraintext: { + valType: 'enumerated', + values: ['inside', 'outside', 'both', 'none'], + + dflt: 'both', + editType: 'calc', + + }, + + cliponaxis: __extendFlat_272({}, _$attributes_369.cliponaxis, { + + }), + + orientation: { + valType: 'enumerated', + + values: ['v', 'h'], + editType: 'calc+clearAxisTypes', + + }, + + base: { + valType: 'any', + dflt: null, + arrayOk: true, + + editType: 'calc', + + }, + + offset: { valType: 'number', - min: 0, - max: 1, - dflt: 0.3, + dflt: null, + arrayOk: true, editType: 'calc', }, - boxgroupgap: { + + width: { valType: 'number', + dflt: null, min: 0, - max: 1, - dflt: 0.3, + arrayOk: true, editType: 'calc', + }, + + marker: marker, + + selected: { + marker: { + opacity: _$attributes_369.selected.marker.opacity, + color: _$attributes_369.selected.marker.color, + editType: 'style' + }, + textfont: _$attributes_369.selected.textfont, + editType: 'style' + }, + unselected: { + marker: { + opacity: _$attributes_369.unselected.marker.opacity, + color: _$attributes_369.unselected.marker.color, + editType: 'style' + }, + textfont: _$attributes_369.unselected.textfont, + editType: 'style' + }, + + r: _$attributes_369.r, + t: _$attributes_369.t, + + _deprecated: { + bardir: { + valType: 'enumerated', + + editType: 'calc', + values: ['v', 'h'], + + } } }; @@ -37207,34 +37616,12 @@ var _$layout_attributes_289 = { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$layout_attributes_289 = require('./layout_attributes'); */; - -function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { - var hasTraceType; - for(var i = 0; i < fullData.length; i++) { - if(fullData[i].type === traceType) { - hasTraceType = true; - break; - } - } - if(!hasTraceType) return; - - coerce(traceType + 'mode'); - coerce(traceType + 'gap'); - coerce(traceType + 'groupgap'); -} +/* removed: var _$lib_172 = require('../../lib'); */; -function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_289, attr, dflt); +var _$calcSelection_371 = function calcSelection(cd, trace) { + if(_$lib_172.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_172.tagSelected(cd, trace); } - _supply(layoutIn, layoutOut, fullData, coerce, 'box'); -} - -var _$layout_defaults_290 = { - supplyLayoutDefaults: supplyLayoutDefaults, - _supply: _supply }; /** @@ -37245,313 +37632,248 @@ var _$layout_defaults_290 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_273 = _$lib_172.isArrayOrTypedArray; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_58 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_271 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_371 = require('../scatter/calc_selection'); */; -// constants for dynamic jitter (ie less jitter for sparser points) -var JITTERCOUNT = 5; // points either side of this to include -var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense" +var _$calc_273 = function calc(gd, trace) { + // depending on bar direction, set position and size axes + // and data ranges + // note: this logic for choosing orientation is + // duplicated in graph_obj->setstyles -function plot(gd, plotinfo, cdbox) { - var fullLayout = gd._fullLayout; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + var xa = _$axes_214.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_214.getFromId(gd, trace.yaxis || 'y'), + orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), + sa, pos, size, i, scalendar; - var boxtraces = plotinfo.plot.select('.boxlayer') - .selectAll('g.trace.boxes') - .data(cdbox) - .enter().append('g') - .attr('class', 'trace boxes'); + if(orientation === 'h') { + sa = xa; + size = xa.makeCalcdata(trace, 'x'); + pos = ya.makeCalcdata(trace, 'y'); - boxtraces.each(function(d) { - var cd0 = d[0]; - var t = cd0.t; - var trace = cd0.trace; - var sel = cd0.node3 = _$d3_15.select(this); - var numBoxes = fullLayout._numBoxes; + // 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. + scalendar = trace.xcalendar; + } + else { + sa = ya; + size = ya.makeCalcdata(trace, 'y'); + pos = xa.makeCalcdata(trace, 'x'); + scalendar = trace.ycalendar; + } - var group = (fullLayout.boxmode === 'group' && numBoxes > 1); - // box half width - var bdPos = t.dPos * (1 - fullLayout.boxgap) * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); - // box center offset - var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * (1 - fullLayout.boxgap) : 0; - // whisker width - var wdPos = bdPos * trace.whiskerwidth; + // create the "calculated data" to plot + var serieslen = Math.min(pos.length, size.length); + var cd = new Array(serieslen); - if(trace.visible !== true || t.empty) { - _$d3_15.select(this).remove(); - return; + // set position and size + for(i = 0; i < serieslen; i++) { + cd[i] = { p: pos[i], s: size[i] }; + + if(trace.ids) { + cd[i].id = String(trace.ids[i]); } + } - var posAxis, valAxis; + // set base + var base = trace.base, + b; - if(trace.orientation === 'h') { - posAxis = ya; - valAxis = xa; - } else { - posAxis = xa; - valAxis = ya; + if(__isArrayOrTypedArray_273(base)) { + for(i = 0; i < Math.min(base.length, cd.length); i++) { + b = sa.d2c(base[i], 0, scalendar); + if(_$fastIsnumeric_18(b)) { + cd[i].b = +b; + cd[i].hasB = 1; + } + else cd[i].b = 0; + } + for(; i < cd.length; i++) { + cd[i].b = 0; + } + } + else { + b = sa.d2c(base, 0, scalendar); + var hasBase = _$fastIsnumeric_18(b); + b = hasBase ? b : 0; + for(i = 0; i < cd.length; i++) { + cd[i].b = b; + if(hasBase) cd[i].hasB = 1; } + } - // save the box size and box position for use by hover - t.bPos = bPos; - t.bdPos = bdPos; - t.wdPos = wdPos; + // auto-z and autocolorscale if applicable + if(_$hasColorscale_65(trace, 'marker')) { + _$calc_58(trace, trace.marker.color, 'marker', 'c'); + } + if(_$hasColorscale_65(trace, 'marker.line')) { + _$calc_58(trace, trace.marker.line.color, 'marker.line', 'c'); + } - // boxes and whiskers - plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, t); + _$arraysToCalcdata_271(cd, trace); + _$calcSelection_371(cd, trace); - // draw points, if desired - if(trace.boxpoints) { - plotPoints(sel, {x: xa, y: ya}, trace, t); - } + return cd; +}; - // draw mean (and stdev diamond) if desired - if(trace.boxmean) { - plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, t); - } - }); -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function plotBoxAndWhiskers(sel, axes, trace, t) { - var posAxis = axes.pos; - var valAxis = axes.val; - var bPos = t.bPos; - var wdPos = t.wdPos || 0; - var bPosPxOffset = t.bPosPxOffset || 0; - var whiskerWidth = trace.whiskerwidth || 0; - var notched = trace.notched || false; - var nw = notched ? 1 - 2 * trace.notchwidth : 1; - // to support for one-sided box - var bdPos0; - var bdPos1; - if(Array.isArray(t.bdPos)) { - bdPos0 = t.bdPos[0]; - bdPos1 = t.bdPos[1]; - } else { - bdPos0 = t.bdPos; - bdPos1 = t.bdPos; +'use strict'; + +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; + +var _$handleStyleDefaults_284 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { + coerce('marker.color', defaultColor); + + if(_$hasColorscale_65(traceIn, 'marker')) { + _$colorScaleDefaults_61( + traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} + ); } - sel.selectAll('path.box') - .data(_$lib_171.identity) - .enter().append('path') - .style('vector-effect', 'non-scaling-stroke') - .attr('class', 'box') - .each(function(d) { - var pos = d.pos; - var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset; - var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset; - var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset; - var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset; - var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset; - var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset; - var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset; - var q1 = valAxis.c2p(d.q1, true); - var q3 = valAxis.c2p(d.q3, true); - // make sure median isn't identical to either of the - // quartiles, so we can see it - var m = _$lib_171.constrain( - valAxis.c2p(d.med, true), - Math.min(q1, q3) + 1, Math.max(q1, q3) - 1 - ); - var lf = valAxis.c2p(trace.boxpoints === false ? d.min : d.lf, true); - var uf = valAxis.c2p(trace.boxpoints === false ? d.max : d.uf, true); - var ln = valAxis.c2p(d.ln, true); - var un = valAxis.c2p(d.un, true); + coerce('marker.line.color', _$color_51.defaultLine); - if(trace.orientation === 'h') { - _$d3_15.select(this).attr('d', - 'M' + m + ',' + posm0 + 'V' + posm1 + // median line - 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge - (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge - 'H' + q3 + // end of the top edge - 'V' + pos0 + // right edge - (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge - 'Z' + // end of the box - 'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers - ((whiskerWidth === 0) ? '' : // whisker caps - 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1)); - } else { - _$d3_15.select(this).attr('d', - 'M' + posm0 + ',' + m + 'H' + posm1 + // median line - 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box - (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge - 'V' + q3 + // end of the right edge - 'H' + pos0 + // bottom of the box - (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge - 'Z' + // end of the box - 'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers - ((whiskerWidth === 0) ? '' : // whisker caps - 'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1)); - } - }); -} + if(_$hasColorscale_65(traceIn, 'marker.line')) { + _$colorScaleDefaults_61( + traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} + ); + } -function plotPoints(sel, axes, trace, t) { - var xa = axes.x; - var ya = axes.y; - var bdPos = t.bdPos; - var bPos = t.bPos; + coerce('marker.line.width'); + coerce('marker.opacity'); + coerce('selected.marker.color'); + coerce('unselected.marker.color'); +}; - // to support violin points - var mode = trace.boxpoints || trace.points; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // repeatable pseudo-random number generator - _$lib_171.seedPseudoRandom(); - sel.selectAll('g.points') - // since box plot points get an extra level of nesting, each - // box needs the trace styling info - .data(function(d) { - d.forEach(function(v) { - v.t = t; - v.trace = trace; - }); - return d; - }) - .enter().append('g') - .attr('class', 'points') - .selectAll('path') - .data(function(d) { - var i; +'use strict'; - var pts = mode === 'all' ? - d.pts : - d.pts.filter(function(pt) { return (pt.v < d.lf || pt.v > d.uf); }); +/* removed: var _$registry_262 = require('../../registry'); */; - // normally use IQR, but if this is 0 or too small, use max-min - var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1); - var minSpread = typicalSpread * 1e-9; - var spreadLimit = typicalSpread * JITTERSPREAD; - var jitterFactors = []; - var maxJitterFactor = 0; - var newJitter; - // dynamic jitter - if(trace.jitter) { - if(typicalSpread === 0) { - // edge case of no spread at all: fall back to max jitter - maxJitterFactor = 1; - jitterFactors = new Array(pts.length); - for(i = 0; i < pts.length; i++) { - jitterFactors[i] = 1; - } - } else { - for(i = 0; i < pts.length; i++) { - var i0 = Math.max(0, i - JITTERCOUNT); - var pmin = pts[i0].v; - var i1 = Math.min(pts.length - 1, i + JITTERCOUNT); - var pmax = pts[i1].v; +var _$handleXYDefaults_393 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { + var len, + x = coerce('x'), + y = coerce('y'); - if(mode !== 'all') { - if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf); - else pmin = Math.max(pmin, d.uf); - } + var handleCalendarDefaults = _$registry_262.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); - var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0; - jitterFactor = _$lib_171.constrain(Math.abs(jitterFactor), 0, 1); + if(x) { + if(y) { + len = Math.min(x.length, y.length); + } + else { + len = x.length; + coerce('y0'); + coerce('dy'); + } + } + else { + if(!y) return 0; - jitterFactors.push(jitterFactor); - maxJitterFactor = Math.max(jitterFactor, maxJitterFactor); - } - } - newJitter = trace.jitter * 2 / maxJitterFactor; - } + len = traceOut.y.length; + coerce('x0'); + coerce('dx'); + } - // fills in 'x' and 'y' in calcdata 'pts' item - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var v = pt.v; + traceOut._length = len; - var jitterOffset = trace.jitter ? - (newJitter * jitterFactors[i] * (_$lib_171.pseudoRandom() - 0.5)) : - 0; + return len; +}; - var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(trace.orientation === 'h') { - pt.y = posPx; - pt.x = v; - } else { - pt.x = posPx; - pt.y = v; - } - // tag suspected outliers - if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) { - pt.so = true; - } - } +'use strict'; - return pts; - }) - .enter().append('path') - .classed('point', true) - .call(_$drawing_76.translatePoints, xa, ya); -} +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -function plotBoxMean(sel, axes, trace, t) { - var posAxis = axes.pos; - var valAxis = axes.val; - var bPos = t.bPos; - var bPosPxOffset = t.bPosPxOffset || 0; +/* removed: var _$handleXYDefaults_393 = require('../scatter/xy_defaults'); */; +/* removed: var _$handleStyleDefaults_284 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_272 = require('./attributes'); */; - // to support for one-sided box - var bdPos0; - var bdPos1; - if(Array.isArray(t.bdPos)) { - bdPos0 = t.bdPos[0]; - bdPos1 = t.bdPos[1]; - } else { - bdPos0 = t.bdPos; - bdPos1 = t.bdPos; +var _$supplyDefaults_274 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_172.coerce(traceIn, traceOut, _$attributes_272, attr, dflt); } - sel.selectAll('path.mean') - .data(_$lib_171.identity) - .enter().append('path') - .attr('class', 'mean') - .style({ - fill: 'none', - 'vector-effect': 'non-scaling-stroke' - }) - .each(function(d) { - var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset; - var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset; - var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset; - var m = valAxis.c2p(d.mean, true); - var sl = valAxis.c2p(d.mean - d.sd, true); - var sh = valAxis.c2p(d.mean + d.sd, true); + var coerceFont = _$lib_172.coerceFont; - if(trace.orientation === 'h') { - _$d3_15.select(this).attr('d', - 'M' + m + ',' + pos0 + 'V' + pos1 + - (trace.boxmean === 'sd' ? - 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : - '') - ); - } else { - _$d3_15.select(this).attr('d', - 'M' + pos0 + ',' + m + 'H' + pos1 + - (trace.boxmean === 'sd' ? - 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : - '') - ); - } - }); -} + var len = _$handleXYDefaults_393(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; + } -var _$plot_291 = { - plot: plot, - plotBoxAndWhiskers: plotBoxAndWhiskers, - plotPoints: plotPoints, - plotBoxMean: plotBoxMean + coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); + coerce('base'); + coerce('offset'); + coerce('width'); + + coerce('text'); + coerce('hovertext'); + + var textPosition = coerce('textposition'); + + var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', + hasInside = hasBoth || textPosition === 'inside', + hasOutside = hasBoth || textPosition === 'outside'; + + if(hasInside || hasOutside) { + var textFont = coerceFont(coerce, 'textfont', layout.font); + if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); + if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); + coerce('constraintext'); + coerce('selected.textfont.color'); + coerce('unselected.textfont.color'); + coerce('cliponaxis'); + } + + _$handleStyleDefaults_284(traceIn, traceOut, coerce, defaultColor, layout); + + // override defaultColor for error bars with defaultLine + var errorBarsSupplyDefaults = _$registry_262.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_51.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_51.defaultLine, {axis: 'x', inherit: 'y'}); + + _$lib_172.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -37564,44 +37886,38 @@ var _$plot_291 = { 'use strict'; -var _$selectPoints_292 = function selectPoints(searchInfo, polygon) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var i, j; +/* removed: var _$lib_172 = require('../../lib'); */; - if(polygon === 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); +/** Fill hover 'pointData' container with 'correct' hover text value + * + * - If trace hoverinfo contains a 'text' flag and hovertext is not set, + * the text elements will be seen in the hover labels. + * + * - If trace hoverinfo contains a 'text' flag and hovertext is set, + * hovertext takes precedence over text + * i.e. the hoverinfo elements will be seen in the hover labels + * + * @param {object} calcPt + * @param {object} trace + * @param {object || array} contOut (mutated here) + */ +var _$fillHoverText_377 = function fillHoverText(calcPt, trace, contOut) { + var fill = Array.isArray(contOut) ? + function(v) { contOut.push(v); } : + function(v) { contOut.text = v; }; - if(polygon.contains([x, y])) { - selection.push({ - pointNumber: pt.i, - x: xa.c2d(pt.x), - y: ya.c2d(pt.y) - }); - pt.selected = 1; - } else { - pt.selected = 0; - } - } - } - } + var htx = _$lib_172.extractOption(calcPt, trace, 'htx', 'hovertext'); + if(isValid(htx)) return fill(htx); - return selection; + var tx = _$lib_172.extractOption(calcPt, trace, 'tx', 'text'); + if(isValid(tx)) return fill(tx); }; +// accept all truthy values and 0 (which gets cast to '0' in the hover labels) +function isValid(v) { + return v || v === 0; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -37610,148 +37926,143 @@ var _$selectPoints_292 = function selectPoints(searchInfo, polygon) { * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +'use strict'; -var orientations = ['v', 'h']; +/* removed: var _$fx_93 = require('../../components/fx'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$fillHoverText_377 = require('../scatter/fill_hover_text'); */; -function setPositions(gd, plotinfo) { - var calcdata = gd.calcdata; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; +var _$hoverPoints_275 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var trace = cd[0].trace; + var t = cd[0].t; + var isClosest = (hovermode === 'closest'); + var maxHoverDistance = pointData.maxHoverDistance; + var maxSpikeDistance = pointData.maxSpikeDistance; - for(var i = 0; i < orientations.length; i++) { - var orientation = orientations[i]; - var posAxis = orientation === 'h' ? ya : xa; - var boxList = []; - var minPad = 0; - var maxPad = 0; + var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; - // make list of boxes - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j]; - var t = cd[0].t; - var trace = cd[0].trace; + function thisBarMinPos(di) { return di[posLetter] - di.w / 2; } + function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; } - if(trace.visible === true && trace.type === 'box' && - !t.empty && - trace.orientation === orientation && - trace.xaxis === xa._id && - trace.yaxis === ya._id - ) { - boxList.push(j); + var minPos = isClosest ? + thisBarMinPos : + function(di) { + /* + * In compare mode, accept a bar if you're on it *or* its group. + * Nearly always it's the group that matters, but in case the bar + * was explicitly set wider than its group we'd better accept the + * whole bar. + * + * use `bardelta` instead of `bargroupwidth` so we accept hover + * in the gap. That way hover doesn't flash on and off as you + * mouse over the plot in compare modes. + * In 'closest' mode though the flashing seems inevitable, + * without far more complex logic + */ + return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2); + }; - if(trace.boxpoints !== false) { - minPad = Math.max(minPad, trace.jitter - trace.pointpos - 1); - maxPad = Math.max(maxPad, trace.jitter + trace.pointpos - 1); - } - } - } + var maxPos = isClosest ? + thisBarMaxPos : + function(di) { + return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2); + }; - setPositionOffset('box', gd, boxList, posAxis, [minPad, maxPad]); + function _positionFn(_minPos, _maxPos) { + // add a little to the pseudo-distance for wider bars, so that like scatter, + // if you are over two overlapping bars, the narrower one wins. + return _$fx_93.inbox(_minPos - posVal, _maxPos - posVal, + maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); } -} - -function setPositionOffset(traceType, gd, boxList, posAxis, pad) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; - var pointList = []; - - // N.B. reused in violin - var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes'; - - var i, j, calcTrace; - // make list of box points - for(i = 0; i < boxList.length; i++) { - calcTrace = calcdata[boxList[i]]; - for(j = 0; j < calcTrace.length; j++) { - pointList.push(calcTrace[j].pos); - } + function positionFn(di) { + return _positionFn(minPos(di), maxPos(di)); } - if(!pointList.length) return; - - // box plots - update dPos based on multiple traces - // and then use for posAxis autorange - var boxdv = _$lib_171.distinctVals(pointList); - var dPos = boxdv.minDiff / 2; - - // if there's no duplication of x points, - // disable 'group' mode by setting counter to 1 - if(pointList.length === boxdv.vals.length) { - fullLayout[numKey] = 1; + function thisBarPositionFn(di) { + return _positionFn(thisBarMinPos(di), thisBarMaxPos(di)); } - // check for forced minimum dtick - _$axes_213.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); + function sizeFn(di) { + // add a gradient so hovering near the end of a + // bar makes it a little closer match + return _$fx_93.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, + maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); + } - // set the width of all boxes - for(i = 0; i < boxList.length; i++) { - calcTrace = calcdata[boxList[i]]; - calcTrace[0].t.dPos = dPos; + if(trace.orientation === 'h') { + posVal = yval; + sizeVal = xval; + posLetter = 'y'; + sizeLetter = 'x'; + dx = sizeFn; + dy = positionFn; + } + else { + posVal = xval; + sizeVal = yval; + posLetter = 'x'; + sizeLetter = 'y'; + dy = sizeFn; + dx = positionFn; } - var gap = fullLayout[traceType + 'gap']; - var groupgap = fullLayout[traceType + 'groupgap']; - var padfactor = (1 - gap) * (1 - groupgap) * dPos / fullLayout[numKey]; + var pa = pointData[posLetter + 'a']; + var sa = pointData[sizeLetter + 'a']; - // autoscale the x axis - including space for points if they're off the side - // TODO: this will overdo it if the outermost boxes don't have - // their points as far out as the other boxes - _$axes_213.expand(posAxis, boxdv.vals, { - vpadminus: dPos + pad[0] * padfactor, - vpadplus: dPos + pad[1] * padfactor - }); -} + pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); -var _$set_positions_293 = { - setPositions: setPositions, - setPositionOffset: setPositionOffset -}; + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_93.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_93.getClosest(cd, distfn, pointData); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // skip the rest (for this trace) if we didn't find a close point + if(pointData.index === false) return; -'use strict'; + // if we get here and we're not in 'closest' mode, push min/max pos back + // onto the group - even though that means occasionally the mouse will be + // over the hover label. + if(!isClosest) { + minPos = function(di) { + return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2); + }; + maxPos = function(di) { + return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2); + }; + } -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$drawing_76 = require('../../components/drawing'); */; + // the closest data point + var index = pointData.index; + var di = cd[index]; + var mc = di.mcc || trace.marker.color; + var mlc = di.mlcc || trace.marker.line.color; + var mlw = di.mlw || trace.marker.line.width; -var _$style_294 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_15.select(gd).selectAll('g.trace.boxes'); + if(_$color_51.opacity(mc)) pointData.color = mc; + else if(_$color_51.opacity(mlc) && mlw) pointData.color = mlc; - s.style('opacity', function(d) { return d[0].trace.opacity; }); + var size = (trace.base) ? di.b + di.s : di.s; + pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); + pointData[sizeLetter + 'LabelVal'] = size; - s.each(function(d) { - var el = _$d3_15.select(this); - var trace = d[0].trace; - var lineWidth = trace.line.width; + var extent = t.extents[t.extents.round(di.p)]; + pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true); + pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true); + pointData[posLetter + 'LabelVal'] = di.p; - el.selectAll('path.box') - .style('stroke-width', lineWidth + 'px') - .call(_$color_51.stroke, trace.line.color) - .call(_$color_51.fill, trace.fillcolor); + // spikelines always want "closest" distance regardless of hovermode + pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance; + // they also want to point to the data value, regardless of where the label goes + // in case of bars shifted within groups + pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); - el.selectAll('path.mean') - .style({ - 'stroke-width': lineWidth, - 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' - }) - .call(_$color_51.stroke, trace.line.color); + _$fillHoverText_377(di, trace, pointData); + _$registry_262.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); - var pts = el.selectAll('path.point'); - _$drawing_76.pointStyle(pts, trace, gd); - _$drawing_76.selectedPointStyle(pts, trace); - }); + return [pointData]; }; /** @@ -37764,29 +38075,43 @@ var _$style_294 = function style(gd, cd) { 'use strict'; -var Box = {}; - -Box.attributes = _$attributes_284; -Box.layoutAttributes = _$layout_attributes_289; -Box.supplyDefaults = _$defaults_286.supplyDefaults; -Box.supplyLayoutDefaults = _$layout_defaults_290.supplyLayoutDefaults; -Box.calc = _$calc_285; -Box.setPositions = _$set_positions_293.setPositions; -Box.plot = _$plot_291.plot; -Box.style = _$style_294; -Box.hoverPoints = _$hover_287.hoverPoints; -Box.selectPoints = _$selectPoints_292; -Box.moduleType = 'trace'; -Box.name = 'box'; -Box.basePlotModule = _$cartesian_224; -Box.categories = ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend']; -Box.meta = { - +var _$layout_attributes_277 = { + 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', + + } }; -var _$Box_288 = Box; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -37795,145 +38120,54 @@ var _$Box_288 = Box; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$box_4 = _$Box_288; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +/* removed: var _$layout_attributes_277 = require('./layout_attributes'); */; -'use strict'; -var _$filter_ops_152 = { - COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='], - COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], - INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], - SET_OPS: ['{}', '}{'], - CONSTRAINT_REDUCTION: { - // for contour constraints, open/closed endpoints are equivalent - '=': '=', +var _$layout_defaults_278 = function(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_277, attr, dflt); + } - '<': '<', - '<=': '<', + var hasBars = false, + shouldBeGapless = false, + gappedAnyway = false, + usedSubplots = {}; - '>': '>', - '>=': '>', + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if(_$registry_262.traceIs(trace, 'bar')) hasBars = true; + else continue; - '[]': '[]', - '()': '[]', - '[)': '[]', - '(]': '[]', + // if we have at least 2 grouped bar traces on the same subplot, + // we should default to a gap anyway, even if the data is histograms + if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') { + var subploti = trace.xaxis + trace.yaxis; + if(usedSubplots[subploti]) gappedAnyway = true; + usedSubplots[subploti] = true; + } - '][': '][', - ')(': '][', - '](': '][', - ')[': '][' + if(trace.visible && trace.type === 'histogram') { + var pa = _$axes_214.getFromId({_fullLayout: layoutOut}, + trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); + if(pa.type !== 'category') shouldBeGapless = true; + } } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_368 = require('../scatter/attributes'); */; -/* removed: var _$attributes_57 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -var __extendFlat_317 = _$extend_165.extendFlat; + if(!hasBars) return; -var _$attributes_317 = __extendFlat_317({}, { - z: { - valType: 'data_array', - editType: 'calc', - - }, - x: __extendFlat_317({}, _$attributes_368.x, {impliedEdits: {xtype: 'array'}}), - x0: __extendFlat_317({}, _$attributes_368.x0, {impliedEdits: {xtype: 'scaled'}}), - dx: __extendFlat_317({}, _$attributes_368.dx, {impliedEdits: {xtype: 'scaled'}}), - y: __extendFlat_317({}, _$attributes_368.y, {impliedEdits: {ytype: 'array'}}), - y0: __extendFlat_317({}, _$attributes_368.y0, {impliedEdits: {ytype: 'scaled'}}), - dy: __extendFlat_317({}, _$attributes_368.dy, {impliedEdits: {ytype: 'scaled'}}), + var mode = coerce('barmode'); + if(mode !== 'overlay') coerce('barnorm'); - text: { - 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', - - }, - connectgaps: { - valType: 'boolean', - dflt: false, - - 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', - - }, -}, - _$attributes_57, - { autocolorscale: __extendFlat_317({}, _$attributes_57.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_52 } -); + coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2); + coerce('bargroupgap'); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -37943,526 +38177,539 @@ var _$attributes_317 = __extendFlat_317({}, { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$attributes_317 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_368 = require('../scatter/attributes'); */; -/* removed: var _$attributes_57 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -var __dash_295 = _$attributes_75.dash; -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -var __extendFlat_295 = _$extend_165.extendFlat; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$filter_ops_152 = require('../../constants/filter_ops'); */; -var COMPARISON_OPS2 = _$filter_ops_152.COMPARISON_OPS2; -var INTERVAL_OPS = _$filter_ops_152.INTERVAL_OPS; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; -var scatterLineAttrs = _$attributes_368.line; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -var _$attributes_295 = __extendFlat_295({ - z: _$attributes_317.z, - x: _$attributes_317.x, - x0: _$attributes_317.x0, - dx: _$attributes_317.dx, - y: _$attributes_317.y, - y0: _$attributes_317.y0, - dy: _$attributes_317.dy, - text: _$attributes_317.text, - transpose: _$attributes_317.transpose, - xtype: _$attributes_317.xtype, - ytype: _$attributes_317.ytype, - zhoverformat: _$attributes_317.zhoverformat, +var __dummy_279$0 = 0, + attributeText = _$attributes_272.text, + attributeTextPosition = _$attributes_272.textposition, + attributeTextFont = _$attributes_272.textfont, + attributeInsideTextFont = _$attributes_272.insidetextfont, + attributeOutsideTextFont = _$attributes_272.outsidetextfont; - connectgaps: _$attributes_317.connectgaps, +// padding in pixels around text +var TEXTPAD = 3; - fillcolor: { - valType: 'color', - - editType: 'calc', - - }, +var _$plot_279 = function plot(gd, plotinfo, cdbar) { + var xa = plotinfo.xaxis, + ya = plotinfo.yaxis, + fullLayout = gd._fullLayout; - 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', - - }, + var bartraces = plotinfo.plot.select('.barlayer') + .selectAll('g.trace.bars') + .data(cdbar); - 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: _$font_attributes_240({ - 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} - }, + bartraces.enter().append('g') + .attr('class', 'trace bars'); - line: { - color: __extendFlat_295({}, scatterLineAttrs.color, { - editType: 'style+colorbars', - - }), - width: __extendFlat_295({}, scatterLineAttrs.width, { - editType: 'style+colorbars' - }), - dash: __dash_295, - smoothing: __extendFlat_295({}, scatterLineAttrs.smoothing, { - - }), - editType: 'plot' + if(!plotinfo.isRangePlot) { + bartraces.each(function(d) { + d[0].node3 = _$d3_15.select(this); + }); } -}, - _$attributes_57, { - autocolorscale: __extendFlat_295({}, _$attributes_57.autocolorscale, {dflt: false}), - zmin: __extendFlat_295({}, _$attributes_57.zmin, {editType: 'calc'}), - zmax: __extendFlat_295({}, _$attributes_57.zmax, {editType: 'calc'}) - }, - { colorbar: _$attributes_52 } -); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + bartraces.append('g') + .attr('class', 'points') + .each(function(d) { + var sel = _$d3_15.select(this); + var t = d[0].t; + var trace = d[0].trace; + var poffset = t.poffset; + var poffsetIsArray = Array.isArray(poffset); + sel.selectAll('g.point') + .data(_$lib_172.identity) + .enter().append('g').classed('point', true) + .each(function(di, i) { + // now display the bar + // clipped xf/yf (2nd arg true): non-positive + // log values go off-screen by plotwidth + // so you see them continue if you drag the plot + var p0 = di.p + ((poffsetIsArray) ? poffset[i] : poffset), + p1 = p0 + di.w, + s0 = di.b, + s1 = s0 + di.s; -'use strict'; + var x0, x1, y0, y1; + if(trace.orientation === 'h') { + y0 = ya.c2p(p0, true); + y1 = ya.c2p(p1, true); + x0 = xa.c2p(s0, true); + x1 = xa.c2p(s1, true); -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -var __extendFlat_314 = _$lib_171.extendFlat; + // for selections + di.ct = [x1, (y0 + y1) / 2]; + } + else { + x0 = xa.c2p(p0, true); + x1 = xa.c2p(p1, true); + y0 = ya.c2p(s0, true); + y1 = ya.c2p(s1, true); + // for selections + di.ct = [(x0 + x1) / 2, y1]; + } -var _$setContours_314 = function setContours(trace) { - var contours = trace.contours; + if(!_$fastIsnumeric_18(x0) || !_$fastIsnumeric_18(x1) || + !_$fastIsnumeric_18(y0) || !_$fastIsnumeric_18(y1) || + x0 === x1 || y0 === y1) { + _$d3_15.select(this).remove(); + return; + } - // check if we need to auto-choose contour levels - if(trace.autocontour) { - var dummyAx = autoContours(trace.zmin, trace.zmax, trace.ncontours); + var lw = (di.mlw + 1 || trace.marker.line.width + 1 || + (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, + offset = _$d3_15.round((lw / 2) % 1, 2); - contours.size = dummyAx.dtick; + function roundWithLine(v) { + // if there are explicit gaps, don't round, + // it can make the gaps look crappy + return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? + _$d3_15.round(Math.round(v) - offset, 2) : v; + } - contours.start = _$axes_213.tickFirst(dummyAx); - dummyAx.range.reverse(); - contours.end = _$axes_213.tickFirst(dummyAx); + function expandToVisible(v, vc) { + // if it's not in danger of disappearing entirely, + // round more precisely + return Math.abs(v - vc) >= 2 ? roundWithLine(v) : + // but if it's very thin, expand it so it's + // necessarily visible, even if it might overlap + // its neighbor + (v > vc ? Math.ceil(v) : Math.floor(v)); + } - if(contours.start === trace.zmin) contours.start += contours.size; - if(contours.end === trace.zmax) contours.end -= contours.size; + if(!gd._context.staticPlot) { + // if bars are not fully opaque or they have a line + // around them, round to integer pixels, mainly for + // safari so we prevent overlaps from its expansive + // pixelation. if the bars ARE fully opaque and have + // no line, expand to a full pixel to make sure we + // can see them + var op = _$color_51.opacity(di.mc || trace.marker.color), + fixpx = (op < 1 || lw > 0.01) ? + roundWithLine : expandToVisible; + x0 = fixpx(x0, x1); + x1 = fixpx(x1, x0); + y0 = fixpx(y0, y1); + y1 = fixpx(y1, y0); + } - // if you set a small ncontours, *and* the ends are exactly on zmin/zmax - // there's an edge case where start > end now. Make sure there's at least - // one meaningful contour, put it midway between the crossed values - if(contours.start > contours.end) { - contours.start = contours.end = (contours.start + contours.end) / 2; - } + // append bar path and text + var bar = _$d3_15.select(this); - // copy auto-contour info back to the source data. - // previously we copied the whole contours object back, but that had - // other info (coloring, showlines) that should be left to supplyDefaults - if(!trace._input.contours) trace._input.contours = {}; - __extendFlat_314(trace._input.contours, { - start: contours.start, - end: contours.end, - size: contours.size - }); - trace._input.autocontour = true; - } - else if(contours.type !== 'constraint') { - // sanity checks on manually-supplied start/end/size - var start = contours.start, - end = contours.end, - inputContours = trace._input.contours; + bar.append('path') + .style('vector-effect', 'non-scaling-stroke') + .attr('d', + 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') + .call(_$drawing_76.setClipUrl, plotinfo.layerClipId); - if(start > end) { - contours.start = inputContours.start = end; - end = contours.end = inputContours.end = start; - start = contours.start; - } + appendBarText(gd, bar, d, i, x0, x1, y0, y1); - if(!(contours.size > 0)) { - var sizeOut; - if(start === end) sizeOut = 1; - else sizeOut = autoContours(start, end, trace.ncontours).dtick; + if(plotinfo.layerClipId) { + _$drawing_76.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); + } + }); + }); - inputContours.size = contours.size = sizeOut; - } - } + // error bars are on the top + _$registry_262.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); + + // lastly, clip points groups of `cliponaxis !== false` traces + // on `plotinfo._hasClipOnAxisFalse === true` subplots + bartraces.each(function(d) { + var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; + _$drawing_76.setClipUrl(_$d3_15.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + }); }; +function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { + var textPosition; -/* - * autoContours: make a dummy axis object with dtick we can use - * as contours.size, and if needed we can use Axes.tickFirst - * with this axis object to calculate the start and end too - * - * start: the value to start the contours at - * end: the value to end at (must be > start) - * ncontours: max number of contours to make, like roughDTick - * - * returns: an axis object - */ -function autoContours(start, end, ncontours) { - var dummyAx = { - type: 'linear', - range: [start, end] - }; + function appendTextNode(bar, text, textFont) { + var textSelection = bar.append('text') + .text(text) + .attr({ + 'class': 'bartext bartext-' + textPosition, + transform: '', + 'text-anchor': 'middle', + // prohibit tex interpretation until we can handle + // tex and regular text together + 'data-notex': 1 + }) + .call(_$drawing_76.font, textFont) + .call(_$svg_text_utils_193.convertToTspans, gd); - _$axes_213.autoTicks( - dummyAx, - (end - start) / (ncontours || 15) - ); + return textSelection; + } - return dummyAx; -} + // get trace attributes + var trace = calcTrace[0].trace, + orientation = trace.orientation; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 text = getText(trace, i); + if(!text) return; -'use strict'; + textPosition = getTextPosition(trace, i); + if(textPosition === 'none') return; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + var textFont = getTextFont(trace, i, gd._fullLayout.font), + insideTextFont = getInsideTextFont(trace, i, textFont), + outsideTextFont = getOutsideTextFont(trace, i, textFont); -var _$clean2dArray_319 = function clean2dArray(zOld, transpose) { - var rowlen, collen, getCollen, old2new, i, j; + // compute text position + var barmode = gd._fullLayout.barmode, + inStackMode = (barmode === 'stack'), + inRelativeMode = (barmode === 'relative'), + inStackOrRelativeMode = inStackMode || inRelativeMode, - function cleanZvalue(v) { - if(!_$fastIsnumeric_18(v)) return undefined; - return +v; - } + calcBar = calcTrace[i], + isOutmostBar = !inStackOrRelativeMode || calcBar._outmost, - if(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]; }; - } + barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD, // padding excluded + barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD, // padding excluded - var zNew = new Array(rowlen); + textSelection, + textBB, + textWidth, + textHeight; - for(i = 0; i < rowlen; i++) { - collen = getCollen(zOld, i); - zNew[i] = new Array(collen); - for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); + if(textPosition === 'outside') { + if(!isOutmostBar) textPosition = 'inside'; } - return zNew; -}; + if(textPosition === 'auto') { + if(isOutmostBar) { + // draw text using insideTextFont and check if it fits inside bar + textPosition = 'inside'; + textSelection = appendTextNode(bar, text, insideTextFont); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + textBB = _$drawing_76.bBox(textSelection.node()), + textWidth = textBB.width, + textHeight = textBB.height; + var textHasSize = (textWidth > 0 && textHeight > 0), + fitsInside = + (textWidth <= barWidth && textHeight <= barHeight), + fitsInsideIfRotated = + (textWidth <= barHeight && textHeight <= barWidth), + fitsInsideIfShrunk = (orientation === 'h') ? + (barWidth >= textWidth * (barHeight / textHeight)) : + (barHeight >= textHeight * (barWidth / textWidth)); + if(textHasSize && + (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) { + textPosition = 'inside'; + } + else { + textPosition = 'outside'; + textSelection.remove(); + textSelection = null; + } + } + else textPosition = 'inside'; + } -'use strict'; + if(!textSelection) { + textSelection = appendTextNode(bar, text, + (textPosition === 'outside') ? + outsideTextFont : insideTextFont); -/* removed: var _$lib_171 = require('../../lib'); */; -var __BADNUM_321 = _$numerical_154.BADNUM; + textBB = _$drawing_76.bBox(textSelection.node()), + textWidth = textBB.width, + textHeight = textBB.height; -var _$convertColumnData_321 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { - var1Name = var1Name || 'x'; - var2Name = var2Name || 'y'; - arrayVarNames = arrayVarNames || ['z']; + if(textWidth <= 0 || textHeight <= 0) { + textSelection.remove(); + return; + } + } - var col1 = trace[var1Name].slice(), - col2 = trace[var2Name].slice(), - textCol = trace.text, - colLen = Math.min(col1.length, col2.length), - hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), - col1Calendar = trace[var1Name + 'calendar'], - col2Calendar = trace[var2Name + 'calendar']; + // compute text transform + var transform, constrained; + if(textPosition === 'outside') { + constrained = trace.constraintext === 'both' || trace.constraintext === 'outside'; + transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, + orientation, constrained); + } + else { + constrained = trace.constraintext === 'both' || trace.constraintext === 'inside'; + transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, + orientation, constrained); + } - var i, j, arrayVar, newArray, arrayVarName; + textSelection.attr('transform', transform); +} - for(i = 0; i < arrayVarNames.length; i++) { - arrayVar = trace[arrayVarNames[i]]; - if(arrayVar) colLen = Math.min(colLen, arrayVar.length); +function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { + // compute text and target positions + var textWidth = textBB.width, + textHeight = textBB.height, + textX = (textBB.left + textBB.right) / 2, + textY = (textBB.top + textBB.bottom) / 2, + barWidth = Math.abs(x1 - x0), + barHeight = Math.abs(y1 - y0), + targetWidth, + targetHeight, + targetX, + targetY; + + // apply text padding + var textpad; + if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) { + textpad = TEXTPAD; + barWidth -= 2 * textpad; + barHeight -= 2 * textpad; } + else textpad = 0; - if(colLen < col1.length) col1 = col1.slice(0, colLen); - if(colLen < col2.length) col2 = col2.slice(0, colLen); + // compute rotation and scale + var rotate, + scale; - for(i = 0; i < colLen; i++) { - col1[i] = ax1.d2c(col1[i], 0, col1Calendar); - col2[i] = ax2.d2c(col2[i], 0, col2Calendar); + if(textWidth <= barWidth && textHeight <= barHeight) { + // no scale or rotation is required + rotate = false; + scale = 1; + } + else if(textWidth <= barHeight && textHeight <= barWidth) { + // only rotation is required + rotate = true; + scale = 1; + } + else if((textWidth < textHeight) === (barWidth < barHeight)) { + // only scale is required + rotate = false; + scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1; + } + else { + // both scale and rotation are required + rotate = true; + scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1; } - var col1dv = _$lib_171.distinctVals(col1), - col1vals = col1dv.vals, - col2dv = _$lib_171.distinctVals(col2), - col2vals = col2dv.vals, - newArrays = []; + if(rotate) rotate = 90; // rotate clockwise - for(i = 0; i < arrayVarNames.length; i++) { - newArrays[i] = _$lib_171.init2dArray(col2vals.length, col1vals.length); + // compute text and target positions + if(rotate) { + targetWidth = scale * textHeight; + targetHeight = scale * textWidth; + } + else { + targetWidth = scale * textWidth; + targetHeight = scale * textHeight; } - var i1, i2, text; - - if(hasColumnText) text = _$lib_171.init2dArray(col2vals.length, col1vals.length); + if(orientation === 'h') { + if(x1 < x0) { + // bar end is on the left hand side + targetX = x1 + textpad + targetWidth / 2; + targetY = (y0 + y1) / 2; + } + else { + targetX = x1 - textpad - targetWidth / 2; + targetY = (y0 + y1) / 2; + } + } + else { + if(y1 > y0) { + // bar end is on the bottom + targetX = (x0 + x1) / 2; + targetY = y1 - textpad - targetHeight / 2; + } + else { + targetX = (x0 + x1) / 2; + targetY = y1 + textpad + targetHeight / 2; + } + } - for(i = 0; i < colLen; i++) { - if(col1[i] !== __BADNUM_321 && col2[i] !== __BADNUM_321) { - i1 = _$lib_171.findBin(col1[i] + col1dv.minDiff / 2, col1vals); - i2 = _$lib_171.findBin(col2[i] + col2dv.minDiff / 2, col2vals); + return getTransform(textX, textY, targetX, targetY, scale, rotate); +} - for(j = 0; j < arrayVarNames.length; j++) { - arrayVarName = arrayVarNames[j]; - arrayVar = trace[arrayVarName]; - newArray = newArrays[j]; - newArray[i2][i1] = arrayVar[i]; - } +function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { + var barWidth = (orientation === 'h') ? + Math.abs(y1 - y0) : + Math.abs(x1 - x0), + textpad; - if(hasColumnText) text[i2][i1] = textCol[i]; - } + // Keep the padding so the text doesn't sit right against + // the bars, but don't factor it into barWidth + if(barWidth > 2 * TEXTPAD) { + textpad = TEXTPAD; } - // hack for Plotly.react - save the input arrays for diffing purposes - trace['_input_' + var1Name] = trace[var1Name]; - trace['_input_' + var2Name] = trace[var2Name]; - trace[var1Name] = col1vals; - trace[var2Name] = col2vals; - for(j = 0; j < arrayVarNames.length; j++) { - trace['_input_' + arrayVarNames[j]] = trace[arrayVarNames[j]]; - trace[arrayVarNames[j]] = newArrays[j]; + // compute rotation and scale + var scale = 1; + if(constrained) { + scale = (orientation === 'h') ? + Math.min(1, barWidth / textBB.height) : + Math.min(1, barWidth / textBB.width); } - if(hasColumnText) trace.text = text; -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // compute text and target positions + var textX = (textBB.left + textBB.right) / 2, + textY = (textBB.top + textBB.bottom) / 2, + targetWidth, + targetHeight, + targetX, + targetY; + targetWidth = scale * textBB.width; + targetHeight = scale * textBB.height; -'use strict'; + if(orientation === 'h') { + if(x1 < x0) { + // bar end is on the left hand side + targetX = x1 - textpad - targetWidth / 2; + targetY = (y0 + y1) / 2; + } + else { + targetX = x1 + textpad + targetWidth / 2; + targetY = (y0 + y1) / 2; + } + } + else { + if(y1 > y0) { + // bar end is on the bottom + targetX = (x0 + x1) / 2; + targetY = y1 + textpad + targetHeight / 2; + } + else { + targetX = (x0 + x1) / 2; + targetY = y1 - textpad - targetHeight / 2; + } + } -var _$maxRowLength_329 = function maxRowLength(z) { - var len = 0; + return getTransform(textX, textY, targetX, targetY, scale, false); +} - for(var i = 0; i < z.length; i++) { - len = Math.max(len, z[i].length); +function getTransform(textX, textY, targetX, targetY, scale, rotate) { + var transformScale, + transformRotate, + transformTranslate; + + if(scale < 1) transformScale = 'scale(' + scale + ') '; + else { + scale = 1; + transformScale = ''; } - return len; -}; + transformRotate = (rotate) ? + 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : ''; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // Note that scaling also affects the center of the text box + var translateX = (targetX - scale * textX), + translateY = (targetY - scale * textY); + transformTranslate = 'translate(' + translateX + ' ' + translateY + ')'; -'use strict'; + return transformTranslate + transformScale + transformRotate; +} -/* removed: var _$maxRowLength_329 = require('./max_row_length'); */; +function getText(trace, index) { + var value = getValue(trace.text, index); + return coerceString(attributeText, value); +} -/* 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 - */ -var _$findEmpties_323 = function findEmpties(z) { - var empties = [], - neighborHash = {}, - noNeighborList = [], - nextRow = z[0], - row = [], - blank = [0, 0, 0], - rowLength = _$maxRowLength_329(z), - prevRow, - i, - j, - thisPt, - p, - neighborCount, - newNeighborHash, - foundNewNeighbors; +function getTextPosition(trace, index) { + var value = getValue(trace.textposition, index); + return coerceEnumerated(attributeTextPosition, value); +} - 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); +function getTextFont(trace, index, defaultValue) { + return getFontValue( + attributeTextFont, trace.textfont, index, defaultValue); +} - 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++; +function getInsideTextFont(trace, index, defaultValue) { + return getFontValue( + attributeInsideTextFont, trace.insidetextfont, index, defaultValue); +} - // 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]; - } +function getOutsideTextFont(trace, index, defaultValue) { + return getFontValue( + attributeOutsideTextFont, trace.outsidetextfont, index, defaultValue); +} - empties.push([i, j, neighborCount]); - } - else noNeighborList.push([i, j]); - } - } +function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { + attributeValue = attributeValue || {}; + + var familyValue = getValue(attributeValue.family, index), + sizeValue = getValue(attributeValue.size, index), + colorValue = getValue(attributeValue.color, index); + + return { + family: coerceString( + attributeDefinition.family, familyValue, defaultValue.family), + size: coerceNumber( + attributeDefinition.size, sizeValue, defaultValue.size), + color: coerceColor( + attributeDefinition.color, colorValue, defaultValue.color) + }; +} + +function getValue(arrayOrScalar, index) { + var value; + if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar; + else if(index < arrayOrScalar.length) value = arrayOrScalar[index]; + return value; +} + +function coerceString(attributeDefinition, value, defaultValue) { + if(typeof value === 'string') { + if(value || !attributeDefinition.noBlank) return value; + } + else if(typeof value === 'number') { + if(!attributeDefinition.strict) return String(value); } - while(noNeighborList.length) { - newNeighborHash = {}; - foundNewNeighbors = false; + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} - // 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]; +function coerceEnumerated(attributeDefinition, value, defaultValue) { + if(attributeDefinition.coerceNumber) value = +value; - 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(attributeDefinition.values.indexOf(value) !== -1) return value; - if(neighborCount) { - newNeighborHash[thisPt] = [i, j, neighborCount]; - noNeighborList.splice(p, 1); - foundNewNeighbors = true; - } - } + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} - if(!foundNewNeighbors) { - throw 'findEmpties iterated with no new neighbors'; - } +function coerceNumber(attributeDefinition, value, defaultValue) { + if(_$fastIsnumeric_18(value)) { + value = +value; - // put these new cells into the main neighbor list - for(thisPt in newNeighborHash) { - neighborHash[thisPt] = newNeighborHash[thisPt]; - empties.push(newNeighborHash[thisPt]); - } + var min = attributeDefinition.min, + max = attributeDefinition.max, + isOutOfBounds = (min !== undefined && value < min) || + (max !== undefined && value > max); + + if(!isOutOfBounds) return value; } - // sort the full list in descending order of neighbor count - return empties.sort(function(a, b) { return b[2] - a[2]; }); -}; + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} + +function coerceColor(attributeDefinition, value, defaultValue) { + if(_$tinycolor_33(value).isValid()) return value; + + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -38474,10 +38721,36 @@ var _$findEmpties_323 = function findEmpties(z) { 'use strict'; -var __isArrayOrTypedArray_324 = _$lib_171.isArrayOrTypedArray; +var _$selectPoints_280 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + + if(polygon === false) { + // clear selection + for(i = 0; i < cd.length; i++) { + cd[i].selected = 0; + } + } else { + for(i = 0; i < cd.length; i++) { + var di = cd[i]; + + if(polygon.contains(di.ct)) { + selection.push({ + pointNumber: i, + x: xa.c2d(di.x), + y: ya.c2d(di.y) + }); + di.selected = 1; + } else { + di.selected = 0; + } + } + } -var _$has_columns_324 = function(trace) { - return !__isArrayOrTypedArray_324(trace.z[0]); + return selection; }; /** @@ -38490,126 +38763,103 @@ var _$has_columns_324 = function(trace) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +var _$Sieve_282 = Sieve; -var INTERPTHRESHOLD = 1e-2, - NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; +/* removed: var _$lib_172 = require('../../lib'); */; +var __BADNUM_282 = _$numerical_154.BADNUM; -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); -} +/** + * Helper class to sieve data from traces into bins + * + * @class + * @param {Array} traces + * Array of calculated traces + * @param {boolean} [separateNegativeValues] + * If true, then split data at the same position into a bar + * for positive values and another for negative values + * @param {boolean} [dontMergeOverlappingData] + * If true, then don't merge overlapping bars into a single bar + */ +function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { + this.traces = traces; + this.separateNegativeValues = separateNegativeValues; + this.dontMergeOverlappingData = dontMergeOverlappingData; -var _$interp2d_327 = function interp2d(z, emptyPoints, savedInterpZ) { - // fill in any missing data in 2D array z 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) - var maxFractionalChange = 1, - i, - thisPt; + // for single-bin histograms - see histogram/calc + var width1 = Infinity; - if(Array.isArray(savedInterpZ)) { - for(i = 0; i < emptyPoints.length; i++) { - thisPt = emptyPoints[i]; - z[thisPt[0]][thisPt[1]] = savedInterpZ[thisPt[0]][thisPt[1]]; + var positions = []; + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; + if(bar.p !== __BADNUM_282) positions.push(bar.p); + } + if(trace[0] && trace[0].width1) { + width1 = Math.min(trace[0].width1, width1); } } - else { - // one pass to fill in a starting value for all the empties - iterateInterp2d(z, emptyPoints); - } + this.positions = positions; - // 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); + var dv = _$lib_172.distinctVals(positions); + this.distinctPositions = dv.vals; + if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; + else this.minDiff = Math.min(dv.minDiff, width1); - for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) { - maxFractionalChange = iterateInterp2d(z, emptyPoints, - correctionOvershoot(maxFractionalChange)); - } - if(maxFractionalChange > INTERPTHRESHOLD) { - _$lib_171.log('interp2d didn\'t converge quickly', maxFractionalChange); - } + this.binWidth = this.minDiff; - return z; -}; + this.bins = {}; +} -function iterateInterp2d(z, emptyPoints, overshoot) { - var maxFractionalChange = 0, - thisPt, - i, - j, - p, - q, - neighborShift, - neighborRow, - neighborVal, - neighborCount, - neighborSum, - initialVal, - minNeighbor, - 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'; - } +/** + * Sieve datum + * + * @method + * @param {number} position + * @param {number} value + * @returns {number} Previous bin value + */ +Sieve.prototype.put = function put(position, value) { + var label = this.getLabel(position, value), + oldValue = this.bins[label] || 0; - // 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; + this.bins[label] = oldValue + value; - 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; + return oldValue; +}; - if(maxNeighbor > minNeighbor) { - maxFractionalChange = Math.max(maxFractionalChange, - Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor)); - } - } - } +/** + * Get current bin value for a given datum + * + * @method + * @param {number} position Position of datum + * @param {number} [value] Value of datum + * (required if this.separateNegativeValues is true) + * @returns {number} Current bin value + */ +Sieve.prototype.get = function put(position, value) { + var label = this.getLabel(position, value); + return this.bins[label] || 0; +}; - return maxFractionalChange; -} +/** + * Get bin label for a given datum + * + * @method + * @param {number} position Position of datum + * @param {number} [value] Value of datum + * (required if this.separateNegativeValues is true) + * @returns {string} Bin label + * (prefixed with a 'v' if value is negative and this.separateNegativeValues is + * true; otherwise prefixed with '^') + */ +Sieve.prototype.getLabel = function getLabel(position, value) { + var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^', + label = (this.dontMergeOverlappingData) ? + position : + Math.round(position / this.binWidth); + return prefix + label; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -38619,921 +38869,650 @@ function iterateInterp2d(z, emptyPoints, overshoot) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -var __isArrayOrTypedArray_328 = _$lib_171.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_281 = _$lib_172.isArrayOrTypedArray; +var __BADNUM_281 = _$numerical_154.BADNUM; -var _$makeBoundArray_328 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { - var arrayOut = [], - isContour = _$registry_261.traceIs(trace, 'contour'), - isHist = _$registry_261.traceIs(trace, 'histogram'), - isGL2D = _$registry_261.traceIs(trace, 'gl2d'), - v0, - dv, - i; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$Sieve_282 = require('./sieve.js'); */; - var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_328(arrayIn) && arrayIn.length > 1; +/* + * 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 + */ - if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) { - var len = arrayIn.length; +var _$setPositions_281 = function setPositions(gd, plotinfo) { + var xa = plotinfo.xaxis, + ya = plotinfo.yaxis; - // given vals are brick centers - // hopefully length === numbricks, but use this method even if too few are supplied - // and extend it linearly based on the last two points - if(len <= numbricks) { - // contour plots only want the centers - if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks); - else if(numbricks === 1) { - arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5]; + var fullTraces = gd._fullData, + calcTraces = gd.calcdata, + calcTracesHorizontal = [], + calcTracesVertical = [], + i; + for(i = 0; i < fullTraces.length; i++) { + var fullTrace = fullTraces[i]; + if( + fullTrace.visible === true && + _$registry_262.traceIs(fullTrace, 'bar') && + fullTrace.xaxis === xa._id && + fullTrace.yaxis === ya._id + ) { + if(fullTrace.orientation === 'h') { + calcTracesHorizontal.push(calcTraces[i]); } else { - arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]]; + calcTracesVertical.push(calcTraces[i]); + } + } + } - for(i = 1; i < len; i++) { - arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5); - } + setGroupPositions(gd, xa, ya, calcTracesVertical); + setGroupPositions(gd, ya, xa, calcTracesHorizontal); +}; - arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]); - } - if(len < numbricks) { - var lastPt = arrayOut[arrayOut.length - 1], - delta = lastPt - arrayOut[arrayOut.length - 2]; +function setGroupPositions(gd, pa, sa, calcTraces) { + if(!calcTraces.length) return; - for(i = len; i < numbricks; i++) { - lastPt += delta; - arrayOut.push(lastPt); - } - } + var barmode = gd._fullLayout.barmode, + overlay = (barmode === 'overlay'), + group = (barmode === 'group'), + excluded, + included, + i, calcTrace, fullTrace; + + if(overlay) { + setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces); + } + else if(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); } - else { - // hopefully length === numbricks+1, but do something regardless: - // given vals are brick boundaries - return isContour ? - arrayIn.slice(0, numbricks) : // we must be strict for contours - arrayIn.slice(0, numbricks + 1); + + if(included.length) { + setGroupPositionsInGroupMode(gd, pa, sa, included); + } + if(excluded.length) { + setGroupPositionsInOverlayMode(gd, pa, sa, excluded); } } else { - dv = dvIn || 1; - - var calendar = trace[ax._id.charAt(0) + 'calendar']; + // 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(isHist || ax.type === 'category') v0 = ax.r2c(v0In, 0, calendar) || 0; - else if(__isArrayOrTypedArray_328(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; - else if(v0In === undefined) v0 = 0; - else v0 = ax.d2c(v0In, 0, calendar); + if(fullTrace.base === undefined) included.push(calcTrace); + else excluded.push(calcTrace); + } - for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) { - arrayOut.push(v0 + dv * i); + if(included.length) { + setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included); + } + if(excluded.length) { + setGroupPositionsInOverlayMode(gd, pa, sa, excluded); } } - return arrayOut; -}; + collectExtents(calcTraces, pa); +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { + var barnorm = gd._fullLayout.barnorm, + separateNegativeValues = false, + dontMergeOverlappingData = !barnorm; -'use strict'; + // 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_282( + [calcTrace], separateNegativeValues, dontMergeOverlappingData + ); -var _$doAvg_335 = function doAvg(size, counts) { - var nMax = size.length, - total = 0; - for(var i = 0; i < nMax; i++) { - if(counts[i]) { - size[i] /= counts[i]; - total += size[i]; + // set bar offsets and widths, and update position axis + setOffsetAndWidth(gd, pa, sieve); + + // 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(barnorm) { + sieveBars(gd, sa, sieve); + normalizeBars(gd, sa, sieve); + } + else { + setBaseAndTop(gd, sa, sieve); } - else size[i] = null; } - return total; -}; +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { + var fullLayout = gd._fullLayout, + barnorm = fullLayout.barnorm, + separateNegativeValues = false, + dontMergeOverlappingData = !barnorm, + sieve = new _$Sieve_282( + calcTraces, separateNegativeValues, dontMergeOverlappingData + ); -'use strict'; + // set bar offsets and widths, and update position axis + setOffsetAndWidthInGroupMode(gd, pa, sieve); -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + // set bar bases and sizes, and update size axis + if(barnorm) { + sieveBars(gd, sa, sieve); + normalizeBars(gd, sa, sieve); + } + else { + setBaseAndTop(gd, sa, sieve); + } +} -var _$bin_functions_337 = { - count: function(n, i, size) { - size[n]++; - return 1; - }, +function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { + var fullLayout = gd._fullLayout, + barmode = fullLayout.barmode, + stack = (barmode === 'stack'), + relative = (barmode === 'relative'), + barnorm = gd._fullLayout.barnorm, + separateNegativeValues = relative, + dontMergeOverlappingData = !(barnorm || stack || relative), + sieve = new _$Sieve_282( + calcTraces, separateNegativeValues, dontMergeOverlappingData + ); - sum: function(n, i, size, counterData) { - var v = counterData[i]; - if(_$fastIsnumeric_18(v)) { - v = Number(v); - size[n] += v; - return v; - } - return 0; - }, + // set bar offsets and widths, and update position axis + setOffsetAndWidth(gd, pa, sieve); - avg: function(n, i, size, counterData, counts) { - var v = counterData[i]; - if(_$fastIsnumeric_18(v)) { - v = Number(v); - size[n] += v; - counts[n]++; - } - return 0; - }, + // set bar bases and sizes, and update size axis + stackBars(gd, sa, sieve); - min: function(n, i, size, counterData) { - var v = counterData[i]; - if(_$fastIsnumeric_18(v)) { - v = Number(v); - if(!_$fastIsnumeric_18(size[n])) { - size[n] = v; - return v; - } - else if(size[n] > v) { - var delta = v - size[n]; - size[n] = v; - return delta; - } - } - return 0; - }, + // flag the outmost bar (for text display purposes) + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; - max: function(n, i, size, counterData) { - var v = counterData[i]; - if(_$fastIsnumeric_18(v)) { - v = Number(v); - if(!_$fastIsnumeric_18(size[n])) { - size[n] = v; - return v; - } - else if(size[n] < v) { - var delta = v - size[n]; - size[n] = v; - return delta; - } + for(var j = 0; j < calcTrace.length; j++) { + var bar = calcTrace[j]; + + if(bar.s === __BADNUM_281) continue; + + var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); + if(isOutmostBar) bar._outmost = true; } - return 0; } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // Note that marking the outmost bars has to be done + // before `normalizeBars` changes `bar.b` and `bar.s`. + if(barnorm) normalizeBars(gd, sa, sieve); +} -'use strict'; +function setOffsetAndWidth(gd, pa, sieve) { + var fullLayout = gd._fullLayout, + bargap = fullLayout.bargap, + bargroupgap = fullLayout.bargroupgap, + minDiff = sieve.minDiff, + calcTraces = sieve.traces, + i, calcTrace, calcTrace0, + t; -/* removed: var _$numerical_154 = require('../../constants/numerical'); */; -var oneYear = _$numerical_154.ONEAVGYEAR; -var oneMonth = _$numerical_154.ONEAVGMONTH; -var oneDay = _$numerical_154.ONEDAY; -var oneHour = _$numerical_154.ONEHOUR; -var oneMin = _$numerical_154.ONEMIN; -var oneSec = _$numerical_154.ONESEC; -var tickIncrement = _$axes_213.tickIncrement; + // set bar offsets and widths + var barGroupWidth = minDiff * (1 - bargap), + barWidthPlusGap = barGroupWidth, + barWidth = barWidthPlusGap * (1 - bargroupgap); + // computer bar group center and bar offset + var offsetFromCenter = -barWidth / 2; -/* - * 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` - */ -var _$getBinSpanLabelRound_338 = 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) - ); + for(i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; - // 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; + // store bar width and offset for this trace + t = calcTrace0.t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; } - if(pa.type === 'date' && digit > oneDay) { - var dashExclude = (digit === oneYear) ? 1 : 6; - var increment = (digit === oneYear) ? 'M12' : 'M1'; + // stack bars that only differ by rounding + sieve.binWidth = calcTraces[0][0].t.barwidth / 100; - 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 defined, apply trace offset and width + applyAttributes(sieve); - if(roundedV < v) { - var nextV = tickIncrement(roundedV, increment, false, calendar); - if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV; - } + // store the bar center in each calcdata item + setBarCenterAndWidth(gd, pa, sieve); - if(isRightEdge && disambiguateEdges) { - return tickIncrement(roundedV, increment, true, calendar); - } + // update position axes + updatePositionAxis(gd, pa, sieve); +} - 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; - }; -}; +function setOffsetAndWidthInGroupMode(gd, pa, sieve) { + var fullLayout = gd._fullLayout, + bargap = fullLayout.bargap, + bargroupgap = fullLayout.bargroupgap, + positions = sieve.positions, + distinctPositions = sieve.distinctPositions, + minDiff = sieve.minDiff, + calcTraces = sieve.traces, + i, calcTrace, calcTrace0, + t; -/* - * 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; + // if there aren't any overlapping positions, + // let them have full width even if mode is group + var overlap = (positions.length !== distinctPositions.length); - 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; -} + var nTraces = calcTraces.length, + barGroupWidth = minDiff * (1 - bargap), + barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth, + barWidth = barWidthPlusGap * (1 - bargroupgap); -/* - * 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; - } + for(i = 0; i < nTraces; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; - if(dv > oneHour) return oneHour; - if(dv > oneMin) return oneMin; - return oneSec; + // computer bar group center and bar offset + var offsetFromCenter = (overlap) ? + ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : + -barWidth / 2; + + // store bar width and offset for this trace + t = calcTrace0.t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; } - 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]; + // stack bars that only differ by rounding + sieve.binWidth = calcTraces[0][0].t.barwidth / 100; - } - return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1; -} + // if defined, apply trace width + applyAttributes(sieve); -function dateParts(v, pa, calendar) { - var parts = pa.c2d(v, oneYear, calendar).split('-'); - if(parts[0] === '') { - parts.unshift(); - parts[0] = '-' + parts[0]; - } - return parts; + // store the bar center in each calcdata item + setBarCenterAndWidth(gd, pa, sieve); + + // update position axes + updatePositionAxis(gd, pa, sieve, overlap); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function applyAttributes(sieve) { + var calcTraces = sieve.traces, + i, calcTrace, calcTrace0, fullTrace, + j, + t; -'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var cleanDate = _$lib_171.cleanDate; -/* removed: var _$numerical_154 = require('../../constants/numerical'); */; -var __ONEDAY_340 = _$numerical_154.ONEDAY; -var __BADNUM_340 = _$numerical_154.BADNUM; + for(i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; + fullTrace = calcTrace0.trace; + t = calcTrace0.t; -/* - * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) - * Mutates trace so all these attributes are valid. - * - * Normally this kind of thing would happen during supplyDefaults, but - * in this case we need to know the axis type, and axis type isn't set until - * after trace supplyDefaults are completed. So this gets called during the - * calc step, when data are inserted into bins. - */ -var _$cleanBins_340 = function cleanBins(trace, ax, binDirection) { - var axType = ax.type, - binAttr = binDirection + 'bins', - bins = trace[binAttr]; + var offset = fullTrace.offset, + initialPoffset = t.poffset, + newPoffset; - if(!bins) bins = trace[binAttr] = {}; + if(__isArrayOrTypedArray_281(offset)) { + // if offset is an array, then clone it into t.poffset. + newPoffset = offset.slice(0, calcTrace.length); - var cleanBound = (axType === 'date') ? - function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_340, bins.calendar) : null; } : - function(v) { return _$fastIsnumeric_18(v) ? Number(v) : null; }; + // guard against non-numeric items + for(j = 0; j < newPoffset.length; j++) { + if(!_$fastIsnumeric_18(newPoffset[j])) { + newPoffset[j] = initialPoffset; + } + } - bins.start = cleanBound(bins.start); - bins.end = cleanBound(bins.end); + // 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); + } - // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) - // but without the extra string options for log axes - // ie the only strings we accept are M for months - var sizeDflt = (axType === 'date') ? __ONEDAY_340 : 1, - binSize = bins.size; + t.poffset = newPoffset; + } + else if(offset !== undefined) { + t.poffset = offset; + } - if(_$fastIsnumeric_18(binSize)) { - bins.size = (binSize > 0) ? Number(binSize) : sizeDflt; - } - else if(typeof binSize !== 'string') { - bins.size = sizeDflt; - } - else { - // date special case: "M" gives bins every (integer) n months - var prefix = binSize.charAt(0), - sizeNum = binSize.substr(1); + var width = fullTrace.width, + initialBarwidth = t.barwidth; - sizeNum = _$fastIsnumeric_18(sizeNum) ? Number(sizeNum) : 0; - if((sizeNum <= 0) || !( - axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum) - )) { - bins.size = sizeDflt; + if(__isArrayOrTypedArray_281(width)) { + // if width is an array, then clone it into t.barwidth. + var newBarwidth = width.slice(0, calcTrace.length); + + // guard against non-numeric items + for(j = 0; j < newBarwidth.length; j++) { + if(!_$fastIsnumeric_18(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; + } } } +} - var autoBinAttr = 'autobin' + binDirection; - if(typeof trace[autoBinAttr] !== 'boolean') { - trace[autoBinAttr] = trace._fullInput[autoBinAttr] = trace._input[autoBinAttr] = !( - (bins.start || bins.start === 0) && - (bins.end || bins.end === 0) - ); - } +function setBarCenterAndWidth(gd, pa, sieve) { + var calcTraces = sieve.traces, + pLetter = getAxisLetter(pa); - if(!trace[autoBinAttr]) { - delete trace['nbins' + binDirection]; - delete trace._fullInput['nbins' + binDirection]; + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i], + t = calcTrace[0].t, + poffset = t.poffset, + poffsetIsArray = Array.isArray(poffset), + barwidth = t.barwidth, + 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; + + + } } -}; +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function updatePositionAxis(gd, pa, sieve, allowMinDtick) { + var calcTraces = sieve.traces, + distinctPositions = sieve.distinctPositions, + distinctPositions0 = distinctPositions[0], + minDiff = sieve.minDiff, + vpad = minDiff / 2; -'use strict'; + _$axes_214.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + // If the user set the bar width or the offset, + // then bars can be shifted away from their positions + // and widths can be larger than minDiff. + // + // Here, we compute pMin and pMax to expand the position axis, + // so that all bars are fully within the axis range. + var pMin = Math.min.apply(Math, distinctPositions) - vpad, + pMax = Math.max.apply(Math, distinctPositions) + vpad; -var _$norm_functions_345 = { - percent: function(size, total) { - var nMax = size.length, - norm = 100 / total; - for(var n = 0; n < nMax; n++) size[n] *= norm; - }, - probability: function(size, total) { - var nMax = size.length; - for(var n = 0; n < nMax; n++) size[n] /= total; - }, - density: function(size, total, inc, yinc) { - var nMax = size.length; - yinc = yinc || 1; - for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc; - }, - 'probability density': function(size, total, inc, yinc) { - var nMax = size.length; - if(yinc) total /= yinc; - for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total; - } -}; + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i], + calcTrace0 = calcTrace[0], + fullTrace = calcTrace0.trace; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(fullTrace.width === undefined && fullTrace.offset === undefined) { + continue; + } + var t = calcTrace0.t, + poffset = t.poffset, + barwidth = t.barwidth, + poffsetIsArray = Array.isArray(poffset), + barwidthIsArray = Array.isArray(barwidth); -'use strict'; + for(var j = 0; j < calcTrace.length; j++) { + var calcBar = calcTrace[j], + calcBarOffset = (poffsetIsArray) ? poffset[j] : poffset, + calcBarWidth = (barwidthIsArray) ? barwidth[j] : barwidth, + p = calcBar.p, + l = p + calcBarOffset, + r = l + calcBarWidth; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; + pMin = Math.min(pMin, l); + pMax = Math.max(pMax, r); + } + } -/* removed: var _$bin_functions_337 = require('../histogram/bin_functions'); */; -/* removed: var _$norm_functions_345 = require('../histogram/norm_functions'); */; -/* removed: var _$doAvg_335 = require('../histogram/average'); */; -/* removed: var _$cleanBins_340 = require('../histogram/clean_bins'); */; -/* removed: var _$getBinSpanLabelRound_338 = require('../histogram/bin_label_vals'); */; + _$axes_214.expand(pa, [pMin, pMax], {padded: false}); +} +function expandRange(range, newValue) { + if(_$fastIsnumeric_18(range[0])) range[0] = Math.min(range[0], newValue); + else range[0] = newValue; -var _$calc_347 = function calc(gd, trace) { - var xa = _$axes_213.getFromId(gd, trace.xaxis || 'x'); - var x = trace.x ? xa.makeCalcdata(trace, 'x') : []; - var ya = _$axes_213.getFromId(gd, trace.yaxis || 'y'); - var y = trace.y ? ya.makeCalcdata(trace, 'y') : []; - 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); }; + if(_$fastIsnumeric_18(range[1])) range[1] = Math.max(range[1], newValue); + else range[1] = newValue; +} - var i, j, n, m; +function setBaseAndTop(gd, sa, sieve) { + // 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. + var traces = sieve.traces, + sLetter = getAxisLetter(sa), + sRange = [null, null]; - var serieslen = Math.min(x.length, y.length); - if(x.length > serieslen) x.splice(serieslen, x.length - serieslen); - if(y.length > serieslen) y.splice(serieslen, y.length - serieslen); + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; - // calculate the bins - cleanAndAutobin(trace, 'x', x, xa, xr2c, xc2r, xcalendar); - cleanAndAutobin(trace, 'y', y, ya, yr2c, yc2r, ycalendar); + for(var j = 0; j < trace.length; j++) { + var bar = trace[j], + barBase = bar.b, + barTop = barBase + bar.s; - // make the empty bin array & scale the map - var z = []; - var onecol = []; - var zerocol = []; - var nonuniformBinsX = (typeof(trace.xbins.size) === 'string'); - var nonuniformBinsY = (typeof(trace.ybins.size) === 'string'); - var xEdges = []; - var yEdges = []; - var xbins = nonuniformBinsX ? xEdges : trace.xbins; - var ybins = nonuniformBinsY ? yEdges : trace.ybins; - 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 = _$bin_functions_337.count; - var normfunc = _$norm_functions_345[norm]; - var doavg = false; - var xinc = []; - var yinc = []; + bar[sLetter] = barTop; - // 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 = _$bin_functions_337[func]; + if(_$fastIsnumeric_18(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_18(sa.c2l(barBase))) expandRange(sRange, barBase); + } } - // decrease end a little in case of rounding errors - var binSpec = trace.xbins, - binStart = xr2c(binSpec.start), - binEnd = xr2c(binSpec.end) + - (binStart - _$axes_213.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; + _$axes_214.expand(sa, sRange, {tozero: true, padded: true}); +} - for(i = binStart; i < binEnd; i = _$axes_213.tickIncrement(i, binSpec.size, false, xcalendar)) { - onecol.push(sizeinit); - xEdges.push(i); - if(doavg) zerocol.push(0); - } - xEdges.push(i); - var nx = onecol.length; - var x0c = xr2c(trace.xbins.start); - var dx = (i - x0c) / nx; - var x0 = xc2r(x0c + dx / 2); +function stackBars(gd, sa, sieve) { + var fullLayout = gd._fullLayout, + barnorm = fullLayout.barnorm, + sLetter = getAxisLetter(sa), + traces = sieve.traces, + i, trace, + j, bar; - binSpec = trace.ybins; - binStart = yr2c(binSpec.start); - binEnd = yr2c(binSpec.end) + - (binStart - _$axes_213.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; + var sRange = [null, null]; - for(i = binStart; i < binEnd; i = _$axes_213.tickIncrement(i, binSpec.size, 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); + for(i = 0; i < traces.length; i++) { + trace = traces[i]; - var ny = z.length; - var y0c = yr2c(trace.ybins.start); - var dy = (i - y0c) / ny; - var y0 = yc2r(y0c + dy / 2); + for(j = 0; j < trace.length; j++) { + bar = trace[j]; - if(densitynorm) { - xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX); - yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY); - } + if(bar.s === __BADNUM_281) continue; - // 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); + // stack current bar and get previous sum + var barBase = sieve.put(bar.p, bar.b + bar.s), + barTop = barBase + bar.b + bar.s; - // 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 = x[i]; - var yi = y[i]; - n = _$lib_171.findBin(xi, xbins); - m = _$lib_171.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); + // store the bar base and top in each calcdata item + bar.b = barBase; + bar[sLetter] = barTop; - if(uniqueValsPerX) { - if(xVals[n] === undefined) xVals[n] = xi; - else if(xVals[n] !== xi) uniqueValsPerX = false; - } - if(uniqueValsPerY) { - if(yVals[n] === undefined) yVals[n] = yi; - else if(yVals[n] !== yi) uniqueValsPerY = false; + if(!barnorm) { + if(_$fastIsnumeric_18(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_18(sa.c2l(barBase))) expandRange(sRange, barBase); } - - 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_335(z[m], counts[m]); - } - if(normfunc) { - for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); - } - return { - x: x, - xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar), - x0: x0, - dx: dx, - y: y, - yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar), - y0: y0, - dy: dy, - z: z, - pts: inputPoints - }; -}; + // if barnorm is set, let normalizeBars update the axis range + if(!barnorm) _$axes_214.expand(sa, sRange, {tozero: true, padded: true}); +} -function cleanAndAutobin(trace, axLetter, data, ax, r2c, c2r, calendar) { - var binSpecAttr = axLetter + 'bins'; - var autoBinAttr = 'autobin' + axLetter; - var binSpec = trace[binSpecAttr]; - _$cleanBins_340(trace, ax, axLetter); +function sieveBars(gd, sa, sieve) { + var traces = sieve.traces; - if(trace[autoBinAttr] || !binSpec || binSpec.start === null || binSpec.end === null) { - binSpec = _$axes_213.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); - if(trace.type === 'histogram2dcontour') { - // the "true" last argument reverses the tick direction (which we can't - // just do with a minus sign because of month bins) - binSpec.start = c2r(_$axes_213.tickIncrement( - r2c(binSpec.start), binSpec.size, true, calendar)); - binSpec.end = c2r(_$axes_213.tickIncrement( - r2c(binSpec.end), binSpec.size, false, calendar)); - } + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; - // copy bin info back to the source data. - trace._input[binSpecAttr] = trace[binSpecAttr] = binSpec; - // note that it's possible to get here with an explicit autobin: false - // if the bins were not specified. - // in that case this will remain in the trace, so that future updates - // which would change the autobinning will not do so. - trace._input[autoBinAttr] = trace[autoBinAttr]; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; + + if(bar.s !== __BADNUM_281) sieve.put(bar.p, bar.b + bar.s); + } } } -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 normalizeBars(gd, sa, sieve) { + // Note: + // + // normalizeBars requires that either sieveBars or stackBars has been + // previously invoked. -function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { - var i; - var len = edges.length - 1; - var out = new Array(len); - if(uniqueVals) { - for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]]; - } - else { - var roundFn = _$getBinSpanLabelRound_338(gapLow, gapHigh, edges, ax, calendar); - for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)]; - } - return out; -} + var traces = sieve.traces, + sLetter = getAxisLetter(sa), + sTop = (gd._fullLayout.barnorm === 'fraction') ? 1 : 100, + sTiny = sTop / 1e9, // in case of rounding error in sum + sMin = sa.l2c(sa.c2l(0)), + sMax = (gd._fullLayout.barmode === 'stack') ? sTop : sMin, + sRange = [sMin, sMax], + padded = false; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function maybeExpand(newValue) { + if(_$fastIsnumeric_18(sa.c2l(newValue)) && + ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_18(sMin)) + ) { + padded = true; + expandRange(sRange, newValue); + } + } + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; -'use strict'; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; + if(bar.s === __BADNUM_281) continue; -/* removed: var _$calc_347 = require('../histogram2d/calc'); */; -/* removed: var _$calc_58 = require('../../components/colorscale/calc'); */; -/* removed: var _$has_columns_324 = require('./has_columns'); */; -/* removed: var _$convertColumnData_321 = require('./convert_column_xyz'); */; -/* removed: var _$maxRowLength_329 = require('./max_row_length'); */; -/* removed: var _$clean2dArray_319 = require('./clean_2d_array'); */; -/* removed: var _$interp2d_327 = require('./interp2d'); */; -/* removed: var _$findEmpties_323 = require('./find_empties'); */; -/* removed: var _$makeBoundArray_328 = require('./make_bound_array'); */; + var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); + bar.b *= scale; + bar.s *= scale; + var barBase = bar.b, + barTop = barBase + bar.s; + bar[sLetter] = barTop; -var _$calc_318 = 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_213.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_213.getFromId(gd, trace.yaxis || 'y'), - isContour = _$registry_261.traceIs(trace, 'contour'), - isHist = _$registry_261.traceIs(trace, 'histogram'), - isGL2D = _$registry_261.traceIs(trace, 'gl2d'), - zsmooth = isContour ? 'best' : trace.zsmooth, - x, - x0, - dx, - y, - y0, - dy, - z, - i, - binned; + maybeExpand(barTop); + if(bar.hasB) maybeExpand(barBase); + } + } - // cancel minimum tick spacings (only applies to bars and boxes) - xa._minDtick = 0; - ya._minDtick = 0; + // update range of size axis + _$axes_214.expand(sa, sRange, {tozero: true, padded: padded}); +} - if(isHist) { - binned = _$calc_347(gd, trace); - x = binned.x; - x0 = binned.x0; - dx = binned.dx; - y = binned.y; - y0 = binned.y0; - dy = binned.dy; - z = binned.z; - } - else { - if(_$has_columns_324(trace)) { - _$convertColumnData_321(trace, xa, ya, 'x', 'y', ['z']); - x = trace.x; - y = trace.y; - } else { - x = trace.x ? xa.makeCalcdata(trace, 'x') : []; - y = trace.y ? ya.makeCalcdata(trace, 'y') : []; - } - x0 = trace.x0 || 0; - dx = trace.dx || 1; - y0 = trace.y0 || 0; - dy = trace.dy || 1; +function getAxisLetter(ax) { + return ax._id.charAt(0); +} - z = _$clean2dArray_319(trace.z, trace.transpose); +// 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 posLetter = pa._id.charAt(0); + var extents = {}; + var pMin = Infinity; + var pMax = -Infinity; - if(isContour || trace.connectgaps) { - trace._emptypoints = _$findEmpties_323(z); - trace._interpz = _$interp2d_327(z, trace._emptypoints, trace._interpz); + var i, j, cd; + for(i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + for(j = 0; j < cd.length; j++) { + var p = cd[j].p; + if(_$fastIsnumeric_18(p)) { + pMin = Math.min(pMin, p); + pMax = Math.max(pMax, p); + } } } - function noZsmooth(msg) { - zsmooth = trace._input.zsmooth = trace.zsmooth = false; - _$lib_171.warn('cannot use zsmooth: "fast": ' + msg); - } + // 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))); + }; - // 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), - 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; - } + for(i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + cd[0].t.extents = extents; + for(j = 0; j < cd.length; j++) { + var di = cd[j]; + var p0 = di[posLetter] - di.w / 2; + if(_$fastIsnumeric_18(p0)) { + var p1 = di[posLetter] + 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])]; } - } - if(y.length && zsmooth === 'fast') { - var avgdy = (y[y.length - 1] - y[0]) / (y.length - 1), - 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; - } + else { + extents[pVal] = [p0, p1]; } } } } - - // create arrays of brick boundaries, to be used by autorange and heatmap.plot - var xlen = _$maxRowLength_329(z); - var xIn = trace.xtype === 'scaled' ? '' : x; - var xArray = _$makeBoundArray_328(trace, xIn, x0, dx, xlen, xa); - var yIn = trace.ytype === 'scaled' ? '' : y; - var yArray = _$makeBoundArray_328(trace, yIn, y0, dy, z.length, ya); - - // handled in gl2d convert step - if(!isGL2D) { - _$axes_213.expand(xa, xArray); - _$axes_213.expand(ya, yArray); - } - - var cd0 = { - x: xArray, - y: yArray, - z: z, - text: trace.text - }; - - 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; - } - - // auto-z and autocolorscale if applicable - if(!isContour || trace.contours.type !== 'constraint') { - _$calc_58(trace, z, '', '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_328(dummyTrace, xIn, x0, dx, xlen, xa); - cd0.yfill = _$makeBoundArray_328(dummyTrace, yIn, y0, dy, z.length, ya); - } - - return [cd0]; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$calc_318 = require('../heatmap/calc'); */; -/* removed: var _$setContours_314 = require('./set_contours'); */; - -// 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 -var _$calc_296 = function calc(gd, trace) { - var cd = _$calc_318(gd, trace); - _$setContours_314(trace); - return cd; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* - * tiny helper to move the end of the contours a little to prevent - * losing the last contour to rounding errors - */ -var _$endPlus_306 = function endPlus(contours) { - return contours.end + contours.size / 1e6; -}; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -39547,136 +39526,61 @@ var _$endPlus_306 = function endPlus(contours) { 'use strict'; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$colorscale_66 = require('../../components/colorscale'); */; -/* removed: var _$endPlus_306 = require('./end_plus'); */; - -var _$makeColorMap_311 = function makeColorMap(trace) { - var contours = trace.contours, - start = contours.start, - end = _$endPlus_306(contours), - cs = contours.size || 1, - nc = Math.floor((end - start) / cs) + 1, - extra = contours.coloring === 'lines' ? 0 : 1; - - if(!isFinite(cs)) { - cs = 1; - nc = 1; - } - - var scl = trace.colorscale, - len = scl.length; - - var domain = new Array(len), - range = new Array(len); - - var si, i; - - if(contours.coloring === 'heatmap') { - if(trace.zauto && trace.autocontour === false) { - trace.zmin = start - cs / 2; - trace.zmax = trace.zmin + nc * cs; - } - - for(i = 0; i < len; i++) { - si = scl[i]; - - domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin; - range[i] = si[1]; - } - - // do the contours extend beyond the colorscale? - // if so, extend the colorscale with constants - var zRange = _$d3_15.extent([trace.zmin, trace.zmax, contours.start, - contours.start + cs * (nc - 1)]), - zmin = zRange[trace.zmin < trace.zmax ? 0 : 1], - zmax = zRange[trace.zmin < trace.zmax ? 1 : 0]; +/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$registry_262 = require('../../registry'); */; - if(zmin !== trace.zmin) { - domain.splice(0, 0, zmin); - range.splice(0, 0, Range[0]); - } +var _$style_283 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_15.select(gd).selectAll('g.trace.bars'); + var barcount = s.size(); + var fullLayout = gd._fullLayout; - if(zmax !== trace.zmax) { - domain.push(zmax); - range.push(range[range.length - 1]); - } - } - else { - for(i = 0; i < len; i++) { - si = scl[i]; + // trace styling + s.style('opacity', function(d) { return d[0].trace.opacity; }) - domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start; - range[i] = si[1]; + // for gapless (either stacked or neighboring grouped) bars use + // crispEdges to turn off antialiasing so an artificial gap + // isn't introduced. + .each(function(d) { + if((fullLayout.barmode === 'stack' && barcount > 1) || + (fullLayout.bargap === 0 && + fullLayout.bargroupgap === 0 && + !d[0].trace.marker.line.width)) { + _$d3_15.select(this).attr('shape-rendering', 'crispEdges'); } - } - - return _$colorscale_66.makeColorScaleFunc({ - domain: domain, - range: range, - }, { - noNumericCheck: true }); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$draw_55 = require('../../components/colorbar/draw'); */; - -/* removed: var _$makeColorMap_311 = require('./make_color_map'); */; -/* removed: var _$endPlus_306 = require('./end_plus'); */; - -var _$colorbar_298 = function colorbar(gd, cd) { - var trace = cd[0].trace, - cbId = 'cb' + trace.uid; - - gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); + s.selectAll('g.points').each(function(d) { + var sel = _$d3_15.select(this); + var pts = sel.selectAll('path'); + var txs = sel.selectAll('text'); + var trace = d[0].trace; - if(!trace.showscale) { - _$plots_246.autoMargin(gd, cbId); - return; - } + _$drawing_76.pointStyle(pts, trace, gd); + _$drawing_76.selectedPointStyle(pts, trace); - var cb = _$draw_55(gd, cbId); - cd[0].t.cb = cb; + txs.each(function(d) { + var tx = _$d3_15.select(this); + var textFont; - var contours = trace.contours, - line = trace.line, - cs = contours.size || 1, - coloring = contours.coloring; + if(tx.classed('bartext-inside')) { + textFont = trace.insidetextfont; + } else if(tx.classed('bartext-outside')) { + textFont = trace.outsidetextfont; + } + if(!textFont) textFont = trace.textfont; - var colorMap = _$makeColorMap_311(trace, {isColorbar: true}); + function cast(k) { + var cont = textFont[k]; + return Array.isArray(cont) ? cont[d.i] : cont; + } - if(coloring === 'heatmap') { - cb.filllevels({ - start: trace.zmin, - end: trace.zmax, - size: (trace.zmax - trace.zmin) / 254 + _$drawing_76.font(tx, cast('family'), cast('size'), cast('color')); }); - } - cb.fillcolor((coloring === 'fill' || coloring === 'heatmap') ? colorMap : '') - .line({ - color: coloring === 'lines' ? colorMap : line.color, - width: contours.showlines !== false ? line.width : 0, - dash: line.dash - }) - .levels({ - start: contours.start, - end: _$endPlus_306(contours), - size: cs - }) - .options(trace.colorbar)(); + _$drawing_76.selectedTextStyle(txs, trace); + }); + + _$registry_262.getComponentMethod('errorbars', 'style')(s); }; /** @@ -39687,25 +39591,23 @@ var _$colorbar_298 = function colorbar(gd, cd) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; - -var _$handleLabelDefaults_310 = function handleLabelDefaults(coerce, layout, lineColor, opts) { - if(!opts) opts = {}; - var showLabels = coerce('contours.showlabels'); - if(showLabels) { - var globalFont = layout.font; - _$lib_171.coerceFont(coerce, 'contours.labelfont', { - family: globalFont.family, - size: globalFont.size, - color: lineColor - }); - coerce('contours.labelformat'); +var _$constants_53 = { + cn: { + colorbar: 'colorbar', + cbbg: 'cbbg', + cbfill: 'cbfill', + cbfills: 'cbfills', + cbline: 'cbline', + cblines: 'cblines', + cbaxis: 'cbaxis', + cbtitleunshift: 'cbtitleunshift', + cbtitle: 'cbtitle', + cboutline: 'cboutline', + crisp: 'crisp', + jsPlaceholder: 'js-placeholder' } - - if(opts.hasHover !== false) coerce('zhoverformat'); }; /** @@ -39718,429 +39620,639 @@ var _$handleLabelDefaults_310 = function handleLabelDefaults(coerce, layout, lin 'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$handleLabelDefaults_310 = require('./label_defaults'); */; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -var addOpacity = _$color_51.addOpacity; -var opacity = _$color_51.opacity; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var __extendFlat_55 = _$extend_166.extendFlat; +/* removed: var _$setCursor_191 = require('../../lib/setcursor'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$titles_144 = require('../titles'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +var __LINE_SPACING_55 = _$alignment_151.LINE_SPACING; -/* removed: var _$filter_ops_152 = require('../../constants/filter_ops'); */; -var CONSTRAINT_REDUCTION = _$filter_ops_152.CONSTRAINT_REDUCTION; -var __COMPARISON_OPS2_300 = _$filter_ops_152.COMPARISON_OPS2; +/* removed: var _$handleAxisDefaults_216 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handlePositionDefaults_229 = require('../../plots/cartesian/position_defaults'); */; +/* removed: var _$layout_attributes_226 = require('../../plots/cartesian/layout_attributes'); */; -var _$handleConstraintDefaults_300 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { - var contours = traceOut.contours; - var showLines, lineColor, fillColor; +/* removed: var _$attributes_52 = require('./attributes'); */; +var cn = _$constants_53.cn; - var operation = coerce('contours.operation'); - contours._operation = CONSTRAINT_REDUCTION[operation]; +var _$draw_55 = function draw(gd, id) { + // opts: options object, containing everything from attributes + // plus a few others that are the equivalent of the colorbar "data" + var opts = {}; + Object.keys(_$attributes_52).forEach(function(k) { + opts[k] = null; + }); + // fillcolor can be a d3 scale, domain is z values, range is colors + // or leave it out for no fill, + // or set to a string constant for single-color fill + opts.fillcolor = null; + // line.color has the same options as fillcolor + opts.line = {color: null, width: null, dash: null}; + // levels of lines to draw. + // note that this DOES NOT determine the extent of the bar + // that's given by the domain of fillcolor + // (or line.color if no fillcolor domain) + opts.levels = {start: null, end: null, size: null}; + // separate fill levels (for example, heatmap coloring of a + // contour map) if this is omitted, fillcolors will be + // evaluated halfway between levels + opts.filllevels = null; - handleConstraintValueDefaults(coerce, contours); + function component() { + var fullLayout = gd._fullLayout, + gs = fullLayout._size; + if((typeof opts.fillcolor !== 'function') && + (typeof opts.line.color !== 'function')) { + fullLayout._infolayer.selectAll('g.' + id).remove(); + return; + } + var zrange = _$d3_15.extent(((typeof opts.fillcolor === 'function') ? + opts.fillcolor : opts.line.color).domain()); + var linelevels = []; + var filllevels = []; + var linecolormap = typeof opts.line.color === 'function' ? + opts.line.color : function() { return opts.line.color; }; + var fillcolormap = typeof opts.fillcolor === 'function' ? + opts.fillcolor : function() { return opts.fillcolor; }; + var l; + var i; - if(operation === '=') { - showLines = contours.showlines = true; - } - else { - showLines = coerce('contours.showlines'); - fillColor = coerce('fillcolor', addOpacity( - (traceIn.line || {}).color || defaultColor, 0.5 - )); - } + var l0 = opts.levels.end + opts.levels.size / 100, + ls = opts.levels.size, + zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), + zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); + for(i = 0; i < 1e5; i++) { + l = opts.levels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zr0 && l < zr1) linelevels.push(l); + } - if(showLines) { - var lineDfltColor = fillColor && opacity(fillColor) ? - addOpacity(traceOut.fillcolor, 1) : - defaultColor; - lineColor = coerce('line.color', lineDfltColor); - coerce('line.width', 2); - coerce('line.dash'); - } - - coerce('line.smoothing'); - - _$handleLabelDefaults_310(coerce, layout, lineColor, opts); -}; - -function handleConstraintValueDefaults(coerce, contours) { - var zvalue; - - if(__COMPARISON_OPS2_300.indexOf(contours.operation) === -1) { - // Requires an array of two numbers: - coerce('contours.value', [0, 1]); - - if(!Array.isArray(contours.value)) { - if(_$fastIsnumeric_18(contours.value)) { - zvalue = parseFloat(contours.value); - contours.value = [zvalue, zvalue + 1]; + if(typeof opts.fillcolor === 'function') { + if(opts.filllevels) { + l0 = opts.filllevels.end + opts.filllevels.size / 100; + ls = opts.filllevels.size; + for(i = 0; i < 1e5; i++) { + l = opts.filllevels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zrange[0] && l < zrange[1]) filllevels.push(l); + } } - } else if(contours.value.length > 2) { - contours.value = contours.value.slice(2); - } else if(contours.length === 0) { - contours.value = [0, 1]; - } else if(contours.length < 2) { - zvalue = parseFloat(contours.value[0]); - contours.value = [zvalue, zvalue + 1]; - } else { - contours.value = [ - parseFloat(contours.value[0]), - parseFloat(contours.value[1]) - ]; - } - } else { - // Requires a single scalar: - coerce('contours.value', 0); - - if(!_$fastIsnumeric_18(contours.value)) { - if(Array.isArray(contours.value)) { - contours.value = parseFloat(contours.value[0]); - } else { - contours.value = 0; + else { + filllevels = linelevels.map(function(v) { + return v - opts.levels.size / 2; + }); + filllevels.push(filllevels[filllevels.length - 1] + + opts.levels.size); } } - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$handleContourDefaults_302 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { - var contourStart = coerce2('contours.start'); - var contourEnd = coerce2('contours.end'); - var missingEnd = (contourStart === false) || (contourEnd === false); - - // normally we only need size if autocontour is off. But contour.calc - // pushes its calculated contour size back to the input trace, so for - // things like restyle that can call supplyDefaults without calc - // after the initial draw, we can just reuse the previous calculation - var contourSize = coerce('contours.size'); - var autoContour; + else if(opts.fillcolor && typeof opts.fillcolor === 'string') { + // doesn't matter what this value is, with a single value + // we'll make a single fill rect covering the whole bar + filllevels = [0]; + } - if(missingEnd) autoContour = traceOut.autocontour = true; - else autoContour = coerce('autocontour', false); + if(opts.levels.size < 0) { + linelevels.reverse(); + filllevels.reverse(); + } - if(autoContour || !contourSize) coerce('ncontours'); -}; + // now make a Plotly Axes object to scale with and draw ticks + // TODO: does not support orientation other than right -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // we calculate pixel sizes based on the specified graph size, + // not the actual (in case something pushed the margins around) + // which is a little odd but avoids an odd iterative effect + // when the colorbar itself is pushing the margins. + // but then the fractional size is calculated based on the + // actual graph size, so that the axes will size correctly. + var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, + originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, + thickPx = Math.round(opts.thickness * + (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), + thickFrac = thickPx / gs.w, + lenPx = Math.round(opts.len * + (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), + lenFrac = lenPx / gs.h, + xpadFrac = opts.xpad / gs.w, + yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, + ypadFrac = opts.ypad / gs.h, + // x positioning: do it initially just for left anchor, + // then fix at the end (since we don't know the width yet) + xLeft = Math.round(opts.x * gs.w + opts.xpad), + // for dragging... this is getting a little muddled... + xLeftFrac = opts.x - thickFrac * + ({middle: 0.5, right: 1}[opts.xanchor]||0), -'use strict'; + // y positioning we can do correctly from the start + yBottomFrac = opts.y + lenFrac * + (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), + yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), + yTopPx = yBottomPx - lenPx, + titleEl, + cbAxisIn = { + type: 'linear', + range: zrange, + tickmode: opts.tickmode, + nticks: opts.nticks, + tick0: opts.tick0, + dtick: opts.dtick, + tickvals: opts.tickvals, + ticktext: opts.ticktext, + ticks: opts.ticks, + ticklen: opts.ticklen, + tickwidth: opts.tickwidth, + tickcolor: opts.tickcolor, + showticklabels: opts.showticklabels, + tickfont: opts.tickfont, + tickangle: opts.tickangle, + tickformat: opts.tickformat, + exponentformat: opts.exponentformat, + separatethousands: opts.separatethousands, + showexponent: opts.showexponent, + showtickprefix: opts.showtickprefix, + tickprefix: opts.tickprefix, + showticksuffix: opts.showticksuffix, + ticksuffix: opts.ticksuffix, + title: opts.title, + titlefont: opts.titlefont, + showline: true, + anchor: 'free', + position: 1 + }, + cbAxisOut = { + type: 'linear', + _id: 'y' + id + }, + axisOptions = { + letter: 'y', + font: fullLayout.font, + noHover: true, + calendar: fullLayout.calendar // not really necessary (yet?) + }; -/* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; -/* removed: var _$handleLabelDefaults_310 = require('./label_defaults'); */; + // Coerce w.r.t. Axes layoutAttributes: + // re-use axes.js logic without updating _fullData + function coerce(attr, dflt) { + return _$lib_172.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_226, attr, dflt); + } + // Prepare the Plotly axis object + _$handleAxisDefaults_216(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handlePositionDefaults_229(cbAxisIn, cbAxisOut, coerce, axisOptions); -var _$handleStyleDefaults_316 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { - var coloring = coerce('contours.coloring'); + // position can't go in through supplyDefaults + // because that restricts it to [0,1] + cbAxisOut.position = opts.x + xpadFrac + thickFrac; - var showLines; - var lineColor = ''; - if(coloring === 'fill') showLines = coerce('contours.showlines'); + // save for other callers to access this axis + component.axis = cbAxisOut; - if(showLines !== false) { - if(coloring !== 'lines') lineColor = coerce('line.color', '#000'); - coerce('line.width', 0.5); - coerce('line.dash'); - } + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + cbAxisOut.titleside = opts.titleside; + cbAxisOut.titlex = opts.x + xpadFrac; + cbAxisOut.titley = yBottomFrac + + (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + } - if(coloring !== 'none') { - _$colorScaleDefaults_61( - traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} - ); - } + if(opts.line.color && opts.tickmode === 'auto') { + cbAxisOut.tickmode = 'linear'; + cbAxisOut.tick0 = opts.levels.start; + var dtick = opts.levels.size; + // expand if too many contours, so we don't get too many ticks + var autoNtick = _$lib_172.constrain( + (yBottomPx - yTopPx) / 50, 4, 15) + 1, + dtFactor = (zrange[1] - zrange[0]) / + ((opts.nticks || autoNtick) * dtick); + if(dtFactor > 1) { + var dtexp = Math.pow(10, Math.floor( + Math.log(dtFactor) / Math.LN10)); + dtick *= dtexp * _$lib_172.roundUp(dtFactor / dtexp, [2, 5, 10]); + // if the contours are at round multiples, reset tick0 + // so they're still at round multiples. Otherwise, + // keep the first label on the first contour level + if((Math.abs(opts.levels.start) / + opts.levels.size + 1e-6) % 1 < 2e-6) { + cbAxisOut.tick0 = 0; + } + } + cbAxisOut.dtick = dtick; + } - coerce('line.smoothing'); + // set domain after init, because we may want to + // allow it outside [0,1] + cbAxisOut.domain = [ + yBottomFrac + ypadFrac, + yBottomFrac + lenFrac - ypadFrac + ]; + cbAxisOut.setScale(); - _$handleLabelDefaults_310(coerce, layout, lineColor, opts); -}; + // now draw the elements + var container = _$lib_172.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_15.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + container.attr('transform', 'translate(' + Math.round(gs.l) + + ',' + Math.round(gs.t) + ')'); + // TODO: this opposite transform is a hack until we make it + // more rational which items get this offset + var titleCont = container.select('.cbtitleunshift') + .attr('transform', 'translate(-' + + Math.round(gs.l) + ',-' + + Math.round(gs.t) + ')'); + cbAxisOut._axislayer = container.select('.cbaxis'); + var titleHeight = 0; + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // draw the title so we know how much room it needs + // when we squish the axis. This one only applies to + // top or bottom titles, not right side. + var x = gs.l + (opts.x + xpadFrac) * gs.w, + fontSize = cbAxisOut.titlefont.size, + y; -'use strict'; + if(opts.titleside === 'top') { + y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + + gs.t + 3 + fontSize * 0.75; + } + else { + y = (1 - (yBottomFrac + ypadFrac)) * gs.h + + gs.t - 3 - fontSize * 0.25; + } + drawTitle(cbAxisOut._id + 'title', { + attributes: {x: x, y: y, 'text-anchor': 'start'} + }); + } -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_333 = _$lib_171.isArrayOrTypedArray; + function drawAxis() { + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // squish the axis top to make room for the title + var titleGroup = container.select('.cbtitle'), + titleText = titleGroup.select('text'), + titleTrans = + [-opts.outlinewidth / 2, opts.outlinewidth / 2], + mathJaxNode = titleGroup + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + lineSize = 15.6; + if(titleText.node()) { + lineSize = + parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_55; + } + if(mathJaxNode) { + titleHeight = _$drawing_76.bBox(mathJaxNode).height; + if(titleHeight > lineSize) { + // not entirely sure how mathjax is doing + // vertical alignment, but this seems to work. + titleTrans[1] -= (titleHeight - lineSize) / 2; + } + } + else if(titleText.node() && + !titleText.classed(cn.jsPlaceholder)) { + titleHeight = _$drawing_76.bBox(titleText.node()).height; + } + if(titleHeight) { + // buffer btwn colorbar and title + // TODO: configurable + titleHeight += 5; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$has_columns_324 = require('./has_columns'); */; + if(opts.titleside === 'top') { + cbAxisOut.domain[1] -= titleHeight / gs.h; + titleTrans[1] *= -1; + } + else { + cbAxisOut.domain[0] += titleHeight / gs.h; + var nlines = _$svg_text_utils_193.lineCount(titleText); + titleTrans[1] += (1 - nlines) * lineSize; + } -var _$handleXYZDefaults_333 = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) { - var z = coerce('z'); - xName = xName || 'x'; - yName = yName || 'y'; - var x, y; + titleGroup.attr('transform', + 'translate(' + titleTrans + ')'); - if(z === undefined || !z.length) return 0; + cbAxisOut.setScale(); + } + } - if(_$has_columns_324(traceIn)) { - x = coerce(xName); - y = coerce(yName); + container.selectAll('.cbfills,.cblines') + .attr('transform', 'translate(0,' + + Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); - // column z must be accompanied by xName and yName arrays - if(!x || !y) return 0; - } - else { - x = coordDefaults(xName, coerce); - y = coordDefaults(yName, coerce); + cbAxisOut._axislayer.attr('transform', 'translate(0,' + + Math.round(-gs.t) + ')'); - // TODO put z validation elsewhere - if(!isValidZ(z)) return 0; + var fills = container.select('.cbfills') + .selectAll('rect.cbfill') + .data(filllevels); + fills.enter().append('rect') + .classed(cn.cbfill, true) + .style('stroke', 'none'); + fills.exit().remove(); + fills.each(function(d, i) { + var z = [ + (i === 0) ? zrange[0] : + (filllevels[i] + filllevels[i - 1]) / 2, + (i === filllevels.length - 1) ? zrange[1] : + (filllevels[i] + filllevels[i + 1]) / 2 + ] + .map(cbAxisOut.c2p) + .map(Math.round); - coerce('transpose'); - } + // offset the side adjoining the next rectangle so they + // overlap, to prevent antialiasing gaps + if(i !== filllevels.length - 1) { + z[1] += (z[1] > z[0]) ? 1 : -1; + } - var handleCalendarDefaults = _$registry_261.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout); - return traceOut.z.length; -}; + // Tinycolor can't handle exponents and + // at this scale, removing it makes no difference. + var colorString = fillcolormap(d).replace('e-', ''), + opaqueColor = _$tinycolor_33(colorString).toHexString(); -function coordDefaults(coordStr, coerce) { - var coord = coerce(coordStr), - coordType = coord ? - coerce(coordStr + 'type', 'array') : - 'scaled'; + // Colorbar cannot currently support opacities so we + // use an opaque fill even when alpha channels present + _$d3_15.select(this).attr({ + x: xLeft, + width: Math.max(thickPx, 2), + y: _$d3_15.min(z), + height: Math.max(_$d3_15.max(z) - _$d3_15.min(z), 2), + fill: opaqueColor + }); + }); - if(coordType === 'scaled') { - coerce(coordStr + '0'); - coerce('d' + coordStr); - } + var lines = container.select('.cblines') + .selectAll('path.cbline') + .data(opts.line.color && opts.line.width ? + linelevels : []); + lines.enter().append('path') + .classed(cn.cbline, true); + lines.exit().remove(); + lines.each(function(d) { + _$d3_15.select(this) + .attr('d', 'M' + xLeft + ',' + + (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + + 'h' + thickPx) + .call(_$drawing_76.lineGroupStyle, + opts.line.width, linecolormap(d), opts.line.dash); + }); - return coord; -} + // force full redraw of labels and ticks + cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') + .remove(); -function isValidZ(z) { - var allRowsAreArrays = true, - oneRowIsFilled = false, - hasOneNumber = false, - zi; + cbAxisOut._pos = xLeft + thickPx + + (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); + cbAxisOut.side = 'right'; - /* - * Without this step: - * - * hasOneNumber = false breaks contour but not heatmap - * allRowsAreArrays = false breaks contour but not heatmap - * oneRowIsFilled = false breaks both - */ + // separate out axis and title drawing, + // so we don't need such complicated logic in Titles.draw + // if title is on the top or bottom, we've already drawn it + // this title call only handles side=right + return _$lib_172.syncOrAsync([ + function() { + return _$axes_214.doTicks(gd, cbAxisOut, true); + }, + function() { + if(['top', 'bottom'].indexOf(opts.titleside) === -1) { + var fontSize = cbAxisOut.titlefont.size, + y = cbAxisOut._offset + cbAxisOut._length / 2, + x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? + 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : + -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); - for(var i = 0; i < z.length; i++) { - zi = z[i]; - if(!__isArrayOrTypedArray_333(zi)) { - allRowsAreArrays = false; - break; - } - if(zi.length > 0) oneRowIsFilled = true; - for(var j = 0; j < zi.length; j++) { - if(_$fastIsnumeric_18(zi[j])) { - hasOneNumber = true; - break; - } + // the 'h' + is a hack to get around the fact that + // convertToTspans rotates any 'y...' class by 90 degrees. + // TODO: find a better way to control this. + drawTitle('h' + cbAxisOut._id + 'title', { + avoid: { + selection: _$d3_15.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), + side: opts.titleside, + offsetLeft: gs.l, + offsetTop: 0, + maxShift: fullLayout.width + }, + attributes: {x: x, y: y, 'text-anchor': 'middle'}, + transform: {rotate: '-90', offset: 0} + }); + } + }]); } - } - - return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; - -/* removed: var _$has_columns_324 = require('../heatmap/has_columns'); */; -/* removed: var _$handleXYZDefaults_333 = require('../heatmap/xyz_defaults'); */; -/* removed: var _$handleConstraintDefaults_300 = require('./constraint_defaults'); */; -/* removed: var _$handleContourDefaults_302 = require('./contours_defaults'); */; -/* removed: var _$handleStyleDefaults_316 = require('./style_defaults'); */; -/* removed: var _$attributes_295 = require('./attributes'); */; + function drawTitle(titleClass, titleOpts) { + var trace = getTrace(), + propName; + if(_$registry_262.traceIs(trace, 'markerColorscale')) { + propName = 'marker.colorbar.title'; + } + else propName = 'colorbar.title'; + var dfltTitleOpts = { + propContainer: cbAxisOut, + propName: propName, + traceIndex: trace.index, + placeholder: fullLayout._dfltTitle.colorbar, + containerGroup: container.select('.cbtitle') + }; -var _$supplyDefaults_304 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_295, attr, dflt); - } + // this class-to-rotate thing with convertToTspans is + // getting hackier and hackier... delete groups with the + // wrong class (in case earlier the colorbar was drawn on + // a different side, I think?) + var otherClass = titleClass.charAt(0) === 'h' ? + titleClass.substr(1) : ('h' + titleClass); + container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') + .remove(); - function coerce2(attr) { - return _$lib_171.coerce2(traceIn, traceOut, _$attributes_295, attr); - } + _$titles_144.draw(gd, titleClass, + __extendFlat_55(dfltTitleOpts, titleOpts || {})); + } - var len = _$handleXYZDefaults_333(traceIn, traceOut, coerce, layout); - if(!len) { - traceOut.visible = false; - return; - } + function positionCB() { + // wait for the axis & title to finish rendering before + // continuing positioning + // TODO: why are we redrawing multiple times now with this? + // I guess autoMargin doesn't like being post-promise? + var innerWidth = thickPx + opts.outlinewidth / 2 + + _$drawing_76.bBox(cbAxisOut._axislayer.node()).width; + titleEl = titleCont.select('text'); + if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { + var mathJaxNode = titleCont + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + titleWidth; + if(mathJaxNode && + ['top', 'bottom'].indexOf(opts.titleside) !== -1) { + titleWidth = _$drawing_76.bBox(mathJaxNode).width; + } + else { + // note: the formula below works for all titlesides, + // (except for top/bottom mathjax, above) + // but the weird gs.l is because the titleunshift + // transform gets removed by Drawing.bBox + titleWidth = + _$drawing_76.bBox(titleCont.node()).right - + xLeft - gs.l; + } + innerWidth = Math.max(innerWidth, titleWidth); + } - coerce('text'); - var isConstraint = (coerce('contours.type') === 'constraint'); - coerce('connectgaps', _$has_columns_324(traceOut)); + var outerwidth = 2 * opts.xpad + innerWidth + + opts.borderwidth + opts.outlinewidth / 2, + outerheight = yBottomPx - yTopPx; - // trace-level showlegend has already been set, but is only allowed if this is a constraint - if(!isConstraint) delete traceOut.showlegend; + container.select('.cbbg').attr({ + x: xLeft - opts.xpad - + (opts.borderwidth + opts.outlinewidth) / 2, + y: yTopPx - yExtraPx, + width: Math.max(outerwidth, 2), + height: Math.max(outerheight + 2 * yExtraPx, 2) + }) + .call(_$color_51.fill, opts.bgcolor) + .call(_$color_51.stroke, opts.bordercolor) + .style({'stroke-width': opts.borderwidth}); - if(isConstraint) { - _$handleConstraintDefaults_300(traceIn, traceOut, coerce, layout, defaultColor); - } - else { - _$handleContourDefaults_302(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_316(traceIn, traceOut, coerce, layout); - } -}; + container.selectAll('.cboutline').attr({ + x: xLeft, + y: yTopPx + opts.ypad + + (opts.titleside === 'top' ? titleHeight : 0), + width: Math.max(thickPx, 2), + height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) + }) + .call(_$color_51.stroke, opts.outlinecolor) + .style({ + fill: 'None', + 'stroke-width': opts.outlinewidth + }); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // fix positioning for xanchor!='left' + var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * + outerwidth; + container.attr('transform', + 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); + // auto margin adjustment + _$plots_246.autoMargin(gd, id, { + x: opts.x, + y: opts.y, + l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), + r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), + t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), + b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) + }); + } -'use strict'; + var cbDone = _$lib_172.syncOrAsync([ + _$plots_246.previousPromises, + drawAxis, + _$plots_246.previousPromises, + positionCB + ], gd); -/* removed: var _$fx_93 = require('../../components/fx'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; + if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); -var _$hoverPoints_325 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { - var cd0 = pointData.cd[0]; - var trace = cd0.trace; - var xa = pointData.xa; - var ya = pointData.ya; - var x = cd0.x; - var y = cd0.y; - var z = cd0.z; - var xc = cd0.xCenter; - var yc = cd0.yCenter; - var zmask = cd0.zmask; - var range = [trace.zmin, trace.zmax]; - var zhoverformat = trace.zhoverformat; - var x2 = x; - var y2 = y; + // dragging... + if(gd._context.edits.colorbarPosition) { + var t0, + xf, + yf; - var xl, yl, nx, ny; + _$dragelement_73.init({ + element: container.node(), + gd: gd, + prepFn: function() { + t0 = container.attr('transform'); + _$setCursor_191(container); + }, + moveFn: function(dx, dy) { + container.attr('transform', + t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); - if(pointData.index !== false) { - try { - nx = Math.round(pointData.index[1]); - ny = Math.round(pointData.index[0]); - } - catch(e) { - _$lib_171.error('Error hovering on heatmap, ' + - 'pointNumber must be [row,col], found:', pointData.index); - return; - } - if(nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) { - return; - } - } - else if(_$fx_93.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || - _$fx_93.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) { - return; - } - else { - if(contour) { - var i2; - x2 = [2 * x[0] - x[1]]; + xf = _$dragelement_73.align(xLeftFrac + (dx / gs.w), thickFrac, + 0, 1, opts.xanchor); + yf = _$dragelement_73.align(yBottomFrac - (dy / gs.h), lenFrac, + 0, 1, opts.yanchor); - for(i2 = 1; i2 < x.length; i2++) { - x2.push((x[i2] + x[i2 - 1]) / 2); - } - x2.push([2 * x[x.length - 1] - x[x.length - 2]]); + var csr = _$dragelement_73.getCursor(xf, yf, + opts.xanchor, opts.yanchor); + _$setCursor_191(container, csr); + }, + doneFn: function() { + _$setCursor_191(container); - y2 = [2 * y[0] - y[1]]; - for(i2 = 1; i2 < y.length; i2++) { - y2.push((y[i2] + y[i2 - 1]) / 2); - } - y2.push([2 * y[y.length - 1] - y[y.length - 2]]); + if(xf !== undefined && yf !== undefined) { + _$registry_262.call('restyle', + gd, + {'colorbar.x': xf, 'colorbar.y': yf}, + getTrace().index + ); + } + } + }); } - nx = Math.max(0, Math.min(x2.length - 2, _$lib_171.findBin(xval, x2))); - ny = Math.max(0, Math.min(y2.length - 2, _$lib_171.findBin(yval, y2))); + return cbDone; } - var x0 = xa.c2p(x[nx]), - x1 = xa.c2p(x[nx + 1]), - y0 = ya.c2p(y[ny]), - y1 = ya.c2p(y[ny + 1]); - - if(contour) { - x1 = x0; - xl = x[nx]; - y1 = y0; - yl = y[ny]; - } - else { - xl = xc ? xc[nx] : ((x[nx] + x[nx + 1]) / 2); - yl = yc ? yc[ny] : ((y[ny] + y[ny + 1]) / 2); - if(trace.zsmooth) { - x0 = x1 = xa.c2p(xl); - y0 = y1 = ya.c2p(yl); + function getTrace() { + var idNum = id.substr(2), + i, + trace; + for(i = 0; i < gd._fullData.length; i++) { + trace = gd._fullData[i]; + if(trace.uid === idNum) return trace; } } - var zVal = z[ny][nx]; - if(zmask && !zmask[ny][nx]) zVal = undefined; + // setter/getters for every item defined in opts + Object.keys(opts).forEach(function(name) { + component[name] = function(v) { + // getter + if(!arguments.length) return opts[name]; - var text; - if(Array.isArray(cd0.text) && Array.isArray(cd0.text[ny])) { - text = cd0.text[ny][nx]; - } + // setter - for multi-part properties, + // set only the parts that are provided + opts[name] = _$lib_172.isPlainObject(opts[name]) ? + _$lib_172.extendFlat(opts[name], v) : + v; - var zLabel; - // dummy axis for formatting the z value - var dummyAx = { - type: 'linear', - range: range, - hoverformat: zhoverformat, - _separators: xa._separators, - _numFormat: xa._numFormat + return component; + }; + }); + + // or use .options to set multiple options at once via a dictionary + component.options = function(o) { + Object.keys(o).forEach(function(name) { + // in case something random comes through + // that's not an option, ignore it + if(typeof component[name] === 'function') { + component[name](o[name]); + } + }); + return component; }; - var zLabelObj = _$axes_213.tickText(dummyAx, zVal, 'hover'); - zLabel = zLabelObj.text; - return [_$lib_171.extendFlat(pointData, { - index: [ny, nx], - // never let a 2D override 1D type as closest point - distance: pointData.maxHoverDistance, - spikeDistance: pointData.maxSpikeDistance, - x0: x0, - x1: x1, - y0: y0, - y1: y1, - xLabelVal: xl, - yLabelVal: yl, - zLabelVal: zVal, - zLabel: zLabel, - text: text - })]; + component._opts = opts; + + return component; }; /** @@ -40154,94 +40266,48 @@ var _$hoverPoints_325 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -/* removed: var _$color_51 = require('../../components/color'); */; - -/* removed: var _$hoverPoints_325 = require('../heatmap/hover'); */; - -var _$hoverPoints_308 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { - var hoverData = _$hoverPoints_325(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_51.opacity(trace.fillcolor)) { - hoverPt.color = _$color_51.addOpacity(trace.fillcolor, 1); - } - else if(trace.contours.showlines && _$color_51.opacity(trace.line.color)) { - hoverPt.color = _$color_51.addOpacity(trace.line.color, 1); - } - } - }); - } +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - return hoverData; -}; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$colorscale_66 = require('../../components/colorscale'); */; +/* removed: var _$draw_55 = require('../../components/colorbar/draw'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; +var _$colorbar_373 = function colorbar(gd, cd) { + var trace = cd[0].trace, + marker = trace.marker, + cbId = 'cb' + trace.uid; -var _$close_boundaries_297 = function(pathinfo, operation, perimeter, trace) { - // Abandon all hope, ye who enter here. - var i, v1, v2; - var pi0 = pathinfo[0]; - var na = pi0.x.length; - var nb = pi0.y.length; - var z = pi0.z; - var contours = trace.contours; + gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); - var boundaryMax = -Infinity; - var boundaryMin = Infinity; + // TODO make Colorbar.draw support multiple colorbar per trace - for(i = 0; i < nb; i++) { - boundaryMin = Math.min(boundaryMin, z[i][0]); - boundaryMin = Math.min(boundaryMin, z[i][na - 1]); - boundaryMax = Math.max(boundaryMax, z[i][0]); - boundaryMax = Math.max(boundaryMax, z[i][na - 1]); + if((marker === undefined) || !marker.showscale) { + _$plots_246.autoMargin(gd, cbId); + return; } - for(i = 1; i < na - 1; i++) { - boundaryMin = Math.min(boundaryMin, z[0][i]); - boundaryMin = Math.min(boundaryMin, z[nb - 1][i]); - boundaryMax = Math.max(boundaryMax, z[0][i]); - boundaryMax = Math.max(boundaryMax, z[nb - 1][i]); - } + var vals = marker.color, + cmin = marker.cmin, + cmax = marker.cmax; - pi0.prefixBoundary = false; + if(!_$fastIsnumeric_18(cmin)) cmin = _$lib_172.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_18(cmax)) cmax = _$lib_172.aggNums(Math.max, null, vals); - switch(operation) { - case '>': - if(contours.value > boundaryMax) { - pi0.prefixBoundary = true; - } - break; - case '<': - if(contours.value < boundaryMin) { - pi0.prefixBoundary = true; - } - break; - case '[]': - v1 = Math.min.apply(null, contours.value); - v2 = Math.max.apply(null, contours.value); - if(v2 < boundaryMin || v1 > boundaryMax) { - pi0.prefixBoundary = true; - } - break; - case '][': - v1 = Math.min.apply(null, contours.value); - v2 = Math.max.apply(null, contours.value); - if(v1 < boundaryMin && v2 > boundaryMax) { - pi0.prefixBoundary = true; - } - break; - } + var cb = cd[0].t.cb = _$draw_55(gd, cbId); + var sclFunc = _$colorscale_66.makeColorScaleFunc( + _$colorscale_66.extractScale( + marker.colorscale, + cmin, + cmax + ), + { noNumericCheck: true } + ); + + cb.fillcolor(sclFunc) + .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) + .options(marker.colorbar)(); }; /** @@ -40252,75 +40318,34 @@ var _$close_boundaries_297 = function(pathinfo, operation, perimeter, trace) { * LICENSE file in the root directory of this source tree. */ -'use strict'; -var _$constants_299 = { - // some constants to help with marching squares algorithm - // where does the path start for each index? - BOTTOMSTART: [1, 9, 13, 104, 713], - TOPSTART: [4, 6, 7, 104, 713], - LEFTSTART: [8, 12, 14, 208, 1114], - RIGHTSTART: [2, 3, 11, 208, 1114], - - // which way [dx,dy] do we leave a given index? - // saddles are already disambiguated - NEWDELTA: [ - null, [-1, 0], [0, -1], [-1, 0], - [1, 0], null, [0, -1], [-1, 0], - [0, 1], [0, 1], null, [0, 1], - [1, 0], [1, 0], [0, -1] - ], - - // for each saddle, the first index here is used - // for dx||dy<0, the second for dx||dy>0 - CHOOSESADDLE: { - 104: [4, 1], - 208: [2, 8], - 713: [7, 13], - 1114: [11, 14] - }, - - // after one index has been used for a saddle, which do we - // substitute to be used up later? - SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11}, - - // length of a contour, as a multiple of the plot area diagonal, per label - LABELDISTANCE: 2, - // number of contour levels after which we start increasing the number of - // labels we draw. Many contours means they will generally be close - // together, so it will be harder to follow a long way to find a label - LABELINCREASE: 10, +'use strict'; - // minimum length of a contour line, as a multiple of the label length, - // at which we draw *any* labels - LABELMIN: 3, +var Bar = {}; - // max number of labels to draw on a single contour path, no matter how long - LABELMAX: 10, +Bar.attributes = _$attributes_272; +Bar.layoutAttributes = _$layout_attributes_277; +Bar.supplyDefaults = _$supplyDefaults_274; +Bar.supplyLayoutDefaults = _$layout_defaults_278; +Bar.calc = _$calc_273; +Bar.setPositions = _$setPositions_281; +Bar.colorbar = _$colorbar_373; +Bar.arraysToCalcdata = _$arraysToCalcdata_271; +Bar.plot = _$plot_279; +Bar.style = _$style_283; +Bar.hoverPoints = _$hoverPoints_275; +Bar.selectPoints = _$selectPoints_280; - // constants for the label position cost function - LABELOPTIMIZER: { - // weight given to edge proximity - EDGECOST: 1, - // weight given to the angle off horizontal - ANGLECOST: 1, - // weight given to distance from already-placed labels - NEIGHBORCOST: 5, - // cost multiplier for labels on the same level - SAMELEVELFACTOR: 10, - // minimum distance (as a multiple of the label length) - // for labels on the same level - SAMELEVELDISTANCE: 5, - // maximum cost before we won't even place the label - MAXCOST: 100, - // number of evenly spaced points to look at in the first - // iteration of the search - INITIALSEARCHPOINTS: 10, - // number of binary search iterations after the initial wide search - ITERATIONS: 5 - } +Bar.moduleType = 'trace'; +Bar.name = 'bar'; +Bar.basePlotModule = _$cartesian_225; +Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend', 'draggedPts']; +Bar.meta = { + }; +var _$Bar_276 = Bar; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40331,82 +40356,7 @@ var _$constants_299 = { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; - -// 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. -var _$convert_to_constraints_303 = 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_171.warn('Contour data invalid for the specified inequality operation.'); - } - - // In this case there should be exactly two contour levels in pathinfo. We - // simply concatenate the info into one pathinfo and flip all of the data - // in one. 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]); - } - 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_171.warn('Contour data invalid for the specified inequality range operation.'); - } - - // In this case there should be exactly two contour levels in pathinfo. We - // simply concatenate the info into one pathinfo and flip all of the data - // in one. This will draw the contour 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]); - } - - while(pi1.edgepaths.length) { - pi0.edgepaths.push(op1(pi1.edgepaths.shift())); - } - while(pi1.paths.length) { - pi0.paths.push(op1(pi1.paths.shift())); - } - return [pi0]; - } -}; - -function copyPathinfo(pi) { - return _$lib_171.extendFlat({}, pi, { - edgepaths: _$lib_171.extendDeep([], pi.edgepaths), - paths: _$lib_171.extendDeep([], pi.paths) - }); -} +var _$bar_3 = _$Bar_276; /** * Copyright 2012-2018, Plotly, Inc. @@ -40418,73 +40368,186 @@ function copyPathinfo(pi) { 'use strict'; -/* removed: var _$filter_ops_152 = require('../../constants/filter_ops'); */; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -// This syntax conforms to the existing filter transform syntax, but we don't care -// about open vs. closed intervals for simply drawing contours constraints: -var _$constraint_mapping_301 = { - '[]': makeRangeSettings('[]'), - '][': makeRangeSettings(']['), - '>': makeInequalitySettings('>'), - '<': makeInequalitySettings('<'), - '=': makeInequalitySettings('=') -}; - -// This does not in any way shape or form support calendars. It's adapted from -// transforms/filter.js. -function coerceValue(operation, value) { - var hasArrayValue = Array.isArray(value); - - var coercedValue; +/* removed: var _$attributes_369 = require('../scatter/attributes'); */; +/* removed: var _$attributes_50 = require('../../components/color/attributes'); */; +var __extendFlat_285 = _$extend_166.extendFlat; - function coerce(value) { - return _$fastIsnumeric_18(value) ? (+value) : null; - } +var __scatterMarkerAttrs_285 = _$attributes_369.marker; +var __scatterMarkerLineAttrs_285 = __scatterMarkerAttrs_285.line; - if(_$filter_ops_152.COMPARISON_OPS2.indexOf(operation) !== -1) { - coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value); - } else if(_$filter_ops_152.INTERVAL_OPS.indexOf(operation) !== -1) { - coercedValue = hasArrayValue ? - [coerce(value[0]), coerce(value[1])] : - [coerce(value), coerce(value)]; - } else if(_$filter_ops_152.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 - }; - }; -} +var _$attributes_285 = { + 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', + + }, + name: { + valType: 'string', + + editType: 'calc+clearAxisTypes', + + }, + text: __extendFlat_285({}, _$attributes_369.text, { + + }), + whiskerwidth: { + valType: 'number', + min: 0, + max: 1, + dflt: 0.5, + + editType: 'calcIfAutorange', + + }, + notched: { + valType: 'boolean', + + editType: 'calcIfAutorange', + + }, + notchwidth: { + valType: 'number', + min: 0, + max: 0.5, + dflt: 0.25, + + editType: 'calcIfAutorange', + + }, + boxpoints: { + valType: 'enumerated', + values: ['all', 'outliers', 'suspectedoutliers', false], + dflt: 'outliers', + + editType: 'calcIfAutorange', + + }, + boxmean: { + valType: 'enumerated', + values: [true, 'sd', false], + dflt: false, + + editType: 'calcIfAutorange', + + }, + jitter: { + valType: 'number', + min: 0, + max: 1, + + editType: 'calcIfAutorange', + + }, + pointpos: { + valType: 'number', + min: -2, + max: 2, + + editType: 'calcIfAutorange', + + }, + orientation: { + valType: 'enumerated', + values: ['v', 'h'], + + editType: 'calc+clearAxisTypes', + + }, + marker: { + outliercolor: { + valType: 'color', + dflt: 'rgba(0, 0, 0, 0)', + + editType: 'style', + + }, + symbol: __extendFlat_285({}, __scatterMarkerAttrs_285.symbol, + {arrayOk: false, editType: 'plot'}), + opacity: __extendFlat_285({}, __scatterMarkerAttrs_285.opacity, + {arrayOk: false, dflt: 1, editType: 'style'}), + size: __extendFlat_285({}, __scatterMarkerAttrs_285.size, + {arrayOk: false, editType: 'calcIfAutorange'}), + color: __extendFlat_285({}, __scatterMarkerAttrs_285.color, + {arrayOk: false, editType: 'style'}), + line: { + color: __extendFlat_285({}, __scatterMarkerLineAttrs_285.color, + {arrayOk: false, dflt: _$attributes_50.defaultLine, editType: 'style'} + ), + width: __extendFlat_285({}, __scatterMarkerLineAttrs_285.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: _$attributes_369.fillcolor, -function makeInequalitySettings(operation) { - return function(value) { - value = coerceValue(operation, value); + selected: { + marker: _$attributes_369.selected.marker, + editType: 'style' + }, + unselected: { + marker: _$attributes_369.unselected.marker, + editType: 'style' + }, - return { - start: value, - end: Infinity, - size: Infinity - }; - }; -} + hoveron: { + valType: 'flaglist', + flags: ['boxes', 'points'], + dflt: 'boxes+points', + + editType: 'style', + + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -40496,449 +40559,339 @@ function makeInequalitySettings(operation) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$constraint_mapping_301 = require('./constraint_mapping'); */; -/* removed: var _$endPlus_306 = require('./end_plus'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var _$emptyPathinfo_305 = function emptyPathinfo(contours, plotinfo, cd0) { - var contoursFinal = (contours.type === 'constraint') ? - _$constraint_mapping_301[contours._operation](contours.value) : - contours; +/* removed: var _$lib_172 = require('../../lib'); */; +var ____286 = _$lib_172._; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; - var cs = contoursFinal.size; - var pathinfo = []; - var end = _$endPlus_306(contoursFinal); +// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html +var _$calc_286 = function calc(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axes_214.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_214.getFromId(gd, trace.yaxis || 'y'); + var cd = []; - var carpet = cd0.trace.carpetTrace; + // N.B. violin reuses same Box.calc + var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes'; - 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 - }; + var i; + var valAxis, valLetter; + var posAxis, posLetter; - for(var ci = contoursFinal.start; ci < end; ci += cs) { - pathinfo.push(_$lib_171.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(trace.orientation === 'h') { + valAxis = xa; + valLetter = 'x'; + posAxis = ya; + posLetter = 'y'; + } else { + valAxis = ya; + valLetter = 'y'; + posAxis = xa; + posLetter = 'x'; + } - if(pathinfo.length > 1000) { - _$lib_171.warn('Too many contours, clipping at 1000', contours); - break; + var val = valAxis.makeCalcdata(trace, valLetter); + var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]); + + var dv = _$lib_172.distinctVals(pos); + var posDistinct = dv.vals; + var dPos = dv.minDiff / 2; + var posBins = makeBins(posDistinct, dPos); + + var vLen = val.length; + var pLen = posDistinct.length; + var ptsPerBin = initNestedArray(pLen); + + // bin pts info per position bins + for(i = 0; i < vLen; i++) { + var v = val[i]; + if(!_$fastIsnumeric_18(v)) continue; + + var n = _$lib_172.findBin(pos[i], posBins); + if(n >= 0 && n < pLen) { + var pt = {v: v, i: i}; + __arraysToCalcdata_286(pt, trace, i); + ptsPerBin[n].push(pt); } } - return pathinfo; -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // build calcdata trace items, one item per distinct position + for(i = 0; i < pLen; i++) { + if(ptsPerBin[i].length > 0) { + var pts = ptsPerBin[i].sort(sortByVal); + var boxVals = pts.map(extractVal); + var bvLen = boxVals.length; -'use strict'; + var cdi = { + pos: posDistinct[i], + pts: pts + }; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$constants_299 = require('./constants'); */; + cdi.min = boxVals[0]; + cdi.max = boxVals[bvLen - 1]; + cdi.mean = _$lib_172.mean(boxVals, bvLen); + cdi.sd = _$lib_172.stdev(boxVals, bvLen, cdi.mean); -var _$findAllPaths_307 = function findAllPaths(pathinfo, xtol, ytol) { - var cnt, - startLoc, - i, - pi, - j; + // first quartile + cdi.q1 = _$lib_172.interp(boxVals, 0.25); + // median + cdi.med = _$lib_172.interp(boxVals, 0.5); + // third quartile + cdi.q3 = _$lib_172.interp(boxVals, 0.75); - // Default just passes these values through as they were before: - xtol = xtol || 0.01; - ytol = ytol || 0.01; + // lower and upper fences - last point inside + // 1.5 interquartile ranges from quartiles + cdi.lf = Math.min( + cdi.q1, + boxVals[Math.min( + _$lib_172.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, + bvLen - 1 + )] + ); + cdi.uf = Math.max( + cdi.q3, + boxVals[Math.max( + _$lib_172.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), + 0 + )] + ); - for(i = 0; i < pathinfo.length; i++) { - pi = pathinfo[i]; + // lower and upper outliers - 3 IQR out (don't clip to max/min, + // this is only for discriminating suspected & far outliers) + cdi.lo = 4 * cdi.q1 - 3 * cdi.q3; + cdi.uo = 4 * cdi.q3 - 3 * cdi.q1; - for(j = 0; j < pi.starts.length; j++) { - startLoc = pi.starts[j]; - makePath(pi, startLoc, 'edge', xtol, ytol); - } - cnt = 0; - while(Object.keys(pi.crossings).length && cnt < 10000) { - cnt++; - startLoc = Object.keys(pi.crossings)[0].split(',').map(Number); - makePath(pi, startLoc, undefined, xtol, ytol); + // lower and upper notches ~95% Confidence Intervals for median + var iqr = cdi.q3 - cdi.q1; + var mci = 1.57 * iqr / Math.sqrt(bvLen); + cdi.ln = cdi.med - mci; + cdi.un = cdi.med + mci; + + cd.push(cdi); } - if(cnt === 10000) _$lib_171.log('Infinite loop in contour?'); } -}; - -function equalPts(pt1, pt2, xtol, ytol) { - return Math.abs(pt1[0] - pt2[0]) < xtol && - Math.abs(pt1[1] - pt2[1]) < ytol; -} -// distance in index units - uses the 3rd and 4th items in points -function ptDist(pt1, pt2) { - var dx = pt1[2] - pt2[2], - dy = pt1[3] - pt2[3]; - return Math.sqrt(dx * dx + dy * dy); -} + __calcSelection_286(cd, trace); + _$axes_214.expand(valAxis, val, {padded: true}); -function makePath(pi, loc, edgeflag, xtol, ytol) { - var startLocStr = loc.join(','); - var locStr = startLocStr; - var mi = pi.crossings[locStr]; - var marchStep = startStep(mi, edgeflag, loc); - // start by going backward a half step and finding the crossing point - var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])]; - var startStepStr = marchStep.join(','); - var m = pi.z.length; - var n = pi.z[0].length; - var cnt; + if(cd.length > 0) { + cd[0].t = { + num: fullLayout[numKey], + dPos: dPos, + posLetter: posLetter, + valLetter: valLetter, + labels: { + med: ____286(gd, 'median:'), + min: ____286(gd, 'min:'), + q1: ____286(gd, 'q1:'), + q3: ____286(gd, 'q3:'), + max: ____286(gd, 'max:'), + mean: trace.boxmean === 'sd' ? ____286(gd, 'mean ± σ:') : ____286(gd, 'mean:'), + lf: ____286(gd, 'lower fence:'), + uf: ____286(gd, 'upper fence:') + } + }; - // now follow the path - for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops - if(mi > 20) { - mi = _$constants_299.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1]; - pi.crossings[locStr] = _$constants_299.SADDLEREMAINDER[mi]; - } - else { - delete pi.crossings[locStr]; - } + fullLayout[numKey]++; + return cd; + } else { + return [{t: {empty: true}}]; + } +}; - marchStep = _$constants_299.NEWDELTA[mi]; - if(!marchStep) { - _$lib_171.log('Found bad marching index:', mi, loc, pi.level); - break; - } +// 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, val, num) { + if(posLetter in trace) { + return posAxis.makeCalcdata(trace, posLetter); + } - // find the crossing a half step forward, and then take the full step - pts.push(getInterpPx(pi, loc, marchStep)); - loc[0] += marchStep[0]; - loc[1] += marchStep[1]; + var pos0; - // don't include the same point multiple times - if(equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop(); - locStr = loc.join(','); + if(posLetter + '0' in trace) { + pos0 = trace[posLetter + '0']; + } else if('name' in trace && ( + posAxis.type === 'category' || ( + _$fastIsnumeric_18(trace.name) && + ['linear', 'log'].indexOf(posAxis.type) !== -1 + ) || ( + _$lib_172.isDateTime(trace.name) && + posAxis.type === 'date' + ) + )) { + pos0 = trace.name; + } else { + pos0 = num; + } - var atEdge = (marchStep[0] && (loc[0] < 0 || loc[0] > n - 2)) || - (marchStep[1] && (loc[1] < 0 || loc[1] > m - 2)), - closedLoop = (locStr === startLocStr) && (marchStep.join(',') === startStepStr); + var pos0c = posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']); + return val.map(function() { return pos0c; }); +} - // have we completed a loop, or reached an edge? - if((closedLoop) || (edgeflag && atEdge)) break; +function makeBins(x, dx) { + var len = x.length; + var bins = new Array(len + 1); - mi = pi.crossings[locStr]; + for(var i = 0; i < len; i++) { + bins[i] = x[i] - dx; } + bins[len] = x[len - 1] + dx; - if(cnt === 10000) { - _$lib_171.log('Infinite loop in contour?'); - } - var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol); - var totaldist = 0; - var distThresholdFactor = 0.2 * pi.smoothing; - var alldists = []; - var cropstart = 0; - var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist, - i, j, edgepathi, edgepathj; + return bins; +} - /* - * Check for points that are too close together (<1/5 the average dist - * *in grid index units* (important for log axes and nonuniform grids), - * less if less smoothed) and just take the center (or avg of center 2). - * This cuts down on funny behavior when a point is very close to a - * contour level. - */ - for(cnt = 1; cnt < pts.length; cnt++) { - thisdist = ptDist(pts[cnt], pts[cnt - 1]); - totaldist += thisdist; - alldists.push(thisdist); +function initNestedArray(len) { + var arr = new Array(len); + for(var i = 0; i < len; i++) { + arr[i] = []; } + return arr; +} - var distThreshold = totaldist / alldists.length * distThresholdFactor; +function __arraysToCalcdata_286(pt, trace, i) { + var trace2calc = { + text: 'tx' + }; - function getpt(i) { return pts[i % pts.length]; } + for(var k in trace2calc) { + if(Array.isArray(trace[k])) { + pt[trace2calc[k]] = trace[k][i]; + } + } +} - for(cnt = pts.length - 2; cnt >= cropstart; cnt--) { - distgroup = alldists[cnt]; - if(distgroup < distThreshold) { - cnt3 = 0; - for(cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) { - if(distgroup + alldists[cnt2] < distThreshold) { - distgroup += alldists[cnt2]; - } - else break; - } +function __calcSelection_286(cd, trace) { + if(_$lib_172.isArrayOrTypedArray(trace.selectedpoints)) { + for(var i = 0; i < cd.length; i++) { + var pts = cd[i].pts || []; + var ptNumber2cdIndex = {}; - // closed path with close points wrapping around the boundary? - if(closedpath && cnt === pts.length - 2) { - for(cnt3 = 0; cnt3 < cnt2; cnt3++) { - if(distgroup + alldists[cnt3] < distThreshold) { - distgroup += alldists[cnt3]; - } - else break; - } + for(var j = 0; j < pts.length; j++) { + ptNumber2cdIndex[pts[j].i] = j; } - ptcnt = cnt - cnt2 + cnt3 + 1; - ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2); - // either endpoint included: keep the endpoint - if(!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1]; - else if(!closedpath && cnt2 === -1) newpt = pts[0]; + _$lib_172.tagSelected(pts, trace, ptNumber2cdIndex); + } + } +} - // odd # of points - just take the central one - else if(ptcnt % 2) newpt = getpt(ptavg); +function sortByVal(a, b) { return a.v - b.v; } - // even # of pts - average central two - else { - newpt = [(getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2, - (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2]; - } +function extractVal(o) { return o.v; } - pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt); - cnt = cnt2 + 1; - if(cnt3) cropstart = cnt3; - if(closedpath) { - if(cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1]; - else if(cnt === 0) pts[pts.length - 1] = pts[0]; - } - } - } - pts.splice(0, cropstart); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // done with the index parts - remove them so path generation works right - // because it depends on only having [xpx, ypx] - for(cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2; +'use strict'; - // don't return single-point paths (ie all points were the same - // so they got deleted?) - if(pts.length < 2) return; - else if(closedpath) { - pts.pop(); - pi.paths.push(pts); +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$color_51 = require('../../components/color'); */; + +/* removed: var _$attributes_285 = require('./attributes'); */; + +function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_172.coerce(traceIn, traceOut, _$attributes_285, attr, dflt); } - else { - if(!edgeflag) { - _$lib_171.log('Unclosed interior contour?', - pi.level, startLocStr, pts.join('L')); - } - // edge path - does it start where an existing edge path ends, or vice versa? - var merged = false; - for(i = 0; i < pi.edgepaths.length; i++) { - edgepathi = pi.edgepaths[i]; - if(!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) { - pts.pop(); - merged = true; + handleSampleDefaults(traceIn, traceOut, coerce, layout); + if(traceOut.visible === false) return; - // now does it ALSO meet the end of another (or the same) path? - var doublemerged = false; - for(j = 0; j < pi.edgepaths.length; j++) { - edgepathj = pi.edgepaths[j]; - if(equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) { - doublemerged = true; - pts.shift(); - pi.edgepaths.splice(i, 1); - if(j === i) { - // the path is now closed - pi.paths.push(pts.concat(edgepathj)); - } - else { - if(j > i) j--; - pi.edgepaths[j] = edgepathj.concat(pts, edgepathi); - } - break; - } - } - if(!doublemerged) { - pi.edgepaths[i] = pts.concat(edgepathi); - } - } - } - for(i = 0; i < pi.edgepaths.length; i++) { - if(merged) break; - edgepathi = pi.edgepaths[i]; - if(equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) { - pts.shift(); - pi.edgepaths[i] = edgepathi.concat(pts); - merged = true; - } - } + coerce('line.color', (traceIn.marker || {}).color || defaultColor); + coerce('line.width'); + coerce('fillcolor', _$color_51.addOpacity(traceOut.line.color, 0.5)); - if(!merged) pi.edgepaths.push(pts); - } -} + coerce('whiskerwidth'); + coerce('boxmean'); -// special function to get the marching step of the -// first point in the path (leading to loc) -function startStep(mi, edgeflag, loc) { - var dx = 0, - dy = 0; - if(mi > 20 && edgeflag) { - // these saddles start at +/- x - if(mi === 208 || mi === 1114) { - // if we're starting at the left side, we must be going right - dx = loc[0] === 0 ? 1 : -1; - } - else { - // if we're starting at the bottom, we must be going up - dy = loc[1] === 0 ? 1 : -1; - } - } - else if(_$constants_299.BOTTOMSTART.indexOf(mi) !== -1) dy = 1; - else if(_$constants_299.LEFTSTART.indexOf(mi) !== -1) dx = 1; - else if(_$constants_299.TOPSTART.indexOf(mi) !== -1) dy = -1; - else dx = -1; - return [dx, dy]; + var notched = coerce('notched', traceIn.notchwidth !== undefined); + if(notched) coerce('notchwidth'); + + handlePointsDefaults(traceIn, traceOut, coerce, {prefix: 'box'}); } -/* - * Find the pixel coordinates of a particular crossing - * - * @param {object} pi: the pathinfo object at this level - * @param {array} loc: the grid index [x, y] of the crossing - * @param {array} step: the direction [dx, dy] we're moving on the grid - * - * @return {array} [xpx, ypx, xi, yi]: the first two are the pixel location, - * the next two are the interpolated grid indices, which we use for - * distance calculations to delete points that are too close together. - * This is important when the grid is nonuniform (and most dramatically when - * we're on log axes and include invalid (0 or negative) values. - * It's crucial to delete these extra two before turning an array of these - * points into a path, because those routines require length-2 points. - */ -function getInterpPx(pi, loc, step) { - var locx = loc[0] + Math.max(step[0], 0), - locy = loc[1] + Math.max(step[1], 0), - zxy = pi.z[locy][locx], - xa = pi.xaxis, - ya = pi.yaxis; +function handleSampleDefaults(traceIn, traceOut, coerce, layout) { + var y = coerce('y'); + var x = coerce('x'); - if(step[1]) { - var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy); + var defaultOrientation; - return [xa.c2p((1 - dx) * pi.x[locx] + dx * pi.x[locx + 1], true), - ya.c2p(pi.y[locy], true), - locx + dx, locy]; - } - else { - var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy); - return [xa.c2p(pi.x[locx], true), - ya.c2p((1 - dy) * pi.y[locy] + dy * pi.y[locy + 1], true), - locx, locy + dy]; + if(y && y.length) { + defaultOrientation = 'v'; + if(!x) coerce('x0'); + } else if(x && x.length) { + defaultOrientation = 'h'; + coerce('y0'); + } else { + traceOut.visible = false; + return; } -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 handleCalendarDefaults = _$registry_262.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); -'use strict'; + coerce('orientation', defaultOrientation); +} -/* removed: var _$constants_299 = require('./constants'); */; +function handlePointsDefaults(traceIn, traceOut, coerce, opts) { + var prefix = opts.prefix; -// Calculate all the marching indices, for ALL levels at once. -// since we want to be exhaustive we'll check for contour crossings -// at every intersection, rather than just following a path -// TODO: shorten the inner loop to only the relevant levels -var _$makeCrossings_312 = function makeCrossings(pathinfo) { - var z = pathinfo[0].z, - m = z.length, - n = z[0].length, // we already made sure z isn't ragged in interp2d - twoWide = m === 2 || n === 2, - xi, - yi, - startIndices, - ystartIndices, - label, - corners, - mi, - pi, - i; + var outlierColorDflt = _$lib_172.coerce2(traceIn, traceOut, _$attributes_285, 'marker.outliercolor'); + var lineoutliercolor = coerce('marker.line.outliercolor'); - for(yi = 0; yi < m - 1; yi++) { - ystartIndices = []; - if(yi === 0) ystartIndices = ystartIndices.concat(_$constants_299.BOTTOMSTART); - if(yi === m - 2) ystartIndices = ystartIndices.concat(_$constants_299.TOPSTART); + var points = coerce( + prefix + 'points', + (outlierColorDflt || lineoutliercolor) ? 'suspectedoutliers' : undefined + ); - for(xi = 0; xi < n - 1; xi++) { - startIndices = ystartIndices.slice(); - if(xi === 0) startIndices = startIndices.concat(_$constants_299.LEFTSTART); - if(xi === n - 2) startIndices = startIndices.concat(_$constants_299.RIGHTSTART); + if(points) { + coerce('jitter', points === 'all' ? 0.3 : 0); + coerce('pointpos', points === 'all' ? -1.5 : 0); - label = xi + ',' + yi; - corners = [[z[yi][xi], z[yi][xi + 1]], - [z[yi + 1][xi], z[yi + 1][xi + 1]]]; - for(i = 0; i < pathinfo.length; i++) { - pi = pathinfo[i]; - mi = getMarchingIndex(pi.level, corners); - if(!mi) continue; + coerce('marker.symbol'); + coerce('marker.opacity'); + coerce('marker.size'); + coerce('marker.color', traceOut.line.color); + coerce('marker.line.color'); + coerce('marker.line.width'); - pi.crossings[label] = mi; - if(startIndices.indexOf(mi) !== -1) { - pi.starts.push([xi, yi]); - if(twoWide && startIndices.indexOf(mi, - startIndices.indexOf(mi) + 1) !== -1) { - // the same square has starts from opposite sides - // it's not possible to have starts on opposite edges - // of a corner, only a start and an end... - // but if the array is only two points wide (either way) - // you can have starts on opposite sides. - pi.starts.push([xi, yi]); - } - } - } + if(points === 'suspectedoutliers') { + coerce('marker.line.outliercolor', traceOut.marker.color); + coerce('marker.line.outlierwidth'); } - } -}; -// modified marching squares algorithm, -// so we disambiguate the saddle points from the start -// and we ignore the cases with no crossings -// the index I'm using is based on: -// http://en.wikipedia.org/wiki/Marching_squares -// except that the saddles bifurcate and I represent them -// as the decimal combination of the two appropriate -// non-saddle indices -function getMarchingIndex(val, corners) { - var mi = (corners[0][0] > val ? 0 : 1) + - (corners[0][1] > val ? 0 : 2) + - (corners[1][1] > val ? 0 : 4) + - (corners[1][0] > val ? 0 : 8); - if(mi === 5 || mi === 10) { - var avg = (corners[0][0] + corners[0][1] + - corners[1][0] + corners[1][1]) / 4; - // two peaks with a big valley - if(val > avg) return (mi === 5) ? 713 : 1114; - // two valleys with a big ridge - return (mi === 5) ? 104 : 208; + coerce('selected.marker.color'); + coerce('unselected.marker.color'); + coerce('selected.marker.size'); + coerce('unselected.marker.size'); + + coerce('text'); + } else { + delete traceOut.marker; } - return (mi === 15) ? 0 : mi; + + coerce('hoveron'); + + _$lib_172.coerceSelectionMarkerOpacity(traceOut, coerce); } +var _$defaults_287 = { + supplyDefaults: supplyDefaults, + handleSampleDefaults: handleSampleDefaults, + handlePointsDefaults: handlePointsDefaults +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40947,443 +40900,338 @@ function getMarchingIndex(val, corners) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$colorscale_66 = require('../../components/colorscale'); */; -/* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; - -/* removed: var _$maxRowLength_329 = require('./max_row_length'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$fx_93 = require('../../components/fx'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$fillHoverText_377 = require('../scatter/fill_hover_text'); */; +function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var trace = cd[0].trace; + var hoveron = trace.hoveron; + var closeBoxData = []; + var closePtData; -var _$plot_330 = function(gd, plotinfo, cdheatmaps) { - for(var i = 0; i < cdheatmaps.length; i++) { - __plotOne_330(gd, plotinfo, cdheatmaps[i]); + if(hoveron.indexOf('boxes') !== -1) { + closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode)); } -}; - -function __plotOne_330(gd, plotinfo, cd) { - var cd0 = cd[0]; - var trace = cd0.trace; - var uid = trace.uid; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var fullLayout = gd._fullLayout; - var id = 'hm' + uid; - - // in case this used to be a contour map - fullLayout._paper.selectAll('.contour' + uid).remove(); - fullLayout._infolayer.selectAll('g.rangeslider-container') - .selectAll('.contour' + uid).remove(); - if(trace.visible !== true) { - fullLayout._paper.selectAll('.' + id).remove(); - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - return; + if(hoveron.indexOf('points') !== -1) { + closePtData = hoverOnPoints(pointData, xval, yval); } - var z = cd0.z; - var x = cd0.x; - var y = cd0.y; - var xc = cd0.xCenter; - var yc = cd0.yCenter; - var isContour = _$registry_261.traceIs(trace, 'contour'); - var zsmooth = isContour ? 'best' : trace.zsmooth; + // If there's a point in range and hoveron has points, show the best single point only. + // If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats. + if(hovermode === 'closest') { + if(closePtData) return [closePtData]; + return closeBoxData; + } - // get z dims - var m = z.length; - var n = _$maxRowLength_329(z); - var xrev = false; - var yrev = false; + // Otherwise in compare mode, allow a point AND the box stats to be labeled + // If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them. + if(closePtData) { + closeBoxData.push(closePtData); + return closeBoxData; + } + return closeBoxData; +} - var left, right, temp, top, bottom, i; +function hoverOnBoxes(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var xa = pointData.xa; + var ya = pointData.ya; + var trace = cd[0].trace; + var t = cd[0].t; + var isViolin = trace.type === 'violin'; + var closeBoxData = []; - // TODO: if there are multiple overlapping categorical heatmaps, - // or if we allow category sorting, then the categories may not be - // sequential... may need to reorder and/or expand z + var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos, + hoverPseudoDistance, spikePseudoDistance; - // Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates) - // figure out if either axis is reversed (y is usually reversed, in pixel coords) - // also clip the image to maximum 50% outside the visible plot area - // bigger image lets you pan more naturally, but slows performance. - // TODO: use low-resolution images outside the visible plot for panning - // these while loops find the first and last brick bounds that are defined - // (in case of log of a negative) - i = 0; - while(left === undefined && i < x.length - 1) { - left = xa.c2p(x[i]); - i++; - } - i = x.length - 1; - while(right === undefined && i > 0) { - right = xa.c2p(x[i]); - i--; - } + var boxDelta = t.bdPos; + var posAcceptance = t.wHover; + var shiftPos = function(di) { return di.pos + t.bPos - pVal; }; - if(right < left) { - temp = right; - right = left; - left = temp; - xrev = true; + if(isViolin && trace.side !== 'both') { + if(trace.side === 'positive') { + dPos = function(di) { + var pos = shiftPos(di); + return _$fx_93.inbox(pos, pos + posAcceptance, hoverPseudoDistance); + }; + } + if(trace.side === 'negative') { + dPos = function(di) { + var pos = shiftPos(di); + return _$fx_93.inbox(pos - posAcceptance, pos, hoverPseudoDistance); + }; + } + } else { + dPos = function(di) { + var pos = shiftPos(di); + return _$fx_93.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance); + }; } - i = 0; - while(top === undefined && i < y.length - 1) { - top = ya.c2p(y[i]); - i++; - } - i = y.length - 1; - while(bottom === undefined && i > 0) { - bottom = ya.c2p(y[i]); - i--; - } + var dVal; - if(bottom < top) { - temp = top; - top = bottom; - bottom = temp; - yrev = true; + if(isViolin) { + dVal = function(di) { + return _$fx_93.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); + }; + } else { + dVal = function(di) { + return _$fx_93.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); + }; } - // for contours with heatmap fill, we generate the boundaries based on - // brick centers but then use the brick edges for drawing the bricks - if(isContour) { - xc = x; - yc = y; - x = cd0.xfill; - y = cd0.yfill; + if(trace.orientation === 'h') { + vVal = xval; + pVal = yval; + dx = dVal; + dy = dPos; + pLetter = 'y'; + pAxis = ya; + vLetter = 'x'; + vAxis = xa; + } else { + vVal = yval; + pVal = xval; + dx = dPos; + dy = dVal; + pLetter = 'x'; + pAxis = xa; + vLetter = 'y'; + vAxis = ya; } - // make an image that goes at most half a screen off either side, to keep - // time reasonable when you zoom in. if zsmooth is true/fast, don't worry - // about this, because zooming doesn't increase number of pixels - // if zsmooth is best, don't include anything off screen because it takes too long - if(zsmooth !== 'fast') { - var extra = zsmooth === 'best' ? 0 : 0.5; - left = Math.max(-extra * xa._length, left); - right = Math.min((1 + extra) * xa._length, right); - top = Math.max(-extra * ya._length, top); - bottom = Math.min((1 + extra) * ya._length, bottom); - } + // if two boxes are overlaying, let the narrowest one win + var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0]))); + hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; + spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; - var imageWidth = Math.round(right - left), - imageHeight = Math.round(bottom - top); + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_93.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_93.getClosest(cd, distfn, pointData); - // setup image nodes + // skip the rest (for this trace) if we didn't find a close point + // and create the item(s) in closedata for this point + if(pointData.index === false) return []; - // if image is entirely off-screen, don't even draw it - var isOffScreen = (imageWidth <= 0 || imageHeight <= 0); + var di = cd[pointData.index]; + var lc = trace.line.color; + var mc = (trace.marker || {}).color; - var plotgroup = plotinfo.plot.select('.imagelayer') - .selectAll('g.hm.' + id) - .data(isOffScreen ? [] : [0]); + if(_$color_51.opacity(lc) && trace.line.width) pointData.color = lc; + else if(_$color_51.opacity(mc) && trace.boxpoints) pointData.color = mc; + else pointData.color = trace.fillcolor; - plotgroup.enter().append('g') - .classed('hm', true) - .classed(id, true); + pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDelta, true); + pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDelta, true); - plotgroup.exit().remove(); + pointData[pLetter + 'LabelVal'] = di.pos; - if(isOffScreen) return; + var spikePosAttr = pLetter + 'Spike'; + pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; + pointData[spikePosAttr] = pAxis.c2p(di.pos, true); - // generate image data + // box plots: each "point" gets many labels + var usedVals = {}; + var attrs = ['med', 'min', 'q1', 'q3', 'max']; - var canvasW, canvasH; - if(zsmooth === 'fast') { - canvasW = n; - canvasH = m; - } else { - canvasW = imageWidth; - canvasH = imageHeight; + if(trace.boxmean || (trace.meanline || {}).visible) { + attrs.push('mean'); + } + if(trace.boxpoints || trace.points) { + attrs.push('lf', 'uf'); } - var canvas = document.createElement('canvas'); - canvas.width = canvasW; - canvas.height = canvasH; - var context = canvas.getContext('2d'); + for(var i = 0; i < attrs.length; i++) { + var attr = attrs[i]; - var sclFunc = _$colorscale_66.makeColorScaleFunc( - _$colorscale_66.extractScale( - trace.colorscale, - trace.zmin, - trace.zmax - ), - { noNumericCheck: true, returnArray: true } - ); + if(!(attr in di) || (di[attr] in usedVals)) continue; + usedVals[di[attr]] = true; - // map brick boundaries to image pixels - var xpx, - ypx; - if(zsmooth === 'fast') { - xpx = xrev ? - function(index) { return n - 1 - index; } : - _$lib_171.identity; - ypx = yrev ? - function(index) { return m - 1 - index; } : - _$lib_171.identity; - } - else { - xpx = function(index) { - return _$lib_171.constrain(Math.round(xa.c2p(x[index]) - left), - 0, imageWidth); - }; - ypx = function(index) { - return _$lib_171.constrain(Math.round(ya.c2p(y[index]) - top), - 0, imageHeight); - }; - } - - // build the pixel map brick-by-brick - // cruise through z-matrix row-by-row - // build a brick at each z-matrix value - var yi = ypx(0); - var yb = [yi, yi]; - var xbi = xrev ? 0 : 1; - var ybi = yrev ? 0 : 1; - // for collecting an average luminosity of the heatmap - var pixcount = 0; - var rcount = 0; - var gcount = 0; - var bcount = 0; - - var xb, j, xi, v, row, c; - - function setColor(v, pixsize) { - if(v !== undefined) { - var c = sclFunc(v); - c[0] = Math.round(c[0]); - c[1] = Math.round(c[1]); - c[2] = Math.round(c[2]); - - pixcount += pixsize; - rcount += c[0] * pixsize; - gcount += c[1] * pixsize; - bcount += c[2] * pixsize; - return c; - } - return [0, 0, 0, 0]; - } - - function interpColor(r0, r1, xinterp, yinterp) { - var z00 = r0[xinterp.bin0]; - if(z00 === undefined) return setColor(undefined, 1); + // copy out to a new object for each value to label + var val = di[attr]; + var valPx = vAxis.c2p(val, true); + var pointData2 = _$lib_172.extendFlat({}, pointData); - var z01 = r0[xinterp.bin1], - z10 = r1[xinterp.bin0], - z11 = r1[xinterp.bin1], - dx = (z01 - z00) || 0, - dy = (z10 - z00) || 0, - dxy; + pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx; + pointData2[vLetter + 'LabelVal'] = val; + pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_214.hoverLabelText(vAxis, val); - // the bilinear interpolation term needs different calculations - // for all the different permutations of missing data - // among the neighbors of the main point, to ensure - // continuity across brick boundaries. - if(z01 === undefined) { - if(z11 === undefined) dxy = 0; - else if(z10 === undefined) dxy = 2 * (z11 - z00); - else dxy = (2 * z11 - z10 - z00) * 2 / 3; - } - else if(z11 === undefined) { - if(z10 === undefined) dxy = 0; - else dxy = (2 * z00 - z01 - z10) * 2 / 3; + if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') { + pointData2[vLetter + 'err'] = di.sd; } - else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3; - else dxy = (z11 + z00 - z01 - z10); + // only keep name and spikes on the first item (median) + pointData.name = ''; + pointData.spikeDistance = undefined; + pointData[spikePosAttr] = undefined; - return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy)); + closeBoxData.push(pointData2); } - if(zsmooth) { // best or fast, works fastest with imageData - var pxIndex = 0, - pixels; + return closeBoxData; +} - try { - pixels = new Uint8Array(imageWidth * imageHeight * 4); - } - catch(e) { - pixels = new Array(imageWidth * imageHeight * 4); - } +function hoverOnPoints(pointData, xval, yval) { + var cd = pointData.cd; + var xa = pointData.xa; + var ya = pointData.ya; + var trace = cd[0].trace; + var xPx = xa.c2p(xval); + var yPx = ya.c2p(yval); + var closePtData; - if(zsmooth === 'best') { - var xForPx = xc || x; - var yForPx = yc || y; - var xPixArray = new Array(xForPx.length); - var yPixArray = new Array(yForPx.length); - var xinterpArray = new Array(imageWidth); - var findInterpX = xc ? findInterpFromCenters : findInterp; - var findInterpY = yc ? findInterpFromCenters : findInterp; - var yinterp, r0, r1; + var dx = function(di) { + var rad = Math.max(3, di.mrc || 0); + return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad); + }; + var dy = function(di) { + var rad = Math.max(3, di.mrc || 0); + return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad); + }; + var distfn = _$fx_93.quadrature(dx, dy); - // first make arrays of x and y pixel locations of brick boundaries - for(i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left); - for(i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top); + // show one point per trace + var ijClosest = false; + var di, pt; - // then make arrays of interpolations - // (bin0=closest, bin1=next, frac=fractional dist.) - for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray); + for(var i = 0; i < cd.length; i++) { + di = cd[i]; - // now do the interpolations and fill the png - for(j = 0; j < imageHeight; j++) { - yinterp = findInterpY(j, yPixArray); - r0 = z[yinterp.bin0]; - r1 = z[yinterp.bin1]; - for(i = 0; i < imageWidth; i++, pxIndex += 4) { - c = interpColor(r0, r1, xinterpArray[i], yinterp); - putColor(pixels, pxIndex, c); - } - } - } - else { // zsmooth = fast - for(j = 0; j < m; j++) { - row = z[j]; - yb = ypx(j); - for(i = 0; i < imageWidth; i++) { - c = setColor(row[i], 1); - pxIndex = (yb * imageWidth + xpx(i)) * 4; - putColor(pixels, pxIndex, c); - } - } - } + for(var j = 0; j < (di.pts || []).length; j++) { + pt = di.pts[j]; - var imageData = context.createImageData(imageWidth, imageHeight); - try { - imageData.data.set(pixels); - } - catch(e) { - var pxArray = imageData.data, - dlen = pxArray.length; - for(j = 0; j < dlen; j ++) { - pxArray[j] = pixels[j]; + var newDistance = distfn(pt); + if(newDistance <= pointData.distance) { + pointData.distance = newDistance; + ijClosest = [i, j]; } } + } - context.putImageData(imageData, 0, 0); - } else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect + if(!ijClosest) return false; - // gaps do not need to be exact integers, but if they *are* we will get - // cleaner edges by rounding at least one edge - var xGap = trace.xgap; - var yGap = trace.ygap; - var xGapLeft = Math.floor(xGap / 2); - var yGapTop = Math.floor(yGap / 2); + di = cd[ijClosest[0]]; + pt = di.pts[ijClosest[1]]; - for(j = 0; j < m; j++) { - row = z[j]; - yb.reverse(); - yb[ybi] = ypx(j + 1); - if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) { - continue; - } - xi = xpx(0); - xb = [xi, xi]; - for(i = 0; i < n; i++) { - // build one color brick! - xb.reverse(); - xb[xbi] = xpx(i + 1); - if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) { - continue; - } - v = row[i]; - c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0])); - context.fillStyle = 'rgba(' + c.join(',') + ')'; + var xc = xa.c2p(pt.x, true); + var yc = ya.c2p(pt.y, true); + var rad = pt.mrc || 1; - context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop, - xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap); - } - } - } + closePtData = _$lib_172.extendFlat({}, pointData, { + // corresponds to index in x/y input data array + index: pt.i, + color: (trace.marker || {}).color, + name: trace.name, + x0: xc - rad, + x1: xc + rad, + xLabelVal: pt.x, + y0: yc - rad, + y1: yc + rad, + yLabelVal: pt.y, + spikeDistance: pointData.distance + }); + var pLetter = trace.orientation === 'h' ? 'y' : 'x'; + var pa = trace.orientation === 'h' ? ya : xa; + closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true); + _$fillHoverText_377(pt, trace, closePtData); - rcount = Math.round(rcount / pixcount); - gcount = Math.round(gcount / pixcount); - bcount = Math.round(bcount / pixcount); - var avgColor = _$tinycolor_33('rgb(' + rcount + ',' + gcount + ',' + bcount + ')'); + return closePtData; +} - gd._hmpixcount = (gd._hmpixcount||0) + pixcount; - gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance(); +var _$hover_288 = { + hoverPoints: hoverPoints, + hoverOnBoxes: hoverOnBoxes, + hoverOnPoints: hoverOnPoints +}; - var image3 = plotgroup.selectAll('image') - .data(cd); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - image3.enter().append('svg:image').attr({ - xmlns: _$xmlns_namespaces_156.svg, - preserveAspectRatio: 'none' - }); +'use strict'; - image3.attr({ - height: imageHeight, - width: imageWidth, - x: left, - y: top, - 'xlink:href': canvas.toDataURL('image/png') - }); - image3.exit().remove(); -} +var _$layout_attributes_290 = { + 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', + + } +}; -// get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin} -function findInterp(pixel, pixArray) { - var maxBin = pixArray.length - 2; - var bin = _$lib_171.constrain(_$lib_171.findBin(pixel, pixArray), 0, maxBin); - var pix0 = pixArray[bin]; - var pix1 = pixArray[bin + 1]; - var interp = _$lib_171.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin); - var bin0 = Math.round(interp); - var frac = Math.abs(interp - bin0); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!interp || interp === maxBin || !frac) { - return { - bin0: bin0, - bin1: bin0, - frac: 0 - }; +'use strict'; + +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$layout_attributes_290 = require('./layout_attributes'); */; + +function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { + var hasTraceType; + var category = traceType + 'Layout'; + for(var i = 0; i < fullData.length; i++) { + if(_$registry_262.traceIs(fullData[i], category)) { + hasTraceType = true; + break; + } } - return { - bin0: bin0, - frac: frac, - bin1: Math.round(bin0 + frac / (interp - bin0)) - }; + if(!hasTraceType) return; + + coerce(traceType + 'mode'); + coerce(traceType + 'gap'); + coerce(traceType + 'groupgap'); } -function findInterpFromCenters(pixel, centerPixArray) { - var maxBin = centerPixArray.length - 1; - var bin = _$lib_171.constrain(_$lib_171.findBin(pixel, centerPixArray), 0, maxBin); - var pix0 = centerPixArray[bin]; - var pix1 = centerPixArray[bin + 1]; - var frac = ((pixel - pix0) / (pix1 - pix0)) || 0; - if(frac <= 0) { - return { - bin0: bin, - bin1: bin, - frac: 0 - }; - } - if(frac < 0.5) { - return { - bin0: bin, - bin1: bin + 1, - frac: frac - }; +function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_290, attr, dflt); } - return { - bin0: bin + 1, - bin1: bin, - frac: 1 - frac - }; + _supply(layoutIn, layoutOut, fullData, coerce, 'box'); } -function putColor(pixels, pxIndex, c) { - pixels[pxIndex] = c[0]; - pixels[pxIndex + 1] = c[1]; - pixels[pxIndex + 2] = c[2]; - pixels[pxIndex + 3] = Math.round(c[3] * 255); -} +var _$layout_defaults_291 = { + supplyLayoutDefaults: supplyLayoutDefaults, + _supply: _supply +}; -var _$plot_313 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -41392,697 +41240,578 @@ var _$plot_313 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$setConvert_232 = require('../../plots/cartesian/set_convert'); */; -/* removed: var _$plot_330 = require('../heatmap/plot'); */; -/* removed: var _$makeCrossings_312 = require('./make_crossings'); */; -/* removed: var _$findAllPaths_307 = require('./find_all_paths'); */; -/* removed: var _$emptyPathinfo_305 = require('./empty_pathinfo'); */; -/* removed: var _$convert_to_constraints_303 = require('./convert_to_constraints'); */; -/* removed: var _$close_boundaries_297 = require('./close_boundaries'); */; -/* removed: var _$constants_299 = require('./constants'); */; -var costConstants = _$constants_299.LABELOPTIMIZER; +// constants for dynamic jitter (ie less jitter for sparser points) +var JITTERCOUNT = 5; // points either side of this to include +var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense" +function plot(gd, plotinfo, cdbox) { + var fullLayout = gd._fullLayout; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -_$plot_313.plot = function plot(gd, plotinfo, cdcontours) { - for(var i = 0; i < cdcontours.length; i++) { - __plotOne_313(gd, plotinfo, cdcontours[i]); - } -}; + var boxtraces = plotinfo.plot.select('.boxlayer') + .selectAll('g.trace.boxes') + .data(cdbox) + .enter().append('g') + .attr('class', 'trace boxes'); -function __plotOne_313(gd, plotinfo, cd) { - var trace = cd[0].trace, - x = cd[0].x, - y = cd[0].y, - contours = trace.contours, - uid = trace.uid, - xa = plotinfo.xaxis, - ya = plotinfo.yaxis, - fullLayout = gd._fullLayout, - id = 'contour' + uid, - pathinfo = _$emptyPathinfo_305(contours, plotinfo, cd[0]); + boxtraces.each(function(d) { + var cd0 = d[0]; + var t = cd0.t; + var trace = cd0.trace; + var sel = _$d3_15.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; + var numBoxes = fullLayout._numBoxes; - if(trace.visible !== true) { - fullLayout._paper.selectAll('.' + id + ',.hm' + uid).remove(); - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - return; - } + var groupFraction = (1 - fullLayout.boxgap); - // use a heatmap to fill - draw it behind the lines - if(contours.coloring === 'heatmap') { - if(trace.zauto && (trace.autocontour === false)) { - trace._input.zmin = trace.zmin = - contours.start - contours.size / 2; - trace._input.zmax = trace.zmax = - trace.zmin + pathinfo.length * contours.size; + var group = (fullLayout.boxmode === 'group' && numBoxes > 1); + // box half width + var bdPos = t.dPos * groupFraction * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); + // box center offset + var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * groupFraction : 0; + // whisker width + var wdPos = bdPos * trace.whiskerwidth; + + if(trace.visible !== true || t.empty) { + sel.remove(); + return; } - _$plot_330(gd, plotinfo, [cd]); - } - // in case this used to be a heatmap (or have heatmap fill) - else { - fullLayout._paper.selectAll('.hm' + uid).remove(); - fullLayout._infolayer.selectAll('g.rangeslider-container') - .selectAll('.hm' + uid).remove(); - } + var posAxis, valAxis; - _$makeCrossings_312(pathinfo); - _$findAllPaths_307(pathinfo); + if(trace.orientation === 'h') { + posAxis = ya; + valAxis = xa; + } else { + posAxis = xa; + valAxis = ya; + } - var leftedge = xa.c2p(x[0], true), - rightedge = xa.c2p(x[x.length - 1], true), - bottomedge = ya.c2p(y[0], true), - topedge = ya.c2p(y[y.length - 1], true), - perimeter = [ - [leftedge, topedge], - [rightedge, topedge], - [rightedge, bottomedge], - [leftedge, bottomedge] - ]; + // save the box size and box position for use by hover + t.bPos = bPos; + t.bdPos = bdPos; + t.wdPos = wdPos; + // half-width within which to accept hover for this box + // always split the distance to the closest box + t.wHover = t.dPos * (group ? groupFraction / numBoxes : 1); - var fillPathinfo = pathinfo; - if(contours.type === 'constraint') { - fillPathinfo = _$convert_to_constraints_303(pathinfo, contours._operation); - _$close_boundaries_297(fillPathinfo, contours._operation, perimeter, trace); - } + // boxes and whiskers + plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, t); - // draw everything - var plotGroup = _$plot_313.makeContourGroup(plotinfo, cd, id); - makeBackground(plotGroup, perimeter, contours); - makeFills(plotGroup, fillPathinfo, perimeter, contours); - makeLinesAndLabels(plotGroup, pathinfo, gd, cd[0], contours, perimeter); - clipGaps(plotGroup, plotinfo, fullLayout._clips, cd[0], perimeter); -} + // draw points, if desired + if(trace.boxpoints) { + plotPoints(sel, {x: xa, y: ya}, trace, t); + } -_$plot_313.makeContourGroup = function(plotinfo, cd, id) { - var plotgroup = plotinfo.plot.select('.maplayer') - .selectAll('g.contour.' + id) - .data(cd); + // draw mean (and stdev diamond) if desired + if(trace.boxmean) { + plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, t); + } + }); +} - plotgroup.enter().append('g') - .classed('contour', true) - .classed(id, true); +function plotBoxAndWhiskers(sel, axes, trace, t) { + var posAxis = axes.pos; + var valAxis = axes.val; + var bPos = t.bPos; + var wdPos = t.wdPos || 0; + var bPosPxOffset = t.bPosPxOffset || 0; + var whiskerWidth = trace.whiskerwidth || 0; + var notched = trace.notched || false; + var nw = notched ? 1 - 2 * trace.notchwidth : 1; - plotgroup.exit().remove(); + // to support for one-sided box + var bdPos0; + var bdPos1; + if(Array.isArray(t.bdPos)) { + bdPos0 = t.bdPos[0]; + bdPos1 = t.bdPos[1]; + } else { + bdPos0 = t.bdPos; + bdPos1 = t.bdPos; + } - return plotgroup; -}; + sel.selectAll('path.box') + .data(_$lib_172.identity) + .enter().append('path') + .style('vector-effect', 'non-scaling-stroke') + .attr('class', 'box') + .each(function(d) { + var pos = d.pos; + var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset; + var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset; + var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset; + var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset; + var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset; + var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset; + var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset; + var q1 = valAxis.c2p(d.q1, true); + var q3 = valAxis.c2p(d.q3, true); + // make sure median isn't identical to either of the + // quartiles, so we can see it + var m = _$lib_172.constrain( + valAxis.c2p(d.med, true), + Math.min(q1, q3) + 1, Math.max(q1, q3) - 1 + ); -function makeBackground(plotgroup, perimeter, contours) { - var bggroup = plotgroup.selectAll('g.contourbg').data([0]); - bggroup.enter().append('g').classed('contourbg', true); + // for compatibility with box, violin, and candlestick + // perhaps we should put this into cd0.t instead so it's more explicit, + // but what we have now is: + // - box always has d.lf, but boxpoints can be anything + // - violin has d.lf and should always use it (boxpoints is undefined) + // - candlestick has only min/max + var useExtremes = (d.lf === undefined) || (trace.boxpoints === false); + var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true); + var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true); + var ln = valAxis.c2p(d.ln, true); + var un = valAxis.c2p(d.un, true); - 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'); + if(trace.orientation === 'h') { + _$d3_15.select(this).attr('d', + 'M' + m + ',' + posm0 + 'V' + posm1 + // median line + 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge + (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge + 'H' + q3 + // end of the top edge + 'V' + pos0 + // right edge + (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge + 'Z' + // end of the box + 'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers + ((whiskerWidth === 0) ? '' : // whisker caps + 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1)); + } else { + _$d3_15.select(this).attr('d', + 'M' + posm0 + ',' + m + 'H' + posm1 + // median line + 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box + (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge + 'V' + q3 + // end of the right edge + 'H' + pos0 + // bottom of the box + (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge + 'Z' + // end of the box + 'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers + ((whiskerWidth === 0) ? '' : // whisker caps + 'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1)); + } + }); } -function makeFills(plotgroup, pathinfo, perimeter, contours) { - var fillgroup = plotgroup.selectAll('g.contourfill') - .data([0]); - fillgroup.enter().append('g') - .classed('contourfill', true); - - var fillitems = fillgroup.selectAll('path') - .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? 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 = joinAllPaths(pi, perimeter); +function plotPoints(sel, axes, trace, t) { + var xa = axes.x; + var ya = axes.y; + var bdPos = t.bdPos; + var bPos = t.bPos; - if(!fullpath) _$d3_15.select(this).remove(); - else _$d3_15.select(this).attr('d', fullpath).style('stroke', 'none'); - }); -} + // to support violin points + var mode = trace.boxpoints || trace.points; -function initFullPath(pi, perimeter) { - var prefixBoundary = pi.prefixBoundary; - if(prefixBoundary === undefined) { - var edgeVal2 = Math.min(pi.z[0][0], pi.z[0][1]); - prefixBoundary = (!pi.edgepaths.length && edgeVal2 > pi.level); - } + // repeatable pseudo-random number generator + _$lib_172.seedPseudoRandom(); - if(prefixBoundary) { - // TODO: why does ^^ not work for constraints? - // pi.prefixBoundary gets set by closeBoundaries - return 'M' + perimeter.join('L') + 'Z'; - } - return ''; -} + sel.selectAll('g.points') + // since box plot points get an extra level of nesting, each + // box needs the trace styling info + .data(function(d) { + d.forEach(function(v) { + v.t = t; + v.trace = trace; + }); + return d; + }) + .enter().append('g') + .attr('class', 'points') + .selectAll('path') + .data(function(d) { + var i; -function joinAllPaths(pi, perimeter) { - var fullpath = initFullPath(pi, perimeter), - i = 0, - startsleft = pi.edgepaths.map(function(v, i) { return i; }), - newloop = true, - endpt, - newendpt, - cnt, - nexti, - possiblei, - addpath; + var pts = mode === 'all' ? + d.pts : + d.pts.filter(function(pt) { return (pt.v < d.lf || pt.v > d.uf); }); - 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; } + // normally use IQR, but if this is 0 or too small, use max-min + var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1); + var minSpread = typicalSpread * 1e-9; + var spreadLimit = typicalSpread * JITTERSPREAD; + var jitterFactors = []; + var maxJitterFactor = 0; + var newJitter; - while(startsleft.length) { - addpath = _$drawing_76.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; + // dynamic jitter + if(trace.jitter) { + if(typicalSpread === 0) { + // edge case of no spread at all: fall back to max jitter + maxJitterFactor = 1; + jitterFactors = new Array(pts.length); + for(i = 0; i < pts.length; i++) { + jitterFactors[i] = 1; + } + } else { + for(i = 0; i < pts.length; i++) { + var i0 = Math.max(0, i - JITTERCOUNT); + var pmin = pts[i0].v; + var i1 = Math.min(pts.length - 1, i + JITTERCOUNT); + var pmax = pts[i1].v; - // 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_171.log('Missing end?', i, pi); - break; - } + if(mode !== 'all') { + if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf); + else pmin = Math.max(pmin, d.uf); + } - 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 + var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0; + jitterFactor = _$lib_172.constrain(Math.abs(jitterFactor), 0, 1); - 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; + jitterFactors.push(jitterFactor); + maxJitterFactor = Math.max(jitterFactor, maxJitterFactor); } } - else { - _$lib_171.log('endpt to newendpt is not vert. or horz.', - endpt, newendpt, ptNew); - } + newJitter = trace.jitter * 2 / (maxJitterFactor || 1); } - endpt = newendpt; + // fills in 'x' and 'y' in calcdata 'pts' item + for(i = 0; i < pts.length; i++) { + var pt = pts[i]; + var v = pt.v; - if(nexti >= 0) break; - fullpath += 'L' + newendpt; - } + var jitterOffset = trace.jitter ? + (newJitter * jitterFactors[i] * (_$lib_172.pseudoRandom() - 0.5)) : + 0; - if(nexti === pi.edgepaths.length) { - _$lib_171.log('unclosed perimeter path'); - break; - } + var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset); - i = nexti; + if(trace.orientation === 'h') { + pt.y = posPx; + pt.x = v; + } else { + pt.x = posPx; + pt.y = v; + } - // 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'; - } - } + // tag suspected outliers + if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) { + pt.so = true; + } + } - // finally add the interior paths - for(i = 0; i < pi.paths.length; i++) { - fullpath += _$drawing_76.smoothclosed(pi.paths[i], pi.smoothing); + return pts; + }) + .enter().append('path') + .classed('point', true) + .call(_$drawing_76.translatePoints, xa, ya); +} + +function plotBoxMean(sel, axes, trace, t) { + var posAxis = axes.pos; + var valAxis = axes.val; + var bPos = t.bPos; + var bPosPxOffset = t.bPosPxOffset || 0; + + // to support for one-sided box + var bdPos0; + var bdPos1; + if(Array.isArray(t.bdPos)) { + bdPos0 = t.bdPos[0]; + bdPos1 = t.bdPos[1]; + } else { + bdPos0 = t.bdPos; + bdPos1 = t.bdPos; } - return fullpath; + sel.selectAll('path.mean') + .data(_$lib_172.identity) + .enter().append('path') + .attr('class', 'mean') + .style({ + fill: 'none', + 'vector-effect': 'non-scaling-stroke' + }) + .each(function(d) { + var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset; + var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset; + var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset; + var m = valAxis.c2p(d.mean, true); + var sl = valAxis.c2p(d.mean - d.sd, true); + var sh = valAxis.c2p(d.mean + d.sd, true); + + if(trace.orientation === 'h') { + _$d3_15.select(this).attr('d', + 'M' + m + ',' + pos0 + 'V' + pos1 + + (trace.boxmean === 'sd' ? + 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : + '') + ); + } else { + _$d3_15.select(this).attr('d', + 'M' + pos0 + ',' + m + 'H' + pos1 + + (trace.boxmean === 'sd' ? + 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : + '') + ); + } + }); } -function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { - var lineContainer = plotgroup.selectAll('g.contourlines').data([0]); +var _$plot_292 = { + plot: plot, + plotBoxAndWhiskers: plotBoxAndWhiskers, + plotPoints: plotPoints, + plotBoxMean: plotBoxMean +}; - lineContainer.enter().append('g') - .classed('contourlines', true); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 showLines = contours.showlines !== false; - var showLabels = contours.showlabels; - var clipLinesForLabels = showLines && showLabels; +'use strict'; - // 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 = _$plot_313.createLines(lineContainer, showLines || showLabels, pathinfo); +var _$selectPoints_293 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i, j; - var lineClip = _$plot_313.createLineClip(lineContainer, clipLinesForLabels, - gd._fullLayout._clips, cd0.trace.uid); + if(polygon === 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); - var labelGroup = plotgroup.selectAll('g.contourlabels') - .data(showLabels ? [0] : []); + if(polygon.contains([x, y])) { + selection.push({ + pointNumber: pt.i, + x: xa.c2d(pt.x), + y: ya.c2d(pt.y) + }); + pt.selected = 1; + } else { + pt.selected = 0; + } + } + } + } - labelGroup.exit().remove(); + return selection; +}; - labelGroup.enter().append('g') - .classed('contourlabels', true); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(showLabels) { - var labelClipPathData = [perimeter]; +'use strict'; - var labelData = []; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_172 = require('../../lib'); */; - // invalidate the getTextLocation cache in case paths changed - _$lib_171.clearLocationCache(); +var orientations = ['v', 'h']; - var contourFormat = _$plot_313.labelFormatter(contours, cd0.t.cb, gd._fullLayout); +function setPositions(gd, plotinfo) { + var calcdata = gd.calcdata; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - var dummyText = _$drawing_76.tester.append('text') - .attr('data-notex', 1) - .call(_$drawing_76.font, contours.labelfont); + for(var i = 0; i < orientations.length; i++) { + var orientation = orientations[i]; + var posAxis = orientation === 'h' ? ya : xa; + var boxList = []; + var minPad = 0; + var maxPad = 0; - var xLen = pathinfo[0].xaxis._length; - var yLen = pathinfo[0].yaxis._length; + // make list of boxes / candlesticks + // For backward compatibility, candlesticks are treated as if they *are* box traces here + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j]; + var t = cd[0].t; + var trace = cd[0].trace; - // visible bounds of the contour trace (and the midpoints, to - // help with cost calculations) - var bounds = { - left: Math.max(perimeter[0][0], 0), - right: Math.min(perimeter[2][0], xLen), - top: Math.max(perimeter[0][1], 0), - bottom: Math.min(perimeter[2][1], yLen) - }; - bounds.middle = (bounds.top + bounds.bottom) / 2; - bounds.center = (bounds.left + bounds.right) / 2; + if(trace.visible === true && + (trace.type === 'box' || trace.type === 'candlestick') && + !t.empty && + (trace.orientation || 'v') === orientation && + trace.xaxis === xa._id && + trace.yaxis === ya._id + ) { + boxList.push(j); - var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen); + if(trace.boxpoints) { + minPad = Math.max(minPad, trace.jitter - trace.pointpos - 1); + maxPad = Math.max(maxPad, trace.jitter + trace.pointpos - 1); + } + } + } - // the path length to use to scale the number of labels to draw: - var normLength = _$constants_299.LABELDISTANCE * plotDiagonal / - Math.max(1, pathinfo.length / _$constants_299.LABELINCREASE); + setPositionOffset('box', gd, boxList, posAxis, [minPad, maxPad]); + } +} - linegroup.each(function(d) { - var textOpts = _$plot_313.calcTextOpts(d.level, contourFormat, dummyText, gd); +function setPositionOffset(traceType, gd, boxList, posAxis, pad) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; + var pointList = []; - _$d3_15.select(this).selectAll('path').each(function() { - var path = this; - var pathBounds = _$lib_171.getVisibleSegment(path, bounds, textOpts.height / 2); - if(!pathBounds) return; + // N.B. reused in violin + var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes'; - if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_299.LABELMIN) return; + var i, j, calcTrace; - var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), - _$constants_299.LABELMAX); + // make list of box points + for(i = 0; i < boxList.length; i++) { + calcTrace = calcdata[boxList[i]]; + for(j = 0; j < calcTrace.length; j++) { + pointList.push(calcTrace[j].pos); + } + } - for(var i = 0; i < maxLabels; i++) { - var loc = _$plot_313.findBestTextLocation(path, pathBounds, textOpts, - labelData, bounds); + if(!pointList.length) return; - if(!loc) break; + // box plots - update dPos based on multiple traces + // and then use for posAxis autorange + var boxdv = _$lib_172.distinctVals(pointList); + var dPos = boxdv.minDiff / 2; - _$plot_313.addLabelData(loc, textOpts, labelData, labelClipPathData); - } - }); - }); + // if there's no duplication of x points, + // disable 'group' mode by setting counter to 1 + if(pointList.length === boxdv.vals.length) { + fullLayout[numKey] = 1; + } - dummyText.remove(); + // check for forced minimum dtick + _$axes_214.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); - _$plot_313.drawLabels(labelGroup, labelData, gd, lineClip, - clipLinesForLabels ? labelClipPathData : null); + // set the width of all boxes + for(i = 0; i < boxList.length; i++) { + calcTrace = calcdata[boxList[i]]; + calcTrace[0].t.dPos = dPos; } - if(showLabels && !showLines) linegroup.remove(); + var gap = fullLayout[traceType + 'gap']; + var groupgap = fullLayout[traceType + 'groupgap']; + var padfactor = (1 - gap) * (1 - groupgap) * dPos / fullLayout[numKey]; + + // autoscale the x axis - including space for points if they're off the side + // TODO: this will overdo it if the outermost boxes don't have + // their points as far out as the other boxes + _$axes_214.expand(posAxis, boxdv.vals, { + vpadminus: dPos + pad[0] * padfactor, + vpadplus: dPos + pad[1] * padfactor + }); } -_$plot_313.createLines = function(lineContainer, makeLines, pathinfo) { - var smoothing = pathinfo[0].smoothing; +var _$set_positions_294 = { + setPositions: setPositions, + setPositionOffset: setPositionOffset +}; - var linegroup = lineContainer.selectAll('g.contourlevel') - .data(makeLines ? pathinfo : []); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - linegroup.exit().remove(); - linegroup.enter().append('g') - .classed('contourlevel', true); +'use strict'; - 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; }); +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +/* removed: var _$drawing_76 = require('../../components/drawing'); */; - opencontourlines.exit().remove(); - opencontourlines.enter().append('path') - .classed('openline', true); +var _$style_295 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_15.select(gd).selectAll('g.trace.boxes'); - opencontourlines - .attr('d', function(d) { - return _$drawing_76.smoothopen(d, smoothing); - }) - .style('stroke-miterlimit', 1) - .style('vector-effect', 'non-scaling-stroke'); + s.style('opacity', function(d) { return d[0].trace.opacity; }); - var closedcontourlines = linegroup.selectAll('path.closedline') - .data(function(d) { return d.ppaths || d.paths; }); + s.each(function(d) { + var el = _$d3_15.select(this); + var trace = d[0].trace; + var lineWidth = trace.line.width; - closedcontourlines.exit().remove(); - closedcontourlines.enter().append('path') - .classed('closedline', true); + function styleBox(boxSel, lineWidth, lineColor, fillColor) { + boxSel.style('stroke-width', lineWidth + 'px') + .call(_$color_51.stroke, lineColor) + .call(_$color_51.fill, fillColor); + } - closedcontourlines - .attr('d', function(d) { - return _$drawing_76.smoothclosed(d, smoothing); - }) - .style('stroke-miterlimit', 1) - .style('vector-effect', 'non-scaling-stroke'); - } + var allBoxes = el.selectAll('path.box'); - return linegroup; + if(trace.type === 'candlestick') { + allBoxes.each(function(boxData) { + var thisBox = _$d3_15.select(this); + var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing' + styleBox(thisBox, container.line.width, container.line.color, container.fillcolor); + // TODO: custom selection style for candlesticks + thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1); + }); + } + else { + styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor); + el.selectAll('path.mean') + .style({ + 'stroke-width': lineWidth, + 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' + }) + .call(_$color_51.stroke, trace.line.color); + + var pts = el.selectAll('path.point'); + _$drawing_76.pointStyle(pts, trace, gd); + _$drawing_76.selectedPointStyle(pts, trace); + } + }); }; -_$plot_313.createLineClip = function(lineContainer, clipLinesForLabels, clips, uid) { - var clipId = clipLinesForLabels ? ('clipline' + uid) : null; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 lineClip = clips.selectAll('#' + clipId) - .data(clipLinesForLabels ? [0] : []); - lineClip.exit().remove(); +'use strict'; - lineClip.enter().append('clipPath') - .classed('contourlineclip', true) - .attr('id', clipId); +var Box = {}; - _$drawing_76.setClipUrl(lineContainer, clipId); +Box.attributes = _$attributes_285; +Box.layoutAttributes = _$layout_attributes_290; +Box.supplyDefaults = _$defaults_287.supplyDefaults; +Box.supplyLayoutDefaults = _$layout_defaults_291.supplyLayoutDefaults; +Box.calc = _$calc_286; +Box.setPositions = _$set_positions_294.setPositions; +Box.plot = _$plot_292.plot; +Box.style = _$style_295; +Box.hoverPoints = _$hover_288.hoverPoints; +Box.selectPoints = _$selectPoints_293; - return lineClip; +Box.moduleType = 'trace'; +Box.name = 'box'; +Box.basePlotModule = _$cartesian_225; +Box.categories = ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'draggedPts', 'boxLayout']; +Box.meta = { + }; -_$plot_313.labelFormatter = function(contours, colorbar, fullLayout) { - if(contours.labelformat) { - return fullLayout._d3locale.numberFormat(contours.labelformat); - } - else { - var formatAxis; - if(colorbar) { - formatAxis = colorbar.axis; - } - else { - formatAxis = { - type: 'linear', - _id: 'ycontour', - showexponent: 'all' - }; - - 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_232(formatAxis, fullLayout); - _$axes_213.prepTicks(formatAxis); - formatAxis._tmin = null; - formatAxis._tmax = null; - } - return function(v) { - return _$axes_213.tickText(formatAxis, v).text; - }; - } -}; - -_$plot_313.calcTextOpts = function(level, contourFormat, dummyText, gd) { - var text = contourFormat(level); - dummyText.text(text) - .call(_$svg_text_utils_192.convertToTspans, gd); - var bBox = _$drawing_76.bBox(dummyText.node(), true); - - return { - text: text, - width: bBox.width, - height: bBox.height, - level: level, - dy: (bBox.top + bBox.bottom) / 2 - }; -}; - -_$plot_313.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_171.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_171.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; -} - -_$plot_313.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); -}; - -_$plot_313.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_15.select(this) - .text(d.text) - .attr({ - x: x, - y: y, - transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')' - }) - .call(_$svg_text_utils_192.convertToTspans, gd); - }); - - if(labelClipPathData) { - var clipPath = ''; - for(var i = 0; i < labelClipPathData.length; i++) { - clipPath += 'M' + labelClipPathData[i].join('L') + 'Z'; - } - - var lineClipPath = lineClip.selectAll('path').data([0]); - lineClipPath.enter().append('path'); - lineClipPath.attr('d', clipPath); - } -}; - -function clipGaps(plotGroup, plotinfo, clips, cd0, perimeter) { - var clipId = 'clip' + cd0.trace.uid; - - var clipPath = clips.selectAll('#' + clipId) - .data(cd0.trace.connectgaps ? [] : [0]); - clipPath.enter().append('clipPath') - .classed('contourclip', true) - .attr('id', clipId); - clipPath.exit().remove(); - - if(cd0.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_312([clipPathInfo]); - _$findAllPaths_307([clipPathInfo]); - var fullpath = joinAllPaths(clipPathInfo, perimeter); - - var path = clipPath.selectAll('path') - .data([0]); - path.enter().append('path'); - path.attr('d', fullpath); - } - else clipId = null; - - plotGroup.call(_$drawing_76.setClipUrl, clipId); - plotinfo.plot.selectAll('.hm' + cd0.trace.uid) - .call(_$drawing_76.setClipUrl, clipId); -} - -function makeClipMask(cd0) { - var empties = cd0.trace._emptypoints, - z = [], - m = cd0.z.length, - n = cd0.z[0].length, - i, - row = [], - 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; -} +var _$Box_289 = Box; /** * Copyright 2012-2018, Plotly, Inc. @@ -42092,17 +41821,9 @@ function makeClipMask(cd0) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; - -var _$style_331 = function style(gd) { - _$d3_15.select(gd).selectAll('.hm image') - .style('opacity', function(d) { - return d.trace.opacity; - }); -}; +var _$box_4 = _$Box_289; /** * Copyright 2012-2018, Plotly, Inc. @@ -42112,77 +41833,33 @@ var _$style_331 = function style(gd) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; - -/* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$style_331 = require('../heatmap/style'); */; - -/* removed: var _$makeColorMap_311 = require('./make_color_map'); */; - - -var _$style_315 = function style(gd) { - var contours = _$d3_15.select(gd).selectAll('g.contour'); - - contours.style('opacity', function(d) { - return d.trace.opacity; - }); - - contours.each(function(d) { - var c = _$d3_15.select(this); - var trace = d.trace; - var contours = trace.contours; - var line = trace.line; - var cs = contours.size || 1; - var start = contours.start; - - // for contourcarpet only - is this a constraint-type contour trace? - var isConstraintType = contours.type === 'constraint'; - var colorLines = !isConstraintType && contours.coloring === 'lines'; - var colorFills = !isConstraintType && contours.coloring === 'fill'; - - var colorMap = (colorLines || colorFills) ? _$makeColorMap_311(trace) : null; - - c.selectAll('g.contourlevel').each(function(d) { - _$d3_15.select(this).selectAll('path') - .call(_$drawing_76.lineGroupStyle, - line.width, - colorLines ? colorMap(d.level) : line.color, - line.dash); - }); - - var labelFont = contours.labelfont; - c.selectAll('g.contourlabels text').each(function(d) { - _$drawing_76.font(_$d3_15.select(this), { - family: labelFont.family, - size: labelFont.size, - color: labelFont.color || (colorLines ? colorMap(d.level) : line.color) - }); - }); - - if(isConstraintType) { - c.selectAll('g.contourfill path') - .style('fill', trace.fillcolor); - } - else if(colorFills) { - var firstFill; +var _$filter_ops_152 = { + COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='], + COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], + INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], + SET_OPS: ['{}', '}{'], + CONSTRAINT_REDUCTION: { + // for contour constraints, open/closed endpoints are equivalent + '=': '=', - c.selectAll('g.contourfill path') - .style('fill', function(d) { - if(firstFill === undefined) firstFill = d.level; - return colorMap(d.level + 0.5 * cs); - }); + '<': '<', + '<=': '<', - if(firstFill === undefined) firstFill = start; + '>': '>', + '>=': '>', - c.selectAll('g.contourbg path') - .style('fill', colorMap(firstFill - 0.5 * cs)); - } - }); + '[]': '[]', + '()': '[]', + '[)': '[]', + '(]': '[]', - _$style_331(gd); + '][': '][', + ')(': '][', + '](': '][', + ')[': '][' + } }; /** @@ -42193,28 +41870,96 @@ var _$style_315 = function style(gd) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var Contour = {}; +/* removed: var _$attributes_369 = require('../scatter/attributes'); */; +/* removed: var _$attributes_57 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -Contour.attributes = _$attributes_295; -Contour.supplyDefaults = _$supplyDefaults_304; -Contour.calc = _$calc_296; -Contour.plot = _$plot_313.plot; -Contour.style = _$style_315; -Contour.colorbar = _$colorbar_298; -Contour.hoverPoints = _$hoverPoints_308; +var __extendFlat_318 = _$extend_166.extendFlat; -Contour.moduleType = 'trace'; -Contour.name = 'contour'; -Contour.basePlotModule = _$cartesian_224; -Contour.categories = ['cartesian', '2dMap', 'contour', 'showLegend']; -Contour.meta = { - -}; +var _$attributes_318 = __extendFlat_318({}, { + z: { + valType: 'data_array', + editType: 'calc', + + }, + x: __extendFlat_318({}, _$attributes_369.x, {impliedEdits: {xtype: 'array'}}), + x0: __extendFlat_318({}, _$attributes_369.x0, {impliedEdits: {xtype: 'scaled'}}), + dx: __extendFlat_318({}, _$attributes_369.dx, {impliedEdits: {xtype: 'scaled'}}), + y: __extendFlat_318({}, _$attributes_369.y, {impliedEdits: {ytype: 'array'}}), + y0: __extendFlat_318({}, _$attributes_369.y0, {impliedEdits: {ytype: 'scaled'}}), + dy: __extendFlat_318({}, _$attributes_369.dy, {impliedEdits: {ytype: 'scaled'}}), -var _$Contour_309 = Contour; + text: { + 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', + + }, + connectgaps: { + valType: 'boolean', + dflt: false, + + 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', + + }, +}, + _$attributes_57, + { autocolorscale: __extendFlat_318({}, _$attributes_57.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_52 } +); /** * Copyright 2012-2018, Plotly, Inc. @@ -42226,1542 +41971,1548 @@ var _$Contour_309 = Contour; 'use strict'; -var _$contour_5 = _$Contour_309; +/* removed: var _$attributes_318 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_369 = require('../scatter/attributes'); */; +/* removed: var _$attributes_57 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; +var __dash_296 = _$attributes_75.dash; +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +var __extendFlat_296 = _$extend_166.extendFlat; -var _$plotcss_1 = {}; -'use strict'; +/* removed: var _$filter_ops_152 = require('../../constants/filter_ops'); */; +var COMPARISON_OPS2 = _$filter_ops_152.COMPARISON_OPS2; +var INTERVAL_OPS = _$filter_ops_152.INTERVAL_OPS; -/* removed: var _$lib_171 = require('../src/lib'); */; -var rules = { - "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", - "X .modebar--hover": "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": "opacity:1;", - "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", - "X .modebar-group:first-child": "margin-left:0px;", - "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", - "X .modebar-btn svg": "position:relative;top:2px;", - "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", - "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", - "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", - "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", - "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 .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;" -}; +var scatterLineAttrs = _$attributes_369.line; -for(var selector in rules) { - var fullSelector = selector.replace(/^,/,' ,') - .replace(/X/g, '.js-plotly-plot .plotly') - .replace(/Y/g, '.plotly-notifier'); - _$lib_171.addStyleRule(fullSelector, rules[selector]); -} +var _$attributes_296 = __extendFlat_296({ + z: _$attributes_318.z, + x: _$attributes_318.x, + x0: _$attributes_318.x0, + dx: _$attributes_318.dx, + y: _$attributes_318.y, + y0: _$attributes_318.y0, + dy: _$attributes_318.dy, + text: _$attributes_318.text, + transpose: _$attributes_318.transpose, + xtype: _$attributes_318.xtype, + ytype: _$attributes_318.ytype, + zhoverformat: _$attributes_318.zhoverformat, -'use strict'; + connectgaps: _$attributes_318.connectgaps, -var _$ploticon_2 = { - 'undo': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'home': { - 'width': 928.6, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'camera-retro': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoombox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'pan': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_plus': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_minus': { - 'width': 1000, - 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', - 'ascent': 850, - 'descent': -150 - }, - 'autoscale': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_basic': { - 'width': 1500, - 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_compare': { - 'width': 1125, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'plotlylogo': { - 'width': 1542, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'z-axis': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - '3d_rotate': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'camera': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'movie': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'question': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 + fillcolor: { + valType: 'color', + + editType: 'calc', + }, - 'disk': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 + + autocontour: { + valType: 'boolean', + dflt: true, + + editType: 'calc', + impliedEdits: { + 'contours.start': undefined, + 'contours.end': undefined, + 'contours.size': undefined + }, + }, - 'lasso': { - 'width': 1031, - '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', - 'ascent': 850, - 'descent': -150 + ncontours: { + valType: 'integer', + dflt: 15, + min: 1, + + editType: 'calc', + }, - 'selectbox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 + + 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: _$font_attributes_240({ + 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} }, - 'spikeline': { - 'width': 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', - 'ascent': 850, - 'descent': -150 + + line: { + color: __extendFlat_296({}, scatterLineAttrs.color, { + editType: 'style+colorbars', + + }), + width: __extendFlat_296({}, scatterLineAttrs.width, { + editType: 'style+colorbars' + }), + dash: __dash_296, + smoothing: __extendFlat_296({}, scatterLineAttrs.smoothing, { + + }), + editType: 'plot' } -}; +}, + _$attributes_57, { + autocolorscale: __extendFlat_296({}, _$attributes_57.autocolorscale, {dflt: false}), + zmin: __extendFlat_296({}, _$attributes_57.zmin, {editType: 'calc'}), + zmax: __extendFlat_296({}, _$attributes_57.zmax, {editType: 'calc'}) + }, + { colorbar: _$attributes_52 } +); -var _$browser_32 = {}; -// shim for using process in browser -var process = _$browser_32 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. -var cachedSetTimeout; -var cachedClearTimeout; +'use strict'; -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +var __extendFlat_315 = _$lib_172.extendFlat; + + +var _$setContours_315 = function setContours(trace) { + var contours = trace.contours; + + // check if we need to auto-choose contour levels + if(trace.autocontour) { + var dummyAx = autoContours(trace.zmin, trace.zmax, trace.ncontours); + + contours.size = dummyAx.dtick; + + contours.start = _$axes_214.tickFirst(dummyAx); + dummyAx.range.reverse(); + contours.end = _$axes_214.tickFirst(dummyAx); + + if(contours.start === trace.zmin) contours.start += contours.size; + if(contours.end === trace.zmax) contours.end -= contours.size; + + // if you set a small ncontours, *and* the ends are exactly on zmin/zmax + // there's an edge case where start > end now. Make sure there's at least + // one meaningful contour, put it midway between the crossed values + if(contours.start > contours.end) { + contours.start = contours.end = (contours.start + contours.end) / 2; } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + + // copy auto-contour info back to the source data. + // previously we copied the whole contours object back, but that had + // other info (coloring, showlines) that should be left to supplyDefaults + if(!trace._input.contours) trace._input.contours = {}; + __extendFlat_315(trace._input.contours, { + start: contours.start, + end: contours.end, + size: contours.size + }); + trace._input.autocontour = true; } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); + else if(contours.type !== 'constraint') { + // sanity checks on manually-supplied start/end/size + var start = contours.start, + end = contours.end, + inputContours = trace._input.contours; + + if(start > end) { + contours.start = inputContours.start = end; + end = contours.end = inputContours.end = start; + start = contours.start; } - } + if(!(contours.size > 0)) { + var sizeOut; + if(start === end) sizeOut = 1; + else sizeOut = autoContours(start, end, trace.ncontours).dtick; -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); + inputContours.size = contours.size = sizeOut; } } +}; +/* + * autoContours: make a dummy axis object with dtick we can use + * as contours.size, and if needed we can use Axes.tickFirst + * with this axis object to calculate the start and end too + * + * start: the value to start the contours at + * end: the value to end at (must be > start) + * ncontours: max number of contours to make, like roughDTick + * + * returns: an axis object + */ +function autoContours(start, end, ncontours) { + var dummyAx = { + type: 'linear', + range: [start, end] + }; + + _$axes_214.autoTicks( + dummyAx, + (end - start) / (ncontours || 15) + ); + return dummyAx; } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + +var _$clean2dArray_320 = function clean2dArray(zOld, transpose) { + var rowlen, collen, getCollen, old2new, i, j; + + function cleanZvalue(v) { + if(!_$fastIsnumeric_18(v)) return undefined; + return +v; } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; + + if(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]; }; } - if (queue.length) { - drainQueue(); + else { + rowlen = zOld.length; + getCollen = function(zOld, i) { return zOld[i].length; }; + old2new = function(zOld, i, j) { return zOld[i][j]; }; } -} -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + var zNew = new Array(rowlen); - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; + for(i = 0; i < rowlen; i++) { + collen = getCollen(zOld, i); + zNew[i] = new Array(collen); + for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } + return zNew; }; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function __noop_32() {} -process.on = __noop_32; -process.addListener = __noop_32; -process.once = __noop_32; -process.off = __noop_32; -process.removeListener = __noop_32; -process.removeAllListeners = __noop_32; -process.emit = __noop_32; -process.prependListener = __noop_32; -process.prependOnceListener = __noop_32; +'use strict'; -process.listeners = function (name) { return [] } +/* removed: var _$lib_172 = require('../../lib'); */; +var __BADNUM_322 = _$numerical_154.BADNUM; -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; +var _$convertColumnData_322 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { + var col1 = trace[var1Name].slice(), + col2 = trace[var2Name].slice(), + textCol = trace.text, + colLen = Math.min(col1.length, col2.length), + hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), + col1Calendar = trace[var1Name + 'calendar'], + col2Calendar = trace[var2Name + 'calendar']; -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + var i, j, arrayVar, newArray, arrayVarName; -var _$es6Promise_16 = { exports: {} }; -(function (process,global){ -/*! - * @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 - */ + for(i = 0; i < arrayVarNames.length; i++) { + arrayVar = trace[arrayVarNames[i]]; + if(arrayVar) colLen = Math.min(colLen, arrayVar.length); + } -(function (global, factory) { - typeof _$es6Promise_16.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_16.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ES6Promise = factory()); -}(this, (function () { 'use strict'; + if(colLen < col1.length) col1 = col1.slice(0, colLen); + if(colLen < col2.length) col2 = col2.slice(0, colLen); -function objectOrFunction(x) { - return typeof x === 'function' || typeof x === 'object' && x !== null; -} + for(i = 0; i < colLen; i++) { + col1[i] = ax1.d2c(col1[i], 0, col1Calendar); + col2[i] = ax2.d2c(col2[i], 0, col2Calendar); + } -function isFunction(x) { - return typeof x === 'function'; -} + var col1dv = _$lib_172.distinctVals(col1), + col1vals = col1dv.vals, + col2dv = _$lib_172.distinctVals(col2), + col2vals = col2dv.vals, + newArrays = []; -var _isArray = undefined; -if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} else { - _isArray = Array.isArray; -} + for(i = 0; i < arrayVarNames.length; i++) { + newArrays[i] = _$lib_172.init2dArray(col2vals.length, col1vals.length); + } -var isArray = _isArray; + var i1, i2, text; -var len = 0; -var vertxNext = undefined; -var customSchedulerFn = undefined; + if(hasColumnText) text = _$lib_172.init2dArray(col2vals.length, col1vals.length); -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(); - } - } -}; + for(i = 0; i < colLen; i++) { + if(col1[i] !== __BADNUM_322 && col2[i] !== __BADNUM_322) { + i1 = _$lib_172.findBin(col1[i] + col1dv.minDiff / 2, col1vals); + i2 = _$lib_172.findBin(col2[i] + col2dv.minDiff / 2, col2vals); -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; -} + for(j = 0; j < arrayVarNames.length; j++) { + arrayVarName = arrayVarNames[j]; + arrayVar = trace[arrayVarName]; + newArray = newArrays[j]; + newArray[i2][i1] = arrayVar[i]; + } -function setAsap(asapFn) { - asap = asapFn; -} + if(hasColumnText) text[i2][i1] = textCol[i]; + } + } -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]'; + trace['_' + var1Name] = col1vals; + trace['_' + var2Name] = col2vals; + for(j = 0; j < arrayVarNames.length; j++) { + trace['_' + arrayVarNames[j]] = newArrays[j]; + } + if(hasColumnText) trace._text = text; +}; -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -// 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); - }; -} +'use strict'; -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); +var _$maxRowLength_330 = function maxRowLength(z) { + var len = 0; - return function () { - node.data = iterations = ++iterations % 2; - }; -} + for(var i = 0; i < z.length; i++) { + len = Math.max(len, z[i].length); + } -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); - }; -} + return len; +}; -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); - }; -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; +'use strict'; - callback(arg); +/* removed: var _$maxRowLength_330 = require('./max_row_length'); */; - queue[i] = undefined; - queue[i + 1] = undefined; - } +/* 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 + */ +var _$findEmpties_324 = function findEmpties(z) { + var empties = [], + neighborHash = {}, + noNeighborList = [], + nextRow = z[0], + row = [], + blank = [0, 0, 0], + rowLength = _$maxRowLength_330(z), + prevRow, + i, + j, + thisPt, + p, + neighborCount, + newNeighborHash, + foundNewNeighbors; - len = 0; -} + 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); -function attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} + 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++; -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 && typeof require === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); -} + // 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]; + } -function then(onFulfillment, onRejection) { - var _arguments = arguments; + empties.push([i, j, neighborCount]); + } + else noNeighborList.push([i, j]); + } + } + } - var parent = this; + while(noNeighborList.length) { + newNeighborHash = {}; + foundNewNeighbors = false; - var child = new this.constructor(noop); + // 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]; - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } + 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; - var _state = parent._state; + if(neighborCount) { + newNeighborHash[thisPt] = [i, j, neighborCount]; + noNeighborList.splice(p, 1); + foundNewNeighbors = true; + } + } - if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } + if(!foundNewNeighbors) { + throw 'findEmpties iterated with no new neighbors'; + } - return child; -} + // 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]; }); +}; /** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ```javascript - let promise = new Promise(function(resolve, reject){ - resolve(1); - }); +'use strict'; - promise.then(function(value){ - // value === 1 - }); - ``` +var __isArrayOrTypedArray_325 = _$lib_172.isArrayOrTypedArray; - Instead of writing the above, your code now simply becomes the following: +var _$has_columns_325 = function(trace) { + return !__isArrayOrTypedArray_325(trace.z[0]); +}; - ```javascript - let promise = Promise.resolve(1); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - promise.then(function(value){ - // value === 1 - }); - ``` +'use strict'; - @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; +/* removed: var _$lib_172 = require('../../lib'); */; - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } +var INTERPTHRESHOLD = 1e-2, + NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; +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); } -var PROMISE_ID = Math.random().toString(36).substring(16); +var _$interp2d_328 = function interp2d(z, emptyPoints, savedInterpZ) { + // fill in any missing data in 2D array z 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) + var maxFractionalChange = 1, + i, + thisPt; -function noop() {} + if(Array.isArray(savedInterpZ)) { + for(i = 0; i < emptyPoints.length; i++) { + thisPt = emptyPoints[i]; + z[thisPt[0]][thisPt[1]] = savedInterpZ[thisPt[0]][thisPt[1]]; + } + } + else { + // one pass to fill in a starting value for all the empties + iterateInterp2d(z, emptyPoints); + } -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; + // 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); -var GET_THEN_ERROR = new ErrorObject(); + for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) { + maxFractionalChange = iterateInterp2d(z, emptyPoints, + correctionOvershoot(maxFractionalChange)); + } + if(maxFractionalChange > INTERPTHRESHOLD) { + _$lib_172.log('interp2d didn\'t converge quickly', maxFractionalChange); + } -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} + return z; +}; -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} +function iterateInterp2d(z, emptyPoints, overshoot) { + var maxFractionalChange = 0, + thisPt, + i, + j, + p, + q, + neighborShift, + neighborRow, + neighborVal, + neighborCount, + neighborSum, + initialVal, + minNeighbor, + maxNeighbor; -function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} + for(p = 0; p < emptyPoints.length; p++) { + thisPt = emptyPoints[p]; + i = thisPt[0]; + j = thisPt[1]; + initialVal = z[i][j]; + neighborSum = 0; + neighborCount = 0; -function tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } -} + 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; + } + } -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; + if(neighborCount === 0) { + throw 'iterateInterp2d order is wrong: no defined neighbors'; + } - _reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); + // 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 (!sealed && error) { - sealed = true; - _reject(promise, error); + 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)); + } + } } - }, 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); - }); - } + return maxFractionalChange; } -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); - } - } -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function _resolve(promise, value) { - if (promise === value) { - _reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } -} +'use strict'; -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } +/* removed: var _$registry_262 = require('../../registry'); */; +var __isArrayOrTypedArray_329 = _$lib_172.isArrayOrTypedArray; - publish(promise); -} +var _$makeBoundArray_329 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { + var arrayOut = [], + isContour = _$registry_262.traceIs(trace, 'contour'), + isHist = _$registry_262.traceIs(trace, 'histogram'), + isGL2D = _$registry_262.traceIs(trace, 'gl2d'), + v0, + dv, + i; -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } + var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_329(arrayIn) && arrayIn.length > 1; - promise._result = value; - promise._state = FULFILLED; + if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) { + var len = arrayIn.length; - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} + // given vals are brick centers + // hopefully length === numbricks, but use this method even if too few are supplied + // and extend it linearly based on the last two points + if(len <= numbricks) { + // contour plots only want the centers + if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks); + else if(numbricks === 1) { + arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5]; + } + else { + arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]]; -function _reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; + for(i = 1; i < len; i++) { + arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5); + } - asap(publishRejection, promise); -} + arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]); + } -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; + if(len < numbricks) { + var lastPt = arrayOut[arrayOut.length - 1], + delta = lastPt - arrayOut[arrayOut.length - 2]; - parent._onerror = null; + for(i = len; i < numbricks; i++) { + lastPt += delta; + arrayOut.push(lastPt); + } + } + } + else { + // hopefully length === numbricks+1, but do something regardless: + // given vals are brick boundaries + return isContour ? + arrayIn.slice(0, numbricks) : // we must be strict for contours + arrayIn.slice(0, numbricks + 1); + } + } + else { + dv = dvIn || 1; - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; + var calendar = trace[ax._id.charAt(0) + 'calendar']; - if (length === 0 && parent._state) { - asap(publish, parent); - } -} + if(isHist || ax.type === 'category') v0 = ax.r2c(v0In, 0, calendar) || 0; + else if(__isArrayOrTypedArray_329(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; + else if(v0In === undefined) v0 = 0; + else v0 = ax.d2c(v0In, 0, calendar); -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; + for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) { + arrayOut.push(v0 + dv * i); + } + } - if (subscribers.length === 0) { - return; - } + return arrayOut; +}; - var child = undefined, - callback = undefined, - detail = promise._result; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 (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); +'use strict'; + + +var _$doAvg_336 = function doAvg(size, counts) { + var nMax = size.length, + total = 0; + for(var i = 0; i < nMax; i++) { + if(counts[i]) { + size[i] /= counts[i]; + total += size[i]; + } + else size[i] = null; } - } + return total; +}; - promise._subscribers.length = 0; -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function ErrorObject() { - this.error = null; -} -var TRY_CATCH_ERROR = new ErrorObject(); +'use strict'; -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; - if (hasCallback) { - value = tryCatch(callback, detail); +var _$bin_functions_338 = { + count: function(n, i, size) { + size[n]++; + return 1; + }, - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } + sum: function(n, i, size, counterData) { + var v = counterData[i]; + if(_$fastIsnumeric_18(v)) { + v = Number(v); + size[n] += v; + return v; + } + return 0; + }, - if (promise === value) { - _reject(promise, cannotReturnOwn()); - return; - } - } else { - value = detail; - succeeded = true; - } + avg: function(n, i, size, counterData, counts) { + var v = counterData[i]; + if(_$fastIsnumeric_18(v)) { + v = Number(v); + size[n] += v; + counts[n]++; + } + return 0; + }, - 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); - } -} + min: function(n, i, size, counterData) { + var v = counterData[i]; + if(_$fastIsnumeric_18(v)) { + v = Number(v); + if(!_$fastIsnumeric_18(size[n])) { + size[n] = v; + return v; + } + else if(size[n] > v) { + var delta = v - size[n]; + size[n] = v; + return delta; + } + } + return 0; + }, -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value) { - _resolve(promise, value); - }, function rejectPromise(reason) { - _reject(promise, reason); - }); - } catch (e) { - _reject(promise, e); - } -} + max: function(n, i, size, counterData) { + var v = counterData[i]; + if(_$fastIsnumeric_18(v)) { + v = Number(v); + if(!_$fastIsnumeric_18(size[n])) { + size[n] = v; + return v; + } + else if(size[n] < v) { + var delta = v - size[n]; + size[n] = v; + return delta; + } + } + return 0; + } +}; -var id = 0; -function nextId() { - return id++; -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -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); +'use strict'; - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } +/* removed: var _$numerical_154 = require('../../constants/numerical'); */; +var oneYear = _$numerical_154.ONEAVGYEAR; +var oneMonth = _$numerical_154.ONEAVGMONTH; +var oneDay = _$numerical_154.ONEDAY; +var oneHour = _$numerical_154.ONEHOUR; +var oneMin = _$numerical_154.ONEMIN; +var oneSec = _$numerical_154.ONESEC; +var tickIncrement = _$axes_214.tickIncrement; - if (isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; - this._result = new Array(this.length); +/* + * 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` + */ +var _$getBinSpanLabelRound_339 = 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) + ); - 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); - } + // 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; } - } 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; + if(pa.type === 'date' && digit > oneDay) { + var dashExclude = (digit === oneYear) ? 1 : 6; + var increment = (digit === oneYear) ? 'M12' : 'M1'; - for (var i = 0; this._state === PENDING && i < length; i++) { - this._eachEntry(_input[i], i); - } -}; + 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); -Enumerator.prototype._eachEntry = function (entry, i) { - var c = this._instanceConstructor; - var resolve$$ = c.resolve; + if(roundedV < v) { + var nextV = tickIncrement(roundedV, increment, false, calendar); + if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV; + } - if (resolve$$ === resolve) { - var _then = getThen(entry); + if(isRightEdge && disambiguateEdges) { + return tickIncrement(roundedV, increment, true, calendar); + } - 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); + return roundedV; + }; } - } else { - this._willSettleAt(resolve$$(entry), i); - } -}; -Enumerator.prototype._settledAt = function (state, i, value) { - var promise = this.promise; + 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; + }; +}; - if (promise._state === PENDING) { - this._remaining--; +/* + * 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; - if (state === REJECTED) { - _reject(promise, value); - } else { - this._result[i] = value; + 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; +} - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; +/* + * 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; + } -Enumerator.prototype._willSettleAt = function (promise, i) { - var enumerator = this; + if(dv > oneHour) return oneHour; + if(dv > oneMin) return oneMin; + return oneSec; + } + return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10)); +} - subscribe(promise, undefined, function (value) { - return enumerator._settledAt(FULFILLED, i, value); - }, function (reason) { - return enumerator._settledAt(REJECTED, i, reason); - }); -}; +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]; -/** - `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. + } + return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1; +} - Example: +function dateParts(v, pa, calendar) { + var parts = pa.c2d(v, oneYear, calendar).split('-'); + if(parts[0] === '') { + parts.unshift(); + parts[0] = '-' + parts[0]; + } + return parts; +} - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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: +'use strict'; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +var cleanDate = _$lib_172.cleanDate; +/* removed: var _$numerical_154 = require('../../constants/numerical'); */; +var __ONEDAY_341 = _$numerical_154.ONEDAY; +var __BADNUM_341 = _$numerical_154.BADNUM; - Example: +/* + * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) + * Mutates trace so all these attributes are valid. + * + * Normally this kind of thing would happen during supplyDefaults, but + * in this case we need to know the axis type, and axis type isn't set until + * after trace supplyDefaults are completed. So this gets called during the + * calc step, when data are inserted into bins. + */ +var _$cleanBins_341 = function cleanBins(trace, ax, binDirection) { + var axType = ax.type, + binAttr = binDirection + 'bins', + bins = trace[binAttr]; - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; + if(!bins) bins = trace[binAttr] = {}; - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` + var cleanBound = (axType === 'date') ? + function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_341, bins.calendar) : null; } : + function(v) { return _$fastIsnumeric_18(v) ? Number(v) : null; }; - @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; -} + bins.start = cleanBound(bins.start); + bins.end = cleanBound(bins.end); -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. + // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) + // but without the extra string options for log axes + // ie the only strings we accept are M for months + var sizeDflt = (axType === 'date') ? __ONEDAY_341 : 1, + binSize = bins.size; - Example: + if(_$fastIsnumeric_18(binSize)) { + bins.size = (binSize > 0) ? Number(binSize) : sizeDflt; + } + else if(typeof binSize !== 'string') { + bins.size = sizeDflt; + } + else { + // date special case: "M" gives bins every (integer) n months + var prefix = binSize.charAt(0), + sizeNum = binSize.substr(1); - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); + sizeNum = _$fastIsnumeric_18(sizeNum) ? Number(sizeNum) : 0; + if((sizeNum <= 0) || !( + axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum) + )) { + bins.size = sizeDflt; + } + } - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); + var autoBinAttr = 'autobin' + binDirection; - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` + if(typeof trace[autoBinAttr] !== 'boolean') { + trace[autoBinAttr] = trace._fullInput[autoBinAttr] = trace._input[autoBinAttr] = !( + (bins.start || bins.start === 0) && + (bins.end || bins.end === 0) + ); + } - `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: + if(!trace[autoBinAttr]) { + delete trace['nbins' + binDirection]; + delete trace._fullInput['nbins' + binDirection]; + } +}; - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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 - }); - ``` +'use strict'; - An example real-world use case is implementing timeouts: - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` +var _$norm_functions_346 = { + percent: function(size, total) { + var nMax = size.length, + norm = 100 / total; + for(var n = 0; n < nMax; n++) size[n] *= norm; + }, + probability: function(size, total) { + var nMax = size.length; + for(var n = 0; n < nMax; n++) size[n] /= total; + }, + density: function(size, total, inc, yinc) { + var nMax = size.length; + yinc = yinc || 1; + for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc; + }, + 'probability density': function(size, total, inc, yinc) { + var nMax = size.length; + if(yinc) total /= yinc; + for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total; + } +}; - @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. +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. */ -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: +'use strict'; - ```javascript - let promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` +/* removed: var _$bin_functions_338 = require('../histogram/bin_functions'); */; +/* removed: var _$norm_functions_346 = require('../histogram/norm_functions'); */; +/* removed: var _$doAvg_336 = require('../histogram/average'); */; +/* removed: var _$cleanBins_341 = require('../histogram/clean_bins'); */; +/* removed: var _$getBinSpanLabelRound_339 = require('../histogram/bin_label_vals'); */; - Instead of writing the above, your code now simply becomes the following: - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); +var _$calc_348 = function calc(gd, trace) { + var xa = _$axes_214.getFromId(gd, trace.xaxis || 'x'); + var x = trace.x ? xa.makeCalcdata(trace, 'x') : []; + var ya = _$axes_214.getFromId(gd, trace.yaxis || 'y'); + var y = trace.y ? ya.makeCalcdata(trace, 'y') : []; + 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); }; - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + var i, j, n, m; - @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; -} + var serieslen = Math.min(x.length, y.length); + if(x.length > serieslen) x.splice(serieslen, x.length - serieslen); + if(y.length > serieslen) y.splice(serieslen, y.length - serieslen); -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} + // calculate the bins + cleanAndAutobin(trace, 'x', x, xa, xr2c, xc2r, xcalendar); + cleanAndAutobin(trace, 'y', y, ya, yr2c, yc2r, ycalendar); -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} + // make the empty bin array & scale the map + var z = []; + var onecol = []; + var zerocol = []; + var nonuniformBinsX = (typeof(trace.xbins.size) === 'string'); + var nonuniformBinsY = (typeof(trace.ybins.size) === 'string'); + var xEdges = []; + var yEdges = []; + var xbins = nonuniformBinsX ? xEdges : trace.xbins; + var ybins = nonuniformBinsY ? yEdges : trace.ybins; + 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 = _$bin_functions_338.count; + var normfunc = _$norm_functions_346[norm]; + var doavg = false; + var xinc = []; + var yinc = []; -/** - 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. + // 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 = _$bin_functions_338[func]; + } - Terminology - ----------- + // decrease end a little in case of rounding errors + var binSpec = trace.xbins, + binStart = xr2c(binSpec.start), + binEnd = xr2c(binSpec.end) + + (binStart - _$axes_214.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; - - `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. + for(i = binStart; i < binEnd; i = _$axes_214.tickIncrement(i, binSpec.size, false, xcalendar)) { + onecol.push(sizeinit); + xEdges.push(i); + if(doavg) zerocol.push(0); + } + xEdges.push(i); - A promise can be in one of three states: pending, fulfilled, or rejected. + var nx = onecol.length; + var x0c = xr2c(trace.xbins.start); + var dx = (i - x0c) / nx; + var x0 = xc2r(x0c + dx / 2); - 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. + binSpec = trace.ybins; + binStart = yr2c(binSpec.start); + binEnd = yr2c(binSpec.end) + + (binStart - _$axes_214.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; - 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. + for(i = binStart; i < binEnd; i = _$axes_214.tickIncrement(i, binSpec.size, 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 y0c = yr2c(trace.ybins.start); + var dy = (i - y0c) / ny; + var y0 = yc2r(y0c + dy / 2); - Basic Usage: - ------------ + if(densitynorm) { + xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX); + yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY); + } - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); + // 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); - // on failure - reject(reason); - }); + // 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 = x[i]; + var yi = y[i]; + n = _$lib_172.findBin(xi, xbins); + m = _$lib_172.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); - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + if(uniqueValsPerX) { + if(xVals[n] === undefined) xVals[n] = xi; + else if(xVals[n] !== xi) uniqueValsPerX = false; + } + if(uniqueValsPerY) { + if(yVals[n] === undefined) yVals[n] = yi; + else if(yVals[n] !== yi) uniqueValsPerY = false; + } - Advanced Usage: - --------------- + 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_336(z[m], counts[m]); + } + if(normfunc) { + for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); + } - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + return { + x: x, + xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar), + x0: x0, + dx: dx, + y: y, + yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar), + y0: y0, + dy: dy, + z: z, + pts: inputPoints + }; +}; - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); +function cleanAndAutobin(trace, axLetter, data, ax, r2c, c2r, calendar) { + var binSpecAttr = axLetter + 'bins'; + var autoBinAttr = 'autobin' + axLetter; + var binSpec = trace[binSpecAttr]; - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + _$cleanBins_341(trace, ax, axLetter); - 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 + ']')); - } + if(trace[autoBinAttr] || !binSpec || binSpec.start === null || binSpec.end === null) { + binSpec = _$axes_214.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); + if(trace.type === 'histogram2dcontour') { + // the "true" last argument reverses the tick direction (which we can't + // just do with a minus sign because of month bins) + binSpec.start = c2r(_$axes_214.tickIncrement( + r2c(binSpec.start), binSpec.size, true, calendar)); + binSpec.end = c2r(_$axes_214.tickIncrement( + r2c(binSpec.end), binSpec.size, false, calendar)); } - }; - }); - } - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + // copy bin info back to the source data. + trace._input[binSpecAttr] = trace[binSpecAttr] = binSpec; + // note that it's possible to get here with an explicit autobin: false + // if the bins were not specified. + // in that case this will remain in the trace, so that future updates + // which would change the autobinning will not do so. + trace._input[autoBinAttr] = trace[autoBinAttr]; + } +} - Unlike callbacks, promises are great composable primitives. +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; +} - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON +function binsToCalc(r2c, bins) { + return { + start: r2c(bins.start), + end: r2c(bins.end), + size: bins.size + }; +} - return values; - }); - ``` +function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { + var i; + var len = edges.length - 1; + var out = new Array(len); + if(uniqueVals) { + for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]]; + } + else { + var roundFn = _$getBinSpanLabelRound_339(gapLow, gapHigh, edges, ax, calendar); + for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)]; + } + return out; +} - @class Promise - @param {function} resolver - Useful for tooling. - @constructor +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. */ -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; +'use strict'; -Promise.prototype = { - constructor: Promise, +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; - /** - 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 +/* removed: var _$calc_348 = require('../histogram2d/calc'); */; +/* removed: var _$calc_58 = require('../../components/colorscale/calc'); */; +/* removed: var _$has_columns_325 = require('./has_columns'); */; +/* removed: var _$convertColumnData_322 = require('./convert_column_xyz'); */; +/* removed: var _$maxRowLength_330 = require('./max_row_length'); */; +/* removed: var _$clean2dArray_320 = require('./clean_2d_array'); */; +/* removed: var _$interp2d_328 = require('./interp2d'); */; +/* removed: var _$findEmpties_324 = require('./find_empties'); */; +/* removed: var _$makeBoundArray_329 = require('./make_bound_array'); */; + + +var _$calc_319 = 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_214.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_214.getFromId(gd, trace.yaxis || 'y'), + isContour = _$registry_262.traceIs(trace, 'contour'), + isHist = _$registry_262.traceIs(trace, 'histogram'), + isGL2D = _$registry_262.traceIs(trace, 'gl2d'), + zsmooth = isContour ? 'best' : trace.zsmooth, + x, + x0, + dx, + y, + y0, + dy, + z, + i, + binned; + + // cancel minimum tick spacings (only applies to bars and boxes) + xa._minDtick = 0; + ya._minDtick = 0; + + if(isHist) { + binned = _$calc_348(gd, trace); + x = binned.x; + x0 = binned.x0; + dx = binned.dx; + y = binned.y; + y0 = binned.y0; + dy = binned.dy; + z = binned.z; } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - + else { + var zIn = trace.z; + if(_$has_columns_325(trace)) { + _$convertColumnData_322(trace, xa, ya, 'x', 'y', ['z']); + x = trace._x; + y = trace._y; + zIn = trace._z; + } else { + x = trace.x ? xa.makeCalcdata(trace, 'x') : []; + y = trace.y ? ya.makeCalcdata(trace, 'y') : []; + } + + x0 = trace.x0 || 0; + dx = trace.dx || 1; + y0 = trace.y0 || 0; + dy = trace.dy || 1; + + z = _$clean2dArray_320(zIn, trace.transpose); + + if(isContour || trace.connectgaps) { + trace._emptypoints = _$findEmpties_324(z); + trace._interpz = _$interp2d_328(z, trace._emptypoints, trace._interpz); + } } - - function failure(reason) { - + + function noZsmooth(msg) { + zsmooth = trace._input.zsmooth = trace.zsmooth = false; + _$lib_172.warn('cannot use zsmooth: "fast": ' + msg); } - - 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); - } + + // 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), + 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), + 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; + } + } } - }); - } 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; + // create arrays of brick boundaries, to be used by autorange and heatmap.plot + var xlen = _$maxRowLength_330(z); + var xIn = trace.xtype === 'scaled' ? '' : x; + var xArray = _$makeBoundArray_329(trace, xIn, x0, dx, xlen, xa); + var yIn = trace.ytype === 'scaled' ? '' : y; + var yArray = _$makeBoundArray_329(trace, yIn, y0, dy, z.length, ya); - 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'); - } + // handled in gl2d convert step + if(!isGL2D) { + _$axes_214.expand(xa, xArray); + _$axes_214.expand(ya, yArray); } - var P = local.Promise; + var cd0 = { + x: xArray, + y: yArray, + z: z, + text: trace._text || trace.text + }; - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } + if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn; + if(yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn; - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } + if(isHist) { + cd0.xRanges = binned.xRanges; + cd0.yRanges = binned.yRanges; + cd0.pts = binned.pts; } - local.Promise = Promise; -} + // auto-z and autocolorscale if applicable + if(!isContour || trace.contours.type !== 'constraint') { + _$calc_58(trace, z, '', 'z'); + } -polyfill(); -// Strange compat.. -Promise.polyfill = polyfill; -Promise.Promise = Promise; + 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_329(dummyTrace, xIn, x0, dx, xlen, xa); + cd0.yfill = _$makeBoundArray_329(dummyTrace, yIn, y0, dy, z.length, ya); + } -return Promise; + return [cd0]; +}; -}))); -//# sourceMappingURL=es6-promise.map -}).call(this,_$browser_32,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$es6Promise_16 = _$es6Promise_16.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -43770,67 +43521,39 @@ _$es6Promise_16 = _$es6Promise_16.exports * LICENSE file in the root directory of this source tree. */ + 'use strict'; +/* removed: var _$calc_319 = require('../heatmap/calc'); */; +/* removed: var _$setContours_315 = require('./set_contours'); */; + +// 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 +var _$calc_297 = function calc(gd, trace) { + var cd = _$calc_319(gd, trace); + _$setContours_315(trace); + return cd; +}; + /** - * All paths are tuned for maximum scalability of the arrowhead, - * ie throughout arrowwidth=0.3..3 the head is joined smoothly - * to the line, with the line coming from the left and ending at (0, 0). - * - * `backoff` is the distance to move the arrowhead and the end of the line, - * in order that the arrowhead points to the desired place, either at - * the tip of the arrow or (in the case of circle or square) - * the center of the symbol. - * - * `noRotate`, if truthy, says that this arrowhead should not rotate with the - * arrow. That's the case for squares, which should always be straight, and - * circles, for which it's irrelevant. - */ +* Copyright 2012-2018, Plotly, Inc. +* All 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 _$arrow_paths_35 = [ - // no arrow - { - path: '', - backoff: 0 - }, - // wide with flat back - { - path: 'M-2.4,-3V3L0.6,0Z', - backoff: 0.6 - }, - // narrower with flat back - { - path: 'M-3.7,-2.5V2.5L1.3,0Z', - backoff: 1.3 - }, - // barbed - { - path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', - backoff: 1.55 - }, - // wide line-drawn - { - path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', - backoff: 1.6 - }, - // narrower line-drawn - { - path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', - backoff: 2 - }, - // circle - { - path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', - backoff: 0, - noRotate: true - }, - // square - { - path: 'M2,2V-2H-2V2Z', - backoff: 0, - noRotate: true - } -]; + +'use strict'; + +/* + * tiny helper to move the end of the contours a little to prevent + * losing the last contour to rounding errors + */ +var _$endPlus_307 = function endPlus(contours) { + return contours.end + contours.size / 1e6; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -43840,351 +43563,79 @@ var _$arrow_paths_35 = [ * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$arrow_paths_35 = require('./arrow_paths'); */; -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_218 = require('../../plots/cartesian/constants'); */; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$colorscale_66 = require('../../components/colorscale'); */; +/* removed: var _$endPlus_307 = require('./end_plus'); */; +var _$makeColorMap_312 = function makeColorMap(trace) { + var contours = trace.contours, + start = contours.start, + end = _$endPlus_307(contours), + cs = contours.size || 1, + nc = Math.floor((end - start) / cs) + 1, + extra = contours.coloring === 'lines' ? 0 : 1; -var _$attributes_36 = { - _isLinkedToArray: 'annotation', + if(!isFinite(cs)) { + cs = 1; + nc = 1; + } - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, + var scl = trace.colorscale, + len = scl.length; - text: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, - textangle: { - valType: 'angle', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - font: _$font_attributes_240({ - editType: 'calcIfAutorange+arraydraw', - colorEditType: 'arraydraw', - - }), - width: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - height: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - align: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'center', - - editType: 'arraydraw', - - }, - valign: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'middle', - - editType: 'arraydraw', - - }, - bgcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - borderpad: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - // arrow - showarrow: { - valType: 'boolean', - dflt: true, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - arrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_35.length, - dflt: 1, - - editType: 'arraydraw', - - }, - startarrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_35.length, - dflt: 1, - - editType: 'arraydraw', - - }, - arrowside: { - valType: 'flaglist', - flags: ['end', 'start'], - extras: ['none'], - dflt: 'end', - - editType: 'arraydraw', - - }, - arrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - startarrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowwidth: { - valType: 'number', - min: 0.1, - - editType: 'calcIfAutorange+arraydraw', - - }, - standoff: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - startstandoff: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - ax: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - ay: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - axref: { - valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_218.idRegex.x.toString() - ], - - editType: 'calc', - - }, - ayref: { - valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_218.idRegex.y.toString() - ], - - editType: 'calc', - - }, - // positioning - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_218.idRegex.x.toString() - ], - - editType: 'calc', - - }, - x: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - - }, - xshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_218.idRegex.y.toString() - ], - - editType: 'calc', - - }, - y: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - - }, - yshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - clicktoshow: { - valType: 'enumerated', - values: [false, 'onoff', 'onout'], - dflt: false, - - editType: 'arraydraw', - - }, - xclick: { - valType: 'any', - - editType: 'arraydraw', - - }, - yclick: { - valType: 'any', - - editType: 'arraydraw', - - }, - hovertext: { - valType: 'string', - - editType: 'arraydraw', - - }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - font: _$font_attributes_240({ - editType: 'arraydraw', - - }), - editType: 'arraydraw' - }, - captureevents: { - valType: 'boolean', - - editType: 'arraydraw', - - }, - editType: 'calc', + var domain = new Array(len), + range = new Array(len); - _deprecated: { - ref: { - valType: 'string', - - editType: 'calc', - + var si, i; + + if(contours.coloring === 'heatmap') { + if(trace.zauto && trace.autocontour === false) { + trace.zmin = start - cs / 2; + trace.zmax = trace.zmin + nc * cs; + } + + for(i = 0; i < len; i++) { + si = scl[i]; + + domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin; + range[i] = si[1]; + } + + // do the contours extend beyond the colorscale? + // if so, extend the colorscale with constants + var zRange = _$d3_15.extent([trace.zmin, trace.zmax, contours.start, + contours.start + cs * (nc - 1)]), + zmin = zRange[trace.zmin < trace.zmax ? 0 : 1], + zmax = zRange[trace.zmin < trace.zmax ? 1 : 0]; + + if(zmin !== trace.zmin) { + domain.splice(0, 0, zmin); + range.splice(0, 0, Range[0]); + } + + if(zmax !== trace.zmax) { + domain.push(zmax); + range.push(range[range.length - 1]); + } + } + else { + for(i = 0; i < len; i++) { + si = scl[i]; + + domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start; + range[i] = si[1]; } } + + return _$colorscale_66.makeColorScaleFunc({ + domain: domain, + range: range, + }, { + noNumericCheck: true + }); }; /** @@ -44198,146 +43649,83 @@ var _$attributes_36 = { 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; - -/* removed: var _$color_51 = require('../color'); */; - -/* removed: var _$arrow_paths_35 = require('./arrow_paths'); */; - -/** - * 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. - */ -var _$drawArrowHead_43 = function drawArrowHead(el3, ends, options) { - var el = el3.node(); - var headStyle = _$arrow_paths_35[options.arrowhead || 0]; - var startHeadStyle = _$arrow_paths_35[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), - backOffY = backOff * Math.sin(startRot); +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$draw_55 = require('../../components/colorbar/draw'); */; - end.x += backOffX; - end.y += backOffY; - el3.attr({x2: end.x, y2: end.y}); +/* removed: var _$makeColorMap_312 = require('./make_color_map'); */; +/* removed: var _$endPlus_307 = require('./end_plus'); */; - } - if(startBackOff) { - if(startBackOff * startBackOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var startBackOffX = startBackOff * Math.cos(startRot), - startbackOffY = startBackOff * Math.sin(startRot); +var _$colorbar_299 = function colorbar(gd, cd) { + var trace = cd[0].trace, + cbId = 'cb' + trace.uid; - start.x -= startBackOffX; - start.y -= startbackOffY; - el3.attr({x1: start.x, y1: start.y}); + gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); - } + if(!trace.showscale) { + _$plots_246.autoMargin(gd, cbId); + return; } - 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 - dashArray = ''; - - if(pathlen < backOff + startBackOff) { - hideLine(); - return; - } - - var start0 = el.getPointAtLength(0); - var dstart = el.getPointAtLength(0.1); + var cb = _$draw_55(gd, cbId); + cd[0].t.cb = cb; - startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); - start = el.getPointAtLength(Math.min(startBackOff, pathlen)); + var contours = trace.contours, + line = trace.line, + cs = contours.size || 1, + coloring = contours.coloring; - dashArray = '0px,' + startBackOff + 'px,'; + var colorMap = _$makeColorMap_312(trace, {isColorbar: true}); - var end0 = el.getPointAtLength(pathlen); - var dend = el.getPointAtLength(pathlen - 0.1); + if(coloring === 'heatmap') { + cb.filllevels({ + start: trace.zmin, + end: trace.zmax, + size: (trace.zmax - trace.zmin) / 254 + }); + } - endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); - end = el.getPointAtLength(Math.max(0, pathlen - backOff)); + cb.fillcolor((coloring === 'fill' || coloring === 'heatmap') ? colorMap : '') + .line({ + color: coloring === 'lines' ? colorMap : line.color, + width: contours.showlines !== false ? line.width : 0, + dash: line.dash + }) + .levels({ + start: contours.start, + end: _$endPlus_307(contours), + size: cs + }) + .options(trace.colorbar)(); +}; - var shortening = dashArray ? startBackOff + backOff : backOff; - dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - el3.style('stroke-dasharray', dashArray); - } - function hideLine() { el3.style('stroke-dasharray', '0px,100px'); } +'use strict'; - function drawhead(arrowHeadStyle, p, rot, arrowScale) { - if(!arrowHeadStyle.path) return; - if(arrowHeadStyle.noRotate) rot = 0; +/* removed: var _$lib_172 = require('../../lib'); */; - _$d3_15.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_51.rgb(options.arrowcolor), - 'stroke-width': 0 - }); +var _$handleLabelDefaults_311 = function handleLabelDefaults(coerce, layout, lineColor, opts) { + if(!opts) opts = {}; + var showLabels = coerce('contours.showlabels'); + if(showLabels) { + var globalFont = layout.font; + _$lib_172.coerceFont(coerce, 'contours.labelfont', { + family: globalFont.family, + size: globalFont.size, + color: lineColor + }); + coerce('contours.labelformat'); } - if(doStart) drawhead(startHeadStyle, start, startRot, startScale); - if(doEnd) drawhead(headStyle, end, endRot, scale); + if(opts.hasHover !== false) coerce('zhoverformat'); }; /** @@ -44348,703 +43736,467 @@ var _$drawArrowHead_43 = function drawArrowHead(el3, ends, options) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$handleLabelDefaults_311 = require('./label_defaults'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$fx_93 = require('../fx'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_190 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$drawArrowHead_43 = require('./draw_arrow_head'); */; +/* removed: var _$color_51 = require('../../components/color'); */; +var addOpacity = _$color_51.addOpacity; +var opacity = _$color_51.opacity; -// Annotations are stored in gd.layout.annotations, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one +/* removed: var _$filter_ops_152 = require('../../constants/filter_ops'); */; +var CONSTRAINT_REDUCTION = _$filter_ops_152.CONSTRAINT_REDUCTION; +var __COMPARISON_OPS2_301 = _$filter_ops_152.COMPARISON_OPS2; -var _$draw_42 = { - draw: __draw_42, - drawOne: drawOne, - drawRaw: drawRaw -}; +var _$handleConstraintDefaults_301 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { + var contours = traceOut.contours; + var showLines, lineColor, fillColor; -/* - * draw: draw all annotations without any new modifications - */ -function __draw_42(gd) { - var fullLayout = gd._fullLayout; + var operation = coerce('contours.operation'); + contours._operation = CONSTRAINT_REDUCTION[operation]; - fullLayout._infolayer.selectAll('.annotation').remove(); + handleConstraintValueDefaults(coerce, contours); - for(var i = 0; i < fullLayout.annotations.length; i++) { - if(fullLayout.annotations[i].visible) { - drawOne(gd, i); - } + if(operation === '=') { + showLines = contours.showlines = true; + } + else { + showLines = coerce('contours.showlines'); + fillColor = coerce('fillcolor', addOpacity( + (traceIn.line || {}).color || defaultColor, 0.5 + )); } - return _$plots_246.previousPromises(gd); -} + if(showLines) { + var lineDfltColor = fillColor && opacity(fillColor) ? + addOpacity(traceOut.fillcolor, 1) : + defaultColor; + lineColor = coerce('line.color', lineDfltColor); + coerce('line.width', 2); + coerce('line.dash'); + } -/* - * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications - * - * index (int): the annotation to draw - */ -function drawOne(gd, index) { - var fullLayout = gd._fullLayout; - var options = fullLayout.annotations[index] || {}; - var xa = _$axes_213.getFromId(gd, options.xref); - var ya = _$axes_213.getFromId(gd, options.yref); + coerce('line.smoothing'); - drawRaw(gd, options, index, false, xa, ya); -} + _$handleLabelDefaults_311(coerce, layout, lineColor, opts); +}; -/** - * drawRaw: draw a single annotation, potentially with modifications - * - * @param {DOM element} gd - * @param {object} options : this annotation's fullLayout options - * @param {integer} index : index in 'annotations' container of the annotation to draw - * @param {string} subplotId : id of the annotation's subplot - * - use false for 2d (i.e. cartesian or paper-ref) annotations - * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px - * @param {object | undefined} ya : ... y-axis - */ -function drawRaw(gd, options, index, subplotId, xa, ya) { - var fullLayout = gd._fullLayout; - var gs = gd._fullLayout._size; - var edits = gd._context.edits; +function handleConstraintValueDefaults(coerce, contours) { + var zvalue; - var className; - var annbase; + if(__COMPARISON_OPS2_301.indexOf(contours.operation) === -1) { + // Requires an array of two numbers: + coerce('contours.value', [0, 1]); - if(subplotId) { - className = 'annotation-' + subplotId; - annbase = subplotId + '.annotations[' + index + ']'; + if(!Array.isArray(contours.value)) { + if(_$fastIsnumeric_18(contours.value)) { + zvalue = parseFloat(contours.value); + contours.value = [zvalue, zvalue + 1]; + } + } else if(contours.value.length > 2) { + contours.value = contours.value.slice(2); + } else if(contours.length === 0) { + contours.value = [0, 1]; + } else if(contours.length < 2) { + zvalue = parseFloat(contours.value[0]); + contours.value = [zvalue, zvalue + 1]; + } else { + contours.value = [ + parseFloat(contours.value[0]), + parseFloat(contours.value[1]) + ]; + } } else { - className = 'annotation'; - annbase = 'annotations[' + index + ']'; + // Requires a single scalar: + coerce('contours.value', 0); + + if(!_$fastIsnumeric_18(contours.value)) { + if(Array.isArray(contours.value)) { + contours.value = parseFloat(contours.value[0]); + } else { + contours.value = 0; + } + } } +} - // remove the existing annotation if there is one - fullLayout._infolayer - .selectAll('.' + className + '[data-index="' + index + '"]') - .remove(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 annClipID = 'clip' + fullLayout._uid + '_ann' + index; +'use strict'; - // this annotation is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!options._input || options.visible === false) { - _$d3_15.selectAll('#' + annClipID).remove(); - return; - } +var _$handleContourDefaults_303 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { + var contourStart = coerce2('contours.start'); + var contourEnd = coerce2('contours.end'); + var missingEnd = (contourStart === false) || (contourEnd === false); - // calculated pixel positions - // x & y each will get text, head, and tail as appropriate - var annPosPx = {x: {}, y: {}}, - textangle = +options.textangle || 0; + // normally we only need size if autocontour is off. But contour.calc + // pushes its calculated contour size back to the input trace, so for + // things like restyle that can call supplyDefaults without calc + // after the initial draw, we can just reuse the previous calculation + var contourSize = coerce('contours.size'); + var autoContour; - // create the components - // made a single group to contain all, so opacity can work right - // with border/arrow together this could handle a whole bunch of - // cleanup at this point, but works for now - var annGroup = fullLayout._infolayer.append('g') - .classed(className, true) - .attr('data-index', String(index)) - .style('opacity', options.opacity); + if(missingEnd) autoContour = traceOut.autocontour = true; + else autoContour = coerce('autocontour', false); - // another group for text+background so that they can rotate together - var annTextGroup = annGroup.append('g') - .classed('annotation-text-g', true); + if(autoContour || !contourSize) coerce('ncontours'); +}; - var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; - var textEvents = options.captureevents || edits.annotationText || editTextPosition; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 annTextGroupInner = annTextGroup.append('g') - .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_190, 'default') - .on('click', function() { - gd._dragging = false; - var eventData = { - index: index, - annotation: options._input, - fullAnnotation: options, - event: _$d3_15.event - }; +'use strict'; - if(subplotId) { - eventData.subplotId = subplotId; - } +/* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; +/* removed: var _$handleLabelDefaults_311 = require('./label_defaults'); */; - gd.emit('plotly_clickannotation', eventData); - }); - if(options.hovertext) { - annTextGroupInner - .on('mouseover', function() { - var hoverOptions = options.hoverlabel; - var hoverFont = hoverOptions.font; - var bBox = this.getBoundingClientRect(); - var bBoxRef = gd.getBoundingClientRect(); +var _$handleStyleDefaults_317 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { + var coloring = coerce('contours.coloring'); - _$fx_93.loneHover({ - x0: bBox.left - bBoxRef.left, - x1: bBox.right - bBoxRef.left, - y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, - text: options.hovertext, - color: hoverOptions.bgcolor, - borderColor: hoverOptions.bordercolor, - fontFamily: hoverFont.family, - fontSize: hoverFont.size, - fontColor: hoverFont.color - }, { - container: fullLayout._hoverlayer.node(), - outerContainer: fullLayout._paper.node(), - gd: gd - }); - }) - .on('mouseout', function() { - _$fx_93.loneUnhover(fullLayout._hoverlayer.node()); - }); + 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'); } - var borderwidth = options.borderwidth, - borderpad = options.borderpad, - borderfull = borderwidth + borderpad; + if(coloring !== 'none') { + _$colorScaleDefaults_61( + traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} + ); + } - var annTextBG = annTextGroupInner.append('rect') - .attr('class', 'bg') - .style('stroke-width', borderwidth + 'px') - .call(_$color_51.stroke, options.bordercolor) - .call(_$color_51.fill, options.bgcolor); + coerce('line.smoothing'); - var isSizeConstrained = options.width || options.height; + _$handleLabelDefaults_311(coerce, layout, lineColor, opts); +}; - var annTextClip = fullLayout._topclips - .selectAll('#' + annClipID) - .data(isSizeConstrained ? [0] : []); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - annTextClip.enter().append('clipPath') - .classed('annclip', true) - .attr('id', annClipID) - .append('rect'); - annTextClip.exit().remove(); - var font = options.font; +'use strict'; - var annText = annTextGroupInner.append('text') - .classed('annotation-text', true) - .text(options.text); +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_334 = _$lib_172.isArrayOrTypedArray; - function textLayout(s) { - s.call(_$drawing_76.font, font) - .attr({ - 'text-anchor': { - left: 'start', - right: 'end' - }[options.align] || 'middle' - }); +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$has_columns_325 = require('./has_columns'); */; - _$svg_text_utils_192.convertToTspans(s, gd, drawGraphicalElements); - return s; +var _$handleXYZDefaults_334 = 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(_$has_columns_325(traceIn)) { + x = coerce(xName); + y = coerce(yName); + + // column z must be accompanied by xName and yName arrays + if(!x || !y) return 0; } + else { + x = coordDefaults(xName, coerce); + y = coordDefaults(yName, coerce); - function drawGraphicalElements() { - // if the text has *only* a link, make the whole box into a link - var anchor3 = annText.selectAll('a'); - if(anchor3.size() === 1 && anchor3.text() === annText.text()) { - var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ - 'xlink:xlink:href': anchor3.attr('xlink:href'), - 'xlink:xlink:show': anchor3.attr('xlink:show') - }) - .style({cursor: 'pointer'}); + // TODO put z validation elsewhere + if(!isValidZ(z)) return 0; - wholeLink.node().appendChild(annTextBG.node()); - } + coerce('transpose'); + } - var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); - var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = _$drawing_76.bBox( - (hasMathjax ? mathjaxGroup : annText).node()); - var textWidth = anntextBB.width; - var textHeight = anntextBB.height; - var annWidth = options.width || textWidth; - var annHeight = options.height || textHeight; - var outerWidth = Math.round(annWidth + 2 * borderfull); - var outerHeight = Math.round(annHeight + 2 * borderfull); + var handleCalendarDefaults = _$registry_262.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout); + return traceOut.z.length; +}; - // save size in the annotation object for use by autoscale - options._w = annWidth; - options._h = annHeight; +function coordDefaults(coordStr, coerce) { + var coord = coerce(coordStr), + coordType = coord ? + coerce(coordStr + 'type', 'array') : + 'scaled'; - function shiftFraction(v, anchor) { - if(anchor === 'auto') { - if(v < 1 / 3) anchor = 'left'; - else if(v > 2 / 3) anchor = 'right'; - else anchor = 'center'; - } - return { - center: 0, - middle: 0, - left: 0.5, - bottom: -0.5, - right: -0.5, - top: 0.5 - }[anchor]; - } + if(coordType === 'scaled') { + coerce(coordStr + '0'); + coerce('d' + coordStr); + } - var annotationIsOffscreen = false; - var letters = ['x', 'y']; + return coord; +} - for(var i = 0; i < letters.length; i++) { - var axLetter = letters[i], - axRef = options[axLetter + 'ref'] || axLetter, - tailRef = options['a' + axLetter + 'ref'], - ax = {x: xa, y: ya}[axLetter], - dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, - // note that these two can be either positive or negative - annSizeFromWidth = outerWidth * Math.cos(dimAngle), - annSizeFromHeight = outerHeight * Math.sin(dimAngle), - // but this one is the positive total size - annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), - anchor = options[axLetter + 'anchor'], - overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), - posPx = annPosPx[axLetter], - basePx, - textPadShift, - alignPosition, - autoAlignFraction, - textShift; +function isValidZ(z) { + var allRowsAreArrays = true, + oneRowIsFilled = false, + hasOneNumber = false, + zi; - /* - * calculate the *primary* pixel position - * which is the arrowhead if there is one, - * otherwise the text anchor point - */ - if(ax) { - /* - * hide the annotation if it's pointing outside the visible plot - * as long as the axis isn't autoranged - then we need to draw it - * anyway to get its bounding box. When we're dragging, an axis can - * still look autoranged even though it won't be when the drag finishes. - */ - var posFraction = ax.r2fraction(options[axLetter]); - if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { - if(tailRef === axRef) { - posFraction = ax.r2fraction(options['a' + axLetter]); - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - } - } - else { - annotationIsOffscreen = true; - } + /* + * Without this step: + * + * hasOneNumber = false breaks contour but not heatmap + * allRowsAreArrays = false breaks contour but not heatmap + * oneRowIsFilled = false breaks both + */ - if(annotationIsOffscreen) continue; - } - 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; + for(var i = 0; i < z.length; i++) { + zi = z[i]; + if(!__isArrayOrTypedArray_334(zi)) { + allRowsAreArrays = false; + break; + } + if(zi.length > 0) oneRowIsFilled = true; + for(var j = 0; j < zi.length; j++) { + if(_$fastIsnumeric_18(zi[j])) { + hasOneNumber = true; + break; } + } + } - // now translate this into pixel positions of head, tail, and text - // as well as paddings for autorange - if(options.showarrow) { - posPx.head = basePx; + return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); +} - var arrowLength = options['a' + axLetter]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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; - } +'use strict'; - posPx.text = posPx.tail + textShift; +/* removed: var _$lib_172 = require('../../lib'); */; - // 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_171.constrain(posPx.head, 1, maxPx - 1); - } - if(tailRef === 'pixel') { - var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), - 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; - } - } +/* removed: var _$has_columns_325 = require('../heatmap/has_columns'); */; +/* removed: var _$handleXYZDefaults_334 = require('../heatmap/xyz_defaults'); */; +/* removed: var _$handleConstraintDefaults_301 = require('./constraint_defaults'); */; +/* removed: var _$handleContourDefaults_303 = require('./contours_defaults'); */; +/* removed: var _$handleStyleDefaults_317 = require('./style_defaults'); */; +/* removed: var _$attributes_296 = require('./attributes'); */; - 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; +var _$supplyDefaults_305 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_172.coerce(traceIn, traceOut, _$attributes_296, attr, dflt); + } - // padplus/minus are used by autorange - options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift; - options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift; + function coerce2(attr) { + return _$lib_172.coerce2(traceIn, traceOut, _$attributes_296, attr); + } - // size/shift are used during dragging - options['_' + axLetter + 'size'] = annSize; - options['_' + axLetter + 'shift'] = textShift; - } + var len = _$handleXYZDefaults_334(traceIn, traceOut, coerce, layout); + if(!len) { + traceOut.visible = false; + return; + } - if(annotationIsOffscreen) { - annTextGroupInner.remove(); - return; - } + coerce('text'); + var isConstraint = (coerce('contours.type') === 'constraint'); + coerce('connectgaps', _$has_columns_325(traceOut)); - var xShift = 0; - var yShift = 0; + // trace-level showlegend has already been set, but is only allowed if this is a constraint + if(!isConstraint) delete traceOut.showlegend; - 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_76.setClipUrl, isSizeConstrained ? annClipID : null); - } - else { - var texty = borderfull + yShift - anntextBB.top; - var textx = borderfull + xShift - anntextBB.left; - - annText.call(_$svg_text_utils_192.positionText, textx, texty) - .call(_$drawing_76.setClipUrl, isSizeConstrained ? annClipID : null); - } - - annTextClip.select('rect').call(_$drawing_76.setRect, borderfull, borderfull, - annWidth, annHeight); + if(isConstraint) { + _$handleConstraintDefaults_301(traceIn, traceOut, coerce, layout, defaultColor); + } + else { + _$handleContourDefaults_303(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_317(traceIn, traceOut, coerce, layout); + } +}; - annTextBG.call(_$drawing_76.setRect, borderwidth / 2, borderwidth / 2, - outerWidth - borderwidth, outerHeight - borderwidth); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - annTextGroupInner.call(_$drawing_76.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 + ')'}); +'use strict'; - /* - * 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(); +/* removed: var _$fx_93 = require('../../components/fx'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; - var headX = annPosPx.x.head, - headY = annPosPx.y.head, - tailX = annPosPx.x.tail + dx, - tailY = annPosPx.y.tail + dy, - textX = annPosPx.x.text + dx, - textY = annPosPx.y.text + dy, +var _$hoverPoints_326 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { + var cd0 = pointData.cd[0]; + var trace = cd0.trace; + var xa = pointData.xa; + var ya = pointData.ya; + var x = cd0.x; + var y = cd0.y; + var z = cd0.z; + var xc = cd0.xCenter; + var yc = cd0.yCenter; + var zmask = cd0.zmask; + var range = [trace.zmin, trace.zmax]; + var zhoverformat = trace.zhoverformat; + var x2 = x; + var y2 = y; - // find the edge of the text box, where we'll start the arrow: - // create transform matrix to rotate the text box corners - transform = _$lib_171.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_171.apply2DTransform(transform), - applyTransform2 = _$lib_171.apply2DTransform2(transform), + var xl, yl, nx, ny; - // calculate and transform bounding box - width = +annTextBG.attr('width'), - height = +annTextBG.attr('height'), - xLeft = textX - 0.5 * width, - xRight = xLeft + width, - yTop = textY - 0.5 * height, - yBottom = yTop + height, - edges = [ - [xLeft, yTop, xLeft, yBottom], - [xLeft, yBottom, xRight, yBottom], - [xRight, yBottom, xRight, yTop], - [xRight, yTop, xLeft, yTop] - ].map(applyTransform2); + if(pointData.index !== false) { + try { + nx = Math.round(pointData.index[1]); + ny = Math.round(pointData.index[0]); + } + catch(e) { + _$lib_172.error('Error hovering on heatmap, ' + + 'pointNumber must be [row,col], found:', pointData.index); + return; + } + if(nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) { + return; + } + } + else if(_$fx_93.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || + _$fx_93.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) { + return; + } + else { + if(contour) { + var i2; + x2 = [2 * x[0] - x[1]]; - // 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_171.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; + for(i2 = 1; i2 < x.length; i2++) { + x2.push((x[i2] + x[i2 - 1]) / 2); } + x2.push([2 * x[x.length - 1] - x[x.length - 2]]); - edges.forEach(function(x) { - var p = _$lib_171.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, - arrowColor = options.arrowcolor, - arrowSide = options.arrowside; - - var arrowGroup = annGroup.append('g') - .style({opacity: _$color_51.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_51.stroke, _$color_51.rgb(arrowColor)); - - _$drawArrowHead_43(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) - .attr({ - d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), - transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' - }) - .style('stroke-width', (strokewidth + 6) + 'px') - .call(_$color_51.stroke, 'rgba(0,0,0,0)') - .call(_$color_51.fill, 'rgba(0,0,0,0)'); - - var update, - annx0, - anny0; - - // dragger for the arrow & head: translates the whole thing - // (head/tail/text) all together - _$dragelement_73.init({ - element: arrowDrag.node(), - gd: gd, - prepFn: function() { - var pos = _$drawing_76.getTranslate(annTextGroupInner); - - annx0 = pos.x; - anny0 = pos.y; - update = {}; - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } - }, - moveFn: function(dx, dy) { - var annxy0 = applyTransform(annx0, anny0), - xcenter = annxy0[0] + dx, - ycenter = annxy0[1] + dy; - annTextGroupInner.call(_$drawing_76.setTranslate, xcenter, ycenter); - - update[annbase + '.x'] = xa ? - xa.p2r(xa.r2p(options.x) + dx) : - (options.x + (dx / gs.w)); - update[annbase + '.y'] = ya ? - ya.p2r(ya.r2p(options.y) + dy) : - (options.y - (dy / gs.h)); - - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } - - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } - - arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); - annTextGroup.attr({ - transform: 'rotate(' + textangle + ',' + - xcenter + ',' + ycenter + ')' - }); - }, - doneFn: function() { - _$registry_261.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); + y2 = [2 * y[0] - y[1]]; + for(i2 = 1; i2 < y.length; i2++) { + y2.push((y[i2] + y[i2 - 1]) / 2); } - }; - - if(options.showarrow) drawArrow(0, 0); + y2.push([2 * y[y.length - 1] - y[y.length - 2]]); + } + nx = Math.max(0, Math.min(x2.length - 2, _$lib_172.findBin(xval, x2))); + ny = Math.max(0, Math.min(y2.length - 2, _$lib_172.findBin(yval, y2))); + } - // user dragging the annotation (text, not arrow) - if(editTextPosition) { - var update, - baseTextTransform; + var x0 = xa.c2p(x[nx]), + x1 = xa.c2p(x[nx + 1]), + y0 = ya.c2p(y[ny]), + y1 = ya.c2p(y[ny + 1]); - // dragger for the textbox: if there's an arrow, just drag the - // textbox and tail, leave the head untouched - _$dragelement_73.init({ - element: annTextGroupInner.node(), - gd: gd, - prepFn: function() { - baseTextTransform = annTextGroup.attr('transform'); - update = {}; - }, - moveFn: function(dx, dy) { - var csr = 'pointer'; - if(options.showarrow) { - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } else { - update[annbase + '.ax'] = options.ax + dx; - } + if(contour) { + x1 = x0; + xl = x[nx]; + y1 = y0; + yl = y[ny]; + } + else { + xl = xc ? xc[nx] : ((x[nx] + x[nx + 1]) / 2); + yl = yc ? yc[ny] : ((y[ny] + y[ny + 1]) / 2); + if(trace.zsmooth) { + x0 = x1 = xa.c2p(xl); + y0 = y1 = ya.c2p(yl); + } + } - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } else { - update[annbase + '.ay'] = options.ay + dy; - } + var zVal = z[ny][nx]; + if(zmask && !zmask[ny][nx]) zVal = undefined; - drawArrow(dx, dy); - } - else if(!subplotId) { - if(xa) { - update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); + var text; + if(Array.isArray(cd0.text) && Array.isArray(cd0.text[ny])) { + text = cd0.text[ny][nx]; + } - } else { - var widthFraction = options._xsize / gs.w, - xLeft = options.x + (options._xshift - options.xshift) / gs.w - - widthFraction / 2; + var zLabel; + // dummy axis for formatting the z value + var dummyAx = { + type: 'linear', + range: range, + hoverformat: zhoverformat, + _separators: xa._separators, + _numFormat: xa._numFormat + }; + var zLabelObj = _$axes_214.tickText(dummyAx, zVal, 'hover'); + zLabel = zLabelObj.text; - update[annbase + '.x'] = _$dragelement_73.align(xLeft + dx / gs.w, - widthFraction, 0, 1, options.xanchor); - } + return [_$lib_172.extendFlat(pointData, { + index: [ny, nx], + // never let a 2D override 1D type as closest point + distance: pointData.maxHoverDistance, + spikeDistance: pointData.maxSpikeDistance, + x0: x0, + x1: x1, + y0: y0, + y1: y1, + xLabelVal: xl, + yLabelVal: yl, + zLabelVal: zVal, + zLabel: zLabel, + text: text + })]; +}; - if(ya) { - update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); - } else { - var heightFraction = options._ysize / gs.h, - yBottom = options.y - (options._yshift + options.yshift) / gs.h - - heightFraction / 2; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - update[annbase + '.y'] = _$dragelement_73.align(yBottom - dy / gs.h, - heightFraction, 0, 1, options.yanchor); - } - if(!xa || !ya) { - csr = _$dragelement_73.getCursor( - xa ? 0.5 : update[annbase + '.x'], - ya ? 0.5 : update[annbase + '.y'], - options.xanchor, options.yanchor - ); - } - } - else return; - annTextGroup.attr({ - transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform - }); +'use strict'; - _$setCursor_190(annTextGroupInner, csr); - }, - doneFn: function() { - _$setCursor_190(annTextGroupInner); - _$registry_261.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } - } +/* removed: var _$color_51 = require('../../components/color'); */; - if(edits.annotationText) { - annText.call(_$svg_text_utils_192.makeEditable, {delegate: annTextGroupInner, gd: gd}) - .call(textLayout) - .on('edit', function(_text) { - options.text = _text; - this.call(textLayout); +/* removed: var _$hoverPoints_326 = require('../heatmap/hover'); */; - var update = {}; - update[annbase + '.text'] = options.text; +var _$hoverPoints_309 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { + var hoverData = _$hoverPoints_326(pointData, xval, yval, hovermode, hoverLayer, true); - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; + if(hoverData) { + hoverData.forEach(function(hoverPt) { + var trace = hoverPt.trace; + if(trace.contours.type === 'constraint') { + if(trace.fillcolor && _$color_51.opacity(trace.fillcolor)) { + hoverPt.color = _$color_51.addOpacity(trace.fillcolor, 1); } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; + else if(trace.contours.showlines && _$color_51.opacity(trace.line.color)) { + hoverPt.color = _$color_51.addOpacity(trace.line.color, 1); } - - _$registry_261.call('relayout', gd, update); - }); + } + }); } - else annText.call(textLayout); -} + + return hoverData; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45054,108 +44206,63 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; - -var __draw_37 = _$draw_42.draw; - - -var _$calcAutorange_37 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - annotationList = _$lib_171.filterVisible(fullLayout.annotations); - - if(!annotationList.length || !gd._fullData.length) return; +var _$close_boundaries_298 = function(pathinfo, operation, perimeter, trace) { + // Abandon all hope, ye who enter here. + var i, v1, v2; + var pi0 = pathinfo[0]; + var na = pi0.x.length; + var nb = pi0.y.length; + var z = pi0.z; + var contours = trace.contours; - var annotationAxes = {}; - annotationList.forEach(function(ann) { - annotationAxes[ann.xref] = 1; - annotationAxes[ann.yref] = 1; - }); + var boundaryMax = -Infinity; + var boundaryMin = Infinity; - for(var axId in annotationAxes) { - var ax = _$axes_213.getFromId(gd, axId); - if(ax && ax.autorange) { - return _$lib_171.syncOrAsync([ - __draw_37, - annAutorange - ], gd); - } + for(i = 0; i < nb; i++) { + boundaryMin = Math.min(boundaryMin, z[i][0]); + boundaryMin = Math.min(boundaryMin, z[i][na - 1]); + boundaryMax = Math.max(boundaryMax, z[i][0]); + boundaryMax = Math.max(boundaryMax, z[i][na - 1]); } -}; - -function annAutorange(gd) { - var fullLayout = gd._fullLayout; - - // find the bounding boxes for each of these annotations' - // relative to their anchor points - // use the arrow and the text bg rectangle, - // as the whole anno may include hidden text in its bbox - _$lib_171.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_213.getFromId(gd, ann.xref), - ya = _$axes_213.getFromId(gd, ann.yref), - headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, - startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - var headPlus, headMinus, startHeadPlus, startHeadMinus; + for(i = 1; i < na - 1; i++) { + boundaryMin = Math.min(boundaryMin, z[0][i]); + boundaryMin = Math.min(boundaryMin, z[nb - 1][i]); + boundaryMax = Math.max(boundaryMax, z[0][i]); + boundaryMax = Math.max(boundaryMax, z[nb - 1][i]); + } - if(xa && xa.autorange) { - headPlus = headSize + ann.xshift; - headMinus = headSize - ann.xshift; - startHeadPlus = startHeadSize + ann.xshift; - startHeadMinus = startHeadSize - ann.xshift; + pi0.prefixBoundary = false; - if(ann.axref === ann.xref) { - // expand for the arrowhead (padded by arrowhead) - _$axes_213.expand(xa, [xa.r2c(ann.x)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - // again for the textbox (padded by textbox) - _$axes_213.expand(xa, [xa.r2c(ann.ax)], { - ppadplus: Math.max(ann._xpadplus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, startHeadMinus) - }); + switch(operation) { + case '>': + if(contours.value > boundaryMax) { + pi0.prefixBoundary = true; } - else { - startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; - startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_213.expand(xa, [xa.r2c(ann.x)], { - ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) - }); + break; + case '<': + if(contours.value < boundaryMin) { + pi0.prefixBoundary = true; } - } - - if(ya && ya.autorange) { - headPlus = headSize - ann.yshift; - headMinus = headSize + ann.yshift; - startHeadPlus = startHeadSize - ann.yshift; - startHeadMinus = startHeadSize + ann.yshift; - - if(ann.ayref === ann.yref) { - _$axes_213.expand(ya, [ya.r2c(ann.y)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - _$axes_213.expand(ya, [ya.r2c(ann.ay)], { - ppadplus: Math.max(ann._ypadplus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, startHeadMinus) - }); + break; + case '[]': + v1 = Math.min.apply(null, contours.value); + v2 = Math.max.apply(null, contours.value); + if(v2 < boundaryMin || v1 > boundaryMax) { + pi0.prefixBoundary = true; } - else { - startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; - startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_213.expand(ya, [ya.r2c(ann.y)], { - ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) - }); + break; + case '][': + v1 = Math.min.apply(null, contours.value); + v2 = Math.max.apply(null, contours.value); + if(v1 < boundaryMin && v2 > boundaryMax) { + pi0.prefixBoundary = true; } - } - }); -} + break; + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45166,127 +44273,73 @@ function annAutorange(gd) { */ 'use strict'; +var _$constants_300 = { + // some constants to help with marching squares algorithm + // where does the path start for each index? + BOTTOMSTART: [1, 9, 13, 104, 713], + TOPSTART: [4, 6, 7, 104, 713], + LEFTSTART: [8, 12, 14, 208, 1114], + RIGHTSTART: [2, 3, 11, 208, 1114], -/* removed: var _$registry_261 = require('../../registry'); */; - -var _$click_38 = { - 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), - onSet = toggleSets.on, - offSet = toggleSets.off.concat(toggleSets.explicitOff), - update = {}, - i; - - if(!(onSet.length || offSet.length)) return; - - for(i = 0; i < onSet.length; i++) { - update['annotations[' + onSet[i] + '].visible'] = true; - } - - for(i = 0; i < offSet.length; i++) { - update['annotations[' + offSet[i] + '].visible'] = false; - } + // which way [dx,dy] do we leave a given index? + // saddles are already disambiguated + NEWDELTA: [ + null, [-1, 0], [0, -1], [-1, 0], + [1, 0], null, [0, -1], [-1, 0], + [0, 1], [0, 1], null, [0, 1], + [1, 0], [1, 0], [0, -1] + ], - return _$registry_261.call('update', gd, {}, update); -} + // for each saddle, the first index here is used + // for dx||dy<0, the second for dx||dy>0 + CHOOSESADDLE: { + 104: [4, 1], + 208: [2, 8], + 713: [7, 13], + 1114: [11, 14] + }, -/* - * 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, - onSet = [], - offSet = [], - explicitOffSet = [], - hoverLen = (hoverData || []).length; + // after one index has been used for a saddle, which do we + // substitute to be used up later? + SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11}, - var i, j, anni, showMode, pointj, xa, ya, toggleType; + // length of a contour, as a multiple of the plot area diagonal, per label + LABELDISTANCE: 2, - for(i = 0; i < annotations.length; i++) { - anni = annotations[i]; - showMode = anni.clicktoshow; + // number of contour levels after which we start increasing the number of + // labels we draw. Many contours means they will generally be close + // together, so it will be harder to follow a long way to find a label + LABELINCREASE: 10, - if(showMode) { - for(j = 0; j < hoverLen; j++) { - pointj = hoverData[j]; - xa = pointj.xaxis; - ya = pointj.yaxis; + // minimum length of a contour line, as a multiple of the label length, + // at which we draw *any* labels + LABELMIN: 3, - 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; - } - } + // max number of labels to draw on a single contour path, no matter how long + LABELMAX: 10, - if(j === hoverLen) { - // no match - only turn this annotation OFF, and only if - // showmode is 'onout' - if(anni.visible && showMode === 'onout') offSet.push(i); - } - } + // constants for the label position cost function + LABELOPTIMIZER: { + // weight given to edge proximity + EDGECOST: 1, + // weight given to the angle off horizontal + ANGLECOST: 1, + // weight given to distance from already-placed labels + NEIGHBORCOST: 5, + // cost multiplier for labels on the same level + SAMELEVELFACTOR: 10, + // minimum distance (as a multiple of the label length) + // for labels on the same level + SAMELEVELDISTANCE: 5, + // maximum cost before we won't even place the label + MAXCOST: 100, + // number of evenly spaced points to look at in the first + // iteration of the search + INITIALSEARCHPOINTS: 10, + // number of binary search iterations after the initial wide search + ITERATIONS: 5 } - - 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); -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45296,60 +44349,85 @@ function clickData2r(d, ax) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_194 = require('../../lib/to_log_range'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* - * 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. - */ -var _$convertCoords_40 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; +// 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. +var _$convert_to_constraints_304 = function(pathinfo, operation) { + var i, pi0, pi1; - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); + var op0 = function(arr) { return arr.reverse(); }; + var op1 = function(arr) { return arr; }; - if(!(toLog || fromLog)) return; + switch(operation) { + case '=': + case '<': + return pathinfo; + case '>': + if(pathinfo.length !== 1) { + _$lib_172.warn('Contour data invalid for the specified inequality operation.'); + } - var annotations = gd._fullLayout.annotations, - axLetter = ax._id.charAt(0), - ann, - attrPrefix; + // In this case there should be exactly two contour levels in pathinfo. We + // simply concatenate the info into one pathinfo and flip all of the data + // in one. This will draw the contour as closed. + pi0 = pathinfo[0]; - function convert(attr) { - var currentVal = ann[attr], - newVal = null; + for(i = 0; i < pi0.edgepaths.length; i++) { + pi0.edgepaths[i] = op0(pi0.edgepaths[i]); + } - if(toLog) newVal = _$toLogRange_194(currentVal, ax.range); - else newVal = Math.pow(10, currentVal); + for(i = 0; i < pi0.paths.length; i++) { + pi0.paths[i] = op0(pi0.paths[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_172.warn('Contour data invalid for the specified inequality range operation.'); + } - // if conversion failed, delete the value so it gets a default value - if(!_$fastIsnumeric_18(newVal)) newVal = null; + // In this case there should be exactly two contour levels in pathinfo. We + // simply concatenate the info into one pathinfo and flip all of the data + // in one. This will draw the contour as closed. + pi0 = copyPathinfo(pathinfo[0]); + pi1 = copyPathinfo(pathinfo[1]); - doExtra(attrPrefix + attr, newVal); - } + for(i = 0; i < pi0.edgepaths.length; i++) { + pi0.edgepaths[i] = op0(pi0.edgepaths[i]); + } - for(var i = 0; i < annotations.length; i++) { - ann = annotations[i]; - attrPrefix = 'annotations[' + i + '].'; + for(i = 0; i < pi0.paths.length; i++) { + pi0.paths[i] = op0(pi0.paths[i]); + } - if(ann[axLetter + 'ref'] === ax._id) convert(axLetter); - if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter); + while(pi1.edgepaths.length) { + pi0.edgepaths.push(op1(pi1.edgepaths.shift())); + } + while(pi1.paths.length) { + pi0.paths.push(op1(pi1.paths.shift())); + } + return [pi0]; } }; +function copyPathinfo(pi) { + return _$lib_172.extendFlat({}, pi, { + edgepaths: _$lib_172.extendDeep([], pi.edgepaths), + paths: _$lib_172.extendDeep([], pi.paths) + }); +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45360,74 +44438,73 @@ var _$convertCoords_40 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$color_51 = require('../color'); */; - -// defaults common to 'annotations' and 'annotations3d' -var _$handleAnnotationCommonDefaults_39 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { - coerce('opacity'); - var bgColor = coerce('bgcolor'); - - var borderColor = coerce('bordercolor'); - var borderOpacity = _$color_51.opacity(borderColor); - - coerce('borderpad'); - - var borderWidth = coerce('borderwidth'); - var showArrow = coerce('showarrow'); - - coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); - coerce('textangle'); - _$lib_171.coerceFont(coerce, 'font', fullLayout.font); - - coerce('width'); - coerce('align'); +/* removed: var _$filter_ops_152 = require('../../constants/filter_ops'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - var h = coerce('height'); - if(h) coerce('valign'); +// This syntax conforms to the existing filter transform syntax, but we don't care +// about open vs. closed intervals for simply drawing contours constraints: +var _$constraint_mapping_302 = { + '[]': makeRangeSettings('[]'), + '][': makeRangeSettings(']['), + '>': makeInequalitySettings('>'), + '<': makeInequalitySettings('<'), + '=': makeInequalitySettings('=') +}; - if(showArrow) { - var arrowside = coerce('arrowside'); - var arrowhead; - var arrowsize; +// 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); - if(arrowside.indexOf('end') !== -1) { - arrowhead = coerce('arrowhead'); - arrowsize = coerce('arrowsize'); - } + var coercedValue; - if(arrowside.indexOf('start') !== -1) { - coerce('startarrowhead', arrowhead); - coerce('startarrowsize', arrowsize); - } - coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_51.defaultLine); - coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); - coerce('standoff'); - coerce('startstandoff'); + function coerce(value) { + return _$fastIsnumeric_18(value) ? (+value) : null; + } + if(_$filter_ops_152.COMPARISON_OPS2.indexOf(operation) !== -1) { + coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value); + } else if(_$filter_ops_152.INTERVAL_OPS.indexOf(operation) !== -1) { + coercedValue = hasArrayValue ? + [coerce(value[0]), coerce(value[1])] : + [coerce(value), coerce(value)]; + } else if(_$filter_ops_152.SET_OPS.indexOf(operation) !== -1) { + coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)]; } - var hoverText = coerce('hovertext'); - var globalHoverLabel = fullLayout.hoverlabel || {}; + return coercedValue; +} - if(hoverText) { - var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || - (_$color_51.opacity(bgColor) ? _$color_51.rgb(bgColor) : _$color_51.defaultLine) - ); +// 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); - var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || - _$color_51.contrast(hoverBG) - ); + // Ensure proper ordering: + var min = Math.min(value[0], value[1]); + var max = Math.max(value[0], value[1]); - _$lib_171.coerceFont(coerce, 'hoverlabel.font', { - family: globalHoverLabel.font.family, - size: globalHoverLabel.font.size, - color: globalHoverLabel.font.color || hoverBorder - }); - } + return { + start: min, + end: max, + size: max - min + }; + }; +} - coerce('captureevents', !!hoverText); -}; +function makeInequalitySettings(operation) { + return function(value) { + value = coerceValue(operation, value); + + return { + start: value, + end: Infinity, + size: Infinity + }; + }; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -45437,92 +44514,59 @@ var _$handleAnnotationCommonDefaults_39 = function handleAnnotationCommonDefault * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleAnnotationCommonDefaults_39 = require('./common_defaults'); */; -/* removed: var _$attributes_36 = require('./attributes'); */; - - -var _$handleAnnotationDefaults_34 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; - - function coerce(attr, dflt) { - return _$lib_171.coerce(annIn, annOut, _$attributes_36, attr, dflt); - } - - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - var clickToShow = coerce('clicktoshow'); - - if(!(visible || clickToShow)) return annOut; - - _$handleAnnotationCommonDefaults_39(annIn, annOut, fullLayout, coerce); - - var showArrow = annOut.showarrow; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$constraint_mapping_302 = require('./constraint_mapping'); */; +/* removed: var _$endPlus_307 = require('./end_plus'); */; - // positioning - var axLetters = ['x', 'y'], - arrowPosDflt = [-10, -30], - gdMock = {_fullLayout: fullLayout}; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i]; +var _$emptyPathinfo_306 = function emptyPathinfo(contours, plotinfo, cd0) { + var contoursFinal = (contours.type === 'constraint') ? + _$constraint_mapping_302[contours._operation](contours.value) : + contours; - // xref, yref - var axRef = _$axes_213.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + var cs = contoursFinal.size; + var pathinfo = []; + var end = _$endPlus_307(contoursFinal); - // x, y - _$axes_213.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + var carpet = cd0.trace._carpetTrace; - if(showArrow) { - var arrowPosAttr = 'a' + axLetter, - // axref, ayref - aaxRef = _$axes_213.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + 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 now the arrow can only be on the same axis or specified as pixels - // TODO: sometime it might be interesting to allow it to be on *any* axis - // but that would require updates to drawing & autorange code and maybe more - if(aaxRef !== 'pixel' && aaxRef !== axRef) { - aaxRef = annOut[arrowPosAttr] = 'pixel'; - } + for(var ci = contoursFinal.start; ci < end; ci += cs) { + pathinfo.push(_$lib_172.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)); - // ax, ay - var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_213.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + if(pathinfo.length > 1000) { + _$lib_172.warn('Too many contours, clipping at 1000', contours); + break; } - - // xanchor, yanchor - coerce(axLetter + 'anchor'); - - // xshift, yshift - coerce(axLetter + 'shift'); - } - - // if you have one coordinate you should have both - _$lib_171.noneOrAll(annIn, annOut, ['x', 'y']); - - // if you have one part of arrow length you should have both - if(showArrow) { - _$lib_171.noneOrAll(annIn, annOut, ['ax', 'ay']); - } - - if(clickToShow) { - var xClick = coerce('xclick'); - var yClick = coerce('yclick'); - - // put the actual click data to bind to into private attributes - // so we don't have to do this little bit of logic on every hover event - annOut._xclick = (xClick === undefined) ? - annOut.x : - _$axes_213.cleanPosition(xClick, gdMock, annOut.xref); - annOut._yclick = (yClick === undefined) ? - annOut.y : - _$axes_213.cleanPosition(yClick, gdMock, annOut.yref); } - - return annOut; + return pathinfo; }; /** @@ -45535,205 +44579,294 @@ var _$handleAnnotationDefaults_34 = function handleAnnotationDefaults(annIn, ann 'use strict'; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$constants_300 = require('./constants'); */; -/** Convenience wrapper for making array container logic DRY and consistent - * - * @param {object} parentObjIn - * user input object where the container in question is linked - * (i.e. either a user trace object or the user layout object) - * - * @param {object} parentObjOut - * full object where the coerced container will be linked - * (i.e. either a full trace object or the full layout object) - * - * @param {object} opts - * options object: - * - name {string} - * name of the key linking the container in question - * - handleItemDefaults {function} - * defaults method to be called on each item in the array container in question - * - * Its arguments are: - * - itemIn {object} item in user layout - * - itemOut {object} item in full layout - * - parentObj {object} (as in closure) - * - opts {object} (as in closure) - * - itemOpts {object} - * - itemIsNotPlainObject {boolean} - * N.B. - * - * - opts is passed to handleItemDefaults so it can also store - * links to supplementary data (e.g. fullData for layout components) - * - */ -var _$handleArrayContainerDefaults_209 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { - var name = opts.name; +var _$findAllPaths_308 = function findAllPaths(pathinfo, xtol, ytol) { + var cnt, + startLoc, + i, + pi, + j; - var previousContOut = parentObjOut[name]; + // Default just passes these values through as they were before: + xtol = xtol || 0.01; + ytol = ytol || 0.01; - var contIn = _$lib_171.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], - contOut = parentObjOut[name] = [], - i; + for(i = 0; i < pathinfo.length; i++) { + pi = pathinfo[i]; - for(i = 0; i < contIn.length; i++) { - var itemIn = contIn[i], - itemOut = {}, - itemOpts = {}; - - if(!_$lib_171.isPlainObject(itemIn)) { - itemOpts.itemIsNotPlainObject = true; - itemIn = {}; + for(j = 0; j < pi.starts.length; j++) { + startLoc = pi.starts[j]; + makePath(pi, startLoc, 'edge', xtol, ytol); } - opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); - - itemOut._input = itemIn; - itemOut._index = i; - - contOut.push(itemOut); - } - - // in case this array gets its defaults rebuilt independent of the whole layout, - // relink the private keys just for this array. - if(_$lib_171.isArrayOrTypedArray(previousContOut)) { - var len = Math.min(previousContOut.length, contOut.length); - for(i = 0; i < len; i++) { - _$lib_171.relinkPrivateKeys(contOut[i], previousContOut[i]); + cnt = 0; + while(Object.keys(pi.crossings).length && cnt < 10000) { + cnt++; + startLoc = Object.keys(pi.crossings)[0].split(',').map(Number); + makePath(pi, startLoc, undefined, xtol, ytol); } + if(cnt === 10000) _$lib_172.log('Infinite loop in contour?'); } }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; +function equalPts(pt1, pt2, xtol, ytol) { + return Math.abs(pt1[0] - pt2[0]) < xtol && + Math.abs(pt1[1] - pt2[1]) < ytol; +} -/* removed: var _$handleArrayContainerDefaults_209 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationDefaults_34 = require('./annotation_defaults'); */; +// distance in index units - uses the 3rd and 4th items in points +function ptDist(pt1, pt2) { + var dx = pt1[2] - pt2[2], + dy = pt1[3] - pt2[3]; + return Math.sqrt(dx * dx + dy * dy); +} +function makePath(pi, loc, edgeflag, xtol, ytol) { + var startLocStr = loc.join(','); + var locStr = startLocStr; + var mi = pi.crossings[locStr]; + var marchStep = startStep(mi, edgeflag, loc); + // start by going backward a half step and finding the crossing point + var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])]; + var startStepStr = marchStep.join(','); + var m = pi.z.length; + var n = pi.z[0].length; + var cnt; -var _$supplyLayoutDefaults_41 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'annotations', - handleItemDefaults: _$handleAnnotationDefaults_34 - }; + // now follow the path + for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops + if(mi > 20) { + mi = _$constants_300.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1]; + pi.crossings[locStr] = _$constants_300.SADDLEREMAINDER[mi]; + } + else { + delete pi.crossings[locStr]; + } - _$handleArrayContainerDefaults_209(layoutIn, layoutOut, opts); -}; + marchStep = _$constants_300.NEWDELTA[mi]; + if(!marchStep) { + _$lib_172.log('Found bad marching index:', mi, loc, pi.level); + break; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // find the crossing a half step forward, and then take the full step + pts.push(getInterpPx(pi, loc, marchStep)); + loc[0] += marchStep[0]; + loc[1] += marchStep[1]; + // don't include the same point multiple times + if(equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop(); + locStr = loc.join(','); -'use strict'; + var atEdge = (marchStep[0] && (loc[0] < 0 || loc[0] > n - 2)) || + (marchStep[1] && (loc[1] < 0 || loc[1] > m - 2)), + closedLoop = (locStr === startLocStr) && (marchStep.join(',') === startStepStr); -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; + // have we completed a loop, or reached an edge? + if((closedLoop) || (edgeflag && atEdge)) break; -/** - * 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 - */ -var _$makeIncludeComponents_223 = function makeIncludeComponents(containerArrayName) { - return function includeComponents(layoutIn, layoutOut) { - var array = layoutIn[containerArrayName]; - if(!Array.isArray(array)) return; + mi = pi.crossings[locStr]; + } - var Cartesian = _$registry_261.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'); + if(cnt === 10000) { + _$lib_172.log('Infinite loop in contour?'); + } + var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol); + var totaldist = 0; + var distThresholdFactor = 0.2 * pi.smoothing; + var alldists = []; + var cropstart = 0; + var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist, + i, j, edgepathi, edgepathj; - for(var i = 0; i < array.length; i++) { - var itemi = array[i]; - if(!_$lib_171.isPlainObject(itemi)) continue; + /* + * Check for points that are too close together (<1/5 the average dist + * *in grid index units* (important for log axes and nonuniform grids), + * less if less smoothed) and just take the center (or avg of center 2). + * This cuts down on funny behavior when a point is very close to a + * contour level. + */ + for(cnt = 1; cnt < pts.length; cnt++) { + thisdist = ptDist(pts[cnt], pts[cnt - 1]); + totaldist += thisdist; + alldists.push(thisdist); + } - var xref = itemi.xref; - var yref = itemi.yref; + var distThreshold = totaldist / alldists.length * distThresholdFactor; - var hasXref = idRegex.x.test(xref); - var hasYref = idRegex.y.test(yref); - if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_171.pushUnique(layoutOut._basePlotModules, Cartesian); + function getpt(i) { return pts[i % pts.length]; } - 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; + for(cnt = pts.length - 2; cnt >= cropstart; cnt--) { + distgroup = alldists[cnt]; + if(distgroup < distThreshold) { + cnt3 = 0; + for(cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) { + if(distgroup + alldists[cnt2] < distThreshold) { + distgroup += alldists[cnt2]; } + else break; + } - /* - * 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); + // closed path with close points wrapping around the boundary? + if(closedpath && cnt === pts.length - 2) { + for(cnt3 = 0; cnt3 < cnt2; cnt3++) { + if(distgroup + alldists[cnt3] < distThreshold) { + distgroup += alldists[cnt3]; + } + else break; } } + ptcnt = cnt - cnt2 + cnt3 + 1; + ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2); + + // either endpoint included: keep the endpoint + if(!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1]; + else if(!closedpath && cnt2 === -1) newpt = pts[0]; + + // odd # of points - just take the central one + else if(ptcnt % 2) newpt = getpt(ptavg); + + // even # of pts - average central two + else { + newpt = [(getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2, + (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2]; + } + + pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt); + cnt = cnt2 + 1; + if(cnt3) cropstart = cnt3; + if(closedpath) { + if(cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1]; + else if(cnt === 0) pts[pts.length - 1] = pts[0]; + } } - }; -}; + } + pts.splice(0, cropstart); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // done with the index parts - remove them so path generation works right + // because it depends on only having [xpx, ypx] + for(cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2; + // don't return single-point paths (ie all points were the same + // so they got deleted?) + if(pts.length < 2) return; + else if(closedpath) { + pts.pop(); + pi.paths.push(pts); + } + else { + if(!edgeflag) { + _$lib_172.log('Unclosed interior contour?', + pi.level, startLocStr, pts.join('L')); + } -'use strict'; + // edge path - does it start where an existing edge path ends, or vice versa? + var merged = false; + for(i = 0; i < pi.edgepaths.length; i++) { + edgepathi = pi.edgepaths[i]; + if(!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) { + pts.pop(); + merged = true; -/* removed: var _$draw_42 = require('./draw'); */; -/* removed: var _$click_38 = require('./click'); */; + // now does it ALSO meet the end of another (or the same) path? + var doublemerged = false; + for(j = 0; j < pi.edgepaths.length; j++) { + edgepathj = pi.edgepaths[j]; + if(equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) { + doublemerged = true; + pts.shift(); + pi.edgepaths.splice(i, 1); + if(j === i) { + // the path is now closed + pi.paths.push(pts.concat(edgepathj)); + } + else { + if(j > i) j--; + pi.edgepaths[j] = edgepathj.concat(pts, edgepathi); + } + break; + } + } + if(!doublemerged) { + pi.edgepaths[i] = pts.concat(edgepathi); + } + } + } + for(i = 0; i < pi.edgepaths.length; i++) { + if(merged) break; + edgepathi = pi.edgepaths[i]; + if(equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) { + pts.shift(); + pi.edgepaths[i] = edgepathi.concat(pts); + merged = true; + } + } -var _$annotations_44 = { - moduleType: 'component', - name: 'annotations', + if(!merged) pi.edgepaths.push(pts); + } +} - layoutAttributes: _$attributes_36, - supplyLayoutDefaults: _$supplyLayoutDefaults_41, - includeBasePlot: _$makeIncludeComponents_223('annotations'), +// special function to get the marching step of the +// first point in the path (leading to loc) +function startStep(mi, edgeflag, loc) { + var dx = 0, + dy = 0; + if(mi > 20 && edgeflag) { + // these saddles start at +/- x + if(mi === 208 || mi === 1114) { + // if we're starting at the left side, we must be going right + dx = loc[0] === 0 ? 1 : -1; + } + else { + // if we're starting at the bottom, we must be going up + dy = loc[1] === 0 ? 1 : -1; + } + } + else if(_$constants_300.BOTTOMSTART.indexOf(mi) !== -1) dy = 1; + else if(_$constants_300.LEFTSTART.indexOf(mi) !== -1) dx = 1; + else if(_$constants_300.TOPSTART.indexOf(mi) !== -1) dy = -1; + else dx = -1; + return [dx, dy]; +} - calcAutorange: _$calcAutorange_37, - draw: _$draw_42.draw, - drawOne: _$draw_42.drawOne, - drawRaw: _$draw_42.drawRaw, +/* + * Find the pixel coordinates of a particular crossing + * + * @param {object} pi: the pathinfo object at this level + * @param {array} loc: the grid index [x, y] of the crossing + * @param {array} step: the direction [dx, dy] we're moving on the grid + * + * @return {array} [xpx, ypx, xi, yi]: the first two are the pixel location, + * the next two are the interpolated grid indices, which we use for + * distance calculations to delete points that are too close together. + * This is important when the grid is nonuniform (and most dramatically when + * we're on log axes and include invalid (0 or negative) values. + * It's crucial to delete these extra two before turning an array of these + * points into a path, because those routines require length-2 points. + */ +function getInterpPx(pi, loc, step) { + var locx = loc[0] + Math.max(step[0], 0), + locy = loc[1] + Math.max(step[1], 0), + zxy = pi.z[locy][locx], + xa = pi.xaxis, + ya = pi.yaxis; - hasClickToShow: _$click_38.hasClickToShow, - onClick: _$click_38.onClick, + if(step[1]) { + var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy); - convertCoords: _$convertCoords_40 -}; + return [xa.c2p((1 - dx) * pi.x[locx] + dx * pi.x[locx + 1], true), + ya.c2p(pi.y[locy], true), + locx + dx, locy]; + } + else { + var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy); + return [xa.c2p(pi.x[locx], true), + ya.c2p((1 - dy) * pi.y[locy] + dy * pi.y[locy + 1], true), + locx, locy + dy]; + } +} /** * Copyright 2012-2018, Plotly, Inc. @@ -45743,85 +44876,88 @@ var _$annotations_44 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$attributes_36 = require('../annotations/attributes'); */; -var __overrideAll_45 = _$edit_types_198.overrideAll; +/* removed: var _$constants_300 = require('./constants'); */; -var _$attributes_45 = __overrideAll_45({ - _isLinkedToArray: 'annotation', +// Calculate all the marching indices, for ALL levels at once. +// since we want to be exhaustive we'll check for contour crossings +// at every intersection, rather than just following a path +// TODO: shorten the inner loop to only the relevant levels +var _$makeCrossings_313 = function makeCrossings(pathinfo) { + var z = pathinfo[0].z, + m = z.length, + n = z[0].length, // we already made sure z isn't ragged in interp2d + twoWide = m === 2 || n === 2, + xi, + yi, + startIndices, + ystartIndices, + label, + corners, + mi, + pi, + i; - visible: _$attributes_36.visible, - x: { - valType: 'any', - - - }, - y: { - valType: 'any', - - - }, - z: { - valType: 'any', - - - }, - ax: { - valType: 'number', - - - }, - ay: { - valType: 'number', - - - }, + for(yi = 0; yi < m - 1; yi++) { + ystartIndices = []; + if(yi === 0) ystartIndices = ystartIndices.concat(_$constants_300.BOTTOMSTART); + if(yi === m - 2) ystartIndices = ystartIndices.concat(_$constants_300.TOPSTART); - xanchor: _$attributes_36.xanchor, - xshift: _$attributes_36.xshift, - yanchor: _$attributes_36.yanchor, - yshift: _$attributes_36.yshift, + for(xi = 0; xi < n - 1; xi++) { + startIndices = ystartIndices.slice(); + if(xi === 0) startIndices = startIndices.concat(_$constants_300.LEFTSTART); + if(xi === n - 2) startIndices = startIndices.concat(_$constants_300.RIGHTSTART); - text: _$attributes_36.text, - textangle: _$attributes_36.textangle, - font: _$attributes_36.font, - width: _$attributes_36.width, - height: _$attributes_36.height, - opacity: _$attributes_36.opacity, - align: _$attributes_36.align, - valign: _$attributes_36.valign, - bgcolor: _$attributes_36.bgcolor, - bordercolor: _$attributes_36.bordercolor, - borderpad: _$attributes_36.borderpad, - borderwidth: _$attributes_36.borderwidth, - showarrow: _$attributes_36.showarrow, - arrowcolor: _$attributes_36.arrowcolor, - arrowhead: _$attributes_36.arrowhead, - startarrowhead: _$attributes_36.startarrowhead, - arrowside: _$attributes_36.arrowside, - arrowsize: _$attributes_36.arrowsize, - startarrowsize: _$attributes_36.startarrowsize, - arrowwidth: _$attributes_36.arrowwidth, - standoff: _$attributes_36.standoff, - startstandoff: _$attributes_36.startstandoff, - hovertext: _$attributes_36.hovertext, - hoverlabel: _$attributes_36.hoverlabel, - captureevents: _$attributes_36.captureevents, + label = xi + ',' + yi; + corners = [[z[yi][xi], z[yi][xi + 1]], + [z[yi + 1][xi], z[yi + 1][xi + 1]]]; + for(i = 0; i < pathinfo.length; i++) { + pi = pathinfo[i]; + mi = getMarchingIndex(pi.level, corners); + if(!mi) continue; - // maybes later? - // clicktoshow: annAtts.clicktoshow, - // xclick: annAtts.xclick, - // yclick: annAtts.yclick, + pi.crossings[label] = mi; + if(startIndices.indexOf(mi) !== -1) { + pi.starts.push([xi, yi]); + if(twoWide && startIndices.indexOf(mi, + startIndices.indexOf(mi) + 1) !== -1) { + // the same square has starts from opposite sides + // it's not possible to have starts on opposite edges + // of a corner, only a start and an end... + // but if the array is only two points wide (either way) + // you can have starts on opposite sides. + pi.starts.push([xi, yi]); + } + } + } + } + } +}; - // not needed! - // axref: 'pixel' - // ayref: 'pixel' - // xref: 'x' - // yref: 'y - // zref: 'z' -}, 'calc', 'from-root'); +// modified marching squares algorithm, +// so we disambiguate the saddle points from the start +// and we ignore the cases with no crossings +// the index I'm using is based on: +// http://en.wikipedia.org/wiki/Marching_squares +// except that the saddles bifurcate and I represent them +// as the decimal combination of the two appropriate +// non-saddle indices +function getMarchingIndex(val, corners) { + var mi = (corners[0][0] > val ? 0 : 1) + + (corners[0][1] > val ? 0 : 2) + + (corners[1][1] > val ? 0 : 4) + + (corners[1][0] > val ? 0 : 8); + if(mi === 5 || mi === 10) { + var avg = (corners[0][0] + corners[0][1] + + corners[1][0] + corners[1][1]) / 4; + // two peaks with a big valley + if(val > avg) return (mi === 5) ? 713 : 1114; + // two valleys with a big ridge + return (mi === 5) ? 104 : 208; + } + return (mi === 15) ? 0 : mi; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -45831,270 +44967,443 @@ var _$attributes_45 = __overrideAll_45({ * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; +/* removed: var _$tinycolor_33 = require('tinycolor2'); */; -var _$convert_46 = function convert(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var anns = fullSceneLayout.annotations; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$colorscale_66 = require('../../components/colorscale'); */; +/* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; - for(var i = 0; i < anns.length; i++) { - mockAnnAxes(anns[i], scene); - } +/* removed: var _$maxRowLength_330 = require('./max_row_length'); */; - scene.fullLayout._infolayer - .selectAll('.annotation-' + scene.id) - .remove(); -}; -function mockAnnAxes(ann, scene) { - var fullSceneLayout = scene.fullSceneLayout; - var domain = fullSceneLayout.domain; - var size = scene.fullLayout._size; +var _$plot_331 = function(gd, plotinfo, cdheatmaps) { + for(var i = 0; i < cdheatmaps.length; i++) { + __plotOne_331(gd, plotinfo, cdheatmaps[i]); + } +}; - var base = { - // this gets fill in on render - pdata: null, +function __plotOne_331(gd, plotinfo, cd) { + var cd0 = cd[0]; + var trace = cd0.trace; + var uid = trace.uid; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var fullLayout = gd._fullLayout; + var id = 'hm' + uid; - // to get setConvert to not execute cleanly - type: 'linear', + // in case this used to be a contour map + fullLayout._paper.selectAll('.contour' + uid).remove(); + fullLayout._infolayer.selectAll('g.rangeslider-container') + .selectAll('.contour' + uid).remove(); - // don't try to update them on `editable: true` - autorange: false, - - // set infinite range so that annotation draw routine - // does not try to remove 'outside-range' annotations, - // this case is handled in the render loop - range: [-Infinity, Infinity] - }; - - ann._xa = {}; - _$lib_171.extendFlat(ann._xa, base); - _$axes_213.setConvert(ann._xa); - ann._xa._offset = size.l + domain.x[0] * size.w; - ann._xa.l2p = function() { - return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); - }; + if(trace.visible !== true) { + fullLayout._paper.selectAll('.' + id).remove(); + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + return; + } - ann._ya = {}; - _$lib_171.extendFlat(ann._ya, base); - _$axes_213.setConvert(ann._ya); - ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; - ann._ya.l2p = function() { - return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); - }; -} + var z = cd0.z; + var x = cd0.x; + var y = cd0.y; + var xc = cd0.xCenter; + var yc = cd0.yCenter; + var isContour = _$registry_262.traceIs(trace, 'contour'); + var zsmooth = isContour ? 'best' : trace.zsmooth; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // get z dims + var m = z.length; + var n = _$maxRowLength_330(z); + var xrev = false; + var yrev = false; -'use strict'; + var left, right, temp, top, bottom, i; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_209 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationCommonDefaults_39 = require('../annotations/common_defaults'); */; -/* removed: var _$attributes_45 = require('./attributes'); */; + // TODO: if there are multiple overlapping categorical heatmaps, + // or if we allow category sorting, then the categories may not be + // sequential... may need to reorder and/or expand z -var _$handleDefaults_47 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_209(sceneLayoutIn, sceneLayoutOut, { - name: 'annotations', - handleItemDefaults: __handleAnnotationDefaults_47, - fullLayout: opts.fullLayout - }); -}; + // Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates) + // figure out if either axis is reversed (y is usually reversed, in pixel coords) + // also clip the image to maximum 50% outside the visible plot area + // bigger image lets you pan more naturally, but slows performance. + // TODO: use low-resolution images outside the visible plot for panning + // these while loops find the first and last brick bounds that are defined + // (in case of log of a negative) + i = 0; + while(left === undefined && i < x.length - 1) { + left = xa.c2p(x[i]); + i++; + } + i = x.length - 1; + while(right === undefined && i > 0) { + right = xa.c2p(x[i]); + i--; + } -function __handleAnnotationDefaults_47(annIn, annOut, sceneLayout, opts, itemOpts) { - function coerce(attr, dflt) { - return _$lib_171.coerce(annIn, annOut, _$attributes_45, attr, dflt); + if(right < left) { + temp = right; + right = left; + left = temp; + xrev = true; } - function coercePosition(axLetter) { - var axName = axLetter + 'axis'; + i = 0; + while(top === undefined && i < y.length - 1) { + top = ya.c2p(y[i]); + i++; + } + i = y.length - 1; + while(bottom === undefined && i > 0) { + bottom = ya.c2p(y[i]); + i--; + } - // mock in such way that getFromId grabs correct 3D axis - var gdMock = { _fullLayout: {} }; - gdMock._fullLayout[axName] = sceneLayout[axName]; + if(bottom < top) { + temp = top; + top = bottom; + bottom = temp; + yrev = true; + } - return _$axes_213.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + // for contours with heatmap fill, we generate the boundaries based on + // brick centers but then use the brick edges for drawing the bricks + if(isContour) { + xc = x; + yc = y; + x = cd0.xfill; + y = cd0.yfill; } + // make an image that goes at most half a screen off either side, to keep + // time reasonable when you zoom in. if zsmooth is true/fast, don't worry + // about this, because zooming doesn't increase number of pixels + // if zsmooth is best, don't include anything off screen because it takes too long + if(zsmooth !== 'fast') { + var extra = zsmooth === 'best' ? 0 : 0.5; + left = Math.max(-extra * xa._length, left); + right = Math.min((1 + extra) * xa._length, right); + top = Math.max(-extra * ya._length, top); + bottom = Math.min((1 + extra) * ya._length, bottom); + } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - if(!visible) return annOut; + var imageWidth = Math.round(right - left), + imageHeight = Math.round(bottom - top); - _$handleAnnotationCommonDefaults_39(annIn, annOut, opts.fullLayout, coerce); + // setup image nodes - coercePosition('x'); - coercePosition('y'); - coercePosition('z'); + // if image is entirely off-screen, don't even draw it + var isOffScreen = (imageWidth <= 0 || imageHeight <= 0); - // if you have one coordinate you should all three - _$lib_171.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + var plotgroup = plotinfo.plot.select('.imagelayer') + .selectAll('g.hm.' + id) + .data(isOffScreen ? [] : [0]); - // hard-set here for completeness - annOut.xref = 'x'; - annOut.yref = 'y'; - annOut.zref = 'z'; + plotgroup.enter().append('g') + .classed('hm', true) + .classed(id, true); - coerce('xanchor'); - coerce('yanchor'); - coerce('xshift'); - coerce('yshift'); + plotgroup.exit().remove(); - if(annOut.showarrow) { - annOut.axref = 'pixel'; - annOut.ayref = 'pixel'; + if(isOffScreen) return; - // TODO maybe default values should be bigger than the 2D case? - coerce('ax', -10); - coerce('ay', -30); + // generate image data - // if you have one part of arrow length you should have both - _$lib_171.noneOrAll(annIn, annOut, ['ax', 'ay']); + var canvasW, canvasH; + if(zsmooth === 'fast') { + canvasW = n; + canvasH = m; + } else { + canvasW = imageWidth; + canvasH = imageHeight; } - return annOut; -} + var canvas = document.createElement('canvas'); + canvas.width = canvasW; + canvas.height = canvasH; + var context = canvas.getContext('2d'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 sclFunc = _$colorscale_66.makeColorScaleFunc( + _$colorscale_66.extractScale( + trace.colorscale, + trace.zmin, + trace.zmax + ), + { noNumericCheck: true, returnArray: true } + ); + + // map brick boundaries to image pixels + var xpx, + ypx; + if(zsmooth === 'fast') { + xpx = xrev ? + function(index) { return n - 1 - index; } : + _$lib_172.identity; + ypx = yrev ? + function(index) { return m - 1 - index; } : + _$lib_172.identity; + } + else { + xpx = function(index) { + return _$lib_172.constrain(Math.round(xa.c2p(x[index]) - left), + 0, imageWidth); + }; + ypx = function(index) { + return _$lib_172.constrain(Math.round(ya.c2p(y[index]) - top), + 0, imageHeight); + }; + } + // build the pixel map brick-by-brick + // cruise through z-matrix row-by-row + // build a brick at each z-matrix value + var yi = ypx(0); + var yb = [yi, yi]; + var xbi = xrev ? 0 : 1; + var ybi = yrev ? 0 : 1; + // for collecting an average luminosity of the heatmap + var pixcount = 0; + var rcount = 0; + var gcount = 0; + var bcount = 0; -'use strict'; + var xb, j, xi, v, row, c; -function xformMatrix(m, v) { - var out = [0, 0, 0, 0]; - var i, j; + function setColor(v, pixsize) { + if(v !== undefined) { + var c = sclFunc(v); + c[0] = Math.round(c[0]); + c[1] = Math.round(c[1]); + c[2] = Math.round(c[2]); - for(i = 0; i < 4; ++i) { - for(j = 0; j < 4; ++j) { - out[j] += m[4 * i + j] * v[i]; + pixcount += pixsize; + rcount += c[0] * pixsize; + gcount += c[1] * pixsize; + bcount += c[2] * pixsize; + return c; } + return [0, 0, 0, 0]; } - return out; -} + function interpColor(r0, r1, xinterp, yinterp) { + var z00 = r0[xinterp.bin0]; + if(z00 === undefined) return setColor(undefined, 1); -function project(camera, v) { - var p = xformMatrix(camera.projection, - xformMatrix(camera.view, - xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); - return p; -} + var z01 = r0[xinterp.bin1], + z10 = r1[xinterp.bin0], + z11 = r1[xinterp.bin1], + dx = (z01 - z00) || 0, + dy = (z10 - z00) || 0, + dxy; -var _$project_243 = project; + // the bilinear interpolation term needs different calculations + // for all the different permutations of missing data + // among the neighbors of the main point, to ensure + // continuity across brick boundaries. + if(z01 === undefined) { + if(z11 === undefined) dxy = 0; + else if(z10 === undefined) dxy = 2 * (z11 - z00); + else dxy = (2 * z11 - z10 - z00) * 2 / 3; + } + else if(z11 === undefined) { + if(z10 === undefined) dxy = 0; + else dxy = (2 * z00 - z01 - z10) * 2 / 3; + } + else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3; + else dxy = (z11 + z00 - z01 - z10); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy)); + } -'use strict'; + if(zsmooth) { // best or fast, works fastest with imageData + var pxIndex = 0, + pixels; -var __drawRaw_48 = _$draw_42.drawRaw; -/* removed: var _$project_243 = require('../../plots/gl3d/project'); */; -var axLetters = ['x', 'y', 'z']; + try { + pixels = new Uint8Array(imageWidth * imageHeight * 4); + } + catch(e) { + pixels = new Array(imageWidth * imageHeight * 4); + } -var _$draw_48 = function draw(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var dataScale = scene.dataScale; - var anns = fullSceneLayout.annotations; + if(zsmooth === 'best') { + var xForPx = xc || x; + var yForPx = yc || y; + var xPixArray = new Array(xForPx.length); + var yPixArray = new Array(yForPx.length); + var xinterpArray = new Array(imageWidth); + var findInterpX = xc ? findInterpFromCenters : findInterp; + var findInterpY = yc ? findInterpFromCenters : findInterp; + var yinterp, r0, r1; - for(var i = 0; i < anns.length; i++) { - var ann = anns[i]; - var annotationIsOffscreen = false; + // first make arrays of x and y pixel locations of brick boundaries + for(i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left); + for(i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top); - for(var j = 0; j < 3; j++) { - var axLetter = axLetters[j]; - var pos = ann[axLetter]; - var ax = fullSceneLayout[axLetter + 'axis']; - var posFraction = ax.r2fraction(pos); + // then make arrays of interpolations + // (bin0=closest, bin1=next, frac=fractional dist.) + for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray); - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - break; + // now do the interpolations and fill the png + for(j = 0; j < imageHeight; j++) { + yinterp = findInterpY(j, yPixArray); + r0 = z[yinterp.bin0]; + r1 = z[yinterp.bin1]; + for(i = 0; i < imageWidth; i++, pxIndex += 4) { + c = interpColor(r0, r1, xinterpArray[i], yinterp); + putColor(pixels, pxIndex, c); + } + } + } + else { // zsmooth = fast + for(j = 0; j < m; j++) { + row = z[j]; + yb = ypx(j); + for(i = 0; i < imageWidth; i++) { + c = setColor(row[i], 1); + pxIndex = (yb * imageWidth + xpx(i)) * 4; + putColor(pixels, pxIndex, c); + } } } - if(annotationIsOffscreen) { - scene.fullLayout._infolayer - .select('.annotation-' + scene.id + '[data-index="' + i + '"]') - .remove(); - } else { - ann._pdata = _$project_243(scene.glplot.cameraParams, [ - fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], - fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], - fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] - ]); + var imageData = context.createImageData(imageWidth, imageHeight); + try { + imageData.data.set(pixels); + } + catch(e) { + var pxArray = imageData.data, + dlen = pxArray.length; + for(j = 0; j < dlen; j ++) { + pxArray[j] = pixels[j]; + } + } - __drawRaw_48(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + context.putImageData(imageData, 0, 0); + } else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect + + // gaps do not need to be exact integers, but if they *are* we will get + // cleaner edges by rounding at least one edge + var xGap = trace.xgap; + var yGap = trace.ygap; + var xGapLeft = Math.floor(xGap / 2); + var yGapTop = Math.floor(yGap / 2); + + for(j = 0; j < m; j++) { + row = z[j]; + yb.reverse(); + yb[ybi] = ypx(j + 1); + if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) { + continue; + } + xi = xpx(0); + xb = [xi, xi]; + for(i = 0; i < n; i++) { + // build one color brick! + xb.reverse(); + xb[xbi] = xpx(i + 1); + if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) { + continue; + } + v = row[i]; + c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0])); + context.fillStyle = 'rgba(' + c.join(',') + ')'; + + context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop, + xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap); + } } } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; + rcount = Math.round(rcount / pixcount); + gcount = Math.round(gcount / pixcount); + bcount = Math.round(bcount / pixcount); + var avgColor = _$tinycolor_33('rgb(' + rcount + ',' + gcount + ',' + bcount + ')'); -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; + gd._hmpixcount = (gd._hmpixcount||0) + pixcount; + gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance(); -var _$annotations3d_49 = { - moduleType: 'component', - name: 'annotations3d', + var image3 = plotgroup.selectAll('image') + .data(cd); - schema: { - subplots: { - scene: {annotations: _$attributes_45} - } - }, + image3.enter().append('svg:image').attr({ + xmlns: _$xmlns_namespaces_156.svg, + preserveAspectRatio: 'none' + }); - layoutAttributes: _$attributes_45, - handleDefaults: _$handleDefaults_47, - includeBasePlot: includeGL3D, + image3.attr({ + height: imageHeight, + width: imageWidth, + x: left, + y: top, + 'xlink:href': canvas.toDataURL('image/png') + }); - convert: _$convert_46, - draw: _$draw_48 -}; + image3.exit().remove(); +} -function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_261.subplotsRegistry.gl3d; - if(!GL3D) return; +// get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin} +function findInterp(pixel, pixArray) { + var maxBin = pixArray.length - 2; + var bin = _$lib_172.constrain(_$lib_172.findBin(pixel, pixArray), 0, maxBin); + var pix0 = pixArray[bin]; + var pix1 = pixArray[bin + 1]; + var interp = _$lib_172.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin); + var bin0 = Math.round(interp); + var frac = Math.abs(interp - bin0); - var attrRegex = GL3D.attrRegex; + if(!interp || interp === maxBin || !frac) { + return { + bin0: bin0, + bin1: bin0, + frac: 0 + }; + } + return { + bin0: bin0, + frac: frac, + bin1: Math.round(bin0 + frac / (interp - bin0)) + }; +} - var keys = Object.keys(layoutIn); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; - if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_171.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_171.pushUnique(layoutOut._subplots.gl3d, k); - } +function findInterpFromCenters(pixel, centerPixArray) { + var maxBin = centerPixArray.length - 1; + var bin = _$lib_172.constrain(_$lib_172.findBin(pixel, centerPixArray), 0, maxBin); + var pix0 = centerPixArray[bin]; + var pix1 = centerPixArray[bin + 1]; + var frac = ((pixel - pix0) / (pix1 - pix0)) || 0; + if(frac <= 0) { + return { + bin0: bin, + bin1: bin, + frac: 0 + }; + } + if(frac < 0.5) { + return { + bin0: bin, + bin1: bin + 1, + frac: frac + }; } + return { + bin0: bin + 1, + bin1: bin, + frac: 1 - frac + }; } +function putColor(pixels, pxIndex, c) { + pixels[pxIndex] = c[0]; + pixels[pxIndex + 1] = c[1]; + pixels[pxIndex + 2] = c[2]; + pixels[pxIndex + 3] = Math.round(c[3] * 255); +} + +var _$plot_314 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46103,654 +45412,687 @@ function includeGL3D(layoutIn, layoutOut) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; +/* removed: var _$d3_15 = require('d3'); */; -var _$attributes_78 = { - visible: { - valType: 'boolean', - - editType: 'calc', - - }, - type: { - valType: 'enumerated', - values: ['percent', 'constant', 'sqrt', 'data'], - - editType: 'calc', - - }, - symmetric: { - valType: 'boolean', - - editType: 'calc', - - }, - array: { - valType: 'data_array', - editType: 'calc', - - }, - arrayminus: { - valType: 'data_array', - editType: 'calc', - - }, - value: { - valType: 'number', - min: 0, - dflt: 10, - - editType: 'calc', - - }, - valueminus: { - valType: 'number', - min: 0, - dflt: 10, - - editType: 'calc', - - }, - traceref: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'style' - }, - tracerefminus: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'style' - }, - copy_ystyle: { - valType: 'boolean', - - editType: 'plot' - }, - copy_zstyle: { - valType: 'boolean', - - editType: 'style' - }, - color: { - valType: 'color', - - editType: 'style', - - }, - thickness: { - valType: 'number', - min: 0, - dflt: 2, - - editType: 'style', - - }, - width: { - valType: 'number', - min: 0, - - editType: 'plot', - - }, - editType: 'calc', - - _deprecated: { - opacity: { - valType: 'number', - - editType: 'style', - - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$setConvert_232 = require('../../plots/cartesian/set_convert'); */; -'use strict'; +/* removed: var _$plot_331 = require('../heatmap/plot'); */; +/* removed: var _$makeCrossings_313 = require('./make_crossings'); */; +/* removed: var _$findAllPaths_308 = require('./find_all_paths'); */; +/* removed: var _$emptyPathinfo_306 = require('./empty_pathinfo'); */; +/* removed: var _$convert_to_constraints_304 = require('./convert_to_constraints'); */; +/* removed: var _$close_boundaries_298 = require('./close_boundaries'); */; +/* removed: var _$constants_300 = require('./constants'); */; +var costConstants = _$constants_300.LABELOPTIMIZER; -/** - * 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 " - */ -var _$makeComputeError_80 = function makeComputeError(opts) { - var type = opts.type, - symmetric = opts.symmetric; +_$plot_314.plot = function plot(gd, plotinfo, cdcontours) { + for(var i = 0; i < cdcontours.length; i++) { + __plotOne_314(gd, plotinfo, cdcontours[i]); + } +}; - if(type === 'data') { - var array = opts.array || []; +function __plotOne_314(gd, plotinfo, cd) { + var trace = cd[0].trace, + x = cd[0].x, + y = cd[0].y, + contours = trace.contours, + uid = trace.uid, + xa = plotinfo.xaxis, + ya = plotinfo.yaxis, + fullLayout = gd._fullLayout, + id = 'contour' + uid, + pathinfo = _$emptyPathinfo_306(contours, plotinfo, cd[0]); - 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]; - }; - } + if(trace.visible !== true) { + fullLayout._paper.selectAll('.' + id + ',.hm' + uid).remove(); + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + return; } - else { - var computeErrorValue = makeComputeErrorValue(type, opts.value), - 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) - ]; - }; + // use a heatmap to fill - draw it behind the lines + if(contours.coloring === 'heatmap') { + if(trace.zauto && (trace.autocontour === false)) { + trace._input.zmin = trace.zmin = + contours.start - contours.size / 2; + trace._input.zmax = trace.zmax = + trace.zmin + pathinfo.length * contours.size; } - } -}; -/** - * 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); - }; + _$plot_331(gd, plotinfo, [cd]); } - if(type === 'sqrt') { - return function(dataPt) { - return Math.sqrt(Math.abs(dataPt)); - }; + // in case this used to be a heatmap (or have heatmap fill) + else { + fullLayout._paper.selectAll('.hm' + uid).remove(); + fullLayout._infolayer.selectAll('g.rangeslider-container') + .selectAll('.hm' + uid).remove(); } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; + _$makeCrossings_313(pathinfo); + _$findAllPaths_308(pathinfo); -/* removed: var _$makeComputeError_80 = require('./compute_error'); */; + var leftedge = xa.c2p(x[0], true), + rightedge = xa.c2p(x[x.length - 1], true), + bottomedge = ya.c2p(y[0], true), + topedge = ya.c2p(y[y.length - 1], true), + perimeter = [ + [leftedge, topedge], + [rightedge, topedge], + [rightedge, bottomedge], + [leftedge, bottomedge] + ]; + var fillPathinfo = pathinfo; + if(contours.type === 'constraint') { + fillPathinfo = _$convert_to_constraints_304(pathinfo, contours._operation); + _$close_boundaries_298(fillPathinfo, contours._operation, perimeter, trace); + } -var _$calc_79 = function calc(gd) { - var calcdata = gd.calcdata; + // draw everything + var plotGroup = _$plot_314.makeContourGroup(plotinfo, cd, id); + makeBackground(plotGroup, perimeter, contours); + makeFills(plotGroup, fillPathinfo, perimeter, contours); + makeLinesAndLabels(plotGroup, pathinfo, gd, cd[0], contours, perimeter); + clipGaps(plotGroup, plotinfo, fullLayout._clips, cd[0], perimeter); +} - for(var i = 0; i < calcdata.length; i++) { - var calcTrace = calcdata[i], - trace = calcTrace[0].trace; +_$plot_314.makeContourGroup = function(plotinfo, cd, id) { + var plotgroup = plotinfo.plot.select('.maplayer') + .selectAll('g.contour.' + id) + .data(cd); - if(!_$registry_261.traceIs(trace, 'errorBarsOK')) continue; + plotgroup.enter().append('g') + .classed('contour', true) + .classed(id, true); - var xa = _$axes_213.getFromId(gd, trace.xaxis), - ya = _$axes_213.getFromId(gd, trace.yaxis); + plotgroup.exit().remove(); - calcOneAxis(calcTrace, trace, xa, 'x'); - calcOneAxis(calcTrace, trace, ya, 'y'); - } + return plotgroup; }; -function calcOneAxis(calcTrace, trace, axis, coord) { - var opts = trace['error_' + coord] || {}, - isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), - vals = []; +function makeBackground(plotgroup, perimeter, contours) { + var bggroup = _$lib_172.ensureSingle(plotgroup, 'g', 'contourbg'); - if(!isVisible) return; + 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'); +} - var computeError = _$makeComputeError_80(opts); +function makeFills(plotgroup, pathinfo, perimeter, contours) { + var fillgroup = _$lib_172.ensureSingle(plotgroup, 'g', 'contourfill'); - for(var i = 0; i < calcTrace.length; i++) { - var calcPt = calcTrace[i], - calcCoord = calcPt[coord]; + var fillitems = fillgroup.selectAll('path') + .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? 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 = joinAllPaths(pi, perimeter); - if(!_$fastIsnumeric_18(axis.c2l(calcCoord))) continue; + if(!fullpath) _$d3_15.select(this).remove(); + else _$d3_15.select(this).attr('d', fullpath).style('stroke', 'none'); + }); +} - var errors = computeError(calcCoord, i); - if(_$fastIsnumeric_18(errors[0]) && _$fastIsnumeric_18(errors[1])) { - var shoe = calcPt[coord + 's'] = calcCoord - errors[0], - hat = calcPt[coord + 'h'] = calcCoord + errors[1]; - vals.push(shoe, hat); - } +function initFullPath(pi, perimeter) { + var prefixBoundary = pi.prefixBoundary; + if(prefixBoundary === undefined) { + var edgeVal2 = Math.min(pi.z[0][0], pi.z[0][1]); + prefixBoundary = (!pi.edgepaths.length && edgeVal2 > pi.level); } - _$axes_213.expand(axis, vals, {padded: true}); + if(prefixBoundary) { + // TODO: why does ^^ not work for constraints? + // pi.prefixBoundary gets set by closeBoundaries + return 'M' + perimeter.join('L') + 'Z'; + } + return ''; } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +function joinAllPaths(pi, perimeter) { + var fullpath = initFullPath(pi, perimeter), + i = 0, + startsleft = pi.edgepaths.map(function(v, i) { return i; }), + newloop = true, + endpt, + newendpt, + cnt, + nexti, + possiblei, + addpath; -/* removed: var _$attributes_78 = require('./attributes'); */; + 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_76.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; -var _$defaults_81 = function(traceIn, traceOut, defaultColor, opts) { - var objName = 'error_' + opts.axis, - containerOut = traceOut[objName] = {}, - containerIn = traceIn[objName] || {}; + // 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_172.log('Missing end?', i, pi); + break; + } - function coerce(attr, dflt) { - return _$lib_171.coerce(containerIn, containerOut, _$attributes_78, attr, dflt); - } + 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 - var hasErrorBars = ( - containerIn.array !== undefined || - containerIn.value !== undefined || - containerIn.type === 'sqrt' - ); + 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_172.log('endpt to newendpt is not vert. or horz.', + endpt, newendpt, ptNew); + } + } - var visible = coerce('visible', hasErrorBars); + endpt = newendpt; - if(visible === false) return; + if(nexti >= 0) break; + fullpath += 'L' + newendpt; + } - var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), - symmetric = true; + if(nexti === pi.edgepaths.length) { + _$lib_172.log('unclosed perimeter path'); + break; + } - if(type !== 'sqrt') { - symmetric = coerce('symmetric', - !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); - } + i = nexti; - if(type === 'data') { - coerce('array'); - coerce('traceref'); - if(!symmetric) { - coerce('arrayminus'); - coerce('tracerefminus'); + // 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'; } } - 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 || - _$fastIsnumeric_18(containerIn.thickness) || - _$fastIsnumeric_18(containerIn.width))); - } - } - if(!opts.inherit || !containerOut[copyAttr]) { - coerce('color', defaultColor); - coerce('thickness'); - coerce('width', _$registry_261.traceIs(traceOut, 'gl3d') ? 0 : 4); + // finally add the interior paths + for(i = 0; i < pi.paths.length; i++) { + fullpath += _$drawing_76.smoothclosed(pi.paths[i], pi.smoothing); } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 fullpath; +} -'use strict'; +function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { + var lineContainer = _$lib_172.ensureSingle(plotgroup, 'g', 'contourlines'); + var showLines = contours.showlines !== false; + var showLabels = contours.showlabels; + var clipLinesForLabels = showLines && showLabels; -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + // 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 = _$plot_314.createLines(lineContainer, showLines || showLabels, pathinfo); -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$subtypes_390 = require('../../traces/scatter/subtypes'); */; + var lineClip = _$plot_314.createLineClip(lineContainer, clipLinesForLabels, + gd._fullLayout._clips, cd0.trace.uid); -var _$plot_83 = function plot(traces, plotinfo, transitionOpts) { - var isNew; + var labelGroup = plotgroup.selectAll('g.contourlabels') + .data(showLabels ? [0] : []); - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + labelGroup.exit().remove(); - var hasAnimation = transitionOpts && transitionOpts.duration > 0; + labelGroup.enter().append('g') + .classed('contourlabels', true); - 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 - xObj = trace.error_x || {}, - yObj = trace.error_y || {}; + if(showLabels) { + var labelClipPathData = [perimeter]; - var keyFunc; + var labelData = []; - if(trace.ids) { - keyFunc = function(d) {return d.id;}; - } + // invalidate the getTextLocation cache in case paths changed + _$lib_172.clearLocationCache(); - var sparse = ( - _$subtypes_390.hasMarkers(trace) && - trace.marker.maxdisplayed > 0 - ); + var contourFormat = _$plot_314.labelFormatter(contours, cd0.t.cb, gd._fullLayout); - if(!yObj.visible && !xObj.visible) d = []; + var dummyText = _$drawing_76.tester.append('text') + .attr('data-notex', 1) + .call(_$drawing_76.font, contours.labelfont); - var errorbars = _$d3_15.select(this).selectAll('g.errorbar') - .data(d, keyFunc); + var xLen = pathinfo[0].xaxis._length; + var yLen = pathinfo[0].yaxis._length; - errorbars.exit().remove(); + // visible bounds of the contour trace (and the midpoints, to + // help with cost calculations) + var bounds = { + left: Math.max(perimeter[0][0], 0), + right: Math.min(perimeter[2][0], xLen), + top: Math.max(perimeter[0][1], 0), + bottom: Math.min(perimeter[2][1], yLen) + }; + bounds.middle = (bounds.top + bounds.bottom) / 2; + bounds.center = (bounds.left + bounds.right) / 2; - if(!d.length) return; + var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen); - if(!xObj.visible) errorbars.selectAll('path.xerror').remove(); - if(!yObj.visible) errorbars.selectAll('path.yerror').remove(); + // the path length to use to scale the number of labels to draw: + var normLength = _$constants_300.LABELDISTANCE * plotDiagonal / + Math.max(1, pathinfo.length / _$constants_300.LABELINCREASE); - errorbars.style('opacity', 1); + linegroup.each(function(d) { + var textOpts = _$plot_314.calcTextOpts(d.level, contourFormat, dummyText, gd); - var enter = errorbars.enter().append('g') - .classed('errorbar', true); + _$d3_15.select(this).selectAll('path').each(function() { + var path = this; + var pathBounds = _$lib_172.getVisibleSegment(path, bounds, textOpts.height / 2); + if(!pathBounds) return; - if(hasAnimation) { - enter.style('opacity', 0).transition() - .duration(transitionOpts.duration) - .style('opacity', 1); - } + if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_300.LABELMIN) return; - _$drawing_76.setClipUrl(errorbars, plotinfo.layerClipId); + var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), + _$constants_300.LABELMAX); - errorbars.each(function(d) { - var errorbar = _$d3_15.select(this); - var coords = errorCoords(d, xa, ya); + for(var i = 0; i < maxLabels; i++) { + var loc = _$plot_314.findBestTextLocation(path, pathBounds, textOpts, + labelData, bounds); - if(sparse && !d.vis) return; + if(!loc) break; - var path; + _$plot_314.addLabelData(loc, textOpts, labelData, labelClipPathData); + } + }); + }); - var yerror = errorbar.select('path.yerror'); - if(yObj.visible && _$fastIsnumeric_18(coords.x) && - _$fastIsnumeric_18(coords.yh) && - _$fastIsnumeric_18(coords.ys)) { - var yw = yObj.width; + dummyText.remove(); - path = 'M' + (coords.x - yw) + ',' + - coords.yh + 'h' + (2 * yw) + // hat - 'm-' + yw + ',0V' + coords.ys; // bar + _$plot_314.drawLabels(labelGroup, labelData, gd, lineClip, + clipLinesForLabels ? labelClipPathData : null); + } + if(showLabels && !showLines) linegroup.remove(); +} - if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe +_$plot_314.createLines = function(lineContainer, makeLines, pathinfo) { + var smoothing = pathinfo[0].smoothing; - isNew = !yerror.size(); + var linegroup = lineContainer.selectAll('g.contourlevel') + .data(makeLines ? pathinfo : []); - 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); - } + linegroup.exit().remove(); + linegroup.enter().append('g') + .classed('contourlevel', true); - yerror.attr('d', path); - } - else yerror.remove(); + 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; }); - var xerror = errorbar.select('path.xerror'); - if(xObj.visible && _$fastIsnumeric_18(coords.y) && - _$fastIsnumeric_18(coords.xh) && - _$fastIsnumeric_18(coords.xs)) { - var xw = (xObj.copy_ystyle ? yObj : xObj).width; + opencontourlines.exit().remove(); + opencontourlines.enter().append('path') + .classed('openline', true); - path = 'M' + coords.xh + ',' + - (coords.y - xw) + 'v' + (2 * xw) + // hat - 'm0,-' + xw + 'H' + coords.xs; // bar + opencontourlines + .attr('d', function(d) { + return _$drawing_76.smoothopen(d, smoothing); + }) + .style('stroke-miterlimit', 1) + .style('vector-effect', 'non-scaling-stroke'); - if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe + var closedcontourlines = linegroup.selectAll('path.closedline') + .data(function(d) { return d.ppaths || d.paths; }); - isNew = !xerror.size(); + closedcontourlines.exit().remove(); + closedcontourlines.enter().append('path') + .classed('closedline', true); - 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); - } + closedcontourlines + .attr('d', function(d) { + return _$drawing_76.smoothclosed(d, smoothing); + }) + .style('stroke-miterlimit', 1) + .style('vector-effect', 'non-scaling-stroke'); + } - xerror.attr('d', path); - } - else xerror.remove(); - }); - }); + return linegroup; }; -// 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) - }; +_$plot_314.createLineClip = function(lineContainer, clipLinesForLabels, clips, uid) { + var clipId = clipLinesForLabels ? ('clipline' + uid) : null; - // 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); + var lineClip = clips.selectAll('#' + clipId) + .data(clipLinesForLabels ? [0] : []); + lineClip.exit().remove(); - // if the shoes go off-scale (ie log scale, error bars past zero) - // clip the bar and hide the shoes - if(!_$fastIsnumeric_18(out.ys)) { - out.noYS = true; - out.ys = ya.c2p(d.ys, true); - } + lineClip.enter().append('clipPath') + .classed('contourlineclip', true) + .attr('id', clipId); + + _$drawing_76.setClipUrl(lineContainer, clipId); + + return lineClip; +}; + +_$plot_314.labelFormatter = function(contours, colorbar, fullLayout) { + if(contours.labelformat) { + return fullLayout._d3locale.numberFormat(contours.labelformat); } + else { + var formatAxis; + if(colorbar) { + formatAxis = colorbar.axis; + } + else { + formatAxis = { + type: 'linear', + _id: 'ycontour', + showexponent: 'all' + }; - if(d.xh !== undefined) { - out.xh = xa.c2p(d.xh); - out.xs = xa.c2p(d.xs); + 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(!_$fastIsnumeric_18(out.xs)) { - out.noXS = true; - out.xs = xa.c2p(d.xs, true); + if(formatAxis.range[0] === formatAxis.range[1]) { + formatAxis.range[1] += formatAxis.range[0] || 1; + } + if(!formatAxis.nticks) formatAxis.nticks = 1000; + + _$setConvert_232(formatAxis, fullLayout); + _$axes_214.prepTicks(formatAxis); + formatAxis._tmin = null; + formatAxis._tmax = null; } + return function(v) { + return _$axes_214.tickText(formatAxis, v).text; + }; } +}; - return out; -} +_$plot_314.calcTextOpts = function(level, contourFormat, dummyText, gd) { + var text = contourFormat(level); + dummyText.text(text) + .call(_$svg_text_utils_193.convertToTspans, gd); + var bBox = _$drawing_76.bBox(dummyText.node(), true); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 { + text: text, + width: bBox.width, + height: bBox.height, + level: level, + dy: (bBox.top + bBox.bottom) / 2 + }; +}; +_$plot_314.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) { + var textWidth = textOpts.width; -'use strict'; + 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; + } -/* removed: var _$d3_15 = require('d3'); */; + var cost = Infinity; + for(var j = 0; j < costConstants.ITERATIONS; j++) { + for(var p = p0; p < pMax; p += dp) { + var newLocation = _$lib_172.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; -/* removed: var _$color_51 = require('../color'); */; + // 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; -var _$style_84 = function style(traces) { - traces.each(function(d) { - var trace = d[0].trace, - yObj = trace.error_y || {}, - xObj = trace.error_x || {}; + // 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)); - var s = _$d3_15.select(this); + // cost for not being horizontal + cost += costConstants.ANGLECOST * theta * theta; - s.selectAll('path.yerror') - .style('stroke-width', yObj.thickness + 'px') - .call(_$color_51.stroke, yObj.color); + // 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_172.segmentDistance( + x1, y1, + x2, y2, + labeli.x - dxd, labeli.y - dyd, + labeli.x + dxd, labeli.y + dyd + ) * 2 / (textOpts.height + labeli.height); - if(xObj.copy_ystyle) xObj = yObj; + var sameLevel = labeli.level === textOpts.level; + var distOffset = sameLevel ? costConstants.SAMELEVELDISTANCE : 1; - s.selectAll('path.xerror') - .style('stroke-width', xObj.thickness + 'px') - .call(_$color_51.stroke, xObj.color); - }); -}; + if(dist <= distOffset) return Infinity; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 distFactor = costConstants.NEIGHBORCOST * + (sameLevel ? costConstants.SAMELEVELFACTOR : 1); -'use strict'; + cost += distFactor / (dist - distOffset); + } -/* removed: var _$lib_171 = require('../../lib'); */; -var __overrideAll_82 = _$edit_types_198.overrideAll; + return cost; +} -/* removed: var _$attributes_78 = require('./attributes'); */; -/* removed: var _$calc_79 = require('./calc'); */; +_$plot_314.addLabelData = function(loc, textOpts, labelData, labelClipPathData) { + var halfWidth = textOpts.width / 2; + var halfHeight = textOpts.height / 2; -var xyAttrs = { - error_x: _$lib_171.extendFlat({}, _$attributes_78), - error_y: _$lib_171.extendFlat({}, _$attributes_78) -}; -delete xyAttrs.error_x.copy_zstyle; -delete xyAttrs.error_y.copy_zstyle; -delete xyAttrs.error_y.copy_ystyle; + var x = loc.x; + var y = loc.y; + var theta = loc.theta; -var xyzAttrs = { - error_x: _$lib_171.extendFlat({}, _$attributes_78), - error_y: _$lib_171.extendFlat({}, _$attributes_78), - error_z: _$lib_171.extendFlat({}, _$attributes_78) + 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); }; -delete xyzAttrs.error_x.copy_ystyle; -delete xyzAttrs.error_y.copy_ystyle; -delete xyzAttrs.error_z.copy_ystyle; -delete xyzAttrs.error_z.copy_zstyle; -var _$errorbars_82 = { - moduleType: 'component', - name: 'errorbars', +_$plot_314.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; + }); - schema: { - traces: { - scatter: xyAttrs, - bar: xyAttrs, - histogram: xyAttrs, - scatter3d: __overrideAll_82(xyzAttrs, 'calc', 'nested'), - scattergl: __overrideAll_82(xyAttrs, 'calc', 'nested') - } - }, + labels.exit().remove(); - supplyDefaults: _$defaults_81, + 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_15.select(this) + .text(d.text) + .attr({ + x: x, + y: y, + transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')' + }) + .call(_$svg_text_utils_193.convertToTspans, gd); + }); - calc: _$calc_79, - calcFromTrace: calcFromTrace, + if(labelClipPathData) { + var clipPath = ''; + for(var i = 0; i < labelClipPathData.length; i++) { + clipPath += 'M' + labelClipPathData[i].join('L') + 'Z'; + } - plot: _$plot_83, - style: _$style_84, - hoverInfo: hoverInfo + var lineClipPath = _$lib_172.ensureSingle(lineClip, 'path', ''); + lineClipPath.attr('d', clipPath); + } }; -function calcFromTrace(trace, layout) { - var x = trace.x || [], - y = trace.y || [], - len = x.length || y.length; +function clipGaps(plotGroup, plotinfo, clips, cd0, perimeter) { + var clipId = 'clip' + cd0.trace.uid; - var calcdataMock = new Array(len); + var clipPath = clips.selectAll('#' + clipId) + .data(cd0.trace.connectgaps ? [] : [0]); + clipPath.enter().append('clipPath') + .classed('contourclip', true) + .attr('id', clipId); + clipPath.exit().remove(); - for(var i = 0; i < len; i++) { - calcdataMock[i] = { - x: x[i], - y: y[i] + if(cd0.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 }; - } - calcdataMock[0].trace = trace; + _$makeCrossings_313([clipPathInfo]); + _$findAllPaths_308([clipPathInfo]); + var fullpath = joinAllPaths(clipPathInfo, perimeter); - _$calc_79({ - calcdata: [calcdataMock], - _fullLayout: layout - }); + var path = _$lib_172.ensureSingle(clipPath, 'path', ''); + path.attr('d', fullpath); + } + else clipId = null; - return calcdataMock; + plotGroup.call(_$drawing_76.setClipUrl, clipId); + plotinfo.plot.selectAll('.hm' + cd0.trace.uid) + .call(_$drawing_76.setClipUrl, clipId); } -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; +function makeClipMask(cd0) { + var empties = cd0.trace._emptypoints, + z = [], + m = cd0.z.length, + n = cd0.z[0].length, + i, + row = [], + 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; } -var _$domain_239 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46759,103 +46101,97 @@ var _$domain_239 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var __extendFlat_239 = _$extend_165.extendFlat; +/* removed: var _$d3_15 = require('d3'); */; + +var _$style_332 = function style(gd) { + _$d3_15.select(gd).selectAll('.hm image') + .style('opacity', function(d) { + return d.trace.opacity; + }); +}; /** - * 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 - */ -_$domain_239.attributes = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; +* Copyright 2012-2018, Plotly, Inc. +* All 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 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 : ''; +'use strict'; - var out = { - x: __extendFlat_239({}, base, { - - }), - y: __extendFlat_239({}, base, { - - }), - editType: opts.editType - }; +/* removed: var _$d3_15 = require('d3'); */; - 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, - - }; - } +/* removed: var _$drawing_76 = require('../../components/drawing'); */; +/* removed: var _$style_332 = require('../heatmap/style'); */; - return out; -}; +/* removed: var _$makeColorMap_312 = require('./make_color_map'); */; -_$domain_239.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 _$style_316 = function style(gd) { + var contours = _$d3_15.select(gd).selectAll('g.contour'); + + contours.style('opacity', function(d) { + return d.trace.opacity; + }); + + contours.each(function(d) { + var c = _$d3_15.select(this); + var trace = d.trace; + var contours = trace.contours; + var line = trace.line; + var cs = contours.size || 1; + var start = contours.start; + + // for contourcarpet only - is this a constraint-type contour trace? + var isConstraintType = contours.type === 'constraint'; + var colorLines = !isConstraintType && contours.coloring === 'lines'; + var colorFills = !isConstraintType && contours.coloring === 'fill'; + + var colorMap = (colorLines || colorFills) ? _$makeColorMap_312(trace) : null; + + c.selectAll('g.contourlevel').each(function(d) { + _$d3_15.select(this).selectAll('path') + .call(_$drawing_76.lineGroupStyle, + line.width, + colorLines ? colorMap(d.level) : line.color, + line.dash); + }); + + var labelFont = contours.labelfont; + c.selectAll('g.contourlabels text').each(function(d) { + _$drawing_76.font(_$d3_15.select(this), { + family: labelFont.family, + size: labelFont.size, + color: labelFont.color || (colorLines ? colorMap(d.level) : line.color) + }); + }); + + if(isConstraintType) { + c.selectAll('g.contourfill path') + .style('fill', trace.fillcolor); } + else if(colorFills) { + var firstFill; - var row = coerce('domain.row'); - if(row !== undefined) { - if(row < grid.rows) dfltY = grid._domains.y[row]; - else delete containerOut.domain.row; + c.selectAll('g.contourfill path') + .style('fill', function(d) { + if(firstFill === undefined) firstFill = d.level; + return colorMap(d.level + 0.5 * cs); + }); + + if(firstFill === undefined) firstFill = start; + + c.selectAll('g.contourbg path') + .style('fill', colorMap(firstFill - 0.5 * cs)); } - } + }); - coerce('domain.x', dfltX); - coerce('domain.y', dfltY); + _$style_332(gd); }; /** @@ -46866,1165 +46202,1575 @@ _$domain_239.defaults = function(containerOut, layout, coerce, dfltDomains) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -var __counterRegex_97 = _$regex_186.counter; -var domainAttrs = _$domain_239.attributes; -var cartesianIdRegex = _$constants_218.idRegex; +var Contour = {}; -var gridAttrs = { - rows: { - valType: 'integer', - min: 1, - - editType: 'plot', - +Contour.attributes = _$attributes_296; +Contour.supplyDefaults = _$supplyDefaults_305; +Contour.calc = _$calc_297; +Contour.plot = _$plot_314.plot; +Contour.style = _$style_316; +Contour.colorbar = _$colorbar_299; +Contour.hoverPoints = _$hoverPoints_309; + +Contour.moduleType = 'trace'; +Contour.name = 'contour'; +Contour.basePlotModule = _$cartesian_225; +Contour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'showLegend']; +Contour.meta = { + +}; + +var _$Contour_310 = Contour; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$contour_5 = _$Contour_310; + +var _$plotcss_1 = {}; +'use strict'; + +/* removed: var _$lib_172 = require('../src/lib'); */; +var rules = { + "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", + "X .modebar--hover": "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": "opacity:1;", + "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", + "X .modebar-group:first-child": "margin-left:0px;", + "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", + "X .modebar-btn svg": "position:relative;top:2px;", + "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", + "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", + "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", + "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", + "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 .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_172.addStyleRule(fullSelector, rules[selector]); +} + +'use strict'; + +var _$ploticon_2 = { + 'undo': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 }, - roworder: { - valType: 'enumerated', - values: ['top to bottom', 'bottom to top'], - dflt: 'top to bottom', - - editType: 'plot', - + 'home': { + 'width': 928.6, + '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', + 'ascent': 850, + 'descent': -150 }, - columns: { - valType: 'integer', - min: 1, - - editType: 'plot', - + 'camera-retro': { + 'width': 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', + 'ascent': 850, + 'descent': -150 }, - subplots: { - valType: 'info_array', - freeLength: true, - dimensions: 2, - items: {valType: 'enumerated', values: [__counterRegex_97('xy').toString(), ''], editType: 'plot'}, - - editType: 'plot', - + 'zoombox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 }, - xaxes: { - valType: 'info_array', - freeLength: true, - items: {valType: 'enumerated', values: [cartesianIdRegex.x.toString(), ''], editType: 'plot'}, - - editType: 'plot', - + 'pan': { + 'width': 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', + 'ascent': 850, + 'descent': -150 }, - yaxes: { - valType: 'info_array', - freeLength: true, - items: {valType: 'enumerated', values: [cartesianIdRegex.y.toString(), ''], editType: 'plot'}, - - editType: 'plot', - + 'zoom_plus': { + 'width': 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', + 'ascent': 850, + 'descent': -150 }, - pattern: { - valType: 'enumerated', - values: ['independent', 'coupled'], - dflt: 'coupled', - - editType: 'plot', - + 'zoom_minus': { + 'width': 1000, + 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', + 'ascent': 850, + 'descent': -150 }, - xgap: { - valType: 'number', - min: 0, - max: 1, - - editType: 'plot', - + 'autoscale': { + 'width': 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', + 'ascent': 850, + 'descent': -150 }, - ygap: { - valType: 'number', - min: 0, - max: 1, - - editType: 'plot', - + 'tooltip_basic': { + 'width': 1500, + 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', + 'ascent': 850, + 'descent': -150 }, - domain: domainAttrs({name: 'grid', editType: 'plot', noGridCell: true}, { - - }), - xside: { - valType: 'enumerated', - values: ['bottom', 'bottom plot', 'top plot', 'top'], - dflt: 'bottom plot', - - editType: 'ticks', - + 'tooltip_compare': { + 'width': 1125, + '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', + 'ascent': 850, + 'descent': -150 }, - yside: { - valType: 'enumerated', - values: ['left', 'left plot', 'right plot', 'right'], - dflt: 'left plot', - - editType: 'ticks', - + 'plotlylogo': { + 'width': 1542, + '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', + 'ascent': 850, + 'descent': -150 }, - editType: 'plot' + 'z-axis': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + '3d_rotate': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'camera': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'movie': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'question': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'disk': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'lasso': { + 'width': 1031, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'selectbox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'spikeline': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + } }; -// 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; - if(!gridIn) return; +var _$browser_32 = {}; +// shim for using process in browser +var process = _$browser_32 = {}; - var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]); - var hasXaxes = Array.isArray(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - var dfltRows, dfltColumns; +var cachedSetTimeout; +var cachedClearTimeout; - if(hasSubplotGrid) { - dfltRows = gridIn.subplots.length; - dfltColumns = gridIn.subplots[0].length; +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; } - else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } } - var gridOut = layoutOut.grid = {}; - function coerce(attr, dflt) { - return _$lib_171.coerce(gridIn, gridOut, gridAttrs, attr, dflt); +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } } - var rows = coerce('rows', dfltRows); - var columns = coerce('columns', dfltColumns); - - if(!(rows * columns > 1)) 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 queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; - gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) - }; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } } -// coerce x or y sizing attributes and return an array of domains for this direction -function fillGridPositions(axLetter, coerce, dfltGap, len, reversed) { - var dirGap = coerce(axLetter + 'gap', dfltGap); - var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - 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]; + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; } - return out; + currentQueue = null; + draining = false; + runClearTimeout(timeout); } -// 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'; +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; - var i, j, xId, yId, subplotId, subplotsOut, yPos; +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; - var axisMap = gridOut._axisMap = {}; +function __noop_32() {} - if(hasSubplotGrid) { - var subplotsIn = gridIn.subplots || []; - subplotsOut = gridOut.subplots = new Array(rows); - var index = 1; +process.on = __noop_32; +process.addListener = __noop_32; +process.once = __noop_32; +process.off = __noop_32; +process.removeListener = __noop_32; +process.removeAllListeners = __noop_32; +process.emit = __noop_32; +process.prependListener = __noop_32; +process.prependOnceListener = __noop_32; - 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]; +process.listeners = function (name) { return [] } - rowOut[j] = ''; +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - 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; - } +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; - rowOut[j] = subplotId; - axisMap[xId] = j; - axisMap[yId] = i; - } - } - } - } - else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); - } +var _$es6Promise_16 = { exports: {} }; +(function (process,global){ +/*! + * @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 + */ - var anchors = gridOut._anchors = {}; - var reversed = gridOut.roworder === 'top to bottom'; +(function (global, factory) { + typeof _$es6Promise_16.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_16.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; - for(var axisId in axisMap) { - var axLetter = axisId.charAt(0); - var side = gridOut[axLetter + 'side']; +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} - var i0, inc, iFinal; +function isFunction(x) { + return typeof x === 'function'; +} - 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; - } - } - } - } - } +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; } -function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { - var out = new Array(len); - var i; +var isArray = _isArray; - function fillOneAxis(i, axisId) { - if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) { - out[i] = axisId; - axisMap[axisId] = i; - } - else out[i] = ''; - } +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; - 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)); - } +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(); } + } +}; - return out; +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; } -var _$grid_97 = { - moduleType: 'component', - name: 'grid', +function setAsap(asapFn) { + asap = asapFn; +} - schema: { - layout: {grid: gridAttrs} - }, +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]'; - layoutAttributes: gridAttrs, - sizeDefaults: sizeDefaults, - contentDefaults: contentDefaults -}; +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// 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); + }; +} -'use strict'; +// vertx +function useVertxTimer() { + return function () { + vertxNext(flush); + }; +} -/* removed: var _$constants_218 = require('../../plots/cartesian/constants'); */; +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; + }; +} -var _$attributes_98 = { - _isLinkedToArray: 'image', +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} - visible: { - valType: 'boolean', - - dflt: true, - editType: 'arraydraw', - - }, +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); + }; +} - source: { - valType: 'string', - - editType: 'arraydraw', - - }, +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, + callback(arg); - sizex: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, + queue[i] = undefined; + queue[i + 1] = undefined; + } - sizey: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, + len = 0; +} - sizing: { - valType: 'enumerated', - values: ['fill', 'contain', 'stretch'], - dflt: 'contain', - - editType: 'arraydraw', - - }, +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} - opacity: { - valType: 'number', - - min: 0, - max: 1, - dflt: 1, - editType: 'arraydraw', - - }, +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 && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} - x: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, +function then(onFulfillment, onRejection) { + var _arguments = arguments; - y: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, + var parent = this; - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - editType: 'arraydraw', - - }, + var child = new this.constructor(noop); - yanchor: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'top', - - editType: 'arraydraw', - - }, + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_218.idRegex.x.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, + var _state = parent._state; - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_218.idRegex.y.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; + 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; +} /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `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); + }); -'use strict'; + promise.then(function(value){ + // value === 1 + }); + ``` -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_194 = require('../../lib/to_log_range'); */; + Instead of writing the above, your code now simply becomes the following: -/* - * convertCoords: when converting an axis between log and linear - * you need to alter any images on that axis to keep them - * pointing at the same data point. - * In v2.0 this will become obsolete (or perhaps size will still need conversion?) - * we convert size by declaring that the maximum extent *in data units* should be - * the same, assuming the image is anchored by its center (could remove that restriction - * if we think it's important) even though the actual left and right values will not be - * quite the same since the scale becomes nonlinear (and central anchor means the pixel - * center of the image, not the data units center) - * - * gd: the plot div - * ax: the axis being changed - * newType: the type it's getting - * doExtra: function(attr, val) from inside relayout that sets the attribute. - * Use this to make the changes as it's aware if any other changes in the - * same relayout call should override this conversion. - */ -var _$convertCoords_99 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; - - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); + ```javascript + let promise = Promise.resolve(1); - if(!(toLog || fromLog)) return; + promise.then(function(value){ + // value === 1 + }); + ``` - var images = gd._fullLayout.images, - axLetter = ax._id.charAt(0), - image, - attrPrefix; + @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; - for(var i = 0; i < images.length; i++) { - image = images[i]; - attrPrefix = 'images[' + i + '].'; + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } - if(image[axLetter + 'ref'] === ax._id) { - var currentPos = image[axLetter], - currentSize = image['size' + axLetter], - newPos = null, - newSize = null; + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} - if(toLog) { - newPos = _$toLogRange_194(currentPos, ax.range); +var PROMISE_ID = Math.random().toString(36).substring(16); - // this is the inverse of the conversion we do in fromLog below - // so that the conversion is reversible (notice the fromLog conversion - // is like sinh, and this one looks like arcsinh) - var dx = currentSize / Math.pow(10, newPos) / 2; - newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; - } - else { - newPos = Math.pow(10, currentPos); - newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); - } +function noop() {} - // if conversion failed, delete the value so it can get a default later on - if(!_$fastIsnumeric_18(newPos)) { - newPos = null; - newSize = null; - } - else if(!_$fastIsnumeric_18(newSize)) newSize = null; +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; - doExtra(attrPrefix + axLetter, newPos); - doExtra(attrPrefix + 'size' + axLetter, newSize); - } - } -}; +var GET_THEN_ERROR = new ErrorObject(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} -'use strict'; +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_209 = require('../../plots/array_container_defaults'); */; +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} -/* removed: var _$attributes_98 = require('./attributes'); */; -var name = 'images'; +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} -var _$supplyLayoutDefaults_100 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: name, - handleItemDefaults: imageDefaults - }; +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; - _$handleArrayContainerDefaults_209(layoutIn, layoutOut, opts); -}; + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} -function imageDefaults(imageIn, imageOut, fullLayout) { +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 coerce(attr, dflt) { - return _$lib_171.coerce(imageIn, imageOut, _$attributes_98, attr, dflt); +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); } + } +} - var source = coerce('source'); - var visible = coerce('visible', !!source); - - if(!visible) return imageOut; +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} - coerce('layer'); - coerce('xanchor'); - coerce('yanchor'); - coerce('sizex'); - coerce('sizey'); - coerce('sizing'); - coerce('opacity'); +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } - var gdMock = { _fullLayout: fullLayout }, - axLetters = ['x', 'y']; + publish(promise); +} - for(var i = 0; i < 2; i++) { - // 'paper' is the fallback axref - var axLetter = axLetters[i], - axRef = _$axes_213.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } - _$axes_213.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); - } + promise._result = value; + promise._state = FULFILLED; - return imageOut; + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; -'use strict'; + asap(publishRejection, promise); +} -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; -var _$draw_101 = function draw(gd) { - var fullLayout = gd._fullLayout, - imageDataAbove = [], - imageDataSubplot = {}, - imageDataBelow = [], - subplot, - i; + parent._onerror = null; - // Sort into top, subplot, and bottom layers - for(i = 0; i < fullLayout.images.length; i++) { - var img = fullLayout.images[i]; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; - if(img.visible) { - if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { - subplot = img.xref + img.yref; + if (length === 0 && parent._state) { + asap(publish, parent); + } +} - var plotinfo = fullLayout._plots[subplot]; +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; - if(!plotinfo) { - // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the image to an x / y axis combination - // that doesn't have any data on it (and layer is below) - imageDataBelow.push(img); - continue; - } + if (subscribers.length === 0) { + return; + } - if(plotinfo.mainplot) { - subplot = plotinfo.mainplot.id; - } + var child = undefined, + callback = undefined, + detail = promise._result; - if(!imageDataSubplot[subplot]) { - imageDataSubplot[subplot] = []; - } - imageDataSubplot[subplot].push(img); - } else if(img.layer === 'above') { - imageDataAbove.push(img); - } else { - imageDataBelow.push(img); - } - } - } + 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); + } + } - var anchors = { - x: { - left: { sizing: 'xMin', offset: 0 }, - center: { sizing: 'xMid', offset: -1 / 2 }, - right: { sizing: 'xMax', offset: -1 } - }, - y: { - top: { sizing: 'YMin', offset: 0 }, - middle: { sizing: 'YMid', offset: -1 / 2 }, - bottom: { sizing: 'YMax', offset: -1 } - } - }; + promise._subscribers.length = 0; +} +function ErrorObject() { + this.error = null; +} - // Images must be converted to dataURL's for exporting. - function setImage(d) { - var thisImage = _$d3_15.select(this); +var TRY_CATCH_ERROR = new ErrorObject(); - if(this.img && this.img.src === d.source) { - return; - } +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} - thisImage.attr('xmlns', _$xmlns_namespaces_156.svg); +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; - var imagePromise = new Promise(function(resolve) { + if (hasCallback) { + value = tryCatch(callback, detail); - var img = new Image(); - this.img = img; + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } - // If not set, a `tainted canvas` error is thrown - img.setAttribute('crossOrigin', 'anonymous'); - img.onerror = errorHandler; - img.onload = function() { - var canvas = document.createElement('canvas'); - canvas.width = this.width; - canvas.height = this.height; + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } - var ctx = canvas.getContext('2d'); - ctx.drawImage(this, 0, 0); + 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); + } +} - var dataURL = canvas.toDataURL('image/png'); +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} - thisImage.attr('xlink:href', dataURL); +var id = 0; +function nextId() { + return id++; +} - // resolve promise in onload handler instead of on 'load' to support IE11 - // see https://github.com/plotly/plotly.js/issues/1685 - // for more details - resolve(); - }; +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); - thisImage.on('error', errorHandler); + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - img.src = d.source; + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; - function errorHandler() { - thisImage.remove(); - resolve(); - } - }.bind(this)); + this._result = new Array(this.length); - gd._promises.push(imagePromise); + 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 applyAttributes(d) { - var thisImage = _$d3_15.select(this); - - // Axes if specified - var xa = _$axes_213.getFromId(gd, d.xref), - ya = _$axes_213.getFromId(gd, d.yref); - - var size = fullLayout._size, - width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, - height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; - // Offsets for anchor positioning - var xOffset = width * anchors.x[d.xanchor].offset, - yOffset = height * anchors.y[d.yanchor].offset; +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; - var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; - // Final positions - var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, - yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + if (resolve$$ === resolve) { + var _then = getThen(entry); - // Construct the proper aspectRatio attribute - switch(d.sizing) { - case 'fill': - sizing += ' slice'; - break; + 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); + } +}; - case 'stretch': - sizing = 'none'; - break; - } +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; - thisImage.attr({ - x: xPos, - y: yPos, - width: width, - height: height, - preserveAspectRatio: sizing, - opacity: d.opacity - }); + if (promise._state === PENDING) { + this._remaining--; + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } - // Set proper clipping on images - var xId = xa ? xa._id : '', - yId = ya ? ya._id : '', - clipAxes = xId + yId; + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; - thisImage.call(_$drawing_76.setClipUrl, clipAxes ? - ('clip' + fullLayout._uid + clipAxes) : - null - ); - } +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; - var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') - .data(imageDataBelow), - imagesAbove = fullLayout._imageUpperLayer.selectAll('image') - .data(imageDataAbove); + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); +}; - imagesBelow.enter().append('image'); - imagesAbove.enter().append('image'); +/** + `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. - imagesBelow.exit().remove(); - imagesAbove.exit().remove(); + Example: - imagesBelow.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - imagesAbove.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; - var allSubplots = Object.keys(fullLayout._plots); - for(i = 0; i < allSubplots.length; i++) { - subplot = allSubplots[i]; - var subplotObj = fullLayout._plots[subplot]; + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` - // filter out overlaid plots (which havd their images on the main plot) - // and gl2d plots (which don't support below images, at least not yet) - if(!subplotObj.imagelayer) continue; + 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: - var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') - // even if there are no images on this subplot, we need to run - // enter and exit in case there were previously - .data(imageDataSubplot[subplot] || []); + Example: - imagesOnSubplot.enter().append('image'); - imagesOnSubplot.exit().remove(); + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; - imagesOnSubplot.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - } -}; + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. + @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; +} -'use strict'; +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. -var _$images_102 = { - moduleType: 'component', - name: 'images', + Example: - layoutAttributes: _$attributes_98, - supplyLayoutDefaults: _$supplyLayoutDefaults_100, - includeBasePlot: _$makeIncludeComponents_223('images'), + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - draw: _$draw_101, + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); - convertCoords: _$convertCoords_99 -}; + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `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: -'use strict'; + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_50 = require('../color/attributes'); */; + 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 + }); + ``` -var _$attributes_104 = { - bgcolor: { - valType: 'color', - - editType: 'legend', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'legend', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'legend', - - }, - font: _$font_attributes_240({ - editType: 'legend', - - }), - orientation: { - valType: 'enumerated', - values: ['v', 'h'], - dflt: 'v', - - editType: 'legend', - - }, - traceorder: { - valType: 'flaglist', - flags: ['reversed', 'grouped'], - extras: ['normal'], - - editType: 'legend', - - }, - tracegroupgap: { - valType: 'number', - min: 0, - dflt: 10, - - editType: 'legend', - - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 1.02, - - editType: 'legend', - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - - editType: 'legend', - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, - - editType: 'legend', - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', - - editType: 'legend', - - }, - editType: 'legend' -}; + An example real-world use case is implementing timeouts: -var _$helpers_110 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. + ```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); + } + }); + } +} -'use strict'; +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: -_$helpers_110.legendGetsTrace = function legendGetsTrace(trace) { - // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? - // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); - // Note that we explicitly include showlegend: false, so a trace that *could* be - // in the legend but is not shown still counts toward the two traces you need to - // ensure the legend is shown by default, because this can still help disambiguate. - return trace.visible && (trace.showlegend !== undefined); -}; + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` -_$helpers_110.isGrouped = function isGrouped(legendLayout) { - return (legendLayout.traceorder || '').indexOf('grouped') !== -1; -}; + Instead of writing the above, your code now simply becomes the following: -_$helpers_110.isVertical = function isVertical(legendLayout) { - return legendLayout.orientation !== 'h'; -}; + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); -_$helpers_110.isReversed = function isReversed(legendLayout) { - return (legendLayout.traceorder || '').indexOf('reversed') !== -1; -}; + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. + @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'); +} -'use strict'; +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/** + 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. -/* removed: var _$attributes_104 = require('./attributes'); */; -/* removed: var _$layout_attributes_244 = require('../../plots/layout_attributes'); */; -/* removed: var _$helpers_110 = require('./helpers'); */; + 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. -var _$legendDefaults_106 = function legendDefaults(layoutIn, layoutOut, fullData) { - var containerIn = layoutIn.legend || {}; - var containerOut = {}; + A promise can be in one of three states: pending, fulfilled, or rejected. - var visibleTraces = 0; - var defaultOrder = 'normal'; + 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. - var defaultX, defaultY, defaultXAnchor, defaultYAnchor; + 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. - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(_$helpers_110.legendGetsTrace(trace)) { - visibleTraces++; - // always show the legend by default if there's a pie - if(_$registry_261.traceIs(trace, 'pie')) visibleTraces++; - } + Basic Usage: + ------------ - if((_$registry_261.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || - ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { - defaultOrder = _$helpers_110.isGrouped({traceorder: defaultOrder}) ? - 'grouped+reversed' : 'reversed'; - } + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); - if(trace.legendgroup !== undefined && trace.legendgroup !== '') { - defaultOrder = _$helpers_110.isReversed({traceorder: defaultOrder}) ? - 'reversed+grouped' : 'grouped'; - } - } + // on failure + reject(reason); + }); - function coerce(attr, dflt) { - return _$lib_171.coerce(containerIn, containerOut, _$attributes_104, attr, dflt); - } + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` - var showLegend = _$lib_171.coerce(layoutIn, layoutOut, - _$layout_attributes_244, 'showlegend', visibleTraces > 1); + Advanced Usage: + --------------- - if(showLegend === false) return; + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. - layoutOut.legend = containerOut; + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - _$lib_171.coerceFont(coerce, 'font', layoutOut.font); + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); - coerce('orientation'); - if(containerOut.orientation === 'h') { - var xaxis = layoutIn.xaxis; - if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = 1.1; - defaultYAnchor = 'bottom'; - } - else { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = -0.1; - defaultYAnchor = 'top'; + 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 + ']')); + } } - } + }; + }); + } - coerce('traceorder', defaultOrder); - if(_$helpers_110.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` - coerce('x', defaultX); - coerce('xanchor', defaultXAnchor); - coerce('y', defaultY); - coerce('yanchor', defaultYAnchor); - _$lib_171.noneOrAll(containerIn, containerOut, ['x', 'y']); -}; + Unlike callbacks, promises are great composable primitives. -var _$anchor_utils_103 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. + ```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(); + } +} -'use strict'; +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, -/** - * 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. - */ + /** + 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, -_$anchor_utils_103.isRightAnchor = function isRightAnchor(opts) { - return ( - opts.xanchor === 'right' || - (opts.xanchor === 'auto' && opts.x >= 2 / 3) - ); + /** + `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); + } }; -_$anchor_utils_103.isCenterAnchor = function isCenterAnchor(opts) { - return ( - opts.xanchor === 'center' || - (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) - ); -}; +function polyfill() { + var local = undefined; -_$anchor_utils_103.isBottomAnchor = function isBottomAnchor(opts) { - return ( - opts.yanchor === 'bottom' || - (opts.yanchor === 'auto' && opts.y <= 1 / 3) - ); -}; + 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'); + } + } -_$anchor_utils_103.isMiddleAnchor = function isMiddleAnchor(opts) { - return ( - opts.yanchor === 'middle' || - (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) - ); -}; + var P = local.Promise; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } -'use strict'; + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } -var _$constants_105 = { - scrollBarWidth: 6, - scrollBarMinHeight: 20, - scrollBarColor: '#808BA4', - scrollBarMargin: 4 -}; + local.Promise = Promise; +} + +polyfill(); +// Strange compat.. +Promise.polyfill = polyfill; +Promise.Promise = Promise; +return Promise; + +}))); +//# sourceMappingURL=es6-promise.map +}).call(this,_$browser_32,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +_$es6Promise_16 = _$es6Promise_16.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48033,101 +47779,67 @@ var _$constants_105 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$helpers_110 = require('./helpers'); */; - - -var _$getLegendData_108 = function getLegendData(calcdata, opts) { - var lgroupToTraces = {}, - lgroups = [], - hasOneNonBlankGroup = false, - slicesShown = {}, - lgroupi = 0; - - var i, j; - - function addOneItem(legendGroup, legendItem) { - // each '' legend group is treated as a separate group - if(legendGroup === '' || !_$helpers_110.isGrouped(opts)) { - var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? - - lgroups.push(uniqueGroup); - lgroupToTraces[uniqueGroup] = [[legendItem]]; - lgroupi++; - } - else if(lgroups.indexOf(legendGroup) === -1) { - lgroups.push(legendGroup); - hasOneNonBlankGroup = true; - lgroupToTraces[legendGroup] = [[legendItem]]; - } - else lgroupToTraces[legendGroup].push([legendItem]); - } - - // build an { legendgroup: [cd0, cd0], ... } object - for(i = 0; i < calcdata.length; i++) { - var cd = calcdata[i], - cd0 = cd[0], - trace = cd0.trace, - lgroup = trace.legendgroup; - - if(!_$helpers_110.legendGetsTrace(trace) || !trace.showlegend) continue; - - if(_$registry_261.traceIs(trace, 'pie')) { - if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; - - for(j = 0; j < cd.length; j++) { - var labelj = cd[j].label; - - if(!slicesShown[lgroup][labelj]) { - addOneItem(lgroup, { - label: labelj, - color: cd[j].color, - i: cd[j].i, - trace: trace - }); - - slicesShown[lgroup][labelj] = true; - } - } - } - - else addOneItem(lgroup, cd0); - } - - // won't draw a legend in this case - if(!lgroups.length) return []; - - // rearrange lgroupToTraces into a d3-friendly array of arrays - var lgroupsLength = lgroups.length, - ltraces, - legendData; - - if(hasOneNonBlankGroup && _$helpers_110.isGrouped(opts)) { - legendData = new Array(lgroupsLength); - - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]]; - legendData[i] = _$helpers_110.isReversed(opts) ? ltraces.reverse() : ltraces; - } - } - else { - // collapse all groups into one if all groups are blank - legendData = [new Array(lgroupsLength)]; +/** + * All paths are tuned for maximum scalability of the arrowhead, + * ie throughout arrowwidth=0.3..3 the head is joined smoothly + * to the line, with the line coming from the left and ending at (0, 0). + * + * `backoff` is the distance to move the arrowhead and the end of the line, + * in order that the arrowhead points to the desired place, either at + * the tip of the arrow or (in the case of circle or square) + * the center of the symbol. + * + * `noRotate`, if truthy, says that this arrowhead should not rotate with the + * arrow. That's the case for squares, which should always be straight, and + * circles, for which it's irrelevant. + */ - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]][0]; - legendData[0][_$helpers_110.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; - } - lgroupsLength = 1; +var _$arrow_paths_35 = [ + // no arrow + { + path: '', + backoff: 0 + }, + // wide with flat back + { + path: 'M-2.4,-3V3L0.6,0Z', + backoff: 0.6 + }, + // narrower with flat back + { + path: 'M-3.7,-2.5V2.5L1.3,0Z', + backoff: 1.3 + }, + // barbed + { + path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', + backoff: 1.55 + }, + // wide line-drawn + { + path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', + backoff: 1.6 + }, + // narrower line-drawn + { + path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', + backoff: 2 + }, + // circle + { + path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', + backoff: 0, + noRotate: true + }, + // square + { + path: 'M2,2V-2H-2V2Z', + backoff: 0, + noRotate: true } - - // needed in repositionLegend - opts._lgroupsLength = lgroupsLength; - return legendData; -}; +]; /** * Copyright 2012-2018, Plotly, Inc. @@ -48139,220 +47851,2785 @@ var _$getLegendData_108 = function getLegendData(calcdata, opts) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$registry_261 = require('../../registry'); */; - -var SHOWISOLATETIP = true; - -var _$handleClick_109 = function handleClick(g, gd, numClicks) { - if(gd._dragged || gd._editing) return; - - var hiddenSlices = gd._fullLayout.hiddenlabels ? - gd._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; +/* removed: var _$arrow_paths_35 = require('./arrow_paths'); */; +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +/* removed: var _$constants_219 = require('../../plots/cartesian/constants'); */; - return attrIndex; - } - function setVisibility(fullTrace, visibility) { - var fullInput = fullTrace._fullInput; - if(_$registry_261.hasTransform(fullInput, 'groupby')) { - var kcont = carrs[fullInput.index]; - if(!kcont) { - var groupbyIndices = _$registry_261.getTransformIndices(fullInput, 'groupby'); - var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_171.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); - carrs[fullInput.index] = kcont; - } +var _$attributes_36 = { + _isLinkedToArray: 'annotation', - var curState = kcont.get(fullTrace._group); + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calcIfAutorange+arraydraw', + + }, - // 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; + text: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, + textangle: { + valType: 'angle', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + font: _$font_attributes_240({ + editType: 'calcIfAutorange+arraydraw', + colorEditType: 'arraydraw', + + }), + width: { + valType: 'number', + min: 1, + dflt: null, + + editType: 'calcIfAutorange+arraydraw', + + }, + height: { + valType: 'number', + min: 1, + dflt: null, + + editType: 'calcIfAutorange+arraydraw', + + }, + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + + }, + align: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'center', + + editType: 'arraydraw', + + }, + valign: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'middle', + + editType: 'arraydraw', + + }, + bgcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + bordercolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + borderpad: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', + + }, + // arrow + showarrow: { + valType: 'boolean', + dflt: true, + + editType: 'calcIfAutorange+arraydraw', + + }, + arrowcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + arrowhead: { + valType: 'integer', + min: 0, + max: _$arrow_paths_35.length, + dflt: 1, + + editType: 'arraydraw', + + }, + startarrowhead: { + valType: 'integer', + min: 0, + max: _$arrow_paths_35.length, + dflt: 1, + + editType: 'arraydraw', + + }, + arrowside: { + valType: 'flaglist', + flags: ['end', 'start'], + extras: ['none'], + dflt: 'end', + + editType: 'arraydraw', + + }, + arrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', + + }, + startarrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', + + }, + arrowwidth: { + valType: 'number', + min: 0.1, + + editType: 'calcIfAutorange+arraydraw', + + }, + standoff: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + startstandoff: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + ax: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + ay: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + axref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_219.idRegex.x.toString() + ], + + editType: 'calc', + + }, + ayref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_219.idRegex.y.toString() + ], + + editType: 'calc', + + }, + // positioning + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_219.idRegex.x.toString() + ], + + editType: 'calc', + + }, + x: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + xshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_219.idRegex.y.toString() + ], + + editType: 'calc', + + }, + y: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + yshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + clicktoshow: { + valType: 'enumerated', + values: [false, 'onoff', 'onout'], + dflt: false, + + editType: 'arraydraw', + + }, + xclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + yclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + hovertext: { + valType: 'string', + + editType: 'arraydraw', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + bordercolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + font: _$font_attributes_240({ + editType: 'arraydraw', + + }), + editType: 'arraydraw' + }, + captureevents: { + valType: 'boolean', + + editType: 'arraydraw', + + }, + editType: 'calc', + + _deprecated: { + ref: { + valType: 'string', + + editType: 'calc', + + } + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_15 = require('d3'); */; + +/* removed: var _$color_51 = require('../color'); */; + +/* removed: var _$arrow_paths_35 = require('./arrow_paths'); */; + +/** + * 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. + */ +var _$drawArrowHead_43 = function drawArrowHead(el3, ends, options) { + var el = el3.node(); + var headStyle = _$arrow_paths_35[options.arrowhead || 0]; + var startHeadStyle = _$arrow_paths_35[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), + 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), + 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 + 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_15.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_51.rgb(options.arrowcolor), + 'stroke-width': 0 + }); + } + + if(doStart) drawhead(startHeadStyle, start, startRot, startScale); + if(doEnd) drawhead(headStyle, end, endRot, scale); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$d3_15 = require('d3'); */; + +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$fx_93 = require('../fx'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_191 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$drawArrowHead_43 = require('./draw_arrow_head'); */; + +// Annotations are stored in gd.layout.annotations, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one + +var _$draw_42 = { + draw: __draw_42, + drawOne: drawOne, + drawRaw: drawRaw +}; + +/* + * draw: draw all annotations without any new modifications + */ +function __draw_42(gd) { + var fullLayout = gd._fullLayout; + + fullLayout._infolayer.selectAll('.annotation').remove(); + + for(var i = 0; i < fullLayout.annotations.length; i++) { + if(fullLayout.annotations[i].visible) { + drawOne(gd, i); + } + } + + return _$plots_246.previousPromises(gd); +} + +/* + * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications + * + * index (int): the annotation to draw + */ +function drawOne(gd, index) { + var fullLayout = gd._fullLayout; + var options = fullLayout.annotations[index] || {}; + var xa = _$axes_214.getFromId(gd, options.xref); + var ya = _$axes_214.getFromId(gd, options.yref); + + drawRaw(gd, options, index, false, xa, ya); +} + +/** + * drawRaw: draw a single annotation, potentially with modifications + * + * @param {DOM element} gd + * @param {object} options : this annotation's fullLayout options + * @param {integer} index : index in 'annotations' container of the annotation to draw + * @param {string} subplotId : id of the annotation's subplot + * - use false for 2d (i.e. cartesian or paper-ref) annotations + * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px + * @param {object | undefined} ya : ... y-axis + */ +function drawRaw(gd, options, index, subplotId, xa, ya) { + var fullLayout = gd._fullLayout; + var gs = gd._fullLayout._size; + var edits = gd._context.edits; + + var className; + var annbase; + + if(subplotId) { + className = 'annotation-' + subplotId; + annbase = subplotId + '.annotations[' + index + ']'; + } else { + className = 'annotation'; + annbase = 'annotations[' + index + ']'; + } + + // remove the existing annotation if there is one + fullLayout._infolayer + .selectAll('.' + className + '[data-index="' + index + '"]') + .remove(); + + var annClipID = 'clip' + fullLayout._uid + '_ann' + index; + + // this annotation is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!options._input || options.visible === false) { + _$d3_15.selectAll('#' + annClipID).remove(); + return; + } + + // calculated pixel positions + // x & y each will get text, head, and tail as appropriate + var annPosPx = {x: {}, y: {}}, + textangle = +options.textangle || 0; + + // create the components + // made a single group to contain all, so opacity can work right + // with border/arrow together this could handle a whole bunch of + // cleanup at this point, but works for now + var annGroup = fullLayout._infolayer.append('g') + .classed(className, true) + .attr('data-index', String(index)) + .style('opacity', options.opacity); + + // another group for text+background so that they can rotate together + var annTextGroup = annGroup.append('g') + .classed('annotation-text-g', true); + + var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; + var textEvents = options.captureevents || edits.annotationText || editTextPosition; + + var annTextGroupInner = annTextGroup.append('g') + .style('pointer-events', textEvents ? 'all' : null) + .call(_$setCursor_191, 'default') + .on('click', function() { + gd._dragging = false; + + var eventData = { + index: index, + annotation: options._input, + fullAnnotation: options, + event: _$d3_15.event + }; + + if(subplotId) { + eventData.subplotId = subplotId; + } + + gd.emit('plotly_clickannotation', eventData); + }); + + if(options.hovertext) { + annTextGroupInner + .on('mouseover', function() { + var hoverOptions = options.hoverlabel; + var hoverFont = hoverOptions.font; + var bBox = this.getBoundingClientRect(); + var bBoxRef = gd.getBoundingClientRect(); + + _$fx_93.loneHover({ + x0: bBox.left - bBoxRef.left, + x1: bBox.right - bBoxRef.left, + y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, + text: options.hovertext, + color: hoverOptions.bgcolor, + borderColor: hoverOptions.bordercolor, + fontFamily: hoverFont.family, + fontSize: hoverFont.size, + fontColor: hoverFont.color + }, { + container: fullLayout._hoverlayer.node(), + outerContainer: fullLayout._paper.node(), + gd: gd + }); + }) + .on('mouseout', function() { + _$fx_93.loneUnhover(fullLayout._hoverlayer.node()); + }); + } + + var borderwidth = options.borderwidth, + borderpad = options.borderpad, + borderfull = borderwidth + borderpad; + + var annTextBG = annTextGroupInner.append('rect') + .attr('class', 'bg') + .style('stroke-width', borderwidth + 'px') + .call(_$color_51.stroke, options.bordercolor) + .call(_$color_51.fill, options.bgcolor); + + var isSizeConstrained = options.width || options.height; + + var annTextClip = fullLayout._topclips + .selectAll('#' + annClipID) + .data(isSizeConstrained ? [0] : []); + + annTextClip.enter().append('clipPath') + .classed('annclip', true) + .attr('id', annClipID) + .append('rect'); + annTextClip.exit().remove(); + + var font = options.font; + + var annText = annTextGroupInner.append('text') + .classed('annotation-text', true) + .text(options.text); + + function textLayout(s) { + s.call(_$drawing_76.font, font) + .attr({ + 'text-anchor': { + left: 'start', + right: 'end' + }[options.align] || 'middle' + }); + + _$svg_text_utils_193.convertToTspans(s, gd, drawGraphicalElements); + return s; + } + + function drawGraphicalElements() { + // if the text has *only* a link, make the whole box into a link + var anchor3 = annText.selectAll('a'); + if(anchor3.size() === 1 && anchor3.text() === annText.text()) { + var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ + 'xlink:xlink:href': anchor3.attr('xlink:href'), + 'xlink:xlink:show': anchor3.attr('xlink:show') + }) + .style({cursor: 'pointer'}); + + wholeLink.node().appendChild(annTextBG.node()); + } + + var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); + var hasMathjax = !mathjaxGroup.empty(); + var anntextBB = _$drawing_76.bBox( + (hasMathjax ? mathjaxGroup : annText).node()); + var textWidth = anntextBB.width; + var textHeight = anntextBB.height; + var annWidth = options.width || textWidth; + var annHeight = options.height || textHeight; + var outerWidth = Math.round(annWidth + 2 * borderfull); + var outerHeight = Math.round(annHeight + 2 * borderfull); + + + // save size in the annotation object for use by autoscale + options._w = annWidth; + options._h = annHeight; + + function shiftFraction(v, anchor) { + if(anchor === 'auto') { + if(v < 1 / 3) anchor = 'left'; + else if(v > 2 / 3) anchor = 'right'; + else anchor = 'center'; + } + return { + center: 0, + middle: 0, + left: 0.5, + bottom: -0.5, + right: -0.5, + top: 0.5 + }[anchor]; + } + + var annotationIsOffscreen = false; + var letters = ['x', 'y']; + + for(var i = 0; i < letters.length; i++) { + var axLetter = letters[i], + axRef = options[axLetter + 'ref'] || axLetter, + tailRef = options['a' + axLetter + 'ref'], + ax = {x: xa, y: ya}[axLetter], + dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, + // note that these two can be either positive or negative + annSizeFromWidth = outerWidth * Math.cos(dimAngle), + annSizeFromHeight = outerHeight * Math.sin(dimAngle), + // but this one is the positive total size + annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), + anchor = options[axLetter + 'anchor'], + overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), + posPx = annPosPx[axLetter], + basePx, + textPadShift, + alignPosition, + autoAlignFraction, + textShift; + + /* + * calculate the *primary* pixel position + * which is the arrowhead if there is one, + * otherwise the text anchor point + */ + if(ax) { + /* + * hide the annotation if it's pointing outside the visible plot + * as long as the axis isn't autoranged - then we need to draw it + * anyway to get its bounding box. When we're dragging, an axis can + * still look autoranged even though it won't be when the drag finishes. + */ + var posFraction = ax.r2fraction(options[axLetter]); + if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { + if(tailRef === axRef) { + posFraction = ax.r2fraction(options['a' + axLetter]); + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + } + } + else { + annotationIsOffscreen = true; + } + + if(annotationIsOffscreen) continue; + } + 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_172.constrain(posPx.head, 1, maxPx - 1); + } + if(tailRef === 'pixel') { + var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), + 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_76.setClipUrl, isSizeConstrained ? annClipID : null); + } + else { + var texty = borderfull + yShift - anntextBB.top; + var textx = borderfull + xShift - anntextBB.left; + + annText.call(_$svg_text_utils_193.positionText, textx, texty) + .call(_$drawing_76.setClipUrl, isSizeConstrained ? annClipID : null); + } + + annTextClip.select('rect').call(_$drawing_76.setRect, borderfull, borderfull, + annWidth, annHeight); + + annTextBG.call(_$drawing_76.setRect, borderwidth / 2, borderwidth / 2, + outerWidth - borderwidth, outerHeight - borderwidth); + + annTextGroupInner.call(_$drawing_76.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, + headY = annPosPx.y.head, + tailX = annPosPx.x.tail + dx, + tailY = annPosPx.y.tail + dy, + textX = annPosPx.x.text + dx, + 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 + transform = _$lib_172.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_172.apply2DTransform(transform), + applyTransform2 = _$lib_172.apply2DTransform2(transform), + + // calculate and transform bounding box + width = +annTextBG.attr('width'), + height = +annTextBG.attr('height'), + xLeft = textX - 0.5 * width, + xRight = xLeft + width, + yTop = textY - 0.5 * height, + yBottom = yTop + height, + 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_172.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_172.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, + arrowColor = options.arrowcolor, + arrowSide = options.arrowside; + + var arrowGroup = annGroup.append('g') + .style({opacity: _$color_51.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_51.stroke, _$color_51.rgb(arrowColor)); + + _$drawArrowHead_43(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) + .attr({ + d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), + transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' + }) + .style('stroke-width', (strokewidth + 6) + 'px') + .call(_$color_51.stroke, 'rgba(0,0,0,0)') + .call(_$color_51.fill, 'rgba(0,0,0,0)'); + + var update, + annx0, + anny0; + + // dragger for the arrow & head: translates the whole thing + // (head/tail/text) all together + _$dragelement_73.init({ + element: arrowDrag.node(), + gd: gd, + prepFn: function() { + var pos = _$drawing_76.getTranslate(annTextGroupInner); + + annx0 = pos.x; + anny0 = pos.y; + update = {}; + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + }, + moveFn: function(dx, dy) { + var annxy0 = applyTransform(annx0, anny0), + xcenter = annxy0[0] + dx, + ycenter = annxy0[1] + dy; + annTextGroupInner.call(_$drawing_76.setTranslate, xcenter, ycenter); + + update[annbase + '.x'] = xa ? + xa.p2r(xa.r2p(options.x) + dx) : + (options.x + (dx / gs.w)); + update[annbase + '.y'] = ya ? + ya.p2r(ya.r2p(options.y) + dy) : + (options.y - (dy / gs.h)); + + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } + + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } + + arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); + annTextGroup.attr({ + transform: 'rotate(' + textangle + ',' + + xcenter + ',' + ycenter + ')' + }); + }, + doneFn: function() { + _$registry_262.call('relayout', gd, update); + 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 update, + baseTextTransform; + + // dragger for the textbox: if there's an arrow, just drag the + // textbox and tail, leave the head untouched + _$dragelement_73.init({ + element: annTextGroupInner.node(), + gd: gd, + prepFn: function() { + baseTextTransform = annTextGroup.attr('transform'); + update = {}; + }, + moveFn: function(dx, dy) { + var csr = 'pointer'; + if(options.showarrow) { + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } else { + update[annbase + '.ax'] = options.ax + dx; + } + + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } else { + update[annbase + '.ay'] = options.ay + dy; + } + + drawArrow(dx, dy); + } + else if(!subplotId) { + if(xa) { + update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); + + } else { + var widthFraction = options._xsize / gs.w, + xLeft = options.x + (options._xshift - options.xshift) / gs.w - + widthFraction / 2; + + update[annbase + '.x'] = _$dragelement_73.align(xLeft + dx / gs.w, + widthFraction, 0, 1, options.xanchor); + } + + if(ya) { + update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); + } else { + var heightFraction = options._ysize / gs.h, + yBottom = options.y - (options._yshift + options.yshift) / gs.h - + heightFraction / 2; + + update[annbase + '.y'] = _$dragelement_73.align(yBottom - dy / gs.h, + heightFraction, 0, 1, options.yanchor); + } + if(!xa || !ya) { + csr = _$dragelement_73.getCursor( + xa ? 0.5 : update[annbase + '.x'], + ya ? 0.5 : update[annbase + '.y'], + options.xanchor, options.yanchor + ); + } + } + else return; + + annTextGroup.attr({ + transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform + }); + + _$setCursor_191(annTextGroupInner, csr); + }, + doneFn: function() { + _$setCursor_191(annTextGroupInner); + _$registry_262.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } + } + + if(edits.annotationText) { + annText.call(_$svg_text_utils_193.makeEditable, {delegate: annTextGroupInner, gd: gd}) + .call(textLayout) + .on('edit', function(_text) { + options.text = _text; + this.call(textLayout); + + var update = {}; + update[annbase + '.text'] = options.text; + + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + + _$registry_262.call('relayout', gd, update); + }); + } + else annText.call(textLayout); +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; + +var __draw_37 = _$draw_42.draw; + + +var _$calcAutorange_37 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + annotationList = _$lib_172.filterVisible(fullLayout.annotations); + + if(!annotationList.length || !gd._fullData.length) return; + + var annotationAxes = {}; + annotationList.forEach(function(ann) { + annotationAxes[ann.xref] = 1; + annotationAxes[ann.yref] = 1; + }); + + for(var axId in annotationAxes) { + var ax = _$axes_214.getFromId(gd, axId); + if(ax && ax.autorange) { + return _$lib_172.syncOrAsync([ + __draw_37, + annAutorange + ], gd); + } + } +}; + +function annAutorange(gd) { + var fullLayout = gd._fullLayout; + + // find the bounding boxes for each of these annotations' + // relative to their anchor points + // use the arrow and the text bg rectangle, + // as the whole anno may include hidden text in its bbox + _$lib_172.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_214.getFromId(gd, ann.xref), + ya = _$axes_214.getFromId(gd, ann.yref), + headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, + startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; + + var headPlus, headMinus, startHeadPlus, startHeadMinus; + + if(xa && xa.autorange) { + headPlus = headSize + ann.xshift; + headMinus = headSize - ann.xshift; + startHeadPlus = startHeadSize + ann.xshift; + startHeadMinus = startHeadSize - ann.xshift; + + if(ann.axref === ann.xref) { + // expand for the arrowhead (padded by arrowhead) + _$axes_214.expand(xa, [xa.r2c(ann.x)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + // again for the textbox (padded by textbox) + _$axes_214.expand(xa, [xa.r2c(ann.ax)], { + ppadplus: Math.max(ann._xpadplus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, startHeadMinus) + }); + } + else { + startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; + startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; + _$axes_214.expand(xa, [xa.r2c(ann.x)], { + ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) + }); + } + } + + if(ya && ya.autorange) { + headPlus = headSize - ann.yshift; + headMinus = headSize + ann.yshift; + startHeadPlus = startHeadSize - ann.yshift; + startHeadMinus = startHeadSize + ann.yshift; + + if(ann.ayref === ann.yref) { + _$axes_214.expand(ya, [ya.r2c(ann.y)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + _$axes_214.expand(ya, [ya.r2c(ann.ay)], { + ppadplus: Math.max(ann._ypadplus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, startHeadMinus) + }); + } + else { + startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; + startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; + _$axes_214.expand(ya, [ya.r2c(ann.y)], { + ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) + }); + } + } + }); +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$registry_262 = require('../../registry'); */; + +var _$click_38 = { + 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), + onSet = toggleSets.on, + offSet = toggleSets.off.concat(toggleSets.explicitOff), + update = {}, + i; + + if(!(onSet.length || offSet.length)) return; + + for(i = 0; i < onSet.length; i++) { + update['annotations[' + onSet[i] + '].visible'] = true; + } + + for(i = 0; i < offSet.length; i++) { + update['annotations[' + offSet[i] + '].visible'] = false; + } + + return _$registry_262.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, + onSet = [], + offSet = [], + explicitOffSet = [], + 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); +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_195 = require('../../lib/to_log_range'); */; + +/* + * 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. + */ +var _$convertCoords_40 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; + + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); + + if(!(toLog || fromLog)) return; + + var annotations = gd._fullLayout.annotations, + axLetter = ax._id.charAt(0), + ann, + attrPrefix; + + function convert(attr) { + var currentVal = ann[attr], + newVal = null; + + if(toLog) newVal = _$toLogRange_195(currentVal, ax.range); + else newVal = Math.pow(10, currentVal); + + // if conversion failed, delete the value so it gets a default value + if(!_$fastIsnumeric_18(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); + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$color_51 = require('../color'); */; + +// defaults common to 'annotations' and 'annotations3d' +var _$handleAnnotationCommonDefaults_39 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { + coerce('opacity'); + var bgColor = coerce('bgcolor'); + + var borderColor = coerce('bordercolor'); + var borderOpacity = _$color_51.opacity(borderColor); + + coerce('borderpad'); + + var borderWidth = coerce('borderwidth'); + var showArrow = coerce('showarrow'); + + coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); + coerce('textangle'); + _$lib_172.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_51.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_51.opacity(bgColor) ? _$color_51.rgb(bgColor) : _$color_51.defaultLine) + ); + + var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || + _$color_51.contrast(hoverBG) + ); + + _$lib_172.coerceFont(coerce, 'hoverlabel.font', { + family: globalHoverLabel.font.family, + size: globalHoverLabel.font.size, + color: globalHoverLabel.font.color || hoverBorder + }); + } + + coerce('captureevents', !!hoverText); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleAnnotationCommonDefaults_39 = require('./common_defaults'); */; +/* removed: var _$attributes_36 = require('./attributes'); */; + + +var _$handleAnnotationDefaults_34 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; + + function coerce(attr, dflt) { + return _$lib_172.coerce(annIn, annOut, _$attributes_36, attr, dflt); + } + + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + var clickToShow = coerce('clicktoshow'); + + if(!(visible || clickToShow)) return annOut; + + _$handleAnnotationCommonDefaults_39(annIn, annOut, fullLayout, coerce); + + var showArrow = annOut.showarrow; + + // positioning + var axLetters = ['x', 'y'], + arrowPosDflt = [-10, -30], + gdMock = {_fullLayout: fullLayout}; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i]; + + // xref, yref + var axRef = _$axes_214.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + + // x, y + _$axes_214.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + + if(showArrow) { + var arrowPosAttr = 'a' + axLetter, + // axref, ayref + aaxRef = _$axes_214.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + + // for now the arrow can only be on the same axis or specified as pixels + // TODO: sometime it might be interesting to allow it to be on *any* axis + // but that would require updates to drawing & autorange code and maybe more + if(aaxRef !== 'pixel' && aaxRef !== axRef) { + aaxRef = annOut[arrowPosAttr] = 'pixel'; + } + + // ax, ay + var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; + _$axes_214.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + } + + // xanchor, yanchor + coerce(axLetter + 'anchor'); + + // xshift, yshift + coerce(axLetter + 'shift'); + } + + // if you have one coordinate you should have both + _$lib_172.noneOrAll(annIn, annOut, ['x', 'y']); + + // if you have one part of arrow length you should have both + if(showArrow) { + _$lib_172.noneOrAll(annIn, annOut, ['ax', 'ay']); + } + + if(clickToShow) { + var xClick = coerce('xclick'); + var yClick = coerce('yclick'); + + // put the actual click data to bind to into private attributes + // so we don't have to do this little bit of logic on every hover event + annOut._xclick = (xClick === undefined) ? + annOut.x : + _$axes_214.cleanPosition(xClick, gdMock, annOut.xref); + annOut._yclick = (yClick === undefined) ? + annOut.y : + _$axes_214.cleanPosition(yClick, gdMock, annOut.yref); + } + + return annOut; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_172 = require('../lib'); */; + +/** Convenience wrapper for making array container logic DRY and consistent + * + * @param {object} parentObjIn + * user input object where the container in question is linked + * (i.e. either a user trace object or the user layout object) + * + * @param {object} parentObjOut + * full object where the coerced container will be linked + * (i.e. either a full trace object or the full layout object) + * + * @param {object} opts + * options object: + * - name {string} + * name of the key linking the container in question + * - handleItemDefaults {function} + * defaults method to be called on each item in the array container in question + * + * Its arguments are: + * - itemIn {object} item in user layout + * - itemOut {object} item in full layout + * - parentObj {object} (as in closure) + * - opts {object} (as in closure) + * - itemOpts {object} + * - itemIsNotPlainObject {boolean} + * N.B. + * + * - opts is passed to handleItemDefaults so it can also store + * links to supplementary data (e.g. fullData for layout components) + * + */ +var _$handleArrayContainerDefaults_210 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { + var name = opts.name; + + var previousContOut = parentObjOut[name]; + + var contIn = _$lib_172.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + contOut = parentObjOut[name] = [], + i; + + for(i = 0; i < contIn.length; i++) { + var itemIn = contIn[i], + itemOut = {}, + itemOpts = {}; + + if(!_$lib_172.isPlainObject(itemIn)) { + itemOpts.itemIsNotPlainObject = true; + itemIn = {}; + } + + opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); + + itemOut._input = itemIn; + itemOut._index = i; + + contOut.push(itemOut); + } + + // in case this array gets its defaults rebuilt independent of the whole layout, + // relink the private keys just for this array. + if(_$lib_172.isArrayOrTypedArray(previousContOut)) { + var len = Math.min(previousContOut.length, contOut.length); + for(i = 0; i < len; i++) { + _$lib_172.relinkPrivateKeys(contOut[i], previousContOut[i]); + } + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$handleArrayContainerDefaults_210 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationDefaults_34 = require('./annotation_defaults'); */; + + +var _$supplyLayoutDefaults_41 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'annotations', + handleItemDefaults: _$handleAnnotationDefaults_34 + }; + + _$handleArrayContainerDefaults_210(layoutIn, layoutOut, opts); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; + +/** + * 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 + */ +var _$makeIncludeComponents_224 = function makeIncludeComponents(containerArrayName) { + return function includeComponents(layoutIn, layoutOut) { + var array = layoutIn[containerArrayName]; + if(!Array.isArray(array)) return; + + var Cartesian = _$registry_262.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_172.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_172.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); + } + } + } + }; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$draw_42 = require('./draw'); */; +/* removed: var _$click_38 = require('./click'); */; + +var _$annotations_44 = { + moduleType: 'component', + name: 'annotations', + + layoutAttributes: _$attributes_36, + supplyLayoutDefaults: _$supplyLayoutDefaults_41, + includeBasePlot: _$makeIncludeComponents_224('annotations'), + + calcAutorange: _$calcAutorange_37, + draw: _$draw_42.draw, + drawOne: _$draw_42.drawOne, + drawRaw: _$draw_42.drawRaw, + + hasClickToShow: _$click_38.hasClickToShow, + onClick: _$click_38.onClick, + + convertCoords: _$convertCoords_40 +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$attributes_36 = require('../annotations/attributes'); */; +var __overrideAll_45 = _$edit_types_199.overrideAll; + +var _$attributes_45 = __overrideAll_45({ + _isLinkedToArray: 'annotation', + + visible: _$attributes_36.visible, + x: { + valType: 'any', + + + }, + y: { + valType: 'any', + + + }, + z: { + valType: 'any', + + + }, + ax: { + valType: 'number', + + + }, + ay: { + valType: 'number', + + + }, + + xanchor: _$attributes_36.xanchor, + xshift: _$attributes_36.xshift, + yanchor: _$attributes_36.yanchor, + yshift: _$attributes_36.yshift, + + text: _$attributes_36.text, + textangle: _$attributes_36.textangle, + font: _$attributes_36.font, + width: _$attributes_36.width, + height: _$attributes_36.height, + opacity: _$attributes_36.opacity, + align: _$attributes_36.align, + valign: _$attributes_36.valign, + bgcolor: _$attributes_36.bgcolor, + bordercolor: _$attributes_36.bordercolor, + borderpad: _$attributes_36.borderpad, + borderwidth: _$attributes_36.borderwidth, + showarrow: _$attributes_36.showarrow, + arrowcolor: _$attributes_36.arrowcolor, + arrowhead: _$attributes_36.arrowhead, + startarrowhead: _$attributes_36.startarrowhead, + arrowside: _$attributes_36.arrowside, + arrowsize: _$attributes_36.arrowsize, + startarrowsize: _$attributes_36.startarrowsize, + arrowwidth: _$attributes_36.arrowwidth, + standoff: _$attributes_36.standoff, + startstandoff: _$attributes_36.startstandoff, + hovertext: _$attributes_36.hovertext, + hoverlabel: _$attributes_36.hoverlabel, + captureevents: _$attributes_36.captureevents, + + // maybes later? + // clicktoshow: annAtts.clicktoshow, + // xclick: annAtts.xclick, + // yclick: annAtts.yclick, + + // not needed! + // axref: 'pixel' + // ayref: 'pixel' + // xref: 'x' + // yref: 'y + // zref: 'z' +}, 'calc', 'from-root'); + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; + +var _$convert_46 = function convert(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var anns = fullSceneLayout.annotations; + + for(var i = 0; i < anns.length; i++) { + mockAnnAxes(anns[i], scene); + } + + scene.fullLayout._infolayer + .selectAll('.annotation-' + scene.id) + .remove(); +}; + +function mockAnnAxes(ann, scene) { + var fullSceneLayout = scene.fullSceneLayout; + var domain = fullSceneLayout.domain; + var size = scene.fullLayout._size; + + var base = { + // this gets fill in on render + pdata: null, + + // to get setConvert to not execute cleanly + type: 'linear', + + // don't try to update them on `editable: true` + autorange: false, + + // set infinite range so that annotation draw routine + // does not try to remove 'outside-range' annotations, + // this case is handled in the render loop + range: [-Infinity, Infinity] + }; + + ann._xa = {}; + _$lib_172.extendFlat(ann._xa, base); + _$axes_214.setConvert(ann._xa); + ann._xa._offset = size.l + domain.x[0] * size.w; + ann._xa.l2p = function() { + return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); + }; + + ann._ya = {}; + _$lib_172.extendFlat(ann._ya, base); + _$axes_214.setConvert(ann._ya); + ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; + ann._ya.l2p = function() { + return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); + }; +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_210 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationCommonDefaults_39 = require('../annotations/common_defaults'); */; +/* removed: var _$attributes_45 = require('./attributes'); */; + +var _$handleDefaults_47 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + _$handleArrayContainerDefaults_210(sceneLayoutIn, sceneLayoutOut, { + name: 'annotations', + handleItemDefaults: __handleAnnotationDefaults_47, + fullLayout: opts.fullLayout + }); +}; + +function __handleAnnotationDefaults_47(annIn, annOut, sceneLayout, opts, itemOpts) { + function coerce(attr, dflt) { + return _$lib_172.coerce(annIn, annOut, _$attributes_45, attr, dflt); + } + + function coercePosition(axLetter) { + var axName = axLetter + 'axis'; + + // mock in such way that getFromId grabs correct 3D axis + var gdMock = { _fullLayout: {} }; + gdMock._fullLayout[axName] = sceneLayout[axName]; + + return _$axes_214.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + } + + + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + if(!visible) return annOut; + + _$handleAnnotationCommonDefaults_39(annIn, annOut, opts.fullLayout, coerce); + + coercePosition('x'); + coercePosition('y'); + coercePosition('z'); + + // if you have one coordinate you should all three + _$lib_172.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + + // hard-set here for completeness + annOut.xref = 'x'; + annOut.yref = 'y'; + annOut.zref = 'z'; + + coerce('xanchor'); + coerce('yanchor'); + coerce('xshift'); + coerce('yshift'); + + if(annOut.showarrow) { + annOut.axref = 'pixel'; + annOut.ayref = 'pixel'; + + // TODO maybe default values should be bigger than the 2D case? + coerce('ax', -10); + coerce('ay', -30); + + // if you have one part of arrow length you should have both + _$lib_172.noneOrAll(annIn, annOut, ['ax', 'ay']); + } + + return annOut; +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +function xformMatrix(m, v) { + var out = [0, 0, 0, 0]; + var i, j; + + for(i = 0; i < 4; ++i) { + for(j = 0; j < 4; ++j) { + out[j] += m[4 * i + j] * v[i]; + } + } + + return out; +} + +function project(camera, v) { + var p = xformMatrix(camera.projection, + xformMatrix(camera.view, + xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); + return p; +} + +var _$project_243 = project; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var __drawRaw_48 = _$draw_42.drawRaw; +/* removed: var _$project_243 = require('../../plots/gl3d/project'); */; +var axLetters = ['x', 'y', 'z']; + +var _$draw_48 = function draw(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var dataScale = scene.dataScale; + var anns = fullSceneLayout.annotations; + + for(var i = 0; i < anns.length; i++) { + var ann = anns[i]; + var annotationIsOffscreen = false; + + for(var j = 0; j < 3; j++) { + var axLetter = axLetters[j]; + var pos = ann[axLetter]; + var ax = fullSceneLayout[axLetter + 'axis']; + var posFraction = ax.r2fraction(pos); + + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + break; } + } + + if(annotationIsOffscreen) { + scene.fullLayout._infolayer + .select('.annotation-' + scene.id + '[data-index="' + i + '"]') + .remove(); + } else { + ann._pdata = _$project_243(scene.glplot.cameraParams, [ + fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], + fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], + fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] + ]); + + __drawRaw_48(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + } + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; + +var _$annotations3d_49 = { + moduleType: 'component', + name: 'annotations3d', + + schema: { + subplots: { + scene: {annotations: _$attributes_45} + } + }, + + layoutAttributes: _$attributes_45, + handleDefaults: _$handleDefaults_47, + includeBasePlot: includeGL3D, + + convert: _$convert_46, + draw: _$draw_48 +}; + +function includeGL3D(layoutIn, layoutOut) { + var GL3D = _$registry_262.subplotsRegistry.gl3d; + if(!GL3D) return; + + var attrRegex = GL3D.attrRegex; + + var keys = Object.keys(layoutIn); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { + _$lib_172.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_172.pushUnique(layoutOut._subplots.gl3d, k); + } + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + + +var _$attributes_78 = { + visible: { + valType: 'boolean', + + editType: 'calc', + + }, + type: { + valType: 'enumerated', + values: ['percent', 'constant', 'sqrt', 'data'], + + editType: 'calc', + + }, + symmetric: { + valType: 'boolean', + + editType: 'calc', + + }, + array: { + valType: 'data_array', + editType: 'calc', + + }, + arrayminus: { + valType: 'data_array', + editType: 'calc', + + }, + value: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'calc', + + }, + valueminus: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'calc', + + }, + traceref: { + valType: 'integer', + min: 0, + dflt: 0, + + editType: 'style' + }, + tracerefminus: { + valType: 'integer', + min: 0, + dflt: 0, + + editType: 'style' + }, + copy_ystyle: { + valType: 'boolean', + + editType: 'plot' + }, + copy_zstyle: { + valType: 'boolean', + + editType: 'style' + }, + color: { + valType: 'color', + + editType: 'style', + + }, + thickness: { + valType: 'number', + min: 0, + dflt: 2, + + editType: 'style', + + }, + width: { + valType: 'number', + min: 0, + + editType: 'plot', + + }, + editType: 'calc', - 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; + _deprecated: { + opacity: { + valType: 'number', + + editType: 'style', + + } + } +}; - insertUpdate(fullInput.index, 'visible', nextVisibility); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + + +/** + * Error bar computing function generator + * + * N.B. The generated function does not clean the dataPt entries. Non-numeric + * entries result in undefined error magnitudes. + * + * @param {object} opts error bar attributes + * + * @return {function} : + * @param {numeric} dataPt data point from where to compute the error magnitude + * @param {number} index index of dataPt in its corresponding data array + * @return {array} + * - error[0] : error magnitude in the negative direction + * - error[1] : " " " " positive " + */ +var _$makeComputeError_80 = function makeComputeError(opts) { + var type = opts.type, + 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), + computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); - if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_171.notifier(_$lib_171._(gd, 'Double-click on legend to isolate one trace'), 'long'); - SHOWISOLATETIP = false; - } else { - SHOWISOLATETIP = false; + 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) + ]; + }; + } } +}; - if(_$registry_261.traceIs(fullTrace, 'pie')) { - var thisLabel = legendItem.label, - thisLabelIndex = hiddenSlices.indexOf(thisLabel); +/** + * 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)); + }; + } +} - if(numClicks === 1) { - if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); - else hiddenSlices.splice(thisLabelIndex, 1); - } else if(numClicks === 2) { - 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 = []; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; + +/* removed: var _$makeComputeError_80 = require('./compute_error'); */; + + +var _$calc_79 = function calc(gd) { + var calcdata = gd.calcdata; + + for(var i = 0; i < calcdata.length; i++) { + var calcTrace = calcdata[i], + trace = calcTrace[0].trace; + + if(!_$registry_262.traceIs(trace, 'errorBarsOK')) continue; + + var xa = _$axes_214.getFromId(gd, trace.xaxis), + ya = _$axes_214.getFromId(gd, trace.yaxis); + + calcOneAxis(calcTrace, trace, xa, 'x'); + calcOneAxis(calcTrace, trace, ya, 'y'); + } +}; + +function calcOneAxis(calcTrace, trace, axis, coord) { + var opts = trace['error_' + coord] || {}, + isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), + vals = []; + + if(!isVisible) return; + + var computeError = _$makeComputeError_80(opts); + + for(var i = 0; i < calcTrace.length; i++) { + var calcPt = calcTrace[i], + calcCoord = calcPt[coord]; + + if(!_$fastIsnumeric_18(axis.c2l(calcCoord))) continue; + + var errors = computeError(calcCoord, i); + if(_$fastIsnumeric_18(errors[0]) && _$fastIsnumeric_18(errors[1])) { + var shoe = calcPt[coord + 's'] = calcCoord - errors[0], + hat = calcPt[coord + 'h'] = calcCoord + errors[1]; + vals.push(shoe, hat); } + } - _$registry_261.call('relayout', 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); - } - } + _$axes_214.expand(axis, vals, {padded: true}); +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; + +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; + +/* removed: var _$attributes_78 = require('./attributes'); */; + + +var _$defaults_81 = function(traceIn, traceOut, defaultColor, opts) { + var objName = 'error_' + opts.axis, + containerOut = traceOut[objName] = {}, + containerIn = traceIn[objName] || {}; + + function coerce(attr, dflt) { + return _$lib_172.coerce(containerIn, containerOut, _$attributes_78, 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'), + 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'); + } - if(numClicks === 1) { - var nextVisibility; + var copyAttr = 'copy_' + opts.inherit + 'style'; + if(opts.inherit) { + var inheritObj = traceOut['error_' + opts.inherit]; + if((inheritObj || {}).visible) { + coerce(copyAttr, !(containerIn.color || + _$fastIsnumeric_18(containerIn.thickness) || + _$fastIsnumeric_18(containerIn.width))); + } + } + if(!opts.inherit || !containerOut[copyAttr]) { + coerce('color', defaultColor); + coerce('thickness'); + coerce('width', _$registry_262.traceIs(traceOut, 'gl3d') ? 0 : 4); + } +}; - switch(fullTrace.visible) { - case true: - nextVisibility = 'legendonly'; - break; - case false: - nextVisibility = false; - break; - case 'legendonly': - nextVisibility = true; - break; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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(numClicks === 2) { - // 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, otherState; - var isIsolated = true; - for(i = 0; i < fullData.length; i++) { - isClicked = fullData[i] === fullTrace; - if(isClicked) continue; - isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); +'use strict'; - if(!isInGroup && fullData[i].visible === true && !_$registry_261.traceIs(fullData[i], 'notLegendIsolatable')) { - isIsolated = false; - break; - } - } +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; - for(i = 0; i < fullData.length; i++) { - // False is sticky; we don't change it. - if(fullData[i].visible === false) continue; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$subtypes_391 = require('../../traces/scatter/subtypes'); */; - if(_$registry_261.traceIs(fullData[i], 'notLegendIsolatable')) { - continue; - } +var _$plot_83 = function plot(traces, plotinfo, transitionOpts) { + var isNew; - switch(fullTrace.visible) { - case 'legendonly': - setVisibility(fullData[i], true); - break; - case true: - otherState = isIsolated ? true : 'legendonly'; - isClicked = fullData[i] === fullTrace; - isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); - setVisibility(fullData[i], isInGroup ? true : otherState); - break; - } - } + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + var hasAnimation = transitionOpts && transitionOpts.duration > 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 + xObj = trace.error_x || {}, + yObj = trace.error_y || {}; + + var keyFunc; + + if(trace.ids) { + keyFunc = function(d) {return d.id;}; } - for(i = 0; i < carrs.length; i++) { - kcont = carrs[i]; - if(!kcont) continue; - var update = kcont.constructUpdate(); + var sparse = ( + _$subtypes_391.hasMarkers(trace) && + trace.marker.maxdisplayed > 0 + ); - 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]; - } + if(!yObj.visible && !xObj.visible) d = []; + + var errorbars = _$d3_15.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); } - // 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; + _$drawing_76.setClipUrl(errorbars, plotinfo.layerClipId); + + errorbars.each(function(d) { + var errorbar = _$d3_15.select(this); + var coords = errorCoords(d, xa, ya); + + if(sparse && !d.vis) return; + + var path; + + var yerror = errorbar.select('path.yerror'); + if(yObj.visible && _$fastIsnumeric_18(coords.x) && + _$fastIsnumeric_18(coords.yh) && + _$fastIsnumeric_18(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 && _$fastIsnumeric_18(coords.y) && + _$fastIsnumeric_18(coords.xh) && + _$fastIsnumeric_18(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(!_$fastIsnumeric_18(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); - _$registry_261.call('restyle', gd, attrUpdate, attrIndices); + if(!_$fastIsnumeric_18(out.xs)) { + out.noXS = true; + out.xs = xa.c2p(d.xs, true); + } } -}; -var _$helpers_360 = {}; + return out; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48361,60 +50638,32 @@ var _$helpers_360 = {}; * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$lib_171 = require('../../lib'); */; -_$helpers_360.formatPiePercent = function formatPiePercent(v, separators) { - var vRounded = (v * 100).toPrecision(3); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_171.numSeparate(vRounded, separators) + '%'; -}; +'use strict'; -_$helpers_360.formatPieValue = function formatPieValue(v, separators) { - var vRounded = v.toPrecision(10); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_171.numSeparate(vRounded, separators); -}; +/* removed: var _$d3_15 = require('d3'); */; -_$helpers_360.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) return v; - } -}; +/* removed: var _$color_51 = require('../color'); */; -_$helpers_360.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_360.getFirstFilled(item, indices); - else if(item) return item; -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$style_84 = function style(traces) { + traces.each(function(d) { + var trace = d[0].trace, + yObj = trace.error_y || {}, + xObj = trace.error_x || {}; -'use strict'; + var s = _$d3_15.select(this); -/* removed: var _$color_51 = require('../../components/color'); */; -var castOption = _$helpers_360.castOption; + s.selectAll('path.yerror') + .style('stroke-width', yObj.thickness + 'px') + .call(_$color_51.stroke, yObj.color); -var _$styleOne_366 = function styleOne(s, pt, trace) { - var line = trace.marker.line; - var lineColor = castOption(line.color, pt.pts) || _$color_51.defaultLine; - var lineWidth = castOption(line.width, pt.pts) || 0; + if(xObj.copy_ystyle) xObj = yObj; - s.style({'stroke-width': lineWidth}) - .call(_$color_51.fill, pt.color) - .call(_$color_51.stroke, lineColor); + s.selectAll('path.xerror') + .style('stroke-width', xObj.thickness + 'px') + .call(_$color_51.stroke, xObj.color); + }); }; /** @@ -48425,229 +50674,197 @@ var _$styleOne_366 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$color_51 = require('../color'); */; - -/* removed: var _$subtypes_390 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_366 = require('../../traces/pie/style_one'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var __overrideAll_82 = _$edit_types_199.overrideAll; +/* removed: var _$attributes_78 = require('./attributes'); */; +/* removed: var _$calc_79 = require('./calc'); */; -var _$style_112 = function style(s, gd) { - s.each(function(d) { - var traceGroup = _$d3_15.select(this); +var xyAttrs = { + error_x: _$lib_172.extendFlat({}, _$attributes_78), + error_y: _$lib_172.extendFlat({}, _$attributes_78) +}; +delete xyAttrs.error_x.copy_zstyle; +delete xyAttrs.error_y.copy_zstyle; +delete xyAttrs.error_y.copy_ystyle; - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); - layers.style('opacity', d[0].trace.opacity); +var xyzAttrs = { + error_x: _$lib_172.extendFlat({}, _$attributes_78), + error_y: _$lib_172.extendFlat({}, _$attributes_78), + error_z: _$lib_172.extendFlat({}, _$attributes_78) +}; +delete xyzAttrs.error_x.copy_ystyle; +delete xyzAttrs.error_y.copy_ystyle; +delete xyzAttrs.error_z.copy_ystyle; +delete xyzAttrs.error_z.copy_zstyle; - var fill = layers - .selectAll('g.legendfill') - .data([d]); - fill.enter().append('g') - .classed('legendfill', true); +var _$errorbars_82 = { + moduleType: 'component', + name: 'errorbars', - var line = layers - .selectAll('g.legendlines') - .data([d]); - line.enter().append('g') - .classed('legendlines', true); + schema: { + traces: { + scatter: xyAttrs, + bar: xyAttrs, + histogram: xyAttrs, + scatter3d: __overrideAll_82(xyzAttrs, 'calc', 'nested'), + scattergl: __overrideAll_82(xyAttrs, 'calc', 'nested') + } + }, - var symbol = layers - .selectAll('g.legendsymbols') - .data([d]); - symbol.enter().append('g') - .classed('legendsymbols', true); + supplyDefaults: _$defaults_81, - symbol.selectAll('g.legendpoints') - .data([d]) - .enter().append('g') - .classed('legendpoints', true); - }) - .each(styleBars) - .each(styleBoxes) - .each(stylePies) - .each(styleLines) - .each(stylePoints); + calc: _$calc_79, + calcFromTrace: calcFromTrace, - function styleLines(d) { - var trace = d[0].trace; - var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_390.hasLines(trace); - var contours = trace.contours; + plot: _$plot_83, + style: _$style_84, + hoverInfo: hoverInfo +}; - if(contours && contours.type === 'constraint') { - showLine = contours.showlines; - showFill = contours._operation !== '='; - } +function calcFromTrace(trace, layout) { + var x = trace.x || [], + y = trace.y || [], + len = x.length || y.length; - var fill = _$d3_15.select(this).select('.legendfill').selectAll('path') - .data(showFill ? [d] : []); - fill.enter().append('path').classed('js-fill', true); - fill.exit().remove(); - fill.attr('d', 'M5,0h30v6h-30z') - .call(_$drawing_76.fillGroupStyle); + var calcdataMock = new Array(len); - var line = _$d3_15.select(this).select('.legendlines').selectAll('path') - .data(showLine ? [d] : []); - line.enter().append('path').classed('js-line', true) - .attr('d', 'M5,0h30'); - line.exit().remove(); - line.call(_$drawing_76.lineGroupStyle); + for(var i = 0; i < len; i++) { + calcdataMock[i] = { + x: x[i], + y: y[i] + }; } - function stylePoints(d) { - var d0 = d[0], - trace = d0.trace, - showMarkers = _$subtypes_390.hasMarkers(trace), - showText = _$subtypes_390.hasText(trace), - showLines = _$subtypes_390.hasLines(trace); - - var dMod, tMod; - - // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; - // use d0.trace to infer arrayOk attributes - - function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_171.nestedProperty(trace, attrIn).get(), - valToBound = (Array.isArray(valIn) && arrayToValFn) ? - arrayToValFn(valIn) : valIn; + calcdataMock[0].trace = trace; - if(bounds) { - if(valToBound < bounds[0]) return bounds[0]; - else if(valToBound > bounds[1]) return bounds[1]; - } - return valToBound; - } + _$calc_79({ + calcdata: [calcdataMock], + _fullLayout: layout + }); - function pickFirst(array) { return array[0]; } + return calcdataMock; +} - // constrain text, markers, etc so they'll fit on the legend - if(showMarkers || showText || showLines) { - var dEdit = {}, - tEdit = {}; +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; + } +} - if(showMarkers) { - dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_171.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_171.mean, [2, 16]); - dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_171.mean, [0, 5]); - tEdit.marker = { - sizeref: 1, - sizemin: 1, - sizemode: 'diameter' - }; - } +var _$domain_239 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(showLines) { - tEdit.line = { - width: boundVal('line.width', pickFirst, [0, 10]) - }; - } +'use strict'; - if(showText) { - dEdit.tx = 'Aa'; - dEdit.tp = boundVal('textposition', pickFirst); - dEdit.ts = 10; - dEdit.tc = boundVal('textfont.color', pickFirst); - dEdit.tf = boundVal('textfont.family', pickFirst); - } +var __extendFlat_239 = _$extend_166.extendFlat; - dMod = [_$lib_171.minExtend(d0, dEdit)]; - tMod = _$lib_171.minExtend(trace, tEdit); - } +/** + * 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 + */ +_$domain_239.attributes = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; - var ptgroup = _$d3_15.select(this).select('g.legendpoints'); + 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 pts = ptgroup.selectAll('path.scatterpts') - .data(showMarkers ? dMod : []); - pts.enter().append('path').classed('scatterpts', true) - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.call(_$drawing_76.pointStyle, tMod, gd); + var namePart = opts.name ? opts.name + ' ' : ''; + var contPart = opts.trace ? 'trace ' : 'subplot '; + var descPart = extra.description ? ' ' + extra.description : ''; - // 'mrc' is set in pointStyle and used in textPointStyle: - // constrain it here - if(showMarkers) dMod[0].mrc = 3; + var out = { + x: __extendFlat_239({}, base, { + + }), + y: __extendFlat_239({}, base, { + + }), + editType: opts.editType + }; - var txt = ptgroup.selectAll('g.pointtext') - .data(showText ? dMod : []); - txt.enter() - .append('g').classed('pointtext', true) - .append('text').attr('transform', 'translate(20,0)'); - txt.exit().remove(); - txt.selectAll('text').call(_$drawing_76.textPointStyle, tMod, gd); + 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, + + }; } - function styleBars(d) { - var trace = d[0].trace, - marker = trace.marker || {}, - markerLine = marker.line || {}, - barpath = _$d3_15.select(this).select('g.legendpoints') - .selectAll('path.legendbar') - .data(_$registry_261.traceIs(trace, 'bar') ? [d] : []); - barpath.enter().append('path').classed('legendbar', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - barpath.exit().remove(); - barpath.each(function(d) { - var p = _$d3_15.select(this), - d0 = d[0], - w = (d0.mlw + 1 || markerLine.width + 1) - 1; - - p.style('stroke-width', w + 'px') - .call(_$color_51.fill, d0.mc || marker.color); - - if(w) { - p.call(_$color_51.stroke, d0.mlc || markerLine.color); - } - }); - } + return out; +}; - function styleBoxes(d) { - var trace = d[0].trace, - pts = _$d3_15.select(this).select('g.legendpoints') - .selectAll('path.legendbox') - .data(_$registry_261.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendbox', true) - // if we want the median bar, prepend M6,0H-6 - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.each(function() { - var w = trace.line.width, - p = _$d3_15.select(this); +_$domain_239.defaults = function(containerOut, layout, coerce, dfltDomains) { + var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; + var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; - p.style('stroke-width', w + 'px') - .call(_$color_51.fill, trace.fillcolor); + 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; + } - if(w) { - p.call(_$color_51.stroke, trace.line.color); - } - }); + var row = coerce('domain.row'); + if(row !== undefined) { + if(row < grid.rows) dfltY = grid._domains.y[row]; + else delete containerOut.domain.row; + } } - function stylePies(d) { - var trace = d[0].trace, - pts = _$d3_15.select(this).select('g.legendpoints') - .selectAll('path.legendpie') - .data(_$registry_261.traceIs(trace, 'pie') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendpie', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - - if(pts.size()) pts.call(_$styleOne_366, d[0], trace); - } + coerce('domain.x', dfltX); + coerce('domain.y', dfltY); }; /** @@ -48660,728 +50877,872 @@ var _$style_112 = function style(s, gd) { 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; - -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$handleClick_109 = require('./handle_click'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var __counterRegex_97 = _$regex_187.counter; +var domainAttrs = _$domain_239.attributes; +var cartesianIdRegex = _$constants_219.idRegex; -/* removed: var _$constants_105 = require('./constants'); */; -/* removed: var _$interactions_153 = require('../../constants/interactions'); */; -/* removed: var _$alignment_151 = require('../../constants/alignment'); */; -var __LINE_SPACING_107 = _$alignment_151.LINE_SPACING; -var FROM_TL = _$alignment_151.FROM_TL; -var FROM_BR = _$alignment_151.FROM_BR; +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_97('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' +}; -/* removed: var _$getLegendData_108 = require('./get_legend_data'); */; -/* removed: var _$style_112 = require('./style'); */; -/* removed: var _$helpers_110 = require('./helpers'); */; -/* removed: var _$anchor_utils_103 = require('./anchor_utils'); */; +function getAxes(layout, grid, axLetter) { + var gridVal = grid[axLetter + 'axes']; + var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {}); -var DBLCLICKDELAY = _$interactions_153.DBLCLICKDELAY; + if(Array.isArray(gridVal)) return gridVal; + if(splomVal.length) return splomVal; +} -var _$draw_107 = function draw(gd) { - var fullLayout = gd._fullLayout; - var clipId = 'legend' + fullLayout._uid; +// 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(!fullLayout._infolayer || !gd.calcdata) return; + if(!layoutIn.grid && !xAxes && !yAxes) return; - if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; + 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 opts = fullLayout.legend, - legendData = fullLayout.showlegend && _$getLegendData_108(gd.calcdata, opts), - hiddenSlices = fullLayout.hiddenlabels || []; + var dfltRows, dfltColumns; - if(!fullLayout.showlegend || !legendData.length) { - fullLayout._infolayer.selectAll('.legend').remove(); - fullLayout._topdefs.select('#' + clipId).remove(); + if(hasSubplotGrid) { + dfltRows = gridIn.subplots.length; + dfltColumns = gridIn.subplots[0].length; + } + else { + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; + } - _$plots_246.autoMargin(gd, 'legend'); - return; + var gridOut = layoutOut.grid = {}; + + function coerce(attr, dflt) { + return _$lib_172.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); + var rows = coerce('rows', dfltRows); + var columns = coerce('columns', dfltColumns); - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); + if(!(rows * columns > 1)) return; - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); + if(!hasSubplotGrid && !hasXaxes && !hasYaxes) { + var useDefaultSubplots = coerce('pattern') === 'independent'; + if(useDefaultSubplots) hasSubplotGrid = true; + } + gridOut._hasSubplotGrid = hasSubplotGrid; - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var rowOrder = coerce('roworder'); + var reversed = rowOrder === 'top to bottom'; - var bg = legend.selectAll('rect.bg') - .data([0]); + var dfltGapX = hasSubplotGrid ? 0.2 : 0.1; + var dfltGapY = hasSubplotGrid ? 0.3 : 0.1; - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' - }); + var dfltSideX, dfltSideY; + if(isSplomGenerated) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } - bg.call(_$color_51.stroke, opts.bordercolor) - .call(_$color_51.fill, opts.bgcolor) - .style('stroke-width', opts.borderwidth + 'px'); + gridOut._domains = { + x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns), + y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed) + }; +} - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); +// 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); - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); + 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; +} - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); +// 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; - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', - rx: 20, - ry: 3, - width: 0, - height: 0 - }) - .call(_$color_51.fill, '#808BA4'); + 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 groups = scrollBox.selectAll('g.groups') - .data(legendData); + var i, j, xId, yId, subplotId, subplotsOut, yPos; - groups.enter().append('g') - .attr('class', 'groups'); + var axisMap = gridOut._axisMap = {}; - groups.exit().remove(); + if(hasSubplotGrid) { + var subplotsIn = gridIn.subplots || []; + subplotsOut = gridOut.subplots = new Array(rows); + var index = 1; - var traces = groups.selectAll('g.traces') - .data(_$lib_171.identity); + 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]; - traces.enter().append('g').attr('class', 'traces'); - traces.exit().remove(); + rowOut[j] = ''; - traces.call(_$style_112, gd) - .style('opacity', function(d) { - var trace = d[0].trace; - if(_$registry_261.traceIs(trace, 'pie')) { - return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; - } else { - return trace.visible === 'legendonly' ? 0.5 : 1; - } - }) - .each(function() { - _$d3_15.select(this) - .call(drawTexts, gd) - .call(setupTraceToggle, gd); - }); + 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; + } - var firstRender = legend.enter().size() !== 0; - if(firstRender) { - computeLegendDimensions(gd, groups, traces); - expandMargin(gd); + 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'); } - // Position and size the legend - var lxMin = 0, - lxMax = fullLayout.width, - lyMin = 0, - lyMax = fullLayout.height; + var anchors = gridOut._anchors = {}; + var reversed = gridOut.roworder === 'top to bottom'; - computeLegendDimensions(gd, groups, traces); + for(var axisId in axisMap) { + var axLetter = axisId.charAt(0); + var side = gridOut[axLetter + 'side']; - if(opts._height > lyMax) { - // If the legend doesn't fit in the plot area, - // do not expand the vertical margins. - expandHorizontalMargin(gd); - } else { - expandMargin(gd); + 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; + } + } + } + } } +} - // Scroll section must be executed after repositionLegend. - // It requires the legend width, height, x and y to position the scrollbox - // and these values are mutated in repositionLegend. - var gs = fullLayout._size, - lx = gs.l + gs.w * opts.x, - ly = gs.t + gs.h * (1 - opts.y); +function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { + var out = new Array(len); + var i; - if(_$anchor_utils_103.isRightAnchor(opts)) { - lx -= opts._width; - } - else if(_$anchor_utils_103.isCenterAnchor(opts)) { - lx -= opts._width / 2; + function fillOneAxis(i, axisId) { + if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) { + out[i] = axisId; + axisMap[axisId] = i; + } + else out[i] = ''; } - if(_$anchor_utils_103.isBottomAnchor(opts)) { - ly -= opts._height; + if(Array.isArray(axesIn)) { + for(i = 0; i < len; i++) { + fillOneAxis(i, axesIn[i]); + } } - else if(_$anchor_utils_103.isMiddleAnchor(opts)) { - ly -= opts._height / 2; + else { + // default axis list is the first `len` axis ids + fillOneAxis(0, axLetter); + for(i = 1; i < len; i++) { + fillOneAxis(i, axLetter + (i + 1)); + } } - // Make sure the legend left and right sides are visible - var legendWidth = opts._width, - legendWidthMax = gs.w; + return out; +} - if(legendWidth > legendWidthMax) { - lx = gs.l; - legendWidth = legendWidthMax; - } - else { - if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; - if(lx < lxMin) lx = lxMin; - legendWidth = Math.min(lxMax - lx, opts._width); - } +var _$grid_97 = { + moduleType: 'component', + name: 'grid', - // Make sure the legend top and bottom are visible - // (legends with a scroll bar are not allowed to stretch beyond the extended - // margins) - var legendHeight = opts._height, - legendHeightMax = gs.h; + schema: { + layout: {grid: gridAttrs} + }, - if(legendHeight > legendHeightMax) { - ly = gs.t; - legendHeight = legendHeightMax; - } - else { - if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; - if(ly < lyMin) ly = lyMin; - legendHeight = Math.min(lyMax - ly, opts._height); - } + layoutAttributes: gridAttrs, + sizeDefaults: sizeDefaults, + contentDefaults: contentDefaults +}; - // Set size and position of all the elements that make up a legend: - // legend, background and border, scroll box and scroll bar - _$drawing_76.setTranslate(legend, lx, ly); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // to be safe, remove previous listeners - scrollBar.on('.drag', null); - legend.on('wheel', null); +'use strict'; - if(opts._height <= legendHeight || gd._context.staticPlot) { - // if scrollbar should not be shown. - bg.attr({ - width: legendWidth - opts.borderwidth, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); +/* removed: var _$constants_219 = require('../../plots/cartesian/constants'); */; - _$drawing_76.setTranslate(scrollBox, 0, 0); - clipPath.select('rect').attr({ - width: legendWidth - 2 * opts.borderwidth, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth - }); +var _$attributes_98 = { + _isLinkedToArray: 'image', - _$drawing_76.setClipUrl(scrollBox, clipId); + visible: { + valType: 'boolean', + + dflt: true, + editType: 'arraydraw', + + }, - _$drawing_76.setRect(scrollBar, 0, 0, 0, 0); - delete opts._scrollY; - } - else { - var scrollBarHeight = Math.max(_$constants_105.scrollBarMinHeight, - legendHeight * legendHeight / opts._height); - var scrollBarYMax = legendHeight - - scrollBarHeight - - 2 * _$constants_105.scrollBarMargin; - var scrollBoxYMax = opts._height - legendHeight; - var scrollRatio = scrollBarYMax / scrollBoxYMax; + source: { + valType: 'string', + + editType: 'arraydraw', + + }, - var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, - // increase the background and clip-path width - // by the scrollbar width and margin - bg.attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_105.scrollBarWidth + - _$constants_105.scrollBarMargin, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); + sizex: { + valType: 'number', + + dflt: 0, + editType: 'arraydraw', + + }, - clipPath.select('rect').attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_105.scrollBarWidth + - _$constants_105.scrollBarMargin, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth + scrollBoxY - }); + sizey: { + valType: 'number', + + dflt: 0, + editType: 'arraydraw', + + }, - _$drawing_76.setClipUrl(scrollBox, clipId); + sizing: { + valType: 'enumerated', + values: ['fill', 'contain', 'stretch'], + dflt: 'contain', + + editType: 'arraydraw', + + }, - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + opacity: { + valType: 'number', + + min: 0, + max: 1, + dflt: 1, + editType: 'arraydraw', + + }, - legend.on('wheel', function() { - scrollBoxY = _$lib_171.constrain( - opts._scrollY + - _$d3_15.event.deltaY / scrollBarYMax * scrollBoxYMax, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - _$d3_15.event.preventDefault(); - } - }); + x: { + valType: 'any', + + dflt: 0, + editType: 'arraydraw', + + }, - var eventY0, scrollBoxY0; + y: { + valType: 'any', + + dflt: 0, + editType: 'arraydraw', + + }, - var drag = _$d3_15.behavior.drag() - .on('dragstart', function() { - eventY0 = _$d3_15.event.sourceEvent.clientY; - scrollBoxY0 = scrollBoxY; - }) - .on('drag', function() { - var e = _$d3_15.event.sourceEvent; - if(e.buttons === 2 || e.ctrlKey) return; + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + editType: 'arraydraw', + + }, - scrollBoxY = _$lib_171.constrain( - (e.clientY - eventY0) / scrollRatio + scrollBoxY0, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - }); + yanchor: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'top', + + editType: 'arraydraw', + + }, - scrollBar.call(drag); - } + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_219.idRegex.x.toString() + ], + dflt: 'paper', + + editType: 'arraydraw', + + }, + + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_219.idRegex.y.toString() + ], + dflt: 'paper', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { - opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; - _$drawing_76.setTranslate(scrollBox, 0, -scrollBoxY); +'use strict'; + +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_195 = require('../../lib/to_log_range'); */; + +/* + * convertCoords: when converting an axis between log and linear + * you need to alter any images on that axis to keep them + * pointing at the same data point. + * In v2.0 this will become obsolete (or perhaps size will still need conversion?) + * we convert size by declaring that the maximum extent *in data units* should be + * the same, assuming the image is anchored by its center (could remove that restriction + * if we think it's important) even though the actual left and right values will not be + * quite the same since the scale becomes nonlinear (and central anchor means the pixel + * center of the image, not the data units center) + * + * gd: the plot div + * ax: the axis being changed + * newType: the type it's getting + * doExtra: function(attr, val) from inside relayout that sets the attribute. + * Use this to make the changes as it's aware if any other changes in the + * same relayout call should override this conversion. + */ +var _$convertCoords_99 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; - _$drawing_76.setRect( - scrollBar, - legendWidth, - _$constants_105.scrollBarMargin + scrollBoxY * scrollRatio, - _$constants_105.scrollBarWidth, - scrollBarHeight - ); - clipPath.select('rect').attr({ - y: opts.borderwidth + scrollBoxY - }); - } + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); - if(gd._context.edits.legendPosition) { - var xf, yf, x0, y0; + if(!(toLog || fromLog)) return; - legend.classed('cursor-move', true); + var images = gd._fullLayout.images, + axLetter = ax._id.charAt(0), + image, + attrPrefix; - _$dragelement_73.init({ - element: legend.node(), - gd: gd, - prepFn: function() { - var transform = _$drawing_76.getTranslate(legend); + for(var i = 0; i < images.length; i++) { + image = images[i]; + attrPrefix = 'images[' + i + '].'; - x0 = transform.x; - y0 = transform.y; - }, - moveFn: function(dx, dy) { - var newX = x0 + dx, - newY = y0 + dy; + if(image[axLetter + 'ref'] === ax._id) { + var currentPos = image[axLetter], + currentSize = image['size' + axLetter], + newPos = null, + newSize = null; - _$drawing_76.setTranslate(legend, newX, newY); + if(toLog) { + newPos = _$toLogRange_195(currentPos, ax.range); - xf = _$dragelement_73.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); - yf = _$dragelement_73.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); - }, - doneFn: function() { - if(xf !== undefined && yf !== undefined) { - _$registry_261.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); - } - }, - clickFn: function(numClicks, e) { - var clickedTrace = - fullLayout._infolayer.selectAll('g.traces').filter(function() { - var bbox = this.getBoundingClientRect(); - return (e.clientX >= bbox.left && e.clientX <= bbox.right && - e.clientY >= bbox.top && e.clientY <= bbox.bottom); - }); - if(clickedTrace.size() > 0) { - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { - _$handleClick_109(clickedTrace, gd, numClicks); - }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - _$handleClick_109(clickedTrace, gd, numClicks); - } - } + // this is the inverse of the conversion we do in fromLog below + // so that the conversion is reversible (notice the fromLog conversion + // is like sinh, and this one looks like arcsinh) + var dx = currentSize / Math.pow(10, newPos) / 2; + newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; + } + else { + newPos = Math.pow(10, currentPos); + newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); } - }); - } -}; - -function drawTexts(g, gd) { - var legendItem = g.data()[0][0], - fullLayout = gd._fullLayout, - trace = legendItem.trace, - isPie = _$registry_261.traceIs(trace, 'pie'), - traceIndex = trace.index, - name = isPie ? legendItem.label : trace.name; - - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); - text.attr('text-anchor', 'start') - .classed('user-select-none', true) - .call(_$drawing_76.font, fullLayout.legend.font) - .text(name); + // if conversion failed, delete the value so it can get a default later on + if(!_$fastIsnumeric_18(newPos)) { + newPos = null; + newSize = null; + } + else if(!_$fastIsnumeric_18(newSize)) newSize = null; - function textLayout(s) { - _$svg_text_utils_192.convertToTspans(s, gd, function() { - computeTextDimensions(g, gd); - }); + doExtra(attrPrefix + axLetter, newPos); + doExtra(attrPrefix + 'size' + axLetter, newSize); + } } +}; - if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_192.makeEditable, {gd: gd}) - .call(textLayout) - .on('edit', function(text) { - this.text(text) - .call(textLayout); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 origText = text; +'use strict'; - if(!this.text()) text = ' \u0020\u0020 '; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_210 = require('../../plots/array_container_defaults'); */; - var transforms, direction; - var fullInput = legendItem.trace._fullInput || {}; - var update = {}; +/* removed: var _$attributes_98 = require('./attributes'); */; +var name = 'images'; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_261.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_261.getTransformIndices(fullInput, 'groupby'); - var index = groupbyIndices[groupbyIndices.length - 1]; +var _$supplyLayoutDefaults_100 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: name, + handleItemDefaults: imageDefaults + }; - var kcont = _$lib_171.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + _$handleArrayContainerDefaults_210(layoutIn, layoutOut, opts); +}; - if(origText === '') { - kcont.remove(legendItem.trace._group); - } else { - kcont.set(legendItem.trace._group, text); - } - update = kcont.constructUpdate(); - } else { - update.name = text; - } +function imageDefaults(imageIn, imageOut, fullLayout) { - return _$registry_261.call('restyle', gd, update, traceIndex); - }); - } else { - textLayout(text); + function coerce(attr, dflt) { + return _$lib_172.coerce(imageIn, imageOut, _$attributes_98, attr, dflt); } -} -function setupTraceToggle(g, gd) { - var newMouseDownTime, - numClicks = 1; + var source = coerce('source'); + var visible = coerce('visible', !!source); - var traceToggle = g.selectAll('rect') - .data([0]); + if(!visible) return imageOut; - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_51.fill, 'rgba(0,0,0,0)'); + coerce('layer'); + coerce('xanchor'); + coerce('yanchor'); + coerce('sizex'); + coerce('sizey'); + coerce('sizing'); + coerce('opacity'); + var gdMock = { _fullLayout: fullLayout }, + axLetters = ['x', 'y']; - traceToggle.on('mousedown', function() { - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { - // 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; + for(var i = 0; i < 2; i++) { + // 'paper' is the fallback axref + var axLetter = axLetters[i], + axRef = _$axes_214.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } + _$axes_214.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + } - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { _$handleClick_109(g, gd, numClicks); }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - gd._legendMouseDownTime = 0; - _$handleClick_109(g, gd, numClicks); - } - }); + return imageOut; } -function computeTextDimensions(g, gd) { - var legendItem = g.data()[0][0]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!legendItem.trace.showlegend) { - g.remove(); - return; - } +'use strict'; - var mathjaxGroup = g.select('g[class*=math-group]'); - var mathjaxNode = mathjaxGroup.node(); - var opts = gd._fullLayout.legend; - var lineHeight = opts.font.size * __LINE_SPACING_107; - var height, width; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$xmlns_namespaces_156 = require('../../constants/xmlns_namespaces'); */; - if(mathjaxNode) { - var mathjaxBB = _$drawing_76.bBox(mathjaxNode); +var _$draw_101 = function draw(gd) { + var fullLayout = gd._fullLayout, + imageDataAbove = [], + imageDataSubplot = {}, + imageDataBelow = [], + subplot, + i; - height = mathjaxBB.height; - width = mathjaxBB.width; + // Sort into top, subplot, and bottom layers + for(i = 0; i < fullLayout.images.length; i++) { + var img = fullLayout.images[i]; - _$drawing_76.setTranslate(mathjaxGroup, 0, (height / 4)); - } - else { - var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_192.lineCount(text); - var textNode = text.node(); + if(img.visible) { + if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { + subplot = img.xref + img.yref; - height = lineHeight * textLines; - width = textNode ? _$drawing_76.bBox(textNode).width : 0; + var plotinfo = fullLayout._plots[subplot]; - // approximation to height offset to center the font - // to avoid getBoundingClientRect - var textY = lineHeight * (0.3 + (1 - textLines) / 2); - // TODO: this 40 should go in a constants file (along with other - // values related to the legend symbol size) - _$svg_text_utils_192.positionText(text, 40, textY); - } + if(!plotinfo) { + // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the image to an x / y axis combination + // that doesn't have any data on it (and layer is below) + imageDataBelow.push(img); + continue; + } - height = Math.max(height, 16) + 3; + if(plotinfo.mainplot) { + subplot = plotinfo.mainplot.id; + } - legendItem.height = height; - legendItem.width = width; -} + if(!imageDataSubplot[subplot]) { + imageDataSubplot[subplot] = []; + } + imageDataSubplot[subplot].push(img); + } else if(img.layer === 'above') { + imageDataAbove.push(img); + } else { + imageDataBelow.push(img); + } + } + } -function computeLegendDimensions(gd, groups, traces) { - var fullLayout = gd._fullLayout; - var opts = fullLayout.legend; - var borderwidth = opts.borderwidth; - var isGrouped = _$helpers_110.isGrouped(opts); - var extraWidth = 0; + var anchors = { + x: { + left: { sizing: 'xMin', offset: 0 }, + center: { sizing: 'xMid', offset: -1 / 2 }, + right: { sizing: 'xMax', offset: -1 } + }, + y: { + top: { sizing: 'YMin', offset: 0 }, + middle: { sizing: 'YMid', offset: -1 / 2 }, + bottom: { sizing: 'YMax', offset: -1 } + } + }; - opts._width = 0; - opts._height = 0; - if(_$helpers_110.isVertical(opts)) { - if(isGrouped) { - groups.each(function(d, i) { - _$drawing_76.setTranslate(this, 0, i * opts.tracegroupgap); - }); + // Images must be converted to dataURL's for exporting. + function setImage(d) { + var thisImage = _$d3_15.select(this); + + if(this.img && this.img.src === d.source) { + return; } - traces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height, - textWidth = legendItem.width; + thisImage.attr('xmlns', _$xmlns_namespaces_156.svg); - _$drawing_76.setTranslate(this, - borderwidth, - (5 + borderwidth + opts._height + textHeight / 2)); + var imagePromise = new Promise(function(resolve) { - opts._height += textHeight; - opts._width = Math.max(opts._width, textWidth); - }); + var img = new Image(); + this.img = img; - opts._width += 45 + borderwidth * 2; - opts._height += 10 + borderwidth * 2; + // If not set, a `tainted canvas` error is thrown + img.setAttribute('crossOrigin', 'anonymous'); + img.onerror = errorHandler; + img.onload = function() { + var canvas = document.createElement('canvas'); + canvas.width = this.width; + canvas.height = this.height; - if(isGrouped) { - opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; - } + var ctx = canvas.getContext('2d'); + ctx.drawImage(this, 0, 0); - extraWidth = 40; - } - else if(isGrouped) { - var groupXOffsets = [opts._width], - groupData = groups.data(); + var dataURL = canvas.toDataURL('image/png'); - for(var i = 0, n = groupData.length; i < n; i++) { - var textWidths = groupData[i].map(function(legendItemArray) { - return legendItemArray[0].width; - }); + thisImage.attr('xlink:href', dataURL); - var groupWidth = 40 + Math.max.apply(null, textWidths); + // resolve promise in onload handler instead of on 'load' to support IE11 + // see https://github.com/plotly/plotly.js/issues/1685 + // for more details + resolve(); + }; - opts._width += opts.tracegroupgap + groupWidth; - groupXOffsets.push(opts._width); - } + thisImage.on('error', errorHandler); - groups.each(function(d, i) { - _$drawing_76.setTranslate(this, groupXOffsets[i], 0); - }); + img.src = d.source; - groups.each(function() { - var group = _$d3_15.select(this), - groupTraces = group.selectAll('g.traces'), - groupHeight = 0; + function errorHandler() { + thisImage.remove(); + resolve(); + } + }.bind(this)); - groupTraces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height; + gd._promises.push(imagePromise); + } - _$drawing_76.setTranslate(this, - 0, - (5 + borderwidth + groupHeight + textHeight / 2)); + function applyAttributes(d) { + var thisImage = _$d3_15.select(this); - groupHeight += textHeight; - }); + // Axes if specified + var xa = _$axes_214.getFromId(gd, d.xref), + ya = _$axes_214.getFromId(gd, d.yref); - opts._height = Math.max(opts._height, groupHeight); - }); + var size = fullLayout._size, + width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, + height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; - opts._height += 10 + borderwidth * 2; - opts._width += borderwidth * 2; - } - else { - var rowHeight = 0, - maxTraceHeight = 0, - maxTraceWidth = 0, - offsetX = 0, - fullTracesWidth = 0, - traceGap = opts.tracegroupgap || 5, - oneRowLegend; + // Offsets for anchor positioning + var xOffset = width * anchors.x[d.xanchor].offset, + yOffset = height * anchors.y[d.yanchor].offset; - // calculate largest width for traces and use for width of all legend items - traces.each(function(d) { - maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); - fullTracesWidth += 40 + d[0].width + traceGap; - }); + var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; - // check if legend fits in one row - oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; - traces.each(function(d) { - var legendItem = d[0], - traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; + // Final positions + var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, + yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; - if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { - offsetX = 0; - rowHeight = rowHeight + maxTraceHeight; - opts._height = opts._height + maxTraceHeight; - // reset for next row - maxTraceHeight = 0; - } - _$drawing_76.setTranslate(this, - (borderwidth + offsetX), - (5 + borderwidth + legendItem.height / 2) + rowHeight); + // Construct the proper aspectRatio attribute + switch(d.sizing) { + case 'fill': + sizing += ' slice'; + break; - opts._width += traceGap + traceWidth; - opts._height = Math.max(opts._height, legendItem.height); + case 'stretch': + sizing = 'none'; + break; + } - // keep track of tallest trace in group - offsetX += traceGap + traceWidth; - maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); + thisImage.attr({ + x: xPos, + y: yPos, + width: width, + height: height, + preserveAspectRatio: sizing, + opacity: d.opacity }); - opts._width += borderwidth * 2; - opts._height += 10 + borderwidth * 2; - - } - - // make sure we're only getting full pixels - opts._width = Math.ceil(opts._width); - opts._height = Math.ceil(opts._height); - traces.each(function(d) { - var legendItem = d[0], - bg = _$d3_15.select(this).select('.legendtoggle'); + // Set proper clipping on images + var xId = xa ? xa._id : '', + yId = ya ? ya._id : '', + clipAxes = xId + yId; - _$drawing_76.setRect(bg, - 0, - -legendItem.height / 2, - (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, - legendItem.height + thisImage.call(_$drawing_76.setClipUrl, clipAxes ? + ('clip' + fullLayout._uid + clipAxes) : + null ); - }); -} + } -function expandMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; + var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') + .data(imageDataBelow), + imagesAbove = fullLayout._imageUpperLayer.selectAll('image') + .data(imageDataAbove); - var xanchor = 'left'; - if(_$anchor_utils_103.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_103.isCenterAnchor(opts)) { - xanchor = 'center'; - } + imagesBelow.enter().append('image'); + imagesAbove.enter().append('image'); - var yanchor = 'top'; - if(_$anchor_utils_103.isBottomAnchor(opts)) { - yanchor = 'bottom'; - } - else if(_$anchor_utils_103.isMiddleAnchor(opts)) { - yanchor = 'middle'; - } + imagesBelow.exit().remove(); + imagesAbove.exit().remove(); - // lastly check if the margin auto-expand has changed - _$plots_246.autoMargin(gd, 'legend', { - x: opts.x, - y: opts.y, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: opts._height * (FROM_BR[yanchor]), - t: opts._height * (FROM_TL[yanchor]) + imagesBelow.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); + }); + imagesAbove.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); }); -} -function expandHorizontalMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; + var allSubplots = Object.keys(fullLayout._plots); + for(i = 0; i < allSubplots.length; i++) { + subplot = allSubplots[i]; + var subplotObj = fullLayout._plots[subplot]; - var xanchor = 'left'; - if(_$anchor_utils_103.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_103.isCenterAnchor(opts)) { - xanchor = 'center'; - } + // filter out overlaid plots (which havd their images on the main plot) + // and gl2d plots (which don't support below images, at least not yet) + if(!subplotObj.imagelayer) continue; - // lastly check if the margin auto-expand has changed - _$plots_246.autoMargin(gd, 'legend', { - x: opts.x, - y: 0.5, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: 0, - t: 0 - }); -} + var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') + // even if there are no images on this subplot, we need to run + // enter and exit in case there were previously + .data(imageDataSubplot[subplot] || []); + + imagesOnSubplot.enter().append('image'); + imagesOnSubplot.exit().remove(); + + imagesOnSubplot.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); + }); + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -49391,19 +51752,19 @@ function expandHorizontalMargin(gd) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; - -var _$legend_111 = { +var _$images_102 = { moduleType: 'component', - name: 'legend', + name: 'images', - layoutAttributes: _$attributes_104, - supplyLayoutDefaults: _$legendDefaults_106, + layoutAttributes: _$attributes_98, + supplyLayoutDefaults: _$supplyLayoutDefaults_100, + includeBasePlot: _$makeIncludeComponents_224('images'), - draw: _$draw_107, - style: _$style_112 + draw: _$draw_101, + + convertCoords: _$convertCoords_99 }; /** @@ -49416,78 +51777,67 @@ var _$legend_111 = { 'use strict'; +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_50 = require('../color/attributes'); */; -var _$button_attributes_118 = { - step: { - valType: 'enumerated', + +var _$attributes_104 = { + bgcolor: { + valType: 'color', - values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], - dflt: 'month', - editType: 'plot', + editType: 'legend', }, - stepmode: { - valType: 'enumerated', + bordercolor: { + valType: 'color', + dflt: _$attributes_50.defaultLine, - values: ['backward', 'todate'], - dflt: 'backward', - editType: 'plot', + editType: 'legend', }, - count: { + borderwidth: { valType: 'number', - min: 0, - dflt: 1, - editType: 'plot', + dflt: 0, + + editType: 'legend', }, - label: { - valType: 'string', + font: _$font_attributes_240({ + editType: 'legend', - editType: 'plot', + }), + orientation: { + valType: 'enumerated', + values: ['v', 'h'], + dflt: 'v', + + editType: 'legend', }, - editType: 'plot' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_50 = require('../color/attributes'); */; -var __extendFlat_117 = _$extend_165.extendFlat; -/* removed: var _$button_attributes_118 = require('./button_attributes'); */; - -_$button_attributes_118 = __extendFlat_117(_$button_attributes_118, { - _isLinkedToArray: 'button', - - -}); - -var _$attributes_117 = { - visible: { - valType: 'boolean', + traceorder: { + valType: 'flaglist', + flags: ['reversed', 'grouped'], + extras: ['normal'], - editType: 'plot', + editType: 'legend', + + }, + tracegroupgap: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'legend', }, - - buttons: _$button_attributes_118, - x: { valType: 'number', min: -2, max: 3, + dflt: 1.02, - editType: 'plot', + editType: 'legend', }, xanchor: { @@ -49495,62 +51845,30 @@ var _$attributes_117 = { values: ['auto', 'left', 'center', 'right'], dflt: 'left', - editType: 'plot', + editType: 'legend', }, y: { valType: 'number', min: -2, max: 3, + dflt: 1, - editType: 'plot', + editType: 'legend', }, yanchor: { valType: 'enumerated', values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'bottom', - - editType: 'plot', - - }, - - font: _$font_attributes_240({ - editType: 'plot', - - }), - - bgcolor: { - valType: 'color', - dflt: _$attributes_50.lightLine, - - editType: 'plot', - - }, - activecolor: { - valType: 'color', - - editType: 'plot', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'plot', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, + dflt: 'auto', - editType: 'plot', + editType: 'legend', }, - editType: 'plot' + editType: 'legend' }; +var _$helpers_110 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49559,24 +51877,29 @@ var _$attributes_117 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; +'use strict'; -var _$constants_119 = { +_$helpers_110.legendGetsTrace = function legendGetsTrace(trace) { + // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? + // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. - // 'y' position pad above counter axis domain - yPad: 0.02, + // Note that we explicitly include showlegend: false, so a trace that *could* be + // in the legend but is not shown still counts toward the two traces you need to + // ensure the legend is shown by default, because this can still help disambiguate. + return trace.visible && (trace.showlegend !== undefined); +}; - // minimum button width (regardless of text size) - minButtonWidth: 30, +_$helpers_110.isGrouped = function isGrouped(legendLayout) { + return (legendLayout.traceorder || '').indexOf('grouped') !== -1; +}; - // buttons rect radii - rx: 3, - ry: 3, +_$helpers_110.isVertical = function isVertical(legendLayout) { + return legendLayout.orientation !== 'h'; +}; - // light fraction used to compute the 'activecolor' default - lightAmount: 25, - darkAmount: 10 +_$helpers_110.isReversed = function isReversed(legendLayout) { + return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; /** @@ -49587,152 +51910,91 @@ var _$constants_119 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$color_51 = require('../color'); */; - -/* removed: var _$attributes_117 = require('./attributes'); */; -/* removed: var _$button_attributes_118 = require('./button_attributes'); */; -/* removed: var _$constants_119 = require('./constants'); */; - - -var _$handleDefaults_120 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { - var selectorIn = containerIn.rangeselector || {}, - selectorOut = containerOut.rangeselector = {}; - - function coerce(attr, dflt) { - return _$lib_171.coerce(selectorIn, selectorOut, _$attributes_117, attr, dflt); - } - - var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - var posDflt = getPosDflt(containerOut, layout, counterAxes); - coerce('x', posDflt[0]); - coerce('y', posDflt[1]); - _$lib_171.noneOrAll(containerIn, containerOut, ['x', 'y']); - - coerce('xanchor'); - coerce('yanchor'); - - _$lib_171.coerceFont(coerce, 'font', layout.font); +'use strict'; - var bgColor = coerce('bgcolor'); - coerce('activecolor', _$color_51.contrast(bgColor, _$constants_119.lightAmount, _$constants_119.darkAmount)); - coerce('bordercolor'); - coerce('borderwidth'); -}; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -function buttonsDefaults(containerIn, containerOut, calendar) { - var buttonsIn = containerIn.buttons || [], - buttonsOut = containerOut.buttons = []; +/* removed: var _$attributes_104 = require('./attributes'); */; +/* removed: var _$layout_attributes_244 = require('../../plots/layout_attributes'); */; +/* removed: var _$helpers_110 = require('./helpers'); */; - var buttonIn, buttonOut; - function coerce(attr, dflt) { - return _$lib_171.coerce(buttonIn, buttonOut, _$button_attributes_118, attr, dflt); - } +var _$legendDefaults_106 = function legendDefaults(layoutIn, layoutOut, fullData) { + var containerIn = layoutIn.legend || {}; + var containerOut = {}; - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + var visibleTraces = 0; + var defaultOrder = 'normal'; - if(!_$lib_171.isPlainObject(buttonIn)) continue; + var defaultX, defaultY, defaultXAnchor, defaultYAnchor; - var step = coerce('step'); - if(step !== 'all') { - if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { - buttonOut.stepmode = 'backward'; - } - else { - coerce('stepmode'); - } + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - coerce('count'); + if(_$helpers_110.legendGetsTrace(trace)) { + visibleTraces++; + // always show the legend by default if there's a pie + if(_$registry_262.traceIs(trace, 'pie')) visibleTraces++; } - coerce('label'); + if((_$registry_262.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { + defaultOrder = _$helpers_110.isGrouped({traceorder: defaultOrder}) ? + 'grouped+reversed' : 'reversed'; + } - buttonOut._index = i; - buttonsOut.push(buttonOut); + if(trace.legendgroup !== undefined && trace.legendgroup !== '') { + defaultOrder = _$helpers_110.isReversed({traceorder: defaultOrder}) ? + 'reversed+grouped' : 'grouped'; + } } - return buttonsOut; -} - -function getPosDflt(containerOut, layout, counterAxes) { - var anchoredList = counterAxes.filter(function(ax) { - return layout[ax].anchor === containerOut._id; - }); - - var posY = 0; - for(var i = 0; i < anchoredList.length; i++) { - var domain = layout[anchoredList[i]].domain; - if(domain) posY = Math.max(domain[1], posY); + function coerce(attr, dflt) { + return _$lib_172.coerce(containerIn, containerOut, _$attributes_104, attr, dflt); } - return [containerOut.domain[0], posY + _$constants_119.yPad]; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 showLegend = _$lib_172.coerce(layoutIn, layoutOut, + _$layout_attributes_244, 'showlegend', visibleTraces > 1); -'use strict'; + if(showLegend === false) return; -/* removed: var _$d3_15 = require('d3'); */; + layoutOut.legend = containerOut; -var _$getUpdateObject_122 = function getUpdateObject(axisLayout, buttonLayout) { - var axName = axisLayout._name; - var update = {}; + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); + _$lib_172.coerceFont(coerce, 'font', layoutOut.font); - if(buttonLayout.step === 'all') { - update[axName + '.autorange'] = true; + coerce('orientation'); + if(containerOut.orientation === 'h') { + var xaxis = layoutIn.xaxis; + if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = 1.1; + defaultYAnchor = 'bottom'; + } + else { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = -0.1; + defaultYAnchor = 'top'; + } } - else { - var xrange = getXRange(axisLayout, buttonLayout); - update[axName + '.range[0]'] = xrange[0]; - update[axName + '.range[1]'] = xrange[1]; - } + coerce('traceorder', defaultOrder); + if(_$helpers_110.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); - return update; + coerce('x', defaultX); + coerce('xanchor', defaultXAnchor); + coerce('y', defaultY); + coerce('yanchor', defaultYAnchor); + _$lib_172.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -function getXRange(axisLayout, buttonLayout) { - var currentRange = axisLayout.range; - var base = new Date(axisLayout.r2l(currentRange[1])); - - var step = buttonLayout.step, - count = buttonLayout.count; - - var range0; - - switch(buttonLayout.stepmode) { - case 'backward': - range0 = axisLayout.l2r(+_$d3_15.time[step].utc.offset(base, -count)); - break; - - case 'todate': - var base2 = _$d3_15.time[step].utc.offset(base, -count); - - range0 = axisLayout.l2r(+_$d3_15.time[step].utc.ceil(base2)); - break; - } - - var range1 = currentRange[1]; - - return [range0, range1]; -} - +var _$anchor_utils_103 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49741,260 +52003,166 @@ function getXRange(axisLayout, buttonLayout) { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$d3_15 = require('d3'); */; - -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_216 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$anchor_utils_103 = require('../legend/anchor_utils'); */; - -/* removed: var _$alignment_151 = require('../../constants/alignment'); */; -var __LINE_SPACING_121 = _$alignment_151.LINE_SPACING; -var __FROM_TL_121 = _$alignment_151.FROM_TL; -var __FROM_BR_121 = _$alignment_151.FROM_BR; - -/* removed: var _$constants_119 = require('./constants'); */; -/* removed: var _$getUpdateObject_122 = require('./get_update_object'); */; - - -var _$draw_121 = function draw(gd) { - var fullLayout = gd._fullLayout; - - var selectors = fullLayout._infolayer.selectAll('.rangeselector') - .data(makeSelectorData(gd), selectorKeyFunc); - - selectors.enter().append('g') - .classed('rangeselector', true); - - selectors.exit().remove(); - - selectors.style({ - cursor: 'pointer', - 'pointer-events': 'all' - }); - - selectors.each(function(d) { - var selector = _$d3_15.select(this), - axisLayout = d, - selectorLayout = axisLayout.rangeselector; - - var buttons = selector.selectAll('g.button') - .data(selectorLayout.buttons); - - buttons.enter().append('g') - .classed('button', true); - - buttons.exit().remove(); - - buttons.each(function(d) { - var button = _$d3_15.select(this); - var update = _$getUpdateObject_122(axisLayout, d); - - d._isActive = isActive(axisLayout, d, update); - - button.call(drawButtonRect, selectorLayout, d); - button.call(drawButtonText, selectorLayout, d, gd); - - button.on('click', function() { - if(gd._dragged) return; - - _$registry_261.call('relayout', gd, update); - }); - - button.on('mouseover', function() { - d._isHovered = true; - button.call(drawButtonRect, selectorLayout, d); - }); - - button.on('mouseout', function() { - d._isHovered = false; - button.call(drawButtonRect, selectorLayout, d); - }); - }); - - reposition(gd, buttons, selectorLayout, axisLayout._name, selector); - }); - -}; - -function makeSelectorData(gd) { - var axes = _$axis_ids_216.list(gd, 'x', true); - var data = []; - - for(var i = 0; i < axes.length; i++) { - var axis = axes[i]; - - if(axis.rangeselector && axis.rangeselector.visible) { - data.push(axis); - } - } - - return data; -} - -function selectorKeyFunc(d) { - return d._id; -} - -function isActive(axisLayout, opts, update) { - if(opts.step === 'all') { - return axisLayout.autorange === true; - } - else { - var keys = Object.keys(update); - return ( - axisLayout.range[0] === update[keys[0]] && - axisLayout.range[1] === update[keys[1]] - ); - } -} - -function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); +'use strict'; - rect.enter().append('rect') - .classed('selector-rect', true); - rect.attr('shape-rendering', 'crispEdges'); +/** + * 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. + */ - rect.attr({ - 'rx': _$constants_119.rx, - 'ry': _$constants_119.ry - }); +_$anchor_utils_103.isRightAnchor = function isRightAnchor(opts) { + return ( + opts.xanchor === 'right' || + (opts.xanchor === 'auto' && opts.x >= 2 / 3) + ); +}; - rect.call(_$color_51.stroke, selectorLayout.bordercolor) - .call(_$color_51.fill, getFillColor(selectorLayout, d)) - .style('stroke-width', selectorLayout.borderwidth + 'px'); -} +_$anchor_utils_103.isCenterAnchor = function isCenterAnchor(opts) { + return ( + opts.xanchor === 'center' || + (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) + ); +}; -function getFillColor(selectorLayout, d) { - return (d._isActive || d._isHovered) ? - selectorLayout.activecolor : - selectorLayout.bgcolor; -} +_$anchor_utils_103.isBottomAnchor = function isBottomAnchor(opts) { + return ( + opts.yanchor === 'bottom' || + (opts.yanchor === 'auto' && opts.y <= 1 / 3) + ); +}; -function drawButtonText(button, selectorLayout, d, gd) { - function textLayout(s) { - _$svg_text_utils_192.convertToTspans(s, gd); - } +_$anchor_utils_103.isMiddleAnchor = function isMiddleAnchor(opts) { + return ( + opts.yanchor === 'middle' || + (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) + ); +}; - var text = button.selectAll('text') - .data([0]); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); +'use strict'; - text.attr('text-anchor', 'middle'); +var _$constants_105 = { + scrollBarWidth: 6, + scrollBarMinHeight: 20, + scrollBarColor: '#808BA4', + scrollBarMargin: 4 +}; - text.call(_$drawing_76.font, selectorLayout.font) - .text(getLabel(d)) - .call(textLayout); -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function getLabel(opts) { - if(opts.label) return opts.label; - if(opts.step === 'all') return 'all'; +'use strict'; - return opts.count + opts.step.charAt(0); -} +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$helpers_110 = require('./helpers'); */; -function reposition(gd, buttons, opts, axName, selector) { - var width = 0; - var height = 0; - var borderWidth = opts.borderwidth; +var _$getLegendData_108 = function getLegendData(calcdata, opts) { + var lgroupToTraces = {}, + lgroups = [], + hasOneNonBlankGroup = false, + slicesShown = {}, + lgroupi = 0; - buttons.each(function() { - var button = _$d3_15.select(this); - var text = button.select('.selector-text'); + var i, j; - var tHeight = opts.font.size * __LINE_SPACING_121; - var hEff = Math.max(tHeight * _$svg_text_utils_192.lineCount(text), 16) + 3; + function addOneItem(legendGroup, legendItem) { + // each '' legend group is treated as a separate group + if(legendGroup === '' || !_$helpers_110.isGrouped(opts)) { + var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? - height = Math.max(height, hEff); - }); + lgroups.push(uniqueGroup); + lgroupToTraces[uniqueGroup] = [[legendItem]]; + lgroupi++; + } + else if(lgroups.indexOf(legendGroup) === -1) { + lgroups.push(legendGroup); + hasOneNonBlankGroup = true; + lgroupToTraces[legendGroup] = [[legendItem]]; + } + else lgroupToTraces[legendGroup].push([legendItem]); + } - buttons.each(function() { - var button = _$d3_15.select(this); - var rect = button.select('.selector-rect'); - var text = button.select('.selector-text'); + // build an { legendgroup: [cd0, cd0], ... } object + for(i = 0; i < calcdata.length; i++) { + var cd = calcdata[i], + cd0 = cd[0], + trace = cd0.trace, + lgroup = trace.legendgroup; - var tWidth = text.node() && _$drawing_76.bBox(text.node()).width; - var tHeight = opts.font.size * __LINE_SPACING_121; - var tLines = _$svg_text_utils_192.lineCount(text); + if(!_$helpers_110.legendGetsTrace(trace) || !trace.showlegend) continue; - var wEff = Math.max(tWidth + 10, _$constants_119.minButtonWidth); + if(_$registry_262.traceIs(trace, 'pie')) { + if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; - // TODO add MathJax support + for(j = 0; j < cd.length; j++) { + var labelj = cd[j].label; - // TODO add buttongap attribute + if(!slicesShown[lgroup][labelj]) { + addOneItem(lgroup, { + label: labelj, + color: cd[j].color, + i: cd[j].i, + trace: trace + }); - button.attr('transform', 'translate(' + - (borderWidth + width) + ',' + borderWidth + - ')'); + slicesShown[lgroup][labelj] = true; + } + } + } - rect.attr({ - x: 0, - y: 0, - width: wEff, - height: height - }); + else addOneItem(lgroup, cd0); + } - _$svg_text_utils_192.positionText(text, wEff / 2, - height / 2 - ((tLines - 1) * tHeight / 2) + 3); + // won't draw a legend in this case + if(!lgroups.length) return []; - width += wEff + 5; - }); + // rearrange lgroupToTraces into a d3-friendly array of arrays + var lgroupsLength = lgroups.length, + ltraces, + legendData; - var graphSize = gd._fullLayout._size; - var lx = graphSize.l + graphSize.w * opts.x; - var ly = graphSize.t + graphSize.h * (1 - opts.y); + if(hasOneNonBlankGroup && _$helpers_110.isGrouped(opts)) { + legendData = new Array(lgroupsLength); - var xanchor = 'left'; - if(_$anchor_utils_103.isRightAnchor(opts)) { - lx -= width; - xanchor = 'right'; - } - if(_$anchor_utils_103.isCenterAnchor(opts)) { - lx -= width / 2; - xanchor = 'center'; + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]]; + legendData[i] = _$helpers_110.isReversed(opts) ? ltraces.reverse() : ltraces; + } } + else { + // collapse all groups into one if all groups are blank + legendData = [new Array(lgroupsLength)]; - var yanchor = 'top'; - if(_$anchor_utils_103.isBottomAnchor(opts)) { - ly -= height; - yanchor = 'bottom'; - } - if(_$anchor_utils_103.isMiddleAnchor(opts)) { - ly -= height / 2; - yanchor = 'middle'; + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]][0]; + legendData[0][_$helpers_110.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; + } + lgroupsLength = 1; } - width = Math.ceil(width); - height = Math.ceil(height); - lx = Math.round(lx); - ly = Math.round(ly); - - _$plots_246.autoMargin(gd, axName + '-range-selector', { - x: opts.x, - y: opts.y, - l: width * __FROM_TL_121[xanchor], - r: width * __FROM_BR_121[xanchor], - b: height * __FROM_BR_121[yanchor], - t: height * __FROM_TL_121[yanchor] - }); - - selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); -} + // needed in repositionLegend + opts._lgroupsLength = lgroupsLength; + return legendData; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -50006,150 +52174,220 @@ function reposition(gd, buttons, opts, axName, selector) { 'use strict'; -var _$rangeselector_123 = { - moduleType: 'component', - name: 'rangeselector', +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; - schema: { - subplots: { - xaxis: {rangeselector: _$attributes_117} +var SHOWISOLATETIP = true; + +var _$handleClick_109 = function handleClick(g, gd, numClicks) { + if(gd._dragged || gd._editing) return; + + var hiddenSlices = gd._fullLayout.hiddenlabels ? + gd._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] = []; } - }, - layoutAttributes: _$attributes_117, - handleDefaults: _$handleDefaults_120, + if(attrIndices.indexOf(traceIndex) === -1) { + attrIndices.push(traceIndex); + attrIndex = attrIndices.length - 1; + } - draw: _$draw_121 -}; + valueArray[attrIndex] = value; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 attrIndex; + } -'use strict'; + function setVisibility(fullTrace, visibility) { + var fullInput = fullTrace._fullInput; + if(_$registry_262.hasTransform(fullInput, 'groupby')) { + var kcont = carrs[fullInput.index]; + if(!kcont) { + var groupbyIndices = _$registry_262.getTransformIndices(fullInput, 'groupby'); + var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; + kcont = _$lib_172.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + carrs[fullInput.index] = kcont; + } -/* removed: var _$attributes_50 = require('../color/attributes'); */; + var curState = kcont.get(fullTrace._group); -var _$attributes_124 = { - bgcolor: { - valType: 'color', - dflt: _$attributes_50.background, - - editType: 'plot', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_50.defaultLine, - - editType: 'plot', - - }, - borderwidth: { - valType: 'integer', - dflt: 0, - min: 0, - - editType: 'plot', - - }, - autorange: { - valType: 'boolean', - dflt: true, - - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, - - }, - range: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} - ], - editType: 'calc', - impliedEdits: {'autorange': false}, - - }, - thickness: { - valType: 'number', - dflt: 0.15, - min: 0, - max: 1, - - editType: 'plot', - - }, - visible: { - valType: 'boolean', - dflt: true, - - editType: 'calc', - - }, - editType: 'calc' -}; + // 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; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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; -'use strict'; + insertUpdate(fullInput.index, 'visible', nextVisibility); + } + } -var _$constants_126 = { + if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { + _$lib_172.notifier(_$lib_172._(gd, 'Double-click on legend to isolate one trace'), 'long'); + SHOWISOLATETIP = false; + } else { + SHOWISOLATETIP = false; + } - // attribute container name - name: 'rangeslider', + if(_$registry_262.traceIs(fullTrace, 'pie')) { + var thisLabel = legendItem.label, + thisLabelIndex = hiddenSlices.indexOf(thisLabel); - // class names + if(numClicks === 1) { + if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); + else hiddenSlices.splice(thisLabelIndex, 1); + } else if(numClicks === 2) { + 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 = []; + } + } - containerClassName: 'rangeslider-container', - bgClassName: 'rangeslider-bg', - rangePlotClassName: 'rangeslider-rangeplot', + _$registry_262.call('relayout', 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); + } + } + } - maskMinClassName: 'rangeslider-mask-min', - maskMaxClassName: 'rangeslider-mask-max', - slideBoxClassName: 'rangeslider-slidebox', + if(numClicks === 1) { + var nextVisibility; - grabberMinClassName: 'rangeslider-grabber-min', - grabAreaMinClassName: 'rangeslider-grabarea-min', - handleMinClassName: 'rangeslider-handle-min', + switch(fullTrace.visible) { + case true: + nextVisibility = 'legendonly'; + break; + case false: + nextVisibility = false; + break; + case 'legendonly': + nextVisibility = true; + break; + } - grabberMaxClassName: 'rangeslider-grabber-max', - grabAreaMaxClassName: 'rangeslider-grabarea-max', - handleMaxClassName: 'rangeslider-handle-max', + 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(numClicks === 2) { + // 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, otherState; + var isIsolated = true; + for(i = 0; i < fullData.length; i++) { + isClicked = fullData[i] === fullTrace; + if(isClicked) continue; - maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', - maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', + isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - // style constants + if(!isInGroup && fullData[i].visible === true && !_$registry_262.traceIs(fullData[i], 'notLegendIsolatable')) { + isIsolated = false; + break; + } + } - maskColor: 'rgba(0,0,0,0.4)', - maskOppAxisColor: 'rgba(0,0,0,0.2)', + for(i = 0; i < fullData.length; i++) { + // False is sticky; we don't change it. + if(fullData[i].visible === false) continue; - slideBoxFill: 'transparent', - slideBoxCursor: 'ew-resize', + if(_$registry_262.traceIs(fullData[i], 'notLegendIsolatable')) { + continue; + } - grabAreaFill: 'transparent', - grabAreaCursor: 'col-resize', - grabAreaWidth: 10, + switch(fullTrace.visible) { + case 'legendonly': + setVisibility(fullData[i], true); + break; + case true: + otherState = isIsolated ? true : 'legendonly'; + isClicked = fullData[i] === fullTrace; + isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); + setVisibility(fullData[i], isInGroup ? true : otherState); + break; + } + } + } - handleWidth: 4, - handleRadius: 1, - handleStrokeWidth: 1, + for(i = 0; i < carrs.length; i++) { + kcont = carrs[i]; + if(!kcont) continue; + var update = kcont.constructUpdate(); - extraPad: 15 + 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_262.call('restyle', gd, attrUpdate, attrIndices); + } }; +var _$helpers_361 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -50160,32 +52398,37 @@ var _$constants_126 = { 'use strict'; -var listAxes = _$axis_ids_216.list; -var __getAutoRange_125 = _$autorange_212.getAutoRange; -/* removed: var _$constants_126 = require('./constants'); */; - -var _$calcAutorange_125 = 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. +/* removed: var _$lib_172 = require('../../lib'); */; - for(var i = 0; i < axes.length; i++) { - var ax = axes[i], - opts = ax[_$constants_126.name]; +_$helpers_361.formatPiePercent = function formatPiePercent(v, separators) { + var vRounded = (v * 100).toPrecision(3); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_172.numSeparate(vRounded, separators) + '%'; +}; - // Don't try calling getAutoRange if _min and _max are filled in. - // This happens on updates where the calc step is skipped. +_$helpers_361.formatPieValue = function formatPieValue(v, separators) { + var vRounded = v.toPrecision(10); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_172.numSeparate(vRounded, separators); +}; - if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { - opts._input.autorange = true; - opts._input.range = opts.range = __getAutoRange_125(ax); - } +_$helpers_361.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) return v; } }; +_$helpers_361.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_361.getFirstFilled(item, indices); + else if(item) return item; +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -50196,31 +52439,17 @@ var _$calcAutorange_125 = function calcAutorange(gd) { 'use strict'; -var _$oppaxis_attributes_130 = { - // not really a 'subplot' attribute container, - // but this is the flag we use to denote attributes that - // support yaxis, yaxis2, yaxis3, ... counters - _isSubplotObj: true, +/* removed: var _$color_51 = require('../../components/color'); */; +var castOption = _$helpers_361.castOption; - 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' +var _$styleOne_367 = function styleOne(s, pt, trace) { + var line = trace.marker.line; + var lineColor = castOption(line.color, pt.pts) || _$color_51.defaultLine; + var lineWidth = castOption(line.width, pt.pts) || 0; + + s.style({'stroke-width': lineWidth}) + .call(_$color_51.fill, pt.color) + .call(_$color_51.stroke, lineColor); }; /** @@ -50233,724 +52462,976 @@ var _$oppaxis_attributes_130 = { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$attributes_124 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_130 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_216 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$d3_15 = require('d3'); */; -var _$handleDefaults_127 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$color_51 = require('../color'); */; - // not super proud of this (maybe store _ in axis object instead - if(!_$lib_171.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; - } +/* removed: var _$subtypes_391 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_367 = require('../../traces/pie/style_one'); */; - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; +var _$style_112 = function style(s, gd) { + s.each(function(d) { + var traceGroup = _$d3_15.select(this); - function coerce(attr, dflt) { - return _$lib_171.coerce(containerIn, containerOut, _$attributes_124, attr, dflt); - } + var layers = _$lib_172.ensureSingle(traceGroup, 'g', 'layers'); + layers.style('opacity', d[0].trace.opacity); - function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_171.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_130, attr, dflt); + var fill = layers + .selectAll('g.legendfill') + .data([d]); + fill.enter().append('g') + .classed('legendfill', true); + + var line = layers + .selectAll('g.legendlines') + .data([d]); + line.enter().append('g') + .classed('legendlines', true); + + var symbol = layers + .selectAll('g.legendsymbols') + .data([d]); + symbol.enter().append('g') + .classed('legendsymbols', true); + + symbol.selectAll('g.legendpoints') + .data([d]) + .enter().append('g') + .classed('legendpoints', true); + }) + .each(styleBars) + .each(styleBoxes) + .each(stylePies) + .each(styleLines) + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); + + function styleLines(d) { + var trace = d[0].trace; + var showFill = trace.visible && trace.fill && trace.fill !== 'none'; + var showLine = _$subtypes_391.hasLines(trace); + var contours = trace.contours; + + if(contours && contours.type === 'constraint') { + showLine = contours.showlines; + showFill = contours._operation !== '='; + } + + var fill = _$d3_15.select(this).select('.legendfill').selectAll('path') + .data(showFill ? [d] : []); + fill.enter().append('path').classed('js-fill', true); + fill.exit().remove(); + fill.attr('d', 'M5,0h30v6h-30z') + .call(_$drawing_76.fillGroupStyle); + + var line = _$d3_15.select(this).select('.legendlines').selectAll('path') + .data(showLine ? [d] : []); + line.enter().append('path').classed('js-line', true) + .attr('d', 'M5,0h30'); + line.exit().remove(); + line.call(_$drawing_76.lineGroupStyle); } - var visible = coerce('visible'); - if(!visible) return; + function stylePoints(d) { + var d0 = d[0], + trace = d0.trace, + showMarkers = _$subtypes_391.hasMarkers(trace), + showText = _$subtypes_391.hasText(trace), + showLines = _$subtypes_391.hasLines(trace); - coerce('bgcolor', layoutOut.plot_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('thickness'); + var dMod, tMod; - axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); - coerce('range'); + // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; + // use d0.trace to infer arrayOk attributes - var subplots = layoutOut._subplots; - if(subplots) { - var yIds = subplots.cartesian - .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_216.name2id(axName); - }) - .map(function(subplotId) { - return subplotId.substr(subplotId.indexOf('y'), subplotId.length); - }); - var yNames = _$lib_171.simpleMap(yIds, _$axis_ids_216.id2name); - for(var i = 0; i < yNames.length; i++) { - var yName = yNames[i]; + function boundVal(attrIn, arrayToValFn, bounds) { + var valIn = _$lib_172.nestedProperty(trace, attrIn).get(), + valToBound = (Array.isArray(valIn) && arrayToValFn) ? + arrayToValFn(valIn) : valIn; - var rangeContainerIn = containerIn[yName] || {}; - var rangeContainerOut = containerOut[yName] = {}; + if(bounds) { + if(valToBound < bounds[0]) return bounds[0]; + else if(valToBound > bounds[1]) return bounds[1]; + } + return valToBound; + } - var yAxOut = layoutOut[yName]; + function pickFirst(array) { return array[0]; } - var rangemodeDflt; - if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { - rangemodeDflt = 'fixed'; + // constrain text, markers, etc so they'll fit on the legend + if(showMarkers || showText || showLines) { + var dEdit = {}, + tEdit = {}; + + if(showMarkers) { + dEdit.mc = boundVal('marker.color', pickFirst); + dEdit.mo = boundVal('marker.opacity', _$lib_172.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_172.mean, [2, 16]); + dEdit.mlc = boundVal('marker.line.color', pickFirst); + dEdit.mlw = boundVal('marker.line.width', _$lib_172.mean, [0, 5]); + tEdit.marker = { + sizeref: 1, + sizemin: 1, + sizemode: 'diameter' + }; } - var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); - if(rangeMode !== 'match') { - coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); + if(showLines) { + tEdit.line = { + width: boundVal('line.width', pickFirst, [0, 10]) + }; } - yAxOut._rangesliderAutorange = (rangeMode === 'auto'); - } - } - // to map back range slider (auto) range - containerOut._input = containerIn; -}; + if(showText) { + dEdit.tx = 'Aa'; + dEdit.tp = boundVal('textposition', pickFirst); + dEdit.ts = 10; + dEdit.tc = boundVal('textfont.color', pickFirst); + dEdit.tf = boundVal('textfont.family', pickFirst); + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + dMod = [_$lib_172.minExtend(d0, dEdit)]; + tMod = _$lib_172.minExtend(trace, tEdit); + } -'use strict'; + var ptgroup = _$d3_15.select(this).select('g.legendpoints'); -/* removed: var _$d3_15 = require('d3'); */; + var pts = ptgroup.selectAll('path.scatterpts') + .data(showMarkers ? dMod : []); + pts.enter().append('path').classed('scatterpts', true) + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.call(_$drawing_76.pointStyle, tMod, gd); -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; + // 'mrc' is set in pointStyle and used in textPointStyle: + // constrain it here + if(showMarkers) dMod[0].mrc = 3; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$titles_144 = require('../titles'); */; + var txt = ptgroup.selectAll('g.pointtext') + .data(showText ? dMod : []); + txt.enter() + .append('g').classed('pointtext', true) + .append('text').attr('transform', 'translate(20,0)'); + txt.exit().remove(); + txt.selectAll('text').call(_$drawing_76.textPointStyle, tMod, gd); + } -/* removed: var _$cartesian_224 = require('../../plots/cartesian'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; + function styleBars(d) { + var trace = d[0].trace, + marker = trace.marker || {}, + markerLine = marker.line || {}, + barpath = _$d3_15.select(this).select('g.legendpoints') + .selectAll('path.legendbar') + .data(_$registry_262.traceIs(trace, 'bar') ? [d] : []); + barpath.enter().append('path').classed('legendbar', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + barpath.exit().remove(); + barpath.each(function(d) { + var p = _$d3_15.select(this), + d0 = d[0], + w = (d0.mlw + 1 || markerLine.width + 1) - 1; -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$setCursor_190 = require('../../lib/setcursor'); */; + p.style('stroke-width', w + 'px') + .call(_$color_51.fill, d0.mc || marker.color); -/* removed: var _$constants_126 = require('./constants'); */; + if(w) { + p.call(_$color_51.stroke, d0.mlc || markerLine.color); + } + }); + } -var _$draw_128 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); + function styleBoxes(d) { + var trace = d[0].trace, + pts = _$d3_15.select(this).select('g.legendpoints') + .selectAll('path.legendbox') + .data(_$registry_262.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendbox', true) + // if we want the median bar, prepend M6,0H-6 + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.each(function() { + var w = trace.line.width, + p = _$d3_15.select(this); - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ + p.style('stroke-width', w + 'px') + .call(_$color_51.fill, trace.fillcolor); - function keyFunction(axisOpts) { - return axisOpts._name; + if(w) { + _$color_51.stroke(p, trace.line.color); + } + }); } - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_126.containerClassName) - .data(rangeSliderData, keyFunction); + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_15.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_15.select(this); - rangeSliders.enter().append('g') - .classed(_$constants_126.containerClassName, true) - .attr('pointer-events', 'all'); + p.style('stroke-width', w + 'px') + .call(_$color_51.fill, container.fillcolor); - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_15.select(this), - opts = axisOpts[_$constants_126.name]; + if(w) { + _$color_51.stroke(p, container.line.color); + } + }); + } - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_15.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_15.select(this); - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); + p.style('fill', 'none') + .call(_$drawing_76.dashLine, container.line.dash, w); - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; + if(w) { + _$color_51.stroke(p, container.line.color); + } + }); + } - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_15.select(this), - opts = axisOpts[_$constants_126.name], - oppAxisOpts = fullLayout[_$axes_213.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_213.id2name(axisOpts.anchor)]; + function stylePies(d) { + var trace = d[0].trace, + pts = _$d3_15.select(this).select('g.legendpoints') + .selectAll('path.legendpie') + .data(_$registry_262.traceIs(trace, 'pie') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendpie', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; + if(pts.size()) pts.call(_$styleOne_367, d[0], trace); + } +}; - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - axisOpts.cleanRange('rangeslider.range'); +'use strict'; +/* removed: var _$d3_15 = require('d3'); */; - // update range slider dimensions +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$handleClick_109 = require('./handle_click'); */; - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; +/* removed: var _$constants_105 = require('./constants'); */; +/* removed: var _$interactions_153 = require('../../constants/interactions'); */; +/* removed: var _$alignment_151 = require('../../constants/alignment'); */; +var __LINE_SPACING_107 = _$alignment_151.LINE_SPACING; +var __FROM_TL_107 = _$alignment_151.FROM_TL; +var FROM_BR = _$alignment_151.FROM_BR; - var oppBottom = Infinity; - var subplotData = _$axes_213.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_213.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); - } +/* removed: var _$getLegendData_108 = require('./get_legend_data'); */; +/* removed: var _$style_112 = require('./style'); */; +/* removed: var _$helpers_110 = require('./helpers'); */; +/* removed: var _$anchor_utils_103 = require('./anchor_utils'); */; - opts._id = _$constants_126.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; +var DBLCLICKDELAY = _$interactions_153.DBLCLICKDELAY; - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); +var _$draw_107 = function draw(gd) { + var fullLayout = gd._fullLayout; + var clipId = 'legend' + fullLayout._uid; - var x = Math.round(margin.l + (graphSize.w * domain[0])); + if(!fullLayout._infolayer || !gd.calcdata) return; - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_126.extraPad - ); + if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); + var opts = fullLayout.legend, + legendData = fullLayout.showlegend && _$getLegendData_108(gd.calcdata, opts), + hiddenSlices = fullLayout.hiddenlabels || []; - // update data <--> pixel coordinate conversion methods + if(!fullLayout.showlegend || !legendData.length) { + fullLayout._infolayer.selectAll('.legend').remove(); + fullLayout._topdefs.select('#' + clipId).remove(); - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; + _$plots_246.autoMargin(gd, 'legend'); + return; + } - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; + var firstRender = false; + var legend = _$lib_172.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; - }; + var clipPath = _$lib_172.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - opts._rl = [range0, range1]; + var bg = _$lib_172.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; + bg.call(_$color_51.stroke, opts.bordercolor) + .call(_$color_51.fill, opts.bgcolor) + .style('stroke-width', opts.borderwidth + 'px'); - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; - } + var scrollBox = _$lib_172.ensureSingle(legend, 'g', 'scrollbox'); - // update inner nodes + var scrollBar = _$lib_172.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ + rx: 20, + ry: 3, + width: 0, + height: 0 + }) + .call(_$color_51.fill, '#808BA4'); + }); - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); + var groups = scrollBox.selectAll('g.groups') + .data(legendData); - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); + groups.enter().append('g') + .attr('class', 'groups'); - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + groups.exit().remove(); - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_144.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' - } - }); - } + var traces = groups.selectAll('g.traces') + .data(_$lib_172.identity); - // update margins - _$plots_246.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_126.extraPad + opts._offsetShift * 2 + traces.enter().append('g').attr('class', 'traces'); + traces.exit().remove(); + + traces.call(_$style_112, gd) + .style('opacity', function(d) { + var trace = d[0].trace; + if(_$registry_262.traceIs(trace, 'pie')) { + return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; + } else { + return trace.visible === 'legendonly' ? 0.5 : 1; + } + }) + .each(function() { + _$d3_15.select(this) + .call(drawTexts, gd) + .call(setupTraceToggle, gd); }); - }); -}; -function makeRangeSliderData(fullLayout) { - var axes = _$axes_213.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_126.name, - out = []; + if(firstRender) { + computeLegendDimensions(gd, groups, traces); + expandMargin(gd); + } + + // Position and size the legend + var lxMin = 0, + lxMax = fullLayout.width, + lyMin = 0, + lyMax = fullLayout.height; + + computeLegendDimensions(gd, groups, traces); + + if(opts._height > lyMax) { + // If the legend doesn't fit in the plot area, + // do not expand the vertical margins. + expandHorizontalMargin(gd); + } else { + expandMargin(gd); + } - if(fullLayout._has('gl2d')) return out; + // Scroll section must be executed after repositionLegend. + // It requires the legend width, height, x and y to position the scrollbox + // and these values are mutated in repositionLegend. + var gs = fullLayout._size, + lx = gs.l + gs.w * opts.x, + ly = gs.t + gs.h * (1 - opts.y); - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; + if(_$anchor_utils_103.isRightAnchor(opts)) { + lx -= opts._width; + } + else if(_$anchor_utils_103.isCenterAnchor(opts)) { + lx -= opts._width / 2; + } - if(ax[name] && ax[name].visible) out.push(ax); + if(_$anchor_utils_103.isBottomAnchor(opts)) { + ly -= opts._height; + } + else if(_$anchor_utils_103.isMiddleAnchor(opts)) { + ly -= opts._height / 2; } - return out; -} + // Make sure the legend left and right sides are visible + var legendWidth = opts._width, + legendWidthMax = gs.w; -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_126.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_126.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_126.grabAreaMaxClassName).node(); + if(legendWidth > legendWidthMax) { + lx = gs.l; + legendWidth = legendWidthMax; + } + else { + if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; + if(lx < lxMin) lx = lxMin; + legendWidth = Math.min(lxMax - lx, opts._width); + } - rangeSlider.on('mousedown', function() { - var event = _$d3_15.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); + // Make sure the legend top and bottom are visible + // (legends with a scroll bar are not allowed to stretch beyond the extended + // margins) + var legendHeight = opts._height, + legendHeightMax = gs.h; - var dragCover = _$dragelement_73.coverSlip(); + if(legendHeight > legendHeightMax) { + ly = gs.t; + legendHeight = legendHeightMax; + } + else { + if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; + if(ly < lyMin) ly = lyMin; + legendHeight = Math.min(lyMax - ly, opts._height); + } - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); + // Set size and position of all the elements that make up a legend: + // legend, background and border, scroll box and scroll bar + _$drawing_76.setTranslate(legend, lx, ly); - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; + // to be safe, remove previous listeners + scrollBar.on('.drag', null); + legend.on('wheel', null); - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; + if(opts._height <= legendHeight || gd._context.staticPlot) { + // if scrollbar should not be shown. + bg.attr({ + width: legendWidth - opts.borderwidth, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; + _$drawing_76.setTranslate(scrollBox, 0, 0); - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; + clipPath.select('rect').attr({ + width: legendWidth - 2 * opts.borderwidth, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + }); - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } + _$drawing_76.setClipUrl(scrollBox, clipId); - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } + _$drawing_76.setRect(scrollBar, 0, 0, 0, 0); + delete opts._scrollY; + } + else { + var scrollBarHeight = Math.max(_$constants_105.scrollBarMinHeight, + legendHeight * legendHeight / opts._height); + var scrollBarYMax = legendHeight - + scrollBarHeight - + 2 * _$constants_105.scrollBarMargin; + var scrollBoxYMax = opts._height - legendHeight; + var scrollRatio = scrollBarYMax / scrollBoxYMax; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; + var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); - _$setCursor_190(_$d3_15.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); - } + // increase the background and clip-path width + // by the scrollbar width and margin + bg.attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_105.scrollBarWidth + + _$constants_105.scrollBarMargin, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_171.removeElement(dragCover); - } - }); -} + clipPath.select('rect').attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_105.scrollBarWidth + + _$constants_105.scrollBarMargin, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + scrollBoxY + }); -function setDataRange(rangeSlider, gd, axisOpts, opts) { + _$drawing_76.setClipUrl(scrollBox, clipId); - function clamp(v) { - return axisOpts.l2r(_$lib_171.constrain(v, opts._rl[0], opts._rl[1])); - } + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); + legend.on('wheel', function() { + scrollBoxY = _$lib_172.constrain( + opts._scrollY + + _$d3_15.event.deltaY / scrollBarYMax * scrollBoxYMax, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { + _$d3_15.event.preventDefault(); + } + }); - window.requestAnimationFrame(function() { - _$registry_261.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} + var eventY0, scrollBoxY0; -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_126.handleWidth / 2; + var drag = _$d3_15.behavior.drag() + .on('dragstart', function() { + eventY0 = _$d3_15.event.sourceEvent.clientY; + scrollBoxY0 = scrollBoxY; + }) + .on('drag', function() { + var e = _$d3_15.event.sourceEvent; + if(e.buttons === 2 || e.ctrlKey) return; - function clamp(v) { - return _$lib_171.constrain(v, 0, opts._width); - } + scrollBoxY = _$lib_172.constrain( + (e.clientY - eventY0) / scrollRatio + scrollBoxY0, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + }); - function clampOppAxis(v) { - return _$lib_171.constrain(v, 0, opts._height); + scrollBar.call(drag); } - function clampHandle(v) { - return _$lib_171.constrain(v, -hw2, opts._width + hw2); - } - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { + opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; + _$drawing_76.setTranslate(scrollBox, 0, -scrollBoxY); - rangeSlider.select('rect.' + _$constants_126.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); + _$drawing_76.setRect( + scrollBar, + legendWidth, + _$constants_105.scrollBarMargin + scrollBoxY * scrollRatio, + _$constants_105.scrollBarWidth, + scrollBarHeight + ); + clipPath.select('rect').attr({ + y: opts.borderwidth + scrollBoxY + }); + } - rangeSlider.select('rect.' + _$constants_126.maskMinClassName) - .attr('width', pixelMin); + if(gd._context.edits.legendPosition) { + var xf, yf, x0, y0; - rangeSlider.select('rect.' + _$constants_126.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + legend.classed('cursor-move', true); - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + _$dragelement_73.init({ + element: legend.node(), + gd: gd, + prepFn: function() { + var transform = _$drawing_76.getTranslate(legend); - rangeSlider.select('rect.' + _$constants_126.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + x0 = transform.x; + y0 = transform.y; + }, + moveFn: function(dx, dy) { + var newX = x0 + dx, + newY = y0 + dy; - rangeSlider.select('rect.' + _$constants_126.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); + _$drawing_76.setTranslate(legend, newX, newY); - rangeSlider.select('rect.' + _$constants_126.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); + xf = _$dragelement_73.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); + yf = _$dragelement_73.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); + }, + doneFn: function() { + if(xf !== undefined && yf !== undefined) { + _$registry_262.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + } + }, + clickFn: function(numClicks, e) { + var clickedTrace = + fullLayout._infolayer.selectAll('g.traces').filter(function() { + var bbox = this.getBoundingClientRect(); + return (e.clientX >= bbox.left && e.clientX <= bbox.right && + e.clientY >= bbox.top && e.clientY <= bbox.bottom); + }); + if(clickedTrace.size() > 0) { + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { + _$handleClick_109(clickedTrace, gd, numClicks); + }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + _$handleClick_109(clickedTrace, gd, numClicks); + } + } + } + }); } +}; - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; +function drawTexts(g, gd) { + var legendItem = g.data()[0][0], + fullLayout = gd._fullLayout, + trace = legendItem.trace, + isPie = _$registry_262.traceIs(trace, 'pie'), + traceIndex = trace.index, + name = isPie ? legendItem.label : trace.name; - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; + var text = _$lib_172.ensureSingle(g, 'text', 'legendtext'); - rangeSlider.select('g.' + _$constants_126.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + text.attr('text-anchor', 'start') + .classed('user-select-none', true) + .call(_$drawing_76.font, fullLayout.legend.font) + .text(name); - rangeSlider.select('g.' + _$constants_126.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} + function textLayout(s) { + _$svg_text_utils_193.convertToTspans(s, gd, function() { + computeTextDimensions(g, gd); + }); + } -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_126.bgClassName) - .data([0]); + if(gd._context.edits.legendText && !isPie) { + text.call(_$svg_text_utils_193.makeEditable, {gd: gd}) + .call(textLayout) + .on('edit', function(text) { + this.text(text) + .call(textLayout); - bg.enter().append('rect') - .classed(_$constants_126.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); + var origText = text; - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; + if(!this.text()) text = ' \u0020\u0020 '; - var offsetShift = -opts._offsetShift; - var lw = _$drawing_76.crispRound(gd, opts.borderwidth); + var fullInput = legendItem.trace._fullInput || {}; + var update = {}; - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} + if(_$registry_262.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_262.getTransformIndices(fullInput, 'groupby'); + var index = groupbyIndices[groupbyIndices.length - 1]; -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; + var kcont = _$lib_172.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); + if(origText === '') { + kcont.remove(legendItem.trace._group); + } else { + kcont.set(legendItem.trace._group, text); + } - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + update = kcont.constructUpdate(); + } else { + update.name = text; + } - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); + return _$registry_262.call('restyle', gd, update, traceIndex); + }); + } else { + textLayout(text); + } } -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_213.getSubplots(gd, axisOpts), - calcData = gd.calcdata; +function setupTraceToggle(g, gd) { + var newMouseDownTime, + numClicks = 1; - var rangePlots = rangeSlider.selectAll('g.' + _$constants_126.rangePlotClassName) - .data(subplotData, _$lib_171.identity); + var traceToggle = _$lib_172.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_51.fill, 'rgba(0,0,0,0)'); + }); - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_126.rangePlotClassName + ' ' + id; }) - .call(_$drawing_76.setClipUrl, opts._clipId); + traceToggle.on('mousedown', function() { + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { + // 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; - rangePlots.order(); + if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - rangePlots.exit().remove(); + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { _$handleClick_109(g, gd, numClicks); }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + gd._legendMouseDownTime = 0; + _$handleClick_109(g, gd, numClicks); + } + }); +} - var mainplotinfo; +function computeTextDimensions(g, gd) { + var legendItem = g.data()[0][0]; - rangePlots.each(function(id, i) { - var plotgroup = _$d3_15.select(this), - isMainPlot = (i === 0); + if(!legendItem.trace.showlegend) { + g.remove(); + return; + } - var oppAxisOpts = _$axes_213.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; + var mathjaxGroup = g.select('g[class*=math-group]'); + var mathjaxNode = mathjaxGroup.node(); + var opts = gd._fullLayout.legend; + var lineHeight = opts.font.size * __LINE_SPACING_107; + var height, width; - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + if(mathjaxNode) { + var mathjaxBB = _$drawing_76.bBox(mathjaxNode); - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; + height = mathjaxBB.height; + width = mathjaxBB.width; - _$plots_246.supplyDefaults(mockFigure); + _$drawing_76.setTranslate(mathjaxGroup, 0, (height / 4)); + } + else { + var text = g.select('.legendtext'); + var textLines = _$svg_text_utils_193.lineCount(text); + var textNode = text.node(); - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; + height = lineHeight * textLines; + width = textNode ? _$drawing_76.bBox(textNode).width : 0; - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya - }; + // approximation to height offset to center the font + // to avoid getBoundingClientRect + var textY = lineHeight * (0.3 + (1 - textLines) / 2); + // TODO: this 40 should go in a constants file (along with other + // values related to the legend symbol size) + _$svg_text_utils_193.positionText(text, 40, textY); + } - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; - } + height = Math.max(height, 16) + 3; - _$cartesian_224.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); + legendItem.height = height; + legendItem.width = width; } -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; +function computeLegendDimensions(gd, groups, traces) { + var fullLayout = gd._fullLayout; + var opts = fullLayout.legend; + var borderwidth = opts.borderwidth; + var isGrouped = _$helpers_110.isGrouped(opts); - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; + var extraWidth = 0; - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); + opts._width = 0; + opts._height = 0; + + if(_$helpers_110.isVertical(opts)) { + if(isGrouped) { + groups.each(function(d, i) { + _$drawing_76.setTranslate(this, 0, i * opts.tracegroupgap); + }); } - } - return out; -} + traces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height, + textWidth = legendItem.width; -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_126.maskMinClassName) - .data([0]); + _$drawing_76.setTranslate(this, + borderwidth, + (5 + borderwidth + opts._height + textHeight / 2)); - maskMin.enter().append('rect') - .classed(_$constants_126.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + opts._height += textHeight; + opts._width = Math.max(opts._width, textWidth); + }); - maskMin - .attr('height', opts._height) - .call(_$color_51.fill, _$constants_126.maskColor); + opts._width += 45 + borderwidth * 2; + opts._height += 10 + borderwidth * 2; - var maskMax = rangeSlider.selectAll('rect.' + _$constants_126.maskMaxClassName) - .data([0]); + if(isGrouped) { + opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; + } - maskMax.enter().append('rect') - .classed(_$constants_126.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + extraWidth = 40; + } + else if(isGrouped) { + var groupXOffsets = [opts._width], + groupData = groups.data(); - maskMax - .attr('height', opts._height) - .call(_$color_51.fill, _$constants_126.maskColor); + for(var i = 0, n = groupData.length; i < n; i++) { + var textWidths = groupData[i].map(function(legendItemArray) { + return legendItemArray[0].width; + }); - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_126.maskMinOppAxisClassName) - .data([0]); + var groupWidth = 40 + Math.max.apply(null, textWidths); - maskMinOppAxis.enter().append('rect') - .classed(_$constants_126.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + opts._width += opts.tracegroupgap + groupWidth; - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_51.fill, _$constants_126.maskOppAxisColor); + groupXOffsets.push(opts._width); + } - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_126.maskMaxOppAxisClassName) - .data([0]); + groups.each(function(d, i) { + _$drawing_76.setTranslate(this, groupXOffsets[i], 0); + }); - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_126.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + groups.each(function() { + var group = _$d3_15.select(this), + groupTraces = group.selectAll('g.traces'), + groupHeight = 0; - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_126.maskOppBorder) - .call(_$color_51.fill, _$constants_126.maskOppAxisColor); - } -} + groupTraces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height; -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; + _$drawing_76.setTranslate(this, + 0, + (5 + borderwidth + groupHeight + textHeight / 2)); - var slideBox = rangeSlider.selectAll('rect.' + _$constants_126.slideBoxClassName) - .data([0]); + groupHeight += textHeight; + }); - slideBox.enter().append('rect') - .classed(_$constants_126.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_126.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); + opts._height = Math.max(opts._height, groupHeight); + }); - slideBox.attr({ - height: opts._height, - fill: _$constants_126.slideBoxFill - }); -} + opts._height += 10 + borderwidth * 2; + opts._width += borderwidth * 2; + } + else { + var rowHeight = 0, + maxTraceHeight = 0, + maxTraceWidth = 0, + offsetX = 0, + fullTracesWidth = 0, + traceGap = opts.tracegroupgap || 5, + oneRowLegend; -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // calculate largest width for traces and use for width of all legend items + traces.each(function(d) { + maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); + fullTracesWidth += 40 + d[0].width + traceGap; + }); - // + // check if legend fits in one row + oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; + traces.each(function(d) { + var legendItem = d[0], + traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; - var grabberMin = rangeSlider.selectAll('g.' + _$constants_126.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_126.grabberMinClassName, true); + if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { + offsetX = 0; + rowHeight = rowHeight + maxTraceHeight; + opts._height = opts._height + maxTraceHeight; + // reset for next row + maxTraceHeight = 0; + } - var grabberMax = rangeSlider.selectAll('g.' + _$constants_126.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_126.grabberMaxClassName, true); + _$drawing_76.setTranslate(this, + (borderwidth + offsetX), + (5 + borderwidth + legendItem.height / 2) + rowHeight); - // + opts._width += traceGap + traceWidth; + opts._height = Math.max(opts._height, legendItem.height); - var handleFixAttrs = { - x: 0, - width: _$constants_126.handleWidth, - rx: _$constants_126.handleRadius, - fill: _$color_51.background, - stroke: _$color_51.defaultLine, - 'stroke-width': _$constants_126.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; + // keep track of tallest trace in group + offsetX += traceGap + traceWidth; + maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); + }); - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; + opts._width += borderwidth * 2; + opts._height += 10 + borderwidth * 2; - var handleMin = grabberMin.selectAll('rect.' + _$constants_126.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_126.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); + } - var handleMax = grabberMax.selectAll('rect.' + _$constants_126.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_126.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); + // make sure we're only getting full pixels + opts._width = Math.ceil(opts._width); + opts._height = Math.ceil(opts._height); - // + traces.each(function(d) { + var legendItem = d[0], + bg = _$d3_15.select(this).select('.legendtoggle'); - if(gd._context.staticPlot) return; + _$drawing_76.setRect(bg, + 0, + -legendItem.height / 2, + (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, + legendItem.height + ); + }); +} - var grabAreaFixAttrs = { - width: _$constants_126.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_126.grabAreaFill, - cursor: _$constants_126.grabAreaCursor - }; +function expandMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_126.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_126.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); + var xanchor = 'left'; + if(_$anchor_utils_103.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_103.isCenterAnchor(opts)) { + xanchor = 'center'; + } - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_126.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_126.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); -} + var yanchor = 'top'; + if(_$anchor_utils_103.isBottomAnchor(opts)) { + yanchor = 'bottom'; + } + else if(_$anchor_utils_103.isMiddleAnchor(opts)) { + yanchor = 'middle'; + } -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + // lastly check if the margin auto-expand has changed + _$plots_246.autoMargin(gd, 'legend', { + x: opts.x, + y: opts.y, + l: opts._width * (__FROM_TL_107[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: opts._height * (FROM_BR[yanchor]), + t: opts._height * (__FROM_TL_107[yanchor]) + }); +} - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; +function expandHorizontalMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - if(k.indexOf(_$constants_126.name) !== -1) { - _$plots_246.autoMargin(gd, k); - } + var xanchor = 'left'; + if(_$anchor_utils_103.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_103.isCenterAnchor(opts)) { + xanchor = 'center'; } + + // lastly check if the margin auto-expand has changed + _$plots_246.autoMargin(gd, 'legend', { + x: opts.x, + y: 0.5, + l: opts._width * (__FROM_TL_107[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: 0, + t: 0 + }); } /** @@ -50961,30 +53442,19 @@ function clearPushMargins(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$attributes_124 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_130 = require('./oppaxis_attributes'); */; -var _$rangeslider_129 = { +var _$legend_111 = { moduleType: 'component', - name: 'rangeslider', + name: 'legend', - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_171.extendFlat({}, _$attributes_124, { - yaxis: _$oppaxis_attributes_130 - }) - } - } - }, + layoutAttributes: _$attributes_104, + supplyLayoutDefaults: _$legendDefaults_106, - layoutAttributes: _$attributes_124, - handleDefaults: _$handleDefaults_127, - calcAutorange: _$calcAutorange_125, - draw: _$draw_128 + draw: _$draw_107, + style: _$style_112 }; /** @@ -50997,246 +53467,139 @@ var _$rangeslider_129 = { 'use strict'; -/* removed: var _$attributes_36 = require('../annotations/attributes'); */; -var __scatterLineAttrs_131 = _$attributes_368.line; -var __dash_131 = _$attributes_75.dash; -var __extendFlat_131 = _$extend_165.extendFlat; - -var _$attributes_131 = { - _isLinkedToArray: 'shape', - visible: { - valType: 'boolean', +var _$button_attributes_118 = { + step: { + valType: 'enumerated', - dflt: true, - editType: 'calcIfAutorange+arraydraw', + values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], + dflt: 'month', + editType: 'plot', }, - - type: { + stepmode: { valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], - editType: 'calcIfAutorange+arraydraw', + values: ['backward', 'todate'], + dflt: 'backward', + editType: 'plot', }, - - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', + count: { + valType: 'number', - editType: 'arraydraw', + min: 0, + dflt: 1, + editType: 'plot', }, - - xref: __extendFlat_131({}, _$attributes_36.xref, { - - }), - x0: { - valType: 'any', + label: { + valType: 'string', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - x1: { - valType: 'any', + editType: 'plot' +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_50 = require('../color/attributes'); */; +var __extendFlat_117 = _$extend_166.extendFlat; +/* removed: var _$button_attributes_118 = require('./button_attributes'); */; + +_$button_attributes_118 = __extendFlat_117(_$button_attributes_118, { + _isLinkedToArray: 'button', + + +}); + +var _$attributes_117 = { + visible: { + valType: 'boolean', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - yref: __extendFlat_131({}, _$attributes_36.yref, { + buttons: _$button_attributes_118, + + x: { + valType: 'number', + min: -2, + max: 3, - }), - y0: { - valType: 'any', + editType: 'plot', - editType: 'calcIfAutorange+arraydraw', + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + editType: 'plot', }, - y1: { - valType: 'any', + y: { + valType: 'number', + min: -2, + max: 3, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - path: { - valType: 'string', + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'bottom', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, + font: _$font_attributes_240({ + editType: 'plot', - editType: 'arraydraw', + }), + + bgcolor: { + valType: 'color', + dflt: _$attributes_50.lightLine, - }, - line: { - color: __extendFlat_131({}, __scatterLineAttrs_131.color, {editType: 'arraydraw'}), - width: __extendFlat_131({}, __scatterLineAttrs_131.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_131({}, __dash_131, {editType: 'arraydraw'}), + editType: 'plot', - editType: 'calcIfAutorange+arraydraw' }, - fillcolor: { + activecolor: { valType: 'color', - dflt: 'rgba(0,0,0,0)', - editType: 'arraydraw', + editType: 'plot', }, - editType: 'arraydraw' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - - -var _$constants_133 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, - - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, - - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} + bordercolor: { + valType: 'color', + dflt: _$attributes_50.defaultLine, + + editType: 'plot', + }, - - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 - } -}; - -var _$helpers_136 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. - -_$helpers_136.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; - -_$helpers_136.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; - -_$helpers_136.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; - -_$helpers_136.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; - -_$helpers_136.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; - - if(axis) { - var d2r = _$helpers_136.shapePositionToRange(axis); - - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; - - if(axis.type === 'date') dataToPixel = _$helpers_136.decodeDate(dataToPixel); - } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; - } - else { - dataToPixel = function(v) { return gs.l + gs.w * v; }; - } - - return dataToPixel; -}; - -_$helpers_136.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; - - if(axis) { - var r2d = _$helpers_136.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; - } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; - } - else { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; - } - - return pixelToData; + borderwidth: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'plot', + + }, + editType: 'plot' }; /** @@ -51247,74 +53610,26 @@ _$helpers_136.getPixelToData = function(gd, axis, isVertical) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$constants_133 = require('./constants'); */; -/* removed: var _$helpers_136 = require('./helpers'); */; - -var _$calcAutorange_132 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_171.filterVisible(fullLayout.shapes); - - if(!shapeList.length || !gd._fullData.length) return; +var _$constants_119 = { - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; + // 'y' position pad above counter axis domain + yPad: 0.02, - var ax, bounds; + // minimum button width (regardless of text size) + minButtonWidth: 30, - if(shape.xref !== 'paper') { - ax = _$axes_213.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_133.paramIsX); - if(bounds) _$axes_213.expand(ax, bounds, {ppad: ppad}); - } + // buttons rect radii + rx: 3, + ry: 3, - if(shape.yref !== 'paper') { - ax = _$axes_213.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_133.paramIsY); - if(bounds) _$axes_213.expand(ax, bounds, {ppad: ppad}); - } - } + // light fraction used to compute the 'activecolor' default + lightAmount: 25, + darkAmount: 10 }; -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; - - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_133.segmentRE), - i, - segment, - drawnParam, - params, - val; - - if(ax.type === 'date') convertVal = _$helpers_136.decodeDate(convertVal); - - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; - - params = segments[i].substr(1).match(_$constants_133.paramRE); - if(!params || params.length < drawnParam) continue; - - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; - } - if(max >= min) return [min, max]; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51323,119 +53638,95 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$attributes_131 = require('./attributes'); */; -/* removed: var _$helpers_136 = require('./helpers'); */; +/* removed: var _$attributes_117 = require('./attributes'); */; +/* removed: var _$button_attributes_118 = require('./button_attributes'); */; +/* removed: var _$constants_119 = require('./constants'); */; -var _$handleShapeDefaults_138 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; +var _$handleDefaults_120 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { + var selectorIn = containerIn.rangeselector || {}, + selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_171.coerce(shapeIn, shapeOut, _$attributes_131, attr, dflt); + return _$lib_172.coerce(selectorIn, selectorOut, _$attributes_117, attr, dflt); } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - - if(!visible) return shapeOut; - - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); + var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + var posDflt = getPosDflt(containerOut, layout, counterAxes); + coerce('x', posDflt[0]); + coerce('y', posDflt[1]); + _$lib_172.noneOrAll(containerIn, containerOut, ['x', 'y']); - // xref, yref - var axRef = _$axes_213.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + coerce('xanchor'); + coerce('yanchor'); - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + _$lib_172.coerceFont(coerce, 'font', layout.font); - if(axRef !== 'paper') { - ax = _$axes_213.getFromId(gdMock, axRef); - r2pos = _$helpers_136.rangeToShapePosition(ax); - pos2r = _$helpers_136.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_171.identity; - } + var bgColor = coerce('bgcolor'); + coerce('activecolor', _$color_51.contrast(bgColor, _$constants_119.lightAmount, _$constants_119.darkAmount)); + coerce('bordercolor'); + coerce('borderwidth'); +}; - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); +function buttonsDefaults(containerIn, containerOut, calendar) { + var buttonsIn = containerIn.buttons || [], + buttonsOut = containerOut.buttons = []; - // x0, x1 (and y0, y1) - _$axes_213.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_213.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + var buttonIn, buttonOut; - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; - } + function coerce(attr, dflt) { + return _$lib_172.coerce(buttonIn, buttonOut, _$button_attributes_118, attr, dflt); } - if(shapeType === 'path') { - coerce('path'); - } - else { - _$lib_171.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); - } + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; - return shapeOut; -}; + if(!_$lib_172.isPlainObject(buttonIn)) continue; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 step = coerce('step'); + if(step !== 'all') { + if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { + buttonOut.stepmode = 'backward'; + } + else { + coerce('stepmode'); + } + coerce('count'); + } -'use strict'; + coerce('label'); -/* removed: var _$handleArrayContainerDefaults_209 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_138 = require('./shape_defaults'); */; + buttonOut._index = i; + buttonsOut.push(buttonOut); + } + return buttonsOut; +} -var _$supplyLayoutDefaults_134 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_138 - }; +function getPosDflt(containerOut, layout, counterAxes) { + var anchoredList = counterAxes.filter(function(ax) { + return layout[ax].anchor === containerOut._id; + }); - _$handleArrayContainerDefaults_209(layoutIn, layoutOut, opts); -}; + var posY = 0; + for(var i = 0; i < anchoredList.length; i++) { + var domain = layout[anchoredList[i]].domain; + if(domain) posY = Math.max(domain[1], posY); + } + + return [containerOut.domain[0], posY + _$constants_119.yPad]; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -51448,487 +53739,306 @@ var _$supplyLayoutDefaults_134 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; - -/* removed: var _$dragelement_73 = require('../dragelement'); */; -/* removed: var _$setCursor_190 = require('../../lib/setcursor'); */; - -/* removed: var _$constants_133 = require('./constants'); */; -/* removed: var _$helpers_136 = require('./helpers'); */; - - -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one - -var _$draw_135 = { - draw: __draw_135, - drawOne: __drawOne_135 -}; - -function __draw_135(gd) { - var fullLayout = gd._fullLayout; - - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); - - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_135(gd, i); - } - } - - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); -} - -function __drawOne_135(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); - - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; +/* removed: var _$d3_15 = require('d3'); */; - // this shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; +var _$getUpdateObject_122 = function getUpdateObject(axisLayout, buttonLayout) { + var axName = axisLayout._name; + var update = {}; - if(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); + if(buttonLayout.step === 'all') { + update[axName + '.autorange'] = true; } else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } - } - - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; - - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_51.stroke, lineColor) - .call(_$color_51.fill, options.fillcolor) - .call(_$drawing_76.dashLine, options.line.dash, options.line.width); - - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - - path.call(_$drawing_76.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); + var xrange = getXRange(axisLayout, buttonLayout); - if(gd._context.edits.shapePosition) __setupDragElement_135(gd, path, options, index); + update[axName + '.range[0]'] = xrange[0]; + update[axName + '.range[1]'] = xrange[1]; } -} - -function __setupDragElement_135(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; - - var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; - var xa, ya, x2p, y2p, p2x, p2y; + return update; +}; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag - }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; +function getXRange(axisLayout, buttonLayout) { + var currentRange = axisLayout.range; + var base = new Date(axisLayout.r2l(currentRange[1])); - _$dragelement_73.init(dragOptions); + var step = buttonLayout.step, + count = buttonLayout.count; - shapePath.node().onmousemove = updateDragMode; + var range0; - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_73.getCursor(x / w, 1 - y / h) : - 'move'; + switch(buttonLayout.stepmode) { + case 'backward': + range0 = axisLayout.l2r(+_$d3_15.time[step].utc.offset(base, -count)); + break; - _$setCursor_190(shapePath, cursor); + case 'todate': + var base2 = _$d3_15.time[step].utc.offset(base, -count); - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; + range0 = axisLayout.l2r(+_$d3_15.time[step].utc.ceil(base2)); + break; } - function startDrag(evt) { - // setup conversion functions - xa = _$axes_213.getFromId(gd, shapeOptions.xref); - ya = _$axes_213.getFromId(gd, shapeOptions.yref); + var range1 = currentRange[1]; - x2p = _$helpers_136.getDataToPixel(gd, xa); - y2p = _$helpers_136.getDataToPixel(gd, ya, true); - p2x = _$helpers_136.getPixelToData(gd, xa); - p2y = _$helpers_136.getPixelToData(gd, ya, true); + return [range0, range1]; +} - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; - } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } +'use strict'; - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; - } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; - } +/* removed: var _$d3_15 = require('d3'); */; - update = {}; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_217 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$anchor_utils_103 = require('../legend/anchor_utils'); */; - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; - } +/* removed: var _$alignment_151 = require('../../constants/alignment'); */; +var __LINE_SPACING_121 = _$alignment_151.LINE_SPACING; +var __FROM_TL_121 = _$alignment_151.FROM_TL; +var __FROM_BR_121 = _$alignment_151.FROM_BR; - function endDrag() { - _$setCursor_190(shapePath); - _$registry_261.call('relayout', gd, update); - } +/* removed: var _$constants_119 = require('./constants'); */; +/* removed: var _$getUpdateObject_122 = require('./get_update_object'); */; - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_136.encodeDate(moveX); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_136.encodeDate(moveY); +var _$draw_121 = function draw(gd) { + var fullLayout = gd._fullLayout; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } + var selectors = fullLayout._infolayer.selectAll('.rangeselector') + .data(makeSelectorData(gd), selectorKeyFunc); - shapePath.attr('d', getPathString(gd, shapeOptions)); - } + selectors.enter().append('g') + .classed('rangeselector', true); - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_136.encodeDate(moveX); + selectors.exit().remove(); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_136.encodeDate(moveY); + selectors.style({ + cursor: 'pointer', + 'pointer-events': 'all' + }); - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; + selectors.each(function(d) { + var selector = _$d3_15.select(this), + axisLayout = d, + selectorLayout = axisLayout.rangeselector; - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + var buttons = selector.selectAll('g.button') + .data(selectorLayout.buttons); - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); - } - } + buttons.enter().append('g') + .classed('button', true); - shapePath.attr('d', getPathString(gd, shapeOptions)); - } -} + buttons.exit().remove(); -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_213.getFromId(gd, options.xref), - ya = _$axes_213.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; + buttons.each(function(d) { + var button = _$d3_15.select(this); + var update = _$getUpdateObject_122(axisLayout, d); - if(xa) { - x2r = _$helpers_136.shapePositionToRange(xa); - x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; - } - else { - x2p = function(v) { return gs.l + gs.w * v; }; - } + d._isActive = isActive(axisLayout, d, update); - if(ya) { - y2r = _$helpers_136.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + button.call(drawButtonRect, selectorLayout, d); + button.call(drawButtonText, selectorLayout, d, gd); - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_136.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_136.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); - } + button.on('click', function() { + if(gd._dragged) return; - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), - y1 = y2p(options.y1); + _$registry_262.call('relayout', gd, update); + }); - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; -} + button.on('mouseover', function() { + d._isHovered = true; + button.call(drawButtonRect, selectorLayout, d); + }); + button.on('mouseout', function() { + d._isHovered = false; + button.call(drawButtonRect, selectorLayout, d); + }); + }); -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_133.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_133.paramIsX[segmentType], - yParams = _$constants_133.paramIsY[segmentType], - nParams = _$constants_133.numParams[segmentType]; + reposition(gd, buttons, selectorLayout, axisLayout._name, selector); + }); - var paramString = segment.substr(1).replace(_$constants_133.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; +}; - if(paramNumber > nParams) param = 'X'; - return param; - }); +function makeSelectorData(gd) { + var axes = _$axis_ids_217.list(gd, 'x', true); + var data = []; - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_171.log('Ignoring extra params in segment ' + segment); + for(var i = 0; i < axes.length; i++) { + var axis = axes[i]; + + if(axis.rangeselector && axis.rangeselector.visible) { + data.push(axis); } + } - return segmentType + paramString; - }); + return data; } -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_133.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_133.paramIsX[segmentType], - yParams = _$constants_133.paramIsY[segmentType], - nParams = _$constants_133.numParams[segmentType]; - - var paramString = segment.substr(1).replace(_$constants_133.paramRE, function(param) { - if(paramNumber >= nParams) return param; +function selectorKeyFunc(d) { + return d._id; +} - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); +function isActive(axisLayout, opts, update) { + if(opts.step === 'all') { + return axisLayout.autorange === true; + } + else { + var keys = Object.keys(update); - paramNumber++; + return ( + axisLayout.range[0] === update[keys[0]] && + axisLayout.range[1] === update[keys[1]] + ); + } +} - return param; - }); +function drawButtonRect(button, selectorLayout, d) { + var rect = _$lib_172.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); - return segmentType + paramString; + rect.attr({ + 'rx': _$constants_119.rx, + 'ry': _$constants_119.ry }); -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + rect.call(_$color_51.stroke, selectorLayout.bordercolor) + .call(_$color_51.fill, getFillColor(selectorLayout, d)) + .style('stroke-width', selectorLayout.borderwidth + 'px'); +} +function getFillColor(selectorLayout, d) { + return (d._isActive || d._isHovered) ? + selectorLayout.activecolor : + selectorLayout.bgcolor; +} -'use strict'; +function drawButtonText(button, selectorLayout, d, gd) { + function textLayout(s) { + _$svg_text_utils_193.convertToTspans(s, gd); + } -/* removed: var _$draw_135 = require('./draw'); */; + var text = _$lib_172.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); -var _$shapes_137 = { - moduleType: 'component', - name: 'shapes', + text.call(_$drawing_76.font, selectorLayout.font) + .text(getLabel(d)) + .call(textLayout); +} - layoutAttributes: _$attributes_131, - supplyLayoutDefaults: _$supplyLayoutDefaults_134, - includeBasePlot: _$makeIncludeComponents_223('shapes'), +function getLabel(opts) { + if(opts.label) return opts.label; - calcAutorange: _$calcAutorange_132, - draw: _$draw_135.draw, - drawOne: _$draw_135.drawOne -}; + if(opts.step === 'all') return 'all'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 opts.count + opts.step.charAt(0); +} +function reposition(gd, buttons, opts, axName, selector) { + var width = 0; + var height = 0; -'use strict'; + var borderWidth = opts.borderwidth; + buttons.each(function() { + var button = _$d3_15.select(this); + var text = button.select('.selector-text'); -var _$constants_140 = { + var tHeight = opts.font.size * __LINE_SPACING_121; + var hEff = Math.max(tHeight * _$svg_text_utils_193.lineCount(text), 16) + 3; - // layout attribute name - name: 'sliders', + height = Math.max(height, hEff); + }); - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', + buttons.each(function() { + var button = _$d3_15.select(this); + var rect = button.select('.selector-rect'); + var text = button.select('.selector-text'); - railHeight: 5, + var tWidth = text.node() && _$drawing_76.bBox(text.node()).width; + var tHeight = opts.font.size * __LINE_SPACING_121; + var tLines = _$svg_text_utils_193.lineCount(text); - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', + var wEff = Math.max(tWidth + 10, _$constants_119.minButtonWidth); - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', + // TODO add MathJax support - // min item width / height - minWidth: 30, - minHeight: 30, + // TODO add buttongap attribute - // padding around item text - textPadX: 40, + button.attr('transform', 'translate(' + + (borderWidth + width) + ',' + borderWidth + + ')'); - // arrow offset off right edge - arrowOffsetX: 4, + rect.attr({ + x: 0, + y: 0, + width: wEff, + height: height + }); - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', + _$svg_text_utils_193.positionText(text, wEff / 2, + height / 2 - ((tLines - 1) * tHeight / 2) + 3); - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, + width += wEff + 5; + }); - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, + var graphSize = gd._fullLayout._size; + var lx = graphSize.l + graphSize.w * opts.x; + var ly = graphSize.t + graphSize.h * (1 - opts.y); - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', + var xanchor = 'left'; + if(_$anchor_utils_103.isRightAnchor(opts)) { + lx -= width; + xanchor = 'right'; + } + if(_$anchor_utils_103.isCenterAnchor(opts)) { + lx -= width / 2; + xanchor = 'center'; + } - labelPadding: 8, - labelOffset: 0, + var yanchor = 'top'; + if(_$anchor_utils_103.isBottomAnchor(opts)) { + ly -= height; + yanchor = 'bottom'; + } + if(_$anchor_utils_103.isMiddleAnchor(opts)) { + ly -= height / 2; + yanchor = 'middle'; + } - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, + width = Math.ceil(width); + height = Math.ceil(height); + lx = Math.round(lx); + ly = Math.round(ly); - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, + _$plots_246.autoMargin(gd, axName + '-range-selector', { + x: opts.x, + y: opts.y, + l: width * __FROM_TL_121[xanchor], + r: width * __FROM_BR_121[xanchor], + b: height * __FROM_BR_121[yanchor], + t: height * __FROM_TL_121[yanchor] + }); - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; + selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -51940,39 +54050,20 @@ var _$constants_140 = { 'use strict'; -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_245 = { - t: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - r: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - b: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - l: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - +var _$rangeselector_123 = { + moduleType: 'component', + name: 'rangeselector', + + schema: { + subplots: { + xaxis: {rangeselector: _$attributes_117} + } }, - editType: 'arraydraw' + + layoutAttributes: _$attributes_117, + handleDefaults: _$handleDefaults_120, + + draw: _$draw_121 }; /** @@ -51985,234 +54076,123 @@ var _$pad_attributes_245 = { 'use strict'; -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_245 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_139 = _$extend_165.extendDeepAll; -var __overrideAll_139 = _$edit_types_198.overrideAll; -/* removed: var _$animation_attributes_208 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_140 = require('./constants'); */; - -var stepsAttrs = { - _isLinkedToArray: 'step', +/* removed: var _$attributes_50 = require('../color/attributes'); */; - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', +var _$attributes_124 = { + bgcolor: { + valType: 'color', + dflt: _$attributes_50.background, - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], + editType: 'plot', }, - label: { - valType: 'string', + bordercolor: { + valType: 'color', + dflt: _$attributes_50.defaultLine, + editType: 'plot', }, - value: { - valType: 'string', + borderwidth: { + valType: 'integer', + dflt: 0, + min: 0, + editType: 'plot', }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; - -var _$attributes_139 = __overrideAll_139({ - _isLinkedToArray: 'slider', - - visible: { + autorange: { valType: 'boolean', - dflt: true, - }, - - active: { - valType: 'number', - - min: 0, - dflt: 0, + editType: 'calc', + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - - steps: stepsAttrs, - - lenmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], + range: { + valType: 'info_array', - dflt: 'fraction', + items: [ + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} + ], + editType: 'calc', + impliedEdits: {'autorange': false}, }, - len: { + thickness: { valType: 'number', + dflt: 0.15, min: 0, - dflt: 1, - - - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, - - - }, - pad: __extendDeepAll_139({}, _$pad_attributes_245, { - - }, {t: {dflt: 20}}), - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, + max: 1, + editType: 'plot', }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', + visible: { + valType: 'boolean', + dflt: true, + editType: 'calc', }, + editType: 'calc' +}; - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_208.transition.easing.values, - - dflt: 'cubic-in-out', - - } - }, - - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, - - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, - - offset: { - valType: 'number', - dflt: 10, - - - }, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - prefix: { - valType: 'string', - - - }, +'use strict'; - suffix: { - valType: 'string', - - - }, +var _$constants_126 = { - font: _$font_attributes_240({ - - }) - }, + // attribute container name + name: 'rangeslider', - font: _$font_attributes_240({ - - }), + // class names - activebgcolor: { - valType: 'color', - - dflt: _$constants_140.gripBgActiveColor, - - }, - bgcolor: { - valType: 'color', - - dflt: _$constants_140.railBgColor, - - }, - bordercolor: { - valType: 'color', - dflt: _$constants_140.railBorderColor, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: _$constants_140.railBorderWidth, - - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_140.tickLength, - - - }, - tickcolor: { - valType: 'color', - dflt: _$constants_140.tickColor, - - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - - }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_140.minorTickLength, - - - } -}, 'arraydraw', 'from-root'); + containerClassName: 'rangeslider-container', + bgClassName: 'rangeslider-bg', + rangePlotClassName: 'rangeslider-rangeplot', + + maskMinClassName: 'rangeslider-mask-min', + maskMaxClassName: 'rangeslider-mask-max', + slideBoxClassName: 'rangeslider-slidebox', + + grabberMinClassName: 'rangeslider-grabber-min', + grabAreaMinClassName: 'rangeslider-grabarea-min', + handleMinClassName: 'rangeslider-handle-min', + + grabberMaxClassName: 'rangeslider-grabber-max', + grabAreaMaxClassName: 'rangeslider-grabarea-max', + handleMaxClassName: 'rangeslider-handle-max', + + maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', + maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', + + // style constants + + maskColor: 'rgba(0,0,0,0.4)', + maskOppAxisColor: 'rgba(0,0,0,0.2)', + + slideBoxFill: 'transparent', + slideBoxCursor: 'ew-resize', + + grabAreaFill: 'transparent', + grabAreaCursor: 'col-resize', + grabAreaWidth: 10, + + handleWidth: 4, + handleRadius: 1, + handleStrokeWidth: 1, + + extraPad: 15 +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -52224,109 +54204,151 @@ var _$attributes_139 = __overrideAll_139({ 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_209 = require('../../plots/array_container_defaults'); */; +var listAxes = _$axis_ids_217.list; +var __getAutoRange_125 = _$autorange_213.getAutoRange; +/* removed: var _$constants_126 = require('./constants'); */; -/* removed: var _$attributes_139 = require('./attributes'); */; -/* removed: var _$constants_140 = require('./constants'); */; +var _$calcAutorange_125 = function calcAutorange(gd) { + var axes = listAxes(gd, 'x', true); -var __name_141 = _$constants_140.name; -var stepAttrs = _$attributes_139.steps; + // 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], + opts = ax[_$constants_126.name]; -var _$slidersDefaults_141 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_141, - handleItemDefaults: sliderDefaults - }; + // Don't try calling getAutoRange if _min and _max are filled in. + // This happens on updates where the calc step is skipped. - _$handleArrayContainerDefaults_209(layoutIn, layoutOut, opts); + if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { + opts._input.autorange = true; + opts._input.range = opts.range = __getAutoRange_125(ax); + } + } }; -function sliderDefaults(sliderIn, sliderOut, layoutOut) { +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function coerce(attr, dflt) { - return _$lib_171.coerce(sliderIn, sliderOut, _$attributes_139, attr, dflt); - } +'use strict'; - var steps = stepsDefaults(sliderIn, sliderOut); +var _$oppaxis_attributes_130 = { + // not really a 'subplot' attribute container, + // but this is the flag we use to denote attributes that + // support yaxis, yaxis2, yaxis3, ... counters + _isSubplotObj: true, - var visible = coerce('visible', steps.length > 0); - if(!visible) return; + 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' +}; - coerce('active'); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('x'); - coerce('y'); - _$lib_171.noneOrAll(sliderIn, sliderOut, ['x', 'y']); +'use strict'; - coerce('xanchor'); - coerce('yanchor'); +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$attributes_124 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_130 = require('./oppaxis_attributes'); */; +/* removed: var _$axis_ids_217 = require('../../plots/cartesian/axis_ids'); */; - coerce('len'); - coerce('lenmode'); +var _$handleDefaults_127 = function handleDefaults(layoutIn, layoutOut, axName) { + var axIn = layoutIn[axName]; + var axOut = layoutOut[axName]; - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; - _$lib_171.coerceFont(coerce, 'font', layoutOut.font); + // not super proud of this (maybe store _ in axis object instead + if(!_$lib_172.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; + } - var currentValueIsVisible = coerce('currentvalue.visible'); + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; - if(currentValueIsVisible) { - coerce('currentvalue.xanchor'); - coerce('currentvalue.prefix'); - coerce('currentvalue.suffix'); - coerce('currentvalue.offset'); + function coerce(attr, dflt) { + return _$lib_172.coerce(containerIn, containerOut, _$attributes_124, attr, dflt); + } - _$lib_171.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { + return _$lib_172.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_130, attr, dflt); } - coerce('transition.duration'); - coerce('transition.easing'); + var visible = coerce('visible'); + if(!visible) return; - coerce('bgcolor'); - coerce('activebgcolor'); + coerce('bgcolor', layoutOut.plot_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - coerce('ticklen'); - coerce('tickwidth'); - coerce('tickcolor'); - coerce('minorticklen'); -} + coerce('thickness'); -function stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; + axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); + coerce('range'); - var valueIn, valueOut; + var subplots = layoutOut._subplots; + if(subplots) { + var yIds = subplots.cartesian + .filter(function(subplotId) { + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_217.name2id(axName); + }) + .map(function(subplotId) { + return subplotId.substr(subplotId.indexOf('y'), subplotId.length); + }); + var yNames = _$lib_172.simpleMap(yIds, _$axis_ids_217.id2name); + for(var i = 0; i < yNames.length; i++) { + var yName = yNames[i]; - function coerce(attr, dflt) { - return _$lib_171.coerce(valueIn, valueOut, stepAttrs, attr, dflt); - } + var rangeContainerIn = containerIn[yName] || {}; + var rangeContainerOut = containerOut[yName] = {}; - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; + var yAxOut = layoutOut[yName]; - coerce('method'); + var rangemodeDflt; + if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { + rangemodeDflt = 'fixed'; + } - if(!_$lib_171.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; + var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); + if(rangeMode !== 'match') { + coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); + } + yAxOut._rangesliderAutorange = (rangeMode === 'auto'); } - - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); - - valuesOut.push(valueOut); } - return valuesOut; -} + // to map back range slider (auto) range + containerOut._input = containerIn; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -52336,624 +54358,611 @@ function stepsDefaults(sliderIn, sliderOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$registry_262 = require('../../registry'); */; /* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_103 = require('../legend/anchor_utils'); */; - -/* removed: var _$constants_140 = require('./constants'); */; -/* removed: var _$alignment_151 = require('../../constants/alignment'); */; -var __LINE_SPACING_142 = _$alignment_151.LINE_SPACING; -var __FROM_TL_142 = _$alignment_151.FROM_TL; -var __FROM_BR_142 = _$alignment_151.FROM_BR; - - -var _$draw_142 = function draw(gd) { - var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); - - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_140.containerClassName) - .data(sliderData.length > 0 ? [0] : []); - - sliders.enter().append('g') - .classed(_$constants_140.containerClassName, true) - .style('cursor', 'ew-resize'); - - sliders.exit().remove(); - - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_142(gd); - // Return early if no menus visible: - if(sliderData.length === 0) return; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$titles_144 = require('../titles'); */; - var sliderGroups = sliders.selectAll('g.' + _$constants_140.groupClassName) - .data(sliderData, keyFunction); +/* removed: var _$cartesian_225 = require('../../plots/cartesian'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; - sliderGroups.enter().append('g') - .classed(_$constants_140.groupClassName, true); +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$setCursor_191 = require('../../lib/setcursor'); */; - sliderGroups.exit().each(function(sliderOpts) { - _$d3_15.select(this).remove(); +/* removed: var _$constants_126 = require('./constants'); */; - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; +var _$draw_128 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); - _$plots_246.autoMargin(gd, _$constants_140.autoMarginIdRoot + sliderOpts._index); - }); + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); + function keyFunction(axisOpts) { + return axisOpts._name; } - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; - - var gSlider = _$d3_15.select(this); - - computeLabelSteps(sliderOpts); - - _$plots_246.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_126.containerClassName) + .data(rangeSliderData, keyFunction); - if(opts.active === data.index) return; - if(opts._dragging) return; + rangeSliders.enter().append('g') + .classed(_$constants_126.containerClassName, true) + .attr('pointer-events', 'all'); - setActive(gd, gSlider, opts, data.index, false, true); - }); + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_15.select(this), + opts = axisOpts[_$constants_126.name]; - drawSlider(gd, _$d3_15.select(this), sliderOpts); + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); }); -}; -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_140.name], - sliderData = []; + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); - } + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; - return sliderData; -} + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_15.select(this), + opts = axisOpts[_$constants_126.name], + oppAxisOpts = fullLayout[_$axes_214.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_214.id2name(axisOpts.anchor)]; -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; -} + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_76.tester.selectAll('g.' + _$constants_140.labelGroupClass) - .data(sliderOpts.steps); + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); + } - sliderLabels.enter().append('g') - .classed(_$constants_140.labelGroupClass, true); + axisOpts.cleanRange('rangeslider.range'); - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_15.select(this); - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + // update range slider dimensions - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_76.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; + + var oppBottom = Infinity; + var subplotData = _$axes_214.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_214.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - }); - sliderLabels.remove(); + opts._id = _$constants_126.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; - var dims = sliderOpts._dims = {}; + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); - dims.inputAreaWidth = Math.max( - _$constants_140.railWidth, - _$constants_140.gripHeight - ); + var x = Math.round(margin.l + (graphSize.w * domain[0])); - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_126.extraPad + ); - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; - } + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + // update data <--> pixel coordinate conversion methods - var textableInputLength = dims.inputAreaLength - 2 * _$constants_140.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_140.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_76.tester.append('g'); + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_76.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_192.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); + opts._rl = [range0, range1]; - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; - dummyGroup.remove(); - } + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; + } - dims.height = dims.currentValueTotalHeight + _$constants_140.tickOffset + sliderOpts.ticklen + _$constants_140.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + // update inner nodes - var xanchor = 'left'; - if(_$anchor_utils_103.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_103.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); - var yanchor = 'top'; - if(_$anchor_utils_103.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_103.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; - } + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - _$plots_246.autoMargin(gd, _$constants_140.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_142[xanchor], - r: dims.outerLength * __FROM_BR_142[xanchor], - b: dims.height * __FROM_BR_142[yanchor], - t: dims.height * __FROM_TL_142[yanchor] - }); -} + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_144.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); + } -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; - } + // update margins + _$plots_246.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_126.extraPad + opts._offsetShift * 2 + }); + }); +}; - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); +function makeRangeSliderData(fullLayout) { + var axes = _$axes_214.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_126.name, + out = []; - var dims = sliderOpts._dims; + if(fullLayout._has('gl2d')) return out; - // Position the rectangle: - _$drawing_76.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); + if(ax[name] && ax[name].visible) out.push(ax); + } + return out; } -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_126.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_126.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_126.grabAreaMaxClassName).node(); - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; + rangeSlider.on('mousedown', function() { + var event = _$d3_15.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_140.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; - break; - default: - x0 = _$constants_140.currentValueInset; - textAnchor = 'left'; - } + var dragCover = _$dragelement_73.coverSlip(); - text.enter().append('text') - .classed(_$constants_140.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; - } + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; - text.call(_$drawing_76.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_192.convertToTspans, sliderOpts._gd); + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; - var lines = _$svg_text_utils_192.lineCount(text); + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_142; + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - _$svg_text_utils_192.positionText(text, x0, y0); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - return text; + _$setCursor_191(_$d3_15.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); + } + + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_172.removeElement(dragCover); + } + }); } -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_140.gripRectClass) - .data([0]); +function setDataRange(rangeSlider, gd, axisOpts, opts) { - grip.enter().append('rect') - .classed(_$constants_140.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + function clamp(v) { + return axisOpts.l2r(_$lib_172.constrain(v, opts._rl[0], opts._rl[1])); + } - grip.attr({ - width: _$constants_140.gripWidth, - height: _$constants_140.gripHeight, - rx: _$constants_140.gripRadius, - ry: _$constants_140.gripRadius, - }) - .call(_$color_51.stroke, sliderOpts.bordercolor) - .call(_$color_51.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); + + window.requestAnimationFrame(function() { + _$registry_262.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); } -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_126.handleWidth / 2; - text.enter().append('text') - .classed(_$constants_140.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); + function clamp(v) { + return _$lib_172.constrain(v, 0, opts._width); + } - text.call(_$drawing_76.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_192.convertToTspans, sliderOpts._gd); + function clampOppAxis(v) { + return _$lib_172.constrain(v, 0, opts._height); + } - return text; -} + function clampHandle(v) { + return _$lib_172.constrain(v, -hw2, opts._width + hw2); + } -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_140.labelsClass) - .data([0]); - var dims = sliderOpts._dims; + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); - labels.enter().append('g') - .classed(_$constants_140.labelsClass, true); + rangeSlider.select('rect.' + _$constants_126.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); - var labelItems = labels.selectAll('g.' + _$constants_140.labelGroupClass) - .data(dims.labelSteps); + rangeSlider.select('rect.' + _$constants_126.maskMinClassName) + .attr('width', pixelMin); - labelItems.enter().append('g') - .classed(_$constants_140.labelGroupClass, true); + rangeSlider.select('rect.' + _$constants_126.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - labelItems.exit().remove(); + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - labelItems.each(function(d) { - var item = _$d3_15.select(this); + rangeSlider.select('rect.' + _$constants_126.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - item.call(drawLabel, d, sliderOpts); + rangeSlider.select('rect.' + _$constants_126.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - _$drawing_76.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_140.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_142 + - _$constants_140.labelOffset + - dims.currentValueTotalHeight - ); - }); + rangeSlider.select('rect.' + _$constants_126.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); + } -} + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); - } + rangeSlider.select('g.' + _$constants_126.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + + rangeSlider.select('g.' + _$constants_126.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); } -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_172.ensureSingle(rangeSlider, 'rect', _$constants_126.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var step = sliderOpts.steps[sliderOpts.active]; + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + var offsetShift = -opts._offsetShift; + var lw = _$drawing_76.crispRound(gd, opts.borderwidth); - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw }); +} - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; - if(_step.execute) { - _$plots_246.executeAPICommand(gd, _step.method, _step.args); - } + var clipPath = _$lib_172.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); - } - } + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); } -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_15.select(gd); - - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; - } +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_214.getSubplots(gd, axisOpts), + calcData = gd.calcdata; - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); + var rangePlots = rangeSlider.selectAll('g.' + _$constants_126.rangePlotClassName) + .data(subplotData, _$lib_172.identity); - var grip = sliderGroup.select('.' + _$constants_140.gripRectClass); + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_126.rangePlotClassName + ' ' + id; }) + .call(_$drawing_76.setClipUrl, opts._clipId); - _$d3_15.event.stopPropagation(); - _$d3_15.event.preventDefault(); - grip.call(_$color_51.fill, sliderOpts.activebgcolor); + rangePlots.order(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_15.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; + rangePlots.exit().remove(); - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_15.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + var mainplotinfo; - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_51.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + rangePlots.each(function(id, i) { + var plotgroup = _$d3_15.select(this), + isMainPlot = (i === 0); - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); -} + var oppAxisOpts = _$axes_214.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_140.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; - tick.enter().append('rect') - .classed(_$constants_140.tickRectClass, true); + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; - tick.exit().remove(); + _$plots_246.supplyDefaults(mockFigure); - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' - }); + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_15.select(this); + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_51.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + if(isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; + } - _$drawing_76.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_140.tickOffset : _$constants_140.minorTickOffset) + dims.currentValueTotalHeight - ); + _$cartesian_225.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); }); - } -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; + + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } } + + return out; } -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_140.gripRectClass); +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_172.ensureSingle(rangeSlider, 'rect', _$constants_126.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var x = normalizedValueToPosition(sliderOpts, position); + maskMin + .attr('height', opts._height) + .call(_$color_51.fill, _$constants_126.maskColor); - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; + var maskMax = _$lib_172.ensureSingle(rangeSlider, 'rect', _$constants_126.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); - } + maskMax + .attr('height', opts._height) + .call(_$color_51.fill, _$constants_126.maskColor); - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_140.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); -} + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_172.ensureSingle(rangeSlider, 'rect', _$constants_126.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_140.stepInset + - (dims.inputAreaLength - 2 * _$constants_140.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_51.fill, _$constants_126.maskOppAxisColor); -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_140.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_140.stepInset - 2 * dims.inputAreaStart))); -} + var maskMaxOppAxis = _$lib_172.ensureSingle(rangeSlider, 'rect', _$constants_126.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_140.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_126.maskOppBorder) + .call(_$color_51.fill, _$constants_126.maskOppAxisColor); + } +} - rect.enter().append('rect') - .classed(_$constants_140.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_140.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_51.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + var slideBox = _$lib_172.ensureSingle(rangeSlider, 'rect', _$constants_126.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_126.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); - _$drawing_76.setTranslate(rect, 0, dims.currentValueTotalHeight); + slideBox.attr({ + height: opts._height, + fill: _$constants_126.slideBoxFill + }); } -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_140.railRectClass) - .data([0]); - var dims = sliderOpts._dims; +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_172.ensureSingle(rangeSlider, 'g', _$constants_126.grabberMinClassName); + var grabberMax = _$lib_172.ensureSingle(rangeSlider, 'g', _$constants_126.grabberMaxClassName); + + // + var handleFixAttrs = { + x: 0, + width: _$constants_126.handleWidth, + rx: _$constants_126.handleRadius, + fill: _$color_51.background, + stroke: _$color_51.defaultLine, + 'stroke-width': _$constants_126.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_172.ensureSingle(grabberMin, 'rect', _$constants_126.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMin.attr(handleDynamicAttrs); + + var handleMax = _$lib_172.ensureSingle(grabberMax, 'rect', _$constants_126.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); - rect.enter().append('rect') - .classed(_$constants_140.railRectClass, true); + // + if(gd._context.staticPlot) return; - var computedLength = dims.inputAreaLength - _$constants_140.railInset * 2; + var grabAreaFixAttrs = { + width: _$constants_126.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_126.grabAreaFill, + cursor: _$constants_126.grabAreaCursor + }; - rect.attr({ - width: computedLength, - height: _$constants_140.railWidth, - rx: _$constants_140.railRadius, - ry: _$constants_140.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_51.stroke, sliderOpts.bordercolor) - .call(_$color_51.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + var grabAreaMin = _$lib_172.ensureSingle(grabberMin, 'rect', _$constants_126.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMin.attr('height', opts._height); - _$drawing_76.setTranslate(rect, - _$constants_140.railInset, - (dims.inputAreaWidth - _$constants_140.railWidth) * 0.5 + dims.currentValueTotalHeight - ); + var grabAreaMax = _$lib_172.ensureSingle(grabberMax, 'rect', _$constants_126.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMax.attr('height', opts._height); } -function __clearPushMargins_142(gd) { +function clearPushMargins(gd) { var pushMargins = gd._fullLayout._pushmargin || {}, keys = Object.keys(pushMargins); for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_140.autoMarginIdRoot) !== -1) { + if(k.indexOf(_$constants_126.name) !== -1) { _$plots_246.autoMargin(gd, k); } } @@ -52969,16 +54978,28 @@ function __clearPushMargins_142(gd) { 'use strict'; -/* removed: var _$constants_140 = require('./constants'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$attributes_124 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_130 = require('./oppaxis_attributes'); */; -var _$sliders_143 = { +var _$rangeslider_129 = { moduleType: 'component', - name: _$constants_140.name, + name: 'rangeslider', - layoutAttributes: _$attributes_139, - supplyLayoutDefaults: _$slidersDefaults_141, + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_172.extendFlat({}, _$attributes_124, { + yaxis: _$oppaxis_attributes_130 + }) + } + } + }, - draw: _$draw_142 + layoutAttributes: _$attributes_124, + handleDefaults: _$handleDefaults_127, + calcAutorange: _$calcAutorange_125, + draw: _$draw_128 }; /** @@ -52991,149 +55012,131 @@ var _$sliders_143 = { 'use strict'; -/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_50 = require('../color/attributes'); */; -var __extendFlat_145 = _$extend_165.extendFlat; -var __overrideAll_145 = _$edit_types_198.overrideAll; -/* removed: var _$pad_attributes_245 = require('../../plots/pad_attributes'); */; - -var buttonsAttrs = { - _isLinkedToArray: 'button', - - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} - ], - - }, - label: { - valType: 'string', - - dflt: '', - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; +/* removed: var _$attributes_36 = require('../annotations/attributes'); */; +var __scatterLineAttrs_131 = _$attributes_369.line; +var __dash_131 = _$attributes_75.dash; +var __extendFlat_131 = _$extend_166.extendFlat; -var _$attributes_145 = __overrideAll_145({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], +var _$attributes_131 = { + _isLinkedToArray: 'shape', visible: { valType: 'boolean', + dflt: true, + editType: 'calcIfAutorange+arraydraw', }, type: { valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', + values: ['circle', 'rect', 'path', 'line'], + editType: 'calcIfAutorange+arraydraw', }, - direction: { + layer: { valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', + values: ['below', 'above'], + dflt: 'above', + editType: 'arraydraw', }, - active: { - valType: 'integer', + xref: __extendFlat_131({}, _$attributes_36.xref, { - min: -1, - dflt: 0, + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', }, - - showactive: { - valType: 'boolean', + xanchor: { + valType: 'any', - dflt: true, + editType: 'calcIfAutorange+arraydraw', }, - - buttons: buttonsAttrs, - - x: { - valType: 'number', - min: -2, - max: 3, - dflt: -0.05, + x0: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'right', + x1: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, + + yref: __extendFlat_131({}, _$attributes_36.yref, { + }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', }, yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - - pad: __extendFlat_145({}, _$pad_attributes_245, { + y0: { + valType: 'any', - }), - - font: _$font_attributes_240({ + editType: 'calcIfAutorange+arraydraw', - }), - - bgcolor: { - valType: 'color', + }, + y1: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_50.borderLine, + + path: { + valType: 'string', + editType: 'calcIfAutorange+arraydraw', }, - borderwidth: { + + opacity: { valType: 'number', min: 0, + max: 1, dflt: 1, editType: 'arraydraw', - } -}, 'arraydraw', 'from-root'); + }, + line: { + color: __extendFlat_131({}, __scatterLineAttrs_131.color, {editType: 'arraydraw'}), + width: __extendFlat_131({}, __scatterLineAttrs_131.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_131({}, __dash_131, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -53147,74 +55150,58 @@ var _$attributes_145 = __overrideAll_145({ 'use strict'; -var _$constants_146 = { - - // 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, +var _$constants_133 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, - // color given to active buttons - activeColor: '#F4FAFF', + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - // color given to hovered buttons - hoverColor: '#F4FAFF', + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, - // symbol for menu open arrow - arrowSymbol: { - left: '◄', - right: '►', - up: '▲', - down: '▼' + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 } }; +var _$helpers_136 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53223,561 +55210,326 @@ var _$constants_146 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_209 = require('../../plots/array_container_defaults'); */; +'use strict'; -/* removed: var _$attributes_145 = require('./attributes'); */; -/* removed: var _$constants_146 = require('./constants'); */; +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. -var __name_147 = _$constants_146.name; -var __buttonAttrs_147 = _$attributes_145.buttons; +_$helpers_136.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; +}; +_$helpers_136.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; +}; -var _$updateMenusDefaults_147 = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_147, - handleItemDefaults: menuDefaults +_$helpers_136.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); }; - - _$handleArrayContainerDefaults_209(layoutIn, layoutOut, opts); }; -function menuDefaults(menuIn, menuOut, layoutOut) { - - function coerce(attr, dflt) { - return _$lib_171.coerce(menuIn, menuOut, _$attributes_145, attr, dflt); - } - - var buttons = __buttonsDefaults_147(menuIn, menuOut); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - - coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); - - coerce('x'); - coerce('y'); - _$lib_171.noneOrAll(menuIn, menuOut, ['x', 'y']); - - coerce('xanchor'); - coerce('yanchor'); - - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); - - _$lib_171.coerceFont(coerce, 'font', layoutOut.font); - - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); -} - -function __buttonsDefaults_147(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; - - var buttonIn, buttonOut; - - function coerce(attr, dflt) { - return _$lib_171.coerce(buttonIn, buttonOut, __buttonAttrs_147, attr, dflt); - } - - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; +_$helpers_136.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; +}; - coerce('method'); +_$helpers_136.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; - if(!_$lib_171.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { - continue; - } + if(axis) { + var d2r = _$helpers_136.shapePositionToRange(axis); - coerce('args'); - coerce('label'); - coerce('execute'); + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; - buttonOut._index = i; - buttonsOut.push(buttonOut); + if(axis.type === 'date') dataToPixel = _$helpers_136.decodeDate(dataToPixel); } - - return buttonsOut; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$ScrollBox_150 = ScrollBox; - -/* removed: var _$d3_15 = require('d3'); */; - -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; - -/* removed: var _$lib_171 = require('../../lib'); */; - -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; - - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection - - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); - - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); - - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} - -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; - -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; - - // compute position of scrollbox - this.position = position; - - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; - - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + } + else { + dataToPixel = function(v) { return gs.l + gs.w * v; }; } - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; + return dataToPixel; +}; - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } +_$helpers_136.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; + + if(axis) { + var r2d = _$helpers_136.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; } else { - boxT = t; - boxB = boxT + boxH; - - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; - } + pixelToData = function(p) { return (p - gs.l) / gs.w; }; } - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; + return pixelToData; +}; - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); +'use strict'; - hbar.exit() - .on('.drag', null) - .remove(); +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_51.fill, ScrollBox.barColor); +/* removed: var _$constants_133 = require('./constants'); */; +/* removed: var _$helpers_136 = require('./helpers'); */; - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH - }); - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } +var _$calcAutorange_132 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + shapeList = _$lib_172.filterVisible(fullLayout.shapes); - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; + if(!shapeList.length || !gd._fullData.length) return; - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); + var ax, bounds; - vbar.exit() - .on('.drag', null) - .remove(); + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_214.getFromId(gd, shape.xref); - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_51.fill, ScrollBox.barColor); + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_133.paramIsX); - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH - }); + if(bounds) _$axes_214.expand(ax, bounds, calcXPaddingOptions(shape)); + } - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_214.getFromId(gd, shape.yref); + + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_133.paramIsY); + if(bounds) _$axes_214.expand(ax, bounds, calcYPaddingOptions(shape)); + } } +}; - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} - clipPath.exit().remove(); +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_133.paramIsY : _$constants_133.paramIsX) : + [v0, v1]; + var maxValue = _$lib_172.aggNums(Math.max, null, coords), + minValue = _$lib_172.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} - this.container.call(_$drawing_76.setClipUrl, clipId); +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } - else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_76.setClipUrl, null); - delete this._clipRect; - } + var segments = path.match(_$constants_133.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_15.behavior.drag() - .on('dragstart', function() { - _$d3_15.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + var params = segment.substr(1).match(_$constants_133.paramRE); + if(!params || params.length < relevantParamIdx) return; - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + extractedCoordinates.push(params[relevantParamIdx]); + }); - var onBarDrag = _$d3_15.behavior.drag() - .on('dragstart', function() { - _$d3_15.event.sourceEvent.preventDefault(); - _$d3_15.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + return extractedCoordinates; +} - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); - } +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); - } - } + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_133.segmentRE), + i, + segment, + drawnParam, + params, + val; -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_76.setClipUrl, null); - delete this._clipRect; - } + if(ax.type === 'date') convertVal = _$helpers_136.decodeDate(convertVal); - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; + params = segments[i].substr(1).match(_$constants_133.paramRE); + if(!params || params.length < drawnParam) continue; + + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; } -}; + if(max >= min) return [min, max]; +} /** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(this.hbar) { - translateX -= _$d3_15.event.dx; - } - if(this.vbar) { - translateY -= _$d3_15.event.dy; - } +'use strict'; - this.setTranslate(translateX, translateY); -}; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; +/* removed: var _$attributes_131 = require('./attributes'); */; +/* removed: var _$helpers_136 = require('./helpers'); */; - if(this.hbar) { - translateX += _$d3_15.event.deltaY; - } - if(this.vbar) { - translateY += _$d3_15.event.deltaY; +var _$handleShapeDefaults_138 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; + + function coerce(attr, dflt) { + return _$lib_172.coerce(shapeIn, shapeOut, _$attributes_131, attr, dflt); } - this.setTranslate(translateX, translateY); -}; + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); -/** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + if(!visible) return shapeOut; - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_171.constrain(_$d3_15.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - var translateXMax = this.position.w - this._box.w; + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); - translateX = xf * translateXMax; - } + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_171.constrain(_$d3_15.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); + // xref, yref + var axRef = _$axes_214.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - var translateYMax = this.position.h - this._box.h; + if(axRef !== 'paper') { + ax = _$axes_214.getFromId(gdMock, axRef); + r2pos = _$helpers_136.rangeToShapePosition(ax); + pos2r = _$helpers_136.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_172.identity; + } - translateY = yf * translateYMax; - } + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; - this.setTranslate(translateX, translateY); -}; + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); -/** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_214.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_214.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } - translateX = _$lib_171.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_171.constrain(translateY || 0, 0, translateYMax); + // hack part 2 + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } - this.translateX = translateX; - this.translateY = translateY; + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); - this.container.call(_$drawing_76.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); + _$axes_214.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) - }); + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; + } } - if(this.hbar) { - var xf = translateX / translateXMax; - - this.hbar.call(_$drawing_76.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); + if(shapeType === 'path') { + coerce('path'); } - - if(this.vbar) { - var yf = translateY / translateYMax; - - this.vbar.call(_$drawing_76.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); + else { + _$lib_172.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); } + + return shapeOut; }; /** @@ -53791,736 +55543,996 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$handleArrayContainerDefaults_210 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_138 = require('./shape_defaults'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$color_51 = require('../color'); */; -/* removed: var _$drawing_76 = require('../drawing'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_103 = require('../legend/anchor_utils'); */; -var __LINE_SPACING_148 = _$alignment_151.LINE_SPACING; +var _$supplyLayoutDefaults_134 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_138 + }; -/* removed: var _$constants_146 = require('./constants'); */; -/* removed: var _$ScrollBox_150 = require('./scrollbox'); */; + _$handleArrayContainerDefaults_210(layoutIn, layoutOut, opts); +}; -var _$draw_148 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_146.containerClassName) - .data(menuData.length > 0 ? [0] : []); +'use strict'; - menus.enter().append('g') - .classed(_$constants_146.containerClassName, true) - .style('cursor', 'pointer'); +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; - menus.exit().remove(); +/* removed: var _$dragelement_73 = require('../dragelement'); */; +/* removed: var _$setCursor_191 = require('../../lib/setcursor'); */; - // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_148(gd); +/* removed: var _$constants_133 = require('./constants'); */; +/* removed: var _$helpers_136 = require('./helpers'); */; - // return early if no update menus are visible - if(menuData.length === 0) return; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_146.headerGroupClassName) - .data(menuData, __keyFunction_148); +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - headerGroups.enter().append('g') - .classed(_$constants_146.headerGroupClassName, true); +var _$draw_135 = { + draw: __draw_135, + drawOne: __drawOne_135 +}; - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_146.dropdownButtonGroupClassName) - .data([0]); +function __draw_135(gd) { + var fullLayout = gd._fullLayout; - gButton.enter().append('g') - .classed(_$constants_146.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_148(gd, menuOpts); + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); } - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_150(gd, gButton, scrollBoxId); + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_135(gd, i); + } + } - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); +} - gButton - .call(removeAllButtons) - .attr(_$constants_146.menuIndexAttrName, '-1'); - } +function __drawOne_135(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - headerGroups.exit().each(function(menuOpts) { - _$d3_15.select(this).remove(); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; - gButton - .call(removeAllButtons) - .attr(_$constants_146.menuIndexAttrName, '-1'); + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; - _$plots_246.autoMargin(gd, _$constants_146.autoMarginIdRoot + menuOpts._index); - }); + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); + } + } - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_15.select(this); + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_246.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_148(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); - }); + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_51.stroke, lineColor) + .call(_$color_51.fill, options.fillcolor) + .call(_$drawing_76.dashLine, options.line.dash, options.line.width); - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - // if this menu is active, update the dropdown container - if(__isActive_148(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); - } + path.call(_$drawing_76.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null + ); - }); -}; + if(gd._context.edits.shapePosition) __setupDragElement_135(gd, path, options, index); + } +} -/** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_146.name]; - var menuData = []; +function __setupDragElement_135(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; - if(item.visible) menuData.push(item); - } + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; - return menuData; -} + var xa, ya, x2p, y2p, p2x, p2y; -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_148(menuOpts) { - return menuOpts._index; -} + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; -function isFolded(gButton) { - return +gButton.attr(_$constants_146.menuIndexAttrName) === -1; -} + _$dragelement_73.init(dragOptions); -function __isActive_148(gButton, menuOpts) { - return +gButton.attr(_$constants_146.menuIndexAttrName) === menuOpts._index; -} + shapePath.node().onmousemove = updateDragMode; -function __setActive_148(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; + function updateDragMode(evt) { + // element might not be on screen at time of setup, + // so obtain bounding box here + var dragBBox = dragOptions.element.getBoundingClientRect(); - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_146.menuIndexAttrName, '-1'); + // choose 'move' or 'resize' + // based on initial position of cursor within the drag element + var w = dragBBox.right - dragBBox.left, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_73.getCursor(x / w, 1 - y / h) : + 'move'; - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + _$setCursor_191(shapePath, cursor); - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; } -} -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_146.headerClassName) - .data([0]); - var dims = menuOpts._dims; + function startDrag(evt) { + // setup conversion functions + xa = _$axes_214.getFromId(gd, shapeOptions.xref); + ya = _$axes_214.getFromId(gd, shapeOptions.yref); - header.enter().append('g') - .classed(_$constants_146.headerClassName, true) - .style('pointer-events', 'all'); + x2p = _$helpers_136.getDataToPixel(gd, xa); + y2p = _$helpers_136.getDataToPixel(gd, ya, true); + p2x = _$helpers_136.getPixelToData(gd, xa); + p2y = _$helpers_136.getPixelToData(gd, ya, true); - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_146.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_146.headerArrowClassName) - .data([0]); + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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); - arrow.enter().append('text') - .classed(_$constants_146.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_76.font, menuOpts.font) - .text(_$constants_146.arrowSymbol[menuOpts.direction]); + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; + } - arrow.attr({ - x: dims.headerWidth - _$constants_146.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_146.textOffsetY + menuOpts.pad.t - }); + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.x0'; optE = 'x0'; + } - header.on('click', function() { - gButton.call(removeAllButtons); + // 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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + } + update = {}; - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_146.menuIndexAttrName, - __isActive_148(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; + } - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - }); + function endDrag() { + _$setCursor_191(shapePath); + _$registry_262.call('relayout', gd, update); + } - header.on('mouseover', function() { - header.call(styleOnMouseOver); - }); + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_136.encodeDate(moveX); + } - // translate header group - _$drawing_76.setTranslate(gHeader, dims.lx, dims.ly); -} + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_136.encodeDate(moveY); + } -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var klass = menuOpts.type === 'dropdown' ? _$constants_146.dropdownButtonClassName : _$constants_146.buttonClassName; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_136.encodeDate(moveX); + } - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_136.encodeDate(moveY); + } - var enter = buttons.enter().append('g') - .classed(klass, true); + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; - var exit = buttons.exit(); + // 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; - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + // 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); + shapePath.attr('d', getPathString(gd, shapeOptions)); } +} - var x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_214.getFromId(gd, options.xref), + ya = _$axes_214.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + if(xa) { + x2r = _$helpers_136.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; + } + else { + x2p = function(v) { return gs.l + gs.w * v; }; + } - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_146.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_146.gapButtonHeader; - } + if(ya) { + y2r = _$helpers_136.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(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_146.gapButtonHeader + _$constants_146.gapButton - dims.openHeight; + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_136.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_136.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_146.gapButtonHeader + _$constants_146.gapButton - dims.openWidth; + 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); } - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_146.gapButton, - xPad: _$constants_146.gapButton, - index: 0, - }; + 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); + } - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; +} - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_15.select(this); - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; - button.on('click', function() { - // skip `dragend` events - if(_$d3_15.event.defaultPrevented) return; - __setActive_148(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + return pathIn.replace(_$constants_133.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_133.paramIsX[segmentType], + yParams = _$constants_133.paramIsY[segmentType], + nParams = _$constants_133.numParams[segmentType]; - if(buttonOpts.execute) { - _$plots_246.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + var paramString = segment.substr(1).replace(_$constants_133.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++; - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + if(paramNumber > nParams) param = 'X'; + return param; }); - button.on('mouseover', function() { - button.call(styleOnMouseOver); - }); + if(paramNumber > nParams) { + paramString = paramString.replace(/[\s,]*X.*/, ''); + _$lib_172.log('Ignoring extra params in segment ' + segment); + } - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); + return segmentType + paramString; }); +} - buttons.call(styleButtons, menuOpts); +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_133.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_133.paramIsX[segmentType], + yParams = _$constants_133.paramIsY[segmentType], + nParams = _$constants_133.numParams[segmentType]; - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); - } + var paramString = segment.substr(1).replace(_$constants_133.paramRE, function(param) { + if(paramNumber >= nParams) return param; - scrollBoxPosition.direction = menuOpts.direction; + if(xParams[paramNumber]) param = moveX(param); + else if(yParams[paramNumber]) param = moveY(param); - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); - } - } + paramNumber++; + + return param; + }); + + return segmentType + paramString; + }); } -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_146.gapButton; - } - } - else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_146.gapButton; - } - } - scrollBox.enable(position, translateX, translateY); +'use strict'; - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } +/* removed: var _$draw_135 = require('./draw'); */; + +var _$shapes_137 = { + moduleType: 'component', + name: 'shapes', + + layoutAttributes: _$attributes_131, + supplyLayoutDefaults: _$supplyLayoutDefaults_134, + includeBasePlot: _$makeIncludeComponents_224('shapes'), + + calcAutorange: _$calcAutorange_132, + draw: _$draw_135.draw, + drawOne: _$draw_135.drawOne +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } -} -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; +var _$constants_140 = { - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } + // layout attribute name + name: 'sliders', - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); - } -} + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); -} + railHeight: 5, -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', - rect.enter().append('rect') - .classed(_$constants_146.itemRectClassName, true) - .attr({ - rx: _$constants_146.rx, - ry: _$constants_146.ry, - 'shape-rendering': 'crispEdges' - }); + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', - rect.call(_$color_51.stroke, menuOpts.bordercolor) - .call(_$color_51.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); -} + // min item width / height + minWidth: 30, + minHeight: 30, -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); + // padding around item text + textPadX: 40, - text.enter().append('text') - .classed(_$constants_146.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + // arrow offset off right edge + arrowOffsetX: 4, - text.call(_$drawing_76.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_192.convertToTspans, gd); -} + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, - buttons.each(function(buttonOpts, i) { - var button = _$d3_15.select(this); + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_146.itemRectClassName) - .call(_$color_51.fill, _$constants_146.activeColor); - } - }); -} + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_146.itemRectClassName) - .call(_$color_51.fill, _$constants_146.hoverColor); -} + labelPadding: 8, + labelOffset: 0, -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_146.itemRectClassName) - .call(_$color_51.fill, menuOpts.bgcolor); -} + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, -// find item dimensions (this mutates menuOpts) -function __findDimensions_148(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, - var fakeButtons = _$drawing_76.tester.selectAll('g.' + _$constants_146.dropdownButtonClassName) - .data(menuOpts.buttons); + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, +}; - fakeButtons.enter().append('g') - .classed(_$constants_146.dropdownButtonClassName, true); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +'use strict'; - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_15.select(this); +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_245 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; - button.call(drawItem, menuOpts, buttonOpts, gd); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 text = button.select('.' + _$constants_146.itemTextClassName); +'use strict'; - // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_76.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_146.textPadX, _$constants_146.minWidth); +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_245 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_139 = _$extend_166.extendDeepAll; +var __overrideAll_139 = _$edit_types_199.overrideAll; +/* removed: var _$animation_attributes_209 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_140 = require('./constants'); */; - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_148; - var tLines = _$svg_text_utils_192.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_146.minHeight) + _$constants_146.textOffsetY; +var stepsAttrs = { + _isLinkedToArray: 'step', - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } + ], + + }, + label: { + valType: 'string', + + + }, + value: { + valType: 'string', + + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; +var _$attributes_139 = __overrideAll_139({ + _isLinkedToArray: 'slider', - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); + visible: { + valType: 'boolean', + + dflt: true, + + }, - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_146.gapButton; - dims.openHeight += hEff + _$constants_146.gapButton; - } else { - dims.totalWidth += wEff + _$constants_146.gapButton; - dims.openWidth += wEff + _$constants_146.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; + active: { + valType: 'number', + + min: 0, + dflt: 0, + + }, + + steps: stepsAttrs, + + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], + + dflt: 'fraction', + + }, + len: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + pad: __extendDeepAll_139({}, _$pad_attributes_245, { + + }, {t: {dflt: 20}}), + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, + + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_209.transition.easing.values, + + dflt: 'cubic-in-out', + } - }); + }, - if(isVertical) { - dims.totalHeight -= _$constants_146.gapButton; - } else { - dims.totalWidth -= _$constants_146.gapButton; - } + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, - dims.headerWidth = dims.width1 + _$constants_146.arrowPadX; - dims.headerHeight = dims.height1; + offset: { + valType: 'number', + dflt: 10, + + + }, - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_146.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_146.arrowPadX; - } + prefix: { + valType: 'string', + + + }, - fakeButtons.remove(); + suffix: { + valType: 'string', + + + }, - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; + font: _$font_attributes_240({ + + }) + }, - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); + font: _$font_attributes_240({ + + }), - var xanchor = 'left'; - if(_$anchor_utils_103.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = 'right'; - } - if(_$anchor_utils_103.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = 'center'; + activebgcolor: { + valType: 'color', + + dflt: _$constants_140.gripBgActiveColor, + + }, + bgcolor: { + valType: 'color', + + dflt: _$constants_140.railBgColor, + + }, + bordercolor: { + valType: 'color', + dflt: _$constants_140.railBorderColor, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_140.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_140.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_140.tickColor, + + + }, + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_140.minorTickLength, + + } +}, 'arraydraw', 'from-root'); - var yanchor = 'top'; - if(_$anchor_utils_103.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = 'bottom'; - } - if(_$anchor_utils_103.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = 'middle'; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); +'use strict'; - _$plots_246.autoMargin(gd, _$constants_146.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); -} +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_210 = require('../../plots/array_container_defaults'); */; -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_146.itemRectClassName); - var text = item.select('.' + _$constants_146.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; +/* removed: var _$attributes_139 = require('./attributes'); */; +/* removed: var _$constants_140 = require('./constants'); */; - _$drawing_76.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); +var __name_141 = _$constants_140.name; +var stepAttrs = _$attributes_139.steps; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight - }); +var _$slidersDefaults_141 = function slidersDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_141, + handleItemDefaults: sliderDefaults + }; - var tHeight = menuOpts.font.size * __LINE_SPACING_148; - var tLines = _$svg_text_utils_192.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); + _$handleArrayContainerDefaults_210(layoutIn, layoutOut, opts); +}; - _$svg_text_utils_192.positionText(text, _$constants_146.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_146.textOffsetY); +function sliderDefaults(sliderIn, sliderOut, layoutOut) { - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; + function coerce(attr, dflt) { + return _$lib_172.coerce(sliderIn, sliderOut, _$attributes_139, attr, dflt); } - posOpts.index++; -} + var steps = stepsDefaults(sliderIn, sliderOut); -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_146.dropdownButtonClassName).remove(); -} + var visible = coerce('visible', steps.length > 0); + if(!visible) return; -function __clearPushMargins_148(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); + coerce('active'); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + coerce('x'); + coerce('y'); + _$lib_172.noneOrAll(sliderIn, sliderOut, ['x', 'y']); - if(k.indexOf(_$constants_146.autoMarginIdRoot) !== -1) { - _$plots_246.autoMargin(gd, k); - } - } -} + coerce('xanchor'); + coerce('yanchor'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + coerce('len'); + coerce('lenmode'); -'use strict'; + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); -/* removed: var _$constants_146 = require('./constants'); */; + _$lib_172.coerceFont(coerce, 'font', layoutOut.font); -var _$updatemenus_149 = { - moduleType: 'component', - name: _$constants_146.name, + var currentValueIsVisible = coerce('currentvalue.visible'); - layoutAttributes: _$attributes_145, - supplyLayoutDefaults: _$updateMenusDefaults_147, + if(currentValueIsVisible) { + coerce('currentvalue.xanchor'); + coerce('currentvalue.prefix'); + coerce('currentvalue.suffix'); + coerce('currentvalue.offset'); - draw: _$draw_148 -}; + _$lib_172.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + } -var _$mathjax_config_158 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + coerce('transition.duration'); + coerce('transition.easing'); -'use strict'; + coerce('bgcolor'); + coerce('activebgcolor'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('ticklen'); + coerce('tickwidth'); + coerce('tickcolor'); + coerce('minorticklen'); +} -/* global MathJax:false */ +function stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; -/** - * Check and configure MathJax - */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_158.MathJax = true; + var valueIn, valueOut; - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] + function coerce(attr, dflt) { + return _$lib_172.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + } + + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; + + coerce('method'); + + if(!_$lib_172.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + continue; } - }); - MathJax.Hub.Configured(); -} else { - _$mathjax_config_158.MathJax = false; + coerce('args'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); + coerce('execute'); + + valuesOut.push(valueOut); + } + + return valuesOut; } /** @@ -54531,893 +56543,784 @@ if(typeof MathJax !== 'undefined') { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_171 = require('../lib'); */; -/* removed: var _$plot_config_203 = require('../plot_api/plot_config'); */; +/* removed: var _$d3_15 = require('d3'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_103 = require('../legend/anchor_utils'); */; -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; +/* removed: var _$constants_140 = require('./constants'); */; +/* removed: var _$alignment_151 = require('../../constants/alignment'); */; +var __LINE_SPACING_142 = _$alignment_151.LINE_SPACING; +var __FROM_TL_142 = _$alignment_151.FROM_TL; +var __FROM_BR_142 = _$alignment_151.FROM_BR; - for(var i = 0; i < args.length; i++) { - arg = args[i]; +var _$draw_142 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_171.extendDeep([], arg) : - _$lib_171.extendDeepAll({}, arg); - } - else copy[i] = arg; - } + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_140.containerClassName) + .data(sliderData.length > 0 ? [0] : []); - return copy; -} + sliders.enter().append('g') + .classed(_$constants_140.containerClassName, true) + .style('cursor', 'ew-resize'); + sliders.exit().remove(); -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_142(gd); + // Return early if no menus visible: + if(sliderData.length === 0) return; -var __queue_185 = {}; + var sliderGroups = sliders.selectAll('g.' + _$constants_140.groupClassName) + .data(sliderData, keyFunction); -// TODO: disable/enable undo and redo buttons appropriately + sliderGroups.enter().append('g') + .classed(_$constants_140.groupClassName, true); -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_185.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + sliderGroups.exit().each(function(sliderOpts) { + _$d3_15.select(this).remove(); - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } + _$plots_246.autoMargin(gd, _$constants_140.autoMarginIdRoot + sliderOpts._index); + }); - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); } - gd.undoQueue.beginSequence = false; - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); - } + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; - if(gd.undoQueue.queue.length > _$plot_config_203.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; - } -}; + var gSlider = _$d3_15.select(this); -/** - * Begin a sequence of undoQueue changes - * - * @param gd - */ -__queue_185.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; + computeLabelSteps(sliderOpts); -/** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended - * - * @param gd - */ -__queue_185.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; -}; + _$plots_246.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; -/** - * Move one step back in the undo queue, and undo the object there. - * - * @param gd - */ -__queue_185.undo = function undo(gd) { - var queueObj, i; + if(opts.active === data.index) return; + if(opts._dragging) return; - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; - } + setActive(gd, gSlider, opts, data.index, false, true); + }); - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; + drawSlider(gd, _$d3_15.select(this), sliderOpts); + }); +}; - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_140.name], + sliderData = []; - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_185.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; -/** - * Redo the current object in the undo, then move forward in the queue. - * - * @param gd - */ -__queue_185.redo = function redo(gd) { - var queueObj, i; + return sliderData; +} - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; - } +// This is set in the defaults step: +function keyFunction(opts) { + return opts._index; +} - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_76.tester.selectAll('g.' + _$constants_140.labelGroupClass) + .data(sliderOpts.steps); - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_185.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); - } - gd.undoQueue.inSequence = false; - gd.autoplay = false; + sliderLabels.enter().append('g') + .classed(_$constants_140.labelGroupClass, true); - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; -}; + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_15.select(this); -/** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. - * - * @param gd - * @param func - * @param args - */ -__queue_185.plotDo = function(gd, func, args) { - gd.autoplay = true; + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_76.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + } + }); - // call the supplied function - func.apply(null, args); -}; + sliderLabels.remove(); -var _$queue_185 = __queue_185; + var dims = sliderOpts._dims = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + dims.inputAreaWidth = Math.max( + _$constants_140.railWidth, + _$constants_140.gripHeight + ); -'use strict'; + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); -var _$localeEnUs_195 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' - }, - format: { - date: '%m/%d/%Y' + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); -'use strict'; + var textableInputLength = dims.inputAreaLength - 2 * _$constants_140.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_140.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; -var _$localeEn_196 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' - } -}; + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; -var _$fromQuat_19 = fromQuat; + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_76.tester.append('g'); -/** - * 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, + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_76.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_193.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); - 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; + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + + dummyGroup.remove(); + } + + dims.height = dims.currentValueTotalHeight + _$constants_140.tickOffset + sliderOpts.ticklen + _$constants_140.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + + var xanchor = 'left'; + if(_$anchor_utils_103.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; + } + if(_$anchor_utils_103.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; + } - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; + var yanchor = 'top'; + if(_$anchor_utils_103.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_103.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; + } - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + _$plots_246.autoMargin(gd, _$constants_140.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_142[xanchor], + r: dims.outerLength * __FROM_BR_142[xanchor], + b: dims.height * __FROM_BR_142[yanchor], + t: dims.height * __FROM_TL_142[yanchor] + }); +} - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; + } - return out; -}; -var _$helpers_199 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); + var dims = sliderOpts._dims; -'use strict'; + // Position the rectangle: + _$drawing_76.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); -/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_19 = require('gl-mat4/fromQuat'); */; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); -/* removed: var _$registry_261 = require('../registry'); */; -/* removed: var _$lib_171 = require('../lib'); */; -/* removed: var _$plots_246 = require('../plots/plots'); */; -/* removed: var _$axis_ids_216 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_216.cleanId; -var getFromTrace = _$axis_ids_216.getFromTrace; -/* removed: var _$color_51 = require('../components/color'); */; +} +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; -// clear the promise queue if one of them got rejected -_$helpers_199.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_171.log('Clearing previous rejected promises from queue.'); - } + var dims = sliderOpts._dims; + var x0, textAnchor; - gd._promises = []; -}; + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_140.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_140.currentValueInset; + textAnchor = 'left'; + } -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_199.cleanLayout = function(layout) { - var i, j; + var text = _$lib_172.ensureSingle(sliderGroup, 'text', _$constants_140.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); - if(!layout) layout = {}; + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; + + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; } - var axisAttrRegex = (_$plots_246.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_246.subplotsRegistry.gl3d || {}).attrRegex; + text.call(_$drawing_76.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_193.convertToTspans, sliderOpts._gd); - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; + var lines = _$svg_text_utils_193.lineCount(text); - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_142; - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories + _$svg_text_utils_193.positionText(text, x0, y0); - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; + return text; +} - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; - } - } +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_172.ensureSingle(sliderGroup, 'rect', _$constants_140.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; + grip.attr({ + width: _$constants_140.gripWidth, + height: _$constants_140.gripHeight, + rx: _$constants_140.gripRadius, + ry: _$constants_140.gripRadius, + }) + .call(_$color_51.stroke, sliderOpts.bordercolor) + .call(_$color_51.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); +} - // clean old Camera coords - var cameraposition = scene.cameraposition; +function drawLabel(item, data, sliderOpts) { + var text = _$lib_172.ensureSingle(item, 'text', _$constants_140.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_19([], rotation), - eye = []; + text.call(_$drawing_76.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_193.convertToTspans, sliderOpts._gd); - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } + return text; +} - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_172.ensureSingle(sliderGroup, 'g', _$constants_140.labelsClass); + var dims = sliderOpts._dims; - delete scene.cameraposition; - } - } - } + var labelItems = labels.selectAll('g.' + _$constants_140.labelGroupClass) + .data(dims.labelSteps); - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; + labelItems.enter().append('g') + .classed(_$constants_140.labelGroupClass, true); - if(!_$lib_171.isPlainObject(ann)) continue; + labelItems.exit().remove(); - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } + labelItems.each(function(d) { + var item = _$d3_15.select(this); - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); - } + item.call(drawLabel, d, sliderOpts); - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; + _$drawing_76.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_140.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_142 + + _$constants_140.labelOffset + + dims.currentValueTotalHeight + ); + }); - if(!_$lib_171.isPlainObject(shape)) continue; +} - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); } +} - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; - } - } + var step = sliderOpts.steps[sliderOpts.active]; - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_51.clean(layout); + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); - return layout; -}; + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); + if(_step.execute) { + _$plots_246.executeAPICommand(gd, _step.method, _step.args); + } + + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } } } -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_199.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_15.select(gd); - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; + } - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); - for(i = 0; i < 100; i++) { - newUid = _$lib_171.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_171.randstr(uids); - uids.push(trace.uid); - } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); + var grip = sliderGroup.select('.' + _$constants_140.gripRectClass); - // BACKWARD COMPATIBILITY FIXES + _$d3_15.event.stopPropagation(); + _$d3_15.event.preventDefault(); + grip.call(_$color_51.fill, sliderOpts.activebgcolor); - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_15.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_51.defaults, - yeColor = trace.error_y.color || - (_$registry_261.traceIs(trace, 'bar') ? _$color_51.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_51.addOpacity( - _$color_51.rgb(yeColor), - _$color_51.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_15.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); + }); - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_261.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_199.swapXYData(trace); - } - delete trace.bardir; - } + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_51.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_199.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; - } + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); + }); +} - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_140.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + tick.enter().append('rect') + .classed(_$constants_140.tickRectClass, true); - // scene ids scene1 -> scene - if(_$registry_261.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_246.subplotsRegistry.gl3d.cleanId(trace.scene); - } + tick.exit().remove(); - if(!_$registry_261.traceIs(trace, 'pie') && !_$registry_261.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); - // fix typo in colorscale definition - if(_$registry_261.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_261.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_15.select(this); - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_171.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_51.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; + _$drawing_76.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_140.tickOffset : _$constants_140.minorTickOffset) + dims.currentValueTotalHeight + ); + }); - if(!_$lib_171.isPlainObject(opts)) continue; +} - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } - } + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); + } +} - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_140.gripRectClass); - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + var x = normalizedValueToPosition(sliderOpts, position); - if(!_$lib_171.isPlainObject(transform)) continue; + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); + } - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_140.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); +} - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_140.stepInset + + (dims.inputAreaLength - 2 * _$constants_140.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_140.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_140.stepInset - 2 * dims.inputAreaStart))); +} - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } - } +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_172.ensureSingle(sliderGroup, 'rect', _$constants_140.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; - } + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_140.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_51.fill, sliderOpts.bgcolor) + .attr('opacity', 0); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_51.clean(trace); - } -}; + _$drawing_76.setTranslate(rect, 0, dims.currentValueTotalHeight); +} -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_140.railInset * 2; + var rect = _$lib_172.ensureSingle(sliderGroup, 'rect', _$constants_140.railRectClass); - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + rect.attr({ + width: computedLength, + height: _$constants_140.railWidth, + rx: _$constants_140.railRadius, + ry: _$constants_140.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_51.stroke, sliderOpts.bordercolor) + .call(_$color_51.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - return posY + ' ' + posX; + _$drawing_76.setTranslate(rect, + _$constants_140.railInset, + (dims.inputAreaWidth - _$constants_140.railWidth) * 0.5 + dims.currentValueTotalHeight + ); } -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); -} +function __clearPushMargins_142(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; -// swap all the data and data attributes associated with x and y -_$helpers_199.swapXYData = function(trace) { - var i; - _$lib_171.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_171.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_171.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); - } - } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + if(k.indexOf(_$constants_140.autoMarginIdRoot) !== -1) { + _$plots_246.autoMargin(gd, k); } - trace.hoverinfo = hoverInfoParts.join('+'); } -}; +} -// coerce traceIndices input to array of trace indices -_$helpers_199.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_18(traceIndices)) { - return [traceIndices]; - } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 traceIndices; +'use strict'; + +/* removed: var _$constants_140 = require('./constants'); */; + +var _$sliders_143 = { + moduleType: 'component', + name: _$constants_140.name, + + layoutAttributes: _$attributes_139, + supplyLayoutDefaults: _$slidersDefaults_141, + + draw: _$draw_142 }; /** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_199.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; +* Copyright 2012-2018, Plotly, Inc. +* All 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 pLastIsNumber = _$fastIsnumeric_18(pLast); +'use strict'; - // delete item - if(pLastIsNumber && newVal === null) { +/* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_50 = require('../color/attributes'); */; +var __extendFlat_145 = _$extend_166.extendFlat; +var __overrideAll_145 = _$edit_types_199.overrideAll; +/* removed: var _$pad_attributes_245 = require('../../plots/pad_attributes'); */; - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_171.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); +var buttonsAttrs = { + _isLinkedToArray: 'button', - // Note that nested property clears null / undefined at end of - // array container, but not within them. + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + } - // create item - else if(pLastIsNumber && np.get() === undefined) { +}; - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; +var _$attributes_145 = __overrideAll_145({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - np.set(newVal); - } - // update item - else { + visible: { + valType: 'boolean', + + + }, - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); - } -}; + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); -} + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_199.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; -}; + showactive: { + valType: 'boolean', + + dflt: true, + + }, -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_199 = ['x', 'y', 'z']; -_$helpers_199.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_199[j]); + buttons: buttonsAttrs, - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_171.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } -}; + pad: __extendFlat_145({}, _$pad_attributes_245, { + + }), -_$helpers_199.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; - } + font: _$font_attributes_240({ + + }), + + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_50.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + } -}; +}, 'arraydraw', 'from-root'); -var _$manage_arrays_201 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -55429,209 +57332,75 @@ var _$manage_arrays_201 = {}; 'use strict'; -/* removed: var _$nestedProperty_179 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_173 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_180 = require('../lib/noop'); */; -/* removed: var _$loggers_176 = require('../lib/loggers'); */; -var sorterAsc = _$search_189.sorterAsc; -/* removed: var _$registry_261 = require('../registry'); */; - - -_$manage_arrays_201.containerArrayMatch = _$containerArrayMatch_197; - -var isAddVal = _$manage_arrays_201.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_173(val); -}; - -var isRemoveVal = _$manage_arrays_201.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; - -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_201.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_261.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_261.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_261.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_180) || - (draw === _$noop_180), - layout = gd.layout, - fullLayout = gd._fullLayout; - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_176.warn('Full array edits are incompatible with other edits', - componentType); - } +var _$constants_146 = { - var fullVal = edits['']['']; + // layout attribute name + name: 'updatemenus', - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); - else { - _$loggers_176.warn('Unrecognized full array edit value', componentType, fullVal); - return true; - } + // 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', - if(replotLater) return false; + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'updatemenu-active-index', - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; - } + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'updatemenu-', - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_179(fullLayout, componentType).get(); + // options when 'active: -1' + blankHeaderOpts: { label: ' ' }, - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; + // min item width / height + minWidth: 30, + minHeight: 30, - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + // padding around item text + textPadX: 24, + arrowPadX: 16, - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_176.warn('index out of range', componentType, componentNum); - continue; - } + // item rect radii + rx: 2, + ry: 2, - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_176.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } + // item text x offset off left edge + textOffsetX: 12, - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_176.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } + // item text y offset (w.r.t. middle) + textOffsetY: 3, - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_179(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } - } + // arrow offset off right edge + arrowOffsetX: 4, - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); - } + // gap between header and buttons + gapButtonHeader: 5, - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); + // gap between between buttons + gapButton: 2, - if(replotLater) return false; + // color given to active buttons + activeColor: '#F4FAFF', - supplyComponentDefaults(layout, fullLayout); + // color given to hovered buttons + hoverColor: '#F4FAFF', - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_180) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); - } + // symbol for menu open arrow + arrowSymbol: { + left: '◄', + right: '►', + up: '▲', + down: '▼' } - else draw(gd); - - return true; }; -var _$buttons_113 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -55640,2805 +57409,2245 @@ var _$buttons_113 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$plots_246 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_216 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_210 = require('../../plots/array_container_defaults'); */; -var ____113 = _$lib_171._; +/* removed: var _$attributes_145 = require('./attributes'); */; +/* removed: var _$constants_146 = require('./constants'); */; -var modeBarButtons = _$buttons_113 = {}; +var __name_147 = _$constants_146.name; +var __buttonAttrs_147 = _$attributes_145.buttons; -/** - * 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) { return ____113(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; +var _$updateMenusDefaults_147 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_147, + handleItemDefaults: menuDefaults + }; - _$lib_171.notifier(____113(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + _$handleArrayContainerDefaults_210(layoutIn, layoutOut, opts); +}; - if(_$lib_171.isIE()) { - _$lib_171.notifier(____113(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; - } +function menuDefaults(menuIn, menuOut, layoutOut) { - _$registry_261.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_171.notifier(____113(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_171.notifier(____113(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); + function coerce(attr, dflt) { + return _$lib_172.coerce(menuIn, menuOut, _$attributes_145, attr, dflt); } -}; -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____113(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_246.sendDataToCloud(gd); - } -}; + var buttons = __buttonsDefaults_147(menuIn, menuOut); -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____113(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian -}; + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____113(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian -}; + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____113(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; + coerce('x'); + coerce('y'); + _$lib_172.noneOrAll(menuIn, menuOut, ['x', 'y']); -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____113(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian -}; + coerce('xanchor'); + coerce('yanchor'); -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____113(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian -}; + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____113(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian -}; + _$lib_172.coerceFont(coerce, 'font', layoutOut.font); -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____113(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian -}; + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____113(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian -}; +function __buttonsDefaults_147(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____113(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian -}; + var buttonIn, buttonOut; -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____113(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; - }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian -}; + function coerce(attr, dflt) { + return _$lib_172.coerce(buttonIn, buttonOut, __buttonAttrs_147, attr, dflt); + } -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 = _$axis_ids_216.list(gd, null, true); - var allSpikesEnabled = 'on'; + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; - var ax, i; + coerce('method'); - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; + if(!_$lib_172.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } - var axName; + coerce('args'); + coerce('label'); + coerce('execute'); - for(i = 0; i < axList.length; i++) { - ax = axList[i]; + buttonOut._index = i; + buttonsOut.push(buttonOut); + } - 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]; - } - 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]), - ]; + return buttonsOut; +} - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); - aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); - } - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } +'use strict'; - aobj[astr] = val; - } +var _$ScrollBox_150 = ScrollBox; - _$registry_261.call('relayout', gd, aobj); -} +/* removed: var _$d3_15 = require('d3'); */; -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____113(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d -}; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____113(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d -}; +/* removed: var _$lib_172 = require('../../lib'); */; -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____113(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d -}; +/** + * Helper class to setup a scroll box + * + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box + */ +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____113(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['z-axis'], - click: handleDrag3d -}; + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection -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 = {}; + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); - var parts = attr.split('.'); + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); - for(var i = 0; i < sceneIds.length; i++) { - layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; - } + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} - // for multi-type subplots - var val2d = (val === 'pan') ? val : 'zoom'; - layoutUpdate.dragmode = val2d; +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; - _$registry_261.call('relayout', gd, layoutUpdate); -} +/** + * If needed, setup a clip path and scrollbars + * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____113(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; + // compute position of scrollbox + this.position = position; -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____113(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d -}; + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; -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 = {}; + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; + } - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; + + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; + } + } + else { + boxT = t; + boxB = boxT + boxH; - if(attr === 'resetDefault') { - aobj[key] = null; + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_171.extendDeep({}, scene.cameraInitial); + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; } } - _$registry_261.call('relayout', gd, aobj); -} + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; + hbar.exit() + .on('.drag', null) + .remove(); - if(val) { - layoutUpdate = _$lib_171.extendDeep(layout, val); - button._previousVal = null; + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_51.fill, ScrollBox.barColor); + + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); + + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; } else { - layoutUpdate = { - 'allaxes.showspikes': false - }; + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; - } - } - } + vbar.exit() + .on('.drag', null) + .remove(); - button._previousVal = _$lib_171.extendDeep({}, currentSpikes); - } + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_51.fill, ScrollBox.barColor); - _$registry_261.call('relayout', gd, layoutUpdate); -} + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____113(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; + } + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____113(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____113(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo -}; + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + clipPath.exit().remove(); -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; + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); - for(var i = 0; i < geoIds.length; i++) { - var id = geoIds[i]; - var geoLayout = fullLayout[id]; + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); - if(attr === 'zoom') { - var scale = geoLayout.projection.scale; - var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; + this.container.call(_$drawing_76.setClipUrl, clipId); - _$registry_261.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); - } + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); } -} - -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; - -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; - -function toggleHover(gd) { - var fullLayout = gd._fullLayout; - - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_76.setClipUrl, null); + delete this._clipRect; } - else onHoverVal = 'closest'; - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_15.behavior.drag() + .on('dragstart', function() { + _$d3_15.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); - _$registry_261.call('relayout', gd, 'hovermode', newHover); -} + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); -// buttons when more then one plot types are present + var onBarDrag = _$d3_15.behavior.drag() + .on('dragstart', function() { + _$d3_15.event.sourceEvent.preventDefault(); + _$d3_15.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } } -}; - -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____113(gd, 'Reset views'); }, - icon: _$ploticon_2.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'); - } + // set scrollbox translation + this.setTranslate(translateX, translateY); }; -modeBarButtons.toggleSpikelines = { - name: 'toggleSpikelines', - title: function(gd) { return ____113(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; - - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; +/** + * If present, remove clip-path and scrollbars + * + * @method + */ +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_76.setClipUrl, null); + delete this._clipRect; + } - var aobj = setSpikelineVisibility(gd); + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } - _$registry_261.call('relayout', gd, aobj); + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } }; -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_216.list(gd, null, true); - var aobj = {}; - - var ax, axName; +/** + * Handles scroll box drag events + * + * @method + */ +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + if(this.hbar) { + translateX -= _$d3_15.event.dx; } - return aobj; -} - -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____113(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); + if(this.vbar) { + translateY -= _$d3_15.event.dy; } + + this.setTranslate(translateX, translateY); }; -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; +/** + * Handles scroll box wheel events + * + * @method + */ +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; - 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); + if(this.hbar) { + translateX += _$d3_15.event.deltaY; + } - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; - } + if(this.vbar) { + translateY += _$d3_15.event.deltaY; } - _$registry_261.call('relayout', gd, aObj); -} + this.setTranslate(translateX, translateY); +}; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; + * Handles scroll bar drag events + * + * @method + */ +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; -/* removed: var _$d3_15 = require('d3'); */; + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_172.constrain(_$d3_15.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; + var translateXMax = this.position.w - this._box.w; + translateX = xf * translateXMax; + } -/** - * 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'); + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_172.constrain(_$d3_15.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); - this.update(opts.graphInfo, opts.buttons); + var translateYMax = this.position.h - this._box.h; - this.container.appendChild(this.element); -} + translateY = yf * translateYMax; + } -var proto = ModeBar.prototype; + this.setTranslate(translateX, translateY); +}; /** - * 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 + * Set clip path and scroll bar translate transform * + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) */ -proto.update = function(graphInfo, buttons) { - this.graphInfo = graphInfo; +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; - var context = this.graphInfo._context; + translateX = _$lib_172.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_172.constrain(translateY || 0, 0, translateYMax); - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; - } - else this.element.className = 'modebar'; + this.translateX = translateX; + this.translateY = translateY; - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); + this.container.call(_$drawing_76.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } - this.updateButtons(buttons); + if(this.hbar) { + var xf = translateX / translateXMax; - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; - } + this.hbar.call(_$drawing_76.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); } - this.updateActiveButton(); + if(this.vbar) { + var yf = translateY / translateYMax; + + this.vbar.call(_$drawing_76.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); + } }; -proto.updateButtons = function(buttons) { - var _this = this; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); +'use strict'; - 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); +/* removed: var _$d3_15 = require('d3'); */; - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$color_51 = require('../color'); */; +/* removed: var _$drawing_76 = require('../drawing'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_103 = require('../legend/anchor_utils'); */; - _this.element.appendChild(group); - }); -}; +var __LINE_SPACING_148 = _$alignment_151.LINE_SPACING; -/** - * Empty div for containing a group of buttons - * @Return {HTMLelement} - */ -proto.createGroup = function() { - var group = document.createElement('div'); - group.className = 'modebar-group'; +/* removed: var _$constants_146 = require('./constants'); */; +/* removed: var _$ScrollBox_150 = require('./scrollbox'); */; - return group; -}; +var _$draw_148 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); -/** - * 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, - button = document.createElement('a'); + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ - button.setAttribute('rel', 'tooltip'); - button.className = 'modebar-btn'; + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_146.containerClassName) + .data(menuData.length > 0 ? [0] : []); - 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); + menus.enter().append('g') + .classed(_$constants_146.containerClassName, true) + .style('cursor', 'pointer'); - if(title || title === 0) button.setAttribute('data-title', title); + menus.exit().remove(); - if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_148(gd); - var val = config.val; - if(val !== undefined) { - if(typeof val === 'function') val = val(this.graphInfo); - button.setAttribute('data-val', val); - } + // return early if no update menus are visible + if(menuData.length === 0) return; - 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); + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_146.headerGroupClassName) + .data(menuData, __keyFunction_148); - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); - } + headerGroups.enter().append('g') + .classed(_$constants_146.headerGroupClassName, true); - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_15.select(button).classed('active', true); + // draw dropdown button container + var gButton = _$lib_172.ensureSingle(menus, 'g', _$constants_146.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - button.setAttribute('data-gravity', config.gravity || 'n'); + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_148(gd, menuOpts); + } - return button; -}; + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_150(gd, gButton, scrollBoxId); -/** - * Add an icon to a button - * @Param {object} thisIcon - * @Param {number} thisIcon.width - * @Param {string} thisIcon.path - * @Return {HTMLelement} - */ -proto.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); + gButton + .call(removeAllButtons) + .attr(_$constants_146.menuIndexAttrName, '-1'); + } - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; + headerGroups.exit().each(function(menuOpts) { + _$d3_15.select(this).remove(); - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); + gButton + .call(removeAllButtons) + .attr(_$constants_146.menuIndexAttrName, '-1'); - return icon; -}; + _$plots_246.autoMargin(gd, _$constants_146.autoMarginIdRoot + menuOpts._index); + }); -/** - * 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, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_15.select(this); - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_15.select(button); + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_246.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_148(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); - // 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_171.nestedProperty(fullLayout, dataAttr).get(); + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - button3.classed('active', val === thisval); + // if this menu is active, update the dropdown container + if(__isActive_148(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); } }); }; /** - * Check if modeBar is configured as button configuration argument - * - * @Param {object} buttons 2d array of grouped button config objects - * @Return {boolean} + * get only visible menus for display */ -proto.hasButtons = function(buttons) { - var currentButtons = this.buttons; - - if(!currentButtons) return false; +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_146.name]; + var menuData = []; - if(buttons.length !== currentButtons.length) return false; + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; - 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; - } + if(item.visible) menuData.push(item); } - return true; -}; + return menuData; +} -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -proto.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_148(menuOpts) { + return menuOpts._index; +} - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_171._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; +function isFolded(gButton) { + return +gButton.attr(_$constants_146.menuIndexAttrName) === -1; +} - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); +function __isActive_148(gButton, menuOpts) { + return +gButton.attr(_$constants_146.menuIndexAttrName) === menuOpts._index; +} - group.appendChild(a); - return group; -}; +function __setActive_148(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; -proto.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_146.menuIndexAttrName, '-1'); - this.hasLogo = false; -}; - -proto.destroy = function() { - _$lib_171.removeElement(this.container.querySelector('.modebar')); -}; - -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; - - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - if(fullLayout._privateplot) { - _$d3_15.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } } - - return modeBar; } -var _$createModeBar_116 = createModeBar; +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_172.ensureSingle(gHeader, 'g', _$constants_146.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_146.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); -'use strict'; + // draw drop arrow at the right edge + var arrow = _$lib_172.ensureSingle(gHeader, 'text', _$constants_146.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_76.font, menuOpts.font) + .text(_$constants_146.arrowSymbol[menuOpts.direction]); + }); -/* removed: var _$axis_ids_216 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_390 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_261 = require('../../registry'); */; + arrow.attr({ + x: dims.headerWidth - _$constants_146.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_146.textOffsetY + menuOpts.pad.t + }); -/* removed: var _$createModeBar_116 = require('./modebar'); */; -/* removed: var _$buttons_113 = require('./buttons'); */; + header.on('click', function() { + gButton.call(removeAllButtons); -/** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object - * - */ -var _$manageModeBar_115 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_146.menuIndexAttrName, + __isActive_148(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); - var customButtons = context.modeBarButtons; - var buttonGroups; + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } + // translate header group + _$drawing_76.setTranslate(gHeader, dims.lx, dims.ly); +} - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_116(gd, buttonGroups); -}; +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); + var klass = menuOpts.type === 'dropdown' ? _$constants_146.dropdownButtonClassName : _$constants_146.buttonClassName; - var groups = []; + var buttons = gButton.selectAll('g.' + klass) + .data(buttonData); - function addGroup(newGroup) { - if(!newGroup.length) return; + var enter = buttons.enter().append('g') + .classed(klass, true); - var out = []; + var exit = buttons.exit(); - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_113[button]); - } + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); - groups.push(out); + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; - } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; - } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; - } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; - } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; - } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_146.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_146.gapButtonHeader; + } } - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_146.gapButtonHeader + _$constants_146.gapButton - dims.openHeight; } - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; - } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_146.gapButtonHeader + _$constants_146.gapButton - dims.openWidth; } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_146.gapButton, + xPad: _$constants_146.gapButton, + index: 0, + }; - return appendButtonsToGroups(groups, buttonsToAdd); -} + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_216.list({_fullLayout: fullLayout}, null, true); + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_15.select(this); - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } - } + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); - return true; -} + button.on('click', function() { + // skip `dragend` events + if(_$d3_15.event.defaultPrevented) return; -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; + __setActive_148(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; + if(buttonOpts.execute) { + _$plots_246.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } - var trace = fullData[i]; + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); - if(!trace._module || !trace._module.selectPoints) continue; + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); - if(_$registry_261.traceIs(trace, 'scatter-like')) { - if(_$subtypes_390.hasMarkers(trace) || _$subtypes_390.hasText(trace)) { - selectable = true; - } - } else if(_$registry_261.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); + + buttons.call(styleButtons, menuOpts); + + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); } - return selectable; + scrollBoxPosition.direction = menuOpts.direction; + + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } } -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; + + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_146.gapButton; + } + } + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_146.gapButton; } - else groups.push(buttons); } - return groups; + scrollBox.enable(position, translateX, translateY); + + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } + + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } } -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } - if(typeof button === 'string') { - if(_$buttons_113[button] !== undefined) { - customButtons[i][j] = _$buttons_113[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); } +} - return customButtons; +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); } -var _$modebar_114 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function drawItemRect(item, menuOpts) { + var rect = _$lib_172.ensureSingle(item, 'rect', _$constants_146.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_146.rx, + ry: _$constants_146.ry, + 'shape-rendering': 'crispEdges' + }); + }); + rect.call(_$color_51.stroke, menuOpts.bordercolor) + .call(_$color_51.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} -'use strict'; +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_172.ensureSingle(item, 'text', _$constants_146.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); -_$modebar_114.manage = _$manageModeBar_115; + text.call(_$drawing_76.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_193.convertToTspans, gd); +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; + buttons.each(function(buttonOpts, i) { + var button = _$d3_15.select(this); -'use strict'; + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_146.itemRectClassName) + .call(_$color_51.fill, _$constants_146.activeColor); + } + }); +} -var FROM_BL = _$alignment_151.FROM_BL; +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_146.itemRectClassName) + .call(_$color_51.fill, _$constants_146.hoverColor); +} -var _$scaleZoom_230 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_146.itemRectClassName) + .call(_$color_51.fill, menuOpts.bgcolor); +} - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; +// find item dimensions (this mutates menuOpts) +function __findDimensions_148(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; + var fakeButtons = _$drawing_76.tester.selectAll('g.' + _$constants_146.dropdownButtonClassName) + .data(menuOpts.buttons); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + fakeButtons.enter().append('g') + .classed(_$constants_146.dropdownButtonClassName, true); -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_15.select(this); - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + button.call(drawItem, menuOpts, buttonOpts, gd); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + var text = button.select('.' + _$constants_146.itemTextClassName); -var _$BuildLog_25 = BuildLog; + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_76.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_146.textPadX, _$constants_146.minWidth); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_148; + var tLines = _$svg_text_utils_193.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_146.minHeight) + _$constants_146.textOffsetY; -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_146.gapButton; + dims.openHeight += hEff + _$constants_146.gapButton; + } else { + dims.totalWidth += wEff + _$constants_146.gapButton; + dims.openWidth += wEff + _$constants_146.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; + if(isVertical) { + dims.totalHeight -= _$constants_146.gapButton; + } else { + dims.totalWidth -= _$constants_146.gapButton; + } - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; + dims.headerWidth = dims.width1 + _$constants_146.arrowPadX; + dims.headerHeight = dims.height1; - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_146.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_146.arrowPadX; + } - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; + fakeButtons.remove(); - // categorize where intersection point is along A and B + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + var xanchor = 'left'; + if(_$anchor_utils_103.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_103.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + var yanchor = 'top'; + if(_$anchor_utils_103.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_103.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; + } - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; + _$plots_246.autoMargin(gd, _$constants_146.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); } -var _$Epsilon_26 = Epsilon; +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_146.itemRectClassName); + var text = item.select('.' + _$constants_146.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + _$drawing_76.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + var tHeight = menuOpts.font.size * __LINE_SPACING_148; + var tLines = _$svg_text_utils_193.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); - // 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] }); - } + _$svg_text_utils_193.positionText(text, _$constants_146.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_146.textOffsetY); - // the first LineString is considered the outside - var out = LineString(coords[0]); + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; + } - // 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]))); + posOpts.index++; +} - return out; - } +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_146.dropdownButtonClassName).remove(); +} - 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'); - }, +function __clearPushMargins_148(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - // 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)); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - // 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); - } + if(k.indexOf(_$constants_146.autoMarginIdRoot) !== -1) { + _$plots_246.autoMargin(gd, k); + } + } +} - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function newNode(region){ - return { - region: region, - children: [] - }; - } +'use strict'; - var roots = newNode(null); +/* removed: var _$constants_146 = require('./constants'); */; - 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; - } - } +var _$updatemenus_149 = { + moduleType: 'component', + name: _$constants_146.name, - // 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--; - } - } + layoutAttributes: _$attributes_145, + supplyLayoutDefaults: _$updateMenusDefaults_147, - // now we can add ourselves - root.children.push(node); - } + draw: _$draw_148 +}; - // 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); - } +var _$mathjax_config_158 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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 +'use strict'; - // while we're at it, exteriors are counter-clockwise, and interiors are clockwise +/* global MathJax:false */ - 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; - } +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_158.MathJax = true; - var geopolys = []; + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); - 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])); - } + MathJax.Hub.Configured(); +} else { + _$mathjax_config_158.MathJax = false; +} - 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); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); - // lastly, construct the approrpriate GeoJSON object +'use strict'; - 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 - }; - } -}; +/* removed: var _$lib_172 = require('../lib'); */; +/* removed: var _$plot_config_204 = require('../plot_api/plot_config'); */; -var _$GeoJSON_27 = GeoJSON; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + for(var i = 0; i < args.length; i++) { + arg = args[i]; -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_172.extendDeep([], arg) : + _$lib_172.extendDeepAll({}, arg); + } + else copy[i] = arg; + } -var _$LinkedList_29 = LinkedList; + return copy; +} -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs -// -// this is the core work-horse -// +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- + + +var __queue_186 = {}; + +// TODO: disable/enable undo and redo buttons appropriately + +/** + * Add an item to the undoQueue for a graphDiv + * + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with + */ +__queue_186.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; + + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; + + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } + + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; + + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } + + if(gd.undoQueue.queue.length > _$plot_config_204.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; -/* removed: var _$LinkedList_29 = require('./linked-list'); */; +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_186.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_186.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; +}; - // - // segment creation - // +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_186.undo = function undo(gd) { + var queueObj, i; - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; - // - // event logic - // + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - var event_root = _$LinkedList_29.create(); + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_186.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd + */ +__queue_186.redo = function redo(gd) { + var queueObj, i; - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_186.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; +}; - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_29.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_186.plotDo = function(gd, func, args) { + gd.autoplay = true; - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_29.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + // call the supplied function + func.apply(null, args); +}; - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) +var _$queue_186 = __queue_186; - if (buildLog) - buildLog.segmentChop(ev.seg, end); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } +'use strict'; - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } +var _$localeEnUs_196 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } +}; - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // - // status logic - // +'use strict'; - var status_root = _$LinkedList_29.create(); +var _$localeEn_197 = { + 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' + } +}; - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; +var _$fromQuat_19 = fromQuat; - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } +/** + * 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, - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + 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; - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; - if (buildLog) - buildLog.checkIntersection(seg1, seg2); + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; - var i = eps.linesIntersect(a1, a2, b1, b2); + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; - if (i === false){ - // segments are parallel or coincident + return out; +}; +var _$helpers_200 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection +'use strict'; - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); +/* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_19 = require('gl-mat4/fromQuat'); */; - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal +/* removed: var _$registry_262 = require('../registry'); */; +/* removed: var _$lib_172 = require('../lib'); */; +/* removed: var _$plots_246 = require('../plots/plots'); */; +/* removed: var _$axis_ids_217 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_217.cleanId; +var getFromTrace = _$axis_ids_217.getFromTrace; +/* removed: var _$color_51 = require('../components/color'); */; - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); +// clear the promise queue if one of them got rejected +_$helpers_200.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_172.log('Clearing previous rejected promises from queue.'); + } - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } + gd._promises = []; +}; - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_200.cleanLayout = function(layout) { + var i, j; - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + if(!layout) layout = {}; - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); + var axisAttrRegex = (_$plots_246.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_246.subplotsRegistry.gl3d || {}).attrRegex; - if (buildLog) - buildLog.vert(ev.pt[0]); + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[i]; - if (ev.isStart){ + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; + } + delete ax.autotick; + } + } - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev + // clean old Camera coords + var cameraposition = scene.cameraposition; - // merge ev.seg's fill information into eve.seg + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_19([], rotation), + eye = []; - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; - if (buildLog) - buildLog.segmentUpdate(eve.seg); + delete scene.cameraposition; + } + } + } - ev.other.remove(); - ev.remove(); - } + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } + if(!_$lib_172.isPlainObject(ann)) continue; - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; + } + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; + } - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); + } - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + if(!_$lib_172.isPlainObject(shape)) continue; - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); + } - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_29.node({ ev: ev })); - } - else{ - var st = ev.status; + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; - if (buildLog) - buildLog.statusRemove(st.ev.seg); + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_51.clean(layout); - // remove the status - st.remove(); + return layout; +}; - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); + } +} - // remove the event and continue - event_root.getHead().remove(); - } +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_200.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); - if (buildLog) - buildLog.done(); + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; - return segments; - } + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } + for(i = 0; i < 100; i++) { + newUid = _$lib_172.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_172.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; + // BACKWARD COMPATIBILITY FIXES - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; -} + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_51.defaults, + yeColor = trace.error_y.color || + (_$registry_262.traceIs(trace, 'bar') ? _$color_51.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_51.addOpacity( + _$color_51.rgb(yeColor), + _$color_51.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; + } -var _$Intersecter_28 = Intersecter; + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_262.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_200.swapXYData(trace); + } + delete trace.bardir; + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_200.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } + // scene ids scene1 -> scene + if(_$registry_262.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_246.subplotsRegistry.gl3d.cleanId(trace.scene); + } - if (buildLog) - buildLog.chainStart(seg); + if(!_$registry_262.traceIs(trace, 'pie') && !_$registry_262.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + // fix typo in colorscale definition + if(_$registry_262.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_262.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_172.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; - if (next_match === second_match){ - // we matched a single chain + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; - if (buildLog) - buildLog.chainMatch(first_match.index); + if(!_$lib_172.isPlainObject(opts)) continue; - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } + } - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; - if (buildLog) - buildLog.chainClose(first_match.index); + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; - // we have a closed chain! - regions.push(chain); - return; - } + if(!_$lib_172.isPlainObject(transform)) continue; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } - // otherwise, we matched two chains, so we need to combine those chains together + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } + } - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_51.clean(trace); + } +}; - var F = first_match.index; - var S = second_match.index; +function cleanFinanceDir(dirContainer) { + if(!_$lib_172.isPlainObject(dirContainer)) return false; - if (buildLog) - buildLog.chainConnect(F, S); + var dirName = dirContainer.name; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); + delete dirContainer.name; + delete dirContainer.showlegend; - return regions; + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); } -var _$SegmentChainer_30 = SegmentChainer; +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; -// -// filter a list of segments based on boolean operations -// + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + var out = name1.substr(0, i); + return out.trim(); +} - if (buildLog) - buildLog.selected(result); +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; - return result; + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; + + return posY + ' ' + posX; } -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} + + +// swap all the data and data attributes associated with x and y +_$helpers_200.swapXYData = function(trace) { + var i; + _$lib_172.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_172.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_172.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); + } }; -var _$SegmentSelector_31 = SegmentSelector; +// coerce traceIndices input to array of trace indices +_$helpers_200.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_18(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); + } -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs + return traceIndices; +}; + +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * */ +_$helpers_200.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; -/* removed: var _$BuildLog_25 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_26 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_28 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_30 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_31 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_27 = require('./lib/geojson'); */; + var pLastIsNumber = _$fastIsnumeric_18(pLast); -var buildLog = false; -var epsilon = _$Epsilon_26(); + // delete item + if(pLastIsNumber && newVal === null) { -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_25(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_172.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); - // core API - segments: function(poly){ - var i = _$Intersecter_28(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_28(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_31.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_31.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_31.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_31.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_31.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_30(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_27.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_27.fromPolygon(PolyBool, epsilon, poly); - }, + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; - // 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); - } + np.set(newVal); + } + // update item + else { + + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); + } }; -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); +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); } -if (typeof window === 'object') - window.PolyBool = PolyBool; +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_200.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; +}; + +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_200 = ['x', 'y', 'z']; +_$helpers_200.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_200[j]); + + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; + } + var typeAttr = axAttr + '.type'; -var _$PolyBool_24 = PolyBool; + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_172.nestedProperty(gd.layout, typeAttr).set(null); + } + } + } + } +}; + +_$helpers_200.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; + } + } +}; -var _$polygon_183 = {}; +var _$manage_arrays_202 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -58450,293 +59659,209 @@ var _$polygon_183 = {}; 'use strict'; -var dot = _$matrix_177.dot; -var __BADNUM_183 = _$numerical_154.BADNUM; - -var polygon = _$polygon_183 = {}; +/* removed: var _$nestedProperty_180 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_174 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_181 = require('../lib/noop'); */; +/* removed: var _$loggers_177 = require('../lib/loggers'); */; +var sorterAsc = _$search_190.sorterAsc; +/* removed: var _$registry_262 = require('../registry'); */; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; +_$manage_arrays_202.containerArrayMatch = _$containerArrayMatch_198; - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } +var isAddVal = _$manage_arrays_202.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_174(val); +}; - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed +var isRemoveVal = _$manage_arrays_202.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; - var isRect = false, - rectFirstEdgeTest; +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. + * + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items + * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. + */ +_$manage_arrays_202.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_262.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_262.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_262.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_181) || + (draw === _$noop_181), + layout = gd.layout, + fullLayout = gd._fullLayout; - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_177.warn('Full array edits are incompatible with other edits', + componentType); } - } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var fullVal = edits['']['']; - if(x === __BADNUM_183 || x < xmin || x > xmax || y === __BADNUM_183 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_177.warn('Unrecognized full array edit value', componentType, fullVal); + return true; } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + if(replotLater) return false; + + supplyComponentDefaults(layout, fullLayout); + draw(gd); return true; } - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_180(fullLayout, componentType).get(); - if(x === __BADNUM_183 || x < xmin || x > xmax || y === __BADNUM_183 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_177.warn('index out of range', componentType, componentNum); + continue; + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_177.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; + + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } - // inside the bounding box, check the actual line intercept else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } - - if(y <= ycross && x !== xmini) crossings++; + _$loggers_177.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); } - } - - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; + if(firstIndexChange === -1) firstIndexChange = componentNum; } - } - - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; - -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; - - for(var i = 0; i < list.length; i++) { - 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); - } - - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_180(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } - - return yes; } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; - -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; - - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); - - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - return false; -}; -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); + if(replotLater) return false; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; + supplyComponentDefaults(layout, fullLayout); + + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_181) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); } } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); + } } + else draw(gd); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); - } - - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; + return true; }; +var _$buttons_113 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -58748,1483 +59873,1166 @@ polygon.filter = function filter(pts, tolerance) { 'use strict'; -/* removed: var _$PolyBool_24 = require('polybooljs'); */; -/* removed: var _$polygon_183 = require('../../lib/polygon'); */; -/* removed: var _$throttle_193 = require('../../lib/throttle'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -var makeEventData = _$helpers_90.makeEventData; -/* removed: var _$fx_93 = require('../../components/fx'); */; - -/* removed: var _$axes_213 = require('./axes'); */; -/* removed: var _$constants_218 = require('./constants'); */; - -var filteredPolygon = _$polygon_183.filter; -var polygonTester = _$polygon_183.tester; -var multipolygonTester = _$polygon_183.multitester; -var MINSELECT = _$constants_218.MINSELECT; - -function getAxId(ax) { return ax._id; } - -var _$prepSelect_231 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } - - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_218.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'); +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$plots_246 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_217 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_51.background, - stroke: _$color_51.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +var ____113 = _$lib_172._; +var modeBarButtons = _$buttons_113 = {}; - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_218.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; +/** + * 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? + */ - 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; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____113(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + _$lib_172.notifier(____113(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_213.getFromId(gd, trace.xaxis), - yaxis: _$axes_213.getFromId(gd, trace.yaxis) - }); + if(_$lib_172.isIE()) { + _$lib_172.notifier(____113(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; } - } - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + _$registry_262.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_172.notifier(____113(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_172.notifier(____113(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); } +}; - function ascending(a, b) { return a - b; } +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____113(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_246.sendDataToCloud(gd); + } +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____113(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____113(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____113(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian +}; - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____113(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } - } +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____113(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian +}; - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____113(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian +}; - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____113(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____113(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____113(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____113(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +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 = _$axis_ids_217.list(gd, null, true); + var allSpikesEnabled = 'on'; - _$throttle_193.throttle( - throttleID, - _$constants_218.SELECTDELAY, - function() { - selection = []; + var ax, i; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); + var axName; - thisSelection = fillSelectionItem(traceSelection, searchInfo); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); + 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]; + } + if(ax._showSpikeInitial !== undefined) { + aobj[axName + '.showspikes'] = ax._showSpikeInitial; + if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) { + allSpikesEnabled = 'off'; } } - else selection = thisSelection; } + else { + var rangeNow = [ + ax.r2l(ax.range[0]), + ax.r2l(ax.range[1]), + ]; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; - - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - _$throttle_193.done(throttleID).then(function() { - _$throttle_193.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); } - - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); } - else { - // 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. - gd.emit('plotly_selected', undefined); + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } - _$fx_93.click(gd, evt); - }); - }; - - dragOptions.doneFn = function() { - corners.remove(); + aobj[astr] = val; + } - _$throttle_193.done(throttleID).then(function() { - _$throttle_193.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); + _$registry_262.call('relayout', gd, aobj); +} - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____113(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d +}; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____113(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____113(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - if(eventData) { - var pts = eventData.points || []; +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____113(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['z-axis'], + click: handleDrag3d +}; - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +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 = {}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; + var parts = attr.split('.'); - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); - } - } + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - else { - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; + + _$registry_262.call('relayout', gd, layoutUpdate); +} + +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____113(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; + +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____113(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.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], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; + + if(attr === 'resetDefault') { + aobj[key] = null; + } + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_172.extendDeep({}, scene.cameraInitial); } } - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } + _$registry_262.call('relayout', gd, aobj); } -function mergePolygons(list, poly, subtract) { - var res; +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - if(subtract) { - res = _$PolyBool_24.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - return res.regions; + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; + + if(val) { + layoutUpdate = _$lib_172.extendDeep(layout, val); + button._previousVal = null; } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - res = _$PolyBool_24.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; - return res.regions; -} + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; -function fillSelectionItem(selection, searchInfo) { - if(Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - for(var i = 0; i < selection.length; i++) { - selection[i] = makeEventData(selection[i], trace, cd); + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + } + } } + + button._previousVal = _$lib_172.extendDeep({}, currentSpikes); } - return selection; + _$registry_262.call('relayout', gd, layoutUpdate); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____113(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____113(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; -'use strict'; +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____113(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; -/* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_21 = require('has-passive-events'); */; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$fx_93 = require('../../components/fx'); */; -/* removed: var _$setCursor_190 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_73 = require('../../components/dragelement'); */; -var __FROM_TL_221 = _$alignment_151.FROM_TL; +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; -/* removed: var _$plots_246 = require('../plots'); */; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; -var doTicks = _$axes_213.doTicks; -var getFromId = _$axis_ids_216.getFromId; -/* removed: var _$prepSelect_231 = require('./select'); */; -/* removed: var _$scaleZoom_230 = require('./scale_zoom'); */; + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; -/* removed: var _$constants_218 = require('./constants'); */; -var MINDRAG = _$constants_218.MINDRAG; -var MINZOOM = _$constants_218.MINZOOM; + _$registry_262.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); + } + } +} +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px +function toggleHover(gd) { var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + } + else onHoverVal = 'closest'; - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$registry_262.call('relayout', gd, 'hovermode', newHover); +} - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); +// buttons when more then one plot types are present - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____113(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____113(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); } +}; - recomputeAxisLists(); +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____113(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - var allFixedRanges = !yActive && !xActive; + var aobj = setSpikelineVisibility(gd); - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; + _$registry_262.call('relayout', gd, aobj); } +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_231(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_217.list(gd, null, true); + var aobj = {}; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + var ax, axName; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - if(numClicks === 2 && !singleEnd) doubleClick(); + return aobj; +} - if(isMainDrag) { - _$fx_93.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____113(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if(ax.fixedrange) return; +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; + 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); - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_15.select(dragger) - .call(_$svg_text_utils_192.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_261.call('relayout', gd, attrStr, v); - } - }); - } - } + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; } - }; - - _$dragelement_73.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + } - // collected changes to be made to the plot by relayout at the end - var updates = {}; + _$registry_262.call('relayout', gd, aObj); +} - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_33(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); +'use strict'; - clearSelect(zoomlayer); - } +/* removed: var _$d3_15 = require('d3'); */; - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +/** + * 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'); - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } + this.update(opts.graphInfo, opts.buttons); - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; + this.container.appendChild(this.element); +} - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } +var proto = ModeBar.prototype; - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } +/** + * 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; - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); + var context = this.graphInfo._context; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; } + else this.element.className = 'modebar'; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_218.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - var pc = gd.querySelector('.plotly'); + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - recomputeAxisLists(); + this.updateButtons(buttons); - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - clearTimeout(redrawTimer); + this.updateActiveButton(); +}; - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_171.log('Did not find wheel motion attributes: ', e); - return; - } +proto.updateButtons = function(buttons) { + var _this = this; - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - var axRange = _$lib_171.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + 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); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +proto.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * 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, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_15.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +proto.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_230(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_230(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * 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, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_15.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_172.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * 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((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_261.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_261.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_261.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +proto.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_172._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +proto.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +proto.destroy = function() { + _$lib_172.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_261.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_15.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_171.syncOrAsync([ - _$plots_246.previousPromises, - function() { _$registry_261.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_116 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_217 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_391 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_262 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_230(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_116 = require('./modebar'); */; +/* removed: var _$buttons_113 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_221[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_115 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_171.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_171.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_116(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_76.setTranslate, clipDx, clipDy) - .call(_$drawing_76.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_76.setTranslate, plotDx, plotDy) - .call(_$drawing_76.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_76.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_76.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_76.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_76.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_113[button]); } - } - - return dragger; -} - -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - dragger3.call(_$setCursor_190, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_15.select(dragger).call(_$drawing_76.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_15.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_15.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_217.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_51.background, - stroke: _$color_51.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_262.traceIs(trace, 'scatter-like')) { + if(_$subtypes_391.hasMarkers(trace) || _$subtypes_391.hasText(trace)) { + selectable = true; + } + } else if(_$registry_262.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_15.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_171.notifier(_$lib_171._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_113[button] !== undefined) { + customButtons[i][j] = _$buttons_113[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_171.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_21) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_221 = { - makeDragBox: makeDragBox, +var _$modebar_114 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_114.manage = _$manageModeBar_115; +var _$constraints_221 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -60236,152 +61044,202 @@ var _$dragbox_221 = { 'use strict'; -/* removed: var _$d3_15 = require('d3'); */; +var __id2name_221 = _$axis_ids_217.id2name; +/* removed: var _$scaleZoom_230 = require('./scale_zoom'); */; +var __makePadFn_221 = _$autorange_213.makePadFn; -/* removed: var _$fx_93 = require('../../components/fx'); */; -/* removed: var _$dragelement_73 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_154.ALMOST_EQUAL; -/* removed: var _$constants_218 = require('./constants'); */; -var __makeDragBox_222 = _$dragbox_221.makeDragBox; +var __FROM_BL_221 = _$alignment_151.FROM_BL; -var _$initInteractions_222 = function initInteractions(gd) { + +_$constraints_221.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_15.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - 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'), - 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)); + 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_221(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_218.DRAGGERSIZE; + // 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; - // 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_222(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + if(mode === 'range') { + _$scaleZoom_230(ax, factor); + } + else { + // mode === 'domain' - 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) { - _$fx_93.hover(gd, evt, subplot); + 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_230(ax, factor); + continue; } - }; - _$fx_93.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_221(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_73.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_222(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_222(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_222(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_222(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_222(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_222(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_222(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_222(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_222(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_222(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_221.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_93.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_93.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_221[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_205 = {}; +var _$subroutines_206 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -60393,21 +61251,27 @@ var _$subroutines_205 = {}; 'use strict'; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$registry_261 = require('../registry'); */; +/* removed: var _$registry_262 = require('../registry'); */; /* removed: var _$plots_246 = require('../plots/plots'); */; -/* removed: var _$lib_171 = require('../lib'); */; + +/* removed: var _$lib_172 = require('../lib'); */; +/* removed: var _$clearGlCanvases_161 = require('../lib/clear_gl_canvases'); */; /* removed: var _$color_51 = require('../components/color'); */; /* removed: var _$drawing_76 = require('../components/drawing'); */; /* removed: var _$titles_144 = require('../components/titles'); */; /* removed: var _$modebar_114 = require('../components/modebar'); */; -/* removed: var _$axes_213 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_222 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_218 = require('../plots/cartesian/constants'); */; + +/* removed: var _$axes_214 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_219 = require('../plots/cartesian/constants'); */; /* removed: var _$alignment_151 = require('../constants/alignment'); */; +/* removed: var _$constraints_221 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_221.enforce; +var cleanAxisConstraints = _$constraints_221.clean; +var __doAutoRange_206 = _$autorange_213.doAutoRange; -_$subroutines_205.layoutStyles = function(gd) { - return _$lib_171.syncOrAsync([_$plots_246.doAutoMargin, _$subroutines_205.lsInner], gd); +_$subroutines_206.layoutStyles = function(gd) { + return _$lib_172.syncOrAsync([_$plots_246.doAutoMargin, _$subroutines_206.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -60425,11 +61289,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_205.lsInner = function(gd) { +_$subroutines_206.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_213.list(gd); + var axList = _$axes_214.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -60508,31 +61372,17 @@ _$subroutines_205.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_172.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -60564,23 +61414,17 @@ _$subroutines_205.lsInner = function(gd) { } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_172.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); _$drawing_76.setTranslate(plotinfo.plot, xa._offset, ya._offset); @@ -60589,16 +61433,16 @@ _$subroutines_205.lsInner = function(gd) { if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } _$drawing_76.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_218.traceLayerClasses.length; i++) { - var layer = _$constants_218.traceLayerClasses[i]; + for(i = 0; i < _$constants_219.traceLayerClasses.length; i++) { + var layer = _$constants_219.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { plotinfo.plot.selectAll('g.' + layer).call(_$drawing_76.setClipUrl, layerClipId); } @@ -60722,8 +61566,8 @@ _$subroutines_205.lsInner = function(gd) { plotinfo.ylines.attr('d', yPath); }); - _$axes_213.makeClipPaths(gd); - _$subroutines_205.drawMainTitle(gd); + _$axes_214.makeClipPaths(gd); + _$subroutines_206.drawMainTitle(gd); _$modebar_114.manage(gd); return gd._promises.length && Promise.all(gd._promises); @@ -60780,7 +61624,7 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_205.drawMainTitle = function(gd) { +_$subroutines_206.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; _$titles_144.draw(gd, 'gtitle', { @@ -60799,7 +61643,7 @@ _$subroutines_205.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_205.doTraceStyle = function(gd) { +_$subroutines_206.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -60809,12 +61653,12 @@ _$subroutines_205.doTraceStyle = function(gd) { } _$plots_246.style(gd); - _$registry_261.getComponentMethod('legend', 'draw')(gd); + _$registry_262.getComponentMethod('legend', 'draw')(gd); return _$plots_246.previousPromises(gd); }; -_$subroutines_205.doColorBars = function(gd) { +_$subroutines_206.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -60822,7 +61666,7 @@ _$subroutines_205.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_261.traceIs(trace, 'contour')) { + if(_$registry_262.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -60831,7 +61675,7 @@ _$subroutines_205.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_261.traceIs(trace, 'markerColorscale')) { + if(_$registry_262.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); @@ -60842,28 +61686,33 @@ _$subroutines_205.doColorBars = function(gd) { }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_205.layoutReplot = function(gd) { +_$subroutines_206.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_261.call('plot', gd, '', layout); + return _$registry_262.call('plot', gd, '', layout); }; -_$subroutines_205.doLegend = function(gd) { - _$registry_261.getComponentMethod('legend', 'draw')(gd); +_$subroutines_206.doLegend = function(gd) { + _$registry_262.getComponentMethod('legend', 'draw')(gd); return _$plots_246.previousPromises(gd); }; -_$subroutines_205.doTicksRelayout = function(gd) { - _$axes_213.doTicks(gd, 'redraw'); - _$subroutines_205.drawMainTitle(gd); +_$subroutines_206.doTicksRelayout = function(gd) { + _$axes_214.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_161(gd); + _$registry_262.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_206.drawMainTitle(gd); return _$plots_246.previousPromises(gd); }; -_$subroutines_205.doModeBar = function(gd) { +_$subroutines_206.doModeBar = function(gd) { var fullLayout = gd._fullLayout; _$modebar_114.manage(gd); - _$initInteractions_222(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; @@ -60873,7 +61722,7 @@ _$subroutines_205.doModeBar = function(gd) { return _$plots_246.previousPromises(gd); }; -_$subroutines_205.doCamera = function(gd) { +_$subroutines_206.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -60885,212 +61734,86 @@ _$subroutines_205.doCamera = function(gd) { } }; -var _$constraints_220 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_220 = _$axis_ids_216.id2name; -/* removed: var _$scaleZoom_230 = require('./scale_zoom'); */; -var __makePadFn_220 = _$autorange_212.makePadFn; - -var ALMOST_EQUAL = _$numerical_154.ALMOST_EQUAL; - -var __FROM_BL_220 = _$alignment_151.FROM_BL; - - -_$constraints_220.enforce = function enforceAxisConstraints(gd) { +_$subroutines_206.drawData = function(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_220(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_262.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_230(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_230(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_161(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_220(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_246.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_262.getComponentMethod('shapes', 'draw')(gd); + _$registry_262.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_246.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_206.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_214.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_206(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_220.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_220[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_206.finalDraw = function(gd) { + _$registry_262.getComponentMethod('shapes', 'draw')(gd); + _$registry_262.getComponentMethod('images', 'draw')(gd); + _$registry_262.getComponentMethod('annotations', 'draw')(gd); + _$registry_262.getComponentMethod('legend', 'draw')(gd); + _$registry_262.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_262.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_262.getComponentMethod('sliders', 'draw')(gd); + _$registry_262.getComponentMethod('updatemenus', 'draw')(gd); +}; var _$micropolar_250 = {}; /** @@ -61102,8 +61825,8 @@ var _$micropolar_250 = {}; */ /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../../../lib'); */; -var __extendDeepAll_250 = _$lib_171.extendDeepAll; +/* removed: var _$lib_172 = require('../../../lib'); */; +var __extendDeepAll_250 = _$lib_172.extendDeepAll; var __MID_SHIFT_250 = _$alignment_151.MID_SHIFT; var µ = _$micropolar_250 = { version: '0.2.2' }; @@ -62591,12 +63314,12 @@ var _$micropolar_manager_251 = {}; 'use strict'; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../../../lib'); */; +/* removed: var _$lib_172 = require('../../../lib'); */; /* removed: var _$color_51 = require('../../../components/color'); */; /* removed: var _$micropolar_250 = require('./micropolar'); */; /* removed: var _$UndoManager_252 = require('./undo_manager'); */; -var __extendDeepAll_251 = _$lib_171.extendDeepAll; +var __extendDeepAll_251 = _$lib_172.extendDeepAll; var manager = _$micropolar_manager_251 = {}; @@ -62678,7 +63401,7 @@ var Polar = _$legacy_249 = _$micropolar_250; Polar.manager = _$micropolar_manager_251; -var _$plot_api_202 = {}; +var _$plot_api_203 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -62695,33 +63418,29 @@ var _$plot_api_202 = {}; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; /* removed: var _$hasHover_20 = require('has-hover'); */; -/* removed: var _$lib_171 = require('../lib'); */; -/* removed: var _$Events_164 = require('../lib/events'); */; -/* removed: var _$queue_185 = require('../lib/queue'); */; +/* removed: var _$lib_172 = require('../lib'); */; +/* removed: var _$Events_165 = require('../lib/events'); */; +/* removed: var _$queue_186 = require('../lib/queue'); */; -/* removed: var _$registry_261 = require('../registry'); */; -/* removed: var _$plot_schema_204 = require('./plot_schema'); */; +/* removed: var _$registry_262 = require('../registry'); */; +/* removed: var _$plot_schema_205 = require('./plot_schema'); */; /* removed: var _$plots_246 = require('../plots/plots'); */; /* removed: var _$legacy_249 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_222 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$axes_213 = require('../plots/cartesian/axes'); */; +/* removed: var _$axes_214 = require('../plots/cartesian/axes'); */; /* removed: var _$drawing_76 = require('../components/drawing'); */; /* removed: var _$color_51 = require('../components/color'); */; +var initInteractions = _$graph_interact_223.initInteractions; /* removed: var _$xmlns_namespaces_156 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_192 = require('../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_193 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_203 = require('./plot_config'); */; -/* removed: var _$manage_arrays_201 = require('./manage_arrays'); */; -/* removed: var _$helpers_199 = require('./helpers'); */; -/* removed: var _$subroutines_205 = require('./subroutines'); */; -/* removed: var _$edit_types_198 = require('./edit_types'); */; +/* removed: var _$plot_config_204 = require('./plot_config'); */; +/* removed: var _$manage_arrays_202 = require('./manage_arrays'); */; +/* removed: var _$helpers_200 = require('./helpers'); */; +/* removed: var _$subroutines_206 = require('./subroutines'); */; +/* removed: var _$edit_types_199 = require('./edit_types'); */; -/* removed: var _$constants_218 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_220 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_220.enforce; -var cleanAxisConstraints = _$constraints_220.clean; -var __doAutoRange_202 = _$autorange_212.doAutoRange; +var AX_NAME_PATTERN = _$constants_219.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -62747,15 +63466,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_202.plot = function(gd, data, layout, config) { +_$plot_api_203.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_171.getGraphDiv(gd); + gd = _$lib_172.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_164.init(gd); + _$Events_165.init(gd); - if(_$lib_171.isPlainObject(data)) { + if(_$lib_172.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -62763,19 +63482,19 @@ _$plot_api_202.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_164.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_165.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_171.isPlotDiv(gd)) { - _$lib_171.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_172.isPlotDiv(gd)) { + _$lib_172.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_202.addFrames(gd, frames); + return _$plot_api_203.addFrames(gd, frames); } } @@ -62794,6 +63513,9 @@ _$plot_api_202.plot = function(gd, data, layout, config) { // so we can share cached text across tabs _$drawing_76.makeTester(); + // clear stashed base url + delete _$drawing_76.baseUrl; + // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all @@ -62805,7 +63527,7 @@ _$plot_api_202.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_199.cleanData(data, gd.data); + _$helpers_200.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -62816,7 +63538,7 @@ _$plot_api_202.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_199.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_200.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -62838,7 +63560,7 @@ _$plot_api_202.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_171.log('Legacy polar charts are deprecated!'); + _$lib_172.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -62859,7 +63581,7 @@ _$plot_api_202.plot = function(gd, data, layout, config) { _$drawing_76.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_213.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_214.saveShowSpikeInitial(gd); // prepare the data and find the autorange @@ -62926,9 +63648,7 @@ _$plot_api_202.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_171.syncOrAsync([ - _$subroutines_205.layoutStyles - ], gd); + return _$plots_246.previousPromises(gd); } // draw anything that can affect margins. @@ -62936,10 +63656,10 @@ _$plot_api_202.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_261.getComponentMethod('legend', 'draw')(gd); - _$registry_261.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_261.getComponentMethod('sliders', 'draw')(gd); - _$registry_261.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_262.getComponentMethod('legend', 'draw')(gd); + _$registry_262.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_262.getComponentMethod('sliders', 'draw')(gd); + _$registry_262.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; @@ -62958,9 +63678,9 @@ _$plot_api_202.plot = function(gd, data, layout, config) { function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_171.syncOrAsync([ + return _$lib_172.syncOrAsync([ marginPushers, - _$subroutines_205.layoutStyles + _$subroutines_206.layoutStyles ], gd); } @@ -62981,7 +63701,7 @@ _$plot_api_202.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_171.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_172.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -62995,113 +63715,31 @@ _$plot_api_202.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_261.getComponentMethod('errorbars', 'calc')(gd); + _$registry_262.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_171.syncOrAsync([ - _$registry_261.getComponentMethod('shapes', 'calcAutorange'), - _$registry_261.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_172.syncOrAsync([ + _$registry_262.getComponentMethod('shapes', 'calcAutorange'), + _$registry_262.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_261.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_262.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_213.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_202(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_206.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_213.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_214.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_213.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_261.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_246.style(gd); - - // show annotations and shapes - _$registry_261.getComponentMethod('shapes', 'draw')(gd); - _$registry_261.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_246.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_246.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_261.getComponentMethod('shapes', 'draw')(gd); - _$registry_261.getComponentMethod('images', 'draw')(gd); - _$registry_261.getComponentMethod('annotations', 'draw')(gd); - _$registry_261.getComponentMethod('legend', 'draw')(gd); - _$registry_261.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_261.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_261.getComponentMethod('sliders', 'draw')(gd); - _$registry_261.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_214.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ @@ -63112,19 +63750,20 @@ _$plot_api_202.plot = function(gd, data, layout, config) { marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_205.layoutStyles); + seq.push(_$subroutines_206.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_222, + _$subroutines_206.drawData, + _$subroutines_206.finalDraw, + initInteractions, + _$plots_246.addLinks, _$plots_246.rehover, _$plots_246.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_171.syncOrAsync(seq, gd); + var plotDone = _$lib_172.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -63133,15 +63772,15 @@ _$plot_api_202.plot = function(gd, data, layout, config) { }); }; -_$plot_api_202.setPlotConfig = function setPlotConfig(obj) { - return _$lib_171.extendFlat(_$plot_config_203, obj); +_$plot_api_203.setPlotConfig = function setPlotConfig(obj) { + return _$lib_172.extendFlat(_$plot_config_204, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_171.error(e); + _$lib_172.error(e); } } @@ -63151,7 +63790,7 @@ function opaqueSetBackground(gd, bgColor) { } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_171.extendDeep({}, _$plot_config_203); + if(!gd._context) gd._context = _$lib_172.extendDeep({}, _$plot_config_204); var context = gd._context; var i, keys, key; @@ -63267,7 +63906,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_192.convertToTspans, gd); + this.call(_$svg_text_utils_193.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -63276,7 +63915,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_171._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_172._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -63295,7 +63934,7 @@ function plotPolar(gd, data, layout) { } var setContenteditable = function() { - this.call(_$svg_text_utils_192.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_193.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -63317,18 +63956,18 @@ function plotPolar(gd, data, layout) { } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_202.redraw = function(gd) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.redraw = function(gd) { + gd = _$lib_172.getGraphDiv(gd); - if(!_$lib_171.isPlotDiv(gd)) { + if(!_$lib_172.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_199.cleanData(gd.data, gd.data); - _$helpers_199.cleanLayout(gd.layout); + _$helpers_200.cleanData(gd.data, gd.data); + _$helpers_200.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_202.plot(gd).then(function() { + return _$plot_api_203.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -63342,14 +63981,14 @@ _$plot_api_202.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_202.newPlot = function(gd, data, layout, config) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.newPlot = function(gd, data, layout, config) { + gd = _$lib_172.getGraphDiv(gd); // remove gl contexts - _$plots_246.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_246.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); _$plots_246.purge(gd); - return _$plot_api_202.plot(gd, data, layout, config); + return _$plot_api_203.plot(gd, data, layout, config); }; /** @@ -63502,12 +64141,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_171.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_172.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_171.isPlainObject(update)) { + if(!_$lib_172.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -63550,7 +64189,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_171.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_172.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -63570,7 +64209,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_171.nestedProperty(trace, key); + prop = _$lib_172.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -63579,10 +64218,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_171.isArrayOrTypedArray(insert)) { + if(!_$lib_172.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_171.isArrayOrTypedArray(target)) { + if(!_$lib_172.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -63677,13 +64316,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_202.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_172.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_171.isTypedArray(target)) { + if(_$lib_172.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -63728,20 +64367,20 @@ _$plot_api_202.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_202.redraw(gd); + var promise = _$plot_api_203.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_185.add(gd, _$plot_api_202.prependTraces, undoArgs, extendTraces, arguments); + _$queue_186.add(gd, _$plot_api_203.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_202.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_172.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_171.isTypedArray(target)) { + if(_$lib_172.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -63785,9 +64424,9 @@ _$plot_api_202.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_202.redraw(gd); + var promise = _$plot_api_203.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_185.add(gd, _$plot_api_202.extendTraces, undoArgs, prependTraces, arguments); + _$queue_186.add(gd, _$plot_api_203.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -63801,11 +64440,11 @@ _$plot_api_202.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_202.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_172.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_202.deleteTraces, + undoFunc = _$plot_api_203.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -63822,10 +64461,10 @@ _$plot_api_202.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_171.extendFlat({}, trace); + return _$lib_172.extendFlat({}, trace); }); - _$helpers_199.cleanData(traces, gd.data); + _$helpers_200.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -63840,8 +64479,8 @@ _$plot_api_202.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_202.redraw(gd); - _$queue_185.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_203.redraw(gd); + _$queue_186.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -63864,10 +64503,10 @@ _$plot_api_202.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_185.startSequence(gd); - _$queue_185.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_202.moveTraces(gd, currentIndices, newIndices); - _$queue_185.stopSequence(gd); + _$queue_186.startSequence(gd); + _$queue_186.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_203.moveTraces(gd, currentIndices, newIndices); + _$queue_186.stopSequence(gd); return promise; }; @@ -63878,11 +64517,11 @@ _$plot_api_202.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_202.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_172.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_202.addTraces, + undoFunc = _$plot_api_203.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -63901,14 +64540,14 @@ _$plot_api_202.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_171.sorterDes); + indices.sort(_$lib_172.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_202.redraw(gd); - _$queue_185.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_203.redraw(gd); + _$queue_186.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -63944,8 +64583,8 @@ _$plot_api_202.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_202.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_172.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -64005,8 +64644,8 @@ _$plot_api_202.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_202.redraw(gd); - _$queue_185.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_203.redraw(gd); + _$queue_186.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -64041,55 +64680,55 @@ _$plot_api_202.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_202.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_171.getGraphDiv(gd); - _$helpers_199.clearPromiseQueue(gd); +_$plot_api_203.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_172.getGraphDiv(gd); + _$helpers_200.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_171.isPlainObject(astr)) { + else if(_$lib_172.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_171.extendFlat({}, astr); + aobj = _$lib_172.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_171.warn('Restyle fail.', astr, val, _traces); + _$lib_172.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_199.coerceTraceIndices(gd, _traces); + var traces = _$helpers_200.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_199.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_200.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_202.plot); + seq.push(_$plot_api_203.plot); } else { seq.push(_$plots_246.previousPromises); _$plots_246.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_205.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_205.doColorBars); + if(flags.style) seq.push(_$subroutines_206.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_206.doColorBars); } seq.push(_$plots_246.rehover); - _$queue_185.add(gd, + _$queue_186.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_171.syncOrAsync(seq, gd); + var plotDone = _$lib_172.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -64112,7 +64751,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_198.traceFlags(); + var flags = _$edit_types_199.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -64125,7 +64764,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_213.id2name(axid); + var axName = _$axes_214.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -64144,13 +64783,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_199.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_200.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_171.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_172.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_171.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_172.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -64167,7 +64806,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_199.hasParent(aobj, ai)) { + if(_$helpers_200.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -64182,7 +64821,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_171.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_172.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -64198,17 +64837,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_171.nestedProperty(cont, ai); + param = _$lib_172.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_204.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_205.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_171.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_172.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -64248,19 +64887,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_171.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_171.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_171.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_172.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_172.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_172.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_171.nestedProperty(cont, 'marker.color') - .set(_$lib_171.nestedProperty(cont, 'marker.colors').get()); + _$lib_172.nestedProperty(cont, 'marker.color') + .set(_$lib_172.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_261.traceIs(cont, 'cartesian')) { - _$lib_171.nestedProperty(cont, 'marker.colors') - .set(_$lib_171.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_262.traceIs(cont, 'cartesian')) { + _$lib_172.nestedProperty(cont, 'marker.colors') + .set(_$lib_172.nestedProperty(cont, 'marker.color').get()); } } @@ -64289,23 +64928,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_199.swapXYData(cont); + _$helpers_200.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(_$plots_246.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_199.manageArrayContainers(param, newVal, undoit); + _$helpers_200.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_171.isArrayOrTypedArray(newVal) || _$lib_171.isArrayOrTypedArray(oldVal)) + _$lib_172.isArrayOrTypedArray(newVal) || _$lib_172.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_198.update(flags, valObject); + else _$edit_types_199.update(flags, valObject); } else { /* @@ -64324,12 +64963,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_213.swap(gd, traces); + _$axes_214.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_171.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_172.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -64344,7 +64983,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_261.traceIs(trace, 'cartesian')) { + if(_$registry_262.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -64361,7 +65000,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_213.list(gd); + var axList = _$axes_214.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -64382,7 +65021,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_171.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_172.extendDeepNoArrays([], [redoit, traces]) }; } @@ -64406,9 +65045,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_202.relayout = function relayout(gd, astr, val) { - gd = _$lib_171.getGraphDiv(gd); - _$helpers_199.clearPromiseQueue(gd); +_$plot_api_203.relayout = function relayout(gd, astr, val) { + gd = _$lib_172.getGraphDiv(gd); + _$helpers_200.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -64417,21 +65056,21 @@ _$plot_api_202.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_171.isPlainObject(astr)) { - aobj = _$lib_171.extendFlat({}, astr); + } else if(_$lib_172.isPlainObject(astr)) { + aobj = _$lib_172.extendFlat({}, astr); } else { - _$lib_171.warn('Relayout fail.', astr, val); + _$lib_172.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_199.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_200.clearAxisAutomargins(gd); // fill in redraw sequence @@ -64441,26 +65080,50 @@ _$plot_api_202.relayout = function relayout(gd, astr, val) { var seq = [_$plots_246.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_205.layoutReplot); + seq.push(_$subroutines_206.layoutReplot); } else if(Object.keys(aobj).length) { _$plots_246.supplyDefaults(gd); - if(flags.legend) seq.push(_$subroutines_205.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_205.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_205.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_205.doModeBar); - if(flags.camera) seq.push(_$subroutines_205.doCamera); + if(flags.legend) seq.push(_$subroutines_206.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_206.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_206.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_206.doTicksRelayout, + _$subroutines_206.drawData, + _$subroutines_206.finalDraw + ); + } + + if(flags.ticks) seq.push(_$subroutines_206.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_206.doModeBar); + if(flags.camera) seq.push(_$subroutines_206.doCamera); } seq.push(_$plots_246.rehover); - _$queue_185.add(gd, + _$queue_186.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_171.syncOrAsync(seq, gd); + var plotDone = _$lib_172.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -64473,7 +65136,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_213.list(gd), + axes = _$axes_214.list(gd), arrayEdits = {}, arrayStr, i, @@ -64496,7 +65159,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_198.layoutFlags(); + var flags = _$edit_types_199.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -64515,9 +65178,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_199.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_200.hasParent(aobj, attr)) return; - var p = _$lib_171.nestedProperty(layout, attr); + var p = _$lib_172.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -64531,18 +65194,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_213.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_214.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_199.hasParent(aobj, ai)) { + if(_$helpers_200.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_171.nestedProperty(layout, ai); + var p = _$lib_172.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -64554,8 +65217,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_171.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_171.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_172.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_172.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -64566,11 +65229,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_204.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_205.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_171.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_172.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -64584,12 +65247,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_171.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_172.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_171.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_171.nestedProperty(fullLayout, ptrunk).get(); + _$lib_172.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_172.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -64597,7 +65260,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_171.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_172.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -64657,8 +65320,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_261.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_261.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_262.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_262.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -64666,18 +65329,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_171.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_172.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_218.AX_NAME_PATTERN)) { - var fullProp = _$lib_171.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_172.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_261.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_261.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_262.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_262.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -64686,12 +65349,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_201.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_202.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_171.nestedProperty(layout, arrayStr); + var componentArray = _$lib_172.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -64701,28 +65364,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_198.update(flags, updateValObject); + else _$edit_types_199.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_201.isAddVal(vi)) { + if(_$manage_arrays_202.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_201.isRemoveVal(vi)) { + else if(_$manage_arrays_202.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_171.warn('unrecognized full object value', aobj); + else _$lib_172.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_198.update(flags, updateValObject); - + else { + _$edit_types_199.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -64751,7 +65415,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_198.update(flags, valObject); + else if(valObject) _$edit_types_199.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -64760,8 +65424,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_201.applyContainerArrayChanges(gd, - _$lib_171.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_202.applyContainerArrayChanges(gd, + _$lib_172.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -64779,7 +65443,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_213.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_214.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -64803,7 +65467,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_171.extendDeep({}, redoit) + eventData: _$lib_172.extendDeep({}, redoit) }; } @@ -64825,9 +65489,9 @@ function updateAutosize(gd) { // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_171.isPlainObject(obj)) return false; + if(!_$lib_172.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_213.getFromId(gd, axRef); + ax = _$axes_214.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -64837,7 +65501,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_213.getFromId(gd, axLetter); + ax = _$axes_214.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -64857,32 +65521,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_202.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_171.getGraphDiv(gd); - _$helpers_199.clearPromiseQueue(gd); +_$plot_api_203.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_172.getGraphDiv(gd); + _$helpers_200.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_171.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_171.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_172.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_172.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_199.coerceTraceIndices(gd, _traces); + var traces = _$helpers_200.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_171.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_172.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_171.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_172.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_199.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_199.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_200.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_200.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -64896,35 +65560,43 @@ _$plot_api_202.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_202.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_203.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_202.plot); + seq.push(_$plot_api_203.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_205.layoutReplot); + seq.push(_$subroutines_206.layoutReplot); } else { seq.push(_$plots_246.previousPromises); _$plots_246.supplyDefaults(gd); - if(restyleFlags.style) seq.push(_$subroutines_205.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_205.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_205.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_205.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_205.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_205.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_205.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_206.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_206.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_206.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_206.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_206.doAutoRangeAndConstraints, + _$subroutines_206.doTicksRelayout, + _$subroutines_206.drawData, + _$subroutines_206.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_206.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_206.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_206.doCamera); } seq.push(_$plots_246.rehover); - _$queue_185.add(gd, + _$queue_186.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_171.syncOrAsync(seq, gd); + var plotDone = _$lib_172.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -64960,23 +65632,23 @@ _$plot_api_202.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_202.react = function(gd, data, layout, config) { +_$plot_api_203.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_202.addFrames(gd, frames); } + function addFrames() { return _$plot_api_203.addFrames(gd, frames); } - gd = _$lib_171.getGraphDiv(gd); + gd = _$lib_172.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_171.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_202.newPlot(gd, data, layout, config); + if(!_$lib_172.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_203.newPlot(gd, data, layout, config); } else { - if(_$lib_171.isPlainObject(data)) { + if(_$lib_172.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -64988,16 +65660,16 @@ _$plot_api_202.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_171.extendDeep({}, gd._context); + var oldConfig = _$lib_172.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_199.cleanData(gd.data, []); + _$helpers_200.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_199.cleanLayout(gd.layout); + _$helpers_200.cleanLayout(gd.layout); _$plots_246.supplyDefaults(gd); @@ -65021,7 +65693,7 @@ _$plot_api_202.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_199.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_200.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -65037,21 +65709,21 @@ _$plot_api_202.react = function(gd, data, layout, config) { if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_202.plot); + seq.push(_$plot_api_203.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_261.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_171.noop) { + var drawOne = _$registry_262.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_172.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_261.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_171.noop) { + var draw = _$registry_262.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_172.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -65060,18 +65732,26 @@ _$plot_api_202.react = function(gd, data, layout, config) { } seq.push(_$plots_246.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_205.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_205.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_205.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_205.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_205.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_205.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_205.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_206.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_206.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_206.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_206.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_206.doAutoRangeAndConstraints, + _$subroutines_206.doTicksRelayout, + _$subroutines_206.drawData, + _$subroutines_206.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_206.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_206.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_206.doCamera); } seq.push(_$plots_246.rehover); - plotDone = _$lib_171.syncOrAsync(seq, gd); + plotDone = _$lib_172.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -65094,12 +65774,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_198.traceFlags(); + var flags = _$edit_types_199.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_204.getTraceValObject(trace, parts); + return _$plot_schema_205.getTraceValObject(trace, parts); } var diffOpts = { @@ -65109,11 +65789,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_213.getFromId(gd, trace.xaxis).autorange || - _$axes_213.getFromId(gd, trace.yaxis).autorange + _$axes_214.getFromId(gd, trace.xaxis).autorange || + _$axes_214.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -65126,11 +65812,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_198.layoutFlags(); + var flags = _$edit_types_199.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_204.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_205.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -65169,10 +65855,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_171.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_172.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_198.update(flags, valObject); + _$edit_types_199.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -65252,7 +65938,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_171.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_172.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -65264,7 +65950,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_171.isPlainObject(oldVal)) { + else if(!valType && _$lib_172.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -65318,7 +66004,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_171.isPlainObject(oldVal) && _$lib_171.isPlainObject(newVal)) { + if(_$lib_172.isPlainObject(oldVal) && _$lib_172.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -65329,7 +66015,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_171.isPlainObject(oldVal[i]) && _$lib_171.isPlainObject(newVal[i])) { + if(_$lib_172.isPlainObject(oldVal[i]) && _$lib_172.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -65374,10 +66060,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_202.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_172.getGraphDiv(gd); - if(!_$lib_171.isPlotDiv(gd)) { + if(!_$lib_172.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -65551,7 +66237,7 @@ _$plot_api_202.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts _$plots_246.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_199.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_200.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -65621,13 +66307,13 @@ _$plot_api_202.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_171.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_172.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_171.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_172.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -65656,10 +66342,10 @@ _$plot_api_202.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_171.isPlainObject(frameOrName)) { + } else if(_$lib_172.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_171.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_172.extendFlat({}, frameOrName)) }); } } @@ -65669,7 +66355,7 @@ _$plot_api_202.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_171.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_172.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -65738,14 +66424,14 @@ _$plot_api_202.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_202.addFrames = function(gd, frameList, indices) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.addFrames = function(gd, frameList, indices) { + gd = _$lib_172.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_171.isPlotDiv(gd)) { + if(!_$lib_172.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -65772,7 +66458,7 @@ _$plot_api_202.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_171.isPlainObject(frameList[i])) continue; + if(!_$lib_172.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -65784,14 +66470,14 @@ _$plot_api_202.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_171.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_172.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_171.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_172.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -65820,7 +66506,7 @@ _$plot_api_202.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_171.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_172.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -65853,7 +66539,7 @@ _$plot_api_202.addFrames = function(gd, frameList, indices) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_185) _$queue_185.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_186) _$queue_186.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_246.modifyFrames(gd, ops); }; @@ -65867,10 +66553,10 @@ _$plot_api_202.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_202.deleteFrames = function(gd, frameList) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.deleteFrames = function(gd, frameList) { + gd = _$lib_172.getGraphDiv(gd); - if(!_$lib_171.isPlotDiv(gd)) { + if(!_$lib_172.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -65900,7 +66586,7 @@ _$plot_api_202.deleteFrames = function(gd, frameList) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_185) _$queue_185.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_186) _$queue_186.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_246.modifyFrames(gd, ops); }; @@ -65911,20 +66597,21 @@ _$plot_api_202.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_202.purge = function purge(gd) { - gd = _$lib_171.getGraphDiv(gd); +_$plot_api_203.purge = function purge(gd) { + gd = _$lib_172.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_246.cleanPlot([], {}, fullData, fullLayout); + _$plots_246.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties _$plots_246.purge(gd); // purge event emitter methods - _$Events_164.purge(gd); + _$Events_165.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -65982,7 +66669,7 @@ function makePlotFramework(gd) { _$d3_15.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_171.randstr(otherUids); + fullLayout._uid = _$lib_172.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') @@ -66058,7 +66745,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_265 = {}; +var _$helpers_266 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -66070,7 +66757,7 @@ var _$helpers_265 = {}; 'use strict'; -_$helpers_265.getDelay = function(fullLayout) { +_$helpers_266.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -66080,7 +66767,7 @@ _$helpers_265.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_265.getRedrawFunc = function(gd) { +_$helpers_266.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -66105,11 +66792,11 @@ _$helpers_265.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_171 = require('../lib'); */; -var __EventEmitter_267 = _$EventEmitter_17.EventEmitter; +/* removed: var _$lib_172 = require('../lib'); */; +var __EventEmitter_268 = _$EventEmitter_17.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_267(); + var ev = opts.emitter || new __EventEmitter_268(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -66117,7 +66804,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_171.isIE() && format !== 'svg') { + if(_$lib_172.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -66208,7 +66895,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_267 = svgToImg; +var _$svgToImg_268 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -66223,7 +66910,7 @@ var _$svgToImg_267 = svgToImg; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$lib_172 = require('../lib'); */; /* removed: var _$drawing_76 = require('../components/drawing'); */; /* removed: var _$color_51 = require('../components/color'); */; @@ -66248,7 +66935,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_269 = function toSVG(gd, format, scale) { +var _$toSVG_270 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -66371,7 +67058,7 @@ var _$toSVG_269 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_171.isIE()) { + if(_$lib_172.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -66396,14 +67083,14 @@ var _$toSVG_269 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_202 = require('./plot_api'); */; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$plot_api_203 = require('./plot_api'); */; +/* removed: var _$lib_172 = require('../lib'); */; -/* removed: var _$helpers_265 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_269 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_267 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_266 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_270 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_268 = require('../snapshot/svgtoimg'); */; -var __attrs_206 = { +var __attrs_207 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -66456,19 +67143,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_171.isPlainObject(gd)) { + if(_$lib_172.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_171.getGraphDiv(gd); - data = _$lib_171.extendDeep([], gd.data); - layout = _$lib_171.extendDeep({}, gd.layout); + gd = _$lib_172.getGraphDiv(gd); + data = _$lib_172.extendDeep([], gd.data); + layout = _$lib_172.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_171.validate(opts[attr], __attrs_206[attr]); + return !(attr in opts) || _$lib_172.validate(opts[attr], __attrs_207[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -66482,7 +67169,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_171.coerce(opts, fullOpts, __attrs_206, attr, dflt); + return _$lib_172.coerce(opts, fullOpts, __attrs_207, attr, dflt); } var format = coerce('format'); @@ -66499,31 +67186,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_171.extendFlat({}, layout); + var layoutImage = _$lib_172.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_171.extendFlat({}, config, { + var configImage = _$lib_172.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_265.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_266.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_265.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_266.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_269(clonedGd, format, scale); + var svg = _$toSVG_270(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_202.purge(clonedGd); + _$plot_api_203.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -66535,9 +67222,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_171.randstr(); + canvas.id = _$lib_172.randstr(); - _$svgToImg_267({ + _$svgToImg_268({ format: format, width: width, height: height, @@ -66564,7 +67251,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_202.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_203.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -66573,7 +67260,7 @@ function toImage(gd, opts) { }); } -var _$toImage_206 = toImage; +var _$toImage_207 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -66585,14 +67272,14 @@ var _$toImage_206 = toImage; 'use strict'; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$lib_172 = require('../lib'); */; /* removed: var _$plots_246 = require('../plots/plots'); */; -/* removed: var _$plot_schema_204 = require('./plot_schema'); */; -/* removed: var _$plot_config_203 = require('./plot_config'); */; +/* removed: var _$plot_schema_205 = require('./plot_schema'); */; +/* removed: var _$plot_config_204 = require('./plot_config'); */; -var __isPlainObject_207 = _$lib_171.isPlainObject; -var __isArray_207 = Array.isArray; -var __isArrayOrTypedArray_207 = _$lib_171.isArrayOrTypedArray; +var __isPlainObject_208 = _$lib_172.isPlainObject; +var __isArray_208 = Array.isArray; +var __isArrayOrTypedArray_208 = _$lib_172.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -66615,15 +67302,15 @@ var __isArrayOrTypedArray_207 = _$lib_171.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_207 = function valiate(data, layout) { - var schema = _$plot_schema_204.get(); +var _$valiate_208 = function valiate(data, layout) { + var schema = _$plot_schema_205.get(); var errorList = []; - var gd = {_context: _$lib_171.extendFlat({}, _$plot_config_203)}; + var gd = {_context: _$lib_172.extendFlat({}, _$plot_config_204)}; var dataIn, layoutIn; - if(__isArray_207(data)) { - gd.data = _$lib_171.extendDeep([], data); + if(__isArray_208(data)) { + gd.data = _$lib_172.extendDeep([], data); dataIn = data; } else { @@ -66632,8 +67319,8 @@ var _$valiate_207 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_207(layout)) { - gd.layout = _$lib_171.extendDeep({}, layout); + if(__isPlainObject_208(layout)) { + gd.layout = _$lib_172.extendDeep({}, layout); layoutIn = layout; } else { @@ -66657,7 +67344,7 @@ var _$valiate_207 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_207(traceIn)) { + if(!__isPlainObject_208(traceIn)) { errorList.push(format('object', base)); continue; } @@ -66677,13 +67364,13 @@ var _$valiate_207 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_207(traceIn, traceOut, traceSchema, errorList, base); + __crawl_208(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_207(transformsIn)) { + if(!__isArray_208(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -66693,7 +67380,7 @@ var _$valiate_207 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_207(transformsIn[j])) { + if(!__isPlainObject_208(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -66708,7 +67395,7 @@ var _$valiate_207 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_207(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_208(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -66716,13 +67403,13 @@ var _$valiate_207 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_207(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_208(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_207(objIn, objOut, schema, list, base, path) { +function __crawl_208(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -66747,10 +67434,10 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_207(valIn) && __isPlainObject_207(valOut)) { - __crawl_207(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_208(valIn) && __isPlainObject_208(valOut)) { + __crawl_208(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_207(valIn)) { + else if(isInfoArray && __isArray_208(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -66760,7 +67447,7 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_207(valIn[n])) { + if(__isArray_208(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -66769,7 +67456,7 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_171.validate(valInPart, item)) { + if(!_$lib_172.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -66787,7 +67474,7 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_171.validate(valInPart, item)) { + if(!_$lib_172.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -66796,7 +67483,7 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_207(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_208(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -66810,9 +67497,9 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_207(valIn[_index]) && __isPlainObject_207(valOut[j])) { + if(__isPlainObject_208(valIn[_index]) && __isPlainObject_208(valOut[j])) { indexList.push(_index); - __crawl_207(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_208(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -66821,7 +67508,7 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_207(valIn[j])) { + if(!__isPlainObject_208(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -66829,16 +67516,16 @@ function __crawl_207(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_207(valIn) && __isPlainObject_207(valOut)) { + else if(!__isPlainObject_208(valIn) && __isPlainObject_208(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_207(valIn) && __isArrayOrTypedArray_207(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_208(valIn) && __isArrayOrTypedArray_208(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_171.validate(valIn, nestedSchema)) { + else if(!_$lib_172.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -66858,7 +67545,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_171.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_172.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -66890,7 +67577,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_207(valIn) ? 'container' : 'key'; + var target = __isPlainObject_208(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -66916,7 +67603,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_207(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_208(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -66929,7 +67616,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_207(base)) { + if(__isArray_208(base)) { container = base[0]; trace = base[1]; } @@ -66942,7 +67629,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_171.log(msg); + _$lib_172.log(msg); return { code: code, @@ -66972,7 +67659,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_171.counterRegex('([a-z]+)'); +var idRegex = _$lib_172.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -66984,7 +67671,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_207(path)) return String(path); + if(!__isArray_208(path)) return String(path); var astr = ''; @@ -67073,7 +67760,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_264 = fileSaver; +var _$fileSaver_265 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -67086,9 +67773,9 @@ var _$fileSaver_264 = fileSaver; 'use strict'; -/* removed: var _$toImage_206 = require('../plot_api/to_image'); */; -/* removed: var _$lib_171 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_264 = require('./filesaver'); */; +/* removed: var _$toImage_207 = require('../plot_api/to_image'); */; +/* removed: var _$lib_172 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_265 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -67116,19 +67803,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_171.isIE() && opts.format !== 'svg') { + if(_$lib_172.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_206(gd, opts); + var promise = _$toImage_207(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_264(result, filename); + return _$fileSaver_265(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -67138,9 +67825,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_263 = downloadImage; +var _$downloadImage_264 = downloadImage; -var _$plot_api_200 = {}; +var _$plot_api_201 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67151,29 +67838,29 @@ var _$plot_api_200 = {}; 'use strict'; -/* removed: var _$plot_api_202 = require('./plot_api'); */; - -_$plot_api_200.plot = _$plot_api_202.plot; -_$plot_api_200.newPlot = _$plot_api_202.newPlot; -_$plot_api_200.restyle = _$plot_api_202.restyle; -_$plot_api_200.relayout = _$plot_api_202.relayout; -_$plot_api_200.redraw = _$plot_api_202.redraw; -_$plot_api_200.update = _$plot_api_202.update; -_$plot_api_200.react = _$plot_api_202.react; -_$plot_api_200.extendTraces = _$plot_api_202.extendTraces; -_$plot_api_200.prependTraces = _$plot_api_202.prependTraces; -_$plot_api_200.addTraces = _$plot_api_202.addTraces; -_$plot_api_200.deleteTraces = _$plot_api_202.deleteTraces; -_$plot_api_200.moveTraces = _$plot_api_202.moveTraces; -_$plot_api_200.purge = _$plot_api_202.purge; -_$plot_api_200.addFrames = _$plot_api_202.addFrames; -_$plot_api_200.deleteFrames = _$plot_api_202.deleteFrames; -_$plot_api_200.animate = _$plot_api_202.animate; -_$plot_api_200.setPlotConfig = _$plot_api_202.setPlotConfig; - -_$plot_api_200.toImage = _$toImage_206; -_$plot_api_200.validate = _$valiate_207; -_$plot_api_200.downloadImage = _$downloadImage_263; +/* removed: var _$plot_api_203 = require('./plot_api'); */; + +_$plot_api_201.plot = _$plot_api_203.plot; +_$plot_api_201.newPlot = _$plot_api_203.newPlot; +_$plot_api_201.restyle = _$plot_api_203.restyle; +_$plot_api_201.relayout = _$plot_api_203.relayout; +_$plot_api_201.redraw = _$plot_api_203.redraw; +_$plot_api_201.update = _$plot_api_203.update; +_$plot_api_201.react = _$plot_api_203.react; +_$plot_api_201.extendTraces = _$plot_api_203.extendTraces; +_$plot_api_201.prependTraces = _$plot_api_203.prependTraces; +_$plot_api_201.addTraces = _$plot_api_203.addTraces; +_$plot_api_201.deleteTraces = _$plot_api_203.deleteTraces; +_$plot_api_201.moveTraces = _$plot_api_203.moveTraces; +_$plot_api_201.purge = _$plot_api_203.purge; +_$plot_api_201.addFrames = _$plot_api_203.addFrames; +_$plot_api_201.deleteFrames = _$plot_api_203.deleteFrames; +_$plot_api_201.animate = _$plot_api_203.animate; +_$plot_api_201.setPlotConfig = _$plot_api_203.setPlotConfig; + +_$plot_api_201.toImage = _$toImage_207; +_$plot_api_201.validate = _$valiate_208; +_$plot_api_201.downloadImage = _$downloadImage_264; /** * Copyright 2012-2018, Plotly, Inc. @@ -67186,10 +67873,10 @@ _$plot_api_200.downloadImage = _$downloadImage_263; 'use strict'; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$lib_172 = require('../lib'); */; -var __extendFlat_262 = _$lib_171.extendFlat; -var extendDeep = _$lib_171.extendDeep; +var __extendFlat_263 = _$lib_172.extendFlat; +var extendDeep = _$lib_172.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -67234,7 +67921,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_262 = function clonePlot(graphObj, options) { +var _$clonePlot_263 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -67307,9 +67994,9 @@ var _$clonePlot_262 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_262(scene.xaxis, axesImageOverride); - __extendFlat_262(scene.yaxis, axesImageOverride); - __extendFlat_262(scene.zaxis, axesImageOverride); + __extendFlat_263(scene.xaxis, axesImageOverride); + __extendFlat_263(scene.yaxis, axesImageOverride); + __extendFlat_263(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -67358,27 +68045,27 @@ var _$clonePlot_262 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_268 = _$EventEmitter_17.EventEmitter; +var __EventEmitter_269 = _$EventEmitter_17.EventEmitter; -/* removed: var _$registry_261 = require('../registry'); */; -/* removed: var _$lib_171 = require('../lib'); */; +/* removed: var _$registry_262 = require('../registry'); */; +/* removed: var _$lib_172 = require('../lib'); */; -/* removed: var _$helpers_265 = require('./helpers'); */; -/* removed: var _$clonePlot_262 = require('./cloneplot'); */; -/* removed: var _$toSVG_269 = require('./tosvg'); */; -/* removed: var _$svgToImg_267 = require('./svgtoimg'); */; +/* removed: var _$helpers_266 = require('./helpers'); */; +/* removed: var _$clonePlot_263 = require('./cloneplot'); */; +/* removed: var _$toSVG_270 = require('./tosvg'); */; +/* removed: var _$svgToImg_268 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_268(gd, opts) { +function __toImage_269(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_268(); + var ev = new __EventEmitter_269(); - var clone = _$clonePlot_262(gd, {format: 'png'}); + var clone = _$clonePlot_263(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -67387,15 +68074,15 @@ function __toImage_268(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_265.getDelay(clonedGd._fullLayout); + var delay = _$helpers_266.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_269(clonedGd); + var svg = _$toSVG_270(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_171.randstr(); + canvas.id = _$lib_172.randstr(); - ev = _$svgToImg_267({ + ev = _$svgToImg_268({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -67411,9 +68098,9 @@ function __toImage_268(gd, opts) { }, delay); } - var redrawFunc = _$helpers_265.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_266.getRedrawFunc(clonedGd); - _$registry_261.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_262.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -67424,7 +68111,7 @@ function __toImage_268(gd, opts) { return ev; } -var _$toImage_268 = __toImage_268; +var _$toImage_269 = __toImage_269; /** * Copyright 2012-2018, Plotly, Inc. @@ -67437,19 +68124,19 @@ var _$toImage_268 = __toImage_268; 'use strict'; -/* removed: var _$helpers_265 = require('./helpers'); */; +/* removed: var _$helpers_266 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_265.getDelay, - getRedrawFunc: _$helpers_265.getRedrawFunc, - clone: _$clonePlot_262, - toSVG: _$toSVG_269, - svgToImg: _$svgToImg_267, - toImage: _$toImage_268, - downloadImage: _$downloadImage_263 + getDelay: _$helpers_266.getDelay, + getRedrawFunc: _$helpers_266.getRedrawFunc, + clone: _$clonePlot_263, + toSVG: _$toSVG_270, + svgToImg: _$svgToImg_268, + toImage: _$toImage_269, + downloadImage: _$downloadImage_264 }; -var _$Snapshot_266 = Snapshot; +var _$Snapshot_267 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -67462,42 +68149,42 @@ var _$Snapshot_266 = Snapshot; 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_367 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_368 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_171.mergeArray(trace.text, cd, 'tx'); - _$lib_171.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_171.mergeArray(trace.customdata, cd, 'data'); - _$lib_171.mergeArray(trace.textposition, cd, 'tp'); + _$lib_172.mergeArray(trace.text, cd, 'tx'); + _$lib_172.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_172.mergeArray(trace.customdata, cd, 'data'); + _$lib_172.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_171.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_171.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_171.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_172.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_172.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_172.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_171.mergeArray(marker.size, cd, 'ms'); - _$lib_171.mergeArray(marker.opacity, cd, 'mo'); - _$lib_171.mergeArray(marker.symbol, cd, 'mx'); - _$lib_171.mergeArray(marker.color, cd, 'mc'); + _$lib_172.mergeArray(marker.size, cd, 'ms'); + _$lib_172.mergeArray(marker.opacity, cd, 'mo'); + _$lib_172.mergeArray(marker.symbol, cd, 'mx'); + _$lib_172.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_171.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_171.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_172.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_172.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_171.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_171.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_172.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_172.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -67516,15 +68203,15 @@ var _$arraysToCalcdata_367 = function arraysToCalcdata(cd, trace) { /* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$calc_58 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_390 = require('./subtypes'); */; +/* removed: var _$subtypes_391 = require('./subtypes'); */; -var _$calcMarkerColorscale_373 = function calcMarkerColorscale(trace) { - if(_$subtypes_390.hasLines(trace) && _$hasColorscale_65(trace, 'line')) { +var _$calcMarkerColorscale_374 = function calcMarkerColorscale(trace) { + if(_$subtypes_391.hasLines(trace) && _$hasColorscale_65(trace, 'line')) { _$calc_58(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_390.hasMarkers(trace)) { + if(_$subtypes_391.hasMarkers(trace)) { if(_$hasColorscale_65(trace, 'marker')) { _$calc_58(trace, trace.marker.color, 'marker', 'c'); } @@ -67545,19 +68232,19 @@ var _$calcMarkerColorscale_373 = function calcMarkerColorscale(trace) { 'use strict'; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_369 = _$lib_171.isArrayOrTypedArray; +var __isArrayOrTypedArray_370 = _$lib_172.isArrayOrTypedArray; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -var __BADNUM_369 = _$numerical_154.BADNUM; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +var __BADNUM_370 = _$numerical_154.BADNUM; -/* removed: var _$subtypes_390 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_373 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_367 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_370 = require('./calc_selection'); */; +/* removed: var _$subtypes_391 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_374 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_368 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_371 = require('./calc_selection'); */; -function __calc_369(gd, trace) { - var xa = _$axes_213.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_213.getFromId(gd, trace.yaxis || 'y'); +function __calc_370(gd, trace) { + var xa = _$axes_214.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_214.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -67569,16 +68256,16 @@ function __calc_369(gd, trace) { for(var i = 0; i < serieslen; i++) { cd[i] = (_$fastIsnumeric_18(x[i]) && _$fastIsnumeric_18(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_369, y: __BADNUM_369}; + {x: __BADNUM_370, y: __BADNUM_370}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_367(cd, trace); - _$calcMarkerColorscale_373(trace); - _$calcSelection_370(cd, trace); + _$arraysToCalcdata_368(cd, trace); + _$calcMarkerColorscale_374(trace); + _$calcSelection_371(cd, trace); gd.firstscatter = false; return cd; @@ -67611,9 +68298,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_390.hasMarkers(trace) && !_$subtypes_390.hasText(trace)) + (!_$subtypes_391.hasMarkers(trace) && !_$subtypes_391.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -67632,12 +68319,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_213.expand(xa, x, xOptions); - _$axes_213.expand(ya, y, yOptions); + _$axes_214.expand(xa, x, xOptions); + _$axes_214.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_390.hasMarkers(trace)) return; + if(!_$subtypes_391.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -67655,10 +68342,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_369(marker.size)) { + if(__isArrayOrTypedArray_370(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_213.setConvert(ax); + _$axes_214.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -67673,8 +68360,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_369 = { - calc: __calc_369, +var _$calc_370 = { + calc: __calc_370, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -67692,7 +68379,7 @@ var _$calc_369 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_371 = function cleanData(fullData) { +var _$cleanData_372 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -67729,9 +68416,9 @@ var _$cleanData_371 = function cleanData(fullData) { 'use strict'; /* removed: var _$color_51 = require('../../components/color'); */; -var __isArrayOrTypedArray_377 = _$lib_171.isArrayOrTypedArray; +var __isArrayOrTypedArray_378 = _$lib_172.isArrayOrTypedArray; -var _$fillColorDefaults_377 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_378 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -67739,10 +68426,10 @@ var _$fillColorDefaults_377 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_377(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_378(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_377(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_378(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } @@ -67764,11 +68451,11 @@ var _$fillColorDefaults_377 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_381 = _$lib_171.isArrayOrTypedArray; +var __isArrayOrTypedArray_382 = _$lib_172.isArrayOrTypedArray; /* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_381 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_382 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); @@ -67777,7 +68464,7 @@ var _$lineDefaults_381 = function lineDefaults(traceIn, traceOut, defaultColor, _$colorScaleDefaults_61(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_381(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_382(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -67798,7 +68485,7 @@ var _$lineDefaults_381 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_383 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_384 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -67818,7 +68505,7 @@ var _$handleLineShapeDefaults_383 = function handleLineShapeDefaults(traceIn, tr /* removed: var _$hasColorscale_65 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_390 = require('./subtypes'); */; +/* removed: var _$subtypes_391 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -67826,8 +68513,8 @@ var _$handleLineShapeDefaults_383 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_386 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_390.isBubble(traceIn), +var _$markerDefaults_387 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_391.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -67896,17 +68583,17 @@ var _$markerDefaults_386 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_391 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_392 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_171.coerceFont(coerce, 'textfont', layout.font); + _$lib_172.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -67924,27 +68611,27 @@ var _$text_defaults_391 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$registry_261 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -/* removed: var _$attributes_368 = require('./attributes'); */; -/* removed: var _$constants_374 = require('./constants'); */; -/* removed: var _$subtypes_390 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_392 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_386 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_381 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_383 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_391 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_377 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_369 = require('./attributes'); */; +/* removed: var _$constants_375 = require('./constants'); */; +/* removed: var _$subtypes_391 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_393 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_387 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_382 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_384 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_392 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_378 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_375 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_376 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_368, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_369, attr, dflt); } - var len = _$handleXYDefaults_392(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_393(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_374.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_375.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -67954,24 +68641,24 @@ var _$supplyDefaults_375 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_390.hasLines(traceOut)) { - _$lineDefaults_381(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_383(traceIn, traceOut, coerce); + if(_$subtypes_391.hasLines(traceOut)) { + _$lineDefaults_382(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_384(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_390.hasMarkers(traceOut)) { - _$markerDefaults_386(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_391.hasMarkers(traceOut)) { + _$markerDefaults_387(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_390.hasText(traceOut)) { - _$text_defaults_391(traceIn, traceOut, layout, coerce); + if(_$subtypes_391.hasText(traceOut)) { + _$text_defaults_392(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_390.hasMarkers(traceOut) || _$subtypes_390.hasText(traceOut)) { + if(_$subtypes_391.hasMarkers(traceOut) || _$subtypes_391.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -67979,8 +68666,8 @@ var _$supplyDefaults_375 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_377(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_390.hasLines(traceOut)) _$handleLineShapeDefaults_383(traceIn, traceOut, coerce); + _$fillColorDefaults_378(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_391.hasLines(traceOut)) _$handleLineShapeDefaults_384(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -67988,11 +68675,11 @@ var _$supplyDefaults_375 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_261.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_262.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_171.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_172.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -68007,10 +68694,10 @@ var _$supplyDefaults_375 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; /* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$subtypes_390 = require('./subtypes'); */; +/* removed: var _$subtypes_391 = require('./subtypes'); */; -var _$getTraceColor_378 = function getTraceColor(trace, di) { +var _$getTraceColor_379 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes @@ -68041,7 +68728,7 @@ var _$getTraceColor_378 = function getTraceColor(trace, di) { else { lc = (trace.line || {}).color; return (lc && _$color_51.opacity(lc) && - _$subtypes_390.hasLines(trace) && trace.line.width) ? + _$subtypes_391.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -68057,14 +68744,14 @@ var _$getTraceColor_378 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$fx_93 = require('../../components/fx'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$getTraceColor_378 = require('./get_trace_color'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$getTraceColor_379 = require('./get_trace_color'); */; /* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$fillHoverText_376 = require('./fill_hover_text'); */; +/* removed: var _$fillHoverText_377 = require('./fill_hover_text'); */; -var _$hoverPoints_379 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_380 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -68117,8 +68804,8 @@ var _$hoverPoints_379 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_171.extendFlat(pointData, { - color: _$getTraceColor_378(trace, di), + _$lib_172.extendFlat(pointData, { + color: _$getTraceColor_379(trace, di), x0: xc - rad, x1: xc + rad, @@ -68131,8 +68818,8 @@ var _$hoverPoints_379 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_376(di, trace, pointData); - _$registry_261.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_377(di, trace, pointData); + _$registry_262.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -68204,7 +68891,7 @@ var _$hoverPoints_379 = function hoverPoints(pointData, xval, yval, hovermode) { color = trace.line.color; } - _$lib_171.extendFlat(pointData, { + _$lib_172.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -68238,14 +68925,14 @@ var _$hoverPoints_379 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_382 = _$numerical_154.BADNUM; -/* removed: var _$lib_171 = require('../../lib'); */; -var __segmentsIntersect_382 = _$lib_171.segmentsIntersect; -var constrain = _$lib_171.constrain; -/* removed: var _$constants_374 = require('./constants'); */; +var __BADNUM_383 = _$numerical_154.BADNUM; +/* removed: var _$lib_172 = require('../../lib'); */; +var __segmentsIntersect_383 = _$lib_172.segmentsIntersect; +var constrain = _$lib_172.constrain; +/* removed: var _$constants_375 = require('./constants'); */; -var _$linePoints_382 = function linePoints(d, opts) { +var _$linePoints_383 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -68254,7 +68941,7 @@ var _$linePoints_382 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_374.minTolerance; + var minTolerance = _$constants_375.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -68292,7 +68979,7 @@ var _$linePoints_382 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_382 || y === __BADNUM_382) return di.intoCenter || false; + if(x === __BADNUM_383 || y === __BADNUM_383) return di.intoCenter || false; return [x, y]; } @@ -68300,7 +68987,7 @@ var _$linePoints_382 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_374.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_375.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -68312,7 +68999,7 @@ var _$linePoints_382 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_374.maxScreensAway; + var maxScreensAway = _$constants_375.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -68341,7 +69028,7 @@ var _$linePoints_382 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_382(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_383(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -68395,7 +69082,7 @@ var _$linePoints_382 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_171.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_172.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -68648,7 +69335,7 @@ var _$linePoints_382 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_384 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_385 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -68690,17 +69377,17 @@ var _$linkTraces_384 = function linkTraces(gd, plotinfo, cdscatter) { /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$subtypes_390 = require('./subtypes'); */; -/* removed: var _$linePoints_382 = require('./line_points'); */; -/* removed: var _$linkTraces_384 = require('./link_traces'); */; -var __polygonTester_387 = _$polygon_183.tester; +/* removed: var _$subtypes_391 = require('./subtypes'); */; +/* removed: var _$linePoints_383 = require('./line_points'); */; +/* removed: var _$linkTraces_385 = require('./link_traces'); */; +var __polygonTester_388 = _$polygon_184.tester; -var _$plot_387 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_388 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -68709,9 +69396,8 @@ var _$plot_387 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -68723,7 +69409,7 @@ var _$plot_387 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_384(gd, plotinfo, cdscatter); + _$linkTraces_385(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -68762,12 +69448,12 @@ var _$plot_387 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_387(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_388(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_387(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_388(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -68822,7 +69508,7 @@ function createFills(gd, scatterlayer, plotinfo) { }); } -function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_388(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -68844,7 +69530,7 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran tr = _$d3_15.select(element); // error bars are at the bottom - _$registry_261.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_262.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -68856,7 +69542,7 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -68882,11 +69568,11 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_171.noop; + makeUpdate = _$lib_172.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_390.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_391.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -68923,7 +69609,7 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_382(cdscatter, { + segments = _$linePoints_383(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -68938,7 +69624,7 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_387(segments[i]); + trace._polygons[i] = __polygonTester_388(segments[i]); } if(segments.length) { @@ -68964,7 +69650,7 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_390.hasLines(trace) && pts.length > 1) { + if(_$subtypes_391.hasLines(trace) && pts.length > 1) { var el = _$d3_15.select(this); // This makes the coloring work correctly: @@ -69091,19 +69777,19 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = d[0].trace, s = _$d3_15.select(this), - showMarkers = _$subtypes_390.hasMarkers(trace), - showText = _$subtypes_390.hasText(trace); + showMarkers = _$subtypes_391.hasMarkers(trace), + showText = _$subtypes_391.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_171.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_172.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_171.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_172.identity; } // marker points @@ -69224,11 +69910,11 @@ function __plotOne_387(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_15.extent(_$lib_171.simpleMap(xa.range, xa.r2c)), - yr = _$d3_15.extent(_$lib_171.simpleMap(ya.range, ya.r2c)); + xr = _$d3_15.extent(_$lib_172.simpleMap(xa.range, xa.r2c)), + yr = _$d3_15.extent(_$lib_172.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_390.hasMarkers(trace)) return; + if(!_$subtypes_391.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -69243,7 +69929,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_390.hasMarkers(tracei) && + if(_$subtypes_391.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -69274,9 +69960,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_390 = require('./subtypes'); */; +/* removed: var _$subtypes_391 = require('./subtypes'); */; -var _$selectPoints_388 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_389 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -69287,7 +69973,7 @@ var _$selectPoints_388 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_390.hasMarkers(trace) && !_$subtypes_390.hasText(trace)); + var hasOnlyLines = (!_$subtypes_391.hasMarkers(trace) && !_$subtypes_391.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -69330,9 +70016,9 @@ var _$selectPoints_388 = function selectPoints(searchInfo, polygon) { /* removed: var _$d3_15 = require('d3'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$registry_261 = require('../../registry'); */; +/* removed: var _$registry_262 = require('../../registry'); */; -function __style_389(gd, cd) { +function __style_390(gd, cd) { var s = cd ? cd[0].node3 : _$d3_15.select(gd).selectAll('g.trace.scatter'); s.style('opacity', function(d) { @@ -69351,7 +70037,7 @@ function __style_389(gd, cd) { s.selectAll('g.trace path.js-fill') .call(_$drawing_76.fillGroupStyle); - _$registry_261.getComponentMethod('errorbars', 'style')(s); + _$registry_262.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { @@ -69364,8 +70050,8 @@ function stylePoints(sel, trace, gd) { _$drawing_76.selectedTextStyle(txs, trace); } -var _$style_389 = { - style: __style_389, +var _$style_390 = { + style: __style_390, stylePoints: stylePoints }; @@ -69382,35 +70068,35 @@ var _$style_389 = { var Scatter = {}; -/* removed: var _$subtypes_390 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_390.hasLines; -Scatter.hasMarkers = _$subtypes_390.hasMarkers; -Scatter.hasText = _$subtypes_390.hasText; -Scatter.isBubble = _$subtypes_390.isBubble; +/* removed: var _$subtypes_391 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_391.hasLines; +Scatter.hasMarkers = _$subtypes_391.hasMarkers; +Scatter.hasText = _$subtypes_391.hasText; +Scatter.isBubble = _$subtypes_391.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_368; -Scatter.supplyDefaults = _$supplyDefaults_375; -Scatter.cleanData = _$cleanData_371; -Scatter.calc = _$calc_369.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_367; -Scatter.plot = _$plot_387; -Scatter.colorbar = _$colorbar_372; -Scatter.style = _$style_389.style; -Scatter.hoverPoints = _$hoverPoints_379; -Scatter.selectPoints = _$selectPoints_388; +Scatter.attributes = _$attributes_369; +Scatter.supplyDefaults = _$supplyDefaults_376; +Scatter.cleanData = _$cleanData_372; +Scatter.calc = _$calc_370.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_368; +Scatter.plot = _$plot_388; +Scatter.colorbar = _$colorbar_373; +Scatter.style = _$style_390.style; +Scatter.hoverPoints = _$hoverPoints_380; +Scatter.selectPoints = _$selectPoints_389; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_224; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_225; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_380 = Scatter; +var _$Scatter_381 = Scatter; var _$core_157 = {}; /** @@ -69424,7 +70110,7 @@ var _$core_157 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_157.version = '1.35.2'; +_$core_157.version = '1.36.0'; // inject promise polyfill _$es6Promise_16.polyfill(); @@ -69436,24 +70122,24 @@ _$plotcss_1; _$mathjax_config_158; // include registry module and expose register method -/* removed: var _$registry_261 = require('./registry'); */; -var register = _$core_157.register = _$registry_261.register; +/* removed: var _$registry_262 = require('./registry'); */; +var register = _$core_157.register = _$registry_262.register; // expose plot api methods -/* removed: var _$plot_api_200 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_200); +/* removed: var _$plot_api_201 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_201); for(var i = 0; i < methodNames.length; i++) { var __name_157 = methodNames[i]; - _$core_157[__name_157] = _$plot_api_200[__name_157]; + _$core_157[__name_157] = _$plot_api_201[__name_157]; register({ moduleType: 'apiMethod', name: __name_157, - fn: _$plot_api_200[__name_157] + fn: _$plot_api_201[__name_157] }); } // scatter is the only trace included by default -register(_$Scatter_380); +register(_$Scatter_381); // register all registrable components modules register([ @@ -69473,8 +70159,8 @@ register([ // locales en and en-US are required for default behavior register([ - _$localeEn_196, - _$localeEnUs_195 + _$localeEn_197, + _$localeEnUs_196 ]); // plot icons @@ -69483,9 +70169,9 @@ _$core_157.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk _$core_157.Plots = _$plots_246; _$core_157.Fx = _$fx_93; -_$core_157.Snapshot = _$Snapshot_266; -_$core_157.PlotSchema = _$plot_schema_204; -_$core_157.Queue = _$queue_185; +_$core_157.Snapshot = _$Snapshot_267; +_$core_157.PlotSchema = _$plot_schema_205; +_$core_157.Queue = _$queue_186; // export d3 used in the bundle _$core_157.d3 = _$d3_15; @@ -69515,20 +70201,20 @@ var _$core_6 = _$core_157; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$plots_246 = require('../../plots/plots'); */; /* removed: var _$colorscale_66 = require('../../components/colorscale'); */; /* removed: var _$draw_55 = require('../../components/colorbar/draw'); */; -var _$colorbar_320 = function colorbar(gd, cd) { +var _$colorbar_321 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, zmin = trace.zmin, zmax = trace.zmax; - if(!_$fastIsnumeric_18(zmin)) zmin = _$lib_171.aggNums(Math.min, null, trace.z); - if(!_$fastIsnumeric_18(zmax)) zmax = _$lib_171.aggNums(Math.max, null, trace.z); + if(!_$fastIsnumeric_18(zmin)) zmin = _$lib_172.aggNums(Math.min, null, trace.z); + if(!_$fastIsnumeric_18(zmax)) zmax = _$lib_172.aggNums(Math.max, null, trace.z); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); @@ -69563,7 +70249,7 @@ var _$colorbar_320 = function colorbar(gd, cd) { 'use strict'; -var _$handleStyleDefaults_332 = function handleStyleDefaults(traceIn, traceOut, coerce) { +var _$handleStyleDefaults_333 = function handleStyleDefaults(traceIn, traceOut, coerce) { var zsmooth = coerce('zsmooth'); if(zsmooth === false) { // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect. @@ -69585,21 +70271,21 @@ var _$handleStyleDefaults_332 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$has_columns_324 = require('./has_columns'); */; -/* removed: var _$handleXYZDefaults_333 = require('./xyz_defaults'); */; -/* removed: var _$handleStyleDefaults_332 = require('./style_defaults'); */; +/* removed: var _$has_columns_325 = require('./has_columns'); */; +/* removed: var _$handleXYZDefaults_334 = require('./xyz_defaults'); */; +/* removed: var _$handleStyleDefaults_333 = require('./style_defaults'); */; /* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_317 = require('./attributes'); */; +/* removed: var _$attributes_318 = require('./attributes'); */; -var _$supplyDefaults_322 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_323 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_317, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_318, attr, dflt); } - var len = _$handleXYZDefaults_333(traceIn, traceOut, coerce, layout); + var len = _$handleXYZDefaults_334(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -69607,9 +70293,9 @@ var _$supplyDefaults_322 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); - _$handleStyleDefaults_332(traceIn, traceOut, coerce, layout); + _$handleStyleDefaults_333(traceIn, traceOut, coerce, layout); - coerce('connectgaps', _$has_columns_324(traceOut) && (traceOut.zsmooth !== false)); + coerce('connectgaps', _$has_columns_325(traceOut) && (traceOut.zsmooth !== false)); _$colorScaleDefaults_61(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; @@ -69627,23 +70313,23 @@ var _$supplyDefaults_322 = function supplyDefaults(traceIn, traceOut, defaultCol var Heatmap = {}; -Heatmap.attributes = _$attributes_317; -Heatmap.supplyDefaults = _$supplyDefaults_322; -Heatmap.calc = _$calc_318; -Heatmap.plot = _$plot_330; -Heatmap.colorbar = _$colorbar_320; -Heatmap.style = _$style_331; -Heatmap.hoverPoints = _$hoverPoints_325; +Heatmap.attributes = _$attributes_318; +Heatmap.supplyDefaults = _$supplyDefaults_323; +Heatmap.calc = _$calc_319; +Heatmap.plot = _$plot_331; +Heatmap.colorbar = _$colorbar_321; +Heatmap.style = _$style_332; +Heatmap.hoverPoints = _$hoverPoints_326; Heatmap.moduleType = 'trace'; Heatmap.name = 'heatmap'; -Heatmap.basePlotModule = _$cartesian_224; -Heatmap.categories = ['cartesian', '2dMap']; +Heatmap.basePlotModule = _$cartesian_225; +Heatmap.categories = ['cartesian', 'svg', '2dMap']; Heatmap.meta = { }; -var _$Heatmap_326 = Heatmap; +var _$Heatmap_327 = Heatmap; /** * Copyright 2012-2018, Plotly, Inc. @@ -69655,7 +70341,7 @@ var _$Heatmap_326 = Heatmap; 'use strict'; -var _$heatmap_7 = _$Heatmap_326; +var _$heatmap_7 = _$Heatmap_327; /** * Copyright 2012-2018, Plotly, Inc. @@ -69667,9 +70353,9 @@ var _$heatmap_7 = _$Heatmap_326; 'use strict'; -/* removed: var _$attributes_271 = require('../bar/attributes'); */; +/* removed: var _$attributes_272 = require('../bar/attributes'); */; -var _$attributes_334 = { +var _$attributes_335 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -69681,8 +70367,8 @@ var _$attributes_334 = { }, - text: _$attributes_271.text, - orientation: _$attributes_271.orientation, + text: _$attributes_272.text, + orientation: _$attributes_272.orientation, histfunc: { valType: 'enumerated', @@ -69774,13 +70460,13 @@ var _$attributes_334 = { }, ybins: makeBinsAttr('y'), - marker: _$attributes_271.marker, + marker: _$attributes_272.marker, - selected: _$attributes_271.selected, - unselected: _$attributes_271.unselected, + selected: _$attributes_272.selected, + unselected: _$attributes_272.unselected, _deprecated: { - bardir: _$attributes_271._deprecated.bardir + bardir: _$attributes_272._deprecated.bardir } }; @@ -69833,18 +70519,18 @@ function makeBinsAttr(axLetter) { /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; -/* removed: var _$arraysToCalcdata_270 = require('../bar/arrays_to_calcdata'); */; -/* removed: var _$bin_functions_337 = require('./bin_functions'); */; -/* removed: var _$norm_functions_345 = require('./norm_functions'); */; -/* removed: var _$doAvg_335 = require('./average'); */; -/* removed: var _$cleanBins_340 = require('./clean_bins'); */; -var __oneMonth_339 = _$numerical_154.ONEAVGMONTH; -/* removed: var _$getBinSpanLabelRound_338 = require('./bin_label_vals'); */; +/* removed: var _$arraysToCalcdata_271 = require('../bar/arrays_to_calcdata'); */; +/* removed: var _$bin_functions_338 = require('./bin_functions'); */; +/* removed: var _$norm_functions_346 = require('./norm_functions'); */; +/* removed: var _$doAvg_336 = require('./average'); */; +/* removed: var _$cleanBins_341 = require('./clean_bins'); */; +var __oneMonth_340 = _$numerical_154.ONEAVGMONTH; +/* removed: var _$getBinSpanLabelRound_339 = require('./bin_label_vals'); */; -var _$calc_339 = function calc(gd, trace) { +var _$calc_340 = function calc(gd, trace) { // ignore as much processing as possible (and including in autorange) if bar is not visible if(trace.visible !== true) return; @@ -69852,7 +70538,7 @@ var _$calc_339 = function calc(gd, trace) { // note: this logic for choosing orientation is duplicated in graph_obj->setstyles var pos = []; var size = []; - var pa = _$axes_213.getFromId(gd, trace.orientation === 'h' ? + var pa = _$axes_214.getFromId(gd, trace.orientation === 'h' ? (trace.yaxis || 'y') : (trace.xaxis || 'x')); var mainData = trace.orientation === 'h' ? 'y' : 'x'; var counterData = {x: 'y', y: 'x'}[mainData]; @@ -69860,7 +70546,7 @@ var _$calc_339 = function calc(gd, trace) { var cumulativeSpec = trace.cumulative; var i; - _$cleanBins_340(trace, pa, mainData); + _$cleanBins_341(trace, pa, mainData); var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData); var binSpec = binsAndPos[0]; @@ -69888,16 +70574,16 @@ var _$calc_339 = function calc(gd, trace) { var extremeFunc = func === 'max' || func === 'min'; var sizeInit = extremeFunc ? null : 0; - var binFunc = _$bin_functions_337.count; - var normFunc = _$norm_functions_345[norm]; + var binFunc = _$bin_functions_338.count; + var normFunc = _$norm_functions_346[norm]; var isAvg = false; var pr2c = function(v) { return pa.r2c(v, 0, calendar); }; var rawCounterData; - if(_$lib_171.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { + if(_$lib_172.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { rawCounterData = trace[counterData]; isAvg = func === 'avg'; - binFunc = _$bin_functions_337[func]; + binFunc = _$bin_functions_338[func]; } // create the bins (and any extra arrays needed) @@ -69905,10 +70591,10 @@ var _$calc_339 = function calc(gd, trace) { i = pr2c(binSpec.start); // decrease end a little in case of rounding errors - binEnd = pr2c(binSpec.end) + (i - _$axes_213.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; + binEnd = pr2c(binSpec.end) + (i - _$axes_214.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; while(i < binEnd && pos.length < 1e6) { - i2 = _$axes_213.tickIncrement(i, binSpec.size, false, calendar); + i2 = _$axes_214.tickIncrement(i, binSpec.size, false, calendar); pos.push((i + i2) / 2); size.push(sizeInit); inputPoints.push([]); @@ -69943,7 +70629,7 @@ var _$calc_339 = function calc(gd, trace) { var ptNumber2cdIndex = {}; for(i = 0; i < pos0.length; i++) { var posi = pos0[i]; - n = _$lib_171.findBin(posi, bins); + n = _$lib_172.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]]) { @@ -69959,11 +70645,11 @@ var _$calc_339 = function calc(gd, trace) { var roundFn; if(!uniqueValsPerBin) { - roundFn = _$getBinSpanLabelRound_338(leftGap, rightGap, binEdges, pa, calendar); + roundFn = _$getBinSpanLabelRound_339(leftGap, rightGap, binEdges, pa, calendar); } // average and/or normalize the data, if needed - if(isAvg) total = _$doAvg_335(size, counts); + if(isAvg) total = _$doAvg_336(size, counts); if(normFunc) normFunc(size, total, inc); // after all normalization etc, now we can accumulate if desired @@ -70016,13 +70702,13 @@ var _$calc_339 = function calc(gd, trace) { 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_213.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; + cd[0].width1 = _$axes_214.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; } - _$arraysToCalcdata_270(cd, trace); + _$arraysToCalcdata_271(cd, trace); - if(_$lib_171.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_171.tagSelected(cd, trace, ptNumber2cdIndex); + if(_$lib_172.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_172.tagSelected(cd, trace, ptNumber2cdIndex); } return cd; @@ -70071,7 +70757,7 @@ function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { calendar = tracei[mainData + 'calendar']; var cumulativeSpec = tracei.cumulative; - binSpec = _$axes_213.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); + binSpec = _$axes_214.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); // Edge case: single-valued histogram overlaying others // Use them all together to calculate the bin size for the single-valued one @@ -70222,7 +70908,7 @@ function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) { // 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_171.distinctVals(dataVals).minDiff; + minSize = _$lib_172.distinctVals(dataVals).minDiff; } // now apply the min size we found to all single-valued traces @@ -70282,7 +70968,7 @@ function getMinSize(size1, size2) { function numericSize(size) { if(_$fastIsnumeric_18(size)) return size; if(typeof size === 'string' && size.charAt(0) === 'M') { - return __oneMonth_339 * +(size.substr(1)); + return __oneMonth_340 * +(size.substr(1)); } return Infinity; } @@ -70351,7 +71037,7 @@ function cdf(size, direction, currentBin) { 'use strict'; -var _$handleBinDefaults_336 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { +var _$handleBinDefaults_337 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { coerce('histnorm'); binDirections.forEach(function(binDirection) { @@ -70383,17 +71069,17 @@ var _$handleBinDefaults_336 = function handleBinDefaults(traceIn, traceOut, coer 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$handleBinDefaults_336 = require('./bin_defaults'); */; -/* removed: var _$handleStyleDefaults_283 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_334 = require('./attributes'); */; +/* removed: var _$handleBinDefaults_337 = require('./bin_defaults'); */; +/* removed: var _$handleStyleDefaults_284 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_335 = require('./attributes'); */; -var _$supplyDefaults_341 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_342 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_334, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_335, attr, dflt); } var x = coerce('x'), @@ -70415,23 +71101,23 @@ var _$supplyDefaults_341 = function supplyDefaults(traceIn, traceOut, defaultCol return; } - var handleCalendarDefaults = _$registry_261.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_262.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); var hasAggregationData = traceOut[orientation === 'h' ? 'x' : 'y']; if(hasAggregationData) coerce('histfunc'); var binDirections = (orientation === 'h') ? ['y'] : ['x']; - _$handleBinDefaults_336(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_337(traceIn, traceOut, coerce, binDirections); - _$handleStyleDefaults_283(traceIn, traceOut, coerce, defaultColor, layout); + _$handleStyleDefaults_284(traceIn, traceOut, coerce, defaultColor, layout); // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_261.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_262.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, _$color_51.defaultLine, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, _$color_51.defaultLine, {axis: 'x', inherit: 'y'}); - _$lib_171.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_172.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -70444,7 +71130,7 @@ var _$supplyDefaults_341 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_342 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_343 = 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; @@ -70490,11 +71176,11 @@ var _$eventData_342 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_274 = require('../bar/hover'); */; -var hoverLabelText = _$axes_213.hoverLabelText; +/* removed: var _$hoverPoints_275 = require('../bar/hover'); */; +var hoverLabelText = _$axes_214.hoverLabelText; -var _$hoverPoints_343 = function hoverPoints(pointData, xval, yval, hovermode) { - var pts = _$hoverPoints_274(pointData, xval, yval, hovermode); +var _$hoverPoints_344 = function hoverPoints(pointData, xval, yval, hovermode) { + var pts = _$hoverPoints_275(pointData, xval, yval, hovermode); if(!pts) return; @@ -70538,28 +71224,28 @@ var _$hoverPoints_343 = function hoverPoints(pointData, xval, yval, hovermode) { var Histogram = {}; -Histogram.attributes = _$attributes_334; -Histogram.layoutAttributes = _$layout_attributes_276; -Histogram.supplyDefaults = _$supplyDefaults_341; -Histogram.supplyLayoutDefaults = _$layout_defaults_277; -Histogram.calc = _$calc_339; -Histogram.setPositions = _$setPositions_280; -Histogram.plot = _$plot_278; -Histogram.style = _$style_282; -Histogram.colorbar = _$colorbar_372; -Histogram.hoverPoints = _$hoverPoints_343; -Histogram.selectPoints = _$selectPoints_279; -Histogram.eventData = _$eventData_342; +Histogram.attributes = _$attributes_335; +Histogram.layoutAttributes = _$layout_attributes_277; +Histogram.supplyDefaults = _$supplyDefaults_342; +Histogram.supplyLayoutDefaults = _$layout_defaults_278; +Histogram.calc = _$calc_340; +Histogram.setPositions = _$setPositions_281; +Histogram.plot = _$plot_279; +Histogram.style = _$style_283; +Histogram.colorbar = _$colorbar_373; +Histogram.hoverPoints = _$hoverPoints_344; +Histogram.selectPoints = _$selectPoints_280; +Histogram.eventData = _$eventData_343; Histogram.moduleType = 'trace'; Histogram.name = 'histogram'; -Histogram.basePlotModule = _$cartesian_224; -Histogram.categories = ['cartesian', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; +Histogram.basePlotModule = _$cartesian_225; +Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; Histogram.meta = { }; -var _$Histogram_344 = Histogram; +var _$Histogram_345 = Histogram; /** * Copyright 2012-2018, Plotly, Inc. @@ -70571,7 +71257,7 @@ var _$Histogram_344 = Histogram; 'use strict'; -var _$histogram_8 = _$Histogram_344; +var _$histogram_8 = _$Histogram_345; /** * Copyright 2012-2018, Plotly, Inc. @@ -70583,17 +71269,17 @@ var _$histogram_8 = _$Histogram_344; 'use strict'; -/* removed: var _$attributes_334 = require('../histogram/attributes'); */; -/* removed: var _$attributes_317 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_335 = require('../histogram/attributes'); */; +/* removed: var _$attributes_318 = require('../heatmap/attributes'); */; /* removed: var _$attributes_57 = require('../../components/colorscale/attributes'); */; /* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -var __extendFlat_346 = _$extend_165.extendFlat; +var __extendFlat_347 = _$extend_166.extendFlat; -var _$attributes_346 = __extendFlat_346({}, +var _$attributes_347 = __extendFlat_347({}, { - x: _$attributes_334.x, - y: _$attributes_334.y, + x: _$attributes_335.x, + y: _$attributes_335.y, z: { valType: 'data_array', @@ -70609,22 +71295,22 @@ var _$attributes_346 = __extendFlat_346({}, editType: 'calc' }, - histnorm: _$attributes_334.histnorm, - histfunc: _$attributes_334.histfunc, - autobinx: _$attributes_334.autobinx, - nbinsx: _$attributes_334.nbinsx, - xbins: _$attributes_334.xbins, - autobiny: _$attributes_334.autobiny, - nbinsy: _$attributes_334.nbinsy, - ybins: _$attributes_334.ybins, + histnorm: _$attributes_335.histnorm, + histfunc: _$attributes_335.histfunc, + autobinx: _$attributes_335.autobinx, + nbinsx: _$attributes_335.nbinsx, + xbins: _$attributes_335.xbins, + autobiny: _$attributes_335.autobiny, + nbinsy: _$attributes_335.nbinsy, + ybins: _$attributes_335.ybins, - xgap: _$attributes_317.xgap, - ygap: _$attributes_317.ygap, - zsmooth: _$attributes_317.zsmooth, - zhoverformat: _$attributes_317.zhoverformat + xgap: _$attributes_318.xgap, + ygap: _$attributes_318.ygap, + zsmooth: _$attributes_318.zsmooth, + zhoverformat: _$attributes_318.zhoverformat }, _$attributes_57, - { autocolorscale: __extendFlat_346({}, _$attributes_57.autocolorscale, {dflt: false}) }, + { autocolorscale: __extendFlat_347({}, _$attributes_57.autocolorscale, {dflt: false}) }, { colorbar: _$attributes_52 } ); @@ -70639,11 +71325,11 @@ var _$attributes_346 = __extendFlat_346({}, 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$handleBinDefaults_336 = require('../histogram/bin_defaults'); */; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$handleBinDefaults_337 = require('../histogram/bin_defaults'); */; -var _$handleSampleDefaults_351 = function handleSampleDefaults(traceIn, traceOut, coerce, layout) { +var _$handleSampleDefaults_352 = function handleSampleDefaults(traceIn, traceOut, coerce, layout) { var x = coerce('x'), y = coerce('y'); @@ -70655,7 +71341,7 @@ var _$handleSampleDefaults_351 = function handleSampleDefaults(traceIn, traceOut return; } - var handleCalendarDefaults = _$registry_261.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_262.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); // if marker.color is an array, we can use it in aggregation instead of z @@ -70664,7 +71350,7 @@ var _$handleSampleDefaults_351 = function handleSampleDefaults(traceIn, traceOut if(hasAggregationData) coerce('histfunc'); var binDirections = ['x', 'y']; - _$handleBinDefaults_336(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_337(traceIn, traceOut, coerce, binDirections); }; /** @@ -70678,23 +71364,23 @@ var _$handleSampleDefaults_351 = function handleSampleDefaults(traceIn, traceOut 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$handleSampleDefaults_351 = require('./sample_defaults'); */; -/* removed: var _$handleStyleDefaults_332 = require('../heatmap/style_defaults'); */; +/* removed: var _$handleSampleDefaults_352 = require('./sample_defaults'); */; +/* removed: var _$handleStyleDefaults_333 = require('../heatmap/style_defaults'); */; /* removed: var _$colorScaleDefaults_61 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_346 = require('./attributes'); */; +/* removed: var _$attributes_347 = require('./attributes'); */; -var _$supplyDefaults_348 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_349 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_346, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_347, attr, dflt); } - _$handleSampleDefaults_351(traceIn, traceOut, coerce, layout); + _$handleSampleDefaults_352(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; - _$handleStyleDefaults_332(traceIn, traceOut, coerce, layout); + _$handleStyleDefaults_333(traceIn, traceOut, coerce, layout); _$colorScaleDefaults_61( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); @@ -70711,11 +71397,11 @@ var _$supplyDefaults_348 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$hoverPoints_325 = require('../heatmap/hover'); */; -var __hoverLabelText_349 = _$axes_213.hoverLabelText; +/* removed: var _$hoverPoints_326 = require('../heatmap/hover'); */; +var __hoverLabelText_350 = _$axes_214.hoverLabelText; -var _$hoverPoints_349 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { - var pts = _$hoverPoints_325(pointData, xval, yval, hovermode, hoverLayer, contour); +var _$hoverPoints_350 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { + var pts = _$hoverPoints_326(pointData, xval, yval, hovermode, hoverLayer, contour); if(!pts) return; @@ -70727,8 +71413,8 @@ var _$hoverPoints_349 = function hoverPoints(pointData, xval, yval, hovermode, h var xRange = cd0.xRanges[nx]; var yRange = cd0.yRanges[ny]; - pointData.xLabel = __hoverLabelText_349(pointData.xa, xRange[0], xRange[1]); - pointData.yLabel = __hoverLabelText_349(pointData.ya, yRange[0], yRange[1]); + pointData.xLabel = __hoverLabelText_350(pointData.xa, xRange[0], xRange[1]); + pointData.yLabel = __hoverLabelText_350(pointData.ya, yRange[0], yRange[1]); return pts; }; @@ -70746,25 +71432,25 @@ var _$hoverPoints_349 = function hoverPoints(pointData, xval, yval, hovermode, h var Histogram2D = {}; -Histogram2D.attributes = _$attributes_346; -Histogram2D.supplyDefaults = _$supplyDefaults_348; -Histogram2D.calc = _$calc_318; -Histogram2D.plot = _$plot_330; -Histogram2D.colorbar = _$colorbar_320; -Histogram2D.style = _$style_331; -Histogram2D.hoverPoints = _$hoverPoints_349; -Histogram2D.eventData = _$eventData_342; +Histogram2D.attributes = _$attributes_347; +Histogram2D.supplyDefaults = _$supplyDefaults_349; +Histogram2D.calc = _$calc_319; +Histogram2D.plot = _$plot_331; +Histogram2D.colorbar = _$colorbar_321; +Histogram2D.style = _$style_332; +Histogram2D.hoverPoints = _$hoverPoints_350; +Histogram2D.eventData = _$eventData_343; Histogram2D.moduleType = 'trace'; Histogram2D.name = 'histogram2d'; -Histogram2D.basePlotModule = _$cartesian_224; -Histogram2D.categories = ['cartesian', '2dMap', 'histogram']; +Histogram2D.basePlotModule = _$cartesian_225; +Histogram2D.categories = ['cartesian', 'svg', '2dMap', 'histogram']; Histogram2D.meta = { }; -var _$Histogram2D_350 = Histogram2D; +var _$Histogram2D_351 = Histogram2D; /** * Copyright 2012-2018, Plotly, Inc. @@ -70776,7 +71462,7 @@ var _$Histogram2D_350 = Histogram2D; 'use strict'; -var _$histogram2d_9 = _$Histogram2D_350; +var _$histogram2d_9 = _$Histogram2D_351; /** * Copyright 2012-2018, Plotly, Inc. @@ -70788,37 +71474,37 @@ var _$histogram2d_9 = _$Histogram2D_350; 'use strict'; -/* removed: var _$attributes_346 = require('../histogram2d/attributes'); */; -/* removed: var _$attributes_295 = require('../contour/attributes'); */; +/* removed: var _$attributes_347 = require('../histogram2d/attributes'); */; +/* removed: var _$attributes_296 = require('../contour/attributes'); */; /* removed: var _$attributes_57 = require('../../components/colorscale/attributes'); */; /* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -var __extendFlat_352 = _$extend_165.extendFlat; - -var _$attributes_352 = __extendFlat_352({ - x: _$attributes_346.x, - y: _$attributes_346.y, - z: _$attributes_346.z, - marker: _$attributes_346.marker, - - histnorm: _$attributes_346.histnorm, - histfunc: _$attributes_346.histfunc, - autobinx: _$attributes_346.autobinx, - nbinsx: _$attributes_346.nbinsx, - xbins: _$attributes_346.xbins, - autobiny: _$attributes_346.autobiny, - nbinsy: _$attributes_346.nbinsy, - ybins: _$attributes_346.ybins, - - autocontour: _$attributes_295.autocontour, - ncontours: _$attributes_295.ncontours, - contours: _$attributes_295.contours, - line: _$attributes_295.line, - zhoverformat: _$attributes_346.zhoverformat +var __extendFlat_353 = _$extend_166.extendFlat; + +var _$attributes_353 = __extendFlat_353({ + x: _$attributes_347.x, + y: _$attributes_347.y, + z: _$attributes_347.z, + marker: _$attributes_347.marker, + + histnorm: _$attributes_347.histnorm, + histfunc: _$attributes_347.histfunc, + autobinx: _$attributes_347.autobinx, + nbinsx: _$attributes_347.nbinsx, + xbins: _$attributes_347.xbins, + autobiny: _$attributes_347.autobiny, + nbinsy: _$attributes_347.nbinsy, + ybins: _$attributes_347.ybins, + + autocontour: _$attributes_296.autocontour, + ncontours: _$attributes_296.ncontours, + contours: _$attributes_296.contours, + line: _$attributes_296.line, + zhoverformat: _$attributes_347.zhoverformat }, _$attributes_57, { - zmin: __extendFlat_352({}, _$attributes_57.zmin, {editType: 'calc'}), - zmax: __extendFlat_352({}, _$attributes_57.zmax, {editType: 'calc'}) + zmin: __extendFlat_353({}, _$attributes_57.zmin, {editType: 'calc'}), + zmax: __extendFlat_353({}, _$attributes_57.zmax, {editType: 'calc'}) }, { colorbar: _$attributes_52 } ); @@ -70834,28 +71520,28 @@ var _$attributes_352 = __extendFlat_352({ 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$handleSampleDefaults_351 = require('../histogram2d/sample_defaults'); */; -/* removed: var _$handleContourDefaults_302 = require('../contour/contours_defaults'); */; -/* removed: var _$handleStyleDefaults_316 = require('../contour/style_defaults'); */; -/* removed: var _$attributes_352 = require('./attributes'); */; +/* removed: var _$handleSampleDefaults_352 = require('../histogram2d/sample_defaults'); */; +/* removed: var _$handleContourDefaults_303 = require('../contour/contours_defaults'); */; +/* removed: var _$handleStyleDefaults_317 = require('../contour/style_defaults'); */; +/* removed: var _$attributes_353 = require('./attributes'); */; -var _$supplyDefaults_353 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_354 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_352, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_353, attr, dflt); } function coerce2(attr) { - return _$lib_171.coerce2(traceIn, traceOut, _$attributes_352, attr); + return _$lib_172.coerce2(traceIn, traceOut, _$attributes_353, attr); } - _$handleSampleDefaults_351(traceIn, traceOut, coerce, layout); + _$handleSampleDefaults_352(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; - _$handleContourDefaults_302(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_316(traceIn, traceOut, coerce, layout); + _$handleContourDefaults_303(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_317(traceIn, traceOut, coerce, layout); }; /** @@ -70871,24 +71557,24 @@ var _$supplyDefaults_353 = function supplyDefaults(traceIn, traceOut, defaultCol var Histogram2dContour = {}; -Histogram2dContour.attributes = _$attributes_352; -Histogram2dContour.supplyDefaults = _$supplyDefaults_353; -Histogram2dContour.calc = _$calc_296; -Histogram2dContour.plot = _$plot_313.plot; -Histogram2dContour.style = _$style_315; -Histogram2dContour.colorbar = _$colorbar_298; -Histogram2dContour.hoverPoints = _$hoverPoints_308; +Histogram2dContour.attributes = _$attributes_353; +Histogram2dContour.supplyDefaults = _$supplyDefaults_354; +Histogram2dContour.calc = _$calc_297; +Histogram2dContour.plot = _$plot_314.plot; +Histogram2dContour.style = _$style_316; +Histogram2dContour.colorbar = _$colorbar_299; +Histogram2dContour.hoverPoints = _$hoverPoints_309; Histogram2dContour.moduleType = 'trace'; Histogram2dContour.name = 'histogram2dcontour'; -Histogram2dContour.basePlotModule = _$cartesian_224; -Histogram2dContour.categories = ['cartesian', '2dMap', 'contour', 'histogram']; +Histogram2dContour.basePlotModule = _$cartesian_225; +Histogram2dContour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'histogram']; Histogram2dContour.meta = { }; -var _$Histogram2dContour_354 = Histogram2dContour; +var _$Histogram2dContour_355 = Histogram2dContour; /** * Copyright 2012-2018, Plotly, Inc. @@ -70900,7 +71586,7 @@ var _$Histogram2dContour_354 = Histogram2dContour; 'use strict'; -var _$histogram2dcontour_10 = _$Histogram2dContour_354; +var _$histogram2dcontour_10 = _$Histogram2dContour_355; /** * Copyright 2012-2018, Plotly, Inc. @@ -70914,18 +71600,18 @@ var _$histogram2dcontour_10 = _$Histogram2dContour_354; /* removed: var _$attributes_50 = require('../../components/color/attributes'); */; /* removed: var _$font_attributes_240 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_210 = require('../../plots/attributes'); */; -var __domainAttrs_355 = _$domain_239.attributes; +/* removed: var _$attributes_211 = require('../../plots/attributes'); */; +var __domainAttrs_356 = _$domain_239.attributes; -var __extendFlat_355 = _$extend_165.extendFlat; +var __extendFlat_356 = _$extend_166.extendFlat; -var __textFontAttrs_355 = _$font_attributes_240({ +var __textFontAttrs_356 = _$font_attributes_240({ editType: 'calc', colorEditType: 'style', }); -var _$attributes_355 = { +var _$attributes_356 = { labels: { valType: 'data_array', editType: 'calc', @@ -71018,7 +71704,7 @@ var _$attributes_355 = { editType: 'calc', }, - hoverinfo: __extendFlat_355({}, _$attributes_210.hoverinfo, { + hoverinfo: __extendFlat_356({}, _$attributes_211.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'] }), textposition: { @@ -71031,18 +71717,18 @@ var _$attributes_355 = { }, // TODO make those arrayOk? - textfont: __extendFlat_355({}, __textFontAttrs_355, { + textfont: __extendFlat_356({}, __textFontAttrs_356, { }), - insidetextfont: __extendFlat_355({}, __textFontAttrs_355, { + insidetextfont: __extendFlat_356({}, __textFontAttrs_356, { }), - outsidetextfont: __extendFlat_355({}, __textFontAttrs_355, { + outsidetextfont: __extendFlat_356({}, __textFontAttrs_356, { }), // position and shape - domain: __domainAttrs_355({name: 'pie', trace: true, editType: 'calc'}), + domain: __domainAttrs_356({name: 'pie', trace: true, editType: 'calc'}), hole: { valType: 'number', @@ -71099,7 +71785,7 @@ var _$attributes_355 = { } }; -var _$base_plot_356 = {}; +var _$base_plot_357 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -71110,19 +71796,19 @@ var _$base_plot_356 = {}; 'use strict'; -/* removed: var _$registry_261 = require('../../registry'); */; - +/* removed: var _$registry_262 = require('../../registry'); */; +var __getModuleCalcData_357 = _$get_data_242.getModuleCalcData; -_$base_plot_356.name = 'pie'; +_$base_plot_357.name = 'pie'; -_$base_plot_356.plot = function(gd) { - var Pie = _$registry_261.getModule('pie'); - var cdPie = getCdModule(gd.calcdata, Pie); +_$base_plot_357.plot = function(gd) { + var Pie = _$registry_262.getModule('pie'); + var cdPie = __getModuleCalcData_357(gd.calcdata, Pie)[0]; if(cdPie.length) Pie.plot(gd, cdPie); }; -_$base_plot_356.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_357.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPie = (oldFullLayout._has && oldFullLayout._has('pie')); var hasPie = (newFullLayout._has && newFullLayout._has('pie')); @@ -71131,21 +71817,6 @@ _$base_plot_356.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -function getCdModule(calcdata, _module) { - var cdModule = []; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - - if((trace._module === _module) && (trace.visible === true)) { - cdModule.push(cd); - } - } - - return cdModule; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -71157,15 +71828,15 @@ function getCdModule(calcdata, _module) { 'use strict'; /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_357 = _$lib_171.isArrayOrTypedArray; +var __isArrayOrTypedArray_358 = _$lib_172.isArrayOrTypedArray; /* removed: var _$tinycolor_33 = require('tinycolor2'); */; /* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$helpers_360 = require('./helpers'); */; +/* removed: var _$helpers_361 = require('./helpers'); */; -var _$calc_357 = function calc(gd, trace) { +var _$calc_358 = function calc(gd, trace) { var vals = trace.values; - var hasVals = __isArrayOrTypedArray_357(vals) && vals.length; + var hasVals = __isArrayOrTypedArray_358(vals) && vals.length; var labels = trace.labels; var colors = trace.marker.colors || []; var cd = []; @@ -71287,11 +71958,11 @@ var _$calc_357 = function calc(gd, trace) { pt = cd[i]; thisText = hasLabel ? [pt.label] : []; if(hasText) { - var texti = _$helpers_360.getFirstFilled(trace.text, pt.pts); + var texti = _$helpers_361.getFirstFilled(trace.text, pt.pts); if(texti) thisText.push(texti); } - if(hasValue) thisText.push(_$helpers_360.formatPieValue(pt.v, separators)); - if(hasPercent) thisText.push(_$helpers_360.formatPiePercent(pt.v / vTotal, separators)); + if(hasValue) thisText.push(_$helpers_361.formatPieValue(pt.v, separators)); + if(hasPercent) thisText.push(_$helpers_361.formatPiePercent(pt.v / vTotal, separators)); pt.text = thisText.join('
'); } } @@ -71342,21 +72013,21 @@ function generateDefaultColors(colorList) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$attributes_355 = require('./attributes'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$attributes_356 = require('./attributes'); */; var handleDomainDefaults = _$domain_239.defaults; -var _$supplyDefaults_358 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_359 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_355, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_356, attr, dflt); } - var coerceFont = _$lib_171.coerceFont; + var coerceFont = _$lib_172.coerceFont; var vals = coerce('values'); var labels = coerce('labels'); if(!Array.isArray(labels)) { - if(!_$lib_171.isArrayOrTypedArray(vals) || !vals.length) { + if(!_$lib_172.isArrayOrTypedArray(vals) || !vals.length) { // must have at least one of vals or labels traceOut.visible = false; return; @@ -71412,7 +72083,7 @@ var _$supplyDefaults_358 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$layout_attributes_362 = { +var _$layout_attributes_363 = { /** * hiddenlabels is the pie chart analog of visible:'legendonly' * but it can contain many labels, and can hide slices @@ -71434,13 +72105,13 @@ var _$layout_attributes_362 = { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$layout_attributes_362 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_363 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_363 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_364 = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_362, attr, dflt); + return _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_363, attr, dflt); } coerce('hiddenlabels'); }; @@ -71462,7 +72133,7 @@ var appendArrayMultiPointValues = _$helpers_90.appendArrayMultiPointValues; // Note: like other eventData routines, this creates the data for hover/unhover/click events // but it has a different API and goes through a totally different pathway. // So to ensure it doesn't get misused, it's not attached to the Pie module. -var _$eventData_359 = function eventData(pt, trace) { +var _$eventData_360 = function eventData(pt, trace) { var out = { curveNumber: trace.index, pointNumbers: pt.pts, @@ -71502,12 +72173,13 @@ var _$eventData_359 = function eventData(pt, trace) { /* removed: var _$fx_93 = require('../../components/fx'); */; /* removed: var _$color_51 = require('../../components/color'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_192 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$svg_text_utils_193 = require('../../lib/svg_text_utils'); */; -/* removed: var _$helpers_360 = require('./helpers'); */; -/* removed: var _$eventData_359 = require('./event_data'); */; +/* removed: var _$helpers_361 = require('./helpers'); */; +/* removed: var _$eventData_360 = require('./event_data'); */; -var _$plot_364 = function plot(gd, cdpie) { +var _$plot_365 = function plot(gd, cdpie) { var fullLayout = gd._fullLayout; scalePies(cdpie, fullLayout._size); @@ -71584,7 +72256,7 @@ var _$plot_364 = function plot(gd, cdpie) { // TODO: do we want to have Fx.castHoverinfo somehow handle this? // it already takes an array for index, for 2D, so this seems tricky. hoverinfo = _$fx_93.castHoverinfo({ - hoverinfo: [_$helpers_360.castOption(hoverinfo, pt.pts)], + hoverinfo: [_$helpers_361.castOption(hoverinfo, pt.pts)], _module: trace._module }, fullLayout2, 0); } @@ -71602,11 +72274,11 @@ var _$plot_364 = function plot(gd, cdpie) { if(hoverinfo.indexOf('label') !== -1) thisText.push(pt.label); if(hoverinfo.indexOf('text') !== -1) { - var texti = _$helpers_360.castOption(trace2.hovertext || trace2.text, pt.pts); + var texti = _$helpers_361.castOption(trace2.hovertext || trace2.text, pt.pts); if(texti) thisText.push(texti); } - if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_360.formatPieValue(pt.v, separators)); - if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_360.formatPiePercent(pt.v / cd0.vTotal, separators)); + if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_361.formatPieValue(pt.v, separators)); + if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_361.formatPiePercent(pt.v / cd0.vTotal, separators)); var hoverLabel = trace.hoverlabel; var hoverFont = hoverLabel.font; @@ -71618,11 +72290,11 @@ var _$plot_364 = function plot(gd, cdpie) { text: thisText.join('
'), name: hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined, idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right', - color: _$helpers_360.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, - borderColor: _$helpers_360.castOption(hoverLabel.bordercolor, pt.pts), - fontFamily: _$helpers_360.castOption(hoverFont.family, pt.pts), - fontSize: _$helpers_360.castOption(hoverFont.size, pt.pts), - fontColor: _$helpers_360.castOption(hoverFont.color, pt.pts) + color: _$helpers_361.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, + borderColor: _$helpers_361.castOption(hoverLabel.bordercolor, pt.pts), + fontFamily: _$helpers_361.castOption(hoverFont.family, pt.pts), + fontSize: _$helpers_361.castOption(hoverFont.size, pt.pts), + fontColor: _$helpers_361.castOption(hoverFont.color, pt.pts) }, { container: fullLayout2._hoverlayer.node(), outerContainer: fullLayout2._paper.node(), @@ -71633,7 +72305,7 @@ var _$plot_364 = function plot(gd, cdpie) { } gd.emit('plotly_hover', { - points: [_$eventData_359(pt, trace2)], + points: [_$eventData_360(pt, trace2)], event: _$d3_15.event }); hasHoverEvent = true; @@ -71646,7 +72318,7 @@ var _$plot_364 = function plot(gd, cdpie) { if(hasHoverEvent) { evt.originalEvent = _$d3_15.event; gd.emit('plotly_unhover', { - points: [_$eventData_359(pt, trace2)], + points: [_$eventData_360(pt, trace2)], event: _$d3_15.event }); hasHoverEvent = false; @@ -71669,7 +72341,7 @@ var _$plot_364 = function plot(gd, cdpie) { if(gd._dragging || fullLayout2.hovermode === false) return; - gd._hoverdata = [_$eventData_359(pt, trace2)]; + gd._hoverdata = [_$eventData_360(pt, trace2)]; _$fx_93.click(gd, _$d3_15.event); } @@ -71685,7 +72357,7 @@ var _$plot_364 = function plot(gd, cdpie) { .on('click', handleClick); if(trace.pull) { - var pull = +_$helpers_360.castOption(trace.pull, pt.pts) || 0; + var pull = +_$helpers_361.castOption(trace.pull, pt.pts) || 0; if(pull > 0) { cx += pull * pt.pxmid[0]; cy += pull * pt.pxmid[1]; @@ -71736,7 +72408,7 @@ var _$plot_364 = function plot(gd, cdpie) { } // add text - var textPosition = _$helpers_360.castOption(trace.textposition, pt.pts); + var textPosition = _$helpers_361.castOption(trace.textposition, pt.pts); var sliceTextGroup = sliceTop.selectAll('g.slicetext') .data(pt.text && (textPosition !== 'none') ? [0] : []); @@ -71745,13 +72417,11 @@ var _$plot_364 = function plot(gd, cdpie) { sliceTextGroup.exit().remove(); sliceTextGroup.each(function() { - var sliceText = _$d3_15.select(this).selectAll('text').data([0]); - - sliceText.enter().append('text') + var sliceText = _$lib_172.ensureSingle(_$d3_15.select(this), 'text', '', function(s) { // prohibit tex interpretation until we can handle // tex and regular text together - .attr('data-notex', 1); - sliceText.exit().remove(); + s.attr('data-notex', 1); + }); sliceText.text(pt.text) .attr({ @@ -71761,7 +72431,7 @@ var _$plot_364 = function plot(gd, cdpie) { }) .call(_$drawing_76.font, textPosition === 'outside' ? trace.outsidetextfont : trace.insidetextfont) - .call(_$svg_text_utils_192.convertToTspans, gd); + .call(_$svg_text_utils_193.convertToTspans, gd); // position the text relative to the slice var textBB = _$drawing_76.bBox(sliceText.node()); @@ -71982,8 +72652,8 @@ function scootLabels(quadrants, trace) { // overlap can only happen if the other point is pulled more than this one if(otherPt === thisPt || ( - (_$helpers_360.castOption(trace.pull, thisPt.pts) || 0) >= - (_$helpers_360.castOption(trace.pull, otherPt.pts) || 0)) + (_$helpers_361.castOption(trace.pull, thisPt.pts) || 0) >= + (_$helpers_361.castOption(trace.pull, otherPt.pts) || 0)) ) { continue; } @@ -72170,9 +72840,9 @@ function setCoords(cd) { /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$styleOne_366 = require('./style_one'); */; +/* removed: var _$styleOne_367 = require('./style_one'); */; -var _$style_365 = function style(gd) { +var _$style_366 = function style(gd) { gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) { var cd0 = cd[0]; var trace = cd0.trace; @@ -72181,7 +72851,7 @@ var _$style_365 = function style(gd) { traceSelection.style({opacity: trace.opacity}); traceSelection.selectAll('path.surface').each(function(pt) { - _$d3_15.select(this).call(_$styleOne_366, pt, trace); + _$d3_15.select(this).call(_$styleOne_367, pt, trace); }); }); }; @@ -72198,24 +72868,24 @@ var _$style_365 = function style(gd) { var Pie = {}; -Pie.attributes = _$attributes_355; -Pie.supplyDefaults = _$supplyDefaults_358; -Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_363; -Pie.layoutAttributes = _$layout_attributes_362; -Pie.calc = _$calc_357; -Pie.plot = _$plot_364; -Pie.style = _$style_365; -Pie.styleOne = _$styleOne_366; +Pie.attributes = _$attributes_356; +Pie.supplyDefaults = _$supplyDefaults_359; +Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_364; +Pie.layoutAttributes = _$layout_attributes_363; +Pie.calc = _$calc_358; +Pie.plot = _$plot_365; +Pie.style = _$style_366; +Pie.styleOne = _$styleOne_367; Pie.moduleType = 'trace'; Pie.name = 'pie'; -Pie.basePlotModule = _$base_plot_356; +Pie.basePlotModule = _$base_plot_357; Pie.categories = ['pie', 'showLegend']; Pie.meta = { }; -var _$Pie_361 = Pie; +var _$Pie_362 = Pie; /** * Copyright 2012-2018, Plotly, Inc. @@ -72227,7 +72897,7 @@ var _$Pie_361 = Pie; 'use strict'; -var _$pie_12 = _$Pie_361; +var _$pie_12 = _$Pie_362; /** * Copyright 2012-2018, Plotly, Inc. @@ -72240,7 +72910,7 @@ var _$pie_12 = _$Pie_361; 'use strict'; -var _$attributes_255 = { +var _$attributes_256 = { subplot: { valType: 'subplotid', @@ -72261,8 +72931,8 @@ var _$attributes_255 = { 'use strict'; -/* removed: var _$lib_171 = require('../lib'); */; -var __handleDomainDefaults_253 = _$domain_239.defaults; +/* removed: var _$lib_172 = require('../lib'); */; +var __handleDomainDefaults_254 = _$domain_239.defaults; /** @@ -72292,7 +72962,7 @@ var __handleDomainDefaults_253 = _$domain_239.defaults; * additional items needed by this function here as well * } */ -var _$handleSubplotDefaults_253 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { +var _$handleSubplotDefaults_254 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { var subplotType = opts.type; var subplotAttributes = opts.attributes; var handleDefaults = opts.handleDefaults; @@ -72304,7 +72974,7 @@ var _$handleSubplotDefaults_253 = function handleSubplotDefaults(layoutIn, layou var subplotLayoutIn, subplotLayoutOut; function coerce(attr, dflt) { - return _$lib_171.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); + return _$lib_172.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); } for(var i = 0; i < idsLength; i++) { @@ -72318,7 +72988,7 @@ var _$handleSubplotDefaults_253 = function handleSubplotDefaults(layoutIn, layou var dfltDomains = {}; dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength]; - __handleDomainDefaults_253(subplotLayoutOut, layoutOut, coerce, dfltDomains); + __handleDomainDefaults_254(subplotLayoutOut, layoutOut, coerce, dfltDomains); opts.id = id; handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts); @@ -72336,46 +73006,46 @@ var _$handleSubplotDefaults_253 = function handleSubplotDefaults(layoutIn, layou 'use strict'; -/* removed: var _$layout_attributes_225 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_256 = _$extend_165.extendFlat; +/* removed: var _$layout_attributes_226 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_257 = _$extend_166.extendFlat; -var _$axis_attributes_256 = { - title: _$layout_attributes_225.title, - titlefont: _$layout_attributes_225.titlefont, - color: _$layout_attributes_225.color, +var _$axis_attributes_257 = { + title: _$layout_attributes_226.title, + titlefont: _$layout_attributes_226.titlefont, + color: _$layout_attributes_226.color, // ticks - tickmode: _$layout_attributes_225.tickmode, - nticks: __extendFlat_256({}, _$layout_attributes_225.nticks, {dflt: 6, min: 1}), - tick0: _$layout_attributes_225.tick0, - dtick: _$layout_attributes_225.dtick, - tickvals: _$layout_attributes_225.tickvals, - ticktext: _$layout_attributes_225.ticktext, - ticks: _$layout_attributes_225.ticks, - ticklen: _$layout_attributes_225.ticklen, - tickwidth: _$layout_attributes_225.tickwidth, - tickcolor: _$layout_attributes_225.tickcolor, - showticklabels: _$layout_attributes_225.showticklabels, - showtickprefix: _$layout_attributes_225.showtickprefix, - tickprefix: _$layout_attributes_225.tickprefix, - showticksuffix: _$layout_attributes_225.showticksuffix, - ticksuffix: _$layout_attributes_225.ticksuffix, - showexponent: _$layout_attributes_225.showexponent, - exponentformat: _$layout_attributes_225.exponentformat, - separatethousands: _$layout_attributes_225.separatethousands, - tickfont: _$layout_attributes_225.tickfont, - tickangle: _$layout_attributes_225.tickangle, - tickformat: _$layout_attributes_225.tickformat, - tickformatstops: _$layout_attributes_225.tickformatstops, - hoverformat: _$layout_attributes_225.hoverformat, + tickmode: _$layout_attributes_226.tickmode, + nticks: __extendFlat_257({}, _$layout_attributes_226.nticks, {dflt: 6, min: 1}), + tick0: _$layout_attributes_226.tick0, + dtick: _$layout_attributes_226.dtick, + tickvals: _$layout_attributes_226.tickvals, + ticktext: _$layout_attributes_226.ticktext, + ticks: _$layout_attributes_226.ticks, + ticklen: _$layout_attributes_226.ticklen, + tickwidth: _$layout_attributes_226.tickwidth, + tickcolor: _$layout_attributes_226.tickcolor, + showticklabels: _$layout_attributes_226.showticklabels, + showtickprefix: _$layout_attributes_226.showtickprefix, + tickprefix: _$layout_attributes_226.tickprefix, + showticksuffix: _$layout_attributes_226.showticksuffix, + ticksuffix: _$layout_attributes_226.ticksuffix, + showexponent: _$layout_attributes_226.showexponent, + exponentformat: _$layout_attributes_226.exponentformat, + separatethousands: _$layout_attributes_226.separatethousands, + tickfont: _$layout_attributes_226.tickfont, + tickangle: _$layout_attributes_226.tickangle, + tickformat: _$layout_attributes_226.tickformat, + tickformatstops: _$layout_attributes_226.tickformatstops, + hoverformat: _$layout_attributes_226.hoverformat, // lines and grids - showline: __extendFlat_256({}, _$layout_attributes_225.showline, {dflt: true}), - linecolor: _$layout_attributes_225.linecolor, - linewidth: _$layout_attributes_225.linewidth, - showgrid: __extendFlat_256({}, _$layout_attributes_225.showgrid, {dflt: true}), - gridcolor: _$layout_attributes_225.gridcolor, - gridwidth: _$layout_attributes_225.gridwidth, - layer: _$layout_attributes_225.layer, + showline: __extendFlat_257({}, _$layout_attributes_226.showline, {dflt: true}), + linecolor: _$layout_attributes_226.linecolor, + linewidth: _$layout_attributes_226.linewidth, + showgrid: __extendFlat_257({}, _$layout_attributes_226.showgrid, {dflt: true}), + gridcolor: _$layout_attributes_226.gridcolor, + gridwidth: _$layout_attributes_226.gridwidth, + layer: _$layout_attributes_226.layer, // range min: { valType: 'number', @@ -72396,16 +73066,16 @@ var _$axis_attributes_256 = { 'use strict'; -/* removed: var _$lib_171 = require('../../../lib'); */; -/* removed: var _$axis_attributes_256 = require('./axis_attributes'); */; +/* removed: var _$lib_172 = require('../../../lib'); */; +/* removed: var _$axis_attributes_257 = require('./axis_attributes'); */; /* removed: var _$handleTickLabelDefaults_233 = require('../../cartesian/tick_label_defaults'); */; /* removed: var _$handleTickDefaults_234 = require('../../cartesian/tick_mark_defaults'); */; /* removed: var _$handleTickValueDefaults_235 = require('../../cartesian/tick_value_defaults'); */; -/* removed: var _$handleLineGridDefaults_227 = require('../../cartesian/line_grid_defaults'); */; +/* removed: var _$handleLineGridDefaults_228 = require('../../cartesian/line_grid_defaults'); */; -var _$supplyLayoutDefaults_257 = function supplyLayoutDefaults(containerIn, containerOut, options) { +var _$supplyLayoutDefaults_258 = function supplyLayoutDefaults(containerIn, containerOut, options) { function coerce(attr, dflt) { - return _$lib_171.coerce(containerIn, containerOut, _$axis_attributes_256, attr, dflt); + return _$lib_172.coerce(containerIn, containerOut, _$axis_attributes_257, attr, dflt); } containerOut.type = 'linear'; // no other types allowed for ternary @@ -72422,7 +73092,7 @@ var _$supplyLayoutDefaults_257 = function supplyLayoutDefaults(containerIn, cont var title = coerce('title', dfltTitle); containerOut._hovertitle = title === dfltTitle ? title : letterUpper; - _$lib_171.coerceFont(coerce, 'titlefont', { + _$lib_172.coerceFont(coerce, 'titlefont', { family: options.font.family, size: Math.round(options.font.size * 1.2), color: dfltFontColor @@ -72438,7 +73108,7 @@ var _$supplyLayoutDefaults_257 = function supplyLayoutDefaults(containerIn, cont var showTickLabels = coerce('showticklabels'); if(showTickLabels) { - _$lib_171.coerceFont(coerce, 'tickfont', { + _$lib_172.coerceFont(coerce, 'tickfont', { family: options.font.family, size: options.font.size, color: dfltFontColor @@ -72447,7 +73117,7 @@ var _$supplyLayoutDefaults_257 = function supplyLayoutDefaults(containerIn, cont coerce('tickformat'); } - _$handleLineGridDefaults_227(containerIn, containerOut, coerce, { + _$handleLineGridDefaults_228(containerIn, containerOut, coerce, { dfltColor: dfltColor, bgColor: options.bgColor, // default grid color is darker here (60%, vs cartesian default ~91%) @@ -72456,7 +73126,7 @@ var _$supplyLayoutDefaults_257 = function supplyLayoutDefaults(containerIn, cont showLine: true, showGrid: true, noZeroLine: true, - attributes: _$axis_attributes_256 + attributes: _$axis_attributes_257 }); coerce('hoverformat'); @@ -72474,12 +73144,12 @@ var _$supplyLayoutDefaults_257 = function supplyLayoutDefaults(containerIn, cont 'use strict'; /* removed: var _$attributes_50 = require('../../../components/color/attributes'); */; -var __domainAttrs_259 = _$domain_239.attributes; -/* removed: var _$axis_attributes_256 = require('./axis_attributes'); */; -var __overrideAll_259 = _$edit_types_198.overrideAll; +var __domainAttrs_260 = _$domain_239.attributes; +/* removed: var _$axis_attributes_257 = require('./axis_attributes'); */; +var __overrideAll_260 = _$edit_types_199.overrideAll; -var _$layout_attributes_259 = __overrideAll_259({ - domain: __domainAttrs_259({name: 'ternary'}), +var _$layout_attributes_260 = __overrideAll_260({ + domain: __domainAttrs_260({name: 'ternary'}), bgcolor: { valType: 'color', @@ -72494,9 +73164,9 @@ var _$layout_attributes_259 = __overrideAll_259({ min: 0, }, - aaxis: _$axis_attributes_256, - baxis: _$axis_attributes_256, - caxis: _$axis_attributes_256 + aaxis: _$axis_attributes_257, + baxis: _$axis_attributes_257, + caxis: _$axis_attributes_257 }, 'plot', 'from-root'); /** @@ -72512,16 +73182,16 @@ var _$layout_attributes_259 = __overrideAll_259({ /* removed: var _$color_51 = require('../../../components/color'); */; -/* removed: var _$handleSubplotDefaults_253 = require('../../subplot_defaults'); */; -/* removed: var _$layout_attributes_259 = require('./layout_attributes'); */; -/* removed: var _$supplyLayoutDefaults_257 = require('./axis_defaults'); */; +/* removed: var _$handleSubplotDefaults_254 = require('../../subplot_defaults'); */; +/* removed: var _$layout_attributes_260 = require('./layout_attributes'); */; +/* removed: var _$supplyLayoutDefaults_258 = require('./axis_defaults'); */; var axesNames = ['aaxis', 'baxis', 'caxis']; -var _$supplyLayoutDefaults_258 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_253(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_259 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_254(layoutIn, layoutOut, fullData, { type: 'ternary', - attributes: _$layout_attributes_259, + attributes: _$layout_attributes_260, handleDefaults: handleTernaryDefaults, font: layoutOut.font, paper_bgcolor: layoutOut.paper_bgcolor @@ -72542,7 +73212,7 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option containerIn = ternaryLayoutIn[axName] || {}; containerOut = ternaryLayoutOut[axName] = {_name: axName, type: 'linear'}; - _$supplyLayoutDefaults_257(containerIn, containerOut, options); + _$supplyLayoutDefaults_258(containerIn, containerOut, options); } // if the min values contradict each other, set them all to default (0) @@ -72575,20 +73245,21 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option /* removed: var _$d3_15 = require('d3'); */; /* removed: var _$tinycolor_33 = require('tinycolor2'); */; -/* removed: var _$registry_261 = require('../../registry'); */; -/* removed: var _$lib_171 = require('../../lib'); */; -var ____260 = _$lib_171._; +/* removed: var _$registry_262 = require('../../registry'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +var ____261 = _$lib_172._; /* removed: var _$color_51 = require('../../components/color'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; /* removed: var _$setConvert_232 = require('../cartesian/set_convert'); */; -var __extendFlat_260 = _$extend_165.extendFlat; +var __extendFlat_261 = _$extend_166.extendFlat; /* removed: var _$plots_246 = require('../plots'); */; -/* removed: var _$axes_213 = require('../cartesian/axes'); */; +/* removed: var _$axes_214 = require('../cartesian/axes'); */; /* removed: var _$dragelement_73 = require('../../components/dragelement'); */; /* removed: var _$fx_93 = require('../../components/fx'); */; /* removed: var _$titles_144 = require('../../components/titles'); */; -/* removed: var _$prepSelect_231 = require('../cartesian/select'); */; -/* removed: var _$constants_218 = require('../cartesian/constants'); */; +var __prepSelect_261 = _$select_231.prepSelect; +var __clearSelect_261 = _$select_231.clearSelect; +/* removed: var _$constants_219 = require('../cartesian/constants'); */; function Ternary(options, fullLayout) { this.id = options.id; @@ -72597,11 +73268,11 @@ function Ternary(options, fullLayout) { this.makeFramework(fullLayout); } -var _$Ternary_260 = Ternary; +var _$Ternary_261 = Ternary; -var __proto_260 = Ternary.prototype; +var __proto_261 = Ternary.prototype; -__proto_260.init = function(fullLayout) { +__proto_261.init = function(fullLayout) { this.container = fullLayout._ternarylayer; this.defs = fullLayout._defs; this.layoutId = fullLayout._uid; @@ -72609,7 +73280,7 @@ __proto_260.init = function(fullLayout) { this.layers = {}; }; -__proto_260.plot = function(ternaryCalcData, fullLayout) { +__proto_261.plot = function(ternaryCalcData, fullLayout) { var _this = this; var ternaryLayout = fullLayout[_this.id]; var graphSize = fullLayout._size; @@ -72630,37 +73301,32 @@ __proto_260.plot = function(ternaryCalcData, fullLayout) { _this.layers.plotbg.select('path').call(_$color_51.fill, ternaryLayout.bgcolor); }; -__proto_260.makeFramework = function(fullLayout) { +__proto_261.makeFramework = function(fullLayout) { var _this = this; 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 = fullLayout._clips.selectAll('#' + clipId) - .data([0]); - _this.clipDef.enter().append('clipPath').attr('id', clipId) - .append('path').attr('d', 'M0,0Z'); + _this.clipDef = _$lib_172.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.append('path').attr('d', 'M0,0Z'); + }); // 'relative' clippath (i.e. no translation) for this ternary subplot - var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id; - _this.clipDefRelative = fullLayout._clips.selectAll('#' + clipIdRelative) - .data([0]); - _this.clipDefRelative.enter().append('clipPath').attr('id', clipIdRelative) - .append('path').attr('d', 'M0,0Z'); + _this.clipDefRelative = _$lib_172.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function(s) { + s.append('path').attr('d', 'M0,0Z'); + }); // container for everything in this ternary subplot - _this.plotContainer = _this.container.selectAll('g.' + _this.id) - .data([0]); - _this.plotContainer.enter().append('g') - .classed(_this.id, true); - + _this.plotContainer = _$lib_172.ensureSingle(_this.container, 'g', _this.id); _this.updateLayers(ternaryLayout); _$drawing_76.setClipUrl(_this.layers.backplot, clipId); _$drawing_76.setClipUrl(_this.layers.grids, clipId); }; -__proto_260.updateLayers = function(ternaryLayout) { +__proto_261.updateLayers = function(ternaryLayout) { var _this = this; var layers = _this.layers; @@ -72730,7 +73396,7 @@ __proto_260.updateLayers = function(ternaryLayout) { var w_over_h = Math.sqrt(4 / 3); -__proto_260.adjustLayout = function(ternaryLayout, graphSize) { +__proto_261.adjustLayout = function(ternaryLayout, graphSize) { var _this = this, domain = ternaryLayout.domain, xDomainCenter = (domain.x[0] + domain.x[1]) / 2, @@ -72809,7 +73475,7 @@ __proto_260.adjustLayout = function(ternaryLayout, graphSize) { // 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_260({}, ternaryLayout.aaxis, { + var aaxis = _this.aaxis = __extendFlat_261({}, ternaryLayout.aaxis, { visible: true, range: [amin, sum - bmin - cmin], side: 'left', @@ -72831,7 +73497,7 @@ __proto_260.adjustLayout = function(ternaryLayout, graphSize) { // baxis goes across the bottom (backward). We can set it up as an x axis // without any enclosing transformation. - var baxis = _this.baxis = __extendFlat_260({}, ternaryLayout.baxis, { + var baxis = _this.baxis = __extendFlat_261({}, ternaryLayout.baxis, { visible: true, range: [sum - amin - cmin, bmin], side: 'bottom', @@ -72852,7 +73518,7 @@ __proto_260.adjustLayout = function(ternaryLayout, graphSize) { // caxis goes down the right side. Set it up as a y axis, with // post-transformation similar to aaxis - var caxis = _this.caxis = __extendFlat_260({}, ternaryLayout.caxis, { + var caxis = _this.caxis = __extendFlat_261({}, ternaryLayout.caxis, { visible: true, range: [sum - amin - bmin, cmin], side: 'right', @@ -72934,7 +73600,7 @@ __proto_260.adjustLayout = function(ternaryLayout, graphSize) { ); }; -__proto_260.drawAxes = function(doTitles) { +__proto_261.drawAxes = function(doTitles) { var _this = this, gd = _this.graphDiv, titlesuffix = _this.id.substr(7) + 'title', @@ -72943,9 +73609,9 @@ __proto_260.drawAxes = function(doTitles) { caxis = _this.caxis; // 3rd arg true below skips titles, so we can configure them // correctly later on. - _$axes_213.doTicks(gd, aaxis, true); - _$axes_213.doTicks(gd, baxis, true); - _$axes_213.doTicks(gd, caxis, true); + _$axes_214.doTicks(gd, aaxis, true); + _$axes_214.doTicks(gd, baxis, true); + _$axes_214.doTicks(gd, caxis, true); if(doTitles) { var apad = Math.max(aaxis.showticklabels ? aaxis.tickfont.size / 2 : 0, @@ -72954,7 +73620,7 @@ __proto_260.drawAxes = function(doTitles) { _this.layers['a-title'] = _$titles_144.draw(gd, 'a' + titlesuffix, { propContainer: aaxis, propName: _this.id + '.aaxis.title', - placeholder: ____260(gd, 'Click to enter Component A title'), + placeholder: ____261(gd, 'Click to enter Component A title'), attributes: { x: _this.x0 + _this.w / 2, y: _this.y0 - aaxis.titlefont.size / 3 - apad, @@ -72969,7 +73635,7 @@ __proto_260.drawAxes = function(doTitles) { _this.layers['b-title'] = _$titles_144.draw(gd, 'b' + titlesuffix, { propContainer: baxis, propName: _this.id + '.baxis.title', - placeholder: ____260(gd, 'Click to enter Component B title'), + placeholder: ____261(gd, 'Click to enter Component B title'), attributes: { x: _this.x0 - bpad, y: _this.y0 + _this.h + baxis.titlefont.size * 0.83 + bpad, @@ -72980,7 +73646,7 @@ __proto_260.drawAxes = function(doTitles) { _this.layers['c-title'] = _$titles_144.draw(gd, 'c' + titlesuffix, { propContainer: caxis, propName: _this.id + '.caxis.title', - placeholder: ____260(gd, 'Click to enter Component C title'), + placeholder: ____261(gd, 'Click to enter Component C title'), attributes: { x: _this.x0 + _this.w + bpad, y: _this.y0 + _this.h + caxis.titlefont.size * 0.83 + bpad, @@ -72992,7 +73658,7 @@ __proto_260.drawAxes = function(doTitles) { // hard coded paths for zoom corners // uses the same sizing as cartesian, length is MINZOOM/2, width is 3px -var CLEN = _$constants_218.MINZOOM / 2 + 0.87; +var CLEN = _$constants_219.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'; @@ -73006,9 +73672,9 @@ var TOPPATH = 'm0,1l' + (CLEN / 2) + ',' + (CLEN * 0.87) + 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_260 = true; +var __SHOWZOOMOUTTIP_261 = true; -__proto_260.initInteractions = function() { +__proto_261.initInteractions = function() { var _this = this, dragger = _this.layers.plotbg.select('path').node(), gd = _this.graphDiv, @@ -73046,14 +73712,14 @@ __proto_260.initInteractions = function() { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragDone; panPrep(); - clearSelect(); + __clearSelect_261(zoomContainer); } else if(dragModeNow === 'select' || dragModeNow === 'lasso') { - _$prepSelect_231(e, startX, startY, dragOptions, dragModeNow); + __prepSelect_261(e, startX, startY, dragOptions, dragModeNow); } }, clickFn: function(numClicks, evt) { - __removeZoombox_260(gd); + __removeZoombox_261(gd); if(numClicks === 2) { var attrs = {}; @@ -73061,7 +73727,7 @@ __proto_260.initInteractions = function() { attrs[_this.id + '.baxis.min'] = 0; attrs[_this.id + '.caxis.min'] = 0; gd.emit('plotly_doubleclick', null); - _$registry_261.call('relayout', gd, attrs); + _$registry_262.call('relayout', gd, attrs); } _$fx_93.click(gd, evt, _this.id); } @@ -73104,7 +73770,7 @@ __proto_260.initInteractions = function() { }) .attr('d', 'M0,0Z'); - clearSelect(); + __clearSelect_261(zoomContainer); } function getAFrac(x, y) { return 1 - (y / _this.h); } @@ -73124,7 +73790,7 @@ __proto_260.initInteractions = function() { yBottom = (1 - afrac) * _this.h, yTop = yBottom - xSpan / w_over_h; - if(xSpan < _$constants_218.MINZOOM) { + if(xSpan < _$constants_219.MINZOOM) { mins = mins0; zb.attr('d', path0); corners.attr('d', 'M0,0Z'); @@ -73157,7 +73823,7 @@ __proto_260.initInteractions = function() { } function zoomDone() { - __removeZoombox_260(gd); + __removeZoombox_261(gd); if(mins === mins0) return; @@ -73166,11 +73832,11 @@ __proto_260.initInteractions = function() { attrs[_this.id + '.baxis.min'] = mins.b; attrs[_this.id + '.caxis.min'] = mins.c; - _$registry_261.call('relayout', gd, attrs); + _$registry_262.call('relayout', gd, attrs); - if(__SHOWZOOMOUTTIP_260 && gd.data && gd._context.showTips) { - _$lib_171.notifier(____260(gd, 'Double-click to zoom back out'), 'long'); - __SHOWZOOMOUTTIP_260 = false; + if(__SHOWZOOMOUTTIP_261 && gd.data && gd._context.showTips) { + _$lib_172.notifier(____261(gd, 'Double-click to zoom back out'), 'long'); + __SHOWZOOMOUTTIP_261 = false; } } @@ -73245,14 +73911,7 @@ __proto_260.initInteractions = function() { attrs[_this.id + '.baxis.min'] = mins.b; attrs[_this.id + '.caxis.min'] = mins.c; - _$registry_261.call('relayout', gd, attrs); - } - - function clearSelect() { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomContainer.selectAll('.select-outline').remove(); + _$registry_262.call('relayout', gd, attrs); } // finally, set up hover and click @@ -73273,13 +73932,13 @@ __proto_260.initInteractions = function() { _$dragelement_73.init(dragOptions); }; -function __removeZoombox_260(gd) { +function __removeZoombox_261(gd) { _$d3_15.select(gd) .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') .remove(); } -var _$ternary_254 = {}; +var _$ternary_255 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -73291,27 +73950,27 @@ var _$ternary_254 = {}; 'use strict'; -/* removed: var _$Ternary_260 = require('./ternary'); */; +/* removed: var _$Ternary_261 = require('./ternary'); */; var getSubplotCalcData = _$get_data_242.getSubplotCalcData; -var __counterRegex_254 = _$lib_171.counterRegex; +var __counterRegex_255 = _$lib_172.counterRegex; var TERNARY = 'ternary'; -_$ternary_254.name = TERNARY; +_$ternary_255.name = TERNARY; -_$ternary_254.attr = 'subplot'; +_$ternary_255.attr = 'subplot'; -_$ternary_254.idRoot = TERNARY; +_$ternary_255.idRoot = TERNARY; -_$ternary_254.idRegex = _$ternary_254.attrRegex = __counterRegex_254(TERNARY); +_$ternary_255.idRegex = _$ternary_255.attrRegex = __counterRegex_255(TERNARY); -_$ternary_254.attributes = _$attributes_255; +_$ternary_255.attributes = _$attributes_256; -_$ternary_254.layoutAttributes = _$layout_attributes_259; +_$ternary_255.layoutAttributes = _$layout_attributes_260; -_$ternary_254.supplyLayoutDefaults = _$supplyLayoutDefaults_258; +_$ternary_255.supplyLayoutDefaults = _$supplyLayoutDefaults_259; -_$ternary_254.plot = function plotTernary(gd) { +_$ternary_255.plot = function plotTernary(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var ternaryIds = fullLayout._subplots[TERNARY]; @@ -73323,7 +73982,7 @@ _$ternary_254.plot = function plotTernary(gd) { // If ternary is not instantiated, create one! if(!ternary) { - ternary = new _$Ternary_260({ + ternary = new _$Ternary_261({ id: ternaryId, graphDiv: gd, container: fullLayout._ternarylayer.node() @@ -73338,7 +73997,7 @@ _$ternary_254.plot = function plotTernary(gd) { } }; -_$ternary_254.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$ternary_255.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || []; for(var i = 0; i < oldTernaryKeys.length; i++) { @@ -73366,19 +74025,19 @@ _$ternary_254.clean = function(newFullData, newFullLayout, oldFullData, oldFullL 'use strict'; -/* removed: var _$attributes_368 = require('../scatter/attributes'); */; -/* removed: var _$attributes_210 = require('../../plots/attributes'); */; +/* removed: var _$attributes_369 = require('../scatter/attributes'); */; +/* removed: var _$attributes_211 = require('../../plots/attributes'); */; /* removed: var _$makeColorScaleAttributes_59 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_52 = require('../../components/colorbar/attributes'); */; -var __dash_393 = _$attributes_75.dash; +var __dash_394 = _$attributes_75.dash; -var __extendFlat_393 = _$extend_165.extendFlat; +var __extendFlat_394 = _$extend_166.extendFlat; -var __scatterMarkerAttrs_393 = _$attributes_368.marker, - __scatterLineAttrs_393 = _$attributes_368.line, - __scatterMarkerLineAttrs_393 = __scatterMarkerAttrs_393.line; +var __scatterMarkerAttrs_394 = _$attributes_369.marker, + __scatterLineAttrs_394 = _$attributes_369.line, + __scatterMarkerLineAttrs_394 = __scatterMarkerAttrs_394.line; -var _$attributes_393 = { +var _$attributes_394 = { a: { valType: 'data_array', editType: 'calc', @@ -73402,60 +74061,60 @@ var _$attributes_393 = { editType: 'calc', }, - mode: __extendFlat_393({}, _$attributes_368.mode, {dflt: 'markers'}), - text: __extendFlat_393({}, _$attributes_368.text, { + mode: __extendFlat_394({}, _$attributes_369.mode, {dflt: 'markers'}), + text: __extendFlat_394({}, _$attributes_369.text, { }), - hovertext: __extendFlat_393({}, _$attributes_368.hovertext, { + hovertext: __extendFlat_394({}, _$attributes_369.hovertext, { }), line: { - color: __scatterLineAttrs_393.color, - width: __scatterLineAttrs_393.width, - dash: __dash_393, - shape: __extendFlat_393({}, __scatterLineAttrs_393.shape, + color: __scatterLineAttrs_394.color, + width: __scatterLineAttrs_394.width, + dash: __dash_394, + shape: __extendFlat_394({}, __scatterLineAttrs_394.shape, {values: ['linear', 'spline']}), - smoothing: __scatterLineAttrs_393.smoothing, + smoothing: __scatterLineAttrs_394.smoothing, editType: 'calc' }, - connectgaps: _$attributes_368.connectgaps, - cliponaxis: _$attributes_368.cliponaxis, - fill: __extendFlat_393({}, _$attributes_368.fill, { + connectgaps: _$attributes_369.connectgaps, + cliponaxis: _$attributes_369.cliponaxis, + fill: __extendFlat_394({}, _$attributes_369.fill, { values: ['none', 'toself', 'tonext'], }), - fillcolor: _$attributes_368.fillcolor, - marker: __extendFlat_393({ - symbol: __scatterMarkerAttrs_393.symbol, - opacity: __scatterMarkerAttrs_393.opacity, - maxdisplayed: __scatterMarkerAttrs_393.maxdisplayed, - size: __scatterMarkerAttrs_393.size, - sizeref: __scatterMarkerAttrs_393.sizeref, - sizemin: __scatterMarkerAttrs_393.sizemin, - sizemode: __scatterMarkerAttrs_393.sizemode, - line: __extendFlat_393({ - width: __scatterMarkerLineAttrs_393.width, + fillcolor: _$attributes_369.fillcolor, + marker: __extendFlat_394({ + symbol: __scatterMarkerAttrs_394.symbol, + opacity: __scatterMarkerAttrs_394.opacity, + maxdisplayed: __scatterMarkerAttrs_394.maxdisplayed, + size: __scatterMarkerAttrs_394.size, + sizeref: __scatterMarkerAttrs_394.sizeref, + sizemin: __scatterMarkerAttrs_394.sizemin, + sizemode: __scatterMarkerAttrs_394.sizemode, + line: __extendFlat_394({ + width: __scatterMarkerLineAttrs_394.width, editType: 'calc' }, _$makeColorScaleAttributes_59('marker.line') ), - gradient: __scatterMarkerAttrs_393.gradient, + gradient: __scatterMarkerAttrs_394.gradient, editType: 'calc' }, _$makeColorScaleAttributes_59('marker'), { - showscale: __scatterMarkerAttrs_393.showscale, + showscale: __scatterMarkerAttrs_394.showscale, colorbar: _$attributes_52 }), - textfont: _$attributes_368.textfont, - textposition: _$attributes_368.textposition, + textfont: _$attributes_369.textfont, + textposition: _$attributes_369.textposition, - selected: _$attributes_368.selected, - unselected: _$attributes_368.unselected, + selected: _$attributes_369.selected, + unselected: _$attributes_369.unselected, - hoverinfo: __extendFlat_393({}, _$attributes_210.hoverinfo, { + hoverinfo: __extendFlat_394({}, _$attributes_211.hoverinfo, { flags: ['a', 'b', 'c', 'text', 'name'] }), - hoveron: _$attributes_368.hoveron, + hoveron: _$attributes_369.hoveron, }; /** @@ -73471,15 +74130,15 @@ var _$attributes_393 = { /* removed: var _$fastIsnumeric_18 = require('fast-isnumeric'); */; -/* removed: var _$calcMarkerColorscale_373 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_367 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_370 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_394 = _$calc_369.calcMarkerSize; +/* removed: var _$calcMarkerColorscale_374 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_368 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_371 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_395 = _$calc_370.calcMarkerSize; var dataArrays = ['a', 'b', 'c']; var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']}; -var _$calc_394 = function calc(gd, trace) { +var _$calc_395 = function calc(gd, trace) { var ternary = gd._fullLayout[trace.subplot]; var displaySum = ternary.sum; var normSum = trace.sum || displaySum; @@ -73531,10 +74190,10 @@ var _$calc_394 = function calc(gd, trace) { else cd[i] = {x: false, y: false}; } - __calcMarkerSize_394(trace, serieslen); - _$calcMarkerColorscale_373(trace); - _$arraysToCalcdata_367(cd, trace); - _$calcSelection_370(cd, trace); + __calcMarkerSize_395(trace, serieslen); + _$calcMarkerColorscale_374(trace); + _$arraysToCalcdata_368(cd, trace); + _$calcSelection_371(cd, trace); return cd; }; @@ -73550,22 +74209,22 @@ var _$calc_394 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; -/* removed: var _$constants_374 = require('../scatter/constants'); */; -/* removed: var _$subtypes_390 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_386 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_381 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_383 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_391 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_377 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$constants_375 = require('../scatter/constants'); */; +/* removed: var _$subtypes_391 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_387 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_382 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_384 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_392 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_378 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_393 = require('./attributes'); */; +/* removed: var _$attributes_394 = require('./attributes'); */; -var _$supplyDefaults_395 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_396 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_393, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_394, attr, dflt); } var a = coerce('a'), @@ -73603,26 +74262,26 @@ var _$supplyDefaults_395 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('hovertext'); - var defaultMode = len < _$constants_374.PTS_LINESONLY ? 'lines+markers' : 'lines'; + var defaultMode = len < _$constants_375.PTS_LINESONLY ? 'lines+markers' : 'lines'; coerce('mode', defaultMode); - if(_$subtypes_390.hasLines(traceOut)) { - _$lineDefaults_381(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_383(traceIn, traceOut, coerce); + if(_$subtypes_391.hasLines(traceOut)) { + _$lineDefaults_382(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_384(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_390.hasMarkers(traceOut)) { - _$markerDefaults_386(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_391.hasMarkers(traceOut)) { + _$markerDefaults_387(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_390.hasText(traceOut)) { - _$text_defaults_391(traceIn, traceOut, layout, coerce); + if(_$subtypes_391.hasText(traceOut)) { + _$text_defaults_392(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_390.hasMarkers(traceOut) || _$subtypes_390.hasText(traceOut)) { + if(_$subtypes_391.hasMarkers(traceOut) || _$subtypes_391.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -73630,8 +74289,8 @@ var _$supplyDefaults_395 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_377(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_390.hasLines(traceOut)) _$handleLineShapeDefaults_383(traceIn, traceOut, coerce); + _$fillColorDefaults_378(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_391.hasLines(traceOut)) _$handleLineShapeDefaults_384(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -73639,7 +74298,7 @@ var _$supplyDefaults_395 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_171.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_172.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -73652,7 +74311,7 @@ var _$supplyDefaults_395 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_396 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_397 = function eventData(out, pt, trace, cd, pointNumber) { if(pt.xa) out.xaxis = pt.xa; if(pt.ya) out.yaxis = pt.ya; @@ -73684,12 +74343,12 @@ var _$eventData_396 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_379 = require('../scatter/hover'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hoverPoints_380 = require('../scatter/hover'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; -var _$hoverPoints_397 = function hoverPoints(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_379(pointData, xval, yval, hovermode); +var _$hoverPoints_398 = function hoverPoints(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_380(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -73731,7 +74390,7 @@ var _$hoverPoints_397 = function hoverPoints(pointData, xval, yval, hovermode) { var text = []; function textPart(ax, val) { - text.push(ax._hovertitle + ': ' + _$axes_213.tickText(ax, val, 'hover').text); + text.push(ax._hovertitle + ': ' + _$axes_214.tickText(ax, val, 'hover').text); } if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'c']; @@ -73755,9 +74414,9 @@ var _$hoverPoints_397 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -/* removed: var _$plot_387 = require('../scatter/plot'); */; +/* removed: var _$plot_388 = require('../scatter/plot'); */; -var _$plot_399 = function plot(gd, ternary, moduleCalcData) { +var _$plot_400 = function plot(gd, ternary, moduleCalcData) { var plotContainer = ternary.plotContainer; // remove all nodes inside the scatter layer @@ -73771,7 +74430,7 @@ var _$plot_399 = function plot(gd, ternary, moduleCalcData) { layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null }; - _$plot_387(gd, plotinfo, moduleCalcData); + _$plot_388(gd, plotinfo, moduleCalcData); }; /** @@ -73786,26 +74445,26 @@ var _$plot_399 = function plot(gd, ternary, moduleCalcData) { var ScatterTernary = {}; -ScatterTernary.attributes = _$attributes_393; -ScatterTernary.supplyDefaults = _$supplyDefaults_395; -ScatterTernary.colorbar = _$colorbar_372; -ScatterTernary.calc = _$calc_394; -ScatterTernary.plot = _$plot_399; -ScatterTernary.style = _$style_389.style; -ScatterTernary.hoverPoints = _$hoverPoints_397; -ScatterTernary.selectPoints = _$selectPoints_388; -ScatterTernary.eventData = _$eventData_396; +ScatterTernary.attributes = _$attributes_394; +ScatterTernary.supplyDefaults = _$supplyDefaults_396; +ScatterTernary.colorbar = _$colorbar_373; +ScatterTernary.calc = _$calc_395; +ScatterTernary.plot = _$plot_400; +ScatterTernary.style = _$style_390.style; +ScatterTernary.hoverPoints = _$hoverPoints_398; +ScatterTernary.selectPoints = _$selectPoints_389; +ScatterTernary.eventData = _$eventData_397; ScatterTernary.moduleType = 'trace'; ScatterTernary.name = 'scatterternary'; -ScatterTernary.basePlotModule = _$ternary_254; +ScatterTernary.basePlotModule = _$ternary_255; ScatterTernary.categories = ['ternary', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like']; ScatterTernary.meta = { }; -var _$ScatterTernary_398 = ScatterTernary; +var _$ScatterTernary_399 = ScatterTernary; /** * Copyright 2012-2018, Plotly, Inc. @@ -73817,7 +74476,7 @@ var _$ScatterTernary_398 = ScatterTernary; 'use strict'; -var _$scatterternary_13 = _$ScatterTernary_398; +var _$scatterternary_13 = _$ScatterTernary_399; /** * Copyright 2012-2018, Plotly, Inc. @@ -73829,16 +74488,16 @@ var _$scatterternary_13 = _$ScatterTernary_398; 'use strict'; -/* removed: var _$attributes_284 = require('../box/attributes'); */; -var __extendFlat_400 = _$extend_165.extendFlat; +/* removed: var _$attributes_285 = require('../box/attributes'); */; +var __extendFlat_401 = _$extend_166.extendFlat; -var _$attributes_400 = { - y: _$attributes_284.y, - x: _$attributes_284.x, - x0: _$attributes_284.x0, - y0: _$attributes_284.y0, - name: _$attributes_284.name, - orientation: __extendFlat_400({}, _$attributes_284.orientation, { +var _$attributes_401 = { + y: _$attributes_285.y, + x: _$attributes_285.x, + x0: _$attributes_285.x0, + y0: _$attributes_285.y0, + name: _$attributes_285.name, + orientation: __extendFlat_401({}, _$attributes_285.orientation, { }), @@ -73902,19 +74561,19 @@ var _$attributes_400 = { }, editType: 'plot' }, - fillcolor: _$attributes_284.fillcolor, + fillcolor: _$attributes_285.fillcolor, - points: __extendFlat_400({}, _$attributes_284.boxpoints, { + points: __extendFlat_401({}, _$attributes_285.boxpoints, { }), - jitter: __extendFlat_400({}, _$attributes_284.jitter, { + jitter: __extendFlat_401({}, _$attributes_285.jitter, { }), - pointpos: __extendFlat_400({}, _$attributes_284.pointpos, { + pointpos: __extendFlat_401({}, _$attributes_285.pointpos, { }), - marker: _$attributes_284.marker, - text: _$attributes_284.text, + marker: _$attributes_285.marker, + text: _$attributes_285.text, box: { visible: { @@ -73991,8 +74650,8 @@ var _$attributes_400 = { }, - selected: _$attributes_284.selected, - unselected: _$attributes_284.unselected, + selected: _$attributes_285.selected, + unselected: _$attributes_285.unselected, hoveron: { valType: 'flaglist', @@ -74005,7 +74664,7 @@ var _$attributes_400 = { } }; -var _$helpers_403 = {}; +var _$helpers_404 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -74016,7 +74675,7 @@ var _$helpers_403 = {}; 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; // Maybe add kernels more down the road, // but note that the default `spanmode: 'soft'` bounds might have @@ -74027,7 +74686,7 @@ var kernels = { } }; -_$helpers_403.makeKDE = function(calcItem, trace, vals) { +_$helpers_404.makeKDE = function(calcItem, trace, vals) { var len = vals.length; var kernel = kernels.gaussian; var bandwidth = calcItem.bandwidth; @@ -74043,7 +74702,7 @@ _$helpers_403.makeKDE = function(calcItem, trace, vals) { }; }; -_$helpers_403.getPositionOnKdePath = function(calcItem, trace, valuePx) { +_$helpers_404.getPositionOnKdePath = function(calcItem, trace, valuePx) { var posLetter, valLetter; if(trace.orientation === 'h') { @@ -74054,7 +74713,7 @@ _$helpers_403.getPositionOnKdePath = function(calcItem, trace, valuePx) { valLetter = 'y'; } - var pointOnPath = _$lib_171.findPointOnPath( + var pointOnPath = _$lib_172.findPointOnPath( calcItem.path, valuePx, valLetter, @@ -74070,13 +74729,13 @@ _$helpers_403.getPositionOnKdePath = function(calcItem, trace, valuePx) { return [posOnPath0, posOnPath1]; }; -_$helpers_403.getKdeValue = function(calcItem, trace, valueDist) { - var vals = calcItem.pts.map(_$helpers_403.extractVal); - var kde = _$helpers_403.makeKDE(calcItem, trace, vals); +_$helpers_404.getKdeValue = function(calcItem, trace, valueDist) { + var vals = calcItem.pts.map(_$helpers_404.extractVal); + var kde = _$helpers_404.makeKDE(calcItem, trace, vals); return kde(valueDist) / calcItem.posDensityScale; }; -_$helpers_403.extractVal = function(o) { return o.v; }; +_$helpers_404.extractVal = function(o) { return o.v; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -74088,19 +74747,19 @@ _$helpers_403.extractVal = function(o) { return o.v; }; 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calc_285 = require('../box/calc'); */; -/* removed: var _$helpers_403 = require('./helpers'); */; -var __BADNUM_401 = _$numerical_154.BADNUM; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$calc_286 = require('../box/calc'); */; +/* removed: var _$helpers_404 = require('./helpers'); */; +var __BADNUM_402 = _$numerical_154.BADNUM; -var _$calc_401 = function calc(gd, trace) { - var cd = _$calc_285(gd, trace); +var _$calc_402 = function calc(gd, trace) { + var cd = _$calc_286(gd, trace); if(cd[0].t.empty) return cd; var fullLayout = gd._fullLayout; - var valAxis = _$axes_213.getFromId( + var valAxis = _$axes_214.getFromId( gd, trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis'] ); @@ -74117,11 +74776,11 @@ var _$calc_401 = function calc(gd, trace) { for(var i = 0; i < cd.length; i++) { var cdi = cd[i]; - var vals = cdi.pts.map(_$helpers_403.extractVal); + var vals = cdi.pts.map(_$helpers_404.extractVal); var len = vals.length; // sample standard deviation - var ssd = _$lib_171.stdev(vals, len - 1, cdi.mean); + var ssd = _$lib_172.stdev(vals, len - 1, cdi.mean); var bandwidthDflt = ruleOfThumbBandwidth(vals, ssd, cdi.q3 - cdi.q1); var bandwidth = cdi.bandwidth = trace.bandwidth || bandwidthDflt; var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth); @@ -74132,12 +74791,12 @@ var _$calc_401 = function calc(gd, trace) { var step = dist / n; if(!isFinite(step) || !isFinite(n)) { - _$lib_171.error('Something went wrong with computing the violin span'); + _$lib_172.error('Something went wrong with computing the violin span'); cd[0].t.empty = true; return cd; } - var kde = _$helpers_403.makeKDE(cdi, trace, vals); + var kde = _$helpers_404.makeKDE(cdi, trace, vals); cdi.density = new Array(n); for(var k = 0, t = span[0]; t < (span[1] + step / 2); k++, t += step) { @@ -74146,11 +74805,11 @@ var _$calc_401 = function calc(gd, trace) { cdi.density[k] = {v: v, t: t}; } - _$axes_213.expand(valAxis, span, {padded: true}); + _$axes_214.expand(valAxis, span, {padded: true}); groupStats.maxCount = Math.max(groupStats.maxCount, vals.length); } - cd[0].t.labels.kde = _$lib_171._(gd, 'kde:'); + cd[0].t.labels.kde = _$lib_172._(gd, 'kde:'); return cd; }; @@ -74174,7 +74833,7 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { function calcSpanItem(index) { var s = spanIn[index]; var sc = valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']); - return sc === __BADNUM_401 ? spanLoose[index] : sc; + return sc === __BADNUM_402 ? spanLoose[index] : sc; } if(spanmode === 'soft') { @@ -74190,7 +74849,7 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { type: 'linear', range: spanOut }; - _$axes_213.setConvert(dummyAx); + _$axes_214.setConvert(dummyAx); dummyAx.cleanRange(); return spanOut; @@ -74206,21 +74865,21 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$color_51 = require('../../components/color'); */; -/* removed: var _$defaults_286 = require('../box/defaults'); */; -/* removed: var _$attributes_400 = require('./attributes'); */; +/* removed: var _$defaults_287 = require('../box/defaults'); */; +/* removed: var _$attributes_401 = require('./attributes'); */; -var _$supplyDefaults_402 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_403 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_171.coerce(traceIn, traceOut, _$attributes_400, attr, dflt); + return _$lib_172.coerce(traceIn, traceOut, _$attributes_401, attr, dflt); } function coerce2(attr, dflt) { - return _$lib_171.coerce2(traceIn, traceOut, _$attributes_400, attr, dflt); + return _$lib_172.coerce2(traceIn, traceOut, _$attributes_401, attr, dflt); } - _$defaults_286.handleSampleDefaults(traceIn, traceOut, coerce, layout); + _$defaults_287.handleSampleDefaults(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; coerce('bandwidth'); @@ -74237,7 +74896,7 @@ var _$supplyDefaults_402 = function supplyDefaults(traceIn, traceOut, defaultCol var lineWidth = coerce('line.width'); var fillColor = coerce('fillcolor', _$color_51.addOpacity(traceOut.line.color, 0.5)); - _$defaults_286.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''}); + _$defaults_287.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''}); var boxWidth = coerce2('box.width'); var boxFillColor = coerce2('box.fillcolor', fillColor); @@ -74262,12 +74921,12 @@ var _$supplyDefaults_402 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$axes_213 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hover_287 = require('../box/hover'); */; -/* removed: var _$helpers_403 = require('./helpers'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$axes_214 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hover_288 = require('../box/hover'); */; +/* removed: var _$helpers_404 = require('./helpers'); */; -var _$hoverPoints_404 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { +var _$hoverPoints_405 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { var cd = pointData.cd; var trace = cd[0].trace; var hoveron = trace.hoveron; @@ -74278,7 +74937,7 @@ var _$hoverPoints_404 = function hoverPoints(pointData, xval, yval, hovermode, h var violinLineAttrs; if(hasHoveronViolins || hasHoveronKDE) { - var closeBoxData = _$hover_287.hoverOnBoxes(pointData, xval, yval, hovermode); + var closeBoxData = _$hover_288.hoverOnBoxes(pointData, xval, yval, hovermode); if(hasHoveronViolins) { closeData = closeData.concat(closeBoxData); @@ -74306,17 +74965,17 @@ var _$hoverPoints_404 = function hoverPoints(pointData, xval, yval, hovermode, h var di = cd[pointData.index]; if(vVal >= di.span[0] && vVal <= di.span[1]) { - var kdePointData = _$lib_171.extendFlat({}, pointData); + var kdePointData = _$lib_172.extendFlat({}, pointData); var vValPx = vAxis.c2p(vVal, true); - var kdeVal = _$helpers_403.getKdeValue(di, trace, vVal); - var pOnPath = _$helpers_403.getPositionOnKdePath(di, trace, vValPx); + var kdeVal = _$helpers_404.getKdeValue(di, trace, vVal); + var pOnPath = _$helpers_404.getPositionOnKdePath(di, trace, vValPx); var paOffset = pAxis._offset; var paLength = pAxis._length; kdePointData[pLetter + '0'] = pOnPath[0]; kdePointData[pLetter + '1'] = pOnPath[1]; kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx; - kdePointData[vLetter + 'Label'] = vLetter + ': ' + _$axes_213.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3); + kdePointData[vLetter + 'Label'] = vLetter + ': ' + _$axes_214.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3); // move the spike to the KDE point kdePointData.spikeDistance = closeBoxData[0].spikeDistance; @@ -74328,15 +74987,15 @@ var _$hoverPoints_404 = function hoverPoints(pointData, xval, yval, hovermode, h closeData.push(kdePointData); violinLineAttrs = {stroke: pointData.color}; - violinLineAttrs[pLetter + '1'] = _$lib_171.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength); - violinLineAttrs[pLetter + '2'] = _$lib_171.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength); + violinLineAttrs[pLetter + '1'] = _$lib_172.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength); + violinLineAttrs[pLetter + '2'] = _$lib_172.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength); violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx; } } } if(hoveron.indexOf('points') !== -1) { - closePtData = _$hover_287.hoverOnPoints(pointData, xval, yval); + closePtData = _$hover_288.hoverOnPoints(pointData, xval, yval); } // update violin line (if any) @@ -74370,17 +75029,17 @@ var _$hoverPoints_404 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -/* removed: var _$layout_attributes_289 = require('../box/layout_attributes'); */; -var __extendFlat_406 = _$lib_171.extendFlat; +/* removed: var _$layout_attributes_290 = require('../box/layout_attributes'); */; +var __extendFlat_407 = _$lib_172.extendFlat; -var _$layout_attributes_406 = { - violinmode: __extendFlat_406({}, _$layout_attributes_289.boxmode, { +var _$layout_attributes_407 = { + violinmode: __extendFlat_407({}, _$layout_attributes_290.boxmode, { }), - violingap: __extendFlat_406({}, _$layout_attributes_289.boxgap, { + violingap: __extendFlat_407({}, _$layout_attributes_290.boxgap, { }), - violingroupgap: __extendFlat_406({}, _$layout_attributes_289.boxgroupgap, { + violingroupgap: __extendFlat_407({}, _$layout_attributes_290.boxgroupgap, { }) }; @@ -74395,15 +75054,15 @@ var _$layout_attributes_406 = { 'use strict'; -/* removed: var _$lib_171 = require('../../lib'); */; -/* removed: var _$layout_attributes_406 = require('./layout_attributes'); */; -/* removed: var _$layout_defaults_290 = require('../box/layout_defaults'); */; +/* removed: var _$lib_172 = require('../../lib'); */; +/* removed: var _$layout_attributes_407 = require('./layout_attributes'); */; +/* removed: var _$layout_defaults_291 = require('../box/layout_defaults'); */; -var _$supplyLayoutDefaults_407 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { +var _$supplyLayoutDefaults_408 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_171.coerce(layoutIn, layoutOut, _$layout_attributes_406, attr, dflt); + return _$lib_172.coerce(layoutIn, layoutOut, _$layout_attributes_407, attr, dflt); } - _$layout_defaults_290._supply(layoutIn, layoutOut, fullData, coerce, 'violin'); + _$layout_defaults_291._supply(layoutIn, layoutOut, fullData, coerce, 'violin'); }; /** @@ -74417,19 +75076,19 @@ var _$supplyLayoutDefaults_407 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; /* removed: var _$d3_15 = require('d3'); */; -/* removed: var _$lib_171 = require('../../lib'); */; +/* removed: var _$lib_172 = require('../../lib'); */; /* removed: var _$drawing_76 = require('../../components/drawing'); */; -/* removed: var _$plot_291 = require('../box/plot'); */; -/* removed: var _$linePoints_382 = require('../scatter/line_points'); */; -/* removed: var _$helpers_403 = require('./helpers'); */; +/* removed: var _$plot_292 = require('../box/plot'); */; +/* removed: var _$linePoints_383 = require('../scatter/line_points'); */; +/* removed: var _$helpers_404 = require('./helpers'); */; -var _$plot_408 = function plot(gd, plotinfo, cd) { +var _$plot_409 = function plot(gd, plotinfo, cd) { var fullLayout = gd._fullLayout; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; function makePath(pts) { - var segments = _$linePoints_382(pts, { + var segments = _$linePoints_383(pts, { xaxis: xa, yaxis: ya, connectGaps: true, @@ -74450,13 +75109,18 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { var cd0 = d[0]; var t = cd0.t; var trace = cd0.trace; - var sel = cd0.node3 = _$d3_15.select(this); + var sel = _$d3_15.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; var numViolins = fullLayout._numViolins; var group = (fullLayout.violinmode === 'group' && numViolins > 1); + var groupFraction = 1 - fullLayout.violingap; // violin max half width - var bdPos = t.bdPos = t.dPos * (1 - fullLayout.violingap) * (1 - fullLayout.violingroupgap) / (group ? numViolins : 1); + var bdPos = t.bdPos = t.dPos * groupFraction * (1 - fullLayout.violingroupgap) / (group ? numViolins : 1); // violin center offset - var bPos = t.bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numViolins) * (1 - fullLayout.violingap) : 0; + var bPos = t.bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numViolins) * groupFraction : 0; + // half-width within which to accept hover for this violin + // always split the distance to the closest violin + t.wHover = t.dPos * (group ? groupFraction / numViolins : 1); if(trace.visible !== true || t.empty) { _$d3_15.select(this).remove(); @@ -74473,7 +75137,7 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup]; sel.selectAll('path.violin') - .data(_$lib_171.identity) + .data(_$lib_172.identity) .enter().append('path') .style('vector-effect', 'non-scaling-stroke') .attr('class', 'violin') @@ -74565,7 +75229,7 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { // do not draw whiskers on inner boxes trace.whiskerwidth = 0; - _$plot_291.plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, { + _$plot_292.plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, { bPos: bPos, bdPos: bdPosScaled, bPosPxOffset: bPosPxOffset @@ -74573,7 +75237,7 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { // if both box and meanline are visible, show mean line inside box if(hasMeanLine) { - _$plot_291.plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, { + _$plot_292.plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, { bPos: bPos, bdPos: bdPosScaled, bPosPxOffset: bPosPxOffset @@ -74583,7 +75247,7 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { else { if(hasMeanLine) { sel.selectAll('path.mean') - .data(_$lib_171.identity) + .data(_$lib_172.identity) .enter().append('path') .attr('class', 'mean') .style({ @@ -74592,7 +75256,7 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { }) .each(function(d) { var v = valAxis.c2p(d.mean, true); - var p = _$helpers_403.getPositionOnKdePath(d, trace, v); + var p = _$helpers_404.getPositionOnKdePath(d, trace, v); _$d3_15.select(this).attr('d', trace.orientation === 'h' ? @@ -74604,7 +75268,7 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { } if(trace.points) { - _$plot_291.plotPoints(sel, {x: xa, y: ya}, trace, t); + _$plot_292.plotPoints(sel, {x: xa, y: ya}, trace, t); } }); }; @@ -74619,16 +75283,16 @@ var _$plot_408 = function plot(gd, plotinfo, cd) { 'use strict'; -var __setPositionOffset_409 = _$set_positions_293.setPositionOffset; -var __orientations_409 = ['v', 'h']; +var __setPositionOffset_410 = _$set_positions_294.setPositionOffset; +var __orientations_410 = ['v', 'h']; -var _$setPositions_409 = function setPositions(gd, plotinfo) { +var _$setPositions_410 = function setPositions(gd, plotinfo) { var calcdata = gd.calcdata; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; - for(var i = 0; i < __orientations_409.length; i++) { - var orientation = __orientations_409[i]; + for(var i = 0; i < __orientations_410.length; i++) { + var orientation = __orientations_410[i]; var posAxis = orientation === 'h' ? ya : xa; var violinList = []; var minPad = 0; @@ -74654,7 +75318,7 @@ var _$setPositions_409 = function setPositions(gd, plotinfo) { } } - __setPositionOffset_409('violin', gd, violinList, posAxis, [minPad, maxPad]); + __setPositionOffset_410('violin', gd, violinList, posAxis, [minPad, maxPad]); } }; @@ -74670,9 +75334,9 @@ var _$setPositions_409 = function setPositions(gd, plotinfo) { /* removed: var _$d3_15 = require('d3'); */; /* removed: var _$color_51 = require('../../components/color'); */; -var __stylePoints_410 = _$style_389.stylePoints; +var __stylePoints_411 = _$style_390.stylePoints; -var _$style_410 = function style(gd, cd) { +var _$style_411 = function style(gd, cd) { var s = cd ? cd[0].node3 : _$d3_15.select(gd).selectAll('g.trace.violins'); s.style('opacity', function(d) { return d[0].trace.opacity; }); @@ -74702,7 +75366,7 @@ var _$style_410 = function style(gd, cd) { }) .call(_$color_51.stroke, meanline.color); - __stylePoints_410(sel, trace, gd); + __stylePoints_411(sel, trace, gd); }); }; @@ -74716,22 +75380,22 @@ var _$style_410 = function style(gd, cd) { 'use strict'; -var _$violin_405 = { - attributes: _$attributes_400, - layoutAttributes: _$layout_attributes_406, - supplyDefaults: _$supplyDefaults_402, - supplyLayoutDefaults: _$supplyLayoutDefaults_407, - calc: _$calc_401, - setPositions: _$setPositions_409, - plot: _$plot_408, - style: _$style_410, - hoverPoints: _$hoverPoints_404, - selectPoints: _$selectPoints_292, +var _$violin_406 = { + attributes: _$attributes_401, + layoutAttributes: _$layout_attributes_407, + supplyDefaults: _$supplyDefaults_403, + supplyLayoutDefaults: _$supplyLayoutDefaults_408, + calc: _$calc_402, + setPositions: _$setPositions_410, + plot: _$plot_409, + style: _$style_411, + hoverPoints: _$hoverPoints_405, + selectPoints: _$selectPoints_293, moduleType: 'trace', name: 'violin', - basePlotModule: _$cartesian_224, - categories: ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend'], + basePlotModule: _$cartesian_225, + categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'draggedPts', 'violinLayout'], meta: { } @@ -74747,7 +75411,7 @@ var _$violin_405 = { 'use strict'; -var _$violin_14 = _$violin_405; +var _$violin_14 = _$violin_406; /** * Copyright 2012-2018, Plotly, Inc. diff --git a/dist/plotly-cartesian.min.js b/dist/plotly-cartesian.min.js index c1a907a8540..19281de3179 100644 --- a/dist/plotly-cartesian.min.js +++ b/dist/plotly-cartesian.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (cartesian - minified) v1.35.2 +* plotly.js (cartesian - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},n=[].slice,r=function(e){return n.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{r(a.documentElement.childNodes)[0].nodeType}catch(e){r=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,d=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,n){c.call(this,e,t,n+"")},u.setProperty=function(e,t,n){d.call(this,e,t+"",n)}}function f(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}t.ascending=f,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},t.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},t.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(f);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,n){return f(e(t),n)}:e)},t.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},t.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},t.pairs=function(e){for(var t=0,n=e.length-1,r=e[0],a=new Array(n<0?0:n);t=0;)for(t=(r=e[a]).length;--t>=0;)n[--o]=r[t];return n};var m=Math.abs;function x(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n==1/0)throw new Error("infinite range");var r,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(n)),o=-1;if(e*=i,t*=i,(n*=i)<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=a.length)return n?n.call(r,i):e?i.sort(e):i;for(var s,c,u,d,f=-1,h=i.length,p=a[l++],g=new b;++f=a.length)return t;var r=[],o=i[n++];return t.forEach(function(t,a){r.push({key:t,values:e(a,n)})}),o?r.sort(function(e,t){return o(e.key,t.key)}):r}(o(t.map,e,0),0)},r.key=function(e){return a.push(e),r},r.sortKeys=function(e){return i[a.length-1]=e,r},r.sortValues=function(t){return e=t,r},r.rollup=function(e){return n=e,r},r},t.set=function(e){var t=new O;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},t.event=null,t.requote=function(e){return e.replace(q,"\\$&")};var q=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,H={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]};function V(e){return H(e,Z),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var n=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var Z=t.selection.prototype=[];function X(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}Z.select=function(e){var t,n,r,a,i=[];e=X(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),J.hasOwnProperty(n)?{space:J[n],local:e}:e}},Z.attr=function(e,n){if(arguments.length<2){if("string"==typeof e){var r=this.node();return(e=t.ns.qualify(e)).local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}for(n in e)this.each($(n,e[n]));return this}return this.each($(e,n))},Z.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=te(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},Z.sort=function(e){e=function(e){arguments.length||(e=f);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?n?function(){var t=l(n,r(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:c:n?N:function(){var n,r=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(n=a.match(r)){var i=this[a];this.removeEventListener(n[1],i,i.$),delete this[a]}}}t.selection.enter=de,t.selection.enter.prototype=fe,fe.append=Z.append,fe.empty=Z.empty,fe.node=Z.node,fe.call=Z.call,fe.size=Z.size,fe.select=function(e){for(var t,n,r,a,i,o=[],l=-1,s=this.length;++l=r&&(r=t+1);!(o=l[r])&&++r0?1:e<0?-1:0}function Pe(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function De(e){return e>1?0:e<-1?Te:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Ne(e){return((e=Math.exp(e))+1/e)/2}function Ie(e){return(e=Math.sin(e/2))*e}var Re=Math.SQRT2;t.interpolateZoom=function(e,t){var n,r,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,d=s-i,f=u*u+d*d;if(f0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-f.x)/f.k}).map(s.invert)),d&&d.domain(u.range().map(function(e){return(e-f.y)/f.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:f.k,translate:[f.x,f.y]})}function O(e){--v||(e({type:"zoomend"}),n=null)}function z(){var e=this,n=_.of(e,arguments),r=0,a=t.select(o(e)).on(m,function(){r=1,T(t.mouse(e),i),S(n)}).on(x,function(){a.on(m,null).on(x,null),l(r),O(n)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(n)}function P(){var e,n=this,r=_.of(n,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],d=t.select(n),h=xe(n);function p(){var r=t.touches(n);return e=f.k,r.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),r}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var r=t.event.changedTouches,o=0,d=r.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,d=t.touches(n);ll.call(n);for(var f=0,h=d.length;f360?e-=360:e<0&&(e+=360),e<60?r+(a-r)*e/60:e<180?a:e<240?r+(a-r)*(240-e)/60:r}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,r=2*(n=n<0?0:n>1?1:n)-(a=n<=.5?n*(1+t):n+t-n*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,n,r){return this instanceof Ge?(this.h=+e,this.c=+n,void(this.l=+r)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Xe?e.l:(e=ft((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,n,r)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new qe;function Ze(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Xe(n,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Xe(e,t,n){return this instanceof Xe?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof Xe?new Xe(e.l,e.a,e.b):e instanceof Ge?Ze(e.h,e.c,e.l):ft((e=it(e)).r,e.g,e.b):new Xe(e,t,n)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Ze(this.h,this.c,this.l).rgb()},t.lab=Xe;var We=18,Qe=.95047,Je=1,$e=1.08883,Ke=Xe.prototype=new qe;function et(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return new it(at(3.2404542*(a=nt(a)*Qe)-1.5371385*(r=nt(r)*Je)-.4985314*(i=nt(i)*$e)),at(-.969266*a+1.8760108*r+.041556*i),at(.0556434*a-.2040259*r+1.0572252*i))}function tt(e,t,n){return e>0?new Ge(Math.atan2(n,t)*Oe,Math.sqrt(t*t+n*n),e):new Ge(NaN,NaN,e)}function nt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function rt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,n){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,n)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Xe(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Xe(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new qe;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function dt(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new He(r,a,s)}function ft(e,t,n){var r=rt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(n=ht(n)))/Qe),a=rt((.2126729*e+.7151522*t+.072175*n)/Je);return Xe(116*a-16,500*(r-a),200*(a-rt((.0193339*e+.119192*t+.9503041*n)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,a=30;return t||n||r?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=d:c.onreadystatechange=function(){c.readyState>3&&d()},c.onprogress=function(e){var n=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=n}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(n=null==e?null:e+"",o):n},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),c.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=n&&c.overrideMimeType&&c.overrideMimeType(n),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==r?null:r),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(z),t.dsv=function(e,t){var n=new RegExp('["'+e+"\n]"),r=e.charCodeAt(0);function a(e,n,r){arguments.length<3&&(r=n,n=null);var a=mt(e,t,null==n?i:o(n),r);return a.row=function(e){return arguments.length?a.response(null==(n=e)?i:o(e)):n},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return n.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var n;return a.parseRows(e,function(e,r){if(n)return n(e,r-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(a(e),n)}:a})},a.parseRows=function(e,t){var n,a,i={},o={},l=[],s=e.length,c=0,u=0;function d(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(Tt,t)),_t=0):(_t=1,kt(Tt))}function At(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}});t.formatPrefix=function(e,n){var r=0;return(e=+e)&&(e<0&&(e*=-1),n&&(e=t.round(e,Ct(e,n))),r=1+Math.floor(1e-12+Math.log(e)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),St[8+r/3]};var Ot=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,zt=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,n){return(e=t.round(e,Ct(e,n))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),n))))}});function Pt(e){return e+""}var Dt=t.time={},Et=Date;function Nt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Nt.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(){It.setUTCDate.apply(this._,arguments)},setDay:function(){It.setUTCDay.apply(this._,arguments)},setFullYear:function(){It.setUTCFullYear.apply(this._,arguments)},setHours:function(){It.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){It.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){It.setUTCMinutes.apply(this._,arguments)},setMonth:function(){It.setUTCMonth.apply(this._,arguments)},setSeconds:function(){It.setUTCSeconds.apply(this._,arguments)},setTime:function(){It.setTime.apply(this._,arguments)}};var It=Date.prototype;function Rt(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o68?1900:2e3),n+a[0].length):-1}function Qt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Jt(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function $t(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Kt(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function en(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function tn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function nn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function rn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function an(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=m(t)/60|0,a=m(t)%60;return n+Ht(r,"0",2)+Ht(a,"0",2)}function on(e,t,n){qt.lastIndex=0;var r=qt.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ln(e){for(var t=e.length,n=-1;++n0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(n-=l,n+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(r)}:z;return function(e){var r=Ot.exec(e),a=r[1]||" ",l=r[2]||">",s=r[3]||"-",c=r[4]||"",u=r[5],d=+r[6],f=r[7],h=r[8],p=r[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":f=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=zt.get(p)||Pt;var b=u&&f;return function(e){var r=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),r=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=n+e.substring(k+1);!u&&f&&(_=o(_,1/0));var T=v.length+_.length+w.length+(b?0:i.length),A=T"===l?A+i+e:"^"===l?A.substring(0,T>>=1)+i+e+A.substring(T):i+(b?e:A+e))+r}}}(e),timeFormat:function(e){var n=e.dateTime,r=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function n(n){for(var r,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in Bt?t.charAt(l++):o])||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}u.utc=function(e){var t=u(e);function n(e){try{var n=new(Et=Nt);return n._=e,t(n)}finally{Et=Date}}return n.parse=function(e){try{Et=Nt;var n=t.parse(e);return n&&n._}finally{Et=Date}},n.toString=t.toString,n},u.multi=u.utc.multi=ln;var f=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){f.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(n),d:function(e,t){return Ht(e.getDate(),t,2)},e:function(e,t){return Ht(e.getDate(),t,2)},H:function(e,t){return Ht(e.getHours(),t,2)},I:function(e,t){return Ht(e.getHours()%12||12,t,2)},j:function(e,t){return Ht(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return Ht(e.getMilliseconds(),t,3)},m:function(e,t){return Ht(e.getMonth()+1,t,2)},M:function(e,t){return Ht(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return Ht(e.getSeconds(),t,2)},U:function(e,t){return Ht(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ht(Dt.mondayOfYear(e),t,2)},x:u(r),X:u(a),y:function(e,t){return Ht(e.getFullYear()%100,t,2)},Y:function(e,t){return Ht(e.getFullYear()%1e4,t,4)},Z:an,"%":function(){return"%"}},w={a:function(e,t,n){g.lastIndex=0;var r=g.exec(t.slice(n));return r?(e.w=v.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(e,t,n){h.lastIndex=0;var r=h.exec(t.slice(n));return r?(e.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.m=m.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(e,t,n){return d(e,_.c.toString(),t,n)},d:$t,e:$t,H:en,I:en,j:Kt,L:rn,m:Jt,M:tn,p:function(e,t,n){var r=f.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)},S:nn,U:Yt,w:Gt,W:Zt,x:function(e,t,n){return d(e,_.x.toString(),t,n)},X:function(e,t,n){return d(e,_.X.toString(),t,n)},y:Wt,Y:Xt,Z:Qt,"%":on};return u}(e)}};var sn=t.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"]});function cn(){}t.format=sn.numberFormat,t.geo={},cn.prototype={s:0,t:0,add:function(e){dn(e,this.t,un),dn(un.s,this.s,this),this.s?this.t+=un.t:this.s=un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var un=new cn;function dn(e,t,n){var r=n.s=e+t,a=r-e,i=r-a;n.t=e-i+(t-a)}function fn(e,t){e&&pn.hasOwnProperty(e.type)&&pn[e.type](e,t)}t.geo.stream=function(e,t){e&&hn.hasOwnProperty(e.type)?hn[e.type](e,t):fn(e,t)};var hn={Feature:function(e,t){fn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++r=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,d=r*s+u*Math.cos(l),f=u*o*Math.sin(l);Sn.add(Math.atan2(f,d)),n=e,r=s,a=c}On.point=function(o,l){On.point=i,n=(e=o)*Se,r=Math.cos(l=(t=l)*Se/2+Te/4),a=Math.sin(l)},On.lineEnd=function(){i(e,t)}}function Pn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function Dn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function En(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Nn(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function In(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Rn(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Fn(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function Bn(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(n=-90),d[0]=e,d[1]=r}};function h(t,i){u.push(d=[e=t,r=t]),ia&&(a=i)}function p(t,o){var l=Pn([t*Se,o*Se]);if(s){var c=En(s,l),u=En([c[1],-c[0],0],c);Rn(u),u=Fn(u);var d=t-i,f=d>0?1:-1,p=u[0]*Oe*f,g=m(d)>180;if(g^(f*ia&&(a=v);else if(g^(f*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t):r>=e?(tr&&(r=t)):t>i?_(e,t)>_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t)}else h(t,o);s=l,i=t}function g(){f.point=p}function v(){d[0]=e,d[1]=r,f.point=h,s=null}function y(e,t){if(s){var n=e-i;c+=m(n)>180?n+(n>0?360:-360):n}else o=e,l=t;On.point(e,t),p(e,t)}function x(){On.lineStart()}function b(){y(o,l),On.lineEnd(),m(c)>ke&&(e=-(r=180)),d[0]=e,d[1]=r,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],r=g[1])}return u=d=null,e===1/0||n===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,n],[r,a]]}}(),t.geo.centroid=function(e){mn=xn=bn=_n=wn=kn=Mn=Tn=An=Ln=Cn=0,t.geo.stream(e,jn);var n=An,r=Ln,a=Cn,i=n*n+r*r+a*a;return i=0;--l)a.point((d=u[l])[0],d[1]);else r(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Wn(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r=0?1:-1,k=w*_,M=k>Te,T=p*x;if(Sn.add(Math.atan2(T*w*Math.sin(k),g*b+T*Math.cos(k))),i+=M?_+w*Ae:_,M^f>=n^y>=n){var A=En(Pn(d),Pn(e));Rn(A);var L=En(a,A);Rn(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(r>C||r===C&&(A[0]||A[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;f=y,p=x,g=b,d=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&n.push(n.pop().concat(n.shift())),l.push(n.filter($n))}return u}}function $n(e){return e.length>1}function Kn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:N,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function er(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var tr=Jn(Zn,function(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Te:-Te,s=m(i-n);m(s-Te)0?Ce:-Ce),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Te&&(m(n-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}(n,r,i,o),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),t=0),e.point(n=i,r=o),a=l},lineEnd:function(){e.lineEnd(),n=r=NaN},clean:function(){return 2-t}}},function(e,t,n,r){var a;if(null==e)a=n*Ce,r.point(-Te,a),r.point(0,a),r.point(Te,a),r.point(Te,0),r.point(Te,-a),r.point(0,-a),r.point(-Te,-a),r.point(-Te,0),r.point(-Te,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=f,f<0){if(i0){if(i>d)return;i>u&&(u=i)}if(i=n-s,f||!(i<0)){if(i/=f,f<0){if(i>d)return;i>u&&(u=i)}else if(f>0){if(i0)){if(i/=h,h<0){if(i0){if(i>d)return;i>u&&(u=i)}if(i=r-c,h||!(i<0)){if(i/=h,h<0){if(i>d)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*f,y:c+u*h}),d<1&&(a.b={x:s+d*f,y:c+d*h}),a}}}}}}var rr=1e9;function ar(e,n,r,a){return function(s){var c,u,d,f,h,p,g,v,y,m,x,b=s,_=Kn(),w=nr(e,n,r,a),k={point:A,lineStart:function(){k.point=L,u&&u.push(d=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(f,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=A,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var n=function(e){for(var t=0,n=u.length,r=e[1],a=0;ar&&Pe(c,i,e)>0&&++t:i[1]<=r&&Pe(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),r=x&&n,i=c.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Xn(c,o,n,M,s),s.polygonEnd()),c=u=d=null}};function M(t,o,s,c){var u=0,d=0;if(null==t||(u=i(t,s))!==(d=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:r,u>1?a:n)}while((u=(u+s+4)%4)!==d);else c.point(o[0],o[1])}function T(t,i){return e<=t&&t<=r&&n<=i&&i<=a}function A(e,t){T(e,t)&&s.point(e,t)}function L(e,t){var n=T(e=Math.max(-rr,Math.min(rr,e)),t=Math.max(-rr,Math.min(rr,t)));if(u&&d.push([e,t]),m)f=e,h=t,p=n,m=!1,n&&(s.lineStart(),s.point(e,t));else if(n&&y)s.point(e,t);else{var r={a:{x:g,y:v},b:{x:e,y:t}};w(r)?(y||(s.lineStart(),s.point(r.a.x,r.a.y)),s.point(r.b.x,r.b.y),n||s.lineEnd(),x=!1):n&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=n}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-r)0?2:1:m(t[1]-n)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}}function ir(e){var t=0,n=Te/3,r=Lr(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Te/180,n=e[1]*Te/180):[t/Te*180,n/Te*180]},a}function or(e,t){var n=Math.sin(e),r=(n+Math.sin(t))/2,a=1+n*(2*r-n),i=Math.sqrt(a)/r;function o(e,t){var n=Math.sqrt(a-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),i-n*Math.cos(e)]}return o.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,Ee((a-(e*e+n*n)*r*r)/(2*r))]},o}t.geo.clipExtent=function(){var e,t,n,r,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=ar(e=+l[0][0],t=+l[0][1],n=+l[1][0],r=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return ir(or)}).raw=or,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,n,r,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,n){e=[t,n]}};function c(t){var i=t[0],o=t[1];return e=null,n(i,o),e||(r(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),n=i.translate(),r=(e[0]-n[0])/t,a=(e[1]-n[1])/t;return(a>=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],d=+e[1];return n=i.translate(e).clipExtent([[u-.455*t,d-.238*t],[u+.455*t,d+.238*t]]).stream(s).point,r=o.translate([u-.307*t,d+.201*t]).clipExtent([[u-.425*t+ke,d+.12*t+ke],[u-.214*t-ke,d+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,d+.212*t]).clipExtent([[u-.214*t+ke,d+.166*t+ke],[u-.115*t-ke,d+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var lr,sr,cr,ur,dr,fr,hr={point:N,lineStart:N,lineEnd:N,polygonStart:function(){sr=0,hr.lineStart=pr},polygonEnd:function(){hr.lineStart=hr.lineEnd=hr.point=N,lr+=m(sr/2)}};function pr(){var e,t,n,r;function a(e,t){sr+=r*e-n*t,n=e,r=t}hr.point=function(i,o){hr.point=a,e=n=i,t=r=o},hr.lineEnd=function(){a(e,t)}}var gr={point:function(e,t){edr&&(dr=e);tfr&&(fr=t)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vr(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yr,mr={point:xr,lineStart:br,lineEnd:_r,polygonStart:function(){mr.lineStart=wr},polygonEnd:function(){mr.point=xr,mr.lineStart=br,mr.lineEnd=_r}};function xr(e,t){bn+=e,_n+=t,++wn}function br(){var e,t;function n(n,r){var a=n-e,i=r-t,o=Math.sqrt(a*a+i*i);kn+=o*(e+n)/2,Mn+=o*(t+r)/2,Tn+=o,xr(e=n,t=r)}mr.point=function(r,a){mr.point=n,xr(e=r,t=a)}}function _r(){mr.point=xr}function wr(){var e,t,n,r;function a(e,t){var a=e-n,i=t-r,o=Math.sqrt(a*a+i*i);kn+=o*(n+e)/2,Mn+=o*(r+t)/2,Tn+=o,An+=(o=r*e-n*t)*(n+e),Ln+=o*(r+t),Cn+=3*o,xr(n=e,r=t)}mr.point=function(i,o){mr.point=a,xr(e=n=i,t=r=o)},mr.lineEnd=function(){a(e,t)}}function kr(e){var t=.5,n=Math.cos(30*Se),r=16;function a(t){return(r?function(t){var n,a,o,l,s,c,u,d,f,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(n,r){n=e(n,r),t.point(n[0],n[1])}function m(){d=NaN,v.point=x,t.lineStart()}function x(n,a){var o=Pn([n,a]),l=e(n,a);i(d,f,u,h,p,g,d=l[0],f=l[1],u=n,h=o[0],p=o[1],g=o[2],r,t),t.point(d,f)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(n=e,t),a=d,o=f,l=h,s=p,c=g,v.point=x}function k(){i(d,f,u,h,p,g,a,o,n,l,s,c,r,t),v.lineEnd=b,b()}return v}:function(t){return Tr(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})})(t)}function i(r,a,o,l,s,c,u,d,f,h,p,g,v,y){var x=u-r,b=d-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,T=Math.sqrt(w*w+k*k+M*M),A=Math.asin(M/=T),L=m(m(M)-1)t||m((x*z+b*P)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mr(e){this.stream=e}function Tr(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Ar(e){return Lr(function(){return e})()}function Lr(e){var n,r,a,i,o,l,s=kr(function(e,t){return[(e=n(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,d=250,f=0,h=0,p=0,g=0,v=0,y=tr,x=z,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Oe,e[1]*Oe]}function M(){a=Yn(r=zr(p,g,v),n);var e=n(f,h);return i=u-e[0]*c,o=d+e[1]*c,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cr(y(r,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,tr):function(e){var t=Math.cos(e),n=t>0,r=m(t)>ke;return Jn(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(d,f){var h,p=[d,f],g=a(d,f),v=n?g?0:o(d,f):g?o(d+(d<0?Te:-Te),f):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(Bn(t,h)||Bn(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(r&&t&&n^g){var y;v&l||!(y=i(p,t,!0))||(u=0,n?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&Bn(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Nr(e,6*Se),n?[0,-e]:[-Te,e-Te]);function a(e,n){return Math.cos(e)*Math.cos(n)>t}function i(e,n,r){var a=[1,0,0],i=En(Pn(e),Pn(n)),o=Dn(i,i),l=i[0],s=o-l*l;if(!s)return!r&&e;var c=t*o/s,u=-t*l/s,d=En(a,i),f=In(a,c);Nn(f,In(i,u));var h=d,p=Dn(f,h),g=Dn(h,h),v=p*p-g*(Dn(f,f)-1);if(!(v<0)){var y=Math.sqrt(v),x=In(h,(-p-y)/g);if(Nn(x,f),x=Fn(x),!r)return x;var b,_=e[0],w=n[0],k=e[1],M=n[1];w<_&&(b=_,_=w,w=b);var T=w-_,A=m(T-Te)0^x[1]<(m(x[0]-_)Te^(_<=x[0]&&x[0]<=w)){var L=In(h,(-p+y)/g);return Nn(L,f),[x,Fn(L)]}}}function o(t,r){var a=n?e:Te-e,i=0;return t<-a?i|=1:t>a&&(i|=2),r<-a?i|=4:r>a&&(i|=8),i}}((b=+e)*Se),T()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?ar(e[0][0],e[0][1],e[1][0],e[1][1]):z,T()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],d=+e[1],M()):[u,d]},w.center=function(e){return arguments.length?(f=e[0]%360*Se,h=e[1]%360*Se,M()):[f*Oe,h*Oe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*Oe,g*Oe,v*Oe]},t.rebind(w,s,"precision"),function(){return n=e.apply(this,arguments),w.invert=n.invert&&k,M()}}function Cr(e){return Tr(e,function(t,n){e.point(t*Se,n*Se)})}function Sr(e,t){return[e,t]}function Or(e,t){return[e>Te?e-Ae:e<-Te?e+Ae:e,t]}function zr(e,t,n){return e?t||n?Yn(Dr(e),Er(t,n)):Dr(e):t||n?Er(t,n):Or}function Pr(e){return function(t,n){return[(t+=e)>Te?t-Ae:t<-Te?t+Ae:t,n]}}function Dr(e){var t=Pr(e);return t.invert=Pr(-e),t}function Er(e,t){var n=Math.cos(e),r=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*n+l*r;return[Math.atan2(s*a-u*i,l*n-c*r),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*n+u*r),Ee(u*n-l*r)]},o}function Nr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=Ir(n,a),i=Ir(n,i),(o>0?ai)&&(a+=o*Ae)):(a=e+o*Ae,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=Oe,t[1]*=Oe,t},t},Or.invert=Sr,t.geo.circle=function(){var e,t,n=[0,0],r=6;function a(){var e="function"==typeof n?n.apply(this,arguments):n,r=zr(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=r(e,t)),e[0]*=Oe,e[1]*=Oe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(n=e,a):n},a.angle=function(n){return arguments.length?(t=Nr((e=+n)*Se,r*Se),a):e},a.precision=function(n){return arguments.length?(t=Nr(e*Se,(r=+n)*Se),a):r},a.angle(90)},t.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),d=Math.cos(i);return Math.atan2(Math.sqrt((n=d*o)*n+(n=c*u-s*d*l)*n),s*u+c*d*l)},t.geo.graticule=function(){var e,n,r,a,i,o,l,s,c,u,d,f,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,r,g).map(d).concat(t.range(Math.ceil(s/v)*v,l,v).map(f)).concat(t.range(Math.ceil(n/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[d(a).concat(f(l).slice(1),d(r).reverse().slice(1),f(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],r=+e[1][0],s=+e[0][1],l=+e[1][1],a>r&&(e=a,a=r,r=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[r,l]]},x.minorExtent=function(t){return arguments.length?(n=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],n>e&&(t=n,n=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[n,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Rr(o,i,90),u=Fr(n,e,y),d=Rr(s,l,90),f=Fr(a,r,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,n,r=Br,a=jr;function i(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||r.apply(this,arguments),n||a.apply(this,arguments))},i.source=function(t){return arguments.length?(r=t,e="function"==typeof t?null:t,i):r},i.target=function(e){return arguments.length?(a=e,n="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return n=e[0]*Se,r=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(r),l=Math.sin(r),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(n),d=o*Math.sin(n),f=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ie(i-r)+o*s*Ie(a-n))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,n=Math.sin(p-e)*g,r=n*u+t*f,a=n*d+t*h,i=n*l+t*c;return[Math.atan2(a,r)*Oe,Math.atan2(i,Math.sqrt(r*r+a*a))*Oe]}:function(){return[n*Oe,r*Oe]}).distance=p,v;var n,r,a,i,o,l,s,c,u,d,f,h,p,g,v},t.geo.length=function(e){return yr=0,t.geo.stream(e,qr),yr};var qr={sphere:N,point:N,lineStart:function(){var e,t,n;function r(r,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((r*=Se)-e),s=Math.cos(l);yr+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=n*i-t*o*s)*l),t*i+n*o*s),e=r,t=i,n=o}qr.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),n=Math.cos(i),qr.point=r},qr.lineEnd=function(){qr.point=qr.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function Hr(e,t){function n(t,n){var r=Math.cos(t),a=Math.cos(n),i=e(r*a);return[i*a*Math.sin(t),i*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),a=t(r),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,r*o),Math.asin(r&&n*i/r)]},n}var Vr=Hr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Ar(Vr)}).raw=Vr;var Ur=Hr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},z);function Gr(e,t){var n=Math.cos(e),r=function(e){return Math.tan(Te/4+e/2)},a=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),i=n*Math.pow(r(e),a)/a;if(!a)return Xr;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var n=i/Math.pow(r(t),a);return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}return o.invert=function(e,t){var n=i-t,r=ze(a)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/a,2*Math.atan(Math.pow(i/r,1/a))-Ce]},o}function Yr(e,t){var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),a=n/r+e;if(m(r)1&&Pe(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function na(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Ar(Jr)}).raw=Jr,$r.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wr($r),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):[(e=n())[0],e[1],e[2]-90]},n([0,0,90])}).raw=$r,t.geom={},t.geom.hull=function(e){var t=Kr,n=ea;if(arguments.length)return r(e);function r(e){if(e.length<3)return[];var r,a=vt(t),i=vt(n),o=e.length,l=[],s=[];for(r=0;r=0;--r)h.push(e[l[c[r]][2]]);for(r=+d;rke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){r>-ke?(t=l.P,n=l):a>-ke?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||n){if(t===n)return ka(t),n=pa(t.site),ca.insert(s,n),s.edge=n.edge=Aa(t.site,s.site),wa(t),void wa(n);if(n){ka(t),ka(n);var c=t.site,u=c.x,d=c.y,f=e.x-u,h=e.y-d,p=n.site,g=p.x-u,v=p.y-d,y=2*(f*v-h*g),m=f*f+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(f*x-g*m)/y+d};La(n.edge,c,p,b),s.edge=Aa(c,e,null,b),n.edge=Aa(e,p,null,b),wa(t),wa(n)}else s.edge=Aa(t.site,s.site)}}function ma(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-1/0;var l=(n=o.site).x,s=n.y,c=s-t;if(!c)return l;var u=l-r,d=1/i-1/c,f=u/c;return d?(-f+Math.sqrt(f*f-2*d*(u*u/(-2*c)-s+c/2+a-i/2)))/d+r:(r+l)/2}function xa(e,t){var n=e.N;if(n)return ma(n,t);var r=e.site;return r.y===t?r.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,a=e.site,i=n.site;if(r!==i){var o=a.x,l=a.y,s=r.x-o,c=r.y-l,u=i.x-o,d=2*(s*(v=i.y-l)-c*u);if(!(d>=-Me)){var f=s*s+c*c,h=u*u+v*v,p=(v*f-c*h)/d,g=(s*h-u*f)/d,v=g+l,y=ha.pop()||new function(){Oa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=da._;x;)if(y.y=l)return;if(f>p){if(i){if(i.y>=c)return}else i={x:v,y:s};n={x:v,y:c}}else{if(i){if(i.y1)if(f>p){if(i){if(i.y>=c)return}else i={x:(s-a)/r,y:s};n={x:(c-a)/r,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xke||m(a-n)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(r-d)ke?{x:d,y:m(t-d)ke?{x:m(n-p)ke?{x:f,y:m(t-f)ke?{x:m(n-h)=n&&c.x<=a&&c.y>=r&&c.y<=o?[[n,o],[a,o],[a,r],[n,r]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(n,r){for(var a,i,o,l,s=n.site,c=n.edges.sort(_a),u=-1,d=c.length,f=c[d-1].edge,h=f.l===s?f.r:f.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:qa(n,r)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(d=0;dg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,n,r,a,i,o,l){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-n)+m(c-r)<.01)T(e,t,n,r,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,T(e,u,s,c,a,i,o,l),T(e,t,n,r,a,i,o,l)}else e.x=n,e.y=r,e.point=t}else T(e,t,n,r,a,i,o,l)}function T(e,t,n,r,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=n>=s,d=r>=c,f=d<<1|u;e.leaf=!1,e=e.nodes[f]||(e.nodes[f]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++d),+x(e,d),h,p,g,v)}}),u?a=s:o=s,d?i=c:l=c,M(e,t,n,r,a,i,o,l)}w>k?v=p+w:g=h+k;var A={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++d),+x(e,d),h,p,g,v)}};if(A.visit=function(e){!function e(t,n,r,a,i,o){if(!t(n,r,a,i,o)){var l=.5*(r+i),s=.5*(a+o),c=n.nodes;c[0]&&e(t,c[0],r,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],r,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,A,h,p,g,v)},A.find=function(e){return function(e,t,n,r,a,i,o){var l,s=1/0;return function e(c,u,d,f,h){if(!(u>i||d>o||f=_)<<1|t>=b,k=w+4;w=0&&!(r=t.interpolators[a](e,n)););return r}function Ya(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ni(e){return Math.pow(2,10*(e-1))}function ri(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function oi(e){var t,n,r,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(r=-l)*(n=a)[0],t[1]+=r*n[1],t))||0;a[0]*i[1]=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"in";return a=Xa.get(a)||Za,i=Wa.get(i)||z,t=i(a.apply(null,n.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,n){e=t.hcl(e),n=t.hcl(n);var r=e.h,a=e.c,i=e.l,o=n.h-r,l=n.c-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.c:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ze(r+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,n){e=t.hsl(e),n=t.hsl(n);var r=e.h,a=e.s,i=e.l,o=n.h-r,l=n.s-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.s:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(r+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,n){e=t.lab(e),n=t.lab(n);var r=e.l,a=e.a,i=e.b,o=n.l-r,l=n.a-a,s=n.b-i;return function(e){return et(r+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var n=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function di(e,n){var r=[],a=[];return e=t.transform(e),n=t.transform(n),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push("translate(",null,",",null,")");r.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else(t[0]||t[1])&&n.push("translate("+t+")")}(e.translate,n.translate,r,a),function(e,t,n,r){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(ui(n)+"rotate(",null,")")-2,x:qa(e,t)})):t&&n.push(ui(n)+"rotate("+t+")")}(e.rotate,n.rotate,r,a),function(e,t,n,r){e!==t?r.push({i:n.push(ui(n)+"skewX(",null,")")-2,x:qa(e,t)}):t&&n.push(ui(n)+"skewX("+t+")")}(e.skew,n.skew,r,a),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(ui(n)+"scale(",null,",",null,")");r.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(ui(n)+"scale("+t+")")}(e.scale,n.scale,r,a),e=n=null,function(e){for(var t,n=-1,i=a.length;++n0?r=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:r=0})):t>0&&(s.start({type:"start",alpha:r=t}),e=Mt(l.tick)),l):r},l.start=function(){var e,t,n,r=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)n.push(a[r])}function Ti(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;n&&(i.value=0),i.children=c}else n&&(i.value=+n.call(r,i,i.depth)||0),delete i.children;return Ti(a,function(t){var r,a;e&&(r=t.children)&&r.sort(e),n&&(a=t.parent)&&(a.value+=t.value)}),l}return r.sort=function(t){return arguments.length?(e=t,r):e},r.children=function(e){return arguments.length?(t=e,r):t},r.value=function(e){return arguments.length?(n=e,r):n},r.revalue=function(e){return n&&(Mi(e,function(e){e.children&&(e.value=0)}),Ti(e,function(e){var t;e.children||(e.value=+n.call(r,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},r},t.layout.partition=function(){var e=t.layout.hierarchy(),n=[1,1];function r(t,r){var a=e.call(this,t,r);return function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(r=t.value?r/t.value:0;++cl&&(l=r),o.push(r)}for(n=0;na&&(r=n,a=t);return r}function Bi(e){return e.reduce(ji,0)}function ji(e,t){return e+t[1]}function qi(e,t){return Hi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Hi(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Zi(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function Xi(e){if((t=e.children)&&(s=t.length)){var t,n,r,a,i,o,l,s,c=1/0,u=-1/0,d=1/0,f=-1/0;if(t.forEach(Wi),(n=t[0]).x=-n.r,n.y=0,x(n),s>1&&((r=t[1]).x=r.r,r.y=0,x(r),s>2))for(Ji(n,r,a=t[2]),x(a),Gi(n,a),n._pack_prev=a,Gi(a,r),r=n._pack_next,i=3;i0)for(o=-1;++o=d[0]&&s<=d[1]&&((l=c[t.bisect(f,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(n=e,i):n},i.range=function(e){return arguments.length?(r=vt(e),i):r},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return Hi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,n=t.layout.hierarchy().sort(Ui),r=0,a=[1,1];function i(t,i){var o=n.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ti(l,function(e){e.r=+u(e.value)}),Ti(l,Xi),r){var d=r*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ti(l,function(e){e.r+=d}),Ti(l,Xi),Ti(l,function(e){e.r-=d})}return function e(t,n,r,a){var i=t.children;t.x=n+=a*t.x;t.y=r+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=n(f,h)/2-f.x,v=r[0]/(h.x+n(h,f)/2+g),y=r[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,r=e.parent.children,a=e.i?r[e.i-1]:null;if(t.length){!function(e){var t,n=0,r=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=n,t.m+=n,n+=t.s+(r+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+n(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+n(e._,a._));e.parent.A=function(e,t,r){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,d=l.m,f=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+d-i.z-c+n(l._,i._))>0&&(to(no(l,e,r),e,a),c+=a,u+=a),d+=l.m,c+=i.m,f+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=d-u),i&&!Ki(s)&&(s.t=i,s.m+=c-f,r=e)}return r}(e,a,e.parent.A||r[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=r[0],e.y=e.depth*r[1]}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e)?s:null,i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null==(r=e)?null:s,i):a?r:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),n=$i,r=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ti(c,function(e){var r=e.children;r&&r.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(r),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(r)):(e.x=l?u+=n(e,l):0,e.y=0,l=e)});var d=function e(t){var n=t.children;return n&&n.length?e(n[0]):t}(c),f=function e(t){var n,r=t.children;return r&&(n=r.length)?e(r[n-1]):t}(c),h=d.x-n(d,f)/2,p=f.x+n(f,d)/2;return Ti(c,a?function(e){e.x=(e.x-c.x)*r[0],e.y=(c.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(c.y?e.y/c.y:1))*r[1]}),s}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e),i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null!=(r=e),i):a?r:null},ki(i,e)},t.layout.treemap=function(){var e,n=t.layout.hierarchy(),r=Math.round,a=[1,1],i=null,o=ro,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var n,r,a=-1,i=e.length;++a0;)l.push(n=c[a-1]),l.area+=n.area,"squarify"!==s||(r=h(l,g))<=f?(c.pop(),f=r):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,f=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(d)}}function f(e){var t=e.children;if(t&&t.length){var n,r=o(e),a=t.slice(),i=[];for(u(a,r.dx*r.dy/e.value),i.area=0;n=a.pop();)i.push(n),i.area+=n.area,null!=n.z&&(p(i,n.z?r.dx:r.dy,r,!a.length),i.length=i.area=0);t.forEach(f)}}function h(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return t*=t,(r*=r)?Math.max(t*a*c/r,r/(t*i*c)):1/0}function p(e,t,n,a){var i,o=-1,l=e.length,s=n.x,c=n.y,u=t?r(e.area/t):0;if(t==n.dx){for((a||u>n.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++o1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var n=t.random.irwinHall(e);return function(){return n()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;n2?fo:lo,l=a?hi:fi;return i=e(t,n,l,r),o=e(n,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(n=e,l()):n};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(r=e,l()):r};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,n){return yo(t,e,n)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,n,r,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(n,r,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(r)}function l(e){return a?Math.pow(r,e):-Math.pow(r,-e)}function s(e){return n(o(e))}s.invert=function(e){return l(n.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,n.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(r=+e,n.domain(i.map(o)),s):r};s.nice=function(){var e=so(i.map(o),a?Math:_o);return n.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],n=e[0],s=e[1],c=Math.floor(o(n)),u=Math.ceil(o(s)),d=r%1?2:r;if(isFinite(u-c)){if(a){for(;c0;f--)t.push(l(c)*f);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,n){if(!arguments.length)return bo;arguments.length<2?n=bo:"function"!=typeof n&&(n=t.format(n));var a=Math.max(1,r*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*r0?a[e-1]:n[0],ed?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,T,A=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=r===Co?Math.sqrt(l*l+c*c):+r.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(A=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(d-L),_=c*Math.sin(d-L);var S=Math.abs(d-u-2*L)<=Te?0:1;if(L&&Eo(m,x,b,_)===h^S){var O=(u+d)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(d-A),k=l*Math.sin(d-A),M=l*Math.cos(u+A),T=l*Math.sin(u+A);var z=Math.abs(u-d+2*A)<=Te?0:1;if(A&&Eo(w,k,M,T)===1-h^z){var P=(u+d)/2;w=l*Math.cos(P),k=l*Math.sin(P),M=T=null}}else w=k=0;if(f>ke&&(p=Math.min(Math.abs(c-l)/2,+n.apply(this,arguments)))>.001){g=l0?0:1}function No(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,d=e[1]+c,f=t[0]+s,h=t[1]+c,p=(u+f)/2,g=(d+h)/2,v=f-u,y=h-d,m=v*v+y*y,x=n-r,b=u*h-f*d,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,T=(-b*v+y*_)/m,A=w-p,L=k-g,C=M-p,S=T-g;return A*A+L*L>C*C+S*S&&(w=M,k=T),[[w-s,k-c],[w*n/x,k*n/x]]}function Io(e){var t=Kr,n=ea,r=Zn,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,d=i.length,f=vt(t),h=vt(n);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",r[0]);return a.join("")},"step-before":jo,"step-after":qo,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,n=[],r=-1,a=e.length,i=[0],o=[0];for(;++r<3;)t=e[r],i.push(t[0]),o.push(t[1]);n.push(Go(Xo,i)+","+Go(Xo,o)),--r;for(;++r9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function Bo(e){return e.join("L")+"Z"}function jo(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cTe)+",1 "+t}function s(e,t,n,r){return"Q 0,0 "+r}return i.radius=function(e){return arguments.length?(n=vt(e),i):n},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(r=vt(e),i):r},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=Br,t=jr,n=el;function r(r,a){var i=e.call(this,r,a),o=t.call(this,r,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(n))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return r.source=function(t){return arguments.length?(e=vt(t),r):e},r.target=function(e){return arguments.length?(t=vt(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),n=el,r=e.projection;return e.projection=function(e){return arguments.length?r(function(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Ce;return[n*Math.cos(r),n*Math.sin(r)]}}(n=e)):n},e},t.svg.symbol=function(){var e=nl,t=tl;function n(n,r){return(al.get(e.call(this,n,r))||rl)(t.call(this,n,r))}return n.type=function(t){return arguments.length?(e=vt(t),n):e},n.size=function(e){return arguments.length?(t=vt(e),n):t},n};var al=t.map({circle:rl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),n=t*ol;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);Z.transition=function(e){for(var t,n,r=ul||++hl,a=vl(e),i=[],o=dl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--f].call(e,o);if(i>=1)return d.event&&d.event.end.call(e,e.__data__,t),--u.count?delete u[r]:delete e[n],1}d||(i=a.time,o=Mt(function(e){var t=d.delay;if(o.t=t+i,t<=e)return f(e-t);o.c=f},0,i),d=u[r]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}fl.call=Z.call,fl.empty=Z.empty,fl.node=Z.node,fl.size=Z.size,t.transition=function(e,n){return e&&e.transition?ul?e.transition(n):e:t.selection().transition(e)},t.transition.prototype=fl,fl.select=function(e){var t,n,r,a=this.id,i=this.namespace,o=[];e=X(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var d,v,y=this,m=t.select(t.event.target),x=r.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),T=xe(y),A=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(d=null,A[0]-=l[1],A[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(A[0]+=l[1],A[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",P):L.on("mousemove.brush",O).on("mouseup.brush",P),b.interrupt().selectAll("*").interrupt(),M)A[0]=l[0]-A[0],A[1]=s[0]-A[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-A[0],s[1-S]-A[1]],A[0]=l[C],A[1]=s[S]}else t.event.altKey&&(d=A.slice());function O(){var e=t.mouse(y),n=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(d||(d=[(l[0]+l[1])/2,(s[0]+s[1])/2]),A[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var n=io(a.domain()),r=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],Sl(+n[1]+1),t<1?1:t)},a.tickFormat=function(){return r},a.copy=function(){return Cl(e.copy(),n,r)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Al,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Al.toString,Dt.second=Rt(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=Rt(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=Rt(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=Rt(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],zl=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],Pl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Zn]]),Dl={range:function(e,n,r){return t.range(Math.ceil(e/r)*r,+n,r).map(Sl)},floor:z,ceil:z};zl.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),zl,Pl)};var El=zl.map(function(e){return[e[0].utc,e[1]]}),Nl=Tl.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Zn]]);function Il(e){return JSON.parse(e.responseText)}function Rl(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Nl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Il,t)},t.html=function(e,t){return mt(e,"text/html",Rl,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t={};t.xmlns="http://www.w3.org/2000/xmlns/",t.svg="http://www.w3.org/2000/svg",t.xlink="http://www.w3.org/1999/xlink",t.svgAttrs={xmlns:t.svg,"xmlns:xlink":t.xlink};var n=function(e){var t=typeof e;if("string"===t){var n=e;if(0===(e=+e)&&function(e){for(var t,n=e.length,r=0;r13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(n))return!1}else if("number"!==t)return!1;return e-e<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},a={},i=Math.PI;a.deg2rad=function(e){return e/180*i},a.rad2deg=function(e){return e/i*180},a.wrap360=function(e){var t=e%360;return t<0?t+360:t},a.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var o=r.BADNUM,l=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(e){var t=/^\s+/,n=/\s+$/,r=0,a=e.round,i=e.min,o=e.max,l=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(r){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,d=!1,f=!1;"string"==typeof r&&(r=function(e){e=e.replace(t,"").replace(n,"").toLowerCase();var r,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(r=j.rgb.exec(e))return{r:r[1],g:r[2],b:r[3]};if(r=j.rgba.exec(e))return{r:r[1],g:r[2],b:r[3],a:r[4]};if(r=j.hsl.exec(e))return{h:r[1],s:r[2],l:r[3]};if(r=j.hsla.exec(e))return{h:r[1],s:r[2],l:r[3],a:r[4]};if(r=j.hsv.exec(e))return{h:r[1],s:r[2],v:r[3]};if(r=j.hsva.exec(e))return{h:r[1],s:r[2],v:r[3],a:r[4]};if(r=j.hex8.exec(e))return{r:P(r[1]),g:P(r[2]),b:P(r[3]),a:I(r[4]),format:a?"name":"hex8"};if(r=j.hex6.exec(e))return{r:P(r[1]),g:P(r[2]),b:P(r[3]),format:a?"name":"hex"};if(r=j.hex4.exec(e))return{r:P(r[1]+""+r[1]),g:P(r[2]+""+r[2]),b:P(r[3]+""+r[3]),a:I(r[4]+""+r[4]),format:a?"name":"hex8"};if(r=j.hex3.exec(e))return{r:P(r[1]+""+r[1]),g:P(r[2]+""+r[2]),b:P(r[3]+""+r[3]),format:a?"name":"hex"};return!1}(r));"object"==typeof r&&(q(r.r)&&q(r.g)&&q(r.b)?(h=r.r,p=r.g,g=r.b,a={r:255*O(h,255),g:255*O(p,255),b:255*O(g,255)},d=!0,f="%"===String(r.r).substr(-1)?"prgb":"rgb"):q(r.h)&&q(r.s)&&q(r.v)?(s=E(r.s),c=E(r.v),a=function(t,n,r){t=6*O(t,360),n=O(n,100),r=O(r,100);var a=e.floor(t),i=t-a,o=r*(1-n),l=r*(1-i*n),s=r*(1-(1-i)*n),c=a%6;return{r:255*[r,l,o,o,s,r][c],g:255*[s,r,r,l,o,o][c],b:255*[o,o,s,r,r,l][c]}}(r.h,s,c),d=!0,f="hsv"):q(r.h)&&q(r.s)&&q(r.l)&&(s=E(r.s),u=E(r.l),a=function(e,t,n){var r,a,i;function o(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=O(e,360),t=O(t,100),n=O(n,100),0===t)r=a=i=n;else{var l=n<.5?n*(1+t):n+t-n*t,s=2*n-l;r=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*r,g:255*a,b:255*i}}(r.h,s,u),d=!0,f="hsl"),r.hasOwnProperty("a")&&(l=r.a));var h,p,g;return l=S(l),{ok:d,format:r.format||f,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=r++}function u(e,t,n){e=O(e,255),t=O(t,255),n=O(n,255);var r,a,l=o(e,t,n),s=i(e,t,n),c=(l+s)/2;if(l==s)r=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:r=(t-n)/u+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,i.push(c(r));return i}function A(e,t){t=t||6;for(var n=c(e).toHsv(),r=n.h,a=n.s,i=n.v,o=[],l=1/t;t--;)o.push(c({h:r,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,n,r,a=this.toRgb();return t=a.r/255,n=a.g/255,r=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=d(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=d(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return f(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(n).toString(16)),D(N(r))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*O(this._r,255))+"%",g:a(100*O(this._g,255))+"%",b:a(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%)":"rgba("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[f(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);n="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:E(e[r]));e=n}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(e,t,n){n=0===n?0:n||50;var r=c(e).toRgb(),a=c(t).toRgb(),i=n/100;return c({r:(a.r-r.r)*i+r.r,g:(a.g-r.g)*i+r.g,b:(a.b-r.b)*i+r.b,a:(a.a-r.a)*i+r.a})},c.readability=function(t,n){var r=c(t),a=c(n);return(e.max(r.getLuminance(),a.getLuminance())+.05)/(e.min(r.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,n){var r,a,i=c.readability(e,t);switch(a=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,n){var r,a,i,o,l=null,s=0;a=(n=n||{}).includeFallbackColors,i=n.level,o=n.size;for(var u=0;us&&(s=r,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(n.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],n))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function O(t,n){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var r=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(n,o(0,parseFloat(t))),r&&(t=parseInt(t*n,10)/100),e.abs(t-n)<1e-6?1:t%n/parseFloat(n)}function z(e){return i(1,o(0,e))}function P(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function N(t){return e.round(255*parseFloat(t)).toString(16)}function I(e){return P(e)/255}var R,F,B,j=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",B="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+B),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+B),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+B),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})$/});function q(e){return!!j.CSS_UNIT.exec(e)}s.exports?s.exports=c:window.tinycolor=c}(Math),s=s.exports;var c={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=c.RdBu,d=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var n=0;n1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(r=e[t][0],a=e[t][1],o=!1,Y(r))for(n=r.length-1;n>=0;n--)Q(r[n],$(a,n))?o?r[n]=void 0:r.pop():o=!0;else if("object"==typeof r&&null!==r)for(i=Object.keys(r),o=!1,n=i.length-1;n>=0;n--)Q(r[i[n]],$(a,i[n]))?delete r[i[n]]:o=!0;if(o)return}}(s)):o[t[i]]=r}}function $(e,t){var r=t;return n(t)?r="["+t+"]":e&&(r="."+t),e+r}function K(e,t,n,r){var a,i=Y(n),o=!0,l=n,s=r.replace("-1",0),c=!i&&Q(n,s),u=t[0];for(a=0;aa.max?t.set(r):t.set(+e)}},integer:{coerceFunction:function(e,t,r,a){e%1||!n(e)||void 0!==a.min&&ea.max?t.set(r):t.set(+e)}},string:{coerceFunction:function(e,t,n,r){if("string"!=typeof e){var a="number"==typeof e;!0!==r.strict&&a?t.set(String(e)):t.set(n)}else r.noBlank&&!e?t.set(n):t.set(e)}},color:{coerceFunction:function(e,t,n){s(e).isValid()?t.set(e):t.set(n)}},colorlist:{coerceFunction:function(e,t,n){Array.isArray(e)&&e.length&&e.every(function(e){return s(e).isValid()})?t.set(e):t.set(n)}},colorscale:{coerceFunction:function(e,t,n){t.set(f(e,n))}},angle:{coerceFunction:function(e,t,r){"auto"===e?t.set("auto"):n(e)?t.set(ie(+e)):t.set(r)}},subplotid:{coerceFunction:function(e,t,n){"string"==typeof e&&re(n).test(e)?t.set(e):t.set(n)},validateFunction:function(e,t){var n=t.dflt;return e===n||"string"==typeof e&&!!re(n).test(e)}},flaglist:{coerceFunction:function(e,t,n,r){if("string"==typeof e)if(-1===(r.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=le&&e<=se?e:de;if("string"!=typeof e&&"number"!=typeof e)return de;e=String(e);var n=_e(t),r=e.charAt(0);!n||"G"!==r&&"g"!==r||(e=e.substr(1),t="");var a=n&&"chinese"===t.substr(0,7),i=e.match(a?xe:me);if(!i)return de;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),d=Number(i[11]||0);if(n){if(2===o.length)return de;var f;o=Number(o);try{var h=D.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),f=h.newDate(o,h.toMonthIndex(o,l,p),s)}else f=h.newDate(o,Number(l),s)}catch(e){return de}return f?(f.toJD()-ve)*fe+c*he+u*pe+d*ge:de}o=2===o.length?(Number(o)+2e3-be)%100+be:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?de:g.getUTCDate()!==s?de:g.getTime()+d*ge},le=ue.MIN_MS=ue.dateTime2ms("-9999"),se=ue.MAX_MS=ue.dateTime2ms("9999-12-31 23:59:59.9999"),ue.isDateTime=function(e,t){return ue.dateTime2ms(e,t)!==de};var ke=90*fe,Me=3*he,Te=5*pe;function Ae(e,t,n,r,a){if((t||n||r||a)&&(e+=" "+we(t,2)+":"+we(n,2),(r||a)&&(e+=":"+we(r,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+we(a,i)}return e}ue.ms2DateTime=function(e,t,n){if("number"!=typeof e||!(e>=le&&e<=se))return de;t||(t=0);var r,a,i,o,l,s,c=Math.floor(10*ce(e+.05,1)),u=Math.round(e-c/10);if(_e(n)){var d=Math.floor(u/fe)+ve,f=Math.floor(ce(e,fe));try{r=D.getComponentMethod("calendars","getCal")(n).fromJD(d).formatDate("yyyy-mm-dd")}catch(e){r=ye("G%Y-%m-%d")(new Date(u))}if("-"===r.charAt(0))for(;r.length<11;)r="-0"+r.substr(1);else for(;r.length<10;)r="0"+r;a=t=le+fe&&t<=se-fe))return de;var n=Math.floor(10*ce(t+.05,1)),r=new Date(Math.round(t-n/10));return Ae(e.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+n)},ue.cleanDate=function(e,t,n){if(ue.isJSDate(e)||"number"==typeof e){if(_e(n))return w.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ue.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ue.isDateTime(e,n))return w.error("unrecognized date",e),t;return e};var Le=/%\d?f/g;function Ce(e,t,n,r){e=e.replace(Le,function(e){var n=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(n).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(_e(r))try{e=D.getComponentMethod("calendars","worldCalFmt")(e,t,r)}catch(e){return"Invalid"}return n(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ue.formatDate=function(e,t,r,a,i,o){if(i=_e(i)&&i,!t)if("y"===r)t=o.year;else if("m"===r)t=o.month;else{if("d"!==r)return function(e,t){var r=ce(e+.05,fe),a=we(Math.floor(r/he),2)+":"+we(ce(Math.floor(r/pe),60),2);if("M"!==t){n(t)||(t=0);var i=(100+Math.min(ce(e/ge,60),Se[t])).toFixed(t).substr(1);t>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,r)+"\n"+Ce(o.dayMonthYear,e,a,i);t=o.dayMonth+"\n"+o.year}return Ce(t,e,a,i)};var Oe=3*fe;ue.incrementMonth=function(e,t,n){n=_e(n)&&n;var r=ce(e,fe);if(e=Math.round(e-r),n)try{var a=Math.round(e/fe)+ve,i=D.getComponentMethod("calendars","getCal")(n),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ve)*fe+r}catch(t){w.error("invalid ms "+e+" in calendar "+n)}var l=new Date(e+Oe);return l.setUTCMonth(l.getUTCMonth()+t)+r-Oe},ue.findExactDates=function(e,t){for(var r,a,i=0,o=0,l=0,s=0,c=_e(t)&&D.getComponentMethod("calendars","getCal")(t),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+d*g}}function Fe(e,t,n,r,a){var i=r*e+a*t;if(i<0)return r*r+a*a;if(i>n){var o=r-e,l=a-t;return o*o+l*l}var s=r*t-a*e;return s*s/n}Ie.segmentsIntersect=Re,Ie.segmentDistance=function(e,t,n,r,a,i,o,l){if(Re(e,t,n,r,a,i,o,l))return 0;var s=n-e,c=r-t,u=o-a,d=l-i,f=s*s+c*c,h=u*u+d*d,p=Math.min(Fe(s,c,f,a-e,i-t),Fe(s,c,f,o-e,l-t),Fe(u,d,h,e-a,t-i),Fe(u,d,h,n-a,r-i));return Math.sqrt(p)},Ie.getTextLocation=function(e,t,n,r){if(e===Ee&&r===Ne||(De={},Ee=e,Ne=r),De[n])return De[n];var a=e.getPointAtLength(ce(n-r/2,t)),i=e.getPointAtLength(ce(n+r/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(ce(n,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return De[n]=s,s},Ie.clearLocationCache=function(){Ee=null},Ie.getVisibleSegment=function(e,t,n){var r,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),d=u;function f(t){var n=e.getPointAtLength(t);0===t?r=n:t===u&&(a=n);var c=n.xo?n.x-o:0,d=n.ys?n.y-s:0;return Math.sqrt(c*c+d*d)}for(var h=f(c);h;){if((c+=h+n)>d)return;h=f(c)}for(h=f(d);h;){if(c>(d-=h+n))return;h=f(d)}return{min:c,max:d,len:d-c,total:u,isClosed:0===c&&d===u&&Math.abs(r.x-a.x)<.1&&Math.abs(r.y-a.y)<.1}},Ie.findPointOnPath=function(e,t,n,r){for(var a,i,o,l=(r=r||{}).pathLength||e.getTotalLength(),s=r.tolerance||.001,c=r.iterationLimit||30,u=e.getPointAtLength(0)[n]>e.getPointAtLength(l)[n]?-1:1,d=0,f=0,h=l;d0?h=a:f=a,d++}return i};var Be=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},je=/^\w*$/,qe={init2dArray:function(e,t){for(var n=new Array(e),r=0;rt}function Qe(e,t){return e>=t}Ye.findBin=function(e,t,r){if(n(t.start))return r?Math.ceil((e-t.start)/t.size-1e-9)-1:Math.floor((e-t.start)/t.size+1e-9);var a,i,o=0,l=t.length,s=0,c=l>1?(t[l-1]-t[0])/(l-1):1;for(i=c>=0?r?Ze:Xe:r?Qe:We,e+=1e-9*c*(r?-1:1)*(c>=0?1:-1);o90&&w.log("Long binary search..."),o-1},Ye.sorterAsc=function(e,t){return e-t},Ye.sorterDes=function(e,t){return t-e},Ye.distinctVals=function(e){var t=e.slice();t.sort(Ye.sorterAsc);for(var n=t.length-1,r=t[n]-t[0]||1,a=r/(n||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(r=Math.min(r,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:r}},Ye.roundUp=function(e,t,n){for(var r,a=0,i=t.length-1,o=0,l=n?0:1,s=n?1:0,c=n?Math.ceil:Math.floor;ar.length)&&(a=r.length),n(t)||(t=!1),$e(r[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var r=t%1;return r*e[Math.ceil(t)]+(1-r)*e[Math.floor(t)]};var Ke={},et={};function tt(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}Ke.throttle=function(e,t,n){var r=et[e],a=Date.now();if(!r){for(var i in et)et[i].tsr.ts+t?o():r.timer=setTimeout(function(){o(),r.timer=null},t)},Ke.done=function(e){var t=et[e];return t&&t.timer?new Promise(function(e){var n=t.onDone;t.onDone=function(){n&&n(),e(),t.onDone=null}}):Promise.resolve()},Ke.clear=function(e){if(e)tt(et[e]),delete et[e];else for(var t in et)Ke.clear(t)};var nt=function(e,t){if(e>0)return Math.log(e)/Math.LN10;var r=Math.log(Math.min(t[0],t[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(t[0],t[1]))/Math.LN10-6),r},rt={},at=r.FP_SAFE,it=r.BADNUM,ot=rt={};ot.nestedProperty=Z,ot.keyedContainer=function(e,t,n,r){var a,i;n=n||"name",r=r||"value";var o={};i=t&&t.length?Z(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lat?it:n(e)?Number(e):it:it},ot.noop=T,ot.identity=function(e){return e},ot.swapAttrs=function(e,t,n,r){n||(n="x"),r||(r="y");for(var a=0;an?Math.max(n,Math.min(t,e)):Math.max(t,Math.min(n,e))},ot.bBoxIntersect=function(e,t,n){return n=n||0,e.left<=t.right+n&&t.left<=e.right+n&&e.top<=t.bottom+n&&t.top<=e.bottom+n},ot.simpleMap=function(e,t,n,r){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,n)?e(t,n,r):l},ot.OptionControl=function(e,t){e||(e={}),t||(t="opt");var n={optionList:[],_newoption:function(r){r[t]=e,n[r.name]=r,n.optionList.push(r)}};return n["_"+t]=e,n},ot.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var n,r,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(n=0;n=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[r];u[n]=i}return u},ot.syncOrAsync=function(e,t,n){var r;function a(){return ot.syncOrAsync(e,t,n)}for(;e.length;)if((r=(0,e.splice(0,1)[0])(t))&&r.then)return r.then(a).then(void 0,ot.promiseError);return n&&n(t)},ot.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},ot.noneOrAll=function(e,t,n){if(e){var r,a,i=!1,o=!0;for(r=0;r=0&&i%1==0){var p=a?a[h]:h,g=r?r[p]:p;d(g)&&(e[g].selected=1)}}},ot.getTargetArray=function(e,t){var n=t.target;if("string"==typeof n&&n){var r=ot.nestedProperty(e,n).get();return!!Array.isArray(r)&&r}return!!Array.isArray(n)&&n},ot.minExtend=function(e,t){var n={};"object"!=typeof t&&(t={});var r,a,i,o=Object.keys(e);for(r=0;r1?a+o[1]:"";if(i&&(o.length>1||l.length>4||n))for(;r.test(l);)l=l.replace(r,"$1"+i+"$2");return l+s};var ct=/%{([^\s%{}]*)}/g,ut=/^\w*$/;ot.templateString=function(e,t){var n={};return e.replace(ct,function(e,r){return ut.test(r)?t[r]||"":(n[r]=n[r]||ot.nestedProperty(t,r).get,n[r]()||"")})};ot.subplotSort=function(e,t){for(var n=Math.min(e.length,t.length)+1,r=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(r=10*r+o-48),c&&(a=10*a+l-48),!s||!c){if(r!==a)return r-a;if(o!==l)return o-l}}return a-r};var dt=2e9;ot.seedPseudoRandom=function(){dt=2e9},ot.pseudoRandom=function(){var e=dt;return dt=(69069*dt+1)%4294967296,Math.abs(dt-e)<429496729?ot.pseudoRandom():dt/4294967296};var ft=te.counter,ht={idRegex:{x:ft("x"),y:ft("y")},attrRegex:ft("[xy]axis"),xAxisMatch:ft("xaxis"),yAxisMatch:ft("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}},pt={id2name:function(e){if("string"==typeof e&&e.match(ht.AX_ID_PATTERN)){var t=e.substr(1);return"1"===t&&(t=""),e.charAt(0)+"axis"+t}},name2id:function(e){if(e.match(ht.AX_NAME_PATTERN)){var t=e.substr(5);return"1"===t&&(t=""),e.charAt(0)+t}},cleanId:function(e,t){if(e.match(ht.AX_ID_PATTERN)&&(!t||e.charAt(0)===t)){var n=e.substr(1).replace(/^0+/,"");return"1"===n&&(n=""),e.charAt(0)+n}},list:function(e,t,n){var r=e._fullLayout;if(!r)return[];var a,i=pt.listIds(e,t),o=new Array(i.length);for(a=0;ar?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},gt={dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},vt=gt.dash,yt=m.extendFlat,mt={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:O.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks+margins"},titlefont:L({editType:"ticks+margins"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}}],editType:"plot+margins",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks+margins",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks+margins"},tick0:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks+margins"},ticktext:{valType:"data_array",editType:"ticks+margins"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks+margins"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:O.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks+margins"},automargin:{valType:"boolean",dflt:!1,editType:"ticks+margins"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:yt({},vt,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:L({editType:"ticks+margins"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks+margins"},tickprefix:{valType:"string",dflt:"",editType:"ticks+margins"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},ticksuffix:{valType:"string",dflt:"",editType:"ticks+margins"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks+margins"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks+margins"},tickformat:{valType:"string",dflt:"",editType:"ticks+margins"},tickformatstops:{_isLinkedToArray:"tickformatstop",dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks+margins"},{valType:"any",editType:"ticks+margins"}],editType:"ticks+margins"},value:{valType:"string",dflt:"",editType:"ticks+margins"},editType:"ticks+margins"},hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:O.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:O.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:O.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot+margins"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot+margins"},overlaying:{valType:"enumerated",values:["free",ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot+margins"},{valType:"number",min:0,max:1,editType:"plot+margins"}],dflt:[0,1],editType:"plot+margins"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot+margins"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks+margins"}}},xt={},bt=xt={};bt.defaults=O.defaults;var _t=bt.defaultLine=O.defaultLine;bt.lightLine=O.lightLine;var wt=bt.background=O.background;function kt(e){if(n(e)||"string"!=typeof e)return e;var t=e.trim();if("rgb"!==t.substr(0,3))return e;var r=t.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return e;var a=r[1].trim().split(/\s*[\s,]\s*/),i="a"===t.charAt(3)&&4===a.length;if(!i&&3!==a.length)return e;for(var o=0;o=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}bt.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},bt.rgb=function(e){return bt.tinyRGB(s(e))},bt.opacity=function(e){return e?s(e).getAlpha():0},bt.addOpacity=function(e,t){var n=s(e).toRgb();return"rgba("+Math.round(n.r)+", "+Math.round(n.g)+", "+Math.round(n.b)+", "+t+")"},bt.combine=function(e,t){var n=s(e).toRgb();if(1===n.a)return s(e).toRgbString();var r=s(t||wt).toRgb(),a=1===r.a?r:{r:255*(1-r.a)+r.r*r.a,g:255*(1-r.a)+r.g*r.a,b:255*(1-r.a)+r.b*r.a},i={r:a.r*(1-n.a)+n.r*n.a,g:a.g*(1-n.a)+n.g*n.a,b:a.b*(1-n.a)+n.b*n.a};return s(i).toRgbString()},bt.contrast=function(e,t,n){var r=s(e);return 1!==r.getAlpha()&&(r=s(bt.combine(e,wt))),(r.isDark()?t?r.lighten(t):wt:n?r.darken(n):_t).toString()},bt.stroke=function(e,t){var n=s(t);e.style({stroke:bt.tinyRGB(n),"stroke-opacity":n.getAlpha()})},bt.fill=function(e,t){var n=s(t);e.style({fill:bt.tinyRGB(n),"fill-opacity":n.getAlpha()})},bt.clean=function(e){if(e&&"object"==typeof e){var t,n,r,a,i=Object.keys(e);for(t=0;t0)return Math.log(e)/Math.LN10;if(e<=0&&n&&t.range&&2===t.range.length){var r=t.range[0],a=t.range[1];return.5*(r+a-3*i*Math.abs(r-a))}return Dt}function l(e,r,a){var i=Ot(e,a||t.calendar);if(i===Dt){if(!n(e))return Dt;i=Ot(new Date(+e))}return i}function s(e,n,r){return St(e,n,r||t.calendar)}function c(e){return t._categories[Math.round(e)]}function u(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(n(e))return+e}function d(r){return n(r)?e.round(t._b+t._m*r,2):Dt}function f(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:zt,t.l2c="log"===t.type?Et:zt,t.l2p=d,t.p2l=f,t.c2p="log"===t.type?function(e,t){return d(o(e,t))}:d,t.p2c="log"===t.type?function(e){return Et(f(e))}:f,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Ct,t.c2d=t.c2r=t.l2d=t.l2r=zt,t.d2p=t.r2p=function(e){return t.l2p(Ct(e))},t.p2d=t.p2r=f,t.cleanPos=zt):"log"===t.type?(t.d2r=t.d2l=function(e,t){return o(Ct(e),t)},t.r2d=t.r2c=function(e){return Et(Ct(e))},t.d2c=t.r2l=Ct,t.c2d=t.l2r=zt,t.c2r=o,t.l2d=Et,t.d2p=function(e,n){return t.l2p(t.d2r(e,n))},t.p2d=function(e){return Et(f(e))},t.r2p=function(e){return t.l2p(Ct(e))},t.p2r=f,t.cleanPos=zt):"date"===t.type?(t.d2r=t.r2d=rt.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,n,r){return t.l2p(l(e,0,r))},t.p2d=t.p2r=function(e,t,n){return s(f(e),t,n)},t.cleanPos=function(e){return rt.cleanDate(e,Dt,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var n=t._categories.length-1;return t._categoriesMap[e]=n,n}return Dt},t.r2d=t.c2d=t.l2d=c,t.d2r=t.d2l_noadd=u,t.r2c=function(e){var n=u(e);return void 0!==n?n:t.fraction2r(.5)},t.l2r=t.c2r=zt,t.r2l=u,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(e){return c(f(e))},t.r2p=t.d2p,t.p2r=f,t.cleanPos=function(e){return"string"==typeof e&&""!==e?e:zt(e)}),t.fraction2r=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return t.l2r(n+e*(r-n))},t.r2fraction=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return(t.r2l(e)-n)/(r-n)},t.cleanRange=function(e,r){r||(r={}),e||(e="range");var i,o,l=rt.nestedProperty(t,e).get();if(o=(o="date"===t.type?rt.dfltRange(t.calendar):"y"===a?ht.DFLTRANGEY:r.dfltRange||ht.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=rt.cleanDate(l[0],Dt,t.calendar),l[1]=rt.cleanDate(l[1],Dt,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!rt.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=rt.constrain(t.r2l(l[0]),rt.MIN_MS+1e3,rt.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!n(l[i])){if(!n(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Pt?l[i]=-Pt:l[i]>Pt&&(l[i]=Pt),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else rt.nestedProperty(t,e).set(o)},t.setScale=function(e){var n=r._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=pt.getFromId({_fullLayout:r},t.overlaying);t.domain=i.domain}var o=e&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===a?(t._offset=n.t+(1-t.domain[1])*n.h,t._length=n.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=n.l+t.domain[0]*n.w,t._length=n.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw r._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,n){var r,a,i,o,l=t.type,s="date"===l&&e[n+"calendar"];if(n in e){if(r=e[n],o=e._length||r.length,rt.isTypedArray(r)&&("linear"===l||"log"===l)){if(o===r.length)return r;if(r.subarray)return r.subarray(0,o)}for(a=new Array(o),i=0;i=t.r2l(t.range[0])&&r<=t.r2l(t.range[1])},t.clearCalc=function(){t._min=[],t._max=[],t._categories=(t._initialCategories||[]).slice(),t._categoriesMap={};for(var e=0;e0?Number(s):l;else if("string"!=typeof s)t.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=n(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(t.dtick=l)}var d="date"===a?rt.dateTick0(t.calendar):0,f=r("tick0",d);"date"===a?t.tick0=rt.cleanDate(f,d):n(f)&&"D1"!==s&&"D2"!==s?t.tick0=Number(f):t.tick0=d}else{void 0===r("tickvals")?t.tickmode="auto":r("ticktext")}},jt=function(t,n,r,a,i){var o=a.letter,l=a.font||{},s=r("visible",!a.cheateronly),c=n.type;"date"===c&&D.getComponentMethod("calendars","handleDefaults")(t,n,"calendar",a.calendar);Nt(n,i);var u=r("autorange",!n.isValidRange(t.range));if(n._rangesliderAutorange=!1,u&&r("rangemode"),r("range"),n.cleanRange(),function(e,t,n){if("category"===t.type){var r,a=e.categoryarray,i=Array.isArray(a)&&a.length>0;i&&(r="array");var o=n("categoryorder",r);"array"===o&&n("categoryarray"),i||"array"!==o||(t.categoryorder="trace")}}(t,n,r),n._initialCategories="category"===c?function(t,n,r,a){switch(n){case"array":return Array.isArray(r)?r.slice():[];case"category ascending":return Lt(t,e.ascending,a);case"category descending":return Lt(t,e.descending,a);case"trace":default:return[]}}(o,n.categoryorder,n.categoryarray,a.data):[],"category"===c||a.noHover||r("hoverformat"),!s)return n;var d=r("color"),f=d===t.color?d:l.color;return r("title",i._dfltTitle[o]),rt.coerceFont(r,"titlefont",{family:l.family,size:Math.round(1.2*l.size),color:f}),Bt(t,n,r,c),It(t,n,r,c,a),Rt(t,n,r,a),At(t,n,r,{dfltColor:d,bgColor:a.bgColor,showGrid:a.showGrid,attributes:mt}),(n.showline||n.ticks)&&r("mirror"),a.automargin&&r("automargin"),n},qt=pt.id2name,Ht=function(e,t,n,r,a){var i=a._axisConstraintGroups,o=t._id,l=o.charAt(0);if(!t.fixedrange&&(n("constrain"),rt.coerce(e,t,{constraintoward:{valType:"enumerated",values:"x"===l?["left","center","right"]:["bottom","middle","top"],dflt:"x"===l?"center":"middle"}},"constraintoward"),e.scaleanchor)){var s=function(e,t,n,r){var a,i,o,l,s=r[qt(t)].type,c=[];for(i=0;ip[1]-.01&&(t.domain=o),rt.noneOrAll(e.domain,t.domain,o)}return r("layer"),t},Ut=r.BADNUM,Gt=function(e,t){return function(e,t){for(var r,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,t)?"date":function(e){for(var t,n=Math.max(1,(e.length-1)/1e3),r=0,a=0,i=0;i2*r}(e)?"category":function(e){if(!e)return!1;for(var t=0;t=0;a--,i++)t=e[a],r[i]=[1-t[0],t[1]];return r},$t=function(e,t,n,r){var a,i;n?(a=rt.nestedProperty(e,n).get(),i=rt.nestedProperty(e._input,n).get()):(a=e,i=e._input);var o=r+"auto",l=r+"min",s=r+"max",u=a[o],d=a[l],f=a[s],h=a.colorscale;!1===u&&void 0!==d||(d=rt.aggNums(Math.min,null,t)),!1===u&&void 0!==f||(f=rt.aggNums(Math.max,null,t)),d===f&&(d-=.5,f+=.5),a[l]=d,a[s]=f,i[l]=d,i[s]=f,i[o]=!1!==u||void 0===d&&void 0===f,a.autocolorscale&&(h=d*f<0?c.RdBu:d>=0?c.Reds:c.Blues,i.colorscale=h,a.reversescale&&(h=Jt(h)),a.colorscale=h)},Kt=rt.extendFlat,en=rt.isPlainObject,tn={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},nn={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},rn=tn.flags.slice().concat(["clearCalc","fullReplot"]),an=nn.flags.slice().concat("layoutReplot"),on={traces:tn,layout:nn,traceFlags:function(){return ln(rn)},layoutFlags:function(){return ln(an)},update:function(e,t){var n=t.editType;if(n&&"none"!==n)for(var r=n.split("+"),a=0;a","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},bn={},_n=mn.LINE_SPACING;function wn(e,t){return e.node().getBoundingClientRect()[t]}var kn=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;bn.convertToTspans=function(n,r,a){var i=n.text(),o=!n.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(kn),l=e.select(n.node().parentNode);if(!l.empty()){var s=n.attr("class")?n.attr("class").split(" ")[0]:"text";return s+="-math",l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove(),n.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(r&&r._promises||[]).push(new Promise(function(t){n.style("display","none");var r=parseInt(n.node().style.fontSize,10),u={fontSize:r};!function(t,n,r){var a="math-output-"+rt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":n.fontSize+"px"}).text((o=t,o.replace(Mn,"\\lt ").replace(Tn,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var n=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())rt.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),n,a)}i.remove()})}(o[2],u,function(e,o,u){l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove();var d=e&&e.select("svg");if(!d||!d.node())return c(),void t();var f=l.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});f.node().appendChild(d.node()),o&&o.node()&&d.node().insertBefore(o.node().cloneNode(!0),d.node().firstChild),d.attr({class:s,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=n.node().style.fill||"black";d.select("g").attr({fill:h,stroke:h});var p=wn(d,"width"),g=wn(d,"height"),v=+n.attr("x")-p*{start:0,middle:.5,end:1}[n.attr("text-anchor")||"start"],y=-(r||wn(n,"height"))/4;"y"===s[0]?(f.attr({transform:"rotate("+[-90,+n.attr("x"),+n.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),d.attr({x:+n.attr("x"),y:+n.attr("y")})):"l"===s[0]?d.attr({x:n.attr("x"),y:y-g/2}):"a"===s[0]?d.attr({x:0,y:y}):d.attr({x:v,y:+n.attr("y")+y-g/2}),a&&a.call(n,f),t(f)})})):c(),n}function c(){l.empty()||(s=n.attr("class")+"-math",l.select("svg."+s).remove()),n.text("").style("white-space","pre"),function(n,r){r=(a=r,function(e,t){if(!e)return"";for(var n=0;n1)for(var o=1;o doesnt match end tag <"+e+">. Pretending it did match.",r),i=l[l.length-1].node}else rt.log("Ignoring unexpected end tag .",r)}In.test(r)?c():(i=n,l=[{node:n}]);for(var h=r.split(En),p=0;p|>|>)/g;var An={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"},Ln={sub:"0.3em",sup:"-0.6em"},Cn={sub:"-0.21em",sup:"0.42em"},Sn="\u200b",On=["http:","https:","mailto:","",void 0,":"],zn=new RegExp("]*)?/?>","g"),Pn=Object.keys(xn.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:xn.entityToUnicode[e]}}),Dn=/(\r\n?|\n)/g,En=/(<[^<>]*>)/,Nn=/<(\/?)([^ >]*)(\s+(.*))?>/i,In=//i,Rn=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Fn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Bn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,jn=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function qn(e,t){if(!e)return null;var n=e.match(t);return n&&(n[3]||n[4])}var Hn=/(^|;)\s*color:/;function Vn(e,t,n){var r,a,i,o=n.horizontalAlign,l=n.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-r.height}:"middle"===l?function(){return s.top+(s.height-r.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-r.width}:"center"===o?function(){return s.left+(s.width-r.width)/2}:function(){return s.left},function(){return r=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}bn.plainText=function(e){return(e||"").replace(zn," ")},bn.lineCount=function(e){return e.selectAll("tspan.line").size()||1},bn.positionText=function(t,n,r){return t.each(function(){var t=e.select(this);function a(e,n){return void 0===n?null===(n=t.attr(e))&&(t.attr(e,0),n=0):t.attr(e,n),n}var i=a("x",n),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},bn.makeEditable=function(t,n){var r=n.gd,a=n.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(r).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:n.fill||c.fill||"black",opacity:1,"background-color":n.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(n.text||t.attr("data-unformatted")).call(Vn(t,a,n)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var n,a=e.select(this).attr("class");(n=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(n).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(r._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Vn(t,a,n)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var d,f=o.attr("class");(d=f?"."+f.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(d).style({opacity:0})}function s(e){var t=e.node(),n=document.createRange();n.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(n),t.focus()}return n.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var Un=function(e){var t=e.marker,r=t.sizeref||1,a=t.sizemin||0,i="area"===t.sizemode?function(e){return Math.sqrt(e/r)}:function(e){return e/r};return function(e){var t=i(e/2);return n(t)&&t>0?Math.max(t,a):0}},Gn={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("markers")},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return rt.isPlainObject(e.marker)&&rt.isArrayOrTypedArray(e.marker.size)}},Yn={},Zn=mn.LINE_SPACING,Xn=h.DESELECTDIM,Wn=Yn={};Wn.font=function(e,t,n,r){rt.isPlainObject(t)&&(r=t.color,n=t.size,t=t.family),t&&e.style("font-family",t),n+1&&e.style("font-size",n+"px"),r&&e.call(xt.fill,r)},Wn.setPosition=function(e,t,n){e.attr("x",t).attr("y",n)},Wn.setSize=function(e,t,n){e.attr("width",t).attr("height",n)},Wn.setRect=function(e,t,n,r,a){e.call(Wn.setPosition,t,n).call(Wn.setSize,r,a)},Wn.translatePoint=function(e,t,r,a){var i=r.c2p(e.x),o=a.c2p(e.y);return!!(n(i)&&n(o)&&t.node())&&("text"===t.node().nodeName?t.attr("x",i).attr("y",o):t.attr("transform","translate("+i+","+o+")"),!0)},Wn.translatePoints=function(t,n,r){t.each(function(t){var a=e.select(this);Wn.translatePoint(t,a,n,r)})},Wn.hideOutsideRangePoint=function(e,t,n,r,a,i){t.attr("display",n.isPtWithinRange(e,a)&&r.isPtWithinRange(e,i)?null:"none")},Wn.hideOutsideRangePoints=function(t,n,r){if(n._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=n.xaxis,i=n.yaxis;t.each(function(n){var o=n[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Wn.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Wn.crispRound=function(e,t,r){return t&&n(t)?e._context.staticPlot?t:t<1?1:Math.round(t):r||0},Wn.singleLineStyle=function(e,t,n,r,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";xt.stroke(t,r||i.color),Wn.dashLine(t,l,o)},Wn.lineGroupStyle=function(t,n,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";e.select(this).call(xt.stroke,r||i.color).call(Wn.dashLine,l,o)})},Wn.dashLine=function(e,t,n){n=+n||0,t=Wn.dashStyle(t,n),e.style({"stroke-dasharray":t,"stroke-width":n+"px"})},Wn.dashStyle=function(e,t){t=+t||1;var n=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),e},Wn.singleFillStyle=function(t){var n=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;n&&t.call(xt.fill,n)},Wn.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(n){var r=e.select(this);try{r.call(xt.fill,n[0].trace.fillcolor)}catch(e){rt.error(e,t),r.remove()}})},Wn.symbolNames=[],Wn.symbolFuncs=[],Wn.symbolNeedLines={},Wn.symbolNoDot={},Wn.symbolNoFill={},Wn.symbolList=[],Object.keys(yn).forEach(function(e){var t=yn[e];Wn.symbolList=Wn.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Wn.symbolNames[t.n]=e,Wn.symbolFuncs[t.n]=t.f,t.needLine&&(Wn.symbolNeedLines[t.n]=!0),t.noDot?Wn.symbolNoDot[t.n]=!0:Wn.symbolList=Wn.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Wn.symbolNoFill[t.n]=!0)});var Qn=Wn.symbolNames.length,Jn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function $n(e,t){var n=e%100;return Wn.symbolFuncs[n](t)+(e>=200?Jn:"")}Wn.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Wn.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Qn||e>=400?0:Math.floor(Math.max(e,0))};var Kn={x1:1,x2:0,y1:0,y2:0},er={x1:0,x2:0,y1:1,y2:0};Wn.gradient=function(t,n,r,a,i,o){var l=n._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],rt.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Kn):"vertical"===a&&t.attr(er),t.attr("id",r);var n=s(i),l=s(o);t.append("stop").attr({offset:"0%","stop-color":xt.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":xt.tinyRGB(n),"stop-opacity":n.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Wn.initGradients=function(e){var t=e._fullLayout._defs.selectAll(".gradients").data([0]);t.enter().append("g").classed("gradients",!0),t.selectAll("linearGradient,radialGradient").remove()},Wn.singlePointStyle=function(e,t,n,r,a,i){var o=n.marker;!function(e,t,n,r,a,i,o,l){if(D.traceIs(n,"symbols")){var s=Un(n);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Gn.isBubble(n)?s(e.ms):(i.size||6)/2,e.mrc=t;var r=Wn.symbolNumber(e.mx||i.symbol)||0;return e.om=r%200>=100,$n(r,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,d,f=!1;if(e.so?(d=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(d=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):rt.isArrayOrTypedArray(o.color)?xt.defaultLine:o.color,rt.isArrayOrTypedArray(i.color)&&(c=xt.defaultLine,f=!0),c="mc"in e?e.mcc=r(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(xt.stroke,c).style({"stroke-width":(d||1)+"px",fill:"none"});else{t.style("stroke-width",d+"px");var h=i.gradient,p=e.mgt;if(p?f=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?f=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+n.uid;f&&(v+="-"+e.i),t.call(Wn.gradient,l,v,p,c,g)}else t.call(xt.fill,c);d&&t.call(xt.stroke,u)}}(e,t,n,r,a,o,o.line,i)},Wn.pointStyle=function(t,n,r){if(t.size()){var a=n.marker,i=Wn.tryColorscale(a,""),o=Wn.tryColorscale(a,"line");t.each(function(t){Wn.singlePointStyle(t,e.select(this),n,i,o,r)})}},Wn.makeSelectedPointStyleFns=function(e){var t={},n=e.selected||{},r=e.unselected||{},a=e.marker||{},i=n.marker||{},o=r.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,d=void 0!==c;t.opacityFn=function(e){var t=e.mo,n=void 0!==t;if(n||u||d){if(!e.selected)return d?c:Xn*(n?t:l);if(u)return s}};var f=i.color,h=o.color;(f||h)&&(t.colorFn=function(e){if(e.selected){if(f)return f}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Wn.selectedPointStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=Wn.makeSelectedPointStyleFns(n),a=n.marker||{};t.each(function(t){var n=e.select(this),a=r.opacityFn(t);void 0!==a&&n.style("opacity",a)}),r.colorFn&&t.each(function(t){var n=e.select(this),a=r.colorFn(t);a&&xt.fill(n,a)}),D.traceIs(n,"symbols")&&r.sizeFn&&t.each(function(t){var n=e.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);n.attr("d",$n(Wn.symbolNumber(i),o)),t.mrc2=o})}},Wn.tryColorscale=function(e,t){var n=t?rt.nestedProperty(e,t).get():e,r=n.colorscale,a=n.color;return r&&rt.isArrayOrTypedArray(a)?vn.makeColorScaleFunc(vn.extractScale(r,n.cmin,n.cmax)):rt.identity};var tr={start:1,end:-1,middle:0,bottom:1,top:-1};function nr(t,n,r,a){var i=e.select(t.node().parentNode),o=-1!==n.indexOf("top")?"top":-1!==n.indexOf("bottom")?"bottom":"middle",l=-1!==n.indexOf("left")?"end":-1!==n.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(bn.lineCount(t)-1)*Zn+1,u=tr[l]*s,d=.75*r+tr[o]*s+(tr[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+d+")")}function rr(e,t){var r=e.ts||t.textfont.size;return n(r)&&r>0?r:0}Wn.textPointStyle=function(t,n,r){t.each(function(t){var a=e.select(this),i=rt.extractOption(t,n,"tx","text");if(i){var o=t.tp||n.textposition,l=rr(t,n);a.call(Wn.font,t.tf||n.textfont.family,l,t.tc||n.textfont.color).text(i).call(bn.convertToTspans,r).call(nr,o,l,t.mrc)}else a.remove()})},Wn.selectedTextStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=n.selected||{},a=n.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||n.textfont.color,s=t.tp||n.textposition,c=rr(t,n),u=(r.textfont||{}).color,d=(a.textfont||{}).color;t.selected?u&&(i=u):d?i=d:u||(i=xt.addOpacity(l,Xn)),i&&xt.fill(o,i),nr(o,s,c,t.mrc2||t.mrc)})}};var ar=.5;function ir(t,n,r,a){var i=t[0]-n[0],o=t[1]-n[1],l=r[0]-n[0],s=r[1]-n[1],c=Math.pow(i*i+o*o,ar/2),u=Math.pow(l*l+s*s,ar/2),d=(u*u*i-c*c*l)*a,f=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(n[0]+(h&&d/h),2),e.round(n[1]+(h&&f/h),2)],[e.round(n[0]-(p&&d/p),2),e.round(n[1]-(p&&f/p),2)]]}Wn.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var n,r="M"+e[0],a=[];for(n=1;n=1e4&&(Wn.savedBBoxes={},sr=0),r&&(Wn.savedBBoxes[r]=p),sr++,rt.extendFlat({},p)},Wn.setClipUrl=function(t,n){if(n){var r="#"+n,a=e.select("base");a.size()&&a.attr("href")&&(r=window.location.href.split("#")[0]+r),t.attr("clip-path","url("+r+")")}else t.attr("clip-path",null)},Wn.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Wn.setTranslate=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||0,n=n||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+n+")").trim(),e[a]("transform",i),i},Wn.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Wn.setScale=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||1,n=n||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+n+")").trim(),e[a]("transform",i),i},Wn.setPointGroupScale=function(e,t,n){var r,a,i;return t=t||1,n=n||1,a=1===t&&1===n?"":" scale("+t+","+n+")",i=/\s*sc.*/,e.each(function(){r=(this.getAttribute("transform")||"").replace(i,""),r=(r+=a).trim(),this.setAttribute("transform",r)}),a};var ur=/translate\([^)]*\)\s*$/;Wn.setTextPointsScale=function(t,n,r){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(ur);t=1===n&&1===r?[]:["translate("+o+","+l+")","scale("+n+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var dr={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500},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"]}}},fr={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}},hr=m.extendFlat,pr=function(e,t,n){return{color:{valType:"color",arrayOk:!0,editType:t||"style"},colorscale:hr({},Qt.colorscale,{}),cauto:hr({},Qt.zauto,{impliedEdits:{cmin:void 0,cmax:void 0}}),cmax:hr({},Qt.zmax,{editType:t||Qt.zmax.editType,impliedEdits:{cauto:!1}}),cmin:hr({},Qt.zmin,{editType:t||Qt.zmin.editType,impliedEdits:{cauto:!1}}),autocolorscale:hr({},Qt.autocolorscale,{dflt:!1===n?n:Qt.autocolorscale.dflt}),reversescale:hr({},Qt.reversescale,{})}},gr={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20},vr=gt.dash,yr=m.extendFlat,mr={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:yr({},vr,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:yr({symbol:{valType:"enumerated",values:Yn.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},showscale:{valType:"boolean",dflt:!1,editType:"calc"},colorbar:dn,line:yr({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},pr()),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},pr()),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:L({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}},xr=mr.marker,br={r:mr.r,t:mr.t,marker:{color:xr.color,size:xr.size,symbol:xr.symbol,opacity:xr.opacity,editType:"calc"}},_r=m.extendFlat,wr=on.overrideAll,kr=_r({},mt.domain,{});function Mr(e,t){return _r({},t,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}var Tr=wr({radialaxis:Mr(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:kr,orientation:{valType:"number"}}),angularaxis:Mr(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:kr}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested"),Ar={},Lr=rt.extendFlat,Cr=rt.extendDeepAll,Sr="_isSubplotObj",Or="_isLinkedToArray",zr=[Sr,Or,"_arrayAttrRegexps","_deprecated"];function Pr(e,t,n){if(!e)return!1;if(e._isLinkedToArray)if(Dr(t[n]))n++;else if(n=i.length)return!1;if(2===e.dimensions){if(n++,t.length===n)return e;var o=t[n];if(!Dr(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function Dr(e){return e===Math.round(e)&&e>=0}function Er(e){return function(e){Ar.crawl(e,function(e,t,n){Ar.isValObject(e)?"data_array"===e.valType?(e.role="data",n[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(n[t+"src"]={valType:"string",editType:"none"}):rt.isPlainObject(e)&&(e.role="object")})}(e),function(e){Ar.crawl(e,function(e,t,n){if(!e)return;var r=e[Or];if(!r)return;delete e[Or],n[t]={items:{}},n[t].items[r]=e,n[t].role="object"})}(e),e}function Nr(e,t,n){var r=rt.nestedProperty(e,n),a=Cr({},t.layoutAttributes);a[Sr]=!0,r.set(a)}function Ir(e,t,n){var r=rt.nestedProperty(e,n);r.set(Cr(r.get()||{},t))}Ar.IS_SUBPLOT_OBJ=Sr,Ar.IS_LINKED_TO_ARRAY=Or,Ar.DEPRECATED="_deprecated",Ar.UNDERSCORE_ATTRS=zr,Ar.get=function(){var e={};D.allTypes.concat("area").forEach(function(t){e[t]=function(e){var t,n;"area"===e?(t={attributes:br},n={}):(t=D.modules[e]._module,n=t.basePlotModule);var r={type:null};Cr(r,S),Cr(r,t.attributes),n.attributes&&Cr(r,n.attributes);r.type=e;var a={meta:t.meta||{},attributes:Er(r)};if(t.layoutAttributes){var i={};Cr(i,t.layoutAttributes),a.layoutAttributes=Er(i)}return a}(t)});var t,n={};return Object.keys(D.transformsRegistry).forEach(function(e){n[e]=function(e){var t=D.transformsRegistry[e],n=Cr({},t.attributes);return Object.keys(D.componentsRegistry).forEach(function(t){var r=D.componentsRegistry[t];r.schema&&r.schema.transforms&&r.schema.transforms[e]&&Object.keys(r.schema.transforms[e]).forEach(function(t){Ir(n,r.schema.transforms[e][t],t)})}),{attributes:Er(n)}}(e)}),{defs:{valObjects:rt.valObjectMeta,metaKeys:zr.concat(["description","role","editType","impliedEdits"]),editType:{traces:on.traces,layout:on.layout},impliedEdits:{}},traces:e,layout:function(){var e,t,n={};for(e in Cr(n,P),D.subplotsRegistry)if((t=D.subplotsRegistry[e]).layoutAttributes)if("cartesian"===t.name)Nr(n,t,"xaxis"),Nr(n,t,"yaxis");else{var r="subplot"===t.attr?t.name:t.attr;Nr(n,t,r)}for(e in n=function(e){return Lr(e,{radialaxis:Tr.radialaxis,angularaxis:Tr.angularaxis}),Lr(e,Tr.layout),e}(n),D.componentsRegistry){var a=(t=D.componentsRegistry[e]).schema;if(a&&(a.subplots||a.layout)){var i=a.subplots;if(i&&i.xaxis&&!i.yaxis)for(var o in i.xaxis)delete n.yaxis[o]}else t.layoutAttributes&&Ir(n,t.layoutAttributes,t.name)}return{layoutAttributes:Er(n)}}(),transforms:n,frames:(t={frames:rt.extendDeepAll({},fr)},Er(t),t.frames),animation:Er(dr)}},Ar.crawl=function(e,t,n,r){var a=n||0;r=r||"",Object.keys(e).forEach(function(n){var i=e[n];if(-1===zr.indexOf(n)){var o=(r?r+".":"")+n;t(i,n,e,a,o),Ar.isValObject(i)||rt.isPlainObject(i)&&"impliedEdits"!==n&&Ar.crawl(i,t,a+1,o)}})},Ar.isValObject=function(e){return e&&void 0!==e.valType},Ar.findArrayAttributes=function(e){var t=[],n=[];function r(r,a,i,o){if(n=n.slice(0,o).concat([a]),r&&("data_array"===r.valType||!0===r.arrayOk)&&!("colorbar"===n[o-1]&&("ticktext"===a||"tickvals"===a))){var l=function(e){return e.join(".")}(n),s=rt.nestedProperty(e,l).get();rt.isArrayOrTypedArray(s)&&t.push(l)}}if(Ar.crawl(S,r),e._module&&e._module.attributes&&Ar.crawl(e._module.attributes,r),e.transforms)for(var a=e.transforms,i=0;i=e.transforms.length)return!1;r=(n=(D.transformsRegistry[e.transforms[o].type]||{}).attributes)&&n[t[2]],i=3}else if("area"===e.type)r=br[a];else{var l=e._module;if(l||(l=(D.modules[e.type||S.type.dflt]||{})._module),!l)return!1;if(!(r=(n=l.attributes)&&n[a])){var s=l.basePlotModule;s&&s.attributes&&(r=s.attributes[a])}r||(r=S[a])}return Pr(r,t,i)},Ar.getLayoutValObject=function(e,t){return Pr(function(e,t){var n,r,a,i,o=e._basePlotModules;if(o){var l;for(n=0;n0?".":"")+a;rt.isPlainObject(i)?qr(i,t,o,r+1):t(o,a,i)}})}Rr.manageCommandObserver=function(e,t,n,r){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Rr.hasSimpleAPICommandBindings(e,n,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Fr(e,o,a.cache),a.check=function(){if(i){var t=Fr(e,o,a.cache);return t.changed&&r&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(r({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=n.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=n._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var n=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)n.on("click",function(){Gr.sendDataToCloud(e)});else{var r=window.location.pathname.split("/"),a=window.location.search;n.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+r[2].split(".")[0]+"/"+r[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},Gr.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var n=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:n+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=Gr.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var Xr,Wr=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Qr=["year","month","dayMonth","dayMonthYear"];function Jr(e,t){var n,r,a=e.trace,i=a._arrayAttrs,o={};for(n=0;n=0)return!0}return!1},Gr.cleanPlot=function(e,t,n,r){var a,i,o=r._basePlotModules||[];for(a=0;a0){var c=function(e){var t,n={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(n.left+=e[t].left||0,n.right+=e[t].right||0,n.bottom+=e[t].bottom||0,n.top+=e[t].top||0);return n}(e._boundingBoxMargins),u=c.left+c.right,d=c.bottom+c.top,f=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};a=Math.round(f*(h.width-u)),i=Math.round(f*(h.height-d))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=Gr.layoutAttributes.width.min,v=Gr.layoutAttributes.height.min;a1,m=!t.height&&Math.abs(r.height-i)>1;(m||y)&&(y&&(r.width=a),m&&(r.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),Gr.sanitizeMargins(r)},Gr.supplyLayoutModuleDefaults=function(e,t,n,r){var a,i,o,l=D.componentsRegistry,s=t._basePlotModules,c=D.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(D.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(rt.subplotSort);for(i=0;i.5*r.width&&(n.l=n.r=0),n.b+n.t>.5*r.height&&(n.b=n.t=0),r._pushmargin[t]={l:{val:n.x,size:n.l+a},r:{val:n.x,size:n.r+a},b:{val:n.y,size:n.b+a},t:{val:n.y,size:n.t+a}}}else delete r._pushmargin[t];r._replotting||Gr.doAutoMargin(e)}},Gr.doAutoMargin=function(e){var t=e._fullLayout;t._size||(t._size={}),t._pushmargin||(t._pushmargin={});var r=t._size,a=JSON.stringify(r),i=Math.max(t.margin.l||0,0),o=Math.max(t.margin.r||0,0),l=Math.max(t.margin.t||0,0),s=Math.max(t.margin.b||0,0),c=t._pushmargin;if(!1!==t.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var d=c[u].l||{},f=c[u].b||{},h=d.val,p=d.size,g=f.val,v=f.size;for(var y in c){if(n(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-t.width)*h)/(m-h),_=(x*(1-h)+(p-t.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(n(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-t.height)*g)/(w-g),T=(k*(1-g)+(v-t.height)*(1-w))/(w-g);M>=0&&T>=0&&M+T>s+l&&(s=M,l=T)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(t.margin.pad),r.w=Math.round(t.width)-r.l-r.r,r.h=Math.round(t.height)-r.t-r.b,!t._replotting&&"{}"!==a&&a!==JSON.stringify(t._size))return D.call("plot",e)},Gr.graphJson=function(e,t,n,r,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&Gr.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(rt.isPlainObject(e)){var t,r,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===n){if("src"===t.substr(t.length-3))continue}else if("keepstream"===n){if("string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0&&!rt.isPlainObject(e.stream))continue}else if("keepall"!==n&&"string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):rt.isJSDate(e)?rt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var n=s(e);return t&&delete n.fit,n})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===r?c:JSON.stringify(c)},Gr.modifyFrames=function(e,t){var n,r,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(n=0;n0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){d=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return D.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var r,o,l=0,s=0;function c(){return l++,function(){var n;d||++s!==l||(n=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return D.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(n)))}}var f=e._fullLayout._basePlotModules,h=!1;if(n)for(o=0;o=0;i--)if(g[i].enabled){n._indexToPoints=g[i]._indexToPoints;break}r&&r.calc&&(p=r.calc(e,n))}Array.isArray(p)&&p[0]||(p=[{x:Ur,y:Ur}]),p[0].t||(p[0].t={}),p[0].trace=n,c[a]=p}D.getComponentMethod("fx","calc")(e)},Gr.rehover=function(e){e._fullLayout._rehover&&e._fullLayout._rehover()},Gr.generalUpdatePerTraceModule=function(e,t,n,r){var a,i=t.traceHash,o={};for(a=0;a0||d<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];r.attr("transform","translate("+p+")")}}}T.call(A),k&&(w?T.on(".opacity",null):(b=0,_=!0,T.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(bn.makeEditable,{gd:t}).on("edit",function(e){void 0!==c?D.call("restyle",t,l,e,c):D.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(A)}).on("input",function(e){this.text(e||" ").call(bn.positionText,d.x,d.y)}));return T.classed("js-placeholder",_),p}},na=/ [XY][0-9]* /;var ra=r.FP_SAFE,aa=sa,ia=ca,oa=function(e){e._length||e.setScale();var t,n=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&n&&(e.range=sa(e),e._r=e.range.slice(),e._rl=rt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var r=e._anchorAxis.rangeslider[e._name];r&&"auto"===r.rangemode&&(r.range=n?sa(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=rt.extendFlat({},r)}},la=function(e,t,r){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!t)return;e._min||(e._min=[]);e._max||(e._max=[]);r||(r={});e._m||e.setScale();var a,i,o,l,s,c,u,d,f,h,p,g,v=t.length,y=r.padded||!1,m=r.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((e._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),T=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-ra&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var A=m&&0===a;v.push({val:a,pad:A?0:b,extrapad:!A&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)A(a)};function sa(e){var t,n,r,a,i,o,l,s,c=[],u=e._min[0].val,d=e._max[0].val,f=0,h=!1,p=ca(e);for(t=1;t0&&l>0&&s/l>f&&(i=r,o=a,f=s/l);if(u===d){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else f&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-f*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),f=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-f*p(i),o.val+f*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),rt.simpleMap(c,e.l2r||Number)}function ca(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function ua(e){return n(e)&&Math.abs(e)=t}var ha={},pa=r.ONEAVGYEAR,ga=r.ONEAVGMONTH,va=r.ONEDAY,ya=r.ONEHOUR,ma=r.ONEMIN,xa=r.ONESEC,ba=r.MINUS_SIGN,_a=r.BADNUM,wa=mn.MID_SHIFT,ka=mn.LINE_SPACING,Ma=ha={};Ma.setConvert=Nt,Ma.id2name=pt.id2name,Ma.name2id=pt.name2id,Ma.cleanId=pt.cleanId,Ma.list=pt.list,Ma.listIds=pt.listIds,Ma.getFromId=pt.getFromId,Ma.getFromTrace=pt.getFromTrace,Ma.expand=la,Ma.getAutoRange=aa,Ma.coerceRef=function(e,t,n,r,a,i){var o=r.charAt(r.length-1),l=n._fullLayout._subplots[o+"axis"],s=r+"ref",c={};return a||(a=l[0]||i),i||(i=a),c[s]={valType:"enumerated",values:l.concat(i?[i]:[]),dflt:a},rt.coerce(e,t,c,s)},Ma.coercePosition=function(e,t,n,r,a,i){var o,l;if("paper"===r||"pixel"===r)o=rt.ensureNumber,l=n(a,i);else{var s=Ma.getFromId(t,r);l=n(a,i=s.fraction2r(i)),o=s.cleanPos}e[a]=o(l)},Ma.cleanPosition=function(e,t,n){return("paper"===n||"pixel"===n?rt.ensureNumber:Ma.getFromId(t,n).cleanPos)(e)};var Ta=Ma.getDataConversions=function(e,t,n,r){var a,i="x"===n||"y"===n||"z"===n?n:r;if(Array.isArray(i)){if(a={type:Gt(r),_categories:[]},Ma.setConvert(a),"category"===a.type)for(var o=0;o2e-6||((n-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},Ma.saveRangeInitial=function(e,t){for(var n=Ma.list(e,"",!0),r=!1,a=0;a.3*f||u(a)||u(i))){var h=r.dtick/2;e+=e+h.8){var o=Number(n.substr(1));i.exactYears>.8&&o%12==0?e=Ma.tickIncrement(e,"M6","reverse")+1.5*va:i.exactMonths>.8?e=Ma.tickIncrement(e,"M1","reverse")+15.5*va:e-=va/2;var l=Ma.tickIncrement(e,n);if(l<=r)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=Ma.tickIncrement(h,l.dtick,!1,i),0;return{start:t.c2r(p,0,i),end:t.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},Ma.prepTicks=function(e){var t=rt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var n,r=e.nticks;r||("category"===e.type?(n=e.tickfont?1.2*(e.tickfont.size||12):15,r=e._length/n):(n="y"===e._id.charAt(0)?40:80,r=rt.constrain(e._length/n,4,9)+1),"radialaxis"===e._name&&(r*=2)),"array"===e.tickmode&&(r*=100),Ma.autoTicks(e,Math.abs(t[1]-t[0])/r),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),Ia(e)},Ma.calcTicks=function(e){Ma.prepTicks(e);var t=rt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,n,r=e.tickvals,a=e.ticktext,i=new Array(r.length),o=rt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),d=0;Array.isArray(a)||(a=[]);var f="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(n=0;nc&&t=r:s<=r)&&!(i.length>l||s===o);s=Ma.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+t.substr(1)%12==0?"y":"m";else if(t>=va&&i<=10||t>=15*va)e._tickround="d";else if(t>=ma&&i<=16||t>=ya)e._tickround="M";else if(t>=xa&&i<=19||t>=ma)e._tickround="S";else{var o=e.l2r(r+t).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(n(t)||"L"===t.charAt(0)){var l=e.range.map(e.r2d||Number);n(t)||(t=Number(t.substr(1))),e._tickround=2-Math.floor(Math.log(t)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(Ba(e.exponentformat)&&!ja(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function Ra(e,t,n){var r=e.tickfont||{};return{x:t,dx:0,dy:0,text:n||"",fontSize:r.size,font:r.family,fontColor:r.color}}Ma.autoTicks=function(e,t){var r;function a(e){return Math.pow(e,Math.floor(Math.log(t)/Math.LN10))}if("date"===e.type){e.tick0=rt.dateTick0(e.calendar);var i=2*t;i>pa?(t/=pa,r=a(10),e.dtick="M"+12*Na(t,r,Ca)):i>ga?(t/=ga,e.dtick="M"+Na(t,1,Sa)):i>va?(e.dtick=Na(t,va,za),e.tick0=rt.dateTick0(e.calendar,!0)):i>ya?e.dtick=Na(t,ya,Sa):i>ma?e.dtick=Na(t,ma,Oa):i>xa?e.dtick=Na(t,xa,Oa):(r=a(10),e.dtick=Na(t,r,Ca))}else if("log"===e.type){e.tick0=0;var o=rt.simpleMap(e.range,e.r2l);if(t>.7)e.dtick=Math.ceil(t);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/t);t=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=a(10),e.dtick="L"+Na(t,r,Ca)}else e.dtick=t>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(t,1))):"angular"===e._id?(e.tick0=0,r=1,e.dtick=Na(t,r,Ea)):(e.tick0=0,r=a(10),e.dtick=Na(t,r,Ca));if(0===e.dtick&&(e.dtick=1),!n(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},Ma.tickIncrement=function(t,r,a,i){var o=a?-1:1;if(n(r))return t+o*r;var l=r.charAt(0),s=o*Number(r.substr(1));if("M"===l)return rt.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var c="D2"===r?Da:Pa,u=t+.01*o,d=rt.roundUp(rt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,d),1))/Math.LN10}throw"unrecognized dtick "+String(r)},Ma.tickFirst=function(t){var r=t.r2l||Number,a=rt.simpleMap(t.range,r),i=a[1]"+l,e._prevDateHead=l));t.text=s}(e,o,r,s):"log"===e.type?function(e,t,r,a,i){var o=e.dtick,l=t.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))t.text=qa(Math.pow(10,l),e,i,a);else if(n(o)||"D"===o.charAt(0)&&rt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||Ba(e.exponentformat)&&ja(c)?(t.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+ba+-c+"",t.fontSize*=1.25):(t.text=qa(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(t.dy-=t.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);t.text=String(Math.round(Math.pow(10,rt.mod(l,1)))),t.fontSize*=.75}if("D1"===e.dtick){var u=String(t.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?t.dx-=t.fontSize/4:(t.dy+=t.fontSize/2,t.dx+=(e.range[1]>e.range[0]?1:-1)*t.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var n=e._categories[Math.round(t.x)];void 0===n&&(n="");t.text=String(n)}(e,o):"angular"===e._id?function(e,t,n,r,a){if("radians"!==e.thetaunit||n)t.text=qa(t.x,e,a,r);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var n=function(e){var n=1;for(;!t(Math.round(e*n)/n,e);)n*=10;return n}(e),r=e*n,a=Math.abs(function e(n,r){return t(r,0)?n:e(r,n%r)}(r,n));return[Math.round(r/a),Math.round(n/a)]}(i);if(o[1]>=100)t.text=qa(rt.deg2rad(t.x),e,a,r);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=ba+t.text)}}}}(e,o,r,s,a):function(e,t,n,r,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=qa(t.x,e,a,r)}(e,o,0,s,a),e.tickprefix&&!f(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!f(e.showticksuffix)&&(o.text+=e.ticksuffix),o},Ma.hoverLabelText=function(e,t,n){if(n!==_a&&n!==t)return Ma.hoverLabelText(e,t)+" - "+Ma.hoverLabelText(e,n);var r="log"===e.type&&t<=0,a=Ma.tickText(e,e.c2l(r?-t:t),"hover").text;return r?0===t?"0":ba+a:a};var Fa=["f","p","n","\u03bc","m","","k","M","G","T"];function Ba(e){return"SI"===e||"B"===e}function ja(e){return e>14||e<-15}function qa(e,t,r,a){var i=e<0,o=t._tickround,l=r||t.exponentformat||"B",s=t._tickexponent,c=Ma.getTickFormat(t),u=t.separatethousands;if(a){var d={exponentformat:l,dtick:"none"===t.showexponent?t.dtick:n(e)&&Math.abs(e)||1,range:"none"===t.showexponent?t.range.map(t.r2d):[0,e||1]};Ia(d),o=(Number(d._tickround)||0)+4,s=d._tickexponent,t.hoverformat&&(c=t.hoverformat)}if(c)return t._numFormat(c)(e).replace(/-/g,ba);var f,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+f+"":"B"===l&&9===s?e+="B":Ba(l)&&(e+=Fa[s/3+5]));return i?ba+e:e}function Ha(e,t){for(var n=0;n=0,i=c(e,t[1])<=0;return(n||a)&&(r||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(r))){n=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(r=1;r rect").call(Yn.setTranslate,0,0).call(Yn.setScale,1,1),e.plot.call(Yn.setTranslate,t._offset,n._offset).call(Yn.setScale,1,1);var r=e.plot.selectAll(".scatterlayer .trace");r.selectAll(".point").call(Yn.setPointGroupScale,1,1),r.selectAll(".textpoint").call(Yn.setTextPointsScale,1,1),r.call(Yn.hideOutsideRangePoints,e)}function g(e,n){var r,a,o,l=d[e.xaxis._id],s=d[e.yaxis._id],c=[];if(l){a=(r=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-n)+n*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],f=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[2]=e.xaxis._length*(1-n+n*f/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(r=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-n)+n*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[3]=e.yaxis._length*(1-n+n*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,n){var r,a=[];for(a=[e._id,n._id],r=0;r rect").call(Yn.setTranslate,_,w).call(Yn.setScale,1/x,1/b),e.plot.call(Yn.setTranslate,T,A).call(Yn.setScale,x,b).selectAll(".points").selectAll(".point").call(Yn.setPointGroupScale,1/x,1/b),e.plot.selectAll(".points").selectAll(".textpoint").call(Yn.setTextPointsScale,1/x,1/b)}a&&(l=a());var v=e.ease(r.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(u),u=null,function(){for(var e={},n=0;nr.duration?(function(){for(var e={},n=0;n0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},mi.prototype.on=mi.prototype.addListener,mi.prototype.once=function(e,t){if(!bi(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},mi.prototype.removeListener=function(e,t){var n,r,a,i;if(!bi(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||bi(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(_i(n)){for(i=a;i-- >0;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},mi.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(bi(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},mi.prototype.listeners=function(e){return this._events&&this._events[e]?bi(this._events[e])?[this._events[e]]:this._events[e].slice():[]},mi.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(bi(t))return 1;if(t)return t.length}return 0},mi.listenerCount=function(e,t){return e.listenerCount(t)};var ki,Mi=xi.EventEmitter,Ti={init:function(e){if(e._ev instanceof Mi)return e;var t=new Mi,n=new Mi;return e._ev=t,e._internalEv=n,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=n.on.bind(n),e._internalOnce=n.once.bind(n),e._removeInternalListener=n.removeListener.bind(n),e._removeAllInternalListeners=n.removeAllListeners.bind(n),e.emit=function(r,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(r,a),t.emit(r,a),n.emit(r,a)},e},triggerHandler:function(e,t,n){var r,a;"undefined"!=typeof jQuery&&(r=jQuery(e).triggerHandler(t,n));var i=e._ev;if(!i)return r;var o=i._events[t];if(!o)return r;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Ci.getCursor=function(e,t,n,r){return e="left"===n?0:"center"===n?1:"right"===n?2:rt.constrain(Math.floor(3*e),0,2),t="bottom"===r?0:"middle"===r?1:"top"===r?2:rt.constrain(Math.floor(3*t),0,2),vi[t][e]},Ci.unhover=ki.wrapped,Ci.unhoverRaw=ki.raw,Ci.init=function(e){var t,n,r,a,i,o,l,s,c=e.gd,u=1,d=h.DBLCLICKDELAY,f=e.element;c._mouseDownTime||(c._mouseDownTime=0),f.style.pointerEvents="all",f.onmousedown=g,hi?(f._ontouchstart&&f.removeEventListener("touchstart",f._ontouchstart),f._ontouchstart=g,f.addEventListener("touchstart",g,{passive:!1})):f.ontouchstart=g;var p=e.clampFn||function(e,t,n){return Math.abs(e)d&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var n;try{n=new MouseEvent("click",t)}catch(e){var r=Oi(t);(n=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,r[0],r[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(n)}!function(e){e._dragging=!1,e._replotPending&&D.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Ci.coverSlip=Si;function zi(e,t,n,r){r=r||rt.identity,Array.isArray(e)&&(t[0][n]=r(e))}var Pi={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},flat:function(e,t){for(var n=new Array(e.length),r=0;r=0&&n.index-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.extraText&&(s+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),""===s&&(""===l&&n.remove(),s=l);var g=n.select("text.nums").call(Yn.font,t.fontFamily||u,t.fontSize||d,t.fontColor||h).text(s).attr("data-notex",1).call(bn.positionText,0,0).call(bn.convertToTspans,r),y=n.select("text.name"),m=0;l&&l!==s?(y.call(Yn.font,t.fontFamily||u,t.fontSize||d,f).text(l).attr("data-notex",1).call(bn.positionText,0,0).call(bn.convertToTspans,r),m=y.node().getBoundingClientRect().width+2*Yi):(y.remove(),n.select("rect").remove()),n.select("path").style({fill:f,stroke:h});var k,M,T=g.node().getBoundingClientRect(),A=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),O=T.width+Gi+Yi+m;t.ty0=x-T.top,t.bx=T.width+2*Yi,t.by=T.height+2*Yi,t.anchor="start",t.txwidth=T.width,t.tx2width=m,t.offset=0,i?(t.pos=A,k=L+S/2+O<=_,M=L-S/2-O>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=A+C/2+O<=b,M=A-C/2-O>=0,"left"!==t.idealAlign&&k||!M?k?(A+=C/2,t.anchor="start"):t.anchor="middle":(A-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),n.attr("transform","translate("+A+","+L+")"+(i?"rotate("+ji+")":""))}),C}function Xi(t,n){t.each(function(t){var r=e.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(Gi+Yi),s=l+o*(t.txwidth+Yi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+Yi),n&&(u*=-Ui,c=t.offset*Vi),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*Gi+c)+","+(Gi+u)+"v"+(t.by/2-Gi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*Gi+c)+"V"+(u-Gi)+"Z"),i.call(bn.positionText,l+c,u+t.ty0-t.by/2+Yi),t.tx2width&&(r.select("text.name").call(bn.positionText,s+o*Yi+c,u+t.ty0-t.by/2+Yi),r.select("rect").call(Yn.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function Wi(e,t){var n=e.index,r=e.trace||{},a=e.cd[0],i=e.cd[n]||{},o=Array.isArray(n)?function(e,t){return rt.castOption(a,n,e)||rt.extractOption({},r,"",t)}:function(e,t){return rt.extractOption(i,r,e,t)};function l(t,n,r){var a=o(n,r);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=rt.constrain(e.x0,0,e.xa._length),e.x1=rt.constrain(e.x1,0,e.xa._length),e.y0=rt.constrain(e.y0,0,e.ya._length),e.y1=rt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:ha.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:ha.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=ha.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+ha.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=ha.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+ha.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function Qi(e,t){var n,r,a=t.container,i=t.fullLayout,o=t.event,l=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||l){var u=xt.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var d,f,h=e.hLinePoint;n=h&&h.xa,"cursor"===(r=h&&h.ya).spikesnap?(d=o.pointerX,f=o.pointerY):(d=n._offset+h.x,f=r._offset+h.y);var p,g,v=s.readability(h.color,u)<1.5?xt.contrast(u):h.color,y=r.spikemode,m=r.spikethickness,x=r.spikecolor||v,b=r._boundingBox,_=(b.left+b.right)/2V.width||q<0||q>V.height)return Li.unhoverRaw(t,r);r.pointerX=r.offsetX,r.pointerY=r.offsetY}if(_="xval"in r?Pi.flat(o,r.xval):Pi.p2c(h,j),w="yval"in r?Pi.flat(o,r.yval):Pi.p2c(p,q),!n(_[0])||!n(w[0]))return rt.warn("Fx.hover failed",r,t),Li.unhoverRaw(t,r)}var U=1/0;for(M=0;ME&&(R.splice(0,E),U=R[0].distance),u&&0!==I&&0===R.length){P.distance=I,P.index=!1;var W=A._module.hoverPoints(P,O,z,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=I})),W&&W.length){var Q,J=W.filter(function(e){return e.xa.showspikes});if(J.length){var $=J[0];n($.x0)&&n($.y0)&&(Q=ne($),(!B.vLinePoint||B.vLinePoint.spikeDistance>Q.spikeDistance)&&(B.vLinePoint=Q))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];n(ee.x0)&&n(ee.y0)&&(Q=ne(ee),(!B.hLinePoint||B.hLinePoint.spikeDistance>Q.spikeDistance)&&(B.hLinePoint=Q))}}}}function te(e,t){for(var n,r=null,a=1/0,i=0;i1,ge=xt.combine(l.plot_bgcolor||xt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=Zi(R,ve,t);if(function(e,t,n){var r,a,i,o,l,s,c,u=0,d=e.map(function(e,r){var a=e[t];return[{i:r,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?Hi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?n.width:n.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function f(e){var t=e[0],n=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=n.pos+n.dp+n.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;r=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;r=!1}if(r){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!r&&u<=e.length;){for(u++,r=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),d.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;r=!1}else o++}d.forEach(f)}for(o=d.length-1;o>=0;o--){var y=d[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(R,pe?"xa":"ya",l),Xi(ye,pe),r.target&&r.target.tagName){var me=D.getComponentMethod("annotations","hasClickToShow")(t,fe);Fi(e.select(r.target),me?"pointer":"")}if(!r.target||i||!function(e,t,n){if(!n||n.length!==e._hoverdata.length)return!0;for(var r=n.length-1;r>=0;r--){var a=n[r],i=e._hoverdata[r];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,de))return;de&&t.emit("plotly_unhover",{event:r,points:de});t.emit("plotly_hover",{event:r,points:t._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(t,r,a,i)})},Bi.loneHover=function(t,n){var r={color:t.color||xt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(n.container),i=n.outerContainer?e.select(n.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:n.bgColor||xt.background,container:a,outerContainer:i},l=Zi([r],o,n.gd);return Xi(l,o.rotateLabels),l.node()};var $i=Bi.hover,Ki=function(e,t,n,r){n("hoverlabel.bgcolor",(r=r||{}).bgcolor),n("hoverlabel.bordercolor",r.bordercolor),n("hoverlabel.namelength",r.namelength),rt.coerceFont(n,"hoverlabel.font",r.font)},eo=L({editType:"none"});eo.family.dflt=yi.HOVERFONT,eo.size.dflt=yi.HOVERFONTSIZE;var to={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:eo,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var no={moduleType:"component",name:"fx",constants:yi,schema:{layout:to},attributes:C,layoutAttributes:to,supplyLayoutGlobalDefaults:function(e,t){Ki(0,0,function(n,r){return rt.coerce(e,t,to,n,r)})},supplyDefaults:function(e,t,n,r){Ki(0,0,function(n,r){return rt.coerce(e,t,C,n,r)},r.hoverlabel)},supplyLayoutDefaults:function(e,t,n){function r(n,r){return rt.coerce(e,t,to,n,r)}var a;r("dragmode"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,n=0;n.01?T:function(e,t){return Math.abs(e-t)>=2?T(e):e>t?Math.ceil(e):Math.floor(e)};p=k(p,h=k(h,p)),v=k(v,g=k(g,v))}var M=e.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+h+","+g+"V"+v+"H"+p+"V"+g+"Z").call(Yn.setClipUrl,r.layerClipId),function(e,t,n,r,a,i,o,l){var s;function c(t,n,r){var a=t.append("text").text(n).attr({class:"bartext bartext-"+s,transform:"","text-anchor":"middle","data-notex":1}).call(Yn.font,r).call(bn.convertToTspans,e);return a}var u=n[0].trace,d=u.orientation,f=function(e,t){var n=mo(e.text,t);return xo(so,n)}(u,r);if(!f)return;if("none"===(s=function(e,t){var n=mo(e.textposition,t);return function(e,t,n){return e.coerceNumber&&(t=+t),-1!==e.values.indexOf(t)?t:void 0!==n?n:e.dflt}(co,n)}(u,r)))return;var h,p,g,v,y,m,x=function(e,t,n){return yo(uo,e.textfont,t,n)}(u,r,e._fullLayout.font),b=function(e,t,n){return yo(fo,e.insidetextfont,t,n)}(u,r,x),_=function(e,t,n){return yo(ho,e.outsidetextfont,t,n)}(u,r,x),w=e._fullLayout.barmode,k="stack"===w||"relative"===w,M=n[r],T=!k||M._outmost,A=Math.abs(i-a)-2*po,L=Math.abs(l-o)-2*po;"outside"===s&&(T||(s="inside"));if("auto"===s)if(T){s="inside",h=c(t,f,b),p=Yn.bBox(h.node()),g=p.width,v=p.height;var C=g>0&&v>0,S=g<=A&&v<=L,O=g<=L&&v<=A,z="h"===d?A>=g*(L/v):L>=v*(A/g);C&&(S||O||z)?s="inside":(s="outside",h.remove(),h=null)}else s="inside";if(!h&&(h=c(t,f,"outside"===s?_:b),p=Yn.bBox(h.node()),g=p.width,v=p.height,g<=0||v<=0))return void h.remove();"outside"===s?(m="both"===u.constraintext||"outside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s="h"===i?Math.abs(r-n):Math.abs(t-e);s>2*po&&(l=po);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,d,f,h,p=(a.left+a.right)/2,g=(a.top+a.bottom)/2;u=c*a.width,d=c*a.height,"h"===i?tn?(f=(e+t)/2,h=r+l+d/2):(f=(e+t)/2,h=r-l-d/2);return vo(p,g,f,h,c,!1)}(a,i,o,l,p,d,m)):(m="both"===u.constraintext||"inside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s,c,u,d,f,h,p=a.width,g=a.height,v=(a.left+a.right)/2,y=(a.top+a.bottom)/2,m=Math.abs(t-e),x=Math.abs(r-n);m>2*po&&x>2*po?(m-=2*(d=po),x-=2*d):d=0;p<=m&&g<=x?(f=!1,h=1):p<=x&&g<=m?(f=!0,h=1):pn?(c=(e+t)/2,u=r-d-s/2):(c=(e+t)/2,u=r+d+s/2);return vo(v,y,c,u,h,f)}(a,i,o,l,p,d,m));h.attr("transform",y)}(t,M,a,c,h,p,g,v),r.layerClipId&&Yn.hideOutsideRangePoint(a[c],M.select("text"),i,o,u.xcalendar,u.ycalendar)}else e.select(this).remove();function T(t){return 0===l.bargap&&0===l.bargroupgap?e.round(Math.round(t)-w,2):t}})}),D.getComponentMethod("errorbars","plot")(s,r),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Yn.setClipUrl(e.select(this),n?null:r.layerClipId)})};function vo(e,t,n,r,a,i){var o;return a<1?o="scale("+a+") ":(a=1,o=""),"translate("+(n-a*e)+" "+(r-a*t)+")"+o+(i?"rotate("+i+" "+e+" "+t+") ":"")}function yo(e,t,r,a){var i=mo((t=t||{}).family,r),o=mo(t.size,r),l=mo(t.color,r);return{family:xo(e.family,i,a.family),size:function(e,t,r){if(n(t)){t=+t;var a=e.min,i=e.max,o=void 0!==a&&ti;if(!o)return t}return void 0!==r?r:e.dflt}(e.size,o,a.size),color:function(e,t,n){return s(t).isValid()?t:void 0!==n?n:e.dflt}(e.color,l,a.color)}}function mo(e,t){var n;return Array.isArray(e)?tc+l||!n(s))&&(d=!0,Do(u,e))}for(var h=0;h1||0===i.bargap&&0===i.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(n){var r=e.select(this),a=r.selectAll("path"),i=r.selectAll("text"),o=n[0].trace;Yn.pointStyle(a,o,t),Yn.selectedPointStyle(a,o),i.each(function(t){var n,r=e.select(this);function a(e){var r=n[e];return Array.isArray(r)?r[t.i]:r}r.classed("bartext-inside")?n=o.insidetextfont:r.classed("bartext-outside")&&(n=o.outsidetextfont),n||(n=o.textfont),Yn.font(r,a("family"),a("size"),a("color"))}),Yn.selectedTextStyle(i,o)}),D.getComponentMethod("errorbars","style")(r)},Bo=m.extendFlat,jo=mn.LINE_SPACING,qo={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},Ho=function(t,n){var r={};function a(){var o=t._fullLayout,l=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var c,u,d=e.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),f=[],h=[],p="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,y=r.levels.size,m=1.001*d[0]-.001*d[1],x=1.001*d[1]-.001*d[0];for(u=0;u<1e5&&(c=r.levels.start+u*y,!(y>0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>d[0]&&c1){var H=Math.pow(10,Math.floor(Math.log(q)/Math.LN10));B*=H*rt.roundUp(q/H,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(R.tick0=0)}R.dtick=B}R.domain=[P+S,P+A-S],R.setScale();var V=o._infolayer.selectAll("g."+n).data([0]);V.enter().append("g").classed(n,!0).classed(qo.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(qo.cbbg,!0),t.append("g").classed(qo.cbfills,!0),t.append("g").classed(qo.cblines,!0),t.append("g").classed(qo.cbaxis,!0).classed(qo.crisp,!0),t.append("g").classed(qo.cbtitleunshift,!0).append("g").classed(qo.cbtitle,!0),t.append("rect").classed(qo.cboutline,!0),t.select(".cbtitle").datum(0)}),V.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");R._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var Y,Z=l.l+(r.x+L)*l.w,X=R.titlefont.size;Y="top"===r.titleside?(1-(P+A-S))*l.h+l.t+3+.75*X:(1-(P+S))*l.h+l.t-3-.25*X,ee(R._id+"title",{attributes:{x:Z,y:Y,"text-anchor":"start"}})}var W,Q,J,$=rt.syncOrAsync([Hr.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var n=V.select(".cbtitle"),a=n.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],c=n.select(".h"+R._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*jo),c?(G=Yn.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(qo.jsPlaceholder)&&(G=Yn.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)R.domain[1]-=G/l.h,i[1]*=-1;else{R.domain[0]+=G/l.h;var v=bn.lineCount(a);i[1]+=(1-v)*u}n.attr("transform","translate("+i+")"),R.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-R.domain[1]))+")"),R._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(qo.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,n){var r=[0===n?d[0]:(h[n]+h[n-1])/2,n===h.length-1?d[1]:(h[n]+h[n+1])/2].map(R.c2p).map(Math.round);n!==h.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=s(a).toHexString();e.select(this).attr({x:O,width:Math.max(k,2),y:e.min(r),height:Math.max(e.max(r)-e.min(r),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?f:[]);return m.enter().append("path").classed(qo.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+O+","+(Math.round(R.c2p(t))+r.line.width/2%1)+"h"+k).call(Yn.lineGroupStyle,r.line.width,p(t),r.line.dash)}),R._axislayer.selectAll("g."+R._id+"tick,path").remove(),R._pos=O+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),R.side="right",rt.syncOrAsync([function(){return ha.doTicks(t,R,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var n=R.titlefont.size,a=R._offset+R._length/2,i=l.l+(R.position||0)*l.w+("right"===R.side?10+n*(R.showticklabels?1:.5):-10-n*(R.showticklabels?.5:0));ee("h"+R._id+"title",{avoid:{selection:e.select(t).selectAll("g."+R._id+"tick"),side:r.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Hr.previousPromises,function(){var e=k+r.outlinewidth/2+Yn.bBox(R._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(qo.jsPlaceholder)){var a,i=U.select(".h"+R._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Yn.bBox(i).width:Yn.bBox(U.node()).right-O-l.l,e=Math.max(e,a)}var o=2*r.xpad+e+r.borderwidth+r.outlinewidth/2,s=E-N;V.select(".cbbg").attr({x:O-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:N-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(xt.fill,r.bgcolor).call(xt.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),V.selectAll(".cboutline").attr({x:O,y:N+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(s-2*r.ypad-G,2)}).call(xt.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*o;V.attr("transform","translate("+(l.l-c)+","+l.t+")"),Hr.autoMargin(t,n,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:s*({bottom:1,middle:.5}[r.yanchor]||0),b:s*({top:1,middle:.5}[r.yanchor]||0)})}],t);if($&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition)Li.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),Ii(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),Q=Li.align(z+e/l.w,M,0,1,r.xanchor),J=Li.align(P-t/l.h,A,0,1,r.yanchor);var n=Li.getCursor(Q,J,r.xanchor,r.yanchor);Ii(V,n)},doneFn:function(){Ii(V),void 0!==Q&&void 0!==J&&D.call("restyle",t,{"colorbar.x":Q,"colorbar.y":J},i().index)}});return $}function K(e,t){return rt.coerce(I,R,mt,e,t)}function ee(e,n){var r,a=i();r=D.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:R,propName:r,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),ta.draw(t,e,Bo(l,n||{}))}o._infolayer.selectAll("g."+n).remove()}function i(){var e,r,a=n.substr(2);for(e=0;e=0&&k0){var T=_[r].sort(Ko),A=T.map(el),L=A.length,C={pos:v[r],pts:T};C.min=A[0],C.max=A[L-1],C.mean=rt.mean(A,L),C.sd=rt.stdev(A,L,C.mean),C.q1=rt.interp(A,.25),C.med=rt.interp(A,.5),C.q3=rt.interp(A,.75),C.lf=Math.min(C.q1,A[Math.min(rt.findBin(2.5*C.q1-1.5*C.q3,A,!0)+1,L-1)]),C.uf=Math.max(C.q3,A[Math.max(rt.findBin(2.5*C.q3-1.5*C.q1,A),0)]),C.lo=4*C.q1-3*C.q3,C.uo=4*C.q3-3*C.q1;var S=1.57*(C.q3-C.q1)/Math.sqrt(L);C.ln=C.med-S,C.un=C.med+S,d.push(C)}return function(e,t){if(rt.isArrayOrTypedArray(t.selectedpoints))for(var n=0;n0?(d[0].t={num:s[f],dPos:y,posLetter:l,valLetter:i,labels:{med:Qo(e,"median:"),min:Qo(e,"min:"),q1:Qo(e,"q1:"),q3:Qo(e,"q3:"),max:Qo(e,"max:"),mean:"sd"===t.boxmean?Qo(e,"mean \xb1 \u03c3:"):Qo(e,"mean:"),lf:Qo(e,"lower fence:"),uf:Qo(e,"upper fence:")}},t._fullInput&&"candlestick"===t._fullInput.type&&delete d[0].t.labels,s[f]++,d):[{t:{empty:!0}}]};function $o(e,t,n){var r={text:"tx"};for(var a in r)Array.isArray(t[a])&&(e[r[a]]=t[a][n])}function Ko(e,t){return e.v-t.v}function el(e){return e.v}function tl(e,t,n,r){var a,i=n("y"),o=n("x");if(i&&i.length)a="v",o||n("x0");else{if(!o||!o.length)return void(t.visible=!1);a="h",n("y0")}D.getComponentMethod("calendars","handleTraceDefaults")(e,t,["x","y"],r),n("orientation",a)}function nl(e,t,n,r){var a=r.prefix,i=rt.coerce2(e,t,Wo,"marker.outliercolor"),o=n("marker.line.outliercolor"),l=n(a+"points",i||o?"suspectedoutliers":void 0);l?(n("jitter","all"===l?.3:0),n("pointpos","all"===l?-1.5:0),n("marker.symbol"),n("marker.opacity"),n("marker.size"),n("marker.color",t.line.color),n("marker.line.color"),n("marker.line.width"),"suspectedoutliers"===l&&(n("marker.line.outliercolor",t.marker.color),n("marker.line.outlierwidth")),n("selected.marker.color"),n("unselected.marker.color"),n("selected.marker.size"),n("unselected.marker.size"),n("text")):delete t.marker,n("hoveron"),rt.coerceSelectionMarkerOpacity(t,n)}var rl={supplyDefaults:function(e,t,n,r){function a(n,r){return rt.coerce(e,t,Wo,n,r)}tl(e,t,a,r),!1!==t.visible&&(a("line.color",(e.marker||{}).color||n),a("line.width"),a("fillcolor",xt.addOpacity(t.line.color,.5)),a("whiskerwidth"),a("boxmean"),a("notched",void 0!==e.notchwidth)&&a("notchwidth"),nl(e,t,a,{prefix:"box"}))},handleSampleDefaults:tl,handlePointsDefaults:nl};function al(e,t,n,r){var a,i,o,l,s,c,u,d,f,h,p,g,v=e.cd,y=e.xa,m=e.ya,x=v[0].trace,b=v[0].t,_="violin"===x.type,w=[],k=b.bdPos,M=function(e){return e.pos+b.bPos-c};_&&"both"!==x.side?("positive"===x.side&&(f=function(e){var t=M(e);return no.inbox(t,t+k,h)}),"negative"===x.side&&(f=function(e){var t=M(e);return no.inbox(t-k,t,h)})):f=function(e){var t=M(e);return no.inbox(t-k,t+k,h)},g=_?function(e){return no.inbox(e.span[0]-s,e.span[1]-s,h)}:function(e){return no.inbox(e.min-s,e.max-s,h)},"h"===x.orientation?(s=t,c=n,u=g,d=f,a="y",o=m,i="x",l=y):(s=n,c=t,u=f,d=g,a="x",o=y,i="y",l=m);var T=Math.min(1,k/Math.abs(o.r2c(o.range[1])-o.r2c(o.range[0])));function A(e){return(u(e)+d(e))/2}h=e.maxHoverDistance-T,p=e.maxSpikeDistance-T;var L=no.getDistanceFunction(r,u,d,A);if(no.getClosest(v,L,e),!1===e.index)return[];var C=v[e.index],S=x.line.color,O=(x.marker||{}).color;xt.opacity(S)&&x.line.width?e.color=S:xt.opacity(O)&&x.boxpoints?e.color=O:e.color=x.fillcolor,e[a+"0"]=o.c2p(C.pos+b.bPos-b.bdPos,!0),e[a+"1"]=o.c2p(C.pos+b.bPos+b.bdPos,!0),ha.tickText(o,o.c2l(C.pos),"hover").text,e[a+"LabelVal"]=C.pos;var z=a+"Spike";e.spikeDistance=A(C)*p/h,e[z]=o.c2p(C.pos,!0);var P={},D=["med","min","q1","q3","max"];(x.boxmean||(x.meanline||{}).visible)&&D.push("mean"),(x.boxpoints||x.points)&&D.push("lf","uf");for(var E=0;Ee.uf}),i=Math.max((e.max-e.min)/10,e.q3-e.q1),c=1e-9*i,u=i*dl,d=[],f=0;if(n.jitter){if(0===i)for(f=1,d=new Array(a.length),t=0;te.lo&&(m.so=!0)}return a}).enter().append("path").classed("point",!0).call(Yn.translatePoints,a,i)}function pl(t,n,r,a){var i,o,l=n.pos,s=n.val,c=a.bPos,u=a.bPosPxOffset||0;Array.isArray(a.bdPos)?(i=a.bdPos[0],o=a.bdPos[1]):(i=a.bdPos,o=a.bdPos),t.selectAll("path.mean").data(rt.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var n=l.c2p(t.pos+c,!0)+u,a=l.c2p(t.pos+c-i,!0)+u,d=l.c2p(t.pos+c+o,!0)+u,f=s.c2p(t.mean,!0),h=s.c2p(t.mean-t.sd,!0),p=s.c2p(t.mean+t.sd,!0);"h"===r.orientation?e.select(this).attr("d","M"+f+","+a+"V"+d+("sd"===r.boxmean?"m0,0L"+h+","+n+"L"+f+","+a+"L"+p+","+n+"Z":"")):e.select(this).attr("d","M"+a+","+f+"H"+d+("sd"===r.boxmean?"m0,0L"+n+","+h+"L"+a+","+f+"L"+n+","+p+"Z":""))})}var gl={plot:function(t,n,r){var a=t._fullLayout,i=n.xaxis,o=n.yaxis;n.plot.select(".boxlayer").selectAll("g.trace.boxes").data(r).enter().append("g").attr("class","trace boxes").each(function(t){var n,r,l=t[0],s=l.t,c=l.trace,u=l.node3=e.select(this),d=a._numBoxes,f="group"===a.boxmode&&d>1,h=s.dPos*(1-a.boxgap)*(1-a.boxgroupgap)/(f?d:1),p=f?2*s.dPos*((s.num+.5)/d-.5)*(1-a.boxgap):0,g=h*c.whiskerwidth;!0!==c.visible||s.empty?e.select(this).remove():("h"===c.orientation?(n=o,r=i):(n=i,r=o),s.bPos=p,s.bdPos=h,s.wdPos=g,fl(u,{pos:n,val:r},c,s),c.boxpoints&&hl(u,{x:i,y:o},c,s),c.boxmean&&pl(u,{pos:n,val:r},c,s))})},plotBoxAndWhiskers:fl,plotPoints:hl,plotBoxMean:pl},vl=function(e,t){var n,r,a=e.cd,i=e.xaxis,o=e.yaxis,l=[];if(!1===t)for(n=0;n=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}},Ml=m.extendFlat,Tl=Ml({},{z:{valType:"data_array",editType:"calc"},x:Ml({},mr.x,{impliedEdits:{xtype:"array"}}),x0:Ml({},mr.x0,{impliedEdits:{xtype:"scaled"}}),dx:Ml({},mr.dx,{impliedEdits:{xtype:"scaled"}}),y:Ml({},mr.y,{impliedEdits:{ytype:"array"}}),y0:Ml({},mr.y0,{impliedEdits:{ytype:"scaled"}}),dy:Ml({},mr.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,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",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,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"}},Qt,{autocolorscale:Ml({},Qt.autocolorscale,{dflt:!1})},{colorbar:dn}),Al=gt.dash,Ll=m.extendFlat,Cl=kl.COMPARISON_OPS2,Sl=kl.INTERVAL_OPS,Ol=mr.line,zl=Ll({z:Tl.z,x:Tl.x,x0:Tl.x0,dx:Tl.dx,y:Tl.y,y0:Tl.y0,dy:Tl.dy,text:Tl.text,transpose:Tl.transpose,xtype:Tl.xtype,ytype:Tl.ytype,zhoverformat:Tl.zhoverformat,connectgaps:Tl.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},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":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:L({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(Cl).concat(Sl),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:Ll({},Ol.color,{editType:"style+colorbars"}),width:Ll({},Ol.width,{editType:"style+colorbars"}),dash:Al,smoothing:Ll({},Ol.smoothing,{}),editType:"plot"}},Qt,{autocolorscale:Ll({},Qt.autocolorscale,{dflt:!1}),zmin:Ll({},Qt.zmin,{editType:"calc"}),zmax:Ll({},Qt.zmax,{editType:"calc"})},{colorbar:dn}),Pl=rt.extendFlat;function Dl(e,t,n){var r={type:"linear",range:[e,t]};return ha.autoTicks(r,(t-e)/(n||15)),r}var El=r.BADNUM,Nl=function(e){for(var t=0,n=0;np&&(v=Math.max(v,Math.abs(e[a][i]-h)/(g-p))))}return v}var ql=rt.isArrayOrTypedArray,Hl=function(e,t,n,r,a,i){var o,l,s,c=[],u=D.traceIs(e,"contour"),d=D.traceIs(e,"histogram"),f=D.traceIs(e,"gl2d");if(ql(t)&&t.length>1&&!d&&"category"!==i.type){var h=t.length;if(!(h<=a))return u?t.slice(0,a):t.slice(0,a+1);if(u||f)c=t.slice(0,a);else if(1===a)c=[t[0]-.5,t[0]+.5];else{for(c=[1.5*t[0]-.5*t[1]],s=1;si){var o=i-r[e];return r[e]=i,o}}return 0},max:function(e,t,r,a){var i=a[t];if(n(i)){if(i=Number(i),!n(r[e]))return r[e]=i,i;if(r[e]h&&hZl){var p=i===Gl?1:6,g=i===Gl?"M12":"M1";return function(t,n){var i=r.c2d(t,Gl,a),l=i.indexOf("-",p);l>0&&(i=i.substr(0,l));var s=r.d2c(i,0,a);if(sQl?e>Zl?e>1.1*Gl?Gl:e>1.1*Yl?Yl:Zl:e>Xl?Xl:e>Wl?Wl:Ql:Math.pow(10,Math.floor(Math.log(e)/Math.LN10))}function ts(e,t,n,r,a,i){if(r&&e>Zl){var o=ns(t,a,i),l=ns(n,a,i),s=e===Gl?0:1;return o[s]!==l[s]}return Math.floor(n/e)-Math.floor(t/e)>.1}function ns(e,t,n){var r=t.c2d(e,Gl,n).split("-");return""===r[0]&&(r.unshift(),r[0]="-"+r[0]),r}var rs=rt.cleanDate,as=r.ONEDAY,is=r.BADNUM,os=function(e,t,r){var a=t.type,i=r+"bins",o=e[i];o||(o=e[i]={});var l="date"===a?function(e){return e||0===e?rs(e,is,o.calendar):null}:function(e){return n(e)?Number(e):null};o.start=l(o.start),o.end=l(o.end);var s="date"===a?as:1,c=o.size;if(n(c))o.size=c>0?Number(c):s;else if("string"!=typeof c)o.size=s;else{var u=c.charAt(0),d=c.substr(1);((d=n(d)?Number(d):0)<=0||"date"!==a||"M"!==u||d!==Math.round(d))&&(o.size=s)}var f="autobin"+r;"boolean"!=typeof e[f]&&(e[f]=e._fullInput[f]=e._input[f]=!((o.start||0===o.start)&&(o.end||0===o.end))),e[f]||(delete e["nbins"+r],delete e._fullInput["nbins"+r])},ls={percent:function(e,t){for(var n=e.length,r=100/t,a=0;av&&l.splice(v,l.length-v),c.length>v&&c.splice(v,c.length-v),ss(t,"x",l,o,f,p,u),ss(t,"y",c,s,h,g,d);var y=[],m=[],x=[],b="string"==typeof t.xbins.size,_="string"==typeof t.ybins.size,w=[],k=[],M=b?w:t.xbins,T=_?k:t.ybins,A=0,L=[],C=[],S=t.histnorm,O=t.histfunc,z=-1!==S.indexOf("density"),P="max"===O||"min"===O?null:0,D=Ul.count,E=ls[S],N=!1,I=[],R=[],F="z"in t?t.z:"marker"in t&&Array.isArray(t.marker.color)?t.marker.color:"";F&&"count"!==O&&(N="avg"===O,D=Ul[O]);var B=t.xbins,j=f(B.start),q=f(B.end)+(j-ha.tickIncrement(j,B.size,!1,u))/1e6;for(n=j;n=0&&a=0&&i=0;i--)(o=((u[[(n=(a=d[i])[0])-1,r=a[1]]]||p)[2]+(u[[n+1,r]]||p)[2]+(u[[n,r-1]]||p)[2]+(u[[n,r+1]]||p)[2])/20)&&(l[a]=[n,r,o],d.splice(i,1),s=!0);if(!s)throw"findEmpties iterated with no new neighbors";for(a in l)u[a]=l[a],c.push(l[a])}return c.sort(function(e,t){return t[2]-e[2]})}(c),t._interpz=function(e,t,n){var r,a,i=1;if(Array.isArray(n))for(r=0;r.01;r++)i=jl(e,t,Bl(i));return i>.01&&rt.log("interp2d didn't converge quickly",i),e}(c,t._emptypoints,t._interpz))),"fast"===y)if("log"===f.type||"log"===h.type)m("log axis found");else if(!g){if(r.length){var x=(r[r.length-1]-r[0])/(r.length-1),b=Math.abs(x/100);for(u=0;ub){m("x scale is not linear");break}}if(o.length&&"fast"===y){var _=(o[o.length-1]-o[0])/(o.length-1),w=Math.abs(_/100);for(u=0;uw){m("y scale is not linear");break}}}var k=Nl(c),M="scaled"===t.xtype?"":r,T=Hl(t,M,a,i,k,f),A="scaled"===t.ytype?"":o,L=Hl(t,A,l,s,c.length,h);v||(ha.expand(f,T),ha.expand(h,L));var C={x:T,y:L,z:c,text:t.text};if(M&&M.length===T.length-1&&(C.xCenter=M),A&&A.length===L.length-1&&(C.yCenter=A),g&&(C.xRanges=d.xRanges,C.yRanges=d.yRanges,C.pts=d.pts),p&&"constraint"===t.contours.type||$t(t,c,"","z"),p&&t.contours&&"heatmap"===t.contours.coloring){var S={type:"contour"===t.type?"heatmap":"histogram2d",xcalendar:t.xcalendar,ycalendar:t.ycalendar};C.xfill=Hl(S,M,a,i,k,f),C.yfill=Hl(S,A,l,s,c.length,h)}return[C]},hs=function(e,t){var n=fs(e,t);return function(e){var t=e.contours;if(e.autocontour){var n=Dl(e.zmin,e.zmax,e.ncontours);t.size=n.dtick,t.start=ha.tickFirst(n),n.range.reverse(),t.end=ha.tickFirst(n),t.start===e.zmin&&(t.start+=t.size),t.end===e.zmax&&(t.end-=t.size),t.start>t.end&&(t.start=t.end=(t.start+t.end)/2),e._input.contours||(e._input.contours={}),Pl(e._input.contours,{start:t.start,end:t.end,size:t.size}),e._input.autocontour=!0}else if("constraint"!==t.type){var r,a=t.start,i=t.end,o=e._input.contours;a>i&&(t.start=o.start=i,i=t.end=o.end=a,a=t.start),t.size>0||(r=a===i?1:Dl(a,i,e.ncontours).dtick,o.size=t.size=r)}}(t),n},ps=function(e){return e.end+e.size/1e6},gs=function(t){var n=t.contours,r=n.start,a=ps(n),i=n.size||1,o=Math.floor((a-r)/i)+1,l="lines"===n.coloring?0:1;isFinite(i)||(i=1,o=1);var s,c,u=t.colorscale,d=u.length,f=new Array(d),h=new Array(d);if("heatmap"===n.coloring){for(t.zauto&&!1===t.autocontour&&(t.zmin=r-i/2,t.zmax=t.zmin+o*i),c=0;c2?t.value=t.value.slice(2):0===t.length?t.value=[0,1]:t.length<2?(r=parseFloat(t.value[0]),t.value=[r,r+1]):t.value=[parseFloat(t.value[0]),parseFloat(t.value[1])]:n(t.value)&&(r=parseFloat(t.value),t.value=[r,r+1])):(e("contours.value",0),n(t.value)||(Array.isArray(t.value)?t.value=parseFloat(t.value[0]):t.value=0))}(r,u),"="===d?l=u.showlines=!0:(l=r("contours.showlines"),c=r("fillcolor",ms((e.line||{}).color||i,.5))),l)&&(s=r("line.color",c&&xs(c)?ms(t.fillcolor,1):i),r("line.width",2),r("line.dash"));r("line.smoothing"),ys(r,a,s,o)};var ks=function(e,t,n,r){var a=r("contours.start"),i=r("contours.end"),o=!1===a||!1===i,l=n("contours.size");!(o?t.autocontour=!0:n("autocontour",!1))&&l||n("ncontours")},Ms=function(e,t,n,r,a){var i,o=n("contours.coloring"),l="";"fill"===o&&(i=n("contours.showlines")),!1!==i&&("lines"!==o&&(l=n("line.color","#000")),n("line.width",.5),n("line.dash")),"none"!==o&&hn(e,t,r,n,{prefix:"",cLetter:"z"}),n("line.smoothing"),ys(n,r,l,a)},Ts=rt.isArrayOrTypedArray,As=function(e,t,r,a,i,o){var l,s,c=r("z");if(i=i||"x",o=o||"y",void 0===c||!c.length)return 0;if(Rl(e)){if(l=r(i),s=r(o),!l||!s)return 0}else{if(l=Ls(i,r),s=Ls(o,r),!function(e){for(var t,r=!0,a=!1,i=!1,o=0;o0&&(a=!0);for(var l=0;l=v[0].length||c<0||c>v.length)return}else{if(no.inbox(t-p[0],t-p[p.length-1],0)>0||no.inbox(n-g[0],n-g[g.length-1],0)>0)return;if(i){var M;for(w=[2*p[0]-p[1]],M=1;M":d.value>f&&(l.prefixBoundary=!0);break;case"<":d.valuef)&&(l.prefixBoundary=!0);break;case"][":i=Math.min.apply(null,d.value),o=Math.max.apply(null,d.value),if&&(l.prefixBoundary=!0)}},zs={BOTTOMSTART:[1,9,13,104,713],TOPSTART:[4,6,7,104,713],LEFTSTART:[8,12,14,208,1114],RIGHTSTART:[2,3,11,208,1114],NEWDELTA:[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],CHOOSESADDLE:{104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},SADDLEREMAINDER:{1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11},LABELDISTANCE:2,LABELINCREASE:10,LABELMIN:3,LABELMAX:10,LABELOPTIMIZER:{EDGECOST:1,ANGLECOST:1,NEIGHBORCOST:5,SAMELEVELFACTOR:10,SAMELEVELDISTANCE:5,MAXCOST:100,INITIALSEARCHPOINTS:10,ITERATIONS:5}},Ps=function(e,t){var n,r,a,i=function(e){return e.reverse()},o=function(e){return e};switch(t){case"=":case"<":return e;case">":for(1!==e.length&&rt.warn("Contour data invalid for the specified inequality operation."),r=e[0],n=0;n":Rs(">"),"<":Rs("<"),"=":Rs("=")};function Ns(e,t){var r,a=Array.isArray(t);function i(e){return n(e)?+e:null}return-1!==kl.COMPARISON_OPS2.indexOf(e)?r=i(a?t[0]:t):-1!==kl.INTERVAL_OPS.indexOf(e)?r=a?[i(t[0]),i(t[1])]:[i(t),i(t)]:-1!==kl.SET_OPS.indexOf(e)&&(r=a?t.map(i):[i(t)]),r}function Is(e){return function(t){t=Ns(e,t);var n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]);return{start:n,end:r,size:r-n}}}function Rs(e){return function(t){return{start:t=Ns(e,t),end:1/0,size:1/0}}}var Fs=function(e,t,n){for(var r="constraint"===e.type?Es[e._operation](e.value):e,a=r.size,i=[],o=ps(r),l=n.trace.carpetTrace,s=l?{xaxis:l.aaxis,yaxis:l.baxis,x:n.a,y:n.b}:{xaxis:t.xaxis,yaxis:t.yaxis,x:n.x,y:n.y},c=r.start;c1e3){rt.warn("Too many contours, clipping at 1000",e);break}return i},Bs=function(e,t,n){var r,a,i,o;for(t=t||.01,n=n||.01,a=0;a20&&t?208===e||1114===e?r=0===n[0]?1:-1:a=0===n[1]?1:-1:-1!==zs.BOTTOMSTART.indexOf(e)?a=1:-1!==zs.LEFTSTART.indexOf(e)?r=1:-1!==zs.TOPSTART.indexOf(e)?a=-1:r=-1;return[r,a]}(s,n,t),u=[Hs(e,t,[-c[0],-c[1]])],d=c.join(","),f=e.z.length,h=e.z[0].length;for(i=0;i<1e4;i++){if(s>20?(s=zs.CHOOSESADDLE[s][(c[0]||c[1])<0?0:1],e.crossings[l]=zs.SADDLEREMAINDER[s]):delete e.crossings[l],!(c=zs.NEWDELTA[s])){rt.log("Found bad marching index:",s,t,e.level);break}u.push(Hs(e,t,c)),t[0]+=c[0],t[1]+=c[1],js(u[u.length-1],u[u.length-2],r,a)&&u.pop(),l=t.join(",");var p=c[0]&&(t[0]<0||t[0]>h-2)||c[1]&&(t[1]<0||t[1]>f-2);if(l===o&&c.join(",")===d||n&&p)break;s=e.crossings[l]}1e4===i&&rt.log("Infinite loop in contour?");var g,v,y,m,x,b,_,w,k,M,T,A,L,C,S,O=js(u[0],u[u.length-1],r,a),z=0,P=.2*e.smoothing,D=[],E=0;for(i=1;i=E;i--)if((g=D[i])=E&&g+D[v]w&&k--,e.edgepaths[k]=T.concat(u,M));break}F||(e.edgepaths[w]=u.concat(M))}for(w=0;we?0:1)+(t[0][1]>e?0:2)+(t[1][1]>e?0:4)+(t[1][0]>e?0:8);return 5===n||10===n?e>(t[0][0]+t[0][1]+t[1][0]+t[1][1])/4?5===n?713:1114:5===n?104:208:15===n?0:n}var Gs=function(e,t,n){for(var r=0;r0;)h=l.c2p(x[y]),y--;for(h0;)v=c.c2p(b[y]),y--;if(ve.level}return n?"M"+t.join("L")+"Z":""}(e,t),u=0,d=e.edgepaths.map(function(e,t){return t}),f=!0;function h(e){return Math.abs(e[1]-t[2][1])<.01}function p(e){return Math.abs(e[0]-t[0][0])<.01}function g(e){return Math.abs(e[0]-t[2][0])<.01}for(;d.length;){for(l=Yn.smoothopen(e.edgepaths[u],e.smoothing),c+=f?l:l.replace(/^M/,"L"),d.splice(d.indexOf(u),1),n=e.edgepaths[u][e.edgepaths[u].length-1],i=-1,a=0;a<4;a++){if(!n){rt.log("Missing end?",u,e);break}for(s=n,Math.abs(s[1]-t[0][1])<.01&&!g(n)?r=t[1]:p(n)?r=t[0]:h(n)?r=t[3]:g(n)&&(r=t[2]),o=0;o=0&&(r=v,i=o):Math.abs(n[1]-r[1])<.01?Math.abs(n[1]-v[1])<.01&&(v[0]-n[0])*(r[0]-v[0])>=0&&(r=v,i=o):rt.log("endpt to newendpt is not vert. or horz.",n,r,v)}if(n=r,i>=0)break;c+="L"+r}if(i===e.edgepaths.length){rt.log("unclosed perimeter path");break}u=i,(f=-1===d.indexOf(u))&&(u=d[0],c+="Z")}for(u=0;ur.center?r.right-o:o-r.left)/(c+Math.abs(Math.sin(s)*i)),f=(l>r.middle?r.bottom-l:l-r.top)/(Math.abs(u)+Math.cos(s)*i);if(d<1||f<1)return 1/0;var h=Js.EDGECOST*(1/(d-1)+1/(f-1));h+=Js.ANGLECOST*s*s;for(var p=o-c,g=l-u,v=o+c,y=l+u,m=0;m2*Js.MAXCOST)break;f&&(o/=2),l=(i=s-o/2)+1.5*o}if(d<=Js.MAXCOST)return c},Qs.addLabelData=function(e,t,n,r){var a=t.width/2,i=t.height/2,o=e.x,l=e.y,s=e.theta,c=Math.sin(s),u=Math.cos(s),d=a*u,f=i*c,h=a*c,p=-i*u,g=[[o-d-f,l-h-p],[o+d-f,l+h-p],[o+d+f,l+h+p],[o-d+f,l-h+p]];n.push({text:t.text,x:o,y:l,dy:t.dy,theta:s,level:t.level,width:t.width,height:t.height}),r.push(g)},Qs.drawLabels=function(t,n,r,a,i){var o=t.selectAll("text").data(n,function(e){return e.text+","+e.x+","+e.y+","+e.theta});if(o.exit().remove(),o.enter().append("text").attr({"data-notex":1,"text-anchor":"middle"}).each(function(t){var n=t.x+Math.sin(t.theta)*t.dy,a=t.y-Math.cos(t.theta)*t.dy;e.select(this).text(t.text).attr({x:n,y:a,transform:"rotate("+180*t.theta/Math.PI+" "+n+" "+a+")"}).call(bn.convertToTspans,r)}),i){for(var l="",s=0;s1)for(var n=1;n=0,p=n.indexOf("end")>=0,g=c.backoff*d+r.standoff,v=u.backoff*f+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}n._w=C,n._h=S;for(var E=!1,N=["x","y"],I=0;I1)&&(U===V?((K=G.r2fraction(n["a"+H]))<0||K>1)&&(E=!0):E=!0,E))continue;R=G._offset+G.r2p(n[H]),j=.5}else"x"===H?(B=n[H],R=u.l+u.w*B):(B=1-n[H],R=u.t+u.h*B),j=n.showarrow?.5:B;if(n.showarrow){$.head=R;var ee=n["a"+H];q=Z*P(.5,n.xanchor)-X*P(.5,n.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=q):($.tail=R+ee,F=q+ee),$.text=$.tail+q;var te=c["x"===H?"width":"height"];if("paper"===V&&($.head=rt.constrain($.head,1,te-1)),"pixel"===U){var ne=-Math.max($.tail-3,$.text),re=Math.min($.tail+3,$.text)-te;ne>0?($.tail+=ne,$.text+=ne):re>0&&($.tail-=re,$.text-=re)}$.tail+=J,$.head+=J}else F=q=W*P(j,Q),$.text=R+q;$.text+=J,q+=J,F+=J,n["_"+H+"padplus"]=W/2+F,n["_"+H+"padminus"]=W/2-F,n["_"+H+"size"]=W,n["_"+H+"shift"]=q}if(E)x.remove();else{var ae=0,ie=0;if("left"!==n.align&&(ae=(C-_)*("center"===n.align?.5:1)),"top"!==n.valign&&(ie=(S-A)*("middle"===n.valign?.5:1)),l)r.select("svg").attr({x:w+ae-1,y:w+ie}).call(Yn.setClipUrl,M?f:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(bn.positionText,le,oe).call(Yn.setClipUrl,M?f:null)}T.select("rect").call(Yn.setRect,w,w,C,S),k.call(Yn.setRect,b/2,b/2,O-b,z-b),x.call(Yn.setTranslate,Math.round(h.x.text-O/2),Math.round(h.y.text-z/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,r){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,f=h.x.tail+e,y=h.y.tail+r,m=h.x.text+e,b=h.y.text+r,_=rt.rotationXYMatrix(p,m,b),w=rt.apply2DTransform(_),M=rt.apply2DTransform2(_),T=+k.attr("width"),A=+k.attr("height"),L=m-.5*T,C=L+T,S=b-.5*A,O=S+A,z=[[L,S,L,O],[L,O,C,O],[C,O,C,S],[C,S,L,S]].map(M);if(!z.reduce(function(e,t){return e^!!rt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){z.forEach(function(e){var t=rt.segmentsIntersect(f,y,l,c,e[0],e[1],e[2],e[3]);t&&(f=t.x,y=t.y)});var P=n.arrowwidth,E=n.arrowcolor,N=n.arrowside,I=g.append("g").style({opacity:xt.opacity(E)}).classed("annotation-arrow-g",!0),R=I.append("path").attr("d","M"+f+","+y+"L"+l+","+c).style("stroke-width",P+"px").call(xt.stroke,xt.rgb(E));if(Lc(R,N,n),d.annotationPosition&&R.node().parentNode&&!a){var F=l,B=c;if(n.standoff){var j=Math.sqrt(Math.pow(l-f,2)+Math.pow(c-y,2));F+=n.standoff*(f-l)/j,B+=n.standoff*(y-c)/j}var q,H,V,U=I.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(f-F)+","+(y-B),transform:"translate("+F+","+B+")"}).style("stroke-width",P+6+"px").call(xt.stroke,"rgba(0,0,0,0)").call(xt.fill,"rgba(0,0,0,0)");Li.init({element:U.node(),gd:t,prepFn:function(){var e=Yn.getTranslate(x);H=e.x,V=e.y,q={},i&&i.autorange&&(q[i._name+".autorange"]=!0),o&&o.autorange&&(q[o._name+".autorange"]=!0)},moveFn:function(e,t){var r=w(H,V),a=r[0]+e,l=r[1]+t;x.call(Yn.setTranslate,a,l),q[s+".x"]=i?i.p2r(i.r2p(n.x)+e):n.x+e/u.w,q[s+".y"]=o?o.p2r(o.r2p(n.y)+t):n.y-t/u.h,n.axref===n.xref&&(q[s+".ax"]=i.p2r(i.r2p(n.ax)+e)),n.ayref===n.yref&&(q[s+".ay"]=o.p2r(o.r2p(n.ay)+t)),I.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){D.call("relayout",t,q);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(n.showarrow&&ue(0,0),y)Li.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var r="pointer";if(n.showarrow)n.axref===n.xref?se[s+".ax"]=i.p2r(i.r2p(n.ax)+e):se[s+".ax"]=n.ax+e,n.ayref===n.yref?se[s+".ay"]=o.p2r(o.r2p(n.ay)+t):se[s+".ay"]=n.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(n.x)+e);else{var l=n._xsize/u.w,c=n.x+(n._xshift-n.xshift)/u.w-l/2;se[s+".x"]=Li.align(c+e/u.w,l,0,1,n.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(n.y)+t);else{var d=n._ysize/u.h,f=n.y-(n._yshift+n.yshift)/u.h-d/2;se[s+".y"]=Li.align(f-t/u.h,d,0,1,n.yanchor)}i&&o||(r=Li.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],n.xanchor,n.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),Ii(x,r)},doneFn:function(){Ii(x),D.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var zc=Cc.draw;function Pc(e){var t=e._fullLayout;rt.filterVisible(t.annotations).forEach(function(t){var n,r,a,i,o=ha.getFromId(e,t.xref),l=ha.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(n=s+t.xshift,r=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(ha.expand(o,[o.r2c(t.x)],{ppadplus:n,ppadminus:r}),ha.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,ha.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,n,a),ppadminus:Math.max(t._xpadminus,r,i)}))),l&&l.autorange&&(n=s-t.yshift,r=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(ha.expand(l,[l.r2c(t.y)],{ppadplus:n,ppadminus:r}),ha.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,ha.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,n,a),ppadminus:Math.max(t._ypadminus,r,i)})))})}var Dc={hasClickToShow:function(e,t){var n=Ec(e,t);return n.on.length>0||n.explicitOff.length>0},onClick:function(e,t){var n,r=Ec(e,t),a=r.on,i=r.off.concat(r.explicitOff),o={};if(!a.length&&!i.length)return;for(n=0;n1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=Gc(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*n[0],t.yaxis.r2l(i.y)*n[1],t.zaxis.r2l(i.z)*n[2]]),Yc(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var Wc={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},Qc=function(e){var t=e.type,n=e.symmetric;if("data"===t){var r=e.array||[];if(n)return function(e,t){var n=+r[t];return[n,n]};var a=e.arrayminus||[];return function(e,t){var n=+r[t],i=+a[t];return isNaN(n)&&isNaN(i)?[NaN,NaN]:[i||0,n||0]}}var i=Jc(t,e.value),o=Jc(t,e.valueminus);return n||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function Jc(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var $c=function(e){for(var t=e.calcdata,n=0;n0;t.each(function(t){var s,c=t[0].trace,u=c.error_x||{},d=c.error_y||{};c.ids&&(s=function(e){return e.id});var f=Gn.hasMarkers(c)&&c.marker.maxdisplayed>0;d.visible||u.visible||(t=[]);var h=e.select(this).selectAll("g.errorbar").data(t,s);if(h.exit().remove(),t.length){u.visible||h.selectAll("path.xerror").remove(),d.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Yn.setClipUrl(h,r.layerClipId),h.each(function(t){var r=e.select(this),s=function(e,t,r){var a={x:t.c2p(e.x),y:r.c2p(e.y)};return void 0!==e.yh&&(a.yh=r.c2p(e.yh),a.ys=r.c2p(e.ys),n(a.ys)||(a.noYS=!0,a.ys=r.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=t.c2p(e.xh),a.xs=t.c2p(e.xs),n(a.xs)||(a.noXS=!0,a.xs=t.c2p(e.xs,!0))),a}(t,i,o);if(!f||t.vis){var c,h=r.select("path.yerror");if(d.visible&&n(s.x)&&n(s.yh)&&n(s.ys)){var p=d.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=r.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=r.select("path.xerror");if(u.visible&&n(s.y)&&n(s.xh)&&n(s.xs)){var v=(u.copy_ystyle?d:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=r.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var n=t[0].trace,r=n.error_y||{},a=n.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(xt.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(xt.stroke,a.color)})},hoverInfo:function(e,t,n){(t.error_y||{}).visible&&(n.yerr=e.yh-e.y,t.error_y.symmetric||(n.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(n.xerr=e.xh-e.x,t.error_x.symmetric||(n.xerrneg=e.x-e.xs))}};var au={},iu=m.extendFlat;au.attributes=function(e,t){e=e||{},t=t||{};var n={valType:"info_array",editType:e.editType,items:[{valType:"number",min:0,max:1,editType:e.editType},{valType:"number",min:0,max:1,editType:e.editType}],dflt:[0,1]},r=(e.name&&e.name,e.trace,t.description&&t.description,{x:iu({},n,{}),y:iu({},n,{}),editType:e.editType});return e.noGridCell||(r.row={valType:"integer",min:0,dflt:0,editType:e.editType},r.column={valType:"integer",min:0,dflt:0,editType:e.editType}),r},au.defaults=function(e,t,n,r){var a=r&&r.x||[0,1],i=r&&r.y||[0,1],o=t.grid;if(o){var l=n("domain.column");void 0!==l&&(l1){i||o||l||"independent"===f("pattern")&&(i=!0),s._hasSubplotGrid=i;var d="top to bottom"===f("roworder");s._domains={x:uu("x",f,i?.2:.1,u),y:uu("y",f,i?.3:.1,c,d)}}}function f(e,t){return rt.coerce(n,s,cu,e,t)}},contentDefaults:function(e,t){var n=t.grid;if(n&&n._domains){var r,a,i,o,l,s,c,u=e.grid,d=t._subplots,f=n._hasSubplotGrid,h=n.rows,p=n.columns,g="independent"===n.pattern,v=n._axisMap={};if(f){var y=u.subplots||[];s=n.subplots=new Array(h);var m=1;for(r=0;r=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},xu={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},bu=!0,_u=function(e,t,n){if(!t._dragged&&!t._editing){var r,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,d=c.trace,f=d.legendgroup,h={},p=[],g=[],v=[];if(1===n&&bu&&t.data&&t._context.showTips?(rt.notifier(rt._(t,"Double-click on legend to isolate one trace"),"long"),bu=!1):bu=!1,D.traceIs(d,"pie")){var y=c.label,m=s.indexOf(y);1===n?-1===m?s.push(y):s.splice(m,1):2===n&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),D.call("relayout",t,"hiddenlabels",s)}else{var x,b=f&&f.length,_=[];if(b)for(r=0;rn[1])return n[1]}return a}function d(e){return e[0]}if(l||s||c){var f={},h={};l&&(f.mc=u("marker.color",d),f.mo=u("marker.opacity",rt.mean,[.2,1]),f.ms=u("marker.size",rt.mean,[2,16]),f.mlc=u("marker.line.color",d),f.mlw=u("marker.line.width",rt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",d,[0,10])}),s&&(f.tx="Aa",f.tp=u("textposition",d),f.ts=10,f.tc=u("textfont.color",d),f.tf=u("textfont.family",d)),r=[rt.minExtend(i,f)],a=rt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Yn.pointStyle,a,n),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Yn.textPointStyle,a,n)})},Au=mn.LINE_SPACING,Lu=mn.FROM_TL,Cu=mn.FROM_BR,Su=h.DBLCLICKDELAY;function Ou(e,t){var n=e.data()[0][0],r=t._fullLayout,a=n.trace,i=D.traceIs(a,"pie"),o=a.index,l=i?n.label:a.name,s=e.selectAll("text.legendtext").data([0]);function c(n){bn.convertToTspans(n,t,function(){!function(e,t){var n=e.data()[0][0];if(!n.trace.showlegend)return void e.remove();var r,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*Au;if(o){var s=Yn.bBox(o);r=s.height,a=s.width,Yn.setTranslate(i,0,r/4)}else{var c=e.select(".legendtext"),u=bn.lineCount(c),d=c.node();r=l*u,a=d?Yn.bBox(d).width:0;var f=l*(.3+(1-u)/2);bn.positionText(c,40,f)}r=Math.max(r,16)+3,n.height=r,n.width=a}(e,t)})}s.enter().append("text").classed("legendtext",!0),s.attr("text-anchor","start").classed("user-select-none",!0).call(Yn.font,r.legend.font).text(l),t._context.edits.legendText&&!i?s.call(bn.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var r,a=e;this.text()||(e=" ");var i=n.trace._fullInput||{},l={};if(-1!==["ohlc","candlestick"].indexOf(i.type))l[(r=n.trace.transforms)[r.length-1].direction+".name"]=e;else if(D.hasTransform(i,"groupby")){var s=D.getTransformIndices(i,"groupby"),u=s[s.length-1],d=rt.keyedContainer(i,"transforms["+u+"].styles","target","value.name");""===a?d.remove(n.trace._group):d.set(n.trace._group,e),l=d.constructUpdate()}else l.name=e;return D.call("restyle",t,l,o)}):c(s)}function zu(e,t){var n,r=1,a=e.selectAll("rect").data([0]);a.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(xt.fill,"rgba(0,0,0,0)"),a.on("mousedown",function(){(n=(new Date).getTime())-t._legendMouseDownTimeSu&&(r=Math.max(r-1,1)),1===r?n._clickTimeout=setTimeout(function(){_u(e,t,r)},Su):2===r&&(n._clickTimeout&&clearTimeout(n._clickTimeout),t._legendMouseDownTime=0,_u(e,t,r))}})}function Pu(t,n,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=yu.isGrouped(i),s=0;if(i._width=0,i._height=0,yu.isVertical(i))l&&n.each(function(e,t){Yn.setTranslate(this,0,t*i.tracegroupgap)}),r.each(function(e){var t=e[0],n=t.height,r=t.width;Yn.setTranslate(this,o,5+o+i._height+n/2),i._height+=n,i._width=Math.max(i._width,r)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=n.data(),d=0,f=u.length;do+b-_,r.each(function(e){var t=e[0],n=g?40+e[0].width:m;o+x+_+n>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Yn.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+n,i._height=Math.max(i._height,t.height),x+=_+n,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(n){var r=n[0],a=e.select(this).select(".legendtoggle");Yn.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function Du(e){var t=e._fullLayout.legend,n="left";mu.isRightAnchor(t)?n="right":mu.isCenterAnchor(t)&&(n="center");var r="top";mu.isBottomAnchor(t)?r="bottom":mu.isMiddleAnchor(t)&&(r="middle"),Hr.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*Lu[n],r:t._width*Cu[n],b:t._height*Cu[r],t:t._height*Lu[r]})}var Eu={moduleType:"component",name:"legend",layoutAttributes:vu,supplyLayoutDefaults:function(e,t,n){for(var r,a,i,o,l=e.legend||{},s={},c=0,u="normal",d=0;d1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),rt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(r=0,i="left",a=1.1,o="bottom"):(r=0,i="left",a=-.1,o="top")}h("traceorder",u),yu.isGrouped(t.legend)&&h("tracegroupgap"),h("x",r),h("xanchor",i),h("y",a),h("yanchor",o),rt.noneOrAll(l,s,["x","y"])}},draw:function(t){var n=t._fullLayout,r="legend"+n._uid;if(n._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=n.legend,i=n.showlegend&&function(e,t){var n,r,a={},i=[],o=!1,l={},s=0;function c(e,n){if(""!==e&&yu.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[n]]):a[e].push([n]);else{var r="~~i"+s;i.push(r),a[r]=[[n]],s++}}for(n=0;ng?function(e){var t=e._fullLayout.legend,n="left";mu.isRightAnchor(t)?n="right":mu.isCenterAnchor(t)&&(n="center"),Hr.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*Lu[n],r:t._width*Cu[n],b:0,t:0})}(t):Du(t);var v=n._size,y=v.l+v.w*a.x,m=v.t+v.h*(1-a.y);mu.isRightAnchor(a)?y-=a._width:mu.isCenterAnchor(a)&&(y-=a._width/2),mu.isBottomAnchor(a)?m-=a._height:mu.isMiddleAnchor(a)&&(m-=a._height/2);var x=a._width,b=v.w;x>b?(y=v.l,x=b):(y+x>p&&(y=p-x),y<0&&(y=0),x=Math.min(p-y,a._width));var _,w,k,M,T=a._height,A=v.h;if(T>A?(m=v.t,T=A):(m+T>g&&(m=g-T),m<0&&(m=0),T=Math.min(g-m,a._height)),Yn.setTranslate(l,y,m),d.on(".drag",null),l.on("wheel",null),a._height<=T||t._context.staticPlot)c.attr({width:x-a.borderwidth,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Yn.setTranslate(u,0,0),s.select("rect").attr({width:x-2*a.borderwidth,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Yn.setClipUrl(u,r),Yn.setRect(d,0,0,0,0),delete a._scrollY;else{var L,C,S=Math.max(xu.scrollBarMinHeight,T*T/a._height),O=T-S-2*xu.scrollBarMargin,z=a._height-T,P=O/z,E=Math.min(a._scrollY||0,z);c.attr({width:x-2*a.borderwidth+xu.scrollBarWidth+xu.scrollBarMargin,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),s.select("rect").attr({width:x-2*a.borderwidth+xu.scrollBarWidth+xu.scrollBarMargin,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+E}),Yn.setClipUrl(u,r),I(E,S,P),l.on("wheel",function(){I(E=rt.constrain(a._scrollY+e.event.deltaY/O*z,0,z),S,P),0!==E&&E!==z&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){L=e.event.sourceEvent.clientY,C=E}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||I(E=rt.constrain((t.clientY-L)/P+C,0,z),S,P)});d.call(N)}t._context.edits.legendPosition&&(l.classed("cursor-move",!0),Li.init({element:l.node(),gd:t,prepFn:function(){var e=Yn.getTranslate(l);k=e.x,M=e.y},moveFn:function(e,t){var n=k+e,r=M+t;Yn.setTranslate(l,n,r),_=Li.align(n,0,v.l,v.l+v.w,a.xanchor),w=Li.align(r,0,v.t+v.h,v.t,a.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&D.call("relayout",t,{"legend.x":_,"legend.y":w})},clickFn:function(e,r){var a=n._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return r.clientX>=e.left&&r.clientX<=e.right&&r.clientY>=e.top&&r.clientY<=e.bottom});a.size()>0&&(1===e?l._clickTimeout=setTimeout(function(){_u(a,t,e)},Su):2===e&&(l._clickTimeout&&clearTimeout(l._clickTimeout),_u(a,t,e)))}}))}function I(e,n,r){a._scrollY=t._fullLayout.legend._scrollY=e,Yn.setTranslate(u,0,-e),Yn.setRect(d,x,xu.scrollBarMargin+e*r,xu.scrollBarWidth,n),s.select("rect").attr({y:a.borderwidth+e})}},style:Tu},Nu={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},Iu=m.extendFlat,Ru={visible:{valType:"boolean",editType:"plot"},buttons:Nu=Iu(Nu,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:L({editType:"plot"}),bgcolor:{valType:"color",dflt:O.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:O.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},Fu={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var Bu=function(t,n){var r=t._name,a={};if("all"===n.step)a[r+".autorange"]=!0;else{var i=function(t,n){var r,a=t.range,i=new Date(t.r2l(a[1])),o=n.step,l=n.count;switch(n.stepmode){case"backward":r=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);r=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,n);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var ju=mn.LINE_SPACING,qu=mn.FROM_TL,Hu=mn.FROM_BR;function Vu(e){return e._id}function Uu(e,t,n){var r=e.selectAll("rect").data([0]);r.enter().append("rect").classed("selector-rect",!0),r.attr("shape-rendering","crispEdges"),r.attr({rx:Fu.rx,ry:Fu.ry}),r.call(xt.stroke,t.bordercolor).call(xt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,n)).style("stroke-width",t.borderwidth+"px")}function Gu(e,t,n,r){var a,i=e.selectAll("text").data([0]);i.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),i.attr("text-anchor","middle"),i.call(Yn.font,t.font).text((a=n,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){bn.convertToTspans(e,r)})}var Yu={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:Ru}}},layoutAttributes:Ru,handleDefaults:function(e,t,n,r,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return rt.coerce(i,o,Ru,e,t)}if(l("visible",function(e,t,n){var r,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return rt.coerce(r,a,Nu,e,t)}for(var s=0;s0)){var s=function(e,t,n){for(var r=n.filter(function(n){return t[n].anchor===e._id}),a=0,i=0;id&&(d=c)));return d>=u?[u,d]:void 0}}var fd=function(e,t,n,r,a){function i(n,r){return rt.coerce(e,t,sd,n,r)}if(r=r||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=["x","y"],s=0;s<2;s++){var c=l[s],u={_fullLayout:n},d=ha.coerceRef(e,t,u,c,"","paper");if("path"!==o){var f,h,p;"paper"!==d?(f=ha.getFromId(u,d),p=ud.rangeToShapePosition(f),h=ud.shapePositionToRange(f)):h=p=rt.identity;var g=c+"0",v=c+"1",y=e[g],m=e[v];e[g]=h(e[g],!0),e[v]=h(e[v],!0),ha.coercePosition(t,u,i,d,g,.25),ha.coercePosition(t,u,i,d,v,.75),t[g]=p(t[g]),t[v]=p(t[v]),e[g]=y,e[v]=m}}return"path"===o?i("path"):rt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},hd={draw:function(e){var t=e._fullLayout;t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._shapeSubplotLayers.selectAll("path").remove();for(var n=0;nN&&r>I&&!e.shiftKey?Li.getCursor(a/n,1-i/r):"move";Ii(t,o),E=o.split("-")[0]}function j(r,h){if("path"===n.type){var p=function(e){return z(S(e)+r)};L&&"date"===L.type&&(p=ud.encodeDate(p));var g=function(e){return P(O(e)+h)};C&&"date"===C.type&&(g=ud.encodeDate(g)),n.path=vd(T,p,g),a[A]=n.path}else a[c]=n.x0=z(i+r),a[u]=n.y0=P(o+h),a[d]=n.x1=z(l+r),a[f]=n.y1=P(s+h);t.attr("d",gd(e,n))}function q(r,i){if("path"===n.type){var o=function(e){return z(S(e)+r)};L&&"date"===L.type&&(o=ud.encodeDate(o));var l=function(e){return P(O(e)+i)};C&&"date"===C.type&&(l=ud.encodeDate(l)),n.path=vd(T,o,l),a[A]=n.path}else{var s=~E.indexOf("n")?h+i:h,c=~E.indexOf("s")?p+i:p,u=~E.indexOf("w")?g+r:g,d=~E.indexOf("e")?v+r:v;c-s>I&&(a[y]=n[_]=P(s),a[m]=n[w]=P(c)),d-u>N&&(a[x]=n[k]=z(u),a[b]=n[M]=z(d))}t.attr("d",gd(e,n))}Li.init(R),t.node().onmousemove=B}(e,o,r,t)}}function gd(e,t){var n,r,a,i,o=t.type,l=ha.getFromId(e,t.xref),s=ha.getFromId(e,t.yref),c=e._fullLayout._size;if(l?(n=ud.shapePositionToRange(l),r=function(e){return l._offset+l.r2p(n(e,!0))}):r=function(e){return c.l+c.w*e},s?(a=ud.shapePositionToRange(s),i=function(e){return s._offset+s.r2p(a(e,!0))}):i=function(e){return c.t+c.h*(1-e)},"path"===o)return l&&"date"===l.type&&(r=ud.decodeDate(r)),s&&"date"===s.type&&(i=ud.decodeDate(i)),function(e,t,n){return e.replace(cd.segmentRE,function(e){var r=0,a=e.charAt(0),i=cd.paramIsX[a],o=cd.paramIsY[a],l=cd.numParams[a],s=e.substr(1).replace(cd.paramRE,function(e){return i[r]?e=t(e):o[r]&&(e=n(e)),++r>l&&(e="X"),e});return r>l&&(s=s.replace(/[\s,]*X.*/,""),rt.log("Ignoring extra params in segment "+e)),a+s})}(t.path,r,i);var u=r(t.x0),d=r(t.x1),f=i(t.y0),h=i(t.y1);if("line"===o)return"M"+u+","+f+"L"+d+","+h;if("rect"===o)return"M"+u+","+f+"H"+d+"V"+h+"H"+u+"Z";var p=(u+d)/2,g=(f+h)/2,v=Math.abs(p-u),y=Math.abs(g-f),m="A"+v+","+y,x=p+v+","+g;return"M"+x+m+" 0 1,1 "+(p+","+(g-y))+m+" 0 0,1 "+x+"Z"}function vd(e,t,n){return e.replace(cd.segmentRE,function(e){var r=0,a=e.charAt(0),i=cd.paramIsX[a],o=cd.paramIsY[a],l=cd.numParams[a];return a+e.substr(1).replace(cd.paramRE,function(e){return r>=l?e:(i[r]?e=t(e):o[r]&&(e=n(e)),r++,e)})})}var yd={moduleType:"component",name:"shapes",layoutAttributes:sd,supplyLayoutDefaults:function(e,t){Fc(e,t,{name:"shapes",handleItemDefaults:fd})},includeBasePlot:Bc("shapes"),calcAutorange:function(e){var t=e._fullLayout,n=rt.filterVisible(t.shapes);if(n.length&&e._fullData.length)for(var r=0;r0)&&(r("active"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("len"),r("lenmode"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("currentvalue.visible")&&(r("currentvalue.xanchor"),r("currentvalue.prefix"),r("currentvalue.suffix"),r("currentvalue.offset"),rt.coerceFont(r,"currentvalue.font",t.font)),r("transition.duration"),r("transition.easing"),r("bgcolor"),r("activebgcolor"),r("bordercolor"),r("borderwidth"),r("ticklen"),r("tickwidth"),r("tickcolor"),r("minorticklen"))}var Td=mn.LINE_SPACING,Ad=mn.FROM_TL,Ld=mn.FROM_BR;function Cd(e){return e._index}function Sd(t,n){var r=Yn.tester.selectAll("g."+md.labelGroupClass).data(n.steps);r.enter().append("g").classed(md.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=Pd(e.select(this),{step:t},n).node();if(r){var o=Yn.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=n._dims={};o.inputAreaWidth=Math.max(md.railWidth,md.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*n.x,o.ly=l.t+l.h*(1-n.y),"fraction"===n.lenmode?o.outerLength=Math.round(l.w*n.len):o.outerLength=n.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-n.pad.l-n.pad.r);var s=(o.inputAreaLength-2*md.stepInset)/(n.steps.length-1),c=a+md.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,n.currentvalue.visible){var u=Yn.tester.append("g");r.each(function(e){var t=Od(u,n,e.label),r=t.node()&&Yn.bBox(t.node())||{width:0,height:0},a=bn.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(r.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(r.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+n.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+md.tickOffset+n.ticklen+md.labelOffset+o.labelHeight+n.pad.t+n.pad.b;var d="left";mu.isRightAnchor(n)&&(o.lx-=o.outerLength,d="right"),mu.isCenterAnchor(n)&&(o.lx-=o.outerLength/2,d="center");var f="top";mu.isBottomAnchor(n)&&(o.ly-=o.height,f="bottom"),mu.isMiddleAnchor(n)&&(o.ly-=o.height/2,f="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Hr.autoMargin(t,md.autoMarginIdRoot+n._index,{x:n.x,y:n.y,l:o.outerLength*Ad[d],r:o.outerLength*Ld[d],b:o.height*Ld[f],t:o.height*Ad[f]})}function Od(e,t,n){if(t.currentvalue.visible){var r,a,i=e.selectAll("text").data([0]),o=t._dims;switch(t.currentvalue.xanchor){case"right":r=o.inputAreaLength-md.currentValueInset-o.currentValueMaxWidth,a="left";break;case"center":r=.5*o.inputAreaLength,a="middle";break;default:r=md.currentValueInset,a="left"}i.enter().append("text").classed(md.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1});var l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof n)l+=n;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),i.call(Yn.font,t.currentvalue.font).text(l).call(bn.convertToTspans,t._gd);var s=bn.lineCount(i),c=(o.currentValueMaxLines+1-s)*t.currentvalue.font.size*Td;return bn.positionText(i,r,c),i}}function zd(e,t,n){var r=e.selectAll("rect."+md.gripRectClass).data([0]);r.enter().append("rect").classed(md.gripRectClass,!0).call(Id,t,e,n).style("pointer-events","all"),r.attr({width:md.gripWidth,height:md.gripHeight,rx:md.gripRadius,ry:md.gripRadius}).call(xt.stroke,n.bordercolor).call(xt.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px")}function Pd(e,t,n){var r=e.selectAll("text").data([0]);return r.enter().append("text").classed(md.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),r.call(Yn.font,n.font).text(t.step.label).call(bn.convertToTspans,n._gd),r}function Dd(t,n){var r=t.selectAll("g."+md.labelsClass).data([0]),a=n._dims;r.enter().append("g").classed(md.labelsClass,!0);var i=r.selectAll("g."+md.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(md.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=e.select(this);r.call(Pd,t,n),Yn.setTranslate(r,Bd(n,t.fraction),md.tickOffset+n.ticklen+n.font.size*Td+md.labelOffset+a.currentValueTotalHeight)})}function Ed(e,t,n,r,a){var i=Math.round(r*(n.steps.length-1));i!==n.active&&Nd(e,t,n,i,!0,a)}function Nd(e,t,n,r,a,i){var o=n.active;n._input.active=n.active=r;var l=n.steps[n.active];t.call(Fd,n,n.active/(n.steps.length-1),i),t.call(Od,n),e.emit("plotly_sliderchange",{slider:n,step:n.steps[n.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var n=t._nextMethod.step;n.method&&(n.execute&&Hr.executeAPICommand(e,n.method,n.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function Id(t,n,r){var a=r.node(),i=e.select(n);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();n.emit("plotly_sliderstart",{slider:t});var l=r.select("."+md.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(xt.fill,t.activebgcolor);var s=jd(t,e.mouse(a)[0]);Ed(n,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=jd(t,e.mouse(a)[0]);Ed(n,r,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(xt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),n.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function Rd(t,n){var r=t.selectAll("rect."+md.tickRectClass).data(n.steps),a=n._dims;r.enter().append("rect").classed(md.tickRectClass,!0),r.exit().remove(),r.attr({width:n.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=e.select(this);o.attr({height:i?n.ticklen:n.minorticklen}).call(xt.fill,n.tickcolor),Yn.setTranslate(o,Bd(n,r/(n.steps.length-1))-.5*n.tickwidth,(i?md.tickOffset:md.minorTickOffset)+a.currentValueTotalHeight)})}function Fd(e,t,n,r){var a=e.select("rect."+md.gripRectClass),i=Bd(t,n);if(!t._invokingCommand){var o=a;r&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*md.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function Bd(e,t){var n=e._dims;return n.inputAreaStart+md.stepInset+(n.inputAreaLength-2*md.stepInset)*Math.min(1,Math.max(0,t))}function jd(e,t){var n=e._dims;return Math.min(1,Math.max(0,(t-md.stepInset-n.inputAreaStart)/(n.inputAreaLength-2*md.stepInset-2*n.inputAreaStart)))}function qd(e,t,n){var r=e.selectAll("rect."+md.railTouchRectClass).data([0]),a=n._dims;r.enter().append("rect").classed(md.railTouchRectClass,!0).call(Id,t,e,n).style("pointer-events","all"),r.attr({width:a.inputAreaLength,height:Math.max(a.inputAreaWidth,md.tickOffset+n.ticklen+a.labelHeight)}).call(xt.fill,n.bgcolor).attr("opacity",0),Yn.setTranslate(r,0,a.currentValueTotalHeight)}function Hd(e,t){var n=e.selectAll("rect."+md.railRectClass).data([0]),r=t._dims;n.enter().append("rect").classed(md.railRectClass,!0);var a=r.inputAreaLength-2*md.railInset;n.attr({width:a,height:md.railWidth,rx:md.railRadius,ry:md.railRadius,"shape-rendering":"crispEdges"}).call(xt.stroke,t.bordercolor).call(xt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Yn.setTranslate(n,md.railInset,.5*(r.inputAreaWidth-md.railWidth)+r.currentValueTotalHeight)}var Vd={moduleType:"component",name:md.name,layoutAttributes:_d,supplyLayoutDefaults:function(e,t){Fc(e,t,{name:wd,handleItemDefaults:Md})},draw:function(t){var n=t._fullLayout,r=function(e,t){for(var n=e[md.name],r=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(md.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r=n.steps.length&&(n.active=0),t.call(Od,n).call(Hd,n).call(Dd,n).call(Rd,n).call(qd,e,n).call(zd,e,n);var r=n._dims;Yn.setTranslate(t,r.lx+n.pad.l,r.ly+n.pad.t),t.call(Fd,n,n.active/(n.steps.length-1),!1),t.call(Od,n)}(t,e.select(this),n)}})}}},Ud=m.extendFlat,Gd=(0,on.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Ud({},xd,{}),font:L({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:O.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Yd={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Zd=Yd.name,Xd=Gd.buttons;function Wd(e,t,n){function r(n,r){return rt.coerce(e,t,Gd,n,r)}r("visible",function(e,t){var n,r,a=e.buttons||[],i=t.buttons=[];function o(e,t){return rt.coerce(n,r,Xd,e,t)}for(var l=0;l0)&&(r("active"),r("direction"),r("type"),r("showactive"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("bgcolor",n.paper_bgcolor),r("bordercolor"),r("borderwidth"))}var Qd=Jd;function Jd(e,t,n){this.gd=e,this.container=t,this.id=n,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Jd.barWidth=2,Jd.barLength=20,Jd.barRadius=2,Jd.barPad=1,Jd.barColor="#808BA4",Jd.prototype.enable=function(t,n,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,d=this.position.l,f=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=f,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=d)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=d+x)-(l=Math.max(s-x,0)):(l=d,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=f>x,w=Jd.barLength+2*Jd.barPad,k=Jd.barWidth+2*Jd.barPad,M=d,T=h+p;T+k>o&&(T=o-k);var A=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);A.exit().on(".drag",null).remove(),A.enter().append("rect").classed("scrollbar-horizontal",!0).call(xt.fill,Jd.barColor),_?(this.hbar=A.attr({rx:Jd.barRadius,ry:Jd.barRadius,x:M,y:T,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=Jd.barWidth+2*Jd.barPad,S=Jd.barLength+2*Jd.barPad,O=d+f,z=h;O+C>i&&(O=i-C);var P=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);P.exit().on(".drag",null).remove(),P.enter().append("rect").classed("scrollbar-vertical",!0).call(xt.fill,Jd.barColor),L?(this.vbar=P.attr({rx:Jd.barRadius,ry:Jd.barRadius,x:O,y:z,width:C,height:S}),this._vbarYMin=z+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,N=L?s+C+.5:s+.5,I=c-.5,R=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(I),width:Math.ceil(N)-Math.floor(E),height:Math.ceil(R)-Math.floor(I)}),this.container.call(Yn.setClipUrl,D),this.bg.attr({x:d,y:h,width:f,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Yn.setClipUrl,null),delete this._clipRect),_||L){var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(B);var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),L&&this.vbar.on(".drag",null).call(j)}this.setTranslate(n,r)},Jd.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Yn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Jd.prototype._onBoxDrag=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(n-=e.event.dy),this.setTranslate(t,n)},Jd.prototype._onBoxWheel=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(n+=e.event.deltaY),this.setTranslate(t,n)},Jd.prototype._onBarDrag=function(){var t=this.translateX,n=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(rt.constrain(e.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=n+this._vbarYMin,o=i+this._vbarTranslateMax;n=(rt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,n)},Jd.prototype.setTranslate=function(e,t){var n=this.position.w-this._box.w,r=this.position.h-this._box.h;if(e=rt.constrain(e||0,0,n),t=rt.constrain(t||0,0,r),this.translateX=e,this.translateY=t,this.container.call(Yn.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/n;this.hbar.call(Yn.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/r;this.vbar.call(Yn.setTranslate,e,t+i*this._vbarTranslateMax)}};var $d=mn.LINE_SPACING;function Kd(e){return e._index}function ef(e,t){return+e.attr(Yd.menuIndexAttrName)===t._index}function tf(e,t,n,r,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?rf(e,r,null,null,t):"dropdown"===t.type&&(a.attr(Yd.menuIndexAttrName,"-1"),nf(e,r,a,i,t),l||rf(e,r,a,i,t))}function nf(e,t,n,r,a){var i=t.selectAll("g."+Yd.headerClassName).data([0]),o=a._dims;i.enter().append("g").classed(Yd.headerClassName,!0).style("pointer-events","all");var l=a.active,s=a.buttons[l]||Yd.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(af,a,s,e).call(ff,a,c,u);var d=t.selectAll("text."+Yd.headerArrowClassName).data([0]);d.enter().append("text").classed(Yd.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(Yn.font,a.font).text(Yd.arrowSymbol[a.direction]),d.attr({x:o.headerWidth-Yd.arrowOffsetX+a.pad.l,y:o.headerHeight/2+Yd.textOffsetY+a.pad.t}),i.on("click",function(){n.call(hf),n.attr(Yd.menuIndexAttrName,ef(n,a)?-1:String(a._index)),rf(e,t,n,r,a)}),i.on("mouseover",function(){i.call(cf)}),i.on("mouseout",function(){i.call(uf,a)}),Yn.setTranslate(t,o.lx,o.ly)}function rf(t,n,r,a,i){r||(r=n).attr("pointer-events","all");var o=function(e){return-1==+e.attr(Yd.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?Yd.dropdownButtonClassName:Yd.buttonClassName,s=r.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var d=0,f=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?f=h.headerHeight+Yd.gapButtonHeader:d=h.headerWidth+Yd.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(f=-Yd.gapButtonHeader+Yd.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(d=-Yd.gapButtonHeader+Yd.gapButton-h.openWidth);var g={x:h.lx+d+i.pad.l,y:h.ly+f+i.pad.t,yPad:Yd.gapButton,xPad:Yd.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(af,i,o,t).call(ff,i,g),c.on("click",function(){e.event.defaultPrevented||(tf(t,i,0,n,r,a,l),o.execute&&Hr.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(cf)}),c.on("mouseout",function(){c.call(uf,i),s.call(sf,i)})}),s.call(sf,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,n,r,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,d=a._dims,f=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(Yd.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r_.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,n;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n0&&rt.log("Clearing previous rejected promises from queue."),e._promises=[]},xf.cleanLayout=function(e){var t,n;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var r=(Hr.subplotsRegistry.cartesian||{}).attrRegex,a=(Hr.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),xt.clean(e),e},xf.cleanData=function(e,t){for(var n=[],r=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}xf.hasParent=function(e,t){for(var n=Af(t);n;){if(n in e)return!0;n=Af(n)}return!1};var Lf=["x","y","z"];xf.clearAxisTypes=function(e,t,n){for(var r=0;r1&&w.warn("Full array edits are incompatible with other edits",a);var d=n[""][""];if(zf(d))t.set(null);else{if(!Array.isArray(d))return w.warn("Unrecognized full array edit value",a,d),!0;t.set(d)}return!s&&(i(c,u),o(e),!0)}var f,h,p,g,v,y,m,x=Object.keys(n).map(Number).sort(Sf),b=t.get(),_=b||[],k=Z(u,a).get(),M=[],A=-1,L=_.length;for(f=0;f_.length-(m?0:1))w.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&w.warn("Insertion & removal are incompatible with edits to the same index.",a,p),zf(y)?M.push(p):m?("add"===y&&(y={}),_.splice(p,0,y),k&&k.splice(p,0,{})):w.warn("Unrecognized full object edit value",a,p,y),-1===A&&(A=p);else for(h=0;h=0;f--)_.splice(M[f],1),k&&k.splice(M[f],1);if(_.length?b||t.set(_):t.set(null),s)return!1;if(i(c,u),l!==T){var C;if(-1===A)C=x;else{for(L=Math.max(_.length,L),C=[],f=0;f=A);f++)C.push(p);for(f=A;f1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):d?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:d||l?x=["pan2d"]:f&&(x=["zoom2d"]),function(e){for(var t=!1,n=0;n0})}function c(e,r){var a=e.seg,i=r.seg,o=a.start,s=a.end,c=i.start,u=i.end;n&&n.checkIntersection(a,i);var d=t.linesIntersect(o,s,c,u);if(!1===d){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var f=t.pointsSame(o,c),h=t.pointsSame(s,u);if(f&&h)return r;var p=!f&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(f)return g?l(r,s):l(e,u),r;p&&(h||(g?l(r,s):l(e,u)),l(r,o))}else 0===d.alongA&&(-1===d.alongB?l(e,c):0===d.alongB?l(e,d.pt):1===d.alongB&&l(e,u)),0===d.alongB&&(-1===d.alongA?l(r,o):0===d.alongA?l(r,d.pt):1===d.alongA&&l(r,s));return!1}for(var u=[];!a.isEmpty();){var d=a.getHead();if(n&&n.vert(d.pt[0]),d.isStart){n&&n.segmentNew(d.seg,d.primary);var f=s(d),h=f.before?f.before.ev:null,p=f.after?f.after.ev:null;function g(){if(h){var e=c(d,h);if(e)return e}return!!p&&c(d,p)}n&&n.tempStatus(d.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===d.seg.myFill.below||d.seg.myFill.above!==d.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=d.seg.myFill,n&&n.segmentUpdate(m.seg),d.other.remove(),d.remove();if(a.getHead()!==d){n&&n.rewind(d.seg);continue}e?(y=null===d.seg.myFill.below||d.seg.myFill.above!==d.seg.myFill.below,d.seg.myFill.below=p?p.seg.myFill.above:r,d.seg.myFill.above=y?!d.seg.myFill.below:d.seg.myFill.below):null===d.seg.otherFill&&(v=p?d.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:d.primary?i:r,d.seg.otherFill={above:v,below:v}),n&&n.status(d.seg,!!h&&h.seg,!!p&&p.seg),d.other.status=f.insert(Qf.node({ev:d}))}else{var x=d.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),n&&n.statusRemove(x.ev.seg),x.remove(),!d.primary){var b=d.seg.myFill;d.seg.myFill=d.seg.otherFill,d.seg.otherFill=b}u.push(d.seg)}a.getHead().remove()}return n&&n.done(),u}return e?{addRegion:function(e){for(var r,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,n,r){var a=t[1]-n[1],i=r[0]-n[0],o=t[0]-n[0],l=r[1]-n[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,n){return Math.abs(t[0]-n[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-r>e&&(l=!l),i=c,o=u}return l}};return t}();function ah(e,t,n){var r=eh.segments(e),a=eh.segments(t),i=n(eh.combine(r,a));return eh.polygon(i)}eh={buildLog:function(e){return!0===e?nh=Xf():!1===e&&(nh=!1),!1!==nh&&nh.list},epsilon:function(e){return rh.epsilon(e)},segments:function(e){var t=Jf(!0,rh,nh);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Jf(!1,rh,nh).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:th.union(e.combined,nh),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:th.intersect(e.combined,nh),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:th.difference(e.combined,nh),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:th.differenceRev(e.combined,nh),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:th.xor(e.combined,nh),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:$f(e.segments,rh,nh),inverted:e.inverted}},polygonFromGeoJSON:function(e){return Wf.toPolygon(eh,e)},polygonToGeoJSON:function(e){return Wf.fromPolygon(eh,rh,e)},union:function(e,t){return ah(e,t,eh.selectUnion)},intersect:function(e,t){return ah(e,t,eh.selectIntersect)},difference:function(e,t){return ah(e,t,eh.selectDifference)},differenceRev:function(e,t){return ah(e,t,eh.selectDifferenceRev)},xor:function(e,t){return ah(e,t,eh.selectXor)}},"object"==typeof window&&(window.PolyBool=eh);var ih,oh=eh,lh=qe.dot,sh=r.BADNUM,ch=ih={};ch.tester=function(e){if(Array.isArray(e[0][0]))return ch.multitester(e);var t,n=e.slice(),r=n[0][0],a=r,i=n[0][1],o=i;for(n.push(n[0]),t=1;ta||s===sh||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===sh||la||s===sh||so)return!1;var c,u,d,f,h,p=n.length,g=n[0][0],v=n[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(d,v)))if(sc||Math.abs(lh(i,d))>r)return!0;return!1};ch.filter=function(e,t){var n=[e[0]],r=0,a=0;function i(i){e.push(i);var o=n.length,l=r;n.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:n}};var dh=Pi.makeEventData,fh=ih.filter,hh=ih.tester,ph=ih.multitester,gh=ht.MINSELECT;function vh(e){return e._id}var yh=function(e,t,n,r,a){var i,o,l,s,c=r.gd,u=c._fullLayout,d=u._zoomlayer,f=r.element.getBoundingClientRect(),h=r.plotinfo,p=h.xaxis._offset,g=h.yaxis._offset,v=t-f.left,y=n-f.top,m=v,x=y,b="M"+v+","+y,_=r.xaxes[0]._length,w=r.yaxes[0]._length,k=r.xaxes.map(vh),M=r.yaxes.map(vh),T=r.xaxes.concat(r.yaxes),A=e.altKey;(e.shiftKey||e.altKey)&&h.selection&&h.selection.polygons&&!r.polygons?(r.polygons=h.selection.polygons,r.mergedPolygons=h.selection.mergedPolygons):(!e.shiftKey&&!e.altKey||(e.shiftKey||e.altKey)&&!h.selection)&&(h.selection={},h.selection.polygons=r.polygons=[],h.selection.mergedPolygons=r.mergedPolygons=[]),"lasso"===a&&(i=fh([[v,y]],ht.BENDPX));var L=d.selectAll("path.select-outline-"+h.id).data([1,2]);L.enter().append("path").attr("class",function(e){return"select-outline select-outline-"+e+" select-outline-"+h.id}).attr("transform","translate("+p+", "+g+")").attr("d",b+"Z");var C,S,O,z,P,D,E=d.append("path").attr("class","zoombox-corners").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1}).attr("transform","translate("+p+", "+g+")").attr("d","M0,0Z"),N=[],I=u._uid+ht.SELECTID,R=[];for(C=0;C=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function Ph(e,t,n,r,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+n+", "+r+")").attr("d",a+"Z")}function Dh(e,t,n){return e.append("path").attr("class","zoombox-corners").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+n+")").attr("d","M0,0Z")}function Eh(e){e.selectAll(".select-outline").remove()}function Nh(e,t,n,r,a,i){e.attr("d",r+"M"+n.l+","+n.t+"v"+n.h+"h"+n.w+"v-"+n.h+"h-"+n.w+"Z"),Ih(e,t,a,i)}function Ih(e,t,n,r){n||(e.transition().style("fill",r>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function Rh(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Fh(e){Th&&e.data&&e._context.showTips&&(rt.notifier(rt._(e,"Double-click to zoom back out"),"long"),Th=!1)}function Bh(e){return"lasso"===e||"select"===e}function jh(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,Mh)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function qh(e,t){if(hi){var n=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(n,e._onwheel),e._onwheel=t,e.addEventListener(n,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}var Hh=function(t,n,r,a,i,o,l,c){var u,d,f,h,p,g,v,y,m,x,b,_,w,k=t._fullLayout,M=t._fullLayout._zoomlayer,T=l+c==="nsew",A=1===(l+c).length;function L(){d=[n.xaxis],f=[n.yaxis];var e=d[0],r=f[0];g=e._length,v=r._length;var a,i,o=k._axisConstraintGroups,s=[e._id],M=[r._id];u=[n].concat(l&&c?n.overlays:[]);for(var T=1;TMh||o>Mh?(R="xy",i/g>o/v?(o=i*v/g,z>a?P.t=z-o:P.b=z+o):(i=o*g/v,O>r?P.l=O-i:P.r=O+i),B.attr("d",jh(P))):l():!m||o rect").call(Yn.setTranslate,a,i).call(Yn.setScale,n,r);var P=x.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");x.plot.call(Yn.setTranslate,O,z).call(Yn.setScale,1/n,1/r),P.selectAll(".point").call(Yn.setPointGroupScale,n,r),P.selectAll(".textpoint").call(Yn.setTextPointsScale,n,r),P.call(Yn.hideOutsideRangePoints,x),x.plot.selectAll(".barlayer .trace").call(Yn.hideOutsideRangePoints,x,".bartext")}}}return l.length*c.length!=1&&qh(C,function(e){if(t._context.scrollZoom||k._enablescrollzoom){if(null===G&&Eh(M),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var n=t.querySelector(".plotly");if(L(),!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(G);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var a,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),o=Z.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(c||b){for(c||(s=.5),a=0;a=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(n,a,h)?(f.push(e),h.push([n,a])):i=[0];var o=t.plotgroup.selectAll(".bg").data(i);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){t.bg=o;var e=t.plotgroup.node();e.insertBefore(this,e.childNodes[0])})});var p=r._bgLayer.selectAll(".bg").data(f);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=e.select(this)}),d.each(function(e){var t=r._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Yn.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(xt.fill,r.plot_bgcolor).style("stroke-width",0),t.clipId="clip"+r._uid+e+"plot";var u,d,f=r._clips.selectAll("#"+t.clipId).data([0]);for(f.enter().append("clipPath").attr({class:"plotclip",id:t.clipId}).append("rect"),f.selectAll("rect").attr({width:a._length,height:c._length}),Yn.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,d=t.clipId):(u=t.clipId,d=null),Yn.setClipUrl(t.plot,u),n=0;nJh*h)||y)for(n=0;nL&&OT&&(T=O);l/=(T-M)/(2*A),M=a.l2r(M),T=a.l2r(T),a.range=a._input.range=_=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var T=k.slice();w&&b&&(T[1]+=M);var A=c.angularAxis.ticksCount||4;A>8&&(A=A/(A/8)+A%8),c.angularAxis.ticksStep&&(A=(T[1]-T[0])/A);var L=c.angularAxis.ticksStep||(T[1]-T[0])/(A*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),T[2]||(T[2]=L);var C=e.range.apply(this,T);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(T.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),O=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(O)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var z,P=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){z=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var N=u.map(function(e,t){var n=rp.util.cloneJson(e);return n.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",n.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,n.color="LinePlot"===e.geometry?e.strokeColor:e.color,n});rp.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:tp({},rp.Legend.defaultConfig().legendConfig,{container:z,elements:N,reverseOrder:c.legend.reverseOrder})})();var I=z.node().getBBox();g=Math.min(c.width-I.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),z.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else z=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),P.attr("transform","translate("+y+")").style({cursor:"crosshair"});var R=[(c.width-(c.margin.left+c.margin.right+2*g+(I?I.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(R[0]=Math.max(0,R[0]),R[1]=Math.max(0,R[1]),t.select(".outer-group").attr("transform","translate("+R+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),B=F.node().getBBox();F.attr({x:y[0]-B.width/2,y:y[1]-g-20})}var j=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var q=j.selectAll("circle.grid-circle").data(r.ticks(5));q.enter().append("circle").attr({class:"grid-circle"}).style(D),q.attr("r",r),q.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(D);var H=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(r).ticks(5).tickSize(5);j.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),j.selectAll(".domain").style(D),j.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var Z=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:np+"em",transform:function(e,t){var n=V(e),r=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-n+" "+r+" 0)":"radial"==a?n<270&&n>90?"rotate(180 "+r+" 0)":null:"rotate("+(n<=180&&n>0?-90:90)+" "+r+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&Z.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var X=e.max(P.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));z.attr({transform:"translate("+[g+X,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,Q=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(Q.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),Q.exit().remove(),u[0]||W){var J=[];u.forEach(function(e,t){var n={};n.radialScale=r,n.angularScale=a,n.container=Q.filter(function(e,n){return n==t}),n.geometry=e.geometry,n.orientation=c.orientation,n.direction=c.direction,n.index=t,J.push({data:e,geometryConfig:n})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(J).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var n;n=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var r=e.map(function(e,t){return tp(rp[n].defaultConfig(),e)});rp[n]().config(r)()})}var K,ee,te=t.select(".guides-group"),ne=t.select(".tooltips-group"),re=rp.tooltipPanel().config({container:ne,fontSize:8})(),ae=rp.tooltipPanel().config({container:ne,fontSize:8})(),ie=rp.tooltipPanel().config({container:ne,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});P.on("mousemove.angular-guide",function(e,t){var n=rp.util.getMousePos(H).angle;oe.attr({x2:-g,transform:"rotate("+n+")"}).style({opacity:.5});var r=(n+180+360-c.orientation)%360;K=a.invert(r);var i=rp.util.convertToCartesian(g+12,n+180);re.text(rp.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});P.on("mousemove.radial-guide",function(e,t){var n=rp.util.getMousePos(H).radius;le.attr({r:n}).style({opacity:.5}),ee=r.invert(rp.util.getMousePos(H).radius);var a=rp.util.convertToCartesian(n,c.radialAxis.orientation);ae.text(rp.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),re.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(n,r){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:rp.util.round(n[0]),r:rp.util.round(n[1])};b&&(s.t=m[n[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),d=t.node().getBoundingClientRect(),f=[u.left+u.width/2-R[0]-d.left,u.top+u.height/2-R[1]-d.top];ie.config({color:o}).text(c),ie.move(f)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,n){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,n){ie.hide();var r=e.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=rp.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),tp(i.data[t],rp.Axis.defaultConfig().data[0]),tp(i.data[t],e)}),tp(i.layout,rp.Axis.defaultConfig().layout),tp(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return r},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},rp.Axis.defaultConfig=function(t,n){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},rp.util={},rp.DATAEXTENT="dataExtent",rp.AREA="AreaChart",rp.LINE="LinePlot",rp.DOT="DotPlot",rp.BAR="BarChart",rp.util._override=function(e,t){for(var n in e)n in t&&(t[n]=e[n])},rp.util._extend=function(e,t){for(var n in e)t[n]=e[n]},rp.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},rp.util.dataFromEquation2=function(t,n){var r=n||6;return e.range(0,360+r,r).map(function(e,n){var r=e*Math.PI/180;return[e,t(r)]})},rp.util.dataFromEquation=function(t,n,r){var a=n||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,n){var r=e*Math.PI/180,a=t(r);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},rp.util.ensureArray=function(t,n){if(void 0===t)return null;var r=[].concat(t);return e.range(n).map(function(e,t){return r[t]||r[0]})},rp.util.fillArrays=function(e,t,n){return t.forEach(function(t,r){e[t]=rp.util.ensureArray(e[t],n)}),e},rp.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},rp.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var n=t.shift();return e[n]&&(!t.length||objHasKeys(e[n],t))},rp.util.sumArrays=function(t,n){return e.zip(t,n).map(function(t,n){return e.sum(t)})},rp.util.arrayLast=function(e){return e[e.length-1]},rp.util.arrayEqual=function(e,t){for(var n=Math.max(e.length,t.length,1);n-- >=0&&e[n]===t[n];);return-2===n},rp.util.flattenArray=function(e){for(var t=[];!rp.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},rp.util.deduplicate=function(e){return e.filter(function(e,t,n){return n.indexOf(e)==t})},rp.util.convertToCartesian=function(e,t){var n=t*Math.PI/180;return[e*Math.cos(n),e*Math.sin(n)]},rp.util.round=function(e,t){var n=t||2,r=Math.pow(10,n);return Math.round(e*r)/r},rp.util.getMousePos=function(t){var n=e.mouse(t.node()),r=n[0],a=n[1],i={};return i.x=r,i.y=a,i.pos=n,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},rp.util.duplicatesCount=function(e){for(var t,n={},r={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(n.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(r,a,i)},"stroke-width":function(e,t){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](r,a,i)},opacity:function(e,t){return p.opacity(r,a,i)},display:function(e,t){return p.display(r,a,i)}})}};var d=n.angularScale.range(),f=Math.abs(d[1]-d[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-f/2}).endAngle(function(e){return f/2}).innerRadius(function(e){return n.radialScale(s+(e[2]||0))}).outerRadius(function(e){return n.radialScale(s+(e[2]||0))+n.radialScale(e[1])});c.arc=function(t,r,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(n.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,n,r){return t[r].data.color},stroke:function(e,n,r){return t[r].data.strokeColor},"stroke-width":function(e,n,r){return t[r].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,n,r){return t[r].data.opacity},display:function(e,n,r){return void 0===t[r].data.visible||t[r].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[n.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,n){t[n]||(t[n]={}),tp(t[n],rp.PolyChart.defaultConfig()),tp(t[n],e)}),this):t},a.getColorScale=function(){},e.rebind(a,n,"on"),a},rp.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},rp.BarChart=function(){return rp.PolyChart()},rp.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},rp.AreaChart=function(){return rp.PolyChart()},rp.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},rp.DotPlot=function(){return rp.PolyChart()},rp.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},rp.LinePlot=function(){return rp.PolyChart()},rp.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},rp.Legend=function(){var t=rp.Legend.defaultConfig(),n=e.dispatch("hover");function r(){var n=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,r){var a=tp({},n.elements[t]);return a.name=e,a.color=[].concat(n.elements[t].color)[r],a})}),i=e.merge(a);i=i.filter(function(e,t){return n.elements[t]&&(n.elements[t].visibleInLegend||void 0===n.elements[t].visibleInLegend)}),n.reverseOrder&&(i=i.reverse());var o=n.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=n.fontSize,c=null==n.isContinuous?"number"==typeof i[0]:n.isContinuous,u=c?n.height:s*i.length,d=o.classed("legend-group",!0).selectAll("svg").data([0]),f=d.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});f.append("g").classed("legend-axis",!0),f.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=d.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),d.append("rect").classed("legend-mark",!0).attr({height:n.height,width:n.colorBandWidth,fill:"url(#grad1)"})}else{var y=d.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,n){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(r)?e.svg.symbol().type(r).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=d.select("g.legend-axis").attr({transform:"translate("+[c?n.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?n.textColor:"none"}),x.selectAll("text").style({fill:n.textColor,"font-size":n.fontSize}).text(function(e,t){return i[t].name}),r}return r.config=function(e){return arguments.length?(tp(t,e),this):t},e.rebind(r,n,"on"),r},rp.Legend.defaultConfig=function(e,t){return{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:!1}}},rp.tooltipPanel=function(){var t,n,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+rp.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),n=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",d=i||"";n.style({fill:u,"font-size":a.fontSize+"px"}).text(d);var f=a.padding,h=n.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*f+o,v=h.height+2*f;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*f]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return tp(a,e),l},l},rp.tooltipPanel.uid=1,rp.adapter={},rp.adapter.plotly=function(){var t={convert:function(t,n){var r={};if(t.data&&(r.data=t.data.map(function(e,t){var r=tp({},e);return[[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"]]].forEach(function(e,t){rp.util.translator.apply(null,e.concat(n))}),n||delete r.marker,n&&delete r.groupId,n?("LinePlot"===r.geometry?(r.type="scatter",!0===r.dotVisible?(delete r.dotVisible,r.mode="lines+markers"):r.mode="lines"):"DotPlot"===r.geometry?(r.type="scatter",r.mode="markers"):"AreaChart"===r.geometry?r.type="area":"BarChart"===r.geometry&&(r.type="bar"),delete r.geometry):("scatter"===r.type?"lines"===r.mode?r.geometry="LinePlot":"markers"===r.mode?r.geometry="DotPlot":"lines+markers"===r.mode&&(r.geometry="LinePlot",r.dotVisible=!0):"area"===r.type?r.geometry="AreaChart":"bar"===r.type&&(r.geometry="BarChart"),delete r.mode,delete r.type),r}),!n&&t.layout&&"stack"===t.layout.barmode)){var a=rp.util.duplicates(r.data.map(function(e,t){return e.geometry}));r.data.forEach(function(e,t){var n=a.indexOf(e.geometry);-1!=n&&(r.data[t].groupId=n)})}if(t.layout){var i=tp({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){rp.util.translator.apply(null,e.concat(n))}),n?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}n&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var ap,ip=rt.extendDeepAll,op=ap={};op.framework=function(t){var n,r,a,i,o,l=new function(){var e,t=[],n=-1,r=!1;function a(e,t){return e?(r=!0,e[t](),r=!1,this):this}return{add:function(e){return r?this:(t.splice(n+1,t.length-n),t.push(e),n=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var r=t[n];return r?(a(r,"undo"),n-=1,e&&e(r.undo),this):this},redo:function(){var r=t[n+1];return r?(a(r,"redo"),n+=1,e&&e(r.redo),this):this},clear:function(){t=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n*:not(.chart-root)").remove(),n=n?ip(n,r):r,a||(a=ep.Axis()),i=ep.adapter.plotly().convert(n),a.config(i).render(o),t.data=n.data,t.layout=n.layout,op.fillLayout(t),n}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return n},s.getLiveConfig=function(){return ep.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=ep.util.cloneJson(n);e=i,t=r,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),r=ep.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},op.fillLayout=function(t){var n=e.select(t).selectAll(".plot-container"),r=n.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:xt.background,_container:n,_paperdiv:r,_paper:a};t._fullLayout=ip(i,t.layout)};var lp={};(lp=ep).manager=ap;var sp={},cp=Xh.enforce,up=Xh.clean,dp=oa,fp=0;function hp(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){rt.error(e)}}function pp(e,t){hp(e,xt.combine(t,"white"))}function gp(e,t){e._context||(e._context=rt.extendDeep({},_));var n,r,a,i=e._context;if(t){for(r=Object.keys(t),n=0;n=e.data.length||a<-e.data.length)throw new Error(n+" must be valid indices for gd.data.");if(t.indexOf(a,r+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+n+" must be unique.")}}function mp(e,t,n){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),yp(e,t,"currentIndices"),void 0===n||Array.isArray(n)||(n=[n]),void 0!==n&&yp(e,n,"newIndices"),void 0!==n&&t.length!==n.length)throw new Error("current and new indices must be of equal length.")}function xp(e,t,r,a,i){!function(e,t,n,r){var a=rt.isPlainObject(r);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!rt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===n)throw new Error("indices must be an integer or array of integers");for(var i in yp(e,n,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==n.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in r)||!Array.isArray(r[i])||r[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,t,r,a);for(var o=function(e,t,r,a){var i,o,l,s,c,u=rt.isPlainObject(a),d=[];for(var f in Array.isArray(r)||(r=[r]),r=vp(r,e.data.length-1),t)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var T=_.parts[M],A=_.parts[M-1]+"."+T,L=_.parts.slice(0,M).join("."),C=rt.nestedProperty(e.layout,L).get(),S=rt.nestedProperty(o,L).get(),O=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===T?w:_p(O);var z=Ar.getLayoutValObject(o,_.parts);if(z&&z.impliedEdits&&null!==w)for(var P in z.impliedEdits)v(rt.relativeAttr(b,P),z.impliedEdits[P]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(A.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(A),rt.nestedProperty(o,L+"._inputRange").set(null);else if(A.match(/^[xyz]axis[0-9]*\.autorange$/)){x(A),rt.nestedProperty(o,L+"._inputRange").set(null);var E=rt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else A.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&rt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===T){var N=C,I="linear"===S.type&&"log"===w,R="log"===S.type&&"linear"===w;if(I||R){if(N&&N.range)if(S.autorange)I&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],B=N.range[1];I?(F<=0&&B<=0&&v(L+".autorange",!0),F<=0?F=B/1e6:B<=0&&(B=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(B)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,B)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],D.getComponentMethod("annotations","convertCoords")(e,S,w,v),D.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);rt.nestedProperty(o,L+"._inputRange").set(null)}else if(T.match(ht.AX_NAME_PATTERN)){var j=rt.nestedProperty(o,b).get(),q=(w||{}).type;q&&"-"!==q||(q="linear"),D.getComponentMethod("annotations","convertCoords")(e,j,q,v),D.getComponentMethod("images","convertCoords")(e,j,q,v)}var H=Cf.containerArrayMatch(b);if(H){n=H.array,r=H.index;var V=H.property,U=(rt.nestedProperty(i,n)||[])[r]||{},G=U,Y=z||{editType:"calc"},Z=-1!==Y.editType.indexOf("calcIfAutorange");""===r?(Z?h.calc=!0:on.update(h,Y),Z=!1):""===V&&(G=w,Cf.isAddVal(w)?g[b]=null:Cf.isRemoveVal(w)?(g[b]=U,G=U):rt.warn("unrecognized full object value",t)),Z&&(Tp(e,G,"x")||Tp(e,G,"y"))?h.calc=!0:on.update(h,Y),c[n]||(c[n]={});var X=c[n][r];X||(X=c[n][r]={}),X[V]=w,delete t[b]}else"reverse"===T?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==O&&"select"!==O?h.plot=!0:z?on.update(h,z):h.calc=!0,_.set(w))}}for(n in c){Cf.applyContainerArrayChanges(e,rt.nestedProperty(i,n),c[n],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(r=0;r=0&&n=0&&n=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var n=0;return function(){if(e&&++n===t)return e()}}return void 0===r._frameWaitingCnt&&(r._frameWaitingCnt=0),new Promise(function(i,c){function u(){r._currentFrame&&r._currentFrame.onComplete&&r._currentFrame.onComplete();var t=r._currentFrame=r._frameQueue.shift();if(t){var n=t.name?t.name.toString():null;e._fullLayout._currentFrame=n,r._lastFrameAt=Date.now(),r._timeToNext=t.frameOpts.duration,Hr.transition(e,t.frame.data,t.frame.layout,xf.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:n,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(r._animationRaf),r._animationRaf=null}function d(){e.emit("plotly_animating"),r._lastFrameAt=-1/0,r._timeToNext=0,r._runningTransitions=0,r._currentFrame=null;var t=function(){r._animationRaf=window.requestAnimationFrame(t),Date.now()-r._lastFrameAt>r._timeToNext&&u()};t()}var f,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&rt.isPlainObject(t))v.push({type:"object",data:g(rt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(f=0;f0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;r--)if(rt.isPlainObject(t[r])){var f=t[r].name,h=(s[f]||d[f]||{}).name,p=t[r].name,g=s[h]||d[h];h&&p&&"number"==typeof p&&g&&fp<5&&(fp++,rt.warn('addFrames: overwriting frame "'+(s[h]||d[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===fp&&rt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),d[f]={name:f},u.push({frame:Hr.supplyFrameDefaults(t[r]),index:n&&void 0!==n[r]&&null!==n[r]?n[r]:c+r})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;r--){if("number"==typeof(a=u[r].frame).name&&rt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;n--)r=t[n],i.push({type:"delete",index:r}),o.unshift({type:"insert",index:r,value:a[r]});var l=Hr.modifyFrames,s=Hr.modifyFrames,c=[e,o],u=[e,i];return yf&&yf.add(e,l,c,s,u),Hr.modifyFrames(e,i)},sp.purge=function(e){var t=(e=rt.getGraphDiv(e))._fullLayout||{},n=e._fullData||[];return Hr.cleanPlot([],{},n,t),Hr.purge(e),Ti.purge(e),t._container&&t._container.remove(),delete e._context,e};var Cp={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},Sp=xi.EventEmitter;var Op=function(e){var t=e.emitter||new Sp,n=new Promise(function(r,a){var i=window.Image,o=e.svg,l=e.format||"png";if(rt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?n:t.emit("error",s)}var c=e.canvas,u=e.scale||1,d=u*(e.width||300),f=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=d,c.height=f,p.onload=function(){var n;switch("svg"!==l&&h.drawImage(p,0,0,d,f),l){case"jpeg":n=c.toDataURL("image/jpeg");break;case"png":n=c.toDataURL("image/png");break;case"webp":n=c.toDataURL("image/webp");break;case"svg":n=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}r(n),e.promise||t.emit("success",n)},p.onerror=function(n){if(a(n),!e.promise)return t.emit("error",n)},p.src=g});return e.promise?n:t},zp=/"/g,Pp=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var Dp=function(n,r,a){var i,o=n._fullLayout,l=o._paper,s=o._toppaper,c=o.width,u=o.height;l.insert("rect",":first-child").call(Yn.setRect,0,0,c,u).call(xt.fill,o.paper_bgcolor);var d=o._basePlotModules||[];for(i=0;i")?"":n.html(e).text()});return n.remove(),r}(v),v=(v=v.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(Pp,"'"),rt.isIE()&&(v=(v=(v=v.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),v},Ep={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},Np=/^data:image\/\w+;base64,/;var Ip=function(e,t){var n,r,a;function i(e){return!(e in t)||rt.validate(t[e],Ep[e])}if(t=t||{},rt.isPlainObject(e)?(n=e.data||[],r=e.layout||{},a=e.config||{}):(e=rt.getGraphDiv(e),n=rt.extendDeep([],e.data),r=rt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,n){return rt.coerce(t,o,Ep,e,n)}var s=l("format"),c=l("width"),u=l("height"),d=l("scale"),f=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=rt.extendFlat({},r);c&&(g.width=c),u&&(g.height=u);var v=rt.extendFlat({},a,{staticPlot:!0,setBackground:f}),y=Cp.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,Cp.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var n=Dp(p,s,d),r=p._fullLayout.width,a=p._fullLayout.height;if(sp.purge(p),document.body.removeChild(p),"svg"===s)return e(h?n:"data:image/svg+xml,"+encodeURIComponent(n));var i=document.createElement("canvas");i.id=rt.randstr(),Op({format:s,width:r,height:a,scale:d,canvas:i,svg:n,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){sp.plot(p,n,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(Np,""):e}(t))}).catch(function(e){t(e)})})},Rp=rt.isPlainObject,Fp=Array.isArray,Bp=rt.isArrayOrTypedArray;function jp(e,t,n,r,a,i){i=i||[];for(var o=Object.keys(e),l=0;ld.length&&r.push(Vp("unused",a,c.concat(d.length)));var v,y,m,x,b,_=d.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===f.dimensions)for(y=0;y<_;y++)if(Fp(u[y])){u[y].length>d[y].length&&r.push(Vp("unused",a,c.concat(y,d[y].length)));var k=d[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=d[y][v],rt.validate(x,m)?b!==x&&b!==+x&&r.push(Vp("dynamic",a,c.concat(y,v),x,b)):r.push(Vp("value",a,c.concat(y,v),x))}else r.push(Vp("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=d[y],rt.validate(x,m)?b!==x&&b!==+x&&r.push(Vp("dynamic",a,c.concat(y),x,b)):r.push(Vp("value",a,c.concat(y),x))}else if(f.items&&!h&&Fp(u)){var M,T,A=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(Vp("object","layout"))),Hr.supplyDefaults(o);for(var l=o._fullData,s=n.length,c=0;c-1&&(l[c[n]].title="");for(n=0;nI!=(L=w[b][1])>=I&&(M=w[b-1][0],T=w[b][0],L-A&&(k=M+(T-M)*(I-A)/(L-A),z=Math.min(z,k),P=Math.max(P,k)));z=Math.max(z,0),P=Math.min(P,o._length);var R=xt.defaultLine;return xt.opacity(i.fillcolor)?R=i.fillcolor:xt.opacity((i.line||{}).color)&&(R=i.line.color),rt.extendFlat(e,{distance:e.maxHoverDistance,x0:z,x1:P,y0:I,y1:I,color:R}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},bg=r.BADNUM,_g=rt.segmentsIntersect,wg=rt.constrain,kg=function(e,t){var n,r,a,i,o,l,s,c,u,d,f,h,p,g,v,y,m=t.xaxis,x=t.yaxis,b=t.simplify,_=t.connectGaps,w=t.baseTolerance,k=t.shape,M="linear"===k,T=[],A=gr.minTolerance,L=new Array(e.length),C=0;function S(t){var n=e[t],r=m.c2p(n.x),a=x.c2p(n.y);return r===bg||a===bg?n.intoCenter||!1:[r,a]}function O(e){var t=e[0]/m._length,n=e[1]/x._length;return(1+gr.toleranceGrowth*Math.max(0,-t,t-1,-n,n-1))*w}function z(e,t){var n=e[0]-t[0],r=e[1]-t[1];return Math.sqrt(n*n+r*r)}b||(w=A=-1);var P,D,E,N,I,R,F,B=gr.maxScreensAway,j=-m._length*B,q=m._length*(1+B),H=-x._length*B,V=x._length*(1+B),U=[[j,H,q,H],[q,H,q,V],[q,V,j,V],[j,V,j,H]];function G(e){if(e[0]q||e[1]V)return[wg(e[0],j,q),wg(e[1],H,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===j||e[0]===q)||(e[1]===t[1]&&(e[1]===H||e[1]===V)||void 0)}function Z(e,t,n){return function(r,a){var i=G(r),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*rt.constrain((r[e]+a[e])/2,t,n)-((i||r)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function X(e){var t=e[0],n=e[1],r=t===L[C-1][0],a=n===L[C-1][1];if(!r||!a)if(C>1){var i=t===L[C-2][0],o=n===L[C-2][1];r&&(t===j||t===q)&&i?o?C--:L[C-1]=e:a&&(n===H||n===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&X([E,N]),X(e),I=null,E=N=0}function Q(e){if(P=e[0]q?q:0,D=e[1]V?V:0,P||D){if(C)if(I){var t=F(I,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else R=F(L[C-1],e)[0],L[C++]=R;else L[C++]=[P||e[0],D||e[1]];var n=L[C-1];P&&D&&(n[0]!==P||n[1]!==D)?(I&&(E!==P&&N!==D?X(E&&N?(r=I,i=(a=e)[0]-r[0],o=(a[1]-r[1])/i,(r[1]*a[0]-a[1]*r[0])/i>0?[o>0?j:q,V]:[o>0?q:j,H]):[E||P,N||D]):E&&N&&X([E,N])),X([P,D])):E-P&&N-D&&X([P||E,D||N]),I=e,E=P,N=D}else I&&W(F(I,e)[0]),L[C++]=e;var r,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var n=[],r=0,a=0;a<4;a++){var i=U[a],o=_g(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!r||Math.abs(o.x-n[0][0])>1||Math.abs(o.y-n[0][1])>1)&&(o=[o.x,o.y],r&&z(o,e)O(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>f?(f=p,i=l,s=!1):p=e.length||!l)break;Q(l),r=l}}else Q(i)}I&&X([E||I[0],N||I[1]]),T.push(L.slice(0,C))}return T},Mg=ih.tester,Tg=function(t,n,r,a,i){var o,l,s,c,u=n.plot.select("g.scatterlayer"),d=!a,f=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(r,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,n){var r,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),f)?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){Ag(t,i,n,e,r,this,a)})})):u.selectAll("g.trace").each(function(e,i){Ag(t,i,n,e,r,this,a)});d&&s.exit().remove(),u.selectAll("path:not([d])").remove()};function Ag(t,n,r,a,i,o,l){var s,c;!function(t,n,r,a,i){var o=r.xaxis,l=r.yaxis,s=e.extent(rt.simpleMap(o.range,o.r2c)),c=e.extent(rt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Gn.hasMarkers(u))return;var d=u.marker.maxdisplayed;if(0===d)return;var f=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(f.length/d),p=0;i.forEach(function(e,t){var r=e[0].trace;Gn.hasMarkers(r)&&r.marker.maxdisplayed>0&&t0;function d(e){return u?e.transition():e}var f=r.xaxis,h=r.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(D.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var y,m;d(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),a[0].node3=v;var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,T,A,L,C,S,O,z,P="",E="",N=[],I=rt.noop;if(y=p._ownFill,Gn.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=Yn.steps(g.shape),A=Yn.steps(g.shape.split("").reverse().join(""))):T=A="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Yn.smoothclosed(e.slice(1),g.smoothing):Yn.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return A(e.reverse())},N=kg(a,{xaxis:f,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),z=p._polygons=new Array(N.length),c=0;c1){var r=e.select(this);if(r.datum(a),t)d(r.style("opacity",0).attr("d",k).call(Yn.lineGroupStyle)).style("opacity",1);else{var i=d(r);i.attr("d",k),Yn.singleLineStyle(a,i)}}}}}var R=v.selectAll(".js-line").data(N);d(R.exit()).style("opacity",0).remove(),R.each(I(!1)),R.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Yn.lineGroupStyle).each(I(!0)),Yn.setClipUrl(R,r.layerClipId),N.length?(y?C&&O&&(x?("y"===x?C[1]=O[1]=h.c2p(0,!0):"x"===x&&(C[0]=O[0]=f.c2p(0,!0)),d(y).attr("d","M"+O+"L"+C+"L"+P.substr(1)).call(Yn.singleFillStyle)):d(y).attr("d",P+"Z").call(Yn.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&P&&b?("tonext"===p.fill?d(m).attr("d",P+"Z"+b+"Z").call(Yn.singleFillStyle):d(m).attr("d",P+"L"+b.substr(1)+"Z").call(Yn.singleFillStyle),p._polygons=p._polygons.concat(_)):(B(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=z):(y?B(y):m&&B(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Yn.setClipUrl(e.select(this),n?null:r.layerClipId)})}function B(e){d(e).attr("d","M0,0Z")}function j(e){return e.filter(function(e){return e.vis})}function q(e){return e.id}function H(e){if(e.ids)return q}function V(){return!1}function U(n){var a,i=n[0].trace,o=e.select(this),l=Gn.hasMarkers(i),s=Gn.hasText(i),c=H(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?j:rt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?j:rt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Yn.pointStyle,i,t).call(Yn.translatePoints,f,h).style("opacity",0).transition().style("opacity",1);var y=l&&Yn.tryColorscale(i.marker,""),m=l&&Yn.tryColorscale(i.marker,"line");a.order(),a.each(function(n){var a=e.select(this),o=d(a);Yn.translatePoint(n,o,f,h)?(Yn.singlePointStyle(n,o,i,y,m,t),r.layerClipId&&Yn.hideOutsideRangePoint(n,o,f,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==n.data&&void 0!==n.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var n=e.select(this),a=d(n.select("text"));Yn.translatePoint(t,a,f,h)?r.layerClipId&&Yn.hideOutsideRangePoint(t,n,f,h,i.xcalendar,i.ycalendar):n.remove()}),a.selectAll("text").call(Yn.textPointStyle,i,t).each(function(t){var n=f.c2p(t.x),r=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){d(e.select(this)).attr({x:n,y:r})})}),a.exit().remove()}}var Lg=function(e,t){var n,r,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Gn.hasMarkers(u)&&!Gn.hasText(u))return[];if(!1===t)for(n=0;n=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===n.xaxis&&i.yaxis===n.yaxis){i.opacity=void 0;break}}}}},zg.calc=ug,zg.arraysToCalcdata=ag,zg.plot=Tg,zg.colorbar=Vo,zg.style=Sg,zg.hoverPoints=xg,zg.selectPoints=Lg,zg.animatable=!0,zg.moduleType="trace",zg.name="scatter",zg.basePlotModule=Xa,zg.categories=["cartesian","symbols","markerColorscale","errorBarsOK","showLegend","scatter-like"],zg.meta={};var Pg=zg,Dg={version:"1.35.2"};Mc.polyfill();for(var Eg=Dg.register=D.register,Ng=Object.keys(Qp),Ig=0;Igc.size/1.9?c.size:c.size/Math.ceil(c.size/g);var _=c.start+(c.size-g)/2;v=_-g*Math.ceil((_-v)/g)}for(o=0;o=0&&h=0;r--)l(r);else if("increasing"===t){for(r=1;r=0;r--)e[r]+=e[r+1];"exclude"===n&&(e.push(0),e.shift())}}(i,u.direction,u.currentbin);var j=Math.min(a.length,i.length),q=[],H=0,V=j-1;for(r=0;r=H;r--)if(i[r]){V=r;break}for(r=H;r<=V;r++)if(n(a[r])&&n(i[r])){var U={p:a[r],s:i[r],b:0};u.enabled||(U.pts=w[r],N?U.p0=U.p1=w[r].length?v[w[r][0]]:a[r]:(U.p0=D(m[r]),U.p1=D(m[r+1],!0))),q.push(U)}return 1===q.length&&(q[0].width1=ha.tickIncrement(q[0].p,g.size,!1,c)-q[0].p),ni(q,t),rt.isArrayOrTypedArray(t.selectedpoints)&&rt.tagSelected(q,t,F),q}},ev.setPositions=Ao,ev.plot=go,ev.style=Fo,ev.colorbar=Vo,ev.hoverPoints=function(e,t,n,r){var a=io(e,t,n,r);if(a){var i=(e=a[0]).cd[e.index],o=e.cd[0].trace;if(!o.cumulative.enabled){var l="h"===o.orientation?"y":"x";e[l+"Label"]=Kg(e[l+"a"],i.p0,i.p1)}return a}},ev.selectPoints=bo,ev.eventData=$g,ev.moduleType="trace",ev.name="histogram",ev.basePlotModule=Xa,ev.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],ev.meta={};var tv=ev,nv=m.extendFlat,rv=nv({},{x:Vg.x,y:Vg.y,z:{valType:"data_array",editType:"calc"},marker:{color:{valType:"data_array",editType:"calc"},editType:"calc"},histnorm:Vg.histnorm,histfunc:Vg.histfunc,autobinx:Vg.autobinx,nbinsx:Vg.nbinsx,xbins:Vg.xbins,autobiny:Vg.autobiny,nbinsy:Vg.nbinsy,ybins:Vg.ybins,xgap:Tl.xgap,ygap:Tl.ygap,zsmooth:Tl.zsmooth,zhoverformat:Tl.zhoverformat},Qt,{autocolorscale:nv({},Qt.autocolorscale,{dflt:!1})},{colorbar:dn}),av=function(e,t,n,r){var a=n("x"),i=n("y");if(a&&a.length&&i&&i.length){D.getComponentMethod("calendars","handleTraceDefaults")(e,t,["x","y"],r),(n("z")||n("marker.color"))&&n("histfunc");Jg(0,t,n,["x","y"])}else t.visible=!1},iv=ha.hoverLabelText,ov={};ov.attributes=rv,ov.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,rv,n,r)}av(e,t,a,r),!1!==t.visible&&(jg(0,0,a),hn(e,t,r,a,{prefix:"",cLetter:"z"}))},ov.calc=fs,ov.plot=Gs,ov.colorbar=Bg,ov.style=tc,ov.hoverPoints=function(e,t,n,r,a,i){var o=Cs(e,t,n,0,0,i);if(o){var l=(e=o[0]).index,s=l[0],c=l[1],u=e.cd[0],d=u.xRanges[c],f=u.yRanges[s];return e.xLabel=iv(e.xa,d[0],d[1]),e.yLabel=iv(e.ya,f[0],f[1]),o}},ov.eventData=$g,ov.moduleType="trace",ov.name="histogram2d",ov.basePlotModule=Xa,ov.categories=["cartesian","2dMap","histogram"],ov.meta={};var lv=ov,sv=m.extendFlat,cv=sv({x:rv.x,y:rv.y,z:rv.z,marker:rv.marker,histnorm:rv.histnorm,histfunc:rv.histfunc,autobinx:rv.autobinx,nbinsx:rv.nbinsx,xbins:rv.xbins,autobiny:rv.autobiny,nbinsy:rv.nbinsy,ybins:rv.ybins,autocontour:zl.autocontour,ncontours:zl.ncontours,contours:zl.contours,line:zl.line,zhoverformat:rv.zhoverformat},Qt,{zmin:sv({},Qt.zmin,{editType:"calc"}),zmax:sv({},Qt.zmax,{editType:"calc"})},{colorbar:dn}),uv={};uv.attributes=cv,uv.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,cv,n,r)}av(e,t,a,r),!1!==t.visible&&(ks(0,t,a,function(n){return rt.coerce2(e,t,cv,n)}),Ms(e,t,a,r))},uv.calc=hs,uv.plot=Qs.plot,uv.style=nc,uv.colorbar=vs,uv.hoverPoints=Ss,uv.moduleType="trace",uv.name="histogram2dcontour",uv.basePlotModule=Xa,uv.categories=["cartesian","2dMap","contour","histogram"],uv.meta={};var dv=uv,fv=au.attributes,hv=m.extendFlat,pv=L({editType:"calc",colorEditType:"style"}),gv={labels:{valType:"data_array",editType:"calc"},label0:{valType:"number",dflt:0,editType:"calc"},dlabel:{valType:"number",dflt:1,editType:"calc"},values:{valType:"data_array",editType:"calc"},marker:{colors:{valType:"data_array",editType:"calc"},line:{color:{valType:"color",dflt:O.defaultLine,arrayOk:!0,editType:"style"},width:{valType:"number",min:0,dflt:0,arrayOk:!0,editType:"style"},editType:"calc"},editType:"calc"},text:{valType:"data_array",editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:hv({},S.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0,editType:"calc"},textfont:hv({},pv,{}),insidetextfont:hv({},pv,{}),outsidetextfont:hv({},pv,{}),domain:fv({name:"pie",trace:!0,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:!0,editType:"calc"},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"number",min:-360,max:360,dflt:0,editType:"calc"},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0,editType:"calc"}},vv={};vv.name="pie",vv.plot=function(e){var t=D.getModule("pie"),n=function(e,t){for(var n=[],r=0;r0?1:-1)/2,y:i/(1+n*n/(r*r)),outside:!0}}var Lv={};Lv.attributes=gv,Lv.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,gv,n,r)}var i=rt.coerceFont,o=a("values"),l=a("labels");if(!Array.isArray(l)){if(!rt.isArrayOrTypedArray(o)||!o.length)return void(t.visible=!1);a("label0"),a("dlabel")}a("marker.line.width")&&a("marker.line.color"),a("marker.colors"),a("scalegroup");var s=a("text"),c=a("textinfo",Array.isArray(s)?"text+percent":"percent");if(a("hovertext"),c&&"none"!==c){var u=a("textposition"),d=Array.isArray(u)||"auto"===u,f=d||"inside"===u,h=d||"outside"===u;if(f||h){var p=i(a,"textfont",r.font);f&&i(a,"insidetextfont",p),h&&i(a,"outsidetextfont",p)}}_v(t,r,a),a("hole"),a("sort"),a("direction"),a("rotation"),a("pull")},Lv.supplyLayoutDefaults=function(e,t){var n,r;n="hiddenlabels",rt.coerce(e,t,wv,n,r)},Lv.layoutAttributes=wv,Lv.calc=function(e,t){var r,a,i,o,l,c=t.values,u=mv(c)&&c.length,d=t.labels,f=t.marker.colors||[],h=[],p=e._fullLayout,g=p.colorway,v=p._piecolormap,y={},m=0,x=p.hiddenlabels||[];if(p._piecolorway||g===xt.defaults||(p._piecolorway=bv(g)),t.dlabel)for(d=new Array(c.length),r=0;r")}}return h},Lv.plot=function(t,n){var r=t._fullLayout;!function(e,t){var n,r,a,i,o,l,s,c,u,d=[];for(a=0;as&&(s=l.pull[i]);o.r=Math.min(n,r)/(2+2*s),o.cx=t.l+t.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=t.t+t.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===d.indexOf(l.scalegroup)&&d.push(l.scalegroup)}for(i=0;ia.vTotal/2?1:0)}(n),a.each(function(){var a=e.select(this).selectAll("g.slice").data(n);a.enter().append("g").classed("slice",!0),a.exit().remove();var l=[[[],[]],[[],[]]],s=!1;a.each(function(n){if(n.hidden)e.select(this).selectAll("path,g").remove();else{n.pointNumber=n.i,n.curveNumber=o.index,l[n.pxmid[1]<0?0:1][n.pxmid[0]<0?0:1].push(n);var a=i.cx,c=i.cy,u=e.select(this),d=u.selectAll("path.surface").data([n]),f=!1,h=!1;if(d.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),u.select("path.textline").remove(),u.on("mouseover",function(){var l=t._fullLayout,s=t._fullData[o.index];if(!t._dragging&&!1!==l.hovermode){var u=s.hoverinfo;if(Array.isArray(u)&&(u=no.castHoverinfo({hoverinfo:[wu.castOption(u,n.pts)],_module:o._module},l,0)),"all"===u&&(u="label+text+value+percent+name"),"none"!==u&&"skip"!==u&&u){var d=Tv(n,i),p=a+n.pxmid[0]*(1-d),g=c+n.pxmid[1]*(1-d),v=r.separators,y=[];if(-1!==u.indexOf("label")&&y.push(n.label),-1!==u.indexOf("text")){var m=wu.castOption(s.hovertext||s.text,n.pts);m&&y.push(m)}-1!==u.indexOf("value")&&y.push(wu.formatPieValue(n.v,v)),-1!==u.indexOf("percent")&&y.push(wu.formatPiePercent(n.v/i.vTotal,v));var x=o.hoverlabel,b=x.font;no.loneHover({x0:p-d*i.r,x1:p+d*i.r,y:g,text:y.join("
"),name:-1!==u.indexOf("name")?s.name:void 0,idealAlign:n.pxmid[0]<0?"left":"right",color:wu.castOption(x.bgcolor,n.pts)||n.color,borderColor:wu.castOption(x.bordercolor,n.pts),fontFamily:wu.castOption(b.family,n.pts),fontSize:wu.castOption(b.size,n.pts),fontColor:wu.castOption(b.color,n.pts)},{container:l._hoverlayer.node(),outerContainer:l._paper.node(),gd:t}),f=!0}t.emit("plotly_hover",{points:[Mv(n,s)],event:e.event}),h=!0}}).on("mouseout",function(r){var a=t._fullLayout,i=t._fullData[o.index];h&&(r.originalEvent=e.event,t.emit("plotly_unhover",{points:[Mv(n,i)],event:e.event}),h=!1),f&&(no.loneUnhover(a._hoverlayer.node()),f=!1)}).on("click",function(){var r=t._fullLayout,a=t._fullData[o.index];t._dragging||!1===r.hovermode||(t._hoverdata=[Mv(n,a)],no.click(t,e.event))}),o.pull){var p=+wu.castOption(o.pull,n.pts)||0;p>0&&(a+=p*n.pxmid[0],c+=p*n.pxmid[1])}n.cxFinal=a,n.cyFinal=c;var g=o.hole;if(n.v===i.vTotal){var v="M"+(a+n.px0[0])+","+(c+n.px0[1])+_(n.px0,n.pxmid,!0,1)+_(n.pxmid,n.px0,!0,1)+"Z";g?d.attr("d","M"+(a+g*n.px0[0])+","+(c+g*n.px0[1])+_(n.px0,n.pxmid,!1,g)+_(n.pxmid,n.px0,!1,g)+"Z"+v):d.attr("d",v)}else{var y=_(n.px0,n.px1,!0,1);if(g){var m=1-g;d.attr("d","M"+(a+g*n.px1[0])+","+(c+g*n.px1[1])+_(n.px1,n.px0,!1,g)+"l"+m*n.px0[0]+","+m*n.px0[1]+y+"Z")}else d.attr("d","M"+a+","+c+"l"+n.px0[0]+","+n.px0[1]+y+"Z")}var x=wu.castOption(o.textposition,n.pts),b=u.selectAll("g.slicetext").data(n.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var r=e.select(this).selectAll("text").data([0]);r.enter().append("text").attr("data-notex",1),r.exit().remove(),r.text(n.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Yn.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(bn.convertToTspans,t);var l,u=Yn.bBox(r.node());"outside"===x?l=Av(u,n):(l=function(e,t,n){var r=Math.sqrt(e.width*e.width+e.height*e.height),a=e.width/e.height,i=Math.PI*Math.min(t.v/n.vTotal,.5),o=1-n.trace.hole,l=Tv(t,n),s={scale:l*n.r*2/r,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=n.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),d={scale:2*u/e.height,rCenter:Math.cos(u/n.r)-u*a/n.r,rotate:(180/Math.PI*t.midangle+720)%180-90},f=1/a,h=f+1/(2*Math.tan(i)),p=n.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(f*f+o/2)+f)),g={scale:2*p/e.width,rCenter:Math.cos(p/n.r)-p/a/n.r,rotate:(180/Math.PI*t.midangle+810)%180-90},v=g.scale>d.scale?g:d;return s.scale<1&&v.scale>s.scale?v:s}(u,n,i),"auto"===x&&l.scale<1&&(r.call(Yn.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(u=Yn.bBox(r.node())),l=Av(u,n)));var d=a+n.pxmid[0]*l.rCenter+(l.x||0),f=c+n.pxmid[1]*l.rCenter+(l.y||0);l.outside&&(n.yLabelMin=f-u.height/2,n.yLabelMid=f,n.yLabelMax=f+u.height/2,n.labelExtraX=0,n.labelExtraY=0,s=!0),r.attr("transform","translate("+d+","+f+")"+(l.scale<1?"scale("+l.scale+")":"")+(l.rotate?"rotate("+l.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function _(e,t,r,a){return"a"+a*i.r+","+a*i.r+" 0 "+n.largeArc+(r?" 1 ":" 0 ")+a*(t[0]-e[0])+","+a*(t[1]-e[1])}}),s&&function(e,t){var n,r,a,i,o,l,s,c,u,d,f,h,p;function g(e,t){return e.pxmid[1]-t.pxmid[1]}function v(e,t){return t.pxmid[1]-e.pxmid[1]}function y(e,n){n||(n={});var a,c,u,f,h,p,g=n.labelExtraY+(r?n.yLabelMax:n.yLabelMin),v=r?e.yLabelMin:e.yLabelMax,y=r?e.yLabelMax:e.yLabelMin,m=e.cyFinal+o(e.px0[1],e.px1[1]),x=g-v;if(x*s>0&&(e.labelExtraY=x),Array.isArray(t.pull))for(c=0;c=(wu.castOption(t.pull,u.pts)||0)||((e.pxmid[1]-u.pxmid[1])*s>0?(f=u.cyFinal+o(u.px0[1],u.px1[1]),(x=f-v-e.labelExtraY)*s>0&&(e.labelExtraY+=x)):(y+e.labelExtraY-m)*s>0&&(a=3*l*Math.abs(c-d.indexOf(e)),h=u.cxFinal+i(u.px0[0],u.px1[0]),(p=h+a-(e.cxFinal+e.pxmid[0])-e.labelExtraX)*l>0&&(e.labelExtraX+=p)))}for(r=0;r<2;r++)for(a=r?g:v,o=r?Math.max:Math.min,s=r?1:-1,n=0;n<2;n++){for(i=n?Math.max:Math.min,l=n?1:-1,(c=e[r][n]).sort(a),u=e[1-r][n],d=u.concat(c),h=[],f=0;fMath.abs(c)?i+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):i+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else i+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;n.append("path").classed("textline",!0).call(xt.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:i,fill:"none"})}})})}),setTimeout(function(){a.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},Lv.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var n=t[0].trace,r=e.select(this);r.style({opacity:n.opacity}),r.selectAll("path.surface").each(function(t){e.select(this).call(Mu,t,n)})})},Lv.styleOne=Mu,Lv.moduleType="trace",Lv.name="pie",Lv.basePlotModule=vv,Lv.categories=["pie","showLegend"],Lv.meta={};var Cv=Lv,Sv=au.defaults,Ov=m.extendFlat,zv={title:mt.title,titlefont:mt.titlefont,color:mt.color,tickmode:mt.tickmode,nticks:Ov({},mt.nticks,{dflt:6,min:1}),tick0:mt.tick0,dtick:mt.dtick,tickvals:mt.tickvals,ticktext:mt.ticktext,ticks:mt.ticks,ticklen:mt.ticklen,tickwidth:mt.tickwidth,tickcolor:mt.tickcolor,showticklabels:mt.showticklabels,showtickprefix:mt.showtickprefix,tickprefix:mt.tickprefix,showticksuffix:mt.showticksuffix,ticksuffix:mt.ticksuffix,showexponent:mt.showexponent,exponentformat:mt.exponentformat,separatethousands:mt.separatethousands,tickfont:mt.tickfont,tickangle:mt.tickangle,tickformat:mt.tickformat,tickformatstops:mt.tickformatstops,hoverformat:mt.hoverformat,showline:Ov({},mt.showline,{dflt:!0}),linecolor:mt.linecolor,linewidth:mt.linewidth,showgrid:Ov({},mt.showgrid,{dflt:!0}),gridcolor:mt.gridcolor,gridwidth:mt.gridwidth,layer:mt.layer,min:{valType:"number",dflt:0,min:0}},Pv=function(e,t,n){function r(n,r){return rt.coerce(e,t,zv,n,r)}t.type="linear";var a=r("color"),i=a===e.color?a:n.font.color,o=t._name.charAt(0).toUpperCase(),l="Component "+o,s=r("title",l);t._hovertitle=s===l?s:o,rt.coerceFont(r,"titlefont",{family:n.font.family,size:Math.round(1.2*n.font.size),color:i}),r("min"),Bt(e,t,r,"linear"),It(e,t,r,"linear",{}),Rt(e,t,r,{outerTicks:!0}),r("showticklabels")&&(rt.coerceFont(r,"tickfont",{family:n.font.family,size:n.font.size,color:i}),r("tickangle"),r("tickformat")),At(e,t,r,{dfltColor:a,bgColor:n.bgColor,blend:60,showLine:!0,showGrid:!0,noZeroLine:!0,attributes:zv}),r("hoverformat"),r("layer")},Dv=au.attributes,Ev=(0,on.overrideAll)({domain:Dv({name:"ternary"}),bgcolor:{valType:"color",dflt:O.background},sum:{valType:"number",dflt:1,min:0},aaxis:zv,baxis:zv,caxis:zv},"plot","from-root"),Nv=["aaxis","baxis","caxis"];function Iv(e,t,n,r){var a,i,o,l=n("bgcolor"),s=n("sum");r.bgColor=xt.combine(l,r.paper_bgcolor);for(var c=0;c=s&&(u.min=0,d.min=0,f.min=0,e.aaxis&&delete e.aaxis.min,e.baxis&&delete e.baxis.min,e.caxis&&delete e.caxis.min)}var Rv=rt._,Fv=m.extendFlat;function Bv(e,t){this.id=e.id,this.graphDiv=e.graphDiv,this.init(t),this.makeFramework(t)}var jv=Bv,qv=Bv.prototype;qv.init=function(e){this.container=e._ternarylayer,this.defs=e._defs,this.layoutId=e._uid,this.traceHash={},this.layers={}},qv.plot=function(e,t){var n=t[this.id],r=t._size;this._hasClipOnAxisFalse=!1;for(var a=0;aHv*g?a=(i=g)*Hv:i=(a=p)/Hv,o=f*a/p,l=h*i/g,n=t.l+t.w*u-a/2,r=t.t+t.h*(1-d)-i/2,s.x0=n,s.y0=r,s.w=a,s.h=i,s.sum=v,s.xaxis={type:"linear",range:[y+2*x-v,v-y-2*m],domain:[u-o/2,u+o/2],_id:"x"},Nt(s.xaxis,s.graphDiv._fullLayout),s.xaxis.setScale(),s.xaxis.isPtWithinRange=function(e){return e.a>=s.aaxis.range[0]&&e.a<=s.aaxis.range[1]&&e.b>=s.baxis.range[1]&&e.b<=s.baxis.range[0]&&e.c>=s.caxis.range[1]&&e.c<=s.caxis.range[0]},s.yaxis={type:"linear",range:[y,v-m-x],domain:[d-l/2,d+l/2],_id:"y"},Nt(s.yaxis,s.graphDiv._fullLayout),s.yaxis.setScale(),s.yaxis.isPtWithinRange=function(){return!0};var b=s.yaxis.domain[0],_=s.aaxis=Fv({},e.aaxis,{visible:!0,range:[y,v-m-x],side:"left",_counterangle:30,tickangle:(+e.aaxis.tickangle||0)-30,domain:[b,b+l*Hv],_axislayer:s.layers.aaxis,_gridlayer:s.layers.agrid,_pos:0,_id:"y",_length:a,_gridpath:"M0,0l"+i+",-"+a/2,automargin:!1});Nt(_,s.graphDiv._fullLayout),_.setScale();var w=s.baxis=Fv({},e.baxis,{visible:!0,range:[v-y-x,m],side:"bottom",_counterangle:30,domain:s.xaxis.domain,_axislayer:s.layers.baxis,_gridlayer:s.layers.bgrid,_counteraxis:s.aaxis,_pos:0,_id:"x",_length:a,_gridpath:"M0,0l-"+a/2+",-"+i,automargin:!1});Nt(w,s.graphDiv._fullLayout),w.setScale(),_._counteraxis=w;var k=s.caxis=Fv({},e.caxis,{visible:!0,range:[v-y-m,x],side:"right",_counterangle:30,tickangle:(+e.caxis.tickangle||0)+30,domain:[b,b+l*Hv],_axislayer:s.layers.caxis,_gridlayer:s.layers.cgrid,_counteraxis:s.baxis,_pos:0,_id:"y",_length:a,_gridpath:"M0,0l-"+i+","+a/2,automargin:!1});Nt(k,s.graphDiv._fullLayout),k.setScale();var M="M"+n+","+(r+i)+"h"+a+"l-"+a/2+",-"+i+"Z";s.clipDef.select("path").attr("d",M),s.layers.plotbg.select("path").attr("d",M);var T="M0,"+i+"h"+a+"l-"+a/2+",-"+i+"Z";s.clipDefRelative.select("path").attr("d",T);var A="translate("+n+","+r+")";s.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",A),s.clipDefRelative.select("path").attr("transform",null);var L="translate("+(n-w._offset)+","+(r+i)+")";s.layers.baxis.attr("transform",L),s.layers.bgrid.attr("transform",L);var C="translate("+(n+a/2)+","+r+")rotate(30)translate(0,"+-_._offset+")";s.layers.aaxis.attr("transform",C),s.layers.agrid.attr("transform",C);var S="translate("+(n+a/2)+","+r+")rotate(-30)translate(0,"+-k._offset+")";s.layers.caxis.attr("transform",S),s.layers.cgrid.attr("transform",S),s.drawAxes(!0),s.plotContainer.selectAll(".crisp").classed("crisp",!1),s.layers.aline.select("path").attr("d",_.showline?"M"+n+","+(r+i)+"l"+a/2+",-"+i:"M0,0").call(xt.stroke,_.linecolor||"#000").style("stroke-width",(_.linewidth||0)+"px"),s.layers.bline.select("path").attr("d",w.showline?"M"+n+","+(r+i)+"h"+a:"M0,0").call(xt.stroke,w.linecolor||"#000").style("stroke-width",(w.linewidth||0)+"px"),s.layers.cline.select("path").attr("d",k.showline?"M"+(n+a/2)+","+r+"l"+a/2+","+i:"M0,0").call(xt.stroke,k.linecolor||"#000").style("stroke-width",(k.linewidth||0)+"px"),s.graphDiv._context.staticPlot||s.initInteractions(),Yn.setClipUrl(s.layers.frontplot,s._hasClipOnAxisFalse?null:s.clipId)},qv.drawAxes=function(e){var t=this.graphDiv,n=this.id.substr(7)+"title",r=this.aaxis,a=this.baxis,i=this.caxis;if(ha.doTicks(t,r,!0),ha.doTicks(t,a,!0),ha.doTicks(t,i,!0),e){var o=Math.max(r.showticklabels?r.tickfont.size/2:0,(i.showticklabels?.75*i.tickfont.size:0)+("outside"===i.ticks?.87*i.ticklen:0));this.layers["a-title"]=ta.draw(t,"a"+n,{propContainer:r,propName:this.id+".aaxis.title",placeholder:Rv(t,"Click to enter Component A title"),attributes:{x:this.x0+this.w/2,y:this.y0-r.titlefont.size/3-o,"text-anchor":"middle"}});var l=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;this.layers["b-title"]=ta.draw(t,"b"+n,{propContainer:a,propName:this.id+".baxis.title",placeholder:Rv(t,"Click to enter Component B title"),attributes:{x:this.x0-l,y:this.y0+this.h+.83*a.titlefont.size+l,"text-anchor":"middle"}}),this.layers["c-title"]=ta.draw(t,"c"+n,{propContainer:i,propName:this.id+".caxis.title",placeholder:Rv(t,"Click to enter Component C title"),attributes:{x:this.x0+this.w+l,y:this.y0+this.h+.83*i.titlefont.size+l,"text-anchor":"middle"}})}};var Vv=ht.MINZOOM/2+.87,Uv="m-0.87,.5h"+Vv+"v3h-"+(Vv+5.2)+"l"+(Vv/2+2.6)+",-"+(.87*Vv+4.5)+"l2.6,1.5l-"+Vv/2+","+.87*Vv+"Z",Gv="m0.87,.5h-"+Vv+"v3h"+(Vv+5.2)+"l-"+(Vv/2+2.6)+",-"+(.87*Vv+4.5)+"l-2.6,1.5l"+Vv/2+","+.87*Vv+"Z",Yv="m0,1l"+Vv/2+","+.87*Vv+"l2.6,-1.5l-"+(Vv/2+2.6)+",-"+(.87*Vv+4.5)+"l-"+(Vv/2+2.6)+","+(.87*Vv+4.5)+"l2.6,1.5l"+Vv/2+",-"+.87*Vv+"Z",Zv="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",Xv=!0;function Wv(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}qv.initInteractions=function(){var e,t,n,r,a,i,o,l,c,u,d=this,f=d.layers.plotbg.select("path").node(),h=d.graphDiv,p=h._fullLayout._zoomlayer,g={element:f,gd:h,plotinfo:{xaxis:d.xaxis,yaxis:d.yaxis},subplot:d.id,prepFn:function(v,y,m){g.xaxes=[d.xaxis],g.yaxes=[d.yaxis];var M=h._fullLayout.dragmode;v.shiftKey&&(M="pan"===M?"zoom":"pan"),g.minDrag="lasso"===M?1:void 0,"zoom"===M?(g.moveFn=x,g.doneFn=b,function(h,g,v){var y=f.getBoundingClientRect();e=g-y.left,t=v-y.top,n={a:d.aaxis.range[0],b:d.baxis.range[1],c:d.caxis.range[1]},a=n,r=d.aaxis.range[1]-n.a,i=s(d.graphDiv._fullLayout[d.id].bgcolor).getLuminance(),o="M0,"+d.h+"L"+d.w/2+", 0L"+d.w+","+d.h+"Z",l=!1,c=p.append("path").attr("class","zoombox").attr("transform","translate("+d.x0+", "+d.y0+")").style({fill:i>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",o),u=p.append("path").attr("class","zoombox-corners").attr("transform","translate("+d.x0+", "+d.y0+")").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),k()}(0,y,m)):"pan"===M?(g.moveFn=_,g.doneFn=w,n={a:d.aaxis.range[0],b:d.baxis.range[1],c:d.caxis.range[1]},a=n,k()):"select"!==M&&"lasso"!==M||yh(v,y,m,g,M)},clickFn:function(e,t){if(Wv(h),2===e){var n={};n[d.id+".aaxis.min"]=0,n[d.id+".baxis.min"]=0,n[d.id+".caxis.min"]=0,h.emit("plotly_doubleclick",null),D.call("relayout",h,n)}no.click(h,t,d.id)}};function v(e,t){return 1-t/d.h}function y(e,t){return 1-(e+(d.h-t)/Math.sqrt(3))/d.w}function m(e,t){return(e-(d.h-t)/Math.sqrt(3))/d.w}function x(s,f){var h=e+s,p=t+f,g=Math.max(0,Math.min(1,v(0,t),v(0,p))),x=Math.max(0,Math.min(1,y(e,t),y(h,p))),b=Math.max(0,Math.min(1,m(e,t),m(h,p))),_=(g/2+b)*d.w,w=(1-g/2-x)*d.w,k=(_+w)/2,M=w-_,T=(1-g)*d.h,A=T-M/Hv;M.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),u.transition().style("opacity",1).duration(200),l=!0)}function b(){if(Wv(h),a!==n){var e={};e[d.id+".aaxis.min"]=a.a,e[d.id+".baxis.min"]=a.b,e[d.id+".caxis.min"]=a.c,D.call("relayout",h,e),Xv&&h.data&&h._context.showTips&&(rt.notifier(Rv(h,"Double-click to zoom back out"),"long"),Xv=!1)}}function _(e,t){var r=e/d.xaxis._m,i=t/d.yaxis._m,o=[(a={a:n.a-i,b:n.b+(r+i)/2,c:n.c-(r-i)/2}).a,a.b,a.c].sort(),l=o.indexOf(a.a),s=o.indexOf(a.b),c=o.indexOf(a.c);o[0]<0&&(o[1]+o[0]/2<0?(o[2]+=o[0]+o[1],o[0]=o[1]=0):(o[2]+=o[0]/2,o[1]+=o[0]/2,o[0]=0),a={a:o[l],b:o[s],c:o[c]},t=(n.a-a.a)*d.yaxis._m,e=(n.c-a.c-n.b+a.b)*d.xaxis._m);var u="translate("+(d.x0+e)+","+(d.y0+t)+")";d.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",u);var f="translate("+-e+","+-t+")";d.clipDefRelative.select("path").attr("transform",f),d.aaxis.range=[a.a,d.sum-a.b-a.c],d.baxis.range=[d.sum-a.a-a.c,a.b],d.caxis.range=[d.sum-a.a-a.b,a.c],d.drawAxes(!1),d.plotContainer.selectAll(".crisp").classed("crisp",!1),d._hasClipOnAxisFalse&&d.plotContainer.select(".scatterlayer").selectAll(".trace").call(Yn.hideOutsideRangePoints,d)}function w(){var e={};e[d.id+".aaxis.min"]=a.a,e[d.id+".baxis.min"]=a.b,e[d.id+".caxis.min"]=a.c,D.call("relayout",h,e)}function k(){p.selectAll(".select-outline").remove()}f.onmousemove=function(e){no.hover(h,e,d.id),h._fullLayout._lasthover=f,h._fullLayout._hoversubplot=d.id},f.onmouseout=function(e){h._dragging||Li.unhover(h,e)},Li.init(g)};var Qv={},Jv=Ya.getSubplotCalcData,$v=rt.counterRegex;Qv.name="ternary",Qv.attr="subplot",Qv.idRoot="ternary",Qv.idRegex=Qv.attrRegex=$v("ternary"),Qv.attributes={subplot:{valType:"subplotid",dflt:"ternary",editType:"calc"}},Qv.layoutAttributes=Ev,Qv.supplyLayoutDefaults=function(e,t,n){!function(e,t,n,r){var a,i,o=r.type,l=r.attributes,s=r.handleDefaults,c=r.partition||"x",u=t._subplots[o],d=u.length;function f(e,t){return rt.coerce(a,i,l,e,t)}for(var h=0;h"),a}function g(e,t){p.push(e._hovertitle+": "+ha.tickText(e,t,"hover").text)}},sy.selectPoints=Lg,sy.eventData=function(e,t,n,r,a){if(t.xa&&(e.xaxis=t.xa),t.ya&&(e.yaxis=t.ya),r[a]){var i=r[a];e.a=i.a,e.b=i.b,e.c=i.c}else e.a=t.a,e.b=t.b,e.c=t.c;return e},sy.moduleType="trace",sy.name="scatterternary",sy.basePlotModule=Qv,sy.categories=["ternary","symbols","markerColorscale","showLegend","scatter-like"],sy.meta={};var cy=sy,uy=m.extendFlat,dy={y:Wo.y,x:Wo.x,x0:Wo.x0,y0:Wo.y0,name:Wo.name,orientation:uy({},Wo.orientation,{}),bandwidth:{valType:"number",min:0,editType:"calc"},scalegroup:{valType:"string",dflt:"",editType:"calc"},scalemode:{valType:"enumerated",values:["width","count"],dflt:"width",editType:"calc"},spanmode:{valType:"enumerated",values:["soft","hard","manual"],dflt:"soft",editType:"calc"},span:{valType:"info_array",items:[{valType:"any",editType:"calc"},{valType:"any",editType:"calc"}],editType:"calc"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:Wo.fillcolor,points:uy({},Wo.boxpoints,{}),jitter:uy({},Wo.jitter,{}),pointpos:uy({},Wo.pointpos,{}),marker:Wo.marker,text:Wo.text,box:{visible:{valType:"boolean",dflt:!1,editType:"plot"},width:{valType:"number",min:0,max:1,dflt:.25,editType:"plot"},fillcolor:{valType:"color",editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,editType:"style"},editType:"style"},editType:"plot"},meanline:{visible:{valType:"boolean",dflt:!1,editType:"plot"},color:{valType:"color",editType:"style"},width:{valType:"number",min:0,editType:"style"},editType:"plot"},side:{valType:"enumerated",values:["both","positive","negative"],dflt:"both",editType:"plot"},selected:Wo.selected,unselected:Wo.unselected,hoveron:{valType:"flaglist",flags:["violins","points","kde"],dflt:"violins+points+kde",extras:["all"],editType:"style"}},fy={},hy=function(e){return 1/Math.sqrt(2*Math.PI)*Math.exp(-.5*e*e)};fy.makeKDE=function(e,t,n){var r=n.length,a=hy,i=e.bandwidth,o=1/(r*i);return function(e){for(var t=0,l=0;l1,h=s.bdPos=s.dPos*(1-a.violingap)*(1-a.violingroupgap)/(f?d:1),p=s.bPos=f?2*s.dPos*((s.num+.5)/d-.5)*(1-a.violingap):0;if(!0!==c.visible||s.empty)e.select(this).remove();else{var g=n[s.valLetter+"axis"],v=n[s.posLetter+"axis"],y="both"===c.side,m=y||"positive"===c.side,x=y||"negative"===c.side,b=c.box&&c.box.visible,_=c.meanline&&c.meanline.visible,w=a._violinScaleGroupStats[c.scalegroup];if(u.selectAll("path.violin").data(rt.identity).enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","violin").each(function(t){var n,r,a,i,o,u,d,f,b=e.select(this),_=t.density,k=_.length,M=t.pos+p,T=v.c2p(M);switch(c.scalemode){case"width":n=w.maxWidth/h;break;case"count":n=w.maxWidth/h*(w.maxCount/t.pts.length)}if(m){for(d=new Array(k),o=0;o0){var p,g,v,y,m,x=e.xa,b=e.ya;"h"===s.orientation?(m=t,p="y",v=b,g="x",y=x):(m=n,p="x",v=x,g="y",y=b);var _=l[e.index];if(m>=_.span[0]&&m<=_.span[1]){var w=rt.extendFlat({},e),k=y.c2p(m,!0),M=fy.getKdeValue(_,s,m),T=fy.getPositionOnKdePath(_,s,k),A=v._offset,L=v._length;w[p+"0"]=T[0],w[p+"1"]=T[1],w[g+"0"]=w[g+"1"]=k,w[g+"Label"]=g+": "+ha.hoverLabelText(y,m)+", "+l[0].t.labels.kde+" "+M.toFixed(3),w.spikeDistance=h[0].spikeDistance;var C=p+"Spike";w[C]=h[0][C],h[0].spikeDistance=void 0,h[0][C]=void 0,f.push(w),(o={stroke:e.color})[p+"1"]=rt.constrain(A+T[0],A,A+L),o[p+"2"]=rt.constrain(A+T[1],A,A+L),o[g+"1"]=o[g+"2"]=y._offset+k}}}-1!==c.indexOf("points")&&(i=ol.hoverOnPoints(e,t,n));var S=a.selectAll(".violinline-"+s.uid).data(o?[0]:[]);return S.enter().append("line").classed("violinline-"+s.uid,!0).attr("stroke-width",1.5),S.exit().remove(),S.attr(o),"closest"===r?i?[i]:f:i?(f.push(i),f):f},selectPoints:vl,moduleType:"trace",name:"violin",basePlotModule:Xa,categories:["cartesian","symbols","oriented","box-violin","showLegend"],meta:{}};return Fg.register([Go,wl,Hg,tv,lv,dv,Cv,ac,cy,wy]),Fg}); \ No newline at end of file +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},n=[].slice,r=function(e){return n.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{r(a.documentElement.childNodes)[0].nodeType}catch(e){r=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,n){c.call(this,e,t,n+"")},u.setProperty=function(e,t,n){f.call(this,e,t+"",n)}}function d(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},t.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},t.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,n){return d(e(t),n)}:e)},t.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},t.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},t.pairs=function(e){for(var t=0,n=e.length-1,r=e[0],a=new Array(n<0?0:n);t=0;)for(t=(r=e[a]).length;--t>=0;)n[--o]=r[t];return n};var m=Math.abs;function x(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n==1/0)throw new Error("infinite range");var r,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(n)),o=-1;if(e*=i,t*=i,(n*=i)<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=a.length)return n?n.call(r,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var r=[],o=i[n++];return t.forEach(function(t,a){r.push({key:t,values:e(a,n)})}),o?r.sort(function(e,t){return o(e.key,t.key)}):r}(o(t.map,e,0),0)},r.key=function(e){return a.push(e),r},r.sortKeys=function(e){return i[a.length-1]=e,r},r.sortValues=function(t){return e=t,r},r.rollup=function(e){return n=e,r},r},t.set=function(e){var t=new z;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},t.event=null,t.requote=function(e){return e.replace(H,"\\$&")};var H=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]};function V(e){return q(e,Z),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var n=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var Z=t.selection.prototype=[];function X(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}Z.select=function(e){var t,n,r,a,i=[];e=X(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),J.hasOwnProperty(n)?{space:J[n],local:e}:e}},Z.attr=function(e,n){if(arguments.length<2){if("string"==typeof e){var r=this.node();return(e=t.ns.qualify(e)).local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}for(n in e)this.each($(n,e[n]));return this}return this.each($(e,n))},Z.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=te(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},Z.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?n?function(){var t=l(n,r(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:c:n?I:function(){var n,r=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(n=a.match(r)){var i=this[a];this.removeEventListener(n[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=Z.append,de.empty=Z.empty,de.node=Z.node,de.call=Z.call,de.size=Z.size,de.select=function(e){for(var t,n,r,a,i,o=[],l=-1,s=this.length;++l=r&&(r=t+1);!(o=l[r])&&++r0?1:e<0?-1:0}function Pe(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function De(e){return e>1?0:e<-1?Te:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Ie(e){return((e=Math.exp(e))+1/e)/2}function Ne(e){return(e=Math.sin(e/2))*e}var Re=Math.SQRT2;t.interpolateZoom=function(e,t){var n,r,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function z(e){--v||(e({type:"zoomend"}),n=null)}function O(){var e=this,n=_.of(e,arguments),r=0,a=t.select(o(e)).on(m,function(){r=1,T(t.mouse(e),i),S(n)}).on(x,function(){a.on(m,null).on(x,null),l(r),z(n)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(n)}function P(){var e,n=this,r=_.of(n,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(n),h=xe(n);function p(){var r=t.touches(n);return e=d.k,r.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),r}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var r=t.event.changedTouches,o=0,f=r.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(n);ll.call(n);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?r+(a-r)*e/60:e<180?a:e<240?r+(a-r)*(240-e)/60:r}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,r=2*(n=n<0?0:n>1?1:n)-(a=n<=.5?n*(1+t):n+t-n*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,n,r){return this instanceof Ge?(this.h=+e,this.c=+n,void(this.l=+r)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Xe?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,n,r)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new He;function Ze(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Xe(n,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Xe(e,t,n){return this instanceof Xe?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof Xe?new Xe(e.l,e.a,e.b):e instanceof Ge?Ze(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Xe(e,t,n)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Ze(this.h,this.c,this.l).rgb()},t.lab=Xe;var We=18,Qe=.95047,Je=1,$e=1.08883,Ke=Xe.prototype=new He;function et(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return new it(at(3.2404542*(a=nt(a)*Qe)-1.5371385*(r=nt(r)*Je)-.4985314*(i=nt(i)*$e)),at(-.969266*a+1.8760108*r+.041556*i),at(.0556434*a-.2040259*r+1.0572252*i))}function tt(e,t,n){return e>0?new Ge(Math.atan2(n,t)*ze,Math.sqrt(t*t+n*n),e):new Ge(NaN,NaN,e)}function nt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function rt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,n){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,n)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Xe(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Xe(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new He;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new qe(r,a,s)}function dt(e,t,n){var r=rt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(n=ht(n)))/Qe),a=rt((.2126729*e+.7151522*t+.072175*n)/Je);return Xe(116*a-16,500*(r-a),200*(a-rt((.0193339*e+.119192*t+.9503041*n)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,a=30;return t||n||r?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var n=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=n}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(n=null==e?null:e+"",o):n},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),c.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=n&&c.overrideMimeType&&c.overrideMimeType(n),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==r?null:r),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(O),t.dsv=function(e,t){var n=new RegExp('["'+e+"\n]"),r=e.charCodeAt(0);function a(e,n,r){arguments.length<3&&(r=n,n=null);var a=mt(e,t,null==n?i:o(n),r);return a.row=function(e){return arguments.length?a.response(null==(n=e)?i:o(e)):n},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return n.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var n;return a.parseRows(e,function(e,r){if(n)return n(e,r-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(a(e),n)}:a})},a.parseRows=function(e,t){var n,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(Tt,t)),_t=0):(_t=1,kt(Tt))}function At(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}});t.formatPrefix=function(e,n){var r=0;return(e=+e)&&(e<0&&(e*=-1),n&&(e=t.round(e,Ct(e,n))),r=1+Math.floor(1e-12+Math.log(e)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),St[8+r/3]};var zt=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Ot=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,n){return(e=t.round(e,Ct(e,n))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),n))))}});function Pt(e){return e+""}var Dt=t.time={},Et=Date;function It(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}It.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(){Nt.setUTCDate.apply(this._,arguments)},setDay:function(){Nt.setUTCDay.apply(this._,arguments)},setFullYear:function(){Nt.setUTCFullYear.apply(this._,arguments)},setHours:function(){Nt.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Nt.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Nt.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Nt.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Nt.setUTCSeconds.apply(this._,arguments)},setTime:function(){Nt.setTime.apply(this._,arguments)}};var Nt=Date.prototype;function Rt(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o68?1900:2e3),n+a[0].length):-1}function Qt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Jt(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function $t(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Kt(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function en(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function tn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function nn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function rn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function an(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=m(t)/60|0,a=m(t)%60;return n+qt(r,"0",2)+qt(a,"0",2)}function on(e,t,n){Ht.lastIndex=0;var r=Ht.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ln(e){for(var t=e.length,n=-1;++n0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(n-=l,n+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(r)}:O;return function(e){var r=zt.exec(e),a=r[1]||" ",l=r[2]||">",s=r[3]||"-",c=r[4]||"",u=r[5],f=+r[6],d=r[7],h=r[8],p=r[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=Ot.get(p)||Pt;var b=u&&d;return function(e){var r=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),r=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=n+e.substring(k+1);!u&&d&&(_=o(_,1/0));var T=v.length+_.length+w.length+(b?0:i.length),A=T"===l?A+i+e:"^"===l?A.substring(0,T>>=1)+i+e+A.substring(T):i+(b?e:A+e))+r}}}(e),timeFormat:function(e){var n=e.dateTime,r=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function n(n){for(var r,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in Bt?t.charAt(l++):o])||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}u.utc=function(e){var t=u(e);function n(e){try{var n=new(Et=It);return n._=e,t(n)}finally{Et=Date}}return n.parse=function(e){try{Et=It;var n=t.parse(e);return n&&n._}finally{Et=Date}},n.toString=t.toString,n},u.multi=u.utc.multi=ln;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(n),d:function(e,t){return qt(e.getDate(),t,2)},e:function(e,t){return qt(e.getDate(),t,2)},H:function(e,t){return qt(e.getHours(),t,2)},I:function(e,t){return qt(e.getHours()%12||12,t,2)},j:function(e,t){return qt(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return qt(e.getMilliseconds(),t,3)},m:function(e,t){return qt(e.getMonth()+1,t,2)},M:function(e,t){return qt(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return qt(e.getSeconds(),t,2)},U:function(e,t){return qt(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return qt(Dt.mondayOfYear(e),t,2)},x:u(r),X:u(a),y:function(e,t){return qt(e.getFullYear()%100,t,2)},Y:function(e,t){return qt(e.getFullYear()%1e4,t,4)},Z:an,"%":function(){return"%"}},w={a:function(e,t,n){g.lastIndex=0;var r=g.exec(t.slice(n));return r?(e.w=v.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(e,t,n){h.lastIndex=0;var r=h.exec(t.slice(n));return r?(e.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.m=m.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(e,t,n){return f(e,_.c.toString(),t,n)},d:$t,e:$t,H:en,I:en,j:Kt,L:rn,m:Jt,M:tn,p:function(e,t,n){var r=d.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)},S:nn,U:Yt,w:Gt,W:Zt,x:function(e,t,n){return f(e,_.x.toString(),t,n)},X:function(e,t,n){return f(e,_.X.toString(),t,n)},y:Wt,Y:Xt,Z:Qt,"%":on};return u}(e)}};var sn=t.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"]});function cn(){}t.format=sn.numberFormat,t.geo={},cn.prototype={s:0,t:0,add:function(e){fn(e,this.t,un),fn(un.s,this.s,this),this.s?this.t+=un.t:this.s=un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var un=new cn;function fn(e,t,n){var r=n.s=e+t,a=r-e,i=r-a;n.t=e-i+(t-a)}function dn(e,t){e&&pn.hasOwnProperty(e.type)&&pn[e.type](e,t)}t.geo.stream=function(e,t){e&&hn.hasOwnProperty(e.type)?hn[e.type](e,t):dn(e,t)};var hn={Feature:function(e,t){dn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++r=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=r*s+u*Math.cos(l),d=u*o*Math.sin(l);Sn.add(Math.atan2(d,f)),n=e,r=s,a=c}zn.point=function(o,l){zn.point=i,n=(e=o)*Se,r=Math.cos(l=(t=l)*Se/2+Te/4),a=Math.sin(l)},zn.lineEnd=function(){i(e,t)}}function Pn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function Dn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function En(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function In(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Nn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Rn(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Fn(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function Bn(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(n=-90),f[0]=e,f[1]=r}};function h(t,i){u.push(f=[e=t,r=t]),ia&&(a=i)}function p(t,o){var l=Pn([t*Se,o*Se]);if(s){var c=En(s,l),u=En([c[1],-c[0],0],c);Rn(u),u=Fn(u);var f=t-i,d=f>0?1:-1,p=u[0]*ze*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t):r>=e?(tr&&(r=t)):t>i?_(e,t)>_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=r,d.point=h,s=null}function y(e,t){if(s){var n=e-i;c+=m(n)>180?n+(n>0?360:-360):n}else o=e,l=t;zn.point(e,t),p(e,t)}function x(){zn.lineStart()}function b(){y(o,l),zn.lineEnd(),m(c)>ke&&(e=-(r=180)),f[0]=e,f[1]=r,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],r=g[1])}return u=f=null,e===1/0||n===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,n],[r,a]]}}(),t.geo.centroid=function(e){mn=xn=bn=_n=wn=kn=Mn=Tn=An=Ln=Cn=0,t.geo.stream(e,jn);var n=An,r=Ln,a=Cn,i=n*n+r*r+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else r(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Wn(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r=0?1:-1,k=w*_,M=k>Te,T=p*x;if(Sn.add(Math.atan2(T*w*Math.sin(k),g*b+T*Math.cos(k))),i+=M?_+w*Ae:_,M^d>=n^y>=n){var A=En(Pn(f),Pn(e));Rn(A);var L=En(a,A);Rn(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(r>C||r===C&&(A[0]||A[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&n.push(n.pop().concat(n.shift())),l.push(n.filter($n))}return u}}function $n(e){return e.length>1}function Kn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:I,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function er(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var tr=Jn(Zn,function(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Te:-Te,s=m(i-n);m(s-Te)0?Ce:-Ce),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Te&&(m(n-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}(n,r,i,o),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),t=0),e.point(n=i,r=o),a=l},lineEnd:function(){e.lineEnd(),n=r=NaN},clean:function(){return 2-t}}},function(e,t,n,r){var a;if(null==e)a=n*Ce,r.point(-Te,a),r.point(0,a),r.point(Te,a),r.point(Te,0),r.point(Te,-a),r.point(0,-a),r.point(-Te,-a),r.point(-Te,0),r.point(-Te,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rr=1e9;function ar(e,n,r,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=Kn(),w=nr(e,n,r,a),k={point:A,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=A,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var n=function(e){for(var t=0,n=u.length,r=e[1],a=0;ar&&Pe(c,i,e)>0&&++t:i[1]<=r&&Pe(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),r=x&&n,i=c.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Xn(c,o,n,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:r,u>1?a:n)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function T(t,i){return e<=t&&t<=r&&n<=i&&i<=a}function A(e,t){T(e,t)&&s.point(e,t)}function L(e,t){var n=T(e=Math.max(-rr,Math.min(rr,e)),t=Math.max(-rr,Math.min(rr,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=n,m=!1,n&&(s.lineStart(),s.point(e,t));else if(n&&y)s.point(e,t);else{var r={a:{x:g,y:v},b:{x:e,y:t}};w(r)?(y||(s.lineStart(),s.point(r.a.x,r.a.y)),s.point(r.b.x,r.b.y),n||s.lineEnd(),x=!1):n&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=n}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-r)0?2:1:m(t[1]-n)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}}function ir(e){var t=0,n=Te/3,r=Lr(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Te/180,n=e[1]*Te/180):[t/Te*180,n/Te*180]},a}function or(e,t){var n=Math.sin(e),r=(n+Math.sin(t))/2,a=1+n*(2*r-n),i=Math.sqrt(a)/r;function o(e,t){var n=Math.sqrt(a-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),i-n*Math.cos(e)]}return o.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,Ee((a-(e*e+n*n)*r*r)/(2*r))]},o}t.geo.clipExtent=function(){var e,t,n,r,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=ar(e=+l[0][0],t=+l[0][1],n=+l[1][0],r=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return ir(or)}).raw=or,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,n,r,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,n){e=[t,n]}};function c(t){var i=t[0],o=t[1];return e=null,n(i,o),e||(r(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),n=i.translate(),r=(e[0]-n[0])/t,a=(e[1]-n[1])/t;return(a>=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return n=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,r=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var lr,sr,cr,ur,fr,dr,hr={point:I,lineStart:I,lineEnd:I,polygonStart:function(){sr=0,hr.lineStart=pr},polygonEnd:function(){hr.lineStart=hr.lineEnd=hr.point=I,lr+=m(sr/2)}};function pr(){var e,t,n,r;function a(e,t){sr+=r*e-n*t,n=e,r=t}hr.point=function(i,o){hr.point=a,e=n=i,t=r=o},hr.lineEnd=function(){a(e,t)}}var gr={point:function(e,t){efr&&(fr=e);tdr&&(dr=t)},lineStart:I,lineEnd:I,polygonStart:I,polygonEnd:I};function vr(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yr,mr={point:xr,lineStart:br,lineEnd:_r,polygonStart:function(){mr.lineStart=wr},polygonEnd:function(){mr.point=xr,mr.lineStart=br,mr.lineEnd=_r}};function xr(e,t){bn+=e,_n+=t,++wn}function br(){var e,t;function n(n,r){var a=n-e,i=r-t,o=Math.sqrt(a*a+i*i);kn+=o*(e+n)/2,Mn+=o*(t+r)/2,Tn+=o,xr(e=n,t=r)}mr.point=function(r,a){mr.point=n,xr(e=r,t=a)}}function _r(){mr.point=xr}function wr(){var e,t,n,r;function a(e,t){var a=e-n,i=t-r,o=Math.sqrt(a*a+i*i);kn+=o*(n+e)/2,Mn+=o*(r+t)/2,Tn+=o,An+=(o=r*e-n*t)*(n+e),Ln+=o*(r+t),Cn+=3*o,xr(n=e,r=t)}mr.point=function(i,o){mr.point=a,xr(e=n=i,t=r=o)},mr.lineEnd=function(){a(e,t)}}function kr(e){var t=.5,n=Math.cos(30*Se),r=16;function a(t){return(r?function(t){var n,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(n,r){n=e(n,r),t.point(n[0],n[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(n,a){var o=Pn([n,a]),l=e(n,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=n,h=o[0],p=o[1],g=o[2],r,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(n=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,n,l,s,c,r,t),v.lineEnd=b,b()}return v}:function(t){return Tr(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})})(t)}function i(r,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-r,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,T=Math.sqrt(w*w+k*k+M*M),A=Math.asin(M/=T),L=m(m(M)-1)t||m((x*O+b*P)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mr(e){this.stream=e}function Tr(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Ar(e){return Lr(function(){return e})()}function Lr(e){var n,r,a,i,o,l,s=kr(function(e,t){return[(e=n(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=tr,x=O,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*ze,e[1]*ze]}function M(){a=Yn(r=Or(p,g,v),n);var e=n(d,h);return i=u-e[0]*c,o=f+e[1]*c,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cr(y(r,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,tr):function(e){var t=Math.cos(e),n=t>0,r=m(t)>ke;return Jn(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=n?g?0:o(f,d):g?o(f+(f<0?Te:-Te),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(Bn(t,h)||Bn(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(r&&t&&n^g){var y;v&l||!(y=i(p,t,!0))||(u=0,n?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&Bn(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Ir(e,6*Se),n?[0,-e]:[-Te,e-Te]);function a(e,n){return Math.cos(e)*Math.cos(n)>t}function i(e,n,r){var a=[1,0,0],i=En(Pn(e),Pn(n)),o=Dn(i,i),l=i[0],s=o-l*l;if(!s)return!r&&e;var c=t*o/s,u=-t*l/s,f=En(a,i),d=Nn(a,c);In(d,Nn(i,u));var h=f,p=Dn(d,h),g=Dn(h,h),v=p*p-g*(Dn(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=Nn(h,(-p-y)/g);if(In(x,d),x=Fn(x),!r)return x;var b,_=e[0],w=n[0],k=e[1],M=n[1];w<_&&(b=_,_=w,w=b);var T=w-_,A=m(T-Te)0^x[1]<(m(x[0]-_)Te^(_<=x[0]&&x[0]<=w)){var L=Nn(h,(-p+y)/g);return In(L,d),[x,Fn(L)]}}}function o(t,r){var a=n?e:Te-e,i=0;return t<-a?i|=1:t>a&&(i|=2),r<-a?i|=4:r>a&&(i|=8),i}}((b=+e)*Se),T()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?ar(e[0][0],e[0][1],e[1][0],e[1][1]):O,T()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Se,h=e[1]%360*Se,M()):[d*ze,h*ze]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*ze,g*ze,v*ze]},t.rebind(w,s,"precision"),function(){return n=e.apply(this,arguments),w.invert=n.invert&&k,M()}}function Cr(e){return Tr(e,function(t,n){e.point(t*Se,n*Se)})}function Sr(e,t){return[e,t]}function zr(e,t){return[e>Te?e-Ae:e<-Te?e+Ae:e,t]}function Or(e,t,n){return e?t||n?Yn(Dr(e),Er(t,n)):Dr(e):t||n?Er(t,n):zr}function Pr(e){return function(t,n){return[(t+=e)>Te?t-Ae:t<-Te?t+Ae:t,n]}}function Dr(e){var t=Pr(e);return t.invert=Pr(-e),t}function Er(e,t){var n=Math.cos(e),r=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*n+l*r;return[Math.atan2(s*a-u*i,l*n-c*r),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*n+u*r),Ee(u*n-l*r)]},o}function Ir(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=Nr(n,a),i=Nr(n,i),(o>0?ai)&&(a+=o*Ae)):(a=e+o*Ae,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=ze,t[1]*=ze,t},t},zr.invert=Sr,t.geo.circle=function(){var e,t,n=[0,0],r=6;function a(){var e="function"==typeof n?n.apply(this,arguments):n,r=Or(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=r(e,t)),e[0]*=ze,e[1]*=ze}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(n=e,a):n},a.angle=function(n){return arguments.length?(t=Ir((e=+n)*Se,r*Se),a):e},a.precision=function(n){return arguments.length?(t=Ir(e*Se,(r=+n)*Se),a):r},a.angle(90)},t.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((n=f*o)*n+(n=c*u-s*f*l)*n),s*u+c*f*l)},t.geo.graticule=function(){var e,n,r,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,r,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(n/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(r).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],r=+e[1][0],s=+e[0][1],l=+e[1][1],a>r&&(e=a,a=r,r=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[r,l]]},x.minorExtent=function(t){return arguments.length?(n=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],n>e&&(t=n,n=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[n,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Rr(o,i,90),u=Fr(n,e,y),f=Rr(s,l,90),d=Fr(a,r,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,n,r=Br,a=jr;function i(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||r.apply(this,arguments),n||a.apply(this,arguments))},i.source=function(t){return arguments.length?(r=t,e="function"==typeof t?null:t,i):r},i.target=function(e){return arguments.length?(a=e,n="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return n=e[0]*Se,r=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(r),l=Math.sin(r),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(n),f=o*Math.sin(n),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ne(i-r)+o*s*Ne(a-n))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,n=Math.sin(p-e)*g,r=n*u+t*d,a=n*f+t*h,i=n*l+t*c;return[Math.atan2(a,r)*ze,Math.atan2(i,Math.sqrt(r*r+a*a))*ze]}:function(){return[n*ze,r*ze]}).distance=p,v;var n,r,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yr=0,t.geo.stream(e,Hr),yr};var Hr={sphere:I,point:I,lineStart:function(){var e,t,n;function r(r,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((r*=Se)-e),s=Math.cos(l);yr+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=n*i-t*o*s)*l),t*i+n*o*s),e=r,t=i,n=o}Hr.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),n=Math.cos(i),Hr.point=r},Hr.lineEnd=function(){Hr.point=Hr.lineEnd=I}},lineEnd:I,polygonStart:I,polygonEnd:I};function qr(e,t){function n(t,n){var r=Math.cos(t),a=Math.cos(n),i=e(r*a);return[i*a*Math.sin(t),i*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),a=t(r),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,r*o),Math.asin(r&&n*i/r)]},n}var Vr=qr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Ar(Vr)}).raw=Vr;var Ur=qr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},O);function Gr(e,t){var n=Math.cos(e),r=function(e){return Math.tan(Te/4+e/2)},a=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),i=n*Math.pow(r(e),a)/a;if(!a)return Xr;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var n=i/Math.pow(r(t),a);return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}return o.invert=function(e,t){var n=i-t,r=Oe(a)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/a,2*Math.atan(Math.pow(i/r,1/a))-Ce]},o}function Yr(e,t){var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),a=n/r+e;if(m(r)1&&Pe(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function na(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Ar(Jr)}).raw=Jr,$r.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wr($r),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):[(e=n())[0],e[1],e[2]-90]},n([0,0,90])}).raw=$r,t.geom={},t.geom.hull=function(e){var t=Kr,n=ea;if(arguments.length)return r(e);function r(e){if(e.length<3)return[];var r,a=vt(t),i=vt(n),o=e.length,l=[],s=[];for(r=0;r=0;--r)h.push(e[l[c[r]][2]]);for(r=+f;rke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){r>-ke?(t=l.P,n=l):a>-ke?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||n){if(t===n)return ka(t),n=pa(t.site),ca.insert(s,n),s.edge=n.edge=Aa(t.site,s.site),wa(t),void wa(n);if(n){ka(t),ka(n);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=n.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(n.edge,c,p,b),s.edge=Aa(c,e,null,b),n.edge=Aa(e,p,null,b),wa(t),wa(n)}else s.edge=Aa(t.site,s.site)}}function ma(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-1/0;var l=(n=o.site).x,s=n.y,c=s-t;if(!c)return l;var u=l-r,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+r:(r+l)/2}function xa(e,t){var n=e.N;if(n)return ma(n,t);var r=e.site;return r.y===t?r.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,a=e.site,i=n.site;if(r!==i){var o=a.x,l=a.y,s=r.x-o,c=r.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){za(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};n={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/r,y:s};n={x:(c-a)/r,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xke||m(a-n)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(r-f)ke?{x:f,y:m(t-f)ke?{x:m(n-p)ke?{x:d,y:m(t-d)ke?{x:m(n-h)=n&&c.x<=a&&c.y>=r&&c.y<=o?[[n,o],[a,o],[a,r],[n,r]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(n,r){for(var a,i,o,l,s=n.site,c=n.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:Ha(n,r)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,n,r,a,i,o,l){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-n)+m(c-r)<.01)T(e,t,n,r,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,T(e,u,s,c,a,i,o,l),T(e,t,n,r,a,i,o,l)}else e.x=n,e.y=r,e.point=t}else T(e,t,n,r,a,i,o,l)}function T(e,t,n,r,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=n>=s,f=r>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,n,r,a,i,o,l)}w>k?v=p+w:g=h+k;var A={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(A.visit=function(e){!function e(t,n,r,a,i,o){if(!t(n,r,a,i,o)){var l=.5*(r+i),s=.5*(a+o),c=n.nodes;c[0]&&e(t,c[0],r,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],r,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,A,h,p,g,v)},A.find=function(e){return function(e,t,n,r,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(r=t.interpolators[a](e,n)););return r}function Ya(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ni(e){return Math.pow(2,10*(e-1))}function ri(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function oi(e){var t,n,r,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(r=-l)*(n=a)[0],t[1]+=r*n[1],t))||0;a[0]*i[1]=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"in";return a=Xa.get(a)||Za,i=Wa.get(i)||O,t=i(a.apply(null,n.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,n){e=t.hcl(e),n=t.hcl(n);var r=e.h,a=e.c,i=e.l,o=n.h-r,l=n.c-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.c:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ze(r+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,n){e=t.hsl(e),n=t.hsl(n);var r=e.h,a=e.s,i=e.l,o=n.h-r,l=n.s-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.s:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(r+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,n){e=t.lab(e),n=t.lab(n);var r=e.l,a=e.a,i=e.b,o=n.l-r,l=n.a-a,s=n.b-i;return function(e){return et(r+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var n=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,n){var r=[],a=[];return e=t.transform(e),n=t.transform(n),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push("translate(",null,",",null,")");r.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else(t[0]||t[1])&&n.push("translate("+t+")")}(e.translate,n.translate,r,a),function(e,t,n,r){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(ui(n)+"rotate(",null,")")-2,x:Ha(e,t)})):t&&n.push(ui(n)+"rotate("+t+")")}(e.rotate,n.rotate,r,a),function(e,t,n,r){e!==t?r.push({i:n.push(ui(n)+"skewX(",null,")")-2,x:Ha(e,t)}):t&&n.push(ui(n)+"skewX("+t+")")}(e.skew,n.skew,r,a),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(ui(n)+"scale(",null,",",null,")");r.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(ui(n)+"scale("+t+")")}(e.scale,n.scale,r,a),e=n=null,function(e){for(var t,n=-1,i=a.length;++n0?r=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:r=0})):t>0&&(s.start({type:"start",alpha:r=t}),e=Mt(l.tick)),l):r},l.start=function(){var e,t,n,r=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)n.push(a[r])}function Ti(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;n&&(i.value=0),i.children=c}else n&&(i.value=+n.call(r,i,i.depth)||0),delete i.children;return Ti(a,function(t){var r,a;e&&(r=t.children)&&r.sort(e),n&&(a=t.parent)&&(a.value+=t.value)}),l}return r.sort=function(t){return arguments.length?(e=t,r):e},r.children=function(e){return arguments.length?(t=e,r):t},r.value=function(e){return arguments.length?(n=e,r):n},r.revalue=function(e){return n&&(Mi(e,function(e){e.children&&(e.value=0)}),Ti(e,function(e){var t;e.children||(e.value=+n.call(r,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},r},t.layout.partition=function(){var e=t.layout.hierarchy(),n=[1,1];function r(t,r){var a=e.call(this,t,r);return function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(r=t.value?r/t.value:0;++cl&&(l=r),o.push(r)}for(n=0;na&&(r=n,a=t);return r}function Bi(e){return e.reduce(ji,0)}function ji(e,t){return e+t[1]}function Hi(e,t){return qi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function qi(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Zi(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function Xi(e){if((t=e.children)&&(s=t.length)){var t,n,r,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(n=t[0]).x=-n.r,n.y=0,x(n),s>1&&((r=t[1]).x=r.r,r.y=0,x(r),s>2))for(Ji(n,r,a=t[2]),x(a),Gi(n,a),n._pack_prev=a,Gi(a,r),r=n._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(n=e,i):n},i.range=function(e){return arguments.length?(r=vt(e),i):r},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return qi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,n=t.layout.hierarchy().sort(Ui),r=0,a=[1,1];function i(t,i){var o=n.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ti(l,function(e){e.r=+u(e.value)}),Ti(l,Xi),r){var f=r*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ti(l,function(e){e.r+=f}),Ti(l,Xi),Ti(l,function(e){e.r-=f})}return function e(t,n,r,a){var i=t.children;t.x=n+=a*t.x;t.y=r+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=n(d,h)/2-d.x,v=r[0]/(h.x+n(h,d)/2+g),y=r[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,r=e.parent.children,a=e.i?r[e.i-1]:null;if(t.length){!function(e){var t,n=0,r=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=n,t.m+=n,n+=t.s+(r+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+n(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+n(e._,a._));e.parent.A=function(e,t,r){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+n(l._,i._))>0&&(to(no(l,e,r),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,r=e)}return r}(e,a,e.parent.A||r[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=r[0],e.y=e.depth*r[1]}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e)?s:null,i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null==(r=e)?null:s,i):a?r:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),n=$i,r=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ti(c,function(e){var r=e.children;r&&r.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(r),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(r)):(e.x=l?u+=n(e,l):0,e.y=0,l=e)});var f=function e(t){var n=t.children;return n&&n.length?e(n[0]):t}(c),d=function e(t){var n,r=t.children;return r&&(n=r.length)?e(r[n-1]):t}(c),h=f.x-n(f,d)/2,p=d.x+n(d,f)/2;return Ti(c,a?function(e){e.x=(e.x-c.x)*r[0],e.y=(c.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(c.y?e.y/c.y:1))*r[1]}),s}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e),i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null!=(r=e),i):a?r:null},ki(i,e)},t.layout.treemap=function(){var e,n=t.layout.hierarchy(),r=Math.round,a=[1,1],i=null,o=ro,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var n,r,a=-1,i=e.length;++a0;)l.push(n=c[a-1]),l.area+=n.area,"squarify"!==s||(r=h(l,g))<=d?(c.pop(),d=r):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var n,r=o(e),a=t.slice(),i=[];for(u(a,r.dx*r.dy/e.value),i.area=0;n=a.pop();)i.push(n),i.area+=n.area,null!=n.z&&(p(i,n.z?r.dx:r.dy,r,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return t*=t,(r*=r)?Math.max(t*a*c/r,r/(t*i*c)):1/0}function p(e,t,n,a){var i,o=-1,l=e.length,s=n.x,c=n.y,u=t?r(e.area/t):0;if(t==n.dx){for((a||u>n.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++o1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var n=t.random.irwinHall(e);return function(){return n()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;n2?fo:lo,l=a?hi:di;return i=e(t,n,l,r),o=e(n,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(n=e,l()):n};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(r=e,l()):r};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,n){return yo(t,e,n)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,n,r,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(n,r,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(r)}function l(e){return a?Math.pow(r,e):-Math.pow(r,-e)}function s(e){return n(o(e))}s.invert=function(e){return l(n.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,n.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(r=+e,n.domain(i.map(o)),s):r};s.nice=function(){var e=so(i.map(o),a?Math:_o);return n.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],n=e[0],s=e[1],c=Math.floor(o(n)),u=Math.ceil(o(s)),f=r%1?2:r;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,n){if(!arguments.length)return bo;arguments.length<2?n=bo:"function"!=typeof n&&(n=t.format(n));var a=Math.max(1,r*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*r0?a[e-1]:n[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,T,A=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=r===Co?Math.sqrt(l*l+c*c):+r.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(A=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Te?0:1;if(L&&Eo(m,x,b,_)===h^S){var z=(u+f)/2;m=c*Math.cos(z),x=c*Math.sin(z),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-A),k=l*Math.sin(f-A),M=l*Math.cos(u+A),T=l*Math.sin(u+A);var O=Math.abs(u-f+2*A)<=Te?0:1;if(A&&Eo(w,k,M,T)===1-h^O){var P=(u+f)/2;w=l*Math.cos(P),k=l*Math.sin(P),M=T=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+n.apply(this,arguments)))>.001){g=l0?0:1}function Io(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=n-r,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,T=(-b*v+y*_)/m,A=w-p,L=k-g,C=M-p,S=T-g;return A*A+L*L>C*C+S*S&&(w=M,k=T),[[w-s,k-c],[w*n/x,k*n/x]]}function No(e){var t=Kr,n=ea,r=Zn,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(n);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",r[0]);return a.join("")},"step-before":jo,"step-after":Ho,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,n=[],r=-1,a=e.length,i=[0],o=[0];for(;++r<3;)t=e[r],i.push(t[0]),o.push(t[1]);n.push(Go(Xo,i)+","+Go(Xo,o)),--r;for(;++r9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function Bo(e){return e.join("L")+"Z"}function jo(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cTe)+",1 "+t}function s(e,t,n,r){return"Q 0,0 "+r}return i.radius=function(e){return arguments.length?(n=vt(e),i):n},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(r=vt(e),i):r},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=Br,t=jr,n=el;function r(r,a){var i=e.call(this,r,a),o=t.call(this,r,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(n))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return r.source=function(t){return arguments.length?(e=vt(t),r):e},r.target=function(e){return arguments.length?(t=vt(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),n=el,r=e.projection;return e.projection=function(e){return arguments.length?r(function(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Ce;return[n*Math.cos(r),n*Math.sin(r)]}}(n=e)):n},e},t.svg.symbol=function(){var e=nl,t=tl;function n(n,r){return(al.get(e.call(this,n,r))||rl)(t.call(this,n,r))}return n.type=function(t){return arguments.length?(e=vt(t),n):e},n.size=function(e){return arguments.length?(t=vt(e),n):t},n};var al=t.map({circle:rl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),n=t*ol;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);Z.transition=function(e){for(var t,n,r=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[r]:delete e[n],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[r]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=Z.call,dl.empty=Z.empty,dl.node=Z.node,dl.size=Z.size,t.transition=function(e,n){return e&&e.transition?ul?e.transition(n):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,n,r,a=this.id,i=this.namespace,o=[];e=X(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=r.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),T=xe(y),A=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,A[0]-=l[1],A[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(A[0]+=l[1],A[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",z).on("touchend.brush",P):L.on("mousemove.brush",z).on("mouseup.brush",P),b.interrupt().selectAll("*").interrupt(),M)A[0]=l[0]-A[0],A[1]=s[0]-A[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-A[0],s[1-S]-A[1]],A[0]=l[C],A[1]=s[S]}else t.event.altKey&&(f=A.slice());function z(){var e=t.mouse(y),n=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),A[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var n=io(a.domain()),r=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],Sl(+n[1]+1),t<1?1:t)},a.tickFormat=function(){return r},a.copy=function(){return Cl(e.copy(),n,r)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Al,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Al.toString,Dt.second=Rt(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=Rt(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=Rt(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=Rt(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var zl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ol=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],Pl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Zn]]),Dl={range:function(e,n,r){return t.range(Math.ceil(e/r)*r,+n,r).map(Sl)},floor:O,ceil:O};Ol.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),Ol,Pl)};var El=Ol.map(function(e){return[e[0].utc,e[1]]}),Il=Tl.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Zn]]);function Nl(e){return JSON.parse(e.responseText)}function Rl(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Il)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Nl,t)},t.html=function(e,t){return mt(e,"text/html",Rl,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t={};t.xmlns="http://www.w3.org/2000/xmlns/",t.svg="http://www.w3.org/2000/svg",t.xlink="http://www.w3.org/1999/xlink",t.svgAttrs={xmlns:t.svg,"xmlns:xlink":t.xlink};var n=function(e){var t=typeof e;if("string"===t){var n=e;if(0===(e=+e)&&function(e){for(var t,n=e.length,r=0;r13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(n))return!1}else if("number"!==t)return!1;return e-e<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},a={},i=Math.PI;a.deg2rad=function(e){return e/180*i},a.rad2deg=function(e){return e/i*180},a.wrap360=function(e){var t=e%360;return t<0?t+360:t},a.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var o=r.BADNUM,l=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(e){var t=/^\s+/,n=/\s+$/,r=0,a=e.round,i=e.min,o=e.max,l=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(r){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof r&&(r=function(e){e=e.replace(t,"").replace(n,"").toLowerCase();var r,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(r=j.rgb.exec(e))return{r:r[1],g:r[2],b:r[3]};if(r=j.rgba.exec(e))return{r:r[1],g:r[2],b:r[3],a:r[4]};if(r=j.hsl.exec(e))return{h:r[1],s:r[2],l:r[3]};if(r=j.hsla.exec(e))return{h:r[1],s:r[2],l:r[3],a:r[4]};if(r=j.hsv.exec(e))return{h:r[1],s:r[2],v:r[3]};if(r=j.hsva.exec(e))return{h:r[1],s:r[2],v:r[3],a:r[4]};if(r=j.hex8.exec(e))return{r:P(r[1]),g:P(r[2]),b:P(r[3]),a:N(r[4]),format:a?"name":"hex8"};if(r=j.hex6.exec(e))return{r:P(r[1]),g:P(r[2]),b:P(r[3]),format:a?"name":"hex"};if(r=j.hex4.exec(e))return{r:P(r[1]+""+r[1]),g:P(r[2]+""+r[2]),b:P(r[3]+""+r[3]),a:N(r[4]+""+r[4]),format:a?"name":"hex8"};if(r=j.hex3.exec(e))return{r:P(r[1]+""+r[1]),g:P(r[2]+""+r[2]),b:P(r[3]+""+r[3]),format:a?"name":"hex"};return!1}(r));"object"==typeof r&&(H(r.r)&&H(r.g)&&H(r.b)?(h=r.r,p=r.g,g=r.b,a={r:255*z(h,255),g:255*z(p,255),b:255*z(g,255)},f=!0,d="%"===String(r.r).substr(-1)?"prgb":"rgb"):H(r.h)&&H(r.s)&&H(r.v)?(s=E(r.s),c=E(r.v),a=function(t,n,r){t=6*z(t,360),n=z(n,100),r=z(r,100);var a=e.floor(t),i=t-a,o=r*(1-n),l=r*(1-i*n),s=r*(1-(1-i)*n),c=a%6;return{r:255*[r,l,o,o,s,r][c],g:255*[s,r,r,l,o,o][c],b:255*[o,o,s,r,r,l][c]}}(r.h,s,c),f=!0,d="hsv"):H(r.h)&&H(r.s)&&H(r.l)&&(s=E(r.s),u=E(r.l),a=function(e,t,n){var r,a,i;function o(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=z(e,360),t=z(t,100),n=z(n,100),0===t)r=a=i=n;else{var l=n<.5?n*(1+t):n+t-n*t,s=2*n-l;r=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*r,g:255*a,b:255*i}}(r.h,s,u),f=!0,d="hsl"),r.hasOwnProperty("a")&&(l=r.a));var h,p,g;return l=S(l),{ok:f,format:r.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=r++}function u(e,t,n){e=z(e,255),t=z(t,255),n=z(n,255);var r,a,l=o(e,t,n),s=i(e,t,n),c=(l+s)/2;if(l==s)r=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:r=(t-n)/u+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,i.push(c(r));return i}function A(e,t){t=t||6;for(var n=c(e).toHsv(),r=n.h,a=n.s,i=n.v,o=[],l=1/t;t--;)o.push(c({h:r,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,n,r,a=this.toRgb();return t=a.r/255,n=a.g/255,r=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(n).toString(16)),D(I(r))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*z(this._r,255))+"%",g:a(100*z(this._g,255))+"%",b:a(100*z(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*z(this._r,255))+"%, "+a(100*z(this._g,255))+"%, "+a(100*z(this._b,255))+"%)":"rgba("+a(100*z(this._r,255))+"%, "+a(100*z(this._g,255))+"%, "+a(100*z(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);n="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:E(e[r]));e=n}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(e,t,n){n=0===n?0:n||50;var r=c(e).toRgb(),a=c(t).toRgb(),i=n/100;return c({r:(a.r-r.r)*i+r.r,g:(a.g-r.g)*i+r.g,b:(a.b-r.b)*i+r.b,a:(a.a-r.a)*i+r.a})},c.readability=function(t,n){var r=c(t),a=c(n);return(e.max(r.getLuminance(),a.getLuminance())+.05)/(e.min(r.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,n){var r,a,i=c.readability(e,t);switch(a=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,n){var r,a,i,o,l=null,s=0;a=(n=n||{}).includeFallbackColors,i=n.level,o=n.size;for(var u=0;us&&(s=r,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(n.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],n))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function z(t,n){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var r=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(n,o(0,parseFloat(t))),r&&(t=parseInt(t*n,10)/100),e.abs(t-n)<1e-6?1:t%n/parseFloat(n)}function O(e){return i(1,o(0,e))}function P(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function I(t){return e.round(255*parseFloat(t)).toString(16)}function N(e){return P(e)/255}var R,F,B,j=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",B="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+B),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+B),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+B),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})$/});function H(e){return!!j.CSS_UNIT.exec(e)}s.exports?s.exports=c:window.tinycolor=c}(Math),s=s.exports;var c={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=c.RdBu,f=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var n=0;n1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(r=e[t][0],a=e[t][1],o=!1,Y(r))for(n=r.length-1;n>=0;n--)Q(r[n],$(a,n))?o?r[n]=void 0:r.pop():o=!0;else if("object"==typeof r&&null!==r)for(i=Object.keys(r),o=!1,n=i.length-1;n>=0;n--)Q(r[i[n]],$(a,i[n]))?delete r[i[n]]:o=!0;if(o)return}}(s)):o[t[i]]=r}}function $(e,t){var r=t;return n(t)?r="["+t+"]":e&&(r="."+t),e+r}function K(e,t,n,r){var a,i=Y(n),o=!0,l=n,s=r.replace("-1",0),c=!i&&Q(n,s),u=t[0];for(a=0;aa.max?t.set(r):t.set(+e)}},integer:{coerceFunction:function(e,t,r,a){e%1||!n(e)||void 0!==a.min&&ea.max?t.set(r):t.set(+e)}},string:{coerceFunction:function(e,t,n,r){if("string"!=typeof e){var a="number"==typeof e;!0!==r.strict&&a?t.set(String(e)):t.set(n)}else r.noBlank&&!e?t.set(n):t.set(e)}},color:{coerceFunction:function(e,t,n){s(e).isValid()?t.set(e):t.set(n)}},colorlist:{coerceFunction:function(e,t,n){Array.isArray(e)&&e.length&&e.every(function(e){return s(e).isValid()})?t.set(e):t.set(n)}},colorscale:{coerceFunction:function(e,t,n){t.set(d(e,n))}},angle:{coerceFunction:function(e,t,r){"auto"===e?t.set("auto"):n(e)?t.set(ie(+e)):t.set(r)}},subplotid:{coerceFunction:function(e,t,n,r){var a=r.regex||re(n);"string"==typeof e&&a.test(e)?t.set(e):t.set(n)},validateFunction:function(e,t){var n=t.dflt;return e===n||"string"==typeof e&&!!re(n).test(e)}},flaglist:{coerceFunction:function(e,t,n,r){if("string"==typeof e)if(-1===(r.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=le&&e<=se?e:fe;if("string"!=typeof e&&"number"!=typeof e)return fe;e=String(e);var n=_e(t),r=e.charAt(0);!n||"G"!==r&&"g"!==r||(e=e.substr(1),t="");var a=n&&"chinese"===t.substr(0,7),i=e.match(a?xe:me);if(!i)return fe;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(n){if(2===o.length)return fe;var d;o=Number(o);try{var h=D.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return fe}return d?(d.toJD()-ve)*de+c*he+u*pe+f*ge:fe}o=2===o.length?(Number(o)+2e3-be)%100+be:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?fe:g.getUTCDate()!==s?fe:g.getTime()+f*ge},le=ue.MIN_MS=ue.dateTime2ms("-9999"),se=ue.MAX_MS=ue.dateTime2ms("9999-12-31 23:59:59.9999"),ue.isDateTime=function(e,t){return ue.dateTime2ms(e,t)!==fe};var ke=90*de,Me=3*he,Te=5*pe;function Ae(e,t,n,r,a){if((t||n||r||a)&&(e+=" "+we(t,2)+":"+we(n,2),(r||a)&&(e+=":"+we(r,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+we(a,i)}return e}ue.ms2DateTime=function(e,t,n){if("number"!=typeof e||!(e>=le&&e<=se))return fe;t||(t=0);var r,a,i,o,l,s,c=Math.floor(10*ce(e+.05,1)),u=Math.round(e-c/10);if(_e(n)){var f=Math.floor(u/de)+ve,d=Math.floor(ce(e,de));try{r=D.getComponentMethod("calendars","getCal")(n).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){r=ye("G%Y-%m-%d")(new Date(u))}if("-"===r.charAt(0))for(;r.length<11;)r="-0"+r.substr(1);else for(;r.length<10;)r="0"+r;a=t=le+de&&t<=se-de))return fe;var n=Math.floor(10*ce(t+.05,1)),r=new Date(Math.round(t-n/10));return Ae(e.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+n)},ue.cleanDate=function(e,t,n){if(ue.isJSDate(e)||"number"==typeof e){if(_e(n))return w.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ue.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ue.isDateTime(e,n))return w.error("unrecognized date",e),t;return e};var Le=/%\d?f/g;function Ce(e,t,n,r){e=e.replace(Le,function(e){var n=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(n).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(_e(r))try{e=D.getComponentMethod("calendars","worldCalFmt")(e,t,r)}catch(e){return"Invalid"}return n(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ue.formatDate=function(e,t,r,a,i,o){if(i=_e(i)&&i,!t)if("y"===r)t=o.year;else if("m"===r)t=o.month;else{if("d"!==r)return function(e,t){var r=ce(e+.05,de),a=we(Math.floor(r/he),2)+":"+we(ce(Math.floor(r/pe),60),2);if("M"!==t){n(t)||(t=0);var i=(100+Math.min(ce(e/ge,60),Se[t])).toFixed(t).substr(1);t>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,r)+"\n"+Ce(o.dayMonthYear,e,a,i);t=o.dayMonth+"\n"+o.year}return Ce(t,e,a,i)};var ze=3*de;ue.incrementMonth=function(e,t,n){n=_e(n)&&n;var r=ce(e,de);if(e=Math.round(e-r),n)try{var a=Math.round(e/de)+ve,i=D.getComponentMethod("calendars","getCal")(n),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ve)*de+r}catch(t){w.error("invalid ms "+e+" in calendar "+n)}var l=new Date(e+ze);return l.setUTCMonth(l.getUTCMonth()+t)+r-ze},ue.findExactDates=function(e,t){for(var r,a,i=0,o=0,l=0,s=0,c=_e(t)&&D.getComponentMethod("calendars","getCal")(t),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Fe(e,t,n,r,a){var i=r*e+a*t;if(i<0)return r*r+a*a;if(i>n){var o=r-e,l=a-t;return o*o+l*l}var s=r*t-a*e;return s*s/n}Ne.segmentsIntersect=Re,Ne.segmentDistance=function(e,t,n,r,a,i,o,l){if(Re(e,t,n,r,a,i,o,l))return 0;var s=n-e,c=r-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Fe(s,c,d,a-e,i-t),Fe(s,c,d,o-e,l-t),Fe(u,f,h,e-a,t-i),Fe(u,f,h,n-a,r-i));return Math.sqrt(p)},Ne.getTextLocation=function(e,t,n,r){if(e===Ee&&r===Ie||(De={},Ee=e,Ie=r),De[n])return De[n];var a=e.getPointAtLength(ce(n-r/2,t)),i=e.getPointAtLength(ce(n+r/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(ce(n,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return De[n]=s,s},Ne.clearLocationCache=function(){Ee=null},Ne.getVisibleSegment=function(e,t,n){var r,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var n=e.getPointAtLength(t);0===t?r=n:t===u&&(a=n);var c=n.xo?n.x-o:0,f=n.ys?n.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+n)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+n))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(r.x-a.x)<.1&&Math.abs(r.y-a.y)<.1}},Ne.findPointOnPath=function(e,t,n,r){for(var a,i,o,l=(r=r||{}).pathLength||e.getTotalLength(),s=r.tolerance||.001,c=r.iterationLimit||30,u=e.getPointAtLength(0)[n]>e.getPointAtLength(l)[n]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var Be=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},je=/^\w*$/,He={init2dArray:function(e,t){for(var n=new Array(e),r=0;rt}function Qe(e,t){return e>=t}Ye.findBin=function(e,t,r){if(n(t.start))return r?Math.ceil((e-t.start)/t.size-1e-9)-1:Math.floor((e-t.start)/t.size+1e-9);var a,i,o=0,l=t.length,s=0,c=l>1?(t[l-1]-t[0])/(l-1):1;for(i=c>=0?r?Ze:Xe:r?Qe:We,e+=1e-9*c*(r?-1:1)*(c>=0?1:-1);o90&&w.log("Long binary search..."),o-1},Ye.sorterAsc=function(e,t){return e-t},Ye.sorterDes=function(e,t){return t-e},Ye.distinctVals=function(e){var t=e.slice();t.sort(Ye.sorterAsc);for(var n=t.length-1,r=t[n]-t[0]||1,a=r/(n||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(r=Math.min(r,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:r}},Ye.roundUp=function(e,t,n){for(var r,a=0,i=t.length-1,o=0,l=n?0:1,s=n?1:0,c=n?Math.ceil:Math.floor;ar.length)&&(a=r.length),n(t)||(t=!1),$e(r[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var r=t%1;return r*e[Math.ceil(t)]+(1-r)*e[Math.floor(t)]};var Ke={},et={};function tt(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}Ke.throttle=function(e,t,n){var r=et[e],a=Date.now();if(!r){for(var i in et)et[i].tsr.ts+t?o():r.timer=setTimeout(function(){o(),r.timer=null},t)},Ke.done=function(e){var t=et[e];return t&&t.timer?new Promise(function(e){var n=t.onDone;t.onDone=function(){n&&n(),e(),t.onDone=null}}):Promise.resolve()},Ke.clear=function(e){if(e)tt(et[e]),delete et[e];else for(var t in et)Ke.clear(t)};var nt=function(e,t){if(e>0)return Math.log(e)/Math.LN10;var r=Math.log(Math.min(t[0],t[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(t[0],t[1]))/Math.LN10-6),r},rt={},at=r.FP_SAFE,it=r.BADNUM,ot=rt={};ot.nestedProperty=Z,ot.keyedContainer=function(e,t,n,r){var a,i;n=n||"name",r=r||"value";var o={};i=t&&t.length?Z(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lat?it:n(e)?Number(e):it:it},ot.noop=T,ot.identity=function(e){return e},ot.swapAttrs=function(e,t,n,r){n||(n="x"),r||(r="y");for(var a=0;an?Math.max(n,Math.min(t,e)):Math.max(t,Math.min(n,e))},ot.bBoxIntersect=function(e,t,n){return n=n||0,e.left<=t.right+n&&t.left<=e.right+n&&e.top<=t.bottom+n&&t.top<=e.bottom+n},ot.simpleMap=function(e,t,n,r){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,n)?e(t,n,r):l},ot.OptionControl=function(e,t){e||(e={}),t||(t="opt");var n={optionList:[],_newoption:function(r){r[t]=e,n[r.name]=r,n.optionList.push(r)}};return n["_"+t]=e,n},ot.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var n,r,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(n=0;n=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[r];u[n]=i}return u},ot.syncOrAsync=function(e,t,n){var r;function a(){return ot.syncOrAsync(e,t,n)}for(;e.length;)if((r=(0,e.splice(0,1)[0])(t))&&r.then)return r.then(a).then(void 0,ot.promiseError);return n&&n(t)},ot.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},ot.noneOrAll=function(e,t,n){if(e){var r,a,i=!1,o=!0;for(r=0;r=0&&i%1==0){var p=a?a[h]:h,g=r?r[p]:p;f(g)&&(e[g].selected=1)}}},ot.getTargetArray=function(e,t){var n=t.target;if("string"==typeof n&&n){var r=ot.nestedProperty(e,n).get();return!!Array.isArray(r)&&r}return!!Array.isArray(n)&&n},ot.minExtend=function(e,t){var n={};"object"!=typeof t&&(t={});var r,a,i,o=Object.keys(e);for(r=0;r1?a+o[1]:"";if(i&&(o.length>1||l.length>4||n))for(;r.test(l);)l=l.replace(r,"$1"+i+"$2");return l+s};var ct=/%{([^\s%{}]*)}/g,ut=/^\w*$/;ot.templateString=function(e,t){var n={};return e.replace(ct,function(e,r){return ut.test(r)?t[r]||"":(n[r]=n[r]||ot.nestedProperty(t,r).get,n[r]()||"")})};ot.subplotSort=function(e,t){for(var n=Math.min(e.length,t.length)+1,r=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(r=10*r+o-48),c&&(a=10*a+l-48),!s||!c){if(r!==a)return r-a;if(o!==l)return o-l}}return a-r};var ft=2e9;ot.seedPseudoRandom=function(){ft=2e9},ot.pseudoRandom=function(){var e=ft;return ft=(69069*ft+1)%4294967296,Math.abs(ft-e)<429496729?ot.pseudoRandom():ft/4294967296};var dt=te.counter,ht={idRegex:{x:dt("x"),y:dt("y")},attrRegex:dt("[xy]axis"),xAxisMatch:dt("xaxis"),yAxisMatch:dt("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","ohlclayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}},pt={id2name:function(e){if("string"==typeof e&&e.match(ht.AX_ID_PATTERN)){var t=e.substr(1);return"1"===t&&(t=""),e.charAt(0)+"axis"+t}},name2id:function(e){if(e.match(ht.AX_NAME_PATTERN)){var t=e.substr(5);return"1"===t&&(t=""),e.charAt(0)+t}},cleanId:function(e,t){if(e.match(ht.AX_ID_PATTERN)&&(!t||e.charAt(0)===t)){var n=e.substr(1).replace(/^0+/,"");return"1"===n&&(n=""),e.charAt(0)+n}},list:function(e,t,n){var r=e._fullLayout;if(!r)return[];var a,i=pt.listIds(e,t),o=new Array(i.length);for(a=0;ar?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},gt={};(function(e){"use strict";var t;t="function"!=typeof e.matchMedia||!e.matchMedia("(hover: none)").matches,gt=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var vt=function(){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(t){e=!1}return e}(),yt={left:0,top:0},mt=function(e,t,n){t=t||e.currentTarget||e.srcElement,Array.isArray(n)||(n=[0,0]);var r=e.clientX||0,a=e.clientY||0,i=(o=t,o===window||o===document||o===document.body?yt:o.getBoundingClientRect());var o;return n[0]=r-i.left,n[1]=a-i.top,n};var xt=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]],bt={YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,HOVERID:"-hover"};function _t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var wt=_t;function kt(e){return"function"==typeof e}function Mt(e){return"object"==typeof e&&null!==e}function Tt(e){return void 0===e}_t.EventEmitter=_t,_t.prototype._events=void 0,_t.prototype._maxListeners=void 0,_t.defaultMaxListeners=10,_t.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},_t.prototype.emit=function(e){var t,n,r,a,i,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||Mt(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(Tt(n=this._events[e]))return!1;if(kt(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(Mt(n))for(a=Array.prototype.slice.call(arguments,1),r=(o=n.slice()).length,i=0;i0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},_t.prototype.on=_t.prototype.addListener,_t.prototype.once=function(e,t){if(!kt(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},_t.prototype.removeListener=function(e,t){var n,r,a,i;if(!kt(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||kt(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(Mt(n)){for(i=a;i-- >0;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},_t.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(kt(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},_t.prototype.listeners=function(e){return this._events&&this._events[e]?kt(this._events[e])?[this._events[e]]:this._events[e].slice():[]},_t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(kt(t))return 1;if(t)return t.length}return 0},_t.listenerCount=function(e,t){return e.listenerCount(t)};var At,Lt=wt.EventEmitter,Ct={init:function(e){if(e._ev instanceof Lt)return e;var t=new Lt,n=new Lt;return e._ev=t,e._internalEv=n,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=n.on.bind(n),e._internalOnce=n.once.bind(n),e._removeInternalListener=n.removeListener.bind(n),e._removeAllInternalListeners=n.removeAllListeners.bind(n),e.emit=function(r,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(r,a),t.emit(r,a),n.emit(r,a)},e},triggerHandler:function(e,t,n){var r,a;"undefined"!=typeof jQuery&&(r=jQuery(e).triggerHandler(t,n));var i=e._ev;if(!i)return r;var o=i._events[t];if(!o)return r;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Ot.getCursor=function(e,t,n,r){return e="left"===n?0:"center"===n?1:"right"===n?2:rt.constrain(Math.floor(3*e),0,2),t="bottom"===r?0:"middle"===r?1:"top"===r?2:rt.constrain(Math.floor(3*t),0,2),xt[t][e]},Ot.unhover=At.wrapped,Ot.unhoverRaw=At.raw,Ot.init=function(e){var t,n,r,a,i,o,l,s,c=e.gd,u=1,f=h.DBLCLICKDELAY,d=e.element;c._mouseDownTime||(c._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,vt?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=e.clampFn||function(e,t,n){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var n;try{n=new MouseEvent("click",t)}catch(e){var r=Dt(t);(n=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,r[0],r[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(n)}!function(e){e._dragging=!1,e._replotPending&&D.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Ot.coverSlip=Pt;function Et(e,t,n,r){r=r||rt.identity,Array.isArray(e)&&(t[0][n]=r(e))}var It={},Nt=It={};Nt.defaults=z.defaults;var Rt=Nt.defaultLine=z.defaultLine;Nt.lightLine=z.lightLine;var Ft=Nt.background=z.background;function Bt(e){if(n(e)||"string"!=typeof e)return e;var t=e.trim();if("rgb"!==t.substr(0,3))return e;var r=t.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return e;var a=r[1].trim().split(/\s*[\s,]\s*/),i="a"===t.charAt(3)&&4===a.length;if(!i&&3!==a.length)return e;for(var o=0;o=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}Nt.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},Nt.rgb=function(e){return Nt.tinyRGB(s(e))},Nt.opacity=function(e){return e?s(e).getAlpha():0},Nt.addOpacity=function(e,t){var n=s(e).toRgb();return"rgba("+Math.round(n.r)+", "+Math.round(n.g)+", "+Math.round(n.b)+", "+t+")"},Nt.combine=function(e,t){var n=s(e).toRgb();if(1===n.a)return s(e).toRgbString();var r=s(t||Ft).toRgb(),a=1===r.a?r:{r:255*(1-r.a)+r.r*r.a,g:255*(1-r.a)+r.g*r.a,b:255*(1-r.a)+r.b*r.a},i={r:a.r*(1-n.a)+n.r*n.a,g:a.g*(1-n.a)+n.g*n.a,b:a.b*(1-n.a)+n.b*n.a};return s(i).toRgbString()},Nt.contrast=function(e,t,n){var r=s(e);return 1!==r.getAlpha()&&(r=s(Nt.combine(e,Ft))),(r.isDark()?t?r.lighten(t):Ft:n?r.darken(n):Rt).toString()},Nt.stroke=function(e,t){var n=s(t);e.style({stroke:Nt.tinyRGB(n),"stroke-opacity":n.getAlpha()})},Nt.fill=function(e,t){var n=s(t);e.style({fill:Nt.tinyRGB(n),"fill-opacity":n.getAlpha()})},Nt.clean=function(e){if(e&&"object"==typeof e){var t,n,r,a,i=Object.keys(e);for(t=0;t=0;a--,i++)t=e[a],r[i]=[1-t[0],t[1]];return r},qt=function(e,t,n,r){var a,i;n?(a=rt.nestedProperty(e,n).get(),i=rt.nestedProperty(e._input,n).get()):(a=e,i=e._input);var o=r+"auto",l=r+"min",s=r+"max",u=a[o],f=a[l],d=a[s],h=a.colorscale;!1===u&&void 0!==f||(f=rt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=rt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[s]=d,i[l]=f,i[s]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?c.RdBu:f>=0?c.Reds:c.Blues,i.colorscale=h,a.reversescale&&(h=Ht(h)),a.colorscale=h)},Vt=rt.extendFlat,Ut=rt.isPlainObject,Gt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},Yt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},Zt=Gt.flags.slice().concat(["clearCalc","fullReplot"]),Xt=Yt.flags.slice().concat("layoutReplot"),Wt={traces:Gt,layout:Yt,traceFlags:function(){return Qt(Zt)},layoutFlags:function(){return Qt(Xt)},update:function(e,t){var n=t.editType;if(n&&"none"!==n)for(var r=n.split("+"),a=0;a0?Number(s):l;else if("string"!=typeof s)t.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=n(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(t.dtick=l)}var f="date"===a?rt.dateTick0(t.calendar):0,d=r("tick0",f);"date"===a?t.tick0=rt.cleanDate(d,f):n(d)&&"D1"!==s&&"D2"!==s?t.tick0=Number(d):t.tick0=f}else{void 0===r("tickvals")?t.tickmode="auto":r("ticktext")}},un=function(e){return void 0!==c[e]||f(e)},fn=function(e,t,r,a,i){var o,l=i.prefix,s=i.cLetter,c=l.slice(0,l.length-1),u=l?rt.nestedProperty(e,c).get()||{}:e,f=l?rt.nestedProperty(t,c).get()||{}:t,d=u[s+"min"],h=u[s+"max"],p=u.colorscale;a(l+s+"auto",!(n(d)&&n(h)&&d","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},mn={},xn=vn.LINE_SPACING;function bn(e,t){return e.node().getBoundingClientRect()[t]}var _n=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;mn.convertToTspans=function(n,r,a){var i=n.text(),o=!n.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(_n),l=e.select(n.node().parentNode);if(!l.empty()){var s=n.attr("class")?n.attr("class").split(" ")[0]:"text";return s+="-math",l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove(),n.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(r&&r._promises||[]).push(new Promise(function(t){n.style("display","none");var r=parseInt(n.node().style.fontSize,10),u={fontSize:r};!function(t,n,r){var a="math-output-"+rt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":n.fontSize+"px"}).text((o=t,o.replace(wn,"\\lt ").replace(kn,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var n=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())rt.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),n,a)}i.remove()})}(o[2],u,function(e,o,u){l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return c(),void t();var d=l.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});d.node().appendChild(f.node()),o&&o.node()&&f.node().insertBefore(o.node().cloneNode(!0),f.node().firstChild),f.attr({class:s,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=n.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=bn(f,"width"),g=bn(f,"height"),v=+n.attr("x")-p*{start:0,middle:.5,end:1}[n.attr("text-anchor")||"start"],y=-(r||bn(n,"height"))/4;"y"===s[0]?(d.attr({transform:"rotate("+[-90,+n.attr("x"),+n.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+n.attr("x"),y:+n.attr("y")})):"l"===s[0]?f.attr({x:n.attr("x"),y:y-g/2}):"a"===s[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+n.attr("y")+y-g/2}),a&&a.call(n,d),t(d)})})):c(),n}function c(){l.empty()||(s=n.attr("class")+"-math",l.select("svg."+s).remove()),n.text("").style("white-space","pre"),function(n,r){r=(a=r,function(e,t){if(!e)return"";for(var n=0;n1)for(var o=1;o doesnt match end tag <"+e+">. Pretending it did match.",r),i=l[l.length-1].node}else rt.log("Ignoring unexpected end tag .",r)}En.test(r)?c():(i=n,l=[{node:n}]);for(var h=r.split(Pn),p=0;p|>|>)/g;var Mn={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"},Tn={sub:"0.3em",sup:"-0.6em"},An={sub:"-0.21em",sup:"0.42em"},Ln="\u200b",Cn=["http:","https:","mailto:","",void 0,":"],Sn=new RegExp("]*)?/?>","g"),zn=Object.keys(yn.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:yn.entityToUnicode[e]}}),On=/(\r\n?|\n)/g,Pn=/(<[^<>]*>)/,Dn=/<(\/?)([^ >]*)(\s+(.*))?>/i,En=//i,In=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Nn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Rn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Fn=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function Bn(e,t){if(!e)return null;var n=e.match(t);return n&&(n[3]||n[4])}var jn=/(^|;)\s*color:/;function Hn(e,t,n){var r,a,i,o=n.horizontalAlign,l=n.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-r.height}:"middle"===l?function(){return s.top+(s.height-r.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-r.width}:"center"===o?function(){return s.left+(s.width-r.width)/2}:function(){return s.left},function(){return r=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}mn.plainText=function(e){return(e||"").replace(Sn," ")},mn.lineCount=function(e){return e.selectAll("tspan.line").size()||1},mn.positionText=function(t,n,r){return t.each(function(){var t=e.select(this);function a(e,n){return void 0===n?null===(n=t.attr(e))&&(t.attr(e,0),n=0):t.attr(e,n),n}var i=a("x",n),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},mn.makeEditable=function(t,n){var r=n.gd,a=n.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(r).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:n.fill||c.fill||"black",opacity:1,"background-color":n.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(n.text||t.attr("data-unformatted")).call(Hn(t,a,n)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var n,a=e.select(this).attr("class");(n=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(n).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(r._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Hn(t,a,n)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),n=document.createRange();n.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(n),t.focus()}return n.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var qn=function(e){var t=e.marker,r=t.sizeref||1,a=t.sizemin||0,i="area"===t.sizemode?function(e){return Math.sqrt(e/r)}:function(e){return e/r};return function(e){var t=i(e/2);return n(t)&&t>0?Math.max(t,a):0}},Vn={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&(e.mode&&-1!==e.mode.indexOf("markers")||"splom"===e.type)},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return rt.isPlainObject(e.marker)&&rt.isArrayOrTypedArray(e.marker.size)}},Un={},Gn=vn.LINE_SPACING,Yn=h.DESELECTDIM,Zn=Un={};Zn.font=function(e,t,n,r){rt.isPlainObject(t)&&(r=t.color,n=t.size,t=t.family),t&&e.style("font-family",t),n+1&&e.style("font-size",n+"px"),r&&e.call(It.fill,r)},Zn.setPosition=function(e,t,n){e.attr("x",t).attr("y",n)},Zn.setSize=function(e,t,n){e.attr("width",t).attr("height",n)},Zn.setRect=function(e,t,n,r,a){e.call(Zn.setPosition,t,n).call(Zn.setSize,r,a)},Zn.translatePoint=function(e,t,r,a){var i=r.c2p(e.x),o=a.c2p(e.y);return!!(n(i)&&n(o)&&t.node())&&("text"===t.node().nodeName?t.attr("x",i).attr("y",o):t.attr("transform","translate("+i+","+o+")"),!0)},Zn.translatePoints=function(t,n,r){t.each(function(t){var a=e.select(this);Zn.translatePoint(t,a,n,r)})},Zn.hideOutsideRangePoint=function(e,t,n,r,a,i){t.attr("display",n.isPtWithinRange(e,a)&&r.isPtWithinRange(e,i)?null:"none")},Zn.hideOutsideRangePoints=function(t,n,r){if(n._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=n.xaxis,i=n.yaxis;t.each(function(n){var o=n[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Zn.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Zn.crispRound=function(e,t,r){return t&&n(t)?e._context.staticPlot?t:t<1?1:Math.round(t):r||0},Zn.singleLineStyle=function(e,t,n,r,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";It.stroke(t,r||i.color),Zn.dashLine(t,l,o)},Zn.lineGroupStyle=function(t,n,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";e.select(this).call(It.stroke,r||i.color).call(Zn.dashLine,l,o)})},Zn.dashLine=function(e,t,n){n=+n||0,t=Zn.dashStyle(t,n),e.style({"stroke-dasharray":t,"stroke-width":n+"px"})},Zn.dashStyle=function(e,t){t=+t||1;var n=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),e},Zn.singleFillStyle=function(t){var n=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;n&&t.call(It.fill,n)},Zn.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(n){var r=e.select(this);try{r.call(It.fill,n[0].trace.fillcolor)}catch(e){rt.error(e,t),r.remove()}})},Zn.symbolNames=[],Zn.symbolFuncs=[],Zn.symbolNeedLines={},Zn.symbolNoDot={},Zn.symbolNoFill={},Zn.symbolList=[],Object.keys(gn).forEach(function(e){var t=gn[e];Zn.symbolList=Zn.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Zn.symbolNames[t.n]=e,Zn.symbolFuncs[t.n]=t.f,t.needLine&&(Zn.symbolNeedLines[t.n]=!0),t.noDot?Zn.symbolNoDot[t.n]=!0:Zn.symbolList=Zn.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Zn.symbolNoFill[t.n]=!0)});var Xn=Zn.symbolNames.length,Wn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Qn(e,t){var n=e%100;return Zn.symbolFuncs[n](t)+(e>=200?Wn:"")}Zn.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Zn.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Xn||e>=400?0:Math.floor(Math.max(e,0))};var Jn={x1:1,x2:0,y1:0,y2:0},$n={x1:0,x2:0,y1:1,y2:0};Zn.gradient=function(t,n,r,a,i,o){var l=n._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],rt.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jn):"vertical"===a&&t.attr($n),t.attr("id",r);var n=s(i),l=s(o);t.append("stop").attr({offset:"0%","stop-color":It.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":It.tinyRGB(n),"stop-opacity":n.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Zn.initGradients=function(e){rt.ensureSingle(e._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},Zn.singlePointStyle=function(e,t,n,r,a,i){var o=n.marker;!function(e,t,n,r,a,i,o,l){if(D.traceIs(n,"symbols")){var s=qn(n);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Vn.isBubble(n)?s(e.ms):(i.size||6)/2,e.mrc=t;var r=Zn.symbolNumber(e.mx||i.symbol)||0;return e.om=r%200>=100,Qn(r,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):rt.isArrayOrTypedArray(o.color)?It.defaultLine:o.color,rt.isArrayOrTypedArray(i.color)&&(c=It.defaultLine,d=!0),c="mc"in e?e.mcc=r(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(It.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+n.uid;d&&(v+="-"+e.i),t.call(Zn.gradient,l,v,p,c,g)}else t.call(It.fill,c);f&&t.call(It.stroke,u)}}(e,t,n,r,a,o,o.line,i)},Zn.pointStyle=function(t,n,r){if(t.size()){var a=n.marker,i=Zn.tryColorscale(a,""),o=Zn.tryColorscale(a,"line");t.each(function(t){Zn.singlePointStyle(t,e.select(this),n,i,o,r)})}},Zn.makeSelectedPointStyleFns=function(e){var t={},n=e.selected||{},r=e.unselected||{},a=e.marker||{},i=n.marker||{},o=r.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,n=void 0!==t;if(n||u||f){if(!e.selected)return f?c:Yn*(n?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Zn.selectedPointStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=Zn.makeSelectedPointStyleFns(n),a=n.marker||{};t.each(function(t){var n=e.select(this),a=r.opacityFn(t);void 0!==a&&n.style("opacity",a)}),r.colorFn&&t.each(function(t){var n=e.select(this),a=r.colorFn(t);a&&It.fill(n,a)}),D.traceIs(n,"symbols")&&r.sizeFn&&t.each(function(t){var n=e.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);n.attr("d",Qn(Zn.symbolNumber(i),o)),t.mrc2=o})}},Zn.tryColorscale=function(e,t){var n=t?rt.nestedProperty(e,t).get():e,r=n.colorscale,a=n.color;return r&&rt.isArrayOrTypedArray(a)?pn.makeColorScaleFunc(pn.extractScale(r,n.cmin,n.cmax)):rt.identity};var Kn={start:1,end:-1,middle:0,bottom:1,top:-1};function er(t,n,r,a){var i=e.select(t.node().parentNode),o=-1!==n.indexOf("top")?"top":-1!==n.indexOf("bottom")?"bottom":"middle",l=-1!==n.indexOf("left")?"end":-1!==n.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(mn.lineCount(t)-1)*Gn+1,u=Kn[l]*s,f=.75*r+Kn[o]*s+(Kn[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function tr(e,t){var r=e.ts||t.textfont.size;return n(r)&&r>0?r:0}Zn.textPointStyle=function(t,n,r){t.each(function(t){var a=e.select(this),i=rt.extractOption(t,n,"tx","text");if(i){var o=t.tp||n.textposition,l=tr(t,n);a.call(Zn.font,t.tf||n.textfont.family,l,t.tc||n.textfont.color).text(i).call(mn.convertToTspans,r).call(er,o,l,t.mrc)}else a.remove()})},Zn.selectedTextStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=n.selected||{},a=n.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||n.textfont.color,s=t.tp||n.textposition,c=tr(t,n),u=(r.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=It.addOpacity(l,Yn)),i&&It.fill(o,i),er(o,s,c,t.mrc2||t.mrc)})}};var nr=.5;function rr(t,n,r,a){var i=t[0]-n[0],o=t[1]-n[1],l=r[0]-n[0],s=r[1]-n[1],c=Math.pow(i*i+o*o,nr/2),u=Math.pow(l*l+s*s,nr/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(n[0]+(h&&f/h),2),e.round(n[1]+(h&&d/h),2)],[e.round(n[0]-(p&&f/p),2),e.round(n[1]-(p&&d/p),2)]]}Zn.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var n,r="M"+e[0],a=[];for(n=1;n=1e4&&(Zn.savedBBoxes={},or=0),r&&(Zn.savedBBoxes[r]=p),or++,rt.extendFlat({},p)},Zn.setClipUrl=function(t,n){if(n){if(void 0===Zn.baseUrl){var r=e.select("base");r.size()&&r.attr("href")?Zn.baseUrl=window.location.href.split("#")[0]:Zn.baseUrl=""}t.attr("clip-path","url("+Zn.baseUrl+"#"+n+")")}else t.attr("clip-path",null)},Zn.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Zn.setTranslate=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||0,n=n||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+n+")").trim(),e[a]("transform",i),i},Zn.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Zn.setScale=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||1,n=n||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+n+")").trim(),e[a]("transform",i),i},Zn.setPointGroupScale=function(e,t,n){var r,a,i;return t=t||1,n=n||1,a=1===t&&1===n?"":" scale("+t+","+n+")",i=/\s*sc.*/,e.each(function(){r=(this.getAttribute("transform")||"").replace(i,""),r=(r+=a).trim(),this.setAttribute("transform",r)}),a};var sr=/translate\([^)]*\)\s*$/;Zn.setTextPointsScale=function(t,n,r){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(sr);t=1===n&&1===r?[]:["translate("+o+","+l+")","scale("+n+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var cr={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},isTraceInSubplots:function(e,t){if("splom"===e.type){for(var n=e.xaxes||[],r=e.yaxes||[],a=0;a=0&&n.index=i.length)return!1;if(2===e.dimensions){if(n++,t.length===n)return e;var o=t[n];if(!Br(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function Br(e){return e===Math.round(e)&&e>=0}function jr(e){return function(e){Or.crawl(e,function(e,t,n){Or.isValObject(e)?"data_array"===e.valType?(e.role="data",n[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(n[t+"src"]={valType:"string",editType:"none"}):Er(e)&&(e.role="object")})}(e),function(e){Or.crawl(e,function(e,t,n){if(!e)return;var r=e[Nr];if(!r)return;delete e[Nr],n[t]={items:{}},n[t].items[r]=e,n[t].role="object"})}(e),function(e){!function e(t){for(var n in t)if(Er(t[n]))e(t[n]);else if(Array.isArray(t[n]))for(var r=0;r=o.length)return!1;r=(n=(D.transformsRegistry[o[l].type]||{}).attributes)&&n[t[2]],i=3}else if("area"===e.type)r=Tr[a];else{var s=e._module;if(s||(s=(D.modules[e.type||S.type.dflt]||{})._module),!s)return!1;if(!(r=(n=s.attributes)&&n[a])){var c=s.basePlotModule;c&&c.attributes&&(r=c.attributes[a])}r||(r=S[a])}return Fr(r,t,i)},Or.getLayoutValObject=function(e,t){return Fr(function(e,t){var n,r,a,i,o=e._basePlotModules;if(o){var l;for(n=0;n0?".":"")+a;rt.isPlainObject(i)?Zr(i,t,o,r+1):t(o,a,i)}})}function Xr(e,t){return"splom"===e?-1:"splom"===t?1:0}Vr.manageCommandObserver=function(e,t,n,r){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Vr.hasSimpleAPICommandBindings(e,n,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Ur(e,o,a.cache),a.check=function(){if(i){var t=Ur(e,o,a.cache);return t.changed&&r&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(r({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=n.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=n._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var n=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)n.on("click",function(){ta.sendDataToCloud(e)});else{var r=window.location.pathname.split("/"),a=window.location.search;n.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+r[2].split(".")[0]+"/"+r[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},ta.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var n=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:n+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=ta.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var ra,aa=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],ia=["year","month","dayMonth","dayMonthYear"];function oa(e,t){var n,r,a=e.trace,i=a._arrayAttrs,o={};for(n=0;n1&&_.length>1){for(D.getComponentMethod("grid","sizeDefaults")(i,a),r=0;r15&&_.length>15&&0===a.shapes.length&&0===a.images.length,a._hasCartesian=a._has("cartesian"),a._hasGeo=a._has("geo"),a._hasGL3D=a._has("gl3d"),a._hasGL2D=a._has("gl2d"),a._hasTernary=a._has("ternary"),a._hasPie=a._has("pie"),ta.cleanPlot(l,a,o,n,c),ta.linkSubplots(l,a,o,n),Kr(a,n),ta.doAutoMargin(t);var T=pt.list(t);for(r=0;r0){var c=function(e){var t,n={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(n.left+=e[t].left||0,n.right+=e[t].right||0,n.bottom+=e[t].bottom||0,n.top+=e[t].top||0);return n}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=ta.layoutAttributes.width.min,v=ta.layoutAttributes.height.min;a1,m=!t.height&&Math.abs(r.height-i)>1;(m||y)&&(y&&(r.width=a),m&&(r.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),ta.sanitizeMargins(r)},ta.supplyLayoutModuleDefaults=function(e,t,n,r){var a,i,o,l=D.componentsRegistry,s=t._basePlotModules,c=D.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(D.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(rt.subplotSort);for(i=0;i.5*r.width&&(n.l=n.r=0),n.b+n.t>.5*r.height&&(n.b=n.t=0),r._pushmargin[t]={l:{val:n.x,size:n.l+a},r:{val:n.x,size:n.r+a},b:{val:n.y,size:n.b+a},t:{val:n.y,size:n.t+a}}}else delete r._pushmargin[t];r._replotting||ta.doAutoMargin(e)}},ta.doAutoMargin=function(e){var t=e._fullLayout;t._size||(t._size={}),t._pushmargin||(t._pushmargin={});var r=t._size,a=JSON.stringify(r),i=Math.max(t.margin.l||0,0),o=Math.max(t.margin.r||0,0),l=Math.max(t.margin.t||0,0),s=Math.max(t.margin.b||0,0),c=t._pushmargin;if(!1!==t.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(n(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-t.width)*h)/(m-h),_=(x*(1-h)+(p-t.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(n(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-t.height)*g)/(w-g),T=(k*(1-g)+(v-t.height)*(1-w))/(w-g);M>=0&&T>=0&&M+T>s+l&&(s=M,l=T)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(t.margin.pad),r.w=Math.round(t.width)-r.l-r.r,r.h=Math.round(t.height)-r.t-r.b,!t._replotting&&"{}"!==a&&a!==JSON.stringify(t._size))return D.call("plot",e)},ta.graphJson=function(e,t,n,r,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&ta.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(rt.isPlainObject(e)){var t,r,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===n){if("src"===t.substr(t.length-3))continue}else if("keepstream"===n){if("string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0&&!rt.isPlainObject(e.stream))continue}else if("keepall"!==n&&"string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):rt.isJSDate(e)?rt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var n=s(e);return t&&delete n.fit,n})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===r?c:JSON.stringify(c)},ta.modifyFrames=function(e,t){var n,r,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(n=0;n0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return D.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var r,o,l=0,s=0;function c(){return l++,function(){var n;f||++s!==l||(n=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return D.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(n)))}}var d=e._fullLayout._basePlotModules,h=!1;if(n)for(o=0;o=0;i--)if(s[i].enabled){n._indexToPoints=s[i]._indexToPoints;break}r&&r.calc&&(o=r.calc(e,n))}Array.isArray(o)&&o[0]||(o=[{x:Jr,y:Jr}]),o[0].t||(o[0].t={}),o[0].trace=n,c[t]=o}}for(d&&ca(o),a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];r.attr("transform","translate("+p+")")}}}T.call(A),k&&(w?T.on(".opacity",null):(b=0,_=!0,T.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(mn.makeEditable,{gd:t}).on("edit",function(e){void 0!==c?D.call("restyle",t,l,e,c):D.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(A)}).on("input",function(e){this.text(e||" ").call(mn.positionText,f.x,f.y)}));return T.classed("js-placeholder",_),p}},fa=/ [XY][0-9]* /;var da=r.FP_SAFE,ha=ya,pa=ma,ga=function(e){e._length||e.setScale();var t,n=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&n&&(e.range=ya(e),e._r=e.range.slice(),e._rl=rt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var r=e._anchorAxis.rangeslider[e._name];r&&"auto"===r.rangemode&&(r.range=n?ya(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=rt.extendFlat({},r)}},va=function(e,t,r){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!t)return;e._min||(e._min=[]);e._max||(e._max=[]);r||(r={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=t.length,y=r.padded||!1,m=r.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((e._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),T=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-da&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var A=m&&0===a;v.push({val:a,pad:A?0:b,extrapad:!A&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)A(a)};function ya(e){var t,n,r,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=ma(e);for(t=1;t0&&l>0&&s/l>d&&(i=r,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),rt.simpleMap(c,e.l2r||Number)}function ma(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function xa(e){return n(e)&&Math.abs(e)=t}var wa=r.BADNUM,ka=function(e,t){return function(e,t){for(var r,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,t)?"date":function(e){for(var t,n=Math.max(1,(e.length-1)/1e3),r=0,a=0,i=0;i2*r}(e)?"category":function(e){if(!e)return!1;for(var t=0;t0)return Math.log(e)/Math.LN10;if(e<=0&&n&&t.range&&2===t.range.length){var r=t.range[0],a=t.range[1];return.5*(r+a-3*i*Math.abs(r-a))}return Sa}function l(e,r,a){var i=Aa(e,a||t.calendar);if(i===Sa){if(!n(e))return Sa;i=Aa(new Date(+e))}return i}function s(e,n,r){return Ta(e,n,r||t.calendar)}function c(e){return t._categories[Math.round(e)]}function u(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(n(e))return+e}function f(r){return n(r)?e.round(t._b+t._m*r,2):Sa}function d(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:La,t.l2c="log"===t.type?za:La,t.l2p=f,t.p2l=d,t.c2p="log"===t.type?function(e,t){return f(o(e,t))}:f,t.p2c="log"===t.type?function(e){return za(d(e))}:d,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Ma,t.c2d=t.c2r=t.l2d=t.l2r=La,t.d2p=t.r2p=function(e){return t.l2p(Ma(e))},t.p2d=t.p2r=d,t.cleanPos=La):"log"===t.type?(t.d2r=t.d2l=function(e,t){return o(Ma(e),t)},t.r2d=t.r2c=function(e){return za(Ma(e))},t.d2c=t.r2l=Ma,t.c2d=t.l2r=La,t.c2r=o,t.l2d=za,t.d2p=function(e,n){return t.l2p(t.d2r(e,n))},t.p2d=function(e){return za(d(e))},t.r2p=function(e){return t.l2p(Ma(e))},t.p2r=d,t.cleanPos=La):"date"===t.type?(t.d2r=t.r2d=rt.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,n,r){return t.l2p(l(e,0,r))},t.p2d=t.p2r=function(e,t,n){return s(d(e),t,n)},t.cleanPos=function(e){return rt.cleanDate(e,Sa,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var n=t._categories.length-1;return t._categoriesMap[e]=n,n}return Sa},t.r2d=t.c2d=t.l2d=c,t.d2r=t.d2l_noadd=u,t.r2c=function(e){var n=u(e);return void 0!==n?n:t.fraction2r(.5)},t.l2r=t.c2r=La,t.r2l=u,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(e){return c(d(e))},t.r2p=t.d2p,t.p2r=d,t.cleanPos=function(e){return"string"==typeof e&&""!==e?e:La(e)}),t.fraction2r=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return t.l2r(n+e*(r-n))},t.r2fraction=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return(t.r2l(e)-n)/(r-n)},t.cleanRange=function(e,r){r||(r={}),e||(e="range");var i,o,l=rt.nestedProperty(t,e).get();if(o=(o="date"===t.type?rt.dfltRange(t.calendar):"y"===a?ht.DFLTRANGEY:r.dfltRange||ht.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=rt.cleanDate(l[0],Sa,t.calendar),l[1]=rt.cleanDate(l[1],Sa,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!rt.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=rt.constrain(t.r2l(l[0]),rt.MIN_MS+1e3,rt.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!n(l[i])){if(!n(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Ca?l[i]=-Ca:l[i]>Ca&&(l[i]=Ca),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else rt.nestedProperty(t,e).set(o)},t.setScale=function(e){var n=r._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=pt.getFromId({_fullLayout:r},t.overlaying);t.domain=i.domain}var o=e&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===a?(t._offset=n.t+(1-t.domain[1])*n.h,t._length=n.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=n.l+t.domain[0]*n.w,t._length=n.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw r._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,n){var r,a,i,o,l=t.type,s="date"===l&&e[n+"calendar"];if(n in e){if(r=e[n],o=e._length||r.length,rt.isTypedArray(r)&&("linear"===l||"log"===l)){if(o===r.length)return r;if(r.subarray)return r.subarray(0,o)}for(a=new Array(o),i=0;i2e-6||((n-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},Va.saveRangeInitial=function(e,t){for(var n=Va.list(e,"",!0),r=!1,a=0;a.3*d||u(a)||u(i))){var h=r.dtick/2;e+=e+h.8){var o=Number(n.substr(1));i.exactYears>.8&&o%12==0?e=Va.tickIncrement(e,"M6","reverse")+1.5*Ia:i.exactMonths>.8?e=Va.tickIncrement(e,"M1","reverse")+15.5*Ia:e-=Ia/2;var l=Va.tickIncrement(e,n);if(l<=r)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=Va.tickIncrement(h,l.dtick,!1,i),0;return{start:t.c2r(p,0,i),end:t.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},Va.prepTicks=function(e){var t=rt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var n,r=e.nticks;r||("category"===e.type?(n=e.tickfont?1.2*(e.tickfont.size||12):15,r=e._length/n):(n="y"===e._id.charAt(0)?40:80,r=rt.constrain(e._length/n,4,9)+1),"radialaxis"===e._name&&(r*=2)),"array"===e.tickmode&&(r*=100),Va.autoTicks(e,Math.abs(t[1]-t[0])/r),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),ti(e)},Va.calcTicks=function(e){Va.prepTicks(e);var t=rt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,n,r=e.tickvals,a=e.ticktext,i=new Array(r.length),o=rt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(n=0;nc&&t=r:s<=r)&&!(i.length>l||s===o);s=Va.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+t.substr(1)%12==0?"y":"m";else if(t>=Ia&&i<=10||t>=15*Ia)e._tickround="d";else if(t>=Ra&&i<=16||t>=Na)e._tickround="M";else if(t>=Fa&&i<=19||t>=Ra)e._tickround="S";else{var o=e.l2r(r+t).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(n(t)||"L"===t.charAt(0)){var l=e.range.map(e.r2d||Number);n(t)||(t=Number(t.substr(1))),e._tickround=2-Math.floor(Math.log(t)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(ai(e.exponentformat)&&!ii(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function ni(e,t,n){var r=e.tickfont||{};return{x:t,dx:0,dy:0,text:n||"",fontSize:r.size,font:r.family,fontColor:r.color}}Va.autoTicks=function(e,t){var r;function a(e){return Math.pow(e,Math.floor(Math.log(t)/Math.LN10))}if("date"===e.type){e.tick0=rt.dateTick0(e.calendar);var i=2*t;i>Da?(t/=Da,r=a(10),e.dtick="M"+12*ei(t,r,Za)):i>Ea?(t/=Ea,e.dtick="M"+ei(t,1,Xa)):i>Ia?(e.dtick=ei(t,Ia,Qa),e.tick0=rt.dateTick0(e.calendar,!0)):i>Na?e.dtick=ei(t,Na,Xa):i>Ra?e.dtick=ei(t,Ra,Wa):i>Fa?e.dtick=ei(t,Fa,Wa):(r=a(10),e.dtick=ei(t,r,Za))}else if("log"===e.type){e.tick0=0;var o=rt.simpleMap(e.range,e.r2l);if(t>.7)e.dtick=Math.ceil(t);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/t);t=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=a(10),e.dtick="L"+ei(t,r,Za)}else e.dtick=t>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(t,1))):"angular"===e._id?(e.tick0=0,r=1,e.dtick=ei(t,r,Ka)):(e.tick0=0,r=a(10),e.dtick=ei(t,r,Za));if(0===e.dtick&&(e.dtick=1),!n(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},Va.tickIncrement=function(t,r,a,i){var o=a?-1:1;if(n(r))return t+o*r;var l=r.charAt(0),s=o*Number(r.substr(1));if("M"===l)return rt.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var c="D2"===r?$a:Ja,u=t+.01*o,f=rt.roundUp(rt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(r)},Va.tickFirst=function(t){var r=t.r2l||Number,a=rt.simpleMap(t.range,r),i=a[1]"+l,e._prevDateHead=l));t.text=s}(e,o,r,s):"log"===e.type?function(e,t,r,a,i){var o=e.dtick,l=t.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))t.text=oi(Math.pow(10,l),e,i,a);else if(n(o)||"D"===o.charAt(0)&&rt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||ai(e.exponentformat)&&ii(c)?(t.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+Ba+-c+"",t.fontSize*=1.25):(t.text=oi(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(t.dy-=t.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);t.text=String(Math.round(Math.pow(10,rt.mod(l,1)))),t.fontSize*=.75}if("D1"===e.dtick){var u=String(t.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?t.dx-=t.fontSize/4:(t.dy+=t.fontSize/2,t.dx+=(e.range[1]>e.range[0]?1:-1)*t.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var n=e._categories[Math.round(t.x)];void 0===n&&(n="");t.text=String(n)}(e,o):"angular"===e._id?function(e,t,n,r,a){if("radians"!==e.thetaunit||n)t.text=oi(t.x,e,a,r);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var n=function(e){var n=1;for(;!t(Math.round(e*n)/n,e);)n*=10;return n}(e),r=e*n,a=Math.abs(function e(n,r){return t(r,0)?n:e(r,n%r)}(r,n));return[Math.round(r/a),Math.round(n/a)]}(i);if(o[1]>=100)t.text=oi(rt.deg2rad(t.x),e,a,r);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=Ba+t.text)}}}}(e,o,r,s,a):function(e,t,n,r,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=oi(t.x,e,a,r)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},Va.hoverLabelText=function(e,t,n){if(n!==ja&&n!==t)return Va.hoverLabelText(e,t)+" - "+Va.hoverLabelText(e,n);var r="log"===e.type&&t<=0,a=Va.tickText(e,e.c2l(r?-t:t),"hover").text;return r?0===t?"0":Ba+a:a};var ri=["f","p","n","\u03bc","m","","k","M","G","T"];function ai(e){return"SI"===e||"B"===e}function ii(e){return e>14||e<-15}function oi(e,t,r,a){var i=e<0,o=t._tickround,l=r||t.exponentformat||"B",s=t._tickexponent,c=Va.getTickFormat(t),u=t.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===t.showexponent?t.dtick:n(e)&&Math.abs(e)||1,range:"none"===t.showexponent?t.range.map(t.r2d):[0,e||1]};ti(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,t.hoverformat&&(c=t.hoverformat)}if(c)return t._numFormat(c)(e).replace(/-/g,Ba);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":ai(l)&&(e+=ri[s/3+5]));return i?Ba+e:e}function li(e,t){for(var n=0;n=0,i=c(e,t[1])<=0;return(n||a)&&(r||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(r))){n=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(r=1;r-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),void 0!==t.extraText&&(s+=(s?"
":"")+t.extraText),""===s&&(""===l&&n.remove(),s=l);var g=n.select("text.nums").call(Un.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(mn.positionText,0,0).call(mn.convertToTspans,r),y=n.select("text.name"),m=0;l&&l!==s?(y.call(Un.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(mn.positionText,0,0).call(mn.convertToTspans,r),m=y.node().getBoundingClientRect().width+2*yi):(y.remove(),n.select("rect").remove()),n.select("path").style({fill:d,stroke:h});var k,M,T=g.node().getBoundingClientRect(),A=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),z=T.width+vi+yi+m;t.ty0=x-T.top,t.bx=T.width+2*yi,t.by=T.height+2*yi,t.anchor="start",t.txwidth=T.width,t.tx2width=m,t.offset=0,i?(t.pos=A,k=L+S/2+z<=_,M=L-S/2-z>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=A+C/2+z<=b,M=A-C/2-z>=0,"left"!==t.idealAlign&&k||!M?k?(A+=C/2,t.anchor="start"):t.anchor="middle":(A-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),n.attr("transform","translate("+A+","+L+")"+(i?"rotate("+fi+")":""))}),C}function xi(t,n){t.each(function(t){var r=e.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(vi+yi),s=l+o*(t.txwidth+yi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+yi),n&&(u*=-gi,c=t.offset*pi),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*vi+c)+","+(vi+u)+"v"+(t.by/2-vi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*vi+c)+"V"+(u-vi)+"Z"),i.call(mn.positionText,l+c,u+t.ty0-t.by/2+yi),t.tx2width&&(r.select("text.name").call(mn.positionText,s+o*yi+c,u+t.ty0-t.by/2+yi),r.select("rect").call(Un.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function bi(e,t){var n=e.index,r=e.trace||{},a=e.cd[0],i=e.cd[n]||{},o=Array.isArray(n)?function(e,t){return rt.castOption(a,n,e)||rt.extractOption({},r,"",t)}:function(e,t){return rt.extractOption(i,r,e,t)};function l(t,n,r){var a=o(n,r);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=rt.constrain(e.x0,0,e.xa._length),e.x1=rt.constrain(e.x1,0,e.xa._length),e.y0=rt.constrain(e.y0,0,e.ya._length),e.y1=rt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:Pa.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:Pa.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=Pa.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+Pa.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=Pa.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+Pa.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function _i(e,t){var n,r,a=t.container,i=t.fullLayout,o=t.event,l=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||l){var u=It.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var f,d,h=e.hLinePoint;n=h&&h.xa,"cursor"===(r=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=n._offset+h.x,d=r._offset+h.y);var p,g,v=s.readability(h.color,u)<1.5?It.contrast(u):h.color,y=r.spikemode,m=r.spikethickness,x=r.spikecolor||v,b=r._boundingBox,_=(b.left+b.right)/2V.width||H<0||H>V.height)return zt.unhoverRaw(t,r);r.pointerX=r.offsetX,r.pointerY=r.offsetY}if(_="xval"in r?cr.flat(o,r.xval):cr.p2c(h,j),w="yval"in r?cr.flat(o,r.yval):cr.p2c(p,H),!n(_[0])||!n(w[0]))return rt.warn("Fx.hover failed",r,t),zt.unhoverRaw(t,r)}var U=1/0;for(M=0;ME&&(R.splice(0,E),U=R[0].distance),u&&0!==N&&0===R.length){P.distance=N,P.index=!1;var W=A._module.hoverPoints(P,z,O,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=N})),W&&W.length){var Q,J=W.filter(function(e){return e.xa.showspikes});if(J.length){var $=J[0];n($.x0)&&n($.y0)&&(Q=ne($),(!B.vLinePoint||B.vLinePoint.spikeDistance>Q.spikeDistance)&&(B.vLinePoint=Q))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];n(ee.x0)&&n(ee.y0)&&(Q=ne(ee),(!B.hLinePoint||B.hLinePoint.spikeDistance>Q.spikeDistance)&&(B.hLinePoint=Q))}}}}function te(e,t){for(var n,r=null,a=1/0,i=0;i1,ge=It.combine(l.plot_bgcolor||It.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=mi(R,ve,t);if(function(e,t,n){var r,a,i,o,l,s,c,u=0,f=e.map(function(e,r){var a=e[t];return[{i:r,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?hi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?n.width:n.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],n=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=n.pos+n.dp+n.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;r=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;r=!1}if(r){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!r&&u<=e.length;){for(u++,r=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;r=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(R,pe?"xa":"ya",l),xi(ye,pe),r.target&&r.target.tagName){var me=D.getComponentMethod("annotations","hasClickToShow")(t,de);gr(e.select(r.target),me?"pointer":"")}if(!r.target||i||!function(e,t,n){if(!n||n.length!==e._hoverdata.length)return!0;for(var r=n.length-1;r>=0;r--){var a=n[r],i=e._hoverdata[r];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,fe))return;fe&&t.emit("plotly_unhover",{event:r,points:fe});t.emit("plotly_hover",{event:r,points:t._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(t,r,a,i)})},ui.loneHover=function(t,n){var r={color:t.color||It.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(n.container),i=n.outerContainer?e.select(n.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:n.bgColor||It.background,container:a,outerContainer:i},l=mi([r],o,n.gd);return xi(l,o.rotateLabels),l.node()};var ki=ui.hover,Mi=function(e,t,n,r){n("hoverlabel.bgcolor",(r=r||{}).bgcolor),n("hoverlabel.bordercolor",r.bordercolor),n("hoverlabel.namelength",r.namelength),rt.coerceFont(n,"hoverlabel.font",r.font)},Ti=L({editType:"none"});Ti.family.dflt=bt.HOVERFONT,Ti.size.dflt=bt.HOVERFONTSIZE;var Ai={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Ti,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var Li={moduleType:"component",name:"fx",constants:bt,schema:{layout:Ai},attributes:C,layoutAttributes:Ai,supplyLayoutGlobalDefaults:function(e,t){Mi(0,0,function(n,r){return rt.coerce(e,t,Ai,n,r)})},supplyDefaults:function(e,t,n,r){Mi(0,0,function(n,r){return rt.coerce(e,t,C,n,r)},r.hoverlabel)},supplyLayoutDefaults:function(e,t,n){function r(n,r){return rt.coerce(e,t,Ai,n,r)}var a;"select"===r("dragmode")&&r("selectdirection"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,n=0;n0})}function c(e,r){var a=e.seg,i=r.seg,o=a.start,s=a.end,c=i.start,u=i.end;n&&n.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return r;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(r,s):l(e,u),r;p&&(h||(g?l(r,s):l(e,u)),l(r,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(r,o):0===f.alongA?l(r,f.pt):1===f.alongA&&l(r,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(n&&n.vert(f.pt[0]),f.isStart){n&&n.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}n&&n.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,n&&n.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){n&&n.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:r,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:r,f.seg.otherFill={above:v,below:v}),n&&n.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(Di.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),n&&n.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return n&&n.done(),u}return e?{addRegion:function(e){for(var r,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,n,r){var a=t[1]-n[1],i=r[0]-n[0],o=t[0]-n[0],l=r[1]-n[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,n){return Math.abs(t[0]-n[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-r>e&&(l=!l),i=c,o=u}return l}};return t}();function Hi(e,t,n){var r=Ri.segments(e),a=Ri.segments(t),i=n(Ri.combine(r,a));return Ri.polygon(i)}Ri={buildLog:function(e){return!0===e?Bi=Oi():!1===e&&(Bi=!1),!1!==Bi&&Bi.list},epsilon:function(e){return ji.epsilon(e)},segments:function(e){var t=Ei(!0,ji,Bi);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Ei(!1,ji,Bi).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:Fi.union(e.combined,Bi),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:Fi.intersect(e.combined,Bi),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:Fi.difference(e.combined,Bi),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:Fi.differenceRev(e.combined,Bi),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:Fi.xor(e.combined,Bi),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Ii(e.segments,ji,Bi),inverted:e.inverted}},polygonFromGeoJSON:function(e){return Pi.toPolygon(Ri,e)},polygonToGeoJSON:function(e){return Pi.fromPolygon(Ri,ji,e)},union:function(e,t){return Hi(e,t,Ri.selectUnion)},intersect:function(e,t){return Hi(e,t,Ri.selectIntersect)},difference:function(e,t){return Hi(e,t,Ri.selectDifference)},differenceRev:function(e,t){return Hi(e,t,Ri.selectDifferenceRev)},xor:function(e,t){return Hi(e,t,Ri.selectXor)}},"object"==typeof window&&(window.PolyBool=Ri);var qi,Vi=Ri,Ui=He.dot,Gi=r.BADNUM,Yi=qi={};Yi.tester=function(e){if(Array.isArray(e[0][0]))return Yi.multitester(e);var t,n=e.slice(),r=n[0][0],a=r,i=n[0][1],o=i;for(n.push(n[0]),t=1;ta||s===Gi||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===Gi||la||s===Gi||so)return!1;var c,u,f,d,h,p=n.length,g=n[0][0],v=n[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(Ui(i,f))>r)return!0;return!1};Yi.filter=function(e,t){var n=[e[0]],r=0,a=0;function i(i){e.push(i);var o=n.length,l=r;n.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:n}};var Xi=cr.makeEventData,Wi=pt.getFromId,Qi=Wr,Ji=ht.MINSELECT,$i=qi.filter,Ki=qi.tester,eo=qi.multitester;function to(e){return e._id}function no(e,t,n){var r,a,i,o;if(n){var l=n.points||[];for(r=0;r=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function wo(e,t,n,r,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+n+", "+r+")").attr("d",a+"Z")}function ko(e,t,n){return e.append("path").attr("class","zoombox-corners").style({fill:It.background,stroke:It.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+n+")").attr("d","M0,0Z")}function Mo(e,t,n,r,a,i){e.attr("d",r+"M"+n.l+","+n.t+"v"+n.h+"h"+n.w+"v-"+n.h+"h-"+n.w+"Z"),To(e,t,a,i)}function To(e,t,n,r){n||(e.transition().style("fill",r>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function Ao(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Lo(e){go&&e.data&&e._context.showTips&&(rt.notifier(rt._(e,"Double-click to zoom back out"),"long"),go=!1)}function Co(e){return"lasso"===e||"select"===e}function So(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,po)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function zo(e,t){if(vt){var n=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(n,e._onwheel),e._onwheel=t,e.addEventListener(n,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}function Oo(e){var t=[];for(var n in e)t.push(e[n]);return t}var Po={},Do=function(t,n,r,a,i,o,l,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k,M,T,A,L=t._fullLayout._zoomlayer,C=l+c==="nsew",S=1===(l+c).length;function z(){if(u=n.xaxis,f=n.yaxis,m=u._length,x=f._length,v=u._offset,y=f._offset,(d={})[u._id]=u,(h={})[f._id]=f,l&&c)for(var e=n.overlays,r=0;rpo||o>po?(j="xy",i/m>o/x?(o=i*x/m,I>a?N.t=I-o:N.b=I+o):(i=o*m/x,E>r?N.l=E-i:N.r=E+i),q.attr("d",So(N))):l():!w||o10||n.scrollWidth-n.clientWidth>10)){clearTimeout(X);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var a,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),o=Q.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(T){for(c||(s=.5),a=0;a0;o&&(a="array");var l,s=n("categoryorder",a);"array"===s&&(l=n("categoryarray")),o||"array"!==s||(s=t.categoryorder="trace"),"trace"===s?t._initialCategories=[]:"array"===s?t._initialCategories=l.slice():(l=function(e,t){var n,r,a,i=t.dataAttr||e._id.charAt(0),o={};if(t.axData)n=t.axData;else for(n=[],r=0;rp[1]-.01&&(t.domain=o),rt.noneOrAll(e.domain,t.domain,o)}return r("layer"),t},Vo=pt.name2id,Uo=function(e,t,n,r,a){a&&(t._name=a,t._id=Vo(a)),"-"===n("type")&&(!function(e,t){if("-"!==e.type)return;var n=e._id,r=n.charAt(0);-1!==n.indexOf("scene")&&(n=r);var a=function(e,t,n){for(var r=0;r0&&a["_"+n+"axes"][t])return a;if((a[n+"axis"]||n)===t){if(Yo(a,n))return a;if((a[n]||[]).length||a[n+"0"])return a}}}(t,n,r);if(!a)return;if("histogram"===a.type&&r==={v:"y",h:"x"}[a.orientation||"v"])return void(e.type="linear");var i,o=r+"calendar",l=a[o];if(Yo(a,r)){var s=Go(a),c=[];for(i=0;i rect").call(Un.setTranslate,0,0).call(Un.setScale,1,1),e.plot.call(Un.setTranslate,t._offset,n._offset).call(Un.setScale,1,1);var r=e.plot.selectAll(".scatterlayer .trace");r.selectAll(".point").call(Un.setPointGroupScale,1,1),r.selectAll(".textpoint").call(Un.setTextPointsScale,1,1),r.call(Un.hideOutsideRangePoints,e)}function g(e,n){var r,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(r=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-n)+n*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[2]=e.xaxis._length*(1-n+n*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(r=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-n)+n*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[3]=e.yaxis._length*(1-n+n*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,n){var r,a=[];for(a=[e._id,n._id],r=0;rr.duration?(function(){for(var e={},n=0;n.01?T:function(e,t){return Math.abs(e-t)>=2?T(e):e>t?Math.ceil(e):Math.floor(e)};p=k(p,h=k(h,p)),v=k(v,g=k(g,v))}var M=e.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+h+","+g+"V"+v+"H"+p+"V"+g+"Z").call(Un.setClipUrl,r.layerClipId),function(e,t,n,r,a,i,o,l){var s;function c(t,n,r){var a=t.append("text").text(n).attr({class:"bartext bartext-"+s,transform:"","text-anchor":"middle","data-notex":1}).call(Un.font,r).call(mn.convertToTspans,e);return a}var u=n[0].trace,f=u.orientation,d=function(e,t){var n=Sl(e.text,t);return zl(bl,n)}(u,r);if(!d)return;if("none"===(s=function(e,t){var n=Sl(e.textposition,t);return function(e,t,n){return e.coerceNumber&&(t=+t),-1!==e.values.indexOf(t)?t:void 0!==n?n:e.dflt}(_l,n)}(u,r)))return;var h,p,g,v,y,m,x=function(e,t,n){return Cl(wl,e.textfont,t,n)}(u,r,e._fullLayout.font),b=function(e,t,n){return Cl(kl,e.insidetextfont,t,n)}(u,r,x),_=function(e,t,n){return Cl(Ml,e.outsidetextfont,t,n)}(u,r,x),w=e._fullLayout.barmode,k="stack"===w||"relative"===w,M=n[r],T=!k||M._outmost,A=Math.abs(i-a)-2*Tl,L=Math.abs(l-o)-2*Tl;"outside"===s&&(T||(s="inside"));if("auto"===s)if(T){s="inside",h=c(t,d,b),p=Un.bBox(h.node()),g=p.width,v=p.height;var C=g>0&&v>0,S=g<=A&&v<=L,z=g<=L&&v<=A,O="h"===f?A>=g*(L/v):L>=v*(A/g);C&&(S||z||O)?s="inside":(s="outside",h.remove(),h=null)}else s="inside";if(!h&&(h=c(t,d,"outside"===s?_:b),p=Un.bBox(h.node()),g=p.width,v=p.height,g<=0||v<=0))return void h.remove();"outside"===s?(m="both"===u.constraintext||"outside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s="h"===i?Math.abs(r-n):Math.abs(t-e);s>2*Tl&&(l=Tl);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,h,p=(a.left+a.right)/2,g=(a.top+a.bottom)/2;u=c*a.width,f=c*a.height,"h"===i?tn?(d=(e+t)/2,h=r+l+f/2):(d=(e+t)/2,h=r-l-f/2);return Ll(p,g,d,h,c,!1)}(a,i,o,l,p,f,m)):(m="both"===u.constraintext||"inside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s,c,u,f,d,h,p=a.width,g=a.height,v=(a.left+a.right)/2,y=(a.top+a.bottom)/2,m=Math.abs(t-e),x=Math.abs(r-n);m>2*Tl&&x>2*Tl?(m-=2*(f=Tl),x-=2*f):f=0;p<=m&&g<=x?(d=!1,h=1):p<=x&&g<=m?(d=!0,h=1):pn?(c=(e+t)/2,u=r-f-s/2):(c=(e+t)/2,u=r+f+s/2);return Ll(v,y,c,u,h,d)}(a,i,o,l,p,f,m));h.attr("transform",y)}(t,M,a,c,h,p,g,v),r.layerClipId&&Un.hideOutsideRangePoint(a[c],M.select("text"),i,o,u.xcalendar,u.ycalendar)}else e.select(this).remove();function T(t){return 0===l.bargap&&0===l.bargroupgap?e.round(Math.round(t)-w,2):t}})}),D.getComponentMethod("errorbars","plot")(s,r),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Un.setClipUrl(e.select(this),n?null:r.layerClipId)})};function Ll(e,t,n,r,a,i){var o;return a<1?o="scale("+a+") ":(a=1,o=""),"translate("+(n-a*e)+" "+(r-a*t)+")"+o+(i?"rotate("+i+" "+e+" "+t+") ":"")}function Cl(e,t,r,a){var i=Sl((t=t||{}).family,r),o=Sl(t.size,r),l=Sl(t.color,r);return{family:zl(e.family,i,a.family),size:function(e,t,r){if(n(t)){t=+t;var a=e.min,i=e.max,o=void 0!==a&&ti;if(!o)return t}return void 0!==r?r:e.dflt}(e.size,o,a.size),color:function(e,t,n){return s(t).isValid()?t:void 0!==n?n:e.dflt}(e.color,l,a.color)}}function Sl(e,t){var n;return Array.isArray(e)?tc+l||!n(s))&&(f=!0,Ul(u,e))}for(var h=0;h1||0===i.bargap&&0===i.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(n){var r=e.select(this),a=r.selectAll("path"),i=r.selectAll("text"),o=n[0].trace;Un.pointStyle(a,o,t),Un.selectedPointStyle(a,o),i.each(function(t){var n,r=e.select(this);function a(e){var r=n[e];return Array.isArray(r)?r[t.i]:r}r.classed("bartext-inside")?n=o.insidetextfont:r.classed("bartext-outside")&&(n=o.outsidetextfont),n||(n=o.textfont),Un.font(r,a("family"),a("size"),a("color"))}),Un.selectedTextStyle(i,o)}),D.getComponentMethod("errorbars","style")(r)},Ql=m.extendFlat,Jl=vn.LINE_SPACING,$l={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},Kl=function(t,n){var r={};function a(){var o=t._fullLayout,l=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var c,u,f=e.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),d=[],h=[],p="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,y=r.levels.size,m=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(u=0;u<1e5&&(c=r.levels.start+u*y,!(y>0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var q=Math.pow(10,Math.floor(Math.log(H)/Math.LN10));B*=q*rt.roundUp(H/q,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(R.tick0=0)}R.dtick=B}R.domain=[P+S,P+A-S],R.setScale();var V=rt.ensureSingle(o._infolayer,"g",n,function(t){t.classed($l.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed($l.cbbg,!0),t.append("g").classed($l.cbfills,!0),t.append("g").classed($l.cblines,!0),t.append("g").classed($l.cbaxis,!0).classed($l.crisp,!0),t.append("g").classed($l.cbtitleunshift,!0).append("g").classed($l.cbtitle,!0),t.append("rect").classed($l.cboutline,!0),t.select(".cbtitle").datum(0)})});V.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");R._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var Y,Z=l.l+(r.x+L)*l.w,X=R.titlefont.size;Y="top"===r.titleside?(1-(P+A-S))*l.h+l.t+3+.75*X:(1-(P+S))*l.h+l.t-3-.25*X,ee(R._id+"title",{attributes:{x:Z,y:Y,"text-anchor":"start"}})}var W,Q,J,$=rt.syncOrAsync([Qr.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var n=V.select(".cbtitle"),a=n.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],c=n.select(".h"+R._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*Jl),c?(G=Un.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed($l.jsPlaceholder)&&(G=Un.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)R.domain[1]-=G/l.h,i[1]*=-1;else{R.domain[0]+=G/l.h;var v=mn.lineCount(a);i[1]+=(1-v)*u}n.attr("transform","translate("+i+")"),R.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-R.domain[1]))+")"),R._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed($l.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,n){var r=[0===n?f[0]:(h[n]+h[n-1])/2,n===h.length-1?f[1]:(h[n]+h[n+1])/2].map(R.c2p).map(Math.round);n!==h.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=s(a).toHexString();e.select(this).attr({x:z,width:Math.max(k,2),y:e.min(r),height:Math.max(e.max(r)-e.min(r),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?d:[]);return m.enter().append("path").classed($l.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+z+","+(Math.round(R.c2p(t))+r.line.width/2%1)+"h"+k).call(Un.lineGroupStyle,r.line.width,p(t),r.line.dash)}),R._axislayer.selectAll("g."+R._id+"tick,path").remove(),R._pos=z+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),R.side="right",rt.syncOrAsync([function(){return Pa.doTicks(t,R,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var n=R.titlefont.size,a=R._offset+R._length/2,i=l.l+(R.position||0)*l.w+("right"===R.side?10+n*(R.showticklabels?1:.5):-10-n*(R.showticklabels?.5:0));ee("h"+R._id+"title",{avoid:{selection:e.select(t).selectAll("g."+R._id+"tick"),side:r.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Qr.previousPromises,function(){var e=k+r.outlinewidth/2+Un.bBox(R._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed($l.jsPlaceholder)){var a,i=U.select(".h"+R._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Un.bBox(i).width:Un.bBox(U.node()).right-z-l.l,e=Math.max(e,a)}var o=2*r.xpad+e+r.borderwidth+r.outlinewidth/2,s=E-I;V.select(".cbbg").attr({x:z-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:I-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(It.fill,r.bgcolor).call(It.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),V.selectAll(".cboutline").attr({x:z,y:I+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(s-2*r.ypad-G,2)}).call(It.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*o;V.attr("transform","translate("+(l.l-c)+","+l.t+")"),Qr.autoMargin(t,n,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:s*({bottom:1,middle:.5}[r.yanchor]||0),b:s*({top:1,middle:.5}[r.yanchor]||0)})}],t);if($&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition)zt.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),hr(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),Q=zt.align(O+e/l.w,M,0,1,r.xanchor),J=zt.align(P-t/l.h,A,0,1,r.yanchor);var n=zt.getCursor(Q,J,r.xanchor,r.yanchor);hr(V,n)},doneFn:function(){hr(V),void 0!==Q&&void 0!==J&&D.call("restyle",t,{"colorbar.x":Q,"colorbar.y":J},i().index)}});return $}function K(e,t){return rt.coerce(N,R,nn,e,t)}function ee(e,n){var r,a=i();r=D.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:R,propName:r,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),ua.draw(t,e,Ql(l,n||{}))}o._infolayer.selectAll("g."+n).remove()}function i(){var e,r,a=n.substr(2);for(e=0;e=0&&k0){var T=_[r].sort(us),A=T.map(fs),L=A.length,C={pos:v[r],pts:T};C.min=A[0],C.max=A[L-1],C.mean=rt.mean(A,L),C.sd=rt.stdev(A,L,C.mean),C.q1=rt.interp(A,.25),C.med=rt.interp(A,.5),C.q3=rt.interp(A,.75),C.lf=Math.min(C.q1,A[Math.min(rt.findBin(2.5*C.q1-1.5*C.q3,A,!0)+1,L-1)]),C.uf=Math.max(C.q3,A[Math.max(rt.findBin(2.5*C.q3-1.5*C.q1,A),0)]),C.lo=4*C.q1-3*C.q3,C.uo=4*C.q3-3*C.q1;var S=1.57*(C.q3-C.q1)/Math.sqrt(L);C.ln=C.med-S,C.un=C.med+S,f.push(C)}return function(e,t){if(rt.isArrayOrTypedArray(t.selectedpoints))for(var n=0;n0?(f[0].t={num:s[d],dPos:y,posLetter:l,valLetter:i,labels:{med:ls(e,"median:"),min:ls(e,"min:"),q1:ls(e,"q1:"),q3:ls(e,"q3:"),max:ls(e,"max:"),mean:"sd"===t.boxmean?ls(e,"mean \xb1 \u03c3:"):ls(e,"mean:"),lf:ls(e,"lower fence:"),uf:ls(e,"upper fence:")}},s[d]++,f):[{t:{empty:!0}}]};function cs(e,t,n){var r={text:"tx"};for(var a in r)Array.isArray(t[a])&&(e[r[a]]=t[a][n])}function us(e,t){return e.v-t.v}function fs(e){return e.v}function ds(e,t,n,r){var a,i=n("y"),o=n("x");if(i&&i.length)a="v",o||n("x0");else{if(!o||!o.length)return void(t.visible=!1);a="h",n("y0")}D.getComponentMethod("calendars","handleTraceDefaults")(e,t,["x","y"],r),n("orientation",a)}function hs(e,t,n,r){var a=r.prefix,i=rt.coerce2(e,t,os,"marker.outliercolor"),o=n("marker.line.outliercolor"),l=n(a+"points",i||o?"suspectedoutliers":void 0);l?(n("jitter","all"===l?.3:0),n("pointpos","all"===l?-1.5:0),n("marker.symbol"),n("marker.opacity"),n("marker.size"),n("marker.color",t.line.color),n("marker.line.color"),n("marker.line.width"),"suspectedoutliers"===l&&(n("marker.line.outliercolor",t.marker.color),n("marker.line.outlierwidth")),n("selected.marker.color"),n("unselected.marker.color"),n("selected.marker.size"),n("unselected.marker.size"),n("text")):delete t.marker,n("hoveron"),rt.coerceSelectionMarkerOpacity(t,n)}var ps={supplyDefaults:function(e,t,n,r){function a(n,r){return rt.coerce(e,t,os,n,r)}ds(e,t,a,r),!1!==t.visible&&(a("line.color",(e.marker||{}).color||n),a("line.width"),a("fillcolor",It.addOpacity(t.line.color,.5)),a("whiskerwidth"),a("boxmean"),a("notched",void 0!==e.notchwidth)&&a("notchwidth"),hs(e,t,a,{prefix:"box"}))},handleSampleDefaults:ds,handlePointsDefaults:hs};function gs(e,t,n,r){var a,i,o,l,s,c,u,f,d,h,p,g,v=e.cd,y=e.xa,m=e.ya,x=v[0].trace,b=v[0].t,_="violin"===x.type,w=[],k=b.bdPos,M=b.wHover,T=function(e){return e.pos+b.bPos-c};_&&"both"!==x.side?("positive"===x.side&&(d=function(e){var t=T(e);return Li.inbox(t,t+M,h)}),"negative"===x.side&&(d=function(e){var t=T(e);return Li.inbox(t-M,t,h)})):d=function(e){var t=T(e);return Li.inbox(t-M,t+M,h)},g=_?function(e){return Li.inbox(e.span[0]-s,e.span[1]-s,h)}:function(e){return Li.inbox(e.min-s,e.max-s,h)},"h"===x.orientation?(s=t,c=n,u=g,f=d,a="y",o=m,i="x",l=y):(s=n,c=t,u=d,f=g,a="x",o=y,i="y",l=m);var A=Math.min(1,k/Math.abs(o.r2c(o.range[1])-o.r2c(o.range[0])));function L(e){return(u(e)+f(e))/2}h=e.maxHoverDistance-A,p=e.maxSpikeDistance-A;var C=Li.getDistanceFunction(r,u,f,L);if(Li.getClosest(v,C,e),!1===e.index)return[];var S=v[e.index],z=x.line.color,O=(x.marker||{}).color;It.opacity(z)&&x.line.width?e.color=z:It.opacity(O)&&x.boxpoints?e.color=O:e.color=x.fillcolor,e[a+"0"]=o.c2p(S.pos+b.bPos-k,!0),e[a+"1"]=o.c2p(S.pos+b.bPos+k,!0),e[a+"LabelVal"]=S.pos;var P=a+"Spike";e.spikeDistance=L(S)*p/h,e[P]=o.c2p(S.pos,!0);var D={},E=["med","min","q1","q3","max"];(x.boxmean||(x.meanline||{}).visible)&&E.push("mean"),(x.boxpoints||x.points)&&E.push("lf","uf");for(var I=0;Ie.uf}),i=Math.max((e.max-e.min)/10,e.q3-e.q1),c=1e-9*i,u=i*ws,f=[],d=0;if(n.jitter){if(0===i)for(d=1,f=new Array(a.length),t=0;te.lo&&(m.so=!0)}return a}).enter().append("path").classed("point",!0).call(Un.translatePoints,a,i)}function Ts(t,n,r,a){var i,o,l=n.pos,s=n.val,c=a.bPos,u=a.bPosPxOffset||0;Array.isArray(a.bdPos)?(i=a.bdPos[0],o=a.bdPos[1]):(i=a.bdPos,o=a.bdPos),t.selectAll("path.mean").data(rt.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var n=l.c2p(t.pos+c,!0)+u,a=l.c2p(t.pos+c-i,!0)+u,f=l.c2p(t.pos+c+o,!0)+u,d=s.c2p(t.mean,!0),h=s.c2p(t.mean-t.sd,!0),p=s.c2p(t.mean+t.sd,!0);"h"===r.orientation?e.select(this).attr("d","M"+d+","+a+"V"+f+("sd"===r.boxmean?"m0,0L"+h+","+n+"L"+d+","+a+"L"+p+","+n+"Z":"")):e.select(this).attr("d","M"+a+","+d+"H"+f+("sd"===r.boxmean?"m0,0L"+n+","+h+"L"+a+","+d+"L"+n+","+p+"Z":""))})}var As={plot:function(t,n,r){var a=t._fullLayout,i=n.xaxis,o=n.yaxis;n.plot.select(".boxlayer").selectAll("g.trace.boxes").data(r).enter().append("g").attr("class","trace boxes").each(function(t){var r=t[0],l=r.t,s=r.trace,c=e.select(this);n.isRangePlot||(r.node3=c);var u,f,d=a._numBoxes,h=1-a.boxgap,p="group"===a.boxmode&&d>1,g=l.dPos*h*(1-a.boxgroupgap)/(p?d:1),v=p?2*l.dPos*((l.num+.5)/d-.5)*h:0,y=g*s.whiskerwidth;!0!==s.visible||l.empty?c.remove():("h"===s.orientation?(u=o,f=i):(u=i,f=o),l.bPos=v,l.bdPos=g,l.wdPos=y,l.wHover=l.dPos*(p?h/d:1),ks(c,{pos:u,val:f},s,l),s.boxpoints&&Ms(c,{x:i,y:o},s,l),s.boxmean&&Ts(c,{pos:u,val:f},s,l))})},plotBoxAndWhiskers:ks,plotPoints:Ms,plotBoxMean:Ts},Ls=function(e,t){var n,r,a=e.cd,i=e.xaxis,o=e.yaxis,l=[];if(!1===t)for(n=0;n=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}},Is=m.extendFlat,Ns=Is({},{z:{valType:"data_array",editType:"calc"},x:Is({},kr.x,{impliedEdits:{xtype:"array"}}),x0:Is({},kr.x0,{impliedEdits:{xtype:"scaled"}}),dx:Is({},kr.dx,{impliedEdits:{xtype:"scaled"}}),y:Is({},kr.y,{impliedEdits:{ytype:"array"}}),y0:Is({},kr.y0,{impliedEdits:{ytype:"scaled"}}),dy:Is({},kr.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,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",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,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"}},jt,{autocolorscale:Is({},jt.autocolorscale,{dflt:!1})},{colorbar:an}),Rs=Kt.dash,Fs=m.extendFlat,Bs=Es.COMPARISON_OPS2,js=Es.INTERVAL_OPS,Hs=kr.line,qs=Fs({z:Ns.z,x:Ns.x,x0:Ns.x0,dx:Ns.dx,y:Ns.y,y0:Ns.y0,dy:Ns.dy,text:Ns.text,transpose:Ns.transpose,xtype:Ns.xtype,ytype:Ns.ytype,zhoverformat:Ns.zhoverformat,connectgaps:Ns.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},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":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:L({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(Bs).concat(js),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:Fs({},Hs.color,{editType:"style+colorbars"}),width:Fs({},Hs.width,{editType:"style+colorbars"}),dash:Rs,smoothing:Fs({},Hs.smoothing,{}),editType:"plot"}},jt,{autocolorscale:Fs({},jt.autocolorscale,{dflt:!1}),zmin:Fs({},jt.zmin,{editType:"calc"}),zmax:Fs({},jt.zmax,{editType:"calc"})},{colorbar:an}),Vs=rt.extendFlat;function Us(e,t,n){var r={type:"linear",range:[e,t]};return Pa.autoTicks(r,(t-e)/(n||15)),r}var Gs=r.BADNUM,Ys=function(e){for(var t=0,n=0;np&&(v=Math.max(v,Math.abs(e[a][i]-h)/(g-p))))}return v}var $s=rt.isArrayOrTypedArray,Ks=function(e,t,n,r,a,i){var o,l,s,c=[],u=D.traceIs(e,"contour"),f=D.traceIs(e,"histogram"),d=D.traceIs(e,"gl2d");if($s(t)&&t.length>1&&!f&&"category"!==i.type){var h=t.length;if(!(h<=a))return u?t.slice(0,a):t.slice(0,a+1);if(u||d)c=t.slice(0,a);else if(1===a)c=[t[0]-.5,t[0]+.5];else{for(c=[1.5*t[0]-.5*t[1]],s=1;si){var o=i-r[e];return r[e]=i,o}}return 0},max:function(e,t,r,a){var i=a[t];if(n(i)){if(i=Number(i),!n(r[e]))return r[e]=i,i;if(r[e]h&&hac){var p=i===nc?1:6,g=i===nc?"M12":"M1";return function(t,n){var i=r.c2d(t,nc,a),l=i.indexOf("-",p);l>0&&(i=i.substr(0,l));var s=r.d2c(i,0,a);if(slc?e>ac?e>1.1*nc?nc:e>1.1*rc?rc:ac:e>ic?ic:e>oc?oc:lc:Math.pow(10,Math.floor(Math.log(e)/Math.LN10))}function dc(e,t,n,r,a,i){if(r&&e>ac){var o=hc(t,a,i),l=hc(n,a,i),s=e===nc?0:1;return o[s]!==l[s]}return Math.floor(n/e)-Math.floor(t/e)>.1}function hc(e,t,n){var r=t.c2d(e,nc,n).split("-");return""===r[0]&&(r.unshift(),r[0]="-"+r[0]),r}var pc=rt.cleanDate,gc=r.ONEDAY,vc=r.BADNUM,yc=function(e,t,r){var a=t.type,i=r+"bins",o=e[i];o||(o=e[i]={});var l="date"===a?function(e){return e||0===e?pc(e,vc,o.calendar):null}:function(e){return n(e)?Number(e):null};o.start=l(o.start),o.end=l(o.end);var s="date"===a?gc:1,c=o.size;if(n(c))o.size=c>0?Number(c):s;else if("string"!=typeof c)o.size=s;else{var u=c.charAt(0),f=c.substr(1);((f=n(f)?Number(f):0)<=0||"date"!==a||"M"!==u||f!==Math.round(f))&&(o.size=s)}var d="autobin"+r;"boolean"!=typeof e[d]&&(e[d]=e._fullInput[d]=e._input[d]=!((o.start||0===o.start)&&(o.end||0===o.end))),e[d]||(delete e["nbins"+r],delete e._fullInput["nbins"+r])},mc={percent:function(e,t){for(var n=e.length,r=100/t,a=0;av&&l.splice(v,l.length-v),c.length>v&&c.splice(v,c.length-v),xc(t,"x",l,o,d,p,u),xc(t,"y",c,s,h,g,f);var y=[],m=[],x=[],b="string"==typeof t.xbins.size,_="string"==typeof t.ybins.size,w=[],k=[],M=b?w:t.xbins,T=_?k:t.ybins,A=0,L=[],C=[],S=t.histnorm,z=t.histfunc,O=-1!==S.indexOf("density"),P="max"===z||"min"===z?null:0,D=tc.count,E=mc[S],I=!1,N=[],R=[],F="z"in t?t.z:"marker"in t&&Array.isArray(t.marker.color)?t.marker.color:"";F&&"count"!==z&&(I="avg"===z,D=tc[z]);var B=t.xbins,j=d(B.start),H=d(B.end)+(j-Pa.tickIncrement(j,B.size,!1,u))/1e6;for(n=j;n=0&&a=0&&i=0;i--)(o=((u[[(n=(a=f[i])[0])-1,r=a[1]]]||p)[2]+(u[[n+1,r]]||p)[2]+(u[[n,r-1]]||p)[2]+(u[[n,r+1]]||p)[2])/20)&&(l[a]=[n,r,o],f.splice(i,1),s=!0);if(!s)throw"findEmpties iterated with no new neighbors";for(a in l)u[a]=l[a],c.push(l[a])}return c.sort(function(e,t){return t[2]-e[2]})}(c),t._interpz=function(e,t,n){var r,a,i=1;if(Array.isArray(n))for(r=0;r.01;r++)i=Js(e,t,Qs(i));return i>.01&&rt.log("interp2d didn't converge quickly",i),e}(c,t._emptypoints,t._interpz))}function x(e){y=t._input.zsmooth=t.zsmooth=!1,rt.warn('cannot use zsmooth: "fast": '+e)}if("fast"===y)if("log"===d.type||"log"===h.type)x("log axis found");else if(!g){if(r.length){var b=(r[r.length-1]-r[0])/(r.length-1),_=Math.abs(b/100);for(u=0;u_){x("x scale is not linear");break}}if(o.length&&"fast"===y){var w=(o[o.length-1]-o[0])/(o.length-1),k=Math.abs(w/100);for(u=0;uk){x("y scale is not linear");break}}}var M=Ys(c),T="scaled"===t.xtype?"":r,A=Ks(t,T,a,i,M,d),L="scaled"===t.ytype?"":o,C=Ks(t,L,l,s,c.length,h);v||(Pa.expand(d,A),Pa.expand(h,C));var S={x:A,y:C,z:c,text:t._text||t.text};if(T&&T.length===A.length-1&&(S.xCenter=T),L&&L.length===C.length-1&&(S.yCenter=L),g&&(S.xRanges=f.xRanges,S.yRanges=f.yRanges,S.pts=f.pts),p&&"constraint"===t.contours.type||qt(t,c,"","z"),p&&t.contours&&"heatmap"===t.contours.coloring){var z={type:"contour"===t.type?"heatmap":"histogram2d",xcalendar:t.xcalendar,ycalendar:t.ycalendar};S.xfill=Ks(z,T,a,i,M,d),S.yfill=Ks(z,L,l,s,c.length,h)}return[S]},Mc=function(e,t){var n=kc(e,t);return function(e){var t=e.contours;if(e.autocontour){var n=Us(e.zmin,e.zmax,e.ncontours);t.size=n.dtick,t.start=Pa.tickFirst(n),n.range.reverse(),t.end=Pa.tickFirst(n),t.start===e.zmin&&(t.start+=t.size),t.end===e.zmax&&(t.end-=t.size),t.start>t.end&&(t.start=t.end=(t.start+t.end)/2),e._input.contours||(e._input.contours={}),Vs(e._input.contours,{start:t.start,end:t.end,size:t.size}),e._input.autocontour=!0}else if("constraint"!==t.type){var r,a=t.start,i=t.end,o=e._input.contours;a>i&&(t.start=o.start=i,i=t.end=o.end=a,a=t.start),t.size>0||(r=a===i?1:Us(a,i,e.ncontours).dtick,o.size=t.size=r)}}(t),n},Tc=function(e){return e.end+e.size/1e6},Ac=function(t){var n=t.contours,r=n.start,a=Tc(n),i=n.size||1,o=Math.floor((a-r)/i)+1,l="lines"===n.coloring?0:1;isFinite(i)||(i=1,o=1);var s,c,u=t.colorscale,f=u.length,d=new Array(f),h=new Array(f);if("heatmap"===n.coloring){for(t.zauto&&!1===t.autocontour&&(t.zmin=r-i/2,t.zmax=t.zmin+o*i),c=0;c2?t.value=t.value.slice(2):0===t.length?t.value=[0,1]:t.length<2?(r=parseFloat(t.value[0]),t.value=[r,r+1]):t.value=[parseFloat(t.value[0]),parseFloat(t.value[1])]:n(t.value)&&(r=parseFloat(t.value),t.value=[r,r+1])):(e("contours.value",0),n(t.value)||(Array.isArray(t.value)?t.value=parseFloat(t.value[0]):t.value=0))}(r,u),"="===f?l=u.showlines=!0:(l=r("contours.showlines"),c=r("fillcolor",Sc((e.line||{}).color||i,.5))),l)&&(s=r("line.color",c&&zc(c)?Sc(t.fillcolor,1):i),r("line.width",2),r("line.dash"));r("line.smoothing"),Cc(r,a,s,o)};var Ec=function(e,t,n,r){var a=r("contours.start"),i=r("contours.end"),o=!1===a||!1===i,l=n("contours.size");!(o?t.autocontour=!0:n("autocontour",!1))&&l||n("ncontours")},Ic=function(e,t,n,r,a){var i,o=n("contours.coloring"),l="";"fill"===o&&(i=n("contours.showlines")),!1!==i&&("lines"!==o&&(l=n("line.color","#000")),n("line.width",.5),n("line.dash")),"none"!==o&&fn(e,t,r,n,{prefix:"",cLetter:"z"}),n("line.smoothing"),Cc(n,r,l,a)},Nc=rt.isArrayOrTypedArray,Rc=function(e,t,r,a,i,o){var l,s,c=r("z");if(i=i||"x",o=o||"y",void 0===c||!c.length)return 0;if(Xs(e)){if(l=r(i),s=r(o),!l||!s)return 0}else{if(l=Fc(i,r),s=Fc(o,r),!function(e){for(var t,r=!0,a=!1,i=!1,o=0;o0&&(a=!0);for(var l=0;l=v[0].length||c<0||c>v.length)return}else{if(Li.inbox(t-p[0],t-p[p.length-1],0)>0||Li.inbox(n-g[0],n-g[g.length-1],0)>0)return;if(i){var M;for(w=[2*p[0]-p[1]],M=1;M":f.value>d&&(l.prefixBoundary=!0);break;case"<":f.valued)&&(l.prefixBoundary=!0);break;case"][":i=Math.min.apply(null,f.value),o=Math.max.apply(null,f.value),id&&(l.prefixBoundary=!0)}},qc={BOTTOMSTART:[1,9,13,104,713],TOPSTART:[4,6,7,104,713],LEFTSTART:[8,12,14,208,1114],RIGHTSTART:[2,3,11,208,1114],NEWDELTA:[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],CHOOSESADDLE:{104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},SADDLEREMAINDER:{1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11},LABELDISTANCE:2,LABELINCREASE:10,LABELMIN:3,LABELMAX:10,LABELOPTIMIZER:{EDGECOST:1,ANGLECOST:1,NEIGHBORCOST:5,SAMELEVELFACTOR:10,SAMELEVELDISTANCE:5,MAXCOST:100,INITIALSEARCHPOINTS:10,ITERATIONS:5}},Vc=function(e,t){var n,r,a,i=function(e){return e.reverse()},o=function(e){return e};switch(t){case"=":case"<":return e;case">":for(1!==e.length&&rt.warn("Contour data invalid for the specified inequality operation."),r=e[0],n=0;n":Xc(">"),"<":Xc("<"),"=":Xc("=")};function Yc(e,t){var r,a=Array.isArray(t);function i(e){return n(e)?+e:null}return-1!==Es.COMPARISON_OPS2.indexOf(e)?r=i(a?t[0]:t):-1!==Es.INTERVAL_OPS.indexOf(e)?r=a?[i(t[0]),i(t[1])]:[i(t),i(t)]:-1!==Es.SET_OPS.indexOf(e)&&(r=a?t.map(i):[i(t)]),r}function Zc(e){return function(t){t=Yc(e,t);var n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]);return{start:n,end:r,size:r-n}}}function Xc(e){return function(t){return{start:t=Yc(e,t),end:1/0,size:1/0}}}var Wc=function(e,t,n){for(var r="constraint"===e.type?Gc[e._operation](e.value):e,a=r.size,i=[],o=Tc(r),l=n.trace._carpetTrace,s=l?{xaxis:l.aaxis,yaxis:l.baxis,x:n.a,y:n.b}:{xaxis:t.xaxis,yaxis:t.yaxis,x:n.x,y:n.y},c=r.start;c1e3){rt.warn("Too many contours, clipping at 1000",e);break}return i},Qc=function(e,t,n){var r,a,i,o;for(t=t||.01,n=n||.01,a=0;a20&&t?208===e||1114===e?r=0===n[0]?1:-1:a=0===n[1]?1:-1:-1!==qc.BOTTOMSTART.indexOf(e)?a=1:-1!==qc.LEFTSTART.indexOf(e)?r=1:-1!==qc.TOPSTART.indexOf(e)?a=-1:r=-1;return[r,a]}(s,n,t),u=[Kc(e,t,[-c[0],-c[1]])],f=c.join(","),d=e.z.length,h=e.z[0].length;for(i=0;i<1e4;i++){if(s>20?(s=qc.CHOOSESADDLE[s][(c[0]||c[1])<0?0:1],e.crossings[l]=qc.SADDLEREMAINDER[s]):delete e.crossings[l],!(c=qc.NEWDELTA[s])){rt.log("Found bad marching index:",s,t,e.level);break}u.push(Kc(e,t,c)),t[0]+=c[0],t[1]+=c[1],Jc(u[u.length-1],u[u.length-2],r,a)&&u.pop(),l=t.join(",");var p=c[0]&&(t[0]<0||t[0]>h-2)||c[1]&&(t[1]<0||t[1]>d-2);if(l===o&&c.join(",")===f||n&&p)break;s=e.crossings[l]}1e4===i&&rt.log("Infinite loop in contour?");var g,v,y,m,x,b,_,w,k,M,T,A,L,C,S,z=Jc(u[0],u[u.length-1],r,a),O=0,P=.2*e.smoothing,D=[],E=0;for(i=1;i=E;i--)if((g=D[i])=E&&g+D[v]w&&k--,e.edgepaths[k]=T.concat(u,M));break}F||(e.edgepaths[w]=u.concat(M))}for(w=0;we?0:1)+(t[0][1]>e?0:2)+(t[1][1]>e?0:4)+(t[1][0]>e?0:8);return 5===n||10===n?e>(t[0][0]+t[0][1]+t[1][0]+t[1][1])/4?5===n?713:1114:5===n?104:208:15===n?0:n}var nu=function(e,t,n){for(var r=0;r0;)h=l.c2p(x[y]),y--;for(h0;)v=c.c2p(b[y]),y--;if(ve.level}return n?"M"+t.join("L")+"Z":""}(e,t),u=0,f=e.edgepaths.map(function(e,t){return t}),d=!0;function h(e){return Math.abs(e[1]-t[2][1])<.01}function p(e){return Math.abs(e[0]-t[0][0])<.01}function g(e){return Math.abs(e[0]-t[2][0])<.01}for(;f.length;){for(l=Un.smoothopen(e.edgepaths[u],e.smoothing),c+=d?l:l.replace(/^M/,"L"),f.splice(f.indexOf(u),1),n=e.edgepaths[u][e.edgepaths[u].length-1],i=-1,a=0;a<4;a++){if(!n){rt.log("Missing end?",u,e);break}for(s=n,Math.abs(s[1]-t[0][1])<.01&&!g(n)?r=t[1]:p(n)?r=t[0]:h(n)?r=t[3]:g(n)&&(r=t[2]),o=0;o=0&&(r=v,i=o):Math.abs(n[1]-r[1])<.01?Math.abs(n[1]-v[1])<.01&&(v[0]-n[0])*(r[0]-v[0])>=0&&(r=v,i=o):rt.log("endpt to newendpt is not vert. or horz.",n,r,v)}if(n=r,i>=0)break;c+="L"+r}if(i===e.edgepaths.length){rt.log("unclosed perimeter path");break}u=i,(d=-1===f.indexOf(u))&&(u=f[0],c+="Z")}for(u=0;ur.center?r.right-o:o-r.left)/(c+Math.abs(Math.sin(s)*i)),d=(l>r.middle?r.bottom-l:l-r.top)/(Math.abs(u)+Math.cos(s)*i);if(f<1||d<1)return 1/0;var h=su.EDGECOST*(1/(f-1)+1/(d-1));h+=su.ANGLECOST*s*s;for(var p=o-c,g=l-u,v=o+c,y=l+u,m=0;m2*su.MAXCOST)break;d&&(o/=2),l=(i=s-o/2)+1.5*o}if(f<=su.MAXCOST)return c},lu.addLabelData=function(e,t,n,r){var a=t.width/2,i=t.height/2,o=e.x,l=e.y,s=e.theta,c=Math.sin(s),u=Math.cos(s),f=a*u,d=i*c,h=a*c,p=-i*u,g=[[o-f-d,l-h-p],[o+f-d,l+h-p],[o+f+d,l+h+p],[o-f+d,l-h+p]];n.push({text:t.text,x:o,y:l,dy:t.dy,theta:s,level:t.level,width:t.width,height:t.height}),r.push(g)},lu.drawLabels=function(t,n,r,a,i){var o=t.selectAll("text").data(n,function(e){return e.text+","+e.x+","+e.y+","+e.theta});if(o.exit().remove(),o.enter().append("text").attr({"data-notex":1,"text-anchor":"middle"}).each(function(t){var n=t.x+Math.sin(t.theta)*t.dy,a=t.y-Math.cos(t.theta)*t.dy;e.select(this).text(t.text).attr({x:n,y:a,transform:"rotate("+180*t.theta/Math.PI+" "+n+" "+a+")"}).call(mn.convertToTspans,r)}),i){for(var l="",s=0;s1)for(var n=1;n=0,p=n.indexOf("end")>=0,g=c.backoff*f+r.standoff,v=u.backoff*d+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}n._w=C,n._h=S;for(var E=!1,I=["x","y"],N=0;N1)&&(U===V?((K=G.r2fraction(n["a"+q]))<0||K>1)&&(E=!0):E=!0,E))continue;R=G._offset+G.r2p(n[q]),j=.5}else"x"===q?(B=n[q],R=u.l+u.w*B):(B=1-n[q],R=u.t+u.h*B),j=n.showarrow?.5:B;if(n.showarrow){$.head=R;var ee=n["a"+q];H=Z*P(.5,n.xanchor)-X*P(.5,n.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=H):($.tail=R+ee,F=H+ee),$.text=$.tail+H;var te=c["x"===q?"width":"height"];if("paper"===V&&($.head=rt.constrain($.head,1,te-1)),"pixel"===U){var ne=-Math.max($.tail-3,$.text),re=Math.min($.tail+3,$.text)-te;ne>0?($.tail+=ne,$.text+=ne):re>0&&($.tail-=re,$.text-=re)}$.tail+=J,$.head+=J}else F=H=W*P(j,Q),$.text=R+H;$.text+=J,H+=J,F+=J,n["_"+q+"padplus"]=W/2+F,n["_"+q+"padminus"]=W/2-F,n["_"+q+"size"]=W,n["_"+q+"shift"]=H}if(E)x.remove();else{var ae=0,ie=0;if("left"!==n.align&&(ae=(C-_)*("center"===n.align?.5:1)),"top"!==n.valign&&(ie=(S-A)*("middle"===n.valign?.5:1)),l)r.select("svg").attr({x:w+ae-1,y:w+ie}).call(Un.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(mn.positionText,le,oe).call(Un.setClipUrl,M?d:null)}T.select("rect").call(Un.setRect,w,w,C,S),k.call(Un.setRect,b/2,b/2,z-b,O-b),x.call(Un.setTranslate,Math.round(h.x.text-z/2),Math.round(h.y.text-O/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,r){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+r,m=h.x.text+e,b=h.y.text+r,_=rt.rotationXYMatrix(p,m,b),w=rt.apply2DTransform(_),M=rt.apply2DTransform2(_),T=+k.attr("width"),A=+k.attr("height"),L=m-.5*T,C=L+T,S=b-.5*A,z=S+A,O=[[L,S,L,z],[L,z,C,z],[C,z,C,S],[C,S,L,S]].map(M);if(!O.reduce(function(e,t){return e^!!rt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){O.forEach(function(e){var t=rt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var P=n.arrowwidth,E=n.arrowcolor,I=n.arrowside,N=g.append("g").style({opacity:It.opacity(E)}).classed("annotation-arrow-g",!0),R=N.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",P+"px").call(It.stroke,It.rgb(E));if(Fu(R,I,n),f.annotationPosition&&R.node().parentNode&&!a){var F=l,B=c;if(n.standoff){var j=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=n.standoff*(d-l)/j,B+=n.standoff*(y-c)/j}var H,q,V,U=N.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-B),transform:"translate("+F+","+B+")"}).style("stroke-width",P+6+"px").call(It.stroke,"rgba(0,0,0,0)").call(It.fill,"rgba(0,0,0,0)");zt.init({element:U.node(),gd:t,prepFn:function(){var e=Un.getTranslate(x);q=e.x,V=e.y,H={},i&&i.autorange&&(H[i._name+".autorange"]=!0),o&&o.autorange&&(H[o._name+".autorange"]=!0)},moveFn:function(e,t){var r=w(q,V),a=r[0]+e,l=r[1]+t;x.call(Un.setTranslate,a,l),H[s+".x"]=i?i.p2r(i.r2p(n.x)+e):n.x+e/u.w,H[s+".y"]=o?o.p2r(o.r2p(n.y)+t):n.y-t/u.h,n.axref===n.xref&&(H[s+".ax"]=i.p2r(i.r2p(n.ax)+e)),n.ayref===n.yref&&(H[s+".ay"]=o.p2r(o.r2p(n.ay)+t)),N.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){D.call("relayout",t,H);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(n.showarrow&&ue(0,0),y)zt.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var r="pointer";if(n.showarrow)n.axref===n.xref?se[s+".ax"]=i.p2r(i.r2p(n.ax)+e):se[s+".ax"]=n.ax+e,n.ayref===n.yref?se[s+".ay"]=o.p2r(o.r2p(n.ay)+t):se[s+".ay"]=n.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(n.x)+e);else{var l=n._xsize/u.w,c=n.x+(n._xshift-n.xshift)/u.w-l/2;se[s+".x"]=zt.align(c+e/u.w,l,0,1,n.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(n.y)+t);else{var f=n._ysize/u.h,d=n.y-(n._yshift+n.yshift)/u.h-f/2;se[s+".y"]=zt.align(d-t/u.h,f,0,1,n.yanchor)}i&&o||(r=zt.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],n.xanchor,n.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),hr(x,r)},doneFn:function(){hr(x),D.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var qu=Bu.draw;function Vu(e){var t=e._fullLayout;rt.filterVisible(t.annotations).forEach(function(t){var n,r,a,i,o=Pa.getFromId(e,t.xref),l=Pa.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(n=s+t.xshift,r=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(Pa.expand(o,[o.r2c(t.x)],{ppadplus:n,ppadminus:r}),Pa.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,Pa.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,n,a),ppadminus:Math.max(t._xpadminus,r,i)}))),l&&l.autorange&&(n=s-t.yshift,r=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(Pa.expand(l,[l.r2c(t.y)],{ppadplus:n,ppadminus:r}),Pa.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,Pa.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,n,a),ppadminus:Math.max(t._ypadminus,r,i)})))})}var Uu={hasClickToShow:function(e,t){var n=Gu(e,t);return n.on.length>0||n.explicitOff.length>0},onClick:function(e,t){var n,r=Gu(e,t),a=r.on,i=r.off.concat(r.explicitOff),o={};if(!a.length&&!i.length)return;for(n=0;n1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=nf(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*n[0],t.yaxis.r2l(i.y)*n[1],t.zaxis.r2l(i.z)*n[2]]),rf(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var lf={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},sf=function(e){var t=e.type,n=e.symmetric;if("data"===t){var r=e.array||[];if(n)return function(e,t){var n=+r[t];return[n,n]};var a=e.arrayminus||[];return function(e,t){var n=+r[t],i=+a[t];return isNaN(n)&&isNaN(i)?[NaN,NaN]:[i||0,n||0]}}var i=cf(t,e.value),o=cf(t,e.valueminus);return n||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function cf(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var uf=function(e){for(var t=e.calcdata,n=0;n0;t.each(function(t){var s,c=t[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Vn.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(t=[]);var h=e.select(this).selectAll("g.errorbar").data(t,s);if(h.exit().remove(),t.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Un.setClipUrl(h,r.layerClipId),h.each(function(t){var r=e.select(this),s=function(e,t,r){var a={x:t.c2p(e.x),y:r.c2p(e.y)};return void 0!==e.yh&&(a.yh=r.c2p(e.yh),a.ys=r.c2p(e.ys),n(a.ys)||(a.noYS=!0,a.ys=r.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=t.c2p(e.xh),a.xs=t.c2p(e.xs),n(a.xs)||(a.noXS=!0,a.xs=t.c2p(e.xs,!0))),a}(t,i,o);if(!d||t.vis){var c,h=r.select("path.yerror");if(f.visible&&n(s.x)&&n(s.yh)&&n(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=r.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=r.select("path.xerror");if(u.visible&&n(s.y)&&n(s.xh)&&n(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=r.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var n=t[0].trace,r=n.error_y||{},a=n.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(It.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(It.stroke,a.color)})},hoverInfo:function(e,t,n){(t.error_y||{}).visible&&(n.yerr=e.yh-e.y,t.error_y.symmetric||(n.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(n.xerr=e.xh-e.x,t.error_x.symmetric||(n.xerrneg=e.x-e.xs))}};var vf={},yf=m.extendFlat;vf.attributes=function(e,t){e=e||{},t=t||{};var n={valType:"info_array",editType:e.editType,items:[{valType:"number",min:0,max:1,editType:e.editType},{valType:"number",min:0,max:1,editType:e.editType}],dflt:[0,1]},r=(e.name&&e.name,e.trace,t.description&&t.description,{x:yf({},n,{}),y:yf({},n,{}),editType:e.editType});return e.noGridCell||(r.row={valType:"integer",min:0,dflt:0,editType:e.editType},r.column={valType:"integer",min:0,dflt:0,editType:e.editType}),r},vf.defaults=function(e,t,n,r){var a=r&&r.x||[0,1],i=r&&r.y||[0,1],o=t.grid;if(o){var l=n("domain.column");void 0!==l&&(l1){l||s||c||"independent"===x("pattern")&&(l=!0),f._hasSubplotGrid=l;var p,g,v="top to bottom"===x("roworder"),y=l?.2:.1,m=l?.3:.1;u&&(p="bottom",g="left"),f._domains={x:kf("x",x,y,p,h),y:kf("y",x,m,g,d,v)}}}function x(e,t){return rt.coerce(n,f,_f,e,t)}},contentDefaults:function(e,t){var n=t.grid;if(n&&n._domains){var r,a,i,o,l,s,c,u=e.grid||{},f=t._subplots,d=n._hasSubplotGrid,h=n.rows,p=n.columns,g="independent"===n.pattern,v=n._axisMap={};if(d){var y=u.subplots||[];s=n.subplots=new Array(h);var m=1;for(r=0;r=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},Pf={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Df=!0,Ef=function(e,t,n){if(!t._dragged&&!t._editing){var r,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===n&&Df&&t.data&&t._context.showTips?(rt.notifier(rt._(t,"Double-click on legend to isolate one trace"),"long"),Df=!1):Df=!1,D.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===n?-1===m?s.push(y):s.splice(m,1):2===n&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),D.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(r=0;rn[1])return n[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",rt.mean,[.2,1]),d.ms=u("marker.size",rt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",rt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),r=[rt.minExtend(i,d)],a=rt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Un.pointStyle,a,n),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Un.textPointStyle,a,n)}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(e,t){return t?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("stroke-width",i+"px").call(It.fill,a.fillcolor),i&&It.stroke(o,a.line.color)})}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(e,t){return t?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("fill","none").call(Un.dashLine,a.line.dash,i),i&&It.stroke(o,a.line.color)})})},Bf=vn.LINE_SPACING,jf=vn.FROM_TL,Hf=vn.FROM_BR,qf=h.DBLCLICKDELAY;function Vf(e,t){var n=e.data()[0][0],r=t._fullLayout,a=n.trace,i=D.traceIs(a,"pie"),o=a.index,l=i?n.label:a.name,s=rt.ensureSingle(e,"text","legendtext");function c(n){mn.convertToTspans(n,t,function(){!function(e,t){var n=e.data()[0][0];if(!n.trace.showlegend)return void e.remove();var r,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*Bf;if(o){var s=Un.bBox(o);r=s.height,a=s.width,Un.setTranslate(i,0,r/4)}else{var c=e.select(".legendtext"),u=mn.lineCount(c),f=c.node();r=l*u,a=f?Un.bBox(f).width:0;var d=l*(.3+(1-u)/2);mn.positionText(c,40,d)}r=Math.max(r,16)+3,n.height=r,n.width=a}(e,t)})}s.attr("text-anchor","start").classed("user-select-none",!0).call(Un.font,r.legend.font).text(l),t._context.edits.legendText&&!i?s.call(mn.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var r=e;this.text()||(e=" ");var a=n.trace._fullInput||{},i={};if(D.hasTransform(a,"groupby")){var l=D.getTransformIndices(a,"groupby"),s=l[l.length-1],u=rt.keyedContainer(a,"transforms["+s+"].styles","target","value.name");""===r?u.remove(n.trace._group):u.set(n.trace._group,e),i=u.constructUpdate()}else i.name=e;return D.call("restyle",t,i,o)}):c(s)}function Uf(e,t){var n,r=1,a=rt.ensureSingle(e,"rect","legendtoggle",function(e){e.style("cursor","pointer").attr("pointer-events","all").call(It.fill,"rgba(0,0,0,0)")});a.on("mousedown",function(){(n=(new Date).getTime())-t._legendMouseDownTimeqf&&(r=Math.max(r-1,1)),1===r?n._clickTimeout=setTimeout(function(){Ef(e,t,r)},qf):2===r&&(n._clickTimeout&&clearTimeout(n._clickTimeout),t._legendMouseDownTime=0,Ef(e,t,r))}})}function Gf(t,n,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=zf.isGrouped(i),s=0;if(i._width=0,i._height=0,zf.isVertical(i))l&&n.each(function(e,t){Un.setTranslate(this,0,t*i.tracegroupgap)}),r.each(function(e){var t=e[0],n=t.height,r=t.width;Un.setTranslate(this,o,5+o+i._height+n/2),i._height+=n,i._width=Math.max(i._width,r)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=n.data(),f=0,d=u.length;fo+b-_,r.each(function(e){var t=e[0],n=g?40+e[0].width:m;o+x+_+n>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Un.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+n,i._height=Math.max(i._height,t.height),x+=_+n,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(n){var r=n[0],a=e.select(this).select(".legendtoggle");Un.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function Yf(e){var t=e._fullLayout.legend,n="left";Of.isRightAnchor(t)?n="right":Of.isCenterAnchor(t)&&(n="center");var r="top";Of.isBottomAnchor(t)?r="bottom":Of.isMiddleAnchor(t)&&(r="middle"),Qr.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*jf[n],r:t._width*Hf[n],b:t._height*Hf[r],t:t._height*jf[r]})}var Zf={moduleType:"component",name:"legend",layoutAttributes:Sf,supplyLayoutDefaults:function(e,t,n){for(var r,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),rt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(r=0,i="left",a=1.1,o="bottom"):(r=0,i="left",a=-.1,o="top")}h("traceorder",u),zf.isGrouped(t.legend)&&h("tracegroupgap"),h("x",r),h("xanchor",i),h("y",a),h("yanchor",o),rt.noneOrAll(l,s,["x","y"])}},draw:function(t){var n=t._fullLayout,r="legend"+n._uid;if(n._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=n.legend,i=n.showlegend&&function(e,t){var n,r,a={},i=[],o=!1,l={},s=0;function c(e,n){if(""!==e&&zf.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[n]]):a[e].push([n]);else{var r="~~i"+s;i.push(r),a[r]=[[n]],s++}}for(n=0;nv?function(e){var t=e._fullLayout.legend,n="left";Of.isRightAnchor(t)?n="right":Of.isCenterAnchor(t)&&(n="center"),Qr.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*jf[n],r:t._width*Hf[n],b:0,t:0})}(t):Yf(t);var y=n._size,m=y.l+y.w*a.x,x=y.t+y.h*(1-a.y);Of.isRightAnchor(a)?m-=a._width:Of.isCenterAnchor(a)&&(m-=a._width/2),Of.isBottomAnchor(a)?x-=a._height:Of.isMiddleAnchor(a)&&(x-=a._height/2);var b=a._width,_=y.w;b>_?(m=y.l,b=_):(m+b>g&&(m=g-b),m<0&&(m=0),b=Math.min(g-m,a._width));var w,k,M,T,A=a._height,L=y.h;if(A>L?(x=y.t,A=L):(x+A>v&&(x=v-A),x<0&&(x=0),A=Math.min(v-x,a._height)),Un.setTranslate(s,m,x),d.on(".drag",null),s.on("wheel",null),a._height<=A||t._context.staticPlot)u.attr({width:b-a.borderwidth,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Un.setTranslate(f,0,0),c.select("rect").attr({width:b-2*a.borderwidth,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Un.setClipUrl(f,r),Un.setRect(d,0,0,0,0),delete a._scrollY;else{var C,S,z=Math.max(Pf.scrollBarMinHeight,A*A/a._height),O=A-z-2*Pf.scrollBarMargin,P=a._height-A,E=O/P,I=Math.min(a._scrollY||0,P);u.attr({width:b-2*a.borderwidth+Pf.scrollBarWidth+Pf.scrollBarMargin,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),c.select("rect").attr({width:b-2*a.borderwidth+Pf.scrollBarWidth+Pf.scrollBarMargin,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+I}),Un.setClipUrl(f,r),R(I,z,E),s.on("wheel",function(){R(I=rt.constrain(a._scrollY+e.event.deltaY/O*P,0,P),z,E),0!==I&&I!==P&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){C=e.event.sourceEvent.clientY,S=I}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||R(I=rt.constrain((t.clientY-C)/E+S,0,P),z,E)});d.call(N)}t._context.edits.legendPosition&&(s.classed("cursor-move",!0),zt.init({element:s.node(),gd:t,prepFn:function(){var e=Un.getTranslate(s);M=e.x,T=e.y},moveFn:function(e,t){var n=M+e,r=T+t;Un.setTranslate(s,n,r),w=zt.align(n,0,y.l,y.l+y.w,a.xanchor),k=zt.align(r,0,y.t+y.h,y.t,a.yanchor)},doneFn:function(){void 0!==w&&void 0!==k&&D.call("relayout",t,{"legend.x":w,"legend.y":k})},clickFn:function(e,r){var a=n._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return r.clientX>=e.left&&r.clientX<=e.right&&r.clientY>=e.top&&r.clientY<=e.bottom});a.size()>0&&(1===e?s._clickTimeout=setTimeout(function(){Ef(a,t,e)},qf):2===e&&(s._clickTimeout&&clearTimeout(s._clickTimeout),Ef(a,t,e)))}}))}function R(e,n,r){a._scrollY=t._fullLayout.legend._scrollY=e,Un.setTranslate(f,0,-e),Un.setRect(d,b,Pf.scrollBarMargin+e*r,Pf.scrollBarWidth,n),c.select("rect").attr({y:a.borderwidth+e})}},style:Ff},Xf={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},Wf=m.extendFlat,Qf={visible:{valType:"boolean",editType:"plot"},buttons:Xf=Wf(Xf,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:L({editType:"plot"}),bgcolor:{valType:"color",dflt:z.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:z.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},Jf={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var $f=function(t,n){var r=t._name,a={};if("all"===n.step)a[r+".autorange"]=!0;else{var i=function(t,n){var r,a=t.range,i=new Date(t.r2l(a[1])),o=n.step,l=n.count;switch(n.stepmode){case"backward":r=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);r=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,n);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var Kf=vn.LINE_SPACING,ed=vn.FROM_TL,td=vn.FROM_BR;function nd(e){return e._id}function rd(e,t,n){var r=rt.ensureSingle(e,"rect","selector-rect",function(e){e.attr("shape-rendering","crispEdges")});r.attr({rx:Jf.rx,ry:Jf.ry}),r.call(It.stroke,t.bordercolor).call(It.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,n)).style("stroke-width",t.borderwidth+"px")}function ad(e,t,n,r){var a;rt.ensureSingle(e,"text","selector-text",function(e){e.classed("user-select-none",!0).attr("text-anchor","middle")}).call(Un.font,t.font).text((a=n,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){mn.convertToTspans(e,r)})}var id={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:Qf}}},layoutAttributes:Qf,handleDefaults:function(e,t,n,r,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return rt.coerce(i,o,Qf,e,t)}if(l("visible",function(e,t,n){var r,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return rt.coerce(r,a,Xf,e,t)}for(var s=0;s0)){var s=function(e,t,n){for(var r=n.filter(function(n){return t[n].anchor===e._id}),a=0,i=0;i0?c+o:o;return{ppad:o,ppadplus:l?f:d,ppadminus:l?d:f}}return{ppad:o}}function Ld(e,t,n,r,a){var i="category"===e.type?e.r2c:e.d2c;if(void 0!==t)return[i(t),i(n)];if(r){var o,l,s,c,u=1/0,f=-1/0,d=r.match(wd.segmentRE);for("date"===e.type&&(i=kd.decodeDate(i)),o=0;of&&(f=c)));return f>=u?[u,f]:void 0}}var Cd=function(e,t,n,r,a){function i(n,r){return rt.coerce(e,t,_d,n,r)}if(r=r||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=i("xsizemode"),s=i("ysizemode"),c=["x","y"],u=0;u<2;u++){var f,d,h,p=c[u],g=p+"anchor",v="x"===p?l:s,y={_fullLayout:n},m=Pa.coerceRef(e,t,y,p,"","paper");if("paper"!==m?(f=Pa.getFromId(y,m),h=kd.rangeToShapePosition(f),d=kd.shapePositionToRange(f)):d=h=rt.identity,"path"!==o){var x=p+"0",b=p+"1",_=e[x],w=e[b];e[x]=d(e[x],!0),e[b]=d(e[b],!0),"pixel"===v?(i(x,0),i(b,10)):(Pa.coercePosition(t,y,i,m,x,.25),Pa.coercePosition(t,y,i,m,b,.75)),t[x]=h(t[x]),t[b]=h(t[b]),e[x]=_,e[b]=w}if("pixel"===v){var k=e[g];e[g]=d(e[g],!0),Pa.coercePosition(t,y,i,m,g,.25),t[g]=h(t[g]),e[g]=k}}return"path"===o?i("path"):rt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},Sd={draw:function(e){var t=e._fullLayout;for(var n in t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._plots){var r=t._plots[n].shapelayer;r&&r.selectAll("path").remove()}for(var a=0;as?(y=o,_=D+".y0",T="y0",m=s,w=D+".y1",A="y1"):(y=s,_=D+".y1",T="y1",m=o,w=D+".y0",A="y0");a={},U(t),V.moveFn="move"===F?G:Y},doneFn:function(){hr(t),D.call("relayout",e,a)}};function U(e){var n=V.element.getBoundingClientRect(),r=n.right-n.left,a=n.bottom-n.top,i=e.clientX-n.left,o=e.clientY-n.top,l=r>B&&a>j&&!e.shiftKey?zt.getCursor(i/r,1-o/a):"move";hr(t,l),F=l.split("-")[0]}function G(r,y){if("path"===n.type){var m=function(e){return e},x=m,b=m;H?a[g]=n.xanchor=N(c+r):(x=function(e){return N(E(e)+r)},O&&"date"===O.type&&(x=kd.encodeDate(x))),q?a[v]=n.yanchor=R(u+y):(b=function(e){return R(I(e)+y)},P&&"date"===P.type&&(b=kd.encodeDate(b))),n.path=Pd(S,x,b),a[z]=n.path}else H?a[g]=n.xanchor=N(c+r):(a[f]=n.x0=N(i+r),a[h]=n.x1=N(l+r)),q?a[v]=n.yanchor=R(u+y):(a[d]=n.y0=R(o+y),a[p]=n.y1=R(s+y));t.attr("d",Od(e,n))}function Y(r,i){if("path"===n.type){var o=function(e){return e},l=o,s=o;H?a[g]=n.xanchor=N(c+r):(l=function(e){return N(E(e)+r)},O&&"date"===O.type&&(l=kd.encodeDate(l))),q?a[v]=n.yanchor=R(u+i):(s=function(e){return R(I(e)+i)},P&&"date"===P.type&&(s=kd.encodeDate(s))),n.path=Pd(S,l,s),a[z]=n.path}else{var f=~F.indexOf("n")?y+i:y,d=~F.indexOf("s")?m+i:m,h=~F.indexOf("w")?x+r:x,p=~F.indexOf("e")?b+r:b;~F.indexOf("n")&&q&&(f=y-i),~F.indexOf("s")&&q&&(d=m-i),(!q&&d-f>j||q&&f-d>j)&&(a[_]=n[T]=q?f:R(f),a[w]=n[A]=q?d:R(d)),p-h>B&&(a[k]=n[L]=H?h:N(h),a[M]=n[C]=H?p:N(p))}t.attr("d",Od(e,n))}zt.init(V),t.node().onmousemove=U}(e,o,r,t)}}function Od(e,t){var n,r,a,i,o,l,s,c,u=t.type,f=Pa.getFromId(e,t.xref),d=Pa.getFromId(e,t.yref),h=e._fullLayout._size;if(f?(n=kd.shapePositionToRange(f),r=function(e){return f._offset+f.r2p(n(e,!0))}):r=function(e){return h.l+h.w*e},d?(a=kd.shapePositionToRange(d),i=function(e){return d._offset+d.r2p(a(e,!0))}):i=function(e){return h.t+h.h*(1-e)},"path"===u)return f&&"date"===f.type&&(r=kd.decodeDate(r)),d&&"date"===d.type&&(i=kd.decodeDate(i)),function(e,t,n){var r=e.path,a=e.xsizemode,i=e.ysizemode,o=e.xanchor,l=e.yanchor;return r.replace(wd.segmentRE,function(e){var r=0,s=e.charAt(0),c=wd.paramIsX[s],u=wd.paramIsY[s],f=wd.numParams[s],d=e.substr(1).replace(wd.paramRE,function(e){return c[r]?e="pixel"===a?t(o)+Number(e):t(e):u[r]&&(e="pixel"===i?n(l)-Number(e):n(e)),++r>f&&(e="X"),e});return r>f&&(d=d.replace(/[\s,]*X.*/,""),rt.log("Ignoring extra params in segment "+e)),s+d})}(t,r,i);if("pixel"===t.xsizemode){var p=r(t.xanchor);o=p+t.x0,l=p+t.x1}else o=r(t.x0),l=r(t.x1);if("pixel"===t.ysizemode){var g=i(t.yanchor);s=g-t.y0,c=g-t.y1}else s=i(t.y0),c=i(t.y1);if("line"===u)return"M"+o+","+s+"L"+l+","+c;if("rect"===u)return"M"+o+","+s+"H"+l+"V"+c+"H"+o+"Z";var v=(o+l)/2,y=(s+c)/2,m=Math.abs(v-o),x=Math.abs(y-s),b="A"+m+","+x,_=v+m+","+y;return"M"+_+b+" 0 1,1 "+(v+","+(y-x))+b+" 0 0,1 "+_+"Z"}function Pd(e,t,n){return e.replace(wd.segmentRE,function(e){var r=0,a=e.charAt(0),i=wd.paramIsX[a],o=wd.paramIsY[a],l=wd.numParams[a];return a+e.substr(1).replace(wd.paramRE,function(e){return r>=l?e:(i[r]?e=t(e):o[r]&&(e=n(e)),r++,e)})})}var Dd={moduleType:"component",name:"shapes",layoutAttributes:_d,supplyLayoutDefaults:function(e,t){Wu(e,t,{name:"shapes",handleItemDefaults:Cd})},includeBasePlot:Qu("shapes"),calcAutorange:function(e){var t=e._fullLayout,n=rt.filterVisible(t.shapes);if(n.length&&e._fullData.length)for(var r=0;r0)&&(r("active"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("len"),r("lenmode"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("currentvalue.visible")&&(r("currentvalue.xanchor"),r("currentvalue.prefix"),r("currentvalue.suffix"),r("currentvalue.offset"),rt.coerceFont(r,"currentvalue.font",t.font)),r("transition.duration"),r("transition.easing"),r("bgcolor"),r("activebgcolor"),r("bordercolor"),r("borderwidth"),r("ticklen"),r("tickwidth"),r("tickcolor"),r("minorticklen"))}var Hd=vn.LINE_SPACING,qd=vn.FROM_TL,Vd=vn.FROM_BR;function Ud(e){return e._index}function Gd(t,n){var r=Un.tester.selectAll("g."+Ed.labelGroupClass).data(n.steps);r.enter().append("g").classed(Ed.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=Xd(e.select(this),{step:t},n).node();if(r){var o=Un.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=n._dims={};o.inputAreaWidth=Math.max(Ed.railWidth,Ed.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*n.x,o.ly=l.t+l.h*(1-n.y),"fraction"===n.lenmode?o.outerLength=Math.round(l.w*n.len):o.outerLength=n.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-n.pad.l-n.pad.r);var s=(o.inputAreaLength-2*Ed.stepInset)/(n.steps.length-1),c=a+Ed.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,n.currentvalue.visible){var u=Un.tester.append("g");r.each(function(e){var t=Yd(u,n,e.label),r=t.node()&&Un.bBox(t.node())||{width:0,height:0},a=mn.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(r.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(r.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+n.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+Ed.tickOffset+n.ticklen+Ed.labelOffset+o.labelHeight+n.pad.t+n.pad.b;var f="left";Of.isRightAnchor(n)&&(o.lx-=o.outerLength,f="right"),Of.isCenterAnchor(n)&&(o.lx-=o.outerLength/2,f="center");var d="top";Of.isBottomAnchor(n)&&(o.ly-=o.height,d="bottom"),Of.isMiddleAnchor(n)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Qr.autoMargin(t,Ed.autoMarginIdRoot+n._index,{x:n.x,y:n.y,l:o.outerLength*qd[f],r:o.outerLength*Vd[f],b:o.height*Vd[d],t:o.height*qd[d]})}function Yd(e,t,n){if(t.currentvalue.visible){var r,a,i=t._dims;switch(t.currentvalue.xanchor){case"right":r=i.inputAreaLength-Ed.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":r=.5*i.inputAreaLength,a="middle";break;default:r=Ed.currentValueInset,a="left"}var o=rt.ensureSingle(e,"text",Ed.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof n)l+=n;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),o.call(Un.font,t.currentvalue.font).text(l).call(mn.convertToTspans,t._gd);var s=mn.lineCount(o),c=(i.currentValueMaxLines+1-s)*t.currentvalue.font.size*Hd;return mn.positionText(o,r,c),o}}function Zd(e,t,n){rt.ensureSingle(e,"rect",Ed.gripRectClass,function(r){r.call($d,t,e,n).style("pointer-events","all")}).attr({width:Ed.gripWidth,height:Ed.gripHeight,rx:Ed.gripRadius,ry:Ed.gripRadius}).call(It.stroke,n.bordercolor).call(It.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px")}function Xd(e,t,n){var r=rt.ensureSingle(e,"text",Ed.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return r.call(Un.font,n.font).text(t.step.label).call(mn.convertToTspans,n._gd),r}function Wd(t,n){var r=rt.ensureSingle(t,"g",Ed.labelsClass),a=n._dims,i=r.selectAll("g."+Ed.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(Ed.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=e.select(this);r.call(Xd,t,n),Un.setTranslate(r,th(n,t.fraction),Ed.tickOffset+n.ticklen+n.font.size*Hd+Ed.labelOffset+a.currentValueTotalHeight)})}function Qd(e,t,n,r,a){var i=Math.round(r*(n.steps.length-1));i!==n.active&&Jd(e,t,n,i,!0,a)}function Jd(e,t,n,r,a,i){var o=n.active;n._input.active=n.active=r;var l=n.steps[n.active];t.call(eh,n,n.active/(n.steps.length-1),i),t.call(Yd,n),e.emit("plotly_sliderchange",{slider:n,step:n.steps[n.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var n=t._nextMethod.step;n.method&&(n.execute&&Qr.executeAPICommand(e,n.method,n.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function $d(t,n,r){var a=r.node(),i=e.select(n);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();n.emit("plotly_sliderstart",{slider:t});var l=r.select("."+Ed.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(It.fill,t.activebgcolor);var s=nh(t,e.mouse(a)[0]);Qd(n,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=nh(t,e.mouse(a)[0]);Qd(n,r,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(It.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),n.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function Kd(t,n){var r=t.selectAll("rect."+Ed.tickRectClass).data(n.steps),a=n._dims;r.enter().append("rect").classed(Ed.tickRectClass,!0),r.exit().remove(),r.attr({width:n.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=e.select(this);o.attr({height:i?n.ticklen:n.minorticklen}).call(It.fill,n.tickcolor),Un.setTranslate(o,th(n,r/(n.steps.length-1))-.5*n.tickwidth,(i?Ed.tickOffset:Ed.minorTickOffset)+a.currentValueTotalHeight)})}function eh(e,t,n,r){var a=e.select("rect."+Ed.gripRectClass),i=th(t,n);if(!t._invokingCommand){var o=a;r&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*Ed.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function th(e,t){var n=e._dims;return n.inputAreaStart+Ed.stepInset+(n.inputAreaLength-2*Ed.stepInset)*Math.min(1,Math.max(0,t))}function nh(e,t){var n=e._dims;return Math.min(1,Math.max(0,(t-Ed.stepInset-n.inputAreaStart)/(n.inputAreaLength-2*Ed.stepInset-2*n.inputAreaStart)))}function rh(e,t,n){var r=n._dims,a=rt.ensureSingle(e,"rect",Ed.railTouchRectClass,function(r){r.call($d,t,e,n).style("pointer-events","all")});a.attr({width:r.inputAreaLength,height:Math.max(r.inputAreaWidth,Ed.tickOffset+n.ticklen+r.labelHeight)}).call(It.fill,n.bgcolor).attr("opacity",0),Un.setTranslate(a,0,r.currentValueTotalHeight)}function ah(e,t){var n=t._dims,r=n.inputAreaLength-2*Ed.railInset,a=rt.ensureSingle(e,"rect",Ed.railRectClass);a.attr({width:r,height:Ed.railWidth,rx:Ed.railRadius,ry:Ed.railRadius,"shape-rendering":"crispEdges"}).call(It.stroke,t.bordercolor).call(It.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Un.setTranslate(a,Ed.railInset,.5*(n.inputAreaWidth-Ed.railWidth)+n.currentValueTotalHeight)}var ih={moduleType:"component",name:Ed.name,layoutAttributes:Rd,supplyLayoutDefaults:function(e,t){Wu(e,t,{name:Fd,handleItemDefaults:jd})},draw:function(t){var n=t._fullLayout,r=function(e,t){for(var n=e[Ed.name],r=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(Ed.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r=n.steps.length&&(n.active=0),t.call(Yd,n).call(ah,n).call(Wd,n).call(Kd,n).call(rh,e,n).call(Zd,e,n);var r=n._dims;Un.setTranslate(t,r.lx+n.pad.l,r.ly+n.pad.t),t.call(eh,n,n.active/(n.steps.length-1),!1),t.call(Yd,n)}(t,e.select(this),n)}})}}},oh=m.extendFlat,lh=(0,Wt.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:oh({},Id,{}),font:L({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:z.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),sh={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},ch=sh.name,uh=lh.buttons;function fh(e,t,n){function r(n,r){return rt.coerce(e,t,lh,n,r)}r("visible",function(e,t){var n,r,a=e.buttons||[],i=t.buttons=[];function o(e,t){return rt.coerce(n,r,uh,e,t)}for(var l=0;l0)&&(r("active"),r("direction"),r("type"),r("showactive"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("bgcolor",n.paper_bgcolor),r("bordercolor"),r("borderwidth"))}var dh=hh;function hh(e,t,n){this.gd=e,this.container=t,this.id=n,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}hh.barWidth=2,hh.barLength=20,hh.barRadius=2,hh.barPad=1,hh.barColor="#808BA4",hh.prototype.enable=function(t,n,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=hh.barLength+2*hh.barPad,k=hh.barWidth+2*hh.barPad,M=f,T=h+p;T+k>o&&(T=o-k);var A=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);A.exit().on(".drag",null).remove(),A.enter().append("rect").classed("scrollbar-horizontal",!0).call(It.fill,hh.barColor),_?(this.hbar=A.attr({rx:hh.barRadius,ry:hh.barRadius,x:M,y:T,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=hh.barWidth+2*hh.barPad,S=hh.barLength+2*hh.barPad,z=f+d,O=h;z+C>i&&(z=i-C);var P=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);P.exit().on(".drag",null).remove(),P.enter().append("rect").classed("scrollbar-vertical",!0).call(It.fill,hh.barColor),L?(this.vbar=P.attr({rx:hh.barRadius,ry:hh.barRadius,x:z,y:O,width:C,height:S}),this._vbarYMin=O+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,I=L?s+C+.5:s+.5,N=c-.5,R=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(N),width:Math.ceil(I)-Math.floor(E),height:Math.ceil(R)-Math.floor(N)}),this.container.call(Un.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Un.setClipUrl,null),delete this._clipRect),_||L){var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(B);var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),L&&this.vbar.on(".drag",null).call(j)}this.setTranslate(n,r)},hh.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Un.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},hh.prototype._onBoxDrag=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(n-=e.event.dy),this.setTranslate(t,n)},hh.prototype._onBoxWheel=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(n+=e.event.deltaY),this.setTranslate(t,n)},hh.prototype._onBarDrag=function(){var t=this.translateX,n=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(rt.constrain(e.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=n+this._vbarYMin,o=i+this._vbarTranslateMax;n=(rt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,n)},hh.prototype.setTranslate=function(e,t){var n=this.position.w-this._box.w,r=this.position.h-this._box.h;if(e=rt.constrain(e||0,0,n),t=rt.constrain(t||0,0,r),this.translateX=e,this.translateY=t,this.container.call(Un.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/n;this.hbar.call(Un.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/r;this.vbar.call(Un.setTranslate,e,t+i*this._vbarTranslateMax)}};var ph=vn.LINE_SPACING;function gh(e){return e._index}function vh(e,t){return+e.attr(sh.menuIndexAttrName)===t._index}function yh(e,t,n,r,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?xh(e,r,null,null,t):"dropdown"===t.type&&(a.attr(sh.menuIndexAttrName,"-1"),mh(e,r,a,i,t),l||xh(e,r,a,i,t))}function mh(e,t,n,r,a){var i=rt.ensureSingle(t,"g",sh.headerClassName,function(e){e.style("pointer-events","all")}),o=a._dims,l=a.active,s=a.buttons[l]||sh.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(bh,a,s,e).call(Lh,a,c,u),rt.ensureSingle(t,"text",sh.headerArrowClassName,function(e){e.classed("user-select-none",!0).attr("text-anchor","end").call(Un.font,a.font).text(sh.arrowSymbol[a.direction])}).attr({x:o.headerWidth-sh.arrowOffsetX+a.pad.l,y:o.headerHeight/2+sh.textOffsetY+a.pad.t}),i.on("click",function(){n.call(Ch),n.attr(sh.menuIndexAttrName,vh(n,a)?-1:String(a._index)),xh(e,t,n,r,a)}),i.on("mouseover",function(){i.call(Mh)}),i.on("mouseout",function(){i.call(Th,a)}),Un.setTranslate(t,o.lx,o.ly)}function xh(t,n,r,a,i){r||(r=n).attr("pointer-events","all");var o=function(e){return-1==+e.attr(sh.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?sh.dropdownButtonClassName:sh.buttonClassName,s=r.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+sh.gapButtonHeader:f=h.headerWidth+sh.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-sh.gapButtonHeader+sh.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-sh.gapButtonHeader+sh.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:sh.gapButton,xPad:sh.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(bh,i,o,t).call(Lh,i,g),c.on("click",function(){e.event.defaultPrevented||(yh(t,i,0,n,r,a,l),o.execute&&Qr.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(Mh)}),c.on("mouseout",function(){c.call(Th,i),s.call(kh,i)})}),s.call(kh,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,n,r,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(sh.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r_.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,n;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n0&&rt.log("Clearing previous rejected promises from queue."),e._promises=[]},Eh.cleanLayout=function(e){var t,n;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var r=(Qr.subplotsRegistry.cartesian||{}).attrRegex,a=(Qr.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),It.clean(e),e},Eh.cleanData=function(e,t){for(var n=[],r=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}Eh.hasParent=function(e,t){for(var n=Vh(t);n;){if(n in e)return!0;n=Vh(n)}return!1};var Uh=["x","y","z"];Eh.clearAxisTypes=function(e,t,n){for(var r=0;r1&&w.warn("Full array edits are incompatible with other edits",a);var f=n[""][""];if(Xh(f))t.set(null);else{if(!Array.isArray(f))return w.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(n).map(Number).sort(Yh),b=t.get(),_=b||[],k=Z(u,a).get(),M=[],A=-1,L=_.length;for(d=0;d_.length-(m?0:1))w.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&w.warn("Insertion & removal are incompatible with edits to the same index.",a,p),Xh(y)?M.push(p):m?("add"===y&&(y={}),_.splice(p,0,y),k&&k.splice(p,0,{})):w.warn("Unrecognized full object edit value",a,p,y),-1===A&&(A=p);else for(h=0;h=0;d--)_.splice(M[d],1),k&&k.splice(M[d],1);if(_.length?b||t.set(_):t.set(null),s)return!1;if(i(c,u),l!==T){var C;if(-1===A)C=x;else{for(L=Math.max(_.length,L),C=[],d=0;d=A);d++)C.push(p);for(d=A;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,n=0;ndp*h)||y)for(n=0;nL&&zT&&(T=z);l/=(T-M)/(2*A),M=a.l2r(M),T=a.l2r(T),a.range=a._input.range=_=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(n,a,h)){var o=i.node(),l=t.bg=rt.ensureSingle(i,"rect","bg");o.insertBefore(l.node(),o.childNodes[0])}else i.select("rect.bg").remove(),d.push(e),h.push([n,a])});var p=r._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=e.select(this)}),f.each(function(e){var t=r._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Un.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(It.fill,r.plot_bgcolor).style("stroke-width",0);var u,f,d=t.clipId="clip"+r._uid+e+"plot",h=rt.ensureSingleById(r._clips,"clipPath",d,function(e){e.classed("plotclip",!0).append("rect")});for(t.clipRect=h.select("rect").attr({width:a._length,height:c._length}),Un.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=d):(u=d,f=null),Un.setClipUrl(t.plot,u),n=0;n=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var T=k.slice();w&&b&&(T[1]+=M);var A=c.angularAxis.ticksCount||4;A>8&&(A=A/(A/8)+A%8),c.angularAxis.ticksStep&&(A=(T[1]-T[0])/A);var L=c.angularAxis.ticksStep||(T[1]-T[0])/(A*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),T[2]||(T[2]=L);var C=e.range.apply(this,T);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(T.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),z=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(z)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var O,P=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){O=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var I=u.map(function(e,t){var n=Tp.util.cloneJson(e);return n.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",n.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,n.color="LinePlot"===e.geometry?e.strokeColor:e.color,n});Tp.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:kp({},Tp.Legend.defaultConfig().legendConfig,{container:O,elements:I,reverseOrder:c.legend.reverseOrder})})();var N=O.node().getBBox();g=Math.min(c.width-N.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),O.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else O=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),P.attr("transform","translate("+y+")").style({cursor:"crosshair"});var R=[(c.width-(c.margin.left+c.margin.right+2*g+(N?N.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(R[0]=Math.max(0,R[0]),R[1]=Math.max(0,R[1]),t.select(".outer-group").attr("transform","translate("+R+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),B=F.node().getBBox();F.attr({x:y[0]-B.width/2,y:y[1]-g-20})}var j=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var H=j.selectAll("circle.grid-circle").data(r.ticks(5));H.enter().append("circle").attr({class:"grid-circle"}).style(D),H.attr("r",r),H.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(D);var q=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(r).ticks(5).tickSize(5);j.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),j.selectAll(".domain").style(D),j.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var Z=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:Mp+"em",transform:function(e,t){var n=V(e),r=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-n+" "+r+" 0)":"radial"==a?n<270&&n>90?"rotate(180 "+r+" 0)":null:"rotate("+(n<=180&&n>0?-90:90)+" "+r+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&Z.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var X=e.max(P.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));O.attr({transform:"translate("+[g+X,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,Q=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(Q.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),Q.exit().remove(),u[0]||W){var J=[];u.forEach(function(e,t){var n={};n.radialScale=r,n.angularScale=a,n.container=Q.filter(function(e,n){return n==t}),n.geometry=e.geometry,n.orientation=c.orientation,n.direction=c.direction,n.index=t,J.push({data:e,geometryConfig:n})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(J).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var n;n=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var r=e.map(function(e,t){return kp(Tp[n].defaultConfig(),e)});Tp[n]().config(r)()})}var K,ee,te=t.select(".guides-group"),ne=t.select(".tooltips-group"),re=Tp.tooltipPanel().config({container:ne,fontSize:8})(),ae=Tp.tooltipPanel().config({container:ne,fontSize:8})(),ie=Tp.tooltipPanel().config({container:ne,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});P.on("mousemove.angular-guide",function(e,t){var n=Tp.util.getMousePos(q).angle;oe.attr({x2:-g,transform:"rotate("+n+")"}).style({opacity:.5});var r=(n+180+360-c.orientation)%360;K=a.invert(r);var i=Tp.util.convertToCartesian(g+12,n+180);re.text(Tp.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});P.on("mousemove.radial-guide",function(e,t){var n=Tp.util.getMousePos(q).radius;le.attr({r:n}).style({opacity:.5}),ee=r.invert(Tp.util.getMousePos(q).radius);var a=Tp.util.convertToCartesian(n,c.radialAxis.orientation);ae.text(Tp.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),re.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(n,r){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:Tp.util.round(n[0]),r:Tp.util.round(n[1])};b&&(s.t=m[n[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-R[0]-f.left,u.top+u.height/2-R[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,n){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,n){ie.hide();var r=e.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=Tp.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),kp(i.data[t],Tp.Axis.defaultConfig().data[0]),kp(i.data[t],e)}),kp(i.layout,Tp.Axis.defaultConfig().layout),kp(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return r},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},Tp.Axis.defaultConfig=function(t,n){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Tp.util={},Tp.DATAEXTENT="dataExtent",Tp.AREA="AreaChart",Tp.LINE="LinePlot",Tp.DOT="DotPlot",Tp.BAR="BarChart",Tp.util._override=function(e,t){for(var n in e)n in t&&(t[n]=e[n])},Tp.util._extend=function(e,t){for(var n in e)t[n]=e[n]},Tp.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Tp.util.dataFromEquation2=function(t,n){var r=n||6;return e.range(0,360+r,r).map(function(e,n){var r=e*Math.PI/180;return[e,t(r)]})},Tp.util.dataFromEquation=function(t,n,r){var a=n||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,n){var r=e*Math.PI/180,a=t(r);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},Tp.util.ensureArray=function(t,n){if(void 0===t)return null;var r=[].concat(t);return e.range(n).map(function(e,t){return r[t]||r[0]})},Tp.util.fillArrays=function(e,t,n){return t.forEach(function(t,r){e[t]=Tp.util.ensureArray(e[t],n)}),e},Tp.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},Tp.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var n=t.shift();return e[n]&&(!t.length||objHasKeys(e[n],t))},Tp.util.sumArrays=function(t,n){return e.zip(t,n).map(function(t,n){return e.sum(t)})},Tp.util.arrayLast=function(e){return e[e.length-1]},Tp.util.arrayEqual=function(e,t){for(var n=Math.max(e.length,t.length,1);n-- >=0&&e[n]===t[n];);return-2===n},Tp.util.flattenArray=function(e){for(var t=[];!Tp.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},Tp.util.deduplicate=function(e){return e.filter(function(e,t,n){return n.indexOf(e)==t})},Tp.util.convertToCartesian=function(e,t){var n=t*Math.PI/180;return[e*Math.cos(n),e*Math.sin(n)]},Tp.util.round=function(e,t){var n=t||2,r=Math.pow(10,n);return Math.round(e*r)/r},Tp.util.getMousePos=function(t){var n=e.mouse(t.node()),r=n[0],a=n[1],i={};return i.x=r,i.y=a,i.pos=n,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},Tp.util.duplicatesCount=function(e){for(var t,n={},r={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(n.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(r,a,i)},"stroke-width":function(e,t){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](r,a,i)},opacity:function(e,t){return p.opacity(r,a,i)},display:function(e,t){return p.display(r,a,i)}})}};var f=n.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return n.radialScale(s+(e[2]||0))}).outerRadius(function(e){return n.radialScale(s+(e[2]||0))+n.radialScale(e[1])});c.arc=function(t,r,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(n.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,n,r){return t[r].data.color},stroke:function(e,n,r){return t[r].data.strokeColor},"stroke-width":function(e,n,r){return t[r].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,n,r){return t[r].data.opacity},display:function(e,n,r){return void 0===t[r].data.visible||t[r].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[n.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,n){t[n]||(t[n]={}),kp(t[n],Tp.PolyChart.defaultConfig()),kp(t[n],e)}),this):t},a.getColorScale=function(){},e.rebind(a,n,"on"),a},Tp.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},Tp.BarChart=function(){return Tp.PolyChart()},Tp.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Tp.AreaChart=function(){return Tp.PolyChart()},Tp.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Tp.DotPlot=function(){return Tp.PolyChart()},Tp.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Tp.LinePlot=function(){return Tp.PolyChart()},Tp.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Tp.Legend=function(){var t=Tp.Legend.defaultConfig(),n=e.dispatch("hover");function r(){var n=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,r){var a=kp({},n.elements[t]);return a.name=e,a.color=[].concat(n.elements[t].color)[r],a})}),i=e.merge(a);i=i.filter(function(e,t){return n.elements[t]&&(n.elements[t].visibleInLegend||void 0===n.elements[t].visibleInLegend)}),n.reverseOrder&&(i=i.reverse());var o=n.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=n.fontSize,c=null==n.isContinuous?"number"==typeof i[0]:n.isContinuous,u=c?n.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:n.height,width:n.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,n){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(r)?e.svg.symbol().type(r).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?n.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?n.textColor:"none"}),x.selectAll("text").style({fill:n.textColor,"font-size":n.fontSize}).text(function(e,t){return i[t].name}),r}return r.config=function(e){return arguments.length?(kp(t,e),this):t},e.rebind(r,n,"on"),r},Tp.Legend.defaultConfig=function(e,t){return{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:!1}}},Tp.tooltipPanel=function(){var t,n,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+Tp.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),n=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";n.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=n.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return kp(a,e),l},l},Tp.tooltipPanel.uid=1,Tp.adapter={},Tp.adapter.plotly=function(){var t={convert:function(t,n){var r={};if(t.data&&(r.data=t.data.map(function(e,t){var r=kp({},e);return[[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"]]].forEach(function(e,t){Tp.util.translator.apply(null,e.concat(n))}),n||delete r.marker,n&&delete r.groupId,n?("LinePlot"===r.geometry?(r.type="scatter",!0===r.dotVisible?(delete r.dotVisible,r.mode="lines+markers"):r.mode="lines"):"DotPlot"===r.geometry?(r.type="scatter",r.mode="markers"):"AreaChart"===r.geometry?r.type="area":"BarChart"===r.geometry&&(r.type="bar"),delete r.geometry):("scatter"===r.type?"lines"===r.mode?r.geometry="LinePlot":"markers"===r.mode?r.geometry="DotPlot":"lines+markers"===r.mode&&(r.geometry="LinePlot",r.dotVisible=!0):"area"===r.type?r.geometry="AreaChart":"bar"===r.type&&(r.geometry="BarChart"),delete r.mode,delete r.type),r}),!n&&t.layout&&"stack"===t.layout.barmode)){var a=Tp.util.duplicates(r.data.map(function(e,t){return e.geometry}));r.data.forEach(function(e,t){var n=a.indexOf(e.geometry);-1!=n&&(r.data[t].groupId=n)})}if(t.layout){var i=kp({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){Tp.util.translator.apply(null,e.concat(n))}),n?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}n&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var Ap,Lp=rt.extendDeepAll,Cp=Ap={};Cp.framework=function(t){var n,r,a,i,o,l=new function(){var e,t=[],n=-1,r=!1;function a(e,t){return e?(r=!0,e[t](),r=!1,this):this}return{add:function(e){return r?this:(t.splice(n+1,t.length-n),t.push(e),n=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var r=t[n];return r?(a(r,"undo"),n-=1,e&&e(r.undo),this):this},redo:function(){var r=t[n+1];return r?(a(r,"redo"),n+=1,e&&e(r.redo),this):this},clear:function(){t=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n*:not(.chart-root)").remove(),n=n?Lp(n,r):r,a||(a=wp.Axis()),i=wp.adapter.plotly().convert(n),a.config(i).render(o),t.data=n.data,t.layout=n.layout,Cp.fillLayout(t),n}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return n},s.getLiveConfig=function(){return wp.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=wp.util.cloneJson(n);e=i,t=r,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),r=wp.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},Cp.fillLayout=function(t){var n=e.select(t).selectAll(".plot-container"),r=n.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:It.background,_container:n,_paperdiv:r,_paper:a};t._fullLayout=Lp(i,t.layout)};var Sp={};(Sp=wp).manager=Ap;var zp={},Op=Po.initInteractions,Pp=ht.AX_NAME_PATTERN,Dp=0;function Ep(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){rt.error(e)}}function Ip(e,t){Ep(e,It.combine(t,"white"))}function Np(e,t){e._context||(e._context=rt.extendDeep({},_));var n,r,a,i=e._context;if(t){for(r=Object.keys(t),n=0;n=e.data.length||a<-e.data.length)throw new Error(n+" must be valid indices for gd.data.");if(t.indexOf(a,r+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+n+" must be unique.")}}function Bp(e,t,n){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),Fp(e,t,"currentIndices"),void 0===n||Array.isArray(n)||(n=[n]),void 0!==n&&Fp(e,n,"newIndices"),void 0!==n&&t.length!==n.length)throw new Error("current and new indices must be of equal length.")}function jp(e,t,r,a,i){!function(e,t,n,r){var a=rt.isPlainObject(r);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!rt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===n)throw new Error("indices must be an integer or array of integers");for(var i in Fp(e,n,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==n.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in r)||!Array.isArray(r[i])||r[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,t,r,a);for(var o=function(e,t,r,a){var i,o,l,s,c,u=rt.isPlainObject(a),f=[];for(var d in Array.isArray(r)||(r=[r]),r=Rp(r,e.data.length-1),t)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var T=_.parts[M],A=_.parts[M-1]+"."+T,L=_.parts.slice(0,M).join("."),C=rt.nestedProperty(e.layout,L).get(),S=rt.nestedProperty(o,L).get(),z=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===T?w:qp(z);var O=Or.getLayoutValObject(o,_.parts);if(O&&O.impliedEdits&&null!==w)for(var P in O.impliedEdits)v(rt.relativeAttr(b,P),O.impliedEdits[P]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(A.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(A),rt.nestedProperty(o,L+"._inputRange").set(null);else if(A.match(/^[xyz]axis[0-9]*\.autorange$/)){x(A),rt.nestedProperty(o,L+"._inputRange").set(null);var E=rt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else A.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&rt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===T){var I=C,N="linear"===S.type&&"log"===w,R="log"===S.type&&"linear"===w;if(N||R){if(I&&I.range)if(S.autorange)N&&(I.range=I.range[1]>I.range[0]?[1,2]:[2,1]);else{var F=I.range[0],B=I.range[1];N?(F<=0&&B<=0&&v(L+".autorange",!0),F<=0?F=B/1e6:B<=0&&(B=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(B)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,B)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],D.getComponentMethod("annotations","convertCoords")(e,S,w,v),D.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);rt.nestedProperty(o,L+"._inputRange").set(null)}else if(T.match(Pp)){var j=rt.nestedProperty(o,b).get(),H=(w||{}).type;H&&"-"!==H||(H="linear"),D.getComponentMethod("annotations","convertCoords")(e,j,H,v),D.getComponentMethod("images","convertCoords")(e,j,H,v)}var q=Gh.containerArrayMatch(b);if(q){n=q.array,r=q.index;var V=q.property,U=(rt.nestedProperty(i,n)||[])[r]||{},G=U,Y=O||{editType:"calc"},Z=-1!==Y.editType.indexOf("calcIfAutorange");""===r?(Z?h.calc=!0:Wt.update(h,Y),Z=!1):""===V&&(G=w,Gh.isAddVal(w)?g[b]=null:Gh.isRemoveVal(w)?(g[b]=U,G=U):rt.warn("unrecognized full object value",t)),Z&&(Yp(e,G,"x")||Yp(e,G,"y"))?h.calc=!0:Wt.update(h,Y),c[n]||(c[n]={});var X=c[n][r];X||(X=c[n][r]={}),X[V]=w,delete t[b]}else"reverse"===T?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==z&&"select"!==z?h.plot=!0:O?Wt.update(h,O):h.calc=!0,_.set(w))}}for(n in c){Gh.applyContainerArrayChanges(e,rt.nestedProperty(i,n),c[n],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(r=0;r=0&&n=0&&n=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var n=0;return function(){if(e&&++n===t)return e()}}return void 0===r._frameWaitingCnt&&(r._frameWaitingCnt=0),new Promise(function(i,c){function u(){r._currentFrame&&r._currentFrame.onComplete&&r._currentFrame.onComplete();var t=r._currentFrame=r._frameQueue.shift();if(t){var n=t.name?t.name.toString():null;e._fullLayout._currentFrame=n,r._lastFrameAt=Date.now(),r._timeToNext=t.frameOpts.duration,Qr.transition(e,t.frame.data,t.frame.layout,Eh.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:n,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(r._animationRaf),r._animationRaf=null}function f(){e.emit("plotly_animating"),r._lastFrameAt=-1/0,r._timeToNext=0,r._runningTransitions=0,r._currentFrame=null;var t=function(){r._animationRaf=window.requestAnimationFrame(t),Date.now()-r._lastFrameAt>r._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&rt.isPlainObject(t))v.push({type:"object",data:g(rt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;r--)if(rt.isPlainObject(t[r])){var d=t[r].name,h=(s[d]||f[d]||{}).name,p=t[r].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&Dp<5&&(Dp++,rt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===Dp&&rt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:Qr.supplyFrameDefaults(t[r]),index:n&&void 0!==n[r]&&null!==n[r]?n[r]:c+r})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;r--){if("number"==typeof(a=u[r].frame).name&&rt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;n--)r=t[n],i.push({type:"delete",index:r}),o.unshift({type:"insert",index:r,value:a[r]});var l=Qr.modifyFrames,s=Qr.modifyFrames,c=[e,o],u=[e,i];return Ph&&Ph.add(e,l,c,s,u),Qr.modifyFrames(e,i)},zp.purge=function(e){var t=(e=rt.getGraphDiv(e))._fullLayout||{},n=e._fullData||[],r=e.calcdata||[];return Qr.cleanPlot([],{},n,t,r),Qr.purge(e),Ct.purge(e),t._container&&t._container.remove(),delete e._context,e};var Wp={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},Qp=wt.EventEmitter;var Jp=function(e){var t=e.emitter||new Qp,n=new Promise(function(r,a){var i=window.Image,o=e.svg,l=e.format||"png";if(rt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?n:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var n;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":n=c.toDataURL("image/jpeg");break;case"png":n=c.toDataURL("image/png");break;case"webp":n=c.toDataURL("image/webp");break;case"svg":n=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}r(n),e.promise||t.emit("success",n)},p.onerror=function(n){if(a(n),!e.promise)return t.emit("error",n)},p.src=g});return e.promise?n:t},$p=/"/g,Kp=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var eg=function(n,r,a){var i,o=n._fullLayout,l=o._paper,s=o._toppaper,c=o.width,u=o.height;l.insert("rect",":first-child").call(Un.setRect,0,0,c,u).call(It.fill,o.paper_bgcolor);var f=o._basePlotModules||[];for(i=0;i")?"":n.html(e).text()});return n.remove(),r}(v),v=(v=v.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(Kp,"'"),rt.isIE()&&(v=(v=(v=v.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),v},tg={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},ng=/^data:image\/\w+;base64,/;var rg=function(e,t){var n,r,a;function i(e){return!(e in t)||rt.validate(t[e],tg[e])}if(t=t||{},rt.isPlainObject(e)?(n=e.data||[],r=e.layout||{},a=e.config||{}):(e=rt.getGraphDiv(e),n=rt.extendDeep([],e.data),r=rt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,n){return rt.coerce(t,o,tg,e,n)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=rt.extendFlat({},r);c&&(g.width=c),u&&(g.height=u);var v=rt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=Wp.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,Wp.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var n=eg(p,s,f),r=p._fullLayout.width,a=p._fullLayout.height;if(zp.purge(p),document.body.removeChild(p),"svg"===s)return e(h?n:"data:image/svg+xml,"+encodeURIComponent(n));var i=document.createElement("canvas");i.id=rt.randstr(),Jp({format:s,width:r,height:a,scale:f,canvas:i,svg:n,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){zp.plot(p,n,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(ng,""):e}(t))}).catch(function(e){t(e)})})},ag=rt.isPlainObject,ig=Array.isArray,og=rt.isArrayOrTypedArray;function lg(e,t,n,r,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&r.push(ug("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(ig(u[y])){u[y].length>f[y].length&&r.push(ug("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],rt.validate(x,m)?b!==x&&b!==+x&&r.push(ug("dynamic",a,c.concat(y,v),x,b)):r.push(ug("value",a,c.concat(y,v),x))}else r.push(ug("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],rt.validate(x,m)?b!==x&&b!==+x&&r.push(ug("dynamic",a,c.concat(y),x,b)):r.push(ug("value",a,c.concat(y),x))}else if(d.items&&!h&&ig(u)){var M,T,A=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(ug("object","layout"))),Qr.supplyDefaults(o);for(var l=o._fullData,s=n.length,c=0;c-1&&(l[c[n]].title="");for(n=0;nN!=(L=w[b][1])>=N&&(M=w[b-1][0],T=w[b][0],L-A&&(k=M+(T-M)*(N-A)/(L-A),O=Math.min(O,k),P=Math.max(P,k)));O=Math.max(O,0),P=Math.min(P,o._length);var R=It.defaultLine;return It.opacity(i.fillcolor)?R=i.fillcolor:It.opacity((i.line||{}).color)&&(R=i.line.color),rt.extendFlat(e,{distance:e.maxHoverDistance,x0:O,x1:P,y0:N,y1:N,color:R}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},Hg=r.BADNUM,qg=rt.segmentsIntersect,Vg=rt.constrain,Ug=function(e,t){var n,r,a,i,o,l,s,c,u,f,d,h,p,g,v,y,m=t.xaxis,x=t.yaxis,b=t.simplify,_=t.connectGaps,w=t.baseTolerance,k=t.shape,M="linear"===k,T=[],A=br.minTolerance,L=new Array(e.length),C=0;function S(t){var n=e[t],r=m.c2p(n.x),a=x.c2p(n.y);return r===Hg||a===Hg?n.intoCenter||!1:[r,a]}function z(e){var t=e[0]/m._length,n=e[1]/x._length;return(1+br.toleranceGrowth*Math.max(0,-t,t-1,-n,n-1))*w}function O(e,t){var n=e[0]-t[0],r=e[1]-t[1];return Math.sqrt(n*n+r*r)}b||(w=A=-1);var P,D,E,I,N,R,F,B=br.maxScreensAway,j=-m._length*B,H=m._length*(1+B),q=-x._length*B,V=x._length*(1+B),U=[[j,q,H,q],[H,q,H,V],[H,V,j,V],[j,V,j,q]];function G(e){if(e[0]H||e[1]V)return[Vg(e[0],j,H),Vg(e[1],q,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===j||e[0]===H)||(e[1]===t[1]&&(e[1]===q||e[1]===V)||void 0)}function Z(e,t,n){return function(r,a){var i=G(r),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*rt.constrain((r[e]+a[e])/2,t,n)-((i||r)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function X(e){var t=e[0],n=e[1],r=t===L[C-1][0],a=n===L[C-1][1];if(!r||!a)if(C>1){var i=t===L[C-2][0],o=n===L[C-2][1];r&&(t===j||t===H)&&i?o?C--:L[C-1]=e:a&&(n===q||n===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&X([E,I]),X(e),N=null,E=I=0}function Q(e){if(P=e[0]H?H:0,D=e[1]V?V:0,P||D){if(C)if(N){var t=F(N,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else R=F(L[C-1],e)[0],L[C++]=R;else L[C++]=[P||e[0],D||e[1]];var n=L[C-1];P&&D&&(n[0]!==P||n[1]!==D)?(N&&(E!==P&&I!==D?X(E&&I?(r=N,i=(a=e)[0]-r[0],o=(a[1]-r[1])/i,(r[1]*a[0]-a[1]*r[0])/i>0?[o>0?j:H,V]:[o>0?H:j,q]):[E||P,I||D]):E&&I&&X([E,I])),X([P,D])):E-P&&I-D&&X([P||E,D||I]),N=e,E=P,I=D}else N&&W(F(N,e)[0]),L[C++]=e;var r,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var n=[],r=0,a=0;a<4;a++){var i=U[a],o=qg(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!r||Math.abs(o.x-n[0][0])>1||Math.abs(o.y-n[0][1])>1)&&(o=[o.x,o.y],r&&O(o,e)z(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;Q(l),r=l}}else Q(i)}N&&X([E||N[0],I||N[1]]),T.push(L.slice(0,C))}return T},Gg=qi.tester,Yg=function(t,n,r,a,i){var o,l,s,c,u=n.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(r,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,n){var r,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d)?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){Zg(t,i,n,e,r,this,a)})})):u.selectAll("g.trace").each(function(e,i){Zg(t,i,n,e,r,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()};function Zg(t,n,r,a,i,o,l){var s,c;!function(t,n,r,a,i){var o=r.xaxis,l=r.yaxis,s=e.extent(rt.simpleMap(o.range,o.r2c)),c=e.extent(rt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Vn.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var r=e[0].trace;Vn.hasMarkers(r)&&r.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=r.xaxis,h=r.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(D.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),r.isRangePlot||(a[0].node3=v);var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,T,A,L,C,S,z,O,P="",E="",I=[],N=rt.noop;if(y=p._ownFill,Vn.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=Un.steps(g.shape),A=Un.steps(g.shape.split("").reverse().join(""))):T=A="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Un.smoothclosed(e.slice(1),g.smoothing):Un.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return A(e.reverse())},I=Ug(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),O=p._polygons=new Array(I.length),c=0;c1){var r=e.select(this);if(r.datum(a),t)f(r.style("opacity",0).attr("d",k).call(Un.lineGroupStyle)).style("opacity",1);else{var i=f(r);i.attr("d",k),Un.singleLineStyle(a,i)}}}}}var R=v.selectAll(".js-line").data(I);f(R.exit()).style("opacity",0).remove(),R.each(N(!1)),R.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Un.lineGroupStyle).each(N(!0)),Un.setClipUrl(R,r.layerClipId),I.length?(y?C&&z&&(x?("y"===x?C[1]=z[1]=h.c2p(0,!0):"x"===x&&(C[0]=z[0]=d.c2p(0,!0)),f(y).attr("d","M"+z+"L"+C+"L"+P.substr(1)).call(Un.singleFillStyle)):f(y).attr("d",P+"Z").call(Un.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&P&&b?("tonext"===p.fill?f(m).attr("d",P+"Z"+b+"Z").call(Un.singleFillStyle):f(m).attr("d",P+"L"+b.substr(1)+"Z").call(Un.singleFillStyle),p._polygons=p._polygons.concat(_)):(B(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=O):(y?B(y):m&&B(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Un.setClipUrl(e.select(this),n?null:r.layerClipId)})}function B(e){f(e).attr("d","M0,0Z")}function j(e){return e.filter(function(e){return e.vis})}function H(e){return e.id}function q(e){if(e.ids)return H}function V(){return!1}function U(n){var a,i=n[0].trace,o=e.select(this),l=Vn.hasMarkers(i),s=Vn.hasText(i),c=q(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?j:rt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?j:rt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Un.pointStyle,i,t).call(Un.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Un.tryColorscale(i.marker,""),m=l&&Un.tryColorscale(i.marker,"line");a.order(),a.each(function(n){var a=e.select(this),o=f(a);Un.translatePoint(n,o,d,h)?(Un.singlePointStyle(n,o,i,y,m,t),r.layerClipId&&Un.hideOutsideRangePoint(n,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==n.data&&void 0!==n.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var n=e.select(this),a=f(n.select("text"));Un.translatePoint(t,a,d,h)?r.layerClipId&&Un.hideOutsideRangePoint(t,n,d,h,i.xcalendar,i.ycalendar):n.remove()}),a.selectAll("text").call(Un.textPointStyle,i,t).each(function(t){var n=d.c2p(t.x),r=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:n,y:r})})}),a.exit().remove()}}var Xg=function(e,t){var n,r,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Vn.hasMarkers(u)&&!Vn.hasText(u))return[];if(!1===t)for(n=0;n=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===n.xaxis&&i.yaxis===n.yaxis){i.opacity=void 0;break}}}}},$g.calc=Og,$g.arraysToCalcdata=Tg,$g.plot=Yg,$g.colorbar=es,$g.style=Qg,$g.hoverPoints=jg,$g.selectPoints=Xg,$g.animatable=!0,$g.moduleType="trace",$g.name="scatter",$g.basePlotModule=Qo,$g.categories=["cartesian","svg","symbols","markerColorscale","errorBarsOK","showLegend","scatter-like","draggedPts"],$g.meta={};var Kg=$g,ev={version:"1.36.0"};Iu.polyfill();for(var tv=ev.register=D.register,nv=Object.keys(yg),rv=0;rvc.size/1.9?c.size:c.size/Math.ceil(c.size/g);var _=c.start+(c.size-g)/2;v=_-g*Math.ceil((_-v)/g)}for(o=0;o=0&&h=0;r--)l(r);else if("increasing"===t){for(r=1;r=0;r--)e[r]+=e[r+1];"exclude"===n&&(e.push(0),e.shift())}}(i,u.direction,u.currentbin);var j=Math.min(a.length,i.length),H=[],q=0,V=j-1;for(r=0;r=q;r--)if(i[r]){V=r;break}for(r=q;r<=V;r++)if(n(a[r])&&n(i[r])){var U={p:a[r],s:i[r],b:0};u.enabled||(U.pts=w[r],I?U.p0=U.p1=w[r].length?v[w[r][0]]:a[r]:(U.p0=D(m[r]),U.p1=D(m[r+1],!0))),H.push(U)}return 1===H.length&&(H[0].width1=Pa.tickIncrement(H[0].p,g.size,!1,c)-H[0].p),il(H,t),rt.isArrayOrTypedArray(t.selectedpoints)&&rt.tagSelected(H,t,F),H}},_v.setPositions=Rl,_v.plot=Al,_v.style=Wl,_v.colorbar=es,_v.hoverPoints=function(e,t,n,r){var a=yl(e,t,n,r);if(a){var i=(e=a[0]).cd[e.index],o=e.cd[0].trace;if(!o.cumulative.enabled){var l="h"===o.orientation?"y":"x";e[l+"Label"]=bv(e[l+"a"],i.p0,i.p1)}return a}},_v.selectPoints=Ol,_v.eventData=xv,_v.moduleType="trace",_v.name="histogram",_v.basePlotModule=Qo,_v.categories=["cartesian","svg","bar","histogram","oriented","errorBarsOK","showLegend"],_v.meta={};var wv=_v,kv=m.extendFlat,Mv=kv({},{x:uv.x,y:uv.y,z:{valType:"data_array",editType:"calc"},marker:{color:{valType:"data_array",editType:"calc"},editType:"calc"},histnorm:uv.histnorm,histfunc:uv.histfunc,autobinx:uv.autobinx,nbinsx:uv.nbinsx,xbins:uv.xbins,autobiny:uv.autobiny,nbinsy:uv.nbinsy,ybins:uv.ybins,xgap:Ns.xgap,ygap:Ns.ygap,zsmooth:Ns.zsmooth,zhoverformat:Ns.zhoverformat},jt,{autocolorscale:kv({},jt.autocolorscale,{dflt:!1})},{colorbar:an}),Tv=function(e,t,n,r){var a=n("x"),i=n("y");if(a&&a.length&&i&&i.length){D.getComponentMethod("calendars","handleTraceDefaults")(e,t,["x","y"],r),(n("z")||n("marker.color"))&&n("histfunc");mv(0,t,n,["x","y"])}else t.visible=!1},Av=Pa.hoverLabelText,Lv={};Lv.attributes=Mv,Lv.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,Mv,n,r)}Tv(e,t,a,r),!1!==t.visible&&(lv(0,0,a),fn(e,t,r,a,{prefix:"",cLetter:"z"}))},Lv.calc=kc,Lv.plot=nu,Lv.colorbar=ov,Lv.style=du,Lv.hoverPoints=function(e,t,n,r,a,i){var o=Bc(e,t,n,0,0,i);if(o){var l=(e=o[0]).index,s=l[0],c=l[1],u=e.cd[0],f=u.xRanges[c],d=u.yRanges[s];return e.xLabel=Av(e.xa,f[0],f[1]),e.yLabel=Av(e.ya,d[0],d[1]),o}},Lv.eventData=xv,Lv.moduleType="trace",Lv.name="histogram2d",Lv.basePlotModule=Qo,Lv.categories=["cartesian","svg","2dMap","histogram"],Lv.meta={};var Cv=Lv,Sv=m.extendFlat,zv=Sv({x:Mv.x,y:Mv.y,z:Mv.z,marker:Mv.marker,histnorm:Mv.histnorm,histfunc:Mv.histfunc,autobinx:Mv.autobinx,nbinsx:Mv.nbinsx,xbins:Mv.xbins,autobiny:Mv.autobiny,nbinsy:Mv.nbinsy,ybins:Mv.ybins,autocontour:qs.autocontour,ncontours:qs.ncontours,contours:qs.contours,line:qs.line,zhoverformat:Mv.zhoverformat},jt,{zmin:Sv({},jt.zmin,{editType:"calc"}),zmax:Sv({},jt.zmax,{editType:"calc"})},{colorbar:an}),Ov={};Ov.attributes=zv,Ov.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,zv,n,r)}Tv(e,t,a,r),!1!==t.visible&&(Ec(0,t,a,function(n){return rt.coerce2(e,t,zv,n)}),Ic(e,t,a,r))},Ov.calc=Mc,Ov.plot=lu.plot,Ov.style=hu,Ov.colorbar=Lc,Ov.hoverPoints=jc,Ov.moduleType="trace",Ov.name="histogram2dcontour",Ov.basePlotModule=Qo,Ov.categories=["cartesian","svg","2dMap","contour","histogram"],Ov.meta={};var Pv=Ov,Dv=vf.attributes,Ev=m.extendFlat,Iv=L({editType:"calc",colorEditType:"style"}),Nv={labels:{valType:"data_array",editType:"calc"},label0:{valType:"number",dflt:0,editType:"calc"},dlabel:{valType:"number",dflt:1,editType:"calc"},values:{valType:"data_array",editType:"calc"},marker:{colors:{valType:"data_array",editType:"calc"},line:{color:{valType:"color",dflt:z.defaultLine,arrayOk:!0,editType:"style"},width:{valType:"number",min:0,dflt:0,arrayOk:!0,editType:"style"},editType:"calc"},editType:"calc"},text:{valType:"data_array",editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:Ev({},S.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0,editType:"calc"},textfont:Ev({},Iv,{}),insidetextfont:Ev({},Iv,{}),outsidetextfont:Ev({},Iv,{}),domain:Dv({name:"pie",trace:!0,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:!0,editType:"calc"},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"number",min:-360,max:360,dflt:0,editType:"calc"},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0,editType:"calc"}},Rv={},Fv=Xo.getModuleCalcData;Rv.name="pie",Rv.plot=function(e){var t=D.getModule("pie"),n=Fv(e.calcdata,t)[0];n.length&&t.plot(e,n)},Rv.clean=function(e,t,n,r){var a=r._has&&r._has("pie"),i=t._has&&t._has("pie");a&&!i&&r._pielayer.selectAll("g.trace").remove()};var Bv,jv=rt.isArrayOrTypedArray;function Hv(e,t){if(!Bv){var n=It.defaults;Bv=qv(n)}var r=t||Bv;return r[e%r.length]}function qv(e){var t,n=e.slice();for(t=0;t0?1:-1)/2,y:i/(1+n*n/(r*r)),outside:!0}}var Wv={};Wv.attributes=Nv,Wv.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,Nv,n,r)}var i=rt.coerceFont,o=a("values"),l=a("labels");if(!Array.isArray(l)){if(!rt.isArrayOrTypedArray(o)||!o.length)return void(t.visible=!1);a("label0"),a("dlabel")}a("marker.line.width")&&a("marker.line.color"),a("marker.colors"),a("scalegroup");var s=a("text"),c=a("textinfo",Array.isArray(s)?"text+percent":"percent");if(a("hovertext"),c&&"none"!==c){var u=a("textposition"),f=Array.isArray(u)||"auto"===u,d=f||"inside"===u,h=f||"outside"===u;if(d||h){var p=i(a,"textfont",r.font);d&&i(a,"insidetextfont",p),h&&i(a,"outsidetextfont",p)}}Vv(t,r,a),a("hole"),a("sort"),a("direction"),a("rotation"),a("pull")},Wv.supplyLayoutDefaults=function(e,t){var n,r;n="hiddenlabels",rt.coerce(e,t,Uv,n,r)},Wv.layoutAttributes=Uv,Wv.calc=function(e,t){var r,a,i,o,l,c=t.values,u=jv(c)&&c.length,f=t.labels,d=t.marker.colors||[],h=[],p=e._fullLayout,g=p.colorway,v=p._piecolormap,y={},m=0,x=p.hiddenlabels||[];if(p._piecolorway||g===It.defaults||(p._piecolorway=qv(g)),t.dlabel)for(f=new Array(c.length),r=0;r")}}return h},Wv.plot=function(t,n){var r=t._fullLayout;!function(e,t){var n,r,a,i,o,l,s,c,u,f=[];for(a=0;as&&(s=l.pull[i]);o.r=Math.min(n,r)/(2+2*s),o.cx=t.l+t.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=t.t+t.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;ia.vTotal/2?1:0)}(n),a.each(function(){var a=e.select(this).selectAll("g.slice").data(n);a.enter().append("g").classed("slice",!0),a.exit().remove();var l=[[[],[]],[[],[]]],s=!1;a.each(function(n){if(n.hidden)e.select(this).selectAll("path,g").remove();else{n.pointNumber=n.i,n.curveNumber=o.index,l[n.pxmid[1]<0?0:1][n.pxmid[0]<0?0:1].push(n);var a=i.cx,c=i.cy,u=e.select(this),f=u.selectAll("path.surface").data([n]),d=!1,h=!1;if(f.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),u.select("path.textline").remove(),u.on("mouseover",function(){var l=t._fullLayout,s=t._fullData[o.index];if(!t._dragging&&!1!==l.hovermode){var u=s.hoverinfo;if(Array.isArray(u)&&(u=Li.castHoverinfo({hoverinfo:[If.castOption(u,n.pts)],_module:o._module},l,0)),"all"===u&&(u="label+text+value+percent+name"),"none"!==u&&"skip"!==u&&u){var f=Zv(n,i),p=a+n.pxmid[0]*(1-f),g=c+n.pxmid[1]*(1-f),v=r.separators,y=[];if(-1!==u.indexOf("label")&&y.push(n.label),-1!==u.indexOf("text")){var m=If.castOption(s.hovertext||s.text,n.pts);m&&y.push(m)}-1!==u.indexOf("value")&&y.push(If.formatPieValue(n.v,v)),-1!==u.indexOf("percent")&&y.push(If.formatPiePercent(n.v/i.vTotal,v));var x=o.hoverlabel,b=x.font;Li.loneHover({x0:p-f*i.r,x1:p+f*i.r,y:g,text:y.join("
"),name:-1!==u.indexOf("name")?s.name:void 0,idealAlign:n.pxmid[0]<0?"left":"right",color:If.castOption(x.bgcolor,n.pts)||n.color,borderColor:If.castOption(x.bordercolor,n.pts),fontFamily:If.castOption(b.family,n.pts),fontSize:If.castOption(b.size,n.pts),fontColor:If.castOption(b.color,n.pts)},{container:l._hoverlayer.node(),outerContainer:l._paper.node(),gd:t}),d=!0}t.emit("plotly_hover",{points:[Yv(n,s)],event:e.event}),h=!0}}).on("mouseout",function(r){var a=t._fullLayout,i=t._fullData[o.index];h&&(r.originalEvent=e.event,t.emit("plotly_unhover",{points:[Yv(n,i)],event:e.event}),h=!1),d&&(Li.loneUnhover(a._hoverlayer.node()),d=!1)}).on("click",function(){var r=t._fullLayout,a=t._fullData[o.index];t._dragging||!1===r.hovermode||(t._hoverdata=[Yv(n,a)],Li.click(t,e.event))}),o.pull){var p=+If.castOption(o.pull,n.pts)||0;p>0&&(a+=p*n.pxmid[0],c+=p*n.pxmid[1])}n.cxFinal=a,n.cyFinal=c;var g=o.hole;if(n.v===i.vTotal){var v="M"+(a+n.px0[0])+","+(c+n.px0[1])+_(n.px0,n.pxmid,!0,1)+_(n.pxmid,n.px0,!0,1)+"Z";g?f.attr("d","M"+(a+g*n.px0[0])+","+(c+g*n.px0[1])+_(n.px0,n.pxmid,!1,g)+_(n.pxmid,n.px0,!1,g)+"Z"+v):f.attr("d",v)}else{var y=_(n.px0,n.px1,!0,1);if(g){var m=1-g;f.attr("d","M"+(a+g*n.px1[0])+","+(c+g*n.px1[1])+_(n.px1,n.px0,!1,g)+"l"+m*n.px0[0]+","+m*n.px0[1]+y+"Z")}else f.attr("d","M"+a+","+c+"l"+n.px0[0]+","+n.px0[1]+y+"Z")}var x=If.castOption(o.textposition,n.pts),b=u.selectAll("g.slicetext").data(n.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var r=rt.ensureSingle(e.select(this),"text","",function(e){e.attr("data-notex",1)});r.text(n.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Un.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(mn.convertToTspans,t);var l,u=Un.bBox(r.node());"outside"===x?l=Xv(u,n):(l=function(e,t,n){var r=Math.sqrt(e.width*e.width+e.height*e.height),a=e.width/e.height,i=Math.PI*Math.min(t.v/n.vTotal,.5),o=1-n.trace.hole,l=Zv(t,n),s={scale:l*n.r*2/r,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=n.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),f={scale:2*u/e.height,rCenter:Math.cos(u/n.r)-u*a/n.r,rotate:(180/Math.PI*t.midangle+720)%180-90},d=1/a,h=d+1/(2*Math.tan(i)),p=n.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(d*d+o/2)+d)),g={scale:2*p/e.width,rCenter:Math.cos(p/n.r)-p/a/n.r,rotate:(180/Math.PI*t.midangle+810)%180-90},v=g.scale>f.scale?g:f;return s.scale<1&&v.scale>s.scale?v:s}(u,n,i),"auto"===x&&l.scale<1&&(r.call(Un.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(u=Un.bBox(r.node())),l=Xv(u,n)));var f=a+n.pxmid[0]*l.rCenter+(l.x||0),d=c+n.pxmid[1]*l.rCenter+(l.y||0);l.outside&&(n.yLabelMin=d-u.height/2,n.yLabelMid=d,n.yLabelMax=d+u.height/2,n.labelExtraX=0,n.labelExtraY=0,s=!0),r.attr("transform","translate("+f+","+d+")"+(l.scale<1?"scale("+l.scale+")":"")+(l.rotate?"rotate("+l.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function _(e,t,r,a){return"a"+a*i.r+","+a*i.r+" 0 "+n.largeArc+(r?" 1 ":" 0 ")+a*(t[0]-e[0])+","+a*(t[1]-e[1])}}),s&&function(e,t){var n,r,a,i,o,l,s,c,u,f,d,h,p;function g(e,t){return e.pxmid[1]-t.pxmid[1]}function v(e,t){return t.pxmid[1]-e.pxmid[1]}function y(e,n){n||(n={});var a,c,u,d,h,p,g=n.labelExtraY+(r?n.yLabelMax:n.yLabelMin),v=r?e.yLabelMin:e.yLabelMax,y=r?e.yLabelMax:e.yLabelMin,m=e.cyFinal+o(e.px0[1],e.px1[1]),x=g-v;if(x*s>0&&(e.labelExtraY=x),Array.isArray(t.pull))for(c=0;c=(If.castOption(t.pull,u.pts)||0)||((e.pxmid[1]-u.pxmid[1])*s>0?(d=u.cyFinal+o(u.px0[1],u.px1[1]),(x=d-v-e.labelExtraY)*s>0&&(e.labelExtraY+=x)):(y+e.labelExtraY-m)*s>0&&(a=3*l*Math.abs(c-f.indexOf(e)),h=u.cxFinal+i(u.px0[0],u.px1[0]),(p=h+a-(e.cxFinal+e.pxmid[0])-e.labelExtraX)*l>0&&(e.labelExtraX+=p)))}for(r=0;r<2;r++)for(a=r?g:v,o=r?Math.max:Math.min,s=r?1:-1,n=0;n<2;n++){for(i=n?Math.max:Math.min,l=n?1:-1,(c=e[r][n]).sort(a),u=e[1-r][n],f=u.concat(c),h=[],d=0;dMath.abs(c)?i+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):i+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else i+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;n.append("path").classed("textline",!0).call(It.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:i,fill:"none"})}})})}),setTimeout(function(){a.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},Wv.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var n=t[0].trace,r=e.select(this);r.style({opacity:n.opacity}),r.selectAll("path.surface").each(function(t){e.select(this).call(Rf,t,n)})})},Wv.styleOne=Rf,Wv.moduleType="trace",Wv.name="pie",Wv.basePlotModule=Rv,Wv.categories=["pie","showLegend"],Wv.meta={};var Qv=Wv,Jv=vf.defaults,$v=m.extendFlat,Kv={title:nn.title,titlefont:nn.titlefont,color:nn.color,tickmode:nn.tickmode,nticks:$v({},nn.nticks,{dflt:6,min:1}),tick0:nn.tick0,dtick:nn.dtick,tickvals:nn.tickvals,ticktext:nn.ticktext,ticks:nn.ticks,ticklen:nn.ticklen,tickwidth:nn.tickwidth,tickcolor:nn.tickcolor,showticklabels:nn.showticklabels,showtickprefix:nn.showtickprefix,tickprefix:nn.tickprefix,showticksuffix:nn.showticksuffix,ticksuffix:nn.ticksuffix,showexponent:nn.showexponent,exponentformat:nn.exponentformat,separatethousands:nn.separatethousands,tickfont:nn.tickfont,tickangle:nn.tickangle,tickformat:nn.tickformat,tickformatstops:nn.tickformatstops,hoverformat:nn.hoverformat,showline:$v({},nn.showline,{dflt:!0}),linecolor:nn.linecolor,linewidth:nn.linewidth,showgrid:$v({},nn.showgrid,{dflt:!0}),gridcolor:nn.gridcolor,gridwidth:nn.gridwidth,layer:nn.layer,min:{valType:"number",dflt:0,min:0}},ey=function(e,t,n){function r(n,r){return rt.coerce(e,t,Kv,n,r)}t.type="linear";var a=r("color"),i=a===e.color?a:n.font.color,o=t._name.charAt(0).toUpperCase(),l="Component "+o,s=r("title",l);t._hovertitle=s===l?s:o,rt.coerceFont(r,"titlefont",{family:n.font.family,size:Math.round(1.2*n.font.size),color:i}),r("min"),cn(e,t,r,"linear"),on(e,t,r,"linear",{}),ln(e,t,r,{outerTicks:!0}),r("showticklabels")&&(rt.coerceFont(r,"tickfont",{family:n.font.family,size:n.font.size,color:i}),r("tickangle"),r("tickformat")),Fo(e,t,r,{dfltColor:a,bgColor:n.bgColor,blend:60,showLine:!0,showGrid:!0,noZeroLine:!0,attributes:Kv}),r("hoverformat"),r("layer")},ty=vf.attributes,ny=(0,Wt.overrideAll)({domain:ty({name:"ternary"}),bgcolor:{valType:"color",dflt:z.background},sum:{valType:"number",dflt:1,min:0},aaxis:Kv,baxis:Kv,caxis:Kv},"plot","from-root"),ry=["aaxis","baxis","caxis"];function ay(e,t,n,r){var a,i,o,l=n("bgcolor"),s=n("sum");r.bgColor=It.combine(l,r.paper_bgcolor);for(var c=0;c=s&&(u.min=0,f.min=0,d.min=0,e.aaxis&&delete e.aaxis.min,e.baxis&&delete e.baxis.min,e.caxis&&delete e.caxis.min)}var iy=rt._,oy=m.extendFlat,ly=io,sy=oo;function cy(e,t){this.id=e.id,this.graphDiv=e.graphDiv,this.init(t),this.makeFramework(t)}var uy=cy,fy=cy.prototype;fy.init=function(e){this.container=e._ternarylayer,this.defs=e._defs,this.layoutId=e._uid,this.traceHash={},this.layers={}},fy.plot=function(e,t){var n=t[this.id],r=t._size;this._hasClipOnAxisFalse=!1;for(var a=0;ady*g?a=(i=g)*dy:i=(a=p)/dy,o=d*a/p,l=h*i/g,n=t.l+t.w*u-a/2,r=t.t+t.h*(1-f)-i/2,s.x0=n,s.y0=r,s.w=a,s.h=i,s.sum=v,s.xaxis={type:"linear",range:[y+2*x-v,v-y-2*m],domain:[u-o/2,u+o/2],_id:"x"},Oa(s.xaxis,s.graphDiv._fullLayout),s.xaxis.setScale(),s.xaxis.isPtWithinRange=function(e){return e.a>=s.aaxis.range[0]&&e.a<=s.aaxis.range[1]&&e.b>=s.baxis.range[1]&&e.b<=s.baxis.range[0]&&e.c>=s.caxis.range[1]&&e.c<=s.caxis.range[0]},s.yaxis={type:"linear",range:[y,v-m-x],domain:[f-l/2,f+l/2],_id:"y"},Oa(s.yaxis,s.graphDiv._fullLayout),s.yaxis.setScale(),s.yaxis.isPtWithinRange=function(){return!0};var b=s.yaxis.domain[0],_=s.aaxis=oy({},e.aaxis,{visible:!0,range:[y,v-m-x],side:"left",_counterangle:30,tickangle:(+e.aaxis.tickangle||0)-30,domain:[b,b+l*dy],_axislayer:s.layers.aaxis,_gridlayer:s.layers.agrid,_pos:0,_id:"y",_length:a,_gridpath:"M0,0l"+i+",-"+a/2,automargin:!1});Oa(_,s.graphDiv._fullLayout),_.setScale();var w=s.baxis=oy({},e.baxis,{visible:!0,range:[v-y-x,m],side:"bottom",_counterangle:30,domain:s.xaxis.domain,_axislayer:s.layers.baxis,_gridlayer:s.layers.bgrid,_counteraxis:s.aaxis,_pos:0,_id:"x",_length:a,_gridpath:"M0,0l-"+a/2+",-"+i,automargin:!1});Oa(w,s.graphDiv._fullLayout),w.setScale(),_._counteraxis=w;var k=s.caxis=oy({},e.caxis,{visible:!0,range:[v-y-m,x],side:"right",_counterangle:30,tickangle:(+e.caxis.tickangle||0)+30,domain:[b,b+l*dy],_axislayer:s.layers.caxis,_gridlayer:s.layers.cgrid,_counteraxis:s.baxis,_pos:0,_id:"y",_length:a,_gridpath:"M0,0l-"+i+","+a/2,automargin:!1});Oa(k,s.graphDiv._fullLayout),k.setScale();var M="M"+n+","+(r+i)+"h"+a+"l-"+a/2+",-"+i+"Z";s.clipDef.select("path").attr("d",M),s.layers.plotbg.select("path").attr("d",M);var T="M0,"+i+"h"+a+"l-"+a/2+",-"+i+"Z";s.clipDefRelative.select("path").attr("d",T);var A="translate("+n+","+r+")";s.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",A),s.clipDefRelative.select("path").attr("transform",null);var L="translate("+(n-w._offset)+","+(r+i)+")";s.layers.baxis.attr("transform",L),s.layers.bgrid.attr("transform",L);var C="translate("+(n+a/2)+","+r+")rotate(30)translate(0,"+-_._offset+")";s.layers.aaxis.attr("transform",C),s.layers.agrid.attr("transform",C);var S="translate("+(n+a/2)+","+r+")rotate(-30)translate(0,"+-k._offset+")";s.layers.caxis.attr("transform",S),s.layers.cgrid.attr("transform",S),s.drawAxes(!0),s.plotContainer.selectAll(".crisp").classed("crisp",!1),s.layers.aline.select("path").attr("d",_.showline?"M"+n+","+(r+i)+"l"+a/2+",-"+i:"M0,0").call(It.stroke,_.linecolor||"#000").style("stroke-width",(_.linewidth||0)+"px"),s.layers.bline.select("path").attr("d",w.showline?"M"+n+","+(r+i)+"h"+a:"M0,0").call(It.stroke,w.linecolor||"#000").style("stroke-width",(w.linewidth||0)+"px"),s.layers.cline.select("path").attr("d",k.showline?"M"+(n+a/2)+","+r+"l"+a/2+","+i:"M0,0").call(It.stroke,k.linecolor||"#000").style("stroke-width",(k.linewidth||0)+"px"),s.graphDiv._context.staticPlot||s.initInteractions(),Un.setClipUrl(s.layers.frontplot,s._hasClipOnAxisFalse?null:s.clipId)},fy.drawAxes=function(e){var t=this.graphDiv,n=this.id.substr(7)+"title",r=this.aaxis,a=this.baxis,i=this.caxis;if(Pa.doTicks(t,r,!0),Pa.doTicks(t,a,!0),Pa.doTicks(t,i,!0),e){var o=Math.max(r.showticklabels?r.tickfont.size/2:0,(i.showticklabels?.75*i.tickfont.size:0)+("outside"===i.ticks?.87*i.ticklen:0));this.layers["a-title"]=ua.draw(t,"a"+n,{propContainer:r,propName:this.id+".aaxis.title",placeholder:iy(t,"Click to enter Component A title"),attributes:{x:this.x0+this.w/2,y:this.y0-r.titlefont.size/3-o,"text-anchor":"middle"}});var l=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;this.layers["b-title"]=ua.draw(t,"b"+n,{propContainer:a,propName:this.id+".baxis.title",placeholder:iy(t,"Click to enter Component B title"),attributes:{x:this.x0-l,y:this.y0+this.h+.83*a.titlefont.size+l,"text-anchor":"middle"}}),this.layers["c-title"]=ua.draw(t,"c"+n,{propContainer:i,propName:this.id+".caxis.title",placeholder:iy(t,"Click to enter Component C title"),attributes:{x:this.x0+this.w+l,y:this.y0+this.h+.83*i.titlefont.size+l,"text-anchor":"middle"}})}};var hy=ht.MINZOOM/2+.87,py="m-0.87,.5h"+hy+"v3h-"+(hy+5.2)+"l"+(hy/2+2.6)+",-"+(.87*hy+4.5)+"l2.6,1.5l-"+hy/2+","+.87*hy+"Z",gy="m0.87,.5h-"+hy+"v3h"+(hy+5.2)+"l-"+(hy/2+2.6)+",-"+(.87*hy+4.5)+"l-2.6,1.5l"+hy/2+","+.87*hy+"Z",vy="m0,1l"+hy/2+","+.87*hy+"l2.6,-1.5l-"+(hy/2+2.6)+",-"+(.87*hy+4.5)+"l-"+(hy/2+2.6)+","+(.87*hy+4.5)+"l2.6,1.5l"+hy/2+",-"+.87*hy+"Z",yy="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",my=!0;function xy(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}fy.initInteractions=function(){var e,t,n,r,a,i,o,l,c,u,f=this,d=f.layers.plotbg.select("path").node(),h=f.graphDiv,p=h._fullLayout._zoomlayer,g={element:d,gd:h,plotinfo:{xaxis:f.xaxis,yaxis:f.yaxis},subplot:f.id,prepFn:function(v,y,m){g.xaxes=[f.xaxis],g.yaxes=[f.yaxis];var k=h._fullLayout.dragmode;v.shiftKey&&(k="pan"===k?"zoom":"pan"),g.minDrag="lasso"===k?1:void 0,"zoom"===k?(g.moveFn=x,g.doneFn=b,function(h,g,v){var y=d.getBoundingClientRect();e=g-y.left,t=v-y.top,n={a:f.aaxis.range[0],b:f.baxis.range[1],c:f.caxis.range[1]},a=n,r=f.aaxis.range[1]-n.a,i=s(f.graphDiv._fullLayout[f.id].bgcolor).getLuminance(),o="M0,"+f.h+"L"+f.w/2+", 0L"+f.w+","+f.h+"Z",l=!1,c=p.append("path").attr("class","zoombox").attr("transform","translate("+f.x0+", "+f.y0+")").style({fill:i>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",o),u=p.append("path").attr("class","zoombox-corners").attr("transform","translate("+f.x0+", "+f.y0+")").style({fill:It.background,stroke:It.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),sy(p)}(0,y,m)):"pan"===k?(g.moveFn=_,g.doneFn=w,n={a:f.aaxis.range[0],b:f.baxis.range[1],c:f.caxis.range[1]},a=n,sy(p)):"select"!==k&&"lasso"!==k||ly(v,y,m,g,k)},clickFn:function(e,t){if(xy(h),2===e){var n={};n[f.id+".aaxis.min"]=0,n[f.id+".baxis.min"]=0,n[f.id+".caxis.min"]=0,h.emit("plotly_doubleclick",null),D.call("relayout",h,n)}Li.click(h,t,f.id)}};function v(e,t){return 1-t/f.h}function y(e,t){return 1-(e+(f.h-t)/Math.sqrt(3))/f.w}function m(e,t){return(e-(f.h-t)/Math.sqrt(3))/f.w}function x(s,d){var h=e+s,p=t+d,g=Math.max(0,Math.min(1,v(0,t),v(0,p))),x=Math.max(0,Math.min(1,y(e,t),y(h,p))),b=Math.max(0,Math.min(1,m(e,t),m(h,p))),_=(g/2+b)*f.w,w=(1-g/2-x)*f.w,k=(_+w)/2,M=w-_,T=(1-g)*f.h,A=T-M/dy;M.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),u.transition().style("opacity",1).duration(200),l=!0)}function b(){if(xy(h),a!==n){var e={};e[f.id+".aaxis.min"]=a.a,e[f.id+".baxis.min"]=a.b,e[f.id+".caxis.min"]=a.c,D.call("relayout",h,e),my&&h.data&&h._context.showTips&&(rt.notifier(iy(h,"Double-click to zoom back out"),"long"),my=!1)}}function _(e,t){var r=e/f.xaxis._m,i=t/f.yaxis._m,o=[(a={a:n.a-i,b:n.b+(r+i)/2,c:n.c-(r-i)/2}).a,a.b,a.c].sort(),l=o.indexOf(a.a),s=o.indexOf(a.b),c=o.indexOf(a.c);o[0]<0&&(o[1]+o[0]/2<0?(o[2]+=o[0]+o[1],o[0]=o[1]=0):(o[2]+=o[0]/2,o[1]+=o[0]/2,o[0]=0),a={a:o[l],b:o[s],c:o[c]},t=(n.a-a.a)*f.yaxis._m,e=(n.c-a.c-n.b+a.b)*f.xaxis._m);var u="translate("+(f.x0+e)+","+(f.y0+t)+")";f.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",u);var d="translate("+-e+","+-t+")";f.clipDefRelative.select("path").attr("transform",d),f.aaxis.range=[a.a,f.sum-a.b-a.c],f.baxis.range=[f.sum-a.a-a.c,a.b],f.caxis.range=[f.sum-a.a-a.b,a.c],f.drawAxes(!1),f.plotContainer.selectAll(".crisp").classed("crisp",!1),f._hasClipOnAxisFalse&&f.plotContainer.select(".scatterlayer").selectAll(".trace").call(Un.hideOutsideRangePoints,f)}function w(){var e={};e[f.id+".aaxis.min"]=a.a,e[f.id+".baxis.min"]=a.b,e[f.id+".caxis.min"]=a.c,D.call("relayout",h,e)}d.onmousemove=function(e){Li.hover(h,e,f.id),h._fullLayout._lasthover=d,h._fullLayout._hoversubplot=f.id},d.onmouseout=function(e){h._dragging||zt.unhover(h,e)},zt.init(g)};var by={},_y=Xo.getSubplotCalcData,wy=rt.counterRegex;by.name="ternary",by.attr="subplot",by.idRoot="ternary",by.idRegex=by.attrRegex=wy("ternary"),by.attributes={subplot:{valType:"subplotid",dflt:"ternary",editType:"calc"}},by.layoutAttributes=ny,by.supplyLayoutDefaults=function(e,t,n){!function(e,t,n,r){var a,i,o=r.type,l=r.attributes,s=r.handleDefaults,c=r.partition||"x",u=t._subplots[o],f=u.length;function d(e,t){return rt.coerce(a,i,l,e,t)}for(var h=0;h"),a}function g(e,t){p.push(e._hovertitle+": "+Pa.tickText(e,t,"hover").text)}},Py.selectPoints=Xg,Py.eventData=function(e,t,n,r,a){if(t.xa&&(e.xaxis=t.xa),t.ya&&(e.yaxis=t.ya),r[a]){var i=r[a];e.a=i.a,e.b=i.b,e.c=i.c}else e.a=t.a,e.b=t.b,e.c=t.c;return e},Py.moduleType="trace",Py.name="scatterternary",Py.basePlotModule=by,Py.categories=["ternary","symbols","markerColorscale","showLegend","scatter-like"],Py.meta={};var Dy=Py,Ey=m.extendFlat,Iy={y:os.y,x:os.x,x0:os.x0,y0:os.y0,name:os.name,orientation:Ey({},os.orientation,{}),bandwidth:{valType:"number",min:0,editType:"calc"},scalegroup:{valType:"string",dflt:"",editType:"calc"},scalemode:{valType:"enumerated",values:["width","count"],dflt:"width",editType:"calc"},spanmode:{valType:"enumerated",values:["soft","hard","manual"],dflt:"soft",editType:"calc"},span:{valType:"info_array",items:[{valType:"any",editType:"calc"},{valType:"any",editType:"calc"}],editType:"calc"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:os.fillcolor,points:Ey({},os.boxpoints,{}),jitter:Ey({},os.jitter,{}),pointpos:Ey({},os.pointpos,{}),marker:os.marker,text:os.text,box:{visible:{valType:"boolean",dflt:!1,editType:"plot"},width:{valType:"number",min:0,max:1,dflt:.25,editType:"plot"},fillcolor:{valType:"color",editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,editType:"style"},editType:"style"},editType:"plot"},meanline:{visible:{valType:"boolean",dflt:!1,editType:"plot"},color:{valType:"color",editType:"style"},width:{valType:"number",min:0,editType:"style"},editType:"plot"},side:{valType:"enumerated",values:["both","positive","negative"],dflt:"both",editType:"plot"},selected:os.selected,unselected:os.unselected,hoveron:{valType:"flaglist",flags:["violins","points","kde"],dflt:"violins+points+kde",extras:["all"],editType:"style"}},Ny={},Ry=function(e){return 1/Math.sqrt(2*Math.PI)*Math.exp(-.5*e*e)};Ny.makeKDE=function(e,t,n){var r=n.length,a=Ry,i=e.bandwidth,o=1/(r*i);return function(e){for(var t=0,l=0;l1,h=1-a.violingap,p=s.bdPos=s.dPos*h*(1-a.violingroupgap)/(d?f:1),g=s.bPos=d?2*s.dPos*((s.num+.5)/f-.5)*h:0;if(s.wHover=s.dPos*(d?h/f:1),!0!==c.visible||s.empty)e.select(this).remove();else{var v=n[s.valLetter+"axis"],y=n[s.posLetter+"axis"],m="both"===c.side,x=m||"positive"===c.side,b=m||"negative"===c.side,_=c.box&&c.box.visible,w=c.meanline&&c.meanline.visible,k=a._violinScaleGroupStats[c.scalegroup];if(u.selectAll("path.violin").data(rt.identity).enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","violin").each(function(t){var n,r,a,i,o,u,f,d,h=e.select(this),_=t.density,w=_.length,M=t.pos+g,T=y.c2p(M);switch(c.scalemode){case"width":n=k.maxWidth/p;break;case"count":n=k.maxWidth/p*(k.maxCount/t.pts.length)}if(x){for(f=new Array(w),o=0;o0){var p,g,v,y,m,x=e.xa,b=e.ya;"h"===s.orientation?(m=t,p="y",v=b,g="x",y=x):(m=n,p="x",v=x,g="y",y=b);var _=l[e.index];if(m>=_.span[0]&&m<=_.span[1]){var w=rt.extendFlat({},e),k=y.c2p(m,!0),M=Ny.getKdeValue(_,s,m),T=Ny.getPositionOnKdePath(_,s,k),A=v._offset,L=v._length;w[p+"0"]=T[0],w[p+"1"]=T[1],w[g+"0"]=w[g+"1"]=k,w[g+"Label"]=g+": "+Pa.hoverLabelText(y,m)+", "+l[0].t.labels.kde+" "+M.toFixed(3),w.spikeDistance=h[0].spikeDistance;var C=p+"Spike";w[C]=h[0][C],h[0].spikeDistance=void 0,h[0][C]=void 0,d.push(w),(o={stroke:e.color})[p+"1"]=rt.constrain(A+T[0],A,A+L),o[p+"2"]=rt.constrain(A+T[1],A,A+L),o[g+"1"]=o[g+"2"]=y._offset+k}}}-1!==c.indexOf("points")&&(i=ys.hoverOnPoints(e,t,n));var S=a.selectAll(".violinline-"+s.uid).data(o?[0]:[]);return S.enter().append("line").classed("violinline-"+s.uid,!0).attr("stroke-width",1.5),S.exit().remove(),S.attr(o),"closest"===r?i?[i]:d:i?(d.push(i),d):d},selectPoints:Ls,moduleType:"trace",name:"violin",basePlotModule:Qo,categories:["cartesian","svg","symbols","oriented","box-violin","showLegend","draggedPts","violinLayout"],meta:{}};return iv.register([ns,Ds,cv,wv,Cv,Pv,Qv,gu,Dy,Yy]),iv}); \ No newline at end of file diff --git a/dist/plotly-finance.js b/dist/plotly-finance.js index 417ab0757c5..b02952e1c03 100644 --- a/dist/plotly-finance.js +++ b/dist/plotly-finance.js @@ -1,5 +1,5 @@ /** -* plotly.js (finance) v1.35.2 +* plotly.js (finance) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -11218,7 +11218,7 @@ var _$interactions_147 = { DESELECTDIM: 0.2 }; -var _$is_array_166 = {}; +var _$is_array_167 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11239,12 +11239,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_166.isTypedArray = function(a) { +_$is_array_167.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_166.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_166.isTypedArray(a); +_$is_array_167.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_167.isTypedArray(a); }; /** @@ -11259,7 +11259,7 @@ _$is_array_166.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_167 = function isPlainObject(obj) { +var _$isPlainObject_168 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11275,7 +11275,7 @@ var _$isPlainObject_167 = function isPlainObject(obj) { ); }; -var _$extend_159 = {}; +var _$extend_160 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11287,7 +11287,7 @@ var _$extend_159 = {}; 'use strict'; -/* removed: var _$isPlainObject_167 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_168 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11304,19 +11304,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_159.extendFlat = function() { +_$extend_160.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_159.extendDeep = function() { +_$extend_160.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_159.extendDeepAll = function() { +_$extend_160.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_159.extendDeepNoArrays = function() { +_$extend_160.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11369,12 +11369,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_167(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_168(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_167(src) ? src : {}; + clone = src && _$isPlainObject_168(src) ? src : {}; } // never move original objects, clone them @@ -11409,7 +11409,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_197 = { +var _$plot_config_198 = { // no interactivity, for export or image generation staticPlot: false, @@ -11577,7 +11577,7 @@ var _$plot_config_197 = { locales: {} }; -var _$loggers_170 = {}; +var _$loggers_171 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11590,9 +11590,9 @@ var _$loggers_170 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_197 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_198 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_170 = {}; +var loggers = _$loggers_171 = {}; /** * ------------------------------------------ @@ -11601,7 +11601,7 @@ var loggers = _$loggers_170 = {}; */ loggers.log = function() { - if(_$plot_config_197.logging > 1) { + if(_$plot_config_198.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11613,7 +11613,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_197.logging > 0) { + if(_$plot_config_198.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11625,7 +11625,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_197.logging > 0) { + if(_$plot_config_198.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11664,7 +11664,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_174 = function noop() {}; +var _$noop_175 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11689,7 +11689,7 @@ var _$noop_174 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_178 = function pushUnique(array, item) { +var _$pushUnique_179 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11826,7 +11826,7 @@ var _$attributes_80 = { /* removed: var _$attributes_80 = require('../components/fx/attributes'); */; -var _$attributes_204 = { +var _$attributes_205 = { type: { valType: 'enumerated', @@ -12132,7 +12132,7 @@ var _$layout_attributes_238 = { } }; -var _$registry_247 = {}; +var _$registry_248 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12143,29 +12143,29 @@ var _$registry_247 = {}; 'use strict'; -/* removed: var _$loggers_170 = require('./lib/loggers'); */; -/* removed: var _$noop_174 = require('./lib/noop'); */; -/* removed: var _$pushUnique_178 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_167 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_159 = require('./lib/extend'); */; +/* removed: var _$loggers_171 = require('./lib/loggers'); */; +/* removed: var _$noop_175 = require('./lib/noop'); */; +/* removed: var _$pushUnique_179 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_168 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_160 = require('./lib/extend'); */; -/* removed: var _$attributes_204 = require('./plots/attributes'); */; +/* removed: var _$attributes_205 = require('./plots/attributes'); */; /* removed: var _$layout_attributes_238 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_159.extendFlat; -var extendDeepAll = _$extend_159.extendDeepAll; - -_$registry_247.modules = {}; -_$registry_247.allCategories = {}; -_$registry_247.allTypes = []; -_$registry_247.subplotsRegistry = {}; -_$registry_247.transformsRegistry = {}; -_$registry_247.componentsRegistry = {}; -_$registry_247.layoutArrayContainers = []; -_$registry_247.layoutArrayRegexes = []; -_$registry_247.traceLayoutAttributes = {}; -_$registry_247.localeRegistry = {}; -_$registry_247.apiMethodRegistry = {}; +var extendFlat = _$extend_160.extendFlat; +var extendDeepAll = _$extend_160.extendDeepAll; + +_$registry_248.modules = {}; +_$registry_248.allCategories = {}; +_$registry_248.allTypes = []; +_$registry_248.subplotsRegistry = {}; +_$registry_248.transformsRegistry = {}; +_$registry_248.componentsRegistry = {}; +_$registry_248.layoutArrayContainers = []; +_$registry_248.layoutArrayRegexes = []; +_$registry_248.traceLayoutAttributes = {}; +_$registry_248.localeRegistry = {}; +_$registry_248.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12206,7 +12206,7 @@ _$registry_247.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_247.register = function register(_modules) { +_$registry_248.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12235,7 +12235,7 @@ _$registry_247.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_247.apiMethodRegistry[name] = newModule.fn; + _$registry_248.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12251,8 +12251,8 @@ _$registry_247.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_247.getModule = function(trace) { - var _module = _$registry_247.modules[getTraceType(trace)]; +_$registry_248.getModule = function(trace) { + var _module = _$registry_248.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12266,20 +12266,20 @@ _$registry_247.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_247.traceIs = function(traceType, category) { +_$registry_248.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_247.modules[traceType]; + var _module = _$registry_248.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_170.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_171.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_247.modules[_$attributes_204.type.dflt]; + _module = _$registry_248.modules[_$attributes_205.type.dflt]; } return !!_module.categories[category]; @@ -12296,7 +12296,7 @@ _$registry_247.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_247.getTransformIndices = function(data, type) { +_$registry_248.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12316,7 +12316,7 @@ _$registry_247.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_247.hasTransform = function(data, type) { +_$registry_248.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12336,11 +12336,11 @@ _$registry_247.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_247.getComponentMethod = function(name, method) { - var _module = _$registry_247.componentsRegistry[name]; +_$registry_248.getComponentMethod = function(name, method) { + var _module = _$registry_248.componentsRegistry[name]; - if(!_module) return _$noop_174; - return _module[method] || _$noop_174; + if(!_module) return _$noop_175; + return _module[method] || _$noop_175; }; /** @@ -12350,10 +12350,10 @@ _$registry_247.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_247.call = function() { +_$registry_248.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_247.apiMethodRegistry[name].apply(null, args); + return _$registry_248.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12361,33 +12361,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_247.modules[thisType]) { - _$loggers_170.log('Type ' + thisType + ' already registered'); + if(_$registry_248.modules[thisType]) { + _$loggers_171.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_247.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_248.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_247.allCategories[categoriesIn[i]] = true; + _$registry_248.allCategories[categoriesIn[i]] = true; } - _$registry_247.modules[thisType] = { + _$registry_248.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_247.modules[thisType].meta = meta; + _$registry_248.modules[thisType].meta = meta; } - _$registry_247.allTypes.push(thisType); + _$registry_248.allTypes.push(thisType); - for(var componentName in _$registry_247.componentsRegistry) { + for(var componentName in _$registry_248.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12397,15 +12397,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_247.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_248.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_247.subplotsRegistry[plotType]) { - _$loggers_170.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_248.subplotsRegistry[plotType]) { + _$loggers_171.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12415,9 +12415,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_247.subplotsRegistry[plotType] = _module; + _$registry_248.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_247.componentsRegistry) { + for(var componentName in _$registry_248.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12428,24 +12428,24 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_247.componentsRegistry[name] = _module; + _$registry_248.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_178(_$registry_247.layoutArrayContainers, name); + _$pushUnique_179(_$registry_248.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_247.modules) { + for(var traceType in _$registry_248.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_247.subplotsRegistry) { + for(var subplotName in _$registry_248.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_247.transformsRegistry) { + for(var transformType in _$registry_248.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } @@ -12467,22 +12467,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_170.log([ + _$loggers_171.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_167(_module.attributes)) { - _$loggers_170.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_168(_module.attributes)) { + _$loggers_171.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_170.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_171.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_247.transformsRegistry[_module.name] = _module; + _$registry_248.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_247.componentsRegistry) { + for(var componentName in _$registry_248.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12496,7 +12496,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_247.localeRegistry; + var locales = _$registry_248.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12528,37 +12528,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_178(_$registry_247.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_179(_$registry_248.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_247.componentsRegistry[componentName].schema; + var componentSchema = _$registry_248.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_247.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_248.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_247.componentsRegistry[componentName].schema; + var componentSchema = _$registry_248.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_247.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_248.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_247.componentsRegistry[componentName].schema; + var componentSchema = _$registry_248.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_247.subplotsRegistry[subplotName]; + var subplotModule = _$registry_248.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12585,7 +12585,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_247 = require('../registry'); */; +/* removed: var _$registry_248 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12600,9 +12600,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_191 = function containerArrayMatch(astr) { - var rootContainers = _$registry_247.layoutArrayContainers, - regexpContainers = _$registry_247.layoutArrayRegexes, +var _$containerArrayMatch_192 = function containerArrayMatch(astr) { + var rootContainers = _$registry_248.layoutArrayContainers, + regexpContainers = _$registry_248.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12643,9 +12643,9 @@ var _$containerArrayMatch_191 = function containerArrayMatch(astr) { 'use strict'; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_166.isArrayOrTypedArray; -/* removed: var _$isPlainObject_167 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_191 = require('../plot_api/container_array_match'); */; +var isArrayOrTypedArray = _$is_array_167.isArrayOrTypedArray; +/* removed: var _$isPlainObject_168 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_192 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12661,7 +12661,7 @@ var isArrayOrTypedArray = _$is_array_166.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_173 = function nestedProperty(container, propStr) { +var _$nestedProperty_174 = function nestedProperty(container, propStr) { if(_$fastIsnumeric_13(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { @@ -12772,7 +12772,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_167(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_168(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12781,7 +12781,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_191(propStr); + var match = _$containerArrayMatch_192(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12934,7 +12934,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_180 = {}; +var _$regex_181 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12954,7 +12954,7 @@ var _$regex_180 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_180.counter = function(head, tail, openEnded) { +_$regex_181.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12962,7 +12962,7 @@ _$regex_180.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_155 = {}; +var _$coerce_156 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12977,16 +12977,16 @@ var _$coerce_155 = {}; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_28 = require('tinycolor2'); */; -/* removed: var _$attributes_204 = require('../plots/attributes'); */; +/* removed: var _$attributes_205 = require('../plots/attributes'); */; /* removed: var _$getScale_59 = require('../components/colorscale/get_scale'); */; var colorscaleNames = Object.keys(_$scales_65); -/* removed: var _$nestedProperty_173 = require('./nested_property'); */; -var counterRegex = _$regex_180.counter; +/* removed: var _$nestedProperty_174 = require('./nested_property'); */; +var counterRegex = _$regex_181.counter; var DESELECTDIM = _$interactions_147.DESELECTDIM; var wrap180 = _$angles_153.wrap180; -var __isArrayOrTypedArray_155 = _$is_array_166.isArrayOrTypedArray; +var __isArrayOrTypedArray_156 = _$is_array_167.isArrayOrTypedArray; -_$coerce_155.valObjectMeta = { +_$coerce_156.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12994,7 +12994,7 @@ _$coerce_155.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_155(v)) propOut.set(v); + if(__isArrayOrTypedArray_156(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13117,8 +13117,9 @@ _$coerce_155.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13172,9 +13173,11 @@ _$coerce_155.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13185,12 +13188,12 @@ _$coerce_155.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_155.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_156.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13200,19 +13203,28 @@ _$coerce_155.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13243,12 +13255,12 @@ _$coerce_155.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_155.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_156.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_155.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_156.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13268,10 +13280,10 @@ _$coerce_155.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_155.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_173(attributes, attribute).get(), - propIn = _$nestedProperty_173(containerIn, attribute), - propOut = _$nestedProperty_173(containerOut, attribute), +_$coerce_156.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_174(attributes, attribute).get(), + propIn = _$nestedProperty_174(containerIn, attribute), + propOut = _$nestedProperty_174(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13282,12 +13294,12 @@ _$coerce_155.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_155(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_156(v)) { propOut.set(v); return v; } - _$coerce_155.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_156.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13299,9 +13311,9 @@ _$coerce_155.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_155.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_173(containerIn, attribute), - propOut = _$coerce_155.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_156.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_174(containerIn, attribute), + propOut = _$coerce_156.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13312,7 +13324,7 @@ _$coerce_155.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_155.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_156.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13332,11 +13344,9 @@ _$coerce_155.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_155.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_156.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_204; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_205; var valObj = attrs.hoverinfo; var dflt; @@ -13350,7 +13360,7 @@ _$coerce_155.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_155.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_156.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13364,7 +13374,7 @@ _$coerce_155.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_155.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_156.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13379,7 +13389,7 @@ _$coerce_155.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_155(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_156(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13388,10 +13398,10 @@ _$coerce_155.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_155.validate = function(value, opts) { - var valObjectDef = _$coerce_155.valObjectMeta[opts.valType]; +_$coerce_156.validate = function(value, opts) { + var valObjectDef = _$coerce_156.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_155(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_156(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13421,12 +13431,12 @@ _$coerce_155.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_172 = function mod(v, d) { +var _$mod_173 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_156 = {}; +var _$dates_157 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13441,18 +13451,18 @@ var _$dates_156 = {}; /* removed: var _$d3_10 = require('d3'); */; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$loggers_170 = require('./loggers'); */; -/* removed: var _$mod_172 = require('./mod'); */; +/* removed: var _$loggers_171 = require('./loggers'); */; +/* removed: var _$mod_173 = require('./mod'); */; /* removed: var _$numerical_148 = require('../constants/numerical'); */; -var __BADNUM_156 = _$numerical_148.BADNUM; +var __BADNUM_157 = _$numerical_148.BADNUM; var ONEDAY = _$numerical_148.ONEDAY; var ONEHOUR = _$numerical_148.ONEHOUR; var ONEMIN = _$numerical_148.ONEMIN; var ONESEC = _$numerical_148.ONESEC; var EPOCHJD = _$numerical_148.EPOCHJD; -/* removed: var _$registry_247 = require('../registry'); */; +/* removed: var _$registry_248 = require('../registry'); */; var utcFormat = _$d3_10.time.format.utc; @@ -13466,7 +13476,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_247.componentsRegistry.calendars && + _$registry_248.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13476,11 +13486,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_156.dateTick0 = function(calendar, sunday) { +_$dates_157.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_247.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_247.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_248.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_248.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13490,9 +13500,9 @@ _$dates_156.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_156.dfltRange = function(calendar) { +_$dates_157.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_247.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_248.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13500,7 +13510,7 @@ _$dates_156.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_156.isJSDate = function(v) { +_$dates_157.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13562,17 +13572,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_156.dateTime2ms = function(s, calendar) { +_$dates_157.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_156.isJSDate(s)) { + if(_$dates_157.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_156; + return __BADNUM_157; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_156; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_157; s = String(s); @@ -13589,7 +13599,7 @@ _$dates_156.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_156; + if(!match) return __BADNUM_157; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13599,12 +13609,12 @@ _$dates_156.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_156; + if(y.length === 2) return __BADNUM_157; y = Number(y); var cDate; try { - var calInstance = _$registry_247.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_248.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13614,9 +13624,9 @@ _$dates_156.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_156; } // Invalid ... date + catch(e) { return __BADNUM_157; } // Invalid ... date - if(!cDate) return __BADNUM_156; + if(!cDate) return __BADNUM_157; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13637,18 +13647,18 @@ _$dates_156.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_156; - if(date.getUTCDate() !== d) return __BADNUM_156; + if(date.getUTCMonth() !== m) return __BADNUM_157; + if(date.getUTCDate() !== d) return __BADNUM_157; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_156.MIN_MS = _$dates_156.dateTime2ms('-9999'); -MAX_MS = _$dates_156.MAX_MS = _$dates_156.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_157.MIN_MS = _$dates_157.dateTime2ms('-9999'); +MAX_MS = _$dates_157.MAX_MS = _$dates_157.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_156.isDateTime = function(s, calendar) { - return (_$dates_156.dateTime2ms(s, calendar) !== __BADNUM_156); +_$dates_157.isDateTime = function(s, calendar) { + return (_$dates_157.dateTime2ms(s, calendar) !== __BADNUM_157); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13667,20 +13677,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_156.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_156; +_$dates_157.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_157; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_172(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_173(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_172(ms, ONEDAY)); + timeMs = Math.floor(_$mod_173(ms, ONEDAY)); try { - dateStr = _$registry_247.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_248.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13728,10 +13738,10 @@ _$dates_156.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_156.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_156; +_$dates_157.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_157; - var msecTenths = Math.floor(_$mod_172(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_173(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), dateStr = _$d3_10.time.format('%Y-%m-%d')(d), h = d.getHours(), @@ -13764,23 +13774,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_156.cleanDate = function(v, dflt, calendar) { - if(_$dates_156.isJSDate(v) || typeof v === 'number') { +_$dates_157.cleanDate = function(v, dflt, calendar) { + if(_$dates_157.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_170.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_171.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 = _$dates_156.ms2DateTimeLocal(+v); + v = _$dates_157.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_156.isDateTime(v, calendar)) { - _$loggers_170.error('unrecognized date', v); + else if(!_$dates_157.isDateTime(v, calendar)) { + _$loggers_171.error('unrecognized date', v); return dflt; } return v; @@ -13810,7 +13820,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_247.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_248.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13827,10 +13837,10 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_172(x + 0.05, ONEDAY); + var timePart = _$mod_173(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_172(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_173(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { if(!_$fastIsnumeric_13(tr)) tr = 0; // should only be 'S' @@ -13850,7 +13860,7 @@ function formatTime(x, tr) { * 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_172(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_173(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13879,7 +13889,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_156.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_157.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13923,19 +13933,19 @@ _$dates_156.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_156.incrementMonth = function(ms, dMonth, calendar) { +_$dates_157.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_172(ms, ONEDAY); + var timeMs = _$mod_173(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_247.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_248.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13944,7 +13954,7 @@ _$dates_156.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_170.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_171.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13959,7 +13969,7 @@ _$dates_156.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_156.findExactDates = function(data, calendar) { +_$dates_157.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13969,7 +13979,7 @@ _$dates_156.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_247.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_248.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { @@ -14036,7 +14046,7 @@ _$dates_156.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_157 = function ensureArray(out, n) { +var _$ensureArray_158 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14079,7 +14089,7 @@ var _$ensureArray_157 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_160 = function filterUnique(array) { +var _$filterUnique_161 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14113,7 +14123,7 @@ var _$filterUnique_160 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_161 = function filterVisible(container) { +var _$filterVisible_162 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14142,7 +14152,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_162 = {}; +var _$geometry2d_163 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14153,13 +14163,13 @@ var _$geometry2d_162 = {}; 'use strict'; -/* removed: var _$mod_172 = require('./mod'); */; +/* removed: var _$mod_173 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_162.segmentsIntersect = segmentsIntersect; +_$geometry2d_163.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14182,7 +14192,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_162.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_163.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 @@ -14235,7 +14245,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_162.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_163.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14247,13 +14257,13 @@ _$geometry2d_162.getTextLocation = function getTextLocation(path, totalPathLen, // 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_172(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_172(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_173(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_173(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_172(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_173(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14262,7 +14272,7 @@ _$geometry2d_162.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_162.clearLocationCache = function() { +_$geometry2d_163.clearLocationCache = function() { workingPath = null; }; @@ -14290,7 +14300,7 @@ _$geometry2d_162.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_162.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_163.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14351,7 +14361,7 @@ _$geometry2d_162.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_162.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_163.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14406,7 +14416,7 @@ _$geometry2d_162.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_163 = function(gd) { +var _$get_graph_div_164 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14438,7 +14448,7 @@ var _$get_graph_div_163 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_164 = function identity(d) { return d; }; +var _$identity_165 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14450,7 +14460,7 @@ var _$identity_164 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_173 = require('./nested_property'); */; +/* removed: var _$nestedProperty_174 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14472,13 +14482,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_173(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_174(baseObj, path).get(); } else { arr = baseObj; } @@ -14504,7 +14514,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_173(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_174(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14514,7 +14524,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_173(newValue, valueName).set(value); + _$nestedProperty_174(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14535,7 +14545,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_173(arr[idx], valueName).get(); + return _$nestedProperty_174(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14576,7 +14586,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value } 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_173(object, valueName).set(null); + _$nestedProperty_174(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, @@ -14603,7 +14613,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_173(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_174(arr[idx], valueName).get(); } } } else { @@ -14629,7 +14639,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_247 = require('../registry'); */; +/* removed: var _$registry_248 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14640,7 +14650,7 @@ var _$keyedContainer_168 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_169 = function localize(gd, s) { +var _$localize_170 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14662,7 +14672,7 @@ var _$localize_169 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_247.localeRegistry; + locales = _$registry_248.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14673,7 +14683,7 @@ var _$localize_169 = function localize(gd, s) { return s; }; -var _$matrix_171 = {}; +var _$matrix_172 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14686,7 +14696,7 @@ var _$matrix_171 = {}; 'use strict'; -_$matrix_171.init2dArray = function(rowLength, colLength) { +_$matrix_172.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14697,7 +14707,7 @@ _$matrix_171.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_171.transposeRagged = function(z) { +_$matrix_172.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14715,7 +14725,7 @@ _$matrix_171.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_171.dot = function(x, y) { +_$matrix_172.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14725,13 +14735,13 @@ _$matrix_171.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_171.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_172.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_171.transposeRagged(y); + var yTranspose = _$matrix_172.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_171.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_172.dot(x, yTranspose[i]); } else { // vec-vec @@ -14743,12 +14753,12 @@ _$matrix_171.dot = function(x, y) { }; // translate by (x,y) -_$matrix_171.translationMatrix = function(x, y) { +_$matrix_172.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_171.rotationMatrix = function(alpha) { +_$matrix_172.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14756,28 +14766,28 @@ _$matrix_171.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_171.rotationXYMatrix = function(a, x, y) { - return _$matrix_171.dot( - _$matrix_171.dot(_$matrix_171.translationMatrix(x, y), - _$matrix_171.rotationMatrix(a)), - _$matrix_171.translationMatrix(-x, -y)); +_$matrix_172.rotationXYMatrix = function(a, x, y) { + return _$matrix_172.dot( + _$matrix_172.dot(_$matrix_172.translationMatrix(x, y), + _$matrix_172.rotationMatrix(a)), + _$matrix_172.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_171.apply2DTransform = function(transform) { +_$matrix_172.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_171.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_172.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_171.apply2DTransform2 = function(transform) { - var at = _$matrix_171.apply2DTransform(transform); +_$matrix_172.apply2DTransform2 = function(transform) { + var at = _$matrix_172.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14806,7 +14816,7 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_175 = function(text, displayLength) { +var _$notifier_176 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); @@ -14898,7 +14908,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_181 = function(baseAttr, relativeAttr) { +var _$relative_attr_182 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14927,8 +14937,8 @@ var _$relative_attr_181 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_182 = _$is_array_166.isArrayOrTypedArray; -/* removed: var _$isPlainObject_167 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_183 = _$is_array_167.isArrayOrTypedArray; +/* removed: var _$isPlainObject_168 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14937,7 +14947,7 @@ var __isArrayOrTypedArray_182 = _$is_array_166.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_182 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_183 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14953,7 +14963,7 @@ var _$relinkPrivateKeys_182 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_182(fromVal) && __isArrayOrTypedArray_182(toVal) && _$isPlainObject_167(fromVal[0])) { + else if(__isArrayOrTypedArray_183(fromVal) && __isArrayOrTypedArray_183(toVal) && _$isPlainObject_168(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14963,12 +14973,12 @@ var _$relinkPrivateKeys_182 = function relinkPrivateKeys(toContainer, fromContai // 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_167(fromVal[j]) && _$isPlainObject_167(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_168(fromVal[j]) && _$isPlainObject_168(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_167(fromVal) && _$isPlainObject_167(toVal)) { + else if(_$isPlainObject_168(fromVal) && _$isPlainObject_168(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14978,7 +14988,7 @@ var _$relinkPrivateKeys_182 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_183 = {}; +var _$search_184 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14991,7 +15001,7 @@ var _$search_183 = {}; 'use strict'; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$loggers_170 = require('./loggers'); */; +/* removed: var _$loggers_171 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -15009,7 +15019,7 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_183.findBin = function(val, bins, linelow) { +_$search_184.findBin = function(val, bins, linelow) { if(_$fastIsnumeric_13(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : @@ -15033,7 +15043,7 @@ _$search_183.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_170.log('Long binary search...'); + if(c > 90) _$loggers_171.log('Long binary search...'); return n1 - 1; } }; @@ -15043,17 +15053,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_183.sorterAsc = function(a, b) { return a - b; }; -_$search_183.sorterDes = function(a, b) { return b - a; }; +_$search_184.sorterAsc = function(a, b) { return a - b; }; +_$search_184.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_183.distinctVals = function(valsIn) { +_$search_184.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_183.sorterAsc); + vals.sort(_$search_184.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15078,7 +15088,7 @@ _$search_183.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_183.roundUp = function(val, arrayIn, reverse) { +_$search_184.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15095,7 +15105,7 @@ _$search_183.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_185 = {}; +var _$stats_186 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15108,7 +15118,7 @@ var _$stats_185 = {}; 'use strict'; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_185 = _$is_array_166.isArrayOrTypedArray; +var __isArrayOrTypedArray_186 = _$is_array_167.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15123,14 +15133,14 @@ var __isArrayOrTypedArray_185 = _$is_array_166.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_185.aggNums = function(f, v, a, len) { +_$stats_186.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; if(!_$fastIsnumeric_13(v)) v = false; - if(__isArrayOrTypedArray_185(a[0])) { + if(__isArrayOrTypedArray_186(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_185.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_186.aggNums(f, v, a[i]); a = b; } @@ -15145,26 +15155,26 @@ _$stats_185.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_185.len = function(data) { - return _$stats_185.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_186.len = function(data) { + return _$stats_186.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_185.mean = function(data, len) { - if(!len) len = _$stats_185.len(data); - return _$stats_185.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_186.mean = function(data, len) { + if(!len) len = _$stats_186.len(data); + return _$stats_186.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_185.variance = function(data, len, mean) { - if(!len) len = _$stats_185.len(data); - if(!_$fastIsnumeric_13(mean)) mean = _$stats_185.mean(data, len); +_$stats_186.variance = function(data, len, mean) { + if(!len) len = _$stats_186.len(data); + if(!_$fastIsnumeric_13(mean)) mean = _$stats_186.mean(data, len); - return _$stats_185.aggNums(function(a, b) { + return _$stats_186.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_185.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_185.variance(data, len, mean)); +_$stats_186.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_186.variance(data, len, mean)); }; /** @@ -15182,7 +15192,7 @@ _$stats_185.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_185.interp = function(arr, n) { +_$stats_186.interp = function(arr, n) { if(!_$fastIsnumeric_13(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; @@ -15191,7 +15201,7 @@ _$stats_185.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_187 = {}; +var _$throttle_188 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15218,7 +15228,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_187.throttle = function throttle(id, minInterval, callback) { +_$throttle_188.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15258,7 +15268,7 @@ _$throttle_187.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_187.done = function(id) { +_$throttle_188.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15278,13 +15288,13 @@ _$throttle_187.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_187.clear = function(id) { +_$throttle_188.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_187.clear(idi); + for(var idi in timerCache) _$throttle_188.clear(idi); } }; @@ -15311,7 +15321,7 @@ function _clearTimeout(cache) { * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_188 = function toLogRange(val, range) { +var _$toLogRange_189 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the @@ -15322,7 +15332,7 @@ var _$toLogRange_188 = function toLogRange(val, range) { return newVal; }; -var _$lib_165 = {}; +var _$lib_166 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15339,71 +15349,71 @@ var _$lib_165 = {}; /* removed: var _$numerical_148 = require('../constants/numerical'); */; var FP_SAFE = _$numerical_148.FP_SAFE; -var __BADNUM_165 = _$numerical_148.BADNUM; - -var lib = _$lib_165 = {}; - -lib.nestedProperty = _$nestedProperty_173; -lib.keyedContainer = _$keyedContainer_168; -lib.relativeAttr = _$relative_attr_181; -lib.isPlainObject = _$isPlainObject_167; -lib.mod = _$mod_172; -lib.toLogRange = _$toLogRange_188; -lib.relinkPrivateKeys = _$relinkPrivateKeys_182; -lib.ensureArray = _$ensureArray_157; - -/* removed: var _$is_array_166 = require('./is_array'); */; -lib.isTypedArray = _$is_array_166.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_166.isArrayOrTypedArray; - -/* removed: var _$coerce_155 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_155.valObjectMeta; -lib.coerce = _$coerce_155.coerce; -lib.coerce2 = _$coerce_155.coerce2; -lib.coerceFont = _$coerce_155.coerceFont; -lib.coerceHoverinfo = _$coerce_155.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_155.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_155.validate; - -/* removed: var _$dates_156 = require('./dates'); */; -lib.dateTime2ms = _$dates_156.dateTime2ms; -lib.isDateTime = _$dates_156.isDateTime; -lib.ms2DateTime = _$dates_156.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_156.ms2DateTimeLocal; -lib.cleanDate = _$dates_156.cleanDate; -lib.isJSDate = _$dates_156.isJSDate; -lib.formatDate = _$dates_156.formatDate; -lib.incrementMonth = _$dates_156.incrementMonth; -lib.dateTick0 = _$dates_156.dateTick0; -lib.dfltRange = _$dates_156.dfltRange; -lib.findExactDates = _$dates_156.findExactDates; -lib.MIN_MS = _$dates_156.MIN_MS; -lib.MAX_MS = _$dates_156.MAX_MS; - -/* removed: var _$search_183 = require('./search'); */; -lib.findBin = _$search_183.findBin; -lib.sorterAsc = _$search_183.sorterAsc; -lib.sorterDes = _$search_183.sorterDes; -lib.distinctVals = _$search_183.distinctVals; -lib.roundUp = _$search_183.roundUp; - -/* removed: var _$stats_185 = require('./stats'); */; -lib.aggNums = _$stats_185.aggNums; -lib.len = _$stats_185.len; -lib.mean = _$stats_185.mean; -lib.variance = _$stats_185.variance; -lib.stdev = _$stats_185.stdev; -lib.interp = _$stats_185.interp; - -/* removed: var _$matrix_171 = require('./matrix'); */; -lib.init2dArray = _$matrix_171.init2dArray; -lib.transposeRagged = _$matrix_171.transposeRagged; -lib.dot = _$matrix_171.dot; -lib.translationMatrix = _$matrix_171.translationMatrix; -lib.rotationMatrix = _$matrix_171.rotationMatrix; -lib.rotationXYMatrix = _$matrix_171.rotationXYMatrix; -lib.apply2DTransform = _$matrix_171.apply2DTransform; -lib.apply2DTransform2 = _$matrix_171.apply2DTransform2; +var __BADNUM_166 = _$numerical_148.BADNUM; + +var lib = _$lib_166 = {}; + +lib.nestedProperty = _$nestedProperty_174; +lib.keyedContainer = _$keyedContainer_169; +lib.relativeAttr = _$relative_attr_182; +lib.isPlainObject = _$isPlainObject_168; +lib.mod = _$mod_173; +lib.toLogRange = _$toLogRange_189; +lib.relinkPrivateKeys = _$relinkPrivateKeys_183; +lib.ensureArray = _$ensureArray_158; + +/* removed: var _$is_array_167 = require('./is_array'); */; +lib.isTypedArray = _$is_array_167.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_167.isArrayOrTypedArray; + +/* removed: var _$coerce_156 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_156.valObjectMeta; +lib.coerce = _$coerce_156.coerce; +lib.coerce2 = _$coerce_156.coerce2; +lib.coerceFont = _$coerce_156.coerceFont; +lib.coerceHoverinfo = _$coerce_156.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_156.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_156.validate; + +/* removed: var _$dates_157 = require('./dates'); */; +lib.dateTime2ms = _$dates_157.dateTime2ms; +lib.isDateTime = _$dates_157.isDateTime; +lib.ms2DateTime = _$dates_157.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_157.ms2DateTimeLocal; +lib.cleanDate = _$dates_157.cleanDate; +lib.isJSDate = _$dates_157.isJSDate; +lib.formatDate = _$dates_157.formatDate; +lib.incrementMonth = _$dates_157.incrementMonth; +lib.dateTick0 = _$dates_157.dateTick0; +lib.dfltRange = _$dates_157.dfltRange; +lib.findExactDates = _$dates_157.findExactDates; +lib.MIN_MS = _$dates_157.MIN_MS; +lib.MAX_MS = _$dates_157.MAX_MS; + +/* removed: var _$search_184 = require('./search'); */; +lib.findBin = _$search_184.findBin; +lib.sorterAsc = _$search_184.sorterAsc; +lib.sorterDes = _$search_184.sorterDes; +lib.distinctVals = _$search_184.distinctVals; +lib.roundUp = _$search_184.roundUp; + +/* removed: var _$stats_186 = require('./stats'); */; +lib.aggNums = _$stats_186.aggNums; +lib.len = _$stats_186.len; +lib.mean = _$stats_186.mean; +lib.variance = _$stats_186.variance; +lib.stdev = _$stats_186.stdev; +lib.interp = _$stats_186.interp; + +/* removed: var _$matrix_172 = require('./matrix'); */; +lib.init2dArray = _$matrix_172.init2dArray; +lib.transposeRagged = _$matrix_172.transposeRagged; +lib.dot = _$matrix_172.dot; +lib.translationMatrix = _$matrix_172.translationMatrix; +lib.rotationMatrix = _$matrix_172.rotationMatrix; +lib.rotationXYMatrix = _$matrix_172.rotationXYMatrix; +lib.apply2DTransform = _$matrix_172.apply2DTransform; +lib.apply2DTransform2 = _$matrix_172.apply2DTransform2; /* removed: var _$angles_153 = require('./angles'); */; lib.deg2rad = _$angles_153.deg2rad; @@ -15411,54 +15421,54 @@ lib.rad2deg = _$angles_153.rad2deg; lib.wrap360 = _$angles_153.wrap360; lib.wrap180 = _$angles_153.wrap180; -/* removed: var _$geometry2d_162 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_162.segmentsIntersect; -lib.segmentDistance = _$geometry2d_162.segmentDistance; -lib.getTextLocation = _$geometry2d_162.getTextLocation; -lib.clearLocationCache = _$geometry2d_162.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_162.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_162.findPointOnPath; +/* removed: var _$geometry2d_163 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_163.segmentsIntersect; +lib.segmentDistance = _$geometry2d_163.segmentDistance; +lib.getTextLocation = _$geometry2d_163.getTextLocation; +lib.clearLocationCache = _$geometry2d_163.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_163.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_163.findPointOnPath; -/* removed: var _$extend_159 = require('./extend'); */; -lib.extendFlat = _$extend_159.extendFlat; -lib.extendDeep = _$extend_159.extendDeep; -lib.extendDeepAll = _$extend_159.extendDeepAll; -lib.extendDeepNoArrays = _$extend_159.extendDeepNoArrays; +/* removed: var _$extend_160 = require('./extend'); */; +lib.extendFlat = _$extend_160.extendFlat; +lib.extendDeep = _$extend_160.extendDeep; +lib.extendDeepAll = _$extend_160.extendDeepAll; +lib.extendDeepNoArrays = _$extend_160.extendDeepNoArrays; -/* removed: var _$loggers_170 = require('./loggers'); */; -lib.log = _$loggers_170.log; -lib.warn = _$loggers_170.warn; -lib.error = _$loggers_170.error; +/* removed: var _$loggers_171 = require('./loggers'); */; +lib.log = _$loggers_171.log; +lib.warn = _$loggers_171.warn; +lib.error = _$loggers_171.error; -/* removed: var _$regex_180 = require('./regex'); */; -lib.counterRegex = _$regex_180.counter; +/* removed: var _$regex_181 = require('./regex'); */; +lib.counterRegex = _$regex_181.counter; -/* removed: var _$throttle_187 = require('./throttle'); */; -lib.throttle = _$throttle_187.throttle; -lib.throttleDone = _$throttle_187.done; -lib.clearThrottle = _$throttle_187.clear; +/* removed: var _$throttle_188 = require('./throttle'); */; +lib.throttle = _$throttle_188.throttle; +lib.throttleDone = _$throttle_188.done; +lib.clearThrottle = _$throttle_188.clear; -lib.getGraphDiv = _$get_graph_div_163; +lib.getGraphDiv = _$get_graph_div_164; -lib._ = _$localize_169; +lib._ = _$localize_170; -lib.notifier = _$notifier_175; +lib.notifier = _$notifier_176; -lib.filterUnique = _$filterUnique_160; -lib.filterVisible = _$filterVisible_161; -lib.pushUnique = _$pushUnique_178; +lib.filterUnique = _$filterUnique_161; +lib.filterVisible = _$filterVisible_162; +lib.pushUnique = _$pushUnique_179; lib.cleanNumber = _$cleanNumber_154; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_13(v)) return __BADNUM_165; + if(!_$fastIsnumeric_13(v)) return __BADNUM_166; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_165; - return _$fastIsnumeric_13(v) ? Number(v) : __BADNUM_165; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_166; + return _$fastIsnumeric_13(v) ? Number(v) : __BADNUM_166; }; -lib.noop = _$noop_174; -lib.identity = _$identity_164; +lib.noop = _$noop_175; +lib.identity = _$identity_165; /** * swap x and y of the same attribute in container cont @@ -15957,6 +15967,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16150,7 +16217,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_165 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_166 = /^\w*$/; /* * Substitute values from an object into a string @@ -16171,7 +16238,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_165.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_166.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16232,7 +16299,7 @@ lib.pseudoRandom = function() { 'use strict'; -var _$attributes_205 = { +var _$attributes_206 = { xaxis: { valType: 'subplotid', @@ -16258,21 +16325,21 @@ var _$attributes_205 = { */ 'use strict'; -var __counterRegex_212 = _$regex_180.counter; +var __counterRegex_213 = _$regex_181.counter; -var _$constants_212 = { +var _$constants_213 = { idRegex: { - x: __counterRegex_212('x'), - y: __counterRegex_212('y') + x: __counterRegex_213('x'), + y: __counterRegex_213('y') }, - attrRegex: __counterRegex_212('[xy]axis'), + attrRegex: __counterRegex_213('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_212('xaxis'), - yAxisMatch: __counterRegex_212('yaxis'), + xAxisMatch: __counterRegex_213('xaxis'), + yAxisMatch: __counterRegex_213('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -16319,6 +16386,7 @@ var _$constants_212 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -16328,7 +16396,7 @@ var _$constants_212 = { } }; -var _$axis_ids_210 = {}; +var _$axis_ids_211 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16339,30 +16407,30 @@ var _$axis_ids_210 = {}; 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -/* removed: var _$constants_212 = require('./constants'); */; +/* removed: var _$constants_213 = require('./constants'); */; // 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. -_$axis_ids_210.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_212.AX_ID_PATTERN)) return; +_$axis_ids_211.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_213.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_210.name2id = function name2id(name) { - if(!name.match(_$constants_212.AX_NAME_PATTERN)) return; +_$axis_ids_211.name2id = function name2id(name) { + if(!name.match(_$constants_213.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_210.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_212.AX_ID_PATTERN)) return; +_$axis_ids_211.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_213.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -16371,11 +16439,11 @@ _$axis_ids_210.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_210.list = function(gd, axLetter, only2d) { +_$axis_ids_211.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_210.listIds(gd, axLetter); + var idList = _$axis_ids_211.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -16400,7 +16468,7 @@ _$axis_ids_210.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_210.listIds = function(gd, axLetter) { +_$axis_ids_211.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -16411,42 +16479,110 @@ _$axis_ids_210.listIds = function(gd, axLetter) { // 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 -_$axis_ids_210.getFromId = function(gd, id, type) { +_$axis_ids_211.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[_$axis_ids_210.id2name(id)]; + return fullLayout[_$axis_ids_211.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_210.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_211.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_247.traceIs(fullTrace, 'gl3d')) { + if(_$registry_248.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_210.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_211.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_210.idSort = function(id1, id2) { +_$axis_ids_211.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); }; -var _$attributes_70 = {}; +var _$client_17 = true; +var _$hasHover_15 = {}; +(function (global){ +'use strict' + +/* removed: var _$client_17 = require('is-browser') */; +var hasHover + +if (typeof global.matchMedia === 'function') { + hasHover = !global.matchMedia('(hover: none)').matches +} +else { + hasHover = _$client_17 +} + +_$hasHover_15 = hasHover + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + +/* removed: var _$client_17 = require('is-browser') */; + +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 +} + +var _$hasPassiveEvents_16 = _$client_17 && detect() + +var rootPosition = { left: 0, top: 0 } + +var _$mouseEventOffset_18 = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16458,17 +16594,25 @@ var _$attributes_70 = {}; 'use strict'; -_$attributes_70.dash = { - valType: 'string', - // string type usually doesn't take values... this one should really be - // a special type or at least a special coercion function, from the GUI - // you only get these values but elsewhere the user can supply a list of - // dash lengths in px, and it will be honored - values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], - dflt: 'solid', - - editType: 'style', - + +// 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 +var _$align_66 = function align(v, dv, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0), + vmax = vmin + dv / (v1 - v0), + 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; }; /** @@ -16479,512 +16623,35 @@ _$attributes_70.dash = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$font_attributes_234 = require('../font_attributes'); */; -/* removed: var _$attributes_45 = require('../../components/color/attributes'); */; -var dash = _$attributes_70.dash; -var __extendFlat_219 = _$extend_159.extendFlat; +/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$constants_212 = require('./constants'); */; +// 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'] +]; -var _$layout_attributes_219 = { - visible: { - valType: 'boolean', - - editType: 'plot', - - }, - color: { - valType: 'color', - dflt: _$attributes_45.defaultLine, - - editType: 'ticks', - - }, - title: { - valType: 'string', - - editType: 'ticks+margins', - - }, - titlefont: _$font_attributes_234({ - editType: 'ticks+margins', - - }), - type: { - valType: 'enumerated', - // '-' means we haven't yet run autotype or couldn't find any data - // it gets turned into linear in gd._fullLayout but not copied back - // to gd.data like the others are. - values: ['-', 'linear', 'log', 'date', 'category'], - dflt: '-', - - editType: 'calc', - - }, - autorange: { - valType: 'enumerated', - values: [true, false, 'reversed'], - dflt: true, - - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, - - }, - rangemode: { - valType: 'enumerated', - values: ['normal', 'tozero', 'nonnegative'], - dflt: 'normal', - - editType: 'plot', - - }, - range: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} - ], - editType: 'plot+margins', - impliedEdits: {'autorange': false}, - - }, - fixedrange: { - valType: 'boolean', - dflt: false, - - editType: 'calc', - - }, - // scaleanchor: not used directly, just put here for reference - // values are any opposite-letter axis id - scaleanchor: { - valType: 'enumerated', - values: [ - _$constants_212.idRegex.x.toString(), - _$constants_212.idRegex.y.toString() - ], - - editType: 'plot', - - }, - scaleratio: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'plot', - - }, - constrain: { - valType: 'enumerated', - values: ['range', 'domain'], - dflt: 'range', - - editType: 'plot', - - }, - // constraintoward: not used directly, just put here for reference - constraintoward: { - valType: 'enumerated', - values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], - - editType: 'plot', - - }, - // ticks - tickmode: { - valType: 'enumerated', - values: ['auto', 'linear', 'array'], - - editType: 'ticks+margins', - impliedEdits: {tick0: undefined, dtick: undefined}, - - }, - nticks: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'ticks+margins', - - }, - tick0: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - dtick: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - tickvals: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticktext: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticks: { - valType: 'enumerated', - values: ['outside', 'inside', ''], - - editType: 'ticks+margins', - - }, - mirror: { - valType: 'enumerated', - values: [true, 'ticks', false, 'all', 'allticks'], - dflt: false, - - editType: 'ticks+layoutstyle', - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: 5, - - editType: 'ticks', - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - tickcolor: { - valType: 'color', - dflt: _$attributes_45.defaultLine, - - editType: 'ticks', - - }, - showticklabels: { - valType: 'boolean', - dflt: true, - - editType: 'ticks+margins', - - }, - automargin: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - showspikes: { - valType: 'boolean', - dflt: false, - - editType: 'modebar', - - }, - spikecolor: { - valType: 'color', - dflt: null, - - editType: 'none', - - }, - spikethickness: { - valType: 'number', - dflt: 3, - - editType: 'none', - - }, - spikedash: __extendFlat_219({}, dash, {dflt: 'dash', editType: 'none'}), - spikemode: { - valType: 'flaglist', - flags: ['toaxis', 'across', 'marker'], - - dflt: 'toaxis', - editType: 'none', - - }, - spikesnap: { - valType: 'enumerated', - values: ['data', 'cursor'], - dflt: 'data', - - editType: 'none', - - }, - tickfont: _$font_attributes_234({ - editType: 'ticks+margins', - - }), - tickangle: { - valType: 'angle', - dflt: 'auto', - - editType: 'ticks+margins', - - }, - tickprefix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showtickprefix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - ticksuffix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showticksuffix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - showexponent: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - exponentformat: { - valType: 'enumerated', - values: ['none', 'e', 'E', 'power', 'SI', 'B'], - dflt: 'B', - - editType: 'ticks+margins', - - }, - separatethousands: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - tickformat: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - tickformatstops: { - _isLinkedToArray: 'tickformatstop', +var _$getCursor_67 = 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_166.constrain(Math.floor(x * 3), 0, 2); - dtickrange: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'ticks+margins'}, - {valType: 'any', editType: 'ticks+margins'} - ], - editType: 'ticks+margins', - - }, - value: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - editType: 'ticks+margins' - }, - hoverformat: { - valType: 'string', - dflt: '', - - editType: 'none', - - }, - // lines and grids - showline: { - valType: 'boolean', - dflt: false, - - editType: 'layoutstyle', - - }, - linecolor: { - valType: 'color', - dflt: _$attributes_45.defaultLine, - - editType: 'layoutstyle', - - }, - linewidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks+layoutstyle', - - }, - showgrid: { - valType: 'boolean', - - editType: 'ticks', - - }, - gridcolor: { - valType: 'color', - dflt: _$attributes_45.lightLine, - - editType: 'ticks', - - }, - gridwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - zeroline: { - valType: 'boolean', - - editType: 'ticks', - - }, - zerolinecolor: { - valType: 'color', - dflt: _$attributes_45.defaultLine, - - editType: 'ticks', - - }, - zerolinewidth: { - valType: 'number', - dflt: 1, - - editType: 'ticks', - - }, - // positioning attributes - // anchor: not used directly, just put here for reference - // values are any opposite-letter axis id - anchor: { - valType: 'enumerated', - values: [ - 'free', - _$constants_212.idRegex.x.toString(), - _$constants_212.idRegex.y.toString() - ], - - editType: 'plot+margins', - - }, - // side: not used directly, as values depend on direction - // values are top, bottom for x axes, and left, right for y - side: { - valType: 'enumerated', - values: ['top', 'bottom', 'left', 'right'], - - editType: 'plot+margins', - - }, - // overlaying: not used directly, just put here for reference - // values are false and any other same-letter axis id that's not - // itself overlaying anything - overlaying: { - valType: 'enumerated', - values: [ - 'free', - _$constants_212.idRegex.x.toString(), - _$constants_212.idRegex.y.toString() - ], - - editType: 'plot', - - }, - layer: { - valType: 'enumerated', - values: ['above traces', 'below traces'], - dflt: 'above traces', - - editType: 'plot', - - }, - domain: { - valType: 'info_array', - - items: [ - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} - ], - dflt: [0, 1], - editType: 'plot+margins', - - }, - position: { - valType: 'number', - min: 0, - max: 1, - dflt: 0, - - editType: 'plot+margins', - - }, - categoryorder: { - valType: 'enumerated', - values: [ - 'trace', 'category ascending', 'category descending', 'array' - /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later - ], - dflt: 'trace', - - editType: 'calc', - - }, - categoryarray: { - valType: 'data_array', - - editType: 'calc', - - }, - editType: 'calc', + if(yanchor === 'bottom') y = 0; + else if(yanchor === 'middle') y = 1; + else if(yanchor === 'top') y = 2; + else y = _$lib_166.constrain(Math.floor(y * 3), 0, 2); - _deprecated: { - autotick: { - valType: 'boolean', - - editType: 'ticks+margins', - - } - } + return cursorset[y][x]; }; -var _$color_46 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16993,342 +16660,331 @@ var _$color_46 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$tinycolor_28 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - -var color = _$color_46 = {}; - -/* removed: var _$attributes_45 = require('./attributes'); */; -color.defaults = _$attributes_45.defaults; -var defaultLine = color.defaultLine = _$attributes_45.defaultLine; -color.lightLine = _$attributes_45.lightLine; -var background = color.background = _$attributes_45.background; +var _$constants_83 = { + // hover labels for multiple horizontal bars get tilted by this angle + YANGLE: 60, -/* - * tinyRGB: turn a tinycolor into an rgb string, but - * unlike the built-in tinycolor.toRgbString this never includes alpha - */ -color.tinyRGB = function(tc) { - var c = tc.toRgb(); - return 'rgb(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ')'; -}; + // size and display constants for hover text -color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_28(cstr)); }; + // pixel size of hover arrows + HOVERARROWSIZE: 6, + // pixels padding around text + HOVERTEXTPAD: 3, + // hover font + HOVERFONTSIZE: 13, + HOVERFONT: 'Arial, sans-serif', -color.opacity = function(cstr) { return cstr ? _$tinycolor_28(cstr).getAlpha() : 0; }; + // minimum time (msec) between hover calls + HOVERMINTIME: 50, -color.addOpacity = function(cstr, op) { - var c = _$tinycolor_28(cstr).toRgb(); - return 'rgba(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; + // ID suffix (with fullLayout._uid) for hover events in the throttle cache + HOVERID: '-hover' }; -// combine two colors into one apparent color -// if back has transparency or is missing, -// color.background is assumed behind it -color.combine = function(front, back) { - var fc = _$tinycolor_28(front).toRgb(); - if(fc.a === 1) return _$tinycolor_28(front).toRgbString(); +// 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 bc = _$tinycolor_28(back || background).toRgb(), - bcflat = bc.a === 1 ? bc : { - r: 255 * (1 - bc.a) + bc.r * bc.a, - g: 255 * (1 - bc.a) + bc.g * bc.a, - b: 255 * (1 - bc.a) + bc.b * bc.a - }, - fcflat = { - r: bcflat.r * (1 - fc.a) + fc.r * fc.a, - g: bcflat.g * (1 - fc.a) + fc.g * fc.a, - b: bcflat.b * (1 - fc.a) + fc.b * fc.a - }; - return _$tinycolor_28(fcflat).toRgbString(); -}; +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +var _$EventEmitter_12 = EventEmitter; -/* - * Create a color that contrasts with cstr. - * - * If cstr is a dark color, we lighten it; if it's light, we darken. - * - * If lightAmount / darkAmount are used, we adjust by these percentages, - * otherwise we go all the way to white or black. - */ -color.contrast = function(cstr, lightAmount, darkAmount) { - var tc = _$tinycolor_28(cstr); +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - if(tc.getAlpha() !== 1) tc = _$tinycolor_28(color.combine(cstr, background)); +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - var newColor = tc.isDark() ? - (lightAmount ? tc.lighten(lightAmount) : background) : - (darkAmount ? tc.darken(darkAmount) : defaultLine); +// 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. +EventEmitter.defaultMaxListeners = 10; - return newColor.toString(); +// 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(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; }; -color.stroke = function(s, c) { - var tc = _$tinycolor_28(c); - s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); -}; +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; -color.fill = function(s, c) { - var tc = _$tinycolor_28(c); - s.style({ - 'fill': color.tinyRGB(tc), - 'fill-opacity': tc.getAlpha() - }); -}; + if (!this._events) + this._events = {}; -// search container for colors with the deprecated rgb(fractions) format -// and convert them to rgb(0-255 values) -color.clean = function(container) { - if(!container || typeof container !== 'object') return; + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - var keys = Object.keys(container), - i, - j, - key, - val; + handler = this._events[type]; - for(i = 0; i < keys.length; i++) { - key = keys[i]; - val = container[key]; + if (isUndefined(handler)) + return false; - // only sanitize keys that end in "color" or "colorscale" - if(key.substr(key.length - 5) === 'color') { - if(Array.isArray(val)) { - for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); - } - else container[key] = cleanOne(val); - } - else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { - // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] - for(j = 0; j < val.length; j++) { - if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); - } - } - // recurse into arrays of objects, and plain objects - else if(Array.isArray(val)) { - var el0 = val[0]; - if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { - for(j = 0; j < val.length; j++) color.clean(val[j]); - } - } - else if(val && typeof val === 'object') color.clean(val); + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; }; -function cleanOne(val) { - if(_$fastIsnumeric_13(val) || typeof val !== 'string') return val; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - var valTrim = val.trim(); - if(valTrim.substr(0, 3) !== 'rgb') return val; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); - if(!match) return val; + if (!this._events) + this._events = {}; - var parts = match[1].trim().split(/\s*[\s,]\s*/), - rgba = valTrim.charAt(3) === 'a' && parts.length === 4; - if(!rgba && parts.length !== 3) return val; + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - for(var i = 0; i < parts.length; i++) { - if(!parts[i].length) return val; - parts[i] = Number(parts[i]); + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - // all parts must be non-negative numbers - if(!(parts[i] >= 0)) return val; - // alpha>1 gets clipped to 1 - if(i === 3) { - if(parts[i] > 1) parts[i] = 1; - } - // r, g, b must be < 1 (ie 1 itself is not allowed) - else if(parts[i] >= 1) return val; + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; } - var rgbStr = Math.round(parts[0] * 255) + ', ' + - Math.round(parts[1] * 255) + ', ' + - Math.round(parts[2] * 255); - - if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; - return 'rgb(' + rgbStr + ')'; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + return this; +}; -var _$handleCategoryOrderDefaults_211 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - var arrayIn = containerIn.categoryarray, - orderDefault; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + var fired = false; - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; + function g() { + this.removeListener(type, g); - var order = coerce('categoryorder', orderDefault); + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + g.listener = listener; + this.on(type, g); - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } + return this; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; -'use strict'; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -var colorMix = _$tinycolor_28.mix; -var lightFraction = _$attributes_45.lightFraction; -/* removed: var _$lib_165 = require('../../lib'); */; + if (!this._events || !this._events[type]) + return this; -/** - * @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 - */ -var _$handleLineGridDefaults_221 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; + list = this._events[type]; + length = list.length; + position = -1; - var dfltColor = opts.dfltColor; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - function coerce2(attr, dflt) { - return _$lib_165.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - var lineColor = coerce2('linecolor', dfltColor); - var lineWidth = coerce2('linewidth'); - var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); + if (position < 0) + return this; - if(!showLine) { - delete containerOut.linecolor; - delete containerOut.linewidth; + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } - 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 (this._events.removeListener) + this.emit('removeListener', type, listener); + } - if(!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } + return this; +}; - if(!opts.noZeroLine) { - var zeroLineColor = coerce2('zerolinecolor', dfltColor); - var zeroLineWidth = coerce2('zerolinewidth'); - var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } -}; + if (!this._events) + return this; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_10 = require('d3'); */; - -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { - - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. - - var categoryArray = []; - - var traceLines = data.map(function(d) {return d[axisLetter];}); - - var i, j, tracePoints, category, insertionIndex; - - var bisector = _$d3_10.bisector(sortFunction).left; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - for(i = 0; i < traceLines.length; i++) { + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - tracePoints = traceLines[i]; + listeners = this._events[type]; - for(j = 0; j < tracePoints.length; j++) { + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - category = tracePoints[j]; + return this; +}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - insertionIndex = bisector(categoryArray, category); +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } - } +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; - return categoryArray; +function isFunction(arg) { + return typeof arg === 'function'; } +function isNumber(arg) { + return typeof arg === 'number'; +} -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ - -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_222 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_10.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_10.descending, data); - case 'trace': return []; - default: return []; - } -}; +function isUndefined(arg) { + return arg === void 0; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -17341,593 +16997,507 @@ var _$orderedCategories_222 = function orderedCategories(axisLetter, categoryord 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - -/* removed: var _$lib_165 = require('../../lib'); */; -var cleanNumber = _$lib_165.cleanNumber; -var ms2DateTime = _$lib_165.ms2DateTime; -var dateTime2ms = _$lib_165.dateTime2ms; -var ensureNumber = _$lib_165.ensureNumber; +/* global jQuery:false */ -/* removed: var _$numerical_148 = require('../../constants/numerical'); */; -var __FP_SAFE_226 = _$numerical_148.FP_SAFE; -var __BADNUM_226 = _$numerical_148.BADNUM; +var __EventEmitter_159 = _$EventEmitter_12.EventEmitter; -/* removed: var _$constants_212 = require('./constants'); */; -/* removed: var _$axis_ids_210 = require('./axis_ids'); */; +var Events = { -function fromLog(v) { - return Math.pow(10, v); -} + init: function(plotObj) { -/** - * 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 autorange bounds ._min and ._max - * and the autotick constraints ._minDtick, ._forceTick0 - */ -var _$setConvert_226 = function setConvert(ax, fullLayout) { - fullLayout = fullLayout || {}; + /* + * If we have already instantiated an emitter for this plot + * return early. + */ + if(plotObj._ev instanceof __EventEmitter_159) return plotObj; - var axLetter = (ax._id || 'x').charAt(0); + var ev = new __EventEmitter_159(); + var internalEv = new __EventEmitter_159(); - // clipMult: how many axis lengths past the edge do we render? - // for panning, 1-2 would suffice, but for zooming more is nice. - // also, clipping can affect the direction of lines off the edge... - var clipMult = 10; + /* + * Assign to plot._ev while we still live in a land + * where plot is a DOM element with stuff attached to it. + * In the future we can make plot the event emitter itself. + */ + plotObj._ev = ev; - function toLog(v, clip) { - if(v > 0) return Math.log(v) / Math.LN10; + /* + * Create a second event handler that will manage events *internally*. + * This allows parts of plotly to respond to thing like relayout without + * having to use the user-facing event handler. They cannot peacefully + * coexist on the same handler because a user invoking + * plotObj.removeAllListeners() would detach internal events, breaking + * plotly. + */ + plotObj._internalEv = internalEv; - else if(v <= 0 && clip && ax.range && ax.range.length === 2) { - // clip NaN (ie past negative infinity) to clipMult axis - // length past the negative edge - var r0 = ax.range[0], - r1 = ax.range[1]; - return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); - } + /* + * Assign bound methods from the ev to the plot object. These methods + * will reference the 'this' of plot._ev even though they are methods + * of plot. This will keep the event machinery away from the plot object + * which currently is often a DOM element but presents an API that will + * continue to function when plot becomes an emitter. Not all EventEmitter + * methods have been bound to `plot` as some do not currently add value to + * the Plotly event API. + */ + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - else return __BADNUM_226; - } + /* + * Create funtions for managing internal events. These are *only* triggered + * by the mirroring of external events via the emit function. + */ + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); - /* - * 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_226) { - if(_$fastIsnumeric_13(v)) ms = dateTime2ms(new Date(+v)); - else return __BADNUM_226; - } - return ms; - } + /* + * We must wrap emit to continue to support JQuery events. The idea + * is to check to see if the user is using JQuery events, if they are + * we emit JQuery events to trigger user handlers as well as the EventEmitter + * events. + */ + plotObj.emit = function(event, data) { + if(typeof jQuery !== 'undefined') { + jQuery(plotObj).trigger(event, data); + } - // wrapped ms2DateTime to insert default ax.calendar - function ms2dt(v, r, calendar) { - return ms2DateTime(v, r, calendar || ax.calendar); - } + ev.emit(event, data); + internalEv.emit(event, data); + }; - function getCategoryName(v) { - return ax._categories[Math.round(v)]; - } + return plotObj; + }, /* - * 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. + * This function behaves like jQueries triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. * - * 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 + * Note: triggerHandler has been recommended for deprecation in v2.0.0, + * so the additional behavior of triggerHandler triggering internal events + * is deliberate excluded in order to avoid reinforcing more usage. */ - function setCategoryIndex(v) { - if(v !== null && v !== undefined) { - if(ax._categoriesMap === undefined) { - ax._categoriesMap = {}; - } + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + /* + * If Jquery exists run all its handlers for this event and + * collect the return value of the LAST handler function + */ + if(typeof jQuery !== 'undefined') { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } - if(ax._categoriesMap[v] !== undefined) { - return ax._categoriesMap[v]; - } else { - ax._categories.push(v); + /* + * Now run all the node style event handlers + */ + var ev = plotObj._ev; + if(!ev) return jQueryHandlerValue; - var curLength = ax._categories.length - 1; - ax._categoriesMap[v] = curLength; + var handlers = ev._events[event]; + if(!handlers) return jQueryHandlerValue; - return curLength; - } - } - return __BADNUM_226; - } + /* + * handlers can be function or an array of functions + */ + if(typeof handlers === 'function') handlers = [handlers]; + var lastHandler = handlers.pop(); - function getCategoryIndex(v) { - // d2l/d2c variant that that won't add categories but will also - // allow numbers to be mapped to the linearized axis positions - if(ax._categoriesMap) { - var index = ax._categoriesMap[v]; - if(index !== undefined) return index; + /* + * Call all the handlers except the last one. + */ + for(var i = 0; i < handlers.length; i++) { + handlers[i](data); } - if(_$fastIsnumeric_13(v)) return +v; - } - - function l2p(v) { - if(!_$fastIsnumeric_13(v)) return __BADNUM_226; - - // include 2 fractional digits on pixel, for PDF zooming etc - return _$d3_10.round(ax._b + ax._m * v, 2); - } + /* + * Now call the final handler and collect its value + */ + nodeEventHandlerValue = lastHandler(data); - function p2l(px) { return (px - ax._b) / ax._m; } + /* + * Return either the jquery handler value if it exists or the + * nodeEventHandler value. Jquery event value superceeds nodejs + * events for backwards compatability reasons. + */ + return jQueryHandlerValue !== undefined ? jQueryHandlerValue : + nodeEventHandlerValue; + }, - // 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; + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; - ax.l2p = l2p; - ax.p2l = p2l; + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; - 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; + return plotObj; + } - /* - * 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; +var _$Events_159 = Events; - 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)); }; +var _$unhover_69 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ax.d2c = ax.r2l = cleanNumber; - ax.c2d = ax.l2r = ensureNumber; - ax.c2r = toLog; - ax.l2d = fromLog; +'use strict'; - 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; +/* removed: var _$Events_159 = require('../../lib/events'); */; +/* removed: var _$throttle_188 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_164 = require('../../lib/get_graph_div'); */; - ax.cleanPos = ensureNumber; - } - else if(ax.type === 'date') { - // r and d are date strings, l and c are ms +/* removed: var _$constants_83 = require('../fx/constants'); */; - /* - * 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_165.identity; +var unhover = _$unhover_69 = {}; - 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); }; +unhover.wrapped = function(gd, evt, subplot) { + gd = _$get_graph_div_164(gd); - ax.cleanPos = function(v) { return _$lib_165.cleanDate(v, __BADNUM_226, ax.calendar); }; + // Important, clear any queued hovers + if(gd._fullLayout) { + _$throttle_188.clear(gd._fullLayout._uid + _$constants_83.HOVERID); } - 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; + unhover.raw(gd, evt, subplot); +}; - ax.d2r = ax.d2l_noadd = getCategoryIndex; - ax.r2c = function(v) { - var index = getCategoryIndex(v); - return index !== undefined ? index : ax.fraction2r(0.5); - }; +// remove hover effects on mouse out, and emit unhover event +unhover.raw = function unhoverRaw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; - ax.l2r = ax.c2r = ensureNumber; - ax.r2l = getCategoryIndex; + if(!evt) evt = {}; + if(evt.target && + _$Events_159.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - 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; + fullLayout._hoverlayer.selectAll('g').remove(); + fullLayout._hoverlayer.selectAll('line').remove(); + fullLayout._hoverlayer.selectAll('circle').remove(); + gd._hoverdata = undefined; - ax.cleanPos = function(v) { - if(typeof v === 'string' && v !== '') return v; - return ensureNumber(v); - }; + if(evt.target && oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } +}; - // find the range value at the specified (linear) fraction of the axis - ax.fraction2r = function(v) { - var rl0 = ax.r2l(ax.range[0]), - 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]), - rl1 = ax.r2l(ax.range[1]); - return (ax.r2l(v) - rl0) / (rl1 - rl0); - }; +var _$dragelement_68 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* - * 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_165.nestedProperty(ax, rangeAttr).get(); - var i, dflt; +'use strict'; - if(ax.type === 'date') dflt = _$lib_165.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_212.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_212.DFLTRANGEX; +/* removed: var _$mouseEventOffset_18 = require('mouse-event-offset'); */; +/* removed: var _$hasHover_15 = require('has-hover'); */; +/* removed: var _$hasPassiveEvents_16 = require('has-passive-events'); */; - // make sure we don't later mutate the defaults - dflt = dflt.slice(); +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; - if(!range || range.length !== 2) { - _$lib_165.nestedProperty(ax, rangeAttr).set(dflt); - return; - } +/* removed: var _$constants_213 = require('../../plots/cartesian/constants'); */; +/* removed: var _$interactions_147 = require('../../constants/interactions'); */; - if(ax.type === 'date') { - // check if milliseconds or js date objects are provided for range - // and convert to date strings - range[0] = _$lib_165.cleanDate(range[0], __BADNUM_226, ax.calendar); - range[1] = _$lib_165.cleanDate(range[1], __BADNUM_226, ax.calendar); - } +var dragElement = _$dragelement_68 = {}; - for(i = 0; i < 2; i++) { - if(ax.type === 'date') { - if(!_$lib_165.isDateTime(range[i], ax.calendar)) { - ax[rangeAttr] = dflt; - break; - } +dragElement.align = _$align_66; +dragElement.getCursor = _$getCursor_67; - if(ax.r2l(range[0]) === ax.r2l(range[1])) { - // split by +/- 1 second - var linCenter = _$lib_165.constrain(ax.r2l(range[0]), - _$lib_165.MIN_MS + 1000, _$lib_165.MAX_MS - 1000); - range[0] = ax.l2r(linCenter - 1000); - range[1] = ax.l2r(linCenter + 1000); - break; - } - } - else { - if(!_$fastIsnumeric_13(range[i])) { - if(_$fastIsnumeric_13(range[1 - i])) { - range[i] = range[1 - i] * (i ? 10 : 0.1); - } - else { - ax[rangeAttr] = dflt; - break; - } - } +/* removed: var _$unhover_69 = require('./unhover'); */; +dragElement.unhover = _$unhover_69.wrapped; +dragElement.unhoverRaw = _$unhover_69.raw; - if(range[i] < -__FP_SAFE_226) range[i] = -__FP_SAFE_226; - else if(range[i] > __FP_SAFE_226) range[i] = __FP_SAFE_226; - 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; - - // TODO cleaner way to handle this case - if(!ax._categories) ax._categories = []; - // Add a map to optimize the performance of category collection - if(!ax._categoriesMap) ax._categoriesMap = {}; +/** + * 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 DBLCLICKDELAY = _$interactions_147.DBLCLICKDELAY; + var element = options.element; - // make sure we have a domain (pull it in from the axis - // this one is overlaying if necessary) - if(ax.overlaying) { - var ax2 = _$axis_ids_210.getFromId({ _fullLayout: fullLayout }, ax.overlaying); - ax.domain = ax2.domain; - } + var startX, + startY, + newMouseDownTime, + cursor, + dragCover, + initialEvent, + initialTarget, + rightClick; - // 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', - calendar = ax.calendar; - ax.cleanRange(rangeAttr); + if(!gd._mouseDownTime) gd._mouseDownTime = 0; - var rl0 = ax.r2l(ax[rangeAttr][0], calendar), - rl1 = ax.r2l(ax[rangeAttr][1], calendar); + element.style.pointerEvents = 'all'; - 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; - } + element.onmousedown = onStart; - if(!isFinite(ax._m) || !isFinite(ax._b)) { - fullLayout._replotting = false; - throw new Error('Something went wrong with axis scaling'); + if(!_$hasPassiveEvents_16) { + element.ontouchstart = onStart; + } + else { + if(element._ontouchstart) { + element.removeEventListener('touchstart', element._ontouchstart); } - }; + element._ontouchstart = onStart; + element.addEventListener('touchstart', onStart, {passive: false}); + } - // 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; + function _clampFn(dx, dy, minDrag) { + if(Math.abs(dx) < minDrag) dx = 0; + if(Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } - var axType = ax.type; - var cal = axType === 'date' && trace[axLetter + 'calendar']; + var clampFn = options.clampFn || _clampFn; - if(axLetter in trace) { - arrayIn = trace[axLetter]; - len = trace._length || arrayIn.length; + function onStart(e) { + e.preventDefault(); - if(_$lib_165.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { - if(len === arrayIn.length) { - return arrayIn; - } else if(arrayIn.subarray) { - return arrayIn.subarray(0, len); - } - } + // 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; - arrayOut = new Array(len); - for(i = 0; i < len; i++) { - arrayOut[i] = ax.d2c(arrayIn[i], 0, cal); - } + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { + // in a click train + numClicks += 1; } 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; - } + // new click train + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; } - return arrayOut; - }; + if(options.prepFn) options.prepFn(e, startX, startY); - ax.isValidRange = function(range) { - return ( - Array.isArray(range) && - range.length === 2 && - _$fastIsnumeric_13(ax.r2l(range[0])) && - _$fastIsnumeric_13(ax.r2l(range[1])) - ); - }; + if(_$hasHover_15 && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } + else if(!_$hasHover_15) { + // 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; + } - ax.isPtWithinRange = function(d, calendar) { - var coord = ax.c2l(d[axLetter], null, calendar); + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onDone); + document.addEventListener('touchmove', onMove); + document.addEventListener('touchend', onDone); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); - }; + return; + } - ax.clearCalc = function() { - // for autoranging: arrays of objects: - // { - // val: axis value, - // pad: pixel padding, - // extrapad: boolean, should this val get 5% additional padding - // } - ax._min = []; - ax._max = []; + function onMove(e) { + e.preventDefault(); - // initialize the category list, if there is one, so we start over - // to be filled in later by ax.d2c - ax._categories = (ax._initialCategories || []).slice(); + var offset = pointerOffset(e); + var minDrag = options.minDrag || _$constants_213.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; - // Build the lookup map for initialized categories - ax._categoriesMap = {}; - for(var j = 0; j < ax._categories.length; j++) { - ax._categoriesMap[ax._categories[j]] = j; + if(dx || dy) { + gd._dragged = true; + dragElement.unhover(gd); } - }; - // 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_10.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_10.format; + if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); - // and for bar charts and box plots: reset forced minimum tick spacing - delete ax._minDtick; - delete ax._forceTick0; -}; + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function onDone(e) { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onDone); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onDone); + e.preventDefault(); -'use strict'; + if(_$hasHover_15) { + _$lib_166.removeElement(dragCover); + } + else if(cursor) { + dragCover.documentElement.style.cursor = cursor; + cursor = null; + } -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$layout_attributes_219 = require('./layout_attributes'); */; + if(!gd._dragging) { + gd._dragged = false; + return; + } + gd._dragging = false; -var _$handleTickLabelDefaults_227 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { - var showAttrDflt = getShowAttrDflt(containerIn); + // don't count as a dblClick unless the mouseUp is also within + // the dblclick delay + if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - var tickPrefix = coerce('tickprefix'); - if(tickPrefix) coerce('showtickprefix', showAttrDflt); + if(gd._dragged) { + if(options.doneFn) options.doneFn(e); + } + else { + if(options.clickFn) options.clickFn(numClicks, initialEvent); - var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); - if(tickSuffix) coerce('showticksuffix', showAttrDflt); + // 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; - var showTickLabels = coerce('showticklabels'); - if(showTickLabels) { - var font = options.font || {}; - // as with titlefont.color, inherit axis.color only if one was - // explicitly provided - var dfltFontColor = (containerOut.color === containerIn.color) ? - containerOut.color : font.color; - _$lib_165.coerceFont(coerce, 'tickfont', { - family: font.family, - size: font.size, - color: dfltFontColor - }); - coerce('tickangle'); + 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); + } - if(axType !== 'category') { - var tickFormat = coerce('tickformat'); - tickformatstopsDefaults(containerIn, containerOut); - if(!tickFormat && axType !== 'date') { - coerce('showexponent', showAttrDflt); - coerce('exponentformat'); - coerce('separatethousands'); + initialTarget.dispatchEvent(e2); } } - } -}; -/* - * 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'], - showAttrs = showAttrsAll.filter(function(a) { - return containerIn[a] !== undefined; - }), - sameVal = function(a) { - return containerIn[a] === containerIn[showAttrs[0]]; - }; + finishDrag(gd); - if(showAttrs.every(sameVal) || showAttrs.length === 1) { - return containerIn[showAttrs[0]]; + gd._dragged = false; + + return; } -} +}; -function tickformatstopsDefaults(tickformatIn, tickformatOut) { - var valuesIn = tickformatIn.tickformatstops; - var valuesOut = tickformatOut.tickformatstops = []; +function coverSlip() { + var cover = document.createElement('div'); - if(!Array.isArray(valuesIn)) return; + 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'; - var valueIn, valueOut; + document.body.appendChild(cover); - function coerce(attr, dflt) { - return _$lib_165.coerce(valueIn, valueOut, _$layout_attributes_219.tickformatstops, attr, dflt); - } + return cover; +} - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; +dragElement.coverSlip = coverSlip; - coerce('dtickrange'); - coerce('value'); +function finishDrag(gd) { + gd._dragging = false; + if(gd._replotPending) _$registry_248.call('plot', gd); +} - valuesOut.push(valueOut); - } +function pointerOffset(e) { + return _$mouseEventOffset_18( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); } /** @@ -17938,30 +17508,54 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -/* removed: var _$layout_attributes_219 = require('./layout_attributes'); */; +var _$calc_81 = function calc(gd) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; + function makeCoerceHoverInfo(trace) { + return function(val) { + return _$lib_166.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + }; + } -/** - * options: inherits outerTicks from axes.handleAxisDefaults - */ -var _$handleTickDefaults_228 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_165.coerce2(containerIn, containerOut, _$layout_attributes_219, 'ticklen'), - tickWidth = _$lib_165.coerce2(containerIn, containerOut, _$layout_attributes_219, 'tickwidth'), - tickColor = _$lib_165.coerce2(containerIn, containerOut, _$layout_attributes_219, 'tickcolor', containerOut.color), - showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; - if(!showTicks) { - delete containerOut.ticklen; - delete containerOut.tickwidth; - delete containerOut.tickcolor; + // 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_248.traceIs(trace, 'pie')) continue; + + var fillFn = _$registry_248.traceIs(trace, '2dMap') ? paste : _$lib_166.fillArray; + + fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + + 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'); } }; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || _$lib_166.identity; + + if(Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} + +var _$color_46 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17973,178 +17567,164 @@ var _$handleTickDefaults_228 = function handleTickDefaults(containerIn, containe 'use strict'; +/* removed: var _$tinycolor_28 = require('tinycolor2'); */; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -var __ONEDAY_229 = _$numerical_148.ONEDAY; +var color = _$color_46 = {}; -var _$handleTickValueDefaults_229 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { - var tickmodeDefault = 'auto'; +/* removed: var _$attributes_45 = require('./attributes'); */; +color.defaults = _$attributes_45.defaults; +var defaultLine = color.defaultLine = _$attributes_45.defaultLine; +color.lightLine = _$attributes_45.lightLine; +var background = color.background = _$attributes_45.background; - if(containerIn.tickmode === 'array' && - (axType === 'log' || axType === 'date')) { - containerIn.tickmode = 'auto'; - } +/* + * tinyRGB: turn a tinycolor into an rgb string, but + * unlike the built-in tinycolor.toRgbString this never includes alpha + */ +color.tinyRGB = function(tc) { + var c = tc.toRgb(); + return 'rgb(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ')'; +}; - if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; - else if(containerIn.dtick) { - tickmodeDefault = 'linear'; - } - var tickmode = coerce('tickmode', tickmodeDefault); +color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_28(cstr)); }; - if(tickmode === 'auto') coerce('nticks'); - else if(tickmode === 'linear') { - // dtick is usually a positive number, but there are some - // special strings available for log or date axes - // default is 1 day for dates, otherwise 1 - var dtickDflt = (axType === 'date') ? __ONEDAY_229 : 1; - var dtick = coerce('dtick', dtickDflt); - if(_$fastIsnumeric_13(dtick)) { - containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; - } - else if(typeof dtick !== 'string') { - containerOut.dtick = dtickDflt; - } - else { - // date and log special cases are all one character plus a number - var prefix = dtick.charAt(0), - dtickNum = dtick.substr(1); +color.opacity = function(cstr) { return cstr ? _$tinycolor_28(cstr).getAlpha() : 0; }; - dtickNum = _$fastIsnumeric_13(dtickNum) ? Number(dtickNum) : 0; - if((dtickNum <= 0) || !( - // "M" gives ticks every (integer) n months - (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || - // "L" gives ticks linearly spaced in data (not in position) every (float) f - (axType === 'log' && prefix === 'L') || - // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 - (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) - )) { - containerOut.dtick = dtickDflt; - } - } - - // tick0 can have different valType for different axis types, so - // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_165.dateTick0(containerOut.calendar) : 0; - var tick0 = coerce('tick0', tick0Dflt); - if(axType === 'date') { - containerOut.tick0 = _$lib_165.cleanDate(tick0, tick0Dflt); - } - // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely - else if(_$fastIsnumeric_13(tick0) && dtick !== 'D1' && dtick !== 'D2') { - containerOut.tick0 = Number(tick0); - } - else { - containerOut.tick0 = tick0Dflt; - } - } - else { - var tickvals = coerce('tickvals'); - if(tickvals === undefined) containerOut.tickmode = 'auto'; - else coerce('ticktext'); - } +color.addOpacity = function(cstr, op) { + var c = _$tinycolor_28(cstr).toRgb(); + return 'rgba(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; +// combine two colors into one apparent color +// if back has transparency or is missing, +// color.background is assumed behind it +color.combine = function(front, back) { + var fc = _$tinycolor_28(front).toRgb(); + if(fc.a === 1) return _$tinycolor_28(front).toRgbString(); -/* removed: var _$layout_attributes_219 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_229 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_228 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_227 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_211 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_221 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_226 = require('./set_convert'); */; -/* removed: var _$orderedCategories_222 = require('./ordered_categories'); */; + var bc = _$tinycolor_28(back || background).toRgb(), + bcflat = bc.a === 1 ? bc : { + r: 255 * (1 - bc.a) + bc.r * bc.a, + g: 255 * (1 - bc.a) + bc.g * bc.a, + b: 255 * (1 - bc.a) + bc.b * bc.a + }, + fcflat = { + r: bcflat.r * (1 - fc.a) + fc.r * fc.a, + g: bcflat.g * (1 - fc.a) + fc.g * fc.a, + b: bcflat.b * (1 - fc.a) + fc.b * fc.a + }; + return _$tinycolor_28(fcflat).toRgbString(); +}; -/** - * options: object containing: +/* + * Create a color that contrasts with cstr. * - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors + * If cstr is a dark color, we lighten it; if it's light, we darken. + * + * If lightAmount / darkAmount are used, we adjust by these percentages, + * otherwise we go all the way to white or black. */ -var _$handleAxisDefaults_209 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; - - var visible = coerce('visible', !options.cheateronly); +color.contrast = function(cstr, lightAmount, darkAmount) { + var tc = _$tinycolor_28(cstr); - var axType = containerOut.type; + if(tc.getAlpha() !== 1) tc = _$tinycolor_28(color.combine(cstr, background)); - if(axType === 'date') { - var handleCalendarDefaults = _$registry_247.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } + var newColor = tc.isDark() ? + (lightAmount ? tc.lighten(lightAmount) : background) : + (darkAmount ? tc.darken(darkAmount) : defaultLine); - _$setConvert_226(containerOut, layoutOut); + return newColor.toString(); +}; - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); +color.stroke = function(s, c) { + var tc = _$tinycolor_28(c); + s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); +}; - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; +color.fill = function(s, c) { + var tc = _$tinycolor_28(c); + s.style({ + 'fill': color.tinyRGB(tc), + 'fill-opacity': tc.getAlpha() + }); +}; - if(autoRange) coerce('rangemode'); +// search container for colors with the deprecated rgb(fractions) format +// and convert them to rgb(0-255 values) +color.clean = function(container) { + if(!container || typeof container !== 'object') return; - coerce('range'); - containerOut.cleanRange(); + var keys = Object.keys(container), + i, + j, + key, + val; - _$handleCategoryOrderDefaults_211(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_222(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + for(i = 0; i < keys.length; i++) { + key = keys[i]; + val = container[key]; + // only sanitize keys that end in "color" or "colorscale" + if(key.substr(key.length - 5) === 'color') { + if(Array.isArray(val)) { + for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); + } + else container[key] = cleanOne(val); + } + else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { + // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] + for(j = 0; j < val.length; j++) { + if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); + } + } + // recurse into arrays of objects, and plain objects + else if(Array.isArray(val)) { + var el0 = val[0]; + if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { + for(j = 0; j < val.length; j++) color.clean(val[j]); + } + } + else if(val && typeof val === 'object') color.clean(val); + } +}; - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); +function cleanOne(val) { + if(_$fastIsnumeric_13(val) || typeof val !== 'string') return val; - if(!visible) return containerOut; + var valTrim = val.trim(); + if(valTrim.substr(0, 3) !== 'rgb') return val; - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); + if(!match) return val; - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_165.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + var parts = match[1].trim().split(/\s*[\s,]\s*/), + rgba = valTrim.charAt(3) === 'a' && parts.length === 4; + if(!rgba && parts.length !== 3) return val; - _$handleTickValueDefaults_229(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_227(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_228(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_221(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_219 - }); + for(var i = 0; i < parts.length; i++) { + if(!parts[i].length) return val; + parts[i] = Number(parts[i]); - if(containerOut.showline || containerOut.ticks) coerce('mirror'); + // all parts must be non-negative numbers + if(!(parts[i] >= 0)) return val; + // alpha>1 gets clipped to 1 + if(i === 3) { + if(parts[i] > 1) parts[i] = 1; + } + // r, g, b must be < 1 (ie 1 itself is not allowed) + else if(parts[i] >= 1) return val; + } - if(options.automargin) coerce('automargin'); + var rgbStr = Math.round(parts[0] * 255) + ', ' + + Math.round(parts[1] * 255) + ', ' + + Math.round(parts[2] * 255); - return containerOut; -}; + if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; + return 'rgb(' + rgbStr + ')'; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -18154,150 +17734,87 @@ var _$handleAxisDefaults_209 = function handleAxisDefaults(containerIn, containe * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -var id2name = _$axis_ids_210.id2name; - - -var _$handleConstraintDefaults_213 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); - - if(containerOut.fixedrange) return; - - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_165.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); - - if(!containerIn.scaleanchor) return; - - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - - var scaleanchor = _$lib_165.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); - - 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, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_165.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.'); +var _$attributes_52 = { + zauto: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + impliedEdits: {zmin: undefined, zmax: undefined}, + + }, + zmin: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + zmax: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + colorscale: { + valType: 'colorscale', + + editType: 'calc', + impliedEdits: {autocolorscale: false}, + + }, + autocolorscale: { + valType: 'boolean', + + dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. + editType: 'calc', + impliedEdits: {colorscale: undefined}, + + }, + reversescale: { + valType: 'boolean', + + dflt: false, + editType: 'calc', + + }, + showscale: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + } }; -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. - - 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 && !axj.fixedrange) linkableAxes.push(idj); - } - - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[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}; -} - +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * 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); - } +'use strict'; - var thisGroupKeys = Object.keys(thisGroup); +var _$flipScale_58 = function flipScale(scl) { + var N = scl.length, + sclNew = new Array(N), + si; - // 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; - } + for(var i = N - 1, j = 0; i >= 0; i--, j++) { + si = scl[i]; + sclNew[j] = [1 - si[0], si[1]]; } - // 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; -} + return sclNew; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -18310,76 +17827,71 @@ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$scales_65 = require('./scales'); */; +/* removed: var _$flipScale_58 = require('./flip_scale'); */; -var _$handlePositionDefaults_223 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; +var _$calc_53 = function calc(trace, vals, containerStr, cLetter) { + var container, inputContainer; - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } + if(containerStr) { + container = _$lib_166.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_166.nestedProperty(trace._input, containerStr).get(); + } + else { + container = trace; + inputContainer = trace._input; } - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_13(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; - - var anchor = _$lib_165.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); - - if(anchor === 'free') coerce('position', dfltPosition); + var autoAttr = cLetter + 'auto', + minAttr = cLetter + 'min', + maxAttr = cLetter + 'max', + auto = container[autoAttr], + min = container[minAttr], + max = container[maxAttr], + scl = container.colorscale; - _$lib_165.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); + if(auto !== false || min === undefined) { + min = _$lib_166.aggNums(Math.min, null, vals); + } - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_165.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); + if(auto !== false || max === undefined) { + max = _$lib_166.aggNums(Math.max, null, vals); } - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_165.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + if(min === max) { + min -= 0.5; + max += 0.5; } - coerce('layer'); + container[minAttr] = min; + container[maxAttr] = max; - return containerOut; + inputContainer[minAttr] = min; + inputContainer[maxAttr] = max; + + /* + * If auto was explicitly false but min or max was missing, + * we filled in the missing piece here but later the trace does + * not look auto. + * Otherwise make sure the trace still looks auto as far as later + * changes are concerned. + */ + inputContainer[autoAttr] = (auto !== false || + (min === undefined && max === undefined)); + + if(container.autocolorscale) { + if(min * max < 0) scl = _$scales_65.RdBu; + else if(min >= 0) scl = _$scales_65.Reds; + else scl = _$scales_65.Blues; + + // reversescale is handled at the containerOut level + inputContainer.colorscale = scl; + if(container.reversescale) scl = _$flipScale_58(scl); + container.colorscale = scl; + } }; /** @@ -18390,199 +17902,124 @@ var _$handlePositionDefaults_223 = function handlePositionDefaults(containerIn, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - -/* removed: var _$lib_165 = require('../../lib'); */; -var __BADNUM_208 = _$numerical_148.BADNUM; +/* removed: var _$lib_166 = require('../lib'); */; +var __extendFlat_193 = _$lib_166.extendFlat; +var __isPlainObject_193 = _$lib_166.isPlainObject; -var _$autoType_208 = function autoType(array, calendar) { - if(moreDates(array, calendar)) return 'date'; - if(category(array)) return 'category'; - if(linearOK(array)) return 'linear'; - else return '-'; +var traceOpts = { + valType: 'flaglist', + extras: ['none'], + flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'], + }; -// is there at least one number in array? If not, we should leave -// ax.type empty so it can be autoset later -function linearOK(array) { - if(!array) return false; - - for(var i = 0; i < array.length; i++) { - if(_$fastIsnumeric_13(array[i])) return true; - } +var layoutOpts = { + valType: 'flaglist', + extras: ['none'], + flags: [ + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', + 'layoutstyle', 'modebar', 'camera', 'arraydraw' + ], + +}; - return false; -} +// flags for inside restyle/relayout include a few extras +// that shouldn't be used in attributes, to deal with certain +// combinations and conditionals efficiently +var traceEditTypeFlags = traceOpts.flags.slice() + .concat(['clearCalc', 'fullReplot']); -// does the array a have mostly dates rather than numbers? -// note: some values can be neither (such as blanks, text) -// 2- or 4-digit integers can be both, so require twice as many -// dates as non-dates, to exclude cases with mostly 2 & 4 digit -// numbers and a few dates -function moreDates(a, calendar) { - var dcnt = 0, - ncnt = 0, - // test at most 1000 points, evenly spaced - inc = Math.max(1, (a.length - 1) / 1000), - ai; +var layoutEditTypeFlags = layoutOpts.flags.slice() + .concat('layoutReplot'); - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_165.isDateTime(ai, calendar)) dcnt += 1; - if(_$fastIsnumeric_13(ai)) ncnt += 1; - } +var _$edit_types_193 = { + traces: traceOpts, + layout: layoutOpts, + /* + * default (all false) edit flags for restyle (traces) + * creates a new object each call, so the caller can mutate freely + */ + traceFlags: function() { return falseObj(traceEditTypeFlags); }, - return (dcnt > ncnt * 2); -} + /* + * default (all false) edit flags for relayout + * creates a new object each call, so the caller can mutate freely + */ + layoutFlags: function() { return falseObj(layoutEditTypeFlags); }, -// are the (x,y)-values in gd.data mostly text? -// require twice as many categories as numbers -function category(a) { - // test at most 1000 points - var inc = Math.max(1, (a.length - 1) / 1000), - curvenums = 0, - curvecats = 0, - ai; + /* + * update `flags` with the `editType` values found in `attr` + */ + update: function(flags, attr) { + var editType = attr.editType; + if(editType && editType !== 'none') { + var editTypeParts = editType.split('+'); + for(var i = 0; i < editTypeParts.length; i++) { + flags[editTypeParts[i]] = true; + } + } + }, - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_165.cleanNumber(ai) !== __BADNUM_208) curvenums++; - else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; - } + overrideAll: overrideAll +}; - return curvecats > curvenums * 2; +function falseObj(keys) { + var out = {}; + for(var i = 0; i < keys.length; i++) out[keys[i]] = false; + return out; } /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$autoType_208 = require('./axis_autotype'); */; -var name2id = _$axis_ids_210.name2id; - -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored + * For attributes that are largely copied from elsewhere into a plot type that doesn't + * support partial redraws - overrides the editType field of all attributes in the object + * + * @param {object} attrs: the attributes to override. Will not be mutated. + * @param {string} editTypeOverride: the new editType to use + * @param {'nested'|'from-root'} overrideContainers: + * - 'nested' will override editType for nested containers but not the root. + * - 'from-root' will also override editType of the root container. + * Containers below the absolute top level (trace or layout root) DO need an + * editType even if they are not `valObject`s themselves (eg `scatter.marker`) + * to handle the case where you edit the whole container. + * + * @return {object} a new attributes object with `editType` modified as directed */ -var _$handleTypeDefaults_231 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } - - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; +function overrideAll(attrs, editTypeOverride, overrideContainers) { + var out = __extendFlat_193({}, attrs); + for(var key in out) { + var attr = out[key]; + if(__isPlainObject_193(attr)) { + out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } -}; - -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; - - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } - - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; - - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; - - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_247.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; - - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); - - if(trace[calAttr] !== calendar) calendar = undefined; - } + if(overrideContainers === 'from-root') out.editType = editTypeOverride; - ax.type = _$autoType_208(boxPositions, calendar); - } - else { - ax.type = _$autoType_208(d0[axLetter] || [d0[axLetter + '0']], calendar); - } + return out; } -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; +function overrideOne(attr, editTypeOverride, overrideContainers, key) { + if(attr.valType) { + var out = __extendFlat_193({}, attr); + out.editType = editTypeOverride; - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; + if(Array.isArray(attr.items)) { + out.items = new Array(attr.items.length); + for(var i = 0; i < attr.items.length; i++) { + out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root'); } } + return out; + } + else { + // don't provide an editType for the _deprecated container + return overrideAll(attr, editTypeOverride, + (key.charAt(0) === '_') ? 'nested' : 'from-root'); } } -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_247.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_247.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} - +var _$attributes_70 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18594,226 +18031,17 @@ function isBoxWithoutPositionCoords(trace, axLetter) { 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$layout_attributes_238 = require('../layout_attributes'); */; - -/* removed: var _$layout_attributes_219 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_231 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_209 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_213 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_223 = require('./position_defaults'); */; -/* removed: var _$axis_ids_210 = require('./axis_ids'); */; - - -var _$supplyLayoutDefaults_220 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; - - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - - if(!_$registry_247.traceIs(trace, 'cartesian') && !_$registry_247.traceIs(trace, 'gl2d')) { - continue; - } - - var xaName = _$axis_ids_210.id2name(trace.xaxis); - var yaName = _$axis_ids_210.id2name(trace.yaxis); - - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_247.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } - - // 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) xaCheater[xaName] = 1; - } - - // check for default formatting tweaks - if(_$registry_247.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } - - if(_$registry_247.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_165.simpleMap(xIds, _$axis_ids_210.id2name); - var yNames = _$lib_165.simpleMap(yIds, _$axis_ids_210.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 plot_bgcolor = _$color_46.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_165.coerce(layoutIn, layoutOut, _$layout_attributes_238, 'plot_bgcolor'); - } - - var bgColor = _$color_46.combine(plot_bgcolor, layoutOut.paper_bgcolor); - - var axName, axLetter, axLayoutIn, axLayoutOut; - - function coerce(attr, dflt) { - return _$lib_165.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_219, attr, dflt); - } - - function coerce2(attr, dflt) { - return _$lib_165.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_219, attr, dflt); - } - - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; - } - - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('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(_$axis_ids_210.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]; - - if(!_$lib_165.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; - - _$handleTypeDefaults_231(axLayoutIn, axLayoutOut, coerce, fullData, axName); - - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); - - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; - - _$handleAxisDefaults_209(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; - } - - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; - - _$handlePositionDefaults_223(axLayoutIn, axLayoutOut, coerce, positioningOptions); - - axLayoutOut._input = axLayoutIn; - } - - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_247.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_247.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[_$axis_ids_210.id2name(axLayoutOut.anchor)]; - - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); - - coerce('fixedrange', fixedRangeDflt); - } - - // Finally, handle scale constraints. 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 - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); - - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; - - _$handleConstraintDefaults_213(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } +_$attributes_70.dash = { + valType: 'string', + // string type usually doesn't take values... this one should really be + // a special type or at least a special coercion function, from the GUI + // you only get these values but elsewhere the user can supply a list of + // dash lengths in px, and it will be honored + values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], + dflt: 'solid', + + editType: 'style', + }; /** @@ -18826,509 +18054,507 @@ var _$supplyLayoutDefaults_220 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -var _$attributes_52 = { - zauto: { +/* removed: var _$font_attributes_234 = require('../font_attributes'); */; +/* removed: var _$attributes_45 = require('../../components/color/attributes'); */; +var dash = _$attributes_70.dash; +var __extendFlat_220 = _$extend_160.extendFlat; + +/* removed: var _$constants_213 = require('./constants'); */; + + +var _$layout_attributes_220 = { + visible: { valType: 'boolean', - dflt: true, - editType: 'calc', - impliedEdits: {zmin: undefined, zmax: undefined}, + editType: 'plot', }, - zmin: { - valType: 'number', + color: { + valType: 'color', + dflt: _$attributes_45.defaultLine, - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks', }, - zmax: { - valType: 'number', + title: { + valType: 'string', - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks+margins', }, - colorscale: { - valType: 'colorscale', + titlefont: _$font_attributes_234({ + editType: 'ticks+margins', + + }), + type: { + valType: 'enumerated', + // '-' means we haven't yet run autotype or couldn't find any data + // it gets turned into linear in gd._fullLayout but not copied back + // to gd.data like the others are. + values: ['-', 'linear', 'log', 'date', 'category'], + dflt: '-', editType: 'calc', - impliedEdits: {autocolorscale: false}, }, - autocolorscale: { - valType: 'boolean', + autorange: { + valType: 'enumerated', + values: [true, false, 'reversed'], + dflt: true, - dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. editType: 'calc', - impliedEdits: {colorscale: undefined}, + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - reversescale: { - valType: 'boolean', + rangemode: { + valType: 'enumerated', + values: ['normal', 'tozero', 'nonnegative'], + dflt: 'normal', - dflt: false, - editType: 'calc', + editType: 'plot', }, - showscale: { + range: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} + ], + editType: 'axrange+margins', + impliedEdits: {'autorange': false}, + + }, + fixedrange: { valType: 'boolean', + dflt: false, - dflt: true, editType: 'calc', - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var _$flipScale_58 = function flipScale(scl) { - var N = scl.length, - sclNew = new Array(N), - si; - - for(var i = N - 1, j = 0; i >= 0; i--, j++) { - si = scl[i]; - sclNew[j] = [1 - si[0], si[1]]; - } - - return sclNew; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_165 = require('../../lib'); */; - -/* removed: var _$scales_65 = require('./scales'); */; -/* removed: var _$flipScale_58 = require('./flip_scale'); */; - - -var _$calc_53 = function calc(trace, vals, containerStr, cLetter) { - var container, inputContainer; - - if(containerStr) { - container = _$lib_165.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_165.nestedProperty(trace._input, containerStr).get(); - } - else { - container = trace; - inputContainer = trace._input; - } - - var autoAttr = cLetter + 'auto', - minAttr = cLetter + 'min', - maxAttr = cLetter + 'max', - auto = container[autoAttr], - min = container[minAttr], - max = container[maxAttr], - scl = container.colorscale; - - if(auto !== false || min === undefined) { - min = _$lib_165.aggNums(Math.min, null, vals); - } - - if(auto !== false || max === undefined) { - max = _$lib_165.aggNums(Math.max, null, vals); - } - - if(min === max) { - min -= 0.5; - max += 0.5; - } - - container[minAttr] = min; - container[maxAttr] = max; - - inputContainer[minAttr] = min; - inputContainer[maxAttr] = max; - - /* - * If auto was explicitly false but min or max was missing, - * we filled in the missing piece here but later the trace does - * not look auto. - * Otherwise make sure the trace still looks auto as far as later - * changes are concerned. - */ - inputContainer[autoAttr] = (auto !== false || - (min === undefined && max === undefined)); - - if(container.autocolorscale) { - if(min * max < 0) scl = _$scales_65.RdBu; - else if(min >= 0) scl = _$scales_65.Reds; - else scl = _$scales_65.Blues; - - // reversescale is handled at the containerOut level - inputContainer.colorscale = scl; - if(container.reversescale) scl = _$flipScale_58(scl); - container.colorscale = scl; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_165 = require('../lib'); */; -var __extendFlat_192 = _$lib_165.extendFlat; -var __isPlainObject_192 = _$lib_165.isPlainObject; - -var traceOpts = { - valType: 'flaglist', - extras: ['none'], - flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'], - -}; - -var layoutOpts = { - valType: 'flaglist', - extras: ['none'], - flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', - 'layoutstyle', 'modebar', 'camera', 'arraydraw' - ], - -}; - -// flags for inside restyle/relayout include a few extras -// that shouldn't be used in attributes, to deal with certain -// combinations and conditionals efficiently -var traceEditTypeFlags = traceOpts.flags.slice() - .concat(['clearCalc', 'fullReplot']); - -var layoutEditTypeFlags = layoutOpts.flags.slice() - .concat('layoutReplot'); - -var _$edit_types_192 = { - traces: traceOpts, - layout: layoutOpts, - /* - * default (all false) edit flags for restyle (traces) - * creates a new object each call, so the caller can mutate freely - */ - traceFlags: function() { return falseObj(traceEditTypeFlags); }, - - /* - * default (all false) edit flags for relayout - * creates a new object each call, so the caller can mutate freely - */ - layoutFlags: function() { return falseObj(layoutEditTypeFlags); }, - - /* - * update `flags` with the `editType` values found in `attr` - */ - update: function(flags, attr) { - var editType = attr.editType; - if(editType && editType !== 'none') { - var editTypeParts = editType.split('+'); - for(var i = 0; i < editTypeParts.length; i++) { - flags[editTypeParts[i]] = true; - } - } }, - - overrideAll: overrideAll -}; - -function falseObj(keys) { - var out = {}; - for(var i = 0; i < keys.length; i++) out[keys[i]] = false; - return out; -} - -/** - * For attributes that are largely copied from elsewhere into a plot type that doesn't - * support partial redraws - overrides the editType field of all attributes in the object - * - * @param {object} attrs: the attributes to override. Will not be mutated. - * @param {string} editTypeOverride: the new editType to use - * @param {'nested'|'from-root'} overrideContainers: - * - 'nested' will override editType for nested containers but not the root. - * - 'from-root' will also override editType of the root container. - * Containers below the absolute top level (trace or layout root) DO need an - * editType even if they are not `valObject`s themselves (eg `scatter.marker`) - * to handle the case where you edit the whole container. - * - * @return {object} a new attributes object with `editType` modified as directed - */ -function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_192({}, attrs); - for(var key in out) { - var attr = out[key]; - if(__isPlainObject_192(attr)) { - out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); - } - } - if(overrideContainers === 'from-root') out.editType = editTypeOverride; - - return out; -} - -function overrideOne(attr, editTypeOverride, overrideContainers, key) { - if(attr.valType) { - var out = __extendFlat_192({}, attr); - out.editType = editTypeOverride; - - if(Array.isArray(attr.items)) { - out.items = new Array(attr.items.length); - for(var i = 0; i < attr.items.length; i++) { - out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root'); - } - } - return out; - } - else { - // don't provide an editType for the _deprecated container - return overrideAll(attr, editTypeOverride, - (key.charAt(0) === '_') ? 'nested' : 'from-root'); - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$layout_attributes_219 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -var __extendFlat_47 = _$extend_159.extendFlat; -var __overrideAll_47 = _$edit_types_192.overrideAll; - - -var _$attributes_47 = __overrideAll_47({ -// TODO: only right is supported currently -// orient: { -// valType: 'enumerated', -// -// values: ['left', 'right', 'top', 'bottom'], -// dflt: 'right', -// -// }, - thicknessmode: { + // scaleanchor: not used directly, just put here for reference + // values are any opposite-letter axis id + scaleanchor: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: [ + _$constants_213.idRegex.x.toString(), + _$constants_213.idRegex.y.toString() + ], - dflt: 'pixels', + editType: 'plot', }, - thickness: { + scaleratio: { valType: 'number', - min: 0, - dflt: 30, + dflt: 1, + + editType: 'plot', }, - lenmode: { + constrain: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: ['range', 'domain'], + dflt: 'range', - dflt: 'fraction', + editType: 'plot', }, - len: { - valType: 'number', + // constraintoward: not used directly, just put here for reference + constraintoward: { + valType: 'enumerated', + values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], + + editType: 'plot', + + }, + // ticks + tickmode: { + valType: 'enumerated', + values: ['auto', 'linear', 'array'], + + editType: 'ticks+margins', + impliedEdits: {tick0: undefined, dtick: undefined}, + + }, + nticks: { + valType: 'integer', min: 0, - dflt: 1, + dflt: 0, + editType: 'ticks+margins', }, - x: { - valType: 'number', - dflt: 1.02, - min: -2, - max: 3, + tick0: { + valType: 'any', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', + dtick: { + valType: 'any', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - xpad: { - valType: 'number', + tickvals: { + valType: 'data_array', + editType: 'ticks+margins', - min: 0, - dflt: 10, + }, + ticktext: { + valType: 'data_array', + editType: 'ticks+margins', }, - y: { - valType: 'number', + ticks: { + valType: 'enumerated', + values: ['outside', 'inside', ''], - dflt: 0.5, - min: -2, - max: 3, + editType: 'ticks+margins', }, - yanchor: { + mirror: { valType: 'enumerated', - values: ['top', 'middle', 'bottom'], + values: [true, 'ticks', false, 'all', 'allticks'], + dflt: false, - dflt: 'middle', + editType: 'ticks+layoutstyle', }, - ypad: { + ticklen: { valType: 'number', - min: 0, - dflt: 10, + dflt: 5, + + editType: 'ticks', }, - // a possible line around the bar itself - outlinecolor: _$layout_attributes_219.linecolor, - outlinewidth: _$layout_attributes_219.linewidth, - // Should outlinewidth have {dflt: 0} ? - // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_219.linecolor, - borderwidth: { + tickwidth: { valType: 'number', - min: 0, - dflt: 0, + dflt: 1, + + editType: 'ticks', }, - bgcolor: { + tickcolor: { valType: 'color', + dflt: _$attributes_45.defaultLine, - dflt: 'rgba(0,0,0,0)', + editType: 'ticks', + + }, + showticklabels: { + valType: 'boolean', + dflt: true, + + editType: 'ticks+margins', + + }, + automargin: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + showspikes: { + valType: 'boolean', + dflt: false, + + editType: 'modebar', + + }, + spikecolor: { + valType: 'color', + dflt: null, + + editType: 'none', + + }, + spikethickness: { + valType: 'number', + dflt: 3, + + editType: 'none', + + }, + spikedash: __extendFlat_220({}, dash, {dflt: 'dash', editType: 'none'}), + spikemode: { + valType: 'flaglist', + flags: ['toaxis', 'across', 'marker'], + + dflt: 'toaxis', + editType: 'none', + + }, + spikesnap: { + valType: 'enumerated', + values: ['data', 'cursor'], + dflt: 'data', + + editType: 'none', }, - // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_219.tickmode, - nticks: _$layout_attributes_219.nticks, - tick0: _$layout_attributes_219.tick0, - dtick: _$layout_attributes_219.dtick, - tickvals: _$layout_attributes_219.tickvals, - ticktext: _$layout_attributes_219.ticktext, - ticks: __extendFlat_47({}, _$layout_attributes_219.ticks, {dflt: ''}), - ticklen: _$layout_attributes_219.ticklen, - tickwidth: _$layout_attributes_219.tickwidth, - tickcolor: _$layout_attributes_219.tickcolor, - showticklabels: _$layout_attributes_219.showticklabels, tickfont: _$font_attributes_234({ + editType: 'ticks+margins', }), - tickangle: _$layout_attributes_219.tickangle, - tickformat: _$layout_attributes_219.tickformat, - tickformatstops: _$layout_attributes_219.tickformatstops, - tickprefix: _$layout_attributes_219.tickprefix, - showtickprefix: _$layout_attributes_219.showtickprefix, - ticksuffix: _$layout_attributes_219.ticksuffix, - showticksuffix: _$layout_attributes_219.showticksuffix, - separatethousands: _$layout_attributes_219.separatethousands, - exponentformat: _$layout_attributes_219.exponentformat, - showexponent: _$layout_attributes_219.showexponent, - title: { + tickangle: { + valType: 'angle', + dflt: 'auto', + + editType: 'ticks+margins', + + }, + tickprefix: { valType: 'string', + dflt: '', + editType: 'ticks+margins', }, - titlefont: _$font_attributes_234({ + showtickprefix: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - }), - titleside: { + editType: 'ticks+margins', + + }, + ticksuffix: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + showticksuffix: { valType: 'enumerated', - values: ['right', 'top', 'bottom'], + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - dflt: 'top', + editType: 'ticks+margins', - } -}, 'colorbars', 'from-root'); - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_229 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_228 = require('../../plots/cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_227 = require('../../plots/cartesian/tick_label_defaults'); */; - -/* removed: var _$attributes_47 = require('./attributes'); */; - - -var _$colorbarDefaults_49 = function colorbarDefaults(containerIn, containerOut, layout) { - var colorbarOut = containerOut.colorbar = {}, - colorbarIn = containerIn.colorbar || {}; - - function coerce(attr, dflt) { - return _$lib_165.coerce(colorbarIn, colorbarOut, _$attributes_47, attr, dflt); - } - - var thicknessmode = coerce('thicknessmode'); - coerce('thickness', (thicknessmode === 'fraction') ? - 30 / (layout.width - layout.margin.l - layout.margin.r) : - 30 - ); - - var lenmode = coerce('lenmode'); - coerce('len', (lenmode === 'fraction') ? - 1 : - layout.height - layout.margin.t - layout.margin.b - ); - - coerce('x'); - coerce('xanchor'); - coerce('xpad'); - coerce('y'); - coerce('yanchor'); - coerce('ypad'); - _$lib_165.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); - - coerce('outlinecolor'); - coerce('outlinewidth'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('bgcolor'); - - _$handleTickValueDefaults_229(colorbarIn, colorbarOut, coerce, 'linear'); - - var opts = {outerTicks: false, font: layout.font}; - _$handleTickLabelDefaults_227(colorbarIn, colorbarOut, coerce, 'linear', opts); - _$handleTickDefaults_228(colorbarIn, colorbarOut, coerce, 'linear', opts); + }, + showexponent: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', + + editType: 'ticks+margins', + + }, + exponentformat: { + valType: 'enumerated', + values: ['none', 'e', 'E', 'power', 'SI', 'B'], + dflt: 'B', + + editType: 'ticks+margins', + + }, + separatethousands: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + tickformat: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + tickformatstops: { + _isLinkedToArray: 'tickformatstop', - coerce('title', layout._dfltTitle.colorbar); - _$lib_165.coerceFont(coerce, 'titlefont', layout.font); - coerce('titleside'); + dtickrange: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'ticks+margins'}, + {valType: 'any', editType: 'ticks+margins'} + ], + editType: 'ticks+margins', + + }, + value: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + editType: 'ticks+margins' + }, + hoverformat: { + valType: 'string', + dflt: '', + + editType: 'none', + + }, + // lines and grids + showline: { + valType: 'boolean', + dflt: false, + + editType: 'layoutstyle', + + }, + linecolor: { + valType: 'color', + dflt: _$attributes_45.defaultLine, + + editType: 'layoutstyle', + + }, + linewidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks+layoutstyle', + + }, + showgrid: { + valType: 'boolean', + + editType: 'ticks', + + }, + gridcolor: { + valType: 'color', + dflt: _$attributes_45.lightLine, + + editType: 'ticks', + + }, + gridwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks', + + }, + zeroline: { + valType: 'boolean', + + editType: 'ticks', + + }, + zerolinecolor: { + valType: 'color', + dflt: _$attributes_45.defaultLine, + + editType: 'ticks', + + }, + zerolinewidth: { + valType: 'number', + dflt: 1, + + editType: 'ticks', + + }, + // positioning attributes + // anchor: not used directly, just put here for reference + // values are any opposite-letter axis id + anchor: { + valType: 'enumerated', + values: [ + 'free', + _$constants_213.idRegex.x.toString(), + _$constants_213.idRegex.y.toString() + ], + + editType: 'plot+margins', + + }, + // side: not used directly, as values depend on direction + // values are top, bottom for x axes, and left, right for y + side: { + valType: 'enumerated', + values: ['top', 'bottom', 'left', 'right'], + + editType: 'plot+margins', + + }, + // overlaying: not used directly, just put here for reference + // values are false and any other same-letter axis id that's not + // itself overlaying anything + overlaying: { + valType: 'enumerated', + values: [ + 'free', + _$constants_213.idRegex.x.toString(), + _$constants_213.idRegex.y.toString() + ], + + editType: 'plot', + + }, + layer: { + valType: 'enumerated', + values: ['above traces', 'below traces'], + dflt: 'above traces', + + editType: 'plot', + + }, + domain: { + valType: 'info_array', + + items: [ + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} + ], + dflt: [0, 1], + editType: 'plot+margins', + + }, + position: { + valType: 'number', + min: 0, + max: 1, + dflt: 0, + + editType: 'plot+margins', + + }, + categoryorder: { + valType: 'enumerated', + values: [ + 'trace', 'category ascending', 'category descending', 'array' + /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later + ], + dflt: 'trace', + + editType: 'calc', + + }, + categoryarray: { + valType: 'data_array', + + editType: 'calc', + + }, + editType: 'calc', + + _deprecated: { + autotick: { + valType: 'boolean', + + editType: 'ticks+margins', + + } + } }; /** @@ -19339,15 +18565,155 @@ var _$colorbarDefaults_49 = function colorbarDefaults(containerIn, containerOut, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$layout_attributes_220 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; +var __extendFlat_47 = _$extend_160.extendFlat; +var __overrideAll_47 = _$edit_types_193.overrideAll; -var _$hasColorbar_51 = function hasColorbar(container) { - return _$lib_165.isPlainObject(container.colorbar); -}; +var _$attributes_47 = __overrideAll_47({ +// 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: _$layout_attributes_220.linecolor, + outlinewidth: _$layout_attributes_220.linewidth, + // Should outlinewidth have {dflt: 0} ? + // another possible line outside the padding and tick labels + bordercolor: _$layout_attributes_220.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: _$layout_attributes_220.tickmode, + nticks: _$layout_attributes_220.nticks, + tick0: _$layout_attributes_220.tick0, + dtick: _$layout_attributes_220.dtick, + tickvals: _$layout_attributes_220.tickvals, + ticktext: _$layout_attributes_220.ticktext, + ticks: __extendFlat_47({}, _$layout_attributes_220.ticks, {dflt: ''}), + ticklen: _$layout_attributes_220.ticklen, + tickwidth: _$layout_attributes_220.tickwidth, + tickcolor: _$layout_attributes_220.tickcolor, + showticklabels: _$layout_attributes_220.showticklabels, + tickfont: _$font_attributes_234({ + + }), + tickangle: _$layout_attributes_220.tickangle, + tickformat: _$layout_attributes_220.tickformat, + tickformatstops: _$layout_attributes_220.tickformatstops, + tickprefix: _$layout_attributes_220.tickprefix, + showtickprefix: _$layout_attributes_220.showtickprefix, + ticksuffix: _$layout_attributes_220.ticksuffix, + showticksuffix: _$layout_attributes_220.showticksuffix, + separatethousands: _$layout_attributes_220.separatethousands, + exponentformat: _$layout_attributes_220.exponentformat, + showexponent: _$layout_attributes_220.showexponent, + title: { + valType: 'string', + + + }, + titlefont: _$font_attributes_234({ + + }), + titleside: { + valType: 'enumerated', + values: ['right', 'top', 'bottom'], + + dflt: 'top', + + } +}, 'colorbars', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -19360,77 +18726,96 @@ var _$hasColorbar_51 = function hasColorbar(container) { 'use strict'; -/* removed: var _$scales_65 = require('./scales'); */; -/* removed: var _$isValidScaleArray_63 = require('./is_valid_scale_array'); */; - +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$layout_attributes_220 = require('./layout_attributes'); */; -var _$isValidScale_62 = function isValidScale(scl) { - if(_$scales_65[scl] !== undefined) return true; - else return _$isValidScaleArray_63(scl); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$handleTickLabelDefaults_227 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { + var showAttrDflt = getShowAttrDflt(containerIn); + var tickPrefix = coerce('tickprefix'); + if(tickPrefix) coerce('showtickprefix', showAttrDflt); -'use strict'; + var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); + if(tickSuffix) coerce('showticksuffix', showAttrDflt); -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + var showTickLabels = coerce('showticklabels'); + if(showTickLabels) { + var font = options.font || {}; + // as with titlefont.color, inherit axis.color only if one was + // explicitly provided + var dfltFontColor = (containerOut.color === containerIn.color) ? + containerOut.color : font.color; + _$lib_166.coerceFont(coerce, 'tickfont', { + family: font.family, + size: font.size, + color: dfltFontColor + }); + coerce('tickangle'); -/* removed: var _$lib_165 = require('../../lib'); */; + if(axType !== 'category') { + var tickFormat = coerce('tickformat'); + tickformatstopsDefaults(containerIn, containerOut); + if(!tickFormat && axType !== 'date') { + coerce('showexponent', showAttrDflt); + coerce('exponentformat'); + coerce('separatethousands'); + } + } + } +}; -/* removed: var _$hasColorbar_51 = require('../colorbar/has_colorbar'); */; -/* removed: var _$colorbarDefaults_49 = require('../colorbar/defaults'); */; -/* removed: var _$isValidScale_62 = require('./is_valid_scale'); */; -/* removed: var _$flipScale_58 = require('./flip_scale'); */; +/* + * 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'], + showAttrs = showAttrsAll.filter(function(a) { + return containerIn[a] !== undefined; + }), + sameVal = function(a) { + return containerIn[a] === containerIn[showAttrs[0]]; + }; + if(showAttrs.every(sameVal) || showAttrs.length === 1) { + return containerIn[showAttrs[0]]; + } +} -var _$colorScaleDefaults_56 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { - var prefix = opts.prefix, - cLetter = opts.cLetter, - containerStr = prefix.slice(0, prefix.length - 1), - containerIn = prefix ? - _$lib_165.nestedProperty(traceIn, containerStr).get() || {} : - traceIn, - containerOut = prefix ? - _$lib_165.nestedProperty(traceOut, containerStr).get() || {} : - traceOut, - minIn = containerIn[cLetter + 'min'], - maxIn = containerIn[cLetter + 'max'], - sclIn = containerIn.colorscale; +function tickformatstopsDefaults(tickformatIn, tickformatOut) { + var valuesIn = tickformatIn.tickformatstops; + var valuesOut = tickformatOut.tickformatstops = []; - var validMinMax = _$fastIsnumeric_13(minIn) && _$fastIsnumeric_13(maxIn) && (minIn < maxIn); - coerce(prefix + cLetter + 'auto', !validMinMax); - coerce(prefix + cLetter + 'min'); - coerce(prefix + cLetter + 'max'); + if(!Array.isArray(valuesIn)) return; - // handles both the trace case (autocolorscale is false by default) and - // the marker and marker.line case (autocolorscale is true by default) - var autoColorscaleDftl; - if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_62(sclIn); - coerce(prefix + 'autocolorscale', autoColorscaleDftl); - var sclOut = coerce(prefix + 'colorscale'); + var valueIn, valueOut; - // reversescale is handled at the containerOut level - var reverseScale = coerce(prefix + 'reversescale'); - if(reverseScale) containerOut.colorscale = _$flipScale_58(sclOut); + function coerce(attr, dflt) { + return _$lib_166.coerce(valueIn, valueOut, _$layout_attributes_220.tickformatstops, attr, dflt); + } - // ... until Scatter.colorbar can handle marker line colorbars - if(prefix === 'marker.line.') return; + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; - // handle both the trace case where the dflt is listed in attributes and - // the marker case where the dflt is determined by hasColorbar - var showScaleDftl; - if(prefix) showScaleDftl = _$hasColorbar_51(containerIn); - var showScale = coerce(prefix + 'showscale', showScaleDftl); + coerce('dtickrange'); + coerce('value'); - if(showScale) _$colorbarDefaults_49(containerIn, containerOut, layout); -}; + valuesOut.push(valueOut); + } +} /** * Copyright 2012-2018, Plotly, Inc. @@ -19443,70 +18828,25 @@ var _$colorScaleDefaults_56 = function colorScaleDefaults(traceIn, traceOut, lay 'use strict'; -/** - * Extract colorscale into numeric domain and color range. - * - * @param {array} scl colorscale array of arrays - * @param {number} cmin minimum color value (used to clamp scale) - * @param {number} cmax maximum color value (used to clamp scale) - */ -var _$extractScale_57 = function extractScale(scl, cmin, cmax) { - var N = scl.length, - domain = new Array(N), - range = new Array(N); - - for(var i = 0; i < N; i++) { - var si = scl[i]; +/* removed: var _$lib_166 = require('../../lib'); */; - domain[i] = cmin + si[0] * (cmax - cmin); - range[i] = si[1]; - } +/* removed: var _$layout_attributes_220 = require('./layout_attributes'); */; - return { - domain: domain, - range: range - }; -}; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$isValidScale_62 = require('./is_valid_scale'); */; - -var _$hasColorscale_60 = function hasColorscale(trace, containerStr) { - var container = containerStr ? - _$lib_165.nestedProperty(trace, containerStr).get() || {} : - trace; - var color = container.color; + * options: inherits outerTicks from axes.handleAxisDefaults + */ +var _$handleTickDefaults_228 = function handleTickDefaults(containerIn, containerOut, coerce, options) { + var tickLen = _$lib_166.coerce2(containerIn, containerOut, _$layout_attributes_220, 'ticklen'), + tickWidth = _$lib_166.coerce2(containerIn, containerOut, _$layout_attributes_220, 'tickwidth'), + tickColor = _$lib_166.coerce2(containerIn, containerOut, _$layout_attributes_220, 'tickcolor', containerOut.color), + showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); - var isArrayWithOneNumber = false; - if(_$lib_165.isArrayOrTypedArray(color)) { - for(var i = 0; i < color.length; i++) { - if(_$fastIsnumeric_13(color[i])) { - isArrayWithOneNumber = true; - break; - } - } + if(!showTicks) { + delete containerOut.ticklen; + delete containerOut.tickwidth; + delete containerOut.tickcolor; } - - return ( - _$lib_165.isPlainObject(container) && ( - isArrayWithOneNumber || - container.showscale === true || - (_$fastIsnumeric_13(container.cmin) && _$fastIsnumeric_13(container.cmax)) || - _$isValidScale_62(container.colorscale) || - _$lib_165.isPlainObject(container.colorbar) - ) - ); }; /** @@ -19520,31 +18860,356 @@ var _$hasColorscale_60 = function hasColorscale(trace, containerStr) { 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$tinycolor_28 = require('tinycolor2'); */; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +var __ONEDAY_229 = _$numerical_148.ONEDAY; -/* removed: var _$color_46 = require('../color'); */; -/** - * 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} - */ -var _$makeColorScaleFunc_64 = function makeColorScaleFunc(specs, opts) { - opts = opts || {}; +var _$handleTickValueDefaults_229 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { + var tickmodeDefault = 'auto'; - var domain = specs.domain, - range = specs.range, - N = range.length, + if(containerIn.tickmode === 'array' && + (axType === 'log' || axType === 'date')) { + containerIn.tickmode = 'auto'; + } + + if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; + else if(containerIn.dtick) { + tickmodeDefault = 'linear'; + } + var tickmode = coerce('tickmode', tickmodeDefault); + + if(tickmode === 'auto') coerce('nticks'); + else if(tickmode === 'linear') { + // dtick is usually a positive number, but there are some + // special strings available for log or date axes + // default is 1 day for dates, otherwise 1 + var dtickDflt = (axType === 'date') ? __ONEDAY_229 : 1; + var dtick = coerce('dtick', dtickDflt); + if(_$fastIsnumeric_13(dtick)) { + containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; + } + else if(typeof dtick !== 'string') { + containerOut.dtick = dtickDflt; + } + else { + // date and log special cases are all one character plus a number + var prefix = dtick.charAt(0), + dtickNum = dtick.substr(1); + + dtickNum = _$fastIsnumeric_13(dtickNum) ? Number(dtickNum) : 0; + if((dtickNum <= 0) || !( + // "M" gives ticks every (integer) n months + (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || + // "L" gives ticks linearly spaced in data (not in position) every (float) f + (axType === 'log' && prefix === 'L') || + // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 + (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) + )) { + containerOut.dtick = dtickDflt; + } + } + + // tick0 can have different valType for different axis types, so + // validate that now. Also for dates, change milliseconds to date strings + var tick0Dflt = (axType === 'date') ? _$lib_166.dateTick0(containerOut.calendar) : 0; + var tick0 = coerce('tick0', tick0Dflt); + if(axType === 'date') { + containerOut.tick0 = _$lib_166.cleanDate(tick0, tick0Dflt); + } + // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely + else if(_$fastIsnumeric_13(tick0) && dtick !== 'D1' && dtick !== 'D2') { + containerOut.tick0 = Number(tick0); + } + else { + containerOut.tick0 = tick0Dflt; + } + } + else { + var tickvals = coerce('tickvals'); + if(tickvals === undefined) containerOut.tickmode = 'auto'; + else coerce('ticktext'); + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_229 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_228 = require('../../plots/cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_227 = require('../../plots/cartesian/tick_label_defaults'); */; + +/* removed: var _$attributes_47 = require('./attributes'); */; + + +var _$colorbarDefaults_49 = function colorbarDefaults(containerIn, containerOut, layout) { + var colorbarOut = containerOut.colorbar = {}, + colorbarIn = containerIn.colorbar || {}; + + function coerce(attr, dflt) { + return _$lib_166.coerce(colorbarIn, colorbarOut, _$attributes_47, attr, dflt); + } + + var thicknessmode = coerce('thicknessmode'); + coerce('thickness', (thicknessmode === 'fraction') ? + 30 / (layout.width - layout.margin.l - layout.margin.r) : + 30 + ); + + var lenmode = coerce('lenmode'); + coerce('len', (lenmode === 'fraction') ? + 1 : + layout.height - layout.margin.t - layout.margin.b + ); + + coerce('x'); + coerce('xanchor'); + coerce('xpad'); + coerce('y'); + coerce('yanchor'); + coerce('ypad'); + _$lib_166.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + + coerce('outlinecolor'); + coerce('outlinewidth'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('bgcolor'); + + _$handleTickValueDefaults_229(colorbarIn, colorbarOut, coerce, 'linear'); + + var opts = {outerTicks: false, font: layout.font}; + _$handleTickLabelDefaults_227(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickDefaults_228(colorbarIn, colorbarOut, coerce, 'linear', opts); + + coerce('title', layout._dfltTitle.colorbar); + _$lib_166.coerceFont(coerce, 'titlefont', layout.font); + coerce('titleside'); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_166 = require('../../lib'); */; + + +var _$hasColorbar_51 = function hasColorbar(container) { + return _$lib_166.isPlainObject(container.colorbar); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$scales_65 = require('./scales'); */; +/* removed: var _$isValidScaleArray_63 = require('./is_valid_scale_array'); */; + + +var _$isValidScale_62 = function isValidScale(scl) { + if(_$scales_65[scl] !== undefined) return true; + else return _$isValidScaleArray_63(scl); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + +/* removed: var _$lib_166 = require('../../lib'); */; + +/* removed: var _$hasColorbar_51 = require('../colorbar/has_colorbar'); */; +/* removed: var _$colorbarDefaults_49 = require('../colorbar/defaults'); */; +/* removed: var _$isValidScale_62 = require('./is_valid_scale'); */; +/* removed: var _$flipScale_58 = require('./flip_scale'); */; + + +var _$colorScaleDefaults_56 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { + var prefix = opts.prefix, + cLetter = opts.cLetter, + containerStr = prefix.slice(0, prefix.length - 1), + containerIn = prefix ? + _$lib_166.nestedProperty(traceIn, containerStr).get() || {} : + traceIn, + containerOut = prefix ? + _$lib_166.nestedProperty(traceOut, containerStr).get() || {} : + traceOut, + minIn = containerIn[cLetter + 'min'], + maxIn = containerIn[cLetter + 'max'], + sclIn = containerIn.colorscale; + + var validMinMax = _$fastIsnumeric_13(minIn) && _$fastIsnumeric_13(maxIn) && (minIn < maxIn); + coerce(prefix + cLetter + 'auto', !validMinMax); + 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 autoColorscaleDftl; + if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_62(sclIn); + coerce(prefix + 'autocolorscale', autoColorscaleDftl); + var sclOut = coerce(prefix + 'colorscale'); + + // reversescale is handled at the containerOut level + var reverseScale = coerce(prefix + 'reversescale'); + if(reverseScale) containerOut.colorscale = _$flipScale_58(sclOut); + + // ... until Scatter.colorbar can handle marker line colorbars + if(prefix === 'marker.line.') return; + + // handle both the trace case where the dflt is listed in attributes and + // the marker case where the dflt is determined by hasColorbar + var showScaleDftl; + if(prefix) showScaleDftl = _$hasColorbar_51(containerIn); + var showScale = coerce(prefix + 'showscale', showScaleDftl); + + if(showScale) _$colorbarDefaults_49(containerIn, containerOut, layout); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/** + * Extract colorscale into numeric domain and color range. + * + * @param {array} scl colorscale array of arrays + * @param {number} cmin minimum color value (used to clamp scale) + * @param {number} cmax maximum color value (used to clamp scale) + */ +var _$extractScale_57 = function extractScale(scl, cmin, cmax) { + var N = scl.length, + domain = new Array(N), + range = new Array(N); + + for(var i = 0; i < N; i++) { + var si = scl[i]; + + domain[i] = cmin + si[0] * (cmax - cmin); + range[i] = si[1]; + } + + return { + domain: domain, + range: range + }; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$isValidScale_62 = require('./is_valid_scale'); */; + +var _$hasColorscale_60 = function hasColorscale(trace, containerStr) { + var container = containerStr ? + _$lib_166.nestedProperty(trace, containerStr).get() || {} : + trace; + var color = container.color; + + var isArrayWithOneNumber = false; + if(_$lib_166.isArrayOrTypedArray(color)) { + for(var i = 0; i < color.length; i++) { + if(_$fastIsnumeric_13(color[i])) { + isArrayWithOneNumber = true; + break; + } + } + } + + return ( + _$lib_166.isPlainObject(container) && ( + isArrayWithOneNumber || + container.showscale === true || + (_$fastIsnumeric_13(container.cmin) && _$fastIsnumeric_13(container.cmax)) || + _$isValidScale_62(container.colorscale) || + _$lib_166.isPlainObject(container.colorbar) + ) + ); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$tinycolor_28 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + +/* removed: var _$color_46 = require('../color'); */; + +/** + * 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} + */ +var _$makeColorScaleFunc_64 = function makeColorScaleFunc(specs, opts) { + opts = opts || {}; + + var domain = specs.domain, + range = specs.range, + N = range.length, _range = new Array(N); for(var i = 0; i < N; i++) { @@ -20226,7 +19891,7 @@ var _$string_mappings_149 = { } }; -var _$svg_text_utils_186 = {}; +var _$svg_text_utils_187 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -20242,7 +19907,7 @@ var _$svg_text_utils_186 = {}; /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$lib_166 = require('../lib'); */; /* removed: var _$xmlns_namespaces_150 = require('../constants/xmlns_namespaces'); */; /* removed: var _$string_mappings_149 = require('../constants/string_mappings'); */; var LINE_SPACING = _$alignment_146.LINE_SPACING; @@ -20255,7 +19920,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_186.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_187.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) @@ -20298,7 +19963,7 @@ _$svg_text_utils_186.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_186.positionText(_context); + _$svg_text_utils_187.positionText(_context); if(_callback) _callback.call(_context); } @@ -20393,7 +20058,7 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_165.randstr([], 64); + var randomID = 'math-output-' + _$lib_166.randstr([], 64); var tmpDiv = _$d3_10.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) @@ -20404,7 +20069,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = _$d3_10.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_165.log('There was an error in the tex syntax.', _texString); + _$lib_166.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -20499,7 +20164,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_186.plainText = function(_str) { +_$svg_text_utils_187.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -20632,14 +20297,14 @@ function buildSVGText(containerNode, str) { // 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_165.log('Ignoring unexpected end tag .', str); + _$lib_166.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_165.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_166.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -20698,7 +20363,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -20713,11 +20381,11 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_186.lineCount = function lineCount(s) { +_$svg_text_utils_187.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_186.positionText = function positionText(s, x, y) { +_$svg_text_utils_187.positionText = function positionText(s, x, y) { return s.each(function() { var text = _$d3_10.select(this); @@ -20793,7 +20461,7 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_186.makeEditable = function(context, options) { +_$svg_text_utils_187.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; var dispatch = _$d3_10.dispatch('edit', 'input', 'cancel'); @@ -20916,7 +20584,7 @@ _$svg_text_utils_186.makeEditable = function(context, options) { // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_334 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_332 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -20952,17 +20620,20 @@ var _$makeBubbleSizeFn_334 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -var _$subtypes_339 = { +var _$subtypes_337 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -20971,8 +20642,8 @@ var _$subtypes_339 = { }, isBubble: function(trace) { - return _$lib_165.isPlainObject(trace.marker) && - _$lib_165.isArrayOrTypedArray(trace.marker.size); + return _$lib_166.isPlainObject(trace.marker) && + _$lib_166.isArrayOrTypedArray(trace.marker.size); } }; @@ -20992,19 +20663,19 @@ var _$drawing_71 = {}; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_28 = require('tinycolor2'); */; -/* removed: var _$registry_247 = require('../../registry'); */; +/* removed: var _$registry_248 = require('../../registry'); */; /* removed: var _$color_46 = require('../color'); */; /* removed: var _$colorscale_61 = require('../colorscale'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; /* removed: var _$xmlns_namespaces_150 = require('../../constants/xmlns_namespaces'); */; /* removed: var _$alignment_146 = require('../../constants/alignment'); */; var __LINE_SPACING_71 = _$alignment_146.LINE_SPACING; var __DESELECTDIM_71 = _$interactions_147.DESELECTDIM; -/* removed: var _$subtypes_339 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_334 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_337 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_332 = require('../../traces/scatter/make_bubble_size_func'); */; var drawing = _$drawing_71 = {}; @@ -21014,7 +20685,7 @@ var drawing = _$drawing_71 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_165.isPlainObject(family)) { + if(_$lib_166.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; @@ -21182,7 +20853,7 @@ drawing.fillGroupStyle = function(s) { shape.call(_$color_46.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_165.error(e, s); + _$lib_166.error(e, s); shape.remove(); } }); @@ -21245,8 +20916,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_247.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_334(trace); + if(_$registry_248.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_332(trace); sel.attr('d', function(d) { var r; @@ -21255,7 +20926,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_339.isBubble(trace) ? + r = _$subtypes_337.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -21295,10 +20966,10 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_165.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_46.defaultLine; + else if(_$lib_166.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_46.defaultLine; else lineColor = markerLine.color; - if(_$lib_165.isArrayOrTypedArray(marker.color)) { + if(_$lib_166.isArrayOrTypedArray(marker.color)) { fillColor = _$color_46.defaultLine; perPointGradient = true; } @@ -21351,7 +21022,7 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_165.identity); + .data([type + color1 + color2], _$lib_166.identity); gradient.exit().remove(); @@ -21394,9 +21065,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_166.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -21502,7 +21171,7 @@ drawing.selectedPointStyle = function(s, trace) { }); } - if(_$registry_247.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_248.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { var pt = _$d3_10.select(this); var mx = d.mx || marker.symbol || 0; @@ -21517,16 +21186,16 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_165.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_166.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_165.isArrayOrTypedArray(colorArray)) { + if(scl && _$lib_166.isArrayOrTypedArray(colorArray)) { return _$colorscale_61.makeColorScaleFunc( _$colorscale_61.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_165.identity; + else return _$lib_166.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; @@ -21546,7 +21215,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_186.lineCount(s) - 1) * __LINE_SPACING_71 + 1; + var numLines = (_$svg_text_utils_187.lineCount(s) - 1) * __LINE_SPACING_71 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -21565,7 +21234,7 @@ function extracTextFontSize(d, trace) { drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { var p = _$d3_10.select(this); - var text = _$lib_165.extractOption(d, trace, 'tx', 'text'); + var text = _$lib_166.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -21580,7 +21249,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_186.convertToTspans, gd) + .call(_$svg_text_utils_187.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -21708,33 +21377,28 @@ drawing.steps = function(shape) { // 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 = _$d3_10.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_150.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_166.ensureSingleById(_$d3_10.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_150.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_166.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; @@ -21779,7 +21443,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_165.extendFlat({}, out); + if(out) return _$lib_166.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -21823,7 +21487,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_165.extendFlat({}, out); + if(out) return _$lib_166.extendFlat({}, out); } } var testNode, tester; @@ -21841,7 +21505,7 @@ drawing.bBox = function(node, inTester, hash) { // standardize its position (and newline tspans if any) _$d3_10.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_186.positionText, 0, 0); + .call(_$svg_text_utils_187.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -21871,7 +21535,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_165.extendFlat({}, bb); + return _$lib_166.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -21896,15 +21560,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_10.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_10.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -22042,6 +21712,319 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { }); }; +var _$helpers_85 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_166 = require('../../lib'); */; + +// look for either subplot or xaxis and yaxis attributes +// does not handle splom case +_$helpers_85.getSubplot = function getSubplot(trace) { + return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +}; + +// is trace in given list of subplots? +// does handle splom case +_$helpers_85.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_85.getSubplot(trace)) !== -1; +}; + +// convenience functions for mapping all relevant axes +_$helpers_85.flat = function flat(subplots, v) { + var out = new Array(subplots.length); + for(var i = 0; i < subplots.length; i++) { + out[i] = v; + } + return out; +}; + +_$helpers_85.p2c = function p2c(axArray, v) { + var out = new Array(axArray.length); + for(var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); + } + return out; +}; + +_$helpers_85.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { + if(mode === 'closest') return dxy || _$helpers_85.quadrature(dx, dy); + return mode === 'x' ? dx : dy; +}; + +_$helpers_85.getClosest = function getClosest(cd, distfn, pointData) { + // do we already have a point number? (array mode only) + if(pointData.index !== false) { + if(pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; + } + else pointData.index = false; + } + else { + // apply the distance function to each data point + // this is the longest loop... if this bogs down, we may need + // to create pre-sorted data (by x or y), not sure how to + // do this for 'closest' + for(var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if(newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; + } + } + } + return pointData; +}; + +/* + * pseudo-distance function for hover effects on areas: inside the region + * distance is finite (`passVal`), outside it's Infinity. + * + * @param {number} v0: signed difference between the current position and the left edge + * @param {number} v1: signed difference between the current position and the right edge + * @param {number} passVal: the value to return on success + */ +_$helpers_85.inbox = function inbox(v0, v1, passVal) { + return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; +}; + +_$helpers_85.quadrature = function quadrature(dx, dy) { + return function(di) { + var x = dx(di), + y = dy(di); + return Math.sqrt(x * x + y * y); + }; +}; + +/** Fill event data point object for hover and selection. + * Invokes _module.eventData if present. + * + * N.B. note that point 'index' corresponds to input data array index + * whereas 'number' is its post-transform version. + * + * If the hovered/selected pt corresponds to an multiple input points + * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' + * are include in the event data. + * + * @param {object} pt + * @param {object} trace + * @param {object} cd + * @return {object} + */ +_$helpers_85.makeEventData = function makeEventData(pt, trace, cd) { + // hover uses 'index', select uses 'pointNumber' + var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber: pointNumber + }; + + if(trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; + + if(pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; + } else { + out.pointIndices = pointIndices; + } + } else { + out.pointIndex = pointNumber; + } + + if(trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if('xVal' in pt) out.x = pt.xVal; + else if('x' in pt) out.x = pt.x; + + if('yVal' in pt) out.y = pt.yVal; + else if('y' in pt) out.y = pt.y; + + if(pt.xa) out.xaxis = pt.xa; + if(pt.ya) out.yaxis = pt.ya; + if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; + } + + _$helpers_85.appendArrayPointValue(out, trace, pointNumber); + + return out; +}; + +/** Appends values inside array attributes corresponding to given point number + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {number|Array(number)} pointNumber : point number. May be a length-2 array + * [row, col] to dig into 2D arrays + */ +_$helpers_85.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_166.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); + + if(pointVal !== undefined) pointData[key] = pointVal; + } + } +}; + +/** + * Appends values inside array attributes corresponding to given point number array + * For use when pointData references a plot entity that arose (or potentially arose) + * from multiple points in the input data + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. + * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays + */ +_$helpers_85.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_166.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); + + for(var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); + } + pointData[key] = keyVal; + } + } +}; + +var pointKeyMap = { + ids: 'id', + locations: 'location', + labels: 'label', + values: 'value', + 'marker.colors': 'color' +}; + +function getPointKey(astr) { + return pointKeyMap[astr] || astr; +} + +function getPointData(val, pointNumber) { + if(Array.isArray(pointNumber)) { + if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; + } + } else { + return val[pointNumber]; + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +// works with our CSS cursor classes (see css/_cursor.scss) +// to apply cursors to d3 single-element selections. +// omit cursor to revert to the default. +var _$setCursor_185 = function setCursor(el3, csr) { + (el3.attr('class') || '').split(' ').forEach(function(cls) { + if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); + }); + + if(csr) el3.classed('cursor-' + csr, true); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$setCursor_185 = require('./setcursor'); */; + +var STASHATTR = 'data-savedcursor'; +var NO_CURSOR = '!!'; + +/* + * works with our CSS cursor classes (see css/_cursor.scss) + * to override a previous cursor set on d3 single-element selections, + * by moving the name of the original cursor to the data-savedcursor attr. + * omit cursor to revert to the previously set value. + */ +var _$overrideCursor_177 = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if(csr) { + if(!savedCursor) { + var classes = (el3.attr('class') || '').split(' '); + for(var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if(cls.indexOf('cursor-') === 0) { + el3.attr(STASHATTR, cls.substr(7)) + .classed(cls, false); + } + } + if(!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); + } + } + _$setCursor_185(el3, csr); + } + else if(savedCursor) { + el3.attr(STASHATTR, null); + + if(savedCursor === NO_CURSOR) _$setCursor_185(el3); + else _$setCursor_185(el3, savedCursor); + } +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22052,7 +22035,7 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -var _$animation_attributes_202 = { +var _$animation_attributes_203 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -22199,7 +22182,7 @@ var _$frame_attributes_235 = { 'use strict'; /* removed: var _$attributes_52 = require('./attributes'); */; -var __extendFlat_54 = _$extend_159.extendFlat; +var __extendFlat_54 = _$extend_160.extendFlat; /* removed: var _$scales_65 = require('./scales.js'); */; /* @@ -22265,7 +22248,7 @@ var _$makeColorScaleAttributes_54 = function makeColorScaleAttributes(context, e 'use strict'; -var _$constants_323 = { +var _$constants_321 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -22293,13 +22276,13 @@ var _$constants_323 = { /* removed: var _$makeColorScaleAttributes_54 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_47 = require('../../components/colorbar/attributes'); */; /* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -var __dash_317 = _$attributes_70.dash; +var __dash_315 = _$attributes_70.dash; /* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$constants_323 = require('./constants'); */; -var __extendFlat_317 = _$extend_159.extendFlat; +/* removed: var _$constants_321 = require('./constants'); */; +var __extendFlat_315 = _$extend_160.extendFlat; -var _$attributes_317 = { +var _$attributes_315 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -22401,7 +22384,7 @@ var _$attributes_317 = { editType: 'plot', }, - dash: __extendFlat_317({}, __dash_317, {editType: 'style'}), + dash: __extendFlat_315({}, __dash_315, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -22441,7 +22424,7 @@ var _$attributes_317 = { editType: 'style', }, - marker: __extendFlat_317({ + marker: __extendFlat_315({ symbol: { valType: 'enumerated', values: _$drawing_71.symbolList, @@ -22510,7 +22493,7 @@ var _$attributes_317 = { }, colorbar: _$attributes_47, - line: __extendFlat_317({ + line: __extendFlat_315({ width: { valType: 'number', min: 0, @@ -22661,12 +22644,12 @@ var _$attributes_317 = { 'use strict'; -/* removed: var _$attributes_317 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_317.marker; +/* removed: var _$attributes_315 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_315.marker; var _$area_attributes_241 = { - r: _$attributes_317.r, - t: _$attributes_317.t, + r: _$attributes_315.r, + t: _$attributes_315.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -22687,11 +22670,11 @@ var _$area_attributes_241 = { 'use strict'; -/* removed: var _$layout_attributes_219 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_242 = _$extend_159.extendFlat; -var __overrideAll_242 = _$edit_types_192.overrideAll; +/* removed: var _$layout_attributes_220 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_242 = _$extend_160.extendFlat; +var __overrideAll_242 = _$edit_types_193.overrideAll; -var domainAttr = __extendFlat_242({}, _$layout_attributes_219.domain, { +var domainAttr = __extendFlat_242({}, _$layout_attributes_220.domain, { }); @@ -22791,7 +22774,7 @@ var _$axis_attributes_242 = __overrideAll_242({ } }, 'plot', 'nested'); -var _$plot_schema_198 = {}; +var _$plot_schema_199 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22803,22 +22786,23 @@ var _$plot_schema_198 = {}; 'use strict'; -/* removed: var _$registry_247 = require('../registry'); */; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$registry_248 = require('../registry'); */; +/* removed: var _$lib_166 = require('../lib'); */; -/* removed: var _$attributes_204 = require('../plots/attributes'); */; +/* removed: var _$attributes_205 = require('../plots/attributes'); */; /* removed: var _$layout_attributes_238 = require('../plots/layout_attributes'); */; /* removed: var _$frame_attributes_235 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_202 = require('../plots/animation_attributes'); */; +/* removed: var _$animation_attributes_203 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet /* removed: var _$area_attributes_241 = require('../plots/polar/legacy/area_attributes'); */; /* removed: var _$axis_attributes_242 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_192 = require('./edit_types'); */; +/* removed: var _$edit_types_193 = require('./edit_types'); */; -var __extendFlat_198 = _$lib_165.extendFlat; -var __extendDeepAll_198 = _$lib_165.extendDeepAll; +var __extendFlat_199 = _$lib_166.extendFlat; +var __extendDeepAll_199 = _$lib_166.extendDeepAll; +var __isPlainObject_199 = _$lib_166.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -22826,10 +22810,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_198.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_198.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_198.DEPRECATED = DEPRECATED; -_$plot_schema_198.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_199.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_199.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_199.DEPRECATED = DEPRECATED; +_$plot_schema_199.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -22842,26 +22826,26 @@ _$plot_schema_198.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_198.get = function() { +_$plot_schema_199.get = function() { var traces = {}; - _$registry_247.allTypes.concat('area').forEach(function(type) { + _$registry_248.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_247.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_248.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_165.valObjectMeta, + valObjects: _$lib_166.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_192.traces, - layout: _$edit_types_192.layout + traces: _$edit_types_193.traces, + layout: _$edit_types_193.layout }, impliedEdits: { @@ -22874,7 +22858,7 @@ _$plot_schema_198.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_202) + animation: formatAttributes(_$animation_attributes_203) }; }; @@ -22905,7 +22889,7 @@ _$plot_schema_198.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_198.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_199.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -22917,10 +22901,10 @@ _$plot_schema_198.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_198.isValObject(attr)) return; + if(_$plot_schema_199.isValObject(attr)) return; - if(_$lib_165.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_198.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_199(attr) && attrName !== 'impliedEdits') { + _$plot_schema_199.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -22932,7 +22916,7 @@ _$plot_schema_198.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_198.isValObject = function(obj) { +_$plot_schema_199.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -22946,7 +22930,7 @@ _$plot_schema_198.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_198.findArrayAttributes = function(trace) { +_$plot_schema_199.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -22969,8 +22953,8 @@ _$plot_schema_198.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_165.nestedProperty(trace, astr).get(); - if(!_$lib_165.isArrayOrTypedArray(val)) return; + var val = _$lib_166.nestedProperty(trace, astr).get(); + if(!_$lib_166.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -22979,9 +22963,9 @@ _$plot_schema_198.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_198.crawl(_$attributes_204, callback); + _$plot_schema_199.crawl(_$attributes_205, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_198.crawl(trace._module.attributes, callback); + _$plot_schema_199.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -22994,7 +22978,7 @@ _$plot_schema_198.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_198.crawl(module.attributes, callback, 1); + _$plot_schema_199.crawl(module.attributes, callback, 1); } } } @@ -23006,8 +22990,8 @@ _$plot_schema_198.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_198.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_165.filterUnique(arrayAttributes); + _$plot_schema_199.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_166.filterUnique(arrayAttributes); } return arrayAttributes; @@ -23028,18 +23012,19 @@ _$plot_schema_198.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_198.getTraceValObject = function(trace, parts) { +_$plot_schema_199.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_247.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_248.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } @@ -23050,7 +23035,7 @@ _$plot_schema_198.getTraceValObject = function(trace, parts) { // 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_247.modules[trace.type || _$attributes_204.type.dflt] || {})._module; + if(!_module) _module = (_$registry_248.modules[trace.type || _$attributes_205.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -23065,7 +23050,7 @@ _$plot_schema_198.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_204[head]; + if(!valObject) valObject = _$attributes_205[head]; } return recurseIntoValObject(valObject, parts, i); @@ -23084,7 +23069,7 @@ _$plot_schema_198.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_198.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_199.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -23135,8 +23120,8 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_247.componentsRegistry) { - _module = _$registry_247.componentsRegistry[key]; + for(key in _$registry_248.componentsRegistry) { + _module = _$registry_248.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } @@ -23166,7 +23151,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_165.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_199(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -23213,7 +23198,7 @@ function getTraceAttributes(type) { basePlotModule = {}; } else { - _module = _$registry_247.modules[type]._module, + _module = _$registry_248.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -23223,14 +23208,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_198(attributes, _$attributes_204); + __extendDeepAll_199(attributes, _$attributes_205); // module attributes - __extendDeepAll_198(attributes, _module.attributes); + __extendDeepAll_199(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_198(attributes, basePlotModule.attributes); + __extendDeepAll_199(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -23245,7 +23230,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_198(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_199(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -23257,21 +23242,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_198(layoutAttributes, _$layout_attributes_238); + __extendDeepAll_199(layoutAttributes, _$layout_attributes_238); // add base plot module layout attributes - for(key in _$registry_247.subplotsRegistry) { - _module = _$registry_247.subplotsRegistry[key]; + for(key in _$registry_248.subplotsRegistry) { + _module = _$registry_248.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -23280,8 +23264,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_247.componentsRegistry) { - _module = _$registry_247.componentsRegistry[key]; + for(key in _$registry_248.componentsRegistry) { + _module = _$registry_248.componentsRegistry[key]; var schema = _module.schema; /* @@ -23312,12 +23296,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_247.transformsRegistry[type]; - var attributes = __extendDeepAll_198({}, _module.attributes); + var _module = _$registry_248.transformsRegistry[type]; + var attributes = __extendDeepAll_199({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_247.componentsRegistry).forEach(function(k) { - var _module = _$registry_247.componentsRegistry[k]; + Object.keys(_$registry_248.componentsRegistry).forEach(function(k) { + var _module = _$registry_248.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -23333,7 +23317,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_165.extendDeepAll({}, _$frame_attributes_235) + frames: _$lib_166.extendDeepAll({}, _$frame_attributes_235) }; formatAttributes(attrs); @@ -23344,6 +23328,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -23360,7 +23345,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_198.isValObject(attr)) { + if(_$plot_schema_199.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -23372,13 +23357,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_165.isPlainObject(attr)) { + else if(__isPlainObject_199(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_198.crawl(attrs, callback); + _$plot_schema_199.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -23397,32 +23382,55 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_198.crawl(attrs, callback); + _$plot_schema_199.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_199(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_198(layoutAttributes, { + __extendFlat_199(layoutAttributes, { radialaxis: _$axis_attributes_242.radialaxis, angularaxis: _$axis_attributes_242.angularaxis }); - __extendFlat_198(layoutAttributes, _$axis_attributes_242.layout); + __extendFlat_199(layoutAttributes, _$axis_attributes_242.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_165.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_198({}, _module.layoutAttributes); + var np = _$lib_166.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_199({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_165.nestedProperty(baseAttrs, astr); + var np = _$lib_166.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_198(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_199(np.get() || {}, newAttrs)); } var _$command_232 = {}; @@ -23436,8 +23444,8 @@ var _$command_232 = {}; 'use strict'; -/* removed: var _$registry_247 = require('../registry'); */; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$registry_248 = require('../registry'); */; +/* removed: var _$lib_166 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -23541,7 +23549,7 @@ _$command_232.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_165.log('Unable to automatically bind plot updates to API command'); + _$lib_166.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -23659,7 +23667,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_165.nestedProperty(container, binding.prop).get(); + value = _$lib_166.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -23691,7 +23699,7 @@ function bindingValueHasChanged(gd, binding, cache) { _$command_232.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_247.apiMethodRegistry[method]; + var _method = _$registry_248.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -23700,7 +23708,7 @@ _$command_232.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_165.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_166.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; @@ -23750,7 +23758,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_165.isPlainObject(astr)) { + } else if(_$lib_166.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -23774,7 +23782,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_165.isPlainObject(astr)) { + } else if(_$lib_166.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -23840,7 +23848,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_165.isPlainObject(attr)) { + if(_$lib_166.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -23849,6 +23857,32 @@ function crawl(attrs, callback, path, depth) { }); } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_247 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + var _$plots_240 = {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -23864,25 +23898,27 @@ var _$plots_240 = {}; /* removed: var _$d3_10 = require('d3'); */; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$registry_247 = require('../registry'); */; -/* removed: var _$plot_schema_198 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_210 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_165 = require('../lib'); */; -var _ = _$lib_165._; +/* removed: var _$registry_248 = require('../registry'); */; +/* removed: var _$plot_schema_199 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_166 = require('../lib'); */; /* removed: var _$color_46 = require('../components/color'); */; var __BADNUM_240 = _$numerical_148.BADNUM; -var plots = _$plots_240 = {}; +/* removed: var _$axis_ids_211 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_240 = _$sort_modules_247.sortBasePlotModules; -/* removed: var _$animation_attributes_202 = require('./animation_attributes'); */; +/* removed: var _$animation_attributes_203 = require('./animation_attributes'); */; /* removed: var _$frame_attributes_235 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_165.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_166.relinkPrivateKeys; +var _ = _$lib_166._; + +var plots = _$plots_240 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_165.extendFlat(plots, _$registry_247); +_$lib_166.extendFlat(plots, _$registry_248); -plots.attributes = _$attributes_204; +plots.attributes = _$attributes_205; plots.attributes.type.values = plots.allTypes; plots.fontAttrs = _$font_attributes_234; plots.layoutAttributes = _$layout_attributes_238; @@ -23902,15 +23938,15 @@ plots.hasSimpleAPICommandBindings = _$command_232.hasSimpleAPICommandBindings; // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_165.getGraphDiv(gd); + gd = _$lib_166.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_247.getComponentMethod('annotations', 'draw')(gd); - _$registry_247.getComponentMethod('legend', 'draw')(gd); + _$registry_248.getComponentMethod('annotations', 'draw')(gd); + _$registry_248.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -23923,7 +23959,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_165.getGraphDiv(gd); + gd = _$lib_166.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -23954,7 +23990,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_247.call('relayout', gd, {autosize: true}).then(function() { + _$registry_248.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -23984,12 +24020,8 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_166.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', 'fill': _$color_46.defaultLine, @@ -24001,12 +24033,11 @@ plots.addLinks = function(gd) { links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -24144,6 +24175,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -24178,7 +24211,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -24221,12 +24253,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_248.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_166.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_166.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_166.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -24237,7 +24295,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -24246,6 +24304,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -24256,7 +24325,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -24268,17 +24337,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_210.list(gd); + var axList = _$axis_ids_211.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -24288,6 +24357,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_240); }; /** @@ -24306,7 +24378,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_247.subplotsRegistry; + var subplotsRegistry = _$registry_248.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -24319,7 +24391,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_165.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_166.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -24340,14 +24412,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_165.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_166.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_165.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_166.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -24392,7 +24464,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_247.localeRegistry; + locales = _$registry_248.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -24401,7 +24473,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_247.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_248.localeRegistry.en.format); return formatObj; } @@ -24453,30 +24525,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_248.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -24484,7 +24554,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -24556,8 +24626,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_210.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_210.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_211.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_211.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -24602,13 +24672,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_210.list(mockGd, null, true); + var axList = _$axis_ids_211.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_210.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_211.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -24630,7 +24700,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_210.getFromId(mockGd, ax.anchor); + _$axis_ids_211.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -24659,7 +24729,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_210.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_211.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -24700,17 +24770,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_198.crawl( + _$plot_schema_199.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_165.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_166.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_165.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_166.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -24732,8 +24802,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_165.pushUnique(modules, _module); - _$lib_165.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_166.pushUnique(modules, _module); + _$lib_166.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -24793,11 +24863,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_247.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_248.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_247.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_248.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -24826,7 +24896,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_165.coerce(opts || {}, optsOut, _$animation_attributes_202, attr, dflt); + return _$lib_166.coerce(opts || {}, optsOut, _$animation_attributes_203, attr, dflt); } coerce('mode'); @@ -24858,7 +24928,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_165.coerce(opts || {}, optsOut, _$animation_attributes_202.frame, attr, dflt); + return _$lib_166.coerce(opts || {}, optsOut, _$animation_attributes_203.frame, attr, dflt); } coerce('duration'); @@ -24871,7 +24941,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_165.coerce(opts || {}, optsOut, _$animation_attributes_202.transition, attr, dflt); + return _$lib_166.coerce(opts || {}, optsOut, _$animation_attributes_203.transition, attr, dflt); } coerce('duration'); @@ -24884,7 +24954,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_165.coerce(frameIn, frameOut, _$frame_attributes_235, attr, dflt); + return _$lib_166.coerce(frameIn, frameOut, _$frame_attributes_235, attr, dflt); } coerce('group'); @@ -24905,7 +24975,7 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) var i; function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_166.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -24921,9 +24991,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -24933,18 +25003,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_165.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_166.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_165.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_166.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_165.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_166.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_165.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_166.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -24954,12 +25024,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_247.traceIs(traceOut, 'showLegend')) { + if(_$registry_248.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_247.getComponentMethod( + _$registry_248.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -24968,12 +25038,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_165.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_166.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_247.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_248.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_247.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_248.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -25017,17 +25087,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_165.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_166.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_165.pushUnique(transformModules, _module); + _$lib_166.pushUnique(transformModules, _module); } else { - transformOut = _$lib_165.extendFlat({}, transformIn); + transformOut = _$lib_166.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -25059,14 +25129,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_165.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_166.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_165.coerceFont(coerce, 'font'); + var globalFont = _$lib_166.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_165.coerceFont(coerce, 'titlefont', { + _$lib_166.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -25094,7 +25164,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_247.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_248.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -25105,12 +25175,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_247.getComponentMethod( + _$registry_248.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_247.getComponentMethod( + _$registry_248.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -25122,7 +25192,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_165.isPlotDiv(gd); + var isPlotDiv = _$lib_166.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -25210,11 +25280,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_247.componentsRegistry; + var componentsRegistry = _$registry_248.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_247.subplotsRegistry.cartesian; + var Cartesian = _$registry_248.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -25233,13 +25303,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_247.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_248.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_165.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_166.subplotSort); } // base plot module layout defaults @@ -25311,7 +25381,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_165.clearThrottle(); + _$lib_166.clearThrottle(); // data and layout delete gd.data; @@ -25367,7 +25437,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_165.pushUnique(styleModules, _module.style); + _$lib_166.pushUnique(styleModules, _module.style); } } @@ -25522,7 +25592,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_247.call('plot', gd); + return _$registry_248.call('plot', gd); } }; @@ -25563,7 +25633,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_165.isPlainObject(d)) { + if(_$lib_166.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -25586,7 +25656,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_165.isPlainObject(d.stream)) { + if(!_$lib_166.isPlainObject(d.stream)) { continue; } } @@ -25612,7 +25682,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_165.isJSDate(d)) return _$lib_165.ms2DateTimeLocal(+d); + if(_$lib_166.isJSDate(d)) return _$lib_166.ms2DateTimeLocal(+d); return d; } @@ -25809,8 +25879,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_165.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_165.expandObjectPaths(copy); + var copy = _$lib_166.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_166.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -25818,29 +25888,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_165.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_166.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_165.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_166.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_165.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_166.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_165.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_166.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_165.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_166.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_165.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_166.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -25865,7 +25935,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_247.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_248.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -25939,7 +26009,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_165.expandObjectPaths(_$lib_165.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_166.expandObjectPaths(_$lib_166.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -25966,7 +26036,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_247.getComponentMethod('errorbars', 'calc')(gd); + _$registry_248.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -26014,7 +26084,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_247.call('redraw', gd); + return _$registry_248.call('redraw', gd); }); } @@ -26046,7 +26116,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_165.expandObjectPaths(layout); + var newLayout = _$lib_166.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -26056,7 +26126,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_165.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_166.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -26086,7 +26156,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_247.call('redraw', gd); + return _$registry_248.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -26121,7 +26191,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_165.syncOrAsync(seq, gd); + var transitionStarting = _$lib_166.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -26133,7 +26203,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_210.list(gd), + var axList = _$axis_ids_211.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -26177,7 +26247,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_198.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_199.findArrayAttributes(trace); } // add polar axes to axis list @@ -26221,14 +26291,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -26263,7 +26334,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_247.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_248.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -26314,7 +26390,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_165.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_166.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -26336,11 +26412,11 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; /* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; /* removed: var _$drawing_71 = require('../drawing'); */; /* removed: var _$color_46 = require('../color'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; /* removed: var _$interactions_147 = require('../../constants/interactions'); */; var _$titles_139 = { @@ -26421,10 +26497,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_166.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -26442,7 +26515,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_165.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_166.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -26470,7 +26543,7 @@ function draw(gd, titleClass, options) { 'font-weight': _$plots_240.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_186.convertToTspans, gd); + .call(_$svg_text_utils_187.convertToTspans, gd); return _$plots_240.previousPromises(gd); } @@ -26520,7 +26593,7 @@ function draw(gd, titleClass, options) { avoid.selection.each(function() { var avoidbb = _$drawing_71.bBox(this); - if(_$lib_165.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_166.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -26560,12 +26633,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_186.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_187.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_247.call('restyle', gd, prop, text, traceIndex); + _$registry_248.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_247.call('relayout', gd, prop, text); + _$registry_248.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -26574,7 +26647,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_186.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_187.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -26595,10 +26668,10 @@ function draw(gd, titleClass, options) { /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -var __FP_SAFE_206 = _$numerical_148.FP_SAFE; +/* removed: var _$lib_166 = require('../../lib'); */; +var __FP_SAFE_207 = _$numerical_148.FP_SAFE; -var _$autorange_206 = { +var _$autorange_207 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -26643,7 +26716,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_165.simpleMap(ax.range, ax.r2l); + var rng = _$lib_166.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -26736,7 +26809,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_165.simpleMap(newRange, ax.l2r || Number); + return _$lib_166.simpleMap(newRange, ax.l2r || Number); } /* @@ -26768,7 +26841,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_165.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_166.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -26790,7 +26863,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_165.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_166.extendFlat({}, axeRangeOpts); } } @@ -26803,6 +26876,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -26863,14 +26938,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_206) vmax = v; + if(v > vmax && v < __FP_SAFE_207) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_206) vmin = v; - if(v > vmax && v < __FP_SAFE_206) vmax = v; + if(v < vmin && v > -__FP_SAFE_207) vmin = v; + if(v > vmax && v < __FP_SAFE_207) vmax = v; } } @@ -26904,7 +26979,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_206 : __lessOrEqual_206; + var atLeastAsExtreme = k ? __greaterOrEqual_207 : __lessOrEqual_207; includeThis = true; /* @@ -26955,13 +27030,12 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_13(v) && Math.abs(v) < __FP_SAFE_206; + return _$fastIsnumeric_13(v) && Math.abs(v) < __FP_SAFE_207; } -function __lessOrEqual_206(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_206(v0, v1) { return v0 >= v1; } +function __lessOrEqual_207(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_207(v0, v1) { return v0 >= v1; } -var _$axes_207 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -26973,2784 +27047,2933 @@ var _$axes_207 = {}; 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$titles_139 = require('../../components/titles'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +var __BADNUM_209 = _$numerical_148.BADNUM; -/* removed: var _$numerical_148 = require('../../constants/numerical'); */; -var ONEAVGYEAR = _$numerical_148.ONEAVGYEAR; -var ONEAVGMONTH = _$numerical_148.ONEAVGMONTH; -var __ONEDAY_207 = _$numerical_148.ONEDAY; -var __ONEHOUR_207 = _$numerical_148.ONEHOUR; -var __ONEMIN_207 = _$numerical_148.ONEMIN; -var __ONESEC_207 = _$numerical_148.ONESEC; -var MINUS_SIGN = _$numerical_148.MINUS_SIGN; -var __BADNUM_207 = _$numerical_148.BADNUM; +var _$autoType_209 = function autoType(array, calendar) { + if(moreDates(array, calendar)) return 'date'; + if(category(array)) return 'category'; + if(linearOK(array)) return 'linear'; + else return '-'; +}; -var MID_SHIFT = _$alignment_146.MID_SHIFT; -var __LINE_SPACING_207 = _$alignment_146.LINE_SPACING; +// is there at least one number in array? If not, we should leave +// ax.type empty so it can be autoset later +function linearOK(array) { + if(!array) return false; -var axes = _$axes_207 = {}; + for(var i = 0; i < array.length; i++) { + if(_$fastIsnumeric_13(array[i])) return true; + } -axes.setConvert = _$setConvert_226; -/* removed: var _$autoType_208 = require('./axis_autotype'); */; + return false; +} -/* removed: var _$axis_ids_210 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_210.id2name; -axes.name2id = _$axis_ids_210.name2id; -axes.cleanId = _$axis_ids_210.cleanId; -axes.list = _$axis_ids_210.list; -axes.listIds = _$axis_ids_210.listIds; -axes.getFromId = _$axis_ids_210.getFromId; -axes.getFromTrace = _$axis_ids_210.getFromTrace; +// does the array a have mostly dates rather than numbers? +// note: some values can be neither (such as blanks, text) +// 2- or 4-digit integers can be both, so require twice as many +// dates as non-dates, to exclude cases with mostly 2 & 4 digit +// numbers and a few dates +function moreDates(a, calendar) { + var dcnt = 0, + ncnt = 0, + // test at most 1000 points, evenly spaced + inc = Math.max(1, (a.length - 1) / 1000), + ai; -/* removed: var _$autorange_206 = require('./autorange'); */; -axes.expand = _$autorange_206.expand; -axes.getAutoRange = _$autorange_206.getAutoRange; + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_166.isDateTime(ai, calendar)) dcnt += 1; + if(_$fastIsnumeric_13(ai)) ncnt += 1; + } -/* - * 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 = {}; + return (dcnt > ncnt * 2); +} - if(!dflt) dflt = axlist[0] || extraOption; - if(!extraOption) extraOption = dflt; +// are the (x,y)-values in gd.data mostly text? +// require twice as many categories as numbers +function category(a) { + // test at most 1000 points + var inc = Math.max(1, (a.length - 1) / 1000), + curvenums = 0, + curvecats = 0, + ai; - // data-ref annotations are not supported in gl2d yet + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_166.cleanNumber(ai) !== __BADNUM_209) curvenums++; + else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; + } - attrDef[refAttr] = { - valType: 'enumerated', - values: axlist.concat(extraOption ? [extraOption] : []), - dflt: dflt - }; + return curvecats > curvenums * 2; +} - // xref, yref - return _$lib_165.coerce(containerIn, containerOut, attrDef, refAttr); -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * 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 + +'use strict'; + +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + +/* removed: var _$lib_166 = require('../../lib'); */; +var cleanNumber = _$lib_166.cleanNumber; +var ms2DateTime = _$lib_166.ms2DateTime; +var dateTime2ms = _$lib_166.dateTime2ms; +var ensureNumber = _$lib_166.ensureNumber; + +/* removed: var _$numerical_148 = require('../../constants/numerical'); */; +var __FP_SAFE_226 = _$numerical_148.FP_SAFE; +var __BADNUM_226 = _$numerical_148.BADNUM; + +/* removed: var _$constants_213 = require('./constants'); */; +/* removed: var _$axis_ids_211 = require('./axis_ids'); */; + +function fromLog(v) { + return Math.pow(10, v); +} + +/** + * Define the conversion functions for an axis data is used in 5 ways: * - * 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 + * 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. * - * 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 + * Creates/updates these conversion functions, and a few more utilities + * like cleanRange, and makeCalcdata + * + * also clears the autorange bounds ._min and ._max + * and the autotick constraints ._minDtick, ._forceTick0 */ -axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { - var cleanPos, pos; +var _$setConvert_226 = function setConvert(ax, fullLayout) { + fullLayout = fullLayout || {}; - if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_165.ensureNumber; - pos = coerce(attr, dflt); - } else { - var ax = axes.getFromId(gd, axRef); - dflt = ax.fraction2r(dflt); - pos = coerce(attr, dflt); - cleanPos = ax.cleanPos; + var axLetter = (ax._id || 'x').charAt(0); + + // clipMult: how many axis lengths past the edge do we render? + // for panning, 1-2 would suffice, but for zooming more is nice. + // also, clipping can affect the direction of lines off the edge... + var clipMult = 10; + + 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 clipMult axis + // length past the negative edge + var r0 = ax.range[0], + r1 = ax.range[1]; + return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); + } + + else return __BADNUM_226; } - containerOut[attr] = cleanPos(pos); -}; + /* + * 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_226) { + if(_$fastIsnumeric_13(v)) ms = dateTime2ms(new Date(+v)); + else return __BADNUM_226; + } + return ms; + } -axes.cleanPosition = function(pos, gd, axRef) { - var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_165.ensureNumber : - axes.getFromId(gd, axRef).cleanPos; + // wrapped ms2DateTime to insert default ax.calendar + function ms2dt(v, r, calendar) { + return ms2DateTime(v, r, calendar || ax.calendar); + } - return cleanPos(pos); -}; + function getCategoryName(v) { + return ax._categories[Math.round(v)]; + } -var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { - var ax; + /* + * 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(v !== null && v !== undefined) { + if(ax._categoriesMap === undefined) { + ax._categoriesMap = {}; + } - // 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; + if(ax._categoriesMap[v] !== undefined) { + return ax._categoriesMap[v]; + } else { + ax._categories.push(v); - // 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_208(targetArray), - _categories: [] - }; - axes.setConvert(ax); + var curLength = ax._categories.length - 1; + ax._categoriesMap[v] = curLength; - // 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]); + return curLength; } } - } else { - ax = axes.getFromTrace(gd, trace, d2cTarget); + return __BADNUM_226; } - // 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}; + function getCategoryIndex(v) { + // d2l/d2c variant that that won't add categories but will also + // allow numbers to be mapped to the linearized axis positions + if(ax._categoriesMap) { + var index = ax._categoriesMap[v]; + if(index !== undefined) return index; + } - // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size') - // -> cast to Number + if(_$fastIsnumeric_13(v)) return +v; + } - return {d2c: toNum, c2d: toNum}; -}; + function l2p(v) { + if(!_$fastIsnumeric_13(v)) return __BADNUM_226; -function toNum(v) { return +v; } -function toString(v) { return String(v); } + // include 2 fractional digits on pixel, for PDF zooming etc + return _$d3_10.round(ax._b + ax._m * v, 2); + } -axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { - return getDataConversions(gd, trace, target, targetArray).d2c; -}; + function p2l(px) { return (px - ax._b) / ax._m; } -// 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'; -}; + // 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; -// 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'].indexOf(ax.type) !== -1 || !allow) { - ax._minDtick = 0; - } - // undefined means there's nothing there yet - else if(ax._minDtick === undefined) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - else if(ax._minDtick) { - // existing minDtick is an integer multiple of newDiff - // (within rounding err) - // and forceTick0 can be shifted to newFirst - if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && - (((newFirst - ax._forceTick0) / newDiff % 1) + - 1.000001) % 1 < 2e-6) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - // 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 - else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || - (((newFirst - ax._forceTick0) / ax._minDtick % 1) + - 1.000001) % 1 > 2e-6) { - ax._minDtick = 0; - } - } -}; + ax.l2p = l2p; + ax.p2l = p2l; -// 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), - hasOneAxisChanged = false; + 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; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + /* + * 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; - var isNew = (ax._rangeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.range[0] === ax._rangeInitial[0] && - ax.range[1] === ax._rangeInitial[1] - ) - ); + ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2d = ax.p2r = p2l; - if((isNew && ax.autorange === false) || (overwrite && hasChanged)) { - ax._rangeInitial = ax.range.slice(); - hasOneAxisChanged = true; - } + 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)); }; - return hasOneAxisChanged; -}; + ax.d2c = ax.r2l = cleanNumber; + ax.c2d = ax.l2r = ensureNumber; -// save a copy of the initial spike visibility -axes.saveShowSpikeInitial = function(gd, overwrite) { - var axList = axes.list(gd, '', true), - hasOneAxisChanged = false, - allSpikesEnabled = 'on'; + ax.c2r = toLog; + ax.l2d = fromLog; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); }; + ax.p2d = function(px) { return fromLog(p2l(px)); }; - var isNew = (ax._showSpikeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.showspikes === ax._showspikes - ) - ); + ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2r = p2l; - if((isNew) || (overwrite && hasChanged)) { - ax._showSpikeInitial = ax.showspikes; - hasOneAxisChanged = true; - } + ax.cleanPos = ensureNumber; + } + else if(ax.type === 'date') { + // r and d are date strings, l and c are ms - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } + /* + * 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_166.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_166.cleanDate(v, __BADNUM_226, ax.calendar); }; } - gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - return hasOneAxisChanged; -}; + else if(ax.type === 'category') { + // d is categories (string) + // c and l are indices (numbers) + // r is categories or numbers -axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_165.aggNums(Math.min, null, data), - dataMax = _$lib_165.aggNums(Math.max, null, data); + ax.d2c = ax.d2l = setCategoryIndex; + ax.r2d = ax.c2d = ax.l2d = getCategoryName; - if(!calendar) calendar = ax.calendar; + ax.d2r = ax.d2l_noadd = getCategoryIndex; - if(ax.type === 'category') { - return { - start: dataMin - 0.5, - end: dataMax + 0.5, - size: 1, - _dataSpan: dataMax - dataMin, + ax.r2c = function(v) { + var index = getCategoryIndex(v); + return index !== undefined ? index : ax.fraction2r(0.5); }; - } - 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_165.distinctVals(data), - msexp = Math.pow(10, Math.floor( - Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_165.roundUp( - distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_165.stdev(data) / - Math.pow(data.length, is2d ? 0.25 : 0.4)); + ax.l2r = ax.c2r = ensureNumber; + ax.r2l = getCategoryIndex; - // fallback if ax.d2c output BADNUMs - // e.g. when user try to plot categorical bins - // on a layout.xaxis.type: 'linear' - if(!_$fastIsnumeric_13(size0)) size0 = 1; - } + 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; - // piggyback off autotick code to make "nice" bin sizes - var dummyAx; - if(ax.type === 'log') { - dummyAx = { - type: 'linear', - range: [dataMin, dataMax] - }; - } - else { - dummyAx = { - type: ax.type, - range: _$lib_165.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), - calendar: calendar + ax.cleanPos = function(v) { + if(typeof v === 'string' && v !== '') return v; + return ensureNumber(v); }; } - axes.setConvert(dummyAx); - axes.autoTicks(dummyAx, size0); - var binStart = axes.tickIncrement( - axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); - var binEnd, bincount; + // find the range value at the specified (linear) fraction of the axis + ax.fraction2r = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return ax.l2r(rl0 + v * (rl1 - rl0)); + }; - // 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 dummyAx.dtick === 'number') { - binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + // find the fraction of the range at the specified range value + ax.r2fraction = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return (ax.r2l(v) - rl0) / (rl1 - rl0); + }; - bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); - binEnd = binStart + bincount * dummyAx.dtick; - } - 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, dummyAx.dtick, dataMin, calendar); + /* + * 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_166.nestedProperty(ax, rangeAttr).get(); + var i, dflt; + + if(ax.type === 'date') dflt = _$lib_166.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_213.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_213.DFLTRANGEX; + + // make sure we don't later mutate the defaults + dflt = dflt.slice(); + + if(!range || range.length !== 2) { + _$lib_166.nestedProperty(ax, rangeAttr).set(dflt); + return; } - // 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, dummyAx.dtick, false, calendar); - bincount++; + if(ax.type === 'date') { + // check if milliseconds or js date objects are provided for range + // and convert to date strings + range[0] = _$lib_166.cleanDate(range[0], __BADNUM_226, ax.calendar); + range[1] = _$lib_166.cleanDate(range[1], __BADNUM_226, ax.calendar); } - } - return { - start: ax.c2r(binStart, 0, calendar), - end: ax.c2r(binEnd, 0, calendar), - size: dummyAx.dtick, - _dataSpan: dataMax - dataMin - }; -}; + for(i = 0; i < 2; i++) { + if(ax.type === 'date') { + if(!_$lib_166.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_166.constrain(ax.r2l(range[0]), + _$lib_166.MIN_MS + 1000, _$lib_166.MAX_MS - 1000); + range[0] = ax.l2r(linCenter - 1000); + range[1] = ax.l2r(linCenter + 1000); + break; + } + } + else { + if(!_$fastIsnumeric_13(range[i])) { + if(_$fastIsnumeric_13(range[1 - i])) { + range[i] = range[1 - i] * (i ? 10 : 0.1); + } + else { + ax[rangeAttr] = dflt; + break; + } + } -function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { - var edgecount = 0, - midcount = 0, - intcount = 0, - blankCount = 0; + if(range[i] < -__FP_SAFE_226) range[i] = -__FP_SAFE_226; + else if(range[i] > __FP_SAFE_226) range[i] = __FP_SAFE_226; - function nearEdge(v) { - // is a value within 1% of a bin edge? - return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; - } + 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; + } + } + } + }; - for(var i = 0; i < data.length; i++) { - if(data[i] % 1 === 0) intcount++; - else if(!_$fastIsnumeric_13(data[i])) blankCount++; + // set scaling to pixels + ax.setScale = function(usePrivateRange) { + var gs = fullLayout._size; - if(nearEdge(data[i])) edgecount++; - if(nearEdge(data[i] + ax.dtick / 2)) midcount++; - } - var dataCount = data.length - blankCount; + // TODO cleaner way to handle this case + if(!ax._categories) ax._categories = []; + // Add a map to optimize the performance of category collection + if(!ax._categoriesMap) ax._categoriesMap = {}; - if(intcount === dataCount && ax.type !== 'date') { - // 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 - if(ax.dtick < 1) { - binStart = dataMin - 0.5 * ax.dtick; - } - // 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. - else { - 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; + // make sure we have a domain (pull it in from the axis + // this one is overlaying if necessary) + if(ax.overlaying) { + var ax2 = _$axis_ids_211.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + ax.domain = ax2.domain; } - } - return binStart; -} + // 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', + calendar = ax.calendar; + ax.cleanRange(rangeAttr); -function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_165.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)); + var rl0 = ax.r2l(ax[rangeAttr][0], calendar), + rl1 = ax.r2l(ax[rangeAttr][1], calendar); - 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_207 * 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_207 * 15.5; + 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 { - // 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_207 / 2; + 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; } - var nextBinStart = axes.tickIncrement(binStart, dtick); - if(nextBinStart <= dataMin) return nextBinStart; - } - return binStart; -} + if(!isFinite(ax._m) || !isFinite(ax._b)) { + fullLayout._replotting = false; + throw new Error('Something went wrong with axis scaling'); + } + }; -// ---------------------------------------------------- -// Ticks and grids -// ---------------------------------------------------- + // 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; -// ensure we have tick0, dtick, and tick rounding calculated -axes.prepTicks = function(ax) { - var rng = _$lib_165.simpleMap(ax.range, ax.r2l); + var axType = ax.type; + var cal = axType === 'date' && trace[axLetter + 'calendar']; - // calculate max number of (auto) ticks to display based on plot size - if(ax.tickmode === 'auto' || !ax.dtick) { - var nt = ax.nticks, - minPx; - if(!nt) { - if(ax.type === 'category') { - 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_165.constrain(ax._length / minPx, 4, 9) + 1; + if(axLetter in trace) { + arrayIn = trace[axLetter]; + len = trace._length || arrayIn.length; + + if(_$lib_166.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(len === arrayIn.length) { + return arrayIn; + } else if(arrayIn.subarray) { + return arrayIn.subarray(0, len); + } } - // radial axes span half their domain, - // multiply nticks value by two to get correct number of auto ticks. - if(ax._name === 'radialaxis') nt *= 2; + 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; - // add a couple of extra digits for filling in ticks when we - // have explicit tickvals without tick text - if(ax.tickmode === 'array') nt *= 100; + // 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); - 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); + for(i = 0; i < len; i++) { + arrayOut[i] = v0 + i * dv; + } } - } - // check for missing tick0 - if(!ax.tick0) { - ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; - } + return arrayOut; + }; - // now figure out rounding of tick values - autoTickRound(ax); -}; + ax.isValidRange = function(range) { + return ( + Array.isArray(range) && + range.length === 2 && + _$fastIsnumeric_13(ax.r2l(range[0])) && + _$fastIsnumeric_13(ax.r2l(range[1])) + ); + }; -// 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_165.simpleMap(ax.range, ax.r2l); + 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]); - // 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); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } + }; - // find the first tick - ax._tmin = axes.tickFirst(ax); + ax.clearCalc = function() { + // for autoranging: arrays of objects: + // { + // val: axis value, + // pad: pixel padding, + // extrapad: boolean, should this val get 5% additional padding + // } + ax._min = []; + ax._max = []; - // 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]); + // initialize the category list, if there is one, so we start over + // to be filled in later by ax.d2c + ax._categories = (ax._initialCategories || []).slice(); - // No visible ticks? Quit. - // I've only seen this on category axes with all categories off the edge. - if((ax._tmin < startTick) !== axrev) return []; + // Build the lookup map for initialized categories + ax._categoriesMap = {}; + for(var j = 0; j < ax._categories.length; j++) { + ax._categoriesMap[ax._categories[j]] = j; + } + }; - // return the full set of tick vals - var vals = []; - if(ax.type === 'category') { - endTick = (axrev) ? Math.max(-0.5, endTick) : - Math.min(ax._categories.length - 0.5, endTick); + // 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_10.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_10.format; - 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(vals.length > maxTicks || x === xPrevious) break; - xPrevious = x; + // and for bar charts and box plots: reset forced minimum tick spacing + delete ax._minDtick; + delete ax._forceTick0; +}; - vals.push(x); - } +var _$axes_208 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // If same angle over a full circle, the last tick vals is a duplicate. - // TODO must do something similar for angular date axes. - if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { - vals.pop(); - } - // save the last tick as well as first, so we can - // show the exponent only on the last one - ax._tmax = vals[vals.length - 1]; +'use strict'; - // 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; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; - var ticksOut = new Array(vals.length); - for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$titles_139 = require('../../components/titles'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; - ax._inCalcTicks = false; +/* removed: var _$numerical_148 = require('../../constants/numerical'); */; +var ONEAVGYEAR = _$numerical_148.ONEAVGYEAR; +var ONEAVGMONTH = _$numerical_148.ONEAVGMONTH; +var __ONEDAY_208 = _$numerical_148.ONEDAY; +var __ONEHOUR_208 = _$numerical_148.ONEHOUR; +var __ONEMIN_208 = _$numerical_148.ONEMIN; +var __ONESEC_208 = _$numerical_148.ONESEC; +var MINUS_SIGN = _$numerical_148.MINUS_SIGN; +var __BADNUM_208 = _$numerical_148.BADNUM; - return ticksOut; -}; +var MID_SHIFT = _$alignment_146.MID_SHIFT; +var __LINE_SPACING_208 = _$alignment_146.LINE_SPACING; -function arrayTicks(ax) { - var vals = ax.tickvals, - text = ax.ticktext, - ticksOut = new Array(vals.length), - rng = _$lib_165.simpleMap(ax.range, ax.r2l), - r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, - r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, - tickMin = Math.min(r0expanded, r1expanded), - tickMax = Math.max(r0expanded, r1expanded), - vali, - i, - j = 0; +var axes = _$axes_208 = {}; - // 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 = []; +axes.setConvert = _$setConvert_226; +/* removed: var _$autoType_209 = require('./axis_autotype'); */; - // make sure showing ticks doesn't accidentally add new categories - var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; +/* removed: var _$axis_ids_211 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_211.id2name; +axes.name2id = _$axis_ids_211.name2id; +axes.cleanId = _$axis_ids_211.cleanId; +axes.list = _$axis_ids_211.list; +axes.listIds = _$axis_ids_211.listIds; +axes.getFromId = _$axis_ids_211.getFromId; +axes.getFromTrace = _$axis_ids_211.getFromTrace; - // 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); - } +/* removed: var _$autorange_207 = require('./autorange'); */; +axes.expand = _$autorange_207.expand; +axes.getAutoRange = _$autorange_207.getAutoRange; - for(i = 0; i < vals.length; i++) { - 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++; - } - } +/* + * 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(j < vals.length) ticksOut.splice(j, vals.length - j); + if(!dflt) dflt = axlist[0] || extraOption; + if(!extraOption) extraOption = dflt; - return ticksOut; -} + // data-ref annotations are not supported in gl2d yet -var roundBase10 = [2, 5, 10], - roundBase24 = [1, 2, 3, 6, 12], - roundBase60 = [1, 2, 5, 10, 15, 30], - // 2&3 day ticks are weird, but need something btwn 1&7 - 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 - roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], - roundLog2 = [-0.301, 0, 0.301, 0.699, 1], - // N.B. `thetaunit; 'radians' angular axes must be converted to degrees - roundAngles = [15, 30, 45, 90, 180]; + attrDef[refAttr] = { + valType: 'enumerated', + values: axlist.concat(extraOption ? [extraOption] : []), + dflt: dflt + }; -function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_165.roundUp(roughDTick / base, roundingSet); -} + // xref, yref + return _$lib_166.coerce(containerIn, containerOut, attrDef, refAttr); +}; -// 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; +/* + * 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; - function getBase(v) { - return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); + if(axRef === 'paper' || axRef === 'pixel') { + cleanPos = _$lib_166.ensureNumber; + pos = coerce(attr, dflt); + } else { + var ax = axes.getFromId(gd, axRef); + dflt = ax.fraction2r(dflt); + pos = coerce(attr, dflt); + cleanPos = ax.cleanPos; } - if(ax.type === 'date') { - ax.tick0 = _$lib_165.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; + containerOut[attr] = cleanPos(pos); +}; - 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_207) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_207, 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_165.dateTick0(ax.calendar, true); - } - else if(roughX2 > __ONEHOUR_207) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_207, roundBase24); - } - else if(roughX2 > __ONEMIN_207) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_207, roundBase60); - } - else if(roughX2 > __ONESEC_207) { - ax.dtick = roundDTick(roughDTick, __ONESEC_207, roundBase60); - } - else { - // milliseconds - base = getBase(10); - ax.dtick = roundDTick(roughDTick, base, roundBase10); - } - } - else if(ax.type === 'log') { - ax.tick0 = 0; - var rng = _$lib_165.simpleMap(ax.range, ax.r2l); +axes.cleanPosition = function(pos, gd, axRef) { + var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? + _$lib_166.ensureNumber : + axes.getFromId(gd, axRef).cleanPos; - 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); + return cleanPos(pos); +}; - // 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'; +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_209(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]); + } } - } - else if(ax.type === 'category') { - ax.tick0 = 0; - ax.dtick = Math.ceil(Math.max(roughDTick, 1)); - } - else if(ax._id === 'angular') { - 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); + } else { + ax = axes.getFromTrace(gd, trace, d2cTarget); } - // prevent infinite loops - if(ax.dtick === 0) ax.dtick = 1; + // if 'target' has corresponding axis + // -> use setConvert method + if(ax) return {d2c: ax.d2c, c2d: ax.c2d}; - // TODO: this is from log axis histograms with autorange off - if(!_$fastIsnumeric_13(ax.dtick) && typeof ax.dtick !== 'string') { - var olddtick = ax.dtick; - ax.dtick = 1; - throw 'ax.dtick error: ' + String(olddtick); - } + // 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}; }; -// 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; +function toNum(v) { return +v; } +function toString(v) { return String(v); } - ax._tickexponent = 0; - if(!_$fastIsnumeric_13(dtick) && typeof dtick !== 'string') { - dtick = 1; - } +axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { + return getDataConversions(gd, trace, target, targetArray).d2c; +}; - if(ax.type === 'category') { - 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), - tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), - tick0len = tick0str.length; +// 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'; +}; - 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'; +// 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'].indexOf(ax.type) !== -1 || !allow) { + ax._minDtick = 0; + } + // undefined means there's nothing there yet + else if(ax._minDtick === undefined) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } + else if(ax._minDtick) { + // existing minDtick is an integer multiple of newDiff + // (within rounding err) + // and forceTick0 can be shifted to newFirst + if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && + (((newFirst - ax._forceTick0) / newDiff % 1) + + 1.000001) % 1 < 2e-6) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; } - else if((dtick >= __ONEDAY_207 && tick0len <= 10) || (dtick >= __ONEDAY_207 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_207 && tick0len <= 16) || (dtick >= __ONEHOUR_207)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_207 && tick0len <= 19) || (dtick >= __ONEMIN_207)) 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; + // 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 + else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || + (((newFirst - ax._forceTick0) / ax._minDtick % 1) + + 1.000001) % 1 > 2e-6) { + ax._minDtick = 0; } } - else if(_$fastIsnumeric_13(dtick) || dtick.charAt(0) === 'L') { - // linear or log (except D1, D2) - var rng = ax.range.map(ax.r2d || Number); - if(!_$fastIsnumeric_13(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])); +// 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), + hasOneAxisChanged = false; - 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; + 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; } } - // D1 or D2 (log) - else 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(_$fastIsnumeric_13(dtick)) return x + axSign * dtick; + return hasOneAxisChanged; +}; - // everything else is a string, one character plus a number - var tType = dtick.charAt(0), - dtSigned = axSign * Number(dtick.substr(1)); +// save a copy of the initial spike visibility +axes.saveShowSpikeInitial = function(gd, overwrite) { + var axList = axes.list(gd, '', true), + hasOneAxisChanged = false, + allSpikesEnabled = 'on'; - // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_165.incrementMonth(x, dtSigned, calendar); + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; - // Log scales: Linear, Digits - else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; + var isNew = (ax._showSpikeInitial === undefined); + var hasChanged = ( + isNew || !( + ax.showspikes === ax._showspikes + ) + ); - // 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, - x2 = x + axSign * 0.01, - frac = _$lib_165.roundUp(_$lib_165.mod(x2, 1), tickset, axrev); + if((isNew) || (overwrite && hasChanged)) { + ax._showSpikeInitial = ax.showspikes; + hasOneAxisChanged = true; + } - return Math.floor(x2) + - Math.log(_$d3_10.round(Math.pow(10, frac), 1)) / Math.LN10; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } - else throw 'unrecognized dtick ' + String(dtick); + gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + return hasOneAxisChanged; }; -// calculate the first tick on an axis -axes.tickFirst = function(ax) { - var r2l = ax.r2l || Number, - rng = _$lib_165.simpleMap(ax.range, r2l), - axrev = rng[1] < rng[0], - sRound = axrev ? Math.floor : Math.ceil, - // add a tiny extra bit to make sure we get ticks - // that may have been rounded out - r0 = rng[0] * 1.0001 - rng[1] * 0.0001, - dtick = ax.dtick, - tick0 = r2l(ax.tick0); +axes.autoBin = function(data, ax, nbins, is2d, calendar) { + var dataMin = _$lib_166.aggNums(Math.min, null, data), + dataMax = _$lib_166.aggNums(Math.max, null, data); - if(_$fastIsnumeric_13(dtick)) { - var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; + if(!calendar) calendar = ax.calendar; - // make sure no ticks outside the category list - if(ax.type === 'category') { - tmin = _$lib_165.constrain(tmin, 0, ax._categories.length - 1); - } - return tmin; + if(ax.type === 'category') { + return { + start: dataMin - 0.5, + end: dataMax + 0.5, + size: 1, + _dataSpan: dataMax - dataMin, + }; } - var tType = dtick.charAt(0), - dtNum = Number(dtick.substr(1)); - - // Dates: months (or years) - if(tType === 'M') { - var cnt = 0, - t0 = tick0, - t1, - mult, - newDTick; + 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_166.distinctVals(data), + msexp = Math.pow(10, Math.floor( + Math.log(distinctData.minDiff) / Math.LN10)), + minSize = msexp * _$lib_166.roundUp( + distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); + size0 = Math.max(minSize, 2 * _$lib_166.stdev(data) / + Math.pow(data.length, is2d ? 0.25 : 0.4)); - // 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_165.error('tickFirst did not converge', ax); - return t0; + // fallback if ax.d2c output BADNUMs + // e.g. when user try to plot categorical bins + // on a layout.xaxis.type: 'linear' + if(!_$fastIsnumeric_13(size0)) size0 = 1; } - // Log scales: Linear, Digits - else if(tType === 'L') { - return Math.log(sRound( - (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + // piggyback off autotick code to make "nice" bin sizes + var dummyAx; + if(ax.type === 'log') { + dummyAx = { + type: 'linear', + range: [dataMin, dataMax] + }; } - else if(tType === 'D') { - var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_165.roundUp(_$lib_165.mod(r0, 1), tickset, axrev); - - return Math.floor(r0) + - Math.log(_$d3_10.round(Math.pow(10, frac), 1)) / Math.LN10; + else { + dummyAx = { + type: ax.type, + range: _$lib_166.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + calendar: calendar + }; } - else throw 'unrecognized dtick ' + String(dtick); -}; + axes.setConvert(dummyAx); -// 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) { - var out = tickTextObj(ax, x), - hideexp, - arrayMode = ax.tickmode === 'array', - extraPrecision = hover || arrayMode, - i, - tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; + axes.autoTicks(dummyAx, size0); + var binStart = axes.tickIncrement( + axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); + var binEnd, bincount; - if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_165.simpleMap(ax.range, ax.r2l), - 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; + // 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 dummyAx.dtick === 'number') { + binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + + bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); + binEnd = binStart + bincount * dummyAx.dtick; + } + 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, dummyAx.dtick, dataMin, calendar); } - if(i < ax.ticktext.length) { - out.text = String(ax.ticktext[i]); - return out; + + // 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, dummyAx.dtick, false, calendar); + bincount++; } } - function isHidden(showAttr) { - var first_or_last; - - if(showAttr === undefined) return true; - if(hover) return showAttr === 'none'; + return { + start: ax.c2r(binStart, 0, calendar), + end: ax.c2r(binEnd, 0, calendar), + size: dummyAx.dtick, + _dataSpan: dataMax - dataMin + }; +}; - first_or_last = { - first: ax._tmin, - last: ax._tmax - }[showAttr]; - return showAttr !== 'all' && x !== first_or_last; - } +function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { + var edgecount = 0, + midcount = 0, + intcount = 0, + blankCount = 0; - if(hover) { - hideexp = 'never'; - } else { - hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; + function nearEdge(v) { + // is a value within 1% of a bin edge? + return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; } - if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); - else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); - else if(ax.type === 'category') formatCategory(ax, out); - else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); - else formatLinear(ax, out, hover, extraPrecision, hideexp); - - // add prefix and suffix - if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; - if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; + for(var i = 0; i < data.length; i++) { + if(data[i] % 1 === 0) intcount++; + else if(!_$fastIsnumeric_13(data[i])) blankCount++; - return out; -}; + if(nearEdge(data[i])) edgecount++; + if(nearEdge(data[i] + ax.dtick / 2)) midcount++; + } + var dataCount = data.length - blankCount; -/** - * 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_207 && val2 !== val) { - return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); + if(intcount === dataCount && ax.type !== 'date') { + // 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 + if(ax.dtick < 1) { + binStart = dataMin - 0.5 * ax.dtick; + } + // 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. + else { + binStart -= 0.5; + if(binStart + ax.dtick < dataMin) binStart += ax.dtick; + } } - - 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; + 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; +} - // 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 || {}; +function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { + var stats = _$lib_166.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; - return { - x: x, - dx: 0, - dy: 0, - text: text || '', - fontSize: tf.size, - font: tf.family, - fontColor: tf.color - }; -} + if(stats.exactDays > threshold) { + var numMonths = Number(dtick.substr(1)); -function formatDate(ax, out, hover, extraPrecision) { - var tr = ax._tickround, - fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); + 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_208 * 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_208 * 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_208 / 2; + } + var nextBinStart = axes.tickIncrement(binStart, dtick); - if(extraPrecision) { - // second or sub-second precision: extra always shows max digits. - // for other fields, extra precision just adds one field. - if(_$fastIsnumeric_13(tr)) tr = 4; - else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + if(nextBinStart <= dataMin) return nextBinStart; } + return binStart; +} - var dateStr = _$lib_165.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), - headStr; +// ---------------------------------------------------- +// Ticks and grids +// ---------------------------------------------------- - var splitIndex = dateStr.indexOf('\n'); - if(splitIndex !== -1) { - headStr = dateStr.substr(splitIndex + 1); - dateStr = dateStr.substr(0, splitIndex); - } +// ensure we have tick0, dtick, and tick rounding calculated +axes.prepTicks = function(ax) { + var rng = _$lib_166.simpleMap(ax.range, ax.r2l); - 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!) + // calculate max number of (auto) ticks to display based on plot size + if(ax.tickmode === 'auto' || !ax.dtick) { + var nt = ax.nticks, + minPx; + if(!nt) { + if(ax.type === 'category') { + 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_166.constrain(ax._length / minPx, 4, 9) + 1; + } - // can we remove the whole time part? - if(dateStr === '00:00:00' || dateStr === '00:00') { - dateStr = headStr; - headStr = ''; + // radial axes span half their domain, + // multiply nticks value by two to get correct number of auto ticks. + if(ax._name === 'radialaxis') nt *= 2; } - 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$/, ''); + + // 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); } } - 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; - } + // check for missing tick0 + if(!ax.tick0) { + ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; } - out.text = dateStr; -} + // now figure out rounding of tick values + autoTickRound(ax); +}; -function formatLog(ax, out, hover, extraPrecision, hideexp) { - var dtick = ax.dtick, - x = out.x, - tickformat = ax.tickformat; +// 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_166.simpleMap(ax.range, ax.r2l); - 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 = ''; - } + // 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); - if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; + // find the first tick + ax._tmin = axes.tickFirst(ax); - if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { - out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); - } - else if(_$fastIsnumeric_13(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_165.mod(x + 0.01, 1) < 0.1))) { - var p = Math.round(x); - if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || - (isSIFormat(ax.exponentformat) && beyondSI(p))) { - if(p === 0) out.text = 1; - else if(p === 1) out.text = '10'; - else if(p > 1) out.text = '10' + p + ''; - else out.text = '10' + MINUS_SIGN + -p + ''; + // 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]); - out.fontSize *= 1.25; - } - else { - out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover'); - if(dtick === 'D1' && ax._id.charAt(0) === 'y') { - out.dy -= out.fontSize / 6; - } - } + // 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 vals = []; + if(ax.type === 'category') { + endTick = (axrev) ? Math.max(-0.5, endTick) : + Math.min(ax._categories.length - 0.5, endTick); } - else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_165.mod(x, 1)))); - out.fontSize *= 0.75; + + 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(vals.length > maxTicks || x === xPrevious) break; + xPrevious = x; + + vals.push(x); } - 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); - } - } + // If same angle over a full circle, the last tick vals is a duplicate. + // TODO must do something similar for angular date axes. + if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { + vals.pop(); } -} -function formatCategory(ax, out) { - var tt = ax._categories[Math.round(out.x)]; - if(tt === undefined) tt = ''; - out.text = String(tt); -} + // save the last tick as well as first, so we can + // show the exponent only on the last one + ax._tmax = vals[vals.length - 1]; -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); -} + // 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; -function formatAngle(ax, out, hover, extraPrecision, hideexp) { - if(ax.thetaunit === 'radians' && !hover) { - var num = out.x / 180; + var ticksOut = new Array(vals.length); + for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); - if(num === 0) { - out.text = '0'; - } else { - var frac = num2frac(num); + ax._inCalcTicks = false; - if(frac[1] >= 100) { - out.text = numFormat(_$lib_165.deg2rad(out.x), ax, hideexp, extraPrecision); - } else { - var isNeg = out.x < 0; + return ticksOut; +}; - if(frac[1] === 1) { - if(frac[0] === 1) out.text = 'π'; - else out.text = frac[0] + 'π'; - } else { - out.text = [ - '', frac[0], '', - '⁄', - '', frac[1], '', - 'π' - ].join(''); - } +function arrayTicks(ax) { + var vals = ax.tickvals, + text = ax.ticktext, + ticksOut = new Array(vals.length), + rng = _$lib_166.simpleMap(ax.range, ax.r2l), + r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, + r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, + tickMin = Math.min(r0expanded, r1expanded), + tickMax = Math.max(r0expanded, r1expanded), + vali, + i, + j = 0; - if(isNeg) out.text = MINUS_SIGN + out.text; - } - } - } else { - out.text = numFormat(out.x, ax, hideexp, extraPrecision); - } -} + // 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 = []; -// 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; - } + // make sure showing ticks doesn't accidentally add new categories + var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - function findGCD(a, b) { - return almostEq(b, 0) ? a : findGCD(b, a % b); + // 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); } - function findPrecision(n) { - var e = 1; - while(!almostEq(Math.round(n * e) / e, n)) { - e *= 10; + for(i = 0; i < vals.length; i++) { + 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++; } - return e; } - var precision = findPrecision(num); - var number = num * precision; - var gcd = Math.abs(findGCD(number, precision)); + if(j < vals.length) ticksOut.splice(j, vals.length - j); - return [ - // numerator - Math.round(number / gcd), - // denominator - Math.round(precision / gcd) - ]; + return ticksOut; } -// 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'; -} +var roundBase10 = [2, 5, 10], + roundBase24 = [1, 2, 3, 6, 12], + roundBase60 = [1, 2, 5, 10, 15, 30], + // 2&3 day ticks are weird, but need something btwn 1&7 + 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 + roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], + roundLog2 = [-0.301, 0, 0.301, 0.699, 1], + // N.B. `thetaunit; 'radians' angular axes must be converted to degrees + roundAngles = [15, 30, 45, 90, 180]; -// 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 roundDTick(roughDTick, base, roundingSet) { + return base * _$lib_166.roundUp(roughDTick / base, roundingSet); } -function numFormat(v, ax, fmtoverride, hover) { - // negative? - var isNeg = v < 0, - // max number of digits past decimal point to show - tickRound = ax._tickround, - exponentFormat = fmtoverride || ax.exponentformat || 'B', - exponent = ax._tickexponent, - tickformat = axes.getTickFormat(ax), - separatethousands = ax.separatethousands; +// 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; - // 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 : - (_$fastIsnumeric_13(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; + function getBase(v) { + return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); } - 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; + if(ax.type === 'date') { + ax.tick0 = _$lib_166.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; - // 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; + if(roughX2 > ONEAVGYEAR) { + roughDTick /= ONEAVGYEAR; + base = getBase(10); + ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10)); } - // 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 if(roughX2 > ONEAVGMONTH) { + roughDTick /= ONEAVGMONTH; + ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); + } + else if(roughX2 > __ONEDAY_208) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_208, 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_166.dateTick0(ax.calendar, true); + } + else if(roughX2 > __ONEHOUR_208) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_208, roundBase24); + } + else if(roughX2 > __ONEMIN_208) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_208, roundBase60); + } + else if(roughX2 > __ONESEC_208) { + ax.dtick = roundDTick(roughDTick, __ONESEC_208, roundBase60); } else { - v = String(v); - var dp = v.indexOf('.') + 1; - if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); + // milliseconds + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); } - // insert appropriate decimal point and thousands separator - v = _$lib_165.numSeparate(v, ax._separators, separatethousands); } + else if(ax.type === 'log') { + ax.tick0 = 0; + var rng = _$lib_166.simpleMap(ax.range, ax.r2l); - // add exponent - if(exponent && exponentFormat !== 'hide') { - if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; + 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); - var signedExponent; - if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; - else if(exponentFormat !== 'power') signedExponent = '+' + exponent; - else signedExponent = String(exponent); - - if(exponentFormat === 'e') { - v += 'e' + signedExponent; - } - else if(exponentFormat === 'E') { - v += 'E' + signedExponent; - } - else if(exponentFormat === 'power') { - v += '×10' + signedExponent + ''; - } - else if(exponentFormat === 'B' && exponent === 9) { - v += 'B'; + // 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 if(isSIFormat(exponentFormat)) { - v += SIPREFIXES[exponent / 3 + 5]; + 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.tick0 = 0; + ax.dtick = Math.ceil(Math.max(roughDTick, 1)); + } + else if(ax._id === 'angular') { + 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); + } - // 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; + // prevent infinite loops + if(ax.dtick === 0) ax.dtick = 1; - function convertToMs(dtick) { - return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH; + // TODO: this is from log axis histograms with autorange off + if(!_$fastIsnumeric_13(ax.dtick) && typeof ax.dtick !== 'string') { + var olddtick = ax.dtick; + ax.dtick = 1; + throw 'ax.dtick error: ' + String(olddtick); } +}; - 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; - } +// 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(!_$fastIsnumeric_13(dtick) && typeof dtick !== 'string') { + dtick = 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)); + if(ax.type === 'category') { + 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), + tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), + tick0len = tick0str.length; - 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); + 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_208 && tick0len <= 10) || (dtick >= __ONEDAY_208 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_208 && tick0len <= 16) || (dtick >= __ONEHOUR_208)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_208 && tick0len <= 19) || (dtick >= __ONEMIN_208)) 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; + } } + else if(_$fastIsnumeric_13(dtick) || dtick.charAt(0) === 'L') { + // linear or log (except D1, D2) + var rng = ax.range.map(ax.r2d || Number); + if(!_$fastIsnumeric_13(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 tickstop; - if(ax.tickformatstops && ax.tickformatstops.length > 0) { - switch(ax.type) { - case 'date': - case 'linear': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; - } - case 'log': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; + 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); } - default: + else ax._tickexponent = rangeexp; } } - return tickstop ? tickstop.value : ax.tickformat; -}; + // D1 or D2 (log) + else ax._tickround = null; +} -// 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 -axes.getSubplots = function(gd, ax) { - var subplotObj = gd._fullLayout._subplots; - var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); +// 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; - var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; + // includes linear, all dates smaller than month, and pure 10^n in log + if(_$fastIsnumeric_13(dtick)) return x + axSign * dtick; - out.sort(function(a, b) { - var aParts = a.substr(1).split('y'); - var bParts = b.substr(1).split('y'); + // everything else is a string, one character plus a number + var tType = dtick.charAt(0), + dtSigned = axSign * Number(dtick.substr(1)); - if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; - return +aParts[0] - +bParts[0]; - }); + // Dates: months (or years - see Lib.incrementMonth) + if(tType === 'M') return _$lib_166.incrementMonth(x, dtSigned, calendar); - return out; -}; + // Log scales: Linear, Digits + else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; -// find all subplots with axis 'ax' -axes.findSubplotsWithAxis = function(subplots, ax) { - var axMatch = new RegExp( - (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') - ); - var subplotsWithAxis = []; + // 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, + x2 = x + axSign * 0.01, + frac = _$lib_166.roundUp(_$lib_166.mod(x2, 1), tickset, axrev); - for(var i = 0; i < subplots.length; i++) { - var sp = subplots[i]; - if(axMatch.test(sp)) subplotsWithAxis.push(sp); + return Math.floor(x2) + + Math.log(_$d3_10.round(Math.pow(10, frac), 1)) / Math.LN10; } - - return subplotsWithAxis; + else throw 'unrecognized dtick ' + String(dtick); }; -// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings -axes.makeClipPaths = function(gd) { - var fullLayout = gd._fullLayout; - 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; +// calculate the first tick on an axis +axes.tickFirst = function(ax) { + var r2l = ax.r2l || Number, + rng = _$lib_166.simpleMap(ax.range, r2l), + axrev = rng[1] < rng[0], + sRound = axrev ? Math.floor : Math.ceil, + // add a tiny extra bit to make sure we get ticks + // that may have been rounded out + r0 = rng[0] * 1.0001 - rng[1] * 0.0001, + dtick = ax.dtick, + tick0 = r2l(ax.tick0); - 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]}); + if(_$fastIsnumeric_13(dtick)) { + var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; + + // make sure no ticks outside the category list + if(ax.type === 'category') { + tmin = _$lib_166.constrain(tmin, 0, ax._categories.length - 1); } + return tmin; } - // 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'); + var tType = dtick.charAt(0), + dtNum = Number(dtick.substr(1)); - axClips.exit().remove(); + // Dates: months (or years) + if(tType === 'M') { + var cnt = 0, + t0 = tick0, + t1, + mult, + newDTick; - axClips.each(function(d) { - _$d3_10.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 - }); - }); -}; + // 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_166.error('tickFirst did not converge', ax); + return t0; + } -// doTicks: draw ticks, grids, and tick labels -// axid: 'x', 'y', 'x2' etc, -// blank to do all, -// 'redraw' to force full redraw, and reset: -// ax._r (stored range for use by zoom/pan) -// ax._rl (stored linearized range for use by zoom/pan) -// or can pass in an axis object directly -axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + // Log scales: Linear, Digits + else if(tType === 'L') { + return Math.log(sRound( + (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + } + else if(tType === 'D') { + var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, + frac = _$lib_166.roundUp(_$lib_166.mod(r0, 1), tickset, axrev); - // allow passing an independent axis object instead of id - if(typeof axid === 'object') { - ax = axid; - axid = ax._id; - independent = true; + return Math.floor(r0) + + Math.log(_$d3_10.round(Math.pow(10, frac), 1)) / Math.LN10; } - else { - ax = axes.getFromId(gd, axid); + else throw 'unrecognized dtick ' + String(dtick); +}; - if(axid === 'redraw') { - fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); - fullLayout._infolayer.select('.g-' + xa._id + 'title').remove(); - fullLayout._infolayer.select('.g-' + ya._id + 'title').remove(); - }); - } +// 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) { + var out = tickTextObj(ax, x), + hideexp, + arrayMode = ax.tickmode === 'array', + extraPrecision = hover || arrayMode, + i, + tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - if(!axid || axid === 'redraw') { - return _$lib_165.syncOrAsync(axes.list(gd, '', true).map(function(ax) { - return function() { - if(!ax._id) return; - var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_165.simpleMap(ax._r, ax.r2l); - } - return axDone; - }; - })); + if(arrayMode && Array.isArray(ax.ticktext)) { + var rng = _$lib_166.simpleMap(ax.range, ax.r2l), + 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; } } - // set scaling to pixels - ax.setScale(); + function isHidden(showAttr) { + var first_or_last; - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_71.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_71.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_71.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + if(showAttr === undefined) return true; + if(hover) return showAttr === 'none'; - if(ax._counterangle && ax.ticks === 'outside') { - var caRad = ax._counterangle * Math.PI / 180; - labelStandoff = ax.ticklen * Math.cos(caRad) + 1; - labelShift = ax.ticklen * Math.sin(caRad); - } + first_or_last = { + first: ax._tmin, + last: ax._tmax + }[showAttr]; - if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { - labelStandoff += 0.2 * ax.tickfont.size; + return showAttr !== 'all' && x !== first_or_last; } - // positioning arguments for x vs y axes - if(axLetter === 'x') { - sides = ['bottom', 'top']; - transfn = ax._transfn || function(d) { - return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); - } - else return 'M0,' + shift + 'v' + len; - }; - } - else if(axLetter === 'y') { - sides = ['left', 'right']; - transfn = ax._transfn || function(d) { - return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); - } - else return 'M' + shift + ',0h' + len; - }; - } - else if(axid === 'angular') { - sides = ['left', 'right']; - transfn = ax._transfn; - tickpathfn = function(shift, len) { - return 'M' + shift + ',0h' + len; - }; - } - else { - _$lib_165.warn('Unrecognized doTicks axis:', axid); - return; - } - var axside = ax.side || sides[0], - // which direction do the side[0], side[1], and free ticks go? - // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; - if((ax.ticks !== 'inside') === (axLetter === 'x')) { - ticksign = ticksign.map(function(v) { return -v; }); + if(hover) { + hideexp = 'never'; + } else { + hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; } - if(!ax.visible) return; + if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); + else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); + else if(ax.type === 'category') formatCategory(ax, out); + else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); + else formatLinear(ax, out, hover, extraPrecision, hideexp); - if(ax._tickFilter) { - vals = vals.filter(ax._tickFilter); - } + // add prefix and suffix + if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; + if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; - // remove zero lines, grid lines, and inside ticks if they're within - // 1 pixel of the end - // The key case here is removing zero lines when the axis bound is zero. - function clipEnds(d) { - var p = ax.l2p(d.x); - return (p > 1 && p < ax._length - 1); - } - var valsClipped = vals.filter(clipEnds); + return out; +}; - // don't clip angular values - if(ax._id === 'angular') { - valsClipped = vals; +/** + * 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_208 && val2 !== val) { + return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } - function drawTicks(container, tickpath) { - var ticks = container.selectAll('path.' + tcls) - .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); - if(tickpath && ax.ticks) { - ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) - .classed('crisp', 1) - .call(_$color_46.stroke, ax.tickcolor) - .style('stroke-width', tickWidth + 'px') - .attr('d', tickpath); - ticks.attr('transform', transfn); - ticks.exit().remove(); - } - else ticks.remove(); + 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; } - function drawLabels(container, position) { - // tick labels - for now just the main labels. - // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + // 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; +}; - if(!_$fastIsnumeric_13(position)) { - tickLabels.remove(); - drawAxTitle(); - return; - } - if(!ax.showticklabels) { - tickLabels.remove(); - drawAxTitle(); - calcBoundingBox(); - return; - } +function tickTextObj(ax, x, text) { + var tf = ax.tickfont || {}; - var labelx, labely, labelanchor, labelpos0, flipit; - if(axLetter === 'x') { - flipit = (axside === 'bottom') ? 1 : -1; - labelx = function(d) { return d.dx + labelShift * flipit; }; - labelpos0 = position + (labelStandoff + pad) * flipit; - labely = function(d) { - return d.dy + labelpos0 + d.fontSize * - ((axside === 'bottom') ? 1 : -0.2); - }; - labelanchor = function(angle) { - if(!_$fastIsnumeric_13(angle) || angle === 0 || angle === 180) { - return 'middle'; - } - return (angle * flipit < 0) ? 'end' : 'start'; - }; - } - else if(axLetter === 'y') { - flipit = (axside === 'right') ? 1 : -1; - labely = function(d) { - return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; - }; - labelx = function(d) { - return d.dx + position + (labelStandoff + pad + - ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; - }; - labelanchor = function(angle) { - if(_$fastIsnumeric_13(angle) && Math.abs(angle) === 90) { - return 'middle'; - } - return axside === 'right' ? 'start' : 'end'; - }; - } - else if(axid === 'angular') { - ax._labelShift = labelShift; - ax._labelStandoff = labelStandoff; - ax._pad = pad; + return { + x: x, + dx: 0, + dy: 0, + text: text || '', + fontSize: tf.size, + font: tf.family, + fontColor: tf.color + }; +} - labelx = ax._labelx; - labely = ax._labely; - labelanchor = ax._labelanchor; - } +function formatDate(ax, out, hover, extraPrecision) { + var tr = ax._tickround, + fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); - var maxFontSize = 0, - autoangle = 0, - labelsReady = []; - tickLabels.enter().append('g').classed(tcls, 1) - .append('text') - // only so tex has predictable alignment that we can - // alter later - .attr('text-anchor', 'middle') - .each(function(d) { - var thisLabel = _$d3_10.select(this), - newPromise = gd._promises.length; - thisLabel - .call(_$svg_text_utils_186.positionText, labelx(d), labely(d)) - .call(_$drawing_71.font, d.font, d.fontSize, d.fontColor) - .text(d.text) - .call(_$svg_text_utils_186.convertToTspans, gd); - newPromise = gd._promises[newPromise]; - if(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, ax.tickangle); - })); - } - else { - // sync label: just position it now. - positionLabels(thisLabel, ax.tickangle); - } - }); - tickLabels.exit().remove(); + if(extraPrecision) { + // second or sub-second precision: extra always shows max digits. + // for other fields, extra precision just adds one field. + if(_$fastIsnumeric_13(tr)) tr = 4; + else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + } - tickLabels.each(function(d) { - maxFontSize = Math.max(maxFontSize, d.fontSize); - }); + var dateStr = _$lib_166.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + headStr; - if(axid === 'angular') { - tickLabels.each(function(d) { - _$d3_10.select(this).select('text') - .call(_$svg_text_utils_186.positionText, labelx(d), labely(d)); - }); - } + var splitIndex = dateStr.indexOf('\n'); + if(splitIndex !== -1) { + headStr = dateStr.substr(splitIndex + 1); + dateStr = dateStr.substr(0, splitIndex); + } - // How much to shift a multi-line label to center it vertically. - function getAnchorHeight(lineCount, lineHeight, angle) { - var h = (lineCount - 1) * lineHeight; - if(axLetter === 'x') { - if(angle < -60 || 60 < angle) { - return -0.5 * h; - } else if(axside === 'top') { - return -h; - } - } else { - angle *= axside === 'left' ? 1 : -1; - if(angle < -30) { - return -h; - } else if(angle < 30) { - return -0.5 * h; - } - } - return 0; + 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$/, ''); } + } - function positionLabels(s, angle) { - s.each(function(d) { - var anchor = labelanchor(angle, d); - var thisLabel = _$d3_10.select(this), - mathjaxGroup = thisLabel.select('.text-math-group'), - transform = transfn.call(thisLabel.node(), d) + - ((_$fastIsnumeric_13(angle) && +angle !== 0) ? - (' rotate(' + angle + ',' + labelx(d) + ',' + - (labely(d) - d.fontSize / 2) + ')') : - ''); - var anchorHeight = getAnchorHeight( - _$svg_text_utils_186.lineCount(thisLabel), - __LINE_SPACING_207 * d.fontSize, - _$fastIsnumeric_13(angle) ? +angle : 0); - if(anchorHeight) { - transform += ' translate(0, ' + anchorHeight + ')'; - } - if(mathjaxGroup.empty()) { - thisLabel.select('text').attr({ - transform: transform, - 'text-anchor': anchor - }); - } - else { - var mjShift = - _$drawing_71.bBox(mathjaxGroup.node()).width * - {end: -0.5, start: 0.5}[anchor]; - mathjaxGroup.attr('transform', transform + - (mjShift ? 'translate(' + mjShift + ',0)' : '')); - } - }); + 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; } + } - // 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, ax._lastangle || ax.tickangle); + out.text = dateStr; +} - function allLabelsReady() { - return labelsReady.length && Promise.all(labelsReady); - } +function formatLog(ax, out, hover, extraPrecision, hideexp) { + var dtick = ax.dtick, + x = out.x, + tickformat = ax.tickformat; - function fixLabelOverlaps() { - positionLabels(tickLabels, ax.tickangle); + 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 = ''; + } - // check for auto-angling if x labels overlap - // don't auto-angle at all for log axes with - // base and digit format - if(axLetter === 'x' && !_$fastIsnumeric_13(ax.tickangle) && - (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { - var lbbArray = []; - tickLabels.each(function(d) { - var s = _$d3_10.select(this), - thisLabel = s.select('.text-math-group'), - x = ax.l2p(d.x); - if(thisLabel.empty()) thisLabel = s.select('text'); + if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; - var bb = _$drawing_71.bBox(thisLabel.node()); + if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { + out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); + } + else if(_$fastIsnumeric_13(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_166.mod(x + 0.01, 1) < 0.1))) { + var p = Math.round(x); + if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || + (isSIFormat(ax.exponentformat) && beyondSI(p))) { + if(p === 0) out.text = 1; + else if(p === 1) out.text = '10'; + else if(p > 1) out.text = '10' + p + ''; + else out.text = '10' + MINUS_SIGN + -p + ''; - 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 - }); - }); - for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_165.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { - // any overlap at all - set 30 degrees - autoangle = 30; - break; - } - } - if(autoangle) { - var tickspacing = Math.abs( - (vals[vals.length - 1].x - vals[0].x) * ax._m - ) / (vals.length - 1); - if(tickspacing < maxFontSize * 2.5) { - autoangle = 90; - } - positionLabels(tickLabels, autoangle); - } - ax._lastangle = autoangle; + out.fontSize *= 1.25; + } + 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(dtick.charAt(0) === 'D') { + out.text = String(Math.round(Math.pow(10, _$lib_166.mod(x, 1)))); + out.fontSize *= 0.75; + } + else throw 'unrecognized dtick ' + String(dtick); - // update the axis title - // (so it can move out of the way if needed) - // TODO: separate out scoot so we don't need to do - // a full redraw of the title (mostly relevant for MathJax) - drawAxTitle(); - return axid + ' done'; + // 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 calcBoundingBox() { - if(ax.showticklabels) { - var gdBB = gd.getBoundingClientRect(); - var bBox = container.node().getBoundingClientRect(); +function formatCategory(ax, out) { + var tt = ax._categories[Math.round(out.x)]; + if(tt === undefined) tt = ''; + out.text = String(tt); +} - /* - * the way we're going to use this, the positioning that matters - * is relative to the origin of gd. This is important particularly - * if gd is scrollable, and may have been scrolled between the time - * we calculate this and the time we use it - */ +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); +} - ax._boundingBox = { - width: bBox.width, - height: bBox.height, - left: bBox.left - gdBB.left, - right: bBox.right - gdBB.left, - top: bBox.top - gdBB.top, - bottom: bBox.bottom - gdBB.top - }; - } else { - var gs = fullLayout._size; - var pos; +function formatAngle(ax, out, hover, extraPrecision, hideexp) { + if(ax.thetaunit === 'radians' && !hover) { + var num = out.x / 180; - // set dummy bbox for ticklabel-less axes + if(num === 0) { + out.text = '0'; + } else { + var frac = num2frac(num); - if(axLetter === 'x') { - pos = ax.anchor === 'free' ? - gs.t + gs.h * (1 - ax.position) : - gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); + if(frac[1] >= 100) { + out.text = numFormat(_$lib_166.deg2rad(out.x), ax, hideexp, extraPrecision); + } else { + var isNeg = out.x < 0; - ax._boundingBox = { - top: pos, - bottom: pos, - left: ax._offset, - right: ax._offset + ax._length, - width: ax._length, - height: 0 - }; + if(frac[1] === 1) { + if(frac[0] === 1) out.text = 'π'; + else out.text = frac[0] + 'π'; } else { - pos = ax.anchor === 'free' ? - gs.l + gs.w * ax.position : - gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - - ax._boundingBox = { - left: pos, - right: pos, - bottom: ax._offset + ax._length, - top: ax._offset, - height: ax._length, - width: 0 - }; - } - } - - /* - * for spikelines: what's the full domain of positions in the - * opposite direction that are associated with this axis? - * This means any axes that we make a subplot with, plus the - * position of the axis itself if it's free. - */ - if(subplots) { - var fullRange = ax._counterSpan = [Infinity, -Infinity]; - - for(i = 0; i < subplots.length; i++) { - var subplot = fullLayout._plots[subplots[i]]; - var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - - extendRange(fullRange, [ - counterAxis._offset, - counterAxis._offset + counterAxis._length - ]); - } - - if(ax.anchor === 'free') { - extendRange(fullRange, (axLetter === 'x') ? - [ax._boundingBox.bottom, ax._boundingBox.top] : - [ax._boundingBox.right, ax._boundingBox.left]); + out.text = [ + '', frac[0], '', + '⁄', + '', frac[1], '', + 'π' + ].join(''); } - } - function extendRange(range, newRange) { - range[0] = Math.min(range[0], newRange[0]); - range[1] = Math.max(range[1], newRange[1]); + if(isNeg) out.text = MINUS_SIGN + out.text; } } + } else { + out.text = numFormat(out.x, ax, hideexp, extraPrecision); + } +} - function doAutoMargins() { - if(!ax.automargin) { return; } - if(axLetter !== 'x' && axLetter !== 'y') { return; } +// 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; + } - var s = ax.side[0]; - var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; + function findGCD(a, b) { + return almostEq(b, 0) ? a : findGCD(b, a % b); + } - if(axLetter === 'x') { - push.y = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 't' ? 1 : 0]); - push[s] += ax._boundingBox.height; - } - else { - push.x = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 'r' ? 1 : 0]); - push[s] += ax._boundingBox.width; - } + function findPrecision(n) { + var e = 1; + while(!almostEq(Math.round(n * e) / e, n)) { + e *= 10; + } + return e; + } - if(ax.title !== fullLayout._dfltTitle[axLetter]) { - push[s] += ax.titlefont.size; - } + var precision = findPrecision(num); + var number = num * precision; + var gcd = Math.abs(findGCD(number, precision)); - var pushKey = ax._name + '.automargin'; - var prevPush = fullLayout._pushmargin[pushKey]; - if(!prevPush || prevPush[s].size < push[s]) { - _$plots_240.autoMargin(gd, pushKey, push); - } - } + return [ + // numerator + Math.round(number / gcd), + // denominator + Math.round(precision / gcd) + ]; +} - var done = _$lib_165.syncOrAsync([ - allLabelsReady, - fixLabelOverlaps, - calcBoundingBox, - doAutoMargins - ]); - if(done && done.then) gd._promises.push(done); - return done; - } +// 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 drawAxTitle() { - if(skipTitle) return; +function isSIFormat(exponentFormat) { + return exponentFormat === 'SI' || exponentFormat === 'B'; +} - // now this only applies to regular cartesian axes; colorbars and - // others ALWAYS call doTicks with skipTitle=true so they can - // configure their own titles. - var ax = _$axis_ids_210.getFromId(gd, axid); +// 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; +} - // rangeslider takes over a bottom title so drop it here - if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; +function numFormat(v, ax, fmtoverride, hover) { + // negative? + var isNeg = v < 0, + // max number of digits past decimal point to show + tickRound = ax._tickround, + exponentFormat = fmtoverride || ax.exponentformat || 'B', + exponent = ax._tickexponent, + tickformat = axes.getTickFormat(ax), + separatethousands = ax.separatethousands; - var avoidSelection = _$d3_10.select(gd).selectAll('g.' + axid + 'tick'); - var avoid = { - selection: avoidSelection, - side: ax.side + // 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 : + (_$fastIsnumeric_13(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] }; - var axLetter = axid.charAt(0); - var gs = gd._fullLayout._size; - var offsetBase = 1.5; - var fontSize = ax.titlefont.size; - - var transform, counterAxis, x, y; + autoTickRound(ah); + tickRound = (Number(ah._tickround) || 0) + 4; + exponent = ah._tickexponent; + if(ax.hoverformat) tickformat = ax.hoverformat; + } - if(avoidSelection.size()) { - var translation = _$drawing_71.getTranslate(avoidSelection.node().parentNode); - avoid.offsetLeft = translation.x; - avoid.offsetTop = translation.y; - } + if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); - var titleStandoff = 10 + fontSize * offsetBase + - (ax.linewidth ? ax.linewidth - 1 : 0); - - if(axLetter === 'x') { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_210.getFromId(gd, ax.anchor); - - x = ax._offset + ax._length / 2; + // 'epsilon' - rounding increment + var e = Math.pow(10, -tickRound) / 2; - if(ax.side === 'top') { - y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); - } - else { - y = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1.5 : 0.5); - } - y += counterAxis._offset; + // 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; - if(!avoid.side) avoid.side = 'bottom'; + // 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 { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_210.getFromId(gd, ax.anchor); + 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_166.numSeparate(v, ax._separators, separatethousands); + } - y = ax._offset + ax._length / 2; - if(ax.side === 'right') { - x = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1 : 0.5); - } - else { - x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); - } - x += counterAxis._offset; + // add exponent + if(exponent && exponentFormat !== 'hide') { + if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; - transform = {rotate: '-90', offset: 0}; - if(!avoid.side) avoid.side = 'left'; - } + var signedExponent; + if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; + else if(exponentFormat !== 'power') signedExponent = '+' + exponent; + else signedExponent = String(exponent); - _$titles_139.draw(gd, axid + 'title', { - propContainer: ax, - propName: ax._name + '.title', - placeholder: fullLayout._dfltTitle[axLetter], - avoid: avoid, - transform: transform, - attributes: {x: x, y: y, 'text-anchor': 'middle'} - }); + if(exponentFormat === 'e') { + v += 'e' + signedExponent; + } + else if(exponentFormat === 'E') { + v += 'E' + 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]; + } } - function traceHasBarsOrFill(trace, subplot) { - if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_247.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; - return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; - } + // 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; +} - function drawGrid(plotinfo, counteraxis, subplot) { - var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); - var zlcontainer = plotinfo.zerolinelayer; - var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; - var gridpath = ax._gridpath || ((axLetter === 'x' ? - ('M0,' + counteraxis._offset + 'v') : - ('M' + counteraxis._offset + ',0h') - ) + counteraxis._length); - var grid = gridcontainer.selectAll('path.' + gcls) - .data((ax.showgrid === false) ? [] : gridvals, datafn); - grid.enter().append('path').classed(gcls, 1) - .classed('crisp', 1) - .attr('d', gridpath) - .each(function(d) { - if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && - Math.abs(d.x) < ax.dtick / 100) { - _$d3_10.select(this).remove(); - } - }); - grid.attr('transform', transfn) - .call(_$color_46.stroke, ax.gridcolor || '#ddd') - .style('stroke-width', gridWidth + 'px'); - if(typeof gridpath === 'function') grid.attr('d', gridpath); - grid.exit().remove(); +axes.getTickFormat = function(ax) { + var i; - // zero line - if(zlcontainer) { - var hasBarsOrFill = false; - for(var i = 0; i < gd._fullData.length; i++) { - if(traceHasBarsOrFill(gd._fullData[i], subplot)) { - hasBarsOrFill = true; - break; + 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; } } - var rng = _$lib_165.simpleMap(ax.range, ax.r2l), - showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && - (ax.type === 'linear' || ax.type === '-') && gridvals.length && - (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); - var zl = zlcontainer.selectAll('path.' + zcls) - .data(showZl ? [{x: 0, id: axid}] : []); - zl.enter().append('path').classed(zcls, 1).classed('zl', 1) - .classed('crisp', 1) - .attr('d', gridpath) - .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. - zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_210.idSort(da.id, db.id); - }); - }); - zl.attr('transform', transfn) - .call(_$color_46.stroke, ax.zerolinecolor || _$color_46.defaultLine) - .style('stroke-width', zeroLineWidth + 'px'); - zl.exit().remove(); + } else { + return typeof left === 'number' ? 1 : -1; } } - if(independent) { - drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); - if(ax._counteraxis) { - var fictionalPlotinfo = { - gridlayer: ax._gridlayer, - zerolinelayer: ax._zerolinelayer - }; - drawGrid(fictionalPlotinfo, ax._counteraxis); - } - return drawLabels(ax._axislayer, ax._pos); + 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)); } - else if(fullLayout._has('cartesian')) { - subplots = axes.getSubplots(gd, ax); - - // keep track of which subplots (by main conteraxis) we've already - // drawn grids for, so we don't overdraw overlaying subplots - var finishedGrids = {}; - - subplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; - var counterAxis = plotinfo[counterLetter + 'axis']; - - var mainCounterID = counterAxis._mainAxis._id; - if(finishedGrids[mainCounterID]) return; - finishedGrids[mainCounterID] = 1; - - drawGrid(plotinfo, counterAxis, subplot); - }); - var mainSubplot = ax._mainSubplot; - var mainPlotinfo = fullLayout._plots[mainSubplot]; - var tickSubplots = []; + 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); + } - if(ax.ticks) { - var mainSign = ticksign[2]; - var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); - if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { - tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + var tickstop; + if(ax.tickformatstops && ax.tickformatstops.length > 0) { + switch(ax.type) { + case 'date': + case 'linear': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; } - drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - - tickSubplots = Object.keys(ax._linepositions); + case 'log': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; + } + default: } + } + return tickstop ? tickstop.value : ax.tickformat; +}; - tickSubplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; +// 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 +axes.getSubplots = function(gd, ax) { + var subplotObj = gd._fullLayout._subplots; + var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); - var container = plotinfo[axLetter + 'axislayer']; + var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; - // [bottom or left, top or right] - // free and main are handled above - var linepositions = ax._linepositions[subplot] || []; + out.sort(function(a, b) { + var aParts = a.substr(1).split('y'); + var bParts = b.substr(1).split('y'); - function tickPathSide(sidei) { - var tsign = ticksign[sidei]; - return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); - } + if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; + return +aParts[0] - +bParts[0]; + }); - drawTicks(container, tickPathSide(0) + tickPathSide(1)); - }); + return out; +}; - var mainContainer = mainPlotinfo[axLetter + 'axislayer']; +// find all subplots with axis 'ax' +axes.findSubplotsWithAxis = function(subplots, ax) { + var axMatch = new RegExp( + (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') + ); + var subplotsWithAxis = []; - return drawLabels(mainContainer, ax._mainLinePosition); + for(var i = 0; i < subplots.length; i++) { + var sp = subplots[i]; + if(axMatch.test(sp)) subplotsWithAxis.push(sp); } + + return subplotsWithAxis; }; -// swap all the presentation attributes of the axes showing these traces -axes.swap = function(gd, traces) { - var axGroups = makeAxisGroups(gd, traces); +// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings +axes.makeClipPaths = function(gd) { + var fullLayout = gd._fullLayout; + 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(var i = 0; i < axGroups.length; i++) { - swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + 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]}); + } } -}; -function makeAxisGroups(gd, traces) { - var groups = [], - i, - 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; }); - for(i = 0; i < traces.length; i++) { - var groupsi = [], - xi = gd._fullData[traces[i]].xaxis, - yi = gd._fullData[traces[i]].yaxis; - if(!xi || !yi) continue; // not a 2D cartesian trace? + axClips.enter().append('clipPath') + .classed('axesclip', true) + .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; }) + .append('rect'); - for(j = 0; j < groups.length; j++) { - if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { - groupsi.push(j); - } - } + axClips.exit().remove(); - if(!groupsi.length) { - groups.push({x: [xi], y: [yi]}); - continue; - } + axClips.each(function(d) { + _$d3_10.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 + }); + }); +}; - var group0 = groups[groupsi[0]], - groupj; +// doTicks: draw ticks, grids, and tick labels +// axid: 'x', 'y', 'x2' etc, +// blank to do all, +// 'redraw' to force full redraw, and reset: +// ax._r (stored range for use by zoom/pan) +// ax._rl (stored linearized range for use by zoom/pan) +// or can pass in an axis object directly +axes.doTicks = function(gd, axid, skipTitle) { + var fullLayout = gd._fullLayout; + var ax; + var independent = false; - 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]); + // allow passing an independent axis object instead of id + if(typeof axid === 'object') { + ax = axid; + axid = ax._id; + independent = true; } + else { + ax = axes.getFromId(gd, axid); - return groups; -} + if(axid === 'redraw') { + fullLayout._paper.selectAll('g.subplot').each(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -function mergeAxisGroups(intoSet, fromSet) { - for(var i = 0; i < fromSet.length; i++) { - if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); + }); + } + + if(!axid || axid === 'redraw') { + return _$lib_166.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return function() { + if(!ax._id) return; + var axDone = axes.doTicks(gd, ax._id); + ax._r = ax.range.slice(); + ax._rl = _$lib_166.simpleMap(ax._r, ax.r2l); + return axDone; + }; + })); + } } -} -function swapAxisGroup(gd, xIds, yIds) { - var i, - j, - xFullAxes = [], - yFullAxes = [], - layout = gd.layout; + // set scaling to pixels + ax.setScale(); - 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 axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_71.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_71.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_71.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; - var allAxKeys = Object.keys(xFullAxes[0]), - noSwapAttrs = [ - 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' - ], - numericTypes = ['linear', 'log']; + if(ax._counterangle && ax.ticks === 'outside') { + var caRad = ax._counterangle * Math.PI / 180; + labelStandoff = ax.ticklen * Math.cos(caRad) + 1; + labelShift = ax.ticklen * Math.sin(caRad); + } - for(i = 0; i < allAxKeys.length; i++) { - var keyi = allAxKeys[i], - xVal = xFullAxes[0][keyi], - yVal = yFullAxes[0][keyi], - allEqual = true, - coerceLinearX = false, - 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; + if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { + labelStandoff += 0.2 * ax.tickfont.size; + } + + // positioning arguments for x vs y axes + if(axLetter === 'x') { + sides = ['bottom', 'top']; + transfn = ax._transfn || function(d) { + return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); } - 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 return 'M0,' + shift + 'v' + len; + }; + } + else if(axLetter === 'y') { + sides = ['left', 'right']; + transfn = ax._transfn || function(d) { + return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); } - 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); - } + else return 'M' + shift + ',0h' + len; + }; + } + else if(axid === 'angular') { + sides = ['left', 'right']; + transfn = ax._transfn; + tickpathfn = function(shift, len) { + return 'M' + shift + ',0h' + len; + }; + } + else { + _$lib_166.warn('Unrecognized doTicks axis:', axid); + return; } - // 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_165.swapAttrs(layout.annotations[i], ['?']); - } + var axside = ax.side || sides[0]; + // which direction do the side[0], side[1], and free ticks go? + // then we flip if outside XOR y axis + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + if((ax.ticks !== 'inside') === (axLetter === 'x')) { + ticksign = ticksign.map(function(v) { return -v; }); } -} -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_165.nestedProperty, - xVal = np(layout[xFullAxes[0]._name], key).get(), - yVal = np(layout[yFullAxes[0]._name], key).get(), - i; - if(key === 'title') { - // special handling of placeholder titles - if(xVal === dfltTitle.x) { - xVal = dfltTitle.y; - } - if(yVal === dfltTitle.y) { - yVal = dfltTitle.x; - } - } + if(!ax.visible) return; - for(i = 0; i < xFullAxes.length; i++) { - np(layout, xFullAxes[i]._name + '.' + key).set(yVal); + if(ax._tickFilter) { + vals = vals.filter(ax._tickFilter); } - for(i = 0; i < yFullAxes.length; i++) { - np(layout, yFullAxes[i]._name + '.' + key).set(xVal); + + // remove zero lines, grid lines, and inside ticks if they're within + // 1 pixel of the end + // The key case here is removing zero lines when the axis bound is zero. + function clipEnds(d) { + var p = ax.l2p(d.x); + return (p > 1 && p < ax._length - 1); } -} + var valsClipped = vals.filter(clipEnds); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // don't clip angular values + if(ax._id === 'angular') { + valsClipped = vals; + } -'use strict'; + function drawTicks(container, tickpath) { + var ticks = container.selectAll('path.' + tcls) + .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); -/* removed: var _$d3_10 = require('d3'); */; + if(tickpath && ax.ticks) { + ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) + .classed('crisp', 1) + .call(_$color_46.stroke, ax.tickcolor) + .style('stroke-width', tickWidth + 'px') + .attr('d', tickpath); + ticks.attr('transform', transfn); + ticks.exit().remove(); + } + else ticks.remove(); + } -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$axes_207 = require('./axes'); */; -var axisRegex = _$constants_212.attrRegex; + function drawLabels(container, position) { + // tick labels - for now just the main labels. + // TODO: mirror labels, esp for subplots + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); -var _$transitionAxes_230 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; + if(!_$fastIsnumeric_13(position)) { + tickLabels.remove(); + drawAxTitle(); + return; + } + if(!ax.showticklabels) { + tickLabels.remove(); + drawAxTitle(); + calcBoundingBox(); + return; + } - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + var labelx, labely, labelanchor, labelpos0, flipit; + if(axLetter === 'x') { + flipit = (axside === 'bottom') ? 1 : -1; + labelx = function(d) { return d.dx + labelShift * flipit; }; + labelpos0 = position + (labelStandoff + pad) * flipit; + labely = function(d) { + return d.dy + labelpos0 + d.fontSize * + ((axside === 'bottom') ? 1 : -0.2); + }; + labelanchor = function(angle) { + if(!_$fastIsnumeric_13(angle) || angle === 0 || angle === 180) { + return 'middle'; + } + return (angle * flipit < 0) ? 'end' : 'start'; + }; + } + else if(axLetter === 'y') { + flipit = (axside === 'right') ? 1 : -1; + labely = function(d) { + return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; + }; + labelx = function(d) { + return d.dx + position + (labelStandoff + pad + + ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; + }; + labelanchor = function(angle) { + if(_$fastIsnumeric_13(angle) && Math.abs(angle) === 90) { + return 'middle'; + } + return axside === 'right' ? 'start' : 'end'; + }; + } + else if(axid === 'angular') { + ax._labelShift = labelShift; + ax._labelStandoff = labelStandoff; + ax._pad = pad; - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + labelx = ax._labelx; + labely = ax._labely; + labelanchor = ax._labelanchor; + } - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); + var maxFontSize = 0, + autoangle = 0, + labelsReady = []; + tickLabels.enter().append('g').classed(tcls, 1) + .append('text') + // only so tex has predictable alignment that we can + // alter later + .attr('text-anchor', 'middle') + .each(function(d) { + var thisLabel = _$d3_10.select(this), + newPromise = gd._promises.length; + thisLabel + .call(_$svg_text_utils_187.positionText, labelx(d), labely(d)) + .call(_$drawing_71.font, d.font, d.fontSize, d.fontColor) + .text(d.text) + .call(_$svg_text_utils_187.convertToTspans, gd); + newPromise = gd._promises[newPromise]; + if(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, ax.tickangle); + })); } - } - if(!update.to) continue; + else { + // sync label: just position it now. + positionLabels(thisLabel, ax.tickangle); + } + }); + tickLabels.exit().remove(); - update.axisName = axisName; - update.length = axis._length; + tickLabels.each(function(d) { + maxFontSize = Math.max(maxFontSize, d.fontSize); + }); - axes.push(axisLetter); + if(axid === 'angular') { + tickLabels.each(function(d) { + _$d3_10.select(this).select('text') + .call(_$svg_text_utils_187.positionText, labelx(d), labely(d)); + }); + } - updates[axisLetter] = update; + // How much to shift a multi-line label to center it vertically. + function getAnchorHeight(lineCount, lineHeight, angle) { + var h = (lineCount - 1) * lineHeight; + if(axLetter === 'x') { + if(angle < -60 || 60 < angle) { + return -0.5 * h; + } else if(axside === 'top') { + return -h; + } + } else { + angle *= axside === 'left' ? 1 : -1; + if(angle < -30) { + return -h; + } else if(angle < 30) { + return -0.5 * h; + } } + return 0; } - return updates; - } + function positionLabels(s, angle) { + s.each(function(d) { + var anchor = labelanchor(angle, d); + var thisLabel = _$d3_10.select(this), + mathjaxGroup = thisLabel.select('.text-math-group'), + transform = transfn.call(thisLabel.node(), d) + + ((_$fastIsnumeric_13(angle) && +angle !== 0) ? + (' rotate(' + angle + ',' + labelx(d) + ',' + + (labely(d) - d.fontSize / 2) + ')') : + ''); + var anchorHeight = getAnchorHeight( + _$svg_text_utils_187.lineCount(thisLabel), + __LINE_SPACING_208 * d.fontSize, + _$fastIsnumeric_13(angle) ? +angle : 0); + if(anchorHeight) { + transform += ' translate(0, ' + anchorHeight + ')'; + } + if(mathjaxGroup.empty()) { + thisLabel.select('text').attr({ + transform: transform, + 'text-anchor': anchor + }); + } + else { + var mjShift = + _$drawing_71.bBox(mathjaxGroup.node()).width * + {end: -0.5, start: 0.5}[anchor]; + mathjaxGroup.attr('transform', transform + + (mjShift ? 'translate(' + mjShift + ',0)' : '')); + } + }); + } - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; + // 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, ax._lastangle || ax.tickangle); - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; + function allLabelsReady() { + return labelsReady.length && Promise.all(labelsReady); + } - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + function fixLabelOverlaps() { + positionLabels(tickLabels, ax.tickangle); - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; + // check for auto-angling if x labels overlap + // don't auto-angle at all for log axes with + // base and digit format + if(axLetter === 'x' && !_$fastIsnumeric_13(ax.tickangle) && + (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { + var lbbArray = []; + tickLabels.each(function(d) { + var s = _$d3_10.select(this), + thisLabel = s.select('.text-math-group'), + x = ax.l2p(d.x); + if(thisLabel.empty()) thisLabel = s.select('text'); - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + var bb = _$drawing_71.bBox(thisLabel.node()); - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; + 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 + }); + }); + for(i = 0; i < lbbArray.length - 1; i++) { + if(_$lib_166.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + // any overlap at all - set 30 degrees + autoangle = 30; + break; + } + } + if(autoangle) { + var tickspacing = Math.abs( + (vals[vals.length - 1].x - vals[0].x) * ax._m + ) / (vals.length - 1); + if(tickspacing < maxFontSize * 2.5) { + autoangle = 90; + } + positionLabels(tickLabels, autoangle); + } + ax._lastangle = autoangle; } - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; - - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); - } + // update the axis title + // (so it can move out of the way if needed) + // TODO: separate out scoot so we don't need to do + // a full redraw of the title (mostly relevant for MathJax) + drawAxTitle(); + return axid + ' done'; } - return affectedSubplots; - } + function calcBoundingBox() { + if(ax.showticklabels) { + var gdBB = gd.getBoundingClientRect(); + var bBox = container.node().getBoundingClientRect(); - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); + /* + * the way we're going to use this, the positioning that matters + * is relative to the origin of gd. This is important particularly + * if gd is scrollable, and may have been scrolled between the time + * we calculate this and the time we use it + */ - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); + ax._boundingBox = { + width: bBox.width, + height: bBox.height, + left: bBox.left - gdBB.left, + right: bBox.right - gdBB.left, + top: bBox.top - gdBB.top, + bottom: bBox.bottom - gdBB.top + }; + } else { + var gs = fullLayout._size; + var pos; - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } + // set dummy bbox for ticklabel-less axes - redrawObjs(fullLayout.annotations || [], _$registry_247.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_247.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_247.getComponentMethod('images', 'draw'), true); - } + if(axLetter === 'x') { + pos = ax.anchor === 'free' ? + gs.t + gs.h * (1 - ax.position) : + gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; - } + ax._boundingBox = { + top: pos, + bottom: pos, + left: ax._offset, + right: ax._offset + ax._length, + width: ax._length, + height: 0 + }; + } else { + pos = ax.anchor === 'free' ? + gs.l + gs.w * ax.position : + gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; + ax._boundingBox = { + left: pos, + right: pos, + bottom: ax._offset + ax._length, + top: ax._offset, + height: ax._length, + width: 0 + }; + } + } - activeAxIds = [xa._id, ya._id]; + /* + * for spikelines: what's the full domain of positions in the + * opposite direction that are associated with this axis? + * This means any axes that we make a subplot with, plus the + * position of the axis itself if it's free. + */ + if(subplots) { + var fullRange = ax._counterSpan = [Infinity, -Infinity]; - for(i = 0; i < activeAxIds.length; i++) { - _$axes_207.doTicks(gd, activeAxIds[i], true); - } + for(i = 0; i < subplots.length; i++) { + var subplot = fullLayout._plots[subplots[i]]; + var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; + extendRange(fullRange, [ + counterAxis._offset, + counterAxis._offset + counterAxis._length + ]); + } - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); + if(ax.anchor === 'free') { + extendRange(fullRange, (axLetter === 'x') ? + [ax._boundingBox.bottom, ax._boundingBox.top] : + [ax._boundingBox.right, ax._boundingBox.left]); } + } - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + function extendRange(range, newRange) { + range[0] = Math.min(range[0], newRange[0]); + range[1] = Math.max(range[1], newRange[1]); } } - redrawObjs(fullLayout.annotations || [], _$registry_247.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_247.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_247.getComponentMethod('images', 'draw'), true); - } + function doAutoMargins() { + if(!ax.automargin) { return; } + if(axLetter !== 'x' && axLetter !== 'y') { return; } - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + var s = ax.side[0]; + var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_71.setTranslate, 0, 0) - .call(_$drawing_71.setScale, 1, 1); + if(axLetter === 'x') { + push.y = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 't' ? 1 : 0]); + push[s] += ax._boundingBox.height; + } + else { + push.x = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 'r' ? 1 : 0]); + push[s] += ax._boundingBox.width; + } - subplot.plot - .call(_$drawing_71.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_71.setScale, 1, 1); + if(ax.title !== fullLayout._dfltTitle[axLetter]) { + push[s] += ax.titlefont.size; + } - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + var pushKey = ax._name + '.automargin'; + var prevPush = fullLayout._pushmargin[pushKey]; + if(!prevPush || prevPush[s].size < push[s]) { + _$plots_240.autoMargin(gd, pushKey, push); + } + } - // 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_71.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_71.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_71.hideOutsideRangePoints, subplot); + var done = _$lib_166.syncOrAsync([ + allLabelsReady, + fixLabelOverlaps, + calcBoundingBox, + doAutoMargins + ]); + if(done && done.then) gd._promises.push(done); + return done; } - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; + function drawAxTitle() { + if(skipTitle) return; - var viewBox = []; + // now this only applies to regular cartesian axes; colorbars and + // others ALWAYS call doTicks with skipTitle=true so they can + // configure their own titles. - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + // rangeslider takes over a bottom title so drop it here + if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + var avoid = { + selection: tickLabels, + side: ax.side + }; + var axLetter = axid.charAt(0); + var gs = gd._fullLayout._size; + var offsetBase = 1.5; + var fontSize = ax.titlefont.size; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; + var transform, counterAxis, x, y; + + if(tickLabels.size()) { + var translation = _$drawing_71.getTranslate(tickLabels.node().parentNode); + avoid.offsetLeft = translation.x; + avoid.offsetTop = translation.y; } - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + var titleStandoff = 10 + fontSize * offsetBase + + (ax.linewidth ? ax.linewidth - 1 : 0); - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + if(axLetter === 'x') { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : + _$axis_ids_211.getFromId(gd, ax.anchor); - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; - } - - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + x = ax._offset + ax._length / 2; - var editX = !!xUpdate; - var editY = !!yUpdate; + if(ax.side === 'top') { + y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); + } + else { + y = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1.5 : 0.5); + } + y += counterAxis._offset; - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + if(!avoid.side) avoid.side = 'bottom'; + } + else { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : + _$axis_ids_211.getFromId(gd, ax.anchor); - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + y = ax._offset + ax._length / 2; + if(ax.side === 'right') { + x = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1 : 0.5); + } + else { + x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); + } + x += counterAxis._offset; - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + transform = {rotate: '-90', offset: 0}; + if(!avoid.side) avoid.side = 'left'; + } - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + _$titles_139.draw(gd, axid + 'title', { + propContainer: ax, + propName: ax._name + '.title', + placeholder: fullLayout._dfltTitle[axLetter], + avoid: avoid, + transform: transform, + attributes: {x: x, y: y, 'text-anchor': 'middle'} + }); + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_71.setTranslate, clipDx, clipDy) - .call(_$drawing_71.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + function traceHasBarsOrFill(trace, subplot) { + if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; + if(_$registry_248.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; + } - subplot.plot - .call(_$drawing_71.setTranslate, plotDx, plotDy) - .call(_$drawing_71.setScale, xScaleFactor, yScaleFactor) + function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_71.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); + var zlcontainer = plotinfo.zerolinelayer; + var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; + var gridpath = ax._gridpath || ((axLetter === 'x' ? + ('M0,' + counteraxis._offset + 'v') : + ('M' + counteraxis._offset + ',0h') + ) + counteraxis._length); + var grid = gridcontainer.selectAll('path.' + gcls) + .data((ax.showgrid === false) ? [] : gridvals, datafn); + grid.enter().append('path').classed(gcls, 1) + .classed('crisp', 1) + .attr('d', gridpath) + .each(function(d) { + if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && + Math.abs(d.x) < ax.dtick / 100) { + _$d3_10.select(this).remove(); + } + }); + grid.attr('transform', transfn) + .call(_$color_46.stroke, ax.gridcolor || '#ddd') + .style('stroke-width', gridWidth + 'px'); + if(typeof gridpath === 'function') grid.attr('d', gridpath); + grid.exit().remove(); - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_71.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + // zero line + if(zlcontainer) { + var hasBarsOrFill = false; + for(var i = 0; i < gd._fullData.length; i++) { + if(traceHasBarsOrFill(gd._fullData[i], subplot)) { + hasBarsOrFill = true; + break; + } + } + var rng = _$lib_166.simpleMap(ax.range, ax.r2l), + showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && + (ax.type === 'linear' || ax.type === '-') && gridvals.length && + (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); + var zl = zlcontainer.selectAll('path.' + zcls) + .data(showZl ? [{x: 0, id: axid}] : []); + zl.enter().append('path').classed(zcls, 1).classed('zl', 1) + .classed('crisp', 1) + .attr('d', gridpath) + .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. + zlcontainer.selectAll('path').sort(function(da, db) { + return _$axis_ids_211.idSort(da.id, db.id); + }); + }); + zl.attr('transform', transfn) + .call(_$color_46.stroke, ax.zerolinecolor || _$color_46.defaultLine) + .style('stroke-width', zeroLineWidth + 'px'); + zl.exit().remove(); + } } - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); + if(independent) { + drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); + if(ax._counteraxis) { + var fictionalPlotinfo = { + gridlayer: ax._gridlayer, + zerolinelayer: ax._zerolinelayer + }; + drawGrid(fictionalPlotinfo, ax._counteraxis); + } + return drawLabels(ax._axislayer, ax._pos); } + else if(fullLayout._has('cartesian')) { + subplots = axes.getSubplots(gd, ax); - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; + // keep track of which subplots (by main conteraxis) we've already + // drawn grids for, so we don't overdraw overlaying subplots + var finishedGrids = {}; - axi.range = to.slice(); - } + subplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var counterAxis = plotinfo[counterLetter + 'axis']; - // Signal that this transition has completed: - onComplete && onComplete(); + var mainCounterID = counterAxis._mainAxis._id; + if(finishedGrids[mainCounterID]) return; + finishedGrids[mainCounterID] = 1; - return _$registry_247.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } + drawGrid(plotinfo, counterAxis, subplot); }); - } - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; + var mainSubplot = ax._mainSubplot; + var mainPlotinfo = fullLayout._plots[mainSubplot]; + var tickSubplots = []; - axi.range = axi._r.slice(); + if(ax.ticks) { + var mainSign = ticksign[2]; + var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); + if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { + tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + } + drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); + + tickSubplots = Object.keys(ax._linepositions || {}); } - return _$registry_247.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); - } + tickSubplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; - var t1, t2, raf; - var easeFn = _$d3_10.ease(transitionOpts.easing); + var container = plotinfo[axLetter + 'axislayer']; - gd._transitionData._interruptCallbacks.push(function() { - window.cancelAnimationFrame(raf); - raf = null; - return transitionInterrupt(); - }); + // [bottom or left, top or right] + // free and main are handled above + var linepositions = ax._linepositions[subplot] || []; - function doFrame() { - t2 = Date.now(); + function tickPathSide(sidei) { + var tsign = ticksign[sidei]; + return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); + } - var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); - var progress = easeFn(tInterp); + drawTicks(container, tickPathSide(0) + tickPathSide(1)); + }); - for(var i = 0; i < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } + var mainContainer = mainPlotinfo[axLetter + 'axislayer']; - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); - } + return drawLabels(mainContainer, ax._mainLinePosition); } +}; - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); +// swap all the presentation attributes of the axes showing these traces +axes.swap = function(gd, traces) { + var axGroups = makeAxisGroups(gd, traces); - return Promise.resolve(); + for(var i = 0; i < axGroups.length; i++) { + swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + } }; -var _$get_data_236 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +function makeAxisGroups(gd, traces) { + var groups = [], + i, + j; -/* removed: var _$registry_247 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_212.SUBPLOT_PATTERN; + for(i = 0; i < traces.length; i++) { + var groupsi = [], + xi = gd._fullData[traces[i]].xaxis, + yi = gd._fullData[traces[i]].yaxis; + if(!xi || !yi) continue; // not a 2D cartesian trace? -/** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces - */ -_$get_data_236.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_247.subplotsRegistry[type]; - if(!basePlotModule) return []; + for(j = 0; j < groups.length; j++) { + if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { + groupsi.push(j); + } + } - var attr = basePlotModule.attr; - var subplotCalcData = []; + if(!groupsi.length) { + groups.push({x: [xi], y: [yi]}); + continue; + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; + var group0 = groups[groupsi[0]], + groupj; - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + 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 subplotCalcData; -}; - -_$get_data_236.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_247.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + return groups; +} - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); +function mergeAxisGroups(intoSet, fromSet) { + for(var i = 0; i < fromSet.length; i++) { + if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); } +} - return moduleCalcData; -}; +function swapAxisGroup(gd, xIds, yIds) { + var i, + j, + xFullAxes = [], + yFullAxes = [], + layout = gd.layout; -/** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. - * - * @return {array} list of trace objects. - * - */ -_$get_data_236.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_247.subplotsRegistry[type]) return []; + 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 attr = _$registry_247.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; + var allAxKeys = Object.keys(xFullAxes[0]), + noSwapAttrs = [ + 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' + ], + numericTypes = ['linear', 'log']; - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; + for(i = 0; i < allAxKeys.length; i++) { + var keyi = allAxKeys[i], + xVal = xFullAxes[0][keyi], + yVal = yFullAxes[0][keyi], + allEqual = true, + coerceLinearX = false, + 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); + } } - for(var i = 0; i < data.length; i++) { - trace = data[i]; + // 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_166.swapAttrs(layout.annotations[i], ['?']); + } + } +} - if(type === 'gl2d' && _$registry_247.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); - } +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_166.nestedProperty, + xVal = np(layout[xFullAxes[0]._name], key).get(), + yVal = np(layout[yFullAxes[0]._name], key).get(), + i; + if(key === 'title') { + // special handling of placeholder titles + if(xVal === dfltTitle.x) { + xVal = dfltTitle.y; } - else { - if(trace[attr] === subplotId) subplotData.push(trace); + if(yVal === dfltTitle.y) { + yVal = dfltTitle.x; } } - return subplotData; -}; + 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); + } +} -var _$cartesian_218 = {}; +var _$hover_86 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29759,1087 +29982,1453 @@ var _$cartesian_218 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$plots_240 = require('../plots'); */; -var getModuleCalcData = _$get_data_236.getModuleCalcData; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_28 = require('tinycolor2'); */; -/* removed: var _$axis_ids_210 = require('./axis_ids'); */; -/* removed: var _$constants_212 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_150 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$Events_159 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_177 = require('../../lib/override_cursor'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -_$cartesian_218.name = 'cartesian'; +/* removed: var _$helpers_85 = require('./helpers'); */; +/* removed: var _$constants_83 = require('./constants'); */; -_$cartesian_218.attr = ['xaxis', 'yaxis']; +// hover labels for multiple horizontal bars get tilted by some angle, +// then need to be offset differently if they overlap +var YANGLE = _$constants_83.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; -_$cartesian_218.idRoot = ['x', 'y']; +// expansion of projected height +var YFACTOR = 1 / Math.sin(YA_RADIANS); -_$cartesian_218.idRegex = _$constants_212.idRegex; +// to make the appropriate post-rotation x offset, +// you need both x and y offsets +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); -_$cartesian_218.attrRegex = _$constants_212.attrRegex; +// size and display constants for hover text +var HOVERARROWSIZE = _$constants_83.HOVERARROWSIZE; +var HOVERTEXTPAD = _$constants_83.HOVERTEXTPAD; -_$cartesian_218.attributes = _$attributes_205; +// fx.hover: highlight data on hover +// evt can be a mousemove event, or an object with data about what points +// to hover on +// {xpx,ypx[,hovermode]} - pixel locations from top left +// (with optional overriding hovermode) +// {xval,yval[,hovermode]} - data values +// [{curveNumber,(pointNumber|xval and/or yval)}] - +// array of specific points to highlight +// pointNumber is a single integer if gd.data[curveNumber] is 1D, +// or a two-element array if it's 2D +// xval and yval are data values, +// 1D data may specify either or both, +// 2D data must specify both +// subplot is an id string (default "xy") +// makes use of gl.hovermode, which can be: +// x (find the points with the closest x values, ie a column), +// closest (find the single closest point) +// internally there are two more that occasionally get used: +// y (pick out a row - only used for multiple horizontal bar charts) +// array (used when the user specifies an explicit +// array of points to hover on) +// +// We wrap the hovers in a timer, to limit their frequency. +// The actual rendering is done by private function _hover. +_$hover_86.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = _$lib_166.getGraphDiv(gd); -_$cartesian_218.layoutAttributes = _$layout_attributes_219; + _$lib_166.throttle( + gd._fullLayout._uid + _$constants_83.HOVERID, + _$constants_83.HOVERMINTIME, + function() { _hover(gd, evt, subplot, noHoverEvent); } + ); +}; -_$cartesian_218.supplyLayoutDefaults = _$supplyLayoutDefaults_220; +/* + * Draw a single hover item in a pre-existing svg container somewhere + * hoverItem should have keys: + * - x and y (or x0, x1, y0, and y1): + * the pixel position to mark, relative to opts.container + * - xLabel, yLabel, zLabel, text, and name: + * info to go in the label + * - color: + * the background color for the label. + * - idealAlign (optional): + * 'left' or 'right' for which side of the x/y box to try to put this on first + * - borderColor (optional): + * color for the border, defaults to strongest contrast with color + * - fontFamily (optional): + * string, the font for this label, defaults to constants.HOVERFONT + * - fontSize (optional): + * the label font size, defaults to constants.HOVERFONTSIZE + * - fontColor (optional): + * defaults to borderColor + * opts should have keys: + * - bgColor: + * the background color this is against, used if the trace is + * non-opaque, and for the name, which goes outside the box + * - container: + * a or element to add the hover label to + * - outerContainer: + * normally a parent of `container`, sets the bounding box to use to + * constrain the hover label and determine whether to show it on the left or right + */ +_$hover_86.loneHover = function loneHover(hoverItem, opts) { + var pointData = { + color: hoverItem.color || _$color_46.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, -_$cartesian_218.transitionAxes = _$transitionAxes_230; + // optional extra bits of styling + borderColor: hoverItem.borderColor, + fontFamily: hoverItem.fontFamily, + fontSize: hoverItem.fontSize, + fontColor: hoverItem.fontColor, -_$cartesian_218.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; - - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } - - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_210.id2name(xi)] || {}).anchor; - if(!_$constants_212.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + // filler to make createHoverText happy + trace: { + index: 0, + hoverinfo: '' + }, + xa: {_offset: 0}, + ya: {_offset: 0}, + index: 0 + }; - if(!allY[yi]) { - allY[yi] = 1; - _$lib_165.pushUnique(yList, yi); - } - } - } + var container3 = _$d3_10.select(opts.container), + outerContainer3 = opts.outerContainer ? + _$d3_10.select(opts.outerContainer) : container3; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_210.id2name(yi)] || {}).anchor; - if(!_$constants_212.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var fullOpts = { + hovermode: 'closest', + rotateLabels: false, + bgColor: opts.bgColor || _$color_46.background, + container: container3, + outerContainer: outerContainer3 + }; - if(!allX[xi]) { - allX[xi] = 1; - _$lib_165.pushUnique(xList, xi); - } - } - } + var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); + alignHoverText(hoverLabel, fullOpts.rotateLabels); - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_212.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_210.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_210.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } + return hoverLabel.node(); }; -_$cartesian_218.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; +// The actual implementation is here: +function _hover(gd, evt, subplot, noHoverEvent) { + if(!subplot) subplot = 'xy'; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + // if the user passed in an array of subplots, + // use those instead of finding overlayed plots + var subplots = Array.isArray(subplot) ? subplot : [subplot]; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var fullLayout = gd._fullLayout; + var plots = fullLayout._plots || []; + var plotinfo = plots[subplot]; + var hasCartesian = fullLayout._has('cartesian'); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } + // list of all overlaid subplots to look at + if(plotinfo) { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; }); - } - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + subplots = subplots.concat(overlayedSubplots); + } - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; + var len = subplots.length; + var xaArray = new Array(len); + var yaArray = new Array(len); + var supportsCompare = false; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + for(var i = 0; i < len; i++) { + var spId = subplots[i]; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + // 'cartesian' case + var plotObj = plots[spId]; + if(plotObj) { + supportsCompare = true; - cdSubplot.push(cd); - } + // TODO make sure that fullLayout_plots axis refs + // get updated properly so that we don't have + // to use Axes.getFromId in general. - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; - } + xaArray[i] = _$axes_208.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_208.getFromId(gd, plotObj.yaxis._id); + continue; } - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + // other subplot types + var _subplot = fullLayout[spId]._subplot; + xaArray[i] = _subplot.xaxis; + yaArray[i] = _subplot.yaxis; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; + var hovermode = evt.hovermode || fullLayout.hovermode; - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + if(hovermode && !supportsCompare) hovermode = 'closest'; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || + gd.querySelector('.zoombox') || gd._dragging) { + return _$dragelement_68.unhoverRaw(gd, evt); } -} -_$cartesian_218.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; + var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + // hoverData: the set of candidate points we've found to highlight + var hoverData = [], + // searchData: the data to search in. Mostly this is just a copy of + // gd.calcdata, filtered to the subplot and overlays we're on + // but if a point array is supplied it will be a mapping + // of indicated curves + searchData = [], - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; - } + // [x|y]valArray: the axis values of the hover event + // mapped onto each of the currently selected overlaid subplots + xvalArray, + yvalArray, - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + // used in loops + itemnum, + curvenum, + cd, + trace, + subplotId, + subploti, + mode, + xval, + yval, + pointData, + closedataPreviousLength, - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // spikePoints: the set of candidate points we've found to draw spikes to + spikePoints = { + hLinePoint: null, + vLinePoint: null + }; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + // Figure out what we're hovering on: + // mouse location or user-supplied data - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + if(Array.isArray(evt)) { + // user specified an array of points to highlight + hovermode = 'array'; + for(itemnum = 0; itemnum < evt.length; itemnum++) { + cd = gd.calcdata[evt[itemnum].curveNumber||0]; + if(cd[0].trace.hoverinfo !== 'skip') { + searchData.push(cd); } } - - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); } + else { + for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { + cd = gd.calcdata[curvenum]; + trace = cd[0].trace; + if(trace.hoverinfo !== 'skip' && _$helpers_85.isTraceInSubplots(trace, subplots)) { + searchData.push(cd); + } + } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // [x|y]px: the pixels (from top left) of the mouse location + // on the currently selected plot area + // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation + var hasUserCalledHover = !evt.target, + xpx, ypx; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(hasUserCalledHover) { + if('xpx' in evt) xpx = evt.xpx; + else xpx = xaArray[0]._length / 2; + evt.pointerX = xpx + xaArray[0]._offset; - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } + if('ypx' in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + evt.pointerY = ypx + yaArray[0]._offset; } - } + else { + // fire the beforehover event and quit if it returns false + // note that we're only calling this on real mouse events, so + // manual calls to fx.hover will always run. + if(_$Events_159.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + var dbb = evt.target.getBoundingClientRect(); - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // in case hover was called from mouseout into hovertext, + // it's possible you're not actually over the plot anymore + if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { + return _$dragelement_68.unhoverRaw(gd, evt); } + evt.pointerX = evt.offsetX; + evt.pointerY = evt.offsetY; } - } - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + if('xval' in evt) xvalArray = _$helpers_85.flat(subplots, evt.xval); + else xvalArray = _$helpers_85.p2c(xaArray, xpx); - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } + if('yval' in evt) yvalArray = _$helpers_85.flat(subplots, evt.yval); + else yvalArray = _$helpers_85.p2c(yaArray, ypx); + + if(!_$fastIsnumeric_13(xvalArray[0]) || !_$fastIsnumeric_13(yvalArray[0])) { + _$lib_166.warn('Fx.hover failed', evt, gd); + return _$dragelement_68.unhoverRaw(gd, evt); } } -}; -_$cartesian_218.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); + // the pixel distance to beat as a matching point + // in 'x' or 'y' mode this resets for each trace + var distance = Infinity; - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_165.identity); + // find the closest point in each trace + // this is minimum dx and/or dy, depending on mode + // and the pixel position for the label (labelXpx, labelYpx) + for(curvenum = 0; curvenum < searchData.length; curvenum++) { + cd = searchData[curvenum]; - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + // filter out invisible or broken data + if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; - subplotLayers.order(); + trace = cd[0].trace; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + // Explicitly bail out for these two. I don't know how to otherwise prevent + // the rest of this function from running and failing + if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_85.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } - // keep ref to plot group - plotinfo.plotgroup = _$d3_10.select(this); + // within one trace mode can sometimes be overridden + mode = hovermode; - // initialize list of overlay subplots - plotinfo.overlays = []; + // container for new point, also used to pass info into module.hoverPoints + pointData = { + // trace properties + cd: cd, + trace: trace, + xa: xaArray[subploti], + ya: yaArray[subploti], - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); - } + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + // point properties - override all of these + index: false, // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance -_$cartesian_218.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_240.style(gd); -}; + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: undefined, + ySpike: undefined, - var subplotData = [], - overlays = []; + // where and how to display the hover label + color: _$color_46.defaultLine, // trace color + name: trace.name, + x0: undefined, + x1: undefined, + y0: undefined, + y1: undefined, + xLabelVal: undefined, + yLabelVal: undefined, + zLabelVal: undefined, + text: undefined + }; - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + // add ref to subplot object (non-cartesian case) + if(fullLayout[subplotId]) { + pointData.subplot = fullLayout[subplotId]._subplot; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + closedataPreviousLength = hoverData.length; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); + // for a highlighting array, figure out what + // we're searching for with this element + if(mode === 'array') { + var selection = evt[curvenum]; + if('pointNumber' in selection) { + pointData.index = selection.pointNumber; + mode = 'closest'; + } + else { + mode = ''; + if('xval' in selection) { + xval = selection.xval; + mode = 'x'; + } + if('yval' in selection) { + yval = selection.yval; + mode = mode ? 'closest' : 'y'; + } + } } else { - subplotData.push(subplot); + xval = xvalArray[subploti]; + yval = yvalArray[subploti]; } - } - - // main subplots before overlays - subplotData = subplotData.concat(overlays); - return subplotData; -} - -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_212.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_212.layerValue2layerClass[plotinfo.yaxis.layer]; - - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); - - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); - - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); - - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); - - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); - - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + // Now if there is range to look in, find the points to hover. + if(hoverdistance !== 0) { + if(trace._module && trace._module.hoverPoints) { + var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); + if(newPoints) { + var newPoint; + for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { + newPoint = newPoints[newPointNum]; + if(_$fastIsnumeric_13(newPoint.x0) && _$fastIsnumeric_13(newPoint.y0)) { + hoverData.push(cleanPoint(newPoint, hovermode)); + } + } + } + } + else { + _$lib_166.log('Unrecognized trace type in hover:', trace); + } + } - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + // in closest mode, remove any existing (farther) points + // and don't look any farther than this latest point (or points, some + // traces like box & violin make multiple hover labels at once) + if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + // Now if there is range to look in, find the points to draw the spikelines + // Do it only if there is no hoverData + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); + if(closestPoints) { + closestPoints = closestPoints.filter(function(point) { + // some hover points, like scatter fills, do not allow spikes, + // so will generate a hover point but without a valid spikeDistance + return point.spikeDistance <= spikedistance; + }); + } + if(closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes; + }); + if(closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if(_$fastIsnumeric_13(closestVPt.x0) && _$fastIsnumeric_13(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.vLinePoint = tmpPoint; + } + } + } - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes; + }); + if(closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if(_$fastIsnumeric_13(closestHPt.x0) && _$fastIsnumeric_13(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } } - else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + function selectClosestPoint(pointsData, spikedistance) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for(var i = 0; i < pointsData.length; i++) { + thisSpikeDistance = pointsData[i].spikeDistance; + if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { + resultPoint = pointsData[i]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + function fillSpikePoint(point) { + if(!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + var spikelineOpts = { + fullLayout: fullLayout, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + event: evt + }; + var oldspikepoints = gd._spikepoints, + newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); + // Now if it is not restricted by spikedistance option, set the points to draw the spikelines + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_210.idSort); - - // common attributes for all subplots, overlays or not + // if hoverData is empty check for the spikes to draw and quit if there are none + if(hoverData.length === 0) { + var result = _$dragelement_68.unhoverRaw(gd, evt); + if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } + return result; + } - for(var i = 0; i < _$constants_212.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_212.traceLayerClasses[i]); + if(hasCartesian) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } } - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); -} + // lastly, emit custom hover/unhover events + var oldhoverdata = gd._hoverdata, + newhoverdata = []; -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; + // pull out just the data that's useful to + // other people and send it to the event + for(itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + newhoverdata.push(_$helpers_85.makeEventData(pt, pt.trace, pt.cd)); + } - var overlayIdsToRemove = {}; + gd._hoverdata = newhoverdata; - layers.each(function(subplotId) { - var plotgroup = _$d3_10.select(this); + // if there's more than one horz bar trace, + // rotate the labels so they don't overlap + var rotateLabels = hovermode === 'y' && searchData.length > 1; - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + var bgColor = _$color_46.combine( + fullLayout.plot_bgcolor || _$color_46.background, + fullLayout.paper_bgcolor + ); - overlayIdsToRemove[subplotId] = true; + var labelOpts = { + hovermode: hovermode, + rotateLabels: rotateLabels, + bgColor: bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }; - // do not remove individual axis s here - // as other subplots may need them - }); + var hoverLabels = createHoverText(hoverData, labelOpts, gd); - // must remove overlaid subplot trace layers 'manually' + hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + alignHoverText(hoverLabels, rotateLabels); - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true + // we should improve the "fx" API so other plots can use it without these hack. + if(evt.target && evt.target.tagName) { + var hasClickToShow = _$registry_248.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_177(_$d3_10.select(evt.target), hasClickToShow ? 'pointer' : ''); + } - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; + // don't emit events if called manually + if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); - } - } + if(oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); + gd.emit('plotly_hover', { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray + }); } -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); +function createHoverText(hoverData, opts, gd) { + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; - layer.enter().append(nodeType) - .classed(className, true); + // opts.fontFamily/Size are used for the common label + // and as defaults for each hover label, though the individual labels + // can override this. + var fontFamily = opts.fontFamily || _$constants_83.HOVERFONT; + var fontSize = opts.fontSize || _$constants_83.HOVERFONTSIZE; - return layer; -} + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; + var t0 = c0[commonAttr]; + var t00 = (String(t0) || '').split(' ')[0]; + var outerContainerBB = outerContainer.node().getBoundingClientRect(); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; -_$cartesian_218.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_10.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); + // show the common label, if any, on the axis + // never show a common label in array mode, + // even if sometimes there could be one + var showCommonLabel = ( + (t0 !== undefined) && + (c0.distance <= opts.hoverdistance) && + (hovermode === 'x' || hovermode === 'y') + ); - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); + // all hover traces hoverinfo must contain the hovermode + // to have common labels + if(showCommonLabel) { + var i, traceHoverinfo; + var allHaveZ = true; + for(i = 0; i < hoverData.length; i++) { + if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; - image.attr({ - xmlns: _$xmlns_namespaces_150.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); + traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; + var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); + if(parts.indexOf('all') === -1 && + parts.indexOf(hovermode) === -1) { + showCommonLabel = false; + break; + } + } + + // xyz labels put all info in their main label, so have no need of a common label + if(allHaveZ) showCommonLabel = false; } - canvases.each(canvasToImage); -}; + var commonLabel = container.selectAll('g.axistext') + .data(showCommonLabel ? [0] : []); + commonLabel.enter().append('g') + .classed('axistext', true); + commonLabel.exit().remove(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + commonLabel.each(function() { + var label = _$d3_10.select(this); + var lpath = _$lib_166.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_166.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); + lpath.style({ + fill: commonLabelOpts.bgcolor || _$color_46.defaultLine, + stroke: commonLabelOpts.bordercolor || _$color_46.background, + }); -'use strict'; + ltext.text(t0) + .call(_$drawing_71.font, + commonLabelOpts.font.family || fontFamily, + commonLabelOpts.font.size || fontSize, + commonLabelOpts.font.color || _$color_46.background + ) + .call(_$svg_text_utils_187.positionText, 0, 0) + .call(_$svg_text_utils_187.convertToTspans, gd); -var mergeArray = _$lib_165.mergeArray; + label.attr('transform', ''); + var tbb = ltext.node().getBoundingClientRect(); + if(hovermode === 'x') { + ltext.attr('text-anchor', 'middle') + .call(_$svg_text_utils_187.positionText, 0, (xa.side === 'top' ? + (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : + (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); -// arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_256 = function arraysToCalcdata(cd, trace) { - for(var i = 0; i < cd.length; i++) cd[i].i = i; + var topsign = xa.side === 'top' ? '-' : ''; + lpath.attr('d', 'M0,0' + + 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + + 'H' + (HOVERTEXTPAD + tbb.width / 2) + + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + + 'H-' + (HOVERTEXTPAD + tbb.width / 2) + + 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); - mergeArray(trace.text, cd, 'tx'); - mergeArray(trace.hovertext, cd, 'htx'); + label.attr('transform', 'translate(' + + (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + + (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + } + else { + ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') + .call(_$svg_text_utils_187.positionText, + (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), + outerTop - tbb.top - tbb.height / 2); - var marker = trace.marker; - if(marker) { - mergeArray(marker.opacity, cd, 'mo'); - mergeArray(marker.color, cd, 'mc'); + var leftsign = ya.side === 'right' ? '' : '-'; + lpath.attr('d', 'M0,0' + + 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + + 'V' + (HOVERTEXTPAD + tbb.height / 2) + + 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + + 'V-' + (HOVERTEXTPAD + tbb.height / 2) + + 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); - var markerLine = marker.line; - if(markerLine) { - mergeArray(markerLine.color, cd, 'mlc'); - mergeArray(markerLine.width, cd, 'mlw'); + label.attr('transform', 'translate(' + + (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + + (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 the "close but not quite" points + // because of error bars, only take up to a space + hoverData = hoverData.filter(function(d) { + return (d.zLabelVal !== undefined) || + (d[commonAttr] || '').split(' ')[0] === t00; + }); + }); -'use strict'; + // show all the individual labels -/* removed: var _$attributes_317 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_54 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_47 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; + // first create the objects + var hoverLabels = container.selectAll('g.hovertext') + .data(hoverData, function(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); + }); + hoverLabels.enter().append('g') + .classed('hovertext', true) + .each(function() { + var g = _$d3_10.select(this); + // trace name label (rect and text.name) + g.append('rect') + .call(_$color_46.fill, _$color_46.addOpacity(bgColor, 0.8)); + g.append('text').classed('name', true); + // trace data label (path and text.nums) + g.append('path') + .style('stroke-width', '1px'); + g.append('text').classed('nums', true) + .call(_$drawing_71.font, fontFamily, fontSize); + }); + hoverLabels.exit().remove(); -var __extendFlat_257 = _$extend_159.extendFlat; + // then put the text in, position the pointer to the data, + // and figure out sizes + hoverLabels.each(function(d) { + var g = _$d3_10.select(this).attr('transform', ''), + name = '', + text = ''; -var textFontAttrs = _$font_attributes_234({ - editType: 'calc', - arrayOk: true, - -}); + // combine possible non-opaque trace color with bgColor + var baseColor = _$color_46.opacity(d.color) ? d.color : _$color_46.defaultLine; + var traceColor = _$color_46.combine(baseColor, bgColor); -var __scatterMarkerAttrs_257 = _$attributes_317.marker; -var scatterMarkerLineAttrs = __scatterMarkerAttrs_257.line; + // find a contrasting color for border and text + var contrastColor = d.borderColor || _$color_46.contrast(traceColor); -var markerLineWidth = __extendFlat_257({}, - scatterMarkerLineAttrs.width, { dflt: 0 }); + // to get custom 'name' labels pass cleanPoint + if(d.nameOverride !== undefined) d.name = d.nameOverride; -var markerLine = __extendFlat_257({ - width: markerLineWidth, - editType: 'calc' -}, _$makeColorScaleAttributes_54('marker.line')); + if(d.name) { + // strip out our pseudo-html elements from d.name (if it exists at all) + name = _$svg_text_utils_187.plainText(d.name || ''); -var marker = __extendFlat_257({ - line: markerLine, - editType: 'calc' -}, _$makeColorScaleAttributes_54('marker'), { - showscale: __scatterMarkerAttrs_257.showscale, - colorbar: _$attributes_47, - opacity: { - valType: 'number', - arrayOk: true, - dflt: 1, - min: 0, - max: 1, - - editType: 'style', - - } -}); + var nameLength = Math.round(d.nameLength); -var _$attributes_257 = { - x: _$attributes_317.x, - x0: _$attributes_317.x0, - dx: _$attributes_317.dx, - y: _$attributes_317.y, - y0: _$attributes_317.y0, - dy: _$attributes_317.dy, + if(nameLength > -1 && name.length > nameLength) { + if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; + else name = name.substr(0, nameLength); + } + } - text: _$attributes_317.text, - hovertext: _$attributes_317.hovertext, + if(d.zLabel !== undefined) { + if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; + if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; + text += (text ? 'z: ' : '') + d.zLabel; + } + else if(showCommonLabel && d[hovermode + 'Label'] === t0) { + text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; + } + else if(d.xLabel === undefined) { + if(d.yLabel !== undefined) text = d.yLabel; + } + else if(d.yLabel === undefined) text = d.xLabel; + else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; - textposition: { - valType: 'enumerated', - - values: ['inside', 'outside', 'auto', 'none'], - dflt: 'none', - arrayOk: true, - editType: 'calc', - - }, + if(d.text && !Array.isArray(d.text)) { + text += (text ? '
' : '') + d.text; + } - textfont: __extendFlat_257({}, textFontAttrs, { - - }), + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; - insidetextfont: __extendFlat_257({}, textFontAttrs, { - - }), + // if 'text' is empty at this point, + // put 'name' in main label and don't show secondary label + if(text === '') { + // if 'name' is also empty, remove entire label + if(name === '') g.remove(); + text = name; + } - outsidetextfont: __extendFlat_257({}, textFontAttrs, { - - }), + // main label + var tx = g.select('text.nums') + .call(_$drawing_71.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + d.fontColor || contrastColor) + .text(text) + .attr('data-notex', 1) + .call(_$svg_text_utils_187.positionText, 0, 0) + .call(_$svg_text_utils_187.convertToTspans, gd); - constraintext: { - valType: 'enumerated', - values: ['inside', 'outside', 'both', 'none'], - - dflt: 'both', - editType: 'calc', - - }, + var tx2 = g.select('text.name'), + tx2width = 0; - cliponaxis: __extendFlat_257({}, _$attributes_317.cliponaxis, { - - }), + // secondary label for non-empty 'name' + if(name && name !== text) { + tx2.call(_$drawing_71.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + traceColor) + .text(name) + .attr('data-notex', 1) + .call(_$svg_text_utils_187.positionText, 0, 0) + .call(_$svg_text_utils_187.convertToTspans, gd); + tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; + } + else { + tx2.remove(); + g.select('rect').remove(); + } - orientation: { - valType: 'enumerated', - - values: ['v', 'h'], - editType: 'calc+clearAxisTypes', - - }, + g.select('path') + .style({ + fill: traceColor, + stroke: contrastColor + }); + var tbb = tx.node().getBoundingClientRect(), + htx = d.xa._offset + (d.x0 + d.x1) / 2, + hty = d.ya._offset + (d.y0 + d.y1) / 2, + dx = Math.abs(d.x1 - d.x0), + dy = Math.abs(d.y1 - d.y0), + txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, + anchorStartOK, + anchorEndOK; - base: { - valType: 'any', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, + d.ty0 = outerTop - tbb.top; + d.bx = tbb.width + 2 * HOVERTEXTPAD; + d.by = tbb.height + 2 * HOVERTEXTPAD; + d.anchor = 'start'; + d.txwidth = tbb.width; + d.tx2width = tx2width; + d.offset = 0; - offset: { - valType: 'number', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, - - width: { - valType: 'number', - dflt: null, - min: 0, - arrayOk: true, - - editType: 'calc', - - }, - - marker: marker, - - selected: { - marker: { - opacity: _$attributes_317.selected.marker.opacity, - color: _$attributes_317.selected.marker.color, - editType: 'style' - }, - textfont: _$attributes_317.selected.textfont, - editType: 'style' - }, - unselected: { - marker: { - opacity: _$attributes_317.unselected.marker.opacity, - color: _$attributes_317.unselected.marker.color, - editType: 'style' - }, - textfont: _$attributes_317.unselected.textfont, - editType: 'style' - }, - - r: _$attributes_317.r, - t: _$attributes_317.t, - - _deprecated: { - bardir: { - valType: 'enumerated', - - editType: 'calc', - values: ['v', 'h'], - + if(rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + hty += dy / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } + else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + htx += dx / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_165 = require('../../lib'); */; - -var _$calcSelection_319 = function calcSelection(cd, trace) { - if(_$lib_165.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_165.tagSelected(cd, trace); - } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + tx.attr('text-anchor', d.anchor); + if(tx2width) tx2.attr('text-anchor', d.anchor); + g.attr('transform', 'translate(' + htx + ',' + hty + ')' + + (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); + }); + return hoverLabels; +} -'use strict'; +// Make groups of touching points, and within each group +// move each point so that no labels overlap, but the average +// label position is the same as it was before moving. Indicentally, +// this is equivalent to saying all the labels are on equal linear +// springs about their initial position. Initially, each point is +// its own group, but as we find overlaps we will clump the points. +// +// Also, there are hard constraints at the edges of the graphs, +// that push all groups to the middle so they are visible. I don't +// know what happens if the group spans all the way from one edge to +// the other, though it hardly matters - there's just too much +// information then. +function hoverAvoidOverlaps(hoverData, ax, fullLayout) { + var nummoves = 0, -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_258 = _$lib_165.isArrayOrTypedArray; + // make groups of touching points + pointgroups = hoverData + .map(function(d, i) { + var axis = d[ax]; + return [{ + i: i, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, + pmin: 0, + pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) + }]; + }) + .sort(function(a, b) { return a[0].posref - b[0].posref; }), + donepositioning, + topOverlap, + bottomOverlap, + i, j, + pti, + sumdp; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_53 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_256 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_319 = require('../scatter/calc_selection'); */; + function constrainGroup(grp) { + var minPt = grp[0], + maxPt = grp[grp.length - 1]; -var _$calc_258 = function calc(gd, trace) { - // depending on bar direction, set position and size axes - // and data ranges - // note: this logic for choosing orientation is - // duplicated in graph_obj->setstyles + // overlap with the top - positive vals are overlaps + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; - var xa = _$axes_207.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_207.getFromId(gd, trace.yaxis || 'y'), - orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), - sa, pos, size, i, scalendar; + // overlap with the bottom - positive vals are overlaps + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; - if(orientation === 'h') { - sa = xa; - size = xa.makeCalcdata(trace, 'x'); - pos = ya.makeCalcdata(trace, 'y'); + // check for min overlap first, so that we always + // see the largest labels + // allow for .01px overlap, so we don't get an + // infinite loop from rounding errors + if(topOverlap > 0.01) { + for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; + donepositioning = false; + } + if(bottomOverlap < 0.01) return; + if(topOverlap < -0.01) { + // make sure we're not pushing back and forth + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + donepositioning = false; + } + if(!donepositioning) return; - // 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. - scalendar = trace.xcalendar; - } - else { - sa = ya; - size = ya.makeCalcdata(trace, 'y'); - pos = xa.makeCalcdata(trace, 'x'); - scalendar = trace.ycalendar; - } + // no room to fix positioning, delete off-screen points - // create the "calculated data" to plot - var serieslen = Math.min(pos.length, size.length); - var cd = new Array(serieslen); + // first see how many points we need to delete + var deleteCount = 0; + for(i = 0; i < grp.length; i++) { + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } - // set position and size - for(i = 0; i < serieslen; i++) { - cd[i] = { p: pos[i], s: size[i] }; + // start by deleting points whose data is off screen + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; - if(trace.ids) { - cd[i].id = String(trace.ids[i]); + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } } - } + for(i = 0; i < grp.length; i++) { + if(deleteCount <= 0) break; + pti = grp[i]; - // set base - var base = trace.base, - b; + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; - if(__isArrayOrTypedArray_258(base)) { - for(i = 0; i < Math.min(base.length, cd.length); i++) { - b = sa.d2c(base[i], 0, scalendar); - if(_$fastIsnumeric_13(b)) { - cd[i].b = +b; - cd[i].hasB = 1; + // shift the whole group minus into this new space + bottomOverlap = pti.size * 2; + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; } - else cd[i].b = 0; - } - for(; i < cd.length; i++) { - cd[i].b = 0; } - } - else { - b = sa.d2c(base, 0, scalendar); - var hasBase = _$fastIsnumeric_13(b); - b = hasBase ? b : 0; - for(i = 0; i < cd.length; i++) { - cd[i].b = b; - if(hasBase) cd[i].hasB = 1; + // then delete points that go off the bottom + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } } } - // auto-z and autocolorscale if applicable - if(_$hasColorscale_60(trace, 'marker')) { - _$calc_53(trace, trace.marker.color, 'marker', 'c'); - } - if(_$hasColorscale_60(trace, 'marker.line')) { - _$calc_53(trace, trace.marker.line.color, 'marker.line', 'c'); - } - - _$arraysToCalcdata_256(cd, trace); - _$calcSelection_319(cd, trace); - - return cd; -}; + // loop through groups, combining them if they overlap, + // until nothing moves + while(!donepositioning && nummoves <= hoverData.length) { + // to avoid infinite loops, don't move more times + // than there are traces + nummoves++; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // assume nothing will move in this iteration, + // reverse this if it does + donepositioning = true; + i = 0; + while(i < pointgroups.length - 1) { + // the higher (g0) and lower (g1) point group + var g0 = pointgroups[i], + g1 = pointgroups[i + 1], + // the lowest point in the higher group (p0) + // the highest point in the lower group (p1) + p0 = g0[g0.length - 1], + p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; -'use strict'; + // Only group points that lie on the same axes + if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { + // push the new point(s) added to this group out of the way + for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_56 = require('../../components/colorscale/defaults'); */; + // add them to the group + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); -var _$handleStyleDefaults_269 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { - coerce('marker.color', defaultColor); + // adjust for minimum average movement + sumdp = 0; + for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } + else i++; + } - if(_$hasColorscale_60(traceIn, 'marker')) { - _$colorScaleDefaults_56( - traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} - ); + // check if we're going off the plot on either side and fix + pointgroups.forEach(constrainGroup); } - coerce('marker.line.color', _$color_46.defaultLine); - - if(_$hasColorscale_60(traceIn, 'marker.line')) { - _$colorScaleDefaults_56( - traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} - ); + // now put these offsets into hoverData + for(i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for(j = grp.length - 1; j >= 0; j--) { + var pt = grp[j], + hoverPt = hoverData[pt.i]; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } } +} - coerce('marker.line.width'); - coerce('marker.opacity'); - coerce('selected.marker.color'); - coerce('unselected.marker.color'); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; +function alignHoverText(hoverLabels, rotateLabels) { + // finally set the text positioning relative to the data and draw the + // box around it + hoverLabels.each(function(d) { + var g = _$d3_10.select(this); + if(d.del) { + g.remove(); + return; + } + var horzSign = d.anchor === 'end' ? -1 : 1, + tx = g.select('text.nums'), + alignShift = {start: 1, end: -1, middle: 0}[d.anchor], + txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), + tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), + offsetX = 0, + offsetY = d.offset; + if(d.anchor === 'middle') { + txx -= d.tx2width / 2; + tx2x += d.txwidth / 2 + HOVERTEXTPAD; + } + if(rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = d.offset * YSHIFTX; + } -/* removed: var _$registry_247 = require('../../registry'); */; + g.select('path').attr('d', d.anchor === 'middle' ? + // middle aligned: rect centered on data + ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + + 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : + // left or right aligned: side rect with arrow to data + ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + + 'v' + (d.by / 2 - HOVERARROWSIZE) + + 'h' + (horzSign * d.bx) + + 'v-' + d.by + + 'H' + (horzSign * HOVERARROWSIZE + offsetX) + + 'V' + (offsetY - HOVERARROWSIZE) + + 'Z')); + tx.call(_$svg_text_utils_187.positionText, + txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); -var _$handleXYDefaults_341 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { - var len, - x = coerce('x'), - y = coerce('y'); + if(d.tx2width) { + g.select('text.name') + .call(_$svg_text_utils_187.positionText, + tx2x + alignShift * HOVERTEXTPAD + offsetX, + offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + g.select('rect') + .call(_$drawing_71.setRect, + tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, + offsetY - d.by / 2 - 1, + d.tx2width, d.by + 2); + } + }); +} - var handleCalendarDefaults = _$registry_247.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); +function cleanPoint(d, hovermode) { + var index = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index] || {}; - if(x) { - if(y) { - len = Math.min(x.length, y.length); - } - else { - len = x.length; - coerce('y0'); - coerce('dy'); - } - } - else { - if(!y) return 0; + var getVal = Array.isArray(index) ? + function(calcKey, traceKey) { + return _$lib_166.castOption(cd0, index, calcKey) || + _$lib_166.extractOption({}, trace, '', traceKey); + } : + function(calcKey, traceKey) { + return _$lib_166.extractOption(cd, trace, calcKey, traceKey); + }; - len = traceOut.y.length; - coerce('x0'); - coerce('dx'); + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if(val) d[key] = val; } - traceOut._length = len; + fill('hoverinfo', 'hi', 'hoverinfo'); + fill('color', 'hbg', 'hoverlabel.bgcolor'); + fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); + fill('fontFamily', 'htf', 'hoverlabel.font.family'); + fill('fontSize', 'hts', 'hoverlabel.font.size'); + fill('fontColor', 'htc', 'hoverlabel.font.color'); + fill('nameLength', 'hnl', 'hoverlabel.namelength'); - return len; -}; + d.posref = hovermode === 'y' ? + (d.xa._offset + (d.x0 + d.x1) / 2) : + (d.ya._offset + (d.y0 + d.y1) / 2); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // then constrain all the positions to be on the plot + d.x0 = _$lib_166.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_166.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_166.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_166.constrain(d.y1, 0, d.ya._length); + // and convert the x and y label values into formatted text + if(d.xLabelVal !== undefined) { + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_208.hoverLabelText(d.xa, d.xLabelVal); + d.xVal = d.xa.c2d(d.xLabelVal); + } + if(d.yLabelVal !== undefined) { + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_208.hoverLabelText(d.ya, d.yLabelVal); + d.yVal = d.ya.c2d(d.yLabelVal); + } -'use strict'; + // Traces like heatmaps generate the zLabel in their hoverPoints function + if(d.zLabelVal !== undefined && d.zLabel === undefined) { + d.zLabel = String(d.zLabelVal); + } -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$registry_247 = require('../../registry'); */; + // for box means and error bars, add the range to the label + if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { + var xeText = _$axes_208.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + if(d.xerrneg !== undefined) { + d.xLabel += ' +' + xeText + ' / -' + + _$axes_208.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + else d.xLabel += ' ± ' + xeText; -/* removed: var _$handleXYDefaults_341 = require('../scatter/xy_defaults'); */; -/* removed: var _$handleStyleDefaults_269 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_257 = require('./attributes'); */; + // small distance penalty for error bars, so that if there are + // traces with errors and some without, the error bar label will + // hoist up to the point + if(hovermode === 'x') d.distance += 1; + } + if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { + var yeText = _$axes_208.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + if(d.yerrneg !== undefined) { + d.yLabel += ' +' + yeText + ' / -' + + _$axes_208.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + } + else d.yLabel += ' ± ' + yeText; -var _$supplyDefaults_259 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_257, attr, dflt); + if(hovermode === 'y') d.distance += 1; } - var coerceFont = _$lib_165.coerceFont; + var infomode = d.hoverinfo || d.trace.hoverinfo; - var len = _$handleXYDefaults_341(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; + if(infomode !== 'all') { + infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); + if(infomode.indexOf('x') === -1) d.xLabel = undefined; + if(infomode.indexOf('y') === -1) d.yLabel = undefined; + if(infomode.indexOf('z') === -1) d.zLabel = undefined; + if(infomode.indexOf('text') === -1) d.text = undefined; + if(infomode.indexOf('name') === -1) d.name = undefined; } - coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); - coerce('base'); - coerce('offset'); - coerce('width'); + return d; +} - coerce('text'); - coerce('hovertext'); +function createSpikelines(closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var evt = opts.event; + var xa, + ya; - var textPosition = coerce('textposition'); + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; - var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', - hasInside = hasBoth || textPosition === 'inside', - hasOutside = hasBoth || textPosition === 'outside'; + // Remove old spikeline items + container.selectAll('.spikeline').remove(); - if(hasInside || hasOutside) { - var textFont = coerceFont(coerce, 'textfont', layout.font); - if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); - if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); - coerce('constraintext'); - coerce('selected.textfont.color'); - coerce('unselected.textfont.color'); - coerce('cliponaxis'); - } + if(!(showX || showY)) return; - _$handleStyleDefaults_269(traceIn, traceOut, coerce, defaultColor, layout); + var contrastColor = _$color_46.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); - // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_247.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_46.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_46.defaultLine, {axis: 'x', inherit: 'y'}); + // Horizontal line (to y-axis) + if(showY) { + var hLinePoint = closestPoints.hLinePoint, + hLinePointX, + hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; - _$lib_165.coerceSelectionMarkerOpacity(traceOut, coerce); -}; + if(ySnap === 'cursor') { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = _$tinycolor_28.readability(hLinePoint.color, contrastColor) < 1.5 ? + _$color_46.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode, + yThickness = ya.spikethickness, + yColor = ya.spikecolor || dfltHLineColor, + yBB = ya._boundingBox, + xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, + xBase, + xEndSpike; -var _$client_17 = true; -var _$hasHover_15 = {}; -(function (global){ -'use strict' - -/* removed: var _$client_17 = require('is-browser') */; -var hasHover - -if (typeof global.matchMedia === 'function') { - hasHover = !global.matchMedia('(hover: none)').matches -} -else { - hasHover = _$client_17 -} - -_$hasHover_15 = hasHover + if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { + if(yMode.indexOf('toaxis') !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; + } + if(yMode.indexOf('across') !== -1) { + xBase = ya._counterSpan[0]; + xEndSpike = ya._counterSpan[1]; + } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -'use strict' - -/* removed: var _$client_17 = require('is-browser') */; - -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 -} - -var _$hasPassiveEvents_16 = _$client_17 && detect() + // Foreground horizontal line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness, + 'stroke': yColor, + 'stroke-dasharray': _$drawing_71.dashStyle(ya.spikedash, yThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); -var rootPosition = { left: 0, top: 0 } + // Background horizontal Line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + // Y axis marker + if(yMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), + 'cy': hLinePointY, + 'r': yThickness, + 'fill': yColor + }) + .classed('spikeline', true); + } + } -var _$mouseEventOffset_18 = mouseEventOffset -function mouseEventOffset (ev, target, out) { - target = target || ev.currentTarget || ev.srcElement - if (!Array.isArray(out)) { - out = [ 0, 0 ] - } - var cx = ev.clientX || 0 - var cy = ev.clientY || 0 - var rect = getBoundingClientOffset(target) - out[0] = cx - rect.left - out[1] = cy - rect.top - return out + if(showX) { + var vLinePoint = closestPoints.vLinePoint, + vLinePointX, + vLinePointY; + + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; + + if(xSnap === 'cursor') { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; + } + var dfltVLineColor = _$tinycolor_28.readability(vLinePoint.color, contrastColor) < 1.5 ? + _$color_46.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode, + xThickness = xa.spikethickness, + xColor = xa.spikecolor || dfltVLineColor, + xBB = xa._boundingBox, + yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, + yBase, + yEndSpike; + + if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { + if(xMode.indexOf('toaxis') !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if(xMode.indexOf('across') !== -1) { + yBase = xa._counterSpan[0]; + yEndSpike = xa._counterSpan[1]; + } + + // Foreground vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness, + 'stroke': xColor, + 'stroke-dasharray': _$drawing_71.dashStyle(xa.spikedash, xThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + + // X axis marker + if(xMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': vLinePointX, + 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), + 'r': xThickness, + 'fill': xColor + }) + .classed('spikeline', true); + } + } } -function getBoundingClientOffset (element) { - if (element === window || - element === document || - element === document.body) { - return rootPosition - } else { - return element.getBoundingClientRect() - } +function hoverChanged(gd, evt, oldhoverdata) { + // don't emit any events if nothing changed + if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + + for(var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i], + newPt = gd._hoverdata[i]; + if(oldPt.curveNumber !== newPt.curveNumber || + String(oldPt.pointNumber) !== String(newPt.pointNumber)) { + return true; + } + } + return false; +} + +function spikesChanged(gd, oldspikepoints) { + // don't relayout the plot because of new spikelines if spikelines points didn't change + if(!oldspikepoints) return true; + if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || + oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint + ) return true; + return false; } /** @@ -30850,28 +31439,33 @@ function getBoundingClientOffset (element) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$registry_248 = require('../../registry'); */; +var hover = _$hover_86.hover; -// 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 -var _$align_66 = function align(v, dv, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0), - vmax = vmin + dv / (v1 - v0), - vc = (vmin + vmax) / 2; +var _$click_82 = function click(gd, evt, subplot) { + var annotationsDone = _$registry_248.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); - // explicitly specified anchor - if(anchor === 'left' || anchor === 'bottom') return vmin; - if(anchor === 'center' || anchor === 'middle') return vc; - if(anchor === 'right' || anchor === 'top') return vmax; + // 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); + } - // automatic based on position - if(vmin < (2 / 3) - vc) return vmin; - if(vmax > (4 / 3) - vc) return vmax; - return vc; + 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(); + } }; /** @@ -30882,33 +31476,39 @@ var _$align_66 = function align(v, dv, v0, v1, anchor) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +var _$handleHoverLabelDefaults_87 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { + opts = opts || {}; -// 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'] -]; + coerce('hoverlabel.bgcolor', opts.bgcolor); + coerce('hoverlabel.bordercolor', opts.bordercolor); + coerce('hoverlabel.namelength', opts.namelength); + _$lib_166.coerceFont(coerce, 'hoverlabel.font', opts.font); +}; -var _$getCursor_67 = 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_165.constrain(Math.floor(x * 3), 0, 2); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(yanchor === 'bottom') y = 0; - else if(yanchor === 'middle') y = 1; - else if(yanchor === 'top') y = 2; - else y = _$lib_165.constrain(Math.floor(y * 3), 0, 2); +'use strict'; - return cursorset[y][x]; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$attributes_80 = require('./attributes'); */; +/* removed: var _$handleHoverLabelDefaults_87 = require('./hoverlabel_defaults'); */; + +var _$supplyDefaults_84 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_166.coerce(traceIn, traceOut, _$attributes_80, attr, dflt); + } + + _$handleHoverLabelDefaults_87(traceIn, traceOut, coerce, layout.hoverlabel); }; /** @@ -30921,330 +31521,169 @@ var _$getCursor_67 = function getCursor(x, y, xanchor, yanchor) { 'use strict'; -var _$constants_83 = { - // hover labels for multiple horizontal bars get tilted by this angle - YANGLE: 60, +/* removed: var _$constants_83 = require('./constants'); */; - // size and display constants for hover text +var __fontAttrs_89 = _$font_attributes_234({ + editType: 'none', + +}); +__fontAttrs_89.family.dflt = _$constants_83.HOVERFONT; +__fontAttrs_89.size.dflt = _$constants_83.HOVERFONTSIZE; - // pixel size of hover arrows - HOVERARROWSIZE: 6, - // pixels padding around text - HOVERTEXTPAD: 3, - // hover font - HOVERFONTSIZE: 13, - HOVERFONT: 'Arial, sans-serif', +var _$layout_attributes_89 = { + dragmode: { + valType: 'enumerated', + + values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], + dflt: 'zoom', + editType: 'modebar', + + }, + hovermode: { + valType: 'enumerated', + + values: ['x', 'y', 'closest', false], + editType: 'modebar', + + }, + hoverdistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + spikedistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'none', + + }, + bordercolor: { + valType: 'color', + + editType: 'none', + + }, + font: __fontAttrs_89, + namelength: { + valType: 'integer', + min: -1, + dflt: 15, + + editType: 'none', + + }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + + editType: 'none' + } +}; - // minimum time (msec) between hover calls - HOVERMINTIME: 50, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // ID suffix (with fullLayout._uid) for hover events in the throttle cache - HOVERID: '-hover' -}; +'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. +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$layout_attributes_89 = require('./layout_attributes'); */; -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -var _$EventEmitter_12 = EventEmitter; +var _$supplyLayoutDefaults_90 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_89, attr, dflt); + } -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; + var hovermodeDflt; + if(layoutOut._has('cartesian')) { + // flag for 'horizontal' plots: + // determines the state of the mode bar 'compare' hovermode button + layoutOut._isHoriz = isHoriz(fullData); + hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + } + else hovermodeDflt = 'closest'; -// 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. -EventEmitter.defaultMaxListeners = 10; + var hoverMode = coerce('hovermode', hovermodeDflt); + if(hoverMode) { + coerce('hoverdistance'); + coerce('spikedistance'); + } -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; + // if only mapbox or geo subplots is present on graph, + // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, + // so that the correct modebar button is active + var hasMapbox = layoutOut._has('mapbox'); + var hasGeo = layoutOut._has('geo'); + var len = layoutOut._basePlotModules.length; + + if(layoutOut.dragmode === 'zoom' && ( + ((hasMapbox || hasGeo) && len === 1) || + (hasMapbox && hasGeo && len === 2) + )) { + layoutOut.dragmode = 'pan'; + } }; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; +function isHoriz(fullData) { + var out = true; - if (!this._events) - this._events = {}; + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } + if(trace.orientation !== 'h') { + out = false; + break; + } } - } - handler = this._events[type]; + return out; +} - if (isUndefined(handler)) - return false; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; +'use strict'; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$handleHoverLabelDefaults_87 = require('./hoverlabel_defaults'); */; +/* removed: var _$layout_attributes_89 = require('./layout_attributes'); */; - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); +var _$supplyLayoutGlobalDefaults_91 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce(attr, dflt) { + return _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_89, attr, dflt); } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); + _$handleHoverLabelDefaults_87(layoutIn, layoutOut, coerce); }; -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31253,164 +31692,75 @@ function isUndefined(arg) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* global jQuery:false */ - -var __EventEmitter_158 = _$EventEmitter_12.EventEmitter; - -var Events = { - - init: function(plotObj) { - - /* - * If we have already instantiated an emitter for this plot - * return early. - */ - if(plotObj._ev instanceof __EventEmitter_158) return plotObj; - - var ev = new __EventEmitter_158(); - var internalEv = new __EventEmitter_158(); - - /* - * Assign to plot._ev while we still live in a land - * where plot is a DOM element with stuff attached to it. - * In the future we can make plot the event emitter itself. - */ - plotObj._ev = ev; - - /* - * Create a second event handler that will manage events *internally*. - * This allows parts of plotly to respond to thing like relayout without - * having to use the user-facing event handler. They cannot peacefully - * coexist on the same handler because a user invoking - * plotObj.removeAllListeners() would detach internal events, breaking - * plotly. - */ - plotObj._internalEv = internalEv; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$helpers_85 = require('./helpers'); */; +/* removed: var _$layout_attributes_89 = require('./layout_attributes'); */; - /* - * Assign bound methods from the ev to the plot object. These methods - * will reference the 'this' of plot._ev even though they are methods - * of plot. This will keep the event machinery away from the plot object - * which currently is often a DOM element but presents an API that will - * continue to function when plot becomes an emitter. Not all EventEmitter - * methods have been bound to `plot` as some do not currently add value to - * the Plotly event API. - */ - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); +var _$fx_88 = { + moduleType: 'component', + name: 'fx', - /* - * Create funtions for managing internal events. These are *only* triggered - * by the mirroring of external events via the emit function. - */ - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); + constants: _$constants_83, + schema: { + layout: _$layout_attributes_89 + }, - /* - * We must wrap emit to continue to support JQuery events. The idea - * is to check to see if the user is using JQuery events, if they are - * we emit JQuery events to trigger user handlers as well as the EventEmitter - * events. - */ - plotObj.emit = function(event, data) { - if(typeof jQuery !== 'undefined') { - jQuery(plotObj).trigger(event, data); - } + attributes: _$attributes_80, + layoutAttributes: _$layout_attributes_89, - ev.emit(event, data); - internalEv.emit(event, data); - }; + supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_91, + supplyDefaults: _$supplyDefaults_84, + supplyLayoutDefaults: _$supplyLayoutDefaults_90, - return plotObj; - }, + calc: _$calc_81, - /* - * This function behaves like jQueries triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - * - * Note: triggerHandler has been recommended for deprecation in v2.0.0, - * so the additional behavior of triggerHandler triggering internal events - * is deliberate excluded in order to avoid reinforcing more usage. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - /* - * If Jquery exists run all its handlers for this event and - * collect the return value of the LAST handler function - */ - if(typeof jQuery !== 'undefined') { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); - } + getDistanceFunction: _$helpers_85.getDistanceFunction, + getClosest: _$helpers_85.getClosest, + inbox: _$helpers_85.inbox, + quadrature: _$helpers_85.quadrature, + appendArrayPointValue: _$helpers_85.appendArrayPointValue, - /* - * Now run all the node style event handlers - */ - var ev = plotObj._ev; - if(!ev) return jQueryHandlerValue; + castHoverOption: castHoverOption, + castHoverinfo: castHoverinfo, - var handlers = ev._events[event]; - if(!handlers) return jQueryHandlerValue; + hover: _$hover_86.hover, + unhover: _$dragelement_68.unhover, - /* - * handlers can be function or an array of functions - */ - if(typeof handlers === 'function') handlers = [handlers]; - var lastHandler = handlers.pop(); + loneHover: _$hover_86.loneHover, + loneUnhover: loneUnhover, - /* - * Call all the handlers except the last one. - */ - for(var i = 0; i < handlers.length; i++) { - handlers[i](data); - } + click: _$click_82 +}; - /* - * Now call the final handler and collect its value - */ - nodeEventHandlerValue = lastHandler(data); +function loneUnhover(containerOrSelection) { + // duck type whether the arg is a d3 selection because ie9 doesn't + // handle instanceof like modern browsers do. + var selection = _$lib_166.isD3Selection(containerOrSelection) ? + containerOrSelection : + _$d3_10.select(containerOrSelection); - /* - * Return either the jquery handler value if it exists or the - * nodeEventHandler value. Jquery event value superceeds nodejs - * events for backwards compatability reasons. - */ - return jQueryHandlerValue !== undefined ? jQueryHandlerValue : - nodeEventHandlerValue; - }, + selection.selectAll('g.hovertext').remove(); + selection.selectAll('.spikeline').remove(); +} - purge: function(plotObj) { - delete plotObj._ev; - delete plotObj.on; - delete plotObj.once; - delete plotObj.removeListener; - delete plotObj.removeAllListeners; - delete plotObj.emit; +// helpers for traces that use Fx.loneHover - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; +function castHoverOption(trace, ptNumber, attr) { + return _$lib_166.castOption(trace, ptNumber, 'hoverlabel.' + attr); +} - return plotObj; +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return _$lib_166.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } -}; - -var _$Events_158 = Events; + return _$lib_166.castOption(trace, ptNumber, 'hoverinfo', _coerce); +} -var _$unhover_69 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31419,56 +31769,25 @@ var _$unhover_69 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; - -/* removed: var _$Events_158 = require('../../lib/events'); */; -/* removed: var _$throttle_187 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_163 = require('../../lib/get_graph_div'); */; - -/* removed: var _$constants_83 = require('../fx/constants'); */; - -var unhover = _$unhover_69 = {}; - - -unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_163(gd); - - // Important, clear any queued hovers - if(gd._fullLayout) { - _$throttle_187.clear(gd._fullLayout._uid + _$constants_83.HOVERID); - } - - unhover.raw(gd, evt, subplot); -}; - - -// remove hover effects on mouse out, and emit unhover event -unhover.raw = function unhoverRaw(gd, evt) { +/** + * 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 + */ +var _$clearGlCanvases_155 = function clearGlCanvases(gd) { var fullLayout = gd._fullLayout; - var oldhoverdata = gd._hoverdata; - - if(!evt) evt = {}; - if(evt.target && - _$Events_158.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 + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); }); } }; -var _$dragelement_68 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31480,2142 +31799,2402 @@ var _$dragelement_68 = {}; 'use strict'; -/* removed: var _$mouseEventOffset_18 = require('mouse-event-offset'); */; -/* removed: var _$hasHover_15 = require('has-hover'); */; -/* removed: var _$hasPassiveEvents_16 = require('has-passive-events'); */; +var FROM_BL = _$alignment_146.FROM_BL; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; +var _$scaleZoom_224 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } -/* removed: var _$constants_212 = require('../../plots/cartesian/constants'); */; -/* removed: var _$interactions_147 = require('../../constants/interactions'); */; + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; -var dragElement = _$dragelement_68 = {}; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; -dragElement.align = _$align_66; -dragElement.getCursor = _$getCursor_67; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$unhover_69 = require('./unhover'); */; -dragElement.unhover = _$unhover_69.wrapped; -dragElement.unhoverRaw = _$unhover_69.raw; +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; -/** - * 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 DBLCLICKDELAY = _$interactions_147.DBLCLICKDELAY; - var element = options.element; - - var startX, - startY, - newMouseDownTime, - cursor, - dragCover, - initialEvent, - initialTarget, - rightClick; - - if(!gd._mouseDownTime) gd._mouseDownTime = 0; + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - element.style.pointerEvents = 'all'; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; +} - element.onmousedown = onStart; +var _$BuildLog_20 = BuildLog; - if(!_$hasPassiveEvents_16) { - element.ontouchstart = onStart; - } - else { - if(element._ontouchstart) { - element.removeEventListener('touchstart', element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener('touchstart', onStart, {passive: false}); - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - function _clampFn(dx, dy, minDrag) { - if(Math.abs(dx) < minDrag) dx = 0; - if(Math.abs(dy) < minDrag) dy = 0; - return [dx, dy]; - } +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// - var clampFn = options.clampFn || _clampFn; +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; - function onStart(e) { - e.preventDefault(); + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; - // 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; + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { - // in a click train - numClicks += 1; - } - else { - // new click train - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; - if(options.prepFn) options.prepFn(e, startX, startY); + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - if(_$hasHover_15 && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } - else if(!_$hasHover_15) { - // 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; - } + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - document.addEventListener('mousemove', onMove); - document.addEventListener('mouseup', onDone); - document.addEventListener('touchmove', onMove); - document.addEventListener('touchend', onDone); + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; - return; - } + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; - function onMove(e) { - e.preventDefault(); + // categorize where intersection point is along A and B - var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_212.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - if(dx || dy) { - gd._dragged = true; - dragElement.unhover(gd); - } + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; - return; - } + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside - function onDone(e) { - document.removeEventListener('mousemove', onMove); - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchmove', onMove); - document.removeEventListener('touchend', onDone); + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} - e.preventDefault(); +var _$Epsilon_21 = Epsilon; - if(_$hasHover_15) { - _$lib_165.removeElement(dragCover); - } - else if(cursor) { - dragCover.documentElement.style.cursor = cursor; - cursor = null; - } +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if(!gd._dragging) { - gd._dragged = false; - return; - } - gd._dragging = false; +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// - // don't count as a dblClick unless the mouseUp is also within - // the dblclick delay - if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - if(gd._dragged) { - if(options.doneFn) options.doneFn(e); - } - else { - if(options.clickFn) options.clickFn(numClicks, initialEvent); + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - // 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; + // 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] }); + } - 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); - } + // the first LineString is considered the outside + var out = LineString(coords[0]); - initialTarget.dispatchEvent(e2); - } - } + // 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]))); - finishDrag(gd); + return out; + } - gd._dragged = false; + 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'); + }, - return; - } -}; + // 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)); -function coverSlip() { - var cover = document.createElement('div'); + // 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); + } - 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'; + // calculate inside heirarchy + // + // _____________________ _______ roots -> A -> F + // | A | | F | | | + // | _______ _______ | | ___ | +-- B +-- G + // | | B | | C | | | | | | | | + // | | ___ | | ___ | | | | | | | +-- D + // | | | D | | | | E | | | | | G | | | + // | | |___| | | |___| | | | | | | +-- C + // | |_______| |_______| | | |___| | | + // |_____________________| |_______| +-- E - document.body.appendChild(cover); + function newNode(region){ + return { + region: region, + children: [] + }; + } - return cover; -} + var roots = newNode(null); -dragElement.coverSlip = coverSlip; + 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; + } + } -function finishDrag(gd) { - gd._dragging = false; - if(gd._replotPending) _$registry_247.call('plot', gd); -} - -function pointerOffset(e) { - return _$mouseEventOffset_18( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); -} + // 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--; + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // now we can add ourselves + root.children.push(node); + } -'use strict'; + // 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); + } -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$registry_247 = require('../../registry'); */; + // 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 -var _$calc_81 = function calc(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - function makeCoerceHoverInfo(trace) { - return function(val) { - return _$lib_165.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); - }; - } + 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; + } - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + var geopolys = []; - // 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_247.traceIs(trace, 'pie')) continue; + 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])); + } - var fillFn = _$registry_247.traceIs(trace, '2dMap') ? paste : _$lib_165.fillArray; + 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); + } - fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - if(!trace.hoverlabel) continue; + // lastly, construct the approrpriate GeoJSON object - 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'); - } + 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 + }; + } }; -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_165.identity; - - if(Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); - } -} - -var _$helpers_85 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$GeoJSON_22 = GeoJSON; -'use strict'; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$lib_165 = require('../../lib'); */; +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// -// look for either subplot or xaxis and yaxis attributes -_$helpers_85.getSubplot = function getSubplot(trace) { - return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } }; -// convenience functions for mapping all relevant axes -_$helpers_85.flat = function flat(subplots, v) { - var out = new Array(subplots.length); - for(var i = 0; i < subplots.length; i++) { - out[i] = v; - } - return out; -}; +var _$LinkedList_24 = LinkedList; -_$helpers_85.p2c = function p2c(axArray, v) { - var out = new Array(axArray.length); - for(var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); - } - return out; -}; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -_$helpers_85.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { - if(mode === 'closest') return dxy || _$helpers_85.quadrature(dx, dy); - return mode === 'x' ? dx : dy; -}; +// +// this is the core work-horse +// -_$helpers_85.getClosest = function getClosest(cd, distfn, pointData) { - // do we already have a point number? (array mode only) - if(pointData.index !== false) { - if(pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } - else pointData.index = false; - } - else { - // apply the distance function to each data point - // this is the longest loop... if this bogs down, we may need - // to create pre-sorted data (by x or y), not sure how to - // do this for 'closest' - for(var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if(newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } - } - } - return pointData; -}; +/* removed: var _$LinkedList_24 = require('./linked-list'); */; -/* - * pseudo-distance function for hover effects on areas: inside the region - * distance is finite (`passVal`), outside it's Infinity. - * - * @param {number} v0: signed difference between the current position and the left edge - * @param {number} v1: signed difference between the current position and the right edge - * @param {number} passVal: the value to return on success - */ -_$helpers_85.inbox = function inbox(v0, v1, passVal) { - return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; -}; +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm -_$helpers_85.quadrature = function quadrature(dx, dy) { - return function(di) { - var x = dx(di), - y = dy(di); - return Math.sqrt(x * x + y * y); - }; -}; + // + // segment creation + // -/** Fill event data point object for hover and selection. - * Invokes _module.eventData if present. - * - * N.B. note that point 'index' corresponds to input data array index - * whereas 'number' is its post-transform version. - * - * If the hovered/selected pt corresponds to an multiple input points - * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' - * are include in the event data. - * - * @param {object} pt - * @param {object} trace - * @param {object} cd - * @return {object} - */ -_$helpers_85.makeEventData = function makeEventData(pt, trace, cd) { - // hover uses 'index', select uses 'pointNumber' - var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber: pointNumber - }; + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } - if(trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; + // + // event logic + // - if(pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; - } + var event_root = _$LinkedList_24.create(); - if(trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if('xVal' in pt) out.x = pt.xVal; - else if('x' in pt) out.x = pt.x; + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same - if('yVal' in pt) out.y = pt.yVal; - else if('y' in pt) out.y = pt.y; + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - if(pt.xa) out.xaxis = pt.xa; - if(pt.ya) out.yaxis = pt.ya; - if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; - } + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start - _$helpers_85.appendArrayPointValue(out, trace, pointNumber); + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } - return out; -}; + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } -/** Appends values inside array attributes corresponding to given point number - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {number|Array(number)} pointNumber : point number. May be a length-2 array - * [row, col] to dig into 2D arrays - */ -_$helpers_85.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_24.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } - if(!arrayAttrs) { - return; - } + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_24.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } - if(pointData[key] === undefined) { - var val = _$lib_165.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) - if(pointVal !== undefined) pointData[key] = pointVal; - } - } -}; + if (buildLog) + buildLog.segmentChop(ev.seg, end); -/** - * Appends values inside array attributes corresponding to given point number array - * For use when pointData references a plot entity that arose (or potentially arose) - * from multiple points in the input data - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. - * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays - */ -_$helpers_85.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } - if(!arrayAttrs) { - return; - } + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used - if(pointData[key] === undefined) { - var val = _$lib_165.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); + // + // status logic + // - for(var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); - } - pointData[key] = keyVal; - } - } -}; + var status_root = _$LinkedList_24.create(); -var pointKeyMap = { - ids: 'id', - locations: 'location', - labels: 'label', - values: 'value', - 'marker.colors': 'color' -}; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; -function getPointKey(astr) { - return pointKeyMap[astr] || astr; -} + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } -function getPointData(val, pointNumber) { - if(Array.isArray(pointNumber)) { - if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; - } - } else { - return val[pointNumber]; - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } -// works with our CSS cursor classes (see css/_cursor.scss) -// to apply cursors to d3 single-element selections. -// omit cursor to revert to the default. -var _$setCursor_184 = function setCursor(el3, csr) { - (el3.attr('class') || '').split(' ').forEach(function(cls) { - if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); - }); + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal - if(csr) el3.classed('cursor-' + csr, true); -}; + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (buildLog) + buildLog.checkIntersection(seg1, seg2); + var i = eps.linesIntersect(a1, a2, b1, b2); -'use strict'; + if (i === false){ + // segments are parallel or coincident -/* removed: var _$setCursor_184 = require('./setcursor'); */; + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) -var STASHATTR = 'data-savedcursor'; -var NO_CURSOR = '!!'; + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection -/* - * works with our CSS cursor classes (see css/_cursor.scss) - * to override a previous cursor set on d3 single-element selections, - * by moving the name of the original cursor to the data-savedcursor attr. - * omit cursor to revert to the previously set value. - */ -var _$overrideCursor_176 = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if(csr) { - if(!savedCursor) { - var classes = (el3.attr('class') || '').split(' '); - for(var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if(cls.indexOf('cursor-') === 0) { - el3.attr(STASHATTR, cls.substr(7)) - .classed(cls, false); - } - } - if(!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); - } - } - _$setCursor_184(el3, csr); - } - else if(savedCursor) { - el3.attr(STASHATTR, null); + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); - if(savedCursor === NO_CURSOR) _$setCursor_184(el3); - else _$setCursor_184(el3, savedCursor); - } -}; + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal -var _$hover_86 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); -'use strict'; + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_28 = require('tinycolor2'); */; + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$Events_158 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_176 = require('../../lib/override_cursor'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_247 = require('../../registry'); */; + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints -/* removed: var _$helpers_85 = require('./helpers'); */; -/* removed: var _$constants_83 = require('./constants'); */; + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } -// hover labels for multiple horizontal bars get tilted by some angle, -// then need to be offset differently if they overlap -var YANGLE = _$constants_83.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } -// expansion of projected height -var YFACTOR = 1 / Math.sin(YA_RADIANS); + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); -// to make the appropriate post-rotation x offset, -// you need both x and y offsets -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); + if (buildLog) + buildLog.vert(ev.pt[0]); -// size and display constants for hover text -var HOVERARROWSIZE = _$constants_83.HOVERARROWSIZE; -var HOVERTEXTPAD = _$constants_83.HOVERTEXTPAD; + if (ev.isStart){ -// fx.hover: highlight data on hover -// evt can be a mousemove event, or an object with data about what points -// to hover on -// {xpx,ypx[,hovermode]} - pixel locations from top left -// (with optional overriding hovermode) -// {xval,yval[,hovermode]} - data values -// [{curveNumber,(pointNumber|xval and/or yval)}] - -// array of specific points to highlight -// pointNumber is a single integer if gd.data[curveNumber] is 1D, -// or a two-element array if it's 2D -// xval and yval are data values, -// 1D data may specify either or both, -// 2D data must specify both -// subplot is an id string (default "xy") -// makes use of gl.hovermode, which can be: -// x (find the points with the closest x values, ie a column), -// closest (find the single closest point) -// internally there are two more that occasionally get used: -// y (pick out a row - only used for multiple horizontal bar charts) -// array (used when the user specifies an explicit -// array of points to hover on) -// -// We wrap the hovers in a timer, to limit their frequency. -// The actual rendering is done by private function _hover. -_$hover_86.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_165.getGraphDiv(gd); + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); - _$lib_165.throttle( - gd._fullLayout._uid + _$constants_83.HOVERID, - _$constants_83.HOVERMINTIME, - function() { _hover(gd, evt, subplot, noHoverEvent); } - ); -}; + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; -/* - * Draw a single hover item in a pre-existing svg container somewhere - * hoverItem should have keys: - * - x and y (or x0, x1, y0, and y1): - * the pixel position to mark, relative to opts.container - * - xLabel, yLabel, zLabel, text, and name: - * info to go in the label - * - color: - * the background color for the label. - * - idealAlign (optional): - * 'left' or 'right' for which side of the x/y box to try to put this on first - * - borderColor (optional): - * color for the border, defaults to strongest contrast with color - * - fontFamily (optional): - * string, the font for this label, defaults to constants.HOVERFONT - * - fontSize (optional): - * the label font size, defaults to constants.HOVERFONTSIZE - * - fontColor (optional): - * defaults to borderColor - * opts should have keys: - * - bgColor: - * the background color this is against, used if the trace is - * non-opaque, and for the name, which goes outside the box - * - container: - * a or element to add the hover label to - * - outerContainer: - * normally a parent of `container`, sets the bounding box to use to - * constrain the hover label and determine whether to show it on the left or right - */ -_$hover_86.loneHover = function loneHover(hoverItem, opts) { - var pointData = { - color: hoverItem.color || _$color_46.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } - // filler to make createHoverText happy - trace: { - index: 0, - hoverinfo: '' - }, - xa: {_offset: 0}, - ya: {_offset: 0}, - index: 0 - }; + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev - var container3 = _$d3_10.select(opts.container), - outerContainer3 = opts.outerContainer ? - _$d3_10.select(opts.outerContainer) : container3; + // merge ev.seg's fill information into eve.seg - var fullOpts = { - hovermode: 'closest', - rotateLabels: false, - bgColor: opts.bgColor || _$color_46.background, - container: container3, - outerContainer: outerContainer3 - }; + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); - alignHoverText(hoverLabel, fullOpts.rotateLabels); + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } - return hoverLabel.node(); -}; + if (buildLog) + buildLog.segmentUpdate(eve.seg); -// The actual implementation is here: -function _hover(gd, evt, subplot, noHoverEvent) { - if(!subplot) subplot = 'xy'; + ev.other.remove(); + ev.remove(); + } - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } - var fullLayout = gd._fullLayout; - var plots = fullLayout._plots || []; - var plotinfo = plots[subplot]; - var hasCartesian = fullLayout._has('cartesian'); + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } - subplots = subplots.concat(overlayedSubplots); - } + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point - var len = subplots.length; - var xaArray = new Array(len); - var yaArray = new Array(len); - var supportsCompare = false; + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } - for(var i = 0; i < len; i++) { - var spId = subplots[i]; + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // 'cartesian' case - var plotObj = plots[spId]; - if(plotObj) { - supportsCompare = true; + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_24.node({ ev: ev })); + } + else{ + var st = ev.status; - // TODO make sure that fullLayout_plots axis refs - // get updated properly so that we don't have - // to use Axes.getFromId in general. + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } - xaArray[i] = _$axes_207.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_207.getFromId(gd, plotObj.yaxis._id); - continue; - } + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); - // other subplot types - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; - } + if (buildLog) + buildLog.statusRemove(st.ev.seg); - var hovermode = evt.hovermode || fullLayout.hovermode; + // remove the status + st.remove(); - if(hovermode && !supportsCompare) hovermode = 'closest'; + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } - if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || - gd.querySelector('.zoombox') || gd._dragging) { - return _$dragelement_68.unhoverRaw(gd, evt); - } + // remove the event and continue + event_root.getHead().remove(); + } - var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; - var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; + if (buildLog) + buildLog.done(); - // hoverData: the set of candidate points we've found to highlight - var hoverData = [], + return segments; + } - // searchData: the data to search in. Mostly this is just a copy of - // gd.calcdata, filtered to the subplot and overlays we're on - // but if a point array is supplied it will be a mapping - // of indicated curves - searchData = [], + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } - // [x|y]valArray: the axis values of the hover event - // mapped onto each of the currently selected overlaid subplots - xvalArray, - yvalArray, + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; - // used in loops - itemnum, - curvenum, - cd, - trace, - subplotId, - subploti, - mode, - xval, - yval, - pointData, - closedataPreviousLength, + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it - // spikePoints: the set of candidate points we've found to draw spikes to - spikePoints = { - hLinePoint: null, - vLinePoint: null - }; + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} - // Figure out what we're hovering on: - // mouse location or user-supplied data +var _$Intersecter_23 = Intersecter; - if(Array.isArray(evt)) { - // user specified an array of points to highlight - hovermode = 'array'; - for(itemnum = 0; itemnum < evt.length; itemnum++) { - cd = gd.calcdata[evt[itemnum].curveNumber||0]; - if(cd[0].trace.hoverinfo !== 'skip') { - searchData.push(cd); - } - } - } - else { - for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { - cd = gd.calcdata[curvenum]; - trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_85.getSubplot(trace)) !== -1) { - searchData.push(cd); - } - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // [x|y]px: the pixels (from top left) of the mouse location - // on the currently selected plot area - // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation - var hasUserCalledHover = !evt.target, - xpx, ypx; +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// - if(hasUserCalledHover) { - if('xpx' in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - evt.pointerX = xpx + xaArray[0]._offset; +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; - if('ypx' in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - evt.pointerY = ypx + yaArray[0]._offset; - } - else { - // fire the beforehover event and quit if it returns false - // note that we're only calling this on real mouse events, so - // manual calls to fx.hover will always run. - if(_$Events_158.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } - var dbb = evt.target.getBoundingClientRect(); + if (buildLog) + buildLog.chainStart(seg); - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } - // in case hover was called from mouseout into hovertext, - // it's possible you're not actually over the plot anymore - if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { - return _$dragelement_68.unhoverRaw(gd, evt); - } - evt.pointerX = evt.offsetX; - evt.pointerY = evt.offsetY; - } + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } - if('xval' in evt) xvalArray = _$helpers_85.flat(subplots, evt.xval); - else xvalArray = _$helpers_85.p2c(xaArray, xpx); + if (next_match === second_match){ + // we matched a single chain - if('yval' in evt) yvalArray = _$helpers_85.flat(subplots, evt.yval); - else yvalArray = _$helpers_85.p2c(yaArray, ypx); + if (buildLog) + buildLog.chainMatch(first_match.index); - if(!_$fastIsnumeric_13(xvalArray[0]) || !_$fastIsnumeric_13(yvalArray[0])) { - _$lib_165.warn('Fx.hover failed', evt, gd); - return _$dragelement_68.unhoverRaw(gd, evt); - } - } + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop - // the pixel distance to beat as a matching point - // in 'x' or 'y' mode this resets for each trace - var distance = Infinity; + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head - // find the closest point in each trace - // this is minimum dx and/or dy, depending on mode - // and the pixel position for the label (labelXpx, labelYpx) - for(curvenum = 0; curvenum < searchData.length; curvenum++) { - cd = searchData[curvenum]; + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - // filter out invisible or broken data - if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } - trace = cd[0].trace; + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); - // Explicitly bail out for these two. I don't know how to otherwise prevent - // the rest of this function from running and failing - if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } - subplotId = _$helpers_85.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if (buildLog) + buildLog.chainClose(first_match.index); - // within one trace mode can sometimes be overridden - mode = hovermode; + // we have a closed chain! + regions.push(chain); + return; + } - // container for new point, also used to pass info into module.hoverPoints - pointData = { - // trace properties - cd: cd, - trace: trace, - xa: xaArray[subploti], - ya: yaArray[subploti], + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } - // max distances for hover and spikes - for points that want to show but do not - // want to override other points, set distance/spikeDistance equal to max*Distance - // and it will not get filtered out but it will be guaranteed to have a greater - // distance than any point that calculated a real distance. - maxHoverDistance: hoverdistance, - maxSpikeDistance: spikedistance, + // otherwise, we matched two chains, so we need to combine those chains together - // point properties - override all of these - index: false, // point index in trace - only used by plotly.js hoverdata consumers - distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } - // distance/pseudo-distance for spikes. This distance should always be calculated - // as if in "closest" mode, and should only be set if this point should - // generate a spike. - spikeDistance: Infinity, + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; - // in some cases the spikes have different positioning from the hover label - // they don't need x0/x1, just one position - xSpike: undefined, - ySpike: undefined, + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } - // where and how to display the hover label - color: _$color_46.defaultLine, // trace color - name: trace.name, - x0: undefined, - x1: undefined, - y0: undefined, - y1: undefined, - xLabelVal: undefined, - yLabelVal: undefined, - zLabelVal: undefined, - text: undefined - }; + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } - // add ref to subplot object (non-cartesian case) - if(fullLayout[subplotId]) { - pointData.subplot = fullLayout[subplotId]._subplot; - } + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } - closedataPreviousLength = hoverData.length; + var F = first_match.index; + var S = second_match.index; - // for a highlighting array, figure out what - // we're searching for with this element - if(mode === 'array') { - var selection = evt[curvenum]; - if('pointNumber' in selection) { - pointData.index = selection.pointNumber; - mode = 'closest'; - } - else { - mode = ''; - if('xval' in selection) { - xval = selection.xval; - mode = 'x'; - } - if('yval' in selection) { - yval = selection.yval; - mode = mode ? 'closest' : 'y'; - } - } - } - else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; - } + if (buildLog) + buildLog.chainConnect(F, S); - // Now if there is range to look in, find the points to hover. - if(hoverdistance !== 0) { - if(trace._module && trace._module.hoverPoints) { - var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); - if(newPoints) { - var newPoint; - for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { - newPoint = newPoints[newPointNum]; - if(_$fastIsnumeric_13(newPoint.x0) && _$fastIsnumeric_13(newPoint.y0)) { - hoverData.push(cleanPoint(newPoint, hovermode)); - } - } - } - } - else { - _$lib_165.log('Unrecognized trace type in hover:', trace); - } - } + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); - // in closest mode, remove any existing (farther) points - // and don't look any farther than this latest point (or points, some - // traces like box & violin make multiple hover labels at once) - if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; - } + return regions; +} - // Now if there is range to look in, find the points to draw the spikelines - // Do it only if there is no hoverData - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length === 0) { - pointData.distance = spikedistance; - pointData.index = false; - var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); - if(closestPoints) { - closestPoints = closestPoints.filter(function(point) { - // some hover points, like scatter fills, do not allow spikes, - // so will generate a hover point but without a valid spikeDistance - return point.spikeDistance <= spikedistance; - }); - } - if(closestPoints && closestPoints.length) { - var tmpPoint; - var closestVPoints = closestPoints.filter(function(point) { - return point.xa.showspikes; - }); - if(closestVPoints.length) { - var closestVPt = closestVPoints[0]; - if(_$fastIsnumeric_13(closestVPt.x0) && _$fastIsnumeric_13(closestVPt.y0)) { - tmpPoint = fillSpikePoint(closestVPt); - if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.vLinePoint = tmpPoint; - } - } - } +var _$SegmentChainer_25 = SegmentChainer; - var closestHPoints = closestPoints.filter(function(point) { - return point.ya.showspikes; - }); - if(closestHPoints.length) { - var closestHPt = closestHPoints[0]; - if(_$fastIsnumeric_13(closestHPt.x0) && _$fastIsnumeric_13(closestHPt.y0)) { - tmpPoint = fillSpikePoint(closestHPt); - if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } - } - } - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - function selectClosestPoint(pointsData, spikedistance) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for(var i = 0; i < pointsData.length; i++) { - thisSpikeDistance = pointsData[i].spikeDistance; - if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { - resultPoint = pointsData[i]; - minDistance = thisSpikeDistance; - } - } - return resultPoint; - } +// +// filter a list of segments based on boolean operations +// - function fillSpikePoint(point) { - if(!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; - } +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); - var spikelineOpts = { - fullLayout: fullLayout, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - event: evt - }; - var oldspikepoints = gd._spikepoints, - newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; + if (buildLog) + buildLog.selected(result); - // Now if it is not restricted by spikedistance option, set the points to draw the spikelines - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); + return result; +} - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); - } - } +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; - // if hoverData is empty check for the spikes to draw and quit if there are none - if(hoverData.length === 0) { - var result = _$dragelement_68.unhoverRaw(gd, evt); - if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } - return result; - } +var _$SegmentSelector_26 = SegmentSelector; - if(hasCartesian) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ - hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); +/* removed: var _$BuildLog_20 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_21 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_23 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_25 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_26 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_22 = require('./lib/geojson'); */; - // lastly, emit custom hover/unhover events - var oldhoverdata = gd._hoverdata, - newhoverdata = []; +var buildLog = false; +var epsilon = _$Epsilon_21(); - // pull out just the data that's useful to - // other people and send it to the event - for(itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - newhoverdata.push(_$helpers_85.makeEventData(pt, pt.trace, pt.cd)); - } +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_20(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v){ + return epsilon.epsilon(v); + }, - gd._hoverdata = newhoverdata; + // core API + segments: function(poly){ + var i = _$Intersecter_23(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_23(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_26.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_26.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_26.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_26.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_26.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_25(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, - // if there's more than one horz bar trace, - // rotate the labels so they don't overlap - var rotateLabels = hovermode === 'y' && searchData.length > 1; + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_22.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_22.fromPolygon(PolyBool, epsilon, poly); + }, - var bgColor = _$color_46.combine( - fullLayout.plot_bgcolor || _$color_46.background, - fullLayout.paper_bgcolor - ); + // 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); + } +}; - var labelOpts = { - hovermode: hovermode, - rotateLabels: rotateLabels, - bgColor: bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }; +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); +} - var hoverLabels = createHoverText(hoverData, labelOpts, gd); +if (typeof window === 'object') + window.PolyBool = PolyBool; - hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); +var _$PolyBool_19 = PolyBool; - alignHoverText(hoverLabels, rotateLabels); +var _$polygon_178 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true - // we should improve the "fx" API so other plots can use it without these hack. - if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_247.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_176(_$d3_10.select(evt.target), hasClickToShow ? 'pointer' : ''); - } - // don't emit events if called manually - if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; +'use strict'; - if(oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } +var dot = _$matrix_172.dot; +var __BADNUM_178 = _$numerical_148.BADNUM; - gd.emit('plotly_hover', { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); -} +var polygon = _$polygon_178 = {}; -function createHoverText(hoverData, opts, gd) { - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - // opts.fontFamily/Size are used for the common label - // and as defaults for each hover label, though the individual labels - // can override this. - var fontFamily = opts.fontFamily || _$constants_83.HOVERFONT; - var fontSize = opts.fontSize || _$constants_83.HOVERFONTSIZE; + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; - var t0 = c0[commonAttr]; - var t00 = (String(t0) || '').split(' ')[0]; - var outerContainerBB = outerContainer.node().getBoundingClientRect(); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); + } - // show the common label, if any, on the axis - // never show a common label in array mode, - // even if sometimes there could be one - var showCommonLabel = ( - (t0 !== undefined) && - (c0.distance <= opts.hoverdistance) && - (hovermode === 'x' || hovermode === 'y') - ); + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed - // all hover traces hoverinfo must contain the hovermode - // to have common labels - if(showCommonLabel) { - var i, traceHoverinfo; - var allHaveZ = true; - for(i = 0; i < hoverData.length; i++) { - if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + var isRect = false, + rectFirstEdgeTest; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); - if(parts.indexOf('all') === -1 && - parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; } } - - // xyz labels put all info in their main label, so have no need of a common label - if(allHaveZ) showCommonLabel = false; } - var commonLabel = container.selectAll('g.axistext') - .data(showCommonLabel ? [0] : []); - commonLabel.enter().append('g') - .classed('axistext', true); - commonLabel.exit().remove(); + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - commonLabel.each(function() { - var label = _$d3_10.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); + if(x === __BADNUM_178 || x < xmin || x > xmax || y === __BADNUM_178 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; - lpath.enter().append('path') - .style({'stroke-width': '1px'}); + return true; + } - lpath.style({ - fill: commonLabelOpts.bgcolor || _$color_46.defaultLine, - stroke: commonLabelOpts.bordercolor || _$color_46.background, - }); + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); + if(x === __BADNUM_178 || x < xmin || x > xmax || y === __BADNUM_178 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } - ltext.text(t0) - .call(_$drawing_71.font, - commonLabelOpts.font.family || fontFamily, - commonLabelOpts.font.size || fontSize, - commonLabelOpts.font.color || _$color_46.background - ) - .call(_$svg_text_utils_186.positionText, 0, 0) - .call(_$svg_text_utils_186.convertToTspans, gd); + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; - label.attr('transform', ''); + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); - var tbb = ltext.node().getBoundingClientRect(); - if(hovermode === 'x') { - ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_186.positionText, 0, (xa.side === 'top' ? - (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : - (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - var topsign = xa.side === 'top' ? '-' : ''; - lpath.attr('d', 'M0,0' + - 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + - 'H' + (HOVERTEXTPAD + tbb.width / 2) + - 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + - 'H-' + (HOVERTEXTPAD + tbb.width / 2) + - 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } - label.attr('transform', 'translate(' + - (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + - (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + if(y <= ycross && x !== xmini) crossings++; + } } - else { - ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_186.positionText, - (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), - outerTop - tbb.top - tbb.height / 2); - var leftsign = ya.side === 'right' ? '' : '-'; - lpath.attr('d', 'M0,0' + - 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + - 'V' + (HOVERTEXTPAD + tbb.height / 2) + - 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + - 'V-' + (HOVERTEXTPAD + tbb.height / 2) + - 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; + } - label.attr('transform', 'translate(' + - (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + - (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; } - // remove the "close but not quite" points - // because of error bars, only take up to a space - hoverData = hoverData.filter(function(d) { - return (d.zLabelVal !== undefined) || - (d[commonAttr] || '').split(' ')[0] === t00; - }); - }); + } - // show all the individual labels + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; +}; - // first create the objects - var hoverLabels = container.selectAll('g.hovertext') - .data(hoverData, function(d) { - return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); - }); - hoverLabels.enter().append('g') - .classed('hovertext', true) - .each(function() { - var g = _$d3_10.select(this); - // trace name label (rect and text.name) - g.append('rect') - .call(_$color_46.fill, _$color_46.addOpacity(bgColor, 0.8)); - g.append('text').classed('name', true); - // trace data label (path and text.nums) - g.append('path') - .style('stroke-width', '1px'); - g.append('text').classed('nums', true) - .call(_$drawing_71.font, fontFamily, fontSize); - }); - hoverLabels.exit().remove(); +/** + * Test multiple polygons + */ +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; - // then put the text in, position the pointer to the data, - // and figure out sizes - hoverLabels.each(function(d) { - var g = _$d3_10.select(this).attr('transform', ''), - name = '', - text = ''; + for(var i = 0; i < list.length; i++) { + 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); + } - // combine possible non-opaque trace color with bgColor - var baseColor = _$color_46.opacity(d.color) ? d.color : _$color_46.defaultLine; - var traceColor = _$color_46.combine(baseColor, bgColor); + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } - // find a contrasting color for border and text - var contrastColor = d.borderColor || _$color_46.contrast(traceColor); + return yes; + } - // to get custom 'name' labels pass cleanPoint - if(d.nameOverride !== undefined) d.name = d.nameOverride; + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; +}; - if(d.name) { - // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_186.plainText(d.name || ''); +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; - var nameLength = Math.round(d.nameLength); + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); - if(nameLength > -1 && name.length > nameLength) { - if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; - else name = name.substr(0, nameLength); - } - } + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; + } + return false; +}; - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; +/** + * Make a filtering polygon, to minimize the number of segments + * + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon + * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs + */ +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; - if(d.zLabel !== undefined) { - if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; - if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; - text += (text ? 'z: ' : '') + d.zLabel; - } - else if(showCommonLabel && d[hovermode + 'Label'] === t0) { - text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; - } - else if(d.xLabel === undefined) { - if(d.yLabel !== undefined) text = d.yLabel; - } - else if(d.yLabel === undefined) text = d.xLabel; - else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); - if(d.text && !Array.isArray(d.text)) { - text += (text ? '
' : '') + d.text; + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } } + } - // if 'text' is empty at this point, - // put 'name' in main label and don't show secondary label - if(text === '') { - // if 'name' is also empty, remove entire label - if(name === '') g.remove(); - text = name; - } + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } - // main label - var tx = g.select('text.nums') - .call(_$drawing_71.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - d.fontColor || contrastColor) - .text(text) - .attr('data-notex', 1) - .call(_$svg_text_utils_186.positionText, 0, 0) - .call(_$svg_text_utils_186.convertToTspans, gd); + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; +}; - var tx2 = g.select('text.name'), - tx2width = 0; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // secondary label for non-empty 'name' - if(name && name !== text) { - tx2.call(_$drawing_71.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - traceColor) - .text(name) - .attr('data-notex', 1) - .call(_$svg_text_utils_186.positionText, 0, 0) - .call(_$svg_text_utils_186.convertToTspans, gd); - tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; - } - else { - tx2.remove(); - g.select('rect').remove(); - } - g.select('path') - .style({ - fill: traceColor, - stroke: contrastColor - }); - var tbb = tx.node().getBoundingClientRect(), - htx = d.xa._offset + (d.x0 + d.x1) / 2, - hty = d.ya._offset + (d.y0 + d.y1) / 2, - dx = Math.abs(d.x1 - d.x0), - dy = Math.abs(d.y1 - d.y0), - txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, - anchorStartOK, - anchorEndOK; +'use strict'; - d.ty0 = outerTop - tbb.top; - d.bx = tbb.width + 2 * HOVERTEXTPAD; - d.by = tbb.height + 2 * HOVERTEXTPAD; - d.anchor = 'start'; - d.txwidth = tbb.width; - d.tx2width = tx2width; - d.offset = 0; +/* removed: var _$PolyBool_19 = require('polybooljs'); */; - if(rotateLabels) { - d.pos = htx; - anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; - anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - hty += dy / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } - else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - htx += dx / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$fx_88 = require('../../components/fx'); */; - tx.attr('text-anchor', d.anchor); - if(tx2width) tx2.attr('text-anchor', d.anchor); - g.attr('transform', 'translate(' + htx + ',' + hty + ')' + - (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); - }); +/* removed: var _$polygon_178 = require('../../lib/polygon'); */; +/* removed: var _$throttle_188 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_85.makeEventData; +var getFromId = _$axis_ids_211.getFromId; +var __sortModules_225 = _$sort_modules_247.sortModules; - return hoverLabels; -} +/* removed: var _$constants_213 = require('./constants'); */; +var MINSELECT = _$constants_213.MINSELECT; -// Make groups of touching points, and within each group -// move each point so that no labels overlap, but the average -// label position is the same as it was before moving. Indicentally, -// this is equivalent to saying all the labels are on equal linear -// springs about their initial position. Initially, each point is -// its own group, but as we find overlaps we will clump the points. -// -// Also, there are hard constraints at the edges of the graphs, -// that push all groups to the middle so they are visible. I don't -// know what happens if the group spans all the way from one edge to -// the other, though it hardly matters - there's just too much -// information then. -function hoverAvoidOverlaps(hoverData, ax, fullLayout) { - var nummoves = 0, +var filteredPolygon = _$polygon_178.filter; +var polygonTester = _$polygon_178.tester; +var multipolygonTester = _$polygon_178.multitester; - // make groups of touching points - pointgroups = hoverData - .map(function(d, i) { - var axis = d[ax]; - return [{ - i: i, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, - pmin: 0, - pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) - }]; - }) - .sort(function(a, b) { return a[0].posref - b[0].posref; }), - donepositioning, - topOverlap, - bottomOverlap, - i, j, - pti, - sumdp; +function getAxId(ax) { return ax._id; } - function constrainGroup(grp) { - var minPt = grp[0], - maxPt = grp[grp.length - 1]; +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; - // overlap with the top - positive vals are overlaps - topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); - // overlap with the bottom - positive vals are overlaps - bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + } - // check for min overlap first, so that we always - // see the largest labels - // allow for .01px overlap, so we don't get an - // infinite loop from rounding errors - if(topOverlap > 0.01) { - for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; - donepositioning = false; - } - if(bottomOverlap < 0.01) return; - if(topOverlap < -0.01) { - // make sure we're not pushing back and forth - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - donepositioning = false; - } - if(!donepositioning) return; + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } - // no room to fix positioning, delete off-screen points + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_213.BENDPX); + } - // first see how many points we need to delete - var deleteCount = 0; - for(i = 0; i < grp.length; i++) { - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; - } + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); - // start by deleting points whose data is off screen - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; + 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'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; - } - } - for(i = 0; i < grp.length; i++) { - if(deleteCount <= 0) break; - pti = grp[i]; + var corners = zoomLayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_46.background, + stroke: _$color_46.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; - // shift the whole group minus into this new space - bottomOverlap = pti.size * 2; - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - } - } - // then delete points that go off the bottom - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; - } - } - } + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_213.SELECTID; + var selection = []; - // loop through groups, combining them if they overlap, - // until nothing moves - while(!donepositioning && nummoves <= hoverData.length) { - // to avoid infinite loops, don't move more times - // than there are traces - nummoves++; + for(i = 0; i < gd.calcdata.length; i++) { + cd = gd.calcdata[i]; + trace = cd[0].trace; - // assume nothing will move in this iteration, - // reverse this if it does - donepositioning = true; - i = 0; - while(i < pointgroups.length - 1) { - // the higher (g0) and lower (g1) point group - var g0 = pointgroups[i], - g1 = pointgroups[i + 1], + if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; - // the lowest point in the higher group (p0) - // the highest point in the lower group (p1) - p0 = g0[g0.length - 1], - p1 = g1[0]; - topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; - - // Only group points that lie on the same axes - if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { - // push the new point(s) added to this group out of the way - for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; - - // add them to the group - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); - - // adjust for minimum average movement - sumdp = 0; - for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; + if(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); } - else i++; - } - - // check if we're going off the plot on either side and fix - pointgroups.forEach(constrainGroup); - } + } 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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; - // now put these offsets into hoverData - for(i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for(j = grp.length - 1; j >= 0; j--) { - var pt = grp[j], - hoverPt = hoverData[pt.i]; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); } } -} -function alignHoverText(hoverLabels, rotateLabels) { - // finally set the text positioning relative to the data and draw the - // box around it - hoverLabels.each(function(d) { - var g = _$d3_10.select(this); - if(d.del) { - g.remove(); - return; - } - var horzSign = d.anchor === 'end' ? -1 : 1, - tx = g.select('text.nums'), - alignShift = {start: 1, end: -1, middle: 0}[d.anchor], - txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), - tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), - offsetX = 0, - offsetY = d.offset; - if(d.anchor === 'middle') { - txx -= d.tx2width / 2; - tx2x += d.txwidth / 2 + HOVERTEXTPAD; - } - if(rotateLabels) { - offsetY *= -YSHIFTY; - offsetX = d.offset * YSHIFTX; - } + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(v[index]); }; + } - g.select('path').attr('d', d.anchor === 'middle' ? - // middle aligned: rect centered on data - ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + - 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : - // left or right aligned: side rect with arrow to data - ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + - 'v' + (d.by / 2 - HOVERARROWSIZE) + - 'h' + (horzSign * d.bx) + - 'v-' + d.by + - 'H' + (horzSign * HOVERARROWSIZE + offsetX) + - 'V' + (offsetY - HOVERARROWSIZE) + - 'Z')); + function ascending(a, b) { return a - b; } - tx.call(_$svg_text_utils_186.positionText, - txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + // allow subplots to override fillRangeItems routine + var fillRangeItems; - if(d.tx2width) { - g.select('text.name') - .call(_$svg_text_utils_186.positionText, - tx2x + alignShift * HOVERTEXTPAD + offsetX, - offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); - g.select('rect') - .call(_$drawing_71.setRect, - tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, - offsetY - d.by / 2 - 1, - d.tx2width, d.by + 2); - } - }); -} + if(plotinfo.fillRangeItems) { + fillRangeItems = plotinfo.fillRangeItems; + } else { + if(mode === 'select') { + fillRangeItems = function(eventData, poly) { + var ranges = eventData.range = {}; -function cleanPoint(d, hovermode) { - var index = d.index; - var trace = d.trace || {}; - var cd0 = d.cd[0]; - var cd = d.cd[index] || {}; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + var axLetter = ax._id.charAt(0); - var getVal = Array.isArray(index) ? - function(calcKey, traceKey) { - return _$lib_165.castOption(cd0, index, calcKey) || - _$lib_165.extractOption({}, trace, '', traceKey); - } : - function(calcKey, traceKey) { - return _$lib_165.extractOption(cd, trace, calcKey, traceKey); - }; + ranges[ax._id] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(poly[axLetter + 'max']) + ].sort(ascending); + } + }; + } else { + fillRangeItems = function(eventData, poly, filterPoly) { + var dataPts = eventData.lassoPoints = {}; - function fill(key, calcKey, traceKey) { - var val = getVal(calcKey, traceKey); - if(val) d[key] = val; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); + } + }; + } } - fill('hoverinfo', 'hi', 'hoverinfo'); - fill('color', 'hbg', 'hoverlabel.bgcolor'); - fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); - fill('fontFamily', 'htf', 'hoverlabel.font.family'); - fill('fontSize', 'hts', 'hoverlabel.font.size'); - fill('fontColor', 'htc', 'hoverlabel.font.color'); - fill('nameLength', 'hnl', 'hoverlabel.namelength'); + dragOptions.moveFn = function(dx0, dy0) { + x1 = Math.max(0, Math.min(pw, dx0 + x0)); + y1 = Math.max(0, Math.min(ph, dy0 + y0)); - d.posref = hovermode === 'y' ? - (d.xa._offset + (d.x0 + d.x1) / 2) : - (d.ya._offset + (d.y0 + d.y1) / 2); + var dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - // then constrain all the positions to be on the plot - d.x0 = _$lib_165.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_165.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_165.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_165.constrain(d.y1, 0, d.ya._length); + if(mode === 'select') { + var direction = fullLayout.selectdirection; - // and convert the x and y label values into formatted text - if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_207.hoverLabelText(d.xa, d.xLabelVal); - d.xVal = d.xa.c2d(d.xLabelVal); - } - if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_207.hoverLabelText(d.ya, d.yLabelVal); - d.yVal = d.ya.c2d(d.yLabelVal); - } + 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; + } - // Traces like heatmaps generate the zLabel in their hoverPoints function - if(d.zLabelVal !== undefined && d.zLabel === undefined) { - d.zLabel = String(d.zLabelVal); - } + 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'); - // for box means and error bars, add the range to the label - if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_207.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; - if(d.xerrneg !== undefined) { - d.xLabel += ' +' + xeText + ' / -' + - _$axes_207.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + 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 d.xLabel += ' ± ' + xeText; - - // small distance penalty for error bars, so that if there are - // traces with errors and some without, the error bar label will - // hoist up to the point - if(hovermode === 'x') d.distance += 1; - } - if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_207.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; - if(d.yerrneg !== undefined) { - d.yLabel += ' +' + yeText + ' / -' + - _$axes_207.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + else if(mode === 'lasso') { + filterPoly.addPt([x1, y1]); + currentPolygon = filterPoly.filtered; } - else d.yLabel += ' ± ' + yeText; - - if(hovermode === 'y') d.distance += 1; - } - var infomode = d.hoverinfo || d.trace.hoverinfo; + // create outline & tester + if(dragOptions.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } - if(infomode !== 'all') { - infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); - if(infomode.indexOf('x') === -1) d.xLabel = undefined; - if(infomode.indexOf('y') === -1) d.yLabel = undefined; - if(infomode.indexOf('z') === -1) d.zLabel = undefined; - if(infomode.indexOf('text') === -1) d.text = undefined; - if(infomode.indexOf('name') === -1) d.name = undefined; - } + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); + } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); - return d; -} + _$throttle_188.throttle( + throttleID, + _$constants_213.SELECTDELAY, + function() { + selection = []; -function createSpikelines(closestPoints, opts) { - var container = opts.container; - var fullLayout = opts.fullLayout; - var evt = opts.event; - var xa, - ya; + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - var showY = !!closestPoints.hLinePoint; - var showX = !!closestPoints.vLinePoint; + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + traceSelections.push(traceSelection); - // Remove old spikeline items - container.selectAll('.spikeline').remove(); + thisSelection = fillSelectionItem(traceSelection, searchInfo); - if(!(showX || showY)) return; + if(selection.length) { + for(var j = 0; j < thisSelection.length; j++) { + selection.push(thisSelection[j]); + } + } + else selection = thisSelection; + } - var contrastColor = _$color_46.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + eventData = {points: selection}; + updateSelectedState(gd, searchTraces, eventData); + fillRangeItems(eventData, currentPolygon, filterPoly); + dragOptions.gd.emit('plotly_selecting', eventData); + } + ); + }; - // Horizontal line (to y-axis) - if(showY) { - var hLinePoint = closestPoints.hLinePoint, - hLinePointX, - hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; + dragOptions.clickFn = function(numClicks, evt) { + corners.remove(); - if(ySnap === 'cursor') { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; - } - var dfltHLineColor = _$tinycolor_28.readability(hLinePoint.color, contrastColor) < 1.5 ? - _$color_46.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode, - yThickness = ya.spikethickness, - yColor = ya.spikecolor || dfltHLineColor, - yBB = ya._boundingBox, - xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, - xBase, - xEndSpike; + _$throttle_188.done(throttleID).then(function() { + _$throttle_188.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); + } - if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { - if(yMode.indexOf('toaxis') !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; + updateSelectedState(gd, searchTraces); + gd.emit('plotly_deselect', null); } - if(yMode.indexOf('across') !== -1) { - xBase = ya._counterSpan[0]; - xEndSpike = ya._counterSpan[1]; + else { + // 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. + gd.emit('plotly_selected', undefined); } - // Foreground horizontal line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness, - 'stroke': yColor, - 'stroke-dasharray': _$drawing_71.dashStyle(ya.spikedash, yThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + _$fx_88.click(gd, evt); + }); + }; - // Background horizontal Line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } - // Y axis marker - if(yMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), - 'cy': hLinePointY, - 'r': yThickness, - 'fill': yColor - }) - .classed('spikeline', true); - } - } + dragOptions.doneFn = function() { + corners.remove(); - if(showX) { - var vLinePoint = closestPoints.vLinePoint, - vLinePointX, - vLinePointY; + _$throttle_188.done(throttleID).then(function() { + _$throttle_188.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); - if(xSnap === 'cursor') { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} + +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; + + if(eventData) { + var pts = eventData.points || []; + + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.selectedpoints = []; } - var dfltVLineColor = _$tinycolor_28.readability(vLinePoint.color, contrastColor) < 1.5 ? - _$color_46.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode, - xThickness = xa.spikethickness, - xColor = xa.spikecolor || dfltVLineColor, - xBB = xa._boundingBox, - yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, - yBase, - yEndSpike; - if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { - if(xMode.indexOf('toaxis') !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if(xMode.indexOf('across') !== -1) { - yBase = xa._counterSpan[0]; - yEndSpike = xa._counterSpan[1]; + 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); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + 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; + } + } - // Foreground vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness, - 'stroke': xColor, - 'stroke-dasharray': _$drawing_71.dashStyle(xa.spikedash, xThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + // group searchInfo traces by trace modules + var lookup = {}; - // Background vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - // X axis marker - if(xMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': vLinePointX, - 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), - 'r': xThickness, - 'fill': xColor - }) - .classed('spikeline', true); + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; } } -} -function hoverChanged(gd, evt, oldhoverdata) { - // don't emit any events if nothing changed - if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + var keys = Object.keys(lookup).sort(__sortModules_225); - for(var i = oldhoverdata.length - 1; i >= 0; i--) { - var oldPt = oldhoverdata[i], - newPt = gd._hoverdata[i]; - if(oldPt.curveNumber !== newPt.curveNumber || - String(oldPt.pointNumber) !== String(newPt.pointNumber)) { - return true; + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_248.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } } } - return false; } -function spikesChanged(gd, oldspikepoints) { - // don't relayout the plot because of new spikelines if spikelines points didn't change - if(!oldspikepoints) return true; - if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || - oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint - ) return true; - return false; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function mergePolygons(list, poly, subtract) { + var res; -'use strict'; + if(subtract) { + res = _$PolyBool_19.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); -/* removed: var _$registry_247 = require('../../registry'); */; -var hover = _$hover_86.hover; + return res.regions; + } -var _$click_82 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_247.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); + res = _$PolyBool_19.union({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); - // 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); - } + return res.regions; +} - function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } +function fillSelectionItem(selection, searchInfo) { + if(Array.isArray(selection)) { + var cd = searchInfo.cd; + var trace = searchInfo.cd[0].trace; - if(gd._hoverdata && evt && evt.target) { - if(annotationsDone && annotationsDone.then) { - annotationsDone.then(emitClick); + for(var i = 0; i < selection.length; i++) { + selection[i] = makeEventData(selection[i], trace, cd); } - else emitClick(); - - // why do we get a double event without this??? - if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; - -/* removed: var _$lib_165 = require('../../lib'); */; + return selection; +} -var _$handleHoverLabelDefaults_87 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { - opts = opts || {}; +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); +} - coerce('hoverlabel.bgcolor', opts.bgcolor); - coerce('hoverlabel.bordercolor', opts.bordercolor); - coerce('hoverlabel.namelength', opts.namelength); - _$lib_165.coerceFont(coerce, 'hoverlabel.font', opts.font); +var _$select_225 = { + prepSelect: prepSelect, + clearSelect: clearSelect }; /** @@ -33626,1093 +34205,1414 @@ var _$handleHoverLabelDefaults_87 = function handleHoverLabelDefaults(contIn, co * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$attributes_80 = require('./attributes'); */; -/* removed: var _$handleHoverLabelDefaults_87 = require('./hoverlabel_defaults'); */; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$tinycolor_28 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_16 = require('has-passive-events'); */; -var _$supplyDefaults_84 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_80, attr, dflt); - } +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_155 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$fx_88 = require('../../components/fx'); */; +/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_68 = require('../../components/dragelement'); */; +var FROM_TL = _$alignment_146.FROM_TL; - _$handleHoverLabelDefaults_87(traceIn, traceOut, coerce, layout.hoverlabel); -}; +/* removed: var _$plots_240 = require('../plots'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 doTicks = _$axes_208.doTicks; +var __getFromId_216 = _$axis_ids_211.getFromId; +var __prepSelect_216 = _$select_225.prepSelect; +var __clearSelect_216 = _$select_225.clearSelect; +/* removed: var _$scaleZoom_224 = require('./scale_zoom'); */; -'use strict'; +/* removed: var _$constants_213 = require('./constants'); */; +var MINDRAG = _$constants_213.MINDRAG; +var MINZOOM = _$constants_213.MINZOOM; -/* removed: var _$constants_83 = require('./constants'); */; -var __fontAttrs_89 = _$font_attributes_234({ - editType: 'none', - -}); -__fontAttrs_89.family.dflt = _$constants_83.HOVERFONT; -__fontAttrs_89.size.dflt = _$constants_83.HOVERFONTSIZE; +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; -var _$layout_attributes_89 = { - dragmode: { - valType: 'enumerated', - - values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], - dflt: 'zoom', - editType: 'modebar', - - }, - hovermode: { - valType: 'enumerated', - - values: ['x', 'y', 'closest', false], - editType: 'modebar', - - }, - hoverdistance: { - valType: 'integer', - min: -1, - dflt: 20, - - editType: 'none', - - }, - spikedistance: { - valType: 'integer', - min: -1, - dflt: 20, - - editType: 'none', - - }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'none', - - }, - bordercolor: { - valType: 'color', - - editType: 'none', - - }, - font: __fontAttrs_89, - namelength: { - valType: 'integer', - min: -1, - dflt: 15, - - editType: 'none', - - }, - editType: 'none' - } -}; +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; -'use strict'; + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$layout_attributes_89 = require('./layout_attributes'); */; + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; -var _$supplyLayoutDefaults_90 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_165.coerce(layoutIn, layoutOut, _$layout_attributes_89, attr, dflt); - } + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } - coerce('dragmode'); + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; - var hovermodeDflt; - if(layoutOut._has('cartesian')) { - // flag for 'horizontal' plots: - // determines the state of the mode bar 'compare' hovermode button - layoutOut._isHoriz = isHoriz(fullData); - hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; } - else hovermodeDflt = 'closest'; - var hoverMode = coerce('hovermode', hovermodeDflt); - if(hoverMode) { - coerce('hoverdistance'); - coerce('spikedistance'); - } + recomputeAxisLists(); - // if only mapbox or geo subplots is present on graph, - // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, - // so that the correct modebar button is active - var hasMapbox = layoutOut._has('mapbox'); - var hasGeo = layoutOut._has('geo'); - var len = layoutOut._basePlotModules.length; + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - if(layoutOut.dragmode === 'zoom' && ( - ((hasMapbox || hasGeo) && len === 1) || - (hasMapbox && hasGeo && len === 2) - )) { - layoutOut.dragmode = 'pan'; + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; } -}; - -function isHoriz(fullData) { - var out = true; - - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(trace.orientation !== 'h') { - out = false; - break; - } - } + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; - return out; -} + recomputeAxisLists(); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } -'use strict'; + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$handleHoverLabelDefaults_87 = require('./hoverlabel_defaults'); */; -/* removed: var _$layout_attributes_89 = require('./layout_attributes'); */; + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_216(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_216(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; -var _$supplyLayoutGlobalDefaults_91 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { - function coerce(attr, dflt) { - return _$lib_165.coerce(layoutIn, layoutOut, _$layout_attributes_89, attr, dflt); - } + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; - _$handleHoverLabelDefaults_87(layoutIn, layoutOut, coerce); -}; + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_216(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(numClicks === 2 && !singleEnd) doubleClick(); -'use strict'; + if(isMainDrag) { + _$fx_88.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$helpers_85 = require('./helpers'); */; -/* removed: var _$layout_attributes_89 = require('./layout_attributes'); */; + if(ax.fixedrange) return; -var _$fx_88 = { - moduleType: 'component', - name: 'fx', + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; - constants: _$constants_83, - schema: { - layout: _$layout_attributes_89 - }, + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_10.select(dragger) + .call(_$svg_text_utils_187.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_248.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; - attributes: _$attributes_80, - layoutAttributes: _$layout_attributes_89, + _$dragelement_68.init(dragOptions); - supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_91, - supplyDefaults: _$supplyDefaults_84, - supplyLayoutDefaults: _$supplyLayoutDefaults_90, + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; - calc: _$calc_81, + // collected changes to be made to the plot by relayout at the end + var updates = {}; - getDistanceFunction: _$helpers_85.getDistanceFunction, - getClosest: _$helpers_85.getClosest, - inbox: _$helpers_85.inbox, - quadrature: _$helpers_85.quadrature, - appendArrayPointValue: _$helpers_85.appendArrayPointValue, + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_28(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; - castHoverOption: castHoverOption, - castHoverinfo: castHoverinfo, + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - hover: _$hover_86.hover, - unhover: _$dragelement_68.unhover, + corners = makeCorners(zoomlayer, xs, ys); - loneHover: _$hover_86.loneHover, - loneUnhover: loneUnhover, + __clearSelect_216(zoomlayer); + } - click: _$click_82 -}; + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } -function loneUnhover(containerOrSelection) { - // duck type whether the arg is a d3 selection because ie9 doesn't - // handle instanceof like modern browsers do. - var selection = _$lib_165.isD3Selection(containerOrSelection) ? - containerOrSelection : - _$d3_10.select(containerOrSelection); + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - selection.selectAll('g.hovertext').remove(); - selection.selectAll('.spikeline').remove(); -} + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); -// helpers for traces that use Fx.loneHover + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); + } -function castHoverOption(trace, ptNumber, attr) { - return _$lib_165.castOption(trace, ptNumber, 'hoverlabel.' + attr); -} + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; -function castHoverinfo(trace, fullLayout, ptNumber) { - function _coerce(val) { - return _$lib_165.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; } - return _$lib_165.castOption(trace, ptNumber, 'hoverinfo', _coerce); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } -'use strict'; + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } -/* removed: var _$lib_165 = require('../../lib'); */; + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } -/** Fill hover 'pointData' container with 'correct' hover text value - * - * - If trace hoverinfo contains a 'text' flag and hovertext is not set, - * the text elements will be seen in the hover labels. - * - * - If trace hoverinfo contains a 'text' flag and hovertext is set, - * hovertext takes precedence over text - * i.e. the hoverinfo elements will be seen in the hover labels - * - * @param {object} calcPt - * @param {object} trace - * @param {object || array} contOut (mutated here) - */ -var _$fillHoverText_325 = function fillHoverText(calcPt, trace, contOut) { - var fill = Array.isArray(contOut) ? - function(v) { contOut.push(v); } : - function(v) { contOut.text = v; }; + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_213.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - var htx = _$lib_165.extractOption(calcPt, trace, 'htx', 'hovertext'); - if(isValid(htx)) return fill(htx); + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } - var tx = _$lib_165.extractOption(calcPt, trace, 'tx', 'text'); - if(isValid(tx)) return fill(tx); -}; + if(redrawTimer === null) { + __clearSelect_216(zoomlayer); + } -// accept all truthy values and 0 (which gets cast to '0' in the hover labels) -function isValid(v) { - return v || v === 0; -} + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 pc = gd.querySelector('.plotly'); + recomputeAxisLists(); -'use strict'; + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } -/* removed: var _$fx_88 = require('../../components/fx'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$fillHoverText_325 = require('../scatter/fill_hover_text'); */; + clearTimeout(redrawTimer); -var _$hoverPoints_260 = function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - var t = cd[0].t; - var isClosest = (hovermode === 'closest'); - var maxHoverDistance = pointData.maxHoverDistance; - var maxSpikeDistance = pointData.maxSpikeDistance; + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_166.log('Did not find wheel motion attributes: ', e); + return; + } - var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; - function thisBarMinPos(di) { return di[posLetter] - di.w / 2; } - function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; } + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; - var minPos = isClosest ? - thisBarMinPos : - function(di) { - /* - * In compare mode, accept a bar if you're on it *or* its group. - * Nearly always it's the group that matters, but in case the bar - * was explicitly set wider than its group we'd better accept the - * whole bar. - * - * use `bardelta` instead of `bargroupwidth` so we accept hover - * in the gap. That way hover doesn't flash on and off as you - * mouse over the plot in compare modes. - * In 'closest' mode though the flashing seems inevitable, - * without far more complex logic - */ - return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2); - }; + var axRange = _$lib_166.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } - var maxPos = isClosest ? - thisBarMaxPos : - function(di) { - return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2); - }; + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; - function _positionFn(_minPos, _maxPos) { - // add a little to the pseudo-distance for wider bars, so that like scatter, - // if you are over two overlapping bars, the narrower one wins. - return _$fx_88.inbox(_minPos - posVal, _maxPos - posVal, - maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); - } + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } - function positionFn(di) { - return _positionFn(minPos(di), maxPos(di)); - } + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; - function thisBarPositionFn(di) { - return _positionFn(thisBarMinPos(di), thisBarMaxPos(di)); - } + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } - function sizeFn(di) { - // add a gradient so hovering near the end of a - // bar makes it a little closer match - return _$fx_88.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, - maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); - } + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } - if(trace.orientation === 'h') { - posVal = yval; - sizeVal = xval; - posLetter = 'y'; - sizeLetter = 'x'; - dx = sizeFn; - dy = positionFn; + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); + + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; + + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + + dragTail(zoomMode); + }, REDRAWDELAY); + + e.preventDefault(); + return; } - else { - posVal = xval; - sizeVal = yval; - posLetter = 'x'; - sizeLetter = 'y'; - dy = sizeFn; - dx = positionFn; + + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); } - var pa = pointData[posLetter + 'a']; - var sa = pointData[sizeLetter + 'a']; + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_88.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_88.getClosest(cd, distfn, pointData); + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); - // skip the rest (for this trace) if we didn't find a close point - if(pointData.index === false) return; + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } - // if we get here and we're not in 'closest' mode, push min/max pos back - // onto the group - even though that means occasionally the mouse will be - // over the hover label. - if(!isClosest) { - minPos = function(di) { - return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2); - }; - maxPos = function(di) { - return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2); - }; - } + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - // the closest data point - var index = pointData.index; - var di = cd[index]; - var mc = di.mcc || trace.marker.color; - var mlc = di.mlcc || trace.marker.line.color; - var mlw = di.mlw || trace.marker.line.width; + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - if(_$color_46.opacity(mc)) pointData.color = mc; - else if(_$color_46.opacity(mlc) && mlw) pointData.color = mlc; + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - var size = (trace.base) ? di.b + di.s : di.s; - pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); - pointData[sizeLetter + 'LabelVal'] = size; + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; - var extent = t.extents[t.extents.round(di.p)]; - pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true); - pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true); - pointData[posLetter + 'LabelVal'] = di.p; + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_224(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_224(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } - // spikelines always want "closest" distance regardless of hovermode - pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance; - // they also want to point to the data value, regardless of where the label goes - // in case of bars shifted within groups - pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } - _$fillHoverText_325(di, trace, pointData); - _$registry_247.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; - return [pointData]; -}; + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } -'use strict'; + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_216(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; -var _$layout_attributes_262 = { - 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', - + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // 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 + + redrawObjs(gd._fullLayout.annotations || [], _$registry_248.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_248.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_248.getComponentMethod('images', 'draw'), true); } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function doubleClick() { + if(gd._transitioningWithDuration) return; + + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; + var ax, i, rangeInitial; -'use strict'; + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { + + doubleClickConfig = 'autosize'; + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_165 = require('../../lib'); */; + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); -/* removed: var _$layout_attributes_262 = require('./layout_attributes'); */; + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } + for(i = 0; i < axList.length; i++) { + ax = axList[i]; -var _$layout_defaults_263 = function(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_165.coerce(layoutIn, layoutOut, _$layout_attributes_262, attr, dflt); + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } + + gd.emit('plotly_doubleclick', null); + _$registry_248.call('relayout', gd, attrs); } - var hasBars = false, - shouldBeGapless = false, - gappedAnyway = false, - usedSubplots = {}; + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(_$registry_247.traceIs(trace, 'bar')) hasBars = true; - else continue; + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_166.syncOrAsync([ + _$plots_240.previousPromises, + function() { _$registry_248.call('relayout', gd, updates); } + ], gd); + } - // if we have at least 2 grouped bar traces on the same subplot, - // we should default to a gap anyway, even if the data is histograms - if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') { - var subploti = trace.xaxis + trace.yaxis; - if(usedSubplots[subploti]) gappedAnyway = true; - usedSubplots[subploti] = true; + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; + + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); + + var i, sp, xa, ya; + + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_155(gd); } - if(trace.visible && trace.type === 'histogram') { - var pa = _$axes_207.getFromId({_fullLayout: layoutOut}, - trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); - if(pa.type !== 'category') shouldBeGapless = true; + if(hasSplom) { + _$registry_248.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; } - } - if(!hasBars) return; + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_166.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_166.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } - var mode = coerce('barmode'); - if(mode !== 'overlay') coerce('barnorm'); + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; - coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2); - coerce('bargroupgap'); -}; + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; -'use strict'; + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_28 = require('tinycolor2'); */; + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$registry_247 = require('../../registry'); */; + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_71.setTranslate, clipDx, clipDy) + .call(_$drawing_71.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_71.setTranslate, plotDx, plotDy) + .call(_$drawing_71.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_71.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_71.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_71.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_71.hideOutsideRangePoints, sp, '.bartext'); + } + } + } + } -var __dummy_264$0 = 0, - attributeText = _$attributes_257.text, - attributeTextPosition = _$attributes_257.textposition, - attributeTextFont = _$attributes_257.textfont, - attributeInsideTextFont = _$attributes_257.insidetextfont, - attributeOutsideTextFont = _$attributes_257.outsidetextfont; + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; -// padding in pixels around text -var TEXTPAD = 3; + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } -var _$plot_264 = function plot(gd, plotinfo, cdbar) { - var xa = plotinfo.xaxis, - ya = plotinfo.yaxis, - fullLayout = gd._fullLayout; + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_224(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } - var bartraces = plotinfo.plot.select('.barlayer') - .selectAll('g.trace.bars') - .data(cdbar); + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle']; + } - bartraces.enter().append('g') - .attr('class', 'trace bars'); + return dragger; +} - bartraces.each(function(d) { - d[0].node3 = _$d3_10.select(this); +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_166.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); }); - bartraces.append('g') - .attr('class', 'points') - .each(function(d) { - var sel = _$d3_10.select(this); - var t = d[0].t; - var trace = d[0].trace; - var poffset = t.poffset; - var poffsetIsArray = Array.isArray(poffset); - - sel.selectAll('g.point') - .data(_$lib_165.identity) - .enter().append('g').classed('point', true) - .each(function(di, i) { - // now display the bar - // clipped xf/yf (2nd arg true): non-positive - // log values go off-screen by plotwidth - // so you see them continue if you drag the plot - var p0 = di.p + ((poffsetIsArray) ? poffset[i] : poffset), - p1 = p0 + di.w, - s0 = di.b, - s1 = s0 + di.s; + dragger3.call(_$setCursor_185, cursor); - var x0, x1, y0, y1; - if(trace.orientation === 'h') { - y0 = ya.c2p(p0, true); - y1 = ya.c2p(p1, true); - x0 = xa.c2p(s0, true); - x1 = xa.c2p(s1, true); + return dragger3.node(); +} - // for selections - di.ct = [x1, (y0 + y1) / 2]; - } - else { - x0 = xa.c2p(p0, true); - x1 = xa.c2p(p1, true); - y0 = ya.c2p(s0, true); - y1 = ya.c2p(s1, true); +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_10.select(dragger).call(_$drawing_71.setRect, x, y, w, h); + return dragger; +} - // for selections - di.ct = [(x0 + x1) / 2, y1]; - } +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} - if(!_$fastIsnumeric_13(x0) || !_$fastIsnumeric_13(x1) || - !_$fastIsnumeric_13(y0) || !_$fastIsnumeric_13(y1) || - x0 === x1 || y0 === y1) { - _$d3_10.select(this).remove(); - return; - } +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - var lw = (di.mlw + 1 || trace.marker.line.width + 1 || - (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, - offset = _$d3_10.round((lw / 2) % 1, 2); + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_10.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_10.format('.' + String(dig) + 'g')(initialVal); + } +} - function roundWithLine(v) { - // if there are explicit gaps, don't round, - // it can make the gaps look crappy - return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? - _$d3_10.round(Math.round(v) - offset, 2) : v; - } +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; - function expandToVisible(v, vc) { - // if it's not in danger of disappearing entirely, - // round more precisely - return Math.abs(v - vc) >= 2 ? roundWithLine(v) : - // but if it's very thin, expand it so it's - // necessarily visible, even if it might overlap - // its neighbor - (v > vc ? Math.ceil(v) : Math.floor(v)); - } + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; - if(!gd._context.staticPlot) { - // if bars are not fully opaque or they have a line - // around them, round to integer pixels, mainly for - // safari so we prevent overlaps from its expansive - // pixelation. if the bars ARE fully opaque and have - // no line, expand to a full pixel to make sure we - // can see them - var op = _$color_46.opacity(di.mc || trace.marker.color), - fixpx = (op < 1 || lw > 0.01) ? - roundWithLine : expandToVisible; - x0 = fixpx(x0, x1); - x1 = fixpx(x1, x0); - y0 = fixpx(y0, y1); - y1 = fixpx(y1, y0); - } + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } - // append bar path and text - var bar = _$d3_10.select(this); + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - bar.append('path') - .style('vector-effect', 'non-scaling-stroke') - .attr('d', - 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') - .call(_$drawing_71.setClipUrl, plotinfo.layerClipId); + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} - appendBarText(gd, bar, d, i, x0, x1, y0, y1); +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} - if(plotinfo.layerClipId) { - _$drawing_71.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); - } - }); - }); +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} - // error bars are on the top - _$registry_247.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} - // lastly, clip points groups of `cliponaxis !== false` traces - // on `plotinfo._hasClipOnAxisFalse === true` subplots - bartraces.each(function(d) { - var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_71.setClipUrl(_$d3_10.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); - }); -}; +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} -function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { - var textPosition; +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_46.background, + stroke: _$color_46.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} - function appendTextNode(bar, text, textFont) { - var textSelection = bar.append('text') - .text(text) - .attr({ - 'class': 'bartext bartext-' + textPosition, - transform: '', - 'text-anchor': 'middle', - // prohibit tex interpretation until we can handle - // tex and regular text together - 'data-notex': 1 - }) - .call(_$drawing_71.font, textFont) - .call(_$svg_text_utils_186.convertToTspans, gd); +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} - return textSelection; +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); } +} - // get trace attributes - var trace = calcTrace[0].trace, - orientation = trace.orientation; - - var text = getText(trace, i); - if(!text) return; - - textPosition = getTextPosition(trace, i); - if(textPosition === 'none') return; - - var textFont = getTextFont(trace, i, gd._fullLayout.font), - insideTextFont = getInsideTextFont(trace, i, textFont), - outsideTextFont = getOutsideTextFont(trace, i, textFont); +function removeZoombox(gd) { + _$d3_10.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} - // compute text position - var barmode = gd._fullLayout.barmode, - inStackMode = (barmode === 'stack'), - inRelativeMode = (barmode === 'relative'), - inStackOrRelativeMode = inStackMode || inRelativeMode, +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_166.notifier(_$lib_166._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} - calcBar = calcTrace[i], - isOutmostBar = !inStackOrRelativeMode || calcBar._outmost, +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} - barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD, // padding excluded - barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD, // padding excluded +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} - textSelection, - textBB, - textWidth, - textHeight; +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} - if(textPosition === 'outside') { - if(!isOutmostBar) textPosition = 'inside'; - } +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - if(textPosition === 'auto') { - if(isOutmostBar) { - // draw text using insideTextFont and check if it fits inside bar - textPosition = 'inside'; - textSelection = appendTextNode(bar, text, insideTextFont); +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; - textBB = _$drawing_71.bBox(textSelection.node()), - textWidth = textBB.width, - textHeight = textBB.height; + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } - var textHasSize = (textWidth > 0 && textHeight > 0), - fitsInside = - (textWidth <= barWidth && textHeight <= barHeight), - fitsInsideIfRotated = - (textWidth <= barHeight && textHeight <= barWidth), - fitsInsideIfShrunk = (orientation === 'h') ? - (barWidth >= textWidth * (barHeight / textHeight)) : - (barHeight >= textHeight * (barWidth / textWidth)); - if(textHasSize && - (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) { - textPosition = 'inside'; - } - else { - textPosition = 'outside'; - textSelection.remove(); - textSelection = null; + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } } } - else textPosition = 'inside'; - } - - if(!textSelection) { - textSelection = appendTextNode(bar, text, - (textPosition === 'outside') ? - outsideTextFont : insideTextFont); - textBB = _$drawing_71.bBox(textSelection.node()), - textWidth = textBB.width, - textHeight = textBB.height; - - if(textWidth <= 0 || textHeight <= 0) { - textSelection.remove(); - return; + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } } } - // compute text transform - var transform, constrained; - if(textPosition === 'outside') { - constrained = trace.constraintext === 'both' || trace.constraintext === 'outside'; - transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, - orientation, constrained); - } - else { - constrained = trace.constraintext === 'both' || trace.constraintext === 'inside'; - transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, - orientation, constrained); + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_166.extendFlat(xLinks, yLinks); + yLinks = {}; } - textSelection.attr('transform', transform); -} - -function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { - // compute text and target positions - var textWidth = textBB.width, - textHeight = textBB.height, - textX = (textBB.left + textBB.right) / 2, - textY = (textBB.top + textBB.bottom) / 2, - barWidth = Math.abs(x1 - x0), - barHeight = Math.abs(y1 - y0), - targetWidth, - targetHeight, - targetX, - targetY; - - // apply text padding - var textpad; - if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) { - textpad = TEXTPAD; - barWidth -= 2 * textpad; - barHeight -= 2 * textpad; + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_216(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; } - else textpad = 0; - - // compute rotation and scale - var rotate, - scale; - if(textWidth <= barWidth && textHeight <= barHeight) { - // no scale or rotation is required - rotate = false; - scale = 1; - } - else if(textWidth <= barHeight && textHeight <= barWidth) { - // only rotation is required - rotate = true; - scale = 1; - } - else if((textWidth < textHeight) === (barWidth < barHeight)) { - // only scale is required - rotate = false; - scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1; - } - else { - // both scale and rotation are required - rotate = true; - scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1; + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_216(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; } - if(rotate) rotate = 90; // rotate clockwise + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} - // compute text and target positions - if(rotate) { - targetWidth = scale * textHeight; - targetHeight = scale * textWidth; +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_16) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; } else { - targetWidth = scale * textWidth; - targetHeight = scale * textHeight; - } + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - if(orientation === 'h') { - if(x1 < x0) { - // bar end is on the left hand side - targetX = x1 + textpad + targetWidth / 2; - targetY = (y0 + y1) / 2; - } - else { - targetX = x1 - textpad - targetWidth / 2; - targetY = (y0 + y1) / 2; - } - } - else { - if(y1 > y0) { - // bar end is on the bottom - targetX = (x0 + x1) / 2; - targetY = y1 - textpad - targetHeight / 2; - } - else { - targetX = (x0 + x1) / 2; - targetY = y1 + textpad + targetHeight / 2; + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); } +} - return getTransform(textX, textY, targetX, targetY, scale, rotate); +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; } -function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { - var barWidth = (orientation === 'h') ? - Math.abs(y1 - y0) : - Math.abs(x1 - x0), - textpad; +var _$dragbox_216 = { + makeDragBox: makeDragBox, - // Keep the padding so the text doesn't sit right against - // the bars, but don't factor it into barWidth - if(barWidth > 2 * TEXTPAD) { - textpad = TEXTPAD; - } + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, - // compute rotation and scale - var scale = 1; - if(constrained) { - scale = (orientation === 'h') ? - Math.min(1, barWidth / textBB.height) : - Math.min(1, barWidth / textBB.width); - } + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, - // compute text and target positions - var textX = (textBB.left + textBB.right) / 2, - textY = (textBB.top + textBB.bottom) / 2, - targetWidth, - targetHeight, - targetX, - targetY; + attachWheelEventHandler: attachWheelEventHandler +}; - targetWidth = scale * textBB.width; - targetHeight = scale * textBB.height; +var _$graph_interact_217 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(orientation === 'h') { - if(x1 < x0) { - // bar end is on the left hand side - targetX = x1 - textpad - targetWidth / 2; - targetY = (y0 + y1) / 2; - } - else { - targetX = x1 + textpad + targetWidth / 2; - targetY = (y0 + y1) / 2; - } - } - else { - if(y1 > y0) { - // bar end is on the bottom - targetX = (x0 + x1) / 2; - targetY = y1 + textpad + targetHeight / 2; - } - else { - targetX = (x0 + x1) / 2; - targetY = y1 - textpad - targetHeight / 2; - } - } - return getTransform(textX, textY, targetX, targetY, scale, false); -} +'use strict'; -function getTransform(textX, textY, targetX, targetY, scale, rotate) { - var transformScale, - transformRotate, - transformTranslate; +/* removed: var _$d3_10 = require('d3'); */; - if(scale < 1) transformScale = 'scale(' + scale + ') '; - else { - scale = 1; - transformScale = ''; +/* removed: var _$fx_88 = require('../../components/fx'); */; +/* removed: var _$dragelement_68 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; + +var __makeDragBox_217 = _$dragbox_216.makeDragBox; +var DRAGGERSIZE = _$constants_213.DRAGGERSIZE; + +_$graph_interact_217.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; + + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_10.select(gd).selectAll('.drag').remove(); + return; } - transformRotate = (rotate) ? - 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : ''; + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - // Note that scaling also affects the center of the text box - var translateX = (targetX - scale * textX), - translateY = (targetY - scale * textY); - transformTranslate = 'translate(' + translateX + ' ' + translateY + ')'; + 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'), + 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; + }); - return transformTranslate + transformScale + transformRotate; -} + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -function getText(trace, index) { - var value = getValue(trace.text, index); - return coerceString(attributeText, value); -} + // 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_217(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); -function getTextPosition(trace, index) { - var value = getValue(trace.textposition, index); - return coerceEnumerated(attributeTextPosition, value); -} + 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) { + _$fx_88.hover(gd, evt, subplot); + } + }; -function getTextFont(trace, index, defaultValue) { - return getFontValue( - attributeTextFont, trace.textfont, index, defaultValue); -} + _$fx_88.hover(gd, evt, subplot); -function getInsideTextFont(trace, index, defaultValue) { - return getFontValue( - attributeInsideTextFont, trace.insidetextfont, index, defaultValue); -} + // 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; + }; -function getOutsideTextFont(trace, index, defaultValue) { - return getFontValue( - attributeOutsideTextFont, trace.outsidetextfont, index, defaultValue); -} + /* + * 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; -function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { - attributeValue = attributeValue || {}; + // 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; - var familyValue = getValue(attributeValue.family, index), - sizeValue = getValue(attributeValue.size, index), - colorValue = getValue(attributeValue.color, index); + _$dragelement_68.unhover(gd, evt); + }; - return { - family: coerceString( - attributeDefinition.family, familyValue, defaultValue.family), - size: coerceNumber( - attributeDefinition.size, sizeValue, defaultValue.size), - color: coerceColor( - attributeDefinition.color, colorValue, defaultValue.color) + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_217(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_217(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_217(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_217(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_217(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_217(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_217(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_217(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_217(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_217(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_88.hover(gd, evt, fullLayout._hoversubplot); }; -} -function getValue(arrayOrScalar, index) { - var value; - if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar; - else if(index < arrayOrScalar.length) value = arrayOrScalar[index]; - return value; -} + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_88.click(gd, evt); + }; -function coerceString(attributeDefinition, value, defaultValue) { - if(typeof value === 'string') { - if(value || !attributeDefinition.noBlank) return value; - } - else if(typeof value === 'number') { - if(!attributeDefinition.strict) return String(value); - } + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} + _$graph_interact_217.updateFx(fullLayout); +}; -function coerceEnumerated(attributeDefinition, value, defaultValue) { - if(attributeDefinition.coerceNumber) value = +value; +// 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. +_$graph_interact_217.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_185(fullLayout._draggers, cursor); +}; - if(attributeDefinition.values.indexOf(value) !== -1) return value; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} +'use strict'; -function coerceNumber(attributeDefinition, value, defaultValue) { - if(_$fastIsnumeric_13(value)) { - value = +value; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; - var min = attributeDefinition.min, - max = attributeDefinition.max, - isOutOfBounds = (min !== undefined && value < min) || - (max !== undefined && value > max); + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } - if(!isOutOfBounds) return value; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } } - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; + return Object.keys(lookup); } -function coerceColor(attributeDefinition, value, defaultValue) { - if(_$tinycolor_28(value).isValid()) return value; +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_212 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; - return (defaultValue !== undefined) ? - defaultValue : - attributeDefinition.dflt; -} + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; + + var order = coerce('categoryorder', orderDefault); + var array; + + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); + } + + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; + } + + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -34724,36 +35624,58 @@ function coerceColor(attributeDefinition, value, defaultValue) { 'use strict'; -var _$selectPoints_265 = function selectPoints(searchInfo, polygon) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var i; +var colorMix = _$tinycolor_28.mix; +var lightFraction = _$attributes_45.lightFraction; +/* removed: var _$lib_166 = require('../../lib'); */; - if(polygon === 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]; +/** + * @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 + */ +var _$handleLineGridDefaults_222 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; - if(polygon.contains(di.ct)) { - selection.push({ - pointNumber: i, - x: xa.c2d(di.x), - y: ya.c2d(di.y) - }); - di.selected = 1; - } else { - di.selected = 0; - } - } + var dfltColor = opts.dfltColor; + + function coerce2(attr, dflt) { + return _$lib_166.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } - return selection; + 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; + } + } }; /** @@ -34766,102 +35688,93 @@ var _$selectPoints_265 = function selectPoints(searchInfo, polygon) { 'use strict'; -var _$Sieve_267 = Sieve; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -var __BADNUM_267 = _$numerical_148.BADNUM; +/* removed: var _$layout_attributes_220 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_229 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_228 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_227 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_212 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_222 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_226 = require('./set_convert'); */; /** - * Helper class to sieve data from traces into bins + * options: object containing: * - * @class - * @param {Array} traces - * Array of calculated traces - * @param {boolean} [separateNegativeValues] - * If true, then split data at the same position into a bar - * for positive values and another for negative values - * @param {boolean} [dontMergeOverlappingData] - * If true, then don't merge overlapping bars into a single bar + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors */ -function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { - this.traces = traces; - this.separateNegativeValues = separateNegativeValues; - this.dontMergeOverlappingData = dontMergeOverlappingData; +var _$handleAxisDefaults_210 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; - // for single-bin histograms - see histogram/calc - var width1 = Infinity; + var visible = coerce('visible', !options.cheateronly); - var positions = []; - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; - if(bar.p !== __BADNUM_267) positions.push(bar.p); - } - if(trace[0] && trace[0].width1) { - width1 = Math.min(trace[0].width1, width1); - } + var axType = containerOut.type; + + if(axType === 'date') { + var handleCalendarDefaults = _$registry_248.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } - this.positions = positions; - var dv = _$lib_165.distinctVals(positions); - this.distinctPositions = dv.vals; - if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; - else this.minDiff = Math.min(dv.minDiff, width1); + _$setConvert_226(containerOut, layoutOut); - this.binWidth = this.minDiff; + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - this.bins = {}; -} + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; -/** - * Sieve datum - * - * @method - * @param {number} position - * @param {number} value - * @returns {number} Previous bin value - */ -Sieve.prototype.put = function put(position, value) { - var label = this.getLabel(position, value), - oldValue = this.bins[label] || 0; + if(autoRange) coerce('rangemode'); - this.bins[label] = oldValue + value; + coerce('range'); + containerOut.cleanRange(); - return oldValue; -}; + _$handleCategoryOrderDefaults_212(containerIn, containerOut, coerce, options); -/** - * Get current bin value for a given datum - * - * @method - * @param {number} position Position of datum - * @param {number} [value] Value of datum - * (required if this.separateNegativeValues is true) - * @returns {number} Current bin value - */ -Sieve.prototype.get = function put(position, value) { - var label = this.getLabel(position, value); - return this.bins[label] || 0; -}; + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); -/** - * Get bin label for a given datum - * - * @method - * @param {number} position Position of datum - * @param {number} [value] Value of datum - * (required if this.separateNegativeValues is true) - * @returns {string} Bin label - * (prefixed with a 'v' if value is negative and this.separateNegativeValues is - * true; otherwise prefixed with '^') - */ -Sieve.prototype.getLabel = function getLabel(position, value) { - var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^', - label = (this.dontMergeOverlappingData) ? - position : - Math.round(position / this.binWidth); - return prefix + label; + if(!visible) return containerOut; + + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; + + coerce('title', dfltTitle); + _$lib_166.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); + + _$handleTickValueDefaults_229(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_227(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_228(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_222(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_220 + }); + + if(containerOut.showline || containerOut.ticks) coerce('mirror'); + + if(options.automargin) coerce('automargin'); + + return containerOut; }; /** @@ -34875,647 +35788,607 @@ Sieve.prototype.getLabel = function getLabel(position, value) { 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_266 = _$lib_165.isArrayOrTypedArray; -var __BADNUM_266 = _$numerical_148.BADNUM; +/* removed: var _$lib_166 = require('../../lib'); */; +var id2name = _$axis_ids_211.id2name; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$Sieve_267 = require('./sieve.js'); */; -/* - * 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 - */ +var _$handleConstraintDefaults_214 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); -var _$setPositions_266 = function setPositions(gd, plotinfo) { - var xa = plotinfo.xaxis, - ya = plotinfo.yaxis; + if(containerOut.fixedrange) return; - var fullTraces = gd._fullData, - calcTraces = gd.calcdata, - calcTracesHorizontal = [], - calcTracesVertical = [], - i; - for(i = 0; i < fullTraces.length; i++) { - var fullTrace = fullTraces[i]; - if( - fullTrace.visible === true && - _$registry_247.traceIs(fullTrace, 'bar') && - fullTrace.xaxis === xa._id && - fullTrace.yaxis === ya._id - ) { - if(fullTrace.orientation === 'h') { - calcTracesHorizontal.push(calcTraces[i]); - } - else { - calcTracesVertical.push(calcTraces[i]); - } + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_166.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' } - } - - setGroupPositions(gd, xa, ya, calcTracesVertical); - setGroupPositions(gd, ya, xa, calcTracesHorizontal); -}; + }, 'constraintoward'); + if(!containerIn.scaleanchor) return; -function setGroupPositions(gd, pa, sa, calcTraces) { - if(!calcTraces.length) return; + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - var barmode = gd._fullLayout.barmode, - overlay = (barmode === 'overlay'), - group = (barmode === 'group'), - excluded, - included, - i, calcTrace, fullTrace; - - if(overlay) { - setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces); - } - else if(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); - } - if(excluded.length) { - setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + var scaleanchor = _$lib_166.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes } - } - else { - // 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; + }, 'scaleanchor'); - if(fullTrace.base === undefined) included.push(calcTrace); - else excluded.push(calcTrace); - } + 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; - if(included.length) { - setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included); - } - if(excluded.length) { - setGroupPositionsInOverlayMode(gd, pa, sa, excluded); - } + updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_166.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.'); } +}; - collectExtents(calcTraces, pa); -} +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. + var thisType = layoutOut[id2name(thisID)].type; -function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { - var barnorm = gd._fullLayout.barnorm, - separateNegativeValues = false, - dontMergeOverlappingData = !barnorm; + var i, j, idj, axj; - // update position axis and set bar offsets and widths - for(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; + var linkableAxes = []; + for(j = 0; j < allAxisIds.length; j++) { + idj = allAxisIds[j]; + if(idj === thisID) continue; - var sieve = new _$Sieve_267( - [calcTrace], separateNegativeValues, dontMergeOverlappingData - ); + axj = layoutOut[id2name(idj)]; + if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); + } - // set bar offsets and widths, and update position axis - setOffsetAndWidth(gd, pa, sieve); + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; - // 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(barnorm) { - sieveBars(gd, sa, sieve); - normalizeBars(gd, sa, sieve); - } - else { - setBaseAndTop(gd, sa, sieve); + 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}; +} -function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { - var fullLayout = gd._fullLayout, - barnorm = fullLayout.barnorm, - separateNegativeValues = false, - dontMergeOverlappingData = !barnorm, - sieve = new _$Sieve_267( - calcTraces, separateNegativeValues, dontMergeOverlappingData - ); - // set bar offsets and widths, and update position axis - setOffsetAndWidthInGroupMode(gd, pa, sieve); +/* + * 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; - // set bar bases and sizes, and update size axis - if(barnorm) { - sieveBars(gd, sa, sieve); - normalizeBars(gd, sa, sieve); + if(thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); } else { - setBaseAndTop(gd, sa, sieve); + thisGroupIndex = constraintGroups.indexOf(thisGroup); } -} - - -function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { - var fullLayout = gd._fullLayout, - barmode = fullLayout.barmode, - stack = (barmode === 'stack'), - relative = (barmode === 'relative'), - barnorm = gd._fullLayout.barnorm, - separateNegativeValues = relative, - dontMergeOverlappingData = !(barnorm || stack || relative), - sieve = new _$Sieve_267( - calcTraces, separateNegativeValues, dontMergeOverlappingData - ); - - // set bar offsets and widths, and update position axis - setOffsetAndWidth(gd, pa, sieve); - - // set bar bases and sizes, and update size axis - stackBars(gd, sa, sieve); - // 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_266) continue; + var thisGroupKeys = Object.keys(thisGroup); - var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); - if(isOutmostBar) bar._outmost = true; + // 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; } } - // Note that marking the outmost bars has to be done - // before `normalizeBars` changes `bar.b` and `bar.s`. - if(barnorm) normalizeBars(gd, sa, sieve); + // 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; } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function setOffsetAndWidth(gd, pa, sieve) { - var fullLayout = gd._fullLayout, - bargap = fullLayout.bargap, - bargroupgap = fullLayout.bargroupgap, - minDiff = sieve.minDiff, - calcTraces = sieve.traces, - i, calcTrace, calcTrace0, - t; - - // set bar offsets and widths - var barGroupWidth = minDiff * (1 - bargap), - barWidthPlusGap = barGroupWidth, - barWidth = barWidthPlusGap * (1 - bargroupgap); - - // computer bar group center and bar offset - var offsetFromCenter = -barWidth / 2; - for(i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; +'use strict'; - // store bar width and offset for this trace - t = calcTrace0.t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; - } +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - // stack bars that only differ by rounding - sieve.binWidth = calcTraces[0][0].t.barwidth / 100; +/* removed: var _$lib_166 = require('../../lib'); */; - // if defined, apply trace offset and width - applyAttributes(sieve); - // store the bar center in each calcdata item - setBarCenterAndWidth(gd, pa, sieve); +var _$handlePositionDefaults_223 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; - // update position axes - updatePositionAxis(gd, pa, sieve); -} + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; + } + } -function setOffsetAndWidthInGroupMode(gd, pa, sieve) { - var fullLayout = gd._fullLayout, - bargap = fullLayout.bargap, - bargroupgap = fullLayout.bargroupgap, - positions = sieve.positions, - distinctPositions = sieve.distinctPositions, - minDiff = sieve.minDiff, - calcTraces = sieve.traces, - i, calcTrace, calcTrace0, - t; + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_13(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; - // if there aren't any overlapping positions, - // let them have full width even if mode is group - var overlap = (positions.length !== distinctPositions.length); + var anchor = _$lib_166.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor + } + }, 'anchor'); - var nTraces = calcTraces.length, - barGroupWidth = minDiff * (1 - bargap), - barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth, - barWidth = barWidthPlusGap * (1 - bargroupgap); + if(anchor === 'free') coerce('position', dfltPosition); - for(i = 0; i < nTraces; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; + _$lib_166.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide + } + }, 'side'); - // computer bar group center and bar offset - var offsetFromCenter = (overlap) ? - ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : - -barWidth / 2; + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_166.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); + } - // store bar width and offset for this trace - t = calcTrace0.t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_166.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } - // stack bars that only differ by rounding - sieve.binWidth = calcTraces[0][0].t.barwidth / 100; + coerce('layer'); - // if defined, apply trace width - applyAttributes(sieve); + return containerOut; +}; - // store the bar center in each calcdata item - setBarCenterAndWidth(gd, pa, sieve); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // update position axes - updatePositionAxis(gd, pa, sieve, overlap); -} +'use strict'; -function applyAttributes(sieve) { - var calcTraces = sieve.traces, - i, calcTrace, calcTrace0, fullTrace, - j, - t; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$autoType_209 = require('./axis_autotype'); */; +var name2id = _$axis_ids_211.name2id; - for(i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - calcTrace0 = calcTrace[0]; - fullTrace = calcTrace0.trace; - t = calcTrace0.t; +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_231 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); + } - var offset = fullTrace.offset, - initialPoffset = t.poffset, - newPoffset; + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - if(__isArrayOrTypedArray_266(offset)) { - // if offset is an array, then clone it into t.poffset. - newPoffset = offset.slice(0, calcTrace.length); + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; + } + } +}; - // guard against non-numeric items - for(j = 0; j < newPoffset.length; j++) { - if(!_$fastIsnumeric_13(newPoffset[j])) { - newPoffset[j] = initialPoffset; - } - } +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - // 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); - } + var id = ax._id; + var axLetter = id.charAt(0); - t.poffset = newPoffset; - } - else if(offset !== undefined) { - t.poffset = offset; - } + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; - var width = fullTrace.width, - initialBarwidth = t.barwidth; + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; - if(__isArrayOrTypedArray_266(width)) { - // if width is an array, then clone it into t.barwidth. - var newBarwidth = width.slice(0, calcTrace.length); + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } - // guard against non-numeric items - for(j = 0; j < newBarwidth.length; j++) { - if(!_$fastIsnumeric_13(newBarwidth[j])) newBarwidth[j] = initialBarwidth; - } + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; - // 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); - } + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - t.barwidth = newBarwidth; + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_248.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; - // 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; - } + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); + + if(trace[calAttr] !== calendar) calendar = undefined; } - 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; + ax.type = _$autoType_209(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_209(dim.values, calendar); + break; } } } + else { + ax.type = _$autoType_209(d0[axLetter] || [d0[axLetter + '0']], calendar); + } } +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; -function setBarCenterAndWidth(gd, pa, sieve) { - var calcTraces = sieve.traces, - pLetter = getAxisLetter(pa); - - for(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i], - t = calcTrace[0].t, - poffset = t.poffset, - poffsetIsArray = Array.isArray(poffset), - barwidth = t.barwidth, - 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; - + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } } } } +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} -function updatePositionAxis(gd, pa, sieve, allowMinDtick) { - var calcTraces = sieve.traces, - distinctPositions = sieve.distinctPositions, - distinctPositions0 = distinctPositions[0], - minDiff = sieve.minDiff, - vpad = minDiff / 2; +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_248.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_248.traceIs(trace._fullInput || {}, 'candlestick'); - _$axes_207.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); +} - // If the user set the bar width or the offset, - // then bars can be shifted away from their positions - // and widths can be larger than minDiff. - // - // Here, we compute pMin and pMax to expand the position axis, - // so that all bars are fully within the axis range. - var pMin = Math.min.apply(Math, distinctPositions) - vpad, - pMax = Math.max.apply(Math, distinctPositions) + vpad; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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(var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i], - calcTrace0 = calcTrace[0], - fullTrace = calcTrace0.trace; - if(fullTrace.width === undefined && fullTrace.offset === undefined) { - continue; - } +'use strict'; - var t = calcTrace0.t, - poffset = t.poffset, - barwidth = t.barwidth, - poffsetIsArray = Array.isArray(poffset), - barwidthIsArray = Array.isArray(barwidth); +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$layout_attributes_238 = require('../layout_attributes'); */; - for(var j = 0; j < calcTrace.length; j++) { - var calcBar = calcTrace[j], - calcBarOffset = (poffsetIsArray) ? poffset[j] : poffset, - calcBarWidth = (barwidthIsArray) ? barwidth[j] : barwidth, - p = calcBar.p, - l = p + calcBarOffset, - r = l + calcBarWidth; +/* removed: var _$layout_attributes_220 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_231 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_210 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_214 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_223 = require('./position_defaults'); */; +/* removed: var _$axis_ids_211 = require('./axis_ids'); */; - pMin = Math.min(pMin, l); - pMax = Math.max(pMax, r); - } - } - _$axes_207.expand(pa, [pMin, pMax], {padded: false}); -} +var _$supplyLayoutDefaults_221 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -function expandRange(range, newValue) { - if(_$fastIsnumeric_13(range[0])) range[0] = Math.min(range[0], newValue); - else range[0] = newValue; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - if(_$fastIsnumeric_13(range[1])) range[1] = Math.max(range[1], newValue); - else range[1] = newValue; -} + if(!_$registry_248.traceIs(trace, 'cartesian') && !_$registry_248.traceIs(trace, 'gl2d')) { + continue; + } -function setBaseAndTop(gd, sa, sieve) { - // 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. - var traces = sieve.traces, - sLetter = getAxisLetter(sa), - sRange = [null, null]; + var xaName = _$axis_ids_211.id2name(trace.xaxis); + var yaName = _$axis_ids_211.id2name(trace.yaxis); - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_248.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - for(var j = 0; j < trace.length; j++) { - var bar = trace[j], - barBase = bar.b, - barTop = barBase + bar.s; + // 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) xaCheater[xaName] = 1; + } - bar[sLetter] = barTop; + // check for default formatting tweaks + if(_$registry_248.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } - if(_$fastIsnumeric_13(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_13(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$registry_248.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; } } - _$axes_207.expand(sa, sRange, {tozero: true, padded: true}); -} + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_166.simpleMap(xIds, _$axis_ids_211.id2name); + var yNames = _$lib_166.simpleMap(yIds, _$axis_ids_211.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 plot_bgcolor = _$color_46.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_238, 'plot_bgcolor'); + } -function stackBars(gd, sa, sieve) { - var fullLayout = gd._fullLayout, - barnorm = fullLayout.barnorm, - sLetter = getAxisLetter(sa), - traces = sieve.traces, - i, trace, - j, bar; + var bgColor = _$color_46.combine(plot_bgcolor, layoutOut.paper_bgcolor); - var sRange = [null, null]; + var axName, axLetter, axLayoutIn, axLayoutOut; - for(i = 0; i < traces.length; i++) { - trace = traces[i]; + function coerce(attr, dflt) { + return _$lib_166.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_220, attr, dflt); + } - for(j = 0; j < trace.length; j++) { - bar = trace[j]; + function coerce2(attr, dflt) { + return _$lib_166.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_220, attr, dflt); + } - if(bar.s === __BADNUM_266) continue; + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } - // stack current bar and get previous sum - var barBase = sieve.put(bar.p, bar.b + bar.s), - barTop = barBase + bar.b + bar.s; + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - // store the bar base and top in each calcdata item - bar.b = barBase; - bar[sLetter] = barTop; + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; - if(!barnorm) { - if(_$fastIsnumeric_13(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_13(sa.c2l(barBase))) expandRange(sRange, barBase); + for(var j = 0; j < list.length; j++) { + var axName2 = list[j]; + + if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { + out.push(_$axis_ids_211.name2id(axName2)); } } - } - // if barnorm is set, let normalizeBars update the axis range - if(!barnorm) _$axes_207.expand(sa, sRange, {tozero: true, padded: true}); -} + 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]; -function sieveBars(gd, sa, sieve) { - var traces = sieve.traces; + if(!_$lib_166.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; + _$handleTypeDefaults_231(axLayoutIn, axLayoutOut, coerce, fullData, axName); - if(bar.s !== __BADNUM_266) sieve.put(bar.p, bar.b + bar.s); - } - } -} + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; -function normalizeBars(gd, sa, sieve) { - // Note: - // - // normalizeBars requires that either sieveBars or stackBars has been - // previously invoked. + _$handleAxisDefaults_210(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - var traces = sieve.traces, - sLetter = getAxisLetter(sa), - sTop = (gd._fullLayout.barnorm === 'fraction') ? 1 : 100, - sTiny = sTop / 1e9, // in case of rounding error in sum - sMin = sa.l2c(sa.c2l(0)), - sMax = (gd._fullLayout.barmode === 'stack') ? sTop : sMin, - sRange = [sMin, sMax], - padded = false; + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - function maybeExpand(newValue) { - if(_$fastIsnumeric_13(sa.c2l(newValue)) && - ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_13(sMin)) - ) { - padded = true; - expandRange(sRange, newValue); + if(!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; } - } - for(var i = 0; i < traces.length; i++) { - var trace = traces[i]; + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; - for(var j = 0; j < trace.length; j++) { - var bar = trace[j]; + _$handlePositionDefaults_223(axLayoutIn, axLayoutOut, coerce, positioningOptions); - if(bar.s === __BADNUM_266) continue; + axLayoutOut._input = axLayoutIn; + } - var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); - bar.b *= scale; - bar.s *= scale; + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_248.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_248.getComponentMethod('rangeselector', 'handleDefaults'); - var barBase = bar.b, - barTop = barBase + bar.s; - bar[sLetter] = barTop; + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - maybeExpand(barTop); - if(bar.hasB) maybeExpand(barBase); + rangeSliderDefaults(layoutIn, layoutOut, axName); + + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); } - } - // update range of size axis - _$axes_207.expand(sa, sRange, {tozero: true, padded: padded}); -} + coerce('fixedrange'); + } + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; -function getAxisLetter(ax) { - return ax._id.charAt(0); -} + var anchoredAxis = layoutOut[_$axis_ids_211.id2name(axLayoutOut.anchor)]; -// 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 posLetter = pa._id.charAt(0); - var extents = {}; - var pMin = Infinity; - var pMax = -Infinity; + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - var i, j, cd; - for(i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - for(j = 0; j < cd.length; j++) { - var p = cd[j].p; - if(_$fastIsnumeric_13(p)) { - pMin = Math.min(pMin, p); - pMax = Math.max(pMax, p); - } - } + coerce('fixedrange', fixedRangeDflt); } - // 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))); - }; + // Finally, handle scale constraints. 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). - for(i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - cd[0].t.extents = extents; - for(j = 0; j < cd.length; j++) { - var di = cd[j]; - var p0 = di[posLetter] - di.w / 2; - if(_$fastIsnumeric_13(p0)) { - var p1 = di[posLetter] + 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]; - } - } - } + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); + + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + + _$handleConstraintDefaults_214(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); } -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -35525,738 +36398,330 @@ function collectExtents(calcTraces, pa) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_10 = require('d3'); */; + +/* removed: var _$registry_248 = require('../../registry'); */; /* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$registry_247 = require('../../registry'); */; +/* removed: var _$axes_208 = require('./axes'); */; +var axisRegex = _$constants_213.attrRegex; -var _$style_268 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_10.select(gd).selectAll('g.trace.bars'); - var barcount = s.size(); +var _$transitionAxes_230 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { var fullLayout = gd._fullLayout; + var axes = []; - // trace styling - s.style('opacity', function(d) { return d[0].trace.opacity; }) + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - // for gapless (either stacked or neighboring grouped) bars use - // crispEdges to turn off antialiasing so an artificial gap - // isn't introduced. - .each(function(d) { - if((fullLayout.barmode === 'stack' && barcount > 1) || - (fullLayout.bargap === 0 && - fullLayout.bargroupgap === 0 && - !d[0].trace.marker.line.width)) { - _$d3_10.select(this).attr('shape-rendering', 'crispEdges'); + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; + + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; + + update.axisName = axisName; + update.length = axis._length; + + axes.push(axisLetter); + + updates[axisLetter] = update; + } } - }); - s.selectAll('g.points').each(function(d) { - var sel = _$d3_10.select(this); - var pts = sel.selectAll('path'); - var txs = sel.selectAll('text'); - var trace = d[0].trace; + return updates; + } - _$drawing_71.pointStyle(pts, trace, gd); - _$drawing_71.selectedPointStyle(pts, trace); + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - txs.each(function(d) { - var tx = _$d3_10.select(this); - var textFont; + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - if(tx.classed('bartext-inside')) { - textFont = trace.insidetextfont; - } else if(tx.classed('bartext-outside')) { - textFont = trace.outsidetextfont; + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; + + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; } - if(!textFont) textFont = trace.textfont; - function cast(k) { - var cont = textFont[k]; - return Array.isArray(cont) ? cont[d.i] : cont; + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); } + } - _$drawing_71.font(tx, cast('family'), cast('size'), cast('color')); - }); + return affectedSubplots; + } - _$drawing_71.selectedTextStyle(txs, trace); - }); + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - _$registry_247.getComponentMethod('errorbars', 'style')(s); -}; + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -'use strict'; + redrawObjs(fullLayout.annotations || [], _$registry_248.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_248.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_248.getComponentMethod('images', 'draw'), true); + } -var _$constants_48 = { - cn: { - colorbar: 'colorbar', - cbbg: 'cbbg', - cbfill: 'cbfill', - cbfills: 'cbfills', - cbline: 'cbline', - cblines: 'cblines', - cbaxis: 'cbaxis', - cbtitleunshift: 'cbtitleunshift', - cbtitle: 'cbtitle', - cboutline: 'cboutline', - crisp: 'crisp', - jsPlaceholder: 'js-placeholder' + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; + activeAxIds = [xa._id, ya._id]; -'use strict'; + for(i = 0; i < activeAxIds.length; i++) { + _$axes_208.doTicks(gd, activeAxIds[i], true); + } -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$tinycolor_28 = require('tinycolor2'); */; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -var __extendFlat_50 = _$extend_159.extendFlat; -/* removed: var _$setCursor_184 = require('../../lib/setcursor'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$titles_139 = require('../titles'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -var __LINE_SPACING_50 = _$alignment_146.LINE_SPACING; + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } -/* removed: var _$handleAxisDefaults_209 = require('../../plots/cartesian/axis_defaults'); */; -/* removed: var _$handlePositionDefaults_223 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_219 = require('../../plots/cartesian/layout_attributes'); */; + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -/* removed: var _$attributes_47 = require('./attributes'); */; -var cn = _$constants_48.cn; + redrawObjs(fullLayout.annotations || [], _$registry_248.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_248.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_248.getComponentMethod('images', 'draw'), true); + } -var _$draw_50 = function draw(gd, id) { - // opts: options object, containing everything from attributes - // plus a few others that are the equivalent of the colorbar "data" - var opts = {}; - Object.keys(_$attributes_47).forEach(function(k) { - opts[k] = null; - }); - // fillcolor can be a d3 scale, domain is z values, range is colors - // or leave it out for no fill, - // or set to a string constant for single-color fill - opts.fillcolor = null; - // line.color has the same options as fillcolor - opts.line = {color: null, width: null, dash: null}; - // levels of lines to draw. - // note that this DOES NOT determine the extent of the bar - // that's given by the domain of fillcolor - // (or line.color if no fillcolor domain) - opts.levels = {start: null, end: null, size: null}; - // separate fill levels (for example, heatmap coloring of a - // contour map) if this is omitted, fillcolors will be - // evaluated halfway between levels - opts.filllevels = null; + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - function component() { - var fullLayout = gd._fullLayout, - gs = fullLayout._size; - if((typeof opts.fillcolor !== 'function') && - (typeof opts.line.color !== 'function')) { - fullLayout._infolayer.selectAll('g.' + id).remove(); - return; - } - var zrange = _$d3_10.extent(((typeof opts.fillcolor === 'function') ? - opts.fillcolor : opts.line.color).domain()); - var linelevels = []; - var filllevels = []; - var linecolormap = typeof opts.line.color === 'function' ? - opts.line.color : function() { return opts.line.color; }; - var fillcolormap = typeof opts.fillcolor === 'function' ? - opts.fillcolor : function() { return opts.fillcolor; }; - var l; - var i; + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_71.setTranslate, 0, 0) + .call(_$drawing_71.setScale, 1, 1); - var l0 = opts.levels.end + opts.levels.size / 100, - ls = opts.levels.size, - zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), - zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); - for(i = 0; i < 1e5; i++) { - l = opts.levels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zr0 && l < zr1) linelevels.push(l); - } + subplot.plot + .call(_$drawing_71.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_71.setScale, 1, 1); - if(typeof opts.fillcolor === 'function') { - if(opts.filllevels) { - l0 = opts.filllevels.end + opts.filllevels.size / 100; - ls = opts.filllevels.size; - for(i = 0; i < 1e5; i++) { - l = opts.filllevels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zrange[0] && l < zrange[1]) filllevels.push(l); - } - } - else { - filllevels = linelevels.map(function(v) { - return v - opts.levels.size / 2; - }); - filllevels.push(filllevels[filllevels.length - 1] + - opts.levels.size); - } - } - else if(opts.fillcolor && typeof opts.fillcolor === 'string') { - // doesn't matter what this value is, with a single value - // we'll make a single fill rect covering the whole bar - filllevels = [0]; - } + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); - if(opts.levels.size < 0) { - linelevels.reverse(); - filllevels.reverse(); - } + // 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_71.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_71.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_71.hideOutsideRangePoints, subplot); + } - // now make a Plotly Axes object to scale with and draw ticks - // TODO: does not support orientation other than right + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - // we calculate pixel sizes based on the specified graph size, - // not the actual (in case something pushed the margins around) - // which is a little odd but avoids an odd iterative effect - // when the colorbar itself is pushing the margins. - // but then the fractional size is calculated based on the - // actual graph size, so that the axes will size correctly. - var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, - originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, - thickPx = Math.round(opts.thickness * - (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), - thickFrac = thickPx / gs.w, - lenPx = Math.round(opts.len * - (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), - lenFrac = lenPx / gs.h, - xpadFrac = opts.xpad / gs.w, - yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, - ypadFrac = opts.ypad / gs.h, + var viewBox = []; - // x positioning: do it initially just for left anchor, - // then fix at the end (since we don't know the width yet) - xLeft = Math.round(opts.x * gs.w + opts.xpad), - // for dragging... this is getting a little muddled... - xLeftFrac = opts.x - thickFrac * - ({middle: 0.5, right: 1}[opts.xanchor]||0), + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - // y positioning we can do correctly from the start - yBottomFrac = opts.y + lenFrac * - (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), - yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), - yTopPx = yBottomPx - lenPx, - titleEl, - cbAxisIn = { - type: 'linear', - range: zrange, - tickmode: opts.tickmode, - nticks: opts.nticks, - tick0: opts.tick0, - dtick: opts.dtick, - tickvals: opts.tickvals, - ticktext: opts.ticktext, - ticks: opts.ticks, - ticklen: opts.ticklen, - tickwidth: opts.tickwidth, - tickcolor: opts.tickcolor, - showticklabels: opts.showticklabels, - tickfont: opts.tickfont, - tickangle: opts.tickangle, - tickformat: opts.tickformat, - exponentformat: opts.exponentformat, - separatethousands: opts.separatethousands, - showexponent: opts.showexponent, - showtickprefix: opts.showtickprefix, - tickprefix: opts.tickprefix, - showticksuffix: opts.showticksuffix, - ticksuffix: opts.ticksuffix, - title: opts.title, - titlefont: opts.titlefont, - showline: true, - anchor: 'free', - position: 1 - }, - cbAxisOut = { - type: 'linear', - _id: 'y' + id - }, - axisOptions = { - letter: 'y', - font: fullLayout.font, - noHover: true, - calendar: fullLayout.calendar // not really necessary (yet?) - }; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - // Coerce w.r.t. Axes layoutAttributes: - // re-use axes.js logic without updating _fullData - function coerce(attr, dflt) { - return _$lib_165.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_219, attr, dflt); + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; } - // Prepare the Plotly axis object - _$handleAxisDefaults_209(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); - _$handlePositionDefaults_223(cbAxisIn, cbAxisOut, coerce, axisOptions); - - // position can't go in through supplyDefaults - // because that restricts it to [0,1] - cbAxisOut.position = opts.x + xpadFrac + thickFrac; + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // save for other callers to access this axis - component.axis = cbAxisOut; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - cbAxisOut.titleside = opts.titleside; - cbAxisOut.titlex = opts.x + xpadFrac; - cbAxisOut.titley = yBottomFrac + - (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; } - if(opts.line.color && opts.tickmode === 'auto') { - cbAxisOut.tickmode = 'linear'; - cbAxisOut.tick0 = opts.levels.start; - var dtick = opts.levels.size; - // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_165.constrain( - (yBottomPx - yTopPx) / 50, 4, 15) + 1, - dtFactor = (zrange[1] - zrange[0]) / - ((opts.nticks || autoNtick) * dtick); - if(dtFactor > 1) { - var dtexp = Math.pow(10, Math.floor( - Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_165.roundUp(dtFactor / dtexp, [2, 5, 10]); - // if the contours are at round multiples, reset tick0 - // so they're still at round multiples. Otherwise, - // keep the first label on the first contour level - if((Math.abs(opts.levels.start) / - opts.levels.size + 1e-6) % 1 < 2e-6) { - cbAxisOut.tick0 = 0; - } - } - cbAxisOut.dtick = dtick; - } + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - // set domain after init, because we may want to - // allow it outside [0,1] - cbAxisOut.domain = [ - yBottomFrac + ypadFrac, - yBottomFrac + lenFrac - ypadFrac - ]; - cbAxisOut.setScale(); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_10.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); - container.attr('transform', 'translate(' + Math.round(gs.l) + - ',' + Math.round(gs.t) + ')'); - // TODO: this opposite transform is a hack until we make it - // more rational which items get this offset - var titleCont = container.select('.cbtitleunshift') - .attr('transform', 'translate(-' + - Math.round(gs.l) + ',-' + - Math.round(gs.t) + ')'); + var editX = !!xUpdate; + var editY = !!yUpdate; - cbAxisOut._axislayer = container.select('.cbaxis'); - var titleHeight = 0; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // draw the title so we know how much room it needs - // when we squish the axis. This one only applies to - // top or bottom titles, not right side. - var x = gs.l + (opts.x + xpadFrac) * gs.w, - fontSize = cbAxisOut.titlefont.size, - y; + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - if(opts.titleside === 'top') { - y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + - gs.t + 3 + fontSize * 0.75; - } - else { - y = (1 - (yBottomFrac + ypadFrac)) * gs.h + - gs.t - 3 - fontSize * 0.25; - } - drawTitle(cbAxisOut._id + 'title', { - attributes: {x: x, y: y, 'text-anchor': 'start'} - }); - } + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - function drawAxis() { - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // squish the axis top to make room for the title - var titleGroup = container.select('.cbtitle'), - titleText = titleGroup.select('text'), - titleTrans = - [-opts.outlinewidth / 2, opts.outlinewidth / 2], - mathJaxNode = titleGroup - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - lineSize = 15.6; - if(titleText.node()) { - lineSize = - parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_50; - } - if(mathJaxNode) { - titleHeight = _$drawing_71.bBox(mathJaxNode).height; - if(titleHeight > lineSize) { - // not entirely sure how mathjax is doing - // vertical alignment, but this seems to work. - titleTrans[1] -= (titleHeight - lineSize) / 2; - } - } - else if(titleText.node() && - !titleText.classed(cn.jsPlaceholder)) { - titleHeight = _$drawing_71.bBox(titleText.node()).height; - } - if(titleHeight) { - // buffer btwn colorbar and title - // TODO: configurable - titleHeight += 5; + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - if(opts.titleside === 'top') { - cbAxisOut.domain[1] -= titleHeight / gs.h; - titleTrans[1] *= -1; - } - else { - cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_186.lineCount(titleText); - titleTrans[1] += (1 - nlines) * lineSize; - } + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - titleGroup.attr('transform', - 'translate(' + titleTrans + ')'); + subplot.clipRect + .call(_$drawing_71.setTranslate, clipDx, clipDy) + .call(_$drawing_71.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - cbAxisOut.setScale(); - } - } + subplot.plot + .call(_$drawing_71.setTranslate, plotDx, plotDy) + .call(_$drawing_71.setScale, xScaleFactor, yScaleFactor) - container.selectAll('.cbfills,.cblines') - .attr('transform', 'translate(0,' + - Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_71.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - cbAxisOut._axislayer.attr('transform', 'translate(0,' + - Math.round(-gs.t) + ')'); + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_71.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + } - var fills = container.select('.cbfills') - .selectAll('rect.cbfill') - .data(filllevels); - fills.enter().append('rect') - .classed(cn.cbfill, true) - .style('stroke', 'none'); - fills.exit().remove(); - fills.each(function(d, i) { - var z = [ - (i === 0) ? zrange[0] : - (filllevels[i] + filllevels[i - 1]) / 2, - (i === filllevels.length - 1) ? zrange[1] : - (filllevels[i] + filllevels[i + 1]) / 2 - ] - .map(cbAxisOut.c2p) - .map(Math.round); + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } - // offset the side adjoining the next rectangle so they - // overlap, to prevent antialiasing gaps - if(i !== filllevels.length - 1) { - z[1] += (z[1] > z[0]) ? 1 : -1; - } + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; + axi.range = to.slice(); + } - // Tinycolor can't handle exponents and - // at this scale, removing it makes no difference. - var colorString = fillcolormap(d).replace('e-', ''), - opaqueColor = _$tinycolor_28(colorString).toHexString(); + // Signal that this transition has completed: + onComplete && onComplete(); - // Colorbar cannot currently support opacities so we - // use an opaque fill even when alpha channels present - _$d3_10.select(this).attr({ - x: xLeft, - width: Math.max(thickPx, 2), - y: _$d3_10.min(z), - height: Math.max(_$d3_10.max(z) - _$d3_10.min(z), 2), - fill: opaqueColor - }); - }); + return _$registry_248.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var lines = container.select('.cblines') - .selectAll('path.cbline') - .data(opts.line.color && opts.line.width ? - linelevels : []); - lines.enter().append('path') - .classed(cn.cbline, true); - lines.exit().remove(); - lines.each(function(d) { - _$d3_10.select(this) - .attr('d', 'M' + xLeft + ',' + - (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + - 'h' + thickPx) - .call(_$drawing_71.lineGroupStyle, - opts.line.width, linecolormap(d), opts.line.dash); - }); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; - // force full redraw of labels and ticks - cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') - .remove(); + axi.range = axi._r.slice(); + } - cbAxisOut._pos = xLeft + thickPx + - (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); - cbAxisOut.side = 'right'; + return _$registry_248.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - // separate out axis and title drawing, - // so we don't need such complicated logic in Titles.draw - // if title is on the top or bottom, we've already drawn it - // this title call only handles side=right - return _$lib_165.syncOrAsync([ - function() { - return _$axes_207.doTicks(gd, cbAxisOut, true); - }, - function() { - if(['top', 'bottom'].indexOf(opts.titleside) === -1) { - var fontSize = cbAxisOut.titlefont.size, - y = cbAxisOut._offset + cbAxisOut._length / 2, - x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? - 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : - -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); + var t1, t2, raf; + var easeFn = _$d3_10.ease(transitionOpts.easing); - // the 'h' + is a hack to get around the fact that - // convertToTspans rotates any 'y...' class by 90 degrees. - // TODO: find a better way to control this. - drawTitle('h' + cbAxisOut._id + 'title', { - avoid: { - selection: _$d3_10.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), - side: opts.titleside, - offsetLeft: gs.l, - offsetTop: 0, - maxShift: fullLayout.width - }, - attributes: {x: x, y: y, 'text-anchor': 'middle'}, - transform: {rotate: '-90', offset: 0} - }); - } - }]); - } + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); - function drawTitle(titleClass, titleOpts) { - var trace = getTrace(), - propName; - if(_$registry_247.traceIs(trace, 'markerColorscale')) { - propName = 'marker.colorbar.title'; - } - else propName = 'colorbar.title'; + function doFrame() { + t2 = Date.now(); - var dfltTitleOpts = { - propContainer: cbAxisOut, - propName: propName, - traceIndex: trace.index, - placeholder: fullLayout._dfltTitle.colorbar, - containerGroup: container.select('.cbtitle') - }; + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); - // this class-to-rotate thing with convertToTspans is - // getting hackier and hackier... delete groups with the - // wrong class (in case earlier the colorbar was drawn on - // a different side, I think?) - var otherClass = titleClass.charAt(0) === 'h' ? - titleClass.substr(1) : ('h' + titleClass); - container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') - .remove(); + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } - _$titles_139.draw(gd, titleClass, - __extendFlat_50(dfltTitleOpts, titleOpts || {})); + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); } + } - function positionCB() { - // wait for the axis & title to finish rendering before - // continuing positioning - // TODO: why are we redrawing multiple times now with this? - // I guess autoMargin doesn't like being post-promise? - var innerWidth = thickPx + opts.outlinewidth / 2 + - _$drawing_71.bBox(cbAxisOut._axislayer.node()).width; - titleEl = titleCont.select('text'); - if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { - var mathJaxNode = titleCont - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - titleWidth; - if(mathJaxNode && - ['top', 'bottom'].indexOf(opts.titleside) !== -1) { - titleWidth = _$drawing_71.bBox(mathJaxNode).width; - } - else { - // note: the formula below works for all titlesides, - // (except for top/bottom mathjax, above) - // but the weird gs.l is because the titleunshift - // transform gets removed by Drawing.bBox - titleWidth = - _$drawing_71.bBox(titleCont.node()).right - - xLeft - gs.l; - } - innerWidth = Math.max(innerWidth, titleWidth); - } - - var outerwidth = 2 * opts.xpad + innerWidth + - opts.borderwidth + opts.outlinewidth / 2, - outerheight = yBottomPx - yTopPx; - - container.select('.cbbg').attr({ - x: xLeft - opts.xpad - - (opts.borderwidth + opts.outlinewidth) / 2, - y: yTopPx - yExtraPx, - width: Math.max(outerwidth, 2), - height: Math.max(outerheight + 2 * yExtraPx, 2) - }) - .call(_$color_46.fill, opts.bgcolor) - .call(_$color_46.stroke, opts.bordercolor) - .style({'stroke-width': opts.borderwidth}); - - container.selectAll('.cboutline').attr({ - x: xLeft, - y: yTopPx + opts.ypad + - (opts.titleside === 'top' ? titleHeight : 0), - width: Math.max(thickPx, 2), - height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) - }) - .call(_$color_46.stroke, opts.outlinecolor) - .style({ - fill: 'None', - 'stroke-width': opts.outlinewidth - }); - - // fix positioning for xanchor!='left' - var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * - outerwidth; - container.attr('transform', - 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); - - // auto margin adjustment - _$plots_240.autoMargin(gd, id, { - x: opts.x, - y: opts.y, - l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), - r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), - t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), - b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) - }); - } - - var cbDone = _$lib_165.syncOrAsync([ - _$plots_240.previousPromises, - drawAxis, - _$plots_240.previousPromises, - positionCB - ], gd); - - if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); - - // dragging... - if(gd._context.edits.colorbarPosition) { - var t0, - xf, - yf; - - _$dragelement_68.init({ - element: container.node(), - gd: gd, - prepFn: function() { - t0 = container.attr('transform'); - _$setCursor_184(container); - }, - moveFn: function(dx, dy) { - container.attr('transform', - t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); - - xf = _$dragelement_68.align(xLeftFrac + (dx / gs.w), thickFrac, - 0, 1, opts.xanchor); - yf = _$dragelement_68.align(yBottomFrac - (dy / gs.h), lenFrac, - 0, 1, opts.yanchor); - - var csr = _$dragelement_68.getCursor(xf, yf, - opts.xanchor, opts.yanchor); - _$setCursor_184(container, csr); - }, - doneFn: function() { - _$setCursor_184(container); - - if(xf !== undefined && yf !== undefined) { - _$registry_247.call('restyle', - gd, - {'colorbar.x': xf, 'colorbar.y': yf}, - getTrace().index - ); - } - } - }); - } - return cbDone; - } - - function getTrace() { - var idNum = id.substr(2), - i, - trace; - for(i = 0; i < gd._fullData.length; i++) { - trace = gd._fullData[i]; - if(trace.uid === idNum) return trace; - } - } - - // setter/getters for every item defined in opts - Object.keys(opts).forEach(function(name) { - component[name] = function(v) { - // getter - if(!arguments.length) return opts[name]; - - // setter - for multi-part properties, - // set only the parts that are provided - opts[name] = _$lib_165.isPlainObject(opts[name]) ? - _$lib_165.extendFlat(opts[name], v) : - v; - - return component; - }; - }); - - // or use .options to set multiple options at once via a dictionary - component.options = function(o) { - Object.keys(o).forEach(function(name) { - // in case something random comes through - // that's not an option, ignore it - if(typeof component[name] === 'function') { - component[name](o[name]); - } - }); - return component; - }; - - component._opts = opts; + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - return component; + return Promise.resolve(); }; +var _$get_data_236 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -36265,292 +36730,112 @@ var _$draw_50 = function draw(gd, id) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$colorscale_61 = require('../../components/colorscale'); */; -/* removed: var _$draw_50 = require('../../components/colorbar/draw'); */; - +/* removed: var _$registry_248 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_213.SUBPLOT_PATTERN; -var _$colorbar_321 = function colorbar(gd, cd) { - var trace = cd[0].trace, - marker = trace.marker, - cbId = 'cb' + trace.uid; +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_236.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_248.subplotsRegistry[type]; + if(!basePlotModule) return []; - gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); + var attr = basePlotModule.attr; + var subplotCalcData = []; - // TODO make Colorbar.draw support multiple colorbar per trace + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; - if((marker === undefined) || !marker.showscale) { - _$plots_240.autoMargin(gd, cbId); - return; + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); } - var vals = marker.color, - cmin = marker.cmin, - cmax = marker.cmax; - - if(!_$fastIsnumeric_13(cmin)) cmin = _$lib_165.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_13(cmax)) cmax = _$lib_165.aggNums(Math.max, null, vals); - - var cb = cd[0].t.cb = _$draw_50(gd, cbId); - var sclFunc = _$colorscale_61.makeColorScaleFunc( - _$colorscale_61.extractScale( - marker.colorscale, - cmin, - cmax - ), - { noNumericCheck: true } - ); - - cb.fillcolor(sclFunc) - .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) - .options(marker.colorbar)(); + return subplotCalcData; }; - /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_236.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_248.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; -var Bar = {}; + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; -Bar.attributes = _$attributes_257; -Bar.layoutAttributes = _$layout_attributes_262; -Bar.supplyDefaults = _$supplyDefaults_259; -Bar.supplyLayoutDefaults = _$layout_defaults_263; -Bar.calc = _$calc_258; -Bar.setPositions = _$setPositions_266; -Bar.colorbar = _$colorbar_321; -Bar.arraysToCalcdata = _$arraysToCalcdata_256; -Bar.plot = _$plot_264; -Bar.style = _$style_268; -Bar.hoverPoints = _$hoverPoints_260; -Bar.selectPoints = _$selectPoints_265; + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } + } -Bar.moduleType = 'trace'; -Bar.name = 'bar'; -Bar.basePlotModule = _$cartesian_218; -Bar.categories = ['cartesian', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend']; -Bar.meta = { - + return [moduleCalcData, remainingCalcData]; }; -var _$Bar_261 = Bar; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$bar_3 = _$Bar_261; - /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_317 = require('../scatter/attributes'); */; -/* removed: var _$attributes_45 = require('../../components/color/attributes'); */; -var __extendFlat_270 = _$extend_159.extendFlat; + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_236.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_248.subplotsRegistry[type]) return []; -var __scatterMarkerAttrs_270 = _$attributes_317.marker; -var __scatterMarkerLineAttrs_270 = __scatterMarkerAttrs_270.line; + var attr = _$registry_248.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; -var _$attributes_270 = { - 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', - - }, - name: { - valType: 'string', - - editType: 'calc+clearAxisTypes', - - }, - text: __extendFlat_270({}, _$attributes_317.text, { - - }), - whiskerwidth: { - valType: 'number', - min: 0, - max: 1, - dflt: 0.5, - - editType: 'calcIfAutorange', - - }, - notched: { - valType: 'boolean', - - editType: 'calcIfAutorange', - - }, - notchwidth: { - valType: 'number', - min: 0, - max: 0.5, - dflt: 0.25, - - editType: 'calcIfAutorange', - - }, - boxpoints: { - valType: 'enumerated', - values: ['all', 'outliers', 'suspectedoutliers', false], - dflt: 'outliers', - - editType: 'calcIfAutorange', - - }, - boxmean: { - valType: 'enumerated', - values: [true, 'sd', false], - dflt: false, - - editType: 'calcIfAutorange', - - }, - jitter: { - valType: 'number', - min: 0, - max: 1, - - editType: 'calcIfAutorange', - - }, - pointpos: { - valType: 'number', - min: -2, - max: 2, - - editType: 'calcIfAutorange', - - }, - orientation: { - valType: 'enumerated', - values: ['v', 'h'], - - editType: 'calc+clearAxisTypes', - - }, - marker: { - outliercolor: { - valType: 'color', - dflt: 'rgba(0, 0, 0, 0)', - - editType: 'style', - - }, - symbol: __extendFlat_270({}, __scatterMarkerAttrs_270.symbol, - {arrayOk: false, editType: 'plot'}), - opacity: __extendFlat_270({}, __scatterMarkerAttrs_270.opacity, - {arrayOk: false, dflt: 1, editType: 'style'}), - size: __extendFlat_270({}, __scatterMarkerAttrs_270.size, - {arrayOk: false, editType: 'calcIfAutorange'}), - color: __extendFlat_270({}, __scatterMarkerAttrs_270.color, - {arrayOk: false, editType: 'style'}), - line: { - color: __extendFlat_270({}, __scatterMarkerLineAttrs_270.color, - {arrayOk: false, dflt: _$attributes_45.defaultLine, editType: 'style'} - ), - width: __extendFlat_270({}, __scatterMarkerLineAttrs_270.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: _$attributes_317.fillcolor, + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } - selected: { - marker: _$attributes_317.selected.marker, - editType: 'style' - }, - unselected: { - marker: _$attributes_317.unselected.marker, - editType: 'style' - }, + for(var i = 0; i < data.length; i++) { + trace = data[i]; - hoveron: { - valType: 'flaglist', - flags: ['boxes', 'points'], - dflt: 'boxes+points', - - editType: 'style', - + if(type === 'gl2d' && _$registry_248.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); + } + } + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } } + + return subplotData; }; +var _$cartesian_219 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -36559,602 +36844,597 @@ var _$attributes_270 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; - -/* removed: var _$lib_165 = require('../../lib'); */; -var ____271 = _$lib_165._; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html -var _$calc_271 = function calc(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = _$axes_207.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_207.getFromId(gd, trace.yaxis || 'y'); - var cd = []; +'use strict'; - // N.B. violin reuses same Box.calc - var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes'; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$plots_240 = require('../plots'); */; +var getModuleCalcData = _$get_data_236.getModuleCalcData; - var i; - var valAxis, valLetter; - var posAxis, posLetter; +/* removed: var _$axis_ids_211 = require('./axis_ids'); */; +/* removed: var _$constants_213 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_150 = require('../../constants/xmlns_namespaces'); */; - if(trace.orientation === 'h') { - valAxis = xa; - valLetter = 'x'; - posAxis = ya; - posLetter = 'y'; - } else { - valAxis = ya; - valLetter = 'y'; - posAxis = xa; - posLetter = 'x'; - } +var ensureSingle = _$lib_166.ensureSingle; - var val = valAxis.makeCalcdata(trace, valLetter); - var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]); +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_166.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} - var dv = _$lib_165.distinctVals(pos); - var posDistinct = dv.vals; - var dPos = dv.minDiff / 2; - var posBins = makeBins(posDistinct, dPos); +_$cartesian_219.name = 'cartesian'; - var vLen = val.length; - var pLen = posDistinct.length; - var ptsPerBin = initNestedArray(pLen); +_$cartesian_219.attr = ['xaxis', 'yaxis']; - // bin pts info per position bins - for(i = 0; i < vLen; i++) { - var v = val[i]; - if(!_$fastIsnumeric_13(v)) continue; +_$cartesian_219.idRoot = ['x', 'y']; - var n = _$lib_165.findBin(pos[i], posBins); - if(n >= 0 && n < pLen) { - var pt = {v: v, i: i}; - __arraysToCalcdata_271(pt, trace, i); - ptsPerBin[n].push(pt); - } - } +_$cartesian_219.idRegex = _$constants_213.idRegex; - // build calcdata trace items, one item per distinct position - for(i = 0; i < pLen; i++) { - if(ptsPerBin[i].length > 0) { - var pts = ptsPerBin[i].sort(sortByVal); - var boxVals = pts.map(extractVal); - var bvLen = boxVals.length; +_$cartesian_219.attrRegex = _$constants_213.attrRegex; - var cdi = { - pos: posDistinct[i], - pts: pts - }; +_$cartesian_219.attributes = _$attributes_206; - cdi.min = boxVals[0]; - cdi.max = boxVals[bvLen - 1]; - cdi.mean = _$lib_165.mean(boxVals, bvLen); - cdi.sd = _$lib_165.stdev(boxVals, bvLen, cdi.mean); - - // first quartile - cdi.q1 = _$lib_165.interp(boxVals, 0.25); - // median - cdi.med = _$lib_165.interp(boxVals, 0.5); - // third quartile - cdi.q3 = _$lib_165.interp(boxVals, 0.75); - - // lower and upper fences - last point inside - // 1.5 interquartile ranges from quartiles - cdi.lf = Math.min( - cdi.q1, - boxVals[Math.min( - _$lib_165.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, - bvLen - 1 - )] - ); - cdi.uf = Math.max( - cdi.q3, - boxVals[Math.max( - _$lib_165.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), - 0 - )] - ); +_$cartesian_219.layoutAttributes = _$layout_attributes_220; - // lower and upper outliers - 3 IQR out (don't clip to max/min, - // this is only for discriminating suspected & far outliers) - cdi.lo = 4 * cdi.q1 - 3 * cdi.q3; - cdi.uo = 4 * cdi.q3 - 3 * cdi.q1; +_$cartesian_219.supplyLayoutDefaults = _$supplyLayoutDefaults_221; +_$cartesian_219.transitionAxes = _$transitionAxes_230; - // lower and upper notches ~95% Confidence Intervals for median - var iqr = cdi.q3 - cdi.q1; - var mci = 1.57 * iqr / Math.sqrt(bvLen); - cdi.ln = cdi.med - mci; - cdi.un = cdi.med + mci; +_$cartesian_219.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - cd.push(cdi); - } + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; } - __calcSelection_271(cd, trace); - _$axes_207.expand(valAxis, val, {padded: true}); + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_211.id2name(xi)] || {}).anchor; + if(!_$constants_213.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - if(cd.length > 0) { - cd[0].t = { - num: fullLayout[numKey], - dPos: dPos, - posLetter: posLetter, - valLetter: valLetter, - labels: { - med: ____271(gd, 'median:'), - min: ____271(gd, 'min:'), - q1: ____271(gd, 'q1:'), - q3: ____271(gd, 'q3:'), - max: ____271(gd, 'max:'), - mean: trace.boxmean === 'sd' ? ____271(gd, 'mean ± σ:') : ____271(gd, 'mean:'), - lf: ____271(gd, 'lower fence:'), - uf: ____271(gd, 'upper fence:') + if(!allY[yi]) { + allY[yi] = 1; + _$lib_166.pushUnique(yList, yi); } - }; - - // don't show labels in candlestick hover labels - if(trace._fullInput && trace._fullInput.type === 'candlestick') { - delete cd[0].t.labels; } - - 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, val, num) { - if(posLetter in trace) { - return posAxis.makeCalcdata(trace, posLetter); } - var pos0; + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_211.id2name(yi)] || {}).anchor; + if(!_$constants_213.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - if(posLetter + '0' in trace) { - pos0 = trace[posLetter + '0']; - } else if('name' in trace && ( - posAxis.type === 'category' || ( - _$fastIsnumeric_13(trace.name) && - ['linear', 'log'].indexOf(posAxis.type) !== -1 - ) || ( - _$lib_165.isDateTime(trace.name) && - posAxis.type === 'date' - ) - )) { - pos0 = trace.name; - } else { - pos0 = num; + if(!allX[xi]) { + allX[xi] = 1; + _$lib_166.pushUnique(xList, xi); + } + } } - var pos0c = posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']); - return val.map(function() { return pos0c; }); -} - -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; + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_213.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } + } + xi = xi ? _$axis_ids_211.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_211.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; - return bins; -} +_$cartesian_219.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; -function initNestedArray(len) { - var arr = new Array(len); - for(var i = 0; i < len; i++) { - arr[i] = []; + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; + + for(i = 0; i < calcdata.length; i++) { + traces.push(i); + } } - return arr; -} -function __arraysToCalcdata_271(pt, trace, i) { - var trace2calc = { - text: 'tx' - }; + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; + + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; + + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; + + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - for(var k in trace2calc) { - if(Array.isArray(trace[k])) { - pt[trace2calc[k]] = trace[k][i]; + cdSubplot.push(cd); + } + + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } } + + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); } -} +}; -function __calcSelection_271(cd, trace) { - if(_$lib_165.isArrayOrTypedArray(trace.selectedpoints)) { - for(var i = 0; i < cd.length; i++) { - var pts = cd[i].pts || []; - var ptNumber2cdIndex = {}; +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; - for(var j = 0; j < pts.length; j++) { - ptNumber2cdIndex[pts[j].i] = j; - } + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); + } - _$lib_165.tagSelected(pts, trace, ptNumber2cdIndex); - } + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; + + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; + + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; + + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); } } -function sortByVal(a, b) { return a.v - b.v; } +_$cartesian_219.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; -function extractVal(o) { return o.v; } + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); + } + } -'use strict'; + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$color_46 = require('../../components/color'); */; + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } -/* removed: var _$attributes_270 = require('./attributes'); */; + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); -function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_270, attr, dflt); - } + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } - handleSampleDefaults(traceIn, traceOut, coerce, layout); - if(traceOut.visible === false) return; + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } - coerce('line.color', (traceIn.marker || {}).color || defaultColor); - coerce('line.width'); - coerce('fillcolor', _$color_46.addOpacity(traceOut.line.color, 0.5)); + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - coerce('whiskerwidth'); - coerce('boxmean'); + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } + } - var notched = coerce('notched', traceIn.notchwidth !== undefined); - if(notched) coerce('notchwidth'); + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - handlePointsDefaults(traceIn, traceOut, coerce, {prefix: 'box'}); -} + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); -function handleSampleDefaults(traceIn, traceOut, coerce, layout) { - var y = coerce('y'); - var x = coerce('x'); + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + } + } + } - var defaultOrientation; + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - if(y && y.length) { - defaultOrientation = 'v'; - if(!x) coerce('x0'); - } else if(x && x.length) { - defaultOrientation = 'h'; - coerce('y0'); - } else { - traceOut.visible = false; - return; + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } } +}; - var handleCalendarDefaults = _$registry_247.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); +_$cartesian_219.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); - coerce('orientation', defaultOrientation); -} + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_166.identity); -function handlePointsDefaults(traceIn, traceOut, coerce, opts) { - var prefix = opts.prefix; + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); - var outlierColorDflt = _$lib_165.coerce2(traceIn, traceOut, _$attributes_270, 'marker.outliercolor'); - var lineoutliercolor = coerce('marker.line.outliercolor'); + subplotLayers.order(); - var points = coerce( - prefix + 'points', - (outlierColorDflt || lineoutliercolor) ? 'suspectedoutliers' : undefined - ); + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); + + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; + + // keep ref to plot group + plotinfo.plotgroup = _$d3_10.select(this); - if(points) { - coerce('jitter', points === 'all' ? 0.3 : 0); - coerce('pointpos', points === 'all' ? -1.5 : 0); + // initialize list of overlay subplots + plotinfo.overlays = []; - coerce('marker.symbol'); - coerce('marker.opacity'); - coerce('marker.size'); - coerce('marker.color', traceOut.line.color); - coerce('marker.line.color'); - coerce('marker.line.width'); + makeSubplotLayer(gd, plotinfo); - if(points === 'suspectedoutliers') { - coerce('marker.line.outliercolor', traceOut.marker.color); - coerce('marker.line.outlierwidth'); + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); } - coerce('selected.marker.color'); - coerce('unselected.marker.color'); - coerce('selected.marker.size'); - coerce('unselected.marker.size'); + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; - coerce('text'); - } else { - delete traceOut.marker; +_$cartesian_219.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_240.style(gd); +}; + +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; + + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; + + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; + } } - coerce('hoveron'); + // main subplots before overlays + subplotData = subplotData.concat(overlays); - _$lib_165.coerceSelectionMarkerOpacity(traceOut, coerce); + return subplotData; } -var _$defaults_272 = { - supplyDefaults: supplyDefaults, - handleSampleDefaults: handleSampleDefaults, - handlePointsDefaults: handlePointsDefaults -}; +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_213.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_213.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); -'use strict'; + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$fx_88 = require('../../components/fx'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$fillHoverText_325 = require('../scatter/fill_hover_text'); */; + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); -function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - var hoveron = trace.hoveron; - var closeBoxData = []; - var closePtData; + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - if(hoveron.indexOf('boxes') !== -1) { - closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode)); - } + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); - if(hoveron.indexOf('points') !== -1) { - closePtData = hoverOnPoints(pointData, xval, yval); - } + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); - // If there's a point in range and hoveron has points, show the best single point only. - // If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats. - if(hovermode === 'closest') { - if(closePtData) return [closePtData]; - return closeBoxData; - } + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); - // Otherwise in compare mode, allow a point AND the box stats to be labeled - // If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them. - if(closePtData) { - closeBoxData.push(closePtData); - return closeBoxData; + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } - return closeBoxData; -} + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; -function hoverOnBoxes(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var xa = pointData.xa; - var ya = pointData.ya; - var trace = cd[0].trace; - var t = cd[0].t; - var isViolin = trace.type === 'violin'; - var closeBoxData = []; + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. - var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos, - hoverPseudoDistance, spikePseudoDistance; + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - var boxDelta = t.bdPos; - var shiftPos = function(di) { return di.pos + t.bPos - pVal; }; + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - if(isViolin && trace.side !== 'both') { - if(trace.side === 'positive') { - dPos = function(di) { - var pos = shiftPos(di); - return _$fx_88.inbox(pos, pos + boxDelta, hoverPseudoDistance); - }; - } - if(trace.side === 'negative') { - dPos = function(di) { - var pos = shiftPos(di); - return _$fx_88.inbox(pos - boxDelta, pos, hoverPseudoDistance); - }; - } - } else { - dPos = function(di) { - var pos = shiftPos(di); - return _$fx_88.inbox(pos - boxDelta, pos + boxDelta, hoverPseudoDistance); - }; - } + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - var dVal; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - if(isViolin) { - dVal = function(di) { - return _$fx_88.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); - }; - } else { - dVal = function(di) { - return _$fx_88.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); - }; + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); } - if(trace.orientation === 'h') { - vVal = xval; - pVal = yval; - dx = dVal; - dy = dPos; - pLetter = 'y'; - pAxis = ya; - vLetter = 'x'; - vAxis = xa; - } else { - vVal = yval; - pVal = xval; - dx = dPos; - dy = dVal; - pLetter = 'x'; - pAxis = xa; - vLetter = 'y'; - vAxis = ya; - } + // common attributes for all subplots, overlays or not - // if two boxes are overlaying, let the narrowest one win - var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0]))); - hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; - spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_211.idSort); - function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_88.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_88.getClosest(cd, distfn, pointData); + for(var i = 0; i < _$constants_213.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_213.traceLayerClasses[i]); + } + } - // skip the rest (for this trace) if we didn't find a close point - // and create the item(s) in closedata for this point - if(pointData.index === false) return []; + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - var di = cd[pointData.index]; - var lc = trace.line.color; - var mc = (trace.marker || {}).color; + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - if(_$color_46.opacity(lc) && trace.line.width) pointData.color = lc; - else if(_$color_46.opacity(mc) && trace.boxpoints) pointData.color = mc; - else pointData.color = trace.fillcolor; +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - t.bdPos, true); - pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + t.bdPos, true); + var overlayIdsToRemove = {}; - _$axes_207.tickText(pAxis, pAxis.c2l(di.pos), 'hover').text; - pointData[pLetter + 'LabelVal'] = di.pos; + layers.each(function(subplotId) { + var plotgroup = _$d3_10.select(this); - var spikePosAttr = pLetter + 'Spike'; - pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; - pointData[spikePosAttr] = pAxis.c2p(di.pos, true); + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - // box plots: each "point" gets many labels - var usedVals = {}; - var attrs = ['med', 'min', 'q1', 'q3', 'max']; + overlayIdsToRemove[subplotId] = true; - if(trace.boxmean || (trace.meanline || {}).visible) { - attrs.push('mean'); - } - if(trace.boxpoints || trace.points) { - attrs.push('lf', 'uf'); - } + // do not remove individual axis s here + // as other subplots may need them + }); - for(var i = 0; i < attrs.length; i++) { - var attr = attrs[i]; + // must remove overlaid subplot trace layers 'manually' - if(!(attr in di) || (di[attr] in usedVals)) continue; - usedVals[di[attr]] = true; + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); - // copy out to a new object for each value to label - var val = di[attr]; - var valPx = vAxis.c2p(val, true); - var pointData2 = _$lib_165.extendFlat({}, pointData); + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx; - pointData2[vLetter + 'LabelVal'] = val; - pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_207.hoverLabelText(vAxis, val); + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; - if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') { - pointData2[vLetter + 'err'] = di.sd; + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } } - // only keep name and spikes on the first item (median) - pointData.name = ''; - pointData.spikeDistance = undefined; - pointData[spikePosAttr] = undefined; - - closeBoxData.push(pointData2); } +} - return closeBoxData; +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); } -function hoverOnPoints(pointData, xval, yval) { - var cd = pointData.cd; - var xa = pointData.xa; - var ya = pointData.ya; - var trace = cd[0].trace; - var xPx = xa.c2p(xval); - var yPx = ya.c2p(yval); - var closePtData; +_$cartesian_219.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_10.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - var dx = function(di) { - var rad = Math.max(3, di.mrc || 0); - return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad); - }; - var dy = function(di) { - var rad = Math.max(3, di.mrc || 0); - return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad); - }; - var distfn = _$fx_88.quadrature(dx, dy); + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); + + image.attr({ + xmlns: _$xmlns_namespaces_150.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); + } - // show one point per trace - var ijClosest = false; - var di, pt; + canvases.each(canvasToImage); +}; - for(var i = 0; i < cd.length; i++) { - di = cd[i]; +_$cartesian_219.updateFx = _$graph_interact_217.updateFx; - for(var j = 0; j < (di.pts || []).length; j++) { - pt = di.pts[j]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 newDistance = distfn(pt); - if(newDistance <= pointData.distance) { - pointData.distance = newDistance; - ijClosest = [i, j]; - } - } - } - if(!ijClosest) return false; +'use strict'; - di = cd[ijClosest[0]]; - pt = di.pts[ijClosest[1]]; +var mergeArray = _$lib_166.mergeArray; - var xc = xa.c2p(pt.x, true); - var yc = ya.c2p(pt.y, true); - var rad = pt.mrc || 1; - closePtData = _$lib_165.extendFlat({}, pointData, { - // corresponds to index in x/y input data array - index: pt.i, - color: (trace.marker || {}).color, - name: trace.name, - x0: xc - rad, - x1: xc + rad, - xLabelVal: pt.x, - y0: yc - rad, - y1: yc + rad, - yLabelVal: pt.y, - spikeDistance: pointData.distance - }); - var pLetter = trace.orientation === 'h' ? 'y' : 'x'; - var pa = trace.orientation === 'h' ? ya : xa; - closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true); - _$fillHoverText_325(pt, trace, closePtData); +// arrayOk attributes, merge them into calcdata array +var _$arraysToCalcdata_257 = function arraysToCalcdata(cd, trace) { + for(var i = 0; i < cd.length; i++) cd[i].i = i; - return closePtData; -} + mergeArray(trace.text, cd, 'tx'); + mergeArray(trace.hovertext, cd, 'htx'); + + var marker = trace.marker; + if(marker) { + mergeArray(marker.opacity, cd, 'mo'); + mergeArray(marker.color, cd, 'mc'); -var _$hover_273 = { - hoverPoints: hoverPoints, - hoverOnBoxes: hoverOnBoxes, - hoverOnPoints: hoverOnPoints + var markerLine = marker.line; + if(markerLine) { + mergeArray(markerLine.color, cd, 'mlc'); + mergeArray(markerLine.width, cd, 'mlw'); + } + } }; /** @@ -37167,33 +37447,162 @@ var _$hover_273 = { 'use strict'; +/* removed: var _$attributes_315 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_54 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_47 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; + +var __extendFlat_258 = _$extend_160.extendFlat; -var _$layout_attributes_275 = { - boxmode: { +var textFontAttrs = _$font_attributes_234({ + editType: 'calc', + arrayOk: true, + +}); + +var __scatterMarkerAttrs_258 = _$attributes_315.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_258.line; + +var markerLineWidth = __extendFlat_258({}, + scatterMarkerLineAttrs.width, { dflt: 0 }); + +var markerLine = __extendFlat_258({ + width: markerLineWidth, + editType: 'calc' +}, _$makeColorScaleAttributes_54('marker.line')); + +var marker = __extendFlat_258({ + line: markerLine, + editType: 'calc' +}, _$makeColorScaleAttributes_54('marker'), { + showscale: __scatterMarkerAttrs_258.showscale, + colorbar: _$attributes_47, + opacity: { + valType: 'number', + arrayOk: true, + dflt: 1, + min: 0, + max: 1, + + editType: 'style', + + } +}); + +var _$attributes_258 = { + x: _$attributes_315.x, + x0: _$attributes_315.x0, + dx: _$attributes_315.dx, + y: _$attributes_315.y, + y0: _$attributes_315.y0, + dy: _$attributes_315.dy, + + text: _$attributes_315.text, + hovertext: _$attributes_315.hovertext, + + textposition: { valType: 'enumerated', - values: ['group', 'overlay'], - dflt: 'overlay', + values: ['inside', 'outside', 'auto', 'none'], + dflt: 'none', + arrayOk: true, editType: 'calc', }, - boxgap: { + + textfont: __extendFlat_258({}, textFontAttrs, { + + }), + + insidetextfont: __extendFlat_258({}, textFontAttrs, { + + }), + + outsidetextfont: __extendFlat_258({}, textFontAttrs, { + + }), + + constraintext: { + valType: 'enumerated', + values: ['inside', 'outside', 'both', 'none'], + + dflt: 'both', + editType: 'calc', + + }, + + cliponaxis: __extendFlat_258({}, _$attributes_315.cliponaxis, { + + }), + + orientation: { + valType: 'enumerated', + + values: ['v', 'h'], + editType: 'calc+clearAxisTypes', + + }, + + base: { + valType: 'any', + dflt: null, + arrayOk: true, + + editType: 'calc', + + }, + + offset: { valType: 'number', - min: 0, - max: 1, - dflt: 0.3, + dflt: null, + arrayOk: true, editType: 'calc', }, - boxgroupgap: { + + width: { valType: 'number', + dflt: null, min: 0, - max: 1, - dflt: 0.3, + arrayOk: true, editType: 'calc', + }, + + marker: marker, + + selected: { + marker: { + opacity: _$attributes_315.selected.marker.opacity, + color: _$attributes_315.selected.marker.color, + editType: 'style' + }, + textfont: _$attributes_315.selected.textfont, + editType: 'style' + }, + unselected: { + marker: { + opacity: _$attributes_315.unselected.marker.opacity, + color: _$attributes_315.unselected.marker.color, + editType: 'style' + }, + textfont: _$attributes_315.unselected.textfont, + editType: 'style' + }, + + r: _$attributes_315.r, + t: _$attributes_315.t, + + _deprecated: { + bardir: { + valType: 'enumerated', + + editType: 'calc', + values: ['v', 'h'], + + } } }; @@ -37207,34 +37616,12 @@ var _$layout_attributes_275 = { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$layout_attributes_275 = require('./layout_attributes'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { - var hasTraceType; - for(var i = 0; i < fullData.length; i++) { - if(fullData[i].type === traceType) { - 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_165.coerce(layoutIn, layoutOut, _$layout_attributes_275, attr, dflt); +var _$calcSelection_317 = function calcSelection(cd, trace) { + if(_$lib_166.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_166.tagSelected(cd, trace); } - _supply(layoutIn, layoutOut, fullData, coerce, 'box'); -} - -var _$layout_defaults_276 = { - supplyLayoutDefaults: supplyLayoutDefaults, - _supply: _supply }; /** @@ -37245,313 +37632,99 @@ var _$layout_defaults_276 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$d3_10 = require('d3'); */; +'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_259 = _$lib_166.isArrayOrTypedArray; -// constants for dynamic jitter (ie less jitter for sparser points) -var JITTERCOUNT = 5; // points either side of this to include -var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense" +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_53 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_257 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_317 = require('../scatter/calc_selection'); */; -function plot(gd, plotinfo, cdbox) { - var fullLayout = gd._fullLayout; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; +var _$calc_259 = function calc(gd, trace) { + // depending on bar direction, set position and size axes + // and data ranges + // note: this logic for choosing orientation is + // duplicated in graph_obj->setstyles - var boxtraces = plotinfo.plot.select('.boxlayer') - .selectAll('g.trace.boxes') - .data(cdbox) - .enter().append('g') - .attr('class', 'trace boxes'); + var xa = _$axes_208.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_208.getFromId(gd, trace.yaxis || 'y'), + orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), + sa, pos, size, i, scalendar; - boxtraces.each(function(d) { - var cd0 = d[0]; - var t = cd0.t; - var trace = cd0.trace; - var sel = cd0.node3 = _$d3_10.select(this); - var numBoxes = fullLayout._numBoxes; + if(orientation === 'h') { + sa = xa; + size = xa.makeCalcdata(trace, 'x'); + pos = ya.makeCalcdata(trace, 'y'); - var group = (fullLayout.boxmode === 'group' && numBoxes > 1); - // box half width - var bdPos = t.dPos * (1 - fullLayout.boxgap) * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); - // box center offset - var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * (1 - fullLayout.boxgap) : 0; - // whisker width - var wdPos = bdPos * trace.whiskerwidth; + // 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. + scalendar = trace.xcalendar; + } + else { + sa = ya; + size = ya.makeCalcdata(trace, 'y'); + pos = xa.makeCalcdata(trace, 'x'); + scalendar = trace.ycalendar; + } - if(trace.visible !== true || t.empty) { - _$d3_10.select(this).remove(); - return; - } + // create the "calculated data" to plot + var serieslen = Math.min(pos.length, size.length); + var cd = new Array(serieslen); - var posAxis, valAxis; + // set position and size + for(i = 0; i < serieslen; i++) { + cd[i] = { p: pos[i], s: size[i] }; - if(trace.orientation === 'h') { - posAxis = ya; - valAxis = xa; - } else { - posAxis = xa; - valAxis = ya; + if(trace.ids) { + cd[i].id = String(trace.ids[i]); } + } - // save the box size and box position for use by hover - t.bPos = bPos; - t.bdPos = bdPos; - t.wdPos = wdPos; - - // boxes and whiskers - plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, t); + // set base + var base = trace.base, + b; - // draw points, if desired - if(trace.boxpoints) { - plotPoints(sel, {x: xa, y: ya}, trace, t); + if(__isArrayOrTypedArray_259(base)) { + for(i = 0; i < Math.min(base.length, cd.length); i++) { + b = sa.d2c(base[i], 0, scalendar); + if(_$fastIsnumeric_13(b)) { + cd[i].b = +b; + cd[i].hasB = 1; + } + else cd[i].b = 0; } - - // draw mean (and stdev diamond) if desired - if(trace.boxmean) { - plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, t); + for(; i < cd.length; i++) { + cd[i].b = 0; } - }); -} - -function plotBoxAndWhiskers(sel, axes, trace, t) { - var posAxis = axes.pos; - var valAxis = axes.val; - var bPos = t.bPos; - var wdPos = t.wdPos || 0; - var bPosPxOffset = t.bPosPxOffset || 0; - var whiskerWidth = trace.whiskerwidth || 0; - var notched = trace.notched || false; - var nw = notched ? 1 - 2 * trace.notchwidth : 1; - - // to support for one-sided box - var bdPos0; - var bdPos1; - if(Array.isArray(t.bdPos)) { - bdPos0 = t.bdPos[0]; - bdPos1 = t.bdPos[1]; - } else { - bdPos0 = t.bdPos; - bdPos1 = t.bdPos; } - - sel.selectAll('path.box') - .data(_$lib_165.identity) - .enter().append('path') - .style('vector-effect', 'non-scaling-stroke') - .attr('class', 'box') - .each(function(d) { - var pos = d.pos; - var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset; - var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset; - var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset; - var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset; - var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset; - var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset; - var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset; - var q1 = valAxis.c2p(d.q1, true); - var q3 = valAxis.c2p(d.q3, true); - // make sure median isn't identical to either of the - // quartiles, so we can see it - var m = _$lib_165.constrain( - valAxis.c2p(d.med, true), - Math.min(q1, q3) + 1, Math.max(q1, q3) - 1 - ); - var lf = valAxis.c2p(trace.boxpoints === false ? d.min : d.lf, true); - var uf = valAxis.c2p(trace.boxpoints === false ? d.max : d.uf, true); - var ln = valAxis.c2p(d.ln, true); - var un = valAxis.c2p(d.un, true); - - if(trace.orientation === 'h') { - _$d3_10.select(this).attr('d', - 'M' + m + ',' + posm0 + 'V' + posm1 + // median line - 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge - (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge - 'H' + q3 + // end of the top edge - 'V' + pos0 + // right edge - (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge - 'Z' + // end of the box - 'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers - ((whiskerWidth === 0) ? '' : // whisker caps - 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1)); - } else { - _$d3_10.select(this).attr('d', - 'M' + posm0 + ',' + m + 'H' + posm1 + // median line - 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box - (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge - 'V' + q3 + // end of the right edge - 'H' + pos0 + // bottom of the box - (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge - 'Z' + // end of the box - 'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers - ((whiskerWidth === 0) ? '' : // whisker caps - 'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1)); - } - }); -} - -function plotPoints(sel, axes, trace, t) { - var xa = axes.x; - var ya = axes.y; - var bdPos = t.bdPos; - var bPos = t.bPos; - - // to support violin points - var mode = trace.boxpoints || trace.points; - - // repeatable pseudo-random number generator - _$lib_165.seedPseudoRandom(); - - sel.selectAll('g.points') - // since box plot points get an extra level of nesting, each - // box needs the trace styling info - .data(function(d) { - d.forEach(function(v) { - v.t = t; - v.trace = trace; - }); - return d; - }) - .enter().append('g') - .attr('class', 'points') - .selectAll('path') - .data(function(d) { - var i; - - var pts = mode === 'all' ? - d.pts : - d.pts.filter(function(pt) { return (pt.v < d.lf || pt.v > d.uf); }); - - // normally use IQR, but if this is 0 or too small, use max-min - var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1); - var minSpread = typicalSpread * 1e-9; - var spreadLimit = typicalSpread * JITTERSPREAD; - var jitterFactors = []; - var maxJitterFactor = 0; - var newJitter; - - // dynamic jitter - if(trace.jitter) { - if(typicalSpread === 0) { - // edge case of no spread at all: fall back to max jitter - maxJitterFactor = 1; - jitterFactors = new Array(pts.length); - for(i = 0; i < pts.length; i++) { - jitterFactors[i] = 1; - } - } else { - for(i = 0; i < pts.length; i++) { - var i0 = Math.max(0, i - JITTERCOUNT); - var pmin = pts[i0].v; - var i1 = Math.min(pts.length - 1, i + JITTERCOUNT); - var pmax = pts[i1].v; - - if(mode !== 'all') { - if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf); - else pmin = Math.max(pmin, d.uf); - } - - var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0; - jitterFactor = _$lib_165.constrain(Math.abs(jitterFactor), 0, 1); - - jitterFactors.push(jitterFactor); - maxJitterFactor = Math.max(jitterFactor, maxJitterFactor); - } - } - newJitter = trace.jitter * 2 / maxJitterFactor; - } - - // fills in 'x' and 'y' in calcdata 'pts' item - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var v = pt.v; - - var jitterOffset = trace.jitter ? - (newJitter * jitterFactors[i] * (_$lib_165.pseudoRandom() - 0.5)) : - 0; - - var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset); - - if(trace.orientation === 'h') { - pt.y = posPx; - pt.x = v; - } else { - pt.x = posPx; - pt.y = v; - } - - // tag suspected outliers - if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) { - pt.so = true; - } - } - - return pts; - }) - .enter().append('path') - .classed('point', true) - .call(_$drawing_71.translatePoints, xa, ya); -} - -function plotBoxMean(sel, axes, trace, t) { - var posAxis = axes.pos; - var valAxis = axes.val; - var bPos = t.bPos; - var bPosPxOffset = t.bPosPxOffset || 0; - - // to support for one-sided box - var bdPos0; - var bdPos1; - if(Array.isArray(t.bdPos)) { - bdPos0 = t.bdPos[0]; - bdPos1 = t.bdPos[1]; - } else { - bdPos0 = t.bdPos; - bdPos1 = t.bdPos; + else { + b = sa.d2c(base, 0, scalendar); + var hasBase = _$fastIsnumeric_13(b); + b = hasBase ? b : 0; + for(i = 0; i < cd.length; i++) { + cd[i].b = b; + if(hasBase) cd[i].hasB = 1; + } } - sel.selectAll('path.mean') - .data(_$lib_165.identity) - .enter().append('path') - .attr('class', 'mean') - .style({ - fill: 'none', - 'vector-effect': 'non-scaling-stroke' - }) - .each(function(d) { - var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset; - var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset; - var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset; - var m = valAxis.c2p(d.mean, true); - var sl = valAxis.c2p(d.mean - d.sd, true); - var sh = valAxis.c2p(d.mean + d.sd, true); + // auto-z and autocolorscale if applicable + if(_$hasColorscale_60(trace, 'marker')) { + _$calc_53(trace, trace.marker.color, 'marker', 'c'); + } + if(_$hasColorscale_60(trace, 'marker.line')) { + _$calc_53(trace, trace.marker.line.color, 'marker.line', 'c'); + } - if(trace.orientation === 'h') { - _$d3_10.select(this).attr('d', - 'M' + m + ',' + pos0 + 'V' + pos1 + - (trace.boxmean === 'sd' ? - 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : - '') - ); - } else { - _$d3_10.select(this).attr('d', - 'M' + pos0 + ',' + m + 'H' + pos1 + - (trace.boxmean === 'sd' ? - 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : - '') - ); - } - }); -} + _$arraysToCalcdata_257(cd, trace); + _$calcSelection_317(cd, trace); -var _$plot_277 = { - plot: plot, - plotBoxAndWhiskers: plotBoxAndWhiskers, - plotPoints: plotPoints, - plotBoxMean: plotBoxMean + return cd; }; /** @@ -37562,44 +37735,34 @@ var _$plot_277 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$selectPoints_278 = function selectPoints(searchInfo, polygon) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var i, j; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_56 = require('../../components/colorscale/defaults'); */; - if(polygon === 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(polygon.contains([x, y])) { - selection.push({ - pointNumber: pt.i, - x: xa.c2d(pt.x), - y: ya.c2d(pt.y) - }); - pt.selected = 1; - } else { - pt.selected = 0; - } - } - } +var _$handleStyleDefaults_270 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { + coerce('marker.color', defaultColor); + + if(_$hasColorscale_60(traceIn, 'marker')) { + _$colorScaleDefaults_56( + traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} + ); } - return selection; + coerce('marker.line.color', _$color_46.defaultLine); + + if(_$hasColorscale_60(traceIn, 'marker.line')) { + _$colorScaleDefaults_56( + traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} + ); + } + + coerce('marker.line.width'); + coerce('marker.opacity'); + coerce('selected.marker.color'); + coerce('unselected.marker.color'); }; /** @@ -37610,106 +37773,41 @@ var _$selectPoints_278 = function selectPoints(searchInfo, polygon) { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -var orientations = ['v', 'h']; +'use strict'; -function setPositions(gd, plotinfo) { - var calcdata = gd.calcdata; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; +/* removed: var _$registry_248 = require('../../registry'); */; - for(var i = 0; i < orientations.length; i++) { - var orientation = orientations[i]; - var posAxis = orientation === 'h' ? ya : xa; - var boxList = []; - var minPad = 0; - var maxPad = 0; - // make list of boxes - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j]; - var t = cd[0].t; - var trace = cd[0].trace; +var _$handleXYDefaults_339 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { + var len, + x = coerce('x'), + y = coerce('y'); - if(trace.visible === true && trace.type === 'box' && - !t.empty && - trace.orientation === orientation && - trace.xaxis === xa._id && - trace.yaxis === ya._id - ) { - boxList.push(j); + var handleCalendarDefaults = _$registry_248.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); - if(trace.boxpoints !== false) { - minPad = Math.max(minPad, trace.jitter - trace.pointpos - 1); - maxPad = Math.max(maxPad, trace.jitter + trace.pointpos - 1); - } - } + if(x) { + if(y) { + len = Math.min(x.length, y.length); } - - setPositionOffset('box', gd, boxList, posAxis, [minPad, maxPad]); - } -} - -function setPositionOffset(traceType, gd, boxList, posAxis, pad) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; - var pointList = []; - - // N.B. reused in violin - var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes'; - - var i, j, calcTrace; - - // make list of box points - for(i = 0; i < boxList.length; i++) { - calcTrace = calcdata[boxList[i]]; - for(j = 0; j < calcTrace.length; j++) { - pointList.push(calcTrace[j].pos); + else { + len = x.length; + coerce('y0'); + coerce('dy'); } } + else { + if(!y) return 0; - if(!pointList.length) return; - - // box plots - update dPos based on multiple traces - // and then use for posAxis autorange - var boxdv = _$lib_165.distinctVals(pointList); - var dPos = boxdv.minDiff / 2; - - // if there's no duplication of x points, - // disable 'group' mode by setting counter to 1 - if(pointList.length === boxdv.vals.length) { - fullLayout[numKey] = 1; - } - - // check for forced minimum dtick - _$axes_207.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); - - // set the width of all boxes - for(i = 0; i < boxList.length; i++) { - calcTrace = calcdata[boxList[i]]; - calcTrace[0].t.dPos = dPos; + len = traceOut.y.length; + coerce('x0'); + coerce('dx'); } - var gap = fullLayout[traceType + 'gap']; - var groupgap = fullLayout[traceType + 'groupgap']; - var padfactor = (1 - gap) * (1 - groupgap) * dPos / fullLayout[numKey]; - - // autoscale the x axis - including space for points if they're off the side - // TODO: this will overdo it if the outermost boxes don't have - // their points as far out as the other boxes - _$axes_207.expand(posAxis, boxdv.vals, { - vpadminus: dPos + pad[0] * padfactor, - vpadplus: dPos + pad[1] * padfactor - }); -} + traceOut._length = len; -var _$set_positions_279 = { - setPositions: setPositions, - setPositionOffset: setPositionOffset + return len; }; /** @@ -37720,188 +37818,62 @@ var _$set_positions_279 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$lib_166 = require('../../lib'); */; /* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -var _$style_280 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_10.select(gd).selectAll('g.trace.boxes'); +/* removed: var _$handleXYDefaults_339 = require('../scatter/xy_defaults'); */; +/* removed: var _$handleStyleDefaults_270 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_258 = require('./attributes'); */; - s.style('opacity', function(d) { return d[0].trace.opacity; }); +var _$supplyDefaults_260 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_166.coerce(traceIn, traceOut, _$attributes_258, attr, dflt); + } - s.each(function(d) { - var el = _$d3_10.select(this); - var trace = d[0].trace; - var lineWidth = trace.line.width; + var coerceFont = _$lib_166.coerceFont; - el.selectAll('path.box') - .style('stroke-width', lineWidth + 'px') - .call(_$color_46.stroke, trace.line.color) - .call(_$color_46.fill, trace.fillcolor); + var len = _$handleXYDefaults_339(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; + } - el.selectAll('path.mean') - .style({ - 'stroke-width': lineWidth, - 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' - }) - .call(_$color_46.stroke, trace.line.color); + coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); + coerce('base'); + coerce('offset'); + coerce('width'); - var pts = el.selectAll('path.point'); - _$drawing_71.pointStyle(pts, trace, gd); - _$drawing_71.selectedPointStyle(pts, trace); - }); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var Box = {}; - -Box.attributes = _$attributes_270; -Box.layoutAttributes = _$layout_attributes_275; -Box.supplyDefaults = _$defaults_272.supplyDefaults; -Box.supplyLayoutDefaults = _$layout_defaults_276.supplyLayoutDefaults; -Box.calc = _$calc_271; -Box.setPositions = _$set_positions_279.setPositions; -Box.plot = _$plot_277.plot; -Box.style = _$style_280; -Box.hoverPoints = _$hover_273.hoverPoints; -Box.selectPoints = _$selectPoints_278; - -Box.moduleType = 'trace'; -Box.name = 'box'; -Box.basePlotModule = _$cartesian_218; -Box.categories = ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend']; -Box.meta = { - -}; - -var _$Box_274 = Box; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __extendFlat_297 = _$lib_165.extendFlat; -/* removed: var _$attributes_317 = require('../scatter/attributes'); */; -var __dash_297 = _$attributes_70.dash; - -var INCREASING_COLOR = '#3D9970'; -var DECREASING_COLOR = '#FF4136'; - -var lineAttrs = _$attributes_317.line; - -function directionAttrs(lineColorDefault) { - return { - name: { - valType: 'string', - - editType: 'style', - - }, - - showlegend: { - valType: 'boolean', - - dflt: true, - editType: 'style', - - }, - - line: { - color: __extendFlat_297({}, lineAttrs.color, {dflt: lineColorDefault}), - width: lineAttrs.width, - dash: __dash_297, - editType: 'style' - }, - editType: 'style' - }; -} - -var _$attributes_297 = { - - x: { - valType: 'data_array', - editType: 'calc+clearAxisTypes', - - }, - - open: { - valType: 'data_array', - dflt: [], - editType: 'calc', - - }, - - high: { - valType: 'data_array', - dflt: [], - editType: 'calc', - - }, - - low: { - valType: 'data_array', - dflt: [], - editType: 'calc', - - }, + coerce('text'); + coerce('hovertext'); - close: { - valType: 'data_array', - dflt: [], - editType: 'calc', - - }, + var textPosition = coerce('textposition'); - line: { - width: __extendFlat_297({}, lineAttrs.width, { - - }), - dash: __extendFlat_297({}, __dash_297, { - - }), - editType: 'style' - }, + var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', + hasInside = hasBoth || textPosition === 'inside', + hasOutside = hasBoth || textPosition === 'outside'; - increasing: directionAttrs(INCREASING_COLOR), + if(hasInside || hasOutside) { + var textFont = coerceFont(coerce, 'textfont', layout.font); + if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); + if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); + coerce('constraintext'); + coerce('selected.textfont.color'); + coerce('unselected.textfont.color'); + coerce('cliponaxis'); + } - decreasing: directionAttrs(DECREASING_COLOR), + _$handleStyleDefaults_270(traceIn, traceOut, coerce, defaultColor, layout); - text: { - valType: 'string', - - dflt: '', - arrayOk: true, - editType: 'calc', - - }, + // override defaultColor for error bars with defaultLine + var errorBarsSupplyDefaults = _$registry_248.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_46.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_46.defaultLine, {axis: 'x', inherit: 'y'}); - tickwidth: { - valType: 'number', - min: 0, - max: 0.5, - dflt: 0.3, - - editType: 'calcIfAutorange', - - } + _$lib_166.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -37912,51 +37884,40 @@ var _$attributes_297 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var __extendFlat_281 = _$lib_165.extendFlat; -/* removed: var _$attributes_297 = require('../ohlc/attributes'); */; -/* removed: var _$attributes_270 = require('../box/attributes'); */; - -function __directionAttrs_281(lineColorDefault) { - return { - name: _$attributes_297.increasing.name, - showlegend: _$attributes_297.increasing.showlegend, - - line: { - color: __extendFlat_281({}, _$attributes_270.line.color, {dflt: lineColorDefault}), - width: _$attributes_270.line.width, - editType: 'style' - }, - - fillcolor: _$attributes_270.fillcolor, - editType: 'style' - }; -} - -var _$attributes_281 = { - x: _$attributes_297.x, - open: _$attributes_297.open, - high: _$attributes_297.high, - low: _$attributes_297.low, - close: _$attributes_297.close, - - line: { - width: __extendFlat_281({}, _$attributes_270.line.width, { - - }), - editType: 'style' - }, +/* removed: var _$lib_166 = require('../../lib'); */; - increasing: __directionAttrs_281(_$attributes_297.increasing.line.color.dflt), +/** Fill hover 'pointData' container with 'correct' hover text value + * + * - If trace hoverinfo contains a 'text' flag and hovertext is not set, + * the text elements will be seen in the hover labels. + * + * - If trace hoverinfo contains a 'text' flag and hovertext is set, + * hovertext takes precedence over text + * i.e. the hoverinfo elements will be seen in the hover labels + * + * @param {object} calcPt + * @param {object} trace + * @param {object || array} contOut (mutated here) + */ +var _$fillHoverText_323 = function fillHoverText(calcPt, trace, contOut) { + var fill = Array.isArray(contOut) ? + function(v) { contOut.push(v); } : + function(v) { contOut.text = v; }; - decreasing: __directionAttrs_281(_$attributes_297.decreasing.line.color.dflt), + var htx = _$lib_166.extractOption(calcPt, trace, 'htx', 'hovertext'); + if(isValid(htx)) return fill(htx); - text: _$attributes_297.text, - whiskerwidth: __extendFlat_281({}, _$attributes_270.whiskerwidth, { dflt: 0 }) + var tx = _$lib_166.extractOption(calcPt, trace, 'tx', 'text'); + if(isValid(tx)) return fill(tx); }; +// accept all truthy values and 0 (which gets cast to '0' in the hover labels) +function isValid(v) { + return v || v === 0; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -37968,167 +37929,140 @@ var _$attributes_281 = { 'use strict'; +/* removed: var _$fx_88 = require('../../components/fx'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$fillHoverText_323 = require('../scatter/fill_hover_text'); */; -var _$handleDirectionDefaults_299 = function handleDirectionDefaults(traceIn, traceOut, coerce, direction) { - coerce(direction + '.showlegend'); - - // trace-wide *showlegend* overrides direction *showlegend* - if(traceIn.showlegend === false) { - traceOut[direction].showlegend = false; - } +var _$hoverPoints_261 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var trace = cd[0].trace; + var t = cd[0].t; + var isClosest = (hovermode === 'closest'); + var maxHoverDistance = pointData.maxHoverDistance; + var maxSpikeDistance = pointData.maxSpikeDistance; - var nameDflt = traceOut.name + ' - ' + direction; + var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; - coerce(direction + '.name', nameDflt); -}; + function thisBarMinPos(di) { return di[posLetter] - di.w / 2; } + function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; } -var _$helpers_300 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 minPos = isClosest ? + thisBarMinPos : + function(di) { + /* + * In compare mode, accept a bar if you're on it *or* its group. + * Nearly always it's the group that matters, but in case the bar + * was explicitly set wider than its group we'd better accept the + * whole bar. + * + * use `bardelta` instead of `bargroupwidth` so we accept hover + * in the gap. That way hover doesn't flash on and off as you + * mouse over the plot in compare modes. + * In 'closest' mode though the flashing seems inevitable, + * without far more complex logic + */ + return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2); + }; + var maxPos = isClosest ? + thisBarMaxPos : + function(di) { + return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2); + }; -'use strict'; + function _positionFn(_minPos, _maxPos) { + // add a little to the pseudo-distance for wider bars, so that like scatter, + // if you are over two overlapping bars, the narrower one wins. + return _$fx_88.inbox(_minPos - posVal, _maxPos - posVal, + maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); + } -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + function positionFn(di) { + return _positionFn(minPos(di), maxPos(di)); + } -/* removed: var _$lib_165 = require('../../lib'); */; + function thisBarPositionFn(di) { + return _positionFn(thisBarMinPos(di), thisBarMaxPos(di)); + } -// This routine gets called during the trace supply-defaults step. -// -// This is a hacky way to make 'ohlc' and 'candlestick' trace types -// go through the transform machinery. -// -// Note that, we must mutate user data (here traceIn) as opposed -// to full data (here traceOut) as - at the moment - transform -// defaults (which are called after trace defaults) start -// from a clear transforms container. The mutations inflicted are -// cleared in exports.clearEphemeralTransformOpts. -_$helpers_300.pushDummyTransformOpts = function(traceIn, traceOut) { - var transformOpts = { - - // give dummy transform the same type as trace - type: traceOut.type, - - // track ephemeral transforms in user data - _ephemeral: true - }; + function sizeFn(di) { + // add a gradient so hovering near the end of a + // bar makes it a little closer match + return _$fx_88.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, + maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); + } - if(Array.isArray(traceIn.transforms)) { - traceIn.transforms.push(transformOpts); + if(trace.orientation === 'h') { + posVal = yval; + sizeVal = xval; + posLetter = 'y'; + sizeLetter = 'x'; + dx = sizeFn; + dy = positionFn; } else { - traceIn.transforms = [transformOpts]; - } -}; - -// This routine gets called during the transform supply-defaults step -// where it clears ephemeral transform opts in user data -// and effectively put back user date in its pre-supplyDefaults state. -_$helpers_300.clearEphemeralTransformOpts = function(traceIn) { - var transformsIn = traceIn.transforms; - - if(!Array.isArray(transformsIn)) return; - - for(var i = 0; i < transformsIn.length; i++) { - if(transformsIn[i]._ephemeral) transformsIn.splice(i, 1); + posVal = xval; + sizeVal = yval; + posLetter = 'x'; + sizeLetter = 'y'; + dy = sizeFn; + dx = positionFn; } - if(transformsIn.length === 0) delete traceIn.transforms; -}; - -// This routine gets called during the transform supply-defaults step -// where it passes 'ohlc' and 'candlestick' attributes -// (found the transform container via exports.makeTransform) -// to the traceOut container such that they can -// be compatible with filter and groupby transforms. -// -// Note that this routine only has an effect during the -// second round of transform defaults done on generated traces -_$helpers_300.copyOHLC = function(container, traceOut) { - if(container.open) traceOut.open = container.open; - if(container.high) traceOut.high = container.high; - if(container.low) traceOut.low = container.low; - if(container.close) traceOut.close = container.close; -}; - -// This routine gets called during the applyTransform step. -// -// We need to track trace attributes and which direction -// ('increasing' or 'decreasing') -// the generated correspond to for the calcTransform step. -// -// To make sure that the attributes reach the calcTransform, -// store it in the transform opts object. -_$helpers_300.makeTransform = function(traceIn, state, direction) { - var out = _$lib_165.extendFlat([], traceIn.transforms); - - out[state.transformIndex] = { - type: traceIn.type, - direction: direction, - - // these are copied to traceOut during exports.copyOHLC - open: traceIn.open, - high: traceIn.high, - low: traceIn.low, - close: traceIn.close - }; + var pa = pointData[posLetter + 'a']; + var sa = pointData[sizeLetter + 'a']; - return out; -}; + pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); -_$helpers_300.getFilterFn = function(direction) { - return new _getFilterFn(direction); -}; + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_88.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_88.getClosest(cd, distfn, pointData); -function _getFilterFn(direction) { - // we're optimists - before we have any changing data, assume increasing - var isPrevIncreasing = true; - var cPrev = null; + // skip the rest (for this trace) if we didn't find a close point + if(pointData.index === false) return; - function _isIncreasing(o, c) { - if(o === c) { - if(c > cPrev) { - isPrevIncreasing = true; // increasing - } else if(c < cPrev) { - isPrevIncreasing = false; // decreasing - } - // else isPrevIncreasing is not changed - } - else isPrevIncreasing = (o < c); - cPrev = c; - return isPrevIncreasing; + // if we get here and we're not in 'closest' mode, push min/max pos back + // onto the group - even though that means occasionally the mouse will be + // over the hover label. + if(!isClosest) { + minPos = function(di) { + return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2); + }; + maxPos = function(di) { + return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2); + }; } - function isIncreasing(o, c) { - return _$fastIsnumeric_13(o) && _$fastIsnumeric_13(c) && _isIncreasing(+o, +c); - } + // the closest data point + var index = pointData.index; + var di = cd[index]; + var mc = di.mcc || trace.marker.color; + var mlc = di.mlcc || trace.marker.line.color; + var mlw = di.mlw || trace.marker.line.width; - function isDecreasing(o, c) { - return _$fastIsnumeric_13(o) && _$fastIsnumeric_13(c) && !_isIncreasing(+o, +c); - } + if(_$color_46.opacity(mc)) pointData.color = mc; + else if(_$color_46.opacity(mlc) && mlw) pointData.color = mlc; - return direction === 'increasing' ? isIncreasing : isDecreasing; -} + var size = (trace.base) ? di.b + di.s : di.s; + pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); + pointData[sizeLetter + 'LabelVal'] = size; + + var extent = t.extents[t.extents.round(di.p)]; + pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true); + pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true); + pointData[posLetter + 'LabelVal'] = di.p; -_$helpers_300.addRangeSlider = function(data, layout) { - var hasOneVisibleTrace = false; + // spikelines always want "closest" distance regardless of hovermode + pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance; + // they also want to point to the data value, regardless of where the label goes + // in case of bars shifted within groups + pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); - for(var i = 0; i < data.length; i++) { - if(data[i].visible === true) { - hasOneVisibleTrace = true; - break; - } - } + _$fillHoverText_323(di, trace, pointData); + _$registry_248.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); - if(hasOneVisibleTrace) { - if(!layout.xaxis) layout.xaxis = {}; - if(!layout.xaxis.rangeslider) layout.xaxis.rangeslider = {}; - } + return [pointData]; }; /** @@ -38139,37 +38073,43 @@ _$helpers_300.addRangeSlider = function(data, layout) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; - -var _$handleOHLC_302 = function handleOHLC(traceIn, traceOut, coerce, layout) { - var len; - - var x = coerce('x'), - open = coerce('open'), - high = coerce('high'), - low = coerce('low'), - close = coerce('close'); - - var handleCalendarDefaults = _$registry_247.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x'], layout); - - len = Math.min(open.length, high.length, low.length, close.length); - - if(x) { - len = Math.min(len, x.length); - if(len < x.length) traceOut.x = x.slice(0, len); +var _$layout_attributes_263 = { + 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', + } - - if(len < open.length) traceOut.open = open.slice(0, len); - if(len < high.length) traceOut.high = high.slice(0, len); - if(len < low.length) traceOut.low = low.slice(0, len); - if(len < close.length) traceOut.close = close.slice(0, len); - - return len; }; /** @@ -38183,43 +38123,52 @@ var _$handleOHLC_302 = function handleOHLC(traceIn, traceOut, coerce, layout) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$handleOHLC_302 = require('../ohlc/ohlc_defaults'); */; -/* removed: var _$handleDirectionDefaults_299 = require('../ohlc/direction_defaults'); */; -/* removed: var _$helpers_300 = require('../ohlc/helpers'); */; -/* removed: var _$attributes_281 = require('./attributes'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_166 = require('../../lib'); */; + +/* removed: var _$layout_attributes_263 = require('./layout_attributes'); */; -var _$supplyDefaults_282 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - _$helpers_300.pushDummyTransformOpts(traceIn, traceOut); +var _$layout_defaults_264 = function(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_281, attr, dflt); + return _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_263, attr, dflt); } - var len = _$handleOHLC_302(traceIn, traceOut, coerce, layout); - if(len === 0) { - traceOut.visible = false; - return; - } + var hasBars = false, + shouldBeGapless = false, + gappedAnyway = false, + usedSubplots = {}; - coerce('line.width'); + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if(_$registry_248.traceIs(trace, 'bar')) hasBars = true; + else continue; - handleDirection(traceIn, traceOut, coerce, 'increasing'); - handleDirection(traceIn, traceOut, coerce, 'decreasing'); + // if we have at least 2 grouped bar traces on the same subplot, + // we should default to a gap anyway, even if the data is histograms + if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') { + var subploti = trace.xaxis + trace.yaxis; + if(usedSubplots[subploti]) gappedAnyway = true; + usedSubplots[subploti] = true; + } - coerce('text'); - coerce('whiskerwidth'); -}; + if(trace.visible && trace.type === 'histogram') { + var pa = _$axes_208.getFromId({_fullLayout: layoutOut}, + trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); + if(pa.type !== 'category') shouldBeGapless = true; + } + } -function handleDirection(traceIn, traceOut, coerce, direction) { - _$handleDirectionDefaults_299(traceIn, traceOut, coerce, direction); + if(!hasBars) return; - coerce(direction + '.line.color'); - coerce(direction + '.line.width', traceOut.line.width); - coerce(direction + '.fillcolor'); -} + var mode = coerce('barmode'); + if(mode !== 'overlay') coerce('barnorm'); + + coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2); + coerce('bargroupgap'); +}; -var _$transform_284 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -38231,1698 +38180,1409 @@ var _$transform_284 = {}; 'use strict'; +/* removed: var _$d3_10 = require('d3'); */; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_28 = require('tinycolor2'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$helpers_300 = require('../ohlc/helpers'); */; - -_$transform_284.moduleType = 'transform'; - -_$transform_284.name = 'candlestick'; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -_$transform_284.attributes = {}; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -_$transform_284.supplyDefaults = function(transformIn, traceOut, layout, traceIn) { - _$helpers_300.clearEphemeralTransformOpts(traceIn); - _$helpers_300.copyOHLC(transformIn, traceOut); +var __dummy_265$0 = 0, + attributeText = _$attributes_258.text, + attributeTextPosition = _$attributes_258.textposition, + attributeTextFont = _$attributes_258.textfont, + attributeInsideTextFont = _$attributes_258.insidetextfont, + attributeOutsideTextFont = _$attributes_258.outsidetextfont; - return transformIn; -}; +// padding in pixels around text +var TEXTPAD = 3; -_$transform_284.transform = function transform(dataIn, state) { - var dataOut = []; +var _$plot_265 = function plot(gd, plotinfo, cdbar) { + var xa = plotinfo.xaxis, + ya = plotinfo.yaxis, + fullLayout = gd._fullLayout; - for(var i = 0; i < dataIn.length; i++) { - var traceIn = dataIn[i]; + var bartraces = plotinfo.plot.select('.barlayer') + .selectAll('g.trace.bars') + .data(cdbar); - if(traceIn.type !== 'candlestick') { - dataOut.push(traceIn); - continue; - } + bartraces.enter().append('g') + .attr('class', 'trace bars'); - dataOut.push( - makeTrace(traceIn, state, 'increasing'), - makeTrace(traceIn, state, 'decreasing') - ); + if(!plotinfo.isRangePlot) { + bartraces.each(function(d) { + d[0].node3 = _$d3_10.select(this); + }); } - _$helpers_300.addRangeSlider(dataOut, state.layout); + bartraces.append('g') + .attr('class', 'points') + .each(function(d) { + var sel = _$d3_10.select(this); + var t = d[0].t; + var trace = d[0].trace; + var poffset = t.poffset; + var poffsetIsArray = Array.isArray(poffset); - return dataOut; -}; + sel.selectAll('g.point') + .data(_$lib_166.identity) + .enter().append('g').classed('point', true) + .each(function(di, i) { + // now display the bar + // clipped xf/yf (2nd arg true): non-positive + // log values go off-screen by plotwidth + // so you see them continue if you drag the plot + var p0 = di.p + ((poffsetIsArray) ? poffset[i] : poffset), + p1 = p0 + di.w, + s0 = di.b, + s1 = s0 + di.s; -function makeTrace(traceIn, state, direction) { - var traceOut = { - type: 'box', - boxpoints: false, + var x0, x1, y0, y1; + if(trace.orientation === 'h') { + y0 = ya.c2p(p0, true); + y1 = ya.c2p(p1, true); + x0 = xa.c2p(s0, true); + x1 = xa.c2p(s1, true); - visible: traceIn.visible, - hoverinfo: traceIn.hoverinfo, - opacity: traceIn.opacity, - xaxis: traceIn.xaxis, - yaxis: traceIn.yaxis, + // for selections + di.ct = [x1, (y0 + y1) / 2]; + } + else { + x0 = xa.c2p(p0, true); + x1 = xa.c2p(p1, true); + y0 = ya.c2p(s0, true); + y1 = ya.c2p(s1, true); - transforms: _$helpers_300.makeTransform(traceIn, state, direction) - }; + // for selections + di.ct = [(x0 + x1) / 2, y1]; + } - // the rest of below may not have been coerced + if(!_$fastIsnumeric_13(x0) || !_$fastIsnumeric_13(x1) || + !_$fastIsnumeric_13(y0) || !_$fastIsnumeric_13(y1) || + x0 === x1 || y0 === y1) { + _$d3_10.select(this).remove(); + return; + } - var directionOpts = traceIn[direction]; + var lw = (di.mlw + 1 || trace.marker.line.width + 1 || + (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, + offset = _$d3_10.round((lw / 2) % 1, 2); - if(directionOpts) { - _$lib_165.extendFlat(traceOut, { + function roundWithLine(v) { + // if there are explicit gaps, don't round, + // it can make the gaps look crappy + return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? + _$d3_10.round(Math.round(v) - offset, 2) : v; + } - // to make autotype catch date axes soon!! - x: traceIn.x || [0], - xcalendar: traceIn.xcalendar, + function expandToVisible(v, vc) { + // if it's not in danger of disappearing entirely, + // round more precisely + return Math.abs(v - vc) >= 2 ? roundWithLine(v) : + // but if it's very thin, expand it so it's + // necessarily visible, even if it might overlap + // its neighbor + (v > vc ? Math.ceil(v) : Math.floor(v)); + } - // concat low and high to get correct autorange - y: [].concat(traceIn.low).concat(traceIn.high), + if(!gd._context.staticPlot) { + // if bars are not fully opaque or they have a line + // around them, round to integer pixels, mainly for + // safari so we prevent overlaps from its expansive + // pixelation. if the bars ARE fully opaque and have + // no line, expand to a full pixel to make sure we + // can see them + var op = _$color_46.opacity(di.mc || trace.marker.color), + fixpx = (op < 1 || lw > 0.01) ? + roundWithLine : expandToVisible; + x0 = fixpx(x0, x1); + x1 = fixpx(x1, x0); + y0 = fixpx(y0, y1); + y1 = fixpx(y1, y0); + } - whiskerwidth: traceIn.whiskerwidth, - text: traceIn.text, + // append bar path and text + var bar = _$d3_10.select(this); - name: directionOpts.name, - showlegend: directionOpts.showlegend, - line: directionOpts.line, - fillcolor: directionOpts.fillcolor - }); - } + bar.append('path') + .style('vector-effect', 'non-scaling-stroke') + .attr('d', + 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') + .call(_$drawing_71.setClipUrl, plotinfo.layerClipId); - return traceOut; -} + appendBarText(gd, bar, d, i, x0, x1, y0, y1); -_$transform_284.calcTransform = function calcTransform(gd, trace, opts) { - var direction = opts.direction, - filterFn = _$helpers_300.getFilterFn(direction); + if(plotinfo.layerClipId) { + _$drawing_71.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); + } + }); + }); - var open = trace.open, - high = trace.high, - low = trace.low, - close = trace.close; + // error bars are on the top + _$registry_248.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); - var len = open.length, - x = [], - y = []; + // lastly, clip points groups of `cliponaxis !== false` traces + // on `plotinfo._hasClipOnAxisFalse === true` subplots + bartraces.each(function(d) { + var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; + _$drawing_71.setClipUrl(_$d3_10.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + }); +}; - var appendX = trace._fullInput.x ? - function(i) { - var v = trace.x[i]; - x.push(v, v, v, v, v, v); - } : - function(i) { - x.push(i, i, i, i, i, i); - }; +function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { + var textPosition; - var appendY = function(o, h, l, c) { - y.push(l, o, c, c, c, h); - }; + function appendTextNode(bar, text, textFont) { + var textSelection = bar.append('text') + .text(text) + .attr({ + 'class': 'bartext bartext-' + textPosition, + transform: '', + 'text-anchor': 'middle', + // prohibit tex interpretation until we can handle + // tex and regular text together + 'data-notex': 1 + }) + .call(_$drawing_71.font, textFont) + .call(_$svg_text_utils_187.convertToTspans, gd); - for(var i = 0; i < len; i++) { - if(filterFn(open[i], close[i]) && _$fastIsnumeric_13(high[i]) && _$fastIsnumeric_13(low[i])) { - appendX(i); - appendY(open[i], high[i], low[i], close[i]); - } + return textSelection; } - trace.x = x; - trace.y = y; -}; + // get trace attributes + var trace = calcTrace[0].trace, + orientation = trace.orientation; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 text = getText(trace, i); + if(!text) return; -'use strict'; + textPosition = getTextPosition(trace, i); + if(textPosition === 'none') return; -/* removed: var _$registry_247 = require('../../registry'); */; + var textFont = getTextFont(trace, i, gd._fullLayout.font), + insideTextFont = getInsideTextFont(trace, i, textFont), + outsideTextFont = getOutsideTextFont(trace, i, textFont); -var _$candlestick_283 = { - moduleType: 'trace', - name: 'candlestick', - basePlotModule: _$cartesian_218, - categories: ['cartesian', 'showLegend', 'candlestick'], - meta: { - - }, + // compute text position + var barmode = gd._fullLayout.barmode, + inStackMode = (barmode === 'stack'), + inRelativeMode = (barmode === 'relative'), + inStackOrRelativeMode = inStackMode || inRelativeMode, - attributes: _$attributes_281, - supplyDefaults: _$supplyDefaults_282, -}; + calcBar = calcTrace[i], + isOutmostBar = !inStackOrRelativeMode || calcBar._outmost, -_$registry_247.register(_$Box_274); -_$registry_247.register(_$transform_284); + barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD, // padding excluded + barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD, // padding excluded -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + textSelection, + textBB, + textWidth, + textHeight; -'use strict'; + if(textPosition === 'outside') { + if(!isOutmostBar) textPosition = 'inside'; + } -var _$candlestick_4 = _$candlestick_283; + if(textPosition === 'auto') { + if(isOutmostBar) { + // draw text using insideTextFont and check if it fits inside bar + textPosition = 'inside'; + textSelection = appendTextNode(bar, text, insideTextFont); -var _$plotcss_1 = {}; -'use strict'; + textBB = _$drawing_71.bBox(textSelection.node()), + textWidth = textBB.width, + textHeight = textBB.height; -/* removed: var _$lib_165 = require('../src/lib'); */; -var rules = { - "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", - "X .modebar--hover": "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": "opacity:1;", - "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", - "X .modebar-group:first-child": "margin-left:0px;", - "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", - "X .modebar-btn svg": "position:relative;top:2px;", - "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", - "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", - "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", - "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", - "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 .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;" -}; + var textHasSize = (textWidth > 0 && textHeight > 0), + fitsInside = + (textWidth <= barWidth && textHeight <= barHeight), + fitsInsideIfRotated = + (textWidth <= barHeight && textHeight <= barWidth), + fitsInsideIfShrunk = (orientation === 'h') ? + (barWidth >= textWidth * (barHeight / textHeight)) : + (barHeight >= textHeight * (barWidth / textWidth)); + if(textHasSize && + (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) { + textPosition = 'inside'; + } + else { + textPosition = 'outside'; + textSelection.remove(); + textSelection = null; + } + } + else textPosition = 'inside'; + } -for(var selector in rules) { - var fullSelector = selector.replace(/^,/,' ,') - .replace(/X/g, '.js-plotly-plot .plotly') - .replace(/Y/g, '.plotly-notifier'); - _$lib_165.addStyleRule(fullSelector, rules[selector]); -} + if(!textSelection) { + textSelection = appendTextNode(bar, text, + (textPosition === 'outside') ? + outsideTextFont : insideTextFont); -'use strict'; + textBB = _$drawing_71.bBox(textSelection.node()), + textWidth = textBB.width, + textHeight = textBB.height; -var _$ploticon_2 = { - 'undo': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'home': { - 'width': 928.6, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'camera-retro': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoombox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'pan': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_plus': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_minus': { - 'width': 1000, - 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', - 'ascent': 850, - 'descent': -150 - }, - 'autoscale': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_basic': { - 'width': 1500, - 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_compare': { - 'width': 1125, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'plotlylogo': { - 'width': 1542, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'z-axis': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - '3d_rotate': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'camera': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'movie': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'question': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'disk': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'lasso': { - 'width': 1031, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'selectbox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'spikeline': { - 'width': 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', - 'ascent': 850, - 'descent': -150 + if(textWidth <= 0 || textHeight <= 0) { + textSelection.remove(); + return; + } } -}; -var _$browser_27 = {}; -// shim for using process in browser -var process = _$browser_27 = {}; + // compute text transform + var transform, constrained; + if(textPosition === 'outside') { + constrained = trace.constraintext === 'both' || trace.constraintext === 'outside'; + transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, + orientation, constrained); + } + else { + constrained = trace.constraintext === 'both' || trace.constraintext === 'inside'; + transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, + orientation, constrained); + } -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + textSelection.attr('transform', transform); +} -var cachedSetTimeout; -var cachedClearTimeout; +function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { + // compute text and target positions + var textWidth = textBB.width, + textHeight = textBB.height, + textX = (textBB.left + textBB.right) / 2, + textY = (textBB.top + textBB.bottom) / 2, + barWidth = Math.abs(x1 - x0), + barHeight = Math.abs(y1 - y0), + targetWidth, + targetHeight, + targetX, + targetY; -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; + // apply text padding + var textpad; + if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) { + textpad = TEXTPAD; + barWidth -= 2 * textpad; + barHeight -= 2 * textpad; } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; + else textpad = 0; + + // compute rotation and scale + var rotate, + scale; + + if(textWidth <= barWidth && textHeight <= barHeight) { + // no scale or rotation is required + rotate = false; + scale = 1; } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); + else if(textWidth <= barHeight && textHeight <= barWidth) { + // only rotation is required + rotate = true; + scale = 1; } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + else if((textWidth < textHeight) === (barWidth < barHeight)) { + // only scale is required + rotate = false; + scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1; } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } + else { + // both scale and rotation are required + rotate = true; + scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1; } + if(rotate) rotate = 90; // rotate clockwise -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); + // compute text and target positions + if(rotate) { + targetWidth = scale * textHeight; + targetHeight = scale * textWidth; } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); + else { + targetWidth = scale * textWidth; + targetHeight = scale * textHeight; } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); + + if(orientation === 'h') { + if(x1 < x0) { + // bar end is on the left hand side + targetX = x1 + textpad + targetWidth / 2; + targetY = (y0 + y1) / 2; + } + else { + targetX = x1 - textpad - targetWidth / 2; + targetY = (y0 + y1) / 2; + } + } + else { + if(y1 > y0) { + // bar end is on the bottom + targetX = (x0 + x1) / 2; + targetY = y1 - textpad - targetHeight / 2; + } + else { + targetX = (x0 + x1) / 2; + targetY = y1 + textpad + targetHeight / 2; } } - - + return getTransform(textX, textY, targetX, targetY, scale, rotate); } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} +function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) { + var barWidth = (orientation === 'h') ? + Math.abs(y1 - y0) : + Math.abs(x1 - x0), + textpad; -function drainQueue() { - if (draining) { - return; + // Keep the padding so the text doesn't sit right against + // the bars, but don't factor it into barWidth + if(barWidth > 2 * TEXTPAD) { + textpad = TEXTPAD; } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; + // compute rotation and scale + var scale = 1; + if(constrained) { + scale = (orientation === 'h') ? + Math.min(1, barWidth / textBB.height) : + Math.min(1, barWidth / textBB.width); } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + // compute text and target positions + var textX = (textBB.left + textBB.right) / 2, + textY = (textBB.top + textBB.bottom) / 2, + targetWidth, + targetHeight, + targetX, + targetY; + + targetWidth = scale * textBB.width; + targetHeight = scale * textBB.height; + + if(orientation === 'h') { + if(x1 < x0) { + // bar end is on the left hand side + targetX = x1 - textpad - targetWidth / 2; + targetY = (y0 + y1) / 2; + } + else { + targetX = x1 + textpad + targetWidth / 2; + targetY = (y0 + y1) / 2; } } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + else { + if(y1 > y0) { + // bar end is on the bottom + targetX = (x0 + x1) / 2; + targetY = y1 + textpad + targetHeight / 2; + } + else { + targetX = (x0 + x1) / 2; + targetY = y1 - textpad - targetHeight / 2; + } } -}; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; + return getTransform(textX, textY, targetX, targetY, scale, false); } -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function __noop_27() {} - -process.on = __noop_27; -process.addListener = __noop_27; -process.once = __noop_27; -process.off = __noop_27; -process.removeListener = __noop_27; -process.removeAllListeners = __noop_27; -process.emit = __noop_27; -process.prependListener = __noop_27; -process.prependOnceListener = __noop_27; - -process.listeners = function (name) { return [] } -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; +function getTransform(textX, textY, targetX, targetY, scale, rotate) { + var transformScale, + transformRotate, + transformTranslate; -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + if(scale < 1) transformScale = 'scale(' + scale + ') '; + else { + scale = 1; + transformScale = ''; + } -var _$es6Promise_11 = { exports: {} }; -(function (process,global){ -/*! - * @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 - */ + transformRotate = (rotate) ? + 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : ''; -(function (global, factory) { - typeof _$es6Promise_11.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_11.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ES6Promise = factory()); -}(this, (function () { 'use strict'; + // Note that scaling also affects the center of the text box + var translateX = (targetX - scale * textX), + translateY = (targetY - scale * textY); + transformTranslate = 'translate(' + translateX + ' ' + translateY + ')'; -function objectOrFunction(x) { - return typeof x === 'function' || typeof x === 'object' && x !== null; + return transformTranslate + transformScale + transformRotate; } -function isFunction(x) { - return typeof x === 'function'; +function getText(trace, index) { + var value = getValue(trace.text, index); + return coerceString(attributeText, value); } -var _isArray = undefined; -if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} else { - _isArray = Array.isArray; +function getTextPosition(trace, index) { + var value = getValue(trace.textposition, index); + return coerceEnumerated(attributeTextPosition, value); } -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 getTextFont(trace, index, defaultValue) { + return getFontValue( + attributeTextFont, trace.textfont, index, defaultValue); +} -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; +function getInsideTextFont(trace, index, defaultValue) { + return getFontValue( + attributeInsideTextFont, trace.insidetextfont, index, defaultValue); } -function setAsap(asapFn) { - asap = asapFn; +function getOutsideTextFont(trace, index, defaultValue) { + return getFontValue( + attributeOutsideTextFont, trace.outsidetextfont, index, defaultValue); } -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]'; +function getFontValue(attributeDefinition, attributeValue, index, defaultValue) { + attributeValue = attributeValue || {}; -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + var familyValue = getValue(attributeValue.family, index), + sizeValue = getValue(attributeValue.size, index), + colorValue = getValue(attributeValue.color, index); -// 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); - }; + return { + family: coerceString( + attributeDefinition.family, familyValue, defaultValue.family), + size: coerceNumber( + attributeDefinition.size, sizeValue, defaultValue.size), + color: coerceColor( + attributeDefinition.color, colorValue, defaultValue.color) + }; } -// vertx -function useVertxTimer() { - return function () { - vertxNext(flush); - }; +function getValue(arrayOrScalar, index) { + var value; + if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar; + else if(index < arrayOrScalar.length) value = arrayOrScalar[index]; + return value; } -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); +function coerceString(attributeDefinition, value, defaultValue) { + if(typeof value === 'string') { + if(value || !attributeDefinition.noBlank) return value; + } + else if(typeof value === 'number') { + if(!attributeDefinition.strict) return String(value); + } - return function () { - node.data = iterations = ++iterations % 2; - }; + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; } -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); - }; -} +function coerceEnumerated(attributeDefinition, value, defaultValue) { + if(attributeDefinition.coerceNumber) value = +value; -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); - }; + if(attributeDefinition.values.indexOf(value) !== -1) return value; + + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; } -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; +function coerceNumber(attributeDefinition, value, defaultValue) { + if(_$fastIsnumeric_13(value)) { + value = +value; - callback(arg); + var min = attributeDefinition.min, + max = attributeDefinition.max, + isOutOfBounds = (min !== undefined && value < min) || + (max !== undefined && value > max); - queue[i] = undefined; - queue[i + 1] = undefined; - } + if(!isOutOfBounds) return value; + } - len = 0; + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; } -function attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} +function coerceColor(attributeDefinition, value, defaultValue) { + if(_$tinycolor_28(value).isValid()) return value; -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 && typeof require === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); + return (defaultValue !== undefined) ? + defaultValue : + attributeDefinition.dflt; } -function then(onFulfillment, onRejection) { - var _arguments = arguments; - - var parent = this; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 child = new this.constructor(noop); +'use strict'; - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } +var _$selectPoints_266 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; - var _state = parent._state; + if(polygon === false) { + // clear selection + for(i = 0; i < cd.length; i++) { + cd[i].selected = 0; + } + } else { + for(i = 0; i < cd.length; i++) { + var di = cd[i]; - if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } + if(polygon.contains(di.ct)) { + selection.push({ + pointNumber: i, + x: xa.c2d(di.x), + y: ya.c2d(di.y) + }); + di.selected = 1; + } else { + di.selected = 0; + } + } + } - return child; -} + return selection; +}; /** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ```javascript - let promise = new Promise(function(resolve, reject){ - resolve(1); - }); +'use strict'; - promise.then(function(value){ - // value === 1 - }); - ``` +var _$Sieve_268 = Sieve; - Instead of writing the above, your code now simply becomes the following: +/* removed: var _$lib_166 = require('../../lib'); */; +var __BADNUM_268 = _$numerical_148.BADNUM; - ```javascript - let promise = Promise.resolve(1); +/** + * Helper class to sieve data from traces into bins + * + * @class + * @param {Array} traces + * Array of calculated traces + * @param {boolean} [separateNegativeValues] + * If true, then split data at the same position into a bar + * for positive values and another for negative values + * @param {boolean} [dontMergeOverlappingData] + * If true, then don't merge overlapping bars into a single bar + */ +function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { + this.traces = traces; + this.separateNegativeValues = separateNegativeValues; + this.dontMergeOverlappingData = dontMergeOverlappingData; - promise.then(function(value){ - // value === 1 - }); - ``` + // for single-bin histograms - see histogram/calc + var width1 = Infinity; - @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; + var positions = []; + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; + if(bar.p !== __BADNUM_268) positions.push(bar.p); + } + if(trace[0] && trace[0].width1) { + width1 = Math.min(trace[0].width1, width1); + } + } + this.positions = positions; - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } + var dv = _$lib_166.distinctVals(positions); + this.distinctPositions = dv.vals; + if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; + else this.minDiff = Math.min(dv.minDiff, width1); - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; + this.binWidth = this.minDiff; + + this.bins = {}; } -var PROMISE_ID = Math.random().toString(36).substring(16); +/** + * Sieve datum + * + * @method + * @param {number} position + * @param {number} value + * @returns {number} Previous bin value + */ +Sieve.prototype.put = function put(position, value) { + var label = this.getLabel(position, value), + oldValue = this.bins[label] || 0; -function noop() {} + this.bins[label] = oldValue + value; -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; + return oldValue; +}; -var GET_THEN_ERROR = new ErrorObject(); +/** + * Get current bin value for a given datum + * + * @method + * @param {number} position Position of datum + * @param {number} [value] Value of datum + * (required if this.separateNegativeValues is true) + * @returns {number} Current bin value + */ +Sieve.prototype.get = function put(position, value) { + var label = this.getLabel(position, value); + return this.bins[label] || 0; +}; -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} +/** + * Get bin label for a given datum + * + * @method + * @param {number} position Position of datum + * @param {number} [value] Value of datum + * (required if this.separateNegativeValues is true) + * @returns {string} Bin label + * (prefixed with a 'v' if value is negative and this.separateNegativeValues is + * true; otherwise prefixed with '^') + */ +Sieve.prototype.getLabel = function getLabel(position, value) { + var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^', + label = (this.dontMergeOverlappingData) ? + position : + Math.round(position / this.binWidth); + return prefix + label; +}; -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -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; - } -} +'use strict'; -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; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_267 = _$lib_166.isArrayOrTypedArray; +var __BADNUM_267 = _$numerical_148.BADNUM; - _reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$Sieve_268 = require('./sieve.js'); */; - if (!sealed && error) { - sealed = true; - _reject(promise, error); - } - }, promise); -} +/* + * 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 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); - }); - } -} +var _$setPositions_267 = function setPositions(gd, plotinfo) { + var xa = plotinfo.xaxis, + ya = plotinfo.yaxis; -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); + var fullTraces = gd._fullData, + calcTraces = gd.calcdata, + calcTracesHorizontal = [], + calcTracesVertical = [], + i; + for(i = 0; i < fullTraces.length; i++) { + var fullTrace = fullTraces[i]; + if( + fullTrace.visible === true && + _$registry_248.traceIs(fullTrace, 'bar') && + fullTrace.xaxis === xa._id && + fullTrace.yaxis === ya._id + ) { + if(fullTrace.orientation === 'h') { + calcTracesHorizontal.push(calcTraces[i]); + } + else { + calcTracesVertical.push(calcTraces[i]); + } + } } - } -} - -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); -} + setGroupPositions(gd, xa, ya, calcTracesVertical); + setGroupPositions(gd, ya, xa, calcTracesHorizontal); +}; -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } - promise._result = value; - promise._state = FULFILLED; +function setGroupPositions(gd, pa, sa, calcTraces) { + if(!calcTraces.length) return; - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} + var barmode = gd._fullLayout.barmode, + overlay = (barmode === 'overlay'), + group = (barmode === 'group'), + excluded, + included, + i, calcTrace, fullTrace; -function _reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; + if(overlay) { + setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces); + } + else if(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; - asap(publishRejection, promise); -} + if(fullTrace.offset === undefined) included.push(calcTrace); + else excluded.push(calcTrace); + } -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; + if(included.length) { + setGroupPositionsInGroupMode(gd, pa, sa, included); + } + if(excluded.length) { + setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + } + } + else { + // 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; - parent._onerror = null; + if(fullTrace.base === undefined) included.push(calcTrace); + else excluded.push(calcTrace); + } - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; + if(included.length) { + setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included); + } + if(excluded.length) { + setGroupPositionsInOverlayMode(gd, pa, sa, excluded); + } + } - if (length === 0 && parent._state) { - asap(publish, parent); - } + collectExtents(calcTraces, pa); } -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); - } - } +function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { + var barnorm = gd._fullLayout.barnorm, + separateNegativeValues = false, + dontMergeOverlappingData = !barnorm; - promise._subscribers.length = 0; -} + // update position axis and set bar offsets and widths + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; -function ErrorObject() { - this.error = null; -} + var sieve = new _$Sieve_268( + [calcTrace], separateNegativeValues, dontMergeOverlappingData + ); -var TRY_CATCH_ERROR = new ErrorObject(); + // set bar offsets and widths, and update position axis + setOffsetAndWidth(gd, pa, sieve); -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } + // 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(barnorm) { + sieveBars(gd, sa, sieve); + normalizeBars(gd, sa, sieve); + } + else { + setBaseAndTop(gd, sa, sieve); + } + } } -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; - if (hasCallback) { - value = tryCatch(callback, detail); +function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { + var fullLayout = gd._fullLayout, + barnorm = fullLayout.barnorm, + separateNegativeValues = false, + dontMergeOverlappingData = !barnorm, + sieve = new _$Sieve_268( + calcTraces, separateNegativeValues, dontMergeOverlappingData + ); - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } + // set bar offsets and widths, and update position axis + setOffsetAndWidthInGroupMode(gd, pa, sieve); - if (promise === value) { - _reject(promise, cannotReturnOwn()); - return; + // set bar bases and sizes, and update size axis + if(barnorm) { + sieveBars(gd, sa, sieve); + normalizeBars(gd, sa, sieve); } - } 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); + else { + setBaseAndTop(gd, sa, sieve); } } -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 setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { + var fullLayout = gd._fullLayout, + barmode = fullLayout.barmode, + stack = (barmode === 'stack'), + relative = (barmode === 'relative'), + barnorm = gd._fullLayout.barnorm, + separateNegativeValues = relative, + dontMergeOverlappingData = !(barnorm || stack || relative), + sieve = new _$Sieve_268( + calcTraces, separateNegativeValues, dontMergeOverlappingData + ); -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; -} + // set bar offsets and widths, and update position axis + setOffsetAndWidth(gd, pa, sieve); -function Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); + // set bar bases and sizes, and update size axis + stackBars(gd, sa, sieve); - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } + // flag the outmost bar (for text display purposes) + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; - if (isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; + for(var j = 0; j < calcTrace.length; j++) { + var bar = calcTrace[j]; - this._result = new Array(this.length); + if(bar.s === __BADNUM_267) continue; - 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); - } + var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); + if(isOutmostBar) bar._outmost = true; + } } - } else { - _reject(this.promise, validationError()); - } + + // Note that marking the outmost bars has to be done + // before `normalizeBars` changes `bar.b` and `bar.s`. + if(barnorm) normalizeBars(gd, sa, sieve); } -function validationError() { - return new Error('Array Methods must be provided an Array'); -}; -Enumerator.prototype._enumerate = function () { - var length = this.length; - var _input = this._input; +function setOffsetAndWidth(gd, pa, sieve) { + var fullLayout = gd._fullLayout, + bargap = fullLayout.bargap, + bargroupgap = fullLayout.bargroupgap, + minDiff = sieve.minDiff, + calcTraces = sieve.traces, + i, calcTrace, calcTrace0, + t; - for (var i = 0; this._state === PENDING && i < length; i++) { - this._eachEntry(_input[i], i); - } -}; + // set bar offsets and widths + var barGroupWidth = minDiff * (1 - bargap), + barWidthPlusGap = barGroupWidth, + barWidth = barWidthPlusGap * (1 - bargroupgap); -Enumerator.prototype._eachEntry = function (entry, i) { - var c = this._instanceConstructor; - var resolve$$ = c.resolve; + // computer bar group center and bar offset + var offsetFromCenter = -barWidth / 2; - if (resolve$$ === resolve) { - var _then = getThen(entry); + for(i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; - 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); + // store bar width and offset for this trace + t = calcTrace0.t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; } - } else { - this._willSettleAt(resolve$$(entry), i); - } -}; -Enumerator.prototype._settledAt = function (state, i, value) { - var promise = this.promise; + // stack bars that only differ by rounding + sieve.binWidth = calcTraces[0][0].t.barwidth / 100; - if (promise._state === PENDING) { - this._remaining--; + // if defined, apply trace offset and width + applyAttributes(sieve); - if (state === REJECTED) { - _reject(promise, value); - } else { - this._result[i] = value; - } - } + // store the bar center in each calcdata item + setBarCenterAndWidth(gd, pa, sieve); - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; + // update position axes + updatePositionAxis(gd, pa, sieve); +} -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); - }); -}; +function setOffsetAndWidthInGroupMode(gd, pa, sieve) { + var fullLayout = gd._fullLayout, + bargap = fullLayout.bargap, + bargroupgap = fullLayout.bargroupgap, + positions = sieve.positions, + distinctPositions = sieve.distinctPositions, + minDiff = sieve.minDiff, + calcTraces = sieve.traces, + i, calcTrace, calcTrace0, + t; -/** - `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. + // if there aren't any overlapping positions, + // let them have full width even if mode is group + var overlap = (positions.length !== distinctPositions.length); - Example: + var nTraces = calcTraces.length, + barGroupWidth = minDiff * (1 - bargap), + barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth, + barWidth = barWidthPlusGap * (1 - bargroupgap); - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; + for(i = 0; i < nTraces; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` + // computer bar group center and bar offset + var offsetFromCenter = (overlap) ? + ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : + -barWidth / 2; - 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: + // store bar width and offset for this trace + t = calcTrace0.t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; + } - Example: + // stack bars that only differ by rounding + sieve.binWidth = calcTraces[0][0].t.barwidth / 100; - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; + // if defined, apply trace width + applyAttributes(sieve); - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` + // store the bar center in each calcdata item + setBarCenterAndWidth(gd, pa, sieve); - @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; + // update position axes + updatePositionAxis(gd, pa, sieve, overlap); } -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - Example: +function applyAttributes(sieve) { + var calcTraces = sieve.traces, + i, calcTrace, calcTrace0, fullTrace, + j, + t; - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); + for(i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + calcTrace0 = calcTrace[0]; + fullTrace = calcTrace0.trace; + t = calcTrace0.t; - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); + var offset = fullTrace.offset, + initialPoffset = t.poffset, + newPoffset; - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` + if(__isArrayOrTypedArray_267(offset)) { + // if offset is an array, then clone it into t.poffset. + newPoffset = offset.slice(0, calcTrace.length); - `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: + // guard against non-numeric items + for(j = 0; j < newPoffset.length; j++) { + if(!_$fastIsnumeric_13(newPoffset[j])) { + newPoffset[j] = initialPoffset; + } + } - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); + // 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); + } - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); + t.poffset = newPoffset; + } + else if(offset !== undefined) { + t.poffset = offset; + } - 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 - }); - ``` + var width = fullTrace.width, + initialBarwidth = t.barwidth; - An example real-world use case is implementing timeouts: + if(__isArrayOrTypedArray_267(width)) { + // if width is an array, then clone it into t.barwidth. + var newBarwidth = width.slice(0, calcTrace.length); - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` + // guard against non-numeric items + for(j = 0; j < newBarwidth.length; j++) { + if(!_$fastIsnumeric_13(newBarwidth[j])) newBarwidth[j] = initialBarwidth; + } - @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 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); + } - 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); - } - }); - } + 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; + } + } + } } -/** - `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')); - }); +function setBarCenterAndWidth(gd, pa, sieve) { + var calcTraces = sieve.traces, + pLetter = getAxisLetter(pa); - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i], + t = calcTrace[0].t, + poffset = t.poffset, + poffsetIsArray = Array.isArray(poffset), + barwidth = t.barwidth, + barwidthIsArray = Array.isArray(barwidth); - Instead of writing the above, your code now simply becomes the following: + for(var j = 0; j < calcTrace.length; j++) { + var calcBar = calcTrace[j]; - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); + // 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; - 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."); +function updatePositionAxis(gd, pa, sieve, allowMinDtick) { + var calcTraces = sieve.traces, + distinctPositions = sieve.distinctPositions, + distinctPositions0 = distinctPositions[0], + minDiff = sieve.minDiff, + vpad = minDiff / 2; + + _$axes_208.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + + // If the user set the bar width or the offset, + // then bars can be shifted away from their positions + // and widths can be larger than minDiff. + // + // Here, we compute pMin and pMax to expand the position axis, + // so that all bars are fully within the axis range. + var pMin = Math.min.apply(Math, distinctPositions) - vpad, + pMax = Math.max.apply(Math, distinctPositions) + vpad; + + for(var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i], + calcTrace0 = calcTrace[0], + fullTrace = calcTrace0.trace; + + if(fullTrace.width === undefined && fullTrace.offset === undefined) { + continue; + } + + var t = calcTrace0.t, + poffset = t.poffset, + barwidth = t.barwidth, + poffsetIsArray = Array.isArray(poffset), + barwidthIsArray = Array.isArray(barwidth); + + for(var j = 0; j < calcTrace.length; j++) { + var calcBar = calcTrace[j], + calcBarOffset = (poffsetIsArray) ? poffset[j] : poffset, + calcBarWidth = (barwidthIsArray) ? barwidth[j] : barwidth, + p = calcBar.p, + l = p + calcBarOffset, + r = l + calcBarWidth; + + pMin = Math.min(pMin, l); + pMax = Math.max(pMax, r); + } + } + + _$axes_208.expand(pa, [pMin, pMax], {padded: false}); } -/** - 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. +function expandRange(range, newValue) { + if(_$fastIsnumeric_13(range[0])) range[0] = Math.min(range[0], newValue); + else range[0] = newValue; - Terminology - ----------- + if(_$fastIsnumeric_13(range[1])) range[1] = Math.max(range[1], newValue); + else range[1] = newValue; +} - - `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. +function setBaseAndTop(gd, sa, sieve) { + // 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. + var traces = sieve.traces, + sLetter = getAxisLetter(sa), + sRange = [null, null]; - A promise can be in one of three states: pending, fulfilled, or rejected. + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; - 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. + for(var j = 0; j < trace.length; j++) { + var bar = trace[j], + barBase = bar.b, + barTop = barBase + bar.s; - 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. + bar[sLetter] = barTop; + if(_$fastIsnumeric_13(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_13(sa.c2l(barBase))) expandRange(sRange, barBase); + } + } - Basic Usage: - ------------ + _$axes_208.expand(sa, sRange, {tozero: true, padded: true}); +} - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - // on failure - reject(reason); - }); +function stackBars(gd, sa, sieve) { + var fullLayout = gd._fullLayout, + barnorm = fullLayout.barnorm, + sLetter = getAxisLetter(sa), + traces = sieve.traces, + i, trace, + j, bar; - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + var sRange = [null, null]; - Advanced Usage: - --------------- + for(i = 0; i < traces.length; i++) { + trace = traces[i]; - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + for(j = 0; j < trace.length; j++) { + bar = trace[j]; - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); + if(bar.s === __BADNUM_267) continue; - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + // stack current bar and get previous sum + var barBase = sieve.put(bar.p, bar.b + bar.s), + barTop = barBase + bar.b + bar.s; - 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 + ']')); - } + // store the bar base and top in each calcdata item + bar.b = barBase; + bar[sLetter] = barTop; + + if(!barnorm) { + if(_$fastIsnumeric_13(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_13(sa.c2l(barBase))) expandRange(sRange, barBase); + } } - }; - }); - } + } - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + // if barnorm is set, let normalizeBars update the axis range + if(!barnorm) _$axes_208.expand(sa, sRange, {tozero: true, padded: true}); +} - Unlike callbacks, promises are great composable primitives. - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON +function sieveBars(gd, sa, sieve) { + var traces = sieve.traces; - return values; - }); - ``` + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise ? initializePromise(this, resolver) : needsNew(); - } + if(bar.s !== __BADNUM_267) sieve.put(bar.p, bar.b + bar.s); + } + } } -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, +function normalizeBars(gd, sa, sieve) { + // Note: + // + // normalizeBars requires that either sieveBars or stackBars has been + // previously invoked. - /** - 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 + var traces = sieve.traces, + sLetter = getAxisLetter(sa), + sTop = (gd._fullLayout.barnorm === 'fraction') ? 1 : 100, + sTiny = sTop / 1e9, // in case of rounding error in sum + sMin = sa.l2c(sa.c2l(0)), + sMax = (gd._fullLayout.barmode === 'stack') ? sTop : sMin, + sRange = [sMin, sMax], + padded = false; + + function maybeExpand(newValue) { + if(_$fastIsnumeric_13(sa.c2l(newValue)) && + ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_13(sMin)) + ) { + padded = true; + expandRange(sRange, newValue); + } } - ``` - - 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) { - + + for(var i = 0; i < traces.length; i++) { + var trace = traces[i]; + + for(var j = 0; j < trace.length; j++) { + var bar = trace[j]; + + if(bar.s === __BADNUM_267) continue; + + var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); + bar.b *= scale; + bar.s *= scale; + + var barBase = bar.b, + barTop = barBase + bar.s; + bar[sLetter] = barTop; + + maybeExpand(barTop); + if(bar.hasB) maybeExpand(barBase); + } } - - 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); - } + + // update range of size axis + _$axes_208.expand(sa, sRange, {tozero: true, padded: padded}); +} + + +function getAxisLetter(ax) { + return ax._id.charAt(0); +} + +// 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 posLetter = pa._id.charAt(0); + var extents = {}; + var pMin = Infinity; + var pMax = -Infinity; + + var i, j, cd; + for(i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + for(j = 0; j < cd.length; j++) { + var p = cd[j].p; + if(_$fastIsnumeric_13(p)) { + pMin = Math.min(pMin, p); + pMax = Math.max(pMax, p); } - }); - } 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; + // 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))); + }; - 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'); + for(i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + cd[0].t.extents = extents; + for(j = 0; j < cd.length; j++) { + var di = cd[j]; + var p0 = di[posLetter] - di.w / 2; + if(_$fastIsnumeric_13(p0)) { + var p1 = di[posLetter] + 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]; + } + } } } +} - var P = local.Promise; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } - if (promiseToString === '[object Promise]' && !P.cast) { - return; +'use strict'; + +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$registry_248 = require('../../registry'); */; + +var _$style_269 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_10.select(gd).selectAll('g.trace.bars'); + var barcount = s.size(); + var fullLayout = gd._fullLayout; + + // trace styling + s.style('opacity', function(d) { return d[0].trace.opacity; }) + + // for gapless (either stacked or neighboring grouped) bars use + // crispEdges to turn off antialiasing so an artificial gap + // isn't introduced. + .each(function(d) { + if((fullLayout.barmode === 'stack' && barcount > 1) || + (fullLayout.bargap === 0 && + fullLayout.bargroupgap === 0 && + !d[0].trace.marker.line.width)) { + _$d3_10.select(this).attr('shape-rendering', 'crispEdges'); } - } + }); - local.Promise = Promise; -} + s.selectAll('g.points').each(function(d) { + var sel = _$d3_10.select(this); + var pts = sel.selectAll('path'); + var txs = sel.selectAll('text'); + var trace = d[0].trace; -polyfill(); -// Strange compat.. -Promise.polyfill = polyfill; -Promise.Promise = Promise; + _$drawing_71.pointStyle(pts, trace, gd); + _$drawing_71.selectedPointStyle(pts, trace); -return Promise; + txs.each(function(d) { + var tx = _$d3_10.select(this); + var textFont; + + if(tx.classed('bartext-inside')) { + textFont = trace.insidetextfont; + } else if(tx.classed('bartext-outside')) { + textFont = trace.outsidetextfont; + } + if(!textFont) textFont = trace.textfont; + + function cast(k) { + var cont = textFont[k]; + return Array.isArray(cont) ? cont[d.i] : cont; + } + + _$drawing_71.font(tx, cast('family'), cast('size'), cast('color')); + }); + + _$drawing_71.selectedTextStyle(txs, trace); + }); + + _$registry_248.getComponentMethod('errorbars', 'style')(s); +}; -}))); -//# sourceMappingURL=es6-promise.map -}).call(this,_$browser_27,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$es6Promise_11 = _$es6Promise_11.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -39933,65 +39593,22 @@ _$es6Promise_11 = _$es6Promise_11.exports 'use strict'; -/** - * All paths are tuned for maximum scalability of the arrowhead, - * ie throughout arrowwidth=0.3..3 the head is joined smoothly - * to the line, with the line coming from the left and ending at (0, 0). - * - * `backoff` is the distance to move the arrowhead and the end of the line, - * in order that the arrowhead points to the desired place, either at - * the tip of the arrow or (in the case of circle or square) - * the center of the symbol. - * - * `noRotate`, if truthy, says that this arrowhead should not rotate with the - * arrow. That's the case for squares, which should always be straight, and - * circles, for which it's irrelevant. - */ - -var _$arrow_paths_30 = [ - // no arrow - { - path: '', - backoff: 0 - }, - // wide with flat back - { - path: 'M-2.4,-3V3L0.6,0Z', - backoff: 0.6 - }, - // narrower with flat back - { - path: 'M-3.7,-2.5V2.5L1.3,0Z', - backoff: 1.3 - }, - // barbed - { - path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', - backoff: 1.55 - }, - // wide line-drawn - { - path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', - backoff: 1.6 - }, - // narrower line-drawn - { - path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', - backoff: 2 - }, - // circle - { - path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', - backoff: 0, - noRotate: true - }, - // square - { - path: 'M2,2V-2H-2V2Z', - backoff: 0, - noRotate: true +var _$constants_48 = { + cn: { + colorbar: 'colorbar', + cbbg: 'cbbg', + cbfill: 'cbfill', + cbfills: 'cbfills', + cbline: 'cbline', + cblines: 'cblines', + cbaxis: 'cbaxis', + cbtitleunshift: 'cbtitleunshift', + cbtitle: 'cbtitle', + cboutline: 'cboutline', + crisp: 'crisp', + jsPlaceholder: 'js-placeholder' } -]; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -40001,350 +39618,1614 @@ var _$arrow_paths_30 = [ * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$arrow_paths_30 = require('./arrow_paths'); */; -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_212 = require('../../plots/cartesian/constants'); */; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$tinycolor_28 = require('tinycolor2'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +var __extendFlat_50 = _$extend_160.extendFlat; +/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$titles_139 = require('../titles'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +var __LINE_SPACING_50 = _$alignment_146.LINE_SPACING; -var _$attributes_31 = { - _isLinkedToArray: 'annotation', +/* removed: var _$handleAxisDefaults_210 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handlePositionDefaults_223 = require('../../plots/cartesian/position_defaults'); */; +/* removed: var _$layout_attributes_220 = require('../../plots/cartesian/layout_attributes'); */; - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, +/* removed: var _$attributes_47 = require('./attributes'); */; +var cn = _$constants_48.cn; - text: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, - textangle: { - valType: 'angle', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - font: _$font_attributes_234({ - editType: 'calcIfAutorange+arraydraw', - colorEditType: 'arraydraw', - - }), - width: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - height: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - align: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'center', - - editType: 'arraydraw', - - }, - valign: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'middle', - - editType: 'arraydraw', - - }, - bgcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - borderpad: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - // arrow - showarrow: { - valType: 'boolean', - dflt: true, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - arrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_30.length, - dflt: 1, - - editType: 'arraydraw', - - }, - startarrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_30.length, - dflt: 1, - - editType: 'arraydraw', - - }, - arrowside: { - valType: 'flaglist', - flags: ['end', 'start'], - extras: ['none'], - dflt: 'end', - - editType: 'arraydraw', - - }, - arrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', +var _$draw_50 = function draw(gd, id) { + // opts: options object, containing everything from attributes + // plus a few others that are the equivalent of the colorbar "data" + var opts = {}; + Object.keys(_$attributes_47).forEach(function(k) { + opts[k] = null; + }); + // fillcolor can be a d3 scale, domain is z values, range is colors + // or leave it out for no fill, + // or set to a string constant for single-color fill + opts.fillcolor = null; + // line.color has the same options as fillcolor + opts.line = {color: null, width: null, dash: null}; + // levels of lines to draw. + // note that this DOES NOT determine the extent of the bar + // that's given by the domain of fillcolor + // (or line.color if no fillcolor domain) + opts.levels = {start: null, end: null, size: null}; + // separate fill levels (for example, heatmap coloring of a + // contour map) if this is omitted, fillcolors will be + // evaluated halfway between levels + opts.filllevels = null; + + function component() { + var fullLayout = gd._fullLayout, + gs = fullLayout._size; + if((typeof opts.fillcolor !== 'function') && + (typeof opts.line.color !== 'function')) { + fullLayout._infolayer.selectAll('g.' + id).remove(); + return; + } + var zrange = _$d3_10.extent(((typeof opts.fillcolor === 'function') ? + opts.fillcolor : opts.line.color).domain()); + var linelevels = []; + var filllevels = []; + var linecolormap = typeof opts.line.color === 'function' ? + opts.line.color : function() { return opts.line.color; }; + var fillcolormap = typeof opts.fillcolor === 'function' ? + opts.fillcolor : function() { return opts.fillcolor; }; + var l; + var i; + + var l0 = opts.levels.end + opts.levels.size / 100, + ls = opts.levels.size, + zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), + zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); + for(i = 0; i < 1e5; i++) { + l = opts.levels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zr0 && l < zr1) linelevels.push(l); + } + + if(typeof opts.fillcolor === 'function') { + if(opts.filllevels) { + l0 = opts.filllevels.end + opts.filllevels.size / 100; + ls = opts.filllevels.size; + for(i = 0; i < 1e5; i++) { + l = opts.filllevels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zrange[0] && l < zrange[1]) filllevels.push(l); + } + } + else { + filllevels = linelevels.map(function(v) { + return v - opts.levels.size / 2; + }); + filllevels.push(filllevels[filllevels.length - 1] + + opts.levels.size); + } + } + else if(opts.fillcolor && typeof opts.fillcolor === 'string') { + // doesn't matter what this value is, with a single value + // we'll make a single fill rect covering the whole bar + filllevels = [0]; + } + + if(opts.levels.size < 0) { + linelevels.reverse(); + filllevels.reverse(); + } + + // now make a Plotly Axes object to scale with and draw ticks + // TODO: does not support orientation other than right + + // we calculate pixel sizes based on the specified graph size, + // not the actual (in case something pushed the margins around) + // which is a little odd but avoids an odd iterative effect + // when the colorbar itself is pushing the margins. + // but then the fractional size is calculated based on the + // actual graph size, so that the axes will size correctly. + var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, + originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, + thickPx = Math.round(opts.thickness * + (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), + thickFrac = thickPx / gs.w, + lenPx = Math.round(opts.len * + (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), + lenFrac = lenPx / gs.h, + xpadFrac = opts.xpad / gs.w, + yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, + ypadFrac = opts.ypad / gs.h, + + // x positioning: do it initially just for left anchor, + // then fix at the end (since we don't know the width yet) + xLeft = Math.round(opts.x * gs.w + opts.xpad), + // for dragging... this is getting a little muddled... + xLeftFrac = opts.x - thickFrac * + ({middle: 0.5, right: 1}[opts.xanchor]||0), + + // y positioning we can do correctly from the start + yBottomFrac = opts.y + lenFrac * + (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), + yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), + yTopPx = yBottomPx - lenPx, + titleEl, + cbAxisIn = { + type: 'linear', + range: zrange, + tickmode: opts.tickmode, + nticks: opts.nticks, + tick0: opts.tick0, + dtick: opts.dtick, + tickvals: opts.tickvals, + ticktext: opts.ticktext, + ticks: opts.ticks, + ticklen: opts.ticklen, + tickwidth: opts.tickwidth, + tickcolor: opts.tickcolor, + showticklabels: opts.showticklabels, + tickfont: opts.tickfont, + tickangle: opts.tickangle, + tickformat: opts.tickformat, + exponentformat: opts.exponentformat, + separatethousands: opts.separatethousands, + showexponent: opts.showexponent, + showtickprefix: opts.showtickprefix, + tickprefix: opts.tickprefix, + showticksuffix: opts.showticksuffix, + ticksuffix: opts.ticksuffix, + title: opts.title, + titlefont: opts.titlefont, + showline: true, + anchor: 'free', + position: 1 + }, + cbAxisOut = { + type: 'linear', + _id: 'y' + id + }, + axisOptions = { + letter: 'y', + font: fullLayout.font, + noHover: true, + calendar: fullLayout.calendar // not really necessary (yet?) + }; + + // Coerce w.r.t. Axes layoutAttributes: + // re-use axes.js logic without updating _fullData + function coerce(attr, dflt) { + return _$lib_166.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_220, attr, dflt); + } + + // Prepare the Plotly axis object + _$handleAxisDefaults_210(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handlePositionDefaults_223(cbAxisIn, cbAxisOut, coerce, axisOptions); + + // position can't go in through supplyDefaults + // because that restricts it to [0,1] + cbAxisOut.position = opts.x + xpadFrac + thickFrac; + + // save for other callers to access this axis + component.axis = cbAxisOut; + + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + cbAxisOut.titleside = opts.titleside; + cbAxisOut.titlex = opts.x + xpadFrac; + cbAxisOut.titley = yBottomFrac + + (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + } + + if(opts.line.color && opts.tickmode === 'auto') { + cbAxisOut.tickmode = 'linear'; + cbAxisOut.tick0 = opts.levels.start; + var dtick = opts.levels.size; + // expand if too many contours, so we don't get too many ticks + var autoNtick = _$lib_166.constrain( + (yBottomPx - yTopPx) / 50, 4, 15) + 1, + dtFactor = (zrange[1] - zrange[0]) / + ((opts.nticks || autoNtick) * dtick); + if(dtFactor > 1) { + var dtexp = Math.pow(10, Math.floor( + Math.log(dtFactor) / Math.LN10)); + dtick *= dtexp * _$lib_166.roundUp(dtFactor / dtexp, [2, 5, 10]); + // if the contours are at round multiples, reset tick0 + // so they're still at round multiples. Otherwise, + // keep the first label on the first contour level + if((Math.abs(opts.levels.start) / + opts.levels.size + 1e-6) % 1 < 2e-6) { + cbAxisOut.tick0 = 0; + } + } + cbAxisOut.dtick = dtick; + } + + // set domain after init, because we may want to + // allow it outside [0,1] + cbAxisOut.domain = [ + yBottomFrac + ypadFrac, + yBottomFrac + lenFrac - ypadFrac + ]; + cbAxisOut.setScale(); + + // now draw the elements + var container = _$lib_166.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_10.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); + + container.attr('transform', 'translate(' + Math.round(gs.l) + + ',' + Math.round(gs.t) + ')'); + // TODO: this opposite transform is a hack until we make it + // more rational which items get this offset + var titleCont = container.select('.cbtitleunshift') + .attr('transform', 'translate(-' + + Math.round(gs.l) + ',-' + + Math.round(gs.t) + ')'); + + cbAxisOut._axislayer = container.select('.cbaxis'); + var titleHeight = 0; + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // draw the title so we know how much room it needs + // when we squish the axis. This one only applies to + // top or bottom titles, not right side. + var x = gs.l + (opts.x + xpadFrac) * gs.w, + fontSize = cbAxisOut.titlefont.size, + y; + + if(opts.titleside === 'top') { + y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + + gs.t + 3 + fontSize * 0.75; + } + else { + y = (1 - (yBottomFrac + ypadFrac)) * gs.h + + gs.t - 3 - fontSize * 0.25; + } + drawTitle(cbAxisOut._id + 'title', { + attributes: {x: x, y: y, 'text-anchor': 'start'} + }); + } + + function drawAxis() { + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // squish the axis top to make room for the title + var titleGroup = container.select('.cbtitle'), + titleText = titleGroup.select('text'), + titleTrans = + [-opts.outlinewidth / 2, opts.outlinewidth / 2], + mathJaxNode = titleGroup + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + lineSize = 15.6; + if(titleText.node()) { + lineSize = + parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_50; + } + if(mathJaxNode) { + titleHeight = _$drawing_71.bBox(mathJaxNode).height; + if(titleHeight > lineSize) { + // not entirely sure how mathjax is doing + // vertical alignment, but this seems to work. + titleTrans[1] -= (titleHeight - lineSize) / 2; + } + } + else if(titleText.node() && + !titleText.classed(cn.jsPlaceholder)) { + titleHeight = _$drawing_71.bBox(titleText.node()).height; + } + if(titleHeight) { + // buffer btwn colorbar and title + // TODO: configurable + titleHeight += 5; + + if(opts.titleside === 'top') { + cbAxisOut.domain[1] -= titleHeight / gs.h; + titleTrans[1] *= -1; + } + else { + cbAxisOut.domain[0] += titleHeight / gs.h; + var nlines = _$svg_text_utils_187.lineCount(titleText); + titleTrans[1] += (1 - nlines) * lineSize; + } + + titleGroup.attr('transform', + 'translate(' + titleTrans + ')'); + + cbAxisOut.setScale(); + } + } + + container.selectAll('.cbfills,.cblines') + .attr('transform', 'translate(0,' + + Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); + + cbAxisOut._axislayer.attr('transform', 'translate(0,' + + Math.round(-gs.t) + ')'); + + var fills = container.select('.cbfills') + .selectAll('rect.cbfill') + .data(filllevels); + fills.enter().append('rect') + .classed(cn.cbfill, true) + .style('stroke', 'none'); + fills.exit().remove(); + fills.each(function(d, i) { + var z = [ + (i === 0) ? zrange[0] : + (filllevels[i] + filllevels[i - 1]) / 2, + (i === filllevels.length - 1) ? zrange[1] : + (filllevels[i] + filllevels[i + 1]) / 2 + ] + .map(cbAxisOut.c2p) + .map(Math.round); + + // offset the side adjoining the next rectangle so they + // overlap, to prevent antialiasing gaps + if(i !== filllevels.length - 1) { + z[1] += (z[1] > z[0]) ? 1 : -1; + } + + + // Tinycolor can't handle exponents and + // at this scale, removing it makes no difference. + var colorString = fillcolormap(d).replace('e-', ''), + opaqueColor = _$tinycolor_28(colorString).toHexString(); + + // Colorbar cannot currently support opacities so we + // use an opaque fill even when alpha channels present + _$d3_10.select(this).attr({ + x: xLeft, + width: Math.max(thickPx, 2), + y: _$d3_10.min(z), + height: Math.max(_$d3_10.max(z) - _$d3_10.min(z), 2), + fill: opaqueColor + }); + }); + + var lines = container.select('.cblines') + .selectAll('path.cbline') + .data(opts.line.color && opts.line.width ? + linelevels : []); + lines.enter().append('path') + .classed(cn.cbline, true); + lines.exit().remove(); + lines.each(function(d) { + _$d3_10.select(this) + .attr('d', 'M' + xLeft + ',' + + (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + + 'h' + thickPx) + .call(_$drawing_71.lineGroupStyle, + opts.line.width, linecolormap(d), opts.line.dash); + }); + + // force full redraw of labels and ticks + cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') + .remove(); + + cbAxisOut._pos = xLeft + thickPx + + (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); + cbAxisOut.side = 'right'; + + // separate out axis and title drawing, + // so we don't need such complicated logic in Titles.draw + // if title is on the top or bottom, we've already drawn it + // this title call only handles side=right + return _$lib_166.syncOrAsync([ + function() { + return _$axes_208.doTicks(gd, cbAxisOut, true); + }, + function() { + if(['top', 'bottom'].indexOf(opts.titleside) === -1) { + var fontSize = cbAxisOut.titlefont.size, + y = cbAxisOut._offset + cbAxisOut._length / 2, + x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? + 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : + -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); + + // the 'h' + is a hack to get around the fact that + // convertToTspans rotates any 'y...' class by 90 degrees. + // TODO: find a better way to control this. + drawTitle('h' + cbAxisOut._id + 'title', { + avoid: { + selection: _$d3_10.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), + side: opts.titleside, + offsetLeft: gs.l, + offsetTop: 0, + maxShift: fullLayout.width + }, + attributes: {x: x, y: y, 'text-anchor': 'middle'}, + transform: {rotate: '-90', offset: 0} + }); + } + }]); + } + + function drawTitle(titleClass, titleOpts) { + var trace = getTrace(), + propName; + if(_$registry_248.traceIs(trace, 'markerColorscale')) { + propName = 'marker.colorbar.title'; + } + else propName = 'colorbar.title'; + + var dfltTitleOpts = { + propContainer: cbAxisOut, + propName: propName, + traceIndex: trace.index, + placeholder: fullLayout._dfltTitle.colorbar, + containerGroup: container.select('.cbtitle') + }; + + // this class-to-rotate thing with convertToTspans is + // getting hackier and hackier... delete groups with the + // wrong class (in case earlier the colorbar was drawn on + // a different side, I think?) + var otherClass = titleClass.charAt(0) === 'h' ? + titleClass.substr(1) : ('h' + titleClass); + container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') + .remove(); + + _$titles_139.draw(gd, titleClass, + __extendFlat_50(dfltTitleOpts, titleOpts || {})); + } + + function positionCB() { + // wait for the axis & title to finish rendering before + // continuing positioning + // TODO: why are we redrawing multiple times now with this? + // I guess autoMargin doesn't like being post-promise? + var innerWidth = thickPx + opts.outlinewidth / 2 + + _$drawing_71.bBox(cbAxisOut._axislayer.node()).width; + titleEl = titleCont.select('text'); + if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { + var mathJaxNode = titleCont + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + titleWidth; + if(mathJaxNode && + ['top', 'bottom'].indexOf(opts.titleside) !== -1) { + titleWidth = _$drawing_71.bBox(mathJaxNode).width; + } + else { + // note: the formula below works for all titlesides, + // (except for top/bottom mathjax, above) + // but the weird gs.l is because the titleunshift + // transform gets removed by Drawing.bBox + titleWidth = + _$drawing_71.bBox(titleCont.node()).right - + xLeft - gs.l; + } + innerWidth = Math.max(innerWidth, titleWidth); + } + + var outerwidth = 2 * opts.xpad + innerWidth + + opts.borderwidth + opts.outlinewidth / 2, + outerheight = yBottomPx - yTopPx; + + container.select('.cbbg').attr({ + x: xLeft - opts.xpad - + (opts.borderwidth + opts.outlinewidth) / 2, + y: yTopPx - yExtraPx, + width: Math.max(outerwidth, 2), + height: Math.max(outerheight + 2 * yExtraPx, 2) + }) + .call(_$color_46.fill, opts.bgcolor) + .call(_$color_46.stroke, opts.bordercolor) + .style({'stroke-width': opts.borderwidth}); + + container.selectAll('.cboutline').attr({ + x: xLeft, + y: yTopPx + opts.ypad + + (opts.titleside === 'top' ? titleHeight : 0), + width: Math.max(thickPx, 2), + height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) + }) + .call(_$color_46.stroke, opts.outlinecolor) + .style({ + fill: 'None', + 'stroke-width': opts.outlinewidth + }); + + // fix positioning for xanchor!='left' + var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * + outerwidth; + container.attr('transform', + 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); + + // auto margin adjustment + _$plots_240.autoMargin(gd, id, { + x: opts.x, + y: opts.y, + l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), + r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), + t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), + b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) + }); + } + + var cbDone = _$lib_166.syncOrAsync([ + _$plots_240.previousPromises, + drawAxis, + _$plots_240.previousPromises, + positionCB + ], gd); + + if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); + + // dragging... + if(gd._context.edits.colorbarPosition) { + var t0, + xf, + yf; + + _$dragelement_68.init({ + element: container.node(), + gd: gd, + prepFn: function() { + t0 = container.attr('transform'); + _$setCursor_185(container); + }, + moveFn: function(dx, dy) { + container.attr('transform', + t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); + + xf = _$dragelement_68.align(xLeftFrac + (dx / gs.w), thickFrac, + 0, 1, opts.xanchor); + yf = _$dragelement_68.align(yBottomFrac - (dy / gs.h), lenFrac, + 0, 1, opts.yanchor); + + var csr = _$dragelement_68.getCursor(xf, yf, + opts.xanchor, opts.yanchor); + _$setCursor_185(container, csr); + }, + doneFn: function() { + _$setCursor_185(container); + + if(xf !== undefined && yf !== undefined) { + _$registry_248.call('restyle', + gd, + {'colorbar.x': xf, 'colorbar.y': yf}, + getTrace().index + ); + } + } + }); + } + return cbDone; + } + + function getTrace() { + var idNum = id.substr(2), + i, + trace; + for(i = 0; i < gd._fullData.length; i++) { + trace = gd._fullData[i]; + if(trace.uid === idNum) return trace; + } + } + + // setter/getters for every item defined in opts + Object.keys(opts).forEach(function(name) { + component[name] = function(v) { + // getter + if(!arguments.length) return opts[name]; + + // setter - for multi-part properties, + // set only the parts that are provided + opts[name] = _$lib_166.isPlainObject(opts[name]) ? + _$lib_166.extendFlat(opts[name], v) : + v; + + return component; + }; + }); + + // or use .options to set multiple options at once via a dictionary + component.options = function(o) { + Object.keys(o).forEach(function(name) { + // in case something random comes through + // that's not an option, ignore it + if(typeof component[name] === 'function') { + component[name](o[name]); + } + }); + return component; + }; + + component._opts = opts; + + return component; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$colorscale_61 = require('../../components/colorscale'); */; +/* removed: var _$draw_50 = require('../../components/colorbar/draw'); */; + + +var _$colorbar_319 = function colorbar(gd, cd) { + var trace = cd[0].trace, + marker = trace.marker, + cbId = 'cb' + trace.uid; + + gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); + + // TODO make Colorbar.draw support multiple colorbar per trace + + if((marker === undefined) || !marker.showscale) { + _$plots_240.autoMargin(gd, cbId); + return; + } + + var vals = marker.color, + cmin = marker.cmin, + cmax = marker.cmax; + + if(!_$fastIsnumeric_13(cmin)) cmin = _$lib_166.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_13(cmax)) cmax = _$lib_166.aggNums(Math.max, null, vals); + + var cb = cd[0].t.cb = _$draw_50(gd, cbId); + var sclFunc = _$colorscale_61.makeColorScaleFunc( + _$colorscale_61.extractScale( + marker.colorscale, + cmin, + cmax + ), + { noNumericCheck: true } + ); + + cb.fillcolor(sclFunc) + .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) + .options(marker.colorbar)(); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +var Bar = {}; + +Bar.attributes = _$attributes_258; +Bar.layoutAttributes = _$layout_attributes_263; +Bar.supplyDefaults = _$supplyDefaults_260; +Bar.supplyLayoutDefaults = _$layout_defaults_264; +Bar.calc = _$calc_259; +Bar.setPositions = _$setPositions_267; +Bar.colorbar = _$colorbar_319; +Bar.arraysToCalcdata = _$arraysToCalcdata_257; +Bar.plot = _$plot_265; +Bar.style = _$style_269; +Bar.hoverPoints = _$hoverPoints_261; +Bar.selectPoints = _$selectPoints_266; + +Bar.moduleType = 'trace'; +Bar.name = 'bar'; +Bar.basePlotModule = _$cartesian_219; +Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend', 'draggedPts']; +Bar.meta = { + +}; + +var _$Bar_262 = Bar; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$bar_3 = _$Bar_262; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + + +var _$layout_attributes_272 = { + 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', + + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$layout_attributes_272 = require('./layout_attributes'); */; + +function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { + var hasTraceType; + var category = traceType + 'Layout'; + for(var i = 0; i < fullData.length; i++) { + if(_$registry_248.traceIs(fullData[i], 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_166.coerce(layoutIn, layoutOut, _$layout_attributes_272, attr, dflt); + } + _supply(layoutIn, layoutOut, fullData, coerce, 'box'); +} + +var _$layout_defaults_273 = { + supplyLayoutDefaults: supplyLayoutDefaults, + _supply: _supply +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$d3_10 = require('d3'); */; + +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; + +// constants for dynamic jitter (ie less jitter for sparser points) +var JITTERCOUNT = 5; // points either side of this to include +var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense" + +function plot(gd, plotinfo, cdbox) { + var fullLayout = gd._fullLayout; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + var boxtraces = plotinfo.plot.select('.boxlayer') + .selectAll('g.trace.boxes') + .data(cdbox) + .enter().append('g') + .attr('class', 'trace boxes'); + + boxtraces.each(function(d) { + var cd0 = d[0]; + var t = cd0.t; + var trace = cd0.trace; + var sel = _$d3_10.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; + var numBoxes = fullLayout._numBoxes; + + var groupFraction = (1 - fullLayout.boxgap); + + var group = (fullLayout.boxmode === 'group' && numBoxes > 1); + // box half width + var bdPos = t.dPos * groupFraction * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); + // box center offset + var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * groupFraction : 0; + // whisker width + var wdPos = bdPos * trace.whiskerwidth; + + if(trace.visible !== true || t.empty) { + sel.remove(); + return; + } + + var posAxis, valAxis; + + if(trace.orientation === 'h') { + posAxis = ya; + valAxis = xa; + } else { + posAxis = xa; + valAxis = ya; + } + + // save the box size and box position for use by hover + t.bPos = bPos; + t.bdPos = bdPos; + t.wdPos = wdPos; + // half-width within which to accept hover for this box + // always split the distance to the closest box + t.wHover = t.dPos * (group ? groupFraction / numBoxes : 1); + + // boxes and whiskers + plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, t); + + // draw points, if desired + if(trace.boxpoints) { + plotPoints(sel, {x: xa, y: ya}, trace, t); + } + + // draw mean (and stdev diamond) if desired + if(trace.boxmean) { + plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, t); + } + }); +} + +function plotBoxAndWhiskers(sel, axes, trace, t) { + var posAxis = axes.pos; + var valAxis = axes.val; + var bPos = t.bPos; + var wdPos = t.wdPos || 0; + var bPosPxOffset = t.bPosPxOffset || 0; + var whiskerWidth = trace.whiskerwidth || 0; + var notched = trace.notched || false; + var nw = notched ? 1 - 2 * trace.notchwidth : 1; + + // to support for one-sided box + var bdPos0; + var bdPos1; + if(Array.isArray(t.bdPos)) { + bdPos0 = t.bdPos[0]; + bdPos1 = t.bdPos[1]; + } else { + bdPos0 = t.bdPos; + bdPos1 = t.bdPos; + } + + sel.selectAll('path.box') + .data(_$lib_166.identity) + .enter().append('path') + .style('vector-effect', 'non-scaling-stroke') + .attr('class', 'box') + .each(function(d) { + var pos = d.pos; + var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset; + var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset; + var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset; + var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset; + var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset; + var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset; + var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset; + var q1 = valAxis.c2p(d.q1, true); + var q3 = valAxis.c2p(d.q3, true); + // make sure median isn't identical to either of the + // quartiles, so we can see it + var m = _$lib_166.constrain( + valAxis.c2p(d.med, true), + Math.min(q1, q3) + 1, Math.max(q1, q3) - 1 + ); + + // for compatibility with box, violin, and candlestick + // perhaps we should put this into cd0.t instead so it's more explicit, + // but what we have now is: + // - box always has d.lf, but boxpoints can be anything + // - violin has d.lf and should always use it (boxpoints is undefined) + // - candlestick has only min/max + var useExtremes = (d.lf === undefined) || (trace.boxpoints === false); + var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true); + var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true); + var ln = valAxis.c2p(d.ln, true); + var un = valAxis.c2p(d.un, true); + + if(trace.orientation === 'h') { + _$d3_10.select(this).attr('d', + 'M' + m + ',' + posm0 + 'V' + posm1 + // median line + 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge + (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge + 'H' + q3 + // end of the top edge + 'V' + pos0 + // right edge + (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge + 'Z' + // end of the box + 'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers + ((whiskerWidth === 0) ? '' : // whisker caps + 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1)); + } else { + _$d3_10.select(this).attr('d', + 'M' + posm0 + ',' + m + 'H' + posm1 + // median line + 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box + (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge + 'V' + q3 + // end of the right edge + 'H' + pos0 + // bottom of the box + (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge + 'Z' + // end of the box + 'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers + ((whiskerWidth === 0) ? '' : // whisker caps + 'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1)); + } + }); +} + +function plotPoints(sel, axes, trace, t) { + var xa = axes.x; + var ya = axes.y; + var bdPos = t.bdPos; + var bPos = t.bPos; + + // to support violin points + var mode = trace.boxpoints || trace.points; + + // repeatable pseudo-random number generator + _$lib_166.seedPseudoRandom(); + + sel.selectAll('g.points') + // since box plot points get an extra level of nesting, each + // box needs the trace styling info + .data(function(d) { + d.forEach(function(v) { + v.t = t; + v.trace = trace; + }); + return d; + }) + .enter().append('g') + .attr('class', 'points') + .selectAll('path') + .data(function(d) { + var i; + + var pts = mode === 'all' ? + d.pts : + d.pts.filter(function(pt) { return (pt.v < d.lf || pt.v > d.uf); }); + + // normally use IQR, but if this is 0 or too small, use max-min + var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1); + var minSpread = typicalSpread * 1e-9; + var spreadLimit = typicalSpread * JITTERSPREAD; + var jitterFactors = []; + var maxJitterFactor = 0; + var newJitter; + + // dynamic jitter + if(trace.jitter) { + if(typicalSpread === 0) { + // edge case of no spread at all: fall back to max jitter + maxJitterFactor = 1; + jitterFactors = new Array(pts.length); + for(i = 0; i < pts.length; i++) { + jitterFactors[i] = 1; + } + } else { + for(i = 0; i < pts.length; i++) { + var i0 = Math.max(0, i - JITTERCOUNT); + var pmin = pts[i0].v; + var i1 = Math.min(pts.length - 1, i + JITTERCOUNT); + var pmax = pts[i1].v; + + if(mode !== 'all') { + if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf); + else pmin = Math.max(pmin, d.uf); + } + + var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0; + jitterFactor = _$lib_166.constrain(Math.abs(jitterFactor), 0, 1); + + jitterFactors.push(jitterFactor); + maxJitterFactor = Math.max(jitterFactor, maxJitterFactor); + } + } + newJitter = trace.jitter * 2 / (maxJitterFactor || 1); + } + + // fills in 'x' and 'y' in calcdata 'pts' item + for(i = 0; i < pts.length; i++) { + var pt = pts[i]; + var v = pt.v; + + var jitterOffset = trace.jitter ? + (newJitter * jitterFactors[i] * (_$lib_166.pseudoRandom() - 0.5)) : + 0; + + var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset); + + if(trace.orientation === 'h') { + pt.y = posPx; + pt.x = v; + } else { + pt.x = posPx; + pt.y = v; + } + + // tag suspected outliers + if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) { + pt.so = true; + } + } + + return pts; + }) + .enter().append('path') + .classed('point', true) + .call(_$drawing_71.translatePoints, xa, ya); +} + +function plotBoxMean(sel, axes, trace, t) { + var posAxis = axes.pos; + var valAxis = axes.val; + var bPos = t.bPos; + var bPosPxOffset = t.bPosPxOffset || 0; + + // to support for one-sided box + var bdPos0; + var bdPos1; + if(Array.isArray(t.bdPos)) { + bdPos0 = t.bdPos[0]; + bdPos1 = t.bdPos[1]; + } else { + bdPos0 = t.bdPos; + bdPos1 = t.bdPos; + } + + sel.selectAll('path.mean') + .data(_$lib_166.identity) + .enter().append('path') + .attr('class', 'mean') + .style({ + fill: 'none', + 'vector-effect': 'non-scaling-stroke' + }) + .each(function(d) { + var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset; + var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset; + var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset; + var m = valAxis.c2p(d.mean, true); + var sl = valAxis.c2p(d.mean - d.sd, true); + var sh = valAxis.c2p(d.mean + d.sd, true); + + if(trace.orientation === 'h') { + _$d3_10.select(this).attr('d', + 'M' + m + ',' + pos0 + 'V' + pos1 + + (trace.boxmean === 'sd' ? + 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : + '') + ); + } else { + _$d3_10.select(this).attr('d', + 'M' + pos0 + ',' + m + 'H' + pos1 + + (trace.boxmean === 'sd' ? + 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : + '') + ); + } + }); +} + +var _$plot_274 = { + plot: plot, + plotBoxAndWhiskers: plotBoxAndWhiskers, + plotPoints: plotPoints, + plotBoxMean: plotBoxMean +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_166 = require('../../lib'); */; + +var orientations = ['v', 'h']; + +function setPositions(gd, plotinfo) { + var calcdata = gd.calcdata; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + for(var i = 0; i < orientations.length; i++) { + var orientation = orientations[i]; + var posAxis = orientation === 'h' ? ya : xa; + var boxList = []; + var minPad = 0; + var maxPad = 0; + + // make list of boxes / candlesticks + // For backward compatibility, candlesticks are treated as if they *are* box traces here + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j]; + var t = cd[0].t; + var trace = cd[0].trace; + + if(trace.visible === true && + (trace.type === 'box' || trace.type === 'candlestick') && + !t.empty && + (trace.orientation || 'v') === orientation && + trace.xaxis === xa._id && + trace.yaxis === ya._id + ) { + boxList.push(j); + + if(trace.boxpoints) { + minPad = Math.max(minPad, trace.jitter - trace.pointpos - 1); + maxPad = Math.max(maxPad, trace.jitter + trace.pointpos - 1); + } + } + } + + setPositionOffset('box', gd, boxList, posAxis, [minPad, maxPad]); + } +} + +function setPositionOffset(traceType, gd, boxList, posAxis, pad) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; + var pointList = []; + + // N.B. reused in violin + var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes'; + + var i, j, calcTrace; + + // make list of box points + for(i = 0; i < boxList.length; i++) { + calcTrace = calcdata[boxList[i]]; + for(j = 0; j < calcTrace.length; j++) { + pointList.push(calcTrace[j].pos); + } + } + + if(!pointList.length) return; + + // box plots - update dPos based on multiple traces + // and then use for posAxis autorange + var boxdv = _$lib_166.distinctVals(pointList); + var dPos = boxdv.minDiff / 2; + + // if there's no duplication of x points, + // disable 'group' mode by setting counter to 1 + if(pointList.length === boxdv.vals.length) { + fullLayout[numKey] = 1; + } + + // check for forced minimum dtick + _$axes_208.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); + + // set the width of all boxes + for(i = 0; i < boxList.length; i++) { + calcTrace = calcdata[boxList[i]]; + calcTrace[0].t.dPos = dPos; + } + + var gap = fullLayout[traceType + 'gap']; + var groupgap = fullLayout[traceType + 'groupgap']; + var padfactor = (1 - gap) * (1 - groupgap) * dPos / fullLayout[numKey]; + + // autoscale the x axis - including space for points if they're off the side + // TODO: this will overdo it if the outermost boxes don't have + // their points as far out as the other boxes + _$axes_208.expand(posAxis, boxdv.vals, { + vpadminus: dPos + pad[0] * padfactor, + vpadplus: dPos + pad[1] * padfactor + }); +} + +var _$set_positions_275 = { + setPositions: setPositions, + setPositionOffset: setPositionOffset +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; + +var _$style_276 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_10.select(gd).selectAll('g.trace.boxes'); + + s.style('opacity', function(d) { return d[0].trace.opacity; }); + + s.each(function(d) { + var el = _$d3_10.select(this); + var trace = d[0].trace; + var lineWidth = trace.line.width; + + function styleBox(boxSel, lineWidth, lineColor, fillColor) { + boxSel.style('stroke-width', lineWidth + 'px') + .call(_$color_46.stroke, lineColor) + .call(_$color_46.fill, fillColor); + } + + var allBoxes = el.selectAll('path.box'); + + if(trace.type === 'candlestick') { + allBoxes.each(function(boxData) { + var thisBox = _$d3_10.select(this); + var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing' + styleBox(thisBox, container.line.width, container.line.color, container.fillcolor); + // TODO: custom selection style for candlesticks + thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1); + }); + } + else { + styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor); + el.selectAll('path.mean') + .style({ + 'stroke-width': lineWidth, + 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' + }) + .call(_$color_46.stroke, trace.line.color); + + var pts = el.selectAll('path.point'); + _$drawing_71.pointStyle(pts, trace, gd); + _$drawing_71.selectedPointStyle(pts, trace); + } + }); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$attributes_315 = require('../scatter/attributes'); */; +/* removed: var _$attributes_45 = require('../../components/color/attributes'); */; +var __extendFlat_271 = _$extend_160.extendFlat; + +var __scatterMarkerAttrs_271 = _$attributes_315.marker; +var __scatterMarkerLineAttrs_271 = __scatterMarkerAttrs_271.line; + +var _$attributes_271 = { + y: { + valType: 'data_array', + editType: 'calc+clearAxisTypes', }, - startarrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, + x: { + valType: 'data_array', + editType: 'calc+clearAxisTypes', - editType: 'calcIfAutorange+arraydraw', + }, + x0: { + valType: 'any', + + editType: 'calc+clearAxisTypes', }, - arrowwidth: { - valType: 'number', - min: 0.1, + y0: { + valType: 'any', - editType: 'calcIfAutorange+arraydraw', + editType: 'calc+clearAxisTypes', }, - standoff: { - valType: 'number', - min: 0, - dflt: 0, + name: { + valType: 'string', - editType: 'calcIfAutorange+arraydraw', + editType: 'calc+clearAxisTypes', }, - startstandoff: { + text: __extendFlat_271({}, _$attributes_315.text, { + + }), + whiskerwidth: { valType: 'number', min: 0, - dflt: 0, + max: 1, + dflt: 0.5, - editType: 'calcIfAutorange+arraydraw', + editType: 'calcIfAutorange', }, - ax: { - valType: 'any', + notched: { + valType: 'boolean', - editType: 'calcIfAutorange+arraydraw', + editType: 'calcIfAutorange', }, - ay: { - valType: 'any', + notchwidth: { + valType: 'number', + min: 0, + max: 0.5, + dflt: 0.25, - editType: 'calcIfAutorange+arraydraw', + editType: 'calcIfAutorange', }, - axref: { + boxpoints: { valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_212.idRegex.x.toString() - ], + values: ['all', 'outliers', 'suspectedoutliers', false], + dflt: 'outliers', - editType: 'calc', + editType: 'calcIfAutorange', }, - ayref: { + boxmean: { valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_212.idRegex.y.toString() - ], + values: [true, 'sd', false], + dflt: false, - editType: 'calc', + editType: 'calcIfAutorange', }, - // positioning - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_212.idRegex.x.toString() - ], + jitter: { + valType: 'number', + min: 0, + max: 1, - editType: 'calc', + editType: 'calcIfAutorange', }, - x: { - valType: 'any', + pointpos: { + valType: 'number', + min: -2, + max: 2, - editType: 'calcIfAutorange+arraydraw', + editType: 'calcIfAutorange', }, - xanchor: { + orientation: { valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'auto', + values: ['v', 'h'], - editType: 'calcIfAutorange+arraydraw', + editType: 'calc+clearAxisTypes', }, - xshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - + marker: { + outliercolor: { + valType: 'color', + dflt: 'rgba(0, 0, 0, 0)', + + editType: 'style', + + }, + symbol: __extendFlat_271({}, __scatterMarkerAttrs_271.symbol, + {arrayOk: false, editType: 'plot'}), + opacity: __extendFlat_271({}, __scatterMarkerAttrs_271.opacity, + {arrayOk: false, dflt: 1, editType: 'style'}), + size: __extendFlat_271({}, __scatterMarkerAttrs_271.size, + {arrayOk: false, editType: 'calcIfAutorange'}), + color: __extendFlat_271({}, __scatterMarkerAttrs_271.color, + {arrayOk: false, editType: 'style'}), + line: { + color: __extendFlat_271({}, __scatterMarkerLineAttrs_271.color, + {arrayOk: false, dflt: _$attributes_45.defaultLine, editType: 'style'} + ), + width: __extendFlat_271({}, __scatterMarkerLineAttrs_271.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' }, - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_212.idRegex.y.toString() - ], - - editType: 'calc', - + line: { + color: { + valType: 'color', + + editType: 'style', + + }, + width: { + valType: 'number', + + min: 0, + dflt: 2, + editType: 'style', + + }, + editType: 'plot' }, - y: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - + fillcolor: _$attributes_315.fillcolor, + + selected: { + marker: _$attributes_315.selected.marker, + editType: 'style' }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - + unselected: { + marker: _$attributes_315.unselected.marker, + editType: 'style' }, - yshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', + + hoveron: { + valType: 'flaglist', + flags: ['boxes', 'points'], + dflt: 'boxes+points', - }, - clicktoshow: { - valType: 'enumerated', - values: [false, 'onoff', 'onout'], - dflt: false, + editType: 'style', - editType: 'arraydraw', + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +var __extendFlat_293 = _$lib_166.extendFlat; +/* removed: var _$attributes_315 = require('../scatter/attributes'); */; +var __dash_293 = _$attributes_70.dash; + +var INCREASING_COLOR = '#3D9970'; +var DECREASING_COLOR = '#FF4136'; + +var lineAttrs = _$attributes_315.line; + +function directionAttrs(lineColorDefault) { + return { + line: { + color: __extendFlat_293({}, lineAttrs.color, {dflt: lineColorDefault}), + width: lineAttrs.width, + dash: __dash_293, + editType: 'style' + }, + editType: 'style' + }; +} + +var _$attributes_293 = { + + x: { + valType: 'data_array', + editType: 'calc+clearAxisTypes', }, - xclick: { - valType: 'any', - - editType: 'arraydraw', + + open: { + valType: 'data_array', + editType: 'calc', }, - yclick: { - valType: 'any', - - editType: 'arraydraw', + + high: { + valType: 'data_array', + editType: 'calc', }, - hovertext: { - valType: 'string', + + low: { + valType: 'data_array', + editType: 'calc', - editType: 'arraydraw', + }, + + close: { + valType: 'data_array', + editType: 'calc', }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - - editType: 'arraydraw', + + line: { + width: __extendFlat_293({}, lineAttrs.width, { - }, - font: _$font_attributes_234({ - editType: 'arraydraw', + }), + dash: __extendFlat_293({}, __dash_293, { }), - editType: 'arraydraw' + editType: 'style' }, - captureevents: { - valType: 'boolean', + + increasing: directionAttrs(INCREASING_COLOR), + + decreasing: directionAttrs(DECREASING_COLOR), + + text: { + valType: 'string', - editType: 'arraydraw', + dflt: '', + arrayOk: true, + editType: 'calc', }, - editType: 'calc', - _deprecated: { - ref: { - valType: 'string', - - editType: 'calc', - - } + tickwidth: { + valType: 'number', + min: 0, + max: 0.5, + dflt: 0.3, + + editType: 'calcIfAutorange', + } }; @@ -40359,1856 +41240,2069 @@ var _$attributes_31 = { 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; - -/* removed: var _$color_46 = require('../color'); */; - -/* removed: var _$arrow_paths_30 = require('./arrow_paths'); */; - -/** - * 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. - */ -var _$drawArrowHead_38 = function drawArrowHead(el3, ends, options) { - var el = el3.node(); - var headStyle = _$arrow_paths_30[options.arrowhead || 0]; - var startHeadStyle = _$arrow_paths_30[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; - } - } +var __extendFlat_277 = _$lib_166.extendFlat; +/* removed: var _$attributes_293 = require('../ohlc/attributes'); */; +/* removed: var _$attributes_271 = require('../box/attributes'); */; - if(backOff) { - if(backOff * backOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var backOffX = backOff * Math.cos(startRot), - backOffY = backOff * Math.sin(startRot); +function __directionAttrs_277(lineColorDefault) { + return { + line: { + color: __extendFlat_277({}, _$attributes_271.line.color, {dflt: lineColorDefault}), + width: _$attributes_271.line.width, + editType: 'style' + }, - end.x += backOffX; - end.y += backOffY; - el3.attr({x2: end.x, y2: end.y}); + fillcolor: _$attributes_271.fillcolor, + editType: 'style' + }; +} - } +var _$attributes_277 = { + x: _$attributes_293.x, + open: _$attributes_293.open, + high: _$attributes_293.high, + low: _$attributes_293.low, + close: _$attributes_293.close, - if(startBackOff) { - if(startBackOff * startBackOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var startBackOffX = startBackOff * Math.cos(startRot), - startbackOffY = startBackOff * Math.sin(startRot); + line: { + width: __extendFlat_277({}, _$attributes_271.line.width, { + + }), + editType: 'style' + }, - start.x -= startBackOffX; - start.y -= startbackOffY; - el3.attr({x1: start.x, y1: start.y}); + increasing: __directionAttrs_277(_$attributes_293.increasing.line.color.dflt), - } - } - 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 - dashArray = ''; + decreasing: __directionAttrs_277(_$attributes_293.decreasing.line.color.dflt), - if(pathlen < backOff + startBackOff) { - hideLine(); - return; - } + text: _$attributes_293.text, + whiskerwidth: __extendFlat_277({}, _$attributes_271.whiskerwidth, { dflt: 0 }) +}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 start0 = el.getPointAtLength(0); - var dstart = el.getPointAtLength(0.1); +'use strict'; - startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); - start = el.getPointAtLength(Math.min(startBackOff, pathlen)); +/* removed: var _$lib_166 = require('../../lib'); */; +var ____294 = _$lib_166._; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +var __BADNUM_294 = _$numerical_148.BADNUM; - dashArray = '0px,' + startBackOff + 'px,'; +function calc(gd, trace) { + var xa = _$axes_208.getFromId(gd, trace.xaxis); + var ya = _$axes_208.getFromId(gd, trace.yaxis); - var end0 = el.getPointAtLength(pathlen); - var dend = el.getPointAtLength(pathlen - 0.1); + var tickLen = convertTickWidth(gd, xa, trace); + var minDiff = trace._minDiff; + trace._minDiff = null; + var x = trace._xcalc; + trace._xcalc = null; - endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); - end = el.getPointAtLength(Math.max(0, pathlen - backOff)); + var cd = calcCommon(gd, trace, x, ya, ptFunc); - var shortening = dashArray ? startBackOff + backOff : backOff; - dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px'; + _$axes_208.expand(xa, x, {vpad: minDiff / 2}); - el3.style('stroke-dasharray', dashArray); + if(cd.length) { + _$lib_166.extendFlat(cd[0].t, { + wHover: minDiff / 2, + tickLen: tickLen + }); + return cd; + } else { + return [{t: {empty: true}}]; } +} - function hideLine() { el3.style('stroke-dasharray', '0px,100px'); } - - function drawhead(arrowHeadStyle, p, rot, arrowScale) { - if(!arrowHeadStyle.path) return; - if(arrowHeadStyle.noRotate) rot = 0; +function ptFunc(o, h, l, c) { + return { + o: o, + h: h, + l: l, + c: c + }; +} - _$d3_10.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_46.rgb(options.arrowcolor), - 'stroke-width': 0 - }); - } - if(doStart) drawhead(startHeadStyle, start, startRot, startScale); - if(doEnd) drawhead(headStyle, end, endRot, scale); -}; +// shared between OHLC and candlestick +// ptFunc makes a calcdata point specific to each trace type, from oi, hi, li, ci +function calcCommon(gd, trace, x, ya, ptFunc) { + var o = ya.makeCalcdata(trace, 'open'); + var h = ya.makeCalcdata(trace, 'high'); + var l = ya.makeCalcdata(trace, 'low'); + var c = ya.makeCalcdata(trace, 'close'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 hasTextArray = Array.isArray(trace.text); -'use strict'; + // we're optimists - before we have any changing data, assume increasing + var increasing = true; + var cPrev = null; -/* removed: var _$d3_10 = require('d3'); */; + var cd = []; + for(var i = 0; i < x.length; i++) { + var xi = x[i]; + var oi = o[i]; + var hi = h[i]; + var li = l[i]; + var ci = c[i]; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$fx_88 = require('../fx'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_184 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$drawArrowHead_38 = require('./draw_arrow_head'); */; + if(xi !== __BADNUM_294 && oi !== __BADNUM_294 && hi !== __BADNUM_294 && li !== __BADNUM_294 && ci !== __BADNUM_294) { + if(ci === oi) { + // if open == close, look for a change from the previous close + if(cPrev !== null && ci !== cPrev) increasing = ci > cPrev; + // else (c === cPrev or cPrev is null) no change + } + else increasing = ci > oi; -// Annotations are stored in gd.layout.annotations, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one + cPrev = ci; -var _$draw_37 = { - draw: __draw_37, - drawOne: drawOne, - drawRaw: drawRaw -}; + var pt = ptFunc(oi, hi, li, ci); -/* - * draw: draw all annotations without any new modifications - */ -function __draw_37(gd) { - var fullLayout = gd._fullLayout; + pt.pos = xi; + pt.yc = (oi + ci) / 2; + pt.i = i; + pt.dir = increasing ? 'increasing' : 'decreasing'; - fullLayout._infolayer.selectAll('.annotation').remove(); + if(hasTextArray) pt.tx = trace.text[i]; - for(var i = 0; i < fullLayout.annotations.length; i++) { - if(fullLayout.annotations[i].visible) { - drawOne(gd, i); + cd.push(pt); } } - return _$plots_240.previousPromises(gd); -} + _$axes_208.expand(ya, l.concat(h), {padded: true}); -/* - * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications - * - * index (int): the annotation to draw - */ -function drawOne(gd, index) { - var fullLayout = gd._fullLayout; - var options = fullLayout.annotations[index] || {}; - var xa = _$axes_207.getFromId(gd, options.xref); - var ya = _$axes_207.getFromId(gd, options.yref); + if(cd.length) { + cd[0].t = { + labels: { + open: ____294(gd, 'open:') + ' ', + high: ____294(gd, 'high:') + ' ', + low: ____294(gd, 'low:') + ' ', + close: ____294(gd, 'close:') + ' ' + } + }; + } - drawRaw(gd, options, index, false, xa, ya); + return cd; } -/** - * drawRaw: draw a single annotation, potentially with modifications - * - * @param {DOM element} gd - * @param {object} options : this annotation's fullLayout options - * @param {integer} index : index in 'annotations' container of the annotation to draw - * @param {string} subplotId : id of the annotation's subplot - * - use false for 2d (i.e. cartesian or paper-ref) annotations - * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px - * @param {object | undefined} ya : ... y-axis +/* + * find min x-coordinates difference of all traces + * attached to this x-axis and stash the result in _minDiff + * in all traces; when a trace uses this in its + * calc step it deletes _minDiff, so that next calc this is + * done again in case the data changed. + * also since we need it here, stash _xcalc on the trace */ -function drawRaw(gd, options, index, subplotId, xa, ya) { - var fullLayout = gd._fullLayout; - var gs = gd._fullLayout._size; - var edits = gd._context.edits; +function convertTickWidth(gd, xa, trace) { + var minDiff = trace._minDiff; - var className; - var annbase; + if(!minDiff) { + var fullData = gd._fullData, + ohlcTracesOnThisXaxis = []; - if(subplotId) { - className = 'annotation-' + subplotId; - annbase = subplotId + '.annotations[' + index + ']'; - } else { - className = 'annotation'; - annbase = 'annotations[' + index + ']'; - } + minDiff = Infinity; - // remove the existing annotation if there is one - fullLayout._infolayer - .selectAll('.' + className + '[data-index="' + index + '"]') - .remove(); + var i; - var annClipID = 'clip' + fullLayout._uid + '_ann' + index; + for(i = 0; i < fullData.length; i++) { + var tracei = fullData[i]; - // this annotation is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!options._input || options.visible === false) { - _$d3_10.selectAll('#' + annClipID).remove(); - return; - } + if(tracei.type === 'ohlc' && + tracei.visible === true && + tracei.xaxis === xa._id + ) { + ohlcTracesOnThisXaxis.push(tracei); - // calculated pixel positions - // x & y each will get text, head, and tail as appropriate - var annPosPx = {x: {}, y: {}}, - textangle = +options.textangle || 0; + var xcalc = xa.makeCalcdata(tracei, 'x'); + tracei._xcalc = xcalc; - // create the components - // made a single group to contain all, so opacity can work right - // with border/arrow together this could handle a whole bunch of - // cleanup at this point, but works for now - var annGroup = fullLayout._infolayer.append('g') - .classed(className, true) - .attr('data-index', String(index)) - .style('opacity', options.opacity); + var _minDiff = _$lib_166.distinctVals(xcalc).minDiff; + if(_minDiff && isFinite(_minDiff)) { + minDiff = Math.min(minDiff, _minDiff); + } + } + } - // another group for text+background so that they can rotate together - var annTextGroup = annGroup.append('g') - .classed('annotation-text-g', true); + // if minDiff is still Infinity here, set it to 1 + if(minDiff === Infinity) minDiff = 1; - var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; - var textEvents = options.captureevents || edits.annotationText || editTextPosition; + for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) { + ohlcTracesOnThisXaxis[i]._minDiff = minDiff; + } + } - var annTextGroupInner = annTextGroup.append('g') - .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_184, 'default') - .on('click', function() { - gd._dragging = false; + return minDiff * trace.tickwidth; +} - var eventData = { - index: index, - annotation: options._input, - fullAnnotation: options, - event: _$d3_10.event - }; +var _$calc_294 = { + calc: calc, + calcCommon: calcCommon +}; - if(subplotId) { - eventData.subplotId = subplotId; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - gd.emit('plotly_clickannotation', eventData); - }); +'use strict'; - if(options.hovertext) { - annTextGroupInner - .on('mouseover', function() { - var hoverOptions = options.hoverlabel; - var hoverFont = hoverOptions.font; - var bBox = this.getBoundingClientRect(); - var bBoxRef = gd.getBoundingClientRect(); +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; - _$fx_88.loneHover({ - x0: bBox.left - bBoxRef.left, - x1: bBox.right - bBoxRef.left, - y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, - text: options.hovertext, - color: hoverOptions.bgcolor, - borderColor: hoverOptions.bordercolor, - fontFamily: hoverFont.family, - fontSize: hoverFont.size, - fontColor: hoverFont.color - }, { - container: fullLayout._hoverlayer.node(), - outerContainer: fullLayout._paper.node(), - gd: gd - }); - }) - .on('mouseout', function() { - _$fx_88.loneUnhover(fullLayout._hoverlayer.node()); - }); - } +var __calcCommon_278 = _$calc_294.calcCommon; - var borderwidth = options.borderwidth, - borderpad = options.borderpad, - borderfull = borderwidth + borderpad; +var _$calc_278 = function(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axes_208.getFromId(gd, trace.xaxis); + var ya = _$axes_208.getFromId(gd, trace.yaxis); - var annTextBG = annTextGroupInner.append('rect') - .attr('class', 'bg') - .style('stroke-width', borderwidth + 'px') - .call(_$color_46.stroke, options.bordercolor) - .call(_$color_46.fill, options.bgcolor); + var x = xa.makeCalcdata(trace, 'x'); - var isSizeConstrained = options.width || options.height; + var cd = __calcCommon_278(gd, trace, x, ya, __ptFunc_278); - var annTextClip = fullLayout._topclips - .selectAll('#' + annClipID) - .data(isSizeConstrained ? [0] : []); + if(cd.length) { + _$lib_166.extendFlat(cd[0].t, { + num: fullLayout._numBoxes, + dPos: _$lib_166.distinctVals(x).minDiff / 2, + posLetter: 'x', + valLetter: 'y', + }); - annTextClip.enter().append('clipPath') - .classed('annclip', true) - .attr('id', annClipID) - .append('rect'); - annTextClip.exit().remove(); + fullLayout._numBoxes++; + return cd; + } else { + return [{t: {empty: true}}]; + } +}; - var font = options.font; +function __ptFunc_278(o, h, l, c) { + return { + min: l, + q1: Math.min(o, c), + med: c, + q3: Math.max(o, c), + max: h, + }; +} - var annText = annTextGroupInner.append('text') - .classed('annotation-text', true) - .text(options.text); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function textLayout(s) { - s.call(_$drawing_71.font, font) - .attr({ - 'text-anchor': { - left: 'start', - right: 'end' - }[options.align] || 'middle' - }); - _$svg_text_utils_186.convertToTspans(s, gd, drawGraphicalElements); - return s; - } +'use strict'; - function drawGraphicalElements() { - // if the text has *only* a link, make the whole box into a link - var anchor3 = annText.selectAll('a'); - if(anchor3.size() === 1 && anchor3.text() === annText.text()) { - var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ - 'xlink:xlink:href': anchor3.attr('xlink:href'), - 'xlink:xlink:show': anchor3.attr('xlink:show') - }) - .style({cursor: 'pointer'}); +/* removed: var _$registry_248 = require('../../registry'); */; - wholeLink.node().appendChild(annTextBG.node()); - } - var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); - var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = _$drawing_71.bBox( - (hasMathjax ? mathjaxGroup : annText).node()); - var textWidth = anntextBB.width; - var textHeight = anntextBB.height; - var annWidth = options.width || textWidth; - var annHeight = options.height || textHeight; - var outerWidth = Math.round(annWidth + 2 * borderfull); - var outerHeight = Math.round(annHeight + 2 * borderfull); +var _$handleOHLC_298 = 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'); + var handleCalendarDefaults = _$registry_248.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x'], layout); - // save size in the annotation object for use by autoscale - options._w = annWidth; - options._h = annHeight; + if(!(open && high && low && close)) return; - function shiftFraction(v, anchor) { - if(anchor === 'auto') { - if(v < 1 / 3) anchor = 'left'; - else if(v > 2 / 3) anchor = 'right'; - else anchor = 'center'; - } - return { - center: 0, - middle: 0, - left: 0.5, - bottom: -0.5, - right: -0.5, - top: 0.5 - }[anchor]; - } + var len = Math.min(open.length, high.length, low.length, close.length); - var annotationIsOffscreen = false; - var letters = ['x', 'y']; + if(x) len = Math.min(len, x.length); - for(var i = 0; i < letters.length; i++) { - var axLetter = letters[i], - axRef = options[axLetter + 'ref'] || axLetter, - tailRef = options['a' + axLetter + 'ref'], - ax = {x: xa, y: ya}[axLetter], - dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, - // note that these two can be either positive or negative - annSizeFromWidth = outerWidth * Math.cos(dimAngle), - annSizeFromHeight = outerHeight * Math.sin(dimAngle), - // but this one is the positive total size - annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), - anchor = options[axLetter + 'anchor'], - overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), - posPx = annPosPx[axLetter], - basePx, - textPadShift, - alignPosition, - autoAlignFraction, - textShift; + traceOut._length = len; - /* - * calculate the *primary* pixel position - * which is the arrowhead if there is one, - * otherwise the text anchor point - */ - if(ax) { - /* - * hide the annotation if it's pointing outside the visible plot - * as long as the axis isn't autoranged - then we need to draw it - * anyway to get its bounding box. When we're dragging, an axis can - * still look autoranged even though it won't be when the drag finishes. - */ - var posFraction = ax.r2fraction(options[axLetter]); - if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { - if(tailRef === axRef) { - posFraction = ax.r2fraction(options['a' + axLetter]); - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - } - } - else { - annotationIsOffscreen = true; - } + return len; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(annotationIsOffscreen) continue; - } - 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; +'use strict'; - var arrowLength = options['a' + axLetter]; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$handleOHLC_298 = require('../ohlc/ohlc_defaults'); */; +/* removed: var _$attributes_277 = require('./attributes'); */; - // with an arrow, the text rotates around the anchor point - textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - - annSizeFromHeight * shiftFraction(0.5, options.yanchor); +var _$supplyDefaults_279 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_166.coerce(traceIn, traceOut, _$attributes_277, attr, dflt); + } - 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; - } + var len = _$handleOHLC_298(traceIn, traceOut, coerce, layout); + if(!len) { + traceOut.visible = false; + return; + } - posPx.text = posPx.tail + textShift; + coerce('line.width'); - // 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_165.constrain(posPx.head, 1, maxPx - 1); - } - if(tailRef === 'pixel') { - var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), - 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; - } - } + handleDirection(traceIn, traceOut, coerce, 'increasing'); + handleDirection(traceIn, traceOut, coerce, 'decreasing'); - 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; - } + coerce('text'); + coerce('whiskerwidth'); - posPx.text += overallShift; - textShift += overallShift; - textPadShift += overallShift; + layout._requestRangeslider[traceOut.xaxis] = true; +}; - // padplus/minus are used by autorange - options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift; - options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift; +function handleDirection(traceIn, traceOut, coerce, direction) { + var lineColor = coerce(direction + '.line.color'); + coerce(direction + '.line.width', traceOut.line.width); + coerce(direction + '.fillcolor', _$color_46.addOpacity(lineColor, 0.5)); +} - // size/shift are used during dragging - options['_' + axLetter + 'size'] = annSize; - options['_' + axLetter + 'shift'] = textShift; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(annotationIsOffscreen) { - annTextGroupInner.remove(); - return; - } +'use strict'; - var xShift = 0; - var yShift = 0; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_88 = require('../../components/fx'); */; +/* removed: var _$color_46 = require('../../components/color'); */; +/* removed: var _$fillHoverText_323 = require('../scatter/fill_hover_text'); */; - 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); - } +var DIRSYMBOL = { + increasing: '▲', + decreasing: '▼' +}; - if(hasMathjax) { - mathjaxGroup.select('svg').attr({ - x: borderfull + xShift - 1, - y: borderfull + yShift - }) - .call(_$drawing_71.setClipUrl, isSizeConstrained ? annClipID : null); - } - else { - var texty = borderfull + yShift - anntextBB.top; - var textx = borderfull + xShift - anntextBB.left; +var _$hoverPoints_296 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var xa = pointData.xa; + var ya = pointData.ya; + var trace = cd[0].trace; + var t = cd[0].t; - annText.call(_$svg_text_utils_186.positionText, textx, texty) - .call(_$drawing_71.setClipUrl, isSizeConstrained ? annClipID : null); - } + var type = trace.type; + var minAttr = type === 'ohlc' ? 'l' : 'min'; + var maxAttr = type === 'ohlc' ? 'h' : 'max'; - annTextClip.select('rect').call(_$drawing_71.setRect, borderfull, borderfull, - annWidth, annHeight); + // potentially shift xval for grouped candlesticks + var centerShift = t.bPos || 0; + var x0 = xval - centerShift; - annTextBG.call(_$drawing_71.setRect, borderwidth / 2, borderwidth / 2, - outerWidth - borderwidth, outerHeight - borderwidth); + // ohlc and candlestick call displayHalfWidth different things... + var displayHalfWidth = t.bdPos || t.tickLen; + var hoverHalfWidth = t.wHover; - annTextGroupInner.call(_$drawing_71.setTranslate, - Math.round(annPosPx.x.text - outerWidth / 2), - Math.round(annPosPx.y.text - outerHeight / 2)); + // if two items are overlaying, let the narrowest one win + var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0]))); + var hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; + var spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; - /* - * 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 + ')'}); + function dx(di) { + var pos = di.pos - x0; + return _$fx_88.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance); + } - /* - * 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(); + function dy(di) { + return _$fx_88.inbox(di[minAttr] - yval, di[maxAttr] - yval, hoverPseudoDistance); + } - var headX = annPosPx.x.head, - headY = annPosPx.y.head, - tailX = annPosPx.x.tail + dx, - tailY = annPosPx.y.tail + dy, - textX = annPosPx.x.text + dx, - textY = annPosPx.y.text + dy, + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_88.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_88.getClosest(cd, distfn, pointData); - // find the edge of the text box, where we'll start the arrow: - // create transform matrix to rotate the text box corners - transform = _$lib_165.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_165.apply2DTransform(transform), - applyTransform2 = _$lib_165.apply2DTransform2(transform), + // skip the rest (for this trace) if we didn't find a close point + if(pointData.index === false) return []; - // calculate and transform bounding box - width = +annTextBG.attr('width'), - height = +annTextBG.attr('height'), - xLeft = textX - 0.5 * width, - xRight = xLeft + width, - yTop = textY - 0.5 * height, - yBottom = yTop + height, - edges = [ - [xLeft, yTop, xLeft, yBottom], - [xLeft, yBottom, xRight, yBottom], - [xRight, yBottom, xRight, yTop], - [xRight, yTop, xLeft, yTop] - ].map(applyTransform2); + // we don't make a calcdata point if we're missing any piece (x/o/h/l/c) + // so we need to fix the index here to point to the data arrays + var cdIndex = pointData.index; + var di = cd[cdIndex]; + var i = pointData.index = di.i; - // 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_165.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; - } + var dir = di.dir; + var container = trace[dir]; + var lc = container.line.color; - edges.forEach(function(x) { - var p = _$lib_165.segmentsIntersect(tailX, tailY, headX, headY, - x[0], x[1], x[2], x[3]); - if(p) { - tailX = p.x; - tailY = p.y; - } - }); + if(_$color_46.opacity(lc) && container.line.width) pointData.color = lc; + else pointData.color = container.fillcolor; - var strokewidth = options.arrowwidth, - arrowColor = options.arrowcolor, - arrowSide = options.arrowside; + pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true); + pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true); - var arrowGroup = annGroup.append('g') - .style({opacity: _$color_46.opacity(arrowColor)}) - .classed('annotation-arrow-g', true); + pointData.xLabelVal = di.pos; - var arrow = arrowGroup.append('path') - .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY) - .style('stroke-width', strokewidth + 'px') - .call(_$color_46.stroke, _$color_46.rgb(arrowColor)); + pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; + pointData.xSpike = xa.c2p(di.pos, true); - _$drawArrowHead_38(arrow, arrowSide, options); + function getLabelLine(attr) { + return t.labels[attr] + _$axes_208.hoverLabelText(ya, trace[attr][i]); + } - // 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) - .attr({ - d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), - transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' - }) - .style('stroke-width', (strokewidth + 6) + 'px') - .call(_$color_46.stroke, 'rgba(0,0,0,0)') - .call(_$color_46.fill, 'rgba(0,0,0,0)'); + var hoverinfo = trace.hoverinfo; + var hoverParts = hoverinfo.split('+'); + var isAll = hoverinfo === 'all'; + var hasY = isAll || hoverParts.indexOf('y') !== -1; + var hasText = isAll || hoverParts.indexOf('text') !== -1; - var update, - annx0, - anny0; + var textParts = hasY ? [ + getLabelLine('open'), + getLabelLine('high'), + getLabelLine('low'), + getLabelLine('close') + ' ' + DIRSYMBOL[dir] + ] : []; + if(hasText) _$fillHoverText_323(di, trace, textParts); - // dragger for the arrow & head: translates the whole thing - // (head/tail/text) all together - _$dragelement_68.init({ - element: arrowDrag.node(), - gd: gd, - prepFn: function() { - var pos = _$drawing_71.getTranslate(annTextGroupInner); + // don't make .yLabelVal or .text, since we're managing hoverinfo + // put it all in .extraText + pointData.extraText = textParts.join('
'); - annx0 = pos.x; - anny0 = pos.y; - update = {}; - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } - }, - moveFn: function(dx, dy) { - var annxy0 = applyTransform(annx0, anny0), - xcenter = annxy0[0] + dx, - ycenter = annxy0[1] + dy; - annTextGroupInner.call(_$drawing_71.setTranslate, xcenter, ycenter); + // this puts the label *and the spike* at the midpoint of the box, ie + // halfway between open and close, not between high and low. + pointData.y0 = pointData.y1 = ya.c2p(di.yc, true); - update[annbase + '.x'] = xa ? - xa.p2r(xa.r2p(options.x) + dx) : - (options.x + (dx / gs.w)); - update[annbase + '.y'] = ya ? - ya.p2r(ya.r2p(options.y) + dy) : - (options.y - (dy / gs.h)); + return [pointData]; +}; - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } +'use strict'; - arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); - annTextGroup.attr({ - transform: 'rotate(' + textangle + ',' + - xcenter + ',' + ycenter + ')' - }); - }, - doneFn: function() { - _$registry_247.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } +var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + // for (potentially grouped) candlesticks + var posOffset = cd[0].t.bPos || 0; + + if(polygon === false) { + // clear selection + for(i = 0; i < cd.length; i++) { + cd[i].selected = 0; + } + } else { + for(i = 0; i < cd.length; i++) { + var di = cd[i]; + + if(polygon.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)])) { + selection.push({ + pointNumber: di.i, + x: xa.c2d(di.pos), + y: ya.c2d(di.yc) }); + di.selected = 1; + } else { + di.selected = 0; } - }; + } + } - if(options.showarrow) drawArrow(0, 0); + return selection; +}; - // user dragging the annotation (text, not arrow) - if(editTextPosition) { - var update, - baseTextTransform; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // dragger for the textbox: if there's an arrow, just drag the - // textbox and tail, leave the head untouched - _$dragelement_68.init({ - element: annTextGroupInner.node(), - gd: gd, - prepFn: function() { - baseTextTransform = annTextGroup.attr('transform'); - update = {}; - }, - moveFn: function(dx, dy) { - var csr = 'pointer'; - if(options.showarrow) { - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } else { - update[annbase + '.ax'] = options.ax + dx; - } +'use strict'; - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } else { - update[annbase + '.ay'] = options.ay + dy; - } +var _$candlestick_280 = { + moduleType: 'trace', + name: 'candlestick', + basePlotModule: _$cartesian_219, + categories: ['cartesian', 'svg', 'showLegend', 'candlestick', 'boxLayout'], + meta: { + + }, - drawArrow(dx, dy); - } - else if(!subplotId) { - if(xa) { - update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); + attributes: _$attributes_277, + layoutAttributes: _$layout_attributes_272, + supplyLayoutDefaults: _$layout_defaults_273.supplyLayoutDefaults, + setPositions: _$set_positions_275.setPositions, + supplyDefaults: _$supplyDefaults_279, + calc: _$calc_278, + plot: _$plot_274.plot, + style: _$style_276, + hoverPoints: _$hoverPoints_296, + selectPoints: _$selectPoints_300 +}; - } else { - var widthFraction = options._xsize / gs.w, - xLeft = options.x + (options._xshift - options.xshift) / gs.w - - widthFraction / 2; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - update[annbase + '.x'] = _$dragelement_68.align(xLeft + dx / gs.w, - widthFraction, 0, 1, options.xanchor); - } +'use strict'; - if(ya) { - update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); - } else { - var heightFraction = options._ysize / gs.h, - yBottom = options.y - (options._yshift + options.yshift) / gs.h - - heightFraction / 2; +var _$candlestick_4 = _$candlestick_280; - update[annbase + '.y'] = _$dragelement_68.align(yBottom - dy / gs.h, - heightFraction, 0, 1, options.yanchor); - } - if(!xa || !ya) { - csr = _$dragelement_68.getCursor( - xa ? 0.5 : update[annbase + '.x'], - ya ? 0.5 : update[annbase + '.y'], - options.xanchor, options.yanchor - ); - } - } - else return; +var _$plotcss_1 = {}; +'use strict'; - annTextGroup.attr({ - transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform - }); +/* removed: var _$lib_166 = require('../src/lib'); */; +var rules = { + "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", + "X .modebar--hover": "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": "opacity:1;", + "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", + "X .modebar-group:first-child": "margin-left:0px;", + "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", + "X .modebar-btn svg": "position:relative;top:2px;", + "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", + "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", + "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", + "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", + "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 .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;" +}; - _$setCursor_184(annTextGroupInner, csr); - }, - doneFn: function() { - _$setCursor_184(annTextGroupInner); - _$registry_247.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } +for(var selector in rules) { + var fullSelector = selector.replace(/^,/,' ,') + .replace(/X/g, '.js-plotly-plot .plotly') + .replace(/Y/g, '.plotly-notifier'); + _$lib_166.addStyleRule(fullSelector, rules[selector]); +} + +'use strict'; + +var _$ploticon_2 = { + 'undo': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'home': { + 'width': 928.6, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'camera-retro': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoombox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'pan': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoom_plus': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoom_minus': { + 'width': 1000, + 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', + 'ascent': 850, + 'descent': -150 + }, + 'autoscale': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'tooltip_basic': { + 'width': 1500, + 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', + 'ascent': 850, + 'descent': -150 + }, + 'tooltip_compare': { + 'width': 1125, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'plotlylogo': { + 'width': 1542, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'z-axis': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + '3d_rotate': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'camera': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'movie': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'question': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'disk': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'lasso': { + 'width': 1031, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'selectbox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'spikeline': { + 'width': 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', + 'ascent': 850, + 'descent': -150 } +}; - if(edits.annotationText) { - annText.call(_$svg_text_utils_186.makeEditable, {delegate: annTextGroupInner, gd: gd}) - .call(textLayout) - .on('edit', function(_text) { - options.text = _text; - this.call(textLayout); +var _$browser_27 = {}; +// shim for using process in browser +var process = _$browser_27 = {}; - var update = {}; - update[annbase + '.text'] = options.text; +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } +var cachedSetTimeout; +var cachedClearTimeout; - _$registry_247.call('relayout', gd, update); - }); - } - else annText.call(textLayout); +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); } - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; - -var __draw_32 = _$draw_37.draw; - - -var _$calcAutorange_32 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - annotationList = _$lib_165.filterVisible(fullLayout.annotations); - - if(!annotationList.length || !gd._fullData.length) return; - - var annotationAxes = {}; - annotationList.forEach(function(ann) { - annotationAxes[ann.xref] = 1; - annotationAxes[ann.yref] = 1; - }); - - for(var axId in annotationAxes) { - var ax = _$axes_207.getFromId(gd, axId); - if(ax && ax.autorange) { - return _$lib_165.syncOrAsync([ - __draw_32, - annAutorange - ], gd); +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; } -}; - -function annAutorange(gd) { - var fullLayout = gd._fullLayout; - - // find the bounding boxes for each of these annotations' - // relative to their anchor points - // use the arrow and the text bg rectangle, - // as the whole anno may include hidden text in its bbox - _$lib_165.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_207.getFromId(gd, ann.xref), - ya = _$axes_207.getFromId(gd, ann.yref), - headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, - startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - - var headPlus, headMinus, startHeadPlus, startHeadMinus; - - if(xa && xa.autorange) { - headPlus = headSize + ann.xshift; - headMinus = headSize - ann.xshift; - startHeadPlus = startHeadSize + ann.xshift; - startHeadMinus = startHeadSize - ann.xshift; - - if(ann.axref === ann.xref) { - // expand for the arrowhead (padded by arrowhead) - _$axes_207.expand(xa, [xa.r2c(ann.x)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - // again for the textbox (padded by textbox) - _$axes_207.expand(xa, [xa.r2c(ann.ax)], { - ppadplus: Math.max(ann._xpadplus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, startHeadMinus) - }); - } - else { - startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; - startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_207.expand(xa, [xa.r2c(ann.x)], { - ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) - }); - } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); } + } - if(ya && ya.autorange) { - headPlus = headSize - ann.yshift; - headMinus = headSize + ann.yshift; - startHeadPlus = startHeadSize - ann.yshift; - startHeadMinus = startHeadSize + ann.yshift; - if(ann.ayref === ann.yref) { - _$axes_207.expand(ya, [ya.r2c(ann.y)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - _$axes_207.expand(ya, [ya.r2c(ann.ay)], { - ppadplus: Math.max(ann._ypadplus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, startHeadMinus) - }); - } - else { - startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; - startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_207.expand(ya, [ya.r2c(ann.y)], { - ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) - }); - } - } - }); } +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_247 = require('../../registry'); */; -var _$click_33 = { - 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; } +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -/* - * 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), - onSet = toggleSets.on, - offSet = toggleSets.off.concat(toggleSets.explicitOff), - update = {}, - i; - - if(!(onSet.length || offSet.length)) return; - - for(i = 0; i < onSet.length; i++) { - update['annotations[' + onSet[i] + '].visible'] = true; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - - for(i = 0; i < offSet.length; i++) { - update['annotations[' + offSet[i] + '].visible'] = false; + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } - - return _$registry_247.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, - onSet = [], - offSet = [], - explicitOffSet = [], - 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; +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; - 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; - } + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} - if(j === hoverLen) { - // no match - only turn this annotation OFF, and only if - // showmode is 'onout' - if(anni.visible && showMode === 'onout') offSet.push(i); - } +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; } } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; - return {on: onSet, off: offSet, explicitOff: explicitOffSet}; +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; } +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; -// to handle log axes until v2 -function clickData2r(d, ax) { - return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); -} +function __noop_27() {} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +process.on = __noop_27; +process.addListener = __noop_27; +process.once = __noop_27; +process.off = __noop_27; +process.removeListener = __noop_27; +process.removeAllListeners = __noop_27; +process.emit = __noop_27; +process.prependListener = __noop_27; +process.prependOnceListener = __noop_27; +process.listeners = function (name) { return [] } -'use strict'; +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_188 = require('../../lib/to_log_range'); */; +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -/* - * 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. +var _$es6Promise_11 = { exports: {} }; +(function (process,global){ +/*! + * @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 */ -var _$convertCoords_35 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); +(function (global, factory) { + typeof _$es6Promise_11.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_11.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; - if(!(toLog || fromLog)) return; +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} - var annotations = gd._fullLayout.annotations, - axLetter = ax._id.charAt(0), - ann, - attrPrefix; +function isFunction(x) { + return typeof x === 'function'; +} - function convert(attr) { - var currentVal = ann[attr], - newVal = null; +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} - if(toLog) newVal = _$toLogRange_188(currentVal, ax.range); - else newVal = Math.pow(10, currentVal); +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(); + } + } +}; - // if conversion failed, delete the value so it gets a default value - if(!_$fastIsnumeric_13(newVal)) newVal = null; +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} - doExtra(attrPrefix + attr, newVal); - } +function setAsap(asapFn) { + asap = asapFn; +} - for(var i = 0; i < annotations.length; i++) { - ann = annotations[i]; - attrPrefix = 'annotations[' + i + '].'; +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]'; - if(ann[axLetter + 'ref'] === ax._id) convert(axLetter); - if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter); - } -}; +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// 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); + }; +} -'use strict'; +// vertx +function useVertxTimer() { + return function () { + vertxNext(flush); + }; +} -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$color_46 = require('../color'); */; +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); -// defaults common to 'annotations' and 'annotations3d' -var _$handleAnnotationCommonDefaults_34 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { - coerce('opacity'); - var bgColor = coerce('bgcolor'); + return function () { + node.data = iterations = ++iterations % 2; + }; +} - var borderColor = coerce('bordercolor'); - var borderOpacity = _$color_46.opacity(borderColor); +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} - coerce('borderpad'); +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 borderWidth = coerce('borderwidth'); - var showArrow = coerce('showarrow'); +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; - coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); - coerce('textangle'); - _$lib_165.coerceFont(coerce, 'font', fullLayout.font); + callback(arg); - coerce('width'); - coerce('align'); + queue[i] = undefined; + queue[i + 1] = undefined; + } - var h = coerce('height'); - if(h) coerce('valign'); + len = 0; +} - if(showArrow) { - var arrowside = coerce('arrowside'); - var arrowhead; - var arrowsize; +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} - if(arrowside.indexOf('end') !== -1) { - arrowhead = coerce('arrowhead'); - arrowsize = coerce('arrowsize'); - } +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 && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} - if(arrowside.indexOf('start') !== -1) { - coerce('startarrowhead', arrowhead); - coerce('startarrowsize', arrowsize); - } - coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_46.defaultLine); - coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); - coerce('standoff'); - coerce('startstandoff'); +function then(onFulfillment, onRejection) { + var _arguments = arguments; - } + var parent = this; - var hoverText = coerce('hovertext'); - var globalHoverLabel = fullLayout.hoverlabel || {}; + var child = new this.constructor(noop); - if(hoverText) { - var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || - (_$color_46.opacity(bgColor) ? _$color_46.rgb(bgColor) : _$color_46.defaultLine) - ); + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } - var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || - _$color_46.contrast(hoverBG) - ); + var _state = parent._state; - _$lib_165.coerceFont(coerce, 'hoverlabel.font', { - family: globalHoverLabel.font.family, - size: globalHoverLabel.font.size, - color: globalHoverLabel.font.color || hoverBorder - }); - } + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } - coerce('captureevents', !!hoverText); -}; + return child; +} /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `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); + }); -'use strict'; + promise.then(function(value){ + // value === 1 + }); + ``` -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleAnnotationCommonDefaults_34 = require('./common_defaults'); */; -/* removed: var _$attributes_31 = require('./attributes'); */; + Instead of writing the above, your code now simply becomes the following: + ```javascript + let promise = Promise.resolve(1); -var _$handleAnnotationDefaults_29 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + promise.then(function(value){ + // value === 1 + }); + ``` - function coerce(attr, dflt) { - return _$lib_165.coerce(annIn, annOut, _$attributes_31, attr, dflt); - } + @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; - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - var clickToShow = coerce('clicktoshow'); + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } - if(!(visible || clickToShow)) return annOut; + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} - _$handleAnnotationCommonDefaults_34(annIn, annOut, fullLayout, coerce); +var PROMISE_ID = Math.random().toString(36).substring(16); - var showArrow = annOut.showarrow; +function noop() {} - // positioning - var axLetters = ['x', 'y'], - arrowPosDflt = [-10, -30], - gdMock = {_fullLayout: fullLayout}; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i]; +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; - // xref, yref - var axRef = _$axes_207.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); +var GET_THEN_ERROR = new ErrorObject(); - // x, y - _$axes_207.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} - if(showArrow) { - var arrowPosAttr = 'a' + axLetter, - // axref, ayref - aaxRef = _$axes_207.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} - // for now the arrow can only be on the same axis or specified as pixels - // TODO: sometime it might be interesting to allow it to be on *any* axis - // but that would require updates to drawing & autorange code and maybe more - if(aaxRef !== 'pixel' && aaxRef !== axRef) { - aaxRef = annOut[arrowPosAttr] = 'pixel'; - } +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} - // ax, ay - var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_207.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); - } +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} - // xanchor, yanchor - coerce(axLetter + 'anchor'); +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; - // xshift, yshift - coerce(axLetter + 'shift'); + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + _reject(promise, error); } + }, promise); +} - // if you have one coordinate you should have both - _$lib_165.noneOrAll(annIn, annOut, ['x', 'y']); +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); + }); + } +} - // if you have one part of arrow length you should have both - if(showArrow) { - _$lib_165.noneOrAll(annIn, annOut, ['ax', 'ay']); +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); } + } +} - if(clickToShow) { - var xClick = coerce('xclick'); - var yClick = coerce('yclick'); +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} - // put the actual click data to bind to into private attributes - // so we don't have to do this little bit of logic on every hover event - annOut._xclick = (xClick === undefined) ? - annOut.x : - _$axes_207.cleanPosition(xClick, gdMock, annOut.xref); - annOut._yclick = (yClick === undefined) ? - annOut.y : - _$axes_207.cleanPosition(yClick, gdMock, annOut.yref); - } +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } - return annOut; -}; + publish(promise); +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } -'use strict'; + promise._result = value; + promise._state = FULFILLED; -/* removed: var _$lib_165 = require('../lib'); */; + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} -/** Convenience wrapper for making array container logic DRY and consistent - * - * @param {object} parentObjIn - * user input object where the container in question is linked - * (i.e. either a user trace object or the user layout object) - * - * @param {object} parentObjOut - * full object where the coerced container will be linked - * (i.e. either a full trace object or the full layout object) - * - * @param {object} opts - * options object: - * - name {string} - * name of the key linking the container in question - * - handleItemDefaults {function} - * defaults method to be called on each item in the array container in question - * - * Its arguments are: - * - itemIn {object} item in user layout - * - itemOut {object} item in full layout - * - parentObj {object} (as in closure) - * - opts {object} (as in closure) - * - itemOpts {object} - * - itemIsNotPlainObject {boolean} - * N.B. - * - * - opts is passed to handleItemDefaults so it can also store - * links to supplementary data (e.g. fullData for layout components) - * - */ -var _$handleArrayContainerDefaults_203 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { - var name = opts.name; +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; - var previousContOut = parentObjOut[name]; + asap(publishRejection, promise); +} - var contIn = _$lib_165.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], - contOut = parentObjOut[name] = [], - i; +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; - for(i = 0; i < contIn.length; i++) { - var itemIn = contIn[i], - itemOut = {}, - itemOpts = {}; + parent._onerror = null; - if(!_$lib_165.isPlainObject(itemIn)) { - itemOpts.itemIsNotPlainObject = true; - itemIn = {}; - } + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; - opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); + if (length === 0 && parent._state) { + asap(publish, parent); + } +} - itemOut._input = itemIn; - itemOut._index = i; +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; - contOut.push(itemOut); - } + if (subscribers.length === 0) { + return; + } - // in case this array gets its defaults rebuilt independent of the whole layout, - // relink the private keys just for this array. - if(_$lib_165.isArrayOrTypedArray(previousContOut)) { - var len = Math.min(previousContOut.length, contOut.length); - for(i = 0; i < len; i++) { - _$lib_165.relinkPrivateKeys(contOut[i], previousContOut[i]); - } + 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); } -}; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} +var TRY_CATCH_ERROR = new ErrorObject(); -'use strict'; +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} -/* removed: var _$handleArrayContainerDefaults_203 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationDefaults_29 = require('./annotation_defaults'); */; +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + if (hasCallback) { + value = tryCatch(callback, detail); -var _$supplyLayoutDefaults_36 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'annotations', - handleItemDefaults: _$handleAnnotationDefaults_29 - }; + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } - _$handleArrayContainerDefaults_203(layoutIn, layoutOut, opts); -}; + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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); + } +} -'use strict'; +var id = 0; +function nextId() { + return id++; +} -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} -/** - * 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 - */ -var _$makeIncludeComponents_217 = function makeIncludeComponents(containerArrayName) { - return function includeComponents(layoutIn, layoutOut) { - var array = layoutIn[containerArrayName]; - if(!Array.isArray(array)) return; +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); - var Cartesian = _$registry_247.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'); + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - for(var i = 0; i < array.length; i++) { - var itemi = array[i]; - if(!_$lib_165.isPlainObject(itemi)) continue; + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; - var xref = itemi.xref; - var yref = itemi.yref; + this._result = new Array(this.length); - var hasXref = idRegex.x.test(xref); - var hasYref = idRegex.y.test(yref); - if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_165.pushUnique(layoutOut._basePlotModules, Cartesian); + 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()); + } +} - 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; - } +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; - /* - * 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); - } - } - } - }; +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); + } }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + if (resolve$$ === resolve) { + var _then = getThen(entry); -'use strict'; + 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); + } +}; -/* removed: var _$draw_37 = require('./draw'); */; -/* removed: var _$click_33 = require('./click'); */; +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; -var _$annotations_39 = { - moduleType: 'component', - name: 'annotations', + if (promise._state === PENDING) { + this._remaining--; - layoutAttributes: _$attributes_31, - supplyLayoutDefaults: _$supplyLayoutDefaults_36, - includeBasePlot: _$makeIncludeComponents_217('annotations'), + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } - calcAutorange: _$calcAutorange_32, - draw: _$draw_37.draw, - drawOne: _$draw_37.drawOne, - drawRaw: _$draw_37.drawRaw, + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; - hasClickToShow: _$click_33.hasClickToShow, - onClick: _$click_33.onClick, +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; - convertCoords: _$convertCoords_35 + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); }; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - + `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. -'use strict'; + Example: -/* removed: var _$attributes_31 = require('../annotations/attributes'); */; -var __overrideAll_40 = _$edit_types_192.overrideAll; + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; -var _$attributes_40 = __overrideAll_40({ - _isLinkedToArray: 'annotation', + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` - visible: _$attributes_31.visible, - x: { - valType: 'any', - - - }, - y: { - valType: 'any', - - - }, - z: { - valType: 'any', - - - }, - ax: { - valType: 'number', - - - }, - ay: { - valType: 'number', - - - }, + 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: - xanchor: _$attributes_31.xanchor, - xshift: _$attributes_31.xshift, - yanchor: _$attributes_31.yanchor, - yshift: _$attributes_31.yshift, + Example: - text: _$attributes_31.text, - textangle: _$attributes_31.textangle, - font: _$attributes_31.font, - width: _$attributes_31.width, - height: _$attributes_31.height, - opacity: _$attributes_31.opacity, - align: _$attributes_31.align, - valign: _$attributes_31.valign, - bgcolor: _$attributes_31.bgcolor, - bordercolor: _$attributes_31.bordercolor, - borderpad: _$attributes_31.borderpad, - borderwidth: _$attributes_31.borderwidth, - showarrow: _$attributes_31.showarrow, - arrowcolor: _$attributes_31.arrowcolor, - arrowhead: _$attributes_31.arrowhead, - startarrowhead: _$attributes_31.startarrowhead, - arrowside: _$attributes_31.arrowside, - arrowsize: _$attributes_31.arrowsize, - startarrowsize: _$attributes_31.startarrowsize, - arrowwidth: _$attributes_31.arrowwidth, - standoff: _$attributes_31.standoff, - startstandoff: _$attributes_31.startstandoff, - hovertext: _$attributes_31.hovertext, - hoverlabel: _$attributes_31.hoverlabel, - captureevents: _$attributes_31.captureevents, + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; - // maybes later? - // clicktoshow: annAtts.clicktoshow, - // xclick: annAtts.xclick, - // yclick: annAtts.yclick, + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` - // not needed! - // axref: 'pixel' - // ayref: 'pixel' - // xref: 'x' - // yref: 'y - // zref: 'z' -}, 'calc', 'from-root'); + @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; +} /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. -'use strict'; + Example: -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); -var _$convert_41 = function convert(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var anns = fullSceneLayout.annotations; + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); - for(var i = 0; i < anns.length; i++) { - mockAnnAxes(anns[i], scene); - } + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` - scene.fullLayout._infolayer - .selectAll('.annotation-' + scene.id) - .remove(); -}; + `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: -function mockAnnAxes(ann, scene) { - var fullSceneLayout = scene.fullSceneLayout; - var domain = fullSceneLayout.domain; - var size = scene.fullLayout._size; + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - var base = { - // this gets fill in on render - pdata: null, + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); - // to get setConvert to not execute cleanly - type: 'linear', + 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 + }); + ``` - // don't try to update them on `editable: true` - autorange: false, + An example real-world use case is implementing timeouts: - // set infinite range so that annotation draw routine - // does not try to remove 'outside-range' annotations, - // this case is handled in the render loop - range: [-Infinity, Infinity] - }; + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` - ann._xa = {}; - _$lib_165.extendFlat(ann._xa, base); - _$axes_207.setConvert(ann._xa); - ann._xa._offset = size.l + domain.x[0] * size.w; - ann._xa.l2p = function() { - return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); - }; + @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; - ann._ya = {}; - _$lib_165.extendFlat(ann._ya, base); - _$axes_207.setConvert(ann._ya); - ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; - ann._ya.l2p = function() { - return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); - }; + 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); + } + }); + } } /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: -'use strict'; + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_203 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationCommonDefaults_34 = require('../annotations/common_defaults'); */; -/* removed: var _$attributes_40 = require('./attributes'); */; + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` -var _$handleDefaults_42 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_203(sceneLayoutIn, sceneLayoutOut, { - name: 'annotations', - handleItemDefaults: __handleAnnotationDefaults_42, - fullLayout: opts.fullLayout - }); -}; + Instead of writing the above, your code now simply becomes the following: -function __handleAnnotationDefaults_42(annIn, annOut, sceneLayout, opts, itemOpts) { - function coerce(attr, dflt) { - return _$lib_165.coerce(annIn, annOut, _$attributes_40, attr, dflt); - } + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); - function coercePosition(axLetter) { - var axName = axLetter + 'axis'; + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` - // mock in such way that getFromId grabs correct 3D axis - var gdMock = { _fullLayout: {} }; - gdMock._fullLayout[axName] = sceneLayout[axName]; + @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; +} - return _$axes_207.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); - } +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."); +} - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - if(!visible) return annOut; +/** + 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. - _$handleAnnotationCommonDefaults_34(annIn, annOut, opts.fullLayout, coerce); + Terminology + ----------- - coercePosition('x'); - coercePosition('y'); - coercePosition('z'); + - `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. - // if you have one coordinate you should all three - _$lib_165.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + A promise can be in one of three states: pending, fulfilled, or rejected. - // hard-set here for completeness - annOut.xref = 'x'; - annOut.yref = 'y'; - annOut.zref = 'z'; + 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. - coerce('xanchor'); - coerce('yanchor'); - coerce('xshift'); - coerce('yshift'); + 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. - if(annOut.showarrow) { - annOut.axref = 'pixel'; - annOut.ayref = 'pixel'; - // TODO maybe default values should be bigger than the 2D case? - coerce('ax', -10); - coerce('ay', -30); + Basic Usage: + ------------ - // if you have one part of arrow length you should have both - _$lib_165.noneOrAll(annIn, annOut, ['ax', 'ay']); - } + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); - return annOut; -} + // on failure + reject(reason); + }); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + Advanced Usage: + --------------- -'use strict'; + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. -function xformMatrix(m, v) { - var out = [0, 0, 0, 0]; - var i, j; + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); - for(i = 0; i < 4; ++i) { - for(j = 0; j < 4; ++j) { - out[j] += m[4 * i + j] * v[i]; + 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 + ']')); + } } - } + }; + }); + } - return out; -} + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` -function project(camera, v) { - var p = xformMatrix(camera.projection, - xformMatrix(camera.view, - xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); - return p; -} + Unlike callbacks, promises are great composable primitives. -var _$project_237 = project; + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor */ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; -'use strict'; + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} -var __drawRaw_43 = _$draw_37.drawRaw; -/* removed: var _$project_237 = require('../../plots/gl3d/project'); */; -var axLetters = ['x', 'y', 'z']; +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; -var _$draw_43 = function draw(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var dataScale = scene.dataScale; - var anns = fullSceneLayout.annotations; +Promise.prototype = { + constructor: Promise, - for(var i = 0; i < anns.length; i++) { - var ann = anns[i]; - var annotationIsOffscreen = false; + /** + 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, - for(var j = 0; j < 3; j++) { - var axLetter = axLetters[j]; - var pos = ann[axLetter]; - var ax = fullSceneLayout[axLetter + 'axis']; - var posFraction = ax.r2fraction(pos); + /** + `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); + } +}; - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - break; - } +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'); } + } - if(annotationIsOffscreen) { - scene.fullLayout._infolayer - .select('.annotation-' + scene.id + '[data-index="' + i + '"]') - .remove(); - } else { - ann._pdata = _$project_237(scene.glplot.cameraParams, [ - fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], - fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], - fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] - ]); + var P = local.Promise; - __drawRaw_43(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + 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 +}).call(this,_$browser_27,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +_$es6Promise_11 = _$es6Promise_11.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -42219,42 +43313,65 @@ var _$draw_43 = function draw(scene) { 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; - -var _$annotations3d_44 = { - moduleType: 'component', - name: 'annotations3d', +/** + * All paths are tuned for maximum scalability of the arrowhead, + * ie throughout arrowwidth=0.3..3 the head is joined smoothly + * to the line, with the line coming from the left and ending at (0, 0). + * + * `backoff` is the distance to move the arrowhead and the end of the line, + * in order that the arrowhead points to the desired place, either at + * the tip of the arrow or (in the case of circle or square) + * the center of the symbol. + * + * `noRotate`, if truthy, says that this arrowhead should not rotate with the + * arrow. That's the case for squares, which should always be straight, and + * circles, for which it's irrelevant. + */ - schema: { - subplots: { - scene: {annotations: _$attributes_40} - } +var _$arrow_paths_30 = [ + // no arrow + { + path: '', + backoff: 0 }, - - layoutAttributes: _$attributes_40, - handleDefaults: _$handleDefaults_42, - includeBasePlot: includeGL3D, - - convert: _$convert_41, - draw: _$draw_43 -}; - -function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_247.subplotsRegistry.gl3d; - if(!GL3D) return; - - var attrRegex = GL3D.attrRegex; - - var keys = Object.keys(layoutIn); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; - if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_165.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_165.pushUnique(layoutOut._subplots.gl3d, k); - } + // wide with flat back + { + path: 'M-2.4,-3V3L0.6,0Z', + backoff: 0.6 + }, + // narrower with flat back + { + path: 'M-3.7,-2.5V2.5L1.3,0Z', + backoff: 1.3 + }, + // barbed + { + path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', + backoff: 1.55 + }, + // wide line-drawn + { + path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', + backoff: 1.6 + }, + // narrower line-drawn + { + path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', + backoff: 2 + }, + // circle + { + path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', + backoff: 0, + noRotate: true + }, + // square + { + path: 'M2,2V-2H-2V2Z', + backoff: 0, + noRotate: true } -} +]; /** * Copyright 2012-2018, Plotly, Inc. @@ -42266,105 +43383,346 @@ function includeGL3D(layoutIn, layoutOut) { 'use strict'; +/* removed: var _$arrow_paths_30 = require('./arrow_paths'); */; +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; +/* removed: var _$constants_213 = require('../../plots/cartesian/constants'); */; + + +var _$attributes_31 = { + _isLinkedToArray: 'annotation', -var _$attributes_73 = { visible: { valType: 'boolean', - editType: 'calc', + dflt: true, + editType: 'calcIfAutorange+arraydraw', }, - type: { + + text: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, + textangle: { + valType: 'angle', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + font: _$font_attributes_234({ + editType: 'calcIfAutorange+arraydraw', + colorEditType: 'arraydraw', + + }), + width: { + valType: 'number', + min: 1, + dflt: null, + + editType: 'calcIfAutorange+arraydraw', + + }, + height: { + valType: 'number', + min: 1, + dflt: null, + + editType: 'calcIfAutorange+arraydraw', + + }, + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + + }, + align: { valType: 'enumerated', - values: ['percent', 'constant', 'sqrt', 'data'], + values: ['left', 'center', 'right'], + dflt: 'center', - editType: 'calc', + editType: 'arraydraw', }, - symmetric: { - valType: 'boolean', + valign: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'middle', - editType: 'calc', + editType: 'arraydraw', }, - array: { - valType: 'data_array', - editType: 'calc', + bgcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', }, - arrayminus: { - valType: 'data_array', - editType: 'calc', + bordercolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', }, - value: { + borderpad: { valType: 'number', min: 0, - dflt: 10, + dflt: 1, - editType: 'calc', + editType: 'calcIfAutorange+arraydraw', }, - valueminus: { + borderwidth: { valType: 'number', min: 0, - dflt: 10, + dflt: 1, - editType: 'calc', + editType: 'calcIfAutorange+arraydraw', }, - traceref: { + // arrow + showarrow: { + valType: 'boolean', + dflt: true, + + editType: 'calcIfAutorange+arraydraw', + + }, + arrowcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + arrowhead: { valType: 'integer', min: 0, - dflt: 0, + max: _$arrow_paths_30.length, + dflt: 1, + + editType: 'arraydraw', - editType: 'style' }, - tracerefminus: { + startarrowhead: { valType: 'integer', min: 0, - dflt: 0, + max: _$arrow_paths_30.length, + dflt: 1, + + editType: 'arraydraw', - editType: 'style' }, - copy_ystyle: { - valType: 'boolean', + arrowside: { + valType: 'flaglist', + flags: ['end', 'start'], + extras: ['none'], + dflt: 'end', + + editType: 'arraydraw', - editType: 'plot' }, - copy_zstyle: { - valType: 'boolean', + arrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', - editType: 'style' }, - color: { - valType: 'color', + startarrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, - editType: 'style', + editType: 'calcIfAutorange+arraydraw', }, - thickness: { + arrowwidth: { + valType: 'number', + min: 0.1, + + editType: 'calcIfAutorange+arraydraw', + + }, + standoff: { valType: 'number', min: 0, - dflt: 2, + dflt: 0, - editType: 'style', + editType: 'calcIfAutorange+arraydraw', }, - width: { + startstandoff: { valType: 'number', min: 0, + dflt: 0, - editType: 'plot', + editType: 'calcIfAutorange+arraydraw', + + }, + ax: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + ay: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + axref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_213.idRegex.x.toString() + ], + + editType: 'calc', + + }, + ayref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_213.idRegex.y.toString() + ], + + editType: 'calc', + + }, + // positioning + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_213.idRegex.x.toString() + ], + + editType: 'calc', + + }, + x: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + xshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_213.idRegex.y.toString() + ], + + editType: 'calc', + + }, + y: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + yshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + clicktoshow: { + valType: 'enumerated', + values: [false, 'onoff', 'onout'], + dflt: false, + + editType: 'arraydraw', + + }, + xclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + yclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + hovertext: { + valType: 'string', + + editType: 'arraydraw', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + bordercolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + font: _$font_attributes_234({ + editType: 'arraydraw', + + }), + editType: 'arraydraw' + }, + captureevents: { + valType: 'boolean', + + editType: 'arraydraw', }, editType: 'calc', _deprecated: { - opacity: { - valType: 'number', + ref: { + valType: 'string', - editType: 'style', + editType: 'calc', } } @@ -42381,97 +43739,147 @@ var _$attributes_73 = { 'use strict'; +/* removed: var _$d3_10 = require('d3'); */; + +/* removed: var _$color_46 = require('../color'); */; + +/* removed: var _$arrow_paths_30 = require('./arrow_paths'); */; /** - * Error bar computing function generator + * Add arrowhead(s) to a path or line element * - * N.B. The generated function does not clean the dataPt entries. Non-numeric - * entries result in undefined error magnitudes. + * @param {d3.selection} el3: a d3-selected line or path element * - * @param {object} opts error bar attributes + * @param {string} ends: 'none', 'start', 'end', or 'start+end' for which ends get arrowheads * - * @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 " + * @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. */ -var _$makeComputeError_75 = function makeComputeError(opts) { - var type = opts.type, - symmetric = opts.symmetric; +var _$drawArrowHead_38 = function drawArrowHead(el3, ends, options) { + var el = el3.node(); + var headStyle = _$arrow_paths_30[options.arrowhead || 0]; + var startHeadStyle = _$arrow_paths_30[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; - if(type === 'data') { - var array = opts.array || []; + var start, end, startRot, endRot; - 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]; - }; + 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; + } } - } - else { - var computeErrorValue = makeComputeErrorValue(type, opts.value), - computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); - if(symmetric || opts.valueminus === undefined) { - return function computeError(dataPt) { - var val = computeErrorValue(dataPt); - return [val, val]; - }; + if(backOff) { + if(backOff * backOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var backOffX = backOff * Math.cos(startRot), + backOffY = backOff * Math.sin(startRot); + + end.x += backOffX; + end.y += backOffY; + el3.attr({x2: end.x, y2: end.y}); + } - else { - return function computeError(dataPt) { - return [ - computeErrorValueMinus(dataPt), - computeErrorValue(dataPt) - ]; - }; + + if(startBackOff) { + if(startBackOff * startBackOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var startBackOffX = startBackOff * Math.cos(startRot), + 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 + dashArray = ''; -/** - * 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(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); } - if(type === 'sqrt') { - return function(dataPt) { - return Math.sqrt(Math.abs(dataPt)); - }; + + function hideLine() { el3.style('stroke-dasharray', '0px,100px'); } + + function drawhead(arrowHeadStyle, p, rot, arrowScale) { + if(!arrowHeadStyle.path) return; + if(arrowHeadStyle.noRotate) rot = 0; + + _$d3_10.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_46.rgb(options.arrowcolor), + 'stroke-width': 0 + }); } -} + + if(doStart) drawhead(startHeadStyle, start, startRot, startScale); + if(doEnd) drawhead(headStyle, end, endRot, scale); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -42481,305 +43889,702 @@ function makeComputeErrorValue(type, value) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$fx_88 = require('../fx'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$drawArrowHead_38 = require('./draw_arrow_head'); */; -/* removed: var _$makeComputeError_75 = require('./compute_error'); */; +// Annotations are stored in gd.layout.annotations, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one +var _$draw_37 = { + draw: __draw_37, + drawOne: drawOne, + drawRaw: drawRaw +}; -var _$calc_74 = function calc(gd) { - var calcdata = gd.calcdata; +/* + * draw: draw all annotations without any new modifications + */ +function __draw_37(gd) { + var fullLayout = gd._fullLayout; - for(var i = 0; i < calcdata.length; i++) { - var calcTrace = calcdata[i], - trace = calcTrace[0].trace; + fullLayout._infolayer.selectAll('.annotation').remove(); - if(!_$registry_247.traceIs(trace, 'errorBarsOK')) continue; + for(var i = 0; i < fullLayout.annotations.length; i++) { + if(fullLayout.annotations[i].visible) { + drawOne(gd, i); + } + } - var xa = _$axes_207.getFromId(gd, trace.xaxis), - ya = _$axes_207.getFromId(gd, trace.yaxis); + return _$plots_240.previousPromises(gd); +} - calcOneAxis(calcTrace, trace, xa, 'x'); - calcOneAxis(calcTrace, trace, ya, 'y'); - } -}; +/* + * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications + * + * index (int): the annotation to draw + */ +function drawOne(gd, index) { + var fullLayout = gd._fullLayout; + var options = fullLayout.annotations[index] || {}; + var xa = _$axes_208.getFromId(gd, options.xref); + var ya = _$axes_208.getFromId(gd, options.yref); -function calcOneAxis(calcTrace, trace, axis, coord) { - var opts = trace['error_' + coord] || {}, - isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), - vals = []; + drawRaw(gd, options, index, false, xa, ya); +} - if(!isVisible) return; +/** + * drawRaw: draw a single annotation, potentially with modifications + * + * @param {DOM element} gd + * @param {object} options : this annotation's fullLayout options + * @param {integer} index : index in 'annotations' container of the annotation to draw + * @param {string} subplotId : id of the annotation's subplot + * - use false for 2d (i.e. cartesian or paper-ref) annotations + * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px + * @param {object | undefined} ya : ... y-axis + */ +function drawRaw(gd, options, index, subplotId, xa, ya) { + var fullLayout = gd._fullLayout; + var gs = gd._fullLayout._size; + var edits = gd._context.edits; - var computeError = _$makeComputeError_75(opts); + var className; + var annbase; - for(var i = 0; i < calcTrace.length; i++) { - var calcPt = calcTrace[i], - calcCoord = calcPt[coord]; + if(subplotId) { + className = 'annotation-' + subplotId; + annbase = subplotId + '.annotations[' + index + ']'; + } else { + className = 'annotation'; + annbase = 'annotations[' + index + ']'; + } - if(!_$fastIsnumeric_13(axis.c2l(calcCoord))) continue; + // remove the existing annotation if there is one + fullLayout._infolayer + .selectAll('.' + className + '[data-index="' + index + '"]') + .remove(); - var errors = computeError(calcCoord, i); - if(_$fastIsnumeric_13(errors[0]) && _$fastIsnumeric_13(errors[1])) { - var shoe = calcPt[coord + 's'] = calcCoord - errors[0], - hat = calcPt[coord + 'h'] = calcCoord + errors[1]; - vals.push(shoe, hat); - } + var annClipID = 'clip' + fullLayout._uid + '_ann' + index; + + // this annotation is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!options._input || options.visible === false) { + _$d3_10.selectAll('#' + annClipID).remove(); + return; } - _$axes_207.expand(axis, vals, {padded: true}); -} + // calculated pixel positions + // x & y each will get text, head, and tail as appropriate + var annPosPx = {x: {}, y: {}}, + textangle = +options.textangle || 0; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // create the components + // made a single group to contain all, so opacity can work right + // with border/arrow together this could handle a whole bunch of + // cleanup at this point, but works for now + var annGroup = fullLayout._infolayer.append('g') + .classed(className, true) + .attr('data-index', String(index)) + .style('opacity', options.opacity); -'use strict'; + // another group for text+background so that they can rotate together + var annTextGroup = annGroup.append('g') + .classed('annotation-text-g', true); -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; + var textEvents = options.captureevents || edits.annotationText || editTextPosition; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; + var annTextGroupInner = annTextGroup.append('g') + .style('pointer-events', textEvents ? 'all' : null) + .call(_$setCursor_185, 'default') + .on('click', function() { + gd._dragging = false; -/* removed: var _$attributes_73 = require('./attributes'); */; + var eventData = { + index: index, + annotation: options._input, + fullAnnotation: options, + event: _$d3_10.event + }; + + if(subplotId) { + eventData.subplotId = subplotId; + } + gd.emit('plotly_clickannotation', eventData); + }); -var _$defaults_76 = function(traceIn, traceOut, defaultColor, opts) { - var objName = 'error_' + opts.axis, - containerOut = traceOut[objName] = {}, - containerIn = traceIn[objName] || {}; + if(options.hovertext) { + annTextGroupInner + .on('mouseover', function() { + var hoverOptions = options.hoverlabel; + var hoverFont = hoverOptions.font; + var bBox = this.getBoundingClientRect(); + var bBoxRef = gd.getBoundingClientRect(); - function coerce(attr, dflt) { - return _$lib_165.coerce(containerIn, containerOut, _$attributes_73, attr, dflt); + _$fx_88.loneHover({ + x0: bBox.left - bBoxRef.left, + x1: bBox.right - bBoxRef.left, + y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, + text: options.hovertext, + color: hoverOptions.bgcolor, + borderColor: hoverOptions.bordercolor, + fontFamily: hoverFont.family, + fontSize: hoverFont.size, + fontColor: hoverFont.color + }, { + container: fullLayout._hoverlayer.node(), + outerContainer: fullLayout._paper.node(), + gd: gd + }); + }) + .on('mouseout', function() { + _$fx_88.loneUnhover(fullLayout._hoverlayer.node()); + }); } - var hasErrorBars = ( - containerIn.array !== undefined || - containerIn.value !== undefined || - containerIn.type === 'sqrt' - ); + var borderwidth = options.borderwidth, + borderpad = options.borderpad, + borderfull = borderwidth + borderpad; - var visible = coerce('visible', hasErrorBars); + var annTextBG = annTextGroupInner.append('rect') + .attr('class', 'bg') + .style('stroke-width', borderwidth + 'px') + .call(_$color_46.stroke, options.bordercolor) + .call(_$color_46.fill, options.bgcolor); - if(visible === false) return; + var isSizeConstrained = options.width || options.height; - var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), - symmetric = true; + var annTextClip = fullLayout._topclips + .selectAll('#' + annClipID) + .data(isSizeConstrained ? [0] : []); - if(type !== 'sqrt') { - symmetric = coerce('symmetric', - !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); + annTextClip.enter().append('clipPath') + .classed('annclip', true) + .attr('id', annClipID) + .append('rect'); + annTextClip.exit().remove(); + + var font = options.font; + + var annText = annTextGroupInner.append('text') + .classed('annotation-text', true) + .text(options.text); + + function textLayout(s) { + s.call(_$drawing_71.font, font) + .attr({ + 'text-anchor': { + left: 'start', + right: 'end' + }[options.align] || 'middle' + }); + + _$svg_text_utils_187.convertToTspans(s, gd, drawGraphicalElements); + return s; } - if(type === 'data') { - coerce('array'); - coerce('traceref'); - if(!symmetric) { - coerce('arrayminus'); - coerce('tracerefminus'); + function drawGraphicalElements() { + // if the text has *only* a link, make the whole box into a link + var anchor3 = annText.selectAll('a'); + if(anchor3.size() === 1 && anchor3.text() === annText.text()) { + var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ + 'xlink:xlink:href': anchor3.attr('xlink:href'), + 'xlink:xlink:show': anchor3.attr('xlink:show') + }) + .style({cursor: 'pointer'}); + + wholeLink.node().appendChild(annTextBG.node()); } - } - 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 || - _$fastIsnumeric_13(containerIn.thickness) || - _$fastIsnumeric_13(containerIn.width))); + var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); + var hasMathjax = !mathjaxGroup.empty(); + var anntextBB = _$drawing_71.bBox( + (hasMathjax ? mathjaxGroup : annText).node()); + var textWidth = anntextBB.width; + var textHeight = anntextBB.height; + var annWidth = options.width || textWidth; + var annHeight = options.height || textHeight; + var outerWidth = Math.round(annWidth + 2 * borderfull); + var outerHeight = Math.round(annHeight + 2 * borderfull); + + + // save size in the annotation object for use by autoscale + options._w = annWidth; + options._h = annHeight; + + function shiftFraction(v, anchor) { + if(anchor === 'auto') { + if(v < 1 / 3) anchor = 'left'; + else if(v > 2 / 3) anchor = 'right'; + else anchor = 'center'; + } + return { + center: 0, + middle: 0, + left: 0.5, + bottom: -0.5, + right: -0.5, + top: 0.5 + }[anchor]; } - } - if(!opts.inherit || !containerOut[copyAttr]) { - coerce('color', defaultColor); - coerce('thickness'); - coerce('width', _$registry_247.traceIs(traceOut, 'gl3d') ? 0 : 4); - } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 annotationIsOffscreen = false; + var letters = ['x', 'y']; + for(var i = 0; i < letters.length; i++) { + var axLetter = letters[i], + axRef = options[axLetter + 'ref'] || axLetter, + tailRef = options['a' + axLetter + 'ref'], + ax = {x: xa, y: ya}[axLetter], + dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, + // note that these two can be either positive or negative + annSizeFromWidth = outerWidth * Math.cos(dimAngle), + annSizeFromHeight = outerHeight * Math.sin(dimAngle), + // but this one is the positive total size + annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), + anchor = options[axLetter + 'anchor'], + overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), + posPx = annPosPx[axLetter], + basePx, + textPadShift, + alignPosition, + autoAlignFraction, + textShift; -'use strict'; + /* + * calculate the *primary* pixel position + * which is the arrowhead if there is one, + * otherwise the text anchor point + */ + if(ax) { + /* + * hide the annotation if it's pointing outside the visible plot + * as long as the axis isn't autoranged - then we need to draw it + * anyway to get its bounding box. When we're dragging, an axis can + * still look autoranged even though it won't be when the drag finishes. + */ + var posFraction = ax.r2fraction(options[axLetter]); + if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { + if(tailRef === axRef) { + posFraction = ax.r2fraction(options['a' + axLetter]); + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + } + } + else { + annotationIsOffscreen = true; + } -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; + if(annotationIsOffscreen) continue; + } + 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; + } -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$subtypes_339 = require('../../traces/scatter/subtypes'); */; + // now translate this into pixel positions of head, tail, and text + // as well as paddings for autorange + if(options.showarrow) { + posPx.head = basePx; -var _$plot_78 = function plot(traces, plotinfo, transitionOpts) { - var isNew; + var arrowLength = options['a' + axLetter]; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // with an arrow, the text rotates around the anchor point + textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - + annSizeFromHeight * shiftFraction(0.5, options.yanchor); - var hasAnimation = transitionOpts && transitionOpts.duration > 0; + 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; + } - 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 - xObj = trace.error_x || {}, - yObj = trace.error_y || {}; + posPx.text = posPx.tail + textShift; - var keyFunc; + // 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_166.constrain(posPx.head, 1, maxPx - 1); + } + if(tailRef === 'pixel') { + var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), + 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; + } + } - if(trace.ids) { - keyFunc = function(d) {return d.id;}; + 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; } - var sparse = ( - _$subtypes_339.hasMarkers(trace) && - trace.marker.maxdisplayed > 0 - ); + 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_71.setClipUrl, isSizeConstrained ? annClipID : null); + } + else { + var texty = borderfull + yShift - anntextBB.top; + var textx = borderfull + xShift - anntextBB.left; + + annText.call(_$svg_text_utils_187.positionText, textx, texty) + .call(_$drawing_71.setClipUrl, isSizeConstrained ? annClipID : null); + } + + annTextClip.select('rect').call(_$drawing_71.setRect, borderfull, borderfull, + annWidth, annHeight); + + annTextBG.call(_$drawing_71.setRect, borderwidth / 2, borderwidth / 2, + outerWidth - borderwidth, outerHeight - borderwidth); + + annTextGroupInner.call(_$drawing_71.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(); - if(!yObj.visible && !xObj.visible) d = []; + var headX = annPosPx.x.head, + headY = annPosPx.y.head, + tailX = annPosPx.x.tail + dx, + tailY = annPosPx.y.tail + dy, + textX = annPosPx.x.text + dx, + textY = annPosPx.y.text + dy, - var errorbars = _$d3_10.select(this).selectAll('g.errorbar') - .data(d, keyFunc); + // find the edge of the text box, where we'll start the arrow: + // create transform matrix to rotate the text box corners + transform = _$lib_166.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_166.apply2DTransform(transform), + applyTransform2 = _$lib_166.apply2DTransform2(transform), - errorbars.exit().remove(); + // calculate and transform bounding box + width = +annTextBG.attr('width'), + height = +annTextBG.attr('height'), + xLeft = textX - 0.5 * width, + xRight = xLeft + width, + yTop = textY - 0.5 * height, + yBottom = yTop + height, + edges = [ + [xLeft, yTop, xLeft, yBottom], + [xLeft, yBottom, xRight, yBottom], + [xRight, yBottom, xRight, yTop], + [xRight, yTop, xLeft, yTop] + ].map(applyTransform2); - if(!d.length) return; + // 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_166.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; + } - if(!xObj.visible) errorbars.selectAll('path.xerror').remove(); - if(!yObj.visible) errorbars.selectAll('path.yerror').remove(); + edges.forEach(function(x) { + var p = _$lib_166.segmentsIntersect(tailX, tailY, headX, headY, + x[0], x[1], x[2], x[3]); + if(p) { + tailX = p.x; + tailY = p.y; + } + }); - errorbars.style('opacity', 1); + var strokewidth = options.arrowwidth, + arrowColor = options.arrowcolor, + arrowSide = options.arrowside; - var enter = errorbars.enter().append('g') - .classed('errorbar', true); + var arrowGroup = annGroup.append('g') + .style({opacity: _$color_46.opacity(arrowColor)}) + .classed('annotation-arrow-g', true); - if(hasAnimation) { - enter.style('opacity', 0).transition() - .duration(transitionOpts.duration) - .style('opacity', 1); - } + var arrow = arrowGroup.append('path') + .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY) + .style('stroke-width', strokewidth + 'px') + .call(_$color_46.stroke, _$color_46.rgb(arrowColor)); - _$drawing_71.setClipUrl(errorbars, plotinfo.layerClipId); + _$drawArrowHead_38(arrow, arrowSide, options); - errorbars.each(function(d) { - var errorbar = _$d3_10.select(this); - var coords = errorCoords(d, xa, ya); + // 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) + .attr({ + d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), + transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' + }) + .style('stroke-width', (strokewidth + 6) + 'px') + .call(_$color_46.stroke, 'rgba(0,0,0,0)') + .call(_$color_46.fill, 'rgba(0,0,0,0)'); - if(sparse && !d.vis) return; + var update, + annx0, + anny0; - var path; + // dragger for the arrow & head: translates the whole thing + // (head/tail/text) all together + _$dragelement_68.init({ + element: arrowDrag.node(), + gd: gd, + prepFn: function() { + var pos = _$drawing_71.getTranslate(annTextGroupInner); - var yerror = errorbar.select('path.yerror'); - if(yObj.visible && _$fastIsnumeric_13(coords.x) && - _$fastIsnumeric_13(coords.yh) && - _$fastIsnumeric_13(coords.ys)) { - var yw = yObj.width; + annx0 = pos.x; + anny0 = pos.y; + update = {}; + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + }, + moveFn: function(dx, dy) { + var annxy0 = applyTransform(annx0, anny0), + xcenter = annxy0[0] + dx, + ycenter = annxy0[1] + dy; + annTextGroupInner.call(_$drawing_71.setTranslate, xcenter, ycenter); - path = 'M' + (coords.x - yw) + ',' + - coords.yh + 'h' + (2 * yw) + // hat - 'm-' + yw + ',0V' + coords.ys; // bar + update[annbase + '.x'] = xa ? + xa.p2r(xa.r2p(options.x) + dx) : + (options.x + (dx / gs.w)); + update[annbase + '.y'] = ya ? + ya.p2r(ya.r2p(options.y) + dy) : + (options.y - (dy / gs.h)); + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } - if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } - isNew = !yerror.size(); + arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); + annTextGroup.attr({ + transform: 'rotate(' + textangle + ',' + + xcenter + ',' + ycenter + ')' + }); + }, + doneFn: function() { + _$registry_248.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } + }; - 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); - } + if(options.showarrow) drawArrow(0, 0); - yerror.attr('d', path); - } - else yerror.remove(); + // user dragging the annotation (text, not arrow) + if(editTextPosition) { + var update, + baseTextTransform; - var xerror = errorbar.select('path.xerror'); - if(xObj.visible && _$fastIsnumeric_13(coords.y) && - _$fastIsnumeric_13(coords.xh) && - _$fastIsnumeric_13(coords.xs)) { - var xw = (xObj.copy_ystyle ? yObj : xObj).width; + // dragger for the textbox: if there's an arrow, just drag the + // textbox and tail, leave the head untouched + _$dragelement_68.init({ + element: annTextGroupInner.node(), + gd: gd, + prepFn: function() { + baseTextTransform = annTextGroup.attr('transform'); + update = {}; + }, + moveFn: function(dx, dy) { + var csr = 'pointer'; + if(options.showarrow) { + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } else { + update[annbase + '.ax'] = options.ax + dx; + } - path = 'M' + coords.xh + ',' + - (coords.y - xw) + 'v' + (2 * xw) + // hat - 'm0,-' + xw + 'H' + coords.xs; // bar + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } else { + update[annbase + '.ay'] = options.ay + dy; + } - if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe + drawArrow(dx, dy); + } + else if(!subplotId) { + if(xa) { + update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); - isNew = !xerror.size(); + } else { + var widthFraction = options._xsize / gs.w, + xLeft = options.x + (options._xshift - options.xshift) / gs.w - + widthFraction / 2; - 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); - } + update[annbase + '.x'] = _$dragelement_68.align(xLeft + dx / gs.w, + widthFraction, 0, 1, options.xanchor); + } - xerror.attr('d', path); - } - else xerror.remove(); - }); - }); -}; + if(ya) { + update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); + } else { + var heightFraction = options._ysize / gs.h, + yBottom = options.y - (options._yshift + options.yshift) / gs.h - + heightFraction / 2; -// 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) - }; + update[annbase + '.y'] = _$dragelement_68.align(yBottom - dy / gs.h, + heightFraction, 0, 1, options.yanchor); + } + if(!xa || !ya) { + csr = _$dragelement_68.getCursor( + xa ? 0.5 : update[annbase + '.x'], + ya ? 0.5 : update[annbase + '.y'], + options.xanchor, options.yanchor + ); + } + } + else return; - // 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); + annTextGroup.attr({ + transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform + }); - // if the shoes go off-scale (ie log scale, error bars past zero) - // clip the bar and hide the shoes - if(!_$fastIsnumeric_13(out.ys)) { - out.noYS = true; - out.ys = ya.c2p(d.ys, true); + _$setCursor_185(annTextGroupInner, csr); + }, + doneFn: function() { + _$setCursor_185(annTextGroupInner); + _$registry_248.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); } } - if(d.xh !== undefined) { - out.xh = xa.c2p(d.xh); - out.xs = xa.c2p(d.xs); + if(edits.annotationText) { + annText.call(_$svg_text_utils_187.makeEditable, {delegate: annTextGroupInner, gd: gd}) + .call(textLayout) + .on('edit', function(_text) { + options.text = _text; + this.call(textLayout); - if(!_$fastIsnumeric_13(out.xs)) { - out.noXS = true; - out.xs = xa.c2p(d.xs, true); - } - } + var update = {}; + update[annbase + '.text'] = options.text; - return out; + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + + _$registry_248.call('relayout', gd, update); + }); + } + else annText.call(textLayout); } /** @@ -42793,30 +44598,105 @@ function errorCoords(d, xa, ya) { 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_46 = require('../color'); */; +var __draw_32 = _$draw_37.draw; -var _$style_79 = function style(traces) { - traces.each(function(d) { - var trace = d[0].trace, - yObj = trace.error_y || {}, - xObj = trace.error_x || {}; +var _$calcAutorange_32 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + annotationList = _$lib_166.filterVisible(fullLayout.annotations); - var s = _$d3_10.select(this); + if(!annotationList.length || !gd._fullData.length) return; - s.selectAll('path.yerror') - .style('stroke-width', yObj.thickness + 'px') - .call(_$color_46.stroke, yObj.color); + var annotationAxes = {}; + annotationList.forEach(function(ann) { + annotationAxes[ann.xref] = 1; + annotationAxes[ann.yref] = 1; + }); - if(xObj.copy_ystyle) xObj = yObj; + for(var axId in annotationAxes) { + var ax = _$axes_208.getFromId(gd, axId); + if(ax && ax.autorange) { + return _$lib_166.syncOrAsync([ + __draw_32, + annAutorange + ], gd); + } + } +}; - s.selectAll('path.xerror') - .style('stroke-width', xObj.thickness + 'px') - .call(_$color_46.stroke, xObj.color); +function annAutorange(gd) { + var fullLayout = gd._fullLayout; + + // find the bounding boxes for each of these annotations' + // relative to their anchor points + // use the arrow and the text bg rectangle, + // as the whole anno may include hidden text in its bbox + _$lib_166.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_208.getFromId(gd, ann.xref), + ya = _$axes_208.getFromId(gd, ann.yref), + headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, + startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; + + var headPlus, headMinus, startHeadPlus, startHeadMinus; + + if(xa && xa.autorange) { + headPlus = headSize + ann.xshift; + headMinus = headSize - ann.xshift; + startHeadPlus = startHeadSize + ann.xshift; + startHeadMinus = startHeadSize - ann.xshift; + + if(ann.axref === ann.xref) { + // expand for the arrowhead (padded by arrowhead) + _$axes_208.expand(xa, [xa.r2c(ann.x)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + // again for the textbox (padded by textbox) + _$axes_208.expand(xa, [xa.r2c(ann.ax)], { + ppadplus: Math.max(ann._xpadplus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, startHeadMinus) + }); + } + else { + startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; + startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; + _$axes_208.expand(xa, [xa.r2c(ann.x)], { + ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) + }); + } + } + + if(ya && ya.autorange) { + headPlus = headSize - ann.yshift; + headMinus = headSize + ann.yshift; + startHeadPlus = startHeadSize - ann.yshift; + startHeadMinus = startHeadSize + ann.yshift; + + if(ann.ayref === ann.yref) { + _$axes_208.expand(ya, [ya.r2c(ann.y)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + _$axes_208.expand(ya, [ya.r2c(ann.ay)], { + ppadplus: Math.max(ann._ypadplus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, startHeadMinus) + }); + } + else { + startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; + startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; + _$axes_208.expand(ya, [ya.r2c(ann.y)], { + ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) + }); + } + } }); -}; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -42828,90 +44708,127 @@ var _$style_79 = function style(traces) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -var __overrideAll_77 = _$edit_types_192.overrideAll; - -/* removed: var _$attributes_73 = require('./attributes'); */; -/* removed: var _$calc_74 = require('./calc'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -var xyAttrs = { - error_x: _$lib_165.extendFlat({}, _$attributes_73), - error_y: _$lib_165.extendFlat({}, _$attributes_73) +var _$click_33 = { + hasClickToShow: hasClickToShow, + onClick: onClick }; -delete xyAttrs.error_x.copy_zstyle; -delete xyAttrs.error_y.copy_zstyle; -delete xyAttrs.error_y.copy_ystyle; -var xyzAttrs = { - error_x: _$lib_165.extendFlat({}, _$attributes_73), - error_y: _$lib_165.extendFlat({}, _$attributes_73), - error_z: _$lib_165.extendFlat({}, _$attributes_73) -}; -delete xyzAttrs.error_x.copy_ystyle; -delete xyzAttrs.error_y.copy_ystyle; -delete xyzAttrs.error_z.copy_ystyle; -delete xyzAttrs.error_z.copy_zstyle; +/* + * 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; +} -var _$errorbars_77 = { - moduleType: 'component', - name: 'errorbars', +/* + * 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), + onSet = toggleSets.on, + offSet = toggleSets.off.concat(toggleSets.explicitOff), + update = {}, + i; - schema: { - traces: { - scatter: xyAttrs, - bar: xyAttrs, - histogram: xyAttrs, - scatter3d: __overrideAll_77(xyzAttrs, 'calc', 'nested'), - scattergl: __overrideAll_77(xyAttrs, 'calc', 'nested') - } - }, + if(!(onSet.length || offSet.length)) return; - supplyDefaults: _$defaults_76, + for(i = 0; i < onSet.length; i++) { + update['annotations[' + onSet[i] + '].visible'] = true; + } - calc: _$calc_74, - calcFromTrace: calcFromTrace, + for(i = 0; i < offSet.length; i++) { + update['annotations[' + offSet[i] + '].visible'] = false; + } - plot: _$plot_78, - style: _$style_79, - hoverInfo: hoverInfo -}; + return _$registry_248.call('update', gd, {}, update); +} -function calcFromTrace(trace, layout) { - var x = trace.x || [], - y = trace.y || [], - len = x.length || y.length; +/* + * 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, + onSet = [], + offSet = [], + explicitOffSet = [], + hoverLen = (hoverData || []).length; - var calcdataMock = new Array(len); + 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; + } + } - for(var i = 0; i < len; i++) { - calcdataMock[i] = { - x: x[i], - y: y[i] - }; + if(j === hoverLen) { + // no match - only turn this annotation OFF, and only if + // showmode is 'onout' + if(anni.visible && showMode === 'onout') offSet.push(i); + } + } } - calcdataMock[0].trace = trace; - - _$calc_74({ - calcdata: [calcdataMock], - _fullLayout: layout - }); - - return calcdataMock; + return {on: onSet, off: offSet, explicitOff: explicitOffSet}; } -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; - } +// to handle log axes until v2 +function clickData2r(d, ax) { + return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); } -var _$domain_233 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -42920,103 +44837,58 @@ var _$domain_233 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var __extendFlat_233 = _$extend_159.extendFlat; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_189 = require('../../lib/to_log_range'); */; -/** - * 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. +/* + * 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 * - * @return {object} attributes object containing {x,y} as specified + * 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. */ -_$domain_233.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 _$convertCoords_35 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; - var namePart = opts.name ? opts.name + ' ' : ''; - var contPart = opts.trace ? 'trace ' : 'subplot '; - var descPart = extra.description ? ' ' + extra.description : ''; + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); - var out = { - x: __extendFlat_233({}, base, { - - }), - y: __extendFlat_233({}, base, { - - }), - editType: opts.editType - }; + if(!(toLog || fromLog)) return; - 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, - - }; - } + var annotations = gd._fullLayout.annotations, + axLetter = ax._id.charAt(0), + ann, + attrPrefix; - return out; -}; + function convert(attr) { + var currentVal = ann[attr], + newVal = null; -_$domain_233.defaults = function(containerOut, layout, coerce, dfltDomains) { - var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; - var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; + if(toLog) newVal = _$toLogRange_189(currentVal, ax.range); + else newVal = Math.pow(10, currentVal); - 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; - } + // if conversion failed, delete the value so it gets a default value + if(!_$fastIsnumeric_13(newVal)) newVal = null; - var row = coerce('domain.row'); - if(row !== undefined) { - if(row < grid.rows) dfltY = grid._domains.y[row]; - else delete containerOut.domain.row; - } + doExtra(attrPrefix + attr, newVal); } - coerce('domain.x', dfltX); - coerce('domain.y', dfltY); + 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); + } }; /** @@ -43029,348 +44901,169 @@ _$domain_233.defaults = function(containerOut, layout, coerce, dfltDomains) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -var __counterRegex_92 = _$regex_180.counter; -var domainAttrs = _$domain_233.attributes; -var cartesianIdRegex = _$constants_212.idRegex; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$color_46 = require('../color'); */; -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_92('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: 'ticks', - - }, - yside: { - valType: 'enumerated', - values: ['left', 'left plot', 'right plot', 'right'], - dflt: 'left plot', - - editType: 'ticks', - - }, - editType: 'plot' -}; +// defaults common to 'annotations' and 'annotations3d' +var _$handleAnnotationCommonDefaults_34 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { + coerce('opacity'); + var bgColor = coerce('bgcolor'); -// 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; - if(!gridIn) return; + var borderColor = coerce('bordercolor'); + var borderOpacity = _$color_46.opacity(borderColor); - var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]); - var hasXaxes = Array.isArray(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + coerce('borderpad'); - var dfltRows, dfltColumns; + var borderWidth = coerce('borderwidth'); + var showArrow = coerce('showarrow'); - if(hasSubplotGrid) { - dfltRows = gridIn.subplots.length; - dfltColumns = gridIn.subplots[0].length; - } - else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; - } + coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); + coerce('textangle'); + _$lib_166.coerceFont(coerce, 'font', fullLayout.font); - var gridOut = layoutOut.grid = {}; + coerce('width'); + coerce('align'); - function coerce(attr, dflt) { - return _$lib_165.coerce(gridIn, gridOut, gridAttrs, attr, dflt); - } + var h = coerce('height'); + if(h) coerce('valign'); - var rows = coerce('rows', dfltRows); - var columns = coerce('columns', dfltColumns); + if(showArrow) { + var arrowside = coerce('arrowside'); + var arrowhead; + var arrowsize; - if(!(rows * columns > 1)) return; + 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_46.defaultLine); + coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); + coerce('standoff'); + coerce('startstandoff'); - 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 hoverText = coerce('hovertext'); + var globalHoverLabel = fullLayout.hoverlabel || {}; - gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) - }; -} + if(hoverText) { + var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || + (_$color_46.opacity(bgColor) ? _$color_46.rgb(bgColor) : _$color_46.defaultLine) + ); -// coerce x or y sizing attributes and return an array of domains for this direction -function fillGridPositions(axLetter, coerce, dfltGap, len, reversed) { - var dirGap = coerce(axLetter + 'gap', dfltGap); - var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || + _$color_46.contrast(hoverBG) + ); - 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]; + _$lib_166.coerceFont(coerce, 'hoverlabel.font', { + family: globalHoverLabel.font.family, + size: globalHoverLabel.font.size, + color: globalHoverLabel.font.color || hoverBorder + }); } - 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'; + coerce('captureevents', !!hoverText); +}; - var i, j, xId, yId, subplotId, subplotsOut, yPos; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 axisMap = gridOut._axisMap = {}; - if(hasSubplotGrid) { - var subplotsIn = gridIn.subplots || []; - subplotsOut = gridOut.subplots = new Array(rows); - var index = 1; +'use strict'; - 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]; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleAnnotationCommonDefaults_34 = require('./common_defaults'); */; +/* removed: var _$attributes_31 = require('./attributes'); */; - 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; - } +var _$handleAnnotationDefaults_29 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; - rowOut[j] = subplotId; - axisMap[xId] = j; - axisMap[yId] = i; - } - } - } - } - else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); + function coerce(attr, dflt) { + return _$lib_166.coerce(annIn, annOut, _$attributes_31, attr, dflt); } - var anchors = gridOut._anchors = {}; - var reversed = gridOut.roworder === 'top to bottom'; + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + var clickToShow = coerce('clicktoshow'); - for(var axisId in axisMap) { - var axLetter = axisId.charAt(0); - var side = gridOut[axLetter + 'side']; + if(!(visible || clickToShow)) return annOut; - var i0, inc, iFinal; + _$handleAnnotationCommonDefaults_34(annIn, annOut, fullLayout, coerce); - 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; - } - } - } - } - } -} + var showArrow = annOut.showarrow; -function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { - var out = new Array(len); - var i; + // positioning + var axLetters = ['x', 'y'], + arrowPosDflt = [-10, -30], + gdMock = {_fullLayout: fullLayout}; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i]; - function fillOneAxis(i, axisId) { - if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) { - out[i] = axisId; - axisMap[axisId] = i; - } - else out[i] = ''; - } + // xref, yref + var axRef = _$axes_208.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); - 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)); + // x, y + _$axes_208.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + + if(showArrow) { + var arrowPosAttr = 'a' + axLetter, + // axref, ayref + aaxRef = _$axes_208.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + + // for now the arrow can only be on the same axis or specified as pixels + // TODO: sometime it might be interesting to allow it to be on *any* axis + // but that would require updates to drawing & autorange code and maybe more + if(aaxRef !== 'pixel' && aaxRef !== axRef) { + aaxRef = annOut[arrowPosAttr] = 'pixel'; + } + + // ax, ay + var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; + _$axes_208.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } + + // xanchor, yanchor + coerce(axLetter + 'anchor'); + + // xshift, yshift + coerce(axLetter + 'shift'); } - return out; -} + // if you have one coordinate you should have both + _$lib_166.noneOrAll(annIn, annOut, ['x', 'y']); -var _$grid_92 = { - moduleType: 'component', - name: 'grid', + // if you have one part of arrow length you should have both + if(showArrow) { + _$lib_166.noneOrAll(annIn, annOut, ['ax', 'ay']); + } - schema: { - layout: {grid: gridAttrs} - }, + if(clickToShow) { + var xClick = coerce('xclick'); + var yClick = coerce('yclick'); - layoutAttributes: gridAttrs, - sizeDefaults: sizeDefaults, - contentDefaults: contentDefaults + // put the actual click data to bind to into private attributes + // so we don't have to do this little bit of logic on every hover event + annOut._xclick = (xClick === undefined) ? + annOut.x : + _$axes_208.cleanPosition(xClick, gdMock, annOut.xref); + annOut._yclick = (yClick === undefined) ? + annOut.y : + _$axes_208.cleanPosition(yClick, gdMock, annOut.yref); + } + + return annOut; }; /** @@ -43383,129 +45076,97 @@ var _$grid_92 = { 'use strict'; -/* removed: var _$constants_212 = require('../../plots/cartesian/constants'); */; +/* removed: var _$lib_166 = require('../lib'); */; +/** Convenience wrapper for making array container logic DRY and consistent + * + * @param {object} parentObjIn + * user input object where the container in question is linked + * (i.e. either a user trace object or the user layout object) + * + * @param {object} parentObjOut + * full object where the coerced container will be linked + * (i.e. either a full trace object or the full layout object) + * + * @param {object} opts + * options object: + * - name {string} + * name of the key linking the container in question + * - handleItemDefaults {function} + * defaults method to be called on each item in the array container in question + * + * Its arguments are: + * - itemIn {object} item in user layout + * - itemOut {object} item in full layout + * - parentObj {object} (as in closure) + * - opts {object} (as in closure) + * - itemOpts {object} + * - itemIsNotPlainObject {boolean} + * N.B. + * + * - opts is passed to handleItemDefaults so it can also store + * links to supplementary data (e.g. fullData for layout components) + * + */ +var _$handleArrayContainerDefaults_204 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { + var name = opts.name; -var _$attributes_93 = { - _isLinkedToArray: 'image', + var previousContOut = parentObjOut[name]; - visible: { - valType: 'boolean', - - dflt: true, - editType: 'arraydraw', - - }, + var contIn = _$lib_166.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + contOut = parentObjOut[name] = [], + i; - source: { - valType: 'string', - - editType: 'arraydraw', - - }, + for(i = 0; i < contIn.length; i++) { + var itemIn = contIn[i], + itemOut = {}, + itemOpts = {}; - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, + if(!_$lib_166.isPlainObject(itemIn)) { + itemOpts.itemIsNotPlainObject = true; + itemIn = {}; + } - sizex: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, + opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); - sizey: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, + itemOut._input = itemIn; + itemOut._index = i; - sizing: { - valType: 'enumerated', - values: ['fill', 'contain', 'stretch'], - dflt: 'contain', - - editType: 'arraydraw', - - }, + contOut.push(itemOut); + } - opacity: { - valType: 'number', - - min: 0, - max: 1, - dflt: 1, - editType: 'arraydraw', - - }, + // in case this array gets its defaults rebuilt independent of the whole layout, + // relink the private keys just for this array. + if(_$lib_166.isArrayOrTypedArray(previousContOut)) { + var len = Math.min(previousContOut.length, contOut.length); + for(i = 0; i < len; i++) { + _$lib_166.relinkPrivateKeys(contOut[i], previousContOut[i]); + } + } +}; - x: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - y: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - editType: 'arraydraw', - - }, +'use strict'; - yanchor: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'top', - - editType: 'arraydraw', - - }, +/* removed: var _$handleArrayContainerDefaults_204 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationDefaults_29 = require('./annotation_defaults'); */; - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_212.idRegex.x.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_212.idRegex.y.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' +var _$supplyLayoutDefaults_36 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'annotations', + handleItemDefaults: _$handleAnnotationDefaults_29 + }; + + _$handleArrayContainerDefaults_204(layoutIn, layoutOut, opts); }; /** @@ -43519,75 +45180,67 @@ var _$attributes_93 = { 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_188 = require('../../lib/to_log_range'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -/* - * convertCoords: when converting an axis between log and linear - * you need to alter any images on that axis to keep them - * pointing at the same data point. - * In v2.0 this will become obsolete (or perhaps size will still need conversion?) - * we convert size by declaring that the maximum extent *in data units* should be - * the same, assuming the image is anchored by its center (could remove that restriction - * if we think it's important) even though the actual left and right values will not be - * quite the same since the scale becomes nonlinear (and central anchor means the pixel - * center of the image, not the data units center) +/** + * Factory function for checking component arrays for subplot references. * - * 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. + * @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 */ -var _$convertCoords_94 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; - - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); - - if(!(toLog || fromLog)) return; +var _$makeIncludeComponents_218 = function makeIncludeComponents(containerArrayName) { + return function includeComponents(layoutIn, layoutOut) { + var array = layoutIn[containerArrayName]; + if(!Array.isArray(array)) return; - var images = gd._fullLayout.images, - axLetter = ax._id.charAt(0), - image, - attrPrefix; + var Cartesian = _$registry_248.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 < images.length; i++) { - image = images[i]; - attrPrefix = 'images[' + i + '].'; + for(var i = 0; i < array.length; i++) { + var itemi = array[i]; + if(!_$lib_166.isPlainObject(itemi)) continue; - if(image[axLetter + 'ref'] === ax._id) { - var currentPos = image[axLetter], - currentSize = image['size' + axLetter], - newPos = null, - newSize = null; + var xref = itemi.xref; + var yref = itemi.yref; - if(toLog) { - newPos = _$toLogRange_188(currentPos, ax.range); + var hasXref = idRegex.x.test(xref); + var hasYref = idRegex.y.test(yref); + if(hasXref || hasYref) { + if(!hasCartesianOrGL2D) _$lib_166.pushUnique(layoutOut._basePlotModules, Cartesian); - // this is the inverse of the conversion we do in fromLog below - // so that the conversion is reversible (notice the fromLog conversion - // is like sinh, and this one looks like arcsinh) - var dx = currentSize / Math.pow(10, newPos) / 2; - newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; - } - else { - newPos = Math.pow(10, currentPos); - newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); - } + 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; + } - // if conversion failed, delete the value so it can get a default later on - if(!_$fastIsnumeric_13(newPos)) { - newPos = null; - newSize = null; + /* + * 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); + } } - else if(!_$fastIsnumeric_13(newSize)) newSize = null; - - doExtra(attrPrefix + axLetter, newPos); - doExtra(attrPrefix + 'size' + axLetter, newSize); } - } + }; }; /** @@ -43598,57 +45251,118 @@ var _$convertCoords_94 = function convertCoords(gd, ax, newType, doExtra) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_203 = require('../../plots/array_container_defaults'); */; +/* removed: var _$draw_37 = require('./draw'); */; +/* removed: var _$click_33 = require('./click'); */; + +var _$annotations_39 = { + moduleType: 'component', + name: 'annotations', -/* removed: var _$attributes_93 = require('./attributes'); */; -var name = 'images'; + layoutAttributes: _$attributes_31, + supplyLayoutDefaults: _$supplyLayoutDefaults_36, + includeBasePlot: _$makeIncludeComponents_218('annotations'), -var _$supplyLayoutDefaults_95 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: name, - handleItemDefaults: imageDefaults - }; + calcAutorange: _$calcAutorange_32, + draw: _$draw_37.draw, + drawOne: _$draw_37.drawOne, + drawRaw: _$draw_37.drawRaw, + + hasClickToShow: _$click_33.hasClickToShow, + onClick: _$click_33.onClick, - _$handleArrayContainerDefaults_203(layoutIn, layoutOut, opts); + convertCoords: _$convertCoords_35 }; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function imageDefaults(imageIn, imageOut, fullLayout) { - function coerce(attr, dflt) { - return _$lib_165.coerce(imageIn, imageOut, _$attributes_93, attr, dflt); - } +'use strict'; - var source = coerce('source'); - var visible = coerce('visible', !!source); +/* removed: var _$attributes_31 = require('../annotations/attributes'); */; +var __overrideAll_40 = _$edit_types_193.overrideAll; - if(!visible) return imageOut; +var _$attributes_40 = __overrideAll_40({ + _isLinkedToArray: 'annotation', - coerce('layer'); - coerce('xanchor'); - coerce('yanchor'); - coerce('sizex'); - coerce('sizey'); - coerce('sizing'); - coerce('opacity'); + visible: _$attributes_31.visible, + x: { + valType: 'any', + + + }, + y: { + valType: 'any', + + + }, + z: { + valType: 'any', + + + }, + ax: { + valType: 'number', + + + }, + ay: { + valType: 'number', + + + }, - var gdMock = { _fullLayout: fullLayout }, - axLetters = ['x', 'y']; + xanchor: _$attributes_31.xanchor, + xshift: _$attributes_31.xshift, + yanchor: _$attributes_31.yanchor, + yshift: _$attributes_31.yshift, - for(var i = 0; i < 2; i++) { - // 'paper' is the fallback axref - var axLetter = axLetters[i], - axRef = _$axes_207.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + text: _$attributes_31.text, + textangle: _$attributes_31.textangle, + font: _$attributes_31.font, + width: _$attributes_31.width, + height: _$attributes_31.height, + opacity: _$attributes_31.opacity, + align: _$attributes_31.align, + valign: _$attributes_31.valign, + bgcolor: _$attributes_31.bgcolor, + bordercolor: _$attributes_31.bordercolor, + borderpad: _$attributes_31.borderpad, + borderwidth: _$attributes_31.borderwidth, + showarrow: _$attributes_31.showarrow, + arrowcolor: _$attributes_31.arrowcolor, + arrowhead: _$attributes_31.arrowhead, + startarrowhead: _$attributes_31.startarrowhead, + arrowside: _$attributes_31.arrowside, + arrowsize: _$attributes_31.arrowsize, + startarrowsize: _$attributes_31.startarrowsize, + arrowwidth: _$attributes_31.arrowwidth, + standoff: _$attributes_31.standoff, + startstandoff: _$attributes_31.startstandoff, + hovertext: _$attributes_31.hovertext, + hoverlabel: _$attributes_31.hoverlabel, + captureevents: _$attributes_31.captureevents, - _$axes_207.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); - } + // maybes later? + // clicktoshow: annAtts.clicktoshow, + // xclick: annAtts.xclick, + // yclick: annAtts.yclick, - return imageOut; -} + // not needed! + // axref: 'pixel' + // ayref: 'pixel' + // xref: 'x' + // yref: 'y + // zref: 'z' +}, 'calc', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -43660,213 +45374,218 @@ function imageDefaults(imageIn, imageOut, fullLayout) { 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$xmlns_namespaces_150 = require('../../constants/xmlns_namespaces'); */; - -var _$draw_96 = function draw(gd) { - var fullLayout = gd._fullLayout, - imageDataAbove = [], - imageDataSubplot = {}, - imageDataBelow = [], - subplot, - i; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; - // Sort into top, subplot, and bottom layers - for(i = 0; i < fullLayout.images.length; i++) { - var img = fullLayout.images[i]; +var _$convert_41 = function convert(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var anns = fullSceneLayout.annotations; - if(img.visible) { - if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { - subplot = img.xref + img.yref; + for(var i = 0; i < anns.length; i++) { + mockAnnAxes(anns[i], scene); + } - var plotinfo = fullLayout._plots[subplot]; + scene.fullLayout._infolayer + .selectAll('.annotation-' + scene.id) + .remove(); +}; - if(!plotinfo) { - // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the image to an x / y axis combination - // that doesn't have any data on it (and layer is below) - imageDataBelow.push(img); - continue; - } +function mockAnnAxes(ann, scene) { + var fullSceneLayout = scene.fullSceneLayout; + var domain = fullSceneLayout.domain; + var size = scene.fullLayout._size; - if(plotinfo.mainplot) { - subplot = plotinfo.mainplot.id; - } + var base = { + // this gets fill in on render + pdata: null, - if(!imageDataSubplot[subplot]) { - imageDataSubplot[subplot] = []; - } - imageDataSubplot[subplot].push(img); - } else if(img.layer === 'above') { - imageDataAbove.push(img); - } else { - imageDataBelow.push(img); - } - } - } + // to get setConvert to not execute cleanly + type: 'linear', + // don't try to update them on `editable: true` + autorange: false, - var anchors = { - x: { - left: { sizing: 'xMin', offset: 0 }, - center: { sizing: 'xMid', offset: -1 / 2 }, - right: { sizing: 'xMax', offset: -1 } - }, - y: { - top: { sizing: 'YMin', offset: 0 }, - middle: { sizing: 'YMid', offset: -1 / 2 }, - bottom: { sizing: 'YMax', offset: -1 } - } + // set infinite range so that annotation draw routine + // does not try to remove 'outside-range' annotations, + // this case is handled in the render loop + range: [-Infinity, Infinity] }; + ann._xa = {}; + _$lib_166.extendFlat(ann._xa, base); + _$axes_208.setConvert(ann._xa); + ann._xa._offset = size.l + domain.x[0] * size.w; + ann._xa.l2p = function() { + return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); + }; - // Images must be converted to dataURL's for exporting. - function setImage(d) { - var thisImage = _$d3_10.select(this); + ann._ya = {}; + _$lib_166.extendFlat(ann._ya, base); + _$axes_208.setConvert(ann._ya); + ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; + ann._ya.l2p = function() { + return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); + }; +} - if(this.img && this.img.src === d.source) { - return; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - thisImage.attr('xmlns', _$xmlns_namespaces_150.svg); +'use strict'; - var imagePromise = new Promise(function(resolve) { +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_204 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationCommonDefaults_34 = require('../annotations/common_defaults'); */; +/* removed: var _$attributes_40 = require('./attributes'); */; - var img = new Image(); - this.img = img; +var _$handleDefaults_42 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + _$handleArrayContainerDefaults_204(sceneLayoutIn, sceneLayoutOut, { + name: 'annotations', + handleItemDefaults: __handleAnnotationDefaults_42, + fullLayout: opts.fullLayout + }); +}; - // If not set, a `tainted canvas` error is thrown - img.setAttribute('crossOrigin', 'anonymous'); - img.onerror = errorHandler; - img.onload = function() { - var canvas = document.createElement('canvas'); - canvas.width = this.width; - canvas.height = this.height; +function __handleAnnotationDefaults_42(annIn, annOut, sceneLayout, opts, itemOpts) { + function coerce(attr, dflt) { + return _$lib_166.coerce(annIn, annOut, _$attributes_40, attr, dflt); + } - var ctx = canvas.getContext('2d'); - ctx.drawImage(this, 0, 0); + function coercePosition(axLetter) { + var axName = axLetter + 'axis'; - var dataURL = canvas.toDataURL('image/png'); + // mock in such way that getFromId grabs correct 3D axis + var gdMock = { _fullLayout: {} }; + gdMock._fullLayout[axName] = sceneLayout[axName]; - thisImage.attr('xlink:href', dataURL); + return _$axes_208.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + } - // resolve promise in onload handler instead of on 'load' to support IE11 - // see https://github.com/plotly/plotly.js/issues/1685 - // for more details - resolve(); - }; + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + if(!visible) return annOut; - thisImage.on('error', errorHandler); + _$handleAnnotationCommonDefaults_34(annIn, annOut, opts.fullLayout, coerce); - img.src = d.source; + coercePosition('x'); + coercePosition('y'); + coercePosition('z'); - function errorHandler() { - thisImage.remove(); - resolve(); - } - }.bind(this)); + // if you have one coordinate you should all three + _$lib_166.noneOrAll(annIn, annOut, ['x', 'y', 'z']); - gd._promises.push(imagePromise); - } + // hard-set here for completeness + annOut.xref = 'x'; + annOut.yref = 'y'; + annOut.zref = 'z'; - function applyAttributes(d) { - var thisImage = _$d3_10.select(this); + coerce('xanchor'); + coerce('yanchor'); + coerce('xshift'); + coerce('yshift'); - // Axes if specified - var xa = _$axes_207.getFromId(gd, d.xref), - ya = _$axes_207.getFromId(gd, d.yref); + if(annOut.showarrow) { + annOut.axref = 'pixel'; + annOut.ayref = 'pixel'; - var size = fullLayout._size, - width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, - height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; + // TODO maybe default values should be bigger than the 2D case? + coerce('ax', -10); + coerce('ay', -30); - // Offsets for anchor positioning - var xOffset = width * anchors.x[d.xanchor].offset, - yOffset = height * anchors.y[d.yanchor].offset; + // if you have one part of arrow length you should have both + _$lib_166.noneOrAll(annIn, annOut, ['ax', 'ay']); + } - var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; + return annOut; +} - // Final positions - var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, - yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // Construct the proper aspectRatio attribute - switch(d.sizing) { - case 'fill': - sizing += ' slice'; - break; +'use strict'; - case 'stretch': - sizing = 'none'; - break; - } +function xformMatrix(m, v) { + var out = [0, 0, 0, 0]; + var i, j; - thisImage.attr({ - x: xPos, - y: yPos, - width: width, - height: height, - preserveAspectRatio: sizing, - opacity: d.opacity - }); + for(i = 0; i < 4; ++i) { + for(j = 0; j < 4; ++j) { + out[j] += m[4 * i + j] * v[i]; + } + } + return out; +} - // Set proper clipping on images - var xId = xa ? xa._id : '', - yId = ya ? ya._id : '', - clipAxes = xId + yId; +function project(camera, v) { + var p = xformMatrix(camera.projection, + xformMatrix(camera.view, + xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); + return p; +} - thisImage.call(_$drawing_71.setClipUrl, clipAxes ? - ('clip' + fullLayout._uid + clipAxes) : - null - ); - } +var _$project_237 = project; - var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') - .data(imageDataBelow), - imagesAbove = fullLayout._imageUpperLayer.selectAll('image') - .data(imageDataAbove); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - imagesBelow.enter().append('image'); - imagesAbove.enter().append('image'); +'use strict'; - imagesBelow.exit().remove(); - imagesAbove.exit().remove(); +var __drawRaw_43 = _$draw_37.drawRaw; +/* removed: var _$project_237 = require('../../plots/gl3d/project'); */; +var axLetters = ['x', 'y', 'z']; - imagesBelow.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - imagesAbove.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); +var _$draw_43 = function draw(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var dataScale = scene.dataScale; + var anns = fullSceneLayout.annotations; - var allSubplots = Object.keys(fullLayout._plots); - for(i = 0; i < allSubplots.length; i++) { - subplot = allSubplots[i]; - var subplotObj = fullLayout._plots[subplot]; + for(var i = 0; i < anns.length; i++) { + var ann = anns[i]; + var annotationIsOffscreen = false; - // filter out overlaid plots (which havd their images on the main plot) - // and gl2d plots (which don't support below images, at least not yet) - if(!subplotObj.imagelayer) continue; + for(var j = 0; j < 3; j++) { + var axLetter = axLetters[j]; + var pos = ann[axLetter]; + var ax = fullSceneLayout[axLetter + 'axis']; + var posFraction = ax.r2fraction(pos); - var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') - // even if there are no images on this subplot, we need to run - // enter and exit in case there were previously - .data(imageDataSubplot[subplot] || []); + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + break; + } + } - imagesOnSubplot.enter().append('image'); - imagesOnSubplot.exit().remove(); + if(annotationIsOffscreen) { + scene.fullLayout._infolayer + .select('.annotation-' + scene.id + '[data-index="' + i + '"]') + .remove(); + } else { + ann._pdata = _$project_237(scene.glplot.cameraParams, [ + fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], + fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], + fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] + ]); - imagesOnSubplot.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); + __drawRaw_43(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + } } }; @@ -43880,19 +45599,43 @@ var _$draw_96 = function draw(gd) { 'use strict'; -var _$images_97 = { +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; + +var _$annotations3d_44 = { moduleType: 'component', - name: 'images', + name: 'annotations3d', - layoutAttributes: _$attributes_93, - supplyLayoutDefaults: _$supplyLayoutDefaults_95, - includeBasePlot: _$makeIncludeComponents_217('images'), + schema: { + subplots: { + scene: {annotations: _$attributes_40} + } + }, - draw: _$draw_96, + layoutAttributes: _$attributes_40, + handleDefaults: _$handleDefaults_42, + includeBasePlot: includeGL3D, - convertCoords: _$convertCoords_94 + convert: _$convert_41, + draw: _$draw_43 }; +function includeGL3D(layoutIn, layoutOut) { + var GL3D = _$registry_248.subplotsRegistry.gl3d; + if(!GL3D) return; + + var attrRegex = GL3D.attrRegex; + + var keys = Object.keys(layoutIn); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { + _$lib_166.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_166.pushUnique(layoutOut._subplots.gl3d, k); + } + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -43903,129 +45646,108 @@ var _$images_97 = { 'use strict'; -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_45 = require('../color/attributes'); */; - -var _$attributes_99 = { - bgcolor: { - valType: 'color', +var _$attributes_73 = { + visible: { + valType: 'boolean', - editType: 'legend', + editType: 'calc', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_45.defaultLine, + type: { + valType: 'enumerated', + values: ['percent', 'constant', 'sqrt', 'data'], - editType: 'legend', + editType: 'calc', }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, + symmetric: { + valType: 'boolean', - editType: 'legend', + editType: 'calc', }, - font: _$font_attributes_234({ - editType: 'legend', - - }), - orientation: { - valType: 'enumerated', - values: ['v', 'h'], - dflt: 'v', + array: { + valType: 'data_array', + editType: 'calc', - editType: 'legend', + }, + arrayminus: { + valType: 'data_array', + editType: 'calc', }, - traceorder: { - valType: 'flaglist', - flags: ['reversed', 'grouped'], - extras: ['normal'], + value: { + valType: 'number', + min: 0, + dflt: 10, - editType: 'legend', + editType: 'calc', }, - tracegroupgap: { + valueminus: { valType: 'number', min: 0, dflt: 10, - editType: 'legend', + editType: 'calc', }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 1.02, + traceref: { + valType: 'integer', + min: 0, + dflt: 0, - editType: 'legend', + editType: 'style' + }, + tracerefminus: { + valType: 'integer', + min: 0, + dflt: 0, + editType: 'style' }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', + copy_ystyle: { + valType: 'boolean', - editType: 'legend', + editType: 'plot' + }, + copy_zstyle: { + valType: 'boolean', + editType: 'style' }, - y: { + color: { + valType: 'color', + + editType: 'style', + + }, + thickness: { valType: 'number', - min: -2, - max: 3, - dflt: 1, + min: 0, + dflt: 2, - editType: 'legend', + editType: 'style', }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', + width: { + valType: 'number', + min: 0, - editType: 'legend', + editType: 'plot', }, - editType: 'legend' -}; - -var _$helpers_105 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -_$helpers_105.legendGetsTrace = function legendGetsTrace(trace) { - // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? - // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. - - // Note that we explicitly include showlegend: false, so a trace that *could* be - // in the legend but is not shown still counts toward the two traces you need to - // ensure the legend is shown by default, because this can still help disambiguate. - return trace.visible && (trace.showlegend !== undefined); -}; - -_$helpers_105.isGrouped = function isGrouped(legendLayout) { - return (legendLayout.traceorder || '').indexOf('grouped') !== -1; -}; - -_$helpers_105.isVertical = function isVertical(legendLayout) { - return legendLayout.orientation !== 'h'; -}; + editType: 'calc', -_$helpers_105.isReversed = function isReversed(legendLayout) { - return (legendLayout.traceorder || '').indexOf('reversed') !== -1; + _deprecated: { + opacity: { + valType: 'number', + + editType: 'style', + + } + } }; /** @@ -44039,88 +45761,98 @@ _$helpers_105.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; - -/* removed: var _$attributes_99 = require('./attributes'); */; -/* removed: var _$layout_attributes_238 = require('../../plots/layout_attributes'); */; -/* removed: var _$helpers_105 = require('./helpers'); */; - - -var _$legendDefaults_101 = function legendDefaults(layoutIn, layoutOut, fullData) { - var containerIn = layoutIn.legend || {}; - var containerOut = {}; - - var visibleTraces = 0; - var defaultOrder = 'normal'; - - var defaultX, defaultY, defaultXAnchor, defaultYAnchor; - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; +/** + * 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 " + */ +var _$makeComputeError_75 = function makeComputeError(opts) { + var type = opts.type, + symmetric = opts.symmetric; - if(_$helpers_105.legendGetsTrace(trace)) { - visibleTraces++; - // always show the legend by default if there's a pie - if(_$registry_247.traceIs(trace, 'pie')) visibleTraces++; - } + if(type === 'data') { + var array = opts.array || []; - if((_$registry_247.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || - ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { - defaultOrder = _$helpers_105.isGrouped({traceorder: defaultOrder}) ? - 'grouped+reversed' : 'reversed'; + if(symmetric) { + return function computeError(dataPt, index) { + var val = +(array[index]); + return [val, val]; + }; } - - if(trace.legendgroup !== undefined && trace.legendgroup !== '') { - defaultOrder = _$helpers_105.isReversed({traceorder: defaultOrder}) ? - 'reversed+grouped' : 'grouped'; + 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), + computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); - function coerce(attr, dflt) { - return _$lib_165.coerce(containerIn, containerOut, _$attributes_99, attr, dflt); - } - - var showLegend = _$lib_165.coerce(layoutIn, layoutOut, - _$layout_attributes_238, 'showlegend', visibleTraces > 1); - - if(showLegend === false) return; - - layoutOut.legend = containerOut; - - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - _$lib_165.coerceFont(coerce, 'font', layoutOut.font); - - coerce('orientation'); - if(containerOut.orientation === 'h') { - var xaxis = layoutIn.xaxis; - if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = 1.1; - defaultYAnchor = 'bottom'; + if(symmetric || opts.valueminus === undefined) { + return function computeError(dataPt) { + var val = computeErrorValue(dataPt); + return [val, val]; + }; } else { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = -0.1; - defaultYAnchor = 'top'; + return function computeError(dataPt) { + return [ + computeErrorValueMinus(dataPt), + computeErrorValue(dataPt) + ]; + }; } } - - coerce('traceorder', defaultOrder); - if(_$helpers_105.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); - - coerce('x', defaultX); - coerce('xanchor', defaultXAnchor); - coerce('y', defaultY); - coerce('yanchor', defaultYAnchor); - _$lib_165.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -var _$anchor_utils_98 = {}; +/** + * 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)); + }; + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44132,60 +45864,57 @@ var _$anchor_utils_98 = {}; 'use strict'; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/** - * 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. - */ +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; -_$anchor_utils_98.isRightAnchor = function isRightAnchor(opts) { - return ( - opts.xanchor === 'right' || - (opts.xanchor === 'auto' && opts.x >= 2 / 3) - ); -}; +/* removed: var _$makeComputeError_75 = require('./compute_error'); */; -_$anchor_utils_98.isCenterAnchor = function isCenterAnchor(opts) { - return ( - opts.xanchor === 'center' || - (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) - ); -}; -_$anchor_utils_98.isBottomAnchor = function isBottomAnchor(opts) { - return ( - opts.yanchor === 'bottom' || - (opts.yanchor === 'auto' && opts.y <= 1 / 3) - ); -}; +var _$calc_74 = function calc(gd) { + var calcdata = gd.calcdata; -_$anchor_utils_98.isMiddleAnchor = function isMiddleAnchor(opts) { - return ( - opts.yanchor === 'middle' || - (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) - ); -}; + for(var i = 0; i < calcdata.length; i++) { + var calcTrace = calcdata[i], + trace = calcTrace[0].trace; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!_$registry_248.traceIs(trace, 'errorBarsOK')) continue; -'use strict'; + var xa = _$axes_208.getFromId(gd, trace.xaxis), + ya = _$axes_208.getFromId(gd, trace.yaxis); -var _$constants_100 = { - scrollBarWidth: 6, - scrollBarMinHeight: 20, - scrollBarColor: '#808BA4', - scrollBarMargin: 4 + calcOneAxis(calcTrace, trace, xa, 'x'); + calcOneAxis(calcTrace, trace, ya, 'y'); + } }; +function calcOneAxis(calcTrace, trace, axis, coord) { + var opts = trace['error_' + coord] || {}, + isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), + vals = []; + + if(!isVisible) return; + + var computeError = _$makeComputeError_75(opts); + + for(var i = 0; i < calcTrace.length; i++) { + var calcPt = calcTrace[i], + calcCoord = calcPt[coord]; + + if(!_$fastIsnumeric_13(axis.c2l(calcCoord))) continue; + + var errors = computeError(calcCoord, i); + if(_$fastIsnumeric_13(errors[0]) && _$fastIsnumeric_13(errors[1])) { + var shoe = calcPt[coord + 's'] = calcCoord - errors[0], + hat = calcPt[coord + 'h'] = calcCoord + errors[1]; + vals.push(shoe, hat); + } + } + + _$axes_208.expand(axis, vals, {padded: true}); +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44194,100 +45923,70 @@ var _$constants_100 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$helpers_105 = require('./helpers'); */; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -var _$getLegendData_103 = function getLegendData(calcdata, opts) { - var lgroupToTraces = {}, - lgroups = [], - hasOneNonBlankGroup = false, - slicesShown = {}, - lgroupi = 0; +/* removed: var _$attributes_73 = require('./attributes'); */; - var i, j; - function addOneItem(legendGroup, legendItem) { - // each '' legend group is treated as a separate group - if(legendGroup === '' || !_$helpers_105.isGrouped(opts)) { - var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? +var _$defaults_76 = function(traceIn, traceOut, defaultColor, opts) { + var objName = 'error_' + opts.axis, + containerOut = traceOut[objName] = {}, + containerIn = traceIn[objName] || {}; - lgroups.push(uniqueGroup); - lgroupToTraces[uniqueGroup] = [[legendItem]]; - lgroupi++; - } - else if(lgroups.indexOf(legendGroup) === -1) { - lgroups.push(legendGroup); - hasOneNonBlankGroup = true; - lgroupToTraces[legendGroup] = [[legendItem]]; - } - else lgroupToTraces[legendGroup].push([legendItem]); + function coerce(attr, dflt) { + return _$lib_166.coerce(containerIn, containerOut, _$attributes_73, attr, dflt); } - // build an { legendgroup: [cd0, cd0], ... } object - for(i = 0; i < calcdata.length; i++) { - var cd = calcdata[i], - cd0 = cd[0], - trace = cd0.trace, - lgroup = trace.legendgroup; - - if(!_$helpers_105.legendGetsTrace(trace) || !trace.showlegend) continue; - - if(_$registry_247.traceIs(trace, 'pie')) { - if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; + var hasErrorBars = ( + containerIn.array !== undefined || + containerIn.value !== undefined || + containerIn.type === 'sqrt' + ); - for(j = 0; j < cd.length; j++) { - var labelj = cd[j].label; + var visible = coerce('visible', hasErrorBars); - if(!slicesShown[lgroup][labelj]) { - addOneItem(lgroup, { - label: labelj, - color: cd[j].color, - i: cd[j].i, - trace: trace - }); + if(visible === false) return; - slicesShown[lgroup][labelj] = true; - } - } - } + var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), + symmetric = true; - else addOneItem(lgroup, cd0); + if(type !== 'sqrt') { + symmetric = coerce('symmetric', + !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); } - // won't draw a legend in this case - if(!lgroups.length) return []; - - // rearrange lgroupToTraces into a d3-friendly array of arrays - var lgroupsLength = lgroups.length, - ltraces, - legendData; - - if(hasOneNonBlankGroup && _$helpers_105.isGrouped(opts)) { - legendData = new Array(lgroupsLength); - - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]]; - legendData[i] = _$helpers_105.isReversed(opts) ? ltraces.reverse() : ltraces; + if(type === 'data') { + coerce('array'); + coerce('traceref'); + if(!symmetric) { + coerce('arrayminus'); + coerce('tracerefminus'); } } - else { - // collapse all groups into one if all groups are blank - legendData = [new Array(lgroupsLength)]; + else if(type === 'percent' || type === 'constant') { + coerce('value'); + if(!symmetric) coerce('valueminus'); + } - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]][0]; - legendData[0][_$helpers_105.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; + var copyAttr = 'copy_' + opts.inherit + 'style'; + if(opts.inherit) { + var inheritObj = traceOut['error_' + opts.inherit]; + if((inheritObj || {}).visible) { + coerce(copyAttr, !(containerIn.color || + _$fastIsnumeric_13(containerIn.thickness) || + _$fastIsnumeric_13(containerIn.width))); } - lgroupsLength = 1; } - - // needed in repositionLegend - opts._lgroupsLength = lgroupsLength; - return legendData; + if(!opts.inherit || !containerOut[copyAttr]) { + coerce('color', defaultColor); + coerce('thickness'); + coerce('width', _$registry_248.traceIs(traceOut, 'gl3d') ? 0 : 4); + } }; /** @@ -44298,262 +45997,170 @@ var _$getLegendData_103 = function getLegendData(calcdata, opts) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$registry_247 = require('../../registry'); */; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var SHOWISOLATETIP = true; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$subtypes_337 = require('../../traces/scatter/subtypes'); */; -var _$handleClick_104 = function handleClick(g, gd, numClicks) { - if(gd._dragged || gd._editing) return; +var _$plot_78 = function plot(traces, plotinfo, transitionOpts) { + var isNew; - var hiddenSlices = gd._fullLayout.hiddenlabels ? - gd._fullLayout.hiddenlabels.slice() : - []; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - var legendItem = g.data()[0][0]; - var fullData = gd._fullData; - var fullTrace = legendItem.trace; - var legendgroup = fullTrace.legendgroup; + var hasAnimation = transitionOpts && transitionOpts.duration > 0; - var i, j, kcont, key, keys, val; - var attrUpdate = {}; - var attrIndices = []; - var carrs = []; - var carrIdx = []; + 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 + xObj = trace.error_x || {}, + yObj = trace.error_y || {}; - function insertUpdate(traceIndex, key, value) { - var attrIndex = attrIndices.indexOf(traceIndex); - var valueArray = attrUpdate[key]; - if(!valueArray) { - valueArray = attrUpdate[key] = []; - } + var keyFunc; - if(attrIndices.indexOf(traceIndex) === -1) { - attrIndices.push(traceIndex); - attrIndex = attrIndices.length - 1; + if(trace.ids) { + keyFunc = function(d) {return d.id;}; } - valueArray[attrIndex] = value; - - return attrIndex; - } + var sparse = ( + _$subtypes_337.hasMarkers(trace) && + trace.marker.maxdisplayed > 0 + ); - function setVisibility(fullTrace, visibility) { - var fullInput = fullTrace._fullInput; - if(_$registry_247.hasTransform(fullInput, 'groupby')) { - var kcont = carrs[fullInput.index]; - if(!kcont) { - var groupbyIndices = _$registry_247.getTransformIndices(fullInput, 'groupby'); - var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_165.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); - carrs[fullInput.index] = kcont; - } + if(!yObj.visible && !xObj.visible) d = []; - var curState = kcont.get(fullTrace._group); + var errorbars = _$d3_10.select(this).selectAll('g.errorbar') + .data(d, keyFunc); - // 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; - } + errorbars.exit().remove(); - 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; + if(!d.length) return; - insertUpdate(fullInput.index, 'visible', nextVisibility); - } - } + if(!xObj.visible) errorbars.selectAll('path.xerror').remove(); + if(!yObj.visible) errorbars.selectAll('path.yerror').remove(); - if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_165.notifier(_$lib_165._(gd, 'Double-click on legend to isolate one trace'), 'long'); - SHOWISOLATETIP = false; - } else { - SHOWISOLATETIP = false; - } + errorbars.style('opacity', 1); - if(_$registry_247.traceIs(fullTrace, 'pie')) { - var thisLabel = legendItem.label, - thisLabelIndex = hiddenSlices.indexOf(thisLabel); + var enter = errorbars.enter().append('g') + .classed('errorbar', true); - if(numClicks === 1) { - if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); - else hiddenSlices.splice(thisLabelIndex, 1); - } else if(numClicks === 2) { - 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 = []; - } + if(hasAnimation) { + enter.style('opacity', 0).transition() + .duration(transitionOpts.duration) + .style('opacity', 1); } - _$registry_247.call('relayout', 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); - } - } - } + _$drawing_71.setClipUrl(errorbars, plotinfo.layerClipId); - if(numClicks === 1) { - var nextVisibility; + errorbars.each(function(d) { + var errorbar = _$d3_10.select(this); + var coords = errorCoords(d, xa, ya); - switch(fullTrace.visible) { - case true: - nextVisibility = 'legendonly'; - break; - case false: - nextVisibility = false; - break; - case 'legendonly': - nextVisibility = true; - break; - } + if(sparse && !d.vis) return; - 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(numClicks === 2) { - // 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, otherState; - var isIsolated = true; - for(i = 0; i < fullData.length; i++) { - isClicked = fullData[i] === fullTrace; - if(isClicked) continue; + var path; - isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); + var yerror = errorbar.select('path.yerror'); + if(yObj.visible && _$fastIsnumeric_13(coords.x) && + _$fastIsnumeric_13(coords.yh) && + _$fastIsnumeric_13(coords.ys)) { + var yw = yObj.width; - if(!isInGroup && fullData[i].visible === true && !_$registry_247.traceIs(fullData[i], 'notLegendIsolatable')) { - isIsolated = false; - break; - } - } + path = 'M' + (coords.x - yw) + ',' + + coords.yh + 'h' + (2 * yw) + // hat + 'm-' + yw + ',0V' + coords.ys; // bar - for(i = 0; i < fullData.length; i++) { - // False is sticky; we don't change it. - if(fullData[i].visible === false) continue; - if(_$registry_247.traceIs(fullData[i], 'notLegendIsolatable')) { - continue; - } + if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe - switch(fullTrace.visible) { - case 'legendonly': - setVisibility(fullData[i], true); - break; - case true: - otherState = isIsolated ? true : 'legendonly'; - isClicked = fullData[i] === fullTrace; - isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); - setVisibility(fullData[i], isInGroup ? true : otherState); - break; + 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(); - for(i = 0; i < carrs.length; i++) { - kcont = carrs[i]; - if(!kcont) continue; - var update = kcont.constructUpdate(); + var xerror = errorbar.select('path.xerror'); + if(xObj.visible && _$fastIsnumeric_13(coords.y) && + _$fastIsnumeric_13(coords.xh) && + _$fastIsnumeric_13(coords.xs)) { + var xw = (xObj.copy_ystyle ? yObj : xObj).width; - 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]; - } - } + path = 'M' + coords.xh + ',' + + (coords.y - xw) + 'v' + (2 * xw) + // hat + 'm0,-' + xw + 'H' + coords.xs; // bar - // 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; + 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); } - } - } - _$registry_247.call('restyle', gd, attrUpdate, attrIndices); - } + xerror.attr('d', path); + } + else xerror.remove(); + }); + }); }; -var _$helpers_309 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +// 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) + }; -/* removed: var _$lib_165 = require('../../lib'); */; + // 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); -_$helpers_309.formatPiePercent = function formatPiePercent(v, separators) { - var vRounded = (v * 100).toPrecision(3); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); + // if the shoes go off-scale (ie log scale, error bars past zero) + // clip the bar and hide the shoes + if(!_$fastIsnumeric_13(out.ys)) { + out.noYS = true; + out.ys = ya.c2p(d.ys, true); + } } - return _$lib_165.numSeparate(vRounded, separators) + '%'; -}; -_$helpers_309.formatPieValue = function formatPieValue(v, separators) { - var vRounded = v.toPrecision(10); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_165.numSeparate(vRounded, separators); -}; + if(d.xh !== undefined) { + out.xh = xa.c2p(d.xh); + out.xs = xa.c2p(d.xs); -_$helpers_309.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) return v; + if(!_$fastIsnumeric_13(out.xs)) { + out.noXS = true; + out.xs = xa.c2p(d.xs, true); + } } -}; -_$helpers_309.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_309.getFirstFilled(item, indices); - else if(item) return item; -}; + return out; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -44563,19 +46170,32 @@ _$helpers_309.castOption = function castOption(item, indices) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$color_46 = require('../../components/color'); */; -var castOption = _$helpers_309.castOption; +/* removed: var _$d3_10 = require('d3'); */; -var _$styleOne_315 = function styleOne(s, pt, trace) { - var line = trace.marker.line; - var lineColor = castOption(line.color, pt.pts) || _$color_46.defaultLine; - var lineWidth = castOption(line.width, pt.pts) || 0; +/* removed: var _$color_46 = require('../color'); */; - s.style({'stroke-width': lineWidth}) - .call(_$color_46.fill, pt.color) - .call(_$color_46.stroke, lineColor); + +var _$style_79 = function style(traces) { + traces.each(function(d) { + var trace = d[0].trace, + yObj = trace.error_y || {}, + xObj = trace.error_x || {}; + + var s = _$d3_10.select(this); + + s.selectAll('path.yerror') + .style('stroke-width', yObj.thickness + 'px') + .call(_$color_46.stroke, yObj.color); + + if(xObj.copy_ystyle) xObj = yObj; + + s.selectAll('path.xerror') + .style('stroke-width', xObj.thickness + 'px') + .call(_$color_46.stroke, xObj.color); + }); }; /** @@ -44586,229 +46206,197 @@ var _$styleOne_315 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; - -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$color_46 = require('../color'); */; - -/* removed: var _$subtypes_339 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_315 = require('../../traces/pie/style_one'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +var __overrideAll_77 = _$edit_types_193.overrideAll; +/* removed: var _$attributes_73 = require('./attributes'); */; +/* removed: var _$calc_74 = require('./calc'); */; -var _$style_107 = function style(s, gd) { - s.each(function(d) { - var traceGroup = _$d3_10.select(this); +var xyAttrs = { + error_x: _$lib_166.extendFlat({}, _$attributes_73), + error_y: _$lib_166.extendFlat({}, _$attributes_73) +}; +delete xyAttrs.error_x.copy_zstyle; +delete xyAttrs.error_y.copy_zstyle; +delete xyAttrs.error_y.copy_ystyle; - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); - layers.style('opacity', d[0].trace.opacity); +var xyzAttrs = { + error_x: _$lib_166.extendFlat({}, _$attributes_73), + error_y: _$lib_166.extendFlat({}, _$attributes_73), + error_z: _$lib_166.extendFlat({}, _$attributes_73) +}; +delete xyzAttrs.error_x.copy_ystyle; +delete xyzAttrs.error_y.copy_ystyle; +delete xyzAttrs.error_z.copy_ystyle; +delete xyzAttrs.error_z.copy_zstyle; - var fill = layers - .selectAll('g.legendfill') - .data([d]); - fill.enter().append('g') - .classed('legendfill', true); +var _$errorbars_77 = { + moduleType: 'component', + name: 'errorbars', - var line = layers - .selectAll('g.legendlines') - .data([d]); - line.enter().append('g') - .classed('legendlines', true); + schema: { + traces: { + scatter: xyAttrs, + bar: xyAttrs, + histogram: xyAttrs, + scatter3d: __overrideAll_77(xyzAttrs, 'calc', 'nested'), + scattergl: __overrideAll_77(xyAttrs, 'calc', 'nested') + } + }, - var symbol = layers - .selectAll('g.legendsymbols') - .data([d]); - symbol.enter().append('g') - .classed('legendsymbols', true); + supplyDefaults: _$defaults_76, - symbol.selectAll('g.legendpoints') - .data([d]) - .enter().append('g') - .classed('legendpoints', true); - }) - .each(styleBars) - .each(styleBoxes) - .each(stylePies) - .each(styleLines) - .each(stylePoints); + calc: _$calc_74, + calcFromTrace: calcFromTrace, - function styleLines(d) { - var trace = d[0].trace; - var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_339.hasLines(trace); - var contours = trace.contours; + plot: _$plot_78, + style: _$style_79, + hoverInfo: hoverInfo +}; - if(contours && contours.type === 'constraint') { - showLine = contours.showlines; - showFill = contours._operation !== '='; - } +function calcFromTrace(trace, layout) { + var x = trace.x || [], + y = trace.y || [], + len = x.length || y.length; - var fill = _$d3_10.select(this).select('.legendfill').selectAll('path') - .data(showFill ? [d] : []); - fill.enter().append('path').classed('js-fill', true); - fill.exit().remove(); - fill.attr('d', 'M5,0h30v6h-30z') - .call(_$drawing_71.fillGroupStyle); + var calcdataMock = new Array(len); - var line = _$d3_10.select(this).select('.legendlines').selectAll('path') - .data(showLine ? [d] : []); - line.enter().append('path').classed('js-line', true) - .attr('d', 'M5,0h30'); - line.exit().remove(); - line.call(_$drawing_71.lineGroupStyle); + for(var i = 0; i < len; i++) { + calcdataMock[i] = { + x: x[i], + y: y[i] + }; } - function stylePoints(d) { - var d0 = d[0], - trace = d0.trace, - showMarkers = _$subtypes_339.hasMarkers(trace), - showText = _$subtypes_339.hasText(trace), - showLines = _$subtypes_339.hasLines(trace); - - var dMod, tMod; - - // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; - // use d0.trace to infer arrayOk attributes - - function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_165.nestedProperty(trace, attrIn).get(), - valToBound = (Array.isArray(valIn) && arrayToValFn) ? - arrayToValFn(valIn) : valIn; + calcdataMock[0].trace = trace; - if(bounds) { - if(valToBound < bounds[0]) return bounds[0]; - else if(valToBound > bounds[1]) return bounds[1]; - } - return valToBound; - } + _$calc_74({ + calcdata: [calcdataMock], + _fullLayout: layout + }); - function pickFirst(array) { return array[0]; } + return calcdataMock; +} - // constrain text, markers, etc so they'll fit on the legend - if(showMarkers || showText || showLines) { - var dEdit = {}, - tEdit = {}; +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; + } +} - if(showMarkers) { - dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_165.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_165.mean, [2, 16]); - dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_165.mean, [0, 5]); - tEdit.marker = { - sizeref: 1, - sizemin: 1, - sizemode: 'diameter' - }; - } +var _$domain_233 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(showLines) { - tEdit.line = { - width: boundVal('line.width', pickFirst, [0, 10]) - }; - } +'use strict'; - if(showText) { - dEdit.tx = 'Aa'; - dEdit.tp = boundVal('textposition', pickFirst); - dEdit.ts = 10; - dEdit.tc = boundVal('textfont.color', pickFirst); - dEdit.tf = boundVal('textfont.family', pickFirst); - } +var __extendFlat_233 = _$extend_160.extendFlat; - dMod = [_$lib_165.minExtend(d0, dEdit)]; - tMod = _$lib_165.minExtend(trace, tEdit); - } +/** + * 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 + */ +_$domain_233.attributes = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; - var ptgroup = _$d3_10.select(this).select('g.legendpoints'); + 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 pts = ptgroup.selectAll('path.scatterpts') - .data(showMarkers ? dMod : []); - pts.enter().append('path').classed('scatterpts', true) - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.call(_$drawing_71.pointStyle, tMod, gd); + var namePart = opts.name ? opts.name + ' ' : ''; + var contPart = opts.trace ? 'trace ' : 'subplot '; + var descPart = extra.description ? ' ' + extra.description : ''; - // 'mrc' is set in pointStyle and used in textPointStyle: - // constrain it here - if(showMarkers) dMod[0].mrc = 3; + var out = { + x: __extendFlat_233({}, base, { + + }), + y: __extendFlat_233({}, base, { + + }), + editType: opts.editType + }; - var txt = ptgroup.selectAll('g.pointtext') - .data(showText ? dMod : []); - txt.enter() - .append('g').classed('pointtext', true) - .append('text').attr('transform', 'translate(20,0)'); - txt.exit().remove(); - txt.selectAll('text').call(_$drawing_71.textPointStyle, tMod, gd); + 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, + + }; } - function styleBars(d) { - var trace = d[0].trace, - marker = trace.marker || {}, - markerLine = marker.line || {}, - barpath = _$d3_10.select(this).select('g.legendpoints') - .selectAll('path.legendbar') - .data(_$registry_247.traceIs(trace, 'bar') ? [d] : []); - barpath.enter().append('path').classed('legendbar', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - barpath.exit().remove(); - barpath.each(function(d) { - var p = _$d3_10.select(this), - d0 = d[0], - w = (d0.mlw + 1 || markerLine.width + 1) - 1; - - p.style('stroke-width', w + 'px') - .call(_$color_46.fill, d0.mc || marker.color); - - if(w) { - p.call(_$color_46.stroke, d0.mlc || markerLine.color); - } - }); - } + return out; +}; - function styleBoxes(d) { - var trace = d[0].trace, - pts = _$d3_10.select(this).select('g.legendpoints') - .selectAll('path.legendbox') - .data(_$registry_247.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendbox', true) - // if we want the median bar, prepend M6,0H-6 - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.each(function() { - var w = trace.line.width, - p = _$d3_10.select(this); +_$domain_233.defaults = function(containerOut, layout, coerce, dfltDomains) { + var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; + var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; - p.style('stroke-width', w + 'px') - .call(_$color_46.fill, trace.fillcolor); + 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; + } - if(w) { - p.call(_$color_46.stroke, trace.line.color); - } - }); + var row = coerce('domain.row'); + if(row !== undefined) { + if(row < grid.rows) dfltY = grid._domains.y[row]; + else delete containerOut.domain.row; + } } - function stylePies(d) { - var trace = d[0].trace, - pts = _$d3_10.select(this).select('g.legendpoints') - .selectAll('path.legendpie') - .data(_$registry_247.traceIs(trace, 'pie') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendpie', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - - if(pts.size()) pts.call(_$styleOne_315, d[0], trace); - } + coerce('domain.x', dfltX); + coerce('domain.y', dfltY); }; /** @@ -44821,728 +46409,872 @@ var _$style_107 = function style(s, gd) { 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +var __counterRegex_92 = _$regex_181.counter; +var domainAttrs = _$domain_233.attributes; +var cartesianIdRegex = _$constants_213.idRegex; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$handleClick_104 = require('./handle_click'); */; +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_92('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' +}; -/* removed: var _$constants_100 = require('./constants'); */; -/* removed: var _$interactions_147 = require('../../constants/interactions'); */; -/* removed: var _$alignment_146 = require('../../constants/alignment'); */; -var __LINE_SPACING_102 = _$alignment_146.LINE_SPACING; -var FROM_TL = _$alignment_146.FROM_TL; -var FROM_BR = _$alignment_146.FROM_BR; +function getAxes(layout, grid, axLetter) { + var gridVal = grid[axLetter + 'axes']; + var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {}); -/* removed: var _$getLegendData_103 = require('./get_legend_data'); */; -/* removed: var _$style_107 = require('./style'); */; -/* removed: var _$helpers_105 = require('./helpers'); */; -/* removed: var _$anchor_utils_98 = require('./anchor_utils'); */; + if(Array.isArray(gridVal)) return gridVal; + if(splomVal.length) return splomVal; +} -var DBLCLICKDELAY = _$interactions_147.DBLCLICKDELAY; +// 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'); -var _$draw_102 = function draw(gd) { - var fullLayout = gd._fullLayout; - var clipId = 'legend' + fullLayout._uid; + if(!layoutIn.grid && !xAxes && !yAxes) return; - if(!fullLayout._infolayer || !gd.calcdata) 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 + ); - if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; + var dfltRows, dfltColumns; - var opts = fullLayout.legend, - legendData = fullLayout.showlegend && _$getLegendData_103(gd.calcdata, opts), - hiddenSlices = fullLayout.hiddenlabels || []; + if(hasSubplotGrid) { + dfltRows = gridIn.subplots.length; + dfltColumns = gridIn.subplots[0].length; + } + else { + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; + } - if(!fullLayout.showlegend || !legendData.length) { - fullLayout._infolayer.selectAll('.legend').remove(); - fullLayout._topdefs.select('#' + clipId).remove(); + var gridOut = layoutOut.grid = {}; - _$plots_240.autoMargin(gd, 'legend'); - return; + function coerce(attr, dflt) { + return _$lib_166.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); + var rows = coerce('rows', dfltRows); + var columns = coerce('columns', dfltColumns); - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); + if(!(rows * columns > 1)) return; - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); + if(!hasSubplotGrid && !hasXaxes && !hasYaxes) { + var useDefaultSubplots = coerce('pattern') === 'independent'; + if(useDefaultSubplots) hasSubplotGrid = true; + } + gridOut._hasSubplotGrid = hasSubplotGrid; - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var rowOrder = coerce('roworder'); + var reversed = rowOrder === 'top to bottom'; - var bg = legend.selectAll('rect.bg') - .data([0]); + var dfltGapX = hasSubplotGrid ? 0.2 : 0.1; + var dfltGapY = hasSubplotGrid ? 0.3 : 0.1; - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' - }); + var dfltSideX, dfltSideY; + if(isSplomGenerated) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } - bg.call(_$color_46.stroke, opts.bordercolor) - .call(_$color_46.fill, opts.bgcolor) - .style('stroke-width', opts.borderwidth + 'px'); + gridOut._domains = { + x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns), + y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed) + }; +} - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); +// 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); - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); + 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; +} - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); +// 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; - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', - rx: 20, - ry: 3, - width: 0, - height: 0 - }) - .call(_$color_46.fill, '#808BA4'); + 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 groups = scrollBox.selectAll('g.groups') - .data(legendData); + var i, j, xId, yId, subplotId, subplotsOut, yPos; - groups.enter().append('g') - .attr('class', 'groups'); + var axisMap = gridOut._axisMap = {}; - groups.exit().remove(); + if(hasSubplotGrid) { + var subplotsIn = gridIn.subplots || []; + subplotsOut = gridOut.subplots = new Array(rows); + var index = 1; - var traces = groups.selectAll('g.traces') - .data(_$lib_165.identity); + 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]; - traces.enter().append('g').attr('class', 'traces'); - traces.exit().remove(); + rowOut[j] = ''; - traces.call(_$style_107, gd) - .style('opacity', function(d) { - var trace = d[0].trace; - if(_$registry_247.traceIs(trace, 'pie')) { - return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; - } else { - return trace.visible === 'legendonly' ? 0.5 : 1; - } - }) - .each(function() { - _$d3_10.select(this) - .call(drawTexts, gd) - .call(setupTraceToggle, gd); - }); + 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; + } - var firstRender = legend.enter().size() !== 0; - if(firstRender) { - computeLegendDimensions(gd, groups, traces); - expandMargin(gd); + 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'); } - // Position and size the legend - var lxMin = 0, - lxMax = fullLayout.width, - lyMin = 0, - lyMax = fullLayout.height; + var anchors = gridOut._anchors = {}; + var reversed = gridOut.roworder === 'top to bottom'; - computeLegendDimensions(gd, groups, traces); + for(var axisId in axisMap) { + var axLetter = axisId.charAt(0); + var side = gridOut[axLetter + 'side']; - if(opts._height > lyMax) { - // If the legend doesn't fit in the plot area, - // do not expand the vertical margins. - expandHorizontalMargin(gd); - } else { - expandMargin(gd); + 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; + } + } + } + } } +} - // Scroll section must be executed after repositionLegend. - // It requires the legend width, height, x and y to position the scrollbox - // and these values are mutated in repositionLegend. - var gs = fullLayout._size, - lx = gs.l + gs.w * opts.x, - ly = gs.t + gs.h * (1 - opts.y); +function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { + var out = new Array(len); + var i; - if(_$anchor_utils_98.isRightAnchor(opts)) { - lx -= opts._width; - } - else if(_$anchor_utils_98.isCenterAnchor(opts)) { - lx -= opts._width / 2; + function fillOneAxis(i, axisId) { + if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) { + out[i] = axisId; + axisMap[axisId] = i; + } + else out[i] = ''; } - if(_$anchor_utils_98.isBottomAnchor(opts)) { - ly -= opts._height; + if(Array.isArray(axesIn)) { + for(i = 0; i < len; i++) { + fillOneAxis(i, axesIn[i]); + } } - else if(_$anchor_utils_98.isMiddleAnchor(opts)) { - ly -= opts._height / 2; + else { + // default axis list is the first `len` axis ids + fillOneAxis(0, axLetter); + for(i = 1; i < len; i++) { + fillOneAxis(i, axLetter + (i + 1)); + } } - // Make sure the legend left and right sides are visible - var legendWidth = opts._width, - legendWidthMax = gs.w; + return out; +} - if(legendWidth > legendWidthMax) { - lx = gs.l; - legendWidth = legendWidthMax; - } - else { - if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; - if(lx < lxMin) lx = lxMin; - legendWidth = Math.min(lxMax - lx, opts._width); - } +var _$grid_92 = { + moduleType: 'component', + name: 'grid', - // Make sure the legend top and bottom are visible - // (legends with a scroll bar are not allowed to stretch beyond the extended - // margins) - var legendHeight = opts._height, - legendHeightMax = gs.h; + schema: { + layout: {grid: gridAttrs} + }, - if(legendHeight > legendHeightMax) { - ly = gs.t; - legendHeight = legendHeightMax; - } - else { - if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; - if(ly < lyMin) ly = lyMin; - legendHeight = Math.min(lyMax - ly, opts._height); - } + layoutAttributes: gridAttrs, + sizeDefaults: sizeDefaults, + contentDefaults: contentDefaults +}; - // Set size and position of all the elements that make up a legend: - // legend, background and border, scroll box and scroll bar - _$drawing_71.setTranslate(legend, lx, ly); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // to be safe, remove previous listeners - scrollBar.on('.drag', null); - legend.on('wheel', null); +'use strict'; - if(opts._height <= legendHeight || gd._context.staticPlot) { - // if scrollbar should not be shown. - bg.attr({ - width: legendWidth - opts.borderwidth, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); +/* removed: var _$constants_213 = require('../../plots/cartesian/constants'); */; - _$drawing_71.setTranslate(scrollBox, 0, 0); - clipPath.select('rect').attr({ - width: legendWidth - 2 * opts.borderwidth, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth - }); +var _$attributes_93 = { + _isLinkedToArray: 'image', - _$drawing_71.setClipUrl(scrollBox, clipId); + visible: { + valType: 'boolean', + + dflt: true, + editType: 'arraydraw', + + }, - _$drawing_71.setRect(scrollBar, 0, 0, 0, 0); - delete opts._scrollY; - } - else { - var scrollBarHeight = Math.max(_$constants_100.scrollBarMinHeight, - legendHeight * legendHeight / opts._height); - var scrollBarYMax = legendHeight - - scrollBarHeight - - 2 * _$constants_100.scrollBarMargin; - var scrollBoxYMax = opts._height - legendHeight; - var scrollRatio = scrollBarYMax / scrollBoxYMax; + source: { + valType: 'string', + + editType: 'arraydraw', + + }, - var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, - // increase the background and clip-path width - // by the scrollbar width and margin - bg.attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_100.scrollBarWidth + - _$constants_100.scrollBarMargin, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); + sizex: { + valType: 'number', + + dflt: 0, + editType: 'arraydraw', + + }, - clipPath.select('rect').attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_100.scrollBarWidth + - _$constants_100.scrollBarMargin, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth + scrollBoxY - }); + sizey: { + valType: 'number', + + dflt: 0, + editType: 'arraydraw', + + }, - _$drawing_71.setClipUrl(scrollBox, clipId); + sizing: { + valType: 'enumerated', + values: ['fill', 'contain', 'stretch'], + dflt: 'contain', + + editType: 'arraydraw', + + }, - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + opacity: { + valType: 'number', + + min: 0, + max: 1, + dflt: 1, + editType: 'arraydraw', + + }, - legend.on('wheel', function() { - scrollBoxY = _$lib_165.constrain( - opts._scrollY + - _$d3_10.event.deltaY / scrollBarYMax * scrollBoxYMax, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - _$d3_10.event.preventDefault(); - } - }); + x: { + valType: 'any', + + dflt: 0, + editType: 'arraydraw', + + }, - var eventY0, scrollBoxY0; + y: { + valType: 'any', + + dflt: 0, + editType: 'arraydraw', + + }, - var drag = _$d3_10.behavior.drag() - .on('dragstart', function() { - eventY0 = _$d3_10.event.sourceEvent.clientY; - scrollBoxY0 = scrollBoxY; - }) - .on('drag', function() { - var e = _$d3_10.event.sourceEvent; - if(e.buttons === 2 || e.ctrlKey) return; + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + editType: 'arraydraw', + + }, - scrollBoxY = _$lib_165.constrain( - (e.clientY - eventY0) / scrollRatio + scrollBoxY0, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - }); + yanchor: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'top', + + editType: 'arraydraw', + + }, - scrollBar.call(drag); - } + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_213.idRegex.x.toString() + ], + dflt: 'paper', + + editType: 'arraydraw', + + }, + + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_213.idRegex.y.toString() + ], + dflt: 'paper', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { - opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; - _$drawing_71.setTranslate(scrollBox, 0, -scrollBoxY); +'use strict'; + +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_189 = require('../../lib/to_log_range'); */; + +/* + * convertCoords: when converting an axis between log and linear + * you need to alter any images on that axis to keep them + * pointing at the same data point. + * In v2.0 this will become obsolete (or perhaps size will still need conversion?) + * we convert size by declaring that the maximum extent *in data units* should be + * the same, assuming the image is anchored by its center (could remove that restriction + * if we think it's important) even though the actual left and right values will not be + * quite the same since the scale becomes nonlinear (and central anchor means the pixel + * center of the image, not the data units center) + * + * gd: the plot div + * ax: the axis being changed + * newType: the type it's getting + * doExtra: function(attr, val) from inside relayout that sets the attribute. + * Use this to make the changes as it's aware if any other changes in the + * same relayout call should override this conversion. + */ +var _$convertCoords_94 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; - _$drawing_71.setRect( - scrollBar, - legendWidth, - _$constants_100.scrollBarMargin + scrollBoxY * scrollRatio, - _$constants_100.scrollBarWidth, - scrollBarHeight - ); - clipPath.select('rect').attr({ - y: opts.borderwidth + scrollBoxY - }); - } + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); - if(gd._context.edits.legendPosition) { - var xf, yf, x0, y0; + if(!(toLog || fromLog)) return; - legend.classed('cursor-move', true); + var images = gd._fullLayout.images, + axLetter = ax._id.charAt(0), + image, + attrPrefix; - _$dragelement_68.init({ - element: legend.node(), - gd: gd, - prepFn: function() { - var transform = _$drawing_71.getTranslate(legend); + for(var i = 0; i < images.length; i++) { + image = images[i]; + attrPrefix = 'images[' + i + '].'; - x0 = transform.x; - y0 = transform.y; - }, - moveFn: function(dx, dy) { - var newX = x0 + dx, - newY = y0 + dy; + if(image[axLetter + 'ref'] === ax._id) { + var currentPos = image[axLetter], + currentSize = image['size' + axLetter], + newPos = null, + newSize = null; - _$drawing_71.setTranslate(legend, newX, newY); + if(toLog) { + newPos = _$toLogRange_189(currentPos, ax.range); - xf = _$dragelement_68.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); - yf = _$dragelement_68.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); - }, - doneFn: function() { - if(xf !== undefined && yf !== undefined) { - _$registry_247.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); - } - }, - clickFn: function(numClicks, e) { - var clickedTrace = - fullLayout._infolayer.selectAll('g.traces').filter(function() { - var bbox = this.getBoundingClientRect(); - return (e.clientX >= bbox.left && e.clientX <= bbox.right && - e.clientY >= bbox.top && e.clientY <= bbox.bottom); - }); - if(clickedTrace.size() > 0) { - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { - _$handleClick_104(clickedTrace, gd, numClicks); - }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - _$handleClick_104(clickedTrace, gd, numClicks); - } - } + // this is the inverse of the conversion we do in fromLog below + // so that the conversion is reversible (notice the fromLog conversion + // is like sinh, and this one looks like arcsinh) + var dx = currentSize / Math.pow(10, newPos) / 2; + newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; + } + else { + newPos = Math.pow(10, currentPos); + newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); } - }); - } -}; - -function drawTexts(g, gd) { - var legendItem = g.data()[0][0], - fullLayout = gd._fullLayout, - trace = legendItem.trace, - isPie = _$registry_247.traceIs(trace, 'pie'), - traceIndex = trace.index, - name = isPie ? legendItem.label : trace.name; - - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); - text.attr('text-anchor', 'start') - .classed('user-select-none', true) - .call(_$drawing_71.font, fullLayout.legend.font) - .text(name); + // if conversion failed, delete the value so it can get a default later on + if(!_$fastIsnumeric_13(newPos)) { + newPos = null; + newSize = null; + } + else if(!_$fastIsnumeric_13(newSize)) newSize = null; - function textLayout(s) { - _$svg_text_utils_186.convertToTspans(s, gd, function() { - computeTextDimensions(g, gd); - }); + doExtra(attrPrefix + axLetter, newPos); + doExtra(attrPrefix + 'size' + axLetter, newSize); + } } +}; - if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_186.makeEditable, {gd: gd}) - .call(textLayout) - .on('edit', function(text) { - this.text(text) - .call(textLayout); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 origText = text; +'use strict'; - if(!this.text()) text = ' \u0020\u0020 '; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_204 = require('../../plots/array_container_defaults'); */; - var transforms, direction; - var fullInput = legendItem.trace._fullInput || {}; - var update = {}; +/* removed: var _$attributes_93 = require('./attributes'); */; +var name = 'images'; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_247.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_247.getTransformIndices(fullInput, 'groupby'); - var index = groupbyIndices[groupbyIndices.length - 1]; +var _$supplyLayoutDefaults_95 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: name, + handleItemDefaults: imageDefaults + }; - var kcont = _$lib_165.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + _$handleArrayContainerDefaults_204(layoutIn, layoutOut, opts); +}; - if(origText === '') { - kcont.remove(legendItem.trace._group); - } else { - kcont.set(legendItem.trace._group, text); - } - update = kcont.constructUpdate(); - } else { - update.name = text; - } +function imageDefaults(imageIn, imageOut, fullLayout) { - return _$registry_247.call('restyle', gd, update, traceIndex); - }); - } else { - textLayout(text); + function coerce(attr, dflt) { + return _$lib_166.coerce(imageIn, imageOut, _$attributes_93, attr, dflt); } -} -function setupTraceToggle(g, gd) { - var newMouseDownTime, - numClicks = 1; + var source = coerce('source'); + var visible = coerce('visible', !!source); - var traceToggle = g.selectAll('rect') - .data([0]); + if(!visible) return imageOut; - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_46.fill, 'rgba(0,0,0,0)'); + coerce('layer'); + coerce('xanchor'); + coerce('yanchor'); + coerce('sizex'); + coerce('sizey'); + coerce('sizing'); + coerce('opacity'); + var gdMock = { _fullLayout: fullLayout }, + axLetters = ['x', 'y']; - traceToggle.on('mousedown', function() { - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { - // 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; + for(var i = 0; i < 2; i++) { + // 'paper' is the fallback axref + var axLetter = axLetters[i], + axRef = _$axes_208.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } + _$axes_208.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + } - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { _$handleClick_104(g, gd, numClicks); }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - gd._legendMouseDownTime = 0; - _$handleClick_104(g, gd, numClicks); - } - }); + return imageOut; } -function computeTextDimensions(g, gd) { - var legendItem = g.data()[0][0]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!legendItem.trace.showlegend) { - g.remove(); - return; - } +'use strict'; - var mathjaxGroup = g.select('g[class*=math-group]'); - var mathjaxNode = mathjaxGroup.node(); - var opts = gd._fullLayout.legend; - var lineHeight = opts.font.size * __LINE_SPACING_102; - var height, width; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$xmlns_namespaces_150 = require('../../constants/xmlns_namespaces'); */; - if(mathjaxNode) { - var mathjaxBB = _$drawing_71.bBox(mathjaxNode); +var _$draw_96 = function draw(gd) { + var fullLayout = gd._fullLayout, + imageDataAbove = [], + imageDataSubplot = {}, + imageDataBelow = [], + subplot, + i; - height = mathjaxBB.height; - width = mathjaxBB.width; + // Sort into top, subplot, and bottom layers + for(i = 0; i < fullLayout.images.length; i++) { + var img = fullLayout.images[i]; - _$drawing_71.setTranslate(mathjaxGroup, 0, (height / 4)); - } - else { - var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_186.lineCount(text); - var textNode = text.node(); + if(img.visible) { + if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { + subplot = img.xref + img.yref; - height = lineHeight * textLines; - width = textNode ? _$drawing_71.bBox(textNode).width : 0; + var plotinfo = fullLayout._plots[subplot]; - // approximation to height offset to center the font - // to avoid getBoundingClientRect - var textY = lineHeight * (0.3 + (1 - textLines) / 2); - // TODO: this 40 should go in a constants file (along with other - // values related to the legend symbol size) - _$svg_text_utils_186.positionText(text, 40, textY); - } + if(!plotinfo) { + // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the image to an x / y axis combination + // that doesn't have any data on it (and layer is below) + imageDataBelow.push(img); + continue; + } - height = Math.max(height, 16) + 3; + if(plotinfo.mainplot) { + subplot = plotinfo.mainplot.id; + } - legendItem.height = height; - legendItem.width = width; -} + if(!imageDataSubplot[subplot]) { + imageDataSubplot[subplot] = []; + } + imageDataSubplot[subplot].push(img); + } else if(img.layer === 'above') { + imageDataAbove.push(img); + } else { + imageDataBelow.push(img); + } + } + } -function computeLegendDimensions(gd, groups, traces) { - var fullLayout = gd._fullLayout; - var opts = fullLayout.legend; - var borderwidth = opts.borderwidth; - var isGrouped = _$helpers_105.isGrouped(opts); - var extraWidth = 0; + var anchors = { + x: { + left: { sizing: 'xMin', offset: 0 }, + center: { sizing: 'xMid', offset: -1 / 2 }, + right: { sizing: 'xMax', offset: -1 } + }, + y: { + top: { sizing: 'YMin', offset: 0 }, + middle: { sizing: 'YMid', offset: -1 / 2 }, + bottom: { sizing: 'YMax', offset: -1 } + } + }; - opts._width = 0; - opts._height = 0; - if(_$helpers_105.isVertical(opts)) { - if(isGrouped) { - groups.each(function(d, i) { - _$drawing_71.setTranslate(this, 0, i * opts.tracegroupgap); - }); + // Images must be converted to dataURL's for exporting. + function setImage(d) { + var thisImage = _$d3_10.select(this); + + if(this.img && this.img.src === d.source) { + return; } - traces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height, - textWidth = legendItem.width; + thisImage.attr('xmlns', _$xmlns_namespaces_150.svg); - _$drawing_71.setTranslate(this, - borderwidth, - (5 + borderwidth + opts._height + textHeight / 2)); + var imagePromise = new Promise(function(resolve) { - opts._height += textHeight; - opts._width = Math.max(opts._width, textWidth); - }); + var img = new Image(); + this.img = img; - opts._width += 45 + borderwidth * 2; - opts._height += 10 + borderwidth * 2; + // If not set, a `tainted canvas` error is thrown + img.setAttribute('crossOrigin', 'anonymous'); + img.onerror = errorHandler; + img.onload = function() { + var canvas = document.createElement('canvas'); + canvas.width = this.width; + canvas.height = this.height; - if(isGrouped) { - opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; - } + var ctx = canvas.getContext('2d'); + ctx.drawImage(this, 0, 0); - extraWidth = 40; - } - else if(isGrouped) { - var groupXOffsets = [opts._width], - groupData = groups.data(); + var dataURL = canvas.toDataURL('image/png'); - for(var i = 0, n = groupData.length; i < n; i++) { - var textWidths = groupData[i].map(function(legendItemArray) { - return legendItemArray[0].width; - }); + thisImage.attr('xlink:href', dataURL); - var groupWidth = 40 + Math.max.apply(null, textWidths); + // resolve promise in onload handler instead of on 'load' to support IE11 + // see https://github.com/plotly/plotly.js/issues/1685 + // for more details + resolve(); + }; - opts._width += opts.tracegroupgap + groupWidth; - groupXOffsets.push(opts._width); - } + thisImage.on('error', errorHandler); - groups.each(function(d, i) { - _$drawing_71.setTranslate(this, groupXOffsets[i], 0); - }); + img.src = d.source; - groups.each(function() { - var group = _$d3_10.select(this), - groupTraces = group.selectAll('g.traces'), - groupHeight = 0; + function errorHandler() { + thisImage.remove(); + resolve(); + } + }.bind(this)); - groupTraces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height; + gd._promises.push(imagePromise); + } - _$drawing_71.setTranslate(this, - 0, - (5 + borderwidth + groupHeight + textHeight / 2)); + function applyAttributes(d) { + var thisImage = _$d3_10.select(this); - groupHeight += textHeight; - }); + // Axes if specified + var xa = _$axes_208.getFromId(gd, d.xref), + ya = _$axes_208.getFromId(gd, d.yref); - opts._height = Math.max(opts._height, groupHeight); - }); + var size = fullLayout._size, + width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, + height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; - opts._height += 10 + borderwidth * 2; - opts._width += borderwidth * 2; - } - else { - var rowHeight = 0, - maxTraceHeight = 0, - maxTraceWidth = 0, - offsetX = 0, - fullTracesWidth = 0, - traceGap = opts.tracegroupgap || 5, - oneRowLegend; + // Offsets for anchor positioning + var xOffset = width * anchors.x[d.xanchor].offset, + yOffset = height * anchors.y[d.yanchor].offset; - // calculate largest width for traces and use for width of all legend items - traces.each(function(d) { - maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); - fullTracesWidth += 40 + d[0].width + traceGap; - }); + var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; - // check if legend fits in one row - oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; - traces.each(function(d) { - var legendItem = d[0], - traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; + // Final positions + var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, + yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; - if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { - offsetX = 0; - rowHeight = rowHeight + maxTraceHeight; - opts._height = opts._height + maxTraceHeight; - // reset for next row - maxTraceHeight = 0; - } - _$drawing_71.setTranslate(this, - (borderwidth + offsetX), - (5 + borderwidth + legendItem.height / 2) + rowHeight); + // Construct the proper aspectRatio attribute + switch(d.sizing) { + case 'fill': + sizing += ' slice'; + break; - opts._width += traceGap + traceWidth; - opts._height = Math.max(opts._height, legendItem.height); + case 'stretch': + sizing = 'none'; + break; + } - // keep track of tallest trace in group - offsetX += traceGap + traceWidth; - maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); + thisImage.attr({ + x: xPos, + y: yPos, + width: width, + height: height, + preserveAspectRatio: sizing, + opacity: d.opacity }); - opts._width += borderwidth * 2; - opts._height += 10 + borderwidth * 2; - - } - - // make sure we're only getting full pixels - opts._width = Math.ceil(opts._width); - opts._height = Math.ceil(opts._height); - traces.each(function(d) { - var legendItem = d[0], - bg = _$d3_10.select(this).select('.legendtoggle'); + // Set proper clipping on images + var xId = xa ? xa._id : '', + yId = ya ? ya._id : '', + clipAxes = xId + yId; - _$drawing_71.setRect(bg, - 0, - -legendItem.height / 2, - (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, - legendItem.height + thisImage.call(_$drawing_71.setClipUrl, clipAxes ? + ('clip' + fullLayout._uid + clipAxes) : + null ); - }); -} + } -function expandMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; + var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') + .data(imageDataBelow), + imagesAbove = fullLayout._imageUpperLayer.selectAll('image') + .data(imageDataAbove); - var xanchor = 'left'; - if(_$anchor_utils_98.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_98.isCenterAnchor(opts)) { - xanchor = 'center'; - } + imagesBelow.enter().append('image'); + imagesAbove.enter().append('image'); - var yanchor = 'top'; - if(_$anchor_utils_98.isBottomAnchor(opts)) { - yanchor = 'bottom'; - } - else if(_$anchor_utils_98.isMiddleAnchor(opts)) { - yanchor = 'middle'; - } + imagesBelow.exit().remove(); + imagesAbove.exit().remove(); - // lastly check if the margin auto-expand has changed - _$plots_240.autoMargin(gd, 'legend', { - x: opts.x, - y: opts.y, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: opts._height * (FROM_BR[yanchor]), - t: opts._height * (FROM_TL[yanchor]) + imagesBelow.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); + }); + imagesAbove.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); }); -} -function expandHorizontalMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; + var allSubplots = Object.keys(fullLayout._plots); + for(i = 0; i < allSubplots.length; i++) { + subplot = allSubplots[i]; + var subplotObj = fullLayout._plots[subplot]; - var xanchor = 'left'; - if(_$anchor_utils_98.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_98.isCenterAnchor(opts)) { - xanchor = 'center'; - } + // filter out overlaid plots (which havd their images on the main plot) + // and gl2d plots (which don't support below images, at least not yet) + if(!subplotObj.imagelayer) continue; - // lastly check if the margin auto-expand has changed - _$plots_240.autoMargin(gd, 'legend', { - x: opts.x, - y: 0.5, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: 0, - t: 0 - }); -} + var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') + // even if there are no images on this subplot, we need to run + // enter and exit in case there were previously + .data(imageDataSubplot[subplot] || []); + + imagesOnSubplot.enter().append('image'); + imagesOnSubplot.exit().remove(); + + imagesOnSubplot.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); + }); + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45552,19 +47284,19 @@ function expandHorizontalMargin(gd) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; - -var _$legend_106 = { +var _$images_97 = { moduleType: 'component', - name: 'legend', + name: 'images', - layoutAttributes: _$attributes_99, - supplyLayoutDefaults: _$legendDefaults_101, + layoutAttributes: _$attributes_93, + supplyLayoutDefaults: _$supplyLayoutDefaults_95, + includeBasePlot: _$makeIncludeComponents_218('images'), - draw: _$draw_102, - style: _$style_107 + draw: _$draw_96, + + convertCoords: _$convertCoords_94 }; /** @@ -45577,78 +47309,67 @@ var _$legend_106 = { 'use strict'; +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_45 = require('../color/attributes'); */; + -var _$button_attributes_113 = { - step: { - valType: 'enumerated', +var _$attributes_99 = { + bgcolor: { + valType: 'color', - values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], - dflt: 'month', - editType: 'plot', + editType: 'legend', }, - stepmode: { - valType: 'enumerated', + bordercolor: { + valType: 'color', + dflt: _$attributes_45.defaultLine, - values: ['backward', 'todate'], - dflt: 'backward', - editType: 'plot', + editType: 'legend', }, - count: { + borderwidth: { valType: 'number', - min: 0, - dflt: 1, - editType: 'plot', + dflt: 0, + + editType: 'legend', }, - label: { - valType: 'string', + font: _$font_attributes_234({ + editType: 'legend', - editType: 'plot', + }), + orientation: { + valType: 'enumerated', + values: ['v', 'h'], + dflt: 'v', + + editType: 'legend', }, - editType: 'plot' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_45 = require('../color/attributes'); */; -var __extendFlat_112 = _$extend_159.extendFlat; -/* removed: var _$button_attributes_113 = require('./button_attributes'); */; - -_$button_attributes_113 = __extendFlat_112(_$button_attributes_113, { - _isLinkedToArray: 'button', - - -}); - -var _$attributes_112 = { - visible: { - valType: 'boolean', + traceorder: { + valType: 'flaglist', + flags: ['reversed', 'grouped'], + extras: ['normal'], - editType: 'plot', + editType: 'legend', + + }, + tracegroupgap: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'legend', }, - - buttons: _$button_attributes_113, - x: { valType: 'number', min: -2, max: 3, + dflt: 1.02, - editType: 'plot', + editType: 'legend', }, xanchor: { @@ -45656,62 +47377,30 @@ var _$attributes_112 = { values: ['auto', 'left', 'center', 'right'], dflt: 'left', - editType: 'plot', + editType: 'legend', }, y: { valType: 'number', min: -2, max: 3, + dflt: 1, - editType: 'plot', + editType: 'legend', }, yanchor: { valType: 'enumerated', values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'bottom', - - editType: 'plot', - - }, - - font: _$font_attributes_234({ - editType: 'plot', - - }), - - bgcolor: { - valType: 'color', - dflt: _$attributes_45.lightLine, - - editType: 'plot', - - }, - activecolor: { - valType: 'color', - - editType: 'plot', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_45.defaultLine, - - editType: 'plot', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, + dflt: 'auto', - editType: 'plot', + editType: 'legend', }, - editType: 'plot' + editType: 'legend' }; +var _$helpers_105 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45720,24 +47409,29 @@ var _$attributes_112 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; +'use strict'; -var _$constants_114 = { +_$helpers_105.legendGetsTrace = function legendGetsTrace(trace) { + // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? + // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. - // 'y' position pad above counter axis domain - yPad: 0.02, + // Note that we explicitly include showlegend: false, so a trace that *could* be + // in the legend but is not shown still counts toward the two traces you need to + // ensure the legend is shown by default, because this can still help disambiguate. + return trace.visible && (trace.showlegend !== undefined); +}; - // minimum button width (regardless of text size) - minButtonWidth: 30, +_$helpers_105.isGrouped = function isGrouped(legendLayout) { + return (legendLayout.traceorder || '').indexOf('grouped') !== -1; +}; - // buttons rect radii - rx: 3, - ry: 3, +_$helpers_105.isVertical = function isVertical(legendLayout) { + return legendLayout.orientation !== 'h'; +}; - // light fraction used to compute the 'activecolor' default - lightAmount: 25, - darkAmount: 10 +_$helpers_105.isReversed = function isReversed(legendLayout) { + return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; /** @@ -45748,152 +47442,91 @@ var _$constants_114 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$color_46 = require('../color'); */; - -/* removed: var _$attributes_112 = require('./attributes'); */; -/* removed: var _$button_attributes_113 = require('./button_attributes'); */; -/* removed: var _$constants_114 = require('./constants'); */; - - -var _$handleDefaults_115 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { - var selectorIn = containerIn.rangeselector || {}, - selectorOut = containerOut.rangeselector = {}; - - function coerce(attr, dflt) { - return _$lib_165.coerce(selectorIn, selectorOut, _$attributes_112, attr, dflt); - } - - var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - - var posDflt = getPosDflt(containerOut, layout, counterAxes); - coerce('x', posDflt[0]); - coerce('y', posDflt[1]); - _$lib_165.noneOrAll(containerIn, containerOut, ['x', 'y']); - - coerce('xanchor'); - coerce('yanchor'); - _$lib_165.coerceFont(coerce, 'font', layout.font); +'use strict'; - var bgColor = coerce('bgcolor'); - coerce('activecolor', _$color_46.contrast(bgColor, _$constants_114.lightAmount, _$constants_114.darkAmount)); - coerce('bordercolor'); - coerce('borderwidth'); -}; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -function buttonsDefaults(containerIn, containerOut, calendar) { - var buttonsIn = containerIn.buttons || [], - buttonsOut = containerOut.buttons = []; +/* removed: var _$attributes_99 = require('./attributes'); */; +/* removed: var _$layout_attributes_238 = require('../../plots/layout_attributes'); */; +/* removed: var _$helpers_105 = require('./helpers'); */; - var buttonIn, buttonOut; - function coerce(attr, dflt) { - return _$lib_165.coerce(buttonIn, buttonOut, _$button_attributes_113, attr, dflt); - } +var _$legendDefaults_101 = function legendDefaults(layoutIn, layoutOut, fullData) { + var containerIn = layoutIn.legend || {}; + var containerOut = {}; - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + var visibleTraces = 0; + var defaultOrder = 'normal'; - if(!_$lib_165.isPlainObject(buttonIn)) continue; + var defaultX, defaultY, defaultXAnchor, defaultYAnchor; - var step = coerce('step'); - if(step !== 'all') { - if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { - buttonOut.stepmode = 'backward'; - } - else { - coerce('stepmode'); - } + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - coerce('count'); + if(_$helpers_105.legendGetsTrace(trace)) { + visibleTraces++; + // always show the legend by default if there's a pie + if(_$registry_248.traceIs(trace, 'pie')) visibleTraces++; } - coerce('label'); + if((_$registry_248.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { + defaultOrder = _$helpers_105.isGrouped({traceorder: defaultOrder}) ? + 'grouped+reversed' : 'reversed'; + } - buttonOut._index = i; - buttonsOut.push(buttonOut); + if(trace.legendgroup !== undefined && trace.legendgroup !== '') { + defaultOrder = _$helpers_105.isReversed({traceorder: defaultOrder}) ? + 'reversed+grouped' : 'grouped'; + } } - return buttonsOut; -} - -function getPosDflt(containerOut, layout, counterAxes) { - var anchoredList = counterAxes.filter(function(ax) { - return layout[ax].anchor === containerOut._id; - }); - - var posY = 0; - for(var i = 0; i < anchoredList.length; i++) { - var domain = layout[anchoredList[i]].domain; - if(domain) posY = Math.max(domain[1], posY); + function coerce(attr, dflt) { + return _$lib_166.coerce(containerIn, containerOut, _$attributes_99, attr, dflt); } - return [containerOut.domain[0], posY + _$constants_114.yPad]; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 showLegend = _$lib_166.coerce(layoutIn, layoutOut, + _$layout_attributes_238, 'showlegend', visibleTraces > 1); -'use strict'; + if(showLegend === false) return; -/* removed: var _$d3_10 = require('d3'); */; + layoutOut.legend = containerOut; -var _$getUpdateObject_117 = function getUpdateObject(axisLayout, buttonLayout) { - var axName = axisLayout._name; - var update = {}; + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); + _$lib_166.coerceFont(coerce, 'font', layoutOut.font); - if(buttonLayout.step === 'all') { - update[axName + '.autorange'] = true; + coerce('orientation'); + if(containerOut.orientation === 'h') { + var xaxis = layoutIn.xaxis; + if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = 1.1; + defaultYAnchor = 'bottom'; + } + else { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = -0.1; + defaultYAnchor = 'top'; + } } - else { - var xrange = getXRange(axisLayout, buttonLayout); - update[axName + '.range[0]'] = xrange[0]; - update[axName + '.range[1]'] = xrange[1]; - } + coerce('traceorder', defaultOrder); + if(_$helpers_105.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); - return update; + coerce('x', defaultX); + coerce('xanchor', defaultXAnchor); + coerce('y', defaultY); + coerce('yanchor', defaultYAnchor); + _$lib_166.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -function getXRange(axisLayout, buttonLayout) { - var currentRange = axisLayout.range; - var base = new Date(axisLayout.r2l(currentRange[1])); - - var step = buttonLayout.step, - count = buttonLayout.count; - - var range0; - - switch(buttonLayout.stepmode) { - case 'backward': - range0 = axisLayout.l2r(+_$d3_10.time[step].utc.offset(base, -count)); - break; - - case 'todate': - var base2 = _$d3_10.time[step].utc.offset(base, -count); - - range0 = axisLayout.l2r(+_$d3_10.time[step].utc.ceil(base2)); - break; - } - - var range1 = currentRange[1]; - - return [range0, range1]; -} - +var _$anchor_utils_98 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45902,260 +47535,166 @@ function getXRange(axisLayout, buttonLayout) { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$d3_10 = require('d3'); */; - -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_210 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$anchor_utils_98 = require('../legend/anchor_utils'); */; - -/* removed: var _$alignment_146 = require('../../constants/alignment'); */; -var __LINE_SPACING_116 = _$alignment_146.LINE_SPACING; -var __FROM_TL_116 = _$alignment_146.FROM_TL; -var __FROM_BR_116 = _$alignment_146.FROM_BR; - -/* removed: var _$constants_114 = require('./constants'); */; -/* removed: var _$getUpdateObject_117 = require('./get_update_object'); */; - - -var _$draw_116 = function draw(gd) { - var fullLayout = gd._fullLayout; - - var selectors = fullLayout._infolayer.selectAll('.rangeselector') - .data(makeSelectorData(gd), selectorKeyFunc); - - selectors.enter().append('g') - .classed('rangeselector', true); - - selectors.exit().remove(); - - selectors.style({ - cursor: 'pointer', - 'pointer-events': 'all' - }); - - selectors.each(function(d) { - var selector = _$d3_10.select(this), - axisLayout = d, - selectorLayout = axisLayout.rangeselector; - - var buttons = selector.selectAll('g.button') - .data(selectorLayout.buttons); - - buttons.enter().append('g') - .classed('button', true); - - buttons.exit().remove(); - - buttons.each(function(d) { - var button = _$d3_10.select(this); - var update = _$getUpdateObject_117(axisLayout, d); - - d._isActive = isActive(axisLayout, d, update); - - button.call(drawButtonRect, selectorLayout, d); - button.call(drawButtonText, selectorLayout, d, gd); - - button.on('click', function() { - if(gd._dragged) return; - - _$registry_247.call('relayout', gd, update); - }); - - button.on('mouseover', function() { - d._isHovered = true; - button.call(drawButtonRect, selectorLayout, d); - }); - - button.on('mouseout', function() { - d._isHovered = false; - button.call(drawButtonRect, selectorLayout, d); - }); - }); - - reposition(gd, buttons, selectorLayout, axisLayout._name, selector); - }); - -}; - -function makeSelectorData(gd) { - var axes = _$axis_ids_210.list(gd, 'x', true); - var data = []; - - for(var i = 0; i < axes.length; i++) { - var axis = axes[i]; - - if(axis.rangeselector && axis.rangeselector.visible) { - data.push(axis); - } - } - - return data; -} - -function selectorKeyFunc(d) { - return d._id; -} - -function isActive(axisLayout, opts, update) { - if(opts.step === 'all') { - return axisLayout.autorange === true; - } - else { - var keys = Object.keys(update); - - return ( - axisLayout.range[0] === update[keys[0]] && - axisLayout.range[1] === update[keys[1]] - ); - } -} -function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); +'use strict'; - rect.enter().append('rect') - .classed('selector-rect', true); - rect.attr('shape-rendering', 'crispEdges'); +/** + * 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. + */ - rect.attr({ - 'rx': _$constants_114.rx, - 'ry': _$constants_114.ry - }); +_$anchor_utils_98.isRightAnchor = function isRightAnchor(opts) { + return ( + opts.xanchor === 'right' || + (opts.xanchor === 'auto' && opts.x >= 2 / 3) + ); +}; - rect.call(_$color_46.stroke, selectorLayout.bordercolor) - .call(_$color_46.fill, getFillColor(selectorLayout, d)) - .style('stroke-width', selectorLayout.borderwidth + 'px'); -} +_$anchor_utils_98.isCenterAnchor = function isCenterAnchor(opts) { + return ( + opts.xanchor === 'center' || + (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) + ); +}; -function getFillColor(selectorLayout, d) { - return (d._isActive || d._isHovered) ? - selectorLayout.activecolor : - selectorLayout.bgcolor; -} +_$anchor_utils_98.isBottomAnchor = function isBottomAnchor(opts) { + return ( + opts.yanchor === 'bottom' || + (opts.yanchor === 'auto' && opts.y <= 1 / 3) + ); +}; -function drawButtonText(button, selectorLayout, d, gd) { - function textLayout(s) { - _$svg_text_utils_186.convertToTspans(s, gd); - } +_$anchor_utils_98.isMiddleAnchor = function isMiddleAnchor(opts) { + return ( + opts.yanchor === 'middle' || + (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) + ); +}; - var text = button.selectAll('text') - .data([0]); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); +'use strict'; - text.attr('text-anchor', 'middle'); +var _$constants_100 = { + scrollBarWidth: 6, + scrollBarMinHeight: 20, + scrollBarColor: '#808BA4', + scrollBarMargin: 4 +}; - text.call(_$drawing_71.font, selectorLayout.font) - .text(getLabel(d)) - .call(textLayout); -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function getLabel(opts) { - if(opts.label) return opts.label; - if(opts.step === 'all') return 'all'; +'use strict'; - return opts.count + opts.step.charAt(0); -} +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$helpers_105 = require('./helpers'); */; -function reposition(gd, buttons, opts, axName, selector) { - var width = 0; - var height = 0; - var borderWidth = opts.borderwidth; +var _$getLegendData_103 = function getLegendData(calcdata, opts) { + var lgroupToTraces = {}, + lgroups = [], + hasOneNonBlankGroup = false, + slicesShown = {}, + lgroupi = 0; - buttons.each(function() { - var button = _$d3_10.select(this); - var text = button.select('.selector-text'); + var i, j; - var tHeight = opts.font.size * __LINE_SPACING_116; - var hEff = Math.max(tHeight * _$svg_text_utils_186.lineCount(text), 16) + 3; + function addOneItem(legendGroup, legendItem) { + // each '' legend group is treated as a separate group + if(legendGroup === '' || !_$helpers_105.isGrouped(opts)) { + var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? - height = Math.max(height, hEff); - }); + lgroups.push(uniqueGroup); + lgroupToTraces[uniqueGroup] = [[legendItem]]; + lgroupi++; + } + else if(lgroups.indexOf(legendGroup) === -1) { + lgroups.push(legendGroup); + hasOneNonBlankGroup = true; + lgroupToTraces[legendGroup] = [[legendItem]]; + } + else lgroupToTraces[legendGroup].push([legendItem]); + } - buttons.each(function() { - var button = _$d3_10.select(this); - var rect = button.select('.selector-rect'); - var text = button.select('.selector-text'); + // build an { legendgroup: [cd0, cd0], ... } object + for(i = 0; i < calcdata.length; i++) { + var cd = calcdata[i], + cd0 = cd[0], + trace = cd0.trace, + lgroup = trace.legendgroup; - var tWidth = text.node() && _$drawing_71.bBox(text.node()).width; - var tHeight = opts.font.size * __LINE_SPACING_116; - var tLines = _$svg_text_utils_186.lineCount(text); + if(!_$helpers_105.legendGetsTrace(trace) || !trace.showlegend) continue; - var wEff = Math.max(tWidth + 10, _$constants_114.minButtonWidth); + if(_$registry_248.traceIs(trace, 'pie')) { + if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; - // TODO add MathJax support + for(j = 0; j < cd.length; j++) { + var labelj = cd[j].label; - // TODO add buttongap attribute + if(!slicesShown[lgroup][labelj]) { + addOneItem(lgroup, { + label: labelj, + color: cd[j].color, + i: cd[j].i, + trace: trace + }); - button.attr('transform', 'translate(' + - (borderWidth + width) + ',' + borderWidth + - ')'); + slicesShown[lgroup][labelj] = true; + } + } + } - rect.attr({ - x: 0, - y: 0, - width: wEff, - height: height - }); + else addOneItem(lgroup, cd0); + } - _$svg_text_utils_186.positionText(text, wEff / 2, - height / 2 - ((tLines - 1) * tHeight / 2) + 3); + // won't draw a legend in this case + if(!lgroups.length) return []; - width += wEff + 5; - }); + // rearrange lgroupToTraces into a d3-friendly array of arrays + var lgroupsLength = lgroups.length, + ltraces, + legendData; - var graphSize = gd._fullLayout._size; - var lx = graphSize.l + graphSize.w * opts.x; - var ly = graphSize.t + graphSize.h * (1 - opts.y); + if(hasOneNonBlankGroup && _$helpers_105.isGrouped(opts)) { + legendData = new Array(lgroupsLength); - var xanchor = 'left'; - if(_$anchor_utils_98.isRightAnchor(opts)) { - lx -= width; - xanchor = 'right'; - } - if(_$anchor_utils_98.isCenterAnchor(opts)) { - lx -= width / 2; - xanchor = 'center'; + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]]; + legendData[i] = _$helpers_105.isReversed(opts) ? ltraces.reverse() : ltraces; + } } + else { + // collapse all groups into one if all groups are blank + legendData = [new Array(lgroupsLength)]; - var yanchor = 'top'; - if(_$anchor_utils_98.isBottomAnchor(opts)) { - ly -= height; - yanchor = 'bottom'; - } - if(_$anchor_utils_98.isMiddleAnchor(opts)) { - ly -= height / 2; - yanchor = 'middle'; + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]][0]; + legendData[0][_$helpers_105.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; + } + lgroupsLength = 1; } - width = Math.ceil(width); - height = Math.ceil(height); - lx = Math.round(lx); - ly = Math.round(ly); - - _$plots_240.autoMargin(gd, axName + '-range-selector', { - x: opts.x, - y: opts.y, - l: width * __FROM_TL_116[xanchor], - r: width * __FROM_BR_116[xanchor], - b: height * __FROM_BR_116[yanchor], - t: height * __FROM_TL_116[yanchor] - }); - - selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); -} + // needed in repositionLegend + opts._lgroupsLength = lgroupsLength; + return legendData; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -46167,150 +47706,220 @@ function reposition(gd, buttons, opts, axName, selector) { 'use strict'; -var _$rangeselector_118 = { - moduleType: 'component', - name: 'rangeselector', +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_248 = require('../../registry'); */; - schema: { - subplots: { - xaxis: {rangeselector: _$attributes_112} +var SHOWISOLATETIP = true; + +var _$handleClick_104 = function handleClick(g, gd, numClicks) { + if(gd._dragged || gd._editing) return; + + var hiddenSlices = gd._fullLayout.hiddenlabels ? + gd._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] = []; } - }, - layoutAttributes: _$attributes_112, - handleDefaults: _$handleDefaults_115, + if(attrIndices.indexOf(traceIndex) === -1) { + attrIndices.push(traceIndex); + attrIndex = attrIndices.length - 1; + } - draw: _$draw_116 -}; + valueArray[attrIndex] = value; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 attrIndex; + } -'use strict'; + function setVisibility(fullTrace, visibility) { + var fullInput = fullTrace._fullInput; + if(_$registry_248.hasTransform(fullInput, 'groupby')) { + var kcont = carrs[fullInput.index]; + if(!kcont) { + var groupbyIndices = _$registry_248.getTransformIndices(fullInput, 'groupby'); + var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; + kcont = _$lib_166.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + carrs[fullInput.index] = kcont; + } -/* removed: var _$attributes_45 = require('../color/attributes'); */; + var curState = kcont.get(fullTrace._group); -var _$attributes_119 = { - bgcolor: { - valType: 'color', - dflt: _$attributes_45.background, - - editType: 'plot', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_45.defaultLine, - - editType: 'plot', - - }, - borderwidth: { - valType: 'integer', - dflt: 0, - min: 0, - - editType: 'plot', - - }, - autorange: { - valType: 'boolean', - dflt: true, - - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, - - }, - range: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} - ], - editType: 'calc', - impliedEdits: {'autorange': false}, - - }, - thickness: { - valType: 'number', - dflt: 0.15, - min: 0, - max: 1, - - editType: 'plot', - - }, - visible: { - valType: 'boolean', - dflt: true, - - editType: 'calc', - - }, - editType: 'calc' -}; + // 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; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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; -'use strict'; + insertUpdate(fullInput.index, 'visible', nextVisibility); + } + } -var _$constants_121 = { + if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { + _$lib_166.notifier(_$lib_166._(gd, 'Double-click on legend to isolate one trace'), 'long'); + SHOWISOLATETIP = false; + } else { + SHOWISOLATETIP = false; + } - // attribute container name - name: 'rangeslider', + if(_$registry_248.traceIs(fullTrace, 'pie')) { + var thisLabel = legendItem.label, + thisLabelIndex = hiddenSlices.indexOf(thisLabel); - // class names + if(numClicks === 1) { + if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); + else hiddenSlices.splice(thisLabelIndex, 1); + } else if(numClicks === 2) { + 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 = []; + } + } - containerClassName: 'rangeslider-container', - bgClassName: 'rangeslider-bg', - rangePlotClassName: 'rangeslider-rangeplot', + _$registry_248.call('relayout', 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); + } + } + } - maskMinClassName: 'rangeslider-mask-min', - maskMaxClassName: 'rangeslider-mask-max', - slideBoxClassName: 'rangeslider-slidebox', + if(numClicks === 1) { + var nextVisibility; - grabberMinClassName: 'rangeslider-grabber-min', - grabAreaMinClassName: 'rangeslider-grabarea-min', - handleMinClassName: 'rangeslider-handle-min', + switch(fullTrace.visible) { + case true: + nextVisibility = 'legendonly'; + break; + case false: + nextVisibility = false; + break; + case 'legendonly': + nextVisibility = true; + break; + } - grabberMaxClassName: 'rangeslider-grabber-max', - grabAreaMaxClassName: 'rangeslider-grabarea-max', - handleMaxClassName: 'rangeslider-handle-max', + 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(numClicks === 2) { + // 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, otherState; + var isIsolated = true; + for(i = 0; i < fullData.length; i++) { + isClicked = fullData[i] === fullTrace; + if(isClicked) continue; - maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', - maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', + isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - // style constants + if(!isInGroup && fullData[i].visible === true && !_$registry_248.traceIs(fullData[i], 'notLegendIsolatable')) { + isIsolated = false; + break; + } + } - maskColor: 'rgba(0,0,0,0.4)', - maskOppAxisColor: 'rgba(0,0,0,0.2)', + for(i = 0; i < fullData.length; i++) { + // False is sticky; we don't change it. + if(fullData[i].visible === false) continue; - slideBoxFill: 'transparent', - slideBoxCursor: 'ew-resize', + if(_$registry_248.traceIs(fullData[i], 'notLegendIsolatable')) { + continue; + } - grabAreaFill: 'transparent', - grabAreaCursor: 'col-resize', - grabAreaWidth: 10, + switch(fullTrace.visible) { + case 'legendonly': + setVisibility(fullData[i], true); + break; + case true: + otherState = isIsolated ? true : 'legendonly'; + isClicked = fullData[i] === fullTrace; + isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); + setVisibility(fullData[i], isInGroup ? true : otherState); + break; + } + } + } - handleWidth: 4, - handleRadius: 1, - handleStrokeWidth: 1, + for(i = 0; i < carrs.length; i++) { + kcont = carrs[i]; + if(!kcont) continue; + var update = kcont.constructUpdate(); - extraPad: 15 + 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_248.call('restyle', gd, attrUpdate, attrIndices); + } }; +var _$helpers_307 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46321,32 +47930,37 @@ var _$constants_121 = { 'use strict'; -var listAxes = _$axis_ids_210.list; -var __getAutoRange_120 = _$autorange_206.getAutoRange; -/* removed: var _$constants_121 = require('./constants'); */; - -var _$calcAutorange_120 = 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. +/* removed: var _$lib_166 = require('../../lib'); */; - for(var i = 0; i < axes.length; i++) { - var ax = axes[i], - opts = ax[_$constants_121.name]; +_$helpers_307.formatPiePercent = function formatPiePercent(v, separators) { + var vRounded = (v * 100).toPrecision(3); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_166.numSeparate(vRounded, separators) + '%'; +}; - // Don't try calling getAutoRange if _min and _max are filled in. - // This happens on updates where the calc step is skipped. +_$helpers_307.formatPieValue = function formatPieValue(v, separators) { + var vRounded = v.toPrecision(10); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_166.numSeparate(vRounded, separators); +}; - if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { - opts._input.autorange = true; - opts._input.range = opts.range = __getAutoRange_120(ax); - } +_$helpers_307.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) return v; } }; +_$helpers_307.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_307.getFirstFilled(item, indices); + else if(item) return item; +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46357,31 +47971,17 @@ var _$calcAutorange_120 = function calcAutorange(gd) { 'use strict'; -var _$oppaxis_attributes_125 = { - // not really a 'subplot' attribute container, - // but this is the flag we use to denote attributes that - // support yaxis, yaxis2, yaxis3, ... counters - _isSubplotObj: true, +/* removed: var _$color_46 = require('../../components/color'); */; +var castOption = _$helpers_307.castOption; - 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' +var _$styleOne_313 = function styleOne(s, pt, trace) { + var line = trace.marker.line; + var lineColor = castOption(line.color, pt.pts) || _$color_46.defaultLine; + var lineWidth = castOption(line.width, pt.pts) || 0; + + s.style({'stroke-width': lineWidth}) + .call(_$color_46.fill, pt.color) + .call(_$color_46.stroke, lineColor); }; /** @@ -46394,724 +47994,976 @@ var _$oppaxis_attributes_125 = { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$attributes_119 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_125 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_210 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$d3_10 = require('d3'); */; -var _$handleDefaults_122 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$color_46 = require('../color'); */; - // not super proud of this (maybe store _ in axis object instead - if(!_$lib_165.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; - } +/* removed: var _$subtypes_337 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_313 = require('../../traces/pie/style_one'); */; - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; +var _$style_107 = function style(s, gd) { + s.each(function(d) { + var traceGroup = _$d3_10.select(this); - function coerce(attr, dflt) { - return _$lib_165.coerce(containerIn, containerOut, _$attributes_119, attr, dflt); - } + var layers = _$lib_166.ensureSingle(traceGroup, 'g', 'layers'); + layers.style('opacity', d[0].trace.opacity); - function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_165.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_125, attr, dflt); + var fill = layers + .selectAll('g.legendfill') + .data([d]); + fill.enter().append('g') + .classed('legendfill', true); + + var line = layers + .selectAll('g.legendlines') + .data([d]); + line.enter().append('g') + .classed('legendlines', true); + + var symbol = layers + .selectAll('g.legendsymbols') + .data([d]); + symbol.enter().append('g') + .classed('legendsymbols', true); + + symbol.selectAll('g.legendpoints') + .data([d]) + .enter().append('g') + .classed('legendpoints', true); + }) + .each(styleBars) + .each(styleBoxes) + .each(stylePies) + .each(styleLines) + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); + + function styleLines(d) { + var trace = d[0].trace; + var showFill = trace.visible && trace.fill && trace.fill !== 'none'; + var showLine = _$subtypes_337.hasLines(trace); + var contours = trace.contours; + + if(contours && contours.type === 'constraint') { + showLine = contours.showlines; + showFill = contours._operation !== '='; + } + + var fill = _$d3_10.select(this).select('.legendfill').selectAll('path') + .data(showFill ? [d] : []); + fill.enter().append('path').classed('js-fill', true); + fill.exit().remove(); + fill.attr('d', 'M5,0h30v6h-30z') + .call(_$drawing_71.fillGroupStyle); + + var line = _$d3_10.select(this).select('.legendlines').selectAll('path') + .data(showLine ? [d] : []); + line.enter().append('path').classed('js-line', true) + .attr('d', 'M5,0h30'); + line.exit().remove(); + line.call(_$drawing_71.lineGroupStyle); } - var visible = coerce('visible'); - if(!visible) return; + function stylePoints(d) { + var d0 = d[0], + trace = d0.trace, + showMarkers = _$subtypes_337.hasMarkers(trace), + showText = _$subtypes_337.hasText(trace), + showLines = _$subtypes_337.hasLines(trace); - coerce('bgcolor', layoutOut.plot_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('thickness'); + var dMod, tMod; - axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); - coerce('range'); + // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; + // use d0.trace to infer arrayOk attributes - var subplots = layoutOut._subplots; - if(subplots) { - var yIds = subplots.cartesian - .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_210.name2id(axName); - }) - .map(function(subplotId) { - return subplotId.substr(subplotId.indexOf('y'), subplotId.length); - }); - var yNames = _$lib_165.simpleMap(yIds, _$axis_ids_210.id2name); - for(var i = 0; i < yNames.length; i++) { - var yName = yNames[i]; + function boundVal(attrIn, arrayToValFn, bounds) { + var valIn = _$lib_166.nestedProperty(trace, attrIn).get(), + valToBound = (Array.isArray(valIn) && arrayToValFn) ? + arrayToValFn(valIn) : valIn; - var rangeContainerIn = containerIn[yName] || {}; - var rangeContainerOut = containerOut[yName] = {}; + if(bounds) { + if(valToBound < bounds[0]) return bounds[0]; + else if(valToBound > bounds[1]) return bounds[1]; + } + return valToBound; + } - var yAxOut = layoutOut[yName]; + function pickFirst(array) { return array[0]; } - var rangemodeDflt; - if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { - rangemodeDflt = 'fixed'; + // constrain text, markers, etc so they'll fit on the legend + if(showMarkers || showText || showLines) { + var dEdit = {}, + tEdit = {}; + + if(showMarkers) { + dEdit.mc = boundVal('marker.color', pickFirst); + dEdit.mo = boundVal('marker.opacity', _$lib_166.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_166.mean, [2, 16]); + dEdit.mlc = boundVal('marker.line.color', pickFirst); + dEdit.mlw = boundVal('marker.line.width', _$lib_166.mean, [0, 5]); + tEdit.marker = { + sizeref: 1, + sizemin: 1, + sizemode: 'diameter' + }; } - var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); - if(rangeMode !== 'match') { - coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); + if(showLines) { + tEdit.line = { + width: boundVal('line.width', pickFirst, [0, 10]) + }; } - yAxOut._rangesliderAutorange = (rangeMode === 'auto'); - } - } - // to map back range slider (auto) range - containerOut._input = containerIn; -}; + if(showText) { + dEdit.tx = 'Aa'; + dEdit.tp = boundVal('textposition', pickFirst); + dEdit.ts = 10; + dEdit.tc = boundVal('textfont.color', pickFirst); + dEdit.tf = boundVal('textfont.family', pickFirst); + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + dMod = [_$lib_166.minExtend(d0, dEdit)]; + tMod = _$lib_166.minExtend(trace, tEdit); + } -'use strict'; + var ptgroup = _$d3_10.select(this).select('g.legendpoints'); -/* removed: var _$d3_10 = require('d3'); */; + var pts = ptgroup.selectAll('path.scatterpts') + .data(showMarkers ? dMod : []); + pts.enter().append('path').classed('scatterpts', true) + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.call(_$drawing_71.pointStyle, tMod, gd); -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; + // 'mrc' is set in pointStyle and used in textPointStyle: + // constrain it here + if(showMarkers) dMod[0].mrc = 3; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$titles_139 = require('../titles'); */; + var txt = ptgroup.selectAll('g.pointtext') + .data(showText ? dMod : []); + txt.enter() + .append('g').classed('pointtext', true) + .append('text').attr('transform', 'translate(20,0)'); + txt.exit().remove(); + txt.selectAll('text').call(_$drawing_71.textPointStyle, tMod, gd); + } -/* removed: var _$cartesian_218 = require('../../plots/cartesian'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; + function styleBars(d) { + var trace = d[0].trace, + marker = trace.marker || {}, + markerLine = marker.line || {}, + barpath = _$d3_10.select(this).select('g.legendpoints') + .selectAll('path.legendbar') + .data(_$registry_248.traceIs(trace, 'bar') ? [d] : []); + barpath.enter().append('path').classed('legendbar', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + barpath.exit().remove(); + barpath.each(function(d) { + var p = _$d3_10.select(this), + d0 = d[0], + w = (d0.mlw + 1 || markerLine.width + 1) - 1; -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$setCursor_184 = require('../../lib/setcursor'); */; + p.style('stroke-width', w + 'px') + .call(_$color_46.fill, d0.mc || marker.color); -/* removed: var _$constants_121 = require('./constants'); */; + if(w) { + p.call(_$color_46.stroke, d0.mlc || markerLine.color); + } + }); + } -var _$draw_123 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); + function styleBoxes(d) { + var trace = d[0].trace, + pts = _$d3_10.select(this).select('g.legendpoints') + .selectAll('path.legendbox') + .data(_$registry_248.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendbox', true) + // if we want the median bar, prepend M6,0H-6 + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.each(function() { + var w = trace.line.width, + p = _$d3_10.select(this); - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ + p.style('stroke-width', w + 'px') + .call(_$color_46.fill, trace.fillcolor); - function keyFunction(axisOpts) { - return axisOpts._name; + if(w) { + _$color_46.stroke(p, trace.line.color); + } + }); } - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_121.containerClassName) - .data(rangeSliderData, keyFunction); + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_10.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_10.select(this); - rangeSliders.enter().append('g') - .classed(_$constants_121.containerClassName, true) - .attr('pointer-events', 'all'); + p.style('stroke-width', w + 'px') + .call(_$color_46.fill, container.fillcolor); - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_10.select(this), - opts = axisOpts[_$constants_121.name]; + if(w) { + _$color_46.stroke(p, container.line.color); + } + }); + } - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_10.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_10.select(this); - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); + p.style('fill', 'none') + .call(_$drawing_71.dashLine, container.line.dash, w); - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; + if(w) { + _$color_46.stroke(p, container.line.color); + } + }); + } - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_10.select(this), - opts = axisOpts[_$constants_121.name], - oppAxisOpts = fullLayout[_$axes_207.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_207.id2name(axisOpts.anchor)]; + function stylePies(d) { + var trace = d[0].trace, + pts = _$d3_10.select(this).select('g.legendpoints') + .selectAll('path.legendpie') + .data(_$registry_248.traceIs(trace, 'pie') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendpie', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; + if(pts.size()) pts.call(_$styleOne_313, d[0], trace); + } +}; - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - axisOpts.cleanRange('rangeslider.range'); +'use strict'; +/* removed: var _$d3_10 = require('d3'); */; - // update range slider dimensions +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$handleClick_104 = require('./handle_click'); */; - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; +/* removed: var _$constants_100 = require('./constants'); */; +/* removed: var _$interactions_147 = require('../../constants/interactions'); */; +/* removed: var _$alignment_146 = require('../../constants/alignment'); */; +var __LINE_SPACING_102 = _$alignment_146.LINE_SPACING; +var __FROM_TL_102 = _$alignment_146.FROM_TL; +var FROM_BR = _$alignment_146.FROM_BR; - var oppBottom = Infinity; - var subplotData = _$axes_207.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_207.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); - } +/* removed: var _$getLegendData_103 = require('./get_legend_data'); */; +/* removed: var _$style_107 = require('./style'); */; +/* removed: var _$helpers_105 = require('./helpers'); */; +/* removed: var _$anchor_utils_98 = require('./anchor_utils'); */; - opts._id = _$constants_121.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; +var DBLCLICKDELAY = _$interactions_147.DBLCLICKDELAY; - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); +var _$draw_102 = function draw(gd) { + var fullLayout = gd._fullLayout; + var clipId = 'legend' + fullLayout._uid; - var x = Math.round(margin.l + (graphSize.w * domain[0])); + if(!fullLayout._infolayer || !gd.calcdata) return; - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_121.extraPad - ); + if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); + var opts = fullLayout.legend, + legendData = fullLayout.showlegend && _$getLegendData_103(gd.calcdata, opts), + hiddenSlices = fullLayout.hiddenlabels || []; - // update data <--> pixel coordinate conversion methods + if(!fullLayout.showlegend || !legendData.length) { + fullLayout._infolayer.selectAll('.legend').remove(); + fullLayout._topdefs.select('#' + clipId).remove(); - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; + _$plots_240.autoMargin(gd, 'legend'); + return; + } - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; + var firstRender = false; + var legend = _$lib_166.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; - }; + var clipPath = _$lib_166.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - opts._rl = [range0, range1]; + var bg = _$lib_166.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; + bg.call(_$color_46.stroke, opts.bordercolor) + .call(_$color_46.fill, opts.bgcolor) + .style('stroke-width', opts.borderwidth + 'px'); - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; - } + var scrollBox = _$lib_166.ensureSingle(legend, 'g', 'scrollbox'); - // update inner nodes + var scrollBar = _$lib_166.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ + rx: 20, + ry: 3, + width: 0, + height: 0 + }) + .call(_$color_46.fill, '#808BA4'); + }); - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); + var groups = scrollBox.selectAll('g.groups') + .data(legendData); - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); + groups.enter().append('g') + .attr('class', 'groups'); - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + groups.exit().remove(); - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_139.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' - } - }); - } + var traces = groups.selectAll('g.traces') + .data(_$lib_166.identity); - // update margins - _$plots_240.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_121.extraPad + opts._offsetShift * 2 + traces.enter().append('g').attr('class', 'traces'); + traces.exit().remove(); + + traces.call(_$style_107, gd) + .style('opacity', function(d) { + var trace = d[0].trace; + if(_$registry_248.traceIs(trace, 'pie')) { + return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; + } else { + return trace.visible === 'legendonly' ? 0.5 : 1; + } + }) + .each(function() { + _$d3_10.select(this) + .call(drawTexts, gd) + .call(setupTraceToggle, gd); }); - }); -}; -function makeRangeSliderData(fullLayout) { - var axes = _$axes_207.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_121.name, - out = []; + if(firstRender) { + computeLegendDimensions(gd, groups, traces); + expandMargin(gd); + } + + // Position and size the legend + var lxMin = 0, + lxMax = fullLayout.width, + lyMin = 0, + lyMax = fullLayout.height; + + computeLegendDimensions(gd, groups, traces); + + if(opts._height > lyMax) { + // If the legend doesn't fit in the plot area, + // do not expand the vertical margins. + expandHorizontalMargin(gd); + } else { + expandMargin(gd); + } - if(fullLayout._has('gl2d')) return out; + // Scroll section must be executed after repositionLegend. + // It requires the legend width, height, x and y to position the scrollbox + // and these values are mutated in repositionLegend. + var gs = fullLayout._size, + lx = gs.l + gs.w * opts.x, + ly = gs.t + gs.h * (1 - opts.y); - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; + if(_$anchor_utils_98.isRightAnchor(opts)) { + lx -= opts._width; + } + else if(_$anchor_utils_98.isCenterAnchor(opts)) { + lx -= opts._width / 2; + } - if(ax[name] && ax[name].visible) out.push(ax); + if(_$anchor_utils_98.isBottomAnchor(opts)) { + ly -= opts._height; + } + else if(_$anchor_utils_98.isMiddleAnchor(opts)) { + ly -= opts._height / 2; } - return out; -} + // Make sure the legend left and right sides are visible + var legendWidth = opts._width, + legendWidthMax = gs.w; -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_121.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_121.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_121.grabAreaMaxClassName).node(); + if(legendWidth > legendWidthMax) { + lx = gs.l; + legendWidth = legendWidthMax; + } + else { + if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; + if(lx < lxMin) lx = lxMin; + legendWidth = Math.min(lxMax - lx, opts._width); + } - rangeSlider.on('mousedown', function() { - var event = _$d3_10.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); + // Make sure the legend top and bottom are visible + // (legends with a scroll bar are not allowed to stretch beyond the extended + // margins) + var legendHeight = opts._height, + legendHeightMax = gs.h; - var dragCover = _$dragelement_68.coverSlip(); + if(legendHeight > legendHeightMax) { + ly = gs.t; + legendHeight = legendHeightMax; + } + else { + if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; + if(ly < lyMin) ly = lyMin; + legendHeight = Math.min(lyMax - ly, opts._height); + } - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); + // Set size and position of all the elements that make up a legend: + // legend, background and border, scroll box and scroll bar + _$drawing_71.setTranslate(legend, lx, ly); - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; + // to be safe, remove previous listeners + scrollBar.on('.drag', null); + legend.on('wheel', null); - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; + if(opts._height <= legendHeight || gd._context.staticPlot) { + // if scrollbar should not be shown. + bg.attr({ + width: legendWidth - opts.borderwidth, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; + _$drawing_71.setTranslate(scrollBox, 0, 0); - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; + clipPath.select('rect').attr({ + width: legendWidth - 2 * opts.borderwidth, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + }); - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } + _$drawing_71.setClipUrl(scrollBox, clipId); - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } + _$drawing_71.setRect(scrollBar, 0, 0, 0, 0); + delete opts._scrollY; + } + else { + var scrollBarHeight = Math.max(_$constants_100.scrollBarMinHeight, + legendHeight * legendHeight / opts._height); + var scrollBarYMax = legendHeight - + scrollBarHeight - + 2 * _$constants_100.scrollBarMargin; + var scrollBoxYMax = opts._height - legendHeight; + var scrollRatio = scrollBarYMax / scrollBoxYMax; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; + var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); - _$setCursor_184(_$d3_10.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); - } + // increase the background and clip-path width + // by the scrollbar width and margin + bg.attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_100.scrollBarWidth + + _$constants_100.scrollBarMargin, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_165.removeElement(dragCover); - } - }); -} + clipPath.select('rect').attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_100.scrollBarWidth + + _$constants_100.scrollBarMargin, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + scrollBoxY + }); -function setDataRange(rangeSlider, gd, axisOpts, opts) { + _$drawing_71.setClipUrl(scrollBox, clipId); - function clamp(v) { - return axisOpts.l2r(_$lib_165.constrain(v, opts._rl[0], opts._rl[1])); - } + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); + legend.on('wheel', function() { + scrollBoxY = _$lib_166.constrain( + opts._scrollY + + _$d3_10.event.deltaY / scrollBarYMax * scrollBoxYMax, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { + _$d3_10.event.preventDefault(); + } + }); - window.requestAnimationFrame(function() { - _$registry_247.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} + var eventY0, scrollBoxY0; -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_121.handleWidth / 2; + var drag = _$d3_10.behavior.drag() + .on('dragstart', function() { + eventY0 = _$d3_10.event.sourceEvent.clientY; + scrollBoxY0 = scrollBoxY; + }) + .on('drag', function() { + var e = _$d3_10.event.sourceEvent; + if(e.buttons === 2 || e.ctrlKey) return; - function clamp(v) { - return _$lib_165.constrain(v, 0, opts._width); - } + scrollBoxY = _$lib_166.constrain( + (e.clientY - eventY0) / scrollRatio + scrollBoxY0, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + }); - function clampOppAxis(v) { - return _$lib_165.constrain(v, 0, opts._height); + scrollBar.call(drag); } - function clampHandle(v) { - return _$lib_165.constrain(v, -hw2, opts._width + hw2); - } - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { + opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; + _$drawing_71.setTranslate(scrollBox, 0, -scrollBoxY); - rangeSlider.select('rect.' + _$constants_121.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); + _$drawing_71.setRect( + scrollBar, + legendWidth, + _$constants_100.scrollBarMargin + scrollBoxY * scrollRatio, + _$constants_100.scrollBarWidth, + scrollBarHeight + ); + clipPath.select('rect').attr({ + y: opts.borderwidth + scrollBoxY + }); + } - rangeSlider.select('rect.' + _$constants_121.maskMinClassName) - .attr('width', pixelMin); + if(gd._context.edits.legendPosition) { + var xf, yf, x0, y0; - rangeSlider.select('rect.' + _$constants_121.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + legend.classed('cursor-move', true); - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + _$dragelement_68.init({ + element: legend.node(), + gd: gd, + prepFn: function() { + var transform = _$drawing_71.getTranslate(legend); - rangeSlider.select('rect.' + _$constants_121.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + x0 = transform.x; + y0 = transform.y; + }, + moveFn: function(dx, dy) { + var newX = x0 + dx, + newY = y0 + dy; - rangeSlider.select('rect.' + _$constants_121.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); + _$drawing_71.setTranslate(legend, newX, newY); - rangeSlider.select('rect.' + _$constants_121.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); + xf = _$dragelement_68.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); + yf = _$dragelement_68.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); + }, + doneFn: function() { + if(xf !== undefined && yf !== undefined) { + _$registry_248.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + } + }, + clickFn: function(numClicks, e) { + var clickedTrace = + fullLayout._infolayer.selectAll('g.traces').filter(function() { + var bbox = this.getBoundingClientRect(); + return (e.clientX >= bbox.left && e.clientX <= bbox.right && + e.clientY >= bbox.top && e.clientY <= bbox.bottom); + }); + if(clickedTrace.size() > 0) { + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { + _$handleClick_104(clickedTrace, gd, numClicks); + }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + _$handleClick_104(clickedTrace, gd, numClicks); + } + } + } + }); } +}; - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; +function drawTexts(g, gd) { + var legendItem = g.data()[0][0], + fullLayout = gd._fullLayout, + trace = legendItem.trace, + isPie = _$registry_248.traceIs(trace, 'pie'), + traceIndex = trace.index, + name = isPie ? legendItem.label : trace.name; - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; + var text = _$lib_166.ensureSingle(g, 'text', 'legendtext'); - rangeSlider.select('g.' + _$constants_121.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + text.attr('text-anchor', 'start') + .classed('user-select-none', true) + .call(_$drawing_71.font, fullLayout.legend.font) + .text(name); - rangeSlider.select('g.' + _$constants_121.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} + function textLayout(s) { + _$svg_text_utils_187.convertToTspans(s, gd, function() { + computeTextDimensions(g, gd); + }); + } -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_121.bgClassName) - .data([0]); + if(gd._context.edits.legendText && !isPie) { + text.call(_$svg_text_utils_187.makeEditable, {gd: gd}) + .call(textLayout) + .on('edit', function(text) { + this.text(text) + .call(textLayout); - bg.enter().append('rect') - .classed(_$constants_121.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); + var origText = text; - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; + if(!this.text()) text = ' \u0020\u0020 '; - var offsetShift = -opts._offsetShift; - var lw = _$drawing_71.crispRound(gd, opts.borderwidth); + var fullInput = legendItem.trace._fullInput || {}; + var update = {}; - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} + if(_$registry_248.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_248.getTransformIndices(fullInput, 'groupby'); + var index = groupbyIndices[groupbyIndices.length - 1]; -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; + var kcont = _$lib_166.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); + if(origText === '') { + kcont.remove(legendItem.trace._group); + } else { + kcont.set(legendItem.trace._group, text); + } - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + update = kcont.constructUpdate(); + } else { + update.name = text; + } - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); + return _$registry_248.call('restyle', gd, update, traceIndex); + }); + } else { + textLayout(text); + } } -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_207.getSubplots(gd, axisOpts), - calcData = gd.calcdata; +function setupTraceToggle(g, gd) { + var newMouseDownTime, + numClicks = 1; - var rangePlots = rangeSlider.selectAll('g.' + _$constants_121.rangePlotClassName) - .data(subplotData, _$lib_165.identity); + var traceToggle = _$lib_166.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_46.fill, 'rgba(0,0,0,0)'); + }); - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_121.rangePlotClassName + ' ' + id; }) - .call(_$drawing_71.setClipUrl, opts._clipId); + traceToggle.on('mousedown', function() { + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { + // 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; - rangePlots.order(); + if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - rangePlots.exit().remove(); + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { _$handleClick_104(g, gd, numClicks); }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + gd._legendMouseDownTime = 0; + _$handleClick_104(g, gd, numClicks); + } + }); +} - var mainplotinfo; +function computeTextDimensions(g, gd) { + var legendItem = g.data()[0][0]; - rangePlots.each(function(id, i) { - var plotgroup = _$d3_10.select(this), - isMainPlot = (i === 0); + if(!legendItem.trace.showlegend) { + g.remove(); + return; + } - var oppAxisOpts = _$axes_207.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; + var mathjaxGroup = g.select('g[class*=math-group]'); + var mathjaxNode = mathjaxGroup.node(); + var opts = gd._fullLayout.legend; + var lineHeight = opts.font.size * __LINE_SPACING_102; + var height, width; - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + if(mathjaxNode) { + var mathjaxBB = _$drawing_71.bBox(mathjaxNode); - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; + height = mathjaxBB.height; + width = mathjaxBB.width; - _$plots_240.supplyDefaults(mockFigure); + _$drawing_71.setTranslate(mathjaxGroup, 0, (height / 4)); + } + else { + var text = g.select('.legendtext'); + var textLines = _$svg_text_utils_187.lineCount(text); + var textNode = text.node(); - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; + height = lineHeight * textLines; + width = textNode ? _$drawing_71.bBox(textNode).width : 0; - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya - }; + // approximation to height offset to center the font + // to avoid getBoundingClientRect + var textY = lineHeight * (0.3 + (1 - textLines) / 2); + // TODO: this 40 should go in a constants file (along with other + // values related to the legend symbol size) + _$svg_text_utils_187.positionText(text, 40, textY); + } - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; - } + height = Math.max(height, 16) + 3; - _$cartesian_218.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); + legendItem.height = height; + legendItem.width = width; } -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; +function computeLegendDimensions(gd, groups, traces) { + var fullLayout = gd._fullLayout; + var opts = fullLayout.legend; + var borderwidth = opts.borderwidth; + var isGrouped = _$helpers_105.isGrouped(opts); - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; + var extraWidth = 0; - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); + opts._width = 0; + opts._height = 0; + + if(_$helpers_105.isVertical(opts)) { + if(isGrouped) { + groups.each(function(d, i) { + _$drawing_71.setTranslate(this, 0, i * opts.tracegroupgap); + }); } - } - return out; -} + traces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height, + textWidth = legendItem.width; -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_121.maskMinClassName) - .data([0]); + _$drawing_71.setTranslate(this, + borderwidth, + (5 + borderwidth + opts._height + textHeight / 2)); - maskMin.enter().append('rect') - .classed(_$constants_121.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + opts._height += textHeight; + opts._width = Math.max(opts._width, textWidth); + }); - maskMin - .attr('height', opts._height) - .call(_$color_46.fill, _$constants_121.maskColor); + opts._width += 45 + borderwidth * 2; + opts._height += 10 + borderwidth * 2; - var maskMax = rangeSlider.selectAll('rect.' + _$constants_121.maskMaxClassName) - .data([0]); + if(isGrouped) { + opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; + } - maskMax.enter().append('rect') - .classed(_$constants_121.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + extraWidth = 40; + } + else if(isGrouped) { + var groupXOffsets = [opts._width], + groupData = groups.data(); - maskMax - .attr('height', opts._height) - .call(_$color_46.fill, _$constants_121.maskColor); + for(var i = 0, n = groupData.length; i < n; i++) { + var textWidths = groupData[i].map(function(legendItemArray) { + return legendItemArray[0].width; + }); - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_121.maskMinOppAxisClassName) - .data([0]); + var groupWidth = 40 + Math.max.apply(null, textWidths); - maskMinOppAxis.enter().append('rect') - .classed(_$constants_121.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + opts._width += opts.tracegroupgap + groupWidth; - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_46.fill, _$constants_121.maskOppAxisColor); + groupXOffsets.push(opts._width); + } - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_121.maskMaxOppAxisClassName) - .data([0]); + groups.each(function(d, i) { + _$drawing_71.setTranslate(this, groupXOffsets[i], 0); + }); - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_121.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + groups.each(function() { + var group = _$d3_10.select(this), + groupTraces = group.selectAll('g.traces'), + groupHeight = 0; - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_121.maskOppBorder) - .call(_$color_46.fill, _$constants_121.maskOppAxisColor); - } -} + groupTraces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height; -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; + _$drawing_71.setTranslate(this, + 0, + (5 + borderwidth + groupHeight + textHeight / 2)); - var slideBox = rangeSlider.selectAll('rect.' + _$constants_121.slideBoxClassName) - .data([0]); + groupHeight += textHeight; + }); - slideBox.enter().append('rect') - .classed(_$constants_121.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_121.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); + opts._height = Math.max(opts._height, groupHeight); + }); - slideBox.attr({ - height: opts._height, - fill: _$constants_121.slideBoxFill - }); -} + opts._height += 10 + borderwidth * 2; + opts._width += borderwidth * 2; + } + else { + var rowHeight = 0, + maxTraceHeight = 0, + maxTraceWidth = 0, + offsetX = 0, + fullTracesWidth = 0, + traceGap = opts.tracegroupgap || 5, + oneRowLegend; -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // calculate largest width for traces and use for width of all legend items + traces.each(function(d) { + maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); + fullTracesWidth += 40 + d[0].width + traceGap; + }); - // + // check if legend fits in one row + oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; + traces.each(function(d) { + var legendItem = d[0], + traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; - var grabberMin = rangeSlider.selectAll('g.' + _$constants_121.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_121.grabberMinClassName, true); + if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { + offsetX = 0; + rowHeight = rowHeight + maxTraceHeight; + opts._height = opts._height + maxTraceHeight; + // reset for next row + maxTraceHeight = 0; + } - var grabberMax = rangeSlider.selectAll('g.' + _$constants_121.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_121.grabberMaxClassName, true); + _$drawing_71.setTranslate(this, + (borderwidth + offsetX), + (5 + borderwidth + legendItem.height / 2) + rowHeight); - // + opts._width += traceGap + traceWidth; + opts._height = Math.max(opts._height, legendItem.height); - var handleFixAttrs = { - x: 0, - width: _$constants_121.handleWidth, - rx: _$constants_121.handleRadius, - fill: _$color_46.background, - stroke: _$color_46.defaultLine, - 'stroke-width': _$constants_121.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; + // keep track of tallest trace in group + offsetX += traceGap + traceWidth; + maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); + }); - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; + opts._width += borderwidth * 2; + opts._height += 10 + borderwidth * 2; - var handleMin = grabberMin.selectAll('rect.' + _$constants_121.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_121.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); + } - var handleMax = grabberMax.selectAll('rect.' + _$constants_121.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_121.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); + // make sure we're only getting full pixels + opts._width = Math.ceil(opts._width); + opts._height = Math.ceil(opts._height); - // + traces.each(function(d) { + var legendItem = d[0], + bg = _$d3_10.select(this).select('.legendtoggle'); - if(gd._context.staticPlot) return; + _$drawing_71.setRect(bg, + 0, + -legendItem.height / 2, + (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, + legendItem.height + ); + }); +} - var grabAreaFixAttrs = { - width: _$constants_121.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_121.grabAreaFill, - cursor: _$constants_121.grabAreaCursor - }; +function expandMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_121.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_121.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); + var xanchor = 'left'; + if(_$anchor_utils_98.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_98.isCenterAnchor(opts)) { + xanchor = 'center'; + } - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_121.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_121.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); -} + var yanchor = 'top'; + if(_$anchor_utils_98.isBottomAnchor(opts)) { + yanchor = 'bottom'; + } + else if(_$anchor_utils_98.isMiddleAnchor(opts)) { + yanchor = 'middle'; + } -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + // lastly check if the margin auto-expand has changed + _$plots_240.autoMargin(gd, 'legend', { + x: opts.x, + y: opts.y, + l: opts._width * (__FROM_TL_102[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: opts._height * (FROM_BR[yanchor]), + t: opts._height * (__FROM_TL_102[yanchor]) + }); +} - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; +function expandHorizontalMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - if(k.indexOf(_$constants_121.name) !== -1) { - _$plots_240.autoMargin(gd, k); - } + var xanchor = 'left'; + if(_$anchor_utils_98.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_98.isCenterAnchor(opts)) { + xanchor = 'center'; } + + // lastly check if the margin auto-expand has changed + _$plots_240.autoMargin(gd, 'legend', { + x: opts.x, + y: 0.5, + l: opts._width * (__FROM_TL_102[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: 0, + t: 0 + }); } /** @@ -47122,30 +48974,19 @@ function clearPushMargins(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$attributes_119 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_125 = require('./oppaxis_attributes'); */; -var _$rangeslider_124 = { +var _$legend_106 = { moduleType: 'component', - name: 'rangeslider', + name: 'legend', - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_165.extendFlat({}, _$attributes_119, { - yaxis: _$oppaxis_attributes_125 - }) - } - } - }, + layoutAttributes: _$attributes_99, + supplyLayoutDefaults: _$legendDefaults_101, - layoutAttributes: _$attributes_119, - handleDefaults: _$handleDefaults_122, - calcAutorange: _$calcAutorange_120, - draw: _$draw_123 + draw: _$draw_102, + style: _$style_107 }; /** @@ -47158,246 +48999,139 @@ var _$rangeslider_124 = { 'use strict'; -/* removed: var _$attributes_31 = require('../annotations/attributes'); */; -var scatterLineAttrs = _$attributes_317.line; -var __dash_126 = _$attributes_70.dash; -var __extendFlat_126 = _$extend_159.extendFlat; - -var _$attributes_126 = { - _isLinkedToArray: 'shape', - visible: { - valType: 'boolean', +var _$button_attributes_113 = { + step: { + valType: 'enumerated', - dflt: true, - editType: 'calcIfAutorange+arraydraw', + values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], + dflt: 'month', + editType: 'plot', }, - - type: { + stepmode: { valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], - editType: 'calcIfAutorange+arraydraw', + values: ['backward', 'todate'], + dflt: 'backward', + editType: 'plot', }, - - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', + count: { + valType: 'number', - editType: 'arraydraw', + min: 0, + dflt: 1, + editType: 'plot', }, - - xref: __extendFlat_126({}, _$attributes_31.xref, { - - }), - x0: { - valType: 'any', + label: { + valType: 'string', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - x1: { - valType: 'any', + editType: 'plot' +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_45 = require('../color/attributes'); */; +var __extendFlat_112 = _$extend_160.extendFlat; +/* removed: var _$button_attributes_113 = require('./button_attributes'); */; + +_$button_attributes_113 = __extendFlat_112(_$button_attributes_113, { + _isLinkedToArray: 'button', + + +}); + +var _$attributes_112 = { + visible: { + valType: 'boolean', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - yref: __extendFlat_126({}, _$attributes_31.yref, { + buttons: _$button_attributes_113, + + x: { + valType: 'number', + min: -2, + max: 3, - }), - y0: { - valType: 'any', + editType: 'plot', - editType: 'calcIfAutorange+arraydraw', + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + editType: 'plot', }, - y1: { - valType: 'any', + y: { + valType: 'number', + min: -2, + max: 3, - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - - path: { - valType: 'string', + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'bottom', - editType: 'calcIfAutorange+arraydraw', + editType: 'plot', }, - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, + font: _$font_attributes_234({ + editType: 'plot', - editType: 'arraydraw', + }), + + bgcolor: { + valType: 'color', + dflt: _$attributes_45.lightLine, - }, - line: { - color: __extendFlat_126({}, scatterLineAttrs.color, {editType: 'arraydraw'}), - width: __extendFlat_126({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_126({}, __dash_126, {editType: 'arraydraw'}), + editType: 'plot', - editType: 'calcIfAutorange+arraydraw' }, - fillcolor: { + activecolor: { valType: 'color', - dflt: 'rgba(0,0,0,0)', - editType: 'arraydraw', + editType: 'plot', }, - editType: 'arraydraw' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - - -var _$constants_128 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, - - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, - - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} + bordercolor: { + valType: 'color', + dflt: _$attributes_45.defaultLine, + + editType: 'plot', + }, - - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 - } -}; - -var _$helpers_131 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. - -_$helpers_131.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; - -_$helpers_131.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; - -_$helpers_131.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; - -_$helpers_131.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; - -_$helpers_131.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; - - if(axis) { - var d2r = _$helpers_131.shapePositionToRange(axis); - - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; - - if(axis.type === 'date') dataToPixel = _$helpers_131.decodeDate(dataToPixel); - } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; - } - else { - dataToPixel = function(v) { return gs.l + gs.w * v; }; - } - - return dataToPixel; -}; - -_$helpers_131.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; - - if(axis) { - var r2d = _$helpers_131.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; - } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; - } - else { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; - } - - return pixelToData; + borderwidth: { + valType: 'number', + min: 0, + dflt: 0, + + editType: 'plot', + + }, + editType: 'plot' }; /** @@ -47408,74 +49142,26 @@ _$helpers_131.getPixelToData = function(gd, axis, isVertical) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$constants_128 = require('./constants'); */; -/* removed: var _$helpers_131 = require('./helpers'); */; - -var _$calcAutorange_127 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_165.filterVisible(fullLayout.shapes); - - if(!shapeList.length || !gd._fullData.length) return; +var _$constants_114 = { - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; + // 'y' position pad above counter axis domain + yPad: 0.02, - var ax, bounds; + // minimum button width (regardless of text size) + minButtonWidth: 30, - if(shape.xref !== 'paper') { - ax = _$axes_207.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_128.paramIsX); - if(bounds) _$axes_207.expand(ax, bounds, {ppad: ppad}); - } + // buttons rect radii + rx: 3, + ry: 3, - if(shape.yref !== 'paper') { - ax = _$axes_207.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_128.paramIsY); - if(bounds) _$axes_207.expand(ax, bounds, {ppad: ppad}); - } - } + // light fraction used to compute the 'activecolor' default + lightAmount: 25, + darkAmount: 10 }; -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; - - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_128.segmentRE), - i, - segment, - drawnParam, - params, - val; - - if(ax.type === 'date') convertVal = _$helpers_131.decodeDate(convertVal); - - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; - - params = segments[i].substr(1).match(_$constants_128.paramRE); - if(!params || params.length < drawnParam) continue; - - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; - } - if(max >= min) return [min, max]; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -47484,119 +49170,95 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$attributes_126 = require('./attributes'); */; -/* removed: var _$helpers_131 = require('./helpers'); */; +/* removed: var _$attributes_112 = require('./attributes'); */; +/* removed: var _$button_attributes_113 = require('./button_attributes'); */; +/* removed: var _$constants_114 = require('./constants'); */; -var _$handleShapeDefaults_133 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; +var _$handleDefaults_115 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { + var selectorIn = containerIn.rangeselector || {}, + selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_165.coerce(shapeIn, shapeOut, _$attributes_126, attr, dflt); + return _$lib_166.coerce(selectorIn, selectorOut, _$attributes_112, attr, dflt); } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - - if(!visible) return shapeOut; - - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); + var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + var posDflt = getPosDflt(containerOut, layout, counterAxes); + coerce('x', posDflt[0]); + coerce('y', posDflt[1]); + _$lib_166.noneOrAll(containerIn, containerOut, ['x', 'y']); - // xref, yref - var axRef = _$axes_207.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + coerce('xanchor'); + coerce('yanchor'); - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + _$lib_166.coerceFont(coerce, 'font', layout.font); - if(axRef !== 'paper') { - ax = _$axes_207.getFromId(gdMock, axRef); - r2pos = _$helpers_131.rangeToShapePosition(ax); - pos2r = _$helpers_131.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_165.identity; - } + var bgColor = coerce('bgcolor'); + coerce('activecolor', _$color_46.contrast(bgColor, _$constants_114.lightAmount, _$constants_114.darkAmount)); + coerce('bordercolor'); + coerce('borderwidth'); +}; - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); +function buttonsDefaults(containerIn, containerOut, calendar) { + var buttonsIn = containerIn.buttons || [], + buttonsOut = containerOut.buttons = []; - // x0, x1 (and y0, y1) - _$axes_207.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_207.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + var buttonIn, buttonOut; - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; - } + function coerce(attr, dflt) { + return _$lib_166.coerce(buttonIn, buttonOut, _$button_attributes_113, attr, dflt); } - if(shapeType === 'path') { - coerce('path'); - } - else { - _$lib_165.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); - } + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; - return shapeOut; -}; + if(!_$lib_166.isPlainObject(buttonIn)) continue; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 step = coerce('step'); + if(step !== 'all') { + if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { + buttonOut.stepmode = 'backward'; + } + else { + coerce('stepmode'); + } + coerce('count'); + } -'use strict'; + coerce('label'); -/* removed: var _$handleArrayContainerDefaults_203 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_133 = require('./shape_defaults'); */; + buttonOut._index = i; + buttonsOut.push(buttonOut); + } + return buttonsOut; +} -var _$supplyLayoutDefaults_129 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_133 - }; +function getPosDflt(containerOut, layout, counterAxes) { + var anchoredList = counterAxes.filter(function(ax) { + return layout[ax].anchor === containerOut._id; + }); - _$handleArrayContainerDefaults_203(layoutIn, layoutOut, opts); -}; + var posY = 0; + for(var i = 0; i < anchoredList.length; i++) { + var domain = layout[anchoredList[i]].domain; + if(domain) posY = Math.max(domain[1], posY); + } + + return [containerOut.domain[0], posY + _$constants_114.yPad]; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -47609,487 +49271,306 @@ var _$supplyLayoutDefaults_129 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; - -/* removed: var _$dragelement_68 = require('../dragelement'); */; -/* removed: var _$setCursor_184 = require('../../lib/setcursor'); */; - -/* removed: var _$constants_128 = require('./constants'); */; -/* removed: var _$helpers_131 = require('./helpers'); */; - - -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one - -var _$draw_130 = { - draw: __draw_130, - drawOne: __drawOne_130 -}; - -function __draw_130(gd) { - var fullLayout = gd._fullLayout; - - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); - - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_130(gd, i); - } - } - - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); -} - -function __drawOne_130(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); - - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; +/* removed: var _$d3_10 = require('d3'); */; - // this shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; +var _$getUpdateObject_117 = function getUpdateObject(axisLayout, buttonLayout) { + var axName = axisLayout._name; + var update = {}; - if(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); + if(buttonLayout.step === 'all') { + update[axName + '.autorange'] = true; } else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } - } - - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; - - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_46.stroke, lineColor) - .call(_$color_46.fill, options.fillcolor) - .call(_$drawing_71.dashLine, options.line.dash, options.line.width); - - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - - path.call(_$drawing_71.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); + var xrange = getXRange(axisLayout, buttonLayout); - if(gd._context.edits.shapePosition) __setupDragElement_130(gd, path, options, index); + update[axName + '.range[0]'] = xrange[0]; + update[axName + '.range[1]'] = xrange[1]; } -} - -function __setupDragElement_130(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; - - var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; - var xa, ya, x2p, y2p, p2x, p2y; + return update; +}; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag - }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; +function getXRange(axisLayout, buttonLayout) { + var currentRange = axisLayout.range; + var base = new Date(axisLayout.r2l(currentRange[1])); - _$dragelement_68.init(dragOptions); + var step = buttonLayout.step, + count = buttonLayout.count; - shapePath.node().onmousemove = updateDragMode; + var range0; - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_68.getCursor(x / w, 1 - y / h) : - 'move'; + switch(buttonLayout.stepmode) { + case 'backward': + range0 = axisLayout.l2r(+_$d3_10.time[step].utc.offset(base, -count)); + break; - _$setCursor_184(shapePath, cursor); + case 'todate': + var base2 = _$d3_10.time[step].utc.offset(base, -count); - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; + range0 = axisLayout.l2r(+_$d3_10.time[step].utc.ceil(base2)); + break; } - function startDrag(evt) { - // setup conversion functions - xa = _$axes_207.getFromId(gd, shapeOptions.xref); - ya = _$axes_207.getFromId(gd, shapeOptions.yref); + var range1 = currentRange[1]; - x2p = _$helpers_131.getDataToPixel(gd, xa); - y2p = _$helpers_131.getDataToPixel(gd, ya, true); - p2x = _$helpers_131.getPixelToData(gd, xa); - p2y = _$helpers_131.getPixelToData(gd, ya, true); + return [range0, range1]; +} - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; - } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } +'use strict'; - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; - } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; - } +/* removed: var _$d3_10 = require('d3'); */; - update = {}; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_211 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$anchor_utils_98 = require('../legend/anchor_utils'); */; - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; - } +/* removed: var _$alignment_146 = require('../../constants/alignment'); */; +var __LINE_SPACING_116 = _$alignment_146.LINE_SPACING; +var __FROM_TL_116 = _$alignment_146.FROM_TL; +var __FROM_BR_116 = _$alignment_146.FROM_BR; - function endDrag() { - _$setCursor_184(shapePath); - _$registry_247.call('relayout', gd, update); - } +/* removed: var _$constants_114 = require('./constants'); */; +/* removed: var _$getUpdateObject_117 = require('./get_update_object'); */; - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_131.encodeDate(moveX); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_131.encodeDate(moveY); +var _$draw_116 = function draw(gd) { + var fullLayout = gd._fullLayout; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } + var selectors = fullLayout._infolayer.selectAll('.rangeselector') + .data(makeSelectorData(gd), selectorKeyFunc); - shapePath.attr('d', getPathString(gd, shapeOptions)); - } + selectors.enter().append('g') + .classed('rangeselector', true); - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_131.encodeDate(moveX); + selectors.exit().remove(); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_131.encodeDate(moveY); + selectors.style({ + cursor: 'pointer', + 'pointer-events': 'all' + }); - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; + selectors.each(function(d) { + var selector = _$d3_10.select(this), + axisLayout = d, + selectorLayout = axisLayout.rangeselector; - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + var buttons = selector.selectAll('g.button') + .data(selectorLayout.buttons); - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); - } - } + buttons.enter().append('g') + .classed('button', true); - shapePath.attr('d', getPathString(gd, shapeOptions)); - } -} + buttons.exit().remove(); -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_207.getFromId(gd, options.xref), - ya = _$axes_207.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; + buttons.each(function(d) { + var button = _$d3_10.select(this); + var update = _$getUpdateObject_117(axisLayout, d); - if(xa) { - x2r = _$helpers_131.shapePositionToRange(xa); - x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; - } - else { - x2p = function(v) { return gs.l + gs.w * v; }; - } + d._isActive = isActive(axisLayout, d, update); - if(ya) { - y2r = _$helpers_131.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + button.call(drawButtonRect, selectorLayout, d); + button.call(drawButtonText, selectorLayout, d, gd); - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_131.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_131.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); - } + button.on('click', function() { + if(gd._dragged) return; - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), - y1 = y2p(options.y1); + _$registry_248.call('relayout', gd, update); + }); - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; -} + button.on('mouseover', function() { + d._isHovered = true; + button.call(drawButtonRect, selectorLayout, d); + }); + button.on('mouseout', function() { + d._isHovered = false; + button.call(drawButtonRect, selectorLayout, d); + }); + }); -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_128.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_128.paramIsX[segmentType], - yParams = _$constants_128.paramIsY[segmentType], - nParams = _$constants_128.numParams[segmentType]; + reposition(gd, buttons, selectorLayout, axisLayout._name, selector); + }); - var paramString = segment.substr(1).replace(_$constants_128.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; +}; - if(paramNumber > nParams) param = 'X'; - return param; - }); +function makeSelectorData(gd) { + var axes = _$axis_ids_211.list(gd, 'x', true); + var data = []; - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_165.log('Ignoring extra params in segment ' + segment); + for(var i = 0; i < axes.length; i++) { + var axis = axes[i]; + + if(axis.rangeselector && axis.rangeselector.visible) { + data.push(axis); } + } - return segmentType + paramString; - }); + return data; } -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_128.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_128.paramIsX[segmentType], - yParams = _$constants_128.paramIsY[segmentType], - nParams = _$constants_128.numParams[segmentType]; - - var paramString = segment.substr(1).replace(_$constants_128.paramRE, function(param) { - if(paramNumber >= nParams) return param; +function selectorKeyFunc(d) { + return d._id; +} - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); +function isActive(axisLayout, opts, update) { + if(opts.step === 'all') { + return axisLayout.autorange === true; + } + else { + var keys = Object.keys(update); - paramNumber++; + return ( + axisLayout.range[0] === update[keys[0]] && + axisLayout.range[1] === update[keys[1]] + ); + } +} - return param; - }); +function drawButtonRect(button, selectorLayout, d) { + var rect = _$lib_166.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); - return segmentType + paramString; + rect.attr({ + 'rx': _$constants_114.rx, + 'ry': _$constants_114.ry }); -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + rect.call(_$color_46.stroke, selectorLayout.bordercolor) + .call(_$color_46.fill, getFillColor(selectorLayout, d)) + .style('stroke-width', selectorLayout.borderwidth + 'px'); +} +function getFillColor(selectorLayout, d) { + return (d._isActive || d._isHovered) ? + selectorLayout.activecolor : + selectorLayout.bgcolor; +} -'use strict'; +function drawButtonText(button, selectorLayout, d, gd) { + function textLayout(s) { + _$svg_text_utils_187.convertToTspans(s, gd); + } -/* removed: var _$draw_130 = require('./draw'); */; + var text = _$lib_166.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); -var _$shapes_132 = { - moduleType: 'component', - name: 'shapes', + text.call(_$drawing_71.font, selectorLayout.font) + .text(getLabel(d)) + .call(textLayout); +} - layoutAttributes: _$attributes_126, - supplyLayoutDefaults: _$supplyLayoutDefaults_129, - includeBasePlot: _$makeIncludeComponents_217('shapes'), +function getLabel(opts) { + if(opts.label) return opts.label; - calcAutorange: _$calcAutorange_127, - draw: _$draw_130.draw, - drawOne: _$draw_130.drawOne -}; + if(opts.step === 'all') return 'all'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 opts.count + opts.step.charAt(0); +} +function reposition(gd, buttons, opts, axName, selector) { + var width = 0; + var height = 0; -'use strict'; + var borderWidth = opts.borderwidth; + buttons.each(function() { + var button = _$d3_10.select(this); + var text = button.select('.selector-text'); -var _$constants_135 = { + var tHeight = opts.font.size * __LINE_SPACING_116; + var hEff = Math.max(tHeight * _$svg_text_utils_187.lineCount(text), 16) + 3; - // layout attribute name - name: 'sliders', + height = Math.max(height, hEff); + }); - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', + buttons.each(function() { + var button = _$d3_10.select(this); + var rect = button.select('.selector-rect'); + var text = button.select('.selector-text'); - railHeight: 5, + var tWidth = text.node() && _$drawing_71.bBox(text.node()).width; + var tHeight = opts.font.size * __LINE_SPACING_116; + var tLines = _$svg_text_utils_187.lineCount(text); - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', + var wEff = Math.max(tWidth + 10, _$constants_114.minButtonWidth); - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', + // TODO add MathJax support - // min item width / height - minWidth: 30, - minHeight: 30, + // TODO add buttongap attribute - // padding around item text - textPadX: 40, + button.attr('transform', 'translate(' + + (borderWidth + width) + ',' + borderWidth + + ')'); - // arrow offset off right edge - arrowOffsetX: 4, + rect.attr({ + x: 0, + y: 0, + width: wEff, + height: height + }); - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', + _$svg_text_utils_187.positionText(text, wEff / 2, + height / 2 - ((tLines - 1) * tHeight / 2) + 3); - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, + width += wEff + 5; + }); - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, + var graphSize = gd._fullLayout._size; + var lx = graphSize.l + graphSize.w * opts.x; + var ly = graphSize.t + graphSize.h * (1 - opts.y); - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', + var xanchor = 'left'; + if(_$anchor_utils_98.isRightAnchor(opts)) { + lx -= width; + xanchor = 'right'; + } + if(_$anchor_utils_98.isCenterAnchor(opts)) { + lx -= width / 2; + xanchor = 'center'; + } - labelPadding: 8, - labelOffset: 0, + var yanchor = 'top'; + if(_$anchor_utils_98.isBottomAnchor(opts)) { + ly -= height; + yanchor = 'bottom'; + } + if(_$anchor_utils_98.isMiddleAnchor(opts)) { + ly -= height / 2; + yanchor = 'middle'; + } - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, + width = Math.ceil(width); + height = Math.ceil(height); + lx = Math.round(lx); + ly = Math.round(ly); - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, + _$plots_240.autoMargin(gd, axName + '-range-selector', { + x: opts.x, + y: opts.y, + l: width * __FROM_TL_116[xanchor], + r: width * __FROM_BR_116[xanchor], + b: height * __FROM_BR_116[yanchor], + t: height * __FROM_TL_116[yanchor] + }); - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; + selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -48101,39 +49582,20 @@ var _$constants_135 = { 'use strict'; -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_239 = { - t: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - r: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - b: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - l: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - +var _$rangeselector_118 = { + moduleType: 'component', + name: 'rangeselector', + + schema: { + subplots: { + xaxis: {rangeselector: _$attributes_112} + } }, - editType: 'arraydraw' + + layoutAttributes: _$attributes_112, + handleDefaults: _$handleDefaults_115, + + draw: _$draw_116 }; /** @@ -48146,234 +49608,123 @@ var _$pad_attributes_239 = { 'use strict'; -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_239 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_134 = _$extend_159.extendDeepAll; -var __overrideAll_134 = _$edit_types_192.overrideAll; -/* removed: var _$animation_attributes_202 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_135 = require('./constants'); */; - -var stepsAttrs = { - _isLinkedToArray: 'step', +/* removed: var _$attributes_45 = require('../color/attributes'); */; - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', +var _$attributes_119 = { + bgcolor: { + valType: 'color', + dflt: _$attributes_45.background, - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], + editType: 'plot', }, - label: { - valType: 'string', + bordercolor: { + valType: 'color', + dflt: _$attributes_45.defaultLine, + editType: 'plot', }, - value: { - valType: 'string', + borderwidth: { + valType: 'integer', + dflt: 0, + min: 0, + editType: 'plot', }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; - -var _$attributes_134 = __overrideAll_134({ - _isLinkedToArray: 'slider', - - visible: { + autorange: { valType: 'boolean', - dflt: true, - }, - - active: { - valType: 'number', - - min: 0, - dflt: 0, + editType: 'calc', + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - - steps: stepsAttrs, - - lenmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], + range: { + valType: 'info_array', - dflt: 'fraction', + items: [ + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} + ], + editType: 'calc', + impliedEdits: {'autorange': false}, }, - len: { + thickness: { valType: 'number', + dflt: 0.15, min: 0, - dflt: 1, - - - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, - - - }, - pad: __extendDeepAll_134({}, _$pad_attributes_239, { - - }, {t: {dflt: 20}}), - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, + max: 1, + editType: 'plot', }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', + visible: { + valType: 'boolean', + dflt: true, + editType: 'calc', }, + editType: 'calc' +}; - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_202.transition.easing.values, - - dflt: 'cubic-in-out', - - } - }, - - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, - - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, - - offset: { - valType: 'number', - dflt: 10, - - - }, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - prefix: { - valType: 'string', - - - }, +'use strict'; - suffix: { - valType: 'string', - - - }, +var _$constants_121 = { - font: _$font_attributes_234({ - - }) - }, + // attribute container name + name: 'rangeslider', - font: _$font_attributes_234({ - - }), + // class names - activebgcolor: { - valType: 'color', - - dflt: _$constants_135.gripBgActiveColor, - - }, - bgcolor: { - valType: 'color', - - dflt: _$constants_135.railBgColor, - - }, - bordercolor: { - valType: 'color', - dflt: _$constants_135.railBorderColor, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: _$constants_135.railBorderWidth, - - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_135.tickLength, - - - }, - tickcolor: { - valType: 'color', - dflt: _$constants_135.tickColor, - - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - - }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_135.minorTickLength, - - - } -}, 'arraydraw', 'from-root'); + containerClassName: 'rangeslider-container', + bgClassName: 'rangeslider-bg', + rangePlotClassName: 'rangeslider-rangeplot', + + maskMinClassName: 'rangeslider-mask-min', + maskMaxClassName: 'rangeslider-mask-max', + slideBoxClassName: 'rangeslider-slidebox', + + grabberMinClassName: 'rangeslider-grabber-min', + grabAreaMinClassName: 'rangeslider-grabarea-min', + handleMinClassName: 'rangeslider-handle-min', + + grabberMaxClassName: 'rangeslider-grabber-max', + grabAreaMaxClassName: 'rangeslider-grabarea-max', + handleMaxClassName: 'rangeslider-handle-max', + + maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', + maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', + + // style constants + + maskColor: 'rgba(0,0,0,0.4)', + maskOppAxisColor: 'rgba(0,0,0,0.2)', + + slideBoxFill: 'transparent', + slideBoxCursor: 'ew-resize', + + grabAreaFill: 'transparent', + grabAreaCursor: 'col-resize', + grabAreaWidth: 10, + + handleWidth: 4, + handleRadius: 1, + handleStrokeWidth: 1, + + extraPad: 15 +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -48385,109 +49736,151 @@ var _$attributes_134 = __overrideAll_134({ 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_203 = require('../../plots/array_container_defaults'); */; +var listAxes = _$axis_ids_211.list; +var __getAutoRange_120 = _$autorange_207.getAutoRange; +/* removed: var _$constants_121 = require('./constants'); */; -/* removed: var _$attributes_134 = require('./attributes'); */; -/* removed: var _$constants_135 = require('./constants'); */; +var _$calcAutorange_120 = function calcAutorange(gd) { + var axes = listAxes(gd, 'x', true); -var __name_136 = _$constants_135.name; -var stepAttrs = _$attributes_134.steps; + // 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], + opts = ax[_$constants_121.name]; -var _$slidersDefaults_136 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_136, - handleItemDefaults: sliderDefaults - }; + // Don't try calling getAutoRange if _min and _max are filled in. + // This happens on updates where the calc step is skipped. - _$handleArrayContainerDefaults_203(layoutIn, layoutOut, opts); + if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { + opts._input.autorange = true; + opts._input.range = opts.range = __getAutoRange_120(ax); + } + } }; -function sliderDefaults(sliderIn, sliderOut, layoutOut) { +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function coerce(attr, dflt) { - return _$lib_165.coerce(sliderIn, sliderOut, _$attributes_134, attr, dflt); - } +'use strict'; - var steps = stepsDefaults(sliderIn, sliderOut); +var _$oppaxis_attributes_125 = { + // not really a 'subplot' attribute container, + // but this is the flag we use to denote attributes that + // support yaxis, yaxis2, yaxis3, ... counters + _isSubplotObj: true, - var visible = coerce('visible', steps.length > 0); - if(!visible) return; + 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' +}; - coerce('active'); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('x'); - coerce('y'); - _$lib_165.noneOrAll(sliderIn, sliderOut, ['x', 'y']); +'use strict'; - coerce('xanchor'); - coerce('yanchor'); +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$attributes_119 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_125 = require('./oppaxis_attributes'); */; +/* removed: var _$axis_ids_211 = require('../../plots/cartesian/axis_ids'); */; - coerce('len'); - coerce('lenmode'); +var _$handleDefaults_122 = function handleDefaults(layoutIn, layoutOut, axName) { + var axIn = layoutIn[axName]; + var axOut = layoutOut[axName]; - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; - _$lib_165.coerceFont(coerce, 'font', layoutOut.font); + // not super proud of this (maybe store _ in axis object instead + if(!_$lib_166.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; + } - var currentValueIsVisible = coerce('currentvalue.visible'); + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; - if(currentValueIsVisible) { - coerce('currentvalue.xanchor'); - coerce('currentvalue.prefix'); - coerce('currentvalue.suffix'); - coerce('currentvalue.offset'); + function coerce(attr, dflt) { + return _$lib_166.coerce(containerIn, containerOut, _$attributes_119, attr, dflt); + } - _$lib_165.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { + return _$lib_166.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_125, attr, dflt); } - coerce('transition.duration'); - coerce('transition.easing'); + var visible = coerce('visible'); + if(!visible) return; - coerce('bgcolor'); - coerce('activebgcolor'); + coerce('bgcolor', layoutOut.plot_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - coerce('ticklen'); - coerce('tickwidth'); - coerce('tickcolor'); - coerce('minorticklen'); -} + coerce('thickness'); -function stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; + axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); + coerce('range'); - var valueIn, valueOut; + var subplots = layoutOut._subplots; + if(subplots) { + var yIds = subplots.cartesian + .filter(function(subplotId) { + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_211.name2id(axName); + }) + .map(function(subplotId) { + return subplotId.substr(subplotId.indexOf('y'), subplotId.length); + }); + var yNames = _$lib_166.simpleMap(yIds, _$axis_ids_211.id2name); + for(var i = 0; i < yNames.length; i++) { + var yName = yNames[i]; - function coerce(attr, dflt) { - return _$lib_165.coerce(valueIn, valueOut, stepAttrs, attr, dflt); - } + var rangeContainerIn = containerIn[yName] || {}; + var rangeContainerOut = containerOut[yName] = {}; - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; + var yAxOut = layoutOut[yName]; - coerce('method'); + var rangemodeDflt; + if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { + rangemodeDflt = 'fixed'; + } - if(!_$lib_165.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; + var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); + if(rangeMode !== 'match') { + coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); + } + yAxOut._rangesliderAutorange = (rangeMode === 'auto'); } - - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); - - valuesOut.push(valueOut); } - return valuesOut; -} + // to map back range slider (auto) range + containerOut._input = containerIn; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -48497,624 +49890,611 @@ function stepsDefaults(sliderIn, sliderOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$registry_248 = require('../../registry'); */; /* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_98 = require('../legend/anchor_utils'); */; - -/* removed: var _$constants_135 = require('./constants'); */; -/* removed: var _$alignment_146 = require('../../constants/alignment'); */; -var __LINE_SPACING_137 = _$alignment_146.LINE_SPACING; -var __FROM_TL_137 = _$alignment_146.FROM_TL; -var __FROM_BR_137 = _$alignment_146.FROM_BR; - - -var _$draw_137 = function draw(gd) { - var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); - - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_135.containerClassName) - .data(sliderData.length > 0 ? [0] : []); - - sliders.enter().append('g') - .classed(_$constants_135.containerClassName, true) - .style('cursor', 'ew-resize'); - - sliders.exit().remove(); - - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_137(gd); - // Return early if no menus visible: - if(sliderData.length === 0) return; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$titles_139 = require('../titles'); */; - var sliderGroups = sliders.selectAll('g.' + _$constants_135.groupClassName) - .data(sliderData, keyFunction); +/* removed: var _$cartesian_219 = require('../../plots/cartesian'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; - sliderGroups.enter().append('g') - .classed(_$constants_135.groupClassName, true); +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; - sliderGroups.exit().each(function(sliderOpts) { - _$d3_10.select(this).remove(); +/* removed: var _$constants_121 = require('./constants'); */; - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; +var _$draw_123 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); - _$plots_240.autoMargin(gd, _$constants_135.autoMarginIdRoot + sliderOpts._index); - }); + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); + function keyFunction(axisOpts) { + return axisOpts._name; } - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; - - var gSlider = _$d3_10.select(this); - - computeLabelSteps(sliderOpts); - - _$plots_240.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_121.containerClassName) + .data(rangeSliderData, keyFunction); - if(opts.active === data.index) return; - if(opts._dragging) return; + rangeSliders.enter().append('g') + .classed(_$constants_121.containerClassName, true) + .attr('pointer-events', 'all'); - setActive(gd, gSlider, opts, data.index, false, true); - }); + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_10.select(this), + opts = axisOpts[_$constants_121.name]; - drawSlider(gd, _$d3_10.select(this), sliderOpts); + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); }); -}; -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_135.name], - sliderData = []; + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); - } + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; - return sliderData; -} + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_10.select(this), + opts = axisOpts[_$constants_121.name], + oppAxisOpts = fullLayout[_$axes_208.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_208.id2name(axisOpts.anchor)]; -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; -} + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_71.tester.selectAll('g.' + _$constants_135.labelGroupClass) - .data(sliderOpts.steps); + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); + } - sliderLabels.enter().append('g') - .classed(_$constants_135.labelGroupClass, true); + axisOpts.cleanRange('rangeslider.range'); - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_10.select(this); - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + // update range slider dimensions - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_71.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; + + var oppBottom = Infinity; + var subplotData = _$axes_208.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_208.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - }); - sliderLabels.remove(); + opts._id = _$constants_121.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; - var dims = sliderOpts._dims = {}; + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); - dims.inputAreaWidth = Math.max( - _$constants_135.railWidth, - _$constants_135.gripHeight - ); + var x = Math.round(margin.l + (graphSize.w * domain[0])); - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_121.extraPad + ); - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; - } + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + // update data <--> pixel coordinate conversion methods - var textableInputLength = dims.inputAreaLength - 2 * _$constants_135.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_135.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_71.tester.append('g'); + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_71.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_186.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); + opts._rl = [range0, range1]; - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; - dummyGroup.remove(); - } + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; + } - dims.height = dims.currentValueTotalHeight + _$constants_135.tickOffset + sliderOpts.ticklen + _$constants_135.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + // update inner nodes - var xanchor = 'left'; - if(_$anchor_utils_98.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_98.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); - var yanchor = 'top'; - if(_$anchor_utils_98.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_98.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; - } + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - _$plots_240.autoMargin(gd, _$constants_135.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_137[xanchor], - r: dims.outerLength * __FROM_BR_137[xanchor], - b: dims.height * __FROM_BR_137[yanchor], - t: dims.height * __FROM_TL_137[yanchor] - }); -} + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_139.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); + } -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; - } + // update margins + _$plots_240.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_121.extraPad + opts._offsetShift * 2 + }); + }); +}; - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); +function makeRangeSliderData(fullLayout) { + var axes = _$axes_208.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_121.name, + out = []; - var dims = sliderOpts._dims; + if(fullLayout._has('gl2d')) return out; - // Position the rectangle: - _$drawing_71.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); + if(ax[name] && ax[name].visible) out.push(ax); + } + return out; } -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_121.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_121.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_121.grabAreaMaxClassName).node(); - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; + rangeSlider.on('mousedown', function() { + var event = _$d3_10.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_135.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; - break; - default: - x0 = _$constants_135.currentValueInset; - textAnchor = 'left'; - } + var dragCover = _$dragelement_68.coverSlip(); - text.enter().append('text') - .classed(_$constants_135.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; - } + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; - text.call(_$drawing_71.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_186.convertToTspans, sliderOpts._gd); + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; - var lines = _$svg_text_utils_186.lineCount(text); + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_137; + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - _$svg_text_utils_186.positionText(text, x0, y0); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - return text; + _$setCursor_185(_$d3_10.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); + } + + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_166.removeElement(dragCover); + } + }); } -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_135.gripRectClass) - .data([0]); +function setDataRange(rangeSlider, gd, axisOpts, opts) { - grip.enter().append('rect') - .classed(_$constants_135.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + function clamp(v) { + return axisOpts.l2r(_$lib_166.constrain(v, opts._rl[0], opts._rl[1])); + } - grip.attr({ - width: _$constants_135.gripWidth, - height: _$constants_135.gripHeight, - rx: _$constants_135.gripRadius, - ry: _$constants_135.gripRadius, - }) - .call(_$color_46.stroke, sliderOpts.bordercolor) - .call(_$color_46.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); + + window.requestAnimationFrame(function() { + _$registry_248.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); } -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_121.handleWidth / 2; - text.enter().append('text') - .classed(_$constants_135.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); + function clamp(v) { + return _$lib_166.constrain(v, 0, opts._width); + } - text.call(_$drawing_71.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_186.convertToTspans, sliderOpts._gd); + function clampOppAxis(v) { + return _$lib_166.constrain(v, 0, opts._height); + } - return text; -} + function clampHandle(v) { + return _$lib_166.constrain(v, -hw2, opts._width + hw2); + } -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_135.labelsClass) - .data([0]); - var dims = sliderOpts._dims; + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); - labels.enter().append('g') - .classed(_$constants_135.labelsClass, true); + rangeSlider.select('rect.' + _$constants_121.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); - var labelItems = labels.selectAll('g.' + _$constants_135.labelGroupClass) - .data(dims.labelSteps); + rangeSlider.select('rect.' + _$constants_121.maskMinClassName) + .attr('width', pixelMin); - labelItems.enter().append('g') - .classed(_$constants_135.labelGroupClass, true); + rangeSlider.select('rect.' + _$constants_121.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - labelItems.exit().remove(); + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - labelItems.each(function(d) { - var item = _$d3_10.select(this); + rangeSlider.select('rect.' + _$constants_121.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - item.call(drawLabel, d, sliderOpts); + rangeSlider.select('rect.' + _$constants_121.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - _$drawing_71.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_135.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_137 + - _$constants_135.labelOffset + - dims.currentValueTotalHeight - ); - }); + rangeSlider.select('rect.' + _$constants_121.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); + } -} + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); - } + rangeSlider.select('g.' + _$constants_121.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + + rangeSlider.select('g.' + _$constants_121.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); } -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_166.ensureSingle(rangeSlider, 'rect', _$constants_121.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var step = sliderOpts.steps[sliderOpts.active]; + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + var offsetShift = -opts._offsetShift; + var lw = _$drawing_71.crispRound(gd, opts.borderwidth); - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw }); +} - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; - if(_step.execute) { - _$plots_240.executeAPICommand(gd, _step.method, _step.args); - } + var clipPath = _$lib_166.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); - } - } + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); } -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_10.select(gd); - - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; - } +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_208.getSubplots(gd, axisOpts), + calcData = gd.calcdata; - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); + var rangePlots = rangeSlider.selectAll('g.' + _$constants_121.rangePlotClassName) + .data(subplotData, _$lib_166.identity); - var grip = sliderGroup.select('.' + _$constants_135.gripRectClass); + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_121.rangePlotClassName + ' ' + id; }) + .call(_$drawing_71.setClipUrl, opts._clipId); - _$d3_10.event.stopPropagation(); - _$d3_10.event.preventDefault(); - grip.call(_$color_46.fill, sliderOpts.activebgcolor); + rangePlots.order(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_10.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; + rangePlots.exit().remove(); - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_10.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + var mainplotinfo; - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_46.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + rangePlots.each(function(id, i) { + var plotgroup = _$d3_10.select(this), + isMainPlot = (i === 0); - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); -} + var oppAxisOpts = _$axes_208.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_135.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; - tick.enter().append('rect') - .classed(_$constants_135.tickRectClass, true); + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; - tick.exit().remove(); + _$plots_240.supplyDefaults(mockFigure); - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' - }); + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_10.select(this); + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_46.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + if(isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; + } - _$drawing_71.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_135.tickOffset : _$constants_135.minorTickOffset) + dims.currentValueTotalHeight - ); + _$cartesian_219.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); }); - } -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; + + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } } + + return out; } -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_135.gripRectClass); +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_166.ensureSingle(rangeSlider, 'rect', _$constants_121.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var x = normalizedValueToPosition(sliderOpts, position); + maskMin + .attr('height', opts._height) + .call(_$color_46.fill, _$constants_121.maskColor); - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; + var maskMax = _$lib_166.ensureSingle(rangeSlider, 'rect', _$constants_121.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); - } + maskMax + .attr('height', opts._height) + .call(_$color_46.fill, _$constants_121.maskColor); - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_135.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); -} + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_166.ensureSingle(rangeSlider, 'rect', _$constants_121.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_135.stepInset + - (dims.inputAreaLength - 2 * _$constants_135.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_46.fill, _$constants_121.maskOppAxisColor); -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_135.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_135.stepInset - 2 * dims.inputAreaStart))); -} + var maskMaxOppAxis = _$lib_166.ensureSingle(rangeSlider, 'rect', _$constants_121.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_135.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_121.maskOppBorder) + .call(_$color_46.fill, _$constants_121.maskOppAxisColor); + } +} - rect.enter().append('rect') - .classed(_$constants_135.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_135.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_46.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + var slideBox = _$lib_166.ensureSingle(rangeSlider, 'rect', _$constants_121.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_121.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); - _$drawing_71.setTranslate(rect, 0, dims.currentValueTotalHeight); + slideBox.attr({ + height: opts._height, + fill: _$constants_121.slideBoxFill + }); } -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_135.railRectClass) - .data([0]); - var dims = sliderOpts._dims; +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_166.ensureSingle(rangeSlider, 'g', _$constants_121.grabberMinClassName); + var grabberMax = _$lib_166.ensureSingle(rangeSlider, 'g', _$constants_121.grabberMaxClassName); + + // + var handleFixAttrs = { + x: 0, + width: _$constants_121.handleWidth, + rx: _$constants_121.handleRadius, + fill: _$color_46.background, + stroke: _$color_46.defaultLine, + 'stroke-width': _$constants_121.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_166.ensureSingle(grabberMin, 'rect', _$constants_121.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMin.attr(handleDynamicAttrs); + + var handleMax = _$lib_166.ensureSingle(grabberMax, 'rect', _$constants_121.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); - rect.enter().append('rect') - .classed(_$constants_135.railRectClass, true); + // + if(gd._context.staticPlot) return; - var computedLength = dims.inputAreaLength - _$constants_135.railInset * 2; + var grabAreaFixAttrs = { + width: _$constants_121.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_121.grabAreaFill, + cursor: _$constants_121.grabAreaCursor + }; - rect.attr({ - width: computedLength, - height: _$constants_135.railWidth, - rx: _$constants_135.railRadius, - ry: _$constants_135.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_46.stroke, sliderOpts.bordercolor) - .call(_$color_46.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + var grabAreaMin = _$lib_166.ensureSingle(grabberMin, 'rect', _$constants_121.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMin.attr('height', opts._height); - _$drawing_71.setTranslate(rect, - _$constants_135.railInset, - (dims.inputAreaWidth - _$constants_135.railWidth) * 0.5 + dims.currentValueTotalHeight - ); + var grabAreaMax = _$lib_166.ensureSingle(grabberMax, 'rect', _$constants_121.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMax.attr('height', opts._height); } -function __clearPushMargins_137(gd) { +function clearPushMargins(gd) { var pushMargins = gd._fullLayout._pushmargin || {}, keys = Object.keys(pushMargins); for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_135.autoMarginIdRoot) !== -1) { + if(k.indexOf(_$constants_121.name) !== -1) { _$plots_240.autoMargin(gd, k); } } @@ -49130,16 +50510,28 @@ function __clearPushMargins_137(gd) { 'use strict'; -/* removed: var _$constants_135 = require('./constants'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$attributes_119 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_125 = require('./oppaxis_attributes'); */; -var _$sliders_138 = { +var _$rangeslider_124 = { moduleType: 'component', - name: _$constants_135.name, + name: 'rangeslider', - layoutAttributes: _$attributes_134, - supplyLayoutDefaults: _$slidersDefaults_136, + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_166.extendFlat({}, _$attributes_119, { + yaxis: _$oppaxis_attributes_125 + }) + } + } + }, - draw: _$draw_137 + layoutAttributes: _$attributes_119, + handleDefaults: _$handleDefaults_122, + calcAutorange: _$calcAutorange_120, + draw: _$draw_123 }; /** @@ -49152,149 +50544,131 @@ var _$sliders_138 = { 'use strict'; -/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_45 = require('../color/attributes'); */; -var __extendFlat_140 = _$extend_159.extendFlat; -var __overrideAll_140 = _$edit_types_192.overrideAll; -/* removed: var _$pad_attributes_239 = require('../../plots/pad_attributes'); */; - -var buttonsAttrs = { - _isLinkedToArray: 'button', - - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} - ], - - }, - label: { - valType: 'string', - - dflt: '', - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; +/* removed: var _$attributes_31 = require('../annotations/attributes'); */; +var scatterLineAttrs = _$attributes_315.line; +var __dash_126 = _$attributes_70.dash; +var __extendFlat_126 = _$extend_160.extendFlat; -var _$attributes_140 = __overrideAll_140({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], +var _$attributes_126 = { + _isLinkedToArray: 'shape', visible: { valType: 'boolean', + dflt: true, + editType: 'calcIfAutorange+arraydraw', }, type: { valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', + values: ['circle', 'rect', 'path', 'line'], + editType: 'calcIfAutorange+arraydraw', }, - direction: { + layer: { valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', + values: ['below', 'above'], + dflt: 'above', + editType: 'arraydraw', }, - active: { - valType: 'integer', + xref: __extendFlat_126({}, _$attributes_31.xref, { - min: -1, - dflt: 0, + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', }, - - showactive: { - valType: 'boolean', + xanchor: { + valType: 'any', - dflt: true, + editType: 'calcIfAutorange+arraydraw', }, - - buttons: buttonsAttrs, - - x: { - valType: 'number', - min: -2, - max: 3, - dflt: -0.05, + x0: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'right', + x1: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, + + yref: __extendFlat_126({}, _$attributes_31.yref, { + }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', }, yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - - pad: __extendFlat_140({}, _$pad_attributes_239, { + y0: { + valType: 'any', - }), - - font: _$font_attributes_234({ + editType: 'calcIfAutorange+arraydraw', - }), - - bgcolor: { - valType: 'color', + }, + y1: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_45.borderLine, + + path: { + valType: 'string', + editType: 'calcIfAutorange+arraydraw', }, - borderwidth: { + + opacity: { valType: 'number', min: 0, + max: 1, dflt: 1, editType: 'arraydraw', - } -}, 'arraydraw', 'from-root'); + }, + line: { + color: __extendFlat_126({}, scatterLineAttrs.color, {editType: 'arraydraw'}), + width: __extendFlat_126({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_126({}, __dash_126, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -49308,74 +50682,58 @@ var _$attributes_140 = __overrideAll_140({ 'use strict'; -var _$constants_141 = { - - // 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, +var _$constants_128 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, - // color given to active buttons - activeColor: '#F4FAFF', + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - // color given to hovered buttons - hoverColor: '#F4FAFF', + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, - // symbol for menu open arrow - arrowSymbol: { - left: '◄', - right: '►', - up: '▲', - down: '▼' + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 } }; +var _$helpers_131 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49384,561 +50742,326 @@ var _$constants_141 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_203 = require('../../plots/array_container_defaults'); */; +'use strict'; -/* removed: var _$attributes_140 = require('./attributes'); */; -/* removed: var _$constants_141 = require('./constants'); */; +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. -var __name_142 = _$constants_141.name; -var __buttonAttrs_142 = _$attributes_140.buttons; +_$helpers_131.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; +}; +_$helpers_131.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; +}; -var _$updateMenusDefaults_142 = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_142, - handleItemDefaults: menuDefaults +_$helpers_131.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); }; - - _$handleArrayContainerDefaults_203(layoutIn, layoutOut, opts); }; -function menuDefaults(menuIn, menuOut, layoutOut) { - - function coerce(attr, dflt) { - return _$lib_165.coerce(menuIn, menuOut, _$attributes_140, attr, dflt); - } - - var buttons = __buttonsDefaults_142(menuIn, menuOut); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - - coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); - - coerce('x'); - coerce('y'); - _$lib_165.noneOrAll(menuIn, menuOut, ['x', 'y']); - - coerce('xanchor'); - coerce('yanchor'); - - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); - - _$lib_165.coerceFont(coerce, 'font', layoutOut.font); - - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); -} - -function __buttonsDefaults_142(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; - - var buttonIn, buttonOut; - - function coerce(attr, dflt) { - return _$lib_165.coerce(buttonIn, buttonOut, __buttonAttrs_142, attr, dflt); - } - - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; +_$helpers_131.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; +}; - coerce('method'); +_$helpers_131.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; - if(!_$lib_165.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { - continue; - } + if(axis) { + var d2r = _$helpers_131.shapePositionToRange(axis); - coerce('args'); - coerce('label'); - coerce('execute'); + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; - buttonOut._index = i; - buttonsOut.push(buttonOut); + if(axis.type === 'date') dataToPixel = _$helpers_131.decodeDate(dataToPixel); } - - return buttonsOut; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$ScrollBox_145 = ScrollBox; - -/* removed: var _$d3_10 = require('d3'); */; - -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; - -/* removed: var _$lib_165 = require('../../lib'); */; - -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; - - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection - - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); - - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); - - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} - -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; - -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; - - // compute position of scrollbox - this.position = position; - - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; - - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + } + else { + dataToPixel = function(v) { return gs.l + gs.w * v; }; } - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; + return dataToPixel; +}; - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } +_$helpers_131.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; + + if(axis) { + var r2d = _$helpers_131.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; } else { - boxT = t; - boxB = boxT + boxH; - - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; - } + pixelToData = function(p) { return (p - gs.l) / gs.w; }; } - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; + return pixelToData; +}; - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); +'use strict'; - hbar.exit() - .on('.drag', null) - .remove(); +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_46.fill, ScrollBox.barColor); +/* removed: var _$constants_128 = require('./constants'); */; +/* removed: var _$helpers_131 = require('./helpers'); */; - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH - }); - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } +var _$calcAutorange_127 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + shapeList = _$lib_166.filterVisible(fullLayout.shapes); - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; + if(!shapeList.length || !gd._fullData.length) return; - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); + var ax, bounds; - vbar.exit() - .on('.drag', null) - .remove(); + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_208.getFromId(gd, shape.xref); - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_46.fill, ScrollBox.barColor); + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_128.paramIsX); - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH - }); + if(bounds) _$axes_208.expand(ax, bounds, calcXPaddingOptions(shape)); + } - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_208.getFromId(gd, shape.yref); + + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_128.paramIsY); + if(bounds) _$axes_208.expand(ax, bounds, calcYPaddingOptions(shape)); + } } +}; - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} - clipPath.exit().remove(); +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_128.paramIsY : _$constants_128.paramIsX) : + [v0, v1]; + var maxValue = _$lib_166.aggNums(Math.max, null, coords), + minValue = _$lib_166.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} - this.container.call(_$drawing_71.setClipUrl, clipId); +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } - else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_71.setClipUrl, null); - delete this._clipRect; - } + var segments = path.match(_$constants_128.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_10.behavior.drag() - .on('dragstart', function() { - _$d3_10.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + var params = segment.substr(1).match(_$constants_128.paramRE); + if(!params || params.length < relevantParamIdx) return; - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + extractedCoordinates.push(params[relevantParamIdx]); + }); - var onBarDrag = _$d3_10.behavior.drag() - .on('dragstart', function() { - _$d3_10.event.sourceEvent.preventDefault(); - _$d3_10.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + return extractedCoordinates; +} - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); - } +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); - } - } + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_128.segmentRE), + i, + segment, + drawnParam, + params, + val; -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_71.setClipUrl, null); - delete this._clipRect; - } + if(ax.type === 'date') convertVal = _$helpers_131.decodeDate(convertVal); - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; + params = segments[i].substr(1).match(_$constants_128.paramRE); + if(!params || params.length < drawnParam) continue; + + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; } -}; + if(max >= min) return [min, max]; +} /** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(this.hbar) { - translateX -= _$d3_10.event.dx; - } - if(this.vbar) { - translateY -= _$d3_10.event.dy; - } +'use strict'; - this.setTranslate(translateX, translateY); -}; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; +/* removed: var _$attributes_126 = require('./attributes'); */; +/* removed: var _$helpers_131 = require('./helpers'); */; - if(this.hbar) { - translateX += _$d3_10.event.deltaY; - } - if(this.vbar) { - translateY += _$d3_10.event.deltaY; +var _$handleShapeDefaults_133 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; + + function coerce(attr, dflt) { + return _$lib_166.coerce(shapeIn, shapeOut, _$attributes_126, attr, dflt); } - this.setTranslate(translateX, translateY); -}; + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); -/** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + if(!visible) return shapeOut; - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_165.constrain(_$d3_10.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - var translateXMax = this.position.w - this._box.w; + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); - translateX = xf * translateXMax; - } + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_165.constrain(_$d3_10.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); + // xref, yref + var axRef = _$axes_208.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - var translateYMax = this.position.h - this._box.h; + if(axRef !== 'paper') { + ax = _$axes_208.getFromId(gdMock, axRef); + r2pos = _$helpers_131.rangeToShapePosition(ax); + pos2r = _$helpers_131.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_166.identity; + } - translateY = yf * translateYMax; - } + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; - this.setTranslate(translateX, translateY); -}; + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); -/** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_208.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_208.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } - translateX = _$lib_165.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_165.constrain(translateY || 0, 0, translateYMax); + // hack part 2 + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } - this.translateX = translateX; - this.translateY = translateY; + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); - this.container.call(_$drawing_71.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); + _$axes_208.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) - }); + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; + } } - if(this.hbar) { - var xf = translateX / translateXMax; - - this.hbar.call(_$drawing_71.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); + if(shapeType === 'path') { + coerce('path'); } - - if(this.vbar) { - var yf = translateY / translateYMax; - - this.vbar.call(_$drawing_71.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); + else { + _$lib_166.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); } + + return shapeOut; }; /** @@ -49952,736 +51075,996 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$handleArrayContainerDefaults_204 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_133 = require('./shape_defaults'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$color_46 = require('../color'); */; -/* removed: var _$drawing_71 = require('../drawing'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_98 = require('../legend/anchor_utils'); */; -var __LINE_SPACING_143 = _$alignment_146.LINE_SPACING; +var _$supplyLayoutDefaults_129 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_133 + }; -/* removed: var _$constants_141 = require('./constants'); */; -/* removed: var _$ScrollBox_145 = require('./scrollbox'); */; + _$handleArrayContainerDefaults_204(layoutIn, layoutOut, opts); +}; -var _$draw_143 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_141.containerClassName) - .data(menuData.length > 0 ? [0] : []); +'use strict'; - menus.enter().append('g') - .classed(_$constants_141.containerClassName, true) - .style('cursor', 'pointer'); +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; - menus.exit().remove(); +/* removed: var _$dragelement_68 = require('../dragelement'); */; +/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; - // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_143(gd); +/* removed: var _$constants_128 = require('./constants'); */; +/* removed: var _$helpers_131 = require('./helpers'); */; - // return early if no update menus are visible - if(menuData.length === 0) return; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_141.headerGroupClassName) - .data(menuData, __keyFunction_143); +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - headerGroups.enter().append('g') - .classed(_$constants_141.headerGroupClassName, true); +var _$draw_130 = { + draw: __draw_130, + drawOne: __drawOne_130 +}; - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_141.dropdownButtonGroupClassName) - .data([0]); +function __draw_130(gd) { + var fullLayout = gd._fullLayout; - gButton.enter().append('g') - .classed(_$constants_141.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_143(gd, menuOpts); + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); } - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_145(gd, gButton, scrollBoxId); + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_130(gd, i); + } + } - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); +} - gButton - .call(removeAllButtons) - .attr(_$constants_141.menuIndexAttrName, '-1'); - } +function __drawOne_130(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - headerGroups.exit().each(function(menuOpts) { - _$d3_10.select(this).remove(); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; - gButton - .call(removeAllButtons) - .attr(_$constants_141.menuIndexAttrName, '-1'); + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; - _$plots_240.autoMargin(gd, _$constants_141.autoMarginIdRoot + menuOpts._index); - }); + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); + } + } - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_10.select(this); + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_240.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_143(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); - }); + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_46.stroke, lineColor) + .call(_$color_46.fill, options.fillcolor) + .call(_$drawing_71.dashLine, options.line.dash, options.line.width); - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - // if this menu is active, update the dropdown container - if(__isActive_143(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); - } + path.call(_$drawing_71.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null + ); - }); -}; + if(gd._context.edits.shapePosition) __setupDragElement_130(gd, path, options, index); + } +} -/** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_141.name]; - var menuData = []; +function __setupDragElement_130(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; - if(item.visible) menuData.push(item); - } + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; - return menuData; -} + var xa, ya, x2p, y2p, p2x, p2y; -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_143(menuOpts) { - return menuOpts._index; -} + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; -function isFolded(gButton) { - return +gButton.attr(_$constants_141.menuIndexAttrName) === -1; -} + _$dragelement_68.init(dragOptions); -function __isActive_143(gButton, menuOpts) { - return +gButton.attr(_$constants_141.menuIndexAttrName) === menuOpts._index; -} + shapePath.node().onmousemove = updateDragMode; -function __setActive_143(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; + function updateDragMode(evt) { + // element might not be on screen at time of setup, + // so obtain bounding box here + var dragBBox = dragOptions.element.getBoundingClientRect(); - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_141.menuIndexAttrName, '-1'); + // choose 'move' or 'resize' + // based on initial position of cursor within the drag element + var w = dragBBox.right - dragBBox.left, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_68.getCursor(x / w, 1 - y / h) : + 'move'; - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + _$setCursor_185(shapePath, cursor); - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; } -} -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_141.headerClassName) - .data([0]); - var dims = menuOpts._dims; + function startDrag(evt) { + // setup conversion functions + xa = _$axes_208.getFromId(gd, shapeOptions.xref); + ya = _$axes_208.getFromId(gd, shapeOptions.yref); - header.enter().append('g') - .classed(_$constants_141.headerClassName, true) - .style('pointer-events', 'all'); + x2p = _$helpers_131.getDataToPixel(gd, xa); + y2p = _$helpers_131.getDataToPixel(gd, ya, true); + p2x = _$helpers_131.getPixelToData(gd, xa); + p2y = _$helpers_131.getPixelToData(gd, ya, true); - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_141.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_141.headerArrowClassName) - .data([0]); + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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); - arrow.enter().append('text') - .classed(_$constants_141.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_71.font, menuOpts.font) - .text(_$constants_141.arrowSymbol[menuOpts.direction]); + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; + } - arrow.attr({ - x: dims.headerWidth - _$constants_141.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_141.textOffsetY + menuOpts.pad.t - }); + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.x0'; optE = 'x0'; + } - header.on('click', function() { - gButton.call(removeAllButtons); + // 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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + } + update = {}; - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_141.menuIndexAttrName, - __isActive_143(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; + } - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - }); + function endDrag() { + _$setCursor_185(shapePath); + _$registry_248.call('relayout', gd, update); + } - header.on('mouseover', function() { - header.call(styleOnMouseOver); - }); + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_131.encodeDate(moveX); + } - // translate header group - _$drawing_71.setTranslate(gHeader, dims.lx, dims.ly); -} + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_131.encodeDate(moveY); + } -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var klass = menuOpts.type === 'dropdown' ? _$constants_141.dropdownButtonClassName : _$constants_141.buttonClassName; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_131.encodeDate(moveX); + } - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_131.encodeDate(moveY); + } - var enter = buttons.enter().append('g') - .classed(klass, true); + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; - var exit = buttons.exit(); + // 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; - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + // 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); + shapePath.attr('d', getPathString(gd, shapeOptions)); } +} - var x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_208.getFromId(gd, options.xref), + ya = _$axes_208.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + if(xa) { + x2r = _$helpers_131.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; + } + else { + x2p = function(v) { return gs.l + gs.w * v; }; + } - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_141.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_141.gapButtonHeader; - } + if(ya) { + y2r = _$helpers_131.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(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_141.gapButtonHeader + _$constants_141.gapButton - dims.openHeight; + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_131.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_131.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_141.gapButtonHeader + _$constants_141.gapButton - dims.openWidth; + 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); } - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_141.gapButton, - xPad: _$constants_141.gapButton, - index: 0, - }; + 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); + } - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; +} - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_10.select(this); - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; - button.on('click', function() { - // skip `dragend` events - if(_$d3_10.event.defaultPrevented) return; - __setActive_143(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + return pathIn.replace(_$constants_128.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_128.paramIsX[segmentType], + yParams = _$constants_128.paramIsY[segmentType], + nParams = _$constants_128.numParams[segmentType]; - if(buttonOpts.execute) { - _$plots_240.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + var paramString = segment.substr(1).replace(_$constants_128.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++; - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + if(paramNumber > nParams) param = 'X'; + return param; }); - button.on('mouseover', function() { - button.call(styleOnMouseOver); - }); + if(paramNumber > nParams) { + paramString = paramString.replace(/[\s,]*X.*/, ''); + _$lib_166.log('Ignoring extra params in segment ' + segment); + } - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); + return segmentType + paramString; }); +} - buttons.call(styleButtons, menuOpts); +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_128.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_128.paramIsX[segmentType], + yParams = _$constants_128.paramIsY[segmentType], + nParams = _$constants_128.numParams[segmentType]; - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); - } + var paramString = segment.substr(1).replace(_$constants_128.paramRE, function(param) { + if(paramNumber >= nParams) return param; - scrollBoxPosition.direction = menuOpts.direction; + if(xParams[paramNumber]) param = moveX(param); + else if(yParams[paramNumber]) param = moveY(param); - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); - } - } + paramNumber++; + + return param; + }); + + return segmentType + paramString; + }); } -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_141.gapButton; - } - } - else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_141.gapButton; - } - } - scrollBox.enable(position, translateX, translateY); +'use strict'; - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } +/* removed: var _$draw_130 = require('./draw'); */; + +var _$shapes_132 = { + moduleType: 'component', + name: 'shapes', + + layoutAttributes: _$attributes_126, + supplyLayoutDefaults: _$supplyLayoutDefaults_129, + includeBasePlot: _$makeIncludeComponents_218('shapes'), + + calcAutorange: _$calcAutorange_127, + draw: _$draw_130.draw, + drawOne: _$draw_130.drawOne +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } -} -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; +var _$constants_135 = { - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } + // layout attribute name + name: 'sliders', - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); - } -} + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); -} + railHeight: 5, -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', - rect.enter().append('rect') - .classed(_$constants_141.itemRectClassName, true) - .attr({ - rx: _$constants_141.rx, - ry: _$constants_141.ry, - 'shape-rendering': 'crispEdges' - }); + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', - rect.call(_$color_46.stroke, menuOpts.bordercolor) - .call(_$color_46.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); -} + // min item width / height + minWidth: 30, + minHeight: 30, -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); + // padding around item text + textPadX: 40, - text.enter().append('text') - .classed(_$constants_141.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + // arrow offset off right edge + arrowOffsetX: 4, - text.call(_$drawing_71.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_186.convertToTspans, gd); -} + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, - buttons.each(function(buttonOpts, i) { - var button = _$d3_10.select(this); + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_141.itemRectClassName) - .call(_$color_46.fill, _$constants_141.activeColor); - } - }); -} + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_141.itemRectClassName) - .call(_$color_46.fill, _$constants_141.hoverColor); -} + labelPadding: 8, + labelOffset: 0, -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_141.itemRectClassName) - .call(_$color_46.fill, menuOpts.bgcolor); -} + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, -// find item dimensions (this mutates menuOpts) -function __findDimensions_143(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, - var fakeButtons = _$drawing_71.tester.selectAll('g.' + _$constants_141.dropdownButtonClassName) - .data(menuOpts.buttons); + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, +}; - fakeButtons.enter().append('g') - .classed(_$constants_141.dropdownButtonClassName, true); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +'use strict'; - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_10.select(this); +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_239 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; - button.call(drawItem, menuOpts, buttonOpts, gd); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 text = button.select('.' + _$constants_141.itemTextClassName); +'use strict'; - // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_71.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_141.textPadX, _$constants_141.minWidth); +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_239 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_134 = _$extend_160.extendDeepAll; +var __overrideAll_134 = _$edit_types_193.overrideAll; +/* removed: var _$animation_attributes_203 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_135 = require('./constants'); */; - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_143; - var tLines = _$svg_text_utils_186.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_141.minHeight) + _$constants_141.textOffsetY; +var stepsAttrs = { + _isLinkedToArray: 'step', - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } + ], + + }, + label: { + valType: 'string', + + + }, + value: { + valType: 'string', + + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; +var _$attributes_134 = __overrideAll_134({ + _isLinkedToArray: 'slider', - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); + visible: { + valType: 'boolean', + + dflt: true, + + }, - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_141.gapButton; - dims.openHeight += hEff + _$constants_141.gapButton; - } else { - dims.totalWidth += wEff + _$constants_141.gapButton; - dims.openWidth += wEff + _$constants_141.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; + active: { + valType: 'number', + + min: 0, + dflt: 0, + + }, + + steps: stepsAttrs, + + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], + + dflt: 'fraction', + + }, + len: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + pad: __extendDeepAll_134({}, _$pad_attributes_239, { + + }, {t: {dflt: 20}}), + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, + + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_203.transition.easing.values, + + dflt: 'cubic-in-out', + } - }); + }, - if(isVertical) { - dims.totalHeight -= _$constants_141.gapButton; - } else { - dims.totalWidth -= _$constants_141.gapButton; - } + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, - dims.headerWidth = dims.width1 + _$constants_141.arrowPadX; - dims.headerHeight = dims.height1; + offset: { + valType: 'number', + dflt: 10, + + + }, - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_141.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_141.arrowPadX; - } + prefix: { + valType: 'string', + + + }, - fakeButtons.remove(); + suffix: { + valType: 'string', + + + }, - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; + font: _$font_attributes_234({ + + }) + }, - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); + font: _$font_attributes_234({ + + }), - var xanchor = 'left'; - if(_$anchor_utils_98.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = 'right'; - } - if(_$anchor_utils_98.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = 'center'; + activebgcolor: { + valType: 'color', + + dflt: _$constants_135.gripBgActiveColor, + + }, + bgcolor: { + valType: 'color', + + dflt: _$constants_135.railBgColor, + + }, + bordercolor: { + valType: 'color', + dflt: _$constants_135.railBorderColor, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_135.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_135.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_135.tickColor, + + + }, + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_135.minorTickLength, + + } +}, 'arraydraw', 'from-root'); - var yanchor = 'top'; - if(_$anchor_utils_98.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = 'bottom'; - } - if(_$anchor_utils_98.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = 'middle'; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); +'use strict'; - _$plots_240.autoMargin(gd, _$constants_141.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); -} +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_204 = require('../../plots/array_container_defaults'); */; -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_141.itemRectClassName); - var text = item.select('.' + _$constants_141.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; +/* removed: var _$attributes_134 = require('./attributes'); */; +/* removed: var _$constants_135 = require('./constants'); */; - _$drawing_71.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); +var __name_136 = _$constants_135.name; +var stepAttrs = _$attributes_134.steps; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight - }); +var _$slidersDefaults_136 = function slidersDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_136, + handleItemDefaults: sliderDefaults + }; - var tHeight = menuOpts.font.size * __LINE_SPACING_143; - var tLines = _$svg_text_utils_186.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); + _$handleArrayContainerDefaults_204(layoutIn, layoutOut, opts); +}; - _$svg_text_utils_186.positionText(text, _$constants_141.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_141.textOffsetY); +function sliderDefaults(sliderIn, sliderOut, layoutOut) { - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; + function coerce(attr, dflt) { + return _$lib_166.coerce(sliderIn, sliderOut, _$attributes_134, attr, dflt); } - posOpts.index++; -} + var steps = stepsDefaults(sliderIn, sliderOut); -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_141.dropdownButtonClassName).remove(); -} + var visible = coerce('visible', steps.length > 0); + if(!visible) return; -function __clearPushMargins_143(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); + coerce('active'); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + coerce('x'); + coerce('y'); + _$lib_166.noneOrAll(sliderIn, sliderOut, ['x', 'y']); - if(k.indexOf(_$constants_141.autoMarginIdRoot) !== -1) { - _$plots_240.autoMargin(gd, k); - } - } -} + coerce('xanchor'); + coerce('yanchor'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + coerce('len'); + coerce('lenmode'); -'use strict'; + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); -/* removed: var _$constants_141 = require('./constants'); */; + _$lib_166.coerceFont(coerce, 'font', layoutOut.font); -var _$updatemenus_144 = { - moduleType: 'component', - name: _$constants_141.name, + var currentValueIsVisible = coerce('currentvalue.visible'); - layoutAttributes: _$attributes_140, - supplyLayoutDefaults: _$updateMenusDefaults_142, + if(currentValueIsVisible) { + coerce('currentvalue.xanchor'); + coerce('currentvalue.prefix'); + coerce('currentvalue.suffix'); + coerce('currentvalue.offset'); - draw: _$draw_143 -}; + _$lib_166.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + } -var _$mathjax_config_152 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + coerce('transition.duration'); + coerce('transition.easing'); -'use strict'; + coerce('bgcolor'); + coerce('activebgcolor'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('ticklen'); + coerce('tickwidth'); + coerce('tickcolor'); + coerce('minorticklen'); +} -/* global MathJax:false */ +function stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; -/** - * Check and configure MathJax - */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_152.MathJax = true; + var valueIn, valueOut; - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] + function coerce(attr, dflt) { + return _$lib_166.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + } + + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; + + coerce('method'); + + if(!_$lib_166.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + continue; } - }); - MathJax.Hub.Configured(); -} else { - _$mathjax_config_152.MathJax = false; + coerce('args'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); + coerce('execute'); + + valuesOut.push(valueOut); + } + + return valuesOut; } /** @@ -50692,893 +52075,784 @@ if(typeof MathJax !== 'undefined') { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_165 = require('../lib'); */; -/* removed: var _$plot_config_197 = require('../plot_api/plot_config'); */; +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_98 = require('../legend/anchor_utils'); */; -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; +/* removed: var _$constants_135 = require('./constants'); */; +/* removed: var _$alignment_146 = require('../../constants/alignment'); */; +var __LINE_SPACING_137 = _$alignment_146.LINE_SPACING; +var __FROM_TL_137 = _$alignment_146.FROM_TL; +var __FROM_BR_137 = _$alignment_146.FROM_BR; - for(var i = 0; i < args.length; i++) { - arg = args[i]; +var _$draw_137 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_165.extendDeep([], arg) : - _$lib_165.extendDeepAll({}, arg); - } - else copy[i] = arg; - } + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_135.containerClassName) + .data(sliderData.length > 0 ? [0] : []); - return copy; -} + sliders.enter().append('g') + .classed(_$constants_135.containerClassName, true) + .style('cursor', 'ew-resize'); + sliders.exit().remove(); -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_137(gd); + // Return early if no menus visible: + if(sliderData.length === 0) return; -var __queue_179 = {}; + var sliderGroups = sliders.selectAll('g.' + _$constants_135.groupClassName) + .data(sliderData, keyFunction); -// TODO: disable/enable undo and redo buttons appropriately + sliderGroups.enter().append('g') + .classed(_$constants_135.groupClassName, true); -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_179.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + sliderGroups.exit().each(function(sliderOpts) { + _$d3_10.select(this).remove(); - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } + _$plots_240.autoMargin(gd, _$constants_135.autoMarginIdRoot + sliderOpts._index); + }); - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); } - gd.undoQueue.beginSequence = false; - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); - } + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; - if(gd.undoQueue.queue.length > _$plot_config_197.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; - } -}; + var gSlider = _$d3_10.select(this); -/** - * Begin a sequence of undoQueue changes - * - * @param gd - */ -__queue_179.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; + computeLabelSteps(sliderOpts); -/** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended - * - * @param gd - */ -__queue_179.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; -}; + _$plots_240.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; -/** - * Move one step back in the undo queue, and undo the object there. - * - * @param gd - */ -__queue_179.undo = function undo(gd) { - var queueObj, i; + if(opts.active === data.index) return; + if(opts._dragging) return; - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; - } + setActive(gd, gSlider, opts, data.index, false, true); + }); - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; + drawSlider(gd, _$d3_10.select(this), sliderOpts); + }); +}; - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_135.name], + sliderData = []; - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_179.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; -/** - * Redo the current object in the undo, then move forward in the queue. - * - * @param gd - */ -__queue_179.redo = function redo(gd) { - var queueObj, i; + return sliderData; +} - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; - } +// This is set in the defaults step: +function keyFunction(opts) { + return opts._index; +} - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_71.tester.selectAll('g.' + _$constants_135.labelGroupClass) + .data(sliderOpts.steps); - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_179.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); - } - gd.undoQueue.inSequence = false; - gd.autoplay = false; + sliderLabels.enter().append('g') + .classed(_$constants_135.labelGroupClass, true); - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; -}; + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_10.select(this); -/** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. - * - * @param gd - * @param func - * @param args - */ -__queue_179.plotDo = function(gd, func, args) { - gd.autoplay = true; + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_71.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + } + }); - // call the supplied function - func.apply(null, args); -}; + sliderLabels.remove(); -var _$queue_179 = __queue_179; + var dims = sliderOpts._dims = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + dims.inputAreaWidth = Math.max( + _$constants_135.railWidth, + _$constants_135.gripHeight + ); -'use strict'; + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); -var _$localeEnUs_189 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' - }, - format: { - date: '%m/%d/%Y' + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); -'use strict'; + var textableInputLength = dims.inputAreaLength - 2 * _$constants_135.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_135.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; -var _$localeEn_190 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' - } -}; + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; -var _$fromQuat_14 = fromQuat; + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_71.tester.append('g'); -/** - * 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, + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_71.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_187.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); - 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; + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + + dummyGroup.remove(); + } + + dims.height = dims.currentValueTotalHeight + _$constants_135.tickOffset + sliderOpts.ticklen + _$constants_135.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + + var xanchor = 'left'; + if(_$anchor_utils_98.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; + } + if(_$anchor_utils_98.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; + } - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; + var yanchor = 'top'; + if(_$anchor_utils_98.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_98.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; + } - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + _$plots_240.autoMargin(gd, _$constants_135.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_137[xanchor], + r: dims.outerLength * __FROM_BR_137[xanchor], + b: dims.height * __FROM_BR_137[yanchor], + t: dims.height * __FROM_TL_137[yanchor] + }); +} - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; + } - return out; -}; -var _$helpers_193 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); + var dims = sliderOpts._dims; -'use strict'; + // Position the rectangle: + _$drawing_71.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_14 = require('gl-mat4/fromQuat'); */; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); -/* removed: var _$registry_247 = require('../registry'); */; -/* removed: var _$lib_165 = require('../lib'); */; -/* removed: var _$plots_240 = require('../plots/plots'); */; -/* removed: var _$axis_ids_210 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_210.cleanId; -var getFromTrace = _$axis_ids_210.getFromTrace; -/* removed: var _$color_46 = require('../components/color'); */; +} +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; -// clear the promise queue if one of them got rejected -_$helpers_193.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_165.log('Clearing previous rejected promises from queue.'); - } + var dims = sliderOpts._dims; + var x0, textAnchor; - gd._promises = []; -}; + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_135.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_135.currentValueInset; + textAnchor = 'left'; + } -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_193.cleanLayout = function(layout) { - var i, j; + var text = _$lib_166.ensureSingle(sliderGroup, 'text', _$constants_135.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); - if(!layout) layout = {}; + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; + + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; } - var axisAttrRegex = (_$plots_240.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_240.subplotsRegistry.gl3d || {}).attrRegex; + text.call(_$drawing_71.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_187.convertToTspans, sliderOpts._gd); - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; + var lines = _$svg_text_utils_187.lineCount(text); - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_137; - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories + _$svg_text_utils_187.positionText(text, x0, y0); - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; + return text; +} - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; - } - } +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_166.ensureSingle(sliderGroup, 'rect', _$constants_135.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; + grip.attr({ + width: _$constants_135.gripWidth, + height: _$constants_135.gripHeight, + rx: _$constants_135.gripRadius, + ry: _$constants_135.gripRadius, + }) + .call(_$color_46.stroke, sliderOpts.bordercolor) + .call(_$color_46.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); +} - // clean old Camera coords - var cameraposition = scene.cameraposition; +function drawLabel(item, data, sliderOpts) { + var text = _$lib_166.ensureSingle(item, 'text', _$constants_135.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_14([], rotation), - eye = []; + text.call(_$drawing_71.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_187.convertToTspans, sliderOpts._gd); - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } + return text; +} - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_166.ensureSingle(sliderGroup, 'g', _$constants_135.labelsClass); + var dims = sliderOpts._dims; - delete scene.cameraposition; - } - } - } + var labelItems = labels.selectAll('g.' + _$constants_135.labelGroupClass) + .data(dims.labelSteps); - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; + labelItems.enter().append('g') + .classed(_$constants_135.labelGroupClass, true); - if(!_$lib_165.isPlainObject(ann)) continue; + labelItems.exit().remove(); - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } + labelItems.each(function(d) { + var item = _$d3_10.select(this); - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); - } + item.call(drawLabel, d, sliderOpts); - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; + _$drawing_71.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_135.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_137 + + _$constants_135.labelOffset + + dims.currentValueTotalHeight + ); + }); - if(!_$lib_165.isPlainObject(shape)) continue; +} - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); } +} - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; - } - } + var step = sliderOpts.steps[sliderOpts.active]; - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_46.clean(layout); + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); - return layout; -}; + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); + if(_step.execute) { + _$plots_240.executeAPICommand(gd, _step.method, _step.args); + } + + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } } } -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_193.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_10.select(gd); - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; + } - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); - for(i = 0; i < 100; i++) { - newUid = _$lib_165.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_165.randstr(uids); - uids.push(trace.uid); - } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); + var grip = sliderGroup.select('.' + _$constants_135.gripRectClass); - // BACKWARD COMPATIBILITY FIXES + _$d3_10.event.stopPropagation(); + _$d3_10.event.preventDefault(); + grip.call(_$color_46.fill, sliderOpts.activebgcolor); - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_10.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_46.defaults, - yeColor = trace.error_y.color || - (_$registry_247.traceIs(trace, 'bar') ? _$color_46.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_46.addOpacity( - _$color_46.rgb(yeColor), - _$color_46.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_10.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); + }); - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_247.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_193.swapXYData(trace); - } - delete trace.bardir; - } + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_46.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_193.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; - } + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); + }); +} - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_135.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + tick.enter().append('rect') + .classed(_$constants_135.tickRectClass, true); - // scene ids scene1 -> scene - if(_$registry_247.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_240.subplotsRegistry.gl3d.cleanId(trace.scene); - } + tick.exit().remove(); - if(!_$registry_247.traceIs(trace, 'pie') && !_$registry_247.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); - // fix typo in colorscale definition - if(_$registry_247.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_247.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_10.select(this); - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_165.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_46.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; + _$drawing_71.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_135.tickOffset : _$constants_135.minorTickOffset) + dims.currentValueTotalHeight + ); + }); - if(!_$lib_165.isPlainObject(opts)) continue; +} - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } - } + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); + } +} - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_135.gripRectClass); - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + var x = normalizedValueToPosition(sliderOpts, position); - if(!_$lib_165.isPlainObject(transform)) continue; + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); + } - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_135.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); +} - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_135.stepInset + + (dims.inputAreaLength - 2 * _$constants_135.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_135.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_135.stepInset - 2 * dims.inputAreaStart))); +} - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } - } +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_166.ensureSingle(sliderGroup, 'rect', _$constants_135.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; - } + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_135.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_46.fill, sliderOpts.bgcolor) + .attr('opacity', 0); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_46.clean(trace); - } -}; + _$drawing_71.setTranslate(rect, 0, dims.currentValueTotalHeight); +} -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_135.railInset * 2; + var rect = _$lib_166.ensureSingle(sliderGroup, 'rect', _$constants_135.railRectClass); - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + rect.attr({ + width: computedLength, + height: _$constants_135.railWidth, + rx: _$constants_135.railRadius, + ry: _$constants_135.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_46.stroke, sliderOpts.bordercolor) + .call(_$color_46.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - return posY + ' ' + posX; + _$drawing_71.setTranslate(rect, + _$constants_135.railInset, + (dims.inputAreaWidth - _$constants_135.railWidth) * 0.5 + dims.currentValueTotalHeight + ); } -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); -} +function __clearPushMargins_137(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; -// swap all the data and data attributes associated with x and y -_$helpers_193.swapXYData = function(trace) { - var i; - _$lib_165.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_165.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_165.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); - } - } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + if(k.indexOf(_$constants_135.autoMarginIdRoot) !== -1) { + _$plots_240.autoMargin(gd, k); } - trace.hoverinfo = hoverInfoParts.join('+'); } -}; +} -// coerce traceIndices input to array of trace indices -_$helpers_193.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_13(traceIndices)) { - return [traceIndices]; - } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 traceIndices; +'use strict'; + +/* removed: var _$constants_135 = require('./constants'); */; + +var _$sliders_138 = { + moduleType: 'component', + name: _$constants_135.name, + + layoutAttributes: _$attributes_134, + supplyLayoutDefaults: _$slidersDefaults_136, + + draw: _$draw_137 }; /** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_193.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; +* Copyright 2012-2018, Plotly, Inc. +* All 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 pLastIsNumber = _$fastIsnumeric_13(pLast); +'use strict'; - // delete item - if(pLastIsNumber && newVal === null) { +/* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_45 = require('../color/attributes'); */; +var __extendFlat_140 = _$extend_160.extendFlat; +var __overrideAll_140 = _$edit_types_193.overrideAll; +/* removed: var _$pad_attributes_239 = require('../../plots/pad_attributes'); */; - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_165.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); +var buttonsAttrs = { + _isLinkedToArray: 'button', - // Note that nested property clears null / undefined at end of - // array container, but not within them. + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + } - // create item - else if(pLastIsNumber && np.get() === undefined) { +}; - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; +var _$attributes_140 = __overrideAll_140({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - np.set(newVal); - } - // update item - else { + visible: { + valType: 'boolean', + + + }, - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); - } -}; + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); -} + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_193.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; -}; + showactive: { + valType: 'boolean', + + dflt: true, + + }, -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_193 = ['x', 'y', 'z']; -_$helpers_193.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_193[j]); + buttons: buttonsAttrs, - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_165.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } -}; + pad: __extendFlat_140({}, _$pad_attributes_239, { + + }), -_$helpers_193.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; - } + font: _$font_attributes_234({ + + }), + + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_45.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + } -}; +}, 'arraydraw', 'from-root'); -var _$manage_arrays_195 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51590,209 +52864,75 @@ var _$manage_arrays_195 = {}; 'use strict'; -/* removed: var _$nestedProperty_173 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_167 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_174 = require('../lib/noop'); */; -/* removed: var _$loggers_170 = require('../lib/loggers'); */; -var sorterAsc = _$search_183.sorterAsc; -/* removed: var _$registry_247 = require('../registry'); */; - - -_$manage_arrays_195.containerArrayMatch = _$containerArrayMatch_191; - -var isAddVal = _$manage_arrays_195.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_167(val); -}; - -var isRemoveVal = _$manage_arrays_195.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; - -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_195.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_247.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_247.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_247.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_174) || - (draw === _$noop_174), - layout = gd.layout, - fullLayout = gd._fullLayout; - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_170.warn('Full array edits are incompatible with other edits', - componentType); - } +var _$constants_141 = { - var fullVal = edits['']['']; + // layout attribute name + name: 'updatemenus', - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); - else { - _$loggers_170.warn('Unrecognized full array edit value', componentType, fullVal); - return true; - } + // 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', - if(replotLater) return false; + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'updatemenu-active-index', - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; - } + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'updatemenu-', - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_173(fullLayout, componentType).get(); + // options when 'active: -1' + blankHeaderOpts: { label: ' ' }, - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; + // min item width / height + minWidth: 30, + minHeight: 30, - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + // padding around item text + textPadX: 24, + arrowPadX: 16, - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_170.warn('index out of range', componentType, componentNum); - continue; - } + // item rect radii + rx: 2, + ry: 2, - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_170.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } + // item text x offset off left edge + textOffsetX: 12, - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_170.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } + // item text y offset (w.r.t. middle) + textOffsetY: 3, - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_173(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } - } + // arrow offset off right edge + arrowOffsetX: 4, - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); - } + // gap between header and buttons + gapButtonHeader: 5, - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); + // gap between between buttons + gapButton: 2, - if(replotLater) return false; + // color given to active buttons + activeColor: '#F4FAFF', - supplyComponentDefaults(layout, fullLayout); + // color given to hovered buttons + hoverColor: '#F4FAFF', - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_174) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); - } + // symbol for menu open arrow + arrowSymbol: { + left: '◄', + right: '►', + up: '▲', + down: '▼' } - else draw(gd); - - return true; }; -var _$buttons_108 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51801,2805 +52941,2245 @@ var _$buttons_108 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$plots_240 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_210 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_204 = require('../../plots/array_container_defaults'); */; -var ____108 = _$lib_165._; +/* removed: var _$attributes_140 = require('./attributes'); */; +/* removed: var _$constants_141 = require('./constants'); */; -var modeBarButtons = _$buttons_108 = {}; +var __name_142 = _$constants_141.name; +var __buttonAttrs_142 = _$attributes_140.buttons; -/** - * 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) { return ____108(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; +var _$updateMenusDefaults_142 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_142, + handleItemDefaults: menuDefaults + }; - _$lib_165.notifier(____108(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + _$handleArrayContainerDefaults_204(layoutIn, layoutOut, opts); +}; - if(_$lib_165.isIE()) { - _$lib_165.notifier(____108(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; - } +function menuDefaults(menuIn, menuOut, layoutOut) { - _$registry_247.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_165.notifier(____108(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_165.notifier(____108(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); + function coerce(attr, dflt) { + return _$lib_166.coerce(menuIn, menuOut, _$attributes_140, attr, dflt); } -}; -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____108(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_240.sendDataToCloud(gd); - } -}; + var buttons = __buttonsDefaults_142(menuIn, menuOut); -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____108(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian -}; + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____108(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian -}; + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____108(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; + coerce('x'); + coerce('y'); + _$lib_166.noneOrAll(menuIn, menuOut, ['x', 'y']); -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____108(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian -}; + coerce('xanchor'); + coerce('yanchor'); -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____108(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian -}; + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____108(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian -}; + _$lib_166.coerceFont(coerce, 'font', layoutOut.font); -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____108(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian -}; + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____108(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian -}; +function __buttonsDefaults_142(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____108(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian -}; + var buttonIn, buttonOut; -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____108(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; - }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian -}; + function coerce(attr, dflt) { + return _$lib_166.coerce(buttonIn, buttonOut, __buttonAttrs_142, attr, dflt); + } -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 = _$axis_ids_210.list(gd, null, true); - var allSpikesEnabled = 'on'; + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; - var ax, i; + coerce('method'); - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; + if(!_$lib_166.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } - var axName; + coerce('args'); + coerce('label'); + coerce('execute'); - for(i = 0; i < axList.length; i++) { - ax = axList[i]; + buttonOut._index = i; + buttonsOut.push(buttonOut); + } - 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]; - } - 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]), - ]; + return buttonsOut; +} - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); - aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); - } - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } +'use strict'; - aobj[astr] = val; - } +var _$ScrollBox_145 = ScrollBox; - _$registry_247.call('relayout', gd, aobj); -} +/* removed: var _$d3_10 = require('d3'); */; -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____108(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d -}; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____108(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d -}; +/* removed: var _$lib_166 = require('../../lib'); */; -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____108(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d -}; +/** + * Helper class to setup a scroll box + * + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box + */ +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____108(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['z-axis'], - click: handleDrag3d -}; + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection -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 = {}; + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); - var parts = attr.split('.'); + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); - for(var i = 0; i < sceneIds.length; i++) { - layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; - } + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} - // for multi-type subplots - var val2d = (val === 'pan') ? val : 'zoom'; - layoutUpdate.dragmode = val2d; +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; - _$registry_247.call('relayout', gd, layoutUpdate); -} +/** + * If needed, setup a clip path and scrollbars + * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____108(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; + // compute position of scrollbox + this.position = position; -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____108(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d -}; + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; -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 = {}; + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; + } - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; + + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; + } + } + else { + boxT = t; + boxB = boxT + boxH; - if(attr === 'resetDefault') { - aobj[key] = null; + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_165.extendDeep({}, scene.cameraInitial); + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; } } - _$registry_247.call('relayout', gd, aobj); -} + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; + hbar.exit() + .on('.drag', null) + .remove(); - if(val) { - layoutUpdate = _$lib_165.extendDeep(layout, val); - button._previousVal = null; + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_46.fill, ScrollBox.barColor); + + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); + + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; } else { - layoutUpdate = { - 'allaxes.showspikes': false - }; + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; - } - } - } + vbar.exit() + .on('.drag', null) + .remove(); - button._previousVal = _$lib_165.extendDeep({}, currentSpikes); - } + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_46.fill, ScrollBox.barColor); - _$registry_247.call('relayout', gd, layoutUpdate); -} + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____108(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; + } + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____108(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____108(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo -}; + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + clipPath.exit().remove(); -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; + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); - for(var i = 0; i < geoIds.length; i++) { - var id = geoIds[i]; - var geoLayout = fullLayout[id]; + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); - if(attr === 'zoom') { - var scale = geoLayout.projection.scale; - var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; + this.container.call(_$drawing_71.setClipUrl, clipId); - _$registry_247.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); - } + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); } -} - -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; - -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; - -function toggleHover(gd) { - var fullLayout = gd._fullLayout; - - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_71.setClipUrl, null); + delete this._clipRect; } - else onHoverVal = 'closest'; - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_10.behavior.drag() + .on('dragstart', function() { + _$d3_10.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); - _$registry_247.call('relayout', gd, 'hovermode', newHover); -} + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); -// buttons when more then one plot types are present + var onBarDrag = _$d3_10.behavior.drag() + .on('dragstart', function() { + _$d3_10.event.sourceEvent.preventDefault(); + _$d3_10.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } } -}; - -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____108(gd, 'Reset views'); }, - icon: _$ploticon_2.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'); - } + // set scrollbox translation + this.setTranslate(translateX, translateY); }; -modeBarButtons.toggleSpikelines = { - name: 'toggleSpikelines', - title: function(gd) { return ____108(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; - - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; +/** + * If present, remove clip-path and scrollbars + * + * @method + */ +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_71.setClipUrl, null); + delete this._clipRect; + } - var aobj = setSpikelineVisibility(gd); + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } - _$registry_247.call('relayout', gd, aobj); + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } }; -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_210.list(gd, null, true); - var aobj = {}; - - var ax, axName; +/** + * Handles scroll box drag events + * + * @method + */ +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + if(this.hbar) { + translateX -= _$d3_10.event.dx; } - return aobj; -} - -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____108(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); + if(this.vbar) { + translateY -= _$d3_10.event.dy; } + + this.setTranslate(translateX, translateY); }; -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; +/** + * Handles scroll box wheel events + * + * @method + */ +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; - 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); + if(this.hbar) { + translateX += _$d3_10.event.deltaY; + } - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; - } + if(this.vbar) { + translateY += _$d3_10.event.deltaY; } - _$registry_247.call('relayout', gd, aObj); -} + this.setTranslate(translateX, translateY); +}; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; + * Handles scroll bar drag events + * + * @method + */ +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; -/* removed: var _$d3_10 = require('d3'); */; + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_166.constrain(_$d3_10.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; + var translateXMax = this.position.w - this._box.w; + translateX = xf * translateXMax; + } -/** - * 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'); + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_166.constrain(_$d3_10.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); - this.update(opts.graphInfo, opts.buttons); + var translateYMax = this.position.h - this._box.h; - this.container.appendChild(this.element); -} + translateY = yf * translateYMax; + } -var proto = ModeBar.prototype; + this.setTranslate(translateX, translateY); +}; /** - * 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 + * Set clip path and scroll bar translate transform * + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) */ -proto.update = function(graphInfo, buttons) { - this.graphInfo = graphInfo; +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; - var context = this.graphInfo._context; + translateX = _$lib_166.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_166.constrain(translateY || 0, 0, translateYMax); - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; - } - else this.element.className = 'modebar'; + this.translateX = translateX; + this.translateY = translateY; - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); + this.container.call(_$drawing_71.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } - this.updateButtons(buttons); + if(this.hbar) { + var xf = translateX / translateXMax; - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; - } + this.hbar.call(_$drawing_71.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); } - this.updateActiveButton(); + if(this.vbar) { + var yf = translateY / translateYMax; + + this.vbar.call(_$drawing_71.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); + } }; -proto.updateButtons = function(buttons) { - var _this = this; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); +'use strict'; - 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); +/* removed: var _$d3_10 = require('d3'); */; - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$color_46 = require('../color'); */; +/* removed: var _$drawing_71 = require('../drawing'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_98 = require('../legend/anchor_utils'); */; - _this.element.appendChild(group); - }); -}; +var __LINE_SPACING_143 = _$alignment_146.LINE_SPACING; -/** - * Empty div for containing a group of buttons - * @Return {HTMLelement} - */ -proto.createGroup = function() { - var group = document.createElement('div'); - group.className = 'modebar-group'; +/* removed: var _$constants_141 = require('./constants'); */; +/* removed: var _$ScrollBox_145 = require('./scrollbox'); */; - return group; -}; +var _$draw_143 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); -/** - * 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, - button = document.createElement('a'); + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ - button.setAttribute('rel', 'tooltip'); - button.className = 'modebar-btn'; + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_141.containerClassName) + .data(menuData.length > 0 ? [0] : []); - 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); + menus.enter().append('g') + .classed(_$constants_141.containerClassName, true) + .style('cursor', 'pointer'); - if(title || title === 0) button.setAttribute('data-title', title); + menus.exit().remove(); - if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_143(gd); - var val = config.val; - if(val !== undefined) { - if(typeof val === 'function') val = val(this.graphInfo); - button.setAttribute('data-val', val); - } + // return early if no update menus are visible + if(menuData.length === 0) return; - 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); + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_141.headerGroupClassName) + .data(menuData, __keyFunction_143); - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); - } + headerGroups.enter().append('g') + .classed(_$constants_141.headerGroupClassName, true); - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_10.select(button).classed('active', true); + // draw dropdown button container + var gButton = _$lib_166.ensureSingle(menus, 'g', _$constants_141.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - button.setAttribute('data-gravity', config.gravity || 'n'); + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_143(gd, menuOpts); + } - return button; -}; + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_145(gd, gButton, scrollBoxId); -/** - * Add an icon to a button - * @Param {object} thisIcon - * @Param {number} thisIcon.width - * @Param {string} thisIcon.path - * @Return {HTMLelement} - */ -proto.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); + gButton + .call(removeAllButtons) + .attr(_$constants_141.menuIndexAttrName, '-1'); + } - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; + headerGroups.exit().each(function(menuOpts) { + _$d3_10.select(this).remove(); - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); + gButton + .call(removeAllButtons) + .attr(_$constants_141.menuIndexAttrName, '-1'); - return icon; -}; + _$plots_240.autoMargin(gd, _$constants_141.autoMarginIdRoot + menuOpts._index); + }); -/** - * 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, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_10.select(this); - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_10.select(button); + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_240.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_143(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); - // 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_165.nestedProperty(fullLayout, dataAttr).get(); + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - button3.classed('active', val === thisval); + // if this menu is active, update the dropdown container + if(__isActive_143(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); } }); }; /** - * Check if modeBar is configured as button configuration argument - * - * @Param {object} buttons 2d array of grouped button config objects - * @Return {boolean} + * get only visible menus for display */ -proto.hasButtons = function(buttons) { - var currentButtons = this.buttons; - - if(!currentButtons) return false; +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_141.name]; + var menuData = []; - if(buttons.length !== currentButtons.length) return false; + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; - 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; - } + if(item.visible) menuData.push(item); } - return true; -}; + return menuData; +} -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -proto.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_143(menuOpts) { + return menuOpts._index; +} - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_165._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; +function isFolded(gButton) { + return +gButton.attr(_$constants_141.menuIndexAttrName) === -1; +} - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); +function __isActive_143(gButton, menuOpts) { + return +gButton.attr(_$constants_141.menuIndexAttrName) === menuOpts._index; +} - group.appendChild(a); - return group; -}; +function __setActive_143(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; -proto.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_141.menuIndexAttrName, '-1'); - this.hasLogo = false; -}; - -proto.destroy = function() { - _$lib_165.removeElement(this.container.querySelector('.modebar')); -}; - -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; - - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - if(fullLayout._privateplot) { - _$d3_10.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } } - - return modeBar; } -var _$createModeBar_111 = createModeBar; +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_166.ensureSingle(gHeader, 'g', _$constants_141.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_141.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); -'use strict'; + // draw drop arrow at the right edge + var arrow = _$lib_166.ensureSingle(gHeader, 'text', _$constants_141.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_71.font, menuOpts.font) + .text(_$constants_141.arrowSymbol[menuOpts.direction]); + }); -/* removed: var _$axis_ids_210 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_339 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_247 = require('../../registry'); */; + arrow.attr({ + x: dims.headerWidth - _$constants_141.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_141.textOffsetY + menuOpts.pad.t + }); -/* removed: var _$createModeBar_111 = require('./modebar'); */; -/* removed: var _$buttons_108 = require('./buttons'); */; + header.on('click', function() { + gButton.call(removeAllButtons); -/** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object - * - */ -var _$manageModeBar_110 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_141.menuIndexAttrName, + __isActive_143(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); - var customButtons = context.modeBarButtons; - var buttonGroups; + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } + // translate header group + _$drawing_71.setTranslate(gHeader, dims.lx, dims.ly); +} - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_111(gd, buttonGroups); -}; +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); + var klass = menuOpts.type === 'dropdown' ? _$constants_141.dropdownButtonClassName : _$constants_141.buttonClassName; - var groups = []; + var buttons = gButton.selectAll('g.' + klass) + .data(buttonData); - function addGroup(newGroup) { - if(!newGroup.length) return; + var enter = buttons.enter().append('g') + .classed(klass, true); - var out = []; + var exit = buttons.exit(); - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_108[button]); - } + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); - groups.push(out); + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; - } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; - } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; - } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; - } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; - } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_141.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_141.gapButtonHeader; + } } - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_141.gapButtonHeader + _$constants_141.gapButton - dims.openHeight; } - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; - } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_141.gapButtonHeader + _$constants_141.gapButton - dims.openWidth; } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_141.gapButton, + xPad: _$constants_141.gapButton, + index: 0, + }; - return appendButtonsToGroups(groups, buttonsToAdd); -} + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_210.list({_fullLayout: fullLayout}, null, true); + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_10.select(this); - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } - } + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); - return true; -} + button.on('click', function() { + // skip `dragend` events + if(_$d3_10.event.defaultPrevented) return; -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; + __setActive_143(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; + if(buttonOpts.execute) { + _$plots_240.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } - var trace = fullData[i]; + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); - if(!trace._module || !trace._module.selectPoints) continue; + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); - if(_$registry_247.traceIs(trace, 'scatter-like')) { - if(_$subtypes_339.hasMarkers(trace) || _$subtypes_339.hasText(trace)) { - selectable = true; - } - } else if(_$registry_247.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); + + buttons.call(styleButtons, menuOpts); + + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); } - return selectable; + scrollBoxPosition.direction = menuOpts.direction; + + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } } -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; + + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_141.gapButton; + } + } + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_141.gapButton; } - else groups.push(buttons); } - return groups; + scrollBox.enable(position, translateX, translateY); + + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } + + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } } -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } - if(typeof button === 'string') { - if(_$buttons_108[button] !== undefined) { - customButtons[i][j] = _$buttons_108[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); } +} - return customButtons; +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); } -var _$modebar_109 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function drawItemRect(item, menuOpts) { + var rect = _$lib_166.ensureSingle(item, 'rect', _$constants_141.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_141.rx, + ry: _$constants_141.ry, + 'shape-rendering': 'crispEdges' + }); + }); + rect.call(_$color_46.stroke, menuOpts.bordercolor) + .call(_$color_46.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} -'use strict'; +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_166.ensureSingle(item, 'text', _$constants_141.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); -_$modebar_109.manage = _$manageModeBar_110; + text.call(_$drawing_71.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_187.convertToTspans, gd); +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; + buttons.each(function(buttonOpts, i) { + var button = _$d3_10.select(this); -'use strict'; + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_141.itemRectClassName) + .call(_$color_46.fill, _$constants_141.activeColor); + } + }); +} -var FROM_BL = _$alignment_146.FROM_BL; +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_141.itemRectClassName) + .call(_$color_46.fill, _$constants_141.hoverColor); +} -var _$scaleZoom_224 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_141.itemRectClassName) + .call(_$color_46.fill, menuOpts.bgcolor); +} - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; +// find item dimensions (this mutates menuOpts) +function __findDimensions_143(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; + var fakeButtons = _$drawing_71.tester.selectAll('g.' + _$constants_141.dropdownButtonClassName) + .data(menuOpts.buttons); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + fakeButtons.enter().append('g') + .classed(_$constants_141.dropdownButtonClassName, true); -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_10.select(this); - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + button.call(drawItem, menuOpts, buttonOpts, gd); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + var text = button.select('.' + _$constants_141.itemTextClassName); -var _$BuildLog_20 = BuildLog; + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_71.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_141.textPadX, _$constants_141.minWidth); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_143; + var tLines = _$svg_text_utils_187.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_141.minHeight) + _$constants_141.textOffsetY; -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_141.gapButton; + dims.openHeight += hEff + _$constants_141.gapButton; + } else { + dims.totalWidth += wEff + _$constants_141.gapButton; + dims.openWidth += wEff + _$constants_141.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; + if(isVertical) { + dims.totalHeight -= _$constants_141.gapButton; + } else { + dims.totalWidth -= _$constants_141.gapButton; + } - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; + dims.headerWidth = dims.width1 + _$constants_141.arrowPadX; + dims.headerHeight = dims.height1; - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_141.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_141.arrowPadX; + } - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; + fakeButtons.remove(); - // categorize where intersection point is along A and B + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + var xanchor = 'left'; + if(_$anchor_utils_98.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_98.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + var yanchor = 'top'; + if(_$anchor_utils_98.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_98.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; + } - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; + _$plots_240.autoMargin(gd, _$constants_141.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); } -var _$Epsilon_21 = Epsilon; +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_141.itemRectClassName); + var text = item.select('.' + _$constants_141.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + _$drawing_71.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + var tHeight = menuOpts.font.size * __LINE_SPACING_143; + var tLines = _$svg_text_utils_187.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); - // 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] }); - } + _$svg_text_utils_187.positionText(text, _$constants_141.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_141.textOffsetY); - // the first LineString is considered the outside - var out = LineString(coords[0]); + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; + } - // 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]))); + posOpts.index++; +} - return out; - } +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_141.dropdownButtonClassName).remove(); +} - 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'); - }, +function __clearPushMargins_143(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - // 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)); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - // 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); - } + if(k.indexOf(_$constants_141.autoMarginIdRoot) !== -1) { + _$plots_240.autoMargin(gd, k); + } + } +} - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function newNode(region){ - return { - region: region, - children: [] - }; - } +'use strict'; - var roots = newNode(null); +/* removed: var _$constants_141 = require('./constants'); */; - 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; - } - } +var _$updatemenus_144 = { + moduleType: 'component', + name: _$constants_141.name, - // 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--; - } - } + layoutAttributes: _$attributes_140, + supplyLayoutDefaults: _$updateMenusDefaults_142, - // now we can add ourselves - root.children.push(node); - } + draw: _$draw_143 +}; - // 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); - } +var _$mathjax_config_152 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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 +'use strict'; - // while we're at it, exteriors are counter-clockwise, and interiors are clockwise +/* global MathJax:false */ - 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; - } +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_152.MathJax = true; - var geopolys = []; + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); - 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])); - } + MathJax.Hub.Configured(); +} else { + _$mathjax_config_152.MathJax = false; +} - 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); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); - // lastly, construct the approrpriate GeoJSON object +'use strict'; - 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 - }; - } -}; +/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$plot_config_198 = require('../plot_api/plot_config'); */; -var _$GeoJSON_22 = GeoJSON; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + for(var i = 0; i < args.length; i++) { + arg = args[i]; -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_166.extendDeep([], arg) : + _$lib_166.extendDeepAll({}, arg); + } + else copy[i] = arg; + } -var _$LinkedList_24 = LinkedList; + return copy; +} -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs -// -// this is the core work-horse -// +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- + + +var __queue_180 = {}; + +// TODO: disable/enable undo and redo buttons appropriately + +/** + * Add an item to the undoQueue for a graphDiv + * + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with + */ +__queue_180.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; + + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; + + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } + + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; + + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } + + if(gd.undoQueue.queue.length > _$plot_config_198.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; -/* removed: var _$LinkedList_24 = require('./linked-list'); */; +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_180.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_180.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; +}; - // - // segment creation - // +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_180.undo = function undo(gd) { + var queueObj, i; - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; - // - // event logic - // + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - var event_root = _$LinkedList_24.create(); + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_180.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd + */ +__queue_180.redo = function redo(gd) { + var queueObj, i; - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_180.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; +}; - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_24.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_180.plotDo = function(gd, func, args) { + gd.autoplay = true; - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_24.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + // call the supplied function + func.apply(null, args); +}; - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) +var _$queue_180 = __queue_180; - if (buildLog) - buildLog.segmentChop(ev.seg, end); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } +'use strict'; - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } +var _$localeEnUs_190 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } +}; - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // - // status logic - // +'use strict'; - var status_root = _$LinkedList_24.create(); +var _$localeEn_191 = { + 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' + } +}; - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; +var _$fromQuat_14 = fromQuat; - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } +/** + * 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, - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + 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; - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; - if (buildLog) - buildLog.checkIntersection(seg1, seg2); + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; - var i = eps.linesIntersect(a1, a2, b1, b2); + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; - if (i === false){ - // segments are parallel or coincident + return out; +}; +var _$helpers_194 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection +'use strict'; - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); +/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_14 = require('gl-mat4/fromQuat'); */; - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal +/* removed: var _$registry_248 = require('../registry'); */; +/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$plots_240 = require('../plots/plots'); */; +/* removed: var _$axis_ids_211 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_211.cleanId; +var getFromTrace = _$axis_ids_211.getFromTrace; +/* removed: var _$color_46 = require('../components/color'); */; - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); +// clear the promise queue if one of them got rejected +_$helpers_194.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_166.log('Clearing previous rejected promises from queue.'); + } - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } + gd._promises = []; +}; - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_194.cleanLayout = function(layout) { + var i, j; - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + if(!layout) layout = {}; - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); + var axisAttrRegex = (_$plots_240.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_240.subplotsRegistry.gl3d || {}).attrRegex; - if (buildLog) - buildLog.vert(ev.pt[0]); + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[i]; - if (ev.isStart){ + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; + } + delete ax.autotick; + } + } - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev + // clean old Camera coords + var cameraposition = scene.cameraposition; - // merge ev.seg's fill information into eve.seg + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_14([], rotation), + eye = []; - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; - if (buildLog) - buildLog.segmentUpdate(eve.seg); + delete scene.cameraposition; + } + } + } - ev.other.remove(); - ev.remove(); - } + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } + if(!_$lib_166.isPlainObject(ann)) continue; - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; + } + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; + } - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); + } - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + if(!_$lib_166.isPlainObject(shape)) continue; - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); + } - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_24.node({ ev: ev })); - } - else{ - var st = ev.status; + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; - if (buildLog) - buildLog.statusRemove(st.ev.seg); + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_46.clean(layout); - // remove the status - st.remove(); + return layout; +}; - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); + } +} - // remove the event and continue - event_root.getHead().remove(); - } +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_194.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); - if (buildLog) - buildLog.done(); + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; - return segments; - } + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } + for(i = 0; i < 100; i++) { + newUid = _$lib_166.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_166.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; + // BACKWARD COMPATIBILITY FIXES - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; -} + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_46.defaults, + yeColor = trace.error_y.color || + (_$registry_248.traceIs(trace, 'bar') ? _$color_46.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_46.addOpacity( + _$color_46.rgb(yeColor), + _$color_46.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; + } -var _$Intersecter_23 = Intersecter; + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_248.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_194.swapXYData(trace); + } + delete trace.bardir; + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_194.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } + // scene ids scene1 -> scene + if(_$registry_248.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_240.subplotsRegistry.gl3d.cleanId(trace.scene); + } - if (buildLog) - buildLog.chainStart(seg); + if(!_$registry_248.traceIs(trace, 'pie') && !_$registry_248.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + // fix typo in colorscale definition + if(_$registry_248.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_248.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_166.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; - if (next_match === second_match){ - // we matched a single chain + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; - if (buildLog) - buildLog.chainMatch(first_match.index); + if(!_$lib_166.isPlainObject(opts)) continue; - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } + } - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; - if (buildLog) - buildLog.chainClose(first_match.index); + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; - // we have a closed chain! - regions.push(chain); - return; - } + if(!_$lib_166.isPlainObject(transform)) continue; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } - // otherwise, we matched two chains, so we need to combine those chains together + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } + } - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_46.clean(trace); + } +}; - var F = first_match.index; - var S = second_match.index; +function cleanFinanceDir(dirContainer) { + if(!_$lib_166.isPlainObject(dirContainer)) return false; - if (buildLog) - buildLog.chainConnect(F, S); + var dirName = dirContainer.name; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); + delete dirContainer.name; + delete dirContainer.showlegend; - return regions; + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); } -var _$SegmentChainer_25 = SegmentChainer; +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; -// -// filter a list of segments based on boolean operations -// + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + var out = name1.substr(0, i); + return out.trim(); +} - if (buildLog) - buildLog.selected(result); +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; - return result; + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; + + return posY + ' ' + posX; } -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} + + +// swap all the data and data attributes associated with x and y +_$helpers_194.swapXYData = function(trace) { + var i; + _$lib_166.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_166.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_166.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); + } }; -var _$SegmentSelector_26 = SegmentSelector; +// coerce traceIndices input to array of trace indices +_$helpers_194.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_13(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); + } -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs + return traceIndices; +}; + +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * */ +_$helpers_194.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; -/* removed: var _$BuildLog_20 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_21 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_23 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_25 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_26 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_22 = require('./lib/geojson'); */; + var pLastIsNumber = _$fastIsnumeric_13(pLast); -var buildLog = false; -var epsilon = _$Epsilon_21(); + // delete item + if(pLastIsNumber && newVal === null) { -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_20(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_166.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); - // core API - segments: function(poly){ - var i = _$Intersecter_23(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_23(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_26.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_26.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_26.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_26.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_26.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_25(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_22.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_22.fromPolygon(PolyBool, epsilon, poly); - }, + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; - // 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); - } + np.set(newVal); + } + // update item + else { + + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); + } }; -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); +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); } -if (typeof window === 'object') - window.PolyBool = PolyBool; +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_194.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; +}; + +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_194 = ['x', 'y', 'z']; +_$helpers_194.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_194[j]); + + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; + } + var typeAttr = axAttr + '.type'; -var _$PolyBool_19 = PolyBool; + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_166.nestedProperty(gd.layout, typeAttr).set(null); + } + } + } + } +}; + +_$helpers_194.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; + } + } +}; -var _$polygon_177 = {}; +var _$manage_arrays_196 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -54611,293 +55191,209 @@ var _$polygon_177 = {}; 'use strict'; -var dot = _$matrix_171.dot; -var __BADNUM_177 = _$numerical_148.BADNUM; - -var polygon = _$polygon_177 = {}; +/* removed: var _$nestedProperty_174 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_168 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_175 = require('../lib/noop'); */; +/* removed: var _$loggers_171 = require('../lib/loggers'); */; +var sorterAsc = _$search_184.sorterAsc; +/* removed: var _$registry_248 = require('../registry'); */; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; +_$manage_arrays_196.containerArrayMatch = _$containerArrayMatch_192; - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } +var isAddVal = _$manage_arrays_196.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_168(val); +}; - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed +var isRemoveVal = _$manage_arrays_196.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; - var isRect = false, - rectFirstEdgeTest; +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. + * + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items + * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. + */ +_$manage_arrays_196.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_248.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_248.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_248.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_175) || + (draw === _$noop_175), + layout = gd.layout, + fullLayout = gd._fullLayout; - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_171.warn('Full array edits are incompatible with other edits', + componentType); } - } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var fullVal = edits['']['']; - if(x === __BADNUM_177 || x < xmin || x > xmax || y === __BADNUM_177 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_171.warn('Unrecognized full array edit value', componentType, fullVal); + return true; } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + if(replotLater) return false; + + supplyComponentDefaults(layout, fullLayout); + draw(gd); return true; } - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_174(fullLayout, componentType).get(); - if(x === __BADNUM_177 || x < xmin || x > xmax || y === __BADNUM_177 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_171.warn('index out of range', componentType, componentNum); + continue; + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_171.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; + + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } - // inside the bounding box, check the actual line intercept else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } - - if(y <= ycross && x !== xmini) crossings++; + _$loggers_171.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); } - } - - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; + if(firstIndexChange === -1) firstIndexChange = componentNum; } - } - - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; - -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; - - for(var i = 0; i < list.length; i++) { - 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); - } - - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_174(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } - - return yes; } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; - -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; - - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); - - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - return false; -}; -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); + if(replotLater) return false; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; + supplyComponentDefaults(layout, fullLayout); + + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_175) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); } } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); + } } + else draw(gd); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); - } - - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; + return true; }; +var _$buttons_108 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -54909,1483 +55405,1166 @@ polygon.filter = function filter(pts, tolerance) { 'use strict'; -/* removed: var _$PolyBool_19 = require('polybooljs'); */; -/* removed: var _$polygon_177 = require('../../lib/polygon'); */; -/* removed: var _$throttle_187 = require('../../lib/throttle'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -var makeEventData = _$helpers_85.makeEventData; -/* removed: var _$fx_88 = require('../../components/fx'); */; - -/* removed: var _$axes_207 = require('./axes'); */; -/* removed: var _$constants_212 = require('./constants'); */; - -var filteredPolygon = _$polygon_177.filter; -var polygonTester = _$polygon_177.tester; -var multipolygonTester = _$polygon_177.multitester; -var MINSELECT = _$constants_212.MINSELECT; - -function getAxId(ax) { return ax._id; } - -var _$prepSelect_225 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } - - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_212.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'); +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$plots_240 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_211 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_46.background, - stroke: _$color_46.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +var ____108 = _$lib_166._; +var modeBarButtons = _$buttons_108 = {}; - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_212.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; +/** + * 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? + */ - 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; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____108(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + _$lib_166.notifier(____108(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_207.getFromId(gd, trace.xaxis), - yaxis: _$axes_207.getFromId(gd, trace.yaxis) - }); + if(_$lib_166.isIE()) { + _$lib_166.notifier(____108(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; } - } - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + _$registry_248.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_166.notifier(____108(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_166.notifier(____108(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); } +}; - function ascending(a, b) { return a - b; } +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____108(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_240.sendDataToCloud(gd); + } +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____108(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____108(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____108(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian +}; - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____108(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } - } +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____108(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian +}; - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____108(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian +}; - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____108(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____108(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____108(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____108(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +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 = _$axis_ids_211.list(gd, null, true); + var allSpikesEnabled = 'on'; - _$throttle_187.throttle( - throttleID, - _$constants_212.SELECTDELAY, - function() { - selection = []; + var ax, i; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); + var axName; - thisSelection = fillSelectionItem(traceSelection, searchInfo); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); + 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]; + } + if(ax._showSpikeInitial !== undefined) { + aobj[axName + '.showspikes'] = ax._showSpikeInitial; + if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) { + allSpikesEnabled = 'off'; } } - else selection = thisSelection; } + else { + var rangeNow = [ + ax.r2l(ax.range[0]), + ax.r2l(ax.range[1]), + ]; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; - - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - _$throttle_187.done(throttleID).then(function() { - _$throttle_187.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); } - - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); } - else { - // 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. - gd.emit('plotly_selected', undefined); + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } - _$fx_88.click(gd, evt); - }); - }; - - dragOptions.doneFn = function() { - corners.remove(); + aobj[astr] = val; + } - _$throttle_187.done(throttleID).then(function() { - _$throttle_187.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); + _$registry_248.call('relayout', gd, aobj); +} - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____108(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d +}; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____108(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____108(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - if(eventData) { - var pts = eventData.points || []; +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____108(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['z-axis'], + click: handleDrag3d +}; - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +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 = {}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; + var parts = attr.split('.'); - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); - } - } + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - else { - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; + + _$registry_248.call('relayout', gd, layoutUpdate); +} + +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____108(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; + +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____108(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.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], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; + + if(attr === 'resetDefault') { + aobj[key] = null; + } + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_166.extendDeep({}, scene.cameraInitial); } } - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } + _$registry_248.call('relayout', gd, aobj); } -function mergePolygons(list, poly, subtract) { - var res; +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - if(subtract) { - res = _$PolyBool_19.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - return res.regions; + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; + + if(val) { + layoutUpdate = _$lib_166.extendDeep(layout, val); + button._previousVal = null; } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - res = _$PolyBool_19.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; - return res.regions; -} + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; -function fillSelectionItem(selection, searchInfo) { - if(Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - for(var i = 0; i < selection.length; i++) { - selection[i] = makeEventData(selection[i], trace, cd); + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + } + } } + + button._previousVal = _$lib_166.extendDeep({}, currentSpikes); } - return selection; + _$registry_248.call('relayout', gd, layoutUpdate); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____108(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____108(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; -'use strict'; +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____108(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; -/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$tinycolor_28 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_16 = require('has-passive-events'); */; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$fx_88 = require('../../components/fx'); */; -/* removed: var _$setCursor_184 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_68 = require('../../components/dragelement'); */; -var __FROM_TL_215 = _$alignment_146.FROM_TL; +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; -/* removed: var _$plots_240 = require('../plots'); */; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; -var doTicks = _$axes_207.doTicks; -var getFromId = _$axis_ids_210.getFromId; -/* removed: var _$prepSelect_225 = require('./select'); */; -/* removed: var _$scaleZoom_224 = require('./scale_zoom'); */; + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; -/* removed: var _$constants_212 = require('./constants'); */; -var MINDRAG = _$constants_212.MINDRAG; -var MINZOOM = _$constants_212.MINZOOM; + _$registry_248.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); + } + } +} +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px +function toggleHover(gd) { var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + } + else onHoverVal = 'closest'; - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$registry_248.call('relayout', gd, 'hovermode', newHover); +} - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); +// buttons when more then one plot types are present - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____108(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____108(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); } +}; - recomputeAxisLists(); +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____108(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - var allFixedRanges = !yActive && !xActive; + var aobj = setSpikelineVisibility(gd); - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; + _$registry_248.call('relayout', gd, aobj); } +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_225(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_211.list(gd, null, true); + var aobj = {}; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + var ax, axName; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - if(numClicks === 2 && !singleEnd) doubleClick(); + return aobj; +} - if(isMainDrag) { - _$fx_88.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____108(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if(ax.fixedrange) return; +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; + 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); - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_10.select(dragger) - .call(_$svg_text_utils_186.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_247.call('relayout', gd, attrStr, v); - } - }); - } - } + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; } - }; - - _$dragelement_68.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + } - // collected changes to be made to the plot by relayout at the end - var updates = {}; + _$registry_248.call('relayout', gd, aObj); +} - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_28(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); +'use strict'; - clearSelect(zoomlayer); - } +/* removed: var _$d3_10 = require('d3'); */; - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +/** + * 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'); - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } + this.update(opts.graphInfo, opts.buttons); - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; + this.container.appendChild(this.element); +} - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } +var proto = ModeBar.prototype; - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } +/** + * 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; - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); + var context = this.graphInfo._context; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; } + else this.element.className = 'modebar'; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_212.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - var pc = gd.querySelector('.plotly'); + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - recomputeAxisLists(); + this.updateButtons(buttons); - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - clearTimeout(redrawTimer); + this.updateActiveButton(); +}; - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_165.log('Did not find wheel motion attributes: ', e); - return; - } +proto.updateButtons = function(buttons) { + var _this = this; - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - var axRange = _$lib_165.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + 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); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +proto.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * 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, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_10.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +proto.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_224(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_224(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * 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, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_10.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_166.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * 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((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_247.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_247.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_247.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +proto.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_166._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +proto.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +proto.destroy = function() { + _$lib_166.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_247.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_10.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_165.syncOrAsync([ - _$plots_240.previousPromises, - function() { _$registry_247.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_111 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_211 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_337 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_248 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_224(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_111 = require('./modebar'); */; +/* removed: var _$buttons_108 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_215[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_110 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_165.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_165.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_111(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_71.setTranslate, clipDx, clipDy) - .call(_$drawing_71.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_71.setTranslate, plotDx, plotDy) - .call(_$drawing_71.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_71.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_71.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_71.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_71.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_108[button]); } - } - - return dragger; -} - -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - dragger3.call(_$setCursor_184, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_10.select(dragger).call(_$drawing_71.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_10.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_10.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_211.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_46.background, - stroke: _$color_46.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_248.traceIs(trace, 'scatter-like')) { + if(_$subtypes_337.hasMarkers(trace) || _$subtypes_337.hasText(trace)) { + selectable = true; + } + } else if(_$registry_248.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_10.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_165.notifier(_$lib_165._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_108[button] !== undefined) { + customButtons[i][j] = _$buttons_108[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_165.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_16) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_215 = { - makeDragBox: makeDragBox, +var _$modebar_109 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_109.manage = _$manageModeBar_110; +var _$constraints_215 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -56397,152 +56576,202 @@ var _$dragbox_215 = { 'use strict'; -/* removed: var _$d3_10 = require('d3'); */; +var __id2name_215 = _$axis_ids_211.id2name; +/* removed: var _$scaleZoom_224 = require('./scale_zoom'); */; +var __makePadFn_215 = _$autorange_207.makePadFn; -/* removed: var _$fx_88 = require('../../components/fx'); */; -/* removed: var _$dragelement_68 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_148.ALMOST_EQUAL; -/* removed: var _$constants_212 = require('./constants'); */; -var __makeDragBox_216 = _$dragbox_215.makeDragBox; +var __FROM_BL_215 = _$alignment_146.FROM_BL; -var _$initInteractions_216 = function initInteractions(gd) { + +_$constraints_215.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_10.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - 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'), - 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)); + 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_215(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_212.DRAGGERSIZE; + // 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; - // 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_216(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + if(mode === 'range') { + _$scaleZoom_224(ax, factor); + } + else { + // mode === 'domain' - 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) { - _$fx_88.hover(gd, evt, subplot); + 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_224(ax, factor); + continue; } - }; - _$fx_88.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_215(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_68.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_216(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_216(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_216(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_216(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_216(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_216(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_216(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_216(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_216(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_216(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_215.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_88.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_88.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_215[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_199 = {}; +var _$subroutines_200 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -56554,21 +56783,27 @@ var _$subroutines_199 = {}; 'use strict'; /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$registry_247 = require('../registry'); */; +/* removed: var _$registry_248 = require('../registry'); */; /* removed: var _$plots_240 = require('../plots/plots'); */; -/* removed: var _$lib_165 = require('../lib'); */; + +/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$clearGlCanvases_155 = require('../lib/clear_gl_canvases'); */; /* removed: var _$color_46 = require('../components/color'); */; /* removed: var _$drawing_71 = require('../components/drawing'); */; /* removed: var _$titles_139 = require('../components/titles'); */; /* removed: var _$modebar_109 = require('../components/modebar'); */; -/* removed: var _$axes_207 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_216 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_212 = require('../plots/cartesian/constants'); */; + +/* removed: var _$axes_208 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_213 = require('../plots/cartesian/constants'); */; /* removed: var _$alignment_146 = require('../constants/alignment'); */; +/* removed: var _$constraints_215 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_215.enforce; +var cleanAxisConstraints = _$constraints_215.clean; +var __doAutoRange_200 = _$autorange_207.doAutoRange; -_$subroutines_199.layoutStyles = function(gd) { - return _$lib_165.syncOrAsync([_$plots_240.doAutoMargin, _$subroutines_199.lsInner], gd); +_$subroutines_200.layoutStyles = function(gd) { + return _$lib_166.syncOrAsync([_$plots_240.doAutoMargin, _$subroutines_200.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -56586,11 +56821,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_199.lsInner = function(gd) { +_$subroutines_200.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_207.list(gd); + var axList = _$axes_208.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -56669,31 +56904,17 @@ _$subroutines_199.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_166.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -56725,23 +56946,17 @@ _$subroutines_199.lsInner = function(gd) { } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_166.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); _$drawing_71.setTranslate(plotinfo.plot, xa._offset, ya._offset); @@ -56750,16 +56965,16 @@ _$subroutines_199.lsInner = function(gd) { if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } _$drawing_71.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_212.traceLayerClasses.length; i++) { - var layer = _$constants_212.traceLayerClasses[i]; + for(i = 0; i < _$constants_213.traceLayerClasses.length; i++) { + var layer = _$constants_213.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { plotinfo.plot.selectAll('g.' + layer).call(_$drawing_71.setClipUrl, layerClipId); } @@ -56883,8 +57098,8 @@ _$subroutines_199.lsInner = function(gd) { plotinfo.ylines.attr('d', yPath); }); - _$axes_207.makeClipPaths(gd); - _$subroutines_199.drawMainTitle(gd); + _$axes_208.makeClipPaths(gd); + _$subroutines_200.drawMainTitle(gd); _$modebar_109.manage(gd); return gd._promises.length && Promise.all(gd._promises); @@ -56941,7 +57156,7 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_199.drawMainTitle = function(gd) { +_$subroutines_200.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; _$titles_139.draw(gd, 'gtitle', { @@ -56960,7 +57175,7 @@ _$subroutines_199.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_199.doTraceStyle = function(gd) { +_$subroutines_200.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -56970,12 +57185,12 @@ _$subroutines_199.doTraceStyle = function(gd) { } _$plots_240.style(gd); - _$registry_247.getComponentMethod('legend', 'draw')(gd); + _$registry_248.getComponentMethod('legend', 'draw')(gd); return _$plots_240.previousPromises(gd); }; -_$subroutines_199.doColorBars = function(gd) { +_$subroutines_200.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -56983,7 +57198,7 @@ _$subroutines_199.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_247.traceIs(trace, 'contour')) { + if(_$registry_248.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -56992,7 +57207,7 @@ _$subroutines_199.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_247.traceIs(trace, 'markerColorscale')) { + if(_$registry_248.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); @@ -57003,28 +57218,33 @@ _$subroutines_199.doColorBars = function(gd) { }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_199.layoutReplot = function(gd) { +_$subroutines_200.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_247.call('plot', gd, '', layout); + return _$registry_248.call('plot', gd, '', layout); }; -_$subroutines_199.doLegend = function(gd) { - _$registry_247.getComponentMethod('legend', 'draw')(gd); +_$subroutines_200.doLegend = function(gd) { + _$registry_248.getComponentMethod('legend', 'draw')(gd); return _$plots_240.previousPromises(gd); }; -_$subroutines_199.doTicksRelayout = function(gd) { - _$axes_207.doTicks(gd, 'redraw'); - _$subroutines_199.drawMainTitle(gd); +_$subroutines_200.doTicksRelayout = function(gd) { + _$axes_208.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_155(gd); + _$registry_248.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_200.drawMainTitle(gd); return _$plots_240.previousPromises(gd); }; -_$subroutines_199.doModeBar = function(gd) { +_$subroutines_200.doModeBar = function(gd) { var fullLayout = gd._fullLayout; _$modebar_109.manage(gd); - _$initInteractions_216(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; @@ -57034,7 +57254,7 @@ _$subroutines_199.doModeBar = function(gd) { return _$plots_240.previousPromises(gd); }; -_$subroutines_199.doCamera = function(gd) { +_$subroutines_200.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -57046,212 +57266,86 @@ _$subroutines_199.doCamera = function(gd) { } }; -var _$constraints_214 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_214 = _$axis_ids_210.id2name; -/* removed: var _$scaleZoom_224 = require('./scale_zoom'); */; -var __makePadFn_214 = _$autorange_206.makePadFn; - -var ALMOST_EQUAL = _$numerical_148.ALMOST_EQUAL; - -var __FROM_BL_214 = _$alignment_146.FROM_BL; - - -_$constraints_214.enforce = function enforceAxisConstraints(gd) { +_$subroutines_200.drawData = function(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_214(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_248.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_224(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_224(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_155(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_214(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_240.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_248.getComponentMethod('shapes', 'draw')(gd); + _$registry_248.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_240.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_200.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_208.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_200(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_214.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_214[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_200.finalDraw = function(gd) { + _$registry_248.getComponentMethod('shapes', 'draw')(gd); + _$registry_248.getComponentMethod('images', 'draw')(gd); + _$registry_248.getComponentMethod('annotations', 'draw')(gd); + _$registry_248.getComponentMethod('legend', 'draw')(gd); + _$registry_248.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_248.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_248.getComponentMethod('sliders', 'draw')(gd); + _$registry_248.getComponentMethod('updatemenus', 'draw')(gd); +}; var _$micropolar_244 = {}; /** @@ -57263,8 +57357,8 @@ var _$micropolar_244 = {}; */ /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../../../lib'); */; -var __extendDeepAll_244 = _$lib_165.extendDeepAll; +/* removed: var _$lib_166 = require('../../../lib'); */; +var __extendDeepAll_244 = _$lib_166.extendDeepAll; var __MID_SHIFT_244 = _$alignment_146.MID_SHIFT; var µ = _$micropolar_244 = { version: '0.2.2' }; @@ -58752,12 +58846,12 @@ var _$micropolar_manager_245 = {}; 'use strict'; /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../../../lib'); */; +/* removed: var _$lib_166 = require('../../../lib'); */; /* removed: var _$color_46 = require('../../../components/color'); */; /* removed: var _$micropolar_244 = require('./micropolar'); */; /* removed: var _$UndoManager_246 = require('./undo_manager'); */; -var __extendDeepAll_245 = _$lib_165.extendDeepAll; +var __extendDeepAll_245 = _$lib_166.extendDeepAll; var manager = _$micropolar_manager_245 = {}; @@ -58839,7 +58933,7 @@ var Polar = _$legacy_243 = _$micropolar_244; Polar.manager = _$micropolar_manager_245; -var _$plot_api_196 = {}; +var _$plot_api_197 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -58856,33 +58950,29 @@ var _$plot_api_196 = {}; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; /* removed: var _$hasHover_15 = require('has-hover'); */; -/* removed: var _$lib_165 = require('../lib'); */; -/* removed: var _$Events_158 = require('../lib/events'); */; -/* removed: var _$queue_179 = require('../lib/queue'); */; +/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$Events_159 = require('../lib/events'); */; +/* removed: var _$queue_180 = require('../lib/queue'); */; -/* removed: var _$registry_247 = require('../registry'); */; -/* removed: var _$plot_schema_198 = require('./plot_schema'); */; +/* removed: var _$registry_248 = require('../registry'); */; +/* removed: var _$plot_schema_199 = require('./plot_schema'); */; /* removed: var _$plots_240 = require('../plots/plots'); */; /* removed: var _$legacy_243 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_216 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$axes_207 = require('../plots/cartesian/axes'); */; +/* removed: var _$axes_208 = require('../plots/cartesian/axes'); */; /* removed: var _$drawing_71 = require('../components/drawing'); */; /* removed: var _$color_46 = require('../components/color'); */; +var initInteractions = _$graph_interact_217.initInteractions; /* removed: var _$xmlns_namespaces_150 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_186 = require('../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_187 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_197 = require('./plot_config'); */; -/* removed: var _$manage_arrays_195 = require('./manage_arrays'); */; -/* removed: var _$helpers_193 = require('./helpers'); */; -/* removed: var _$subroutines_199 = require('./subroutines'); */; -/* removed: var _$edit_types_192 = require('./edit_types'); */; +/* removed: var _$plot_config_198 = require('./plot_config'); */; +/* removed: var _$manage_arrays_196 = require('./manage_arrays'); */; +/* removed: var _$helpers_194 = require('./helpers'); */; +/* removed: var _$subroutines_200 = require('./subroutines'); */; +/* removed: var _$edit_types_193 = require('./edit_types'); */; -/* removed: var _$constants_212 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_214 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_214.enforce; -var cleanAxisConstraints = _$constraints_214.clean; -var __doAutoRange_196 = _$autorange_206.doAutoRange; +var AX_NAME_PATTERN = _$constants_213.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -58908,15 +58998,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_196.plot = function(gd, data, layout, config) { +_$plot_api_197.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_165.getGraphDiv(gd); + gd = _$lib_166.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_158.init(gd); + _$Events_159.init(gd); - if(_$lib_165.isPlainObject(data)) { + if(_$lib_166.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -58924,19 +59014,19 @@ _$plot_api_196.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_158.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_159.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_165.isPlotDiv(gd)) { - _$lib_165.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_166.isPlotDiv(gd)) { + _$lib_166.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_196.addFrames(gd, frames); + return _$plot_api_197.addFrames(gd, frames); } } @@ -58955,6 +59045,9 @@ _$plot_api_196.plot = function(gd, data, layout, config) { // so we can share cached text across tabs _$drawing_71.makeTester(); + // clear stashed base url + delete _$drawing_71.baseUrl; + // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all @@ -58966,7 +59059,7 @@ _$plot_api_196.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_193.cleanData(data, gd.data); + _$helpers_194.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -58977,7 +59070,7 @@ _$plot_api_196.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_193.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_194.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -58999,7 +59092,7 @@ _$plot_api_196.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_165.log('Legacy polar charts are deprecated!'); + _$lib_166.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -59020,7 +59113,7 @@ _$plot_api_196.plot = function(gd, data, layout, config) { _$drawing_71.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_207.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_208.saveShowSpikeInitial(gd); // prepare the data and find the autorange @@ -59087,9 +59180,7 @@ _$plot_api_196.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_165.syncOrAsync([ - _$subroutines_199.layoutStyles - ], gd); + return _$plots_240.previousPromises(gd); } // draw anything that can affect margins. @@ -59097,10 +59188,10 @@ _$plot_api_196.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_247.getComponentMethod('legend', 'draw')(gd); - _$registry_247.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_247.getComponentMethod('sliders', 'draw')(gd); - _$registry_247.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_248.getComponentMethod('legend', 'draw')(gd); + _$registry_248.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_248.getComponentMethod('sliders', 'draw')(gd); + _$registry_248.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; @@ -59119,9 +59210,9 @@ _$plot_api_196.plot = function(gd, data, layout, config) { function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_165.syncOrAsync([ + return _$lib_166.syncOrAsync([ marginPushers, - _$subroutines_199.layoutStyles + _$subroutines_200.layoutStyles ], gd); } @@ -59142,7 +59233,7 @@ _$plot_api_196.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_165.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_166.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -59156,113 +59247,31 @@ _$plot_api_196.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_247.getComponentMethod('errorbars', 'calc')(gd); + _$registry_248.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_165.syncOrAsync([ - _$registry_247.getComponentMethod('shapes', 'calcAutorange'), - _$registry_247.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_166.syncOrAsync([ + _$registry_248.getComponentMethod('shapes', 'calcAutorange'), + _$registry_248.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_247.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_248.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_207.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_196(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_200.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_207.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_208.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_207.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_247.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_240.style(gd); - - // show annotations and shapes - _$registry_247.getComponentMethod('shapes', 'draw')(gd); - _$registry_247.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_240.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_240.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_247.getComponentMethod('shapes', 'draw')(gd); - _$registry_247.getComponentMethod('images', 'draw')(gd); - _$registry_247.getComponentMethod('annotations', 'draw')(gd); - _$registry_247.getComponentMethod('legend', 'draw')(gd); - _$registry_247.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_247.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_247.getComponentMethod('sliders', 'draw')(gd); - _$registry_247.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_208.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ @@ -59273,19 +59282,20 @@ _$plot_api_196.plot = function(gd, data, layout, config) { marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_199.layoutStyles); + seq.push(_$subroutines_200.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_216, + _$subroutines_200.drawData, + _$subroutines_200.finalDraw, + initInteractions, + _$plots_240.addLinks, _$plots_240.rehover, _$plots_240.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_165.syncOrAsync(seq, gd); + var plotDone = _$lib_166.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -59294,15 +59304,15 @@ _$plot_api_196.plot = function(gd, data, layout, config) { }); }; -_$plot_api_196.setPlotConfig = function setPlotConfig(obj) { - return _$lib_165.extendFlat(_$plot_config_197, obj); +_$plot_api_197.setPlotConfig = function setPlotConfig(obj) { + return _$lib_166.extendFlat(_$plot_config_198, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_165.error(e); + _$lib_166.error(e); } } @@ -59312,7 +59322,7 @@ function opaqueSetBackground(gd, bgColor) { } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_165.extendDeep({}, _$plot_config_197); + if(!gd._context) gd._context = _$lib_166.extendDeep({}, _$plot_config_198); var context = gd._context; var i, keys, key; @@ -59428,7 +59438,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_186.convertToTspans, gd); + this.call(_$svg_text_utils_187.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -59437,7 +59447,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_165._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_166._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -59456,7 +59466,7 @@ function plotPolar(gd, data, layout) { } var setContenteditable = function() { - this.call(_$svg_text_utils_186.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_187.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -59478,18 +59488,18 @@ function plotPolar(gd, data, layout) { } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_196.redraw = function(gd) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.redraw = function(gd) { + gd = _$lib_166.getGraphDiv(gd); - if(!_$lib_165.isPlotDiv(gd)) { + if(!_$lib_166.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_193.cleanData(gd.data, gd.data); - _$helpers_193.cleanLayout(gd.layout); + _$helpers_194.cleanData(gd.data, gd.data); + _$helpers_194.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_196.plot(gd).then(function() { + return _$plot_api_197.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -59503,14 +59513,14 @@ _$plot_api_196.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_196.newPlot = function(gd, data, layout, config) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.newPlot = function(gd, data, layout, config) { + gd = _$lib_166.getGraphDiv(gd); // remove gl contexts - _$plots_240.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_240.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); _$plots_240.purge(gd); - return _$plot_api_196.plot(gd, data, layout, config); + return _$plot_api_197.plot(gd, data, layout, config); }; /** @@ -59663,12 +59673,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_165.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_166.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_165.isPlainObject(update)) { + if(!_$lib_166.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -59711,7 +59721,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_165.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_166.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -59731,7 +59741,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_165.nestedProperty(trace, key); + prop = _$lib_166.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -59740,10 +59750,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_165.isArrayOrTypedArray(insert)) { + if(!_$lib_166.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_165.isArrayOrTypedArray(target)) { + if(!_$lib_166.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -59838,13 +59848,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_196.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_166.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_165.isTypedArray(target)) { + if(_$lib_166.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -59889,20 +59899,20 @@ _$plot_api_196.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_196.redraw(gd); + var promise = _$plot_api_197.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_179.add(gd, _$plot_api_196.prependTraces, undoArgs, extendTraces, arguments); + _$queue_180.add(gd, _$plot_api_197.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_196.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_166.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_165.isTypedArray(target)) { + if(_$lib_166.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -59946,9 +59956,9 @@ _$plot_api_196.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_196.redraw(gd); + var promise = _$plot_api_197.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_179.add(gd, _$plot_api_196.extendTraces, undoArgs, prependTraces, arguments); + _$queue_180.add(gd, _$plot_api_197.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -59962,11 +59972,11 @@ _$plot_api_196.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_196.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_166.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_196.deleteTraces, + undoFunc = _$plot_api_197.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -59983,10 +59993,10 @@ _$plot_api_196.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_165.extendFlat({}, trace); + return _$lib_166.extendFlat({}, trace); }); - _$helpers_193.cleanData(traces, gd.data); + _$helpers_194.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -60001,8 +60011,8 @@ _$plot_api_196.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_196.redraw(gd); - _$queue_179.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_197.redraw(gd); + _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -60025,10 +60035,10 @@ _$plot_api_196.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_179.startSequence(gd); - _$queue_179.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_196.moveTraces(gd, currentIndices, newIndices); - _$queue_179.stopSequence(gd); + _$queue_180.startSequence(gd); + _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_197.moveTraces(gd, currentIndices, newIndices); + _$queue_180.stopSequence(gd); return promise; }; @@ -60039,11 +60049,11 @@ _$plot_api_196.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_196.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_166.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_196.addTraces, + undoFunc = _$plot_api_197.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -60062,14 +60072,14 @@ _$plot_api_196.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_165.sorterDes); + indices.sort(_$lib_166.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_196.redraw(gd); - _$queue_179.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_197.redraw(gd); + _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -60105,8 +60115,8 @@ _$plot_api_196.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_196.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_166.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -60166,8 +60176,8 @@ _$plot_api_196.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_196.redraw(gd); - _$queue_179.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_197.redraw(gd); + _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -60202,55 +60212,55 @@ _$plot_api_196.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_196.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_165.getGraphDiv(gd); - _$helpers_193.clearPromiseQueue(gd); +_$plot_api_197.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_166.getGraphDiv(gd); + _$helpers_194.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_165.isPlainObject(astr)) { + else if(_$lib_166.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_165.extendFlat({}, astr); + aobj = _$lib_166.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_165.warn('Restyle fail.', astr, val, _traces); + _$lib_166.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_193.coerceTraceIndices(gd, _traces); + var traces = _$helpers_194.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_193.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_194.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_196.plot); + seq.push(_$plot_api_197.plot); } else { seq.push(_$plots_240.previousPromises); _$plots_240.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_199.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_199.doColorBars); + if(flags.style) seq.push(_$subroutines_200.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_200.doColorBars); } seq.push(_$plots_240.rehover); - _$queue_179.add(gd, + _$queue_180.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_165.syncOrAsync(seq, gd); + var plotDone = _$lib_166.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -60273,7 +60283,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_192.traceFlags(); + var flags = _$edit_types_193.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -60286,7 +60296,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_207.id2name(axid); + var axName = _$axes_208.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -60305,13 +60315,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_193.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_194.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_165.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_166.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_165.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_166.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -60328,7 +60338,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_193.hasParent(aobj, ai)) { + if(_$helpers_194.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -60343,7 +60353,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_165.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_166.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -60359,17 +60369,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_165.nestedProperty(cont, ai); + param = _$lib_166.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_198.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_199.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_165.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_166.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -60409,19 +60419,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_165.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_165.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_165.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_166.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_166.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_166.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_165.nestedProperty(cont, 'marker.color') - .set(_$lib_165.nestedProperty(cont, 'marker.colors').get()); + _$lib_166.nestedProperty(cont, 'marker.color') + .set(_$lib_166.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_247.traceIs(cont, 'cartesian')) { - _$lib_165.nestedProperty(cont, 'marker.colors') - .set(_$lib_165.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_248.traceIs(cont, 'cartesian')) { + _$lib_166.nestedProperty(cont, 'marker.colors') + .set(_$lib_166.nestedProperty(cont, 'marker.color').get()); } } @@ -60450,23 +60460,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_193.swapXYData(cont); + _$helpers_194.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(_$plots_240.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_193.manageArrayContainers(param, newVal, undoit); + _$helpers_194.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_165.isArrayOrTypedArray(newVal) || _$lib_165.isArrayOrTypedArray(oldVal)) + _$lib_166.isArrayOrTypedArray(newVal) || _$lib_166.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_192.update(flags, valObject); + else _$edit_types_193.update(flags, valObject); } else { /* @@ -60485,12 +60495,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_207.swap(gd, traces); + _$axes_208.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_165.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_166.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -60505,7 +60515,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_247.traceIs(trace, 'cartesian')) { + if(_$registry_248.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -60522,7 +60532,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_207.list(gd); + var axList = _$axes_208.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -60543,7 +60553,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_165.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_166.extendDeepNoArrays([], [redoit, traces]) }; } @@ -60567,9 +60577,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_196.relayout = function relayout(gd, astr, val) { - gd = _$lib_165.getGraphDiv(gd); - _$helpers_193.clearPromiseQueue(gd); +_$plot_api_197.relayout = function relayout(gd, astr, val) { + gd = _$lib_166.getGraphDiv(gd); + _$helpers_194.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -60578,21 +60588,21 @@ _$plot_api_196.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_165.isPlainObject(astr)) { - aobj = _$lib_165.extendFlat({}, astr); + } else if(_$lib_166.isPlainObject(astr)) { + aobj = _$lib_166.extendFlat({}, astr); } else { - _$lib_165.warn('Relayout fail.', astr, val); + _$lib_166.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_193.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_194.clearAxisAutomargins(gd); // fill in redraw sequence @@ -60602,26 +60612,50 @@ _$plot_api_196.relayout = function relayout(gd, astr, val) { var seq = [_$plots_240.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_199.layoutReplot); + seq.push(_$subroutines_200.layoutReplot); } else if(Object.keys(aobj).length) { _$plots_240.supplyDefaults(gd); - if(flags.legend) seq.push(_$subroutines_199.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_199.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_199.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_199.doModeBar); - if(flags.camera) seq.push(_$subroutines_199.doCamera); + if(flags.legend) seq.push(_$subroutines_200.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_200.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_200.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_200.doTicksRelayout, + _$subroutines_200.drawData, + _$subroutines_200.finalDraw + ); + } + + if(flags.ticks) seq.push(_$subroutines_200.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_200.doModeBar); + if(flags.camera) seq.push(_$subroutines_200.doCamera); } seq.push(_$plots_240.rehover); - _$queue_179.add(gd, + _$queue_180.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_165.syncOrAsync(seq, gd); + var plotDone = _$lib_166.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -60634,7 +60668,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_207.list(gd), + axes = _$axes_208.list(gd), arrayEdits = {}, arrayStr, i, @@ -60657,7 +60691,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_192.layoutFlags(); + var flags = _$edit_types_193.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -60676,9 +60710,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_193.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_194.hasParent(aobj, attr)) return; - var p = _$lib_165.nestedProperty(layout, attr); + var p = _$lib_166.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -60692,18 +60726,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_207.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_208.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_193.hasParent(aobj, ai)) { + if(_$helpers_194.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_165.nestedProperty(layout, ai); + var p = _$lib_166.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -60715,8 +60749,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_165.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_165.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_166.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_166.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -60727,11 +60761,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_198.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_199.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_165.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_166.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -60745,12 +60779,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_165.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_165.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_165.nestedProperty(fullLayout, ptrunk).get(); + _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_166.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -60758,7 +60792,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_165.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -60818,8 +60852,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_247.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_247.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_248.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_248.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -60827,18 +60861,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_165.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_212.AX_NAME_PATTERN)) { - var fullProp = _$lib_165.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_166.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_247.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_247.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_248.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_248.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -60847,12 +60881,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_195.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_196.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_165.nestedProperty(layout, arrayStr); + var componentArray = _$lib_166.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -60862,28 +60896,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_192.update(flags, updateValObject); + else _$edit_types_193.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_195.isAddVal(vi)) { + if(_$manage_arrays_196.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_195.isRemoveVal(vi)) { + else if(_$manage_arrays_196.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_165.warn('unrecognized full object value', aobj); + else _$lib_166.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_192.update(flags, updateValObject); - + else { + _$edit_types_193.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -60912,7 +60947,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_192.update(flags, valObject); + else if(valObject) _$edit_types_193.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -60921,8 +60956,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_195.applyContainerArrayChanges(gd, - _$lib_165.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_196.applyContainerArrayChanges(gd, + _$lib_166.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -60940,7 +60975,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_207.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_208.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -60964,7 +60999,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_165.extendDeep({}, redoit) + eventData: _$lib_166.extendDeep({}, redoit) }; } @@ -60986,9 +61021,9 @@ function updateAutosize(gd) { // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_165.isPlainObject(obj)) return false; + if(!_$lib_166.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_207.getFromId(gd, axRef); + ax = _$axes_208.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -60998,7 +61033,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_207.getFromId(gd, axLetter); + ax = _$axes_208.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -61018,32 +61053,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_196.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_165.getGraphDiv(gd); - _$helpers_193.clearPromiseQueue(gd); +_$plot_api_197.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_166.getGraphDiv(gd); + _$helpers_194.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_165.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_165.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_166.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_166.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_193.coerceTraceIndices(gd, _traces); + var traces = _$helpers_194.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_165.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_166.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_165.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_166.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_193.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_193.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_194.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_194.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -61057,35 +61092,43 @@ _$plot_api_196.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_196.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_197.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_196.plot); + seq.push(_$plot_api_197.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_199.layoutReplot); + seq.push(_$subroutines_200.layoutReplot); } else { seq.push(_$plots_240.previousPromises); _$plots_240.supplyDefaults(gd); - if(restyleFlags.style) seq.push(_$subroutines_199.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_199.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_199.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_199.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_199.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_199.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_199.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_200.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_200.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_200.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_200.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_200.doAutoRangeAndConstraints, + _$subroutines_200.doTicksRelayout, + _$subroutines_200.drawData, + _$subroutines_200.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_200.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_200.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_200.doCamera); } seq.push(_$plots_240.rehover); - _$queue_179.add(gd, + _$queue_180.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_165.syncOrAsync(seq, gd); + var plotDone = _$lib_166.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -61121,23 +61164,23 @@ _$plot_api_196.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_196.react = function(gd, data, layout, config) { +_$plot_api_197.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_196.addFrames(gd, frames); } + function addFrames() { return _$plot_api_197.addFrames(gd, frames); } - gd = _$lib_165.getGraphDiv(gd); + gd = _$lib_166.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_165.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_196.newPlot(gd, data, layout, config); + if(!_$lib_166.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_197.newPlot(gd, data, layout, config); } else { - if(_$lib_165.isPlainObject(data)) { + if(_$lib_166.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -61149,16 +61192,16 @@ _$plot_api_196.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_165.extendDeep({}, gd._context); + var oldConfig = _$lib_166.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_193.cleanData(gd.data, []); + _$helpers_194.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_193.cleanLayout(gd.layout); + _$helpers_194.cleanLayout(gd.layout); _$plots_240.supplyDefaults(gd); @@ -61182,7 +61225,7 @@ _$plot_api_196.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_193.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_194.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -61198,21 +61241,21 @@ _$plot_api_196.react = function(gd, data, layout, config) { if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_196.plot); + seq.push(_$plot_api_197.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_247.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_165.noop) { + var drawOne = _$registry_248.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_166.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_247.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_165.noop) { + var draw = _$registry_248.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_166.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -61221,18 +61264,26 @@ _$plot_api_196.react = function(gd, data, layout, config) { } seq.push(_$plots_240.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_199.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_199.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_199.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_199.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_199.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_199.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_199.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_200.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_200.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_200.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_200.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_200.doAutoRangeAndConstraints, + _$subroutines_200.doTicksRelayout, + _$subroutines_200.drawData, + _$subroutines_200.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_200.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_200.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_200.doCamera); } seq.push(_$plots_240.rehover); - plotDone = _$lib_165.syncOrAsync(seq, gd); + plotDone = _$lib_166.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -61255,12 +61306,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_192.traceFlags(); + var flags = _$edit_types_193.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_198.getTraceValObject(trace, parts); + return _$plot_schema_199.getTraceValObject(trace, parts); } var diffOpts = { @@ -61270,11 +61321,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_207.getFromId(gd, trace.xaxis).autorange || - _$axes_207.getFromId(gd, trace.yaxis).autorange + _$axes_208.getFromId(gd, trace.xaxis).autorange || + _$axes_208.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -61287,11 +61344,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_192.layoutFlags(); + var flags = _$edit_types_193.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_198.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_199.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -61330,10 +61387,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_165.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_166.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_192.update(flags, valObject); + _$edit_types_193.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -61413,7 +61470,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_165.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_166.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -61425,7 +61482,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_165.isPlainObject(oldVal)) { + else if(!valType && _$lib_166.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -61479,7 +61536,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_165.isPlainObject(oldVal) && _$lib_165.isPlainObject(newVal)) { + if(_$lib_166.isPlainObject(oldVal) && _$lib_166.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -61490,7 +61547,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_165.isPlainObject(oldVal[i]) && _$lib_165.isPlainObject(newVal[i])) { + if(_$lib_166.isPlainObject(oldVal[i]) && _$lib_166.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -61535,10 +61592,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_196.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_166.getGraphDiv(gd); - if(!_$lib_165.isPlotDiv(gd)) { + if(!_$lib_166.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -61712,7 +61769,7 @@ _$plot_api_196.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts _$plots_240.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_193.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_194.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -61782,13 +61839,13 @@ _$plot_api_196.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_165.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_166.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_165.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_166.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -61817,10 +61874,10 @@ _$plot_api_196.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_165.isPlainObject(frameOrName)) { + } else if(_$lib_166.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_165.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_166.extendFlat({}, frameOrName)) }); } } @@ -61830,7 +61887,7 @@ _$plot_api_196.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_165.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_166.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -61899,14 +61956,14 @@ _$plot_api_196.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_196.addFrames = function(gd, frameList, indices) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.addFrames = function(gd, frameList, indices) { + gd = _$lib_166.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_165.isPlotDiv(gd)) { + if(!_$lib_166.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -61933,7 +61990,7 @@ _$plot_api_196.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_165.isPlainObject(frameList[i])) continue; + if(!_$lib_166.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -61945,14 +62002,14 @@ _$plot_api_196.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_165.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_166.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_165.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_166.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -61981,7 +62038,7 @@ _$plot_api_196.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_165.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_166.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -62014,7 +62071,7 @@ _$plot_api_196.addFrames = function(gd, frameList, indices) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_179) _$queue_179.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_180) _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_240.modifyFrames(gd, ops); }; @@ -62028,10 +62085,10 @@ _$plot_api_196.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_196.deleteFrames = function(gd, frameList) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.deleteFrames = function(gd, frameList) { + gd = _$lib_166.getGraphDiv(gd); - if(!_$lib_165.isPlotDiv(gd)) { + if(!_$lib_166.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -62061,7 +62118,7 @@ _$plot_api_196.deleteFrames = function(gd, frameList) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_179) _$queue_179.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_180) _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_240.modifyFrames(gd, ops); }; @@ -62072,20 +62129,21 @@ _$plot_api_196.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_196.purge = function purge(gd) { - gd = _$lib_165.getGraphDiv(gd); +_$plot_api_197.purge = function purge(gd) { + gd = _$lib_166.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_240.cleanPlot([], {}, fullData, fullLayout); + _$plots_240.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties _$plots_240.purge(gd); // purge event emitter methods - _$Events_158.purge(gd); + _$Events_159.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -62143,7 +62201,7 @@ function makePlotFramework(gd) { _$d3_10.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_165.randstr(otherUids); + fullLayout._uid = _$lib_166.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') @@ -62219,7 +62277,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_251 = {}; +var _$helpers_252 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -62231,7 +62289,7 @@ var _$helpers_251 = {}; 'use strict'; -_$helpers_251.getDelay = function(fullLayout) { +_$helpers_252.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -62241,7 +62299,7 @@ _$helpers_251.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_251.getRedrawFunc = function(gd) { +_$helpers_252.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -62266,11 +62324,11 @@ _$helpers_251.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_165 = require('../lib'); */; -var __EventEmitter_253 = _$EventEmitter_12.EventEmitter; +/* removed: var _$lib_166 = require('../lib'); */; +var __EventEmitter_254 = _$EventEmitter_12.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_253(); + var ev = opts.emitter || new __EventEmitter_254(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -62278,7 +62336,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_165.isIE() && format !== 'svg') { + if(_$lib_166.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -62369,7 +62427,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_253 = svgToImg; +var _$svgToImg_254 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -62384,7 +62442,7 @@ var _$svgToImg_253 = svgToImg; /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$lib_166 = require('../lib'); */; /* removed: var _$drawing_71 = require('../components/drawing'); */; /* removed: var _$color_46 = require('../components/color'); */; @@ -62409,7 +62467,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_255 = function toSVG(gd, format, scale) { +var _$toSVG_256 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -62532,7 +62590,7 @@ var _$toSVG_255 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_165.isIE()) { + if(_$lib_166.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -62557,14 +62615,14 @@ var _$toSVG_255 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_196 = require('./plot_api'); */; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$plot_api_197 = require('./plot_api'); */; +/* removed: var _$lib_166 = require('../lib'); */; -/* removed: var _$helpers_251 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_255 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_253 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_252 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_256 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_254 = require('../snapshot/svgtoimg'); */; -var __attrs_200 = { +var __attrs_201 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -62617,19 +62675,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_165.isPlainObject(gd)) { + if(_$lib_166.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_165.getGraphDiv(gd); - data = _$lib_165.extendDeep([], gd.data); - layout = _$lib_165.extendDeep({}, gd.layout); + gd = _$lib_166.getGraphDiv(gd); + data = _$lib_166.extendDeep([], gd.data); + layout = _$lib_166.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_165.validate(opts[attr], __attrs_200[attr]); + return !(attr in opts) || _$lib_166.validate(opts[attr], __attrs_201[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -62643,7 +62701,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_165.coerce(opts, fullOpts, __attrs_200, attr, dflt); + return _$lib_166.coerce(opts, fullOpts, __attrs_201, attr, dflt); } var format = coerce('format'); @@ -62660,31 +62718,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_165.extendFlat({}, layout); + var layoutImage = _$lib_166.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_165.extendFlat({}, config, { + var configImage = _$lib_166.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_251.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_252.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_251.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_252.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_255(clonedGd, format, scale); + var svg = _$toSVG_256(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_196.purge(clonedGd); + _$plot_api_197.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -62696,9 +62754,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_165.randstr(); + canvas.id = _$lib_166.randstr(); - _$svgToImg_253({ + _$svgToImg_254({ format: format, width: width, height: height, @@ -62725,7 +62783,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_196.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_197.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -62734,7 +62792,7 @@ function toImage(gd, opts) { }); } -var _$toImage_200 = toImage; +var _$toImage_201 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -62746,14 +62804,14 @@ var _$toImage_200 = toImage; 'use strict'; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$lib_166 = require('../lib'); */; /* removed: var _$plots_240 = require('../plots/plots'); */; -/* removed: var _$plot_schema_198 = require('./plot_schema'); */; -/* removed: var _$plot_config_197 = require('./plot_config'); */; +/* removed: var _$plot_schema_199 = require('./plot_schema'); */; +/* removed: var _$plot_config_198 = require('./plot_config'); */; -var __isPlainObject_201 = _$lib_165.isPlainObject; -var __isArray_201 = Array.isArray; -var __isArrayOrTypedArray_201 = _$lib_165.isArrayOrTypedArray; +var __isPlainObject_202 = _$lib_166.isPlainObject; +var __isArray_202 = Array.isArray; +var __isArrayOrTypedArray_202 = _$lib_166.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -62776,15 +62834,15 @@ var __isArrayOrTypedArray_201 = _$lib_165.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_201 = function valiate(data, layout) { - var schema = _$plot_schema_198.get(); +var _$valiate_202 = function valiate(data, layout) { + var schema = _$plot_schema_199.get(); var errorList = []; - var gd = {_context: _$lib_165.extendFlat({}, _$plot_config_197)}; + var gd = {_context: _$lib_166.extendFlat({}, _$plot_config_198)}; var dataIn, layoutIn; - if(__isArray_201(data)) { - gd.data = _$lib_165.extendDeep([], data); + if(__isArray_202(data)) { + gd.data = _$lib_166.extendDeep([], data); dataIn = data; } else { @@ -62793,8 +62851,8 @@ var _$valiate_201 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_201(layout)) { - gd.layout = _$lib_165.extendDeep({}, layout); + if(__isPlainObject_202(layout)) { + gd.layout = _$lib_166.extendDeep({}, layout); layoutIn = layout; } else { @@ -62818,7 +62876,7 @@ var _$valiate_201 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_201(traceIn)) { + if(!__isPlainObject_202(traceIn)) { errorList.push(format('object', base)); continue; } @@ -62838,13 +62896,13 @@ var _$valiate_201 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_201(traceIn, traceOut, traceSchema, errorList, base); + __crawl_202(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_201(transformsIn)) { + if(!__isArray_202(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -62854,7 +62912,7 @@ var _$valiate_201 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_201(transformsIn[j])) { + if(!__isPlainObject_202(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -62869,7 +62927,7 @@ var _$valiate_201 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_201(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_202(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -62877,13 +62935,13 @@ var _$valiate_201 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_201(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_202(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_201(objIn, objOut, schema, list, base, path) { +function __crawl_202(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -62908,10 +62966,10 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_201(valIn) && __isPlainObject_201(valOut)) { - __crawl_201(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_202(valIn) && __isPlainObject_202(valOut)) { + __crawl_202(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_201(valIn)) { + else if(isInfoArray && __isArray_202(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -62921,7 +62979,7 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_201(valIn[n])) { + if(__isArray_202(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -62930,7 +62988,7 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_165.validate(valInPart, item)) { + if(!_$lib_166.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -62948,7 +63006,7 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_165.validate(valInPart, item)) { + if(!_$lib_166.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -62957,7 +63015,7 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_201(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_202(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -62971,9 +63029,9 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_201(valIn[_index]) && __isPlainObject_201(valOut[j])) { + if(__isPlainObject_202(valIn[_index]) && __isPlainObject_202(valOut[j])) { indexList.push(_index); - __crawl_201(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_202(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -62982,7 +63040,7 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_201(valIn[j])) { + if(!__isPlainObject_202(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -62990,16 +63048,16 @@ function __crawl_201(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_201(valIn) && __isPlainObject_201(valOut)) { + else if(!__isPlainObject_202(valIn) && __isPlainObject_202(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_201(valIn) && __isArrayOrTypedArray_201(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_202(valIn) && __isArrayOrTypedArray_202(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_165.validate(valIn, nestedSchema)) { + else if(!_$lib_166.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -63019,7 +63077,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_165.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_166.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -63051,7 +63109,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_201(valIn) ? 'container' : 'key'; + var target = __isPlainObject_202(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -63077,7 +63135,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_201(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_202(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -63090,7 +63148,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_201(base)) { + if(__isArray_202(base)) { container = base[0]; trace = base[1]; } @@ -63103,7 +63161,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_165.log(msg); + _$lib_166.log(msg); return { code: code, @@ -63133,7 +63191,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_165.counterRegex('([a-z]+)'); +var idRegex = _$lib_166.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -63145,7 +63203,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_201(path)) return String(path); + if(!__isArray_202(path)) return String(path); var astr = ''; @@ -63234,7 +63292,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_250 = fileSaver; +var _$fileSaver_251 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -63247,9 +63305,9 @@ var _$fileSaver_250 = fileSaver; 'use strict'; -/* removed: var _$toImage_200 = require('../plot_api/to_image'); */; -/* removed: var _$lib_165 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_250 = require('./filesaver'); */; +/* removed: var _$toImage_201 = require('../plot_api/to_image'); */; +/* removed: var _$lib_166 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_251 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -63277,19 +63335,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_165.isIE() && opts.format !== 'svg') { + if(_$lib_166.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_200(gd, opts); + var promise = _$toImage_201(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_250(result, filename); + return _$fileSaver_251(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -63299,9 +63357,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_249 = downloadImage; +var _$downloadImage_250 = downloadImage; -var _$plot_api_194 = {}; +var _$plot_api_195 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -63312,29 +63370,29 @@ var _$plot_api_194 = {}; 'use strict'; -/* removed: var _$plot_api_196 = require('./plot_api'); */; - -_$plot_api_194.plot = _$plot_api_196.plot; -_$plot_api_194.newPlot = _$plot_api_196.newPlot; -_$plot_api_194.restyle = _$plot_api_196.restyle; -_$plot_api_194.relayout = _$plot_api_196.relayout; -_$plot_api_194.redraw = _$plot_api_196.redraw; -_$plot_api_194.update = _$plot_api_196.update; -_$plot_api_194.react = _$plot_api_196.react; -_$plot_api_194.extendTraces = _$plot_api_196.extendTraces; -_$plot_api_194.prependTraces = _$plot_api_196.prependTraces; -_$plot_api_194.addTraces = _$plot_api_196.addTraces; -_$plot_api_194.deleteTraces = _$plot_api_196.deleteTraces; -_$plot_api_194.moveTraces = _$plot_api_196.moveTraces; -_$plot_api_194.purge = _$plot_api_196.purge; -_$plot_api_194.addFrames = _$plot_api_196.addFrames; -_$plot_api_194.deleteFrames = _$plot_api_196.deleteFrames; -_$plot_api_194.animate = _$plot_api_196.animate; -_$plot_api_194.setPlotConfig = _$plot_api_196.setPlotConfig; - -_$plot_api_194.toImage = _$toImage_200; -_$plot_api_194.validate = _$valiate_201; -_$plot_api_194.downloadImage = _$downloadImage_249; +/* removed: var _$plot_api_197 = require('./plot_api'); */; + +_$plot_api_195.plot = _$plot_api_197.plot; +_$plot_api_195.newPlot = _$plot_api_197.newPlot; +_$plot_api_195.restyle = _$plot_api_197.restyle; +_$plot_api_195.relayout = _$plot_api_197.relayout; +_$plot_api_195.redraw = _$plot_api_197.redraw; +_$plot_api_195.update = _$plot_api_197.update; +_$plot_api_195.react = _$plot_api_197.react; +_$plot_api_195.extendTraces = _$plot_api_197.extendTraces; +_$plot_api_195.prependTraces = _$plot_api_197.prependTraces; +_$plot_api_195.addTraces = _$plot_api_197.addTraces; +_$plot_api_195.deleteTraces = _$plot_api_197.deleteTraces; +_$plot_api_195.moveTraces = _$plot_api_197.moveTraces; +_$plot_api_195.purge = _$plot_api_197.purge; +_$plot_api_195.addFrames = _$plot_api_197.addFrames; +_$plot_api_195.deleteFrames = _$plot_api_197.deleteFrames; +_$plot_api_195.animate = _$plot_api_197.animate; +_$plot_api_195.setPlotConfig = _$plot_api_197.setPlotConfig; + +_$plot_api_195.toImage = _$toImage_201; +_$plot_api_195.validate = _$valiate_202; +_$plot_api_195.downloadImage = _$downloadImage_250; /** * Copyright 2012-2018, Plotly, Inc. @@ -63347,10 +63405,10 @@ _$plot_api_194.downloadImage = _$downloadImage_249; 'use strict'; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$lib_166 = require('../lib'); */; -var __extendFlat_248 = _$lib_165.extendFlat; -var extendDeep = _$lib_165.extendDeep; +var __extendFlat_249 = _$lib_166.extendFlat; +var extendDeep = _$lib_166.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -63395,7 +63453,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_248 = function clonePlot(graphObj, options) { +var _$clonePlot_249 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -63468,9 +63526,9 @@ var _$clonePlot_248 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_248(scene.xaxis, axesImageOverride); - __extendFlat_248(scene.yaxis, axesImageOverride); - __extendFlat_248(scene.zaxis, axesImageOverride); + __extendFlat_249(scene.xaxis, axesImageOverride); + __extendFlat_249(scene.yaxis, axesImageOverride); + __extendFlat_249(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -63519,27 +63577,27 @@ var _$clonePlot_248 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_254 = _$EventEmitter_12.EventEmitter; +var __EventEmitter_255 = _$EventEmitter_12.EventEmitter; -/* removed: var _$registry_247 = require('../registry'); */; -/* removed: var _$lib_165 = require('../lib'); */; +/* removed: var _$registry_248 = require('../registry'); */; +/* removed: var _$lib_166 = require('../lib'); */; -/* removed: var _$helpers_251 = require('./helpers'); */; -/* removed: var _$clonePlot_248 = require('./cloneplot'); */; -/* removed: var _$toSVG_255 = require('./tosvg'); */; -/* removed: var _$svgToImg_253 = require('./svgtoimg'); */; +/* removed: var _$helpers_252 = require('./helpers'); */; +/* removed: var _$clonePlot_249 = require('./cloneplot'); */; +/* removed: var _$toSVG_256 = require('./tosvg'); */; +/* removed: var _$svgToImg_254 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_254(gd, opts) { +function __toImage_255(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_254(); + var ev = new __EventEmitter_255(); - var clone = _$clonePlot_248(gd, {format: 'png'}); + var clone = _$clonePlot_249(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -63548,15 +63606,15 @@ function __toImage_254(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_251.getDelay(clonedGd._fullLayout); + var delay = _$helpers_252.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_255(clonedGd); + var svg = _$toSVG_256(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_165.randstr(); + canvas.id = _$lib_166.randstr(); - ev = _$svgToImg_253({ + ev = _$svgToImg_254({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -63572,9 +63630,9 @@ function __toImage_254(gd, opts) { }, delay); } - var redrawFunc = _$helpers_251.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_252.getRedrawFunc(clonedGd); - _$registry_247.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_248.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -63585,7 +63643,7 @@ function __toImage_254(gd, opts) { return ev; } -var _$toImage_254 = __toImage_254; +var _$toImage_255 = __toImage_255; /** * Copyright 2012-2018, Plotly, Inc. @@ -63598,19 +63656,19 @@ var _$toImage_254 = __toImage_254; 'use strict'; -/* removed: var _$helpers_251 = require('./helpers'); */; +/* removed: var _$helpers_252 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_251.getDelay, - getRedrawFunc: _$helpers_251.getRedrawFunc, - clone: _$clonePlot_248, - toSVG: _$toSVG_255, - svgToImg: _$svgToImg_253, - toImage: _$toImage_254, - downloadImage: _$downloadImage_249 + getDelay: _$helpers_252.getDelay, + getRedrawFunc: _$helpers_252.getRedrawFunc, + clone: _$clonePlot_249, + toSVG: _$toSVG_256, + svgToImg: _$svgToImg_254, + toImage: _$toImage_255, + downloadImage: _$downloadImage_250 }; -var _$Snapshot_252 = Snapshot; +var _$Snapshot_253 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -63623,42 +63681,42 @@ var _$Snapshot_252 = Snapshot; 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_316 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_314 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_165.mergeArray(trace.text, cd, 'tx'); - _$lib_165.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_165.mergeArray(trace.customdata, cd, 'data'); - _$lib_165.mergeArray(trace.textposition, cd, 'tp'); + _$lib_166.mergeArray(trace.text, cd, 'tx'); + _$lib_166.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_166.mergeArray(trace.customdata, cd, 'data'); + _$lib_166.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_165.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_165.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_165.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_166.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_166.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_166.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_165.mergeArray(marker.size, cd, 'ms'); - _$lib_165.mergeArray(marker.opacity, cd, 'mo'); - _$lib_165.mergeArray(marker.symbol, cd, 'mx'); - _$lib_165.mergeArray(marker.color, cd, 'mc'); + _$lib_166.mergeArray(marker.size, cd, 'ms'); + _$lib_166.mergeArray(marker.opacity, cd, 'mo'); + _$lib_166.mergeArray(marker.symbol, cd, 'mx'); + _$lib_166.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_165.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_165.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_166.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_166.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_165.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_165.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_166.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_166.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -63677,15 +63735,15 @@ var _$arraysToCalcdata_316 = function arraysToCalcdata(cd, trace) { /* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$calc_53 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_339 = require('./subtypes'); */; +/* removed: var _$subtypes_337 = require('./subtypes'); */; -var _$calcMarkerColorscale_322 = function calcMarkerColorscale(trace) { - if(_$subtypes_339.hasLines(trace) && _$hasColorscale_60(trace, 'line')) { +var _$calcMarkerColorscale_320 = function calcMarkerColorscale(trace) { + if(_$subtypes_337.hasLines(trace) && _$hasColorscale_60(trace, 'line')) { _$calc_53(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_339.hasMarkers(trace)) { + if(_$subtypes_337.hasMarkers(trace)) { if(_$hasColorscale_60(trace, 'marker')) { _$calc_53(trace, trace.marker.color, 'marker', 'c'); } @@ -63706,19 +63764,19 @@ var _$calcMarkerColorscale_322 = function calcMarkerColorscale(trace) { 'use strict'; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_318 = _$lib_165.isArrayOrTypedArray; +var __isArrayOrTypedArray_316 = _$lib_166.isArrayOrTypedArray; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -var __BADNUM_318 = _$numerical_148.BADNUM; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; +var __BADNUM_316 = _$numerical_148.BADNUM; -/* removed: var _$subtypes_339 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_322 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_316 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_319 = require('./calc_selection'); */; +/* removed: var _$subtypes_337 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_320 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_314 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_317 = require('./calc_selection'); */; -function __calc_318(gd, trace) { - var xa = _$axes_207.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_207.getFromId(gd, trace.yaxis || 'y'); +function __calc_316(gd, trace) { + var xa = _$axes_208.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_208.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -63730,16 +63788,16 @@ function __calc_318(gd, trace) { for(var i = 0; i < serieslen; i++) { cd[i] = (_$fastIsnumeric_13(x[i]) && _$fastIsnumeric_13(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_318, y: __BADNUM_318}; + {x: __BADNUM_316, y: __BADNUM_316}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_316(cd, trace); - _$calcMarkerColorscale_322(trace); - _$calcSelection_319(cd, trace); + _$arraysToCalcdata_314(cd, trace); + _$calcMarkerColorscale_320(trace); + _$calcSelection_317(cd, trace); gd.firstscatter = false; return cd; @@ -63772,9 +63830,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_339.hasMarkers(trace) && !_$subtypes_339.hasText(trace)) + (!_$subtypes_337.hasMarkers(trace) && !_$subtypes_337.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -63793,12 +63851,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_207.expand(xa, x, xOptions); - _$axes_207.expand(ya, y, yOptions); + _$axes_208.expand(xa, x, xOptions); + _$axes_208.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_339.hasMarkers(trace)) return; + if(!_$subtypes_337.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -63816,10 +63874,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_318(marker.size)) { + if(__isArrayOrTypedArray_316(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_207.setConvert(ax); + _$axes_208.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -63834,8 +63892,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_318 = { - calc: __calc_318, +var _$calc_316 = { + calc: __calc_316, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -63853,7 +63911,7 @@ var _$calc_318 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_320 = function cleanData(fullData) { +var _$cleanData_318 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -63890,9 +63948,9 @@ var _$cleanData_320 = function cleanData(fullData) { 'use strict'; /* removed: var _$color_46 = require('../../components/color'); */; -var __isArrayOrTypedArray_326 = _$lib_165.isArrayOrTypedArray; +var __isArrayOrTypedArray_324 = _$lib_166.isArrayOrTypedArray; -var _$fillColorDefaults_326 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_324 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -63900,10 +63958,10 @@ var _$fillColorDefaults_326 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_326(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_324(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_326(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_324(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } @@ -63925,11 +63983,11 @@ var _$fillColorDefaults_326 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_330 = _$lib_165.isArrayOrTypedArray; +var __isArrayOrTypedArray_328 = _$lib_166.isArrayOrTypedArray; /* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_56 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_330 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_328 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); @@ -63938,7 +63996,7 @@ var _$lineDefaults_330 = function lineDefaults(traceIn, traceOut, defaultColor, _$colorScaleDefaults_56(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_330(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_328(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -63959,7 +64017,7 @@ var _$lineDefaults_330 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_332 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_330 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -63979,7 +64037,7 @@ var _$handleLineShapeDefaults_332 = function handleLineShapeDefaults(traceIn, tr /* removed: var _$hasColorscale_60 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_56 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_339 = require('./subtypes'); */; +/* removed: var _$subtypes_337 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -63987,8 +64045,8 @@ var _$handleLineShapeDefaults_332 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_335 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_339.isBubble(traceIn), +var _$markerDefaults_333 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_337.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -64057,17 +64115,17 @@ var _$markerDefaults_335 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_340 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_338 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_165.coerceFont(coerce, 'textfont', layout.font); + _$lib_166.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -64085,27 +64143,27 @@ var _$text_defaults_340 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$registry_247 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -/* removed: var _$attributes_317 = require('./attributes'); */; -/* removed: var _$constants_323 = require('./constants'); */; -/* removed: var _$subtypes_339 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_341 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_335 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_330 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_332 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_340 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_326 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_315 = require('./attributes'); */; +/* removed: var _$constants_321 = require('./constants'); */; +/* removed: var _$subtypes_337 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_339 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_333 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_328 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_330 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_338 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_324 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_324 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_322 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_317, attr, dflt); + return _$lib_166.coerce(traceIn, traceOut, _$attributes_315, attr, dflt); } - var len = _$handleXYDefaults_341(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_339(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_323.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_321.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -64115,24 +64173,24 @@ var _$supplyDefaults_324 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_339.hasLines(traceOut)) { - _$lineDefaults_330(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_332(traceIn, traceOut, coerce); + if(_$subtypes_337.hasLines(traceOut)) { + _$lineDefaults_328(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_330(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_339.hasMarkers(traceOut)) { - _$markerDefaults_335(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_337.hasMarkers(traceOut)) { + _$markerDefaults_333(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_339.hasText(traceOut)) { - _$text_defaults_340(traceIn, traceOut, layout, coerce); + if(_$subtypes_337.hasText(traceOut)) { + _$text_defaults_338(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_339.hasMarkers(traceOut) || _$subtypes_339.hasText(traceOut)) { + if(_$subtypes_337.hasMarkers(traceOut) || _$subtypes_337.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -64140,8 +64198,8 @@ var _$supplyDefaults_324 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_326(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_339.hasLines(traceOut)) _$handleLineShapeDefaults_332(traceIn, traceOut, coerce); + _$fillColorDefaults_324(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_337.hasLines(traceOut)) _$handleLineShapeDefaults_330(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -64149,11 +64207,11 @@ var _$supplyDefaults_324 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_247.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_248.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_165.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_166.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -64168,10 +64226,10 @@ var _$supplyDefaults_324 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; /* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$subtypes_339 = require('./subtypes'); */; +/* removed: var _$subtypes_337 = require('./subtypes'); */; -var _$getTraceColor_327 = function getTraceColor(trace, di) { +var _$getTraceColor_325 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes @@ -64202,7 +64260,7 @@ var _$getTraceColor_327 = function getTraceColor(trace, di) { else { lc = (trace.line || {}).color; return (lc && _$color_46.opacity(lc) && - _$subtypes_339.hasLines(trace) && trace.line.width) ? + _$subtypes_337.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -64218,14 +64276,14 @@ var _$getTraceColor_327 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; /* removed: var _$fx_88 = require('../../components/fx'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$getTraceColor_327 = require('./get_trace_color'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$getTraceColor_325 = require('./get_trace_color'); */; /* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$fillHoverText_325 = require('./fill_hover_text'); */; +/* removed: var _$fillHoverText_323 = require('./fill_hover_text'); */; -var _$hoverPoints_328 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_326 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -64278,8 +64336,8 @@ var _$hoverPoints_328 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_165.extendFlat(pointData, { - color: _$getTraceColor_327(trace, di), + _$lib_166.extendFlat(pointData, { + color: _$getTraceColor_325(trace, di), x0: xc - rad, x1: xc + rad, @@ -64292,8 +64350,8 @@ var _$hoverPoints_328 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_325(di, trace, pointData); - _$registry_247.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_323(di, trace, pointData); + _$registry_248.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -64365,7 +64423,7 @@ var _$hoverPoints_328 = function hoverPoints(pointData, xval, yval, hovermode) { color = trace.line.color; } - _$lib_165.extendFlat(pointData, { + _$lib_166.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -64399,14 +64457,14 @@ var _$hoverPoints_328 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_331 = _$numerical_148.BADNUM; -/* removed: var _$lib_165 = require('../../lib'); */; -var __segmentsIntersect_331 = _$lib_165.segmentsIntersect; -var constrain = _$lib_165.constrain; -/* removed: var _$constants_323 = require('./constants'); */; +var __BADNUM_329 = _$numerical_148.BADNUM; +/* removed: var _$lib_166 = require('../../lib'); */; +var __segmentsIntersect_329 = _$lib_166.segmentsIntersect; +var constrain = _$lib_166.constrain; +/* removed: var _$constants_321 = require('./constants'); */; -var _$linePoints_331 = function linePoints(d, opts) { +var _$linePoints_329 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -64415,7 +64473,7 @@ var _$linePoints_331 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_323.minTolerance; + var minTolerance = _$constants_321.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -64453,7 +64511,7 @@ var _$linePoints_331 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_331 || y === __BADNUM_331) return di.intoCenter || false; + if(x === __BADNUM_329 || y === __BADNUM_329) return di.intoCenter || false; return [x, y]; } @@ -64461,7 +64519,7 @@ var _$linePoints_331 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_323.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_321.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -64473,7 +64531,7 @@ var _$linePoints_331 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_323.maxScreensAway; + var maxScreensAway = _$constants_321.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -64502,7 +64560,7 @@ var _$linePoints_331 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_331(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_329(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -64556,7 +64614,7 @@ var _$linePoints_331 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_165.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_166.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -64809,7 +64867,7 @@ var _$linePoints_331 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_333 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_331 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -64851,17 +64909,17 @@ var _$linkTraces_333 = function linkTraces(gd, plotinfo, cdscatter) { /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; /* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$subtypes_339 = require('./subtypes'); */; -/* removed: var _$linePoints_331 = require('./line_points'); */; -/* removed: var _$linkTraces_333 = require('./link_traces'); */; -var __polygonTester_336 = _$polygon_177.tester; +/* removed: var _$subtypes_337 = require('./subtypes'); */; +/* removed: var _$linePoints_329 = require('./line_points'); */; +/* removed: var _$linkTraces_331 = require('./link_traces'); */; +var __polygonTester_334 = _$polygon_178.tester; -var _$plot_336 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_334 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -64870,9 +64928,8 @@ var _$plot_336 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -64884,7 +64941,7 @@ var _$plot_336 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_333(gd, plotinfo, cdscatter); + _$linkTraces_331(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -64923,12 +64980,12 @@ var _$plot_336 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_336(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_334(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_336(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_334(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -64983,7 +65040,7 @@ function createFills(gd, scatterlayer, plotinfo) { }); } -function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_334(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -65005,7 +65062,7 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran tr = _$d3_10.select(element); // error bars are at the bottom - _$registry_247.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_248.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -65017,7 +65074,7 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -65043,11 +65100,11 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_165.noop; + makeUpdate = _$lib_166.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_339.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_337.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -65084,7 +65141,7 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_331(cdscatter, { + segments = _$linePoints_329(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -65099,7 +65156,7 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_336(segments[i]); + trace._polygons[i] = __polygonTester_334(segments[i]); } if(segments.length) { @@ -65125,7 +65182,7 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_339.hasLines(trace) && pts.length > 1) { + if(_$subtypes_337.hasLines(trace) && pts.length > 1) { var el = _$d3_10.select(this); // This makes the coloring work correctly: @@ -65252,19 +65309,19 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = d[0].trace, s = _$d3_10.select(this), - showMarkers = _$subtypes_339.hasMarkers(trace), - showText = _$subtypes_339.hasText(trace); + showMarkers = _$subtypes_337.hasMarkers(trace), + showText = _$subtypes_337.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_165.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_166.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_165.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_166.identity; } // marker points @@ -65385,11 +65442,11 @@ function __plotOne_336(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_10.extent(_$lib_165.simpleMap(xa.range, xa.r2c)), - yr = _$d3_10.extent(_$lib_165.simpleMap(ya.range, ya.r2c)); + xr = _$d3_10.extent(_$lib_166.simpleMap(xa.range, xa.r2c)), + yr = _$d3_10.extent(_$lib_166.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_339.hasMarkers(trace)) return; + if(!_$subtypes_337.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -65404,7 +65461,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_339.hasMarkers(tracei) && + if(_$subtypes_337.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -65435,9 +65492,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_339 = require('./subtypes'); */; +/* removed: var _$subtypes_337 = require('./subtypes'); */; -var _$selectPoints_337 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_335 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -65448,7 +65505,7 @@ var _$selectPoints_337 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_339.hasMarkers(trace) && !_$subtypes_339.hasText(trace)); + var hasOnlyLines = (!_$subtypes_337.hasMarkers(trace) && !_$subtypes_337.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -65491,9 +65548,9 @@ var _$selectPoints_337 = function selectPoints(searchInfo, polygon) { /* removed: var _$d3_10 = require('d3'); */; /* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$registry_247 = require('../../registry'); */; +/* removed: var _$registry_248 = require('../../registry'); */; -function __style_338(gd, cd) { +function __style_336(gd, cd) { var s = cd ? cd[0].node3 : _$d3_10.select(gd).selectAll('g.trace.scatter'); s.style('opacity', function(d) { @@ -65512,7 +65569,7 @@ function __style_338(gd, cd) { s.selectAll('g.trace path.js-fill') .call(_$drawing_71.fillGroupStyle); - _$registry_247.getComponentMethod('errorbars', 'style')(s); + _$registry_248.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { @@ -65525,8 +65582,8 @@ function stylePoints(sel, trace, gd) { _$drawing_71.selectedTextStyle(txs, trace); } -var _$style_338 = { - style: __style_338, +var _$style_336 = { + style: __style_336, stylePoints: stylePoints }; @@ -65543,35 +65600,35 @@ var _$style_338 = { var Scatter = {}; -/* removed: var _$subtypes_339 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_339.hasLines; -Scatter.hasMarkers = _$subtypes_339.hasMarkers; -Scatter.hasText = _$subtypes_339.hasText; -Scatter.isBubble = _$subtypes_339.isBubble; +/* removed: var _$subtypes_337 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_337.hasLines; +Scatter.hasMarkers = _$subtypes_337.hasMarkers; +Scatter.hasText = _$subtypes_337.hasText; +Scatter.isBubble = _$subtypes_337.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_317; -Scatter.supplyDefaults = _$supplyDefaults_324; -Scatter.cleanData = _$cleanData_320; -Scatter.calc = _$calc_318.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_316; -Scatter.plot = _$plot_336; -Scatter.colorbar = _$colorbar_321; -Scatter.style = _$style_338.style; -Scatter.hoverPoints = _$hoverPoints_328; -Scatter.selectPoints = _$selectPoints_337; +Scatter.attributes = _$attributes_315; +Scatter.supplyDefaults = _$supplyDefaults_322; +Scatter.cleanData = _$cleanData_318; +Scatter.calc = _$calc_316.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_314; +Scatter.plot = _$plot_334; +Scatter.colorbar = _$colorbar_319; +Scatter.style = _$style_336.style; +Scatter.hoverPoints = _$hoverPoints_326; +Scatter.selectPoints = _$selectPoints_335; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_218; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_219; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_329 = Scatter; +var _$Scatter_327 = Scatter; var _$core_151 = {}; /** @@ -65585,7 +65642,7 @@ var _$core_151 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_151.version = '1.35.2'; +_$core_151.version = '1.36.0'; // inject promise polyfill _$es6Promise_11.polyfill(); @@ -65597,24 +65654,24 @@ _$plotcss_1; _$mathjax_config_152; // include registry module and expose register method -/* removed: var _$registry_247 = require('./registry'); */; -var register = _$core_151.register = _$registry_247.register; +/* removed: var _$registry_248 = require('./registry'); */; +var register = _$core_151.register = _$registry_248.register; // expose plot api methods -/* removed: var _$plot_api_194 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_194); +/* removed: var _$plot_api_195 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_195); for(var i = 0; i < methodNames.length; i++) { var __name_151 = methodNames[i]; - _$core_151[__name_151] = _$plot_api_194[__name_151]; + _$core_151[__name_151] = _$plot_api_195[__name_151]; register({ moduleType: 'apiMethod', name: __name_151, - fn: _$plot_api_194[__name_151] + fn: _$plot_api_195[__name_151] }); } // scatter is the only trace included by default -register(_$Scatter_329); +register(_$Scatter_327); // register all registrable components modules register([ @@ -65634,8 +65691,8 @@ register([ // locales en and en-US are required for default behavior register([ - _$localeEn_190, - _$localeEnUs_189 + _$localeEn_191, + _$localeEnUs_190 ]); // plot icons @@ -65644,9 +65701,9 @@ _$core_151.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk _$core_151.Plots = _$plots_240; _$core_151.Fx = _$fx_88; -_$core_151.Snapshot = _$Snapshot_252; -_$core_151.PlotSchema = _$plot_schema_198; -_$core_151.Queue = _$queue_179; +_$core_151.Snapshot = _$Snapshot_253; +_$core_151.PlotSchema = _$plot_schema_199; +_$core_151.Queue = _$queue_180; // export d3 used in the bundle _$core_151.d3 = _$d3_10; @@ -65673,9 +65730,9 @@ var _$core_5 = _$core_151; 'use strict'; -/* removed: var _$attributes_257 = require('../bar/attributes'); */; +/* removed: var _$attributes_258 = require('../bar/attributes'); */; -var _$attributes_285 = { +var _$attributes_281 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -65687,8 +65744,8 @@ var _$attributes_285 = { }, - text: _$attributes_257.text, - orientation: _$attributes_257.orientation, + text: _$attributes_258.text, + orientation: _$attributes_258.orientation, histfunc: { valType: 'enumerated', @@ -65780,13 +65837,13 @@ var _$attributes_285 = { }, ybins: makeBinsAttr('y'), - marker: _$attributes_257.marker, + marker: _$attributes_258.marker, - selected: _$attributes_257.selected, - unselected: _$attributes_257.unselected, + selected: _$attributes_258.selected, + unselected: _$attributes_258.unselected, _deprecated: { - bardir: _$attributes_257._deprecated.bardir + bardir: _$attributes_258._deprecated.bardir } }; @@ -65838,7 +65895,7 @@ function makeBinsAttr(axLetter) { 'use strict'; -var _$doAvg_286 = function doAvg(size, counts) { +var _$doAvg_282 = function doAvg(size, counts) { var nMax = size.length, total = 0; for(var i = 0; i < nMax; i++) { @@ -65865,7 +65922,7 @@ var _$doAvg_286 = function doAvg(size, counts) { /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var _$bin_functions_288 = { +var _$bin_functions_284 = { count: function(n, i, size) { size[n]++; return 1; @@ -65944,7 +66001,7 @@ var oneDay = _$numerical_148.ONEDAY; var oneHour = _$numerical_148.ONEHOUR; var oneMin = _$numerical_148.ONEMIN; var oneSec = _$numerical_148.ONESEC; -var tickIncrement = _$axes_207.tickIncrement; +var tickIncrement = _$axes_208.tickIncrement; /* @@ -65958,7 +66015,7 @@ var tickIncrement = _$axes_207.tickIncrement; * @return {function(v, isRightEdge)}: * find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v` */ -var _$getBinSpanLabelRound_289 = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) { +var _$getBinSpanLabelRound_285 = 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) @@ -66114,10 +66171,10 @@ function dateParts(v, pa, calendar) { 'use strict'; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var cleanDate = _$lib_165.cleanDate; +var cleanDate = _$lib_166.cleanDate; /* removed: var _$numerical_148 = require('../../constants/numerical'); */; -var __ONEDAY_291 = _$numerical_148.ONEDAY; -var __BADNUM_291 = _$numerical_148.BADNUM; +var __ONEDAY_287 = _$numerical_148.ONEDAY; +var __BADNUM_287 = _$numerical_148.BADNUM; /* * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) @@ -66128,7 +66185,7 @@ var __BADNUM_291 = _$numerical_148.BADNUM; * after trace supplyDefaults are completed. So this gets called during the * calc step, when data are inserted into bins. */ -var _$cleanBins_291 = function cleanBins(trace, ax, binDirection) { +var _$cleanBins_287 = function cleanBins(trace, ax, binDirection) { var axType = ax.type, binAttr = binDirection + 'bins', bins = trace[binAttr]; @@ -66136,7 +66193,7 @@ var _$cleanBins_291 = function cleanBins(trace, ax, binDirection) { if(!bins) bins = trace[binAttr] = {}; var cleanBound = (axType === 'date') ? - function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_291, bins.calendar) : null; } : + function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_287, bins.calendar) : null; } : function(v) { return _$fastIsnumeric_13(v) ? Number(v) : null; }; bins.start = cleanBound(bins.start); @@ -66145,7 +66202,7 @@ var _$cleanBins_291 = function cleanBins(trace, ax, binDirection) { // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) // but without the extra string options for log axes // ie the only strings we accept are M for months - var sizeDflt = (axType === 'date') ? __ONEDAY_291 : 1, + var sizeDflt = (axType === 'date') ? __ONEDAY_287 : 1, binSize = bins.size; if(_$fastIsnumeric_13(binSize)) { @@ -66194,7 +66251,7 @@ var _$cleanBins_291 = function cleanBins(trace, ax, binDirection) { 'use strict'; -var _$norm_functions_296 = { +var _$norm_functions_292 = { percent: function(size, total) { var nMax = size.length, norm = 100 / total; @@ -66229,18 +66286,18 @@ var _$norm_functions_296 = { /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$axes_208 = require('../../plots/cartesian/axes'); */; -/* removed: var _$arraysToCalcdata_256 = require('../bar/arrays_to_calcdata'); */; -/* removed: var _$bin_functions_288 = require('./bin_functions'); */; -/* removed: var _$norm_functions_296 = require('./norm_functions'); */; -/* removed: var _$doAvg_286 = require('./average'); */; -/* removed: var _$cleanBins_291 = require('./clean_bins'); */; -var __oneMonth_290 = _$numerical_148.ONEAVGMONTH; -/* removed: var _$getBinSpanLabelRound_289 = require('./bin_label_vals'); */; +/* removed: var _$arraysToCalcdata_257 = require('../bar/arrays_to_calcdata'); */; +/* removed: var _$bin_functions_284 = require('./bin_functions'); */; +/* removed: var _$norm_functions_292 = require('./norm_functions'); */; +/* removed: var _$doAvg_282 = require('./average'); */; +/* removed: var _$cleanBins_287 = require('./clean_bins'); */; +var __oneMonth_286 = _$numerical_148.ONEAVGMONTH; +/* removed: var _$getBinSpanLabelRound_285 = require('./bin_label_vals'); */; -var _$calc_290 = function calc(gd, trace) { +var _$calc_286 = function calc(gd, trace) { // ignore as much processing as possible (and including in autorange) if bar is not visible if(trace.visible !== true) return; @@ -66248,7 +66305,7 @@ var _$calc_290 = function calc(gd, trace) { // note: this logic for choosing orientation is duplicated in graph_obj->setstyles var pos = []; var size = []; - var pa = _$axes_207.getFromId(gd, trace.orientation === 'h' ? + var pa = _$axes_208.getFromId(gd, trace.orientation === 'h' ? (trace.yaxis || 'y') : (trace.xaxis || 'x')); var mainData = trace.orientation === 'h' ? 'y' : 'x'; var counterData = {x: 'y', y: 'x'}[mainData]; @@ -66256,7 +66313,7 @@ var _$calc_290 = function calc(gd, trace) { var cumulativeSpec = trace.cumulative; var i; - _$cleanBins_291(trace, pa, mainData); + _$cleanBins_287(trace, pa, mainData); var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData); var binSpec = binsAndPos[0]; @@ -66284,16 +66341,16 @@ var _$calc_290 = function calc(gd, trace) { var extremeFunc = func === 'max' || func === 'min'; var sizeInit = extremeFunc ? null : 0; - var binFunc = _$bin_functions_288.count; - var normFunc = _$norm_functions_296[norm]; + var binFunc = _$bin_functions_284.count; + var normFunc = _$norm_functions_292[norm]; var isAvg = false; var pr2c = function(v) { return pa.r2c(v, 0, calendar); }; var rawCounterData; - if(_$lib_165.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { + if(_$lib_166.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { rawCounterData = trace[counterData]; isAvg = func === 'avg'; - binFunc = _$bin_functions_288[func]; + binFunc = _$bin_functions_284[func]; } // create the bins (and any extra arrays needed) @@ -66301,10 +66358,10 @@ var _$calc_290 = function calc(gd, trace) { i = pr2c(binSpec.start); // decrease end a little in case of rounding errors - binEnd = pr2c(binSpec.end) + (i - _$axes_207.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; + binEnd = pr2c(binSpec.end) + (i - _$axes_208.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; while(i < binEnd && pos.length < 1e6) { - i2 = _$axes_207.tickIncrement(i, binSpec.size, false, calendar); + i2 = _$axes_208.tickIncrement(i, binSpec.size, false, calendar); pos.push((i + i2) / 2); size.push(sizeInit); inputPoints.push([]); @@ -66339,7 +66396,7 @@ var _$calc_290 = function calc(gd, trace) { var ptNumber2cdIndex = {}; for(i = 0; i < pos0.length; i++) { var posi = pos0[i]; - n = _$lib_165.findBin(posi, bins); + n = _$lib_166.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]]) { @@ -66355,11 +66412,11 @@ var _$calc_290 = function calc(gd, trace) { var roundFn; if(!uniqueValsPerBin) { - roundFn = _$getBinSpanLabelRound_289(leftGap, rightGap, binEdges, pa, calendar); + roundFn = _$getBinSpanLabelRound_285(leftGap, rightGap, binEdges, pa, calendar); } // average and/or normalize the data, if needed - if(isAvg) total = _$doAvg_286(size, counts); + if(isAvg) total = _$doAvg_282(size, counts); if(normFunc) normFunc(size, total, inc); // after all normalization etc, now we can accumulate if desired @@ -66412,13 +66469,13 @@ var _$calc_290 = function calc(gd, trace) { 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_207.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; + cd[0].width1 = _$axes_208.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; } - _$arraysToCalcdata_256(cd, trace); + _$arraysToCalcdata_257(cd, trace); - if(_$lib_165.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_165.tagSelected(cd, trace, ptNumber2cdIndex); + if(_$lib_166.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_166.tagSelected(cd, trace, ptNumber2cdIndex); } return cd; @@ -66467,7 +66524,7 @@ function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { calendar = tracei[mainData + 'calendar']; var cumulativeSpec = tracei.cumulative; - binSpec = _$axes_207.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); + binSpec = _$axes_208.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); // Edge case: single-valued histogram overlaying others // Use them all together to calculate the bin size for the single-valued one @@ -66618,7 +66675,7 @@ function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) { // 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_165.distinctVals(dataVals).minDiff; + minSize = _$lib_166.distinctVals(dataVals).minDiff; } // now apply the min size we found to all single-valued traces @@ -66678,7 +66735,7 @@ function getMinSize(size1, size2) { function numericSize(size) { if(_$fastIsnumeric_13(size)) return size; if(typeof size === 'string' && size.charAt(0) === 'M') { - return __oneMonth_290 * +(size.substr(1)); + return __oneMonth_286 * +(size.substr(1)); } return Infinity; } @@ -66747,7 +66804,7 @@ function cdf(size, direction, currentBin) { 'use strict'; -var _$handleBinDefaults_287 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { +var _$handleBinDefaults_283 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { coerce('histnorm'); binDirections.forEach(function(binDirection) { @@ -66779,17 +66836,17 @@ var _$handleBinDefaults_287 = function handleBinDefaults(traceIn, traceOut, coer 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$registry_248 = require('../../registry'); */; +/* removed: var _$lib_166 = require('../../lib'); */; /* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$handleBinDefaults_287 = require('./bin_defaults'); */; -/* removed: var _$handleStyleDefaults_269 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_285 = require('./attributes'); */; +/* removed: var _$handleBinDefaults_283 = require('./bin_defaults'); */; +/* removed: var _$handleStyleDefaults_270 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_281 = require('./attributes'); */; -var _$supplyDefaults_292 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_288 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_285, attr, dflt); + return _$lib_166.coerce(traceIn, traceOut, _$attributes_281, attr, dflt); } var x = coerce('x'), @@ -66811,23 +66868,23 @@ var _$supplyDefaults_292 = function supplyDefaults(traceIn, traceOut, defaultCol return; } - var handleCalendarDefaults = _$registry_247.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_248.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); var hasAggregationData = traceOut[orientation === 'h' ? 'x' : 'y']; if(hasAggregationData) coerce('histfunc'); var binDirections = (orientation === 'h') ? ['y'] : ['x']; - _$handleBinDefaults_287(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_283(traceIn, traceOut, coerce, binDirections); - _$handleStyleDefaults_269(traceIn, traceOut, coerce, defaultColor, layout); + _$handleStyleDefaults_270(traceIn, traceOut, coerce, defaultColor, layout); // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_247.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_248.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, _$color_46.defaultLine, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, _$color_46.defaultLine, {axis: 'x', inherit: 'y'}); - _$lib_165.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_166.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -66840,7 +66897,7 @@ var _$supplyDefaults_292 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_293 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_289 = 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; @@ -66886,11 +66943,11 @@ var _$eventData_293 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_260 = require('../bar/hover'); */; -var hoverLabelText = _$axes_207.hoverLabelText; +/* removed: var _$hoverPoints_261 = require('../bar/hover'); */; +var hoverLabelText = _$axes_208.hoverLabelText; -var _$hoverPoints_294 = function hoverPoints(pointData, xval, yval, hovermode) { - var pts = _$hoverPoints_260(pointData, xval, yval, hovermode); +var _$hoverPoints_290 = function hoverPoints(pointData, xval, yval, hovermode) { + var pts = _$hoverPoints_261(pointData, xval, yval, hovermode); if(!pts) return; @@ -66934,28 +66991,28 @@ var _$hoverPoints_294 = function hoverPoints(pointData, xval, yval, hovermode) { var Histogram = {}; -Histogram.attributes = _$attributes_285; -Histogram.layoutAttributes = _$layout_attributes_262; -Histogram.supplyDefaults = _$supplyDefaults_292; -Histogram.supplyLayoutDefaults = _$layout_defaults_263; -Histogram.calc = _$calc_290; -Histogram.setPositions = _$setPositions_266; -Histogram.plot = _$plot_264; -Histogram.style = _$style_268; -Histogram.colorbar = _$colorbar_321; -Histogram.hoverPoints = _$hoverPoints_294; -Histogram.selectPoints = _$selectPoints_265; -Histogram.eventData = _$eventData_293; +Histogram.attributes = _$attributes_281; +Histogram.layoutAttributes = _$layout_attributes_263; +Histogram.supplyDefaults = _$supplyDefaults_288; +Histogram.supplyLayoutDefaults = _$layout_defaults_264; +Histogram.calc = _$calc_286; +Histogram.setPositions = _$setPositions_267; +Histogram.plot = _$plot_265; +Histogram.style = _$style_269; +Histogram.colorbar = _$colorbar_319; +Histogram.hoverPoints = _$hoverPoints_290; +Histogram.selectPoints = _$selectPoints_266; +Histogram.eventData = _$eventData_289; Histogram.moduleType = 'trace'; Histogram.name = 'histogram'; -Histogram.basePlotModule = _$cartesian_218; -Histogram.categories = ['cartesian', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; +Histogram.basePlotModule = _$cartesian_219; +Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; Histogram.meta = { }; -var _$Histogram_295 = Histogram; +var _$Histogram_291 = Histogram; /** * Copyright 2012-2018, Plotly, Inc. @@ -66967,7 +67024,7 @@ var _$Histogram_295 = Histogram; 'use strict'; -var _$histogram_6 = _$Histogram_295; +var _$histogram_6 = _$Histogram_291; /** * Copyright 2012-2018, Plotly, Inc. @@ -66980,21 +67037,17 @@ var _$histogram_6 = _$Histogram_295; 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$handleOHLC_302 = require('./ohlc_defaults'); */; -/* removed: var _$handleDirectionDefaults_299 = require('./direction_defaults'); */; -/* removed: var _$attributes_297 = require('./attributes'); */; -/* removed: var _$helpers_300 = require('./helpers'); */; - -var _$supplyDefaults_298 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - _$helpers_300.pushDummyTransformOpts(traceIn, traceOut); +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$handleOHLC_298 = require('./ohlc_defaults'); */; +/* removed: var _$attributes_293 = require('./attributes'); */; +var _$supplyDefaults_295 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_297, attr, dflt); + return _$lib_166.coerce(traceIn, traceOut, _$attributes_293, attr, dflt); } - var len = _$handleOHLC_302(traceIn, traceOut, coerce, layout); - if(len === 0) { + var len = _$handleOHLC_298(traceIn, traceOut, coerce, layout); + if(!len) { traceOut.visible = false; return; } @@ -67002,22 +67055,21 @@ var _$supplyDefaults_298 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('line.width'); coerce('line.dash'); - __handleDirection_298(traceIn, traceOut, coerce, 'increasing'); - __handleDirection_298(traceIn, traceOut, coerce, 'decreasing'); + __handleDirection_295(traceIn, traceOut, coerce, 'increasing'); + __handleDirection_295(traceIn, traceOut, coerce, 'decreasing'); coerce('text'); coerce('tickwidth'); -}; -function __handleDirection_298(traceIn, traceOut, coerce, direction) { - _$handleDirectionDefaults_299(traceIn, traceOut, coerce, direction); + layout._requestRangeslider[traceOut.xaxis] = true; +}; +function __handleDirection_295(traceIn, traceOut, coerce, direction) { coerce(direction + '.line.color'); coerce(direction + '.line.width', traceOut.line.width); coerce(direction + '.line.dash', traceOut.line.dash); } -var _$transform_303 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67026,264 +67078,100 @@ var _$transform_303 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; +/* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$lib_165 = require('../../lib'); */; -var ____303 = _$lib_165._; -/* removed: var _$helpers_300 = require('./helpers'); */; -/* removed: var _$axes_207 = require('../../plots/cartesian/axes'); */; -/* removed: var _$axis_ids_210 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -_$transform_303.moduleType = 'transform'; +var _$plot_299 = function plot(gd, plotinfo, cdOHLC) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -_$transform_303.name = 'ohlc'; + var ohlcLayer = plotinfo.plot.select('g.ohlclayer'); -_$transform_303.attributes = {}; + var traces = ohlcLayer.selectAll('g.trace') + .data(cdOHLC, function(d) { return d[0].trace.uid; }); -_$transform_303.supplyDefaults = function(transformIn, traceOut, layout, traceIn) { - _$helpers_300.clearEphemeralTransformOpts(traceIn); - _$helpers_300.copyOHLC(transformIn, traceOut); + traces.enter().append('g') + .attr('class', 'trace ohlc'); - return transformIn; -}; + traces.exit().remove(); -_$transform_303.transform = function transform(dataIn, state) { - var dataOut = []; + traces.order(); - for(var i = 0; i < dataIn.length; i++) { - var traceIn = dataIn[i]; + traces.each(function(d) { + var cd0 = d[0]; + var t = cd0.t; + var trace = cd0.trace; + var sel = _$d3_10.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; - if(traceIn.type !== 'ohlc') { - dataOut.push(traceIn); - continue; + if(trace.visible !== true || t.empty) { + sel.remove(); + return; } - dataOut.push( - __makeTrace_303(traceIn, state, 'increasing'), - __makeTrace_303(traceIn, state, 'decreasing') - ); - } - - _$helpers_300.addRangeSlider(dataOut, state.layout); - - return dataOut; -}; - -function __makeTrace_303(traceIn, state, direction) { - var traceOut = { - type: 'scatter', - mode: 'lines', - connectgaps: false, - - visible: traceIn.visible, - opacity: traceIn.opacity, - xaxis: traceIn.xaxis, - yaxis: traceIn.yaxis, - - hoverinfo: makeHoverInfo(traceIn), - transforms: _$helpers_300.makeTransform(traceIn, state, direction) - }; + var tickLen = t.tickLen; - // the rest of below may not have been coerced + var paths = sel.selectAll('path').data(_$lib_166.identity); - var directionOpts = traceIn[direction]; + paths.enter().append('path'); - if(directionOpts) { - _$lib_165.extendFlat(traceOut, { + paths.exit().remove(); - // to make autotype catch date axes soon!! - x: traceIn.x || [0], - xcalendar: traceIn.xcalendar, + paths.attr('d', function(d) { + var x = xa.c2p(d.pos, true); + var xo = xa.c2p(d.pos - tickLen, true); + var xc = xa.c2p(d.pos + tickLen, true); - // concat low and high to get correct autorange - y: [].concat(traceIn.low).concat(traceIn.high), + var yo = ya.c2p(d.o, true); + var yh = ya.c2p(d.h, true); + var yl = ya.c2p(d.l, true); + var yc = ya.c2p(d.c, true); - text: traceIn.text, - - name: directionOpts.name, - showlegend: directionOpts.showlegend, - line: directionOpts.line + return 'M' + xo + ',' + yo + 'H' + x + + 'M' + x + ',' + yh + 'V' + yl + + 'M' + xc + ',' + yc + 'H' + x; }); - } - - return traceOut; -} - -// Let scatter hoverPoint format 'x' coordinates, if desired. -// -// Note that, this solution isn't perfect: it shows open and close -// values at slightly different 'x' coordinates then the rest of the -// segments, but is for more robust than calling `Axes.tickText` during -// calcTransform. -// -// A future iteration should perhaps try to add a hook for transforms in -// the hoverPoints handlers. -function makeHoverInfo(traceIn) { - var hoverinfo = traceIn.hoverinfo; - - if(hoverinfo === 'all') return 'x+text+name'; - - var parts = hoverinfo.split('+'), - indexOfY = parts.indexOf('y'), - indexOfText = parts.indexOf('text'); - - if(indexOfY !== -1) { - parts.splice(indexOfY, 1); - - if(indexOfText === -1) parts.push('text'); - } - - return parts.join('+'); -} - -_$transform_303.calcTransform = function calcTransform(gd, trace, opts) { - var direction = opts.direction, - filterFn = _$helpers_300.getFilterFn(direction); - - var xa = _$axis_ids_210.getFromTrace(gd, trace, 'x'), - ya = _$axis_ids_210.getFromTrace(gd, trace, 'y'), - tickWidth = convertTickWidth(gd, xa, trace); - - var open = trace.open, - high = trace.high, - low = trace.low, - close = trace.close, - textIn = trace.text; - - var openName = ____303(gd, 'open:') + ' '; - var highName = ____303(gd, 'high:') + ' '; - var lowName = ____303(gd, 'low:') + ' '; - var closeName = ____303(gd, 'close:') + ' '; - - var len = open.length, - x = [], - y = [], - textOut = []; - - var appendX; - if(trace._fullInput.x) { - appendX = function(i) { - var xi = trace.x[i], - xcalendar = trace.xcalendar, - xcalc = xa.d2c(xi, 0, xcalendar); - - x.push( - xa.c2d(xcalc - tickWidth, 0, xcalendar), - xi, xi, xi, xi, - xa.c2d(xcalc + tickWidth, 0, xcalendar), - null); - }; - } - else { - appendX = function(i) { - x.push( - i - tickWidth, - i, i, i, i, - i + tickWidth, - null); - }; - } - - var appendY = function(o, h, l, c) { - y.push(o, o, h, l, c, c, null); - }; - - var format = function(ax, val) { - return _$axes_207.tickText(ax, ax.c2l(val), 'hover').text; - }; - - var hoverinfo = trace._fullInput.hoverinfo, - hoverParts = hoverinfo.split('+'), - hasAll = hoverinfo === 'all', - hasY = hasAll || hoverParts.indexOf('y') !== -1, - hasText = hasAll || hoverParts.indexOf('text') !== -1; - - var getTextItem = Array.isArray(textIn) ? - function(i) { return textIn[i] || ''; } : - function() { return textIn; }; - - var appendText = function(i, o, h, l, c) { - var t = []; - - if(hasY) { - t.push(openName + format(ya, o)); - t.push(highName + format(ya, h)); - t.push(lowName + format(ya, l)); - t.push(closeName + format(ya, c)); - } - - if(hasText) t.push(getTextItem(i)); - - var _t = t.join('
'); - - textOut.push(_t, _t, _t, _t, _t, _t, null); - }; - - for(var i = 0; i < len; i++) { - if(filterFn(open[i], close[i]) && _$fastIsnumeric_13(high[i]) && _$fastIsnumeric_13(low[i])) { - appendX(i); - appendY(open[i], high[i], low[i], close[i]); - appendText(i, open[i], high[i], low[i], close[i]); - } - } - - trace.x = x; - trace.y = y; - trace.text = textOut; - trace._length = x.length; + }); }; -function convertTickWidth(gd, xa, trace) { - var fullInput = trace._fullInput, - tickWidth = fullInput.tickwidth, - minDiff = fullInput._minDiff; - - if(!minDiff) { - var fullData = gd._fullData, - ohlcTracesOnThisXaxis = []; - - minDiff = Infinity; - - // find min x-coordinates difference of all traces - // attached to this x-axis and stash the result - - var i; - - for(i = 0; i < fullData.length; i++) { - var _trace = fullData[i]._fullInput; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(_trace.type === 'ohlc' && - _trace.visible === true && - _trace.xaxis === xa._id - ) { - ohlcTracesOnThisXaxis.push(_trace); +'use strict'; - // - _trace.x may be undefined here, - // it is filled later in calcTransform - // - // - handle trace of length 1 separately. +/* removed: var _$d3_10 = require('d3'); */; +/* removed: var _$drawing_71 = require('../../components/drawing'); */; +/* removed: var _$color_46 = require('../../components/color'); */; - if(_trace.x && _trace.x.length > 1) { - var xcalc = _$lib_165.simpleMap(_trace.x, xa.d2c, 0, trace.xcalendar), - _minDiff = _$lib_165.distinctVals(xcalc).minDiff; - minDiff = Math.min(minDiff, _minDiff); - } - } - } +var _$style_301 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_10.select(gd).selectAll('g.ohlclayer').selectAll('g.trace'); - // if minDiff is still Infinity here, set it to 1 - if(minDiff === Infinity) minDiff = 1; + s.style('opacity', function(d) { + return d[0].trace.opacity; + }); - for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) { - ohlcTracesOnThisXaxis[i]._minDiff = minDiff; - } - } + s.each(function(d) { + var trace = d[0].trace; - return minDiff * tickWidth; -} + _$d3_10.select(this).selectAll('path').each(function(di) { + var dirLine = trace[di.dir].line; + _$d3_10.select(this) + .style('fill', 'none') + .call(_$color_46.stroke, dirLine.color) + .call(_$drawing_71.dashLine, dirLine.dash, dirLine.width) + // TODO: custom selection style for OHLC + .style('opacity', trace.selectedpoints && !di.selected ? 0.3 : 1); + }); + }); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -67295,24 +67183,24 @@ function convertTickWidth(gd, xa, trace) { 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; - -var _$ohlc_301 = { +var _$ohlc_297 = { moduleType: 'trace', name: 'ohlc', - basePlotModule: _$cartesian_218, - categories: ['cartesian', 'showLegend'], + basePlotModule: _$cartesian_219, + categories: ['cartesian', 'svg', 'showLegend'], meta: { }, - attributes: _$attributes_297, - supplyDefaults: _$supplyDefaults_298, + attributes: _$attributes_293, + supplyDefaults: _$supplyDefaults_295, + calc: _$calc_294.calc, + plot: _$plot_299, + style: _$style_301, + hoverPoints: _$hoverPoints_296, + selectPoints: _$selectPoints_300 }; -_$registry_247.register(_$Scatter_329); -_$registry_247.register(_$transform_303); - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67323,7 +67211,7 @@ _$registry_247.register(_$transform_303); 'use strict'; -var _$ohlc_8 = _$ohlc_301; +var _$ohlc_8 = _$ohlc_297; /** * Copyright 2012-2018, Plotly, Inc. @@ -67337,18 +67225,18 @@ var _$ohlc_8 = _$ohlc_301; /* removed: var _$attributes_45 = require('../../components/color/attributes'); */; /* removed: var _$font_attributes_234 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_204 = require('../../plots/attributes'); */; -var __domainAttrs_304 = _$domain_233.attributes; +/* removed: var _$attributes_205 = require('../../plots/attributes'); */; +var __domainAttrs_302 = _$domain_233.attributes; -var __extendFlat_304 = _$extend_159.extendFlat; +var __extendFlat_302 = _$extend_160.extendFlat; -var __textFontAttrs_304 = _$font_attributes_234({ +var __textFontAttrs_302 = _$font_attributes_234({ editType: 'calc', colorEditType: 'style', }); -var _$attributes_304 = { +var _$attributes_302 = { labels: { valType: 'data_array', editType: 'calc', @@ -67441,7 +67329,7 @@ var _$attributes_304 = { editType: 'calc', }, - hoverinfo: __extendFlat_304({}, _$attributes_204.hoverinfo, { + hoverinfo: __extendFlat_302({}, _$attributes_205.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'] }), textposition: { @@ -67454,18 +67342,18 @@ var _$attributes_304 = { }, // TODO make those arrayOk? - textfont: __extendFlat_304({}, __textFontAttrs_304, { + textfont: __extendFlat_302({}, __textFontAttrs_302, { }), - insidetextfont: __extendFlat_304({}, __textFontAttrs_304, { + insidetextfont: __extendFlat_302({}, __textFontAttrs_302, { }), - outsidetextfont: __extendFlat_304({}, __textFontAttrs_304, { + outsidetextfont: __extendFlat_302({}, __textFontAttrs_302, { }), // position and shape - domain: __domainAttrs_304({name: 'pie', trace: true, editType: 'calc'}), + domain: __domainAttrs_302({name: 'pie', trace: true, editType: 'calc'}), hole: { valType: 'number', @@ -67522,7 +67410,7 @@ var _$attributes_304 = { } }; -var _$base_plot_305 = {}; +var _$base_plot_303 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67533,19 +67421,19 @@ var _$base_plot_305 = {}; 'use strict'; -/* removed: var _$registry_247 = require('../../registry'); */; - +/* removed: var _$registry_248 = require('../../registry'); */; +var __getModuleCalcData_303 = _$get_data_236.getModuleCalcData; -_$base_plot_305.name = 'pie'; +_$base_plot_303.name = 'pie'; -_$base_plot_305.plot = function(gd) { - var Pie = _$registry_247.getModule('pie'); - var cdPie = getCdModule(gd.calcdata, Pie); +_$base_plot_303.plot = function(gd) { + var Pie = _$registry_248.getModule('pie'); + var cdPie = __getModuleCalcData_303(gd.calcdata, Pie)[0]; if(cdPie.length) Pie.plot(gd, cdPie); }; -_$base_plot_305.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_303.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPie = (oldFullLayout._has && oldFullLayout._has('pie')); var hasPie = (newFullLayout._has && newFullLayout._has('pie')); @@ -67554,21 +67442,6 @@ _$base_plot_305.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -function getCdModule(calcdata, _module) { - var cdModule = []; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - - if((trace._module === _module) && (trace.visible === true)) { - cdModule.push(cd); - } - } - - return cdModule; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67580,15 +67453,15 @@ function getCdModule(calcdata, _module) { 'use strict'; /* removed: var _$fastIsnumeric_13 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_306 = _$lib_165.isArrayOrTypedArray; +var __isArrayOrTypedArray_304 = _$lib_166.isArrayOrTypedArray; /* removed: var _$tinycolor_28 = require('tinycolor2'); */; /* removed: var _$color_46 = require('../../components/color'); */; -/* removed: var _$helpers_309 = require('./helpers'); */; +/* removed: var _$helpers_307 = require('./helpers'); */; -var _$calc_306 = function calc(gd, trace) { +var _$calc_304 = function calc(gd, trace) { var vals = trace.values; - var hasVals = __isArrayOrTypedArray_306(vals) && vals.length; + var hasVals = __isArrayOrTypedArray_304(vals) && vals.length; var labels = trace.labels; var colors = trace.marker.colors || []; var cd = []; @@ -67710,11 +67583,11 @@ var _$calc_306 = function calc(gd, trace) { pt = cd[i]; thisText = hasLabel ? [pt.label] : []; if(hasText) { - var texti = _$helpers_309.getFirstFilled(trace.text, pt.pts); + var texti = _$helpers_307.getFirstFilled(trace.text, pt.pts); if(texti) thisText.push(texti); } - if(hasValue) thisText.push(_$helpers_309.formatPieValue(pt.v, separators)); - if(hasPercent) thisText.push(_$helpers_309.formatPiePercent(pt.v / vTotal, separators)); + if(hasValue) thisText.push(_$helpers_307.formatPieValue(pt.v, separators)); + if(hasPercent) thisText.push(_$helpers_307.formatPiePercent(pt.v / vTotal, separators)); pt.text = thisText.join('
'); } } @@ -67765,21 +67638,21 @@ function generateDefaultColors(colorList) { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; -/* removed: var _$attributes_304 = require('./attributes'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$attributes_302 = require('./attributes'); */; var handleDomainDefaults = _$domain_233.defaults; -var _$supplyDefaults_307 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_305 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_165.coerce(traceIn, traceOut, _$attributes_304, attr, dflt); + return _$lib_166.coerce(traceIn, traceOut, _$attributes_302, attr, dflt); } - var coerceFont = _$lib_165.coerceFont; + var coerceFont = _$lib_166.coerceFont; var vals = coerce('values'); var labels = coerce('labels'); if(!Array.isArray(labels)) { - if(!_$lib_165.isArrayOrTypedArray(vals) || !vals.length) { + if(!_$lib_166.isArrayOrTypedArray(vals) || !vals.length) { // must have at least one of vals or labels traceOut.visible = false; return; @@ -67835,7 +67708,7 @@ var _$supplyDefaults_307 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$layout_attributes_311 = { +var _$layout_attributes_309 = { /** * hiddenlabels is the pie chart analog of visible:'legendonly' * but it can contain many labels, and can hide slices @@ -67857,13 +67730,13 @@ var _$layout_attributes_311 = { 'use strict'; -/* removed: var _$lib_165 = require('../../lib'); */; +/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$layout_attributes_311 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_309 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_312 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_310 = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_165.coerce(layoutIn, layoutOut, _$layout_attributes_311, attr, dflt); + return _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_309, attr, dflt); } coerce('hiddenlabels'); }; @@ -67885,7 +67758,7 @@ var appendArrayMultiPointValues = _$helpers_85.appendArrayMultiPointValues; // Note: like other eventData routines, this creates the data for hover/unhover/click events // but it has a different API and goes through a totally different pathway. // So to ensure it doesn't get misused, it's not attached to the Pie module. -var _$eventData_308 = function eventData(pt, trace) { +var _$eventData_306 = function eventData(pt, trace) { var out = { curveNumber: trace.index, pointNumbers: pt.pts, @@ -67925,12 +67798,13 @@ var _$eventData_308 = function eventData(pt, trace) { /* removed: var _$fx_88 = require('../../components/fx'); */; /* removed: var _$color_46 = require('../../components/color'); */; /* removed: var _$drawing_71 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_186 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$helpers_309 = require('./helpers'); */; -/* removed: var _$eventData_308 = require('./event_data'); */; +/* removed: var _$helpers_307 = require('./helpers'); */; +/* removed: var _$eventData_306 = require('./event_data'); */; -var _$plot_313 = function plot(gd, cdpie) { +var _$plot_311 = function plot(gd, cdpie) { var fullLayout = gd._fullLayout; scalePies(cdpie, fullLayout._size); @@ -68007,7 +67881,7 @@ var _$plot_313 = function plot(gd, cdpie) { // TODO: do we want to have Fx.castHoverinfo somehow handle this? // it already takes an array for index, for 2D, so this seems tricky. hoverinfo = _$fx_88.castHoverinfo({ - hoverinfo: [_$helpers_309.castOption(hoverinfo, pt.pts)], + hoverinfo: [_$helpers_307.castOption(hoverinfo, pt.pts)], _module: trace._module }, fullLayout2, 0); } @@ -68025,11 +67899,11 @@ var _$plot_313 = function plot(gd, cdpie) { if(hoverinfo.indexOf('label') !== -1) thisText.push(pt.label); if(hoverinfo.indexOf('text') !== -1) { - var texti = _$helpers_309.castOption(trace2.hovertext || trace2.text, pt.pts); + var texti = _$helpers_307.castOption(trace2.hovertext || trace2.text, pt.pts); if(texti) thisText.push(texti); } - if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_309.formatPieValue(pt.v, separators)); - if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_309.formatPiePercent(pt.v / cd0.vTotal, separators)); + if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_307.formatPieValue(pt.v, separators)); + if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_307.formatPiePercent(pt.v / cd0.vTotal, separators)); var hoverLabel = trace.hoverlabel; var hoverFont = hoverLabel.font; @@ -68041,11 +67915,11 @@ var _$plot_313 = function plot(gd, cdpie) { text: thisText.join('
'), name: hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined, idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right', - color: _$helpers_309.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, - borderColor: _$helpers_309.castOption(hoverLabel.bordercolor, pt.pts), - fontFamily: _$helpers_309.castOption(hoverFont.family, pt.pts), - fontSize: _$helpers_309.castOption(hoverFont.size, pt.pts), - fontColor: _$helpers_309.castOption(hoverFont.color, pt.pts) + color: _$helpers_307.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, + borderColor: _$helpers_307.castOption(hoverLabel.bordercolor, pt.pts), + fontFamily: _$helpers_307.castOption(hoverFont.family, pt.pts), + fontSize: _$helpers_307.castOption(hoverFont.size, pt.pts), + fontColor: _$helpers_307.castOption(hoverFont.color, pt.pts) }, { container: fullLayout2._hoverlayer.node(), outerContainer: fullLayout2._paper.node(), @@ -68056,7 +67930,7 @@ var _$plot_313 = function plot(gd, cdpie) { } gd.emit('plotly_hover', { - points: [_$eventData_308(pt, trace2)], + points: [_$eventData_306(pt, trace2)], event: _$d3_10.event }); hasHoverEvent = true; @@ -68069,7 +67943,7 @@ var _$plot_313 = function plot(gd, cdpie) { if(hasHoverEvent) { evt.originalEvent = _$d3_10.event; gd.emit('plotly_unhover', { - points: [_$eventData_308(pt, trace2)], + points: [_$eventData_306(pt, trace2)], event: _$d3_10.event }); hasHoverEvent = false; @@ -68092,7 +67966,7 @@ var _$plot_313 = function plot(gd, cdpie) { if(gd._dragging || fullLayout2.hovermode === false) return; - gd._hoverdata = [_$eventData_308(pt, trace2)]; + gd._hoverdata = [_$eventData_306(pt, trace2)]; _$fx_88.click(gd, _$d3_10.event); } @@ -68108,7 +67982,7 @@ var _$plot_313 = function plot(gd, cdpie) { .on('click', handleClick); if(trace.pull) { - var pull = +_$helpers_309.castOption(trace.pull, pt.pts) || 0; + var pull = +_$helpers_307.castOption(trace.pull, pt.pts) || 0; if(pull > 0) { cx += pull * pt.pxmid[0]; cy += pull * pt.pxmid[1]; @@ -68159,7 +68033,7 @@ var _$plot_313 = function plot(gd, cdpie) { } // add text - var textPosition = _$helpers_309.castOption(trace.textposition, pt.pts); + var textPosition = _$helpers_307.castOption(trace.textposition, pt.pts); var sliceTextGroup = sliceTop.selectAll('g.slicetext') .data(pt.text && (textPosition !== 'none') ? [0] : []); @@ -68168,13 +68042,11 @@ var _$plot_313 = function plot(gd, cdpie) { sliceTextGroup.exit().remove(); sliceTextGroup.each(function() { - var sliceText = _$d3_10.select(this).selectAll('text').data([0]); - - sliceText.enter().append('text') + var sliceText = _$lib_166.ensureSingle(_$d3_10.select(this), 'text', '', function(s) { // prohibit tex interpretation until we can handle // tex and regular text together - .attr('data-notex', 1); - sliceText.exit().remove(); + s.attr('data-notex', 1); + }); sliceText.text(pt.text) .attr({ @@ -68184,7 +68056,7 @@ var _$plot_313 = function plot(gd, cdpie) { }) .call(_$drawing_71.font, textPosition === 'outside' ? trace.outsidetextfont : trace.insidetextfont) - .call(_$svg_text_utils_186.convertToTspans, gd); + .call(_$svg_text_utils_187.convertToTspans, gd); // position the text relative to the slice var textBB = _$drawing_71.bBox(sliceText.node()); @@ -68405,8 +68277,8 @@ function scootLabels(quadrants, trace) { // overlap can only happen if the other point is pulled more than this one if(otherPt === thisPt || ( - (_$helpers_309.castOption(trace.pull, thisPt.pts) || 0) >= - (_$helpers_309.castOption(trace.pull, otherPt.pts) || 0)) + (_$helpers_307.castOption(trace.pull, thisPt.pts) || 0) >= + (_$helpers_307.castOption(trace.pull, otherPt.pts) || 0)) ) { continue; } @@ -68593,9 +68465,9 @@ function setCoords(cd) { /* removed: var _$d3_10 = require('d3'); */; -/* removed: var _$styleOne_315 = require('./style_one'); */; +/* removed: var _$styleOne_313 = require('./style_one'); */; -var _$style_314 = function style(gd) { +var _$style_312 = function style(gd) { gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) { var cd0 = cd[0]; var trace = cd0.trace; @@ -68604,7 +68476,7 @@ var _$style_314 = function style(gd) { traceSelection.style({opacity: trace.opacity}); traceSelection.selectAll('path.surface').each(function(pt) { - _$d3_10.select(this).call(_$styleOne_315, pt, trace); + _$d3_10.select(this).call(_$styleOne_313, pt, trace); }); }); }; @@ -68621,24 +68493,24 @@ var _$style_314 = function style(gd) { var Pie = {}; -Pie.attributes = _$attributes_304; -Pie.supplyDefaults = _$supplyDefaults_307; -Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_312; -Pie.layoutAttributes = _$layout_attributes_311; -Pie.calc = _$calc_306; -Pie.plot = _$plot_313; -Pie.style = _$style_314; -Pie.styleOne = _$styleOne_315; +Pie.attributes = _$attributes_302; +Pie.supplyDefaults = _$supplyDefaults_305; +Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_310; +Pie.layoutAttributes = _$layout_attributes_309; +Pie.calc = _$calc_304; +Pie.plot = _$plot_311; +Pie.style = _$style_312; +Pie.styleOne = _$styleOne_313; Pie.moduleType = 'trace'; Pie.name = 'pie'; -Pie.basePlotModule = _$base_plot_305; +Pie.basePlotModule = _$base_plot_303; Pie.categories = ['pie', 'showLegend']; Pie.meta = { }; -var _$Pie_310 = Pie; +var _$Pie_308 = Pie; /** * Copyright 2012-2018, Plotly, Inc. @@ -68650,7 +68522,7 @@ var _$Pie_310 = Pie; 'use strict'; -var _$pie_9 = _$Pie_310; +var _$pie_9 = _$Pie_308; /** * Copyright 2012-2018, Plotly, Inc. diff --git a/dist/plotly-finance.min.js b/dist/plotly-finance.min.js index 467bd30e5a4..af9c4d6d4f0 100644 --- a/dist/plotly-finance.min.js +++ b/dist/plotly-finance.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (finance - minified) v1.35.2 +* plotly.js (finance - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},r=[].slice,n=function(e){return r.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{n(a.documentElement.childNodes)[0].nodeType}catch(e){n=function(e){for(var t=e.length,r=new Array(t);t--;)r[t]=e[t];return r}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,r){c.call(this,e,t,r+"")},u.setProperty=function(e,t,r){f.call(this,e,t+"",r)}}function d(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=t.length);n>>1;e(t[i],r)<0?n=i+1:a=i}return n},right:function(t,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=t.length);n>>1;e(t[i],r)>0?a=i:n=i+1}return n}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var r,n,a=-1,i=e.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++an&&(r=n)}else{for(;++a=n){r=n;break}for(;++an&&(r=n)}return r},t.max=function(e,t){var r,n,a=-1,i=e.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++ar&&(r=n)}else{for(;++a=n){r=n;break}for(;++ar&&(r=n)}return r},t.extent=function(e,t){var r,n,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=n){r=a=n;break}for(;++in&&(r=n),a=n){r=a=n;break}for(;++in&&(r=n),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,r){return d(e(t),r)}:e)},t.shuffle=function(e,t,r){(i=arguments.length)<3&&(r=e.length,i<2&&(t=0));for(var n,a,i=r-t;i;)a=Math.random()*i--|0,n=e[i+t],e[i+t]=e[a+t],e[a+t]=n;return e},t.permute=function(e,t){for(var r=t.length,n=new Array(r);r--;)n[r]=e[t[r]];return n},t.pairs=function(e){for(var t=0,r=e.length-1,n=e[0],a=new Array(r<0?0:r);t=0;)for(t=(n=e[a]).length;--t>=0;)r[--o]=n[t];return r};var m=Math.abs;function x(e,t){for(var r in t)Object.defineProperty(e.prototype,r,{value:t[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,r){if(arguments.length<3&&(r=1,arguments.length<2&&(t=e,e=0)),(t-e)/r==1/0)throw new Error("infinite range");var n,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(r)),o=-1;if(e*=i,t*=i,(r*=i)<0)for(;(n=e+r*++o)>t;)a.push(n/i);else for(;(n=e+r*++o)=a.length)return r?r.call(n,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var n=[],o=i[r++];return t.forEach(function(t,a){n.push({key:t,values:e(a,r)})}),o?n.sort(function(e,t){return o(e.key,t.key)}):n}(o(t.map,e,0),0)},n.key=function(e){return a.push(e),n},n.sortKeys=function(e){return i[a.length-1]=e,n},n.sortValues=function(t){return e=t,n},n.rollup=function(e){return r=e,n},n},t.set=function(e){var t=new O;if(e)for(var r=0,n=e.length;r=0&&(n=e.slice(r+1),e=e.slice(0,r)),e)return arguments.length<2?this[e].on(n):this[e].on(n,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(n,null);return this}},t.event=null,t.requote=function(e){return e.replace(q,"\\$&")};var q=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,H={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var r in t)e[r]=t[r]};function V(e){return H(e,X),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var r=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return r.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}X.select=function(e){var t,r,n,a,i=[];e=Z(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(r=e.slice(0,t))&&(e=e.slice(t+1)),J.hasOwnProperty(r)?{space:J[r],local:e}:e}},X.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each($(r,e[r]));return this}return this.each($(e,r))},X.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var r=this.node(),n=(e=te(e)).length,a=-1;if(t=r.classList){for(;++a=0;)(r=n[a])&&(i&&i!==r.nextSibling&&i.parentNode.insertBefore(r,i),i=r);return this},X.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,r){return t&&r?e(t.__data__,r.__data__):!t-!r}}.apply(this,arguments);for(var t=-1,r=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?r?function(){var t=l(r,n(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=r}:c:r?N:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(r=a.match(n)){var i=this[a];this.removeEventListener(r[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=X.append,de.empty=X.empty,de.node=X.node,de.call=X.call,de.size=X.size,de.select=function(e){for(var t,r,n,a,i,o=[],l=-1,s=this.length;++l=n&&(n=t+1);!(o=l[n])&&++n0?1:e<0?-1:0}function ze(e,t,r){return(t[0]-e[0])*(r[1]-e[1])-(t[1]-e[1])*(r[0]-e[0])}function De(e){return e>1?0:e<-1?Te:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Ne(e){return((e=Math.exp(e))+1/e)/2}function Ie(e){return(e=Math.sin(e/2))*e}var Re=Math.SQRT2;t.interpolateZoom=function(e,t){var r,n,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function O(e){--v||(e({type:"zoomend"}),r=null)}function P(){var e=this,r=_.of(e,arguments),n=0,a=t.select(o(e)).on(m,function(){n=1,T(t.mouse(e),i),S(r)}).on(x,function(){a.on(m,null).on(x,null),l(n),O(r)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(r)}function z(){var e,r=this,n=_.of(r,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(r),h=xe(r);function p(){var n=t.touches(r);return e=d.k,n.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),n}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var n=t.event.changedTouches,o=0,f=n.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(r);ll.call(r);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?n+(a-n)*e/60:e<180?a:e<240?n+(a-n)*(240-e)/60:n}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,n=2*(r=r<0?0:r>1?1:r)-(a=r<=.5?r*(1+t):r+t-r*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,r,n){return this instanceof Ge?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Ze?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,r,n)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new qe;function Xe(e,t,r){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Ze(r,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Ze(e,t,r){return this instanceof Ze?(this.l=+e,this.a=+t,void(this.b=+r)):arguments.length<2?e instanceof Ze?new Ze(e.l,e.a,e.b):e instanceof Ge?Xe(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Ze(e,t,r)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Xe(this.h,this.c,this.l).rgb()},t.lab=Ze;var We=18,Qe=.95047,Je=1,$e=1.08883,Ke=Ze.prototype=new qe;function et(e,t,r){var n=(e+16)/116,a=n+t/500,i=n-r/200;return new it(at(3.2404542*(a=rt(a)*Qe)-1.5371385*(n=rt(n)*Je)-.4985314*(i=rt(i)*$e)),at(-.969266*a+1.8760108*n+.041556*i),at(.0556434*a-.2040259*n+1.0572252*i))}function tt(e,t,r){return e>0?new Ge(Math.atan2(r,t)*Oe,Math.sqrt(t*t+r*r),e):new Ge(NaN,NaN,e)}function rt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function nt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,r){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~r)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,r)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Ze(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Ze(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new qe;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,r){var n,a,i,o=0,l=0,s=0;if(n=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=n[2].split(","),n[1]){case"hsl":return r(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,r){var n,a,i=Math.min(e/=255,t/=255,r/=255),o=Math.max(e,t,r),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),n=e==o?(t-r)/l+(t0&&s<1?0:n),new He(n,a,s)}function dt(e,t,r){var n=nt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(r=ht(r)))/Qe),a=nt((.2126729*e+.7151522*t+.072175*r)/Je);return Ze(116*a-16,500*(n-a),200*(a-nt((.0193339*e+.119192*t+.9503041*r)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,r=this.g,n=this.b,a=30;return t||r||n?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var r=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=r}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(r=null==e?null:e+"",o):r},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(n(arguments)))}}),o.send=function(t,n,a){if(2===arguments.length&&"function"==typeof n&&(a=n,n=null),c.open(t,e,!0),null==r||"accept"in s||(s.accept=r+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=r&&c.overrideMimeType&&c.overrideMimeType(r),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==n?null:n),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,r){e(null==t?r:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(P),t.dsv=function(e,t){var r=new RegExp('["'+e+"\n]"),n=e.charCodeAt(0);function a(e,r,n){arguments.length<3&&(n=r,r=null);var a=mt(e,t,null==r?i:o(r),n);return a.row=function(e){return arguments.length?a.response(null==(r=e)?i:o(e)):r},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return r.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var r;return a.parseRows(e,function(e,n){if(r)return r(e,n-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");r=t?function(e,r){return t(a(e),r)}:a})},a.parseRows=function(e,t){var r,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var r=t;r++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(Tt,t)),_t=0):(_t=1,kt(Tt))}function At(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,r=1/0;t;)t.c?(t.t8?function(e){return e/r}:function(e){return e*r},symbol:e}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ct(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),St[8+n/3]};var Ot=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pt=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,r){return(e=t.round(e,Ct(e,r))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),r))))}});function zt(e){return e+""}var Dt=t.time={},Et=Date;function Nt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Nt.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(){It.setUTCDate.apply(this._,arguments)},setDay:function(){It.setUTCDay.apply(this._,arguments)},setFullYear:function(){It.setUTCFullYear.apply(this._,arguments)},setHours:function(){It.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){It.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){It.setUTCMinutes.apply(this._,arguments)},setMonth:function(){It.setUTCMonth.apply(this._,arguments)},setSeconds:function(){It.setUTCSeconds.apply(this._,arguments)},setTime:function(){It.setTime.apply(this._,arguments)}};var It=Date.prototype;function Rt(e,t,r){function n(t){var r=e(t),n=i(r,1);return t-r1)for(;o68?1900:2e3),r+a[0].length):-1}function Qt(e,t,r){return/^[+-]\d{4}$/.test(t=t.slice(r,r+5))?(e.Z=-t,r+5):-1}function Jt(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function $t(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function Kt(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+3));return n?(e.j=+n[0],r+n[0].length):-1}function er(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function tr(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function rr(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function nr(e,t,r){Bt.lastIndex=0;var n=Bt.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function ar(e){var t=e.getTimezoneOffset(),r=t>0?"-":"+",n=m(t)/60|0,a=m(t)%60;return r+Ht(n,"0",2)+Ht(a,"0",2)}function ir(e,t,r){qt.lastIndex=0;var n=qt.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function or(e){for(var t=e.length,r=-1;++r0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(r-=l,r+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(n)}:P;return function(e){var n=Ot.exec(e),a=n[1]||" ",l=n[2]||">",s=n[3]||"-",c=n[4]||"",u=n[5],f=+n[6],d=n[7],h=n[8],p=n[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=Pt.get(p)||zt;var b=u&&d;return function(e){var n=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),n=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=r+e.substring(k+1);!u&&d&&(_=o(_,1/0));var T=v.length+_.length+w.length+(b?0:i.length),A=T"===l?A+i+e:"^"===l?A.substring(0,T>>=1)+i+e+A.substring(T):i+(b?e:A+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function r(r){for(var n,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in jt?t.charAt(l++):o])||(n=i(e,r,n))<0)return-1}else if(a!=r.charCodeAt(n++))return-1}return n}u.utc=function(e){var t=u(e);function r(e){try{var r=new(Et=Nt);return r._=e,t(r)}finally{Et=Date}}return r.parse=function(e){try{Et=Nt;var r=t.parse(e);return r&&r._}finally{Et=Date}},r.toString=t.toString,r},u.multi=u.utc.multi=or;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(r),d:function(e,t){return Ht(e.getDate(),t,2)},e:function(e,t){return Ht(e.getDate(),t,2)},H:function(e,t){return Ht(e.getHours(),t,2)},I:function(e,t){return Ht(e.getHours()%12||12,t,2)},j:function(e,t){return Ht(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return Ht(e.getMilliseconds(),t,3)},m:function(e,t){return Ht(e.getMonth()+1,t,2)},M:function(e,t){return Ht(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return Ht(e.getSeconds(),t,2)},U:function(e,t){return Ht(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ht(Dt.mondayOfYear(e),t,2)},x:u(n),X:u(a),y:function(e,t){return Ht(e.getFullYear()%100,t,2)},Y:function(e,t){return Ht(e.getFullYear()%1e4,t,4)},Z:ar,"%":function(){return"%"}},w={a:function(e,t,r){g.lastIndex=0;var n=g.exec(t.slice(r));return n?(e.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(e,t,r){h.lastIndex=0;var n=h.exec(t.slice(r));return n?(e.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(e,t,r){x.lastIndex=0;var n=x.exec(t.slice(r));return n?(e.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(e,t,r){y.lastIndex=0;var n=y.exec(t.slice(r));return n?(e.m=m.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(e,t,r){return f(e,_.c.toString(),t,r)},d:$t,e:$t,H:er,I:er,j:Kt,L:nr,m:Jt,M:tr,p:function(e,t,r){var n=d.get(t.slice(r,r+=2).toLowerCase());return null==n?-1:(e.p=n,r)},S:rr,U:Yt,w:Gt,W:Xt,x:function(e,t,r){return f(e,_.x.toString(),t,r)},X:function(e,t,r){return f(e,_.X.toString(),t,r)},y:Wt,Y:Zt,Z:Qt,"%":ir};return u}(e)}};var lr=t.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"]});function sr(){}t.format=lr.numberFormat,t.geo={},sr.prototype={s:0,t:0,add:function(e){ur(e,this.t,cr),ur(cr.s,this.s,this),this.s?this.t+=cr.t:this.s=cr.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cr=new sr;function ur(e,t,r){var n=r.s=e+t,a=n-e,i=n-a;r.t=e-i+(t-a)}function fr(e,t){e&&hr.hasOwnProperty(e.type)&&hr[e.type](e,t)}t.geo.stream=function(e,t){e&&dr.hasOwnProperty(e.type)?dr[e.type](e,t):fr(e,t)};var dr={Feature:function(e,t){fr(e.geometry,t)},FeatureCollection:function(e,t){for(var r=e.features,n=-1,a=r.length;++n=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=n*s+u*Math.cos(l),d=u*o*Math.sin(l);Cr.add(Math.atan2(d,f)),r=e,n=s,a=c}Sr.point=function(o,l){Sr.point=i,r=(e=o)*Se,n=Math.cos(l=(t=l)*Se/2+Te/4),a=Math.sin(l)},Sr.lineEnd=function(){i(e,t)}}function Pr(e){var t=e[0],r=e[1],n=Math.cos(r);return[n*Math.cos(t),n*Math.sin(t),Math.sin(r)]}function zr(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Dr(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Er(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Nr(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Ir(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Rr(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function Fr(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(r=-90),f[0]=e,f[1]=n}};function h(t,i){u.push(f=[e=t,n=t]),ia&&(a=i)}function p(t,o){var l=Pr([t*Se,o*Se]);if(s){var c=Dr(s,l),u=Dr([c[1],-c[0],0],c);Ir(u),u=Rr(u);var f=t-i,d=f>0?1:-1,p=u[0]*Oe*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(tn&&(n=t)):t>i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=n,d.point=h,s=null}function y(e,t){if(s){var r=e-i;c+=m(r)>180?r+(r>0?360:-360):r}else o=e,l=t;Sr.point(e,t),p(e,t)}function x(){Sr.lineStart()}function b(){y(o,l),Sr.lineEnd(),m(c)>ke&&(e=-(n=180)),f[0]=e,f[1]=n,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],n=g[1])}return u=f=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,a]]}}(),t.geo.centroid=function(e){yr=mr=xr=br=_r=wr=kr=Mr=Tr=Ar=Lr=0,t.geo.stream(e,jr);var r=Tr,n=Ar,a=Lr,i=r*r+n*n+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else n(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Zr(e){if(t=e.length){for(var t,r,n=0,a=e[0];++n=0?1:-1,k=w*_,M=k>Te,T=p*x;if(Cr.add(Math.atan2(T*w*Math.sin(k),g*b+T*Math.cos(k))),i+=M?_+w*Ae:_,M^d>=r^y>=r){var A=Dr(Pr(f),Pr(e));Ir(A);var L=Dr(a,A);Ir(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(n>C||n===C&&(A[0]||A[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&r.push(r.pop().concat(r.shift())),l.push(r.filter(Jr))}return u}}function Jr(e){return e.length>1}function $r(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,r){e.push([t,r])},lineEnd:N,buffer:function(){var r=t;return t=[],e=null,r},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Kr(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var en=Qr(Yr,function(e){var t,r=NaN,n=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Te:-Te,s=m(i-r);m(s-Te)0?Ce:-Ce),e.point(a,n),e.lineEnd(),e.lineStart(),e.point(l,n),e.point(i,n),t=0):a!==l&&s>=Te&&(m(r-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(n))*Math.sin(r)-Math.sin(n)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+n)/2}(r,n,i,o),e.point(a,n),e.lineEnd(),e.lineStart(),e.point(l,n),t=0),e.point(r=i,n=o),a=l},lineEnd:function(){e.lineEnd(),r=n=NaN},clean:function(){return 2-t}}},function(e,t,r,n){var a;if(null==e)a=r*Ce,n.point(-Te,a),n.point(0,a),n.point(Te,a),n.point(Te,0),n.point(Te,-a),n.point(0,-a),n.point(-Te,-a),n.point(-Te,0),n.point(-Te,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rn=1e9;function nn(e,r,n,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=$r(),w=tn(e,r,n,a),k={point:A,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=A,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var r=function(e){for(var t=0,r=u.length,n=e[1],a=0;an&&ze(c,i,e)>0&&++t:i[1]<=n&&ze(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),n=x&&r,i=c.length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Xr(c,o,r,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:n,u>1?a:r)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function T(t,i){return e<=t&&t<=n&&r<=i&&i<=a}function A(e,t){T(e,t)&&s.point(e,t)}function L(e,t){var r=T(e=Math.max(-rn,Math.min(rn,e)),t=Math.max(-rn,Math.min(rn,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=r,m=!1,r&&(s.lineStart(),s.point(e,t));else if(r&&y)s.point(e,t);else{var n={a:{x:g,y:v},b:{x:e,y:t}};w(n)?(y||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),x=!1):r&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=r}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-n)0?2:1:m(t[1]-r)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var r=i(e,1),n=i(t,1);return r!==n?r-n:0===r?t[1]-e[1]:1===r?e[0]-t[0]:2===r?e[1]-t[1]:t[0]-e[0]}}function an(e){var t=0,r=Te/3,n=Ln(e),a=n(t,r);return a.parallels=function(e){return arguments.length?n(t=e[0]*Te/180,r=e[1]*Te/180):[t/Te*180,r/Te*180]},a}function on(e,t){var r=Math.sin(e),n=(r+Math.sin(t))/2,a=1+r*(2*n-r),i=Math.sqrt(a)/n;function o(e,t){var r=Math.sqrt(a-2*n*Math.sin(t))/n;return[r*Math.sin(e*=n),i-r*Math.cos(e)]}return o.invert=function(e,t){var r=i-t;return[Math.atan2(e,r)/n,Ee((a-(e*e+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var e,t,r,n,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=nn(e=+l[0][0],t=+l[0][1],r=+l[1][0],n=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,r){e=[t,r]}};function c(t){var i=t[0],o=t[1];return e=null,r(i,o),e||(n(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),r=i.translate(),n=(e[0]-r[0])/t,a=(e[1]-r[1])/t;return(a>=.12&&a<.234&&n>=-.425&&n<-.214?o:a>=.166&&a<.234&&n>=-.214&&n<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),r=o.stream(e),n=l.stream(e);return{point:function(e,a){t.point(e,a),r.point(e,a),n.point(e,a)},sphere:function(){t.sphere(),r.sphere(),n.sphere()},lineStart:function(){t.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){t.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){t.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){t.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return r=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,n=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var ln,sn,cn,un,fn,dn,hn={point:N,lineStart:N,lineEnd:N,polygonStart:function(){sn=0,hn.lineStart=pn},polygonEnd:function(){hn.lineStart=hn.lineEnd=hn.point=N,ln+=m(sn/2)}};function pn(){var e,t,r,n;function a(e,t){sn+=n*e-r*t,r=e,n=t}hn.point=function(i,o){hn.point=a,e=r=i,t=n=o},hn.lineEnd=function(){a(e,t)}}var gn={point:function(e,t){efn&&(fn=e);tdn&&(dn=t)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vn(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yn,mn={point:xn,lineStart:bn,lineEnd:_n,polygonStart:function(){mn.lineStart=wn},polygonEnd:function(){mn.point=xn,mn.lineStart=bn,mn.lineEnd=_n}};function xn(e,t){xr+=e,br+=t,++_r}function bn(){var e,t;function r(r,n){var a=r-e,i=n-t,o=Math.sqrt(a*a+i*i);wr+=o*(e+r)/2,kr+=o*(t+n)/2,Mr+=o,xn(e=r,t=n)}mn.point=function(n,a){mn.point=r,xn(e=n,t=a)}}function _n(){mn.point=xn}function wn(){var e,t,r,n;function a(e,t){var a=e-r,i=t-n,o=Math.sqrt(a*a+i*i);wr+=o*(r+e)/2,kr+=o*(n+t)/2,Mr+=o,Tr+=(o=n*e-r*t)*(r+e),Ar+=o*(n+t),Lr+=3*o,xn(r=e,n=t)}mn.point=function(i,o){mn.point=a,xn(e=r=i,t=n=o)},mn.lineEnd=function(){a(e,t)}}function kn(e){var t=.5,r=Math.cos(30*Se),n=16;function a(t){return(n?function(t){var r,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(r,n){r=e(r,n),t.point(r[0],r[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(r,a){var o=Pr([r,a]),l=e(r,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=r,h=o[0],p=o[1],g=o[2],n,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(r=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,r,l,s,c,n,t),v.lineEnd=b,b()}return v}:function(t){return Tn(t,function(r,n){r=e(r,n),t.point(r[0],r[1])})})(t)}function i(n,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-n,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,T=Math.sqrt(w*w+k*k+M*M),A=Math.asin(M/=T),L=m(m(M)-1)t||m((x*P+b*z)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mn(e){this.stream=e}function Tn(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function An(e){return Ln(function(){return e})()}function Ln(e){var r,n,a,i,o,l,s=kn(function(e,t){return[(e=r(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=en,x=P,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Oe,e[1]*Oe]}function M(){a=Gr(n=Pn(p,g,v),r);var e=r(d,h);return i=u-e[0]*c,o=f+e[1]*c,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cn(y(n,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,en):function(e){var t=Math.cos(e),r=t>0,n=m(t)>ke;return Qr(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=r?g?0:o(f,d):g?o(f+(f<0?Te:-Te),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(Fr(t,h)||Fr(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(n&&t&&r^g){var y;v&l||!(y=i(p,t,!0))||(u=0,r?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&Fr(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Nn(e,6*Se),r?[0,-e]:[-Te,e-Te]);function a(e,r){return Math.cos(e)*Math.cos(r)>t}function i(e,r,n){var a=[1,0,0],i=Dr(Pr(e),Pr(r)),o=zr(i,i),l=i[0],s=o-l*l;if(!s)return!n&&e;var c=t*o/s,u=-t*l/s,f=Dr(a,i),d=Nr(a,c);Er(d,Nr(i,u));var h=f,p=zr(d,h),g=zr(h,h),v=p*p-g*(zr(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=Nr(h,(-p-y)/g);if(Er(x,d),x=Rr(x),!n)return x;var b,_=e[0],w=r[0],k=e[1],M=r[1];w<_&&(b=_,_=w,w=b);var T=w-_,A=m(T-Te)0^x[1]<(m(x[0]-_)Te^(_<=x[0]&&x[0]<=w)){var L=Nr(h,(-p+y)/g);return Er(L,d),[x,Rr(L)]}}}function o(t,n){var a=r?e:Te-e,i=0;return t<-a?i|=1:t>a&&(i|=2),n<-a?i|=4:n>a&&(i|=8),i}}((b=+e)*Se),T()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?nn(e[0][0],e[0][1],e[1][0],e[1][1]):P,T()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Se,h=e[1]%360*Se,M()):[d*Oe,h*Oe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*Oe,g*Oe,v*Oe]},t.rebind(w,s,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&k,M()}}function Cn(e){return Tn(e,function(t,r){e.point(t*Se,r*Se)})}function Sn(e,t){return[e,t]}function On(e,t){return[e>Te?e-Ae:e<-Te?e+Ae:e,t]}function Pn(e,t,r){return e?t||r?Gr(Dn(e),En(t,r)):Dn(e):t||r?En(t,r):On}function zn(e){return function(t,r){return[(t+=e)>Te?t-Ae:t<-Te?t+Ae:t,r]}}function Dn(e){var t=zn(e);return t.invert=zn(-e),t}function En(e,t){var r=Math.cos(e),n=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*r+l*n;return[Math.atan2(s*a-u*i,l*r-c*n),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*r+u*n),Ee(u*r-l*n)]},o}function Nn(e,t){var r=Math.cos(e),n=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=In(r,a),i=In(r,i),(o>0?ai)&&(a+=o*Ae)):(a=e+o*Ae,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=Oe,t[1]*=Oe,t},t},On.invert=Sn,t.geo.circle=function(){var e,t,r=[0,0],n=6;function a(){var e="function"==typeof r?r.apply(this,arguments):r,n=Pn(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=n(e,t)),e[0]*=Oe,e[1]*=Oe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(r=e,a):r},a.angle=function(r){return arguments.length?(t=Nn((e=+r)*Se,n*Se),a):e},a.precision=function(r){return arguments.length?(t=Nn(e*Se,(n=+r)*Se),a):n},a.angle(90)},t.geo.distance=function(e,t){var r,n=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(n),l=Math.cos(n),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-s*f*l)*r),s*u+c*f*l)},t.geo.graticule=function(){var e,r,n,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,n,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(r/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(n).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],n=+e[1][0],s=+e[0][1],l=+e[1][1],a>n&&(e=a,a=n,n=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[n,l]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],r>e&&(t=r,r=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[r,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Rn(o,i,90),u=Fn(r,e,y),f=Rn(s,l,90),d=Fn(a,n,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,r,n=jn,a=Bn;function i(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||a.apply(this,arguments))},i.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,i):n},i.target=function(e){return arguments.length?(a=e,r="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return r=e[0]*Se,n=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(n),l=Math.sin(n),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(r),f=o*Math.sin(r),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ie(i-n)+o*s*Ie(a-r))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,r=Math.sin(p-e)*g,n=r*u+t*d,a=r*f+t*h,i=r*l+t*c;return[Math.atan2(a,n)*Oe,Math.atan2(i,Math.sqrt(n*n+a*a))*Oe]}:function(){return[r*Oe,n*Oe]}).distance=p,v;var r,n,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yn=0,t.geo.stream(e,qn),yn};var qn={sphere:N,point:N,lineStart:function(){var e,t,r;function n(n,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((n*=Se)-e),s=Math.cos(l);yn+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=r*i-t*o*s)*l),t*i+r*o*s),e=n,t=i,r=o}qn.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),r=Math.cos(i),qn.point=n},qn.lineEnd=function(){qn.point=qn.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function Hn(e,t){function r(t,r){var n=Math.cos(t),a=Math.cos(r),i=e(n*a);return[i*a*Math.sin(t),i*Math.sin(r)]}return r.invert=function(e,r){var n=Math.sqrt(e*e+r*r),a=t(n),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,n*o),Math.asin(n&&r*i/n)]},r}var Vn=Hn(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return An(Vn)}).raw=Vn;var Un=Hn(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},P);function Gn(e,t){var r=Math.cos(e),n=function(e){return Math.tan(Te/4+e/2)},a=e===t?Math.sin(e):Math.log(r/Math.cos(t))/Math.log(n(t)/n(e)),i=r*Math.pow(n(e),a)/a;if(!a)return Zn;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var r=i/Math.pow(n(t),a);return[r*Math.sin(a*e),i-r*Math.cos(a*e)]}return o.invert=function(e,t){var r=i-t,n=Pe(a)*Math.sqrt(e*e+r*r);return[Math.atan2(e,r)/a,2*Math.atan(Math.pow(i/n,1/a))-Ce]},o}function Yn(e,t){var r=Math.cos(e),n=e===t?Math.sin(e):(r-Math.cos(t))/(t-e),a=r/n+e;if(m(n)1&&ze(e[r[n-2]],e[r[n-1]],e[a])<=0;)--n;r[n++]=a}return r.slice(0,n)}function ra(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return An(Jn)}).raw=Jn,$n.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wn($n),t=e.center,r=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?r([e[0],e[1],e.length>2?e[2]+90:90]):[(e=r())[0],e[1],e[2]-90]},r([0,0,90])}).raw=$n,t.geom={},t.geom.hull=function(e){var t=Kn,r=ea;if(arguments.length)return n(e);function n(e){if(e.length<3)return[];var n,a=vt(t),i=vt(r),o=e.length,l=[],s=[];for(n=0;n=0;--n)h.push(e[l[c[n]][2]]);for(n=+f;nke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){n>-ke?(t=l.P,r=l):a>-ke?(t=l,r=l.N):t=r=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||r){if(t===r)return ka(t),r=pa(t.site),ca.insert(s,r),s.edge=r.edge=Aa(t.site,s.site),wa(t),void wa(r);if(r){ka(t),ka(r);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=r.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(r.edge,c,p,b),s.edge=Aa(c,e,null,b),r.edge=Aa(e,p,null,b),wa(t),wa(r)}else s.edge=Aa(t.site,s.site)}}function ma(e,t){var r=e.site,n=r.x,a=r.y,i=a-t;if(!i)return n;var o=e.P;if(!o)return-1/0;var l=(r=o.site).x,s=r.y,c=s-t;if(!c)return l;var u=l-n,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+n:(n+l)/2}function xa(e,t){var r=e.N;if(r)return ma(r,t);var n=e.site;return n.y===t?n.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,r=e.N;if(t&&r){var n=t.site,a=e.site,i=r.site;if(n!==i){var o=a.x,l=a.y,s=n.x-o,c=n.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){Oa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};r={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/n,y:s};r={x:(c-a)/n,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:n*o+a};r={x:l,y:n*l+a}}else{if(i){if(i.xke||m(a-r)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(n-f)ke?{x:f,y:m(t-f)ke?{x:m(r-p)ke?{x:d,y:m(t-d)ke?{x:m(r-h)=r&&c.x<=a&&c.y>=n&&c.y<=o?[[r,o],[a,o],[a,n],[r,n]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(n(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(r,n){for(var a,i,o,l,s=r.site,c=r.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(r=r[0])===(n=n[0])?l[o]?l[o]+=n:l[++o]=n:(l[++o]=null,s.push({i:o,x:qa(r,n)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,r,n,a,i,o,l){if(!isNaN(r)&&!isNaN(n))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-r)+m(c-n)<.01)T(e,t,r,n,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,T(e,u,s,c,a,i,o,l),T(e,t,r,n,a,i,o,l)}else e.x=r,e.y=n,e.point=t}else T(e,t,r,n,a,i,o,l)}function T(e,t,r,n,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=r>=s,f=n>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,r,n,a,i,o,l)}w>k?v=p+w:g=h+k;var A={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(A.visit=function(e){!function e(t,r,n,a,i,o){if(!t(r,n,a,i,o)){var l=.5*(n+i),s=.5*(a+o),c=r.nodes;c[0]&&e(t,c[0],n,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],n,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,A,h,p,g,v)},A.find=function(e){return function(e,t,r,n,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(n=t.interpolators[a](e,r)););return n}function Ya(e,t){var r,n=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(r=0;r=1)return 1;var t=e*e,r=t*e;return 4*(e<.5?r:3*(e-t)+r-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ri(e){return Math.pow(2,10*(e-1))}function ni(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(r){return Math.round(e+t*r)}}function oi(e){var t,r,n,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(n=-l)*(r=a)[0],t[1]+=n*r[1],t))||0;a[0]*i[1]=0?e.slice(0,n):e,i=n>=0?e.slice(n+1):"in";return a=Za.get(a)||Xa,i=Wa.get(i)||P,t=i(a.apply(null,r.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,a=e.c,i=e.l,o=r.h-n,l=r.c-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.c:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(e){return Xe(n+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,a=e.s,i=e.l,o=r.h-n,l=r.s-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.s:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(n+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,a=e.a,i=e.b,o=r.l-n,l=r.a-a,s=r.b-i;return function(e){return et(n+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var r=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){r.setAttribute("transform",e);var t=r.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,r){var n=[],a=[];return e=t.transform(e),r=t.transform(r),function(e,t,r,n){if(e[0]!==t[0]||e[1]!==t[1]){var a=r.push("translate(",null,",",null,")");n.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else(t[0]||t[1])&&r.push("translate("+t+")")}(e.translate,r.translate,n,a),function(e,t,r,n){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),n.push({i:r.push(ui(r)+"rotate(",null,")")-2,x:qa(e,t)})):t&&r.push(ui(r)+"rotate("+t+")")}(e.rotate,r.rotate,n,a),function(e,t,r,n){e!==t?n.push({i:r.push(ui(r)+"skewX(",null,")")-2,x:qa(e,t)}):t&&r.push(ui(r)+"skewX("+t+")")}(e.skew,r.skew,n,a),function(e,t,r,n){if(e[0]!==t[0]||e[1]!==t[1]){var a=r.push(ui(r)+"scale(",null,",",null,")");n.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else 1===t[0]&&1===t[1]||r.push(ui(r)+"scale("+t+")")}(e.scale,r.scale,n,a),e=r=null,function(e){for(var t,r=-1,i=a.length;++r0?n=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:n=0})):t>0&&(s.start({type:"start",alpha:n=t}),e=Mt(l.tick)),l):n},l.start=function(){var e,t,r,n=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)r.push(a[n])}function Ti(e,t){for(var r=[e],n=[];null!=(e=r.pop());)if(n.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;r&&(i.value=0),i.children=c}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Ti(a,function(t){var n,a;e&&(n=t.children)&&n.sort(e),r&&(a=t.parent)&&(a.value+=t.value)}),l}return n.sort=function(t){return arguments.length?(e=t,n):e},n.children=function(e){return arguments.length?(t=e,n):t},n.value=function(e){return arguments.length?(r=e,n):r},n.revalue=function(e){return r&&(Mi(e,function(e){e.children&&(e.value=0)}),Ti(e,function(e){var t;e.children||(e.value=+r.call(n,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var a=e.call(this,t,n);return function e(t,r,n,a){var i=t.children;if(t.x=r,t.y=t.depth*a,t.dx=n,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(n=t.value?n/t.value:0;++cl&&(l=n),o.push(n)}for(r=0;ra&&(n=r,a=t);return n}function ji(e){return e.reduce(Bi,0)}function Bi(e,t){return e+t[1]}function qi(e,t){return Hi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Hi(e,t){for(var r=-1,n=+e[0],a=(e[1]-n)/t,i=[];++r<=t;)i[r]=a*r+n;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var r=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=r,r._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Xi(e,t){var r=t.x-e.x,n=t.y-e.y,a=e.r+t.r;return.999*a*a>r*r+n*n}function Zi(e){if((t=e.children)&&(s=t.length)){var t,r,n,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(r=t[0]).x=-r.r,r.y=0,x(r),s>1&&((n=t[1]).x=n.r,n.y=0,x(n),s>2))for(Ji(r,n,a=t[2]),x(a),Gi(r,a),r._pack_prev=a,Gi(a,n),n=r._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(r=e,i):r},i.range=function(e){return arguments.length?(n=vt(e),i):n},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return Hi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Ui),n=0,a=[1,1];function i(t,i){var o=r.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ti(l,function(e){e.r=+u(e.value)}),Ti(l,Zi),n){var f=n*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ti(l,function(e){e.r+=f}),Ti(l,Zi),Ti(l,function(e){e.r-=f})}return function e(t,r,n,a){var i=t.children;t.x=r+=a*t.x;t.y=n+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=r(d,h)/2-d.x,v=n[0]/(h.x+r(h,d)/2+g),y=n[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,n=e.parent.children,a=e.i?n[e.i-1]:null;if(t.length){!function(e){var t,r=0,n=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=r,t.m+=r,r+=t.s+(n+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+r(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+r(e._,a._));e.parent.A=function(e,t,n){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+r(l._,i._))>0&&(to(ro(l,e,n),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,n=e)}return n}(e,a,e.parent.A||n[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=n[0],e.y=e.depth*n[1]}return i.separation=function(e){return arguments.length?(r=e,i):r},i.size=function(e){return arguments.length?(a=null==(n=e)?s:null,i):a?null:n},i.nodeSize=function(e){return arguments.length?(a=null==(n=e)?null:s,i):a?n:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=$i,n=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ti(c,function(e){var n=e.children;n&&n.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(n),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(n)):(e.x=l?u+=r(e,l):0,e.y=0,l=e)});var f=function e(t){var r=t.children;return r&&r.length?e(r[0]):t}(c),d=function e(t){var r,n=t.children;return n&&(r=n.length)?e(n[r-1]):t}(c),h=f.x-r(f,d)/2,p=d.x+r(d,f)/2;return Ti(c,a?function(e){e.x=(e.x-c.x)*n[0],e.y=(c.y-e.y)*n[1]}:function(e){e.x=(e.x-h)/(p-h)*n[0],e.y=(1-(c.y?e.y/c.y:1))*n[1]}),s}return i.separation=function(e){return arguments.length?(r=e,i):r},i.size=function(e){return arguments.length?(a=null==(n=e),i):a?null:n},i.nodeSize=function(e){return arguments.length?(a=null!=(n=e),i):a?n:null},ki(i,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,a=[1,1],i=null,o=no,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var r,n,a=-1,i=e.length;++a0;)l.push(r=c[a-1]),l.area+=r.area,"squarify"!==s||(n=h(l,g))<=d?(c.pop(),d=n):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var r,n=o(e),a=t.slice(),i=[];for(u(a,n.dx*n.dy/e.value),i.area=0;r=a.pop();)i.push(r),i.area+=r.area,null!=r.z&&(p(i,r.z?n.dx:n.dy,n,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var r,n=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=r));return t*=t,(n*=n)?Math.max(t*a*c/n,n/(t*i*c)):1/0}function p(e,t,r,a){var i,o=-1,l=e.length,s=r.x,c=r.y,u=t?n(e.area/t):0;if(t==r.dx){for((a||u>r.dy)&&(u=r.dy);++or.dx)&&(u=r.dx);++o1);return e+t*r*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(e){return function(){for(var t=0,r=0;r2?fo:lo,l=a?hi:di;return i=e(t,r,l,n),o=e(r,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(r=e,l()):r};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(n=e,l()):n};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,r){return yo(t,e,r)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,r,n,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(n)}function l(e){return a?Math.pow(n,e):-Math.pow(n,-e)}function s(e){return r(o(e))}s.invert=function(e){return l(r.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,r.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(n=+e,r.domain(i.map(o)),s):n};s.nice=function(){var e=so(i.map(o),a?Math:_o);return r.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],r=e[0],s=e[1],c=Math.floor(o(r)),u=Math.ceil(o(s)),f=n%1?2:n;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,r){if(!arguments.length)return bo;arguments.length<2?r=bo:"function"!=typeof r&&(r=t.format(r));var a=Math.max(1,n*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*n0?a[e-1]:r[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,T,A=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=n===Co?Math.sqrt(l*l+c*c):+n.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(A=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Te?0:1;if(L&&Eo(m,x,b,_)===h^S){var O=(u+f)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-A),k=l*Math.sin(f-A),M=l*Math.cos(u+A),T=l*Math.sin(u+A);var P=Math.abs(u-f+2*A)<=Te?0:1;if(A&&Eo(w,k,M,T)===1-h^P){var z=(u+f)/2;w=l*Math.cos(z),k=l*Math.sin(z),M=T=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+r.apply(this,arguments)))>.001){g=l0?0:1}function No(e,t,r,n,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?n:-n)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=r-n,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,T=(-b*v+y*_)/m,A=w-p,L=k-g,C=M-p,S=T-g;return A*A+L*L>C*C+S*S&&(w=M,k=T),[[w-s,k-c],[w*r/x,k*r/x]]}function Io(e){var t=Kn,r=ea,n=Yr,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(r);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",n[0]);return a.join("")},"step-before":Bo,"step-after":qo,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,r=[],n=-1,a=e.length,i=[0],o=[0];for(;++n<3;)t=e[n],i.push(t[0]),o.push(t[1]);r.push(Go(Zo,i)+","+Go(Zo,o)),--n;for(;++n9&&(a=3*t/Math.sqrt(a),o[l]=a*r,o[l+1]=a*n));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function jo(e){return e.join("L")+"Z"}function Bo(e){for(var t=0,r=e.length,n=e[0],a=[n[0],",",n[1]];++t1){l=t[1],i=e[s],s++,n+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cTe)+",1 "+t}function s(e,t,r,n){return"Q 0,0 "+n}return i.radius=function(e){return arguments.length?(r=vt(e),i):r},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(n=vt(e),i):n},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=jn,t=Bn,r=el;function n(n,a){var i=e.call(this,n,a),o=t.call(this,n,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(r))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return n.source=function(t){return arguments.length?(e=vt(t),n):e},n.target=function(e){return arguments.length?(t=vt(e),n):t},n.projection=function(e){return arguments.length?(r=e,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=el,n=e.projection;return e.projection=function(e){return arguments.length?n(function(e){return function(){var t=e.apply(this,arguments),r=t[0],n=t[1]-Ce;return[r*Math.cos(n),r*Math.sin(n)]}}(r=e)):r},e},t.svg.symbol=function(){var e=rl,t=tl;function r(r,n){return(al.get(e.call(this,r,n))||nl)(t.call(this,r,n))}return r.type=function(t){return arguments.length?(e=vt(t),r):e},r.size=function(e){return arguments.length?(t=vt(e),r):t},r};var al=t.map({circle:nl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),r=t*ol;return"M0,"+-t+"L"+r+",0 0,"+t+" "+-r+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),r=t*il/2;return"M0,"+r+"L"+t+","+-r+" "+-t+","+-r+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),r=t*il/2;return"M0,"+-r+"L"+t+","+r+" "+-t+","+r+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);X.transition=function(e){for(var t,r,n=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[n]:delete e[r],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[n]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=X.call,dl.empty=X.empty,dl.node=X.node,dl.size=X.size,t.transition=function(e,r){return e&&e.transition?ul?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,r,n,a=this.id,i=this.namespace,o=[];e=Z(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=n.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),T=xe(y),A=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,A[0]-=l[1],A[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(A[0]+=l[1],A[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",z):L.on("mousemove.brush",O).on("mouseup.brush",z),b.interrupt().selectAll("*").interrupt(),M)A[0]=l[0]-A[0],A[1]=s[0]-A[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-A[0],s[1-S]-A[1]],A[0]=l[C],A[1]=s[S]}else t.event.altKey&&(f=A.slice());function O(){var e=t.mouse(y),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),A[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var r=io(a.domain()),n=null==e?i(r,10):"number"==typeof e?i(r,e):!e.range&&[{range:e},t];return n&&(e=n[0],t=n[1]),e.range(r[0],Sl(+r[1]+1),t<1?1:t)},a.tickFormat=function(){return n},a.copy=function(){return Cl(e.copy(),r,n)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Al,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Al.toString,Dt.second=Rt(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=Rt(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=Rt(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=Rt(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Pl=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],zl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Yr]]),Dl={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Sl)},floor:P,ceil:P};Pl.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),Pl,zl)};var El=Pl.map(function(e){return[e[0].utc,e[1]]}),Nl=Tl.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Yr]]);function Il(e){return JSON.parse(e.responseText)}function Rl(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Nl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Il,t)},t.html=function(e,t){return mt(e,"text/html",Rl,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t={};t.xmlns="http://www.w3.org/2000/xmlns/",t.svg="http://www.w3.org/2000/svg",t.xlink="http://www.w3.org/1999/xlink",t.svgAttrs={xmlns:t.svg,"xmlns:xlink":t.xlink};var r=function(e){var t=typeof e;if("string"===t){var r=e;if(0===(e=+e)&&function(e){for(var t,r=e.length,n=0;n13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(r))return!1}else if("number"!==t)return!1;return e-e<1},n={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},a={},i=Math.PI;a.deg2rad=function(e){return e/180*i},a.rad2deg=function(e){return e/i*180},a.wrap360=function(e){var t=e%360;return t<0?t+360:t},a.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var o=n.BADNUM,l=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(e){var t=/^\s+/,r=/\s+$/,n=0,a=e.round,i=e.min,o=e.max,l=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(n){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof n&&(n=function(e){e=e.replace(t,"").replace(r,"").toLowerCase();var n,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(n=B.rgb.exec(e))return{r:n[1],g:n[2],b:n[3]};if(n=B.rgba.exec(e))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=B.hsl.exec(e))return{h:n[1],s:n[2],l:n[3]};if(n=B.hsla.exec(e))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=B.hsv.exec(e))return{h:n[1],s:n[2],v:n[3]};if(n=B.hsva.exec(e))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=B.hex8.exec(e))return{r:z(n[1]),g:z(n[2]),b:z(n[3]),a:I(n[4]),format:a?"name":"hex8"};if(n=B.hex6.exec(e))return{r:z(n[1]),g:z(n[2]),b:z(n[3]),format:a?"name":"hex"};if(n=B.hex4.exec(e))return{r:z(n[1]+""+n[1]),g:z(n[2]+""+n[2]),b:z(n[3]+""+n[3]),a:I(n[4]+""+n[4]),format:a?"name":"hex8"};if(n=B.hex3.exec(e))return{r:z(n[1]+""+n[1]),g:z(n[2]+""+n[2]),b:z(n[3]+""+n[3]),format:a?"name":"hex"};return!1}(n));"object"==typeof n&&(q(n.r)&&q(n.g)&&q(n.b)?(h=n.r,p=n.g,g=n.b,a={r:255*O(h,255),g:255*O(p,255),b:255*O(g,255)},f=!0,d="%"===String(n.r).substr(-1)?"prgb":"rgb"):q(n.h)&&q(n.s)&&q(n.v)?(s=E(n.s),c=E(n.v),a=function(t,r,n){t=6*O(t,360),r=O(r,100),n=O(n,100);var a=e.floor(t),i=t-a,o=n*(1-r),l=n*(1-i*r),s=n*(1-(1-i)*r),c=a%6;return{r:255*[n,l,o,o,s,n][c],g:255*[s,n,n,l,o,o][c],b:255*[o,o,s,n,n,l][c]}}(n.h,s,c),f=!0,d="hsv"):q(n.h)&&q(n.s)&&q(n.l)&&(s=E(n.s),u=E(n.l),a=function(e,t,r){var n,a,i;function o(e,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?e+6*(t-e)*r:r<.5?t:r<2/3?e+(t-e)*(2/3-r)*6:e}if(e=O(e,360),t=O(t,100),r=O(r,100),0===t)n=a=i=r;else{var l=r<.5?r*(1+t):r+t-r*t,s=2*r-l;n=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*n,g:255*a,b:255*i}}(n.h,s,u),f=!0,d="hsl"),n.hasOwnProperty("a")&&(l=n.a));var h,p,g;return l=S(l),{ok:f,format:n.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=n++}function u(e,t,r){e=O(e,255),t=O(t,255),r=O(r,255);var n,a,l=o(e,t,r),s=i(e,t,r),c=(l+s)/2;if(l==s)n=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:n=(t-r)/u+(t>1)+720)%360;--t;)n.h=(n.h+a)%360,i.push(c(n));return i}function A(e,t){t=t||6;for(var r=c(e).toHsv(),n=r.h,a=r.s,i=r.v,o=[],l=1/t;t--;)o.push(c({h:n,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,r,n,a=this.toRgb();return t=a.r/255,r=a.g/255,n=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),r=a(100*e.s),n=a(100*e.v);return 1==this._a?"hsv("+t+", "+r+"%, "+n+"%)":"hsva("+t+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),r=a(100*e.s),n=a(100*e.l);return 1==this._a?"hsl("+t+", "+r+"%, "+n+"%)":"hsla("+t+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,r,n,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(r).toString(16)),D(N(n))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*O(this._r,255))+"%",g:a(100*O(this._g,255))+"%",b:a(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%)":"rgba("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),r=t,n=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);r="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+t+",endColorstr="+r+")"},toString:function(e){var t=!!e;e=e||this._format;var r=!1,n=this._a<1&&this._a>=0;return t||!n||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(r=this.toRgbString()),"prgb"===e&&(r=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(r=this.toHexString()),"hex3"===e&&(r=this.toHexString(!0)),"hex4"===e&&(r=this.toHex8String(!0)),"hex8"===e&&(r=this.toHex8String()),"name"===e&&(r=this.toName()),"hsl"===e&&(r=this.toHslString()),"hsv"===e&&(r=this.toHsvString()),r||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var r=e.apply(null,[this].concat([].slice.call(t)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var r={};for(var n in e)e.hasOwnProperty(n)&&(r[n]="a"===n?e[n]:E(e[n]));e=r}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(e,t,r){r=0===r?0:r||50;var n=c(e).toRgb(),a=c(t).toRgb(),i=r/100;return c({r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a})},c.readability=function(t,r){var n=c(t),a=c(r);return(e.max(n.getLuminance(),a.getLuminance())+.05)/(e.min(n.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,r){var n,a,i=c.readability(e,t);switch(a=!1,(n=function(e){var t,r;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==r&&"large"!==r&&(r="small");return{level:t,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,r){var n,a,i,o,l=null,s=0;a=(r=r||{}).includeFallbackColors,i=r.level,o=r.size;for(var u=0;us&&(s=n,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(r.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],r))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[e[r]]=r);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function O(t,r){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(r,o(0,parseFloat(t))),n&&(t=parseInt(t*r,10)/100),e.abs(t-r)<1e-6?1:t%r/parseFloat(r)}function P(e){return i(1,o(0,e))}function z(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function N(t){return e.round(255*parseFloat(t)).toString(16)}function I(e){return z(e)/255}var R,F,j,B=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",j="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function q(e){return!!B.CSS_UNIT.exec(e)}s.exports?s.exports=c:window.tinycolor=c}(Math),s=s.exports;var c={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=c.RdBu,f=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var r=0;r1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(n=e[t][0],a=e[t][1],o=!1,Y(n))for(r=n.length-1;r>=0;r--)Q(n[r],$(a,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(i=Object.keys(n),o=!1,r=i.length-1;r>=0;r--)Q(n[i[r]],$(a,i[r]))?delete n[i[r]]:o=!0;if(o)return}}(s)):o[t[i]]=n}}function $(e,t){var n=t;return r(t)?n="["+t+"]":e&&(n="."+t),e+n}function K(e,t,r,n){var a,i=Y(r),o=!0,l=r,s=n.replace("-1",0),c=!i&&Q(r,s),u=t[0];for(a=0;aa.max?t.set(n):t.set(+e)}},integer:{coerceFunction:function(e,t,n,a){e%1||!r(e)||void 0!==a.min&&ea.max?t.set(n):t.set(+e)}},string:{coerceFunction:function(e,t,r,n){if("string"!=typeof e){var a="number"==typeof e;!0!==n.strict&&a?t.set(String(e)):t.set(r)}else n.noBlank&&!e?t.set(r):t.set(e)}},color:{coerceFunction:function(e,t,r){s(e).isValid()?t.set(e):t.set(r)}},colorlist:{coerceFunction:function(e,t,r){Array.isArray(e)&&e.length&&e.every(function(e){return s(e).isValid()})?t.set(e):t.set(r)}},colorscale:{coerceFunction:function(e,t,r){t.set(d(e,r))}},angle:{coerceFunction:function(e,t,n){"auto"===e?t.set("auto"):r(e)?t.set(ie(+e)):t.set(n)}},subplotid:{coerceFunction:function(e,t,r){"string"==typeof e&&ne(r).test(e)?t.set(e):t.set(r)},validateFunction:function(e,t){var r=t.dflt;return e===r||"string"==typeof e&&!!ne(r).test(e)}},flaglist:{coerceFunction:function(e,t,r,n){if("string"==typeof e)if(-1===(n.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=le&&e<=se?e:fe;if("string"!=typeof e&&"number"!=typeof e)return fe;e=String(e);var r=_e(t),n=e.charAt(0);!r||"G"!==n&&"g"!==n||(e=e.substr(1),t="");var a=r&&"chinese"===t.substr(0,7),i=e.match(a?xe:me);if(!i)return fe;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(r){if(2===o.length)return fe;var d;o=Number(o);try{var h=D.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return fe}return d?(d.toJD()-ve)*de+c*he+u*pe+f*ge:fe}o=2===o.length?(Number(o)+2e3-be)%100+be:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?fe:g.getUTCDate()!==s?fe:g.getTime()+f*ge},le=ue.MIN_MS=ue.dateTime2ms("-9999"),se=ue.MAX_MS=ue.dateTime2ms("9999-12-31 23:59:59.9999"),ue.isDateTime=function(e,t){return ue.dateTime2ms(e,t)!==fe};var ke=90*de,Me=3*he,Te=5*pe;function Ae(e,t,r,n,a){if((t||r||n||a)&&(e+=" "+we(t,2)+":"+we(r,2),(n||a)&&(e+=":"+we(n,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+we(a,i)}return e}ue.ms2DateTime=function(e,t,r){if("number"!=typeof e||!(e>=le&&e<=se))return fe;t||(t=0);var n,a,i,o,l,s,c=Math.floor(10*ce(e+.05,1)),u=Math.round(e-c/10);if(_e(r)){var f=Math.floor(u/de)+ve,d=Math.floor(ce(e,de));try{n=D.getComponentMethod("calendars","getCal")(r).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){n=ye("G%Y-%m-%d")(new Date(u))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;a=t=le+de&&t<=se-de))return fe;var r=Math.floor(10*ce(t+.05,1)),n=new Date(Math.round(t-r/10));return Ae(e.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ue.cleanDate=function(e,t,r){if(ue.isJSDate(e)||"number"==typeof e){if(_e(r))return w.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ue.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ue.isDateTime(e,r))return w.error("unrecognized date",e),t;return e};var Le=/%\d?f/g;function Ce(e,t,r,n){e=e.replace(Le,function(e){var r=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(_e(n))try{e=D.getComponentMethod("calendars","worldCalFmt")(e,t,n)}catch(e){return"Invalid"}return r(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ue.formatDate=function(e,t,n,a,i,o){if(i=_e(i)&&i,!t)if("y"===n)t=o.year;else if("m"===n)t=o.month;else{if("d"!==n)return function(e,t){var n=ce(e+.05,de),a=we(Math.floor(n/he),2)+":"+we(ce(Math.floor(n/pe),60),2);if("M"!==t){r(t)||(t=0);var i=(100+Math.min(ce(e/ge,60),Se[t])).toFixed(t).substr(1);t>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,n)+"\n"+Ce(o.dayMonthYear,e,a,i);t=o.dayMonth+"\n"+o.year}return Ce(t,e,a,i)};var Oe=3*de;ue.incrementMonth=function(e,t,r){r=_e(r)&&r;var n=ce(e,de);if(e=Math.round(e-n),r)try{var a=Math.round(e/de)+ve,i=D.getComponentMethod("calendars","getCal")(r),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ve)*de+n}catch(t){w.error("invalid ms "+e+" in calendar "+r)}var l=new Date(e+Oe);return l.setUTCMonth(l.getUTCMonth()+t)+n-Oe},ue.findExactDates=function(e,t){for(var n,a,i=0,o=0,l=0,s=0,c=_e(t)&&D.getComponentMethod("calendars","getCal")(t),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Fe(e,t,r,n,a){var i=n*e+a*t;if(i<0)return n*n+a*a;if(i>r){var o=n-e,l=a-t;return o*o+l*l}var s=n*t-a*e;return s*s/r}Ie.segmentsIntersect=Re,Ie.segmentDistance=function(e,t,r,n,a,i,o,l){if(Re(e,t,r,n,a,i,o,l))return 0;var s=r-e,c=n-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Fe(s,c,d,a-e,i-t),Fe(s,c,d,o-e,l-t),Fe(u,f,h,e-a,t-i),Fe(u,f,h,r-a,n-i));return Math.sqrt(p)},Ie.getTextLocation=function(e,t,r,n){if(e===Ee&&n===Ne||(De={},Ee=e,Ne=n),De[r])return De[r];var a=e.getPointAtLength(ce(r-n/2,t)),i=e.getPointAtLength(ce(r+n/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(ce(r,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return De[r]=s,s},Ie.clearLocationCache=function(){Ee=null},Ie.getVisibleSegment=function(e,t,r){var n,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var r=e.getPointAtLength(t);0===t?n=r:t===u&&(a=r);var c=r.xo?r.x-o:0,f=r.ys?r.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+r)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+r))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(n.x-a.x)<.1&&Math.abs(n.y-a.y)<.1}},Ie.findPointOnPath=function(e,t,r,n){for(var a,i,o,l=(n=n||{}).pathLength||e.getTotalLength(),s=n.tolerance||.001,c=n.iterationLimit||30,u=e.getPointAtLength(0)[r]>e.getPointAtLength(l)[r]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var je=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},Be=/^\w*$/,qe={init2dArray:function(e,t){for(var r=new Array(e),n=0;nt}function Qe(e,t){return e>=t}Ye.findBin=function(e,t,n){if(r(t.start))return n?Math.ceil((e-t.start)/t.size-1e-9)-1:Math.floor((e-t.start)/t.size+1e-9);var a,i,o=0,l=t.length,s=0,c=l>1?(t[l-1]-t[0])/(l-1):1;for(i=c>=0?n?Xe:Ze:n?Qe:We,e+=1e-9*c*(n?-1:1)*(c>=0?1:-1);o90&&w.log("Long binary search..."),o-1},Ye.sorterAsc=function(e,t){return e-t},Ye.sorterDes=function(e,t){return t-e},Ye.distinctVals=function(e){var t=e.slice();t.sort(Ye.sorterAsc);for(var r=t.length-1,n=t[r]-t[0]||1,a=n/(r||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(n=Math.min(n,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:n}},Ye.roundUp=function(e,t,r){for(var n,a=0,i=t.length-1,o=0,l=r?0:1,s=r?1:0,c=r?Math.ceil:Math.floor;an.length)&&(a=n.length),r(t)||(t=!1),$e(n[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var n=t%1;return n*e[Math.ceil(t)]+(1-n)*e[Math.floor(t)]};var Ke={},et={};function tt(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}Ke.throttle=function(e,t,r){var n=et[e],a=Date.now();if(!n){for(var i in et)et[i].tsn.ts+t?o():n.timer=setTimeout(function(){o(),n.timer=null},t)},Ke.done=function(e){var t=et[e];return t&&t.timer?new Promise(function(e){var r=t.onDone;t.onDone=function(){r&&r(),e(),t.onDone=null}}):Promise.resolve()},Ke.clear=function(e){if(e)tt(et[e]),delete et[e];else for(var t in et)Ke.clear(t)};var rt=function(e,t){if(e>0)return Math.log(e)/Math.LN10;var n=Math.log(Math.min(t[0],t[1]))/Math.LN10;return r(n)||(n=Math.log(Math.max(t[0],t[1]))/Math.LN10-6),n},nt={},at=n.FP_SAFE,it=n.BADNUM,ot=nt={};ot.nestedProperty=X,ot.keyedContainer=function(e,t,r,n){var a,i;r=r||"name",n=n||"value";var o={};i=t&&t.length?X(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lat?it:r(e)?Number(e):it:it},ot.noop=T,ot.identity=function(e){return e},ot.swapAttrs=function(e,t,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(t,e)):Math.max(t,Math.min(r,e))},ot.bBoxIntersect=function(e,t,r){return r=r||0,e.left<=t.right+r&&t.left<=e.right+r&&e.top<=t.bottom+r&&t.top<=e.bottom+r},ot.simpleMap=function(e,t,r,n){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,r)?e(t,r,n):l},ot.OptionControl=function(e,t){e||(e={}),t||(t="opt");var r={optionList:[],_newoption:function(n){n[t]=e,r[n.name]=n,r.optionList.push(n)}};return r["_"+t]=e,r},ot.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var r,n,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(r=0;r=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[n];u[r]=i}return u},ot.syncOrAsync=function(e,t,r){var n;function a(){return ot.syncOrAsync(e,t,r)}for(;e.length;)if((n=(0,e.splice(0,1)[0])(t))&&n.then)return n.then(a).then(void 0,ot.promiseError);return r&&r(t)},ot.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},ot.noneOrAll=function(e,t,r){if(e){var n,a,i=!1,o=!0;for(n=0;n=0&&i%1==0){var p=a?a[h]:h,g=n?n[p]:p;f(g)&&(e[g].selected=1)}}},ot.getTargetArray=function(e,t){var r=t.target;if("string"==typeof r&&r){var n=ot.nestedProperty(e,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ot.minExtend=function(e,t){var r={};"object"!=typeof t&&(t={});var n,a,i,o=Object.keys(e);for(n=0;n1?a+o[1]:"";if(i&&(o.length>1||l.length>4||r))for(;n.test(l);)l=l.replace(n,"$1"+i+"$2");return l+s};var ct=/%{([^\s%{}]*)}/g,ut=/^\w*$/;ot.templateString=function(e,t){var r={};return e.replace(ct,function(e,n){return ut.test(n)?t[n]||"":(r[n]=r[n]||ot.nestedProperty(t,n).get,r[n]()||"")})};ot.subplotSort=function(e,t){for(var r=Math.min(e.length,t.length)+1,n=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(n=10*n+o-48),c&&(a=10*a+l-48),!s||!c){if(n!==a)return n-a;if(o!==l)return o-l}}return a-n};var ft=2e9;ot.seedPseudoRandom=function(){ft=2e9},ot.pseudoRandom=function(){var e=ft;return ft=(69069*ft+1)%4294967296,Math.abs(ft-e)<429496729?ot.pseudoRandom():ft/4294967296};var dt=te.counter,ht={idRegex:{x:dt("x"),y:dt("y")},attrRegex:dt("[xy]axis"),xAxisMatch:dt("xaxis"),yAxisMatch:dt("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}},pt={id2name:function(e){if("string"==typeof e&&e.match(ht.AX_ID_PATTERN)){var t=e.substr(1);return"1"===t&&(t=""),e.charAt(0)+"axis"+t}},name2id:function(e){if(e.match(ht.AX_NAME_PATTERN)){var t=e.substr(5);return"1"===t&&(t=""),e.charAt(0)+t}},cleanId:function(e,t){if(e.match(ht.AX_ID_PATTERN)&&(!t||e.charAt(0)===t)){var r=e.substr(1).replace(/^0+/,"");return"1"===r&&(r=""),e.charAt(0)+r}},list:function(e,t,r){var n=e._fullLayout;if(!n)return[];var a,i=pt.listIds(e,t),o=new Array(i.length);for(a=0;an?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},gt={dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},vt=gt.dash,yt=m.extendFlat,mt={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:O.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks+margins"},titlefont:L({editType:"ticks+margins"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}}],editType:"plot+margins",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks+margins",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks+margins"},tick0:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks+margins"},ticktext:{valType:"data_array",editType:"ticks+margins"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks+margins"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:O.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks+margins"},automargin:{valType:"boolean",dflt:!1,editType:"ticks+margins"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:yt({},vt,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:L({editType:"ticks+margins"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks+margins"},tickprefix:{valType:"string",dflt:"",editType:"ticks+margins"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},ticksuffix:{valType:"string",dflt:"",editType:"ticks+margins"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks+margins"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks+margins"},tickformat:{valType:"string",dflt:"",editType:"ticks+margins"},tickformatstops:{_isLinkedToArray:"tickformatstop",dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks+margins"},{valType:"any",editType:"ticks+margins"}],editType:"ticks+margins"},value:{valType:"string",dflt:"",editType:"ticks+margins"},editType:"ticks+margins"},hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:O.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:O.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:O.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot+margins"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot+margins"},overlaying:{valType:"enumerated",values:["free",ht.idRegex.x.toString(),ht.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot+margins"},{valType:"number",min:0,max:1,editType:"plot+margins"}],dflt:[0,1],editType:"plot+margins"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot+margins"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks+margins"}}},xt={},bt=xt={};bt.defaults=O.defaults;var _t=bt.defaultLine=O.defaultLine;bt.lightLine=O.lightLine;var wt=bt.background=O.background;function kt(e){if(r(e)||"string"!=typeof e)return e;var t=e.trim();if("rgb"!==t.substr(0,3))return e;var n=t.match(/^rgba?\s*\(([^()]*)\)$/);if(!n)return e;var a=n[1].trim().split(/\s*[\s,]\s*/),i="a"===t.charAt(3)&&4===a.length;if(!i&&3!==a.length)return e;for(var o=0;o=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}bt.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},bt.rgb=function(e){return bt.tinyRGB(s(e))},bt.opacity=function(e){return e?s(e).getAlpha():0},bt.addOpacity=function(e,t){var r=s(e).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+t+")"},bt.combine=function(e,t){var r=s(e).toRgb();if(1===r.a)return s(e).toRgbString();var n=s(t||wt).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},i={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return s(i).toRgbString()},bt.contrast=function(e,t,r){var n=s(e);return 1!==n.getAlpha()&&(n=s(bt.combine(e,wt))),(n.isDark()?t?n.lighten(t):wt:r?n.darken(r):_t).toString()},bt.stroke=function(e,t){var r=s(t);e.style({stroke:bt.tinyRGB(r),"stroke-opacity":r.getAlpha()})},bt.fill=function(e,t){var r=s(t);e.style({fill:bt.tinyRGB(r),"fill-opacity":r.getAlpha()})},bt.clean=function(e){if(e&&"object"==typeof e){var t,r,n,a,i=Object.keys(e);for(t=0;t0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],a=t.range[1];return.5*(n+a-3*i*Math.abs(n-a))}return zt}function l(e,n,a){var i=St(e,a||t.calendar);if(i===zt){if(!r(e))return zt;i=St(new Date(+e))}return i}function s(e,r,n){return Ct(e,r,n||t.calendar)}function c(e){return t._categories[Math.round(e)]}function u(e){if(t._categoriesMap){var n=t._categoriesMap[e];if(void 0!==n)return n}if(r(e))return+e}function f(n){return r(n)?e.round(t._b+t._m*n,2):zt}function d(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:Ot,t.l2c="log"===t.type?Dt:Ot,t.l2p=f,t.p2l=d,t.c2p="log"===t.type?function(e,t){return f(o(e,t))}:f,t.p2c="log"===t.type?function(e){return Dt(d(e))}:d,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Lt,t.c2d=t.c2r=t.l2d=t.l2r=Ot,t.d2p=t.r2p=function(e){return t.l2p(Lt(e))},t.p2d=t.p2r=d,t.cleanPos=Ot):"log"===t.type?(t.d2r=t.d2l=function(e,t){return o(Lt(e),t)},t.r2d=t.r2c=function(e){return Dt(Lt(e))},t.d2c=t.r2l=Lt,t.c2d=t.l2r=Ot,t.c2r=o,t.l2d=Dt,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(e){return Dt(d(e))},t.r2p=function(e){return t.l2p(Lt(e))},t.p2r=d,t.cleanPos=Ot):"date"===t.type?(t.d2r=t.r2d=nt.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,r,n){return t.l2p(l(e,0,n))},t.p2d=t.p2r=function(e,t,r){return s(d(e),t,r)},t.cleanPos=function(e){return nt.cleanDate(e,zt,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return zt},t.r2d=t.c2d=t.l2d=c,t.d2r=t.d2l_noadd=u,t.r2c=function(e){var r=u(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=Ot,t.r2l=u,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(e){return c(d(e))},t.r2p=t.d2p,t.p2r=d,t.cleanPos=function(e){return"string"==typeof e&&""!==e?e:Ot(e)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var i,o,l=nt.nestedProperty(t,e).get();if(o=(o="date"===t.type?nt.dfltRange(t.calendar):"y"===a?ht.DFLTRANGEY:n.dfltRange||ht.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=nt.cleanDate(l[0],zt,t.calendar),l[1]=nt.cleanDate(l[1],zt,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!nt.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=nt.constrain(t.r2l(l[0]),nt.MIN_MS+1e3,nt.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!r(l[i])){if(!r(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Pt?l[i]=-Pt:l[i]>Pt&&(l[i]=Pt),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else nt.nestedProperty(t,e).set(o)},t.setScale=function(e){var r=n._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=pt.getFromId({_fullLayout:n},t.overlaying);t.domain=i.domain}var o=e&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===a?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,a,i,o,l=t.type,s="date"===l&&e[r+"calendar"];if(r in e){if(n=e[r],o=e._length||n.length,nt.isTypedArray(n)&&("linear"===l||"log"===l)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(a=new Array(o),i=0;i=t.r2l(t.range[0])&&n<=t.r2l(t.range[1])},t.clearCalc=function(){t._min=[],t._max=[],t._categories=(t._initialCategories||[]).slice(),t._categoriesMap={};for(var e=0;e0?Number(s):l;else if("string"!=typeof s)t.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=r(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(t.dtick=l)}var f="date"===a?nt.dateTick0(t.calendar):0,d=n("tick0",f);"date"===a?t.tick0=nt.cleanDate(d,f):r(d)&&"D1"!==s&&"D2"!==s?t.tick0=Number(d):t.tick0=f}else{void 0===n("tickvals")?t.tickmode="auto":n("ticktext")}},jt=function(t,r,n,a,i){var o=a.letter,l=a.font||{},s=n("visible",!a.cheateronly),c=r.type;"date"===c&&D.getComponentMethod("calendars","handleDefaults")(t,r,"calendar",a.calendar);Et(r,i);var u=n("autorange",!r.isValidRange(t.range));if(r._rangesliderAutorange=!1,u&&n("rangemode"),n("range"),r.cleanRange(),function(e,t,r){if("category"===t.type){var n,a=e.categoryarray,i=Array.isArray(a)&&a.length>0;i&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),i||"array"!==o||(t.categoryorder="trace")}}(t,r,n),r._initialCategories="category"===c?function(t,r,n,a){switch(r){case"array":return Array.isArray(n)?n.slice():[];case"category ascending":return At(t,e.ascending,a);case"category descending":return At(t,e.descending,a);case"trace":default:return[]}}(o,r.categoryorder,r.categoryarray,a.data):[],"category"===c||a.noHover||n("hoverformat"),!s)return r;var f=n("color"),d=f===t.color?f:l.color;return n("title",i._dfltTitle[o]),nt.coerceFont(n,"titlefont",{family:l.family,size:Math.round(1.2*l.size),color:d}),Ft(t,r,n,c),Nt(t,r,n,c,a),It(t,r,n,a),function(e,t,r,n){var a=(n=n||{}).dfltColor;function i(r,a){return nt.coerce2(e,t,n.attributes,r,a)}var o=i("linecolor",a),l=i("linewidth");r("showline",n.showLine||!!o||!!l)||(delete t.linecolor,delete t.linewidth);var s=i("gridcolor",Mt(a,n.bgColor,n.blend||Tt).toRgbString()),c=i("gridwidth");if(r("showgrid",n.showGrid||!!s||!!c)||(delete t.gridcolor,delete t.gridwidth),!n.noZeroLine){var u=i("zerolinecolor",a),f=i("zerolinewidth");r("zeroline",n.showGrid||!!u||!!f)||(delete t.zerolinecolor,delete t.zerolinewidth)}}(t,r,n,{dfltColor:f,bgColor:a.bgColor,showGrid:a.showGrid,attributes:mt}),(r.showline||r.ticks)&&n("mirror"),a.automargin&&n("automargin"),r},Bt=pt.id2name,qt=function(e,t,r,n,a){var i=a._axisConstraintGroups,o=t._id,l=o.charAt(0);if(!t.fixedrange&&(r("constrain"),nt.coerce(e,t,{constraintoward:{valType:"enumerated",values:"x"===l?["left","center","right"]:["bottom","middle","top"],dflt:"x"===l?"center":"middle"}},"constraintoward"),e.scaleanchor)){var s=function(e,t,r,n){var a,i,o,l,s=n[Bt(t)].type,c=[];for(i=0;ip[1]-.01&&(t.domain=o),nt.noneOrAll(e.domain,t.domain,o)}return n("layer"),t},Vt=n.BADNUM,Ut=function(e,t){return function(e,t){for(var n,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,t)?"date":function(e){for(var t,r=Math.max(1,(e.length-1)/1e3),n=0,a=0,i=0;i2*n}(e)?"category":function(e){if(!e)return!1;for(var t=0;t=0;a--,i++)t=e[a],n[i]=[1-t[0],t[1]];return n},Jt=function(e,t,r,n){var a,i;r?(a=nt.nestedProperty(e,r).get(),i=nt.nestedProperty(e._input,r).get()):(a=e,i=e._input);var o=n+"auto",l=n+"min",s=n+"max",u=a[o],f=a[l],d=a[s],h=a.colorscale;!1===u&&void 0!==f||(f=nt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=nt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[s]=d,i[l]=f,i[s]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?c.RdBu:f>=0?c.Reds:c.Blues,i.colorscale=h,a.reversescale&&(h=Qt(h)),a.colorscale=h)},$t=nt.extendFlat,Kt=nt.isPlainObject,er={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},tr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},rr=er.flags.slice().concat(["clearCalc","fullReplot"]),nr=tr.flags.slice().concat("layoutReplot"),ar={traces:er,layout:tr,traceFlags:function(){return ir(rr)},layoutFlags:function(){return ir(nr)},update:function(e,t){var r=t.editType;if(r&&"none"!==r)for(var n=r.split("+"),a=0;a","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},mr={},xr=vr.LINE_SPACING;function br(e,t){return e.node().getBoundingClientRect()[t]}var _r=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;mr.convertToTspans=function(r,n,a){var i=r.text(),o=!r.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(_r),l=e.select(r.node().parentNode);if(!l.empty()){var s=r.attr("class")?r.attr("class").split(" ")[0]:"text";return s+="-math",l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove(),r.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(n&&n._promises||[]).push(new Promise(function(t){r.style("display","none");var n=parseInt(r.node().style.fontSize,10),u={fontSize:n};!function(t,r,n){var a="math-output-"+nt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=t,o.replace(wr,"\\lt ").replace(kr,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var r=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())nt.log("There was an error in the tex syntax.",t),n();else{var a=i.select("svg").node().getBoundingClientRect();n(i.select(".MathJax_SVG"),r,a)}i.remove()})}(o[2],u,function(e,o,u){l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return c(),void t();var d=l.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});d.node().appendChild(f.node()),o&&o.node()&&f.node().insertBefore(o.node().cloneNode(!0),f.node().firstChild),f.attr({class:s,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=r.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=br(f,"width"),g=br(f,"height"),v=+r.attr("x")-p*{start:0,middle:.5,end:1}[r.attr("text-anchor")||"start"],y=-(n||br(r,"height"))/4;"y"===s[0]?(d.attr({transform:"rotate("+[-90,+r.attr("x"),+r.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+r.attr("x"),y:+r.attr("y")})):"l"===s[0]?f.attr({x:r.attr("x"),y:y-g/2}):"a"===s[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+r.attr("y")+y-g/2}),a&&a.call(r,d),t(d)})})):c(),r}function c(){l.empty()||(s=r.attr("class")+"-math",l.select("svg."+s).remove()),r.text("").style("white-space","pre"),function(r,n){n=(a=n,function(e,t){if(!e)return"";for(var r=0;r1)for(var o=1;o doesnt match end tag <"+e+">. Pretending it did match.",n),i=l[l.length-1].node}else nt.log("Ignoring unexpected end tag .",n)}Er.test(n)?c():(i=r,l=[{node:r}]);for(var h=n.split(zr),p=0;p|>|>)/g;var Mr={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"},Tr={sub:"0.3em",sup:"-0.6em"},Ar={sub:"-0.21em",sup:"0.42em"},Lr="\u200b",Cr=["http:","https:","mailto:","",void 0,":"],Sr=new RegExp("]*)?/?>","g"),Or=Object.keys(yr.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:yr.entityToUnicode[e]}}),Pr=/(\r\n?|\n)/g,zr=/(<[^<>]*>)/,Dr=/<(\/?)([^ >]*)(\s+(.*))?>/i,Er=//i,Nr=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Ir=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Rr=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Fr=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function jr(e,t){if(!e)return null;var r=e.match(t);return r&&(r[3]||r[4])}var Br=/(^|;)\s*color:/;function qr(e,t,r){var n,a,i,o=r.horizontalAlign,l=r.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-n.height}:"middle"===l?function(){return s.top+(s.height-n.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-n.width}:"center"===o?function(){return s.left+(s.width-n.width)/2}:function(){return s.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}mr.plainText=function(e){return(e||"").replace(Sr," ")},mr.lineCount=function(e){return e.selectAll("tspan.line").size()||1},mr.positionText=function(t,r,n){return t.each(function(){var t=e.select(this);function a(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var i=a("x",r),o=a("y",n);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},mr.makeEditable=function(t,r){var n=r.gd,a=r.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(n).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:r.fill||c.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||t.attr("data-unformatted")).call(qr(t,a,r)).on("blur",function(){n._editing=!1,t.text(this.textContent).style({opacity:1});var r,a=e.select(this).attr("class");(r=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(r).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;n._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(n._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(qr(t,a,r)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),r=document.createRange();r.selectNodeContents(t);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),t.focus()}return r.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var Hr=function(e){var t=e.marker,n=t.sizeref||1,a=t.sizemin||0,i="area"===t.sizemode?function(e){return Math.sqrt(e/n)}:function(e){return e/n};return function(e){var t=i(e/2);return r(t)&&t>0?Math.max(t,a):0}},Vr={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("markers")},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return nt.isPlainObject(e.marker)&&nt.isArrayOrTypedArray(e.marker.size)}},Ur={},Gr=vr.LINE_SPACING,Yr=h.DESELECTDIM,Xr=Ur={};Xr.font=function(e,t,r,n){nt.isPlainObject(t)&&(n=t.color,r=t.size,t=t.family),t&&e.style("font-family",t),r+1&&e.style("font-size",r+"px"),n&&e.call(xt.fill,n)},Xr.setPosition=function(e,t,r){e.attr("x",t).attr("y",r)},Xr.setSize=function(e,t,r){e.attr("width",t).attr("height",r)},Xr.setRect=function(e,t,r,n,a){e.call(Xr.setPosition,t,r).call(Xr.setSize,n,a)},Xr.translatePoint=function(e,t,n,a){var i=n.c2p(e.x),o=a.c2p(e.y);return!!(r(i)&&r(o)&&t.node())&&("text"===t.node().nodeName?t.attr("x",i).attr("y",o):t.attr("transform","translate("+i+","+o+")"),!0)},Xr.translatePoints=function(t,r,n){t.each(function(t){var a=e.select(this);Xr.translatePoint(t,a,r,n)})},Xr.hideOutsideRangePoint=function(e,t,r,n,a,i){t.attr("display",r.isPtWithinRange(e,a)&&n.isPtWithinRange(e,i)?null:"none")},Xr.hideOutsideRangePoints=function(t,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var a=r.xaxis,i=r.yaxis;t.each(function(r){var o=r[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(n).each(function(t){Xr.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Xr.crispRound=function(e,t,n){return t&&r(t)?e._context.staticPlot?t:t<1?1:Math.round(t):n||0},Xr.singleLineStyle=function(e,t,r,n,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";xt.stroke(t,n||i.color),Xr.dashLine(t,l,o)},Xr.lineGroupStyle=function(t,r,n,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";e.select(this).call(xt.stroke,n||i.color).call(Xr.dashLine,l,o)})},Xr.dashLine=function(e,t,r){r=+r||0,t=Xr.dashStyle(t,r),e.style({"stroke-dasharray":t,"stroke-width":r+"px"})},Xr.dashStyle=function(e,t){t=+t||1;var r=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=r+"px,"+r+"px":"dash"===e?e=3*r+"px,"+3*r+"px":"longdash"===e?e=5*r+"px,"+5*r+"px":"dashdot"===e?e=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===e&&(e=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),e},Xr.singleFillStyle=function(t){var r=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&t.call(xt.fill,r)},Xr.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(r){var n=e.select(this);try{n.call(xt.fill,r[0].trace.fillcolor)}catch(e){nt.error(e,t),n.remove()}})},Xr.symbolNames=[],Xr.symbolFuncs=[],Xr.symbolNeedLines={},Xr.symbolNoDot={},Xr.symbolNoFill={},Xr.symbolList=[],Object.keys(gr).forEach(function(e){var t=gr[e];Xr.symbolList=Xr.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Xr.symbolNames[t.n]=e,Xr.symbolFuncs[t.n]=t.f,t.needLine&&(Xr.symbolNeedLines[t.n]=!0),t.noDot?Xr.symbolNoDot[t.n]=!0:Xr.symbolList=Xr.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Xr.symbolNoFill[t.n]=!0)});var Zr=Xr.symbolNames.length,Wr="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Qr(e,t){var r=e%100;return Xr.symbolFuncs[r](t)+(e>=200?Wr:"")}Xr.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Xr.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Zr||e>=400?0:Math.floor(Math.max(e,0))};var Jr={x1:1,x2:0,y1:0,y2:0},$r={x1:0,x2:0,y1:1,y2:0};Xr.gradient=function(t,r,n,a,i,o){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([a+i+o],nt.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jr):"vertical"===a&&t.attr($r),t.attr("id",n);var r=s(i),l=s(o);t.append("stop").attr({offset:"0%","stop-color":xt.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":xt.tinyRGB(r),"stop-opacity":r.getAlpha()})}),t.style({fill:"url(#"+n+")","fill-opacity":null})},Xr.initGradients=function(e){var t=e._fullLayout._defs.selectAll(".gradients").data([0]);t.enter().append("g").classed("gradients",!0),t.selectAll("linearGradient,radialGradient").remove()},Xr.singlePointStyle=function(e,t,r,n,a,i){var o=r.marker;!function(e,t,r,n,a,i,o,l){if(D.traceIs(r,"symbols")){var s=Hr(r);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Vr.isBubble(r)?s(e.ms):(i.size||6)/2,e.mrc=t;var n=Xr.symbolNumber(e.mx||i.symbol)||0;return e.om=n%200>=100,Qr(n,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):nt.isArrayOrTypedArray(o.color)?xt.defaultLine:o.color,nt.isArrayOrTypedArray(i.color)&&(c=xt.defaultLine,d=!0),c="mc"in e?e.mcc=n(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(xt.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+r.uid;d&&(v+="-"+e.i),t.call(Xr.gradient,l,v,p,c,g)}else t.call(xt.fill,c);f&&t.call(xt.stroke,u)}}(e,t,r,n,a,o,o.line,i)},Xr.pointStyle=function(t,r,n){if(t.size()){var a=r.marker,i=Xr.tryColorscale(a,""),o=Xr.tryColorscale(a,"line");t.each(function(t){Xr.singlePointStyle(t,e.select(this),r,i,o,n)})}},Xr.makeSelectedPointStyleFns=function(e){var t={},r=e.selected||{},n=e.unselected||{},a=e.marker||{},i=r.marker||{},o=n.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,r=void 0!==t;if(r||u||f){if(!e.selected)return f?c:Yr*(r?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Xr.selectedPointStyle=function(t,r){if(t.size()&&r.selectedpoints){var n=Xr.makeSelectedPointStyleFns(r),a=r.marker||{};t.each(function(t){var r=e.select(this),a=n.opacityFn(t);void 0!==a&&r.style("opacity",a)}),n.colorFn&&t.each(function(t){var r=e.select(this),a=n.colorFn(t);a&&xt.fill(r,a)}),D.traceIs(r,"symbols")&&n.sizeFn&&t.each(function(t){var r=e.select(this),i=t.mx||a.symbol||0,o=n.sizeFn(t);r.attr("d",Qr(Xr.symbolNumber(i),o)),t.mrc2=o})}},Xr.tryColorscale=function(e,t){var r=t?nt.nestedProperty(e,t).get():e,n=r.colorscale,a=r.color;return n&&nt.isArrayOrTypedArray(a)?pr.makeColorScaleFunc(pr.extractScale(n,r.cmin,r.cmax)):nt.identity};var Kr={start:1,end:-1,middle:0,bottom:1,top:-1};function en(t,r,n,a){var i=e.select(t.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",l=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(mr.lineCount(t)-1)*Gr+1,u=Kr[l]*s,f=.75*n+Kr[o]*s+(Kr[o]-1)*c*n/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function tn(e,t){var n=e.ts||t.textfont.size;return r(n)&&n>0?n:0}Xr.textPointStyle=function(t,r,n){t.each(function(t){var a=e.select(this),i=nt.extractOption(t,r,"tx","text");if(i){var o=t.tp||r.textposition,l=tn(t,r);a.call(Xr.font,t.tf||r.textfont.family,l,t.tc||r.textfont.color).text(i).call(mr.convertToTspans,n).call(en,o,l,t.mrc)}else a.remove()})},Xr.selectedTextStyle=function(t,r){if(t.size()&&r.selectedpoints){var n=r.selected||{},a=r.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||r.textfont.color,s=t.tp||r.textposition,c=tn(t,r),u=(n.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=xt.addOpacity(l,Yr)),i&&xt.fill(o,i),en(o,s,c,t.mrc2||t.mrc)})}};var rn=.5;function nn(t,r,n,a){var i=t[0]-r[0],o=t[1]-r[1],l=n[0]-r[0],s=n[1]-r[1],c=Math.pow(i*i+o*o,rn/2),u=Math.pow(l*l+s*s,rn/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(r[0]+(h&&f/h),2),e.round(r[1]+(h&&d/h),2)],[e.round(r[0]-(p&&f/p),2),e.round(r[1]-(p&&d/p),2)]]}Xr.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var r,n="M"+e[0],a=[];for(r=1;r=1e4&&(Xr.savedBBoxes={},ln=0),n&&(Xr.savedBBoxes[n]=p),ln++,nt.extendFlat({},p)},Xr.setClipUrl=function(t,r){if(r){var n="#"+r,a=e.select("base");a.size()&&a.attr("href")&&(n=window.location.href.split("#")[0]+n),t.attr("clip-path","url("+n+")")}else t.attr("clip-path",null)},Xr.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,r){return[t,r].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Xr.setTranslate=function(e,t,r){var n=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[n]("transform")||"";return t=t||0,r=r||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+r+")").trim(),e[a]("transform",i),i},Xr.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,r){return[t,r].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Xr.setScale=function(e,t,r){var n=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[n]("transform")||"";return t=t||1,r=r||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+r+")").trim(),e[a]("transform",i),i},Xr.setPointGroupScale=function(e,t,r){var n,a,i;return t=t||1,r=r||1,a=1===t&&1===r?"":" scale("+t+","+r+")",i=/\s*sc.*/,e.each(function(){n=(this.getAttribute("transform")||"").replace(i,""),n=(n+=a).trim(),this.setAttribute("transform",n)}),a};var cn=/translate\([^)]*\)\s*$/;Xr.setTextPointsScale=function(t,r,n){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(cn);t=1===r&&1===n?[]:["translate("+o+","+l+")","scale("+r+","+n+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var un={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500},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"]}}},fn={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}},dn=m.extendFlat,hn=function(e,t,r){return{color:{valType:"color",arrayOk:!0,editType:t||"style"},colorscale:dn({},Wt.colorscale,{}),cauto:dn({},Wt.zauto,{impliedEdits:{cmin:void 0,cmax:void 0}}),cmax:dn({},Wt.zmax,{editType:t||Wt.zmax.editType,impliedEdits:{cauto:!1}}),cmin:dn({},Wt.zmin,{editType:t||Wt.zmin.editType,impliedEdits:{cauto:!1}}),autocolorscale:dn({},Wt.autocolorscale,{dflt:!1===r?r:Wt.autocolorscale.dflt}),reversescale:dn({},Wt.reversescale,{})}},pn={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20},gn=gt.dash,vn=m.extendFlat,yn={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:vn({},gn,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:vn({symbol:{valType:"enumerated",values:Ur.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},showscale:{valType:"boolean",dflt:!1,editType:"calc"},colorbar:cr,line:vn({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},hn()),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},hn()),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:L({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}},mn=yn.marker,xn={r:yn.r,t:yn.t,marker:{color:mn.color,size:mn.size,symbol:mn.symbol,opacity:mn.opacity,editType:"calc"}},bn=m.extendFlat,_n=ar.overrideAll,wn=bn({},mt.domain,{});function kn(e,t){return bn({},t,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}var Mn=_n({radialaxis:kn(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:wn,orientation:{valType:"number"}}),angularaxis:kn(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:wn}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested"),Tn={},An=nt.extendFlat,Ln=nt.extendDeepAll,Cn="_isSubplotObj",Sn="_isLinkedToArray",On=[Cn,Sn,"_arrayAttrRegexps","_deprecated"];function Pn(e,t,r){if(!e)return!1;if(e._isLinkedToArray)if(zn(t[r]))r++;else if(r=i.length)return!1;if(2===e.dimensions){if(r++,t.length===r)return e;var o=t[r];if(!zn(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function zn(e){return e===Math.round(e)&&e>=0}function Dn(e){return function(e){Tn.crawl(e,function(e,t,r){Tn.isValObject(e)?"data_array"===e.valType?(e.role="data",r[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(r[t+"src"]={valType:"string",editType:"none"}):nt.isPlainObject(e)&&(e.role="object")})}(e),function(e){Tn.crawl(e,function(e,t,r){if(!e)return;var n=e[Sn];if(!n)return;delete e[Sn],r[t]={items:{}},r[t].items[n]=e,r[t].role="object"})}(e),e}function En(e,t,r){var n=nt.nestedProperty(e,r),a=Ln({},t.layoutAttributes);a[Cn]=!0,n.set(a)}function Nn(e,t,r){var n=nt.nestedProperty(e,r);n.set(Ln(n.get()||{},t))}Tn.IS_SUBPLOT_OBJ=Cn,Tn.IS_LINKED_TO_ARRAY=Sn,Tn.DEPRECATED="_deprecated",Tn.UNDERSCORE_ATTRS=On,Tn.get=function(){var e={};D.allTypes.concat("area").forEach(function(t){e[t]=function(e){var t,r;"area"===e?(t={attributes:xn},r={}):(t=D.modules[e]._module,r=t.basePlotModule);var n={type:null};Ln(n,S),Ln(n,t.attributes),r.attributes&&Ln(n,r.attributes);n.type=e;var a={meta:t.meta||{},attributes:Dn(n)};if(t.layoutAttributes){var i={};Ln(i,t.layoutAttributes),a.layoutAttributes=Dn(i)}return a}(t)});var t,r={};return Object.keys(D.transformsRegistry).forEach(function(e){r[e]=function(e){var t=D.transformsRegistry[e],r=Ln({},t.attributes);return Object.keys(D.componentsRegistry).forEach(function(t){var n=D.componentsRegistry[t];n.schema&&n.schema.transforms&&n.schema.transforms[e]&&Object.keys(n.schema.transforms[e]).forEach(function(t){Nn(r,n.schema.transforms[e][t],t)})}),{attributes:Dn(r)}}(e)}),{defs:{valObjects:nt.valObjectMeta,metaKeys:On.concat(["description","role","editType","impliedEdits"]),editType:{traces:ar.traces,layout:ar.layout},impliedEdits:{}},traces:e,layout:function(){var e,t,r={};for(e in Ln(r,z),D.subplotsRegistry)if((t=D.subplotsRegistry[e]).layoutAttributes)if("cartesian"===t.name)En(r,t,"xaxis"),En(r,t,"yaxis");else{var n="subplot"===t.attr?t.name:t.attr;En(r,t,n)}for(e in r=function(e){return An(e,{radialaxis:Mn.radialaxis,angularaxis:Mn.angularaxis}),An(e,Mn.layout),e}(r),D.componentsRegistry){var a=(t=D.componentsRegistry[e]).schema;if(a&&(a.subplots||a.layout)){var i=a.subplots;if(i&&i.xaxis&&!i.yaxis)for(var o in i.xaxis)delete r.yaxis[o]}else t.layoutAttributes&&Nn(r,t.layoutAttributes,t.name)}return{layoutAttributes:Dn(r)}}(),transforms:r,frames:(t={frames:nt.extendDeepAll({},fn)},Dn(t),t.frames),animation:Dn(un)}},Tn.crawl=function(e,t,r,n){var a=r||0;n=n||"",Object.keys(e).forEach(function(r){var i=e[r];if(-1===On.indexOf(r)){var o=(n?n+".":"")+r;t(i,r,e,a,o),Tn.isValObject(i)||nt.isPlainObject(i)&&"impliedEdits"!==r&&Tn.crawl(i,t,a+1,o)}})},Tn.isValObject=function(e){return e&&void 0!==e.valType},Tn.findArrayAttributes=function(e){var t=[],r=[];function n(n,a,i,o){if(r=r.slice(0,o).concat([a]),n&&("data_array"===n.valType||!0===n.arrayOk)&&!("colorbar"===r[o-1]&&("ticktext"===a||"tickvals"===a))){var l=function(e){return e.join(".")}(r),s=nt.nestedProperty(e,l).get();nt.isArrayOrTypedArray(s)&&t.push(l)}}if(Tn.crawl(S,n),e._module&&e._module.attributes&&Tn.crawl(e._module.attributes,n),e.transforms)for(var a=e.transforms,i=0;i=e.transforms.length)return!1;n=(r=(D.transformsRegistry[e.transforms[o].type]||{}).attributes)&&r[t[2]],i=3}else if("area"===e.type)n=xn[a];else{var l=e._module;if(l||(l=(D.modules[e.type||S.type.dflt]||{})._module),!l)return!1;if(!(n=(r=l.attributes)&&r[a])){var s=l.basePlotModule;s&&s.attributes&&(n=s.attributes[a])}n||(n=S[a])}return Pn(n,t,i)},Tn.getLayoutValObject=function(e,t){return Pn(function(e,t){var r,n,a,i,o=e._basePlotModules;if(o){var l;for(r=0;r0?".":"")+a;nt.isPlainObject(i)?Bn(i,t,o,n+1):t(o,a,i)}})}In.manageCommandObserver=function(e,t,r,n){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=In.hasSimpleAPICommandBindings(e,r,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Rn(e,o,a.cache),a.check=function(){if(i){var t=Rn(e,o,a.cache);return t.changed&&n&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(n({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=r.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=r._paper.attr("width")-7),n.attr(i);var o=n.select(".js-link-to-tool"),l=n.select(".js-link-spacer"),s=n.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var r=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)r.on("click",function(){Un.sendDataToCloud(e)});else{var n=window.location.pathname.split("/"),a=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},Un.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=Un.graphJson(t,!1,"keepdata"),a.node().submit(),n.remove(),t.emit("plotly_afterexport"),!1};var Xn,Zn=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Wn=["year","month","dayMonth","dayMonthYear"];function Qn(e,t){var r,n,a=e.trace,i=a._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},Un.cleanPlot=function(e,t,r,n){var a,i,o=n._basePlotModules||[];for(a=0;a0){var c=function(e){var t,r={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(r.left+=e[t].left||0,r.right+=e[t].right||0,r.bottom+=e[t].bottom||0,r.top+=e[t].top||0);return r}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||n.width,i=parseFloat(p.height)||n.height}var g=Un.layoutAttributes.width.min,v=Un.layoutAttributes.height.min;a1,m=!t.height&&Math.abs(n.height-i)>1;(m||y)&&(y&&(n.width=a),m&&(n.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),Un.sanitizeMargins(n)},Un.supplyLayoutModuleDefaults=function(e,t,r,n){var a,i,o,l=D.componentsRegistry,s=t._basePlotModules,c=D.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(D.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(nt.subplotSort);for(i=0;i.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[t]={l:{val:r.x,size:r.l+a},r:{val:r.x,size:r.r+a},b:{val:r.y,size:r.b+a},t:{val:r.y,size:r.t+a}}}else delete n._pushmargin[t];n._replotting||Un.doAutoMargin(e)}},Un.doAutoMargin=function(e){var t=e._fullLayout;t._size||(t._size={}),t._pushmargin||(t._pushmargin={});var n=t._size,a=JSON.stringify(n),i=Math.max(t.margin.l||0,0),o=Math.max(t.margin.r||0,0),l=Math.max(t.margin.t||0,0),s=Math.max(t.margin.b||0,0),c=t._pushmargin;if(!1!==t.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(r(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-t.width)*h)/(m-h),_=(x*(1-h)+(p-t.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(r(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-t.height)*g)/(w-g),T=(k*(1-g)+(v-t.height)*(1-w))/(w-g);M>=0&&T>=0&&M+T>s+l&&(s=M,l=T)}}}}if(n.l=Math.round(i),n.r=Math.round(o),n.t=Math.round(l),n.b=Math.round(s),n.p=Math.round(t.margin.pad),n.w=Math.round(t.width)-n.l-n.r,n.h=Math.round(t.height)-n.t-n.b,!t._replotting&&"{}"!==a&&a!==JSON.stringify(t._size))return D.call("plot",e)},Un.graphJson=function(e,t,r,n,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&Un.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(nt.isPlainObject(e)){var t,n,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===r){if("src"===t.substr(t.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=e[t+"src"])&&n.indexOf(":")>0&&!nt.isPlainObject(e.stream))continue}else if("keepall"!==r&&"string"==typeof(n=e[t+"src"])&&n.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):nt.isJSDate(e)?nt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var r=s(e);return t&&delete r.fit,r})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===n?c:JSON.stringify(c)},Un.modifyFrames=function(e,t){var r,n,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(r=0;r0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return D.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var n,o,l=0,s=0;function c(){return l++,function(){var r;f||++s!==l||(r=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return D.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(r)))}}var d=e._fullLayout._basePlotModules,h=!1;if(r)for(o=0;o=0;i--)if(g[i].enabled){r._indexToPoints=g[i]._indexToPoints;break}n&&n.calc&&(p=n.calc(e,r))}Array.isArray(p)&&p[0]||(p=[{x:Vn,y:Vn}]),p[0].t||(p[0].t={}),p[0].trace=r,c[a]=p}D.getComponentMethod("fx","calc")(e)},Un.rehover=function(e){e._fullLayout._rehover&&e._fullLayout._rehover()},Un.generalUpdatePerTraceModule=function(e,t,r,n){var a,i=t.traceHash,o={};for(a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];n.attr("transform","translate("+p+")")}}}T.call(A),k&&(w?T.on(".opacity",null):(b=0,_=!0,T.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(mr.makeEditable,{gd:t}).on("edit",function(e){void 0!==c?D.call("restyle",t,l,e,c):D.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(A)}).on("input",function(e){this.text(e||" ").call(mr.positionText,f.x,f.y)}));return T.classed("js-placeholder",_),p}},ta=/ [XY][0-9]* /;var ra=n.FP_SAFE,na=la,aa=sa,ia=function(e){e._length||e.setScale();var t,r=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&r&&(e.range=la(e),e._r=e.range.slice(),e._rl=nt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var n=e._anchorAxis.rangeslider[e._name];n&&"auto"===n.rangemode&&(n.range=r?la(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=nt.extendFlat({},n)}},oa=function(e,t,n){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!t)return;e._min||(e._min=[]);e._max||(e._max=[]);n||(n={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=t.length,y=n.padded||!1,m=n.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),k=_((e._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),M=_(n.vpadplus||n.vpad),T=_(n.vpadminus||n.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-ra&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var A=m&&0===a;v.push({val:a,pad:A?0:b,extrapad:!A&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)A(a)};function la(e){var t,r,n,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=sa(e);for(t=1;t0&&l>0&&s/l>d&&(i=n,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),nt.simpleMap(c,e.l2r||Number)}function sa(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function ca(e){return r(e)&&Math.abs(e)=t}var da={},ha=n.ONEAVGYEAR,pa=n.ONEAVGMONTH,ga=n.ONEDAY,va=n.ONEHOUR,ya=n.ONEMIN,ma=n.ONESEC,xa=n.MINUS_SIGN,ba=n.BADNUM,_a=vr.MID_SHIFT,wa=vr.LINE_SPACING,ka=da={};ka.setConvert=Et,ka.id2name=pt.id2name,ka.name2id=pt.name2id,ka.cleanId=pt.cleanId,ka.list=pt.list,ka.listIds=pt.listIds,ka.getFromId=pt.getFromId,ka.getFromTrace=pt.getFromTrace,ka.expand=oa,ka.getAutoRange=na,ka.coerceRef=function(e,t,r,n,a,i){var o=n.charAt(n.length-1),l=r._fullLayout._subplots[o+"axis"],s=n+"ref",c={};return a||(a=l[0]||i),i||(i=a),c[s]={valType:"enumerated",values:l.concat(i?[i]:[]),dflt:a},nt.coerce(e,t,c,s)},ka.coercePosition=function(e,t,r,n,a,i){var o,l;if("paper"===n||"pixel"===n)o=nt.ensureNumber,l=r(a,i);else{var s=ka.getFromId(t,n);l=r(a,i=s.fraction2r(i)),o=s.cleanPos}e[a]=o(l)},ka.cleanPosition=function(e,t,r){return("paper"===r||"pixel"===r?nt.ensureNumber:ka.getFromId(t,r).cleanPos)(e)};var Ma=ka.getDataConversions=function(e,t,r,n){var a,i="x"===r||"y"===r||"z"===r?r:n;if(Array.isArray(i)){if(a={type:Ut(n),_categories:[]},ka.setConvert(a),"category"===a.type)for(var o=0;o2e-6||((r-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},ka.saveRangeInitial=function(e,t){for(var r=ka.list(e,"",!0),n=!1,a=0;a.3*d||u(a)||u(i))){var h=n.dtick/2;e+=e+h.8){var o=Number(r.substr(1));i.exactYears>.8&&o%12==0?e=ka.tickIncrement(e,"M6","reverse")+1.5*ga:i.exactMonths>.8?e=ka.tickIncrement(e,"M1","reverse")+15.5*ga:e-=ga/2;var l=ka.tickIncrement(e,r);if(l<=n)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=ka.tickIncrement(h,l.dtick,!1,i),0;return{start:t.c2r(p,0,i),end:t.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},ka.prepTicks=function(e){var t=nt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var r,n=e.nticks;n||("category"===e.type?(r=e.tickfont?1.2*(e.tickfont.size||12):15,n=e._length/r):(r="y"===e._id.charAt(0)?40:80,n=nt.constrain(e._length/r,4,9)+1),"radialaxis"===e._name&&(n*=2)),"array"===e.tickmode&&(n*=100),ka.autoTicks(e,Math.abs(t[1]-t[0])/n),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),Na(e)},ka.calcTicks=function(e){ka.prepTicks(e);var t=nt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,r,n=e.tickvals,a=e.ticktext,i=new Array(n.length),o=nt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(r=0;rc&&t=n:s<=n)&&!(i.length>l||s===o);s=ka.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+t.substr(1)%12==0?"y":"m";else if(t>=ga&&i<=10||t>=15*ga)e._tickround="d";else if(t>=ya&&i<=16||t>=va)e._tickround="M";else if(t>=ma&&i<=19||t>=ya)e._tickround="S";else{var o=e.l2r(n+t).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(r(t)||"L"===t.charAt(0)){var l=e.range.map(e.r2d||Number);r(t)||(t=Number(t.substr(1))),e._tickround=2-Math.floor(Math.log(t)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(Fa(e.exponentformat)&&!ja(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function Ia(e,t,r){var n=e.tickfont||{};return{x:t,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}ka.autoTicks=function(e,t){var n;function a(e){return Math.pow(e,Math.floor(Math.log(t)/Math.LN10))}if("date"===e.type){e.tick0=nt.dateTick0(e.calendar);var i=2*t;i>ha?(t/=ha,n=a(10),e.dtick="M"+12*Ea(t,n,La)):i>pa?(t/=pa,e.dtick="M"+Ea(t,1,Ca)):i>ga?(e.dtick=Ea(t,ga,Oa),e.tick0=nt.dateTick0(e.calendar,!0)):i>va?e.dtick=Ea(t,va,Ca):i>ya?e.dtick=Ea(t,ya,Sa):i>ma?e.dtick=Ea(t,ma,Sa):(n=a(10),e.dtick=Ea(t,n,La))}else if("log"===e.type){e.tick0=0;var o=nt.simpleMap(e.range,e.r2l);if(t>.7)e.dtick=Math.ceil(t);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/t);t=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,n=a(10),e.dtick="L"+Ea(t,n,La)}else e.dtick=t>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(t,1))):"angular"===e._id?(e.tick0=0,n=1,e.dtick=Ea(t,n,Da)):(e.tick0=0,n=a(10),e.dtick=Ea(t,n,La));if(0===e.dtick&&(e.dtick=1),!r(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},ka.tickIncrement=function(t,n,a,i){var o=a?-1:1;if(r(n))return t+o*n;var l=n.charAt(0),s=o*Number(n.substr(1));if("M"===l)return nt.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var c="D2"===n?za:Pa,u=t+.01*o,f=nt.roundUp(nt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(n)},ka.tickFirst=function(t){var n=t.r2l||Number,a=nt.simpleMap(t.range,n),i=a[1]"+l,e._prevDateHead=l));t.text=s}(e,o,n,s):"log"===e.type?function(e,t,n,a,i){var o=e.dtick,l=t.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))t.text=Ba(Math.pow(10,l),e,i,a);else if(r(o)||"D"===o.charAt(0)&&nt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||Fa(e.exponentformat)&&ja(c)?(t.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+xa+-c+"",t.fontSize*=1.25):(t.text=Ba(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(t.dy-=t.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);t.text=String(Math.round(Math.pow(10,nt.mod(l,1)))),t.fontSize*=.75}if("D1"===e.dtick){var u=String(t.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?t.dx-=t.fontSize/4:(t.dy+=t.fontSize/2,t.dx+=(e.range[1]>e.range[0]?1:-1)*t.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var r=e._categories[Math.round(t.x)];void 0===r&&(r="");t.text=String(r)}(e,o):"angular"===e._id?function(e,t,r,n,a){if("radians"!==e.thetaunit||r)t.text=Ba(t.x,e,a,n);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var r=function(e){var r=1;for(;!t(Math.round(e*r)/r,e);)r*=10;return r}(e),n=e*r,a=Math.abs(function e(r,n){return t(n,0)?r:e(n,r%n)}(n,r));return[Math.round(n/a),Math.round(r/a)]}(i);if(o[1]>=100)t.text=Ba(nt.deg2rad(t.x),e,a,n);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=xa+t.text)}}}}(e,o,n,s,a):function(e,t,r,n,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=Ba(t.x,e,a,n)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},ka.hoverLabelText=function(e,t,r){if(r!==ba&&r!==t)return ka.hoverLabelText(e,t)+" - "+ka.hoverLabelText(e,r);var n="log"===e.type&&t<=0,a=ka.tickText(e,e.c2l(n?-t:t),"hover").text;return n?0===t?"0":xa+a:a};var Ra=["f","p","n","\u03bc","m","","k","M","G","T"];function Fa(e){return"SI"===e||"B"===e}function ja(e){return e>14||e<-15}function Ba(e,t,n,a){var i=e<0,o=t._tickround,l=n||t.exponentformat||"B",s=t._tickexponent,c=ka.getTickFormat(t),u=t.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===t.showexponent?t.dtick:r(e)&&Math.abs(e)||1,range:"none"===t.showexponent?t.range.map(t.r2d):[0,e||1]};Na(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,t.hoverformat&&(c=t.hoverformat)}if(c)return t._numFormat(c)(e).replace(/-/g,xa);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":Fa(l)&&(e+=Ra[s/3+5]));return i?xa+e:e}function qa(e,t){for(var r=0;r=0,i=c(e,t[1])<=0;return(r||a)&&(n||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(n))){r=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(n=1;n rect").call(Ur.setTranslate,0,0).call(Ur.setScale,1,1),e.plot.call(Ur.setTranslate,t._offset,r._offset).call(Ur.setScale,1,1);var n=e.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(Ur.setPointGroupScale,1,1),n.selectAll(".textpoint").call(Ur.setTextPointsScale,1,1),n.call(Ur.hideOutsideRangePoints,e)}function g(e,r){var n,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(n=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-r)+r*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],c[2]=e.xaxis._length*(1-r+r*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(n=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-r)+r*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],c[3]=e.yaxis._length*(1-r+r*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,r){var n,a=[];for(a=[e._id,r._id],n=0;n rect").call(Ur.setTranslate,_,w).call(Ur.setScale,1/x,1/b),e.plot.call(Ur.setTranslate,T,A).call(Ur.setScale,x,b).selectAll(".points").selectAll(".point").call(Ur.setPointGroupScale,1/x,1/b),e.plot.selectAll(".points").selectAll(".textpoint").call(Ur.setTextPointsScale,1/x,1/b)}a&&(l=a());var v=e.ease(n.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(u),u=null,function(){for(var e={},r=0;rn.duration?(function(){for(var e={},r=0;r0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},yi.prototype.on=yi.prototype.addListener,yi.prototype.once=function(e,t){if(!xi(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},yi.prototype.removeListener=function(e,t){var r,n,a,i;if(!xi(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(r=this._events[e]).length,n=-1,r===t||xi(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(bi(r)){for(i=a;i-- >0;)if(r[i]===t||r[i].listener&&r[i].listener===t){n=i;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},yi.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(xi(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},yi.prototype.listeners=function(e){return this._events&&this._events[e]?xi(this._events[e])?[this._events[e]]:this._events[e].slice():[]},yi.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(xi(t))return 1;if(t)return t.length}return 0},yi.listenerCount=function(e,t){return e.listenerCount(t)};var wi,ki=mi.EventEmitter,Mi={init:function(e){if(e._ev instanceof ki)return e;var t=new ki,r=new ki;return e._ev=t,e._internalEv=r,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=r.on.bind(r),e._internalOnce=r.once.bind(r),e._removeInternalListener=r.removeListener.bind(r),e._removeAllInternalListeners=r.removeAllListeners.bind(r),e.emit=function(n,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(n,a),t.emit(n,a),r.emit(n,a)},e},triggerHandler:function(e,t,r){var n,a;"undefined"!=typeof jQuery&&(n=jQuery(e).triggerHandler(t,r));var i=e._ev;if(!i)return n;var o=i._events[t];if(!o)return n;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Li.getCursor=function(e,t,r,n){return e="left"===r?0:"center"===r?1:"right"===r?2:nt.constrain(Math.floor(3*e),0,2),t="bottom"===n?0:"middle"===n?1:"top"===n?2:nt.constrain(Math.floor(3*t),0,2),gi[t][e]},Li.unhover=wi.wrapped,Li.unhoverRaw=wi.raw,Li.init=function(e){var t,r,n,a,i,o,l,s,c=e.gd,u=1,f=h.DBLCLICKDELAY,d=e.element;c._mouseDownTime||(c._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,di?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=e.clampFn||function(e,t,r){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var r;try{r=new MouseEvent("click",t)}catch(e){var n=Si(t);(r=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,n[0],n[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(r)}!function(e){e._dragging=!1,e._replotPending&&D.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Li.coverSlip=Ci;function Oi(e,t,r,n){n=n||nt.identity,Array.isArray(e)&&(t[0][r]=n(e))}var Pi={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},flat:function(e,t){for(var r=new Array(e.length),n=0;n=0&&r.index-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.extraText&&(s+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),""===s&&(""===l&&r.remove(),s=l);var g=r.select("text.nums").call(Ur.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(mr.positionText,0,0).call(mr.convertToTspans,n),y=r.select("text.name"),m=0;l&&l!==s?(y.call(Ur.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(mr.positionText,0,0).call(mr.convertToTspans,n),m=y.node().getBoundingClientRect().width+2*Gi):(y.remove(),r.select("rect").remove()),r.select("path").style({fill:d,stroke:h});var k,M,T=g.node().getBoundingClientRect(),A=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),O=T.width+Ui+Gi+m;t.ty0=x-T.top,t.bx=T.width+2*Gi,t.by=T.height+2*Gi,t.anchor="start",t.txwidth=T.width,t.tx2width=m,t.offset=0,i?(t.pos=A,k=L+S/2+O<=_,M=L-S/2-O>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=A+C/2+O<=b,M=A-C/2-O>=0,"left"!==t.idealAlign&&k||!M?k?(A+=C/2,t.anchor="start"):t.anchor="middle":(A-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),r.attr("transform","translate("+A+","+L+")"+(i?"rotate("+ji+")":""))}),C}function Xi(t,r){t.each(function(t){var n=e.select(this);if(t.del)n.remove();else{var a="end"===t.anchor?-1:1,i=n.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(Ui+Gi),s=l+o*(t.txwidth+Gi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+Gi),r&&(u*=-Vi,c=t.offset*Hi),n.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*Ui+c)+","+(Ui+u)+"v"+(t.by/2-Ui)+"h"+a*t.bx+"v-"+t.by+"H"+(a*Ui+c)+"V"+(u-Ui)+"Z"),i.call(mr.positionText,l+c,u+t.ty0-t.by/2+Gi),t.tx2width&&(n.select("text.name").call(mr.positionText,s+o*Gi+c,u+t.ty0-t.by/2+Gi),n.select("rect").call(Ur.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function Zi(e,t){var r=e.index,n=e.trace||{},a=e.cd[0],i=e.cd[r]||{},o=Array.isArray(r)?function(e,t){return nt.castOption(a,r,e)||nt.extractOption({},n,"",t)}:function(e,t){return nt.extractOption(i,n,e,t)};function l(t,r,n){var a=o(r,n);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=nt.constrain(e.x0,0,e.xa._length),e.x1=nt.constrain(e.x1,0,e.xa._length),e.y0=nt.constrain(e.y0,0,e.ya._length),e.y1=nt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:da.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:da.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=da.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+da.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=da.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+da.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function Wi(e,t){var r,n,a=t.container,i=t.fullLayout,o=t.event,l=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||l){var u=xt.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var f,d,h=e.hLinePoint;r=h&&h.xa,"cursor"===(n=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=r._offset+h.x,d=n._offset+h.y);var p,g,v=s.readability(h.color,u)<1.5?xt.contrast(u):h.color,y=n.spikemode,m=n.spikethickness,x=n.spikecolor||v,b=n._boundingBox,_=(b.left+b.right)/2V.width||q<0||q>V.height)return Ai.unhoverRaw(t,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(_="xval"in n?Pi.flat(o,n.xval):Pi.p2c(h,B),w="yval"in n?Pi.flat(o,n.yval):Pi.p2c(p,q),!r(_[0])||!r(w[0]))return nt.warn("Fx.hover failed",n,t),Ai.unhoverRaw(t,n)}var U=1/0;for(M=0;ME&&(R.splice(0,E),U=R[0].distance),u&&0!==I&&0===R.length){z.distance=I,z.index=!1;var W=A._module.hoverPoints(z,O,P,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=I})),W&&W.length){var Q,J=W.filter(function(e){return e.xa.showspikes});if(J.length){var $=J[0];r($.x0)&&r($.y0)&&(Q=re($),(!j.vLinePoint||j.vLinePoint.spikeDistance>Q.spikeDistance)&&(j.vLinePoint=Q))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];r(ee.x0)&&r(ee.y0)&&(Q=re(ee),(!j.hLinePoint||j.hLinePoint.spikeDistance>Q.spikeDistance)&&(j.hLinePoint=Q))}}}}function te(e,t){for(var r,n=null,a=1/0,i=0;i1,ge=xt.combine(l.plot_bgcolor||xt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=Yi(R,ve,t);if(function(e,t,r){var n,a,i,o,l,s,c,u=0,f=e.map(function(e,n){var a=e[t];return[{i:n,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?qi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?r.width:r.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],r=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=r.pos+r.dp+r.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;n=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;n=!1}if(n){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!n&&u<=e.length;){for(u++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;n=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(R,pe?"xa":"ya",l),Xi(ye,pe),n.target&&n.target.tagName){var me=D.getComponentMethod("annotations","hasClickToShow")(t,de);Ri(e.select(n.target),me?"pointer":"")}if(!n.target||i||!function(e,t,r){if(!r||r.length!==e._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var a=r[n],i=e._hoverdata[n];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,fe))return;fe&&t.emit("plotly_unhover",{event:n,points:fe});t.emit("plotly_hover",{event:n,points:t._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(t,n,a,i)})},Fi.loneHover=function(t,r){var n={color:t.color||xt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(r.container),i=r.outerContainer?e.select(r.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||xt.background,container:a,outerContainer:i},l=Yi([n],o,r.gd);return Xi(l,o.rotateLabels),l.node()};var Ji=Fi.hover,$i=function(e,t,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),nt.coerceFont(r,"hoverlabel.font",n.font)},Ki=L({editType:"none"});Ki.family.dflt=vi.HOVERFONT,Ki.size.dflt=vi.HOVERFONTSIZE;var eo={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Ki,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var to={moduleType:"component",name:"fx",constants:vi,schema:{layout:eo},attributes:C,layoutAttributes:eo,supplyLayoutGlobalDefaults:function(e,t){$i(0,0,function(r,n){return nt.coerce(e,t,eo,r,n)})},supplyDefaults:function(e,t,r,n){$i(0,0,function(r,n){return nt.coerce(e,t,C,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(e,t,r){function n(r,n){return nt.coerce(e,t,eo,r,n)}var a;n("dragmode"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,r=0;r.01?T:function(e,t){return Math.abs(e-t)>=2?T(e):e>t?Math.ceil(e):Math.floor(e)};p=k(p,h=k(h,p)),v=k(v,g=k(g,v))}var M=e.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+h+","+g+"V"+v+"H"+p+"V"+g+"Z").call(Ur.setClipUrl,n.layerClipId),function(e,t,r,n,a,i,o,l){var s;function c(t,r,n){var a=t.append("text").text(r).attr({class:"bartext bartext-"+s,transform:"","text-anchor":"middle","data-notex":1}).call(Ur.font,n).call(mr.convertToTspans,e);return a}var u=r[0].trace,f=u.orientation,d=function(e,t){var r=yo(e.text,t);return mo(lo,r)}(u,n);if(!d)return;if("none"===(s=function(e,t){var r=yo(e.textposition,t);return function(e,t,r){return e.coerceNumber&&(t=+t),-1!==e.values.indexOf(t)?t:void 0!==r?r:e.dflt}(so,r)}(u,n)))return;var h,p,g,v,y,m,x=function(e,t,r){return vo(co,e.textfont,t,r)}(u,n,e._fullLayout.font),b=function(e,t,r){return vo(uo,e.insidetextfont,t,r)}(u,n,x),_=function(e,t,r){return vo(fo,e.outsidetextfont,t,r)}(u,n,x),w=e._fullLayout.barmode,k="stack"===w||"relative"===w,M=r[n],T=!k||M._outmost,A=Math.abs(i-a)-2*ho,L=Math.abs(l-o)-2*ho;"outside"===s&&(T||(s="inside"));if("auto"===s)if(T){s="inside",h=c(t,d,b),p=Ur.bBox(h.node()),g=p.width,v=p.height;var C=g>0&&v>0,S=g<=A&&v<=L,O=g<=L&&v<=A,P="h"===f?A>=g*(L/v):L>=v*(A/g);C&&(S||O||P)?s="inside":(s="outside",h.remove(),h=null)}else s="inside";if(!h&&(h=c(t,d,"outside"===s?_:b),p=Ur.bBox(h.node()),g=p.width,v=p.height,g<=0||v<=0))return void h.remove();"outside"===s?(m="both"===u.constraintext||"outside"===u.constraintext,y=function(e,t,r,n,a,i,o){var l,s="h"===i?Math.abs(n-r):Math.abs(t-e);s>2*ho&&(l=ho);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,h,p=(a.left+a.right)/2,g=(a.top+a.bottom)/2;u=c*a.width,f=c*a.height,"h"===i?tr?(d=(e+t)/2,h=n+l+f/2):(d=(e+t)/2,h=n-l-f/2);return go(p,g,d,h,c,!1)}(a,i,o,l,p,f,m)):(m="both"===u.constraintext||"inside"===u.constraintext,y=function(e,t,r,n,a,i,o){var l,s,c,u,f,d,h,p=a.width,g=a.height,v=(a.left+a.right)/2,y=(a.top+a.bottom)/2,m=Math.abs(t-e),x=Math.abs(n-r);m>2*ho&&x>2*ho?(m-=2*(f=ho),x-=2*f):f=0;p<=m&&g<=x?(d=!1,h=1):p<=x&&g<=m?(d=!0,h=1):pr?(c=(e+t)/2,u=n-f-s/2):(c=(e+t)/2,u=n+f+s/2);return go(v,y,c,u,h,d)}(a,i,o,l,p,f,m));h.attr("transform",y)}(t,M,a,c,h,p,g,v),n.layerClipId&&Ur.hideOutsideRangePoint(a[c],M.select("text"),i,o,u.xcalendar,u.ycalendar)}else e.select(this).remove();function T(t){return 0===l.bargap&&0===l.bargroupgap?e.round(Math.round(t)-w,2):t}})}),D.getComponentMethod("errorbars","plot")(s,n),s.each(function(t){var r=!1===t[0].trace.cliponaxis;Ur.setClipUrl(e.select(this),r?null:n.layerClipId)})};function go(e,t,r,n,a,i){var o;return a<1?o="scale("+a+") ":(a=1,o=""),"translate("+(r-a*e)+" "+(n-a*t)+")"+o+(i?"rotate("+i+" "+e+" "+t+") ":"")}function vo(e,t,n,a){var i=yo((t=t||{}).family,n),o=yo(t.size,n),l=yo(t.color,n);return{family:mo(e.family,i,a.family),size:function(e,t,n){if(r(t)){t=+t;var a=e.min,i=e.max,o=void 0!==a&&ti;if(!o)return t}return void 0!==n?n:e.dflt}(e.size,o,a.size),color:function(e,t,r){return s(t).isValid()?t:void 0!==r?r:e.dflt}(e.color,l,a.color)}}function yo(e,t){var r;return Array.isArray(e)?tc+l||!r(s))&&(f=!0,zo(u,e))}for(var h=0;h1||0===i.bargap&&0===i.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),n.selectAll("g.points").each(function(r){var n=e.select(this),a=n.selectAll("path"),i=n.selectAll("text"),o=r[0].trace;Ur.pointStyle(a,o,t),Ur.selectedPointStyle(a,o),i.each(function(t){var r,n=e.select(this);function a(e){var n=r[e];return Array.isArray(n)?n[t.i]:n}n.classed("bartext-inside")?r=o.insidetextfont:n.classed("bartext-outside")&&(r=o.outsidetextfont),r||(r=o.textfont),Ur.font(n,a("family"),a("size"),a("color"))}),Ur.selectedTextStyle(i,o)}),D.getComponentMethod("errorbars","style")(n)},Fo=m.extendFlat,jo=vr.LINE_SPACING,Bo={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},qo=function(t,n){var a=n[0].trace,i=a.marker,o="cb"+a.uid;if(t._fullLayout._infolayer.selectAll("."+o).remove(),void 0!==i&&i.showscale){var l=i.color,c=i.cmin,u=i.cmax;r(c)||(c=nt.aggNums(Math.min,null,l)),r(u)||(u=nt.aggNums(Math.max,null,l));var f=n[0].t.cb=function(t,r){var n={};function a(){var o=t._fullLayout,l=o._size;if("function"==typeof n.fillcolor||"function"==typeof n.line.color){var c,u,f=e.extent(("function"==typeof n.fillcolor?n.fillcolor:n.line.color).domain()),d=[],h=[],p="function"==typeof n.line.color?n.line.color:function(){return n.line.color},g="function"==typeof n.fillcolor?n.fillcolor:function(){return n.fillcolor},v=n.levels.end+n.levels.size/100,y=n.levels.size,m=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(u=0;u<1e5&&(c=n.levels.start+u*y,!(y>0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var H=Math.pow(10,Math.floor(Math.log(q)/Math.LN10));j*=H*nt.roundUp(q/H,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(R.tick0=0)}R.dtick=j}R.domain=[z+S,z+A-S],R.setScale();var V=o._infolayer.selectAll("g."+r).data([0]);V.enter().append("g").classed(r,!0).classed(Bo.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(Bo.cbbg,!0),t.append("g").classed(Bo.cbfills,!0),t.append("g").classed(Bo.cblines,!0),t.append("g").classed(Bo.cbaxis,!0).classed(Bo.crisp,!0),t.append("g").classed(Bo.cbtitleunshift,!0).append("g").classed(Bo.cbtitle,!0),t.append("rect").classed(Bo.cboutline,!0),t.select(".cbtitle").datum(0)}),V.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");R._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var Y,X=l.l+(n.x+L)*l.w,Z=R.titlefont.size;Y="top"===n.titleside?(1-(z+A-S))*l.h+l.t+3+.75*Z:(1-(z+S))*l.h+l.t-3-.25*Z,ee(R._id+"title",{attributes:{x:X,y:Y,"text-anchor":"start"}})}var W,Q,J,$=nt.syncOrAsync([qn.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=V.select(".cbtitle"),a=r.select("text"),i=[-n.outlinewidth/2,n.outlinewidth/2],c=r.select(".h"+R._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*jo),c?(G=Ur.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(Bo.jsPlaceholder)&&(G=Ur.bBox(a.node()).height),G){if(G+=5,"top"===n.titleside)R.domain[1]-=G/l.h,i[1]*=-1;else{R.domain[0]+=G/l.h;var v=mr.lineCount(a);i[1]+=(1-v)*u}r.attr("transform","translate("+i+")"),R.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-R.domain[1]))+")"),R._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(Bo.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,r){var n=[0===r?f[0]:(h[r]+h[r-1])/2,r===h.length-1?f[1]:(h[r]+h[r+1])/2].map(R.c2p).map(Math.round);r!==h.length-1&&(n[1]+=n[1]>n[0]?1:-1);var a=g(t).replace("e-",""),i=s(a).toHexString();e.select(this).attr({x:O,width:Math.max(k,2),y:e.min(n),height:Math.max(e.max(n)-e.min(n),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?d:[]);return m.enter().append("path").classed(Bo.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+O+","+(Math.round(R.c2p(t))+n.line.width/2%1)+"h"+k).call(Ur.lineGroupStyle,n.line.width,p(t),n.line.dash)}),R._axislayer.selectAll("g."+R._id+"tick,path").remove(),R._pos=O+k+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),R.side="right",nt.syncOrAsync([function(){return da.doTicks(t,R,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=R.titlefont.size,a=R._offset+R._length/2,i=l.l+(R.position||0)*l.w+("right"===R.side?10+r*(R.showticklabels?1:.5):-10-r*(R.showticklabels?.5:0));ee("h"+R._id+"title",{avoid:{selection:e.select(t).selectAll("g."+R._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},qn.previousPromises,function(){var e=k+n.outlinewidth/2+Ur.bBox(R._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(Bo.jsPlaceholder)){var a,i=U.select(".h"+R._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(n.titleside)?Ur.bBox(i).width:Ur.bBox(U.node()).right-O-l.l,e=Math.max(e,a)}var o=2*n.xpad+e+n.borderwidth+n.outlinewidth/2,s=E-N;V.select(".cbbg").attr({x:O-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:N-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(xt.fill,n.bgcolor).call(xt.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),V.selectAll(".cboutline").attr({x:O,y:N+n.ypad+("top"===n.titleside?G:0),width:Math.max(k,2),height:Math.max(s-2*n.ypad-G,2)}).call(xt.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var c=({center:.5,right:1}[n.xanchor]||0)*o;V.attr("transform","translate("+(l.l-c)+","+l.t+")"),qn.autoMargin(t,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],t);return $&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition&&Ai.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),Ni(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),Q=Ai.align(P+e/l.w,M,0,1,n.xanchor),J=Ai.align(z-t/l.h,A,0,1,n.yanchor);var r=Ai.getCursor(Q,J,n.xanchor,n.yanchor);Ni(V,r)},doneFn:function(){Ni(V),void 0!==Q&&void 0!==J&&D.call("restyle",t,{"colorbar.x":Q,"colorbar.y":J},i().index)}}),$}function K(e,t){return nt.coerce(I,R,mt,e,t)}function ee(e,r){var n,a=i();n=D.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:R,propName:n,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),ea.draw(t,e,Fo(l,r||{}))}o._infolayer.selectAll("g."+r).remove()}function i(){var e,n,a=r.substr(2);for(e=0;ee.uf}),i=Math.max((e.max-e.min)/10,e.q3-e.q1),c=1e-9*i,u=i*sl,f=[],d=0;if(r.jitter){if(0===i)for(d=1,f=new Array(a.length),t=0;te.lo&&(m.so=!0)}return a}).enter().append("path").classed("point",!0).call(Ur.translatePoints,a,i)}function fl(t,r,n,a){var i,o,l=r.pos,s=r.val,c=a.bPos,u=a.bPosPxOffset||0;Array.isArray(a.bdPos)?(i=a.bdPos[0],o=a.bdPos[1]):(i=a.bdPos,o=a.bdPos),t.selectAll("path.mean").data(nt.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var r=l.c2p(t.pos+c,!0)+u,a=l.c2p(t.pos+c-i,!0)+u,f=l.c2p(t.pos+c+o,!0)+u,d=s.c2p(t.mean,!0),h=s.c2p(t.mean-t.sd,!0),p=s.c2p(t.mean+t.sd,!0);"h"===n.orientation?e.select(this).attr("d","M"+d+","+a+"V"+f+("sd"===n.boxmean?"m0,0L"+h+","+r+"L"+d+","+a+"L"+p+","+r+"Z":"")):e.select(this).attr("d","M"+a+","+d+"H"+f+("sd"===n.boxmean?"m0,0L"+r+","+h+"L"+a+","+d+"L"+r+","+p+"Z":""))})}var dl=function(t,r,n){var a=t._fullLayout,i=r.xaxis,o=r.yaxis;r.plot.select(".boxlayer").selectAll("g.trace.boxes").data(n).enter().append("g").attr("class","trace boxes").each(function(t){var r,n,l=t[0],s=l.t,c=l.trace,u=l.node3=e.select(this),f=a._numBoxes,d="group"===a.boxmode&&f>1,h=s.dPos*(1-a.boxgap)*(1-a.boxgroupgap)/(d?f:1),p=d?2*s.dPos*((s.num+.5)/f-.5)*(1-a.boxgap):0,g=h*c.whiskerwidth;!0!==c.visible||s.empty?e.select(this).remove():("h"===c.orientation?(r=o,n=i):(r=i,n=o),s.bPos=p,s.bdPos=h,s.wdPos=g,cl(u,{pos:r,val:n},c,s),c.boxpoints&&ul(u,{x:i,y:o},c,s),c.boxmean&&fl(u,{pos:r,val:n},c,s))})},hl=["v","h"];function pl(e,t,r,n,a){var i,o,l,s=t.calcdata,c=t._fullLayout,u=[],f="violin"===e?"_numViolins":"_numBoxes";for(i=0;i=0&&k0){var T=_[n].sort(Qo),A=T.map(Jo),L=A.length,C={pos:v[n],pts:T};C.min=A[0],C.max=A[L-1],C.mean=nt.mean(A,L),C.sd=nt.stdev(A,L,C.mean),C.q1=nt.interp(A,.25),C.med=nt.interp(A,.5),C.q3=nt.interp(A,.75),C.lf=Math.min(C.q1,A[Math.min(nt.findBin(2.5*C.q1-1.5*C.q3,A,!0)+1,L-1)]),C.uf=Math.max(C.q3,A[Math.max(nt.findBin(2.5*C.q3-1.5*C.q1,A),0)]),C.lo=4*C.q1-3*C.q3,C.uo=4*C.q3-3*C.q1;var S=1.57*(C.q3-C.q1)/Math.sqrt(L);C.ln=C.med-S,C.un=C.med+S,f.push(C)}return function(e,t){if(nt.isArrayOrTypedArray(t.selectedpoints))for(var r=0;r0?(f[0].t={num:s[d],dPos:y,posLetter:l,valLetter:i,labels:{med:Zo(e,"median:"),min:Zo(e,"min:"),q1:Zo(e,"q1:"),q3:Zo(e,"q3:"),max:Zo(e,"max:"),mean:"sd"===t.boxmean?Zo(e,"mean \xb1 \u03c3:"):Zo(e,"mean:"),lf:Zo(e,"lower fence:"),uf:Zo(e,"upper fence:")}},t._fullInput&&"candlestick"===t._fullInput.type&&delete f[0].t.labels,s[d]++,f):[{t:{empty:!0}}]},vl.setPositions=gl,vl.plot=dl,vl.style=function(t,r){var n=r?r[0].node3:e.select(t).selectAll("g.trace.boxes");n.style("opacity",function(e){return e[0].trace.opacity}),n.each(function(r){var n=e.select(this),a=r[0].trace,i=a.line.width;n.selectAll("path.box").style("stroke-width",i+"px").call(xt.stroke,a.line.color).call(xt.fill,a.fillcolor),n.selectAll("path.mean").style({"stroke-width":i,"stroke-dasharray":2*i+"px,"+i+"px"}).call(xt.stroke,a.line.color);var o=n.selectAll("path.point");Ur.pointStyle(o,a,t),Ur.selectedPointStyle(o,a)})},vl.hoverPoints=nl,vl.selectPoints=function(e,t){var r,n,a=e.cd,i=e.xaxis,o=e.yaxis,l=[];if(!1===t)for(r=0;rn?t=!0:r1)for(var r=1;r=0,p=r.indexOf("end")>=0,g=c.backoff*f+n.standoff,v=u.backoff*d+n.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}r._w=C,r._h=S;for(var E=!1,N=["x","y"],I=0;I1)&&(U===V?((K=G.r2fraction(r["a"+H]))<0||K>1)&&(E=!0):E=!0,E))continue;R=G._offset+G.r2p(r[H]),B=.5}else"x"===H?(j=r[H],R=u.l+u.w*j):(j=1-r[H],R=u.t+u.h*j),B=r.showarrow?.5:j;if(r.showarrow){$.head=R;var ee=r["a"+H];q=X*z(.5,r.xanchor)-Z*z(.5,r.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=q):($.tail=R+ee,F=q+ee),$.text=$.tail+q;var te=c["x"===H?"width":"height"];if("paper"===V&&($.head=nt.constrain($.head,1,te-1)),"pixel"===U){var re=-Math.max($.tail-3,$.text),ne=Math.min($.tail+3,$.text)-te;re>0?($.tail+=re,$.text+=re):ne>0&&($.tail-=ne,$.text-=ne)}$.tail+=J,$.head+=J}else F=q=W*z(B,Q),$.text=R+q;$.text+=J,q+=J,F+=J,r["_"+H+"padplus"]=W/2+F,r["_"+H+"padminus"]=W/2-F,r["_"+H+"size"]=W,r["_"+H+"shift"]=q}if(E)x.remove();else{var ae=0,ie=0;if("left"!==r.align&&(ae=(C-_)*("center"===r.align?.5:1)),"top"!==r.valign&&(ie=(S-A)*("middle"===r.valign?.5:1)),l)n.select("svg").attr({x:w+ae-1,y:w+ie}).call(Ur.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(mr.positionText,le,oe).call(Ur.setClipUrl,M?d:null)}T.select("rect").call(Ur.setRect,w,w,C,S),k.call(Ur.setRect,b/2,b/2,O-b,P-b),x.call(Ur.setTranslate,Math.round(h.x.text-O/2),Math.round(h.y.text-P/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,n){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+n,m=h.x.text+e,b=h.y.text+n,_=nt.rotationXYMatrix(p,m,b),w=nt.apply2DTransform(_),M=nt.apply2DTransform2(_),T=+k.attr("width"),A=+k.attr("height"),L=m-.5*T,C=L+T,S=b-.5*A,O=S+A,P=[[L,S,L,O],[L,O,C,O],[C,O,C,S],[C,S,L,S]].map(M);if(!P.reduce(function(e,t){return e^!!nt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){P.forEach(function(e){var t=nt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var z=r.arrowwidth,E=r.arrowcolor,N=r.arrowside,I=g.append("g").style({opacity:xt.opacity(E)}).classed("annotation-arrow-g",!0),R=I.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",z+"px").call(xt.stroke,xt.rgb(E));if(rs(R,N,r),f.annotationPosition&&R.node().parentNode&&!a){var F=l,j=c;if(r.standoff){var B=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=r.standoff*(d-l)/B,j+=r.standoff*(y-c)/B}var q,H,V,U=I.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-j),transform:"translate("+F+","+j+")"}).style("stroke-width",z+6+"px").call(xt.stroke,"rgba(0,0,0,0)").call(xt.fill,"rgba(0,0,0,0)");Ai.init({element:U.node(),gd:t,prepFn:function(){var e=Ur.getTranslate(x);H=e.x,V=e.y,q={},i&&i.autorange&&(q[i._name+".autorange"]=!0),o&&o.autorange&&(q[o._name+".autorange"]=!0)},moveFn:function(e,t){var n=w(H,V),a=n[0]+e,l=n[1]+t;x.call(Ur.setTranslate,a,l),q[s+".x"]=i?i.p2r(i.r2p(r.x)+e):r.x+e/u.w,q[s+".y"]=o?o.p2r(o.r2p(r.y)+t):r.y-t/u.h,r.axref===r.xref&&(q[s+".ax"]=i.p2r(i.r2p(r.ax)+e)),r.ayref===r.yref&&(q[s+".ay"]=o.p2r(o.r2p(r.ay)+t)),I.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){D.call("relayout",t,q);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(r.showarrow&&ue(0,0),y)Ai.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var n="pointer";if(r.showarrow)r.axref===r.xref?se[s+".ax"]=i.p2r(i.r2p(r.ax)+e):se[s+".ax"]=r.ax+e,r.ayref===r.yref?se[s+".ay"]=o.p2r(o.r2p(r.ay)+t):se[s+".ay"]=r.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(r.x)+e);else{var l=r._xsize/u.w,c=r.x+(r._xshift-r.xshift)/u.w-l/2;se[s+".x"]=Ai.align(c+e/u.w,l,0,1,r.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(r.y)+t);else{var f=r._ysize/u.h,d=r.y-(r._yshift+r.yshift)/u.h-f/2;se[s+".y"]=Ai.align(d-t/u.h,f,0,1,r.yanchor)}i&&o||(n=Ai.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],r.xanchor,r.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),Ni(x,n)},doneFn:function(){Ni(x),D.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var os=ns.draw;function ls(e){var t=e._fullLayout;nt.filterVisible(t.annotations).forEach(function(t){var r,n,a,i,o=da.getFromId(e,t.xref),l=da.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(r=s+t.xshift,n=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(da.expand(o,[o.r2c(t.x)],{ppadplus:r,ppadminus:n}),da.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,da.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,r,a),ppadminus:Math.max(t._xpadminus,n,i)}))),l&&l.autorange&&(r=s-t.yshift,n=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(da.expand(l,[l.r2c(t.y)],{ppadplus:r,ppadminus:n}),da.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,da.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,r,a),ppadminus:Math.max(t._ypadminus,n,i)})))})}var ss={hasClickToShow:function(e,t){var r=cs(e,t);return r.on.length>0||r.explicitOff.length>0},onClick:function(e,t){var r,n=cs(e,t),a=n.on,i=n.off.concat(n.explicitOff),o={};if(!a.length&&!i.length)return;for(r=0;r1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=bs(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*r[0],t.yaxis.r2l(i.y)*r[1],t.zaxis.r2l(i.z)*r[2]]),_s(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var Ms={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},Ts=function(e){var t=e.type,r=e.symmetric;if("data"===t){var n=e.array||[];if(r)return function(e,t){var r=+n[t];return[r,r]};var a=e.arrayminus||[];return function(e,t){var r=+n[t],i=+a[t];return isNaN(r)&&isNaN(i)?[NaN,NaN]:[i||0,r||0]}}var i=As(t,e.value),o=As(t,e.valueminus);return r||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function As(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var Ls=function(e){for(var t=e.calcdata,r=0;r0;t.each(function(t){var s,c=t[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Vr.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(t=[]);var h=e.select(this).selectAll("g.errorbar").data(t,s);if(h.exit().remove(),t.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Ur.setClipUrl(h,n.layerClipId),h.each(function(t){var n=e.select(this),s=function(e,t,n){var a={x:t.c2p(e.x),y:n.c2p(e.y)};return void 0!==e.yh&&(a.yh=n.c2p(e.yh),a.ys=n.c2p(e.ys),r(a.ys)||(a.noYS=!0,a.ys=n.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=t.c2p(e.xh),a.xs=t.c2p(e.xs),r(a.xs)||(a.noXS=!0,a.xs=t.c2p(e.xs,!0))),a}(t,i,o);if(!d||t.vis){var c,h=n.select("path.yerror");if(f.visible&&r(s.x)&&r(s.yh)&&r(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=n.select("path.xerror");if(u.visible&&r(s.y)&&r(s.xh)&&r(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var r=t[0].trace,n=r.error_y||{},a=r.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(xt.stroke,n.color),a.copy_ystyle&&(a=n),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(xt.stroke,a.color)})},hoverInfo:function(e,t,r){(t.error_y||{}).visible&&(r.yerr=e.yh-e.y,t.error_y.symmetric||(r.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(r.xerr=e.xh-e.x,t.error_x.symmetric||(r.xerrneg=e.x-e.xs))}};var Ds={},Es=m.extendFlat;Ds.attributes=function(e,t){e=e||{},t=t||{};var r={valType:"info_array",editType:e.editType,items:[{valType:"number",min:0,max:1,editType:e.editType},{valType:"number",min:0,max:1,editType:e.editType}],dflt:[0,1]},n=(e.name&&e.name,e.trace,t.description&&t.description,{x:Es({},r,{}),y:Es({},r,{}),editType:e.editType});return e.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:e.editType},n.column={valType:"integer",min:0,dflt:0,editType:e.editType}),n},Ds.defaults=function(e,t,r,n){var a=n&&n.x||[0,1],i=n&&n.y||[0,1],o=t.grid;if(o){var l=r("domain.column");void 0!==l&&(l1){i||o||l||"independent"===d("pattern")&&(i=!0),s._hasSubplotGrid=i;var f="top to bottom"===d("roworder");s._domains={x:js("x",d,i?.2:.1,u),y:js("y",d,i?.3:.1,c,f)}}}function d(e,t){return nt.coerce(r,s,Fs,e,t)}},contentDefaults:function(e,t){var r=t.grid;if(r&&r._domains){var n,a,i,o,l,s,c,u=e.grid,f=t._subplots,d=r._hasSubplotGrid,h=r.rows,p=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(d){var y=u.subplots||[];s=r.subplots=new Array(h);var m=1;for(n=0;n=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},Zs={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Ws=!0,Qs=function(e,t,r){if(!t._dragged&&!t._editing){var n,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===r&&Ws&&t.data&&t._context.showTips?(nt.notifier(nt._(t,"Double-click on legend to isolate one trace"),"long"),Ws=!1):Ws=!1,D.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===r?-1===m?s.push(y):s.splice(m,1):2===r&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),D.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(n=0;nr[1])return r[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",nt.mean,[.2,1]),d.ms=u("marker.size",nt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",nt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),n=[nt.minExtend(i,d)],a=nt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?n:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Ur.pointStyle,a,r),l&&(n[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?n:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Ur.textPointStyle,a,r)})},tc=vr.LINE_SPACING,rc=vr.FROM_TL,nc=vr.FROM_BR,ac=h.DBLCLICKDELAY;function ic(e,t){var r=e.data()[0][0],n=t._fullLayout,a=r.trace,i=D.traceIs(a,"pie"),o=a.index,l=i?r.label:a.name,s=e.selectAll("text.legendtext").data([0]);function c(r){mr.convertToTspans(r,t,function(){!function(e,t){var r=e.data()[0][0];if(!r.trace.showlegend)return void e.remove();var n,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*tc;if(o){var s=Ur.bBox(o);n=s.height,a=s.width,Ur.setTranslate(i,0,n/4)}else{var c=e.select(".legendtext"),u=mr.lineCount(c),f=c.node();n=l*u,a=f?Ur.bBox(f).width:0;var d=l*(.3+(1-u)/2);mr.positionText(c,40,d)}n=Math.max(n,16)+3,r.height=n,r.width=a}(e,t)})}s.enter().append("text").classed("legendtext",!0),s.attr("text-anchor","start").classed("user-select-none",!0).call(Ur.font,n.legend.font).text(l),t._context.edits.legendText&&!i?s.call(mr.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var n,a=e;this.text()||(e=" ");var i=r.trace._fullInput||{},l={};if(-1!==["ohlc","candlestick"].indexOf(i.type))l[(n=r.trace.transforms)[n.length-1].direction+".name"]=e;else if(D.hasTransform(i,"groupby")){var s=D.getTransformIndices(i,"groupby"),u=s[s.length-1],f=nt.keyedContainer(i,"transforms["+u+"].styles","target","value.name");""===a?f.remove(r.trace._group):f.set(r.trace._group,e),l=f.constructUpdate()}else l.name=e;return D.call("restyle",t,l,o)}):c(s)}function oc(e,t){var r,n=1,a=e.selectAll("rect").data([0]);a.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(xt.fill,"rgba(0,0,0,0)"),a.on("mousedown",function(){(r=(new Date).getTime())-t._legendMouseDownTimeac&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Qs(e,t,n)},ac):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),t._legendMouseDownTime=0,Qs(e,t,n))}})}function lc(t,r,n){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=Ys.isGrouped(i),s=0;if(i._width=0,i._height=0,Ys.isVertical(i))l&&r.each(function(e,t){Ur.setTranslate(this,0,t*i.tracegroupgap)}),n.each(function(e){var t=e[0],r=t.height,n=t.width;Ur.setTranslate(this,o,5+o+i._height+r/2),i._height+=r,i._width=Math.max(i._width,n)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=r.data(),f=0,d=u.length;fo+b-_,n.each(function(e){var t=e[0],r=g?40+e[0].width:m;o+x+_+r>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Ur.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+r,i._height=Math.max(i._height,t.height),x+=_+r,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),n.each(function(r){var n=r[0],a=e.select(this).select(".legendtoggle");Ur.setRect(a,0,-n.height/2,(t._context.edits.legendText?0:i._width)+s,n.height)})}function sc(e){var t=e._fullLayout.legend,r="left";Xs.isRightAnchor(t)?r="right":Xs.isCenterAnchor(t)&&(r="center");var n="top";Xs.isBottomAnchor(t)?n="bottom":Xs.isMiddleAnchor(t)&&(n="middle"),qn.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*rc[r],r:t._width*nc[r],b:t._height*nc[n],t:t._height*rc[n]})}var cc={moduleType:"component",name:"legend",layoutAttributes:Gs,supplyLayoutDefaults:function(e,t,r){for(var n,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),nt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(n=0,i="left",a=1.1,o="bottom"):(n=0,i="left",a=-.1,o="top")}h("traceorder",u),Ys.isGrouped(t.legend)&&h("tracegroupgap"),h("x",n),h("xanchor",i),h("y",a),h("yanchor",o),nt.noneOrAll(l,s,["x","y"])}},draw:function(t){var r=t._fullLayout,n="legend"+r._uid;if(r._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=r.legend,i=r.showlegend&&function(e,t){var r,n,a={},i=[],o=!1,l={},s=0;function c(e,r){if(""!==e&&Ys.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[r]]):a[e].push([r]);else{var n="~~i"+s;i.push(n),a[n]=[[r]],s++}}for(r=0;rg?function(e){var t=e._fullLayout.legend,r="left";Xs.isRightAnchor(t)?r="right":Xs.isCenterAnchor(t)&&(r="center"),qn.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*rc[r],r:t._width*nc[r],b:0,t:0})}(t):sc(t);var v=r._size,y=v.l+v.w*a.x,m=v.t+v.h*(1-a.y);Xs.isRightAnchor(a)?y-=a._width:Xs.isCenterAnchor(a)&&(y-=a._width/2),Xs.isBottomAnchor(a)?m-=a._height:Xs.isMiddleAnchor(a)&&(m-=a._height/2);var x=a._width,b=v.w;x>b?(y=v.l,x=b):(y+x>p&&(y=p-x),y<0&&(y=0),x=Math.min(p-y,a._width));var _,w,k,M,T=a._height,A=v.h;if(T>A?(m=v.t,T=A):(m+T>g&&(m=g-T),m<0&&(m=0),T=Math.min(g-m,a._height)),Ur.setTranslate(l,y,m),f.on(".drag",null),l.on("wheel",null),a._height<=T||t._context.staticPlot)c.attr({width:x-a.borderwidth,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Ur.setTranslate(u,0,0),s.select("rect").attr({width:x-2*a.borderwidth,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Ur.setClipUrl(u,n),Ur.setRect(f,0,0,0,0),delete a._scrollY;else{var L,C,S=Math.max(Zs.scrollBarMinHeight,T*T/a._height),O=T-S-2*Zs.scrollBarMargin,P=a._height-T,z=O/P,E=Math.min(a._scrollY||0,P);c.attr({width:x-2*a.borderwidth+Zs.scrollBarWidth+Zs.scrollBarMargin,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),s.select("rect").attr({width:x-2*a.borderwidth+Zs.scrollBarWidth+Zs.scrollBarMargin,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+E}),Ur.setClipUrl(u,n),I(E,S,z),l.on("wheel",function(){I(E=nt.constrain(a._scrollY+e.event.deltaY/O*P,0,P),S,z),0!==E&&E!==P&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){L=e.event.sourceEvent.clientY,C=E}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||I(E=nt.constrain((t.clientY-L)/z+C,0,P),S,z)});f.call(N)}t._context.edits.legendPosition&&(l.classed("cursor-move",!0),Ai.init({element:l.node(),gd:t,prepFn:function(){var e=Ur.getTranslate(l);k=e.x,M=e.y},moveFn:function(e,t){var r=k+e,n=M+t;Ur.setTranslate(l,r,n),_=Ai.align(r,0,v.l,v.l+v.w,a.xanchor),w=Ai.align(n,0,v.t+v.h,v.t,a.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&D.call("relayout",t,{"legend.x":_,"legend.y":w})},clickFn:function(e,n){var a=r._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return n.clientX>=e.left&&n.clientX<=e.right&&n.clientY>=e.top&&n.clientY<=e.bottom});a.size()>0&&(1===e?l._clickTimeout=setTimeout(function(){Qs(a,t,e)},ac):2===e&&(l._clickTimeout&&clearTimeout(l._clickTimeout),Qs(a,t,e)))}}))}function I(e,r,n){a._scrollY=t._fullLayout.legend._scrollY=e,Ur.setTranslate(u,0,-e),Ur.setRect(f,x,Zs.scrollBarMargin+e*n,Zs.scrollBarWidth,r),s.select("rect").attr({y:a.borderwidth+e})}},style:ec},uc={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},fc=m.extendFlat,dc={visible:{valType:"boolean",editType:"plot"},buttons:uc=fc(uc,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:L({editType:"plot"}),bgcolor:{valType:"color",dflt:O.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:O.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},hc={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var pc=function(t,r){var n=t._name,a={};if("all"===r.step)a[n+".autorange"]=!0;else{var i=function(t,r){var n,a=t.range,i=new Date(t.r2l(a[1])),o=r.step,l=r.count;switch(r.stepmode){case"backward":n=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);n=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[n,c]}(t,r);a[n+".range[0]"]=i[0],a[n+".range[1]"]=i[1]}return a};var gc=vr.LINE_SPACING,vc=vr.FROM_TL,yc=vr.FROM_BR;function mc(e){return e._id}function xc(e,t,r){var n=e.selectAll("rect").data([0]);n.enter().append("rect").classed("selector-rect",!0),n.attr("shape-rendering","crispEdges"),n.attr({rx:hc.rx,ry:hc.ry}),n.call(xt.stroke,t.bordercolor).call(xt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,r)).style("stroke-width",t.borderwidth+"px")}function bc(e,t,r,n){var a,i=e.selectAll("text").data([0]);i.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),i.attr("text-anchor","middle"),i.call(Ur.font,t.font).text((a=r,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){mr.convertToTspans(e,n)})}var _c={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:dc}}},layoutAttributes:dc,handleDefaults:function(e,t,r,n,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return nt.coerce(i,o,dc,e,t)}if(l("visible",function(e,t,r){var n,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return nt.coerce(n,a,uc,e,t)}for(var s=0;s0)){var s=function(e,t,r){for(var n=r.filter(function(r){return t[r].anchor===e._id}),a=0,i=0;if&&(f=c)));return f>=u?[u,f]:void 0}}var qc=function(e,t,r,n,a){function i(r,n){return nt.coerce(e,t,Rc,r,n)}if(n=n||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=["x","y"],s=0;s<2;s++){var c=l[s],u={_fullLayout:r},f=da.coerceRef(e,t,u,c,"","paper");if("path"!==o){var d,h,p;"paper"!==f?(d=da.getFromId(u,f),p=jc.rangeToShapePosition(d),h=jc.shapePositionToRange(d)):h=p=nt.identity;var g=c+"0",v=c+"1",y=e[g],m=e[v];e[g]=h(e[g],!0),e[v]=h(e[v],!0),da.coercePosition(t,u,i,f,g,.25),da.coercePosition(t,u,i,f,v,.75),t[g]=p(t[g]),t[v]=p(t[v]),e[g]=y,e[v]=m}}return"path"===o?i("path"):nt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},Hc={draw:function(e){var t=e._fullLayout;t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._shapeSubplotLayers.selectAll("path").remove();for(var r=0;rN&&n>I&&!e.shiftKey?Ai.getCursor(a/r,1-i/n):"move";Ni(t,o),E=o.split("-")[0]}function B(n,h){if("path"===r.type){var p=function(e){return P(S(e)+n)};L&&"date"===L.type&&(p=jc.encodeDate(p));var g=function(e){return z(O(e)+h)};C&&"date"===C.type&&(g=jc.encodeDate(g)),r.path=Gc(T,p,g),a[A]=r.path}else a[c]=r.x0=P(i+n),a[u]=r.y0=z(o+h),a[f]=r.x1=P(l+n),a[d]=r.y1=z(s+h);t.attr("d",Uc(e,r))}function q(n,i){if("path"===r.type){var o=function(e){return P(S(e)+n)};L&&"date"===L.type&&(o=jc.encodeDate(o));var l=function(e){return z(O(e)+i)};C&&"date"===C.type&&(l=jc.encodeDate(l)),r.path=Gc(T,o,l),a[A]=r.path}else{var s=~E.indexOf("n")?h+i:h,c=~E.indexOf("s")?p+i:p,u=~E.indexOf("w")?g+n:g,f=~E.indexOf("e")?v+n:v;c-s>I&&(a[y]=r[_]=z(s),a[m]=r[w]=z(c)),f-u>N&&(a[x]=r[k]=P(u),a[b]=r[M]=P(f))}t.attr("d",Uc(e,r))}Ai.init(R),t.node().onmousemove=j}(e,o,n,t)}}function Uc(e,t){var r,n,a,i,o=t.type,l=da.getFromId(e,t.xref),s=da.getFromId(e,t.yref),c=e._fullLayout._size;if(l?(r=jc.shapePositionToRange(l),n=function(e){return l._offset+l.r2p(r(e,!0))}):n=function(e){return c.l+c.w*e},s?(a=jc.shapePositionToRange(s),i=function(e){return s._offset+s.r2p(a(e,!0))}):i=function(e){return c.t+c.h*(1-e)},"path"===o)return l&&"date"===l.type&&(n=jc.decodeDate(n)),s&&"date"===s.type&&(i=jc.decodeDate(i)),function(e,t,r){return e.replace(Fc.segmentRE,function(e){var n=0,a=e.charAt(0),i=Fc.paramIsX[a],o=Fc.paramIsY[a],l=Fc.numParams[a],s=e.substr(1).replace(Fc.paramRE,function(e){return i[n]?e=t(e):o[n]&&(e=r(e)),++n>l&&(e="X"),e});return n>l&&(s=s.replace(/[\s,]*X.*/,""),nt.log("Ignoring extra params in segment "+e)),a+s})}(t.path,n,i);var u=n(t.x0),f=n(t.x1),d=i(t.y0),h=i(t.y1);if("line"===o)return"M"+u+","+d+"L"+f+","+h;if("rect"===o)return"M"+u+","+d+"H"+f+"V"+h+"H"+u+"Z";var p=(u+f)/2,g=(d+h)/2,v=Math.abs(p-u),y=Math.abs(g-d),m="A"+v+","+y,x=p+v+","+g;return"M"+x+m+" 0 1,1 "+(p+","+(g-y))+m+" 0 0,1 "+x+"Z"}function Gc(e,t,r){return e.replace(Fc.segmentRE,function(e){var n=0,a=e.charAt(0),i=Fc.paramIsX[a],o=Fc.paramIsY[a],l=Fc.numParams[a];return a+e.substr(1).replace(Fc.paramRE,function(e){return n>=l?e:(i[n]?e=t(e):o[n]&&(e=r(e)),n++,e)})})}var Yc={moduleType:"component",name:"shapes",layoutAttributes:Rc,supplyLayoutDefaults:function(e,t){hs(e,t,{name:"shapes",handleItemDefaults:qc})},includeBasePlot:ps("shapes"),calcAutorange:function(e){var t=e._fullLayout,r=nt.filterVisible(t.shapes);if(r.length&&e._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),nt.noneOrAll(e,t,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),nt.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),nt.coerceFont(n,"currentvalue.font",t.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var eu=vr.LINE_SPACING,tu=vr.FROM_TL,ru=vr.FROM_BR;function nu(e){return e._index}function au(t,r){var n=Ur.tester.selectAll("g."+Xc.labelGroupClass).data(r.steps);n.enter().append("g").classed(Xc.labelGroupClass,!0);var a=0,i=0;n.each(function(t){var n=lu(e.select(this),{step:t},r).node();if(n){var o=Ur.bBox(n);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(Xc.railWidth,Xc.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*r.x,o.ly=l.t+l.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(l.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var s=(o.inputAreaLength-2*Xc.stepInset)/(r.steps.length-1),c=a+Xc.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var u=Ur.tester.append("g");n.each(function(e){var t=iu(u,r,e.label),n=t.node()&&Ur.bBox(t.node())||{width:0,height:0},a=mr.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+Xc.tickOffset+r.ticklen+Xc.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var f="left";Xs.isRightAnchor(r)&&(o.lx-=o.outerLength,f="right"),Xs.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,f="center");var d="top";Xs.isBottomAnchor(r)&&(o.ly-=o.height,d="bottom"),Xs.isMiddleAnchor(r)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),qn.autoMargin(t,Xc.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*tu[f],r:o.outerLength*ru[f],b:o.height*ru[d],t:o.height*tu[d]})}function iu(e,t,r){if(t.currentvalue.visible){var n,a,i=e.selectAll("text").data([0]),o=t._dims;switch(t.currentvalue.xanchor){case"right":n=o.inputAreaLength-Xc.currentValueInset-o.currentValueMaxWidth,a="left";break;case"center":n=.5*o.inputAreaLength,a="middle";break;default:n=Xc.currentValueInset,a="left"}i.enter().append("text").classed(Xc.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1});var l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof r)l+=r;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),i.call(Ur.font,t.currentvalue.font).text(l).call(mr.convertToTspans,t._gd);var s=mr.lineCount(i),c=(o.currentValueMaxLines+1-s)*t.currentvalue.font.size*eu;return mr.positionText(i,n,c),i}}function ou(e,t,r){var n=e.selectAll("rect."+Xc.gripRectClass).data([0]);n.enter().append("rect").classed(Xc.gripRectClass,!0).call(fu,t,e,r).style("pointer-events","all"),n.attr({width:Xc.gripWidth,height:Xc.gripHeight,rx:Xc.gripRadius,ry:Xc.gripRadius}).call(xt.stroke,r.bordercolor).call(xt.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function lu(e,t,r){var n=e.selectAll("text").data([0]);return n.enter().append("text").classed(Xc.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(Ur.font,r.font).text(t.step.label).call(mr.convertToTspans,r._gd),n}function su(t,r){var n=t.selectAll("g."+Xc.labelsClass).data([0]),a=r._dims;n.enter().append("g").classed(Xc.labelsClass,!0);var i=n.selectAll("g."+Xc.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(Xc.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var n=e.select(this);n.call(lu,t,r),Ur.setTranslate(n,pu(r,t.fraction),Xc.tickOffset+r.ticklen+r.font.size*eu+Xc.labelOffset+a.currentValueTotalHeight)})}function cu(e,t,r,n,a){var i=Math.round(n*(r.steps.length-1));i!==r.active&&uu(e,t,r,i,!0,a)}function uu(e,t,r,n,a,i){var o=r.active;r._input.active=r.active=n;var l=r.steps[r.active];t.call(hu,r,r.active/(r.steps.length-1),i),t.call(iu,r),e.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var r=t._nextMethod.step;r.method&&(r.execute&&qn.executeAPICommand(e,r.method,r.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function fu(t,r,n){var a=n.node(),i=e.select(r);function o(){return n.data()[0]}t.on("mousedown",function(){var t=o();r.emit("plotly_sliderstart",{slider:t});var l=n.select("."+Xc.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(xt.fill,t.activebgcolor);var s=gu(t,e.mouse(a)[0]);cu(r,n,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=gu(t,e.mouse(a)[0]);cu(r,n,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(xt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),r.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function du(t,r){var n=t.selectAll("rect."+Xc.tickRectClass).data(r.steps),a=r._dims;n.enter().append("rect").classed(Xc.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(t,n){var i=n%a.labelStride==0,o=e.select(this);o.attr({height:i?r.ticklen:r.minorticklen}).call(xt.fill,r.tickcolor),Ur.setTranslate(o,pu(r,n/(r.steps.length-1))-.5*r.tickwidth,(i?Xc.tickOffset:Xc.minorTickOffset)+a.currentValueTotalHeight)})}function hu(e,t,r,n){var a=e.select("rect."+Xc.gripRectClass),i=pu(t,r);if(!t._invokingCommand){var o=a;n&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*Xc.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function pu(e,t){var r=e._dims;return r.inputAreaStart+Xc.stepInset+(r.inputAreaLength-2*Xc.stepInset)*Math.min(1,Math.max(0,t))}function gu(e,t){var r=e._dims;return Math.min(1,Math.max(0,(t-Xc.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*Xc.stepInset-2*r.inputAreaStart)))}function vu(e,t,r){var n=e.selectAll("rect."+Xc.railTouchRectClass).data([0]),a=r._dims;n.enter().append("rect").classed(Xc.railTouchRectClass,!0).call(fu,t,e,r).style("pointer-events","all"),n.attr({width:a.inputAreaLength,height:Math.max(a.inputAreaWidth,Xc.tickOffset+r.ticklen+a.labelHeight)}).call(xt.fill,r.bgcolor).attr("opacity",0),Ur.setTranslate(n,0,a.currentValueTotalHeight)}function yu(e,t){var r=e.selectAll("rect."+Xc.railRectClass).data([0]),n=t._dims;r.enter().append("rect").classed(Xc.railRectClass,!0);var a=n.inputAreaLength-2*Xc.railInset;r.attr({width:a,height:Xc.railWidth,rx:Xc.railRadius,ry:Xc.railRadius,"shape-rendering":"crispEdges"}).call(xt.stroke,t.bordercolor).call(xt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Ur.setTranslate(r,Xc.railInset,.5*(n.inputAreaWidth-Xc.railWidth)+n.currentValueTotalHeight)}var mu={moduleType:"component",name:Xc.name,layoutAttributes:Qc,supplyLayoutDefaults:function(e,t){hs(e,t,{name:Jc,handleItemDefaults:Kc})},draw:function(t){var r=t._fullLayout,n=function(e,t){for(var r=e[Xc.name],n=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(Xc.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},r=Object.keys(t),n=0;n=r.steps.length&&(r.active=0),t.call(iu,r).call(yu,r).call(su,r).call(du,r).call(vu,e,r).call(ou,e,r);var n=r._dims;Ur.setTranslate(t,n.lx+r.pad.l,n.ly+r.pad.t),t.call(hu,r,r.active/(r.steps.length-1),!1),t.call(iu,r)}(t,e.select(this),r)}})}}},xu=m.extendFlat,bu=(0,ar.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:xu({},Zc,{}),font:L({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:O.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),_u={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},wu=_u.name,ku=bu.buttons;function Mu(e,t,r){function n(r,n){return nt.coerce(e,t,bu,r,n)}n("visible",function(e,t){var r,n,a=e.buttons||[],i=t.buttons=[];function o(e,t){return nt.coerce(r,n,ku,e,t)}for(var l=0;l0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),nt.noneOrAll(e,t,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),nt.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var Tu=Au;function Au(e,t,r){this.gd=e,this.container=t,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Au.barWidth=2,Au.barLength=20,Au.barRadius=2,Au.barPad=1,Au.barColor="#808BA4",Au.prototype.enable=function(t,r,n){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=Au.barLength+2*Au.barPad,k=Au.barWidth+2*Au.barPad,M=f,T=h+p;T+k>o&&(T=o-k);var A=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);A.exit().on(".drag",null).remove(),A.enter().append("rect").classed("scrollbar-horizontal",!0).call(xt.fill,Au.barColor),_?(this.hbar=A.attr({rx:Au.barRadius,ry:Au.barRadius,x:M,y:T,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=Au.barWidth+2*Au.barPad,S=Au.barLength+2*Au.barPad,O=f+d,P=h;O+C>i&&(O=i-C);var z=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);z.exit().on(".drag",null).remove(),z.enter().append("rect").classed("scrollbar-vertical",!0).call(xt.fill,Au.barColor),L?(this.vbar=z.attr({rx:Au.barRadius,ry:Au.barRadius,x:O,y:P,width:C,height:S}),this._vbarYMin=P+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,N=L?s+C+.5:s+.5,I=c-.5,R=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(I),width:Math.ceil(N)-Math.floor(E),height:Math.ceil(R)-Math.floor(I)}),this.container.call(Ur.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Ur.setClipUrl,null),delete this._clipRect),_||L){var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),L&&this.vbar.on(".drag",null).call(B)}this.setTranslate(r,n)},Au.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Ur.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Au.prototype._onBoxDrag=function(){var t=this.translateX,r=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(r-=e.event.dy),this.setTranslate(t,r)},Au.prototype._onBoxWheel=function(){var t=this.translateX,r=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(r+=e.event.deltaY),this.setTranslate(t,r)},Au.prototype._onBarDrag=function(){var t=this.translateX,r=this.translateY;if(this.hbar){var n=t+this._hbarXMin,a=n+this._hbarTranslateMax;t=(nt.constrain(e.event.x,n,a)-n)/(a-n)*(this.position.w-this._box.w)}if(this.vbar){var i=r+this._vbarYMin,o=i+this._vbarTranslateMax;r=(nt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,r)},Au.prototype.setTranslate=function(e,t){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(e=nt.constrain(e||0,0,r),t=nt.constrain(t||0,0,n),this.translateX=e,this.translateY=t,this.container.call(Ur.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/r;this.hbar.call(Ur.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/n;this.vbar.call(Ur.setTranslate,e,t+i*this._vbarTranslateMax)}};var Lu=vr.LINE_SPACING;function Cu(e){return e._index}function Su(e,t){return+e.attr(_u.menuIndexAttrName)===t._index}function Ou(e,t,r,n,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?zu(e,n,null,null,t):"dropdown"===t.type&&(a.attr(_u.menuIndexAttrName,"-1"),Pu(e,n,a,i,t),l||zu(e,n,a,i,t))}function Pu(e,t,r,n,a){var i=t.selectAll("g."+_u.headerClassName).data([0]),o=a._dims;i.enter().append("g").classed(_u.headerClassName,!0).style("pointer-events","all");var l=a.active,s=a.buttons[l]||_u.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(Du,a,s,e).call(Bu,a,c,u);var f=t.selectAll("text."+_u.headerArrowClassName).data([0]);f.enter().append("text").classed(_u.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(Ur.font,a.font).text(_u.arrowSymbol[a.direction]),f.attr({x:o.headerWidth-_u.arrowOffsetX+a.pad.l,y:o.headerHeight/2+_u.textOffsetY+a.pad.t}),i.on("click",function(){r.call(qu),r.attr(_u.menuIndexAttrName,Su(r,a)?-1:String(a._index)),zu(e,t,r,n,a)}),i.on("mouseover",function(){i.call(Ru)}),i.on("mouseout",function(){i.call(Fu,a)}),Ur.setTranslate(t,o.lx,o.ly)}function zu(t,r,n,a,i){n||(n=r).attr("pointer-events","all");var o=function(e){return-1==+e.attr(_u.menuIndexAttrName)}(n)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?_u.dropdownButtonClassName:_u.buttonClassName,s=n.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+_u.gapButtonHeader:f=h.headerWidth+_u.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-_u.gapButtonHeader+_u.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-_u.gapButtonHeader+_u.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:_u.gapButton,xPad:_u.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(Du,i,o,t).call(Bu,i,g),c.on("click",function(){e.event.defaultPrevented||(Ou(t,i,0,r,n,a,l),o.execute&&qn.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(Ru)}),c.on("mouseout",function(){c.call(Fu,i),s.call(Iu,i)})}),s.call(Iu,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,r,n,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(_u.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},r=Object.keys(t),n=0;n_.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,r;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,r=0;r=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,r=0;r0&&nt.log("Clearing previous rejected promises from queue."),e._promises=[]},Xu.cleanLayout=function(e){var t,r;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var n=(qn.subplotsRegistry.cartesian||{}).attrRegex,a=(qn.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),xt.clean(e),e},Xu.cleanData=function(e,t){for(var r=[],n=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}Xu.hasParent=function(e,t){for(var r=ef(t);r;){if(r in e)return!0;r=ef(r)}return!1};var tf=["x","y","z"];Xu.clearAxisTypes=function(e,t,r){for(var n=0;n1&&w.warn("Full array edits are incompatible with other edits",a);var f=r[""][""];if(of(f))t.set(null);else{if(!Array.isArray(f))return w.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(r).map(Number).sort(nf),b=t.get(),_=b||[],k=X(u,a).get(),M=[],A=-1,L=_.length;for(d=0;d_.length-(m?0:1))w.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&w.warn("Insertion & removal are incompatible with edits to the same index.",a,p),of(y)?M.push(p):m?("add"===y&&(y={}),_.splice(p,0,y),k&&k.splice(p,0,{})):w.warn("Unrecognized full object edit value",a,p,y),-1===A&&(A=p);else for(h=0;h=0;d--)_.splice(M[d],1),k&&k.splice(M[d],1);if(_.length?b||t.set(_):t.set(null),s)return!1;if(i(c,u),l!==T){var C;if(-1===A)C=x;else{for(L=Math.max(_.length,L),C=[],d=0;d=A);d++)C.push(p);for(d=A;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,r=0;r0})}function c(e,n){var a=e.seg,i=n.seg,o=a.start,s=a.end,c=i.start,u=i.end;r&&r.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return n;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(n,s):l(e,u),n;p&&(h||(g?l(n,s):l(e,u)),l(n,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(n,o):0===f.alongA?l(n,f.pt):1===f.alongA&&l(n,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(r&&r.vert(f.pt[0]),f.isStart){r&&r.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}r&&r.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,r&&r.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){r&&r.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:n,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:n,f.seg.otherFill={above:v,below:v}),r&&r.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(Tf.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return r&&r.done(),u}return e?{addRegion:function(e){for(var n,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,r,n){var a=t[1]-r[1],i=n[0]-r[0],o=t[0]-r[0],l=n[1]-r[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,r){return Math.abs(t[0]-r[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-n>e&&(l=!l),i=c,o=u}return l}};return t}();function Df(e,t,r){var n=Sf.segments(e),a=Sf.segments(t),i=r(Sf.combine(n,a));return Sf.polygon(i)}Sf={buildLog:function(e){return!0===e?Pf=kf():!1===e&&(Pf=!1),!1!==Pf&&Pf.list},epsilon:function(e){return zf.epsilon(e)},segments:function(e){var t=Af(!0,zf,Pf);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Af(!1,zf,Pf).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:Of.union(e.combined,Pf),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:Of.intersect(e.combined,Pf),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:Of.difference(e.combined,Pf),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:Of.differenceRev(e.combined,Pf),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:Of.xor(e.combined,Pf),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Lf(e.segments,zf,Pf),inverted:e.inverted}},polygonFromGeoJSON:function(e){return Mf.toPolygon(Sf,e)},polygonToGeoJSON:function(e){return Mf.fromPolygon(Sf,zf,e)},union:function(e,t){return Df(e,t,Sf.selectUnion)},intersect:function(e,t){return Df(e,t,Sf.selectIntersect)},difference:function(e,t){return Df(e,t,Sf.selectDifference)},differenceRev:function(e,t){return Df(e,t,Sf.selectDifferenceRev)},xor:function(e,t){return Df(e,t,Sf.selectXor)}},"object"==typeof window&&(window.PolyBool=Sf);var Ef,Nf=Sf,If=qe.dot,Rf=n.BADNUM,Ff=Ef={};Ff.tester=function(e){if(Array.isArray(e[0][0]))return Ff.multitester(e);var t,r=e.slice(),n=r[0][0],a=n,i=r[0][1],o=i;for(r.push(r[0]),t=1;ta||s===Rf||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===Rf||la||s===Rf||so)return!1;var c,u,f,d,h,p=r.length,g=r[0][0],v=r[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(If(i,f))>n)return!0;return!1};Ff.filter=function(e,t){var r=[e[0]],n=0,a=0;function i(i){e.push(i);var o=r.length,l=n;r.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:r}};var Bf=Pi.makeEventData,qf=Ef.filter,Hf=Ef.tester,Vf=Ef.multitester,Uf=ht.MINSELECT;function Gf(e){return e._id}var Yf=function(e,t,r,n,a){var i,o,l,s,c=n.gd,u=c._fullLayout,f=u._zoomlayer,d=n.element.getBoundingClientRect(),h=n.plotinfo,p=h.xaxis._offset,g=h.yaxis._offset,v=t-d.left,y=r-d.top,m=v,x=y,b="M"+v+","+y,_=n.xaxes[0]._length,w=n.yaxes[0]._length,k=n.xaxes.map(Gf),M=n.yaxes.map(Gf),T=n.xaxes.concat(n.yaxes),A=e.altKey;(e.shiftKey||e.altKey)&&h.selection&&h.selection.polygons&&!n.polygons?(n.polygons=h.selection.polygons,n.mergedPolygons=h.selection.mergedPolygons):(!e.shiftKey&&!e.altKey||(e.shiftKey||e.altKey)&&!h.selection)&&(h.selection={},h.selection.polygons=n.polygons=[],h.selection.mergedPolygons=n.mergedPolygons=[]),"lasso"===a&&(i=qf([[v,y]],ht.BENDPX));var L=f.selectAll("path.select-outline-"+h.id).data([1,2]);L.enter().append("path").attr("class",function(e){return"select-outline select-outline-"+e+" select-outline-"+h.id}).attr("transform","translate("+p+", "+g+")").attr("d",b+"Z");var C,S,O,P,z,D,E=f.append("path").attr("class","zoombox-corners").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1}).attr("transform","translate("+p+", "+g+")").attr("d","M0,0Z"),N=[],I=u._uid+ht.SELECTID,R=[];for(C=0;C=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function ld(e,t,r,n,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",a+"Z")}function sd(e,t,r){return e.append("path").attr("class","zoombox-corners").style({fill:xt.background,stroke:xt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+r+")").attr("d","M0,0Z")}function cd(e){e.selectAll(".select-outline").remove()}function ud(e,t,r,n,a,i){e.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),fd(e,t,a,i)}function fd(e,t,r,n){r||(e.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function dd(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function hd(e){ed&&e.data&&e._context.showTips&&(nt.notifier(nt._(e,"Double-click to zoom back out"),"long"),ed=!1)}function pd(e){return"lasso"===e||"select"===e}function gd(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,Kf)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function vd(e,t){if(di){var r=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(r,e._onwheel),e._onwheel=t,e.addEventListener(r,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}var yd=function(t,r,n,a,i,o,l,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k=t._fullLayout,M=t._fullLayout._zoomlayer,T=l+c==="nsew",A=1===(l+c).length;function L(){f=[r.xaxis],d=[r.yaxis];var e=f[0],n=d[0];g=e._length,v=n._length;var a,i,o=k._axisConstraintGroups,s=[e._id],M=[n._id];u=[r].concat(l&&c?r.overlays:[]);for(var T=1;TKf||o>Kf?(R="xy",i/g>o/v?(o=i*v/g,P>a?z.t=P-o:z.b=P+o):(i=o*g/v,O>n?z.l=O-i:z.r=O+i),j.attr("d",gd(z))):l():!m||o rect").call(Ur.setTranslate,a,i).call(Ur.setScale,r,n);var z=x.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");x.plot.call(Ur.setTranslate,O,P).call(Ur.setScale,1/r,1/n),z.selectAll(".point").call(Ur.setPointGroupScale,r,n),z.selectAll(".textpoint").call(Ur.setTextPointsScale,r,n),z.call(Ur.hideOutsideRangePoints,x),x.plot.selectAll(".barlayer .trace").call(Ur.hideOutsideRangePoints,x,".bartext")}}}return l.length*c.length!=1&&vd(C,function(e){if(t._context.scrollZoom||k._enablescrollzoom){if(null===G&&cd(M),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var r=t.querySelector(".plotly");if(L(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(G);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var a,i=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=X.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(c||b){for(c||(s=.5),a=0;a=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(r,a,h)?(d.push(e),h.push([r,a])):i=[0];var o=t.plotgroup.selectAll(".bg").data(i);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){t.bg=o;var e=t.plotgroup.node();e.insertBefore(this,e.childNodes[0])})});var p=n._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){n._plots[t].bg=e.select(this)}),f.each(function(e){var t=n._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Ur.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(xt.fill,n.plot_bgcolor).style("stroke-width",0),t.clipId="clip"+n._uid+e+"plot";var u,f,d=n._clips.selectAll("#"+t.clipId).data([0]);for(d.enter().append("clipPath").attr({class:"plotclip",id:t.clipId}).append("rect"),d.selectAll("rect").attr({width:a._length,height:c._length}),Ur.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=t.clipId):(u=t.clipId,f=null),Ur.setClipUrl(t.plot,u),r=0;rAd*h)||y)for(r=0;rL&&OT&&(T=O);l/=(T-M)/(2*A),M=a.l2r(M),T=a.l2r(T),a.range=a._input.range=_=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var T=k.slice();w&&b&&(T[1]+=M);var A=c.angularAxis.ticksCount||4;A>8&&(A=A/(A/8)+A%8),c.angularAxis.ticksStep&&(A=(T[1]-T[0])/A);var L=c.angularAxis.ticksStep||(T[1]-T[0])/(A*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),T[2]||(T[2]=L);var C=e.range.apply(this,T);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(T.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),O=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(O)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var P,z=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){P=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var N=u.map(function(e,t){var r=zd.util.cloneJson(e);return r.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",r.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,r.color="LinePlot"===e.geometry?e.strokeColor:e.color,r});zd.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:Od({},zd.Legend.defaultConfig().legendConfig,{container:P,elements:N,reverseOrder:c.legend.reverseOrder})})();var I=P.node().getBBox();g=Math.min(c.width-I.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],n.range([0,g]),l.layout.radialAxis.domain=n.domain(),P.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else P=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),z.attr("transform","translate("+y+")").style({cursor:"crosshair"});var R=[(c.width-(c.margin.left+c.margin.right+2*g+(I?I.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(R[0]=Math.max(0,R[0]),R[1]=Math.max(0,R[1]),t.select(".outer-group").attr("transform","translate("+R+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),j=F.node().getBBox();F.attr({x:y[0]-j.width/2,y:y[1]-g-20})}var B=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var q=B.selectAll("circle.grid-circle").data(n.ticks(5));q.enter().append("circle").attr({class:"grid-circle"}).style(D),q.attr("r",n),q.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(D);var H=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(n).ticks(5).tickSize(5);B.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),B.selectAll(".domain").style(D),B.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var X=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:Pd+"em",transform:function(e,t){var r=V(e),n=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-r+" "+n+" 0)":"radial"==a?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&X.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var Z=e.max(z.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));P.attr({transform:"translate("+[g+Z,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,Q=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(Q.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),Q.exit().remove(),u[0]||W){var J=[];u.forEach(function(e,t){var r={};r.radialScale=n,r.angularScale=a,r.container=Q.filter(function(e,r){return r==t}),r.geometry=e.geometry,r.orientation=c.orientation,r.direction=c.direction,r.index=t,J.push({data:e,geometryConfig:r})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(J).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var r;r=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var n=e.map(function(e,t){return Od(zd[r].defaultConfig(),e)});zd[r]().config(n)()})}var K,ee,te=t.select(".guides-group"),re=t.select(".tooltips-group"),ne=zd.tooltipPanel().config({container:re,fontSize:8})(),ae=zd.tooltipPanel().config({container:re,fontSize:8})(),ie=zd.tooltipPanel().config({container:re,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});z.on("mousemove.angular-guide",function(e,t){var r=zd.util.getMousePos(H).angle;oe.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-c.orientation)%360;K=a.invert(n);var i=zd.util.convertToCartesian(g+12,r+180);ne.text(zd.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});z.on("mousemove.radial-guide",function(e,t){var r=zd.util.getMousePos(H).radius;le.attr({r:r}).style({opacity:.5}),ee=n.invert(zd.util.getMousePos(H).radius);var a=zd.util.convertToCartesian(r,c.radialAxis.orientation);ae.text(zd.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),ne.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:zd.util.round(r[0]),r:zd.util.round(r[1])};b&&(s.t=m[r[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-R[0]-f.left,u.top+u.height/2-R[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,r){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,r){ie.hide();var n=e.select(this),a=n.attr("data-fill");a?n.style({fill:a,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=zd.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),Od(i.data[t],zd.Axis.defaultConfig().data[0]),Od(i.data[t],e)}),Od(i.layout,zd.Axis.defaultConfig().layout),Od(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return n},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},zd.Axis.defaultConfig=function(t,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},zd.util={},zd.DATAEXTENT="dataExtent",zd.AREA="AreaChart",zd.LINE="LinePlot",zd.DOT="DotPlot",zd.BAR="BarChart",zd.util._override=function(e,t){for(var r in e)r in t&&(t[r]=e[r])},zd.util._extend=function(e,t){for(var r in e)t[r]=e[r]},zd.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},zd.util.dataFromEquation2=function(t,r){var n=r||6;return e.range(0,360+n,n).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},zd.util.dataFromEquation=function(t,r,n){var a=r||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,r){var n=e*Math.PI/180,a=t(n);i.push(e),o.push(a)});var l={t:i,r:o};return n&&(l.name=n),l},zd.util.ensureArray=function(t,r){if(void 0===t)return null;var n=[].concat(t);return e.range(r).map(function(e,t){return n[t]||n[0]})},zd.util.fillArrays=function(e,t,r){return t.forEach(function(t,n){e[t]=zd.util.ensureArray(e[t],r)}),e},zd.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},zd.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var r=t.shift();return e[r]&&(!t.length||objHasKeys(e[r],t))},zd.util.sumArrays=function(t,r){return e.zip(t,r).map(function(t,r){return e.sum(t)})},zd.util.arrayLast=function(e){return e[e.length-1]},zd.util.arrayEqual=function(e,t){for(var r=Math.max(e.length,t.length,1);r-- >=0&&e[r]===t[r];);return-2===r},zd.util.flattenArray=function(e){for(var t=[];!zd.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},zd.util.deduplicate=function(e){return e.filter(function(e,t,r){return r.indexOf(e)==t})},zd.util.convertToCartesian=function(e,t){var r=t*Math.PI/180;return[e*Math.cos(r),e*Math.sin(r)]},zd.util.round=function(e,t){var r=t||2,n=Math.pow(10,r);return Math.round(e*n)/n},zd.util.getMousePos=function(t){var r=e.mouse(t.node()),n=r[0],a=r[1],i={};return i.x=n,i.y=a,i.pos=r,i.angle=180*(Math.atan2(a,n)+Math.PI)/Math.PI,i.radius=Math.sqrt(n*n+a*a),i},zd.util.duplicatesCount=function(e){for(var t,r={},n={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(n,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(n,a,i)},"stroke-width":function(e,t){return p["stroke-width"](n,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](n,a,i)},opacity:function(e,t){return p.opacity(n,a,i)},display:function(e,t){return p.display(n,a,i)}})}};var f=r.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return r.radialScale(s+(e[2]||0))}).outerRadius(function(e){return r.radialScale(s+(e[2]||0))+r.radialScale(e[1])});c.arc=function(t,n,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(r.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,r,a){return n[t[a].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return void 0===t[n].data.visible||t[n].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[r.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),Od(t[r],zd.PolyChart.defaultConfig()),Od(t[r],e)}),this):t},a.getColorScale=function(){},e.rebind(a,r,"on"),a},zd.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},zd.BarChart=function(){return zd.PolyChart()},zd.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},zd.AreaChart=function(){return zd.PolyChart()},zd.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},zd.DotPlot=function(){return zd.PolyChart()},zd.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},zd.LinePlot=function(){return zd.PolyChart()},zd.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},zd.Legend=function(){var t=zd.Legend.defaultConfig(),r=e.dispatch("hover");function n(){var r=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,n){var a=Od({},r.elements[t]);return a.name=e,a.color=[].concat(r.elements[t].color)[n],a})}),i=e.merge(a);i=i.filter(function(e,t){return r.elements[t]&&(r.elements[t].visibleInLegend||void 0===r.elements[t].visibleInLegend)}),r.reverseOrder&&(i=i.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=r.fontSize,c=null==r.isContinuous?"number"==typeof i[0]:r.isContinuous,u=c?r.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,r){var n,a,i,o=t.symbol;return i=3*(a=s),"line"===(n=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(n)?e.svg.symbol().type(n).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?r.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?r.textColor:"none"}),x.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(e,t){return i[t].name}),n}return n.config=function(e){return arguments.length?(Od(t,e),this):t},e.rebind(n,r,"on"),n},zd.Legend.defaultConfig=function(e,t){return{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:!1}}},zd.tooltipPanel=function(){var t,r,n,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+zd.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return n=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";r.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=r.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return n.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return Od(a,e),l},l},zd.tooltipPanel.uid=1,zd.adapter={},zd.adapter.plotly=function(){var t={convert:function(t,r){var n={};if(t.data&&(n.data=t.data.map(function(e,t){var n=Od({},e);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(e,t){zd.util.translator.apply(null,e.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&t.layout&&"stack"===t.layout.barmode)){var a=zd.util.duplicates(n.data.map(function(e,t){return e.geometry}));n.data.forEach(function(e,t){var r=a.indexOf(e.geometry);-1!=r&&(n.data[t].groupId=r)})}if(t.layout){var i=Od({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){zd.util.translator.apply(null,e.concat(r))}),r?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}r&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),n.layout=i}return n}};return t};var Dd,Ed=nt.extendDeepAll,Nd=Dd={};Nd.framework=function(t){var r,n,a,i,o,l=new function(){var e,t=[],r=-1,n=!1;function a(e,t){return e?(n=!0,e[t](),n=!1,this):this}return{add:function(e){return n?this:(t.splice(r+1,t.length-r),t.push(e),r=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var n=t[r];return n?(a(n,"undo"),r-=1,e&&e(n.undo),this):this},redo:function(){var n=t[r+1];return n?(a(n,"redo"),r+=1,e&&e(n.redo),this):this},clear:function(){t=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?Ed(r,n):n,a||(a=Sd.Axis()),i=Sd.adapter.plotly().convert(r),a.config(i).render(o),t.data=r.data,t.layout=r.layout,Nd.fillLayout(t),r}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return r},s.getLiveConfig=function(){return Sd.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=Sd.util.cloneJson(r);e=i,t=n,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),n=Sd.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},Nd.fillLayout=function(t){var r=e.select(t).selectAll(".plot-container"),n=r.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:xt.background,_container:r,_paperdiv:n,_paper:a};t._fullLayout=Ed(i,t.layout)};var Id={};(Id=Sd).manager=Dd;var Rd={},Fd=kd.enforce,jd=kd.clean,Bd=ia,qd=0;function Hd(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){nt.error(e)}}function Vd(e,t){Hd(e,xt.combine(t,"white"))}function Ud(e,t){e._context||(e._context=nt.extendDeep({},_));var r,n,a,i=e._context;if(t){for(n=Object.keys(t),r=0;r=e.data.length||a<-e.data.length)throw new Error(r+" must be valid indices for gd.data.");if(t.indexOf(a,n+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+r+" must be unique.")}}function Xd(e,t,r){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),Yd(e,t,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&Yd(e,r,"newIndices"),void 0!==r&&t.length!==r.length)throw new Error("current and new indices must be of equal length.")}function Zd(e,t,n,a,i){!function(e,t,r,n){var a=nt.isPlainObject(n);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!nt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var i in Yd(e,r,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==r.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in n)||!Array.isArray(n[i])||n[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,t,n,a);for(var o=function(e,t,n,a){var i,o,l,s,c,u=nt.isPlainObject(a),f=[];for(var d in Array.isArray(n)||(n=[n]),n=Gd(n,e.data.length-1),t)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var T=_.parts[M],A=_.parts[M-1]+"."+T,L=_.parts.slice(0,M).join("."),C=nt.nestedProperty(e.layout,L).get(),S=nt.nestedProperty(o,L).get(),O=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===T?w:Qd(O);var P=Tn.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var z in P.impliedEdits)v(nt.relativeAttr(b,z),P.impliedEdits[z]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(A.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(A),nt.nestedProperty(o,L+"._inputRange").set(null);else if(A.match(/^[xyz]axis[0-9]*\.autorange$/)){x(A),nt.nestedProperty(o,L+"._inputRange").set(null);var E=nt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else A.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&nt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===T){var N=C,I="linear"===S.type&&"log"===w,R="log"===S.type&&"linear"===w;if(I||R){if(N&&N.range)if(S.autorange)I&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],j=N.range[1];I?(F<=0&&j<=0&&v(L+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(j)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,j)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],D.getComponentMethod("annotations","convertCoords")(e,S,w,v),D.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);nt.nestedProperty(o,L+"._inputRange").set(null)}else if(T.match(ht.AX_NAME_PATTERN)){var B=nt.nestedProperty(o,b).get(),q=(w||{}).type;q&&"-"!==q||(q="linear"),D.getComponentMethod("annotations","convertCoords")(e,B,q,v),D.getComponentMethod("images","convertCoords")(e,B,q,v)}var H=rf.containerArrayMatch(b);if(H){r=H.array,n=H.index;var V=H.property,U=(nt.nestedProperty(i,r)||[])[n]||{},G=U,Y=P||{editType:"calc"},X=-1!==Y.editType.indexOf("calcIfAutorange");""===n?(X?h.calc=!0:ar.update(h,Y),X=!1):""===V&&(G=w,rf.isAddVal(w)?g[b]=null:rf.isRemoveVal(w)?(g[b]=U,G=U):nt.warn("unrecognized full object value",t)),X&&(eh(e,G,"x")||eh(e,G,"y"))?h.calc=!0:ar.update(h,Y),c[r]||(c[r]={});var Z=c[r][n];Z||(Z=c[r][n]={}),Z[V]=w,delete t[b]}else"reverse"===T?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==O&&"select"!==O?h.plot=!0:P?ar.update(h,P):h.calc=!0,_.set(w))}}for(r in c){rf.applyContainerArrayChanges(e,nt.nestedProperty(i,r),c[r],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(n=0;n=0&&r=0&&r=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var r=0;return function(){if(e&&++r===t)return e()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(i,c){function u(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var t=n._currentFrame=n._frameQueue.shift();if(t){var r=t.name?t.name.toString():null;e._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=t.frameOpts.duration,qn.transition(e,t.frame.data,t.frame.layout,Xu.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:r,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function f(){e.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var t=function(){n._animationRaf=window.requestAnimationFrame(t),Date.now()-n._lastFrameAt>n._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&nt.isPlainObject(t))v.push({type:"object",data:g(nt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;n--)if(nt.isPlainObject(t[n])){var d=t[n].name,h=(s[d]||f[d]||{}).name,p=t[n].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&qd<5&&(qd++,nt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===qd&&nt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:qn.supplyFrameDefaults(t[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:c+n})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;n--){if("number"==typeof(a=u[n].frame).name&&nt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;r--)n=t[r],i.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:a[n]});var l=qn.modifyFrames,s=qn.modifyFrames,c=[e,o],u=[e,i];return Gu&&Gu.add(e,l,c,s,u),qn.modifyFrames(e,i)},Rd.purge=function(e){var t=(e=nt.getGraphDiv(e))._fullLayout||{},r=e._fullData||[];return qn.cleanPlot([],{},r,t),qn.purge(e),Mi.purge(e),t._container&&t._container.remove(),delete e._context,e};var nh={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},ah=mi.EventEmitter;var ih=function(e){var t=e.emitter||new ah,r=new Promise(function(n,a){var i=window.Image,o=e.svg,l=e.format||"png";if(nt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?r:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var r;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":r=c.toDataURL("image/jpeg");break;case"png":r=c.toDataURL("image/png");break;case"webp":r=c.toDataURL("image/webp");break;case"svg":r=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}n(r),e.promise||t.emit("success",r)},p.onerror=function(r){if(a(r),!e.promise)return t.emit("error",r)},p.src=g});return e.promise?r:t},oh=/"/g,lh=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var sh=function(r,n,a){var i,o=r._fullLayout,l=o._paper,s=o._toppaper,c=o.width,u=o.height;l.insert("rect",":first-child").call(Ur.setRect,0,0,c,u).call(xt.fill,o.paper_bgcolor);var f=o._basePlotModules||[];for(i=0;i")?"":r.html(e).text()});return r.remove(),n}(v),v=(v=v.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(lh,"'"),nt.isIE()&&(v=(v=(v=v.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),v},ch={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},uh=/^data:image\/\w+;base64,/;var fh=function(e,t){var r,n,a;function i(e){return!(e in t)||nt.validate(t[e],ch[e])}if(t=t||{},nt.isPlainObject(e)?(r=e.data||[],n=e.layout||{},a=e.config||{}):(e=nt.getGraphDiv(e),r=nt.extendDeep([],e.data),n=nt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,r){return nt.coerce(t,o,ch,e,r)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=nt.extendFlat({},n);c&&(g.width=c),u&&(g.height=u);var v=nt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=nh.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,nh.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var r=sh(p,s,f),n=p._fullLayout.width,a=p._fullLayout.height;if(Rd.purge(p),document.body.removeChild(p),"svg"===s)return e(h?r:"data:image/svg+xml,"+encodeURIComponent(r));var i=document.createElement("canvas");i.id=nt.randstr(),ih({format:s,width:n,height:a,scale:f,canvas:i,svg:r,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){Rd.plot(p,r,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(uh,""):e}(t))}).catch(function(e){t(e)})})},dh=nt.isPlainObject,hh=Array.isArray,ph=nt.isArrayOrTypedArray;function gh(e,t,r,n,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&n.push(mh("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(hh(u[y])){u[y].length>f[y].length&&n.push(mh("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],nt.validate(x,m)?b!==x&&b!==+x&&n.push(mh("dynamic",a,c.concat(y,v),x,b)):n.push(mh("value",a,c.concat(y,v),x))}else n.push(mh("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],nt.validate(x,m)?b!==x&&b!==+x&&n.push(mh("dynamic",a,c.concat(y),x,b)):n.push(mh("value",a,c.concat(y),x))}else if(d.items&&!h&&hh(u)){var M,T,A=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(mh("object","layout"))),qn.supplyDefaults(o);for(var l=o._fullData,s=r.length,c=0;c-1&&(l[c[r]].title="");for(r=0;rq||e[1]V)return[Gh(e[0],B,q),Gh(e[1],H,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===B||e[0]===q)||(e[1]===t[1]&&(e[1]===H||e[1]===V)||void 0)}function X(e,t,r){return function(n,a){var i=G(n),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*nt.constrain((n[e]+a[e])/2,t,r)-((i||n)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function Z(e){var t=e[0],r=e[1],n=t===L[C-1][0],a=r===L[C-1][1];if(!n||!a)if(C>1){var i=t===L[C-2][0],o=r===L[C-2][1];n&&(t===B||t===q)&&i?o?C--:L[C-1]=e:a&&(r===H||r===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&Z([E,N]),Z(e),I=null,E=N=0}function Q(e){if(z=e[0]q?q:0,D=e[1]V?V:0,z||D){if(C)if(I){var t=F(I,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else R=F(L[C-1],e)[0],L[C++]=R;else L[C++]=[z||e[0],D||e[1]];var r=L[C-1];z&&D&&(r[0]!==z||r[1]!==D)?(I&&(E!==z&&N!==D?Z(E&&N?(n=I,i=(a=e)[0]-n[0],o=(a[1]-n[1])/i,(n[1]*a[0]-a[1]*n[0])/i>0?[o>0?B:q,V]:[o>0?q:B,H]):[E||z,N||D]):E&&N&&Z([E,N])),Z([z,D])):E-z&&N-D&&Z([z||E,D||N]),I=e,E=z,N=D}else I&&W(F(I,e)[0]),L[C++]=e;var n,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var r=[],n=0,a=0;a<4;a++){var i=U[a],o=Uh(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&P(o,e)O(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;Q(l),n=l}}else Q(i)}I&&Z([E||I[0],N||I[1]]),T.push(L.slice(0,C))}return T},Xh=Ef.tester;function Zh(t,r,n,a,i,o,l){var s,c;!function(t,r,n,a,i){var o=n.xaxis,l=n.yaxis,s=e.extent(nt.simpleMap(o.range,o.r2c)),c=e.extent(nt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Vr.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var n=e[0].trace;Vr.hasMarkers(n)&&n.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=n.xaxis,h=n.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(D.getComponentMethod("errorbars","plot")(v,n,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),a[0].node3=v;var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,T,A,L,C,S,O,P,z="",E="",N=[],I=nt.noop;if(y=p._ownFill,Vr.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=Ur.steps(g.shape),A=Ur.steps(g.shape.split("").reverse().join(""))):T=A="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Ur.smoothclosed(e.slice(1),g.smoothing):Ur.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return A(e.reverse())},N=Yh(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=p._polygons=new Array(N.length),c=0;c1){var n=e.select(this);if(n.datum(a),t)f(n.style("opacity",0).attr("d",k).call(Ur.lineGroupStyle)).style("opacity",1);else{var i=f(n);i.attr("d",k),Ur.singleLineStyle(a,i)}}}}}var R=v.selectAll(".js-line").data(N);f(R.exit()).style("opacity",0).remove(),R.each(I(!1)),R.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Ur.lineGroupStyle).each(I(!0)),Ur.setClipUrl(R,n.layerClipId),N.length?(y?C&&O&&(x?("y"===x?C[1]=O[1]=h.c2p(0,!0):"x"===x&&(C[0]=O[0]=d.c2p(0,!0)),f(y).attr("d","M"+O+"L"+C+"L"+z.substr(1)).call(Ur.singleFillStyle)):f(y).attr("d",z+"Z").call(Ur.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&z&&b?("tonext"===p.fill?f(m).attr("d",z+"Z"+b+"Z").call(Ur.singleFillStyle):f(m).attr("d",z+"L"+b.substr(1)+"Z").call(Ur.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=P):(y?j(y):m&&j(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var r=!1===t[0].trace.cliponaxis;Ur.setClipUrl(e.select(this),r?null:n.layerClipId)})}function j(e){f(e).attr("d","M0,0Z")}function B(e){return e.filter(function(e){return e.vis})}function q(e){return e.id}function H(e){if(e.ids)return q}function V(){return!1}function U(r){var a,i=r[0].trace,o=e.select(this),l=Vr.hasMarkers(i),s=Vr.hasText(i),c=H(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?B:nt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?B:nt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Ur.pointStyle,i,t).call(Ur.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Ur.tryColorscale(i.marker,""),m=l&&Ur.tryColorscale(i.marker,"line");a.order(),a.each(function(r){var a=e.select(this),o=f(a);Ur.translatePoint(r,o,d,h)?(Ur.singlePointStyle(r,o,i,y,m,t),n.layerClipId&&Ur.hideOutsideRangePoint(r,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var r=e.select(this),a=f(r.select("text"));Ur.translatePoint(t,a,d,h)?n.layerClipId&&Ur.hideOutsideRangePoint(t,r,d,h,i.xcalendar,i.ycalendar):r.remove()}),a.selectAll("text").call(Ur.textPointStyle,i,t).each(function(t){var r=d.c2p(t.x),n=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:r,y:n})})}),a.exit().remove()}}function Wh(e,t,r){var n=e.selectAll("path.point"),a=e.selectAll("text");Ur.pointStyle(n,t,r),Ur.textPointStyle(a,t,r),Ur.selectedPointStyle(n,t),Ur.selectedTextStyle(a,t)}var Qh=function(t,r){var n=r?r[0].node3:e.select(t).selectAll("g.trace.scatter");n.style("opacity",function(e){return e[0].trace.opacity}),n.selectAll("g.points").each(function(r){Wh(e.select(this),r.trace||r[0].trace,t)}),n.selectAll("g.trace path.js-line").call(Ur.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(Ur.fillGroupStyle),D.getComponentMethod("errorbars","style")(n)},Jh={};Jh.hasLines=Vr.hasLines,Jh.hasMarkers=Vr.hasMarkers,Jh.hasText=Vr.hasText,Jh.isBubble=Vr.isBubble,Jh.attributes=yn,Jh.supplyDefaults=function(e,t,r,n){function a(r,n){return nt.coerce(e,t,yn,r,n)}var i=ui(e,t,n,a),o=i=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===r.xaxis&&i.yaxis===r.yaxis){i.opacity=void 0;break}}}}},Jh.calc=jh,Jh.arraysToCalcdata=Dh,Jh.plot=function(t,r,n,a,i){var o,l,s,c,u=r.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(n,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,r){var n,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){Zh(t,i,r,e,n,this,a)})})):u.selectAll("g.trace").each(function(e,i){Zh(t,i,r,e,n,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()},Jh.colorbar=qo,Jh.style=Qh,Jh.hoverPoints=function(e,t,r,n){var a=e.cd,i=a[0].trace,o=e.xa,l=e.ya,s=o.c2p(t),c=l.c2p(r),u=[s,c],f=i.hoveron||"",d=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var h=function(e){var t=Math.max(d,e.mrc||0),r=o.c2p(e.x)-s,n=l.c2p(e.y)-c;return Math.max(Math.sqrt(r*r+n*n)-t,1-d/t)},p=to.getDistanceFunction(n,function(e){var t=Math.max(3,e.mrc||0),r=1-1/t,n=Math.abs(o.c2p(e.x)-s);return nI!=(L=w[b][1])>=I&&(M=w[b-1][0],T=w[b][0],L-A&&(k=M+(T-M)*(I-A)/(L-A),P=Math.min(P,k),z=Math.max(z,k)));P=Math.max(P,0),z=Math.min(z,o._length);var R=xt.defaultLine;return xt.opacity(i.fillcolor)?R=i.fillcolor:xt.opacity((i.line||{}).color)&&(R=i.line.color),nt.extendFlat(e,{distance:e.maxHoverDistance,x0:P,x1:z,y0:I,y1:I,color:R}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},Jh.selectPoints=function(e,t){var r,n,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Vr.hasMarkers(u)&&!Vr.hasText(u))return[];if(!1===t)for(r=0;ri){var o=i-n[e];return n[e]=i,o}}return 0},max:function(e,t,n,a){var i=a[t];if(r(i)){if(i=Number(i),!r(n[e]))return n[e]=i,i;if(n[e]hp?e>up?e>1.1*sp?sp:e>1.1*cp?cp:up:e>fp?fp:e>dp?dp:hp:Math.pow(10,Math.floor(Math.log(e)/Math.LN10))}function yp(e,t,r,n,a,i){if(n&&e>up){var o=mp(t,a,i),l=mp(r,a,i),s=e===sp?0:1;return o[s]!==l[s]}return Math.floor(r/e)-Math.floor(t/e)>.1}function mp(e,t,r){var n=t.c2d(e,sp,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}var xp=nt.cleanDate,bp=n.ONEDAY,_p=n.BADNUM,wp={percent:function(e,t){for(var r=e.length,n=100/t,a=0;ac.size/1.9?c.size:c.size/Math.ceil(c.size/g);var _=c.start+(c.size-g)/2;v=_-g*Math.ceil((_-v)/g)}for(o=0;o0?Number(c):s;else if("string"!=typeof c)o.size=s;else{var u=c.charAt(0),f=c.substr(1);((f=r(f)?Number(f):0)<=0||"date"!==a||"M"!==u||f!==Math.round(f))&&(o.size=s)}var d="autobin"+n;"boolean"!=typeof e[d]&&(e[d]=e._fullInput[d]=e._input[d]=!((o.start||0===o.start)&&(o.end||0===o.end))),e[d]||(delete e["nbins"+n],delete e._fullInput["nbins"+n])}(t,o,l);var f,d,h,p=Mp(e,t,o,l),g=p[0],v=p[1],y="string"==typeof g.size,m=[],x=y?m:g,b=[],_=[],w=[],k=0,M=t.histnorm,T=t.histfunc,A=-1!==M.indexOf("density");u.enabled&&A&&(M=M.replace(/ ?density$/,""),A=!1);var L,C="max"===T||"min"===T?null:0,S=lp.count,O=wp[M],P=!1,z=function(e){return o.r2c(e,0,c)};for(nt.isArrayOrTypedArray(t[s])&&"count"!==T&&(L=t[s],P="avg"===T,S=lp[T]),n=z(g.start),d=z(g.end)+(n-da.tickIncrement(n,g.size,!1,c))/1e6;n=0&&hh&&hup){var p=i===sp?1:6,g=i===sp?"M12":"M1";return function(t,r){var i=n.c2d(t,sp,a),l=i.indexOf("-",p);l>0&&(i=i.substr(0,l));var s=n.d2c(i,0,a);if(s=0;n--)l(n);else if("increasing"===t){for(n=1;n=0;n--)e[n]+=e[n+1];"exclude"===r&&(e.push(0),e.shift())}}(i,u.direction,u.currentbin);var B=Math.min(a.length,i.length),q=[],H=0,V=B-1;for(n=0;n=H;n--)if(i[n]){V=n;break}for(n=H;n<=V;n++)if(r(a[n])&&r(i[n])){var U={p:a[n],s:i[n],b:0};u.enabled||(U.pts=w[n],N?U.p0=U.p1=w[n].length?v[w[n][0]]:a[n]:(U.p0=D(m[n]),U.p1=D(m[n+1],!0))),q.push(U)}return 1===q.length&&(q[0].width1=da.tickIncrement(q[0].p,g.size,!1,c)-q[0].p),ti(q,t),nt.isArrayOrTypedArray(t.selectedpoints)&&nt.tagSelected(q,t,F),q}},Op.setPositions=To,Op.plot=po,Op.style=Ro,Op.colorbar=qo,Op.hoverPoints=function(e,t,r,n){var a=ao(e,t,r,n);if(a){var i=(e=a[0]).cd[e.index],o=e.cd[0].trace;if(!o.cumulative.enabled){var l="h"===o.orientation?"y":"x";e[l+"Label"]=Sp(e[l+"a"],i.p0,i.p1)}return a}},Op.selectPoints=xo,Op.eventData=function(e,t,r,n,a){if(e.x="xVal"in t?t.xVal:t.x,e.y="yVal"in t?t.yVal:t.y,t.xa&&(e.xaxis=t.xa),t.ya&&(e.yaxis=t.ya),!(r.cumulative||{}).enabled){var i,o=Array.isArray(a)?n[0].pts[a[0]][a[1]]:n[a].pts;if(e.pointNumbers=o,e.binNumber=e.pointNumber,delete e.pointNumber,delete e.pointIndex,r._indexToPoints){i=[];for(var l=0;l1)){var u=nt.simpleMap(c.x,t.d2c,0,r.xcalendar),f=nt.distinctVals(u).minDiff;i=Math.min(i,f)}}for(i===1/0&&(i=1),o=0;o");w.push(o,o,o,o,o,o,null)},N=0;N0?1:-1)/2,y:i/(1+r*r/(n*n)),outside:!0}}var Kp={};Kp.attributes=qp,Kp.supplyDefaults=function(e,t,r,n){function a(r,n){return nt.coerce(e,t,qp,r,n)}var i=nt.coerceFont,o=a("values"),l=a("labels");if(!Array.isArray(l)){if(!nt.isArrayOrTypedArray(o)||!o.length)return void(t.visible=!1);a("label0"),a("dlabel")}a("marker.line.width")&&a("marker.line.color"),a("marker.colors"),a("scalegroup");var s=a("text"),c=a("textinfo",Array.isArray(s)?"text+percent":"percent");if(a("hovertext"),c&&"none"!==c){var u=a("textposition"),f=Array.isArray(u)||"auto"===u,d=f||"inside"===u,h=f||"outside"===u;if(d||h){var p=i(a,"textfont",n.font);d&&i(a,"insidetextfont",p),h&&i(a,"outsidetextfont",p)}}Xp(t,n,a),a("hole"),a("sort"),a("direction"),a("rotation"),a("pull")},Kp.supplyLayoutDefaults=function(e,t){var r,n;r="hiddenlabels",nt.coerce(e,t,Zp,r,n)},Kp.layoutAttributes=Zp,Kp.calc=function(e,t){var n,a,i,o,l,c=t.values,u=Up(c)&&c.length,f=t.labels,d=t.marker.colors||[],h=[],p=e._fullLayout,g=p.colorway,v=p._piecolormap,y={},m=0,x=p.hiddenlabels||[];if(p._piecolorway||g===xt.defaults||(p._piecolorway=Yp(g)),t.dlabel)for(f=new Array(c.length),n=0;n")}}return h},Kp.plot=function(t,r){var n=t._fullLayout;!function(e,t){var r,n,a,i,o,l,s,c,u,f=[];for(a=0;as&&(s=l.pull[i]);o.r=Math.min(r,n)/(2+2*s),o.cx=t.l+t.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=t.t+t.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;ia.vTotal/2?1:0)}(r),a.each(function(){var a=e.select(this).selectAll("g.slice").data(r);a.enter().append("g").classed("slice",!0),a.exit().remove();var l=[[[],[]],[[],[]]],s=!1;a.each(function(r){if(r.hidden)e.select(this).selectAll("path,g").remove();else{r.pointNumber=r.i,r.curveNumber=o.index,l[r.pxmid[1]<0?0:1][r.pxmid[0]<0?0:1].push(r);var a=i.cx,c=i.cy,u=e.select(this),f=u.selectAll("path.surface").data([r]),d=!1,h=!1;if(f.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),u.select("path.textline").remove(),u.on("mouseover",function(){var l=t._fullLayout,s=t._fullData[o.index];if(!t._dragging&&!1!==l.hovermode){var u=s.hoverinfo;if(Array.isArray(u)&&(u=to.castHoverinfo({hoverinfo:[Js.castOption(u,r.pts)],_module:o._module},l,0)),"all"===u&&(u="label+text+value+percent+name"),"none"!==u&&"skip"!==u&&u){var f=Jp(r,i),p=a+r.pxmid[0]*(1-f),g=c+r.pxmid[1]*(1-f),v=n.separators,y=[];if(-1!==u.indexOf("label")&&y.push(r.label),-1!==u.indexOf("text")){var m=Js.castOption(s.hovertext||s.text,r.pts);m&&y.push(m)}-1!==u.indexOf("value")&&y.push(Js.formatPieValue(r.v,v)),-1!==u.indexOf("percent")&&y.push(Js.formatPiePercent(r.v/i.vTotal,v));var x=o.hoverlabel,b=x.font;to.loneHover({x0:p-f*i.r,x1:p+f*i.r,y:g,text:y.join("
"),name:-1!==u.indexOf("name")?s.name:void 0,idealAlign:r.pxmid[0]<0?"left":"right",color:Js.castOption(x.bgcolor,r.pts)||r.color,borderColor:Js.castOption(x.bordercolor,r.pts),fontFamily:Js.castOption(b.family,r.pts),fontSize:Js.castOption(b.size,r.pts),fontColor:Js.castOption(b.color,r.pts)},{container:l._hoverlayer.node(),outerContainer:l._paper.node(),gd:t}),d=!0}t.emit("plotly_hover",{points:[Qp(r,s)],event:e.event}),h=!0}}).on("mouseout",function(n){var a=t._fullLayout,i=t._fullData[o.index];h&&(n.originalEvent=e.event,t.emit("plotly_unhover",{points:[Qp(r,i)],event:e.event}),h=!1),d&&(to.loneUnhover(a._hoverlayer.node()),d=!1)}).on("click",function(){var n=t._fullLayout,a=t._fullData[o.index];t._dragging||!1===n.hovermode||(t._hoverdata=[Qp(r,a)],to.click(t,e.event))}),o.pull){var p=+Js.castOption(o.pull,r.pts)||0;p>0&&(a+=p*r.pxmid[0],c+=p*r.pxmid[1])}r.cxFinal=a,r.cyFinal=c;var g=o.hole;if(r.v===i.vTotal){var v="M"+(a+r.px0[0])+","+(c+r.px0[1])+_(r.px0,r.pxmid,!0,1)+_(r.pxmid,r.px0,!0,1)+"Z";g?f.attr("d","M"+(a+g*r.px0[0])+","+(c+g*r.px0[1])+_(r.px0,r.pxmid,!1,g)+_(r.pxmid,r.px0,!1,g)+"Z"+v):f.attr("d",v)}else{var y=_(r.px0,r.px1,!0,1);if(g){var m=1-g;f.attr("d","M"+(a+g*r.px1[0])+","+(c+g*r.px1[1])+_(r.px1,r.px0,!1,g)+"l"+m*r.px0[0]+","+m*r.px0[1]+y+"Z")}else f.attr("d","M"+a+","+c+"l"+r.px0[0]+","+r.px0[1]+y+"Z")}var x=Js.castOption(o.textposition,r.pts),b=u.selectAll("g.slicetext").data(r.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var n=e.select(this).selectAll("text").data([0]);n.enter().append("text").attr("data-notex",1),n.exit().remove(),n.text(r.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Ur.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(mr.convertToTspans,t);var l,u=Ur.bBox(n.node());"outside"===x?l=$p(u,r):(l=function(e,t,r){var n=Math.sqrt(e.width*e.width+e.height*e.height),a=e.width/e.height,i=Math.PI*Math.min(t.v/r.vTotal,.5),o=1-r.trace.hole,l=Jp(t,r),s={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),f={scale:2*u/e.height,rCenter:Math.cos(u/r.r)-u*a/r.r,rotate:(180/Math.PI*t.midangle+720)%180-90},d=1/a,h=d+1/(2*Math.tan(i)),p=r.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(d*d+o/2)+d)),g={scale:2*p/e.width,rCenter:Math.cos(p/r.r)-p/a/r.r,rotate:(180/Math.PI*t.midangle+810)%180-90},v=g.scale>f.scale?g:f;return s.scale<1&&v.scale>s.scale?v:s}(u,r,i),"auto"===x&&l.scale<1&&(n.call(Ur.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(u=Ur.bBox(n.node())),l=$p(u,r)));var f=a+r.pxmid[0]*l.rCenter+(l.x||0),d=c+r.pxmid[1]*l.rCenter+(l.y||0);l.outside&&(r.yLabelMin=d-u.height/2,r.yLabelMid=d,r.yLabelMax=d+u.height/2,r.labelExtraX=0,r.labelExtraY=0,s=!0),n.attr("transform","translate("+f+","+d+")"+(l.scale<1?"scale("+l.scale+")":"")+(l.rotate?"rotate("+l.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function _(e,t,n,a){return"a"+a*i.r+","+a*i.r+" 0 "+r.largeArc+(n?" 1 ":" 0 ")+a*(t[0]-e[0])+","+a*(t[1]-e[1])}}),s&&function(e,t){var r,n,a,i,o,l,s,c,u,f,d,h,p;function g(e,t){return e.pxmid[1]-t.pxmid[1]}function v(e,t){return t.pxmid[1]-e.pxmid[1]}function y(e,r){r||(r={});var a,c,u,d,h,p,g=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),v=n?e.yLabelMin:e.yLabelMax,y=n?e.yLabelMax:e.yLabelMin,m=e.cyFinal+o(e.px0[1],e.px1[1]),x=g-v;if(x*s>0&&(e.labelExtraY=x),Array.isArray(t.pull))for(c=0;c=(Js.castOption(t.pull,u.pts)||0)||((e.pxmid[1]-u.pxmid[1])*s>0?(d=u.cyFinal+o(u.px0[1],u.px1[1]),(x=d-v-e.labelExtraY)*s>0&&(e.labelExtraY+=x)):(y+e.labelExtraY-m)*s>0&&(a=3*l*Math.abs(c-f.indexOf(e)),h=u.cxFinal+i(u.px0[0],u.px1[0]),(p=h+a-(e.cxFinal+e.pxmid[0])-e.labelExtraX)*l>0&&(e.labelExtraX+=p)))}for(n=0;n<2;n++)for(a=n?g:v,o=n?Math.max:Math.min,s=n?1:-1,r=0;r<2;r++){for(i=r?Math.max:Math.min,l=r?1:-1,(c=e[n][r]).sort(a),u=e[1-n][r],f=u.concat(c),h=[],d=0;dMath.abs(c)?i+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):i+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else i+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;r.append("path").classed("textline",!0).call(xt.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:i,fill:"none"})}})})}),setTimeout(function(){a.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},Kp.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var r=t[0].trace,n=e.select(this);n.style({opacity:r.opacity}),n.selectAll("path.surface").each(function(t){e.select(this).call(Ks,t,r)})})},Kp.styleOne=Ks,Kp.moduleType="trace",Kp.name="pie",Kp.basePlotModule=Hp,Kp.categories=["pie","showLegend"],Kp.meta={};var eg=Kp;return ap.register([Vo,Pp,eg,Rp,Dl]),ap}); \ No newline at end of file +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},n=[].slice,r=function(e){return n.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{r(a.documentElement.childNodes)[0].nodeType}catch(e){r=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,n){c.call(this,e,t,n+"")},u.setProperty=function(e,t,n){f.call(this,e,t+"",n)}}function d(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},t.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},t.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,n){return d(e(t),n)}:e)},t.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},t.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},t.pairs=function(e){for(var t=0,n=e.length-1,r=e[0],a=new Array(n<0?0:n);t=0;)for(t=(r=e[a]).length;--t>=0;)n[--o]=r[t];return n};var m=Math.abs;function x(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n==1/0)throw new Error("infinite range");var r,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(n)),o=-1;if(e*=i,t*=i,(n*=i)<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=a.length)return n?n.call(r,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var r=[],o=i[n++];return t.forEach(function(t,a){r.push({key:t,values:e(a,n)})}),o?r.sort(function(e,t){return o(e.key,t.key)}):r}(o(t.map,e,0),0)},r.key=function(e){return a.push(e),r},r.sortKeys=function(e){return i[a.length-1]=e,r},r.sortValues=function(t){return e=t,r},r.rollup=function(e){return n=e,r},r},t.set=function(e){var t=new O;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},t.event=null,t.requote=function(e){return e.replace(H,"\\$&")};var H=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]};function V(e){return q(e,X),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var n=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}X.select=function(e){var t,n,r,a,i=[];e=Z(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),J.hasOwnProperty(n)?{space:J[n],local:e}:e}},X.attr=function(e,n){if(arguments.length<2){if("string"==typeof e){var r=this.node();return(e=t.ns.qualify(e)).local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}for(n in e)this.each($(n,e[n]));return this}return this.each($(e,n))},X.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=te(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},X.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?n?function(){var t=l(n,r(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:c:n?N:function(){var n,r=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(n=a.match(r)){var i=this[a];this.removeEventListener(n[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=X.append,de.empty=X.empty,de.node=X.node,de.call=X.call,de.size=X.size,de.select=function(e){for(var t,n,r,a,i,o=[],l=-1,s=this.length;++l=r&&(r=t+1);!(o=l[r])&&++r0?1:e<0?-1:0}function ze(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function De(e){return e>1?0:e<-1?Te:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Ne(e){return((e=Math.exp(e))+1/e)/2}function Ie(e){return(e=Math.sin(e/2))*e}var Re=Math.SQRT2;t.interpolateZoom=function(e,t){var n,r,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function O(e){--v||(e({type:"zoomend"}),n=null)}function P(){var e=this,n=_.of(e,arguments),r=0,a=t.select(o(e)).on(m,function(){r=1,T(t.mouse(e),i),S(n)}).on(x,function(){a.on(m,null).on(x,null),l(r),O(n)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(n)}function z(){var e,n=this,r=_.of(n,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(n),h=xe(n);function p(){var r=t.touches(n);return e=d.k,r.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),r}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var r=t.event.changedTouches,o=0,f=r.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(n);ll.call(n);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?r+(a-r)*e/60:e<180?a:e<240?r+(a-r)*(240-e)/60:r}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,r=2*(n=n<0?0:n>1?1:n)-(a=n<=.5?n*(1+t):n+t-n*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,n,r){return this instanceof Ge?(this.h=+e,this.c=+n,void(this.l=+r)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Ze?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,n,r)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new qe(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new He;function Xe(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Ze(n,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Ze(e,t,n){return this instanceof Ze?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof Ze?new Ze(e.l,e.a,e.b):e instanceof Ge?Xe(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Ze(e,t,n)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Xe(this.h,this.c,this.l).rgb()},t.lab=Ze;var We=18,Qe=.95047,Je=1,$e=1.08883,Ke=Ze.prototype=new He;function et(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return new it(at(3.2404542*(a=nt(a)*Qe)-1.5371385*(r=nt(r)*Je)-.4985314*(i=nt(i)*$e)),at(-.969266*a+1.8760108*r+.041556*i),at(.0556434*a-.2040259*r+1.0572252*i))}function tt(e,t,n){return e>0?new Ge(Math.atan2(n,t)*Oe,Math.sqrt(t*t+n*n),e):new Ge(NaN,NaN,e)}function nt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function rt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,n){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,n)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Ze(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Ze(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new He;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new qe(r,a,s)}function dt(e,t,n){var r=rt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(n=ht(n)))/Qe),a=rt((.2126729*e+.7151522*t+.072175*n)/Je);return Ze(116*a-16,500*(r-a),200*(a-rt((.0193339*e+.119192*t+.9503041*n)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,a=30;return t||n||r?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var n=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=n}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(n=null==e?null:e+"",o):n},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),c.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=n&&c.overrideMimeType&&c.overrideMimeType(n),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==r?null:r),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(P),t.dsv=function(e,t){var n=new RegExp('["'+e+"\n]"),r=e.charCodeAt(0);function a(e,n,r){arguments.length<3&&(r=n,n=null);var a=mt(e,t,null==n?i:o(n),r);return a.row=function(e){return arguments.length?a.response(null==(n=e)?i:o(e)):n},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return n.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var n;return a.parseRows(e,function(e,r){if(n)return n(e,r-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(a(e),n)}:a})},a.parseRows=function(e,t){var n,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(Tt,t)),_t=0):(_t=1,kt(Tt))}function At(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}});t.formatPrefix=function(e,n){var r=0;return(e=+e)&&(e<0&&(e*=-1),n&&(e=t.round(e,Ct(e,n))),r=1+Math.floor(1e-12+Math.log(e)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),St[8+r/3]};var Ot=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pt=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,n){return(e=t.round(e,Ct(e,n))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),n))))}});function zt(e){return e+""}var Dt=t.time={},Et=Date;function Nt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Nt.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(){It.setUTCDate.apply(this._,arguments)},setDay:function(){It.setUTCDay.apply(this._,arguments)},setFullYear:function(){It.setUTCFullYear.apply(this._,arguments)},setHours:function(){It.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){It.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){It.setUTCMinutes.apply(this._,arguments)},setMonth:function(){It.setUTCMonth.apply(this._,arguments)},setSeconds:function(){It.setUTCSeconds.apply(this._,arguments)},setTime:function(){It.setTime.apply(this._,arguments)}};var It=Date.prototype;function Rt(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o68?1900:2e3),n+a[0].length):-1}function Qt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Jt(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function $t(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Kt(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function en(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function tn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function nn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function rn(e,t,n){jt.lastIndex=0;var r=jt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function an(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=m(t)/60|0,a=m(t)%60;return n+qt(r,"0",2)+qt(a,"0",2)}function on(e,t,n){Ht.lastIndex=0;var r=Ht.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ln(e){for(var t=e.length,n=-1;++n0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(n-=l,n+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(r)}:P;return function(e){var r=Ot.exec(e),a=r[1]||" ",l=r[2]||">",s=r[3]||"-",c=r[4]||"",u=r[5],f=+r[6],d=r[7],h=r[8],p=r[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=Pt.get(p)||zt;var b=u&&d;return function(e){var r=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),r=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=n+e.substring(k+1);!u&&d&&(_=o(_,1/0));var T=v.length+_.length+w.length+(b?0:i.length),A=T"===l?A+i+e:"^"===l?A.substring(0,T>>=1)+i+e+A.substring(T):i+(b?e:A+e))+r}}}(e),timeFormat:function(e){var n=e.dateTime,r=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function n(n){for(var r,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in Bt?t.charAt(l++):o])||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}u.utc=function(e){var t=u(e);function n(e){try{var n=new(Et=Nt);return n._=e,t(n)}finally{Et=Date}}return n.parse=function(e){try{Et=Nt;var n=t.parse(e);return n&&n._}finally{Et=Date}},n.toString=t.toString,n},u.multi=u.utc.multi=ln;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(n),d:function(e,t){return qt(e.getDate(),t,2)},e:function(e,t){return qt(e.getDate(),t,2)},H:function(e,t){return qt(e.getHours(),t,2)},I:function(e,t){return qt(e.getHours()%12||12,t,2)},j:function(e,t){return qt(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return qt(e.getMilliseconds(),t,3)},m:function(e,t){return qt(e.getMonth()+1,t,2)},M:function(e,t){return qt(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return qt(e.getSeconds(),t,2)},U:function(e,t){return qt(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return qt(Dt.mondayOfYear(e),t,2)},x:u(r),X:u(a),y:function(e,t){return qt(e.getFullYear()%100,t,2)},Y:function(e,t){return qt(e.getFullYear()%1e4,t,4)},Z:an,"%":function(){return"%"}},w={a:function(e,t,n){g.lastIndex=0;var r=g.exec(t.slice(n));return r?(e.w=v.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(e,t,n){h.lastIndex=0;var r=h.exec(t.slice(n));return r?(e.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.m=m.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(e,t,n){return f(e,_.c.toString(),t,n)},d:$t,e:$t,H:en,I:en,j:Kt,L:rn,m:Jt,M:tn,p:function(e,t,n){var r=d.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)},S:nn,U:Yt,w:Gt,W:Xt,x:function(e,t,n){return f(e,_.x.toString(),t,n)},X:function(e,t,n){return f(e,_.X.toString(),t,n)},y:Wt,Y:Zt,Z:Qt,"%":on};return u}(e)}};var sn=t.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"]});function cn(){}t.format=sn.numberFormat,t.geo={},cn.prototype={s:0,t:0,add:function(e){fn(e,this.t,un),fn(un.s,this.s,this),this.s?this.t+=un.t:this.s=un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var un=new cn;function fn(e,t,n){var r=n.s=e+t,a=r-e,i=r-a;n.t=e-i+(t-a)}function dn(e,t){e&&pn.hasOwnProperty(e.type)&&pn[e.type](e,t)}t.geo.stream=function(e,t){e&&hn.hasOwnProperty(e.type)?hn[e.type](e,t):dn(e,t)};var hn={Feature:function(e,t){dn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++r=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=r*s+u*Math.cos(l),d=u*o*Math.sin(l);Sn.add(Math.atan2(d,f)),n=e,r=s,a=c}On.point=function(o,l){On.point=i,n=(e=o)*Se,r=Math.cos(l=(t=l)*Se/2+Te/4),a=Math.sin(l)},On.lineEnd=function(){i(e,t)}}function zn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function Dn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function En(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Nn(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function In(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Rn(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Fn(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function Bn(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(n=-90),f[0]=e,f[1]=r}};function h(t,i){u.push(f=[e=t,r=t]),ia&&(a=i)}function p(t,o){var l=zn([t*Se,o*Se]);if(s){var c=En(s,l),u=En([c[1],-c[0],0],c);Rn(u),u=Fn(u);var f=t-i,d=f>0?1:-1,p=u[0]*Oe*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t):r>=e?(tr&&(r=t)):t>i?_(e,t)>_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=r,d.point=h,s=null}function y(e,t){if(s){var n=e-i;c+=m(n)>180?n+(n>0?360:-360):n}else o=e,l=t;On.point(e,t),p(e,t)}function x(){On.lineStart()}function b(){y(o,l),On.lineEnd(),m(c)>ke&&(e=-(r=180)),f[0]=e,f[1]=r,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],r=g[1])}return u=f=null,e===1/0||n===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,n],[r,a]]}}(),t.geo.centroid=function(e){mn=xn=bn=_n=wn=kn=Mn=Tn=An=Ln=Cn=0,t.geo.stream(e,jn);var n=An,r=Ln,a=Cn,i=n*n+r*r+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else r(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Wn(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r=0?1:-1,k=w*_,M=k>Te,T=p*x;if(Sn.add(Math.atan2(T*w*Math.sin(k),g*b+T*Math.cos(k))),i+=M?_+w*Ae:_,M^d>=n^y>=n){var A=En(zn(f),zn(e));Rn(A);var L=En(a,A);Rn(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(r>C||r===C&&(A[0]||A[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&n.push(n.pop().concat(n.shift())),l.push(n.filter($n))}return u}}function $n(e){return e.length>1}function Kn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:N,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function er(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var tr=Jn(Xn,function(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Te:-Te,s=m(i-n);m(s-Te)0?Ce:-Ce),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Te&&(m(n-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}(n,r,i,o),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),t=0),e.point(n=i,r=o),a=l},lineEnd:function(){e.lineEnd(),n=r=NaN},clean:function(){return 2-t}}},function(e,t,n,r){var a;if(null==e)a=n*Ce,r.point(-Te,a),r.point(0,a),r.point(Te,a),r.point(Te,0),r.point(Te,-a),r.point(0,-a),r.point(-Te,-a),r.point(-Te,0),r.point(-Te,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rr=1e9;function ar(e,n,r,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=Kn(),w=nr(e,n,r,a),k={point:A,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=A,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var n=function(e){for(var t=0,n=u.length,r=e[1],a=0;ar&&ze(c,i,e)>0&&++t:i[1]<=r&&ze(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),r=x&&n,i=c.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Zn(c,o,n,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:r,u>1?a:n)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function T(t,i){return e<=t&&t<=r&&n<=i&&i<=a}function A(e,t){T(e,t)&&s.point(e,t)}function L(e,t){var n=T(e=Math.max(-rr,Math.min(rr,e)),t=Math.max(-rr,Math.min(rr,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=n,m=!1,n&&(s.lineStart(),s.point(e,t));else if(n&&y)s.point(e,t);else{var r={a:{x:g,y:v},b:{x:e,y:t}};w(r)?(y||(s.lineStart(),s.point(r.a.x,r.a.y)),s.point(r.b.x,r.b.y),n||s.lineEnd(),x=!1):n&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=n}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-r)0?2:1:m(t[1]-n)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}}function ir(e){var t=0,n=Te/3,r=Lr(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Te/180,n=e[1]*Te/180):[t/Te*180,n/Te*180]},a}function or(e,t){var n=Math.sin(e),r=(n+Math.sin(t))/2,a=1+n*(2*r-n),i=Math.sqrt(a)/r;function o(e,t){var n=Math.sqrt(a-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),i-n*Math.cos(e)]}return o.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,Ee((a-(e*e+n*n)*r*r)/(2*r))]},o}t.geo.clipExtent=function(){var e,t,n,r,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=ar(e=+l[0][0],t=+l[0][1],n=+l[1][0],r=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return ir(or)}).raw=or,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,n,r,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,n){e=[t,n]}};function c(t){var i=t[0],o=t[1];return e=null,n(i,o),e||(r(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),n=i.translate(),r=(e[0]-n[0])/t,a=(e[1]-n[1])/t;return(a>=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return n=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,r=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var lr,sr,cr,ur,fr,dr,hr={point:N,lineStart:N,lineEnd:N,polygonStart:function(){sr=0,hr.lineStart=pr},polygonEnd:function(){hr.lineStart=hr.lineEnd=hr.point=N,lr+=m(sr/2)}};function pr(){var e,t,n,r;function a(e,t){sr+=r*e-n*t,n=e,r=t}hr.point=function(i,o){hr.point=a,e=n=i,t=r=o},hr.lineEnd=function(){a(e,t)}}var gr={point:function(e,t){efr&&(fr=e);tdr&&(dr=t)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vr(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yr,mr={point:xr,lineStart:br,lineEnd:_r,polygonStart:function(){mr.lineStart=wr},polygonEnd:function(){mr.point=xr,mr.lineStart=br,mr.lineEnd=_r}};function xr(e,t){bn+=e,_n+=t,++wn}function br(){var e,t;function n(n,r){var a=n-e,i=r-t,o=Math.sqrt(a*a+i*i);kn+=o*(e+n)/2,Mn+=o*(t+r)/2,Tn+=o,xr(e=n,t=r)}mr.point=function(r,a){mr.point=n,xr(e=r,t=a)}}function _r(){mr.point=xr}function wr(){var e,t,n,r;function a(e,t){var a=e-n,i=t-r,o=Math.sqrt(a*a+i*i);kn+=o*(n+e)/2,Mn+=o*(r+t)/2,Tn+=o,An+=(o=r*e-n*t)*(n+e),Ln+=o*(r+t),Cn+=3*o,xr(n=e,r=t)}mr.point=function(i,o){mr.point=a,xr(e=n=i,t=r=o)},mr.lineEnd=function(){a(e,t)}}function kr(e){var t=.5,n=Math.cos(30*Se),r=16;function a(t){return(r?function(t){var n,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(n,r){n=e(n,r),t.point(n[0],n[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(n,a){var o=zn([n,a]),l=e(n,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=n,h=o[0],p=o[1],g=o[2],r,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(n=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,n,l,s,c,r,t),v.lineEnd=b,b()}return v}:function(t){return Tr(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})})(t)}function i(r,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-r,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,T=Math.sqrt(w*w+k*k+M*M),A=Math.asin(M/=T),L=m(m(M)-1)t||m((x*P+b*z)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mr(e){this.stream=e}function Tr(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Ar(e){return Lr(function(){return e})()}function Lr(e){var n,r,a,i,o,l,s=kr(function(e,t){return[(e=n(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=tr,x=P,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Oe,e[1]*Oe]}function M(){a=Yn(r=Pr(p,g,v),n);var e=n(d,h);return i=u-e[0]*c,o=f+e[1]*c,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cr(y(r,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,tr):function(e){var t=Math.cos(e),n=t>0,r=m(t)>ke;return Jn(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=n?g?0:o(f,d):g?o(f+(f<0?Te:-Te),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(Bn(t,h)||Bn(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(r&&t&&n^g){var y;v&l||!(y=i(p,t,!0))||(u=0,n?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&Bn(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Nr(e,6*Se),n?[0,-e]:[-Te,e-Te]);function a(e,n){return Math.cos(e)*Math.cos(n)>t}function i(e,n,r){var a=[1,0,0],i=En(zn(e),zn(n)),o=Dn(i,i),l=i[0],s=o-l*l;if(!s)return!r&&e;var c=t*o/s,u=-t*l/s,f=En(a,i),d=In(a,c);Nn(d,In(i,u));var h=f,p=Dn(d,h),g=Dn(h,h),v=p*p-g*(Dn(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=In(h,(-p-y)/g);if(Nn(x,d),x=Fn(x),!r)return x;var b,_=e[0],w=n[0],k=e[1],M=n[1];w<_&&(b=_,_=w,w=b);var T=w-_,A=m(T-Te)0^x[1]<(m(x[0]-_)Te^(_<=x[0]&&x[0]<=w)){var L=In(h,(-p+y)/g);return Nn(L,d),[x,Fn(L)]}}}function o(t,r){var a=n?e:Te-e,i=0;return t<-a?i|=1:t>a&&(i|=2),r<-a?i|=4:r>a&&(i|=8),i}}((b=+e)*Se),T()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?ar(e[0][0],e[0][1],e[1][0],e[1][1]):P,T()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Se,h=e[1]%360*Se,M()):[d*Oe,h*Oe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*Oe,g*Oe,v*Oe]},t.rebind(w,s,"precision"),function(){return n=e.apply(this,arguments),w.invert=n.invert&&k,M()}}function Cr(e){return Tr(e,function(t,n){e.point(t*Se,n*Se)})}function Sr(e,t){return[e,t]}function Or(e,t){return[e>Te?e-Ae:e<-Te?e+Ae:e,t]}function Pr(e,t,n){return e?t||n?Yn(Dr(e),Er(t,n)):Dr(e):t||n?Er(t,n):Or}function zr(e){return function(t,n){return[(t+=e)>Te?t-Ae:t<-Te?t+Ae:t,n]}}function Dr(e){var t=zr(e);return t.invert=zr(-e),t}function Er(e,t){var n=Math.cos(e),r=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*n+l*r;return[Math.atan2(s*a-u*i,l*n-c*r),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*n+u*r),Ee(u*n-l*r)]},o}function Nr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=Ir(n,a),i=Ir(n,i),(o>0?ai)&&(a+=o*Ae)):(a=e+o*Ae,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=Oe,t[1]*=Oe,t},t},Or.invert=Sr,t.geo.circle=function(){var e,t,n=[0,0],r=6;function a(){var e="function"==typeof n?n.apply(this,arguments):n,r=Pr(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=r(e,t)),e[0]*=Oe,e[1]*=Oe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(n=e,a):n},a.angle=function(n){return arguments.length?(t=Nr((e=+n)*Se,r*Se),a):e},a.precision=function(n){return arguments.length?(t=Nr(e*Se,(r=+n)*Se),a):r},a.angle(90)},t.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((n=f*o)*n+(n=c*u-s*f*l)*n),s*u+c*f*l)},t.geo.graticule=function(){var e,n,r,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,r,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(n/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(r).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],r=+e[1][0],s=+e[0][1],l=+e[1][1],a>r&&(e=a,a=r,r=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[r,l]]},x.minorExtent=function(t){return arguments.length?(n=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],n>e&&(t=n,n=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[n,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Rr(o,i,90),u=Fr(n,e,y),f=Rr(s,l,90),d=Fr(a,r,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,n,r=Br,a=jr;function i(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||r.apply(this,arguments),n||a.apply(this,arguments))},i.source=function(t){return arguments.length?(r=t,e="function"==typeof t?null:t,i):r},i.target=function(e){return arguments.length?(a=e,n="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return n=e[0]*Se,r=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(r),l=Math.sin(r),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(n),f=o*Math.sin(n),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ie(i-r)+o*s*Ie(a-n))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,n=Math.sin(p-e)*g,r=n*u+t*d,a=n*f+t*h,i=n*l+t*c;return[Math.atan2(a,r)*Oe,Math.atan2(i,Math.sqrt(r*r+a*a))*Oe]}:function(){return[n*Oe,r*Oe]}).distance=p,v;var n,r,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yr=0,t.geo.stream(e,Hr),yr};var Hr={sphere:N,point:N,lineStart:function(){var e,t,n;function r(r,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((r*=Se)-e),s=Math.cos(l);yr+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=n*i-t*o*s)*l),t*i+n*o*s),e=r,t=i,n=o}Hr.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),n=Math.cos(i),Hr.point=r},Hr.lineEnd=function(){Hr.point=Hr.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function qr(e,t){function n(t,n){var r=Math.cos(t),a=Math.cos(n),i=e(r*a);return[i*a*Math.sin(t),i*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),a=t(r),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,r*o),Math.asin(r&&n*i/r)]},n}var Vr=qr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Ar(Vr)}).raw=Vr;var Ur=qr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},P);function Gr(e,t){var n=Math.cos(e),r=function(e){return Math.tan(Te/4+e/2)},a=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),i=n*Math.pow(r(e),a)/a;if(!a)return Zr;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var n=i/Math.pow(r(t),a);return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}return o.invert=function(e,t){var n=i-t,r=Pe(a)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/a,2*Math.atan(Math.pow(i/r,1/a))-Ce]},o}function Yr(e,t){var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),a=n/r+e;if(m(r)1&&ze(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function na(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Ar(Jr)}).raw=Jr,$r.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wr($r),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):[(e=n())[0],e[1],e[2]-90]},n([0,0,90])}).raw=$r,t.geom={},t.geom.hull=function(e){var t=Kr,n=ea;if(arguments.length)return r(e);function r(e){if(e.length<3)return[];var r,a=vt(t),i=vt(n),o=e.length,l=[],s=[];for(r=0;r=0;--r)h.push(e[l[c[r]][2]]);for(r=+f;rke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){r>-ke?(t=l.P,n=l):a>-ke?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||n){if(t===n)return ka(t),n=pa(t.site),ca.insert(s,n),s.edge=n.edge=Aa(t.site,s.site),wa(t),void wa(n);if(n){ka(t),ka(n);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=n.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(n.edge,c,p,b),s.edge=Aa(c,e,null,b),n.edge=Aa(e,p,null,b),wa(t),wa(n)}else s.edge=Aa(t.site,s.site)}}function ma(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-1/0;var l=(n=o.site).x,s=n.y,c=s-t;if(!c)return l;var u=l-r,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+r:(r+l)/2}function xa(e,t){var n=e.N;if(n)return ma(n,t);var r=e.site;return r.y===t?r.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,a=e.site,i=n.site;if(r!==i){var o=a.x,l=a.y,s=r.x-o,c=r.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){Oa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};n={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/r,y:s};n={x:(c-a)/r,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xke||m(a-n)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(r-f)ke?{x:f,y:m(t-f)ke?{x:m(n-p)ke?{x:d,y:m(t-d)ke?{x:m(n-h)=n&&c.x<=a&&c.y>=r&&c.y<=o?[[n,o],[a,o],[a,r],[n,r]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(n,r){for(var a,i,o,l,s=n.site,c=n.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:Ha(n,r)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,n,r,a,i,o,l){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-n)+m(c-r)<.01)T(e,t,n,r,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,T(e,u,s,c,a,i,o,l),T(e,t,n,r,a,i,o,l)}else e.x=n,e.y=r,e.point=t}else T(e,t,n,r,a,i,o,l)}function T(e,t,n,r,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=n>=s,f=r>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,n,r,a,i,o,l)}w>k?v=p+w:g=h+k;var A={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(A,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(A.visit=function(e){!function e(t,n,r,a,i,o){if(!t(n,r,a,i,o)){var l=.5*(r+i),s=.5*(a+o),c=n.nodes;c[0]&&e(t,c[0],r,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],r,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,A,h,p,g,v)},A.find=function(e){return function(e,t,n,r,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(r=t.interpolators[a](e,n)););return r}function Ya(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ni(e){return Math.pow(2,10*(e-1))}function ri(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function oi(e){var t,n,r,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(r=-l)*(n=a)[0],t[1]+=r*n[1],t))||0;a[0]*i[1]=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"in";return a=Za.get(a)||Xa,i=Wa.get(i)||P,t=i(a.apply(null,n.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,n){e=t.hcl(e),n=t.hcl(n);var r=e.h,a=e.c,i=e.l,o=n.h-r,l=n.c-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.c:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Xe(r+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,n){e=t.hsl(e),n=t.hsl(n);var r=e.h,a=e.s,i=e.l,o=n.h-r,l=n.s-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.s:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(r+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,n){e=t.lab(e),n=t.lab(n);var r=e.l,a=e.a,i=e.b,o=n.l-r,l=n.a-a,s=n.b-i;return function(e){return et(r+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var n=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,n){var r=[],a=[];return e=t.transform(e),n=t.transform(n),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push("translate(",null,",",null,")");r.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else(t[0]||t[1])&&n.push("translate("+t+")")}(e.translate,n.translate,r,a),function(e,t,n,r){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(ui(n)+"rotate(",null,")")-2,x:Ha(e,t)})):t&&n.push(ui(n)+"rotate("+t+")")}(e.rotate,n.rotate,r,a),function(e,t,n,r){e!==t?r.push({i:n.push(ui(n)+"skewX(",null,")")-2,x:Ha(e,t)}):t&&n.push(ui(n)+"skewX("+t+")")}(e.skew,n.skew,r,a),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(ui(n)+"scale(",null,",",null,")");r.push({i:a-4,x:Ha(e[0],t[0])},{i:a-2,x:Ha(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(ui(n)+"scale("+t+")")}(e.scale,n.scale,r,a),e=n=null,function(e){for(var t,n=-1,i=a.length;++n0?r=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:r=0})):t>0&&(s.start({type:"start",alpha:r=t}),e=Mt(l.tick)),l):r},l.start=function(){var e,t,n,r=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)n.push(a[r])}function Ti(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;n&&(i.value=0),i.children=c}else n&&(i.value=+n.call(r,i,i.depth)||0),delete i.children;return Ti(a,function(t){var r,a;e&&(r=t.children)&&r.sort(e),n&&(a=t.parent)&&(a.value+=t.value)}),l}return r.sort=function(t){return arguments.length?(e=t,r):e},r.children=function(e){return arguments.length?(t=e,r):t},r.value=function(e){return arguments.length?(n=e,r):n},r.revalue=function(e){return n&&(Mi(e,function(e){e.children&&(e.value=0)}),Ti(e,function(e){var t;e.children||(e.value=+n.call(r,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},r},t.layout.partition=function(){var e=t.layout.hierarchy(),n=[1,1];function r(t,r){var a=e.call(this,t,r);return function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(r=t.value?r/t.value:0;++cl&&(l=r),o.push(r)}for(n=0;na&&(r=n,a=t);return r}function Bi(e){return e.reduce(ji,0)}function ji(e,t){return e+t[1]}function Hi(e,t){return qi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function qi(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Xi(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function Zi(e){if((t=e.children)&&(s=t.length)){var t,n,r,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(n=t[0]).x=-n.r,n.y=0,x(n),s>1&&((r=t[1]).x=r.r,r.y=0,x(r),s>2))for(Ji(n,r,a=t[2]),x(a),Gi(n,a),n._pack_prev=a,Gi(a,r),r=n._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(n=e,i):n},i.range=function(e){return arguments.length?(r=vt(e),i):r},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return qi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,n=t.layout.hierarchy().sort(Ui),r=0,a=[1,1];function i(t,i){var o=n.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ti(l,function(e){e.r=+u(e.value)}),Ti(l,Zi),r){var f=r*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ti(l,function(e){e.r+=f}),Ti(l,Zi),Ti(l,function(e){e.r-=f})}return function e(t,n,r,a){var i=t.children;t.x=n+=a*t.x;t.y=r+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=n(d,h)/2-d.x,v=r[0]/(h.x+n(h,d)/2+g),y=r[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,r=e.parent.children,a=e.i?r[e.i-1]:null;if(t.length){!function(e){var t,n=0,r=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=n,t.m+=n,n+=t.s+(r+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+n(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+n(e._,a._));e.parent.A=function(e,t,r){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+n(l._,i._))>0&&(to(no(l,e,r),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,r=e)}return r}(e,a,e.parent.A||r[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=r[0],e.y=e.depth*r[1]}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e)?s:null,i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null==(r=e)?null:s,i):a?r:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),n=$i,r=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ti(c,function(e){var r=e.children;r&&r.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(r),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(r)):(e.x=l?u+=n(e,l):0,e.y=0,l=e)});var f=function e(t){var n=t.children;return n&&n.length?e(n[0]):t}(c),d=function e(t){var n,r=t.children;return r&&(n=r.length)?e(r[n-1]):t}(c),h=f.x-n(f,d)/2,p=d.x+n(d,f)/2;return Ti(c,a?function(e){e.x=(e.x-c.x)*r[0],e.y=(c.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(c.y?e.y/c.y:1))*r[1]}),s}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e),i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null!=(r=e),i):a?r:null},ki(i,e)},t.layout.treemap=function(){var e,n=t.layout.hierarchy(),r=Math.round,a=[1,1],i=null,o=ro,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var n,r,a=-1,i=e.length;++a0;)l.push(n=c[a-1]),l.area+=n.area,"squarify"!==s||(r=h(l,g))<=d?(c.pop(),d=r):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var n,r=o(e),a=t.slice(),i=[];for(u(a,r.dx*r.dy/e.value),i.area=0;n=a.pop();)i.push(n),i.area+=n.area,null!=n.z&&(p(i,n.z?r.dx:r.dy,r,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return t*=t,(r*=r)?Math.max(t*a*c/r,r/(t*i*c)):1/0}function p(e,t,n,a){var i,o=-1,l=e.length,s=n.x,c=n.y,u=t?r(e.area/t):0;if(t==n.dx){for((a||u>n.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++o1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var n=t.random.irwinHall(e);return function(){return n()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;n2?fo:lo,l=a?hi:di;return i=e(t,n,l,r),o=e(n,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(n=e,l()):n};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(r=e,l()):r};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,n){return yo(t,e,n)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,n,r,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(n,r,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(r)}function l(e){return a?Math.pow(r,e):-Math.pow(r,-e)}function s(e){return n(o(e))}s.invert=function(e){return l(n.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,n.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(r=+e,n.domain(i.map(o)),s):r};s.nice=function(){var e=so(i.map(o),a?Math:_o);return n.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],n=e[0],s=e[1],c=Math.floor(o(n)),u=Math.ceil(o(s)),f=r%1?2:r;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,n){if(!arguments.length)return bo;arguments.length<2?n=bo:"function"!=typeof n&&(n=t.format(n));var a=Math.max(1,r*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*r0?a[e-1]:n[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,T,A=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=r===Co?Math.sqrt(l*l+c*c):+r.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(A=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Te?0:1;if(L&&Eo(m,x,b,_)===h^S){var O=(u+f)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-A),k=l*Math.sin(f-A),M=l*Math.cos(u+A),T=l*Math.sin(u+A);var P=Math.abs(u-f+2*A)<=Te?0:1;if(A&&Eo(w,k,M,T)===1-h^P){var z=(u+f)/2;w=l*Math.cos(z),k=l*Math.sin(z),M=T=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+n.apply(this,arguments)))>.001){g=l0?0:1}function No(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=n-r,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,T=(-b*v+y*_)/m,A=w-p,L=k-g,C=M-p,S=T-g;return A*A+L*L>C*C+S*S&&(w=M,k=T),[[w-s,k-c],[w*n/x,k*n/x]]}function Io(e){var t=Kr,n=ea,r=Xn,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(n);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",r[0]);return a.join("")},"step-before":jo,"step-after":Ho,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,n=[],r=-1,a=e.length,i=[0],o=[0];for(;++r<3;)t=e[r],i.push(t[0]),o.push(t[1]);n.push(Go(Zo,i)+","+Go(Zo,o)),--r;for(;++r9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function Bo(e){return e.join("L")+"Z"}function jo(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cTe)+",1 "+t}function s(e,t,n,r){return"Q 0,0 "+r}return i.radius=function(e){return arguments.length?(n=vt(e),i):n},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(r=vt(e),i):r},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=Br,t=jr,n=el;function r(r,a){var i=e.call(this,r,a),o=t.call(this,r,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(n))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return r.source=function(t){return arguments.length?(e=vt(t),r):e},r.target=function(e){return arguments.length?(t=vt(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),n=el,r=e.projection;return e.projection=function(e){return arguments.length?r(function(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Ce;return[n*Math.cos(r),n*Math.sin(r)]}}(n=e)):n},e},t.svg.symbol=function(){var e=nl,t=tl;function n(n,r){return(al.get(e.call(this,n,r))||rl)(t.call(this,n,r))}return n.type=function(t){return arguments.length?(e=vt(t),n):e},n.size=function(e){return arguments.length?(t=vt(e),n):t},n};var al=t.map({circle:rl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),n=t*ol;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);X.transition=function(e){for(var t,n,r=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[r]:delete e[n],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[r]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=X.call,dl.empty=X.empty,dl.node=X.node,dl.size=X.size,t.transition=function(e,n){return e&&e.transition?ul?e.transition(n):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,n,r,a=this.id,i=this.namespace,o=[];e=Z(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=r.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),T=xe(y),A=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,A[0]-=l[1],A[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(A[0]+=l[1],A[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",z):L.on("mousemove.brush",O).on("mouseup.brush",z),b.interrupt().selectAll("*").interrupt(),M)A[0]=l[0]-A[0],A[1]=s[0]-A[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-A[0],s[1-S]-A[1]],A[0]=l[C],A[1]=s[S]}else t.event.altKey&&(f=A.slice());function O(){var e=t.mouse(y),n=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),A[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var n=io(a.domain()),r=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],Sl(+n[1]+1),t<1?1:t)},a.tickFormat=function(){return r},a.copy=function(){return Cl(e.copy(),n,r)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Al,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Al.toString,Dt.second=Rt(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=Rt(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=Rt(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=Rt(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Pl=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],zl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Xn]]),Dl={range:function(e,n,r){return t.range(Math.ceil(e/r)*r,+n,r).map(Sl)},floor:P,ceil:P};Pl.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),Pl,zl)};var El=Pl.map(function(e){return[e[0].utc,e[1]]}),Nl=Tl.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Xn]]);function Il(e){return JSON.parse(e.responseText)}function Rl(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Nl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Il,t)},t.html=function(e,t){return mt(e,"text/html",Rl,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t={};t.xmlns="http://www.w3.org/2000/xmlns/",t.svg="http://www.w3.org/2000/svg",t.xlink="http://www.w3.org/1999/xlink",t.svgAttrs={xmlns:t.svg,"xmlns:xlink":t.xlink};var n=function(e){var t=typeof e;if("string"===t){var n=e;if(0===(e=+e)&&function(e){for(var t,n=e.length,r=0;r13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(n))return!1}else if("number"!==t)return!1;return e-e<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},a={},i=Math.PI;a.deg2rad=function(e){return e/180*i},a.rad2deg=function(e){return e/i*180},a.wrap360=function(e){var t=e%360;return t<0?t+360:t},a.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var o=r.BADNUM,l=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(e){var t=/^\s+/,n=/\s+$/,r=0,a=e.round,i=e.min,o=e.max,l=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(r){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof r&&(r=function(e){e=e.replace(t,"").replace(n,"").toLowerCase();var r,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(r=j.rgb.exec(e))return{r:r[1],g:r[2],b:r[3]};if(r=j.rgba.exec(e))return{r:r[1],g:r[2],b:r[3],a:r[4]};if(r=j.hsl.exec(e))return{h:r[1],s:r[2],l:r[3]};if(r=j.hsla.exec(e))return{h:r[1],s:r[2],l:r[3],a:r[4]};if(r=j.hsv.exec(e))return{h:r[1],s:r[2],v:r[3]};if(r=j.hsva.exec(e))return{h:r[1],s:r[2],v:r[3],a:r[4]};if(r=j.hex8.exec(e))return{r:z(r[1]),g:z(r[2]),b:z(r[3]),a:I(r[4]),format:a?"name":"hex8"};if(r=j.hex6.exec(e))return{r:z(r[1]),g:z(r[2]),b:z(r[3]),format:a?"name":"hex"};if(r=j.hex4.exec(e))return{r:z(r[1]+""+r[1]),g:z(r[2]+""+r[2]),b:z(r[3]+""+r[3]),a:I(r[4]+""+r[4]),format:a?"name":"hex8"};if(r=j.hex3.exec(e))return{r:z(r[1]+""+r[1]),g:z(r[2]+""+r[2]),b:z(r[3]+""+r[3]),format:a?"name":"hex"};return!1}(r));"object"==typeof r&&(H(r.r)&&H(r.g)&&H(r.b)?(h=r.r,p=r.g,g=r.b,a={r:255*O(h,255),g:255*O(p,255),b:255*O(g,255)},f=!0,d="%"===String(r.r).substr(-1)?"prgb":"rgb"):H(r.h)&&H(r.s)&&H(r.v)?(s=E(r.s),c=E(r.v),a=function(t,n,r){t=6*O(t,360),n=O(n,100),r=O(r,100);var a=e.floor(t),i=t-a,o=r*(1-n),l=r*(1-i*n),s=r*(1-(1-i)*n),c=a%6;return{r:255*[r,l,o,o,s,r][c],g:255*[s,r,r,l,o,o][c],b:255*[o,o,s,r,r,l][c]}}(r.h,s,c),f=!0,d="hsv"):H(r.h)&&H(r.s)&&H(r.l)&&(s=E(r.s),u=E(r.l),a=function(e,t,n){var r,a,i;function o(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=O(e,360),t=O(t,100),n=O(n,100),0===t)r=a=i=n;else{var l=n<.5?n*(1+t):n+t-n*t,s=2*n-l;r=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*r,g:255*a,b:255*i}}(r.h,s,u),f=!0,d="hsl"),r.hasOwnProperty("a")&&(l=r.a));var h,p,g;return l=S(l),{ok:f,format:r.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=r++}function u(e,t,n){e=O(e,255),t=O(t,255),n=O(n,255);var r,a,l=o(e,t,n),s=i(e,t,n),c=(l+s)/2;if(l==s)r=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:r=(t-n)/u+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,i.push(c(r));return i}function A(e,t){t=t||6;for(var n=c(e).toHsv(),r=n.h,a=n.s,i=n.v,o=[],l=1/t;t--;)o.push(c({h:r,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,n,r,a=this.toRgb();return t=a.r/255,n=a.g/255,r=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(n).toString(16)),D(N(r))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*O(this._r,255))+"%",g:a(100*O(this._g,255))+"%",b:a(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%)":"rgba("+a(100*O(this._r,255))+"%, "+a(100*O(this._g,255))+"%, "+a(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);n="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:E(e[r]));e=n}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:l(),g:l(),b:l()})},c.mix=function(e,t,n){n=0===n?0:n||50;var r=c(e).toRgb(),a=c(t).toRgb(),i=n/100;return c({r:(a.r-r.r)*i+r.r,g:(a.g-r.g)*i+r.g,b:(a.b-r.b)*i+r.b,a:(a.a-r.a)*i+r.a})},c.readability=function(t,n){var r=c(t),a=c(n);return(e.max(r.getLuminance(),a.getLuminance())+.05)/(e.min(r.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,n){var r,a,i=c.readability(e,t);switch(a=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,n){var r,a,i,o,l=null,s=0;a=(n=n||{}).includeFallbackColors,i=n.level,o=n.size;for(var u=0;us&&(s=r,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(n.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],n))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function O(t,n){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var r=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(n,o(0,parseFloat(t))),r&&(t=parseInt(t*n,10)/100),e.abs(t-n)<1e-6?1:t%n/parseFloat(n)}function P(e){return i(1,o(0,e))}function z(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function N(t){return e.round(255*parseFloat(t)).toString(16)}function I(e){return z(e)/255}var R,F,B,j=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",B="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+B),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+B),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+B),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})$/});function H(e){return!!j.CSS_UNIT.exec(e)}s.exports?s.exports=c:window.tinycolor=c}(Math),s=s.exports;var c={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=c.RdBu,f=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var n=0;n1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(r=e[t][0],a=e[t][1],o=!1,Y(r))for(n=r.length-1;n>=0;n--)Q(r[n],$(a,n))?o?r[n]=void 0:r.pop():o=!0;else if("object"==typeof r&&null!==r)for(i=Object.keys(r),o=!1,n=i.length-1;n>=0;n--)Q(r[i[n]],$(a,i[n]))?delete r[i[n]]:o=!0;if(o)return}}(s)):o[t[i]]=r}}function $(e,t){var r=t;return n(t)?r="["+t+"]":e&&(r="."+t),e+r}function K(e,t,n,r){var a,i=Y(n),o=!0,l=n,s=r.replace("-1",0),c=!i&&Q(n,s),u=t[0];for(a=0;aa.max?t.set(r):t.set(+e)}},integer:{coerceFunction:function(e,t,r,a){e%1||!n(e)||void 0!==a.min&&ea.max?t.set(r):t.set(+e)}},string:{coerceFunction:function(e,t,n,r){if("string"!=typeof e){var a="number"==typeof e;!0!==r.strict&&a?t.set(String(e)):t.set(n)}else r.noBlank&&!e?t.set(n):t.set(e)}},color:{coerceFunction:function(e,t,n){s(e).isValid()?t.set(e):t.set(n)}},colorlist:{coerceFunction:function(e,t,n){Array.isArray(e)&&e.length&&e.every(function(e){return s(e).isValid()})?t.set(e):t.set(n)}},colorscale:{coerceFunction:function(e,t,n){t.set(d(e,n))}},angle:{coerceFunction:function(e,t,r){"auto"===e?t.set("auto"):n(e)?t.set(ie(+e)):t.set(r)}},subplotid:{coerceFunction:function(e,t,n,r){var a=r.regex||re(n);"string"==typeof e&&a.test(e)?t.set(e):t.set(n)},validateFunction:function(e,t){var n=t.dflt;return e===n||"string"==typeof e&&!!re(n).test(e)}},flaglist:{coerceFunction:function(e,t,n,r){if("string"==typeof e)if(-1===(r.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=le&&e<=se?e:fe;if("string"!=typeof e&&"number"!=typeof e)return fe;e=String(e);var n=_e(t),r=e.charAt(0);!n||"G"!==r&&"g"!==r||(e=e.substr(1),t="");var a=n&&"chinese"===t.substr(0,7),i=e.match(a?xe:me);if(!i)return fe;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(n){if(2===o.length)return fe;var d;o=Number(o);try{var h=D.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return fe}return d?(d.toJD()-ve)*de+c*he+u*pe+f*ge:fe}o=2===o.length?(Number(o)+2e3-be)%100+be:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?fe:g.getUTCDate()!==s?fe:g.getTime()+f*ge},le=ue.MIN_MS=ue.dateTime2ms("-9999"),se=ue.MAX_MS=ue.dateTime2ms("9999-12-31 23:59:59.9999"),ue.isDateTime=function(e,t){return ue.dateTime2ms(e,t)!==fe};var ke=90*de,Me=3*he,Te=5*pe;function Ae(e,t,n,r,a){if((t||n||r||a)&&(e+=" "+we(t,2)+":"+we(n,2),(r||a)&&(e+=":"+we(r,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+we(a,i)}return e}ue.ms2DateTime=function(e,t,n){if("number"!=typeof e||!(e>=le&&e<=se))return fe;t||(t=0);var r,a,i,o,l,s,c=Math.floor(10*ce(e+.05,1)),u=Math.round(e-c/10);if(_e(n)){var f=Math.floor(u/de)+ve,d=Math.floor(ce(e,de));try{r=D.getComponentMethod("calendars","getCal")(n).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){r=ye("G%Y-%m-%d")(new Date(u))}if("-"===r.charAt(0))for(;r.length<11;)r="-0"+r.substr(1);else for(;r.length<10;)r="0"+r;a=t=le+de&&t<=se-de))return fe;var n=Math.floor(10*ce(t+.05,1)),r=new Date(Math.round(t-n/10));return Ae(e.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+n)},ue.cleanDate=function(e,t,n){if(ue.isJSDate(e)||"number"==typeof e){if(_e(n))return w.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ue.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ue.isDateTime(e,n))return w.error("unrecognized date",e),t;return e};var Le=/%\d?f/g;function Ce(e,t,n,r){e=e.replace(Le,function(e){var n=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(n).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(_e(r))try{e=D.getComponentMethod("calendars","worldCalFmt")(e,t,r)}catch(e){return"Invalid"}return n(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ue.formatDate=function(e,t,r,a,i,o){if(i=_e(i)&&i,!t)if("y"===r)t=o.year;else if("m"===r)t=o.month;else{if("d"!==r)return function(e,t){var r=ce(e+.05,de),a=we(Math.floor(r/he),2)+":"+we(ce(Math.floor(r/pe),60),2);if("M"!==t){n(t)||(t=0);var i=(100+Math.min(ce(e/ge,60),Se[t])).toFixed(t).substr(1);t>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,r)+"\n"+Ce(o.dayMonthYear,e,a,i);t=o.dayMonth+"\n"+o.year}return Ce(t,e,a,i)};var Oe=3*de;ue.incrementMonth=function(e,t,n){n=_e(n)&&n;var r=ce(e,de);if(e=Math.round(e-r),n)try{var a=Math.round(e/de)+ve,i=D.getComponentMethod("calendars","getCal")(n),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ve)*de+r}catch(t){w.error("invalid ms "+e+" in calendar "+n)}var l=new Date(e+Oe);return l.setUTCMonth(l.getUTCMonth()+t)+r-Oe},ue.findExactDates=function(e,t){for(var r,a,i=0,o=0,l=0,s=0,c=_e(t)&&D.getComponentMethod("calendars","getCal")(t),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Fe(e,t,n,r,a){var i=r*e+a*t;if(i<0)return r*r+a*a;if(i>n){var o=r-e,l=a-t;return o*o+l*l}var s=r*t-a*e;return s*s/n}Ie.segmentsIntersect=Re,Ie.segmentDistance=function(e,t,n,r,a,i,o,l){if(Re(e,t,n,r,a,i,o,l))return 0;var s=n-e,c=r-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Fe(s,c,d,a-e,i-t),Fe(s,c,d,o-e,l-t),Fe(u,f,h,e-a,t-i),Fe(u,f,h,n-a,r-i));return Math.sqrt(p)},Ie.getTextLocation=function(e,t,n,r){if(e===Ee&&r===Ne||(De={},Ee=e,Ne=r),De[n])return De[n];var a=e.getPointAtLength(ce(n-r/2,t)),i=e.getPointAtLength(ce(n+r/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(ce(n,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return De[n]=s,s},Ie.clearLocationCache=function(){Ee=null},Ie.getVisibleSegment=function(e,t,n){var r,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var n=e.getPointAtLength(t);0===t?r=n:t===u&&(a=n);var c=n.xo?n.x-o:0,f=n.ys?n.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+n)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+n))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(r.x-a.x)<.1&&Math.abs(r.y-a.y)<.1}},Ie.findPointOnPath=function(e,t,n,r){for(var a,i,o,l=(r=r||{}).pathLength||e.getTotalLength(),s=r.tolerance||.001,c=r.iterationLimit||30,u=e.getPointAtLength(0)[n]>e.getPointAtLength(l)[n]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var Be=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},je=/^\w*$/,He={init2dArray:function(e,t){for(var n=new Array(e),r=0;rt}function Qe(e,t){return e>=t}Ye.findBin=function(e,t,r){if(n(t.start))return r?Math.ceil((e-t.start)/t.size-1e-9)-1:Math.floor((e-t.start)/t.size+1e-9);var a,i,o=0,l=t.length,s=0,c=l>1?(t[l-1]-t[0])/(l-1):1;for(i=c>=0?r?Xe:Ze:r?Qe:We,e+=1e-9*c*(r?-1:1)*(c>=0?1:-1);o90&&w.log("Long binary search..."),o-1},Ye.sorterAsc=function(e,t){return e-t},Ye.sorterDes=function(e,t){return t-e},Ye.distinctVals=function(e){var t=e.slice();t.sort(Ye.sorterAsc);for(var n=t.length-1,r=t[n]-t[0]||1,a=r/(n||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(r=Math.min(r,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:r}},Ye.roundUp=function(e,t,n){for(var r,a=0,i=t.length-1,o=0,l=n?0:1,s=n?1:0,c=n?Math.ceil:Math.floor;ar.length)&&(a=r.length),n(t)||(t=!1),$e(r[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var r=t%1;return r*e[Math.ceil(t)]+(1-r)*e[Math.floor(t)]};var Ke={},et={};function tt(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}Ke.throttle=function(e,t,n){var r=et[e],a=Date.now();if(!r){for(var i in et)et[i].tsr.ts+t?o():r.timer=setTimeout(function(){o(),r.timer=null},t)},Ke.done=function(e){var t=et[e];return t&&t.timer?new Promise(function(e){var n=t.onDone;t.onDone=function(){n&&n(),e(),t.onDone=null}}):Promise.resolve()},Ke.clear=function(e){if(e)tt(et[e]),delete et[e];else for(var t in et)Ke.clear(t)};var nt=function(e,t){if(e>0)return Math.log(e)/Math.LN10;var r=Math.log(Math.min(t[0],t[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(t[0],t[1]))/Math.LN10-6),r},rt={},at=r.FP_SAFE,it=r.BADNUM,ot=rt={};ot.nestedProperty=X,ot.keyedContainer=function(e,t,n,r){var a,i;n=n||"name",r=r||"value";var o={};i=t&&t.length?X(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lat?it:n(e)?Number(e):it:it},ot.noop=T,ot.identity=function(e){return e},ot.swapAttrs=function(e,t,n,r){n||(n="x"),r||(r="y");for(var a=0;an?Math.max(n,Math.min(t,e)):Math.max(t,Math.min(n,e))},ot.bBoxIntersect=function(e,t,n){return n=n||0,e.left<=t.right+n&&t.left<=e.right+n&&e.top<=t.bottom+n&&t.top<=e.bottom+n},ot.simpleMap=function(e,t,n,r){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,n)?e(t,n,r):l},ot.OptionControl=function(e,t){e||(e={}),t||(t="opt");var n={optionList:[],_newoption:function(r){r[t]=e,n[r.name]=r,n.optionList.push(r)}};return n["_"+t]=e,n},ot.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var n,r,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(n=0;n=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[r];u[n]=i}return u},ot.syncOrAsync=function(e,t,n){var r;function a(){return ot.syncOrAsync(e,t,n)}for(;e.length;)if((r=(0,e.splice(0,1)[0])(t))&&r.then)return r.then(a).then(void 0,ot.promiseError);return n&&n(t)},ot.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},ot.noneOrAll=function(e,t,n){if(e){var r,a,i=!1,o=!0;for(r=0;r=0&&i%1==0){var p=a?a[h]:h,g=r?r[p]:p;f(g)&&(e[g].selected=1)}}},ot.getTargetArray=function(e,t){var n=t.target;if("string"==typeof n&&n){var r=ot.nestedProperty(e,n).get();return!!Array.isArray(r)&&r}return!!Array.isArray(n)&&n},ot.minExtend=function(e,t){var n={};"object"!=typeof t&&(t={});var r,a,i,o=Object.keys(e);for(r=0;r1?a+o[1]:"";if(i&&(o.length>1||l.length>4||n))for(;r.test(l);)l=l.replace(r,"$1"+i+"$2");return l+s};var ct=/%{([^\s%{}]*)}/g,ut=/^\w*$/;ot.templateString=function(e,t){var n={};return e.replace(ct,function(e,r){return ut.test(r)?t[r]||"":(n[r]=n[r]||ot.nestedProperty(t,r).get,n[r]()||"")})};ot.subplotSort=function(e,t){for(var n=Math.min(e.length,t.length)+1,r=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(r=10*r+o-48),c&&(a=10*a+l-48),!s||!c){if(r!==a)return r-a;if(o!==l)return o-l}}return a-r};var ft=2e9;ot.seedPseudoRandom=function(){ft=2e9},ot.pseudoRandom=function(){var e=ft;return ft=(69069*ft+1)%4294967296,Math.abs(ft-e)<429496729?ot.pseudoRandom():ft/4294967296};var dt=te.counter,ht={idRegex:{x:dt("x"),y:dt("y")},attrRegex:dt("[xy]axis"),xAxisMatch:dt("xaxis"),yAxisMatch:dt("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["imagelayer","maplayer","barlayer","carpetlayer","violinlayer","boxlayer","ohlclayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}},pt={id2name:function(e){if("string"==typeof e&&e.match(ht.AX_ID_PATTERN)){var t=e.substr(1);return"1"===t&&(t=""),e.charAt(0)+"axis"+t}},name2id:function(e){if(e.match(ht.AX_NAME_PATTERN)){var t=e.substr(5);return"1"===t&&(t=""),e.charAt(0)+t}},cleanId:function(e,t){if(e.match(ht.AX_ID_PATTERN)&&(!t||e.charAt(0)===t)){var n=e.substr(1).replace(/^0+/,"");return"1"===n&&(n=""),e.charAt(0)+n}},list:function(e,t,n){var r=e._fullLayout;if(!r)return[];var a,i=pt.listIds(e,t),o=new Array(i.length);for(a=0;ar?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},gt={};(function(e){"use strict";var t;t="function"!=typeof e.matchMedia||!e.matchMedia("(hover: none)").matches,gt=t}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var vt=function(){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(t){e=!1}return e}(),yt={left:0,top:0},mt=function(e,t,n){t=t||e.currentTarget||e.srcElement,Array.isArray(n)||(n=[0,0]);var r=e.clientX||0,a=e.clientY||0,i=(o=t,o===window||o===document||o===document.body?yt:o.getBoundingClientRect());var o;return n[0]=r-i.left,n[1]=a-i.top,n};var xt=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]],bt={YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,HOVERID:"-hover"};function _t(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var wt=_t;function kt(e){return"function"==typeof e}function Mt(e){return"object"==typeof e&&null!==e}function Tt(e){return void 0===e}_t.EventEmitter=_t,_t.prototype._events=void 0,_t.prototype._maxListeners=void 0,_t.defaultMaxListeners=10,_t.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},_t.prototype.emit=function(e){var t,n,r,a,i,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||Mt(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(Tt(n=this._events[e]))return!1;if(kt(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),n.apply(this,a)}else if(Mt(n))for(a=Array.prototype.slice.call(arguments,1),r=(o=n.slice()).length,i=0;i0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},_t.prototype.on=_t.prototype.addListener,_t.prototype.once=function(e,t){if(!kt(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},_t.prototype.removeListener=function(e,t){var n,r,a,i;if(!kt(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||kt(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(Mt(n)){for(i=a;i-- >0;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},_t.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(kt(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},_t.prototype.listeners=function(e){return this._events&&this._events[e]?kt(this._events[e])?[this._events[e]]:this._events[e].slice():[]},_t.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(kt(t))return 1;if(t)return t.length}return 0},_t.listenerCount=function(e,t){return e.listenerCount(t)};var At,Lt=wt.EventEmitter,Ct={init:function(e){if(e._ev instanceof Lt)return e;var t=new Lt,n=new Lt;return e._ev=t,e._internalEv=n,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=n.on.bind(n),e._internalOnce=n.once.bind(n),e._removeInternalListener=n.removeListener.bind(n),e._removeAllInternalListeners=n.removeAllListeners.bind(n),e.emit=function(r,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(r,a),t.emit(r,a),n.emit(r,a)},e},triggerHandler:function(e,t,n){var r,a;"undefined"!=typeof jQuery&&(r=jQuery(e).triggerHandler(t,n));var i=e._ev;if(!i)return r;var o=i._events[t];if(!o)return r;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Pt.getCursor=function(e,t,n,r){return e="left"===n?0:"center"===n?1:"right"===n?2:rt.constrain(Math.floor(3*e),0,2),t="bottom"===r?0:"middle"===r?1:"top"===r?2:rt.constrain(Math.floor(3*t),0,2),xt[t][e]},Pt.unhover=At.wrapped,Pt.unhoverRaw=At.raw,Pt.init=function(e){var t,n,r,a,i,o,l,s,c=e.gd,u=1,f=h.DBLCLICKDELAY,d=e.element;c._mouseDownTime||(c._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,vt?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=e.clampFn||function(e,t,n){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var n;try{n=new MouseEvent("click",t)}catch(e){var r=Dt(t);(n=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,r[0],r[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(n)}!function(e){e._dragging=!1,e._replotPending&&D.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Pt.coverSlip=zt;function Et(e,t,n,r){r=r||rt.identity,Array.isArray(e)&&(t[0][n]=r(e))}var Nt={},It=Nt={};It.defaults=O.defaults;var Rt=It.defaultLine=O.defaultLine;It.lightLine=O.lightLine;var Ft=It.background=O.background;function Bt(e){if(n(e)||"string"!=typeof e)return e;var t=e.trim();if("rgb"!==t.substr(0,3))return e;var r=t.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return e;var a=r[1].trim().split(/\s*[\s,]\s*/),i="a"===t.charAt(3)&&4===a.length;if(!i&&3!==a.length)return e;for(var o=0;o=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}It.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},It.rgb=function(e){return It.tinyRGB(s(e))},It.opacity=function(e){return e?s(e).getAlpha():0},It.addOpacity=function(e,t){var n=s(e).toRgb();return"rgba("+Math.round(n.r)+", "+Math.round(n.g)+", "+Math.round(n.b)+", "+t+")"},It.combine=function(e,t){var n=s(e).toRgb();if(1===n.a)return s(e).toRgbString();var r=s(t||Ft).toRgb(),a=1===r.a?r:{r:255*(1-r.a)+r.r*r.a,g:255*(1-r.a)+r.g*r.a,b:255*(1-r.a)+r.b*r.a},i={r:a.r*(1-n.a)+n.r*n.a,g:a.g*(1-n.a)+n.g*n.a,b:a.b*(1-n.a)+n.b*n.a};return s(i).toRgbString()},It.contrast=function(e,t,n){var r=s(e);return 1!==r.getAlpha()&&(r=s(It.combine(e,Ft))),(r.isDark()?t?r.lighten(t):Ft:n?r.darken(n):Rt).toString()},It.stroke=function(e,t){var n=s(t);e.style({stroke:It.tinyRGB(n),"stroke-opacity":n.getAlpha()})},It.fill=function(e,t){var n=s(t);e.style({fill:It.tinyRGB(n),"fill-opacity":n.getAlpha()})},It.clean=function(e){if(e&&"object"==typeof e){var t,n,r,a,i=Object.keys(e);for(t=0;t=0;a--,i++)t=e[a],r[i]=[1-t[0],t[1]];return r},qt=function(e,t,n,r){var a,i;n?(a=rt.nestedProperty(e,n).get(),i=rt.nestedProperty(e._input,n).get()):(a=e,i=e._input);var o=r+"auto",l=r+"min",s=r+"max",u=a[o],f=a[l],d=a[s],h=a.colorscale;!1===u&&void 0!==f||(f=rt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=rt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[s]=d,i[l]=f,i[s]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?c.RdBu:f>=0?c.Reds:c.Blues,i.colorscale=h,a.reversescale&&(h=Ht(h)),a.colorscale=h)},Vt=rt.extendFlat,Ut=rt.isPlainObject,Gt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},Yt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},Xt=Gt.flags.slice().concat(["clearCalc","fullReplot"]),Zt=Yt.flags.slice().concat("layoutReplot"),Wt={traces:Gt,layout:Yt,traceFlags:function(){return Qt(Xt)},layoutFlags:function(){return Qt(Zt)},update:function(e,t){var n=t.editType;if(n&&"none"!==n)for(var r=n.split("+"),a=0;a0?Number(s):l;else if("string"!=typeof s)t.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=n(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(t.dtick=l)}var f="date"===a?rt.dateTick0(t.calendar):0,d=r("tick0",f);"date"===a?t.tick0=rt.cleanDate(d,f):n(d)&&"D1"!==s&&"D2"!==s?t.tick0=Number(d):t.tick0=f}else{void 0===r("tickvals")?t.tickmode="auto":r("ticktext")}},un=function(e){return void 0!==c[e]||f(e)},fn=function(e,t,r,a,i){var o,l=i.prefix,s=i.cLetter,c=l.slice(0,l.length-1),u=l?rt.nestedProperty(e,c).get()||{}:e,f=l?rt.nestedProperty(t,c).get()||{}:t,d=u[s+"min"],h=u[s+"max"],p=u.colorscale;a(l+s+"auto",!(n(d)&&n(h)&&d","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},mn={},xn=vn.LINE_SPACING;function bn(e,t){return e.node().getBoundingClientRect()[t]}var _n=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;mn.convertToTspans=function(n,r,a){var i=n.text(),o=!n.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(_n),l=e.select(n.node().parentNode);if(!l.empty()){var s=n.attr("class")?n.attr("class").split(" ")[0]:"text";return s+="-math",l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove(),n.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(r&&r._promises||[]).push(new Promise(function(t){n.style("display","none");var r=parseInt(n.node().style.fontSize,10),u={fontSize:r};!function(t,n,r){var a="math-output-"+rt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":n.fontSize+"px"}).text((o=t,o.replace(wn,"\\lt ").replace(kn,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var n=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())rt.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),n,a)}i.remove()})}(o[2],u,function(e,o,u){l.selectAll("svg."+s).remove(),l.selectAll("g."+s+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return c(),void t();var d=l.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});d.node().appendChild(f.node()),o&&o.node()&&f.node().insertBefore(o.node().cloneNode(!0),f.node().firstChild),f.attr({class:s,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=n.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=bn(f,"width"),g=bn(f,"height"),v=+n.attr("x")-p*{start:0,middle:.5,end:1}[n.attr("text-anchor")||"start"],y=-(r||bn(n,"height"))/4;"y"===s[0]?(d.attr({transform:"rotate("+[-90,+n.attr("x"),+n.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+n.attr("x"),y:+n.attr("y")})):"l"===s[0]?f.attr({x:n.attr("x"),y:y-g/2}):"a"===s[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+n.attr("y")+y-g/2}),a&&a.call(n,d),t(d)})})):c(),n}function c(){l.empty()||(s=n.attr("class")+"-math",l.select("svg."+s).remove()),n.text("").style("white-space","pre"),function(n,r){r=(a=r,function(e,t){if(!e)return"";for(var n=0;n1)for(var o=1;o doesnt match end tag <"+e+">. Pretending it did match.",r),i=l[l.length-1].node}else rt.log("Ignoring unexpected end tag .",r)}En.test(r)?c():(i=n,l=[{node:n}]);for(var h=r.split(zn),p=0;p|>|>)/g;var Mn={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"},Tn={sub:"0.3em",sup:"-0.6em"},An={sub:"-0.21em",sup:"0.42em"},Ln="\u200b",Cn=["http:","https:","mailto:","",void 0,":"],Sn=new RegExp("]*)?/?>","g"),On=Object.keys(yn.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:yn.entityToUnicode[e]}}),Pn=/(\r\n?|\n)/g,zn=/(<[^<>]*>)/,Dn=/<(\/?)([^ >]*)(\s+(.*))?>/i,En=//i,Nn=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,In=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Rn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Fn=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function Bn(e,t){if(!e)return null;var n=e.match(t);return n&&(n[3]||n[4])}var jn=/(^|;)\s*color:/;function Hn(e,t,n){var r,a,i,o=n.horizontalAlign,l=n.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-r.height}:"middle"===l?function(){return s.top+(s.height-r.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-r.width}:"center"===o?function(){return s.left+(s.width-r.width)/2}:function(){return s.left},function(){return r=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}mn.plainText=function(e){return(e||"").replace(Sn," ")},mn.lineCount=function(e){return e.selectAll("tspan.line").size()||1},mn.positionText=function(t,n,r){return t.each(function(){var t=e.select(this);function a(e,n){return void 0===n?null===(n=t.attr(e))&&(t.attr(e,0),n=0):t.attr(e,n),n}var i=a("x",n),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},mn.makeEditable=function(t,n){var r=n.gd,a=n.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(r).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:n.fill||c.fill||"black",opacity:1,"background-color":n.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(n.text||t.attr("data-unformatted")).call(Hn(t,a,n)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var n,a=e.select(this).attr("class");(n=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(n).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(r._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Hn(t,a,n)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),n=document.createRange();n.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(n),t.focus()}return n.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var qn=function(e){var t=e.marker,r=t.sizeref||1,a=t.sizemin||0,i="area"===t.sizemode?function(e){return Math.sqrt(e/r)}:function(e){return e/r};return function(e){var t=i(e/2);return n(t)&&t>0?Math.max(t,a):0}},Vn={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&(e.mode&&-1!==e.mode.indexOf("markers")||"splom"===e.type)},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return rt.isPlainObject(e.marker)&&rt.isArrayOrTypedArray(e.marker.size)}},Un={},Gn=vn.LINE_SPACING,Yn=h.DESELECTDIM,Xn=Un={};Xn.font=function(e,t,n,r){rt.isPlainObject(t)&&(r=t.color,n=t.size,t=t.family),t&&e.style("font-family",t),n+1&&e.style("font-size",n+"px"),r&&e.call(Nt.fill,r)},Xn.setPosition=function(e,t,n){e.attr("x",t).attr("y",n)},Xn.setSize=function(e,t,n){e.attr("width",t).attr("height",n)},Xn.setRect=function(e,t,n,r,a){e.call(Xn.setPosition,t,n).call(Xn.setSize,r,a)},Xn.translatePoint=function(e,t,r,a){var i=r.c2p(e.x),o=a.c2p(e.y);return!!(n(i)&&n(o)&&t.node())&&("text"===t.node().nodeName?t.attr("x",i).attr("y",o):t.attr("transform","translate("+i+","+o+")"),!0)},Xn.translatePoints=function(t,n,r){t.each(function(t){var a=e.select(this);Xn.translatePoint(t,a,n,r)})},Xn.hideOutsideRangePoint=function(e,t,n,r,a,i){t.attr("display",n.isPtWithinRange(e,a)&&r.isPtWithinRange(e,i)?null:"none")},Xn.hideOutsideRangePoints=function(t,n,r){if(n._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=n.xaxis,i=n.yaxis;t.each(function(n){var o=n[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Xn.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Xn.crispRound=function(e,t,r){return t&&n(t)?e._context.staticPlot?t:t<1?1:Math.round(t):r||0},Xn.singleLineStyle=function(e,t,n,r,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";Nt.stroke(t,r||i.color),Xn.dashLine(t,l,o)},Xn.lineGroupStyle=function(t,n,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";e.select(this).call(Nt.stroke,r||i.color).call(Xn.dashLine,l,o)})},Xn.dashLine=function(e,t,n){n=+n||0,t=Xn.dashStyle(t,n),e.style({"stroke-dasharray":t,"stroke-width":n+"px"})},Xn.dashStyle=function(e,t){t=+t||1;var n=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),e},Xn.singleFillStyle=function(t){var n=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;n&&t.call(Nt.fill,n)},Xn.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(n){var r=e.select(this);try{r.call(Nt.fill,n[0].trace.fillcolor)}catch(e){rt.error(e,t),r.remove()}})},Xn.symbolNames=[],Xn.symbolFuncs=[],Xn.symbolNeedLines={},Xn.symbolNoDot={},Xn.symbolNoFill={},Xn.symbolList=[],Object.keys(gn).forEach(function(e){var t=gn[e];Xn.symbolList=Xn.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Xn.symbolNames[t.n]=e,Xn.symbolFuncs[t.n]=t.f,t.needLine&&(Xn.symbolNeedLines[t.n]=!0),t.noDot?Xn.symbolNoDot[t.n]=!0:Xn.symbolList=Xn.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Xn.symbolNoFill[t.n]=!0)});var Zn=Xn.symbolNames.length,Wn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Qn(e,t){var n=e%100;return Xn.symbolFuncs[n](t)+(e>=200?Wn:"")}Xn.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Xn.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Zn||e>=400?0:Math.floor(Math.max(e,0))};var Jn={x1:1,x2:0,y1:0,y2:0},$n={x1:0,x2:0,y1:1,y2:0};Xn.gradient=function(t,n,r,a,i,o){var l=n._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],rt.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jn):"vertical"===a&&t.attr($n),t.attr("id",r);var n=s(i),l=s(o);t.append("stop").attr({offset:"0%","stop-color":Nt.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":Nt.tinyRGB(n),"stop-opacity":n.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Xn.initGradients=function(e){rt.ensureSingle(e._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},Xn.singlePointStyle=function(e,t,n,r,a,i){var o=n.marker;!function(e,t,n,r,a,i,o,l){if(D.traceIs(n,"symbols")){var s=qn(n);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Vn.isBubble(n)?s(e.ms):(i.size||6)/2,e.mrc=t;var r=Xn.symbolNumber(e.mx||i.symbol)||0;return e.om=r%200>=100,Qn(r,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):rt.isArrayOrTypedArray(o.color)?Nt.defaultLine:o.color,rt.isArrayOrTypedArray(i.color)&&(c=Nt.defaultLine,d=!0),c="mc"in e?e.mcc=r(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(Nt.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+n.uid;d&&(v+="-"+e.i),t.call(Xn.gradient,l,v,p,c,g)}else t.call(Nt.fill,c);f&&t.call(Nt.stroke,u)}}(e,t,n,r,a,o,o.line,i)},Xn.pointStyle=function(t,n,r){if(t.size()){var a=n.marker,i=Xn.tryColorscale(a,""),o=Xn.tryColorscale(a,"line");t.each(function(t){Xn.singlePointStyle(t,e.select(this),n,i,o,r)})}},Xn.makeSelectedPointStyleFns=function(e){var t={},n=e.selected||{},r=e.unselected||{},a=e.marker||{},i=n.marker||{},o=r.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,n=void 0!==t;if(n||u||f){if(!e.selected)return f?c:Yn*(n?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Xn.selectedPointStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=Xn.makeSelectedPointStyleFns(n),a=n.marker||{};t.each(function(t){var n=e.select(this),a=r.opacityFn(t);void 0!==a&&n.style("opacity",a)}),r.colorFn&&t.each(function(t){var n=e.select(this),a=r.colorFn(t);a&&Nt.fill(n,a)}),D.traceIs(n,"symbols")&&r.sizeFn&&t.each(function(t){var n=e.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);n.attr("d",Qn(Xn.symbolNumber(i),o)),t.mrc2=o})}},Xn.tryColorscale=function(e,t){var n=t?rt.nestedProperty(e,t).get():e,r=n.colorscale,a=n.color;return r&&rt.isArrayOrTypedArray(a)?pn.makeColorScaleFunc(pn.extractScale(r,n.cmin,n.cmax)):rt.identity};var Kn={start:1,end:-1,middle:0,bottom:1,top:-1};function er(t,n,r,a){var i=e.select(t.node().parentNode),o=-1!==n.indexOf("top")?"top":-1!==n.indexOf("bottom")?"bottom":"middle",l=-1!==n.indexOf("left")?"end":-1!==n.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(mn.lineCount(t)-1)*Gn+1,u=Kn[l]*s,f=.75*r+Kn[o]*s+(Kn[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function tr(e,t){var r=e.ts||t.textfont.size;return n(r)&&r>0?r:0}Xn.textPointStyle=function(t,n,r){t.each(function(t){var a=e.select(this),i=rt.extractOption(t,n,"tx","text");if(i){var o=t.tp||n.textposition,l=tr(t,n);a.call(Xn.font,t.tf||n.textfont.family,l,t.tc||n.textfont.color).text(i).call(mn.convertToTspans,r).call(er,o,l,t.mrc)}else a.remove()})},Xn.selectedTextStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=n.selected||{},a=n.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||n.textfont.color,s=t.tp||n.textposition,c=tr(t,n),u=(r.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=Nt.addOpacity(l,Yn)),i&&Nt.fill(o,i),er(o,s,c,t.mrc2||t.mrc)})}};var nr=.5;function rr(t,n,r,a){var i=t[0]-n[0],o=t[1]-n[1],l=r[0]-n[0],s=r[1]-n[1],c=Math.pow(i*i+o*o,nr/2),u=Math.pow(l*l+s*s,nr/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(n[0]+(h&&f/h),2),e.round(n[1]+(h&&d/h),2)],[e.round(n[0]-(p&&f/p),2),e.round(n[1]-(p&&d/p),2)]]}Xn.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var n,r="M"+e[0],a=[];for(n=1;n=1e4&&(Xn.savedBBoxes={},or=0),r&&(Xn.savedBBoxes[r]=p),or++,rt.extendFlat({},p)},Xn.setClipUrl=function(t,n){if(n){if(void 0===Xn.baseUrl){var r=e.select("base");r.size()&&r.attr("href")?Xn.baseUrl=window.location.href.split("#")[0]:Xn.baseUrl=""}t.attr("clip-path","url("+Xn.baseUrl+"#"+n+")")}else t.attr("clip-path",null)},Xn.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Xn.setTranslate=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||0,n=n||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+n+")").trim(),e[a]("transform",i),i},Xn.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Xn.setScale=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||1,n=n||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+n+")").trim(),e[a]("transform",i),i},Xn.setPointGroupScale=function(e,t,n){var r,a,i;return t=t||1,n=n||1,a=1===t&&1===n?"":" scale("+t+","+n+")",i=/\s*sc.*/,e.each(function(){r=(this.getAttribute("transform")||"").replace(i,""),r=(r+=a).trim(),this.setAttribute("transform",r)}),a};var sr=/translate\([^)]*\)\s*$/;Xn.setTextPointsScale=function(t,n,r){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(sr);t=1===n&&1===r?[]:["translate("+o+","+l+")","scale("+n+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var cr={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},isTraceInSubplots:function(e,t){if("splom"===e.type){for(var n=e.xaxes||[],r=e.yaxes||[],a=0;a=0&&n.index=i.length)return!1;if(2===e.dimensions){if(n++,t.length===n)return e;var o=t[n];if(!Br(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function Br(e){return e===Math.round(e)&&e>=0}function jr(e){return function(e){Pr.crawl(e,function(e,t,n){Pr.isValObject(e)?"data_array"===e.valType?(e.role="data",n[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(n[t+"src"]={valType:"string",editType:"none"}):Er(e)&&(e.role="object")})}(e),function(e){Pr.crawl(e,function(e,t,n){if(!e)return;var r=e[Ir];if(!r)return;delete e[Ir],n[t]={items:{}},n[t].items[r]=e,n[t].role="object"})}(e),function(e){!function e(t){for(var n in t)if(Er(t[n]))e(t[n]);else if(Array.isArray(t[n]))for(var r=0;r=o.length)return!1;r=(n=(D.transformsRegistry[o[l].type]||{}).attributes)&&n[t[2]],i=3}else if("area"===e.type)r=Tr[a];else{var s=e._module;if(s||(s=(D.modules[e.type||S.type.dflt]||{})._module),!s)return!1;if(!(r=(n=s.attributes)&&n[a])){var c=s.basePlotModule;c&&c.attributes&&(r=c.attributes[a])}r||(r=S[a])}return Fr(r,t,i)},Pr.getLayoutValObject=function(e,t){return Fr(function(e,t){var n,r,a,i,o=e._basePlotModules;if(o){var l;for(n=0;n0?".":"")+a;rt.isPlainObject(i)?Xr(i,t,o,r+1):t(o,a,i)}})}function Zr(e,t){return"splom"===e?-1:"splom"===t?1:0}Vr.manageCommandObserver=function(e,t,n,r){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Vr.hasSimpleAPICommandBindings(e,n,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Ur(e,o,a.cache),a.check=function(){if(i){var t=Ur(e,o,a.cache);return t.changed&&r&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(r({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=n.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=n._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var n=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)n.on("click",function(){ta.sendDataToCloud(e)});else{var r=window.location.pathname.split("/"),a=window.location.search;n.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+r[2].split(".")[0]+"/"+r[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},ta.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var n=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:n+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=ta.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var ra,aa=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],ia=["year","month","dayMonth","dayMonthYear"];function oa(e,t){var n,r,a=e.trace,i=a._arrayAttrs,o={};for(n=0;n1&&_.length>1){for(D.getComponentMethod("grid","sizeDefaults")(i,a),r=0;r15&&_.length>15&&0===a.shapes.length&&0===a.images.length,a._hasCartesian=a._has("cartesian"),a._hasGeo=a._has("geo"),a._hasGL3D=a._has("gl3d"),a._hasGL2D=a._has("gl2d"),a._hasTernary=a._has("ternary"),a._hasPie=a._has("pie"),ta.cleanPlot(l,a,o,n,c),ta.linkSubplots(l,a,o,n),Kr(a,n),ta.doAutoMargin(t);var T=pt.list(t);for(r=0;r0){var c=function(e){var t,n={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(n.left+=e[t].left||0,n.right+=e[t].right||0,n.bottom+=e[t].bottom||0,n.top+=e[t].top||0);return n}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=ta.layoutAttributes.width.min,v=ta.layoutAttributes.height.min;a1,m=!t.height&&Math.abs(r.height-i)>1;(m||y)&&(y&&(r.width=a),m&&(r.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),ta.sanitizeMargins(r)},ta.supplyLayoutModuleDefaults=function(e,t,n,r){var a,i,o,l=D.componentsRegistry,s=t._basePlotModules,c=D.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(D.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(rt.subplotSort);for(i=0;i.5*r.width&&(n.l=n.r=0),n.b+n.t>.5*r.height&&(n.b=n.t=0),r._pushmargin[t]={l:{val:n.x,size:n.l+a},r:{val:n.x,size:n.r+a},b:{val:n.y,size:n.b+a},t:{val:n.y,size:n.t+a}}}else delete r._pushmargin[t];r._replotting||ta.doAutoMargin(e)}},ta.doAutoMargin=function(e){var t=e._fullLayout;t._size||(t._size={}),t._pushmargin||(t._pushmargin={});var r=t._size,a=JSON.stringify(r),i=Math.max(t.margin.l||0,0),o=Math.max(t.margin.r||0,0),l=Math.max(t.margin.t||0,0),s=Math.max(t.margin.b||0,0),c=t._pushmargin;if(!1!==t.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(n(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-t.width)*h)/(m-h),_=(x*(1-h)+(p-t.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(n(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-t.height)*g)/(w-g),T=(k*(1-g)+(v-t.height)*(1-w))/(w-g);M>=0&&T>=0&&M+T>s+l&&(s=M,l=T)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(t.margin.pad),r.w=Math.round(t.width)-r.l-r.r,r.h=Math.round(t.height)-r.t-r.b,!t._replotting&&"{}"!==a&&a!==JSON.stringify(t._size))return D.call("plot",e)},ta.graphJson=function(e,t,n,r,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&ta.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(rt.isPlainObject(e)){var t,r,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===n){if("src"===t.substr(t.length-3))continue}else if("keepstream"===n){if("string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0&&!rt.isPlainObject(e.stream))continue}else if("keepall"!==n&&"string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):rt.isJSDate(e)?rt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var n=s(e);return t&&delete n.fit,n})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===r?c:JSON.stringify(c)},ta.modifyFrames=function(e,t){var n,r,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(n=0;n0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return D.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var r,o,l=0,s=0;function c(){return l++,function(){var n;f||++s!==l||(n=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return D.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(n)))}}var d=e._fullLayout._basePlotModules,h=!1;if(n)for(o=0;o=0;i--)if(s[i].enabled){n._indexToPoints=s[i]._indexToPoints;break}r&&r.calc&&(o=r.calc(e,n))}Array.isArray(o)&&o[0]||(o=[{x:Jr,y:Jr}]),o[0].t||(o[0].t={}),o[0].trace=n,c[t]=o}}for(d&&ca(o),a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];r.attr("transform","translate("+p+")")}}}T.call(A),k&&(w?T.on(".opacity",null):(b=0,_=!0,T.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(mn.makeEditable,{gd:t}).on("edit",function(e){void 0!==c?D.call("restyle",t,l,e,c):D.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(A)}).on("input",function(e){this.text(e||" ").call(mn.positionText,f.x,f.y)}));return T.classed("js-placeholder",_),p}},fa=/ [XY][0-9]* /;var da=r.FP_SAFE,ha=ya,pa=ma,ga=function(e){e._length||e.setScale();var t,n=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&n&&(e.range=ya(e),e._r=e.range.slice(),e._rl=rt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var r=e._anchorAxis.rangeslider[e._name];r&&"auto"===r.rangemode&&(r.range=n?ya(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=rt.extendFlat({},r)}},va=function(e,t,r){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!t)return;e._min||(e._min=[]);e._max||(e._max=[]);r||(r={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=t.length,y=r.padded||!1,m=r.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((e._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),T=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-da&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var A=m&&0===a;v.push({val:a,pad:A?0:b,extrapad:!A&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)A(a)};function ya(e){var t,n,r,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=ma(e);for(t=1;t0&&l>0&&s/l>d&&(i=r,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),rt.simpleMap(c,e.l2r||Number)}function ma(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function xa(e){return n(e)&&Math.abs(e)=t}var wa=r.BADNUM,ka=function(e,t){return function(e,t){for(var r,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,t)?"date":function(e){for(var t,n=Math.max(1,(e.length-1)/1e3),r=0,a=0,i=0;i2*r}(e)?"category":function(e){if(!e)return!1;for(var t=0;t0)return Math.log(e)/Math.LN10;if(e<=0&&n&&t.range&&2===t.range.length){var r=t.range[0],a=t.range[1];return.5*(r+a-3*i*Math.abs(r-a))}return Sa}function l(e,r,a){var i=Aa(e,a||t.calendar);if(i===Sa){if(!n(e))return Sa;i=Aa(new Date(+e))}return i}function s(e,n,r){return Ta(e,n,r||t.calendar)}function c(e){return t._categories[Math.round(e)]}function u(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(n(e))return+e}function f(r){return n(r)?e.round(t._b+t._m*r,2):Sa}function d(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:La,t.l2c="log"===t.type?Oa:La,t.l2p=f,t.p2l=d,t.c2p="log"===t.type?function(e,t){return f(o(e,t))}:f,t.p2c="log"===t.type?function(e){return Oa(d(e))}:d,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Ma,t.c2d=t.c2r=t.l2d=t.l2r=La,t.d2p=t.r2p=function(e){return t.l2p(Ma(e))},t.p2d=t.p2r=d,t.cleanPos=La):"log"===t.type?(t.d2r=t.d2l=function(e,t){return o(Ma(e),t)},t.r2d=t.r2c=function(e){return Oa(Ma(e))},t.d2c=t.r2l=Ma,t.c2d=t.l2r=La,t.c2r=o,t.l2d=Oa,t.d2p=function(e,n){return t.l2p(t.d2r(e,n))},t.p2d=function(e){return Oa(d(e))},t.r2p=function(e){return t.l2p(Ma(e))},t.p2r=d,t.cleanPos=La):"date"===t.type?(t.d2r=t.r2d=rt.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,n,r){return t.l2p(l(e,0,r))},t.p2d=t.p2r=function(e,t,n){return s(d(e),t,n)},t.cleanPos=function(e){return rt.cleanDate(e,Sa,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var n=t._categories.length-1;return t._categoriesMap[e]=n,n}return Sa},t.r2d=t.c2d=t.l2d=c,t.d2r=t.d2l_noadd=u,t.r2c=function(e){var n=u(e);return void 0!==n?n:t.fraction2r(.5)},t.l2r=t.c2r=La,t.r2l=u,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(e){return c(d(e))},t.r2p=t.d2p,t.p2r=d,t.cleanPos=function(e){return"string"==typeof e&&""!==e?e:La(e)}),t.fraction2r=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return t.l2r(n+e*(r-n))},t.r2fraction=function(e){var n=t.r2l(t.range[0]),r=t.r2l(t.range[1]);return(t.r2l(e)-n)/(r-n)},t.cleanRange=function(e,r){r||(r={}),e||(e="range");var i,o,l=rt.nestedProperty(t,e).get();if(o=(o="date"===t.type?rt.dfltRange(t.calendar):"y"===a?ht.DFLTRANGEY:r.dfltRange||ht.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=rt.cleanDate(l[0],Sa,t.calendar),l[1]=rt.cleanDate(l[1],Sa,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!rt.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=rt.constrain(t.r2l(l[0]),rt.MIN_MS+1e3,rt.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!n(l[i])){if(!n(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Ca?l[i]=-Ca:l[i]>Ca&&(l[i]=Ca),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else rt.nestedProperty(t,e).set(o)},t.setScale=function(e){var n=r._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=pt.getFromId({_fullLayout:r},t.overlaying);t.domain=i.domain}var o=e&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===a?(t._offset=n.t+(1-t.domain[1])*n.h,t._length=n.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=n.l+t.domain[0]*n.w,t._length=n.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw r._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,n){var r,a,i,o,l=t.type,s="date"===l&&e[n+"calendar"];if(n in e){if(r=e[n],o=e._length||r.length,rt.isTypedArray(r)&&("linear"===l||"log"===l)){if(o===r.length)return r;if(r.subarray)return r.subarray(0,o)}for(a=new Array(o),i=0;i2e-6||((n-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},Va.saveRangeInitial=function(e,t){for(var n=Va.list(e,"",!0),r=!1,a=0;a.3*d||u(a)||u(i))){var h=r.dtick/2;e+=e+h.8){var o=Number(n.substr(1));i.exactYears>.8&&o%12==0?e=Va.tickIncrement(e,"M6","reverse")+1.5*Na:i.exactMonths>.8?e=Va.tickIncrement(e,"M1","reverse")+15.5*Na:e-=Na/2;var l=Va.tickIncrement(e,n);if(l<=r)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=Va.tickIncrement(h,l.dtick,!1,i),0;return{start:t.c2r(p,0,i),end:t.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},Va.prepTicks=function(e){var t=rt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var n,r=e.nticks;r||("category"===e.type?(n=e.tickfont?1.2*(e.tickfont.size||12):15,r=e._length/n):(n="y"===e._id.charAt(0)?40:80,r=rt.constrain(e._length/n,4,9)+1),"radialaxis"===e._name&&(r*=2)),"array"===e.tickmode&&(r*=100),Va.autoTicks(e,Math.abs(t[1]-t[0])/r),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),ti(e)},Va.calcTicks=function(e){Va.prepTicks(e);var t=rt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,n,r=e.tickvals,a=e.ticktext,i=new Array(r.length),o=rt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(n=0;nc&&t=r:s<=r)&&!(i.length>l||s===o);s=Va.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+t.substr(1)%12==0?"y":"m";else if(t>=Na&&i<=10||t>=15*Na)e._tickround="d";else if(t>=Ra&&i<=16||t>=Ia)e._tickround="M";else if(t>=Fa&&i<=19||t>=Ra)e._tickround="S";else{var o=e.l2r(r+t).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(n(t)||"L"===t.charAt(0)){var l=e.range.map(e.r2d||Number);n(t)||(t=Number(t.substr(1))),e._tickround=2-Math.floor(Math.log(t)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(ai(e.exponentformat)&&!ii(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function ni(e,t,n){var r=e.tickfont||{};return{x:t,dx:0,dy:0,text:n||"",fontSize:r.size,font:r.family,fontColor:r.color}}Va.autoTicks=function(e,t){var r;function a(e){return Math.pow(e,Math.floor(Math.log(t)/Math.LN10))}if("date"===e.type){e.tick0=rt.dateTick0(e.calendar);var i=2*t;i>Da?(t/=Da,r=a(10),e.dtick="M"+12*ei(t,r,Xa)):i>Ea?(t/=Ea,e.dtick="M"+ei(t,1,Za)):i>Na?(e.dtick=ei(t,Na,Qa),e.tick0=rt.dateTick0(e.calendar,!0)):i>Ia?e.dtick=ei(t,Ia,Za):i>Ra?e.dtick=ei(t,Ra,Wa):i>Fa?e.dtick=ei(t,Fa,Wa):(r=a(10),e.dtick=ei(t,r,Xa))}else if("log"===e.type){e.tick0=0;var o=rt.simpleMap(e.range,e.r2l);if(t>.7)e.dtick=Math.ceil(t);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/t);t=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=a(10),e.dtick="L"+ei(t,r,Xa)}else e.dtick=t>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(t,1))):"angular"===e._id?(e.tick0=0,r=1,e.dtick=ei(t,r,Ka)):(e.tick0=0,r=a(10),e.dtick=ei(t,r,Xa));if(0===e.dtick&&(e.dtick=1),!n(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},Va.tickIncrement=function(t,r,a,i){var o=a?-1:1;if(n(r))return t+o*r;var l=r.charAt(0),s=o*Number(r.substr(1));if("M"===l)return rt.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var c="D2"===r?$a:Ja,u=t+.01*o,f=rt.roundUp(rt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(r)},Va.tickFirst=function(t){var r=t.r2l||Number,a=rt.simpleMap(t.range,r),i=a[1]"+l,e._prevDateHead=l));t.text=s}(e,o,r,s):"log"===e.type?function(e,t,r,a,i){var o=e.dtick,l=t.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))t.text=oi(Math.pow(10,l),e,i,a);else if(n(o)||"D"===o.charAt(0)&&rt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||ai(e.exponentformat)&&ii(c)?(t.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+Ba+-c+"",t.fontSize*=1.25):(t.text=oi(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(t.dy-=t.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);t.text=String(Math.round(Math.pow(10,rt.mod(l,1)))),t.fontSize*=.75}if("D1"===e.dtick){var u=String(t.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?t.dx-=t.fontSize/4:(t.dy+=t.fontSize/2,t.dx+=(e.range[1]>e.range[0]?1:-1)*t.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var n=e._categories[Math.round(t.x)];void 0===n&&(n="");t.text=String(n)}(e,o):"angular"===e._id?function(e,t,n,r,a){if("radians"!==e.thetaunit||n)t.text=oi(t.x,e,a,r);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var n=function(e){var n=1;for(;!t(Math.round(e*n)/n,e);)n*=10;return n}(e),r=e*n,a=Math.abs(function e(n,r){return t(r,0)?n:e(r,n%r)}(r,n));return[Math.round(r/a),Math.round(n/a)]}(i);if(o[1]>=100)t.text=oi(rt.deg2rad(t.x),e,a,r);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=Ba+t.text)}}}}(e,o,r,s,a):function(e,t,n,r,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=oi(t.x,e,a,r)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},Va.hoverLabelText=function(e,t,n){if(n!==ja&&n!==t)return Va.hoverLabelText(e,t)+" - "+Va.hoverLabelText(e,n);var r="log"===e.type&&t<=0,a=Va.tickText(e,e.c2l(r?-t:t),"hover").text;return r?0===t?"0":Ba+a:a};var ri=["f","p","n","\u03bc","m","","k","M","G","T"];function ai(e){return"SI"===e||"B"===e}function ii(e){return e>14||e<-15}function oi(e,t,r,a){var i=e<0,o=t._tickround,l=r||t.exponentformat||"B",s=t._tickexponent,c=Va.getTickFormat(t),u=t.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===t.showexponent?t.dtick:n(e)&&Math.abs(e)||1,range:"none"===t.showexponent?t.range.map(t.r2d):[0,e||1]};ti(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,t.hoverformat&&(c=t.hoverformat)}if(c)return t._numFormat(c)(e).replace(/-/g,Ba);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":ai(l)&&(e+=ri[s/3+5]));return i?Ba+e:e}function li(e,t){for(var n=0;n=0,i=c(e,t[1])<=0;return(n||a)&&(r||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(r))){n=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(r=1;r-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),void 0!==t.extraText&&(s+=(s?"
":"")+t.extraText),""===s&&(""===l&&n.remove(),s=l);var g=n.select("text.nums").call(Un.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(mn.positionText,0,0).call(mn.convertToTspans,r),y=n.select("text.name"),m=0;l&&l!==s?(y.call(Un.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(mn.positionText,0,0).call(mn.convertToTspans,r),m=y.node().getBoundingClientRect().width+2*yi):(y.remove(),n.select("rect").remove()),n.select("path").style({fill:d,stroke:h});var k,M,T=g.node().getBoundingClientRect(),A=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),O=T.width+vi+yi+m;t.ty0=x-T.top,t.bx=T.width+2*yi,t.by=T.height+2*yi,t.anchor="start",t.txwidth=T.width,t.tx2width=m,t.offset=0,i?(t.pos=A,k=L+S/2+O<=_,M=L-S/2-O>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=A+C/2+O<=b,M=A-C/2-O>=0,"left"!==t.idealAlign&&k||!M?k?(A+=C/2,t.anchor="start"):t.anchor="middle":(A-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),n.attr("transform","translate("+A+","+L+")"+(i?"rotate("+fi+")":""))}),C}function xi(t,n){t.each(function(t){var r=e.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(vi+yi),s=l+o*(t.txwidth+yi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+yi),n&&(u*=-gi,c=t.offset*pi),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*vi+c)+","+(vi+u)+"v"+(t.by/2-vi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*vi+c)+"V"+(u-vi)+"Z"),i.call(mn.positionText,l+c,u+t.ty0-t.by/2+yi),t.tx2width&&(r.select("text.name").call(mn.positionText,s+o*yi+c,u+t.ty0-t.by/2+yi),r.select("rect").call(Un.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function bi(e,t){var n=e.index,r=e.trace||{},a=e.cd[0],i=e.cd[n]||{},o=Array.isArray(n)?function(e,t){return rt.castOption(a,n,e)||rt.extractOption({},r,"",t)}:function(e,t){return rt.extractOption(i,r,e,t)};function l(t,n,r){var a=o(n,r);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=rt.constrain(e.x0,0,e.xa._length),e.x1=rt.constrain(e.x1,0,e.xa._length),e.y0=rt.constrain(e.y0,0,e.ya._length),e.y1=rt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:za.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:za.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=za.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+za.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=za.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+za.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function _i(e,t){var n,r,a=t.container,i=t.fullLayout,o=t.event,l=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||l){var u=Nt.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var f,d,h=e.hLinePoint;n=h&&h.xa,"cursor"===(r=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=n._offset+h.x,d=r._offset+h.y);var p,g,v=s.readability(h.color,u)<1.5?Nt.contrast(u):h.color,y=r.spikemode,m=r.spikethickness,x=r.spikecolor||v,b=r._boundingBox,_=(b.left+b.right)/2V.width||H<0||H>V.height)return Ot.unhoverRaw(t,r);r.pointerX=r.offsetX,r.pointerY=r.offsetY}if(_="xval"in r?cr.flat(o,r.xval):cr.p2c(h,j),w="yval"in r?cr.flat(o,r.yval):cr.p2c(p,H),!n(_[0])||!n(w[0]))return rt.warn("Fx.hover failed",r,t),Ot.unhoverRaw(t,r)}var U=1/0;for(M=0;ME&&(R.splice(0,E),U=R[0].distance),u&&0!==I&&0===R.length){z.distance=I,z.index=!1;var W=A._module.hoverPoints(z,O,P,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=I})),W&&W.length){var Q,J=W.filter(function(e){return e.xa.showspikes});if(J.length){var $=J[0];n($.x0)&&n($.y0)&&(Q=ne($),(!B.vLinePoint||B.vLinePoint.spikeDistance>Q.spikeDistance)&&(B.vLinePoint=Q))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];n(ee.x0)&&n(ee.y0)&&(Q=ne(ee),(!B.hLinePoint||B.hLinePoint.spikeDistance>Q.spikeDistance)&&(B.hLinePoint=Q))}}}}function te(e,t){for(var n,r=null,a=1/0,i=0;i1,ge=Nt.combine(l.plot_bgcolor||Nt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=mi(R,ve,t);if(function(e,t,n){var r,a,i,o,l,s,c,u=0,f=e.map(function(e,r){var a=e[t];return[{i:r,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?hi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?n.width:n.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],n=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=n.pos+n.dp+n.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;r=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;r=!1}if(r){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!r&&u<=e.length;){for(u++,r=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;r=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(R,pe?"xa":"ya",l),xi(ye,pe),r.target&&r.target.tagName){var me=D.getComponentMethod("annotations","hasClickToShow")(t,de);gr(e.select(r.target),me?"pointer":"")}if(!r.target||i||!function(e,t,n){if(!n||n.length!==e._hoverdata.length)return!0;for(var r=n.length-1;r>=0;r--){var a=n[r],i=e._hoverdata[r];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,fe))return;fe&&t.emit("plotly_unhover",{event:r,points:fe});t.emit("plotly_hover",{event:r,points:t._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(t,r,a,i)})},ui.loneHover=function(t,n){var r={color:t.color||Nt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(n.container),i=n.outerContainer?e.select(n.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:n.bgColor||Nt.background,container:a,outerContainer:i},l=mi([r],o,n.gd);return xi(l,o.rotateLabels),l.node()};var ki=ui.hover,Mi=function(e,t,n,r){n("hoverlabel.bgcolor",(r=r||{}).bgcolor),n("hoverlabel.bordercolor",r.bordercolor),n("hoverlabel.namelength",r.namelength),rt.coerceFont(n,"hoverlabel.font",r.font)},Ti=L({editType:"none"});Ti.family.dflt=bt.HOVERFONT,Ti.size.dflt=bt.HOVERFONTSIZE;var Ai={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Ti,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var Li={moduleType:"component",name:"fx",constants:bt,schema:{layout:Ai},attributes:C,layoutAttributes:Ai,supplyLayoutGlobalDefaults:function(e,t){Mi(0,0,function(n,r){return rt.coerce(e,t,Ai,n,r)})},supplyDefaults:function(e,t,n,r){Mi(0,0,function(n,r){return rt.coerce(e,t,C,n,r)},r.hoverlabel)},supplyLayoutDefaults:function(e,t,n){function r(n,r){return rt.coerce(e,t,Ai,n,r)}var a;"select"===r("dragmode")&&r("selectdirection"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,n=0;n0})}function c(e,r){var a=e.seg,i=r.seg,o=a.start,s=a.end,c=i.start,u=i.end;n&&n.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return r;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(r,s):l(e,u),r;p&&(h||(g?l(r,s):l(e,u)),l(r,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(r,o):0===f.alongA?l(r,f.pt):1===f.alongA&&l(r,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(n&&n.vert(f.pt[0]),f.isStart){n&&n.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}n&&n.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,n&&n.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){n&&n.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:r,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:r,f.seg.otherFill={above:v,below:v}),n&&n.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(Di.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),n&&n.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return n&&n.done(),u}return e?{addRegion:function(e){for(var r,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,n,r){var a=t[1]-n[1],i=r[0]-n[0],o=t[0]-n[0],l=r[1]-n[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,n){return Math.abs(t[0]-n[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-r>e&&(l=!l),i=c,o=u}return l}};return t}();function Hi(e,t,n){var r=Ri.segments(e),a=Ri.segments(t),i=n(Ri.combine(r,a));return Ri.polygon(i)}Ri={buildLog:function(e){return!0===e?Bi=Pi():!1===e&&(Bi=!1),!1!==Bi&&Bi.list},epsilon:function(e){return ji.epsilon(e)},segments:function(e){var t=Ei(!0,ji,Bi);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Ei(!1,ji,Bi).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:Fi.union(e.combined,Bi),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:Fi.intersect(e.combined,Bi),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:Fi.difference(e.combined,Bi),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:Fi.differenceRev(e.combined,Bi),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:Fi.xor(e.combined,Bi),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Ni(e.segments,ji,Bi),inverted:e.inverted}},polygonFromGeoJSON:function(e){return zi.toPolygon(Ri,e)},polygonToGeoJSON:function(e){return zi.fromPolygon(Ri,ji,e)},union:function(e,t){return Hi(e,t,Ri.selectUnion)},intersect:function(e,t){return Hi(e,t,Ri.selectIntersect)},difference:function(e,t){return Hi(e,t,Ri.selectDifference)},differenceRev:function(e,t){return Hi(e,t,Ri.selectDifferenceRev)},xor:function(e,t){return Hi(e,t,Ri.selectXor)}},"object"==typeof window&&(window.PolyBool=Ri);var qi,Vi=Ri,Ui=He.dot,Gi=r.BADNUM,Yi=qi={};Yi.tester=function(e){if(Array.isArray(e[0][0]))return Yi.multitester(e);var t,n=e.slice(),r=n[0][0],a=r,i=n[0][1],o=i;for(n.push(n[0]),t=1;ta||s===Gi||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===Gi||la||s===Gi||so)return!1;var c,u,f,d,h,p=n.length,g=n[0][0],v=n[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(Ui(i,f))>r)return!0;return!1};Yi.filter=function(e,t){var n=[e[0]],r=0,a=0;function i(i){e.push(i);var o=n.length,l=r;n.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:n}};var Zi=cr.makeEventData,Wi=pt.getFromId,Qi=Wr,Ji=ht.MINSELECT,$i=qi.filter,Ki=qi.tester,eo=qi.multitester;function to(e){return e._id}function no(e,t,n){var r,a,i,o;if(n){var l=n.points||[];for(r=0;r=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function wo(e,t,n,r,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+n+", "+r+")").attr("d",a+"Z")}function ko(e,t,n){return e.append("path").attr("class","zoombox-corners").style({fill:Nt.background,stroke:Nt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+n+")").attr("d","M0,0Z")}function Mo(e,t,n,r,a,i){e.attr("d",r+"M"+n.l+","+n.t+"v"+n.h+"h"+n.w+"v-"+n.h+"h-"+n.w+"Z"),To(e,t,a,i)}function To(e,t,n,r){n||(e.transition().style("fill",r>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function Ao(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Lo(e){go&&e.data&&e._context.showTips&&(rt.notifier(rt._(e,"Double-click to zoom back out"),"long"),go=!1)}function Co(e){return"lasso"===e||"select"===e}function So(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,po)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function Oo(e,t){if(vt){var n=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(n,e._onwheel),e._onwheel=t,e.addEventListener(n,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}function Po(e){var t=[];for(var n in e)t.push(e[n]);return t}var zo={},Do=function(t,n,r,a,i,o,l,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k,M,T,A,L=t._fullLayout._zoomlayer,C=l+c==="nsew",S=1===(l+c).length;function O(){if(u=n.xaxis,f=n.yaxis,m=u._length,x=f._length,v=u._offset,y=f._offset,(d={})[u._id]=u,(h={})[f._id]=f,l&&c)for(var e=n.overlays,r=0;rpo||o>po?(j="xy",i/m>o/x?(o=i*x/m,N>a?I.t=N-o:I.b=N+o):(i=o*m/x,E>r?I.l=E-i:I.r=E+i),q.attr("d",So(I))):l():!w||o10||n.scrollWidth-n.clientWidth>10)){clearTimeout(Z);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var a,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),o=Q.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(T){for(c||(s=.5),a=0;a0;o&&(a="array");var l,s=n("categoryorder",a);"array"===s&&(l=n("categoryarray")),o||"array"!==s||(s=t.categoryorder="trace"),"trace"===s?t._initialCategories=[]:"array"===s?t._initialCategories=l.slice():(l=function(e,t){var n,r,a,i=t.dataAttr||e._id.charAt(0),o={};if(t.axData)n=t.axData;else for(n=[],r=0;rp[1]-.01&&(t.domain=o),rt.noneOrAll(e.domain,t.domain,o)}return r("layer"),t},qo=pt.name2id,Vo=function(e,t,n,r,a){a&&(t._name=a,t._id=qo(a)),"-"===n("type")&&(!function(e,t){if("-"!==e.type)return;var n=e._id,r=n.charAt(0);-1!==n.indexOf("scene")&&(n=r);var a=function(e,t,n){for(var r=0;r0&&a["_"+n+"axes"][t])return a;if((a[n+"axis"]||n)===t){if(Go(a,n))return a;if((a[n]||[]).length||a[n+"0"])return a}}}(t,n,r);if(!a)return;if("histogram"===a.type&&r==={v:"y",h:"x"}[a.orientation||"v"])return void(e.type="linear");var i,o=r+"calendar",l=a[o];if(Go(a,r)){var s=Uo(a),c=[];for(i=0;i rect").call(Un.setTranslate,0,0).call(Un.setScale,1,1),e.plot.call(Un.setTranslate,t._offset,n._offset).call(Un.setScale,1,1);var r=e.plot.selectAll(".scatterlayer .trace");r.selectAll(".point").call(Un.setPointGroupScale,1,1),r.selectAll(".textpoint").call(Un.setTextPointsScale,1,1),r.call(Un.hideOutsideRangePoints,e)}function g(e,n){var r,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(r=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-n)+n*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[2]=e.xaxis._length*(1-n+n*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(r=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-n)+n*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[3]=e.yaxis._length*(1-n+n*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,n){var r,a=[];for(a=[e._id,n._id],r=0;rr.duration?(function(){for(var e={},n=0;n.01?T:function(e,t){return Math.abs(e-t)>=2?T(e):e>t?Math.ceil(e):Math.floor(e)};p=k(p,h=k(h,p)),v=k(v,g=k(g,v))}var M=e.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+h+","+g+"V"+v+"H"+p+"V"+g+"Z").call(Un.setClipUrl,r.layerClipId),function(e,t,n,r,a,i,o,l){var s;function c(t,n,r){var a=t.append("text").text(n).attr({class:"bartext bartext-"+s,transform:"","text-anchor":"middle","data-notex":1}).call(Un.font,r).call(mn.convertToTspans,e);return a}var u=n[0].trace,f=u.orientation,d=function(e,t){var n=Cl(e.text,t);return Sl(xl,n)}(u,r);if(!d)return;if("none"===(s=function(e,t){var n=Cl(e.textposition,t);return function(e,t,n){return e.coerceNumber&&(t=+t),-1!==e.values.indexOf(t)?t:void 0!==n?n:e.dflt}(bl,n)}(u,r)))return;var h,p,g,v,y,m,x=function(e,t,n){return Ll(_l,e.textfont,t,n)}(u,r,e._fullLayout.font),b=function(e,t,n){return Ll(wl,e.insidetextfont,t,n)}(u,r,x),_=function(e,t,n){return Ll(kl,e.outsidetextfont,t,n)}(u,r,x),w=e._fullLayout.barmode,k="stack"===w||"relative"===w,M=n[r],T=!k||M._outmost,A=Math.abs(i-a)-2*Ml,L=Math.abs(l-o)-2*Ml;"outside"===s&&(T||(s="inside"));if("auto"===s)if(T){s="inside",h=c(t,d,b),p=Un.bBox(h.node()),g=p.width,v=p.height;var C=g>0&&v>0,S=g<=A&&v<=L,O=g<=L&&v<=A,P="h"===f?A>=g*(L/v):L>=v*(A/g);C&&(S||O||P)?s="inside":(s="outside",h.remove(),h=null)}else s="inside";if(!h&&(h=c(t,d,"outside"===s?_:b),p=Un.bBox(h.node()),g=p.width,v=p.height,g<=0||v<=0))return void h.remove();"outside"===s?(m="both"===u.constraintext||"outside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s="h"===i?Math.abs(r-n):Math.abs(t-e);s>2*Ml&&(l=Ml);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,h,p=(a.left+a.right)/2,g=(a.top+a.bottom)/2;u=c*a.width,f=c*a.height,"h"===i?tn?(d=(e+t)/2,h=r+l+f/2):(d=(e+t)/2,h=r-l-f/2);return Al(p,g,d,h,c,!1)}(a,i,o,l,p,f,m)):(m="both"===u.constraintext||"inside"===u.constraintext,y=function(e,t,n,r,a,i,o){var l,s,c,u,f,d,h,p=a.width,g=a.height,v=(a.left+a.right)/2,y=(a.top+a.bottom)/2,m=Math.abs(t-e),x=Math.abs(r-n);m>2*Ml&&x>2*Ml?(m-=2*(f=Ml),x-=2*f):f=0;p<=m&&g<=x?(d=!1,h=1):p<=x&&g<=m?(d=!0,h=1):pn?(c=(e+t)/2,u=r-f-s/2):(c=(e+t)/2,u=r+f+s/2);return Al(v,y,c,u,h,d)}(a,i,o,l,p,f,m));h.attr("transform",y)}(t,M,a,c,h,p,g,v),r.layerClipId&&Un.hideOutsideRangePoint(a[c],M.select("text"),i,o,u.xcalendar,u.ycalendar)}else e.select(this).remove();function T(t){return 0===l.bargap&&0===l.bargroupgap?e.round(Math.round(t)-w,2):t}})}),D.getComponentMethod("errorbars","plot")(s,r),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Un.setClipUrl(e.select(this),n?null:r.layerClipId)})};function Al(e,t,n,r,a,i){var o;return a<1?o="scale("+a+") ":(a=1,o=""),"translate("+(n-a*e)+" "+(r-a*t)+")"+o+(i?"rotate("+i+" "+e+" "+t+") ":"")}function Ll(e,t,r,a){var i=Cl((t=t||{}).family,r),o=Cl(t.size,r),l=Cl(t.color,r);return{family:Sl(e.family,i,a.family),size:function(e,t,r){if(n(t)){t=+t;var a=e.min,i=e.max,o=void 0!==a&&ti;if(!o)return t}return void 0!==r?r:e.dflt}(e.size,o,a.size),color:function(e,t,n){return s(t).isValid()?t:void 0!==n?n:e.dflt}(e.color,l,a.color)}}function Cl(e,t){var n;return Array.isArray(e)?tc+l||!n(s))&&(f=!0,Vl(u,e))}for(var h=0;h1||0===i.bargap&&0===i.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(n){var r=e.select(this),a=r.selectAll("path"),i=r.selectAll("text"),o=n[0].trace;Un.pointStyle(a,o,t),Un.selectedPointStyle(a,o),i.each(function(t){var n,r=e.select(this);function a(e){var r=n[e];return Array.isArray(r)?r[t.i]:r}r.classed("bartext-inside")?n=o.insidetextfont:r.classed("bartext-outside")&&(n=o.outsidetextfont),n||(n=o.textfont),Un.font(r,a("family"),a("size"),a("color"))}),Un.selectedTextStyle(i,o)}),D.getComponentMethod("errorbars","style")(r)},Wl=m.extendFlat,Ql=vn.LINE_SPACING,Jl={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},$l=function(t,r){var a=r[0].trace,i=a.marker,o="cb"+a.uid;if(t._fullLayout._infolayer.selectAll("."+o).remove(),void 0!==i&&i.showscale){var l=i.color,c=i.cmin,u=i.cmax;n(c)||(c=rt.aggNums(Math.min,null,l)),n(u)||(u=rt.aggNums(Math.max,null,l));var f=r[0].t.cb=function(t,n){var r={};function a(){var o=t._fullLayout,l=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var c,u,f=e.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),d=[],h=[],p="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,y=r.levels.size,m=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(u=0;u<1e5&&(c=r.levels.start+u*y,!(y>0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var q=Math.pow(10,Math.floor(Math.log(H)/Math.LN10));B*=q*rt.roundUp(H/q,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(R.tick0=0)}R.dtick=B}R.domain=[z+S,z+A-S],R.setScale();var V=rt.ensureSingle(o._infolayer,"g",n,function(t){t.classed(Jl.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(Jl.cbbg,!0),t.append("g").classed(Jl.cbfills,!0),t.append("g").classed(Jl.cblines,!0),t.append("g").classed(Jl.cbaxis,!0).classed(Jl.crisp,!0),t.append("g").classed(Jl.cbtitleunshift,!0).append("g").classed(Jl.cbtitle,!0),t.append("rect").classed(Jl.cboutline,!0),t.select(".cbtitle").datum(0)})});V.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");R._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var Y,X=l.l+(r.x+L)*l.w,Z=R.titlefont.size;Y="top"===r.titleside?(1-(z+A-S))*l.h+l.t+3+.75*Z:(1-(z+S))*l.h+l.t-3-.25*Z,ee(R._id+"title",{attributes:{x:X,y:Y,"text-anchor":"start"}})}var W,Q,J,$=rt.syncOrAsync([Qr.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var n=V.select(".cbtitle"),a=n.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],c=n.select(".h"+R._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*Ql),c?(G=Un.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(Jl.jsPlaceholder)&&(G=Un.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)R.domain[1]-=G/l.h,i[1]*=-1;else{R.domain[0]+=G/l.h;var v=mn.lineCount(a);i[1]+=(1-v)*u}n.attr("transform","translate("+i+")"),R.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-R.domain[1]))+")"),R._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(Jl.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,n){var r=[0===n?f[0]:(h[n]+h[n-1])/2,n===h.length-1?f[1]:(h[n]+h[n+1])/2].map(R.c2p).map(Math.round);n!==h.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=s(a).toHexString();e.select(this).attr({x:O,width:Math.max(k,2),y:e.min(r),height:Math.max(e.max(r)-e.min(r),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?d:[]);return m.enter().append("path").classed(Jl.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+O+","+(Math.round(R.c2p(t))+r.line.width/2%1)+"h"+k).call(Un.lineGroupStyle,r.line.width,p(t),r.line.dash)}),R._axislayer.selectAll("g."+R._id+"tick,path").remove(),R._pos=O+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),R.side="right",rt.syncOrAsync([function(){return za.doTicks(t,R,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var n=R.titlefont.size,a=R._offset+R._length/2,i=l.l+(R.position||0)*l.w+("right"===R.side?10+n*(R.showticklabels?1:.5):-10-n*(R.showticklabels?.5:0));ee("h"+R._id+"title",{avoid:{selection:e.select(t).selectAll("g."+R._id+"tick"),side:r.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Qr.previousPromises,function(){var e=k+r.outlinewidth/2+Un.bBox(R._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(Jl.jsPlaceholder)){var a,i=U.select(".h"+R._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Un.bBox(i).width:Un.bBox(U.node()).right-O-l.l,e=Math.max(e,a)}var o=2*r.xpad+e+r.borderwidth+r.outlinewidth/2,s=E-N;V.select(".cbbg").attr({x:O-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:N-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(Nt.fill,r.bgcolor).call(Nt.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),V.selectAll(".cboutline").attr({x:O,y:N+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(s-2*r.ypad-G,2)}).call(Nt.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*o;V.attr("transform","translate("+(l.l-c)+","+l.t+")"),Qr.autoMargin(t,n,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:s*({bottom:1,middle:.5}[r.yanchor]||0),b:s*({top:1,middle:.5}[r.yanchor]||0)})}],t);return $&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition&&Ot.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),hr(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),Q=Ot.align(P+e/l.w,M,0,1,r.xanchor),J=Ot.align(z-t/l.h,A,0,1,r.yanchor);var n=Ot.getCursor(Q,J,r.xanchor,r.yanchor);hr(V,n)},doneFn:function(){hr(V),void 0!==Q&&void 0!==J&&D.call("restyle",t,{"colorbar.x":Q,"colorbar.y":J},i().index)}}),$}function K(e,t){return rt.coerce(I,R,nn,e,t)}function ee(e,n){var r,a=i();r=D.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:R,propName:r,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),ua.draw(t,e,Wl(l,n||{}))}o._infolayer.selectAll("g."+n).remove()}function i(){var e,r,a=n.substr(2);for(e=0;ee.uf}),i=Math.max((e.max-e.min)/10,e.q3-e.q1),c=1e-9*i,u=i*is,f=[],d=0;if(n.jitter){if(0===i)for(d=1,f=new Array(a.length),t=0;te.lo&&(m.so=!0)}return a}).enter().append("path").classed("point",!0).call(Un.translatePoints,a,i)}function ss(t,n,r,a){var i,o,l=n.pos,s=n.val,c=a.bPos,u=a.bPosPxOffset||0;Array.isArray(a.bdPos)?(i=a.bdPos[0],o=a.bdPos[1]):(i=a.bdPos,o=a.bdPos),t.selectAll("path.mean").data(rt.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var n=l.c2p(t.pos+c,!0)+u,a=l.c2p(t.pos+c-i,!0)+u,f=l.c2p(t.pos+c+o,!0)+u,d=s.c2p(t.mean,!0),h=s.c2p(t.mean-t.sd,!0),p=s.c2p(t.mean+t.sd,!0);"h"===r.orientation?e.select(this).attr("d","M"+d+","+a+"V"+f+("sd"===r.boxmean?"m0,0L"+h+","+n+"L"+d+","+a+"L"+p+","+n+"Z":"")):e.select(this).attr("d","M"+a+","+d+"H"+f+("sd"===r.boxmean?"m0,0L"+n+","+h+"L"+a+","+d+"L"+n+","+p+"Z":""))})}var cs={plot:function(t,n,r){var a=t._fullLayout,i=n.xaxis,o=n.yaxis;n.plot.select(".boxlayer").selectAll("g.trace.boxes").data(r).enter().append("g").attr("class","trace boxes").each(function(t){var r=t[0],l=r.t,s=r.trace,c=e.select(this);n.isRangePlot||(r.node3=c);var u,f,d=a._numBoxes,h=1-a.boxgap,p="group"===a.boxmode&&d>1,g=l.dPos*h*(1-a.boxgroupgap)/(p?d:1),v=p?2*l.dPos*((l.num+.5)/d-.5)*h:0,y=g*s.whiskerwidth;!0!==s.visible||l.empty?c.remove():("h"===s.orientation?(u=o,f=i):(u=i,f=o),l.bPos=v,l.bdPos=g,l.wdPos=y,l.wHover=l.dPos*(p?h/d:1),os(c,{pos:u,val:f},s,l),s.boxpoints&&ls(c,{x:i,y:o},s,l),s.boxmean&&ss(c,{pos:u,val:f},s,l))})},plotBoxAndWhiskers:os,plotPoints:ls,plotBoxMean:ss},us=["v","h"];function fs(e,t,n,r,a){var i,o,l,s=t.calcdata,c=t._fullLayout,u=[],f="violin"===e?"_numViolins":"_numBoxes";for(i=0;if):u=m>g,f=m;var x=a(g,v,y,m);x.pos=p,x.yc=(g+m)/2,x.i=h,x.dir=u?"increasing":"decreasing",c&&(x.tx=t.text[h]),d.push(x)}}return za.expand(r,l.concat(o),{padded:!0}),d.length&&(d[0].t={labels:{open:Ts(e,"open:")+" ",high:Ts(e,"high:")+" ",low:Ts(e,"low:")+" ",close:Ts(e,"close:")+" "}}),d}var Ss={calc:function(e,t){var n=za.getFromId(e,t.xaxis),r=za.getFromId(e,t.yaxis),a=function(e,t,n){var r=n._minDiff;if(!r){var a,i=e._fullData,o=[];for(r=1/0,a=0;a"),e.y0=e.y1=o.c2p(k.yc,!0),[e]},Is=function(e,t){var n,r=e.cd,a=e.xaxis,i=e.yaxis,o=[],l=r[0].t.bPos||0;if(!1===t)for(n=0;n1)for(var n=1;n=0,p=n.indexOf("end")>=0,g=c.backoff*f+r.standoff,v=u.backoff*d+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}n._w=C,n._h=S;for(var E=!1,N=["x","y"],I=0;I1)&&(U===V?((K=G.r2fraction(n["a"+q]))<0||K>1)&&(E=!0):E=!0,E))continue;R=G._offset+G.r2p(n[q]),j=.5}else"x"===q?(B=n[q],R=u.l+u.w*B):(B=1-n[q],R=u.t+u.h*B),j=n.showarrow?.5:B;if(n.showarrow){$.head=R;var ee=n["a"+q];H=X*z(.5,n.xanchor)-Z*z(.5,n.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=H):($.tail=R+ee,F=H+ee),$.text=$.tail+H;var te=c["x"===q?"width":"height"];if("paper"===V&&($.head=rt.constrain($.head,1,te-1)),"pixel"===U){var ne=-Math.max($.tail-3,$.text),re=Math.min($.tail+3,$.text)-te;ne>0?($.tail+=ne,$.text+=ne):re>0&&($.tail-=re,$.text-=re)}$.tail+=J,$.head+=J}else F=H=W*z(j,Q),$.text=R+H;$.text+=J,H+=J,F+=J,n["_"+q+"padplus"]=W/2+F,n["_"+q+"padminus"]=W/2-F,n["_"+q+"size"]=W,n["_"+q+"shift"]=H}if(E)x.remove();else{var ae=0,ie=0;if("left"!==n.align&&(ae=(C-_)*("center"===n.align?.5:1)),"top"!==n.valign&&(ie=(S-A)*("middle"===n.valign?.5:1)),l)r.select("svg").attr({x:w+ae-1,y:w+ie}).call(Un.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(mn.positionText,le,oe).call(Un.setClipUrl,M?d:null)}T.select("rect").call(Un.setRect,w,w,C,S),k.call(Un.setRect,b/2,b/2,O-b,P-b),x.call(Un.setTranslate,Math.round(h.x.text-O/2),Math.round(h.y.text-P/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,r){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+r,m=h.x.text+e,b=h.y.text+r,_=rt.rotationXYMatrix(p,m,b),w=rt.apply2DTransform(_),M=rt.apply2DTransform2(_),T=+k.attr("width"),A=+k.attr("height"),L=m-.5*T,C=L+T,S=b-.5*A,O=S+A,P=[[L,S,L,O],[L,O,C,O],[C,O,C,S],[C,S,L,S]].map(M);if(!P.reduce(function(e,t){return e^!!rt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){P.forEach(function(e){var t=rt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var z=n.arrowwidth,E=n.arrowcolor,N=n.arrowside,I=g.append("g").style({opacity:Nt.opacity(E)}).classed("annotation-arrow-g",!0),R=I.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",z+"px").call(Nt.stroke,Nt.rgb(E));if(oc(R,N,n),f.annotationPosition&&R.node().parentNode&&!a){var F=l,B=c;if(n.standoff){var j=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=n.standoff*(d-l)/j,B+=n.standoff*(y-c)/j}var H,q,V,U=I.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-B),transform:"translate("+F+","+B+")"}).style("stroke-width",z+6+"px").call(Nt.stroke,"rgba(0,0,0,0)").call(Nt.fill,"rgba(0,0,0,0)");Ot.init({element:U.node(),gd:t,prepFn:function(){var e=Un.getTranslate(x);q=e.x,V=e.y,H={},i&&i.autorange&&(H[i._name+".autorange"]=!0),o&&o.autorange&&(H[o._name+".autorange"]=!0)},moveFn:function(e,t){var r=w(q,V),a=r[0]+e,l=r[1]+t;x.call(Un.setTranslate,a,l),H[s+".x"]=i?i.p2r(i.r2p(n.x)+e):n.x+e/u.w,H[s+".y"]=o?o.p2r(o.r2p(n.y)+t):n.y-t/u.h,n.axref===n.xref&&(H[s+".ax"]=i.p2r(i.r2p(n.ax)+e)),n.ayref===n.yref&&(H[s+".ay"]=o.p2r(o.r2p(n.ay)+t)),I.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){D.call("relayout",t,H);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(n.showarrow&&ue(0,0),y)Ot.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var r="pointer";if(n.showarrow)n.axref===n.xref?se[s+".ax"]=i.p2r(i.r2p(n.ax)+e):se[s+".ax"]=n.ax+e,n.ayref===n.yref?se[s+".ay"]=o.p2r(o.r2p(n.ay)+t):se[s+".ay"]=n.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(n.x)+e);else{var l=n._xsize/u.w,c=n.x+(n._xshift-n.xshift)/u.w-l/2;se[s+".x"]=Ot.align(c+e/u.w,l,0,1,n.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(n.y)+t);else{var f=n._ysize/u.h,d=n.y-(n._yshift+n.yshift)/u.h-f/2;se[s+".y"]=Ot.align(d-t/u.h,f,0,1,n.yanchor)}i&&o||(r=Ot.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],n.xanchor,n.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),hr(x,r)},doneFn:function(){hr(x),D.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var uc=lc.draw;function fc(e){var t=e._fullLayout;rt.filterVisible(t.annotations).forEach(function(t){var n,r,a,i,o=za.getFromId(e,t.xref),l=za.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(n=s+t.xshift,r=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(za.expand(o,[o.r2c(t.x)],{ppadplus:n,ppadminus:r}),za.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,za.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,n,a),ppadminus:Math.max(t._xpadminus,r,i)}))),l&&l.autorange&&(n=s-t.yshift,r=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(za.expand(l,[l.r2c(t.y)],{ppadplus:n,ppadminus:r}),za.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,za.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,n,a),ppadminus:Math.max(t._ypadminus,r,i)})))})}var dc={hasClickToShow:function(e,t){var n=hc(e,t);return n.on.length>0||n.explicitOff.length>0},onClick:function(e,t){var n,r=hc(e,t),a=r.on,i=r.off.concat(r.explicitOff),o={};if(!a.length&&!i.length)return;for(n=0;n1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=Mc(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*n[0],t.yaxis.r2l(i.y)*n[1],t.zaxis.r2l(i.z)*n[2]]),Tc(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var Cc={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},Sc=function(e){var t=e.type,n=e.symmetric;if("data"===t){var r=e.array||[];if(n)return function(e,t){var n=+r[t];return[n,n]};var a=e.arrayminus||[];return function(e,t){var n=+r[t],i=+a[t];return isNaN(n)&&isNaN(i)?[NaN,NaN]:[i||0,n||0]}}var i=Oc(t,e.value),o=Oc(t,e.valueminus);return n||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function Oc(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var Pc=function(e){for(var t=e.calcdata,n=0;n0;t.each(function(t){var s,c=t[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Vn.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(t=[]);var h=e.select(this).selectAll("g.errorbar").data(t,s);if(h.exit().remove(),t.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Un.setClipUrl(h,r.layerClipId),h.each(function(t){var r=e.select(this),s=function(e,t,r){var a={x:t.c2p(e.x),y:r.c2p(e.y)};return void 0!==e.yh&&(a.yh=r.c2p(e.yh),a.ys=r.c2p(e.ys),n(a.ys)||(a.noYS=!0,a.ys=r.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=t.c2p(e.xh),a.xs=t.c2p(e.xs),n(a.xs)||(a.noXS=!0,a.xs=t.c2p(e.xs,!0))),a}(t,i,o);if(!d||t.vis){var c,h=r.select("path.yerror");if(f.visible&&n(s.x)&&n(s.yh)&&n(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=r.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=r.select("path.xerror");if(u.visible&&n(s.y)&&n(s.xh)&&n(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=r.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var n=t[0].trace,r=n.error_y||{},a=n.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(Nt.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(Nt.stroke,a.color)})},hoverInfo:function(e,t,n){(t.error_y||{}).visible&&(n.yerr=e.yh-e.y,t.error_y.symmetric||(n.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(n.xerr=e.xh-e.x,t.error_x.symmetric||(n.xerrneg=e.x-e.xs))}};var Rc={},Fc=m.extendFlat;Rc.attributes=function(e,t){e=e||{},t=t||{};var n={valType:"info_array",editType:e.editType,items:[{valType:"number",min:0,max:1,editType:e.editType},{valType:"number",min:0,max:1,editType:e.editType}],dflt:[0,1]},r=(e.name&&e.name,e.trace,t.description&&t.description,{x:Fc({},n,{}),y:Fc({},n,{}),editType:e.editType});return e.noGridCell||(r.row={valType:"integer",min:0,dflt:0,editType:e.editType},r.column={valType:"integer",min:0,dflt:0,editType:e.editType}),r},Rc.defaults=function(e,t,n,r){var a=r&&r.x||[0,1],i=r&&r.y||[0,1],o=t.grid;if(o){var l=n("domain.column");void 0!==l&&(l1){l||s||c||"independent"===x("pattern")&&(l=!0),f._hasSubplotGrid=l;var p,g,v="top to bottom"===x("roworder"),y=l?.2:.1,m=l?.3:.1;u&&(p="bottom",g="left"),f._domains={x:Uc("x",x,y,p,h),y:Uc("y",x,m,g,d,v)}}}function x(e,t){return rt.coerce(n,f,qc,e,t)}},contentDefaults:function(e,t){var n=t.grid;if(n&&n._domains){var r,a,i,o,l,s,c,u=e.grid||{},f=t._subplots,d=n._hasSubplotGrid,h=n.rows,p=n.columns,g="independent"===n.pattern,v=n._axisMap={};if(d){var y=u.subplots||[];s=n.subplots=new Array(h);var m=1;for(r=0;r=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},Kc={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},eu=!0,tu=function(e,t,n){if(!t._dragged&&!t._editing){var r,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===n&&eu&&t.data&&t._context.showTips?(rt.notifier(rt._(t,"Double-click on legend to isolate one trace"),"long"),eu=!1):eu=!1,D.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===n?-1===m?s.push(y):s.splice(m,1):2===n&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),D.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(r=0;rn[1])return n[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",rt.mean,[.2,1]),d.ms=u("marker.size",rt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",rt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),r=[rt.minExtend(i,d)],a=rt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Un.pointStyle,a,n),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Un.textPointStyle,a,n)}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(e,t){return t?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("stroke-width",i+"px").call(Nt.fill,a.fillcolor),i&&Nt.stroke(o,a.line.color)})}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(e,t){return t?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("fill","none").call(Un.dashLine,a.line.dash,i),i&&Nt.stroke(o,a.line.color)})})},ou=vn.LINE_SPACING,lu=vn.FROM_TL,su=vn.FROM_BR,cu=h.DBLCLICKDELAY;function uu(e,t){var n=e.data()[0][0],r=t._fullLayout,a=n.trace,i=D.traceIs(a,"pie"),o=a.index,l=i?n.label:a.name,s=rt.ensureSingle(e,"text","legendtext");function c(n){mn.convertToTspans(n,t,function(){!function(e,t){var n=e.data()[0][0];if(!n.trace.showlegend)return void e.remove();var r,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*ou;if(o){var s=Un.bBox(o);r=s.height,a=s.width,Un.setTranslate(i,0,r/4)}else{var c=e.select(".legendtext"),u=mn.lineCount(c),f=c.node();r=l*u,a=f?Un.bBox(f).width:0;var d=l*(.3+(1-u)/2);mn.positionText(c,40,d)}r=Math.max(r,16)+3,n.height=r,n.width=a}(e,t)})}s.attr("text-anchor","start").classed("user-select-none",!0).call(Un.font,r.legend.font).text(l),t._context.edits.legendText&&!i?s.call(mn.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var r=e;this.text()||(e=" ");var a=n.trace._fullInput||{},i={};if(D.hasTransform(a,"groupby")){var l=D.getTransformIndices(a,"groupby"),s=l[l.length-1],u=rt.keyedContainer(a,"transforms["+s+"].styles","target","value.name");""===r?u.remove(n.trace._group):u.set(n.trace._group,e),i=u.constructUpdate()}else i.name=e;return D.call("restyle",t,i,o)}):c(s)}function fu(e,t){var n,r=1,a=rt.ensureSingle(e,"rect","legendtoggle",function(e){e.style("cursor","pointer").attr("pointer-events","all").call(Nt.fill,"rgba(0,0,0,0)")});a.on("mousedown",function(){(n=(new Date).getTime())-t._legendMouseDownTimecu&&(r=Math.max(r-1,1)),1===r?n._clickTimeout=setTimeout(function(){tu(e,t,r)},cu):2===r&&(n._clickTimeout&&clearTimeout(n._clickTimeout),t._legendMouseDownTime=0,tu(e,t,r))}})}function du(t,n,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=Jc.isGrouped(i),s=0;if(i._width=0,i._height=0,Jc.isVertical(i))l&&n.each(function(e,t){Un.setTranslate(this,0,t*i.tracegroupgap)}),r.each(function(e){var t=e[0],n=t.height,r=t.width;Un.setTranslate(this,o,5+o+i._height+n/2),i._height+=n,i._width=Math.max(i._width,r)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=n.data(),f=0,d=u.length;fo+b-_,r.each(function(e){var t=e[0],n=g?40+e[0].width:m;o+x+_+n>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Un.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+n,i._height=Math.max(i._height,t.height),x+=_+n,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(n){var r=n[0],a=e.select(this).select(".legendtoggle");Un.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function hu(e){var t=e._fullLayout.legend,n="left";$c.isRightAnchor(t)?n="right":$c.isCenterAnchor(t)&&(n="center");var r="top";$c.isBottomAnchor(t)?r="bottom":$c.isMiddleAnchor(t)&&(r="middle"),Qr.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*lu[n],r:t._width*su[n],b:t._height*su[r],t:t._height*lu[r]})}var pu={moduleType:"component",name:"legend",layoutAttributes:Qc,supplyLayoutDefaults:function(e,t,n){for(var r,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),rt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(r=0,i="left",a=1.1,o="bottom"):(r=0,i="left",a=-.1,o="top")}h("traceorder",u),Jc.isGrouped(t.legend)&&h("tracegroupgap"),h("x",r),h("xanchor",i),h("y",a),h("yanchor",o),rt.noneOrAll(l,s,["x","y"])}},draw:function(t){var n=t._fullLayout,r="legend"+n._uid;if(n._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=n.legend,i=n.showlegend&&function(e,t){var n,r,a={},i=[],o=!1,l={},s=0;function c(e,n){if(""!==e&&Jc.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[n]]):a[e].push([n]);else{var r="~~i"+s;i.push(r),a[r]=[[n]],s++}}for(n=0;nv?function(e){var t=e._fullLayout.legend,n="left";$c.isRightAnchor(t)?n="right":$c.isCenterAnchor(t)&&(n="center"),Qr.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*lu[n],r:t._width*su[n],b:0,t:0})}(t):hu(t);var y=n._size,m=y.l+y.w*a.x,x=y.t+y.h*(1-a.y);$c.isRightAnchor(a)?m-=a._width:$c.isCenterAnchor(a)&&(m-=a._width/2),$c.isBottomAnchor(a)?x-=a._height:$c.isMiddleAnchor(a)&&(x-=a._height/2);var b=a._width,_=y.w;b>_?(m=y.l,b=_):(m+b>g&&(m=g-b),m<0&&(m=0),b=Math.min(g-m,a._width));var w,k,M,T,A=a._height,L=y.h;if(A>L?(x=y.t,A=L):(x+A>v&&(x=v-A),x<0&&(x=0),A=Math.min(v-x,a._height)),Un.setTranslate(s,m,x),d.on(".drag",null),s.on("wheel",null),a._height<=A||t._context.staticPlot)u.attr({width:b-a.borderwidth,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Un.setTranslate(f,0,0),c.select("rect").attr({width:b-2*a.borderwidth,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Un.setClipUrl(f,r),Un.setRect(d,0,0,0,0),delete a._scrollY;else{var C,S,O=Math.max(Kc.scrollBarMinHeight,A*A/a._height),P=A-O-2*Kc.scrollBarMargin,z=a._height-A,E=P/z,N=Math.min(a._scrollY||0,z);u.attr({width:b-2*a.borderwidth+Kc.scrollBarWidth+Kc.scrollBarMargin,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),c.select("rect").attr({width:b-2*a.borderwidth+Kc.scrollBarWidth+Kc.scrollBarMargin,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+N}),Un.setClipUrl(f,r),R(N,O,E),s.on("wheel",function(){R(N=rt.constrain(a._scrollY+e.event.deltaY/P*z,0,z),O,E),0!==N&&N!==z&&e.event.preventDefault()});var I=e.behavior.drag().on("dragstart",function(){C=e.event.sourceEvent.clientY,S=N}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||R(N=rt.constrain((t.clientY-C)/E+S,0,z),O,E)});d.call(I)}t._context.edits.legendPosition&&(s.classed("cursor-move",!0),Ot.init({element:s.node(),gd:t,prepFn:function(){var e=Un.getTranslate(s);M=e.x,T=e.y},moveFn:function(e,t){var n=M+e,r=T+t;Un.setTranslate(s,n,r),w=Ot.align(n,0,y.l,y.l+y.w,a.xanchor),k=Ot.align(r,0,y.t+y.h,y.t,a.yanchor)},doneFn:function(){void 0!==w&&void 0!==k&&D.call("relayout",t,{"legend.x":w,"legend.y":k})},clickFn:function(e,r){var a=n._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return r.clientX>=e.left&&r.clientX<=e.right&&r.clientY>=e.top&&r.clientY<=e.bottom});a.size()>0&&(1===e?s._clickTimeout=setTimeout(function(){tu(a,t,e)},cu):2===e&&(s._clickTimeout&&clearTimeout(s._clickTimeout),tu(a,t,e)))}}))}function R(e,n,r){a._scrollY=t._fullLayout.legend._scrollY=e,Un.setTranslate(f,0,-e),Un.setRect(d,b,Kc.scrollBarMargin+e*r,Kc.scrollBarWidth,n),c.select("rect").attr({y:a.borderwidth+e})}},style:iu},gu={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},vu=m.extendFlat,yu={visible:{valType:"boolean",editType:"plot"},buttons:gu=vu(gu,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:L({editType:"plot"}),bgcolor:{valType:"color",dflt:O.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:O.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},mu={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var xu=function(t,n){var r=t._name,a={};if("all"===n.step)a[r+".autorange"]=!0;else{var i=function(t,n){var r,a=t.range,i=new Date(t.r2l(a[1])),o=n.step,l=n.count;switch(n.stepmode){case"backward":r=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);r=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,n);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var bu=vn.LINE_SPACING,_u=vn.FROM_TL,wu=vn.FROM_BR;function ku(e){return e._id}function Mu(e,t,n){var r=rt.ensureSingle(e,"rect","selector-rect",function(e){e.attr("shape-rendering","crispEdges")});r.attr({rx:mu.rx,ry:mu.ry}),r.call(Nt.stroke,t.bordercolor).call(Nt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,n)).style("stroke-width",t.borderwidth+"px")}function Tu(e,t,n,r){var a;rt.ensureSingle(e,"text","selector-text",function(e){e.classed("user-select-none",!0).attr("text-anchor","middle")}).call(Un.font,t.font).text((a=n,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){mn.convertToTspans(e,r)})}var Au={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:yu}}},layoutAttributes:yu,handleDefaults:function(e,t,n,r,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return rt.coerce(i,o,yu,e,t)}if(l("visible",function(e,t,n){var r,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return rt.coerce(r,a,gu,e,t)}for(var s=0;s0)){var s=function(e,t,n){for(var r=n.filter(function(n){return t[n].anchor===e._id}),a=0,i=0;i0?c+o:o;return{ppad:o,ppadplus:l?f:d,ppadminus:l?d:f}}return{ppad:o}}function Zu(e,t,n,r,a){var i="category"===e.type?e.r2c:e.d2c;if(void 0!==t)return[i(t),i(n)];if(r){var o,l,s,c,u=1/0,f=-1/0,d=r.match(Vu.segmentRE);for("date"===e.type&&(i=Uu.decodeDate(i)),o=0;of&&(f=c)));return f>=u?[u,f]:void 0}}var Wu=function(e,t,n,r,a){function i(n,r){return rt.coerce(e,t,qu,n,r)}if(r=r||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=i("xsizemode"),s=i("ysizemode"),c=["x","y"],u=0;u<2;u++){var f,d,h,p=c[u],g=p+"anchor",v="x"===p?l:s,y={_fullLayout:n},m=za.coerceRef(e,t,y,p,"","paper");if("paper"!==m?(f=za.getFromId(y,m),h=Uu.rangeToShapePosition(f),d=Uu.shapePositionToRange(f)):d=h=rt.identity,"path"!==o){var x=p+"0",b=p+"1",_=e[x],w=e[b];e[x]=d(e[x],!0),e[b]=d(e[b],!0),"pixel"===v?(i(x,0),i(b,10)):(za.coercePosition(t,y,i,m,x,.25),za.coercePosition(t,y,i,m,b,.75)),t[x]=h(t[x]),t[b]=h(t[b]),e[x]=_,e[b]=w}if("pixel"===v){var k=e[g];e[g]=d(e[g],!0),za.coercePosition(t,y,i,m,g,.25),t[g]=h(t[g]),e[g]=k}}return"path"===o?i("path"):rt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},Qu={draw:function(e){var t=e._fullLayout;for(var n in t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._plots){var r=t._plots[n].shapelayer;r&&r.selectAll("path").remove()}for(var a=0;as?(y=o,_=D+".y0",T="y0",m=s,w=D+".y1",A="y1"):(y=s,_=D+".y1",T="y1",m=o,w=D+".y0",A="y0");a={},U(t),V.moveFn="move"===F?G:Y},doneFn:function(){hr(t),D.call("relayout",e,a)}};function U(e){var n=V.element.getBoundingClientRect(),r=n.right-n.left,a=n.bottom-n.top,i=e.clientX-n.left,o=e.clientY-n.top,l=r>B&&a>j&&!e.shiftKey?Ot.getCursor(i/r,1-o/a):"move";hr(t,l),F=l.split("-")[0]}function G(r,y){if("path"===n.type){var m=function(e){return e},x=m,b=m;H?a[g]=n.xanchor=I(c+r):(x=function(e){return I(E(e)+r)},P&&"date"===P.type&&(x=Uu.encodeDate(x))),q?a[v]=n.yanchor=R(u+y):(b=function(e){return R(N(e)+y)},z&&"date"===z.type&&(b=Uu.encodeDate(b))),n.path=Ku(S,x,b),a[O]=n.path}else H?a[g]=n.xanchor=I(c+r):(a[f]=n.x0=I(i+r),a[h]=n.x1=I(l+r)),q?a[v]=n.yanchor=R(u+y):(a[d]=n.y0=R(o+y),a[p]=n.y1=R(s+y));t.attr("d",$u(e,n))}function Y(r,i){if("path"===n.type){var o=function(e){return e},l=o,s=o;H?a[g]=n.xanchor=I(c+r):(l=function(e){return I(E(e)+r)},P&&"date"===P.type&&(l=Uu.encodeDate(l))),q?a[v]=n.yanchor=R(u+i):(s=function(e){return R(N(e)+i)},z&&"date"===z.type&&(s=Uu.encodeDate(s))),n.path=Ku(S,l,s),a[O]=n.path}else{var f=~F.indexOf("n")?y+i:y,d=~F.indexOf("s")?m+i:m,h=~F.indexOf("w")?x+r:x,p=~F.indexOf("e")?b+r:b;~F.indexOf("n")&&q&&(f=y-i),~F.indexOf("s")&&q&&(d=m-i),(!q&&d-f>j||q&&f-d>j)&&(a[_]=n[T]=q?f:R(f),a[w]=n[A]=q?d:R(d)),p-h>B&&(a[k]=n[L]=H?h:I(h),a[M]=n[C]=H?p:I(p))}t.attr("d",$u(e,n))}Ot.init(V),t.node().onmousemove=U}(e,o,r,t)}}function $u(e,t){var n,r,a,i,o,l,s,c,u=t.type,f=za.getFromId(e,t.xref),d=za.getFromId(e,t.yref),h=e._fullLayout._size;if(f?(n=Uu.shapePositionToRange(f),r=function(e){return f._offset+f.r2p(n(e,!0))}):r=function(e){return h.l+h.w*e},d?(a=Uu.shapePositionToRange(d),i=function(e){return d._offset+d.r2p(a(e,!0))}):i=function(e){return h.t+h.h*(1-e)},"path"===u)return f&&"date"===f.type&&(r=Uu.decodeDate(r)),d&&"date"===d.type&&(i=Uu.decodeDate(i)),function(e,t,n){var r=e.path,a=e.xsizemode,i=e.ysizemode,o=e.xanchor,l=e.yanchor;return r.replace(Vu.segmentRE,function(e){var r=0,s=e.charAt(0),c=Vu.paramIsX[s],u=Vu.paramIsY[s],f=Vu.numParams[s],d=e.substr(1).replace(Vu.paramRE,function(e){return c[r]?e="pixel"===a?t(o)+Number(e):t(e):u[r]&&(e="pixel"===i?n(l)-Number(e):n(e)),++r>f&&(e="X"),e});return r>f&&(d=d.replace(/[\s,]*X.*/,""),rt.log("Ignoring extra params in segment "+e)),s+d})}(t,r,i);if("pixel"===t.xsizemode){var p=r(t.xanchor);o=p+t.x0,l=p+t.x1}else o=r(t.x0),l=r(t.x1);if("pixel"===t.ysizemode){var g=i(t.yanchor);s=g-t.y0,c=g-t.y1}else s=i(t.y0),c=i(t.y1);if("line"===u)return"M"+o+","+s+"L"+l+","+c;if("rect"===u)return"M"+o+","+s+"H"+l+"V"+c+"H"+o+"Z";var v=(o+l)/2,y=(s+c)/2,m=Math.abs(v-o),x=Math.abs(y-s),b="A"+m+","+x,_=v+m+","+y;return"M"+_+b+" 0 1,1 "+(v+","+(y-x))+b+" 0 0,1 "+_+"Z"}function Ku(e,t,n){return e.replace(Vu.segmentRE,function(e){var r=0,a=e.charAt(0),i=Vu.paramIsX[a],o=Vu.paramIsY[a],l=Vu.numParams[a];return a+e.substr(1).replace(Vu.paramRE,function(e){return r>=l?e:(i[r]?e=t(e):o[r]&&(e=n(e)),r++,e)})})}var ef={moduleType:"component",name:"shapes",layoutAttributes:qu,supplyLayoutDefaults:function(e,t){yc(e,t,{name:"shapes",handleItemDefaults:Wu})},includeBasePlot:mc("shapes"),calcAutorange:function(e){var t=e._fullLayout,n=rt.filterVisible(t.shapes);if(n.length&&e._fullData.length)for(var r=0;r0)&&(r("active"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("len"),r("lenmode"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("currentvalue.visible")&&(r("currentvalue.xanchor"),r("currentvalue.prefix"),r("currentvalue.suffix"),r("currentvalue.offset"),rt.coerceFont(r,"currentvalue.font",t.font)),r("transition.duration"),r("transition.easing"),r("bgcolor"),r("activebgcolor"),r("bordercolor"),r("borderwidth"),r("ticklen"),r("tickwidth"),r("tickcolor"),r("minorticklen"))}var cf=vn.LINE_SPACING,uf=vn.FROM_TL,ff=vn.FROM_BR;function df(e){return e._index}function hf(t,n){var r=Un.tester.selectAll("g."+tf.labelGroupClass).data(n.steps);r.enter().append("g").classed(tf.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=vf(e.select(this),{step:t},n).node();if(r){var o=Un.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=n._dims={};o.inputAreaWidth=Math.max(tf.railWidth,tf.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*n.x,o.ly=l.t+l.h*(1-n.y),"fraction"===n.lenmode?o.outerLength=Math.round(l.w*n.len):o.outerLength=n.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-n.pad.l-n.pad.r);var s=(o.inputAreaLength-2*tf.stepInset)/(n.steps.length-1),c=a+tf.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,n.currentvalue.visible){var u=Un.tester.append("g");r.each(function(e){var t=pf(u,n,e.label),r=t.node()&&Un.bBox(t.node())||{width:0,height:0},a=mn.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(r.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(r.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+n.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+tf.tickOffset+n.ticklen+tf.labelOffset+o.labelHeight+n.pad.t+n.pad.b;var f="left";$c.isRightAnchor(n)&&(o.lx-=o.outerLength,f="right"),$c.isCenterAnchor(n)&&(o.lx-=o.outerLength/2,f="center");var d="top";$c.isBottomAnchor(n)&&(o.ly-=o.height,d="bottom"),$c.isMiddleAnchor(n)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Qr.autoMargin(t,tf.autoMarginIdRoot+n._index,{x:n.x,y:n.y,l:o.outerLength*uf[f],r:o.outerLength*ff[f],b:o.height*ff[d],t:o.height*uf[d]})}function pf(e,t,n){if(t.currentvalue.visible){var r,a,i=t._dims;switch(t.currentvalue.xanchor){case"right":r=i.inputAreaLength-tf.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":r=.5*i.inputAreaLength,a="middle";break;default:r=tf.currentValueInset,a="left"}var o=rt.ensureSingle(e,"text",tf.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof n)l+=n;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),o.call(Un.font,t.currentvalue.font).text(l).call(mn.convertToTspans,t._gd);var s=mn.lineCount(o),c=(i.currentValueMaxLines+1-s)*t.currentvalue.font.size*cf;return mn.positionText(o,r,c),o}}function gf(e,t,n){rt.ensureSingle(e,"rect",tf.gripRectClass,function(r){r.call(bf,t,e,n).style("pointer-events","all")}).attr({width:tf.gripWidth,height:tf.gripHeight,rx:tf.gripRadius,ry:tf.gripRadius}).call(Nt.stroke,n.bordercolor).call(Nt.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px")}function vf(e,t,n){var r=rt.ensureSingle(e,"text",tf.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return r.call(Un.font,n.font).text(t.step.label).call(mn.convertToTspans,n._gd),r}function yf(t,n){var r=rt.ensureSingle(t,"g",tf.labelsClass),a=n._dims,i=r.selectAll("g."+tf.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(tf.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=e.select(this);r.call(vf,t,n),Un.setTranslate(r,kf(n,t.fraction),tf.tickOffset+n.ticklen+n.font.size*cf+tf.labelOffset+a.currentValueTotalHeight)})}function mf(e,t,n,r,a){var i=Math.round(r*(n.steps.length-1));i!==n.active&&xf(e,t,n,i,!0,a)}function xf(e,t,n,r,a,i){var o=n.active;n._input.active=n.active=r;var l=n.steps[n.active];t.call(wf,n,n.active/(n.steps.length-1),i),t.call(pf,n),e.emit("plotly_sliderchange",{slider:n,step:n.steps[n.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var n=t._nextMethod.step;n.method&&(n.execute&&Qr.executeAPICommand(e,n.method,n.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function bf(t,n,r){var a=r.node(),i=e.select(n);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();n.emit("plotly_sliderstart",{slider:t});var l=r.select("."+tf.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(Nt.fill,t.activebgcolor);var s=Mf(t,e.mouse(a)[0]);mf(n,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=Mf(t,e.mouse(a)[0]);mf(n,r,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(Nt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),n.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function _f(t,n){var r=t.selectAll("rect."+tf.tickRectClass).data(n.steps),a=n._dims;r.enter().append("rect").classed(tf.tickRectClass,!0),r.exit().remove(),r.attr({width:n.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=e.select(this);o.attr({height:i?n.ticklen:n.minorticklen}).call(Nt.fill,n.tickcolor),Un.setTranslate(o,kf(n,r/(n.steps.length-1))-.5*n.tickwidth,(i?tf.tickOffset:tf.minorTickOffset)+a.currentValueTotalHeight)})}function wf(e,t,n,r){var a=e.select("rect."+tf.gripRectClass),i=kf(t,n);if(!t._invokingCommand){var o=a;r&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*tf.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function kf(e,t){var n=e._dims;return n.inputAreaStart+tf.stepInset+(n.inputAreaLength-2*tf.stepInset)*Math.min(1,Math.max(0,t))}function Mf(e,t){var n=e._dims;return Math.min(1,Math.max(0,(t-tf.stepInset-n.inputAreaStart)/(n.inputAreaLength-2*tf.stepInset-2*n.inputAreaStart)))}function Tf(e,t,n){var r=n._dims,a=rt.ensureSingle(e,"rect",tf.railTouchRectClass,function(r){r.call(bf,t,e,n).style("pointer-events","all")});a.attr({width:r.inputAreaLength,height:Math.max(r.inputAreaWidth,tf.tickOffset+n.ticklen+r.labelHeight)}).call(Nt.fill,n.bgcolor).attr("opacity",0),Un.setTranslate(a,0,r.currentValueTotalHeight)}function Af(e,t){var n=t._dims,r=n.inputAreaLength-2*tf.railInset,a=rt.ensureSingle(e,"rect",tf.railRectClass);a.attr({width:r,height:tf.railWidth,rx:tf.railRadius,ry:tf.railRadius,"shape-rendering":"crispEdges"}).call(Nt.stroke,t.bordercolor).call(Nt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Un.setTranslate(a,tf.railInset,.5*(n.inputAreaWidth-tf.railWidth)+n.currentValueTotalHeight)}var Lf={moduleType:"component",name:tf.name,layoutAttributes:af,supplyLayoutDefaults:function(e,t){yc(e,t,{name:of,handleItemDefaults:sf})},draw:function(t){var n=t._fullLayout,r=function(e,t){for(var n=e[tf.name],r=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(tf.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r=n.steps.length&&(n.active=0),t.call(pf,n).call(Af,n).call(yf,n).call(_f,n).call(Tf,e,n).call(gf,e,n);var r=n._dims;Un.setTranslate(t,r.lx+n.pad.l,r.ly+n.pad.t),t.call(wf,n,n.active/(n.steps.length-1),!1),t.call(pf,n)}(t,e.select(this),n)}})}}},Cf=m.extendFlat,Sf=(0,Wt.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Cf({},nf,{}),font:L({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:O.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Of={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Pf=Of.name,zf=Sf.buttons;function Df(e,t,n){function r(n,r){return rt.coerce(e,t,Sf,n,r)}r("visible",function(e,t){var n,r,a=e.buttons||[],i=t.buttons=[];function o(e,t){return rt.coerce(n,r,zf,e,t)}for(var l=0;l0)&&(r("active"),r("direction"),r("type"),r("showactive"),r("x"),r("y"),rt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),rt.coerceFont(r,"font",n.font),r("bgcolor",n.paper_bgcolor),r("bordercolor"),r("borderwidth"))}var Ef=Nf;function Nf(e,t,n){this.gd=e,this.container=t,this.id=n,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Nf.barWidth=2,Nf.barLength=20,Nf.barRadius=2,Nf.barPad=1,Nf.barColor="#808BA4",Nf.prototype.enable=function(t,n,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=Nf.barLength+2*Nf.barPad,k=Nf.barWidth+2*Nf.barPad,M=f,T=h+p;T+k>o&&(T=o-k);var A=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);A.exit().on(".drag",null).remove(),A.enter().append("rect").classed("scrollbar-horizontal",!0).call(Nt.fill,Nf.barColor),_?(this.hbar=A.attr({rx:Nf.barRadius,ry:Nf.barRadius,x:M,y:T,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=Nf.barWidth+2*Nf.barPad,S=Nf.barLength+2*Nf.barPad,O=f+d,P=h;O+C>i&&(O=i-C);var z=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);z.exit().on(".drag",null).remove(),z.enter().append("rect").classed("scrollbar-vertical",!0).call(Nt.fill,Nf.barColor),L?(this.vbar=z.attr({rx:Nf.barRadius,ry:Nf.barRadius,x:O,y:P,width:C,height:S}),this._vbarYMin=P+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,N=L?s+C+.5:s+.5,I=c-.5,R=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(I),width:Math.ceil(N)-Math.floor(E),height:Math.ceil(R)-Math.floor(I)}),this.container.call(Un.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Un.setClipUrl,null),delete this._clipRect),_||L){var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(B);var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),L&&this.vbar.on(".drag",null).call(j)}this.setTranslate(n,r)},Nf.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Un.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Nf.prototype._onBoxDrag=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(n-=e.event.dy),this.setTranslate(t,n)},Nf.prototype._onBoxWheel=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(n+=e.event.deltaY),this.setTranslate(t,n)},Nf.prototype._onBarDrag=function(){var t=this.translateX,n=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(rt.constrain(e.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=n+this._vbarYMin,o=i+this._vbarTranslateMax;n=(rt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,n)},Nf.prototype.setTranslate=function(e,t){var n=this.position.w-this._box.w,r=this.position.h-this._box.h;if(e=rt.constrain(e||0,0,n),t=rt.constrain(t||0,0,r),this.translateX=e,this.translateY=t,this.container.call(Un.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/n;this.hbar.call(Un.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/r;this.vbar.call(Un.setTranslate,e,t+i*this._vbarTranslateMax)}};var If=vn.LINE_SPACING;function Rf(e){return e._index}function Ff(e,t){return+e.attr(Of.menuIndexAttrName)===t._index}function Bf(e,t,n,r,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?Hf(e,r,null,null,t):"dropdown"===t.type&&(a.attr(Of.menuIndexAttrName,"-1"),jf(e,r,a,i,t),l||Hf(e,r,a,i,t))}function jf(e,t,n,r,a){var i=rt.ensureSingle(t,"g",Of.headerClassName,function(e){e.style("pointer-events","all")}),o=a._dims,l=a.active,s=a.buttons[l]||Of.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(qf,a,s,e).call(Wf,a,c,u),rt.ensureSingle(t,"text",Of.headerArrowClassName,function(e){e.classed("user-select-none",!0).attr("text-anchor","end").call(Un.font,a.font).text(Of.arrowSymbol[a.direction])}).attr({x:o.headerWidth-Of.arrowOffsetX+a.pad.l,y:o.headerHeight/2+Of.textOffsetY+a.pad.t}),i.on("click",function(){n.call(Qf),n.attr(Of.menuIndexAttrName,Ff(n,a)?-1:String(a._index)),Hf(e,t,n,r,a)}),i.on("mouseover",function(){i.call(Yf)}),i.on("mouseout",function(){i.call(Xf,a)}),Un.setTranslate(t,o.lx,o.ly)}function Hf(t,n,r,a,i){r||(r=n).attr("pointer-events","all");var o=function(e){return-1==+e.attr(Of.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?Of.dropdownButtonClassName:Of.buttonClassName,s=r.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+Of.gapButtonHeader:f=h.headerWidth+Of.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-Of.gapButtonHeader+Of.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-Of.gapButtonHeader+Of.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:Of.gapButton,xPad:Of.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(qf,i,o,t).call(Wf,i,g),c.on("click",function(){e.event.defaultPrevented||(Bf(t,i,0,n,r,a,l),o.execute&&Qr.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(Yf)}),c.on("mouseout",function(){c.call(Xf,i),s.call(Gf,i)})}),s.call(Gf,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,n,r,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(Of.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r_.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,n;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n0&&rt.log("Clearing previous rejected promises from queue."),e._promises=[]},nd.cleanLayout=function(e){var t,n;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var r=(Qr.subplotsRegistry.cartesian||{}).attrRegex,a=(Qr.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),Nt.clean(e),e},nd.cleanData=function(e,t){for(var n=[],r=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}nd.hasParent=function(e,t){for(var n=fd(t);n;){if(n in e)return!0;n=fd(n)}return!1};var dd=["x","y","z"];nd.clearAxisTypes=function(e,t,n){for(var r=0;r1&&w.warn("Full array edits are incompatible with other edits",a);var f=n[""][""];if(vd(f))t.set(null);else{if(!Array.isArray(f))return w.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(n).map(Number).sort(pd),b=t.get(),_=b||[],k=X(u,a).get(),M=[],A=-1,L=_.length;for(d=0;d_.length-(m?0:1))w.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&w.warn("Insertion & removal are incompatible with edits to the same index.",a,p),vd(y)?M.push(p):m?("add"===y&&(y={}),_.splice(p,0,y),k&&k.splice(p,0,{})):w.warn("Unrecognized full object edit value",a,p,y),-1===A&&(A=p);else for(h=0;h=0;d--)_.splice(M[d],1),k&&k.splice(M[d],1);if(_.length?b||t.set(_):t.set(null),s)return!1;if(i(c,u),l!==T){var C;if(-1===A)C=x;else{for(L=Math.max(_.length,L),C=[],d=0;d=A);d++)C.push(p);for(d=A;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,n=0;nEd*h)||y)for(n=0;nL&&OT&&(T=O);l/=(T-M)/(2*A),M=a.l2r(M),T=a.l2r(T),a.range=a._input.range=_=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(n,a,h)){var o=i.node(),l=t.bg=rt.ensureSingle(i,"rect","bg");o.insertBefore(l.node(),o.childNodes[0])}else i.select("rect.bg").remove(),d.push(e),h.push([n,a])});var p=r._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=e.select(this)}),f.each(function(e){var t=r._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Un.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(Nt.fill,r.plot_bgcolor).style("stroke-width",0);var u,f,d=t.clipId="clip"+r._uid+e+"plot",h=rt.ensureSingleById(r._clips,"clipPath",d,function(e){e.classed("plotclip",!0).append("rect")});for(t.clipRect=h.select("rect").attr({width:a._length,height:c._length}),Un.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=d):(u=d,f=null),Un.setClipUrl(t.plot,u),n=0;n=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var T=k.slice();w&&b&&(T[1]+=M);var A=c.angularAxis.ticksCount||4;A>8&&(A=A/(A/8)+A%8),c.angularAxis.ticksStep&&(A=(T[1]-T[0])/A);var L=c.angularAxis.ticksStep||(T[1]-T[0])/(A*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),T[2]||(T[2]=L);var C=e.range.apply(this,T);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(T.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),O=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(O)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var P,z=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){P=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var N=u.map(function(e,t){var n=Xd.util.cloneJson(e);return n.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",n.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,n.color="LinePlot"===e.geometry?e.strokeColor:e.color,n});Xd.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:Gd({},Xd.Legend.defaultConfig().legendConfig,{container:P,elements:N,reverseOrder:c.legend.reverseOrder})})();var I=P.node().getBBox();g=Math.min(c.width-I.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),P.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else P=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),z.attr("transform","translate("+y+")").style({cursor:"crosshair"});var R=[(c.width-(c.margin.left+c.margin.right+2*g+(I?I.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(R[0]=Math.max(0,R[0]),R[1]=Math.max(0,R[1]),t.select(".outer-group").attr("transform","translate("+R+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),B=F.node().getBBox();F.attr({x:y[0]-B.width/2,y:y[1]-g-20})}var j=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var H=j.selectAll("circle.grid-circle").data(r.ticks(5));H.enter().append("circle").attr({class:"grid-circle"}).style(D),H.attr("r",r),H.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(D);var q=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(r).ticks(5).tickSize(5);j.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),j.selectAll(".domain").style(D),j.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var X=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:Yd+"em",transform:function(e,t){var n=V(e),r=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-n+" "+r+" 0)":"radial"==a?n<270&&n>90?"rotate(180 "+r+" 0)":null:"rotate("+(n<=180&&n>0?-90:90)+" "+r+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&X.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var Z=e.max(z.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));P.attr({transform:"translate("+[g+Z,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,Q=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(Q.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),Q.exit().remove(),u[0]||W){var J=[];u.forEach(function(e,t){var n={};n.radialScale=r,n.angularScale=a,n.container=Q.filter(function(e,n){return n==t}),n.geometry=e.geometry,n.orientation=c.orientation,n.direction=c.direction,n.index=t,J.push({data:e,geometryConfig:n})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(J).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var n;n=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var r=e.map(function(e,t){return Gd(Xd[n].defaultConfig(),e)});Xd[n]().config(r)()})}var K,ee,te=t.select(".guides-group"),ne=t.select(".tooltips-group"),re=Xd.tooltipPanel().config({container:ne,fontSize:8})(),ae=Xd.tooltipPanel().config({container:ne,fontSize:8})(),ie=Xd.tooltipPanel().config({container:ne,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});z.on("mousemove.angular-guide",function(e,t){var n=Xd.util.getMousePos(q).angle;oe.attr({x2:-g,transform:"rotate("+n+")"}).style({opacity:.5});var r=(n+180+360-c.orientation)%360;K=a.invert(r);var i=Xd.util.convertToCartesian(g+12,n+180);re.text(Xd.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});z.on("mousemove.radial-guide",function(e,t){var n=Xd.util.getMousePos(q).radius;le.attr({r:n}).style({opacity:.5}),ee=r.invert(Xd.util.getMousePos(q).radius);var a=Xd.util.convertToCartesian(n,c.radialAxis.orientation);ae.text(Xd.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),re.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(n,r){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:Xd.util.round(n[0]),r:Xd.util.round(n[1])};b&&(s.t=m[n[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-R[0]-f.left,u.top+u.height/2-R[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,n){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,n){ie.hide();var r=e.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=Xd.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),Gd(i.data[t],Xd.Axis.defaultConfig().data[0]),Gd(i.data[t],e)}),Gd(i.layout,Xd.Axis.defaultConfig().layout),Gd(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return r},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},Xd.Axis.defaultConfig=function(t,n){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Xd.util={},Xd.DATAEXTENT="dataExtent",Xd.AREA="AreaChart",Xd.LINE="LinePlot",Xd.DOT="DotPlot",Xd.BAR="BarChart",Xd.util._override=function(e,t){for(var n in e)n in t&&(t[n]=e[n])},Xd.util._extend=function(e,t){for(var n in e)t[n]=e[n]},Xd.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Xd.util.dataFromEquation2=function(t,n){var r=n||6;return e.range(0,360+r,r).map(function(e,n){var r=e*Math.PI/180;return[e,t(r)]})},Xd.util.dataFromEquation=function(t,n,r){var a=n||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,n){var r=e*Math.PI/180,a=t(r);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},Xd.util.ensureArray=function(t,n){if(void 0===t)return null;var r=[].concat(t);return e.range(n).map(function(e,t){return r[t]||r[0]})},Xd.util.fillArrays=function(e,t,n){return t.forEach(function(t,r){e[t]=Xd.util.ensureArray(e[t],n)}),e},Xd.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},Xd.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var n=t.shift();return e[n]&&(!t.length||objHasKeys(e[n],t))},Xd.util.sumArrays=function(t,n){return e.zip(t,n).map(function(t,n){return e.sum(t)})},Xd.util.arrayLast=function(e){return e[e.length-1]},Xd.util.arrayEqual=function(e,t){for(var n=Math.max(e.length,t.length,1);n-- >=0&&e[n]===t[n];);return-2===n},Xd.util.flattenArray=function(e){for(var t=[];!Xd.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},Xd.util.deduplicate=function(e){return e.filter(function(e,t,n){return n.indexOf(e)==t})},Xd.util.convertToCartesian=function(e,t){var n=t*Math.PI/180;return[e*Math.cos(n),e*Math.sin(n)]},Xd.util.round=function(e,t){var n=t||2,r=Math.pow(10,n);return Math.round(e*r)/r},Xd.util.getMousePos=function(t){var n=e.mouse(t.node()),r=n[0],a=n[1],i={};return i.x=r,i.y=a,i.pos=n,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},Xd.util.duplicatesCount=function(e){for(var t,n={},r={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(n.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(r,a,i)},"stroke-width":function(e,t){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](r,a,i)},opacity:function(e,t){return p.opacity(r,a,i)},display:function(e,t){return p.display(r,a,i)}})}};var f=n.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return n.radialScale(s+(e[2]||0))}).outerRadius(function(e){return n.radialScale(s+(e[2]||0))+n.radialScale(e[1])});c.arc=function(t,r,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(n.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,n,r){return t[r].data.color},stroke:function(e,n,r){return t[r].data.strokeColor},"stroke-width":function(e,n,r){return t[r].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,n,r){return t[r].data.opacity},display:function(e,n,r){return void 0===t[r].data.visible||t[r].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[n.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,n){t[n]||(t[n]={}),Gd(t[n],Xd.PolyChart.defaultConfig()),Gd(t[n],e)}),this):t},a.getColorScale=function(){},e.rebind(a,n,"on"),a},Xd.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},Xd.BarChart=function(){return Xd.PolyChart()},Xd.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Xd.AreaChart=function(){return Xd.PolyChart()},Xd.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Xd.DotPlot=function(){return Xd.PolyChart()},Xd.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Xd.LinePlot=function(){return Xd.PolyChart()},Xd.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Xd.Legend=function(){var t=Xd.Legend.defaultConfig(),n=e.dispatch("hover");function r(){var n=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,r){var a=Gd({},n.elements[t]);return a.name=e,a.color=[].concat(n.elements[t].color)[r],a})}),i=e.merge(a);i=i.filter(function(e,t){return n.elements[t]&&(n.elements[t].visibleInLegend||void 0===n.elements[t].visibleInLegend)}),n.reverseOrder&&(i=i.reverse());var o=n.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=n.fontSize,c=null==n.isContinuous?"number"==typeof i[0]:n.isContinuous,u=c?n.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:n.height,width:n.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,n){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(r)?e.svg.symbol().type(r).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?n.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?n.textColor:"none"}),x.selectAll("text").style({fill:n.textColor,"font-size":n.fontSize}).text(function(e,t){return i[t].name}),r}return r.config=function(e){return arguments.length?(Gd(t,e),this):t},e.rebind(r,n,"on"),r},Xd.Legend.defaultConfig=function(e,t){return{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:!1}}},Xd.tooltipPanel=function(){var t,n,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+Xd.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),n=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";n.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=n.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return Gd(a,e),l},l},Xd.tooltipPanel.uid=1,Xd.adapter={},Xd.adapter.plotly=function(){var t={convert:function(t,n){var r={};if(t.data&&(r.data=t.data.map(function(e,t){var r=Gd({},e);return[[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"]]].forEach(function(e,t){Xd.util.translator.apply(null,e.concat(n))}),n||delete r.marker,n&&delete r.groupId,n?("LinePlot"===r.geometry?(r.type="scatter",!0===r.dotVisible?(delete r.dotVisible,r.mode="lines+markers"):r.mode="lines"):"DotPlot"===r.geometry?(r.type="scatter",r.mode="markers"):"AreaChart"===r.geometry?r.type="area":"BarChart"===r.geometry&&(r.type="bar"),delete r.geometry):("scatter"===r.type?"lines"===r.mode?r.geometry="LinePlot":"markers"===r.mode?r.geometry="DotPlot":"lines+markers"===r.mode&&(r.geometry="LinePlot",r.dotVisible=!0):"area"===r.type?r.geometry="AreaChart":"bar"===r.type&&(r.geometry="BarChart"),delete r.mode,delete r.type),r}),!n&&t.layout&&"stack"===t.layout.barmode)){var a=Xd.util.duplicates(r.data.map(function(e,t){return e.geometry}));r.data.forEach(function(e,t){var n=a.indexOf(e.geometry);-1!=n&&(r.data[t].groupId=n)})}if(t.layout){var i=Gd({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){Xd.util.translator.apply(null,e.concat(n))}),n?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}n&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var Zd,Wd=rt.extendDeepAll,Qd=Zd={};Qd.framework=function(t){var n,r,a,i,o,l=new function(){var e,t=[],n=-1,r=!1;function a(e,t){return e?(r=!0,e[t](),r=!1,this):this}return{add:function(e){return r?this:(t.splice(n+1,t.length-n),t.push(e),n=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var r=t[n];return r?(a(r,"undo"),n-=1,e&&e(r.undo),this):this},redo:function(){var r=t[n+1];return r?(a(r,"redo"),n+=1,e&&e(r.redo),this):this},clear:function(){t=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n*:not(.chart-root)").remove(),n=n?Wd(n,r):r,a||(a=Ud.Axis()),i=Ud.adapter.plotly().convert(n),a.config(i).render(o),t.data=n.data,t.layout=n.layout,Qd.fillLayout(t),n}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return n},s.getLiveConfig=function(){return Ud.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=Ud.util.cloneJson(n);e=i,t=r,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),r=Ud.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},Qd.fillLayout=function(t){var n=e.select(t).selectAll(".plot-container"),r=n.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:Nt.background,_container:n,_paperdiv:r,_paper:a};t._fullLayout=Wd(i,t.layout)};var Jd={};(Jd=Ud).manager=Zd;var $d={},Kd=zo.initInteractions,eh=ht.AX_NAME_PATTERN,th=0;function nh(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){rt.error(e)}}function rh(e,t){nh(e,Nt.combine(t,"white"))}function ah(e,t){e._context||(e._context=rt.extendDeep({},_));var n,r,a,i=e._context;if(t){for(r=Object.keys(t),n=0;n=e.data.length||a<-e.data.length)throw new Error(n+" must be valid indices for gd.data.");if(t.indexOf(a,r+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+n+" must be unique.")}}function lh(e,t,n){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),oh(e,t,"currentIndices"),void 0===n||Array.isArray(n)||(n=[n]),void 0!==n&&oh(e,n,"newIndices"),void 0!==n&&t.length!==n.length)throw new Error("current and new indices must be of equal length.")}function sh(e,t,r,a,i){!function(e,t,n,r){var a=rt.isPlainObject(r);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!rt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===n)throw new Error("indices must be an integer or array of integers");for(var i in oh(e,n,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==n.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in r)||!Array.isArray(r[i])||r[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,t,r,a);for(var o=function(e,t,r,a){var i,o,l,s,c,u=rt.isPlainObject(a),f=[];for(var d in Array.isArray(r)||(r=[r]),r=ih(r,e.data.length-1),t)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var T=_.parts[M],A=_.parts[M-1]+"."+T,L=_.parts.slice(0,M).join("."),C=rt.nestedProperty(e.layout,L).get(),S=rt.nestedProperty(o,L).get(),O=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===T?w:uh(O);var P=Pr.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var z in P.impliedEdits)v(rt.relativeAttr(b,z),P.impliedEdits[z]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(A.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(A),rt.nestedProperty(o,L+"._inputRange").set(null);else if(A.match(/^[xyz]axis[0-9]*\.autorange$/)){x(A),rt.nestedProperty(o,L+"._inputRange").set(null);var E=rt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else A.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&rt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===T){var N=C,I="linear"===S.type&&"log"===w,R="log"===S.type&&"linear"===w;if(I||R){if(N&&N.range)if(S.autorange)I&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],B=N.range[1];I?(F<=0&&B<=0&&v(L+".autorange",!0),F<=0?F=B/1e6:B<=0&&(B=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(B)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,B)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],D.getComponentMethod("annotations","convertCoords")(e,S,w,v),D.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);rt.nestedProperty(o,L+"._inputRange").set(null)}else if(T.match(eh)){var j=rt.nestedProperty(o,b).get(),H=(w||{}).type;H&&"-"!==H||(H="linear"),D.getComponentMethod("annotations","convertCoords")(e,j,H,v),D.getComponentMethod("images","convertCoords")(e,j,H,v)}var q=hd.containerArrayMatch(b);if(q){n=q.array,r=q.index;var V=q.property,U=(rt.nestedProperty(i,n)||[])[r]||{},G=U,Y=P||{editType:"calc"},X=-1!==Y.editType.indexOf("calcIfAutorange");""===r?(X?h.calc=!0:Wt.update(h,Y),X=!1):""===V&&(G=w,hd.isAddVal(w)?g[b]=null:hd.isRemoveVal(w)?(g[b]=U,G=U):rt.warn("unrecognized full object value",t)),X&&(ph(e,G,"x")||ph(e,G,"y"))?h.calc=!0:Wt.update(h,Y),c[n]||(c[n]={});var Z=c[n][r];Z||(Z=c[n][r]={}),Z[V]=w,delete t[b]}else"reverse"===T?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==O&&"select"!==O?h.plot=!0:P?Wt.update(h,P):h.calc=!0,_.set(w))}}for(n in c){hd.applyContainerArrayChanges(e,rt.nestedProperty(i,n),c[n],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(r=0;r=0&&n=0&&n=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var n=0;return function(){if(e&&++n===t)return e()}}return void 0===r._frameWaitingCnt&&(r._frameWaitingCnt=0),new Promise(function(i,c){function u(){r._currentFrame&&r._currentFrame.onComplete&&r._currentFrame.onComplete();var t=r._currentFrame=r._frameQueue.shift();if(t){var n=t.name?t.name.toString():null;e._fullLayout._currentFrame=n,r._lastFrameAt=Date.now(),r._timeToNext=t.frameOpts.duration,Qr.transition(e,t.frame.data,t.frame.layout,nd.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:n,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(r._animationRaf),r._animationRaf=null}function f(){e.emit("plotly_animating"),r._lastFrameAt=-1/0,r._timeToNext=0,r._runningTransitions=0,r._currentFrame=null;var t=function(){r._animationRaf=window.requestAnimationFrame(t),Date.now()-r._lastFrameAt>r._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&rt.isPlainObject(t))v.push({type:"object",data:g(rt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;r--)if(rt.isPlainObject(t[r])){var d=t[r].name,h=(s[d]||f[d]||{}).name,p=t[r].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&th<5&&(th++,rt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===th&&rt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:Qr.supplyFrameDefaults(t[r]),index:n&&void 0!==n[r]&&null!==n[r]?n[r]:c+r})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;r--){if("number"==typeof(a=u[r].frame).name&&rt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;n--)r=t[n],i.push({type:"delete",index:r}),o.unshift({type:"insert",index:r,value:a[r]});var l=Qr.modifyFrames,s=Qr.modifyFrames,c=[e,o],u=[e,i];return ed&&ed.add(e,l,c,s,u),Qr.modifyFrames(e,i)},$d.purge=function(e){var t=(e=rt.getGraphDiv(e))._fullLayout||{},n=e._fullData||[],r=e.calcdata||[];return Qr.cleanPlot([],{},n,t,r),Qr.purge(e),Ct.purge(e),t._container&&t._container.remove(),delete e._context,e};var yh={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},mh=wt.EventEmitter;var xh=function(e){var t=e.emitter||new mh,n=new Promise(function(r,a){var i=window.Image,o=e.svg,l=e.format||"png";if(rt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?n:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var n;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":n=c.toDataURL("image/jpeg");break;case"png":n=c.toDataURL("image/png");break;case"webp":n=c.toDataURL("image/webp");break;case"svg":n=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}r(n),e.promise||t.emit("success",n)},p.onerror=function(n){if(a(n),!e.promise)return t.emit("error",n)},p.src=g});return e.promise?n:t},bh=/"/g,_h=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var wh=function(n,r,a){var i,o=n._fullLayout,l=o._paper,s=o._toppaper,c=o.width,u=o.height;l.insert("rect",":first-child").call(Un.setRect,0,0,c,u).call(Nt.fill,o.paper_bgcolor);var f=o._basePlotModules||[];for(i=0;i")?"":n.html(e).text()});return n.remove(),r}(v),v=(v=v.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(_h,"'"),rt.isIE()&&(v=(v=(v=v.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),v},kh={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},Mh=/^data:image\/\w+;base64,/;var Th=function(e,t){var n,r,a;function i(e){return!(e in t)||rt.validate(t[e],kh[e])}if(t=t||{},rt.isPlainObject(e)?(n=e.data||[],r=e.layout||{},a=e.config||{}):(e=rt.getGraphDiv(e),n=rt.extendDeep([],e.data),r=rt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,n){return rt.coerce(t,o,kh,e,n)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=rt.extendFlat({},r);c&&(g.width=c),u&&(g.height=u);var v=rt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=yh.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,yh.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var n=wh(p,s,f),r=p._fullLayout.width,a=p._fullLayout.height;if($d.purge(p),document.body.removeChild(p),"svg"===s)return e(h?n:"data:image/svg+xml,"+encodeURIComponent(n));var i=document.createElement("canvas");i.id=rt.randstr(),xh({format:s,width:r,height:a,scale:f,canvas:i,svg:n,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){$d.plot(p,n,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(Mh,""):e}(t))}).catch(function(e){t(e)})})},Ah=rt.isPlainObject,Lh=Array.isArray,Ch=rt.isArrayOrTypedArray;function Sh(e,t,n,r,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&r.push(zh("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(Lh(u[y])){u[y].length>f[y].length&&r.push(zh("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],rt.validate(x,m)?b!==x&&b!==+x&&r.push(zh("dynamic",a,c.concat(y,v),x,b)):r.push(zh("value",a,c.concat(y,v),x))}else r.push(zh("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],rt.validate(x,m)?b!==x&&b!==+x&&r.push(zh("dynamic",a,c.concat(y),x,b)):r.push(zh("value",a,c.concat(y),x))}else if(d.items&&!h&&Lh(u)){var M,T,A=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(zh("object","layout"))),Qr.supplyDefaults(o);for(var l=o._fullData,s=n.length,c=0;c-1&&(l[c[n]].title="");for(n=0;nH||e[1]V)return[ip(e[0],j,H),ip(e[1],q,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===j||e[0]===H)||(e[1]===t[1]&&(e[1]===q||e[1]===V)||void 0)}function X(e,t,n){return function(r,a){var i=G(r),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*rt.constrain((r[e]+a[e])/2,t,n)-((i||r)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function Z(e){var t=e[0],n=e[1],r=t===L[C-1][0],a=n===L[C-1][1];if(!r||!a)if(C>1){var i=t===L[C-2][0],o=n===L[C-2][1];r&&(t===j||t===H)&&i?o?C--:L[C-1]=e:a&&(n===q||n===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&Z([E,N]),Z(e),I=null,E=N=0}function Q(e){if(z=e[0]H?H:0,D=e[1]V?V:0,z||D){if(C)if(I){var t=F(I,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else R=F(L[C-1],e)[0],L[C++]=R;else L[C++]=[z||e[0],D||e[1]];var n=L[C-1];z&&D&&(n[0]!==z||n[1]!==D)?(I&&(E!==z&&N!==D?Z(E&&N?(r=I,i=(a=e)[0]-r[0],o=(a[1]-r[1])/i,(r[1]*a[0]-a[1]*r[0])/i>0?[o>0?j:H,V]:[o>0?H:j,q]):[E||z,N||D]):E&&N&&Z([E,N])),Z([z,D])):E-z&&N-D&&Z([z||E,D||N]),I=e,E=z,N=D}else I&&W(F(I,e)[0]),L[C++]=e;var r,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var n=[],r=0,a=0;a<4;a++){var i=U[a],o=ap(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!r||Math.abs(o.x-n[0][0])>1||Math.abs(o.y-n[0][1])>1)&&(o=[o.x,o.y],r&&P(o,e)O(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;Q(l),r=l}}else Q(i)}I&&Z([E||I[0],N||I[1]]),T.push(L.slice(0,C))}return T},lp=qi.tester;function sp(t,n,r,a,i,o,l){var s,c;!function(t,n,r,a,i){var o=r.xaxis,l=r.yaxis,s=e.extent(rt.simpleMap(o.range,o.r2c)),c=e.extent(rt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Vn.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var r=e[0].trace;Vn.hasMarkers(r)&&r.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=r.xaxis,h=r.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(D.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),r.isRangePlot||(a[0].node3=v);var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,T,A,L,C,S,O,P,z="",E="",N=[],I=rt.noop;if(y=p._ownFill,Vn.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=Un.steps(g.shape),A=Un.steps(g.shape.split("").reverse().join(""))):T=A="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Un.smoothclosed(e.slice(1),g.smoothing):Un.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return A(e.reverse())},N=op(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=p._polygons=new Array(N.length),c=0;c1){var r=e.select(this);if(r.datum(a),t)f(r.style("opacity",0).attr("d",k).call(Un.lineGroupStyle)).style("opacity",1);else{var i=f(r);i.attr("d",k),Un.singleLineStyle(a,i)}}}}}var R=v.selectAll(".js-line").data(N);f(R.exit()).style("opacity",0).remove(),R.each(I(!1)),R.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Un.lineGroupStyle).each(I(!0)),Un.setClipUrl(R,r.layerClipId),N.length?(y?C&&O&&(x?("y"===x?C[1]=O[1]=h.c2p(0,!0):"x"===x&&(C[0]=O[0]=d.c2p(0,!0)),f(y).attr("d","M"+O+"L"+C+"L"+z.substr(1)).call(Un.singleFillStyle)):f(y).attr("d",z+"Z").call(Un.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&z&&b?("tonext"===p.fill?f(m).attr("d",z+"Z"+b+"Z").call(Un.singleFillStyle):f(m).attr("d",z+"L"+b.substr(1)+"Z").call(Un.singleFillStyle),p._polygons=p._polygons.concat(_)):(B(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=P):(y?B(y):m&&B(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Un.setClipUrl(e.select(this),n?null:r.layerClipId)})}function B(e){f(e).attr("d","M0,0Z")}function j(e){return e.filter(function(e){return e.vis})}function H(e){return e.id}function q(e){if(e.ids)return H}function V(){return!1}function U(n){var a,i=n[0].trace,o=e.select(this),l=Vn.hasMarkers(i),s=Vn.hasText(i),c=q(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?j:rt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?j:rt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Un.pointStyle,i,t).call(Un.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Un.tryColorscale(i.marker,""),m=l&&Un.tryColorscale(i.marker,"line");a.order(),a.each(function(n){var a=e.select(this),o=f(a);Un.translatePoint(n,o,d,h)?(Un.singlePointStyle(n,o,i,y,m,t),r.layerClipId&&Un.hideOutsideRangePoint(n,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==n.data&&void 0!==n.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var n=e.select(this),a=f(n.select("text"));Un.translatePoint(t,a,d,h)?r.layerClipId&&Un.hideOutsideRangePoint(t,n,d,h,i.xcalendar,i.ycalendar):n.remove()}),a.selectAll("text").call(Un.textPointStyle,i,t).each(function(t){var n=d.c2p(t.x),r=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:n,y:r})})}),a.exit().remove()}}function cp(e,t,n){var r=e.selectAll("path.point"),a=e.selectAll("text");Un.pointStyle(r,t,n),Un.textPointStyle(a,t,n),Un.selectedPointStyle(r,t),Un.selectedTextStyle(a,t)}var up=function(t,n){var r=n?n[0].node3:e.select(t).selectAll("g.trace.scatter");r.style("opacity",function(e){return e[0].trace.opacity}),r.selectAll("g.points").each(function(n){cp(e.select(this),n.trace||n[0].trace,t)}),r.selectAll("g.trace path.js-line").call(Un.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(Un.fillGroupStyle),D.getComponentMethod("errorbars","style")(r)},fp={};fp.hasLines=Vn.hasLines,fp.hasMarkers=Vn.hasMarkers,fp.hasText=Vn.hasText,fp.isBubble=Vn.isBubble,fp.attributes=kr,fp.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,kr,n,r)}var i=hl(e,t,r,a),o=i=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===n.xaxis&&i.yaxis===n.yaxis){i.opacity=void 0;break}}}}},fp.calc=Kh,fp.arraysToCalcdata=Xh,fp.plot=function(t,n,r,a,i){var o,l,s,c,u=n.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(r,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,n){var r,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){sp(t,i,n,e,r,this,a)})})):u.selectAll("g.trace").each(function(e,i){sp(t,i,n,e,r,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()},fp.colorbar=$l,fp.style=up,fp.hoverPoints=function(e,t,n,r){var a=e.cd,i=a[0].trace,o=e.xa,l=e.ya,s=o.c2p(t),c=l.c2p(n),u=[s,c],f=i.hoveron||"",d=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var h=function(e){var t=Math.max(d,e.mrc||0),n=o.c2p(e.x)-s,r=l.c2p(e.y)-c;return Math.max(Math.sqrt(n*n+r*r)-t,1-d/t)},p=Li.getDistanceFunction(r,function(e){var t=Math.max(3,e.mrc||0),n=1-1/t,r=Math.abs(o.c2p(e.x)-s);return rI!=(L=w[b][1])>=I&&(M=w[b-1][0],T=w[b][0],L-A&&(k=M+(T-M)*(I-A)/(L-A),P=Math.min(P,k),z=Math.max(z,k)));P=Math.max(P,0),z=Math.min(z,o._length);var R=Nt.defaultLine;return Nt.opacity(i.fillcolor)?R=i.fillcolor:Nt.opacity((i.line||{}).color)&&(R=i.line.color),rt.extendFlat(e,{distance:e.maxHoverDistance,x0:P,x1:z,y0:I,y1:I,color:R}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},fp.selectPoints=function(e,t){var n,r,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Vn.hasMarkers(u)&&!Vn.hasText(u))return[];if(!1===t)for(n=0;ni){var o=i-r[e];return r[e]=i,o}}return 0},max:function(e,t,r,a){var i=a[t];if(n(i)){if(i=Number(i),!n(r[e]))return r[e]=i,i;if(r[e]Lp?e>Mp?e>1.1*wp?wp:e>1.1*kp?kp:Mp:e>Tp?Tp:e>Ap?Ap:Lp:Math.pow(10,Math.floor(Math.log(e)/Math.LN10))}function Pp(e,t,n,r,a,i){if(r&&e>Mp){var o=zp(t,a,i),l=zp(n,a,i),s=e===wp?0:1;return o[s]!==l[s]}return Math.floor(n/e)-Math.floor(t/e)>.1}function zp(e,t,n){var r=t.c2d(e,wp,n).split("-");return""===r[0]&&(r.unshift(),r[0]="-"+r[0]),r}var Dp=rt.cleanDate,Ep=r.ONEDAY,Np=r.BADNUM,Ip={percent:function(e,t){for(var n=e.length,r=100/t,a=0;ac.size/1.9?c.size:c.size/Math.ceil(c.size/g);var _=c.start+(c.size-g)/2;v=_-g*Math.ceil((_-v)/g)}for(o=0;o0?Number(c):s;else if("string"!=typeof c)o.size=s;else{var u=c.charAt(0),f=c.substr(1);((f=n(f)?Number(f):0)<=0||"date"!==a||"M"!==u||f!==Math.round(f))&&(o.size=s)}var d="autobin"+r;"boolean"!=typeof e[d]&&(e[d]=e._fullInput[d]=e._input[d]=!((o.start||0===o.start)&&(o.end||0===o.end))),e[d]||(delete e["nbins"+r],delete e._fullInput["nbins"+r])}(t,o,l);var f,d,h,p=Fp(e,t,o,l),g=p[0],v=p[1],y="string"==typeof g.size,m=[],x=y?m:g,b=[],_=[],w=[],k=0,M=t.histnorm,T=t.histfunc,A=-1!==M.indexOf("density");u.enabled&&A&&(M=M.replace(/ ?density$/,""),A=!1);var L,C="max"===T||"min"===T?null:0,S=_p.count,O=Ip[M],P=!1,z=function(e){return o.r2c(e,0,c)};for(rt.isArrayOrTypedArray(t[s])&&"count"!==T&&(L=t[s],P="avg"===T,S=_p[T]),r=z(g.start),d=z(g.end)+(r-za.tickIncrement(r,g.size,!1,c))/1e6;r=0&&hh&&hMp){var p=i===wp?1:6,g=i===wp?"M12":"M1";return function(t,n){var i=r.c2d(t,wp,a),l=i.indexOf("-",p);l>0&&(i=i.substr(0,l));var s=r.d2c(i,0,a);if(s=0;r--)l(r);else if("increasing"===t){for(r=1;r=0;r--)e[r]+=e[r+1];"exclude"===n&&(e.push(0),e.shift())}}(i,u.direction,u.currentbin);var j=Math.min(a.length,i.length),H=[],q=0,V=j-1;for(r=0;r=q;r--)if(i[r]){V=r;break}for(r=q;r<=V;r++)if(n(a[r])&&n(i[r])){var U={p:a[r],s:i[r],b:0};u.enabled||(U.pts=w[r],N?U.p0=U.p1=w[r].length?v[w[r][0]]:a[r]:(U.p0=D(m[r]),U.p1=D(m[r+1],!0))),H.push(U)}return 1===H.length&&(H[0].width1=za.tickIncrement(H[0].p,g.size,!1,c)-H[0].p),al(H,t),rt.isArrayOrTypedArray(t.selectedpoints)&&rt.tagSelected(H,t,F),H}},Up.setPositions=Il,Up.plot=Tl,Up.style=Zl,Up.colorbar=$l,Up.hoverPoints=function(e,t,n,r){var a=vl(e,t,n,r);if(a){var i=(e=a[0]).cd[e.index],o=e.cd[0].trace;if(!o.cumulative.enabled){var l="h"===o.orientation?"y":"x";e[l+"Label"]=Vp(e[l+"a"],i.p0,i.p1)}return a}},Up.selectPoints=Ol,Up.eventData=function(e,t,n,r,a){if(e.x="xVal"in t?t.xVal:t.x,e.y="yVal"in t?t.yVal:t.y,t.xa&&(e.xaxis=t.xa),t.ya&&(e.yaxis=t.ya),!(n.cumulative||{}).enabled){var i,o=Array.isArray(a)?r[0].pts[a[0]][a[1]]:r[a].pts;if(e.pointNumbers=o,e.binNumber=e.pointNumber,delete e.pointNumber,delete e.pointIndex,n._indexToPoints){i=[];for(var l=0;l0?1:-1)/2,y:i/(1+n*n/(r*r)),outside:!0}}var ug={};ug.attributes=Jp,ug.supplyDefaults=function(e,t,n,r){function a(n,r){return rt.coerce(e,t,Jp,n,r)}var i=rt.coerceFont,o=a("values"),l=a("labels");if(!Array.isArray(l)){if(!rt.isArrayOrTypedArray(o)||!o.length)return void(t.visible=!1);a("label0"),a("dlabel")}a("marker.line.width")&&a("marker.line.color"),a("marker.colors"),a("scalegroup");var s=a("text"),c=a("textinfo",Array.isArray(s)?"text+percent":"percent");if(a("hovertext"),c&&"none"!==c){var u=a("textposition"),f=Array.isArray(u)||"auto"===u,d=f||"inside"===u,h=f||"outside"===u;if(d||h){var p=i(a,"textfont",r.font);d&&i(a,"insidetextfont",p),h&&i(a,"outsidetextfont",p)}}ag(t,r,a),a("hole"),a("sort"),a("direction"),a("rotation"),a("pull")},ug.supplyLayoutDefaults=function(e,t){var n,r;n="hiddenlabels",rt.coerce(e,t,ig,n,r)},ug.layoutAttributes=ig,ug.calc=function(e,t){var r,a,i,o,l,c=t.values,u=tg(c)&&c.length,f=t.labels,d=t.marker.colors||[],h=[],p=e._fullLayout,g=p.colorway,v=p._piecolormap,y={},m=0,x=p.hiddenlabels||[];if(p._piecolorway||g===Nt.defaults||(p._piecolorway=rg(g)),t.dlabel)for(f=new Array(c.length),r=0;r")}}return h},ug.plot=function(t,n){var r=t._fullLayout;!function(e,t){var n,r,a,i,o,l,s,c,u,f=[];for(a=0;as&&(s=l.pull[i]);o.r=Math.min(n,r)/(2+2*s),o.cx=t.l+t.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=t.t+t.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;ia.vTotal/2?1:0)}(n),a.each(function(){var a=e.select(this).selectAll("g.slice").data(n);a.enter().append("g").classed("slice",!0),a.exit().remove();var l=[[[],[]],[[],[]]],s=!1;a.each(function(n){if(n.hidden)e.select(this).selectAll("path,g").remove();else{n.pointNumber=n.i,n.curveNumber=o.index,l[n.pxmid[1]<0?0:1][n.pxmid[0]<0?0:1].push(n);var a=i.cx,c=i.cy,u=e.select(this),f=u.selectAll("path.surface").data([n]),d=!1,h=!1;if(f.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),u.select("path.textline").remove(),u.on("mouseover",function(){var l=t._fullLayout,s=t._fullData[o.index];if(!t._dragging&&!1!==l.hovermode){var u=s.hoverinfo;if(Array.isArray(u)&&(u=Li.castHoverinfo({hoverinfo:[nu.castOption(u,n.pts)],_module:o._module},l,0)),"all"===u&&(u="label+text+value+percent+name"),"none"!==u&&"skip"!==u&&u){var f=sg(n,i),p=a+n.pxmid[0]*(1-f),g=c+n.pxmid[1]*(1-f),v=r.separators,y=[];if(-1!==u.indexOf("label")&&y.push(n.label),-1!==u.indexOf("text")){var m=nu.castOption(s.hovertext||s.text,n.pts);m&&y.push(m)}-1!==u.indexOf("value")&&y.push(nu.formatPieValue(n.v,v)),-1!==u.indexOf("percent")&&y.push(nu.formatPiePercent(n.v/i.vTotal,v));var x=o.hoverlabel,b=x.font;Li.loneHover({x0:p-f*i.r,x1:p+f*i.r,y:g,text:y.join("
"),name:-1!==u.indexOf("name")?s.name:void 0,idealAlign:n.pxmid[0]<0?"left":"right",color:nu.castOption(x.bgcolor,n.pts)||n.color,borderColor:nu.castOption(x.bordercolor,n.pts),fontFamily:nu.castOption(b.family,n.pts),fontSize:nu.castOption(b.size,n.pts),fontColor:nu.castOption(b.color,n.pts)},{container:l._hoverlayer.node(),outerContainer:l._paper.node(),gd:t}),d=!0}t.emit("plotly_hover",{points:[lg(n,s)],event:e.event}),h=!0}}).on("mouseout",function(r){var a=t._fullLayout,i=t._fullData[o.index];h&&(r.originalEvent=e.event,t.emit("plotly_unhover",{points:[lg(n,i)],event:e.event}),h=!1),d&&(Li.loneUnhover(a._hoverlayer.node()),d=!1)}).on("click",function(){var r=t._fullLayout,a=t._fullData[o.index];t._dragging||!1===r.hovermode||(t._hoverdata=[lg(n,a)],Li.click(t,e.event))}),o.pull){var p=+nu.castOption(o.pull,n.pts)||0;p>0&&(a+=p*n.pxmid[0],c+=p*n.pxmid[1])}n.cxFinal=a,n.cyFinal=c;var g=o.hole;if(n.v===i.vTotal){var v="M"+(a+n.px0[0])+","+(c+n.px0[1])+_(n.px0,n.pxmid,!0,1)+_(n.pxmid,n.px0,!0,1)+"Z";g?f.attr("d","M"+(a+g*n.px0[0])+","+(c+g*n.px0[1])+_(n.px0,n.pxmid,!1,g)+_(n.pxmid,n.px0,!1,g)+"Z"+v):f.attr("d",v)}else{var y=_(n.px0,n.px1,!0,1);if(g){var m=1-g;f.attr("d","M"+(a+g*n.px1[0])+","+(c+g*n.px1[1])+_(n.px1,n.px0,!1,g)+"l"+m*n.px0[0]+","+m*n.px0[1]+y+"Z")}else f.attr("d","M"+a+","+c+"l"+n.px0[0]+","+n.px0[1]+y+"Z")}var x=nu.castOption(o.textposition,n.pts),b=u.selectAll("g.slicetext").data(n.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var r=rt.ensureSingle(e.select(this),"text","",function(e){e.attr("data-notex",1)});r.text(n.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Un.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(mn.convertToTspans,t);var l,u=Un.bBox(r.node());"outside"===x?l=cg(u,n):(l=function(e,t,n){var r=Math.sqrt(e.width*e.width+e.height*e.height),a=e.width/e.height,i=Math.PI*Math.min(t.v/n.vTotal,.5),o=1-n.trace.hole,l=sg(t,n),s={scale:l*n.r*2/r,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=n.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),f={scale:2*u/e.height,rCenter:Math.cos(u/n.r)-u*a/n.r,rotate:(180/Math.PI*t.midangle+720)%180-90},d=1/a,h=d+1/(2*Math.tan(i)),p=n.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(d*d+o/2)+d)),g={scale:2*p/e.width,rCenter:Math.cos(p/n.r)-p/a/n.r,rotate:(180/Math.PI*t.midangle+810)%180-90},v=g.scale>f.scale?g:f;return s.scale<1&&v.scale>s.scale?v:s}(u,n,i),"auto"===x&&l.scale<1&&(r.call(Un.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(u=Un.bBox(r.node())),l=cg(u,n)));var f=a+n.pxmid[0]*l.rCenter+(l.x||0),d=c+n.pxmid[1]*l.rCenter+(l.y||0);l.outside&&(n.yLabelMin=d-u.height/2,n.yLabelMid=d,n.yLabelMax=d+u.height/2,n.labelExtraX=0,n.labelExtraY=0,s=!0),r.attr("transform","translate("+f+","+d+")"+(l.scale<1?"scale("+l.scale+")":"")+(l.rotate?"rotate("+l.rotate+")":"")+"translate("+-(u.left+u.right)/2+","+-(u.top+u.bottom)/2+")")})}function _(e,t,r,a){return"a"+a*i.r+","+a*i.r+" 0 "+n.largeArc+(r?" 1 ":" 0 ")+a*(t[0]-e[0])+","+a*(t[1]-e[1])}}),s&&function(e,t){var n,r,a,i,o,l,s,c,u,f,d,h,p;function g(e,t){return e.pxmid[1]-t.pxmid[1]}function v(e,t){return t.pxmid[1]-e.pxmid[1]}function y(e,n){n||(n={});var a,c,u,d,h,p,g=n.labelExtraY+(r?n.yLabelMax:n.yLabelMin),v=r?e.yLabelMin:e.yLabelMax,y=r?e.yLabelMax:e.yLabelMin,m=e.cyFinal+o(e.px0[1],e.px1[1]),x=g-v;if(x*s>0&&(e.labelExtraY=x),Array.isArray(t.pull))for(c=0;c=(nu.castOption(t.pull,u.pts)||0)||((e.pxmid[1]-u.pxmid[1])*s>0?(d=u.cyFinal+o(u.px0[1],u.px1[1]),(x=d-v-e.labelExtraY)*s>0&&(e.labelExtraY+=x)):(y+e.labelExtraY-m)*s>0&&(a=3*l*Math.abs(c-f.indexOf(e)),h=u.cxFinal+i(u.px0[0],u.px1[0]),(p=h+a-(e.cxFinal+e.pxmid[0])-e.labelExtraX)*l>0&&(e.labelExtraX+=p)))}for(r=0;r<2;r++)for(a=r?g:v,o=r?Math.max:Math.min,s=r?1:-1,n=0;n<2;n++){for(i=n?Math.max:Math.min,l=n?1:-1,(c=e[r][n]).sort(a),u=e[1-r][n],f=u.concat(c),h=[],d=0;dMath.abs(c)?i+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):i+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else i+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;n.append("path").classed("textline",!0).call(Nt.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:i,fill:"none"})}})})}),setTimeout(function(){a.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},ug.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var n=t[0].trace,r=e.select(this);r.style({opacity:n.opacity}),r.selectAll("path.surface").each(function(t){e.select(this).call(au,t,n)})})},ug.styleOne=au,ug.moduleType="trace",ug.name="pie",ug.basePlotModule=$p,ug.categories=["pie","showLegend"],ug.meta={};var fg=ug;return mp.register([es,Gp,fg,Xp,Rs]),mp}); \ No newline at end of file diff --git a/dist/plotly-geo-assets.js b/dist/plotly-geo-assets.js index 06c844f5d88..ebcd10b6368 100644 --- a/dist/plotly-geo-assets.js +++ b/dist/plotly-geo-assets.js @@ -1,5 +1,5 @@ /** -* plotly.js v1.35.2 +* plotly.js v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -69,7 +69,7 @@ var saneTopojson = require('sane-topojson'); // package version injected by `npm run preprocess` -exports.version = '1.35.2'; +exports.version = '1.36.0'; exports.topojson = saneTopojson; diff --git a/dist/plotly-geo.js b/dist/plotly-geo.js index 856a7ab926a..45eef076523 100644 --- a/dist/plotly-geo.js +++ b/dist/plotly-geo.js @@ -1,5 +1,5 @@ /** -* plotly.js (geo) v1.35.2 +* plotly.js (geo) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -11194,7 +11194,7 @@ var _$interactions_146 = { DESELECTDIM: 0.2 }; -var _$is_array_167 = {}; +var _$is_array_168 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11215,12 +11215,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_167.isTypedArray = function(a) { +_$is_array_168.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_167.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_167.isTypedArray(a); +_$is_array_168.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_168.isTypedArray(a); }; /** @@ -11235,7 +11235,7 @@ _$is_array_167.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_168 = function isPlainObject(obj) { +var _$isPlainObject_169 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11251,7 +11251,7 @@ var _$isPlainObject_168 = function isPlainObject(obj) { ); }; -var _$extend_158 = {}; +var _$extend_159 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11263,7 +11263,7 @@ var _$extend_158 = {}; 'use strict'; -/* removed: var _$isPlainObject_168 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_169 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11280,19 +11280,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_158.extendFlat = function() { +_$extend_159.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_158.extendDeep = function() { +_$extend_159.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_158.extendDeepAll = function() { +_$extend_159.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_158.extendDeepNoArrays = function() { +_$extend_159.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11345,12 +11345,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_168(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_169(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_168(src) ? src : {}; + clone = src && _$isPlainObject_169(src) ? src : {}; } // never move original objects, clone them @@ -11385,7 +11385,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_199 = { +var _$plot_config_200 = { // no interactivity, for export or image generation staticPlot: false, @@ -11553,7 +11553,7 @@ var _$plot_config_199 = { locales: {} }; -var _$loggers_171 = {}; +var _$loggers_172 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11566,9 +11566,9 @@ var _$loggers_171 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_199 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_200 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_171 = {}; +var loggers = _$loggers_172 = {}; /** * ------------------------------------------ @@ -11577,7 +11577,7 @@ var loggers = _$loggers_171 = {}; */ loggers.log = function() { - if(_$plot_config_199.logging > 1) { + if(_$plot_config_200.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11589,7 +11589,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_199.logging > 0) { + if(_$plot_config_200.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11601,7 +11601,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_199.logging > 0) { + if(_$plot_config_200.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11640,7 +11640,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_175 = function noop() {}; +var _$noop_176 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11665,7 +11665,7 @@ var _$noop_175 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_179 = function pushUnique(array, item) { +var _$pushUnique_180 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11802,7 +11802,7 @@ var _$attributes_79 = { /* removed: var _$attributes_79 = require('../components/fx/attributes'); */; -var _$attributes_206 = { +var _$attributes_207 = { type: { valType: 'enumerated', @@ -12108,7 +12108,7 @@ var _$layout_attributes_248 = { } }; -var _$registry_258 = {}; +var _$registry_259 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12119,29 +12119,29 @@ var _$registry_258 = {}; 'use strict'; -/* removed: var _$loggers_171 = require('./lib/loggers'); */; -/* removed: var _$noop_175 = require('./lib/noop'); */; -/* removed: var _$pushUnique_179 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_168 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_158 = require('./lib/extend'); */; +/* removed: var _$loggers_172 = require('./lib/loggers'); */; +/* removed: var _$noop_176 = require('./lib/noop'); */; +/* removed: var _$pushUnique_180 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_169 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_159 = require('./lib/extend'); */; -/* removed: var _$attributes_206 = require('./plots/attributes'); */; +/* removed: var _$attributes_207 = require('./plots/attributes'); */; /* removed: var _$layout_attributes_248 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_158.extendFlat; -var extendDeepAll = _$extend_158.extendDeepAll; - -_$registry_258.modules = {}; -_$registry_258.allCategories = {}; -_$registry_258.allTypes = []; -_$registry_258.subplotsRegistry = {}; -_$registry_258.transformsRegistry = {}; -_$registry_258.componentsRegistry = {}; -_$registry_258.layoutArrayContainers = []; -_$registry_258.layoutArrayRegexes = []; -_$registry_258.traceLayoutAttributes = {}; -_$registry_258.localeRegistry = {}; -_$registry_258.apiMethodRegistry = {}; +var extendFlat = _$extend_159.extendFlat; +var extendDeepAll = _$extend_159.extendDeepAll; + +_$registry_259.modules = {}; +_$registry_259.allCategories = {}; +_$registry_259.allTypes = []; +_$registry_259.subplotsRegistry = {}; +_$registry_259.transformsRegistry = {}; +_$registry_259.componentsRegistry = {}; +_$registry_259.layoutArrayContainers = []; +_$registry_259.layoutArrayRegexes = []; +_$registry_259.traceLayoutAttributes = {}; +_$registry_259.localeRegistry = {}; +_$registry_259.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12182,7 +12182,7 @@ _$registry_258.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_258.register = function register(_modules) { +_$registry_259.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12211,7 +12211,7 @@ _$registry_258.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_258.apiMethodRegistry[name] = newModule.fn; + _$registry_259.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12227,8 +12227,8 @@ _$registry_258.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_258.getModule = function(trace) { - var _module = _$registry_258.modules[getTraceType(trace)]; +_$registry_259.getModule = function(trace) { + var _module = _$registry_259.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12242,20 +12242,20 @@ _$registry_258.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_258.traceIs = function(traceType, category) { +_$registry_259.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_258.modules[traceType]; + var _module = _$registry_259.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_171.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_172.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_258.modules[_$attributes_206.type.dflt]; + _module = _$registry_259.modules[_$attributes_207.type.dflt]; } return !!_module.categories[category]; @@ -12272,7 +12272,7 @@ _$registry_258.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_258.getTransformIndices = function(data, type) { +_$registry_259.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12292,7 +12292,7 @@ _$registry_258.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_258.hasTransform = function(data, type) { +_$registry_259.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12312,11 +12312,11 @@ _$registry_258.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_258.getComponentMethod = function(name, method) { - var _module = _$registry_258.componentsRegistry[name]; +_$registry_259.getComponentMethod = function(name, method) { + var _module = _$registry_259.componentsRegistry[name]; - if(!_module) return _$noop_175; - return _module[method] || _$noop_175; + if(!_module) return _$noop_176; + return _module[method] || _$noop_176; }; /** @@ -12326,10 +12326,10 @@ _$registry_258.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_258.call = function() { +_$registry_259.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_258.apiMethodRegistry[name].apply(null, args); + return _$registry_259.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12337,33 +12337,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_258.modules[thisType]) { - _$loggers_171.log('Type ' + thisType + ' already registered'); + if(_$registry_259.modules[thisType]) { + _$loggers_172.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_258.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_259.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_258.allCategories[categoriesIn[i]] = true; + _$registry_259.allCategories[categoriesIn[i]] = true; } - _$registry_258.modules[thisType] = { + _$registry_259.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_258.modules[thisType].meta = meta; + _$registry_259.modules[thisType].meta = meta; } - _$registry_258.allTypes.push(thisType); + _$registry_259.allTypes.push(thisType); - for(var componentName in _$registry_258.componentsRegistry) { + for(var componentName in _$registry_259.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12373,15 +12373,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_258.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_259.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_258.subplotsRegistry[plotType]) { - _$loggers_171.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_259.subplotsRegistry[plotType]) { + _$loggers_172.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12391,9 +12391,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_258.subplotsRegistry[plotType] = _module; + _$registry_259.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_258.componentsRegistry) { + for(var componentName in _$registry_259.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12404,24 +12404,24 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_258.componentsRegistry[name] = _module; + _$registry_259.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_179(_$registry_258.layoutArrayContainers, name); + _$pushUnique_180(_$registry_259.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_258.modules) { + for(var traceType in _$registry_259.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_258.subplotsRegistry) { + for(var subplotName in _$registry_259.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_258.transformsRegistry) { + for(var transformType in _$registry_259.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } @@ -12443,22 +12443,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_171.log([ + _$loggers_172.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_168(_module.attributes)) { - _$loggers_171.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_169(_module.attributes)) { + _$loggers_172.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_171.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_172.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_258.transformsRegistry[_module.name] = _module; + _$registry_259.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_258.componentsRegistry) { + for(var componentName in _$registry_259.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12472,7 +12472,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_258.localeRegistry; + var locales = _$registry_259.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12504,37 +12504,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_179(_$registry_258.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_180(_$registry_259.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_258.componentsRegistry[componentName].schema; + var componentSchema = _$registry_259.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_258.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_259.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_258.componentsRegistry[componentName].schema; + var componentSchema = _$registry_259.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_258.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_259.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_258.componentsRegistry[componentName].schema; + var componentSchema = _$registry_259.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_258.subplotsRegistry[subplotName]; + var subplotModule = _$registry_259.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12561,7 +12561,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_258 = require('../registry'); */; +/* removed: var _$registry_259 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12576,9 +12576,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_193 = function containerArrayMatch(astr) { - var rootContainers = _$registry_258.layoutArrayContainers, - regexpContainers = _$registry_258.layoutArrayRegexes, +var _$containerArrayMatch_194 = function containerArrayMatch(astr) { + var rootContainers = _$registry_259.layoutArrayContainers, + regexpContainers = _$registry_259.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12619,9 +12619,9 @@ var _$containerArrayMatch_193 = function containerArrayMatch(astr) { 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_167.isArrayOrTypedArray; -/* removed: var _$isPlainObject_168 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_193 = require('../plot_api/container_array_match'); */; +var isArrayOrTypedArray = _$is_array_168.isArrayOrTypedArray; +/* removed: var _$isPlainObject_169 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_194 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12637,7 +12637,7 @@ var isArrayOrTypedArray = _$is_array_167.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_174 = function nestedProperty(container, propStr) { +var _$nestedProperty_175 = function nestedProperty(container, propStr) { if(_$fastIsnumeric_11(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { @@ -12748,7 +12748,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_168(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_169(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12757,7 +12757,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_193(propStr); + var match = _$containerArrayMatch_194(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12910,7 +12910,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_181 = {}; +var _$regex_182 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12930,7 +12930,7 @@ var _$regex_181 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_181.counter = function(head, tail, openEnded) { +_$regex_182.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12938,7 +12938,7 @@ _$regex_181.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_154 = {}; +var _$coerce_155 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12953,16 +12953,16 @@ var _$coerce_154 = {}; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_26 = require('tinycolor2'); */; -/* removed: var _$attributes_206 = require('../plots/attributes'); */; +/* removed: var _$attributes_207 = require('../plots/attributes'); */; /* removed: var _$getScale_58 = require('../components/colorscale/get_scale'); */; var colorscaleNames = Object.keys(_$scales_64); -/* removed: var _$nestedProperty_174 = require('./nested_property'); */; -var counterRegex = _$regex_181.counter; +/* removed: var _$nestedProperty_175 = require('./nested_property'); */; +var counterRegex = _$regex_182.counter; var DESELECTDIM = _$interactions_146.DESELECTDIM; var wrap180 = _$angles_152.wrap180; -var __isArrayOrTypedArray_154 = _$is_array_167.isArrayOrTypedArray; +var __isArrayOrTypedArray_155 = _$is_array_168.isArrayOrTypedArray; -_$coerce_154.valObjectMeta = { +_$coerce_155.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12970,7 +12970,7 @@ _$coerce_154.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_154(v)) propOut.set(v); + if(__isArrayOrTypedArray_155(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13093,8 +13093,9 @@ _$coerce_154.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13148,9 +13149,11 @@ _$coerce_154.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13161,12 +13164,12 @@ _$coerce_154.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_154.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_155.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13176,19 +13179,28 @@ _$coerce_154.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13219,12 +13231,12 @@ _$coerce_154.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_154.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_155.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_154.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_155.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13244,10 +13256,10 @@ _$coerce_154.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_154.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_174(attributes, attribute).get(), - propIn = _$nestedProperty_174(containerIn, attribute), - propOut = _$nestedProperty_174(containerOut, attribute), +_$coerce_155.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_175(attributes, attribute).get(), + propIn = _$nestedProperty_175(containerIn, attribute), + propOut = _$nestedProperty_175(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13258,12 +13270,12 @@ _$coerce_154.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_154(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_155(v)) { propOut.set(v); return v; } - _$coerce_154.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_155.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13275,9 +13287,9 @@ _$coerce_154.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_154.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_174(containerIn, attribute), - propOut = _$coerce_154.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_155.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_175(containerIn, attribute), + propOut = _$coerce_155.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13288,7 +13300,7 @@ _$coerce_154.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_154.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_155.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13308,11 +13320,9 @@ _$coerce_154.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_154.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_155.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_206; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_207; var valObj = attrs.hoverinfo; var dflt; @@ -13326,7 +13336,7 @@ _$coerce_154.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_154.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_155.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13340,7 +13350,7 @@ _$coerce_154.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_154.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_155.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13355,7 +13365,7 @@ _$coerce_154.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_154(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_155(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13364,10 +13374,10 @@ _$coerce_154.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_154.validate = function(value, opts) { - var valObjectDef = _$coerce_154.valObjectMeta[opts.valType]; +_$coerce_155.validate = function(value, opts) { + var valObjectDef = _$coerce_155.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_154(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_155(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13397,12 +13407,12 @@ _$coerce_154.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_173 = function mod(v, d) { +var _$mod_174 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_155 = {}; +var _$dates_156 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13417,18 +13427,18 @@ var _$dates_155 = {}; /* removed: var _$d3_8 = require('d3'); */; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$loggers_171 = require('./loggers'); */; -/* removed: var _$mod_173 = require('./mod'); */; +/* removed: var _$loggers_172 = require('./loggers'); */; +/* removed: var _$mod_174 = require('./mod'); */; /* removed: var _$numerical_147 = require('../constants/numerical'); */; -var __BADNUM_155 = _$numerical_147.BADNUM; +var __BADNUM_156 = _$numerical_147.BADNUM; var ONEDAY = _$numerical_147.ONEDAY; var ONEHOUR = _$numerical_147.ONEHOUR; var ONEMIN = _$numerical_147.ONEMIN; var ONESEC = _$numerical_147.ONESEC; var EPOCHJD = _$numerical_147.EPOCHJD; -/* removed: var _$registry_258 = require('../registry'); */; +/* removed: var _$registry_259 = require('../registry'); */; var utcFormat = _$d3_8.time.format.utc; @@ -13442,7 +13452,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_258.componentsRegistry.calendars && + _$registry_259.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13452,11 +13462,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_155.dateTick0 = function(calendar, sunday) { +_$dates_156.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_258.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_258.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_259.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_259.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13466,9 +13476,9 @@ _$dates_155.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_155.dfltRange = function(calendar) { +_$dates_156.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_258.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_259.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13476,7 +13486,7 @@ _$dates_155.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_155.isJSDate = function(v) { +_$dates_156.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13538,17 +13548,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_155.dateTime2ms = function(s, calendar) { +_$dates_156.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_155.isJSDate(s)) { + if(_$dates_156.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_155; + return __BADNUM_156; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_155; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_156; s = String(s); @@ -13565,7 +13575,7 @@ _$dates_155.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_155; + if(!match) return __BADNUM_156; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13575,12 +13585,12 @@ _$dates_155.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_155; + if(y.length === 2) return __BADNUM_156; y = Number(y); var cDate; try { - var calInstance = _$registry_258.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_259.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13590,9 +13600,9 @@ _$dates_155.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_155; } // Invalid ... date + catch(e) { return __BADNUM_156; } // Invalid ... date - if(!cDate) return __BADNUM_155; + if(!cDate) return __BADNUM_156; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13613,18 +13623,18 @@ _$dates_155.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_155; - if(date.getUTCDate() !== d) return __BADNUM_155; + if(date.getUTCMonth() !== m) return __BADNUM_156; + if(date.getUTCDate() !== d) return __BADNUM_156; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_155.MIN_MS = _$dates_155.dateTime2ms('-9999'); -MAX_MS = _$dates_155.MAX_MS = _$dates_155.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_156.MIN_MS = _$dates_156.dateTime2ms('-9999'); +MAX_MS = _$dates_156.MAX_MS = _$dates_156.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_155.isDateTime = function(s, calendar) { - return (_$dates_155.dateTime2ms(s, calendar) !== __BADNUM_155); +_$dates_156.isDateTime = function(s, calendar) { + return (_$dates_156.dateTime2ms(s, calendar) !== __BADNUM_156); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13643,20 +13653,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_155.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_155; +_$dates_156.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_156; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_173(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_174(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_173(ms, ONEDAY)); + timeMs = Math.floor(_$mod_174(ms, ONEDAY)); try { - dateStr = _$registry_258.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_259.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13704,10 +13714,10 @@ _$dates_155.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_155.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_155; +_$dates_156.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_156; - var msecTenths = Math.floor(_$mod_173(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_174(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), dateStr = _$d3_8.time.format('%Y-%m-%d')(d), h = d.getHours(), @@ -13740,23 +13750,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_155.cleanDate = function(v, dflt, calendar) { - if(_$dates_155.isJSDate(v) || typeof v === 'number') { +_$dates_156.cleanDate = function(v, dflt, calendar) { + if(_$dates_156.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_171.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_172.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 = _$dates_155.ms2DateTimeLocal(+v); + v = _$dates_156.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_155.isDateTime(v, calendar)) { - _$loggers_171.error('unrecognized date', v); + else if(!_$dates_156.isDateTime(v, calendar)) { + _$loggers_172.error('unrecognized date', v); return dflt; } return v; @@ -13786,7 +13796,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_258.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_259.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13803,10 +13813,10 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_173(x + 0.05, ONEDAY); + var timePart = _$mod_174(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_173(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_174(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { if(!_$fastIsnumeric_11(tr)) tr = 0; // should only be 'S' @@ -13826,7 +13836,7 @@ function formatTime(x, tr) { * 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_173(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_174(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13855,7 +13865,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_155.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_156.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13899,19 +13909,19 @@ _$dates_155.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_155.incrementMonth = function(ms, dMonth, calendar) { +_$dates_156.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_173(ms, ONEDAY); + var timeMs = _$mod_174(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_258.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_259.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13920,7 +13930,7 @@ _$dates_155.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_171.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_172.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13935,7 +13945,7 @@ _$dates_155.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_155.findExactDates = function(data, calendar) { +_$dates_156.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13945,7 +13955,7 @@ _$dates_155.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_258.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_259.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { @@ -14012,7 +14022,7 @@ _$dates_155.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_156 = function ensureArray(out, n) { +var _$ensureArray_157 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14055,7 +14065,7 @@ var _$ensureArray_156 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_159 = function filterUnique(array) { +var _$filterUnique_160 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14089,7 +14099,7 @@ var _$filterUnique_159 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_160 = function filterVisible(container) { +var _$filterVisible_161 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14118,7 +14128,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_163 = {}; +var _$geometry2d_164 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14129,13 +14139,13 @@ var _$geometry2d_163 = {}; 'use strict'; -/* removed: var _$mod_173 = require('./mod'); */; +/* removed: var _$mod_174 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_163.segmentsIntersect = segmentsIntersect; +_$geometry2d_164.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14158,7 +14168,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_163.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_164.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 @@ -14211,7 +14221,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_163.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_164.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14223,13 +14233,13 @@ _$geometry2d_163.getTextLocation = function getTextLocation(path, totalPathLen, // 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_173(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_173(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_174(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_174(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_173(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_174(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14238,7 +14248,7 @@ _$geometry2d_163.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_163.clearLocationCache = function() { +_$geometry2d_164.clearLocationCache = function() { workingPath = null; }; @@ -14266,7 +14276,7 @@ _$geometry2d_163.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_163.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_164.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14327,7 +14337,7 @@ _$geometry2d_163.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_163.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_164.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14382,7 +14392,7 @@ _$geometry2d_163.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_164 = function(gd) { +var _$get_graph_div_165 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14414,7 +14424,7 @@ var _$get_graph_div_164 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_165 = function identity(d) { return d; }; +var _$identity_166 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14426,7 +14436,7 @@ var _$identity_165 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_174 = require('./nested_property'); */; +/* removed: var _$nestedProperty_175 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14448,13 +14458,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_170 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_174(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_175(baseObj, path).get(); } else { arr = baseObj; } @@ -14480,7 +14490,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_174(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_175(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14490,7 +14500,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_174(newValue, valueName).set(value); + _$nestedProperty_175(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14511,7 +14521,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_174(arr[idx], valueName).get(); + return _$nestedProperty_175(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14552,7 +14562,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value } 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_174(object, valueName).set(null); + _$nestedProperty_175(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, @@ -14579,7 +14589,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_174(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_175(arr[idx], valueName).get(); } } } else { @@ -14605,7 +14615,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_258 = require('../registry'); */; +/* removed: var _$registry_259 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14616,7 +14626,7 @@ var _$keyedContainer_169 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_170 = function localize(gd, s) { +var _$localize_171 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14638,7 +14648,7 @@ var _$localize_170 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_258.localeRegistry; + locales = _$registry_259.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14649,7 +14659,7 @@ var _$localize_170 = function localize(gd, s) { return s; }; -var _$matrix_172 = {}; +var _$matrix_173 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14662,7 +14672,7 @@ var _$matrix_172 = {}; 'use strict'; -_$matrix_172.init2dArray = function(rowLength, colLength) { +_$matrix_173.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14673,7 +14683,7 @@ _$matrix_172.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_172.transposeRagged = function(z) { +_$matrix_173.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14691,7 +14701,7 @@ _$matrix_172.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_172.dot = function(x, y) { +_$matrix_173.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14701,13 +14711,13 @@ _$matrix_172.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_172.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_173.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_172.transposeRagged(y); + var yTranspose = _$matrix_173.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_172.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_173.dot(x, yTranspose[i]); } else { // vec-vec @@ -14719,12 +14729,12 @@ _$matrix_172.dot = function(x, y) { }; // translate by (x,y) -_$matrix_172.translationMatrix = function(x, y) { +_$matrix_173.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_172.rotationMatrix = function(alpha) { +_$matrix_173.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14732,28 +14742,28 @@ _$matrix_172.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_172.rotationXYMatrix = function(a, x, y) { - return _$matrix_172.dot( - _$matrix_172.dot(_$matrix_172.translationMatrix(x, y), - _$matrix_172.rotationMatrix(a)), - _$matrix_172.translationMatrix(-x, -y)); +_$matrix_173.rotationXYMatrix = function(a, x, y) { + return _$matrix_173.dot( + _$matrix_173.dot(_$matrix_173.translationMatrix(x, y), + _$matrix_173.rotationMatrix(a)), + _$matrix_173.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_172.apply2DTransform = function(transform) { +_$matrix_173.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_172.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_173.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_172.apply2DTransform2 = function(transform) { - var at = _$matrix_172.apply2DTransform(transform); +_$matrix_173.apply2DTransform2 = function(transform) { + var at = _$matrix_173.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14782,7 +14792,7 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_176 = function(text, displayLength) { +var _$notifier_177 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); @@ -14874,7 +14884,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_182 = function(baseAttr, relativeAttr) { +var _$relative_attr_183 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14903,8 +14913,8 @@ var _$relative_attr_182 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_183 = _$is_array_167.isArrayOrTypedArray; -/* removed: var _$isPlainObject_168 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_184 = _$is_array_168.isArrayOrTypedArray; +/* removed: var _$isPlainObject_169 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14913,7 +14923,7 @@ var __isArrayOrTypedArray_183 = _$is_array_167.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_183 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_184 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14929,7 +14939,7 @@ var _$relinkPrivateKeys_183 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_183(fromVal) && __isArrayOrTypedArray_183(toVal) && _$isPlainObject_168(fromVal[0])) { + else if(__isArrayOrTypedArray_184(fromVal) && __isArrayOrTypedArray_184(toVal) && _$isPlainObject_169(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14939,12 +14949,12 @@ var _$relinkPrivateKeys_183 = function relinkPrivateKeys(toContainer, fromContai // 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_168(fromVal[j]) && _$isPlainObject_168(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_169(fromVal[j]) && _$isPlainObject_169(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_168(fromVal) && _$isPlainObject_168(toVal)) { + else if(_$isPlainObject_169(fromVal) && _$isPlainObject_169(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14954,7 +14964,7 @@ var _$relinkPrivateKeys_183 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_184 = {}; +var _$search_185 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14967,7 +14977,7 @@ var _$search_184 = {}; 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$loggers_171 = require('./loggers'); */; +/* removed: var _$loggers_172 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -14985,7 +14995,7 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_184.findBin = function(val, bins, linelow) { +_$search_185.findBin = function(val, bins, linelow) { if(_$fastIsnumeric_11(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : @@ -15009,7 +15019,7 @@ _$search_184.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_171.log('Long binary search...'); + if(c > 90) _$loggers_172.log('Long binary search...'); return n1 - 1; } }; @@ -15019,17 +15029,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_184.sorterAsc = function(a, b) { return a - b; }; -_$search_184.sorterDes = function(a, b) { return b - a; }; +_$search_185.sorterAsc = function(a, b) { return a - b; }; +_$search_185.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_184.distinctVals = function(valsIn) { +_$search_185.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_184.sorterAsc); + vals.sort(_$search_185.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15054,7 +15064,7 @@ _$search_184.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_184.roundUp = function(val, arrayIn, reverse) { +_$search_185.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15071,7 +15081,7 @@ _$search_184.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_186 = {}; +var _$stats_187 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15084,7 +15094,7 @@ var _$stats_186 = {}; 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_186 = _$is_array_167.isArrayOrTypedArray; +var __isArrayOrTypedArray_187 = _$is_array_168.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15099,14 +15109,14 @@ var __isArrayOrTypedArray_186 = _$is_array_167.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_186.aggNums = function(f, v, a, len) { +_$stats_187.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; if(!_$fastIsnumeric_11(v)) v = false; - if(__isArrayOrTypedArray_186(a[0])) { + if(__isArrayOrTypedArray_187(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_186.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_187.aggNums(f, v, a[i]); a = b; } @@ -15121,26 +15131,26 @@ _$stats_186.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_186.len = function(data) { - return _$stats_186.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_187.len = function(data) { + return _$stats_187.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_186.mean = function(data, len) { - if(!len) len = _$stats_186.len(data); - return _$stats_186.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_187.mean = function(data, len) { + if(!len) len = _$stats_187.len(data); + return _$stats_187.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_186.variance = function(data, len, mean) { - if(!len) len = _$stats_186.len(data); - if(!_$fastIsnumeric_11(mean)) mean = _$stats_186.mean(data, len); +_$stats_187.variance = function(data, len, mean) { + if(!len) len = _$stats_187.len(data); + if(!_$fastIsnumeric_11(mean)) mean = _$stats_187.mean(data, len); - return _$stats_186.aggNums(function(a, b) { + return _$stats_187.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_186.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_186.variance(data, len, mean)); +_$stats_187.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_187.variance(data, len, mean)); }; /** @@ -15158,7 +15168,7 @@ _$stats_186.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_186.interp = function(arr, n) { +_$stats_187.interp = function(arr, n) { if(!_$fastIsnumeric_11(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; @@ -15167,7 +15177,7 @@ _$stats_186.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_188 = {}; +var _$throttle_189 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15194,7 +15204,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_188.throttle = function throttle(id, minInterval, callback) { +_$throttle_189.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15234,7 +15244,7 @@ _$throttle_188.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_188.done = function(id) { +_$throttle_189.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15254,13 +15264,13 @@ _$throttle_188.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_188.clear = function(id) { +_$throttle_189.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_188.clear(idi); + for(var idi in timerCache) _$throttle_189.clear(idi); } }; @@ -15287,7 +15297,7 @@ function _clearTimeout(cache) { * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_189 = function toLogRange(val, range) { +var _$toLogRange_190 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the @@ -15298,7 +15308,7 @@ var _$toLogRange_189 = function toLogRange(val, range) { return newVal; }; -var _$lib_166 = {}; +var _$lib_167 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15315,71 +15325,71 @@ var _$lib_166 = {}; /* removed: var _$numerical_147 = require('../constants/numerical'); */; var FP_SAFE = _$numerical_147.FP_SAFE; -var __BADNUM_166 = _$numerical_147.BADNUM; - -var lib = _$lib_166 = {}; - -lib.nestedProperty = _$nestedProperty_174; -lib.keyedContainer = _$keyedContainer_169; -lib.relativeAttr = _$relative_attr_182; -lib.isPlainObject = _$isPlainObject_168; -lib.mod = _$mod_173; -lib.toLogRange = _$toLogRange_189; -lib.relinkPrivateKeys = _$relinkPrivateKeys_183; -lib.ensureArray = _$ensureArray_156; - -/* removed: var _$is_array_167 = require('./is_array'); */; -lib.isTypedArray = _$is_array_167.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_167.isArrayOrTypedArray; - -/* removed: var _$coerce_154 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_154.valObjectMeta; -lib.coerce = _$coerce_154.coerce; -lib.coerce2 = _$coerce_154.coerce2; -lib.coerceFont = _$coerce_154.coerceFont; -lib.coerceHoverinfo = _$coerce_154.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_154.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_154.validate; - -/* removed: var _$dates_155 = require('./dates'); */; -lib.dateTime2ms = _$dates_155.dateTime2ms; -lib.isDateTime = _$dates_155.isDateTime; -lib.ms2DateTime = _$dates_155.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_155.ms2DateTimeLocal; -lib.cleanDate = _$dates_155.cleanDate; -lib.isJSDate = _$dates_155.isJSDate; -lib.formatDate = _$dates_155.formatDate; -lib.incrementMonth = _$dates_155.incrementMonth; -lib.dateTick0 = _$dates_155.dateTick0; -lib.dfltRange = _$dates_155.dfltRange; -lib.findExactDates = _$dates_155.findExactDates; -lib.MIN_MS = _$dates_155.MIN_MS; -lib.MAX_MS = _$dates_155.MAX_MS; - -/* removed: var _$search_184 = require('./search'); */; -lib.findBin = _$search_184.findBin; -lib.sorterAsc = _$search_184.sorterAsc; -lib.sorterDes = _$search_184.sorterDes; -lib.distinctVals = _$search_184.distinctVals; -lib.roundUp = _$search_184.roundUp; - -/* removed: var _$stats_186 = require('./stats'); */; -lib.aggNums = _$stats_186.aggNums; -lib.len = _$stats_186.len; -lib.mean = _$stats_186.mean; -lib.variance = _$stats_186.variance; -lib.stdev = _$stats_186.stdev; -lib.interp = _$stats_186.interp; - -/* removed: var _$matrix_172 = require('./matrix'); */; -lib.init2dArray = _$matrix_172.init2dArray; -lib.transposeRagged = _$matrix_172.transposeRagged; -lib.dot = _$matrix_172.dot; -lib.translationMatrix = _$matrix_172.translationMatrix; -lib.rotationMatrix = _$matrix_172.rotationMatrix; -lib.rotationXYMatrix = _$matrix_172.rotationXYMatrix; -lib.apply2DTransform = _$matrix_172.apply2DTransform; -lib.apply2DTransform2 = _$matrix_172.apply2DTransform2; +var __BADNUM_167 = _$numerical_147.BADNUM; + +var lib = _$lib_167 = {}; + +lib.nestedProperty = _$nestedProperty_175; +lib.keyedContainer = _$keyedContainer_170; +lib.relativeAttr = _$relative_attr_183; +lib.isPlainObject = _$isPlainObject_169; +lib.mod = _$mod_174; +lib.toLogRange = _$toLogRange_190; +lib.relinkPrivateKeys = _$relinkPrivateKeys_184; +lib.ensureArray = _$ensureArray_157; + +/* removed: var _$is_array_168 = require('./is_array'); */; +lib.isTypedArray = _$is_array_168.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_168.isArrayOrTypedArray; + +/* removed: var _$coerce_155 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_155.valObjectMeta; +lib.coerce = _$coerce_155.coerce; +lib.coerce2 = _$coerce_155.coerce2; +lib.coerceFont = _$coerce_155.coerceFont; +lib.coerceHoverinfo = _$coerce_155.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_155.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_155.validate; + +/* removed: var _$dates_156 = require('./dates'); */; +lib.dateTime2ms = _$dates_156.dateTime2ms; +lib.isDateTime = _$dates_156.isDateTime; +lib.ms2DateTime = _$dates_156.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_156.ms2DateTimeLocal; +lib.cleanDate = _$dates_156.cleanDate; +lib.isJSDate = _$dates_156.isJSDate; +lib.formatDate = _$dates_156.formatDate; +lib.incrementMonth = _$dates_156.incrementMonth; +lib.dateTick0 = _$dates_156.dateTick0; +lib.dfltRange = _$dates_156.dfltRange; +lib.findExactDates = _$dates_156.findExactDates; +lib.MIN_MS = _$dates_156.MIN_MS; +lib.MAX_MS = _$dates_156.MAX_MS; + +/* removed: var _$search_185 = require('./search'); */; +lib.findBin = _$search_185.findBin; +lib.sorterAsc = _$search_185.sorterAsc; +lib.sorterDes = _$search_185.sorterDes; +lib.distinctVals = _$search_185.distinctVals; +lib.roundUp = _$search_185.roundUp; + +/* removed: var _$stats_187 = require('./stats'); */; +lib.aggNums = _$stats_187.aggNums; +lib.len = _$stats_187.len; +lib.mean = _$stats_187.mean; +lib.variance = _$stats_187.variance; +lib.stdev = _$stats_187.stdev; +lib.interp = _$stats_187.interp; + +/* removed: var _$matrix_173 = require('./matrix'); */; +lib.init2dArray = _$matrix_173.init2dArray; +lib.transposeRagged = _$matrix_173.transposeRagged; +lib.dot = _$matrix_173.dot; +lib.translationMatrix = _$matrix_173.translationMatrix; +lib.rotationMatrix = _$matrix_173.rotationMatrix; +lib.rotationXYMatrix = _$matrix_173.rotationXYMatrix; +lib.apply2DTransform = _$matrix_173.apply2DTransform; +lib.apply2DTransform2 = _$matrix_173.apply2DTransform2; /* removed: var _$angles_152 = require('./angles'); */; lib.deg2rad = _$angles_152.deg2rad; @@ -15387,54 +15397,54 @@ lib.rad2deg = _$angles_152.rad2deg; lib.wrap360 = _$angles_152.wrap360; lib.wrap180 = _$angles_152.wrap180; -/* removed: var _$geometry2d_163 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_163.segmentsIntersect; -lib.segmentDistance = _$geometry2d_163.segmentDistance; -lib.getTextLocation = _$geometry2d_163.getTextLocation; -lib.clearLocationCache = _$geometry2d_163.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_163.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_163.findPointOnPath; +/* removed: var _$geometry2d_164 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_164.segmentsIntersect; +lib.segmentDistance = _$geometry2d_164.segmentDistance; +lib.getTextLocation = _$geometry2d_164.getTextLocation; +lib.clearLocationCache = _$geometry2d_164.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_164.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_164.findPointOnPath; -/* removed: var _$extend_158 = require('./extend'); */; -lib.extendFlat = _$extend_158.extendFlat; -lib.extendDeep = _$extend_158.extendDeep; -lib.extendDeepAll = _$extend_158.extendDeepAll; -lib.extendDeepNoArrays = _$extend_158.extendDeepNoArrays; +/* removed: var _$extend_159 = require('./extend'); */; +lib.extendFlat = _$extend_159.extendFlat; +lib.extendDeep = _$extend_159.extendDeep; +lib.extendDeepAll = _$extend_159.extendDeepAll; +lib.extendDeepNoArrays = _$extend_159.extendDeepNoArrays; -/* removed: var _$loggers_171 = require('./loggers'); */; -lib.log = _$loggers_171.log; -lib.warn = _$loggers_171.warn; -lib.error = _$loggers_171.error; +/* removed: var _$loggers_172 = require('./loggers'); */; +lib.log = _$loggers_172.log; +lib.warn = _$loggers_172.warn; +lib.error = _$loggers_172.error; -/* removed: var _$regex_181 = require('./regex'); */; -lib.counterRegex = _$regex_181.counter; +/* removed: var _$regex_182 = require('./regex'); */; +lib.counterRegex = _$regex_182.counter; -/* removed: var _$throttle_188 = require('./throttle'); */; -lib.throttle = _$throttle_188.throttle; -lib.throttleDone = _$throttle_188.done; -lib.clearThrottle = _$throttle_188.clear; +/* removed: var _$throttle_189 = require('./throttle'); */; +lib.throttle = _$throttle_189.throttle; +lib.throttleDone = _$throttle_189.done; +lib.clearThrottle = _$throttle_189.clear; -lib.getGraphDiv = _$get_graph_div_164; +lib.getGraphDiv = _$get_graph_div_165; -lib._ = _$localize_170; +lib._ = _$localize_171; -lib.notifier = _$notifier_176; +lib.notifier = _$notifier_177; -lib.filterUnique = _$filterUnique_159; -lib.filterVisible = _$filterVisible_160; -lib.pushUnique = _$pushUnique_179; +lib.filterUnique = _$filterUnique_160; +lib.filterVisible = _$filterVisible_161; +lib.pushUnique = _$pushUnique_180; lib.cleanNumber = _$cleanNumber_153; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_11(v)) return __BADNUM_166; + if(!_$fastIsnumeric_11(v)) return __BADNUM_167; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_166; - return _$fastIsnumeric_11(v) ? Number(v) : __BADNUM_166; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_167; + return _$fastIsnumeric_11(v) ? Number(v) : __BADNUM_167; }; -lib.noop = _$noop_175; -lib.identity = _$identity_165; +lib.noop = _$noop_176; +lib.identity = _$identity_166; /** * swap x and y of the same attribute in container cont @@ -15933,6 +15943,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16126,7 +16193,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_166 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_167 = /^\w*$/; /* * Substitute values from an object into a string @@ -16147,7 +16214,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_166.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_167.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -17001,7 +17068,7 @@ var _$align_65 = function align(v, dv, v0, v1, anchor) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; // set cursors pointing toward the closest corner/side, @@ -17017,12 +17084,12 @@ var _$getCursor_66 = 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_166.constrain(Math.floor(x * 3), 0, 2); + else x = _$lib_167.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_166.constrain(Math.floor(y * 3), 0, 2); + else y = _$lib_167.constrain(Math.floor(y * 3), 0, 2); return cursorset[y][x]; }; @@ -17374,7 +17441,7 @@ function isUndefined(arg) { /* global jQuery:false */ -var __EventEmitter_157 = _$EventEmitter_10.EventEmitter; +var __EventEmitter_158 = _$EventEmitter_10.EventEmitter; var Events = { @@ -17384,10 +17451,10 @@ var Events = { * If we have already instantiated an emitter for this plot * return early. */ - if(plotObj._ev instanceof __EventEmitter_157) return plotObj; + if(plotObj._ev instanceof __EventEmitter_158) return plotObj; - var ev = new __EventEmitter_157(); - var internalEv = new __EventEmitter_157(); + var ev = new __EventEmitter_158(); + var internalEv = new __EventEmitter_158(); /* * Assign to plot._ev while we still live in a land @@ -17524,7 +17591,7 @@ var Events = { }; -var _$Events_157 = Events; +var _$Events_158 = Events; var _$unhover_68 = {}; /** @@ -17539,9 +17606,9 @@ var _$unhover_68 = {}; 'use strict'; -/* removed: var _$Events_157 = require('../../lib/events'); */; -/* removed: var _$throttle_188 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_164 = require('../../lib/get_graph_div'); */; +/* removed: var _$Events_158 = require('../../lib/events'); */; +/* removed: var _$throttle_189 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_165 = require('../../lib/get_graph_div'); */; /* removed: var _$constants_82 = require('../fx/constants'); */; @@ -17549,11 +17616,11 @@ var unhover = _$unhover_68 = {}; unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_164(gd); + gd = _$get_graph_div_165(gd); // Important, clear any queued hovers if(gd._fullLayout) { - _$throttle_188.clear(gd._fullLayout._uid + _$constants_82.HOVERID); + _$throttle_189.clear(gd._fullLayout._uid + _$constants_82.HOVERID); } unhover.raw(gd, evt, subplot); @@ -17567,7 +17634,7 @@ unhover.raw = function unhoverRaw(gd, evt) { if(!evt) evt = {}; if(evt.target && - _$Events_157.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + _$Events_158.triggerHandler(gd, 'plotly_beforehover', evt) === false) { return; } @@ -17593,21 +17660,21 @@ unhover.raw = function unhoverRaw(gd, evt) { */ 'use strict'; -var __counterRegex_214 = _$regex_181.counter; +var __counterRegex_215 = _$regex_182.counter; -var _$constants_214 = { +var _$constants_215 = { idRegex: { - x: __counterRegex_214('x'), - y: __counterRegex_214('y') + x: __counterRegex_215('x'), + y: __counterRegex_215('y') }, - attrRegex: __counterRegex_214('[xy]axis'), + attrRegex: __counterRegex_215('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_214('xaxis'), - yAxisMatch: __counterRegex_214('yaxis'), + xAxisMatch: __counterRegex_215('xaxis'), + yAxisMatch: __counterRegex_215('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -17654,6 +17721,7 @@ var _$constants_214 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -17679,10 +17747,10 @@ var _$dragelement_67 = {}; /* removed: var _$hasHover_13 = require('has-hover'); */; /* removed: var _$hasPassiveEvents_14 = require('has-passive-events'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -/* removed: var _$constants_214 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_215 = require('../../plots/cartesian/constants'); */; /* removed: var _$interactions_146 = require('../../constants/interactions'); */; var dragElement = _$dragelement_67 = {}; @@ -17839,7 +17907,7 @@ dragElement.init = function init(options) { e.preventDefault(); var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_214.MINDRAG; + var minDrag = options.minDrag || _$constants_215.MINDRAG; var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); var dx = dxdy[0]; var dy = dxdy[1]; @@ -17863,7 +17931,7 @@ dragElement.init = function init(options) { e.preventDefault(); if(_$hasHover_13) { - _$lib_166.removeElement(dragCover); + _$lib_167.removeElement(dragCover); } else if(cursor) { dragCover.documentElement.style.cursor = cursor; @@ -17944,7 +18012,7 @@ dragElement.coverSlip = coverSlip; function finishDrag(gd) { gd._dragging = false; - if(gd._replotPending) _$registry_258.call('plot', gd); + if(gd._replotPending) _$registry_259.call('plot', gd); } function pointerOffset(e) { @@ -18055,7 +18123,7 @@ var _$flipScale_57 = function flipScale(scl) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$scales_64 = require('./scales'); */; /* removed: var _$flipScale_57 = require('./flip_scale'); */; @@ -18065,8 +18133,8 @@ var _$calc_52 = function calc(trace, vals, containerStr, cLetter) { var container, inputContainer; if(containerStr) { - container = _$lib_166.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_166.nestedProperty(trace._input, containerStr).get(); + container = _$lib_167.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_167.nestedProperty(trace._input, containerStr).get(); } else { container = trace; @@ -18082,11 +18150,11 @@ var _$calc_52 = function calc(trace, vals, containerStr, cLetter) { scl = container.colorscale; if(auto !== false || min === undefined) { - min = _$lib_166.aggNums(Math.min, null, vals); + min = _$lib_167.aggNums(Math.min, null, vals); } if(auto !== false || max === undefined) { - max = _$lib_166.aggNums(Math.max, null, vals); + max = _$lib_167.aggNums(Math.max, null, vals); } if(min === max) { @@ -18132,9 +18200,9 @@ var _$calc_52 = function calc(trace, vals, containerStr, cLetter) { 'use strict'; -/* removed: var _$lib_166 = require('../lib'); */; -var __extendFlat_194 = _$lib_166.extendFlat; -var __isPlainObject_194 = _$lib_166.isPlainObject; +/* removed: var _$lib_167 = require('../lib'); */; +var __extendFlat_195 = _$lib_167.extendFlat; +var __isPlainObject_195 = _$lib_167.isPlainObject; var traceOpts = { valType: 'flaglist', @@ -18147,7 +18215,7 @@ var layoutOpts = { valType: 'flaglist', extras: ['none'], flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', 'layoutstyle', 'modebar', 'camera', 'arraydraw' ], @@ -18162,7 +18230,7 @@ var traceEditTypeFlags = traceOpts.flags.slice() var layoutEditTypeFlags = layoutOpts.flags.slice() .concat('layoutReplot'); -var _$edit_types_194 = { +var _$edit_types_195 = { traces: traceOpts, layout: layoutOpts, /* @@ -18215,10 +18283,10 @@ function falseObj(keys) { * @return {object} a new attributes object with `editType` modified as directed */ function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_194({}, attrs); + var out = __extendFlat_195({}, attrs); for(var key in out) { var attr = out[key]; - if(__isPlainObject_194(attr)) { + if(__isPlainObject_195(attr)) { out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } @@ -18229,7 +18297,7 @@ function overrideAll(attrs, editTypeOverride, overrideContainers) { function overrideOne(attr, editTypeOverride, overrideContainers, key) { if(attr.valType) { - var out = __extendFlat_194({}, attr); + var out = __extendFlat_195({}, attr); out.editType = editTypeOverride; if(Array.isArray(attr.items)) { @@ -18285,12 +18353,12 @@ _$attributes_69.dash = { /* removed: var _$font_attributes_236 = require('../font_attributes'); */; /* removed: var _$attributes_44 = require('../../components/color/attributes'); */; var dash = _$attributes_69.dash; -var __extendFlat_221 = _$extend_158.extendFlat; +var __extendFlat_222 = _$extend_159.extendFlat; -/* removed: var _$constants_214 = require('./constants'); */; +/* removed: var _$constants_215 = require('./constants'); */; -var _$layout_attributes_221 = { +var _$layout_attributes_222 = { visible: { valType: 'boolean', @@ -18346,10 +18414,10 @@ var _$layout_attributes_221 = { valType: 'info_array', items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} ], - editType: 'plot+margins', + editType: 'axrange+margins', impliedEdits: {'autorange': false}, }, @@ -18365,8 +18433,8 @@ var _$layout_attributes_221 = { scaleanchor: { valType: 'enumerated', values: [ - _$constants_214.idRegex.x.toString(), - _$constants_214.idRegex.y.toString() + _$constants_215.idRegex.x.toString(), + _$constants_215.idRegex.y.toString() ], editType: 'plot', @@ -18510,7 +18578,7 @@ var _$layout_attributes_221 = { editType: 'none', }, - spikedash: __extendFlat_221({}, dash, {dflt: 'dash', editType: 'none'}), + spikedash: __extendFlat_222({}, dash, {dflt: 'dash', editType: 'none'}), spikemode: { valType: 'flaglist', flags: ['toaxis', 'across', 'marker'], @@ -18698,8 +18766,8 @@ var _$layout_attributes_221 = { valType: 'enumerated', values: [ 'free', - _$constants_214.idRegex.x.toString(), - _$constants_214.idRegex.y.toString() + _$constants_215.idRegex.x.toString(), + _$constants_215.idRegex.y.toString() ], editType: 'plot+margins', @@ -18721,8 +18789,8 @@ var _$layout_attributes_221 = { valType: 'enumerated', values: [ 'free', - _$constants_214.idRegex.x.toString(), - _$constants_214.idRegex.y.toString() + _$constants_215.idRegex.x.toString(), + _$constants_215.idRegex.y.toString() ], editType: 'plot', @@ -18795,10 +18863,10 @@ var _$layout_attributes_221 = { 'use strict'; -/* removed: var _$layout_attributes_221 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$layout_attributes_222 = require('../../plots/cartesian/layout_attributes'); */; /* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; -var __extendFlat_46 = _$extend_158.extendFlat; -var __overrideAll_46 = _$edit_types_194.overrideAll; +var __extendFlat_46 = _$extend_159.extendFlat; +var __overrideAll_46 = _$edit_types_195.overrideAll; var _$attributes_46 = __overrideAll_46({ @@ -18883,11 +18951,11 @@ var _$attributes_46 = __overrideAll_46({ }, // a possible line around the bar itself - outlinecolor: _$layout_attributes_221.linecolor, - outlinewidth: _$layout_attributes_221.linewidth, + outlinecolor: _$layout_attributes_222.linecolor, + outlinewidth: _$layout_attributes_222.linewidth, // Should outlinewidth have {dflt: 0} ? // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_221.linecolor, + bordercolor: _$layout_attributes_222.linecolor, borderwidth: { valType: 'number', @@ -18902,30 +18970,30 @@ var _$attributes_46 = __overrideAll_46({ }, // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_221.tickmode, - nticks: _$layout_attributes_221.nticks, - tick0: _$layout_attributes_221.tick0, - dtick: _$layout_attributes_221.dtick, - tickvals: _$layout_attributes_221.tickvals, - ticktext: _$layout_attributes_221.ticktext, - ticks: __extendFlat_46({}, _$layout_attributes_221.ticks, {dflt: ''}), - ticklen: _$layout_attributes_221.ticklen, - tickwidth: _$layout_attributes_221.tickwidth, - tickcolor: _$layout_attributes_221.tickcolor, - showticklabels: _$layout_attributes_221.showticklabels, + tickmode: _$layout_attributes_222.tickmode, + nticks: _$layout_attributes_222.nticks, + tick0: _$layout_attributes_222.tick0, + dtick: _$layout_attributes_222.dtick, + tickvals: _$layout_attributes_222.tickvals, + ticktext: _$layout_attributes_222.ticktext, + ticks: __extendFlat_46({}, _$layout_attributes_222.ticks, {dflt: ''}), + ticklen: _$layout_attributes_222.ticklen, + tickwidth: _$layout_attributes_222.tickwidth, + tickcolor: _$layout_attributes_222.tickcolor, + showticklabels: _$layout_attributes_222.showticklabels, tickfont: _$font_attributes_236({ }), - tickangle: _$layout_attributes_221.tickangle, - tickformat: _$layout_attributes_221.tickformat, - tickformatstops: _$layout_attributes_221.tickformatstops, - tickprefix: _$layout_attributes_221.tickprefix, - showtickprefix: _$layout_attributes_221.showtickprefix, - ticksuffix: _$layout_attributes_221.ticksuffix, - showticksuffix: _$layout_attributes_221.showticksuffix, - separatethousands: _$layout_attributes_221.separatethousands, - exponentformat: _$layout_attributes_221.exponentformat, - showexponent: _$layout_attributes_221.showexponent, + tickangle: _$layout_attributes_222.tickangle, + tickformat: _$layout_attributes_222.tickformat, + tickformatstops: _$layout_attributes_222.tickformatstops, + tickprefix: _$layout_attributes_222.tickprefix, + showtickprefix: _$layout_attributes_222.showtickprefix, + ticksuffix: _$layout_attributes_222.ticksuffix, + showticksuffix: _$layout_attributes_222.showticksuffix, + separatethousands: _$layout_attributes_222.separatethousands, + exponentformat: _$layout_attributes_222.exponentformat, + showexponent: _$layout_attributes_222.showexponent, title: { valType: 'string', @@ -18954,8 +19022,8 @@ var _$attributes_46 = __overrideAll_46({ 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$layout_attributes_221 = require('./layout_attributes'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$layout_attributes_222 = require('./layout_attributes'); */; var _$handleTickLabelDefaults_229 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); @@ -18973,7 +19041,7 @@ var _$handleTickLabelDefaults_229 = function handleTickLabelDefaults(containerIn // explicitly provided var dfltFontColor = (containerOut.color === containerIn.color) ? containerOut.color : font.color; - _$lib_166.coerceFont(coerce, 'tickfont', { + _$lib_167.coerceFont(coerce, 'tickfont', { family: font.family, size: font.size, color: dfltFontColor @@ -19031,7 +19099,7 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_166.coerce(valueIn, valueOut, _$layout_attributes_221.tickformatstops, attr, dflt); + return _$lib_167.coerce(valueIn, valueOut, _$layout_attributes_222.tickformatstops, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -19056,18 +19124,18 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -/* removed: var _$layout_attributes_221 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_222 = require('./layout_attributes'); */; /** * options: inherits outerTicks from axes.handleAxisDefaults */ var _$handleTickDefaults_230 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_166.coerce2(containerIn, containerOut, _$layout_attributes_221, 'ticklen'), - tickWidth = _$lib_166.coerce2(containerIn, containerOut, _$layout_attributes_221, 'tickwidth'), - tickColor = _$lib_166.coerce2(containerIn, containerOut, _$layout_attributes_221, 'tickcolor', containerOut.color), + var tickLen = _$lib_167.coerce2(containerIn, containerOut, _$layout_attributes_222, 'ticklen'), + tickWidth = _$lib_167.coerce2(containerIn, containerOut, _$layout_attributes_222, 'tickwidth'), + tickColor = _$lib_167.coerce2(containerIn, containerOut, _$layout_attributes_222, 'tickcolor', containerOut.color), showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); if(!showTicks) { @@ -19089,7 +19157,7 @@ var _$handleTickDefaults_230 = function handleTickDefaults(containerIn, containe 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; var __ONEDAY_231 = _$numerical_147.ONEDAY; @@ -19140,10 +19208,10 @@ var _$handleTickValueDefaults_231 = function handleTickValueDefaults(containerIn // tick0 can have different valType for different axis types, so // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_166.dateTick0(containerOut.calendar) : 0; + var tick0Dflt = (axType === 'date') ? _$lib_167.dateTick0(containerOut.calendar) : 0; var tick0 = coerce('tick0', tick0Dflt); if(axType === 'date') { - containerOut.tick0 = _$lib_166.cleanDate(tick0, tick0Dflt); + containerOut.tick0 = _$lib_167.cleanDate(tick0, tick0Dflt); } // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely else if(_$fastIsnumeric_11(tick0) && dtick !== 'D1' && dtick !== 'D2') { @@ -19171,7 +19239,7 @@ var _$handleTickValueDefaults_231 = function handleTickValueDefaults(containerIn 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$handleTickValueDefaults_231 = require('../../plots/cartesian/tick_value_defaults'); */; /* removed: var _$handleTickDefaults_230 = require('../../plots/cartesian/tick_mark_defaults'); */; /* removed: var _$handleTickLabelDefaults_229 = require('../../plots/cartesian/tick_label_defaults'); */; @@ -19184,7 +19252,7 @@ var _$colorbarDefaults_48 = function colorbarDefaults(containerIn, containerOut, colorbarIn = containerIn.colorbar || {}; function coerce(attr, dflt) { - return _$lib_166.coerce(colorbarIn, colorbarOut, _$attributes_46, attr, dflt); + return _$lib_167.coerce(colorbarIn, colorbarOut, _$attributes_46, attr, dflt); } var thicknessmode = coerce('thicknessmode'); @@ -19205,7 +19273,7 @@ var _$colorbarDefaults_48 = function colorbarDefaults(containerIn, containerOut, coerce('y'); coerce('yanchor'); coerce('ypad'); - _$lib_166.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + _$lib_167.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); coerce('outlinecolor'); coerce('outlinewidth'); @@ -19220,7 +19288,7 @@ var _$colorbarDefaults_48 = function colorbarDefaults(containerIn, containerOut, _$handleTickDefaults_230(colorbarIn, colorbarOut, coerce, 'linear', opts); coerce('title', layout._dfltTitle.colorbar); - _$lib_166.coerceFont(coerce, 'titlefont', layout.font); + _$lib_167.coerceFont(coerce, 'titlefont', layout.font); coerce('titleside'); }; @@ -19235,11 +19303,11 @@ var _$colorbarDefaults_48 = function colorbarDefaults(containerIn, containerOut, 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; var _$hasColorbar_50 = function hasColorbar(container) { - return _$lib_166.isPlainObject(container.colorbar); + return _$lib_167.isPlainObject(container.colorbar); }; /** @@ -19275,7 +19343,7 @@ var _$isValidScale_61 = function isValidScale(scl) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$hasColorbar_50 = require('../colorbar/has_colorbar'); */; /* removed: var _$colorbarDefaults_48 = require('../colorbar/defaults'); */; @@ -19288,10 +19356,10 @@ var _$colorScaleDefaults_55 = function colorScaleDefaults(traceIn, traceOut, lay cLetter = opts.cLetter, containerStr = prefix.slice(0, prefix.length - 1), containerIn = prefix ? - _$lib_166.nestedProperty(traceIn, containerStr).get() || {} : + _$lib_167.nestedProperty(traceIn, containerStr).get() || {} : traceIn, containerOut = prefix ? - _$lib_166.nestedProperty(traceOut, containerStr).get() || {} : + _$lib_167.nestedProperty(traceOut, containerStr).get() || {} : traceOut, minIn = containerIn[cLetter + 'min'], maxIn = containerIn[cLetter + 'max'], @@ -19372,17 +19440,17 @@ var _$extractScale_56 = function extractScale(scl, cmin, cmax) { 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$isValidScale_61 = require('./is_valid_scale'); */; var _$hasColorscale_59 = function hasColorscale(trace, containerStr) { var container = containerStr ? - _$lib_166.nestedProperty(trace, containerStr).get() || {} : + _$lib_167.nestedProperty(trace, containerStr).get() || {} : trace; var color = container.color; var isArrayWithOneNumber = false; - if(_$lib_166.isArrayOrTypedArray(color)) { + if(_$lib_167.isArrayOrTypedArray(color)) { for(var i = 0; i < color.length; i++) { if(_$fastIsnumeric_11(color[i])) { isArrayWithOneNumber = true; @@ -19392,12 +19460,12 @@ var _$hasColorscale_59 = function hasColorscale(trace, containerStr) { } return ( - _$lib_166.isPlainObject(container) && ( + _$lib_167.isPlainObject(container) && ( isArrayWithOneNumber || container.showscale === true || (_$fastIsnumeric_11(container.cmin) && _$fastIsnumeric_11(container.cmax)) || _$isValidScale_61(container.colorscale) || - _$lib_166.isPlainObject(container.colorbar) + _$lib_167.isPlainObject(container.colorbar) ) ); }; @@ -20143,7 +20211,7 @@ var _$string_mappings_148 = { } }; -var _$svg_text_utils_187 = {}; +var _$svg_text_utils_188 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -20159,7 +20227,7 @@ var _$svg_text_utils_187 = {}; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; /* removed: var _$xmlns_namespaces_149 = require('../constants/xmlns_namespaces'); */; /* removed: var _$string_mappings_148 = require('../constants/string_mappings'); */; var LINE_SPACING = _$alignment_145.LINE_SPACING; @@ -20172,7 +20240,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_187.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_188.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) @@ -20215,7 +20283,7 @@ _$svg_text_utils_187.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_187.positionText(_context); + _$svg_text_utils_188.positionText(_context); if(_callback) _callback.call(_context); } @@ -20310,7 +20378,7 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_166.randstr([], 64); + var randomID = 'math-output-' + _$lib_167.randstr([], 64); var tmpDiv = _$d3_8.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) @@ -20321,7 +20389,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = _$d3_8.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_166.log('There was an error in the tex syntax.', _texString); + _$lib_167.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -20416,7 +20484,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_187.plainText = function(_str) { +_$svg_text_utils_188.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -20549,14 +20617,14 @@ function buildSVGText(containerNode, str) { // 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_166.log('Ignoring unexpected end tag .', str); + _$lib_167.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_166.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_167.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -20615,7 +20683,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -20630,11 +20701,11 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_187.lineCount = function lineCount(s) { +_$svg_text_utils_188.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_187.positionText = function positionText(s, x, y) { +_$svg_text_utils_188.positionText = function positionText(s, x, y) { return s.each(function() { var text = _$d3_8.select(this); @@ -20710,7 +20781,7 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_187.makeEditable = function(context, options) { +_$svg_text_utils_188.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; var dispatch = _$d3_8.dispatch('edit', 'input', 'cancel'); @@ -20833,7 +20904,7 @@ _$svg_text_utils_187.makeEditable = function(context, options) { // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_297 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_298 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -20869,17 +20940,20 @@ var _$makeBubbleSizeFn_297 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -var _$subtypes_302 = { +var _$subtypes_303 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -20888,8 +20962,8 @@ var _$subtypes_302 = { }, isBubble: function(trace) { - return _$lib_166.isPlainObject(trace.marker) && - _$lib_166.isArrayOrTypedArray(trace.marker.size); + return _$lib_167.isPlainObject(trace.marker) && + _$lib_167.isArrayOrTypedArray(trace.marker.size); } }; @@ -20909,19 +20983,19 @@ var _$drawing_70 = {}; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_26 = require('tinycolor2'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$colorscale_60 = require('../colorscale'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; /* removed: var _$xmlns_namespaces_149 = require('../../constants/xmlns_namespaces'); */; /* removed: var _$alignment_145 = require('../../constants/alignment'); */; var __LINE_SPACING_70 = _$alignment_145.LINE_SPACING; var __DESELECTDIM_70 = _$interactions_146.DESELECTDIM; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_297 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_298 = require('../../traces/scatter/make_bubble_size_func'); */; var drawing = _$drawing_70 = {}; @@ -20931,7 +21005,7 @@ var drawing = _$drawing_70 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_166.isPlainObject(family)) { + if(_$lib_167.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; @@ -21099,7 +21173,7 @@ drawing.fillGroupStyle = function(s) { shape.call(_$color_45.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_166.error(e, s); + _$lib_167.error(e, s); shape.remove(); } }); @@ -21162,8 +21236,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_258.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_297(trace); + if(_$registry_259.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_298(trace); sel.attr('d', function(d) { var r; @@ -21172,7 +21246,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_302.isBubble(trace) ? + r = _$subtypes_303.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -21212,10 +21286,10 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_166.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_45.defaultLine; + else if(_$lib_167.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_45.defaultLine; else lineColor = markerLine.color; - if(_$lib_166.isArrayOrTypedArray(marker.color)) { + if(_$lib_167.isArrayOrTypedArray(marker.color)) { fillColor = _$color_45.defaultLine; perPointGradient = true; } @@ -21268,7 +21342,7 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_166.identity); + .data([type + color1 + color2], _$lib_167.identity); gradient.exit().remove(); @@ -21311,9 +21385,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_167.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -21419,7 +21491,7 @@ drawing.selectedPointStyle = function(s, trace) { }); } - if(_$registry_258.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_259.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { var pt = _$d3_8.select(this); var mx = d.mx || marker.symbol || 0; @@ -21434,16 +21506,16 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_166.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_167.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_166.isArrayOrTypedArray(colorArray)) { + if(scl && _$lib_167.isArrayOrTypedArray(colorArray)) { return _$colorscale_60.makeColorScaleFunc( _$colorscale_60.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_166.identity; + else return _$lib_167.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; @@ -21463,7 +21535,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_187.lineCount(s) - 1) * __LINE_SPACING_70 + 1; + var numLines = (_$svg_text_utils_188.lineCount(s) - 1) * __LINE_SPACING_70 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -21482,7 +21554,7 @@ function extracTextFontSize(d, trace) { drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { var p = _$d3_8.select(this); - var text = _$lib_166.extractOption(d, trace, 'tx', 'text'); + var text = _$lib_167.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -21497,7 +21569,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_187.convertToTspans, gd) + .call(_$svg_text_utils_188.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -21625,33 +21697,28 @@ drawing.steps = function(shape) { // 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 = _$d3_8.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_149.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_167.ensureSingleById(_$d3_8.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_149.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_167.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; @@ -21696,7 +21763,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_166.extendFlat({}, out); + if(out) return _$lib_167.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -21740,7 +21807,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_166.extendFlat({}, out); + if(out) return _$lib_167.extendFlat({}, out); } } var testNode, tester; @@ -21758,7 +21825,7 @@ drawing.bBox = function(node, inTester, hash) { // standardize its position (and newline tspans if any) _$d3_8.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_187.positionText, 0, 0); + .call(_$svg_text_utils_188.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -21788,7 +21855,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_166.extendFlat({}, bb); + return _$lib_167.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -21813,15 +21880,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_8.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_8.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -21969,8 +22042,8 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; var _$calc_80 = function calc(gd) { var calcdata = gd.calcdata; @@ -21978,7 +22051,7 @@ var _$calc_80 = function calc(gd) { function makeCoerceHoverInfo(trace) { return function(val) { - return _$lib_166.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + return _$lib_167.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); }; } @@ -21989,9 +22062,9 @@ var _$calc_80 = function calc(gd) { // 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_258.traceIs(trace, 'pie')) continue; + if(_$registry_259.traceIs(trace, 'pie')) continue; - var fillFn = _$registry_258.traceIs(trace, '2dMap') ? paste : _$lib_166.fillArray; + var fillFn = _$registry_259.traceIs(trace, '2dMap') ? paste : _$lib_167.fillArray; fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); @@ -22007,7 +22080,7 @@ var _$calc_80 = function calc(gd) { }; function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_166.identity; + fn = fn || _$lib_167.identity; if(Array.isArray(traceAttr)) { cd[0][cdAttr] = fn(traceAttr); @@ -22025,13 +22098,33 @@ var _$helpers_84 = {}; 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; // look for either subplot or xaxis and yaxis attributes +// does not handle splom case _$helpers_84.getSubplot = function getSubplot(trace) { return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; }; +// is trace in given list of subplots? +// does handle splom case +_$helpers_84.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_84.getSubplot(trace)) !== -1; +}; + // convenience functions for mapping all relevant axes _$helpers_84.flat = function flat(subplots, v) { var out = new Array(subplots.length); @@ -22174,7 +22267,7 @@ _$helpers_84.appendArrayPointValue = function(pointData, trace, pointNumber) { var key = getPointKey(astr); if(pointData[key] === undefined) { - var val = _$lib_166.nestedProperty(trace, astr).get(); + var val = _$lib_167.nestedProperty(trace, astr).get(); var pointVal = getPointData(val, pointNumber); if(pointVal !== undefined) pointData[key] = pointVal; @@ -22204,7 +22297,7 @@ _$helpers_84.appendArrayMultiPointValues = function(pointData, trace, pointNumbe var key = getPointKey(astr); if(pointData[key] === undefined) { - var val = _$lib_166.nestedProperty(trace, astr).get(); + var val = _$lib_167.nestedProperty(trace, astr).get(); var keyVal = new Array(pointNumbers.length); for(var j = 0; j < pointNumbers.length; j++) { @@ -22251,7 +22344,7 @@ function getPointData(val, pointNumber) { // works with our CSS cursor classes (see css/_cursor.scss) // to apply cursors to d3 single-element selections. // omit cursor to revert to the default. -var _$setCursor_185 = function setCursor(el3, csr) { +var _$setCursor_186 = function setCursor(el3, csr) { (el3.attr('class') || '').split(' ').forEach(function(cls) { if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); }); @@ -22270,7 +22363,7 @@ var _$setCursor_185 = function setCursor(el3, csr) { 'use strict'; -/* removed: var _$setCursor_185 = require('./setcursor'); */; +/* removed: var _$setCursor_186 = require('./setcursor'); */; var STASHATTR = 'data-savedcursor'; var NO_CURSOR = '!!'; @@ -22281,7 +22374,7 @@ var NO_CURSOR = '!!'; * by moving the name of the original cursor to the data-savedcursor attr. * omit cursor to revert to the previously set value. */ -var _$overrideCursor_177 = function overrideCursor(el3, csr) { +var _$overrideCursor_178 = function overrideCursor(el3, csr) { var savedCursor = el3.attr(STASHATTR); if(csr) { if(!savedCursor) { @@ -22297,13 +22390,13 @@ var _$overrideCursor_177 = function overrideCursor(el3, csr) { el3.attr(STASHATTR, NO_CURSOR); } } - _$setCursor_185(el3, csr); + _$setCursor_186(el3, csr); } else if(savedCursor) { el3.attr(STASHATTR, null); - if(savedCursor === NO_CURSOR) _$setCursor_185(el3); - else _$setCursor_185(el3, savedCursor); + if(savedCursor === NO_CURSOR) _$setCursor_186(el3); + else _$setCursor_186(el3, savedCursor); } }; @@ -22317,7 +22410,7 @@ var _$overrideCursor_177 = function overrideCursor(el3, csr) { 'use strict'; -var _$animation_attributes_204 = { +var _$animation_attributes_205 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -22464,7 +22557,7 @@ var _$frame_attributes_237 = { 'use strict'; /* removed: var _$attributes_51 = require('./attributes'); */; -var __extendFlat_53 = _$extend_158.extendFlat; +var __extendFlat_53 = _$extend_159.extendFlat; /* removed: var _$scales_64 = require('./scales.js'); */; /* @@ -22530,7 +22623,7 @@ var _$makeColorScaleAttributes_53 = function makeColorScaleAttributes(context, e 'use strict'; -var _$constants_286 = { +var _$constants_287 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -22558,13 +22651,13 @@ var _$constants_286 = { /* removed: var _$makeColorScaleAttributes_53 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_46 = require('../../components/colorbar/attributes'); */; /* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; -var __dash_280 = _$attributes_69.dash; +var __dash_281 = _$attributes_69.dash; /* removed: var _$drawing_70 = require('../../components/drawing'); */; -/* removed: var _$constants_286 = require('./constants'); */; -var __extendFlat_280 = _$extend_158.extendFlat; +/* removed: var _$constants_287 = require('./constants'); */; +var __extendFlat_281 = _$extend_159.extendFlat; -var _$attributes_280 = { +var _$attributes_281 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -22666,7 +22759,7 @@ var _$attributes_280 = { editType: 'plot', }, - dash: __extendFlat_280({}, __dash_280, {editType: 'style'}), + dash: __extendFlat_281({}, __dash_281, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -22706,7 +22799,7 @@ var _$attributes_280 = { editType: 'style', }, - marker: __extendFlat_280({ + marker: __extendFlat_281({ symbol: { valType: 'enumerated', values: _$drawing_70.symbolList, @@ -22775,7 +22868,7 @@ var _$attributes_280 = { }, colorbar: _$attributes_46, - line: __extendFlat_280({ + line: __extendFlat_281({ width: { valType: 'number', min: 0, @@ -22926,12 +23019,12 @@ var _$attributes_280 = { 'use strict'; -/* removed: var _$attributes_280 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_280.marker; +/* removed: var _$attributes_281 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_281.marker; var _$area_attributes_251 = { - r: _$attributes_280.r, - t: _$attributes_280.t, + r: _$attributes_281.r, + t: _$attributes_281.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -22952,11 +23045,11 @@ var _$area_attributes_251 = { 'use strict'; -/* removed: var _$layout_attributes_221 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_252 = _$extend_158.extendFlat; -var __overrideAll_252 = _$edit_types_194.overrideAll; +/* removed: var _$layout_attributes_222 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_252 = _$extend_159.extendFlat; +var __overrideAll_252 = _$edit_types_195.overrideAll; -var domainAttr = __extendFlat_252({}, _$layout_attributes_221.domain, { +var domainAttr = __extendFlat_252({}, _$layout_attributes_222.domain, { }); @@ -23056,7 +23149,7 @@ var _$axis_attributes_252 = __overrideAll_252({ } }, 'plot', 'nested'); -var _$plot_schema_200 = {}; +var _$plot_schema_201 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -23068,22 +23161,23 @@ var _$plot_schema_200 = {}; 'use strict'; -/* removed: var _$registry_258 = require('../registry'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$registry_259 = require('../registry'); */; +/* removed: var _$lib_167 = require('../lib'); */; -/* removed: var _$attributes_206 = require('../plots/attributes'); */; +/* removed: var _$attributes_207 = require('../plots/attributes'); */; /* removed: var _$layout_attributes_248 = require('../plots/layout_attributes'); */; /* removed: var _$frame_attributes_237 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_204 = require('../plots/animation_attributes'); */; +/* removed: var _$animation_attributes_205 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet /* removed: var _$area_attributes_251 = require('../plots/polar/legacy/area_attributes'); */; /* removed: var _$axis_attributes_252 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_194 = require('./edit_types'); */; +/* removed: var _$edit_types_195 = require('./edit_types'); */; -var __extendFlat_200 = _$lib_166.extendFlat; -var __extendDeepAll_200 = _$lib_166.extendDeepAll; +var __extendFlat_201 = _$lib_167.extendFlat; +var __extendDeepAll_201 = _$lib_167.extendDeepAll; +var __isPlainObject_201 = _$lib_167.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -23091,10 +23185,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_200.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_200.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_200.DEPRECATED = DEPRECATED; -_$plot_schema_200.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_201.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_201.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_201.DEPRECATED = DEPRECATED; +_$plot_schema_201.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -23107,26 +23201,26 @@ _$plot_schema_200.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_200.get = function() { +_$plot_schema_201.get = function() { var traces = {}; - _$registry_258.allTypes.concat('area').forEach(function(type) { + _$registry_259.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_258.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_259.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_166.valObjectMeta, + valObjects: _$lib_167.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_194.traces, - layout: _$edit_types_194.layout + traces: _$edit_types_195.traces, + layout: _$edit_types_195.layout }, impliedEdits: { @@ -23139,7 +23233,7 @@ _$plot_schema_200.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_204) + animation: formatAttributes(_$animation_attributes_205) }; }; @@ -23170,7 +23264,7 @@ _$plot_schema_200.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_200.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_201.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -23182,10 +23276,10 @@ _$plot_schema_200.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_200.isValObject(attr)) return; + if(_$plot_schema_201.isValObject(attr)) return; - if(_$lib_166.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_200.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_201(attr) && attrName !== 'impliedEdits') { + _$plot_schema_201.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -23197,7 +23291,7 @@ _$plot_schema_200.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_200.isValObject = function(obj) { +_$plot_schema_201.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -23211,7 +23305,7 @@ _$plot_schema_200.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_200.findArrayAttributes = function(trace) { +_$plot_schema_201.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -23234,8 +23328,8 @@ _$plot_schema_200.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_166.nestedProperty(trace, astr).get(); - if(!_$lib_166.isArrayOrTypedArray(val)) return; + var val = _$lib_167.nestedProperty(trace, astr).get(); + if(!_$lib_167.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -23244,9 +23338,9 @@ _$plot_schema_200.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_200.crawl(_$attributes_206, callback); + _$plot_schema_201.crawl(_$attributes_207, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_200.crawl(trace._module.attributes, callback); + _$plot_schema_201.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -23259,7 +23353,7 @@ _$plot_schema_200.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_200.crawl(module.attributes, callback, 1); + _$plot_schema_201.crawl(module.attributes, callback, 1); } } } @@ -23271,8 +23365,8 @@ _$plot_schema_200.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_200.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_166.filterUnique(arrayAttributes); + _$plot_schema_201.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_167.filterUnique(arrayAttributes); } return arrayAttributes; @@ -23293,18 +23387,19 @@ _$plot_schema_200.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_200.getTraceValObject = function(trace, parts) { +_$plot_schema_201.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_258.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_259.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } @@ -23315,7 +23410,7 @@ _$plot_schema_200.getTraceValObject = function(trace, parts) { // 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_258.modules[trace.type || _$attributes_206.type.dflt] || {})._module; + if(!_module) _module = (_$registry_259.modules[trace.type || _$attributes_207.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -23330,7 +23425,7 @@ _$plot_schema_200.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_206[head]; + if(!valObject) valObject = _$attributes_207[head]; } return recurseIntoValObject(valObject, parts, i); @@ -23349,7 +23444,7 @@ _$plot_schema_200.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_200.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_201.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -23400,8 +23495,8 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_258.componentsRegistry) { - _module = _$registry_258.componentsRegistry[key]; + for(key in _$registry_259.componentsRegistry) { + _module = _$registry_259.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } @@ -23431,7 +23526,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_166.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_201(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -23478,7 +23573,7 @@ function getTraceAttributes(type) { basePlotModule = {}; } else { - _module = _$registry_258.modules[type]._module, + _module = _$registry_259.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -23488,14 +23583,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_200(attributes, _$attributes_206); + __extendDeepAll_201(attributes, _$attributes_207); // module attributes - __extendDeepAll_200(attributes, _module.attributes); + __extendDeepAll_201(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_200(attributes, basePlotModule.attributes); + __extendDeepAll_201(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -23510,7 +23605,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_200(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_201(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -23522,21 +23617,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_200(layoutAttributes, _$layout_attributes_248); + __extendDeepAll_201(layoutAttributes, _$layout_attributes_248); // add base plot module layout attributes - for(key in _$registry_258.subplotsRegistry) { - _module = _$registry_258.subplotsRegistry[key]; + for(key in _$registry_259.subplotsRegistry) { + _module = _$registry_259.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -23545,8 +23639,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_258.componentsRegistry) { - _module = _$registry_258.componentsRegistry[key]; + for(key in _$registry_259.componentsRegistry) { + _module = _$registry_259.componentsRegistry[key]; var schema = _module.schema; /* @@ -23577,12 +23671,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_258.transformsRegistry[type]; - var attributes = __extendDeepAll_200({}, _module.attributes); + var _module = _$registry_259.transformsRegistry[type]; + var attributes = __extendDeepAll_201({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_258.componentsRegistry).forEach(function(k) { - var _module = _$registry_258.componentsRegistry[k]; + Object.keys(_$registry_259.componentsRegistry).forEach(function(k) { + var _module = _$registry_259.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -23598,7 +23692,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_166.extendDeepAll({}, _$frame_attributes_237) + frames: _$lib_167.extendDeepAll({}, _$frame_attributes_237) }; formatAttributes(attrs); @@ -23609,6 +23703,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -23625,7 +23720,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_200.isValObject(attr)) { + if(_$plot_schema_201.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -23637,13 +23732,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_166.isPlainObject(attr)) { + else if(__isPlainObject_201(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_200.crawl(attrs, callback); + _$plot_schema_201.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -23662,35 +23757,58 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_200.crawl(attrs, callback); + _$plot_schema_201.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_201(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_200(layoutAttributes, { + __extendFlat_201(layoutAttributes, { radialaxis: _$axis_attributes_252.radialaxis, angularaxis: _$axis_attributes_252.angularaxis }); - __extendFlat_200(layoutAttributes, _$axis_attributes_252.layout); + __extendFlat_201(layoutAttributes, _$axis_attributes_252.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_166.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_200({}, _module.layoutAttributes); + var np = _$lib_167.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_201({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_166.nestedProperty(baseAttrs, astr); + var np = _$lib_167.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_200(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_201(np.get() || {}, newAttrs)); } -var _$axis_ids_212 = {}; +var _$axis_ids_213 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -23701,30 +23819,30 @@ var _$axis_ids_212 = {}; 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; -/* removed: var _$constants_214 = require('./constants'); */; +/* removed: var _$constants_215 = require('./constants'); */; // 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. -_$axis_ids_212.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_214.AX_ID_PATTERN)) return; +_$axis_ids_213.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_215.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_212.name2id = function name2id(name) { - if(!name.match(_$constants_214.AX_NAME_PATTERN)) return; +_$axis_ids_213.name2id = function name2id(name) { + if(!name.match(_$constants_215.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_212.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_214.AX_ID_PATTERN)) return; +_$axis_ids_213.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_215.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -23733,11 +23851,11 @@ _$axis_ids_212.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_212.list = function(gd, axLetter, only2d) { +_$axis_ids_213.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_212.listIds(gd, axLetter); + var idList = _$axis_ids_213.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -23762,7 +23880,7 @@ _$axis_ids_212.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_212.listIds = function(gd, axLetter) { +_$axis_ids_213.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -23773,35 +23891,35 @@ _$axis_ids_212.listIds = function(gd, axLetter) { // 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 -_$axis_ids_212.getFromId = function(gd, id, type) { +_$axis_ids_213.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[_$axis_ids_212.id2name(id)]; + return fullLayout[_$axis_ids_213.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_212.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_213.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_258.traceIs(fullTrace, 'gl3d')) { + if(_$registry_259.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_212.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_213.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_212.idSort = function(id1, id2) { +_$axis_ids_213.idSort = function(id1, id2) { var letter1 = id1.charAt(0); var letter2 = id2.charAt(0); if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1; @@ -23819,8 +23937,8 @@ var _$command_234 = {}; 'use strict'; -/* removed: var _$registry_258 = require('../registry'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$registry_259 = require('../registry'); */; +/* removed: var _$lib_167 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -23924,7 +24042,7 @@ _$command_234.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_166.log('Unable to automatically bind plot updates to API command'); + _$lib_167.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -24042,7 +24160,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_166.nestedProperty(container, binding.prop).get(); + value = _$lib_167.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -24074,7 +24192,7 @@ function bindingValueHasChanged(gd, binding, cache) { _$command_234.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_258.apiMethodRegistry[method]; + var _method = _$registry_259.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -24083,7 +24201,7 @@ _$command_234.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_166.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_167.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; @@ -24133,7 +24251,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_166.isPlainObject(astr)) { + } else if(_$lib_167.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -24157,7 +24275,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_166.isPlainObject(astr)) { + } else if(_$lib_167.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -24223,7 +24341,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_166.isPlainObject(attr)) { + if(_$lib_167.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -24232,6 +24350,32 @@ function crawl(attrs, callback, path, depth) { }); } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_257 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + var _$plots_250 = {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -24247,25 +24391,27 @@ var _$plots_250 = {}; /* removed: var _$d3_8 = require('d3'); */; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$registry_258 = require('../registry'); */; -/* removed: var _$plot_schema_200 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_212 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_166 = require('../lib'); */; -var _ = _$lib_166._; +/* removed: var _$registry_259 = require('../registry'); */; +/* removed: var _$plot_schema_201 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_167 = require('../lib'); */; /* removed: var _$color_45 = require('../components/color'); */; var __BADNUM_250 = _$numerical_147.BADNUM; -var plots = _$plots_250 = {}; +/* removed: var _$axis_ids_213 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_250 = _$sort_modules_257.sortBasePlotModules; -/* removed: var _$animation_attributes_204 = require('./animation_attributes'); */; +/* removed: var _$animation_attributes_205 = require('./animation_attributes'); */; /* removed: var _$frame_attributes_237 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_166.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_167.relinkPrivateKeys; +var _ = _$lib_167._; + +var plots = _$plots_250 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_166.extendFlat(plots, _$registry_258); +_$lib_167.extendFlat(plots, _$registry_259); -plots.attributes = _$attributes_206; +plots.attributes = _$attributes_207; plots.attributes.type.values = plots.allTypes; plots.fontAttrs = _$font_attributes_236; plots.layoutAttributes = _$layout_attributes_248; @@ -24285,15 +24431,15 @@ plots.hasSimpleAPICommandBindings = _$command_234.hasSimpleAPICommandBindings; // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_166.getGraphDiv(gd); + gd = _$lib_167.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_258.getComponentMethod('annotations', 'draw')(gd); - _$registry_258.getComponentMethod('legend', 'draw')(gd); + _$registry_259.getComponentMethod('annotations', 'draw')(gd); + _$registry_259.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -24306,7 +24452,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_166.getGraphDiv(gd); + gd = _$lib_167.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -24337,7 +24483,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_258.call('relayout', gd, {autosize: true}).then(function() { + _$registry_259.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -24367,12 +24513,8 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_167.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', 'fill': _$color_45.defaultLine, @@ -24384,12 +24526,11 @@ plots.addLinks = function(gd) { links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -24527,6 +24668,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -24561,7 +24704,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -24604,12 +24746,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_259.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_167.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_167.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_167.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -24620,7 +24788,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -24629,6 +24797,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -24639,7 +24818,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -24651,17 +24830,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_212.list(gd); + var axList = _$axis_ids_213.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -24671,6 +24850,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_250); }; /** @@ -24689,7 +24871,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_258.subplotsRegistry; + var subplotsRegistry = _$registry_259.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -24702,7 +24884,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_166.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_167.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -24723,14 +24905,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_166.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_167.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_166.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_167.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -24775,7 +24957,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_258.localeRegistry; + locales = _$registry_259.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -24784,7 +24966,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_258.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_259.localeRegistry.en.format); return formatObj; } @@ -24836,30 +25018,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_259.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -24867,7 +25047,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -24939,8 +25119,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_212.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_212.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_213.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_213.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -24985,13 +25165,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_212.list(mockGd, null, true); + var axList = _$axis_ids_213.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_212.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_213.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -25013,7 +25193,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_212.getFromId(mockGd, ax.anchor); + _$axis_ids_213.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -25042,7 +25222,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_212.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_213.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -25083,17 +25263,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_200.crawl( + _$plot_schema_201.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_166.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_167.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_166.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_167.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -25115,8 +25295,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_166.pushUnique(modules, _module); - _$lib_166.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_167.pushUnique(modules, _module); + _$lib_167.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -25176,11 +25356,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_258.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_259.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_258.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_259.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -25209,7 +25389,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(opts || {}, optsOut, _$animation_attributes_204, attr, dflt); + return _$lib_167.coerce(opts || {}, optsOut, _$animation_attributes_205, attr, dflt); } coerce('mode'); @@ -25241,7 +25421,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(opts || {}, optsOut, _$animation_attributes_204.frame, attr, dflt); + return _$lib_167.coerce(opts || {}, optsOut, _$animation_attributes_205.frame, attr, dflt); } coerce('duration'); @@ -25254,7 +25434,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(opts || {}, optsOut, _$animation_attributes_204.transition, attr, dflt); + return _$lib_167.coerce(opts || {}, optsOut, _$animation_attributes_205.transition, attr, dflt); } coerce('duration'); @@ -25267,7 +25447,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(frameIn, frameOut, _$frame_attributes_237, attr, dflt); + return _$lib_167.coerce(frameIn, frameOut, _$frame_attributes_237, attr, dflt); } coerce('group'); @@ -25288,7 +25468,7 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) var i; function coerce(attr, dflt) { - return _$lib_166.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_167.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -25304,9 +25484,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -25316,18 +25496,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_166.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_167.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_166.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_167.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_166.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_167.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_166.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_167.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -25337,12 +25517,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_258.traceIs(traceOut, 'showLegend')) { + if(_$registry_259.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_258.getComponentMethod( + _$registry_259.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -25351,12 +25531,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_166.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_167.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_258.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_259.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_258.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_259.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -25400,17 +25580,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_166.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_167.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_166.pushUnique(transformModules, _module); + _$lib_167.pushUnique(transformModules, _module); } else { - transformOut = _$lib_166.extendFlat({}, transformIn); + transformOut = _$lib_167.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -25442,14 +25622,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_166.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_167.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_166.coerceFont(coerce, 'font'); + var globalFont = _$lib_167.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_166.coerceFont(coerce, 'titlefont', { + _$lib_167.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -25477,7 +25657,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_258.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_259.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -25488,12 +25668,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_258.getComponentMethod( + _$registry_259.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_258.getComponentMethod( + _$registry_259.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -25505,7 +25685,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_166.isPlotDiv(gd); + var isPlotDiv = _$lib_167.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -25593,11 +25773,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_258.componentsRegistry; + var componentsRegistry = _$registry_259.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_258.subplotsRegistry.cartesian; + var Cartesian = _$registry_259.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -25616,13 +25796,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_258.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_259.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_166.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_167.subplotSort); } // base plot module layout defaults @@ -25694,7 +25874,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_166.clearThrottle(); + _$lib_167.clearThrottle(); // data and layout delete gd.data; @@ -25750,7 +25930,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_166.pushUnique(styleModules, _module.style); + _$lib_167.pushUnique(styleModules, _module.style); } } @@ -25905,7 +26085,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_258.call('plot', gd); + return _$registry_259.call('plot', gd); } }; @@ -25946,7 +26126,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_166.isPlainObject(d)) { + if(_$lib_167.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -25969,7 +26149,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_166.isPlainObject(d.stream)) { + if(!_$lib_167.isPlainObject(d.stream)) { continue; } } @@ -25995,7 +26175,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_166.isJSDate(d)) return _$lib_166.ms2DateTimeLocal(+d); + if(_$lib_167.isJSDate(d)) return _$lib_167.ms2DateTimeLocal(+d); return d; } @@ -26192,8 +26372,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_166.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_166.expandObjectPaths(copy); + var copy = _$lib_167.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_167.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -26201,29 +26381,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_166.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_167.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_166.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_167.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_166.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_167.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_166.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_167.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_166.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_167.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_166.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_167.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -26248,7 +26428,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_258.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_259.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -26322,7 +26502,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_166.expandObjectPaths(_$lib_166.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_167.expandObjectPaths(_$lib_167.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -26349,7 +26529,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_258.getComponentMethod('errorbars', 'calc')(gd); + _$registry_259.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -26397,7 +26577,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_258.call('redraw', gd); + return _$registry_259.call('redraw', gd); }); } @@ -26429,7 +26609,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_166.expandObjectPaths(layout); + var newLayout = _$lib_167.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -26439,7 +26619,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_166.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_167.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -26469,7 +26649,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_258.call('redraw', gd); + return _$registry_259.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -26504,7 +26684,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_166.syncOrAsync(seq, gd); + var transitionStarting = _$lib_167.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -26516,7 +26696,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_212.list(gd), + var axList = _$axis_ids_213.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -26560,7 +26740,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_200.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_201.findArrayAttributes(trace); } // add polar axes to axis list @@ -26604,14 +26784,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -26646,7 +26827,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_258.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_259.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -26697,7 +26883,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_166.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_167.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -26719,11 +26905,11 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$drawing_70 = require('../drawing'); */; /* removed: var _$color_45 = require('../color'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; /* removed: var _$interactions_146 = require('../../constants/interactions'); */; var _$titles_138 = { @@ -26804,10 +26990,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_167.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -26825,7 +27008,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_166.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_167.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -26853,7 +27036,7 @@ function draw(gd, titleClass, options) { 'font-weight': _$plots_250.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_187.convertToTspans, gd); + .call(_$svg_text_utils_188.convertToTspans, gd); return _$plots_250.previousPromises(gd); } @@ -26903,7 +27086,7 @@ function draw(gd, titleClass, options) { avoid.selection.each(function() { var avoidbb = _$drawing_70.bBox(this); - if(_$lib_166.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_167.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -26943,12 +27126,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_187.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_188.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_258.call('restyle', gd, prop, text, traceIndex); + _$registry_259.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_258.call('relayout', gd, prop, text); + _$registry_259.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -26957,7 +27140,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_187.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_188.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -26978,10 +27161,10 @@ function draw(gd, titleClass, options) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -var __FP_SAFE_208 = _$numerical_147.FP_SAFE; +/* removed: var _$lib_167 = require('../../lib'); */; +var __FP_SAFE_209 = _$numerical_147.FP_SAFE; -var _$autorange_208 = { +var _$autorange_209 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -27026,7 +27209,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_166.simpleMap(ax.range, ax.r2l); + var rng = _$lib_167.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -27119,7 +27302,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_166.simpleMap(newRange, ax.l2r || Number); + return _$lib_167.simpleMap(newRange, ax.l2r || Number); } /* @@ -27151,7 +27334,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_166.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_167.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -27173,7 +27356,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_166.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_167.extendFlat({}, axeRangeOpts); } } @@ -27186,6 +27369,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -27246,14 +27431,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_208) vmax = v; + if(v > vmax && v < __FP_SAFE_209) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_208) vmin = v; - if(v > vmax && v < __FP_SAFE_208) vmax = v; + if(v < vmin && v > -__FP_SAFE_209) vmin = v; + if(v > vmax && v < __FP_SAFE_209) vmax = v; } } @@ -27287,7 +27472,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_208 : __lessOrEqual_208; + var atLeastAsExtreme = k ? __greaterOrEqual_209 : __lessOrEqual_209; includeThis = true; /* @@ -27338,11 +27523,11 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_11(v) && Math.abs(v) < __FP_SAFE_208; + return _$fastIsnumeric_11(v) && Math.abs(v) < __FP_SAFE_209; } -function __lessOrEqual_208(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_208(v0, v1) { return v0 >= v1; } +function __lessOrEqual_209(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_209(v0, v1) { return v0 >= v1; } /** * Copyright 2012-2018, Plotly, Inc. @@ -27357,10 +27542,10 @@ function __greaterOrEqual_208(v0, v1) { return v0 >= v1; } /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -var __BADNUM_210 = _$numerical_147.BADNUM; +/* removed: var _$lib_167 = require('../../lib'); */; +var __BADNUM_211 = _$numerical_147.BADNUM; -var _$autoType_210 = function autoType(array, calendar) { +var _$autoType_211 = function autoType(array, calendar) { if(moreDates(array, calendar)) return 'date'; if(category(array)) return 'category'; if(linearOK(array)) return 'linear'; @@ -27393,7 +27578,7 @@ function moreDates(a, calendar) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_166.isDateTime(ai, calendar)) dcnt += 1; + if(_$lib_167.isDateTime(ai, calendar)) dcnt += 1; if(_$fastIsnumeric_11(ai)) ncnt += 1; } @@ -27411,7 +27596,7 @@ function category(a) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_166.cleanNumber(ai) !== __BADNUM_210) curvenums++; + if(_$lib_167.cleanNumber(ai) !== __BADNUM_211) curvenums++; else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; } @@ -27432,18 +27617,18 @@ function category(a) { /* removed: var _$d3_8 = require('d3'); */; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -var cleanNumber = _$lib_166.cleanNumber; -var ms2DateTime = _$lib_166.ms2DateTime; -var dateTime2ms = _$lib_166.dateTime2ms; -var ensureNumber = _$lib_166.ensureNumber; +/* removed: var _$lib_167 = require('../../lib'); */; +var cleanNumber = _$lib_167.cleanNumber; +var ms2DateTime = _$lib_167.ms2DateTime; +var dateTime2ms = _$lib_167.dateTime2ms; +var ensureNumber = _$lib_167.ensureNumber; /* removed: var _$numerical_147 = require('../../constants/numerical'); */; var __FP_SAFE_228 = _$numerical_147.FP_SAFE; var __BADNUM_228 = _$numerical_147.BADNUM; -/* removed: var _$constants_214 = require('./constants'); */; -/* removed: var _$axis_ids_212 = require('./axis_ids'); */; +/* removed: var _$constants_215 = require('./constants'); */; +/* removed: var _$axis_ids_213 = require('./axis_ids'); */; function fromLog(v) { return Math.pow(10, v); @@ -27635,7 +27820,7 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { * 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_166.identity; + ax.d2r = ax.r2d = _$lib_167.identity; ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; @@ -27643,7 +27828,7 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { 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_166.cleanDate(v, __BADNUM_228, ax.calendar); }; + ax.cleanPos = function(v) { return _$lib_167.cleanDate(v, __BADNUM_228, ax.calendar); }; } else if(ax.type === 'category') { // d is categories (string) @@ -27700,39 +27885,39 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { if(!opts) opts = {}; if(!rangeAttr) rangeAttr = 'range'; - var range = _$lib_166.nestedProperty(ax, rangeAttr).get(); + var range = _$lib_167.nestedProperty(ax, rangeAttr).get(); var i, dflt; - if(ax.type === 'date') dflt = _$lib_166.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_214.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_214.DFLTRANGEX; + if(ax.type === 'date') dflt = _$lib_167.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_215.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_215.DFLTRANGEX; // make sure we don't later mutate the defaults dflt = dflt.slice(); if(!range || range.length !== 2) { - _$lib_166.nestedProperty(ax, rangeAttr).set(dflt); + _$lib_167.nestedProperty(ax, rangeAttr).set(dflt); return; } if(ax.type === 'date') { // check if milliseconds or js date objects are provided for range // and convert to date strings - range[0] = _$lib_166.cleanDate(range[0], __BADNUM_228, ax.calendar); - range[1] = _$lib_166.cleanDate(range[1], __BADNUM_228, ax.calendar); + range[0] = _$lib_167.cleanDate(range[0], __BADNUM_228, ax.calendar); + range[1] = _$lib_167.cleanDate(range[1], __BADNUM_228, ax.calendar); } for(i = 0; i < 2; i++) { if(ax.type === 'date') { - if(!_$lib_166.isDateTime(range[i], ax.calendar)) { + if(!_$lib_167.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_166.constrain(ax.r2l(range[0]), - _$lib_166.MIN_MS + 1000, _$lib_166.MAX_MS - 1000); + var linCenter = _$lib_167.constrain(ax.r2l(range[0]), + _$lib_167.MIN_MS + 1000, _$lib_167.MAX_MS - 1000); range[0] = ax.l2r(linCenter - 1000); range[1] = ax.l2r(linCenter + 1000); break; @@ -27774,7 +27959,7 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { // make sure we have a domain (pull it in from the axis // this one is overlaying if necessary) if(ax.overlaying) { - var ax2 = _$axis_ids_212.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + var ax2 = _$axis_ids_213.getFromId({ _fullLayout: fullLayout }, ax.overlaying); ax.domain = ax2.domain; } @@ -27827,7 +28012,7 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { arrayIn = trace[axLetter]; len = trace._length || arrayIn.length; - if(_$lib_166.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(_$lib_167.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { if(len === arrayIn.length) { return arrayIn; } else if(arrayIn.subarray) { @@ -27868,11 +28053,15 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { 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]); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } }; ax.clearCalc = function() { @@ -27916,7 +28105,7 @@ var _$setConvert_228 = function setConvert(ax, fullLayout) { delete ax._forceTick0; }; -var _$axes_209 = {}; +var _$axes_210 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -27932,9 +28121,9 @@ var _$axes_209 = {}; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; /* removed: var _$titles_138 = require('../../components/titles'); */; /* removed: var _$color_45 = require('../../components/color'); */; /* removed: var _$drawing_70 = require('../../components/drawing'); */; @@ -27942,33 +28131,33 @@ var _$axes_209 = {}; /* removed: var _$numerical_147 = require('../../constants/numerical'); */; var ONEAVGYEAR = _$numerical_147.ONEAVGYEAR; var ONEAVGMONTH = _$numerical_147.ONEAVGMONTH; -var __ONEDAY_209 = _$numerical_147.ONEDAY; -var __ONEHOUR_209 = _$numerical_147.ONEHOUR; -var __ONEMIN_209 = _$numerical_147.ONEMIN; -var __ONESEC_209 = _$numerical_147.ONESEC; +var __ONEDAY_210 = _$numerical_147.ONEDAY; +var __ONEHOUR_210 = _$numerical_147.ONEHOUR; +var __ONEMIN_210 = _$numerical_147.ONEMIN; +var __ONESEC_210 = _$numerical_147.ONESEC; var MINUS_SIGN = _$numerical_147.MINUS_SIGN; -var __BADNUM_209 = _$numerical_147.BADNUM; +var __BADNUM_210 = _$numerical_147.BADNUM; var MID_SHIFT = _$alignment_145.MID_SHIFT; -var __LINE_SPACING_209 = _$alignment_145.LINE_SPACING; +var __LINE_SPACING_210 = _$alignment_145.LINE_SPACING; -var axes = _$axes_209 = {}; +var axes = _$axes_210 = {}; axes.setConvert = _$setConvert_228; -/* removed: var _$autoType_210 = require('./axis_autotype'); */; +/* removed: var _$autoType_211 = require('./axis_autotype'); */; -/* removed: var _$axis_ids_212 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_212.id2name; -axes.name2id = _$axis_ids_212.name2id; -axes.cleanId = _$axis_ids_212.cleanId; -axes.list = _$axis_ids_212.list; -axes.listIds = _$axis_ids_212.listIds; -axes.getFromId = _$axis_ids_212.getFromId; -axes.getFromTrace = _$axis_ids_212.getFromTrace; +/* removed: var _$axis_ids_213 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_213.id2name; +axes.name2id = _$axis_ids_213.name2id; +axes.cleanId = _$axis_ids_213.cleanId; +axes.list = _$axis_ids_213.list; +axes.listIds = _$axis_ids_213.listIds; +axes.getFromId = _$axis_ids_213.getFromId; +axes.getFromTrace = _$axis_ids_213.getFromTrace; -/* removed: var _$autorange_208 = require('./autorange'); */; -axes.expand = _$autorange_208.expand; -axes.getAutoRange = _$autorange_208.getAutoRange; +/* removed: var _$autorange_209 = require('./autorange'); */; +axes.expand = _$autorange_209.expand; +axes.getAutoRange = _$autorange_209.getAutoRange; /* * find the list of possible axes to reference with an xref or yref attribute @@ -27999,7 +28188,7 @@ axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption }; // xref, yref - return _$lib_166.coerce(containerIn, containerOut, attrDef, refAttr); + return _$lib_167.coerce(containerIn, containerOut, attrDef, refAttr); }; /* @@ -28028,7 +28217,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { var cleanPos, pos; if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_166.ensureNumber; + cleanPos = _$lib_167.ensureNumber; pos = coerce(attr, dflt); } else { var ax = axes.getFromId(gd, axRef); @@ -28042,7 +28231,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { axes.cleanPosition = function(pos, gd, axRef) { var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_166.ensureNumber : + _$lib_167.ensureNumber : axes.getFromId(gd, axRef).cleanPos; return cleanPos(pos); @@ -28062,7 +28251,7 @@ var getDataConversions = axes.getDataConversions = function(gd, trace, target, t // setup the data-to-calc method. if(Array.isArray(d2cTarget)) { ax = { - type: _$autoType_210(targetArray), + type: _$autoType_211(targetArray), _categories: [] }; axes.setConvert(ax); @@ -28198,8 +28387,8 @@ axes.saveShowSpikeInitial = function(gd, overwrite) { }; axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_166.aggNums(Math.min, null, data), - dataMax = _$lib_166.aggNums(Math.max, null, data); + var dataMin = _$lib_167.aggNums(Math.min, null, data), + dataMax = _$lib_167.aggNums(Math.max, null, data); if(!calendar) calendar = ax.calendar; @@ -28219,12 +28408,12 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { // 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_166.distinctVals(data), + var distinctData = _$lib_167.distinctVals(data), msexp = Math.pow(10, Math.floor( Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_166.roundUp( + minSize = msexp * _$lib_167.roundUp( distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_166.stdev(data) / + size0 = Math.max(minSize, 2 * _$lib_167.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4)); // fallback if ax.d2c output BADNUMs @@ -28244,7 +28433,7 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { else { dummyAx = { type: ax.type, - range: _$lib_166.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + range: _$lib_167.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), calendar: calendar }; } @@ -28343,7 +28532,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_166.findExactDates(data, calendar); + var stats = _$lib_167.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; @@ -28355,21 +28544,21 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // 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_209 * 1.5; + binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + __ONEDAY_210 * 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_209 * 15.5; + binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + __ONEDAY_210 * 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_209 / 2; + binStart -= __ONEDAY_210 / 2; } var nextBinStart = axes.tickIncrement(binStart, dtick); @@ -28384,7 +28573,7 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // ensure we have tick0, dtick, and tick rounding calculated axes.prepTicks = function(ax) { - var rng = _$lib_166.simpleMap(ax.range, ax.r2l); + var rng = _$lib_167.simpleMap(ax.range, ax.r2l); // calculate max number of (auto) ticks to display based on plot size if(ax.tickmode === 'auto' || !ax.dtick) { @@ -28397,7 +28586,7 @@ axes.prepTicks = function(ax) { } else { minPx = ax._id.charAt(0) === 'y' ? 40 : 80; - nt = _$lib_166.constrain(ax._length / minPx, 4, 9) + 1; + nt = _$lib_167.constrain(ax._length / minPx, 4, 9) + 1; } // radial axes span half their domain, @@ -28432,7 +28621,7 @@ axes.prepTicks = function(ax) { // or codes to this effect for log and date scales axes.calcTicks = function calcTicks(ax) { axes.prepTicks(ax); - var rng = _$lib_166.simpleMap(ax.range, ax.r2l); + var rng = _$lib_167.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 @@ -28500,7 +28689,7 @@ function arrayTicks(ax) { var vals = ax.tickvals, text = ax.ticktext, ticksOut = new Array(vals.length), - rng = _$lib_166.simpleMap(ax.range, ax.r2l), + rng = _$lib_167.simpleMap(ax.range, ax.r2l), r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, tickMin = Math.min(r0expanded, r1expanded), @@ -28549,7 +28738,7 @@ var roundBase10 = [2, 5, 10], roundAngles = [15, 30, 45, 90, 180]; function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_166.roundUp(roughDTick / base, roundingSet); + return base * _$lib_167.roundUp(roughDTick / base, roundingSet); } // autoTicks: calculate best guess at pleasant ticks for this axis @@ -28576,7 +28765,7 @@ axes.autoTicks = function(ax, roughDTick) { } if(ax.type === 'date') { - ax.tick0 = _$lib_166.dateTick0(ax.calendar); + ax.tick0 = _$lib_167.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; @@ -28590,21 +28779,21 @@ axes.autoTicks = function(ax, roughDTick) { roughDTick /= ONEAVGMONTH; ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); } - else if(roughX2 > __ONEDAY_209) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_209, roundDays); + else if(roughX2 > __ONEDAY_210) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_210, 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_166.dateTick0(ax.calendar, true); + ax.tick0 = _$lib_167.dateTick0(ax.calendar, true); } - else if(roughX2 > __ONEHOUR_209) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_209, roundBase24); + else if(roughX2 > __ONEHOUR_210) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_210, roundBase24); } - else if(roughX2 > __ONEMIN_209) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_209, roundBase60); + else if(roughX2 > __ONEMIN_210) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_210, roundBase60); } - else if(roughX2 > __ONESEC_209) { - ax.dtick = roundDTick(roughDTick, __ONESEC_209, roundBase60); + else if(roughX2 > __ONESEC_210) { + ax.dtick = roundDTick(roughDTick, __ONESEC_210, roundBase60); } else { // milliseconds @@ -28614,7 +28803,7 @@ axes.autoTicks = function(ax, roughDTick) { } else if(ax.type === 'log') { ax.tick0 = 0; - var rng = _$lib_166.simpleMap(ax.range, ax.r2l); + var rng = _$lib_167.simpleMap(ax.range, ax.r2l); if(roughDTick > 0.7) { // only show powers of 10 @@ -28695,9 +28884,9 @@ function autoTickRound(ax) { // 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_209 && tick0len <= 10) || (dtick >= __ONEDAY_209 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_209 && tick0len <= 16) || (dtick >= __ONEHOUR_209)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_209 && tick0len <= 19) || (dtick >= __ONEMIN_209)) ax._tickround = 'S'; + else if((dtick >= __ONEDAY_210 && tick0len <= 10) || (dtick >= __ONEDAY_210 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_210 && tick0len <= 16) || (dtick >= __ONEHOUR_210)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_210 && tick0len <= 19) || (dtick >= __ONEMIN_210)) 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 @@ -28744,7 +28933,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { dtSigned = axSign * Number(dtick.substr(1)); // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_166.incrementMonth(x, dtSigned, calendar); + if(tType === 'M') return _$lib_167.incrementMonth(x, dtSigned, calendar); // Log scales: Linear, Digits else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; @@ -28754,7 +28943,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, x2 = x + axSign * 0.01, - frac = _$lib_166.roundUp(_$lib_166.mod(x2, 1), tickset, axrev); + frac = _$lib_167.roundUp(_$lib_167.mod(x2, 1), tickset, axrev); return Math.floor(x2) + Math.log(_$d3_8.round(Math.pow(10, frac), 1)) / Math.LN10; @@ -28765,7 +28954,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { // calculate the first tick on an axis axes.tickFirst = function(ax) { var r2l = ax.r2l || Number, - rng = _$lib_166.simpleMap(ax.range, r2l), + rng = _$lib_167.simpleMap(ax.range, r2l), axrev = rng[1] < rng[0], sRound = axrev ? Math.floor : Math.ceil, // add a tiny extra bit to make sure we get ticks @@ -28779,7 +28968,7 @@ axes.tickFirst = function(ax) { // make sure no ticks outside the category list if(ax.type === 'category') { - tmin = _$lib_166.constrain(tmin, 0, ax._categories.length - 1); + tmin = _$lib_167.constrain(tmin, 0, ax._categories.length - 1); } return tmin; } @@ -28809,7 +28998,7 @@ axes.tickFirst = function(ax) { t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); cnt++; } - _$lib_166.error('tickFirst did not converge', ax); + _$lib_167.error('tickFirst did not converge', ax); return t0; } @@ -28820,7 +29009,7 @@ axes.tickFirst = function(ax) { } else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_166.roundUp(_$lib_166.mod(r0, 1), tickset, axrev); + frac = _$lib_167.roundUp(_$lib_167.mod(r0, 1), tickset, axrev); return Math.floor(r0) + Math.log(_$d3_8.round(Math.pow(10, frac), 1)) / Math.LN10; @@ -28843,7 +29032,7 @@ axes.tickText = function(ax, x, hover) { tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_166.simpleMap(ax.range, ax.r2l), + var rng = _$lib_167.simpleMap(ax.range, ax.r2l), 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; @@ -28900,7 +29089,7 @@ axes.tickText = function(ax, x, hover) { * it's different from `val`. */ axes.hoverLabelText = function(ax, val, val2) { - if(val2 !== __BADNUM_209 && val2 !== val) { + if(val2 !== __BADNUM_210 && val2 !== val) { return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } @@ -28943,7 +29132,7 @@ function formatDate(ax, out, hover, extraPrecision) { else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; } - var dateStr = _$lib_166.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + var dateStr = _$lib_167.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), headStr; var splitIndex = dateStr.indexOf('\n'); @@ -29008,7 +29197,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); } - else if(_$fastIsnumeric_11(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_166.mod(x + 0.01, 1) < 0.1))) { + else if(_$fastIsnumeric_11(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_167.mod(x + 0.01, 1) < 0.1))) { var p = Math.round(x); if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || (isSIFormat(ax.exponentformat) && beyondSI(p))) { @@ -29027,7 +29216,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { } } else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_166.mod(x, 1)))); + out.text = String(Math.round(Math.pow(10, _$lib_167.mod(x, 1)))); out.fontSize *= 0.75; } else throw 'unrecognized dtick ' + String(dtick); @@ -29082,7 +29271,7 @@ function formatAngle(ax, out, hover, extraPrecision, hideexp) { var frac = num2frac(num); if(frac[1] >= 100) { - out.text = numFormat(_$lib_166.deg2rad(out.x), ax, hideexp, extraPrecision); + out.text = numFormat(_$lib_167.deg2rad(out.x), ax, hideexp, extraPrecision); } else { var isNeg = out.x < 0; @@ -29230,7 +29419,7 @@ function numFormat(v, ax, fmtoverride, hover) { if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); } // insert appropriate decimal point and thousands separator - v = _$lib_166.numSeparate(v, ax._separators, separatethousands); + v = _$lib_167.numSeparate(v, ax._separators, separatethousands); } // add exponent @@ -29421,9 +29610,9 @@ axes.makeClipPaths = function(gd) { // ax._rl (stored linearized range for use by zoom/pan) // or can pass in an axis object directly axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + var fullLayout = gd._fullLayout; + var ax; + var independent = false; // allow passing an independent axis object instead of id if(typeof axid === 'object') { @@ -29436,32 +29625,26 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'redraw') { fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); }); } if(!axid || axid === 'redraw') { - return _$lib_166.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return _$lib_167.syncOrAsync(axes.list(gd, '', true).map(function(ax) { return function() { if(!ax._id) return; var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_166.simpleMap(ax._r, ax.r2l); - } + ax._r = ax.range.slice(); + ax._rl = _$lib_167.simpleMap(ax._r, ax.r2l); return axDone; }; })); @@ -29471,21 +29654,22 @@ axes.doTicks = function(gd, axid, skipTitle) { // set scaling to pixels ax.setScale(); - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_70.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_70.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_70.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + var axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_70.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_70.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_70.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; if(ax._counterangle && ax.ticks === 'outside') { var caRad = ax._counterangle * Math.PI / 180; @@ -29532,13 +29716,14 @@ axes.doTicks = function(gd, axid, skipTitle) { }; } else { - _$lib_166.warn('Unrecognized doTicks axis:', axid); + _$lib_167.warn('Unrecognized doTicks axis:', axid); return; } - var axside = ax.side || sides[0], + + var axside = ax.side || sides[0]; // which direction do the side[0], side[1], and free ticks go? // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; if((ax.ticks !== 'inside') === (axLetter === 'x')) { ticksign = ticksign.map(function(v) { return -v; }); } @@ -29566,6 +29751,7 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawTicks(container, tickpath) { var ticks = container.selectAll('path.' + tcls) .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); + if(tickpath && ax.ticks) { ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) .classed('crisp', 1) @@ -29581,7 +29767,7 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawLabels(container, position) { // tick labels - for now just the main labels. // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); if(!_$fastIsnumeric_11(position)) { tickLabels.remove(); @@ -29649,10 +29835,10 @@ axes.doTicks = function(gd, axid, skipTitle) { var thisLabel = _$d3_8.select(this), newPromise = gd._promises.length; thisLabel - .call(_$svg_text_utils_187.positionText, labelx(d), labely(d)) + .call(_$svg_text_utils_188.positionText, labelx(d), labely(d)) .call(_$drawing_70.font, d.font, d.fontSize, d.fontColor) .text(d.text) - .call(_$svg_text_utils_187.convertToTspans, gd); + .call(_$svg_text_utils_188.convertToTspans, gd); newPromise = gd._promises[newPromise]; if(newPromise) { // if we have an async label, we'll deal with that @@ -29677,7 +29863,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'angular') { tickLabels.each(function(d) { _$d3_8.select(this).select('text') - .call(_$svg_text_utils_187.positionText, labelx(d), labely(d)); + .call(_$svg_text_utils_188.positionText, labelx(d), labely(d)); }); } @@ -29712,8 +29898,8 @@ axes.doTicks = function(gd, axid, skipTitle) { (labely(d) - d.fontSize / 2) + ')') : ''); var anchorHeight = getAnchorHeight( - _$svg_text_utils_187.lineCount(thisLabel), - __LINE_SPACING_209 * d.fontSize, + _$svg_text_utils_188.lineCount(thisLabel), + __LINE_SPACING_210 * d.fontSize, _$fastIsnumeric_11(angle) ? +angle : 0); if(anchorHeight) { transform += ' translate(0, ' + anchorHeight + ')'; @@ -29774,7 +29960,7 @@ axes.doTicks = function(gd, axid, skipTitle) { }); }); for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_166.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + if(_$lib_167.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { // any overlap at all - set 30 degrees autoangle = 30; break; @@ -29916,7 +30102,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } } - var done = _$lib_166.syncOrAsync([ + var done = _$lib_167.syncOrAsync([ allLabelsReady, fixLabelOverlaps, calcBoundingBox, @@ -29932,14 +30118,12 @@ axes.doTicks = function(gd, axid, skipTitle) { // now this only applies to regular cartesian axes; colorbars and // others ALWAYS call doTicks with skipTitle=true so they can // configure their own titles. - var ax = _$axis_ids_212.getFromId(gd, axid); // rangeslider takes over a bottom title so drop it here if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - var avoidSelection = _$d3_8.select(gd).selectAll('g.' + axid + 'tick'); var avoid = { - selection: avoidSelection, + selection: tickLabels, side: ax.side }; var axLetter = axid.charAt(0); @@ -29949,8 +30133,8 @@ axes.doTicks = function(gd, axid, skipTitle) { var transform, counterAxis, x, y; - if(avoidSelection.size()) { - var translation = _$drawing_70.getTranslate(avoidSelection.node().parentNode); + if(tickLabels.size()) { + var translation = _$drawing_70.getTranslate(tickLabels.node().parentNode); avoid.offsetLeft = translation.x; avoid.offsetTop = translation.y; } @@ -29961,7 +30145,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axLetter === 'x') { counterAxis = (ax.anchor === 'free') ? {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_212.getFromId(gd, ax.anchor); + _$axis_ids_213.getFromId(gd, ax.anchor); x = ax._offset + ax._length / 2; @@ -29979,7 +30163,7 @@ axes.doTicks = function(gd, axid, skipTitle) { else { counterAxis = (ax.anchor === 'free') ? {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_212.getFromId(gd, ax.anchor); + _$axis_ids_213.getFromId(gd, ax.anchor); y = ax._offset + ax._length / 2; if(ax.side === 'right') { @@ -30007,11 +30191,13 @@ axes.doTicks = function(gd, axid, skipTitle) { function traceHasBarsOrFill(trace, subplot) { if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_258.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + if(_$registry_259.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; } function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); var zlcontainer = plotinfo.zerolinelayer; var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; @@ -30045,7 +30231,7 @@ axes.doTicks = function(gd, axid, skipTitle) { break; } } - var rng = _$lib_166.simpleMap(ax.range, ax.r2l), + var rng = _$lib_167.simpleMap(ax.range, ax.r2l), showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && (ax.type === 'linear' || ax.type === '-') && gridvals.length && (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); @@ -30059,7 +30245,7 @@ axes.doTicks = function(gd, axid, skipTitle) { // If several zerolines enter at the same time we will sort once per, // but generally this should be a minimal overhead. zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_212.idSort(da.id, db.id); + return _$axis_ids_213.idSort(da.id, db.id); }); }); zl.attr('transform', transfn) @@ -30110,7 +30296,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - tickSubplots = Object.keys(ax._linepositions); + tickSubplots = Object.keys(ax._linepositions || {}); } tickSubplots.map(function(subplot) { @@ -30249,7 +30435,7 @@ function swapAxisGroup(gd, xIds, yIds) { var ann = gd._fullLayout.annotations[i]; if(xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { - _$lib_166.swapAttrs(layout.annotations[i], ['?']); + _$lib_167.swapAttrs(layout.annotations[i], ['?']); } } } @@ -30258,7 +30444,7 @@ 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_166.nestedProperty, + var np = _$lib_167.nestedProperty, xVal = np(layout[xFullAxes[0]._name], key).get(), yVal = np(layout[yFullAxes[0]._name], key).get(), i; @@ -30295,15 +30481,15 @@ var _$hover_85 = {}; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_26 = require('tinycolor2'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$Events_157 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_177 = require('../../lib/override_cursor'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$Events_158 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_178 = require('../../lib/override_cursor'); */; /* removed: var _$drawing_70 = require('../drawing'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$dragelement_67 = require('../dragelement'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$helpers_84 = require('./helpers'); */; /* removed: var _$constants_82 = require('./constants'); */; @@ -30350,9 +30536,9 @@ var HOVERTEXTPAD = _$constants_82.HOVERTEXTPAD; // We wrap the hovers in a timer, to limit their frequency. // The actual rendering is done by private function _hover. _$hover_85.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_166.getGraphDiv(gd); + gd = _$lib_167.getGraphDiv(gd); - _$lib_166.throttle( + _$lib_167.throttle( gd._fullLayout._uid + _$constants_82.HOVERID, _$constants_82.HOVERMINTIME, function() { _hover(gd, evt, subplot, noHoverEvent); } @@ -30475,8 +30661,8 @@ function _hover(gd, evt, subplot, noHoverEvent) { // get updated properly so that we don't have // to use Axes.getFromId in general. - xaArray[i] = _$axes_209.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_209.getFromId(gd, plotObj.yaxis._id); + xaArray[i] = _$axes_210.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_210.getFromId(gd, plotObj.yaxis._id); continue; } @@ -30498,7 +30684,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - // hoverData: the set of candidate points we've found to highlight + // hoverData: the set of candidate points we've found to highlight var hoverData = [], // searchData: the data to search in. Mostly this is just a copy of @@ -30548,7 +30734,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { cd = gd.calcdata[curvenum]; trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_84.getSubplot(trace)) !== -1) { + if(trace.hoverinfo !== 'skip' && _$helpers_84.isTraceInSubplots(trace, subplots)) { searchData.push(cd); } } @@ -30572,7 +30758,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { // fire the beforehover event and quit if it returns false // note that we're only calling this on real mouse events, so // manual calls to fx.hover will always run. - if(_$Events_157.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + if(_$Events_158.triggerHandler(gd, 'plotly_beforehover', evt) === false) { return; } @@ -30597,7 +30783,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { else yvalArray = _$helpers_84.p2c(yaArray, ypx); if(!_$fastIsnumeric_11(xvalArray[0]) || !_$fastIsnumeric_11(yvalArray[0])) { - _$lib_166.warn('Fx.hover failed', evt, gd); + _$lib_167.warn('Fx.hover failed', evt, gd); return _$dragelement_67.unhoverRaw(gd, evt); } } @@ -30621,8 +30807,15 @@ function _hover(gd, evt, subplot, noHoverEvent) { // the rest of this function from running and failing if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotId = _$helpers_84.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_84.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } // within one trace mode can sometimes be overridden mode = hovermode; @@ -30716,7 +30909,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { } } else { - _$lib_166.log('Unrecognized trace type in hover:', trace); + _$lib_167.log('Unrecognized trace type in hover:', trace); } } @@ -30893,8 +31086,8 @@ function _hover(gd, evt, subplot, noHoverEvent) { // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true // we should improve the "fx" API so other plots can use it without these hack. if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_258.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_177(_$d3_8.select(evt.target), hasClickToShow ? 'pointer' : ''); + var hasClickToShow = _$registry_259.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_178(_$d3_8.select(evt.target), hasClickToShow ? 'pointer' : ''); } // don't emit events if called manually @@ -30979,38 +31172,36 @@ function createHoverText(hoverData, opts, gd) { commonLabel.exit().remove(); commonLabel.each(function() { - var label = _$d3_8.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); - - lpath.enter().append('path') - .style({'stroke-width': '1px'}); + var label = _$d3_8.select(this); + var lpath = _$lib_167.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_167.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); lpath.style({ fill: commonLabelOpts.bgcolor || _$color_45.defaultLine, stroke: commonLabelOpts.bordercolor || _$color_45.background, }); - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); - ltext.text(t0) .call(_$drawing_70.font, commonLabelOpts.font.family || fontFamily, commonLabelOpts.font.size || fontSize, commonLabelOpts.font.color || _$color_45.background ) - .call(_$svg_text_utils_187.positionText, 0, 0) - .call(_$svg_text_utils_187.convertToTspans, gd); + .call(_$svg_text_utils_188.positionText, 0, 0) + .call(_$svg_text_utils_188.convertToTspans, gd); label.attr('transform', ''); var tbb = ltext.node().getBoundingClientRect(); if(hovermode === 'x') { ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_187.positionText, 0, (xa.side === 'top' ? + .call(_$svg_text_utils_188.positionText, 0, (xa.side === 'top' ? (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); @@ -31028,7 +31219,7 @@ function createHoverText(hoverData, opts, gd) { } else { ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_187.positionText, + .call(_$svg_text_utils_188.positionText, (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), outerTop - tbb.top - tbb.height / 2); @@ -31094,7 +31285,7 @@ function createHoverText(hoverData, opts, gd) { if(d.name) { // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_187.plainText(d.name || ''); + name = _$svg_text_utils_188.plainText(d.name || ''); var nameLength = Math.round(d.nameLength); @@ -31104,13 +31295,6 @@ function createHoverText(hoverData, opts, gd) { } } - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; - if(d.zLabel !== undefined) { if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; @@ -31129,6 +31313,13 @@ function createHoverText(hoverData, opts, gd) { text += (text ? '
' : '') + d.text; } + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; + // if 'text' is empty at this point, // put 'name' in main label and don't show secondary label if(text === '') { @@ -31145,8 +31336,8 @@ function createHoverText(hoverData, opts, gd) { d.fontColor || contrastColor) .text(text) .attr('data-notex', 1) - .call(_$svg_text_utils_187.positionText, 0, 0) - .call(_$svg_text_utils_187.convertToTspans, gd); + .call(_$svg_text_utils_188.positionText, 0, 0) + .call(_$svg_text_utils_188.convertToTspans, gd); var tx2 = g.select('text.name'), tx2width = 0; @@ -31159,8 +31350,8 @@ function createHoverText(hoverData, opts, gd) { traceColor) .text(name) .attr('data-notex', 1) - .call(_$svg_text_utils_187.positionText, 0, 0) - .call(_$svg_text_utils_187.convertToTspans, gd); + .call(_$svg_text_utils_188.positionText, 0, 0) + .call(_$svg_text_utils_188.convertToTspans, gd); tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; } else { @@ -31429,12 +31620,12 @@ function alignHoverText(hoverLabels, rotateLabels) { 'V' + (offsetY - HOVERARROWSIZE) + 'Z')); - tx.call(_$svg_text_utils_187.positionText, + tx.call(_$svg_text_utils_188.positionText, txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); if(d.tx2width) { g.select('text.name') - .call(_$svg_text_utils_187.positionText, + .call(_$svg_text_utils_188.positionText, tx2x + alignShift * HOVERTEXTPAD + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); g.select('rect') @@ -31454,11 +31645,11 @@ function cleanPoint(d, hovermode) { var getVal = Array.isArray(index) ? function(calcKey, traceKey) { - return _$lib_166.castOption(cd0, index, calcKey) || - _$lib_166.extractOption({}, trace, '', traceKey); + return _$lib_167.castOption(cd0, index, calcKey) || + _$lib_167.extractOption({}, trace, '', traceKey); } : function(calcKey, traceKey) { - return _$lib_166.extractOption(cd, trace, calcKey, traceKey); + return _$lib_167.extractOption(cd, trace, calcKey, traceKey); }; function fill(key, calcKey, traceKey) { @@ -31479,18 +31670,18 @@ function cleanPoint(d, hovermode) { (d.ya._offset + (d.y0 + d.y1) / 2); // then constrain all the positions to be on the plot - d.x0 = _$lib_166.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_166.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_166.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_166.constrain(d.y1, 0, d.ya._length); + d.x0 = _$lib_167.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_167.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_167.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_167.constrain(d.y1, 0, d.ya._length); // and convert the x and y label values into formatted text if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_209.hoverLabelText(d.xa, d.xLabelVal); + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_210.hoverLabelText(d.xa, d.xLabelVal); d.xVal = d.xa.c2d(d.xLabelVal); } if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_209.hoverLabelText(d.ya, d.yLabelVal); + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_210.hoverLabelText(d.ya, d.yLabelVal); d.yVal = d.ya.c2d(d.yLabelVal); } @@ -31501,10 +31692,10 @@ function cleanPoint(d, hovermode) { // for box means and error bars, add the range to the label if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_209.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + var xeText = _$axes_210.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; if(d.xerrneg !== undefined) { d.xLabel += ' +' + xeText + ' / -' + - _$axes_209.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + _$axes_210.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; } else d.xLabel += ' ± ' + xeText; @@ -31514,10 +31705,10 @@ function cleanPoint(d, hovermode) { if(hovermode === 'x') d.distance += 1; } if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_209.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + var yeText = _$axes_210.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; if(d.yerrneg !== undefined) { d.yLabel += ' +' + yeText + ' / -' + - _$axes_209.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + _$axes_210.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; } else d.yLabel += ' ± ' + yeText; @@ -31743,11 +31934,11 @@ function spikesChanged(gd, oldspikepoints) { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; var hover = _$hover_85.hover; var _$click_81 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_258.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); + var annotationsDone = _$registry_259.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. @@ -31780,7 +31971,7 @@ var _$click_81 = function click(gd, evt, subplot) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; var _$handleHoverLabelDefaults_86 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { opts = opts || {}; @@ -31788,7 +31979,7 @@ var _$handleHoverLabelDefaults_86 = function handleHoverLabelDefaults(contIn, co coerce('hoverlabel.bgcolor', opts.bgcolor); coerce('hoverlabel.bordercolor', opts.bordercolor); coerce('hoverlabel.namelength', opts.namelength); - _$lib_166.coerceFont(coerce, 'hoverlabel.font', opts.font); + _$lib_167.coerceFont(coerce, 'hoverlabel.font', opts.font); }; /** @@ -31801,13 +31992,13 @@ var _$handleHoverLabelDefaults_86 = function handleHoverLabelDefaults(contIn, co 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$attributes_79 = require('./attributes'); */; /* removed: var _$handleHoverLabelDefaults_86 = require('./hoverlabel_defaults'); */; var _$supplyDefaults_83 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_166.coerce(traceIn, traceOut, _$attributes_79, attr, dflt); + return _$lib_167.coerce(traceIn, traceOut, _$attributes_79, attr, dflt); } _$handleHoverLabelDefaults_86(traceIn, traceOut, coerce, layout.hoverlabel); @@ -31886,6 +32077,14 @@ var _$layout_attributes_88 = { editType: 'none', }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + editType: 'none' } }; @@ -31900,15 +32099,16 @@ var _$layout_attributes_88 = { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$layout_attributes_88 = require('./layout_attributes'); */; var _$supplyLayoutDefaults_89 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_88, attr, dflt); + return _$lib_167.coerce(layoutIn, layoutOut, _$layout_attributes_88, attr, dflt); } - coerce('dragmode'); + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); var hovermodeDflt; if(layoutOut._has('cartesian')) { @@ -31965,13 +32165,13 @@ function isHoriz(fullData) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$handleHoverLabelDefaults_86 = require('./hoverlabel_defaults'); */; /* removed: var _$layout_attributes_88 = require('./layout_attributes'); */; var _$supplyLayoutGlobalDefaults_90 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_88, attr, dflt); + return _$lib_167.coerce(layoutIn, layoutOut, _$layout_attributes_88, attr, dflt); } _$handleHoverLabelDefaults_86(layoutIn, layoutOut, coerce); @@ -31988,7 +32188,7 @@ var _$supplyLayoutGlobalDefaults_90 = function supplyLayoutGlobalDefaults(layout 'use strict'; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$dragelement_67 = require('../dragelement'); */; /* removed: var _$helpers_84 = require('./helpers'); */; /* removed: var _$layout_attributes_88 = require('./layout_attributes'); */; @@ -32032,7 +32232,7 @@ var _$fx_87 = { function loneUnhover(containerOrSelection) { // duck type whether the arg is a d3 selection because ie9 doesn't // handle instanceof like modern browsers do. - var selection = _$lib_166.isD3Selection(containerOrSelection) ? + var selection = _$lib_167.isD3Selection(containerOrSelection) ? containerOrSelection : _$d3_8.select(containerOrSelection); @@ -32043,15 +32243,15 @@ function loneUnhover(containerOrSelection) { // helpers for traces that use Fx.loneHover function castHoverOption(trace, ptNumber, attr) { - return _$lib_166.castOption(trace, ptNumber, 'hoverlabel.' + attr); + return _$lib_167.castOption(trace, ptNumber, 'hoverlabel.' + attr); } function castHoverinfo(trace, fullLayout, ptNumber) { function _coerce(val) { - return _$lib_166.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + return _$lib_167.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } - return _$lib_166.castOption(trace, ptNumber, 'hoverinfo', _coerce); + return _$lib_167.castOption(trace, ptNumber, 'hoverinfo', _coerce); } var _$constants_238 = {}; @@ -32229,7 +32429,7 @@ _$constants_238.layerNameToAdjective = { frame: 'frame' }; -var _$topojson_utils_190 = {}; +var _$topojson_utils_191 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -32241,7 +32441,7 @@ var _$topojson_utils_190 = {}; 'use strict'; -var topojsonUtils = _$topojson_utils_190 = {}; +var topojsonUtils = _$topojson_utils_191 = {}; var locationmodeToLayer = _$constants_238.locationmodeToLayer; var topojsonFeature = _$topojsonClient_27.feature; @@ -33874,7 +34074,7 @@ if (typeof window === 'object') var _$PolyBool_17 = PolyBool; -var _$polygon_178 = {}; +var _$polygon_179 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -33886,10 +34086,10 @@ var _$polygon_178 = {}; 'use strict'; -var dot = _$matrix_172.dot; -var __BADNUM_178 = _$numerical_147.BADNUM; +var dot = _$matrix_173.dot; +var __BADNUM_179 = _$numerical_147.BADNUM; -var polygon = _$polygon_178 = {}; +var polygon = _$polygon_179 = {}; /** * Turn an array of [x, y] pairs into a polygon object @@ -33954,7 +34154,7 @@ polygon.tester = function tester(ptsIn) { var x = pt[0], y = pt[1]; - if(x === __BADNUM_178 || x < xmin || x > xmax || y === __BADNUM_178 || y < ymin || y > ymax) { + if(x === __BADNUM_179 || x < xmin || x > xmax || y === __BADNUM_179 || y < ymin || y > ymax) { // pt is outside the bounding box of polygon return false; } @@ -33967,7 +34167,7 @@ polygon.tester = function tester(ptsIn) { var x = pt[0], y = pt[1]; - if(x === __BADNUM_178 || x < xmin || x > xmax || y === __BADNUM_178 || y < ymin || y > ymax) { + if(x === __BADNUM_179 || x < xmin || x > xmax || y === __BADNUM_179 || y < ymin || y > ymax) { // pt is outside the bounding box of polygon return false; } @@ -34185,59 +34385,83 @@ polygon.filter = function filter(pts, tolerance) { 'use strict'; /* removed: var _$PolyBool_17 = require('polybooljs'); */; -/* removed: var _$polygon_178 = require('../../lib/polygon'); */; -/* removed: var _$throttle_188 = require('../../lib/throttle'); */; + +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$color_45 = require('../../components/color'); */; -var makeEventData = _$helpers_84.makeEventData; /* removed: var _$fx_87 = require('../../components/fx'); */; -/* removed: var _$axes_209 = require('./axes'); */; -/* removed: var _$constants_214 = require('./constants'); */; +/* removed: var _$polygon_179 = require('../../lib/polygon'); */; +/* removed: var _$throttle_189 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_84.makeEventData; +var getFromId = _$axis_ids_213.getFromId; +var __sortModules_227 = _$sort_modules_257.sortModules; + +/* removed: var _$constants_215 = require('./constants'); */; +var MINSELECT = _$constants_215.MINSELECT; -var filteredPolygon = _$polygon_178.filter; -var polygonTester = _$polygon_178.tester; -var multipolygonTester = _$polygon_178.multitester; -var MINSELECT = _$constants_214.MINSELECT; +var filteredPolygon = _$polygon_179.filter; +var polygonTester = _$polygon_179.tester; +var multipolygonTester = _$polygon_179.multitester; function getAxId(ax) { return ax._id; } -var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; + + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); + + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any dragOptions.polygons = plotinfo.selection.polygons; dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots plotinfo.selection = {}; plotinfo.selection.polygons = dragOptions.polygons = []; plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; } + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } + if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_214.BENDPX); + filterPoly = filteredPolygon([[x0, y0]], _$constants_215.BENDPX); } + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); outlines.enter() @@ -34259,13 +34483,13 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) // find the traces to search for selection points var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_214.SELECTID; + var throttleID = fullLayout._uid + _$constants_215.SELECTID; var selection = []; - var i, cd, trace, searchInfo, eventData; 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(dragOptions.subplot) { @@ -34274,23 +34498,32 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) trace.geo === dragOptions.subplot ) { searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, + _module: trace._module, cd: cd, xaxis: dragOptions.xaxes[0], yaxis: dragOptions.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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); } else { if(xAxisIds.indexOf(trace.xaxis) === -1) continue; if(yAxisIds.indexOf(trace.yaxis) === -1) continue; searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, + _module: trace._module, cd: cd, - xaxis: _$axes_209.getFromId(gd, trace.xaxis), - yaxis: _$axes_209.getFromId(gd, trace.yaxis) + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) }); } } @@ -34342,7 +34575,18 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) dy = Math.abs(y1 - y0); if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { + 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); @@ -34356,7 +34600,7 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) 'h4v' + (2 * MINSELECT) + 'h-4Z'); } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { + 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); @@ -34368,7 +34612,7 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) 'M' + (x0 - MINSELECT) + ',' + (currentPolygon.ymax - 1) + 'v4h' + (2 * MINSELECT) + 'v-4Z'); } - else { + else if(direction === 'd') { // diagonal motion currentPolygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]; currentPolygon.xmin = Math.min(x0, x1); @@ -34403,9 +34647,9 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) outlines .attr('d', 'M' + paths.join('M') + 'Z'); - _$throttle_188.throttle( + _$throttle_189.throttle( throttleID, - _$constants_214.SELECTDELAY, + _$constants_215.SELECTDELAY, function() { selection = []; @@ -34413,7 +34657,7 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) for(i = 0; i < searchTraces.length; i++) { searchInfo = searchTraces[i]; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); traceSelections.push(traceSelection); thisSelection = fillSelectionItem(traceSelection, searchInfo); @@ -34437,14 +34681,14 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) dragOptions.clickFn = function(numClicks, evt) { corners.remove(); - _$throttle_188.done(throttleID).then(function() { - _$throttle_188.clear(throttleID); + _$throttle_189.done(throttleID).then(function() { + _$throttle_189.clear(throttleID); if(numClicks === 2) { // clear selection on doubleclick outlines.remove(); for(i = 0; i < searchTraces.length; i++) { searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); + searchInfo._module.selectPoints(searchInfo, false); } updateSelectedState(gd, searchTraces); @@ -34463,8 +34707,8 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) dragOptions.doneFn = function() { corners.remove(); - _$throttle_188.done(throttleID).then(function() { - _$throttle_188.clear(throttleID); + _$throttle_189.done(throttleID).then(function() { + _$throttle_189.clear(throttleID); dragOptions.gd.emit('plotly_selected', eventData); if(currentPolygon && dragOptions.polygons) { @@ -34478,10 +34722,10 @@ var _$prepSelect_227 = function prepSelect(e, startX, startY, dragOptions, mode) } }); }; -}; +} function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; + var i, j, searchInfo, trace; if(eventData) { var pts = eventData.points || []; @@ -34511,17 +34755,44 @@ function updateSelectedState(gd, searchTraces, eventData) { trace = searchTraces[i].cd[0].trace; delete trace.selectedpoints; delete trace._input.selectedpoints; - - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } } } + // group searchInfo traces by trace modules + var lookup = {}; + for(i = 0; i < searchTraces.length; i++) { searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); + + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; + } + } + + var keys = Object.keys(lookup).sort(__sortModules_227); + + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_259.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } + } } } @@ -34564,6 +34835,18 @@ function fillSelectionItem(selection, searchInfo) { return selection; } +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); +} + +var _$select_227 = { + prepSelect: prepSelect, + clearSelect: clearSelect +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -35021,7 +35304,7 @@ var _$addProjectionsToD3_244 = addProjectionsToD3; 'use strict'; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; var radians = Math.PI / 180; var degrees = 180 / Math.PI; @@ -35064,11 +35347,11 @@ function sync(geo, projection, cb) { var eventData = {}; function set(propStr, val) { - var fullNp = _$lib_166.nestedProperty(fullOpts, propStr); + var fullNp = _$lib_167.nestedProperty(fullOpts, propStr); if(fullNp.get() !== val) { fullNp.set(val); - _$lib_166.nestedProperty(userOpts, propStr).set(val); + _$lib_167.nestedProperty(userOpts, propStr).set(val); eventData[id + '.' + propStr] = val; } } @@ -35490,20 +35773,20 @@ function d3_eventDispatch(target) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$color_45 = require('../../components/color'); */; /* removed: var _$drawing_70 = require('../../components/drawing'); */; /* removed: var _$fx_87 = require('../../components/fx'); */; /* removed: var _$plots_250 = require('../plots'); */; -/* removed: var _$axes_209 = require('../cartesian/axes'); */; +/* removed: var _$axes_210 = require('../cartesian/axes'); */; /* removed: var _$dragelement_67 = require('../../components/dragelement'); */; -/* removed: var _$prepSelect_227 = require('../cartesian/select'); */; +var __prepSelect_239 = _$select_227.prepSelect; /* removed: var _$createGeoZoom_245 = require('./zoom'); */; /* removed: var _$constants_238 = require('./constants'); */; -/* removed: var _$topojson_utils_190 = require('../../lib/topojson_utils'); */; +/* removed: var _$topojson_utils_191 = require('../../lib/topojson_utils'); */; var __topojsonFeature_239 = _$topojsonClient_27.feature; _$addProjectionsToD3_244(_$d3_8); @@ -35548,7 +35831,7 @@ var _$createGeo_239 = function createGeo(opts) { proto.plot = function(geoCalcData, fullLayout, promises) { var _this = this; var geoLayout = fullLayout[this.id]; - var topojsonNameNew = _$topojson_utils_190.getTopojsonName(geoLayout); + var topojsonNameNew = _$topojson_utils_191.getTopojsonName(geoLayout); if(_this.topojson === null || topojsonNameNew !== _this.topojsonName) { _this.topojsonName = topojsonNameNew; @@ -35569,7 +35852,7 @@ proto.plot = function(geoCalcData, fullLayout, promises) { }; proto.fetchTopojson = function() { - var topojsonPath = _$topojson_utils_190.getTopojsonPath( + var topojsonPath = _$topojson_utils_191.getTopojsonPath( this.topojsonURL, this.topojsonName ); @@ -35685,8 +35968,8 @@ proto.updateProjection = function(fullLayout, geoLayout) { this.viewInitial = null; - _$lib_166.warn(msg); - gd._promises.push(_$registry_258.call('relayout', gd, updateObj)); + _$lib_167.warn(msg); + gd._promises.push(_$registry_259.call('relayout', gd, updateObj)); return msg; } @@ -35843,7 +36126,7 @@ proto.updateFx = function(fullLayout, geoLayout) { updateObj[_this.id + '.' + k] = viewInitial[k]; } - _$registry_258.call('relayout', gd, updateObj); + _$registry_259.call('relayout', gd, updateObj); gd.emit('plotly_doubleclick', null); } @@ -35898,7 +36181,7 @@ proto.updateFx = function(fullLayout, geoLayout) { }; dragOptions.prepFn = function(e, startX, startY) { - _$prepSelect_227(e, startX, startY, dragOptions, dragMode); + __prepSelect_239(e, startX, startY, dragOptions, dragMode); }; _$dragelement_67.init(dragOptions); @@ -35968,7 +36251,7 @@ proto.makeFramework = function() { showexponent: 'all', exponentformat: 'B' }; - _$axes_209.setConvert(_this.mockAxis, fullLayout); + _$axes_210.setConvert(_this.mockAxis, fullLayout); }; proto.saveViewInitial = function(geoLayout) { @@ -36200,7 +36483,7 @@ var _$domain_235 = {}; 'use strict'; -var __extendFlat_235 = _$extend_158.extendFlat; +var __extendFlat_235 = _$extend_159.extendFlat; /** * Make a xy domain attribute group @@ -36310,7 +36593,7 @@ _$domain_235.defaults = function(containerOut, layout, coerce, dfltDomains) { /* removed: var _$attributes_44 = require('../../../components/color/attributes'); */; var domainAttrs = _$domain_235.attributes; /* removed: var _$constants_238 = require('../constants'); */; -var __overrideAll_243 = _$edit_types_194.overrideAll; +var __overrideAll_243 = _$edit_types_195.overrideAll; var geoAxesAttrs = { range: { @@ -36574,7 +36857,7 @@ var _$layout_attributes_243 = __overrideAll_243({ 'use strict'; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; var handleDomainDefaults = _$domain_235.defaults; @@ -36605,7 +36888,7 @@ var handleDomainDefaults = _$domain_235.defaults; * additional items needed by this function here as well * } */ -var _$handleSubplotDefaults_257 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { +var _$handleSubplotDefaults_258 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { var subplotType = opts.type; var subplotAttributes = opts.attributes; var handleDefaults = opts.handleDefaults; @@ -36617,7 +36900,7 @@ var _$handleSubplotDefaults_257 = function handleSubplotDefaults(layoutIn, layou var subplotLayoutIn, subplotLayoutOut; function coerce(attr, dflt) { - return _$lib_166.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); + return _$lib_167.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); } for(var i = 0; i < idsLength; i++) { @@ -36649,14 +36932,14 @@ var _$handleSubplotDefaults_257 = function handleSubplotDefaults(layoutIn, layou 'use strict'; -/* removed: var _$handleSubplotDefaults_257 = require('../../subplot_defaults'); */; +/* removed: var _$handleSubplotDefaults_258 = require('../../subplot_defaults'); */; /* removed: var _$constants_238 = require('../constants'); */; /* removed: var _$layout_attributes_243 = require('./layout_attributes'); */; var axesNames = _$constants_238.axesNames; var _$supplyLayoutDefaults_242 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_257(layoutIn, layoutOut, fullData, { + _$handleSubplotDefaults_258(layoutIn, layoutOut, fullData, { type: 'geo', attributes: _$layout_attributes_243, handleDefaults: handleGeoDefaults, @@ -36812,20 +37095,20 @@ var _$get_data_246 = {}; 'use strict'; -/* removed: var _$registry_258 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_214.SUBPLOT_PATTERN; +/* removed: var _$registry_259 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_215.SUBPLOT_PATTERN; /** - * Get calcdata traces(s) associated with a given subplot + * Get calcdata trace(s) associated with a given subplot * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for * * @return {array} array of calcdata traces */ _$get_data_246.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_258.subplotsRegistry[type]; + var basePlotModule = _$registry_259.subplotsRegistry[type]; if(!basePlotModule) return []; var attr = basePlotModule.attr; @@ -36840,20 +37123,40 @@ _$get_data_246.getSubplotCalcData = function(calcData, type, subplotId) { return subplotCalcData; }; - +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ _$get_data_246.getModuleCalcData = function(calcdata, typeOrModule) { var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_258.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_259.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; for(var i = 0; i < calcdata.length; i++) { var cd = calcdata[i]; var trace = cd[0].trace; + if(trace.visible !== true) continue; - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } } - return moduleCalcData; + return [moduleCalcData, remainingCalcData]; }; /** @@ -36867,9 +37170,9 @@ _$get_data_246.getModuleCalcData = function(calcdata, typeOrModule) { * */ _$get_data_246.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_258.subplotsRegistry[type]) return []; + if(!_$registry_259.subplotsRegistry[type]) return []; - var attr = _$registry_258.subplotsRegistry[type].attr; + var attr = _$registry_259.subplotsRegistry[type].attr; var subplotData = []; var trace, subplotX, subplotY; @@ -36882,7 +37185,7 @@ _$get_data_246.getSubplotData = function getSubplotData(data, type, subplotId) { for(var i = 0; i < data.length; i++) { trace = data[i]; - if(type === 'gl2d' && _$registry_258.traceIs(trace, 'gl2d')) { + if(type === 'gl2d' && _$registry_259.traceIs(trace, 'gl2d')) { if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { subplotData.push(trace); } @@ -36909,7 +37212,7 @@ var _$geo_240 = {}; /* removed: var _$createGeo_239 = require('./geo'); */; var getSubplotCalcData = _$get_data_246.getSubplotCalcData; -var __counterRegex_240 = _$lib_166.counterRegex; +var __counterRegex_240 = _$lib_167.counterRegex; var GEO = 'geo'; @@ -36996,19 +37299,19 @@ _$geo_240.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_280 = require('../scatter/attributes'); */; -/* removed: var _$attributes_206 = require('../../plots/attributes'); */; +/* removed: var _$attributes_281 = require('../scatter/attributes'); */; +/* removed: var _$attributes_207 = require('../../plots/attributes'); */; /* removed: var _$makeColorScaleAttributes_53 = require('../../components/colorscale/color_attributes'); */; -var __dash_305 = _$attributes_69.dash; +var __dash_306 = _$attributes_69.dash; -var __extendFlat_305 = _$extend_158.extendFlat; -var __overrideAll_305 = _$edit_types_194.overrideAll; +var __extendFlat_306 = _$extend_159.extendFlat; +var __overrideAll_306 = _$edit_types_195.overrideAll; -var __scatterMarkerAttrs_305 = _$attributes_280.marker, - scatterLineAttrs = _$attributes_280.line, - scatterMarkerLineAttrs = __scatterMarkerAttrs_305.line; +var __scatterMarkerAttrs_306 = _$attributes_281.marker, + scatterLineAttrs = _$attributes_281.line, + scatterMarkerLineAttrs = __scatterMarkerAttrs_306.line; -var _$attributes_305 = __overrideAll_305({ +var _$attributes_306 = __overrideAll_306({ lon: { valType: 'data_array', @@ -37030,40 +37333,40 @@ var _$attributes_305 = __overrideAll_305({ }, - mode: __extendFlat_305({}, _$attributes_280.mode, {dflt: 'markers'}), + mode: __extendFlat_306({}, _$attributes_281.mode, {dflt: 'markers'}), - text: __extendFlat_305({}, _$attributes_280.text, { + text: __extendFlat_306({}, _$attributes_281.text, { }), - hovertext: __extendFlat_305({}, _$attributes_280.hovertext, { + hovertext: __extendFlat_306({}, _$attributes_281.hovertext, { }), - textfont: _$attributes_280.textfont, - textposition: _$attributes_280.textposition, + textfont: _$attributes_281.textfont, + textposition: _$attributes_281.textposition, line: { color: scatterLineAttrs.color, width: scatterLineAttrs.width, - dash: __dash_305 - }, - connectgaps: _$attributes_280.connectgaps, - - marker: __extendFlat_305({ - symbol: __scatterMarkerAttrs_305.symbol, - opacity: __scatterMarkerAttrs_305.opacity, - size: __scatterMarkerAttrs_305.size, - sizeref: __scatterMarkerAttrs_305.sizeref, - sizemin: __scatterMarkerAttrs_305.sizemin, - sizemode: __scatterMarkerAttrs_305.sizemode, - showscale: __scatterMarkerAttrs_305.showscale, - colorbar: __scatterMarkerAttrs_305.colorbar, - line: __extendFlat_305({ + dash: __dash_306 + }, + connectgaps: _$attributes_281.connectgaps, + + marker: __extendFlat_306({ + symbol: __scatterMarkerAttrs_306.symbol, + opacity: __scatterMarkerAttrs_306.opacity, + size: __scatterMarkerAttrs_306.size, + sizeref: __scatterMarkerAttrs_306.sizeref, + sizemin: __scatterMarkerAttrs_306.sizemin, + sizemode: __scatterMarkerAttrs_306.sizemode, + showscale: __scatterMarkerAttrs_306.showscale, + colorbar: __scatterMarkerAttrs_306.colorbar, + line: __extendFlat_306({ width: scatterMarkerLineAttrs.width }, _$makeColorScaleAttributes_53('marker.line') ), - gradient: __scatterMarkerAttrs_305.gradient + gradient: __scatterMarkerAttrs_306.gradient }, _$makeColorScaleAttributes_53('marker') ), @@ -37075,12 +37378,12 @@ var _$attributes_305 = __overrideAll_305({ }, - fillcolor: _$attributes_280.fillcolor, + fillcolor: _$attributes_281.fillcolor, - selected: _$attributes_280.selected, - unselected: _$attributes_280.unselected, + selected: _$attributes_281.selected, + unselected: _$attributes_281.unselected, - hoverinfo: __extendFlat_305({}, _$attributes_206.hoverinfo, { + hoverinfo: __extendFlat_306({}, _$attributes_207.hoverinfo, { flags: ['lon', 'lat', 'location', 'text', 'name'] }) }, 'calc', 'nested'); @@ -37095,36 +37398,36 @@ var _$attributes_305 = __overrideAll_305({ 'use strict'; -/* removed: var _$attributes_305 = require('../scattergeo/attributes'); */; +/* removed: var _$attributes_306 = require('../scattergeo/attributes'); */; /* removed: var _$attributes_51 = require('../../components/colorscale/attributes'); */; /* removed: var _$attributes_46 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_206 = require('../../plots/attributes'); */; +/* removed: var _$attributes_207 = require('../../plots/attributes'); */; -/* removed: var _$extend_158 = require('../../lib/extend'); */; -var __extendFlat_267 = _$extend_158.extendFlat; -var __extendDeepAll_267 = _$extend_158.extendDeepAll; +/* removed: var _$extend_159 = require('../../lib/extend'); */; +var __extendFlat_268 = _$extend_159.extendFlat; +var __extendDeepAll_268 = _$extend_159.extendDeepAll; -var scatterGeoMarkerLineAttrs = _$attributes_305.marker.line; +var scatterGeoMarkerLineAttrs = _$attributes_306.marker.line; -var _$attributes_267 = __extendFlat_267({ +var _$attributes_268 = __extendFlat_268({ locations: { valType: 'data_array', editType: 'calc', }, - locationmode: _$attributes_305.locationmode, + locationmode: _$attributes_306.locationmode, z: { valType: 'data_array', editType: 'calc', }, - text: __extendFlat_267({}, _$attributes_305.text, { + text: __extendFlat_268({}, _$attributes_306.text, { }), marker: { line: { color: scatterGeoMarkerLineAttrs.color, - width: __extendFlat_267({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}), + width: __extendFlat_268({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}), editType: 'calc' }, opacity: { @@ -37142,25 +37445,25 @@ var _$attributes_267 = __extendFlat_267({ selected: { marker: { - opacity: _$attributes_305.selected.marker.opacity, + opacity: _$attributes_306.selected.marker.opacity, editType: 'plot' }, editType: 'plot' }, unselected: { marker: { - opacity: _$attributes_305.unselected.marker.opacity, + opacity: _$attributes_306.unselected.marker.opacity, editType: 'plot' }, editType: 'plot' }, - hoverinfo: __extendFlat_267({}, _$attributes_206.hoverinfo, { + hoverinfo: __extendFlat_268({}, _$attributes_207.hoverinfo, { editType: 'calc', flags: ['location', 'z', 'text', 'name'] }) }, - __extendDeepAll_267({}, _$attributes_51, { + __extendDeepAll_268({}, _$attributes_51, { zmax: {editType: 'calc'}, zmin: {editType: 'calc'} }), @@ -37178,42 +37481,42 @@ var _$attributes_267 = __extendFlat_267({ 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_279 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_280 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_166.mergeArray(trace.text, cd, 'tx'); - _$lib_166.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_166.mergeArray(trace.customdata, cd, 'data'); - _$lib_166.mergeArray(trace.textposition, cd, 'tp'); + _$lib_167.mergeArray(trace.text, cd, 'tx'); + _$lib_167.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_167.mergeArray(trace.customdata, cd, 'data'); + _$lib_167.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_166.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_166.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_166.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_167.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_167.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_167.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_166.mergeArray(marker.size, cd, 'ms'); - _$lib_166.mergeArray(marker.opacity, cd, 'mo'); - _$lib_166.mergeArray(marker.symbol, cd, 'mx'); - _$lib_166.mergeArray(marker.color, cd, 'mc'); + _$lib_167.mergeArray(marker.size, cd, 'ms'); + _$lib_167.mergeArray(marker.opacity, cd, 'mo'); + _$lib_167.mergeArray(marker.symbol, cd, 'mx'); + _$lib_167.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_166.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_166.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_167.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_167.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_166.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_166.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_167.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_167.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -37228,11 +37531,11 @@ var _$arraysToCalcdata_279 = function arraysToCalcdata(cd, trace) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -var _$calcSelection_282 = function calcSelection(cd, trace) { - if(_$lib_166.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_166.tagSelected(cd, trace); +var _$calcSelection_283 = function calcSelection(cd, trace) { + if(_$lib_167.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_167.tagSelected(cd, trace); } }; @@ -37248,13 +37551,13 @@ var _$calcSelection_282 = function calcSelection(cd, trace) { 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -var __BADNUM_268 = _$numerical_147.BADNUM; +var __BADNUM_269 = _$numerical_147.BADNUM; /* removed: var _$calc_52 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_279 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_282 = require('../scatter/calc_selection'); */; +/* removed: var _$arraysToCalcdata_280 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_283 = require('../scatter/calc_selection'); */; -var _$calc_268 = function calc(gd, trace) { +var _$calc_269 = function calc(gd, trace) { var len = trace.locations.length; var calcTrace = new Array(len); @@ -37264,12 +37567,12 @@ var _$calc_268 = function calc(gd, trace) { var z = trace.z[i]; calcPt.loc = typeof loc === 'string' ? loc : null; - calcPt.z = _$fastIsnumeric_11(z) ? z : __BADNUM_268; + calcPt.z = _$fastIsnumeric_11(z) ? z : __BADNUM_269; } - _$arraysToCalcdata_279(calcTrace, trace); + _$arraysToCalcdata_280(calcTrace, trace); _$calc_52(trace, trace.z, '', 'z'); - _$calcSelection_282(calcTrace, trace); + _$calcSelection_283(calcTrace, trace); return calcTrace; }; @@ -37285,13 +37588,13 @@ var _$calc_268 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$colorScaleDefaults_55 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_267 = require('./attributes'); */; +/* removed: var _$attributes_268 = require('./attributes'); */; -var _$supplyDefaults_269 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_270 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_166.coerce(traceIn, traceOut, _$attributes_267, attr, dflt); + return _$lib_167.coerce(traceIn, traceOut, _$attributes_268, attr, dflt); } var locations = coerce('locations'); @@ -37305,7 +37608,7 @@ var _$supplyDefaults_269 = function supplyDefaults(traceIn, traceOut, defaultCol } var z = coerce('z'); - if(!_$lib_166.isArrayOrTypedArray(z)) { + if(!_$lib_167.isArrayOrTypedArray(z)) { traceOut.visible = false; return; } @@ -37324,7 +37627,7 @@ var _$supplyDefaults_269 = function supplyDefaults(traceIn, traceOut, defaultCol traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); - _$lib_166.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_167.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -37338,7 +37641,7 @@ var _$supplyDefaults_269 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_270 = function eventData(out, pt) { +var _$eventData_271 = function eventData(out, pt) { out.location = pt.location; out.z = pt.z; @@ -37355,7 +37658,7 @@ var _$eventData_270 = function eventData(out, pt) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /** Fill hover 'pointData' container with 'correct' hover text value * @@ -37370,15 +37673,15 @@ var _$eventData_270 = function eventData(out, pt) { * @param {object} trace * @param {object || array} contOut (mutated here) */ -var _$fillHoverText_288 = function fillHoverText(calcPt, trace, contOut) { +var _$fillHoverText_289 = function fillHoverText(calcPt, trace, contOut) { var fill = Array.isArray(contOut) ? function(v) { contOut.push(v); } : function(v) { contOut.text = v; }; - var htx = _$lib_166.extractOption(calcPt, trace, 'htx', 'hovertext'); + var htx = _$lib_167.extractOption(calcPt, trace, 'htx', 'hovertext'); if(isValid(htx)) return fill(htx); - var tx = _$lib_166.extractOption(calcPt, trace, 'tx', 'text'); + var tx = _$lib_167.extractOption(calcPt, trace, 'tx', 'text'); if(isValid(tx)) return fill(tx); }; @@ -37398,11 +37701,11 @@ function isValid(v) { 'use strict'; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -/* removed: var _$attributes_267 = require('./attributes'); */; -/* removed: var _$fillHoverText_288 = require('../scatter/fill_hover_text'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +/* removed: var _$attributes_268 = require('./attributes'); */; +/* removed: var _$fillHoverText_289 = require('../scatter/fill_hover_text'); */; -var _$hoverPoints_271 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_272 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var geo = pointData.subplot; @@ -37446,7 +37749,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { var hoverinfo = pt.hi || trace.hoverinfo; var parts = (hoverinfo === 'all') ? - _$attributes_267.hoverinfo.flags : + _$attributes_268.hoverinfo.flags : hoverinfo.split('+'); var hasName = (parts.indexOf('name') !== -1); @@ -37458,7 +37761,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { var text = []; function formatter(val) { - return _$axes_209.tickText(axis, axis.c2l(val), 'hover').text; + return _$axes_210.tickText(axis, axis.c2l(val), 'hover').text; } if(hasIdAsNameLabel) { @@ -37470,7 +37773,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { if(hasZ) text.push(formatter(pt.z)); if(hasText) { - _$fillHoverText_288(pt, trace, text); + _$fillHoverText_289(pt, trace, text); } pointData.extraText = text.join('
'); @@ -37734,7 +38037,7 @@ var _$countryRegex_7 = { ZWE: 'zimbabwe|^(?!.*northern).*rhodesia' } -var _$geo_location_utils_161 = {}; +var _$geo_location_utils_162 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -37747,19 +38050,19 @@ var _$geo_location_utils_161 = {}; 'use strict'; /* removed: var _$countryRegex_7 = require('country-regex'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; // make list of all country iso3 ids from at runtime var countryIds = Object.keys(_$countryRegex_7); var locationmodeToIdFinder = { - 'ISO-3': _$lib_166.identity, - 'USA-states': _$lib_166.identity, + 'ISO-3': _$lib_167.identity, + 'USA-states': _$lib_167.identity, 'country names': countryNameToISO3 }; -_$geo_location_utils_161.locationToFeature = function(locationmode, location, features) { +_$geo_location_utils_162.locationToFeature = function(locationmode, location, features) { if(!location || typeof location !== 'string') return false; var locationId = getLocationId(locationmode, location); @@ -37771,7 +38074,7 @@ _$geo_location_utils_161.locationToFeature = function(locationmode, location, fe if(feature.id === locationId) return feature; } - _$lib_166.log([ + _$lib_167.log([ 'Location with id', locationId, 'does not have a matching topojson feature at this resolution.' ].join(' ')); @@ -37793,7 +38096,7 @@ function countryNameToISO3(countryName) { if(regex.test(countryName.trim().toLowerCase())) return iso3; } - _$lib_166.log('Unrecognized country name: ' + countryName + '.'); + _$lib_167.log('Unrecognized country name: ' + countryName + '.'); return false; } @@ -37813,7 +38116,7 @@ function countryNameToISO3(countryName) { /* removed: var _$drawing_70 = require('../../components/drawing'); */; /* removed: var _$colorscale_60 = require('../../components/colorscale'); */; -var _$style_275 = function style(gd, calcTrace) { +var _$style_276 = function style(gd, calcTrace) { if(calcTrace) styleTrace(gd, calcTrace); }; @@ -37855,14 +38158,14 @@ function styleTrace(gd, calcTrace) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$polygon_178 = require('../../lib/polygon'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$polygon_179 = require('../../lib/polygon'); */; -var getTopojsonFeatures = _$topojson_utils_190.getTopojsonFeatures; -var locationToFeature = _$geo_location_utils_161.locationToFeature; -/* removed: var _$style_275 = require('./style'); */; +var getTopojsonFeatures = _$topojson_utils_191.getTopojsonFeatures; +var locationToFeature = _$geo_location_utils_162.locationToFeature; +/* removed: var _$style_276 = require('./style'); */; -var _$plot_273 = function plot(gd, geo, calcData) { +var _$plot_274 = function plot(gd, geo, calcData) { for(var i = 0; i < calcData.length; i++) { calcGeoJSON(calcData[i], geo.topojson); } @@ -37882,7 +38185,7 @@ var _$plot_273 = function plot(gd, geo, calcData) { var sel = calcTrace[0].node3 = _$d3_8.select(this); var paths = sel.selectAll('path.choroplethlocation') - .data(_$lib_166.identity); + .data(_$lib_167.identity); paths.enter().append('path') .classed('choroplethlocation', true); @@ -37890,7 +38193,7 @@ var _$plot_273 = function plot(gd, geo, calcData) { paths.exit().remove(); // call style here within topojson request callback - _$style_275(gd, calcTrace); + _$style_276(gd, calcTrace); }); }; @@ -37955,7 +38258,7 @@ function feature2polygons(feature) { } } - polygons.push(_$polygon_178.tester(pts)); + polygons.push(_$polygon_179.tester(pts)); }; } else if(loc === 'ATA') { // Antarctica has a landmass that wraps around every longitudes which @@ -37965,7 +38268,7 @@ function feature2polygons(feature) { // polygon that do not cross anti-meridian need no special handling if(crossAntiMeridianIndex === null) { - return polygons.push(_$polygon_178.tester(pts)); + return polygons.push(_$polygon_179.tester(pts)); } // stitch polygon by adding pt over South Pole, @@ -37991,14 +38294,14 @@ function feature2polygons(feature) { // 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_178.tester(stitch); + var tester = _$polygon_179.tester(stitch); tester.pts.pop(); polygons.push(tester); }; } else { // otherwise using same array ref is fine appendPolygon = function(pts) { - polygons.push(_$polygon_178.tester(pts)); + polygons.push(_$polygon_179.tester(pts)); }; } @@ -38030,7 +38333,7 @@ function feature2polygons(feature) { 'use strict'; -var _$selectPoints_274 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_275 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -38105,26 +38408,86 @@ var _$constants_47 = { 'use strict'; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; -var _$handleCategoryOrderDefaults_213 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } - var arrayIn = containerIn.categoryarray, - orderDefault; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } + } + + return Object.keys(lookup); +} +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_214 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; + + var arrayIn = containerIn.categoryarray; var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; if(isValidArray) orderDefault = 'array'; var order = coerce('categoryorder', orderDefault); + var array; // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + if(order === 'array') { + array = coerce('categoryarray'); + } // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; + order = containerOut.categoryorder = 'trace'; + } + + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } } }; @@ -38140,7 +38503,7 @@ var _$handleCategoryOrderDefaults_213 = function handleCategoryOrderDefaults(con var colorMix = _$tinycolor_26.mix; var lightFraction = _$attributes_44.lightFraction; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /** * @param {object} opts : @@ -38152,13 +38515,13 @@ var lightFraction = _$attributes_44.lightFraction; * - noZeroLine {boolean} : don't coerce zeroline* attributes * - attributes {object} : attribute object associated with input containers */ -var _$handleLineGridDefaults_223 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { +var _$handleLineGridDefaults_224 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { opts = opts || {}; var dfltColor = opts.dfltColor; function coerce2(attr, dflt) { - return _$lib_166.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + return _$lib_167.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } var lineColor = coerce2('linecolor', dfltColor); @@ -38200,97 +38563,18 @@ var _$handleLineGridDefaults_223 = function handleLineGridDefaults(containerIn, * LICENSE file in the root directory of this source tree. */ - -'use strict'; - -/* removed: var _$d3_8 = require('d3'); */; - -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { - - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. - - var categoryArray = []; - - var traceLines = data.map(function(d) {return d[axisLetter];}); - - var i, j, tracePoints, category, insertionIndex; - - var bisector = _$d3_8.bisector(sortFunction).left; - - for(i = 0; i < traceLines.length; i++) { - - tracePoints = traceLines[i]; - - for(j = 0; j < tracePoints.length; j++) { - - category = tracePoints[j]; - - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; - - insertionIndex = bisector(categoryArray, category); - - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; - - // insert value - categoryArray.splice(insertionIndex, 0, category); - } - } - - return categoryArray; -} - - -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ - -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_224 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { - - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_8.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_8.descending, data); - case 'trace': return []; - default: return []; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -/* removed: var _$layout_attributes_221 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_222 = require('./layout_attributes'); */; /* removed: var _$handleTickValueDefaults_231 = require('./tick_value_defaults'); */; /* removed: var _$handleTickDefaults_230 = require('./tick_mark_defaults'); */; /* removed: var _$handleTickLabelDefaults_229 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_213 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_223 = require('./line_grid_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_214 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_224 = require('./line_grid_defaults'); */; /* removed: var _$setConvert_228 = require('./set_convert'); */; -/* removed: var _$orderedCategories_224 = require('./ordered_categories'); */; /** * options: object containing: @@ -38304,8 +38588,9 @@ var _$orderedCategories_224 = function orderedCategories(axisLetter, categoryord * data: the plot data, used to manage categories * bgColor: the plot background color, to calculate default gridline colors */ -var _$handleAxisDefaults_211 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { +var _$handleAxisDefaults_212 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { var letter = options.letter; + var id = containerOut._id; var font = options.font || {}; var visible = coerce('visible', !options.cheateronly); @@ -38313,7 +38598,7 @@ var _$handleAxisDefaults_211 = function handleAxisDefaults(containerIn, containe var axType = containerOut.type; if(axType === 'date') { - var handleCalendarDefaults = _$registry_258.getComponentMethod('calendars', 'handleDefaults'); + var handleCalendarDefaults = _$registry_259.getComponentMethod('calendars', 'handleDefaults'); handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } @@ -38332,11 +38617,7 @@ var _$handleAxisDefaults_211 = function handleAxisDefaults(containerIn, containe coerce('range'); containerOut.cleanRange(); - _$handleCategoryOrderDefaults_213(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_224(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; - + _$handleCategoryOrderDefaults_214(containerIn, containerOut, coerce, options); if(axType !== 'category' && !options.noHover) coerce('hoverformat'); @@ -38346,9 +38627,11 @@ var _$handleAxisDefaults_211 = function handleAxisDefaults(containerIn, containe // if axis.color was provided, use it for fonts too; otherwise, // inherit from global font color in case that was provided. var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_166.coerceFont(coerce, 'titlefont', { + coerce('title', dfltTitle); + _$lib_167.coerceFont(coerce, 'titlefont', { family: font.family, size: Math.round(font.size * 1.2), color: dfltFontColor @@ -38357,11 +38640,11 @@ var _$handleAxisDefaults_211 = function handleAxisDefaults(containerIn, containe _$handleTickValueDefaults_231(containerIn, containerOut, coerce, axType); _$handleTickLabelDefaults_229(containerIn, containerOut, coerce, axType, options); _$handleTickDefaults_230(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_223(containerIn, containerOut, coerce, { + _$handleLineGridDefaults_224(containerIn, containerOut, coerce, { dfltColor: dfltColor, bgColor: options.bgColor, showGrid: options.showGrid, - attributes: _$layout_attributes_221 + attributes: _$layout_attributes_222 }); if(containerOut.showline || containerOut.ticks) coerce('mirror'); @@ -38384,7 +38667,7 @@ var _$handleAxisDefaults_211 = function handleAxisDefaults(containerIn, containe /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; var _$handlePositionDefaults_225 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { @@ -38410,7 +38693,7 @@ var _$handlePositionDefaults_225 = function handlePositionDefaults(containerIn, dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); dfltPosition = dfltPosition || 0; - var anchor = _$lib_166.coerce(containerIn, containerOut, { + var anchor = _$lib_167.coerce(containerIn, containerOut, { anchor: { valType: 'enumerated', values: ['free'].concat(counterAxes), @@ -38420,7 +38703,7 @@ var _$handlePositionDefaults_225 = function handlePositionDefaults(containerIn, if(anchor === 'free') coerce('position', dfltPosition); - _$lib_166.coerce(containerIn, containerOut, { + _$lib_167.coerce(containerIn, containerOut, { side: { valType: 'enumerated', values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], @@ -38430,7 +38713,7 @@ var _$handlePositionDefaults_225 = function handlePositionDefaults(containerIn, var overlaying = false; if(overlayableAxes.length) { - overlaying = _$lib_166.coerce(containerIn, containerOut, { + overlaying = _$lib_167.coerce(containerIn, containerOut, { overlaying: { valType: 'enumerated', values: [false].concat(overlayableAxes), @@ -38446,7 +38729,7 @@ var _$handlePositionDefaults_225 = function handlePositionDefaults(containerIn, // perhaps I should make a private version _domain that all axes get??? var domain = coerce('domain', dfltDomain); if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_166.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + _$lib_167.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } coerce('layer'); @@ -38469,21 +38752,21 @@ var _$handlePositionDefaults_225 = function handlePositionDefaults(containerIn, /* removed: var _$tinycolor_26 = require('tinycolor2'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; /* removed: var _$dragelement_67 = require('../dragelement'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -var __extendFlat_49 = _$extend_158.extendFlat; -/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +var __extendFlat_49 = _$extend_159.extendFlat; +/* removed: var _$setCursor_186 = require('../../lib/setcursor'); */; /* removed: var _$drawing_70 = require('../drawing'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$titles_138 = require('../titles'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; var __LINE_SPACING_49 = _$alignment_145.LINE_SPACING; -/* removed: var _$handleAxisDefaults_211 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handleAxisDefaults_212 = require('../../plots/cartesian/axis_defaults'); */; /* removed: var _$handlePositionDefaults_225 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_221 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$layout_attributes_222 = require('../../plots/cartesian/layout_attributes'); */; /* removed: var _$attributes_46 = require('./attributes'); */; var cn = _$constants_47.cn; @@ -38647,11 +38930,11 @@ var _$draw_49 = function draw(gd, id) { // Coerce w.r.t. Axes layoutAttributes: // re-use axes.js logic without updating _fullData function coerce(attr, dflt) { - return _$lib_166.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_221, attr, dflt); + return _$lib_167.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_222, attr, dflt); } // Prepare the Plotly axis object - _$handleAxisDefaults_211(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handleAxisDefaults_212(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); _$handlePositionDefaults_225(cbAxisIn, cbAxisOut, coerce, axisOptions); // position can't go in through supplyDefaults @@ -38673,14 +38956,14 @@ var _$draw_49 = function draw(gd, id) { cbAxisOut.tick0 = opts.levels.start; var dtick = opts.levels.size; // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_166.constrain( + var autoNtick = _$lib_167.constrain( (yBottomPx - yTopPx) / 50, 4, 15) + 1, dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick); if(dtFactor > 1) { var dtexp = Math.pow(10, Math.floor( Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_166.roundUp(dtFactor / dtexp, [2, 5, 10]); + dtick *= dtexp * _$lib_167.roundUp(dtFactor / dtexp, [2, 5, 10]); // if the contours are at round multiples, reset tick0 // so they're still at round multiples. Otherwise, // keep the first label on the first contour level @@ -38701,20 +38984,21 @@ var _$draw_49 = function draw(gd, id) { cbAxisOut.setScale(); // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_8.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); + var container = _$lib_167.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_8.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); + container.attr('transform', 'translate(' + Math.round(gs.l) + ',' + Math.round(gs.t) + ')'); // TODO: this opposite transform is a hack until we make it @@ -38785,7 +39069,7 @@ var _$draw_49 = function draw(gd, id) { } else { cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_187.lineCount(titleText); + var nlines = _$svg_text_utils_188.lineCount(titleText); titleTrans[1] += (1 - nlines) * lineSize; } @@ -38871,9 +39155,9 @@ var _$draw_49 = function draw(gd, id) { // so we don't need such complicated logic in Titles.draw // if title is on the top or bottom, we've already drawn it // this title call only handles side=right - return _$lib_166.syncOrAsync([ + return _$lib_167.syncOrAsync([ function() { - return _$axes_209.doTicks(gd, cbAxisOut, true); + return _$axes_210.doTicks(gd, cbAxisOut, true); }, function() { if(['top', 'bottom'].indexOf(opts.titleside) === -1) { @@ -38904,7 +39188,7 @@ var _$draw_49 = function draw(gd, id) { function drawTitle(titleClass, titleOpts) { var trace = getTrace(), propName; - if(_$registry_258.traceIs(trace, 'markerColorscale')) { + if(_$registry_259.traceIs(trace, 'markerColorscale')) { propName = 'marker.colorbar.title'; } else propName = 'colorbar.title'; @@ -39004,7 +39288,7 @@ var _$draw_49 = function draw(gd, id) { }); } - var cbDone = _$lib_166.syncOrAsync([ + var cbDone = _$lib_167.syncOrAsync([ _$plots_250.previousPromises, drawAxis, _$plots_250.previousPromises, @@ -39024,7 +39308,7 @@ var _$draw_49 = function draw(gd, id) { gd: gd, prepFn: function() { t0 = container.attr('transform'); - _$setCursor_185(container); + _$setCursor_186(container); }, moveFn: function(dx, dy) { container.attr('transform', @@ -39037,13 +39321,13 @@ var _$draw_49 = function draw(gd, id) { var csr = _$dragelement_67.getCursor(xf, yf, opts.xanchor, opts.yanchor); - _$setCursor_185(container, csr); + _$setCursor_186(container, csr); }, doneFn: function() { - _$setCursor_185(container); + _$setCursor_186(container); if(xf !== undefined && yf !== undefined) { - _$registry_258.call('restyle', + _$registry_259.call('restyle', gd, {'colorbar.x': xf, 'colorbar.y': yf}, getTrace().index @@ -39073,8 +39357,8 @@ var _$draw_49 = function draw(gd, id) { // setter - for multi-part properties, // set only the parts that are provided - opts[name] = _$lib_166.isPlainObject(opts[name]) ? - _$lib_166.extendFlat(opts[name], v) : + opts[name] = _$lib_167.isPlainObject(opts[name]) ? + _$lib_167.extendFlat(opts[name], v) : v; return component; @@ -39111,20 +39395,20 @@ var _$draw_49 = function draw(gd, id) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; /* removed: var _$colorscale_60 = require('../../components/colorscale'); */; /* removed: var _$draw_49 = require('../../components/colorbar/draw'); */; -var _$colorbar_276 = function colorbar(gd, cd) { +var _$colorbar_277 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, zmin = trace.zmin, zmax = trace.zmax; - if(!_$fastIsnumeric_11(zmin)) zmin = _$lib_166.aggNums(Math.min, null, trace.z); - if(!_$fastIsnumeric_11(zmax)) zmax = _$lib_166.aggNums(Math.max, null, trace.z); + if(!_$fastIsnumeric_11(zmin)) zmin = _$lib_167.aggNums(Math.min, null, trace.z); + if(!_$fastIsnumeric_11(zmax)) zmax = _$lib_167.aggNums(Math.max, null, trace.z); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); @@ -39161,15 +39445,15 @@ var _$colorbar_276 = function colorbar(gd, cd) { var Choropleth = {}; -Choropleth.attributes = _$attributes_267; -Choropleth.supplyDefaults = _$supplyDefaults_269; -Choropleth.colorbar = _$colorbar_276; -Choropleth.calc = _$calc_268; -Choropleth.plot = _$plot_273; -Choropleth.style = _$style_275; -Choropleth.hoverPoints = _$hoverPoints_271; -Choropleth.eventData = _$eventData_270; -Choropleth.selectPoints = _$selectPoints_274; +Choropleth.attributes = _$attributes_268; +Choropleth.supplyDefaults = _$supplyDefaults_270; +Choropleth.colorbar = _$colorbar_277; +Choropleth.calc = _$calc_269; +Choropleth.plot = _$plot_274; +Choropleth.style = _$style_276; +Choropleth.hoverPoints = _$hoverPoints_272; +Choropleth.eventData = _$eventData_271; +Choropleth.selectPoints = _$selectPoints_275; Choropleth.moduleType = 'trace'; Choropleth.name = 'choropleth'; @@ -39179,7 +39463,7 @@ Choropleth.meta = { }; -var _$Choropleth_272 = Choropleth; +var _$Choropleth_273 = Choropleth; /** * Copyright 2012-2018, Plotly, Inc. @@ -39191,12 +39475,12 @@ var _$Choropleth_272 = Choropleth; 'use strict'; -var _$choropleth_3 = _$Choropleth_272; +var _$choropleth_3 = _$Choropleth_273; var _$plotcss_1 = {}; 'use strict'; -/* removed: var _$lib_166 = require('../src/lib'); */; +/* removed: var _$lib_167 = require('../src/lib'); */; var rules = { "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;", "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;", @@ -39255,7 +39539,7 @@ for(var selector in rules) { var fullSelector = selector.replace(/^,/,' ,') .replace(/X/g, '.js-plotly-plot .plotly') .replace(/Y/g, '.plotly-notifier'); - _$lib_166.addStyleRule(fullSelector, rules[selector]); + _$lib_167.addStyleRule(fullSelector, rules[selector]); } 'use strict'; @@ -40809,7 +41093,7 @@ var _$arrow_paths_29 = [ /* removed: var _$arrow_paths_29 = require('./arrow_paths'); */; /* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_214 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_215 = require('../../plots/cartesian/constants'); */; var _$attributes_30 = { @@ -41009,7 +41293,7 @@ var _$attributes_30 = { dflt: 'pixel', values: [ 'pixel', - _$constants_214.idRegex.x.toString() + _$constants_215.idRegex.x.toString() ], editType: 'calc', @@ -41020,7 +41304,7 @@ var _$attributes_30 = { dflt: 'pixel', values: [ 'pixel', - _$constants_214.idRegex.y.toString() + _$constants_215.idRegex.y.toString() ], editType: 'calc', @@ -41031,7 +41315,7 @@ var _$attributes_30 = { valType: 'enumerated', values: [ 'paper', - _$constants_214.idRegex.x.toString() + _$constants_215.idRegex.x.toString() ], editType: 'calc', @@ -41062,7 +41346,7 @@ var _$attributes_30 = { valType: 'enumerated', values: [ 'paper', - _$constants_214.idRegex.y.toString() + _$constants_215.idRegex.y.toString() ], editType: 'calc', @@ -41317,15 +41601,15 @@ var _$drawArrowHead_37 = function drawArrowHead(el3, ends, options) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$drawing_70 = require('../drawing'); */; /* removed: var _$fx_87 = require('../fx'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_186 = require('../../lib/setcursor'); */; /* removed: var _$dragelement_67 = require('../dragelement'); */; /* removed: var _$drawArrowHead_37 = require('./draw_arrow_head'); */; @@ -41369,8 +41653,8 @@ function __draw_36(gd) { function drawOne(gd, index) { var fullLayout = gd._fullLayout; var options = fullLayout.annotations[index] || {}; - var xa = _$axes_209.getFromId(gd, options.xref); - var ya = _$axes_209.getFromId(gd, options.yref); + var xa = _$axes_210.getFromId(gd, options.xref); + var ya = _$axes_210.getFromId(gd, options.yref); drawRaw(gd, options, index, false, xa, ya); } @@ -41439,7 +41723,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextGroupInner = annTextGroup.append('g') .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_185, 'default') + .call(_$setCursor_186, 'default') .on('click', function() { gd._dragging = false; @@ -41523,7 +41807,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }[options.align] || 'middle' }); - _$svg_text_utils_187.convertToTspans(s, gd, drawGraphicalElements); + _$svg_text_utils_188.convertToTspans(s, gd, drawGraphicalElements); return s; } @@ -41664,7 +41948,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // partially visible var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height']; if(axRef === 'paper') { - posPx.head = _$lib_166.constrain(posPx.head, 1, maxPx - 1); + posPx.head = _$lib_167.constrain(posPx.head, 1, maxPx - 1); } if(tailRef === 'pixel') { var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), @@ -41729,7 +42013,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var texty = borderfull + yShift - anntextBB.top; var textx = borderfull + xShift - anntextBB.left; - annText.call(_$svg_text_utils_187.positionText, textx, texty) + annText.call(_$svg_text_utils_188.positionText, textx, texty) .call(_$drawing_70.setClipUrl, isSizeConstrained ? annClipID : null); } @@ -41772,9 +42056,9 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // find the edge of the text box, where we'll start the arrow: // create transform matrix to rotate the text box corners - transform = _$lib_166.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_166.apply2DTransform(transform), - applyTransform2 = _$lib_166.apply2DTransform2(transform), + transform = _$lib_167.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_167.apply2DTransform(transform), + applyTransform2 = _$lib_167.apply2DTransform2(transform), // calculate and transform bounding box width = +annTextBG.attr('width'), @@ -41796,7 +42080,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // to get the parity of the number of intersections. if(edges.reduce(function(a, x) { return a ^ - !!_$lib_166.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, + !!_$lib_167.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, x[0], x[1], x[2], x[3]); }, false)) { // no line or arrow - so quit drawArrow now @@ -41804,7 +42088,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } edges.forEach(function(x) { - var p = _$lib_166.segmentsIntersect(tailX, tailY, headX, headY, + var p = _$lib_167.segmentsIntersect(tailX, tailY, headX, headY, x[0], x[1], x[2], x[3]); if(p) { tailX = p.x; @@ -41898,7 +42182,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }, doneFn: function() { - _$registry_258.call('relayout', gd, update); + _$registry_259.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -41976,11 +42260,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform }); - _$setCursor_185(annTextGroupInner, csr); + _$setCursor_186(annTextGroupInner, csr); }, doneFn: function() { - _$setCursor_185(annTextGroupInner); - _$registry_258.call('relayout', gd, update); + _$setCursor_186(annTextGroupInner); + _$registry_259.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -41989,7 +42273,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } if(edits.annotationText) { - annText.call(_$svg_text_utils_187.makeEditable, {delegate: annTextGroupInner, gd: gd}) + annText.call(_$svg_text_utils_188.makeEditable, {delegate: annTextGroupInner, gd: gd}) .call(textLayout) .on('edit', function(_text) { options.text = _text; @@ -42005,7 +42289,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { update[ya._name + '.autorange'] = true; } - _$registry_258.call('relayout', gd, update); + _$registry_259.call('relayout', gd, update); }); } else annText.call(textLayout); @@ -42022,15 +42306,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; var __draw_31 = _$draw_36.draw; var _$calcAutorange_31 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - annotationList = _$lib_166.filterVisible(fullLayout.annotations); + annotationList = _$lib_167.filterVisible(fullLayout.annotations); if(!annotationList.length || !gd._fullData.length) return; @@ -42041,9 +42325,9 @@ var _$calcAutorange_31 = function calcAutorange(gd) { }); for(var axId in annotationAxes) { - var ax = _$axes_209.getFromId(gd, axId); + var ax = _$axes_210.getFromId(gd, axId); if(ax && ax.autorange) { - return _$lib_166.syncOrAsync([ + return _$lib_167.syncOrAsync([ __draw_31, annAutorange ], gd); @@ -42058,9 +42342,9 @@ function annAutorange(gd) { // relative to their anchor points // use the arrow and the text bg rectangle, // as the whole anno may include hidden text in its bbox - _$lib_166.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_209.getFromId(gd, ann.xref), - ya = _$axes_209.getFromId(gd, ann.yref), + _$lib_167.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_210.getFromId(gd, ann.xref), + ya = _$axes_210.getFromId(gd, ann.yref), headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; @@ -42074,12 +42358,12 @@ function annAutorange(gd) { if(ann.axref === ann.xref) { // expand for the arrowhead (padded by arrowhead) - _$axes_209.expand(xa, [xa.r2c(ann.x)], { + _$axes_210.expand(xa, [xa.r2c(ann.x)], { ppadplus: headPlus, ppadminus: headMinus }); // again for the textbox (padded by textbox) - _$axes_209.expand(xa, [xa.r2c(ann.ax)], { + _$axes_210.expand(xa, [xa.r2c(ann.ax)], { ppadplus: Math.max(ann._xpadplus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, startHeadMinus) }); @@ -42087,7 +42371,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_209.expand(xa, [xa.r2c(ann.x)], { + _$axes_210.expand(xa, [xa.r2c(ann.x)], { ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) }); @@ -42101,11 +42385,11 @@ function annAutorange(gd) { startHeadMinus = startHeadSize + ann.yshift; if(ann.ayref === ann.yref) { - _$axes_209.expand(ya, [ya.r2c(ann.y)], { + _$axes_210.expand(ya, [ya.r2c(ann.y)], { ppadplus: headPlus, ppadminus: headMinus }); - _$axes_209.expand(ya, [ya.r2c(ann.ay)], { + _$axes_210.expand(ya, [ya.r2c(ann.ay)], { ppadplus: Math.max(ann._ypadplus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, startHeadMinus) }); @@ -42113,7 +42397,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_209.expand(ya, [ya.r2c(ann.y)], { + _$axes_210.expand(ya, [ya.r2c(ann.y)], { ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) }); @@ -42132,7 +42416,7 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; var _$click_32 = { hasClickToShow: hasClickToShow, @@ -42181,7 +42465,7 @@ function onClick(gd, hoverData) { update['annotations[' + offSet[i] + '].visible'] = false; } - return _$registry_258.call('update', gd, {}, update); + return _$registry_259.call('update', gd, {}, update); } /* @@ -42265,7 +42549,7 @@ function clickData2r(d, ax) { 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_189 = require('../../lib/to_log_range'); */; +/* removed: var _$toLogRange_190 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -42297,7 +42581,7 @@ var _$convertCoords_34 = function convertCoords(gd, ax, newType, doExtra) { var currentVal = ann[attr], newVal = null; - if(toLog) newVal = _$toLogRange_189(currentVal, ax.range); + if(toLog) newVal = _$toLogRange_190(currentVal, ax.range); else newVal = Math.pow(10, currentVal); // if conversion failed, delete the value so it gets a default value @@ -42325,7 +42609,7 @@ var _$convertCoords_34 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$color_45 = require('../color'); */; // defaults common to 'annotations' and 'annotations3d' @@ -42343,7 +42627,7 @@ var _$handleAnnotationCommonDefaults_33 = function handleAnnotationCommonDefault coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); coerce('textangle'); - _$lib_166.coerceFont(coerce, 'font', fullLayout.font); + _$lib_167.coerceFont(coerce, 'font', fullLayout.font); coerce('width'); coerce('align'); @@ -42384,7 +42668,7 @@ var _$handleAnnotationCommonDefaults_33 = function handleAnnotationCommonDefault _$color_45.contrast(hoverBG) ); - _$lib_166.coerceFont(coerce, 'hoverlabel.font', { + _$lib_167.coerceFont(coerce, 'hoverlabel.font', { family: globalHoverLabel.font.family, size: globalHoverLabel.font.size, color: globalHoverLabel.font.color || hoverBorder @@ -42405,8 +42689,8 @@ var _$handleAnnotationCommonDefaults_33 = function handleAnnotationCommonDefault 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; /* removed: var _$handleAnnotationCommonDefaults_33 = require('./common_defaults'); */; /* removed: var _$attributes_30 = require('./attributes'); */; @@ -42416,7 +42700,7 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_166.coerce(annIn, annOut, _$attributes_30, attr, dflt); + return _$lib_167.coerce(annIn, annOut, _$attributes_30, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -42436,15 +42720,15 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann var axLetter = axLetters[i]; // xref, yref - var axRef = _$axes_209.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_210.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); // x, y - _$axes_209.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + _$axes_210.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); if(showArrow) { var arrowPosAttr = 'a' + axLetter, // axref, ayref - aaxRef = _$axes_209.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + aaxRef = _$axes_210.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); // for now the arrow can only be on the same axis or specified as pixels // TODO: sometime it might be interesting to allow it to be on *any* axis @@ -42455,7 +42739,7 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann // ax, ay var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_209.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + _$axes_210.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } // xanchor, yanchor @@ -42466,11 +42750,11 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann } // if you have one coordinate you should have both - _$lib_166.noneOrAll(annIn, annOut, ['x', 'y']); + _$lib_167.noneOrAll(annIn, annOut, ['x', 'y']); // if you have one part of arrow length you should have both if(showArrow) { - _$lib_166.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_167.noneOrAll(annIn, annOut, ['ax', 'ay']); } if(clickToShow) { @@ -42481,10 +42765,10 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann // so we don't have to do this little bit of logic on every hover event annOut._xclick = (xClick === undefined) ? annOut.x : - _$axes_209.cleanPosition(xClick, gdMock, annOut.xref); + _$axes_210.cleanPosition(xClick, gdMock, annOut.xref); annOut._yclick = (yClick === undefined) ? annOut.y : - _$axes_209.cleanPosition(yClick, gdMock, annOut.yref); + _$axes_210.cleanPosition(yClick, gdMock, annOut.yref); } return annOut; @@ -42500,7 +42784,7 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann 'use strict'; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; /** Convenience wrapper for making array container logic DRY and consistent * @@ -42532,12 +42816,12 @@ var _$handleAnnotationDefaults_28 = function handleAnnotationDefaults(annIn, ann * links to supplementary data (e.g. fullData for layout components) * */ -var _$handleArrayContainerDefaults_205 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { +var _$handleArrayContainerDefaults_206 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { var name = opts.name; var previousContOut = parentObjOut[name]; - var contIn = _$lib_166.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + var contIn = _$lib_167.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], contOut = parentObjOut[name] = [], i; @@ -42546,7 +42830,7 @@ var _$handleArrayContainerDefaults_205 = function handleArrayContainerDefaults(p itemOut = {}, itemOpts = {}; - if(!_$lib_166.isPlainObject(itemIn)) { + if(!_$lib_167.isPlainObject(itemIn)) { itemOpts.itemIsNotPlainObject = true; itemIn = {}; } @@ -42561,10 +42845,10 @@ var _$handleArrayContainerDefaults_205 = function handleArrayContainerDefaults(p // in case this array gets its defaults rebuilt independent of the whole layout, // relink the private keys just for this array. - if(_$lib_166.isArrayOrTypedArray(previousContOut)) { + if(_$lib_167.isArrayOrTypedArray(previousContOut)) { var len = Math.min(previousContOut.length, contOut.length); for(i = 0; i < len; i++) { - _$lib_166.relinkPrivateKeys(contOut[i], previousContOut[i]); + _$lib_167.relinkPrivateKeys(contOut[i], previousContOut[i]); } } }; @@ -42580,7 +42864,7 @@ var _$handleArrayContainerDefaults_205 = function handleArrayContainerDefaults(p 'use strict'; -/* removed: var _$handleArrayContainerDefaults_205 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_206 = require('../../plots/array_container_defaults'); */; /* removed: var _$handleAnnotationDefaults_28 = require('./annotation_defaults'); */; @@ -42590,7 +42874,7 @@ var _$supplyLayoutDefaults_35 = function supplyLayoutDefaults(layoutIn, layoutOu handleItemDefaults: _$handleAnnotationDefaults_28 }; - _$handleArrayContainerDefaults_205(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_206(layoutIn, layoutOut, opts); }; /** @@ -42604,8 +42888,8 @@ var _$supplyLayoutDefaults_35 = function supplyLayoutDefaults(layoutIn, layoutOu 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /** * Factory function for checking component arrays for subplot references. @@ -42618,12 +42902,12 @@ var _$supplyLayoutDefaults_35 = function supplyLayoutDefaults(layoutIn, layoutOu * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout) * as expected of a component includeBasePlot method */ -var _$makeIncludeComponents_219 = function makeIncludeComponents(containerArrayName) { +var _$makeIncludeComponents_220 = function makeIncludeComponents(containerArrayName) { return function includeComponents(layoutIn, layoutOut) { var array = layoutIn[containerArrayName]; if(!Array.isArray(array)) return; - var Cartesian = _$registry_258.subplotsRegistry.cartesian; + var Cartesian = _$registry_259.subplotsRegistry.cartesian; var idRegex = Cartesian.idRegex; var subplots = layoutOut._subplots; var xaList = subplots.xaxis; @@ -42633,7 +42917,7 @@ var _$makeIncludeComponents_219 = function makeIncludeComponents(containerArrayN for(var i = 0; i < array.length; i++) { var itemi = array[i]; - if(!_$lib_166.isPlainObject(itemi)) continue; + if(!_$lib_167.isPlainObject(itemi)) continue; var xref = itemi.xref; var yref = itemi.yref; @@ -42641,7 +42925,7 @@ var _$makeIncludeComponents_219 = function makeIncludeComponents(containerArrayN var hasXref = idRegex.x.test(xref); var hasYref = idRegex.y.test(yref); if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_166.pushUnique(layoutOut._basePlotModules, Cartesian); + if(!hasCartesianOrGL2D) _$lib_167.pushUnique(layoutOut._basePlotModules, Cartesian); var newAxis = false; if(hasXref && xaList.indexOf(xref) === -1) { @@ -42687,7 +42971,7 @@ var _$annotations_38 = { layoutAttributes: _$attributes_30, supplyLayoutDefaults: _$supplyLayoutDefaults_35, - includeBasePlot: _$makeIncludeComponents_219('annotations'), + includeBasePlot: _$makeIncludeComponents_220('annotations'), calcAutorange: _$calcAutorange_31, draw: _$draw_36.draw, @@ -42712,7 +42996,7 @@ var _$annotations_38 = { 'use strict'; /* removed: var _$attributes_30 = require('../annotations/attributes'); */; -var __overrideAll_39 = _$edit_types_194.overrideAll; +var __overrideAll_39 = _$edit_types_195.overrideAll; var _$attributes_39 = __overrideAll_39({ _isLinkedToArray: 'annotation', @@ -42798,8 +43082,8 @@ var _$attributes_39 = __overrideAll_39({ 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; var _$convert_40 = function convert(scene) { var fullSceneLayout = scene.fullSceneLayout; @@ -42836,16 +43120,16 @@ function mockAnnAxes(ann, scene) { }; ann._xa = {}; - _$lib_166.extendFlat(ann._xa, base); - _$axes_209.setConvert(ann._xa); + _$lib_167.extendFlat(ann._xa, base); + _$axes_210.setConvert(ann._xa); ann._xa._offset = size.l + domain.x[0] * size.w; ann._xa.l2p = function() { return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); }; ann._ya = {}; - _$lib_166.extendFlat(ann._ya, base); - _$axes_209.setConvert(ann._ya); + _$lib_167.extendFlat(ann._ya, base); + _$axes_210.setConvert(ann._ya); ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; ann._ya.l2p = function() { return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); @@ -42862,14 +43146,14 @@ function mockAnnAxes(ann, scene) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_205 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_206 = require('../../plots/array_container_defaults'); */; /* removed: var _$handleAnnotationCommonDefaults_33 = require('../annotations/common_defaults'); */; /* removed: var _$attributes_39 = require('./attributes'); */; var _$handleDefaults_41 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_205(sceneLayoutIn, sceneLayoutOut, { + _$handleArrayContainerDefaults_206(sceneLayoutIn, sceneLayoutOut, { name: 'annotations', handleItemDefaults: __handleAnnotationDefaults_41, fullLayout: opts.fullLayout @@ -42878,7 +43162,7 @@ var _$handleDefaults_41 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, function __handleAnnotationDefaults_41(annIn, annOut, sceneLayout, opts, itemOpts) { function coerce(attr, dflt) { - return _$lib_166.coerce(annIn, annOut, _$attributes_39, attr, dflt); + return _$lib_167.coerce(annIn, annOut, _$attributes_39, attr, dflt); } function coercePosition(axLetter) { @@ -42888,7 +43172,7 @@ function __handleAnnotationDefaults_41(annIn, annOut, sceneLayout, opts, itemOpt var gdMock = { _fullLayout: {} }; gdMock._fullLayout[axName] = sceneLayout[axName]; - return _$axes_209.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + return _$axes_210.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } @@ -42902,7 +43186,7 @@ function __handleAnnotationDefaults_41(annIn, annOut, sceneLayout, opts, itemOpt coercePosition('z'); // if you have one coordinate you should all three - _$lib_166.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + _$lib_167.noneOrAll(annIn, annOut, ['x', 'y', 'z']); // hard-set here for completeness annOut.xref = 'x'; @@ -42923,7 +43207,7 @@ function __handleAnnotationDefaults_41(annIn, annOut, sceneLayout, opts, itemOpt coerce('ay', -30); // if you have one part of arrow length you should have both - _$lib_166.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_167.noneOrAll(annIn, annOut, ['ax', 'ay']); } return annOut; @@ -43023,8 +43307,8 @@ var _$draw_42 = function draw(scene) { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; var _$annotations3d_43 = { moduleType: 'component', @@ -43045,7 +43329,7 @@ var _$annotations3d_43 = { }; function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_258.subplotsRegistry.gl3d; + var GL3D = _$registry_259.subplotsRegistry.gl3d; if(!GL3D) return; var attrRegex = GL3D.attrRegex; @@ -43054,8 +43338,8 @@ function includeGL3D(layoutIn, layoutOut) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_166.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_166.pushUnique(layoutOut._subplots.gl3d, k); + _$lib_167.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_167.pushUnique(layoutOut._subplots.gl3d, k); } } } @@ -43290,8 +43574,8 @@ function makeComputeErrorValue(type, value) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; /* removed: var _$makeComputeError_74 = require('./compute_error'); */; @@ -43303,10 +43587,10 @@ var _$calc_73 = function calc(gd) { var calcTrace = calcdata[i], trace = calcTrace[0].trace; - if(!_$registry_258.traceIs(trace, 'errorBarsOK')) continue; + if(!_$registry_259.traceIs(trace, 'errorBarsOK')) continue; - var xa = _$axes_209.getFromId(gd, trace.xaxis), - ya = _$axes_209.getFromId(gd, trace.yaxis); + var xa = _$axes_210.getFromId(gd, trace.xaxis), + ya = _$axes_210.getFromId(gd, trace.yaxis); calcOneAxis(calcTrace, trace, xa, 'x'); calcOneAxis(calcTrace, trace, ya, 'y'); @@ -43336,7 +43620,7 @@ function calcOneAxis(calcTrace, trace, axis, coord) { } } - _$axes_209.expand(axis, vals, {padded: true}); + _$axes_210.expand(axis, vals, {padded: true}); } /** @@ -43351,8 +43635,8 @@ function calcOneAxis(calcTrace, trace, axis, coord) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$attributes_72 = require('./attributes'); */; @@ -43363,7 +43647,7 @@ var _$defaults_75 = function(traceIn, traceOut, defaultColor, opts) { containerIn = traceIn[objName] || {}; function coerce(attr, dflt) { - return _$lib_166.coerce(containerIn, containerOut, _$attributes_72, attr, dflt); + return _$lib_167.coerce(containerIn, containerOut, _$attributes_72, attr, dflt); } var hasErrorBars = ( @@ -43409,7 +43693,7 @@ var _$defaults_75 = function(traceIn, traceOut, defaultColor, opts) { if(!opts.inherit || !containerOut[copyAttr]) { coerce('color', defaultColor); coerce('thickness'); - coerce('width', _$registry_258.traceIs(traceOut, 'gl3d') ? 0 : 4); + coerce('width', _$registry_259.traceIs(traceOut, 'gl3d') ? 0 : 4); } }; @@ -43428,7 +43712,7 @@ var _$defaults_75 = function(traceIn, traceOut, defaultColor, opts) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$drawing_70 = require('../drawing'); */; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; var _$plot_77 = function plot(traces, plotinfo, transitionOpts) { var isNew; @@ -43454,7 +43738,7 @@ var _$plot_77 = function plot(traces, plotinfo, transitionOpts) { } var sparse = ( - _$subtypes_302.hasMarkers(trace) && + _$subtypes_303.hasMarkers(trace) && trace.marker.maxdisplayed > 0 ); @@ -43632,24 +43916,24 @@ var _$style_78 = function style(traces) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -var __overrideAll_76 = _$edit_types_194.overrideAll; +/* removed: var _$lib_167 = require('../../lib'); */; +var __overrideAll_76 = _$edit_types_195.overrideAll; /* removed: var _$attributes_72 = require('./attributes'); */; /* removed: var _$calc_73 = require('./calc'); */; var xyAttrs = { - error_x: _$lib_166.extendFlat({}, _$attributes_72), - error_y: _$lib_166.extendFlat({}, _$attributes_72) + error_x: _$lib_167.extendFlat({}, _$attributes_72), + error_y: _$lib_167.extendFlat({}, _$attributes_72) }; delete xyAttrs.error_x.copy_zstyle; delete xyAttrs.error_y.copy_zstyle; delete xyAttrs.error_y.copy_ystyle; var xyzAttrs = { - error_x: _$lib_166.extendFlat({}, _$attributes_72), - error_y: _$lib_166.extendFlat({}, _$attributes_72), - error_z: _$lib_166.extendFlat({}, _$attributes_72) + error_x: _$lib_167.extendFlat({}, _$attributes_72), + error_y: _$lib_167.extendFlat({}, _$attributes_72), + error_z: _$lib_167.extendFlat({}, _$attributes_72) }; delete xyzAttrs.error_x.copy_ystyle; delete xyzAttrs.error_y.copy_ystyle; @@ -43725,10 +44009,10 @@ function hoverInfo(calcPoint, trace, hoverPoint) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -var __counterRegex_91 = _$regex_181.counter; +/* removed: var _$lib_167 = require('../../lib'); */; +var __counterRegex_91 = _$regex_182.counter; var __domainAttrs_91 = _$domain_235.attributes; -var cartesianIdRegex = _$constants_214.idRegex; +var cartesianIdRegex = _$constants_215.idRegex; var gridAttrs = { rows: { @@ -43810,7 +44094,7 @@ var gridAttrs = { values: ['bottom', 'bottom plot', 'top plot', 'top'], dflt: 'bottom plot', - editType: 'ticks', + editType: 'plot', }, yside: { @@ -43818,21 +44102,36 @@ var gridAttrs = { values: ['left', 'left plot', 'right plot', 'right'], dflt: 'left plot', - editType: 'ticks', + 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; - if(!gridIn) return; + 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(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + var hasXaxes = Array.isArray(xAxes); + var hasYaxes = Array.isArray(yAxes); + var isSplomGenerated = ( + hasXaxes && xAxes !== gridIn.xaxes && + hasYaxes && yAxes !== gridIn.yaxes + ); var dfltRows, dfltColumns; @@ -43841,14 +44140,14 @@ function sizeDefaults(layoutIn, layoutOut) { dfltColumns = gridIn.subplots[0].length; } else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } var gridOut = layoutOut.grid = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + return _$lib_167.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } var rows = coerce('rows', dfltRows); @@ -43865,17 +44164,26 @@ function sizeDefaults(layoutIn, layoutOut) { 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) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } + gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) + 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, len, reversed) { +function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) { var dirGap = coerce(axLetter + 'gap', dfltGap); var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + coerce(axLetter + 'side', dfltSide); var out = new Array(len); var start = domain[0]; @@ -43895,7 +44203,7 @@ function contentDefaults(layoutIn, layoutOut) { // make sure we got to the end of handleGridSizing if(!gridOut || !gridOut._domains) return; - var gridIn = layoutIn.grid; + var gridIn = layoutIn.grid || {}; var subplots = layoutOut._subplots; var hasSubplotGrid = gridOut._hasSubplotGrid; var rows = gridOut.rows; @@ -43941,8 +44249,10 @@ function contentDefaults(layoutIn, layoutOut) { } } else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); + 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 = {}; @@ -44079,7 +44389,7 @@ var _$grid_91 = { 'use strict'; -/* removed: var _$constants_214 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_215 = require('../../plots/cartesian/constants'); */; var _$attributes_92 = { @@ -44182,7 +44492,7 @@ var _$attributes_92 = { valType: 'enumerated', values: [ 'paper', - _$constants_214.idRegex.x.toString() + _$constants_215.idRegex.x.toString() ], dflt: 'paper', @@ -44194,7 +44504,7 @@ var _$attributes_92 = { valType: 'enumerated', values: [ 'paper', - _$constants_214.idRegex.y.toString() + _$constants_215.idRegex.y.toString() ], dflt: 'paper', @@ -44216,7 +44526,7 @@ var _$attributes_92 = { 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_189 = require('../../lib/to_log_range'); */; +/* removed: var _$toLogRange_190 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -44260,7 +44570,7 @@ var _$convertCoords_93 = function convertCoords(gd, ax, newType, doExtra) { newSize = null; if(toLog) { - newPos = _$toLogRange_189(currentPos, ax.range); + newPos = _$toLogRange_190(currentPos, ax.range); // this is the inverse of the conversion we do in fromLog below // so that the conversion is reversible (notice the fromLog conversion @@ -44296,9 +44606,9 @@ var _$convertCoords_93 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_205 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_206 = require('../../plots/array_container_defaults'); */; /* removed: var _$attributes_92 = require('./attributes'); */; var name = 'images'; @@ -44309,14 +44619,14 @@ var _$supplyLayoutDefaults_94 = function supplyLayoutDefaults(layoutIn, layoutOu handleItemDefaults: imageDefaults }; - _$handleArrayContainerDefaults_205(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_206(layoutIn, layoutOut, opts); }; function imageDefaults(imageIn, imageOut, fullLayout) { function coerce(attr, dflt) { - return _$lib_166.coerce(imageIn, imageOut, _$attributes_92, attr, dflt); + return _$lib_167.coerce(imageIn, imageOut, _$attributes_92, attr, dflt); } var source = coerce('source'); @@ -44338,9 +44648,9 @@ function imageDefaults(imageIn, imageOut, fullLayout) { for(var i = 0; i < 2; i++) { // 'paper' is the fallback axref var axLetter = axLetters[i], - axRef = _$axes_209.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + axRef = _$axes_210.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - _$axes_209.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + _$axes_210.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); } return imageOut; @@ -44358,7 +44668,7 @@ function imageDefaults(imageIn, imageOut, fullLayout) { /* removed: var _$d3_8 = require('d3'); */; /* removed: var _$drawing_70 = require('../drawing'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; /* removed: var _$xmlns_namespaces_149 = require('../../constants/xmlns_namespaces'); */; var _$draw_95 = function draw(gd) { @@ -44472,8 +44782,8 @@ var _$draw_95 = function draw(gd) { var thisImage = _$d3_8.select(this); // Axes if specified - var xa = _$axes_209.getFromId(gd, d.xref), - ya = _$axes_209.getFromId(gd, d.yref); + var xa = _$axes_210.getFromId(gd, d.xref), + ya = _$axes_210.getFromId(gd, d.yref); var size = fullLayout._size, width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, @@ -44582,7 +44892,7 @@ var _$images_96 = { layoutAttributes: _$attributes_92, supplyLayoutDefaults: _$supplyLayoutDefaults_94, - includeBasePlot: _$makeIncludeComponents_219('images'), + includeBasePlot: _$makeIncludeComponents_220('images'), draw: _$draw_95, @@ -44735,8 +45045,8 @@ _$helpers_104.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$attributes_98 = require('./attributes'); */; /* removed: var _$layout_attributes_248 = require('../../plots/layout_attributes'); */; @@ -44758,10 +45068,10 @@ var _$legendDefaults_100 = function legendDefaults(layoutIn, layoutOut, fullData if(_$helpers_104.legendGetsTrace(trace)) { visibleTraces++; // always show the legend by default if there's a pie - if(_$registry_258.traceIs(trace, 'pie')) visibleTraces++; + if(_$registry_259.traceIs(trace, 'pie')) visibleTraces++; } - if((_$registry_258.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + if((_$registry_259.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { defaultOrder = _$helpers_104.isGrouped({traceorder: defaultOrder}) ? 'grouped+reversed' : 'reversed'; @@ -44774,10 +45084,10 @@ var _$legendDefaults_100 = function legendDefaults(layoutIn, layoutOut, fullData } function coerce(attr, dflt) { - return _$lib_166.coerce(containerIn, containerOut, _$attributes_98, attr, dflt); + return _$lib_167.coerce(containerIn, containerOut, _$attributes_98, attr, dflt); } - var showLegend = _$lib_166.coerce(layoutIn, layoutOut, + var showLegend = _$lib_167.coerce(layoutIn, layoutOut, _$layout_attributes_248, 'showlegend', visibleTraces > 1); if(showLegend === false) return; @@ -44787,7 +45097,7 @@ var _$legendDefaults_100 = function legendDefaults(layoutIn, layoutOut, fullData coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - _$lib_166.coerceFont(coerce, 'font', layoutOut.font); + _$lib_167.coerceFont(coerce, 'font', layoutOut.font); coerce('orientation'); if(containerOut.orientation === 'h') { @@ -44813,7 +45123,7 @@ var _$legendDefaults_100 = function legendDefaults(layoutIn, layoutOut, fullData coerce('xanchor', defaultXAnchor); coerce('y', defaultY); coerce('yanchor', defaultYAnchor); - _$lib_166.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_167.noneOrAll(containerIn, containerOut, ['x', 'y']); }; var _$anchor_utils_97 = {}; @@ -44893,7 +45203,7 @@ var _$constants_99 = { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$helpers_104 = require('./helpers'); */; @@ -44932,7 +45242,7 @@ var _$getLegendData_102 = function getLegendData(calcdata, opts) { if(!_$helpers_104.legendGetsTrace(trace) || !trace.showlegend) continue; - if(_$registry_258.traceIs(trace, 'pie')) { + if(_$registry_259.traceIs(trace, 'pie')) { if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; for(j = 0; j < cd.length; j++) { @@ -44996,8 +45306,8 @@ var _$getLegendData_102 = function getLegendData(calcdata, opts) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; var SHOWISOLATETIP = true; @@ -45038,12 +45348,12 @@ var _$handleClick_103 = function handleClick(g, gd, numClicks) { function setVisibility(fullTrace, visibility) { var fullInput = fullTrace._fullInput; - if(_$registry_258.hasTransform(fullInput, 'groupby')) { + if(_$registry_259.hasTransform(fullInput, 'groupby')) { var kcont = carrs[fullInput.index]; if(!kcont) { - var groupbyIndices = _$registry_258.getTransformIndices(fullInput, 'groupby'); + var groupbyIndices = _$registry_259.getTransformIndices(fullInput, 'groupby'); var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_166.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + kcont = _$lib_167.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); carrs[fullInput.index] = kcont; } @@ -45074,13 +45384,13 @@ var _$handleClick_103 = function handleClick(g, gd, numClicks) { } if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_166.notifier(_$lib_166._(gd, 'Double-click on legend to isolate one trace'), 'long'); + _$lib_167.notifier(_$lib_167._(gd, 'Double-click on legend to isolate one trace'), 'long'); SHOWISOLATETIP = false; } else { SHOWISOLATETIP = false; } - if(_$registry_258.traceIs(fullTrace, 'pie')) { + if(_$registry_259.traceIs(fullTrace, 'pie')) { var thisLabel = legendItem.label, thisLabelIndex = hiddenSlices.indexOf(thisLabel); @@ -45099,7 +45409,7 @@ var _$handleClick_103 = function handleClick(g, gd, numClicks) { } } - _$registry_258.call('relayout', gd, 'hiddenlabels', hiddenSlices); + _$registry_259.call('relayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; @@ -45149,7 +45459,7 @@ var _$handleClick_103 = function handleClick(g, gd, numClicks) { isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - if(!isInGroup && fullData[i].visible === true && !_$registry_258.traceIs(fullData[i], 'notLegendIsolatable')) { + if(!isInGroup && fullData[i].visible === true && !_$registry_259.traceIs(fullData[i], 'notLegendIsolatable')) { isIsolated = false; break; } @@ -45159,7 +45469,7 @@ var _$handleClick_103 = function handleClick(g, gd, numClicks) { // False is sticky; we don't change it. if(fullData[i].visible === false) continue; - if(_$registry_258.traceIs(fullData[i], 'notLegendIsolatable')) { + if(_$registry_259.traceIs(fullData[i], 'notLegendIsolatable')) { continue; } @@ -45205,11 +45515,11 @@ var _$handleClick_103 = function handleClick(g, gd, numClicks) { } } - _$registry_258.call('restyle', gd, attrUpdate, attrIndices); + _$registry_259.call('restyle', gd, attrUpdate, attrIndices); } }; -var _$helpers_277 = {}; +var _$helpers_278 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45220,25 +45530,25 @@ var _$helpers_277 = {}; 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -_$helpers_277.formatPiePercent = function formatPiePercent(v, separators) { +_$helpers_278.formatPiePercent = function formatPiePercent(v, separators) { var vRounded = (v * 100).toPrecision(3); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_166.numSeparate(vRounded, separators) + '%'; + return _$lib_167.numSeparate(vRounded, separators) + '%'; }; -_$helpers_277.formatPieValue = function formatPieValue(v, separators) { +_$helpers_278.formatPieValue = function formatPieValue(v, separators) { var vRounded = v.toPrecision(10); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_166.numSeparate(vRounded, separators); + return _$lib_167.numSeparate(vRounded, separators); }; -_$helpers_277.getFirstFilled = function getFirstFilled(array, indices) { +_$helpers_278.getFirstFilled = function getFirstFilled(array, indices) { if(!Array.isArray(array)) return; for(var i = 0; i < indices.length; i++) { var v = array[indices[i]]; @@ -45246,8 +45556,8 @@ _$helpers_277.getFirstFilled = function getFirstFilled(array, indices) { } }; -_$helpers_277.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_277.getFirstFilled(item, indices); +_$helpers_278.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_278.getFirstFilled(item, indices); else if(item) return item; }; @@ -45262,9 +45572,9 @@ _$helpers_277.castOption = function castOption(item, indices) { 'use strict'; /* removed: var _$color_45 = require('../../components/color'); */; -var castOption = _$helpers_277.castOption; +var castOption = _$helpers_278.castOption; -var _$styleOne_278 = function styleOne(s, pt, trace) { +var _$styleOne_279 = function styleOne(s, pt, trace) { var line = trace.marker.line; var lineColor = castOption(line.color, pt.pts) || _$color_45.defaultLine; var lineWidth = castOption(line.width, pt.pts) || 0; @@ -45282,28 +45592,23 @@ var _$styleOne_278 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$drawing_70 = require('../drawing'); */; /* removed: var _$color_45 = require('../color'); */; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_278 = require('../../traces/pie/style_one'); */; - +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_279 = require('../../traces/pie/style_one'); */; var _$style_106 = function style(s, gd) { s.each(function(d) { var traceGroup = _$d3_8.select(this); - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); + var layers = _$lib_167.ensureSingle(traceGroup, 'g', 'layers'); layers.style('opacity', d[0].trace.opacity); var fill = layers @@ -45333,12 +45638,14 @@ var _$style_106 = function style(s, gd) { .each(styleBoxes) .each(stylePies) .each(styleLines) - .each(stylePoints); + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); function styleLines(d) { var trace = d[0].trace; var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_302.hasLines(trace); + var showLine = _$subtypes_303.hasLines(trace); var contours = trace.contours; if(contours && contours.type === 'constraint') { @@ -45364,9 +45671,9 @@ var _$style_106 = function style(s, gd) { function stylePoints(d) { var d0 = d[0], trace = d0.trace, - showMarkers = _$subtypes_302.hasMarkers(trace), - showText = _$subtypes_302.hasText(trace), - showLines = _$subtypes_302.hasLines(trace); + showMarkers = _$subtypes_303.hasMarkers(trace), + showText = _$subtypes_303.hasText(trace), + showLines = _$subtypes_303.hasLines(trace); var dMod, tMod; @@ -45374,7 +45681,7 @@ var _$style_106 = function style(s, gd) { // use d0.trace to infer arrayOk attributes function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_166.nestedProperty(trace, attrIn).get(), + var valIn = _$lib_167.nestedProperty(trace, attrIn).get(), valToBound = (Array.isArray(valIn) && arrayToValFn) ? arrayToValFn(valIn) : valIn; @@ -45394,10 +45701,10 @@ var _$style_106 = function style(s, gd) { if(showMarkers) { dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_166.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_166.mean, [2, 16]); + dEdit.mo = boundVal('marker.opacity', _$lib_167.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_167.mean, [2, 16]); dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_166.mean, [0, 5]); + dEdit.mlw = boundVal('marker.line.width', _$lib_167.mean, [0, 5]); tEdit.marker = { sizeref: 1, sizemin: 1, @@ -45419,8 +45726,8 @@ var _$style_106 = function style(s, gd) { dEdit.tf = boundVal('textfont.family', pickFirst); } - dMod = [_$lib_166.minExtend(d0, dEdit)]; - tMod = _$lib_166.minExtend(trace, tEdit); + dMod = [_$lib_167.minExtend(d0, dEdit)]; + tMod = _$lib_167.minExtend(trace, tEdit); } var ptgroup = _$d3_8.select(this).select('g.legendpoints'); @@ -45451,7 +45758,7 @@ var _$style_106 = function style(s, gd) { markerLine = marker.line || {}, barpath = _$d3_8.select(this).select('g.legendpoints') .selectAll('path.legendbar') - .data(_$registry_258.traceIs(trace, 'bar') ? [d] : []); + .data(_$registry_259.traceIs(trace, 'bar') ? [d] : []); barpath.enter().append('path').classed('legendbar', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); @@ -45474,7 +45781,7 @@ var _$style_106 = function style(s, gd) { var trace = d[0].trace, pts = _$d3_8.select(this).select('g.legendpoints') .selectAll('path.legendbox') - .data(_$registry_258.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + .data(_$registry_259.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendbox', true) // if we want the median bar, prepend M6,0H-6 .attr('d', 'M6,6H-6V-6H6Z') @@ -45488,7 +45795,61 @@ var _$style_106 = function style(s, gd) { .call(_$color_45.fill, trace.fillcolor); if(w) { - p.call(_$color_45.stroke, trace.line.color); + _$color_45.stroke(p, trace.line.color); + } + }); + } + + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_8.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_8.select(this); + + p.style('stroke-width', w + 'px') + .call(_$color_45.fill, container.fillcolor); + + if(w) { + _$color_45.stroke(p, container.line.color); + } + }); + } + + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_8.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_8.select(this); + + p.style('fill', 'none') + .call(_$drawing_70.dashLine, container.line.dash, w); + + if(w) { + _$color_45.stroke(p, container.line.color); } }); } @@ -45497,13 +45858,13 @@ var _$style_106 = function style(s, gd) { var trace = d[0].trace, pts = _$d3_8.select(this).select('g.legendpoints') .selectAll('path.legendpie') - .data(_$registry_258.traceIs(trace, 'pie') && trace.visible ? [d] : []); + .data(_$registry_259.traceIs(trace, 'pie') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendpie', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); pts.exit().remove(); - if(pts.size()) pts.call(_$styleOne_278, d[0], trace); + if(pts.size()) pts.call(_$styleOne_279, d[0], trace); } }; @@ -45519,13 +45880,13 @@ var _$style_106 = function style(s, gd) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$dragelement_67 = require('../dragelement'); */; /* removed: var _$drawing_70 = require('../drawing'); */; /* removed: var _$color_45 = require('../color'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; /* removed: var _$handleClick_103 = require('./handle_click'); */; /* removed: var _$constants_99 = require('./constants'); */; @@ -45562,52 +45923,35 @@ var _$draw_101 = function draw(gd) { return; } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); - - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); - - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var firstRender = false; + var legend = _$lib_167.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - var bg = legend.selectAll('rect.bg') - .data([0]); + var clipPath = _$lib_167.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' + var bg = _$lib_167.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); }); bg.call(_$color_45.stroke, opts.bordercolor) .call(_$color_45.fill, opts.bgcolor) .style('stroke-width', opts.borderwidth + 'px'); - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); - - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); - - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); + var scrollBox = _$lib_167.ensureSingle(legend, 'g', 'scrollbox'); - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', + var scrollBar = _$lib_167.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ rx: 20, ry: 3, width: 0, height: 0 }) .call(_$color_45.fill, '#808BA4'); + }); var groups = scrollBox.selectAll('g.groups') .data(legendData); @@ -45618,7 +45962,7 @@ var _$draw_101 = function draw(gd) { groups.exit().remove(); var traces = groups.selectAll('g.traces') - .data(_$lib_166.identity); + .data(_$lib_167.identity); traces.enter().append('g').attr('class', 'traces'); traces.exit().remove(); @@ -45626,7 +45970,7 @@ var _$draw_101 = function draw(gd) { traces.call(_$style_106, gd) .style('opacity', function(d) { var trace = d[0].trace; - if(_$registry_258.traceIs(trace, 'pie')) { + if(_$registry_259.traceIs(trace, 'pie')) { return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; } else { return trace.visible === 'legendonly' ? 0.5 : 1; @@ -45638,7 +45982,6 @@ var _$draw_101 = function draw(gd) { .call(setupTraceToggle, gd); }); - var firstRender = legend.enter().size() !== 0; if(firstRender) { computeLegendDimensions(gd, groups, traces); expandMargin(gd); @@ -45780,7 +46123,7 @@ var _$draw_101 = function draw(gd) { scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); legend.on('wheel', function() { - scrollBoxY = _$lib_166.constrain( + scrollBoxY = _$lib_167.constrain( opts._scrollY + _$d3_8.event.deltaY / scrollBarYMax * scrollBoxYMax, 0, scrollBoxYMax); @@ -45801,7 +46144,7 @@ var _$draw_101 = function draw(gd) { var e = _$d3_8.event.sourceEvent; if(e.buttons === 2 || e.ctrlKey) return; - scrollBoxY = _$lib_166.constrain( + scrollBoxY = _$lib_167.constrain( (e.clientY - eventY0) / scrollRatio + scrollBoxY0, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); @@ -45852,7 +46195,7 @@ var _$draw_101 = function draw(gd) { }, doneFn: function() { if(xf !== undefined && yf !== undefined) { - _$registry_258.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + _$registry_259.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); } }, clickFn: function(numClicks, e) { @@ -45883,14 +46226,11 @@ function drawTexts(g, gd) { var legendItem = g.data()[0][0], fullLayout = gd._fullLayout, trace = legendItem.trace, - isPie = _$registry_258.traceIs(trace, 'pie'), + isPie = _$registry_259.traceIs(trace, 'pie'), traceIndex = trace.index, name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); + var text = _$lib_167.ensureSingle(g, 'text', 'legendtext'); text.attr('text-anchor', 'start') .classed('user-select-none', true) @@ -45898,13 +46238,13 @@ function drawTexts(g, gd) { .text(name); function textLayout(s) { - _$svg_text_utils_187.convertToTspans(s, gd, function() { + _$svg_text_utils_188.convertToTspans(s, gd, function() { computeTextDimensions(g, gd); }); } if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_187.makeEditable, {gd: gd}) + text.call(_$svg_text_utils_188.makeEditable, {gd: gd}) .call(textLayout) .on('edit', function(text) { this.text(text) @@ -45914,24 +46254,14 @@ function drawTexts(g, gd) { if(!this.text()) text = ' \u0020\u0020 '; - var transforms, direction; var fullInput = legendItem.trace._fullInput || {}; var update = {}; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_258.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_258.getTransformIndices(fullInput, 'groupby'); + if(_$registry_259.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_259.getTransformIndices(fullInput, 'groupby'); var index = groupbyIndices[groupbyIndices.length - 1]; - var kcont = _$lib_166.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + var kcont = _$lib_167.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); if(origText === '') { kcont.remove(legendItem.trace._group); @@ -45944,7 +46274,7 @@ function drawTexts(g, gd) { update.name = text; } - return _$registry_258.call('restyle', gd, update, traceIndex); + return _$registry_259.call('restyle', gd, update, traceIndex); }); } else { textLayout(text); @@ -45955,15 +46285,11 @@ function setupTraceToggle(g, gd) { var newMouseDownTime, numClicks = 1; - var traceToggle = g.selectAll('rect') - .data([0]); - - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_45.fill, 'rgba(0,0,0,0)'); - + var traceToggle = _$lib_167.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_45.fill, 'rgba(0,0,0,0)'); + }); traceToggle.on('mousedown', function() { newMouseDownTime = (new Date()).getTime(); @@ -46021,7 +46347,7 @@ function computeTextDimensions(g, gd) { } else { var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_187.lineCount(text); + var textLines = _$svg_text_utils_188.lineCount(text); var textNode = text.node(); height = lineHeight * textLines; @@ -46032,7 +46358,7 @@ function computeTextDimensions(g, gd) { var textY = lineHeight * (0.3 + (1 - textLines) / 2); // TODO: this 40 should go in a constants file (along with other // values related to the legend symbol size) - _$svg_text_utils_187.positionText(text, 40, textY); + _$svg_text_utils_188.positionText(text, 40, textY); } height = Math.max(height, 16) + 3; @@ -46320,7 +46646,7 @@ var _$button_attributes_112 = { /* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; /* removed: var _$attributes_44 = require('../color/attributes'); */; -var __extendFlat_111 = _$extend_158.extendFlat; +var __extendFlat_111 = _$extend_159.extendFlat; /* removed: var _$button_attributes_112 = require('./button_attributes'); */; _$button_attributes_112 = __extendFlat_111(_$button_attributes_112, { @@ -46446,7 +46772,7 @@ var _$constants_113 = { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$attributes_111 = require('./attributes'); */; @@ -46459,7 +46785,7 @@ var _$handleDefaults_114 = function handleDefaults(containerIn, containerOut, la selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(selectorIn, selectorOut, _$attributes_111, attr, dflt); + return _$lib_167.coerce(selectorIn, selectorOut, _$attributes_111, attr, dflt); } var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); @@ -46470,12 +46796,12 @@ var _$handleDefaults_114 = function handleDefaults(containerIn, containerOut, la var posDflt = getPosDflt(containerOut, layout, counterAxes); coerce('x', posDflt[0]); coerce('y', posDflt[1]); - _$lib_166.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_167.noneOrAll(containerIn, containerOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); - _$lib_166.coerceFont(coerce, 'font', layout.font); + _$lib_167.coerceFont(coerce, 'font', layout.font); var bgColor = coerce('bgcolor'); coerce('activecolor', _$color_45.contrast(bgColor, _$constants_113.lightAmount, _$constants_113.darkAmount)); @@ -46490,14 +46816,14 @@ function buttonsDefaults(containerIn, containerOut, calendar) { var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_166.coerce(buttonIn, buttonOut, _$button_attributes_112, attr, dflt); + return _$lib_167.coerce(buttonIn, buttonOut, _$button_attributes_112, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { buttonIn = buttonsIn[i]; buttonOut = {}; - if(!_$lib_166.isPlainObject(buttonIn)) continue; + if(!_$lib_167.isPlainObject(buttonIn)) continue; var step = coerce('step'); if(step !== 'all') { @@ -46602,12 +46928,13 @@ function getXRange(axisLayout, buttonLayout) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$drawing_70 = require('../drawing'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_212 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_213 = require('../../plots/cartesian/axis_ids'); */; /* removed: var _$anchor_utils_97 = require('../legend/anchor_utils'); */; /* removed: var _$alignment_145 = require('../../constants/alignment'); */; @@ -46660,7 +46987,7 @@ var _$draw_115 = function draw(gd) { button.on('click', function() { if(gd._dragged) return; - _$registry_258.call('relayout', gd, update); + _$registry_259.call('relayout', gd, update); }); button.on('mouseover', function() { @@ -46680,7 +47007,7 @@ var _$draw_115 = function draw(gd) { }; function makeSelectorData(gd) { - var axes = _$axis_ids_212.list(gd, 'x', true); + var axes = _$axis_ids_213.list(gd, 'x', true); var data = []; for(var i = 0; i < axes.length; i++) { @@ -46713,13 +47040,9 @@ function isActive(axisLayout, opts, update) { } function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - - rect.attr('shape-rendering', 'crispEdges'); + var rect = _$lib_167.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); rect.attr({ 'rx': _$constants_113.rx, @@ -46739,17 +47062,13 @@ function getFillColor(selectorLayout, d) { function drawButtonText(button, selectorLayout, d, gd) { function textLayout(s) { - _$svg_text_utils_187.convertToTspans(s, gd); + _$svg_text_utils_188.convertToTspans(s, gd); } - var text = button.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - - text.attr('text-anchor', 'middle'); + var text = _$lib_167.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); text.call(_$drawing_70.font, selectorLayout.font) .text(getLabel(d)) @@ -46775,7 +47094,7 @@ function reposition(gd, buttons, opts, axName, selector) { var text = button.select('.selector-text'); var tHeight = opts.font.size * __LINE_SPACING_115; - var hEff = Math.max(tHeight * _$svg_text_utils_187.lineCount(text), 16) + 3; + var hEff = Math.max(tHeight * _$svg_text_utils_188.lineCount(text), 16) + 3; height = Math.max(height, hEff); }); @@ -46787,7 +47106,7 @@ function reposition(gd, buttons, opts, axName, selector) { var tWidth = text.node() && _$drawing_70.bBox(text.node()).width; var tHeight = opts.font.size * __LINE_SPACING_115; - var tLines = _$svg_text_utils_187.lineCount(text); + var tLines = _$svg_text_utils_188.lineCount(text); var wEff = Math.max(tWidth + 10, _$constants_113.minButtonWidth); @@ -46806,7 +47125,7 @@ function reposition(gd, buttons, opts, axName, selector) { height: height }); - _$svg_text_utils_187.positionText(text, wEff / 2, + _$svg_text_utils_188.positionText(text, wEff / 2, height / 2 - ((tLines - 1) * tHeight / 2) + 3); width += wEff + 5; @@ -47017,8 +47336,8 @@ var _$constants_120 = { 'use strict'; -var listAxes = _$axis_ids_212.list; -var __getAutoRange_119 = _$autorange_208.getAutoRange; +var listAxes = _$axis_ids_213.list; +var __getAutoRange_119 = _$autorange_209.getAutoRange; /* removed: var _$constants_120 = require('./constants'); */; var _$calcAutorange_119 = function calcAutorange(gd) { @@ -47090,29 +47409,31 @@ var _$oppaxis_attributes_124 = { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$attributes_118 = require('./attributes'); */; /* removed: var _$oppaxis_attributes_124 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_212 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$axis_ids_213 = require('../../plots/cartesian/axis_ids'); */; var _$handleDefaults_121 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; + 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_166.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; + if(!_$lib_167.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; } - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(containerIn, containerOut, _$attributes_118, attr, dflt); + return _$lib_167.coerce(containerIn, containerOut, _$attributes_118, attr, dflt); } function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_166.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_124, attr, dflt); + return _$lib_167.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_124, attr, dflt); } var visible = coerce('visible'); @@ -47130,12 +47451,12 @@ var _$handleDefaults_121 = function handleDefaults(layoutIn, layoutOut, axName) if(subplots) { var yIds = subplots.cartesian .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_212.name2id(axName); + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_213.name2id(axName); }) .map(function(subplotId) { return subplotId.substr(subplotId.indexOf('y'), subplotId.length); }); - var yNames = _$lib_166.simpleMap(yIds, _$axis_ids_212.id2name); + var yNames = _$lib_167.simpleMap(yIds, _$axis_ids_213.id2name); for(var i = 0; i < yNames.length; i++) { var yName = yNames[i]; @@ -47172,7 +47493,7 @@ var _$handleDefaults_121 = function handleDefaults(layoutIn, layoutOut, axName) 'use strict'; -var _$attributes_207 = { +var _$attributes_208 = { xaxis: { valType: 'subplotid', @@ -47197,150 +47518,24 @@ var _$attributes_207 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -var id2name = _$axis_ids_212.id2name; - - -var _$handleConstraintDefaults_215 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); - - if(containerOut.fixedrange) return; - - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_166.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); - - if(!containerIn.scaleanchor) return; - - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - - var scaleanchor = _$lib_166.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); - - 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, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_166.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.'); - } -}; - -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. - - 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 && !axj.fixedrange) linkableAxes.push(idj); - } - - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[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 +/** + * 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`). * - * 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 + * @param {DOM node or object} gd : graph div object */ -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; - } - } +var _$clearGlCanvases_154 = function clearGlCanvases(gd) { + var fullLayout = gd._fullLayout; - // 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; - } + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); + }); } - thisGroup[scaleanchor] = 1; -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -47353,122 +47548,22 @@ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$autoType_210 = require('./axis_autotype'); */; -var name2id = _$axis_ids_212.name2id; +var FROM_BL = _$alignment_145.FROM_BL; -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored - */ -var _$handleTypeDefaults_233 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); +var _$scaleZoom_226 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; } - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; - } - } + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; }; -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; - - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } - - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; - - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; - - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_258.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; - - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); - - if(trace[calAttr] !== calendar) calendar = undefined; - } - - ax.type = _$autoType_210(boxPositions, calendar); - } - else { - ax.type = _$autoType_210(d0[axLetter] || [d0[axLetter + '0']], calendar); - } -} - -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; - - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; - } - } - } -} - -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_258.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_258.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -47480,1108 +47575,1615 @@ function isBoxWithoutPositionCoords(trace, axLetter) { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$d3_8 = require('d3'); */; +/* removed: var _$tinycolor_26 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_14 = require('has-passive-events'); */; + +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_154 = require('../../lib/clear_gl_canvases'); */; /* removed: var _$color_45 = require('../../components/color'); */; -/* removed: var _$layout_attributes_248 = require('../layout_attributes'); */; +/* removed: var _$drawing_70 = require('../../components/drawing'); */; +/* removed: var _$fx_87 = require('../../components/fx'); */; +/* removed: var _$setCursor_186 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_67 = require('../../components/dragelement'); */; +var __FROM_TL_218 = _$alignment_145.FROM_TL; -/* removed: var _$layout_attributes_221 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_233 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_211 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_215 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_225 = require('./position_defaults'); */; -/* removed: var _$axis_ids_212 = require('./axis_ids'); */; +/* removed: var _$plots_250 = require('../plots'); */; +var doTicks = _$axes_210.doTicks; +var __getFromId_218 = _$axis_ids_213.getFromId; +var __prepSelect_218 = _$select_227.prepSelect; +var __clearSelect_218 = _$select_227.clearSelect; +/* removed: var _$scaleZoom_226 = require('./scale_zoom'); */; -var _$supplyLayoutDefaults_222 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; +/* removed: var _$constants_215 = require('./constants'); */; +var MINDRAG = _$constants_215.MINDRAG; +var MINZOOM = _$constants_215.MINZOOM; - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if(!_$registry_258.traceIs(trace, 'cartesian') && !_$registry_258.traceIs(trace, 'gl2d')) { - continue; - } +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; - var xaName = _$axis_ids_212.id2name(trace.xaxis); - var yaName = _$axis_ids_212.id2name(trace.yaxis); +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_258.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; - // 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) xaCheater[xaName] = 1; - } + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; - // check for default formatting tweaks - if(_$registry_258.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; - if(_$registry_258.traceIs(trace, 'oriented')) { - var positionAxis = trace.orientation === 'h' ? yaName : xaName; - noGrids[positionAxis] = true; + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } } - } - var subplots = layoutOut._subplots; - var xIds = subplots.xaxis; - var yIds = subplots.yaxis; - var xNames = _$lib_166.simpleMap(xIds, _$axis_ids_212.id2name); - var yNames = _$lib_166.simpleMap(yIds, _$axis_ids_212.id2name); - var axNames = xNames.concat(yNames); + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; - // plot_bgcolor only makes sense if there's a (2D) plot! - // TODO: bgcolor for each subplot, to inherit from the main one - var plot_bgcolor = _$color_45.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_166.coerce(layoutIn, layoutOut, _$layout_attributes_248, 'plot_bgcolor'); + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; } - var bgColor = _$color_45.combine(plot_bgcolor, layoutOut.paper_bgcolor); - - var axName, axLetter, axLayoutIn, axLayoutOut; - - function coerce(attr, dflt) { - return _$lib_166.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_221, attr, dflt); - } + recomputeAxisLists(); - function coerce2(attr, dflt) { - return _$lib_166.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_221, attr, dflt); - } + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; } - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - - function getOverlayableAxes(axLetter, axName) { - var list = (axLetter === 'x') ? xNames : yNames; - var out = []; + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; - for(var j = 0; j < list.length; j++) { - var axName2 = list[j]; + recomputeAxisLists(); - if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { - out.push(_$axis_ids_212.name2id(axName2)); + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; } - } - return out; - } + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; - // first pass creates the containers, determines types, and handles most of the settings - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_218(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_218(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; - if(!_$lib_166.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_218(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); - _$handleTypeDefaults_233(axLayoutIn, axLayoutOut, coerce, fullData, axName); + if(numClicks === 2 && !singleEnd) doubleClick(); - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); + if(isMainDrag) { + _$fx_87.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; + if(ax.fixedrange) return; - _$handleAxisDefaults_211(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_8.select(dragger) + .call(_$svg_text_utils_188.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_259.call('relayout', gd, attrStr, v); + } + }); + } + } } + }; - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; + _$dragelement_67.init(dragOptions); - _$handlePositionDefaults_225(axLayoutIn, axLayoutOut, coerce, positioningOptions); + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; - axLayoutOut._input = axLayoutIn; + // collected changes to be made to the plot by relayout at the end + var updates = {}; + + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_26(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; + + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); + + corners = makeCorners(zoomlayer, xs, ys); + + __clearSelect_218(zoomlayer); } - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_258.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_258.getComponentMethod('rangeselector', 'handleDefaults'); + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } - for(i = 0; i < xNames.length; i++) { - axName = xNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - rangeSliderDefaults(layoutIn, layoutOut, axName); + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); - if(axLayoutOut.type === 'date') { - rangeSelectorDefaults( - axLayoutIn, - axLayoutOut, - layoutOut, - yNames, - axLayoutOut.calendar - ); + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); } - coerce('fixedrange'); - } + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; - for(i = 0; i < yNames.length; i++) { - axName = yNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; + } - var anchoredAxis = layoutOut[_$axis_ids_212.id2name(axLayoutOut.anchor)]; + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } - coerce('fixedrange', fixedRangeDflt); + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); } - // Finally, handle scale constraints. 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). + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_215.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - // sets of axes linked by `scaleanchor` along with the scaleratios compounded - // together, populated in handleConstraintDefaults - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); + if(redrawTimer === null) { + __clearSelect_218(zoomlayer); + } - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } - _$handleConstraintDefaults_215(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } -}; + var pc = gd.querySelector('.plotly'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + recomputeAxisLists(); -'use strict'; + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } -/* removed: var _$d3_8 = require('d3'); */; + clearTimeout(redrawTimer); -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$drawing_70 = require('../../components/drawing'); */; -/* removed: var _$axes_209 = require('./axes'); */; -var axisRegex = _$constants_214.attrRegex; + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_167.log('Did not find wheel motion attributes: ', e); + return; + } -var _$transitionAxes_232 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + var axRange = _$lib_167.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); - } - } - if(!update.to) continue; + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; - update.axisName = axisName; - update.length = axis._length; + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } - axes.push(axisLetter); + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; - updates[axisLetter] = update; + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); } + + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); } - return updates; - } + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + dragTail(zoomMode); + }, REDRAWDELAY); - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; + e.preventDefault(); + return; + } - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); + } - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; - } + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); + + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); } - return affectedSubplots; - } + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; + + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_226(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_226(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; } } - redrawObjs(fullLayout.annotations || [], _$registry_258.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_258.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_258.getComponentMethod('images', 'draw'), true); - } - - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); } - function ticksAndAnnotations(xa, ya) { + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { var activeAxIds = [], i; - activeAxIds = [xa._id, ya._id]; + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } + + updates = {}; for(i = 0; i < activeAxIds.length; i++) { - _$axes_209.doTicks(gd, activeAxIds[i], true); + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_218(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; } function redrawObjs(objArray, method, shortCircuit) { for(i = 0; i < objArray.length; i++) { var obji = objArray[i]; - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { method(gd, i); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; } - - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; } } - redrawObjs(fullLayout.annotations || [], _$registry_258.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_258.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_258.getComponentMethod('images', 'draw'), true); - } + // annotations and shapes 'draw' method is slow, + // use the finer-grained 'drawOne' method instead - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + redrawObjs(gd._fullLayout.annotations || [], _$registry_259.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_259.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_259.getComponentMethod('images', 'draw'), true); + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_70.setTranslate, 0, 0) - .call(_$drawing_70.setScale, 1, 1); + function doubleClick() { + if(gd._transitioningWithDuration) return; - subplot.plot - .call(_$drawing_70.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_70.setScale, 1, 1); + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + var ax, i, rangeInitial; - // 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_70.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_70.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_70.hideOutsideRangePoints, subplot); - } + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; + doubleClickConfig = 'autosize'; - var viewBox = []; + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; - } + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; - - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } } - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); + gd.emit('plotly_doubleclick', null); + _$registry_259.call('relayout', gd, attrs); + } - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); - var editX = !!xUpdate; - var editY = !!yUpdate; + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_167.syncOrAsync([ + _$plots_250.previousPromises, + function() { _$registry_259.call('relayout', gd, updates); } + ], gd); + } - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + var i, sp, xa, ya; - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_154(gd); + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_70.setTranslate, clipDx, clipDy) - .call(_$drawing_70.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + if(hasSplom) { + _$registry_259.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; + } - subplot.plot - .call(_$drawing_70.setTranslate, plotDx, plotDy) - .call(_$drawing_70.setScale, xScaleFactor, yScaleFactor) + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_167.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_167.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_70.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_70.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); - } + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); - } + var editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; - axi.range = to.slice(); - } + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } - // Signal that this transition has completed: - onComplete && onComplete(); + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } - return _$registry_258.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } + + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_70.setTranslate, clipDx, clipDy) + .call(_$drawing_70.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_70.setTranslate, plotDx, plotDy) + .call(_$drawing_70.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_70.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_70.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_70.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_70.hideOutsideRangePoints, sp, '.bartext'); + } } - }); + } } - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; - axi.range = axi._r.slice(); + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } + + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_226(ax, scaleFactor); + return getShift(ax, scaleFactor); } + return 0; + } - return _$registry_258.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * __FROM_TL_218[ax.constraintoward || 'middle']; } - var t1, t2, raf; - var easeFn = _$d3_8.ease(transitionOpts.easing); + return dragger; +} - gd._transitionData._interruptCallbacks.push(function() { - window.cancelAnimationFrame(raf); - raf = null; - return transitionInterrupt(); +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_167.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); }); - function doFrame() { - t2 = Date.now(); + dragger3.call(_$setCursor_186, cursor); - var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); - var progress = easeFn(tInterp); + return dragger3.node(); +} - for(var i = 0; i < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_8.select(dragger).call(_$drawing_70.setRect, x, y, w, h); + return dragger; +} - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); - } +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; } + return ''; +} - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - return Promise.resolve(); -}; + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_8.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_8.format('.' + String(dig) + 'g')(initialVal); + } +} -var _$cartesian_220 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; + + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } -'use strict'; + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; -/* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$plots_250 = require('../plots'); */; -var getModuleCalcData = _$get_data_246.getModuleCalcData; + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} -/* removed: var _$axis_ids_212 = require('./axis_ids'); */; -/* removed: var _$constants_214 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_149 = require('../../constants/xmlns_namespaces'); */; +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} -_$cartesian_220.name = 'cartesian'; +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} -_$cartesian_220.attr = ['xaxis', 'yaxis']; +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} -_$cartesian_220.idRoot = ['x', 'y']; +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} -_$cartesian_220.idRegex = _$constants_214.idRegex; +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_45.background, + stroke: _$color_45.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} -_$cartesian_220.attrRegex = _$constants_214.attrRegex; +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} -_$cartesian_220.attributes = _$attributes_207; +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); + } +} -_$cartesian_220.layoutAttributes = _$layout_attributes_221; +function removeZoombox(gd) { + _$d3_8.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} -_$cartesian_220.supplyLayoutDefaults = _$supplyLayoutDefaults_222; +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_167.notifier(_$lib_167._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} -_$cartesian_220.transitionAxes = _$transitionAxes_232; +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} -_$cartesian_220.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_212.id2name(xi)] || {}).anchor; - if(!_$constants_214.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - if(!allY[yi]) { - allY[yi] = 1; - _$lib_166.pushUnique(yList, yi); - } - } - } +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_212.id2name(yi)] || {}).anchor; - if(!_$constants_214.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } - if(!allX[xi]) { - allX[xi] = 1; - _$lib_166.pushUnique(xList, xi); + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } } } - } - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_214.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; } } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } } } - xi = xi ? _$axis_ids_212.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_212.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); } -}; - -_$cartesian_220.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_167.extendFlat(xLinks, yLinks); + yLinks = {}; + } - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_218(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; } - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_218(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; } - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_14) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; + } + else { + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); + } + element._onwheel = handler; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + element.addEventListener(wheelEventName, handler, {passive: false}); + } +} - cdSubplot.push(cd); - } +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; +} - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; - } - } +var _$dragbox_218 = { + makeDragBox: makeDragBox, - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); - } + attachWheelEventHandler: attachWheelEventHandler +}; - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; +var _$graph_interact_219 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); +'use strict'; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); - } -} +/* removed: var _$d3_8 = require('d3'); */; -_$cartesian_220.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; +/* removed: var _$fx_87 = require('../../components/fx'); */; +/* removed: var _$dragelement_67 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_186 = require('../../lib/setcursor'); */; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; +var __makeDragBox_219 = _$dragbox_218.makeDragBox; +var DRAGGERSIZE = _$constants_215.DRAGGERSIZE; +_$graph_interact_219.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_8.select(gd).selectAll('.drag').remove(); + return; } - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + 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'), + 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; + }); - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); - } - } + // 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_219(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); - } + 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) { + _$fx_87.hover(gd, evt, subplot); + } + }; - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + _$fx_87.hover(gd, evt, subplot); - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + // 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; + }; - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } - } - } + /* + * 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; - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + // 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; - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + _$dragelement_67.unhover(gd, evt); + }; - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_219(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_219(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_219(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_219(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); } } - } - - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); + 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_219(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_219(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_219(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_219(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_219(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_219(gd, plotinfo, x0, ya._offset, + DRAGGERSIZE, ya._length * 0.1, 'n', ''); } } - } -}; + }); -_$cartesian_220.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); + // 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(); - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_166.identity); + hoverLayer.onmousemove = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_87.hover(gd, evt, fullLayout._hoversubplot); + }; - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_87.click(gd, evt); + }; - subplotLayers.order(); + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + _$graph_interact_219.updateFx(fullLayout); +}; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; +// 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. +_$graph_interact_219.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_186(fullLayout._draggers, cursor); +}; - // keep ref to plot group - plotinfo.plotgroup = _$d3_8.select(this); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // initialize list of overlay subplots - plotinfo.overlays = []; - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); - } +'use strict'; - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; +/* removed: var _$lib_167 = require('../../lib'); */; +var id2name = _$axis_ids_213.id2name; -_$cartesian_220.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_250.style(gd); -}; -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); +var _$handleConstraintDefaults_216 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); - var subplotData = [], - overlays = []; + if(containerOut.fixedrange) return; - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_167.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' + } + }, 'constraintoward'); - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + if(!containerIn.scaleanchor) return; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); - } - else { - subplotData.push(subplot); + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + + var scaleanchor = _$lib_167.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes } - } + }, 'scaleanchor'); - // main subplots before overlays - subplotData = subplotData.concat(overlays); + 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; - return subplotData; -} + updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_167.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.'); + } +}; -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_214.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_214.layerValue2layerClass[plotinfo.yaxis.layer]; +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); + var thisType = layoutOut[id2name(thisID)].type; + + var i, j, idj, axj; - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); + var linkableAxes = []; + for(j = 0; j < allAxisIds.length; j++) { + idj = allAxisIds[j]; + if(idj === thisID) continue; - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); + axj = layoutOut[id2name(idj)]; + if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); + } - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); + var linkableAxesNoLoops = []; + for(j = 0; j < linkableAxes.length; j++) { + idj = linkableAxes[j]; + if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); + } + return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; + } + } - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + return {linkableAxes: linkableAxes, thisGroup: null}; +} - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); +/* + * 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; - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + if(thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); } else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. + thisGroupIndex = constraintGroups.indexOf(thisGroup); + } - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + var thisGroupKeys = Object.keys(thisGroup); - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + // 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; + } + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + // 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; +} - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); - } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_212.idSort); +'use strict'; - // common attributes for all subplots, overlays or not +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$autoType_211 = require('./axis_autotype'); */; +var name2id = _$axis_ids_213.name2id; - for(var i = 0; i < _$constants_214.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_214.traceLayerClasses[i]); +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_233 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); } - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); -} + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; + } + } +}; -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - var overlayIdsToRemove = {}; + var id = ax._id; + var axLetter = id.charAt(0); - layers.each(function(subplotId) { - var plotgroup = _$d3_8.select(this); + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; - overlayIdsToRemove[subplotId] = true; + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } - // do not remove individual axis s here - // as other subplots may need them - }); + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; - // must remove overlaid subplot trace layers 'manually' + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_259.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; + if(trace[calAttr] !== calendar) calendar = undefined; + } - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); + ax.type = _$autoType_211(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_211(dim.values, calendar); + break; } } } + else { + ax.type = _$autoType_211(d0[axLetter] || [d0[axLetter + '0']], calendar); + } } -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); -} - -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; - layer.enter().append(nodeType) - .classed(className, true); + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } - return layer; + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } + } + } } -_$cartesian_220.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_8.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); - - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} - image.attr({ - xmlns: _$xmlns_namespaces_149.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); - } +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_259.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_259.traceIs(trace._fullInput || {}, 'candlestick'); - canvases.each(canvasToImage); -}; + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -48591,681 +49193,563 @@ _$cartesian_220.toSVG = function(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_8 = require('d3'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$color_45 = require('../../components/color'); */; +/* removed: var _$layout_attributes_248 = require('../layout_attributes'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$plots_250 = require('../../plots/plots'); */; +/* removed: var _$layout_attributes_222 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_233 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_212 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_216 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_225 = require('./position_defaults'); */; +/* removed: var _$axis_ids_213 = require('./axis_ids'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$drawing_70 = require('../drawing'); */; -/* removed: var _$color_45 = require('../color'); */; -/* removed: var _$titles_138 = require('../titles'); */; -/* removed: var _$cartesian_220 = require('../../plots/cartesian'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; +var _$supplyLayoutDefaults_223 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -/* removed: var _$dragelement_67 = require('../dragelement'); */; -/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -/* removed: var _$constants_120 = require('./constants'); */; + if(!_$registry_259.traceIs(trace, 'cartesian') && !_$registry_259.traceIs(trace, 'gl2d')) { + continue; + } -var _$draw_122 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); + var xaName = _$axis_ids_213.id2name(trace.xaxis); + var yaName = _$axis_ids_213.id2name(trace.yaxis); - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ - - function keyFunction(axisOpts) { - return axisOpts._name; - } + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_259.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_120.containerClassName) - .data(rangeSliderData, keyFunction); + // 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) xaCheater[xaName] = 1; + } - rangeSliders.enter().append('g') - .classed(_$constants_120.containerClassName, true) - .attr('pointer-events', 'all'); + // check for default formatting tweaks + if(_$registry_259.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_8.select(this), - opts = axisOpts[_$constants_120.name]; + if(_$registry_259.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; + } + } - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_167.simpleMap(xIds, _$axis_ids_213.id2name); + var yNames = _$lib_167.simpleMap(yIds, _$axis_ids_213.id2name); + var axNames = xNames.concat(yNames); - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); + // plot_bgcolor only makes sense if there's a (2D) plot! + // TODO: bgcolor for each subplot, to inherit from the main one + var plot_bgcolor = _$color_45.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_167.coerce(layoutIn, layoutOut, _$layout_attributes_248, 'plot_bgcolor'); + } - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; + var bgColor = _$color_45.combine(plot_bgcolor, layoutOut.paper_bgcolor); - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_8.select(this), - opts = axisOpts[_$constants_120.name], - oppAxisOpts = fullLayout[_$axes_209.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_209.id2name(axisOpts.anchor)]; + var axName, axLetter, axLayoutIn, axLayoutOut; - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; + function coerce(attr, dflt) { + return _$lib_167.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_222, attr, dflt); + } - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } + function coerce2(attr, dflt) { + return _$lib_167.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_222, attr, dflt); + } - axisOpts.cleanRange('rangeslider.range'); + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - // update range slider dimensions + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; + for(var j = 0; j < list.length; j++) { + var axName2 = list[j]; - var oppBottom = Infinity; - var subplotData = _$axes_209.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_209.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); + if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { + out.push(_$axis_ids_213.name2id(axName2)); + } } - opts._id = _$constants_120.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; - - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); - - var x = Math.round(margin.l + (graphSize.w * domain[0])); + return out; + } - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_120.extraPad - ); + // first pass creates the containers, determines types, and handles most of the settings + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); + if(!_$lib_167.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } - // update data <--> pixel coordinate conversion methods + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; + _$handleTypeDefaults_233(axLayoutIn, axLayoutOut, coerce, fullData, axName); - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] }; - opts._rl = [range0, range1]; + _$handleAxisDefaults_212(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; + if(!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; } - // update inner nodes - - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); - - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + _$handlePositionDefaults_225(axLayoutIn, axLayoutOut, coerce, positioningOptions); - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_138.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' - } - }); - } + axLayoutOut._input = axLayoutIn; + } - // update margins - _$plots_250.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_120.extraPad + opts._offsetShift * 2 - }); - }); -}; + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_259.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_259.getComponentMethod('rangeselector', 'handleDefaults'); -function makeRangeSliderData(fullLayout) { - var axes = _$axes_209.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_120.name, - out = []; + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - if(fullLayout._has('gl2d')) return out; + rangeSliderDefaults(layoutIn, layoutOut, axName); - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); + } - if(ax[name] && ax[name].visible) out.push(ax); + coerce('fixedrange'); } - return out; -} + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_120.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_120.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_120.grabAreaMaxClassName).node(); + var anchoredAxis = layoutOut[_$axis_ids_213.id2name(axLayoutOut.anchor)]; - rangeSlider.on('mousedown', function() { - var event = _$d3_8.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - var dragCover = _$dragelement_67.coverSlip(); + coerce('fixedrange', fixedRangeDflt); + } - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); + // Finally, handle scale constraints. 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). - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; + _$handleConstraintDefaults_216(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); + } +}; - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } +'use strict'; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; +/* removed: var _$d3_8 = require('d3'); */; - _$setCursor_185(_$d3_8.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); - } +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$drawing_70 = require('../../components/drawing'); */; +/* removed: var _$axes_210 = require('./axes'); */; +var axisRegex = _$constants_215.attrRegex; - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_166.removeElement(dragCover); - } - }); -} +var _$transitionAxes_232 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var axes = []; -function setDataRange(rangeSlider, gd, axisOpts, opts) { + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - function clamp(v) { - return axisOpts.l2r(_$lib_166.constrain(v, opts._rl[0], opts._rl[1])); - } + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; - window.requestAnimationFrame(function() { - _$registry_258.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} + update.axisName = axisName; + update.length = axis._length; -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_120.handleWidth / 2; + axes.push(axisLetter); - function clamp(v) { - return _$lib_166.constrain(v, 0, opts._width); - } + updates[axisLetter] = update; + } + } - function clampOppAxis(v) { - return _$lib_166.constrain(v, 0, opts._height); + return updates; } - function clampHandle(v) { - return _$lib_166.constrain(v, -hw2, opts._width + hw2); - } + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - rangeSlider.select('rect.' + _$constants_120.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; - rangeSlider.select('rect.' + _$constants_120.maskMinClassName) - .attr('width', pixelMin); + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; - rangeSlider.select('rect.' + _$constants_120.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; + } - rangeSlider.select('rect.' + _$constants_120.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; - rangeSlider.select('rect.' + _$constants_120.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } + } - rangeSlider.select('rect.' + _$constants_120.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); + return affectedSubplots; } - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; - - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - rangeSlider.select('g.' + _$constants_120.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); - rangeSlider.select('g.' + _$constants_120.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_120.bgClassName) - .data([0]); + redrawObjs(fullLayout.annotations || [], _$registry_259.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_259.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_259.getComponentMethod('images', 'draw'), true); + } - bg.enter().append('rect') - .classed(_$constants_120.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; + } - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; - var offsetShift = -opts._offsetShift; - var lw = _$drawing_70.crispRound(gd, opts.borderwidth); + activeAxIds = [xa._id, ya._id]; - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} + for(i = 0; i < activeAxIds.length; i++) { + _$axes_210.doTicks(gd, activeAxIds[i], true); + } -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); -} + redrawObjs(fullLayout.annotations || [], _$registry_259.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_259.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_259.getComponentMethod('images', 'draw'), true); + } -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_209.getSubplots(gd, axisOpts), - calcData = gd.calcdata; + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - var rangePlots = rangeSlider.selectAll('g.' + _$constants_120.rangePlotClassName) - .data(subplotData, _$lib_166.identity); + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_70.setTranslate, 0, 0) + .call(_$drawing_70.setScale, 1, 1); - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_120.rangePlotClassName + ' ' + id; }) - .call(_$drawing_70.setClipUrl, opts._clipId); + subplot.plot + .call(_$drawing_70.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_70.setScale, 1, 1); - rangePlots.order(); + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); - rangePlots.exit().remove(); - - var mainplotinfo; - - rangePlots.each(function(id, i) { - var plotgroup = _$d3_8.select(this), - isMainPlot = (i === 0); - - var oppAxisOpts = _$axes_209.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; - - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + // 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_70.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_70.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_70.hideOutsideRangePoints, subplot); + } - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - _$plots_250.supplyDefaults(mockFigure); + var viewBox = []; - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya - }; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; } - _$cartesian_220.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); -} - -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; } - } - - return out; -} - -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_120.maskMinClassName) - .data([0]); - maskMin.enter().append('rect') - .classed(_$constants_120.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - maskMin - .attr('height', opts._height) - .call(_$color_45.fill, _$constants_120.maskColor); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - var maskMax = rangeSlider.selectAll('rect.' + _$constants_120.maskMaxClassName) - .data([0]); + var editX = !!xUpdate; + var editY = !!yUpdate; - maskMax.enter().append('rect') - .classed(_$constants_120.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - maskMax - .attr('height', opts._height) - .call(_$color_45.fill, _$constants_120.maskColor); + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_120.maskMinOppAxisClassName) - .data([0]); + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - maskMinOppAxis.enter().append('rect') - .classed(_$constants_120.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_45.fill, _$constants_120.maskOppAxisColor); + subplot.clipRect + .call(_$drawing_70.setTranslate, clipDx, clipDy) + .call(_$drawing_70.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_120.maskMaxOppAxisClassName) - .data([0]); + subplot.plot + .call(_$drawing_70.setTranslate, plotDx, plotDy) + .call(_$drawing_70.setScale, xScaleFactor, yScaleFactor) - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_120.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_70.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_120.maskOppBorder) - .call(_$color_45.fill, _$constants_120.maskOppAxisColor); + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_70.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); } -} - -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; - - var slideBox = rangeSlider.selectAll('rect.' + _$constants_120.slideBoxClassName) - .data([0]); - - slideBox.enter().append('rect') - .classed(_$constants_120.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_120.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); - - slideBox.attr({ - height: opts._height, - fill: _$constants_120.slideBoxFill - }); -} - -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { - - // - - var grabberMin = rangeSlider.selectAll('g.' + _$constants_120.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_120.grabberMinClassName, true); - var grabberMax = rangeSlider.selectAll('g.' + _$constants_120.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_120.grabberMaxClassName, true); + 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 < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; - var handleFixAttrs = { - x: 0, - width: _$constants_120.handleWidth, - rx: _$constants_120.handleRadius, - fill: _$color_45.background, - stroke: _$color_45.defaultLine, - 'stroke-width': _$constants_120.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; + axi.range = to.slice(); + } - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; + // Signal that this transition has completed: + onComplete && onComplete(); - var handleMin = grabberMin.selectAll('rect.' + _$constants_120.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_120.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); + return _$registry_259.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var handleMax = grabberMax.selectAll('rect.' + _$constants_120.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_120.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; - // + axi.range = axi._r.slice(); + } - if(gd._context.staticPlot) return; + return _$registry_259.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var grabAreaFixAttrs = { - width: _$constants_120.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_120.grabAreaFill, - cursor: _$constants_120.grabAreaCursor - }; + var t1, t2, raf; + var easeFn = _$d3_8.ease(transitionOpts.easing); - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_120.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_120.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_120.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_120.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); -} + function doFrame() { + t2 = Date.now(); -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } - if(k.indexOf(_$constants_120.name) !== -1) { - _$plots_250.autoMargin(gd, k); + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); } } -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$attributes_118 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_124 = require('./oppaxis_attributes'); */; - -var _$rangeslider_123 = { - moduleType: 'component', - name: 'rangeslider', - - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_166.extendFlat({}, _$attributes_118, { - yaxis: _$oppaxis_attributes_124 - }) - } - } - }, + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - layoutAttributes: _$attributes_118, - handleDefaults: _$handleDefaults_121, - calcAutorange: _$calcAutorange_119, - draw: _$draw_122 + return Promise.resolve(); }; +var _$cartesian_221 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49274,940 +49758,1182 @@ var _$rangeslider_123 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$attributes_30 = require('../annotations/attributes'); */; -var __scatterLineAttrs_125 = _$attributes_280.line; -var __dash_125 = _$attributes_69.dash; -var __extendFlat_125 = _$extend_158.extendFlat; +/* removed: var _$d3_8 = require('d3'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$plots_250 = require('../plots'); */; +var getModuleCalcData = _$get_data_246.getModuleCalcData; -var _$attributes_125 = { - _isLinkedToArray: 'shape', +/* removed: var _$axis_ids_213 = require('./axis_ids'); */; +/* removed: var _$constants_215 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_149 = require('../../constants/xmlns_namespaces'); */; - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, +var ensureSingle = _$lib_167.ensureSingle; - type: { - valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], - - editType: 'calcIfAutorange+arraydraw', - - }, +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_167.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, +_$cartesian_221.name = 'cartesian'; - xref: __extendFlat_125({}, _$attributes_30.xref, { - - }), - x0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - x1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, +_$cartesian_221.attr = ['xaxis', 'yaxis']; - yref: __extendFlat_125({}, _$attributes_30.yref, { - - }), - y0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - y1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, +_$cartesian_221.idRoot = ['x', 'y']; - path: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, +_$cartesian_221.idRegex = _$constants_215.idRegex; - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - line: { - color: __extendFlat_125({}, __scatterLineAttrs_125.color, {editType: 'arraydraw'}), - width: __extendFlat_125({}, __scatterLineAttrs_125.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_125({}, __dash_125, {editType: 'arraydraw'}), - - editType: 'calcIfAutorange+arraydraw' - }, - fillcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; +_$cartesian_221.attrRegex = _$constants_215.attrRegex; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +_$cartesian_221.attributes = _$attributes_208; +_$cartesian_221.layoutAttributes = _$layout_attributes_222; -'use strict'; +_$cartesian_221.supplyLayoutDefaults = _$supplyLayoutDefaults_223; +_$cartesian_221.transitionAxes = _$transitionAxes_232; -var _$constants_127 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, +_$cartesian_221.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; + } - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} - }, + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_213.id2name(xi)] || {}).anchor; + if(!_$constants_215.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 + if(!allY[yi]) { + allY[yi] = 1; + _$lib_167.pushUnique(yList, yi); + } + } } -}; - -var _$helpers_130 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_213.id2name(yi)] || {}).anchor; + if(!_$constants_215.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); -'use strict'; + if(!allX[xi]) { + allX[xi] = 1; + _$lib_167.pushUnique(xList, xi); + } + } + } -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_215.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } + } + xi = xi ? _$axis_ids_213.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_213.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; -_$helpers_130.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; +_$cartesian_221.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; -_$helpers_130.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; -_$helpers_130.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; + for(i = 0; i < calcdata.length; i++) { + traces.push(i); + } + } -_$helpers_130.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; -_$helpers_130.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; - if(axis) { - var d2r = _$helpers_130.shapePositionToRange(axis); + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - if(axis.type === 'date') dataToPixel = _$helpers_130.decodeDate(dataToPixel); - } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; - } - else { - dataToPixel = function(v) { return gs.l + gs.w * v; }; - } + cdSubplot.push(cd); + } - return dataToPixel; + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } + } + + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + } }; -_$helpers_130.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; - if(axis) { - var r2d = _$helpers_130.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; - } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); } - else { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; + + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; + + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; + + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; + + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); } +} - return pixelToData; -}; +_$cartesian_221.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); + } + } -'use strict'; + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } -/* removed: var _$constants_127 = require('./constants'); */; -/* removed: var _$helpers_130 = require('./helpers'); */; + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } -var _$calcAutorange_126 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_166.filterVisible(fullLayout.shapes); + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } - if(!shapeList.length || !gd._fullData.length) return; + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } + } - var ax, bounds; + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - if(shape.xref !== 'paper') { - ax = _$axes_209.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_127.paramIsX); - if(bounds) _$axes_209.expand(ax, bounds, {ppad: ppad}); + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + } } + } - if(shape.yref !== 'paper') { - ax = _$axes_209.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_127.paramIsY); - if(bounds) _$axes_209.expand(ax, bounds, {ppad: ppad}); + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } } } }; -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; +_$cartesian_221.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_167.identity); - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_127.segmentRE), - i, - segment, - drawnParam, - params, - val; + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); - if(ax.type === 'date') convertVal = _$helpers_130.decodeDate(convertVal); + subplotLayers.order(); - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - params = segments[i].substr(1).match(_$constants_127.paramRE); - if(!params || params.length < drawnParam) continue; + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; - } - if(max >= min) return [min, max]; -} + // keep ref to plot group + plotinfo.plotgroup = _$d3_8.select(this); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // initialize list of overlay subplots + plotinfo.overlays = []; + makeSubplotLayer(gd, plotinfo); -'use strict'; + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); + } -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; -/* removed: var _$attributes_125 = require('./attributes'); */; -/* removed: var _$helpers_130 = require('./helpers'); */; +_$cartesian_221.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_250.style(gd); +}; +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; -var _$handleShapeDefaults_132 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; - function coerce(attr, dflt) { - return _$lib_166.coerce(shapeIn, shapeOut, _$attributes_125, attr, dflt); + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; + } } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + // main subplots before overlays + subplotData = subplotData.concat(overlays); - if(!visible) return shapeOut; + return subplotData; +} - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_215.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_215.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); - // xref, yref - var axRef = _$axes_209.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - if(axRef !== 'paper') { - ax = _$axes_209.getFromId(gdMock, axRef); - r2pos = _$helpers_130.rangeToShapePosition(ax); - pos2r = _$helpers_130.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_166.identity; - } + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); - // x0, x1 (and y0, y1) - _$axes_209.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_209.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); } } - - if(shapeType === 'path') { - coerce('path'); - } else { - _$lib_166.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); - } + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - return shapeOut; -}; + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); -'use strict'; + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); -/* removed: var _$handleArrayContainerDefaults_205 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_132 = require('./shape_defaults'); */; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + } -var _$supplyLayoutDefaults_128 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_132 - }; + // common attributes for all subplots, overlays or not - _$handleArrayContainerDefaults_205(layoutIn, layoutOut, opts); -}; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_213.idSort); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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(var i = 0; i < _$constants_215.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_215.traceLayerClasses[i]); + } + } + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); -'use strict'; + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_45 = require('../color'); */; -/* removed: var _$drawing_70 = require('../drawing'); */; +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; -/* removed: var _$dragelement_67 = require('../dragelement'); */; -/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; + var overlayIdsToRemove = {}; -/* removed: var _$constants_127 = require('./constants'); */; -/* removed: var _$helpers_130 = require('./helpers'); */; + layers.each(function(subplotId) { + var plotgroup = _$d3_8.select(this); + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one + overlayIdsToRemove[subplotId] = true; -var _$draw_129 = { - draw: __draw_129, - drawOne: __drawOne_129 -}; + // do not remove individual axis s here + // as other subplots may need them + }); -function __draw_129(gd) { - var fullLayout = gd._fullLayout; + // must remove overlaid subplot trace layers 'manually' - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_129(gd, i); + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; + + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; + + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } } } - - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); } -function __drawOne_129(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); +} - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; +_$cartesian_221.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_8.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - // this shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); - if(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); - } - else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } + image.attr({ + xmlns: _$xmlns_namespaces_149.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); } - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; + canvases.each(canvasToImage); +}; - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_45.stroke, lineColor) - .call(_$color_45.fill, options.fillcolor) - .call(_$drawing_70.dashLine, options.line.dash, options.line.width); +_$cartesian_221.updateFx = _$graph_interact_219.updateFx; - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - path.call(_$drawing_70.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); +'use strict'; - if(gd._context.edits.shapePosition) __setupDragElement_129(gd, path, options, index); - } -} +/* removed: var _$d3_8 = require('d3'); */; -function __setupDragElement_129(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$plots_250 = require('../../plots/plots'); */; - var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$drawing_70 = require('../drawing'); */; +/* removed: var _$color_45 = require('../color'); */; +/* removed: var _$titles_138 = require('../titles'); */; - var xa, ya, x2p, y2p, p2x, p2y; +/* removed: var _$cartesian_221 = require('../../plots/cartesian'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag - }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; - - _$dragelement_67.init(dragOptions); +/* removed: var _$dragelement_67 = require('../dragelement'); */; +/* removed: var _$setCursor_186 = require('../../lib/setcursor'); */; - shapePath.node().onmousemove = updateDragMode; +/* removed: var _$constants_120 = require('./constants'); */; - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_67.getCursor(x / w, 1 - y / h) : - 'move'; +var _$draw_122 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); - _$setCursor_185(shapePath, cursor); + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; + function keyFunction(axisOpts) { + return axisOpts._name; } - function startDrag(evt) { - // setup conversion functions - xa = _$axes_209.getFromId(gd, shapeOptions.xref); - ya = _$axes_209.getFromId(gd, shapeOptions.yref); + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_120.containerClassName) + .data(rangeSliderData, keyFunction); - x2p = _$helpers_130.getDataToPixel(gd, xa); - y2p = _$helpers_130.getDataToPixel(gd, ya, true); - p2x = _$helpers_130.getPixelToData(gd, xa); - p2y = _$helpers_130.getPixelToData(gd, ya, true); + rangeSliders.enter().append('g') + .classed(_$constants_120.containerClassName, true) + .attr('pointer-events', 'all'); - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; - } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_8.select(this), + opts = axisOpts[_$constants_120.name]; - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); + }); - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); + + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; + + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_8.select(this), + opts = axisOpts[_$constants_120.name], + oppAxisOpts = fullLayout[_$axes_210.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_210.id2name(axisOpts.anchor)]; + + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; + + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + + axisOpts.cleanRange('rangeslider.range'); + + + // update range slider dimensions + + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; + + var oppBottom = Infinity; + var subplotData = _$axes_210.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_210.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - update = {}; + opts._id = _$constants_120.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; - } + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); - function endDrag() { - _$setCursor_185(shapePath); - _$registry_258.call('relayout', gd, update); - } + var x = Math.round(margin.l + (graphSize.w * domain[0])); - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_130.encodeDate(moveX); + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_120.extraPad + ); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_130.encodeDate(moveY); + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } + // update data <--> pixel coordinate conversion methods - shapePath.attr('d', getPathString(gd, shapeOptions)); - } + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_130.encodeDate(moveX); + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; + + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_130.encodeDate(moveY); + opts._rl = [range0, range1]; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; + + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + // update inner nodes - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); - } + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); + + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); + + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_138.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); } - shapePath.attr('d', getPathString(gd, shapeOptions)); - } -} + // update margins + _$plots_250.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_120.extraPad + opts._offsetShift * 2 + }); + }); +}; -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_209.getFromId(gd, options.xref), - ya = _$axes_209.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; +function makeRangeSliderData(fullLayout) { + var axes = _$axes_210.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_120.name, + out = []; - if(xa) { - x2r = _$helpers_130.shapePositionToRange(xa); - x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; - } - else { - x2p = function(v) { return gs.l + gs.w * v; }; - } + if(fullLayout._has('gl2d')) return out; - if(ya) { - y2r = _$helpers_130.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_130.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_130.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); + if(ax[name] && ax[name].visible) out.push(ax); } - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; + return out; } +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_120.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_120.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_120.grabAreaMaxClassName).node(); -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_127.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_127.paramIsX[segmentType], - yParams = _$constants_127.paramIsY[segmentType], - nParams = _$constants_127.numParams[segmentType]; + rangeSlider.on('mousedown', function() { + var event = _$d3_8.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); - var paramString = segment.substr(1).replace(_$constants_127.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; + var dragCover = _$dragelement_67.coverSlip(); - if(paramNumber > nParams) param = 'X'; - return param; - }); + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_166.log('Ignoring extra params in segment ' + segment); - } + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; - return segmentType + paramString; - }); -} + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_127.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_127.paramIsX[segmentType], - yParams = _$constants_127.paramIsY[segmentType], - nParams = _$constants_127.numParams[segmentType]; + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; - var paramString = segment.substr(1).replace(_$constants_127.paramRE, function(param) { - if(paramNumber >= nParams) return param; + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - paramNumber++; + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - return param; - }); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - return segmentType + paramString; + _$setCursor_186(_$d3_8.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); + } + + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_167.removeElement(dragCover); + } }); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setDataRange(rangeSlider, gd, axisOpts, opts) { + function clamp(v) { + return axisOpts.l2r(_$lib_167.constrain(v, opts._rl[0], opts._rl[1])); + } -'use strict'; + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); -/* removed: var _$draw_129 = require('./draw'); */; + window.requestAnimationFrame(function() { + _$registry_259.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); +} -var _$shapes_131 = { - moduleType: 'component', - name: 'shapes', +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_120.handleWidth / 2; - layoutAttributes: _$attributes_125, - supplyLayoutDefaults: _$supplyLayoutDefaults_128, - includeBasePlot: _$makeIncludeComponents_219('shapes'), + function clamp(v) { + return _$lib_167.constrain(v, 0, opts._width); + } - calcAutorange: _$calcAutorange_126, - draw: _$draw_129.draw, - drawOne: _$draw_129.drawOne -}; + function clampOppAxis(v) { + return _$lib_167.constrain(v, 0, opts._height); + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function clampHandle(v) { + return _$lib_167.constrain(v, -hw2, opts._width + hw2); + } + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); -'use strict'; + rangeSlider.select('rect.' + _$constants_120.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); + rangeSlider.select('rect.' + _$constants_120.maskMinClassName) + .attr('width', pixelMin); -var _$constants_134 = { + rangeSlider.select('rect.' + _$constants_120.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - // layout attribute name - name: 'sliders', + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', + rangeSlider.select('rect.' + _$constants_120.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - railHeight: 5, + rangeSlider.select('rect.' + _$constants_120.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', + rangeSlider.select('rect.' + _$constants_120.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); + } - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; - // min item width / height - minWidth: 30, - minHeight: 30, + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - // padding around item text - textPadX: 40, + rangeSlider.select('g.' + _$constants_120.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); - // arrow offset off right edge - arrowOffsetX: 4, + rangeSlider.select('g.' + _$constants_120.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); +} - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_167.ensureSingle(rangeSlider, 'rect', _$constants_120.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, + var offsetShift = -opts._offsetShift; + var lw = _$drawing_70.crispRound(gd, opts.borderwidth); - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw + }); +} - labelPadding: 8, - labelOffset: 0, +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, + var clipPath = _$lib_167.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); +} - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_210.getSubplots(gd, axisOpts), + calcData = gd.calcdata; + + var rangePlots = rangeSlider.selectAll('g.' + _$constants_120.rangePlotClassName) + .data(subplotData, _$lib_167.identity); + + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_120.rangePlotClassName + ' ' + id; }) + .call(_$drawing_70.setClipUrl, opts._clipId); + + rangePlots.order(); + + rangePlots.exit().remove(); + + var mainplotinfo; + + rangePlots.each(function(id, i) { + var plotgroup = _$d3_8.select(this), + isMainPlot = (i === 0); + + var oppAxisOpts = _$axes_210.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; + + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; + + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; + + _$plots_250.supplyDefaults(mockFigure); + + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; + + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; + + if(isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; + } + + _$cartesian_221.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + }); +} + +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; + + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; + + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } + } + + return out; +} + +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_167.ensureSingle(rangeSlider, 'rect', _$constants_120.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); + + maskMin + .attr('height', opts._height) + .call(_$color_45.fill, _$constants_120.maskColor); + + var maskMax = _$lib_167.ensureSingle(rangeSlider, 'rect', _$constants_120.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); + + maskMax + .attr('height', opts._height) + .call(_$color_45.fill, _$constants_120.maskColor); + + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_167.ensureSingle(rangeSlider, 'rect', _$constants_120.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); + + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_45.fill, _$constants_120.maskOppAxisColor); + + var maskMaxOppAxis = _$lib_167.ensureSingle(rangeSlider, 'rect', _$constants_120.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); + + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_120.maskOppBorder) + .call(_$color_45.fill, _$constants_120.maskOppAxisColor); + } +} + +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; + + var slideBox = _$lib_167.ensureSingle(rangeSlider, 'rect', _$constants_120.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_120.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); + + slideBox.attr({ + height: opts._height, + fill: _$constants_120.slideBoxFill + }); +} + +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_167.ensureSingle(rangeSlider, 'g', _$constants_120.grabberMinClassName); + var grabberMax = _$lib_167.ensureSingle(rangeSlider, 'g', _$constants_120.grabberMaxClassName); + + // + var handleFixAttrs = { + x: 0, + width: _$constants_120.handleWidth, + rx: _$constants_120.handleRadius, + fill: _$color_45.background, + stroke: _$color_45.defaultLine, + 'stroke-width': _$constants_120.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_167.ensureSingle(grabberMin, 'rect', _$constants_120.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMin.attr(handleDynamicAttrs); + + var handleMax = _$lib_167.ensureSingle(grabberMax, 'rect', _$constants_120.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); + + // + if(gd._context.staticPlot) return; + + var grabAreaFixAttrs = { + width: _$constants_120.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_120.grabAreaFill, + cursor: _$constants_120.grabAreaCursor + }; + + var grabAreaMin = _$lib_167.ensureSingle(grabberMin, 'rect', _$constants_120.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMin.attr('height', opts._height); + + var grabAreaMax = _$lib_167.ensureSingle(grabberMax, 'rect', _$constants_120.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMax.attr('height', opts._height); +} + +function clearPushMargins(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); + + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + + if(k.indexOf(_$constants_120.name) !== -1) { + _$plots_250.autoMargin(gd, k); + } + } +} /** * Copyright 2012-2018, Plotly, Inc. @@ -50219,39 +50945,28 @@ var _$constants_134 = { 'use strict'; -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_249 = { - t: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - r: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - b: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - l: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$attributes_118 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_124 = require('./oppaxis_attributes'); */; + +var _$rangeslider_123 = { + moduleType: 'component', + name: 'rangeslider', + + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_167.extendFlat({}, _$attributes_118, { + yaxis: _$oppaxis_attributes_124 + }) + } + } }, - editType: 'arraydraw' + + layoutAttributes: _$attributes_118, + handleDefaults: _$handleDefaults_121, + calcAutorange: _$calcAutorange_119, + draw: _$draw_122 }; /** @@ -50264,234 +50979,131 @@ var _$pad_attributes_249 = { 'use strict'; -/* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_249 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_133 = _$extend_158.extendDeepAll; -var __overrideAll_133 = _$edit_types_194.overrideAll; -/* removed: var _$animation_attributes_204 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_134 = require('./constants'); */; - -var stepsAttrs = { - _isLinkedToArray: 'step', - - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], - - }, - label: { - valType: 'string', - - - }, - value: { - valType: 'string', - - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; +/* removed: var _$attributes_30 = require('../annotations/attributes'); */; +var __scatterLineAttrs_125 = _$attributes_281.line; +var __dash_125 = _$attributes_69.dash; +var __extendFlat_125 = _$extend_159.extendFlat; -var _$attributes_133 = __overrideAll_133({ - _isLinkedToArray: 'slider', +var _$attributes_125 = { + _isLinkedToArray: 'shape', visible: { valType: 'boolean', dflt: true, + editType: 'calcIfAutorange+arraydraw', }, - active: { - valType: 'number', + type: { + valType: 'enumerated', + values: ['circle', 'rect', 'path', 'line'], - min: 0, - dflt: 0, + editType: 'calcIfAutorange+arraydraw', }, - steps: stepsAttrs, - - lenmode: { + layer: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: ['below', 'above'], + dflt: 'above', - dflt: 'fraction', + editType: 'arraydraw', }, - len: { - valType: 'number', - min: 0, - dflt: 1, - + + xref: __extendFlat_125({}, _$attributes_30.xref, { - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + editType: 'calcIfAutorange+arraydraw', }, - pad: __extendDeepAll_133({}, _$pad_attributes_249, { - - }, {t: {dflt: 20}}), xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, + x0: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', + x1: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_204.transition.easing.values, - - dflt: 'cubic-in-out', - - } - }, - - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, - - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, - - offset: { - valType: 'number', - dflt: 10, - - - }, - - prefix: { - valType: 'string', - - - }, - - suffix: { - valType: 'string', - - - }, - - font: _$font_attributes_236({ - - }) - }, - - font: _$font_attributes_236({ + yref: __extendFlat_125({}, _$attributes_30.yref, { }), - - activebgcolor: { - valType: 'color', - - dflt: _$constants_134.gripBgActiveColor, - - }, - bgcolor: { - valType: 'color', + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', - dflt: _$constants_134.railBgColor, + editType: 'calcIfAutorange+arraydraw', }, - bordercolor: { - valType: 'color', - dflt: _$constants_134.railBorderColor, + yanchor: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - borderwidth: { - valType: 'number', - min: 0, - dflt: _$constants_134.railBorderWidth, + y0: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_134.tickLength, + y1: { + valType: 'any', + editType: 'calcIfAutorange+arraydraw', }, - tickcolor: { - valType: 'color', - dflt: _$constants_134.tickColor, + + path: { + valType: 'string', + editType: 'calcIfAutorange+arraydraw', }, - tickwidth: { + + opacity: { valType: 'number', min: 0, + max: 1, dflt: 1, + editType: 'arraydraw', }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_134.minorTickLength, + line: { + color: __extendFlat_125({}, __scatterLineAttrs_125.color, {editType: 'arraydraw'}), + width: __extendFlat_125({}, __scatterLineAttrs_125.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_125({}, __dash_125, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + editType: 'arraydraw', - } -}, 'arraydraw', 'from-root'); + }, + editType: 'arraydraw' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -50501,111 +51113,141 @@ var _$attributes_133 = __overrideAll_133({ * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_205 = require('../../plots/array_container_defaults'); */; - -/* removed: var _$attributes_133 = require('./attributes'); */; -/* removed: var _$constants_134 = require('./constants'); */; - -var __name_135 = _$constants_134.name; -var stepAttrs = _$attributes_133.steps; +'use strict'; -var _$slidersDefaults_135 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_135, - handleItemDefaults: sliderDefaults - }; - _$handleArrayContainerDefaults_205(layoutIn, layoutOut, opts); -}; +var _$constants_127 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, -function sliderDefaults(sliderIn, sliderOut, layoutOut) { + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - function coerce(attr, dflt) { - return _$lib_166.coerce(sliderIn, sliderOut, _$attributes_133, attr, dflt); - } - - var steps = stepsDefaults(sliderIn, sliderOut); - - var visible = coerce('visible', steps.length > 0); - if(!visible) return; - - coerce('active'); + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, - coerce('x'); - coerce('y'); - _$lib_166.noneOrAll(sliderIn, sliderOut, ['x', 'y']); + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 + } +}; - coerce('xanchor'); - coerce('yanchor'); +var _$helpers_130 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('len'); - coerce('lenmode'); - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); +'use strict'; - _$lib_166.coerceFont(coerce, 'font', layoutOut.font); +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. - var currentValueIsVisible = coerce('currentvalue.visible'); +_$helpers_130.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; +}; - if(currentValueIsVisible) { - coerce('currentvalue.xanchor'); - coerce('currentvalue.prefix'); - coerce('currentvalue.suffix'); - coerce('currentvalue.offset'); +_$helpers_130.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; +}; - _$lib_166.coerceFont(coerce, 'currentvalue.font', sliderOut.font); - } +_$helpers_130.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); + }; +}; - coerce('transition.duration'); - coerce('transition.easing'); +_$helpers_130.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; +}; - coerce('bgcolor'); - coerce('activebgcolor'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('ticklen'); - coerce('tickwidth'); - coerce('tickcolor'); - coerce('minorticklen'); -} +_$helpers_130.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; -function stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; + if(axis) { + var d2r = _$helpers_130.shapePositionToRange(axis); - var valueIn, valueOut; + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; - function coerce(attr, dflt) { - return _$lib_166.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + if(axis.type === 'date') dataToPixel = _$helpers_130.decodeDate(dataToPixel); + } + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + } + else { + dataToPixel = function(v) { return gs.l + gs.w * v; }; } - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; - - coerce('method'); - - if(!_$lib_166.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; - } + return dataToPixel; +}; - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); +_$helpers_130.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; - valuesOut.push(valueOut); + if(axis) { + var r2d = _$helpers_130.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + } + else { + pixelToData = function(p) { return (p - gs.l) / gs.w; }; } - return valuesOut; -} + return pixelToData; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -50618,624 +51260,729 @@ function stepsDefaults(sliderIn, sliderOut) { 'use strict'; -/* removed: var _$d3_8 = require('d3'); */; - -/* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$color_45 = require('../color'); */; -/* removed: var _$drawing_70 = require('../drawing'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_97 = require('../legend/anchor_utils'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; -/* removed: var _$constants_134 = require('./constants'); */; -/* removed: var _$alignment_145 = require('../../constants/alignment'); */; -var __LINE_SPACING_136 = _$alignment_145.LINE_SPACING; -var __FROM_TL_136 = _$alignment_145.FROM_TL; -var __FROM_BR_136 = _$alignment_145.FROM_BR; +/* removed: var _$constants_127 = require('./constants'); */; +/* removed: var _$helpers_130 = require('./helpers'); */; -var _$draw_136 = function draw(gd) { +var _$calcAutorange_126 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); - - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_134.containerClassName) - .data(sliderData.length > 0 ? [0] : []); + shapeList = _$lib_167.filterVisible(fullLayout.shapes); - sliders.enter().append('g') - .classed(_$constants_134.containerClassName, true) - .style('cursor', 'ew-resize'); + if(!shapeList.length || !gd._fullData.length) return; - sliders.exit().remove(); + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_136(gd); + var ax, bounds; - // Return early if no menus visible: - if(sliderData.length === 0) return; + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_210.getFromId(gd, shape.xref); - var sliderGroups = sliders.selectAll('g.' + _$constants_134.groupClassName) - .data(sliderData, keyFunction); + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_127.paramIsX); - sliderGroups.enter().append('g') - .classed(_$constants_134.groupClassName, true); + if(bounds) _$axes_210.expand(ax, bounds, calcXPaddingOptions(shape)); + } - sliderGroups.exit().each(function(sliderOpts) { - _$d3_8.select(this).remove(); + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_210.getFromId(gd, shape.yref); - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_127.paramIsY); + if(bounds) _$axes_210.expand(ax, bounds, calcYPaddingOptions(shape)); + } + } +}; - _$plots_250.autoMargin(gd, _$constants_134.autoMarginIdRoot + sliderOpts._index); - }); +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); - } +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - var gSlider = _$d3_8.select(this); + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_127.paramIsY : _$constants_127.paramIsX) : + [v0, v1]; + var maxValue = _$lib_167.aggNums(Math.max, null, coords), + minValue = _$lib_167.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - computeLabelSteps(sliderOpts); + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} - _$plots_250.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; - if(opts.active === data.index) return; - if(opts._dragging) return; + var segments = path.match(_$constants_127.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - setActive(gd, gSlider, opts, data.index, false, true); - }); + var params = segment.substr(1).match(_$constants_127.paramRE); + if(!params || params.length < relevantParamIdx) return; - drawSlider(gd, _$d3_8.select(this), sliderOpts); + extractedCoordinates.push(params[relevantParamIdx]); }); -}; -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_134.name], - sliderData = []; + return extractedCoordinates; +} - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); - } +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - return sliderData; -} + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; -} + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_127.segmentRE), + i, + segment, + drawnParam, + params, + val; -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_70.tester.selectAll('g.' + _$constants_134.labelGroupClass) - .data(sliderOpts.steps); + if(ax.type === 'date') convertVal = _$helpers_130.decodeDate(convertVal); - sliderLabels.enter().append('g') - .classed(_$constants_134.labelGroupClass, true); + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_8.select(this); + params = segments[i].substr(1).match(_$constants_127.paramRE); + if(!params || params.length < drawnParam) continue; - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; + } + if(max >= min) return [min, max]; +} - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_70.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); - } - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - sliderLabels.remove(); - var dims = sliderOpts._dims = {}; +'use strict'; - dims.inputAreaWidth = Math.max( - _$constants_134.railWidth, - _$constants_134.gripHeight - ); +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); +/* removed: var _$attributes_125 = require('./attributes'); */; +/* removed: var _$helpers_130 = require('./helpers'); */; - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; + +var _$handleShapeDefaults_132 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; + + function coerce(attr, dflt) { + return _$lib_167.coerce(shapeIn, shapeOut, _$attributes_125, attr, dflt); } - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - var textableInputLength = dims.inputAreaLength - 2 * _$constants_134.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_134.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; + if(!visible) return shapeOut; - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_70.tester.append('g'); + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_70.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_187.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + // xref, yref + var axRef = _$axes_210.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - dummyGroup.remove(); - } + if(axRef !== 'paper') { + ax = _$axes_210.getFromId(gdMock, axRef); + r2pos = _$helpers_130.rangeToShapePosition(ax); + pos2r = _$helpers_130.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_167.identity; + } - dims.height = dims.currentValueTotalHeight + _$constants_134.tickOffset + sliderOpts.ticklen + _$constants_134.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; - var xanchor = 'left'; - if(_$anchor_utils_97.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_97.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); - var yanchor = 'top'; - if(_$anchor_utils_97.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_97.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; - } + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_210.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_210.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + // hack part 2 + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } - _$plots_250.autoMargin(gd, _$constants_134.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_136[xanchor], - r: dims.outerLength * __FROM_BR_136[xanchor], - b: dims.height * __FROM_BR_136[yanchor], - t: dims.height * __FROM_TL_136[yanchor] - }); -} + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; + _$axes_210.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); + + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; + } } - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); + if(shapeType === 'path') { + coerce('path'); + } + else { + _$lib_167.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + } - var dims = sliderOpts._dims; + return shapeOut; +}; - // Position the rectangle: - _$drawing_70.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); -} +'use strict'; -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; +/* removed: var _$handleArrayContainerDefaults_206 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_132 = require('./shape_defaults'); */; - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_134.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; - break; - default: - x0 = _$constants_134.currentValueInset; - textAnchor = 'left'; - } +var _$supplyLayoutDefaults_128 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_132 + }; - text.enter().append('text') - .classed(_$constants_134.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); + _$handleArrayContainerDefaults_206(layoutIn, layoutOut, opts); +}; - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; - } +'use strict'; - text.call(_$drawing_70.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_187.convertToTspans, sliderOpts._gd); +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_45 = require('../color'); */; +/* removed: var _$drawing_70 = require('../drawing'); */; - var lines = _$svg_text_utils_187.lineCount(text); +/* removed: var _$dragelement_67 = require('../dragelement'); */; +/* removed: var _$setCursor_186 = require('../../lib/setcursor'); */; - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_136; +/* removed: var _$constants_127 = require('./constants'); */; +/* removed: var _$helpers_130 = require('./helpers'); */; - _$svg_text_utils_187.positionText(text, x0, y0); - return text; -} - -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_134.gripRectClass) - .data([0]); +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - grip.enter().append('rect') - .classed(_$constants_134.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); +var _$draw_129 = { + draw: __draw_129, + drawOne: __drawOne_129 +}; - grip.attr({ - width: _$constants_134.gripWidth, - height: _$constants_134.gripHeight, - rx: _$constants_134.gripRadius, - ry: _$constants_134.gripRadius, - }) - .call(_$color_45.stroke, sliderOpts.bordercolor) - .call(_$color_45.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); -} +function __draw_129(gd) { + var fullLayout = gd._fullLayout; -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); - text.enter().append('text') - .classed(_$constants_134.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); + } - text.call(_$drawing_70.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_187.convertToTspans, sliderOpts._gd); + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_129(gd, i); + } + } - return text; + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); } -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_134.labelsClass) - .data([0]); - var dims = sliderOpts._dims; +function __drawOne_129(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - labels.enter().append('g') - .classed(_$constants_134.labelsClass, true); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; - var labelItems = labels.selectAll('g.' + _$constants_134.labelGroupClass) - .data(dims.labelSteps); + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; - labelItems.enter().append('g') - .classed(_$constants_134.labelGroupClass, true); + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); + } + } - labelItems.exit().remove(); + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; - labelItems.each(function(d) { - var item = _$d3_8.select(this); + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_45.stroke, lineColor) + .call(_$color_45.fill, options.fillcolor) + .call(_$drawing_70.dashLine, options.line.dash, options.line.width); - item.call(drawLabel, d, sliderOpts); + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - _$drawing_70.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_134.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_136 + - _$constants_134.labelOffset + - dims.currentValueTotalHeight + path.call(_$drawing_70.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null ); - }); + if(gd._context.edits.shapePosition) __setupDragElement_129(gd, path, options, index); + } } -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); +function __setupDragElement_129(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; + + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; + + var xa, ya, x2p, y2p, p2x, p2y; + + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; + + _$dragelement_67.init(dragOptions); + + shapePath.node().onmousemove = updateDragMode; + + function updateDragMode(evt) { + // 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, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_67.getCursor(x / w, 1 - y / h) : + 'move'; + + _$setCursor_186(shapePath, cursor); + + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; } -} -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; + function startDrag(evt) { + // setup conversion functions + xa = _$axes_210.getFromId(gd, shapeOptions.xref); + ya = _$axes_210.getFromId(gd, shapeOptions.yref); - var step = sliderOpts.steps[sliderOpts.active]; + x2p = _$helpers_130.getDataToPixel(gd, xa); + y2p = _$helpers_130.getDataToPixel(gd, ya, true); + p2x = _$helpers_130.getPixelToData(gd, xa); + p2y = _$helpers_130.getPixelToData(gd, ya, true); - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive - }); + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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(_step.execute) { - _$plots_250.executeAPICommand(gd, _step.method, _step.args); - } + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; + } - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.x0'; optE = 'x0'; } - } -} -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_8.select(gd); + // 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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + } - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; - } + update = {}; - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; + } - var grip = sliderGroup.select('.' + _$constants_134.gripRectClass); + function endDrag() { + _$setCursor_186(shapePath); + _$registry_259.call('relayout', gd, update); + } - _$d3_8.event.stopPropagation(); - _$d3_8.event.preventDefault(); - grip.call(_$color_45.fill, sliderOpts.activebgcolor); + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_8.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_130.encodeDate(moveX); + } - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_8.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_130.encodeDate(moveY); + } - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_45.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); -} + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_134.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; + shapePath.attr('d', getPathString(gd, shapeOptions)); + } - tick.enter().append('rect') - .classed(_$constants_134.tickRectClass, true); + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - tick.exit().remove(); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_130.encodeDate(moveX); + } - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' - }); + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_130.encodeDate(moveY); + } - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_8.select(this); + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_45.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + // 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; - _$drawing_70.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_134.tickOffset : _$constants_134.minorTickOffset) + dims.currentValueTotalHeight - ); - }); + // 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } + shapePath.attr('d', getPathString(gd, shapeOptions)); + } } -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_210.getFromId(gd, options.xref), + ya = _$axes_210.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); + if(xa) { + x2r = _$helpers_130.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; + } + else { + x2p = function(v) { return gs.l + gs.w * v; }; } -} -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_134.gripRectClass); + if(ya) { + y2r = _$helpers_130.shapePositionToRange(ya); + y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; + } + else { + y2p = function(v) { return gs.t + gs.h * (1 - v); }; + } - var x = normalizedValueToPosition(sliderOpts, position); + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_130.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_130.decodeDate(y2p); + return convertPath(options, x2p, y2p); + } - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; + 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); + } - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); + 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); } - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_134.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; } -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_134.stepInset + - (dims.inputAreaLength - 2 * _$constants_134.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_134.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_134.stepInset - 2 * dims.inputAreaStart))); -} +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_134.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; - rect.enter().append('rect') - .classed(_$constants_134.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + return pathIn.replace(_$constants_127.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_127.paramIsX[segmentType], + yParams = _$constants_127.paramIsY[segmentType], + nParams = _$constants_127.numParams[segmentType]; - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_134.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_45.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + var paramString = segment.substr(1).replace(_$constants_127.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++; - _$drawing_70.setTranslate(rect, 0, dims.currentValueTotalHeight); -} + if(paramNumber > nParams) param = 'X'; + return param; + }); -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_134.railRectClass) - .data([0]); - var dims = sliderOpts._dims; + if(paramNumber > nParams) { + paramString = paramString.replace(/[\s,]*X.*/, ''); + _$lib_167.log('Ignoring extra params in segment ' + segment); + } - rect.enter().append('rect') - .classed(_$constants_134.railRectClass, true); + return segmentType + paramString; + }); +} - var computedLength = dims.inputAreaLength - _$constants_134.railInset * 2; +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_127.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_127.paramIsX[segmentType], + yParams = _$constants_127.paramIsY[segmentType], + nParams = _$constants_127.numParams[segmentType]; - rect.attr({ - width: computedLength, - height: _$constants_134.railWidth, - rx: _$constants_134.railRadius, - ry: _$constants_134.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_45.stroke, sliderOpts.bordercolor) - .call(_$color_45.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + var paramString = segment.substr(1).replace(_$constants_127.paramRE, function(param) { + if(paramNumber >= nParams) return param; - _$drawing_70.setTranslate(rect, - _$constants_134.railInset, - (dims.inputAreaWidth - _$constants_134.railWidth) * 0.5 + dims.currentValueTotalHeight - ); -} + if(xParams[paramNumber]) param = moveX(param); + else if(yParams[paramNumber]) param = moveY(param); -function __clearPushMargins_136(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + paramNumber++; - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + return param; + }); - if(k.indexOf(_$constants_134.autoMarginIdRoot) !== -1) { - _$plots_250.autoMargin(gd, k); - } - } + return segmentType + paramString; + }); } /** @@ -51246,18 +51993,22 @@ function __clearPushMargins_136(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$constants_134 = require('./constants'); */; +/* removed: var _$draw_129 = require('./draw'); */; -var _$sliders_137 = { +var _$shapes_131 = { moduleType: 'component', - name: _$constants_134.name, + name: 'shapes', - layoutAttributes: _$attributes_133, - supplyLayoutDefaults: _$slidersDefaults_135, + layoutAttributes: _$attributes_125, + supplyLayoutDefaults: _$supplyLayoutDefaults_128, + includeBasePlot: _$makeIncludeComponents_220('shapes'), - draw: _$draw_136 + calcAutorange: _$calcAutorange_126, + draw: _$draw_129.draw, + drawOne: _$draw_129.drawOne }; /** @@ -51268,39 +52019,182 @@ var _$sliders_137 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_44 = require('../color/attributes'); */; -var __extendFlat_139 = _$extend_158.extendFlat; -var __overrideAll_139 = _$edit_types_194.overrideAll; -/* removed: var _$pad_attributes_249 = require('../../plots/pad_attributes'); */; -var buttonsAttrs = { - _isLinkedToArray: 'button', +var _$constants_134 = { - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, + // layout attribute name + name: 'sliders', + + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', + + railHeight: 5, + + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', + + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', + + // min item width / height + minWidth: 30, + minHeight: 30, + + // padding around item text + textPadX: 40, + + // arrow offset off right edge + arrowOffsetX: 4, + + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', + + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, + + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, + + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', + + labelPadding: 8, + labelOffset: 0, + + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, + + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, + + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_249 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_249 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_133 = _$extend_159.extendDeepAll; +var __overrideAll_133 = _$edit_types_195.overrideAll; +/* removed: var _$animation_attributes_205 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_134 = require('./constants'); */; + +var stepsAttrs = { + _isLinkedToArray: 'step', + + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } ], }, label: { valType: 'string', - dflt: '', + + }, + value: { + valType: 'string', + }, execute: { @@ -51311,61 +52205,55 @@ var buttonsAttrs = { } }; -var _$attributes_139 = __overrideAll_139({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], +var _$attributes_133 = __overrideAll_133({ + _isLinkedToArray: 'slider', visible: { valType: 'boolean', + dflt: true, }, - type: { - valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', + active: { + valType: 'number', + min: 0, + dflt: 0, }, - direction: { - valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', - - - }, + steps: stepsAttrs, - active: { - valType: 'integer', + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], - min: -1, - dflt: 0, + dflt: 'fraction', }, - - showactive: { - valType: 'boolean', + len: { + valType: 'number', + min: 0, + dflt: 1, - dflt: true, }, - - buttons: buttonsAttrs, - x: { valType: 'number', min: -2, max: 3, - dflt: -0.05, + dflt: 0, }, + pad: __extendDeepAll_133({}, _$pad_attributes_249, { + + }, {t: {dflt: 20}}), xanchor: { valType: 'enumerated', values: ['auto', 'left', 'center', 'right'], - dflt: 'right', + dflt: 'left', }, @@ -51373,7 +52261,7 @@ var _$attributes_139 = __overrideAll_139({ valType: 'number', min: -2, max: 3, - dflt: 1, + dflt: 0, }, @@ -51385,31 +52273,117 @@ var _$attributes_139 = __overrideAll_139({ }, - pad: __extendFlat_139({}, _$pad_attributes_249, { - - }), + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_205.transition.easing.values, + + dflt: 'cubic-in-out', + + } + }, + + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, + + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, + + offset: { + valType: 'number', + dflt: 10, + + + }, + + prefix: { + valType: 'string', + + + }, + + suffix: { + valType: 'string', + + + }, + + font: _$font_attributes_236({ + + }) + }, font: _$font_attributes_236({ }), + activebgcolor: { + valType: 'color', + + dflt: _$constants_134.gripBgActiveColor, + + }, bgcolor: { valType: 'color', + dflt: _$constants_134.railBgColor, }, bordercolor: { valType: 'color', - dflt: _$attributes_44.borderLine, + dflt: _$constants_134.railBorderColor, }, borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_134.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_134.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_134.tickColor, + + + }, + tickwidth: { valType: 'number', min: 0, dflt: 1, - editType: 'arraydraw', + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_134.minorTickLength, + } }, 'arraydraw', 'from-root'); @@ -51422,171 +52396,110 @@ var _$attributes_139 = __overrideAll_139({ * LICENSE file in the root directory of this source tree. */ - -'use strict'; - - -var _$constants_140 = { - - // 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: '▼' - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_205 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_206 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_139 = require('./attributes'); */; -/* removed: var _$constants_140 = require('./constants'); */; +/* removed: var _$attributes_133 = require('./attributes'); */; +/* removed: var _$constants_134 = require('./constants'); */; -var __name_141 = _$constants_140.name; -var __buttonAttrs_141 = _$attributes_139.buttons; +var __name_135 = _$constants_134.name; +var stepAttrs = _$attributes_133.steps; -var _$updateMenusDefaults_141 = function updateMenusDefaults(layoutIn, layoutOut) { +var _$slidersDefaults_135 = function slidersDefaults(layoutIn, layoutOut) { var opts = { - name: __name_141, - handleItemDefaults: menuDefaults + name: __name_135, + handleItemDefaults: sliderDefaults }; - _$handleArrayContainerDefaults_205(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_206(layoutIn, layoutOut, opts); }; -function menuDefaults(menuIn, menuOut, layoutOut) { +function sliderDefaults(sliderIn, sliderOut, layoutOut) { function coerce(attr, dflt) { - return _$lib_166.coerce(menuIn, menuOut, _$attributes_139, attr, dflt); + return _$lib_167.coerce(sliderIn, sliderOut, _$attributes_133, attr, dflt); } - var buttons = __buttonsDefaults_141(menuIn, menuOut); + var steps = stepsDefaults(sliderIn, sliderOut); - var visible = coerce('visible', buttons.length > 0); + var visible = coerce('visible', steps.length > 0); if(!visible) return; coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); coerce('x'); coerce('y'); - _$lib_166.noneOrAll(menuIn, menuOut, ['x', 'y']); + _$lib_167.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_166.coerceFont(coerce, 'font', layoutOut.font); + _$lib_167.coerceFont(coerce, 'font', layoutOut.font); - coerce('bgcolor', layoutOut.paper_bgcolor); + var currentValueIsVisible = coerce('currentvalue.visible'); + + if(currentValueIsVisible) { + coerce('currentvalue.xanchor'); + coerce('currentvalue.prefix'); + coerce('currentvalue.suffix'); + coerce('currentvalue.offset'); + + _$lib_167.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 __buttonsDefaults_141(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; +function stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; - var buttonIn, buttonOut; + var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_166.coerce(buttonIn, buttonOut, __buttonAttrs_141, attr, dflt); + return _$lib_167.coerce(valueIn, valueOut, stepAttrs, attr, dflt); } - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; coerce('method'); - if(!_$lib_166.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + if(!_$lib_167.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { continue; } coerce('args'); - coerce('label'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); coerce('execute'); - buttonOut._index = i; - buttonsOut.push(buttonOut); + valuesOut.push(valueOut); } - return buttonsOut; + return valuesOut; } /** @@ -51599,1152 +52512,955 @@ function __buttonsDefaults_141(menuIn, menuOut) { 'use strict'; -var _$ScrollBox_144 = ScrollBox; - /* removed: var _$d3_8 = require('d3'); */; +/* removed: var _$plots_250 = require('../../plots/plots'); */; /* removed: var _$color_45 = require('../color'); */; /* removed: var _$drawing_70 = require('../drawing'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_97 = require('../legend/anchor_utils'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$constants_134 = require('./constants'); */; +/* removed: var _$alignment_145 = require('../../constants/alignment'); */; +var __LINE_SPACING_136 = _$alignment_145.LINE_SPACING; +var __FROM_TL_136 = _$alignment_145.FROM_TL; +var __FROM_BR_136 = _$alignment_145.FROM_BR; -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; +var _$draw_136 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_134.containerClassName) + .data(sliderData.length > 0 ? [0] : []); - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + sliders.enter().append('g') + .classed(_$constants_134.containerClassName, true) + .style('cursor', 'ew-resize'); - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); + sliders.exit().remove(); - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_136(gd); -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; + // Return early if no menus visible: + if(sliderData.length === 0) return; -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; + var sliderGroups = sliders.selectAll('g.' + _$constants_134.groupClassName) + .data(sliderData, keyFunction); - // compute position of scrollbox - this.position = position; + sliderGroups.enter().append('g') + .classed(_$constants_134.groupClassName, true); - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; + sliderGroups.exit().each(function(sliderOpts) { + _$d3_8.select(this).remove(); - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; - } + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; + _$plots_250.autoMargin(gd, _$constants_134.autoMarginIdRoot + sliderOpts._index); + }); - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); } - else { - boxT = t; - boxB = boxT + boxH; - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; - } - } + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; + var gSlider = _$d3_8.select(this); - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; + computeLabelSteps(sliderOpts); - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + _$plots_250.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); + if(opts.active === data.index) return; + if(opts._dragging) return; - hbar.exit() - .on('.drag', null) - .remove(); + setActive(gd, gSlider, opts, data.index, false, true); + }); - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_45.fill, ScrollBox.barColor); + drawSlider(gd, _$d3_8.select(this), sliderOpts); + }); +}; - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH - }); +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_134.name], + sliderData = []; - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); } - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; + return sliderData; +} - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; +// This is set in the defaults step: +function keyFunction(opts) { + return opts._index; +} - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_70.tester.selectAll('g.' + _$constants_134.labelGroupClass) + .data(sliderOpts.steps); - vbar.exit() - .on('.drag', null) - .remove(); + sliderLabels.enter().append('g') + .classed(_$constants_134.labelGroupClass, true); - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_45.fill, ScrollBox.barColor); + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_8.select(this); - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH - }); + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_70.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + } + }); - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + sliderLabels.remove(); - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + var dims = sliderOpts._dims = {}; - clipPath.exit().remove(); + dims.inputAreaWidth = Math.max( + _$constants_134.railWidth, + _$constants_134.gripHeight + ); - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; + } - this.container.call(_$drawing_70.setClipUrl, clipId); + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } - else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_70.setClipUrl, null); - delete this._clipRect; - } + var textableInputLength = dims.inputAreaLength - 2 * _$constants_134.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_134.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_8.behavior.drag() - .on('dragstart', function() { - _$d3_8.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_70.tester.append('g'); - var onBarDrag = _$d3_8.behavior.drag() - .on('dragstart', function() { - _$d3_8.event.sourceEvent.preventDefault(); - _$d3_8.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_70.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_188.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); - } + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); - } + dummyGroup.remove(); } - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + dims.height = dims.currentValueTotalHeight + _$constants_134.tickOffset + sliderOpts.ticklen + _$constants_134.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_70.setClipUrl, null); - delete this._clipRect; + var xanchor = 'left'; + if(_$anchor_utils_97.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; } - - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; + if(_$anchor_utils_97.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; } - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; + var yanchor = 'top'; + if(_$anchor_utils_97.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_97.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; } -}; -/** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - if(this.hbar) { - translateX -= _$d3_8.event.dx; - } + _$plots_250.autoMargin(gd, _$constants_134.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_136[xanchor], + r: dims.outerLength * __FROM_BR_136[xanchor], + b: dims.height * __FROM_BR_136[yanchor], + t: dims.height * __FROM_TL_136[yanchor] + }); +} - if(this.vbar) { - translateY -= _$d3_8.event.dy; +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; } - this.setTranslate(translateX, translateY); -}; - -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); - if(this.hbar) { - translateX += _$d3_8.event.deltaY; - } + var dims = sliderOpts._dims; - if(this.vbar) { - translateY += _$d3_8.event.deltaY; - } + // Position the rectangle: + _$drawing_70.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); - this.setTranslate(translateX, translateY); -}; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); -/** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; +} - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_166.constrain(_$d3_8.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; - var translateXMax = this.position.w - this._box.w; + var dims = sliderOpts._dims; + var x0, textAnchor; - translateX = xf * translateXMax; + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_134.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_134.currentValueInset; + textAnchor = 'left'; } - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_166.constrain(_$d3_8.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); + var text = _$lib_167.ensureSingle(sliderGroup, 'text', _$constants_134.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); - var translateYMax = this.position.h - this._box.h; + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; - translateY = yf * translateYMax; + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; } - this.setTranslate(translateX, translateY); -}; + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; + } -/** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; + text.call(_$drawing_70.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_188.convertToTspans, sliderOpts._gd); - translateX = _$lib_166.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_166.constrain(translateY || 0, 0, translateYMax); + var lines = _$svg_text_utils_188.lineCount(text); - this.translateX = translateX; - this.translateY = translateY; - - this.container.call(_$drawing_70.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_136; - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) - }); - } + _$svg_text_utils_188.positionText(text, x0, y0); - if(this.hbar) { - var xf = translateX / translateXMax; + return text; +} - this.hbar.call(_$drawing_70.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); - } +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_167.ensureSingle(sliderGroup, 'rect', _$constants_134.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - if(this.vbar) { - var yf = translateY / translateYMax; + grip.attr({ + width: _$constants_134.gripWidth, + height: _$constants_134.gripHeight, + rx: _$constants_134.gripRadius, + ry: _$constants_134.gripRadius, + }) + .call(_$color_45.stroke, sliderOpts.bordercolor) + .call(_$color_45.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); +} - this.vbar.call(_$drawing_70.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); - } -}; +function drawLabel(item, data, sliderOpts) { + var text = _$lib_167.ensureSingle(item, 'text', _$constants_134.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + text.call(_$drawing_70.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_188.convertToTspans, sliderOpts._gd); + return text; +} -'use strict'; +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_167.ensureSingle(sliderGroup, 'g', _$constants_134.labelsClass); + var dims = sliderOpts._dims; -/* removed: var _$d3_8 = require('d3'); */; + var labelItems = labels.selectAll('g.' + _$constants_134.labelGroupClass) + .data(dims.labelSteps); -/* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$color_45 = require('../color'); */; -/* removed: var _$drawing_70 = require('../drawing'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_97 = require('../legend/anchor_utils'); */; + labelItems.enter().append('g') + .classed(_$constants_134.labelGroupClass, true); -var __LINE_SPACING_142 = _$alignment_145.LINE_SPACING; + labelItems.exit().remove(); -/* removed: var _$constants_140 = require('./constants'); */; -/* removed: var _$ScrollBox_144 = require('./scrollbox'); */; + labelItems.each(function(d) { + var item = _$d3_8.select(this); -var _$draw_142 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); + item.call(drawLabel, d, sliderOpts); - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ + _$drawing_70.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_134.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_136 + + _$constants_134.labelOffset + + dims.currentValueTotalHeight + ); + }); - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_140.containerClassName) - .data(menuData.length > 0 ? [0] : []); +} - menus.enter().append('g') - .classed(_$constants_140.containerClassName, true) - .style('cursor', 'pointer'); +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); - menus.exit().remove(); + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); + } +} - // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_142(gd); +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; - // return early if no update menus are visible - if(menuData.length === 0) return; + var step = sliderOpts.steps[sliderOpts.active]; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_140.headerGroupClassName) - .data(menuData, __keyFunction_142); + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); - headerGroups.enter().append('g') - .classed(_$constants_140.headerGroupClassName, true); + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_140.dropdownButtonGroupClassName) - .data([0]); + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; - gButton.enter().append('g') - .classed(_$constants_140.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + if(_step.execute) { + _$plots_250.executeAPICommand(gd, _step.method, _step.args); + } - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_142(gd, menuOpts); + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } } +} - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_144(gd, gButton, scrollBoxId); - - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_8.select(gd); - gButton - .call(removeAllButtons) - .attr(_$constants_140.menuIndexAttrName, '-1'); + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; } - headerGroups.exit().each(function(menuOpts) { - _$d3_8.select(this).remove(); + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); - gButton - .call(removeAllButtons) - .attr(_$constants_140.menuIndexAttrName, '-1'); + var grip = sliderGroup.select('.' + _$constants_134.gripRectClass); - _$plots_250.autoMargin(gd, _$constants_140.autoMarginIdRoot + menuOpts._index); - }); + _$d3_8.event.stopPropagation(); + _$d3_8.event.preventDefault(); + grip.call(_$color_45.fill, sliderOpts.activebgcolor); - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_8.select(this); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_8.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_250.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_142(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_8.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); }); - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - - // if this menu is active, update the dropdown container - if(__isActive_142(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); - } + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_45.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); }); -}; - -/** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_140.name]; - var menuData = []; +} - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_134.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; - if(item.visible) menuData.push(item); - } + tick.enter().append('rect') + .classed(_$constants_134.tickRectClass, true); - return menuData; -} + tick.exit().remove(); -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_142(menuOpts) { - return menuOpts._index; -} + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); -function isFolded(gButton) { - return +gButton.attr(_$constants_140.menuIndexAttrName) === -1; -} + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_8.select(this); -function __isActive_142(gButton, menuOpts) { - return +gButton.attr(_$constants_140.menuIndexAttrName) === menuOpts._index; -} + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_45.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); -function __setActive_142(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; + _$drawing_70.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_134.tickOffset : _$constants_134.minorTickOffset) + dims.currentValueTotalHeight + ); + }); - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_140.menuIndexAttrName, '-1'); +} - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); } } -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_140.headerClassName) - .data([0]); - var dims = menuOpts._dims; - - header.enter().append('g') - .classed(_$constants_140.headerClassName, true) - .style('pointer-events', 'all'); - - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_140.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; - - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); - - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_140.headerArrowClassName) - .data([0]); +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_134.gripRectClass); - arrow.enter().append('text') - .classed(_$constants_140.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_70.font, menuOpts.font) - .text(_$constants_140.arrowSymbol[menuOpts.direction]); + var x = normalizedValueToPosition(sliderOpts, position); - arrow.attr({ - x: dims.headerWidth - _$constants_140.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_140.textOffsetY + menuOpts.pad.t - }); + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; - header.on('click', function() { - gButton.call(removeAllButtons); + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); + } + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_134.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); +} - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_140.menuIndexAttrName, - __isActive_142(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_134.stepInset + + (dims.inputAreaLength - 2 * _$constants_134.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - }); +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_134.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_134.stepInset - 2 * dims.inputAreaStart))); +} - header.on('mouseover', function() { - header.call(styleOnMouseOver); +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_167.ensureSingle(sliderGroup, 'rect', _$constants_134.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); }); - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_134.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_45.fill, sliderOpts.bgcolor) + .attr('opacity', 0); - // translate header group - _$drawing_70.setTranslate(gHeader, dims.lx, dims.ly); + _$drawing_70.setTranslate(rect, 0, dims.currentValueTotalHeight); } -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); - } - - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; - - var klass = menuOpts.type === 'dropdown' ? _$constants_140.dropdownButtonClassName : _$constants_140.buttonClassName; - - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); - - var enter = buttons.enter().append('g') - .classed(klass, true); - - var exit = buttons.exit(); +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_134.railInset * 2; + var rect = _$lib_167.ensureSingle(sliderGroup, 'rect', _$constants_134.railRectClass); - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + rect.attr({ + width: computedLength, + height: _$constants_134.railWidth, + rx: _$constants_134.railRadius, + ry: _$constants_134.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_45.stroke, sliderOpts.bordercolor) + .call(_$color_45.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); - } + _$drawing_70.setTranslate(rect, + _$constants_134.railInset, + (dims.inputAreaWidth - _$constants_134.railWidth) * 0.5 + dims.currentValueTotalHeight + ); +} - var x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; +function __clearPushMargins_136(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_140.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_140.gapButtonHeader; + if(k.indexOf(_$constants_134.autoMarginIdRoot) !== -1) { + _$plots_250.autoMargin(gd, k); } } +} - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_140.gapButtonHeader + _$constants_140.gapButton - dims.openHeight; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_140.gapButtonHeader + _$constants_140.gapButton - dims.openWidth; - } +'use strict'; - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_140.gapButton, - xPad: _$constants_140.gapButton, - index: 0, - }; +/* removed: var _$constants_134 = require('./constants'); */; - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; +var _$sliders_137 = { + moduleType: 'component', + name: _$constants_134.name, - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_8.select(this); + layoutAttributes: _$attributes_133, + supplyLayoutDefaults: _$slidersDefaults_135, - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); + draw: _$draw_136 +}; - button.on('click', function() { - // skip `dragend` events - if(_$d3_8.event.defaultPrevented) return; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - __setActive_142(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); +'use strict'; - if(buttonOpts.execute) { - _$plots_250.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); - } +/* removed: var _$font_attributes_236 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_44 = require('../color/attributes'); */; +var __extendFlat_139 = _$extend_159.extendFlat; +var __overrideAll_139 = _$edit_types_195.overrideAll; +/* removed: var _$pad_attributes_249 = require('../../plots/pad_attributes'); */; - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); - }); - - button.on('mouseover', function() { - button.call(styleOnMouseOver); - }); - - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); - }); - - buttons.call(styleButtons, menuOpts); +var buttonsAttrs = { + _isLinkedToArray: 'button', - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + } +}; - scrollBoxPosition.direction = menuOpts.direction; - - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); - } - } -} +var _$attributes_139 = __overrideAll_139({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; + visible: { + valType: 'boolean', + + + }, - var active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_140.gapButton; - } - } - else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_140.gapButton; - } - } + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, - scrollBox.enable(position, translateX, translateY); + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } -} + showactive: { + valType: 'boolean', + + dflt: true, + + }, -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; + buttons: buttonsAttrs, - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); - } -} + pad: __extendFlat_139({}, _$pad_attributes_249, { + + }), -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); -} + font: _$font_attributes_236({ + + }), -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_44.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + + } +}, 'arraydraw', 'from-root'); - rect.enter().append('rect') - .classed(_$constants_140.itemRectClassName, true) - .attr({ - rx: _$constants_140.rx, - ry: _$constants_140.ry, - 'shape-rendering': 'crispEdges' - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - rect.call(_$color_45.stroke, menuOpts.bordercolor) - .call(_$color_45.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); -} -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); +'use strict'; - text.enter().append('text') - .classed(_$constants_140.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); - text.call(_$drawing_70.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_187.convertToTspans, gd); -} +var _$constants_140 = { -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; + // layout attribute name + name: 'updatemenus', - buttons.each(function(buttonOpts, i) { - var button = _$d3_8.select(this); + // 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', - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_140.itemRectClassName) - .call(_$color_45.fill, _$constants_140.activeColor); - } - }); -} + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'updatemenu-active-index', -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_140.itemRectClassName) - .call(_$color_45.fill, _$constants_140.hoverColor); -} + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'updatemenu-', -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_140.itemRectClassName) - .call(_$color_45.fill, menuOpts.bgcolor); -} + // options when 'active: -1' + blankHeaderOpts: { label: ' ' }, -// find item dimensions (this mutates menuOpts) -function __findDimensions_142(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; + // min item width / height + minWidth: 30, + minHeight: 30, - var fakeButtons = _$drawing_70.tester.selectAll('g.' + _$constants_140.dropdownButtonClassName) - .data(menuOpts.buttons); + // padding around item text + textPadX: 24, + arrowPadX: 16, - fakeButtons.enter().append('g') - .classed(_$constants_140.dropdownButtonClassName, true); + // item rect radii + rx: 2, + ry: 2, - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + // item text x offset off left edge + textOffsetX: 12, - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_8.select(this); + // item text y offset (w.r.t. middle) + textOffsetY: 3, - button.call(drawItem, menuOpts, buttonOpts, gd); + // arrow offset off right edge + arrowOffsetX: 4, - var text = button.select('.' + _$constants_140.itemTextClassName); + // gap between header and buttons + gapButtonHeader: 5, - // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_70.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_140.textPadX, _$constants_140.minWidth); + // gap between between buttons + gapButton: 2, - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_142; - var tLines = _$svg_text_utils_187.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_140.minHeight) + _$constants_140.textOffsetY; + // color given to active buttons + activeColor: '#F4FAFF', - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); + // color given to hovered buttons + hoverColor: '#F4FAFF', - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; + // symbol for menu open arrow + arrowSymbol: { + left: '◄', + right: '►', + up: '▲', + down: '▼' + } +}; - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_140.gapButton; - dims.openHeight += hEff + _$constants_140.gapButton; - } else { - dims.totalWidth += wEff + _$constants_140.gapButton; - dims.openWidth += wEff + _$constants_140.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; - } - }); +'use strict'; - if(isVertical) { - dims.totalHeight -= _$constants_140.gapButton; - } else { - dims.totalWidth -= _$constants_140.gapButton; - } +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_206 = require('../../plots/array_container_defaults'); */; +/* removed: var _$attributes_139 = require('./attributes'); */; +/* removed: var _$constants_140 = require('./constants'); */; - dims.headerWidth = dims.width1 + _$constants_140.arrowPadX; - dims.headerHeight = dims.height1; +var __name_141 = _$constants_140.name; +var __buttonAttrs_141 = _$attributes_139.buttons; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_140.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_140.arrowPadX; - } - fakeButtons.remove(); +var _$updateMenusDefaults_141 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_141, + handleItemDefaults: menuDefaults + }; - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; + _$handleArrayContainerDefaults_206(layoutIn, layoutOut, opts); +}; - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); +function menuDefaults(menuIn, menuOut, layoutOut) { - var xanchor = 'left'; - if(_$anchor_utils_97.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = 'right'; - } - if(_$anchor_utils_97.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = 'center'; + function coerce(attr, dflt) { + return _$lib_167.coerce(menuIn, menuOut, _$attributes_139, attr, dflt); } - var yanchor = 'top'; - if(_$anchor_utils_97.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = 'bottom'; - } - if(_$anchor_utils_97.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = 'middle'; - } + var buttons = __buttonsDefaults_141(menuIn, menuOut); - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; - _$plots_250.autoMargin(gd, _$constants_140.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); -} + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_140.itemRectClassName); - var text = item.select('.' + _$constants_140.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; + coerce('x'); + coerce('y'); + _$lib_167.noneOrAll(menuIn, menuOut, ['x', 'y']); - _$drawing_70.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + coerce('xanchor'); + coerce('yanchor'); - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight - }); + _$lib_167.coerceFont(coerce, 'font', layoutOut.font); - var tHeight = menuOpts.font.size * __LINE_SPACING_142; - var tLines = _$svg_text_utils_187.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} - _$svg_text_utils_187.positionText(text, _$constants_140.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_140.textOffsetY); +function __buttonsDefaults_141(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; + var buttonIn, buttonOut; + + function coerce(attr, dflt) { + return _$lib_167.coerce(buttonIn, buttonOut, __buttonAttrs_141, attr, dflt); } - posOpts.index++; -} + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_140.dropdownButtonClassName).remove(); -} + coerce('method'); -function __clearPushMargins_142(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); + if(!_$lib_167.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + coerce('args'); + coerce('label'); + coerce('execute'); - if(k.indexOf(_$constants_140.autoMarginIdRoot) !== -1) { - _$plots_250.autoMargin(gd, k); - } + buttonOut._index = i; + buttonsOut.push(buttonOut); } + + return buttonsOut; } /** @@ -52757,279 +53473,463 @@ function __clearPushMargins_142(gd) { 'use strict'; -/* removed: var _$constants_140 = require('./constants'); */; +var _$ScrollBox_144 = ScrollBox; -var _$updatemenus_143 = { - moduleType: 'component', - name: _$constants_140.name, +/* removed: var _$d3_8 = require('d3'); */; - layoutAttributes: _$attributes_139, - supplyLayoutDefaults: _$updateMenusDefaults_141, +/* removed: var _$color_45 = require('../color'); */; +/* removed: var _$drawing_70 = require('../drawing'); */; - draw: _$draw_142 -}; +/* removed: var _$lib_167 = require('../../lib'); */; -var _$mathjax_config_151 = {}; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + * Helper class to setup a scroll box + * + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box + */ +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; -'use strict'; + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection -/* global MathJax:false */ + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); + + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} + +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; /** - * Check and configure MathJax + * If needed, setup a clip path and scrollbars + * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_151.MathJax = true; +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] + // compute position of scrollbox + this.position = position; + + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; + + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; + } + + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; + + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; } - }); + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; + } + } + else { + boxT = t; + boxB = boxT + boxH; - MathJax.Hub.Configured(); -} else { - _$mathjax_config_151.MathJax = false; -} + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; + } + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; -'use strict'; + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; -/* removed: var _$lib_166 = require('../lib'); */; -/* removed: var _$plot_config_199 = require('../plot_api/plot_config'); */; + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); + hbar.exit() + .on('.drag', null) + .remove(); -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_45.fill, ScrollBox.barColor); - for(var i = 0; i < args.length; i++) { - arg = args[i]; + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_166.extendDeep([], arg) : - _$lib_166.extendDeepAll({}, arg); - } - else copy[i] = arg; + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; + } + else { + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - return copy; -} + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); + vbar.exit() + .on('.drag', null) + .remove(); -var __queue_180 = {}; + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_45.fill, ScrollBox.barColor); -// TODO: disable/enable undo and redo buttons appropriately + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_180.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; + } + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; - } - gd.undoQueue.beginSequence = false; + clipPath.exit().remove(); - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); + + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); + + this.container.call(_$drawing_70.setClipUrl, clipId); + + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); + } + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_70.setClipUrl, null); + delete this._clipRect; } - if(gd.undoQueue.queue.length > _$plot_config_199.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_8.behavior.drag() + .on('dragstart', function() { + _$d3_8.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); + + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); + + var onBarDrag = _$d3_8.behavior.drag() + .on('dragstart', function() { + _$d3_8.event.sourceEvent.preventDefault(); + _$d3_8.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); + + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } + + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } } + + // set scrollbox translation + this.setTranslate(translateX, translateY); }; /** - * Begin a sequence of undoQueue changes + * If present, remove clip-path and scrollbars * - * @param gd + * @method */ -__queue_180.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_70.setClipUrl, null); + delete this._clipRect; + } + + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } + + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } }; /** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended + * Handles scroll box drag events * - * @param gd + * @method */ -__queue_180.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX -= _$d3_8.event.dx; + } + + if(this.vbar) { + translateY -= _$d3_8.event.dy; + } + + this.setTranslate(translateX, translateY); }; /** - * Move one step back in the undo queue, and undo the object there. + * Handles scroll box wheel events * - * @param gd + * @method */ -__queue_180.undo = function undo(gd) { - var queueObj, i; +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; + if(this.hbar) { + translateX += _$d3_8.event.deltaY; } - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; - - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_180.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + if(this.vbar) { + translateY += _$d3_8.event.deltaY; } - gd.undoQueue.inSequence = false; - gd.autoplay = false; + + this.setTranslate(translateX, translateY); }; /** - * Redo the current object in the undo, then move forward in the queue. + * Handles scroll bar drag events * - * @param gd + * @method */ -__queue_180.redo = function redo(gd) { - var queueObj, i; +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_167.constrain(_$d3_8.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); + + var translateXMax = this.position.w - this._box.w; + + translateX = xf * translateXMax; } - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_167.constrain(_$d3_8.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_180.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + var translateYMax = this.position.h - this._box.h; + + translateY = yf * translateYMax; } - gd.undoQueue.inSequence = false; - gd.autoplay = false; - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; + this.setTranslate(translateX, translateY); }; /** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. + * Set clip path and scroll bar translate transform * - * @param gd - * @param func - * @param args + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) */ -__queue_180.plotDo = function(gd, func, args) { - gd.autoplay = true; +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); + translateX = _$lib_167.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_167.constrain(translateY || 0, 0, translateYMax); - // call the supplied function - func.apply(null, args); -}; + this.translateX = translateX; + this.translateY = translateY; -var _$queue_180 = __queue_180; + this.container.call(_$drawing_70.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } -'use strict'; + if(this.hbar) { + var xf = translateX / translateXMax; -var _$localeEnUs_191 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' - }, - format: { - date: '%m/%d/%Y' + this.hbar.call(_$drawing_70.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); + } + + if(this.vbar) { + var yf = translateY / translateYMax; + + this.vbar.call(_$drawing_70.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); } }; @@ -53041,876 +53941,727 @@ var _$localeEnUs_191 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$localeEn_192 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' - } -}; +/* removed: var _$d3_8 = require('d3'); */; -var _$fromQuat_12 = fromQuat; +/* removed: var _$plots_250 = require('../../plots/plots'); */; +/* removed: var _$color_45 = require('../color'); */; +/* removed: var _$drawing_70 = require('../drawing'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$svg_text_utils_188 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_97 = require('../legend/anchor_utils'); */; -/** - * 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, +var __LINE_SPACING_142 = _$alignment_145.LINE_SPACING; - 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; +/* removed: var _$constants_140 = require('./constants'); */; +/* removed: var _$ScrollBox_144 = require('./scrollbox'); */; - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; +var _$draw_142 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_140.containerClassName) + .data(menuData.length > 0 ? [0] : []); - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + menus.enter().append('g') + .classed(_$constants_140.containerClassName, true) + .style('cursor', 'pointer'); - return out; -}; -var _$helpers_195 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + menus.exit().remove(); + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_142(gd); -'use strict'; + // return early if no update menus are visible + if(menuData.length === 0) return; -/* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_12 = require('gl-mat4/fromQuat'); */; + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_140.headerGroupClassName) + .data(menuData, __keyFunction_142); -/* removed: var _$registry_258 = require('../registry'); */; -/* removed: var _$lib_166 = require('../lib'); */; -/* removed: var _$plots_250 = require('../plots/plots'); */; -/* removed: var _$axis_ids_212 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_212.cleanId; -var getFromTrace = _$axis_ids_212.getFromTrace; -/* removed: var _$color_45 = require('../components/color'); */; + headerGroups.enter().append('g') + .classed(_$constants_140.headerGroupClassName, true); + // draw dropdown button container + var gButton = _$lib_167.ensureSingle(menus, 'g', _$constants_140.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); -// clear the promise queue if one of them got rejected -_$helpers_195.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_166.log('Clearing previous rejected promises from queue.'); + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_142(gd, menuOpts); } - gd._promises = []; -}; - -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_195.cleanLayout = function(layout) { - var i, j; + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_144(gd, gButton, scrollBoxId); - if(!layout) layout = {}; + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; - } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; + gButton + .call(removeAllButtons) + .attr(_$constants_140.menuIndexAttrName, '-1'); } - var axisAttrRegex = (_$plots_250.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_250.subplotsRegistry.gl3d || {}).attrRegex; + headerGroups.exit().each(function(menuOpts) { + _$d3_8.select(this).remove(); - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; + gButton + .call(removeAllButtons) + .attr(_$constants_140.menuIndexAttrName, '-1'); - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + _$plots_250.autoMargin(gd, _$constants_140.autoMarginIdRoot + menuOpts._index); + }); - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_8.select(this); - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_250.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_142(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + + // if this menu is active, update the dropdown container + if(__isActive_142(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); } - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; - - // clean old Camera coords - var cameraposition = scene.cameraposition; - - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_12([], rotation), - eye = []; + }); +}; - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } +/** + * get only visible menus for display + */ +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_140.name]; + var menuData = []; - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; - delete scene.cameraposition; - } - } + if(item.visible) menuData.push(item); } - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; - - if(!_$lib_166.isPlainObject(ann)) continue; + return menuData; +} - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_142(menuOpts) { + return menuOpts._index; +} - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); - } +function isFolded(gButton) { + return +gButton.attr(_$constants_140.menuIndexAttrName) === -1; +} - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; +function __isActive_142(gButton, menuOpts) { + return +gButton.attr(_$constants_140.menuIndexAttrName) === menuOpts._index; +} - if(!_$lib_166.isPlainObject(shape)) continue; +function __setActive_142(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_140.menuIndexAttrName, '-1'); - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); } } +} - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_167.ensureSingle(gHeader, 'g', _$constants_140.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_45.clean(layout); + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_140.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; - return layout; -}; + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); - } -} + // draw drop arrow at the right edge + var arrow = _$lib_167.ensureSingle(gHeader, 'text', _$constants_140.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_70.font, menuOpts.font) + .text(_$constants_140.arrowSymbol[menuOpts.direction]); + }); -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_195.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); + arrow.attr({ + x: dims.headerWidth - _$constants_140.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_140.textOffsetY + menuOpts.pad.t + }); - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; + header.on('click', function() { + gButton.call(removeAllButtons); - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; - for(i = 0; i < 100; i++) { - newUid = _$lib_166.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_166.randstr(uids); - uids.push(trace.uid); - } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_140.menuIndexAttrName, + __isActive_142(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); - // BACKWARD COMPATIBILITY FIXES + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_45.defaults, - yeColor = trace.error_y.color || - (_$registry_258.traceIs(trace, 'bar') ? _$color_45.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_45.addOpacity( - _$color_45.rgb(yeColor), - _$color_45.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_258.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_195.swapXYData(trace); - } - delete trace.bardir; - } + // translate header group + _$drawing_70.setTranslate(gHeader, dims.lx, dims.ly); +} - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_195.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; - } +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + var klass = menuOpts.type === 'dropdown' ? _$constants_140.dropdownButtonClassName : _$constants_140.buttonClassName; - // scene ids scene1 -> scene - if(_$registry_258.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_250.subplotsRegistry.gl3d.cleanId(trace.scene); - } + var buttons = gButton.selectAll('g.' + klass) + .data(buttonData); - if(!_$registry_258.traceIs(trace, 'pie') && !_$registry_258.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } + var enter = buttons.enter().append('g') + .classed(klass, true); - // fix typo in colorscale definition - if(_$registry_258.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_258.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } + var exit = buttons.exit(); - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_166.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); + } - if(!_$lib_166.isPlainObject(opts)) continue; + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_140.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_140.gapButtonHeader; } + } - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_140.gapButtonHeader + _$constants_140.gapButton - dims.openHeight; + } - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_140.gapButtonHeader + _$constants_140.gapButton - dims.openWidth; + } + + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_140.gapButton, + xPad: _$constants_140.gapButton, + index: 0, + }; - if(!_$lib_166.isPlainObject(transform)) continue; + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_8.select(this); - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; + button.on('click', function() { + // skip `dragend` events + if(_$d3_8.event.defaultPrevented) return; - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); + __setActive_142(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } + if(buttonOpts.execute) { + _$plots_250.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); } - } - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; - } + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_45.clean(trace); - } -}; + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + buttons.call(styleButtons, menuOpts); - return posY + ' ' + posX; -} + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + } -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); + scrollBoxPosition.direction = menuOpts.direction; + + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } } +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; -// swap all the data and data attributes associated with x and y -_$helpers_195.swapXYData = function(trace) { - var i; - _$lib_166.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_166.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_166.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_140.gapButton; } } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_140.gapButton; } - trace.hoverinfo = hoverInfoParts.join('+'); } -}; -// coerce traceIndices input to array of trace indices -_$helpers_195.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_11(traceIndices)) { - return [traceIndices]; + scrollBox.enable(position, translateX, translateY); + + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); + + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); } +} - return traceIndices; -}; +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; -/** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_195.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } - var pLastIsNumber = _$fastIsnumeric_11(pLast); + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); + } +} - // delete item - if(pLastIsNumber && newVal === null) { +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); +} - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_166.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); +function drawItemRect(item, menuOpts) { + var rect = _$lib_167.ensureSingle(item, 'rect', _$constants_140.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_140.rx, + ry: _$constants_140.ry, + 'shape-rendering': 'crispEdges' + }); + }); - // Note that nested property clears null / undefined at end of - // array container, but not within them. - } - // create item - else if(pLastIsNumber && np.get() === undefined) { + rect.call(_$color_45.stroke, menuOpts.bordercolor) + .call(_$color_45.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_167.ensureSingle(item, 'text', _$constants_140.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); - np.set(newVal); - } - // update item - else { + text.call(_$drawing_70.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_188.convertToTspans, gd); +} - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); - } -}; +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + buttons.each(function(buttonOpts, i) { + var button = _$d3_8.select(this); -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_140.itemRectClassName) + .call(_$color_45.fill, _$constants_140.activeColor); + } + }); } -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_195.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; -}; +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_140.itemRectClassName) + .call(_$color_45.fill, _$constants_140.hoverColor); +} -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_195 = ['x', 'y', 'z']; -_$helpers_195.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_195[j]); +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_140.itemRectClassName) + .call(_$color_45.fill, menuOpts.bgcolor); +} - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; +// find item dimensions (this mutates menuOpts) +function __findDimensions_142(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_166.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } -}; + var fakeButtons = _$drawing_70.tester.selectAll('g.' + _$constants_140.dropdownButtonClassName) + .data(menuOpts.buttons); -_$helpers_195.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; - } - } -}; + fakeButtons.enter().append('g') + .classed(_$constants_140.dropdownButtonClassName, true); -var _$manage_arrays_197 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_8.select(this); -'use strict'; + button.call(drawItem, menuOpts, buttonOpts, gd); -/* removed: var _$nestedProperty_174 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_168 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_175 = require('../lib/noop'); */; -/* removed: var _$loggers_171 = require('../lib/loggers'); */; -var sorterAsc = _$search_184.sorterAsc; -/* removed: var _$registry_258 = require('../registry'); */; + var text = button.select('.' + _$constants_140.itemTextClassName); + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_70.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_140.textPadX, _$constants_140.minWidth); -_$manage_arrays_197.containerArrayMatch = _$containerArrayMatch_193; + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_142; + var tLines = _$svg_text_utils_188.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_140.minHeight) + _$constants_140.textOffsetY; -var isAddVal = _$manage_arrays_197.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_168(val); -}; + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); -var isRemoveVal = _$manage_arrays_197.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_197.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_258.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_258.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_258.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_175) || - (draw === _$noop_175), - layout = gd.layout, - fullLayout = gd._fullLayout; + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_171.warn('Full array edits are incompatible with other edits', - componentType); + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_140.gapButton; + dims.openHeight += hEff + _$constants_140.gapButton; + } else { + dims.totalWidth += wEff + _$constants_140.gapButton; + dims.openWidth += wEff + _$constants_140.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; } + }); - var fullVal = edits['']['']; - - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); - else { - _$loggers_171.warn('Unrecognized full array edit value', componentType, fullVal); - return true; - } + if(isVertical) { + dims.totalHeight -= _$constants_140.gapButton; + } else { + dims.totalWidth -= _$constants_140.gapButton; + } - if(replotLater) return false; - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; - } + dims.headerWidth = dims.width1 + _$constants_140.arrowPadX; + dims.headerHeight = dims.height1; - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_174(fullLayout, componentType).get(); - - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_140.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_140.arrowPadX; + } - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + fakeButtons.remove(); - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_171.warn('index out of range', componentType, componentNum); - continue; - } + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_171.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_171.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } + var xanchor = 'left'; + if(_$anchor_utils_97.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_97.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_174(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } + var yanchor = 'top'; + if(_$anchor_utils_97.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_97.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; } - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); + + _$plots_250.autoMargin(gd, _$constants_140.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); +} + +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_140.itemRectClassName); + var text = item.select('.' + _$constants_140.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; + + _$drawing_70.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); + + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); + + var tHeight = menuOpts.font.size * __LINE_SPACING_142; + var tLines = _$svg_text_utils_188.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); + + _$svg_text_utils_188.positionText(text, _$constants_140.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_140.textOffsetY); + + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; } - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); + posOpts.index++; +} - if(replotLater) return false; +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_140.dropdownButtonClassName).remove(); +} - supplyComponentDefaults(layout, fullLayout); +function __clearPushMargins_142(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_175) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + + if(k.indexOf(_$constants_140.autoMarginIdRoot) !== -1) { + _$plots_250.autoMargin(gd, k); } } - else draw(gd); +} - return true; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$constants_140 = require('./constants'); */; + +var _$updatemenus_143 = { + moduleType: 'component', + name: _$constants_140.name, + + layoutAttributes: _$attributes_139, + supplyLayoutDefaults: _$updateMenusDefaults_141, + + draw: _$draw_142 }; -var _$buttons_107 = {}; +var _$mathjax_config_151 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* global MathJax:false */ + +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_151.MathJax = true; + + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); + + MathJax.Hub.Configured(); +} else { + _$mathjax_config_151.MathJax = false; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53922,601 +54673,948 @@ var _$buttons_107 = {}; 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$plots_250 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_212 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; +/* removed: var _$lib_167 = require('../lib'); */; +/* removed: var _$plot_config_200 = require('../plot_api/plot_config'); */; -var ____107 = _$lib_166._; -var modeBarButtons = _$buttons_107 = {}; +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; + + for(var i = 0; i < args.length; i++) { + arg = args[i]; + + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_167.extendDeep([], arg) : + _$lib_167.extendDeepAll({}, arg); + } + else copy[i] = arg; + } + + return copy; +} + + +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- + + +var __queue_181 = {}; + +// TODO: disable/enable undo and redo buttons appropriately /** - * ModeBar buttons configuration + * Add an item to the undoQueue for a graphDiv * - * @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? + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with */ +__queue_181.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; -modeBarButtons.toImage = { - name: 'toImage', - title: function(gd) { return ____107(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; - _$lib_166.notifier(____107(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } - if(_$lib_166.isIE()) { - _$lib_166.notifier(____107(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; - } + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; - _$registry_258.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_166.notifier(____107(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_166.notifier(____107(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); } -}; -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____107(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_250.sendDataToCloud(gd); + if(gd.undoQueue.queue.length > _$plot_config_200.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; } }; -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____107(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_181.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; }; -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____107(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_181.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; }; -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____107(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_181.undo = function undo(gd) { + var queueObj, i; -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____107(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } + + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; + + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_181.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; }; -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____107(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd + */ +__queue_181.redo = function redo(gd) { + var queueObj, i; + + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } + + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_181.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; + + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; }; -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____107(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_181.plotDo = function(gd, func, args) { + gd.autoplay = true; + + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); + + // call the supplied function + func.apply(null, args); }; -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____107(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian +var _$queue_181 = __queue_181; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$localeEnUs_192 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } }; -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____107(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$localeEn_193 = { + 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' + } }; -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____107(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian +var _$fromQuat_12 = 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; }; +var _$helpers_196 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____107(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; - }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian + +'use strict'; + +/* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_12 = require('gl-mat4/fromQuat'); */; + +/* removed: var _$registry_259 = require('../registry'); */; +/* removed: var _$lib_167 = require('../lib'); */; +/* removed: var _$plots_250 = require('../plots/plots'); */; +/* removed: var _$axis_ids_213 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_213.cleanId; +var getFromTrace = _$axis_ids_213.getFromTrace; +/* removed: var _$color_45 = require('../components/color'); */; + + +// clear the promise queue if one of them got rejected +_$helpers_196.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_167.log('Clearing previous rejected promises from queue.'); + } + + gd._promises = []; }; -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 = _$axis_ids_212.list(gd, null, true); - var allSpikesEnabled = 'on'; +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_196.cleanLayout = function(layout) { + var i, j; - var ax, i; + if(!layout) layout = {}; - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } - var axName; + var axisAttrRegex = (_$plots_250.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_250.subplotsRegistry.gl3d || {}).attrRegex; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[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]; - } - if(ax._showSpikeInitial !== undefined) { - aobj[axName + '.showspikes'] = ax._showSpikeInitial; - if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) { - allSpikesEnabled = 'off'; - } - } + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories + + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; + + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; } - else { - var rangeNow = [ - ax.r2l(ax.range[0]), - ax.r2l(ax.range[1]), - ]; + delete ax.autotick; + } + } - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; - aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); - aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); + // clean old Camera coords + var cameraposition = scene.cameraposition; + + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_12([], rotation), + eye = []; + + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; } + + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; + + delete scene.cameraposition; } } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } + + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; + + if(!_$lib_167.isPlainObject(ann)) continue; + + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; } - aobj[astr] = val; + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); + } + + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; + + if(!_$lib_167.isPlainObject(shape)) continue; + + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); } - _$registry_258.call('relayout', gd, aobj); -} + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____107(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d -}; + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____107(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d -}; + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____107(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d -}; + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_45.clean(layout); -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____107(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['z-axis'], - click: handleDrag3d + return layout; }; -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; +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); } +} - // for multi-type subplots - var val2d = (val === 'pan') ? val : 'zoom'; - layoutUpdate.dragmode = val2d; +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_196.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); - _$registry_258.call('relayout', gd, layoutUpdate); -} + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____107(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____107(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d -}; + for(i = 0; i < 100; i++) { + newUid = _$lib_167.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_167.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); -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 = {}; + // BACKWARD COMPATIBILITY FIXES - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } - if(attr === 'resetDefault') { - aobj[key] = null; + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_45.defaults, + yeColor = trace.error_y.color || + (_$registry_259.traceIs(trace, 'bar') ? _$color_45.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_45.addOpacity( + _$color_45.rgb(yeColor), + _$color_45.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_166.extendDeep({}, scene.cameraInitial); + + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_259.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_196.swapXYData(trace); + } + delete trace.bardir; } - } - _$registry_258.call('relayout', gd, aobj); -} + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_196.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + // scene ids scene1 -> scene + if(_$registry_259.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_250.subplotsRegistry.gl3d.cleanId(trace.scene); + } - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; + if(!_$registry_259.traceIs(trace, 'pie') && !_$registry_259.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } - if(val) { - layoutUpdate = _$lib_166.extendDeep(layout, val); - button._previousVal = null; - } - else { - layoutUpdate = { - 'allaxes.showspikes': false - }; + // fix typo in colorscale definition + if(_$registry_259.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_259.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_167.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + if(!_$lib_167.isPlainObject(opts)) continue; - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } + + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; } } } - button._previousVal = _$lib_166.extendDeep({}, currentSpikes); - } + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); - _$registry_258.call('relayout', gd, layoutUpdate); -} + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____107(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____107(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____107(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo -}; + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + if(!_$lib_167.isPlainObject(transform)) continue; -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; + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } - for(var i = 0; i < geoIds.length; i++) { - var id = geoIds[i]; - var geoLayout = fullLayout[id]; + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; - if(attr === 'zoom') { - var scale = geoLayout.projection.scale; - var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; - _$registry_258.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); + + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } } - } -} -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_45.clean(trace); + } }; -function toggleHover(gd) { - var fullLayout = gd._fullLayout; +function cleanFinanceDir(dirContainer) { + if(!_$lib_167.isPlainObject(dirContainer)) return false; - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; - } - else onHoverVal = 'closest'; + var dirName = dirContainer.name; - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; + delete dirContainer.name; + delete dirContainer.showlegend; - _$registry_258.call('relayout', gd, 'hovermode', newHover); + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); } -// buttons when more then one plot types are present +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; } -}; -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____107(gd, 'Reset views'); }, - icon: _$ploticon_2.home, - click: function(gd, ev) { - var button = ev.currentTarget; + var out = name1.substr(0, i); + return out.trim(); +} - button.setAttribute('data-attr', 'zoom'); - button.setAttribute('data-val', 'reset'); - handleCartesian(gd, ev); +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; - button.setAttribute('data-attr', 'resetLastSave'); - handleCamera3d(gd, ev); + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; - resetView(gd, 'geo'); - resetView(gd, 'mapbox'); + return posY + ' ' + posX; +} + +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} + + +// swap all the data and data attributes associated with x and y +_$helpers_196.swapXYData = function(trace) { + var i; + _$lib_167.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_167.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_167.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); } }; -modeBarButtons.toggleSpikelines = { - name: 'toggleSpikelines', - title: function(gd) { return ____107(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; +// coerce traceIndices input to array of trace indices +_$helpers_196.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_11(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); + } - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; + return traceIndices; +}; - var aobj = setSpikelineVisibility(gd); +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * + */ +_$helpers_196.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; + + var pLastIsNumber = _$fastIsnumeric_11(pLast); + + // delete item + if(pLastIsNumber && newVal === null) { + + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_167.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); + + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { + + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; + + np.set(newVal); + } + // update item + else { - _$registry_258.call('relayout', gd, aobj); + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); } }; -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_212.list(gd, null, true); - var aobj = {}; - - var ax, axName; - - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; - } +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; - return aobj; +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); } -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____107(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_196.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); } + return false; }; -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_196 = ['x', 'y', 'z']; +_$helpers_196.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_196[j]); - 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); + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; + } + var typeAttr = axAttr + '.type'; - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_167.nestedProperty(gd.layout, typeAttr).set(null); + } + } } } +}; - _$registry_258.call('relayout', gd, aObj); -} +_$helpers_196.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; + } + } +}; +var _$manage_arrays_198 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -54528,1683 +55626,1380 @@ function resetView(gd, subplotType) { 'use strict'; -/* removed: var _$d3_8 = require('d3'); */; - -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - +/* removed: var _$nestedProperty_175 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_169 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_176 = require('../lib/noop'); */; +/* removed: var _$loggers_172 = require('../lib/loggers'); */; +var sorterAsc = _$search_185.sorterAsc; +/* removed: var _$registry_259 = require('../registry'); */; -/** - * 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); +_$manage_arrays_198.containerArrayMatch = _$containerArrayMatch_194; - this.container.appendChild(this.element); -} +var isAddVal = _$manage_arrays_198.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_169(val); +}; -var __proto_110 = ModeBar.prototype; +var isRemoveVal = _$manage_arrays_198.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; -/** - * Update modeBar (buttons and logo) +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. * - * @param {object} graphInfo primary plot object containing data and layout - * @param {array of arrays} buttons nested arrays of grouped buttons to initialize + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. */ -__proto_110.update = function(graphInfo, buttons) { - this.graphInfo = graphInfo; - - var context = this.graphInfo._context; +_$manage_arrays_198.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_259.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_259.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_259.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_176) || + (draw === _$noop_176), + layout = gd.layout, + fullLayout = gd._fullLayout; - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; - } - else this.element.className = 'modebar'; + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_172.warn('Full array edits are incompatible with other edits', + componentType); + } - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); + var fullVal = edits['']['']; - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_172.warn('Unrecognized full array edit value', componentType, fullVal); + return true; + } - this.updateButtons(buttons); + if(replotLater) return false; - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; - } + supplyComponentDefaults(layout, fullLayout); + draw(gd); + return true; } - this.updateActiveButton(); -}; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_175(fullLayout, componentType).get(); -__proto_110.updateButtons = function(buttons) { - var _this = this; + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - this.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_172.warn('index out of range', componentType, componentNum); + continue; + } - 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'); + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_172.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); } - _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_110.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_110.createButton = function(config) { - var _this = this, - 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); - } + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); + } + else { + _$loggers_172.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); + } - var click = config.click; - if(typeof click !== 'function') { - throw new Error('must provide button \'click\' function in button config'); + if(firstIndexChange === -1) firstIndexChange = componentNum; + } + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_175(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); + } + } } - else { - button.addEventListener('click', function(ev) { - config.click(_this.graphInfo, ev); - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_8.select(button).classed('active', true); - - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - 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 - * @Return {HTMLelement} - */ -__proto_110.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); + if(replotLater) return false; - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; + supplyComponentDefaults(layout, fullLayout); - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_176) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); + } + } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); + } + } + else draw(gd); - return icon; + return true; }; +var _$buttons_107 = {}; /** - * Updates active button with attribute specified in layout - * @Param {object} graphInfo plot object containing data and layout - * @Return {HTMLelement} - */ -__proto_110.updateActiveButton = function(buttonClicked) { - var fullLayout = this.graphInfo._fullLayout, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; +* Copyright 2012-2018, Plotly, Inc. +* All 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.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_8.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_166.nestedProperty(fullLayout, dataAttr).get(); +'use strict'; - button3.classed('active', val === thisval); - } +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$plots_250 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_213 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - }); -}; +var ____107 = _$lib_167._; + +var modeBarButtons = _$buttons_107 = {}; /** - * Check if modeBar is configured as button configuration argument + * ModeBar buttons configuration * - * @Param {object} buttons 2d array of grouped button config objects - * @Return {boolean} + * @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? */ -__proto_110.hasButtons = function(buttons) { - var currentButtons = this.buttons; - if(!currentButtons) return false; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____107(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - if(buttons.length !== currentButtons.length) return false; + _$lib_167.notifier(____107(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - 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; + if(_$lib_167.isIE()) { + _$lib_167.notifier(____107(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; } - } - return true; + _$registry_259.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_167.notifier(____107(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_167.notifier(____107(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); + } }; -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -__proto_110.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____107(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_250.sendDataToCloud(gd); + } +}; - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_166._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____107(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____107(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - group.appendChild(a); - return group; +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____107(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian }; -__proto_110.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); - } +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____107(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - this.hasLogo = false; +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____107(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian }; -__proto_110.destroy = function() { - _$lib_166.removeElement(this.container.querySelector('.modebar')); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____107(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian }; -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____107(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____107(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - if(fullLayout._privateplot) { - _$d3_8.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); - } +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____107(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - return modeBar; -} +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____107(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; -var _$createModeBar_110 = createModeBar; +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 = _$axis_ids_213.list(gd, null, true); + var allSpikesEnabled = 'on'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 ax, i; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; -'use strict'; + var axName; -/* removed: var _$axis_ids_212 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_302 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_258 = require('../../registry'); */; + for(i = 0; i < axList.length; i++) { + ax = axList[i]; -/* removed: var _$createModeBar_110 = require('./modebar'); */; -/* removed: var _$buttons_107 = require('./buttons'); */; + 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]; + } + 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]), + ]; -/** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object - * - */ -var _$manageModeBar_109 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); + } + } } - return; - } - - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); + aobj[astr] = val; } - var customButtons = context.modeBarButtons; - var buttonGroups; - - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } + _$registry_259.call('relayout', gd, aobj); +} - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_110(gd, buttonGroups); +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____107(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d }; -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; - - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____107(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d +}; - var groups = []; +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____107(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - function addGroup(newGroup) { - if(!newGroup.length) return; +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____107(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['z-axis'], + click: handleDrag3d +}; - var out = []; +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 = {}; - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_107[button]); - } + var parts = attr.split('.'); - groups.push(out); + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); - - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; - - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; - } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; - } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; - } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; - } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; - } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; - } + _$registry_259.call('relayout', gd, layoutUpdate); +} - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; - } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); - } +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____107(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____107(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.movie, + click: handleCamera3d +}; - return appendButtonsToGroups(groups, buttonsToAdd); -} +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 = {}; -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_212.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; + if(attr === 'resetDefault') { + aobj[key] = null; + } + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_167.extendDeep({}, scene.cameraInitial); } } - return true; + _$registry_259.call('relayout', gd, aobj); } -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; - - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; - - var trace = fullData[i]; +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - if(!trace._module || !trace._module.selectPoints) continue; +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - if(_$registry_258.traceIs(trace, 'scatter-like')) { - if(_$subtypes_302.hasMarkers(trace) || _$subtypes_302.hasText(trace)) { - selectable = true; - } - } else if(_$registry_258.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; - } + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; - return selectable; -} + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } - } - else groups.push(buttons); + if(val) { + layoutUpdate = _$lib_167.extendDeep(layout, val); + button._previousVal = null; } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - return groups; -} + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - if(typeof button === 'string') { - if(_$buttons_107[button] !== undefined) { - customButtons[i][j] = _$buttons_107[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; } } } - } - - return customButtons; -} - -var _$modebar_108 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -_$modebar_108.manage = _$manageModeBar_109; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; -var FROM_BL = _$alignment_145.FROM_BL; - -var _$scaleZoom_226 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; + button._previousVal = _$lib_167.extendDeep({}, currentSpikes); } - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; + _$registry_259.call('relayout', gd, layoutUpdate); +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____107(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____107(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; -'use strict'; +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____107(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; -/* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$tinycolor_26 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_14 = require('has-passive-events'); */; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$svg_text_utils_187 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_45 = require('../../components/color'); */; -/* removed: var _$drawing_70 = require('../../components/drawing'); */; -/* removed: var _$fx_87 = require('../../components/fx'); */; -/* removed: var _$setCursor_185 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_67 = require('../../components/dragelement'); */; -var __FROM_TL_217 = _$alignment_145.FROM_TL; +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; -/* removed: var _$plots_250 = require('../plots'); */; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; -var doTicks = _$axes_209.doTicks; -var getFromId = _$axis_ids_212.getFromId; -/* removed: var _$prepSelect_227 = require('./select'); */; -/* removed: var _$scaleZoom_226 = require('./scale_zoom'); */; + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; -/* removed: var _$constants_214 = require('./constants'); */; -var MINDRAG = _$constants_214.MINDRAG; -var MINZOOM = _$constants_214.MINZOOM; + _$registry_259.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); + } + } +} +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px +function toggleHover(gd) { var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + } + else onHoverVal = 'closest'; - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$registry_259.call('relayout', gd, 'hovermode', newHover); +} - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); +// buttons when more then one plot types are present - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____107(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____107(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); } +}; - recomputeAxisLists(); +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____107(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - var allFixedRanges = !yActive && !xActive; + var aobj = setSpikelineVisibility(gd); - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; + _$registry_259.call('relayout', gd, aobj); } +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_227(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_213.list(gd, null, true); + var aobj = {}; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + var ax, axName; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - if(numClicks === 2 && !singleEnd) doubleClick(); + return aobj; +} - if(isMainDrag) { - _$fx_87.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____107(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if(ax.fixedrange) return; +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; + 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); - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_8.select(dragger) - .call(_$svg_text_utils_187.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_258.call('relayout', gd, attrStr, v); - } - }); - } - } + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; } - }; - - _$dragelement_67.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + } - // collected changes to be made to the plot by relayout at the end - var updates = {}; + _$registry_259.call('relayout', gd, aObj); +} - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_26(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); +'use strict'; - clearSelect(zoomlayer); - } +/* removed: var _$d3_8 = require('d3'); */; - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +/** + * 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'); - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } + this.update(opts.graphInfo, opts.buttons); - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; + this.container.appendChild(this.element); +} - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } +var __proto_110 = ModeBar.prototype; - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } +/** + * 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_110.update = function(graphInfo, buttons) { + this.graphInfo = graphInfo; - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); + var context = this.graphInfo._context; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; } + else this.element.className = 'modebar'; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_214.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - var pc = gd.querySelector('.plotly'); + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - recomputeAxisLists(); + this.updateButtons(buttons); - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - clearTimeout(redrawTimer); + this.updateActiveButton(); +}; - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_166.log('Did not find wheel motion attributes: ', e); - return; - } +__proto_110.updateButtons = function(buttons) { + var _this = this; - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - var axRange = _$lib_166.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + 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); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +__proto_110.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * Create a new button div and set constant and configurable attributes + * @Param {object} config (see ./buttons.js for more info) + * @Return {HTMLelement} + */ +__proto_110.createButton = function(config) { + var _this = this, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_8.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +__proto_110.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_226(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_226(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * Updates active button with attribute specified in layout + * @Param {object} graphInfo plot object containing data and layout + * @Return {HTMLelement} + */ +__proto_110.updateActiveButton = function(buttonClicked) { + var fullLayout = this.graphInfo._fullLayout, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_8.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_167.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * Check if modeBar is configured as button configuration argument + * + * @Param {object} buttons 2d array of grouped button config objects + * @Return {boolean} + */ +__proto_110.hasButtons = function(buttons) { + var currentButtons = this.buttons; - if((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_258.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_258.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_258.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +__proto_110.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_167._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +__proto_110.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +__proto_110.destroy = function() { + _$lib_167.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_258.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_8.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_166.syncOrAsync([ - _$plots_250.previousPromises, - function() { _$registry_258.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_110 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_213 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_303 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_259 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_226(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_110 = require('./modebar'); */; +/* removed: var _$buttons_107 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_217[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_109 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_166.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_166.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_110(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_70.setTranslate, clipDx, clipDy) - .call(_$drawing_70.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_70.setTranslate, plotDx, plotDy) - .call(_$drawing_70.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_70.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_70.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_70.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_70.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_107[button]); } - } - - return dragger; -} - -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - dragger3.call(_$setCursor_185, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_8.select(dragger).call(_$drawing_70.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_8.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_8.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } + + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); + + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_213.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_45.background, - stroke: _$color_45.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_259.traceIs(trace, 'scatter-like')) { + if(_$subtypes_303.hasMarkers(trace) || _$subtypes_303.hasText(trace)) { + selectable = true; + } + } else if(_$registry_259.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_8.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_166.notifier(_$lib_166._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_107[button] !== undefined) { + customButtons[i][j] = _$buttons_107[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_166.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_14) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_217 = { - makeDragBox: makeDragBox, +var _$modebar_108 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_108.manage = _$manageModeBar_109; +var _$constraints_217 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -56216,152 +57011,202 @@ var _$dragbox_217 = { 'use strict'; -/* removed: var _$d3_8 = require('d3'); */; +var __id2name_217 = _$axis_ids_213.id2name; +/* removed: var _$scaleZoom_226 = require('./scale_zoom'); */; +var __makePadFn_217 = _$autorange_209.makePadFn; -/* removed: var _$fx_87 = require('../../components/fx'); */; -/* removed: var _$dragelement_67 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_147.ALMOST_EQUAL; -/* removed: var _$constants_214 = require('./constants'); */; -var __makeDragBox_218 = _$dragbox_217.makeDragBox; +var __FROM_BL_217 = _$alignment_145.FROM_BL; -var _$initInteractions_218 = function initInteractions(gd) { + +_$constraints_217.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_8.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - 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'), - 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)); + 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_217(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_214.DRAGGERSIZE; + // 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; - // 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_218(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + if(mode === 'range') { + _$scaleZoom_226(ax, factor); + } + else { + // mode === 'domain' - 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) { - _$fx_87.hover(gd, evt, subplot); + 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_226(ax, factor); + continue; } - }; - _$fx_87.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_217(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_67.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_218(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_218(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_218(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_218(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_218(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_218(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_218(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_218(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_218(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_218(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_217.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_87.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_87.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_217[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_201 = {}; +var _$subroutines_202 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -56373,21 +57218,27 @@ var _$subroutines_201 = {}; 'use strict'; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$registry_258 = require('../registry'); */; +/* removed: var _$registry_259 = require('../registry'); */; /* removed: var _$plots_250 = require('../plots/plots'); */; -/* removed: var _$lib_166 = require('../lib'); */; + +/* removed: var _$lib_167 = require('../lib'); */; +/* removed: var _$clearGlCanvases_154 = require('../lib/clear_gl_canvases'); */; /* removed: var _$color_45 = require('../components/color'); */; /* removed: var _$drawing_70 = require('../components/drawing'); */; /* removed: var _$titles_138 = require('../components/titles'); */; /* removed: var _$modebar_108 = require('../components/modebar'); */; -/* removed: var _$axes_209 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_218 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_214 = require('../plots/cartesian/constants'); */; + +/* removed: var _$axes_210 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_215 = require('../plots/cartesian/constants'); */; /* removed: var _$alignment_145 = require('../constants/alignment'); */; +/* removed: var _$constraints_217 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_217.enforce; +var cleanAxisConstraints = _$constraints_217.clean; +var __doAutoRange_202 = _$autorange_209.doAutoRange; -_$subroutines_201.layoutStyles = function(gd) { - return _$lib_166.syncOrAsync([_$plots_250.doAutoMargin, _$subroutines_201.lsInner], gd); +_$subroutines_202.layoutStyles = function(gd) { + return _$lib_167.syncOrAsync([_$plots_250.doAutoMargin, _$subroutines_202.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -56405,11 +57256,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_201.lsInner = function(gd) { +_$subroutines_202.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_209.list(gd); + var axList = _$axes_210.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -56488,31 +57339,17 @@ _$subroutines_201.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_167.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -56544,23 +57381,17 @@ _$subroutines_201.lsInner = function(gd) { } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_167.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); _$drawing_70.setTranslate(plotinfo.plot, xa._offset, ya._offset); @@ -56569,16 +57400,16 @@ _$subroutines_201.lsInner = function(gd) { if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } _$drawing_70.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_214.traceLayerClasses.length; i++) { - var layer = _$constants_214.traceLayerClasses[i]; + for(i = 0; i < _$constants_215.traceLayerClasses.length; i++) { + var layer = _$constants_215.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { plotinfo.plot.selectAll('g.' + layer).call(_$drawing_70.setClipUrl, layerClipId); } @@ -56702,8 +57533,8 @@ _$subroutines_201.lsInner = function(gd) { plotinfo.ylines.attr('d', yPath); }); - _$axes_209.makeClipPaths(gd); - _$subroutines_201.drawMainTitle(gd); + _$axes_210.makeClipPaths(gd); + _$subroutines_202.drawMainTitle(gd); _$modebar_108.manage(gd); return gd._promises.length && Promise.all(gd._promises); @@ -56760,7 +57591,7 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_201.drawMainTitle = function(gd) { +_$subroutines_202.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; _$titles_138.draw(gd, 'gtitle', { @@ -56779,7 +57610,7 @@ _$subroutines_201.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_201.doTraceStyle = function(gd) { +_$subroutines_202.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -56789,12 +57620,12 @@ _$subroutines_201.doTraceStyle = function(gd) { } _$plots_250.style(gd); - _$registry_258.getComponentMethod('legend', 'draw')(gd); + _$registry_259.getComponentMethod('legend', 'draw')(gd); return _$plots_250.previousPromises(gd); }; -_$subroutines_201.doColorBars = function(gd) { +_$subroutines_202.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -56802,7 +57633,7 @@ _$subroutines_201.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_258.traceIs(trace, 'contour')) { + if(_$registry_259.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -56811,7 +57642,7 @@ _$subroutines_201.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_258.traceIs(trace, 'markerColorscale')) { + if(_$registry_259.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); @@ -56822,28 +57653,33 @@ _$subroutines_201.doColorBars = function(gd) { }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_201.layoutReplot = function(gd) { +_$subroutines_202.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_258.call('plot', gd, '', layout); + return _$registry_259.call('plot', gd, '', layout); }; -_$subroutines_201.doLegend = function(gd) { - _$registry_258.getComponentMethod('legend', 'draw')(gd); +_$subroutines_202.doLegend = function(gd) { + _$registry_259.getComponentMethod('legend', 'draw')(gd); return _$plots_250.previousPromises(gd); }; -_$subroutines_201.doTicksRelayout = function(gd) { - _$axes_209.doTicks(gd, 'redraw'); - _$subroutines_201.drawMainTitle(gd); +_$subroutines_202.doTicksRelayout = function(gd) { + _$axes_210.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_154(gd); + _$registry_259.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_202.drawMainTitle(gd); return _$plots_250.previousPromises(gd); }; -_$subroutines_201.doModeBar = function(gd) { +_$subroutines_202.doModeBar = function(gd) { var fullLayout = gd._fullLayout; _$modebar_108.manage(gd); - _$initInteractions_218(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; @@ -56853,7 +57689,7 @@ _$subroutines_201.doModeBar = function(gd) { return _$plots_250.previousPromises(gd); }; -_$subroutines_201.doCamera = function(gd) { +_$subroutines_202.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -56865,212 +57701,86 @@ _$subroutines_201.doCamera = function(gd) { } }; -var _$constraints_216 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_216 = _$axis_ids_212.id2name; -/* removed: var _$scaleZoom_226 = require('./scale_zoom'); */; -var __makePadFn_216 = _$autorange_208.makePadFn; - -var ALMOST_EQUAL = _$numerical_147.ALMOST_EQUAL; - -var __FROM_BL_216 = _$alignment_145.FROM_BL; - - -_$constraints_216.enforce = function enforceAxisConstraints(gd) { +_$subroutines_202.drawData = function(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_216(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_259.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_226(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_226(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_154(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_216(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_250.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_259.getComponentMethod('shapes', 'draw')(gd); + _$registry_259.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_250.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_202.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_210.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_202(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_216.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_216[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_202.finalDraw = function(gd) { + _$registry_259.getComponentMethod('shapes', 'draw')(gd); + _$registry_259.getComponentMethod('images', 'draw')(gd); + _$registry_259.getComponentMethod('annotations', 'draw')(gd); + _$registry_259.getComponentMethod('legend', 'draw')(gd); + _$registry_259.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_259.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_259.getComponentMethod('sliders', 'draw')(gd); + _$registry_259.getComponentMethod('updatemenus', 'draw')(gd); +}; var _$micropolar_254 = {}; /** @@ -57082,8 +57792,8 @@ var _$micropolar_254 = {}; */ /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../../lib'); */; -var __extendDeepAll_254 = _$lib_166.extendDeepAll; +/* removed: var _$lib_167 = require('../../../lib'); */; +var __extendDeepAll_254 = _$lib_167.extendDeepAll; var __MID_SHIFT_254 = _$alignment_145.MID_SHIFT; var µ = _$micropolar_254 = { version: '0.2.2' }; @@ -58571,12 +59281,12 @@ var _$micropolar_manager_255 = {}; 'use strict'; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../../lib'); */; +/* removed: var _$lib_167 = require('../../../lib'); */; /* removed: var _$color_45 = require('../../../components/color'); */; /* removed: var _$micropolar_254 = require('./micropolar'); */; /* removed: var _$UndoManager_256 = require('./undo_manager'); */; -var __extendDeepAll_255 = _$lib_166.extendDeepAll; +var __extendDeepAll_255 = _$lib_167.extendDeepAll; var manager = _$micropolar_manager_255 = {}; @@ -58658,7 +59368,7 @@ var Polar = _$legacy_253 = _$micropolar_254; Polar.manager = _$micropolar_manager_255; -var _$plot_api_198 = {}; +var _$plot_api_199 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -58675,33 +59385,29 @@ var _$plot_api_198 = {}; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; /* removed: var _$hasHover_13 = require('has-hover'); */; -/* removed: var _$lib_166 = require('../lib'); */; -/* removed: var _$Events_157 = require('../lib/events'); */; -/* removed: var _$queue_180 = require('../lib/queue'); */; +/* removed: var _$lib_167 = require('../lib'); */; +/* removed: var _$Events_158 = require('../lib/events'); */; +/* removed: var _$queue_181 = require('../lib/queue'); */; -/* removed: var _$registry_258 = require('../registry'); */; -/* removed: var _$plot_schema_200 = require('./plot_schema'); */; +/* removed: var _$registry_259 = require('../registry'); */; +/* removed: var _$plot_schema_201 = require('./plot_schema'); */; /* removed: var _$plots_250 = require('../plots/plots'); */; /* removed: var _$legacy_253 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_218 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$axes_209 = require('../plots/cartesian/axes'); */; +/* removed: var _$axes_210 = require('../plots/cartesian/axes'); */; /* removed: var _$drawing_70 = require('../components/drawing'); */; /* removed: var _$color_45 = require('../components/color'); */; +var initInteractions = _$graph_interact_219.initInteractions; /* removed: var _$xmlns_namespaces_149 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_187 = require('../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_188 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_199 = require('./plot_config'); */; -/* removed: var _$manage_arrays_197 = require('./manage_arrays'); */; -/* removed: var _$helpers_195 = require('./helpers'); */; -/* removed: var _$subroutines_201 = require('./subroutines'); */; -/* removed: var _$edit_types_194 = require('./edit_types'); */; +/* removed: var _$plot_config_200 = require('./plot_config'); */; +/* removed: var _$manage_arrays_198 = require('./manage_arrays'); */; +/* removed: var _$helpers_196 = require('./helpers'); */; +/* removed: var _$subroutines_202 = require('./subroutines'); */; +/* removed: var _$edit_types_195 = require('./edit_types'); */; -/* removed: var _$constants_214 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_216 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_216.enforce; -var cleanAxisConstraints = _$constraints_216.clean; -var __doAutoRange_198 = _$autorange_208.doAutoRange; +var AX_NAME_PATTERN = _$constants_215.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -58727,15 +59433,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_198.plot = function(gd, data, layout, config) { +_$plot_api_199.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_166.getGraphDiv(gd); + gd = _$lib_167.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_157.init(gd); + _$Events_158.init(gd); - if(_$lib_166.isPlainObject(data)) { + if(_$lib_167.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -58743,19 +59449,19 @@ _$plot_api_198.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_157.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_158.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_166.isPlotDiv(gd)) { - _$lib_166.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_167.isPlotDiv(gd)) { + _$lib_167.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_198.addFrames(gd, frames); + return _$plot_api_199.addFrames(gd, frames); } } @@ -58774,6 +59480,9 @@ _$plot_api_198.plot = function(gd, data, layout, config) { // so we can share cached text across tabs _$drawing_70.makeTester(); + // clear stashed base url + delete _$drawing_70.baseUrl; + // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all @@ -58785,7 +59494,7 @@ _$plot_api_198.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_195.cleanData(data, gd.data); + _$helpers_196.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -58796,7 +59505,7 @@ _$plot_api_198.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_195.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_196.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -58818,7 +59527,7 @@ _$plot_api_198.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_166.log('Legacy polar charts are deprecated!'); + _$lib_167.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -58839,7 +59548,7 @@ _$plot_api_198.plot = function(gd, data, layout, config) { _$drawing_70.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_209.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_210.saveShowSpikeInitial(gd); // prepare the data and find the autorange @@ -58906,9 +59615,7 @@ _$plot_api_198.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_166.syncOrAsync([ - _$subroutines_201.layoutStyles - ], gd); + return _$plots_250.previousPromises(gd); } // draw anything that can affect margins. @@ -58916,10 +59623,10 @@ _$plot_api_198.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_258.getComponentMethod('legend', 'draw')(gd); - _$registry_258.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_258.getComponentMethod('sliders', 'draw')(gd); - _$registry_258.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_259.getComponentMethod('legend', 'draw')(gd); + _$registry_259.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_259.getComponentMethod('sliders', 'draw')(gd); + _$registry_259.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; @@ -58938,9 +59645,9 @@ _$plot_api_198.plot = function(gd, data, layout, config) { function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_166.syncOrAsync([ + return _$lib_167.syncOrAsync([ marginPushers, - _$subroutines_201.layoutStyles + _$subroutines_202.layoutStyles ], gd); } @@ -58961,7 +59668,7 @@ _$plot_api_198.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_166.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_167.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -58975,113 +59682,31 @@ _$plot_api_198.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_258.getComponentMethod('errorbars', 'calc')(gd); + _$registry_259.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_166.syncOrAsync([ - _$registry_258.getComponentMethod('shapes', 'calcAutorange'), - _$registry_258.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_167.syncOrAsync([ + _$registry_259.getComponentMethod('shapes', 'calcAutorange'), + _$registry_259.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_258.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_259.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_209.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_198(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_202.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_209.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_210.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_209.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_258.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_250.style(gd); - - // show annotations and shapes - _$registry_258.getComponentMethod('shapes', 'draw')(gd); - _$registry_258.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_250.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_250.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_258.getComponentMethod('shapes', 'draw')(gd); - _$registry_258.getComponentMethod('images', 'draw')(gd); - _$registry_258.getComponentMethod('annotations', 'draw')(gd); - _$registry_258.getComponentMethod('legend', 'draw')(gd); - _$registry_258.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_258.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_258.getComponentMethod('sliders', 'draw')(gd); - _$registry_258.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_210.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ @@ -59092,19 +59717,20 @@ _$plot_api_198.plot = function(gd, data, layout, config) { marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_201.layoutStyles); + seq.push(_$subroutines_202.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_218, + _$subroutines_202.drawData, + _$subroutines_202.finalDraw, + initInteractions, + _$plots_250.addLinks, _$plots_250.rehover, _$plots_250.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_166.syncOrAsync(seq, gd); + var plotDone = _$lib_167.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -59113,15 +59739,15 @@ _$plot_api_198.plot = function(gd, data, layout, config) { }); }; -_$plot_api_198.setPlotConfig = function setPlotConfig(obj) { - return _$lib_166.extendFlat(_$plot_config_199, obj); +_$plot_api_199.setPlotConfig = function setPlotConfig(obj) { + return _$lib_167.extendFlat(_$plot_config_200, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_166.error(e); + _$lib_167.error(e); } } @@ -59131,7 +59757,7 @@ function opaqueSetBackground(gd, bgColor) { } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_166.extendDeep({}, _$plot_config_199); + if(!gd._context) gd._context = _$lib_167.extendDeep({}, _$plot_config_200); var context = gd._context; var i, keys, key; @@ -59247,7 +59873,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_187.convertToTspans, gd); + this.call(_$svg_text_utils_188.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -59256,7 +59882,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_166._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_167._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -59275,7 +59901,7 @@ function plotPolar(gd, data, layout) { } var setContenteditable = function() { - this.call(_$svg_text_utils_187.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_188.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -59297,18 +59923,18 @@ function plotPolar(gd, data, layout) { } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_198.redraw = function(gd) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.redraw = function(gd) { + gd = _$lib_167.getGraphDiv(gd); - if(!_$lib_166.isPlotDiv(gd)) { + if(!_$lib_167.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_195.cleanData(gd.data, gd.data); - _$helpers_195.cleanLayout(gd.layout); + _$helpers_196.cleanData(gd.data, gd.data); + _$helpers_196.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_198.plot(gd).then(function() { + return _$plot_api_199.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -59322,14 +59948,14 @@ _$plot_api_198.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_198.newPlot = function(gd, data, layout, config) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.newPlot = function(gd, data, layout, config) { + gd = _$lib_167.getGraphDiv(gd); // remove gl contexts - _$plots_250.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_250.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); _$plots_250.purge(gd); - return _$plot_api_198.plot(gd, data, layout, config); + return _$plot_api_199.plot(gd, data, layout, config); }; /** @@ -59482,12 +60108,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_166.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_167.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_166.isPlainObject(update)) { + if(!_$lib_167.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -59530,7 +60156,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_166.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_167.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -59550,7 +60176,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_166.nestedProperty(trace, key); + prop = _$lib_167.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -59559,10 +60185,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_166.isArrayOrTypedArray(insert)) { + if(!_$lib_167.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_166.isArrayOrTypedArray(target)) { + if(!_$lib_167.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -59657,13 +60283,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_198.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_167.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_166.isTypedArray(target)) { + if(_$lib_167.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -59708,20 +60334,20 @@ _$plot_api_198.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_198.redraw(gd); + var promise = _$plot_api_199.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_180.add(gd, _$plot_api_198.prependTraces, undoArgs, extendTraces, arguments); + _$queue_181.add(gd, _$plot_api_199.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_198.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_167.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_166.isTypedArray(target)) { + if(_$lib_167.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -59765,9 +60391,9 @@ _$plot_api_198.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_198.redraw(gd); + var promise = _$plot_api_199.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_180.add(gd, _$plot_api_198.extendTraces, undoArgs, prependTraces, arguments); + _$queue_181.add(gd, _$plot_api_199.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -59781,11 +60407,11 @@ _$plot_api_198.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_198.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_167.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_198.deleteTraces, + undoFunc = _$plot_api_199.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -59802,10 +60428,10 @@ _$plot_api_198.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_166.extendFlat({}, trace); + return _$lib_167.extendFlat({}, trace); }); - _$helpers_195.cleanData(traces, gd.data); + _$helpers_196.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -59820,8 +60446,8 @@ _$plot_api_198.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_198.redraw(gd); - _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_199.redraw(gd); + _$queue_181.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -59844,10 +60470,10 @@ _$plot_api_198.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_180.startSequence(gd); - _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_198.moveTraces(gd, currentIndices, newIndices); - _$queue_180.stopSequence(gd); + _$queue_181.startSequence(gd); + _$queue_181.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_199.moveTraces(gd, currentIndices, newIndices); + _$queue_181.stopSequence(gd); return promise; }; @@ -59858,11 +60484,11 @@ _$plot_api_198.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_198.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_167.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_198.addTraces, + undoFunc = _$plot_api_199.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -59881,14 +60507,14 @@ _$plot_api_198.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_166.sorterDes); + indices.sort(_$lib_167.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_198.redraw(gd); - _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_199.redraw(gd); + _$queue_181.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -59924,8 +60550,8 @@ _$plot_api_198.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_198.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_167.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -59985,8 +60611,8 @@ _$plot_api_198.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_198.redraw(gd); - _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_199.redraw(gd); + _$queue_181.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -60021,55 +60647,55 @@ _$plot_api_198.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_198.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_166.getGraphDiv(gd); - _$helpers_195.clearPromiseQueue(gd); +_$plot_api_199.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_167.getGraphDiv(gd); + _$helpers_196.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_166.isPlainObject(astr)) { + else if(_$lib_167.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_166.extendFlat({}, astr); + aobj = _$lib_167.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_166.warn('Restyle fail.', astr, val, _traces); + _$lib_167.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_195.coerceTraceIndices(gd, _traces); + var traces = _$helpers_196.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_195.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_196.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_198.plot); + seq.push(_$plot_api_199.plot); } else { seq.push(_$plots_250.previousPromises); _$plots_250.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_201.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_201.doColorBars); + if(flags.style) seq.push(_$subroutines_202.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_202.doColorBars); } seq.push(_$plots_250.rehover); - _$queue_180.add(gd, + _$queue_181.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_166.syncOrAsync(seq, gd); + var plotDone = _$lib_167.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -60092,7 +60718,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_194.traceFlags(); + var flags = _$edit_types_195.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -60105,7 +60731,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_209.id2name(axid); + var axName = _$axes_210.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -60124,13 +60750,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_195.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_196.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_166.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_167.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_166.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_167.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -60147,7 +60773,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_195.hasParent(aobj, ai)) { + if(_$helpers_196.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -60162,7 +60788,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_166.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_167.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -60178,17 +60804,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_166.nestedProperty(cont, ai); + param = _$lib_167.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_200.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_201.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_166.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_167.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -60228,19 +60854,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_166.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_166.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_166.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_167.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_167.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_167.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_166.nestedProperty(cont, 'marker.color') - .set(_$lib_166.nestedProperty(cont, 'marker.colors').get()); + _$lib_167.nestedProperty(cont, 'marker.color') + .set(_$lib_167.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_258.traceIs(cont, 'cartesian')) { - _$lib_166.nestedProperty(cont, 'marker.colors') - .set(_$lib_166.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_259.traceIs(cont, 'cartesian')) { + _$lib_167.nestedProperty(cont, 'marker.colors') + .set(_$lib_167.nestedProperty(cont, 'marker.color').get()); } } @@ -60269,23 +60895,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_195.swapXYData(cont); + _$helpers_196.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(_$plots_250.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_195.manageArrayContainers(param, newVal, undoit); + _$helpers_196.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_166.isArrayOrTypedArray(newVal) || _$lib_166.isArrayOrTypedArray(oldVal)) + _$lib_167.isArrayOrTypedArray(newVal) || _$lib_167.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_194.update(flags, valObject); + else _$edit_types_195.update(flags, valObject); } else { /* @@ -60304,12 +60930,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_209.swap(gd, traces); + _$axes_210.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_166.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_167.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -60324,7 +60950,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_258.traceIs(trace, 'cartesian')) { + if(_$registry_259.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -60341,7 +60967,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_209.list(gd); + var axList = _$axes_210.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -60362,7 +60988,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_166.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_167.extendDeepNoArrays([], [redoit, traces]) }; } @@ -60386,9 +61012,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_198.relayout = function relayout(gd, astr, val) { - gd = _$lib_166.getGraphDiv(gd); - _$helpers_195.clearPromiseQueue(gd); +_$plot_api_199.relayout = function relayout(gd, astr, val) { + gd = _$lib_167.getGraphDiv(gd); + _$helpers_196.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -60397,21 +61023,21 @@ _$plot_api_198.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_166.isPlainObject(astr)) { - aobj = _$lib_166.extendFlat({}, astr); + } else if(_$lib_167.isPlainObject(astr)) { + aobj = _$lib_167.extendFlat({}, astr); } else { - _$lib_166.warn('Relayout fail.', astr, val); + _$lib_167.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_195.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_196.clearAxisAutomargins(gd); // fill in redraw sequence @@ -60421,26 +61047,50 @@ _$plot_api_198.relayout = function relayout(gd, astr, val) { var seq = [_$plots_250.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_201.layoutReplot); + seq.push(_$subroutines_202.layoutReplot); } else if(Object.keys(aobj).length) { _$plots_250.supplyDefaults(gd); - if(flags.legend) seq.push(_$subroutines_201.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_201.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_201.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_201.doModeBar); - if(flags.camera) seq.push(_$subroutines_201.doCamera); + if(flags.legend) seq.push(_$subroutines_202.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_202.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_202.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_202.doTicksRelayout, + _$subroutines_202.drawData, + _$subroutines_202.finalDraw + ); + } + + if(flags.ticks) seq.push(_$subroutines_202.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_202.doModeBar); + if(flags.camera) seq.push(_$subroutines_202.doCamera); } seq.push(_$plots_250.rehover); - _$queue_180.add(gd, + _$queue_181.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_166.syncOrAsync(seq, gd); + var plotDone = _$lib_167.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -60453,7 +61103,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_209.list(gd), + axes = _$axes_210.list(gd), arrayEdits = {}, arrayStr, i, @@ -60476,7 +61126,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_194.layoutFlags(); + var flags = _$edit_types_195.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -60495,9 +61145,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_195.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_196.hasParent(aobj, attr)) return; - var p = _$lib_166.nestedProperty(layout, attr); + var p = _$lib_167.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -60511,18 +61161,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_209.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_210.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_195.hasParent(aobj, ai)) { + if(_$helpers_196.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_166.nestedProperty(layout, ai); + var p = _$lib_167.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -60534,8 +61184,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_166.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_166.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_167.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_167.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -60546,11 +61196,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_200.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_201.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_166.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_167.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -60564,12 +61214,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_167.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_166.nestedProperty(fullLayout, ptrunk).get(); + _$lib_167.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_167.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -60577,7 +61227,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_167.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -60637,8 +61287,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_258.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_258.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_259.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_259.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -60646,18 +61296,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_166.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_167.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_214.AX_NAME_PATTERN)) { - var fullProp = _$lib_166.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_167.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_258.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_258.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_259.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_259.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -60666,12 +61316,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_197.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_198.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_166.nestedProperty(layout, arrayStr); + var componentArray = _$lib_167.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -60681,28 +61331,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_194.update(flags, updateValObject); + else _$edit_types_195.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_197.isAddVal(vi)) { + if(_$manage_arrays_198.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_197.isRemoveVal(vi)) { + else if(_$manage_arrays_198.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_166.warn('unrecognized full object value', aobj); + else _$lib_167.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_194.update(flags, updateValObject); - + else { + _$edit_types_195.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -60731,7 +61382,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_194.update(flags, valObject); + else if(valObject) _$edit_types_195.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -60740,8 +61391,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_197.applyContainerArrayChanges(gd, - _$lib_166.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_198.applyContainerArrayChanges(gd, + _$lib_167.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -60759,7 +61410,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_209.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_210.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -60783,7 +61434,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_166.extendDeep({}, redoit) + eventData: _$lib_167.extendDeep({}, redoit) }; } @@ -60805,9 +61456,9 @@ function updateAutosize(gd) { // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_166.isPlainObject(obj)) return false; + if(!_$lib_167.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_209.getFromId(gd, axRef); + ax = _$axes_210.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -60817,7 +61468,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_209.getFromId(gd, axLetter); + ax = _$axes_210.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -60837,32 +61488,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_198.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_166.getGraphDiv(gd); - _$helpers_195.clearPromiseQueue(gd); +_$plot_api_199.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_167.getGraphDiv(gd); + _$helpers_196.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_166.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_166.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_167.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_167.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_195.coerceTraceIndices(gd, _traces); + var traces = _$helpers_196.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_166.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_167.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_166.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_167.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_195.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_195.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_196.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_196.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -60876,35 +61527,43 @@ _$plot_api_198.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_198.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_199.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_198.plot); + seq.push(_$plot_api_199.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_201.layoutReplot); + seq.push(_$subroutines_202.layoutReplot); } else { seq.push(_$plots_250.previousPromises); _$plots_250.supplyDefaults(gd); - if(restyleFlags.style) seq.push(_$subroutines_201.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_201.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_201.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_201.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_201.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_201.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_201.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_202.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_202.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_202.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_202.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_202.doAutoRangeAndConstraints, + _$subroutines_202.doTicksRelayout, + _$subroutines_202.drawData, + _$subroutines_202.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_202.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_202.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_202.doCamera); } seq.push(_$plots_250.rehover); - _$queue_180.add(gd, + _$queue_181.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_166.syncOrAsync(seq, gd); + var plotDone = _$lib_167.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -60940,23 +61599,23 @@ _$plot_api_198.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_198.react = function(gd, data, layout, config) { +_$plot_api_199.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_198.addFrames(gd, frames); } + function addFrames() { return _$plot_api_199.addFrames(gd, frames); } - gd = _$lib_166.getGraphDiv(gd); + gd = _$lib_167.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_166.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_198.newPlot(gd, data, layout, config); + if(!_$lib_167.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_199.newPlot(gd, data, layout, config); } else { - if(_$lib_166.isPlainObject(data)) { + if(_$lib_167.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -60968,16 +61627,16 @@ _$plot_api_198.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_166.extendDeep({}, gd._context); + var oldConfig = _$lib_167.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_195.cleanData(gd.data, []); + _$helpers_196.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_195.cleanLayout(gd.layout); + _$helpers_196.cleanLayout(gd.layout); _$plots_250.supplyDefaults(gd); @@ -61001,7 +61660,7 @@ _$plot_api_198.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_195.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_196.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -61017,21 +61676,21 @@ _$plot_api_198.react = function(gd, data, layout, config) { if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_198.plot); + seq.push(_$plot_api_199.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_258.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_166.noop) { + var drawOne = _$registry_259.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_167.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_258.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_166.noop) { + var draw = _$registry_259.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_167.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -61040,18 +61699,26 @@ _$plot_api_198.react = function(gd, data, layout, config) { } seq.push(_$plots_250.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_201.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_201.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_201.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_201.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_201.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_201.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_201.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_202.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_202.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_202.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_202.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_202.doAutoRangeAndConstraints, + _$subroutines_202.doTicksRelayout, + _$subroutines_202.drawData, + _$subroutines_202.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_202.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_202.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_202.doCamera); } seq.push(_$plots_250.rehover); - plotDone = _$lib_166.syncOrAsync(seq, gd); + plotDone = _$lib_167.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -61074,12 +61741,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_194.traceFlags(); + var flags = _$edit_types_195.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_200.getTraceValObject(trace, parts); + return _$plot_schema_201.getTraceValObject(trace, parts); } var diffOpts = { @@ -61089,11 +61756,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_209.getFromId(gd, trace.xaxis).autorange || - _$axes_209.getFromId(gd, trace.yaxis).autorange + _$axes_210.getFromId(gd, trace.xaxis).autorange || + _$axes_210.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -61106,11 +61779,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_194.layoutFlags(); + var flags = _$edit_types_195.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_200.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_201.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -61149,10 +61822,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_166.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_167.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_194.update(flags, valObject); + _$edit_types_195.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -61232,7 +61905,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_166.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_167.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -61244,7 +61917,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_166.isPlainObject(oldVal)) { + else if(!valType && _$lib_167.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -61298,7 +61971,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_166.isPlainObject(oldVal) && _$lib_166.isPlainObject(newVal)) { + if(_$lib_167.isPlainObject(oldVal) && _$lib_167.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -61309,7 +61982,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_166.isPlainObject(oldVal[i]) && _$lib_166.isPlainObject(newVal[i])) { + if(_$lib_167.isPlainObject(oldVal[i]) && _$lib_167.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -61354,10 +62027,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_198.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_167.getGraphDiv(gd); - if(!_$lib_166.isPlotDiv(gd)) { + if(!_$lib_167.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -61531,7 +62204,7 @@ _$plot_api_198.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts _$plots_250.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_195.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_196.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -61601,13 +62274,13 @@ _$plot_api_198.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_166.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_167.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_166.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_167.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -61636,10 +62309,10 @@ _$plot_api_198.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_166.isPlainObject(frameOrName)) { + } else if(_$lib_167.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_166.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_167.extendFlat({}, frameOrName)) }); } } @@ -61649,7 +62322,7 @@ _$plot_api_198.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_166.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_167.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -61718,14 +62391,14 @@ _$plot_api_198.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_198.addFrames = function(gd, frameList, indices) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.addFrames = function(gd, frameList, indices) { + gd = _$lib_167.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_166.isPlotDiv(gd)) { + if(!_$lib_167.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -61752,7 +62425,7 @@ _$plot_api_198.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_166.isPlainObject(frameList[i])) continue; + if(!_$lib_167.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -61764,14 +62437,14 @@ _$plot_api_198.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_166.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_167.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_166.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_167.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -61800,7 +62473,7 @@ _$plot_api_198.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_166.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_167.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -61833,7 +62506,7 @@ _$plot_api_198.addFrames = function(gd, frameList, indices) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_180) _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_181) _$queue_181.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_250.modifyFrames(gd, ops); }; @@ -61847,10 +62520,10 @@ _$plot_api_198.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_198.deleteFrames = function(gd, frameList) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.deleteFrames = function(gd, frameList) { + gd = _$lib_167.getGraphDiv(gd); - if(!_$lib_166.isPlotDiv(gd)) { + if(!_$lib_167.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -61880,7 +62553,7 @@ _$plot_api_198.deleteFrames = function(gd, frameList) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_180) _$queue_180.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_181) _$queue_181.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_250.modifyFrames(gd, ops); }; @@ -61891,20 +62564,21 @@ _$plot_api_198.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_198.purge = function purge(gd) { - gd = _$lib_166.getGraphDiv(gd); +_$plot_api_199.purge = function purge(gd) { + gd = _$lib_167.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_250.cleanPlot([], {}, fullData, fullLayout); + _$plots_250.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties _$plots_250.purge(gd); // purge event emitter methods - _$Events_157.purge(gd); + _$Events_158.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -61962,7 +62636,7 @@ function makePlotFramework(gd) { _$d3_8.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_166.randstr(otherUids); + fullLayout._uid = _$lib_167.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') @@ -62038,7 +62712,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_262 = {}; +var _$helpers_263 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -62050,7 +62724,7 @@ var _$helpers_262 = {}; 'use strict'; -_$helpers_262.getDelay = function(fullLayout) { +_$helpers_263.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -62060,7 +62734,7 @@ _$helpers_262.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_262.getRedrawFunc = function(gd) { +_$helpers_263.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -62085,11 +62759,11 @@ _$helpers_262.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_166 = require('../lib'); */; -var __EventEmitter_264 = _$EventEmitter_10.EventEmitter; +/* removed: var _$lib_167 = require('../lib'); */; +var __EventEmitter_265 = _$EventEmitter_10.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_264(); + var ev = opts.emitter || new __EventEmitter_265(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -62097,7 +62771,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_166.isIE() && format !== 'svg') { + if(_$lib_167.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -62188,7 +62862,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_264 = svgToImg; +var _$svgToImg_265 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -62203,7 +62877,7 @@ var _$svgToImg_264 = svgToImg; /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; /* removed: var _$drawing_70 = require('../components/drawing'); */; /* removed: var _$color_45 = require('../components/color'); */; @@ -62228,7 +62902,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_266 = function toSVG(gd, format, scale) { +var _$toSVG_267 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -62351,7 +63025,7 @@ var _$toSVG_266 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_166.isIE()) { + if(_$lib_167.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -62376,14 +63050,14 @@ var _$toSVG_266 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_198 = require('./plot_api'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$plot_api_199 = require('./plot_api'); */; +/* removed: var _$lib_167 = require('../lib'); */; -/* removed: var _$helpers_262 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_266 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_264 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_263 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_267 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_265 = require('../snapshot/svgtoimg'); */; -var __attrs_202 = { +var __attrs_203 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -62436,19 +63110,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_166.isPlainObject(gd)) { + if(_$lib_167.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_166.getGraphDiv(gd); - data = _$lib_166.extendDeep([], gd.data); - layout = _$lib_166.extendDeep({}, gd.layout); + gd = _$lib_167.getGraphDiv(gd); + data = _$lib_167.extendDeep([], gd.data); + layout = _$lib_167.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_166.validate(opts[attr], __attrs_202[attr]); + return !(attr in opts) || _$lib_167.validate(opts[attr], __attrs_203[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -62462,7 +63136,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_166.coerce(opts, fullOpts, __attrs_202, attr, dflt); + return _$lib_167.coerce(opts, fullOpts, __attrs_203, attr, dflt); } var format = coerce('format'); @@ -62479,31 +63153,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_166.extendFlat({}, layout); + var layoutImage = _$lib_167.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_166.extendFlat({}, config, { + var configImage = _$lib_167.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_262.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_263.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_262.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_263.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_266(clonedGd, format, scale); + var svg = _$toSVG_267(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_198.purge(clonedGd); + _$plot_api_199.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -62515,9 +63189,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_166.randstr(); + canvas.id = _$lib_167.randstr(); - _$svgToImg_264({ + _$svgToImg_265({ format: format, width: width, height: height, @@ -62544,7 +63218,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_198.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_199.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -62553,7 +63227,7 @@ function toImage(gd, opts) { }); } -var _$toImage_202 = toImage; +var _$toImage_203 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -62565,14 +63239,14 @@ var _$toImage_202 = toImage; 'use strict'; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; /* removed: var _$plots_250 = require('../plots/plots'); */; -/* removed: var _$plot_schema_200 = require('./plot_schema'); */; -/* removed: var _$plot_config_199 = require('./plot_config'); */; +/* removed: var _$plot_schema_201 = require('./plot_schema'); */; +/* removed: var _$plot_config_200 = require('./plot_config'); */; -var __isPlainObject_203 = _$lib_166.isPlainObject; -var __isArray_203 = Array.isArray; -var __isArrayOrTypedArray_203 = _$lib_166.isArrayOrTypedArray; +var __isPlainObject_204 = _$lib_167.isPlainObject; +var __isArray_204 = Array.isArray; +var __isArrayOrTypedArray_204 = _$lib_167.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -62595,15 +63269,15 @@ var __isArrayOrTypedArray_203 = _$lib_166.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_203 = function valiate(data, layout) { - var schema = _$plot_schema_200.get(); +var _$valiate_204 = function valiate(data, layout) { + var schema = _$plot_schema_201.get(); var errorList = []; - var gd = {_context: _$lib_166.extendFlat({}, _$plot_config_199)}; + var gd = {_context: _$lib_167.extendFlat({}, _$plot_config_200)}; var dataIn, layoutIn; - if(__isArray_203(data)) { - gd.data = _$lib_166.extendDeep([], data); + if(__isArray_204(data)) { + gd.data = _$lib_167.extendDeep([], data); dataIn = data; } else { @@ -62612,8 +63286,8 @@ var _$valiate_203 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_203(layout)) { - gd.layout = _$lib_166.extendDeep({}, layout); + if(__isPlainObject_204(layout)) { + gd.layout = _$lib_167.extendDeep({}, layout); layoutIn = layout; } else { @@ -62637,7 +63311,7 @@ var _$valiate_203 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_203(traceIn)) { + if(!__isPlainObject_204(traceIn)) { errorList.push(format('object', base)); continue; } @@ -62657,13 +63331,13 @@ var _$valiate_203 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_203(traceIn, traceOut, traceSchema, errorList, base); + __crawl_204(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_203(transformsIn)) { + if(!__isArray_204(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -62673,7 +63347,7 @@ var _$valiate_203 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_203(transformsIn[j])) { + if(!__isPlainObject_204(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -62688,7 +63362,7 @@ var _$valiate_203 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_203(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_204(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -62696,13 +63370,13 @@ var _$valiate_203 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_203(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_204(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_203(objIn, objOut, schema, list, base, path) { +function __crawl_204(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -62727,10 +63401,10 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_203(valIn) && __isPlainObject_203(valOut)) { - __crawl_203(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_204(valIn) && __isPlainObject_204(valOut)) { + __crawl_204(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_203(valIn)) { + else if(isInfoArray && __isArray_204(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -62740,7 +63414,7 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_203(valIn[n])) { + if(__isArray_204(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -62749,7 +63423,7 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_166.validate(valInPart, item)) { + if(!_$lib_167.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -62767,7 +63441,7 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_166.validate(valInPart, item)) { + if(!_$lib_167.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -62776,7 +63450,7 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_203(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_204(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -62790,9 +63464,9 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_203(valIn[_index]) && __isPlainObject_203(valOut[j])) { + if(__isPlainObject_204(valIn[_index]) && __isPlainObject_204(valOut[j])) { indexList.push(_index); - __crawl_203(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_204(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -62801,7 +63475,7 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_203(valIn[j])) { + if(!__isPlainObject_204(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -62809,16 +63483,16 @@ function __crawl_203(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_203(valIn) && __isPlainObject_203(valOut)) { + else if(!__isPlainObject_204(valIn) && __isPlainObject_204(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_203(valIn) && __isArrayOrTypedArray_203(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_204(valIn) && __isArrayOrTypedArray_204(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_166.validate(valIn, nestedSchema)) { + else if(!_$lib_167.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -62838,7 +63512,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_166.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_167.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -62870,7 +63544,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_203(valIn) ? 'container' : 'key'; + var target = __isPlainObject_204(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -62896,7 +63570,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_203(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_204(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -62909,7 +63583,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_203(base)) { + if(__isArray_204(base)) { container = base[0]; trace = base[1]; } @@ -62922,7 +63596,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_166.log(msg); + _$lib_167.log(msg); return { code: code, @@ -62952,7 +63626,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_166.counterRegex('([a-z]+)'); +var idRegex = _$lib_167.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -62964,7 +63638,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_203(path)) return String(path); + if(!__isArray_204(path)) return String(path); var astr = ''; @@ -63053,7 +63727,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_261 = fileSaver; +var _$fileSaver_262 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -63066,9 +63740,9 @@ var _$fileSaver_261 = fileSaver; 'use strict'; -/* removed: var _$toImage_202 = require('../plot_api/to_image'); */; -/* removed: var _$lib_166 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_261 = require('./filesaver'); */; +/* removed: var _$toImage_203 = require('../plot_api/to_image'); */; +/* removed: var _$lib_167 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_262 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -63096,19 +63770,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_166.isIE() && opts.format !== 'svg') { + if(_$lib_167.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_202(gd, opts); + var promise = _$toImage_203(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_261(result, filename); + return _$fileSaver_262(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -63118,9 +63792,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_260 = downloadImage; +var _$downloadImage_261 = downloadImage; -var _$plot_api_196 = {}; +var _$plot_api_197 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -63131,29 +63805,29 @@ var _$plot_api_196 = {}; 'use strict'; -/* removed: var _$plot_api_198 = require('./plot_api'); */; - -_$plot_api_196.plot = _$plot_api_198.plot; -_$plot_api_196.newPlot = _$plot_api_198.newPlot; -_$plot_api_196.restyle = _$plot_api_198.restyle; -_$plot_api_196.relayout = _$plot_api_198.relayout; -_$plot_api_196.redraw = _$plot_api_198.redraw; -_$plot_api_196.update = _$plot_api_198.update; -_$plot_api_196.react = _$plot_api_198.react; -_$plot_api_196.extendTraces = _$plot_api_198.extendTraces; -_$plot_api_196.prependTraces = _$plot_api_198.prependTraces; -_$plot_api_196.addTraces = _$plot_api_198.addTraces; -_$plot_api_196.deleteTraces = _$plot_api_198.deleteTraces; -_$plot_api_196.moveTraces = _$plot_api_198.moveTraces; -_$plot_api_196.purge = _$plot_api_198.purge; -_$plot_api_196.addFrames = _$plot_api_198.addFrames; -_$plot_api_196.deleteFrames = _$plot_api_198.deleteFrames; -_$plot_api_196.animate = _$plot_api_198.animate; -_$plot_api_196.setPlotConfig = _$plot_api_198.setPlotConfig; - -_$plot_api_196.toImage = _$toImage_202; -_$plot_api_196.validate = _$valiate_203; -_$plot_api_196.downloadImage = _$downloadImage_260; +/* removed: var _$plot_api_199 = require('./plot_api'); */; + +_$plot_api_197.plot = _$plot_api_199.plot; +_$plot_api_197.newPlot = _$plot_api_199.newPlot; +_$plot_api_197.restyle = _$plot_api_199.restyle; +_$plot_api_197.relayout = _$plot_api_199.relayout; +_$plot_api_197.redraw = _$plot_api_199.redraw; +_$plot_api_197.update = _$plot_api_199.update; +_$plot_api_197.react = _$plot_api_199.react; +_$plot_api_197.extendTraces = _$plot_api_199.extendTraces; +_$plot_api_197.prependTraces = _$plot_api_199.prependTraces; +_$plot_api_197.addTraces = _$plot_api_199.addTraces; +_$plot_api_197.deleteTraces = _$plot_api_199.deleteTraces; +_$plot_api_197.moveTraces = _$plot_api_199.moveTraces; +_$plot_api_197.purge = _$plot_api_199.purge; +_$plot_api_197.addFrames = _$plot_api_199.addFrames; +_$plot_api_197.deleteFrames = _$plot_api_199.deleteFrames; +_$plot_api_197.animate = _$plot_api_199.animate; +_$plot_api_197.setPlotConfig = _$plot_api_199.setPlotConfig; + +_$plot_api_197.toImage = _$toImage_203; +_$plot_api_197.validate = _$valiate_204; +_$plot_api_197.downloadImage = _$downloadImage_261; /** * Copyright 2012-2018, Plotly, Inc. @@ -63166,10 +63840,10 @@ _$plot_api_196.downloadImage = _$downloadImage_260; 'use strict'; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$lib_167 = require('../lib'); */; -var __extendFlat_259 = _$lib_166.extendFlat; -var extendDeep = _$lib_166.extendDeep; +var __extendFlat_260 = _$lib_167.extendFlat; +var extendDeep = _$lib_167.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -63214,7 +63888,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_259 = function clonePlot(graphObj, options) { +var _$clonePlot_260 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -63287,9 +63961,9 @@ var _$clonePlot_259 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_259(scene.xaxis, axesImageOverride); - __extendFlat_259(scene.yaxis, axesImageOverride); - __extendFlat_259(scene.zaxis, axesImageOverride); + __extendFlat_260(scene.xaxis, axesImageOverride); + __extendFlat_260(scene.yaxis, axesImageOverride); + __extendFlat_260(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -63338,27 +64012,27 @@ var _$clonePlot_259 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_265 = _$EventEmitter_10.EventEmitter; +var __EventEmitter_266 = _$EventEmitter_10.EventEmitter; -/* removed: var _$registry_258 = require('../registry'); */; -/* removed: var _$lib_166 = require('../lib'); */; +/* removed: var _$registry_259 = require('../registry'); */; +/* removed: var _$lib_167 = require('../lib'); */; -/* removed: var _$helpers_262 = require('./helpers'); */; -/* removed: var _$clonePlot_259 = require('./cloneplot'); */; -/* removed: var _$toSVG_266 = require('./tosvg'); */; -/* removed: var _$svgToImg_264 = require('./svgtoimg'); */; +/* removed: var _$helpers_263 = require('./helpers'); */; +/* removed: var _$clonePlot_260 = require('./cloneplot'); */; +/* removed: var _$toSVG_267 = require('./tosvg'); */; +/* removed: var _$svgToImg_265 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_265(gd, opts) { +function __toImage_266(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_265(); + var ev = new __EventEmitter_266(); - var clone = _$clonePlot_259(gd, {format: 'png'}); + var clone = _$clonePlot_260(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -63367,15 +64041,15 @@ function __toImage_265(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_262.getDelay(clonedGd._fullLayout); + var delay = _$helpers_263.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_266(clonedGd); + var svg = _$toSVG_267(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_166.randstr(); + canvas.id = _$lib_167.randstr(); - ev = _$svgToImg_264({ + ev = _$svgToImg_265({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -63391,9 +64065,9 @@ function __toImage_265(gd, opts) { }, delay); } - var redrawFunc = _$helpers_262.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_263.getRedrawFunc(clonedGd); - _$registry_258.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_259.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -63404,7 +64078,7 @@ function __toImage_265(gd, opts) { return ev; } -var _$toImage_265 = __toImage_265; +var _$toImage_266 = __toImage_266; /** * Copyright 2012-2018, Plotly, Inc. @@ -63417,19 +64091,19 @@ var _$toImage_265 = __toImage_265; 'use strict'; -/* removed: var _$helpers_262 = require('./helpers'); */; +/* removed: var _$helpers_263 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_262.getDelay, - getRedrawFunc: _$helpers_262.getRedrawFunc, - clone: _$clonePlot_259, - toSVG: _$toSVG_266, - svgToImg: _$svgToImg_264, - toImage: _$toImage_265, - downloadImage: _$downloadImage_260 + getDelay: _$helpers_263.getDelay, + getRedrawFunc: _$helpers_263.getRedrawFunc, + clone: _$clonePlot_260, + toSVG: _$toSVG_267, + svgToImg: _$svgToImg_265, + toImage: _$toImage_266, + downloadImage: _$downloadImage_261 }; -var _$Snapshot_263 = Snapshot; +var _$Snapshot_264 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -63445,15 +64119,15 @@ var _$Snapshot_263 = Snapshot; /* removed: var _$hasColorscale_59 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$calc_52 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; -var _$calcMarkerColorscale_285 = function calcMarkerColorscale(trace) { - if(_$subtypes_302.hasLines(trace) && _$hasColorscale_59(trace, 'line')) { +var _$calcMarkerColorscale_286 = function calcMarkerColorscale(trace) { + if(_$subtypes_303.hasLines(trace) && _$hasColorscale_59(trace, 'line')) { _$calc_52(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_302.hasMarkers(trace)) { + if(_$subtypes_303.hasMarkers(trace)) { if(_$hasColorscale_59(trace, 'marker')) { _$calc_52(trace, trace.marker.color, 'marker', 'c'); } @@ -63474,19 +64148,19 @@ var _$calcMarkerColorscale_285 = function calcMarkerColorscale(trace) { 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_281 = _$lib_166.isArrayOrTypedArray; +var __isArrayOrTypedArray_282 = _$lib_167.isArrayOrTypedArray; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -var __BADNUM_281 = _$numerical_147.BADNUM; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +var __BADNUM_282 = _$numerical_147.BADNUM; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_285 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_279 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_282 = require('./calc_selection'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_286 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_280 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_283 = require('./calc_selection'); */; -function __calc_281(gd, trace) { - var xa = _$axes_209.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_209.getFromId(gd, trace.yaxis || 'y'); +function __calc_282(gd, trace) { + var xa = _$axes_210.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_210.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -63498,16 +64172,16 @@ function __calc_281(gd, trace) { for(var i = 0; i < serieslen; i++) { cd[i] = (_$fastIsnumeric_11(x[i]) && _$fastIsnumeric_11(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_281, y: __BADNUM_281}; + {x: __BADNUM_282, y: __BADNUM_282}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_279(cd, trace); - _$calcMarkerColorscale_285(trace); - _$calcSelection_282(cd, trace); + _$arraysToCalcdata_280(cd, trace); + _$calcMarkerColorscale_286(trace); + _$calcSelection_283(cd, trace); gd.firstscatter = false; return cd; @@ -63540,9 +64214,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_302.hasMarkers(trace) && !_$subtypes_302.hasText(trace)) + (!_$subtypes_303.hasMarkers(trace) && !_$subtypes_303.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -63561,12 +64235,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_209.expand(xa, x, xOptions); - _$axes_209.expand(ya, y, yOptions); + _$axes_210.expand(xa, x, xOptions); + _$axes_210.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_302.hasMarkers(trace)) return; + if(!_$subtypes_303.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -63584,10 +64258,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_281(marker.size)) { + if(__isArrayOrTypedArray_282(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_209.setConvert(ax); + _$axes_210.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -63602,8 +64276,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_281 = { - calc: __calc_281, +var _$calc_282 = { + calc: __calc_282, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -63621,7 +64295,7 @@ var _$calc_281 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_283 = function cleanData(fullData) { +var _$cleanData_284 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -63659,13 +64333,13 @@ var _$cleanData_283 = function cleanData(fullData) { /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$plots_250 = require('../../plots/plots'); */; /* removed: var _$colorscale_60 = require('../../components/colorscale'); */; /* removed: var _$draw_49 = require('../../components/colorbar/draw'); */; -var _$colorbar_284 = function colorbar(gd, cd) { +var _$colorbar_285 = function colorbar(gd, cd) { var trace = cd[0].trace, marker = trace.marker, cbId = 'cb' + trace.uid; @@ -63683,8 +64357,8 @@ var _$colorbar_284 = function colorbar(gd, cd) { cmin = marker.cmin, cmax = marker.cmax; - if(!_$fastIsnumeric_11(cmin)) cmin = _$lib_166.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_11(cmax)) cmax = _$lib_166.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_11(cmin)) cmin = _$lib_167.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_11(cmax)) cmax = _$lib_167.aggNums(Math.max, null, vals); var cb = cd[0].t.cb = _$draw_49(gd, cbId); var sclFunc = _$colorscale_60.makeColorScaleFunc( @@ -63713,9 +64387,9 @@ var _$colorbar_284 = function colorbar(gd, cd) { 'use strict'; /* removed: var _$color_45 = require('../../components/color'); */; -var __isArrayOrTypedArray_289 = _$lib_166.isArrayOrTypedArray; +var __isArrayOrTypedArray_290 = _$lib_167.isArrayOrTypedArray; -var _$fillColorDefaults_289 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_290 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -63723,10 +64397,10 @@ var _$fillColorDefaults_289 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_289(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_290(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_289(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_290(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } @@ -63748,11 +64422,11 @@ var _$fillColorDefaults_289 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_293 = _$lib_166.isArrayOrTypedArray; +var __isArrayOrTypedArray_294 = _$lib_167.isArrayOrTypedArray; /* removed: var _$hasColorscale_59 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_55 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_293 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_294 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); @@ -63761,7 +64435,7 @@ var _$lineDefaults_293 = function lineDefaults(traceIn, traceOut, defaultColor, _$colorScaleDefaults_55(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_293(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_294(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -63782,7 +64456,7 @@ var _$lineDefaults_293 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_295 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_296 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -63802,7 +64476,7 @@ var _$handleLineShapeDefaults_295 = function handleLineShapeDefaults(traceIn, tr /* removed: var _$hasColorscale_59 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_55 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -63810,8 +64484,8 @@ var _$handleLineShapeDefaults_295 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_298 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_302.isBubble(traceIn), +var _$markerDefaults_299 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_303.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -63880,17 +64554,17 @@ var _$markerDefaults_298 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_303 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_304 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_166.coerceFont(coerce, 'textfont', layout.font); + _$lib_167.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -63909,15 +64583,15 @@ var _$text_defaults_303 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; -var _$handleXYDefaults_304 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { +var _$handleXYDefaults_305 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { var len, x = coerce('x'), y = coerce('y'); - var handleCalendarDefaults = _$registry_258.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_259.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); if(x) { @@ -63953,27 +64627,27 @@ var _$handleXYDefaults_304 = function handleXYDefaults(traceIn, traceOut, layout 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; -/* removed: var _$attributes_280 = require('./attributes'); */; -/* removed: var _$constants_286 = require('./constants'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_304 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_298 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_293 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_295 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_303 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_289 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_281 = require('./attributes'); */; +/* removed: var _$constants_287 = require('./constants'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_305 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_299 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_294 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_296 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_304 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_290 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_288 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_166.coerce(traceIn, traceOut, _$attributes_280, attr, dflt); + return _$lib_167.coerce(traceIn, traceOut, _$attributes_281, attr, dflt); } - var len = _$handleXYDefaults_304(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_305(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_286.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_287.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -63983,24 +64657,24 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_302.hasLines(traceOut)) { - _$lineDefaults_293(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_295(traceIn, traceOut, coerce); + if(_$subtypes_303.hasLines(traceOut)) { + _$lineDefaults_294(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_296(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_302.hasMarkers(traceOut)) { - _$markerDefaults_298(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_303.hasMarkers(traceOut)) { + _$markerDefaults_299(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_302.hasText(traceOut)) { - _$text_defaults_303(traceIn, traceOut, layout, coerce); + if(_$subtypes_303.hasText(traceOut)) { + _$text_defaults_304(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_302.hasMarkers(traceOut) || _$subtypes_302.hasText(traceOut)) { + if(_$subtypes_303.hasMarkers(traceOut) || _$subtypes_303.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -64008,8 +64682,8 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_289(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_302.hasLines(traceOut)) _$handleLineShapeDefaults_295(traceIn, traceOut, coerce); + _$fillColorDefaults_290(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_303.hasLines(traceOut)) _$handleLineShapeDefaults_296(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -64017,11 +64691,11 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_258.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_259.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_166.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_167.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -64036,10 +64710,10 @@ var _$supplyDefaults_287 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; /* removed: var _$color_45 = require('../../components/color'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; -var _$getTraceColor_290 = function getTraceColor(trace, di) { +var _$getTraceColor_291 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes @@ -64070,7 +64744,7 @@ var _$getTraceColor_290 = function getTraceColor(trace, di) { else { lc = (trace.line || {}).color; return (lc && _$color_45.opacity(lc) && - _$subtypes_302.hasLines(trace) && trace.line.width) ? + _$subtypes_303.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -64086,14 +64760,14 @@ var _$getTraceColor_290 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$fx_87 = require('../../components/fx'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$getTraceColor_290 = require('./get_trace_color'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$getTraceColor_291 = require('./get_trace_color'); */; /* removed: var _$color_45 = require('../../components/color'); */; -/* removed: var _$fillHoverText_288 = require('./fill_hover_text'); */; +/* removed: var _$fillHoverText_289 = require('./fill_hover_text'); */; -var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_292 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -64146,8 +64820,8 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_166.extendFlat(pointData, { - color: _$getTraceColor_290(trace, di), + _$lib_167.extendFlat(pointData, { + color: _$getTraceColor_291(trace, di), x0: xc - rad, x1: xc + rad, @@ -64160,8 +64834,8 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_288(di, trace, pointData); - _$registry_258.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_289(di, trace, pointData); + _$registry_259.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -64233,7 +64907,7 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { color = trace.line.color; } - _$lib_166.extendFlat(pointData, { + _$lib_167.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -64267,14 +64941,14 @@ var _$hoverPoints_291 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_294 = _$numerical_147.BADNUM; -/* removed: var _$lib_166 = require('../../lib'); */; -var __segmentsIntersect_294 = _$lib_166.segmentsIntersect; -var constrain = _$lib_166.constrain; -/* removed: var _$constants_286 = require('./constants'); */; +var __BADNUM_295 = _$numerical_147.BADNUM; +/* removed: var _$lib_167 = require('../../lib'); */; +var __segmentsIntersect_295 = _$lib_167.segmentsIntersect; +var constrain = _$lib_167.constrain; +/* removed: var _$constants_287 = require('./constants'); */; -var _$linePoints_294 = function linePoints(d, opts) { +var _$linePoints_295 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -64283,7 +64957,7 @@ var _$linePoints_294 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_286.minTolerance; + var minTolerance = _$constants_287.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -64321,7 +64995,7 @@ var _$linePoints_294 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_294 || y === __BADNUM_294) return di.intoCenter || false; + if(x === __BADNUM_295 || y === __BADNUM_295) return di.intoCenter || false; return [x, y]; } @@ -64329,7 +65003,7 @@ var _$linePoints_294 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_286.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_287.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -64341,7 +65015,7 @@ var _$linePoints_294 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_286.maxScreensAway; + var maxScreensAway = _$constants_287.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -64370,7 +65044,7 @@ var _$linePoints_294 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_294(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_295(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -64424,7 +65098,7 @@ var _$linePoints_294 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_166.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_167.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -64677,7 +65351,7 @@ var _$linePoints_294 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_296 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_297 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -64719,17 +65393,17 @@ var _$linkTraces_296 = function linkTraces(gd, plotinfo, cdscatter) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$registry_258 = require('../../registry'); */; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$registry_259 = require('../../registry'); */; +/* removed: var _$lib_167 = require('../../lib'); */; /* removed: var _$drawing_70 = require('../../components/drawing'); */; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -/* removed: var _$linePoints_294 = require('./line_points'); */; -/* removed: var _$linkTraces_296 = require('./link_traces'); */; -var __polygonTester_299 = _$polygon_178.tester; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +/* removed: var _$linePoints_295 = require('./line_points'); */; +/* removed: var _$linkTraces_297 = require('./link_traces'); */; +var __polygonTester_300 = _$polygon_179.tester; -var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_300 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -64738,9 +65412,8 @@ var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -64752,7 +65425,7 @@ var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_296(gd, plotinfo, cdscatter); + _$linkTraces_297(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -64791,12 +65464,12 @@ var _$plot_299 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_299(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_300(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_299(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_300(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -64851,7 +65524,7 @@ function createFills(gd, scatterlayer, plotinfo) { }); } -function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_300(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -64873,7 +65546,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran tr = _$d3_8.select(element); // error bars are at the bottom - _$registry_258.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_259.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -64885,7 +65558,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -64911,11 +65584,11 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_166.noop; + makeUpdate = _$lib_167.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_302.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_303.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -64952,7 +65625,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_294(cdscatter, { + segments = _$linePoints_295(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -64967,7 +65640,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_299(segments[i]); + trace._polygons[i] = __polygonTester_300(segments[i]); } if(segments.length) { @@ -64993,7 +65666,7 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_302.hasLines(trace) && pts.length > 1) { + if(_$subtypes_303.hasLines(trace) && pts.length > 1) { var el = _$d3_8.select(this); // This makes the coloring work correctly: @@ -65120,19 +65793,19 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = d[0].trace, s = _$d3_8.select(this), - showMarkers = _$subtypes_302.hasMarkers(trace), - showText = _$subtypes_302.hasText(trace); + showMarkers = _$subtypes_303.hasMarkers(trace), + showText = _$subtypes_303.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_166.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_167.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_166.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_167.identity; } // marker points @@ -65253,11 +65926,11 @@ function __plotOne_299(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_8.extent(_$lib_166.simpleMap(xa.range, xa.r2c)), - yr = _$d3_8.extent(_$lib_166.simpleMap(ya.range, ya.r2c)); + xr = _$d3_8.extent(_$lib_167.simpleMap(xa.range, xa.r2c)), + yr = _$d3_8.extent(_$lib_167.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_302.hasMarkers(trace)) return; + if(!_$subtypes_303.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -65272,7 +65945,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_302.hasMarkers(tracei) && + if(_$subtypes_303.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -65303,9 +65976,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_302 = require('./subtypes'); */; +/* removed: var _$subtypes_303 = require('./subtypes'); */; -var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_301 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -65316,7 +65989,7 @@ var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_302.hasMarkers(trace) && !_$subtypes_302.hasText(trace)); + var hasOnlyLines = (!_$subtypes_303.hasMarkers(trace) && !_$subtypes_303.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -65359,9 +66032,9 @@ var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { /* removed: var _$d3_8 = require('d3'); */; /* removed: var _$drawing_70 = require('../../components/drawing'); */; -/* removed: var _$registry_258 = require('../../registry'); */; +/* removed: var _$registry_259 = require('../../registry'); */; -function __style_301(gd, cd) { +function __style_302(gd, cd) { var s = cd ? cd[0].node3 : _$d3_8.select(gd).selectAll('g.trace.scatter'); s.style('opacity', function(d) { @@ -65380,7 +66053,7 @@ function __style_301(gd, cd) { s.selectAll('g.trace path.js-fill') .call(_$drawing_70.fillGroupStyle); - _$registry_258.getComponentMethod('errorbars', 'style')(s); + _$registry_259.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { @@ -65393,8 +66066,8 @@ function stylePoints(sel, trace, gd) { _$drawing_70.selectedTextStyle(txs, trace); } -var _$style_301 = { - style: __style_301, +var _$style_302 = { + style: __style_302, stylePoints: stylePoints }; @@ -65411,35 +66084,35 @@ var _$style_301 = { var Scatter = {}; -/* removed: var _$subtypes_302 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_302.hasLines; -Scatter.hasMarkers = _$subtypes_302.hasMarkers; -Scatter.hasText = _$subtypes_302.hasText; -Scatter.isBubble = _$subtypes_302.isBubble; +/* removed: var _$subtypes_303 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_303.hasLines; +Scatter.hasMarkers = _$subtypes_303.hasMarkers; +Scatter.hasText = _$subtypes_303.hasText; +Scatter.isBubble = _$subtypes_303.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_280; -Scatter.supplyDefaults = _$supplyDefaults_287; -Scatter.cleanData = _$cleanData_283; -Scatter.calc = _$calc_281.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_279; -Scatter.plot = _$plot_299; -Scatter.colorbar = _$colorbar_284; -Scatter.style = _$style_301.style; -Scatter.hoverPoints = _$hoverPoints_291; -Scatter.selectPoints = _$selectPoints_300; +Scatter.attributes = _$attributes_281; +Scatter.supplyDefaults = _$supplyDefaults_288; +Scatter.cleanData = _$cleanData_284; +Scatter.calc = _$calc_282.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_280; +Scatter.plot = _$plot_300; +Scatter.colorbar = _$colorbar_285; +Scatter.style = _$style_302.style; +Scatter.hoverPoints = _$hoverPoints_292; +Scatter.selectPoints = _$selectPoints_301; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_220; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_221; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_292 = Scatter; +var _$Scatter_293 = Scatter; var _$core_150 = {}; /** @@ -65453,7 +66126,7 @@ var _$core_150 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_150.version = '1.35.2'; +_$core_150.version = '1.36.0'; // inject promise polyfill _$es6Promise_9.polyfill(); @@ -65465,24 +66138,24 @@ _$plotcss_1; _$mathjax_config_151; // include registry module and expose register method -/* removed: var _$registry_258 = require('./registry'); */; -var register = _$core_150.register = _$registry_258.register; +/* removed: var _$registry_259 = require('./registry'); */; +var register = _$core_150.register = _$registry_259.register; // expose plot api methods -/* removed: var _$plot_api_196 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_196); +/* removed: var _$plot_api_197 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_197); for(var i = 0; i < methodNames.length; i++) { var __name_150 = methodNames[i]; - _$core_150[__name_150] = _$plot_api_196[__name_150]; + _$core_150[__name_150] = _$plot_api_197[__name_150]; register({ moduleType: 'apiMethod', name: __name_150, - fn: _$plot_api_196[__name_150] + fn: _$plot_api_197[__name_150] }); } // scatter is the only trace included by default -register(_$Scatter_292); +register(_$Scatter_293); // register all registrable components modules register([ @@ -65502,8 +66175,8 @@ register([ // locales en and en-US are required for default behavior register([ - _$localeEn_192, - _$localeEnUs_191 + _$localeEn_193, + _$localeEnUs_192 ]); // plot icons @@ -65512,9 +66185,9 @@ _$core_150.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk _$core_150.Plots = _$plots_250; _$core_150.Fx = _$fx_87; -_$core_150.Snapshot = _$Snapshot_263; -_$core_150.PlotSchema = _$plot_schema_200; -_$core_150.Queue = _$queue_180; +_$core_150.Snapshot = _$Snapshot_264; +_$core_150.PlotSchema = _$plot_schema_201; +_$core_150.Queue = _$queue_181; // export d3 used in the bundle _$core_150.d3 = _$d3_8; @@ -65543,15 +66216,15 @@ var _$core_4 = _$core_150; 'use strict'; /* removed: var _$fastIsnumeric_11 = require('fast-isnumeric'); */; -var __BADNUM_306 = _$numerical_147.BADNUM; +var __BADNUM_307 = _$numerical_147.BADNUM; -/* removed: var _$calcMarkerColorscale_285 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_279 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_282 = require('../scatter/calc_selection'); */; +/* removed: var _$calcMarkerColorscale_286 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_280 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_283 = require('../scatter/calc_selection'); */; -var ____306 = _$lib_166._; +var ____307 = _$lib_167._; -var _$calc_306 = function calc(gd, trace) { +var _$calc_307 = function calc(gd, trace) { var hasLocationData = Array.isArray(trace.locations); var len = hasLocationData ? trace.locations.length : trace._length; var calcTrace = new Array(len); @@ -65567,19 +66240,19 @@ var _$calc_306 = function calc(gd, trace) { var lat = trace.lat[i]; if(_$fastIsnumeric_11(lon) && _$fastIsnumeric_11(lat)) calcPt.lonlat = [+lon, +lat]; - else calcPt.lonlat = [__BADNUM_306, __BADNUM_306]; + else calcPt.lonlat = [__BADNUM_307, __BADNUM_307]; } } - _$arraysToCalcdata_279(calcTrace, trace); - _$calcMarkerColorscale_285(trace); - _$calcSelection_282(calcTrace, trace); + _$arraysToCalcdata_280(calcTrace, trace); + _$calcMarkerColorscale_286(trace); + _$calcSelection_283(calcTrace, trace); if(len) { calcTrace[0].t = { labels: { - lat: ____306(gd, 'lat:') + ' ', - lon: ____306(gd, 'lon:') + ' ' + lat: ____307(gd, 'lat:') + ' ', + lon: ____307(gd, 'lon:') + ' ' } }; } @@ -65598,20 +66271,20 @@ var _$calc_306 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_166 = require('../../lib'); */; +/* removed: var _$lib_167 = require('../../lib'); */; -/* removed: var _$subtypes_302 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_298 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_293 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_303 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_289 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$subtypes_303 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_299 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_294 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_304 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_290 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_305 = require('./attributes'); */; +/* removed: var _$attributes_306 = require('./attributes'); */; -var _$supplyDefaults_307 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_308 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_166.coerce(traceIn, traceOut, _$attributes_305, attr, dflt); + return _$lib_167.coerce(traceIn, traceOut, _$attributes_306, attr, dflt); } var len = handleLonLatLocDefaults(traceIn, traceOut, coerce); @@ -65624,22 +66297,22 @@ var _$supplyDefaults_307 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_302.hasLines(traceOut)) { - _$lineDefaults_293(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_303.hasLines(traceOut)) { + _$lineDefaults_294(traceIn, traceOut, defaultColor, layout, coerce); coerce('connectgaps'); } - if(_$subtypes_302.hasMarkers(traceOut)) { - _$markerDefaults_298(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_303.hasMarkers(traceOut)) { + _$markerDefaults_299(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_302.hasText(traceOut)) { - _$text_defaults_303(traceIn, traceOut, layout, coerce); + if(_$subtypes_303.hasText(traceOut)) { + _$text_defaults_304(traceIn, traceOut, layout, coerce); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_289(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_290(traceIn, traceOut, defaultColor, coerce); } }; @@ -65675,7 +66348,7 @@ function handleLonLatLocDefaults(traceIn, traceOut, coerce) { 'use strict'; -var _$eventData_308 = function eventData(out, pt) { +var _$eventData_309 = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; out.location = pt.loc ? pt.loc : null; @@ -65695,14 +66368,14 @@ var _$eventData_308 = function eventData(out, pt) { 'use strict'; /* removed: var _$fx_87 = require('../../components/fx'); */; -/* removed: var _$axes_209 = require('../../plots/cartesian/axes'); */; -var __BADNUM_309 = _$numerical_147.BADNUM; +/* removed: var _$axes_210 = require('../../plots/cartesian/axes'); */; +var __BADNUM_310 = _$numerical_147.BADNUM; -/* removed: var _$getTraceColor_290 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_288 = require('../scatter/fill_hover_text'); */; -/* removed: var _$attributes_305 = require('./attributes'); */; +/* removed: var _$getTraceColor_291 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_289 = require('../scatter/fill_hover_text'); */; +/* removed: var _$attributes_306 = require('./attributes'); */; -var _$hoverPoints_309 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_310 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -65715,7 +66388,7 @@ var _$hoverPoints_309 = function hoverPoints(pointData, xval, yval) { function distFn(d) { var lonlat = d.lonlat; - if(lonlat[0] === __BADNUM_309) return Infinity; + if(lonlat[0] === __BADNUM_310) return Infinity; if(isLonLatOverEdges(lonlat)) return Infinity; var pt = project(lonlat); @@ -65749,7 +66422,7 @@ var _$hoverPoints_309 = function hoverPoints(pointData, xval, yval) { pointData.lon = lonlat[0]; pointData.lat = lonlat[1]; - pointData.color = _$getTraceColor_290(trace, di); + pointData.color = _$getTraceColor_291(trace, di); pointData.extraText = getExtraText(trace, di, geo.mockAxis, cd[0].t.labels); return [pointData]; @@ -65759,7 +66432,7 @@ function getExtraText(trace, pt, axis, labels) { var hoverinfo = pt.hi || trace.hoverinfo; var parts = hoverinfo === 'all' ? - _$attributes_305.hoverinfo.flags : + _$attributes_306.hoverinfo.flags : hoverinfo.split('+'); var hasLocation = parts.indexOf('location') !== -1 && Array.isArray(trace.locations); @@ -65769,7 +66442,7 @@ function getExtraText(trace, pt, axis, labels) { var text = []; function format(val) { - return _$axes_209.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0'; + return _$axes_210.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0'; } if(hasLocation) { @@ -65783,13 +66456,13 @@ function getExtraText(trace, pt, axis, labels) { } if(hasText) { - _$fillHoverText_288(pt, trace, text); + _$fillHoverText_289(pt, trace, text); } return text.join('
'); } -var _$geojson_utils_162 = {}; +var _$geojson_utils_163 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -65801,7 +66474,7 @@ var _$geojson_utils_162 = {}; 'use strict'; -var __BADNUM_162 = _$numerical_147.BADNUM; +var __BADNUM_163 = _$numerical_147.BADNUM; /** * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays @@ -65814,7 +66487,7 @@ var __BADNUM_162 = _$numerical_147.BADNUM; * return line coords array (or array of arrays) * */ -_$geojson_utils_162.calcTraceToLineCoords = function(calcTrace) { +_$geojson_utils_163.calcTraceToLineCoords = function(calcTrace) { var trace = calcTrace[0].trace; var connectgaps = trace.connectgaps; @@ -65825,7 +66498,7 @@ _$geojson_utils_162.calcTraceToLineCoords = function(calcTrace) { var calcPt = calcTrace[i]; var lonlat = calcPt.lonlat; - if(lonlat[0] !== __BADNUM_162) { + if(lonlat[0] !== __BADNUM_163) { lineString.push(lonlat); } else if(!connectgaps && lineString.length > 0) { coords.push(lineString); @@ -65850,7 +66523,7 @@ _$geojson_utils_162.calcTraceToLineCoords = function(calcTrace) { * GeoJSON object * */ -_$geojson_utils_162.makeLine = function(coords) { +_$geojson_utils_163.makeLine = function(coords) { if(coords.length === 1) { return { type: 'LineString', @@ -65872,7 +66545,7 @@ _$geojson_utils_162.makeLine = function(coords) { * @return {object} out * GeoJSON object */ -_$geojson_utils_162.makePolygon = function(coords) { +_$geojson_utils_163.makePolygon = function(coords) { if(coords.length === 1) { return { type: 'Polygon', @@ -65899,7 +66572,7 @@ _$geojson_utils_162.makePolygon = function(coords) { * Blank GeoJSON object * */ -_$geojson_utils_162.makeBlank = function() { +_$geojson_utils_163.makeBlank = function() { return { type: 'Point', coordinates: [] @@ -65920,19 +66593,19 @@ _$geojson_utils_162.makeBlank = function() { /* removed: var _$drawing_70 = require('../../components/drawing'); */; /* removed: var _$color_45 = require('../../components/color'); */; -var __stylePoints_313 = _$style_301.stylePoints; +var __stylePoints_314 = _$style_302.stylePoints; -var _$style_313 = function style(gd, calcTrace) { - if(calcTrace) __styleTrace_313(gd, calcTrace); +var _$style_314 = function style(gd, calcTrace) { + if(calcTrace) __styleTrace_314(gd, calcTrace); }; -function __styleTrace_313(gd, calcTrace) { +function __styleTrace_314(gd, calcTrace) { var trace = calcTrace[0].trace; var s = calcTrace[0].node3; s.style('opacity', calcTrace[0].trace.opacity); - __stylePoints_313(s, trace, gd); + __stylePoints_314(s, trace, gd); // this part is incompatible with Drawing.lineGroupStyle s.selectAll('path.js-line') @@ -65964,23 +66637,23 @@ function __styleTrace_313(gd, calcTrace) { /* removed: var _$d3_8 = require('d3'); */; -/* removed: var _$lib_166 = require('../../lib'); */; -var __BADNUM_311 = _$numerical_147.BADNUM; -var __getTopojsonFeatures_311 = _$topojson_utils_190.getTopojsonFeatures; -var __locationToFeature_311 = _$geo_location_utils_161.locationToFeature; -/* removed: var _$geojson_utils_162 = require('../../lib/geojson_utils'); */; -/* removed: var _$subtypes_302 = require('../scatter/subtypes'); */; -/* removed: var _$style_313 = require('./style'); */; +/* removed: var _$lib_167 = require('../../lib'); */; +var __BADNUM_312 = _$numerical_147.BADNUM; +var __getTopojsonFeatures_312 = _$topojson_utils_191.getTopojsonFeatures; +var __locationToFeature_312 = _$geo_location_utils_162.locationToFeature; +/* removed: var _$geojson_utils_163 = require('../../lib/geojson_utils'); */; +/* removed: var _$subtypes_303 = require('../scatter/subtypes'); */; +/* removed: var _$style_314 = require('./style'); */; -var _$plot_311 = function plot(gd, geo, calcData) { +var _$plot_312 = function plot(gd, geo, calcData) { for(var i = 0; i < calcData.length; i++) { - __calcGeoJSON_311(calcData[i], geo.topojson); + __calcGeoJSON_312(calcData[i], geo.topojson); } function keyFunc(d) { return d[0].trace.uid; } function removeBADNUM(d, node) { - if(d.lonlat[0] === __BADNUM_311) { + if(d.lonlat[0] === __BADNUM_312) { _$d3_8.select(node).remove(); } } @@ -66001,12 +66674,12 @@ var _$plot_311 = function plot(gd, geo, calcData) { var s = calcTrace[0].node3 = _$d3_8.select(this); var trace = calcTrace[0].trace; - if(_$subtypes_302.hasLines(trace) || trace.fill !== 'none') { - var lineCoords = _$geojson_utils_162.calcTraceToLineCoords(calcTrace); + if(_$subtypes_303.hasLines(trace) || trace.fill !== 'none') { + var lineCoords = _$geojson_utils_163.calcTraceToLineCoords(calcTrace); var lineData = (trace.fill !== 'none') ? - _$geojson_utils_162.makePolygon(lineCoords) : - _$geojson_utils_162.makeLine(lineCoords); + _$geojson_utils_163.makePolygon(lineCoords) : + _$geojson_utils_163.makeLine(lineCoords); s.selectAll('path.js-line') .data([{geojson: lineData, trace: trace}]) @@ -66015,40 +66688,40 @@ var _$plot_311 = function plot(gd, geo, calcData) { .style('stroke-miterlimit', 2); } - if(_$subtypes_302.hasMarkers(trace)) { + if(_$subtypes_303.hasMarkers(trace)) { s.selectAll('path.point') - .data(_$lib_166.identity) + .data(_$lib_167.identity) .enter().append('path') .classed('point', true) .each(function(calcPt) { removeBADNUM(calcPt, this); }); } - if(_$subtypes_302.hasText(trace)) { + if(_$subtypes_303.hasText(trace)) { s.selectAll('g') - .data(_$lib_166.identity) + .data(_$lib_167.identity) .enter().append('g') .append('text') .each(function(calcPt) { removeBADNUM(calcPt, this); }); } // call style here within topojson request callback - _$style_313(gd, calcTrace); + _$style_314(gd, calcTrace); }); }; -function __calcGeoJSON_311(calcTrace, topojson) { +function __calcGeoJSON_312(calcTrace, topojson) { var trace = calcTrace[0].trace; if(!Array.isArray(trace.locations)) return; - var features = __getTopojsonFeatures_311(trace, topojson); + var features = __getTopojsonFeatures_312(trace, topojson); var locationmode = trace.locationmode; for(var i = 0; i < calcTrace.length; i++) { var calcPt = calcTrace[i]; - var feature = __locationToFeature_311(locationmode, calcPt.loc, features); + var feature = __locationToFeature_312(locationmode, calcPt.loc, features); - calcPt.lonlat = feature ? feature.properties.ct : [__BADNUM_311, __BADNUM_311]; + calcPt.lonlat = feature ? feature.properties.ct : [__BADNUM_312, __BADNUM_312]; } } @@ -66062,9 +66735,9 @@ function __calcGeoJSON_311(calcTrace, topojson) { 'use strict'; -/* removed: var _$subtypes_302 = require('../scatter/subtypes'); */; +/* removed: var _$subtypes_303 = require('../scatter/subtypes'); */; -var _$selectPoints_312 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_313 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -66073,7 +66746,7 @@ var _$selectPoints_312 = function selectPoints(searchInfo, polygon) { var di, lonlat, x, y, i; - var hasOnlyLines = (!_$subtypes_302.hasMarkers(trace) && !_$subtypes_302.hasText(trace)); + var hasOnlyLines = (!_$subtypes_303.hasMarkers(trace) && !_$subtypes_303.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { @@ -66116,15 +66789,15 @@ var _$selectPoints_312 = function selectPoints(searchInfo, polygon) { var ScatterGeo = {}; -ScatterGeo.attributes = _$attributes_305; -ScatterGeo.supplyDefaults = _$supplyDefaults_307; -ScatterGeo.colorbar = _$colorbar_284; -ScatterGeo.calc = _$calc_306; -ScatterGeo.plot = _$plot_311; -ScatterGeo.style = _$style_313; -ScatterGeo.hoverPoints = _$hoverPoints_309; -ScatterGeo.eventData = _$eventData_308; -ScatterGeo.selectPoints = _$selectPoints_312; +ScatterGeo.attributes = _$attributes_306; +ScatterGeo.supplyDefaults = _$supplyDefaults_308; +ScatterGeo.colorbar = _$colorbar_285; +ScatterGeo.calc = _$calc_307; +ScatterGeo.plot = _$plot_312; +ScatterGeo.style = _$style_314; +ScatterGeo.hoverPoints = _$hoverPoints_310; +ScatterGeo.eventData = _$eventData_309; +ScatterGeo.selectPoints = _$selectPoints_313; ScatterGeo.moduleType = 'trace'; ScatterGeo.name = 'scattergeo'; @@ -66135,7 +66808,7 @@ ScatterGeo.meta = { }; -var _$ScatterGeo_310 = ScatterGeo; +var _$ScatterGeo_311 = ScatterGeo; /** * Copyright 2012-2018, Plotly, Inc. @@ -66147,7 +66820,7 @@ var _$ScatterGeo_310 = ScatterGeo; 'use strict'; -var _$scattergeo_6 = _$ScatterGeo_310; +var _$scattergeo_6 = _$ScatterGeo_311; /** * Copyright 2012-2018, Plotly, Inc. diff --git a/dist/plotly-geo.min.js b/dist/plotly-geo.min.js index 4a5041c02c3..fc16f634f21 100644 --- a/dist/plotly-geo.min.js +++ b/dist/plotly-geo.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (geo - minified) v1.35.2 +* plotly.js (geo - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=e()}}(function(){var e={exports:{}};!function(){var t={version:"3.5.17"},n=[].slice,r=function(e){return n.call(e)},a=this.document;function i(e){return e&&(e.ownerDocument||e.document||e).documentElement}function o(e){return e&&(e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView)}if(a)try{r(a.documentElement.childNodes)[0].nodeType}catch(e){r=function(e){for(var t=e.length,n=new Array(t);t--;)n[t]=e[t];return n}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(e){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(e,t){s.call(this,e,t+"")},l.setAttributeNS=function(e,t,n){c.call(this,e,t,n+"")},u.setProperty=function(e,t,n){f.call(this,e,t+"",n)}}function d(e,t){return et?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},t.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},t.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,n){return d(e(t),n)}:e)},t.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},t.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},t.pairs=function(e){for(var t=0,n=e.length-1,r=e[0],a=new Array(n<0?0:n);t=0;)for(t=(r=e[a]).length;--t>=0;)n[--o]=r[t];return n};var m=Math.abs;function x(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n==1/0)throw new Error("infinite range");var r,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(n)),o=-1;if(e*=i,t*=i,(n*=i)<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=a.length)return n?n.call(r,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var r=[],o=i[n++];return t.forEach(function(t,a){r.push({key:t,values:e(a,n)})}),o?r.sort(function(e,t){return o(e.key,t.key)}):r}(o(t.map,e,0),0)},r.key=function(e){return a.push(e),r},r.sortKeys=function(e){return i[a.length-1]=e,r},r.sortValues=function(t){return e=t,r},r.rollup=function(e){return n=e,r},r},t.set=function(e){var t=new P;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},t.event=null,t.requote=function(e){return e.replace(q,"\\$&")};var q=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,H={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]};function V(e){return H(e,X),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var n=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}X.select=function(e){var t,n,r,a,i=[];e=Z(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),Q.hasOwnProperty(n)?{space:Q[n],local:e}:e}},X.attr=function(e,n){if(arguments.length<2){if("string"==typeof e){var r=this.node();return(e=t.ns.qualify(e)).local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}for(n in e)this.each($(n,e[n]));return this}return this.each($(e,n))},X.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=te(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},X.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?n?function(){var t=l(n,r(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:c:n?N:function(){var n,r=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(n=a.match(r)){var i=this[a];this.removeEventListener(n[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=X.append,de.empty=X.empty,de.node=X.node,de.call=X.call,de.size=X.size,de.select=function(e){for(var t,n,r,a,i,o=[],l=-1,s=this.length;++l=r&&(r=t+1);!(o=l[r])&&++r0?1:e<0?-1:0}function ze(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function De(e){return e>1?0:e<-1?Ae:Math.acos(e)}function Ee(e){return e>1?Ce:e<-1?-Ce:Math.asin(e)}function Ne(e){return((e=Math.exp(e))+1/e)/2}function Re(e){return(e=Math.sin(e/2))*e}var Ie=Math.SQRT2;t.interpolateZoom=function(e,t){var n,r,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function C(e){v++||e({type:"zoomstart"})}function S(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function P(e){--v||(e({type:"zoomend"}),n=null)}function O(){var e=this,n=_.of(e,arguments),r=0,a=t.select(o(e)).on(m,function(){r=1,A(t.mouse(e),i),S(n)}).on(x,function(){a.on(m,null).on(x,null),l(r),P(n)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),C(n)}function z(){var e,n=this,r=_.of(n,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(n),h=xe(n);function p(){var r=t.touches(n);return e=d.k,r.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),r}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var r=t.event.changedTouches,o=0,f=r.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(n);ll.call(n);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?r+(a-r)*e/60:e<180?a:e<240?r+(a-r)*(240-e)/60:r}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,r=2*(n=n<0?0:n>1?1:n)-(a=n<=.5?n*(1+t):n+t-n*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,n,r){return this instanceof Ge?(this.h=+e,this.c=+n,void(this.l=+r)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Ze?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,n,r)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new qe;function Xe(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Ze(n,Math.cos(e*=Se)*t,Math.sin(e)*t)}function Ze(e,t,n){return this instanceof Ze?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof Ze?new Ze(e.l,e.a,e.b):e instanceof Ge?Xe(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Ze(e,t,n)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Xe(this.h,this.c,this.l).rgb()},t.lab=Ze;var We=18,Je=.95047,Qe=1,$e=1.08883,Ke=Ze.prototype=new qe;function et(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return new it(at(3.2404542*(a=nt(a)*Je)-1.5371385*(r=nt(r)*Qe)-.4985314*(i=nt(i)*$e)),at(-.969266*a+1.8760108*r+.041556*i),at(.0556434*a-.2040259*r+1.0572252*i))}function tt(e,t,n){return e>0?new Ge(Math.atan2(n,t)*Pe,Math.sqrt(t*t+n*n),e):new Ge(NaN,NaN,e)}function nt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function rt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,n){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,n)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Ze(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Ze(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new qe;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new He(r,a,s)}function dt(e,t,n){var r=rt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(n=ht(n)))/Je),a=rt((.2126729*e+.7151522*t+.072175*n)/Qe);return Ze(116*a-16,500*(r-a),200*(a-rt((.0193339*e+.119192*t+.9503041*n)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,a=30;return t||n||r?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var n=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=n}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(n=null==e?null:e+"",o):n},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),c.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=n&&c.overrideMimeType&&c.overrideMimeType(n),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==r?null:r),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(O),t.dsv=function(e,t){var n=new RegExp('["'+e+"\n]"),r=e.charCodeAt(0);function a(e,n,r){arguments.length<3&&(r=n,n=null);var a=mt(e,t,null==n?i:o(n),r);return a.row=function(e){return arguments.length?a.response(null==(n=e)?i:o(e)):n},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return n.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var n;return a.parseRows(e,function(e,r){if(n)return n(e,r-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(a(e),n)}:a})},a.parseRows=function(e,t){var n,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(At,t)),_t=0):(_t=1,kt(At))}function Tt(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}});t.formatPrefix=function(e,n){var r=0;return(e=+e)&&(e<0&&(e*=-1),n&&(e=t.round(e,Ct(e,n))),r=1+Math.floor(1e-12+Math.log(e)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),St[8+r/3]};var Pt=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Ot=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,n){return(e=t.round(e,Ct(e,n))).toFixed(Math.max(0,Math.min(20,Ct(e*(1+1e-15),n))))}});function zt(e){return e+""}var Dt=t.time={},Et=Date;function Nt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Nt.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(){Rt.setUTCDate.apply(this._,arguments)},setDay:function(){Rt.setUTCDay.apply(this._,arguments)},setFullYear:function(){Rt.setUTCFullYear.apply(this._,arguments)},setHours:function(){Rt.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Rt.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Rt.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Rt.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Rt.setUTCSeconds.apply(this._,arguments)},setTime:function(){Rt.setTime.apply(this._,arguments)}};var Rt=Date.prototype;function It(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o68?1900:2e3),n+a[0].length):-1}function Jt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Qt(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function $t(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Kt(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function en(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function tn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function nn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function rn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function an(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=m(t)/60|0,a=m(t)%60;return n+Ht(r,"0",2)+Ht(a,"0",2)}function on(e,t,n){qt.lastIndex=0;var r=qt.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ln(e){for(var t=e.length,n=-1;++n0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(n-=l,n+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(r)}:O;return function(e){var r=Pt.exec(e),a=r[1]||" ",l=r[2]||">",s=r[3]||"-",c=r[4]||"",u=r[5],f=+r[6],d=r[7],h=r[8],p=r[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=Ot.get(p)||zt;var b=u&&d;return function(e){var r=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),r=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=n+e.substring(k+1);!u&&d&&(_=o(_,1/0));var A=v.length+_.length+w.length+(b?0:i.length),T=A"===l?T+i+e:"^"===l?T.substring(0,A>>=1)+i+e+T.substring(A):i+(b?e:T+e))+r}}}(e),timeFormat:function(e){var n=e.dateTime,r=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function n(n){for(var r,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in jt?t.charAt(l++):o])||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}u.utc=function(e){var t=u(e);function n(e){try{var n=new(Et=Nt);return n._=e,t(n)}finally{Et=Date}}return n.parse=function(e){try{Et=Nt;var n=t.parse(e);return n&&n._}finally{Et=Date}},n.toString=t.toString,n},u.multi=u.utc.multi=ln;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(n),d:function(e,t){return Ht(e.getDate(),t,2)},e:function(e,t){return Ht(e.getDate(),t,2)},H:function(e,t){return Ht(e.getHours(),t,2)},I:function(e,t){return Ht(e.getHours()%12||12,t,2)},j:function(e,t){return Ht(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return Ht(e.getMilliseconds(),t,3)},m:function(e,t){return Ht(e.getMonth()+1,t,2)},M:function(e,t){return Ht(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return Ht(e.getSeconds(),t,2)},U:function(e,t){return Ht(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ht(Dt.mondayOfYear(e),t,2)},x:u(r),X:u(a),y:function(e,t){return Ht(e.getFullYear()%100,t,2)},Y:function(e,t){return Ht(e.getFullYear()%1e4,t,4)},Z:an,"%":function(){return"%"}},w={a:function(e,t,n){g.lastIndex=0;var r=g.exec(t.slice(n));return r?(e.w=v.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(e,t,n){h.lastIndex=0;var r=h.exec(t.slice(n));return r?(e.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.m=m.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(e,t,n){return f(e,_.c.toString(),t,n)},d:$t,e:$t,H:en,I:en,j:Kt,L:rn,m:Qt,M:tn,p:function(e,t,n){var r=d.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)},S:nn,U:Yt,w:Gt,W:Xt,x:function(e,t,n){return f(e,_.x.toString(),t,n)},X:function(e,t,n){return f(e,_.X.toString(),t,n)},y:Wt,Y:Zt,Z:Jt,"%":on};return u}(e)}};var sn=t.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"]});function cn(){}t.format=sn.numberFormat,t.geo={},cn.prototype={s:0,t:0,add:function(e){fn(e,this.t,un),fn(un.s,this.s,this),this.s?this.t+=un.t:this.s=un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var un=new cn;function fn(e,t,n){var r=n.s=e+t,a=r-e,i=r-a;n.t=e-i+(t-a)}function dn(e,t){e&&pn.hasOwnProperty(e.type)&&pn[e.type](e,t)}t.geo.stream=function(e,t){e&&hn.hasOwnProperty(e.type)?hn[e.type](e,t):dn(e,t)};var hn={Feature:function(e,t){dn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++r=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=r*s+u*Math.cos(l),d=u*o*Math.sin(l);Sn.add(Math.atan2(d,f)),n=e,r=s,a=c}Pn.point=function(o,l){Pn.point=i,n=(e=o)*Se,r=Math.cos(l=(t=l)*Se/2+Ae/4),a=Math.sin(l)},Pn.lineEnd=function(){i(e,t)}}function zn(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function Dn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function En(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Nn(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Rn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function In(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Fn(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function jn(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(n=-90),f[0]=e,f[1]=r}};function h(t,i){u.push(f=[e=t,r=t]),ia&&(a=i)}function p(t,o){var l=zn([t*Se,o*Se]);if(s){var c=En(s,l),u=En([c[1],-c[0],0],c);In(u),u=Fn(u);var f=t-i,d=f>0?1:-1,p=u[0]*Pe*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t):r>=e?(tr&&(r=t)):t>i?_(e,t)>_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=r,d.point=h,s=null}function y(e,t){if(s){var n=e-i;c+=m(n)>180?n+(n>0?360:-360):n}else o=e,l=t;Pn.point(e,t),p(e,t)}function x(){Pn.lineStart()}function b(){y(o,l),Pn.lineEnd(),m(c)>ke&&(e=-(r=180)),f[0]=e,f[1]=r,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],r=g[1])}return u=f=null,e===1/0||n===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,n],[r,a]]}}(),t.geo.centroid=function(e){mn=xn=bn=_n=wn=kn=Mn=An=Tn=Ln=Cn=0,t.geo.stream(e,Bn);var n=Tn,r=Ln,a=Cn,i=n*n+r*r+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else r(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Wn(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r=0?1:-1,k=w*_,M=k>Ae,A=p*x;if(Sn.add(Math.atan2(A*w*Math.sin(k),g*b+A*Math.cos(k))),i+=M?_+w*Te:_,M^d>=n^y>=n){var T=En(zn(f),zn(e));In(T);var L=En(a,T);In(L);var C=(M^_>=0?-1:1)*Ee(L[2]);(r>C||r===C&&(T[0]||T[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&n.push(n.pop().concat(n.shift())),l.push(n.filter($n))}return u}}function $n(e){return e.length>1}function Kn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:N,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function er(e,t){return((e=e.x)[0]<0?e[1]-Ce-ke:Ce-e[1])-((t=t.x)[0]<0?t[1]-Ce-ke:Ce-t[1])}var tr=Qn(Xn,function(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Ae:-Ae,s=m(i-n);m(s-Ae)0?Ce:-Ce),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Ae&&(m(n-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}(n,r,i,o),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),t=0),e.point(n=i,r=o),a=l},lineEnd:function(){e.lineEnd(),n=r=NaN},clean:function(){return 2-t}}},function(e,t,n,r){var a;if(null==e)a=n*Ce,r.point(-Ae,a),r.point(0,a),r.point(Ae,a),r.point(Ae,0),r.point(Ae,-a),r.point(0,-a),r.point(-Ae,-a),r.point(-Ae,0),r.point(-Ae,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rr=1e9;function ar(e,n,r,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=Kn(),w=nr(e,n,r,a),k={point:T,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=T,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var n=function(e){for(var t=0,n=u.length,r=e[1],a=0;ar&&ze(c,i,e)>0&&++t:i[1]<=r&&ze(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),r=x&&n,i=c.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Zn(c,o,n,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:r,u>1?a:n)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function A(t,i){return e<=t&&t<=r&&n<=i&&i<=a}function T(e,t){A(e,t)&&s.point(e,t)}function L(e,t){var n=A(e=Math.max(-rr,Math.min(rr,e)),t=Math.max(-rr,Math.min(rr,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=n,m=!1,n&&(s.lineStart(),s.point(e,t));else if(n&&y)s.point(e,t);else{var r={a:{x:g,y:v},b:{x:e,y:t}};w(r)?(y||(s.lineStart(),s.point(r.a.x,r.a.y)),s.point(r.b.x,r.b.y),n||s.lineEnd(),x=!1):n&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=n}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-r)0?2:1:m(t[1]-n)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}}function ir(e){var t=0,n=Ae/3,r=Lr(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Ae/180,n=e[1]*Ae/180):[t/Ae*180,n/Ae*180]},a}function or(e,t){var n=Math.sin(e),r=(n+Math.sin(t))/2,a=1+n*(2*r-n),i=Math.sqrt(a)/r;function o(e,t){var n=Math.sqrt(a-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),i-n*Math.cos(e)]}return o.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,Ee((a-(e*e+n*n)*r*r)/(2*r))]},o}t.geo.clipExtent=function(){var e,t,n,r,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=ar(e=+l[0][0],t=+l[0][1],n=+l[1][0],r=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return ir(or)}).raw=or,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,n,r,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,n){e=[t,n]}};function c(t){var i=t[0],o=t[1];return e=null,n(i,o),e||(r(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),n=i.translate(),r=(e[0]-n[0])/t,a=(e[1]-n[1])/t;return(a>=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return n=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,r=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var lr,sr,cr,ur,fr,dr,hr={point:N,lineStart:N,lineEnd:N,polygonStart:function(){sr=0,hr.lineStart=pr},polygonEnd:function(){hr.lineStart=hr.lineEnd=hr.point=N,lr+=m(sr/2)}};function pr(){var e,t,n,r;function a(e,t){sr+=r*e-n*t,n=e,r=t}hr.point=function(i,o){hr.point=a,e=n=i,t=r=o},hr.lineEnd=function(){a(e,t)}}var gr={point:function(e,t){efr&&(fr=e);tdr&&(dr=t)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vr(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yr,mr={point:xr,lineStart:br,lineEnd:_r,polygonStart:function(){mr.lineStart=wr},polygonEnd:function(){mr.point=xr,mr.lineStart=br,mr.lineEnd=_r}};function xr(e,t){bn+=e,_n+=t,++wn}function br(){var e,t;function n(n,r){var a=n-e,i=r-t,o=Math.sqrt(a*a+i*i);kn+=o*(e+n)/2,Mn+=o*(t+r)/2,An+=o,xr(e=n,t=r)}mr.point=function(r,a){mr.point=n,xr(e=r,t=a)}}function _r(){mr.point=xr}function wr(){var e,t,n,r;function a(e,t){var a=e-n,i=t-r,o=Math.sqrt(a*a+i*i);kn+=o*(n+e)/2,Mn+=o*(r+t)/2,An+=o,Tn+=(o=r*e-n*t)*(n+e),Ln+=o*(r+t),Cn+=3*o,xr(n=e,r=t)}mr.point=function(i,o){mr.point=a,xr(e=n=i,t=r=o)},mr.lineEnd=function(){a(e,t)}}function kr(e){var t=.5,n=Math.cos(30*Se),r=16;function a(t){return(r?function(t){var n,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(n,r){n=e(n,r),t.point(n[0],n[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(n,a){var o=zn([n,a]),l=e(n,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=n,h=o[0],p=o[1],g=o[2],r,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(n=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,n,l,s,c,r,t),v.lineEnd=b,b()}return v}:function(t){return Ar(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})})(t)}function i(r,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-r,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,A=Math.sqrt(w*w+k*k+M*M),T=Math.asin(M/=A),L=m(m(M)-1)t||m((x*O+b*z)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mr(e){this.stream=e}function Ar(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Tr(e){return Lr(function(){return e})()}function Lr(e){var n,r,a,i,o,l,s=kr(function(e,t){return[(e=n(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=tr,x=O,b=null,_=null;function w(e){return[(e=a(e[0]*Se,e[1]*Se))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Pe,e[1]*Pe]}function M(){a=Yn(r=Or(p,g,v),n);var e=n(d,h);return i=u-e[0]*c,o=f+e[1]*c,A()}function A(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Cr(y(r,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,tr):function(e){var t=Math.cos(e),n=t>0,r=m(t)>ke;return Qn(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=n?g?0:o(f,d):g?o(f+(f<0?Ae:-Ae),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(jn(t,h)||jn(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(r&&t&&n^g){var y;v&l||!(y=i(p,t,!0))||(u=0,n?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&jn(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Nr(e,6*Se),n?[0,-e]:[-Ae,e-Ae]);function a(e,n){return Math.cos(e)*Math.cos(n)>t}function i(e,n,r){var a=[1,0,0],i=En(zn(e),zn(n)),o=Dn(i,i),l=i[0],s=o-l*l;if(!s)return!r&&e;var c=t*o/s,u=-t*l/s,f=En(a,i),d=Rn(a,c);Nn(d,Rn(i,u));var h=f,p=Dn(d,h),g=Dn(h,h),v=p*p-g*(Dn(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=Rn(h,(-p-y)/g);if(Nn(x,d),x=Fn(x),!r)return x;var b,_=e[0],w=n[0],k=e[1],M=n[1];w<_&&(b=_,_=w,w=b);var A=w-_,T=m(A-Ae)0^x[1]<(m(x[0]-_)Ae^(_<=x[0]&&x[0]<=w)){var L=Rn(h,(-p+y)/g);return Nn(L,d),[x,Fn(L)]}}}function o(t,r){var a=n?e:Ae-e,i=0;return t<-a?i|=1:t>a&&(i|=2),r<-a?i|=4:r>a&&(i|=8),i}}((b=+e)*Se),A()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?ar(e[0][0],e[0][1],e[1][0],e[1][1]):O,A()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Se,h=e[1]%360*Se,M()):[d*Pe,h*Pe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Se,g=e[1]%360*Se,v=e.length>2?e[2]%360*Se:0,M()):[p*Pe,g*Pe,v*Pe]},t.rebind(w,s,"precision"),function(){return n=e.apply(this,arguments),w.invert=n.invert&&k,M()}}function Cr(e){return Ar(e,function(t,n){e.point(t*Se,n*Se)})}function Sr(e,t){return[e,t]}function Pr(e,t){return[e>Ae?e-Te:e<-Ae?e+Te:e,t]}function Or(e,t,n){return e?t||n?Yn(Dr(e),Er(t,n)):Dr(e):t||n?Er(t,n):Pr}function zr(e){return function(t,n){return[(t+=e)>Ae?t-Te:t<-Ae?t+Te:t,n]}}function Dr(e){var t=zr(e);return t.invert=zr(-e),t}function Er(e,t){var n=Math.cos(e),r=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*n+l*r;return[Math.atan2(s*a-u*i,l*n-c*r),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*n+u*r),Ee(u*n-l*r)]},o}function Nr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=Rr(n,a),i=Rr(n,i),(o>0?ai)&&(a+=o*Te)):(a=e+o*Te,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Se:0),t.invert=function(t){return(t=e.invert(t[0]*Se,t[1]*Se))[0]*=Pe,t[1]*=Pe,t},t},Pr.invert=Sr,t.geo.circle=function(){var e,t,n=[0,0],r=6;function a(){var e="function"==typeof n?n.apply(this,arguments):n,r=Or(-e[0]*Se,-e[1]*Se,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=r(e,t)),e[0]*=Pe,e[1]*=Pe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(n=e,a):n},a.angle=function(n){return arguments.length?(t=Nr((e=+n)*Se,r*Se),a):e},a.precision=function(n){return arguments.length?(t=Nr(e*Se,(r=+n)*Se),a):r},a.angle(90)},t.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Se,a=e[1]*Se,i=t[1]*Se,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((n=f*o)*n+(n=c*u-s*f*l)*n),s*u+c*f*l)},t.geo.graticule=function(){var e,n,r,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,r,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(n/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(r).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],r=+e[1][0],s=+e[0][1],l=+e[1][1],a>r&&(e=a,a=r,r=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[r,l]]},x.minorExtent=function(t){return arguments.length?(n=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],n>e&&(t=n,n=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[n,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Ir(o,i,90),u=Fr(n,e,y),f=Ir(s,l,90),d=Fr(a,r,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,n,r=jr,a=Br;function i(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||r.apply(this,arguments),n||a.apply(this,arguments))},i.source=function(t){return arguments.length?(r=t,e="function"==typeof t?null:t,i):r},i.target=function(e){return arguments.length?(a=e,n="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return n=e[0]*Se,r=e[1]*Se,a=t[0]*Se,i=t[1]*Se,o=Math.cos(r),l=Math.sin(r),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(n),f=o*Math.sin(n),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Re(i-r)+o*s*Re(a-n))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,n=Math.sin(p-e)*g,r=n*u+t*d,a=n*f+t*h,i=n*l+t*c;return[Math.atan2(a,r)*Pe,Math.atan2(i,Math.sqrt(r*r+a*a))*Pe]}:function(){return[n*Pe,r*Pe]}).distance=p,v;var n,r,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yr=0,t.geo.stream(e,qr),yr};var qr={sphere:N,point:N,lineStart:function(){var e,t,n;function r(r,a){var i=Math.sin(a*=Se),o=Math.cos(a),l=m((r*=Se)-e),s=Math.cos(l);yr+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=n*i-t*o*s)*l),t*i+n*o*s),e=r,t=i,n=o}qr.point=function(a,i){e=a*Se,t=Math.sin(i*=Se),n=Math.cos(i),qr.point=r},qr.lineEnd=function(){qr.point=qr.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function Hr(e,t){function n(t,n){var r=Math.cos(t),a=Math.cos(n),i=e(r*a);return[i*a*Math.sin(t),i*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),a=t(r),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,r*o),Math.asin(r&&n*i/r)]},n}var Vr=Hr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Tr(Vr)}).raw=Vr;var Ur=Hr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},O);function Gr(e,t){var n=Math.cos(e),r=function(e){return Math.tan(Ae/4+e/2)},a=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),i=n*Math.pow(r(e),a)/a;if(!a)return Zr;function o(e,t){i>0?t<-Ce+ke&&(t=-Ce+ke):t>Ce-ke&&(t=Ce-ke);var n=i/Math.pow(r(t),a);return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}return o.invert=function(e,t){var n=i-t,r=Oe(a)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/a,2*Math.atan(Math.pow(i/r,1/a))-Ce]},o}function Yr(e,t){var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),a=n/r+e;if(m(r)1&&ze(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function na(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Tr(Qr)}).raw=Qr,$r.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Ce]},(t.geo.transverseMercator=function(){var e=Wr($r),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):[(e=n())[0],e[1],e[2]-90]},n([0,0,90])}).raw=$r,t.geom={},t.geom.hull=function(e){var t=Kr,n=ea;if(arguments.length)return r(e);function r(e){if(e.length<3)return[];var r,a=vt(t),i=vt(n),o=e.length,l=[],s=[];for(r=0;r=0;--r)h.push(e[l[c[r]][2]]);for(r=+f;rke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){r>-ke?(t=l.P,n=l):a>-ke?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||n){if(t===n)return ka(t),n=pa(t.site),ca.insert(s,n),s.edge=n.edge=Ta(t.site,s.site),wa(t),void wa(n);if(n){ka(t),ka(n);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=n.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(n.edge,c,p,b),s.edge=Ta(c,e,null,b),n.edge=Ta(e,p,null,b),wa(t),wa(n)}else s.edge=Ta(t.site,s.site)}}function ma(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-1/0;var l=(n=o.site).x,s=n.y,c=s-t;if(!c)return l;var u=l-r,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+r:(r+l)/2}function xa(e,t){var n=e.N;if(n)return ma(n,t);var r=e.site;return r.y===t?r.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,a=e.site,i=n.site;if(r!==i){var o=a.x,l=a.y,s=r.x-o,c=r.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){Pa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};n={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/r,y:s};n={x:(c-a)/r,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xke||m(a-n)>ke)&&(l.splice(o,0,new Ca((y=i.site,x=u,b=m(r-f)ke?{x:f,y:m(t-f)ke?{x:m(n-p)ke?{x:d,y:m(t-d)ke?{x:m(n-h)=n&&c.x<=a&&c.y>=r&&c.y<=o?[[n,o],[a,o],[a,r],[n,r]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(n,r){for(var a,i,o,l,s=n.site,c=n.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:qa(n,r)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,n,r,a,i,o,l){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-n)+m(c-r)<.01)A(e,t,n,r,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,A(e,u,s,c,a,i,o,l),A(e,t,n,r,a,i,o,l)}else e.x=n,e.y=r,e.point=t}else A(e,t,n,r,a,i,o,l)}function A(e,t,n,r,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=n>=s,f=r>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,n,r,a,i,o,l)}w>k?v=p+w:g=h+k;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(T.visit=function(e){!function e(t,n,r,a,i,o){if(!t(n,r,a,i,o)){var l=.5*(r+i),s=.5*(a+o),c=n.nodes;c[0]&&e(t,c[0],r,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],r,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,T,h,p,g,v)},T.find=function(e){return function(e,t,n,r,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(r=t.interpolators[a](e,n)););return r}function Ya(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function ti(e){return 1-Math.cos(e*Ce)}function ni(e){return Math.pow(2,10*(e-1))}function ri(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function oi(e){var t,n,r,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(r=-l)*(n=a)[0],t[1]+=r*n[1],t))||0;a[0]*i[1]=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"in";return a=Za.get(a)||Xa,i=Wa.get(i)||O,t=i(a.apply(null,n.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,n){e=t.hcl(e),n=t.hcl(n);var r=e.h,a=e.c,i=e.l,o=n.h-r,l=n.c-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.c:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Xe(r+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,n){e=t.hsl(e),n=t.hsl(n);var r=e.h,a=e.s,i=e.l,o=n.h-r,l=n.s-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.s:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(r+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,n){e=t.lab(e),n=t.lab(n);var r=e.l,a=e.a,i=e.b,o=n.l-r,l=n.a-a,s=n.b-i;return function(e){return et(r+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var n=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,n){var r=[],a=[];return e=t.transform(e),n=t.transform(n),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push("translate(",null,",",null,")");r.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else(t[0]||t[1])&&n.push("translate("+t+")")}(e.translate,n.translate,r,a),function(e,t,n,r){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(ui(n)+"rotate(",null,")")-2,x:qa(e,t)})):t&&n.push(ui(n)+"rotate("+t+")")}(e.rotate,n.rotate,r,a),function(e,t,n,r){e!==t?r.push({i:n.push(ui(n)+"skewX(",null,")")-2,x:qa(e,t)}):t&&n.push(ui(n)+"skewX("+t+")")}(e.skew,n.skew,r,a),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(ui(n)+"scale(",null,",",null,")");r.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(ui(n)+"scale("+t+")")}(e.scale,n.scale,r,a),e=n=null,function(e){for(var t,n=-1,i=a.length;++n0?r=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:r=0})):t>0&&(s.start({type:"start",alpha:r=t}),e=Mt(l.tick)),l):r},l.start=function(){var e,t,n,r=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)n.push(a[r])}function Ai(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;n&&(i.value=0),i.children=c}else n&&(i.value=+n.call(r,i,i.depth)||0),delete i.children;return Ai(a,function(t){var r,a;e&&(r=t.children)&&r.sort(e),n&&(a=t.parent)&&(a.value+=t.value)}),l}return r.sort=function(t){return arguments.length?(e=t,r):e},r.children=function(e){return arguments.length?(t=e,r):t},r.value=function(e){return arguments.length?(n=e,r):n},r.revalue=function(e){return n&&(Mi(e,function(e){e.children&&(e.value=0)}),Ai(e,function(e){var t;e.children||(e.value=+n.call(r,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},r},t.layout.partition=function(){var e=t.layout.hierarchy(),n=[1,1];function r(t,r){var a=e.call(this,t,r);return function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(r=t.value?r/t.value:0;++cl&&(l=r),o.push(r)}for(n=0;na&&(r=n,a=t);return r}function ji(e){return e.reduce(Bi,0)}function Bi(e,t){return e+t[1]}function qi(e,t){return Hi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Hi(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Xi(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function Zi(e){if((t=e.children)&&(s=t.length)){var t,n,r,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(n=t[0]).x=-n.r,n.y=0,x(n),s>1&&((r=t[1]).x=r.r,r.y=0,x(r),s>2))for(Qi(n,r,a=t[2]),x(a),Gi(n,a),n._pack_prev=a,Gi(a,r),r=n._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(n=e,i):n},i.range=function(e){return arguments.length?(r=vt(e),i):r},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return Hi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,n=t.layout.hierarchy().sort(Ui),r=0,a=[1,1];function i(t,i){var o=n.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ai(l,function(e){e.r=+u(e.value)}),Ai(l,Zi),r){var f=r*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ai(l,function(e){e.r+=f}),Ai(l,Zi),Ai(l,function(e){e.r-=f})}return function e(t,n,r,a){var i=t.children;t.x=n+=a*t.x;t.y=r+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=n(d,h)/2-d.x,v=r[0]/(h.x+n(h,d)/2+g),y=r[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,r=e.parent.children,a=e.i?r[e.i-1]:null;if(t.length){!function(e){var t,n=0,r=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=n,t.m+=n,n+=t.s+(r+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+n(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+n(e._,a._));e.parent.A=function(e,t,r){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+n(l._,i._))>0&&(to(no(l,e,r),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,r=e)}return r}(e,a,e.parent.A||r[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=r[0],e.y=e.depth*r[1]}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e)?s:null,i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null==(r=e)?null:s,i):a?r:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),n=$i,r=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ai(c,function(e){var r=e.children;r&&r.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(r),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(r)):(e.x=l?u+=n(e,l):0,e.y=0,l=e)});var f=function e(t){var n=t.children;return n&&n.length?e(n[0]):t}(c),d=function e(t){var n,r=t.children;return r&&(n=r.length)?e(r[n-1]):t}(c),h=f.x-n(f,d)/2,p=d.x+n(d,f)/2;return Ai(c,a?function(e){e.x=(e.x-c.x)*r[0],e.y=(c.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(c.y?e.y/c.y:1))*r[1]}),s}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e),i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null!=(r=e),i):a?r:null},ki(i,e)},t.layout.treemap=function(){var e,n=t.layout.hierarchy(),r=Math.round,a=[1,1],i=null,o=ro,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var n,r,a=-1,i=e.length;++a0;)l.push(n=c[a-1]),l.area+=n.area,"squarify"!==s||(r=h(l,g))<=d?(c.pop(),d=r):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var n,r=o(e),a=t.slice(),i=[];for(u(a,r.dx*r.dy/e.value),i.area=0;n=a.pop();)i.push(n),i.area+=n.area,null!=n.z&&(p(i,n.z?r.dx:r.dy,r,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return t*=t,(r*=r)?Math.max(t*a*c/r,r/(t*i*c)):1/0}function p(e,t,n,a){var i,o=-1,l=e.length,s=n.x,c=n.y,u=t?r(e.area/t):0;if(t==n.dx){for((a||u>n.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++o1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var n=t.random.irwinHall(e);return function(){return n()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;n2?fo:lo,l=a?hi:di;return i=e(t,n,l,r),o=e(n,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(n=e,l()):n};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(r=e,l()):r};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,n){return yo(t,e,n)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,n,r,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(n,r,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(r)}function l(e){return a?Math.pow(r,e):-Math.pow(r,-e)}function s(e){return n(o(e))}s.invert=function(e){return l(n.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,n.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(r=+e,n.domain(i.map(o)),s):r};s.nice=function(){var e=so(i.map(o),a?Math:_o);return n.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],n=e[0],s=e[1],c=Math.floor(o(n)),u=Math.ceil(o(s)),f=r%1?2:r;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,n){if(!arguments.length)return bo;arguments.length<2?n=bo:"function"!=typeof n&&(n=t.format(n));var a=Math.max(1,r*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*r0?a[e-1]:n[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,A,T=0,L=0,C=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=r===Co?Math.sqrt(l*l+c*c):+r.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(T=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Ae?0:1;if(L&&Eo(m,x,b,_)===h^S){var P=(u+f)/2;m=c*Math.cos(P),x=c*Math.sin(P),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-T),k=l*Math.sin(f-T),M=l*Math.cos(u+T),A=l*Math.sin(u+T);var O=Math.abs(u-f+2*T)<=Ae?0:1;if(T&&Eo(w,k,M,A)===1-h^O){var z=(u+f)/2;w=l*Math.cos(z),k=l*Math.sin(z),M=A=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+n.apply(this,arguments)))>.001){g=l0?0:1}function No(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=n-r,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,A=(-b*v+y*_)/m,T=w-p,L=k-g,C=M-p,S=A-g;return T*T+L*L>C*C+S*S&&(w=M,k=A),[[w-s,k-c],[w*n/x,k*n/x]]}function Ro(e){var t=Kr,n=ea,r=Xn,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(n);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",r[0]);return a.join("")},"step-before":Bo,"step-after":qo,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,n=[],r=-1,a=e.length,i=[0],o=[0];for(;++r<3;)t=e[r],i.push(t[0]),o.push(t[1]);n.push(Go(Zo,i)+","+Go(Zo,o)),--r;for(;++r9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function jo(e){return e.join("L")+"Z"}function Bo(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cAe)+",1 "+t}function s(e,t,n,r){return"Q 0,0 "+r}return i.radius=function(e){return arguments.length?(n=vt(e),i):n},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(r=vt(e),i):r},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=jr,t=Br,n=el;function r(r,a){var i=e.call(this,r,a),o=t.call(this,r,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(n))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return r.source=function(t){return arguments.length?(e=vt(t),r):e},r.target=function(e){return arguments.length?(t=vt(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),n=el,r=e.projection;return e.projection=function(e){return arguments.length?r(function(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Ce;return[n*Math.cos(r),n*Math.sin(r)]}}(n=e)):n},e},t.svg.symbol=function(){var e=nl,t=tl;function n(n,r){return(al.get(e.call(this,n,r))||rl)(t.call(this,n,r))}return n.type=function(t){return arguments.length?(e=vt(t),n):e},n.size=function(e){return arguments.length?(t=vt(e),n):t},n};var al=t.map({circle:rl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),n=t*ol;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Se);X.transition=function(e){for(var t,n,r=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[r]:delete e[n],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[r]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=X.call,dl.empty=X.empty,dl.node=X.node,dl.size=X.size,t.transition=function(e,n){return e&&e.transition?ul?e.transition(n):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,n,r,a=this.id,i=this.namespace,o=[];e=Z(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=r.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),A=xe(y),T=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,T[0]-=l[1],T[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(T[0]+=l[1],T[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",P).on("touchend.brush",z):L.on("mousemove.brush",P).on("mouseup.brush",z),b.interrupt().selectAll("*").interrupt(),M)T[0]=l[0]-T[0],T[1]=s[0]-T[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-T[0],s[1-S]-T[1]],T[0]=l[C],T[1]=s[S]}else t.event.altKey&&(f=T.slice());function P(){var e=t.mouse(y),n=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),T[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Sl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Sl(+t+1);return t}}:e))},a.ticks=function(e,t){var n=io(a.domain()),r=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],Sl(+n[1]+1),t<1?1:t)},a.tickFormat=function(){return r},a.copy=function(){return Cl(e.copy(),n,r)},ho(a,e)}function Sl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Tl,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Tl.toString,Dt.second=It(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=It(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=It(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=It(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Pl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ol=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],zl=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Xn]]),Dl={range:function(e,n,r){return t.range(Math.ceil(e/r)*r,+n,r).map(Sl)},floor:O,ceil:O};Ol.year=Dt.year,Dt.scale=function(){return Cl(t.scale.linear(),Ol,zl)};var El=Ol.map(function(e){return[e[0].utc,e[1]]}),Nl=Al.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Xn]]);function Rl(e){return JSON.parse(e.responseText)}function Il(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Cl(t.scale.linear(),El,Nl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Rl,t)},t.html=function(e,t){return mt(e,"text/html",Il,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t=function(e){var t=typeof e;if("string"===t){var n=e;if(0===(e=+e)&&function(e){for(var t,n=e.length,r=0;r13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(n))return!1}else if("number"!==t)return!1;return e-e<1},n={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},r={},a=Math.PI;r.deg2rad=function(e){return e/180*a},r.rad2deg=function(e){return e/a*180},r.wrap360=function(e){var t=e%360;return t<0?t+360:t},r.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var i=n.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,l={exports:{}};!function(e){var t=/^\s+/,n=/\s+$/,r=0,a=e.round,i=e.min,o=e.max,s=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(r){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof r&&(r=function(e){e=e.replace(t,"").replace(n,"").toLowerCase();var r,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(r=B.rgb.exec(e))return{r:r[1],g:r[2],b:r[3]};if(r=B.rgba.exec(e))return{r:r[1],g:r[2],b:r[3],a:r[4]};if(r=B.hsl.exec(e))return{h:r[1],s:r[2],l:r[3]};if(r=B.hsla.exec(e))return{h:r[1],s:r[2],l:r[3],a:r[4]};if(r=B.hsv.exec(e))return{h:r[1],s:r[2],v:r[3]};if(r=B.hsva.exec(e))return{h:r[1],s:r[2],v:r[3],a:r[4]};if(r=B.hex8.exec(e))return{r:z(r[1]),g:z(r[2]),b:z(r[3]),a:R(r[4]),format:a?"name":"hex8"};if(r=B.hex6.exec(e))return{r:z(r[1]),g:z(r[2]),b:z(r[3]),format:a?"name":"hex"};if(r=B.hex4.exec(e))return{r:z(r[1]+""+r[1]),g:z(r[2]+""+r[2]),b:z(r[3]+""+r[3]),a:R(r[4]+""+r[4]),format:a?"name":"hex8"};if(r=B.hex3.exec(e))return{r:z(r[1]+""+r[1]),g:z(r[2]+""+r[2]),b:z(r[3]+""+r[3]),format:a?"name":"hex"};return!1}(r));"object"==typeof r&&(q(r.r)&&q(r.g)&&q(r.b)?(h=r.r,p=r.g,g=r.b,a={r:255*P(h,255),g:255*P(p,255),b:255*P(g,255)},f=!0,d="%"===String(r.r).substr(-1)?"prgb":"rgb"):q(r.h)&&q(r.s)&&q(r.v)?(s=E(r.s),c=E(r.v),a=function(t,n,r){t=6*P(t,360),n=P(n,100),r=P(r,100);var a=e.floor(t),i=t-a,o=r*(1-n),l=r*(1-i*n),s=r*(1-(1-i)*n),c=a%6;return{r:255*[r,l,o,o,s,r][c],g:255*[s,r,r,l,o,o][c],b:255*[o,o,s,r,r,l][c]}}(r.h,s,c),f=!0,d="hsv"):q(r.h)&&q(r.s)&&q(r.l)&&(s=E(r.s),u=E(r.l),a=function(e,t,n){var r,a,i;function o(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=P(e,360),t=P(t,100),n=P(n,100),0===t)r=a=i=n;else{var l=n<.5?n*(1+t):n+t-n*t,s=2*n-l;r=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*r,g:255*a,b:255*i}}(r.h,s,u),f=!0,d="hsl"),r.hasOwnProperty("a")&&(l=r.a));var h,p,g;return l=S(l),{ok:f,format:r.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=r++}function u(e,t,n){e=P(e,255),t=P(t,255),n=P(n,255);var r,a,l=o(e,t,n),s=i(e,t,n),c=(l+s)/2;if(l==s)r=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:r=(t-n)/u+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,i.push(c(r));return i}function T(e,t){t=t||6;for(var n=c(e).toHsv(),r=n.h,a=n.s,i=n.v,o=[],l=1/t;t--;)o.push(c({h:r,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,n,r,a=this.toRgb();return t=a.r/255,n=a.g/255,r=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))},setAlpha:function(e){return this._a=S(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(n).toString(16)),D(N(r))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*P(this._r,255))+"%",g:a(100*P(this._g,255))+"%",b:a(100*P(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*P(this._r,255))+"%, "+a(100*P(this._g,255))+"%, "+a(100*P(this._b,255))+"%)":"rgba("+a(100*P(this._r,255))+"%, "+a(100*P(this._g,255))+"%, "+a(100*P(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);n="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(A,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:E(e[r]));e=n}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:s(),g:s(),b:s()})},c.mix=function(e,t,n){n=0===n?0:n||50;var r=c(e).toRgb(),a=c(t).toRgb(),i=n/100;return c({r:(a.r-r.r)*i+r.r,g:(a.g-r.g)*i+r.g,b:(a.b-r.b)*i+r.b,a:(a.a-r.a)*i+r.a})},c.readability=function(t,n){var r=c(t),a=c(n);return(e.max(r.getLuminance(),a.getLuminance())+.05)/(e.min(r.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,n){var r,a,i=c.readability(e,t);switch(a=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,n){var r,a,i,o,l=null,s=0;a=(n=n||{}).includeFallbackColors,i=n.level,o=n.size;for(var u=0;us&&(s=r,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(n.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],n))};var L=c.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"},C=c.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(L);function S(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function P(t,n){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var r=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(n,o(0,parseFloat(t))),r&&(t=parseInt(t*n,10)/100),e.abs(t-n)<1e-6?1:t%n/parseFloat(n)}function O(e){return i(1,o(0,e))}function z(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function N(t){return e.round(255*parseFloat(t)).toString(16)}function R(e){return z(e)/255}var I,F,j,B=(F="[\\s|\\(]+("+(I="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+I+")[,|\\s]+("+I+")\\s*\\)?",j="[\\s|\\(]+("+I+")[,|\\s]+("+I+")[,|\\s]+("+I+")[,|\\s]+("+I+")\\s*\\)?",{CSS_UNIT:new RegExp(I),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function q(e){return!!B.CSS_UNIT.exec(e)}l.exports?l.exports=c:window.tinycolor=c}(Math),l=l.exports;var s={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},c=s.RdBu,u=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var n=0;n1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(r=e[t][0],a=e[t][1],o=!1,G(r))for(n=r.length-1;n>=0;n--)W(r[n],Q(a,n))?o?r[n]=void 0:r.pop():o=!0;else if("object"==typeof r&&null!==r)for(i=Object.keys(r),o=!1,n=i.length-1;n>=0;n--)W(r[i[n]],Q(a,i[n]))?delete r[i[n]]:o=!0;if(o)return}}(s)):o[t[i]]=r}}function Q(e,n){var r=n;return t(n)?r="["+n+"]":e&&(r="."+n),e+r}function $(e,t,n,r){var a,i=G(n),o=!0,l=n,s=r.replace("-1",0),c=!i&&W(n,s),u=t[0];for(a=0;aa.max?n.set(r):n.set(+e)}},integer:{coerceFunction:function(e,n,r,a){e%1||!t(e)||void 0!==a.min&&ea.max?n.set(r):n.set(+e)}},string:{coerceFunction:function(e,t,n,r){if("string"!=typeof e){var a="number"==typeof e;!0!==r.strict&&a?t.set(String(e)):t.set(n)}else r.noBlank&&!e?t.set(n):t.set(e)}},color:{coerceFunction:function(e,t,n){l(e).isValid()?t.set(e):t.set(n)}},colorlist:{coerceFunction:function(e,t,n){Array.isArray(e)&&e.length&&e.every(function(e){return l(e).isValid()})?t.set(e):t.set(n)}},colorscale:{coerceFunction:function(e,t,n){t.set(f(e,n))}},angle:{coerceFunction:function(e,n,r){"auto"===e?n.set("auto"):t(e)?n.set(ae(+e)):n.set(r)}},subplotid:{coerceFunction:function(e,t,n){"string"==typeof e&&ne(n).test(e)?t.set(e):t.set(n)},validateFunction:function(e,t){var n=t.dflt;return e===n||"string"==typeof e&&!!ne(n).test(e)}},flaglist:{coerceFunction:function(e,t,n,r){if("string"==typeof e)if(-1===(r.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=oe&&e<=le?e:ue;if("string"!=typeof e&&"number"!=typeof e)return ue;e=String(e);var n=be(t),r=e.charAt(0);!n||"G"!==r&&"g"!==r||(e=e.substr(1),t="");var a=n&&"chinese"===t.substr(0,7),i=e.match(a?me:ye);if(!i)return ue;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(n){if(2===o.length)return ue;var d;o=Number(o);try{var h=z.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return ue}return d?(d.toJD()-ge)*fe+c*de+u*he+f*pe:ue}o=2===o.length?(Number(o)+2e3-xe)%100+xe:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?ue:g.getUTCDate()!==s?ue:g.getTime()+f*pe},oe=ce.MIN_MS=ce.dateTime2ms("-9999"),le=ce.MAX_MS=ce.dateTime2ms("9999-12-31 23:59:59.9999"),ce.isDateTime=function(e,t){return ce.dateTime2ms(e,t)!==ue};var we=90*fe,ke=3*de,Me=5*he;function Ae(e,t,n,r,a){if((t||n||r||a)&&(e+=" "+_e(t,2)+":"+_e(n,2),(r||a)&&(e+=":"+_e(r,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+_e(a,i)}return e}ce.ms2DateTime=function(e,t,n){if("number"!=typeof e||!(e>=oe&&e<=le))return ue;t||(t=0);var r,a,i,o,l,s,c=Math.floor(10*se(e+.05,1)),u=Math.round(e-c/10);if(be(n)){var f=Math.floor(u/fe)+ge,d=Math.floor(se(e,fe));try{r=z.getComponentMethod("calendars","getCal")(n).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){r=ve("G%Y-%m-%d")(new Date(u))}if("-"===r.charAt(0))for(;r.length<11;)r="-0"+r.substr(1);else for(;r.length<10;)r="0"+r;a=t=oe+fe&&t<=le-fe))return ue;var n=Math.floor(10*se(t+.05,1)),r=new Date(Math.round(t-n/10));return Ae(e.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+n)},ce.cleanDate=function(e,t,n){if(ce.isJSDate(e)||"number"==typeof e){if(be(n))return _.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ce.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ce.isDateTime(e,n))return _.error("unrecognized date",e),t;return e};var Te=/%\d?f/g;function Le(e,t,n,r){e=e.replace(Te,function(e){var n=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(n).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(be(r))try{e=z.getComponentMethod("calendars","worldCalFmt")(e,t,r)}catch(e){return"Invalid"}return n(e)(a)}var Ce=[59,59.9,59.99,59.999,59.9999];ce.formatDate=function(e,n,r,a,i,o){if(i=be(i)&&i,!n)if("y"===r)n=o.year;else if("m"===r)n=o.month;else{if("d"!==r)return function(e,n){var r=se(e+.05,fe),a=_e(Math.floor(r/de),2)+":"+_e(se(Math.floor(r/he),60),2);if("M"!==n){t(n)||(n=0);var i=(100+Math.min(se(e/pe,60),Ce[n])).toFixed(n).substr(1);n>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,r)+"\n"+Le(o.dayMonthYear,e,a,i);n=o.dayMonth+"\n"+o.year}return Le(n,e,a,i)};var Se=3*fe;ce.incrementMonth=function(e,t,n){n=be(n)&&n;var r=se(e,fe);if(e=Math.round(e-r),n)try{var a=Math.round(e/fe)+ge,i=z.getComponentMethod("calendars","getCal")(n),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ge)*fe+r}catch(t){_.error("invalid ms "+e+" in calendar "+n)}var l=new Date(e+Se);return l.setUTCMonth(l.getUTCMonth()+t)+r-Se},ce.findExactDates=function(e,n){for(var r,a,i=0,o=0,l=0,s=0,c=be(n)&&z.getComponentMethod("calendars","getCal")(n),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Ie(e,t,n,r,a){var i=r*e+a*t;if(i<0)return r*r+a*a;if(i>n){var o=r-e,l=a-t;return o*o+l*l}var s=r*t-a*e;return s*s/n}Ne.segmentsIntersect=Re,Ne.segmentDistance=function(e,t,n,r,a,i,o,l){if(Re(e,t,n,r,a,i,o,l))return 0;var s=n-e,c=r-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Ie(s,c,d,a-e,i-t),Ie(s,c,d,o-e,l-t),Ie(u,f,h,e-a,t-i),Ie(u,f,h,n-a,r-i));return Math.sqrt(p)},Ne.getTextLocation=function(e,t,n,r){if(e===De&&r===Ee||(ze={},De=e,Ee=r),ze[n])return ze[n];var a=e.getPointAtLength(se(n-r/2,t)),i=e.getPointAtLength(se(n+r/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(se(n,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return ze[n]=s,s},Ne.clearLocationCache=function(){De=null},Ne.getVisibleSegment=function(e,t,n){var r,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var n=e.getPointAtLength(t);0===t?r=n:t===u&&(a=n);var c=n.xo?n.x-o:0,f=n.ys?n.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+n)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+n))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(r.x-a.x)<.1&&Math.abs(r.y-a.y)<.1}},Ne.findPointOnPath=function(e,t,n,r){for(var a,i,o,l=(r=r||{}).pathLength||e.getTotalLength(),s=r.tolerance||.001,c=r.iterationLimit||30,u=e.getPointAtLength(0)[n]>e.getPointAtLength(l)[n]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var Fe=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},je=/^\w*$/,Be={init2dArray:function(e,t){for(var n=new Array(e),r=0;rt}function We(e,t){return e>=t}Ge.findBin=function(e,n,r){if(t(n.start))return r?Math.ceil((e-n.start)/n.size-1e-9)-1:Math.floor((e-n.start)/n.size+1e-9);var a,i,o=0,l=n.length,s=0,c=l>1?(n[l-1]-n[0])/(l-1):1;for(i=c>=0?r?Ye:Xe:r?We:Ze,e+=1e-9*c*(r?-1:1)*(c>=0?1:-1);o90&&_.log("Long binary search..."),o-1},Ge.sorterAsc=function(e,t){return e-t},Ge.sorterDes=function(e,t){return t-e},Ge.distinctVals=function(e){var t=e.slice();t.sort(Ge.sorterAsc);for(var n=t.length-1,r=t[n]-t[0]||1,a=r/(n||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(r=Math.min(r,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:r}},Ge.roundUp=function(e,t,n){for(var r,a=0,i=t.length-1,o=0,l=n?0:1,s=n?1:0,c=n?Math.ceil:Math.floor;ar.length)&&(a=r.length),t(n)||(n=!1),Qe(r[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var r=n%1;return r*e[Math.ceil(n)]+(1-r)*e[Math.floor(n)]};var $e={},Ke={};function et(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}$e.throttle=function(e,t,n){var r=Ke[e],a=Date.now();if(!r){for(var i in Ke)Ke[i].tsr.ts+t?o():r.timer=setTimeout(function(){o(),r.timer=null},t)},$e.done=function(e){var t=Ke[e];return t&&t.timer?new Promise(function(e){var n=t.onDone;t.onDone=function(){n&&n(),e(),t.onDone=null}}):Promise.resolve()},$e.clear=function(e){if(e)et(Ke[e]),delete Ke[e];else for(var t in Ke)$e.clear(t)};var tt=function(e,n){if(e>0)return Math.log(e)/Math.LN10;var r=Math.log(Math.min(n[0],n[1]))/Math.LN10;return t(r)||(r=Math.log(Math.max(n[0],n[1]))/Math.LN10-6),r},nt={},rt=n.FP_SAFE,at=n.BADNUM,it=nt={};it.nestedProperty=Y,it.keyedContainer=function(e,t,n,r){var a,i;n=n||"name",r=r||"value";var o={};i=t&&t.length?Y(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lrt?at:t(e)?Number(e):at:at},it.noop=M,it.identity=function(e){return e},it.swapAttrs=function(e,t,n,r){n||(n="x"),r||(r="y");for(var a=0;an?Math.max(n,Math.min(t,e)):Math.max(t,Math.min(n,e))},it.bBoxIntersect=function(e,t,n){return n=n||0,e.left<=t.right+n&&t.left<=e.right+n&&e.top<=t.bottom+n&&t.top<=e.bottom+n},it.simpleMap=function(e,t,n,r){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,n)?e(t,n,r):l},it.OptionControl=function(e,t){e||(e={}),t||(t="opt");var n={optionList:[],_newoption:function(r){r[t]=e,n[r.name]=r,n.optionList.push(r)}};return n["_"+t]=e,n},it.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var n,r,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(n=0;n=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[r];u[n]=i}return u},it.syncOrAsync=function(e,t,n){var r;function a(){return it.syncOrAsync(e,t,n)}for(;e.length;)if((r=(0,e.splice(0,1)[0])(t))&&r.then)return r.then(a).then(void 0,it.promiseError);return n&&n(t)},it.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},it.noneOrAll=function(e,t,n){if(e){var r,a,i=!1,o=!0;for(r=0;r=0&&i%1==0){var p=a?a[h]:h,g=r?r[p]:p;f(g)&&(e[g].selected=1)}}},it.getTargetArray=function(e,t){var n=t.target;if("string"==typeof n&&n){var r=it.nestedProperty(e,n).get();return!!Array.isArray(r)&&r}return!!Array.isArray(n)&&n},it.minExtend=function(e,t){var n={};"object"!=typeof t&&(t={});var r,a,i,o=Object.keys(e);for(r=0;r1?a+o[1]:"";if(i&&(o.length>1||l.length>4||n))for(;r.test(l);)l=l.replace(r,"$1"+i+"$2");return l+s};var st=/%{([^\s%{}]*)}/g,ct=/^\w*$/;it.templateString=function(e,t){var n={};return e.replace(st,function(e,r){return ct.test(r)?t[r]||"":(n[r]=n[r]||it.nestedProperty(t,r).get,n[r]()||"")})};it.subplotSort=function(e,t){for(var n=Math.min(e.length,t.length)+1,r=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(r=10*r+o-48),c&&(a=10*a+l-48),!s||!c){if(r!==a)return r-a;if(o!==l)return o-l}}return a-r};var ut=2e9;it.seedPseudoRandom=function(){ut=2e9},it.pseudoRandom=function(){var e=ut;return ut=(69069*ut+1)%4294967296,Math.abs(ut-e)<429496729?it.pseudoRandom():ut/4294967296};var ft={exports:{}};!function(e,t){"object"==typeof ft.exports?t(ft.exports):t(e.topojson=e.topojson||{})}(this,function(e){"use strict";var t=function(e){return e},n=function(e){if(null==(n=e.transform))return t;var n,r,a,i=n.scale[0],o=n.scale[1],l=n.translate[0],s=n.translate[1];return function(e,t){return t||(r=a=0),e[0]=(r+=e[0])*i+l,e[1]=(a+=e[1])*o+s,e}},r=function(e){var t=e.bbox;function r(e){s[0]=e[0],s[1]=e[1],l(s),s[0]f&&(f=s[0]),s[1]d&&(d=s[1])}function a(e){switch(e.type){case"GeometryCollection":e.geometries.forEach(a);break;case"Point":r(e.coordinates);break;case"MultiPoint":e.coordinates.forEach(r)}}if(!t){var i,o,l=n(e),s=new Array(2),c=1/0,u=c,f=-c,d=-c;for(o in e.arcs.forEach(function(e){for(var t=-1,n=e.length;++tf&&(f=s[0]),s[1]d&&(d=s[1])}),e.objects)a(e.objects[o]);t=e.bbox=[c,u,f,d]}return t},a=function(e,t){for(var n,r=e.length,a=r-t;a<--r;)n=e[a],e[a++]=e[r],e[r]=n};function i(e,t){var n=t.id,r=t.bbox,a=null==t.properties?{}:t.properties,i=o(e,t);return null==n&&null==r?{type:"Feature",properties:a,geometry:i}:null==r?{type:"Feature",id:n,properties:a,geometry:i}:{type:"Feature",id:n,bbox:r,properties:a,geometry:i}}function o(e,t){var r=n(e),i=e.arcs;function o(e,t){t.length&&t.pop();for(var n=i[e<0?~e:e],o=0,l=n.length;o1)r=function(e,t,n){var r,a=[],i=[];function o(e){var t=e<0?~e:e;(i[t]||(i[t]=[])).push({i:e,g:r})}function l(e){e.forEach(o)}function s(e){e.forEach(l)}return function e(t){switch(r=t,t.type){case"GeometryCollection":t.geometries.forEach(e);break;case"LineString":l(t.arcs);break;case"MultiLineString":case"Polygon":s(t.arcs);break;case"MultiPolygon":t.arcs.forEach(s)}}(t),i.forEach(null==n?function(e){a.push(e[0].i)}:function(e){n(e[0].g,e[e.length-1].g)&&a.push(e[0].i)}),a}(0,t,n);else for(a=0,r=new Array(i=e.arcs.length);a1)for(var i,o,c=1,u=s(a[0]);cu&&(o=a[0],a[0]=a[c],a[c]=o,u=i);return a})}}var u=function(e,t){for(var n=0,r=e.length;n>>1;e[a]=2))throw new Error("n must be \u22652");if(e.transform)throw new Error("already quantized");var n,a=r(e),i=a[0],o=(a[2]-i)/(t-1)||1,l=a[1],s=(a[3]-l)/(t-1)||1;function c(e){e[0]=Math.round((e[0]-i)/o),e[1]=Math.round((e[1]-l)/s)}function u(e){switch(e.type){case"GeometryCollection":e.geometries.forEach(u);break;case"Point":c(e.coordinates);break;case"MultiPoint":e.coordinates.forEach(c)}}for(n in e.arcs.forEach(function(e){for(var t,n,r,a=1,c=1,u=e.length,f=e[0],d=f[0]=Math.round((f[0]-i)/o),h=f[1]=Math.round((f[1]-l)/s);a=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}ht.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},ht.rgb=function(e){return ht.tinyRGB(l(e))},ht.opacity=function(e){return e?l(e).getAlpha():0},ht.addOpacity=function(e,t){var n=l(e).toRgb();return"rgba("+Math.round(n.r)+", "+Math.round(n.g)+", "+Math.round(n.b)+", "+t+")"},ht.combine=function(e,t){var n=l(e).toRgb();if(1===n.a)return l(e).toRgbString();var r=l(t||gt).toRgb(),a=1===r.a?r:{r:255*(1-r.a)+r.r*r.a,g:255*(1-r.a)+r.g*r.a,b:255*(1-r.a)+r.b*r.a},i={r:a.r*(1-n.a)+n.r*n.a,g:a.g*(1-n.a)+n.g*n.a,b:a.b*(1-n.a)+n.b*n.a};return l(i).toRgbString()},ht.contrast=function(e,t,n){var r=l(e);return 1!==r.getAlpha()&&(r=l(ht.combine(e,gt))),(r.isDark()?t?r.lighten(t):gt:n?r.darken(n):pt).toString()},ht.stroke=function(e,t){var n=l(t);e.style({stroke:ht.tinyRGB(n),"stroke-opacity":n.getAlpha()})},ht.fill=function(e,t){var n=l(t);e.style({fill:ht.tinyRGB(n),"fill-opacity":n.getAlpha()})},ht.clean=function(e){if(e&&"object"==typeof e){var t,n,r,a,i=Object.keys(e);for(t=0;t0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},kt.prototype.on=kt.prototype.addListener,kt.prototype.once=function(e,t){if(!At(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},kt.prototype.removeListener=function(e,t){var n,r,a,i;if(!At(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||At(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(Tt(n)){for(i=a;i-- >0;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},kt.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(At(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},kt.prototype.listeners=function(e){return this._events&&this._events[e]?At(this._events[e])?[this._events[e]]:this._events[e].slice():[]},kt.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(At(t))return 1;if(t)return t.length}return 0},kt.listenerCount=function(e,t){return e.listenerCount(t)};var Ct,St=Mt.EventEmitter,Pt={init:function(e){if(e._ev instanceof St)return e;var t=new St,n=new St;return e._ev=t,e._internalEv=n,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=n.on.bind(n),e._internalOnce=n.once.bind(n),e._removeInternalListener=n.removeListener.bind(n),e._removeAllInternalListeners=n.removeAllListeners.bind(n),e.emit=function(r,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(r,a),t.emit(r,a),n.emit(r,a)},e},triggerHandler:function(e,t,n){var r,a;"undefined"!=typeof jQuery&&(r=jQuery(e).triggerHandler(t,n));var i=e._ev;if(!i)return r;var o=i._events[t];if(!o)return r;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Nt.getCursor=function(e,t,n,r){return e="left"===n?0:"center"===n?1:"right"===n?2:nt.constrain(Math.floor(3*e),0,2),t="bottom"===r?0:"middle"===r?1:"top"===r?2:nt.constrain(Math.floor(3*t),0,2),_t[t][e]},Nt.unhover=Ct.wrapped,Nt.unhoverRaw=Ct.raw,Nt.init=function(e){var t,n,r,a,i,o,l,s,c=e.gd,u=1,f=d.DBLCLICKDELAY,h=e.element;c._mouseDownTime||(c._mouseDownTime=0),h.style.pointerEvents="all",h.onmousedown=g,mt?(h._ontouchstart&&h.removeEventListener("touchstart",h._ontouchstart),h._ontouchstart=g,h.addEventListener("touchstart",g,{passive:!1})):h.ontouchstart=g;var p=e.clampFn||function(e,t,n){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var n;try{n=new MouseEvent("click",t)}catch(e){var r=It(t);(n=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,r[0],r[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(n)}!function(e){e._dragging=!1,e._replotPending&&z.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Nt.coverSlip=Rt;var Ft={zauto:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{zmin:void 0,zmax:void 0}},zmin:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},zmax:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},colorscale:{valType:"colorscale",editType:"calc",impliedEdits:{autocolorscale:!1}},autocolorscale:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{colorscale:void 0}},reversescale:{valType:"boolean",dflt:!1,editType:"calc"},showscale:{valType:"boolean",dflt:!0,editType:"calc"}},jt=function(e){for(var t,n=e.length,r=new Array(n),a=n-1,i=0;a>=0;a--,i++)t=e[a],r[i]=[1-t[0],t[1]];return r},Bt=function(e,t,n,r){var a,i;n?(a=nt.nestedProperty(e,n).get(),i=nt.nestedProperty(e._input,n).get()):(a=e,i=e._input);var o=r+"auto",l=r+"min",c=r+"max",u=a[o],f=a[l],d=a[c],h=a.colorscale;!1===u&&void 0!==f||(f=nt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=nt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[c]=d,i[l]=f,i[c]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?s.RdBu:f>=0?s.Reds:s.Blues,i.colorscale=h,a.reversescale&&(h=jt(h)),a.colorscale=h)},qt=nt.extendFlat,Ht=nt.isPlainObject,Vt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},Ut={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},Gt=Vt.flags.slice().concat(["clearCalc","fullReplot"]),Yt=Ut.flags.slice().concat("layoutReplot"),Xt={traces:Vt,layout:Ut,traceFlags:function(){return Zt(Gt)},layoutFlags:function(){return Zt(Yt)},update:function(e,t){var n=t.editType;if(n&&"none"!==n)for(var r=n.split("+"),a=0;a0?Number(s):l;else if("string"!=typeof s)n.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=t(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(n.dtick=l)}var f="date"===a?nt.dateTick0(n.calendar):0,d=r("tick0",f);"date"===a?n.tick0=nt.cleanDate(d,f):t(d)&&"D1"!==s&&"D2"!==s?n.tick0=Number(d):n.tick0=f}else{void 0===r("tickvals")?n.tickmode="auto":r("ticktext")}},sn=function(e){return void 0!==s[e]||u(e)},cn=function(e,n,r,a,i){var o,l=i.prefix,s=i.cLetter,c=l.slice(0,l.length-1),u=l?nt.nestedProperty(e,c).get()||{}:e,f=l?nt.nestedProperty(n,c).get()||{}:n,d=u[s+"min"],h=u[s+"max"],p=u.colorscale;a(l+s+"auto",!(t(d)&&t(h)&&d","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},yn={},mn=pn.LINE_SPACING;function xn(e,t){return e.node().getBoundingClientRect()[t]}var bn=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;yn.convertToTspans=function(t,n,r){var a=t.text(),i=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&a.match(bn),o=e.select(t.node().parentNode);if(!o.empty()){var l=t.attr("class")?t.attr("class").split(" ")[0]:"text";return l+="-math",o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove(),t.style("display",null).attr({"data-unformatted":a,"data-math":"N"}),i?(n&&n._promises||[]).push(new Promise(function(n){t.style("display","none");var c=parseInt(t.node().style.fontSize,10),u={fontSize:c};!function(t,n,r){var a="math-output-"+nt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":n.fontSize+"px"}).text((o=t,o.replace(_n,"\\lt ").replace(wn,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var n=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())nt.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),n,a)}i.remove()})}(i[2],u,function(e,i,u){o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return s(),void n();var d=o.append("g").classed(l+"-group",!0).attr({"pointer-events":"none","data-unformatted":a,"data-math":"Y"});d.node().appendChild(f.node()),i&&i.node()&&f.node().insertBefore(i.node().cloneNode(!0),f.node().firstChild),f.attr({class:l,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=t.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=xn(f,"width"),g=xn(f,"height"),v=+t.attr("x")-p*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],y=-(c||xn(t,"height"))/4;"y"===l[0]?(d.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===l[0]?f.attr({x:t.attr("x"),y:y-g/2}):"a"===l[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+t.attr("y")+y-g/2}),r&&r.call(t,d),n(d)})})):s(),t}function s(){o.empty()||(l=t.attr("class")+"-math",o.select("svg."+l).remove()),t.text("").style("white-space","pre"),function(t,n){n=(r=n,function(e,t){if(!e)return"";for(var n=0;n1)for(var i=1;i doesnt match end tag <"+e+">. Pretending it did match.",n),a=o[o.length-1].node}else nt.log("Ignoring unexpected end tag .",n)}Dn.test(n)?s():(a=t,o=[{node:t}]);for(var d=n.split(On),h=0;h|>|>)/g;var kn={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"},Mn={sub:"0.3em",sup:"-0.6em"},An={sub:"-0.21em",sup:"0.42em"},Tn="\u200b",Ln=["http:","https:","mailto:","",void 0,":"],Cn=new RegExp("]*)?/?>","g"),Sn=Object.keys(vn.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:vn.entityToUnicode[e]}}),Pn=/(\r\n?|\n)/g,On=/(<[^<>]*>)/,zn=/<(\/?)([^ >]*)(\s+(.*))?>/i,Dn=//i,En=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Nn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Rn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,In=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function Fn(e,t){if(!e)return null;var n=e.match(t);return n&&(n[3]||n[4])}var jn=/(^|;)\s*color:/;function Bn(e,t,n){var r,a,i,o=n.horizontalAlign,l=n.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-r.height}:"middle"===l?function(){return s.top+(s.height-r.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-r.width}:"center"===o?function(){return s.left+(s.width-r.width)/2}:function(){return s.left},function(){return r=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}yn.plainText=function(e){return(e||"").replace(Cn," ")},yn.lineCount=function(e){return e.selectAll("tspan.line").size()||1},yn.positionText=function(t,n,r){return t.each(function(){var t=e.select(this);function a(e,n){return void 0===n?null===(n=t.attr(e))&&(t.attr(e,0),n=0):t.attr(e,n),n}var i=a("x",n),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},yn.makeEditable=function(t,n){var r=n.gd,a=n.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(r).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:n.fill||c.fill||"black",opacity:1,"background-color":n.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(n.text||t.attr("data-unformatted")).call(Bn(t,a,n)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var n,a=e.select(this).attr("class");(n=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(n).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(r._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Bn(t,a,n)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),n=document.createRange();n.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(n),t.focus()}return n.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var qn=function(e){var n=e.marker,r=n.sizeref||1,a=n.sizemin||0,i="area"===n.sizemode?function(e){return Math.sqrt(e/r)}:function(e){return e/r};return function(e){var n=i(e/2);return t(n)&&n>0?Math.max(n,a):0}},Hn={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("markers")},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return nt.isPlainObject(e.marker)&&nt.isArrayOrTypedArray(e.marker.size)}},Vn={},Un=pn.LINE_SPACING,Gn=d.DESELECTDIM,Yn=Vn={};Yn.font=function(e,t,n,r){nt.isPlainObject(t)&&(r=t.color,n=t.size,t=t.family),t&&e.style("font-family",t),n+1&&e.style("font-size",n+"px"),r&&e.call(dt.fill,r)},Yn.setPosition=function(e,t,n){e.attr("x",t).attr("y",n)},Yn.setSize=function(e,t,n){e.attr("width",t).attr("height",n)},Yn.setRect=function(e,t,n,r,a){e.call(Yn.setPosition,t,n).call(Yn.setSize,r,a)},Yn.translatePoint=function(e,n,r,a){var i=r.c2p(e.x),o=a.c2p(e.y);return!!(t(i)&&t(o)&&n.node())&&("text"===n.node().nodeName?n.attr("x",i).attr("y",o):n.attr("transform","translate("+i+","+o+")"),!0)},Yn.translatePoints=function(t,n,r){t.each(function(t){var a=e.select(this);Yn.translatePoint(t,a,n,r)})},Yn.hideOutsideRangePoint=function(e,t,n,r,a,i){t.attr("display",n.isPtWithinRange(e,a)&&r.isPtWithinRange(e,i)?null:"none")},Yn.hideOutsideRangePoints=function(t,n,r){if(n._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=n.xaxis,i=n.yaxis;t.each(function(n){var o=n[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Yn.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Yn.crispRound=function(e,n,r){return n&&t(n)?e._context.staticPlot?n:n<1?1:Math.round(n):r||0},Yn.singleLineStyle=function(e,t,n,r,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";dt.stroke(t,r||i.color),Yn.dashLine(t,l,o)},Yn.lineGroupStyle=function(t,n,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";e.select(this).call(dt.stroke,r||i.color).call(Yn.dashLine,l,o)})},Yn.dashLine=function(e,t,n){n=+n||0,t=Yn.dashStyle(t,n),e.style({"stroke-dasharray":t,"stroke-width":n+"px"})},Yn.dashStyle=function(e,t){t=+t||1;var n=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),e},Yn.singleFillStyle=function(t){var n=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;n&&t.call(dt.fill,n)},Yn.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(n){var r=e.select(this);try{r.call(dt.fill,n[0].trace.fillcolor)}catch(e){nt.error(e,t),r.remove()}})},Yn.symbolNames=[],Yn.symbolFuncs=[],Yn.symbolNeedLines={},Yn.symbolNoDot={},Yn.symbolNoFill={},Yn.symbolList=[],Object.keys(hn).forEach(function(e){var t=hn[e];Yn.symbolList=Yn.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Yn.symbolNames[t.n]=e,Yn.symbolFuncs[t.n]=t.f,t.needLine&&(Yn.symbolNeedLines[t.n]=!0),t.noDot?Yn.symbolNoDot[t.n]=!0:Yn.symbolList=Yn.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Yn.symbolNoFill[t.n]=!0)});var Xn=Yn.symbolNames.length,Zn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Wn(e,t){var n=e%100;return Yn.symbolFuncs[n](t)+(e>=200?Zn:"")}Yn.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Yn.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Xn||e>=400?0:Math.floor(Math.max(e,0))};var Jn={x1:1,x2:0,y1:0,y2:0},Qn={x1:0,x2:0,y1:1,y2:0};Yn.gradient=function(t,n,r,a,i,o){var s=n._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],nt.identity);s.exit().remove(),s.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jn):"vertical"===a&&t.attr(Qn),t.attr("id",r);var n=l(i),s=l(o);t.append("stop").attr({offset:"0%","stop-color":dt.tinyRGB(s),"stop-opacity":s.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":dt.tinyRGB(n),"stop-opacity":n.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Yn.initGradients=function(e){var t=e._fullLayout._defs.selectAll(".gradients").data([0]);t.enter().append("g").classed("gradients",!0),t.selectAll("linearGradient,radialGradient").remove()},Yn.singlePointStyle=function(e,t,n,r,a,i){var o=n.marker;!function(e,t,n,r,a,i,o,l){if(z.traceIs(n,"symbols")){var s=qn(n);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Hn.isBubble(n)?s(e.ms):(i.size||6)/2,e.mrc=t;var r=Yn.symbolNumber(e.mx||i.symbol)||0;return e.om=r%200>=100,Wn(r,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):nt.isArrayOrTypedArray(o.color)?dt.defaultLine:o.color,nt.isArrayOrTypedArray(i.color)&&(c=dt.defaultLine,d=!0),c="mc"in e?e.mcc=r(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(dt.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+n.uid;d&&(v+="-"+e.i),t.call(Yn.gradient,l,v,p,c,g)}else t.call(dt.fill,c);f&&t.call(dt.stroke,u)}}(e,t,n,r,a,o,o.line,i)},Yn.pointStyle=function(t,n,r){if(t.size()){var a=n.marker,i=Yn.tryColorscale(a,""),o=Yn.tryColorscale(a,"line");t.each(function(t){Yn.singlePointStyle(t,e.select(this),n,i,o,r)})}},Yn.makeSelectedPointStyleFns=function(e){var t={},n=e.selected||{},r=e.unselected||{},a=e.marker||{},i=n.marker||{},o=r.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,n=void 0!==t;if(n||u||f){if(!e.selected)return f?c:Gn*(n?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Yn.selectedPointStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=Yn.makeSelectedPointStyleFns(n),a=n.marker||{};t.each(function(t){var n=e.select(this),a=r.opacityFn(t);void 0!==a&&n.style("opacity",a)}),r.colorFn&&t.each(function(t){var n=e.select(this),a=r.colorFn(t);a&&dt.fill(n,a)}),z.traceIs(n,"symbols")&&r.sizeFn&&t.each(function(t){var n=e.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);n.attr("d",Wn(Yn.symbolNumber(i),o)),t.mrc2=o})}},Yn.tryColorscale=function(e,t){var n=t?nt.nestedProperty(e,t).get():e,r=n.colorscale,a=n.color;return r&&nt.isArrayOrTypedArray(a)?dn.makeColorScaleFunc(dn.extractScale(r,n.cmin,n.cmax)):nt.identity};var $n={start:1,end:-1,middle:0,bottom:1,top:-1};function Kn(t,n,r,a){var i=e.select(t.node().parentNode),o=-1!==n.indexOf("top")?"top":-1!==n.indexOf("bottom")?"bottom":"middle",l=-1!==n.indexOf("left")?"end":-1!==n.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(yn.lineCount(t)-1)*Un+1,u=$n[l]*s,f=.75*r+$n[o]*s+($n[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function er(e,n){var r=e.ts||n.textfont.size;return t(r)&&r>0?r:0}Yn.textPointStyle=function(t,n,r){t.each(function(t){var a=e.select(this),i=nt.extractOption(t,n,"tx","text");if(i){var o=t.tp||n.textposition,l=er(t,n);a.call(Yn.font,t.tf||n.textfont.family,l,t.tc||n.textfont.color).text(i).call(yn.convertToTspans,r).call(Kn,o,l,t.mrc)}else a.remove()})},Yn.selectedTextStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=n.selected||{},a=n.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||n.textfont.color,s=t.tp||n.textposition,c=er(t,n),u=(r.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=dt.addOpacity(l,Gn)),i&&dt.fill(o,i),Kn(o,s,c,t.mrc2||t.mrc)})}};var tr=.5;function nr(t,n,r,a){var i=t[0]-n[0],o=t[1]-n[1],l=r[0]-n[0],s=r[1]-n[1],c=Math.pow(i*i+o*o,tr/2),u=Math.pow(l*l+s*s,tr/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(n[0]+(h&&f/h),2),e.round(n[1]+(h&&d/h),2)],[e.round(n[0]-(p&&f/p),2),e.round(n[1]-(p&&d/p),2)]]}Yn.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var n,r="M"+e[0],a=[];for(n=1;n=1e4&&(Yn.savedBBoxes={},ir=0),r&&(Yn.savedBBoxes[r]=p),ir++,nt.extendFlat({},p)},Yn.setClipUrl=function(t,n){if(n){var r="#"+n,a=e.select("base");a.size()&&a.attr("href")&&(r=window.location.href.split("#")[0]+r),t.attr("clip-path","url("+r+")")}else t.attr("clip-path",null)},Yn.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Yn.setTranslate=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||0,n=n||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+n+")").trim(),e[a]("transform",i),i},Yn.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Yn.setScale=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||1,n=n||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+n+")").trim(),e[a]("transform",i),i},Yn.setPointGroupScale=function(e,t,n){var r,a,i;return t=t||1,n=n||1,a=1===t&&1===n?"":" scale("+t+","+n+")",i=/\s*sc.*/,e.each(function(){r=(this.getAttribute("transform")||"").replace(i,""),r=(r+=a).trim(),this.setAttribute("transform",r)}),a};var lr=/translate\([^)]*\)\s*$/;Yn.setTextPointsScale=function(t,n,r){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(lr);t=1===n&&1===r?[]:["translate("+o+","+l+")","scale("+n+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};function sr(e,t,n,r){r=r||nt.identity,Array.isArray(e)&&(t[0][n]=r(e))}var cr={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},flat:function(e,t){for(var n=new Array(e.length),r=0;r=0&&n.index=i.length)return!1;if(2===e.dimensions){if(n++,t.length===n)return e;var o=t[n];if(!Fr(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function Fr(e){return e===Math.round(e)&&e>=0}function jr(e){return function(e){Or.crawl(e,function(e,t,n){Or.isValObject(e)?"data_array"===e.valType?(e.role="data",n[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(n[t+"src"]={valType:"string",editType:"none"}):nt.isPlainObject(e)&&(e.role="object")})}(e),function(e){Or.crawl(e,function(e,t,n){if(!e)return;var r=e[Nr];if(!r)return;delete e[Nr],n[t]={items:{}},n[t].items[r]=e,n[t].role="object"})}(e),e}function Br(e,t,n){var r=nt.nestedProperty(e,n),a=Dr({},t.layoutAttributes);a[Er]=!0,r.set(a)}function qr(e,t,n){var r=nt.nestedProperty(e,n);r.set(Dr(r.get()||{},t))}Or.IS_SUBPLOT_OBJ=Er,Or.IS_LINKED_TO_ARRAY=Nr,Or.DEPRECATED="_deprecated",Or.UNDERSCORE_ATTRS=Rr,Or.get=function(){var e={};z.allTypes.concat("area").forEach(function(t){e[t]=function(e){var t,n;"area"===e?(t={attributes:Ar},n={}):(t=z.modules[e]._module,n=t.basePlotModule);var r={type:null};Dr(r,C),Dr(r,t.attributes),n.attributes&&Dr(r,n.attributes);r.type=e;var a={meta:t.meta||{},attributes:jr(r)};if(t.layoutAttributes){var i={};Dr(i,t.layoutAttributes),a.layoutAttributes=jr(i)}return a}(t)});var t,n={};return Object.keys(z.transformsRegistry).forEach(function(e){n[e]=function(e){var t=z.transformsRegistry[e],n=Dr({},t.attributes);return Object.keys(z.componentsRegistry).forEach(function(t){var r=z.componentsRegistry[t];r.schema&&r.schema.transforms&&r.schema.transforms[e]&&Object.keys(r.schema.transforms[e]).forEach(function(t){qr(n,r.schema.transforms[e][t],t)})}),{attributes:jr(n)}}(e)}),{defs:{valObjects:nt.valObjectMeta,metaKeys:Rr.concat(["description","role","editType","impliedEdits"]),editType:{traces:Xt.traces,layout:Xt.layout},impliedEdits:{}},traces:e,layout:function(){var e,t,n={};for(e in Dr(n,O),z.subplotsRegistry)if((t=z.subplotsRegistry[e]).layoutAttributes)if("cartesian"===t.name)Br(n,t,"xaxis"),Br(n,t,"yaxis");else{var r="subplot"===t.attr?t.name:t.attr;Br(n,t,r)}for(e in n=function(e){return zr(e,{radialaxis:Pr.radialaxis,angularaxis:Pr.angularaxis}),zr(e,Pr.layout),e}(n),z.componentsRegistry){var a=(t=z.componentsRegistry[e]).schema;if(a&&(a.subplots||a.layout)){var i=a.subplots;if(i&&i.xaxis&&!i.yaxis)for(var o in i.xaxis)delete n.yaxis[o]}else t.layoutAttributes&&qr(n,t.layoutAttributes,t.name)}return{layoutAttributes:jr(n)}}(),transforms:n,frames:(t={frames:nt.extendDeepAll({},yr)},jr(t),t.frames),animation:jr(vr)}},Or.crawl=function(e,t,n,r){var a=n||0;r=r||"",Object.keys(e).forEach(function(n){var i=e[n];if(-1===Rr.indexOf(n)){var o=(r?r+".":"")+n;t(i,n,e,a,o),Or.isValObject(i)||nt.isPlainObject(i)&&"impliedEdits"!==n&&Or.crawl(i,t,a+1,o)}})},Or.isValObject=function(e){return e&&void 0!==e.valType},Or.findArrayAttributes=function(e){var t=[],n=[];function r(r,a,i,o){if(n=n.slice(0,o).concat([a]),r&&("data_array"===r.valType||!0===r.arrayOk)&&!("colorbar"===n[o-1]&&("ticktext"===a||"tickvals"===a))){var l=function(e){return e.join(".")}(n),s=nt.nestedProperty(e,l).get();nt.isArrayOrTypedArray(s)&&t.push(l)}}if(Or.crawl(C,r),e._module&&e._module.attributes&&Or.crawl(e._module.attributes,r),e.transforms)for(var a=e.transforms,i=0;i=e.transforms.length)return!1;r=(n=(z.transformsRegistry[e.transforms[o].type]||{}).attributes)&&n[t[2]],i=3}else if("area"===e.type)r=Ar[a];else{var l=e._module;if(l||(l=(z.modules[e.type||C.type.dflt]||{})._module),!l)return!1;if(!(r=(n=l.attributes)&&n[a])){var s=l.basePlotModule;s&&s.attributes&&(r=s.attributes[a])}r||(r=C[a])}return Ir(r,t,i)},Or.getLayoutValObject=function(e,t){return Ir(function(e,t){var n,r,a,i,o=e._basePlotModules;if(o){var l;for(n=0;nr?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},Vr={};function Ur(e,t,n){var r,a,i,o=!1;if("data"===t.type)r=e._fullData[null!==t.traces?t.traces[0]:0];else{if("layout"!==t.type)return!1;r=e._fullLayout}return a=nt.nestedProperty(r,t.prop).get(),(i=n[t.type]=n[t.type]||{}).hasOwnProperty(t.prop)&&i[t.prop]!==a&&(o=!0),i[t.prop]=a,{changed:o,value:a}}function Gr(e,t){var n=[],r=t[0],a={};if("string"==typeof r)a[r]=t[1];else{if(!nt.isPlainObject(r))return n;a=r}return Xr(a,function(e,t,r){n.push({type:"layout",prop:e,value:r})},"",0),n}function Yr(e,t){var n,r,a,i,o=[];if(r=t[0],a=t[1],n=t[2],i={},"string"==typeof r)i[r]=a;else{if(!nt.isPlainObject(r))return o;i=r,void 0===n&&(n=a)}return void 0===n&&(n=null),Xr(i,function(t,r,a){var i;if(Array.isArray(a)){var l=Math.min(a.length,e.data.length);n&&(l=Math.min(l,n.length)),i=[];for(var s=0;s0?".":"")+a;nt.isPlainObject(i)?Xr(i,t,o,r+1):t(o,a,i)}})}Vr.manageCommandObserver=function(e,t,n,r){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Vr.hasSimpleAPICommandBindings(e,n,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Ur(e,o,a.cache),a.check=function(){if(i){var t=Ur(e,o,a.cache);return t.changed&&r&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(r({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=n.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=n._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var n=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)n.on("click",function(){Qr.sendDataToCloud(e)});else{var r=window.location.pathname.split("/"),a=window.location.search;n.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+r[2].split(".")[0]+"/"+r[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},Qr.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var n=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:n+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=Qr.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var ea,ta=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],na=["year","month","dayMonth","dayMonthYear"];function ra(e,t){var n,r,a=e.trace,i=a._arrayAttrs,o={};for(n=0;n=0)return!0}return!1},Qr.cleanPlot=function(e,t,n,r){var a,i,o=r._basePlotModules||[];for(a=0;a0){var c=function(e){var t,n={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(n.left+=e[t].left||0,n.right+=e[t].right||0,n.bottom+=e[t].bottom||0,n.top+=e[t].top||0);return n}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=Qr.layoutAttributes.width.min,v=Qr.layoutAttributes.height.min;a1,m=!n.height&&Math.abs(r.height-i)>1;(m||y)&&(y&&(r.width=a),m&&(r.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),Qr.sanitizeMargins(r)},Qr.supplyLayoutModuleDefaults=function(e,t,n,r){var a,i,o,l=z.componentsRegistry,s=t._basePlotModules,c=z.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(z.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(nt.subplotSort);for(i=0;i.5*r.width&&(n.l=n.r=0),n.b+n.t>.5*r.height&&(n.b=n.t=0),r._pushmargin[t]={l:{val:n.x,size:n.l+a},r:{val:n.x,size:n.r+a},b:{val:n.y,size:n.b+a},t:{val:n.y,size:n.t+a}}}else delete r._pushmargin[t];r._replotting||Qr.doAutoMargin(e)}},Qr.doAutoMargin=function(e){var n=e._fullLayout;n._size||(n._size={}),n._pushmargin||(n._pushmargin={});var r=n._size,a=JSON.stringify(r),i=Math.max(n.margin.l||0,0),o=Math.max(n.margin.r||0,0),l=Math.max(n.margin.t||0,0),s=Math.max(n.margin.b||0,0),c=n._pushmargin;if(!1!==n.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(t(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-n.width)*h)/(m-h),_=(x*(1-h)+(p-n.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(t(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-n.height)*g)/(w-g),A=(k*(1-g)+(v-n.height)*(1-w))/(w-g);M>=0&&A>=0&&M+A>s+l&&(s=M,l=A)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(n.margin.pad),r.w=Math.round(n.width)-r.l-r.r,r.h=Math.round(n.height)-r.t-r.b,!n._replotting&&"{}"!==a&&a!==JSON.stringify(n._size))return z.call("plot",e)},Qr.graphJson=function(e,t,n,r,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&Qr.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(nt.isPlainObject(e)){var t,r,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===n){if("src"===t.substr(t.length-3))continue}else if("keepstream"===n){if("string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0&&!nt.isPlainObject(e.stream))continue}else if("keepall"!==n&&"string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):nt.isJSDate(e)?nt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var n=s(e);return t&&delete n.fit,n})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===r?c:JSON.stringify(c)},Qr.modifyFrames=function(e,t){var n,r,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(n=0;n0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return z.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var r,o,l=0,s=0;function c(){return l++,function(){var n;f||++s!==l||(n=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return z.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(n)))}}var d=e._fullLayout._basePlotModules,h=!1;if(n)for(o=0;o=0;i--)if(g[i].enabled){n._indexToPoints=g[i]._indexToPoints;break}r&&r.calc&&(p=r.calc(e,n))}Array.isArray(p)&&p[0]||(p=[{x:Jr,y:Jr}]),p[0].t||(p[0].t={}),p[0].trace=n,c[a]=p}z.getComponentMethod("fx","calc")(e)},Qr.rehover=function(e){e._fullLayout._rehover&&e._fullLayout._rehover()},Qr.generalUpdatePerTraceModule=function(e,t,n,r){var a,i=t.traceHash,o={};for(a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];r.attr("transform","translate("+p+")")}}}A.call(T),k&&(w?A.on(".opacity",null):(b=0,_=!0,A.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(d.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(d.HIDE_PLACEHOLDER).style("opacity",0)})),A.call(yn.makeEditable,{gd:n}).on("edit",function(e){void 0!==c?z.call("restyle",n,l,e,c):z.call("relayout",n,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(T)}).on("input",function(e){this.text(e||" ").call(yn.positionText,f.x,f.y)}));return A.classed("js-placeholder",_),p}},sa=/ [XY][0-9]* /;var ca=n.FP_SAFE,ua=pa,fa=ga,da=function(e){e._length||e.setScale();var t,n=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&n&&(e.range=pa(e),e._r=e.range.slice(),e._rl=nt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var r=e._anchorAxis.rangeslider[e._name];r&&"auto"===r.rangemode&&(r.range=n?pa(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=nt.extendFlat({},r)}},ha=function(e,n,r){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!n)return;e._min||(e._min=[]);e._max||(e._max=[]);r||(r={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=n.length,y=r.padded||!1,m=r.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((e._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),A=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-ca&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var T=m&&0===a;v.push({val:a,pad:T?0:b,extrapad:!T&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)T(a)};function pa(e){var t,n,r,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=ga(e);for(t=1;t0&&l>0&&s/l>d&&(i=r,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),nt.simpleMap(c,e.l2r||Number)}function ga(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function va(e){return t(e)&&Math.abs(e)=t}var xa=n.BADNUM,ba=function(e,n){return function(e,n){for(var r,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,n)?"date":function(e){for(var t,n=Math.max(1,(e.length-1)/1e3),r=0,a=0,i=0;i2*r}(e)?"category":function(e){if(!e)return!1;for(var n=0;n0)return Math.log(e)/Math.LN10;if(e<=0&&t&&n.range&&2===n.range.length){var r=n.range[0],a=n.range[1];return.5*(r+a-3*i*Math.abs(r-a))}return Ta}function l(e,r,a){var i=ka(e,a||n.calendar);if(i===Ta){if(!t(e))return Ta;i=ka(new Date(+e))}return i}function s(e,t,r){return wa(e,t,r||n.calendar)}function c(e){return n._categories[Math.round(e)]}function u(e){if(n._categoriesMap){var r=n._categoriesMap[e];if(void 0!==r)return r}if(t(e))return+e}function f(r){return t(r)?e.round(n._b+n._m*r,2):Ta}function d(e){return(e-n._b)/n._m}n.c2l="log"===n.type?o:Ma,n.l2c="log"===n.type?La:Ma,n.l2p=f,n.p2l=d,n.c2p="log"===n.type?function(e,t){return f(o(e,t))}:f,n.p2c="log"===n.type?function(e){return La(d(e))}:d,-1!==["linear","-"].indexOf(n.type)?(n.d2r=n.r2d=n.d2c=n.r2c=n.d2l=n.r2l=_a,n.c2d=n.c2r=n.l2d=n.l2r=Ma,n.d2p=n.r2p=function(e){return n.l2p(_a(e))},n.p2d=n.p2r=d,n.cleanPos=Ma):"log"===n.type?(n.d2r=n.d2l=function(e,t){return o(_a(e),t)},n.r2d=n.r2c=function(e){return La(_a(e))},n.d2c=n.r2l=_a,n.c2d=n.l2r=Ma,n.c2r=o,n.l2d=La,n.d2p=function(e,t){return n.l2p(n.d2r(e,t))},n.p2d=function(e){return La(d(e))},n.r2p=function(e){return n.l2p(_a(e))},n.p2r=d,n.cleanPos=Ma):"date"===n.type?(n.d2r=n.r2d=nt.identity,n.d2c=n.r2c=n.d2l=n.r2l=l,n.c2d=n.c2r=n.l2d=n.l2r=s,n.d2p=n.r2p=function(e,t,r){return n.l2p(l(e,0,r))},n.p2d=n.p2r=function(e,t,n){return s(d(e),t,n)},n.cleanPos=function(e){return nt.cleanDate(e,Ta,n.calendar)}):"category"===n.type&&(n.d2c=n.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===n._categoriesMap&&(n._categoriesMap={}),void 0!==n._categoriesMap[e])return n._categoriesMap[e];n._categories.push(e);var t=n._categories.length-1;return n._categoriesMap[e]=t,t}return Ta},n.r2d=n.c2d=n.l2d=c,n.d2r=n.d2l_noadd=u,n.r2c=function(e){var t=u(e);return void 0!==t?t:n.fraction2r(.5)},n.l2r=n.c2r=Ma,n.r2l=u,n.d2p=function(e){return n.l2p(n.r2c(e))},n.p2d=function(e){return c(d(e))},n.r2p=n.d2p,n.p2r=d,n.cleanPos=function(e){return"string"==typeof e&&""!==e?e:Ma(e)}),n.fraction2r=function(e){var t=n.r2l(n.range[0]),r=n.r2l(n.range[1]);return n.l2r(t+e*(r-t))},n.r2fraction=function(e){var t=n.r2l(n.range[0]),r=n.r2l(n.range[1]);return(n.r2l(e)-t)/(r-t)},n.cleanRange=function(e,r){r||(r={}),e||(e="range");var i,o,l=nt.nestedProperty(n,e).get();if(o=(o="date"===n.type?nt.dfltRange(n.calendar):"y"===a?Dt.DFLTRANGEY:r.dfltRange||Dt.DFLTRANGEX).slice(),l&&2===l.length)for("date"===n.type&&(l[0]=nt.cleanDate(l[0],Ta,n.calendar),l[1]=nt.cleanDate(l[1],Ta,n.calendar)),i=0;i<2;i++)if("date"===n.type){if(!nt.isDateTime(l[i],n.calendar)){n[e]=o;break}if(n.r2l(l[0])===n.r2l(l[1])){var s=nt.constrain(n.r2l(l[0]),nt.MIN_MS+1e3,nt.MAX_MS-1e3);l[0]=n.l2r(s-1e3),l[1]=n.l2r(s+1e3);break}}else{if(!t(l[i])){if(!t(l[1-i])){n[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Aa?l[i]=-Aa:l[i]>Aa&&(l[i]=Aa),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else nt.nestedProperty(n,e).set(o)},n.setScale=function(e){var t=r._size;if(n._categories||(n._categories=[]),n._categoriesMap||(n._categoriesMap={}),n.overlaying){var i=Hr.getFromId({_fullLayout:r},n.overlaying);n.domain=i.domain}var o=e&&n._r?"_r":"range",l=n.calendar;n.cleanRange(o);var s=n.r2l(n[o][0],l),c=n.r2l(n[o][1],l);if("y"===a?(n._offset=t.t+(1-n.domain[1])*t.h,n._length=t.h*(n.domain[1]-n.domain[0]),n._m=n._length/(s-c),n._b=-n._m*c):(n._offset=t.l+n.domain[0]*t.w,n._length=t.w*(n.domain[1]-n.domain[0]),n._m=n._length/(c-s),n._b=-n._m*s),!isFinite(n._m)||!isFinite(n._b))throw r._replotting=!1,new Error("Something went wrong with axis scaling")},n.makeCalcdata=function(e,t){var r,a,i,o,l=n.type,s="date"===l&&e[t+"calendar"];if(t in e){if(r=e[t],o=e._length||r.length,nt.isTypedArray(r)&&("linear"===l||"log"===l)){if(o===r.length)return r;if(r.subarray)return r.subarray(0,o)}for(a=new Array(o),i=0;i=n.r2l(n.range[0])&&r<=n.r2l(n.range[1])},n.clearCalc=function(){n._min=[],n._max=[],n._categories=(n._initialCategories||[]).slice(),n._categoriesMap={};for(var e=0;e2e-6||((n-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},Ba.saveRangeInitial=function(e,t){for(var n=Ba.list(e,"",!0),r=!1,a=0;a.3*d||u(a)||u(i))){var h=r.dtick/2;e+=e+h.8){var o=Number(n.substr(1));i.exactYears>.8&&o%12==0?e=Ba.tickIncrement(e,"M6","reverse")+1.5*za:i.exactMonths>.8?e=Ba.tickIncrement(e,"M1","reverse")+15.5*za:e-=za/2;var l=Ba.tickIncrement(e,n);if(l<=r)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=Ba.tickIncrement(h,l.dtick,!1,i),0;return{start:n.c2r(p,0,i),end:n.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},Ba.prepTicks=function(e){var t=nt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var n,r=e.nticks;r||("category"===e.type?(n=e.tickfont?1.2*(e.tickfont.size||12):15,r=e._length/n):(n="y"===e._id.charAt(0)?40:80,r=nt.constrain(e._length/n,4,9)+1),"radialaxis"===e._name&&(r*=2)),"array"===e.tickmode&&(r*=100),Ba.autoTicks(e,Math.abs(t[1]-t[0])/r),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),$a(e)},Ba.calcTicks=function(e){Ba.prepTicks(e);var t=nt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,n,r=e.tickvals,a=e.ticktext,i=new Array(r.length),o=nt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(n=0;nc&&t=r:s<=r)&&!(i.length>l||s===o);s=Ba.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+n.substr(1)%12==0?"y":"m";else if(n>=za&&i<=10||n>=15*za)e._tickround="d";else if(n>=Ea&&i<=16||n>=Da)e._tickround="M";else if(n>=Na&&i<=19||n>=Ea)e._tickround="S";else{var o=e.l2r(r+n).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(t(n)||"L"===n.charAt(0)){var l=e.range.map(e.r2d||Number);t(n)||(n=Number(n.substr(1))),e._tickround=2-Math.floor(Math.log(n)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(ti(e.exponentformat)&&!ni(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function Ka(e,t,n){var r=e.tickfont||{};return{x:t,dx:0,dy:0,text:n||"",fontSize:r.size,font:r.family,fontColor:r.color}}Ba.autoTicks=function(e,n){var r;function a(e){return Math.pow(e,Math.floor(Math.log(n)/Math.LN10))}if("date"===e.type){e.tick0=nt.dateTick0(e.calendar);var i=2*n;i>Pa?(n/=Pa,r=a(10),e.dtick="M"+12*Qa(n,r,Ua)):i>Oa?(n/=Oa,e.dtick="M"+Qa(n,1,Ga)):i>za?(e.dtick=Qa(n,za,Xa),e.tick0=nt.dateTick0(e.calendar,!0)):i>Da?e.dtick=Qa(n,Da,Ga):i>Ea?e.dtick=Qa(n,Ea,Ya):i>Na?e.dtick=Qa(n,Na,Ya):(r=a(10),e.dtick=Qa(n,r,Ua))}else if("log"===e.type){e.tick0=0;var o=nt.simpleMap(e.range,e.r2l);if(n>.7)e.dtick=Math.ceil(n);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/n);n=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=a(10),e.dtick="L"+Qa(n,r,Ua)}else e.dtick=n>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(n,1))):"angular"===e._id?(e.tick0=0,r=1,e.dtick=Qa(n,r,Ja)):(e.tick0=0,r=a(10),e.dtick=Qa(n,r,Ua));if(0===e.dtick&&(e.dtick=1),!t(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},Ba.tickIncrement=function(n,r,a,i){var o=a?-1:1;if(t(r))return n+o*r;var l=r.charAt(0),s=o*Number(r.substr(1));if("M"===l)return nt.incrementMonth(n,s,i);if("L"===l)return Math.log(Math.pow(10,n)+s)/Math.LN10;if("D"===l){var c="D2"===r?Wa:Za,u=n+.01*o,f=nt.roundUp(nt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(r)},Ba.tickFirst=function(n){var r=n.r2l||Number,a=nt.simpleMap(n.range,r),i=a[1]"+l,e._prevDateHead=l));n.text=s}(e,o,r,s):"log"===e.type?function(e,n,r,a,i){var o=e.dtick,l=n.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))n.text=ri(Math.pow(10,l),e,i,a);else if(t(o)||"D"===o.charAt(0)&&nt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||ti(e.exponentformat)&&ni(c)?(n.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+Ra+-c+"",n.fontSize*=1.25):(n.text=ri(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(n.dy-=n.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);n.text=String(Math.round(Math.pow(10,nt.mod(l,1)))),n.fontSize*=.75}if("D1"===e.dtick){var u=String(n.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?n.dx-=n.fontSize/4:(n.dy+=n.fontSize/2,n.dx+=(e.range[1]>e.range[0]?1:-1)*n.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var n=e._categories[Math.round(t.x)];void 0===n&&(n="");t.text=String(n)}(e,o):"angular"===e._id?function(e,t,n,r,a){if("radians"!==e.thetaunit||n)t.text=ri(t.x,e,a,r);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var n=function(e){var n=1;for(;!t(Math.round(e*n)/n,e);)n*=10;return n}(e),r=e*n,a=Math.abs(function e(n,r){return t(r,0)?n:e(r,n%r)}(r,n));return[Math.round(r/a),Math.round(n/a)]}(i);if(o[1]>=100)t.text=ri(nt.deg2rad(t.x),e,a,r);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=Ra+t.text)}}}}(e,o,r,s,a):function(e,t,n,r,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=ri(t.x,e,a,r)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},Ba.hoverLabelText=function(e,t,n){if(n!==Ia&&n!==t)return Ba.hoverLabelText(e,t)+" - "+Ba.hoverLabelText(e,n);var r="log"===e.type&&t<=0,a=Ba.tickText(e,e.c2l(r?-t:t),"hover").text;return r?0===t?"0":Ra+a:a};var ei=["f","p","n","\u03bc","m","","k","M","G","T"];function ti(e){return"SI"===e||"B"===e}function ni(e){return e>14||e<-15}function ri(e,n,r,a){var i=e<0,o=n._tickround,l=r||n.exponentformat||"B",s=n._tickexponent,c=Ba.getTickFormat(n),u=n.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===n.showexponent?n.dtick:t(e)&&Math.abs(e)||1,range:"none"===n.showexponent?n.range.map(n.r2d):[0,e||1]};$a(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,n.hoverformat&&(c=n.hoverformat)}if(c)return n._numFormat(c)(e).replace(/-/g,Ra);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":ti(l)&&(e+=ei[s/3+5]));return i?Ra+e:e}function ai(e,t){for(var n=0;n=0,i=c(e,t[1])<=0;return(n||a)&&(r||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(r))){n=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(r=1;r-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.extraText&&(s+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),""===s&&(""===l&&n.remove(),s=l);var g=n.select("text.nums").call(Vn.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(yn.positionText,0,0).call(yn.convertToTspans,r),y=n.select("text.name"),m=0;l&&l!==s?(y.call(Vn.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(yn.positionText,0,0).call(yn.convertToTspans,r),m=y.node().getBoundingClientRect().width+2*pi):(y.remove(),n.select("rect").remove()),n.select("path").style({fill:d,stroke:h});var k,M,A=g.node().getBoundingClientRect(),T=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),P=A.width+hi+pi+m;t.ty0=x-A.top,t.bx=A.width+2*pi,t.by=A.height+2*pi,t.anchor="start",t.txwidth=A.width,t.tx2width=m,t.offset=0,i?(t.pos=T,k=L+S/2+P<=_,M=L-S/2-P>=0,"top"!==t.idealAlign&&k||!M?k?(L+=S/2,t.anchor="start"):t.anchor="middle":(L-=S/2,t.anchor="end")):(t.pos=L,k=T+C/2+P<=b,M=T-C/2-P>=0,"left"!==t.idealAlign&&k||!M?k?(T+=C/2,t.anchor="start"):t.anchor="middle":(T-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),n.attr("transform","translate("+T+","+L+")"+(i?"rotate("+si+")":""))}),C}function vi(t,n){t.each(function(t){var r=e.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(hi+pi),s=l+o*(t.txwidth+pi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+pi),n&&(u*=-di,c=t.offset*fi),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*hi+c)+","+(hi+u)+"v"+(t.by/2-hi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*hi+c)+"V"+(u-hi)+"Z"),i.call(yn.positionText,l+c,u+t.ty0-t.by/2+pi),t.tx2width&&(r.select("text.name").call(yn.positionText,s+o*pi+c,u+t.ty0-t.by/2+pi),r.select("rect").call(Vn.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function yi(e,t){var n=e.index,r=e.trace||{},a=e.cd[0],i=e.cd[n]||{},o=Array.isArray(n)?function(e,t){return nt.castOption(a,n,e)||nt.extractOption({},r,"",t)}:function(e,t){return nt.extractOption(i,r,e,t)};function l(t,n,r){var a=o(n,r);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=nt.constrain(e.x0,0,e.xa._length),e.x1=nt.constrain(e.x1,0,e.xa._length),e.y0=nt.constrain(e.y0,0,e.ya._length),e.y1=nt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:Sa.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:Sa.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=Sa.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+Sa.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=Sa.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+Sa.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function mi(e,t){var n,r,a=t.container,i=t.fullLayout,o=t.event,s=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||s){var u=dt.combine(i.plot_bgcolor,i.paper_bgcolor);if(s){var f,d,h=e.hLinePoint;n=h&&h.xa,"cursor"===(r=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=n._offset+h.x,d=r._offset+h.y);var p,g,v=l.readability(h.color,u)<1.5?dt.contrast(u):h.color,y=r.spikemode,m=r.spikethickness,x=r.spikecolor||v,b=r._boundingBox,_=(b.left+b.right)/2V.width||q<0||q>V.height)return Et.unhoverRaw(n,r);r.pointerX=r.offsetX,r.pointerY=r.offsetY}if(_="xval"in r?cr.flat(o,r.xval):cr.p2c(h,B),w="yval"in r?cr.flat(o,r.yval):cr.p2c(p,q),!t(_[0])||!t(w[0]))return nt.warn("Fx.hover failed",r,n),Et.unhoverRaw(n,r)}var U=1/0;for(M=0;ME&&(I.splice(0,E),U=I[0].distance),u&&0!==R&&0===I.length){D.distance=R,D.index=!1;var W=T._module.hoverPoints(D,P,O,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=R})),W&&W.length){var J,Q=W.filter(function(e){return e.xa.showspikes});if(Q.length){var $=Q[0];t($.x0)&&t($.y0)&&(J=ne($),(!j.vLinePoint||j.vLinePoint.spikeDistance>J.spikeDistance)&&(j.vLinePoint=J))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];t(ee.x0)&&t(ee.y0)&&(J=ne(ee),(!j.hLinePoint||j.hLinePoint.spikeDistance>J.spikeDistance)&&(j.hLinePoint=J))}}}}function te(e,t){for(var n,r=null,a=1/0,i=0;i1,ge=dt.combine(l.plot_bgcolor||dt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=gi(I,ve,n);if(function(e,t,n){var r,a,i,o,l,s,c,u=0,f=e.map(function(e,r){var a=e[t];return[{i:r,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?ui:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?n.width:n.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],n=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=n.pos+n.dp+n.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;r=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;r=!1}if(r){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!r&&u<=e.length;){for(u++,r=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;r=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(I,pe?"xa":"ya",l),vi(ye,pe),r.target&&r.target.tagName){var me=z.getComponentMethod("annotations","hasClickToShow")(n,de);gr(e.select(r.target),me?"pointer":"")}if(!r.target||i||!function(e,t,n){if(!n||n.length!==e._hoverdata.length)return!0;for(var r=n.length-1;r>=0;r--){var a=n[r],i=e._hoverdata[r];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(n,0,fe))return;fe&&n.emit("plotly_unhover",{event:r,points:fe});n.emit("plotly_hover",{event:r,points:n._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(n,r,a,i)})},li.loneHover=function(t,n){var r={color:t.color||dt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(n.container),i=n.outerContainer?e.select(n.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:n.bgColor||dt.background,container:a,outerContainer:i},l=gi([r],o,n.gd);return vi(l,o.rotateLabels),l.node()};var bi=li.hover,_i=function(e,t,n,r){n("hoverlabel.bgcolor",(r=r||{}).bgcolor),n("hoverlabel.bordercolor",r.bordercolor),n("hoverlabel.namelength",r.namelength),nt.coerceFont(n,"hoverlabel.font",r.font)},wi=T({editType:"none"});wi.family.dflt=wt.HOVERFONT,wi.size.dflt=wt.HOVERFONTSIZE;var ki={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:wi,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var Mi={moduleType:"component",name:"fx",constants:wt,schema:{layout:ki},attributes:L,layoutAttributes:ki,supplyLayoutGlobalDefaults:function(e,t){_i(0,0,function(n,r){return nt.coerce(e,t,ki,n,r)})},supplyDefaults:function(e,t,n,r){_i(0,0,function(n,r){return nt.coerce(e,t,L,n,r)},r.hoverlabel)},supplyLayoutDefaults:function(e,t,n){function r(n,r){return nt.coerce(e,t,ki,n,r)}var a;r("dragmode"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,n=0;n0})}function c(e,r){var a=e.seg,i=r.seg,o=a.start,s=a.end,c=i.start,u=i.end;n&&n.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return r;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(r,s):l(e,u),r;p&&(h||(g?l(r,s):l(e,u)),l(r,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(r,o):0===f.alongA?l(r,f.pt):1===f.alongA&&l(r,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(n&&n.vert(f.pt[0]),f.isStart){n&&n.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}n&&n.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,n&&n.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){n&&n.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:r,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:r,f.seg.otherFill={above:v,below:v}),n&&n.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(zi.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),n&&n.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return n&&n.done(),u}return e?{addRegion:function(e){for(var r,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,n,r){var a=t[1]-n[1],i=r[0]-n[0],o=t[0]-n[0],l=r[1]-n[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,n){return Math.abs(t[0]-n[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-r>e&&(l=!l),i=c,o=u}return l}};return t}();function Bi(e,t,n){var r=Ri.segments(e),a=Ri.segments(t),i=n(Ri.combine(r,a));return Ri.polygon(i)}Ri={buildLog:function(e){return!0===e?Fi=Pi():!1===e&&(Fi=!1),!1!==Fi&&Fi.list},epsilon:function(e){return ji.epsilon(e)},segments:function(e){var t=Di(!0,ji,Fi);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Di(!1,ji,Fi).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:Ii.union(e.combined,Fi),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:Ii.intersect(e.combined,Fi),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:Ii.difference(e.combined,Fi),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:Ii.differenceRev(e.combined,Fi),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:Ii.xor(e.combined,Fi),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Ei(e.segments,ji,Fi),inverted:e.inverted}},polygonFromGeoJSON:function(e){return Oi.toPolygon(Ri,e)},polygonToGeoJSON:function(e){return Oi.fromPolygon(Ri,ji,e)},union:function(e,t){return Bi(e,t,Ri.selectUnion)},intersect:function(e,t){return Bi(e,t,Ri.selectIntersect)},difference:function(e,t){return Bi(e,t,Ri.selectDifference)},differenceRev:function(e,t){return Bi(e,t,Ri.selectDifferenceRev)},xor:function(e,t){return Bi(e,t,Ri.selectXor)}},"object"==typeof window&&(window.PolyBool=Ri);var qi=Ri,Hi={},Vi=Be.dot,Ui=n.BADNUM,Gi=Hi={};Gi.tester=function(e){if(Array.isArray(e[0][0]))return Gi.multitester(e);var t,n=e.slice(),r=n[0][0],a=r,i=n[0][1],o=i;for(n.push(n[0]),t=1;ta||s===Ui||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===Ui||la||s===Ui||so)return!1;var c,u,f,d,h,p=n.length,g=n[0][0],v=n[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(Vi(i,f))>r)return!0;return!1};Gi.filter=function(e,t){var n=[e[0]],r=0,a=0;function i(i){e.push(i);var o=n.length,l=r;n.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:n}};var Xi=cr.makeEventData,Zi=Hi.filter,Wi=Hi.tester,Ji=Hi.multitester,Qi=Dt.MINSELECT;function $i(e){return e._id}var Ki=function(e,t,n,r,a){var i,o,l,s,c=r.gd,u=c._fullLayout,f=u._zoomlayer,d=r.element.getBoundingClientRect(),h=r.plotinfo,p=h.xaxis._offset,g=h.yaxis._offset,v=t-d.left,y=n-d.top,m=v,x=y,b="M"+v+","+y,_=r.xaxes[0]._length,w=r.yaxes[0]._length,k=r.xaxes.map($i),M=r.yaxes.map($i),A=r.xaxes.concat(r.yaxes),T=e.altKey;(e.shiftKey||e.altKey)&&h.selection&&h.selection.polygons&&!r.polygons?(r.polygons=h.selection.polygons,r.mergedPolygons=h.selection.mergedPolygons):(!e.shiftKey&&!e.altKey||(e.shiftKey||e.altKey)&&!h.selection)&&(h.selection={},h.selection.polygons=r.polygons=[],h.selection.mergedPolygons=r.mergedPolygons=[]),"lasso"===a&&(i=Zi([[v,y]],Dt.BENDPX));var L=f.selectAll("path.select-outline-"+h.id).data([1,2]);L.enter().append("path").attr("class",function(e){return"select-outline select-outline-"+e+" select-outline-"+h.id}).attr("transform","translate("+p+", "+g+")").attr("d",b+"Z");var C,S,P,O,z,D,E=f.append("path").attr("class","zoombox-corners").style({fill:dt.background,stroke:dt.defaultLine,"stroke-width":1}).attr("transform","translate("+p+", "+g+")").attr("d","M0,0Z"),N=[],R=u._uid+Dt.SELECTID,I=[];for(C=0;Cr^h>r&&n<(d-c)*(r-u)/(h-u)+c&&(a=!a)}return a}(e[0],n))return e.push(t),!0})||e.push([t])}),i=[],e.length?e.length>1?{type:"MultiPolygon",coordinates:e}:{type:"Polygon",coordinates:e[0]}:null}},c={Point:o,MultiPoint:o,LineString:l,MultiLineString:l,Polygon:s,MultiPolygon:s,Sphere:s};function u(){}var f=1e-6,d=f*f,h=Math.PI,p=h/2,g=(Math.sqrt(h),h/180),v=180/h;function y(e){return e>1?p:e<-1?-p:Math.asin(e)}function m(e){return e>1?0:e<-1?h:Math.acos(e)}var x=e.geo.projection,b=e.geo.projectionMutator;function _(e,t){var n=(2+p)*Math.sin(t);t/=2;for(var r=0,a=1/0;r<10&&Math.abs(a)>f;r++){var i=Math.cos(t);t-=a=(t+Math.sin(t)*(i+2)-n)/(2*i*(1+i))}return[2/Math.sqrt(h*(4+h))*e*(1+Math.cos(t)),2*Math.sqrt(h/(4+h))*Math.sin(t)]}e.geo.interrupt=function(t){var n,r=[[[[-h,0],[0,p],[h,0]]],[[[-h,0],[0,-p],[h,0]]]];function a(e,n){for(var a=n<0?-1:1,i=r[+(n<0)],o=0,l=i.length-1;oi[o][2][0];++o);var s=t(e-i[o][1][0],n);return s[0]+=t(i[o][1][0],a*n>a*i[o][0][1]?i[o][0][1]:n)[0],s}t.invert&&(a.invert=function(e,i){for(var o=n[+(i<0)],l=r[+(i<0)],c=0,u=o.length;c=0;--a){var o=r[1][a],s=180*o[0][0]/h,c=180*o[0][1]/h,u=180*o[1][1]/h,f=180*o[2][0]/h,d=180*o[2][1]/h;n.push(l([[f-t,d-t],[f-t,u+t],[s+t,u+t],[s+t,c-t]],30))}return{type:"Polygon",coordinates:[e.merge(n)]}}(),s)},a},i.lobes=function(e){return arguments.length?(r=e.map(function(e){return e.map(function(e){return[[e[0][0]*h/180,e[0][1]*h/180],[e[1][0]*h/180,e[1][1]*h/180],[e[2][0]*h/180,e[2][1]*h/180]]})}),n=r.map(function(e){return e.map(function(e){var n,r=t(e[0][0],e[0][1])[0],a=t(e[2][0],e[2][1])[0],i=t(e[1][0],e[0][1])[1],o=t(e[1][0],e[1][1])[1];return i>o&&(n=i,i=o,o=n),[[r,i],[a,o]]})}),i):r.map(function(e){return e.map(function(e){return[[180*e[0][0]/h,180*e[0][1]/h],[180*e[1][0]/h,180*e[1][1]/h],[180*e[2][0]/h,180*e[2][1]/h]]})})},i},_.invert=function(e,t){var n=.5*t*Math.sqrt((4+h)/h),r=y(n),a=Math.cos(r);return[e/(2/Math.sqrt(h*(4+h))*(1+a)),y((r+n*(a+2))/(2+p))]},(e.geo.eckert4=function(){return x(_)}).raw=_;var w=e.geo.azimuthalEqualArea.raw;function k(e,t){if(arguments.length<2&&(t=e),1===t)return w;if(t===1/0)return M;function n(n,r){var a=w(n/t,r);return a[0]*=e,a}return n.invert=function(n,r){var a=w.invert(n/e,r);return a[0]*=t,a},n}function M(e,t){return[e*Math.cos(t)/Math.cos(t/=2),2*Math.sin(t)]}function A(e,t){return[3*e/(2*h)*Math.sqrt(h*h/3-t*t),t]}function T(e,t){return[e,1.25*Math.log(Math.tan(h/4+.4*t))]}function L(e){return function(t){var n,r=e*Math.sin(t),a=30;do{t-=n=(t+Math.sin(t)-r)/(1+Math.cos(t))}while(Math.abs(n)>f&&--a>0);return t/2}}M.invert=function(e,t){var n=2*y(t/2);return[e*Math.cos(n/2)/Math.cos(n),n]},(e.geo.hammer=function(){var e=2,t=b(k),n=t(e);return n.coefficient=function(n){return arguments.length?t(e=+n):e},n}).raw=k,A.invert=function(e,t){return[2/3*h*e/Math.sqrt(h*h/3-t*t),t]},(e.geo.kavrayskiy7=function(){return x(A)}).raw=A,T.invert=function(e,t){return[e,2.5*Math.atan(Math.exp(.8*t))-.625*h]},(e.geo.miller=function(){return x(T)}).raw=T,L(h);var C=function(e,t,n){var r=L(n);function a(n,a){return[e*n*Math.cos(a=r(a)),t*Math.sin(a)]}return a.invert=function(r,a){var i=y(a/t);return[r/(e*Math.cos(i)),y((2*i+Math.sin(2*i))/n)]},a}(Math.SQRT2/p,Math.SQRT2,h);function S(e,t){var n=t*t,r=n*n;return[e*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),t*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}(e.geo.mollweide=function(){return x(C)}).raw=C,S.invert=function(e,t){var n,r=t,a=25;do{var i=r*r,o=i*i;r-=n=(r*(1.007226+i*(.015085+o*(.028874*i-.044475-.005916*o)))-t)/(1.007226+i*(.045255+o*(.259866*i-.311325-.005916*11*o)))}while(Math.abs(n)>f&&--a>0);return[e/(.8707+(i=r*r)*(i*(i*i*i*(.003971-.001529*i)-.013791)-.131979)),r]},(e.geo.naturalEarth=function(){return x(S)}).raw=S;var P=[[.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]];function O(e,t){var n,r=Math.min(18,36*Math.abs(t)/h),a=Math.floor(r),i=r-a,o=(n=P[a])[0],l=n[1],s=(n=P[++a])[0],c=n[1],u=(n=P[Math.min(19,++a)])[0],f=n[1];return[e*(s+i*(u-o)/2+i*i*(u-2*s+o)/2),(t>0?p:-p)*(c+i*(f-l)/2+i*i*(f-2*c+l)/2)]}function z(e,t){return[e*Math.cos(t),t]}function D(e,t){var n,r=Math.cos(t),a=(n=m(r*Math.cos(e/=2)))?n/Math.sin(n):1;return[2*r*Math.sin(e)*a,Math.sin(t)*a]}function E(e,t){var n=D(e,t);return[(n[0]+e/p)/2,(n[1]+t)/2]}P.forEach(function(e){e[1]*=1.0144}),O.invert=function(e,t){var n=t/p,r=90*n,a=Math.min(18,Math.abs(r/5)),i=Math.max(0,Math.floor(a));do{var o=P[i][1],l=P[i+1][1],s=P[Math.min(19,i+2)][1],c=s-o,u=s-2*l+o,f=2*(Math.abs(n)-l)/c,h=u/c,y=f*(1-h*f*(1-2*h*f));if(y>=0||1===i){r=(t>=0?5:-5)*(y+a);var m,x=50;do{y=(a=Math.min(18,Math.abs(r)/5))-(i=Math.floor(a)),o=P[i][1],l=P[i+1][1],s=P[Math.min(19,i+2)][1],r-=(m=(t>=0?p:-p)*(l+y*(s-o)/2+y*y*(s-2*l+o)/2)-t)*v}while(Math.abs(m)>d&&--x>0);break}}while(--i>=0);var b=P[i][0],_=P[i+1][0],w=P[Math.min(19,i+2)][0];return[e/(_+y*(w-b)/2+y*y*(w-2*_+b)/2),r*g]},(e.geo.robinson=function(){return x(O)}).raw=O,z.invert=function(e,t){return[e/Math.cos(t),t]},(e.geo.sinusoidal=function(){return x(z)}).raw=z,D.invert=function(e,t){if(!(e*e+4*t*t>h*h+f)){var n=e,r=t,a=25;do{var i,o=Math.sin(n),l=Math.sin(n/2),s=Math.cos(n/2),c=Math.sin(r),u=Math.cos(r),d=Math.sin(2*r),p=c*c,g=u*u,v=l*l,y=1-g*s*s,x=y?m(u*s)*Math.sqrt(i=1/y):i=0,b=2*x*u*l-e,_=x*c-t,w=i*(g*v+x*u*s*p),k=i*(.5*o*d-2*x*c*l),M=.25*i*(d*l-x*c*g*o),A=i*(p*s+x*v*u),T=k*M-A*w;if(!T)break;var L=(_*k-b*A)/T,C=(b*M-_*w)/T;n-=L,r-=C}while((Math.abs(L)>f||Math.abs(C)>f)&&--a>0);return[n,r]}},(e.geo.aitoff=function(){return x(D)}).raw=D,E.invert=function(e,t){var n=e,r=t,a=25;do{var i,o=Math.cos(r),l=Math.sin(r),s=Math.sin(2*r),c=l*l,u=o*o,d=Math.sin(n),h=Math.cos(n/2),g=Math.sin(n/2),v=g*g,y=1-u*h*h,x=y?m(o*h)*Math.sqrt(i=1/y):i=0,b=.5*(2*x*o*g+n/p)-e,_=.5*(x*l+r)-t,w=.5*i*(u*v+x*o*h*c)+.5/p,k=i*(d*s/4-x*l*g),M=.125*i*(s*g-x*l*u*d),A=.5*i*(c*h+x*v*o)+.5,T=k*M-A*w,L=(_*k-b*A)/T,C=(b*M-_*w)/T;n-=L,r-=C}while((Math.abs(L)>f||Math.abs(C)>f)&&--a>0);return[n,r]},(e.geo.winkel3=function(){return x(E)}).raw=E},ro=Math.PI/180,ao=180/Math.PI,io={cursor:"pointer"},oo={cursor:"auto"};var lo=function(e,t){var n=e.projection;return(t._isScoped?uo:t._isClipped?ho:fo)(e,n)};function so(t,n){return e.behavior.zoom().translate(n.translate()).scale(n.scale())}function co(e,t,n){var r=e.id,a=e.graphDiv,i=a.layout[r],o=a._fullLayout[r],l={};function s(e,t){var n=nt.nestedProperty(o,e);n.get()!==t&&(n.set(t),nt.nestedProperty(i,e).set(t),l[r+"."+e]=t)}n(s),s("projection.scale",t.scale()/e.fitScale),a.emit("plotly_relayout",l)}function uo(t,n){var r=so(0,n);function a(e){var r=n.invert(t.midPt);e("center.lon",r[0]),e("center.lat",r[1])}return r.on("zoomstart",function(){e.select(this).style(io)}).on("zoom",function(){n.scale(e.event.scale).translate(e.event.translate),t.render()}).on("zoomend",function(){e.select(this).style(oo),co(t,n,a)}),r}function fo(t,n){var r,a,i,o,l,s,c,u,f=so(0,n),d=2;function h(e){return n.invert(e)}function p(e){var r=n.rotate(),a=n.invert(t.midPt);e("projection.rotation.lon",-r[0]),e("center.lon",a[0]),e("center.lat",a[1])}return f.on("zoomstart",function(){e.select(this).style(io),r=e.mouse(this),a=n.rotate(),i=n.translate(),o=a,l=h(r)}).on("zoom",function(){if(s=e.mouse(this),g=n(h(p=r)),Math.abs(g[0]-p[0])>d||Math.abs(g[1]-p[1])>d)return f.scale(n.scale()),void f.translate(n.translate());var p,g;n.scale(e.event.scale),n.translate([i[0],e.event.translate[1]]),l?h(s)&&(u=h(s),c=[o[0]+(u[0]-l[0]),a[1],a[2]],n.rotate(c),o=c):l=h(r=s),t.render()}).on("zoomend",function(){e.select(this).style(oo),co(t,n,p)}),f}function ho(t,n){var r,a={r:n.rotate(),k:n.scale()},i=so(0,n),o=function(t){var n=0,r=arguments.length,a=[];for(;++nh?(i=(u>0?90:-90)-d,a=0):(i=Math.asin(u/h)*ao-d,a=Math.sqrt(h*h-u*u));var p=180-i-2*d,g=(Math.atan2(f,c)-Math.atan2(s,a))*ao,v=(Math.atan2(f,c)-Math.atan2(s,-a))*ao,y=go(n[0],n[1],i,g),m=go(n[0],n[1],p,v);return y<=m?[i,g,n[2]]:[p,v,n[2]]}(m,r,_);isFinite(M[0])&&isFinite(M[1])&&isFinite(M[2])||(M=_),n.rotate(M),_=M}}else r=po(n,x=g);o.of(this,arguments)({type:"zoom"})}),m=o.of(this,arguments),l++||m({type:"zoomstart"})}).on("zoomend",function(){var r;e.select(this).style(oo),s.call(i,"zoom",null),r=o.of(this,arguments),--l||r({type:"zoomend"}),co(t,n,c)}).on("zoom.redraw",function(){t.render()}),e.rebind(i,o,"on")}function po(e,t){var n=e.invert(t);return n&&isFinite(n[0])&&isFinite(n[1])&&function(e){var t=e[0]*ro,n=e[1]*ro,r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}(n)}function go(e,t,n,r){var a=vo(n-e),i=vo(r-t);return Math.sqrt(a*a+i*i)}function vo(e){return(e%360+540)%360-180}function yo(e,t,n){var r=n*ro,a=e.slice(),i=0===t?1:0,o=2===t?1:2,l=Math.cos(r),s=Math.sin(r);return a[i]=e[i]*l-e[o]*s,a[o]=e[o]*l+e[i]*s,a}function mo(e,t){for(var n=0,r=0,a=e.length;ra*Math.PI/180}return!1},r.getPath=function(){return e.geo.path().projection(r)},r.getBounds=function(e){return r.getPath().bounds(e)},r.fitExtent=function(e,t){var n=e[1][0]-e[0][0],a=e[1][1]-e[0][1],i=r.clipExtent&&r.clipExtent();r.scale(150).translate([0,0]),i&&r.clipExtent(null);var o=r.getBounds(t),l=Math.min(n/(o[1][0]-o[0][0]),a/(o[1][1]-o[0][1])),s=+e[0][0]+(n-l*(o[1][0]+o[0][0]))/2,c=+e[0][1]+(a-l*(o[1][1]+o[0][1]))/2;return i&&r.clipExtent(i),r.scale(150*l).translate([s,c])},r.precision(Ai.precision),a&&r.clipAngle(a-Ai.clipPad);return r}(n);s.center([l.lon-o.lon,l.lat-o.lat]).rotate([-o.lon,-o.lat,o.roll]).parallels(i.parallels);var c=[[r.l+r.w*a.x[0],r.t+r.h*(1-a.y[1])],[r.l+r.w*a.x[1],r.t+r.h*(1-a.y[0])]],u=n.lonaxis,f=n.lataxis,d=function(e,t){var n=Ai.clipPad,r=e[0]+n,a=e[1]-n,i=t[0]+n,o=t[1]-n;r>0&&a<0&&(a+=360);var l=(a-r)/4;return{type:"Polygon",coordinates:[[[r,i],[r,o],[r+l,o],[r+2*l,o],[r+3*l,o],[a,o],[a,i],[a-l,i],[a-2*l,i],[a-3*l,i],[r,i]]]}}(u.range,f.range);s.fitExtent(c,d);var h=this.bounds=s.getBounds(d),p=this.fitScale=s.scale(),g=s.translate();if(!isFinite(h[0][0])||!isFinite(h[0][1])||!isFinite(h[1][0])||!isFinite(h[1][1])||isNaN(g[0])||isNaN(g[0])){for(var v=this.graphDiv,y=["projection.rotation","center","lonaxis.range","lataxis.range"],m="Invalid geo settings, relayout'ing to default view.",x={},b=0;b0&&b<0&&(b+=360);var _,w,k,M=(x+b)/2;if(!l){var A=s?i.projRotate:[M,0,0];_=n("projection.rotation.lon",A[0]),n("projection.rotation.lat",A[1]),n("projection.rotation.roll",A[2]),n("showcoastlines",!s)&&(n("coastlinecolor"),n("coastlinewidth")),n("showocean")&&n("oceancolor")}(l?(w=-96.6,k=38.7):(w=s?M:_,k=(m[0]+m[1])/2),n("center.lon",w),n("center.lat",k),c)&&n("projection.parallels",i.projParallels||[0,60]);n("projection.scale"),n("showland")&&n("landcolor"),n("showlakes")&&n("lakecolor"),n("showrivers")&&(n("rivercolor"),n("riverwidth")),n("showcountries",s&&"usa"!==a)&&(n("countrycolor"),n("countrywidth")),("usa"===a||"north america"===a&&50===r)&&(n("showsubunits",!0),n("subunitcolor"),n("subunitwidth")),s||n("showframe",!0)&&(n("framecolor"),n("framewidth")),n("bgcolor")}var Oo={},zo=Dt.SUBPLOT_PATTERN;Oo.getSubplotCalcData=function(e,t,n){var r=z.subplotsRegistry[t];if(!r)return[];for(var a=r.attr,i=[],o=0;o0&&e[t+1][0]<0)return t;return null}switch(t="RUS"===l||"FJI"===l?function(e){var t;if(null===c(e))t=e;else for(t=new Array(e.length),a=0;at?n[r++]=[e[a][0]+360,e[a][1]]:a===t?(n[r++]=e[a],n[r++]=[e[a][0],-90]):n[r++]=e[a];var i=Hi.tester(n);i.pts.pop(),s.push(i)}:function(e){s.push(Hi.tester(e))},i.type){case"MultiPolygon":for(n=0;n0;i&&(r="array");var o=n("categoryorder",r);"array"===o&&n("categoryarray"),i||"array"!==o||(t.categoryorder="trace")}}(t,n,r),n._initialCategories="category"===c?function(t,n,r,a){switch(n){case"array":return Array.isArray(r)?r.slice():[];case"category ascending":return ul(t,e.ascending,a);case"category descending":return ul(t,e.descending,a);case"trace":default:return[]}}(o,n.categoryorder,n.categoryarray,a.data):[],"category"===c||a.noHover||r("hoverformat"),!s)return n;var f=r("color"),d=f===t.color?f:l.color;return r("title",i._dfltTitle[o]),nt.coerceFont(r,"titlefont",{family:l.family,size:Math.round(1.2*l.size),color:d}),ln(t,n,r,c),rn(t,n,r,c,a),an(t,n,r,a),function(e,t,n,r){var a=(r=r||{}).dfltColor;function i(n,a){return nt.coerce2(e,t,r.attributes,n,a)}var o=i("linecolor",a),l=i("linewidth");n("showline",r.showLine||!!o||!!l)||(delete t.linecolor,delete t.linewidth);var s=i("gridcolor",sl(a,r.bgColor,r.blend||cl).toRgbString()),c=i("gridwidth");if(n("showgrid",r.showGrid||!!s||!!c)||(delete t.gridcolor,delete t.gridwidth),!r.noZeroLine){var u=i("zerolinecolor",a),f=i("zerolinewidth");n("zeroline",r.showGrid||!!u||!!f)||(delete t.zerolinecolor,delete t.zerolinewidth)}}(t,n,r,{dfltColor:f,bgColor:a.bgColor,showGrid:a.showGrid,attributes:en}),(n.showline||n.ticks)&&r("mirror"),a.automargin&&r("automargin"),n},dl=function(e,n,r,a){var i,o,l,s,c=a.counterAxes||[],u=a.overlayableAxes||[],f=a.letter,d=a.grid;d&&(o=d._domains[f][d._axisMap[n._id]],i=d._anchors[n._id],o&&(l=d[f+"side"].split(" ")[0],s=d.domain[f]["right"===l||"top"===l?1:0])),o=o||[0,1],i=i||(t(e.position)?"free":c[0]||"free"),l=l||("x"===f?"bottom":"left"),s=s||0,"free"===nt.coerce(e,n,{anchor:{valType:"enumerated",values:["free"].concat(c),dflt:i}},"anchor")&&r("position",s),nt.coerce(e,n,{side:{valType:"enumerated",values:"x"===f?["bottom","top"]:["left","right"],dflt:l}},"side");var h=!1;if(u.length&&(h=nt.coerce(e,n,{overlaying:{valType:"enumerated",values:[!1].concat(u),dflt:!1}},"overlaying")),!h){var p=r("domain",o);p[0]>p[1]-.01&&(n.domain=o),nt.noneOrAll(e.domain,n.domain,o)}return r("layer"),n},hl=y.extendFlat,pl=pn.LINE_SPACING,gl={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},vl=function(t,n){var r={};function a(){var o=t._fullLayout,s=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var c,u,f=e.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),d=[],h=[],p="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,y=r.levels.size,m=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(u=0;u<1e5&&(c=r.levels.start+u*y,!(y>0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var H=Math.pow(10,Math.floor(Math.log(q)/Math.LN10));j*=H*nt.roundUp(q/H,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(I.tick0=0)}I.dtick=j}I.domain=[D+S,D+T-S],I.setScale();var V=o._infolayer.selectAll("g."+n).data([0]);V.enter().append("g").classed(n,!0).classed(gl.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(gl.cbbg,!0),t.append("g").classed(gl.cbfills,!0),t.append("g").classed(gl.cblines,!0),t.append("g").classed(gl.cbaxis,!0).classed(gl.crisp,!0),t.append("g").classed(gl.cbtitleunshift,!0).append("g").classed(gl.cbtitle,!0),t.append("rect").classed(gl.cboutline,!0),t.select(".cbtitle").datum(0)}),V.attr("transform","translate("+Math.round(s.l)+","+Math.round(s.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(s.l)+",-"+Math.round(s.t)+")");I._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var Y,X=s.l+(r.x+L)*s.w,Z=I.titlefont.size;Y="top"===r.titleside?(1-(D+T-S))*s.h+s.t+3+.75*Z:(1-(D+S))*s.h+s.t-3-.25*Z,ee(I._id+"title",{attributes:{x:X,y:Y,"text-anchor":"start"}})}var W,J,Q,$=nt.syncOrAsync([Zr.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var n=V.select(".cbtitle"),a=n.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],c=n.select(".h"+I._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*pl),c?(G=Vn.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(gl.jsPlaceholder)&&(G=Vn.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)I.domain[1]-=G/s.h,i[1]*=-1;else{I.domain[0]+=G/s.h;var v=yn.lineCount(a);i[1]+=(1-v)*u}n.attr("transform","translate("+i+")"),I.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(s.h*(1-I.domain[1]))+")"),I._axislayer.attr("transform","translate(0,"+Math.round(-s.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(gl.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,n){var r=[0===n?f[0]:(h[n]+h[n-1])/2,n===h.length-1?f[1]:(h[n]+h[n+1])/2].map(I.c2p).map(Math.round);n!==h.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=l(a).toHexString();e.select(this).attr({x:P,width:Math.max(k,2),y:e.min(r),height:Math.max(e.max(r)-e.min(r),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?d:[]);return m.enter().append("path").classed(gl.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+P+","+(Math.round(I.c2p(t))+r.line.width/2%1)+"h"+k).call(Vn.lineGroupStyle,r.line.width,p(t),r.line.dash)}),I._axislayer.selectAll("g."+I._id+"tick,path").remove(),I._pos=P+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),I.side="right",nt.syncOrAsync([function(){return Sa.doTicks(t,I,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var n=I.titlefont.size,a=I._offset+I._length/2,i=s.l+(I.position||0)*s.w+("right"===I.side?10+n*(I.showticklabels?1:.5):-10-n*(I.showticklabels?.5:0));ee("h"+I._id+"title",{avoid:{selection:e.select(t).selectAll("g."+I._id+"tick"),side:r.titleside,offsetLeft:s.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Zr.previousPromises,function(){var e=k+r.outlinewidth/2+Vn.bBox(I._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(gl.jsPlaceholder)){var a,i=U.select(".h"+I._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Vn.bBox(i).width:Vn.bBox(U.node()).right-P-s.l,e=Math.max(e,a)}var o=2*r.xpad+e+r.borderwidth+r.outlinewidth/2,l=E-N;V.select(".cbbg").attr({x:P-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:N-C,width:Math.max(o,2),height:Math.max(l+2*C,2)}).call(dt.fill,r.bgcolor).call(dt.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),V.selectAll(".cboutline").attr({x:P,y:N+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(l-2*r.ypad-G,2)}).call(dt.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*o;V.attr("transform","translate("+(s.l-c)+","+s.t+")"),Zr.autoMargin(t,n,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:l*({bottom:1,middle:.5}[r.yanchor]||0),b:l*({top:1,middle:.5}[r.yanchor]||0)})}],t);if($&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition)Et.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),hr(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),J=Et.align(O+e/s.w,M,0,1,r.xanchor),Q=Et.align(D-t/s.h,T,0,1,r.yanchor);var n=Et.getCursor(J,Q,r.xanchor,r.yanchor);hr(V,n)},doneFn:function(){hr(V),void 0!==J&&void 0!==Q&&z.call("restyle",t,{"colorbar.x":J,"colorbar.y":Q},i().index)}});return $}function K(e,t){return nt.coerce(R,I,en,e,t)}function ee(e,n){var r,a=i();r=z.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:I,propName:r,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),la.draw(t,e,hl(l,n||{}))}o._infolayer.selectAll("g."+n).remove()}function i(){var e,r,a=n.substr(2);for(e=0;ei&&(t.z=l.slice(0,i)),a("locationmode"),a("text"),a("marker.line.color"),a("marker.line.width"),a("marker.opacity"),cn(e,t,r,a,{prefix:"",cLetter:"z"}),nt.coerceSelectionMarkerOpacity(t,a)):t.visible=!1}else t.visible=!1},yl.colorbar=function(e,n){var r=n[0].trace,a="cb"+r.uid,i=r.zmin,o=r.zmax;if(t(i)||(i=nt.aggNums(Math.min,null,r.z)),t(o)||(o=nt.aggNums(Math.max,null,r.z)),e._fullLayout._infolayer.selectAll("."+a).remove(),r.showscale){var l=n[0].t.cb=vl(e,a),s=dn.makeColorScaleFunc(dn.extractScale(r.colorscale,i,o),{noNumericCheck:!0});l.fillcolor(s).filllevels({start:i,end:o,size:(o-i)/254}).options(r.colorbar)()}else Zr.autoMargin(e,a)},yl.calc=function(e,n){for(var r=n.locations.length,a=new Array(r),i=0;i")}(e,s,r,c.mockAxis),[e]},yl.eventData=function(e,t){return e.location=t.location,e.z=t.z,e},yl.selectPoints=function(e,t){var n,r,a,i,o,l=e.cd,s=e.xaxis,c=e.yaxis,u=[];if(!1===t)for(n=0;n1)for(var n=1;n=0,p=n.indexOf("end")>=0,g=c.backoff*f+r.standoff,v=u.backoff*d+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void S();if(g){if(g*g>y*y+m*m)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}n._w=C,n._h=S;for(var E=!1,N=["x","y"],R=0;R1)&&(U===V?((K=G.r2fraction(n["a"+H]))<0||K>1)&&(E=!0):E=!0,E))continue;I=G._offset+G.r2p(n[H]),B=.5}else"x"===H?(j=n[H],I=u.l+u.w*j):(j=1-n[H],I=u.t+u.h*j),B=n.showarrow?.5:j;if(n.showarrow){$.head=I;var ee=n["a"+H];q=X*D(.5,n.xanchor)-Z*D(.5,n.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=q):($.tail=I+ee,F=q+ee),$.text=$.tail+q;var te=c["x"===H?"width":"height"];if("paper"===V&&($.head=nt.constrain($.head,1,te-1)),"pixel"===U){var ne=-Math.max($.tail-3,$.text),re=Math.min($.tail+3,$.text)-te;ne>0?($.tail+=ne,$.text+=ne):re>0&&($.tail-=re,$.text-=re)}$.tail+=Q,$.head+=Q}else F=q=W*D(B,J),$.text=I+q;$.text+=Q,q+=Q,F+=Q,n["_"+H+"padplus"]=W/2+F,n["_"+H+"padminus"]=W/2-F,n["_"+H+"size"]=W,n["_"+H+"shift"]=q}if(E)x.remove();else{var ae=0,ie=0;if("left"!==n.align&&(ae=(C-_)*("center"===n.align?.5:1)),"top"!==n.valign&&(ie=(S-T)*("middle"===n.valign?.5:1)),l)r.select("svg").attr({x:w+ae-1,y:w+ie}).call(Vn.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(yn.positionText,le,oe).call(Vn.setClipUrl,M?d:null)}A.select("rect").call(Vn.setRect,w,w,C,S),k.call(Vn.setRect,b/2,b/2,P-b,O-b),x.call(Vn.setTranslate,Math.round(h.x.text-P/2),Math.round(h.y.text-O/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,r){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+r,m=h.x.text+e,b=h.y.text+r,_=nt.rotationXYMatrix(p,m,b),w=nt.apply2DTransform(_),M=nt.apply2DTransform2(_),A=+k.attr("width"),T=+k.attr("height"),L=m-.5*A,C=L+A,S=b-.5*T,P=S+T,O=[[L,S,L,P],[L,P,C,P],[C,P,C,S],[C,S,L,S]].map(M);if(!O.reduce(function(e,t){return e^!!nt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){O.forEach(function(e){var t=nt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var D=n.arrowwidth,E=n.arrowcolor,N=n.arrowside,R=g.append("g").style({opacity:dt.opacity(E)}).classed("annotation-arrow-g",!0),I=R.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",D+"px").call(dt.stroke,dt.rgb(E));if(ql(I,N,n),f.annotationPosition&&I.node().parentNode&&!a){var F=l,j=c;if(n.standoff){var B=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=n.standoff*(d-l)/B,j+=n.standoff*(y-c)/B}var q,H,V,U=R.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-j),transform:"translate("+F+","+j+")"}).style("stroke-width",D+6+"px").call(dt.stroke,"rgba(0,0,0,0)").call(dt.fill,"rgba(0,0,0,0)");Et.init({element:U.node(),gd:t,prepFn:function(){var e=Vn.getTranslate(x);H=e.x,V=e.y,q={},i&&i.autorange&&(q[i._name+".autorange"]=!0),o&&o.autorange&&(q[o._name+".autorange"]=!0)},moveFn:function(e,t){var r=w(H,V),a=r[0]+e,l=r[1]+t;x.call(Vn.setTranslate,a,l),q[s+".x"]=i?i.p2r(i.r2p(n.x)+e):n.x+e/u.w,q[s+".y"]=o?o.p2r(o.r2p(n.y)+t):n.y-t/u.h,n.axref===n.xref&&(q[s+".ax"]=i.p2r(i.r2p(n.ax)+e)),n.ayref===n.yref&&(q[s+".ay"]=o.p2r(o.r2p(n.ay)+t)),R.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){z.call("relayout",t,q);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(n.showarrow&&ue(0,0),y)Et.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var r="pointer";if(n.showarrow)n.axref===n.xref?se[s+".ax"]=i.p2r(i.r2p(n.ax)+e):se[s+".ax"]=n.ax+e,n.ayref===n.yref?se[s+".ay"]=o.p2r(o.r2p(n.ay)+t):se[s+".ay"]=n.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(n.x)+e);else{var l=n._xsize/u.w,c=n.x+(n._xshift-n.xshift)/u.w-l/2;se[s+".x"]=Et.align(c+e/u.w,l,0,1,n.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(n.y)+t);else{var f=n._ysize/u.h,d=n.y-(n._yshift+n.yshift)/u.h-f/2;se[s+".y"]=Et.align(d-t/u.h,f,0,1,n.yanchor)}i&&o||(r=Et.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],n.xanchor,n.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),hr(x,r)},doneFn:function(){hr(x),z.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var Gl=Hl.draw;function Yl(e){var t=e._fullLayout;nt.filterVisible(t.annotations).forEach(function(t){var n,r,a,i,o=Sa.getFromId(e,t.xref),l=Sa.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(n=s+t.xshift,r=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(Sa.expand(o,[o.r2c(t.x)],{ppadplus:n,ppadminus:r}),Sa.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,Sa.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,n,a),ppadminus:Math.max(t._xpadminus,r,i)}))),l&&l.autorange&&(n=s-t.yshift,r=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(Sa.expand(l,[l.r2c(t.y)],{ppadplus:n,ppadminus:r}),Sa.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,Sa.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,n,a),ppadminus:Math.max(t._ypadminus,r,i)})))})}var Xl={hasClickToShow:function(e,t){var n=Zl(e,t);return n.on.length>0||n.explicitOff.length>0},onClick:function(e,t){var n,r=Zl(e,t),a=r.on,i=r.off.concat(r.explicitOff),o={};if(!a.length&&!i.length)return;for(n=0;n1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=is(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*n[0],t.yaxis.r2l(i.y)*n[1],t.zaxis.r2l(i.z)*n[2]]),os(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var cs={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},us=function(e){var t=e.type,n=e.symmetric;if("data"===t){var r=e.array||[];if(n)return function(e,t){var n=+r[t];return[n,n]};var a=e.arrayminus||[];return function(e,t){var n=+r[t],i=+a[t];return isNaN(n)&&isNaN(i)?[NaN,NaN]:[i||0,n||0]}}var i=fs(t,e.value),o=fs(t,e.valueminus);return n||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function fs(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var ds=function(e){for(var t=e.calcdata,n=0;n0;n.each(function(n){var s,c=n[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Hn.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(n=[]);var h=e.select(this).selectAll("g.errorbar").data(n,s);if(h.exit().remove(),n.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Vn.setClipUrl(h,r.layerClipId),h.each(function(n){var r=e.select(this),s=function(e,n,r){var a={x:n.c2p(e.x),y:r.c2p(e.y)};return void 0!==e.yh&&(a.yh=r.c2p(e.yh),a.ys=r.c2p(e.ys),t(a.ys)||(a.noYS=!0,a.ys=r.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=n.c2p(e.xh),a.xs=n.c2p(e.xs),t(a.xs)||(a.noXS=!0,a.xs=n.c2p(e.xs,!0))),a}(n,i,o);if(!d||n.vis){var c,h=r.select("path.yerror");if(f.visible&&t(s.x)&&t(s.yh)&&t(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=r.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=r.select("path.xerror");if(u.visible&&t(s.y)&&t(s.xh)&&t(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=r.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var n=t[0].trace,r=n.error_y||{},a=n.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(dt.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(dt.stroke,a.color)})},hoverInfo:function(e,t,n){(t.error_y||{}).visible&&(n.yerr=e.yh-e.y,t.error_y.symmetric||(n.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(n.xerr=e.xh-e.x,t.error_x.symmetric||(n.xerrneg=e.x-e.xs))}};var ms=ee.counter,xs=wo.attributes,bs=Dt.idRegex,_s={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:!0,dimensions:2,items:{valType:"enumerated",values:[ms("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[bs.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[bs.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:xs({name:"grid",editType:"plot",noGridCell:!0},{}),xside:{valType:"enumerated",values:["bottom","bottom plot","top plot","top"],dflt:"bottom plot",editType:"ticks"},yside:{valType:"enumerated",values:["left","left plot","right plot","right"],dflt:"left plot",editType:"ticks"},editType:"plot"};function ws(e,t,n,r,a){var i=t(e+"gap",n),o=t("domain."+e);t(e+"side");for(var l=new Array(r),s=o[0],c=(o[1]-s)/(r-i),u=c*(1-i),f=0;f1){i||o||l||"independent"===d("pattern")&&(i=!0),s._hasSubplotGrid=i;var f="top to bottom"===d("roworder");s._domains={x:ws("x",d,i?.2:.1,u),y:ws("y",d,i?.3:.1,c,f)}}}function d(e,t){return nt.coerce(n,s,_s,e,t)}},contentDefaults:function(e,t){var n=t.grid;if(n&&n._domains){var r,a,i,o,l,s,c,u=e.grid,f=t._subplots,d=n._hasSubplotGrid,h=n.rows,p=n.columns,g="independent"===n.pattern,v=n._axisMap={};if(d){var y=u.subplots||[];s=n.subplots=new Array(h);var m=1;for(r=0;r=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},Os={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},zs=!0,Ds=function(e,t,n){if(!t._dragged&&!t._editing){var r,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===n&&zs&&t.data&&t._context.showTips?(nt.notifier(nt._(t,"Double-click on legend to isolate one trace"),"long"),zs=!1):zs=!1,z.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===n?-1===m?s.push(y):s.splice(m,1):2===n&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),z.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(r=0;rn[1])return n[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",nt.mean,[.2,1]),d.ms=u("marker.size",nt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",nt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),r=[nt.minExtend(i,d)],a=nt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Vn.pointStyle,a,n),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Vn.textPointStyle,a,n)})},Fs=pn.LINE_SPACING,js=pn.FROM_TL,Bs=pn.FROM_BR,qs=d.DBLCLICKDELAY;function Hs(e,t){var n=e.data()[0][0],r=t._fullLayout,a=n.trace,i=z.traceIs(a,"pie"),o=a.index,l=i?n.label:a.name,s=e.selectAll("text.legendtext").data([0]);function c(n){yn.convertToTspans(n,t,function(){!function(e,t){var n=e.data()[0][0];if(!n.trace.showlegend)return void e.remove();var r,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*Fs;if(o){var s=Vn.bBox(o);r=s.height,a=s.width,Vn.setTranslate(i,0,r/4)}else{var c=e.select(".legendtext"),u=yn.lineCount(c),f=c.node();r=l*u,a=f?Vn.bBox(f).width:0;var d=l*(.3+(1-u)/2);yn.positionText(c,40,d)}r=Math.max(r,16)+3,n.height=r,n.width=a}(e,t)})}s.enter().append("text").classed("legendtext",!0),s.attr("text-anchor","start").classed("user-select-none",!0).call(Vn.font,r.legend.font).text(l),t._context.edits.legendText&&!i?s.call(yn.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var r,a=e;this.text()||(e=" ");var i=n.trace._fullInput||{},l={};if(-1!==["ohlc","candlestick"].indexOf(i.type))l[(r=n.trace.transforms)[r.length-1].direction+".name"]=e;else if(z.hasTransform(i,"groupby")){var s=z.getTransformIndices(i,"groupby"),u=s[s.length-1],f=nt.keyedContainer(i,"transforms["+u+"].styles","target","value.name");""===a?f.remove(n.trace._group):f.set(n.trace._group,e),l=f.constructUpdate()}else l.name=e;return z.call("restyle",t,l,o)}):c(s)}function Vs(e,t){var n,r=1,a=e.selectAll("rect").data([0]);a.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(dt.fill,"rgba(0,0,0,0)"),a.on("mousedown",function(){(n=(new Date).getTime())-t._legendMouseDownTimeqs&&(r=Math.max(r-1,1)),1===r?n._clickTimeout=setTimeout(function(){Ds(e,t,r)},qs):2===r&&(n._clickTimeout&&clearTimeout(n._clickTimeout),t._legendMouseDownTime=0,Ds(e,t,r))}})}function Us(t,n,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=Ss.isGrouped(i),s=0;if(i._width=0,i._height=0,Ss.isVertical(i))l&&n.each(function(e,t){Vn.setTranslate(this,0,t*i.tracegroupgap)}),r.each(function(e){var t=e[0],n=t.height,r=t.width;Vn.setTranslate(this,o,5+o+i._height+n/2),i._height+=n,i._width=Math.max(i._width,r)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=n.data(),f=0,d=u.length;fo+b-_,r.each(function(e){var t=e[0],n=g?40+e[0].width:m;o+x+_+n>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Vn.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+n,i._height=Math.max(i._height,t.height),x+=_+n,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(n){var r=n[0],a=e.select(this).select(".legendtoggle");Vn.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function Gs(e){var t=e._fullLayout.legend,n="left";Ps.isRightAnchor(t)?n="right":Ps.isCenterAnchor(t)&&(n="center");var r="top";Ps.isBottomAnchor(t)?r="bottom":Ps.isMiddleAnchor(t)&&(r="middle"),Zr.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*js[n],r:t._width*Bs[n],b:t._height*Bs[r],t:t._height*js[r]})}var Ys={moduleType:"component",name:"legend",layoutAttributes:Cs,supplyLayoutDefaults:function(e,t,n){for(var r,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),nt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(r=0,i="left",a=1.1,o="bottom"):(r=0,i="left",a=-.1,o="top")}h("traceorder",u),Ss.isGrouped(t.legend)&&h("tracegroupgap"),h("x",r),h("xanchor",i),h("y",a),h("yanchor",o),nt.noneOrAll(l,s,["x","y"])}},draw:function(t){var n=t._fullLayout,r="legend"+n._uid;if(n._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=n.legend,i=n.showlegend&&function(e,t){var n,r,a={},i=[],o=!1,l={},s=0;function c(e,n){if(""!==e&&Ss.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[n]]):a[e].push([n]);else{var r="~~i"+s;i.push(r),a[r]=[[n]],s++}}for(n=0;ng?function(e){var t=e._fullLayout.legend,n="left";Ps.isRightAnchor(t)?n="right":Ps.isCenterAnchor(t)&&(n="center"),Zr.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*js[n],r:t._width*Bs[n],b:0,t:0})}(t):Gs(t);var v=n._size,y=v.l+v.w*a.x,m=v.t+v.h*(1-a.y);Ps.isRightAnchor(a)?y-=a._width:Ps.isCenterAnchor(a)&&(y-=a._width/2),Ps.isBottomAnchor(a)?m-=a._height:Ps.isMiddleAnchor(a)&&(m-=a._height/2);var x=a._width,b=v.w;x>b?(y=v.l,x=b):(y+x>p&&(y=p-x),y<0&&(y=0),x=Math.min(p-y,a._width));var _,w,k,M,A=a._height,T=v.h;if(A>T?(m=v.t,A=T):(m+A>g&&(m=g-A),m<0&&(m=0),A=Math.min(g-m,a._height)),Vn.setTranslate(l,y,m),f.on(".drag",null),l.on("wheel",null),a._height<=A||t._context.staticPlot)c.attr({width:x-a.borderwidth,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Vn.setTranslate(u,0,0),s.select("rect").attr({width:x-2*a.borderwidth,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Vn.setClipUrl(u,r),Vn.setRect(f,0,0,0,0),delete a._scrollY;else{var L,C,S=Math.max(Os.scrollBarMinHeight,A*A/a._height),P=A-S-2*Os.scrollBarMargin,O=a._height-A,D=P/O,E=Math.min(a._scrollY||0,O);c.attr({width:x-2*a.borderwidth+Os.scrollBarWidth+Os.scrollBarMargin,height:A-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),s.select("rect").attr({width:x-2*a.borderwidth+Os.scrollBarWidth+Os.scrollBarMargin,height:A-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+E}),Vn.setClipUrl(u,r),R(E,S,D),l.on("wheel",function(){R(E=nt.constrain(a._scrollY+e.event.deltaY/P*O,0,O),S,D),0!==E&&E!==O&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){L=e.event.sourceEvent.clientY,C=E}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||R(E=nt.constrain((t.clientY-L)/D+C,0,O),S,D)});f.call(N)}t._context.edits.legendPosition&&(l.classed("cursor-move",!0),Et.init({element:l.node(),gd:t,prepFn:function(){var e=Vn.getTranslate(l);k=e.x,M=e.y},moveFn:function(e,t){var n=k+e,r=M+t;Vn.setTranslate(l,n,r),_=Et.align(n,0,v.l,v.l+v.w,a.xanchor),w=Et.align(r,0,v.t+v.h,v.t,a.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&z.call("relayout",t,{"legend.x":_,"legend.y":w})},clickFn:function(e,r){var a=n._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return r.clientX>=e.left&&r.clientX<=e.right&&r.clientY>=e.top&&r.clientY<=e.bottom});a.size()>0&&(1===e?l._clickTimeout=setTimeout(function(){Ds(a,t,e)},qs):2===e&&(l._clickTimeout&&clearTimeout(l._clickTimeout),Ds(a,t,e)))}}))}function R(e,n,r){a._scrollY=t._fullLayout.legend._scrollY=e,Vn.setTranslate(u,0,-e),Vn.setRect(f,x,Os.scrollBarMargin+e*r,Os.scrollBarWidth,n),s.select("rect").attr({y:a.borderwidth+e})}},style:Is},Xs={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},Zs=y.extendFlat,Ws={visible:{valType:"boolean",editType:"plot"},buttons:Xs=Zs(Xs,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:T({editType:"plot"}),bgcolor:{valType:"color",dflt:S.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:S.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},Js={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var Qs=function(t,n){var r=t._name,a={};if("all"===n.step)a[r+".autorange"]=!0;else{var i=function(t,n){var r,a=t.range,i=new Date(t.r2l(a[1])),o=n.step,l=n.count;switch(n.stepmode){case"backward":r=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);r=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,n);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var $s=pn.LINE_SPACING,Ks=pn.FROM_TL,ec=pn.FROM_BR;function tc(e){return e._id}function nc(e,t,n){var r=e.selectAll("rect").data([0]);r.enter().append("rect").classed("selector-rect",!0),r.attr("shape-rendering","crispEdges"),r.attr({rx:Js.rx,ry:Js.ry}),r.call(dt.stroke,t.bordercolor).call(dt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,n)).style("stroke-width",t.borderwidth+"px")}function rc(e,t,n,r){var a,i=e.selectAll("text").data([0]);i.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),i.attr("text-anchor","middle"),i.call(Vn.font,t.font).text((a=n,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){yn.convertToTspans(e,r)})}var ac={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:Ws}}},layoutAttributes:Ws,handleDefaults:function(e,t,n,r,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return nt.coerce(i,o,Ws,e,t)}if(l("visible",function(e,t,n){var r,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return nt.coerce(r,a,Xs,e,t)}for(var s=0;s0)){var s=function(e,t,n){for(var r=n.filter(function(n){return t[n].anchor===e._id}),a=0,i=0;i rect").call(Vn.setTranslate,0,0).call(Vn.setScale,1,1),e.plot.call(Vn.setTranslate,t._offset,n._offset).call(Vn.setScale,1,1);var r=e.plot.selectAll(".scatterlayer .trace");r.selectAll(".point").call(Vn.setPointGroupScale,1,1),r.selectAll(".textpoint").call(Vn.setTextPointsScale,1,1),r.call(Vn.hideOutsideRangePoints,e)}function g(e,n){var r,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(r=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-n)+n*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[2]=e.xaxis._length*(1-n+n*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(r=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-n)+n*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[3]=e.yaxis._length*(1-n+n*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,n){var r,a=[];for(a=[e._id,n._id],r=0;r rect").call(Vn.setTranslate,_,w).call(Vn.setScale,1/x,1/b),e.plot.call(Vn.setTranslate,A,T).call(Vn.setScale,x,b).selectAll(".points").selectAll(".point").call(Vn.setPointGroupScale,1/x,1/b),e.plot.selectAll(".points").selectAll(".textpoint").call(Vn.setTextPointsScale,1/x,1/b)}a&&(l=a());var v=e.ease(r.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(u),u=null,function(){for(var e={},n=0;nr.duration?(function(){for(var e={},n=0;nf&&(f=c)));return f>=u?[u,f]:void 0}}var Fc=function(e,t,n,r,a){function i(n,r){return nt.coerce(e,t,Ec,n,r)}if(r=r||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=["x","y"],s=0;s<2;s++){var c=l[s],u={_fullLayout:n},f=Sa.coerceRef(e,t,u,c,"","paper");if("path"!==o){var d,h,p;"paper"!==f?(d=Sa.getFromId(u,f),p=Rc.rangeToShapePosition(d),h=Rc.shapePositionToRange(d)):h=p=nt.identity;var g=c+"0",v=c+"1",y=e[g],m=e[v];e[g]=h(e[g],!0),e[v]=h(e[v],!0),Sa.coercePosition(t,u,i,f,g,.25),Sa.coercePosition(t,u,i,f,v,.75),t[g]=p(t[g]),t[v]=p(t[v]),e[g]=y,e[v]=m}}return"path"===o?i("path"):nt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},jc={draw:function(e){var t=e._fullLayout;t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._shapeSubplotLayers.selectAll("path").remove();for(var n=0;nN&&r>R&&!e.shiftKey?Et.getCursor(a/n,1-i/r):"move";hr(t,o),E=o.split("-")[0]}function B(r,h){if("path"===n.type){var p=function(e){return O(S(e)+r)};L&&"date"===L.type&&(p=Rc.encodeDate(p));var g=function(e){return D(P(e)+h)};C&&"date"===C.type&&(g=Rc.encodeDate(g)),n.path=Hc(A,p,g),a[T]=n.path}else a[c]=n.x0=O(i+r),a[u]=n.y0=D(o+h),a[f]=n.x1=O(l+r),a[d]=n.y1=D(s+h);t.attr("d",qc(e,n))}function q(r,i){if("path"===n.type){var o=function(e){return O(S(e)+r)};L&&"date"===L.type&&(o=Rc.encodeDate(o));var l=function(e){return D(P(e)+i)};C&&"date"===C.type&&(l=Rc.encodeDate(l)),n.path=Hc(A,o,l),a[T]=n.path}else{var s=~E.indexOf("n")?h+i:h,c=~E.indexOf("s")?p+i:p,u=~E.indexOf("w")?g+r:g,f=~E.indexOf("e")?v+r:v;c-s>R&&(a[y]=n[_]=D(s),a[m]=n[w]=D(c)),f-u>N&&(a[x]=n[k]=O(u),a[b]=n[M]=O(f))}t.attr("d",qc(e,n))}Et.init(I),t.node().onmousemove=j}(e,o,r,t)}}function qc(e,t){var n,r,a,i,o=t.type,l=Sa.getFromId(e,t.xref),s=Sa.getFromId(e,t.yref),c=e._fullLayout._size;if(l?(n=Rc.shapePositionToRange(l),r=function(e){return l._offset+l.r2p(n(e,!0))}):r=function(e){return c.l+c.w*e},s?(a=Rc.shapePositionToRange(s),i=function(e){return s._offset+s.r2p(a(e,!0))}):i=function(e){return c.t+c.h*(1-e)},"path"===o)return l&&"date"===l.type&&(r=Rc.decodeDate(r)),s&&"date"===s.type&&(i=Rc.decodeDate(i)),function(e,t,n){return e.replace(Nc.segmentRE,function(e){var r=0,a=e.charAt(0),i=Nc.paramIsX[a],o=Nc.paramIsY[a],l=Nc.numParams[a],s=e.substr(1).replace(Nc.paramRE,function(e){return i[r]?e=t(e):o[r]&&(e=n(e)),++r>l&&(e="X"),e});return r>l&&(s=s.replace(/[\s,]*X.*/,""),nt.log("Ignoring extra params in segment "+e)),a+s})}(t.path,r,i);var u=r(t.x0),f=r(t.x1),d=i(t.y0),h=i(t.y1);if("line"===o)return"M"+u+","+d+"L"+f+","+h;if("rect"===o)return"M"+u+","+d+"H"+f+"V"+h+"H"+u+"Z";var p=(u+f)/2,g=(d+h)/2,v=Math.abs(p-u),y=Math.abs(g-d),m="A"+v+","+y,x=p+v+","+g;return"M"+x+m+" 0 1,1 "+(p+","+(g-y))+m+" 0 0,1 "+x+"Z"}function Hc(e,t,n){return e.replace(Nc.segmentRE,function(e){var r=0,a=e.charAt(0),i=Nc.paramIsX[a],o=Nc.paramIsY[a],l=Nc.numParams[a];return a+e.substr(1).replace(Nc.paramRE,function(e){return r>=l?e:(i[r]?e=t(e):o[r]&&(e=n(e)),r++,e)})})}var Vc={moduleType:"component",name:"shapes",layoutAttributes:Ec,supplyLayoutDefaults:function(e,t){$l(e,t,{name:"shapes",handleItemDefaults:Fc})},includeBasePlot:Kl("shapes"),calcAutorange:function(e){var t=e._fullLayout,n=nt.filterVisible(t.shapes);if(n.length&&e._fullData.length)for(var r=0;r0)&&(r("active"),r("x"),r("y"),nt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("len"),r("lenmode"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),nt.coerceFont(r,"font",n.font),r("currentvalue.visible")&&(r("currentvalue.xanchor"),r("currentvalue.prefix"),r("currentvalue.suffix"),r("currentvalue.offset"),nt.coerceFont(r,"currentvalue.font",t.font)),r("transition.duration"),r("transition.easing"),r("bgcolor"),r("activebgcolor"),r("bordercolor"),r("borderwidth"),r("ticklen"),r("tickwidth"),r("tickcolor"),r("minorticklen"))}var Qc=pn.LINE_SPACING,$c=pn.FROM_TL,Kc=pn.FROM_BR;function eu(e){return e._index}function tu(t,n){var r=Vn.tester.selectAll("g."+Uc.labelGroupClass).data(n.steps);r.enter().append("g").classed(Uc.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=au(e.select(this),{step:t},n).node();if(r){var o=Vn.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=n._dims={};o.inputAreaWidth=Math.max(Uc.railWidth,Uc.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*n.x,o.ly=l.t+l.h*(1-n.y),"fraction"===n.lenmode?o.outerLength=Math.round(l.w*n.len):o.outerLength=n.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-n.pad.l-n.pad.r);var s=(o.inputAreaLength-2*Uc.stepInset)/(n.steps.length-1),c=a+Uc.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,n.currentvalue.visible){var u=Vn.tester.append("g");r.each(function(e){var t=nu(u,n,e.label),r=t.node()&&Vn.bBox(t.node())||{width:0,height:0},a=yn.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(r.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(r.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+n.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+Uc.tickOffset+n.ticklen+Uc.labelOffset+o.labelHeight+n.pad.t+n.pad.b;var f="left";Ps.isRightAnchor(n)&&(o.lx-=o.outerLength,f="right"),Ps.isCenterAnchor(n)&&(o.lx-=o.outerLength/2,f="center");var d="top";Ps.isBottomAnchor(n)&&(o.ly-=o.height,d="bottom"),Ps.isMiddleAnchor(n)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Zr.autoMargin(t,Uc.autoMarginIdRoot+n._index,{x:n.x,y:n.y,l:o.outerLength*$c[f],r:o.outerLength*Kc[f],b:o.height*Kc[d],t:o.height*$c[d]})}function nu(e,t,n){if(t.currentvalue.visible){var r,a,i=e.selectAll("text").data([0]),o=t._dims;switch(t.currentvalue.xanchor){case"right":r=o.inputAreaLength-Uc.currentValueInset-o.currentValueMaxWidth,a="left";break;case"center":r=.5*o.inputAreaLength,a="middle";break;default:r=Uc.currentValueInset,a="left"}i.enter().append("text").classed(Uc.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1});var l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof n)l+=n;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),i.call(Vn.font,t.currentvalue.font).text(l).call(yn.convertToTspans,t._gd);var s=yn.lineCount(i),c=(o.currentValueMaxLines+1-s)*t.currentvalue.font.size*Qc;return yn.positionText(i,r,c),i}}function ru(e,t,n){var r=e.selectAll("rect."+Uc.gripRectClass).data([0]);r.enter().append("rect").classed(Uc.gripRectClass,!0).call(su,t,e,n).style("pointer-events","all"),r.attr({width:Uc.gripWidth,height:Uc.gripHeight,rx:Uc.gripRadius,ry:Uc.gripRadius}).call(dt.stroke,n.bordercolor).call(dt.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px")}function au(e,t,n){var r=e.selectAll("text").data([0]);return r.enter().append("text").classed(Uc.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),r.call(Vn.font,n.font).text(t.step.label).call(yn.convertToTspans,n._gd),r}function iu(t,n){var r=t.selectAll("g."+Uc.labelsClass).data([0]),a=n._dims;r.enter().append("g").classed(Uc.labelsClass,!0);var i=r.selectAll("g."+Uc.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(Uc.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=e.select(this);r.call(au,t,n),Vn.setTranslate(r,fu(n,t.fraction),Uc.tickOffset+n.ticklen+n.font.size*Qc+Uc.labelOffset+a.currentValueTotalHeight)})}function ou(e,t,n,r,a){var i=Math.round(r*(n.steps.length-1));i!==n.active&&lu(e,t,n,i,!0,a)}function lu(e,t,n,r,a,i){var o=n.active;n._input.active=n.active=r;var l=n.steps[n.active];t.call(uu,n,n.active/(n.steps.length-1),i),t.call(nu,n),e.emit("plotly_sliderchange",{slider:n,step:n.steps[n.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var n=t._nextMethod.step;n.method&&(n.execute&&Zr.executeAPICommand(e,n.method,n.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function su(t,n,r){var a=r.node(),i=e.select(n);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();n.emit("plotly_sliderstart",{slider:t});var l=r.select("."+Uc.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(dt.fill,t.activebgcolor);var s=du(t,e.mouse(a)[0]);ou(n,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=du(t,e.mouse(a)[0]);ou(n,r,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(dt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),n.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function cu(t,n){var r=t.selectAll("rect."+Uc.tickRectClass).data(n.steps),a=n._dims;r.enter().append("rect").classed(Uc.tickRectClass,!0),r.exit().remove(),r.attr({width:n.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=e.select(this);o.attr({height:i?n.ticklen:n.minorticklen}).call(dt.fill,n.tickcolor),Vn.setTranslate(o,fu(n,r/(n.steps.length-1))-.5*n.tickwidth,(i?Uc.tickOffset:Uc.minorTickOffset)+a.currentValueTotalHeight)})}function uu(e,t,n,r){var a=e.select("rect."+Uc.gripRectClass),i=fu(t,n);if(!t._invokingCommand){var o=a;r&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*Uc.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function fu(e,t){var n=e._dims;return n.inputAreaStart+Uc.stepInset+(n.inputAreaLength-2*Uc.stepInset)*Math.min(1,Math.max(0,t))}function du(e,t){var n=e._dims;return Math.min(1,Math.max(0,(t-Uc.stepInset-n.inputAreaStart)/(n.inputAreaLength-2*Uc.stepInset-2*n.inputAreaStart)))}function hu(e,t,n){var r=e.selectAll("rect."+Uc.railTouchRectClass).data([0]),a=n._dims;r.enter().append("rect").classed(Uc.railTouchRectClass,!0).call(su,t,e,n).style("pointer-events","all"),r.attr({width:a.inputAreaLength,height:Math.max(a.inputAreaWidth,Uc.tickOffset+n.ticklen+a.labelHeight)}).call(dt.fill,n.bgcolor).attr("opacity",0),Vn.setTranslate(r,0,a.currentValueTotalHeight)}function pu(e,t){var n=e.selectAll("rect."+Uc.railRectClass).data([0]),r=t._dims;n.enter().append("rect").classed(Uc.railRectClass,!0);var a=r.inputAreaLength-2*Uc.railInset;n.attr({width:a,height:Uc.railWidth,rx:Uc.railRadius,ry:Uc.railRadius,"shape-rendering":"crispEdges"}).call(dt.stroke,t.bordercolor).call(dt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Vn.setTranslate(n,Uc.railInset,.5*(r.inputAreaWidth-Uc.railWidth)+r.currentValueTotalHeight)}var gu={moduleType:"component",name:Uc.name,layoutAttributes:Xc,supplyLayoutDefaults:function(e,t){$l(e,t,{name:Zc,handleItemDefaults:Jc})},draw:function(t){var n=t._fullLayout,r=function(e,t){for(var n=e[Uc.name],r=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(Uc.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r=n.steps.length&&(n.active=0),t.call(nu,n).call(pu,n).call(iu,n).call(cu,n).call(hu,e,n).call(ru,e,n);var r=n._dims;Vn.setTranslate(t,r.lx+n.pad.l,r.ly+n.pad.t),t.call(uu,n,n.active/(n.steps.length-1),!1),t.call(nu,n)}(t,e.select(this),n)}})}}},vu=y.extendFlat,yu=(0,Xt.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:vu({},Gc,{}),font:T({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:S.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),mu={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},xu=mu.name,bu=yu.buttons;function _u(e,t,n){function r(n,r){return nt.coerce(e,t,yu,n,r)}r("visible",function(e,t){var n,r,a=e.buttons||[],i=t.buttons=[];function o(e,t){return nt.coerce(n,r,bu,e,t)}for(var l=0;l0)&&(r("active"),r("direction"),r("type"),r("showactive"),r("x"),r("y"),nt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),nt.coerceFont(r,"font",n.font),r("bgcolor",n.paper_bgcolor),r("bordercolor"),r("borderwidth"))}var wu=ku;function ku(e,t,n){this.gd=e,this.container=t,this.id=n,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}ku.barWidth=2,ku.barLength=20,ku.barRadius=2,ku.barPad=1,ku.barColor="#808BA4",ku.prototype.enable=function(t,n,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=ku.barLength+2*ku.barPad,k=ku.barWidth+2*ku.barPad,M=f,A=h+p;A+k>o&&(A=o-k);var T=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);T.exit().on(".drag",null).remove(),T.enter().append("rect").classed("scrollbar-horizontal",!0).call(dt.fill,ku.barColor),_?(this.hbar=T.attr({rx:ku.barRadius,ry:ku.barRadius,x:M,y:A,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,C=ku.barWidth+2*ku.barPad,S=ku.barLength+2*ku.barPad,P=f+d,O=h;P+C>i&&(P=i-C);var z=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);z.exit().on(".drag",null).remove(),z.enter().append("rect").classed("scrollbar-vertical",!0).call(dt.fill,ku.barColor),L?(this.vbar=z.attr({rx:ku.barRadius,ry:ku.barRadius,x:P,y:O,width:C,height:S}),this._vbarYMin=O+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,N=L?s+C+.5:s+.5,R=c-.5,I=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(R),width:Math.ceil(N)-Math.floor(E),height:Math.ceil(I)-Math.floor(R)}),this.container.call(Vn.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Vn.setClipUrl,null),delete this._clipRect),_||L){var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),L&&this.vbar.on(".drag",null).call(B)}this.setTranslate(n,r)},ku.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Vn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},ku.prototype._onBoxDrag=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(n-=e.event.dy),this.setTranslate(t,n)},ku.prototype._onBoxWheel=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(n+=e.event.deltaY),this.setTranslate(t,n)},ku.prototype._onBarDrag=function(){var t=this.translateX,n=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(nt.constrain(e.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=n+this._vbarYMin,o=i+this._vbarTranslateMax;n=(nt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,n)},ku.prototype.setTranslate=function(e,t){var n=this.position.w-this._box.w,r=this.position.h-this._box.h;if(e=nt.constrain(e||0,0,n),t=nt.constrain(t||0,0,r),this.translateX=e,this.translateY=t,this.container.call(Vn.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/n;this.hbar.call(Vn.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/r;this.vbar.call(Vn.setTranslate,e,t+i*this._vbarTranslateMax)}};var Mu=pn.LINE_SPACING;function Au(e){return e._index}function Tu(e,t){return+e.attr(mu.menuIndexAttrName)===t._index}function Lu(e,t,n,r,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?Su(e,r,null,null,t):"dropdown"===t.type&&(a.attr(mu.menuIndexAttrName,"-1"),Cu(e,r,a,i,t),l||Su(e,r,a,i,t))}function Cu(e,t,n,r,a){var i=t.selectAll("g."+mu.headerClassName).data([0]),o=a._dims;i.enter().append("g").classed(mu.headerClassName,!0).style("pointer-events","all");var l=a.active,s=a.buttons[l]||mu.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(Pu,a,s,e).call(Iu,a,c,u);var f=t.selectAll("text."+mu.headerArrowClassName).data([0]);f.enter().append("text").classed(mu.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(Vn.font,a.font).text(mu.arrowSymbol[a.direction]),f.attr({x:o.headerWidth-mu.arrowOffsetX+a.pad.l,y:o.headerHeight/2+mu.textOffsetY+a.pad.t}),i.on("click",function(){n.call(Fu),n.attr(mu.menuIndexAttrName,Tu(n,a)?-1:String(a._index)),Su(e,t,n,r,a)}),i.on("mouseover",function(){i.call(Eu)}),i.on("mouseout",function(){i.call(Nu,a)}),Vn.setTranslate(t,o.lx,o.ly)}function Su(t,n,r,a,i){r||(r=n).attr("pointer-events","all");var o=function(e){return-1==+e.attr(mu.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?mu.dropdownButtonClassName:mu.buttonClassName,s=r.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+mu.gapButtonHeader:f=h.headerWidth+mu.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-mu.gapButtonHeader+mu.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-mu.gapButtonHeader+mu.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:mu.gapButton,xPad:mu.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(Pu,i,o,t).call(Iu,i,g),c.on("click",function(){e.event.defaultPrevented||(Lu(t,i,0,n,r,a,l),o.execute&&Zr.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(Eu)}),c.on("mouseout",function(){c.call(Nu,i),s.call(Du,i)})}),s.call(Du,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,n,r,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(mu.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;rb.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,n;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n0&&nt.log("Clearing previous rejected promises from queue."),e._promises=[]},Uu.cleanLayout=function(e){var t,n;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var r=(Zr.subplotsRegistry.cartesian||{}).attrRegex,a=(Zr.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),dt.clean(e),e},Uu.cleanData=function(e,t){for(var n=[],r=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}Uu.hasParent=function(e,t){for(var n=Qu(t);n;){if(n in e)return!0;n=Qu(n)}return!1};var $u=["x","y","z"];Uu.clearAxisTypes=function(e,t,n){for(var r=0;r1&&_.warn("Full array edits are incompatible with other edits",a);var f=n[""][""];if(nf(f))t.set(null);else{if(!Array.isArray(f))return _.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(n).map(Number).sort(ef),b=t.get(),w=b||[],k=Y(u,a).get(),A=[],T=-1,L=w.length;for(d=0;dw.length-(m?0:1))_.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&_.warn("Insertion & removal are incompatible with edits to the same index.",a,p),nf(y)?A.push(p):m?("add"===y&&(y={}),w.splice(p,0,y),k&&k.splice(p,0,{})):_.warn("Unrecognized full object edit value",a,p,y),-1===T&&(T=p);else for(h=0;h=0;d--)w.splice(A[d],1),k&&k.splice(A[d],1);if(w.length?b||t.set(w):t.set(null),s)return!1;if(i(c,u),l!==M){var C;if(-1===T)C=x;else{for(L=Math.max(w.length,L),C=[],d=0;d=T);d++)C.push(p);for(d=T;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,n=0;n=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function zf(e,t,n,r,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+n+", "+r+")").attr("d",a+"Z")}function Df(e,t,n){return e.append("path").attr("class","zoombox-corners").style({fill:dt.background,stroke:dt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+n+")").attr("d","M0,0Z")}function Ef(e){e.selectAll(".select-outline").remove()}function Nf(e,t,n,r,a,i){e.attr("d",r+"M"+n.l+","+n.t+"v"+n.h+"h"+n.w+"v-"+n.h+"h-"+n.w+"Z"),Rf(e,t,a,i)}function Rf(e,t,n,r){n||(e.transition().style("fill",r>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function If(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Ff(e){Af&&e.data&&e._context.showTips&&(nt.notifier(nt._(e,"Double-click to zoom back out"),"long"),Af=!1)}function jf(e){return"lasso"===e||"select"===e}function Bf(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,Mf)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function qf(e,t){if(mt){var n=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(n,e._onwheel),e._onwheel=t,e.addEventListener(n,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}var Hf=function(t,n,r,a,i,o,s,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k=t._fullLayout,M=t._fullLayout._zoomlayer,A=s+c==="nsew",T=1===(s+c).length;function L(){f=[n.xaxis],d=[n.yaxis];var e=f[0],r=d[0];g=e._length,v=r._length;var a,i,o=k._axisConstraintGroups,l=[e._id],M=[r._id];u=[n].concat(s&&c?n.overlays:[]);for(var A=1;AMf||o>Mf?(I="xy",i/g>o/v?(o=i*v/g,O>a?D.t=O-o:D.b=O+o):(i=o*g/v,P>r?D.l=P-i:D.r=P+i),j.attr("d",Bf(D))):l():!m||o rect").call(Vn.setTranslate,a,i).call(Vn.setScale,n,r);var z=x.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");x.plot.call(Vn.setTranslate,P,O).call(Vn.setScale,1/n,1/r),z.selectAll(".point").call(Vn.setPointGroupScale,n,r),z.selectAll(".textpoint").call(Vn.setTextPointsScale,n,r),z.call(Vn.hideOutsideRangePoints,x),x.plot.selectAll(".barlayer .trace").call(Vn.hideOutsideRangePoints,x,".bartext")}}}return s.length*c.length!=1&&qf(C,function(e){if(t._context.scrollZoom||k._enablescrollzoom){if(null===G&&Ef(M),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var n=t.querySelector(".plotly");if(L(),!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(G);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var a,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),o=X.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(c||b){for(c||(l=.5),a=0;a=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(n,a,h)?(d.push(e),h.push([n,a])):i=[0];var o=t.plotgroup.selectAll(".bg").data(i);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){t.bg=o;var e=t.plotgroup.node();e.insertBefore(this,e.childNodes[0])})});var p=r._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=e.select(this)}),f.each(function(e){var t=r._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Vn.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(dt.fill,r.plot_bgcolor).style("stroke-width",0),t.clipId="clip"+r._uid+e+"plot";var u,f,d=r._clips.selectAll("#"+t.clipId).data([0]);for(d.enter().append("clipPath").attr({class:"plotclip",id:t.clipId}).append("rect"),d.selectAll("rect").attr({width:a._length,height:c._length}),Vn.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=t.clipId):(u=t.clipId,f=null),Vn.setClipUrl(t.plot,u),n=0;nQf*h)||y)for(n=0;nL&&PA&&(A=P);l/=(A-M)/(2*T),M=a.l2r(M),A=a.l2r(A),a.range=a._input.range=_=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var A=k.slice();w&&b&&(A[1]+=M);var T=c.angularAxis.ticksCount||4;T>8&&(T=T/(T/8)+T%8),c.angularAxis.ticksStep&&(T=(A[1]-A[0])/T);var L=c.angularAxis.ticksStep||(A[1]-A[0])/(T*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),A[2]||(A[2]=L);var C=e.range.apply(this,A);if(C=C.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(A.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),P=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=e.select(P)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var O,z=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){O=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var N=u.map(function(e,t){var n=rd.util.cloneJson(e);return n.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",n.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,n.color="LinePlot"===e.geometry?e.strokeColor:e.color,n});rd.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:td({},rd.Legend.defaultConfig().legendConfig,{container:O,elements:N,reverseOrder:c.legend.reverseOrder})})();var R=O.node().getBBox();g=Math.min(c.width-R.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),O.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else O=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),z.attr("transform","translate("+y+")").style({cursor:"crosshair"});var I=[(c.width-(c.margin.left+c.margin.right+2*g+(R?R.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(I[0]=Math.max(0,I[0]),I[1]=Math.max(0,I[1]),t.select(".outer-group").attr("transform","translate("+I+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),j=F.node().getBBox();F.attr({x:y[0]-j.width/2,y:y[1]-g-20})}var B=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var q=B.selectAll("circle.grid-circle").data(r.ticks(5));q.enter().append("circle").attr({class:"grid-circle"}).style(D),q.attr("r",r),q.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(D);var H=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(r).ticks(5).tickSize(5);B.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),B.selectAll(".domain").style(D),B.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var X=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:nd+"em",transform:function(e,t){var n=V(e),r=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-n+" "+r+" 0)":"radial"==a?n<270&&n>90?"rotate(180 "+r+" 0)":null:"rotate("+(n<=180&&n>0?-90:90)+" "+r+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&X.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var Z=e.max(z.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));O.attr({transform:"translate("+[g+Z,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,J=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(J.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),J.exit().remove(),u[0]||W){var Q=[];u.forEach(function(e,t){var n={};n.radialScale=r,n.angularScale=a,n.container=J.filter(function(e,n){return n==t}),n.geometry=e.geometry,n.orientation=c.orientation,n.direction=c.direction,n.index=t,Q.push({data:e,geometryConfig:n})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(Q).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var n;n=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var r=e.map(function(e,t){return td(rd[n].defaultConfig(),e)});rd[n]().config(r)()})}var K,ee,te=t.select(".guides-group"),ne=t.select(".tooltips-group"),re=rd.tooltipPanel().config({container:ne,fontSize:8})(),ae=rd.tooltipPanel().config({container:ne,fontSize:8})(),ie=rd.tooltipPanel().config({container:ne,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});z.on("mousemove.angular-guide",function(e,t){var n=rd.util.getMousePos(H).angle;oe.attr({x2:-g,transform:"rotate("+n+")"}).style({opacity:.5});var r=(n+180+360-c.orientation)%360;K=a.invert(r);var i=rd.util.convertToCartesian(g+12,n+180);re.text(rd.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});z.on("mousemove.radial-guide",function(e,t){var n=rd.util.getMousePos(H).radius;le.attr({r:n}).style({opacity:.5}),ee=r.invert(rd.util.getMousePos(H).radius);var a=rd.util.convertToCartesian(n,c.radialAxis.orientation);ae.text(rd.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),re.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(n,r){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:rd.util.round(n[0]),r:rd.util.round(n[1])};b&&(s.t=m[n[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-I[0]-f.left,u.top+u.height/2-I[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,n){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,n){ie.hide();var r=e.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=rd.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),td(i.data[t],rd.Axis.defaultConfig().data[0]),td(i.data[t],e)}),td(i.layout,rd.Axis.defaultConfig().layout),td(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return r},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},rd.Axis.defaultConfig=function(t,n){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},rd.util={},rd.DATAEXTENT="dataExtent",rd.AREA="AreaChart",rd.LINE="LinePlot",rd.DOT="DotPlot",rd.BAR="BarChart",rd.util._override=function(e,t){for(var n in e)n in t&&(t[n]=e[n])},rd.util._extend=function(e,t){for(var n in e)t[n]=e[n]},rd.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},rd.util.dataFromEquation2=function(t,n){var r=n||6;return e.range(0,360+r,r).map(function(e,n){var r=e*Math.PI/180;return[e,t(r)]})},rd.util.dataFromEquation=function(t,n,r){var a=n||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,n){var r=e*Math.PI/180,a=t(r);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},rd.util.ensureArray=function(t,n){if(void 0===t)return null;var r=[].concat(t);return e.range(n).map(function(e,t){return r[t]||r[0]})},rd.util.fillArrays=function(e,t,n){return t.forEach(function(t,r){e[t]=rd.util.ensureArray(e[t],n)}),e},rd.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},rd.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var n=t.shift();return e[n]&&(!t.length||objHasKeys(e[n],t))},rd.util.sumArrays=function(t,n){return e.zip(t,n).map(function(t,n){return e.sum(t)})},rd.util.arrayLast=function(e){return e[e.length-1]},rd.util.arrayEqual=function(e,t){for(var n=Math.max(e.length,t.length,1);n-- >=0&&e[n]===t[n];);return-2===n},rd.util.flattenArray=function(e){for(var t=[];!rd.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},rd.util.deduplicate=function(e){return e.filter(function(e,t,n){return n.indexOf(e)==t})},rd.util.convertToCartesian=function(e,t){var n=t*Math.PI/180;return[e*Math.cos(n),e*Math.sin(n)]},rd.util.round=function(e,t){var n=t||2,r=Math.pow(10,n);return Math.round(e*r)/r},rd.util.getMousePos=function(t){var n=e.mouse(t.node()),r=n[0],a=n[1],i={};return i.x=r,i.y=a,i.pos=n,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},rd.util.duplicatesCount=function(e){for(var t,n={},r={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(n.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(r,a,i)},"stroke-width":function(e,t){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](r,a,i)},opacity:function(e,t){return p.opacity(r,a,i)},display:function(e,t){return p.display(r,a,i)}})}};var f=n.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return n.radialScale(s+(e[2]||0))}).outerRadius(function(e){return n.radialScale(s+(e[2]||0))+n.radialScale(e[1])});c.arc=function(t,r,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(n.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,n,r){return t[r].data.color},stroke:function(e,n,r){return t[r].data.strokeColor},"stroke-width":function(e,n,r){return t[r].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,n,r){return t[r].data.opacity},display:function(e,n,r){return void 0===t[r].data.visible||t[r].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[n.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,n){t[n]||(t[n]={}),td(t[n],rd.PolyChart.defaultConfig()),td(t[n],e)}),this):t},a.getColorScale=function(){},e.rebind(a,n,"on"),a},rd.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},rd.BarChart=function(){return rd.PolyChart()},rd.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},rd.AreaChart=function(){return rd.PolyChart()},rd.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},rd.DotPlot=function(){return rd.PolyChart()},rd.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},rd.LinePlot=function(){return rd.PolyChart()},rd.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},rd.Legend=function(){var t=rd.Legend.defaultConfig(),n=e.dispatch("hover");function r(){var n=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,r){var a=td({},n.elements[t]);return a.name=e,a.color=[].concat(n.elements[t].color)[r],a})}),i=e.merge(a);i=i.filter(function(e,t){return n.elements[t]&&(n.elements[t].visibleInLegend||void 0===n.elements[t].visibleInLegend)}),n.reverseOrder&&(i=i.reverse());var o=n.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=n.fontSize,c=null==n.isContinuous?"number"==typeof i[0]:n.isContinuous,u=c?n.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:n.height,width:n.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,n){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(r)?e.svg.symbol().type(r).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?n.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?n.textColor:"none"}),x.selectAll("text").style({fill:n.textColor,"font-size":n.fontSize}).text(function(e,t){return i[t].name}),r}return r.config=function(e){return arguments.length?(td(t,e),this):t},e.rebind(r,n,"on"),r},rd.Legend.defaultConfig=function(e,t){return{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:!1}}},rd.tooltipPanel=function(){var t,n,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+rd.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),n=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";n.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=n.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return td(a,e),l},l},rd.tooltipPanel.uid=1,rd.adapter={},rd.adapter.plotly=function(){var t={convert:function(t,n){var r={};if(t.data&&(r.data=t.data.map(function(e,t){var r=td({},e);return[[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"]]].forEach(function(e,t){rd.util.translator.apply(null,e.concat(n))}),n||delete r.marker,n&&delete r.groupId,n?("LinePlot"===r.geometry?(r.type="scatter",!0===r.dotVisible?(delete r.dotVisible,r.mode="lines+markers"):r.mode="lines"):"DotPlot"===r.geometry?(r.type="scatter",r.mode="markers"):"AreaChart"===r.geometry?r.type="area":"BarChart"===r.geometry&&(r.type="bar"),delete r.geometry):("scatter"===r.type?"lines"===r.mode?r.geometry="LinePlot":"markers"===r.mode?r.geometry="DotPlot":"lines+markers"===r.mode&&(r.geometry="LinePlot",r.dotVisible=!0):"area"===r.type?r.geometry="AreaChart":"bar"===r.type&&(r.geometry="BarChart"),delete r.mode,delete r.type),r}),!n&&t.layout&&"stack"===t.layout.barmode)){var a=rd.util.duplicates(r.data.map(function(e,t){return e.geometry}));r.data.forEach(function(e,t){var n=a.indexOf(e.geometry);-1!=n&&(r.data[t].groupId=n)})}if(t.layout){var i=td({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){rd.util.translator.apply(null,e.concat(n))}),n?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}n&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var ad,id=nt.extendDeepAll,od=ad={};od.framework=function(t){var n,r,a,i,o,l=new function(){var e,t=[],n=-1,r=!1;function a(e,t){return e?(r=!0,e[t](),r=!1,this):this}return{add:function(e){return r?this:(t.splice(n+1,t.length-n),t.push(e),n=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var r=t[n];return r?(a(r,"undo"),n-=1,e&&e(r.undo),this):this},redo:function(){var r=t[n+1];return r?(a(r,"redo"),n+=1,e&&e(r.redo),this):this},clear:function(){t=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n*:not(.chart-root)").remove(),n=n?id(n,r):r,a||(a=ed.Axis()),i=ed.adapter.plotly().convert(n),a.config(i).render(o),t.data=n.data,t.layout=n.layout,od.fillLayout(t),n}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return n},s.getLiveConfig=function(){return ed.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=ed.util.cloneJson(n);e=i,t=r,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),r=ed.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},od.fillLayout=function(t){var n=e.select(t).selectAll(".plot-container"),r=n.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:dt.background,_container:n,_paperdiv:r,_paper:a};t._fullLayout=id(i,t.layout)};var ld={};(ld=ed).manager=ad;var sd={},cd=Zf.enforce,ud=Zf.clean,fd=da,dd=0;function hd(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){nt.error(e)}}function pd(e,t){hd(e,dt.combine(t,"white"))}function gd(e,t){e._context||(e._context=nt.extendDeep({},b));var n,r,a,i=e._context;if(t){for(r=Object.keys(t),n=0;n=e.data.length||a<-e.data.length)throw new Error(n+" must be valid indices for gd.data.");if(t.indexOf(a,r+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+n+" must be unique.")}}function md(e,t,n){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),yd(e,t,"currentIndices"),void 0===n||Array.isArray(n)||(n=[n]),void 0!==n&&yd(e,n,"newIndices"),void 0!==n&&t.length!==n.length)throw new Error("current and new indices must be of equal length.")}function xd(e,n,r,a,i){!function(e,t,n,r){var a=nt.isPlainObject(r);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!nt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===n)throw new Error("indices must be an integer or array of integers");for(var i in yd(e,n,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==n.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in r)||!Array.isArray(r[i])||r[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,n,r,a);for(var o=function(e,n,r,a){var i,o,l,s,c,u=nt.isPlainObject(a),f=[];for(var d in Array.isArray(r)||(r=[r]),r=vd(r,e.data.length-1),n)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var A=_.parts[M],T=_.parts[M-1]+"."+A,L=_.parts.slice(0,M).join("."),C=nt.nestedProperty(e.layout,L).get(),S=nt.nestedProperty(o,L).get(),P=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===A?w:_d(P);var O=Or.getLayoutValObject(o,_.parts);if(O&&O.impliedEdits&&null!==w)for(var D in O.impliedEdits)v(nt.relativeAttr(b,D),O.impliedEdits[D]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(T.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(T),nt.nestedProperty(o,L+"._inputRange").set(null);else if(T.match(/^[xyz]axis[0-9]*\.autorange$/)){x(T),nt.nestedProperty(o,L+"._inputRange").set(null);var E=nt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else T.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&nt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===A){var N=C,R="linear"===S.type&&"log"===w,I="log"===S.type&&"linear"===w;if(R||I){if(N&&N.range)if(S.autorange)R&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],j=N.range[1];R?(F<=0&&j<=0&&v(L+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(j)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,j)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],z.getComponentMethod("annotations","convertCoords")(e,S,w,v),z.getComponentMethod("images","convertCoords")(e,S,w,v)}else v(L+".autorange",!0),v(L+".range",null);nt.nestedProperty(o,L+"._inputRange").set(null)}else if(A.match(Dt.AX_NAME_PATTERN)){var B=nt.nestedProperty(o,b).get(),q=(w||{}).type;q&&"-"!==q||(q="linear"),z.getComponentMethod("annotations","convertCoords")(e,B,q,v),z.getComponentMethod("images","convertCoords")(e,B,q,v)}var H=Ku.containerArrayMatch(b);if(H){n=H.array,r=H.index;var V=H.property,U=(nt.nestedProperty(i,n)||[])[r]||{},G=U,Y=O||{editType:"calc"},X=-1!==Y.editType.indexOf("calcIfAutorange");""===r?(X?h.calc=!0:Xt.update(h,Y),X=!1):""===V&&(G=w,Ku.isAddVal(w)?g[b]=null:Ku.isRemoveVal(w)?(g[b]=U,G=U):nt.warn("unrecognized full object value",t)),X&&(Ad(e,G,"x")||Ad(e,G,"y"))?h.calc=!0:Xt.update(h,Y),c[n]||(c[n]={});var Z=c[n][r];Z||(Z=c[n][r]={}),Z[V]=w,delete t[b]}else"reverse"===A?(C.range?C.range.reverse():(v(L+".autorange",!0),C.range=[1,0]),S.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==P&&"select"!==P?h.plot=!0:O?Xt.update(h,O):h.calc=!0,_.set(w))}}for(n in c){Ku.applyContainerArrayChanges(e,nt.nestedProperty(i,n),c[n],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(r=0;r=0&&n=0&&n=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var n=0;return function(){if(e&&++n===t)return e()}}return void 0===r._frameWaitingCnt&&(r._frameWaitingCnt=0),new Promise(function(i,c){function u(){r._currentFrame&&r._currentFrame.onComplete&&r._currentFrame.onComplete();var t=r._currentFrame=r._frameQueue.shift();if(t){var n=t.name?t.name.toString():null;e._fullLayout._currentFrame=n,r._lastFrameAt=Date.now(),r._timeToNext=t.frameOpts.duration,Zr.transition(e,t.frame.data,t.frame.layout,Uu.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:n,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(r._animationRaf),r._animationRaf=null}function f(){e.emit("plotly_animating"),r._lastFrameAt=-1/0,r._timeToNext=0,r._runningTransitions=0,r._currentFrame=null;var t=function(){r._animationRaf=window.requestAnimationFrame(t),Date.now()-r._lastFrameAt>r._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&nt.isPlainObject(t))v.push({type:"object",data:g(nt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;r--)if(nt.isPlainObject(t[r])){var d=t[r].name,h=(s[d]||f[d]||{}).name,p=t[r].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&dd<5&&(dd++,nt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===dd&&nt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:Zr.supplyFrameDefaults(t[r]),index:n&&void 0!==n[r]&&null!==n[r]?n[r]:c+r})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;r--){if("number"==typeof(a=u[r].frame).name&&nt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;n--)r=t[n],i.push({type:"delete",index:r}),o.unshift({type:"insert",index:r,value:a[r]});var l=Zr.modifyFrames,s=Zr.modifyFrames,c=[e,o],u=[e,i];return Hu&&Hu.add(e,l,c,s,u),Zr.modifyFrames(e,i)},sd.purge=function(e){var t=(e=nt.getGraphDiv(e))._fullLayout||{},n=e._fullData||[];return Zr.cleanPlot([],{},n,t),Zr.purge(e),Pt.purge(e),t._container&&t._container.remove(),delete e._context,e};var Cd={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},Sd=Mt.EventEmitter;var Pd=function(e){var t=e.emitter||new Sd,n=new Promise(function(r,a){var i=window.Image,o=e.svg,l=e.format||"png";if(nt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?n:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var n;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":n=c.toDataURL("image/jpeg");break;case"png":n=c.toDataURL("image/png");break;case"webp":n=c.toDataURL("image/webp");break;case"svg":n=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}r(n),e.promise||t.emit("success",n)},p.onerror=function(n){if(a(n),!e.promise)return t.emit("error",n)},p.src=g});return e.promise?n:t},Od=/"/g,zd=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var Dd=function(t,n,r){var a,i=t._fullLayout,o=i._paper,l=i._toppaper,s=i.width,c=i.height;o.insert("rect",":first-child").call(Vn.setRect,0,0,s,c).call(dt.fill,i.paper_bgcolor);var u=i._basePlotModules||[];for(a=0;a")?"":n.html(e).text()});return n.remove(),r}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(zd,"'"),nt.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},Ed={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},Nd=/^data:image\/\w+;base64,/;var Rd=function(e,t){var n,r,a;function i(e){return!(e in t)||nt.validate(t[e],Ed[e])}if(t=t||{},nt.isPlainObject(e)?(n=e.data||[],r=e.layout||{},a=e.config||{}):(e=nt.getGraphDiv(e),n=nt.extendDeep([],e.data),r=nt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,n){return nt.coerce(t,o,Ed,e,n)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=nt.extendFlat({},r);c&&(g.width=c),u&&(g.height=u);var v=nt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=Cd.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,Cd.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var n=Dd(p,s,f),r=p._fullLayout.width,a=p._fullLayout.height;if(sd.purge(p),document.body.removeChild(p),"svg"===s)return e(h?n:"data:image/svg+xml,"+encodeURIComponent(n));var i=document.createElement("canvas");i.id=nt.randstr(),Pd({format:s,width:r,height:a,scale:f,canvas:i,svg:n,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){sd.plot(p,n,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(Nd,""):e}(t))}).catch(function(e){t(e)})})},Id=nt.isPlainObject,Fd=Array.isArray,jd=nt.isArrayOrTypedArray;function Bd(e,t,n,r,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&r.push(Vd("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(Fd(u[y])){u[y].length>f[y].length&&r.push(Vd("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],nt.validate(x,m)?b!==x&&b!==+x&&r.push(Vd("dynamic",a,c.concat(y,v),x,b)):r.push(Vd("value",a,c.concat(y,v),x))}else r.push(Vd("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],nt.validate(x,m)?b!==x&&b!==+x&&r.push(Vd("dynamic",a,c.concat(y),x,b)):r.push(Vd("value",a,c.concat(y),x))}else if(d.items&&!h&&Fd(u)){var M,A,T=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(Vd("object","layout"))),Zr.supplyDefaults(o);for(var l=o._fullData,s=n.length,c=0;c-1&&(l[c[n]].title="");for(n=0;nq||e[1]V)return[_h(e[0],B,q),_h(e[1],H,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===B||e[0]===q)||(e[1]===t[1]&&(e[1]===H||e[1]===V)||void 0)}function X(e,t,n){return function(r,a){var i=G(r),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*nt.constrain((r[e]+a[e])/2,t,n)-((i||r)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function Z(e){var t=e[0],n=e[1],r=t===L[C-1][0],a=n===L[C-1][1];if(!r||!a)if(C>1){var i=t===L[C-2][0],o=n===L[C-2][1];r&&(t===B||t===q)&&i?o?C--:L[C-1]=e:a&&(n===H||n===V)&&o?i?C--:L[C-1]=e:L[C++]=e}else L[C++]=e}function W(e){L[C-1][0]!==e[0]&&L[C-1][1]!==e[1]&&Z([E,N]),Z(e),R=null,E=N=0}function J(e){if(z=e[0]q?q:0,D=e[1]V?V:0,z||D){if(C)if(R){var t=F(R,e);t.length>1&&(W(t[0]),L[C++]=t[1])}else I=F(L[C-1],e)[0],L[C++]=I;else L[C++]=[z||e[0],D||e[1]];var n=L[C-1];z&&D&&(n[0]!==z||n[1]!==D)?(R&&(E!==z&&N!==D?Z(E&&N?(r=R,i=(a=e)[0]-r[0],o=(a[1]-r[1])/i,(r[1]*a[0]-a[1]*r[0])/i>0?[o>0?B:q,V]:[o>0?q:B,H]):[E||z,N||D]):E&&N&&Z([E,N])),Z([z,D])):E-z&&N-D&&Z([z||E,D||N]),R=e,E=z,N=D}else R&&W(F(R,e)[0]),L[C++]=e;var r,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var n=[],r=0,a=0;a<4;a++){var i=U[a],o=bh(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!r||Math.abs(o.x-n[0][0])>1||Math.abs(o.y-n[0][1])>1)&&(o=[o.x,o.y],r&&O(o,e)P(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;J(l),r=l}}else J(i)}R&&Z([E||R[0],N||R[1]]),A.push(L.slice(0,C))}return A},kh=Hi.tester;function Mh(t,n,r,a,i,o,l){var s,c;!function(t,n,r,a,i){var o=r.xaxis,l=r.yaxis,s=e.extent(nt.simpleMap(o.range,o.r2c)),c=e.extent(nt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Hn.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var r=e[0].trace;Hn.hasMarkers(r)&&r.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=r.xaxis,h=r.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(z.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),a[0].node3=v;var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,A,T,L,C,S,P,O,D="",E="",N=[],R=nt.noop;if(y=p._ownFill,Hn.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(A=Vn.steps(g.shape),T=Vn.steps(g.shape.split("").reverse().join(""))):A=T="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Vn.smoothclosed(e.slice(1),g.smoothing):Vn.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return T(e.reverse())},N=wh(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),O=p._polygons=new Array(N.length),c=0;c1){var r=e.select(this);if(r.datum(a),t)f(r.style("opacity",0).attr("d",k).call(Vn.lineGroupStyle)).style("opacity",1);else{var i=f(r);i.attr("d",k),Vn.singleLineStyle(a,i)}}}}}var I=v.selectAll(".js-line").data(N);f(I.exit()).style("opacity",0).remove(),I.each(R(!1)),I.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Vn.lineGroupStyle).each(R(!0)),Vn.setClipUrl(I,r.layerClipId),N.length?(y?C&&P&&(x?("y"===x?C[1]=P[1]=h.c2p(0,!0):"x"===x&&(C[0]=P[0]=d.c2p(0,!0)),f(y).attr("d","M"+P+"L"+C+"L"+D.substr(1)).call(Vn.singleFillStyle)):f(y).attr("d",D+"Z").call(Vn.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&D&&b?("tonext"===p.fill?f(m).attr("d",D+"Z"+b+"Z").call(Vn.singleFillStyle):f(m).attr("d",D+"L"+b.substr(1)+"Z").call(Vn.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=O):(y?j(y):m&&j(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Vn.setClipUrl(e.select(this),n?null:r.layerClipId)})}function j(e){f(e).attr("d","M0,0Z")}function B(e){return e.filter(function(e){return e.vis})}function q(e){return e.id}function H(e){if(e.ids)return q}function V(){return!1}function U(n){var a,i=n[0].trace,o=e.select(this),l=Hn.hasMarkers(i),s=Hn.hasText(i),c=H(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?B:nt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?B:nt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Vn.pointStyle,i,t).call(Vn.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Vn.tryColorscale(i.marker,""),m=l&&Vn.tryColorscale(i.marker,"line");a.order(),a.each(function(n){var a=e.select(this),o=f(a);Vn.translatePoint(n,o,d,h)?(Vn.singlePointStyle(n,o,i,y,m,t),r.layerClipId&&Vn.hideOutsideRangePoint(n,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==n.data&&void 0!==n.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var n=e.select(this),a=f(n.select("text"));Vn.translatePoint(t,a,d,h)?r.layerClipId&&Vn.hideOutsideRangePoint(t,n,d,h,i.xcalendar,i.ycalendar):n.remove()}),a.selectAll("text").call(Vn.textPointStyle,i,t).each(function(t){var n=d.c2p(t.x),r=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:n,y:r})})}),a.exit().remove()}}function Ah(e,t,n){var r=e.selectAll("path.point"),a=e.selectAll("text");Vn.pointStyle(r,t,n),Vn.textPointStyle(a,t,n),Vn.selectedPointStyle(r,t),Vn.selectedTextStyle(a,t)}var Th=function(t,n){var r=n?n[0].node3:e.select(t).selectAll("g.trace.scatter");r.style("opacity",function(e){return e[0].trace.opacity}),r.selectAll("g.points").each(function(n){Ah(e.select(this),n.trace||n[0].trace,t)}),r.selectAll("g.trace path.js-line").call(Vn.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(Vn.fillGroupStyle),z.getComponentMethod("errorbars","style")(r)},Lh=Ah,Ch={};Ch.hasLines=Hn.hasLines,Ch.hasMarkers=Hn.hasMarkers,Ch.hasText=Hn.hasText,Ch.isBubble=Hn.isBubble,Ch.attributes=kr,Ch.supplyDefaults=function(e,t,n,r){function a(n,r){return nt.coerce(e,t,kr,n,r)}var i=function(e,t,n,r){var a,i=r("x"),o=r("y");if(z.getComponentMethod("calendars","handleTraceDefaults")(e,t,["x","y"],n),i)o?a=Math.min(i.length,o.length):(a=i.length,r("y0"),r("dy"));else{if(!o)return 0;a=t.y.length,r("x0"),r("dx")}return t._length=a,a}(e,t,r,a),o=i=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===n.xaxis&&i.yaxis===n.yaxis){i.opacity=void 0;break}}}}},Ch.calc=ch,Ch.arraysToCalcdata=Zo,Ch.plot=function(t,n,r,a,i){var o,l,s,c,u=n.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(r,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,n){var r,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){Mh(t,i,n,e,r,this,a)})})):u.selectAll("g.trace").each(function(e,i){Mh(t,i,n,e,r,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()},Ch.colorbar=uh,Ch.style=Th,Ch.hoverPoints=function(e,t,n,r){var a=e.cd,i=a[0].trace,o=e.xa,l=e.ya,s=o.c2p(t),c=l.c2p(n),u=[s,c],f=i.hoveron||"",d=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var h=function(e){var t=Math.max(d,e.mrc||0),n=o.c2p(e.x)-s,r=l.c2p(e.y)-c;return Math.max(Math.sqrt(n*n+r*r)-t,1-d/t)},p=Mi.getDistanceFunction(r,function(e){var t=Math.max(3,e.mrc||0),n=1-1/t,r=Math.abs(o.c2p(e.x)-s);return rR!=(L=w[b][1])>=R&&(M=w[b-1][0],A=w[b][0],L-T&&(k=M+(A-M)*(R-T)/(L-T),O=Math.min(O,k),D=Math.max(D,k)));O=Math.max(O,0),D=Math.min(D,o._length);var I=dt.defaultLine;return dt.opacity(i.fillcolor)?I=i.fillcolor:dt.opacity((i.line||{}).color)&&(I=i.line.color),nt.extendFlat(e,{distance:e.maxHoverDistance,x0:O,x1:D,y0:R,y1:R,color:I}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},Ch.selectPoints=function(e,t){var n,r,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Hn.hasMarkers(u)&&!Hn.hasText(u))return[];if(!1===t)for(n=0;n0&&(n.push(r),r=[])}return r.length>0&&n.push(r),n},jh.makeLine=function(e){return 1===e.length?{type:"LineString",coordinates:e[0]}:{type:"MultiLineString",coordinates:e}},jh.makePolygon=function(e){if(1===e.length)return{type:"Polygon",coordinates:e};for(var t=new Array(e.length),n=0;n")}(a,u,l.mockAxis,r[0].t.labels),[e]}},Xh.eventData=function(e,t){return e.lon=t.lon,e.lat=t.lat,e.location=t.loc?t.loc:null,e},Xh.selectPoints=function(e,t){var n,r,a,i,o,l=e.cd,s=e.xaxis,c=e.yaxis,u=[],f=l[0].trace;if(!Hn.hasMarkers(f)&&!Hn.hasText(f))return[];if(!1===t)for(o=0;ot?1:e>=t?0:NaN}function h(e){return null===e?NaN:+e}function p(e){return!isNaN(e)}function g(e){return{left:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)<0?r=i+1:a=i}return r},right:function(t,n,r,a){for(arguments.length<3&&(r=0),arguments.length<4&&(a=t.length);r>>1;e(t[i],n)>0?a=i:r=i+1}return r}}}t.ascending=d,t.descending=function(e,t){return te?1:t>=e?0:NaN},t.min=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++ar&&(n=r)}else{for(;++a=r){n=r;break}for(;++ar&&(n=r)}return n},t.max=function(e,t){var n,r,a=-1,i=e.length;if(1===arguments.length){for(;++a=r){n=r;break}for(;++an&&(n=r)}else{for(;++a=r){n=r;break}for(;++an&&(n=r)}return n},t.extent=function(e,t){var n,r,a,i=-1,o=e.length;if(1===arguments.length){for(;++i=r){n=a=r;break}for(;++ir&&(n=r),a=r){n=a=r;break}for(;++ir&&(n=r),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(d);function y(e){return e.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(e){return g(1===e.length?function(t,n){return d(e(t),n)}:e)},t.shuffle=function(e,t,n){(i=arguments.length)<3&&(n=e.length,i<2&&(t=0));for(var r,a,i=n-t;i;)a=Math.random()*i--|0,r=e[i+t],e[i+t]=e[a+t],e[a+t]=r;return e},t.permute=function(e,t){for(var n=t.length,r=new Array(n);n--;)r[n]=e[t[n]];return r},t.pairs=function(e){for(var t=0,n=e.length-1,r=e[0],a=new Array(n<0?0:n);t=0;)for(t=(r=e[a]).length;--t>=0;)n[--o]=r[t];return n};var m=Math.abs;function x(e,t){for(var n in t)Object.defineProperty(e.prototype,n,{value:t[n],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(e,t,n){if(arguments.length<3&&(n=1,arguments.length<2&&(t=e,e=0)),(t-e)/n==1/0)throw new Error("infinite range");var r,a=[],i=function(e){var t=1;for(;e*t%1;)t*=10;return t}(m(n)),o=-1;if(e*=i,t*=i,(n*=i)<0)for(;(r=e+n*++o)>t;)a.push(r/i);else for(;(r=e+n*++o)=a.length)return n?n.call(r,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,h=i.length,p=a[l++],g=new b;++d=a.length)return t;var r=[],o=i[n++];return t.forEach(function(t,a){r.push({key:t,values:e(a,n)})}),o?r.sort(function(e,t){return o(e.key,t.key)}):r}(o(t.map,e,0),0)},r.key=function(e){return a.push(e),r},r.sortKeys=function(e){return i[a.length-1]=e,r},r.sortValues=function(t){return e=t,r},r.rollup=function(e){return n=e,r},r},t.set=function(e){var t=new P;if(e)for(var n=0,r=e.length;n=0&&(r=e.slice(n+1),e=e.slice(0,n)),e)return arguments.length<2?this[e].on(r):this[e].on(r,t);if(2===arguments.length){if(null==t)for(e in this)this.hasOwnProperty(e)&&this[e].on(r,null);return this}},t.event=null,t.requote=function(e){return e.replace(q,"\\$&")};var q=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,H={}.__proto__?function(e,t){e.__proto__=t}:function(e,t){for(var n in t)e[n]=t[n]};function V(e){return H(e,X),e}var U=function(e,t){return t.querySelector(e)},G=function(e,t){return t.querySelectorAll(e)},Y=function(e,t){var n=e.matches||e[D(e,"matchesSelector")];return(Y=function(e,t){return n.call(e,t)})(e,t)};"function"==typeof Sizzle&&(U=function(e,t){return Sizzle(e,t)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(e){return"function"==typeof e?e:function(){return U(e,this)}}function W(e){return"function"==typeof e?e:function(){return G(e,this)}}X.select=function(e){var t,n,r,a,i=[];e=Z(e);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(n=e.slice(0,t))&&(e=e.slice(t+1)),Q.hasOwnProperty(n)?{space:Q[n],local:e}:e}},X.attr=function(e,n){if(arguments.length<2){if("string"==typeof e){var r=this.node();return(e=t.ns.qualify(e)).local?r.getAttributeNS(e.space,e.local):r.getAttribute(e)}for(n in e)this.each($(n,e[n]));return this}return this.each($(e,n))},X.classed=function(e,t){if(arguments.length<2){if("string"==typeof e){var n=this.node(),r=(e=te(e)).length,a=-1;if(t=n.classList){for(;++a=0;)(n=r[a])&&(i&&i!==n.nextSibling&&i.parentNode.insertBefore(n,i),i=n);return this},X.sort=function(e){e=function(e){arguments.length||(e=d);return function(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}}.apply(this,arguments);for(var t=-1,n=this.length;++t0&&(e=e.slice(0,o));var s=pe.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=ve),o?n?function(){var t=l(n,r(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:c:n?R:function(){var n,r=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(n=a.match(r)){var i=this[a];this.removeEventListener(n[1],i,i.$),delete this[a]}}}t.selection.enter=fe,t.selection.enter.prototype=de,de.append=X.append,de.empty=X.empty,de.node=X.node,de.call=X.call,de.size=X.size,de.select=function(e){for(var t,n,r,a,i,o=[],l=-1,s=this.length;++l=r&&(r=t+1);!(o=l[r])&&++r0?1:e<0?-1:0}function Oe(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function De(e){return e>1?0:e<-1?Ae:Math.acos(e)}function Ee(e){return e>1?Se:e<-1?-Se:Math.asin(e)}function Re(e){return((e=Math.exp(e))+1/e)/2}function Ne(e){return(e=Math.sin(e/2))*e}var Ie=Math.SQRT2;t.interpolateZoom=function(e,t){var n,r,a=e[0],i=e[1],o=e[2],l=t[0],s=t[1],c=t[2],u=l-a,f=s-i,d=u*u+f*f;if(d0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(e){return(e-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(e){return(e-d.y)/d.k}).map(u.invert))}function S(e){v++||e({type:"zoomstart"})}function C(e){L(),e({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function P(e){--v||(e({type:"zoomend"}),n=null)}function z(){var e=this,n=_.of(e,arguments),r=0,a=t.select(o(e)).on(m,function(){r=1,A(t.mouse(e),i),C(n)}).on(x,function(){a.on(m,null).on(x,null),l(r),P(n)}),i=k(t.mouse(e)),l=xe(e);ll.call(e),S(n)}function O(){var e,n=this,r=_.of(n,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(n),h=xe(n);function p(){var r=t.touches(n);return e=d.k,r.forEach(function(e){e.identifier in a&&(a[e.identifier]=k(e))}),r}function g(){var e=t.event.target;t.select(e).on(s,v).on(c,m),u.push(e);for(var r=t.event.changedTouches,o=0,f=r.length;o1){y=h[0];var x=h[1],b=y[0]-x[0],_=y[1]-x[1];i=b*b+_*_}}function v(){var o,s,c,u,f=t.touches(n);ll.call(n);for(var d=0,h=f.length;d360?e-=360:e<0&&(e+=360),e<60?r+(a-r)*e/60:e<180?a:e<240?r+(a-r)*(240-e)/60:r}(e))}return e=isNaN(e)?0:(e%=360)<0?e+360:e,t=isNaN(t)?0:t<0?0:t>1?1:t,r=2*(n=n<0?0:n>1?1:n)-(a=n<=.5?n*(1+t):n+t-n*t),new it(i(e+120),i(e),i(e-120))}function Ge(e,n,r){return this instanceof Ge?(this.h=+e,this.c=+n,void(this.l=+r)):arguments.length<2?e instanceof Ge?new Ge(e.h,e.c,e.l):tt(e instanceof Ze?e.l:(e=dt((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Ge(e,n,r)}Ve.brighter=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,this.l/e)},Ve.darker=function(e){return e=Math.pow(.7,arguments.length?e:1),new He(this.h,this.s,e*this.l)},Ve.rgb=function(){return Ue(this.h,this.s,this.l)},t.hcl=Ge;var Ye=Ge.prototype=new qe;function Xe(e,t,n){return isNaN(e)&&(e=0),isNaN(t)&&(t=0),new Ze(n,Math.cos(e*=Ce)*t,Math.sin(e)*t)}function Ze(e,t,n){return this instanceof Ze?(this.l=+e,this.a=+t,void(this.b=+n)):arguments.length<2?e instanceof Ze?new Ze(e.l,e.a,e.b):e instanceof Ge?Xe(e.h,e.c,e.l):dt((e=it(e)).r,e.g,e.b):new Ze(e,t,n)}Ye.brighter=function(e){return new Ge(this.h,this.c,Math.min(100,this.l+We*(arguments.length?e:1)))},Ye.darker=function(e){return new Ge(this.h,this.c,Math.max(0,this.l-We*(arguments.length?e:1)))},Ye.rgb=function(){return Xe(this.h,this.c,this.l).rgb()},t.lab=Ze;var We=18,Je=.95047,Qe=1,$e=1.08883,Ke=Ze.prototype=new qe;function et(e,t,n){var r=(e+16)/116,a=r+t/500,i=r-n/200;return new it(at(3.2404542*(a=nt(a)*Je)-1.5371385*(r=nt(r)*Qe)-.4985314*(i=nt(i)*$e)),at(-.969266*a+1.8760108*r+.041556*i),at(.0556434*a-.2040259*r+1.0572252*i))}function tt(e,t,n){return e>0?new Ge(Math.atan2(n,t)*Pe,Math.sqrt(t*t+n*n),e):new Ge(NaN,NaN,e)}function nt(e){return e>.206893034?e*e*e:(e-4/29)/7.787037}function rt(e){return e>.008856?Math.pow(e,1/3):7.787037*e+4/29}function at(e){return Math.round(255*(e<=.00304?12.92*e:1.055*Math.pow(e,1/2.4)-.055))}function it(e,t,n){return this instanceof it?(this.r=~~e,this.g=~~t,void(this.b=~~n)):arguments.length<2?e instanceof it?new it(e.r,e.g,e.b):ut(""+e,it,Ue):new it(e,t,n)}function ot(e){return new it(e>>16,e>>8&255,255&e)}function lt(e){return ot(e)+""}Ke.brighter=function(e){return new Ze(Math.min(100,this.l+We*(arguments.length?e:1)),this.a,this.b)},Ke.darker=function(e){return new Ze(Math.max(0,this.l-We*(arguments.length?e:1)),this.a,this.b)},Ke.rgb=function(){return et(this.l,this.a,this.b)},t.rgb=it;var st=it.prototype=new qe;function ct(e){return e<16?"0"+Math.max(0,e).toString(16):Math.min(255,e).toString(16)}function ut(e,t,n){var r,a,i,o=0,l=0,s=0;if(r=/([a-z]+)\((.*)\)/.exec(e=e.toLowerCase()))switch(a=r[2].split(","),r[1]){case"hsl":return n(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return t(pt(a[0]),pt(a[1]),pt(a[2]))}return(i=gt.get(e))?t(i.r,i.g,i.b):(null==e||"#"!==e.charAt(0)||isNaN(i=parseInt(e.slice(1),16))||(4===e.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===e.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),t(o,l,s))}function ft(e,t,n){var r,a,i=Math.min(e/=255,t/=255,n/=255),o=Math.max(e,t,n),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),r=e==o?(t-n)/l+(t0&&s<1?0:r),new He(r,a,s)}function dt(e,t,n){var r=rt((.4124564*(e=ht(e))+.3575761*(t=ht(t))+.1804375*(n=ht(n)))/Je),a=rt((.2126729*e+.7151522*t+.072175*n)/Qe);return Ze(116*a-16,500*(r-a),200*(a-rt((.0193339*e+.119192*t+.9503041*n)/$e)))}function ht(e){return(e/=255)<=.04045?e/12.92:Math.pow((e+.055)/1.055,2.4)}function pt(e){var t=parseFloat(e);return"%"===e.charAt(e.length-1)?Math.round(2.55*t):t}st.brighter=function(e){e=Math.pow(.7,arguments.length?e:1);var t=this.r,n=this.g,r=this.b,a=30;return t||n||r?(t&&t=200&&t<300||304===t){try{e=a.call(o,c)}catch(e){return void l.error.call(o,e)}l.load.call(o,e)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var n=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=n}},o.header=function(e,t){return e=(e+"").toLowerCase(),arguments.length<2?s[e]:(null==t?delete s[e]:s[e]=t+"",o)},o.mimeType=function(e){return arguments.length?(n=null==e?null:e+"",o):n},o.responseType=function(e){return arguments.length?(u=e,o):u},o.response=function(e){return a=e,o},["get","post"].forEach(function(e){o[e]=function(){return o.send.apply(o,[e].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),c.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=n&&c.overrideMimeType&&c.overrideMimeType(n),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(e){a(null,e)}),l.beforesend.call(o,c),c.send(null==r?null:r),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(e){return 1===e.length?function(t,n){e(null==t?n:null)}:e}(i))}gt.forEach(function(e,t){gt.set(e,ot(t))}),t.functor=vt,t.xhr=yt(z),t.dsv=function(e,t){var n=new RegExp('["'+e+"\n]"),r=e.charCodeAt(0);function a(e,n,r){arguments.length<3&&(r=n,n=null);var a=mt(e,t,null==n?i:o(n),r);return a.row=function(e){return arguments.length?a.response(null==(n=e)?i:o(e)):n},a}function i(e){return a.parse(e.responseText)}function o(e){return function(t){return a.parse(t.responseText,e)}}function l(t){return t.map(s).join(e)}function s(e){return n.test(e)?'"'+e.replace(/\"/g,'""')+'"':e}return a.parse=function(e,t){var n;return a.parseRows(e,function(e,r){if(n)return n(e,r-1);var a=new Function("d","return {"+e.map(function(e,t){return JSON.stringify(e)+": d["+t+"]"}).join(",")+"}");n=t?function(e,n){return t(a(e),n)}:a})},a.parseRows=function(e,t){var n,a,i={},o={},l=[],s=e.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var t=c;if(34===e.charCodeAt(t)){for(var n=t;n++24?(isFinite(t)&&(clearTimeout(wt),wt=setTimeout(At,t)),_t=0):(_t=1,kt(At))}function Tt(){for(var e=Date.now(),t=xt;t;)e>=t.t&&t.c(e-t.t)&&(t.c=null),t=t.n;return e}function Lt(){for(var e,t=xt,n=1/0;t;)t.c?(t.t8?function(e){return e/n}:function(e){return e*n},symbol:e}});t.formatPrefix=function(e,n){var r=0;return(e=+e)&&(e<0&&(e*=-1),n&&(e=t.round(e,St(e,n))),r=1+Math.floor(1e-12+Math.log(e)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),Ct[8+r/3]};var Pt=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,zt=t.map({b:function(e){return e.toString(2)},c:function(e){return String.fromCharCode(e)},o:function(e){return e.toString(8)},x:function(e){return e.toString(16)},X:function(e){return e.toString(16).toUpperCase()},g:function(e,t){return e.toPrecision(t)},e:function(e,t){return e.toExponential(t)},f:function(e,t){return e.toFixed(t)},r:function(e,n){return(e=t.round(e,St(e,n))).toFixed(Math.max(0,Math.min(20,St(e*(1+1e-15),n))))}});function Ot(e){return e+""}var Dt=t.time={},Et=Date;function Rt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Rt.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(){Nt.setUTCDate.apply(this._,arguments)},setDay:function(){Nt.setUTCDay.apply(this._,arguments)},setFullYear:function(){Nt.setUTCFullYear.apply(this._,arguments)},setHours:function(){Nt.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Nt.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Nt.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Nt.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Nt.setUTCSeconds.apply(this._,arguments)},setTime:function(){Nt.setTime.apply(this._,arguments)}};var Nt=Date.prototype;function It(e,t,n){function r(t){var n=e(t),r=i(n,1);return t-n1)for(;o68?1900:2e3),n+a[0].length):-1}function Jt(e,t,n){return/^[+-]\d{4}$/.test(t=t.slice(n,n+5))?(e.Z=-t,n+5):-1}function Qt(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function $t(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function Kt(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+3));return r?(e.j=+r[0],n+r[0].length):-1}function en(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function tn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function nn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function rn(e,t,n){Bt.lastIndex=0;var r=Bt.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function an(e){var t=e.getTimezoneOffset(),n=t>0?"-":"+",r=m(t)/60|0,a=m(t)%60;return n+Ht(r,"0",2)+Ht(a,"0",2)}function on(e,t,n){qt.lastIndex=0;var r=qt.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function ln(e){for(var t=e.length,n=-1;++n0&&l>0&&(s+l+1>t&&(l=Math.max(1,t-s)),i.push(e.substring(n-=l,n+l)),!((s+=l+1)>t));)l=a[o=(o+1)%a.length];return i.reverse().join(r)}:z;return function(e){var r=Pt.exec(e),a=r[1]||" ",l=r[2]||">",s=r[3]||"-",c=r[4]||"",u=r[5],f=+r[6],d=r[7],h=r[8],p=r[9],g=1,v="",y="",m=!1,x=!0;switch(h&&(h=+h.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),p){case"n":d=!0,p="g";break;case"%":g=100,y="%",p="f";break;case"p":g=100,y="%",p="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":m=!0,h=0;break;case"s":g=-1,p="r"}"$"===c&&(v=i[0],y=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=zt.get(p)||Ot;var b=u&&d;return function(e){var r=y;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,h);e=c.scale(e),r=c.symbol+y}else e*=g;var _,w,k=(e=p(e,h)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=n+e.substring(k+1);!u&&d&&(_=o(_,1/0));var A=v.length+_.length+w.length+(b?0:i.length),T=A"===l?T+i+e:"^"===l?T.substring(0,A>>=1)+i+e+T.substring(A):i+(b?e:T+e))+r}}}(e),timeFormat:function(e){var n=e.dateTime,r=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(e){var t=e.length;function n(n){for(var r,a,i,o=[],l=-1,s=0;++l=c)return-1;if(37===(a=t.charCodeAt(l++))){if(o=t.charAt(l++),!(i=w[o in jt?t.charAt(l++):o])||(r=i(e,n,r))<0)return-1}else if(a!=n.charCodeAt(r++))return-1}return r}u.utc=function(e){var t=u(e);function n(e){try{var n=new(Et=Rt);return n._=e,t(n)}finally{Et=Date}}return n.parse=function(e){try{Et=Rt;var n=t.parse(e);return n&&n._}finally{Et=Date}},n.toString=t.toString,n},u.multi=u.utc.multi=ln;var d=t.map(),h=Vt(o),p=Ut(o),g=Vt(l),v=Ut(l),y=Vt(s),m=Ut(s),x=Vt(c),b=Ut(c);i.forEach(function(e,t){d.set(e.toLowerCase(),t)});var _={a:function(e){return l[e.getDay()]},A:function(e){return o[e.getDay()]},b:function(e){return c[e.getMonth()]},B:function(e){return s[e.getMonth()]},c:u(n),d:function(e,t){return Ht(e.getDate(),t,2)},e:function(e,t){return Ht(e.getDate(),t,2)},H:function(e,t){return Ht(e.getHours(),t,2)},I:function(e,t){return Ht(e.getHours()%12||12,t,2)},j:function(e,t){return Ht(1+Dt.dayOfYear(e),t,3)},L:function(e,t){return Ht(e.getMilliseconds(),t,3)},m:function(e,t){return Ht(e.getMonth()+1,t,2)},M:function(e,t){return Ht(e.getMinutes(),t,2)},p:function(e){return i[+(e.getHours()>=12)]},S:function(e,t){return Ht(e.getSeconds(),t,2)},U:function(e,t){return Ht(Dt.sundayOfYear(e),t,2)},w:function(e){return e.getDay()},W:function(e,t){return Ht(Dt.mondayOfYear(e),t,2)},x:u(r),X:u(a),y:function(e,t){return Ht(e.getFullYear()%100,t,2)},Y:function(e,t){return Ht(e.getFullYear()%1e4,t,4)},Z:an,"%":function(){return"%"}},w={a:function(e,t,n){g.lastIndex=0;var r=g.exec(t.slice(n));return r?(e.w=v.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(e,t,n){h.lastIndex=0;var r=h.exec(t.slice(n));return r?(e.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(e,t,n){x.lastIndex=0;var r=x.exec(t.slice(n));return r?(e.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(e,t,n){y.lastIndex=0;var r=y.exec(t.slice(n));return r?(e.m=m.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(e,t,n){return f(e,_.c.toString(),t,n)},d:$t,e:$t,H:en,I:en,j:Kt,L:rn,m:Qt,M:tn,p:function(e,t,n){var r=d.get(t.slice(n,n+=2).toLowerCase());return null==r?-1:(e.p=r,n)},S:nn,U:Yt,w:Gt,W:Xt,x:function(e,t,n){return f(e,_.x.toString(),t,n)},X:function(e,t,n){return f(e,_.X.toString(),t,n)},y:Wt,Y:Zt,Z:Jt,"%":on};return u}(e)}};var sn=t.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"]});function cn(){}t.format=sn.numberFormat,t.geo={},cn.prototype={s:0,t:0,add:function(e){fn(e,this.t,un),fn(un.s,this.s,this),this.s?this.t+=un.t:this.s=un.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var un=new cn;function fn(e,t,n){var r=n.s=e+t,a=r-e,i=r-a;n.t=e-i+(t-a)}function dn(e,t){e&&pn.hasOwnProperty(e.type)&&pn[e.type](e,t)}t.geo.stream=function(e,t){e&&hn.hasOwnProperty(e.type)?hn[e.type](e,t):dn(e,t)};var hn={Feature:function(e,t){dn(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,a=n.length;++r=0?1:-1,l=o*i,s=Math.cos(t),c=Math.sin(t),u=a*c,f=r*s+u*Math.cos(l),d=u*o*Math.sin(l);Cn.add(Math.atan2(d,f)),n=e,r=s,a=c}Pn.point=function(o,l){Pn.point=i,n=(e=o)*Ce,r=Math.cos(l=(t=l)*Ce/2+Ae/4),a=Math.sin(l)},Pn.lineEnd=function(){i(e,t)}}function On(e){var t=e[0],n=e[1],r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}function Dn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function En(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Rn(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Nn(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function In(e){var t=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function Fn(e){return[Math.atan2(e[1],e[0]),Ee(e[2])]}function jn(e,t){return m(e[0]-t[0])ke?a=90:c<-ke&&(n=-90),f[0]=e,f[1]=r}};function h(t,i){u.push(f=[e=t,r=t]),ia&&(a=i)}function p(t,o){var l=On([t*Ce,o*Ce]);if(s){var c=En(s,l),u=En([c[1],-c[0],0],c);In(u),u=Fn(u);var f=t-i,d=f>0?1:-1,p=u[0]*Pe*d,g=m(f)>180;if(g^(d*ia&&(a=v);else if(g^(d*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t):r>=e?(tr&&(r=t)):t>i?_(e,t)>_(e,r)&&(r=t):_(t,r)>_(e,r)&&(e=t)}else h(t,o);s=l,i=t}function g(){d.point=p}function v(){f[0]=e,f[1]=r,d.point=h,s=null}function y(e,t){if(s){var n=e-i;c+=m(n)>180?n+(n>0?360:-360):n}else o=e,l=t;Pn.point(e,t),p(e,t)}function x(){Pn.lineStart()}function b(){y(o,l),Pn.lineEnd(),m(c)>ke&&(e=-(r=180)),f[0]=e,f[1]=r,s=null}function _(e,t){return(t-=e)<0?t+360:t}function w(e,t){return e[0]-t[0]}function k(e,t){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e_(g[0],g[1])&&(g[1]=h[1]),_(h[0],g[1])>_(g[0],g[1])&&(g[0]=h[0])):l.push(g=h);for(var s,c,h,p=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=h,++o)h=l[o],(s=_(g[1],h[0]))>p&&(p=s,e=h[0],r=g[1])}return u=f=null,e===1/0||n===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,n],[r,a]]}}(),t.geo.centroid=function(e){mn=xn=bn=_n=wn=kn=Mn=An=Tn=Ln=Sn=0,t.geo.stream(e,Bn);var n=Tn,r=Ln,a=Sn,i=n*n+r*r+a*a;return i=0;--l)a.point((f=u[l])[0],f[1]);else r(h.x,h.p.x,-1,a);h=h.p}u=(h=h.o).z,p=!p}while(!h.v);a.lineEnd()}}}function Wn(e){if(t=e.length){for(var t,n,r=0,a=e[0];++r=0?1:-1,k=w*_,M=k>Ae,A=p*x;if(Cn.add(Math.atan2(A*w*Math.sin(k),g*b+A*Math.cos(k))),i+=M?_+w*Te:_,M^d>=n^y>=n){var T=En(On(f),On(e));In(T);var L=En(a,T);In(L);var S=(M^_>=0?-1:1)*Ee(L[2]);(r>S||r===S&&(T[0]||T[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;d=y,p=x,g=b,f=e}}return(i<-ke||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&t&&n.push(n.pop().concat(n.shift())),l.push(n.filter($n))}return u}}function $n(e){return e.length>1}function Kn(){var e,t=[];return{lineStart:function(){t.push(e=[])},point:function(t,n){e.push([t,n])},lineEnd:R,buffer:function(){var n=t;return t=[],e=null,n},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function er(e,t){return((e=e.x)[0]<0?e[1]-Se-ke:Se-e[1])-((t=t.x)[0]<0?t[1]-Se-ke:Se-t[1])}var tr=Qn(Xn,function(e){var t,n=NaN,r=NaN,a=NaN;return{lineStart:function(){e.lineStart(),t=1},point:function(i,o){var l=i>0?Ae:-Ae,s=m(i-n);m(s-Ae)0?Se:-Se),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),e.point(i,r),t=0):a!==l&&s>=Ae&&(m(n-a)ke?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(n)-Math.sin(r)*(a=Math.cos(t))*Math.sin(e))/(a*i*o)):(t+r)/2}(n,r,i,o),e.point(a,r),e.lineEnd(),e.lineStart(),e.point(l,r),t=0),e.point(n=i,r=o),a=l},lineEnd:function(){e.lineEnd(),n=r=NaN},clean:function(){return 2-t}}},function(e,t,n,r){var a;if(null==e)a=n*Se,r.point(-Ae,a),r.point(0,a),r.point(Ae,a),r.point(Ae,0),r.point(Ae,-a),r.point(0,-a),r.point(-Ae,-a),r.point(-Ae,0),r.point(-Ae,a);else if(m(e[0]-t[0])>ke){var i=e[0]0)){if(i/=d,d<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=n-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i0)){if(i/=h,h<0){if(i0){if(i>f)return;i>u&&(u=i)}if(i=r-c,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>u&&(u=i)}else if(h>0){if(i0&&(a.a={x:s+u*d,y:c+u*h}),f<1&&(a.b={x:s+f*d,y:c+f*h}),a}}}}}}var rr=1e9;function ar(e,n,r,a){return function(s){var c,u,f,d,h,p,g,v,y,m,x,b=s,_=Kn(),w=nr(e,n,r,a),k={point:T,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,y=!1,g=v=NaN},lineEnd:function(){c&&(L(d,h),p&&y&&_.rejoin(),c.push(_.buffer()));k.point=T,y&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var n=function(e){for(var t=0,n=u.length,r=e[1],a=0;ar&&Oe(c,i,e)>0&&++t:i[1]<=r&&Oe(c,i,e)<0&&--t,c=i;return 0!==t}([e,a]),r=x&&n,i=c.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Zn(c,o,n,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:r,u>1?a:n)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function A(t,i){return e<=t&&t<=r&&n<=i&&i<=a}function T(e,t){A(e,t)&&s.point(e,t)}function L(e,t){var n=A(e=Math.max(-rr,Math.min(rr,e)),t=Math.max(-rr,Math.min(rr,t)));if(u&&f.push([e,t]),m)d=e,h=t,p=n,m=!1,n&&(s.lineStart(),s.point(e,t));else if(n&&y)s.point(e,t);else{var r={a:{x:g,y:v},b:{x:e,y:t}};w(r)?(y||(s.lineStart(),s.point(r.a.x,r.a.y)),s.point(r.b.x,r.b.y),n||s.lineEnd(),x=!1):n&&(s.lineStart(),s.point(e,t),x=!1)}g=e,v=t,y=n}return k};function i(t,a){return m(t[0]-e)0?0:3:m(t[0]-r)0?2:1:m(t[1]-n)0?1:0:a>0?3:2}function o(e,t){return l(e.x,t.x)}function l(e,t){var n=i(e,1),r=i(t,1);return n!==r?n-r:0===n?t[1]-e[1]:1===n?e[0]-t[0]:2===n?e[1]-t[1]:t[0]-e[0]}}function ir(e){var t=0,n=Ae/3,r=Lr(e),a=r(t,n);return a.parallels=function(e){return arguments.length?r(t=e[0]*Ae/180,n=e[1]*Ae/180):[t/Ae*180,n/Ae*180]},a}function or(e,t){var n=Math.sin(e),r=(n+Math.sin(t))/2,a=1+n*(2*r-n),i=Math.sqrt(a)/r;function o(e,t){var n=Math.sqrt(a-2*r*Math.sin(t))/r;return[n*Math.sin(e*=r),i-n*Math.cos(e)]}return o.invert=function(e,t){var n=i-t;return[Math.atan2(e,n)/r,Ee((a-(e*e+n*n)*r*r)/(2*r))]},o}t.geo.clipExtent=function(){var e,t,n,r,a,i,o={stream:function(e){return a&&(a.valid=!1),(a=i(e)).valid=!0,a},extent:function(l){return arguments.length?(i=ar(e=+l[0][0],t=+l[0][1],n=+l[1][0],r=+l[1][1]),a&&(a.valid=!1,a=null),o):[[e,t],[n,r]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return ir(or)}).raw=or,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,n,r,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,n){e=[t,n]}};function c(t){var i=t[0],o=t[1];return e=null,n(i,o),e||(r(i,o),e)||a(i,o),e}return c.invert=function(e){var t=i.scale(),n=i.translate(),r=(e[0]-n[0])/t,a=(e[1]-n[1])/t;return(a>=.12&&a<.234&&r>=-.425&&r<-.214?o:a>=.166&&a<.234&&r>=-.214&&r<-.115?l:i).invert(e)},c.stream=function(e){var t=i.stream(e),n=o.stream(e),r=l.stream(e);return{point:function(e,a){t.point(e,a),n.point(e,a),r.point(e,a)},sphere:function(){t.sphere(),n.sphere(),r.sphere()},lineStart:function(){t.lineStart(),n.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),n.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),n.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),n.polygonEnd(),r.polygonEnd()}}},c.precision=function(e){return arguments.length?(i.precision(e),o.precision(e),l.precision(e),c):i.precision()},c.scale=function(e){return arguments.length?(i.scale(e),o.scale(.35*e),l.scale(e),c.translate(i.translate())):i.scale()},c.translate=function(e){if(!arguments.length)return i.translate();var t=i.scale(),u=+e[0],f=+e[1];return n=i.translate(e).clipExtent([[u-.455*t,f-.238*t],[u+.455*t,f+.238*t]]).stream(s).point,r=o.translate([u-.307*t,f+.201*t]).clipExtent([[u-.425*t+ke,f+.12*t+ke],[u-.214*t-ke,f+.234*t-ke]]).stream(s).point,a=l.translate([u-.205*t,f+.212*t]).clipExtent([[u-.214*t+ke,f+.166*t+ke],[u-.115*t-ke,f+.234*t-ke]]).stream(s).point,c},c.scale(1070)};var lr,sr,cr,ur,fr,dr,hr={point:R,lineStart:R,lineEnd:R,polygonStart:function(){sr=0,hr.lineStart=pr},polygonEnd:function(){hr.lineStart=hr.lineEnd=hr.point=R,lr+=m(sr/2)}};function pr(){var e,t,n,r;function a(e,t){sr+=r*e-n*t,n=e,r=t}hr.point=function(i,o){hr.point=a,e=n=i,t=r=o},hr.lineEnd=function(){a(e,t)}}var gr={point:function(e,t){efr&&(fr=e);tdr&&(dr=t)},lineStart:R,lineEnd:R,polygonStart:R,polygonEnd:R};function vr(e){return"m0,"+e+"a"+e+","+e+" 0 1,1 0,"+-2*e+"a"+e+","+e+" 0 1,1 0,"+2*e+"z"}var yr,mr={point:xr,lineStart:br,lineEnd:_r,polygonStart:function(){mr.lineStart=wr},polygonEnd:function(){mr.point=xr,mr.lineStart=br,mr.lineEnd=_r}};function xr(e,t){bn+=e,_n+=t,++wn}function br(){var e,t;function n(n,r){var a=n-e,i=r-t,o=Math.sqrt(a*a+i*i);kn+=o*(e+n)/2,Mn+=o*(t+r)/2,An+=o,xr(e=n,t=r)}mr.point=function(r,a){mr.point=n,xr(e=r,t=a)}}function _r(){mr.point=xr}function wr(){var e,t,n,r;function a(e,t){var a=e-n,i=t-r,o=Math.sqrt(a*a+i*i);kn+=o*(n+e)/2,Mn+=o*(r+t)/2,An+=o,Tn+=(o=r*e-n*t)*(n+e),Ln+=o*(r+t),Sn+=3*o,xr(n=e,r=t)}mr.point=function(i,o){mr.point=a,xr(e=n=i,t=r=o)},mr.lineEnd=function(){a(e,t)}}function kr(e){var t=.5,n=Math.cos(30*Ce),r=16;function a(t){return(r?function(t){var n,a,o,l,s,c,u,f,d,h,p,g,v={point:y,lineStart:m,lineEnd:b,polygonStart:function(){t.polygonStart(),v.lineStart=_},polygonEnd:function(){t.polygonEnd(),v.lineStart=m}};function y(n,r){n=e(n,r),t.point(n[0],n[1])}function m(){f=NaN,v.point=x,t.lineStart()}function x(n,a){var o=On([n,a]),l=e(n,a);i(f,d,u,h,p,g,f=l[0],d=l[1],u=n,h=o[0],p=o[1],g=o[2],r,t),t.point(f,d)}function b(){v.point=y,t.lineEnd()}function _(){m(),v.point=w,v.lineEnd=k}function w(e,t){x(n=e,t),a=f,o=d,l=h,s=p,c=g,v.point=x}function k(){i(f,d,u,h,p,g,a,o,n,l,s,c,r,t),v.lineEnd=b,b()}return v}:function(t){return Ar(t,function(n,r){n=e(n,r),t.point(n[0],n[1])})})(t)}function i(r,a,o,l,s,c,u,f,d,h,p,g,v,y){var x=u-r,b=f-a,_=x*x+b*b;if(_>4*t&&v--){var w=l+h,k=s+p,M=c+g,A=Math.sqrt(w*w+k*k+M*M),T=Math.asin(M/=A),L=m(m(M)-1)t||m((x*z+b*O)/_-.5)>.3||l*h+s*p+c*g0&&16,a):Math.sqrt(t)},a}function Mr(e){this.stream=e}function Ar(e,t){return{point:t,sphere:function(){e.sphere()},lineStart:function(){e.lineStart()},lineEnd:function(){e.lineEnd()},polygonStart:function(){e.polygonStart()},polygonEnd:function(){e.polygonEnd()}}}function Tr(e){return Lr(function(){return e})()}function Lr(e){var n,r,a,i,o,l,s=kr(function(e,t){return[(e=n(e,t))[0]*c+i,o-e[1]*c]}),c=150,u=480,f=250,d=0,h=0,p=0,g=0,v=0,y=tr,x=z,b=null,_=null;function w(e){return[(e=a(e[0]*Ce,e[1]*Ce))[0]*c+i,o-e[1]*c]}function k(e){return(e=a.invert((e[0]-i)/c,(o-e[1])/c))&&[e[0]*Pe,e[1]*Pe]}function M(){a=Yn(r=zr(p,g,v),n);var e=n(d,h);return i=u-e[0]*c,o=f+e[1]*c,A()}function A(){return l&&(l.valid=!1,l=null),w}return w.stream=function(e){return l&&(l.valid=!1),(l=Sr(y(r,s(x(e))))).valid=!0,l},w.clipAngle=function(e){return arguments.length?(y=null==e?(b=e,tr):function(e){var t=Math.cos(e),n=t>0,r=m(t)>ke;return Qn(a,function(e){var t,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var h,p=[f,d],g=a(f,d),v=n?g?0:o(f,d):g?o(f+(f<0?Ae:-Ae),d):0;if(!t&&(c=s=g)&&e.lineStart(),g!==s&&(h=i(t,p),(jn(t,h)||jn(p,h))&&(p[0]+=ke,p[1]+=ke,g=a(p[0],p[1]))),g!==s)u=0,g?(e.lineStart(),h=i(p,t),e.point(h[0],h[1])):(h=i(t,p),e.point(h[0],h[1]),e.lineEnd()),t=h;else if(r&&t&&n^g){var y;v&l||!(y=i(p,t,!0))||(u=0,n?(e.lineStart(),e.point(y[0][0],y[0][1]),e.point(y[1][0],y[1][1]),e.lineEnd()):(e.point(y[1][0],y[1][1]),e.lineEnd(),e.lineStart(),e.point(y[0][0],y[0][1])))}!g||t&&jn(t,p)||e.point(p[0],p[1]),t=p,s=g,l=v},lineEnd:function(){s&&e.lineEnd(),t=null},clean:function(){return u|(c&&s)<<1}}},Rr(e,6*Ce),n?[0,-e]:[-Ae,e-Ae]);function a(e,n){return Math.cos(e)*Math.cos(n)>t}function i(e,n,r){var a=[1,0,0],i=En(On(e),On(n)),o=Dn(i,i),l=i[0],s=o-l*l;if(!s)return!r&&e;var c=t*o/s,u=-t*l/s,f=En(a,i),d=Nn(a,c);Rn(d,Nn(i,u));var h=f,p=Dn(d,h),g=Dn(h,h),v=p*p-g*(Dn(d,d)-1);if(!(v<0)){var y=Math.sqrt(v),x=Nn(h,(-p-y)/g);if(Rn(x,d),x=Fn(x),!r)return x;var b,_=e[0],w=n[0],k=e[1],M=n[1];w<_&&(b=_,_=w,w=b);var A=w-_,T=m(A-Ae)0^x[1]<(m(x[0]-_)Ae^(_<=x[0]&&x[0]<=w)){var L=Nn(h,(-p+y)/g);return Rn(L,d),[x,Fn(L)]}}}function o(t,r){var a=n?e:Ae-e,i=0;return t<-a?i|=1:t>a&&(i|=2),r<-a?i|=4:r>a&&(i|=8),i}}((b=+e)*Ce),A()):b},w.clipExtent=function(e){return arguments.length?(_=e,x=e?ar(e[0][0],e[0][1],e[1][0],e[1][1]):z,A()):_},w.scale=function(e){return arguments.length?(c=+e,M()):c},w.translate=function(e){return arguments.length?(u=+e[0],f=+e[1],M()):[u,f]},w.center=function(e){return arguments.length?(d=e[0]%360*Ce,h=e[1]%360*Ce,M()):[d*Pe,h*Pe]},w.rotate=function(e){return arguments.length?(p=e[0]%360*Ce,g=e[1]%360*Ce,v=e.length>2?e[2]%360*Ce:0,M()):[p*Pe,g*Pe,v*Pe]},t.rebind(w,s,"precision"),function(){return n=e.apply(this,arguments),w.invert=n.invert&&k,M()}}function Sr(e){return Ar(e,function(t,n){e.point(t*Ce,n*Ce)})}function Cr(e,t){return[e,t]}function Pr(e,t){return[e>Ae?e-Te:e<-Ae?e+Te:e,t]}function zr(e,t,n){return e?t||n?Yn(Dr(e),Er(t,n)):Dr(e):t||n?Er(t,n):Pr}function Or(e){return function(t,n){return[(t+=e)>Ae?t-Te:t<-Ae?t+Te:t,n]}}function Dr(e){var t=Or(e);return t.invert=Or(-e),t}function Er(e,t){var n=Math.cos(e),r=Math.sin(e),a=Math.cos(t),i=Math.sin(t);function o(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*n+l*r;return[Math.atan2(s*a-u*i,l*n-c*r),Ee(u*a+s*i)]}return o.invert=function(e,t){var o=Math.cos(t),l=Math.cos(e)*o,s=Math.sin(e)*o,c=Math.sin(t),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*n+u*r),Ee(u*n-l*r)]},o}function Rr(e,t){var n=Math.cos(e),r=Math.sin(e);return function(a,i,o,l){var s=o*t;null!=a?(a=Nr(n,a),i=Nr(n,i),(o>0?ai)&&(a+=o*Te)):(a=e+o*Te,i=e-.5*s);for(var c,u=a;o>0?u>i:u2?e[2]*Ce:0),t.invert=function(t){return(t=e.invert(t[0]*Ce,t[1]*Ce))[0]*=Pe,t[1]*=Pe,t},t},Pr.invert=Cr,t.geo.circle=function(){var e,t,n=[0,0],r=6;function a(){var e="function"==typeof n?n.apply(this,arguments):n,r=zr(-e[0]*Ce,-e[1]*Ce,0).invert,a=[];return t(null,null,1,{point:function(e,t){a.push(e=r(e,t)),e[0]*=Pe,e[1]*=Pe}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(e){return arguments.length?(n=e,a):n},a.angle=function(n){return arguments.length?(t=Rr((e=+n)*Ce,r*Ce),a):e},a.precision=function(n){return arguments.length?(t=Rr(e*Ce,(r=+n)*Ce),a):r},a.angle(90)},t.geo.distance=function(e,t){var n,r=(t[0]-e[0])*Ce,a=e[1]*Ce,i=t[1]*Ce,o=Math.sin(r),l=Math.cos(r),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((n=f*o)*n+(n=c*u-s*f*l)*n),s*u+c*f*l)},t.geo.graticule=function(){var e,n,r,a,i,o,l,s,c,u,f,d,h=10,p=h,g=90,v=360,y=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,r,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(d)).concat(t.range(Math.ceil(n/h)*h,e,h).filter(function(e){return m(e%g)>ke}).map(c)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(e){return m(e%v)>ke}).map(u))}return x.lines=function(){return b().map(function(e){return{type:"LineString",coordinates:e}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(r).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(e){return arguments.length?x.majorExtent(e).minorExtent(e):x.minorExtent()},x.majorExtent=function(e){return arguments.length?(a=+e[0][0],r=+e[1][0],s=+e[0][1],l=+e[1][1],a>r&&(e=a,a=r,r=e),s>l&&(e=s,s=l,l=e),x.precision(y)):[[a,s],[r,l]]},x.minorExtent=function(t){return arguments.length?(n=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],n>e&&(t=n,n=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(y)):[[n,o],[e,i]]},x.step=function(e){return arguments.length?x.majorStep(e).minorStep(e):x.minorStep()},x.majorStep=function(e){return arguments.length?(g=+e[0],v=+e[1],x):[g,v]},x.minorStep=function(e){return arguments.length?(h=+e[0],p=+e[1],x):[h,p]},x.precision=function(t){return arguments.length?(y=+t,c=Ir(o,i,90),u=Fr(n,e,y),f=Ir(s,l,90),d=Fr(a,r,y),x):y},x.majorExtent([[-180,-90+ke],[180,90-ke]]).minorExtent([[-180,-80-ke],[180,80+ke]])},t.geo.greatArc=function(){var e,n,r=jr,a=Br;function i(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||r.apply(this,arguments),n||a.apply(this,arguments))},i.source=function(t){return arguments.length?(r=t,e="function"==typeof t?null:t,i):r},i.target=function(e){return arguments.length?(a=e,n="function"==typeof e?null:e,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(e,t){return n=e[0]*Ce,r=e[1]*Ce,a=t[0]*Ce,i=t[1]*Ce,o=Math.cos(r),l=Math.sin(r),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(n),f=o*Math.sin(n),d=s*Math.cos(a),h=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ne(i-r)+o*s*Ne(a-n))),g=1/Math.sin(p),(v=p?function(e){var t=Math.sin(e*=p)*g,n=Math.sin(p-e)*g,r=n*u+t*d,a=n*f+t*h,i=n*l+t*c;return[Math.atan2(a,r)*Pe,Math.atan2(i,Math.sqrt(r*r+a*a))*Pe]}:function(){return[n*Pe,r*Pe]}).distance=p,v;var n,r,a,i,o,l,s,c,u,f,d,h,p,g,v},t.geo.length=function(e){return yr=0,t.geo.stream(e,qr),yr};var qr={sphere:R,point:R,lineStart:function(){var e,t,n;function r(r,a){var i=Math.sin(a*=Ce),o=Math.cos(a),l=m((r*=Ce)-e),s=Math.cos(l);yr+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=n*i-t*o*s)*l),t*i+n*o*s),e=r,t=i,n=o}qr.point=function(a,i){e=a*Ce,t=Math.sin(i*=Ce),n=Math.cos(i),qr.point=r},qr.lineEnd=function(){qr.point=qr.lineEnd=R}},lineEnd:R,polygonStart:R,polygonEnd:R};function Hr(e,t){function n(t,n){var r=Math.cos(t),a=Math.cos(n),i=e(r*a);return[i*a*Math.sin(t),i*Math.sin(n)]}return n.invert=function(e,n){var r=Math.sqrt(e*e+n*n),a=t(r),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(e*i,r*o),Math.asin(r&&n*i/r)]},n}var Vr=Hr(function(e){return Math.sqrt(2/(1+e))},function(e){return 2*Math.asin(e/2)});(t.geo.azimuthalEqualArea=function(){return Tr(Vr)}).raw=Vr;var Ur=Hr(function(e){var t=Math.acos(e);return t&&t/Math.sin(t)},z);function Gr(e,t){var n=Math.cos(e),r=function(e){return Math.tan(Ae/4+e/2)},a=e===t?Math.sin(e):Math.log(n/Math.cos(t))/Math.log(r(t)/r(e)),i=n*Math.pow(r(e),a)/a;if(!a)return Zr;function o(e,t){i>0?t<-Se+ke&&(t=-Se+ke):t>Se-ke&&(t=Se-ke);var n=i/Math.pow(r(t),a);return[n*Math.sin(a*e),i-n*Math.cos(a*e)]}return o.invert=function(e,t){var n=i-t,r=ze(a)*Math.sqrt(e*e+n*n);return[Math.atan2(e,n)/a,2*Math.atan(Math.pow(i/r,1/a))-Se]},o}function Yr(e,t){var n=Math.cos(e),r=e===t?Math.sin(e):(n-Math.cos(t))/(t-e),a=n/r+e;if(m(r)1&&Oe(e[n[r-2]],e[n[r-1]],e[a])<=0;)--r;n[r++]=a}return n.slice(0,r)}function na(e,t){return e[0]-t[0]||e[1]-t[1]}(t.geo.stereographic=function(){return Tr(Qr)}).raw=Qr,$r.invert=function(e,t){return[-t,2*Math.atan(Math.exp(e))-Se]},(t.geo.transverseMercator=function(){var e=Wr($r),t=e.center,n=e.rotate;return e.center=function(e){return e?t([-e[1],e[0]]):[(e=t())[1],-e[0]]},e.rotate=function(e){return e?n([e[0],e[1],e.length>2?e[2]+90:90]):[(e=n())[0],e[1],e[2]-90]},n([0,0,90])}).raw=$r,t.geom={},t.geom.hull=function(e){var t=Kr,n=ea;if(arguments.length)return r(e);function r(e){if(e.length<3)return[];var r,a=vt(t),i=vt(n),o=e.length,l=[],s=[];for(r=0;r=0;--r)h.push(e[l[c[r]][2]]);for(r=+f;rke)l=l.L;else{if(!((a=i-xa(l,o))>ke)){r>-ke?(t=l.P,n=l):a>-ke?(t=l,n=l.N):t=n=l;break}if(!l.R){t=l;break}l=l.R}var s=pa(e);if(ca.insert(t,s),t||n){if(t===n)return ka(t),n=pa(t.site),ca.insert(s,n),s.edge=n.edge=Ta(t.site,s.site),wa(t),void wa(n);if(n){ka(t),ka(n);var c=t.site,u=c.x,f=c.y,d=e.x-u,h=e.y-f,p=n.site,g=p.x-u,v=p.y-f,y=2*(d*v-h*g),m=d*d+h*h,x=g*g+v*v,b={x:(v*m-h*x)/y+u,y:(d*x-g*m)/y+f};La(n.edge,c,p,b),s.edge=Ta(c,e,null,b),n.edge=Ta(e,p,null,b),wa(t),wa(n)}else s.edge=Ta(t.site,s.site)}}function ma(e,t){var n=e.site,r=n.x,a=n.y,i=a-t;if(!i)return r;var o=e.P;if(!o)return-1/0;var l=(n=o.site).x,s=n.y,c=s-t;if(!c)return l;var u=l-r,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+r:(r+l)/2}function xa(e,t){var n=e.N;if(n)return ma(n,t);var r=e.site;return r.y===t?r.x:1/0}function ba(e){this.site=e,this.edges=[]}function _a(e,t){return t.angle-e.angle}function wa(e){var t=e.P,n=e.N;if(t&&n){var r=t.site,a=e.site,i=n.site;if(r!==i){var o=a.x,l=a.y,s=r.x-o,c=r.y-l,u=i.x-o,f=2*(s*(v=i.y-l)-c*u);if(!(f>=-Me)){var d=s*s+c*c,h=u*u+v*v,p=(v*d-c*h)/f,g=(s*h-u*d)/f,v=g+l,y=ha.pop()||new function(){Pa(this),this.x=this.y=this.arc=this.site=this.cy=null};y.arc=e,y.site=a,y.x=p+o,y.y=v+Math.sqrt(p*p+g*g),y.cy=v,e.circle=y;for(var m=null,x=fa._;x;)if(y.y=l)return;if(d>p){if(i){if(i.y>=c)return}else i={x:v,y:s};n={x:v,y:c}}else{if(i){if(i.y1)if(d>p){if(i){if(i.y>=c)return}else i={x:(s-a)/r,y:s};n={x:(c-a)/r,y:c}}else{if(i){if(i.y=l)return}else i={x:o,y:r*o+a};n={x:l,y:r*l+a}}else{if(i){if(i.xke||m(a-n)>ke)&&(l.splice(o,0,new Sa((y=i.site,x=u,b=m(r-f)ke?{x:f,y:m(t-f)ke?{x:m(n-p)ke?{x:d,y:m(t-d)ke?{x:m(n-h)=n&&c.x<=a&&c.y>=r&&c.y<=o?[[n,o],[a,o],[a,r],[n,r]]:[]).point=e[l]}),t}function l(e){return e.map(function(e,t){return{x:Math.round(r(e,t)/ke)*ke,y:Math.round(a(e,t)/ke)*ke,i:t}})}return o.links=function(e){return Ea(l(e)).edges.filter(function(e){return e.l&&e.r}).map(function(t){return{source:e[t.l.i],target:e[t.r.i]}})},o.triangles=function(e){var t=[];return Ea(l(e)).cells.forEach(function(n,r){for(var a,i,o,l,s=n.site,c=n.edges.sort(_a),u=-1,f=c.length,d=c[f-1].edge,h=d.l===s?d.r:d.l;++ui&&(a=t.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(n=n[0])===(r=r[0])?l[o]?l[o]+=r:l[++o]=r:(l[++o]=null,s.push({i:o,x:qa(n,r)})),i=Ua.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),c.push(s.x),u.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),c.push(b),u.push(_)}var w=g-h,k=v-p;function M(e,t,n,r,a,i,o,l){if(!isNaN(n)&&!isNaN(r))if(e.leaf){var s=e.x,c=e.y;if(null!=s)if(m(s-n)+m(c-r)<.01)A(e,t,n,r,a,i,o,l);else{var u=e.point;e.x=e.y=e.point=null,A(e,u,s,c,a,i,o,l),A(e,t,n,r,a,i,o,l)}else e.x=n,e.y=r,e.point=t}else A(e,t,n,r,a,i,o,l)}function A(e,t,n,r,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=n>=s,f=r>=c,d=f<<1|u;e.leaf=!1,e=e.nodes[d]||(e.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}}),u?a=s:o=s,f?i=c:l=c,M(e,t,n,r,a,i,o,l)}w>k?v=p+w:g=h+k;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(e){M(T,e,+y(e,++f),+x(e,f),h,p,g,v)}};if(T.visit=function(e){!function e(t,n,r,a,i,o){if(!t(n,r,a,i,o)){var l=.5*(r+i),s=.5*(a+o),c=n.nodes;c[0]&&e(t,c[0],r,a,l,s),c[1]&&e(t,c[1],l,a,i,s),c[2]&&e(t,c[2],r,s,l,o),c[3]&&e(t,c[3],l,s,i,o)}}(e,T,h,p,g,v)},T.find=function(e){return function(e,t,n,r,a,i,o){var l,s=1/0;return function e(c,u,f,d,h){if(!(u>i||f>o||d=_)<<1|t>=b,k=w+4;w=0&&!(r=t.interpolators[a](e,n)););return r}function Ya(e,t){var n,r=[],a=[],i=e.length,o=t.length,l=Math.min(e.length,t.length);for(n=0;n=1)return 1;var t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function ti(e){return 1-Math.cos(e*Se)}function ni(e){return Math.pow(2,10*(e-1))}function ri(e){return 1-Math.sqrt(1-e*e)}function ai(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}function ii(e,t){return t-=e,function(n){return Math.round(e+t*n)}}function oi(e){var t,n,r,a=[e.a,e.b],i=[e.c,e.d],o=si(a),l=li(a,i),s=si(((t=i)[0]+=(r=-l)*(n=a)[0],t[1]+=r*n[1],t))||0;a[0]*i[1]=0?e.slice(0,r):e,i=r>=0?e.slice(r+1):"in";return a=Za.get(a)||Xa,i=Wa.get(i)||z,t=i(a.apply(null,n.call(arguments,1))),function(e){return e<=0?0:e>=1?1:t(e)}},t.interpolateHcl=function(e,n){e=t.hcl(e),n=t.hcl(n);var r=e.h,a=e.c,i=e.l,o=n.h-r,l=n.c-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.c:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Xe(r+o*e,a+l*e,i+s*e)+""}},t.interpolateHsl=function(e,n){e=t.hsl(e),n=t.hsl(n);var r=e.h,a=e.s,i=e.l,o=n.h-r,l=n.s-a,s=n.l-i;isNaN(l)&&(l=0,a=isNaN(a)?n.s:a);isNaN(o)?(o=0,r=isNaN(r)?n.h:r):o>180?o-=360:o<-180&&(o+=360);return function(e){return Ue(r+o*e,a+l*e,i+s*e)+""}},t.interpolateLab=function(e,n){e=t.lab(e),n=t.lab(n);var r=e.l,a=e.a,i=e.b,o=n.l-r,l=n.a-a,s=n.b-i;return function(e){return et(r+o*e,a+l*e,i+s*e)+""}},t.interpolateRound=ii,t.transform=function(e){var n=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(e){if(null!=e){n.setAttribute("transform",e);var t=n.transform.baseVal.consolidate()}return new oi(t?t.matrix:ci)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ci={a:1,b:0,c:0,d:1,e:0,f:0};function ui(e){return e.length?e.pop()+",":""}function fi(e,n){var r=[],a=[];return e=t.transform(e),n=t.transform(n),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push("translate(",null,",",null,")");r.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else(t[0]||t[1])&&n.push("translate("+t+")")}(e.translate,n.translate,r,a),function(e,t,n,r){e!==t?(e-t>180?t+=360:t-e>180&&(e+=360),r.push({i:n.push(ui(n)+"rotate(",null,")")-2,x:qa(e,t)})):t&&n.push(ui(n)+"rotate("+t+")")}(e.rotate,n.rotate,r,a),function(e,t,n,r){e!==t?r.push({i:n.push(ui(n)+"skewX(",null,")")-2,x:qa(e,t)}):t&&n.push(ui(n)+"skewX("+t+")")}(e.skew,n.skew,r,a),function(e,t,n,r){if(e[0]!==t[0]||e[1]!==t[1]){var a=n.push(ui(n)+"scale(",null,",",null,")");r.push({i:a-4,x:qa(e[0],t[0])},{i:a-2,x:qa(e[1],t[1])})}else 1===t[0]&&1===t[1]||n.push(ui(n)+"scale("+t+")")}(e.scale,n.scale,r,a),e=n=null,function(e){for(var t,n=-1,i=a.length;++n0?r=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:r=0})):t>0&&(s.start({type:"start",alpha:r=t}),e=Mt(l.tick)),l):r},l.start=function(){var e,t,n,r=y.length,s=m.length,u=c[0],p=c[1];for(e=0;e=0;)n.push(a[r])}function Ai(e,t){for(var n=[e],r=[];null!=(e=n.pop());)if(r.push(e),(i=e.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;n&&(i.value=0),i.children=c}else n&&(i.value=+n.call(r,i,i.depth)||0),delete i.children;return Ai(a,function(t){var r,a;e&&(r=t.children)&&r.sort(e),n&&(a=t.parent)&&(a.value+=t.value)}),l}return r.sort=function(t){return arguments.length?(e=t,r):e},r.children=function(e){return arguments.length?(t=e,r):t},r.value=function(e){return arguments.length?(n=e,r):n},r.revalue=function(e){return n&&(Mi(e,function(e){e.children&&(e.value=0)}),Ai(e,function(e){var t;e.children||(e.value=+n.call(r,e,e.depth)||0),(t=e.parent)&&(t.value+=e.value)})),e},r},t.layout.partition=function(){var e=t.layout.hierarchy(),n=[1,1];function r(t,r){var a=e.call(this,t,r);return function e(t,n,r,a){var i=t.children;if(t.x=n,t.y=t.depth*a,t.dx=r,t.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(r=t.value?r/t.value:0;++cl&&(l=r),o.push(r)}for(n=0;na&&(r=n,a=t);return r}function ji(e){return e.reduce(Bi,0)}function Bi(e,t){return e+t[1]}function qi(e,t){return Hi(e,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Hi(e,t){for(var n=-1,r=+e[0],a=(e[1]-r)/t,i=[];++n<=t;)i[n]=a*n+r;return i}function Vi(e){return[t.min(e),t.max(e)]}function Ui(e,t){return e.value-t.value}function Gi(e,t){var n=e._pack_next;e._pack_next=t,t._pack_prev=e,t._pack_next=n,n._pack_prev=t}function Yi(e,t){e._pack_next=t,t._pack_prev=e}function Xi(e,t){var n=t.x-e.x,r=t.y-e.y,a=e.r+t.r;return.999*a*a>n*n+r*r}function Zi(e){if((t=e.children)&&(s=t.length)){var t,n,r,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(t.forEach(Wi),(n=t[0]).x=-n.r,n.y=0,x(n),s>1&&((r=t[1]).x=r.r,r.y=0,x(r),s>2))for(Qi(n,r,a=t[2]),x(a),Gi(n,a),n._pack_prev=a,Gi(a,r),r=n._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,p)-1]).y+=g,l.push(i[o]));return c}return i.value=function(e){return arguments.length?(n=e,i):n},i.range=function(e){return arguments.length?(r=vt(e),i):r},i.bins=function(e){return arguments.length?(a="number"==typeof e?function(t){return Hi(t,e)}:vt(e),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,n=t.layout.hierarchy().sort(Ui),r=0,a=[1,1];function i(t,i){var o=n.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ai(l,function(e){e.r=+u(e.value)}),Ai(l,Zi),r){var f=r*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Ai(l,function(e){e.r+=f}),Ai(l,Zi),Ai(l,function(e){e.r-=f})}return function e(t,n,r,a){var i=t.children;t.x=n+=a*t.x;t.y=r+=a*t.y;t.r*=a;if(i)for(var o=-1,l=i.length;++oh.x&&(h=e),e.depth>p.depth&&(p=e)});var g=n(d,h)/2-d.x,v=r[0]/(h.x+n(h,d)/2+g),y=r[1]/(p.depth||1);Mi(u,function(e){e.x=(e.x+g)*v,e.y=e.depth*y})}return c}function o(e){var t=e.children,r=e.parent.children,a=e.i?r[e.i-1]:null;if(t.length){!function(e){var t,n=0,r=0,a=e.children,i=a.length;for(;--i>=0;)(t=a[i]).z+=n,t.m+=n,n+=t.s+(r+=t.c)}(e);var i=(t[0].z+t[t.length-1].z)/2;a?(e.z=a.z+n(e._,a._),e.m=e.z-i):e.z=i}else a&&(e.z=a.z+n(e._,a._));e.parent.A=function(e,t,r){if(t){for(var a,i=e,o=e,l=t,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=eo(l),i=Ki(i),l&&i;)s=Ki(s),(o=eo(o)).a=e,(a=l.z+f-i.z-c+n(l._,i._))>0&&(to(no(l,e,r),e,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!eo(o)&&(o.t=l,o.m+=f-u),i&&!Ki(s)&&(s.t=i,s.m+=c-d,r=e)}return r}(e,a,e.parent.A||r[0])}function l(e){e._.x=e.z+e.parent.m,e.m+=e.parent.m}function s(e){e.x*=r[0],e.y=e.depth*r[1]}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e)?s:null,i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null==(r=e)?null:s,i):a?r:null},ki(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),n=$i,r=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Ai(c,function(e){var r=e.children;r&&r.length?(e.x=function(e){return e.reduce(function(e,t){return e+t.x},0)/e.length}(r),e.y=function(e){return 1+t.max(e,function(e){return e.y})}(r)):(e.x=l?u+=n(e,l):0,e.y=0,l=e)});var f=function e(t){var n=t.children;return n&&n.length?e(n[0]):t}(c),d=function e(t){var n,r=t.children;return r&&(n=r.length)?e(r[n-1]):t}(c),h=f.x-n(f,d)/2,p=d.x+n(d,f)/2;return Ai(c,a?function(e){e.x=(e.x-c.x)*r[0],e.y=(c.y-e.y)*r[1]}:function(e){e.x=(e.x-h)/(p-h)*r[0],e.y=(1-(c.y?e.y/c.y:1))*r[1]}),s}return i.separation=function(e){return arguments.length?(n=e,i):n},i.size=function(e){return arguments.length?(a=null==(r=e),i):a?null:r},i.nodeSize=function(e){return arguments.length?(a=null!=(r=e),i):a?r:null},ki(i,e)},t.layout.treemap=function(){var e,n=t.layout.hierarchy(),r=Math.round,a=[1,1],i=null,o=ro,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(e,t){for(var n,r,a=-1,i=e.length;++a0;)l.push(n=c[a-1]),l.area+=n.area,"squarify"!==s||(r=h(l,g))<=d?(c.pop(),d=r):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),t.forEach(f)}}function d(e){var t=e.children;if(t&&t.length){var n,r=o(e),a=t.slice(),i=[];for(u(a,r.dx*r.dy/e.value),i.area=0;n=a.pop();)i.push(n),i.area+=n.area,null!=n.z&&(p(i,n.z?r.dx:r.dy,r,!a.length),i.length=i.area=0);t.forEach(d)}}function h(e,t){for(var n,r=e.area,a=0,i=1/0,o=-1,l=e.length;++oa&&(a=n));return t*=t,(r*=r)?Math.max(t*a*c/r,r/(t*i*c)):1/0}function p(e,t,n,a){var i,o=-1,l=e.length,s=n.x,c=n.y,u=t?r(e.area/t):0;if(t==n.dx){for((a||u>n.dy)&&(u=n.dy);++on.dx)&&(u=n.dx);++o1);return e+t*n*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var n=t.random.irwinHall(e);return function(){return n()/e}},irwinHall:function(e){return function(){for(var t=0,n=0;n2?fo:lo,l=a?hi:di;return i=e(t,n,l,r),o=e(n,t,l,Ga),s}function s(e){return i(e)}s.invert=function(e){return o(e)};s.domain=function(e){return arguments.length?(t=e.map(Number),l()):t};s.range=function(e){return arguments.length?(n=e,l()):n};s.rangeRound=function(e){return s.range(e).interpolate(ii)};s.clamp=function(e){return arguments.length?(a=e,l()):a};s.interpolate=function(e){return arguments.length?(r=e,l()):r};s.ticks=function(e){return vo(t,e)};s.tickFormat=function(e,n){return yo(t,e,n)};s.nice=function(e){return po(t,e),l()};s.copy=function(){return e(t,n,r,a)};return l()}([0,1],[0,1],Ga,!1)};var mo={s:1,g:1,p:1,r:1,e:1};function xo(e){return-Math.floor(Math.log(e)/Math.LN10+.01)}t.scale.log=function(){return function e(n,r,a,i){function o(e){return(a?Math.log(e<0?0:e):-Math.log(e>0?0:-e))/Math.log(r)}function l(e){return a?Math.pow(r,e):-Math.pow(r,-e)}function s(e){return n(o(e))}s.invert=function(e){return l(n.invert(e))};s.domain=function(e){return arguments.length?(a=e[0]>=0,n.domain((i=e.map(Number)).map(o)),s):i};s.base=function(e){return arguments.length?(r=+e,n.domain(i.map(o)),s):r};s.nice=function(){var e=so(i.map(o),a?Math:_o);return n.domain(e),i=e.map(l),s};s.ticks=function(){var e=io(i),t=[],n=e[0],s=e[1],c=Math.floor(o(n)),u=Math.ceil(o(s)),f=r%1?2:r;if(isFinite(u-c)){if(a){for(;c0;d--)t.push(l(c)*d);for(c=0;t[c]s;u--);t=t.slice(c,u)}return t};s.tickFormat=function(e,n){if(!arguments.length)return bo;arguments.length<2?n=bo:"function"!=typeof n&&(n=t.format(n));var a=Math.max(1,r*e/s.ticks().length);return function(e){var t=e/l(Math.round(o(e)));return t*r0?a[e-1]:n[0],ef?0:1;if(c=Le)return s(c,h)+(l?s(l,1-h):"")+"Z";var p,g,v,y,m,x,b,_,w,k,M,A,T=0,L=0,S=[];if((y=(+o.apply(this,arguments)||0)/2)&&(v=r===So?Math.sqrt(l*l+c*c):+r.apply(this,arguments),h||(L*=-1),c&&(L=Ee(v/c*Math.sin(y))),l&&(T=Ee(v/l*Math.sin(y)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var C=Math.abs(f-u-2*L)<=Ae?0:1;if(L&&Eo(m,x,b,_)===h^C){var P=(u+f)/2;m=c*Math.cos(P),x=c*Math.sin(P),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-T),k=l*Math.sin(f-T),M=l*Math.cos(u+T),A=l*Math.sin(u+T);var z=Math.abs(u-f+2*T)<=Ae?0:1;if(T&&Eo(w,k,M,A)===1-h^z){var O=(u+f)/2;w=l*Math.cos(O),k=l*Math.sin(O),M=A=null}}else w=k=0;if(d>ke&&(p=Math.min(Math.abs(c-l)/2,+n.apply(this,arguments)))>.001){g=l0?0:1}function Ro(e,t,n,r,a){var i=e[0]-t[0],o=e[1]-t[1],l=(a?r:-r)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=e[0]+s,f=e[1]+c,d=t[0]+s,h=t[1]+c,p=(u+d)/2,g=(f+h)/2,v=d-u,y=h-f,m=v*v+y*y,x=n-r,b=u*h-d*f,_=(y<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*y-v*_)/m,k=(-b*v-y*_)/m,M=(b*y+v*_)/m,A=(-b*v+y*_)/m,T=w-p,L=k-g,S=M-p,C=A-g;return T*T+L*L>S*S+C*C&&(w=M,k=A),[[w-s,k-c],[w*n/x,k*n/x]]}function No(e){var t=Kr,n=ea,r=Xn,a=Fo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=vt(t),h=vt(n);function p(){s.push("M",a(e(c),o))}for(;++u1&&a.push("H",r[0]);return a.join("")},"step-before":Bo,"step-after":qo,basis:Uo,"basis-open":function(e){if(e.length<4)return Fo(e);var t,n=[],r=-1,a=e.length,i=[0],o=[0];for(;++r<3;)t=e[r],i.push(t[0]),o.push(t[1]);n.push(Go(Zo,i)+","+Go(Zo,o)),--r;for(;++r9&&(a=3*t/Math.sqrt(a),o[l]=a*n,o[l+1]=a*r));l=-1;for(;++l<=s;)a=(e[Math.min(s,l+1)][0]-e[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(e))}});function Fo(e){return e.length>1?e.join("L"):e+"Z"}function jo(e){return e.join("L")+"Z"}function Bo(e){for(var t=0,n=e.length,r=e[0],a=[r[0],",",r[1]];++t1){l=t[1],i=e[s],s++,r+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;cAe)+",1 "+t}function s(e,t,n,r){return"Q 0,0 "+r}return i.radius=function(e){return arguments.length?(n=vt(e),i):n},i.source=function(t){return arguments.length?(e=vt(t),i):e},i.target=function(e){return arguments.length?(t=vt(e),i):t},i.startAngle=function(e){return arguments.length?(r=vt(e),i):r},i.endAngle=function(e){return arguments.length?(a=vt(e),i):a},i},t.svg.diagonal=function(){var e=jr,t=Br,n=el;function r(r,a){var i=e.call(this,r,a),o=t.call(this,r,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(n))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return r.source=function(t){return arguments.length?(e=vt(t),r):e},r.target=function(e){return arguments.length?(t=vt(e),r):t},r.projection=function(e){return arguments.length?(n=e,r):n},r},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),n=el,r=e.projection;return e.projection=function(e){return arguments.length?r(function(e){return function(){var t=e.apply(this,arguments),n=t[0],r=t[1]-Se;return[n*Math.cos(r),n*Math.sin(r)]}}(n=e)):n},e},t.svg.symbol=function(){var e=nl,t=tl;function n(n,r){return(al.get(e.call(this,n,r))||rl)(t.call(this,n,r))}return n.type=function(t){return arguments.length?(e=vt(t),n):e},n.size=function(e){return arguments.length?(t=vt(e),n):t},n};var al=t.map({circle:rl,cross:function(e){var t=Math.sqrt(e/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(e){var t=Math.sqrt(e/(2*ol)),n=t*ol;return"M0,"+-t+"L"+n+",0 0,"+t+" "+-n+",0Z"},square:function(e){var t=Math.sqrt(e)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+n+"L"+t+","+-n+" "+-t+","+-n+"Z"},"triangle-up":function(e){var t=Math.sqrt(e/il),n=t*il/2;return"M0,"+-n+"L"+t+","+n+" "+-t+","+n+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*Ce);X.transition=function(e){for(var t,n,r=ul||++hl,a=vl(e),i=[],o=fl||{time:Date.now(),ease:ei,delay:0,duration:250},l=-1,s=this.length;++l0;)c[--d].call(e,o);if(i>=1)return f.event&&f.event.end.call(e,e.__data__,t),--u.count?delete u[r]:delete e[n],1}f||(i=a.time,o=Mt(function(e){var t=f.delay;if(o.t=t+i,t<=e)return d(e-t);o.c=d},0,i),f=u[r]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:t},a=null,++u.count)}dl.call=X.call,dl.empty=X.empty,dl.node=X.node,dl.size=X.size,t.transition=function(e,n){return e&&e.transition?ul?e.transition(n):e:t.selection().transition(e)},t.transition.prototype=dl,dl.select=function(e){var t,n,r,a=this.id,i=this.namespace,o=[];e=Z(e);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(e){e.select(".extent").attr("y",s[0]),e.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,y=this,m=t.select(t.event.target),x=r.of(y,arguments),b=t.select(y),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),A=xe(y),T=t.mouse(y),L=t.select(o(y)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,T[0]-=l[1],T[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(T[0]+=l[1],T[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",P).on("touchend.brush",O):L.on("mousemove.brush",P).on("mouseup.brush",O),b.interrupt().selectAll("*").interrupt(),M)T[0]=l[0]-T[0],T[1]=s[0]-T[1];else if(_){var S=+/w$/.test(_),C=+/^n/.test(_);v=[l[1-S]-T[0],s[1-C]-T[1]],T[0]=l[S],T[1]=s[C]}else t.event.altKey&&(f=T.slice());function P(){var e=t.mouse(y),n=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),T[0]=l[+(e[0]1?{floor:function(t){for(;l(t=e.floor(t));)t=Cl(t-1);return t},ceil:function(t){for(;l(t=e.ceil(t));)t=Cl(+t+1);return t}}:e))},a.ticks=function(e,t){var n=io(a.domain()),r=null==e?i(n,10):"number"==typeof e?i(n,e):!e.range&&[{range:e},t];return r&&(e=r[0],t=r[1]),e.range(n[0],Cl(+n[1]+1),t<1?1:t)},a.tickFormat=function(){return r},a.copy=function(){return Sl(e.copy(),n,r)},ho(a,e)}function Cl(e){return new Date(e)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ll:Tl,Ll.parse=function(e){var t=new Date(e);return isNaN(t)?null:t},Ll.toString=Tl.toString,Dt.second=It(function(e){return new Et(1e3*Math.floor(e/1e3))},function(e,t){e.setTime(e.getTime()+1e3*Math.floor(t))},function(e){return e.getSeconds()}),Dt.seconds=Dt.second.range,Dt.seconds.utc=Dt.second.utc.range,Dt.minute=It(function(e){return new Et(6e4*Math.floor(e/6e4))},function(e,t){e.setTime(e.getTime()+6e4*Math.floor(t))},function(e){return e.getMinutes()}),Dt.minutes=Dt.minute.range,Dt.minutes.utc=Dt.minute.utc.range,Dt.hour=It(function(e){var t=e.getTimezoneOffset()/60;return new Et(36e5*(Math.floor(e/36e5-t)+t))},function(e,t){e.setTime(e.getTime()+36e5*Math.floor(t))},function(e){return e.getHours()}),Dt.hours=Dt.hour.range,Dt.hours.utc=Dt.hour.utc.range,Dt.month=It(function(e){return(e=Dt.day(e)).setDate(1),e},function(e,t){e.setMonth(e.getMonth()+t)},function(e){return e.getMonth()}),Dt.months=Dt.month.range,Dt.months.utc=Dt.month.utc.range;var Pl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],zl=[[Dt.second,1],[Dt.second,5],[Dt.second,15],[Dt.second,30],[Dt.minute,1],[Dt.minute,5],[Dt.minute,15],[Dt.minute,30],[Dt.hour,1],[Dt.hour,3],[Dt.hour,6],[Dt.hour,12],[Dt.day,1],[Dt.day,2],[Dt.week,1],[Dt.month,1],[Dt.month,3],[Dt.year,1]],Ol=Ml.multi([[".%L",function(e){return e.getMilliseconds()}],[":%S",function(e){return e.getSeconds()}],["%I:%M",function(e){return e.getMinutes()}],["%I %p",function(e){return e.getHours()}],["%a %d",function(e){return e.getDay()&&1!=e.getDate()}],["%b %d",function(e){return 1!=e.getDate()}],["%B",function(e){return e.getMonth()}],["%Y",Xn]]),Dl={range:function(e,n,r){return t.range(Math.ceil(e/r)*r,+n,r).map(Cl)},floor:z,ceil:z};zl.year=Dt.year,Dt.scale=function(){return Sl(t.scale.linear(),zl,Ol)};var El=zl.map(function(e){return[e[0].utc,e[1]]}),Rl=Al.multi([[".%L",function(e){return e.getUTCMilliseconds()}],[":%S",function(e){return e.getUTCSeconds()}],["%I:%M",function(e){return e.getUTCMinutes()}],["%I %p",function(e){return e.getUTCHours()}],["%a %d",function(e){return e.getUTCDay()&&1!=e.getUTCDate()}],["%b %d",function(e){return 1!=e.getUTCDate()}],["%B",function(e){return e.getUTCMonth()}],["%Y",Xn]]);function Nl(e){return JSON.parse(e.responseText)}function Il(e){var t=a.createRange();return t.selectNode(a.body),t.createContextualFragment(e.responseText)}El.year=Dt.year.utc,Dt.scale.utc=function(){return Sl(t.scale.linear(),El,Rl)},t.text=yt(function(e){return e.responseText}),t.json=function(e,t){return mt(e,"application/json",Nl,t)},t.html=function(e,t){return mt(e,"text/html",Il,t)},t.xml=yt(function(e){return e.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var t=function(e){var t=typeof e;if("string"===t){var n=e;if(0===(e=+e)&&function(e){for(var t,n=e.length,r=0;r13)&&32!==t&&133!==t&&160!==t&&5760!==t&&6158!==t&&(t<8192||t>8205)&&8232!==t&&8233!==t&&8239!==t&&8287!==t&&8288!==t&&12288!==t&&65279!==t)return!1;return!0}(n))return!1}else if("number"!==t)return!1;return e-e<1},n={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},r={},a=Math.PI;r.deg2rad=function(e){return e/180*a},r.rad2deg=function(e){return e/a*180},r.wrap360=function(e){var t=e%360;return t<0?t+360:t},r.wrap180=function(e){return Math.abs(e)>180&&(e-=360*Math.round(e/360)),e};var i=n.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,l={exports:{}};!function(e){var t=/^\s+/,n=/\s+$/,r=0,a=e.round,i=e.min,o=e.max,s=e.random;function c(l,s){if(l=l||"",s=s||{},l instanceof c)return l;if(!(this instanceof c))return new c(l,s);var u=function(r){var a={r:0,g:0,b:0},l=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof r&&(r=function(e){e=e.replace(t,"").replace(n,"").toLowerCase();var r,a=!1;if(L[e])e=L[e],a=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(r=B.rgb.exec(e))return{r:r[1],g:r[2],b:r[3]};if(r=B.rgba.exec(e))return{r:r[1],g:r[2],b:r[3],a:r[4]};if(r=B.hsl.exec(e))return{h:r[1],s:r[2],l:r[3]};if(r=B.hsla.exec(e))return{h:r[1],s:r[2],l:r[3],a:r[4]};if(r=B.hsv.exec(e))return{h:r[1],s:r[2],v:r[3]};if(r=B.hsva.exec(e))return{h:r[1],s:r[2],v:r[3],a:r[4]};if(r=B.hex8.exec(e))return{r:O(r[1]),g:O(r[2]),b:O(r[3]),a:N(r[4]),format:a?"name":"hex8"};if(r=B.hex6.exec(e))return{r:O(r[1]),g:O(r[2]),b:O(r[3]),format:a?"name":"hex"};if(r=B.hex4.exec(e))return{r:O(r[1]+""+r[1]),g:O(r[2]+""+r[2]),b:O(r[3]+""+r[3]),a:N(r[4]+""+r[4]),format:a?"name":"hex8"};if(r=B.hex3.exec(e))return{r:O(r[1]+""+r[1]),g:O(r[2]+""+r[2]),b:O(r[3]+""+r[3]),format:a?"name":"hex"};return!1}(r));"object"==typeof r&&(q(r.r)&&q(r.g)&&q(r.b)?(h=r.r,p=r.g,g=r.b,a={r:255*P(h,255),g:255*P(p,255),b:255*P(g,255)},f=!0,d="%"===String(r.r).substr(-1)?"prgb":"rgb"):q(r.h)&&q(r.s)&&q(r.v)?(s=E(r.s),c=E(r.v),a=function(t,n,r){t=6*P(t,360),n=P(n,100),r=P(r,100);var a=e.floor(t),i=t-a,o=r*(1-n),l=r*(1-i*n),s=r*(1-(1-i)*n),c=a%6;return{r:255*[r,l,o,o,s,r][c],g:255*[s,r,r,l,o,o][c],b:255*[o,o,s,r,r,l][c]}}(r.h,s,c),f=!0,d="hsv"):q(r.h)&&q(r.s)&&q(r.l)&&(s=E(r.s),u=E(r.l),a=function(e,t,n){var r,a,i;function o(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=P(e,360),t=P(t,100),n=P(n,100),0===t)r=a=i=n;else{var l=n<.5?n*(1+t):n+t-n*t,s=2*n-l;r=o(s,l,e+1/3),a=o(s,l,e),i=o(s,l,e-1/3)}return{r:255*r,g:255*a,b:255*i}}(r.h,s,u),f=!0,d="hsl"),r.hasOwnProperty("a")&&(l=r.a));var h,p,g;return l=C(l),{ok:f,format:r.format||d,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=a(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=u.ok,this._tc_id=r++}function u(e,t,n){e=P(e,255),t=P(t,255),n=P(n,255);var r,a,l=o(e,t,n),s=i(e,t,n),c=(l+s)/2;if(l==s)r=a=0;else{var u=l-s;switch(a=c>.5?u/(2-l-s):u/(l+s),l){case e:r=(t-n)/u+(t>1)+720)%360;--t;)r.h=(r.h+a)%360,i.push(c(r));return i}function T(e,t){t=t||6;for(var n=c(e).toHsv(),r=n.h,a=n.s,i=n.v,o=[],l=1/t;t--;)o.push(c({h:r,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var t,n,r,a=this.toRgb();return t=a.r/255,n=a.g/255,r=a.b/255,.2126*(t<=.03928?t/12.92:e.pow((t+.055)/1.055,2.4))+.7152*(n<=.03928?n/12.92:e.pow((n+.055)/1.055,2.4))+.0722*(r<=.03928?r/12.92:e.pow((r+.055)/1.055,2.4))},setAlpha:function(e){return this._a=C(e),this._roundA=a(100*this._a)/100,this},toHsv:function(){var e=f(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=f(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=u(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=u(this._r,this._g,this._b),t=a(360*e.h),n=a(100*e.s),r=a(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return d(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var o=[D(a(e).toString(16)),D(a(t).toString(16)),D(a(n).toString(16)),D(R(r))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*P(this._r,255))+"%",g:a(100*P(this._g,255))+"%",b:a(100*P(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*P(this._r,255))+"%, "+a(100*P(this._g,255))+"%, "+a(100*P(this._b,255))+"%)":"rgba("+a(100*P(this._r,255))+"%, "+a(100*P(this._g,255))+"%, "+a(100*P(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(S[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+h(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var a=c(e);n="#"+h(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(y,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(A,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(e,t){if("object"==typeof e){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:E(e[r]));e=n}return c(e,t)},c.equals=function(e,t){return!(!e||!t)&&c(e).toRgbString()==c(t).toRgbString()},c.random=function(){return c.fromRatio({r:s(),g:s(),b:s()})},c.mix=function(e,t,n){n=0===n?0:n||50;var r=c(e).toRgb(),a=c(t).toRgb(),i=n/100;return c({r:(a.r-r.r)*i+r.r,g:(a.g-r.g)*i+r.g,b:(a.b-r.b)*i+r.b,a:(a.a-r.a)*i+r.a})},c.readability=function(t,n){var r=c(t),a=c(n);return(e.max(r.getLuminance(),a.getLuminance())+.05)/(e.min(r.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(e,t,n){var r,a,i=c.readability(e,t);switch(a=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(e,t,n){var r,a,i,o,l=null,s=0;a=(n=n||{}).includeFallbackColors,i=n.level,o=n.size;for(var u=0;us&&(s=r,l=c(t[u]));return c.isReadable(e,l,{level:i,size:o})||!a?l:(n.includeFallbackColors=!1,c.mostReadable(e,["#fff","#000"],n))};var L=c.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"},S=c.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(L);function C(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function P(t,n){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(t)&&(t="100%");var r=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(t);return t=i(n,o(0,parseFloat(t))),r&&(t=parseInt(t*n,10)/100),e.abs(t-n)<1e-6?1:t%n/parseFloat(n)}function z(e){return i(1,o(0,e))}function O(e){return parseInt(e,16)}function D(e){return 1==e.length?"0"+e:""+e}function E(e){return e<=1&&(e=100*e+"%"),e}function R(t){return e.round(255*parseFloat(t)).toString(16)}function N(e){return O(e)/255}var I,F,j,B=(F="[\\s|\\(]+("+(I="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+I+")[,|\\s]+("+I+")\\s*\\)?",j="[\\s|\\(]+("+I+")[,|\\s]+("+I+")[,|\\s]+("+I+")[,|\\s]+("+I+")\\s*\\)?",{CSS_UNIT:new RegExp(I),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function q(e){return!!B.CSS_UNIT.exec(e)}l.exports?l.exports=c:window.tinycolor=c}(Math),l=l.exports;var s={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},c=s.RdBu,u=function(e){var t=0;if(!Array.isArray(e)||e.length<2)return!1;if(!e[0]||!e[e.length-1])return!1;if(0!=+e[0][0]||1!=+e[e.length-1][0])return!1;for(var n=0;n1){for(var e=["LOG:"],t=0;t0){for(var e=["WARN:"],t=0;t0){for(var e=["ERROR:"],t=0;t=0;t--){if(r=e[t][0],a=e[t][1],o=!1,G(r))for(n=r.length-1;n>=0;n--)W(r[n],Q(a,n))?o?r[n]=void 0:r.pop():o=!0;else if("object"==typeof r&&null!==r)for(i=Object.keys(r),o=!1,n=i.length-1;n>=0;n--)W(r[i[n]],Q(a,i[n]))?delete r[i[n]]:o=!0;if(o)return}}(s)):o[t[i]]=r}}function Q(e,n){var r=n;return t(n)?r="["+n+"]":e&&(r="."+n),e+r}function $(e,t,n,r){var a,i=G(n),o=!0,l=n,s=r.replace("-1",0),c=!i&&W(n,s),u=t[0];for(a=0;aa.max?n.set(r):n.set(+e)}},integer:{coerceFunction:function(e,n,r,a){e%1||!t(e)||void 0!==a.min&&ea.max?n.set(r):n.set(+e)}},string:{coerceFunction:function(e,t,n,r){if("string"!=typeof e){var a="number"==typeof e;!0!==r.strict&&a?t.set(String(e)):t.set(n)}else r.noBlank&&!e?t.set(n):t.set(e)}},color:{coerceFunction:function(e,t,n){l(e).isValid()?t.set(e):t.set(n)}},colorlist:{coerceFunction:function(e,t,n){Array.isArray(e)&&e.length&&e.every(function(e){return l(e).isValid()})?t.set(e):t.set(n)}},colorscale:{coerceFunction:function(e,t,n){t.set(f(e,n))}},angle:{coerceFunction:function(e,n,r){"auto"===e?n.set("auto"):t(e)?n.set(ae(+e)):n.set(r)}},subplotid:{coerceFunction:function(e,t,n,r){var a=r.regex||ne(n);"string"==typeof e&&a.test(e)?t.set(e):t.set(n)},validateFunction:function(e,t){var n=t.dflt;return e===n||"string"==typeof e&&!!ne(n).test(e)}},flaglist:{coerceFunction:function(e,t,n,r){if("string"==typeof e)if(-1===(r.extras||[]).indexOf(e)){for(var a=e.split("+"),i=0;i=oe&&e<=le?e:ue;if("string"!=typeof e&&"number"!=typeof e)return ue;e=String(e);var n=be(t),r=e.charAt(0);!n||"G"!==r&&"g"!==r||(e=e.substr(1),t="");var a=n&&"chinese"===t.substr(0,7),i=e.match(a?me:ye);if(!i)return ue;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),c=Number(i[7]||0),u=Number(i[9]||0),f=Number(i[11]||0);if(n){if(2===o.length)return ue;var d;o=Number(o);try{var h=O.getComponentMethod("calendars","getCal")(t);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),d=h.newDate(o,h.toMonthIndex(o,l,p),s)}else d=h.newDate(o,Number(l),s)}catch(e){return ue}return d?(d.toJD()-ge)*fe+c*de+u*he+f*pe:ue}o=2===o.length?(Number(o)+2e3-xe)%100+xe:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,c,u));return g.setUTCFullYear(o),g.getUTCMonth()!==l?ue:g.getUTCDate()!==s?ue:g.getTime()+f*pe},oe=ce.MIN_MS=ce.dateTime2ms("-9999"),le=ce.MAX_MS=ce.dateTime2ms("9999-12-31 23:59:59.9999"),ce.isDateTime=function(e,t){return ce.dateTime2ms(e,t)!==ue};var we=90*fe,ke=3*de,Me=5*he;function Ae(e,t,n,r,a){if((t||n||r||a)&&(e+=" "+_e(t,2)+":"+_e(n,2),(r||a)&&(e+=":"+_e(r,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;e+="."+_e(a,i)}return e}ce.ms2DateTime=function(e,t,n){if("number"!=typeof e||!(e>=oe&&e<=le))return ue;t||(t=0);var r,a,i,o,l,s,c=Math.floor(10*se(e+.05,1)),u=Math.round(e-c/10);if(be(n)){var f=Math.floor(u/fe)+ge,d=Math.floor(se(e,fe));try{r=O.getComponentMethod("calendars","getCal")(n).fromJD(f).formatDate("yyyy-mm-dd")}catch(e){r=ve("G%Y-%m-%d")(new Date(u))}if("-"===r.charAt(0))for(;r.length<11;)r="-0"+r.substr(1);else for(;r.length<10;)r="0"+r;a=t=oe+fe&&t<=le-fe))return ue;var n=Math.floor(10*se(t+.05,1)),r=new Date(Math.round(t-n/10));return Ae(e.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+n)},ce.cleanDate=function(e,t,n){if(ce.isJSDate(e)||"number"==typeof e){if(be(n))return _.error("JS Dates and milliseconds are incompatible with world calendars",e),t;if(!(e=ce.ms2DateTimeLocal(+e))&&void 0!==t)return t}else if(!ce.isDateTime(e,n))return _.error("unrecognized date",e),t;return e};var Te=/%\d?f/g;function Le(e,t,n,r){e=e.replace(Te,function(e){var n=Math.min(+e.charAt(1)||6,6);return(t/1e3%1+2).toFixed(n).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(t+.05));if(be(r))try{e=O.getComponentMethod("calendars","worldCalFmt")(e,t,r)}catch(e){return"Invalid"}return n(e)(a)}var Se=[59,59.9,59.99,59.999,59.9999];ce.formatDate=function(e,n,r,a,i,o){if(i=be(i)&&i,!n)if("y"===r)n=o.year;else if("m"===r)n=o.month;else{if("d"!==r)return function(e,n){var r=se(e+.05,fe),a=_e(Math.floor(r/de),2)+":"+_e(se(Math.floor(r/he),60),2);if("M"!==n){t(n)||(n=0);var i=(100+Math.min(se(e/pe,60),Se[n])).toFixed(n).substr(1);n>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(e,r)+"\n"+Le(o.dayMonthYear,e,a,i);n=o.dayMonth+"\n"+o.year}return Le(n,e,a,i)};var Ce=3*fe;ce.incrementMonth=function(e,t,n){n=be(n)&&n;var r=se(e,fe);if(e=Math.round(e-r),n)try{var a=Math.round(e/fe)+ge,i=O.getComponentMethod("calendars","getCal")(n),o=i.fromJD(a);return t%12?i.add(o,t,"m"):i.add(o,t/12,"y"),(o.toJD()-ge)*fe+r}catch(t){_.error("invalid ms "+e+" in calendar "+n)}var l=new Date(e+Ce);return l.setUTCMonth(l.getUTCMonth()+t)+r-Ce},ce.findExactDates=function(e,n){for(var r,a,i=0,o=0,l=0,s=0,c=be(n)&&O.getComponentMethod("calendars","getCal")(n),u=0;u1||g<0||g>1?null:{x:e+s*g,y:t+f*g}}function Ie(e,t,n,r,a){var i=r*e+a*t;if(i<0)return r*r+a*a;if(i>n){var o=r-e,l=a-t;return o*o+l*l}var s=r*t-a*e;return s*s/n}Re.segmentsIntersect=Ne,Re.segmentDistance=function(e,t,n,r,a,i,o,l){if(Ne(e,t,n,r,a,i,o,l))return 0;var s=n-e,c=r-t,u=o-a,f=l-i,d=s*s+c*c,h=u*u+f*f,p=Math.min(Ie(s,c,d,a-e,i-t),Ie(s,c,d,o-e,l-t),Ie(u,f,h,e-a,t-i),Ie(u,f,h,n-a,r-i));return Math.sqrt(p)},Re.getTextLocation=function(e,t,n,r){if(e===De&&r===Ee||(Oe={},De=e,Ee=r),Oe[n])return Oe[n];var a=e.getPointAtLength(se(n-r/2,t)),i=e.getPointAtLength(se(n+r/2,t)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=e.getPointAtLength(se(n,t)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return Oe[n]=s,s},Re.clearLocationCache=function(){De=null},Re.getVisibleSegment=function(e,t,n){var r,a,i=t.left,o=t.right,l=t.top,s=t.bottom,c=0,u=e.getTotalLength(),f=u;function d(t){var n=e.getPointAtLength(t);0===t?r=n:t===u&&(a=n);var c=n.xo?n.x-o:0,f=n.ys?n.y-s:0;return Math.sqrt(c*c+f*f)}for(var h=d(c);h;){if((c+=h+n)>f)return;h=d(c)}for(h=d(f);h;){if(c>(f-=h+n))return;h=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(r.x-a.x)<.1&&Math.abs(r.y-a.y)<.1}},Re.findPointOnPath=function(e,t,n,r){for(var a,i,o,l=(r=r||{}).pathLength||e.getTotalLength(),s=r.tolerance||.001,c=r.iterationLimit||30,u=e.getPointAtLength(0)[n]>e.getPointAtLength(l)[n]?-1:1,f=0,d=0,h=l;f0?h=a:d=a,f++}return i};var Fe=function(e){var t;if("string"==typeof e){if(null===(t=document.getElementById(e)))throw new Error("No DOM element with id '"+e+"' exists on the page.");return t}if(null===e||void 0===e)throw new Error("DOM element provided is null or undefined");return e},je=/^\w*$/,Be={init2dArray:function(e,t){for(var n=new Array(e),r=0;rt}function We(e,t){return e>=t}Ge.findBin=function(e,n,r){if(t(n.start))return r?Math.ceil((e-n.start)/n.size-1e-9)-1:Math.floor((e-n.start)/n.size+1e-9);var a,i,o=0,l=n.length,s=0,c=l>1?(n[l-1]-n[0])/(l-1):1;for(i=c>=0?r?Ye:Xe:r?We:Ze,e+=1e-9*c*(r?-1:1)*(c>=0?1:-1);o90&&_.log("Long binary search..."),o-1},Ge.sorterAsc=function(e,t){return e-t},Ge.sorterDes=function(e,t){return t-e},Ge.distinctVals=function(e){var t=e.slice();t.sort(Ge.sorterAsc);for(var n=t.length-1,r=t[n]-t[0]||1,a=r/(n||1)/1e4,i=[t[0]],o=0;ot[o]+a&&(r=Math.min(r,t[o+1]-t[o]),i.push(t[o+1]));return{vals:i,minDiff:r}},Ge.roundUp=function(e,t,n){for(var r,a=0,i=t.length-1,o=0,l=n?0:1,s=n?1:0,c=n?Math.ceil:Math.floor;ar.length)&&(a=r.length),t(n)||(n=!1),Qe(r[0])){for(o=new Array(a),i=0;ie.length-1)return e[e.length-1];var r=n%1;return r*e[Math.ceil(n)]+(1-r)*e[Math.floor(n)]};var $e={},Ke={};function et(e){e&&null!==e.timer&&(clearTimeout(e.timer),e.timer=null)}$e.throttle=function(e,t,n){var r=Ke[e],a=Date.now();if(!r){for(var i in Ke)Ke[i].tsr.ts+t?o():r.timer=setTimeout(function(){o(),r.timer=null},t)},$e.done=function(e){var t=Ke[e];return t&&t.timer?new Promise(function(e){var n=t.onDone;t.onDone=function(){n&&n(),e(),t.onDone=null}}):Promise.resolve()},$e.clear=function(e){if(e)et(Ke[e]),delete Ke[e];else for(var t in Ke)$e.clear(t)};var tt=function(e,n){if(e>0)return Math.log(e)/Math.LN10;var r=Math.log(Math.min(n[0],n[1]))/Math.LN10;return t(r)||(r=Math.log(Math.max(n[0],n[1]))/Math.LN10-6),r},nt={},rt=n.FP_SAFE,at=n.BADNUM,it=nt={};it.nestedProperty=Y,it.keyedContainer=function(e,t,n,r){var a,i;n=n||"name",r=r||"value";var o={};i=t&&t.length?Y(e,t).get():e,t=t||"",i=i||[];var l={};for(a=0;a2)return o[t]=2|o[t],c.set(e,null);if(s){for(a=t;a/g),l=0;lrt?at:t(e)?Number(e):at:at},it.noop=M,it.identity=function(e){return e},it.swapAttrs=function(e,t,n,r){n||(n="x"),r||(r="y");for(var a=0;an?Math.max(n,Math.min(t,e)):Math.max(t,Math.min(n,e))},it.bBoxIntersect=function(e,t,n){return n=n||0,e.left<=t.right+n&&t.left<=e.right+n&&e.top<=t.bottom+n&&t.top<=e.bottom+n},it.simpleMap=function(e,t,n,r){for(var a=e.length,i=new Array(a),o=0;o-1||c!==1/0&&c>=Math.pow(2,n)?e(t,n,r):l},it.OptionControl=function(e,t){e||(e={}),t||(t="opt");var n={optionList:[],_newoption:function(r){r[t]=e,n[r.name]=r,n.optionList.push(r)}};return n["_"+t]=e,n},it.smooth=function(e,t){if((t=Math.round(t)||0)<2)return e;var n,r,a,i,o=e.length,l=2*o,s=2*t-1,c=new Array(s),u=new Array(o);for(n=0;n=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=e[a]*c[r];u[n]=i}return u},it.syncOrAsync=function(e,t,n){var r;function a(){return it.syncOrAsync(e,t,n)}for(;e.length;)if((r=(0,e.splice(0,1)[0])(t))&&r.then)return r.then(a).then(void 0,it.promiseError);return n&&n(t)},it.stripTrailingSlash=function(e){return"/"===e.substr(-1)?e.substr(0,e.length-1):e},it.noneOrAll=function(e,t,n){if(e){var r,a,i=!1,o=!0;for(r=0;r=0&&i%1==0){var p=a?a[h]:h,g=r?r[p]:p;f(g)&&(e[g].selected=1)}}},it.getTargetArray=function(e,t){var n=t.target;if("string"==typeof n&&n){var r=it.nestedProperty(e,n).get();return!!Array.isArray(r)&&r}return!!Array.isArray(n)&&n},it.minExtend=function(e,t){var n={};"object"!=typeof t&&(t={});var r,a,i,o=Object.keys(e);for(r=0;r1?a+o[1]:"";if(i&&(o.length>1||l.length>4||n))for(;r.test(l);)l=l.replace(r,"$1"+i+"$2");return l+s};var st=/%{([^\s%{}]*)}/g,ct=/^\w*$/;it.templateString=function(e,t){var n={};return e.replace(st,function(e,r){return ct.test(r)?t[r]||"":(n[r]=n[r]||it.nestedProperty(t,r).get,n[r]()||"")})};it.subplotSort=function(e,t){for(var n=Math.min(e.length,t.length)+1,r=0,a=0,i=0;i=48&&o<=57,c=l>=48&&l<=57;if(s&&(r=10*r+o-48),c&&(a=10*a+l-48),!s||!c){if(r!==a)return r-a;if(o!==l)return o-l}}return a-r};var ut=2e9;it.seedPseudoRandom=function(){ut=2e9},it.pseudoRandom=function(){var e=ut;return ut=(69069*ut+1)%4294967296,Math.abs(ut-e)<429496729?it.pseudoRandom():ut/4294967296};var ft={exports:{}};!function(e,t){"object"==typeof ft.exports?t(ft.exports):t(e.topojson=e.topojson||{})}(this,function(e){"use strict";var t=function(e){return e},n=function(e){if(null==(n=e.transform))return t;var n,r,a,i=n.scale[0],o=n.scale[1],l=n.translate[0],s=n.translate[1];return function(e,t){return t||(r=a=0),e[0]=(r+=e[0])*i+l,e[1]=(a+=e[1])*o+s,e}},r=function(e){var t=e.bbox;function r(e){s[0]=e[0],s[1]=e[1],l(s),s[0]f&&(f=s[0]),s[1]d&&(d=s[1])}function a(e){switch(e.type){case"GeometryCollection":e.geometries.forEach(a);break;case"Point":r(e.coordinates);break;case"MultiPoint":e.coordinates.forEach(r)}}if(!t){var i,o,l=n(e),s=new Array(2),c=1/0,u=c,f=-c,d=-c;for(o in e.arcs.forEach(function(e){for(var t=-1,n=e.length;++tf&&(f=s[0]),s[1]d&&(d=s[1])}),e.objects)a(e.objects[o]);t=e.bbox=[c,u,f,d]}return t},a=function(e,t){for(var n,r=e.length,a=r-t;a<--r;)n=e[a],e[a++]=e[r],e[r]=n};function i(e,t){var n=t.id,r=t.bbox,a=null==t.properties?{}:t.properties,i=o(e,t);return null==n&&null==r?{type:"Feature",properties:a,geometry:i}:null==r?{type:"Feature",id:n,properties:a,geometry:i}:{type:"Feature",id:n,bbox:r,properties:a,geometry:i}}function o(e,t){var r=n(e),i=e.arcs;function o(e,t){t.length&&t.pop();for(var n=i[e<0?~e:e],o=0,l=n.length;o1)r=function(e,t,n){var r,a=[],i=[];function o(e){var t=e<0?~e:e;(i[t]||(i[t]=[])).push({i:e,g:r})}function l(e){e.forEach(o)}function s(e){e.forEach(l)}return function e(t){switch(r=t,t.type){case"GeometryCollection":t.geometries.forEach(e);break;case"LineString":l(t.arcs);break;case"MultiLineString":case"Polygon":s(t.arcs);break;case"MultiPolygon":t.arcs.forEach(s)}}(t),i.forEach(null==n?function(e){a.push(e[0].i)}:function(e){n(e[0].g,e[e.length-1].g)&&a.push(e[0].i)}),a}(0,t,n);else for(a=0,r=new Array(i=e.arcs.length);a1)for(var i,o,c=1,u=s(a[0]);cu&&(o=a[0],a[0]=a[c],a[c]=o,u=i);return a})}}var u=function(e,t){for(var n=0,r=e.length;n>>1;e[a]=2))throw new Error("n must be \u22652");if(e.transform)throw new Error("already quantized");var n,a=r(e),i=a[0],o=(a[2]-i)/(t-1)||1,l=a[1],s=(a[3]-l)/(t-1)||1;function c(e){e[0]=Math.round((e[0]-i)/o),e[1]=Math.round((e[1]-l)/s)}function u(e){switch(e.type){case"GeometryCollection":e.geometries.forEach(u);break;case"Point":c(e.coordinates);break;case"MultiPoint":e.coordinates.forEach(c)}}for(n in e.arcs.forEach(function(e){for(var t,n,r,a=1,c=1,u=e.length,f=e[0],d=f[0]=Math.round((f[0]-i)/o),h=f[1]=Math.round((f[1]-l)/s);a=0))return e;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return e}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}ht.tinyRGB=function(e){var t=e.toRgb();return"rgb("+Math.round(t.r)+", "+Math.round(t.g)+", "+Math.round(t.b)+")"},ht.rgb=function(e){return ht.tinyRGB(l(e))},ht.opacity=function(e){return e?l(e).getAlpha():0},ht.addOpacity=function(e,t){var n=l(e).toRgb();return"rgba("+Math.round(n.r)+", "+Math.round(n.g)+", "+Math.round(n.b)+", "+t+")"},ht.combine=function(e,t){var n=l(e).toRgb();if(1===n.a)return l(e).toRgbString();var r=l(t||gt).toRgb(),a=1===r.a?r:{r:255*(1-r.a)+r.r*r.a,g:255*(1-r.a)+r.g*r.a,b:255*(1-r.a)+r.b*r.a},i={r:a.r*(1-n.a)+n.r*n.a,g:a.g*(1-n.a)+n.g*n.a,b:a.b*(1-n.a)+n.b*n.a};return l(i).toRgbString()},ht.contrast=function(e,t,n){var r=l(e);return 1!==r.getAlpha()&&(r=l(ht.combine(e,gt))),(r.isDark()?t?r.lighten(t):gt:n?r.darken(n):pt).toString()},ht.stroke=function(e,t){var n=l(t);e.style({stroke:ht.tinyRGB(n),"stroke-opacity":n.getAlpha()})},ht.fill=function(e,t){var n=l(t);e.style({fill:ht.tinyRGB(n),"fill-opacity":n.getAlpha()})},ht.clean=function(e){if(e&&"object"==typeof e){var t,n,r,a,i=Object.keys(e);for(t=0;t0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},kt.prototype.on=kt.prototype.addListener,kt.prototype.once=function(e,t){if(!At(t))throw TypeError("listener must be a function");var n=!1;function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}return r.listener=t,this.on(e,r),this},kt.prototype.removeListener=function(e,t){var n,r,a,i;if(!At(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,r=-1,n===t||At(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(Tt(n)){for(i=a;i-- >0;)if(n[i]===t||n[i].listener&&n[i].listener===t){r=i;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},kt.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(At(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},kt.prototype.listeners=function(e){return this._events&&this._events[e]?At(this._events[e])?[this._events[e]]:this._events[e].slice():[]},kt.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(At(t))return 1;if(t)return t.length}return 0},kt.listenerCount=function(e,t){return e.listenerCount(t)};var St,Ct=Mt.EventEmitter,Pt={init:function(e){if(e._ev instanceof Ct)return e;var t=new Ct,n=new Ct;return e._ev=t,e._internalEv=n,e.on=t.on.bind(t),e.once=t.once.bind(t),e.removeListener=t.removeListener.bind(t),e.removeAllListeners=t.removeAllListeners.bind(t),e._internalOn=n.on.bind(n),e._internalOnce=n.once.bind(n),e._removeInternalListener=n.removeListener.bind(n),e._removeAllInternalListeners=n.removeAllListeners.bind(n),e.emit=function(r,a){"undefined"!=typeof jQuery&&jQuery(e).trigger(r,a),t.emit(r,a),n.emit(r,a)},e},triggerHandler:function(e,t,n){var r,a;"undefined"!=typeof jQuery&&(r=jQuery(e).triggerHandler(t,n));var i=e._ev;if(!i)return r;var o=i._events[t];if(!o)return r;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},Rt.getCursor=function(e,t,n,r){return e="left"===n?0:"center"===n?1:"right"===n?2:nt.constrain(Math.floor(3*e),0,2),t="bottom"===r?0:"middle"===r?1:"top"===r?2:nt.constrain(Math.floor(3*t),0,2),_t[t][e]},Rt.unhover=St.wrapped,Rt.unhoverRaw=St.raw,Rt.init=function(e){var t,n,r,a,i,o,l,s,c=e.gd,u=1,f=d.DBLCLICKDELAY,h=e.element;c._mouseDownTime||(c._mouseDownTime=0),h.style.pointerEvents="all",h.onmousedown=g,mt?(h._ontouchstart&&h.removeEventListener("touchstart",h._ontouchstart),h._ontouchstart=g,h.addEventListener("touchstart",g,{passive:!1})):h.ontouchstart=g;var p=e.clampFn||function(e,t,n){return Math.abs(e)f&&(u=Math.max(u-1,1)),c._dragged)e.doneFn&&e.doneFn(t);else if(e.clickFn&&e.clickFn(u,o),!s){var n;try{n=new MouseEvent("click",t)}catch(e){var r=It(t);(n=document.createEvent("MouseEvents")).initMouseEvent("click",t.bubbles,t.cancelable,t.view,t.detail,t.screenX,t.screenY,r[0],r[1],t.ctrlKey,t.altKey,t.shiftKey,t.metaKey,t.button,t.relatedTarget)}l.dispatchEvent(n)}!function(e){e._dragging=!1,e._replotPending&&O.call("plot",e)}(c),c._dragged=!1}else c._dragged=!1}},Rt.coverSlip=Nt;var Ft={zauto:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{zmin:void 0,zmax:void 0}},zmin:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},zmax:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},colorscale:{valType:"colorscale",editType:"calc",impliedEdits:{autocolorscale:!1}},autocolorscale:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{colorscale:void 0}},reversescale:{valType:"boolean",dflt:!1,editType:"calc"},showscale:{valType:"boolean",dflt:!0,editType:"calc"}},jt=function(e){for(var t,n=e.length,r=new Array(n),a=n-1,i=0;a>=0;a--,i++)t=e[a],r[i]=[1-t[0],t[1]];return r},Bt=function(e,t,n,r){var a,i;n?(a=nt.nestedProperty(e,n).get(),i=nt.nestedProperty(e._input,n).get()):(a=e,i=e._input);var o=r+"auto",l=r+"min",c=r+"max",u=a[o],f=a[l],d=a[c],h=a.colorscale;!1===u&&void 0!==f||(f=nt.aggNums(Math.min,null,t)),!1===u&&void 0!==d||(d=nt.aggNums(Math.max,null,t)),f===d&&(f-=.5,d+=.5),a[l]=f,a[c]=d,i[l]=f,i[c]=d,i[o]=!1!==u||void 0===f&&void 0===d,a.autocolorscale&&(h=f*d<0?s.RdBu:f>=0?s.Reds:s.Blues,i.colorscale=h,a.reversescale&&(h=jt(h)),a.colorscale=h)},qt=nt.extendFlat,Ht=nt.isPlainObject,Vt={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},Ut={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},Gt=Vt.flags.slice().concat(["clearCalc","fullReplot"]),Yt=Ut.flags.slice().concat("layoutReplot"),Xt={traces:Vt,layout:Ut,traceFlags:function(){return Zt(Gt)},layoutFlags:function(){return Zt(Yt)},update:function(e,t){var n=t.editType;if(n&&"none"!==n)for(var r=n.split("+"),a=0;a0?Number(s):l;else if("string"!=typeof s)n.dtick=l;else{var c=s.charAt(0),u=s.substr(1);((u=t(u)?Number(u):0)<=0||!("date"===a&&"M"===c&&u===Math.round(u)||"log"===a&&"L"===c||"log"===a&&"D"===c&&(1===u||2===u)))&&(n.dtick=l)}var f="date"===a?nt.dateTick0(n.calendar):0,d=r("tick0",f);"date"===a?n.tick0=nt.cleanDate(d,f):t(d)&&"D1"!==s&&"D2"!==s?n.tick0=Number(d):n.tick0=f}else{void 0===r("tickvals")?n.tickmode="auto":r("ticktext")}},sn=function(e){return void 0!==s[e]||u(e)},cn=function(e,n,r,a,i){var o,l=i.prefix,s=i.cLetter,c=l.slice(0,l.length-1),u=l?nt.nestedProperty(e,c).get()||{}:e,f=l?nt.nestedProperty(n,c).get()||{}:n,d=u[s+"min"],h=u[s+"max"],p=u.colorscale;a(l+s+"auto",!(t(d)&&t(h)&&d","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},yn={},mn=pn.LINE_SPACING;function xn(e,t){return e.node().getBoundingClientRect()[t]}var bn=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;yn.convertToTspans=function(t,n,r){var a=t.text(),i=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&a.match(bn),o=e.select(t.node().parentNode);if(!o.empty()){var l=t.attr("class")?t.attr("class").split(" ")[0]:"text";return l+="-math",o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove(),t.style("display",null).attr({"data-unformatted":a,"data-math":"N"}),i?(n&&n._promises||[]).push(new Promise(function(n){t.style("display","none");var c=parseInt(t.node().style.fontSize,10),u={fontSize:c};!function(t,n,r){var a="math-output-"+nt.randstr([],64),i=e.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":n.fontSize+"px"}).text((o=t,o.replace(_n,"\\lt ").replace(wn,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var n=e.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())nt.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),n,a)}i.remove()})}(i[2],u,function(e,i,u){o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove();var f=e&&e.select("svg");if(!f||!f.node())return s(),void n();var d=o.append("g").classed(l+"-group",!0).attr({"pointer-events":"none","data-unformatted":a,"data-math":"Y"});d.node().appendChild(f.node()),i&&i.node()&&f.node().insertBefore(i.node().cloneNode(!0),f.node().firstChild),f.attr({class:l,height:u.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var h=t.node().style.fill||"black";f.select("g").attr({fill:h,stroke:h});var p=xn(f,"width"),g=xn(f,"height"),v=+t.attr("x")-p*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],y=-(c||xn(t,"height"))/4;"y"===l[0]?(d.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-p/2,y-g/2]+")"}),f.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===l[0]?f.attr({x:t.attr("x"),y:y-g/2}):"a"===l[0]?f.attr({x:0,y:y}):f.attr({x:v,y:+t.attr("y")+y-g/2}),r&&r.call(t,d),n(d)})})):s(),t}function s(){o.empty()||(l=t.attr("class")+"-math",o.select("svg."+l).remove()),t.text("").style("white-space","pre"),function(t,n){n=(r=n,function(e,t){if(!e)return"";for(var n=0;n1)for(var i=1;i doesnt match end tag <"+e+">. Pretending it did match.",n),a=o[o.length-1].node}else nt.log("Ignoring unexpected end tag .",n)}Dn.test(n)?s():(a=t,o=[{node:t}]);for(var d=n.split(zn),h=0;h|>|>)/g;var kn={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"},Mn={sub:"0.3em",sup:"-0.6em"},An={sub:"-0.21em",sup:"0.42em"},Tn="\u200b",Ln=["http:","https:","mailto:","",void 0,":"],Sn=new RegExp("]*)?/?>","g"),Cn=Object.keys(vn.entityToUnicode).map(function(e){return{regExp:new RegExp("&"+e+";","g"),sub:vn.entityToUnicode[e]}}),Pn=/(\r\n?|\n)/g,zn=/(<[^<>]*>)/,On=/<(\/?)([^ >]*)(\s+(.*))?>/i,Dn=//i,En=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Rn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Nn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,In=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function Fn(e,t){if(!e)return null;var n=e.match(t);return n&&(n[3]||n[4])}var jn=/(^|;)\s*color:/;function Bn(e,t,n){var r,a,i,o=n.horizontalAlign,l=n.verticalAlign||"top",s=e.node().getBoundingClientRect(),c=t.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-r.height}:"middle"===l?function(){return s.top+(s.height-r.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-r.width}:"center"===o?function(){return s.left+(s.width-r.width)/2}:function(){return s.left},function(){return r=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}yn.plainText=function(e){return(e||"").replace(Sn," ")},yn.lineCount=function(e){return e.selectAll("tspan.line").size()||1},yn.positionText=function(t,n,r){return t.each(function(){var t=e.select(this);function a(e,n){return void 0===n?null===(n=t.attr(e))&&(t.attr(e,0),n=0):t.attr(e,n),n}var i=a("x",n),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},yn.makeEditable=function(t,n){var r=n.gd,a=n.delegate,i=e.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,c,u;a=e.select(r).select(".svg-container"),l=a.append("div"),c=t.node().style,u=parseFloat(c.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":c.fontFamily||"Arial","font-size":u,color:n.fill||c.fill||"black",opacity:1,"background-color":n.background||"transparent",outline:"#ffffff33 1px solid",margin:[-u/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(n.text||t.attr("data-unformatted")).call(Bn(t,a,n)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var n,a=e.select(this).attr("class");(n=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(n).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===e.event.which?(r._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),e.select(this).call(Bn(t,a,n)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,d=o.attr("class");(f=d?"."+d.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(f).style({opacity:0})}function s(e){var t=e.node(),n=document.createRange();n.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(n),t.focus()}return n.immediate?l():o.on("click",l),e.rebind(t,i,"on")};var qn=function(e){var n=e.marker,r=n.sizeref||1,a=n.sizemin||0,i="area"===n.sizemode?function(e){return Math.sqrt(e/r)}:function(e){return e/r};return function(e){var n=i(e/2);return t(n)&&n>0?Math.max(n,a):0}},Hn={hasLines:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("lines")},hasMarkers:function(e){return e.visible&&(e.mode&&-1!==e.mode.indexOf("markers")||"splom"===e.type)},hasText:function(e){return e.visible&&e.mode&&-1!==e.mode.indexOf("text")},isBubble:function(e){return nt.isPlainObject(e.marker)&&nt.isArrayOrTypedArray(e.marker.size)}},Vn={},Un=pn.LINE_SPACING,Gn=d.DESELECTDIM,Yn=Vn={};Yn.font=function(e,t,n,r){nt.isPlainObject(t)&&(r=t.color,n=t.size,t=t.family),t&&e.style("font-family",t),n+1&&e.style("font-size",n+"px"),r&&e.call(dt.fill,r)},Yn.setPosition=function(e,t,n){e.attr("x",t).attr("y",n)},Yn.setSize=function(e,t,n){e.attr("width",t).attr("height",n)},Yn.setRect=function(e,t,n,r,a){e.call(Yn.setPosition,t,n).call(Yn.setSize,r,a)},Yn.translatePoint=function(e,n,r,a){var i=r.c2p(e.x),o=a.c2p(e.y);return!!(t(i)&&t(o)&&n.node())&&("text"===n.node().nodeName?n.attr("x",i).attr("y",o):n.attr("transform","translate("+i+","+o+")"),!0)},Yn.translatePoints=function(t,n,r){t.each(function(t){var a=e.select(this);Yn.translatePoint(t,a,n,r)})},Yn.hideOutsideRangePoint=function(e,t,n,r,a,i){t.attr("display",n.isPtWithinRange(e,a)&&r.isPtWithinRange(e,i)?null:"none")},Yn.hideOutsideRangePoints=function(t,n,r){if(n._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=n.xaxis,i=n.yaxis;t.each(function(n){var o=n[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Yn.hideOutsideRangePoint(t,e.select(this),a,i,l,s)})})}},Yn.crispRound=function(e,n,r){return n&&t(n)?e._context.staticPlot?n:n<1?1:Math.round(n):r||0},Yn.singleLineStyle=function(e,t,n,r,a){t.style("fill","none");var i=(((e||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";dt.stroke(t,r||i.color),Yn.dashLine(t,l,o)},Yn.lineGroupStyle=function(t,n,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=n||i.width||0,l=a||i.dash||"";e.select(this).call(dt.stroke,r||i.color).call(Yn.dashLine,l,o)})},Yn.dashLine=function(e,t,n){n=+n||0,t=Yn.dashStyle(t,n),e.style({"stroke-dasharray":t,"stroke-width":n+"px"})},Yn.dashStyle=function(e,t){t=+t||1;var n=Math.max(t,3);return"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),e},Yn.singleFillStyle=function(t){var n=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;n&&t.call(dt.fill,n)},Yn.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(n){var r=e.select(this);try{r.call(dt.fill,n[0].trace.fillcolor)}catch(e){nt.error(e,t),r.remove()}})},Yn.symbolNames=[],Yn.symbolFuncs=[],Yn.symbolNeedLines={},Yn.symbolNoDot={},Yn.symbolNoFill={},Yn.symbolList=[],Object.keys(hn).forEach(function(e){var t=hn[e];Yn.symbolList=Yn.symbolList.concat([t.n,e,t.n+100,e+"-open"]),Yn.symbolNames[t.n]=e,Yn.symbolFuncs[t.n]=t.f,t.needLine&&(Yn.symbolNeedLines[t.n]=!0),t.noDot?Yn.symbolNoDot[t.n]=!0:Yn.symbolList=Yn.symbolList.concat([t.n+200,e+"-dot",t.n+300,e+"-open-dot"]),t.noFill&&(Yn.symbolNoFill[t.n]=!0)});var Xn=Yn.symbolNames.length,Zn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Wn(e,t){var n=e%100;return Yn.symbolFuncs[n](t)+(e>=200?Zn:"")}Yn.symbolNumber=function(e){if("string"==typeof e){var t=0;e.indexOf("-open")>0&&(t=100,e=e.replace("-open","")),e.indexOf("-dot")>0&&(t+=200,e=e.replace("-dot","")),(e=Yn.symbolNames.indexOf(e))>=0&&(e+=t)}return e%100>=Xn||e>=400?0:Math.floor(Math.max(e,0))};var Jn={x1:1,x2:0,y1:0,y2:0},Qn={x1:0,x2:0,y1:1,y2:0};Yn.gradient=function(t,n,r,a,i,o){var s=n._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],nt.identity);s.exit().remove(),s.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===a?t.attr(Jn):"vertical"===a&&t.attr(Qn),t.attr("id",r);var n=l(i),s=l(o);t.append("stop").attr({offset:"0%","stop-color":dt.tinyRGB(s),"stop-opacity":s.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":dt.tinyRGB(n),"stop-opacity":n.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Yn.initGradients=function(e){nt.ensureSingle(e._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},Yn.singlePointStyle=function(e,t,n,r,a,i){var o=n.marker;!function(e,t,n,r,a,i,o,l){if(O.traceIs(n,"symbols")){var s=qn(n);t.attr("d",function(e){var t;t="various"===e.ms||"various"===i.size?3:Hn.isBubble(n)?s(e.ms):(i.size||6)/2,e.mrc=t;var r=Yn.symbolNumber(e.mx||i.symbol)||0;return e.om=r%200>=100,Wn(r,t)})}t.style("opacity",function(e){return(e.mo+1||i.opacity+1)-1});var c,u,f,d=!1;if(e.so?(f=o.outlierwidth,u=o.outliercolor,c=i.outliercolor):(f=(e.mlw+1||o.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,u="mlc"in e?e.mlcc=a(e.mlc):nt.isArrayOrTypedArray(o.color)?dt.defaultLine:o.color,nt.isArrayOrTypedArray(i.color)&&(c=dt.defaultLine,d=!0),c="mc"in e?e.mcc=r(e.mc):i.color||"rgba(0,0,0,0)"),e.om)t.call(dt.stroke,c).style({"stroke-width":(f||1)+"px",fill:"none"});else{t.style("stroke-width",f+"px");var h=i.gradient,p=e.mgt;if(p?d=!0:p=h&&h.type,p&&"none"!==p){var g=e.mgc;g?d=!0:g=h.color;var v="g"+l._fullLayout._uid+"-"+n.uid;d&&(v+="-"+e.i),t.call(Yn.gradient,l,v,p,c,g)}else t.call(dt.fill,c);f&&t.call(dt.stroke,u)}}(e,t,n,r,a,o,o.line,i)},Yn.pointStyle=function(t,n,r){if(t.size()){var a=n.marker,i=Yn.tryColorscale(a,""),o=Yn.tryColorscale(a,"line");t.each(function(t){Yn.singlePointStyle(t,e.select(this),n,i,o,r)})}},Yn.makeSelectedPointStyleFns=function(e){var t={},n=e.selected||{},r=e.unselected||{},a=e.marker||{},i=n.marker||{},o=r.marker||{},l=a.opacity,s=i.opacity,c=o.opacity,u=void 0!==s,f=void 0!==c;t.opacityFn=function(e){var t=e.mo,n=void 0!==t;if(n||u||f){if(!e.selected)return f?c:Gn*(n?t:l);if(u)return s}};var d=i.color,h=o.color;(d||h)&&(t.colorFn=function(e){if(e.selected){if(d)return d}else if(h)return h});var p=i.size,g=o.size,v=void 0!==p,y=void 0!==g;return(v||y)&&(t.sizeFn=function(e){var t=e.mrc;return e.selected?v?p/2:t:y?g/2:t}),t},Yn.selectedPointStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=Yn.makeSelectedPointStyleFns(n),a=n.marker||{};t.each(function(t){var n=e.select(this),a=r.opacityFn(t);void 0!==a&&n.style("opacity",a)}),r.colorFn&&t.each(function(t){var n=e.select(this),a=r.colorFn(t);a&&dt.fill(n,a)}),O.traceIs(n,"symbols")&&r.sizeFn&&t.each(function(t){var n=e.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);n.attr("d",Wn(Yn.symbolNumber(i),o)),t.mrc2=o})}},Yn.tryColorscale=function(e,t){var n=t?nt.nestedProperty(e,t).get():e,r=n.colorscale,a=n.color;return r&&nt.isArrayOrTypedArray(a)?dn.makeColorScaleFunc(dn.extractScale(r,n.cmin,n.cmax)):nt.identity};var $n={start:1,end:-1,middle:0,bottom:1,top:-1};function Kn(t,n,r,a){var i=e.select(t.node().parentNode),o=-1!==n.indexOf("top")?"top":-1!==n.indexOf("bottom")?"bottom":"middle",l=-1!==n.indexOf("left")?"end":-1!==n.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(yn.lineCount(t)-1)*Un+1,u=$n[l]*s,f=.75*r+$n[o]*s+($n[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+u+","+f+")")}function er(e,n){var r=e.ts||n.textfont.size;return t(r)&&r>0?r:0}Yn.textPointStyle=function(t,n,r){t.each(function(t){var a=e.select(this),i=nt.extractOption(t,n,"tx","text");if(i){var o=t.tp||n.textposition,l=er(t,n);a.call(Yn.font,t.tf||n.textfont.family,l,t.tc||n.textfont.color).text(i).call(yn.convertToTspans,r).call(Kn,o,l,t.mrc)}else a.remove()})},Yn.selectedTextStyle=function(t,n){if(t.size()&&n.selectedpoints){var r=n.selected||{},a=n.unselected||{};t.each(function(t){var i,o=e.select(this),l=t.tc||n.textfont.color,s=t.tp||n.textposition,c=er(t,n),u=(r.textfont||{}).color,f=(a.textfont||{}).color;t.selected?u&&(i=u):f?i=f:u||(i=dt.addOpacity(l,Gn)),i&&dt.fill(o,i),Kn(o,s,c,t.mrc2||t.mrc)})}};var tr=.5;function nr(t,n,r,a){var i=t[0]-n[0],o=t[1]-n[1],l=r[0]-n[0],s=r[1]-n[1],c=Math.pow(i*i+o*o,tr/2),u=Math.pow(l*l+s*s,tr/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,h=3*u*(c+u),p=3*c*(c+u);return[[e.round(n[0]+(h&&f/h),2),e.round(n[1]+(h&&d/h),2)],[e.round(n[0]-(p&&f/p),2),e.round(n[1]-(p&&d/p),2)]]}Yn.smoothopen=function(e,t){if(e.length<3)return"M"+e.join("L");var n,r="M"+e[0],a=[];for(n=1;n=1e4&&(Yn.savedBBoxes={},ir=0),r&&(Yn.savedBBoxes[r]=p),ir++,nt.extendFlat({},p)},Yn.setClipUrl=function(t,n){if(n){if(void 0===Yn.baseUrl){var r=e.select("base");r.size()&&r.attr("href")?Yn.baseUrl=window.location.href.split("#")[0]:Yn.baseUrl=""}t.attr("clip-path","url("+Yn.baseUrl+"#"+n+")")}else t.attr("clip-path",null)},Yn.getTranslate=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||0,y:+t[1]||0}},Yn.setTranslate=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||0,n=n||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+t+", "+n+")").trim(),e[a]("transform",i),i},Yn.getScale=function(e){var t=(e[e.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(e,t,n){return[t,n].join(" ")}).split(" ");return{x:+t[0]||1,y:+t[1]||1}},Yn.setScale=function(e,t,n){var r=e.attr?"attr":"getAttribute",a=e.attr?"attr":"setAttribute",i=e[r]("transform")||"";return t=t||1,n=n||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+t+", "+n+")").trim(),e[a]("transform",i),i},Yn.setPointGroupScale=function(e,t,n){var r,a,i;return t=t||1,n=n||1,a=1===t&&1===n?"":" scale("+t+","+n+")",i=/\s*sc.*/,e.each(function(){r=(this.getAttribute("transform")||"").replace(i,""),r=(r+=a).trim(),this.setAttribute("transform",r)}),a};var lr=/translate\([^)]*\)\s*$/;Yn.setTextPointsScale=function(t,n,r){t.each(function(){var t,a=e.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(lr);t=1===n&&1===r?[]:["translate("+o+","+l+")","scale("+n+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};function sr(e,t,n,r){r=r||nt.identity,Array.isArray(e)&&(t[0][n]=r(e))}var cr={getSubplot:function(e){return e.subplot||e.xaxis+e.yaxis||e.geo},isTraceInSubplots:function(e,t){if("splom"===e.type){for(var n=e.xaxes||[],r=e.yaxes||[],a=0;a=0&&n.index=i.length)return!1;if(2===e.dimensions){if(n++,t.length===n)return e;var o=t[n];if(!jr(o))return!1;e=i[a][o]}else e=i[a]}else e=i}}return e}function jr(e){return e===Math.round(e)&&e>=0}function Br(e){return function(e){zr.crawl(e,function(e,t,n){zr.isValObject(e)?"data_array"===e.valType?(e.role="data",n[t+"src"]={valType:"string",editType:"none"}):!0===e.arrayOk&&(n[t+"src"]={valType:"string",editType:"none"}):Er(e)&&(e.role="object")})}(e),function(e){zr.crawl(e,function(e,t,n){if(!e)return;var r=e[Nr];if(!r)return;delete e[Nr],n[t]={items:{}},n[t].items[r]=e,n[t].role="object"})}(e),function(e){!function e(t){for(var n in t)if(Er(t[n]))e(t[n]);else if(Array.isArray(t[n]))for(var r=0;r=o.length)return!1;r=(n=(O.transformsRegistry[o[l].type]||{}).attributes)&&n[t[2]],i=3}else if("area"===e.type)r=Ar[a];else{var s=e._module;if(s||(s=(O.modules[e.type||S.type.dflt]||{})._module),!s)return!1;if(!(r=(n=s.attributes)&&n[a])){var c=s.basePlotModule;c&&c.attributes&&(r=c.attributes[a])}r||(r=S[a])}return Fr(r,t,i)},zr.getLayoutValObject=function(e,t){return Fr(function(e,t){var n,r,a,i,o=e._basePlotModules;if(o){var l;for(n=0;nr?1:-1:+(e.substr(1)||1)-+(t.substr(1)||1)}},Ur={};function Gr(e,t,n){var r,a,i,o=!1;if("data"===t.type)r=e._fullData[null!==t.traces?t.traces[0]:0];else{if("layout"!==t.type)return!1;r=e._fullLayout}return a=nt.nestedProperty(r,t.prop).get(),(i=n[t.type]=n[t.type]||{}).hasOwnProperty(t.prop)&&i[t.prop]!==a&&(o=!0),i[t.prop]=a,{changed:o,value:a}}function Yr(e,t){var n=[],r=t[0],a={};if("string"==typeof r)a[r]=t[1];else{if(!nt.isPlainObject(r))return n;a=r}return Zr(a,function(e,t,r){n.push({type:"layout",prop:e,value:r})},"",0),n}function Xr(e,t){var n,r,a,i,o=[];if(r=t[0],a=t[1],n=t[2],i={},"string"==typeof r)i[r]=a;else{if(!nt.isPlainObject(r))return o;i=r,void 0===n&&(n=a)}return void 0===n&&(n=null),Zr(i,function(t,r,a){var i;if(Array.isArray(a)){var l=Math.min(a.length,e.data.length);n&&(l=Math.min(l,n.length)),i=[];for(var s=0;s0?".":"")+a;nt.isPlainObject(i)?Zr(i,t,o,r+1):t(o,a,i)}})}function Wr(e,t){return"splom"===e?-1:"splom"===t?1:0}Ur.manageCommandObserver=function(e,t,n,r){var a={},i=!0;t&&t._commandObserver&&(a=t._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Ur.hasSimpleAPICommandBindings(e,n,a.lookupTable);if(t&&t._commandObserver){if(o)return a;if(t._commandObserver.remove)return t._commandObserver.remove(),t._commandObserver=null,a}if(o){Gr(e,o,a.cache),a.check=function(){if(i){var t=Gr(e,o,a.cache);return t.changed&&r&&void 0!==a.lookupTable[t.value]&&(a.disable(),Promise.resolve(r({value:t.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[t.value]})).then(a.enable,a.enable)),t.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=n.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=n._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(e,t){t.text("");var n=t.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(e._context.linkText+" "+String.fromCharCode(187));if(e._context.sendData)n.on("click",function(){na.sendDataToCloud(e)});else{var r=window.location.pathname.split("/"),a=window.location.search;n.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+r[2].split(".")[0]+"/"+r[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},na.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var n=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=e.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:n+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=na.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var aa,ia=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],oa=["year","month","dayMonth","dayMonthYear"];function la(e,t){var n,r,a=e.trace,i=a._arrayAttrs,o={};for(n=0;n1&&_.length>1){for(O.getComponentMethod("grid","sizeDefaults")(i,a),r=0;r15&&_.length>15&&0===a.shapes.length&&0===a.images.length,a._hasCartesian=a._has("cartesian"),a._hasGeo=a._has("geo"),a._hasGL3D=a._has("gl3d"),a._hasGL2D=a._has("gl2d"),a._hasTernary=a._has("ternary"),a._hasPie=a._has("pie"),na.cleanPlot(l,a,o,n,c),na.linkSubplots(l,a,o,n),ea(a,n),na.doAutoMargin(t);var A=Vr.list(t);for(r=0;r0){var c=function(e){var t,n={left:0,right:0,bottom:0,top:0};if(e)for(t in e)e.hasOwnProperty(t)&&(n.left+=e[t].left||0,n.right+=e[t].right||0,n.bottom+=e[t].bottom||0,n.top+=e[t].top||0);return n}(e._boundingBoxMargins),u=c.left+c.right,f=c.bottom+c.top,d=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};a=Math.round(d*(h.width-u)),i=Math.round(d*(h.height-f))}else{var p=s?window.getComputedStyle(e):{};a=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=na.layoutAttributes.width.min,v=na.layoutAttributes.height.min;a1,m=!n.height&&Math.abs(r.height-i)>1;(m||y)&&(y&&(r.width=a),m&&(r.height=i)),e._initialAutoSize||(e._initialAutoSize={width:a,height:i}),na.sanitizeMargins(r)},na.supplyLayoutModuleDefaults=function(e,t,n,r){var a,i,o,l=O.componentsRegistry,s=t._basePlotModules,c=O.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(e,t);for(var u in s.length||s.push(c),t._has("cartesian")&&(O.getComponentMethod("grid","contentDefaults")(e,t),c.finalizeSubplots(e,t)),t._subplots)t._subplots[u].sort(nt.subplotSort);for(i=0;i.5*r.width&&(n.l=n.r=0),n.b+n.t>.5*r.height&&(n.b=n.t=0),r._pushmargin[t]={l:{val:n.x,size:n.l+a},r:{val:n.x,size:n.r+a},b:{val:n.y,size:n.b+a},t:{val:n.y,size:n.t+a}}}else delete r._pushmargin[t];r._replotting||na.doAutoMargin(e)}},na.doAutoMargin=function(e){var n=e._fullLayout;n._size||(n._size={}),n._pushmargin||(n._pushmargin={});var r=n._size,a=JSON.stringify(r),i=Math.max(n.margin.l||0,0),o=Math.max(n.margin.r||0,0),l=Math.max(n.margin.t||0,0),s=Math.max(n.margin.b||0,0),c=n._pushmargin;if(!1!==n.margin.autoexpand)for(var u in c.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},c){var f=c[u].l||{},d=c[u].b||{},h=f.val,p=f.size,g=d.val,v=d.size;for(var y in c){if(t(p)&&c[y].r){var m=c[y].r.val,x=c[y].r.size;if(m>h){var b=(p*m+(x-n.width)*h)/(m-h),_=(x*(1-h)+(p-n.width)*(1-m))/(m-h);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(t(v)&&c[y].t){var w=c[y].t.val,k=c[y].t.size;if(w>g){var M=(v*w+(k-n.height)*g)/(w-g),A=(k*(1-g)+(v-n.height)*(1-w))/(w-g);M>=0&&A>=0&&M+A>s+l&&(s=M,l=A)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(n.margin.pad),r.w=Math.round(n.width)-r.l-r.r,r.h=Math.round(n.height)-r.t-r.b,!n._replotting&&"{}"!==a&&a!==JSON.stringify(n._size))return O.call("plot",e)},na.graphJson=function(e,t,n,r,a){(a&&t&&!e._fullData||a&&!t&&!e._fullLayout)&&na.supplyDefaults(e);var i=a?e._fullData:e.data,o=a?e._fullLayout:e.layout,l=(e._transitionData||{})._frames;function s(e){if("function"==typeof e)return null;if(nt.isPlainObject(e)){var t,r,a={};for(t in e)if("function"!=typeof e[t]&&-1===["_","["].indexOf(t.charAt(0))){if("keepdata"===n){if("src"===t.substr(t.length-3))continue}else if("keepstream"===n){if("string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0&&!nt.isPlainObject(e.stream))continue}else if("keepall"!==n&&"string"==typeof(r=e[t+"src"])&&r.indexOf(":")>0)continue;a[t]=s(e[t])}return a}return Array.isArray(e)?e.map(s):nt.isJSDate(e)?nt.ms2DateTimeLocal(+e):e}var c={data:(i||[]).map(function(e){var n=s(e);return t&&delete n.fit,n})};return t||(c.layout=s(o)),e.framework&&e.framework.isPolar&&(c=e.framework.getConfig()),l&&(c.frames=s(l)),"object"===r?c:JSON.stringify(c)},na.modifyFrames=function(e,t){var n,r,a,i=e._transitionData._frames,o=e._transitionData._frameHash;for(n=0;n0&&(e._transitioningWithDuration=!0),e._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&e._transitionData._interruptCallbacks.push(function(){return O.call("redraw",e)}),e._transitionData._interruptCallbacks.push(function(){e.emit("plotly_transitioninterrupted",[])});var r,o,l=0,s=0;function c(){return l++,function(){var n;f||++s!==l||(n=t,e._transitionData&&(function(e){if(e)for(;e.length;)e.shift()}(e._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return O.call("redraw",e)}).then(function(){e._transitioning=!1,e._transitioningWithDuration=!1,e.emit("plotly_transitioned",[])}).then(n)))}}var d=e._fullLayout._basePlotModules,h=!1;if(n)for(o=0;o=0;i--)if(s[i].enabled){n._indexToPoints=s[i]._indexToPoints;break}r&&r.calc&&(o=r.calc(e,n))}Array.isArray(o)&&o[0]||(o=[{x:$r,y:$r}]),o[0].t||(o[0].t={}),o[0].trace=n,c[t]=o}}for(d&&ua(o),a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[u.side];r.attr("transform","translate("+p+")")}}}A.call(T),k&&(w?A.on(".opacity",null):(b=0,_=!0,A.text(s).on("mouseover.opacity",function(){e.select(this).transition().duration(d.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(d.HIDE_PLACEHOLDER).style("opacity",0)})),A.call(yn.makeEditable,{gd:n}).on("edit",function(e){void 0!==c?O.call("restyle",n,l,e,c):O.call("relayout",n,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(T)}).on("input",function(e){this.text(e||" ").call(yn.positionText,f.x,f.y)}));return A.classed("js-placeholder",_),p}},da=/ [XY][0-9]* /;var ha=n.FP_SAFE,pa=ma,ga=xa,va=function(e){e._length||e.setScale();var t,n=e._min&&e._max&&e._min.length&&e._max.length;e.autorange&&n&&(e.range=ma(e),e._r=e.range.slice(),e._rl=nt.simpleMap(e._r,e.r2l),(t=e._input).range=e.range.slice(),t.autorange=e.autorange);if(e._anchorAxis&&e._anchorAxis.rangeslider){var r=e._anchorAxis.rangeslider[e._name];r&&"auto"===r.rangemode&&(r.range=n?ma(e):e._rangeInitial?e._rangeInitial.slice():e.range.slice()),(t=e._anchorAxis._input).rangeslider[e._name]=nt.extendFlat({},r)}},ya=function(e,n,r){if(!function(e){return e.autorange||e._rangesliderAutorange}(e)||!n)return;e._min||(e._min=[]);e._max||(e._max=[]);r||(r={});e._m||e.setScale();var a,i,o,l,s,c,u,f,d,h,p,g,v=n.length,y=r.padded||!1,m=r.tozero&&("linear"===e.type||"-"===e.type),x="log"===e.type,b=!1;function _(e){if(Array.isArray(e))return b=!0,function(t){return Math.max(Number(e[t]||0),0)};var t=Math.max(Number(e||0),0);return function(){return t}}var w=_((e._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((e._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),A=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-ha&&(p=l),l>g&&l=b&&(l.extrapad||!y)){h=!1;break}_(a,l.val)&&l.pad<=b&&(y||!l.extrapad)&&(v.splice(i,1),i--)}if(h){var T=m&&0===a;v.push({val:a,pad:T?0:b,extrapad:!T&&y})}}}}var L=Math.min(6,v);for(a=0;a=L;a--)T(a)};function ma(e){var t,n,r,a,i,o,l,s,c=[],u=e._min[0].val,f=e._max[0].val,d=0,h=!1,p=xa(e);for(t=1;t0&&l>0&&s/l>d&&(i=r,o=a,d=s/l);if(u===f){var v=u-1,y=u+1;c="tozero"===e.rangemode?u<0?[v,0]:[0,y]:"nonnegative"===e.rangemode?[Math.max(0,v),Math.max(0,y)]:[v,y]}else d&&("linear"!==e.type&&"-"!==e.type||("tozero"===e.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===e.rangemode&&(i.val-d*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),d=(o.val-i.val)/(e._length-p(i)-p(o))),c=[i.val-d*p(i),o.val+d*p(o)]);return c[0]===c[1]&&("tozero"===e.rangemode?c=c[0]<0?[c[0],0]:c[0]>0?[0,c[0]]:[0,1]:(c=[c[0]-1,c[0]+1],"nonnegative"===e.rangemode&&(c[0]=Math.max(0,c[0])))),h&&c.reverse(),nt.simpleMap(c,e.l2r||Number)}function xa(e){var t=e._length/20;return"domain"===e.constrain&&e._inputDomain&&(t*=(e._inputDomain[1]-e._inputDomain[0])/(e.domain[1]-e.domain[0])),function(e){return e.pad+(e.extrapad?t:0)}}function ba(e){return t(e)&&Math.abs(e)=t}var ka=n.BADNUM,Ma=function(e,n){return function(e,n){for(var r,a=0,i=0,o=Math.max(1,(e.length-1)/1e3),l=0;l2*i}(e,n)?"date":function(e){for(var t,n=Math.max(1,(e.length-1)/1e3),r=0,a=0,i=0;i2*r}(e)?"category":function(e){if(!e)return!1;for(var n=0;n0)return Math.log(e)/Math.LN10;if(e<=0&&t&&n.range&&2===n.range.length){var r=n.range[0],a=n.range[1];return.5*(r+a-3*i*Math.abs(r-a))}return Pa}function l(e,r,a){var i=La(e,a||n.calendar);if(i===Pa){if(!t(e))return Pa;i=La(new Date(+e))}return i}function s(e,t,r){return Ta(e,t,r||n.calendar)}function c(e){return n._categories[Math.round(e)]}function u(e){if(n._categoriesMap){var r=n._categoriesMap[e];if(void 0!==r)return r}if(t(e))return+e}function f(r){return t(r)?e.round(n._b+n._m*r,2):Pa}function d(e){return(e-n._b)/n._m}n.c2l="log"===n.type?o:Sa,n.l2c="log"===n.type?za:Sa,n.l2p=f,n.p2l=d,n.c2p="log"===n.type?function(e,t){return f(o(e,t))}:f,n.p2c="log"===n.type?function(e){return za(d(e))}:d,-1!==["linear","-"].indexOf(n.type)?(n.d2r=n.r2d=n.d2c=n.r2c=n.d2l=n.r2l=Aa,n.c2d=n.c2r=n.l2d=n.l2r=Sa,n.d2p=n.r2p=function(e){return n.l2p(Aa(e))},n.p2d=n.p2r=d,n.cleanPos=Sa):"log"===n.type?(n.d2r=n.d2l=function(e,t){return o(Aa(e),t)},n.r2d=n.r2c=function(e){return za(Aa(e))},n.d2c=n.r2l=Aa,n.c2d=n.l2r=Sa,n.c2r=o,n.l2d=za,n.d2p=function(e,t){return n.l2p(n.d2r(e,t))},n.p2d=function(e){return za(d(e))},n.r2p=function(e){return n.l2p(Aa(e))},n.p2r=d,n.cleanPos=Sa):"date"===n.type?(n.d2r=n.r2d=nt.identity,n.d2c=n.r2c=n.d2l=n.r2l=l,n.c2d=n.c2r=n.l2d=n.l2r=s,n.d2p=n.r2p=function(e,t,r){return n.l2p(l(e,0,r))},n.p2d=n.p2r=function(e,t,n){return s(d(e),t,n)},n.cleanPos=function(e){return nt.cleanDate(e,Pa,n.calendar)}):"category"===n.type&&(n.d2c=n.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===n._categoriesMap&&(n._categoriesMap={}),void 0!==n._categoriesMap[e])return n._categoriesMap[e];n._categories.push(e);var t=n._categories.length-1;return n._categoriesMap[e]=t,t}return Pa},n.r2d=n.c2d=n.l2d=c,n.d2r=n.d2l_noadd=u,n.r2c=function(e){var t=u(e);return void 0!==t?t:n.fraction2r(.5)},n.l2r=n.c2r=Sa,n.r2l=u,n.d2p=function(e){return n.l2p(n.r2c(e))},n.p2d=function(e){return c(d(e))},n.r2p=n.d2p,n.p2r=d,n.cleanPos=function(e){return"string"==typeof e&&""!==e?e:Sa(e)}),n.fraction2r=function(e){var t=n.r2l(n.range[0]),r=n.r2l(n.range[1]);return n.l2r(t+e*(r-t))},n.r2fraction=function(e){var t=n.r2l(n.range[0]),r=n.r2l(n.range[1]);return(n.r2l(e)-t)/(r-t)},n.cleanRange=function(e,r){r||(r={}),e||(e="range");var i,o,l=nt.nestedProperty(n,e).get();if(o=(o="date"===n.type?nt.dfltRange(n.calendar):"y"===a?Dt.DFLTRANGEY:r.dfltRange||Dt.DFLTRANGEX).slice(),l&&2===l.length)for("date"===n.type&&(l[0]=nt.cleanDate(l[0],Pa,n.calendar),l[1]=nt.cleanDate(l[1],Pa,n.calendar)),i=0;i<2;i++)if("date"===n.type){if(!nt.isDateTime(l[i],n.calendar)){n[e]=o;break}if(n.r2l(l[0])===n.r2l(l[1])){var s=nt.constrain(n.r2l(l[0]),nt.MIN_MS+1e3,nt.MAX_MS-1e3);l[0]=n.l2r(s-1e3),l[1]=n.l2r(s+1e3);break}}else{if(!t(l[i])){if(!t(l[1-i])){n[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Ca?l[i]=-Ca:l[i]>Ca&&(l[i]=Ca),l[0]===l[1]){var c=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=c,l[1]+=c}}else nt.nestedProperty(n,e).set(o)},n.setScale=function(e){var t=r._size;if(n._categories||(n._categories=[]),n._categoriesMap||(n._categoriesMap={}),n.overlaying){var i=Vr.getFromId({_fullLayout:r},n.overlaying);n.domain=i.domain}var o=e&&n._r?"_r":"range",l=n.calendar;n.cleanRange(o);var s=n.r2l(n[o][0],l),c=n.r2l(n[o][1],l);if("y"===a?(n._offset=t.t+(1-n.domain[1])*t.h,n._length=t.h*(n.domain[1]-n.domain[0]),n._m=n._length/(s-c),n._b=-n._m*c):(n._offset=t.l+n.domain[0]*t.w,n._length=t.w*(n.domain[1]-n.domain[0]),n._m=n._length/(c-s),n._b=-n._m*s),!isFinite(n._m)||!isFinite(n._b))throw r._replotting=!1,new Error("Something went wrong with axis scaling")},n.makeCalcdata=function(e,t){var r,a,i,o,l=n.type,s="date"===l&&e[t+"calendar"];if(t in e){if(r=e[t],o=e._length||r.length,nt.isTypedArray(r)&&("linear"===l||"log"===l)){if(o===r.length)return r;if(r.subarray)return r.subarray(0,o)}for(a=new Array(o),i=0;i2e-6||((n-e._forceTick0)/e._minDtick%1+1.000001)%1>2e-6)&&(e._minDtick=0)):e._minDtick=0},Ua.saveRangeInitial=function(e,t){for(var n=Ua.list(e,"",!0),r=!1,a=0;a.3*d||u(a)||u(i))){var h=r.dtick/2;e+=e+h.8){var o=Number(n.substr(1));i.exactYears>.8&&o%12==0?e=Ua.tickIncrement(e,"M6","reverse")+1.5*Na:i.exactMonths>.8?e=Ua.tickIncrement(e,"M1","reverse")+15.5*Na:e-=Na/2;var l=Ua.tickIncrement(e,n);if(l<=r)return l}return e}(p,e,l.dtick,s,i)),h=p,0;h<=c;)h=Ua.tickIncrement(h,l.dtick,!1,i),0;return{start:n.c2r(p,0,i),end:n.c2r(h,0,i),size:l.dtick,_dataSpan:c-s}},Ua.prepTicks=function(e){var t=nt.simpleMap(e.range,e.r2l);if("auto"===e.tickmode||!e.dtick){var n,r=e.nticks;r||("category"===e.type?(n=e.tickfont?1.2*(e.tickfont.size||12):15,r=e._length/n):(n="y"===e._id.charAt(0)?40:80,r=nt.constrain(e._length/n,4,9)+1),"radialaxis"===e._name&&(r*=2)),"array"===e.tickmode&&(r*=100),Ua.autoTicks(e,Math.abs(t[1]-t[0])/r),e._minDtick>0&&e.dtick<2*e._minDtick&&(e.dtick=e._minDtick,e.tick0=e.l2r(e._forceTick0))}e.tick0||(e.tick0="date"===e.type?"2000-01-01":0),ni(e)},Ua.calcTicks=function(e){Ua.prepTicks(e);var t=nt.simpleMap(e.range,e.r2l);if("array"===e.tickmode)return function(e){var t,n,r=e.tickvals,a=e.ticktext,i=new Array(r.length),o=nt.simpleMap(e.range,e.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],c=Math.min(l,s),u=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var d="category"===e.type?e.d2l_noadd:e.d2l;"log"===e.type&&"L"!==String(e.dtick).charAt(0)&&(e.dtick="L"+Math.pow(10,Math.floor(Math.min(e.range[0],e.range[1]))-1));for(n=0;nc&&t=r:s<=r)&&!(i.length>l||s===o);s=Ua.tickIncrement(s,e.dtick,a,e.calendar))o=s,i.push(s);"angular"===e._id&&360===Math.abs(t[1]-t[0])&&i.pop(),e._tmax=i[i.length-1],e._prevDateHead="",e._inCalcTicks=!0;for(var c=new Array(i.length),u=0;u10||"01-01"!==a.substr(5)?e._tickround="d":e._tickround=+n.substr(1)%12==0?"y":"m";else if(n>=Na&&i<=10||n>=15*Na)e._tickround="d";else if(n>=Fa&&i<=16||n>=Ia)e._tickround="M";else if(n>=ja&&i<=19||n>=Fa)e._tickround="S";else{var o=e.l2r(r+n).replace(/^-/,"").length;e._tickround=Math.max(i,o)-20}}else if(t(n)||"L"===n.charAt(0)){var l=e.range.map(e.r2d||Number);t(n)||(n=Number(n.substr(1))),e._tickround=2-Math.floor(Math.log(n)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(ii(e.exponentformat)&&!oi(c)?e._tickexponent=3*Math.round((c-1)/3):e._tickexponent=c)}else e._tickround=null}function ri(e,t,n){var r=e.tickfont||{};return{x:t,dx:0,dy:0,text:n||"",fontSize:r.size,font:r.family,fontColor:r.color}}Ua.autoTicks=function(e,n){var r;function a(e){return Math.pow(e,Math.floor(Math.log(n)/Math.LN10))}if("date"===e.type){e.tick0=nt.dateTick0(e.calendar);var i=2*n;i>Ea?(n/=Ea,r=a(10),e.dtick="M"+12*ti(n,r,Za)):i>Ra?(n/=Ra,e.dtick="M"+ti(n,1,Wa)):i>Na?(e.dtick=ti(n,Na,Qa),e.tick0=nt.dateTick0(e.calendar,!0)):i>Ia?e.dtick=ti(n,Ia,Wa):i>Fa?e.dtick=ti(n,Fa,Ja):i>ja?e.dtick=ti(n,ja,Ja):(r=a(10),e.dtick=ti(n,r,Za))}else if("log"===e.type){e.tick0=0;var o=nt.simpleMap(e.range,e.r2l);if(n>.7)e.dtick=Math.ceil(n);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/n);n=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=a(10),e.dtick="L"+ti(n,r,Za)}else e.dtick=n>.3?"D2":"D1"}else"category"===e.type?(e.tick0=0,e.dtick=Math.ceil(Math.max(n,1))):"angular"===e._id?(e.tick0=0,r=1,e.dtick=ti(n,r,ei)):(e.tick0=0,r=a(10),e.dtick=ti(n,r,Za));if(0===e.dtick&&(e.dtick=1),!t(e.dtick)&&"string"!=typeof e.dtick){var s=e.dtick;throw e.dtick=1,"ax.dtick error: "+String(s)}},Ua.tickIncrement=function(n,r,a,i){var o=a?-1:1;if(t(r))return n+o*r;var l=r.charAt(0),s=o*Number(r.substr(1));if("M"===l)return nt.incrementMonth(n,s,i);if("L"===l)return Math.log(Math.pow(10,n)+s)/Math.LN10;if("D"===l){var c="D2"===r?Ka:$a,u=n+.01*o,f=nt.roundUp(nt.mod(u,1),c,a);return Math.floor(u)+Math.log(e.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(r)},Ua.tickFirst=function(n){var r=n.r2l||Number,a=nt.simpleMap(n.range,r),i=a[1]"+l,e._prevDateHead=l));n.text=s}(e,o,r,s):"log"===e.type?function(e,n,r,a,i){var o=e.dtick,l=n.x,s=e.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))n.text=li(Math.pow(10,l),e,i,a);else if(t(o)||"D"===o.charAt(0)&&nt.mod(l+.01,1)<.1){var c=Math.round(l);-1!==["e","E","power"].indexOf(e.exponentformat)||ii(e.exponentformat)&&oi(c)?(n.text=0===c?1:1===c?"10":c>1?"10"+c+"":"10"+Ba+-c+"",n.fontSize*=1.25):(n.text=li(Math.pow(10,l),e,"","fakehover"),"D1"===o&&"y"===e._id.charAt(0)&&(n.dy-=n.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);n.text=String(Math.round(Math.pow(10,nt.mod(l,1)))),n.fontSize*=.75}if("D1"===e.dtick){var u=String(n.text).charAt(0);"0"!==u&&"1"!==u||("y"===e._id.charAt(0)?n.dx-=n.fontSize/4:(n.dy+=n.fontSize/2,n.dx+=(e.range[1]>e.range[0]?1:-1)*n.fontSize*(l<0?.5:.25)))}}(e,o,0,s,a):"category"===e.type?function(e,t){var n=e._categories[Math.round(t.x)];void 0===n&&(n="");t.text=String(n)}(e,o):"angular"===e._id?function(e,t,n,r,a){if("radians"!==e.thetaunit||n)t.text=li(t.x,e,a,r);else{var i=t.x/180;if(0===i)t.text="0";else{var o=function(e){function t(e,t){return Math.abs(e-t)<=1e-6}var n=function(e){var n=1;for(;!t(Math.round(e*n)/n,e);)n*=10;return n}(e),r=e*n,a=Math.abs(function e(n,r){return t(r,0)?n:e(r,n%r)}(r,n));return[Math.round(r/a),Math.round(n/a)]}(i);if(o[1]>=100)t.text=li(nt.deg2rad(t.x),e,a,r);else{var l=t.x<0;1===o[1]?1===o[0]?t.text="\u03c0":t.text=o[0]+"\u03c0":t.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(t.text=Ba+t.text)}}}}(e,o,r,s,a):function(e,t,n,r,a){"never"===a?a="":"all"===e.showexponent&&Math.abs(t.x/e.dtick)<1e-6&&(a="hide");t.text=li(t.x,e,a,r)}(e,o,0,s,a),e.tickprefix&&!d(e.showtickprefix)&&(o.text=e.tickprefix+o.text),e.ticksuffix&&!d(e.showticksuffix)&&(o.text+=e.ticksuffix),o},Ua.hoverLabelText=function(e,t,n){if(n!==qa&&n!==t)return Ua.hoverLabelText(e,t)+" - "+Ua.hoverLabelText(e,n);var r="log"===e.type&&t<=0,a=Ua.tickText(e,e.c2l(r?-t:t),"hover").text;return r?0===t?"0":Ba+a:a};var ai=["f","p","n","\u03bc","m","","k","M","G","T"];function ii(e){return"SI"===e||"B"===e}function oi(e){return e>14||e<-15}function li(e,n,r,a){var i=e<0,o=n._tickround,l=r||n.exponentformat||"B",s=n._tickexponent,c=Ua.getTickFormat(n),u=n.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===n.showexponent?n.dtick:t(e)&&Math.abs(e)||1,range:"none"===n.showexponent?n.range.map(n.r2d):[0,e||1]};ni(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,n.hoverformat&&(c=n.hoverformat)}if(c)return n._numFormat(c)(e).replace(/-/g,Ba);var d,h=Math.pow(10,-o)/2;if("none"===l&&(s=0),(e=Math.abs(e))"+d+"":"B"===l&&9===s?e+="B":ii(l)&&(e+=ai[s/3+5]));return i?Ba+e:e}function si(e,t){for(var n=0;n=0,i=c(e,t[1])<=0;return(n||a)&&(r||i)}if(e.tickformatstops&&e.tickformatstops.length>0)switch(e.type){case"date":case"linear":for(t=0;t=i(r))){n=e.tickformatstops[t];break}break;case"log":for(t=0;t1&&t1)for(r=1;r-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),void 0!==t.extraText&&(s+=(s?"
":"")+t.extraText),""===s&&(""===l&&n.remove(),s=l);var g=n.select("text.nums").call(Vn.font,t.fontFamily||u,t.fontSize||f,t.fontColor||h).text(s).attr("data-notex",1).call(yn.positionText,0,0).call(yn.convertToTspans,r),y=n.select("text.name"),m=0;l&&l!==s?(y.call(Vn.font,t.fontFamily||u,t.fontSize||f,d).text(l).attr("data-notex",1).call(yn.positionText,0,0).call(yn.convertToTspans,r),m=y.node().getBoundingClientRect().width+2*mi):(y.remove(),n.select("rect").remove()),n.select("path").style({fill:d,stroke:h});var k,M,A=g.node().getBoundingClientRect(),T=t.xa._offset+(t.x0+t.x1)/2,L=t.ya._offset+(t.y0+t.y1)/2,S=Math.abs(t.x1-t.x0),C=Math.abs(t.y1-t.y0),P=A.width+yi+mi+m;t.ty0=x-A.top,t.bx=A.width+2*mi,t.by=A.height+2*mi,t.anchor="start",t.txwidth=A.width,t.tx2width=m,t.offset=0,i?(t.pos=T,k=L+C/2+P<=_,M=L-C/2-P>=0,"top"!==t.idealAlign&&k||!M?k?(L+=C/2,t.anchor="start"):t.anchor="middle":(L-=C/2,t.anchor="end")):(t.pos=L,k=T+S/2+P<=b,M=T-S/2-P>=0,"left"!==t.idealAlign&&k||!M?k?(T+=S/2,t.anchor="start"):t.anchor="middle":(T-=S/2,t.anchor="end")),g.attr("text-anchor",t.anchor),m&&y.attr("text-anchor",t.anchor),n.attr("transform","translate("+T+","+L+")"+(i?"rotate("+di+")":""))}),S}function bi(t,n){t.each(function(t){var r=e.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(yi+mi),s=l+o*(t.txwidth+mi),c=0,u=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+mi),n&&(u*=-vi,c=t.offset*gi),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(u-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*yi+c)+","+(yi+u)+"v"+(t.by/2-yi)+"h"+a*t.bx+"v-"+t.by+"H"+(a*yi+c)+"V"+(u-yi)+"Z"),i.call(yn.positionText,l+c,u+t.ty0-t.by/2+mi),t.tx2width&&(r.select("text.name").call(yn.positionText,s+o*mi+c,u+t.ty0-t.by/2+mi),r.select("rect").call(Vn.setRect,s+(o-1)*t.tx2width/2+c,u-t.by/2-1,t.tx2width,t.by+2))}})}function _i(e,t){var n=e.index,r=e.trace||{},a=e.cd[0],i=e.cd[n]||{},o=Array.isArray(n)?function(e,t){return nt.castOption(a,n,e)||nt.extractOption({},r,"",t)}:function(e,t){return nt.extractOption(i,r,e,t)};function l(t,n,r){var a=o(n,r);a&&(e[t]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),e.posref="y"===t?e.xa._offset+(e.x0+e.x1)/2:e.ya._offset+(e.y0+e.y1)/2,e.x0=nt.constrain(e.x0,0,e.xa._length),e.x1=nt.constrain(e.x1,0,e.xa._length),e.y0=nt.constrain(e.y0,0,e.ya._length),e.y1=nt.constrain(e.y1,0,e.ya._length),void 0!==e.xLabelVal&&(e.xLabel="xLabel"in e?e.xLabel:Da.hoverLabelText(e.xa,e.xLabelVal),e.xVal=e.xa.c2d(e.xLabelVal)),void 0!==e.yLabelVal&&(e.yLabel="yLabel"in e?e.yLabel:Da.hoverLabelText(e.ya,e.yLabelVal),e.yVal=e.ya.c2d(e.yLabelVal)),void 0!==e.zLabelVal&&void 0===e.zLabel&&(e.zLabel=String(e.zLabelVal)),!(isNaN(e.xerr)||"log"===e.xa.type&&e.xerr<=0)){var s=Da.tickText(e.xa,e.xa.c2l(e.xerr),"hover").text;void 0!==e.xerrneg?e.xLabel+=" +"+s+" / -"+Da.tickText(e.xa,e.xa.c2l(e.xerrneg),"hover").text:e.xLabel+=" \xb1 "+s,"x"===t&&(e.distance+=1)}if(!(isNaN(e.yerr)||"log"===e.ya.type&&e.yerr<=0)){var c=Da.tickText(e.ya,e.ya.c2l(e.yerr),"hover").text;void 0!==e.yerrneg?e.yLabel+=" +"+c+" / -"+Da.tickText(e.ya,e.ya.c2l(e.yerrneg),"hover").text:e.yLabel+=" \xb1 "+c,"y"===t&&(e.distance+=1)}var u=e.hoverinfo||e.trace.hoverinfo;return"all"!==u&&(-1===(u=Array.isArray(u)?u:u.split("+")).indexOf("x")&&(e.xLabel=void 0),-1===u.indexOf("y")&&(e.yLabel=void 0),-1===u.indexOf("z")&&(e.zLabel=void 0),-1===u.indexOf("text")&&(e.text=void 0),-1===u.indexOf("name")&&(e.name=void 0)),e}function wi(e,t){var n,r,a=t.container,i=t.fullLayout,o=t.event,s=!!e.hLinePoint,c=!!e.vLinePoint;if(a.selectAll(".spikeline").remove(),c||s){var u=dt.combine(i.plot_bgcolor,i.paper_bgcolor);if(s){var f,d,h=e.hLinePoint;n=h&&h.xa,"cursor"===(r=h&&h.ya).spikesnap?(f=o.pointerX,d=o.pointerY):(f=n._offset+h.x,d=r._offset+h.y);var p,g,v=l.readability(h.color,u)<1.5?dt.contrast(u):h.color,y=r.spikemode,m=r.spikethickness,x=r.spikecolor||v,b=r._boundingBox,_=(b.left+b.right)/2V.width||q<0||q>V.height)return Et.unhoverRaw(n,r);r.pointerX=r.offsetX,r.pointerY=r.offsetY}if(_="xval"in r?cr.flat(o,r.xval):cr.p2c(h,B),w="yval"in r?cr.flat(o,r.yval):cr.p2c(p,q),!t(_[0])||!t(w[0]))return nt.warn("Fx.hover failed",r,n),Et.unhoverRaw(n,r)}var U=1/0;for(M=0;ME&&(I.splice(0,E),U=I[0].distance),u&&0!==N&&0===I.length){D.distance=N,D.index=!1;var W=T._module.hoverPoints(D,P,z,"closest",l._hoverlayer);if(W&&(W=W.filter(function(e){return e.spikeDistance<=N})),W&&W.length){var J,Q=W.filter(function(e){return e.xa.showspikes});if(Q.length){var $=Q[0];t($.x0)&&t($.y0)&&(J=ne($),(!j.vLinePoint||j.vLinePoint.spikeDistance>J.spikeDistance)&&(j.vLinePoint=J))}var K=W.filter(function(e){return e.ya.showspikes});if(K.length){var ee=K[0];t(ee.x0)&&t(ee.y0)&&(J=ne(ee),(!j.hLinePoint||j.hLinePoint.spikeDistance>J.spikeDistance)&&(j.hLinePoint=J))}}}}function te(e,t){for(var n,r=null,a=1/0,i=0;i1,ge=dt.combine(l.plot_bgcolor||dt.background,l.paper_bgcolor),ve={hovermode:b,rotateLabels:pe,bgColor:ge,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},ye=xi(I,ve,n);if(function(e,t,n){var r,a,i,o,l,s,c,u=0,f=e.map(function(e,r){var a=e[t];return[{i:r,dp:0,pos:e.pos,posref:e.posref,size:e.by*("x"===a._id.charAt(0)?pi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?n.width:n.height}]}).sort(function(e,t){return e[0].posref-t[0].posref});function d(e){var t=e[0],n=e[e.length-1];if(a=t.pmin-t.pos-t.dp+t.size,i=n.pos+n.dp+n.size-t.pmax,a>.01){for(l=e.length-1;l>=0;l--)e[l].dp+=a;r=!1}if(!(i<.01)){if(a<-.01){for(l=e.length-1;l>=0;l--)e[l].dp-=i;r=!1}if(r){var c=0;for(o=0;ot.pmax&&c++;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos>t.pmax-1&&(s.del=!0,c--);for(o=0;o=0;l--)e[l].dp-=i;for(o=e.length-1;o>=0&&!(c<=0);o--)(s=e[o]).pos+s.dp+s.size>t.pmax&&(s.del=!0,c--)}}}for(;!r&&u<=e.length;){for(u++,r=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(h.push.apply(h,p),f.splice(o+1,1),c=0,l=h.length-1;l>=0;l--)c+=h[l].dp;for(i=c/h.length,l=h.length-1;l>=0;l--)h[l].dp-=i;r=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var y=f[o];for(l=y.length-1;l>=0;l--){var m=y[l],x=e[m.i];x.offset=m.dp,x.del=m.del}}}(I,pe?"xa":"ya",l),bi(ye,pe),r.target&&r.target.tagName){var me=O.getComponentMethod("annotations","hasClickToShow")(n,de);gr(e.select(r.target),me?"pointer":"")}if(!r.target||i||!function(e,t,n){if(!n||n.length!==e._hoverdata.length)return!0;for(var r=n.length-1;r>=0;r--){var a=n[r],i=e._hoverdata[r];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(n,0,fe))return;fe&&n.emit("plotly_unhover",{event:r,points:fe});n.emit("plotly_hover",{event:r,points:n._hoverdata,xaxes:h,yaxes:p,xvals:_,yvals:w})}(n,r,a,i)})},fi.loneHover=function(t,n){var r={color:t.color||dt.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=e.select(n.container),i=n.outerContainer?e.select(n.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:n.bgColor||dt.background,container:a,outerContainer:i},l=xi([r],o,n.gd);return bi(l,o.rotateLabels),l.node()};var Mi=fi.hover,Ai=function(e,t,n,r){n("hoverlabel.bgcolor",(r=r||{}).bgcolor),n("hoverlabel.bordercolor",r.bordercolor),n("hoverlabel.namelength",r.namelength),nt.coerceFont(n,"hoverlabel.font",r.font)},Ti=T({editType:"none"});Ti.family.dflt=wt.HOVERFONT,Ti.size.dflt=wt.HOVERFONTSIZE;var Li={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Ti,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var Si={moduleType:"component",name:"fx",constants:wt,schema:{layout:Li},attributes:L,layoutAttributes:Li,supplyLayoutGlobalDefaults:function(e,t){Ai(0,0,function(n,r){return nt.coerce(e,t,Li,n,r)})},supplyDefaults:function(e,t,n,r){Ai(0,0,function(n,r){return nt.coerce(e,t,L,n,r)},r.hoverlabel)},supplyLayoutDefaults:function(e,t,n){function r(n,r){return nt.coerce(e,t,Li,n,r)}var a;"select"===r("dragmode")&&r("selectdirection"),t._has("cartesian")?(t._isHoriz=function(e){for(var t=!0,n=0;n0})}function c(e,r){var a=e.seg,i=r.seg,o=a.start,s=a.end,c=i.start,u=i.end;n&&n.checkIntersection(a,i);var f=t.linesIntersect(o,s,c,u);if(!1===f){if(!t.pointsCollinear(o,s,c))return!1;if(t.pointsSame(o,u)||t.pointsSame(s,c))return!1;var d=t.pointsSame(o,c),h=t.pointsSame(s,u);if(d&&h)return r;var p=!d&&t.pointBetween(o,c,u),g=!h&&t.pointBetween(s,c,u);if(d)return g?l(r,s):l(e,u),r;p&&(h||(g?l(r,s):l(e,u)),l(r,o))}else 0===f.alongA&&(-1===f.alongB?l(e,c):0===f.alongB?l(e,f.pt):1===f.alongB&&l(e,u)),0===f.alongB&&(-1===f.alongA?l(r,o):0===f.alongA?l(r,f.pt):1===f.alongA&&l(r,s));return!1}for(var u=[];!a.isEmpty();){var f=a.getHead();if(n&&n.vert(f.pt[0]),f.isStart){n&&n.segmentNew(f.seg,f.primary);var d=s(f),h=d.before?d.before.ev:null,p=d.after?d.after.ev:null;function g(){if(h){var e=c(f,h);if(e)return e}return!!p&&c(f,p)}n&&n.tempStatus(f.seg,!!h&&h.seg,!!p&&p.seg);var v,y,m=g();if(m)e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(m.seg.myFill.above=!m.seg.myFill.above):m.seg.otherFill=f.seg.myFill,n&&n.segmentUpdate(m.seg),f.other.remove(),f.remove();if(a.getHead()!==f){n&&n.rewind(f.seg);continue}e?(y=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:r,f.seg.myFill.above=y?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:r,f.seg.otherFill={above:v,below:v}),n&&n.status(f.seg,!!h&&h.seg,!!p&&p.seg),f.other.status=d.insert(Ni.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&c(x.prev.ev,x.next.ev),n&&n.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}u.push(f.seg)}a.getHead().remove()}return n&&n.done(),u}return e?{addRegion:function(e){for(var r,a,i,l=e[e.length-1],s=0;s=-e},pointBetween:function(t,n,r){var a=t[1]-n[1],i=r[0]-n[0],o=t[0]-n[0],l=r[1]-n[1],s=o*i+a*l;return!(s-e)},pointsSameX:function(t,n){return Math.abs(t[0]-n[0])e!=o-a>e&&(i-c)*(a-u)/(o-u)+c-r>e&&(l=!l),i=c,o=u}return l}};return t}();function Ui(e,t,n){var r=Bi.segments(e),a=Bi.segments(t),i=n(Bi.combine(r,a));return Bi.polygon(i)}Bi={buildLog:function(e){return!0===e?Hi=Ei():!1===e&&(Hi=!1),!1!==Hi&&Hi.list},epsilon:function(e){return Vi.epsilon(e)},segments:function(e){var t=Ii(!0,Vi,Hi);return e.regions.forEach(t.addRegion),{segments:t.calculate(e.inverted),inverted:e.inverted}},combine:function(e,t){return{combined:Ii(!1,Vi,Hi).calculate(e.segments,e.inverted,t.segments,t.inverted),inverted1:e.inverted,inverted2:t.inverted}},selectUnion:function(e){return{segments:qi.union(e.combined,Hi),inverted:e.inverted1||e.inverted2}},selectIntersect:function(e){return{segments:qi.intersect(e.combined,Hi),inverted:e.inverted1&&e.inverted2}},selectDifference:function(e){return{segments:qi.difference(e.combined,Hi),inverted:e.inverted1&&!e.inverted2}},selectDifferenceRev:function(e){return{segments:qi.differenceRev(e.combined,Hi),inverted:!e.inverted1&&e.inverted2}},selectXor:function(e){return{segments:qi.xor(e.combined,Hi),inverted:e.inverted1!==e.inverted2}},polygon:function(e){return{regions:Fi(e.segments,Vi,Hi),inverted:e.inverted}},polygonFromGeoJSON:function(e){return Ri.toPolygon(Bi,e)},polygonToGeoJSON:function(e){return Ri.fromPolygon(Bi,Vi,e)},union:function(e,t){return Ui(e,t,Bi.selectUnion)},intersect:function(e,t){return Ui(e,t,Bi.selectIntersect)},difference:function(e,t){return Ui(e,t,Bi.selectDifference)},differenceRev:function(e,t){return Ui(e,t,Bi.selectDifferenceRev)},xor:function(e,t){return Ui(e,t,Bi.selectXor)}},"object"==typeof window&&(window.PolyBool=Bi);var Gi=Bi,Yi={},Xi=Be.dot,Zi=n.BADNUM,Wi=Yi={};Wi.tester=function(e){if(Array.isArray(e[0][0]))return Wi.multitester(e);var t,n=e.slice(),r=n[0][0],a=r,i=n[0][1],o=i;for(n.push(n[0]),t=1;ta||s===Zi||so||t&&l(e))}:function(e,t){var l=e[0],s=e[1];if(l===Zi||la||s===Zi||so)return!1;var c,u,f,d,h,p=n.length,g=n[0][0],v=n[0][1],y=0;for(c=1;cMath.max(u,g)||s>Math.max(f,v)))if(sc||Math.abs(Xi(i,f))>r)return!0;return!1};Wi.filter=function(e,t){var n=[e[0]],r=0,a=0;function i(i){e.push(i);var o=n.length,l=r;n.splice(a+1);for(var s=l+1;s1&&i(e.pop());return{addPt:i,raw:e,filtered:n}};var Qi=cr.makeEventData,$i=Vr.getFromId,Ki=Jr,eo=Dt.MINSELECT,to=Yi.filter,no=Yi.tester,ro=Yi.multitester;function ao(e){return e._id}function io(e,t,n){var r,a,i,o;if(n){var l=n.points||[];for(r=0;rr^h>r&&n<(d-c)*(r-u)/(h-u)+c&&(a=!a)}return a}(e[0],n))return e.push(t),!0})||e.push([t])}),i=[],e.length?e.length>1?{type:"MultiPolygon",coordinates:e}:{type:"Polygon",coordinates:e[0]}:null}},c={Point:o,MultiPoint:o,LineString:l,MultiLineString:l,Polygon:s,MultiPolygon:s,Sphere:s};function u(){}var f=1e-6,d=f*f,h=Math.PI,p=h/2,g=(Math.sqrt(h),h/180),v=180/h;function y(e){return e>1?p:e<-1?-p:Math.asin(e)}function m(e){return e>1?0:e<-1?h:Math.acos(e)}var x=e.geo.projection,b=e.geo.projectionMutator;function _(e,t){var n=(2+p)*Math.sin(t);t/=2;for(var r=0,a=1/0;r<10&&Math.abs(a)>f;r++){var i=Math.cos(t);t-=a=(t+Math.sin(t)*(i+2)-n)/(2*i*(1+i))}return[2/Math.sqrt(h*(4+h))*e*(1+Math.cos(t)),2*Math.sqrt(h/(4+h))*Math.sin(t)]}e.geo.interrupt=function(t){var n,r=[[[[-h,0],[0,p],[h,0]]],[[[-h,0],[0,-p],[h,0]]]];function a(e,n){for(var a=n<0?-1:1,i=r[+(n<0)],o=0,l=i.length-1;oi[o][2][0];++o);var s=t(e-i[o][1][0],n);return s[0]+=t(i[o][1][0],a*n>a*i[o][0][1]?i[o][0][1]:n)[0],s}t.invert&&(a.invert=function(e,i){for(var o=n[+(i<0)],l=r[+(i<0)],c=0,u=o.length;c=0;--a){var o=r[1][a],s=180*o[0][0]/h,c=180*o[0][1]/h,u=180*o[1][1]/h,f=180*o[2][0]/h,d=180*o[2][1]/h;n.push(l([[f-t,d-t],[f-t,u+t],[s+t,u+t],[s+t,c-t]],30))}return{type:"Polygon",coordinates:[e.merge(n)]}}(),s)},a},i.lobes=function(e){return arguments.length?(r=e.map(function(e){return e.map(function(e){return[[e[0][0]*h/180,e[0][1]*h/180],[e[1][0]*h/180,e[1][1]*h/180],[e[2][0]*h/180,e[2][1]*h/180]]})}),n=r.map(function(e){return e.map(function(e){var n,r=t(e[0][0],e[0][1])[0],a=t(e[2][0],e[2][1])[0],i=t(e[1][0],e[0][1])[1],o=t(e[1][0],e[1][1])[1];return i>o&&(n=i,i=o,o=n),[[r,i],[a,o]]})}),i):r.map(function(e){return e.map(function(e){return[[180*e[0][0]/h,180*e[0][1]/h],[180*e[1][0]/h,180*e[1][1]/h],[180*e[2][0]/h,180*e[2][1]/h]]})})},i},_.invert=function(e,t){var n=.5*t*Math.sqrt((4+h)/h),r=y(n),a=Math.cos(r);return[e/(2/Math.sqrt(h*(4+h))*(1+a)),y((r+n*(a+2))/(2+p))]},(e.geo.eckert4=function(){return x(_)}).raw=_;var w=e.geo.azimuthalEqualArea.raw;function k(e,t){if(arguments.length<2&&(t=e),1===t)return w;if(t===1/0)return M;function n(n,r){var a=w(n/t,r);return a[0]*=e,a}return n.invert=function(n,r){var a=w.invert(n/e,r);return a[0]*=t,a},n}function M(e,t){return[e*Math.cos(t)/Math.cos(t/=2),2*Math.sin(t)]}function A(e,t){return[3*e/(2*h)*Math.sqrt(h*h/3-t*t),t]}function T(e,t){return[e,1.25*Math.log(Math.tan(h/4+.4*t))]}function L(e){return function(t){var n,r=e*Math.sin(t),a=30;do{t-=n=(t+Math.sin(t)-r)/(1+Math.cos(t))}while(Math.abs(n)>f&&--a>0);return t/2}}M.invert=function(e,t){var n=2*y(t/2);return[e*Math.cos(n/2)/Math.cos(n),n]},(e.geo.hammer=function(){var e=2,t=b(k),n=t(e);return n.coefficient=function(n){return arguments.length?t(e=+n):e},n}).raw=k,A.invert=function(e,t){return[2/3*h*e/Math.sqrt(h*h/3-t*t),t]},(e.geo.kavrayskiy7=function(){return x(A)}).raw=A,T.invert=function(e,t){return[e,2.5*Math.atan(Math.exp(.8*t))-.625*h]},(e.geo.miller=function(){return x(T)}).raw=T,L(h);var S=function(e,t,n){var r=L(n);function a(n,a){return[e*n*Math.cos(a=r(a)),t*Math.sin(a)]}return a.invert=function(r,a){var i=y(a/t);return[r/(e*Math.cos(i)),y((2*i+Math.sin(2*i))/n)]},a}(Math.SQRT2/p,Math.SQRT2,h);function C(e,t){var n=t*t,r=n*n;return[e*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),t*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}(e.geo.mollweide=function(){return x(S)}).raw=S,C.invert=function(e,t){var n,r=t,a=25;do{var i=r*r,o=i*i;r-=n=(r*(1.007226+i*(.015085+o*(.028874*i-.044475-.005916*o)))-t)/(1.007226+i*(.045255+o*(.259866*i-.311325-.005916*11*o)))}while(Math.abs(n)>f&&--a>0);return[e/(.8707+(i=r*r)*(i*(i*i*i*(.003971-.001529*i)-.013791)-.131979)),r]},(e.geo.naturalEarth=function(){return x(C)}).raw=C;var P=[[.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]];function z(e,t){var n,r=Math.min(18,36*Math.abs(t)/h),a=Math.floor(r),i=r-a,o=(n=P[a])[0],l=n[1],s=(n=P[++a])[0],c=n[1],u=(n=P[Math.min(19,++a)])[0],f=n[1];return[e*(s+i*(u-o)/2+i*i*(u-2*s+o)/2),(t>0?p:-p)*(c+i*(f-l)/2+i*i*(f-2*c+l)/2)]}function O(e,t){return[e*Math.cos(t),t]}function D(e,t){var n,r=Math.cos(t),a=(n=m(r*Math.cos(e/=2)))?n/Math.sin(n):1;return[2*r*Math.sin(e)*a,Math.sin(t)*a]}function E(e,t){var n=D(e,t);return[(n[0]+e/p)/2,(n[1]+t)/2]}P.forEach(function(e){e[1]*=1.0144}),z.invert=function(e,t){var n=t/p,r=90*n,a=Math.min(18,Math.abs(r/5)),i=Math.max(0,Math.floor(a));do{var o=P[i][1],l=P[i+1][1],s=P[Math.min(19,i+2)][1],c=s-o,u=s-2*l+o,f=2*(Math.abs(n)-l)/c,h=u/c,y=f*(1-h*f*(1-2*h*f));if(y>=0||1===i){r=(t>=0?5:-5)*(y+a);var m,x=50;do{y=(a=Math.min(18,Math.abs(r)/5))-(i=Math.floor(a)),o=P[i][1],l=P[i+1][1],s=P[Math.min(19,i+2)][1],r-=(m=(t>=0?p:-p)*(l+y*(s-o)/2+y*y*(s-2*l+o)/2)-t)*v}while(Math.abs(m)>d&&--x>0);break}}while(--i>=0);var b=P[i][0],_=P[i+1][0],w=P[Math.min(19,i+2)][0];return[e/(_+y*(w-b)/2+y*y*(w-2*_+b)/2),r*g]},(e.geo.robinson=function(){return x(z)}).raw=z,O.invert=function(e,t){return[e/Math.cos(t),t]},(e.geo.sinusoidal=function(){return x(O)}).raw=O,D.invert=function(e,t){if(!(e*e+4*t*t>h*h+f)){var n=e,r=t,a=25;do{var i,o=Math.sin(n),l=Math.sin(n/2),s=Math.cos(n/2),c=Math.sin(r),u=Math.cos(r),d=Math.sin(2*r),p=c*c,g=u*u,v=l*l,y=1-g*s*s,x=y?m(u*s)*Math.sqrt(i=1/y):i=0,b=2*x*u*l-e,_=x*c-t,w=i*(g*v+x*u*s*p),k=i*(.5*o*d-2*x*c*l),M=.25*i*(d*l-x*c*g*o),A=i*(p*s+x*v*u),T=k*M-A*w;if(!T)break;var L=(_*k-b*A)/T,S=(b*M-_*w)/T;n-=L,r-=S}while((Math.abs(L)>f||Math.abs(S)>f)&&--a>0);return[n,r]}},(e.geo.aitoff=function(){return x(D)}).raw=D,E.invert=function(e,t){var n=e,r=t,a=25;do{var i,o=Math.cos(r),l=Math.sin(r),s=Math.sin(2*r),c=l*l,u=o*o,d=Math.sin(n),h=Math.cos(n/2),g=Math.sin(n/2),v=g*g,y=1-u*h*h,x=y?m(o*h)*Math.sqrt(i=1/y):i=0,b=.5*(2*x*o*g+n/p)-e,_=.5*(x*l+r)-t,w=.5*i*(u*v+x*o*h*c)+.5/p,k=i*(d*s/4-x*l*g),M=.125*i*(s*g-x*l*u*d),A=.5*i*(c*h+x*v*o)+.5,T=k*M-A*w,L=(_*k-b*A)/T,S=(b*M-_*w)/T;n-=L,r-=S}while((Math.abs(L)>f||Math.abs(S)>f)&&--a>0);return[n,r]},(e.geo.winkel3=function(){return x(E)}).raw=E},fo=Math.PI/180,ho=180/Math.PI,po={cursor:"pointer"},go={cursor:"auto"};var vo=function(e,t){var n=e.projection;return(t._isScoped?xo:t._isClipped?_o:bo)(e,n)};function yo(t,n){return e.behavior.zoom().translate(n.translate()).scale(n.scale())}function mo(e,t,n){var r=e.id,a=e.graphDiv,i=a.layout[r],o=a._fullLayout[r],l={};function s(e,t){var n=nt.nestedProperty(o,e);n.get()!==t&&(n.set(t),nt.nestedProperty(i,e).set(t),l[r+"."+e]=t)}n(s),s("projection.scale",t.scale()/e.fitScale),a.emit("plotly_relayout",l)}function xo(t,n){var r=yo(0,n);function a(e){var r=n.invert(t.midPt);e("center.lon",r[0]),e("center.lat",r[1])}return r.on("zoomstart",function(){e.select(this).style(po)}).on("zoom",function(){n.scale(e.event.scale).translate(e.event.translate),t.render()}).on("zoomend",function(){e.select(this).style(go),mo(t,n,a)}),r}function bo(t,n){var r,a,i,o,l,s,c,u,f=yo(0,n),d=2;function h(e){return n.invert(e)}function p(e){var r=n.rotate(),a=n.invert(t.midPt);e("projection.rotation.lon",-r[0]),e("center.lon",a[0]),e("center.lat",a[1])}return f.on("zoomstart",function(){e.select(this).style(po),r=e.mouse(this),a=n.rotate(),i=n.translate(),o=a,l=h(r)}).on("zoom",function(){if(s=e.mouse(this),g=n(h(p=r)),Math.abs(g[0]-p[0])>d||Math.abs(g[1]-p[1])>d)return f.scale(n.scale()),void f.translate(n.translate());var p,g;n.scale(e.event.scale),n.translate([i[0],e.event.translate[1]]),l?h(s)&&(u=h(s),c=[o[0]+(u[0]-l[0]),a[1],a[2]],n.rotate(c),o=c):l=h(r=s),t.render()}).on("zoomend",function(){e.select(this).style(go),mo(t,n,p)}),f}function _o(t,n){var r,a={r:n.rotate(),k:n.scale()},i=yo(0,n),o=function(t){var n=0,r=arguments.length,a=[];for(;++nh?(i=(u>0?90:-90)-d,a=0):(i=Math.asin(u/h)*ho-d,a=Math.sqrt(h*h-u*u));var p=180-i-2*d,g=(Math.atan2(f,c)-Math.atan2(s,a))*ho,v=(Math.atan2(f,c)-Math.atan2(s,-a))*ho,y=ko(n[0],n[1],i,g),m=ko(n[0],n[1],p,v);return y<=m?[i,g,n[2]]:[p,v,n[2]]}(m,r,_);isFinite(M[0])&&isFinite(M[1])&&isFinite(M[2])||(M=_),n.rotate(M),_=M}}else r=wo(n,x=g);o.of(this,arguments)({type:"zoom"})}),m=o.of(this,arguments),l++||m({type:"zoomstart"})}).on("zoomend",function(){var r;e.select(this).style(go),s.call(i,"zoom",null),r=o.of(this,arguments),--l||r({type:"zoomend"}),mo(t,n,c)}).on("zoom.redraw",function(){t.render()}),e.rebind(i,o,"on")}function wo(e,t){var n=e.invert(t);return n&&isFinite(n[0])&&isFinite(n[1])&&function(e){var t=e[0]*fo,n=e[1]*fo,r=Math.cos(n);return[r*Math.cos(t),r*Math.sin(t),Math.sin(n)]}(n)}function ko(e,t,n,r){var a=Mo(n-e),i=Mo(r-t);return Math.sqrt(a*a+i*i)}function Mo(e){return(e%360+540)%360-180}function Ao(e,t,n){var r=n*fo,a=e.slice(),i=0===t?1:0,o=2===t?1:2,l=Math.cos(r),s=Math.sin(r);return a[i]=e[i]*l-e[o]*s,a[o]=e[o]*l+e[i]*s,a}function To(e,t){for(var n=0,r=0,a=e.length;ra*Math.PI/180}return!1},r.getPath=function(){return e.geo.path().projection(r)},r.getBounds=function(e){return r.getPath().bounds(e)},r.fitExtent=function(e,t){var n=e[1][0]-e[0][0],a=e[1][1]-e[0][1],i=r.clipExtent&&r.clipExtent();r.scale(150).translate([0,0]),i&&r.clipExtent(null);var o=r.getBounds(t),l=Math.min(n/(o[1][0]-o[0][0]),a/(o[1][1]-o[0][1])),s=+e[0][0]+(n-l*(o[1][0]+o[0][0]))/2,c=+e[0][1]+(a-l*(o[1][1]+o[0][1]))/2;return i&&r.clipExtent(i),r.scale(150*l).translate([s,c])},r.precision(Ci.precision),a&&r.clipAngle(a-Ci.clipPad);return r}(n);s.center([l.lon-o.lon,l.lat-o.lat]).rotate([-o.lon,-o.lat,o.roll]).parallels(i.parallels);var c=[[r.l+r.w*a.x[0],r.t+r.h*(1-a.y[1])],[r.l+r.w*a.x[1],r.t+r.h*(1-a.y[0])]],u=n.lonaxis,f=n.lataxis,d=function(e,t){var n=Ci.clipPad,r=e[0]+n,a=e[1]-n,i=t[0]+n,o=t[1]-n;r>0&&a<0&&(a+=360);var l=(a-r)/4;return{type:"Polygon",coordinates:[[[r,i],[r,o],[r+l,o],[r+2*l,o],[r+3*l,o],[a,o],[a,i],[a-l,i],[a-2*l,i],[a-3*l,i],[r,i]]]}}(u.range,f.range);s.fitExtent(c,d);var h=this.bounds=s.getBounds(d),p=this.fitScale=s.scale(),g=s.translate();if(!isFinite(h[0][0])||!isFinite(h[0][1])||!isFinite(h[1][0])||!isFinite(h[1][1])||isNaN(g[0])||isNaN(g[0])){for(var v=this.graphDiv,y=["projection.rotation","center","lonaxis.range","lataxis.range"],m="Invalid geo settings, relayout'ing to default view.",x={},b=0;b0&&b<0&&(b+=360);var _,w,k,M=(x+b)/2;if(!l){var A=s?i.projRotate:[M,0,0];_=n("projection.rotation.lon",A[0]),n("projection.rotation.lat",A[1]),n("projection.rotation.roll",A[2]),n("showcoastlines",!s)&&(n("coastlinecolor"),n("coastlinewidth")),n("showocean")&&n("oceancolor")}(l?(w=-96.6,k=38.7):(w=s?M:_,k=(m[0]+m[1])/2),n("center.lon",w),n("center.lat",k),c)&&n("projection.parallels",i.projParallels||[0,60]);n("projection.scale"),n("showland")&&n("landcolor"),n("showlakes")&&n("lakecolor"),n("showrivers")&&(n("rivercolor"),n("riverwidth")),n("showcountries",s&&"usa"!==a)&&(n("countrycolor"),n("countrywidth")),("usa"===a||"north america"===a&&50===r)&&(n("showsubunits",!0),n("subunitcolor"),n("subunitwidth")),s||n("showframe",!0)&&(n("framecolor"),n("framewidth")),n("bgcolor")}var Bo={},qo=Dt.SUBPLOT_PATTERN;Bo.getSubplotCalcData=function(e,t,n){var r=O.subplotsRegistry[t];if(!r)return[];for(var a=r.attr,i=[],o=0;o0&&e[t+1][0]<0)return t;return null}switch(t="RUS"===l||"FJI"===l?function(e){var t;if(null===c(e))t=e;else for(t=new Array(e.length),a=0;at?n[r++]=[e[a][0]+360,e[a][1]]:a===t?(n[r++]=e[a],n[r++]=[e[a][0],-90]):n[r++]=e[a];var i=Yi.tester(n);i.pts.pop(),s.push(i)}:function(e){s.push(Yi.tester(e))},i.type){case"MultiPolygon":for(n=0;n0;o&&(a="array");var l,s=n("categoryorder",a);"array"===s&&(l=n("categoryarray")),o||"array"!==s||(s=t.categoryorder="trace"),"trace"===s?t._initialCategories=[]:"array"===s?t._initialCategories=l.slice():(l=function(e,t){var n,r,a,i=t.dataAttr||e._id.charAt(0),o={};if(t.axData)n=t.axData;else for(n=[],r=0;rp[1]-.01&&(n.domain=o),nt.noneOrAll(e.domain,n.domain,o)}return r("layer"),n},wl=y.extendFlat,kl=pn.LINE_SPACING,Ml={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},Al=function(t,n){var r={};function a(){var o=t._fullLayout,s=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var c,u,f=e.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),d=[],h=[],p="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,y=r.levels.size,m=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(u=0;u<1e5&&(c=r.levels.start+u*y,!(y>0?c>=v:c<=v));u++)c>m&&c0?c>=v:c<=v));u++)c>f[0]&&c1){var H=Math.pow(10,Math.floor(Math.log(q)/Math.LN10));j*=H*nt.roundUp(q/H,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(I.tick0=0)}I.dtick=j}I.domain=[D+C,D+T-C],I.setScale();var V=nt.ensureSingle(o._infolayer,"g",n,function(t){t.classed(Ml.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(Ml.cbbg,!0),t.append("g").classed(Ml.cbfills,!0),t.append("g").classed(Ml.cblines,!0),t.append("g").classed(Ml.cbaxis,!0).classed(Ml.crisp,!0),t.append("g").classed(Ml.cbtitleunshift,!0).append("g").classed(Ml.cbtitle,!0),t.append("rect").classed(Ml.cboutline,!0),t.select(".cbtitle").datum(0)})});V.attr("transform","translate("+Math.round(s.l)+","+Math.round(s.t)+")");var U=V.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(s.l)+",-"+Math.round(s.t)+")");I._axislayer=V.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var Y,X=s.l+(r.x+L)*s.w,Z=I.titlefont.size;Y="top"===r.titleside?(1-(D+T-C))*s.h+s.t+3+.75*Z:(1-(D+C))*s.h+s.t-3-.25*Z,ee(I._id+"title",{attributes:{x:X,y:Y,"text-anchor":"start"}})}var W,J,Q,$=nt.syncOrAsync([Qr.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var n=V.select(".cbtitle"),a=n.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],c=n.select(".h"+I._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*kl),c?(G=Vn.bBox(c).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(Ml.jsPlaceholder)&&(G=Vn.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)I.domain[1]-=G/s.h,i[1]*=-1;else{I.domain[0]+=G/s.h;var v=yn.lineCount(a);i[1]+=(1-v)*u}n.attr("transform","translate("+i+")"),I.setScale()}}V.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(s.h*(1-I.domain[1]))+")"),I._axislayer.attr("transform","translate(0,"+Math.round(-s.t)+")");var y=V.select(".cbfills").selectAll("rect.cbfill").data(h);y.enter().append("rect").classed(Ml.cbfill,!0).style("stroke","none"),y.exit().remove(),y.each(function(t,n){var r=[0===n?f[0]:(h[n]+h[n-1])/2,n===h.length-1?f[1]:(h[n]+h[n+1])/2].map(I.c2p).map(Math.round);n!==h.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=l(a).toHexString();e.select(this).attr({x:P,width:Math.max(k,2),y:e.min(r),height:Math.max(e.max(r)-e.min(r),2),fill:i})});var m=V.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?d:[]);return m.enter().append("path").classed(Ml.cbline,!0),m.exit().remove(),m.each(function(t){e.select(this).attr("d","M"+P+","+(Math.round(I.c2p(t))+r.line.width/2%1)+"h"+k).call(Vn.lineGroupStyle,r.line.width,p(t),r.line.dash)}),I._axislayer.selectAll("g."+I._id+"tick,path").remove(),I._pos=P+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),I.side="right",nt.syncOrAsync([function(){return Da.doTicks(t,I,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var n=I.titlefont.size,a=I._offset+I._length/2,i=s.l+(I.position||0)*s.w+("right"===I.side?10+n*(I.showticklabels?1:.5):-10-n*(I.showticklabels?.5:0));ee("h"+I._id+"title",{avoid:{selection:e.select(t).selectAll("g."+I._id+"tick"),side:r.titleside,offsetLeft:s.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Qr.previousPromises,function(){var e=k+r.outlinewidth/2+Vn.bBox(I._axislayer.node()).width;if((b=U.select("text")).node()&&!b.classed(Ml.jsPlaceholder)){var a,i=U.select(".h"+I._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Vn.bBox(i).width:Vn.bBox(U.node()).right-P-s.l,e=Math.max(e,a)}var o=2*r.xpad+e+r.borderwidth+r.outlinewidth/2,l=E-R;V.select(".cbbg").attr({x:P-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:R-S,width:Math.max(o,2),height:Math.max(l+2*S,2)}).call(dt.fill,r.bgcolor).call(dt.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),V.selectAll(".cboutline").attr({x:P,y:R+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(l-2*r.ypad-G,2)}).call(dt.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*o;V.attr("transform","translate("+(s.l-c)+","+s.t+")"),Qr.autoMargin(t,n,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:l*({bottom:1,middle:.5}[r.yanchor]||0),b:l*({top:1,middle:.5}[r.yanchor]||0)})}],t);if($&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition)Et.init({element:V.node(),gd:t,prepFn:function(){W=V.attr("transform"),hr(V)},moveFn:function(e,t){V.attr("transform",W+" translate("+e+","+t+")"),J=Et.align(z+e/s.w,M,0,1,r.xanchor),Q=Et.align(D-t/s.h,T,0,1,r.yanchor);var n=Et.getCursor(J,Q,r.xanchor,r.yanchor);hr(V,n)},doneFn:function(){hr(V),void 0!==J&&void 0!==Q&&O.call("restyle",t,{"colorbar.x":J,"colorbar.y":Q},i().index)}});return $}function K(e,t){return nt.coerce(N,I,en,e,t)}function ee(e,n){var r,a=i();r=O.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:I,propName:r,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:V.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;V.selectAll("."+s+",."+s+"-math-group").remove(),fa.draw(t,e,wl(l,n||{}))}o._infolayer.selectAll("g."+n).remove()}function i(){var e,r,a=n.substr(2);for(e=0;ei&&(t.z=l.slice(0,i)),a("locationmode"),a("text"),a("marker.line.color"),a("marker.line.width"),a("marker.opacity"),cn(e,t,r,a,{prefix:"",cLetter:"z"}),nt.coerceSelectionMarkerOpacity(t,a)):t.visible=!1}else t.visible=!1},Tl.colorbar=function(e,n){var r=n[0].trace,a="cb"+r.uid,i=r.zmin,o=r.zmax;if(t(i)||(i=nt.aggNums(Math.min,null,r.z)),t(o)||(o=nt.aggNums(Math.max,null,r.z)),e._fullLayout._infolayer.selectAll("."+a).remove(),r.showscale){var l=n[0].t.cb=Al(e,a),s=dn.makeColorScaleFunc(dn.extractScale(r.colorscale,i,o),{noNumericCheck:!0});l.fillcolor(s).filllevels({start:i,end:o,size:(o-i)/254}).options(r.colorbar)()}else Qr.autoMargin(e,a)},Tl.calc=function(e,n){for(var r=n.locations.length,a=new Array(r),i=0;i")}(e,s,r,c.mockAxis),[e]},Tl.eventData=function(e,t){return e.location=t.location,e.z=t.z,e},Tl.selectPoints=function(e,t){var n,r,a,i,o,l=e.cd,s=e.xaxis,c=e.yaxis,u=[];if(!1===t)for(n=0;n1)for(var n=1;n=0,p=n.indexOf("end")>=0,g=c.backoff*f+r.standoff,v=u.backoff*d+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var y=a.x-i.x,m=a.y-i.y;if(l=(o=Math.atan2(m,y))+Math.PI,g&&v&&g+v>Math.sqrt(y*y+m*m))return void C();if(g){if(g*g>y*y+m*m)return void C();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>y*y+m*m)return void C();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var k=s.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[t]}n._w=S,n._h=C;for(var E=!1,R=["x","y"],N=0;N1)&&(U===V?((K=G.r2fraction(n["a"+H]))<0||K>1)&&(E=!0):E=!0,E))continue;I=G._offset+G.r2p(n[H]),B=.5}else"x"===H?(j=n[H],I=u.l+u.w*j):(j=1-n[H],I=u.t+u.h*j),B=n.showarrow?.5:j;if(n.showarrow){$.head=I;var ee=n["a"+H];q=X*D(.5,n.xanchor)-Z*D(.5,n.yanchor),U===V?($.tail=G._offset+G.r2p(ee),F=q):($.tail=I+ee,F=q+ee),$.text=$.tail+q;var te=c["x"===H?"width":"height"];if("paper"===V&&($.head=nt.constrain($.head,1,te-1)),"pixel"===U){var ne=-Math.max($.tail-3,$.text),re=Math.min($.tail+3,$.text)-te;ne>0?($.tail+=ne,$.text+=ne):re>0&&($.tail-=re,$.text-=re)}$.tail+=Q,$.head+=Q}else F=q=W*D(B,J),$.text=I+q;$.text+=Q,q+=Q,F+=Q,n["_"+H+"padplus"]=W/2+F,n["_"+H+"padminus"]=W/2-F,n["_"+H+"size"]=W,n["_"+H+"shift"]=q}if(E)x.remove();else{var ae=0,ie=0;if("left"!==n.align&&(ae=(S-_)*("center"===n.align?.5:1)),"top"!==n.valign&&(ie=(C-T)*("middle"===n.valign?.5:1)),l)r.select("svg").attr({x:w+ae-1,y:w+ie}).call(Vn.setClipUrl,M?d:null);else{var oe=w+ie-m.top,le=w+ae-m.left;L.call(yn.positionText,le,oe).call(Vn.setClipUrl,M?d:null)}A.select("rect").call(Vn.setRect,w,w,S,C),k.call(Vn.setRect,b/2,b/2,P-b,z-b),x.call(Vn.setTranslate,Math.round(h.x.text-P/2),Math.round(h.y.text-z/2)),v.attr({transform:"rotate("+p+","+h.x.text+","+h.y.text+")"});var se,ce,ue=function(e,r){g.selectAll(".annotation-arrow-g").remove();var l=h.x.head,c=h.y.head,d=h.x.tail+e,y=h.y.tail+r,m=h.x.text+e,b=h.y.text+r,_=nt.rotationXYMatrix(p,m,b),w=nt.apply2DTransform(_),M=nt.apply2DTransform2(_),A=+k.attr("width"),T=+k.attr("height"),L=m-.5*A,S=L+A,C=b-.5*T,P=C+T,z=[[L,C,L,P],[L,P,S,P],[S,P,S,C],[S,C,L,C]].map(M);if(!z.reduce(function(e,t){return e^!!nt.segmentsIntersect(l,c,l+1e6,c+1e6,t[0],t[1],t[2],t[3])},!1)){z.forEach(function(e){var t=nt.segmentsIntersect(d,y,l,c,e[0],e[1],e[2],e[3]);t&&(d=t.x,y=t.y)});var D=n.arrowwidth,E=n.arrowcolor,R=n.arrowside,N=g.append("g").style({opacity:dt.opacity(E)}).classed("annotation-arrow-g",!0),I=N.append("path").attr("d","M"+d+","+y+"L"+l+","+c).style("stroke-width",D+"px").call(dt.stroke,dt.rgb(E));if(Jl(I,R,n),f.annotationPosition&&I.node().parentNode&&!a){var F=l,j=c;if(n.standoff){var B=Math.sqrt(Math.pow(l-d,2)+Math.pow(c-y,2));F+=n.standoff*(d-l)/B,j+=n.standoff*(y-c)/B}var q,H,V,U=N.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-F)+","+(y-j),transform:"translate("+F+","+j+")"}).style("stroke-width",D+6+"px").call(dt.stroke,"rgba(0,0,0,0)").call(dt.fill,"rgba(0,0,0,0)");Et.init({element:U.node(),gd:t,prepFn:function(){var e=Vn.getTranslate(x);H=e.x,V=e.y,q={},i&&i.autorange&&(q[i._name+".autorange"]=!0),o&&o.autorange&&(q[o._name+".autorange"]=!0)},moveFn:function(e,t){var r=w(H,V),a=r[0]+e,l=r[1]+t;x.call(Vn.setTranslate,a,l),q[s+".x"]=i?i.p2r(i.r2p(n.x)+e):n.x+e/u.w,q[s+".y"]=o?o.p2r(o.r2p(n.y)+t):n.y-t/u.h,n.axref===n.xref&&(q[s+".ax"]=i.p2r(i.r2p(n.ax)+e)),n.ayref===n.yref&&(q[s+".ay"]=o.p2r(o.r2p(n.ay)+t)),N.attr("transform","translate("+e+","+t+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){O.call("relayout",t,q);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(n.showarrow&&ue(0,0),y)Et.init({element:x.node(),gd:t,prepFn:function(){ce=v.attr("transform"),se={}},moveFn:function(e,t){var r="pointer";if(n.showarrow)n.axref===n.xref?se[s+".ax"]=i.p2r(i.r2p(n.ax)+e):se[s+".ax"]=n.ax+e,n.ayref===n.yref?se[s+".ay"]=o.p2r(o.r2p(n.ay)+t):se[s+".ay"]=n.ay+t,ue(e,t);else{if(a)return;if(i)se[s+".x"]=i.p2r(i.r2p(n.x)+e);else{var l=n._xsize/u.w,c=n.x+(n._xshift-n.xshift)/u.w-l/2;se[s+".x"]=Et.align(c+e/u.w,l,0,1,n.xanchor)}if(o)se[s+".y"]=o.p2r(o.r2p(n.y)+t);else{var f=n._ysize/u.h,d=n.y-(n._yshift+n.yshift)/u.h-f/2;se[s+".y"]=Et.align(d-t/u.h,f,0,1,n.yanchor)}i&&o||(r=Et.getCursor(i?.5:se[s+".x"],o?.5:se[s+".y"],n.xanchor,n.yanchor))}v.attr({transform:"translate("+e+","+t+")"+ce}),hr(x,r)},doneFn:function(){hr(x),O.call("relayout",t,se);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var es=Ql.draw;function ts(e){var t=e._fullLayout;nt.filterVisible(t.annotations).forEach(function(t){var n,r,a,i,o=Da.getFromId(e,t.xref),l=Da.getFromId(e,t.yref),s=3*t.arrowsize*t.arrowwidth||0,c=3*t.startarrowsize*t.arrowwidth||0;o&&o.autorange&&(n=s+t.xshift,r=s-t.xshift,a=c+t.xshift,i=c-t.xshift,t.axref===t.xref?(Da.expand(o,[o.r2c(t.x)],{ppadplus:n,ppadminus:r}),Da.expand(o,[o.r2c(t.ax)],{ppadplus:Math.max(t._xpadplus,a),ppadminus:Math.max(t._xpadminus,i)})):(a=t.ax?a+t.ax:a,i=t.ax?i-t.ax:i,Da.expand(o,[o.r2c(t.x)],{ppadplus:Math.max(t._xpadplus,n,a),ppadminus:Math.max(t._xpadminus,r,i)}))),l&&l.autorange&&(n=s-t.yshift,r=s+t.yshift,a=c-t.yshift,i=c+t.yshift,t.ayref===t.yref?(Da.expand(l,[l.r2c(t.y)],{ppadplus:n,ppadminus:r}),Da.expand(l,[l.r2c(t.ay)],{ppadplus:Math.max(t._ypadplus,a),ppadminus:Math.max(t._ypadminus,i)})):(a=t.ay?a+t.ay:a,i=t.ay?i-t.ay:i,Da.expand(l,[l.r2c(t.y)],{ppadplus:Math.max(t._ypadplus,n,a),ppadminus:Math.max(t._ypadminus,r,i)})))})}var ns={hasClickToShow:function(e,t){var n=rs(e,t);return n.on.length>0||n.explicitOff.length>0},onClick:function(e,t){var n,r=rs(e,t),a=r.on,i=r.off.concat(r.explicitOff),o={};if(!a.length&&!i.length)return;for(n=0;n1){o=!0;break}}o?e.fullLayout._infolayer.select(".annotation-"+e.id+'[data-index="'+a+'"]').remove():(i._pdata=ps(e.glplot.cameraParams,[t.xaxis.r2l(i.x)*n[0],t.yaxis.r2l(i.y)*n[1],t.zaxis.r2l(i.z)*n[2]]),gs(e.graphDiv,i,a,e.id,i._xa,i._ya))}}};var ms={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},xs=function(e){var t=e.type,n=e.symmetric;if("data"===t){var r=e.array||[];if(n)return function(e,t){var n=+r[t];return[n,n]};var a=e.arrayminus||[];return function(e,t){var n=+r[t],i=+a[t];return isNaN(n)&&isNaN(i)?[NaN,NaN]:[i||0,n||0]}}var i=bs(t,e.value),o=bs(t,e.valueminus);return n||void 0===e.valueminus?function(e){var t=i(e);return[t,t]}:function(e){return[o(e),i(e)]}};function bs(e,t){return"percent"===e?function(e){return Math.abs(e*t/100)}:"constant"===e?function(){return Math.abs(t)}:"sqrt"===e?function(e){return Math.sqrt(Math.abs(e))}:void 0}var _s=function(e){for(var t=e.calcdata,n=0;n0;n.each(function(n){var s,c=n[0].trace,u=c.error_x||{},f=c.error_y||{};c.ids&&(s=function(e){return e.id});var d=Hn.hasMarkers(c)&&c.marker.maxdisplayed>0;f.visible||u.visible||(n=[]);var h=e.select(this).selectAll("g.errorbar").data(n,s);if(h.exit().remove(),n.length){u.visible||h.selectAll("path.xerror").remove(),f.visible||h.selectAll("path.yerror").remove(),h.style("opacity",1);var p=h.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Vn.setClipUrl(h,r.layerClipId),h.each(function(n){var r=e.select(this),s=function(e,n,r){var a={x:n.c2p(e.x),y:r.c2p(e.y)};return void 0!==e.yh&&(a.yh=r.c2p(e.yh),a.ys=r.c2p(e.ys),t(a.ys)||(a.noYS=!0,a.ys=r.c2p(e.ys,!0))),void 0!==e.xh&&(a.xh=n.c2p(e.xh),a.xs=n.c2p(e.xs),t(a.xs)||(a.noXS=!0,a.xs=n.c2p(e.xs,!0))),a}(n,i,o);if(!d||n.vis){var c,h=r.select("path.yerror");if(f.visible&&t(s.x)&&t(s.yh)&&t(s.ys)){var p=f.width;c="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(c+="m-"+p+",0h"+2*p),h.size()?l&&(h=h.transition().duration(a.duration).ease(a.easing)):h=r.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),h.attr("d",c)}else h.remove();var g=r.select("path.xerror");if(u.visible&&t(s.y)&&t(s.xh)&&t(s.xs)){var v=(u.copy_ystyle?f:u).width;c="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(c+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=r.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",c)}else g.remove()}})}})},style:function(t){t.each(function(t){var n=t[0].trace,r=n.error_y||{},a=n.error_x||{},i=e.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(dt.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(dt.stroke,a.color)})},hoverInfo:function(e,t,n){(t.error_y||{}).visible&&(n.yerr=e.yh-e.y,t.error_y.symmetric||(n.yerrneg=e.y-e.ys));(t.error_x||{}).visible&&(n.xerr=e.xh-e.x,t.error_x.symmetric||(n.xerrneg=e.x-e.xs))}};var Ls=ee.counter,Ss=zo.attributes,Cs=Dt.idRegex,Ps={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:!0,dimensions:2,items:{valType:"enumerated",values:[Ls("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[Cs.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[Cs.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:Ss({name:"grid",editType:"plot",noGridCell:!0},{}),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 zs(e,t,n){var r=t[n+"axes"],a=Object.keys((e._splomAxes||{})[n]||{});return Array.isArray(r)?r:a.length?a:void 0}function Os(e,t,n,r,a,i){var o=t(e+"gap",n),l=t("domain."+e);t(e+"side",r);for(var s=new Array(a),c=l[0],u=(l[1]-c)/(a-o),f=u*(1-o),d=0;d1){l||s||c||"independent"===x("pattern")&&(l=!0),f._hasSubplotGrid=l;var p,g,v="top to bottom"===x("roworder"),y=l?.2:.1,m=l?.3:.1;u&&(p="bottom",g="left"),f._domains={x:Os("x",x,y,p,h),y:Os("y",x,m,g,d,v)}}}function x(e,t){return nt.coerce(n,f,Ps,e,t)}},contentDefaults:function(e,t){var n=t.grid;if(n&&n._domains){var r,a,i,o,l,s,c,u=e.grid||{},f=t._subplots,d=n._hasSubplotGrid,h=n.rows,p=n.columns,g="independent"===n.pattern,v=n._axisMap={};if(d){var y=u.subplots||[];s=n.subplots=new Array(h);var m=1;for(r=0;r=2/3},isCenterAnchor:function(e){return"center"===e.xanchor||"auto"===e.xanchor&&e.x>1/3&&e.x<2/3},isBottomAnchor:function(e){return"bottom"===e.yanchor||"auto"===e.yanchor&&e.y<=1/3},isMiddleAnchor:function(e){return"middle"===e.yanchor||"auto"===e.yanchor&&e.y>1/3&&e.y<2/3}},qs={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Hs=!0,Vs=function(e,t,n){if(!t._dragged&&!t._editing){var r,a,i,o,l,s=t._fullLayout.hiddenlabels?t._fullLayout.hiddenlabels.slice():[],c=e.data()[0][0],u=t._fullData,f=c.trace,d=f.legendgroup,h={},p=[],g=[],v=[];if(1===n&&Hs&&t.data&&t._context.showTips?(nt.notifier(nt._(t,"Double-click on legend to isolate one trace"),"long"),Hs=!1):Hs=!1,O.traceIs(f,"pie")){var y=c.label,m=s.indexOf(y);1===n?-1===m?s.push(y):s.splice(m,1):2===n&&(s=[],t.calcdata[0].forEach(function(e){y!==e.label&&s.push(e.label)}),t._fullLayout.hiddenlabels&&t._fullLayout.hiddenlabels.length===s.length&&-1===m&&(s=[])),O.call("relayout",t,"hiddenlabels",s)}else{var x,b=d&&d.length,_=[];if(b)for(r=0;rn[1])return n[1]}return a}function f(e){return e[0]}if(l||s||c){var d={},h={};l&&(d.mc=u("marker.color",f),d.mo=u("marker.opacity",nt.mean,[.2,1]),d.ms=u("marker.size",nt.mean,[2,16]),d.mlc=u("marker.line.color",f),d.mlw=u("marker.line.width",nt.mean,[0,5]),h.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),c&&(h.line={width:u("line.width",f,[0,10])}),s&&(d.tx="Aa",d.tp=u("textposition",f),d.ts=10,d.tc=u("textfont.color",f),d.tf=u("textfont.family",f)),r=[nt.minExtend(i,d)],a=nt.minExtend(o,h)}var p=e.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Vn.pointStyle,a,n),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Vn.textPointStyle,a,n)}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(e,t){return t?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("stroke-width",i+"px").call(dt.fill,a.fillcolor),i&&dt.stroke(o,a.line.color)})}).each(function(t){var n=t[0].trace,r=e.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===n.type&&n.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(e,t){return t?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=n[r?"increasing":"decreasing"],i=a.line.width,o=e.select(this);o.style("fill","none").call(Vn.dashLine,a.line.dash,i),i&&dt.stroke(o,a.line.color)})})},Zs=pn.LINE_SPACING,Ws=pn.FROM_TL,Js=pn.FROM_BR,Qs=d.DBLCLICKDELAY;function $s(e,t){var n=e.data()[0][0],r=t._fullLayout,a=n.trace,i=O.traceIs(a,"pie"),o=a.index,l=i?n.label:a.name,s=nt.ensureSingle(e,"text","legendtext");function c(n){yn.convertToTspans(n,t,function(){!function(e,t){var n=e.data()[0][0];if(!n.trace.showlegend)return void e.remove();var r,a,i=e.select("g[class*=math-group]"),o=i.node(),l=t._fullLayout.legend.font.size*Zs;if(o){var s=Vn.bBox(o);r=s.height,a=s.width,Vn.setTranslate(i,0,r/4)}else{var c=e.select(".legendtext"),u=yn.lineCount(c),f=c.node();r=l*u,a=f?Vn.bBox(f).width:0;var d=l*(.3+(1-u)/2);yn.positionText(c,40,d)}r=Math.max(r,16)+3,n.height=r,n.width=a}(e,t)})}s.attr("text-anchor","start").classed("user-select-none",!0).call(Vn.font,r.legend.font).text(l),t._context.edits.legendText&&!i?s.call(yn.makeEditable,{gd:t}).call(c).on("edit",function(e){this.text(e).call(c);var r=e;this.text()||(e=" ");var a=n.trace._fullInput||{},i={};if(O.hasTransform(a,"groupby")){var l=O.getTransformIndices(a,"groupby"),s=l[l.length-1],u=nt.keyedContainer(a,"transforms["+s+"].styles","target","value.name");""===r?u.remove(n.trace._group):u.set(n.trace._group,e),i=u.constructUpdate()}else i.name=e;return O.call("restyle",t,i,o)}):c(s)}function Ks(e,t){var n,r=1,a=nt.ensureSingle(e,"rect","legendtoggle",function(e){e.style("cursor","pointer").attr("pointer-events","all").call(dt.fill,"rgba(0,0,0,0)")});a.on("mousedown",function(){(n=(new Date).getTime())-t._legendMouseDownTimeQs&&(r=Math.max(r-1,1)),1===r?n._clickTimeout=setTimeout(function(){Vs(e,t,r)},Qs):2===r&&(n._clickTimeout&&clearTimeout(n._clickTimeout),t._legendMouseDownTime=0,Vs(e,t,r))}})}function ec(t,n,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=js.isGrouped(i),s=0;if(i._width=0,i._height=0,js.isVertical(i))l&&n.each(function(e,t){Vn.setTranslate(this,0,t*i.tracegroupgap)}),r.each(function(e){var t=e[0],n=t.height,r=t.width;Vn.setTranslate(this,o,5+o+i._height+n/2),i._height+=n,i._width=Math.max(i._width,r)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var c=[i._width],u=n.data(),f=0,d=u.length;fo+b-_,r.each(function(e){var t=e[0],n=g?40+e[0].width:m;o+x+_+n>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=y,i._height=i._height+y,y=0),Vn.setTranslate(this,o+x,5+o+t.height/2+v),i._width+=_+n,i._height=Math.max(i._height,t.height),x+=_+n,y=Math.max(t.height,y)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(n){var r=n[0],a=e.select(this).select(".legendtoggle");Vn.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function tc(e){var t=e._fullLayout.legend,n="left";Bs.isRightAnchor(t)?n="right":Bs.isCenterAnchor(t)&&(n="center");var r="top";Bs.isBottomAnchor(t)?r="bottom":Bs.isMiddleAnchor(t)&&(r="middle"),Qr.autoMargin(e,"legend",{x:t.x,y:t.y,l:t._width*Ws[n],r:t._width*Js[n],b:t._height*Js[r],t:t._height*Ws[r]})}var nc={moduleType:"component",name:"legend",layoutAttributes:Fs,supplyLayoutDefaults:function(e,t,n){for(var r,a,i,o,l=e.legend||{},s={},c=0,u="normal",f=0;f1)){if(t.legend=s,h("bgcolor",t.paper_bgcolor),h("bordercolor"),h("borderwidth"),nt.coerceFont(h,"font",t.font),h("orientation"),"h"===s.orientation){var p=e.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(r=0,i="left",a=1.1,o="bottom"):(r=0,i="left",a=-.1,o="top")}h("traceorder",u),js.isGrouped(t.legend)&&h("tracegroupgap"),h("x",r),h("xanchor",i),h("y",a),h("yanchor",o),nt.noneOrAll(l,s,["x","y"])}},draw:function(t){var n=t._fullLayout,r="legend"+n._uid;if(n._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=n.legend,i=n.showlegend&&function(e,t){var n,r,a={},i=[],o=!1,l={},s=0;function c(e,n){if(""!==e&&js.isGrouped(t))-1===i.indexOf(e)?(i.push(e),o=!0,a[e]=[[n]]):a[e].push([n]);else{var r="~~i"+s;i.push(r),a[r]=[[n]],s++}}for(n=0;nv?function(e){var t=e._fullLayout.legend,n="left";Bs.isRightAnchor(t)?n="right":Bs.isCenterAnchor(t)&&(n="center"),Qr.autoMargin(e,"legend",{x:t.x,y:.5,l:t._width*Ws[n],r:t._width*Js[n],b:0,t:0})}(t):tc(t);var y=n._size,m=y.l+y.w*a.x,x=y.t+y.h*(1-a.y);Bs.isRightAnchor(a)?m-=a._width:Bs.isCenterAnchor(a)&&(m-=a._width/2),Bs.isBottomAnchor(a)?x-=a._height:Bs.isMiddleAnchor(a)&&(x-=a._height/2);var b=a._width,_=y.w;b>_?(m=y.l,b=_):(m+b>g&&(m=g-b),m<0&&(m=0),b=Math.min(g-m,a._width));var w,k,M,A,T=a._height,L=y.h;if(T>L?(x=y.t,T=L):(x+T>v&&(x=v-T),x<0&&(x=0),T=Math.min(v-x,a._height)),Vn.setTranslate(s,m,x),d.on(".drag",null),s.on("wheel",null),a._height<=T||t._context.staticPlot)u.attr({width:b-a.borderwidth,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Vn.setTranslate(f,0,0),c.select("rect").attr({width:b-2*a.borderwidth,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Vn.setClipUrl(f,r),Vn.setRect(d,0,0,0,0),delete a._scrollY;else{var S,C,P=Math.max(qs.scrollBarMinHeight,T*T/a._height),z=T-P-2*qs.scrollBarMargin,D=a._height-T,E=z/D,R=Math.min(a._scrollY||0,D);u.attr({width:b-2*a.borderwidth+qs.scrollBarWidth+qs.scrollBarMargin,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),c.select("rect").attr({width:b-2*a.borderwidth+qs.scrollBarWidth+qs.scrollBarMargin,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+R}),Vn.setClipUrl(f,r),I(R,P,E),s.on("wheel",function(){I(R=nt.constrain(a._scrollY+e.event.deltaY/z*D,0,D),P,E),0!==R&&R!==D&&e.event.preventDefault()});var N=e.behavior.drag().on("dragstart",function(){S=e.event.sourceEvent.clientY,C=R}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||I(R=nt.constrain((t.clientY-S)/E+C,0,D),P,E)});d.call(N)}t._context.edits.legendPosition&&(s.classed("cursor-move",!0),Et.init({element:s.node(),gd:t,prepFn:function(){var e=Vn.getTranslate(s);M=e.x,A=e.y},moveFn:function(e,t){var n=M+e,r=A+t;Vn.setTranslate(s,n,r),w=Et.align(n,0,y.l,y.l+y.w,a.xanchor),k=Et.align(r,0,y.t+y.h,y.t,a.yanchor)},doneFn:function(){void 0!==w&&void 0!==k&&O.call("relayout",t,{"legend.x":w,"legend.y":k})},clickFn:function(e,r){var a=n._infolayer.selectAll("g.traces").filter(function(){var e=this.getBoundingClientRect();return r.clientX>=e.left&&r.clientX<=e.right&&r.clientY>=e.top&&r.clientY<=e.bottom});a.size()>0&&(1===e?s._clickTimeout=setTimeout(function(){Vs(a,t,e)},Qs):2===e&&(s._clickTimeout&&clearTimeout(s._clickTimeout),Vs(a,t,e)))}}))}function I(e,n,r){a._scrollY=t._fullLayout.legend._scrollY=e,Vn.setTranslate(f,0,-e),Vn.setRect(d,b,qs.scrollBarMargin+e*r,qs.scrollBarWidth,n),c.select("rect").attr({y:a.borderwidth+e})}},style:Xs},rc={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},ac=y.extendFlat,ic={visible:{valType:"boolean",editType:"plot"},buttons:rc=ac(rc,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:T({editType:"plot"}),bgcolor:{valType:"color",dflt:C.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:C.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},oc={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var lc=function(t,n){var r=t._name,a={};if("all"===n.step)a[r+".autorange"]=!0;else{var i=function(t,n){var r,a=t.range,i=new Date(t.r2l(a[1])),o=n.step,l=n.count;switch(n.stepmode){case"backward":r=t.l2r(+e.time[o].utc.offset(i,-l));break;case"todate":var s=e.time[o].utc.offset(i,-l);r=t.l2r(+e.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,n);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var sc=pn.LINE_SPACING,cc=pn.FROM_TL,uc=pn.FROM_BR;function fc(e){return e._id}function dc(e,t,n){var r=nt.ensureSingle(e,"rect","selector-rect",function(e){e.attr("shape-rendering","crispEdges")});r.attr({rx:oc.rx,ry:oc.ry}),r.call(dt.stroke,t.bordercolor).call(dt.fill,function(e,t){return t._isActive||t._isHovered?e.activecolor:e.bgcolor}(t,n)).style("stroke-width",t.borderwidth+"px")}function hc(e,t,n,r){var a;nt.ensureSingle(e,"text","selector-text",function(e){e.classed("user-select-none",!0).attr("text-anchor","middle")}).call(Vn.font,t.font).text((a=n,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(e){yn.convertToTspans(e,r)})}var pc={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:ic}}},layoutAttributes:ic,handleDefaults:function(e,t,n,r,a){var i=e.rangeselector||{},o=t.rangeselector={};function l(e,t){return nt.coerce(i,o,ic,e,t)}if(l("visible",function(e,t,n){var r,a,i=e.buttons||[],o=t.buttons=[];function l(e,t){return nt.coerce(r,a,rc,e,t)}for(var s=0;s0)){var s=function(e,t,n){for(var r=n.filter(function(n){return t[n].anchor===e._id}),a=0,i=0;i=0?Math.min(e,.9):1/(1/Math.max(e,-.3)+3.222))}function Ic(e,t,n,r,a){return e.append("path").attr("class","zoombox").style({fill:t>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+n+", "+r+")").attr("d",a+"Z")}function Fc(e,t,n){return e.append("path").attr("class","zoombox-corners").style({fill:dt.background,stroke:dt.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+t+", "+n+")").attr("d","M0,0Z")}function jc(e,t,n,r,a,i){e.attr("d",r+"M"+n.l+","+n.t+"v"+n.h+"h"+n.w+"v-"+n.h+"h-"+n.w+"Z"),Bc(e,t,a,i)}function Bc(e,t,n,r){n||(e.transition().style("fill",r>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),t.transition().style("opacity",1).duration(200))}function qc(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Hc(e){Pc&&e.data&&e._context.showTips&&(nt.notifier(nt._(e,"Double-click to zoom back out"),"long"),Pc=!1)}function Vc(e){return"lasso"===e||"select"===e}function Uc(e){var t=Math.floor(Math.min(e.b-e.t,e.r-e.l,Cc)/2);return"M"+(e.l-3.5)+","+(e.t-.5+t)+"h3v"+-t+"h"+t+"v-3h-"+(t+3)+"ZM"+(e.r+3.5)+","+(e.t-.5+t)+"h-3v"+-t+"h"+-t+"v-3h"+(t+3)+"ZM"+(e.r+3.5)+","+(e.b+.5-t)+"h-3v"+t+"h"+-t+"v3h"+(t+3)+"ZM"+(e.l-3.5)+","+(e.b+.5-t)+"h3v"+t+"h"+t+"v3h-"+(t+3)+"Z"}function Gc(e,t){if(mt){var n=void 0!==e.onwheel?"wheel":"mousewheel";e._onwheel&&e.removeEventListener(n,e._onwheel),e._onwheel=t,e.addEventListener(n,t,{passive:!1})}else void 0!==e.onwheel?e.onwheel=t:void 0!==e.onmousewheel&&(e.onmousewheel=t)}function Yc(e){var t=[];for(var n in e)t.push(e[n]);return t}var Xc={},Zc=function(t,n,r,a,i,o,s,c){var u,f,d,h,p,g,v,y,m,x,b,_,w,k,M,A,T,L=t._fullLayout._zoomlayer,S=s+c==="nsew",C=1===(s+c).length;function P(){if(u=n.xaxis,f=n.yaxis,m=u._length,x=f._length,v=u._offset,y=f._offset,(d={})[u._id]=u,(h={})[f._id]=f,s&&c)for(var e=n.overlays,r=0;rCc||o>Cc?(B="xy",i/m>o/x?(o=i*x/m,R>a?N.t=R-o:N.b=R+o):(i=o*m/x,E>r?N.l=E-i:N.r=E+i),H.attr("d",Uc(N))):l():!w||o10||n.scrollWidth-n.clientWidth>10)){clearTimeout(Z);var r=-e.deltaY;if(isFinite(r)||(r=e.wheelDelta/10),isFinite(r)){var a,i=Math.exp(-Math.min(Math.max(r,-20),20)/200),o=J.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(e.clientX-o.left)/o.width,u=(o.bottom-e.clientY)/o.height;if(A){for(c||(l=.5),a=0;a0&&a["_"+n+"axes"][t])return a;if((a[n+"axis"]||n)===t){if(tu(a,n))return a;if((a[n]||[]).length||a[n+"0"])return a}}}(t,n,r);if(!a)return;if("histogram"===a.type&&r==={v:"y",h:"x"}[a.orientation||"v"])return void(e.type="linear");var i,o=r+"calendar",l=a[o];if(tu(a,r)){var s=eu(a),c=[];for(i=0;i rect").call(Vn.setTranslate,0,0).call(Vn.setScale,1,1),e.plot.call(Vn.setTranslate,t._offset,n._offset).call(Vn.setScale,1,1);var r=e.plot.selectAll(".scatterlayer .trace");r.selectAll(".point").call(Vn.setPointGroupScale,1,1),r.selectAll(".textpoint").call(Vn.setTextPointsScale,1,1),r.call(Vn.hideOutsideRangePoints,e)}function g(e,n){var r,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],c=[];if(l){a=(r=t._fullLayout[l.axisName])._r,o=l.to,c[0]=(a[0]*(1-n)+n*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var u=a[1]-a[0],d=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[2]=e.xaxis._length*(1-n+n*d/u)}else c[0]=0,c[2]=e.xaxis._length;if(s){a=(r=t._fullLayout[s.axisName])._r,o=s.to,c[1]=(a[1]*(1-n)+n*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var h=a[1]-a[0],p=o[1]-o[0];r.range[0]=a[0]*(1-n)+n*o[0],r.range[1]=a[1]*(1-n)+n*o[1],c[3]=e.yaxis._length*(1-n+n*p/h)}else c[1]=0,c[3]=e.yaxis._length;!function(e,n){var r,a=[];for(a=[e._id,n._id],r=0;rr.duration?(function(){for(var e={},n=0;n0?c+o:o;return{ppad:o,ppadplus:l?f:d,ppadminus:l?d:f}}return{ppad:o}}function Lu(e,t,n,r,a){var i="category"===e.type?e.r2c:e.d2c;if(void 0!==t)return[i(t),i(n)];if(r){var o,l,s,c,u=1/0,f=-1/0,d=r.match(wu.segmentRE);for("date"===e.type&&(i=ku.decodeDate(i)),o=0;of&&(f=c)));return f>=u?[u,f]:void 0}}var Su=function(e,t,n,r,a){function i(n,r){return nt.coerce(e,t,_u,n,r)}if(r=r||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return t;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",e.path?"path":"rect"),l=i("xsizemode"),s=i("ysizemode"),c=["x","y"],u=0;u<2;u++){var f,d,h,p=c[u],g=p+"anchor",v="x"===p?l:s,y={_fullLayout:n},m=Da.coerceRef(e,t,y,p,"","paper");if("paper"!==m?(f=Da.getFromId(y,m),h=ku.rangeToShapePosition(f),d=ku.shapePositionToRange(f)):d=h=nt.identity,"path"!==o){var x=p+"0",b=p+"1",_=e[x],w=e[b];e[x]=d(e[x],!0),e[b]=d(e[b],!0),"pixel"===v?(i(x,0),i(b,10)):(Da.coercePosition(t,y,i,m,x,.25),Da.coercePosition(t,y,i,m,b,.75)),t[x]=h(t[x]),t[b]=h(t[b]),e[x]=_,e[b]=w}if("pixel"===v){var k=e[g];e[g]=d(e[g],!0),Da.coercePosition(t,y,i,m,g,.25),t[g]=h(t[g]),e[g]=k}}return"path"===o?i("path"):nt.noneOrAll(e,t,["x0","x1","y0","y1"]),t},Cu={draw:function(e){var t=e._fullLayout;for(var n in t._shapeUpperLayer.selectAll("path").remove(),t._shapeLowerLayer.selectAll("path").remove(),t._plots){var r=t._plots[n].shapelayer;r&&r.selectAll("path").remove()}for(var a=0;as?(y=o,_=O+".y0",A="y0",m=s,w=O+".y1",T="y1"):(y=s,_=O+".y1",A="y1",m=o,w=O+".y0",T="y0");a={},U(t),V.moveFn="move"===F?G:Y},doneFn:function(){hr(t),O.call("relayout",e,a)}};function U(e){var n=V.element.getBoundingClientRect(),r=n.right-n.left,a=n.bottom-n.top,i=e.clientX-n.left,o=e.clientY-n.top,l=r>j&&a>B&&!e.shiftKey?Et.getCursor(i/r,1-o/a):"move";hr(t,l),F=l.split("-")[0]}function G(r,y){if("path"===n.type){var m=function(e){return e},x=m,b=m;q?a[g]=n.xanchor=N(c+r):(x=function(e){return N(E(e)+r)},z&&"date"===z.type&&(x=ku.encodeDate(x))),H?a[v]=n.yanchor=I(u+y):(b=function(e){return I(R(e)+y)},D&&"date"===D.type&&(b=ku.encodeDate(b))),n.path=Ou(C,x,b),a[P]=n.path}else q?a[g]=n.xanchor=N(c+r):(a[f]=n.x0=N(i+r),a[h]=n.x1=N(l+r)),H?a[v]=n.yanchor=I(u+y):(a[d]=n.y0=I(o+y),a[p]=n.y1=I(s+y));t.attr("d",zu(e,n))}function Y(r,i){if("path"===n.type){var o=function(e){return e},l=o,s=o;q?a[g]=n.xanchor=N(c+r):(l=function(e){return N(E(e)+r)},z&&"date"===z.type&&(l=ku.encodeDate(l))),H?a[v]=n.yanchor=I(u+i):(s=function(e){return I(R(e)+i)},D&&"date"===D.type&&(s=ku.encodeDate(s))),n.path=Ou(C,l,s),a[P]=n.path}else{var f=~F.indexOf("n")?y+i:y,d=~F.indexOf("s")?m+i:m,h=~F.indexOf("w")?x+r:x,p=~F.indexOf("e")?b+r:b;~F.indexOf("n")&&H&&(f=y-i),~F.indexOf("s")&&H&&(d=m-i),(!H&&d-f>B||H&&f-d>B)&&(a[_]=n[A]=H?f:I(f),a[w]=n[T]=H?d:I(d)),p-h>j&&(a[k]=n[L]=q?h:N(h),a[M]=n[S]=q?p:N(p))}t.attr("d",zu(e,n))}Et.init(V),t.node().onmousemove=U}(e,o,r,t)}}function zu(e,t){var n,r,a,i,o,l,s,c,u=t.type,f=Da.getFromId(e,t.xref),d=Da.getFromId(e,t.yref),h=e._fullLayout._size;if(f?(n=ku.shapePositionToRange(f),r=function(e){return f._offset+f.r2p(n(e,!0))}):r=function(e){return h.l+h.w*e},d?(a=ku.shapePositionToRange(d),i=function(e){return d._offset+d.r2p(a(e,!0))}):i=function(e){return h.t+h.h*(1-e)},"path"===u)return f&&"date"===f.type&&(r=ku.decodeDate(r)),d&&"date"===d.type&&(i=ku.decodeDate(i)),function(e,t,n){var r=e.path,a=e.xsizemode,i=e.ysizemode,o=e.xanchor,l=e.yanchor;return r.replace(wu.segmentRE,function(e){var r=0,s=e.charAt(0),c=wu.paramIsX[s],u=wu.paramIsY[s],f=wu.numParams[s],d=e.substr(1).replace(wu.paramRE,function(e){return c[r]?e="pixel"===a?t(o)+Number(e):t(e):u[r]&&(e="pixel"===i?n(l)-Number(e):n(e)),++r>f&&(e="X"),e});return r>f&&(d=d.replace(/[\s,]*X.*/,""),nt.log("Ignoring extra params in segment "+e)),s+d})}(t,r,i);if("pixel"===t.xsizemode){var p=r(t.xanchor);o=p+t.x0,l=p+t.x1}else o=r(t.x0),l=r(t.x1);if("pixel"===t.ysizemode){var g=i(t.yanchor);s=g-t.y0,c=g-t.y1}else s=i(t.y0),c=i(t.y1);if("line"===u)return"M"+o+","+s+"L"+l+","+c;if("rect"===u)return"M"+o+","+s+"H"+l+"V"+c+"H"+o+"Z";var v=(o+l)/2,y=(s+c)/2,m=Math.abs(v-o),x=Math.abs(y-s),b="A"+m+","+x,_=v+m+","+y;return"M"+_+b+" 0 1,1 "+(v+","+(y-x))+b+" 0 0,1 "+_+"Z"}function Ou(e,t,n){return e.replace(wu.segmentRE,function(e){var r=0,a=e.charAt(0),i=wu.paramIsX[a],o=wu.paramIsY[a],l=wu.numParams[a];return a+e.substr(1).replace(wu.paramRE,function(e){return r>=l?e:(i[r]?e=t(e):o[r]&&(e=n(e)),r++,e)})})}var Du={moduleType:"component",name:"shapes",layoutAttributes:_u,supplyLayoutDefaults:function(e,t){ls(e,t,{name:"shapes",handleItemDefaults:Su})},includeBasePlot:ss("shapes"),calcAutorange:function(e){var t=e._fullLayout,n=nt.filterVisible(t.shapes);if(n.length&&e._fullData.length)for(var r=0;r0)&&(r("active"),r("x"),r("y"),nt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("len"),r("lenmode"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),nt.coerceFont(r,"font",n.font),r("currentvalue.visible")&&(r("currentvalue.xanchor"),r("currentvalue.prefix"),r("currentvalue.suffix"),r("currentvalue.offset"),nt.coerceFont(r,"currentvalue.font",t.font)),r("transition.duration"),r("transition.easing"),r("bgcolor"),r("activebgcolor"),r("bordercolor"),r("borderwidth"),r("ticklen"),r("tickwidth"),r("tickcolor"),r("minorticklen"))}var qu=pn.LINE_SPACING,Hu=pn.FROM_TL,Vu=pn.FROM_BR;function Uu(e){return e._index}function Gu(t,n){var r=Vn.tester.selectAll("g."+Eu.labelGroupClass).data(n.steps);r.enter().append("g").classed(Eu.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=Zu(e.select(this),{step:t},n).node();if(r){var o=Vn.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=n._dims={};o.inputAreaWidth=Math.max(Eu.railWidth,Eu.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*n.x,o.ly=l.t+l.h*(1-n.y),"fraction"===n.lenmode?o.outerLength=Math.round(l.w*n.len):o.outerLength=n.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-n.pad.l-n.pad.r);var s=(o.inputAreaLength-2*Eu.stepInset)/(n.steps.length-1),c=a+Eu.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(c/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,n.currentvalue.visible){var u=Vn.tester.append("g");r.each(function(e){var t=Yu(u,n,e.label),r=t.node()&&Vn.bBox(t.node())||{width:0,height:0},a=yn.lineCount(t);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(r.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(r.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+n.currentvalue.offset,u.remove()}o.height=o.currentValueTotalHeight+Eu.tickOffset+n.ticklen+Eu.labelOffset+o.labelHeight+n.pad.t+n.pad.b;var f="left";Bs.isRightAnchor(n)&&(o.lx-=o.outerLength,f="right"),Bs.isCenterAnchor(n)&&(o.lx-=o.outerLength/2,f="center");var d="top";Bs.isBottomAnchor(n)&&(o.ly-=o.height,d="bottom"),Bs.isMiddleAnchor(n)&&(o.ly-=o.height/2,d="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Qr.autoMargin(t,Eu.autoMarginIdRoot+n._index,{x:n.x,y:n.y,l:o.outerLength*Hu[f],r:o.outerLength*Vu[f],b:o.height*Vu[d],t:o.height*Hu[d]})}function Yu(e,t,n){if(t.currentvalue.visible){var r,a,i=t._dims;switch(t.currentvalue.xanchor){case"right":r=i.inputAreaLength-Eu.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":r=.5*i.inputAreaLength,a="middle";break;default:r=Eu.currentValueInset,a="left"}var o=nt.ensureSingle(e,"text",Eu.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),l=t.currentvalue.prefix?t.currentvalue.prefix:"";if("string"==typeof n)l+=n;else l+=t.steps[t.active].label;t.currentvalue.suffix&&(l+=t.currentvalue.suffix),o.call(Vn.font,t.currentvalue.font).text(l).call(yn.convertToTspans,t._gd);var s=yn.lineCount(o),c=(i.currentValueMaxLines+1-s)*t.currentvalue.font.size*qu;return yn.positionText(o,r,c),o}}function Xu(e,t,n){nt.ensureSingle(e,"rect",Eu.gripRectClass,function(r){r.call($u,t,e,n).style("pointer-events","all")}).attr({width:Eu.gripWidth,height:Eu.gripHeight,rx:Eu.gripRadius,ry:Eu.gripRadius}).call(dt.stroke,n.bordercolor).call(dt.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px")}function Zu(e,t,n){var r=nt.ensureSingle(e,"text",Eu.labelClass,function(e){e.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return r.call(Vn.font,n.font).text(t.step.label).call(yn.convertToTspans,n._gd),r}function Wu(t,n){var r=nt.ensureSingle(t,"g",Eu.labelsClass),a=n._dims,i=r.selectAll("g."+Eu.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(Eu.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=e.select(this);r.call(Zu,t,n),Vn.setTranslate(r,tf(n,t.fraction),Eu.tickOffset+n.ticklen+n.font.size*qu+Eu.labelOffset+a.currentValueTotalHeight)})}function Ju(e,t,n,r,a){var i=Math.round(r*(n.steps.length-1));i!==n.active&&Qu(e,t,n,i,!0,a)}function Qu(e,t,n,r,a,i){var o=n.active;n._input.active=n.active=r;var l=n.steps[n.active];t.call(ef,n,n.active/(n.steps.length-1),i),t.call(Yu,n),e.emit("plotly_sliderchange",{slider:n,step:n.steps[n.active],interaction:a,previousActive:o}),l&&l.method&&a&&(t._nextMethod?(t._nextMethod.step=l,t._nextMethod.doCallback=a,t._nextMethod.doTransition=i):(t._nextMethod={step:l,doCallback:a,doTransition:i},t._nextMethodRaf=window.requestAnimationFrame(function(){var n=t._nextMethod.step;n.method&&(n.execute&&Qr.executeAPICommand(e,n.method,n.args),t._nextMethod=null,t._nextMethodRaf=null)})))}function $u(t,n,r){var a=r.node(),i=e.select(n);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();n.emit("plotly_sliderstart",{slider:t});var l=r.select("."+Eu.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),l.call(dt.fill,t.activebgcolor);var s=nf(t,e.mouse(a)[0]);Ju(n,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=nf(t,e.mouse(a)[0]);Ju(n,r,t,i,!1)}),i.on("mouseup",function(){var e=o();e._dragging=!1,l.call(dt.fill,e.bgcolor),i.on("mouseup",null),i.on("mousemove",null),n.emit("plotly_sliderend",{slider:e,step:e.steps[e.active]})})})}function Ku(t,n){var r=t.selectAll("rect."+Eu.tickRectClass).data(n.steps),a=n._dims;r.enter().append("rect").classed(Eu.tickRectClass,!0),r.exit().remove(),r.attr({width:n.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=e.select(this);o.attr({height:i?n.ticklen:n.minorticklen}).call(dt.fill,n.tickcolor),Vn.setTranslate(o,tf(n,r/(n.steps.length-1))-.5*n.tickwidth,(i?Eu.tickOffset:Eu.minorTickOffset)+a.currentValueTotalHeight)})}function ef(e,t,n,r){var a=e.select("rect."+Eu.gripRectClass),i=tf(t,n);if(!t._invokingCommand){var o=a;r&&t.transition.duration>0&&(o=o.transition().duration(t.transition.duration).ease(t.transition.easing)),o.attr("transform","translate("+(i-.5*Eu.gripWidth)+","+t._dims.currentValueTotalHeight+")")}}function tf(e,t){var n=e._dims;return n.inputAreaStart+Eu.stepInset+(n.inputAreaLength-2*Eu.stepInset)*Math.min(1,Math.max(0,t))}function nf(e,t){var n=e._dims;return Math.min(1,Math.max(0,(t-Eu.stepInset-n.inputAreaStart)/(n.inputAreaLength-2*Eu.stepInset-2*n.inputAreaStart)))}function rf(e,t,n){var r=n._dims,a=nt.ensureSingle(e,"rect",Eu.railTouchRectClass,function(r){r.call($u,t,e,n).style("pointer-events","all")});a.attr({width:r.inputAreaLength,height:Math.max(r.inputAreaWidth,Eu.tickOffset+n.ticklen+r.labelHeight)}).call(dt.fill,n.bgcolor).attr("opacity",0),Vn.setTranslate(a,0,r.currentValueTotalHeight)}function af(e,t){var n=t._dims,r=n.inputAreaLength-2*Eu.railInset,a=nt.ensureSingle(e,"rect",Eu.railRectClass);a.attr({width:r,height:Eu.railWidth,rx:Eu.railRadius,ry:Eu.railRadius,"shape-rendering":"crispEdges"}).call(dt.stroke,t.bordercolor).call(dt.fill,t.bgcolor).style("stroke-width",t.borderwidth+"px"),Vn.setTranslate(a,Eu.railInset,.5*(n.inputAreaWidth-Eu.railWidth)+n.currentValueTotalHeight)}var of={moduleType:"component",name:Eu.name,layoutAttributes:Iu,supplyLayoutDefaults:function(e,t){ls(e,t,{name:Fu,handleItemDefaults:Bu})},draw:function(t){var n=t._fullLayout,r=function(e,t){for(var n=e[Eu.name],r=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(Eu.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;r=n.steps.length&&(n.active=0),t.call(Yu,n).call(af,n).call(Wu,n).call(Ku,n).call(rf,e,n).call(Xu,e,n);var r=n._dims;Vn.setTranslate(t,r.lx+n.pad.l,r.ly+n.pad.t),t.call(ef,n,n.active/(n.steps.length-1),!1),t.call(Yu,n)}(t,e.select(this),n)}})}}},lf=y.extendFlat,sf=(0,Xt.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:lf({},Ru,{}),font:T({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:C.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),cf={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},uf=cf.name,ff=sf.buttons;function df(e,t,n){function r(n,r){return nt.coerce(e,t,sf,n,r)}r("visible",function(e,t){var n,r,a=e.buttons||[],i=t.buttons=[];function o(e,t){return nt.coerce(n,r,ff,e,t)}for(var l=0;l0)&&(r("active"),r("direction"),r("type"),r("showactive"),r("x"),r("y"),nt.noneOrAll(e,t,["x","y"]),r("xanchor"),r("yanchor"),r("pad.t"),r("pad.r"),r("pad.b"),r("pad.l"),nt.coerceFont(r,"font",n.font),r("bgcolor",n.paper_bgcolor),r("bordercolor"),r("borderwidth"))}var hf=pf;function pf(e,t,n){this.gd=e,this.container=t,this.id=n,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}pf.barWidth=2,pf.barLength=20,pf.barRadius=2,pf.barPad=1,pf.barColor="#808BA4",pf.prototype.enable=function(t,n,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,c,u,f=this.position.l,d=this.position.w,h=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,y="left"===g,m="up"===g,x=d,b=p;v||y||"right"===g||m||(this.position.direction="down",v=!0),v||m?(s=(l=f)+x,v?(c=h,b=(u=Math.min(c+b,o))-c):b=(u=h+b)-(c=Math.max(u-b,0))):(u=(c=h)+b,y?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:c,w:x,h:b};var _=d>x,w=pf.barLength+2*pf.barPad,k=pf.barWidth+2*pf.barPad,M=f,A=h+p;A+k>o&&(A=o-k);var T=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);T.exit().on(".drag",null).remove(),T.enter().append("rect").classed("scrollbar-horizontal",!0).call(dt.fill,pf.barColor),_?(this.hbar=T.attr({rx:pf.barRadius,ry:pf.barRadius,x:M,y:A,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var L=p>b,S=pf.barWidth+2*pf.barPad,C=pf.barLength+2*pf.barPad,P=f+d,z=h;P+S>i&&(P=i-S);var O=this.container.selectAll("rect.scrollbar-vertical").data(L?[0]:[]);O.exit().on(".drag",null).remove(),O.enter().append("rect").classed("scrollbar-vertical",!0).call(dt.fill,pf.barColor),L?(this.vbar=O.attr({rx:pf.barRadius,ry:pf.barRadius,x:P,y:z,width:S,height:C}),this._vbarYMin=z+C/2,this._vbarTranslateMax=b-C):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,E=l-.5,R=L?s+S+.5:s+.5,N=c-.5,I=_?u+k+.5:u+.5,F=a._topdefs.selectAll("#"+D).data(_||L?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||L?(this._clipRect=F.select("rect").attr({x:Math.floor(E),y:Math.floor(N),width:Math.ceil(R)-Math.floor(E),height:Math.ceil(I)-Math.floor(N)}),this.container.call(Vn.setClipUrl,D),this.bg.attr({x:f,y:h,width:d,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Vn.setClipUrl,null),delete this._clipRect),_||L){var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),L&&this.vbar.on(".drag",null).call(B)}this.setTranslate(n,r)},pf.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Vn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},pf.prototype._onBoxDrag=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(n-=e.event.dy),this.setTranslate(t,n)},pf.prototype._onBoxWheel=function(){var t=this.translateX,n=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(n+=e.event.deltaY),this.setTranslate(t,n)},pf.prototype._onBarDrag=function(){var t=this.translateX,n=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(nt.constrain(e.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=n+this._vbarYMin,o=i+this._vbarTranslateMax;n=(nt.constrain(e.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,n)},pf.prototype.setTranslate=function(e,t){var n=this.position.w-this._box.w,r=this.position.h-this._box.h;if(e=nt.constrain(e||0,0,n),t=nt.constrain(t||0,0,r),this.translateX=e,this.translateY=t,this.container.call(Vn.setTranslate,this._box.l-this.position.l-e,this._box.t-this.position.t-t),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+e-.5),y:Math.floor(this.position.t+t-.5)}),this.hbar){var a=e/n;this.hbar.call(Vn.setTranslate,e+a*this._hbarTranslateMax,t)}if(this.vbar){var i=t/r;this.vbar.call(Vn.setTranslate,e,t+i*this._vbarTranslateMax)}};var gf=pn.LINE_SPACING;function vf(e){return e._index}function yf(e,t){return+e.attr(cf.menuIndexAttrName)===t._index}function mf(e,t,n,r,a,i,o,l){t._input.active=t.active=o,"buttons"===t.type?bf(e,r,null,null,t):"dropdown"===t.type&&(a.attr(cf.menuIndexAttrName,"-1"),xf(e,r,a,i,t),l||bf(e,r,a,i,t))}function xf(e,t,n,r,a){var i=nt.ensureSingle(t,"g",cf.headerClassName,function(e){e.style("pointer-events","all")}),o=a._dims,l=a.active,s=a.buttons[l]||cf.blankHeaderOpts,c={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},u={width:o.headerWidth,height:o.headerHeight};i.call(_f,a,s,e).call(Sf,a,c,u),nt.ensureSingle(t,"text",cf.headerArrowClassName,function(e){e.classed("user-select-none",!0).attr("text-anchor","end").call(Vn.font,a.font).text(cf.arrowSymbol[a.direction])}).attr({x:o.headerWidth-cf.arrowOffsetX+a.pad.l,y:o.headerHeight/2+cf.textOffsetY+a.pad.t}),i.on("click",function(){n.call(Cf),n.attr(cf.menuIndexAttrName,yf(n,a)?-1:String(a._index)),bf(e,t,n,r,a)}),i.on("mouseover",function(){i.call(Af)}),i.on("mouseout",function(){i.call(Tf,a)}),Vn.setTranslate(t,o.lx,o.ly)}function bf(t,n,r,a,i){r||(r=n).attr("pointer-events","all");var o=function(e){return-1==+e.attr(cf.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?cf.dropdownButtonClassName:cf.buttonClassName,s=r.selectAll("g."+l).data(o),c=s.enter().append("g").classed(l,!0),u=s.exit();"dropdown"===i.type?(c.attr("opacity","0").transition().attr("opacity","1"),u.transition().attr("opacity","0").remove()):u.remove();var f=0,d=0,h=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?d=h.headerHeight+cf.gapButtonHeader:f=h.headerWidth+cf.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(d=-cf.gapButtonHeader+cf.gapButton-h.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-cf.gapButtonHeader+cf.gapButton-h.openWidth);var g={x:h.lx+f+i.pad.l,y:h.ly+d+i.pad.t,yPad:cf.gapButton,xPad:cf.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var c=e.select(this);c.call(_f,i,o,t).call(Sf,i,g),c.on("click",function(){e.event.defaultPrevented||(mf(t,i,0,n,r,a,l),o.execute&&Qr.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),c.on("mouseover",function(){c.call(Af)}),c.on("mouseout",function(){c.call(Tf,i),s.call(Mf,i)})}),s.call(Mf,i),p?(v.w=Math.max(h.openWidth,h.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(h.openHeight,h.headerHeight)),v.direction=i.direction,a&&(s.size()?function(e,t,n,r,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,d=a.active;if(u)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(cf.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(e){for(var t=e._fullLayout._pushmargin||{},n=Object.keys(t),r=0;rb.queueLength&&(e.undoQueue.queue.shift(),e.undoQueue.index--))},startSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!0,e.undoQueue.beginSequence=!0},stopSequence:function(e){e.undoQueue=e.undoQueue||{index:0,queue:[],sequence:!1},e.undoQueue.sequence=!1,e.undoQueue.beginSequence=!1},undo:function(e){var t,n;if(e.framework&&e.framework.isPolar)e.framework.undo();else if(!(void 0===e.undoQueue||isNaN(e.undoQueue.index)||e.undoQueue.index<=0)){for(e.undoQueue.index--,t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n=e.undoQueue.queue.length)){for(t=e.undoQueue.queue[e.undoQueue.index],e.undoQueue.inSequence=!0,n=0;n0&&nt.log("Clearing previous rejected promises from queue."),e._promises=[]},Rf.cleanLayout=function(e){var t,n;e||(e={}),e.xaxis1&&(e.xaxis||(e.xaxis=e.xaxis1),delete e.xaxis1),e.yaxis1&&(e.yaxis||(e.yaxis=e.yaxis1),delete e.yaxis1),e.scene1&&(e.scene||(e.scene=e.scene1),delete e.scene1);var r=(Qr.subplotsRegistry.cartesian||{}).attrRegex,a=(Qr.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(e);for(t=0;t3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===e.dragmode&&(e.dragmode="orbit"),dt.clean(e),e},Rf.cleanData=function(e,t){for(var n=[],r=e.concat(Array.isArray(t)?t:[]).filter(function(e){return"uid"in e}).map(function(e){return e.uid}),a=0;a0)return e.substr(0,t)}Rf.hasParent=function(e,t){for(var n=Uf(t);n;){if(n in e)return!0;n=Uf(n)}return!1};var Gf=["x","y","z"];Rf.clearAxisTypes=function(e,t,n){for(var r=0;r1&&_.warn("Full array edits are incompatible with other edits",a);var f=n[""][""];if(Wf(f))t.set(null);else{if(!Array.isArray(f))return _.warn("Unrecognized full array edit value",a,f),!0;t.set(f)}return!s&&(i(c,u),o(e),!0)}var d,h,p,g,v,y,m,x=Object.keys(n).map(Number).sort(Xf),b=t.get(),w=b||[],k=Y(u,a).get(),A=[],T=-1,L=w.length;for(d=0;dw.length-(m?0:1))_.warn("index out of range",a,p);else if(void 0!==y)v.length>1&&_.warn("Insertion & removal are incompatible with edits to the same index.",a,p),Wf(y)?A.push(p):m?("add"===y&&(y={}),w.splice(p,0,y),k&&k.splice(p,0,{})):_.warn("Unrecognized full object edit value",a,p,y),-1===T&&(T=p);else for(h=0;h=0;d--)w.splice(A[d],1),k&&k.splice(A[d],1);if(w.length?b||t.set(w):t.set(null),s)return!1;if(i(c,u),l!==M){var S;if(-1===T)S=x;else{for(L=Math.max(w.length,L),S=[],d=0;d=T);d++)S.push(p);for(d=T;d1?(y=["toggleHover"],m=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],y=["hoverClosestGeo"],m=["resetGeo"]):o?(y=["hoverClosest3d"],m=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(y=["toggleHover"],m=["resetViewMapbox"]):y=c?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(y=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!c||h||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==m[0]&&(m=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||c)&&!h||u?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:d&&(x=["zoom2d"]),function(e){for(var t=!1,n=0;nhd*h)||y)for(n=0;nL&&PA&&(A=P);l/=(A-M)/(2*T),M=a.l2r(M),A=a.l2r(A),a.range=a._input.range=_=e[1]||a[1]<=e[0])&&i[0]t[0])return!0}return!1}(n,a,h)){var o=i.node(),l=t.bg=nt.ensureSingle(i,"rect","bg");o.insertBefore(l.node(),o.childNodes[0])}else i.select("rect.bg").remove(),d.push(e),h.push([n,a])});var p=r._bgLayer.selectAll(".bg").data(d);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=e.select(this)}),f.each(function(e){var t=r._plots[e],a=t.xaxis,c=t.yaxis;t.bg&&l&&t.bg.call(Vn.setRect,a._offset-i,c._offset-i,a._length+2*i,c._length+2*i).call(dt.fill,r.plot_bgcolor).style("stroke-width",0);var u,f,d=t.clipId="clip"+r._uid+e+"plot",h=nt.ensureSingleById(r._clips,"clipPath",d,function(e){e.classed("plotclip",!0).append("rect")});for(t.clipRect=h.select("rect").attr({width:a._length,height:c._length}),Vn.setTranslate(t.plot,a._offset,c._offset),t._hasClipOnAxisFalse?(u=null,f=d):(u=d,f=null),Vn.setClipUrl(t.plot,u),n=0;n=0?c.angularAxis.domain:e.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var A=k.slice();w&&b&&(A[1]+=M);var T=c.angularAxis.ticksCount||4;T>8&&(T=T/(T/8)+T%8),c.angularAxis.ticksStep&&(T=(A[1]-A[0])/T);var L=c.angularAxis.ticksStep||(A[1]-A[0])/(T*(c.minorTicks+1));m&&(L=Math.max(Math.round(L),1)),A[2]||(A[2]=L);var S=e.range.apply(this,A);if(S=S.map(function(e,t){return parseFloat(e.toPrecision(12))}),a=e.scale.linear().domain(A.slice(0,2)).range("clockwise"===c.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var C=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),P=this.appendChild(this.ownerDocument.importNode(C.documentElement,!0));t=e.select(P)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var z,O=t.select(".chart-group"),D={fill:"none",stroke:c.tickColor},E={"font-size":c.font.size,"font-family":c.font.family,fill:c.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(e,t){return" "+e+" 0 "+c.font.outlineColor}).join(",")};if(c.showLegend){z=t.select(".legend-group").attr({transform:"translate("+[g,c.margin.top]+")"}).style({display:"block"});var R=u.map(function(e,t){var n=Td.util.cloneJson(e);return n.symbol="DotPlot"===e.geometry?e.dotType||"circle":"LinePlot"!=e.geometry?"square":"line",n.visibleInLegend=void 0===e.visibleInLegend||e.visibleInLegend,n.color="LinePlot"===e.geometry?e.strokeColor:e.color,n});Td.Legend().config({data:u.map(function(e,t){return e.name||"Element"+t}),legendConfig:Md({},Td.Legend.defaultConfig().legendConfig,{container:z,elements:R,reverseOrder:c.legend.reverseOrder})})();var N=z.node().getBBox();g=Math.min(c.width-N.width-c.margin.left-c.margin.right,c.height-c.margin.top-c.margin.bottom)/2,g=Math.max(10,g),y=[c.margin.left+g,c.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),z.attr("transform","translate("+[y[0]+g,y[1]-g]+")")}else z=t.select(".legend-group").style({display:"none"});t.attr({width:c.width,height:c.height}).style({opacity:c.opacity}),O.attr("transform","translate("+y+")").style({cursor:"crosshair"});var I=[(c.width-(c.margin.left+c.margin.right+2*g+(N?N.width:0)))/2,(c.height-(c.margin.top+c.margin.bottom+2*g))/2];if(I[0]=Math.max(0,I[0]),I[1]=Math.max(0,I[1]),t.select(".outer-group").attr("transform","translate("+I+")"),c.title){var F=t.select("g.title-group text").style(E).text(c.title),j=F.node().getBBox();F.attr({x:y[0]-j.width/2,y:y[1]-g-20})}var B=t.select(".radial.axis-group");if(c.radialAxis.gridLinesVisible){var q=B.selectAll("circle.grid-circle").data(r.ticks(5));q.enter().append("circle").attr({class:"grid-circle"}).style(D),q.attr("r",r),q.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(D);var H=t.select("circle.background-circle").attr({r:g}).style({fill:c.backgroundColor,stroke:c.stroke});function V(e,t){return a(e)%360+c.orientation}if(c.radialAxis.visible){var U=e.svg.axis().scale(r).ticks(5).tickSize(5);B.call(U).attr({transform:"rotate("+c.radialAxis.orientation+")"}),B.selectAll(".domain").style(D),B.selectAll("g>text").text(function(e,t){return this.textContent+c.radialAxis.ticksSuffix}).style(E).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(e,t){return"horizontal"===c.radialAxis.tickOrientation?"rotate("+-c.radialAxis.orientation+") translate("+[0,E["font-size"]]+")":"translate("+[0,E["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(S),Y=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(e,t){return"rotate("+V(e)+")"}}).style({display:c.angularAxis.visible?"block":"none"}),G.exit().remove(),Y.append("line").classed("grid-line",!0).classed("major",function(e,t){return t%(c.minorTicks+1)==0}).classed("minor",function(e,t){return!(t%(c.minorTicks+1)==0)}).style(D),Y.selectAll(".minor").style({stroke:c.minorTickColor}),G.select("line.grid-line").attr({x1:c.tickLength?g-c.tickLength:0,x2:g}).style({display:c.angularAxis.gridLinesVisible?"block":"none"}),Y.append("text").classed("axis-text",!0).style(E);var X=G.select("text.axis-text").attr({x:g+c.labelOffset,dy:Ad+"em",transform:function(e,t){var n=V(e),r=g+c.labelOffset,a=c.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-n+" "+r+" 0)":"radial"==a?n<270&&n>90?"rotate(180 "+r+" 0)":null:"rotate("+(n<=180&&n>0?-90:90)+" "+r+" 0)"}}).style({"text-anchor":"middle",display:c.angularAxis.labelsVisible?"block":"none"}).text(function(e,t){return t%(c.minorTicks+1)!=0?"":m?m[e]+c.angularAxis.ticksSuffix:e+c.angularAxis.ticksSuffix}).style(E);c.angularAxis.rewriteTicks&&X.text(function(e,t){return t%(c.minorTicks+1)!=0?"":c.angularAxis.rewriteTicks(this.textContent,t)});var Z=e.max(O.selectAll(".angular-tick text")[0].map(function(e,t){return e.getCTM().e+e.getBBox().width}));z.attr({transform:"translate("+[g+Z,c.margin.top]+")"});var W=t.select("g.geometry-group").selectAll("g").size()>0,J=t.select("g.geometry-group").selectAll("g.geometry").data(u);if(J.enter().append("g").attr({class:function(e,t){return"geometry geometry"+t}}),J.exit().remove(),u[0]||W){var Q=[];u.forEach(function(e,t){var n={};n.radialScale=r,n.angularScale=a,n.container=J.filter(function(e,n){return n==t}),n.geometry=e.geometry,n.orientation=c.orientation,n.direction=c.direction,n.index=t,Q.push({data:e,geometryConfig:n})});var $=[];e.nest().key(function(e,t){return void 0!==e.data.groupId||"unstacked"}).entries(Q).forEach(function(e,t){"unstacked"===e.key?$=$.concat(e.values.map(function(e,t){return[e]})):$.push(e.values)}),$.forEach(function(e,t){var n;n=Array.isArray(e)?e[0].geometryConfig.geometry:e.geometryConfig.geometry;var r=e.map(function(e,t){return Md(Td[n].defaultConfig(),e)});Td[n]().config(r)()})}var K,ee,te=t.select(".guides-group"),ne=t.select(".tooltips-group"),re=Td.tooltipPanel().config({container:ne,fontSize:8})(),ae=Td.tooltipPanel().config({container:ne,fontSize:8})(),ie=Td.tooltipPanel().config({container:ne,hasTick:!0})();if(!b){var oe=te.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});O.on("mousemove.angular-guide",function(e,t){var n=Td.util.getMousePos(H).angle;oe.attr({x2:-g,transform:"rotate("+n+")"}).style({opacity:.5});var r=(n+180+360-c.orientation)%360;K=a.invert(r);var i=Td.util.convertToCartesian(g+12,n+180);re.text(Td.util.round(K)).move([i[0]+y[0],i[1]+y[1]])}).on("mouseout.angular-guide",function(e,t){te.select("line").style({opacity:0})})}var le=te.select("circle").style({stroke:"grey",fill:"none"});O.on("mousemove.radial-guide",function(e,t){var n=Td.util.getMousePos(H).radius;le.attr({r:n}).style({opacity:.5}),ee=r.invert(Td.util.getMousePos(H).radius);var a=Td.util.convertToCartesian(n,c.radialAxis.orientation);ae.text(Td.util.round(ee)).move([a[0]+y[0],a[1]+y[1]])}).on("mouseout.radial-guide",function(e,t){le.style({opacity:0}),ie.hide(),re.hide(),ae.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(n,r){var a=e.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=e.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:Td.util.round(n[0]),r:Td.util.round(n[1])};b&&(s.t=m[n[0]]);var c="t: "+s.t+", r: "+s.r,u=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),d=[u.left+u.width/2-I[0]-f.left,u.top+u.height/2-I[1]-f.top];ie.config({color:o}).text(c),ie.move(d)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=e.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,n){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&ie.show()}).on("mouseout.tooltip",function(t,n){ie.hide();var r=e.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},c.config=function(e){if(!arguments.length)return i;var t=Td.util.cloneJson(e);return t.data.forEach(function(e,t){i.data[t]||(i.data[t]={}),Md(i.data[t],Td.Axis.defaultConfig().data[0]),Md(i.data[t],e)}),Md(i.layout,Td.Axis.defaultConfig().layout),Md(i.layout,t.layout),this},c.getLiveConfig=function(){return l},c.getinputConfig=function(){return o},c.radialScale=function(e){return r},c.angularScale=function(e){return a},c.svg=function(){return t},e.rebind(c,s,"on"),c},Td.Axis.defaultConfig=function(t,n){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Td.util={},Td.DATAEXTENT="dataExtent",Td.AREA="AreaChart",Td.LINE="LinePlot",Td.DOT="DotPlot",Td.BAR="BarChart",Td.util._override=function(e,t){for(var n in e)n in t&&(t[n]=e[n])},Td.util._extend=function(e,t){for(var n in e)t[n]=e[n]},Td.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Td.util.dataFromEquation2=function(t,n){var r=n||6;return e.range(0,360+r,r).map(function(e,n){var r=e*Math.PI/180;return[e,t(r)]})},Td.util.dataFromEquation=function(t,n,r){var a=n||6,i=[],o=[];e.range(0,360+a,a).forEach(function(e,n){var r=e*Math.PI/180,a=t(r);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},Td.util.ensureArray=function(t,n){if(void 0===t)return null;var r=[].concat(t);return e.range(n).map(function(e,t){return r[t]||r[0]})},Td.util.fillArrays=function(e,t,n){return t.forEach(function(t,r){e[t]=Td.util.ensureArray(e[t],n)}),e},Td.util.cloneJson=function(e){return JSON.parse(JSON.stringify(e))},Td.util.validateKeys=function(e,t){"string"==typeof t&&(t=t.split("."));var n=t.shift();return e[n]&&(!t.length||objHasKeys(e[n],t))},Td.util.sumArrays=function(t,n){return e.zip(t,n).map(function(t,n){return e.sum(t)})},Td.util.arrayLast=function(e){return e[e.length-1]},Td.util.arrayEqual=function(e,t){for(var n=Math.max(e.length,t.length,1);n-- >=0&&e[n]===t[n];);return-2===n},Td.util.flattenArray=function(e){for(var t=[];!Td.util.arrayEqual(t,e);)t=e,e=[].concat.apply([],e);return e},Td.util.deduplicate=function(e){return e.filter(function(e,t,n){return n.indexOf(e)==t})},Td.util.convertToCartesian=function(e,t){var n=t*Math.PI/180;return[e*Math.cos(n),e*Math.sin(n)]},Td.util.round=function(e,t){var n=t||2,r=Math.pow(10,n);return Math.round(e*r)/r},Td.util.getMousePos=function(t){var n=e.mouse(t.node()),r=n[0],a=n[1],i={};return i.x=r,i.y=a,i.pos=n,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},Td.util.duplicatesCount=function(e){for(var t,n={},r={},a=0,i=e.length;a0)){var s=e.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(e,t){return"rotate("+(n.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(e,t){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(e,t){return p.stroke(r,a,i)},"stroke-width":function(e,t){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(e,t){return p["stroke-dasharray"](r,a,i)},opacity:function(e,t){return p.opacity(r,a,i)},display:function(e,t){return p.display(r,a,i)}})}};var f=n.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,h=e.svg.arc().startAngle(function(e){return-d/2}).endAngle(function(e){return d/2}).innerRadius(function(e){return n.radialScale(s+(e[2]||0))}).outerRadius(function(e){return n.radialScale(s+(e[2]||0))+n.radialScale(e[1])});c.arc=function(t,r,a){e.select(this).attr({class:"mark arc",d:h,transform:function(e,t){return"rotate("+(n.orientation+l(e[0])+90)+")"}})};var p={fill:function(e,n,r){return t[r].data.color},stroke:function(e,n,r){return t[r].data.strokeColor},"stroke-width":function(e,n,r){return t[r].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,n,r){return t[r].data.opacity},display:function(e,n,r){return void 0===t[r].data.visible||t[r].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(e,t){return e});v.enter().append("path").attr({class:"mark"}),v.style(p).each(c[n.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,n){t[n]||(t[n]={}),Md(t[n],Td.PolyChart.defaultConfig()),Md(t[n],e)}),this):t},a.getColorScale=function(){},e.rebind(a,n,"on"),a},Td.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},Td.BarChart=function(){return Td.PolyChart()},Td.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Td.AreaChart=function(){return Td.PolyChart()},Td.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Td.DotPlot=function(){return Td.PolyChart()},Td.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Td.LinePlot=function(){return Td.PolyChart()},Td.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Td.Legend=function(){var t=Td.Legend.defaultConfig(),n=e.dispatch("hover");function r(){var n=t.legendConfig,a=t.data.map(function(e,t){return[].concat(e).map(function(e,r){var a=Md({},n.elements[t]);return a.name=e,a.color=[].concat(n.elements[t].color)[r],a})}),i=e.merge(a);i=i.filter(function(e,t){return n.elements[t]&&(n.elements[t].visibleInLegend||void 0===n.elements[t].visibleInLegend)}),n.reverseOrder&&(i=i.reverse());var o=n.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var l=i.map(function(e,t){return e.color}),s=n.fontSize,c=null==n.isContinuous?"number"==typeof i[0]:n.isContinuous,u=c?n.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),d=f.enter().append("svg").attr({width:300,height:u+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var h=e.range(i.length),p=e.scale[c?"linear":"ordinal"]().domain(h).range(l),g=e.scale[c?"linear":"ordinal"]().domain(h)[c?"range":"rangePoints"]([0,u]);if(c){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(e,t){return t/(l.length-1)*100+"%"}}).style({"stop-color":function(e,t){return e}}),f.append("rect").classed("legend-mark",!0).attr({height:n.height,width:n.colorBandWidth,fill:"url(#grad1)"})}else{var y=f.select(".legend-marks").selectAll("path.legend-mark").data(i);y.enter().append("path").classed("legend-mark",!0),y.attr({transform:function(e,t){return"translate("+[s/2,g(t)+s/2]+")"},d:function(t,n){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(r)?e.svg.symbol().type(r).size(i)():e.svg.symbol().type("square").size(i)()},fill:function(e,t){return p(t)}}),y.exit().remove()}var m=e.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[c?n.colorBandWidth:s,s/2]+")"}).call(m);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:c?n.textColor:"none"}),x.selectAll("text").style({fill:n.textColor,"font-size":n.fontSize}).text(function(e,t){return i[t].name}),r}return r.config=function(e){return arguments.length?(Md(t,e),this):t},e.rebind(r,n,"on"),r},Td.Legend.defaultConfig=function(e,t){return{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:!1}}},Td.tooltipPanel=function(){var t,n,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+Td.tooltipPanel.uid++,o=10,l=function(){var e=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),n=e.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=e.hsl(a.color).l,c=s>=.5?"#aaa":"white",u=s>=.5?"black":"white",f=i||"";n.style({fill:u,"font-size":a.fontSize+"px"}).text(f);var d=a.padding,h=n.node().getBBox(),p={fill:a.color,stroke:c,"stroke-width":"2px"},g=h.width+2*d+o,v=h.height+2*d;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*d]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(e){return Md(a,e),l},l},Td.tooltipPanel.uid=1,Td.adapter={},Td.adapter.plotly=function(){var t={convert:function(t,n){var r={};if(t.data&&(r.data=t.data.map(function(e,t){var r=Md({},e);return[[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"]]].forEach(function(e,t){Td.util.translator.apply(null,e.concat(n))}),n||delete r.marker,n&&delete r.groupId,n?("LinePlot"===r.geometry?(r.type="scatter",!0===r.dotVisible?(delete r.dotVisible,r.mode="lines+markers"):r.mode="lines"):"DotPlot"===r.geometry?(r.type="scatter",r.mode="markers"):"AreaChart"===r.geometry?r.type="area":"BarChart"===r.geometry&&(r.type="bar"),delete r.geometry):("scatter"===r.type?"lines"===r.mode?r.geometry="LinePlot":"markers"===r.mode?r.geometry="DotPlot":"lines+markers"===r.mode&&(r.geometry="LinePlot",r.dotVisible=!0):"area"===r.type?r.geometry="AreaChart":"bar"===r.type&&(r.geometry="BarChart"),delete r.mode,delete r.type),r}),!n&&t.layout&&"stack"===t.layout.barmode)){var a=Td.util.duplicates(r.data.map(function(e,t){return e.geometry}));r.data.forEach(function(e,t){var n=a.indexOf(e.geometry);-1!=n&&(r.data[t].groupId=n)})}if(t.layout){var i=Md({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(e,t){Td.util.translator.apply(null,e.concat(n))}),n?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};e.entries(i.margin).forEach(function(e,t){s[l[o.indexOf(e.key)]]=e.value}),i.margin=s}n&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var Ld,Sd=nt.extendDeepAll,Cd=Ld={};Cd.framework=function(t){var n,r,a,i,o,l=new function(){var e,t=[],n=-1,r=!1;function a(e,t){return e?(r=!0,e[t](),r=!1,this):this}return{add:function(e){return r?this:(t.splice(n+1,t.length-n),t.push(e),n=t.length-1,this)},setCallback:function(t){e=t},undo:function(){var r=t[n];return r?(a(r,"undo"),n-=1,e&&e(r.undo),this):this},redo:function(){var r=t[n+1];return r?(a(r,"redo"),n+=1,e&&e(r.redo),this):this},clear:function(){t=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n*:not(.chart-root)").remove(),n=n?Sd(n,r):r,a||(a=kd.Axis()),i=kd.adapter.plotly().convert(n),a.config(i).render(o),t.data=n.data,t.layout=n.layout,Cd.fillLayout(t),n}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return n},s.getLiveConfig=function(){return kd.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var e,t,a=this,i=kd.util.cloneJson(n);e=i,t=r,l.add({undo:function(){t&&a(t)},redo:function(){a(e)}}),r=kd.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},Cd.fillLayout=function(t){var n=e.select(t).selectAll(".plot-container"),r=n.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:dt.background,_container:n,_paperdiv:r,_paper:a};t._fullLayout=Sd(i,t.layout)};var Pd={};(Pd=kd).manager=Ld;var zd={},Od=Xc.initInteractions,Dd=Dt.AX_NAME_PATTERN,Ed=0;function Rd(e,t){try{e._fullLayout._paper.style("background",t)}catch(e){nt.error(e)}}function Nd(e,t){Rd(e,dt.combine(t,"white"))}function Id(e,t){e._context||(e._context=nt.extendDeep({},b));var n,r,a,i=e._context;if(t){for(r=Object.keys(t),n=0;n=e.data.length||a<-e.data.length)throw new Error(n+" must be valid indices for gd.data.");if(t.indexOf(a,r+1)>-1||a>=0&&t.indexOf(-e.data.length+a)>-1||a<0&&t.indexOf(e.data.length+a)>-1)throw new Error("each index in "+n+" must be unique.")}}function Bd(e,t,n){if(!Array.isArray(e.data))throw new Error("gd.data must be an array.");if(void 0===t)throw new Error("currentIndices is a required argument.");if(Array.isArray(t)||(t=[t]),jd(e,t,"currentIndices"),void 0===n||Array.isArray(n)||(n=[n]),void 0!==n&&jd(e,n,"newIndices"),void 0!==n&&t.length!==n.length)throw new Error("current and new indices must be of equal length.")}function qd(e,n,r,a,i){!function(e,t,n,r){var a=nt.isPlainObject(r);if(!Array.isArray(e.data))throw new Error("gd.data must be an array");if(!nt.isPlainObject(t))throw new Error("update must be a key:value object");if(void 0===n)throw new Error("indices must be an integer or array of integers");for(var i in jd(e,n,"indices"),t){if(!Array.isArray(t[i])||t[i].length!==n.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in r)||!Array.isArray(r[i])||r[i].length!==t[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(e,n,r,a);for(var o=function(e,n,r,a){var i,o,l,s,c,u=nt.isPlainObject(a),f=[];for(var d in Array.isArray(r)||(r=[r]),r=Fd(r,e.data.length-1),n)for(var h=0;h0&&"string"!=typeof _.parts[k-1];)M--;var A=_.parts[M],T=_.parts[M-1]+"."+A,L=_.parts.slice(0,M).join("."),S=nt.nestedProperty(e.layout,L).get(),C=nt.nestedProperty(o,L).get(),P=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===A?w:Vd(P);var z=zr.getLayoutValObject(o,_.parts);if(z&&z.impliedEdits&&null!==w)for(var D in z.impliedEdits)v(nt.relativeAttr(b,D),z.impliedEdits[D]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=e._initialAutoSize[b];else if(T.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(T),nt.nestedProperty(o,L+"._inputRange").set(null);else if(T.match(/^[xyz]axis[0-9]*\.autorange$/)){x(T),nt.nestedProperty(o,L+"._inputRange").set(null);var E=nt.nestedProperty(o,L).get();E._inputDomain&&(E._input.domain=E._inputDomain.slice())}else T.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&nt.nestedProperty(o,L+"._inputDomain").set(null);if("type"===A){var R=S,N="linear"===C.type&&"log"===w,I="log"===C.type&&"linear"===w;if(N||I){if(R&&R.range)if(C.autorange)N&&(R.range=R.range[1]>R.range[0]?[1,2]:[2,1]);else{var F=R.range[0],j=R.range[1];N?(F<=0&&j<=0&&v(L+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(L+".range[0]",Math.log(F)/Math.LN10),v(L+".range[1]",Math.log(j)/Math.LN10)):(v(L+".range[0]",Math.pow(10,F)),v(L+".range[1]",Math.pow(10,j)))}else v(L+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],O.getComponentMethod("annotations","convertCoords")(e,C,w,v),O.getComponentMethod("images","convertCoords")(e,C,w,v)}else v(L+".autorange",!0),v(L+".range",null);nt.nestedProperty(o,L+"._inputRange").set(null)}else if(A.match(Dd)){var B=nt.nestedProperty(o,b).get(),q=(w||{}).type;q&&"-"!==q||(q="linear"),O.getComponentMethod("annotations","convertCoords")(e,B,q,v),O.getComponentMethod("images","convertCoords")(e,B,q,v)}var H=Yf.containerArrayMatch(b);if(H){n=H.array,r=H.index;var V=H.property,U=(nt.nestedProperty(i,n)||[])[r]||{},G=U,Y=z||{editType:"calc"},X=-1!==Y.editType.indexOf("calcIfAutorange");""===r?(X?h.calc=!0:Xt.update(h,Y),X=!1):""===V&&(G=w,Yf.isAddVal(w)?g[b]=null:Yf.isRemoveVal(w)?(g[b]=U,G=U):nt.warn("unrecognized full object value",t)),X&&(Xd(e,G,"x")||Xd(e,G,"y"))?h.calc=!0:Xt.update(h,Y),c[n]||(c[n]={});var Z=c[n][r];Z||(Z=c[n][r]={}),Z[V]=w,delete t[b]}else"reverse"===A?(S.range?S.range.reverse():(v(L+".autorange",!0),S.range=[1,0]),C.autorange?h.calc=!0:h.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==P&&"select"!==P?h.plot=!0:z?Xt.update(h,z):h.calc=!0,_.set(w))}}for(n in c){Yf.applyContainerArrayChanges(e,nt.nestedProperty(i,n),c[n],h)||(h.plot=!0)}var W=o._axisConstraintGroups||[];for(y in m)for(r=0;r=0&&n=0&&n=a.length?a[0]:a[e]:a}function l(e){return Array.isArray(i)?e>=i.length?i[0]:i[e]:i}function s(e,t){var n=0;return function(){if(e&&++n===t)return e()}}return void 0===r._frameWaitingCnt&&(r._frameWaitingCnt=0),new Promise(function(i,c){function u(){r._currentFrame&&r._currentFrame.onComplete&&r._currentFrame.onComplete();var t=r._currentFrame=r._frameQueue.shift();if(t){var n=t.name?t.name.toString():null;e._fullLayout._currentFrame=n,r._lastFrameAt=Date.now(),r._timeToNext=t.frameOpts.duration,Qr.transition(e,t.frame.data,t.frame.layout,Rf.coerceTraceIndices(e,t.frame.traces),t.frameOpts,t.transitionOpts).then(function(){t.onComplete&&t.onComplete()}),e.emit("plotly_animatingframe",{name:n,frame:t.frame,animation:{frame:t.frameOpts,transition:t.transitionOpts}})}else e.emit("plotly_animated"),window.cancelAnimationFrame(r._animationRaf),r._animationRaf=null}function f(){e.emit("plotly_animating"),r._lastFrameAt=-1/0,r._timeToNext=0,r._runningTransitions=0,r._currentFrame=null;var t=function(){r._animationRaf=window.requestAnimationFrame(t),Date.now()-r._lastFrameAt>r._timeToNext&&u()};t()}var d,h,p=0;function g(e){return Array.isArray(a)?p>=a.length?e.transitionOpts=a[p]:e.transitionOpts=a[0]:e.transitionOpts=a,p++,e}var v=[],y=void 0===t||null===t,m=Array.isArray(t);if(!y&&!m&&nt.isPlainObject(t))v.push({type:"object",data:g(nt.extendFlat({},t))});else if(y||-1!==["string","number"].indexOf(typeof t))for(d=0;d0&&__)&&w.push(h);v=w}}v.length>0?function(t){if(0!==t.length){for(var a=0;a=0;r--)if(nt.isPlainObject(t[r])){var d=t[r].name,h=(s[d]||f[d]||{}).name,p=t[r].name,g=s[h]||f[h];h&&p&&"number"==typeof p&&g&&Ed<5&&(Ed++,nt.warn('addFrames: overwriting frame "'+(s[h]||f[h]).name+'" with a frame whose name of type "number" also equates to "'+h+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===Ed&&nt.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[d]={name:d},u.push({frame:Qr.supplyFrameDefaults(t[r]),index:n&&void 0!==n[r]&&null!==n[r]?n[r]:c+r})}u.sort(function(e,t){return e.index>t.index?-1:e.index=0;r--){if("number"==typeof(a=u[r].frame).name&&nt.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+e._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;n--)r=t[n],i.push({type:"delete",index:r}),o.unshift({type:"insert",index:r,value:a[r]});var l=Qr.modifyFrames,s=Qr.modifyFrames,c=[e,o],u=[e,i];return Df&&Df.add(e,l,c,s,u),Qr.modifyFrames(e,i)},zd.purge=function(e){var t=(e=nt.getGraphDiv(e))._fullLayout||{},n=e._fullData||[],r=e.calcdata||[];return Qr.cleanPlot([],{},n,t,r),Qr.purge(e),Pt.purge(e),t._container&&t._container.remove(),delete e._context,e};var Jd={getDelay:function(e){return e._has&&(e._has("gl3d")||e._has("gl2d")||e._has("mapbox"))?500:0},getRedrawFunc:function(e){var t=e._fullLayout||{};if(!(!(t._has&&t._has("polar"))&&e.data&&e.data[0]&&e.data[0].r))return function(){(e.calcdata||[]).forEach(function(e){e[0]&&e[0].t&&e[0].t.cb&&e[0].t.cb()})}}},Qd=Mt.EventEmitter;var $d=function(e){var t=e.emitter||new Qd,n=new Promise(function(r,a){var i=window.Image,o=e.svg,l=e.format||"png";if(nt.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),e.promise?n:t.emit("error",s)}var c=e.canvas,u=e.scale||1,f=u*(e.width||300),d=u*(e.height||150),h=c.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);c.width=f,c.height=d,p.onload=function(){var n;switch("svg"!==l&&h.drawImage(p,0,0,f,d),l){case"jpeg":n=c.toDataURL("image/jpeg");break;case"png":n=c.toDataURL("image/png");break;case"webp":n=c.toDataURL("image/webp");break;case"svg":n=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!e.promise)return t.emit("error",i)}r(n),e.promise||t.emit("success",n)},p.onerror=function(n){if(a(n),!e.promise)return t.emit("error",n)},p.src=g});return e.promise?n:t},Kd=/"/g,eh=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var th=function(t,n,r){var a,i=t._fullLayout,o=i._paper,l=i._toppaper,s=i.width,c=i.height;o.insert("rect",":first-child").call(Vn.setRect,0,0,s,c).call(dt.fill,i.paper_bgcolor);var u=i._basePlotModules||[];for(a=0;a")?"":n.html(e).text()});return n.remove(),r}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(eh,"'"),nt.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},nh={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},rh=/^data:image\/\w+;base64,/;var ah=function(e,t){var n,r,a;function i(e){return!(e in t)||nt.validate(t[e],nh[e])}if(t=t||{},nt.isPlainObject(e)?(n=e.data||[],r=e.layout||{},a=e.config||{}):(e=nt.getGraphDiv(e),n=nt.extendDeep([],e.data),r=nt.extendDeep({},e.layout),a=e._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(e,n){return nt.coerce(t,o,nh,e,n)}var s=l("format"),c=l("width"),u=l("height"),f=l("scale"),d=l("setBackground"),h=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=nt.extendFlat({},r);c&&(g.width=c),u&&(g.height=u);var v=nt.extendFlat({},a,{staticPlot:!0,setBackground:d}),y=Jd.getRedrawFunc(p);function m(){return new Promise(function(e){setTimeout(e,Jd.getDelay(p._fullLayout))})}function x(){return new Promise(function(e,t){var n=th(p,s,f),r=p._fullLayout.width,a=p._fullLayout.height;if(zd.purge(p),document.body.removeChild(p),"svg"===s)return e(h?n:"data:image/svg+xml,"+encodeURIComponent(n));var i=document.createElement("canvas");i.id=nt.randstr(),$d({format:s,width:r,height:a,scale:f,canvas:i,svg:n,promise:!0}).then(e).catch(t)})}return new Promise(function(e,t){zd.plot(p,n,g,v).then(y).then(m).then(x).then(function(t){e(function(e){return h?e.replace(rh,""):e}(t))}).catch(function(e){t(e)})})},ih=nt.isPlainObject,oh=Array.isArray,lh=nt.isArrayOrTypedArray;function sh(e,t,n,r,a,i){i=i||[];for(var o=Object.keys(e),l=0;lf.length&&r.push(fh("unused",a,c.concat(f.length)));var v,y,m,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===d.dimensions)for(y=0;y<_;y++)if(oh(u[y])){u[y].length>f[y].length&&r.push(fh("unused",a,c.concat(y,f[y].length)));var k=f[y].length;for(v=0;v<(w?Math.min(k,g[y].length):k);v++)m=w?g[y][v]:g,x=u[y][v],b=f[y][v],nt.validate(x,m)?b!==x&&b!==+x&&r.push(fh("dynamic",a,c.concat(y,v),x,b)):r.push(fh("value",a,c.concat(y,v),x))}else r.push(fh("array",a,c.concat(y),u[y]));else for(y=0;y<_;y++)m=w?g[y]:g,x=u[y],b=f[y],nt.validate(x,m)?b!==x&&b!==+x&&r.push(fh("dynamic",a,c.concat(y),x,b)):r.push(fh("value",a,c.concat(y),x))}else if(d.items&&!h&&oh(u)){var M,A,T=g[Object.keys(g)[0]],L=[];for(M=0;M1&&i.push(fh("object","layout"))),Qr.supplyDefaults(o);for(var l=o._fullData,s=n.length,c=0;c-1&&(l[c[n]].title="");for(n=0;nq||e[1]V)return[Vh(e[0],B,q),Vh(e[1],H,V)]}function Y(e,t){return e[0]===t[0]&&(e[0]===B||e[0]===q)||(e[1]===t[1]&&(e[1]===H||e[1]===V)||void 0)}function X(e,t,n){return function(r,a){var i=G(r),o=G(a),l=[];if(i&&o&&Y(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*nt.constrain((r[e]+a[e])/2,t,n)-((i||r)[e]+(o||a)[e]);s&&((i&&o?s>0==i[e]>o[e]?i:o:i||o)[e]+=s);return l}}function Z(e){var t=e[0],n=e[1],r=t===L[S-1][0],a=n===L[S-1][1];if(!r||!a)if(S>1){var i=t===L[S-2][0],o=n===L[S-2][1];r&&(t===B||t===q)&&i?o?S--:L[S-1]=e:a&&(n===H||n===V)&&o?i?S--:L[S-1]=e:L[S++]=e}else L[S++]=e}function W(e){L[S-1][0]!==e[0]&&L[S-1][1]!==e[1]&&Z([E,R]),Z(e),N=null,E=R=0}function J(e){if(O=e[0]q?q:0,D=e[1]V?V:0,O||D){if(S)if(N){var t=F(N,e);t.length>1&&(W(t[0]),L[S++]=t[1])}else I=F(L[S-1],e)[0],L[S++]=I;else L[S++]=[O||e[0],D||e[1]];var n=L[S-1];O&&D&&(n[0]!==O||n[1]!==D)?(N&&(E!==O&&R!==D?Z(E&&R?(r=N,i=(a=e)[0]-r[0],o=(a[1]-r[1])/i,(r[1]*a[0]-a[1]*r[0])/i>0?[o>0?B:q,V]:[o>0?q:B,H]):[E||O,R||D]):E&&R&&Z([E,R])),Z([O,D])):E-O&&R-D&&Z([O||E,D||R]),N=e,E=O,R=D}else N&&W(F(N,e)[0]),L[S++]=e;var r,a,i,o}for("linear"===k||"spline"===k?F=function(e,t){for(var n=[],r=0,a=0;a<4;a++){var i=U[a],o=Hh(e[0],e[1],t[0],t[1],i[0],i[1],i[2],i[3]);o&&(!r||Math.abs(o.x-n[0][0])>1||Math.abs(o.y-n[0][1])>1)&&(o=[o.x,o.y],r&&z(o,e)P(l))break;a=l,(p=u[0]*c[0]+u[1]*c[1])>d?(d=p,i=l,s=!1):p=e.length||!l)break;J(l),r=l}}else J(i)}N&&Z([E||N[0],R||N[1]]),A.push(L.slice(0,S))}return A},Gh=Yi.tester;function Yh(t,n,r,a,i,o,l){var s,c;!function(t,n,r,a,i){var o=r.xaxis,l=r.yaxis,s=e.extent(nt.simpleMap(o.range,o.r2c)),c=e.extent(nt.simpleMap(l.range,l.r2c)),u=a[0].trace;if(!Hn.hasMarkers(u))return;var f=u.marker.maxdisplayed;if(0===f)return;var d=a.filter(function(e){return e.x>=s[0]&&e.x<=s[1]&&e.y>=c[0]&&e.y<=c[1]}),h=Math.ceil(d.length/f),p=0;i.forEach(function(e,t){var r=e[0].trace;Hn.hasMarkers(r)&&r.marker.maxdisplayed>0&&t0;function f(e){return u?e.transition():e}var d=r.xaxis,h=r.yaxis,p=a[0].trace,g=p.line,v=e.select(o);if(O.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var y,m;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),r.isRangePlot||(a[0].node3=v);var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",m=w._nextFill,_=w._polygons);var k,M,A,T,L,S,C,P,z,D="",E="",R=[],N=nt.noop;if(y=p._ownFill,Hn.hasLines(p)||"none"!==p.fill){for(m&&m.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(A=Vn.steps(g.shape),T=Vn.steps(g.shape.split("").reverse().join(""))):A=T="spline"===g.shape?function(e){var t=e[e.length-1];return e.length>1&&e[0][0]===t[0]&&e[0][1]===t[1]?Vn.smoothclosed(e.slice(1),g.smoothing):Vn.smoothopen(e,g.smoothing)}:function(e){return"M"+e.join("L")},L=function(e){return T(e.reverse())},R=Uh(a,{xaxis:d,yaxis:h,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),z=p._polygons=new Array(R.length),c=0;c1){var r=e.select(this);if(r.datum(a),t)f(r.style("opacity",0).attr("d",k).call(Vn.lineGroupStyle)).style("opacity",1);else{var i=f(r);i.attr("d",k),Vn.singleLineStyle(a,i)}}}}}var I=v.selectAll(".js-line").data(R);f(I.exit()).style("opacity",0).remove(),I.each(N(!1)),I.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Vn.lineGroupStyle).each(N(!0)),Vn.setClipUrl(I,r.layerClipId),R.length?(y?S&&P&&(x?("y"===x?S[1]=P[1]=h.c2p(0,!0):"x"===x&&(S[0]=P[0]=d.c2p(0,!0)),f(y).attr("d","M"+P+"L"+S+"L"+D.substr(1)).call(Vn.singleFillStyle)):f(y).attr("d",D+"Z").call(Vn.singleFillStyle)):m&&("tonext"===p.fill.substr(0,6)&&D&&b?("tonext"===p.fill?f(m).attr("d",D+"Z"+b+"Z").call(Vn.singleFillStyle):f(m).attr("d",D+"L"+b.substr(1)+"Z").call(Vn.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(m),p._polygons=null)),p._prevRevpath=E,p._prevPolygons=z):(y?j(y):m&&j(m),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");s=F.data([a]),F.each(U),s.enter().append("g").classed("points",!0).each(U),s.exit().remove(),s.each(function(t){var n=!1===t[0].trace.cliponaxis;Vn.setClipUrl(e.select(this),n?null:r.layerClipId)})}function j(e){f(e).attr("d","M0,0Z")}function B(e){return e.filter(function(e){return e.vis})}function q(e){return e.id}function H(e){if(e.ids)return q}function V(){return!1}function U(n){var a,i=n[0].trace,o=e.select(this),l=Hn.hasMarkers(i),s=Hn.hasText(i),c=H(i),p=V,g=V;l&&(p=i.marker.maxdisplayed||i._needsCull?B:nt.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?B:nt.identity);var v=(a=o.selectAll("path.point").data(p,c)).enter().append("path").classed("point",!0);u&&v.call(Vn.pointStyle,i,t).call(Vn.translatePoints,d,h).style("opacity",0).transition().style("opacity",1);var y=l&&Vn.tryColorscale(i.marker,""),m=l&&Vn.tryColorscale(i.marker,"line");a.order(),a.each(function(n){var a=e.select(this),o=f(a);Vn.translatePoint(n,o,d,h)?(Vn.singlePointStyle(n,o,i,y,m,t),r.layerClipId&&Vn.hideOutsideRangePoint(n,o,d,h,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==n.data&&void 0!==n.data)):o.remove()}),u?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,c)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var n=e.select(this),a=f(n.select("text"));Vn.translatePoint(t,a,d,h)?r.layerClipId&&Vn.hideOutsideRangePoint(t,n,d,h,i.xcalendar,i.ycalendar):n.remove()}),a.selectAll("text").call(Vn.textPointStyle,i,t).each(function(t){var n=d.c2p(t.x),r=h.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){f(e.select(this)).attr({x:n,y:r})})}),a.exit().remove()}}function Xh(e,t,n){var r=e.selectAll("path.point"),a=e.selectAll("text");Vn.pointStyle(r,t,n),Vn.textPointStyle(a,t,n),Vn.selectedPointStyle(r,t),Vn.selectedTextStyle(a,t)}var Zh=function(t,n){var r=n?n[0].node3:e.select(t).selectAll("g.trace.scatter");r.style("opacity",function(e){return e[0].trace.opacity}),r.selectAll("g.points").each(function(n){Xh(e.select(this),n.trace||n[0].trace,t)}),r.selectAll("g.trace path.js-line").call(Vn.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(Vn.fillGroupStyle),O.getComponentMethod("errorbars","style")(r)},Wh=Xh,Jh={};Jh.hasLines=Hn.hasLines,Jh.hasMarkers=Hn.hasMarkers,Jh.hasText=Hn.hasText,Jh.isBubble=Hn.isBubble,Jh.attributes=kr,Jh.supplyDefaults=function(e,t,n,r){function a(n,r){return nt.coerce(e,t,kr,n,r)}var i=function(e,t,n,r){var a,i=r("x"),o=r("y");if(O.getComponentMethod("calendars","handleTraceDefaults")(e,t,["x","y"],n),i)o?a=Math.min(i.length,o.length):(a=i.length,r("y0"),r("dy"));else{if(!o)return 0;a=t.y.length,r("x0"),r("dx")}return t._length=a,a}(e,t,r,a),o=i=0;a--){var i=e[a];if("scatter"===i.type&&i.xaxis===n.xaxis&&i.yaxis===n.yaxis){i.opacity=void 0;break}}}}},Jh.calc=zh,Jh.arraysToCalcdata=rl,Jh.plot=function(t,n,r,a,i){var o,l,s,c,u=n.plot.select("g.scatterlayer"),f=!a,d=!!a&&a.duration>0;for((s=u.selectAll("g.trace").data(r,function(e){return e[0].trace.uid})).enter().append("g").attr("class",function(e){return"trace scatter trace"+e[0].trace.uid}).style("stroke-miterlimit",2),function(e,t,n){var r,a,i=null;for(a=0;al[t[0].trace.uid]?1:-1}),d?(i&&(c=i()),e.transition().duration(a.duration).ease(a.easing).each("end",function(){c&&c()}).each("interrupt",function(){c&&c()}).each(function(){u.selectAll("g.trace").each(function(e,i){Yh(t,i,n,e,r,this,a)})})):u.selectAll("g.trace").each(function(e,i){Yh(t,i,n,e,r,this,a)});f&&s.exit().remove(),u.selectAll("path:not([d])").remove()},Jh.colorbar=Oh,Jh.style=Zh,Jh.hoverPoints=function(e,t,n,r){var a=e.cd,i=a[0].trace,o=e.xa,l=e.ya,s=o.c2p(t),c=l.c2p(n),u=[s,c],f=i.hoveron||"",d=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var h=function(e){var t=Math.max(d,e.mrc||0),n=o.c2p(e.x)-s,r=l.c2p(e.y)-c;return Math.max(Math.sqrt(n*n+r*r)-t,1-d/t)},p=Si.getDistanceFunction(r,function(e){var t=Math.max(3,e.mrc||0),n=1-1/t,r=Math.abs(o.c2p(e.x)-s);return rN!=(L=w[b][1])>=N&&(M=w[b-1][0],A=w[b][0],L-T&&(k=M+(A-M)*(N-T)/(L-T),z=Math.min(z,k),D=Math.max(D,k)));z=Math.max(z,0),D=Math.min(D,o._length);var I=dt.defaultLine;return dt.opacity(i.fillcolor)?I=i.fillcolor:dt.opacity((i.line||{}).color)&&(I=i.line.color),nt.extendFlat(e,{distance:e.maxHoverDistance,x0:z,x1:D,y0:N,y1:N,color:I}),delete e.index,i.text&&!Array.isArray(i.text)?e.text=String(i.text):e.text=i.name,[e]}}},Jh.selectPoints=function(e,t){var n,r,a,i,o=e.cd,l=e.xaxis,s=e.yaxis,c=[],u=o[0].trace;if(!Hn.hasMarkers(u)&&!Hn.hasText(u))return[];if(!1===t)for(n=0;n0&&(n.push(r),r=[])}return r.length>0&&n.push(r),n},lp.makeLine=function(e){return 1===e.length?{type:"LineString",coordinates:e[0]}:{type:"MultiLineString",coordinates:e}},lp.makePolygon=function(e){if(1===e.length)return{type:"Polygon",coordinates:e};for(var t=new Array(e.length),n=0;n")}(a,u,l.mockAxis,r[0].t.labels),[e]}},gp.eventData=function(e,t){return e.lon=t.lon,e.lat=t.lat,e.location=t.loc?t.loc:null,e},gp.selectPoints=function(e,t){var n,r,a,i,o,l=e.cd,s=e.xaxis,c=e.yaxis,u=[],f=l[0].trace;if(!Hn.hasMarkers(f)&&!Hn.hasText(f))return[];if(!1===t)for(o=0;o * but significantly simplified and sped up by ignoring number and string constructors @@ -9604,7 +9754,7 @@ function allBlankCharCodes(str){ return true; } -var _$fastIsnumeric_78 = function(n) { +var _$fastIsnumeric_135 = function(n) { var type = typeof n; if(type === 'string') { var original = n; @@ -9628,7 +9778,7 @@ var _$fastIsnumeric_78 = function(n) { 'use strict'; -var _$numerical_343 = { +var _$numerical_404 = { /** * Standardize all missing data in calcdata to use undefined * never null or NaN. @@ -9675,7 +9825,7 @@ var _$numerical_343 = { MINUS_SIGN: '\u2212' }; -var _$angles_348 = {}; +var _$angles_409 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -9688,20 +9838,20 @@ var _$angles_348 = {}; var PI = Math.PI; -_$angles_348.deg2rad = function(deg) { +_$angles_409.deg2rad = function(deg) { return deg / 180 * PI; }; -_$angles_348.rad2deg = function(rad) { +_$angles_409.rad2deg = function(rad) { return rad / PI * 180; }; -_$angles_348.wrap360 = function(deg) { +_$angles_409.wrap360 = function(deg) { var out = deg % 360; return out < 0 ? out + 360 : out; }; -_$angles_348.wrap180 = function(deg) { +_$angles_409.wrap180 = function(deg) { if(Math.abs(deg) > 180) deg -= Math.round(deg / 360) * 360; return deg; }; @@ -9717,9 +9867,9 @@ _$angles_348.wrap180 = function(deg) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -var BADNUM = _$numerical_343.BADNUM; +var BADNUM = _$numerical_404.BADNUM; // precompile for speed var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; @@ -9728,17 +9878,17 @@ var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; * cleanNumber: remove common leading and trailing cruft * Always returns either a number or BADNUM. */ -var _$cleanNumber_349 = function cleanNumber(v) { +var _$cleanNumber_410 = function cleanNumber(v) { if(typeof v === 'string') { v = v.replace(JUNK, ''); } - if(_$fastIsnumeric_78(v)) return Number(v); + if(_$fastIsnumeric_135(v)) return Number(v); return BADNUM; }; -var _$tinycolor_201 = { exports: {} }; +var _$tinycolor_263 = { exports: {} }; // TinyColor v1.4.1 // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License @@ -10921,8 +11071,8 @@ function validateWCAG2Parms(parms) { } // Node: Export function -if ("object" !== "undefined" && _$tinycolor_201.exports) { - _$tinycolor_201.exports = tinycolor; +if ("object" !== "undefined" && _$tinycolor_263.exports) { + _$tinycolor_263.exports = tinycolor; } // AMD/requirejs: Define the module else if (typeof define === 'function' && define.amd) { @@ -10935,7 +11085,7 @@ else { })(Math); -_$tinycolor_201 = _$tinycolor_201.exports +_$tinycolor_263 = _$tinycolor_263.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -10947,7 +11097,7 @@ _$tinycolor_201 = _$tinycolor_201.exports 'use strict'; -var _$scales_258 = { +var _$scales_320 = { 'Greys': [ [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)'] ], @@ -11088,10 +11238,10 @@ var _$scales_258 = { 'use strict'; -/* removed: var _$scales_258 = require('./scales'); */; +/* removed: var _$scales_320 = require('./scales'); */; -var _$default_scale_248 = _$scales_258.RdBu; +var _$default_scale_310 = _$scales_320.RdBu; /** * Copyright 2012-2018, Plotly, Inc. @@ -11104,10 +11254,10 @@ var _$default_scale_248 = _$scales_258.RdBu; 'use strict'; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; -var _$isValidScaleArray_256 = function isValidScaleArray(scl) { +var _$isValidScaleArray_318 = function isValidScaleArray(scl) { var highestVal = 0; if(!Array.isArray(scl) || scl.length < 2) return false; @@ -11119,7 +11269,7 @@ var _$isValidScaleArray_256 = function isValidScaleArray(scl) { for(var i = 0; i < scl.length; i++) { var si = scl[i]; - if(si.length !== 2 || +si[0] < highestVal || !_$tinycolor_201(si[1]).isValid()) { + if(si.length !== 2 || +si[0] < highestVal || !_$tinycolor_263(si[1]).isValid()) { return false; } @@ -11140,18 +11290,18 @@ var _$isValidScaleArray_256 = function isValidScaleArray(scl) { 'use strict'; -/* removed: var _$scales_258 = require('./scales'); */; -/* removed: var _$default_scale_248 = require('./default_scale'); */; -/* removed: var _$isValidScaleArray_256 = require('./is_valid_scale_array'); */; +/* removed: var _$scales_320 = require('./scales'); */; +/* removed: var _$default_scale_310 = require('./default_scale'); */; +/* removed: var _$isValidScaleArray_318 = require('./is_valid_scale_array'); */; -var _$getScale_252 = function getScale(scl, dflt) { - if(!dflt) dflt = _$default_scale_248; +var _$getScale_314 = function getScale(scl, dflt) { + if(!dflt) dflt = _$default_scale_310; if(!scl) return dflt; function parseScale() { try { - scl = _$scales_258[scl] || JSON.parse(scl); + scl = _$scales_320[scl] || JSON.parse(scl); } catch(e) { scl = dflt; @@ -11164,7 +11314,7 @@ var _$getScale_252 = function getScale(scl, dflt) { if(typeof scl === 'string') parseScale(); } - if(!_$isValidScaleArray_256(scl)) return dflt; + if(!_$isValidScaleArray_318(scl)) return dflt; return scl; }; @@ -11179,7 +11329,7 @@ var _$getScale_252 = function getScale(scl, dflt) { 'use strict'; -var _$interactions_342 = { +var _$interactions_403 = { /** * Timing information for interactive elements */ @@ -11194,7 +11344,7 @@ var _$interactions_342 = { DESELECTDIM: 0.2 }; -var _$is_array_364 = {}; +var _$is_array_426 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11215,12 +11365,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_364.isTypedArray = function(a) { +_$is_array_426.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_364.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_364.isTypedArray(a); +_$is_array_426.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_426.isTypedArray(a); }; /** @@ -11235,7 +11385,7 @@ _$is_array_364.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_365 = function isPlainObject(obj) { +var _$isPlainObject_427 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11251,7 +11401,7 @@ var _$isPlainObject_365 = function isPlainObject(obj) { ); }; -var _$extend_354 = {}; +var _$extend_416 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11263,7 +11413,7 @@ var _$extend_354 = {}; 'use strict'; -/* removed: var _$isPlainObject_365 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_427 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11280,19 +11430,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_354.extendFlat = function() { +_$extend_416.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_354.extendDeep = function() { +_$extend_416.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_354.extendDeepAll = function() { +_$extend_416.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_354.extendDeepNoArrays = function() { +_$extend_416.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11345,12 +11495,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_365(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_427(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_365(src) ? src : {}; + clone = src && _$isPlainObject_427(src) ? src : {}; } // never move original objects, clone them @@ -11385,7 +11535,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_397 = { +var _$plot_config_460 = { // no interactivity, for export or image generation staticPlot: false, @@ -11553,7 +11703,7 @@ var _$plot_config_397 = { locales: {} }; -var _$loggers_368 = {}; +var _$loggers_430 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11566,9 +11716,9 @@ var _$loggers_368 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_397 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_460 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_368 = {}; +var loggers = _$loggers_430 = {}; /** * ------------------------------------------ @@ -11577,7 +11727,7 @@ var loggers = _$loggers_368 = {}; */ loggers.log = function() { - if(_$plot_config_397.logging > 1) { + if(_$plot_config_460.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11589,7 +11739,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_397.logging > 0) { + if(_$plot_config_460.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11601,7 +11751,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_397.logging > 0) { + if(_$plot_config_460.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11640,7 +11790,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_372 = function noop() {}; +var _$noop_434 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11665,7 +11815,7 @@ var _$noop_372 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_376 = function pushUnique(array, item) { +var _$pushUnique_439 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11706,7 +11856,7 @@ var _$pushUnique_376 = function pushUnique(array, item) { * * @return {object} attributes object containing {family, size, color} as specified */ -var _$font_attributes_434 = function(opts) { +var _$font_attributes_496 = function(opts) { var editType = opts.editType; var colorEditType = opts.colorEditType; if(colorEditType === undefined) colorEditType = editType; @@ -11755,9 +11905,9 @@ var _$font_attributes_434 = function(opts) { 'use strict'; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; -var _$attributes_273 = { +var _$attributes_335 = { hoverlabel: { bgcolor: { valType: 'color', @@ -11773,7 +11923,7 @@ var _$attributes_273 = { editType: 'none', }, - font: _$font_attributes_434({ + font: _$font_attributes_496({ arrayOk: true, editType: 'none', @@ -11800,9 +11950,9 @@ var _$attributes_273 = { 'use strict'; -/* removed: var _$attributes_273 = require('../components/fx/attributes'); */; +/* removed: var _$attributes_335 = require('../components/fx/attributes'); */; -var _$attributes_404 = { +var _$attributes_467 = { type: { valType: 'enumerated', @@ -11886,7 +12036,7 @@ var _$attributes_404 = { editType: 'none', }, - hoverlabel: _$attributes_273.hoverlabel, + hoverlabel: _$attributes_335.hoverlabel, stream: { token: { valType: 'string', @@ -11909,7 +12059,7 @@ var _$attributes_404 = { } }; -var _$attributes_238 = {}; +var _$attributes_300 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11922,7 +12072,7 @@ var _$attributes_238 = {}; // IMPORTANT - default colors should be in hex for compatibility -_$attributes_238.defaults = [ +_$attributes_300.defaults = [ '#1f77b4', // muted blue '#ff7f0e', // safety orange '#2ca02c', // cooked asparagus green @@ -11935,19 +12085,19 @@ _$attributes_238.defaults = [ '#17becf' // blue-teal ]; -_$attributes_238.defaultLine = '#444'; +_$attributes_300.defaultLine = '#444'; -_$attributes_238.lightLine = '#eee'; +_$attributes_300.lightLine = '#eee'; -_$attributes_238.background = '#fff'; +_$attributes_300.background = '#fff'; -_$attributes_238.borderLine = '#BEC8D9'; +_$attributes_300.borderLine = '#BEC8D9'; // with axis.color and Color.interp we aren't using lightLine // itself anymore, instead interpolating between axis.color // and the background color using tinycolor.mix. lightFraction // gives back exactly lightLine if the other colors are defaults. -_$attributes_238.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); +_$attributes_300.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); /** * Copyright 2012-2018, Plotly, Inc. @@ -11959,18 +12109,18 @@ _$attributes_238.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); 'use strict'; -/* removed: var _$font_attributes_434 = require('./font_attributes'); */; -/* removed: var _$attributes_238 = require('../components/color/attributes'); */; +/* removed: var _$font_attributes_496 = require('./font_attributes'); */; +/* removed: var _$attributes_300 = require('../components/color/attributes'); */; -var globalFont = _$font_attributes_434({ +var globalFont = _$font_attributes_496({ editType: 'calc', }); globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; globalFont.size.dflt = 12; -globalFont.color.dflt = _$attributes_238.defaultLine; +globalFont.color.dflt = _$attributes_300.defaultLine; -var _$layout_attributes_442 = { +var _$layout_attributes_504 = { font: globalFont, title: { valType: 'string', @@ -11978,7 +12128,7 @@ var _$layout_attributes_442 = { editType: 'layoutstyle', }, - titlefont: _$font_attributes_434({ + titlefont: _$font_attributes_496({ editType: 'layoutstyle', }), @@ -12059,7 +12209,7 @@ var _$layout_attributes_442 = { paper_bgcolor: { valType: 'color', - dflt: _$attributes_238.background, + dflt: _$attributes_300.background, editType: 'plot', }, @@ -12068,7 +12218,7 @@ var _$layout_attributes_442 = { // because it needs to know if there are (2D) axes or not valType: 'color', - dflt: _$attributes_238.background, + dflt: _$attributes_300.background, editType: 'layoutstyle', }, @@ -12095,7 +12245,7 @@ var _$layout_attributes_442 = { }, colorway: { valType: 'colorlist', - dflt: _$attributes_238.defaults, + dflt: _$attributes_300.defaults, editType: 'calc', @@ -12108,7 +12258,7 @@ var _$layout_attributes_442 = { } }; -var _$registry_451 = {}; +var _$registry_514 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12119,29 +12269,29 @@ var _$registry_451 = {}; 'use strict'; -/* removed: var _$loggers_368 = require('./lib/loggers'); */; -/* removed: var _$noop_372 = require('./lib/noop'); */; -/* removed: var _$pushUnique_376 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_365 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_354 = require('./lib/extend'); */; - -/* removed: var _$attributes_404 = require('./plots/attributes'); */; -/* removed: var _$layout_attributes_442 = require('./plots/layout_attributes'); */; - -var extendFlat = _$extend_354.extendFlat; -var extendDeepAll = _$extend_354.extendDeepAll; - -_$registry_451.modules = {}; -_$registry_451.allCategories = {}; -_$registry_451.allTypes = []; -_$registry_451.subplotsRegistry = {}; -_$registry_451.transformsRegistry = {}; -_$registry_451.componentsRegistry = {}; -_$registry_451.layoutArrayContainers = []; -_$registry_451.layoutArrayRegexes = []; -_$registry_451.traceLayoutAttributes = {}; -_$registry_451.localeRegistry = {}; -_$registry_451.apiMethodRegistry = {}; +/* removed: var _$loggers_430 = require('./lib/loggers'); */; +/* removed: var _$noop_434 = require('./lib/noop'); */; +/* removed: var _$pushUnique_439 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_427 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_416 = require('./lib/extend'); */; + +/* removed: var _$attributes_467 = require('./plots/attributes'); */; +/* removed: var _$layout_attributes_504 = require('./plots/layout_attributes'); */; + +var extendFlat = _$extend_416.extendFlat; +var extendDeepAll = _$extend_416.extendDeepAll; + +_$registry_514.modules = {}; +_$registry_514.allCategories = {}; +_$registry_514.allTypes = []; +_$registry_514.subplotsRegistry = {}; +_$registry_514.transformsRegistry = {}; +_$registry_514.componentsRegistry = {}; +_$registry_514.layoutArrayContainers = []; +_$registry_514.layoutArrayRegexes = []; +_$registry_514.traceLayoutAttributes = {}; +_$registry_514.localeRegistry = {}; +_$registry_514.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12182,7 +12332,7 @@ _$registry_451.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_451.register = function register(_modules) { +_$registry_514.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12211,7 +12361,7 @@ _$registry_451.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_451.apiMethodRegistry[name] = newModule.fn; + _$registry_514.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12227,8 +12377,8 @@ _$registry_451.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_451.getModule = function(trace) { - var _module = _$registry_451.modules[getTraceType(trace)]; +_$registry_514.getModule = function(trace) { + var _module = _$registry_514.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12242,20 +12392,20 @@ _$registry_451.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_451.traceIs = function(traceType, category) { +_$registry_514.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_451.modules[traceType]; + var _module = _$registry_514.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_368.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_430.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_451.modules[_$attributes_404.type.dflt]; + _module = _$registry_514.modules[_$attributes_467.type.dflt]; } return !!_module.categories[category]; @@ -12272,7 +12422,7 @@ _$registry_451.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_451.getTransformIndices = function(data, type) { +_$registry_514.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12292,7 +12442,7 @@ _$registry_451.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_451.hasTransform = function(data, type) { +_$registry_514.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12312,11 +12462,11 @@ _$registry_451.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_451.getComponentMethod = function(name, method) { - var _module = _$registry_451.componentsRegistry[name]; +_$registry_514.getComponentMethod = function(name, method) { + var _module = _$registry_514.componentsRegistry[name]; - if(!_module) return _$noop_372; - return _module[method] || _$noop_372; + if(!_module) return _$noop_434; + return _module[method] || _$noop_434; }; /** @@ -12326,10 +12476,10 @@ _$registry_451.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_451.call = function() { +_$registry_514.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_451.apiMethodRegistry[name].apply(null, args); + return _$registry_514.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12337,33 +12487,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_451.modules[thisType]) { - _$loggers_368.log('Type ' + thisType + ' already registered'); + if(_$registry_514.modules[thisType]) { + _$loggers_430.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_451.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_514.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_451.allCategories[categoriesIn[i]] = true; + _$registry_514.allCategories[categoriesIn[i]] = true; } - _$registry_451.modules[thisType] = { + _$registry_514.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_451.modules[thisType].meta = meta; + _$registry_514.modules[thisType].meta = meta; } - _$registry_451.allTypes.push(thisType); + _$registry_514.allTypes.push(thisType); - for(var componentName in _$registry_451.componentsRegistry) { + for(var componentName in _$registry_514.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12373,15 +12523,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_451.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_514.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_451.subplotsRegistry[plotType]) { - _$loggers_368.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_514.subplotsRegistry[plotType]) { + _$loggers_430.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12391,9 +12541,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_451.subplotsRegistry[plotType] = _module; + _$registry_514.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_451.componentsRegistry) { + for(var componentName in _$registry_514.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12404,29 +12554,29 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_451.componentsRegistry[name] = _module; + _$registry_514.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_376(_$registry_451.layoutArrayContainers, name); + _$pushUnique_439(_$registry_514.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_451.modules) { + for(var traceType in _$registry_514.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_451.subplotsRegistry) { + for(var subplotName in _$registry_514.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_451.transformsRegistry) { + for(var transformType in _$registry_514.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } if(_module.schema && _module.schema.layout) { - extendDeepAll(_$layout_attributes_442, _module.schema.layout); + extendDeepAll(_$layout_attributes_504, _module.schema.layout); } } @@ -12443,22 +12593,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_368.log([ + _$loggers_430.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_365(_module.attributes)) { - _$loggers_368.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_427(_module.attributes)) { + _$loggers_430.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_368.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_430.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_451.transformsRegistry[_module.name] = _module; + _$registry_514.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_451.componentsRegistry) { + for(var componentName in _$registry_514.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12472,7 +12622,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_451.localeRegistry; + var locales = _$registry_514.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12504,37 +12654,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_376(_$registry_451.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_439(_$registry_514.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_451.componentsRegistry[componentName].schema; + var componentSchema = _$registry_514.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_451.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_514.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_451.componentsRegistry[componentName].schema; + var componentSchema = _$registry_514.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_451.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_514.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_451.componentsRegistry[componentName].schema; + var componentSchema = _$registry_514.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_451.subplotsRegistry[subplotName]; + var subplotModule = _$registry_514.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12561,7 +12711,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_451 = require('../registry'); */; +/* removed: var _$registry_514 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12576,9 +12726,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_391 = function containerArrayMatch(astr) { - var rootContainers = _$registry_451.layoutArrayContainers, - regexpContainers = _$registry_451.layoutArrayRegexes, +var _$containerArrayMatch_454 = function containerArrayMatch(astr) { + var rootContainers = _$registry_514.layoutArrayContainers, + regexpContainers = _$registry_514.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12618,10 +12768,10 @@ var _$containerArrayMatch_391 = function containerArrayMatch(astr) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_364.isArrayOrTypedArray; -/* removed: var _$isPlainObject_365 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_391 = require('../plot_api/container_array_match'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +var isArrayOrTypedArray = _$is_array_426.isArrayOrTypedArray; +/* removed: var _$isPlainObject_427 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_454 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12637,8 +12787,8 @@ var isArrayOrTypedArray = _$is_array_364.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_371 = function nestedProperty(container, propStr) { - if(_$fastIsnumeric_78(propStr)) propStr = String(propStr); +var _$nestedProperty_433 = function nestedProperty(container, propStr) { + if(_$fastIsnumeric_135(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { throw 'bad property string'; @@ -12748,7 +12898,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_365(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_427(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12757,7 +12907,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_391(propStr); + var match = _$containerArrayMatch_454(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12812,7 +12962,7 @@ function npSet(cont, parts, propStr) { function joinPropStr(propStr, newPart) { var toAdd = newPart; - if(_$fastIsnumeric_78(newPart)) toAdd = '[' + newPart + ']'; + if(_$fastIsnumeric_135(newPart)) toAdd = '[' + newPart + ']'; else if(propStr) toAdd = '.' + newPart; return propStr + toAdd; @@ -12910,7 +13060,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_378 = {}; +var _$regex_441 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12930,7 +13080,7 @@ var _$regex_378 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_378.counter = function(head, tail, openEnded) { +_$regex_441.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12938,7 +13088,7 @@ _$regex_378.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_350 = {}; +var _$coerce_412 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12950,19 +13100,19 @@ var _$coerce_350 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; -/* removed: var _$attributes_404 = require('../plots/attributes'); */; -/* removed: var _$getScale_252 = require('../components/colorscale/get_scale'); */; -var colorscaleNames = Object.keys(_$scales_258); -/* removed: var _$nestedProperty_371 = require('./nested_property'); */; -var counterRegex = _$regex_378.counter; -var DESELECTDIM = _$interactions_342.DESELECTDIM; -var wrap180 = _$angles_348.wrap180; -var __isArrayOrTypedArray_350 = _$is_array_364.isArrayOrTypedArray; +/* removed: var _$attributes_467 = require('../plots/attributes'); */; +/* removed: var _$getScale_314 = require('../components/colorscale/get_scale'); */; +var colorscaleNames = Object.keys(_$scales_320); +/* removed: var _$nestedProperty_433 = require('./nested_property'); */; +var counterRegex = _$regex_441.counter; +var DESELECTDIM = _$interactions_403.DESELECTDIM; +var wrap180 = _$angles_409.wrap180; +var __isArrayOrTypedArray_412 = _$is_array_426.isArrayOrTypedArray; -_$coerce_350.valObjectMeta = { +_$coerce_412.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12970,7 +13120,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_350(v)) propOut.set(v); + if(__isArrayOrTypedArray_412(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13012,7 +13162,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt, opts) { - if(!_$fastIsnumeric_78(v) || + if(!_$fastIsnumeric_135(v) || (opts.min !== undefined && v < opts.min) || (opts.max !== undefined && v > opts.max)) { propOut.set(dflt); @@ -13025,7 +13175,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt, opts) { - if(v % 1 || !_$fastIsnumeric_78(v) || + if(v % 1 || !_$fastIsnumeric_135(v) || (opts.min !== undefined && v < opts.min) || (opts.max !== undefined && v > opts.max)) { propOut.set(dflt); @@ -13054,7 +13204,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { - if(_$tinycolor_201(v).isValid()) propOut.set(v); + if(_$tinycolor_263(v).isValid()) propOut.set(v); else propOut.set(dflt); } }, @@ -13064,7 +13214,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { function isColor(color) { - return _$tinycolor_201(color).isValid(); + return _$tinycolor_263(color).isValid(); } if(!Array.isArray(v) || !v.length) propOut.set(dflt); else if(v.every(isColor)) propOut.set(v); @@ -13076,7 +13226,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { - propOut.set(_$getScale_252(v, dflt)); + propOut.set(_$getScale_314(v, dflt)); } }, angle: { @@ -13085,7 +13235,7 @@ _$coerce_350.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { if(v === 'auto') propOut.set('auto'); - else if(!_$fastIsnumeric_78(v)) propOut.set(dflt); + else if(!_$fastIsnumeric_135(v)) propOut.set(dflt); else propOut.set(wrap180(+v)); } }, @@ -13093,8 +13243,9 @@ _$coerce_350.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13148,9 +13299,11 @@ _$coerce_350.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13161,12 +13314,12 @@ _$coerce_350.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_350.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_412.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13176,19 +13329,28 @@ _$coerce_350.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13219,12 +13381,12 @@ _$coerce_350.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_350.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_412.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_350.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_412.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13244,10 +13406,10 @@ _$coerce_350.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_350.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_371(attributes, attribute).get(), - propIn = _$nestedProperty_371(containerIn, attribute), - propOut = _$nestedProperty_371(containerOut, attribute), +_$coerce_412.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_433(attributes, attribute).get(), + propIn = _$nestedProperty_433(containerIn, attribute), + propOut = _$nestedProperty_433(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13258,12 +13420,12 @@ _$coerce_350.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_350(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_412(v)) { propOut.set(v); return v; } - _$coerce_350.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_412.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13275,9 +13437,9 @@ _$coerce_350.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_350.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_371(containerIn, attribute), - propOut = _$coerce_350.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_412.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_433(containerIn, attribute), + propOut = _$coerce_412.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13288,7 +13450,7 @@ _$coerce_350.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_350.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_412.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13308,11 +13470,9 @@ _$coerce_350.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_350.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_412.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_404; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_467; var valObj = attrs.hoverinfo; var dflt; @@ -13326,7 +13486,7 @@ _$coerce_350.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_350.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_412.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13340,7 +13500,7 @@ _$coerce_350.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_350.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_412.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13355,7 +13515,7 @@ _$coerce_350.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_350(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_412(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13364,10 +13524,10 @@ _$coerce_350.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_350.validate = function(value, opts) { - var valObjectDef = _$coerce_350.valObjectMeta[opts.valType]; +_$coerce_412.validate = function(value, opts) { + var valObjectDef = _$coerce_412.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_350(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_412(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13397,12 +13557,12 @@ _$coerce_350.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_370 = function mod(v, d) { +var _$mod_432 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_351 = {}; +var _$dates_413 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13414,23 +13574,23 @@ var _$dates_351 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$loggers_368 = require('./loggers'); */; -/* removed: var _$mod_370 = require('./mod'); */; +/* removed: var _$loggers_430 = require('./loggers'); */; +/* removed: var _$mod_432 = require('./mod'); */; -/* removed: var _$numerical_343 = require('../constants/numerical'); */; -var __BADNUM_351 = _$numerical_343.BADNUM; -var ONEDAY = _$numerical_343.ONEDAY; -var ONEHOUR = _$numerical_343.ONEHOUR; -var ONEMIN = _$numerical_343.ONEMIN; -var ONESEC = _$numerical_343.ONESEC; -var EPOCHJD = _$numerical_343.EPOCHJD; +/* removed: var _$numerical_404 = require('../constants/numerical'); */; +var __BADNUM_413 = _$numerical_404.BADNUM; +var ONEDAY = _$numerical_404.ONEDAY; +var ONEHOUR = _$numerical_404.ONEHOUR; +var ONEMIN = _$numerical_404.ONEMIN; +var ONESEC = _$numerical_404.ONESEC; +var EPOCHJD = _$numerical_404.EPOCHJD; -/* removed: var _$registry_451 = require('../registry'); */; +/* removed: var _$registry_514 = require('../registry'); */; -var utcFormat = _$d3_68.time.format.utc; +var utcFormat = _$d3_71.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 @@ -13442,7 +13602,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_451.componentsRegistry.calendars && + _$registry_514.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13452,11 +13612,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_351.dateTick0 = function(calendar, sunday) { +_$dates_413.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_451.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_451.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_514.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_514.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13466,9 +13626,9 @@ _$dates_351.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_351.dfltRange = function(calendar) { +_$dates_413.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_451.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_514.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13476,7 +13636,7 @@ _$dates_351.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_351.isJSDate = function(v) { +_$dates_413.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13538,17 +13698,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_351.dateTime2ms = function(s, calendar) { +_$dates_413.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_351.isJSDate(s)) { + if(_$dates_413.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_351; + return __BADNUM_413; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_351; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_413; s = String(s); @@ -13565,7 +13725,7 @@ _$dates_351.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_351; + if(!match) return __BADNUM_413; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13575,12 +13735,12 @@ _$dates_351.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_351; + if(y.length === 2) return __BADNUM_413; y = Number(y); var cDate; try { - var calInstance = _$registry_451.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_514.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13590,9 +13750,9 @@ _$dates_351.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_351; } // Invalid ... date + catch(e) { return __BADNUM_413; } // Invalid ... date - if(!cDate) return __BADNUM_351; + if(!cDate) return __BADNUM_413; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13613,18 +13773,18 @@ _$dates_351.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_351; - if(date.getUTCDate() !== d) return __BADNUM_351; + if(date.getUTCMonth() !== m) return __BADNUM_413; + if(date.getUTCDate() !== d) return __BADNUM_413; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_351.MIN_MS = _$dates_351.dateTime2ms('-9999'); -MAX_MS = _$dates_351.MAX_MS = _$dates_351.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_413.MIN_MS = _$dates_413.dateTime2ms('-9999'); +MAX_MS = _$dates_413.MAX_MS = _$dates_413.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_351.isDateTime = function(s, calendar) { - return (_$dates_351.dateTime2ms(s, calendar) !== __BADNUM_351); +_$dates_413.isDateTime = function(s, calendar) { + return (_$dates_413.dateTime2ms(s, calendar) !== __BADNUM_413); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13643,20 +13803,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_351.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_351; +_$dates_413.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_413; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_370(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_432(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_370(ms, ONEDAY)); + timeMs = Math.floor(_$mod_432(ms, ONEDAY)); try { - dateStr = _$registry_451.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_514.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13704,12 +13864,12 @@ _$dates_351.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_351.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_351; +_$dates_413.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_413; - var msecTenths = Math.floor(_$mod_370(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_432(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), - dateStr = _$d3_68.time.format('%Y-%m-%d')(d), + dateStr = _$d3_71.time.format('%Y-%m-%d')(d), h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), @@ -13740,23 +13900,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_351.cleanDate = function(v, dflt, calendar) { - if(_$dates_351.isJSDate(v) || typeof v === 'number') { +_$dates_413.cleanDate = function(v, dflt, calendar) { + if(_$dates_413.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_368.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_430.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 = _$dates_351.ms2DateTimeLocal(+v); + v = _$dates_413.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_351.isDateTime(v, calendar)) { - _$loggers_368.error('unrecognized date', v); + else if(!_$dates_413.isDateTime(v, calendar)) { + _$loggers_430.error('unrecognized date', v); return dflt; } return v; @@ -13786,7 +13946,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_451.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_514.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13803,13 +13963,13 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_370(x + 0.05, ONEDAY); + var timePart = _$mod_432(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_370(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_432(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { - if(!_$fastIsnumeric_78(tr)) tr = 0; // should only be 'S' + if(!_$fastIsnumeric_135(tr)) tr = 0; // should only be 'S' /* * this is a weird one - and shouldn't come up unless people @@ -13826,7 +13986,7 @@ function formatTime(x, tr) { * 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_370(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_432(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13855,7 +14015,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_351.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_413.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13899,19 +14059,19 @@ _$dates_351.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_351.incrementMonth = function(ms, dMonth, calendar) { +_$dates_413.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_370(ms, ONEDAY); + var timeMs = _$mod_432(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_451.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_514.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13920,7 +14080,7 @@ _$dates_351.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_368.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_430.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13935,7 +14095,7 @@ _$dates_351.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_351.findExactDates = function(data, calendar) { +_$dates_413.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13945,14 +14105,14 @@ _$dates_351.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_451.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_514.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { di = data[i]; // not date data at all - if(!_$fastIsnumeric_78(di)) { + if(!_$fastIsnumeric_135(di)) { blankCount ++; continue; } @@ -14012,7 +14172,7 @@ _$dates_351.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_352 = function ensureArray(out, n) { +var _$ensureArray_414 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14055,7 +14215,7 @@ var _$ensureArray_352 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_355 = function filterUnique(array) { +var _$filterUnique_417 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14089,7 +14249,7 @@ var _$filterUnique_355 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_356 = function filterVisible(container) { +var _$filterVisible_418 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14118,7 +14278,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_357 = {}; +var _$geometry2d_419 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14129,13 +14289,13 @@ var _$geometry2d_357 = {}; 'use strict'; -/* removed: var _$mod_370 = require('./mod'); */; +/* removed: var _$mod_432 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_357.segmentsIntersect = segmentsIntersect; +_$geometry2d_419.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14158,7 +14318,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_357.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_419.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 @@ -14211,7 +14371,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_357.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_419.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14223,13 +14383,13 @@ _$geometry2d_357.getTextLocation = function getTextLocation(path, totalPathLen, // 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_370(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_370(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_432(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_432(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_370(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_432(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14238,7 +14398,7 @@ _$geometry2d_357.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_357.clearLocationCache = function() { +_$geometry2d_419.clearLocationCache = function() { workingPath = null; }; @@ -14266,7 +14426,7 @@ _$geometry2d_357.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_357.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_419.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14327,7 +14487,7 @@ _$geometry2d_357.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_357.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_419.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14382,7 +14542,7 @@ _$geometry2d_357.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_358 = function(gd) { +var _$get_graph_div_420 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14414,7 +14574,7 @@ var _$get_graph_div_358 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_362 = function identity(d) { return d; }; +var _$identity_424 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14426,7 +14586,7 @@ var _$identity_362 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_371 = require('./nested_property'); */; +/* removed: var _$nestedProperty_433 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14448,13 +14608,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_428 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_371(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_433(baseObj, path).get(); } else { arr = baseObj; } @@ -14480,7 +14640,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_371(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_433(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14490,7 +14650,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_371(newValue, valueName).set(value); + _$nestedProperty_433(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14511,7 +14671,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_371(arr[idx], valueName).get(); + return _$nestedProperty_433(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14552,7 +14712,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value } 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_371(object, valueName).set(null); + _$nestedProperty_433(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, @@ -14579,7 +14739,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_371(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_433(arr[idx], valueName).get(); } } } else { @@ -14605,7 +14765,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_451 = require('../registry'); */; +/* removed: var _$registry_514 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14616,7 +14776,7 @@ var _$keyedContainer_366 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_367 = function localize(gd, s) { +var _$localize_429 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14638,7 +14798,7 @@ var _$localize_367 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_451.localeRegistry; + locales = _$registry_514.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14649,7 +14809,7 @@ var _$localize_367 = function localize(gd, s) { return s; }; -var _$matrix_369 = {}; +var _$matrix_431 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14662,7 +14822,7 @@ var _$matrix_369 = {}; 'use strict'; -_$matrix_369.init2dArray = function(rowLength, colLength) { +_$matrix_431.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14673,7 +14833,7 @@ _$matrix_369.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_369.transposeRagged = function(z) { +_$matrix_431.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14691,7 +14851,7 @@ _$matrix_369.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_369.dot = function(x, y) { +_$matrix_431.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14701,13 +14861,13 @@ _$matrix_369.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_369.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_431.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_369.transposeRagged(y); + var yTranspose = _$matrix_431.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_369.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_431.dot(x, yTranspose[i]); } else { // vec-vec @@ -14719,12 +14879,12 @@ _$matrix_369.dot = function(x, y) { }; // translate by (x,y) -_$matrix_369.translationMatrix = function(x, y) { +_$matrix_431.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_369.rotationMatrix = function(alpha) { +_$matrix_431.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14732,28 +14892,28 @@ _$matrix_369.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_369.rotationXYMatrix = function(a, x, y) { - return _$matrix_369.dot( - _$matrix_369.dot(_$matrix_369.translationMatrix(x, y), - _$matrix_369.rotationMatrix(a)), - _$matrix_369.translationMatrix(-x, -y)); +_$matrix_431.rotationXYMatrix = function(a, x, y) { + return _$matrix_431.dot( + _$matrix_431.dot(_$matrix_431.translationMatrix(x, y), + _$matrix_431.rotationMatrix(a)), + _$matrix_431.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_369.apply2DTransform = function(transform) { +_$matrix_431.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_369.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_431.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_369.apply2DTransform2 = function(transform) { - var at = _$matrix_369.apply2DTransform(transform); +_$matrix_431.apply2DTransform2 = function(transform) { + var at = _$matrix_431.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14770,8 +14930,8 @@ _$matrix_369.apply2DTransform2 = function(transform) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; var NOTEDATA = []; @@ -14782,16 +14942,16 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_373 = function(text, displayLength) { +var _$notifier_435 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); var ts = 1000; - if(_$fastIsnumeric_78(displayLength)) ts = displayLength; + if(_$fastIsnumeric_135(displayLength)) ts = displayLength; else if(displayLength === 'long') ts = 3000; - var notifierContainer = _$d3_68.select('body') + var notifierContainer = _$d3_71.select('body') .selectAll('.plotly-notifier') .data([0]); notifierContainer.enter() @@ -14807,7 +14967,7 @@ var _$notifier_373 = function(text, displayLength) { .each('end', function(thisText) { var thisIndex = NOTEDATA.indexOf(thisText); if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1); - _$d3_68.select(this).remove(); + _$d3_71.select(this).remove(); }); } @@ -14815,7 +14975,7 @@ var _$notifier_373 = function(text, displayLength) { .classed('notifier-note', true) .style('opacity', 0) .each(function(thisText) { - var note = _$d3_68.select(this); + var note = _$d3_71.select(this); note.append('button') .classed('notifier-close', true) @@ -14874,7 +15034,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_379 = function(baseAttr, relativeAttr) { +var _$relative_attr_442 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14903,8 +15063,8 @@ var _$relative_attr_379 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_380 = _$is_array_364.isArrayOrTypedArray; -/* removed: var _$isPlainObject_365 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_443 = _$is_array_426.isArrayOrTypedArray; +/* removed: var _$isPlainObject_427 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14913,7 +15073,7 @@ var __isArrayOrTypedArray_380 = _$is_array_364.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_380 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_443 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14929,7 +15089,7 @@ var _$relinkPrivateKeys_380 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_380(fromVal) && __isArrayOrTypedArray_380(toVal) && _$isPlainObject_365(fromVal[0])) { + else if(__isArrayOrTypedArray_443(fromVal) && __isArrayOrTypedArray_443(toVal) && _$isPlainObject_427(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14939,12 +15099,12 @@ var _$relinkPrivateKeys_380 = function relinkPrivateKeys(toContainer, fromContai // 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_365(fromVal[j]) && _$isPlainObject_365(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_427(fromVal[j]) && _$isPlainObject_427(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_365(fromVal) && _$isPlainObject_365(toVal)) { + else if(_$isPlainObject_427(fromVal) && _$isPlainObject_427(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14954,7 +15114,7 @@ var _$relinkPrivateKeys_380 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_381 = {}; +var _$search_444 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14966,8 +15126,8 @@ var _$search_381 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$loggers_368 = require('./loggers'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$loggers_430 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -14985,8 +15145,8 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_381.findBin = function(val, bins, linelow) { - if(_$fastIsnumeric_78(bins.start)) { +_$search_444.findBin = function(val, bins, linelow) { + if(_$fastIsnumeric_135(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError); @@ -15009,7 +15169,7 @@ _$search_381.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_368.log('Long binary search...'); + if(c > 90) _$loggers_430.log('Long binary search...'); return n1 - 1; } }; @@ -15019,17 +15179,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_381.sorterAsc = function(a, b) { return a - b; }; -_$search_381.sorterDes = function(a, b) { return b - a; }; +_$search_444.sorterAsc = function(a, b) { return a - b; }; +_$search_444.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_381.distinctVals = function(valsIn) { +_$search_444.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_381.sorterAsc); + vals.sort(_$search_444.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15054,7 +15214,7 @@ _$search_381.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_381.roundUp = function(val, arrayIn, reverse) { +_$search_444.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15071,7 +15231,7 @@ _$search_381.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_384 = {}; +var _$stats_447 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15083,8 +15243,8 @@ var _$stats_384 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_384 = _$is_array_364.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_447 = _$is_array_426.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15099,20 +15259,20 @@ var __isArrayOrTypedArray_384 = _$is_array_364.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_384.aggNums = function(f, v, a, len) { +_$stats_447.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; - if(!_$fastIsnumeric_78(v)) v = false; - if(__isArrayOrTypedArray_384(a[0])) { + if(!_$fastIsnumeric_135(v)) v = false; + if(__isArrayOrTypedArray_447(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_384.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_447.aggNums(f, v, a[i]); a = b; } for(i = 0; i < len; i++) { - if(!_$fastIsnumeric_78(v)) v = a[i]; - else if(_$fastIsnumeric_78(a[i])) v = f(+v, +a[i]); + if(!_$fastIsnumeric_135(v)) v = a[i]; + else if(_$fastIsnumeric_135(a[i])) v = f(+v, +a[i]); } return v; }; @@ -15121,26 +15281,26 @@ _$stats_384.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_384.len = function(data) { - return _$stats_384.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_447.len = function(data) { + return _$stats_447.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_384.mean = function(data, len) { - if(!len) len = _$stats_384.len(data); - return _$stats_384.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_447.mean = function(data, len) { + if(!len) len = _$stats_447.len(data); + return _$stats_447.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_384.variance = function(data, len, mean) { - if(!len) len = _$stats_384.len(data); - if(!_$fastIsnumeric_78(mean)) mean = _$stats_384.mean(data, len); +_$stats_447.variance = function(data, len, mean) { + if(!len) len = _$stats_447.len(data); + if(!_$fastIsnumeric_135(mean)) mean = _$stats_447.mean(data, len); - return _$stats_384.aggNums(function(a, b) { + return _$stats_447.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_384.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_384.variance(data, len, mean)); +_$stats_447.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_447.variance(data, len, mean)); }; /** @@ -15158,8 +15318,8 @@ _$stats_384.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_384.interp = function(arr, n) { - if(!_$fastIsnumeric_78(n)) throw 'n should be a finite number'; +_$stats_447.interp = function(arr, n) { + if(!_$fastIsnumeric_135(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; if(n > arr.length - 1) return arr[arr.length - 1]; @@ -15167,7 +15327,7 @@ _$stats_384.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_387 = {}; +var _$throttle_450 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15194,7 +15354,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_387.throttle = function throttle(id, minInterval, callback) { +_$throttle_450.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15234,7 +15394,7 @@ _$throttle_387.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_387.done = function(id) { +_$throttle_450.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15254,13 +15414,13 @@ _$throttle_387.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_387.clear = function(id) { +_$throttle_450.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_387.clear(idi); + for(var idi in timerCache) _$throttle_450.clear(idi); } }; @@ -15281,24 +15441,24 @@ function _clearTimeout(cache) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; /** * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_388 = function toLogRange(val, range) { +var _$toLogRange_451 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the // result at the lowest range value on the plot (or if the range also went negative, // one millionth of the top of the range) var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10; - if(!_$fastIsnumeric_78(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; + if(!_$fastIsnumeric_135(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; return newVal; }; -var _$lib_363 = {}; +var _$lib_425 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15310,131 +15470,131 @@ var _$lib_363 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; - -/* removed: var _$numerical_343 = require('../constants/numerical'); */; -var FP_SAFE = _$numerical_343.FP_SAFE; -var __BADNUM_363 = _$numerical_343.BADNUM; - -var lib = _$lib_363 = {}; - -lib.nestedProperty = _$nestedProperty_371; -lib.keyedContainer = _$keyedContainer_366; -lib.relativeAttr = _$relative_attr_379; -lib.isPlainObject = _$isPlainObject_365; -lib.mod = _$mod_370; -lib.toLogRange = _$toLogRange_388; -lib.relinkPrivateKeys = _$relinkPrivateKeys_380; -lib.ensureArray = _$ensureArray_352; - -/* removed: var _$is_array_364 = require('./is_array'); */; -lib.isTypedArray = _$is_array_364.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_364.isArrayOrTypedArray; - -/* removed: var _$coerce_350 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_350.valObjectMeta; -lib.coerce = _$coerce_350.coerce; -lib.coerce2 = _$coerce_350.coerce2; -lib.coerceFont = _$coerce_350.coerceFont; -lib.coerceHoverinfo = _$coerce_350.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_350.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_350.validate; - -/* removed: var _$dates_351 = require('./dates'); */; -lib.dateTime2ms = _$dates_351.dateTime2ms; -lib.isDateTime = _$dates_351.isDateTime; -lib.ms2DateTime = _$dates_351.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_351.ms2DateTimeLocal; -lib.cleanDate = _$dates_351.cleanDate; -lib.isJSDate = _$dates_351.isJSDate; -lib.formatDate = _$dates_351.formatDate; -lib.incrementMonth = _$dates_351.incrementMonth; -lib.dateTick0 = _$dates_351.dateTick0; -lib.dfltRange = _$dates_351.dfltRange; -lib.findExactDates = _$dates_351.findExactDates; -lib.MIN_MS = _$dates_351.MIN_MS; -lib.MAX_MS = _$dates_351.MAX_MS; - -/* removed: var _$search_381 = require('./search'); */; -lib.findBin = _$search_381.findBin; -lib.sorterAsc = _$search_381.sorterAsc; -lib.sorterDes = _$search_381.sorterDes; -lib.distinctVals = _$search_381.distinctVals; -lib.roundUp = _$search_381.roundUp; - -/* removed: var _$stats_384 = require('./stats'); */; -lib.aggNums = _$stats_384.aggNums; -lib.len = _$stats_384.len; -lib.mean = _$stats_384.mean; -lib.variance = _$stats_384.variance; -lib.stdev = _$stats_384.stdev; -lib.interp = _$stats_384.interp; - -/* removed: var _$matrix_369 = require('./matrix'); */; -lib.init2dArray = _$matrix_369.init2dArray; -lib.transposeRagged = _$matrix_369.transposeRagged; -lib.dot = _$matrix_369.dot; -lib.translationMatrix = _$matrix_369.translationMatrix; -lib.rotationMatrix = _$matrix_369.rotationMatrix; -lib.rotationXYMatrix = _$matrix_369.rotationXYMatrix; -lib.apply2DTransform = _$matrix_369.apply2DTransform; -lib.apply2DTransform2 = _$matrix_369.apply2DTransform2; - -/* removed: var _$angles_348 = require('./angles'); */; -lib.deg2rad = _$angles_348.deg2rad; -lib.rad2deg = _$angles_348.rad2deg; -lib.wrap360 = _$angles_348.wrap360; -lib.wrap180 = _$angles_348.wrap180; - -/* removed: var _$geometry2d_357 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_357.segmentsIntersect; -lib.segmentDistance = _$geometry2d_357.segmentDistance; -lib.getTextLocation = _$geometry2d_357.getTextLocation; -lib.clearLocationCache = _$geometry2d_357.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_357.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_357.findPointOnPath; - -/* removed: var _$extend_354 = require('./extend'); */; -lib.extendFlat = _$extend_354.extendFlat; -lib.extendDeep = _$extend_354.extendDeep; -lib.extendDeepAll = _$extend_354.extendDeepAll; -lib.extendDeepNoArrays = _$extend_354.extendDeepNoArrays; - -/* removed: var _$loggers_368 = require('./loggers'); */; -lib.log = _$loggers_368.log; -lib.warn = _$loggers_368.warn; -lib.error = _$loggers_368.error; - -/* removed: var _$regex_378 = require('./regex'); */; -lib.counterRegex = _$regex_378.counter; - -/* removed: var _$throttle_387 = require('./throttle'); */; -lib.throttle = _$throttle_387.throttle; -lib.throttleDone = _$throttle_387.done; -lib.clearThrottle = _$throttle_387.clear; - -lib.getGraphDiv = _$get_graph_div_358; - -lib._ = _$localize_367; - -lib.notifier = _$notifier_373; - -lib.filterUnique = _$filterUnique_355; -lib.filterVisible = _$filterVisible_356; -lib.pushUnique = _$pushUnique_376; - -lib.cleanNumber = _$cleanNumber_349; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; + +/* removed: var _$numerical_404 = require('../constants/numerical'); */; +var FP_SAFE = _$numerical_404.FP_SAFE; +var __BADNUM_425 = _$numerical_404.BADNUM; + +var lib = _$lib_425 = {}; + +lib.nestedProperty = _$nestedProperty_433; +lib.keyedContainer = _$keyedContainer_428; +lib.relativeAttr = _$relative_attr_442; +lib.isPlainObject = _$isPlainObject_427; +lib.mod = _$mod_432; +lib.toLogRange = _$toLogRange_451; +lib.relinkPrivateKeys = _$relinkPrivateKeys_443; +lib.ensureArray = _$ensureArray_414; + +/* removed: var _$is_array_426 = require('./is_array'); */; +lib.isTypedArray = _$is_array_426.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_426.isArrayOrTypedArray; + +/* removed: var _$coerce_412 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_412.valObjectMeta; +lib.coerce = _$coerce_412.coerce; +lib.coerce2 = _$coerce_412.coerce2; +lib.coerceFont = _$coerce_412.coerceFont; +lib.coerceHoverinfo = _$coerce_412.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_412.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_412.validate; + +/* removed: var _$dates_413 = require('./dates'); */; +lib.dateTime2ms = _$dates_413.dateTime2ms; +lib.isDateTime = _$dates_413.isDateTime; +lib.ms2DateTime = _$dates_413.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_413.ms2DateTimeLocal; +lib.cleanDate = _$dates_413.cleanDate; +lib.isJSDate = _$dates_413.isJSDate; +lib.formatDate = _$dates_413.formatDate; +lib.incrementMonth = _$dates_413.incrementMonth; +lib.dateTick0 = _$dates_413.dateTick0; +lib.dfltRange = _$dates_413.dfltRange; +lib.findExactDates = _$dates_413.findExactDates; +lib.MIN_MS = _$dates_413.MIN_MS; +lib.MAX_MS = _$dates_413.MAX_MS; + +/* removed: var _$search_444 = require('./search'); */; +lib.findBin = _$search_444.findBin; +lib.sorterAsc = _$search_444.sorterAsc; +lib.sorterDes = _$search_444.sorterDes; +lib.distinctVals = _$search_444.distinctVals; +lib.roundUp = _$search_444.roundUp; + +/* removed: var _$stats_447 = require('./stats'); */; +lib.aggNums = _$stats_447.aggNums; +lib.len = _$stats_447.len; +lib.mean = _$stats_447.mean; +lib.variance = _$stats_447.variance; +lib.stdev = _$stats_447.stdev; +lib.interp = _$stats_447.interp; + +/* removed: var _$matrix_431 = require('./matrix'); */; +lib.init2dArray = _$matrix_431.init2dArray; +lib.transposeRagged = _$matrix_431.transposeRagged; +lib.dot = _$matrix_431.dot; +lib.translationMatrix = _$matrix_431.translationMatrix; +lib.rotationMatrix = _$matrix_431.rotationMatrix; +lib.rotationXYMatrix = _$matrix_431.rotationXYMatrix; +lib.apply2DTransform = _$matrix_431.apply2DTransform; +lib.apply2DTransform2 = _$matrix_431.apply2DTransform2; + +/* removed: var _$angles_409 = require('./angles'); */; +lib.deg2rad = _$angles_409.deg2rad; +lib.rad2deg = _$angles_409.rad2deg; +lib.wrap360 = _$angles_409.wrap360; +lib.wrap180 = _$angles_409.wrap180; + +/* removed: var _$geometry2d_419 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_419.segmentsIntersect; +lib.segmentDistance = _$geometry2d_419.segmentDistance; +lib.getTextLocation = _$geometry2d_419.getTextLocation; +lib.clearLocationCache = _$geometry2d_419.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_419.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_419.findPointOnPath; + +/* removed: var _$extend_416 = require('./extend'); */; +lib.extendFlat = _$extend_416.extendFlat; +lib.extendDeep = _$extend_416.extendDeep; +lib.extendDeepAll = _$extend_416.extendDeepAll; +lib.extendDeepNoArrays = _$extend_416.extendDeepNoArrays; + +/* removed: var _$loggers_430 = require('./loggers'); */; +lib.log = _$loggers_430.log; +lib.warn = _$loggers_430.warn; +lib.error = _$loggers_430.error; + +/* removed: var _$regex_441 = require('./regex'); */; +lib.counterRegex = _$regex_441.counter; + +/* removed: var _$throttle_450 = require('./throttle'); */; +lib.throttle = _$throttle_450.throttle; +lib.throttleDone = _$throttle_450.done; +lib.clearThrottle = _$throttle_450.clear; + +lib.getGraphDiv = _$get_graph_div_420; + +lib._ = _$localize_429; + +lib.notifier = _$notifier_435; + +lib.filterUnique = _$filterUnique_417; +lib.filterVisible = _$filterVisible_418; +lib.pushUnique = _$pushUnique_439; + +lib.cleanNumber = _$cleanNumber_410; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_78(v)) return __BADNUM_363; + if(!_$fastIsnumeric_135(v)) return __BADNUM_425; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_363; - return _$fastIsnumeric_78(v) ? Number(v) : __BADNUM_363; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_425; + return _$fastIsnumeric_135(v) ? Number(v) : __BADNUM_425; }; -lib.noop = _$noop_372; -lib.identity = _$identity_362; +lib.noop = _$noop_434; +lib.identity = _$identity_424; /** * swap x and y of the same attribute in container cont @@ -15794,7 +15954,7 @@ lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) { } function isPtIndexValid(v) { - return _$fastIsnumeric_78(v) && v >= 0 && v % 1 === 0; + return _$fastIsnumeric_135(v) && v >= 0 && v % 1 === 0; } function isCdIndexValid(v) { @@ -15886,7 +16046,7 @@ lib.containsAny = function(s, fragments) { }; lib.isPlotDiv = function(el) { - var el3 = _$d3_68.select(el); + var el3 = _$d3_71.select(el); return el3.node() instanceof HTMLElement && el3.size() && el3.classed('js-plotly-plot'); @@ -15933,6 +16093,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16126,7 +16343,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_363 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_425 = /^\w*$/; /* * Substitute values from an object into a string @@ -16147,7 +16364,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_363.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_425.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16207,9 +16424,9 @@ lib.pseudoRandom = function() { 'use strict'; -/* removed: var _$lib_363 = require('../lib'); */; -var __extendFlat_392 = _$lib_363.extendFlat; -var __isPlainObject_392 = _$lib_363.isPlainObject; +/* removed: var _$lib_425 = require('../lib'); */; +var __extendFlat_455 = _$lib_425.extendFlat; +var __isPlainObject_455 = _$lib_425.isPlainObject; var traceOpts = { valType: 'flaglist', @@ -16222,7 +16439,7 @@ var layoutOpts = { valType: 'flaglist', extras: ['none'], flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', 'layoutstyle', 'modebar', 'camera', 'arraydraw' ], @@ -16237,7 +16454,7 @@ var traceEditTypeFlags = traceOpts.flags.slice() var layoutEditTypeFlags = layoutOpts.flags.slice() .concat('layoutReplot'); -var _$edit_types_392 = { +var _$edit_types_455 = { traces: traceOpts, layout: layoutOpts, /* @@ -16290,10 +16507,10 @@ function falseObj(keys) { * @return {object} a new attributes object with `editType` modified as directed */ function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_392({}, attrs); + var out = __extendFlat_455({}, attrs); for(var key in out) { var attr = out[key]; - if(__isPlainObject_392(attr)) { + if(__isPlainObject_455(attr)) { out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } @@ -16304,7 +16521,7 @@ function overrideAll(attrs, editTypeOverride, overrideContainers) { function overrideOne(attr, editTypeOverride, overrideContainers, key) { if(attr.valType) { - var out = __extendFlat_392({}, attr); + var out = __extendFlat_455({}, attr); out.editType = editTypeOverride; if(Array.isArray(attr.items)) { @@ -16332,7 +16549,7 @@ function overrideOne(attr, editTypeOverride, overrideContainers, key) { 'use strict'; -var _$constants_276 = { +var _$constants_338 = { // hover labels for multiple horizontal bars get tilted by this angle YANGLE: 60, @@ -16363,16 +16580,16 @@ var _$constants_276 = { 'use strict'; -/* removed: var _$constants_276 = require('./constants'); */; +/* removed: var _$constants_338 = require('./constants'); */; -var __fontAttrs_282 = _$font_attributes_434({ +var __fontAttrs_344 = _$font_attributes_496({ editType: 'none', }); -__fontAttrs_282.family.dflt = _$constants_276.HOVERFONT; -__fontAttrs_282.size.dflt = _$constants_276.HOVERFONTSIZE; +__fontAttrs_344.family.dflt = _$constants_338.HOVERFONT; +__fontAttrs_344.size.dflt = _$constants_338.HOVERFONTSIZE; -var _$layout_attributes_282 = { +var _$layout_attributes_344 = { dragmode: { valType: 'enumerated', @@ -16417,7 +16634,7 @@ var _$layout_attributes_282 = { editType: 'none', }, - font: __fontAttrs_282, + font: __fontAttrs_344, namelength: { valType: 'integer', min: -1, @@ -16426,11 +16643,19 @@ var _$layout_attributes_282 = { editType: 'none', }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + editType: 'none' } }; -var _$xmlns_namespaces_345 = {}; +var _$xmlns_namespaces_406 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16443,15 +16668,15 @@ var _$xmlns_namespaces_345 = {}; 'use strict'; -_$xmlns_namespaces_345.xmlns = 'http://www.w3.org/2000/xmlns/'; -_$xmlns_namespaces_345.svg = 'http://www.w3.org/2000/svg'; -_$xmlns_namespaces_345.xlink = 'http://www.w3.org/1999/xlink'; +_$xmlns_namespaces_406.xmlns = 'http://www.w3.org/2000/xmlns/'; +_$xmlns_namespaces_406.svg = 'http://www.w3.org/2000/svg'; +_$xmlns_namespaces_406.xlink = 'http://www.w3.org/1999/xlink'; // the 'old' d3 quirk got fix in v3.5.7 // https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed -_$xmlns_namespaces_345.svgAttrs = { - xmlns: _$xmlns_namespaces_345.svg, - 'xmlns:xlink': _$xmlns_namespaces_345.xlink +_$xmlns_namespaces_406.svgAttrs = { + xmlns: _$xmlns_namespaces_406.svg, + 'xmlns:xlink': _$xmlns_namespaces_406.xlink }; /** @@ -16465,7 +16690,7 @@ _$xmlns_namespaces_345.svgAttrs = { 'use strict'; -var _$attributes_405 = { +var _$attributes_468 = { xaxis: { valType: 'subplotid', @@ -16491,21 +16716,21 @@ var _$attributes_405 = { */ 'use strict'; -var __counterRegex_412 = _$regex_378.counter; +var __counterRegex_475 = _$regex_441.counter; -var _$constants_412 = { +var _$constants_475 = { idRegex: { - x: __counterRegex_412('x'), - y: __counterRegex_412('y') + x: __counterRegex_475('x'), + y: __counterRegex_475('y') }, - attrRegex: __counterRegex_412('[xy]axis'), + attrRegex: __counterRegex_475('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_412('xaxis'), - yAxisMatch: __counterRegex_412('yaxis'), + xAxisMatch: __counterRegex_475('xaxis'), + yAxisMatch: __counterRegex_475('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -16552,6 +16777,7 @@ var _$constants_412 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -16561,7 +16787,7 @@ var _$constants_412 = { } }; -var _$axis_ids_410 = {}; +var _$axis_ids_473 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16572,30 +16798,30 @@ var _$axis_ids_410 = {}; 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; +/* removed: var _$registry_514 = require('../../registry'); */; -/* removed: var _$constants_412 = require('./constants'); */; +/* removed: var _$constants_475 = require('./constants'); */; // 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. -_$axis_ids_410.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_412.AX_ID_PATTERN)) return; +_$axis_ids_473.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_475.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_410.name2id = function name2id(name) { - if(!name.match(_$constants_412.AX_NAME_PATTERN)) return; +_$axis_ids_473.name2id = function name2id(name) { + if(!name.match(_$constants_475.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_410.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_412.AX_ID_PATTERN)) return; +_$axis_ids_473.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_475.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -16604,11 +16830,11 @@ _$axis_ids_410.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_410.list = function(gd, axLetter, only2d) { +_$axis_ids_473.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_410.listIds(gd, axLetter); + var idList = _$axis_ids_473.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -16633,7 +16859,7 @@ _$axis_ids_410.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_410.listIds = function(gd, axLetter) { +_$axis_ids_473.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -16644,42 +16870,110 @@ _$axis_ids_410.listIds = function(gd, axLetter) { // 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 -_$axis_ids_410.getFromId = function(gd, id, type) { +_$axis_ids_473.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[_$axis_ids_410.id2name(id)]; + return fullLayout[_$axis_ids_473.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_410.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_473.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_451.traceIs(fullTrace, 'gl3d')) { + if(_$registry_514.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_410.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_473.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_410.idSort = function(id1, id2) { +_$axis_ids_473.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); }; -var _$attributes_263 = {}; +var _$client_188 = true; +var _$hasHover_182 = {}; +(function (global){ +'use strict' + +/* removed: var _$client_188 = require('is-browser') */; +var hasHover + +if (typeof global.matchMedia === 'function') { + hasHover = !global.matchMedia('(hover: none)').matches +} +else { + hasHover = _$client_188 +} + +_$hasHover_182 = hasHover + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + +/* removed: var _$client_188 = require('is-browser') */; + +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 +} + +var _$hasPassiveEvents_183 = _$client_188 && detect() + +var rootPosition = { left: 0, top: 0 } + +var _$mouseEventOffset_196 = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16691,17 +16985,25 @@ var _$attributes_263 = {}; 'use strict'; -_$attributes_263.dash = { - valType: 'string', - // string type usually doesn't take values... this one should really be - // a special type or at least a special coercion function, from the GUI - // you only get these values but elsewhere the user can supply a list of - // dash lengths in px, and it will be honored - values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], - dflt: 'solid', - - editType: 'style', - + +// 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 +var _$align_321 = function align(v, dv, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0), + vmax = vmin + dv / (v1 - v0), + 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; }; /** @@ -16712,779 +17014,338 @@ _$attributes_263.dash = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$font_attributes_434 = require('../font_attributes'); */; -/* removed: var _$attributes_238 = require('../../components/color/attributes'); */; -var dash = _$attributes_263.dash; -var __extendFlat_419 = _$extend_354.extendFlat; +/* removed: var _$lib_425 = require('../../lib'); */; -/* removed: var _$constants_412 = require('./constants'); */; +// 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'] +]; -var _$layout_attributes_419 = { - visible: { - valType: 'boolean', - - editType: 'plot', - - }, - color: { - valType: 'color', - dflt: _$attributes_238.defaultLine, - - editType: 'ticks', - - }, - title: { - valType: 'string', - - editType: 'ticks+margins', - - }, - titlefont: _$font_attributes_434({ - editType: 'ticks+margins', - - }), - type: { - valType: 'enumerated', - // '-' means we haven't yet run autotype or couldn't find any data - // it gets turned into linear in gd._fullLayout but not copied back - // to gd.data like the others are. - values: ['-', 'linear', 'log', 'date', 'category'], - dflt: '-', - - editType: 'calc', - - }, - autorange: { - valType: 'enumerated', - values: [true, false, 'reversed'], - dflt: true, - - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, - - }, - rangemode: { - valType: 'enumerated', - values: ['normal', 'tozero', 'nonnegative'], - dflt: 'normal', - - editType: 'plot', - - }, - range: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} - ], - editType: 'plot+margins', - impliedEdits: {'autorange': false}, - - }, - fixedrange: { - valType: 'boolean', - dflt: false, - - editType: 'calc', - - }, - // scaleanchor: not used directly, just put here for reference - // values are any opposite-letter axis id - scaleanchor: { - valType: 'enumerated', - values: [ - _$constants_412.idRegex.x.toString(), - _$constants_412.idRegex.y.toString() - ], - - editType: 'plot', - - }, - scaleratio: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'plot', - - }, - constrain: { - valType: 'enumerated', - values: ['range', 'domain'], - dflt: 'range', - - editType: 'plot', - - }, - // constraintoward: not used directly, just put here for reference - constraintoward: { - valType: 'enumerated', - values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], - - editType: 'plot', - - }, - // ticks - tickmode: { - valType: 'enumerated', - values: ['auto', 'linear', 'array'], - - editType: 'ticks+margins', - impliedEdits: {tick0: undefined, dtick: undefined}, - - }, - nticks: { - valType: 'integer', - min: 0, - dflt: 0, - - editType: 'ticks+margins', - - }, - tick0: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - dtick: { - valType: 'any', - - editType: 'ticks+margins', - impliedEdits: {tickmode: 'linear'}, - - }, - tickvals: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticktext: { - valType: 'data_array', - editType: 'ticks+margins', - - }, - ticks: { - valType: 'enumerated', - values: ['outside', 'inside', ''], - - editType: 'ticks+margins', - - }, - mirror: { - valType: 'enumerated', - values: [true, 'ticks', false, 'all', 'allticks'], - dflt: false, - - editType: 'ticks+layoutstyle', - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: 5, - - editType: 'ticks', - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - tickcolor: { - valType: 'color', - dflt: _$attributes_238.defaultLine, - - editType: 'ticks', - - }, - showticklabels: { - valType: 'boolean', - dflt: true, - - editType: 'ticks+margins', - - }, - automargin: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - showspikes: { - valType: 'boolean', - dflt: false, - - editType: 'modebar', - - }, - spikecolor: { - valType: 'color', - dflt: null, - - editType: 'none', - - }, - spikethickness: { - valType: 'number', - dflt: 3, - - editType: 'none', - - }, - spikedash: __extendFlat_419({}, dash, {dflt: 'dash', editType: 'none'}), - spikemode: { - valType: 'flaglist', - flags: ['toaxis', 'across', 'marker'], - - dflt: 'toaxis', - editType: 'none', - - }, - spikesnap: { - valType: 'enumerated', - values: ['data', 'cursor'], - dflt: 'data', - - editType: 'none', - - }, - tickfont: _$font_attributes_434({ - editType: 'ticks+margins', - - }), - tickangle: { - valType: 'angle', - dflt: 'auto', - - editType: 'ticks+margins', - - }, - tickprefix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showtickprefix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - ticksuffix: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - showticksuffix: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - showexponent: { - valType: 'enumerated', - values: ['all', 'first', 'last', 'none'], - dflt: 'all', - - editType: 'ticks+margins', - - }, - exponentformat: { - valType: 'enumerated', - values: ['none', 'e', 'E', 'power', 'SI', 'B'], - dflt: 'B', - - editType: 'ticks+margins', - - }, - separatethousands: { - valType: 'boolean', - dflt: false, - - editType: 'ticks+margins', - - }, - tickformat: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - tickformatstops: { - _isLinkedToArray: 'tickformatstop', +var _$getCursor_322 = 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_425.constrain(Math.floor(x * 3), 0, 2); - dtickrange: { - valType: 'info_array', - - items: [ - {valType: 'any', editType: 'ticks+margins'}, - {valType: 'any', editType: 'ticks+margins'} - ], - editType: 'ticks+margins', - - }, - value: { - valType: 'string', - dflt: '', - - editType: 'ticks+margins', - - }, - editType: 'ticks+margins' - }, - hoverformat: { - valType: 'string', - dflt: '', - - editType: 'none', - - }, - // lines and grids - showline: { - valType: 'boolean', - dflt: false, - - editType: 'layoutstyle', - - }, - linecolor: { - valType: 'color', - dflt: _$attributes_238.defaultLine, - - editType: 'layoutstyle', - - }, - linewidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks+layoutstyle', - - }, - showgrid: { - valType: 'boolean', - - editType: 'ticks', - - }, - gridcolor: { - valType: 'color', - dflt: _$attributes_238.lightLine, - - editType: 'ticks', - - }, - gridwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'ticks', - - }, - zeroline: { - valType: 'boolean', - - editType: 'ticks', - - }, - zerolinecolor: { - valType: 'color', - dflt: _$attributes_238.defaultLine, - - editType: 'ticks', - - }, - zerolinewidth: { - valType: 'number', - dflt: 1, - - editType: 'ticks', - - }, - // positioning attributes - // anchor: not used directly, just put here for reference - // values are any opposite-letter axis id - anchor: { - valType: 'enumerated', - values: [ - 'free', - _$constants_412.idRegex.x.toString(), - _$constants_412.idRegex.y.toString() - ], - - editType: 'plot+margins', - - }, - // side: not used directly, as values depend on direction - // values are top, bottom for x axes, and left, right for y - side: { - valType: 'enumerated', - values: ['top', 'bottom', 'left', 'right'], - - editType: 'plot+margins', - - }, - // overlaying: not used directly, just put here for reference - // values are false and any other same-letter axis id that's not - // itself overlaying anything - overlaying: { - valType: 'enumerated', - values: [ - 'free', - _$constants_412.idRegex.x.toString(), - _$constants_412.idRegex.y.toString() - ], - - editType: 'plot', - - }, - layer: { - valType: 'enumerated', - values: ['above traces', 'below traces'], - dflt: 'above traces', - - editType: 'plot', - - }, - domain: { - valType: 'info_array', - - items: [ - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, - {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} - ], - dflt: [0, 1], - editType: 'plot+margins', - - }, - position: { - valType: 'number', - min: 0, - max: 1, - dflt: 0, - - editType: 'plot+margins', - - }, - categoryorder: { - valType: 'enumerated', - values: [ - 'trace', 'category ascending', 'category descending', 'array' - /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later - ], - dflt: 'trace', - - editType: 'calc', - - }, - categoryarray: { - valType: 'data_array', - - editType: 'calc', - - }, - editType: 'calc', + if(yanchor === 'bottom') y = 0; + else if(yanchor === 'middle') y = 1; + else if(yanchor === 'top') y = 2; + else y = _$lib_425.constrain(Math.floor(y * 3), 0, 2); - _deprecated: { - autotick: { - valType: 'boolean', - - editType: 'ticks+margins', - - } - } + return cursorset[y][x]; }; -var _$color_239 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - +// 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. -'use strict'; +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +var _$EventEmitter_134 = EventEmitter; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; -var color = _$color_239 = {}; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; -/* removed: var _$attributes_238 = require('./attributes'); */; -color.defaults = _$attributes_238.defaults; -var defaultLine = color.defaultLine = _$attributes_238.defaultLine; -color.lightLine = _$attributes_238.lightLine; -var background = color.background = _$attributes_238.background; +// 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. +EventEmitter.defaultMaxListeners = 10; -/* - * tinyRGB: turn a tinycolor into an rgb string, but - * unlike the built-in tinycolor.toRgbString this never includes alpha - */ -color.tinyRGB = function(tc) { - var c = tc.toRgb(); - return 'rgb(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ')'; +// 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(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; }; -color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_201(cstr)); }; - -color.opacity = function(cstr) { return cstr ? _$tinycolor_201(cstr).getAlpha() : 0; }; - -color.addOpacity = function(cstr, op) { - var c = _$tinycolor_201(cstr).toRgb(); - return 'rgba(' + Math.round(c.r) + ', ' + - Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; -}; +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; -// combine two colors into one apparent color -// if back has transparency or is missing, -// color.background is assumed behind it -color.combine = function(front, back) { - var fc = _$tinycolor_201(front).toRgb(); - if(fc.a === 1) return _$tinycolor_201(front).toRgbString(); + if (!this._events) + this._events = {}; - var bc = _$tinycolor_201(back || background).toRgb(), - bcflat = bc.a === 1 ? bc : { - r: 255 * (1 - bc.a) + bc.r * bc.a, - g: 255 * (1 - bc.a) + bc.g * bc.a, - b: 255 * (1 - bc.a) + bc.b * bc.a - }, - fcflat = { - r: bcflat.r * (1 - fc.a) + fc.r * fc.a, - g: bcflat.g * (1 - fc.a) + fc.g * fc.a, - b: bcflat.b * (1 - fc.a) + fc.b * fc.a - }; - return _$tinycolor_201(fcflat).toRgbString(); -}; + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } -/* - * Create a color that contrasts with cstr. - * - * If cstr is a dark color, we lighten it; if it's light, we darken. - * - * If lightAmount / darkAmount are used, we adjust by these percentages, - * otherwise we go all the way to white or black. - */ -color.contrast = function(cstr, lightAmount, darkAmount) { - var tc = _$tinycolor_201(cstr); + handler = this._events[type]; - if(tc.getAlpha() !== 1) tc = _$tinycolor_201(color.combine(cstr, background)); + if (isUndefined(handler)) + return false; - var newColor = tc.isDark() ? - (lightAmount ? tc.lighten(lightAmount) : background) : - (darkAmount ? tc.darken(darkAmount) : defaultLine); + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - return newColor.toString(); + return true; }; -color.stroke = function(s, c) { - var tc = _$tinycolor_201(c); - s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); -}; +EventEmitter.prototype.addListener = function(type, listener) { + var m; -color.fill = function(s, c) { - var tc = _$tinycolor_201(c); - s.style({ - 'fill': color.tinyRGB(tc), - 'fill-opacity': tc.getAlpha() - }); -}; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -// search container for colors with the deprecated rgb(fractions) format -// and convert them to rgb(0-255 values) -color.clean = function(container) { - if(!container || typeof container !== 'object') return; + if (!this._events) + this._events = {}; - var keys = Object.keys(container), - i, - j, - key, - val; + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); - for(i = 0; i < keys.length; i++) { - key = keys[i]; - val = container[key]; + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; - // only sanitize keys that end in "color" or "colorscale" - if(key.substr(key.length - 5) === 'color') { - if(Array.isArray(val)) { - for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); - } - else container[key] = cleanOne(val); - } - else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { - // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] - for(j = 0; j < val.length; j++) { - if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); - } - } - // recurse into arrays of objects, and plain objects - else if(Array.isArray(val)) { - var el0 = val[0]; - if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { - for(j = 0; j < val.length; j++) color.clean(val[j]); - } - } - else if(val && typeof val === 'object') color.clean(val); + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; } -}; - -function cleanOne(val) { - if(_$fastIsnumeric_78(val) || typeof val !== 'string') return val; - var valTrim = val.trim(); - if(valTrim.substr(0, 3) !== 'rgb') return val; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } - var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); - if(!match) return val; + return this; +}; - var parts = match[1].trim().split(/\s*[\s,]\s*/), - rgba = valTrim.charAt(3) === 'a' && parts.length === 4; - if(!rgba && parts.length !== 3) return val; +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - for(var i = 0; i < parts.length; i++) { - if(!parts[i].length) return val; - parts[i] = Number(parts[i]); +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - // all parts must be non-negative numbers - if(!(parts[i] >= 0)) return val; - // alpha>1 gets clipped to 1 - if(i === 3) { - if(parts[i] > 1) parts[i] = 1; - } - // r, g, b must be < 1 (ie 1 itself is not allowed) - else if(parts[i] >= 1) return val; - } + var fired = false; - var rgbStr = Math.round(parts[0] * 255) + ', ' + - Math.round(parts[1] * 255) + ', ' + - Math.round(parts[2] * 255); + function g() { + this.removeListener(type, g); - if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; - return 'rgb(' + rgbStr + ')'; -} + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + g.listener = listener; + this.on(type, g); -'use strict'; + return this; +}; +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; -var _$handleCategoryOrderDefaults_411 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var arrayIn = containerIn.categoryarray, - orderDefault; + if (!this._events || !this._events[type]) + return this; - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); + list = this._events[type]; + length = list.length; + position = -1; - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); - var order = coerce('categoryorder', orderDefault); + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + if (position < 0) + return this; - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } -'use strict'; + return this; +}; -var colorMix = _$tinycolor_201.mix; -var lightFraction = _$attributes_238.lightFraction; -/* removed: var _$lib_363 = require('../../lib'); */; +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; -/** - * @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 - */ -var _$handleLineGridDefaults_421 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; + if (!this._events) + return this; - var dfltColor = opts.dfltColor; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - function coerce2(attr, dflt) { - return _$lib_363.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - 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; - } + listeners = this._events[type]; - 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 (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - if(!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } + return this; +}; - if(!opts.noZeroLine) { - var zeroLineColor = coerce2('zerolinecolor', dfltColor); - var zeroLineWidth = coerce2('zerolinewidth'); - var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); }; +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17496,73 +17357,161 @@ var _$handleLineGridDefaults_421 = function handleLineGridDefaults(containerIn, 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* global jQuery:false */ + +var __EventEmitter_415 = _$EventEmitter_134.EventEmitter; + +var Events = { -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { + init: function(plotObj) { + + /* + * If we have already instantiated an emitter for this plot + * return early. + */ + if(plotObj._ev instanceof __EventEmitter_415) return plotObj; - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. + var ev = new __EventEmitter_415(); + var internalEv = new __EventEmitter_415(); - var categoryArray = []; + /* + * Assign to plot._ev while we still live in a land + * where plot is a DOM element with stuff attached to it. + * In the future we can make plot the event emitter itself. + */ + plotObj._ev = ev; - var traceLines = data.map(function(d) {return d[axisLetter];}); + /* + * Create a second event handler that will manage events *internally*. + * This allows parts of plotly to respond to thing like relayout without + * having to use the user-facing event handler. They cannot peacefully + * coexist on the same handler because a user invoking + * plotObj.removeAllListeners() would detach internal events, breaking + * plotly. + */ + plotObj._internalEv = internalEv; - var i, j, tracePoints, category, insertionIndex; + /* + * Assign bound methods from the ev to the plot object. These methods + * will reference the 'this' of plot._ev even though they are methods + * of plot. This will keep the event machinery away from the plot object + * which currently is often a DOM element but presents an API that will + * continue to function when plot becomes an emitter. Not all EventEmitter + * methods have been bound to `plot` as some do not currently add value to + * the Plotly event API. + */ + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - var bisector = _$d3_68.bisector(sortFunction).left; + /* + * Create funtions for managing internal events. These are *only* triggered + * by the mirroring of external events via the emit function. + */ + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); - for(i = 0; i < traceLines.length; i++) { + /* + * We must wrap emit to continue to support JQuery events. The idea + * is to check to see if the user is using JQuery events, if they are + * we emit JQuery events to trigger user handlers as well as the EventEmitter + * events. + */ + plotObj.emit = function(event, data) { + if(typeof jQuery !== 'undefined') { + jQuery(plotObj).trigger(event, data); + } - tracePoints = traceLines[i]; + ev.emit(event, data); + internalEv.emit(event, data); + }; - for(j = 0; j < tracePoints.length; j++) { + return plotObj; + }, - category = tracePoints[j]; + /* + * This function behaves like jQueries triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. + * + * Note: triggerHandler has been recommended for deprecation in v2.0.0, + * so the additional behavior of triggerHandler triggering internal events + * is deliberate excluded in order to avoid reinforcing more usage. + */ + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + /* + * If Jquery exists run all its handlers for this event and + * collect the return value of the LAST handler function + */ + if(typeof jQuery !== 'undefined') { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; + /* + * Now run all the node style event handlers + */ + var ev = plotObj._ev; + if(!ev) return jQueryHandlerValue; - insertionIndex = bisector(categoryArray, category); + var handlers = ev._events[event]; + if(!handlers) return jQueryHandlerValue; - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; + /* + * handlers can be function or an array of functions + */ + if(typeof handlers === 'function') handlers = [handlers]; + var lastHandler = handlers.pop(); - // insert value - categoryArray.splice(insertionIndex, 0, category); + /* + * Call all the handlers except the last one. + */ + for(var i = 0; i < handlers.length; i++) { + handlers[i](data); } - } - return categoryArray; -} + /* + * Now call the final handler and collect its value + */ + nodeEventHandlerValue = lastHandler(data); + /* + * Return either the jquery handler value if it exists or the + * nodeEventHandler value. Jquery event value superceeds nodejs + * events for backwards compatability reasons. + */ + return jQueryHandlerValue !== undefined ? jQueryHandlerValue : + nodeEventHandlerValue; + }, -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_422 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_68.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_68.descending, data); - case 'trace': return []; - default: return []; + return plotObj; } + }; +var _$Events_415 = Events; + +var _$unhover_324 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17574,493 +17523,399 @@ var _$orderedCategories_422 = function orderedCategories(axisLetter, categoryord 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -var cleanNumber = _$lib_363.cleanNumber; -var ms2DateTime = _$lib_363.ms2DateTime; -var dateTime2ms = _$lib_363.dateTime2ms; -var ensureNumber = _$lib_363.ensureNumber; +/* removed: var _$Events_415 = require('../../lib/events'); */; +/* removed: var _$throttle_450 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_420 = require('../../lib/get_graph_div'); */; -/* removed: var _$numerical_343 = require('../../constants/numerical'); */; -var __FP_SAFE_426 = _$numerical_343.FP_SAFE; -var __BADNUM_426 = _$numerical_343.BADNUM; +/* removed: var _$constants_338 = require('../fx/constants'); */; -/* removed: var _$constants_412 = require('./constants'); */; -/* removed: var _$axis_ids_410 = require('./axis_ids'); */; +var unhover = _$unhover_324 = {}; -function fromLog(v) { - return Math.pow(10, v); -} -/** - * 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 autorange bounds ._min and ._max - * and the autotick constraints ._minDtick, ._forceTick0 - */ -var _$setConvert_426 = function setConvert(ax, fullLayout) { - fullLayout = fullLayout || {}; +unhover.wrapped = function(gd, evt, subplot) { + gd = _$get_graph_div_420(gd); - var axLetter = (ax._id || 'x').charAt(0); + // Important, clear any queued hovers + if(gd._fullLayout) { + _$throttle_450.clear(gd._fullLayout._uid + _$constants_338.HOVERID); + } - // clipMult: how many axis lengths past the edge do we render? - // for panning, 1-2 would suffice, but for zooming more is nice. - // also, clipping can affect the direction of lines off the edge... - var clipMult = 10; + unhover.raw(gd, evt, subplot); +}; - 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 clipMult axis - // length past the negative edge - var r0 = ax.range[0], - r1 = ax.range[1]; - return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); - } +// remove hover effects on mouse out, and emit unhover event +unhover.raw = function unhoverRaw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; - else return __BADNUM_426; + if(!evt) evt = {}; + if(evt.target && + _$Events_415.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; } - /* - * 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_426) { - if(_$fastIsnumeric_78(v)) ms = dateTime2ms(new Date(+v)); - else return __BADNUM_426; - } - return ms; - } + fullLayout._hoverlayer.selectAll('g').remove(); + fullLayout._hoverlayer.selectAll('line').remove(); + fullLayout._hoverlayer.selectAll('circle').remove(); + gd._hoverdata = undefined; - // wrapped ms2DateTime to insert default ax.calendar - function ms2dt(v, r, calendar) { - return ms2DateTime(v, r, calendar || ax.calendar); + if(evt.target && oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); } +}; - function getCategoryName(v) { - return ax._categories[Math.round(v)]; - } +var _$dragelement_323 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* - * 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(v !== null && v !== undefined) { - if(ax._categoriesMap === undefined) { - ax._categoriesMap = {}; - } - if(ax._categoriesMap[v] !== undefined) { - return ax._categoriesMap[v]; - } else { - ax._categories.push(v); +'use strict'; - var curLength = ax._categories.length - 1; - ax._categoriesMap[v] = curLength; +/* removed: var _$mouseEventOffset_196 = require('mouse-event-offset'); */; +/* removed: var _$hasHover_182 = require('has-hover'); */; +/* removed: var _$hasPassiveEvents_183 = require('has-passive-events'); */; - return curLength; - } - } - return __BADNUM_426; - } +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; - function getCategoryIndex(v) { - // d2l/d2c variant that that won't add categories but will also - // allow numbers to be mapped to the linearized axis positions - if(ax._categoriesMap) { - var index = ax._categoriesMap[v]; - if(index !== undefined) return index; - } +/* removed: var _$constants_475 = require('../../plots/cartesian/constants'); */; +/* removed: var _$interactions_403 = require('../../constants/interactions'); */; - if(_$fastIsnumeric_78(v)) return +v; - } +var dragElement = _$dragelement_323 = {}; - function l2p(v) { - if(!_$fastIsnumeric_78(v)) return __BADNUM_426; +dragElement.align = _$align_321; +dragElement.getCursor = _$getCursor_322; - // include 2 fractional digits on pixel, for PDF zooming etc - return _$d3_68.round(ax._b + ax._m * v, 2); - } +/* removed: var _$unhover_324 = require('./unhover'); */; +dragElement.unhover = _$unhover_324.wrapped; +dragElement.unhoverRaw = _$unhover_324.raw; - 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; +/** + * 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 DBLCLICKDELAY = _$interactions_403.DBLCLICKDELAY; + var element = options.element; - ax.l2p = l2p; - ax.p2l = p2l; + var startX, + startY, + newMouseDownTime, + cursor, + dragCover, + initialEvent, + initialTarget, + rightClick; - 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; + if(!gd._mouseDownTime) gd._mouseDownTime = 0; - /* - * 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; + element.style.pointerEvents = 'all'; - ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; - ax.p2d = ax.p2r = p2l; + element.onmousedown = onStart; - ax.cleanPos = ensureNumber; + if(!_$hasPassiveEvents_183) { + element.ontouchstart = onStart; + } + else { + if(element._ontouchstart) { + element.removeEventListener('touchstart', element._ontouchstart); + } + element._ontouchstart = onStart; + element.addEventListener('touchstart', onStart, {passive: false}); } - 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; + function _clampFn(dx, dy, minDrag) { + if(Math.abs(dx) < minDrag) dx = 0; + if(Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } - ax.c2r = toLog; - ax.l2d = fromLog; + var clampFn = options.clampFn || _clampFn; - ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); }; - ax.p2d = function(px) { return fromLog(p2l(px)); }; + function onStart(e) { + e.preventDefault(); - ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; - ax.p2r = p2l; + // 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; - ax.cleanPos = ensureNumber; - } - else if(ax.type === 'date') { - // r and d are date strings, l and c are ms + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { + // in a click train + numClicks += 1; + } + else { + // new click train + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; + } - /* - * 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_363.identity; + if(options.prepFn) options.prepFn(e, startX, startY); - ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; - ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; + if(_$hasHover_182 && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } + else if(!_$hasHover_182) { + // 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; + } - 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); }; + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onDone); + document.addEventListener('touchmove', onMove); + document.addEventListener('touchend', onDone); - ax.cleanPos = function(v) { return _$lib_363.cleanDate(v, __BADNUM_426, ax.calendar); }; + return; } - 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 = getCategoryIndex; + function onMove(e) { + e.preventDefault(); - ax.r2c = function(v) { - var index = getCategoryIndex(v); - return index !== undefined ? index : ax.fraction2r(0.5); - }; + var offset = pointerOffset(e); + var minDrag = options.minDrag || _$constants_475.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; - ax.l2r = ax.c2r = ensureNumber; - ax.r2l = getCategoryIndex; + if(dx || dy) { + gd._dragged = true; + dragElement.unhover(gd); + } - 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; + if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); - ax.cleanPos = function(v) { - if(typeof v === 'string' && v !== '') return v; - return ensureNumber(v); - }; + return; } - // find the range value at the specified (linear) fraction of the axis - ax.fraction2r = function(v) { - var rl0 = ax.r2l(ax.range[0]), - 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]), - 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_363.nestedProperty(ax, rangeAttr).get(); - var i, dflt; + function onDone(e) { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onDone); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onDone); - if(ax.type === 'date') dflt = _$lib_363.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_412.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_412.DFLTRANGEX; + e.preventDefault(); - // make sure we don't later mutate the defaults - dflt = dflt.slice(); + if(_$hasHover_182) { + _$lib_425.removeElement(dragCover); + } + else if(cursor) { + dragCover.documentElement.style.cursor = cursor; + cursor = null; + } - if(!range || range.length !== 2) { - _$lib_363.nestedProperty(ax, rangeAttr).set(dflt); + if(!gd._dragging) { + gd._dragged = false; return; } + gd._dragging = false; - if(ax.type === 'date') { - // check if milliseconds or js date objects are provided for range - // and convert to date strings - range[0] = _$lib_363.cleanDate(range[0], __BADNUM_426, ax.calendar); - range[1] = _$lib_363.cleanDate(range[1], __BADNUM_426, ax.calendar); + // don't count as a dblClick unless the mouseUp is also within + // the dblclick delay + if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); } - for(i = 0; i < 2; i++) { - if(ax.type === 'date') { - if(!_$lib_363.isDateTime(range[i], ax.calendar)) { - ax[rangeAttr] = dflt; - break; - } + if(gd._dragged) { + if(options.doneFn) options.doneFn(e); + } + else { + if(options.clickFn) options.clickFn(numClicks, initialEvent); - if(ax.r2l(range[0]) === ax.r2l(range[1])) { - // split by +/- 1 second - var linCenter = _$lib_363.constrain(ax.r2l(range[0]), - _$lib_363.MIN_MS + 1000, _$lib_363.MAX_MS - 1000); - range[0] = ax.l2r(linCenter - 1000); - range[1] = ax.l2r(linCenter + 1000); - break; + // 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); } - } - else { - if(!_$fastIsnumeric_78(range[i])) { - if(_$fastIsnumeric_78(range[1 - i])) { - range[i] = range[1 - i] * (i ? 10 : 0.1); - } - else { - ax[rangeAttr] = dflt; - break; - } + 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); } - if(range[i] < -__FP_SAFE_426) range[i] = -__FP_SAFE_426; - else if(range[i] > __FP_SAFE_426) range[i] = __FP_SAFE_426; - - 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; - } + initialTarget.dispatchEvent(e2); } } - }; - - // set scaling to pixels - ax.setScale = function(usePrivateRange) { - var gs = fullLayout._size; - // TODO cleaner way to handle this case - if(!ax._categories) ax._categories = []; - // Add a map to optimize the performance of category collection - if(!ax._categoriesMap) ax._categoriesMap = {}; + finishDrag(gd); - // make sure we have a domain (pull it in from the axis - // this one is overlaying if necessary) - if(ax.overlaying) { - var ax2 = _$axis_ids_410.getFromId({ _fullLayout: fullLayout }, ax.overlaying); - ax.domain = ax2.domain; - } + gd._dragged = false; - // 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', - calendar = ax.calendar; - ax.cleanRange(rangeAttr); + return; + } +}; - var rl0 = ax.r2l(ax[rangeAttr][0], calendar), - rl1 = ax.r2l(ax[rangeAttr][1], calendar); +function coverSlip() { + var cover = document.createElement('div'); - 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; - } + 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'; - if(!isFinite(ax._m) || !isFinite(ax._b)) { - fullLayout._replotting = false; - throw new Error('Something went wrong with axis scaling'); - } - }; + document.body.appendChild(cover); - // 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; + return cover; +} - var axType = ax.type; - var cal = axType === 'date' && trace[axLetter + 'calendar']; +dragElement.coverSlip = coverSlip; - if(axLetter in trace) { - arrayIn = trace[axLetter]; - len = trace._length || arrayIn.length; +function finishDrag(gd) { + gd._dragging = false; + if(gd._replotPending) _$registry_514.call('plot', gd); +} - if(_$lib_363.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { - if(len === arrayIn.length) { - return arrayIn; - } else if(arrayIn.subarray) { - return arrayIn.subarray(0, len); - } - } +function pointerOffset(e) { + return _$mouseEventOffset_196( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); +} - 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; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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); +'use strict'; - for(i = 0; i < len; i++) { - arrayOut[i] = v0 + i * dv; - } - } +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$registry_514 = require('../../registry'); */; - return arrayOut; - }; +var _$calc_336 = function calc(gd) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; - ax.isValidRange = function(range) { - return ( - Array.isArray(range) && - range.length === 2 && - _$fastIsnumeric_78(ax.r2l(range[0])) && - _$fastIsnumeric_78(ax.r2l(range[1])) - ); - }; + function makeCoerceHoverInfo(trace) { + return function(val) { + return _$lib_425.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + }; + } - ax.isPtWithinRange = function(d, calendar) { - var coord = ax.c2l(d[axLetter], null, calendar); + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); - }; + // 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_514.traceIs(trace, 'pie')) continue; - ax.clearCalc = function() { - // for autoranging: arrays of objects: - // { - // val: axis value, - // pad: pixel padding, - // extrapad: boolean, should this val get 5% additional padding - // } - ax._min = []; - ax._max = []; + var fillFn = _$registry_514.traceIs(trace, '2dMap') ? paste : _$lib_425.fillArray; - // initialize the category list, if there is one, so we start over - // to be filled in later by ax.d2c - ax._categories = (ax._initialCategories || []).slice(); + fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); - // Build the lookup map for initialized categories - ax._categoriesMap = {}; - for(var j = 0; j < ax._categories.length; j++) { - ax._categoriesMap[ax._categories[j]] = j; - } - }; + if(!trace.hoverlabel) continue; - // 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_68.time.format.utc; - ax._extraFormat = fullLayout._extraFormat; + 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'); } - // 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_68.format; - - // and for bar charts and box plots: reset forced minimum tick spacing - delete ax._minDtick; - delete ax._forceTick0; }; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || _$lib_425.identity; + + if(Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} + +var _$color_301 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18072,128 +17927,164 @@ var _$setConvert_426 = function setConvert(ax, fullLayout) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$layout_attributes_419 = require('./layout_attributes'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -var _$handleTickLabelDefaults_427 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { - var showAttrDflt = getShowAttrDflt(containerIn); +var color = _$color_301 = {}; - var tickPrefix = coerce('tickprefix'); - if(tickPrefix) coerce('showtickprefix', showAttrDflt); +/* removed: var _$attributes_300 = require('./attributes'); */; +color.defaults = _$attributes_300.defaults; +var defaultLine = color.defaultLine = _$attributes_300.defaultLine; +color.lightLine = _$attributes_300.lightLine; +var background = color.background = _$attributes_300.background; - var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt); - if(tickSuffix) coerce('showticksuffix', showAttrDflt); +/* + * tinyRGB: turn a tinycolor into an rgb string, but + * unlike the built-in tinycolor.toRgbString this never includes alpha + */ +color.tinyRGB = function(tc) { + var c = tc.toRgb(); + return 'rgb(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ')'; +}; - var showTickLabels = coerce('showticklabels'); - if(showTickLabels) { - var font = options.font || {}; - // as with titlefont.color, inherit axis.color only if one was - // explicitly provided - var dfltFontColor = (containerOut.color === containerIn.color) ? - containerOut.color : font.color; - _$lib_363.coerceFont(coerce, 'tickfont', { - family: font.family, - size: font.size, - color: dfltFontColor - }); - coerce('tickangle'); +color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_263(cstr)); }; - if(axType !== 'category') { - var tickFormat = coerce('tickformat'); - tickformatstopsDefaults(containerIn, containerOut); - if(!tickFormat && axType !== 'date') { - coerce('showexponent', showAttrDflt); - coerce('exponentformat'); - coerce('separatethousands'); - } - } - } +color.opacity = function(cstr) { return cstr ? _$tinycolor_263(cstr).getAlpha() : 0; }; + +color.addOpacity = function(cstr, op) { + var c = _$tinycolor_263(cstr).toRgb(); + return 'rgba(' + Math.round(c.r) + ', ' + + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; +}; + +// combine two colors into one apparent color +// if back has transparency or is missing, +// color.background is assumed behind it +color.combine = function(front, back) { + var fc = _$tinycolor_263(front).toRgb(); + if(fc.a === 1) return _$tinycolor_263(front).toRgbString(); + + var bc = _$tinycolor_263(back || background).toRgb(), + bcflat = bc.a === 1 ? bc : { + r: 255 * (1 - bc.a) + bc.r * bc.a, + g: 255 * (1 - bc.a) + bc.g * bc.a, + b: 255 * (1 - bc.a) + bc.b * bc.a + }, + fcflat = { + r: bcflat.r * (1 - fc.a) + fc.r * fc.a, + g: bcflat.g * (1 - fc.a) + fc.g * fc.a, + b: bcflat.b * (1 - fc.a) + fc.b * fc.a + }; + return _$tinycolor_263(fcflat).toRgbString(); }; /* - * 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. + * Create a color that contrasts with cstr. * - * If 2 attributes are set to different values, - * the remaining is set to its dflt value. + * If cstr is a dark color, we lighten it; if it's light, we darken. * + * If lightAmount / darkAmount are used, we adjust by these percentages, + * otherwise we go all the way to white or black. */ -function getShowAttrDflt(containerIn) { - var showAttrsAll = ['showexponent', - 'showtickprefix', - 'showticksuffix'], - showAttrs = showAttrsAll.filter(function(a) { - return containerIn[a] !== undefined; - }), - sameVal = function(a) { - return containerIn[a] === containerIn[showAttrs[0]]; - }; +color.contrast = function(cstr, lightAmount, darkAmount) { + var tc = _$tinycolor_263(cstr); - if(showAttrs.every(sameVal) || showAttrs.length === 1) { - return containerIn[showAttrs[0]]; - } -} + if(tc.getAlpha() !== 1) tc = _$tinycolor_263(color.combine(cstr, background)); -function tickformatstopsDefaults(tickformatIn, tickformatOut) { - var valuesIn = tickformatIn.tickformatstops; - var valuesOut = tickformatOut.tickformatstops = []; + var newColor = tc.isDark() ? + (lightAmount ? tc.lighten(lightAmount) : background) : + (darkAmount ? tc.darken(darkAmount) : defaultLine); - if(!Array.isArray(valuesIn)) return; + return newColor.toString(); +}; - var valueIn, valueOut; +color.stroke = function(s, c) { + var tc = _$tinycolor_263(c); + s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); +}; - function coerce(attr, dflt) { - return _$lib_363.coerce(valueIn, valueOut, _$layout_attributes_419.tickformatstops, attr, dflt); - } +color.fill = function(s, c) { + var tc = _$tinycolor_263(c); + s.style({ + 'fill': color.tinyRGB(tc), + 'fill-opacity': tc.getAlpha() + }); +}; - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; +// search container for colors with the deprecated rgb(fractions) format +// and convert them to rgb(0-255 values) +color.clean = function(container) { + if(!container || typeof container !== 'object') return; - coerce('dtickrange'); - coerce('value'); + var keys = Object.keys(container), + i, + j, + key, + val; - valuesOut.push(valueOut); + for(i = 0; i < keys.length; i++) { + key = keys[i]; + val = container[key]; + + // only sanitize keys that end in "color" or "colorscale" + if(key.substr(key.length - 5) === 'color') { + if(Array.isArray(val)) { + for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); + } + else container[key] = cleanOne(val); + } + else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) { + // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]] + for(j = 0; j < val.length; j++) { + if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); + } + } + // recurse into arrays of objects, and plain objects + else if(Array.isArray(val)) { + var el0 = val[0]; + if(!Array.isArray(el0) && el0 && typeof el0 === 'object') { + for(j = 0; j < val.length; j++) color.clean(val[j]); + } + } + else if(val && typeof val === 'object') color.clean(val); } -} +}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function cleanOne(val) { + if(_$fastIsnumeric_135(val) || typeof val !== 'string') return val; + var valTrim = val.trim(); + if(valTrim.substr(0, 3) !== 'rgb') return val; -'use strict'; + var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); + if(!match) return val; -/* removed: var _$lib_363 = require('../../lib'); */; + var parts = match[1].trim().split(/\s*[\s,]\s*/), + rgba = valTrim.charAt(3) === 'a' && parts.length === 4; + if(!rgba && parts.length !== 3) return val; -/* removed: var _$layout_attributes_419 = require('./layout_attributes'); */; + for(var i = 0; i < parts.length; i++) { + if(!parts[i].length) return val; + parts[i] = Number(parts[i]); + // all parts must be non-negative numbers + if(!(parts[i] >= 0)) return val; + // alpha>1 gets clipped to 1 + if(i === 3) { + if(parts[i] > 1) parts[i] = 1; + } + // r, g, b must be < 1 (ie 1 itself is not allowed) + else if(parts[i] >= 1) return val; + } -/** - * options: inherits outerTicks from axes.handleAxisDefaults - */ -var _$handleTickDefaults_428 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_363.coerce2(containerIn, containerOut, _$layout_attributes_419, 'ticklen'), - tickWidth = _$lib_363.coerce2(containerIn, containerOut, _$layout_attributes_419, 'tickwidth'), - tickColor = _$lib_363.coerce2(containerIn, containerOut, _$layout_attributes_419, 'tickcolor', containerOut.color), - showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); + var rgbStr = Math.round(parts[0] * 255) + ', ' + + Math.round(parts[1] * 255) + ', ' + + Math.round(parts[2] * 255); - if(!showTicks) { - delete containerOut.ticklen; - delete containerOut.tickwidth; - delete containerOut.tickcolor; - } -}; + if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')'; + return 'rgb(' + rgbStr + ')'; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -18203,78 +18094,61 @@ var _$handleTickDefaults_428 = function handleTickDefaults(containerIn, containe * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -var __ONEDAY_429 = _$numerical_343.ONEDAY; - - -var _$handleTickValueDefaults_429 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { - var tickmodeDefault = 'auto'; - - if(containerIn.tickmode === 'array' && - (axType === 'log' || axType === 'date')) { - containerIn.tickmode = 'auto'; - } - - if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; - else if(containerIn.dtick) { - tickmodeDefault = 'linear'; - } - var tickmode = coerce('tickmode', tickmodeDefault); - - if(tickmode === 'auto') coerce('nticks'); - else if(tickmode === 'linear') { - // dtick is usually a positive number, but there are some - // special strings available for log or date axes - // default is 1 day for dates, otherwise 1 - var dtickDflt = (axType === 'date') ? __ONEDAY_429 : 1; - var dtick = coerce('dtick', dtickDflt); - if(_$fastIsnumeric_78(dtick)) { - containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; - } - else if(typeof dtick !== 'string') { - containerOut.dtick = dtickDflt; - } - else { - // date and log special cases are all one character plus a number - var prefix = dtick.charAt(0), - dtickNum = dtick.substr(1); - - dtickNum = _$fastIsnumeric_78(dtickNum) ? Number(dtickNum) : 0; - if((dtickNum <= 0) || !( - // "M" gives ticks every (integer) n months - (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || - // "L" gives ticks linearly spaced in data (not in position) every (float) f - (axType === 'log' && prefix === 'L') || - // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 - (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) - )) { - containerOut.dtick = dtickDflt; - } - } - - // tick0 can have different valType for different axis types, so - // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_363.dateTick0(containerOut.calendar) : 0; - var tick0 = coerce('tick0', tick0Dflt); - if(axType === 'date') { - containerOut.tick0 = _$lib_363.cleanDate(tick0, tick0Dflt); - } - // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely - else if(_$fastIsnumeric_78(tick0) && dtick !== 'D1' && dtick !== 'D2') { - containerOut.tick0 = Number(tick0); - } - else { - containerOut.tick0 = tick0Dflt; - } - } - else { - var tickvals = coerce('tickvals'); - if(tickvals === undefined) containerOut.tickmode = 'auto'; - else coerce('ticktext'); +var _$attributes_307 = { + zauto: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + impliedEdits: {zmin: undefined, zmax: undefined}, + + }, + zmin: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + zmax: { + valType: 'number', + + dflt: null, + editType: 'plot', + impliedEdits: {zauto: false}, + + }, + colorscale: { + valType: 'colorscale', + + editType: 'calc', + impliedEdits: {autocolorscale: false}, + + }, + autocolorscale: { + valType: 'boolean', + + dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. + editType: 'calc', + impliedEdits: {colorscale: undefined}, + + }, + reversescale: { + valType: 'boolean', + + dflt: false, + editType: 'calc', + + }, + showscale: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + } }; @@ -18286,97 +18160,20 @@ var _$handleTickValueDefaults_429 = function handleTickValueDefaults(containerIn * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; - -/* removed: var _$layout_attributes_419 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_429 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_428 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_427 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_411 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_421 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_426 = require('./set_convert'); */; -/* removed: var _$orderedCategories_422 = require('./ordered_categories'); */; - -/** - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_409 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; - var visible = coerce('visible', !options.cheateronly); +'use strict'; - var axType = containerOut.type; +var _$flipScale_313 = function flipScale(scl) { + var N = scl.length, + sclNew = new Array(N), + si; - if(axType === 'date') { - var handleCalendarDefaults = _$registry_451.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); + for(var i = N - 1, j = 0; i >= 0; i--, j++) { + si = scl[i]; + sclNew[j] = [1 - si[0], si[1]]; } - _$setConvert_426(containerOut, layoutOut); - - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; - - if(autoRange) coerce('rangemode'); - - coerce('range'); - containerOut.cleanRange(); - - _$handleCategoryOrderDefaults_411(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_422(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; - - - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); - - if(!visible) return containerOut; - - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; - - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_363.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); - - _$handleTickValueDefaults_429(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_427(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_428(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_421(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_419 - }); - - if(containerOut.showline || containerOut.ticks) coerce('mirror'); - - if(options.automargin) coerce('automargin'); - - return containerOut; + return sclNew; }; /** @@ -18390,231 +18187,74 @@ var _$handleAxisDefaults_409 = function handleAxisDefaults(containerIn, containe 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -var id2name = _$axis_ids_410.id2name; - - -var _$handleConstraintDefaults_413 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); - - if(containerOut.fixedrange) return; - - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_363.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); - - if(!containerIn.scaleanchor) return; - - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - - var scaleanchor = _$lib_363.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); - - 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, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_363.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.'); - } -}; - -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. - - 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 && !axj.fixedrange) linkableAxes.push(idj); - } - - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[i]; - - var linkableAxesNoLoops = []; - for(j = 0; j < linkableAxes.length; j++) { - idj = linkableAxes[j]; - if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); - } - return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; - } - } +/* removed: var _$lib_425 = require('../../lib'); */; - return {linkableAxes: linkableAxes, thisGroup: null}; -} +/* removed: var _$scales_320 = require('./scales'); */; +/* removed: var _$flipScale_313 = require('./flip_scale'); */; -/* - * 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; +var _$calc_308 = function calc(trace, vals, containerStr, cLetter) { + var container, inputContainer; - if(thisGroup === null) { - thisGroup = {}; - thisGroup[thisID] = 1; - thisGroupIndex = constraintGroups.length; - constraintGroups.push(thisGroup); + if(containerStr) { + container = _$lib_425.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_425.nestedProperty(trace._input, containerStr).get(); } else { - thisGroupIndex = constraintGroups.indexOf(thisGroup); + container = trace; + inputContainer = trace._input; } - var thisGroupKeys = Object.keys(thisGroup); + var autoAttr = cLetter + 'auto', + minAttr = cLetter + 'min', + maxAttr = cLetter + 'max', + auto = container[autoAttr], + min = container[minAttr], + max = container[maxAttr], + scl = container.colorscale; - // 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; - } + if(auto !== false || min === undefined) { + min = _$lib_425.aggNums(Math.min, null, vals); } - // 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; - } + if(auto !== false || max === undefined) { + max = _$lib_425.aggNums(Math.max, null, vals); } - thisGroup[scaleanchor] = 1; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; - -/* removed: var _$lib_363 = require('../../lib'); */; - - -var _$handlePositionDefaults_423 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; - - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } + if(min === max) { + min -= 0.5; + max += 0.5; } - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_78(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; - - var anchor = _$lib_363.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); + container[minAttr] = min; + container[maxAttr] = max; - if(anchor === 'free') coerce('position', dfltPosition); + inputContainer[minAttr] = min; + inputContainer[maxAttr] = max; - _$lib_363.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); + /* + * If auto was explicitly false but min or max was missing, + * we filled in the missing piece here but later the trace does + * not look auto. + * Otherwise make sure the trace still looks auto as far as later + * changes are concerned. + */ + inputContainer[autoAttr] = (auto !== false || + (min === undefined && max === undefined)); - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_363.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); - } + if(container.autocolorscale) { + if(min * max < 0) scl = _$scales_320.RdBu; + else if(min >= 0) scl = _$scales_320.Reds; + else scl = _$scales_320.Blues; - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_363.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + // reversescale is handled at the containerOut level + inputContainer.colorscale = scl; + if(container.reversescale) scl = _$flipScale_313(scl); + container.colorscale = scl; } - - coerce('layer'); - - return containerOut; }; +var _$attributes_325 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18626,69 +18266,19 @@ var _$handlePositionDefaults_423 = function handlePositionDefaults(containerIn, 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; - -/* removed: var _$lib_363 = require('../../lib'); */; -var __BADNUM_408 = _$numerical_343.BADNUM; - -var _$autoType_408 = function autoType(array, calendar) { - if(moreDates(array, calendar)) return 'date'; - if(category(array)) return 'category'; - if(linearOK(array)) return 'linear'; - else return '-'; +_$attributes_325.dash = { + valType: 'string', + // string type usually doesn't take values... this one should really be + // a special type or at least a special coercion function, from the GUI + // you only get these values but elsewhere the user can supply a list of + // dash lengths in px, and it will be honored + values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'], + dflt: 'solid', + + editType: 'style', + }; -// is there at least one number in array? If not, we should leave -// ax.type empty so it can be autoset later -function linearOK(array) { - if(!array) return false; - - for(var i = 0; i < array.length; i++) { - if(_$fastIsnumeric_78(array[i])) return true; - } - - return false; -} - -// does the array a have mostly dates rather than numbers? -// note: some values can be neither (such as blanks, text) -// 2- or 4-digit integers can be both, so require twice as many -// dates as non-dates, to exclude cases with mostly 2 & 4 digit -// numbers and a few dates -function moreDates(a, calendar) { - var dcnt = 0, - ncnt = 0, - // test at most 1000 points, evenly spaced - inc = Math.max(1, (a.length - 1) / 1000), - ai; - - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_363.isDateTime(ai, calendar)) dcnt += 1; - if(_$fastIsnumeric_78(ai)) ncnt += 1; - } - - return (dcnt > ncnt * 2); -} - -// are the (x,y)-values in gd.data mostly text? -// require twice as many categories as numbers -function category(a) { - // test at most 1000 points - var inc = Math.max(1, (a.length - 1) / 1000), - curvenums = 0, - curvecats = 0, - ai; - - for(var i = 0; i < a.length; i += inc) { - ai = a[Math.round(i)]; - if(_$lib_363.cleanNumber(ai) !== __BADNUM_408) curvenums++; - else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; - } - - return curvecats > curvenums * 2; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18697,746 +18287,509 @@ function category(a) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$autoType_408 = require('./axis_autotype'); */; -var name2id = _$axis_ids_410.name2id; - -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored - */ -var _$handleTypeDefaults_431 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } - - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; - } - } -}; - -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; - - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } +/* removed: var _$font_attributes_496 = require('../font_attributes'); */; +/* removed: var _$attributes_300 = require('../../components/color/attributes'); */; +var dash = _$attributes_325.dash; +var __extendFlat_482 = _$extend_416.extendFlat; - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; +/* removed: var _$constants_475 = require('./constants'); */; - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_451.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; - - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); - - if(trace[calAttr] !== calendar) calendar = undefined; - } - - ax.type = _$autoType_408(boxPositions, calendar); - } - else { - ax.type = _$autoType_408(d0[axLetter] || [d0[axLetter + '0']], calendar); - } -} - -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; - - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; - } - } - } -} - -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_451.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_451.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$color_239 = require('../../components/color'); */; -/* removed: var _$layout_attributes_442 = require('../layout_attributes'); */; - -/* removed: var _$layout_attributes_419 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_431 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_409 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_413 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_423 = require('./position_defaults'); */; -/* removed: var _$axis_ids_410 = require('./axis_ids'); */; - - -var _$supplyLayoutDefaults_420 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; - - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - - if(!_$registry_451.traceIs(trace, 'cartesian') && !_$registry_451.traceIs(trace, 'gl2d')) { - continue; - } - - var xaName = _$axis_ids_410.id2name(trace.xaxis); - var yaName = _$axis_ids_410.id2name(trace.yaxis); - - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_451.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } - - // 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) xaCheater[xaName] = 1; - } - - // check for default formatting tweaks - if(_$registry_451.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } - - if(_$registry_451.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_363.simpleMap(xIds, _$axis_ids_410.id2name); - var yNames = _$lib_363.simpleMap(yIds, _$axis_ids_410.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 plot_bgcolor = _$color_239.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_363.coerce(layoutIn, layoutOut, _$layout_attributes_442, 'plot_bgcolor'); - } - - var bgColor = _$color_239.combine(plot_bgcolor, layoutOut.paper_bgcolor); - - var axName, axLetter, axLayoutIn, axLayoutOut; - - function coerce(attr, dflt) { - return _$lib_363.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_419, attr, dflt); - } - - function coerce2(attr, dflt) { - return _$lib_363.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_419, attr, dflt); - } - - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; - } - - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('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(_$axis_ids_410.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]; - - if(!_$lib_363.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; - - _$handleTypeDefaults_431(axLayoutIn, axLayoutOut, coerce, fullData, axName); - - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); - - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; - - _$handleAxisDefaults_409(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; - } - - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; - - _$handlePositionDefaults_423(axLayoutIn, axLayoutOut, coerce, positioningOptions); - - axLayoutOut._input = axLayoutIn; - } - - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_451.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_451.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[_$axis_ids_410.id2name(axLayoutOut.anchor)]; - - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); - - coerce('fixedrange', fixedRangeDflt); - } - - // Finally, handle scale constraints. 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 - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); - - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); - - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; - - _$handleConstraintDefaults_413(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$attributes_245 = { - zauto: { +var _$layout_attributes_482 = { + visible: { valType: 'boolean', - dflt: true, - editType: 'calc', - impliedEdits: {zmin: undefined, zmax: undefined}, - - }, - zmin: { - valType: 'number', - - dflt: null, editType: 'plot', - impliedEdits: {zauto: false}, }, - zmax: { - valType: 'number', + color: { + valType: 'color', + dflt: _$attributes_300.defaultLine, - dflt: null, - editType: 'plot', - impliedEdits: {zauto: false}, + editType: 'ticks', }, - colorscale: { - valType: 'colorscale', + title: { + valType: 'string', - editType: 'calc', - impliedEdits: {autocolorscale: false}, + editType: 'ticks+margins', }, - autocolorscale: { - valType: 'boolean', + titlefont: _$font_attributes_496({ + editType: 'ticks+margins', + + }), + type: { + valType: 'enumerated', + // '-' means we haven't yet run autotype or couldn't find any data + // it gets turned into linear in gd._fullLayout but not copied back + // to gd.data like the others are. + values: ['-', 'linear', 'log', 'date', 'category'], + dflt: '-', - dflt: true, // gets overrode in 'heatmap' & 'surface' for backwards comp. editType: 'calc', - impliedEdits: {colorscale: undefined}, }, - reversescale: { - valType: 'boolean', + autorange: { + valType: 'enumerated', + values: [true, false, 'reversed'], + dflt: true, - dflt: false, editType: 'calc', + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - showscale: { - valType: 'boolean', + rangemode: { + valType: 'enumerated', + values: ['normal', 'tozero', 'nonnegative'], + dflt: 'normal', - dflt: true, - editType: 'calc', + editType: 'plot', - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var _$flipScale_251 = function flipScale(scl) { - var N = scl.length, - sclNew = new Array(N), - si; - - for(var i = N - 1, j = 0; i >= 0; i--, j++) { - si = scl[i]; - sclNew[j] = [1 - si[0], si[1]]; - } - - return sclNew; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_363 = require('../../lib'); */; - -/* removed: var _$scales_258 = require('./scales'); */; -/* removed: var _$flipScale_251 = require('./flip_scale'); */; - - -var _$calc_246 = function calc(trace, vals, containerStr, cLetter) { - var container, inputContainer; - - if(containerStr) { - container = _$lib_363.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_363.nestedProperty(trace._input, containerStr).get(); - } - else { - container = trace; - inputContainer = trace._input; - } - - var autoAttr = cLetter + 'auto', - minAttr = cLetter + 'min', - maxAttr = cLetter + 'max', - auto = container[autoAttr], - min = container[minAttr], - max = container[maxAttr], - scl = container.colorscale; - - if(auto !== false || min === undefined) { - min = _$lib_363.aggNums(Math.min, null, vals); - } - - if(auto !== false || max === undefined) { - max = _$lib_363.aggNums(Math.max, null, vals); - } - - if(min === max) { - min -= 0.5; - max += 0.5; - } - - container[minAttr] = min; - container[maxAttr] = max; - - inputContainer[minAttr] = min; - inputContainer[maxAttr] = max; - - /* - * If auto was explicitly false but min or max was missing, - * we filled in the missing piece here but later the trace does - * not look auto. - * Otherwise make sure the trace still looks auto as far as later - * changes are concerned. - */ - inputContainer[autoAttr] = (auto !== false || - (min === undefined && max === undefined)); - - if(container.autocolorscale) { - if(min * max < 0) scl = _$scales_258.RdBu; - else if(min >= 0) scl = _$scales_258.Reds; - else scl = _$scales_258.Blues; - - // reversescale is handled at the containerOut level - inputContainer.colorscale = scl; - if(container.reversescale) scl = _$flipScale_251(scl); - container.colorscale = scl; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$layout_attributes_419 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -var __extendFlat_240 = _$extend_354.extendFlat; -var __overrideAll_240 = _$edit_types_392.overrideAll; - - -var _$attributes_240 = __overrideAll_240({ -// TODO: only right is supported currently -// orient: { -// valType: 'enumerated', -// -// values: ['left', 'right', 'top', 'bottom'], -// dflt: 'right', -// -// }, - thicknessmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], + }, + range: { + valType: 'info_array', - dflt: 'pixels', + items: [ + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} + ], + editType: 'axrange+margins', + impliedEdits: {'autorange': false}, }, - thickness: { - valType: 'number', + fixedrange: { + valType: 'boolean', + dflt: false, - min: 0, - dflt: 30, + editType: 'calc', }, - lenmode: { + // scaleanchor: not used directly, just put here for reference + // values are any opposite-letter axis id + scaleanchor: { valType: 'enumerated', - values: ['fraction', 'pixels'], + values: [ + _$constants_475.idRegex.x.toString(), + _$constants_475.idRegex.y.toString() + ], - dflt: 'fraction', + editType: 'plot', }, - len: { + scaleratio: { valType: 'number', min: 0, dflt: 1, + editType: 'plot', }, - x: { - valType: 'number', - dflt: 1.02, - min: -2, - max: 3, + constrain: { + valType: 'enumerated', + values: ['range', 'domain'], + dflt: 'range', + editType: 'plot', }, - xanchor: { + // constraintoward: not used directly, just put here for reference + constraintoward: { valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', + values: ['left', 'center', 'right', 'top', 'middle', 'bottom'], + editType: 'plot', }, - xpad: { - valType: 'number', + // ticks + tickmode: { + valType: 'enumerated', + values: ['auto', 'linear', 'array'], - min: 0, - dflt: 10, + editType: 'ticks+margins', + impliedEdits: {tick0: undefined, dtick: undefined}, }, - y: { - valType: 'number', + nticks: { + valType: 'integer', + min: 0, + dflt: 0, - dflt: 0.5, - min: -2, - max: 3, + editType: 'ticks+margins', }, - yanchor: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], + tick0: { + valType: 'any', - dflt: 'middle', + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - ypad: { - valType: 'number', + dtick: { + valType: 'any', - min: 0, - dflt: 10, + editType: 'ticks+margins', + impliedEdits: {tickmode: 'linear'}, }, - // a possible line around the bar itself - outlinecolor: _$layout_attributes_419.linecolor, - outlinewidth: _$layout_attributes_419.linewidth, - // Should outlinewidth have {dflt: 0} ? - // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_419.linecolor, - borderwidth: { - valType: 'number', + tickvals: { + valType: 'data_array', + editType: 'ticks+margins', + + }, + ticktext: { + valType: 'data_array', + editType: 'ticks+margins', + + }, + ticks: { + valType: 'enumerated', + values: ['outside', 'inside', ''], + + editType: 'ticks+margins', + + }, + mirror: { + valType: 'enumerated', + values: [true, 'ticks', false, 'all', 'allticks'], + dflt: false, + + editType: 'ticks+layoutstyle', + }, + ticklen: { + valType: 'number', min: 0, - dflt: 0, + dflt: 5, + + editType: 'ticks', }, - bgcolor: { + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks', + + }, + tickcolor: { valType: 'color', + dflt: _$attributes_300.defaultLine, - dflt: 'rgba(0,0,0,0)', + editType: 'ticks', }, - // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_419.tickmode, - nticks: _$layout_attributes_419.nticks, - tick0: _$layout_attributes_419.tick0, - dtick: _$layout_attributes_419.dtick, - tickvals: _$layout_attributes_419.tickvals, - ticktext: _$layout_attributes_419.ticktext, - ticks: __extendFlat_240({}, _$layout_attributes_419.ticks, {dflt: ''}), - ticklen: _$layout_attributes_419.ticklen, - tickwidth: _$layout_attributes_419.tickwidth, - tickcolor: _$layout_attributes_419.tickcolor, - showticklabels: _$layout_attributes_419.showticklabels, - tickfont: _$font_attributes_434({ + showticklabels: { + valType: 'boolean', + dflt: true, + + editType: 'ticks+margins', + + }, + automargin: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + showspikes: { + valType: 'boolean', + dflt: false, + + editType: 'modebar', + + }, + spikecolor: { + valType: 'color', + dflt: null, + + editType: 'none', + + }, + spikethickness: { + valType: 'number', + dflt: 3, + + editType: 'none', + + }, + spikedash: __extendFlat_482({}, dash, {dflt: 'dash', editType: 'none'}), + spikemode: { + valType: 'flaglist', + flags: ['toaxis', 'across', 'marker'], + + dflt: 'toaxis', + editType: 'none', + + }, + spikesnap: { + valType: 'enumerated', + values: ['data', 'cursor'], + dflt: 'data', + + editType: 'none', + + }, + tickfont: _$font_attributes_496({ + editType: 'ticks+margins', }), - tickangle: _$layout_attributes_419.tickangle, - tickformat: _$layout_attributes_419.tickformat, - tickformatstops: _$layout_attributes_419.tickformatstops, - tickprefix: _$layout_attributes_419.tickprefix, - showtickprefix: _$layout_attributes_419.showtickprefix, - ticksuffix: _$layout_attributes_419.ticksuffix, - showticksuffix: _$layout_attributes_419.showticksuffix, - separatethousands: _$layout_attributes_419.separatethousands, - exponentformat: _$layout_attributes_419.exponentformat, - showexponent: _$layout_attributes_419.showexponent, - title: { + tickangle: { + valType: 'angle', + dflt: 'auto', + + editType: 'ticks+margins', + + }, + tickprefix: { valType: 'string', + dflt: '', + editType: 'ticks+margins', }, - titlefont: _$font_attributes_434({ + showtickprefix: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - }), - titleside: { + editType: 'ticks+margins', + + }, + ticksuffix: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + showticksuffix: { valType: 'enumerated', - values: ['right', 'top', 'bottom'], + values: ['all', 'first', 'last', 'none'], + dflt: 'all', - dflt: 'top', + editType: 'ticks+margins', - } -}, 'colorbars', 'from-root'); - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_429 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_428 = require('../../plots/cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_427 = require('../../plots/cartesian/tick_label_defaults'); */; - -/* removed: var _$attributes_240 = require('./attributes'); */; - + }, + showexponent: { + valType: 'enumerated', + values: ['all', 'first', 'last', 'none'], + dflt: 'all', + + editType: 'ticks+margins', + + }, + exponentformat: { + valType: 'enumerated', + values: ['none', 'e', 'E', 'power', 'SI', 'B'], + dflt: 'B', + + editType: 'ticks+margins', + + }, + separatethousands: { + valType: 'boolean', + dflt: false, + + editType: 'ticks+margins', + + }, + tickformat: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + tickformatstops: { + _isLinkedToArray: 'tickformatstop', -var _$colorbarDefaults_242 = function colorbarDefaults(containerIn, containerOut, layout) { - var colorbarOut = containerOut.colorbar = {}, - colorbarIn = containerIn.colorbar || {}; + dtickrange: { + valType: 'info_array', + + items: [ + {valType: 'any', editType: 'ticks+margins'}, + {valType: 'any', editType: 'ticks+margins'} + ], + editType: 'ticks+margins', + + }, + value: { + valType: 'string', + dflt: '', + + editType: 'ticks+margins', + + }, + editType: 'ticks+margins' + }, + hoverformat: { + valType: 'string', + dflt: '', + + editType: 'none', + + }, + // lines and grids + showline: { + valType: 'boolean', + dflt: false, + + editType: 'layoutstyle', + + }, + linecolor: { + valType: 'color', + dflt: _$attributes_300.defaultLine, + + editType: 'layoutstyle', + + }, + linewidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks+layoutstyle', + + }, + showgrid: { + valType: 'boolean', + + editType: 'ticks', + + }, + gridcolor: { + valType: 'color', + dflt: _$attributes_300.lightLine, + + editType: 'ticks', + + }, + gridwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'ticks', + + }, + zeroline: { + valType: 'boolean', + + editType: 'ticks', + + }, + zerolinecolor: { + valType: 'color', + dflt: _$attributes_300.defaultLine, + + editType: 'ticks', + + }, + zerolinewidth: { + valType: 'number', + dflt: 1, + + editType: 'ticks', + + }, + // positioning attributes + // anchor: not used directly, just put here for reference + // values are any opposite-letter axis id + anchor: { + valType: 'enumerated', + values: [ + 'free', + _$constants_475.idRegex.x.toString(), + _$constants_475.idRegex.y.toString() + ], + + editType: 'plot+margins', + + }, + // side: not used directly, as values depend on direction + // values are top, bottom for x axes, and left, right for y + side: { + valType: 'enumerated', + values: ['top', 'bottom', 'left', 'right'], + + editType: 'plot+margins', + + }, + // overlaying: not used directly, just put here for reference + // values are false and any other same-letter axis id that's not + // itself overlaying anything + overlaying: { + valType: 'enumerated', + values: [ + 'free', + _$constants_475.idRegex.x.toString(), + _$constants_475.idRegex.y.toString() + ], + + editType: 'plot', + + }, + layer: { + valType: 'enumerated', + values: ['above traces', 'below traces'], + dflt: 'above traces', + + editType: 'plot', + + }, + domain: { + valType: 'info_array', + + items: [ + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}, + {valType: 'number', min: 0, max: 1, editType: 'plot+margins'} + ], + dflt: [0, 1], + editType: 'plot+margins', + + }, + position: { + valType: 'number', + min: 0, + max: 1, + dflt: 0, + + editType: 'plot+margins', + + }, + categoryorder: { + valType: 'enumerated', + values: [ + 'trace', 'category ascending', 'category descending', 'array' + /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later + ], + dflt: 'trace', + + editType: 'calc', + + }, + categoryarray: { + valType: 'data_array', + + editType: 'calc', + + }, + editType: 'calc', - function coerce(attr, dflt) { - return _$lib_363.coerce(colorbarIn, colorbarOut, _$attributes_240, attr, dflt); + _deprecated: { + autotick: { + valType: 'boolean', + + editType: 'ticks+margins', + + } } - - var thicknessmode = coerce('thicknessmode'); - coerce('thickness', (thicknessmode === 'fraction') ? - 30 / (layout.width - layout.margin.l - layout.margin.r) : - 30 - ); - - var lenmode = coerce('lenmode'); - coerce('len', (lenmode === 'fraction') ? - 1 : - layout.height - layout.margin.t - layout.margin.b - ); - - coerce('x'); - coerce('xanchor'); - coerce('xpad'); - coerce('y'); - coerce('yanchor'); - coerce('ypad'); - _$lib_363.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); - - coerce('outlinecolor'); - coerce('outlinewidth'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('bgcolor'); - - _$handleTickValueDefaults_429(colorbarIn, colorbarOut, coerce, 'linear'); - - var opts = {outerTicks: false, font: layout.font}; - _$handleTickLabelDefaults_427(colorbarIn, colorbarOut, coerce, 'linear', opts); - _$handleTickDefaults_428(colorbarIn, colorbarOut, coerce, 'linear', opts); - - coerce('title', layout._dfltTitle.colorbar); - _$lib_363.coerceFont(coerce, 'titlefont', layout.font); - coerce('titleside'); }; /** @@ -19447,15 +18800,155 @@ var _$colorbarDefaults_242 = function colorbarDefaults(containerIn, containerOut * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$layout_attributes_482 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +var __extendFlat_302 = _$extend_416.extendFlat; +var __overrideAll_302 = _$edit_types_455.overrideAll; -var _$hasColorbar_244 = function hasColorbar(container) { - return _$lib_363.isPlainObject(container.colorbar); -}; +var _$attributes_302 = __overrideAll_302({ +// 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: _$layout_attributes_482.linecolor, + outlinewidth: _$layout_attributes_482.linewidth, + // Should outlinewidth have {dflt: 0} ? + // another possible line outside the padding and tick labels + bordercolor: _$layout_attributes_482.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: _$layout_attributes_482.tickmode, + nticks: _$layout_attributes_482.nticks, + tick0: _$layout_attributes_482.tick0, + dtick: _$layout_attributes_482.dtick, + tickvals: _$layout_attributes_482.tickvals, + ticktext: _$layout_attributes_482.ticktext, + ticks: __extendFlat_302({}, _$layout_attributes_482.ticks, {dflt: ''}), + ticklen: _$layout_attributes_482.ticklen, + tickwidth: _$layout_attributes_482.tickwidth, + tickcolor: _$layout_attributes_482.tickcolor, + showticklabels: _$layout_attributes_482.showticklabels, + tickfont: _$font_attributes_496({ + + }), + tickangle: _$layout_attributes_482.tickangle, + tickformat: _$layout_attributes_482.tickformat, + tickformatstops: _$layout_attributes_482.tickformatstops, + tickprefix: _$layout_attributes_482.tickprefix, + showtickprefix: _$layout_attributes_482.showtickprefix, + ticksuffix: _$layout_attributes_482.ticksuffix, + showticksuffix: _$layout_attributes_482.showticksuffix, + separatethousands: _$layout_attributes_482.separatethousands, + exponentformat: _$layout_attributes_482.exponentformat, + showexponent: _$layout_attributes_482.showexponent, + title: { + valType: 'string', + + + }, + titlefont: _$font_attributes_496({ + + }), + titleside: { + valType: 'enumerated', + values: ['right', 'top', 'bottom'], + + dflt: 'top', + + } +}, 'colorbars', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -19468,51 +18961,350 @@ var _$hasColorbar_244 = function hasColorbar(container) { 'use strict'; -/* removed: var _$scales_258 = require('./scales'); */; -/* removed: var _$isValidScaleArray_256 = require('./is_valid_scale_array'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$layout_attributes_482 = require('./layout_attributes'); */; +var _$handleTickLabelDefaults_489 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { + var showAttrDflt = getShowAttrDflt(containerIn); -var _$isValidScale_255 = function isValidScale(scl) { - if(_$scales_258[scl] !== undefined) return true; - else return _$isValidScaleArray_256(scl); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 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 || {}; + // as with titlefont.color, inherit axis.color only if one was + // explicitly provided + var dfltFontColor = (containerOut.color === containerIn.color) ? + containerOut.color : font.color; + _$lib_425.coerceFont(coerce, 'tickfont', { + family: font.family, + size: font.size, + color: dfltFontColor + }); + coerce('tickangle'); + + if(axType !== 'category') { + var tickFormat = coerce('tickformat'); + tickformatstopsDefaults(containerIn, containerOut); + 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'], + showAttrs = showAttrsAll.filter(function(a) { + return containerIn[a] !== undefined; + }), + sameVal = function(a) { + return containerIn[a] === containerIn[showAttrs[0]]; + }; + + if(showAttrs.every(sameVal) || showAttrs.length === 1) { + return containerIn[showAttrs[0]]; + } +} + +function tickformatstopsDefaults(tickformatIn, tickformatOut) { + var valuesIn = tickformatIn.tickformatstops; + var valuesOut = tickformatOut.tickformatstops = []; + + if(!Array.isArray(valuesIn)) return; + + var valueIn, valueOut; + + function coerce(attr, dflt) { + return _$lib_425.coerce(valueIn, valueOut, _$layout_attributes_482.tickformatstops, attr, dflt); + } + + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; + + coerce('dtickrange'); + coerce('value'); + + valuesOut.push(valueOut); + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_425 = require('../../lib'); */; + +/* removed: var _$layout_attributes_482 = require('./layout_attributes'); */; + + +/** + * options: inherits outerTicks from axes.handleAxisDefaults + */ +var _$handleTickDefaults_490 = function handleTickDefaults(containerIn, containerOut, coerce, options) { + var tickLen = _$lib_425.coerce2(containerIn, containerOut, _$layout_attributes_482, 'ticklen'), + tickWidth = _$lib_425.coerce2(containerIn, containerOut, _$layout_attributes_482, 'tickwidth'), + tickColor = _$lib_425.coerce2(containerIn, containerOut, _$layout_attributes_482, 'tickcolor', containerOut.color), + showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); + + if(!showTicks) { + delete containerOut.ticklen; + delete containerOut.tickwidth; + delete containerOut.tickcolor; + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +var __ONEDAY_491 = _$numerical_404.ONEDAY; + + +var _$handleTickValueDefaults_491 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { + var tickmodeDefault = 'auto'; + + if(containerIn.tickmode === 'array' && + (axType === 'log' || axType === 'date')) { + containerIn.tickmode = 'auto'; + } + + if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array'; + else if(containerIn.dtick) { + tickmodeDefault = 'linear'; + } + var tickmode = coerce('tickmode', tickmodeDefault); + + if(tickmode === 'auto') coerce('nticks'); + else if(tickmode === 'linear') { + // dtick is usually a positive number, but there are some + // special strings available for log or date axes + // default is 1 day for dates, otherwise 1 + var dtickDflt = (axType === 'date') ? __ONEDAY_491 : 1; + var dtick = coerce('dtick', dtickDflt); + if(_$fastIsnumeric_135(dtick)) { + containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; + } + else if(typeof dtick !== 'string') { + containerOut.dtick = dtickDflt; + } + else { + // date and log special cases are all one character plus a number + var prefix = dtick.charAt(0), + dtickNum = dtick.substr(1); + + dtickNum = _$fastIsnumeric_135(dtickNum) ? Number(dtickNum) : 0; + if((dtickNum <= 0) || !( + // "M" gives ticks every (integer) n months + (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || + // "L" gives ticks linearly spaced in data (not in position) every (float) f + (axType === 'log' && prefix === 'L') || + // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 + (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2)) + )) { + containerOut.dtick = dtickDflt; + } + } + + // tick0 can have different valType for different axis types, so + // validate that now. Also for dates, change milliseconds to date strings + var tick0Dflt = (axType === 'date') ? _$lib_425.dateTick0(containerOut.calendar) : 0; + var tick0 = coerce('tick0', tick0Dflt); + if(axType === 'date') { + containerOut.tick0 = _$lib_425.cleanDate(tick0, tick0Dflt); + } + // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely + else if(_$fastIsnumeric_135(tick0) && dtick !== 'D1' && dtick !== 'D2') { + containerOut.tick0 = Number(tick0); + } + else { + containerOut.tick0 = tick0Dflt; + } + } + else { + var tickvals = coerce('tickvals'); + if(tickvals === undefined) containerOut.tickmode = 'auto'; + else coerce('ticktext'); + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_491 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_490 = require('../../plots/cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_489 = require('../../plots/cartesian/tick_label_defaults'); */; + +/* removed: var _$attributes_302 = require('./attributes'); */; + + +var _$colorbarDefaults_304 = function colorbarDefaults(containerIn, containerOut, layout) { + var colorbarOut = containerOut.colorbar = {}, + colorbarIn = containerIn.colorbar || {}; + + function coerce(attr, dflt) { + return _$lib_425.coerce(colorbarIn, colorbarOut, _$attributes_302, attr, dflt); + } + + var thicknessmode = coerce('thicknessmode'); + coerce('thickness', (thicknessmode === 'fraction') ? + 30 / (layout.width - layout.margin.l - layout.margin.r) : + 30 + ); + + var lenmode = coerce('lenmode'); + coerce('len', (lenmode === 'fraction') ? + 1 : + layout.height - layout.margin.t - layout.margin.b + ); + + coerce('x'); + coerce('xanchor'); + coerce('xpad'); + coerce('y'); + coerce('yanchor'); + coerce('ypad'); + _$lib_425.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + + coerce('outlinecolor'); + coerce('outlinewidth'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('bgcolor'); + + _$handleTickValueDefaults_491(colorbarIn, colorbarOut, coerce, 'linear'); + + var opts = {outerTicks: false, font: layout.font}; + _$handleTickLabelDefaults_489(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickDefaults_490(colorbarIn, colorbarOut, coerce, 'linear', opts); + + coerce('title', layout._dfltTitle.colorbar); + _$lib_425.coerceFont(coerce, 'titlefont', layout.font); + coerce('titleside'); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$lib_425 = require('../../lib'); */; + + +var _$hasColorbar_306 = function hasColorbar(container) { + return _$lib_425.isPlainObject(container.colorbar); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$scales_320 = require('./scales'); */; +/* removed: var _$isValidScaleArray_318 = require('./is_valid_scale_array'); */; + + +var _$isValidScale_317 = function isValidScale(scl) { + if(_$scales_320[scl] !== undefined) return true; + else return _$isValidScaleArray_318(scl); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; -/* removed: var _$hasColorbar_244 = require('../colorbar/has_colorbar'); */; -/* removed: var _$colorbarDefaults_242 = require('../colorbar/defaults'); */; -/* removed: var _$isValidScale_255 = require('./is_valid_scale'); */; -/* removed: var _$flipScale_251 = require('./flip_scale'); */; +/* removed: var _$hasColorbar_306 = require('../colorbar/has_colorbar'); */; +/* removed: var _$colorbarDefaults_304 = require('../colorbar/defaults'); */; +/* removed: var _$isValidScale_317 = require('./is_valid_scale'); */; +/* removed: var _$flipScale_313 = require('./flip_scale'); */; -var _$colorScaleDefaults_249 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { +var _$colorScaleDefaults_311 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { var prefix = opts.prefix, cLetter = opts.cLetter, containerStr = prefix.slice(0, prefix.length - 1), containerIn = prefix ? - _$lib_363.nestedProperty(traceIn, containerStr).get() || {} : + _$lib_425.nestedProperty(traceIn, containerStr).get() || {} : traceIn, containerOut = prefix ? - _$lib_363.nestedProperty(traceOut, containerStr).get() || {} : + _$lib_425.nestedProperty(traceOut, containerStr).get() || {} : traceOut, minIn = containerIn[cLetter + 'min'], maxIn = containerIn[cLetter + 'max'], sclIn = containerIn.colorscale; - var validMinMax = _$fastIsnumeric_78(minIn) && _$fastIsnumeric_78(maxIn) && (minIn < maxIn); + var validMinMax = _$fastIsnumeric_135(minIn) && _$fastIsnumeric_135(maxIn) && (minIn < maxIn); coerce(prefix + cLetter + 'auto', !validMinMax); coerce(prefix + cLetter + 'min'); coerce(prefix + cLetter + 'max'); @@ -19520,13 +19312,13 @@ var _$colorScaleDefaults_249 = function colorScaleDefaults(traceIn, traceOut, la // handles both the trace case (autocolorscale is false by default) and // the marker and marker.line case (autocolorscale is true by default) var autoColorscaleDftl; - if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_255(sclIn); + if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_317(sclIn); coerce(prefix + 'autocolorscale', autoColorscaleDftl); var sclOut = coerce(prefix + 'colorscale'); // reversescale is handled at the containerOut level var reverseScale = coerce(prefix + 'reversescale'); - if(reverseScale) containerOut.colorscale = _$flipScale_251(sclOut); + if(reverseScale) containerOut.colorscale = _$flipScale_313(sclOut); // ... until Scatter.colorbar can handle marker line colorbars if(prefix === 'marker.line.') return; @@ -19534,10 +19326,10 @@ var _$colorScaleDefaults_249 = function colorScaleDefaults(traceIn, traceOut, la // handle both the trace case where the dflt is listed in attributes and // the marker case where the dflt is determined by hasColorbar var showScaleDftl; - if(prefix) showScaleDftl = _$hasColorbar_244(containerIn); + if(prefix) showScaleDftl = _$hasColorbar_306(containerIn); var showScale = coerce(prefix + 'showscale', showScaleDftl); - if(showScale) _$colorbarDefaults_242(containerIn, containerOut, layout); + if(showScale) _$colorbarDefaults_304(containerIn, containerOut, layout); }; /** @@ -19558,7 +19350,7 @@ var _$colorScaleDefaults_249 = function colorScaleDefaults(traceIn, traceOut, la * @param {number} cmin minimum color value (used to clamp scale) * @param {number} cmax maximum color value (used to clamp scale) */ -var _$extractScale_250 = function extractScale(scl, cmin, cmax) { +var _$extractScale_312 = function extractScale(scl, cmin, cmax) { var N = scl.length, domain = new Array(N), range = new Array(N); @@ -19586,20 +19378,20 @@ var _$extractScale_250 = function extractScale(scl, cmin, cmax) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$isValidScale_255 = require('./is_valid_scale'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$isValidScale_317 = require('./is_valid_scale'); */; -var _$hasColorscale_253 = function hasColorscale(trace, containerStr) { +var _$hasColorscale_315 = function hasColorscale(trace, containerStr) { var container = containerStr ? - _$lib_363.nestedProperty(trace, containerStr).get() || {} : + _$lib_425.nestedProperty(trace, containerStr).get() || {} : trace; var color = container.color; var isArrayWithOneNumber = false; - if(_$lib_363.isArrayOrTypedArray(color)) { + if(_$lib_425.isArrayOrTypedArray(color)) { for(var i = 0; i < color.length; i++) { - if(_$fastIsnumeric_78(color[i])) { + if(_$fastIsnumeric_135(color[i])) { isArrayWithOneNumber = true; break; } @@ -19607,12 +19399,12 @@ var _$hasColorscale_253 = function hasColorscale(trace, containerStr) { } return ( - _$lib_363.isPlainObject(container) && ( + _$lib_425.isPlainObject(container) && ( isArrayWithOneNumber || container.showscale === true || - (_$fastIsnumeric_78(container.cmin) && _$fastIsnumeric_78(container.cmax)) || - _$isValidScale_255(container.colorscale) || - _$lib_363.isPlainObject(container.colorbar) + (_$fastIsnumeric_135(container.cmin) && _$fastIsnumeric_135(container.cmax)) || + _$isValidScale_317(container.colorscale) || + _$lib_425.isPlainObject(container.colorbar) ) ); }; @@ -19628,11 +19420,11 @@ var _$hasColorscale_253 = function hasColorscale(trace, containerStr) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$color_239 = require('../color'); */; +/* removed: var _$color_301 = require('../color'); */; /** * General colorscale function generator. @@ -19647,7 +19439,7 @@ var _$hasColorscale_253 = function hasColorscale(trace, containerStr) { * * @return {function} */ -var _$makeColorScaleFunc_257 = function makeColorScaleFunc(specs, opts) { +var _$makeColorScaleFunc_319 = function makeColorScaleFunc(specs, opts) { opts = opts || {}; var domain = specs.domain, @@ -19656,11 +19448,11 @@ var _$makeColorScaleFunc_257 = function makeColorScaleFunc(specs, opts) { _range = new Array(N); for(var i = 0; i < N; i++) { - var rgba = _$tinycolor_201(range[i]).toRgb(); + var rgba = _$tinycolor_263(range[i]).toRgb(); _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a]; } - var _sclFunc = _$d3_68.scale.linear() + var _sclFunc = _$d3_71.scale.linear() .domain(domain) .range(_range) .clamp(true); @@ -19679,16 +19471,16 @@ var _$makeColorScaleFunc_257 = function makeColorScaleFunc(specs, opts) { } else if(returnArray) { sclFunc = function(v) { - if(_$fastIsnumeric_78(v)) return _sclFunc(v); - else if(_$tinycolor_201(v).isValid()) return v; - else return _$color_239.defaultLine; + if(_$fastIsnumeric_135(v)) return _sclFunc(v); + else if(_$tinycolor_263(v).isValid()) return v; + else return _$color_301.defaultLine; }; } else { sclFunc = function(v) { - if(_$fastIsnumeric_78(v)) return colorArray2rbga(_sclFunc(v)); - else if(_$tinycolor_201(v).isValid()) return v; - else return _$color_239.defaultLine; + if(_$fastIsnumeric_135(v)) return colorArray2rbga(_sclFunc(v)); + else if(_$tinycolor_263(v).isValid()) return v; + else return _$color_301.defaultLine; }; } @@ -19709,10 +19501,10 @@ function colorArray2rbga(colorArray) { a: colorArray[3] }; - return _$tinycolor_201(colorObj).toRgbString(); + return _$tinycolor_263(colorObj).toRgbString(); } -var _$colorscale_254 = {}; +var _$colorscale_316 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -19724,27 +19516,27 @@ var _$colorscale_254 = {}; 'use strict'; -_$colorscale_254.scales = _$scales_258; +_$colorscale_316.scales = _$scales_320; -_$colorscale_254.defaultScale = _$default_scale_248; +_$colorscale_316.defaultScale = _$default_scale_310; -_$colorscale_254.attributes = _$attributes_245; +_$colorscale_316.attributes = _$attributes_307; -_$colorscale_254.handleDefaults = _$colorScaleDefaults_249; +_$colorscale_316.handleDefaults = _$colorScaleDefaults_311; -_$colorscale_254.calc = _$calc_246; +_$colorscale_316.calc = _$calc_308; -_$colorscale_254.hasColorscale = _$hasColorscale_253; +_$colorscale_316.hasColorscale = _$hasColorscale_315; -_$colorscale_254.isValidScale = _$isValidScale_255; +_$colorscale_316.isValidScale = _$isValidScale_317; -_$colorscale_254.getScale = _$getScale_252; +_$colorscale_316.getScale = _$getScale_314; -_$colorscale_254.flipScale = _$flipScale_251; +_$colorscale_316.flipScale = _$flipScale_313; -_$colorscale_254.extractScale = _$extractScale_250; +_$colorscale_316.extractScale = _$extractScale_312; -_$colorscale_254.makeColorScaleFunc = _$makeColorScaleFunc_257; +_$colorscale_316.makeColorScaleFunc = _$makeColorScaleFunc_319; /** * Copyright 2012-2018, Plotly, Inc. @@ -19757,7 +19549,7 @@ _$colorscale_254.makeColorScaleFunc = _$makeColorScaleFunc_257; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$d3_71 = require('d3'); */; /** Marker symbol definitions * users can specify markers either by number or name @@ -19767,11 +19559,11 @@ _$colorscale_254.makeColorScaleFunc = _$makeColorScaleFunc_257; * add both and you get both */ -var _$symbol_defs_265 = { +var _$symbol_defs_327 = { circle: { n: 0, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.round(r, 2); return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; } @@ -19779,22 +19571,22 @@ var _$symbol_defs_265 = { square: { n: 1, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; } }, diamond: { n: 2, f: function(r) { - var rd = _$d3_68.round(r * 1.3, 2); + var rd = _$d3_71.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z'; } }, cross: { n: 3, f: function(r) { - var rc = _$d3_68.round(r * 0.4, 2), - rc2 = _$d3_68.round(r * 1.2, 2); + var rc = _$d3_71.round(r * 0.4, 2), + rc2 = _$d3_71.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'; @@ -19803,7 +19595,7 @@ var _$symbol_defs_265 = { x: { n: 4, f: function(r) { - var rx = _$d3_68.round(r * 0.8 / Math.sqrt(2), 2), + var rx = _$d3_71.round(r * 0.8 / Math.sqrt(2), 2), ne = 'l' + rx + ',' + rx, se = 'l' + rx + ',-' + rx, sw = 'l-' + rx + ',-' + rx, @@ -19814,79 +19606,79 @@ var _$symbol_defs_265 = { 'triangle-up': { n: 5, f: function(r) { - var rt = _$d3_68.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_68.round(r / 2, 2), - rs = _$d3_68.round(r, 2); + var rt = _$d3_71.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_71.round(r / 2, 2), + rs = _$d3_71.round(r, 2); return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z'; } }, 'triangle-down': { n: 6, f: function(r) { - var rt = _$d3_68.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_68.round(r / 2, 2), - rs = _$d3_68.round(r, 2); + var rt = _$d3_71.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_71.round(r / 2, 2), + rs = _$d3_71.round(r, 2); return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z'; } }, 'triangle-left': { n: 7, f: function(r) { - var rt = _$d3_68.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_68.round(r / 2, 2), - rs = _$d3_68.round(r, 2); + var rt = _$d3_71.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_71.round(r / 2, 2), + rs = _$d3_71.round(r, 2); return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z'; } }, 'triangle-right': { n: 8, f: function(r) { - var rt = _$d3_68.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_68.round(r / 2, 2), - rs = _$d3_68.round(r, 2); + var rt = _$d3_71.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_71.round(r / 2, 2), + rs = _$d3_71.round(r, 2); return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z'; } }, 'triangle-ne': { n: 9, f: function(r) { - var r1 = _$d3_68.round(r * 0.6, 2), - r2 = _$d3_68.round(r * 1.2, 2); + var r1 = _$d3_71.round(r * 0.6, 2), + r2 = _$d3_71.round(r * 1.2, 2); return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z'; } }, 'triangle-se': { n: 10, f: function(r) { - var r1 = _$d3_68.round(r * 0.6, 2), - r2 = _$d3_68.round(r * 1.2, 2); + var r1 = _$d3_71.round(r * 0.6, 2), + r2 = _$d3_71.round(r * 1.2, 2); return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z'; } }, 'triangle-sw': { n: 11, f: function(r) { - var r1 = _$d3_68.round(r * 0.6, 2), - r2 = _$d3_68.round(r * 1.2, 2); + var r1 = _$d3_71.round(r * 0.6, 2), + r2 = _$d3_71.round(r * 1.2, 2); return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z'; } }, 'triangle-nw': { n: 12, f: function(r) { - var r1 = _$d3_68.round(r * 0.6, 2), - r2 = _$d3_68.round(r * 1.2, 2); + var r1 = _$d3_71.round(r * 0.6, 2), + r2 = _$d3_71.round(r * 1.2, 2); return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z'; } }, pentagon: { n: 13, f: function(r) { - var x1 = _$d3_68.round(r * 0.951, 2), - x2 = _$d3_68.round(r * 0.588, 2), - y0 = _$d3_68.round(-r, 2), - y1 = _$d3_68.round(r * -0.309, 2), - y2 = _$d3_68.round(r * 0.809, 2); + var x1 = _$d3_71.round(r * 0.951, 2), + x2 = _$d3_71.round(r * 0.588, 2), + y0 = _$d3_71.round(-r, 2), + y1 = _$d3_71.round(r * -0.309, 2), + y2 = _$d3_71.round(r * 0.809, 2); return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 + 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z'; } @@ -19894,9 +19686,9 @@ var _$symbol_defs_265 = { hexagon: { n: 14, f: function(r) { - var y0 = _$d3_68.round(r, 2), - y1 = _$d3_68.round(r / 2, 2), - x = _$d3_68.round(r * Math.sqrt(3) / 2, 2); + var y0 = _$d3_71.round(r, 2), + y1 = _$d3_71.round(r / 2, 2), + x = _$d3_71.round(r * Math.sqrt(3) / 2, 2); return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 + 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z'; } @@ -19904,9 +19696,9 @@ var _$symbol_defs_265 = { hexagon2: { n: 15, f: function(r) { - var x0 = _$d3_68.round(r, 2), - x1 = _$d3_68.round(r / 2, 2), - y = _$d3_68.round(r * Math.sqrt(3) / 2, 2); + var x0 = _$d3_71.round(r, 2), + x1 = _$d3_71.round(r / 2, 2), + y = _$d3_71.round(r * Math.sqrt(3) / 2, 2); return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 + ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z'; } @@ -19914,8 +19706,8 @@ var _$symbol_defs_265 = { octagon: { n: 16, f: function(r) { - var a = _$d3_68.round(r * 0.924, 2), - b = _$d3_68.round(r * 0.383, 2); + var a = _$d3_71.round(r * 0.924, 2), + b = _$d3_71.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'; } @@ -19924,15 +19716,15 @@ var _$symbol_defs_265 = { n: 17, f: function(r) { var rs = r * 1.4, - x1 = _$d3_68.round(rs * 0.225, 2), - x2 = _$d3_68.round(rs * 0.951, 2), - x3 = _$d3_68.round(rs * 0.363, 2), - x4 = _$d3_68.round(rs * 0.588, 2), - y0 = _$d3_68.round(-rs, 2), - y1 = _$d3_68.round(rs * -0.309, 2), - y3 = _$d3_68.round(rs * 0.118, 2), - y4 = _$d3_68.round(rs * 0.809, 2), - y5 = _$d3_68.round(rs * 0.382, 2); + x1 = _$d3_71.round(rs * 0.225, 2), + x2 = _$d3_71.round(rs * 0.951, 2), + x3 = _$d3_71.round(rs * 0.363, 2), + x4 = _$d3_71.round(rs * 0.588, 2), + y0 = _$d3_71.round(-rs, 2), + y1 = _$d3_71.round(rs * -0.309, 2), + y3 = _$d3_71.round(rs * 0.118, 2), + y4 = _$d3_71.round(rs * 0.809, 2), + y5 = _$d3_71.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 + @@ -19942,9 +19734,9 @@ var _$symbol_defs_265 = { hexagram: { n: 18, f: function(r) { - var y = _$d3_68.round(r * 0.66, 2), - x1 = _$d3_68.round(r * 0.38, 2), - x2 = _$d3_68.round(r * 0.76, 2); + var y = _$d3_71.round(r * 0.66, 2), + x1 = _$d3_71.round(r * 0.38, 2), + x2 = _$d3_71.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 + @@ -19954,10 +19746,10 @@ var _$symbol_defs_265 = { 'star-triangle-up': { n: 19, f: function(r) { - var x = _$d3_68.round(r * Math.sqrt(3) * 0.8, 2), - y1 = _$d3_68.round(r * 0.8, 2), - y2 = _$d3_68.round(r * 1.6, 2), - rc = _$d3_68.round(r * 4, 2), + var x = _$d3_71.round(r * Math.sqrt(3) * 0.8, 2), + y1 = _$d3_71.round(r * 0.8, 2), + y2 = _$d3_71.round(r * 1.6, 2), + rc = _$d3_71.round(r * 4, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 + aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z'; @@ -19966,10 +19758,10 @@ var _$symbol_defs_265 = { 'star-triangle-down': { n: 20, f: function(r) { - var x = _$d3_68.round(r * Math.sqrt(3) * 0.8, 2), - y1 = _$d3_68.round(r * 0.8, 2), - y2 = _$d3_68.round(r * 1.6, 2), - rc = _$d3_68.round(r * 4, 2), + var x = _$d3_71.round(r * Math.sqrt(3) * 0.8, 2), + y1 = _$d3_71.round(r * 0.8, 2), + y2 = _$d3_71.round(r * 1.6, 2), + rc = _$d3_71.round(r * 4, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 + aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z'; @@ -19978,8 +19770,8 @@ var _$symbol_defs_265 = { 'star-square': { n: 21, f: function(r) { - var rp = _$d3_68.round(r * 1.1, 2), - rc = _$d3_68.round(r * 2, 2), + var rp = _$d3_71.round(r * 1.1, 2), + rc = _$d3_71.round(r * 2, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp + aPart + rp + ',' + rp + aPart + rp + ',-' + rp + @@ -19989,8 +19781,8 @@ var _$symbol_defs_265 = { 'star-diamond': { n: 22, f: function(r) { - var rp = _$d3_68.round(r * 1.4, 2), - rc = _$d3_68.round(r * 1.9, 2), + var rp = _$d3_71.round(r * 1.4, 2), + rc = _$d3_71.round(r * 1.9, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',0' + aPart + '0,' + rp + aPart + rp + ',0' + aPart + '0,-' + rp + @@ -20000,23 +19792,23 @@ var _$symbol_defs_265 = { 'diamond-tall': { n: 23, f: function(r) { - var x = _$d3_68.round(r * 0.7, 2), - y = _$d3_68.round(r * 1.4, 2); + var x = _$d3_71.round(r * 0.7, 2), + y = _$d3_71.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_68.round(r * 1.4, 2), - y = _$d3_68.round(r * 0.7, 2); + var x = _$d3_71.round(r * 1.4, 2), + y = _$d3_71.round(r * 0.7, 2); return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; } }, hourglass: { n: 25, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z'; }, noDot: true @@ -20024,7 +19816,7 @@ var _$symbol_defs_265 = { bowtie: { n: 26, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.round(r, 2); return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z'; }, noDot: true @@ -20032,7 +19824,7 @@ var _$symbol_defs_265 = { 'circle-cross': { n: 27, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.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'; @@ -20043,8 +19835,8 @@ var _$symbol_defs_265 = { 'circle-x': { n: 28, f: function(r) { - var rs = _$d3_68.round(r, 2), - rc = _$d3_68.round(r / Math.sqrt(2), 2); + var rs = _$d3_71.round(r, 2), + rc = _$d3_71.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 + @@ -20056,7 +19848,7 @@ var _$symbol_defs_265 = { 'square-cross': { n: 29, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.round(r, 2); return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; }, @@ -20066,7 +19858,7 @@ var _$symbol_defs_265 = { 'square-x': { n: 30, f: function(r) { - var rs = _$d3_68.round(r, 2); + var rs = _$d3_71.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'; @@ -20077,7 +19869,7 @@ var _$symbol_defs_265 = { 'diamond-cross': { n: 31, f: function(r) { - var rd = _$d3_68.round(r * 1.3, 2); + var rd = _$d3_71.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + 'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd; }, @@ -20087,8 +19879,8 @@ var _$symbol_defs_265 = { 'diamond-x': { n: 32, f: function(r) { - var rd = _$d3_68.round(r * 1.3, 2), - r2 = _$d3_68.round(r * 0.65, 2); + var rd = _$d3_71.round(r * 1.3, 2), + r2 = _$d3_71.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; @@ -20099,7 +19891,7 @@ var _$symbol_defs_265 = { 'cross-thin': { n: 33, f: function(r) { - var rc = _$d3_68.round(r * 1.4, 2); + var rc = _$d3_71.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc; }, needLine: true, @@ -20109,7 +19901,7 @@ var _$symbol_defs_265 = { 'x-thin': { n: 34, f: function(r) { - var rx = _$d3_68.round(r, 2); + var rx = _$d3_71.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx + 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, @@ -20120,8 +19912,8 @@ var _$symbol_defs_265 = { asterisk: { n: 35, f: function(r) { - var rc = _$d3_68.round(r * 1.2, 2); - var rs = _$d3_68.round(r * 0.85, 2); + var rc = _$d3_71.round(r * 1.2, 2); + var rs = _$d3_71.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; @@ -20133,8 +19925,8 @@ var _$symbol_defs_265 = { hash: { n: 36, f: function(r) { - var r1 = _$d3_68.round(r / 2, 2), - r2 = _$d3_68.round(r, 2); + var r1 = _$d3_71.round(r / 2, 2), + r2 = _$d3_71.round(r, 2); return 'M' + r1 + ',' + r2 + 'V-' + r2 + 'm-' + r2 + ',0V' + r2 + 'M' + r2 + ',' + r1 + 'H-' + r2 + @@ -20146,9 +19938,9 @@ var _$symbol_defs_265 = { 'y-up': { n: 37, f: function(r) { - var x = _$d3_68.round(r * 1.2, 2), - y0 = _$d3_68.round(r * 1.6, 2), - y1 = _$d3_68.round(r * 0.8, 2); + var x = _$d3_71.round(r * 1.2, 2), + y0 = _$d3_71.round(r * 1.6, 2), + y1 = _$d3_71.round(r * 0.8, 2); return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0'; }, needLine: true, @@ -20158,9 +19950,9 @@ var _$symbol_defs_265 = { 'y-down': { n: 38, f: function(r) { - var x = _$d3_68.round(r * 1.2, 2), - y0 = _$d3_68.round(r * 1.6, 2), - y1 = _$d3_68.round(r * 0.8, 2); + var x = _$d3_71.round(r * 1.2, 2), + y0 = _$d3_71.round(r * 1.6, 2), + y1 = _$d3_71.round(r * 0.8, 2); return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0'; }, needLine: true, @@ -20170,9 +19962,9 @@ var _$symbol_defs_265 = { 'y-left': { n: 39, f: function(r) { - var y = _$d3_68.round(r * 1.2, 2), - x0 = _$d3_68.round(r * 1.6, 2), - x1 = _$d3_68.round(r * 0.8, 2); + var y = _$d3_71.round(r * 1.2, 2), + x0 = _$d3_71.round(r * 1.6, 2), + x1 = _$d3_71.round(r * 0.8, 2); return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0'; }, needLine: true, @@ -20182,9 +19974,9 @@ var _$symbol_defs_265 = { 'y-right': { n: 40, f: function(r) { - var y = _$d3_68.round(r * 1.2, 2), - x0 = _$d3_68.round(r * 1.6, 2), - x1 = _$d3_68.round(r * 0.8, 2); + var y = _$d3_71.round(r * 1.2, 2), + x0 = _$d3_71.round(r * 1.6, 2), + x1 = _$d3_71.round(r * 0.8, 2); return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0'; }, needLine: true, @@ -20194,7 +19986,7 @@ var _$symbol_defs_265 = { 'line-ew': { n: 41, f: function(r) { - var rc = _$d3_68.round(r * 1.4, 2); + var rc = _$d3_71.round(r * 1.4, 2); return 'M' + rc + ',0H-' + rc; }, needLine: true, @@ -20204,7 +19996,7 @@ var _$symbol_defs_265 = { 'line-ns': { n: 42, f: function(r) { - var rc = _$d3_68.round(r * 1.4, 2); + var rc = _$d3_71.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc; }, needLine: true, @@ -20214,7 +20006,7 @@ var _$symbol_defs_265 = { 'line-ne': { n: 43, f: function(r) { - var rx = _$d3_68.round(r, 2); + var rx = _$d3_71.round(r, 2); return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, needLine: true, @@ -20224,7 +20016,7 @@ var _$symbol_defs_265 = { 'line-nw': { n: 44, f: function(r) { - var rx = _$d3_68.round(r, 2); + var rx = _$d3_71.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx; }, needLine: true, @@ -20244,7 +20036,7 @@ var _$symbol_defs_265 = { 'use strict'; // fraction of some size to get to a named position -var _$alignment_339 = { +var _$alignment_401 = { // from bottom left: this is the origin of our paper-reference // positioning system FROM_BL: { @@ -20306,7 +20098,7 @@ var _$alignment_339 = { // N.B. HTML entities are listed without the leading '&' and trailing ';' // https://www.freeformatter.com/html-entities.html -var _$string_mappings_344 = { +var _$string_mappings_405 = { entityToUnicode: { 'mu': 'μ', '#956': 'μ', @@ -20334,7 +20126,7 @@ var _$string_mappings_344 = { } }; -var _$svg_text_utils_386 = {}; +var _$svg_text_utils_449 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -20348,12 +20140,12 @@ var _$svg_text_utils_386 = {}; /* global MathJax:false */ -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$d3_71 = require('d3'); */; -/* removed: var _$lib_363 = require('../lib'); */; -/* removed: var _$xmlns_namespaces_345 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$string_mappings_344 = require('../constants/string_mappings'); */; -var LINE_SPACING = _$alignment_339.LINE_SPACING; +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$xmlns_namespaces_406 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$string_mappings_405 = require('../constants/string_mappings'); */; +var LINE_SPACING = _$alignment_401.LINE_SPACING; // text converter @@ -20363,7 +20155,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_386.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_449.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) @@ -20372,7 +20164,7 @@ _$svg_text_utils_386.convertToTspans = function(_context, gd, _callback) { (typeof MathJax !== 'undefined') && str.match(FIND_TEX); - var parent = _$d3_68.select(_context.node().parentNode); + var parent = _$d3_71.select(_context.node().parentNode); if(parent.empty()) return; var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text'; svgClass += '-math'; @@ -20406,7 +20198,7 @@ _$svg_text_utils_386.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_386.positionText(_context); + _$svg_text_utils_449.positionText(_context); if(_callback) _callback.call(_context); } @@ -20501,18 +20293,18 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_363.randstr([], 64); - var tmpDiv = _$d3_68.select('body').append('div') + var randomID = 'math-output-' + _$lib_425.randstr([], 64); + var tmpDiv = _$d3_71.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) .style({'font-size': _config.fontSize + 'px'}) .text(cleanEscapesForTex(_texString)); MathJax.Hub.Queue(['Typeset', MathJax.Hub, tmpDiv.node()], function() { - var glyphDefs = _$d3_68.select('body').select('#MathJax_SVG_glyphs'); + var glyphDefs = _$d3_71.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_363.log('There was an error in the tex syntax.', _texString); + _$lib_425.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -20560,10 +20352,10 @@ var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':']; var STRIP_TAGS = new RegExp(']*)?/?>', 'g'); -var ENTITY_TO_UNICODE = Object.keys(_$string_mappings_344.entityToUnicode).map(function(k) { +var ENTITY_TO_UNICODE = Object.keys(_$string_mappings_405.entityToUnicode).map(function(k) { return { regExp: new RegExp('&' + k + ';', 'g'), - sub: _$string_mappings_344.entityToUnicode[k] + sub: _$string_mappings_405.entityToUnicode[k] }; }); @@ -20607,7 +20399,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_386.plainText = function(_str) { +_$svg_text_utils_449.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -20661,8 +20453,8 @@ function buildSVGText(containerNode, str) { function newLine() { currentLine++; - var lineNode = document.createElementNS(_$xmlns_namespaces_345.svg, 'tspan'); - _$d3_68.select(lineNode).attr({ + var lineNode = document.createElementNS(_$xmlns_namespaces_406.svg, 'tspan'); + _$d3_71.select(lineNode).attr({ class: 'line', dy: (currentLine * LINE_SPACING) + 'em' }); @@ -20708,15 +20500,15 @@ function buildSVGText(containerNode, str) { if(nodeSpec.style) nodeAttrs.style = nodeSpec.style; - var newNode = document.createElementNS(_$xmlns_namespaces_345.svg, nodeType); + var newNode = document.createElementNS(_$xmlns_namespaces_406.svg, nodeType); if(type === 'sup' || type === 'sub') { addTextNode(currentNode, ZERO_WIDTH_SPACE); currentNode.appendChild(newNode); - var resetter = document.createElementNS(_$xmlns_namespaces_345.svg, 'tspan'); + var resetter = document.createElementNS(_$xmlns_namespaces_406.svg, 'tspan'); addTextNode(resetter, ZERO_WIDTH_SPACE); - _$d3_68.select(resetter).attr('dy', RESET_DY[type]); + _$d3_71.select(resetter).attr('dy', RESET_DY[type]); nodeAttrs.dy = SHIFT_DY[type]; currentNode.appendChild(newNode); @@ -20726,7 +20518,7 @@ function buildSVGText(containerNode, str) { currentNode.appendChild(newNode); } - _$d3_68.select(newNode).attr(nodeAttrs); + _$d3_71.select(newNode).attr(nodeAttrs); currentNode = nodeSpec.node = newNode; nodeStack.push(nodeSpec); @@ -20740,14 +20532,14 @@ function buildSVGText(containerNode, str) { // 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_363.log('Ignoring unexpected end tag .', str); + _$lib_425.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_363.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_425.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -20806,7 +20598,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -20821,13 +20616,13 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_386.lineCount = function lineCount(s) { +_$svg_text_utils_449.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_386.positionText = function positionText(s, x, y) { +_$svg_text_utils_449.positionText = function positionText(s, x, y) { return s.each(function() { - var text = _$d3_68.select(this); + var text = _$d3_71.select(this); function setOrGet(attr, val) { if(val === undefined) { @@ -20901,10 +20696,10 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_386.makeEditable = function(context, options) { +_$svg_text_utils_449.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; - var dispatch = _$d3_68.dispatch('edit', 'input', 'cancel'); + var dispatch = _$d3_71.dispatch('edit', 'input', 'cancel'); var handlerElement = _delegate || context; context.style({'pointer-events': _delegate ? 'none' : 'all'}); @@ -20920,7 +20715,7 @@ _$svg_text_utils_386.makeEditable = function(context, options) { if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group'; else mathjaxClass = '[class*=-math-group]'; if(mathjaxClass) { - _$d3_68.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); + _$d3_71.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); } } @@ -20935,7 +20730,7 @@ _$svg_text_utils_386.makeEditable = function(context, options) { } function appendEditable() { - var plotDiv = _$d3_68.select(gd); + var plotDiv = _$d3_71.select(gd); var container = plotDiv.select('.svg-container'); var div = container.append('div'); var cStyle = context.node().style; @@ -20961,31 +20756,31 @@ _$svg_text_utils_386.makeEditable = function(context, options) { gd._editing = false; context.text(this.textContent) .style({opacity: 1}); - var svgClass = _$d3_68.select(this).attr('class'), + var svgClass = _$d3_71.select(this).attr('class'), mathjaxClass; if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group'; else mathjaxClass = '[class*=-math-group]'; if(mathjaxClass) { - _$d3_68.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); + _$d3_71.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); } var text = this.textContent; - _$d3_68.select(this).transition().duration(0).remove(); - _$d3_68.select(document).on('mouseup', null); + _$d3_71.select(this).transition().duration(0).remove(); + _$d3_71.select(document).on('mouseup', null); dispatch.edit.call(context, text); }) .on('focus', function() { var editDiv = this; gd._editing = true; - _$d3_68.select(document).on('mouseup', function() { - if(_$d3_68.event.target === editDiv) return false; + _$d3_71.select(document).on('mouseup', function() { + if(_$d3_71.event.target === editDiv) return false; if(document.activeElement === div.node()) div.node().blur(); }); }) .on('keyup', function() { - if(_$d3_68.event.which === 27) { + if(_$d3_71.event.which === 27) { gd._editing = false; context.style({opacity: 1}); - _$d3_68.select(this) + _$d3_71.select(this) .style({opacity: 0}) .on('blur', function() { return false; }) .transition().remove(); @@ -20993,11 +20788,11 @@ _$svg_text_utils_386.makeEditable = function(context, options) { } else { dispatch.input.call(context, this.textContent); - _$d3_68.select(this).call(alignHTMLWith(context, container, options)); + _$d3_71.select(this).call(alignHTMLWith(context, container, options)); } }) .on('keydown', function() { - if(_$d3_68.event.which === 13) this.blur(); + if(_$d3_71.event.which === 13) this.blur(); }) .call(selectElementContents); } @@ -21005,7 +20800,7 @@ _$svg_text_utils_386.makeEditable = function(context, options) { if(options.immediate) handleClick(); else handlerElement.on('click', handleClick); - return _$d3_68.rebind(context, dispatch, 'on'); + return _$d3_71.rebind(context, dispatch, 'on'); }; /** @@ -21019,12 +20814,12 @@ _$svg_text_utils_386.makeEditable = function(context, options) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_529 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_593 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -21043,7 +20838,7 @@ var _$makeBubbleSizeFn_529 = function makeBubbleSizeFn(trace) { var baseSize = baseFn(v / 2); // don't show non-numeric and negative sizes - return (_$fastIsnumeric_78(baseSize) && (baseSize > 0)) ? + return (_$fastIsnumeric_135(baseSize) && (baseSize > 0)) ? Math.max(baseSize, sizeMin) : 0; }; @@ -21060,17 +20855,20 @@ var _$makeBubbleSizeFn_529 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; -var _$subtypes_534 = { +var _$subtypes_598 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -21079,12 +20877,12 @@ var _$subtypes_534 = { }, isBubble: function(trace) { - return _$lib_363.isPlainObject(trace.marker) && - _$lib_363.isArrayOrTypedArray(trace.marker.size); + return _$lib_425.isPlainObject(trace.marker) && + _$lib_425.isArrayOrTypedArray(trace.marker.size); } }; -var _$drawing_264 = {}; +var _$drawing_326 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21096,25 +20894,25 @@ var _$drawing_264 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$colorscale_254 = require('../colorscale'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$colorscale_316 = require('../colorscale'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; -/* removed: var _$xmlns_namespaces_345 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$alignment_339 = require('../../constants/alignment'); */; -var __LINE_SPACING_264 = _$alignment_339.LINE_SPACING; -var __DESELECTDIM_264 = _$interactions_342.DESELECTDIM; +/* removed: var _$xmlns_namespaces_406 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$alignment_401 = require('../../constants/alignment'); */; +var __LINE_SPACING_326 = _$alignment_401.LINE_SPACING; +var __DESELECTDIM_326 = _$interactions_403.DESELECTDIM; -/* removed: var _$subtypes_534 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_529 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_598 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_593 = require('../../traces/scatter/make_bubble_size_func'); */; -var drawing = _$drawing_264 = {}; +var drawing = _$drawing_326 = {}; // ----------------------------------------------------- // styling functions for plot elements @@ -21122,14 +20920,14 @@ var drawing = _$drawing_264 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_363.isPlainObject(family)) { + if(_$lib_425.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_239.fill, color); + if(color) s.call(_$color_301.fill, color); }; /* @@ -21159,7 +20957,7 @@ drawing.translatePoint = function(d, sel, xa, ya) { var x = xa.c2p(d.x); var y = ya.c2p(d.y); - if(_$fastIsnumeric_78(x) && _$fastIsnumeric_78(y) && sel.node()) { + if(_$fastIsnumeric_135(x) && _$fastIsnumeric_135(y) && sel.node()) { // for multiline text this works better if(sel.node().nodeName === 'text') { sel.attr('x', x).attr('y', y); @@ -21175,7 +20973,7 @@ drawing.translatePoint = function(d, sel, xa, ya) { drawing.translatePoints = function(s, xa, ya) { s.each(function(d) { - var sel = _$d3_68.select(this); + var sel = _$d3_71.select(this); drawing.translatePoint(d, sel, xa, ya); }); }; @@ -21201,7 +20999,7 @@ drawing.hideOutsideRangePoints = function(traceGroups, subplot, selector) { var ycalendar = trace.ycalendar; traceGroups.selectAll(selector).each(function(d) { - drawing.hideOutsideRangePoint(d, _$d3_68.select(this), xa, ya, xcalendar, ycalendar); + drawing.hideOutsideRangePoint(d, _$d3_71.select(this), xa, ya, xcalendar, ycalendar); }); }); }; @@ -21210,7 +21008,7 @@ 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 || !_$fastIsnumeric_78(lineWidth)) return dflt || 0; + if(!lineWidth || !_$fastIsnumeric_135(lineWidth)) return dflt || 0; // but not for static plots - these don't get antialiased anyway. if(gd._context.staticPlot) return lineWidth; @@ -21225,7 +21023,7 @@ drawing.singleLineStyle = function(d, s, lw, lc, ld) { lw1 = lw || line.width||0, dash = ld || line.dash || ''; - _$color_239.stroke(s, lc || line.color); + _$color_301.stroke(s, lc || line.color); drawing.dashLine(s, dash, lw1); }; @@ -21236,8 +21034,8 @@ drawing.lineGroupStyle = function(s, lw, lc, ld) { lw1 = lw || line.width||0, dash = ld || line.dash || ''; - _$d3_68.select(this) - .call(_$color_239.stroke, lc || line.color) + _$d3_71.select(this) + .call(_$color_301.stroke, lc || line.color) .call(drawing.dashLine, dash, lw1); }); }; @@ -21274,29 +21072,29 @@ drawing.dashStyle = function(dash, lineWidth) { // Same as fillGroupStyle, except in this case the selection may be a transition drawing.singleFillStyle = function(sel) { - var node = _$d3_68.select(sel.node()); + var node = _$d3_71.select(sel.node()); var data = node.data(); var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor; if(fillcolor) { - sel.call(_$color_239.fill, fillcolor); + sel.call(_$color_301.fill, fillcolor); } }; drawing.fillGroupStyle = function(s) { s.style('stroke-width', 0) .each(function(d) { - var shape = _$d3_68.select(this); + var shape = _$d3_71.select(this); try { - shape.call(_$color_239.fill, d[0].trace.fillcolor); + shape.call(_$color_301.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_363.error(e, s); + _$lib_425.error(e, s); shape.remove(); } }); }; -/* removed: var _$symbol_defs_265 = require('./symbol_defs'); */; +/* removed: var _$symbol_defs_327 = require('./symbol_defs'); */; drawing.symbolNames = []; drawing.symbolFuncs = []; @@ -21305,8 +21103,8 @@ drawing.symbolNoDot = {}; drawing.symbolNoFill = {}; drawing.symbolList = []; -Object.keys(_$symbol_defs_265).forEach(function(k) { - var symDef = _$symbol_defs_265[k]; +Object.keys(_$symbol_defs_327).forEach(function(k) { + var symDef = _$symbol_defs_327[k]; drawing.symbolList = drawing.symbolList.concat( [symDef.n, k, symDef.n + 100, k + '-open']); drawing.symbolNames[symDef.n] = k; @@ -21353,8 +21151,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_451.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_529(trace); + if(_$registry_514.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_593(trace); sel.attr('d', function(d) { var r; @@ -21363,7 +21161,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_534.isBubble(trace) ? + r = _$subtypes_598.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -21403,11 +21201,11 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_363.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_239.defaultLine; + else if(_$lib_425.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_301.defaultLine; else lineColor = markerLine.color; - if(_$lib_363.isArrayOrTypedArray(marker.color)) { - fillColor = _$color_239.defaultLine; + if(_$lib_425.isArrayOrTypedArray(marker.color)) { + fillColor = _$color_301.defaultLine; perPointGradient = true; } @@ -21418,7 +21216,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.om) { // open markers can't have zero linewidth, default to 1px, // and use fill color as stroke color - sel.call(_$color_239.stroke, fillColor) + sel.call(_$color_301.stroke, fillColor) .style({ 'stroke-width': (lineWidth || 1) + 'px', fill: 'none' @@ -21444,11 +21242,11 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL sel.call(drawing.gradient, gd, gradientID, gradientType, fillColor, gradientColor); } else { - sel.call(_$color_239.fill, fillColor); + sel.call(_$color_301.fill, fillColor); } if(lineWidth) { - sel.call(_$color_239.stroke, lineColor); + sel.call(_$color_301.stroke, lineColor); } } } @@ -21459,31 +21257,31 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_363.identity); + .data([type + color1 + color2], _$lib_425.identity); gradient.exit().remove(); gradient.enter() .append(type === 'radial' ? 'radialGradient' : 'linearGradient') .each(function() { - var el = _$d3_68.select(this); + var el = _$d3_71.select(this); if(type === 'horizontal') el.attr(HORZGRADIENT); else if(type === 'vertical') el.attr(VERTGRADIENT); el.attr('id', gradientID); - var tc1 = _$tinycolor_201(color1); - var tc2 = _$tinycolor_201(color2); + var tc1 = _$tinycolor_263(color1); + var tc2 = _$tinycolor_263(color2); el.append('stop').attr({ offset: '0%', - 'stop-color': _$color_239.tinyRGB(tc2), + 'stop-color': _$color_301.tinyRGB(tc2), 'stop-opacity': tc2.getAlpha() }); el.append('stop').attr({ offset: '100%', - 'stop-color': _$color_239.tinyRGB(tc1), + 'stop-color': _$color_301.tinyRGB(tc1), 'stop-opacity': tc1.getAlpha() }); }); @@ -21502,9 +21300,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_425.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -21524,7 +21320,7 @@ drawing.pointStyle = function(s, trace, gd) { var lineScale = drawing.tryColorscale(marker, 'line'); s.each(function(d) { - drawing.singlePointStyle(d, _$d3_68.select(this), trace, markerScale, lineScale, gd); + drawing.singlePointStyle(d, _$d3_71.select(this), trace, markerScale, lineScale, gd); }); }; @@ -21553,7 +21349,7 @@ drawing.makeSelectedPointStyleFns = function(trace) { if(smoIsDefined) return smo; } else { if(usmoIsDefined) return usmo; - return __DESELECTDIM_264 * (dmoIsDefined ? dmo : mo); + return __DESELECTDIM_326 * (dmoIsDefined ? dmo : mo); } } }; @@ -21597,22 +21393,22 @@ drawing.selectedPointStyle = function(s, trace) { var marker = trace.marker || {}; s.each(function(d) { - var pt = _$d3_68.select(this); + var pt = _$d3_71.select(this); var mo2 = fns.opacityFn(d); if(mo2 !== undefined) pt.style('opacity', mo2); }); if(fns.colorFn) { s.each(function(d) { - var pt = _$d3_68.select(this); + var pt = _$d3_71.select(this); var mc2 = fns.colorFn(d); - if(mc2) _$color_239.fill(pt, mc2); + if(mc2) _$color_301.fill(pt, mc2); }); } - if(_$registry_451.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_514.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { - var pt = _$d3_68.select(this); + var pt = _$d3_71.select(this); var mx = d.mx || marker.symbol || 0; var mrc2 = fns.sizeFn(d); @@ -21625,22 +21421,22 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_363.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_425.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_363.isArrayOrTypedArray(colorArray)) { - return _$colorscale_254.makeColorScaleFunc( - _$colorscale_254.extractScale(scl, cont.cmin, cont.cmax) + if(scl && _$lib_425.isArrayOrTypedArray(colorArray)) { + return _$colorscale_316.makeColorScaleFunc( + _$colorscale_316.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_363.identity; + else return _$lib_425.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; function textPointPosition(s, textPosition, fontSize, markerRadius) { - var group = _$d3_68.select(s.node().parentNode); + var group = _$d3_71.select(s.node().parentNode); var v = textPosition.indexOf('top') !== -1 ? 'top' : @@ -21654,7 +21450,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_386.lineCount(s) - 1) * __LINE_SPACING_264 + 1; + var numLines = (_$svg_text_utils_449.lineCount(s) - 1) * __LINE_SPACING_326 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -21666,14 +21462,14 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { function extracTextFontSize(d, trace) { var fontSize = d.ts || trace.textfont.size; - return (_$fastIsnumeric_78(fontSize) && fontSize > 0) ? fontSize : 0; + return (_$fastIsnumeric_135(fontSize) && fontSize > 0) ? fontSize : 0; } // draw text at points drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { - var p = _$d3_68.select(this); - var text = _$lib_363.extractOption(d, trace, 'tx', 'text'); + var p = _$d3_71.select(this); + var text = _$lib_425.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -21688,7 +21484,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_386.convertToTspans, gd) + .call(_$svg_text_utils_449.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -21700,7 +21496,7 @@ drawing.selectedTextStyle = function(s, trace) { var unselectedAttrs = trace.unselected || {}; s.each(function(d) { - var tx = _$d3_68.select(this); + var tx = _$d3_71.select(this); var tc = d.tc || trace.textfont.color; var tp = d.tp || trace.textposition; var fontSize = extracTextFontSize(d, trace); @@ -21712,10 +21508,10 @@ drawing.selectedTextStyle = function(s, trace) { if(stc) tc2 = stc; } else { if(utc) tc2 = utc; - else if(!stc) tc2 = _$color_239.addOpacity(tc, __DESELECTDIM_264); + else if(!stc) tc2 = _$color_301.addOpacity(tc, __DESELECTDIM_326); } - if(tc2) _$color_239.fill(tx, tc2); + if(tc2) _$color_301.fill(tx, tc2); textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc); }); }; @@ -21772,11 +21568,11 @@ function makeTangent(prevpt, thispt, nextpt, smoothness) { denom2 = 3 * d1a * (d1a + d2a); return [ [ - _$d3_68.round(thispt[0] + (denom1 && numx / denom1), 2), - _$d3_68.round(thispt[1] + (denom1 && numy / denom1), 2) + _$d3_71.round(thispt[0] + (denom1 && numx / denom1), 2), + _$d3_71.round(thispt[1] + (denom1 && numy / denom1), 2) ], [ - _$d3_68.round(thispt[0] - (denom2 && numx / denom2), 2), - _$d3_68.round(thispt[1] - (denom2 && numy / denom2), 2) + _$d3_71.round(thispt[0] - (denom2 && numx / denom2), 2), + _$d3_71.round(thispt[1] - (denom2 && numy / denom2), 2) ] ]; } @@ -21785,27 +21581,27 @@ function makeTangent(prevpt, thispt, nextpt, smoothness) { // with the given step shape var STEPPATH = { hv: function(p0, p1) { - return 'H' + _$d3_68.round(p1[0], 2) + 'V' + _$d3_68.round(p1[1], 2); + return 'H' + _$d3_71.round(p1[0], 2) + 'V' + _$d3_71.round(p1[1], 2); }, vh: function(p0, p1) { - return 'V' + _$d3_68.round(p1[1], 2) + 'H' + _$d3_68.round(p1[0], 2); + return 'V' + _$d3_71.round(p1[1], 2) + 'H' + _$d3_71.round(p1[0], 2); }, hvh: function(p0, p1) { - return 'H' + _$d3_68.round((p0[0] + p1[0]) / 2, 2) + 'V' + - _$d3_68.round(p1[1], 2) + 'H' + _$d3_68.round(p1[0], 2); + return 'H' + _$d3_71.round((p0[0] + p1[0]) / 2, 2) + 'V' + + _$d3_71.round(p1[1], 2) + 'H' + _$d3_71.round(p1[0], 2); }, vhv: function(p0, p1) { - return 'V' + _$d3_68.round((p0[1] + p1[1]) / 2, 2) + 'H' + - _$d3_68.round(p1[0], 2) + 'V' + _$d3_68.round(p1[1], 2); + return 'V' + _$d3_71.round((p0[1] + p1[1]) / 2, 2) + 'H' + + _$d3_71.round(p1[0], 2) + 'V' + _$d3_71.round(p1[1], 2); } }; var STEPLINEAR = function(p0, p1) { - return 'L' + _$d3_68.round(p1[0], 2) + ',' + _$d3_68.round(p1[1], 2); + return 'L' + _$d3_71.round(p1[0], 2) + ',' + _$d3_71.round(p1[1], 2); }; drawing.steps = function(shape) { var onestep = STEPPATH[shape] || STEPLINEAR; return function(pts) { - var path = 'M' + _$d3_68.round(pts[0][0], 2) + ',' + _$d3_68.round(pts[0][1], 2); + var path = 'M' + _$d3_71.round(pts[0][0], 2) + ',' + _$d3_71.round(pts[0][1], 2); for(var i = 1; i < pts.length; i++) { path += onestep(pts[i - 1], pts[i]); } @@ -21816,33 +21612,28 @@ drawing.steps = function(shape) { // 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 = _$d3_68.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_345.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_425.ensureSingleById(_$d3_71.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_406.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_425.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; @@ -21887,7 +21678,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_363.extendFlat({}, out); + if(out) return _$lib_425.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -21931,7 +21722,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_363.extendFlat({}, out); + if(out) return _$lib_425.extendFlat({}, out); } } var testNode, tester; @@ -21947,9 +21738,9 @@ drawing.bBox = function(node, inTester, hash) { } // standardize its position (and newline tspans if any) - _$d3_68.select(testNode) + _$d3_71.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_386.positionText, 0, 0); + .call(_$svg_text_utils_449.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -21979,7 +21770,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_363.extendFlat({}, bb); + return _$lib_425.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -22004,15 +21795,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_68.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_71.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -22122,7 +21919,7 @@ var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/; drawing.setTextPointsScale = function(selection, xScale, yScale) { selection.each(function() { var transforms; - var el = _$d3_68.select(this); + var el = _$d3_71.select(this); var text = el.select('text'); if(!text.node()) return; @@ -22150,6 +21947,319 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { }); }; +var _$helpers_340 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_425 = require('../../lib'); */; + +// look for either subplot or xaxis and yaxis attributes +// does not handle splom case +_$helpers_340.getSubplot = function getSubplot(trace) { + return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +}; + +// is trace in given list of subplots? +// does handle splom case +_$helpers_340.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_340.getSubplot(trace)) !== -1; +}; + +// convenience functions for mapping all relevant axes +_$helpers_340.flat = function flat(subplots, v) { + var out = new Array(subplots.length); + for(var i = 0; i < subplots.length; i++) { + out[i] = v; + } + return out; +}; + +_$helpers_340.p2c = function p2c(axArray, v) { + var out = new Array(axArray.length); + for(var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); + } + return out; +}; + +_$helpers_340.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { + if(mode === 'closest') return dxy || _$helpers_340.quadrature(dx, dy); + return mode === 'x' ? dx : dy; +}; + +_$helpers_340.getClosest = function getClosest(cd, distfn, pointData) { + // do we already have a point number? (array mode only) + if(pointData.index !== false) { + if(pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; + } + else pointData.index = false; + } + else { + // apply the distance function to each data point + // this is the longest loop... if this bogs down, we may need + // to create pre-sorted data (by x or y), not sure how to + // do this for 'closest' + for(var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if(newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; + } + } + } + return pointData; +}; + +/* + * pseudo-distance function for hover effects on areas: inside the region + * distance is finite (`passVal`), outside it's Infinity. + * + * @param {number} v0: signed difference between the current position and the left edge + * @param {number} v1: signed difference between the current position and the right edge + * @param {number} passVal: the value to return on success + */ +_$helpers_340.inbox = function inbox(v0, v1, passVal) { + return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; +}; + +_$helpers_340.quadrature = function quadrature(dx, dy) { + return function(di) { + var x = dx(di), + y = dy(di); + return Math.sqrt(x * x + y * y); + }; +}; + +/** Fill event data point object for hover and selection. + * Invokes _module.eventData if present. + * + * N.B. note that point 'index' corresponds to input data array index + * whereas 'number' is its post-transform version. + * + * If the hovered/selected pt corresponds to an multiple input points + * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' + * are include in the event data. + * + * @param {object} pt + * @param {object} trace + * @param {object} cd + * @return {object} + */ +_$helpers_340.makeEventData = function makeEventData(pt, trace, cd) { + // hover uses 'index', select uses 'pointNumber' + var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber: pointNumber + }; + + if(trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; + + if(pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; + } else { + out.pointIndices = pointIndices; + } + } else { + out.pointIndex = pointNumber; + } + + if(trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if('xVal' in pt) out.x = pt.xVal; + else if('x' in pt) out.x = pt.x; + + if('yVal' in pt) out.y = pt.yVal; + else if('y' in pt) out.y = pt.y; + + if(pt.xa) out.xaxis = pt.xa; + if(pt.ya) out.yaxis = pt.ya; + if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; + } + + _$helpers_340.appendArrayPointValue(out, trace, pointNumber); + + return out; +}; + +/** Appends values inside array attributes corresponding to given point number + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {number|Array(number)} pointNumber : point number. May be a length-2 array + * [row, col] to dig into 2D arrays + */ +_$helpers_340.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_425.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); + + if(pointVal !== undefined) pointData[key] = pointVal; + } + } +}; + +/** + * Appends values inside array attributes corresponding to given point number array + * For use when pointData references a plot entity that arose (or potentially arose) + * from multiple points in the input data + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. + * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays + */ +_$helpers_340.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; + + if(!arrayAttrs) { + return; + } + + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + + if(pointData[key] === undefined) { + var val = _$lib_425.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); + + for(var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); + } + pointData[key] = keyVal; + } + } +}; + +var pointKeyMap = { + ids: 'id', + locations: 'location', + labels: 'label', + values: 'value', + 'marker.colors': 'color' +}; + +function getPointKey(astr) { + return pointKeyMap[astr] || astr; +} + +function getPointData(val, pointNumber) { + if(Array.isArray(pointNumber)) { + if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; + } + } else { + return val[pointNumber]; + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +// works with our CSS cursor classes (see css/_cursor.scss) +// to apply cursors to d3 single-element selections. +// omit cursor to revert to the default. +var _$setCursor_445 = function setCursor(el3, csr) { + (el3.attr('class') || '').split(' ').forEach(function(cls) { + if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); + }); + + if(csr) el3.classed('cursor-' + csr, true); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$setCursor_445 = require('./setcursor'); */; + +var STASHATTR = 'data-savedcursor'; +var NO_CURSOR = '!!'; + +/* + * works with our CSS cursor classes (see css/_cursor.scss) + * to override a previous cursor set on d3 single-element selections, + * by moving the name of the original cursor to the data-savedcursor attr. + * omit cursor to revert to the previously set value. + */ +var _$overrideCursor_436 = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if(csr) { + if(!savedCursor) { + var classes = (el3.attr('class') || '').split(' '); + for(var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if(cls.indexOf('cursor-') === 0) { + el3.attr(STASHATTR, cls.substr(7)) + .classed(cls, false); + } + } + if(!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); + } + } + _$setCursor_445(el3, csr); + } + else if(savedCursor) { + el3.attr(STASHATTR, null); + + if(savedCursor === NO_CURSOR) _$setCursor_445(el3); + else _$setCursor_445(el3, savedCursor); + } +}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22160,7 +22270,7 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -var _$animation_attributes_402 = { +var _$animation_attributes_465 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -22261,7 +22371,7 @@ var _$animation_attributes_402 = { 'use strict'; -var _$frame_attributes_435 = { +var _$frame_attributes_497 = { _isLinkedToArray: 'frames_entry', group: { @@ -22306,9 +22416,9 @@ var _$frame_attributes_435 = { 'use strict'; -/* removed: var _$attributes_245 = require('./attributes'); */; -var __extendFlat_247 = _$extend_354.extendFlat; -/* removed: var _$scales_258 = require('./scales.js'); */; +/* removed: var _$attributes_307 = require('./attributes'); */; +var __extendFlat_309 = _$extend_416.extendFlat; +/* removed: var _$scales_320 = require('./scales.js'); */; /* * Make all the attributes for a regular colorscale: @@ -22324,7 +22434,7 @@ var __extendFlat_247 = _$extend_354.extendFlat; * * @return {object} the finished attributes object */ -var _$makeColorScaleAttributes_247 = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) { +var _$makeColorScaleAttributes_309 = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) { var contextHead = context ? (context + '.') : ''; return { @@ -22335,28 +22445,28 @@ var _$makeColorScaleAttributes_247 = function makeColorScaleAttributes(context, editType: editTypeOverride || 'style', }, - colorscale: __extendFlat_247({}, _$attributes_245.colorscale, { + colorscale: __extendFlat_309({}, _$attributes_307.colorscale, { }), - cauto: __extendFlat_247({}, _$attributes_245.zauto, { + cauto: __extendFlat_309({}, _$attributes_307.zauto, { impliedEdits: {cmin: undefined, cmax: undefined}, }), - cmax: __extendFlat_247({}, _$attributes_245.zmax, { - editType: editTypeOverride || _$attributes_245.zmax.editType, + cmax: __extendFlat_309({}, _$attributes_307.zmax, { + editType: editTypeOverride || _$attributes_307.zmax.editType, impliedEdits: {cauto: false}, }), - cmin: __extendFlat_247({}, _$attributes_245.zmin, { - editType: editTypeOverride || _$attributes_245.zmin.editType, + cmin: __extendFlat_309({}, _$attributes_307.zmin, { + editType: editTypeOverride || _$attributes_307.zmin.editType, impliedEdits: {cauto: false}, }), - autocolorscale: __extendFlat_247({}, _$attributes_245.autocolorscale, { + autocolorscale: __extendFlat_309({}, _$attributes_307.autocolorscale, { - dflt: autoColorDflt === false ? autoColorDflt : _$attributes_245.autocolorscale.dflt + dflt: autoColorDflt === false ? autoColorDflt : _$attributes_307.autocolorscale.dflt }), - reversescale: __extendFlat_247({}, _$attributes_245.reversescale, { + reversescale: __extendFlat_309({}, _$attributes_307.reversescale, { }) }; @@ -22373,7 +22483,7 @@ var _$makeColorScaleAttributes_247 = function makeColorScaleAttributes(context, 'use strict'; -var _$constants_518 = { +var _$constants_582 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -22398,16 +22508,16 @@ var _$constants_518 = { 'use strict'; -/* removed: var _$makeColorScaleAttributes_247 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_240 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -var __dash_512 = _$attributes_263.dash; +/* removed: var _$makeColorScaleAttributes_309 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_302 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +var __dash_576 = _$attributes_325.dash; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; -/* removed: var _$constants_518 = require('./constants'); */; -var __extendFlat_512 = _$extend_354.extendFlat; +/* removed: var _$drawing_326 = require('../../components/drawing'); */; +/* removed: var _$constants_582 = require('./constants'); */; +var __extendFlat_576 = _$extend_416.extendFlat; -var _$attributes_512 = { +var _$attributes_576 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -22509,7 +22619,7 @@ var _$attributes_512 = { editType: 'plot', }, - dash: __extendFlat_512({}, __dash_512, {editType: 'style'}), + dash: __extendFlat_576({}, __dash_576, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -22549,10 +22659,10 @@ var _$attributes_512 = { editType: 'style', }, - marker: __extendFlat_512({ + marker: __extendFlat_576({ symbol: { valType: 'enumerated', - values: _$drawing_264.symbolList, + values: _$drawing_326.symbolList, dflt: 'circle', arrayOk: true, @@ -22616,9 +22726,9 @@ var _$attributes_512 = { editType: 'calc', }, - colorbar: _$attributes_240, + colorbar: _$attributes_302, - line: __extendFlat_512({ + line: __extendFlat_576({ width: { valType: 'number', min: 0, @@ -22629,7 +22739,7 @@ var _$attributes_512 = { }, editType: 'calc' }, - _$makeColorScaleAttributes_247('marker.line') + _$makeColorScaleAttributes_309('marker.line') ), gradient: { type: { @@ -22652,7 +22762,7 @@ var _$attributes_512 = { }, editType: 'calc' }, - _$makeColorScaleAttributes_247('marker') + _$makeColorScaleAttributes_309('marker') ), selected: { marker: { @@ -22740,7 +22850,7 @@ var _$attributes_512 = { editType: 'calc', }, - textfont: _$font_attributes_434({ + textfont: _$font_attributes_496({ editType: 'calc', colorEditType: 'style', arrayOk: true, @@ -22769,12 +22879,12 @@ var _$attributes_512 = { 'use strict'; -/* removed: var _$attributes_512 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_512.marker; +/* removed: var _$attributes_576 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_576.marker; -var _$area_attributes_445 = { - r: _$attributes_512.r, - t: _$attributes_512.t, +var _$area_attributes_507 = { + r: _$attributes_576.r, + t: _$attributes_576.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -22795,11 +22905,11 @@ var _$area_attributes_445 = { 'use strict'; -/* removed: var _$layout_attributes_419 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_446 = _$extend_354.extendFlat; -var __overrideAll_446 = _$edit_types_392.overrideAll; +/* removed: var _$layout_attributes_482 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_508 = _$extend_416.extendFlat; +var __overrideAll_508 = _$edit_types_455.overrideAll; -var domainAttr = __extendFlat_446({}, _$layout_attributes_419.domain, { +var domainAttr = __extendFlat_508({}, _$layout_attributes_482.domain, { }); @@ -22848,10 +22958,10 @@ function mergeAttrs(axisName, nonCommonAttrs) { } }; - return __extendFlat_446({}, nonCommonAttrs, commonAttrs); + return __extendFlat_508({}, nonCommonAttrs, commonAttrs); } -var _$axis_attributes_446 = __overrideAll_446({ +var _$axis_attributes_508 = __overrideAll_508({ radialaxis: mergeAttrs('radial', { range: { valType: 'info_array', @@ -22899,7 +23009,7 @@ var _$axis_attributes_446 = __overrideAll_446({ } }, 'plot', 'nested'); -var _$plot_schema_398 = {}; +var _$plot_schema_461 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22911,22 +23021,23 @@ var _$plot_schema_398 = {}; 'use strict'; -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$lib_363 = require('../lib'); */; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$lib_425 = require('../lib'); */; -/* removed: var _$attributes_404 = require('../plots/attributes'); */; -/* removed: var _$layout_attributes_442 = require('../plots/layout_attributes'); */; -/* removed: var _$frame_attributes_435 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_402 = require('../plots/animation_attributes'); */; +/* removed: var _$attributes_467 = require('../plots/attributes'); */; +/* removed: var _$layout_attributes_504 = require('../plots/layout_attributes'); */; +/* removed: var _$frame_attributes_497 = require('../plots/frame_attributes'); */; +/* removed: var _$animation_attributes_465 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet -/* removed: var _$area_attributes_445 = require('../plots/polar/legacy/area_attributes'); */; -/* removed: var _$axis_attributes_446 = require('../plots/polar/legacy/axis_attributes'); */; +/* removed: var _$area_attributes_507 = require('../plots/polar/legacy/area_attributes'); */; +/* removed: var _$axis_attributes_508 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_392 = require('./edit_types'); */; +/* removed: var _$edit_types_455 = require('./edit_types'); */; -var __extendFlat_398 = _$lib_363.extendFlat; -var __extendDeepAll_398 = _$lib_363.extendDeepAll; +var __extendFlat_461 = _$lib_425.extendFlat; +var __extendDeepAll_461 = _$lib_425.extendDeepAll; +var __isPlainObject_461 = _$lib_425.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -22934,10 +23045,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_398.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_398.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_398.DEPRECATED = DEPRECATED; -_$plot_schema_398.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_461.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_461.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_461.DEPRECATED = DEPRECATED; +_$plot_schema_461.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -22950,26 +23061,26 @@ _$plot_schema_398.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_398.get = function() { +_$plot_schema_461.get = function() { var traces = {}; - _$registry_451.allTypes.concat('area').forEach(function(type) { + _$registry_514.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_451.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_514.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_363.valObjectMeta, + valObjects: _$lib_425.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_392.traces, - layout: _$edit_types_392.layout + traces: _$edit_types_455.traces, + layout: _$edit_types_455.layout }, impliedEdits: { @@ -22982,7 +23093,7 @@ _$plot_schema_398.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_402) + animation: formatAttributes(_$animation_attributes_465) }; }; @@ -23013,7 +23124,7 @@ _$plot_schema_398.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_398.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_461.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -23025,10 +23136,10 @@ _$plot_schema_398.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_398.isValObject(attr)) return; + if(_$plot_schema_461.isValObject(attr)) return; - if(_$lib_363.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_398.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_461(attr) && attrName !== 'impliedEdits') { + _$plot_schema_461.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -23040,7 +23151,7 @@ _$plot_schema_398.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_398.isValObject = function(obj) { +_$plot_schema_461.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -23054,7 +23165,7 @@ _$plot_schema_398.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_398.findArrayAttributes = function(trace) { +_$plot_schema_461.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -23077,8 +23188,8 @@ _$plot_schema_398.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_363.nestedProperty(trace, astr).get(); - if(!_$lib_363.isArrayOrTypedArray(val)) return; + var val = _$lib_425.nestedProperty(trace, astr).get(); + if(!_$lib_425.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -23087,9 +23198,9 @@ _$plot_schema_398.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_398.crawl(_$attributes_404, callback); + _$plot_schema_461.crawl(_$attributes_467, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_398.crawl(trace._module.attributes, callback); + _$plot_schema_461.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -23102,7 +23213,7 @@ _$plot_schema_398.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_398.crawl(module.attributes, callback, 1); + _$plot_schema_461.crawl(module.attributes, callback, 1); } } } @@ -23114,8 +23225,8 @@ _$plot_schema_398.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_398.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_363.filterUnique(arrayAttributes); + _$plot_schema_461.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_425.filterUnique(arrayAttributes); } return arrayAttributes; @@ -23136,29 +23247,30 @@ _$plot_schema_398.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_398.getTraceValObject = function(trace, parts) { +_$plot_schema_461.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_451.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_514.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } else if(trace.type === 'area') { - valObject = _$area_attributes_445[head]; + valObject = _$area_attributes_507[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_451.modules[trace.type || _$attributes_404.type.dflt] || {})._module; + if(!_module) _module = (_$registry_514.modules[trace.type || _$attributes_467.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -23173,7 +23285,7 @@ _$plot_schema_398.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_404[head]; + if(!valObject) valObject = _$attributes_467[head]; } return recurseIntoValObject(valObject, parts, i); @@ -23192,7 +23304,7 @@ _$plot_schema_398.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_398.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_461.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -23243,21 +23355,21 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_451.componentsRegistry) { - _module = _$registry_451.componentsRegistry[key]; + for(key in _$registry_514.componentsRegistry) { + _module = _$registry_514.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } } - if(head in _$layout_attributes_442) return _$layout_attributes_442[head]; + if(head in _$layout_attributes_504) return _$layout_attributes_504[head]; // Polar doesn't populate _modules or _basePlotModules // just fall back on these when the others fail if(head === 'radialaxis' || head === 'angularaxis') { - return _$axis_attributes_446[head]; + return _$axis_attributes_508[head]; } - return _$axis_attributes_446.layout[head] || false; + return _$axis_attributes_508.layout[head] || false; } function recurseIntoValObject(valObject, parts, i) { @@ -23274,7 +23386,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_363.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_461(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -23317,11 +23429,11 @@ function getTraceAttributes(type) { var _module, basePlotModule; if(type === 'area') { - _module = { attributes: _$area_attributes_445 }; + _module = { attributes: _$area_attributes_507 }; basePlotModule = {}; } else { - _module = _$registry_451.modules[type]._module, + _module = _$registry_514.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -23331,14 +23443,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_398(attributes, _$attributes_404); + __extendDeepAll_461(attributes, _$attributes_467); // module attributes - __extendDeepAll_398(attributes, _module.attributes); + __extendDeepAll_461(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_398(attributes, basePlotModule.attributes); + __extendDeepAll_461(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -23353,7 +23465,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_398(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_461(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -23365,21 +23477,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_398(layoutAttributes, _$layout_attributes_442); + __extendDeepAll_461(layoutAttributes, _$layout_attributes_504); // add base plot module layout attributes - for(key in _$registry_451.subplotsRegistry) { - _module = _$registry_451.subplotsRegistry[key]; + for(key in _$registry_514.subplotsRegistry) { + _module = _$registry_514.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -23388,8 +23499,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_451.componentsRegistry) { - _module = _$registry_451.componentsRegistry[key]; + for(key in _$registry_514.componentsRegistry) { + _module = _$registry_514.componentsRegistry[key]; var schema = _module.schema; /* @@ -23420,12 +23531,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_451.transformsRegistry[type]; - var attributes = __extendDeepAll_398({}, _module.attributes); + var _module = _$registry_514.transformsRegistry[type]; + var attributes = __extendDeepAll_461({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_451.componentsRegistry).forEach(function(k) { - var _module = _$registry_451.componentsRegistry[k]; + Object.keys(_$registry_514.componentsRegistry).forEach(function(k) { + var _module = _$registry_514.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -23441,7 +23552,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_363.extendDeepAll({}, _$frame_attributes_435) + frames: _$lib_425.extendDeepAll({}, _$frame_attributes_497) }; formatAttributes(attrs); @@ -23452,6 +23563,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -23468,7 +23580,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_398.isValObject(attr)) { + if(_$plot_schema_461.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -23480,13 +23592,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_363.isPlainObject(attr)) { + else if(__isPlainObject_461(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_398.crawl(attrs, callback); + _$plot_schema_461.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -23505,35 +23617,58 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_398.crawl(attrs, callback); + _$plot_schema_461.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_461(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_398(layoutAttributes, { - radialaxis: _$axis_attributes_446.radialaxis, - angularaxis: _$axis_attributes_446.angularaxis + __extendFlat_461(layoutAttributes, { + radialaxis: _$axis_attributes_508.radialaxis, + angularaxis: _$axis_attributes_508.angularaxis }); - __extendFlat_398(layoutAttributes, _$axis_attributes_446.layout); + __extendFlat_461(layoutAttributes, _$axis_attributes_508.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_363.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_398({}, _module.layoutAttributes); + var np = _$lib_425.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_461({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_363.nestedProperty(baseAttrs, astr); + var np = _$lib_425.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_398(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_461(np.get() || {}, newAttrs)); } -var _$command_432 = {}; +var _$command_494 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -23544,8 +23679,8 @@ var _$command_432 = {}; 'use strict'; -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$lib_363 = require('../lib'); */; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$lib_425 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -23563,7 +23698,7 @@ var _$command_432 = {}; * A listener called when the value is changed. Receives data object * with information about the new state. */ -_$command_432.manageCommandObserver = function(gd, container, commandList, onchange) { +_$command_494.manageCommandObserver = function(gd, container, commandList, onchange) { var ret = {}; var enabled = true; @@ -23578,7 +23713,7 @@ _$command_432.manageCommandObserver = function(gd, container, commandList, oncha // Either create or just recompute this: ret.lookupTable = {}; - var binding = _$command_432.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); + var binding = _$command_494.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); if(container && container._commandObserver) { if(!binding) { @@ -23649,7 +23784,7 @@ _$command_432.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_363.log('Unable to automatically bind plot updates to API command'); + _$lib_425.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -23679,7 +23814,7 @@ _$command_432.manageCommandObserver = function(gd, container, commandList, oncha * 2. only one property may be affected * 3. the same property must be affected by all commands */ -_$command_432.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { +_$command_494.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { var i; var n = commandList.length; @@ -23697,7 +23832,7 @@ _$command_432.hasSimpleAPICommandBindings = function(gd, commandList, bindingsBy if(!method) { return false; } - var bindings = _$command_432.computeAPICommandBindings(gd, method, args); + var bindings = _$command_494.computeAPICommandBindings(gd, method, args); // Right now, handle one and *only* one property being set: if(bindings.length !== 1) { @@ -23767,7 +23902,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_363.nestedProperty(container, binding.prop).get(); + value = _$lib_425.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -23796,10 +23931,10 @@ function bindingValueHasChanged(gd, binding, cache) { * @param {array} args * A list of arguments passed to the API command */ -_$command_432.executeAPICommand = function(gd, method, args) { +_$command_494.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_451.apiMethodRegistry[method]; + var _method = _$registry_514.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -23808,12 +23943,12 @@ _$command_432.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_363.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_425.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; -_$command_432.computeAPICommandBindings = function(gd, method, args) { +_$command_494.computeAPICommandBindings = function(gd, method, args) { var bindings; if(!Array.isArray(args)) args = []; @@ -23858,7 +23993,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_363.isPlainObject(astr)) { + } else if(_$lib_425.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -23882,7 +24017,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_363.isPlainObject(astr)) { + } else if(_$lib_425.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -23948,7 +24083,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_363.isPlainObject(attr)) { + if(_$lib_425.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -23957,7 +24092,33 @@ function crawl(attrs, callback, path, depth) { }); } -var _$plots_444 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_513 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + +var _$plots_506 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -23969,56 +24130,58 @@ var _$plots_444 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$plot_schema_398 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_410 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_363 = require('../lib'); */; -var _ = _$lib_363._; -/* removed: var _$color_239 = require('../components/color'); */; -var __BADNUM_444 = _$numerical_343.BADNUM; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$plot_schema_461 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$color_301 = require('../components/color'); */; +var __BADNUM_506 = _$numerical_404.BADNUM; -var plots = _$plots_444 = {}; +/* removed: var _$axis_ids_473 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_506 = _$sort_modules_513.sortBasePlotModules; -/* removed: var _$animation_attributes_402 = require('./animation_attributes'); */; -/* removed: var _$frame_attributes_435 = require('./frame_attributes'); */; +/* removed: var _$animation_attributes_465 = require('./animation_attributes'); */; +/* removed: var _$frame_attributes_497 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_363.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_425.relinkPrivateKeys; +var _ = _$lib_425._; + +var plots = _$plots_506 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_363.extendFlat(plots, _$registry_451); +_$lib_425.extendFlat(plots, _$registry_514); -plots.attributes = _$attributes_404; +plots.attributes = _$attributes_467; plots.attributes.type.values = plots.allTypes; -plots.fontAttrs = _$font_attributes_434; -plots.layoutAttributes = _$layout_attributes_442; +plots.fontAttrs = _$font_attributes_496; +plots.layoutAttributes = _$layout_attributes_504; // TODO make this a plot attribute? plots.fontWeight = 'normal'; var transformsRegistry = plots.transformsRegistry; -/* removed: var _$command_432 = require('./command'); */; -plots.executeAPICommand = _$command_432.executeAPICommand; -plots.computeAPICommandBindings = _$command_432.computeAPICommandBindings; -plots.manageCommandObserver = _$command_432.manageCommandObserver; -plots.hasSimpleAPICommandBindings = _$command_432.hasSimpleAPICommandBindings; +/* removed: var _$command_494 = require('./command'); */; +plots.executeAPICommand = _$command_494.executeAPICommand; +plots.computeAPICommandBindings = _$command_494.computeAPICommandBindings; +plots.manageCommandObserver = _$command_494.manageCommandObserver; +plots.hasSimpleAPICommandBindings = _$command_494.hasSimpleAPICommandBindings; // in some cases the browser doesn't seem to know how big // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_363.getGraphDiv(gd); + gd = _$lib_425.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_451.getComponentMethod('annotations', 'draw')(gd); - _$registry_451.getComponentMethod('legend', 'draw')(gd); + _$registry_514.getComponentMethod('annotations', 'draw')(gd); + _$registry_514.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -24031,7 +24194,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_363.getGraphDiv(gd); + gd = _$lib_425.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -24062,7 +24225,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_451.call('relayout', gd, {autosize: true}).then(function() { + _$registry_514.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -24092,29 +24255,24 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_425.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', - 'fill': _$color_239.defaultLine, + 'fill': _$color_301.defaultLine, 'pointer-events': 'all' }) .each(function() { - var links = _$d3_68.select(this); + var links = _$d3_71.select(this); links.append('tspan').classed('js-link-to-tool', true); links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -24179,7 +24337,7 @@ plots.sendDataToCloud = function(gd) { var baseUrl = (window.PLOTLYENV && window.PLOTLYENV.BASE_URL) || 'https://plot.ly'; - var hiddenformDiv = _$d3_68.select(gd) + var hiddenformDiv = _$d3_71.select(gd) .append('div') .attr('id', 'hiddenform') .style('display', 'none'); @@ -24252,6 +24410,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -24286,7 +24446,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -24329,12 +24488,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_514.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_425.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_425.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_425.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -24345,7 +24530,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -24354,6 +24539,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -24364,7 +24560,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -24376,17 +24572,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_410.list(gd); + var axList = _$axis_ids_473.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -24396,6 +24592,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_506); }; /** @@ -24414,7 +24613,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_451.subplotsRegistry; + var subplotsRegistry = _$registry_514.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -24427,7 +24626,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_363.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_425.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -24448,14 +24647,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_363.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_425.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_363.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_425.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -24500,7 +24699,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_451.localeRegistry; + locales = _$registry_514.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -24509,7 +24708,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_451.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_514.localeRegistry.en.format); return formatObj; } @@ -24530,7 +24729,7 @@ function getFormatter(formatObj, separators) { formatObj.decimal = separators.charAt(0); formatObj.thousands = separators.charAt(1); - return _$d3_68.locale(formatObj); + return _$d3_71.locale(formatObj); } // Create storage for all of the data related to frames and transitions: @@ -24561,30 +24760,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_514.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -24592,7 +24789,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -24664,8 +24861,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_410.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_410.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_473.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_473.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -24710,13 +24907,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_410.list(mockGd, null, true); + var axList = _$axis_ids_473.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_410.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_473.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -24738,7 +24935,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_410.getFromId(mockGd, ax.anchor); + _$axis_ids_473.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -24767,7 +24964,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_410.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_473.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -24808,17 +25005,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_398.crawl( + _$plot_schema_461.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_363.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_425.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_363.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_425.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -24840,8 +25037,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_363.pushUnique(modules, _module); - _$lib_363.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_425.pushUnique(modules, _module); + _$lib_425.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -24901,11 +25098,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_451.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_514.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_451.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_514.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -24934,7 +25131,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_363.coerce(opts || {}, optsOut, _$animation_attributes_402, attr, dflt); + return _$lib_425.coerce(opts || {}, optsOut, _$animation_attributes_465, attr, dflt); } coerce('mode'); @@ -24966,7 +25163,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_363.coerce(opts || {}, optsOut, _$animation_attributes_402.frame, attr, dflt); + return _$lib_425.coerce(opts || {}, optsOut, _$animation_attributes_465.frame, attr, dflt); } coerce('duration'); @@ -24979,7 +25176,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_363.coerce(opts || {}, optsOut, _$animation_attributes_402.transition, attr, dflt); + return _$lib_425.coerce(opts || {}, optsOut, _$animation_attributes_465.transition, attr, dflt); } coerce('duration'); @@ -24992,7 +25189,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_363.coerce(frameIn, frameOut, _$frame_attributes_435, attr, dflt); + return _$lib_425.coerce(frameIn, frameOut, _$frame_attributes_497, attr, dflt); } coerce('group'); @@ -25006,14 +25203,14 @@ plots.supplyFrameDefaults = function(frameIn) { }; plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) { - var colorway = layout.colorway || _$color_239.defaults; + var colorway = layout.colorway || _$color_301.defaults; var traceOut = {}, defaultColor = colorway[colorIndex % colorway.length]; var i; function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_425.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -25029,9 +25226,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -25041,18 +25238,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_363.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_425.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_363.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_425.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_363.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_425.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_363.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_425.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -25062,12 +25259,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_451.traceIs(traceOut, 'showLegend')) { + if(_$registry_514.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_451.getComponentMethod( + _$registry_514.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -25076,12 +25273,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_363.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_425.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_451.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_514.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_451.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_514.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -25125,17 +25322,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_363.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_425.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_363.pushUnique(transformModules, _module); + _$lib_425.pushUnique(transformModules, _module); } else { - transformOut = _$lib_363.extendFlat({}, transformIn); + transformOut = _$lib_425.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -25167,14 +25364,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_363.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_425.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_363.coerceFont(coerce, 'font'); + var globalFont = _$lib_425.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_363.coerceFont(coerce, 'titlefont', { + _$lib_425.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -25202,7 +25399,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_451.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_514.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -25213,12 +25410,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_451.getComponentMethod( + _$registry_514.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_451.getComponentMethod( + _$registry_514.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -25230,7 +25427,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_363.isPlotDiv(gd); + var isPlotDiv = _$lib_425.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -25244,7 +25441,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { // just hide it document.body.style.overflow = 'hidden'; } - else if(_$fastIsnumeric_78(frameMargins) && frameMargins > 0) { + else if(_$fastIsnumeric_135(frameMargins) && frameMargins > 0) { var reservedMargins = calculateReservedMargins(gd._boundingBoxMargins), reservedWidth = reservedMargins.left + reservedMargins.right, reservedHeight = reservedMargins.bottom + reservedMargins.top, @@ -25318,11 +25515,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_451.componentsRegistry; + var componentsRegistry = _$registry_514.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_451.subplotsRegistry.cartesian; + var Cartesian = _$registry_514.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -25341,13 +25538,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_451.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_514.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_363.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_425.subplotSort); } // base plot module layout defaults @@ -25419,7 +25616,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_363.clearThrottle(); + _$lib_425.clearThrottle(); // data and layout delete gd.data; @@ -25475,7 +25672,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_363.pushUnique(styleModules, _module.style); + _$lib_425.pushUnique(styleModules, _module.style); } } @@ -25584,7 +25781,7 @@ plots.doAutoMargin = function(gd) { pb = pushbottom.size; for(var k2 in pm) { - if(_$fastIsnumeric_78(pl) && pm[k2].r) { + if(_$fastIsnumeric_135(pl) && pm[k2].r) { var fr = pm[k2].r.val, pr = pm[k2].r.size; @@ -25600,7 +25797,7 @@ plots.doAutoMargin = function(gd) { } } - if(_$fastIsnumeric_78(pb) && pm[k2].t) { + if(_$fastIsnumeric_135(pb) && pm[k2].t) { var ft = pm[k2].t.val, pt = pm[k2].t.size; @@ -25630,7 +25827,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_451.call('plot', gd); + return _$registry_514.call('plot', gd); } }; @@ -25671,7 +25868,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_363.isPlainObject(d)) { + if(_$lib_425.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -25694,7 +25891,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_363.isPlainObject(d.stream)) { + if(!_$lib_425.isPlainObject(d.stream)) { continue; } } @@ -25720,7 +25917,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_363.isJSDate(d)) return _$lib_363.ms2DateTimeLocal(+d); + if(_$lib_425.isJSDate(d)) return _$lib_425.ms2DateTimeLocal(+d); return d; } @@ -25917,8 +26114,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_363.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_363.expandObjectPaths(copy); + var copy = _$lib_425.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_425.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -25926,29 +26123,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_363.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_425.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_363.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_425.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_363.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_425.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_363.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_425.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_363.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_425.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_363.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_425.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -25973,7 +26170,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_451.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_514.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -26047,7 +26244,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_363.expandObjectPaths(_$lib_363.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_425.expandObjectPaths(_$lib_425.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -26074,7 +26271,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_451.getComponentMethod('errorbars', 'calc')(gd); + _$registry_514.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -26122,7 +26319,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_451.call('redraw', gd); + return _$registry_514.call('redraw', gd); }); } @@ -26154,7 +26351,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_363.expandObjectPaths(layout); + var newLayout = _$lib_425.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -26164,7 +26361,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_363.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_425.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -26194,7 +26391,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_451.call('redraw', gd); + return _$registry_514.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -26229,7 +26426,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_363.syncOrAsync(seq, gd); + var transitionStarting = _$lib_425.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -26241,7 +26438,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_410.list(gd), + var axList = _$axis_ids_473.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -26285,7 +26482,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_398.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_461.findArrayAttributes(trace); } // add polar axes to axis list @@ -26329,14 +26526,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -26359,7 +26557,7 @@ plots.doCalcdata = function(gd, traces) { // This ensures there is a calcdata item for every trace, // even if cartesian logic doesn't handle it (for things like legends). if(!Array.isArray(cd) || !cd[0]) { - cd = [{x: __BADNUM_444, y: __BADNUM_444}]; + cd = [{x: __BADNUM_506, y: __BADNUM_506}]; } // add the trace-wide properties to the first point, @@ -26371,7 +26569,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_451.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_514.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -26422,7 +26625,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_363.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_425.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -26440,18 +26643,18 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$interactions_342 = require('../../constants/interactions'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$interactions_403 = require('../../constants/interactions'); */; -var _$titles_332 = { +var _$titles_394 = { draw: draw }; @@ -26529,10 +26732,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_425.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -26550,7 +26750,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_363.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_425.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -26572,19 +26772,19 @@ function draw(gd, titleClass, options) { titleEl.style({ 'font-family': font, - 'font-size': _$d3_68.round(fontSize, 2) + 'px', - fill: _$color_239.rgb(fontColor), - opacity: opacity * _$color_239.opacity(fontColor), - 'font-weight': _$plots_444.fontWeight + 'font-size': _$d3_71.round(fontSize, 2) + 'px', + fill: _$color_301.rgb(fontColor), + opacity: opacity * _$color_301.opacity(fontColor), + 'font-weight': _$plots_506.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_386.convertToTspans, gd); + .call(_$svg_text_utils_449.convertToTspans, gd); - return _$plots_444.previousPromises(gd); + return _$plots_506.previousPromises(gd); } function scootTitle(titleElIn) { - var titleGroup = _$d3_68.select(titleElIn.node().parentNode); + var titleGroup = _$d3_71.select(titleElIn.node().parentNode); if(avoid && avoid.selection && avoid.side && txt) { titleGroup.attr('transform', null); @@ -26600,8 +26800,8 @@ function draw(gd, titleClass, options) { }[avoid.side]; var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ? -1 : 1; - var pad = _$fastIsnumeric_78(avoid.pad) ? avoid.pad : 2; - var titlebb = _$drawing_264.bBox(titleGroup.node()); + var pad = _$fastIsnumeric_135(avoid.pad) ? avoid.pad : 2; + var titlebb = _$drawing_326.bBox(titleGroup.node()); var paperbb = { left: 0, top: 0, @@ -26626,9 +26826,9 @@ function draw(gd, titleClass, options) { // iterate over a set of elements (avoid.selection) // to avoid collisions with avoid.selection.each(function() { - var avoidbb = _$drawing_264.bBox(this); + var avoidbb = _$drawing_326.bBox(this); - if(_$lib_363.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_425.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -26655,12 +26855,12 @@ function draw(gd, titleClass, options) { isplaceholder = true; el.text(placeholder) .on('mouseover.opacity', function() { - _$d3_68.select(this).transition() - .duration(_$interactions_342.SHOW_PLACEHOLDER).style('opacity', 1); + _$d3_71.select(this).transition() + .duration(_$interactions_403.SHOW_PLACEHOLDER).style('opacity', 1); }) .on('mouseout.opacity', function() { - _$d3_68.select(this).transition() - .duration(_$interactions_342.HIDE_PLACEHOLDER).style('opacity', 0); + _$d3_71.select(this).transition() + .duration(_$interactions_403.HIDE_PLACEHOLDER).style('opacity', 0); }); } @@ -26668,12 +26868,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_386.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_449.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_451.call('restyle', gd, prop, text, traceIndex); + _$registry_514.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_451.call('relayout', gd, prop, text); + _$registry_514.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -26682,7 +26882,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_386.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_449.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -26701,12 +26901,12 @@ function draw(gd, titleClass, options) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -var __FP_SAFE_406 = _$numerical_343.FP_SAFE; +/* removed: var _$lib_425 = require('../../lib'); */; +var __FP_SAFE_469 = _$numerical_404.FP_SAFE; -var _$autorange_406 = { +var _$autorange_469 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -26751,7 +26951,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_363.simpleMap(ax.range, ax.r2l); + var rng = _$lib_425.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -26844,7 +27044,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_363.simpleMap(newRange, ax.l2r || Number); + return _$lib_425.simpleMap(newRange, ax.l2r || Number); } /* @@ -26876,7 +27076,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_363.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_425.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -26898,7 +27098,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_363.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_425.extendFlat({}, axeRangeOpts); } } @@ -26911,6 +27111,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -26971,14 +27173,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_406) vmax = v; + if(v > vmax && v < __FP_SAFE_469) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_406) vmin = v; - if(v > vmax && v < __FP_SAFE_406) vmax = v; + if(v < vmin && v > -__FP_SAFE_469) vmin = v; + if(v > vmax && v < __FP_SAFE_469) vmax = v; } } @@ -26988,7 +27190,7 @@ function expand(ax, data, options) { function addItem(i) { di = data[i]; - if(!_$fastIsnumeric_78(di)) return; + if(!_$fastIsnumeric_135(di)) return; ppadiplus = ppadplus(i); ppadiminus = ppadminus(i); vmin = di - vpadminus(i); @@ -27012,7 +27214,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_406 : __lessOrEqual_406; + var atLeastAsExtreme = k ? __greaterOrEqual_469 : __lessOrEqual_469; includeThis = true; /* @@ -27063,13 +27265,12 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_78(v) && Math.abs(v) < __FP_SAFE_406; + return _$fastIsnumeric_135(v) && Math.abs(v) < __FP_SAFE_469; } -function __lessOrEqual_406(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_406(v0, v1) { return v0 >= v1; } +function __lessOrEqual_469(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_469(v0, v1) { return v0 >= v1; } -var _$axes_407 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -27081,18520 +27282,17011 @@ var _$axes_407 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$titles_332 = require('../../components/titles'); */; -/* removed: var _$color_239 = require('../../components/color'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; - -/* removed: var _$numerical_343 = require('../../constants/numerical'); */; -var ONEAVGYEAR = _$numerical_343.ONEAVGYEAR; -var ONEAVGMONTH = _$numerical_343.ONEAVGMONTH; -var __ONEDAY_407 = _$numerical_343.ONEDAY; -var __ONEHOUR_407 = _$numerical_343.ONEHOUR; -var __ONEMIN_407 = _$numerical_343.ONEMIN; -var __ONESEC_407 = _$numerical_343.ONESEC; -var MINUS_SIGN = _$numerical_343.MINUS_SIGN; -var __BADNUM_407 = _$numerical_343.BADNUM; - -var MID_SHIFT = _$alignment_339.MID_SHIFT; -var __LINE_SPACING_407 = _$alignment_339.LINE_SPACING; - -var axes = _$axes_407 = {}; - -axes.setConvert = _$setConvert_426; -/* removed: var _$autoType_408 = require('./axis_autotype'); */; - -/* removed: var _$axis_ids_410 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_410.id2name; -axes.name2id = _$axis_ids_410.name2id; -axes.cleanId = _$axis_ids_410.cleanId; -axes.list = _$axis_ids_410.list; -axes.listIds = _$axis_ids_410.listIds; -axes.getFromId = _$axis_ids_410.getFromId; -axes.getFromTrace = _$axis_ids_410.getFromTrace; - -/* removed: var _$autorange_406 = require('./autorange'); */; -axes.expand = _$autorange_406.expand; -axes.getAutoRange = _$autorange_406.getAutoRange; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* - * 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 = {}; +/* removed: var _$lib_425 = require('../../lib'); */; +var __BADNUM_471 = _$numerical_404.BADNUM; - if(!dflt) dflt = axlist[0] || extraOption; - if(!extraOption) extraOption = dflt; +var _$autoType_471 = function autoType(array, calendar) { + if(moreDates(array, calendar)) return 'date'; + if(category(array)) return 'category'; + if(linearOK(array)) return 'linear'; + else return '-'; +}; - // data-ref annotations are not supported in gl2d yet +// is there at least one number in array? If not, we should leave +// ax.type empty so it can be autoset later +function linearOK(array) { + if(!array) return false; - attrDef[refAttr] = { - valType: 'enumerated', - values: axlist.concat(extraOption ? [extraOption] : []), - dflt: dflt - }; + for(var i = 0; i < array.length; i++) { + if(_$fastIsnumeric_135(array[i])) return true; + } - // xref, yref - return _$lib_363.coerce(containerIn, containerOut, attrDef, refAttr); -}; + return false; +} -/* - * 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; +// does the array a have mostly dates rather than numbers? +// note: some values can be neither (such as blanks, text) +// 2- or 4-digit integers can be both, so require twice as many +// dates as non-dates, to exclude cases with mostly 2 & 4 digit +// numbers and a few dates +function moreDates(a, calendar) { + var dcnt = 0, + ncnt = 0, + // test at most 1000 points, evenly spaced + inc = Math.max(1, (a.length - 1) / 1000), + ai; - if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_363.ensureNumber; - pos = coerce(attr, dflt); - } else { - var ax = axes.getFromId(gd, axRef); - dflt = ax.fraction2r(dflt); - pos = coerce(attr, dflt); - cleanPos = ax.cleanPos; + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_425.isDateTime(ai, calendar)) dcnt += 1; + if(_$fastIsnumeric_135(ai)) ncnt += 1; } - containerOut[attr] = cleanPos(pos); -}; + return (dcnt > ncnt * 2); +} -axes.cleanPosition = function(pos, gd, axRef) { - var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_363.ensureNumber : - axes.getFromId(gd, axRef).cleanPos; +// are the (x,y)-values in gd.data mostly text? +// require twice as many categories as numbers +function category(a) { + // test at most 1000 points + var inc = Math.max(1, (a.length - 1) / 1000), + curvenums = 0, + curvecats = 0, + ai; - return cleanPos(pos); -}; + for(var i = 0; i < a.length; i += inc) { + ai = a[Math.round(i)]; + if(_$lib_425.cleanNumber(ai) !== __BADNUM_471) curvenums++; + else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; + } -var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { - var ax; + return curvecats > curvenums * 2; +} - // 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; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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_408(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]); - } - } - } else { - ax = axes.getFromTrace(gd, trace, d2cTarget); - } +'use strict'; - // if 'target' has corresponding axis - // -> use setConvert method - if(ax) return {d2c: ax.d2c, c2d: ax.c2d}; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; - // special case for 'ids' - // -> cast to String - if(d2cTarget === 'ids') return {d2c: toString, c2d: toString}; +/* removed: var _$lib_425 = require('../../lib'); */; +var cleanNumber = _$lib_425.cleanNumber; +var ms2DateTime = _$lib_425.ms2DateTime; +var dateTime2ms = _$lib_425.dateTime2ms; +var ensureNumber = _$lib_425.ensureNumber; - // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size') - // -> cast to Number +/* removed: var _$numerical_404 = require('../../constants/numerical'); */; +var __FP_SAFE_488 = _$numerical_404.FP_SAFE; +var __BADNUM_488 = _$numerical_404.BADNUM; - return {d2c: toNum, c2d: toNum}; -}; +/* removed: var _$constants_475 = require('./constants'); */; +/* removed: var _$axis_ids_473 = require('./axis_ids'); */; -function toNum(v) { return +v; } -function toString(v) { return String(v); } +function fromLog(v) { + return Math.pow(10, v); +} -axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { - return getDataConversions(gd, trace, target, targetArray).d2c; -}; +/** + * 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 autorange bounds ._min and ._max + * and the autotick constraints ._minDtick, ._forceTick0 + */ +var _$setConvert_488 = function setConvert(ax, fullLayout) { + fullLayout = fullLayout || {}; -// 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'; -}; + var axLetter = (ax._id || 'x').charAt(0); -// 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'].indexOf(ax.type) !== -1 || !allow) { - ax._minDtick = 0; - } - // undefined means there's nothing there yet - else if(ax._minDtick === undefined) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - else if(ax._minDtick) { - // existing minDtick is an integer multiple of newDiff - // (within rounding err) - // and forceTick0 can be shifted to newFirst - if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && - (((newFirst - ax._forceTick0) / newDiff % 1) + - 1.000001) % 1 < 2e-6) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } - // 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 - else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || - (((newFirst - ax._forceTick0) / ax._minDtick % 1) + - 1.000001) % 1 > 2e-6) { - ax._minDtick = 0; - } - } -}; + // clipMult: how many axis lengths past the edge do we render? + // for panning, 1-2 would suffice, but for zooming more is nice. + // also, clipping can affect the direction of lines off the edge... + var clipMult = 10; -// 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), - hasOneAxisChanged = false; + function toLog(v, clip) { + if(v > 0) return Math.log(v) / Math.LN10; - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + else if(v <= 0 && clip && ax.range && ax.range.length === 2) { + // clip NaN (ie past negative infinity) to clipMult axis + // length past the negative edge + var r0 = ax.range[0], + r1 = ax.range[1]; + return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); + } - var isNew = (ax._rangeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.range[0] === ax._rangeInitial[0] && - ax.range[1] === ax._rangeInitial[1] - ) - ); + else return __BADNUM_488; + } - if((isNew && ax.autorange === false) || (overwrite && hasChanged)) { - ax._rangeInitial = ax.range.slice(); - hasOneAxisChanged = true; + /* + * 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_488) { + if(_$fastIsnumeric_135(v)) ms = dateTime2ms(new Date(+v)); + else return __BADNUM_488; } + return ms; } - return hasOneAxisChanged; -}; + // wrapped ms2DateTime to insert default ax.calendar + function ms2dt(v, r, calendar) { + return ms2DateTime(v, r, calendar || ax.calendar); + } -// save a copy of the initial spike visibility -axes.saveShowSpikeInitial = function(gd, overwrite) { - var axList = axes.list(gd, '', true), - hasOneAxisChanged = false, - allSpikesEnabled = 'on'; + function getCategoryName(v) { + return ax._categories[Math.round(v)]; + } - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; + /* + * 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(v !== null && v !== undefined) { + if(ax._categoriesMap === undefined) { + ax._categoriesMap = {}; + } - var isNew = (ax._showSpikeInitial === undefined); - var hasChanged = ( - isNew || !( - ax.showspikes === ax._showspikes - ) - ); + if(ax._categoriesMap[v] !== undefined) { + return ax._categoriesMap[v]; + } else { + ax._categories.push(v); - if((isNew) || (overwrite && hasChanged)) { - ax._showSpikeInitial = ax.showspikes; - hasOneAxisChanged = true; - } + var curLength = ax._categories.length - 1; + ax._categoriesMap[v] = curLength; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; + return curLength; + } } + return __BADNUM_488; } - gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - return hasOneAxisChanged; -}; -axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_363.aggNums(Math.min, null, data), - dataMax = _$lib_363.aggNums(Math.max, null, data); - - if(!calendar) calendar = ax.calendar; + function getCategoryIndex(v) { + // d2l/d2c variant that that won't add categories but will also + // allow numbers to be mapped to the linearized axis positions + if(ax._categoriesMap) { + var index = ax._categoriesMap[v]; + if(index !== undefined) return index; + } - if(ax.type === 'category') { - return { - start: dataMin - 0.5, - end: dataMax + 0.5, - size: 1, - _dataSpan: dataMax - dataMin, - }; + if(_$fastIsnumeric_135(v)) return +v; } - 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_363.distinctVals(data), - msexp = Math.pow(10, Math.floor( - Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_363.roundUp( - distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_363.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(!_$fastIsnumeric_78(size0)) size0 = 1; - } + function l2p(v) { + if(!_$fastIsnumeric_135(v)) return __BADNUM_488; - // piggyback off autotick code to make "nice" bin sizes - var dummyAx; - if(ax.type === 'log') { - dummyAx = { - type: 'linear', - range: [dataMin, dataMax] - }; - } - else { - dummyAx = { - type: ax.type, - range: _$lib_363.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), - calendar: calendar - }; + // include 2 fractional digits on pixel, for PDF zooming etc + return _$d3_71.round(ax._b + ax._m * v, 2); } - axes.setConvert(dummyAx); - - axes.autoTicks(dummyAx, size0); - var binStart = axes.tickIncrement( - axes.tickFirst(dummyAx), dummyAx.dtick, '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 dummyAx.dtick === 'number') { - binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + function p2l(px) { return (px - ax._b) / ax._m; } - bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); - binEnd = binStart + bincount * dummyAx.dtick; - } - 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, dummyAx.dtick, dataMin, calendar); - } + // 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; - // 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, dummyAx.dtick, false, calendar); - bincount++; - } - } + ax.l2p = l2p; + ax.p2l = p2l; - return { - start: ax.c2r(binStart, 0, calendar), - end: ax.c2r(binEnd, 0, calendar), - size: dummyAx.dtick, - _dataSpan: dataMax - dataMin - }; -}; + 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; -function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { - var edgecount = 0, - midcount = 0, - intcount = 0, - blankCount = 0; + ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2d = ax.p2r = p2l; - function nearEdge(v) { - // is a value within 1% of a bin edge? - return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; + 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)); }; - for(var i = 0; i < data.length; i++) { - if(data[i] % 1 === 0) intcount++; - else if(!_$fastIsnumeric_78(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') { - // 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 - if(ax.dtick < 1) { - binStart = dataMin - 0.5 * ax.dtick; - } - // 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. - else { - 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; -} - + ax.d2c = ax.r2l = cleanNumber; + ax.c2d = ax.l2r = ensureNumber; -function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_363.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; + ax.c2r = toLog; + ax.l2d = fromLog; - if(stats.exactDays > threshold) { - var numMonths = Number(dtick.substr(1)); + ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); }; + ax.p2d = function(px) { return fromLog(p2l(px)); }; - 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_407 * 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_407 * 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_407 / 2; - } - var nextBinStart = axes.tickIncrement(binStart, dtick); + ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); }; + ax.p2r = p2l; - if(nextBinStart <= dataMin) return nextBinStart; + ax.cleanPos = ensureNumber; } - return binStart; -} - -// ---------------------------------------------------- -// Ticks and grids -// ---------------------------------------------------- - -// ensure we have tick0, dtick, and tick rounding calculated -axes.prepTicks = function(ax) { - var rng = _$lib_363.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, - minPx; - if(!nt) { - if(ax.type === 'category') { - 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_363.constrain(ax._length / minPx, 4, 9) + 1; - } + else if(ax.type === 'date') { + // r and d are date strings, l and c are ms - // radial axes span half their domain, - // multiply nticks value by two to get correct number of auto ticks. - if(ax._name === 'radialaxis') nt *= 2; - } + /* + * 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_425.identity; - // add a couple of extra digits for filling in ticks when we - // have explicit tickvals without tick text - if(ax.tickmode === 'array') nt *= 100; + ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; + ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; - 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); - } - } + 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); }; - // check for missing tick0 - if(!ax.tick0) { - ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; + ax.cleanPos = function(v) { return _$lib_425.cleanDate(v, __BADNUM_488, ax.calendar); }; } + else if(ax.type === 'category') { + // d is categories (string) + // c and l are indices (numbers) + // r is categories or numbers - // 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_363.simpleMap(ax.range, ax.r2l); + ax.d2c = ax.d2l = setCategoryIndex; + ax.r2d = ax.c2d = ax.l2d = getCategoryName; - // 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); + ax.d2r = ax.d2l_noadd = getCategoryIndex; - // find the first tick - ax._tmin = axes.tickFirst(ax); + ax.r2c = function(v) { + var index = getCategoryIndex(v); + return index !== undefined ? index : ax.fraction2r(0.5); + }; - // 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]); + ax.l2r = ax.c2r = ensureNumber; + ax.r2l = getCategoryIndex; - // No visible ticks? Quit. - // I've only seen this on category axes with all categories off the edge. - if((ax._tmin < startTick) !== axrev) return []; + 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; - // return the full set of tick vals - var vals = []; - if(ax.type === 'category') { - endTick = (axrev) ? Math.max(-0.5, endTick) : - Math.min(ax._categories.length - 0.5, endTick); + ax.cleanPos = function(v) { + if(typeof v === 'string' && v !== '') return v; + return ensureNumber(v); + }; } - 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(vals.length > maxTicks || x === xPrevious) break; - xPrevious = x; - - vals.push(x); - } + // find the range value at the specified (linear) fraction of the axis + ax.fraction2r = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return ax.l2r(rl0 + v * (rl1 - rl0)); + }; - // If same angle over a full circle, the last tick vals is a duplicate. - // TODO must do something similar for angular date axes. - if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { - vals.pop(); - } + // find the fraction of the range at the specified range value + ax.r2fraction = function(v) { + var rl0 = ax.r2l(ax.range[0]), + rl1 = ax.r2l(ax.range[1]); + return (ax.r2l(v) - rl0) / (rl1 - rl0); + }; - // save the last tick as well as first, so we can - // show the exponent only on the last one - ax._tmax = vals[vals.length - 1]; + /* + * 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'; - // 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 range = _$lib_425.nestedProperty(ax, rangeAttr).get(); + var i, dflt; - var ticksOut = new Array(vals.length); - for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); + if(ax.type === 'date') dflt = _$lib_425.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_475.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_475.DFLTRANGEX; - ax._inCalcTicks = false; + // make sure we don't later mutate the defaults + dflt = dflt.slice(); - return ticksOut; -}; + if(!range || range.length !== 2) { + _$lib_425.nestedProperty(ax, rangeAttr).set(dflt); + return; + } -function arrayTicks(ax) { - var vals = ax.tickvals, - text = ax.ticktext, - ticksOut = new Array(vals.length), - rng = _$lib_363.simpleMap(ax.range, ax.r2l), - r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, - r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, - tickMin = Math.min(r0expanded, r1expanded), - tickMax = Math.max(r0expanded, r1expanded), - vali, - i, - j = 0; + if(ax.type === 'date') { + // check if milliseconds or js date objects are provided for range + // and convert to date strings + range[0] = _$lib_425.cleanDate(range[0], __BADNUM_488, ax.calendar); + range[1] = _$lib_425.cleanDate(range[1], __BADNUM_488, ax.calendar); + } - // 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 = []; + for(i = 0; i < 2; i++) { + if(ax.type === 'date') { + if(!_$lib_425.isDateTime(range[i], ax.calendar)) { + ax[rangeAttr] = dflt; + break; + } - // make sure showing ticks doesn't accidentally add new categories - var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; + if(ax.r2l(range[0]) === ax.r2l(range[1])) { + // split by +/- 1 second + var linCenter = _$lib_425.constrain(ax.r2l(range[0]), + _$lib_425.MIN_MS + 1000, _$lib_425.MAX_MS - 1000); + range[0] = ax.l2r(linCenter - 1000); + range[1] = ax.l2r(linCenter + 1000); + break; + } + } + else { + if(!_$fastIsnumeric_135(range[i])) { + if(_$fastIsnumeric_135(range[1 - i])) { + range[i] = range[1 - i] * (i ? 10 : 0.1); + } + else { + ax[rangeAttr] = dflt; + break; + } + } - // 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); - } + if(range[i] < -__FP_SAFE_488) range[i] = -__FP_SAFE_488; + else if(range[i] > __FP_SAFE_488) range[i] = __FP_SAFE_488; - for(i = 0; i < vals.length; i++) { - 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(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; + } + } } - } - - if(j < vals.length) ticksOut.splice(j, vals.length - j); - - return ticksOut; -} + }; -var roundBase10 = [2, 5, 10], - roundBase24 = [1, 2, 3, 6, 12], - roundBase60 = [1, 2, 5, 10, 15, 30], - // 2&3 day ticks are weird, but need something btwn 1&7 - 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 - roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], - roundLog2 = [-0.301, 0, 0.301, 0.699, 1], - // N.B. `thetaunit; 'radians' angular axes must be converted to degrees - roundAngles = [15, 30, 45, 90, 180]; + // set scaling to pixels + ax.setScale = function(usePrivateRange) { + var gs = fullLayout._size; -function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_363.roundUp(roughDTick / base, roundingSet); -} + // TODO cleaner way to handle this case + if(!ax._categories) ax._categories = []; + // Add a map to optimize the performance of category collection + if(!ax._categoriesMap) ax._categoriesMap = {}; -// 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; + // make sure we have a domain (pull it in from the axis + // this one is overlaying if necessary) + if(ax.overlaying) { + var ax2 = _$axis_ids_473.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + ax.domain = ax2.domain; + } - function getBase(v) { - return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); - } + // 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', + calendar = ax.calendar; + ax.cleanRange(rangeAttr); - if(ax.type === 'date') { - ax.tick0 = _$lib_363.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; + var rl0 = ax.r2l(ax[rangeAttr][0], calendar), + rl1 = ax.r2l(ax[rangeAttr][1], calendar); - 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_407) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_407, 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_363.dateTick0(ax.calendar, true); - } - else if(roughX2 > __ONEHOUR_407) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_407, roundBase24); - } - else if(roughX2 > __ONEMIN_407) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_407, roundBase60); - } - else if(roughX2 > __ONESEC_407) { - ax.dtick = roundDTick(roughDTick, __ONESEC_407, roundBase60); + 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 { - // milliseconds - base = getBase(10); - ax.dtick = roundDTick(roughDTick, base, roundBase10); - } - } - else if(ax.type === 'log') { - ax.tick0 = 0; - var rng = _$lib_363.simpleMap(ax.range, ax.r2l); - - if(roughDTick > 0.7) { - // only show powers of 10 - ax.dtick = Math.ceil(roughDTick); + 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; } - 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'; + if(!isFinite(ax._m) || !isFinite(ax._b)) { + fullLayout._replotting = false; + throw new Error('Something went wrong with axis scaling'); } - } - else if(ax.type === 'category') { - ax.tick0 = 0; - ax.dtick = Math.ceil(Math.max(roughDTick, 1)); - } - else if(ax._id === 'angular') { - 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(!_$fastIsnumeric_78(ax.dtick) && typeof ax.dtick !== 'string') { - var olddtick = ax.dtick; - ax.dtick = 1; - throw 'ax.dtick error: ' + String(olddtick); - } -}; + // 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; -// 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; + var axType = ax.type; + var cal = axType === 'date' && trace[axLetter + 'calendar']; - ax._tickexponent = 0; - if(!_$fastIsnumeric_78(dtick) && typeof dtick !== 'string') { - dtick = 1; - } + if(axLetter in trace) { + arrayIn = trace[axLetter]; + len = trace._length || arrayIn.length; - if(ax.type === 'category') { - 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), - tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), - tick0len = tick0str.length; + if(_$lib_425.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(len === arrayIn.length) { + return arrayIn; + } else if(arrayIn.subarray) { + return arrayIn.subarray(0, len); + } + } - 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'; + arrayOut = new Array(len); + for(i = 0; i < len; i++) { + arrayOut[i] = ax.d2c(arrayIn[i], 0, cal); + } } - else if((dtick >= __ONEDAY_407 && tick0len <= 10) || (dtick >= __ONEDAY_407 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_407 && tick0len <= 16) || (dtick >= __ONEHOUR_407)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_407 && tick0len <= 19) || (dtick >= __ONEMIN_407)) 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; - } - } - else if(_$fastIsnumeric_78(dtick) || dtick.charAt(0) === 'L') { - // linear or log (except D1, D2) - var rng = ax.range.map(ax.r2d || Number); - if(!_$fastIsnumeric_78(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 v0 = ((axLetter + '0') in trace) ? ax.d2c(trace[axLetter + '0'], 0, cal) : 0; + var dv = (trace['d' + axLetter]) ? Number(trace['d' + axLetter]) : 1; - var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[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); - 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); + for(i = 0; i < len; i++) { + arrayOut[i] = v0 + i * dv; } - else ax._tickexponent = rangeexp; } - } - // D1 or D2 (log) - else 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; + return arrayOut; + }; - // includes linear, all dates smaller than month, and pure 10^n in log - if(_$fastIsnumeric_78(dtick)) return x + axSign * dtick; + ax.isValidRange = function(range) { + return ( + Array.isArray(range) && + range.length === 2 && + _$fastIsnumeric_135(ax.r2l(range[0])) && + _$fastIsnumeric_135(ax.r2l(range[1])) + ); + }; - // everything else is a string, one character plus a number - var tType = dtick.charAt(0), - dtSigned = axSign * Number(dtick.substr(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]); - // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_363.incrementMonth(x, dtSigned, calendar); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } + }; - // Log scales: Linear, Digits - else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; + ax.clearCalc = function() { + // for autoranging: arrays of objects: + // { + // val: axis value, + // pad: pixel padding, + // extrapad: boolean, should this val get 5% additional padding + // } + ax._min = []; + ax._max = []; - // 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, - x2 = x + axSign * 0.01, - frac = _$lib_363.roundUp(_$lib_363.mod(x2, 1), tickset, axrev); + // initialize the category list, if there is one, so we start over + // to be filled in later by ax.d2c + ax._categories = (ax._initialCategories || []).slice(); - return Math.floor(x2) + - Math.log(_$d3_68.round(Math.pow(10, frac), 1)) / Math.LN10; + // Build the lookup map for initialized categories + ax._categoriesMap = {}; + for(var j = 0; j < ax._categories.length; j++) { + ax._categoriesMap[ax._categories[j]] = j; + } + }; + + // 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_71.time.format.utc; + ax._extraFormat = fullLayout._extraFormat; } - else throw 'unrecognized dtick ' + String(dtick); + // 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_71.format; + + // and for bar charts and box plots: reset forced minimum tick spacing + delete ax._minDtick; + delete ax._forceTick0; }; -// calculate the first tick on an axis -axes.tickFirst = function(ax) { - var r2l = ax.r2l || Number, - rng = _$lib_363.simpleMap(ax.range, r2l), - axrev = rng[1] < rng[0], - sRound = axrev ? Math.floor : Math.ceil, - // add a tiny extra bit to make sure we get ticks - // that may have been rounded out - r0 = rng[0] * 1.0001 - rng[1] * 0.0001, - dtick = ax.dtick, - tick0 = r2l(ax.tick0); +var _$axes_470 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(_$fastIsnumeric_78(dtick)) { - var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; - // make sure no ticks outside the category list - if(ax.type === 'category') { - tmin = _$lib_363.constrain(tmin, 0, ax._categories.length - 1); - } - return tmin; - } +'use strict'; - var tType = dtick.charAt(0), - dtNum = Number(dtick.substr(1)); +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; + +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$titles_394 = require('../../components/titles'); */; +/* removed: var _$color_301 = require('../../components/color'); */; +/* removed: var _$drawing_326 = require('../../components/drawing'); */; + +/* removed: var _$numerical_404 = require('../../constants/numerical'); */; +var ONEAVGYEAR = _$numerical_404.ONEAVGYEAR; +var ONEAVGMONTH = _$numerical_404.ONEAVGMONTH; +var __ONEDAY_470 = _$numerical_404.ONEDAY; +var __ONEHOUR_470 = _$numerical_404.ONEHOUR; +var __ONEMIN_470 = _$numerical_404.ONEMIN; +var __ONESEC_470 = _$numerical_404.ONESEC; +var MINUS_SIGN = _$numerical_404.MINUS_SIGN; +var __BADNUM_470 = _$numerical_404.BADNUM; + +var MID_SHIFT = _$alignment_401.MID_SHIFT; +var __LINE_SPACING_470 = _$alignment_401.LINE_SPACING; + +var axes = _$axes_470 = {}; + +axes.setConvert = _$setConvert_488; +/* removed: var _$autoType_471 = require('./axis_autotype'); */; + +/* removed: var _$axis_ids_473 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_473.id2name; +axes.name2id = _$axis_ids_473.name2id; +axes.cleanId = _$axis_ids_473.cleanId; +axes.list = _$axis_ids_473.list; +axes.listIds = _$axis_ids_473.listIds; +axes.getFromId = _$axis_ids_473.getFromId; +axes.getFromTrace = _$axis_ids_473.getFromTrace; + +/* removed: var _$autorange_469 = require('./autorange'); */; +axes.expand = _$autorange_469.expand; +axes.getAutoRange = _$autorange_469.getAutoRange; - // Dates: months (or years) - if(tType === 'M') { - var cnt = 0, - t0 = tick0, - t1, - mult, - newDTick; +/* + * 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 = {}; - // 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_363.error('tickFirst did not converge', ax); - return t0; - } + if(!dflt) dflt = axlist[0] || extraOption; + if(!extraOption) extraOption = dflt; - // Log scales: Linear, Digits - else if(tType === 'L') { - return Math.log(sRound( - (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; - } - else if(tType === 'D') { - var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_363.roundUp(_$lib_363.mod(r0, 1), tickset, axrev); + // data-ref annotations are not supported in gl2d yet - return Math.floor(r0) + - Math.log(_$d3_68.round(Math.pow(10, frac), 1)) / Math.LN10; - } - else throw 'unrecognized dtick ' + String(dtick); + attrDef[refAttr] = { + valType: 'enumerated', + values: axlist.concat(extraOption ? [extraOption] : []), + dflt: dflt + }; + + // xref, yref + return _$lib_425.coerce(containerIn, containerOut, attrDef, refAttr); }; -// 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) { - var out = tickTextObj(ax, x), - hideexp, - arrayMode = ax.tickmode === 'array', - extraPrecision = hover || arrayMode, - i, - tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; +/* + * 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(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_363.simpleMap(ax.range, ax.r2l), - 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; - } + if(axRef === 'paper' || axRef === 'pixel') { + cleanPos = _$lib_425.ensureNumber; + pos = coerce(attr, dflt); + } else { + var ax = axes.getFromId(gd, axRef); + dflt = ax.fraction2r(dflt); + pos = coerce(attr, dflt); + cleanPos = ax.cleanPos; } - function isHidden(showAttr) { - var first_or_last; + containerOut[attr] = cleanPos(pos); +}; - if(showAttr === undefined) return true; - if(hover) return showAttr === 'none'; +axes.cleanPosition = function(pos, gd, axRef) { + var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? + _$lib_425.ensureNumber : + axes.getFromId(gd, axRef).cleanPos; - first_or_last = { - first: ax._tmin, - last: ax._tmax - }[showAttr]; + return cleanPos(pos); +}; - return showAttr !== 'all' && x !== first_or_last; - } +var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { + var ax; - if(hover) { - hideexp = 'never'; + // 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_471(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]); + } + } } else { - hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; + ax = axes.getFromTrace(gd, trace, d2cTarget); } - if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); - else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); - else if(ax.type === 'category') formatCategory(ax, out); - else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); - else formatLinear(ax, out, hover, extraPrecision, hideexp); + // if 'target' has corresponding axis + // -> use setConvert method + if(ax) return {d2c: ax.d2c, c2d: ax.c2d}; - // add prefix and suffix - if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; - if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; + // special case for 'ids' + // -> cast to String + if(d2cTarget === 'ids') return {d2c: toString, c2d: toString}; - return out; + // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size') + // -> cast to Number + + return {d2c: toNum, c2d: toNum}; }; -/** - * 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_407 && val2 !== val) { - return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); - } +function toNum(v) { return +v; } +function toString(v) { return String(v); } - var logOffScale = (ax.type === 'log' && val <= 0); - var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text; +axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { + return getDataConversions(gd, trace, target, targetArray).d2c; +}; - if(logOffScale) { - return val === 0 ? '0' : MINUS_SIGN + tx; - } +// 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'; +}; - // 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; +// 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'].indexOf(ax.type) !== -1 || !allow) { + ax._minDtick = 0; + } + // undefined means there's nothing there yet + else if(ax._minDtick === undefined) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } + else if(ax._minDtick) { + // existing minDtick is an integer multiple of newDiff + // (within rounding err) + // and forceTick0 can be shifted to newFirst + if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && + (((newFirst - ax._forceTick0) / newDiff % 1) + + 1.000001) % 1 < 2e-6) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } + // 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 + else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || + (((newFirst - ax._forceTick0) / ax._minDtick % 1) + + 1.000001) % 1 > 2e-6) { + ax._minDtick = 0; + } + } }; -function tickTextObj(ax, x, text) { - var tf = ax.tickfont || {}; +// 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), + hasOneAxisChanged = false; - return { - x: x, - dx: 0, - dy: 0, - text: text || '', - fontSize: tf.size, - font: tf.family, - fontColor: tf.color - }; -} + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; -function formatDate(ax, out, hover, extraPrecision) { - var tr = ax._tickround, - fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); + var isNew = (ax._rangeInitial === undefined); + var hasChanged = ( + isNew || !( + ax.range[0] === ax._rangeInitial[0] && + ax.range[1] === ax._rangeInitial[1] + ) + ); - if(extraPrecision) { - // second or sub-second precision: extra always shows max digits. - // for other fields, extra precision just adds one field. - if(_$fastIsnumeric_78(tr)) tr = 4; - else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; + if((isNew && ax.autorange === false) || (overwrite && hasChanged)) { + ax._rangeInitial = ax.range.slice(); + hasOneAxisChanged = true; + } } - var dateStr = _$lib_363.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), - headStr; + return hasOneAxisChanged; +}; - var splitIndex = dateStr.indexOf('\n'); - if(splitIndex !== -1) { - headStr = dateStr.substr(splitIndex + 1); - dateStr = dateStr.substr(0, splitIndex); - } +// save a copy of the initial spike visibility +axes.saveShowSpikeInitial = function(gd, overwrite) { + var axList = axes.list(gd, '', true), + hasOneAxisChanged = false, + allSpikesEnabled = 'on'; - 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!) + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; - // 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$/, ''); - } - } + var isNew = (ax._showSpikeInitial === undefined); + var hasChanged = ( + isNew || !( + ax.showspikes === ax._showspikes + ) + ); - 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 : ''); + if((isNew) || (overwrite && hasChanged)) { + ax._showSpikeInitial = ax.showspikes; + hasOneAxisChanged = true; } - else if(!ax._inCalcTicks || (headStr !== ax._prevDateHead)) { - dateStr += '
' + headStr; - ax._prevDateHead = headStr; + + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; } } + gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + return hasOneAxisChanged; +}; - out.text = dateStr; -} +axes.autoBin = function(data, ax, nbins, is2d, calendar) { + var dataMin = _$lib_425.aggNums(Math.min, null, data), + dataMax = _$lib_425.aggNums(Math.max, null, data); -function formatLog(ax, out, hover, extraPrecision, hideexp) { - var dtick = ax.dtick, - x = out.x, - tickformat = ax.tickformat; + if(!calendar) calendar = ax.calendar; - 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(ax.type === 'category') { + return { + start: dataMin - 0.5, + end: dataMax + 0.5, + size: 1, + _dataSpan: dataMax - dataMin, + }; } - if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; + 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_425.distinctVals(data), + msexp = Math.pow(10, Math.floor( + Math.log(distinctData.minDiff) / Math.LN10)), + minSize = msexp * _$lib_425.roundUp( + distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); + size0 = Math.max(minSize, 2 * _$lib_425.stdev(data) / + Math.pow(data.length, is2d ? 0.25 : 0.4)); - if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { - out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); + // fallback if ax.d2c output BADNUMs + // e.g. when user try to plot categorical bins + // on a layout.xaxis.type: 'linear' + if(!_$fastIsnumeric_135(size0)) size0 = 1; } - else if(_$fastIsnumeric_78(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_363.mod(x + 0.01, 1) < 0.1))) { - var p = Math.round(x); - if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || - (isSIFormat(ax.exponentformat) && beyondSI(p))) { - if(p === 0) out.text = 1; - else if(p === 1) out.text = '10'; - else if(p > 1) out.text = '10' + p + ''; - else out.text = '10' + MINUS_SIGN + -p + ''; - out.fontSize *= 1.25; - } - else { - out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover'); - if(dtick === 'D1' && ax._id.charAt(0) === 'y') { - out.dy -= out.fontSize / 6; - } - } + // piggyback off autotick code to make "nice" bin sizes + var dummyAx; + if(ax.type === 'log') { + dummyAx = { + type: 'linear', + range: [dataMin, dataMax] + }; } - else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_363.mod(x, 1)))); - out.fontSize *= 0.75; + else { + dummyAx = { + type: ax.type, + range: _$lib_425.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + calendar: calendar + }; } - else throw 'unrecognized dtick ' + String(dtick); + axes.setConvert(dummyAx); - // 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); - } - } - } -} + axes.autoTicks(dummyAx, size0); + var binStart = axes.tickIncrement( + axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar); + var binEnd, bincount; -function formatCategory(ax, out) { - var tt = ax._categories[Math.round(out.x)]; - if(tt === undefined) tt = ''; - out.text = String(tt); -} + // 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 dummyAx.dtick === 'number') { + binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); -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'; + bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick); + binEnd = binStart + bincount * dummyAx.dtick; } - out.text = numFormat(out.x, ax, hideexp, extraPrecision); -} + 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, dummyAx.dtick, dataMin, calendar); + } -function formatAngle(ax, out, hover, extraPrecision, hideexp) { - if(ax.thetaunit === 'radians' && !hover) { - var num = out.x / 180; + // 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, dummyAx.dtick, false, calendar); + bincount++; + } + } - if(num === 0) { - out.text = '0'; - } else { - var frac = num2frac(num); + return { + start: ax.c2r(binStart, 0, calendar), + end: ax.c2r(binEnd, 0, calendar), + size: dummyAx.dtick, + _dataSpan: dataMax - dataMin + }; +}; - if(frac[1] >= 100) { - out.text = numFormat(_$lib_363.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(''); - } +function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { + var edgecount = 0, + midcount = 0, + intcount = 0, + blankCount = 0; - if(isNeg) out.text = MINUS_SIGN + out.text; - } - } - } else { - out.text = numFormat(out.x, ax, hideexp, extraPrecision); + function nearEdge(v) { + // is a value within 1% of a bin edge? + return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; } -} -// 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; - } + for(var i = 0; i < data.length; i++) { + if(data[i] % 1 === 0) intcount++; + else if(!_$fastIsnumeric_135(data[i])) blankCount++; - function findGCD(a, b) { - return almostEq(b, 0) ? a : findGCD(b, a % b); + if(nearEdge(data[i])) edgecount++; + if(nearEdge(data[i] + ax.dtick / 2)) midcount++; } + var dataCount = data.length - blankCount; - function findPrecision(n) { - var e = 1; - while(!almostEq(Math.round(n * e) / e, n)) { - e *= 10; + if(intcount === dataCount && ax.type !== 'date') { + // 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 + if(ax.dtick < 1) { + binStart = dataMin - 0.5 * ax.dtick; + } + // 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. + else { + binStart -= 0.5; + if(binStart + ax.dtick < dataMin) binStart += ax.dtick; } - 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) - ]; + 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; } -// 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'; -} +function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { + var stats = _$lib_425.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; -// 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; -} + if(stats.exactDays > threshold) { + var numMonths = Number(dtick.substr(1)); -function numFormat(v, ax, fmtoverride, hover) { - // negative? - var isNeg = v < 0, - // max number of digits past decimal point to show - tickRound = ax._tickround, - exponentFormat = fmtoverride || ax.exponentformat || 'B', - exponent = ax._tickexponent, - tickformat = axes.getTickFormat(ax), - separatethousands = ax.separatethousands; + 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_470 * 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_470 * 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_470 / 2; + } + var nextBinStart = axes.tickIncrement(binStart, dtick); - // 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 : - (_$fastIsnumeric_78(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(nextBinStart <= dataMin) return nextBinStart; } + return binStart; +} - if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); +// ---------------------------------------------------- +// Ticks and grids +// ---------------------------------------------------- - // 'epsilon' - rounding increment - var e = Math.pow(10, -tickRound) / 2; +// ensure we have tick0, dtick, and tick rounding calculated +axes.prepTicks = function(ax) { + var rng = _$lib_425.simpleMap(ax.range, ax.r2l); - // 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; + // calculate max number of (auto) ticks to display based on plot size + if(ax.tickmode === 'auto' || !ax.dtick) { + var nt = ax.nticks, + minPx; + if(!nt) { + if(ax.type === 'category') { + 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_425.constrain(ax._length / minPx, 4, 9) + 1; + } - // 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'; + // radial axes span half their domain, + // multiply nticks value by two to get correct number of auto ticks. + if(ax._name === 'radialaxis') nt *= 2; } - else { - v = String(v); - var dp = v.indexOf('.') + 1; - if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); + + // 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); } - // insert appropriate decimal point and thousands separator - v = _$lib_363.numSeparate(v, ax._separators, separatethousands); } - // add exponent - if(exponent && exponentFormat !== 'hide') { - if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; + // check for missing tick0 + if(!ax.tick0) { + ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0; + } - var signedExponent; - if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; - else if(exponentFormat !== 'power') signedExponent = '+' + exponent; - else signedExponent = String(exponent); + // now figure out rounding of tick values + autoTickRound(ax); +}; - if(exponentFormat === 'e') { - v += 'e' + signedExponent; - } - else if(exponentFormat === 'E') { - v += 'E' + 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]; - } - } +// 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_425.simpleMap(ax.range, ax.r2l); - // 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; -} + // 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); -axes.getTickFormat = function(ax) { - var i; + // find the first tick + ax._tmin = axes.tickFirst(ax); - function convertToMs(dtick) { - return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH; - } + // 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]); - 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; - } - } + // No visible ticks? Quit. + // I've only seen this on category axes with all categories off the edge. + if((ax._tmin < startTick) !== axrev) return []; - 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)); + // return the full set of tick vals + var vals = []; + if(ax.type === 'category') { + endTick = (axrev) ? Math.max(-0.5, endTick) : + Math.min(ax._categories.length - 0.5, endTick); } - 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 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(vals.length > maxTicks || x === xPrevious) break; + xPrevious = x; + + vals.push(x); } - var tickstop; - if(ax.tickformatstops && ax.tickformatstops.length > 0) { - switch(ax.type) { - case 'date': - case 'linear': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; - } - case 'log': { - for(i = 0; i < ax.tickformatstops.length; i++) { - if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { - tickstop = ax.tickformatstops[i]; - break; - } - } - break; - } - default: - } + // If same angle over a full circle, the last tick vals is a duplicate. + // TODO must do something similar for angular date axes. + if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) { + vals.pop(); } - 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 -axes.getSubplots = function(gd, ax) { - var subplotObj = gd._fullLayout._subplots; - var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); + // save the last tick as well as first, so we can + // show the exponent only on the last one + ax._tmax = vals[vals.length - 1]; - var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; + // 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; - out.sort(function(a, b) { - var aParts = a.substr(1).split('y'); - var bParts = b.substr(1).split('y'); + var ticksOut = new Array(vals.length); + for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]); - if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; - return +aParts[0] - +bParts[0]; - }); + ax._inCalcTicks = false; - return out; + return ticksOut; }; -// find all subplots with axis 'ax' -axes.findSubplotsWithAxis = function(subplots, ax) { - var axMatch = new RegExp( - (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') - ); - var subplotsWithAxis = []; +function arrayTicks(ax) { + var vals = ax.tickvals, + text = ax.ticktext, + ticksOut = new Array(vals.length), + rng = _$lib_425.simpleMap(ax.range, ax.r2l), + r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, + r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, + tickMin = Math.min(r0expanded, r1expanded), + tickMax = Math.max(r0expanded, r1expanded), + vali, + i, + j = 0; - for(var i = 0; i < subplots.length; i++) { - var sp = subplots[i]; - if(axMatch.test(sp)) subplotsWithAxis.push(sp); - } + // 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 = []; - return subplotsWithAxis; -}; + // make sure showing ticks doesn't accidentally add new categories + var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; -// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings -axes.makeClipPaths = function(gd) { - var fullLayout = gd._fullLayout; - 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; + // 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(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]}); + for(i = 0; i < vals.length; i++) { + 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++; } } - // 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; }); + if(j < vals.length) ticksOut.splice(j, vals.length - j); - axClips.enter().append('clipPath') - .classed('axesclip', true) - .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; }) - .append('rect'); + return ticksOut; +} - axClips.exit().remove(); +var roundBase10 = [2, 5, 10], + roundBase24 = [1, 2, 3, 6, 12], + roundBase60 = [1, 2, 5, 10, 15, 30], + // 2&3 day ticks are weird, but need something btwn 1&7 + 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 + roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1], + roundLog2 = [-0.301, 0, 0.301, 0.699, 1], + // N.B. `thetaunit; 'radians' angular axes must be converted to degrees + roundAngles = [15, 30, 45, 90, 180]; - axClips.each(function(d) { - _$d3_68.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 - }); - }); -}; +function roundDTick(roughDTick, base, roundingSet) { + return base * _$lib_425.roundUp(roughDTick / base, roundingSet); +} -// doTicks: draw ticks, grids, and tick labels -// axid: 'x', 'y', 'x2' etc, -// blank to do all, -// 'redraw' to force full redraw, and reset: -// ax._r (stored range for use by zoom/pan) -// ax._rl (stored linearized range for use by zoom/pan) -// or can pass in an axis object directly -axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; +// 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; - // allow passing an independent axis object instead of id - if(typeof axid === 'object') { - ax = axid; - axid = ax._id; - independent = true; + function getBase(v) { + return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); } - else { - ax = axes.getFromId(gd, axid); - if(axid === 'redraw') { - fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); - fullLayout._infolayer.select('.g-' + xa._id + 'title').remove(); - fullLayout._infolayer.select('.g-' + ya._id + 'title').remove(); - }); - } + if(ax.type === 'date') { + ax.tick0 = _$lib_425.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(!axid || axid === 'redraw') { - return _$lib_363.syncOrAsync(axes.list(gd, '', true).map(function(ax) { - return function() { - if(!ax._id) return; - var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_363.simpleMap(ax._r, ax.r2l); - } - return axDone; - }; - })); + 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_470) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_470, 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_425.dateTick0(ax.calendar, true); + } + else if(roughX2 > __ONEHOUR_470) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_470, roundBase24); + } + else if(roughX2 > __ONEMIN_470) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_470, roundBase60); + } + else if(roughX2 > __ONESEC_470) { + ax.dtick = roundDTick(roughDTick, __ONESEC_470, roundBase60); + } + else { + // milliseconds + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); } } + else if(ax.type === 'log') { + ax.tick0 = 0; + var rng = _$lib_425.simpleMap(ax.range, ax.r2l); - // set scaling to pixels - ax.setScale(); - - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_264.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_264.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_264.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; - - if(ax._counterangle && ax.ticks === 'outside') { - var caRad = ax._counterangle * Math.PI / 180; - labelStandoff = ax.ticklen * Math.cos(caRad) + 1; - labelShift = ax.ticklen * Math.sin(caRad); - } - - if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { - labelStandoff += 0.2 * ax.tickfont.size; - } + 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); - // positioning arguments for x vs y axes - if(axLetter === 'x') { - sides = ['bottom', 'top']; - transfn = ax._transfn || function(d) { - return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); - } - else return 'M0,' + shift + 'v' + len; - }; + // 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(axLetter === 'y') { - sides = ['left', 'right']; - transfn = ax._transfn || function(d) { - return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; - }; - tickpathfn = function(shift, len) { - if(ax._counterangle) { - var caRad = ax._counterangle * Math.PI / 180; - return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); - } - else return 'M' + shift + ',0h' + len; - }; + else if(ax.type === 'category') { + ax.tick0 = 0; + ax.dtick = Math.ceil(Math.max(roughDTick, 1)); } - else if(axid === 'angular') { - sides = ['left', 'right']; - transfn = ax._transfn; - tickpathfn = function(shift, len) { - return 'M' + shift + ',0h' + len; - }; + else if(ax._id === 'angular') { + ax.tick0 = 0; + base = 1; + ax.dtick = roundDTick(roughDTick, base, roundAngles); } else { - _$lib_363.warn('Unrecognized doTicks axis:', axid); - return; - } - var axside = ax.side || sides[0], - // which direction do the side[0], side[1], and free ticks go? - // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; - if((ax.ticks !== 'inside') === (axLetter === 'x')) { - ticksign = ticksign.map(function(v) { return -v; }); + // auto ticks always start at 0 + ax.tick0 = 0; + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); } - if(!ax.visible) return; + // prevent infinite loops + if(ax.dtick === 0) ax.dtick = 1; - if(ax._tickFilter) { - vals = vals.filter(ax._tickFilter); + // TODO: this is from log axis histograms with autorange off + if(!_$fastIsnumeric_135(ax.dtick) && typeof ax.dtick !== 'string') { + var olddtick = ax.dtick; + ax.dtick = 1; + throw 'ax.dtick error: ' + String(olddtick); } +}; - // remove zero lines, grid lines, and inside ticks if they're within - // 1 pixel of the end - // The key case here is removing zero lines when the axis bound is zero. - function clipEnds(d) { - var p = ax.l2p(d.x); - return (p > 1 && p < ax._length - 1); - } - var valsClipped = vals.filter(clipEnds); +// 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; - // don't clip angular values - if(ax._id === 'angular') { - valsClipped = vals; + ax._tickexponent = 0; + if(!_$fastIsnumeric_135(dtick) && typeof dtick !== 'string') { + dtick = 1; } - function drawTicks(container, tickpath) { - var ticks = container.selectAll('path.' + tcls) - .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); - if(tickpath && ax.ticks) { - ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) - .classed('crisp', 1) - .call(_$color_239.stroke, ax.tickcolor) - .style('stroke-width', tickWidth + 'px') - .attr('d', tickpath); - ticks.attr('transform', transfn); - ticks.exit().remove(); - } - else ticks.remove(); + if(ax.type === 'category') { + 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), + tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''), + tick0len = tick0str.length; - function drawLabels(container, position) { - // tick labels - for now just the main labels. - // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); - - if(!_$fastIsnumeric_78(position)) { - tickLabels.remove(); - drawAxTitle(); - return; + 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'; } - if(!ax.showticklabels) { - tickLabels.remove(); - drawAxTitle(); - calcBoundingBox(); - return; + else if((dtick >= __ONEDAY_470 && tick0len <= 10) || (dtick >= __ONEDAY_470 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_470 && tick0len <= 16) || (dtick >= __ONEHOUR_470)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_470 && tick0len <= 19) || (dtick >= __ONEMIN_470)) 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; } + } + else if(_$fastIsnumeric_135(dtick) || dtick.charAt(0) === 'L') { + // linear or log (except D1, D2) + var rng = ax.range.map(ax.r2d || Number); + if(!_$fastIsnumeric_135(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 labelx, labely, labelanchor, labelpos0, flipit; - if(axLetter === 'x') { - flipit = (axside === 'bottom') ? 1 : -1; - labelx = function(d) { return d.dx + labelShift * flipit; }; - labelpos0 = position + (labelStandoff + pad) * flipit; - labely = function(d) { - return d.dy + labelpos0 + d.fontSize * - ((axside === 'bottom') ? 1 : -0.2); - }; - labelanchor = function(angle) { - if(!_$fastIsnumeric_78(angle) || angle === 0 || angle === 180) { - return 'middle'; - } - return (angle * flipit < 0) ? 'end' : 'start'; - }; - } - else if(axLetter === 'y') { - flipit = (axside === 'right') ? 1 : -1; - labely = function(d) { - return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; - }; - labelx = function(d) { - return d.dx + position + (labelStandoff + pad + - ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; - }; - labelanchor = function(angle) { - if(_$fastIsnumeric_78(angle) && Math.abs(angle) === 90) { - return 'middle'; - } - return axside === 'right' ? 'start' : 'end'; - }; - } - else if(axid === 'angular') { - ax._labelShift = labelShift; - ax._labelStandoff = labelStandoff; - ax._pad = pad; + var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1])); - labelx = ax._labelx; - labely = ax._labely; - labelanchor = ax._labelanchor; + 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; } + } + // D1 or D2 (log) + else ax._tickround = null; +} - var maxFontSize = 0, - autoangle = 0, - labelsReady = []; - tickLabels.enter().append('g').classed(tcls, 1) - .append('text') - // only so tex has predictable alignment that we can - // alter later - .attr('text-anchor', 'middle') - .each(function(d) { - var thisLabel = _$d3_68.select(this), - newPromise = gd._promises.length; - thisLabel - .call(_$svg_text_utils_386.positionText, labelx(d), labely(d)) - .call(_$drawing_264.font, d.font, d.fontSize, d.fontColor) - .text(d.text) - .call(_$svg_text_utils_386.convertToTspans, gd); - newPromise = gd._promises[newPromise]; - if(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, ax.tickangle); - })); - } - else { - // sync label: just position it now. - positionLabels(thisLabel, ax.tickangle); - } - }); - tickLabels.exit().remove(); - - tickLabels.each(function(d) { - maxFontSize = Math.max(maxFontSize, d.fontSize); - }); - - if(axid === 'angular') { - tickLabels.each(function(d) { - _$d3_68.select(this).select('text') - .call(_$svg_text_utils_386.positionText, labelx(d), labely(d)); - }); - } +// 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; - // How much to shift a multi-line label to center it vertically. - function getAnchorHeight(lineCount, lineHeight, angle) { - var h = (lineCount - 1) * lineHeight; - if(axLetter === 'x') { - if(angle < -60 || 60 < angle) { - return -0.5 * h; - } else if(axside === 'top') { - return -h; - } - } else { - angle *= axside === 'left' ? 1 : -1; - if(angle < -30) { - return -h; - } else if(angle < 30) { - return -0.5 * h; - } - } - return 0; - } + // includes linear, all dates smaller than month, and pure 10^n in log + if(_$fastIsnumeric_135(dtick)) return x + axSign * dtick; - function positionLabels(s, angle) { - s.each(function(d) { - var anchor = labelanchor(angle, d); - var thisLabel = _$d3_68.select(this), - mathjaxGroup = thisLabel.select('.text-math-group'), - transform = transfn.call(thisLabel.node(), d) + - ((_$fastIsnumeric_78(angle) && +angle !== 0) ? - (' rotate(' + angle + ',' + labelx(d) + ',' + - (labely(d) - d.fontSize / 2) + ')') : - ''); - var anchorHeight = getAnchorHeight( - _$svg_text_utils_386.lineCount(thisLabel), - __LINE_SPACING_407 * d.fontSize, - _$fastIsnumeric_78(angle) ? +angle : 0); - if(anchorHeight) { - transform += ' translate(0, ' + anchorHeight + ')'; - } - if(mathjaxGroup.empty()) { - thisLabel.select('text').attr({ - transform: transform, - 'text-anchor': anchor - }); - } - else { - var mjShift = - _$drawing_264.bBox(mathjaxGroup.node()).width * - {end: -0.5, start: 0.5}[anchor]; - mathjaxGroup.attr('transform', transform + - (mjShift ? 'translate(' + mjShift + ',0)' : '')); - } - }); - } + // everything else is a string, one character plus a number + var tType = dtick.charAt(0), + dtSigned = axSign * Number(dtick.substr(1)); - // 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, ax._lastangle || ax.tickangle); + // Dates: months (or years - see Lib.incrementMonth) + if(tType === 'M') return _$lib_425.incrementMonth(x, dtSigned, calendar); - function allLabelsReady() { - return labelsReady.length && Promise.all(labelsReady); - } + // Log scales: Linear, Digits + else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; - function fixLabelOverlaps() { - positionLabels(tickLabels, ax.tickangle); + // 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, + x2 = x + axSign * 0.01, + frac = _$lib_425.roundUp(_$lib_425.mod(x2, 1), tickset, axrev); - // check for auto-angling if x labels overlap - // don't auto-angle at all for log axes with - // base and digit format - if(axLetter === 'x' && !_$fastIsnumeric_78(ax.tickangle) && - (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { - var lbbArray = []; - tickLabels.each(function(d) { - var s = _$d3_68.select(this), - thisLabel = s.select('.text-math-group'), - x = ax.l2p(d.x); - if(thisLabel.empty()) thisLabel = s.select('text'); + return Math.floor(x2) + + Math.log(_$d3_71.round(Math.pow(10, frac), 1)) / Math.LN10; + } + else throw 'unrecognized dtick ' + String(dtick); +}; - var bb = _$drawing_264.bBox(thisLabel.node()); +// calculate the first tick on an axis +axes.tickFirst = function(ax) { + var r2l = ax.r2l || Number, + rng = _$lib_425.simpleMap(ax.range, r2l), + axrev = rng[1] < rng[0], + sRound = axrev ? Math.floor : Math.ceil, + // add a tiny extra bit to make sure we get ticks + // that may have been rounded out + r0 = rng[0] * 1.0001 - rng[1] * 0.0001, + dtick = ax.dtick, + tick0 = r2l(ax.tick0); - 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 - }); - }); - for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_363.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { - // any overlap at all - set 30 degrees - autoangle = 30; - break; - } - } - if(autoangle) { - var tickspacing = Math.abs( - (vals[vals.length - 1].x - vals[0].x) * ax._m - ) / (vals.length - 1); - if(tickspacing < maxFontSize * 2.5) { - autoangle = 90; - } - positionLabels(tickLabels, autoangle); - } - ax._lastangle = autoangle; - } + if(_$fastIsnumeric_135(dtick)) { + var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; - // update the axis title - // (so it can move out of the way if needed) - // TODO: separate out scoot so we don't need to do - // a full redraw of the title (mostly relevant for MathJax) - drawAxTitle(); - return axid + ' done'; + // make sure no ticks outside the category list + if(ax.type === 'category') { + tmin = _$lib_425.constrain(tmin, 0, ax._categories.length - 1); } + return tmin; + } - function calcBoundingBox() { - if(ax.showticklabels) { - var gdBB = gd.getBoundingClientRect(); - var bBox = container.node().getBoundingClientRect(); + var tType = dtick.charAt(0), + dtNum = Number(dtick.substr(1)); - /* - * the way we're going to use this, the positioning that matters - * is relative to the origin of gd. This is important particularly - * if gd is scrollable, and may have been scrolled between the time - * we calculate this and the time we use it - */ + // Dates: months (or years) + if(tType === 'M') { + var cnt = 0, + t0 = tick0, + t1, + mult, + newDTick; - ax._boundingBox = { - width: bBox.width, - height: bBox.height, - left: bBox.left - gdBB.left, - right: bBox.right - gdBB.left, - top: bBox.top - gdBB.top, - bottom: bBox.bottom - gdBB.top - }; - } else { - var gs = fullLayout._size; - var pos; - - // set dummy bbox for ticklabel-less axes - - if(axLetter === 'x') { - pos = ax.anchor === 'free' ? - gs.t + gs.h * (1 - ax.position) : - gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); - - ax._boundingBox = { - top: pos, - bottom: pos, - left: ax._offset, - right: ax._offset + ax._length, - width: ax._length, - height: 0 - }; - } else { - pos = ax.anchor === 'free' ? - gs.l + gs.w * ax.position : - gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; - - ax._boundingBox = { - left: pos, - right: pos, - bottom: ax._offset + ax._length, - top: ax._offset, - height: ax._length, - width: 0 - }; - } + // 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_425.error('tickFirst did not converge', ax); + return t0; + } - /* - * for spikelines: what's the full domain of positions in the - * opposite direction that are associated with this axis? - * This means any axes that we make a subplot with, plus the - * position of the axis itself if it's free. - */ - if(subplots) { - var fullRange = ax._counterSpan = [Infinity, -Infinity]; - - for(i = 0; i < subplots.length; i++) { - var subplot = fullLayout._plots[subplots[i]]; - var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; + // Log scales: Linear, Digits + else if(tType === 'L') { + return Math.log(sRound( + (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10; + } + else if(tType === 'D') { + var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, + frac = _$lib_425.roundUp(_$lib_425.mod(r0, 1), tickset, axrev); - extendRange(fullRange, [ - counterAxis._offset, - counterAxis._offset + counterAxis._length - ]); - } + return Math.floor(r0) + + Math.log(_$d3_71.round(Math.pow(10, frac), 1)) / Math.LN10; + } + else throw 'unrecognized dtick ' + String(dtick); +}; - if(ax.anchor === 'free') { - extendRange(fullRange, (axLetter === 'x') ? - [ax._boundingBox.bottom, ax._boundingBox.top] : - [ax._boundingBox.right, ax._boundingBox.left]); - } - } +// 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) { + var out = tickTextObj(ax, x), + hideexp, + arrayMode = ax.tickmode === 'array', + extraPrecision = hover || arrayMode, + i, + tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; - function extendRange(range, newRange) { - range[0] = Math.min(range[0], newRange[0]); - range[1] = Math.max(range[1], newRange[1]); - } + if(arrayMode && Array.isArray(ax.ticktext)) { + var rng = _$lib_425.simpleMap(ax.range, ax.r2l), + 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 doAutoMargins() { - if(!ax.automargin) { return; } - if(axLetter !== 'x' && axLetter !== 'y') { return; } - - var s = ax.side[0]; - var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; - - if(axLetter === 'x') { - push.y = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 't' ? 1 : 0]); - push[s] += ax._boundingBox.height; - } - else { - push.x = (ax.anchor === 'free' ? ax.position : - ax._anchorAxis.domain[s === 'r' ? 1 : 0]); - push[s] += ax._boundingBox.width; - } + function isHidden(showAttr) { + var first_or_last; - if(ax.title !== fullLayout._dfltTitle[axLetter]) { - push[s] += ax.titlefont.size; - } + if(showAttr === undefined) return true; + if(hover) return showAttr === 'none'; - var pushKey = ax._name + '.automargin'; - var prevPush = fullLayout._pushmargin[pushKey]; - if(!prevPush || prevPush[s].size < push[s]) { - _$plots_444.autoMargin(gd, pushKey, push); - } - } + first_or_last = { + first: ax._tmin, + last: ax._tmax + }[showAttr]; - var done = _$lib_363.syncOrAsync([ - allLabelsReady, - fixLabelOverlaps, - calcBoundingBox, - doAutoMargins - ]); - if(done && done.then) gd._promises.push(done); - return done; + return showAttr !== 'all' && x !== first_or_last; } - function drawAxTitle() { - if(skipTitle) return; - - // now this only applies to regular cartesian axes; colorbars and - // others ALWAYS call doTicks with skipTitle=true so they can - // configure their own titles. - var ax = _$axis_ids_410.getFromId(gd, axid); - - // rangeslider takes over a bottom title so drop it here - if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; + if(hover) { + hideexp = 'never'; + } else { + hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : ''; + } - var avoidSelection = _$d3_68.select(gd).selectAll('g.' + axid + 'tick'); - var avoid = { - selection: avoidSelection, - side: ax.side - }; - var axLetter = axid.charAt(0); - var gs = gd._fullLayout._size; - var offsetBase = 1.5; - var fontSize = ax.titlefont.size; + if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision); + else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp); + else if(ax.type === 'category') formatCategory(ax, out); + else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp); + else formatLinear(ax, out, hover, extraPrecision, hideexp); - var transform, counterAxis, x, y; + // add prefix and suffix + if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; + if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; - if(avoidSelection.size()) { - var translation = _$drawing_264.getTranslate(avoidSelection.node().parentNode); - avoid.offsetLeft = translation.x; - avoid.offsetTop = translation.y; - } + return out; +}; - var titleStandoff = 10 + fontSize * offsetBase + - (ax.linewidth ? ax.linewidth - 1 : 0); +/** + * 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_470 && val2 !== val) { + return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); + } - if(axLetter === 'x') { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_410.getFromId(gd, ax.anchor); + var logOffScale = (ax.type === 'log' && val <= 0); + var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text; - x = ax._offset + ax._length / 2; + if(logOffScale) { + return val === 0 ? '0' : MINUS_SIGN + tx; + } - if(ax.side === 'top') { - y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); - } - else { - y = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1.5 : 0.5); - } - y += counterAxis._offset; + // 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; +}; - if(!avoid.side) avoid.side = 'bottom'; - } - else { - counterAxis = (ax.anchor === 'free') ? - {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_410.getFromId(gd, ax.anchor); +function tickTextObj(ax, x, text) { + var tf = ax.tickfont || {}; - y = ax._offset + ax._length / 2; - if(ax.side === 'right') { - x = counterAxis._length + titleStandoff + - fontSize * (ax.showticklabels ? 1 : 0.5); - } - else { - x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); - } - x += counterAxis._offset; + return { + x: x, + dx: 0, + dy: 0, + text: text || '', + fontSize: tf.size, + font: tf.family, + fontColor: tf.color + }; +} - transform = {rotate: '-90', offset: 0}; - if(!avoid.side) avoid.side = 'left'; - } +function formatDate(ax, out, hover, extraPrecision) { + var tr = ax._tickround, + fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax); - _$titles_332.draw(gd, axid + 'title', { - propContainer: ax, - propName: ax._name + '.title', - placeholder: fullLayout._dfltTitle[axLetter], - avoid: avoid, - transform: transform, - attributes: {x: x, y: y, 'text-anchor': 'middle'} - }); + if(extraPrecision) { + // second or sub-second precision: extra always shows max digits. + // for other fields, extra precision just adds one field. + if(_$fastIsnumeric_135(tr)) tr = 4; + else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; } - function traceHasBarsOrFill(trace, subplot) { - if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_451.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; - return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; + var dateStr = _$lib_425.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + headStr; + + var splitIndex = dateStr.indexOf('\n'); + if(splitIndex !== -1) { + headStr = dateStr.substr(splitIndex + 1); + dateStr = dateStr.substr(0, splitIndex); } - function drawGrid(plotinfo, counteraxis, subplot) { - var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); - var zlcontainer = plotinfo.zerolinelayer; - var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; - var gridpath = ax._gridpath || ((axLetter === 'x' ? - ('M0,' + counteraxis._offset + 'v') : - ('M' + counteraxis._offset + ',0h') - ) + counteraxis._length); - var grid = gridcontainer.selectAll('path.' + gcls) - .data((ax.showgrid === false) ? [] : gridvals, datafn); - grid.enter().append('path').classed(gcls, 1) - .classed('crisp', 1) - .attr('d', gridpath) - .each(function(d) { - if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && - Math.abs(d.x) < ax.dtick / 100) { - _$d3_68.select(this).remove(); - } - }); - grid.attr('transform', transfn) - .call(_$color_239.stroke, ax.gridcolor || '#ddd') - .style('stroke-width', gridWidth + 'px'); - if(typeof gridpath === 'function') grid.attr('d', gridpath); - grid.exit().remove(); + 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!) - // zero line - if(zlcontainer) { - var hasBarsOrFill = false; - for(var i = 0; i < gd._fullData.length; i++) { - if(traceHasBarsOrFill(gd._fullData[i], subplot)) { - hasBarsOrFill = true; - break; - } - } - var rng = _$lib_363.simpleMap(ax.range, ax.r2l), - showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && - (ax.type === 'linear' || ax.type === '-') && gridvals.length && - (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); - var zl = zlcontainer.selectAll('path.' + zcls) - .data(showZl ? [{x: 0, id: axid}] : []); - zl.enter().append('path').classed(zcls, 1).classed('zl', 1) - .classed('crisp', 1) - .attr('d', gridpath) - .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. - zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_410.idSort(da.id, db.id); - }); - }); - zl.attr('transform', transfn) - .call(_$color_239.stroke, ax.zerolinecolor || _$color_239.defaultLine) - .style('stroke-width', zeroLineWidth + 'px'); - zl.exit().remove(); + // 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(independent) { - drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); - if(ax._counteraxis) { - var fictionalPlotinfo = { - gridlayer: ax._gridlayer, - zerolinelayer: ax._zerolinelayer - }; - drawGrid(fictionalPlotinfo, ax._counteraxis); + 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; } - return drawLabels(ax._axislayer, ax._pos); } - else if(fullLayout._has('cartesian')) { - subplots = axes.getSubplots(gd, ax); - - // keep track of which subplots (by main conteraxis) we've already - // drawn grids for, so we don't overdraw overlaying subplots - var finishedGrids = {}; - subplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; - var counterAxis = plotinfo[counterLetter + 'axis']; + out.text = dateStr; +} - var mainCounterID = counterAxis._mainAxis._id; - if(finishedGrids[mainCounterID]) return; - finishedGrids[mainCounterID] = 1; +function formatLog(ax, out, hover, extraPrecision, hideexp) { + var dtick = ax.dtick, + x = out.x, + tickformat = ax.tickformat; - drawGrid(plotinfo, counterAxis, subplot); - }); + 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 = ''; + } - var mainSubplot = ax._mainSubplot; - var mainPlotinfo = fullLayout._plots[mainSubplot]; - var tickSubplots = []; + if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3'; - if(ax.ticks) { - var mainSign = ticksign[2]; - var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); - if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { - tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); - } - drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); + if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { + out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); + } + else if(_$fastIsnumeric_135(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_425.mod(x + 0.01, 1) < 0.1))) { + var p = Math.round(x); + if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || + (isSIFormat(ax.exponentformat) && beyondSI(p))) { + if(p === 0) out.text = 1; + else if(p === 1) out.text = '10'; + else if(p > 1) out.text = '10' + p + ''; + else out.text = '10' + MINUS_SIGN + -p + ''; - tickSubplots = Object.keys(ax._linepositions); + out.fontSize *= 1.25; } - - tickSubplots.map(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; - - var container = plotinfo[axLetter + 'axislayer']; - - // [bottom or left, top or right] - // free and main are handled above - var linepositions = ax._linepositions[subplot] || []; - - function tickPathSide(sidei) { - var tsign = ticksign[sidei]; - return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); + else { + out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover'); + if(dtick === 'D1' && ax._id.charAt(0) === 'y') { + out.dy -= out.fontSize / 6; } - - drawTicks(container, tickPathSide(0) + tickPathSide(1)); - }); - - var mainContainer = mainPlotinfo[axLetter + 'axislayer']; - - return drawLabels(mainContainer, ax._mainLinePosition); + } } -}; - -// 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); + else if(dtick.charAt(0) === 'D') { + out.text = String(Math.round(Math.pow(10, _$lib_425.mod(x, 1)))); + out.fontSize *= 0.75; } -}; - -function makeAxisGroups(gd, traces) { - var groups = [], - i, - j; - - for(i = 0; i < traces.length; i++) { - var groupsi = [], - xi = gd._fullData[traces[i]].xaxis, - yi = gd._fullData[traces[i]].yaxis; - if(!xi || !yi) continue; // not a 2D cartesian trace? + else throw 'unrecognized dtick ' + String(dtick); - for(j = 0; j < groups.length; j++) { - if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { - groupsi.push(j); + // 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; } - } - - if(!groupsi.length) { - groups.push({x: [xi], y: [yi]}); - continue; - } - - var group0 = groups[groupsi[0]], - 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); + else { + out.dy += out.fontSize / 2; + out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) * + out.fontSize * (x < 0 ? 0.5 : 0.25); } } - 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 formatCategory(ax, out) { + var tt = ax._categories[Math.round(out.x)]; + if(tt === undefined) tt = ''; + out.text = String(tt); } -function swapAxisGroup(gd, xIds, yIds) { - var i, - j, - xFullAxes = [], - yFullAxes = [], - layout = gd.layout; +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); +} - 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])); +function formatAngle(ax, out, hover, extraPrecision, hideexp) { + if(ax.thetaunit === 'radians' && !hover) { + var num = out.x / 180; - var allAxKeys = Object.keys(xFullAxes[0]), - noSwapAttrs = [ - 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' - ], - numericTypes = ['linear', 'log']; + if(num === 0) { + out.text = '0'; + } else { + var frac = num2frac(num); - for(i = 0; i < allAxKeys.length; i++) { - var keyi = allAxKeys[i], - xVal = xFullAxes[0][keyi], - yVal = yFullAxes[0][keyi], - allEqual = true, - coerceLinearX = false, - 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); - } - } + if(frac[1] >= 100) { + out.text = numFormat(_$lib_425.deg2rad(out.x), ax, hideexp, extraPrecision); + } else { + var isNeg = out.x < 0; - // 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_363.swapAttrs(layout.annotations[i], ['?']); + 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); } } -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_363.nestedProperty, - xVal = np(layout[xFullAxes[0]._name], key).get(), - yVal = np(layout[yFullAxes[0]._name], key).get(), - i; - if(key === 'title') { - // special handling of placeholder titles - if(xVal === dfltTitle.x) { - xVal = dfltTitle.y; - } - if(yVal === dfltTitle.y) { - yVal = dfltTitle.x; - } +// 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; } - for(i = 0; i < xFullAxes.length; i++) { - np(layout, xFullAxes[i]._name + '.' + key).set(yVal); + function findGCD(a, b) { + return almostEq(b, 0) ? a : findGCD(b, a % b); } - for(i = 0; i < yFullAxes.length; i++) { - np(layout, yFullAxes[i]._name + '.' + key).set(xVal); + + function findPrecision(n) { + var e = 1; + while(!almostEq(Math.round(n * e) / e, n)) { + e *= 10; + } + return e; } -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 precision = findPrecision(num); + var number = num * precision; + var gcd = Math.abs(findGCD(number, precision)); -'use strict'; + return [ + // numerator + Math.round(number / gcd), + // denominator + Math.round(precision / gcd) + ]; +} -/* removed: var _$d3_68 = require('d3'); */; +// 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']; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; -/* removed: var _$axes_407 = require('./axes'); */; -var axisRegex = _$constants_412.attrRegex; +function isSIFormat(exponentFormat) { + return exponentFormat === 'SI' || exponentFormat === 'B'; +} -var _$transitionAxes_430 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; +// 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 computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; +function numFormat(v, ax, fmtoverride, hover) { + // negative? + var isNeg = v < 0, + // max number of digits past decimal point to show + tickRound = ax._tickround, + exponentFormat = fmtoverride || ax.exponentformat || 'B', + exponent = ax._tickexponent, + tickformat = axes.getTickFormat(ax), + separatethousands = ax.separatethousands; - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + // 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 : + (_$fastIsnumeric_135(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(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); - } - } - if(!update.to) continue; + if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); - update.axisName = axisName; - update.length = axis._length; + // 'epsilon' - rounding increment + var e = Math.pow(10, -tickRound) / 2; - axes.push(axisLetter); + // 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; - updates[axisLetter] = update; - } + // 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; } - - return updates; + // 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_425.numSeparate(v, ax._separators, separatethousands); } - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; - - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; - - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; - - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; - - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); - - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; - } + // add exponent + if(exponent && exponentFormat !== 'hide') { + if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power'; - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + var signedExponent; + if(exponent < 0) signedExponent = MINUS_SIGN + -exponent; + else if(exponentFormat !== 'power') signedExponent = '+' + exponent; + else signedExponent = String(exponent); - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); - } + if(exponentFormat === 'e') { + v += 'e' + signedExponent; + } + else if(exponentFormat === 'E') { + v += 'E' + 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]; } - - return affectedSubplots; } - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); + // 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; +} - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); +axes.getTickFormat = function(ax) { + var i; - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + 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; } - - redrawObjs(fullLayout.annotations || [], _$registry_451.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_451.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_451.getComponentMethod('images', 'draw'), true); } - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; + 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 ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; - - activeAxIds = [xa._id, ya._id]; - - for(i = 0; i < activeAxIds.length; i++) { - _$axes_407.doTicks(gd, activeAxIds[i], true); - } - - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; + 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); + } - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); + var tickstop; + if(ax.tickformatstops && ax.tickformatstops.length > 0) { + switch(ax.type) { + case 'date': + case 'linear': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) { + tickstop = ax.tickformatstops[i]; + break; + } } - - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + break; + } + case 'log': { + for(i = 0; i < ax.tickformatstops.length; i++) { + if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) { + tickstop = ax.tickformatstops[i]; + break; + } + } + break; } + default: } - - redrawObjs(fullLayout.annotations || [], _$registry_451.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_451.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_451.getComponentMethod('images', 'draw'), true); } + return tickstop ? tickstop.value : ax.tickformat; +}; - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; +// 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 +axes.getSubplots = function(gd, ax) { + var subplotObj = gd._fullLayout._subplots; + var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_264.setTranslate, 0, 0) - .call(_$drawing_264.setScale, 1, 1); + var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; - subplot.plot - .call(_$drawing_264.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_264.setScale, 1, 1); + out.sort(function(a, b) { + var aParts = a.substr(1).split('y'); + var bParts = b.substr(1).split('y'); - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; + return +aParts[0] - +bParts[0]; + }); - // 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_264.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_264.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_264.hideOutsideRangePoints, subplot); - } + return out; +}; - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; +// find all subplots with axis 'ax' +axes.findSubplotsWithAxis = function(subplots, ax) { + var axMatch = new RegExp( + (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$') + ); + var subplotsWithAxis = []; - var viewBox = []; + for(var i = 0; i < subplots.length; i++) { + var sp = subplots[i]; + if(axMatch.test(sp)) subplotsWithAxis.push(sp); + } - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + return subplotsWithAxis; +}; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; +// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings +axes.makeClipPaths = function(gd) { + var fullLayout = gd._fullLayout; + 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; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; + 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]}); } + } - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; - - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; - } + // 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; }); - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); + axClips.enter().append('clipPath') + .classed('axesclip', true) + .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; }) + .append('rect'); - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + axClips.exit().remove(); - var editX = !!xUpdate; - var editY = !!yUpdate; + axClips.each(function(d) { + _$d3_71.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 + }); + }); +}; - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; +// doTicks: draw ticks, grids, and tick labels +// axid: 'x', 'y', 'x2' etc, +// blank to do all, +// 'redraw' to force full redraw, and reset: +// ax._r (stored range for use by zoom/pan) +// ax._rl (stored linearized range for use by zoom/pan) +// or can pass in an axis object directly +axes.doTicks = function(gd, axid, skipTitle) { + var fullLayout = gd._fullLayout; + var ax; + var independent = false; - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + // allow passing an independent axis object instead of id + if(typeof axid === 'object') { + ax = axid; + axid = ax._id; + independent = true; + } + else { + ax = axes.getFromId(gd, axid); - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + if(axid === 'redraw') { + fullLayout._paper.selectAll('g.subplot').each(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); + }); + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_264.setTranslate, clipDx, clipDy) - .call(_$drawing_264.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + if(!axid || axid === 'redraw') { + return _$lib_425.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return function() { + if(!ax._id) return; + var axDone = axes.doTicks(gd, ax._id); + ax._r = ax.range.slice(); + ax._rl = _$lib_425.simpleMap(ax._r, ax.r2l); + return axDone; + }; + })); + } + } - subplot.plot - .call(_$drawing_264.setTranslate, plotDx, plotDy) - .call(_$drawing_264.setScale, xScaleFactor, yScaleFactor) + // set scaling to pixels + ax.setScale(); - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_264.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); + var axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_326.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_326.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_326.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_264.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + if(ax._counterangle && ax.ticks === 'outside') { + var caRad = ax._counterangle * Math.PI / 180; + labelStandoff = ax.ticklen * Math.cos(caRad) + 1; + labelShift = ax.ticklen * Math.sin(caRad); } - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); + if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) { + labelStandoff += 0.2 * ax.tickfont.size; } - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; - - axi.range = to.slice(); - } - - // Signal that this transition has completed: - onComplete && onComplete(); - - return _$registry_451.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + // positioning arguments for x vs y axes + if(axLetter === 'x') { + sides = ['bottom', 'top']; + transfn = ax._transfn || function(d) { + return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len); } - }); + else return 'M0,' + shift + 'v' + len; + }; } - - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; - - axi.range = axi._r.slice(); - } - - return _$registry_451.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + else if(axLetter === 'y') { + sides = ['left', 'right']; + transfn = ax._transfn || function(d) { + return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')'; + }; + tickpathfn = function(shift, len) { + if(ax._counterangle) { + var caRad = ax._counterangle * Math.PI / 180; + return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len); } - }); + else return 'M' + shift + ',0h' + len; + }; } - - var t1, t2, raf; - var easeFn = _$d3_68.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 < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } - - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); - } + else if(axid === 'angular') { + sides = ['left', 'right']; + transfn = ax._transfn; + tickpathfn = function(shift, len) { + return 'M' + shift + ',0h' + len; + }; + } + else { + _$lib_425.warn('Unrecognized doTicks axis:', axid); + return; } - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); - - return Promise.resolve(); -}; - -var _$get_data_436 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_451 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_412.SUBPLOT_PATTERN; + var axside = ax.side || sides[0]; + // which direction do the side[0], side[1], and free ticks go? + // then we flip if outside XOR y axis + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + if((ax.ticks !== 'inside') === (axLetter === 'x')) { + ticksign = ticksign.map(function(v) { return -v; }); + } -/** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces - */ -_$get_data_436.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_451.subplotsRegistry[type]; - if(!basePlotModule) return []; + if(!ax.visible) return; - var attr = basePlotModule.attr; - var subplotCalcData = []; + if(ax._tickFilter) { + vals = vals.filter(ax._tickFilter); + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; + // remove zero lines, grid lines, and inside ticks if they're within + // 1 pixel of the end + // The key case here is removing zero lines when the axis bound is zero. + function clipEnds(d) { + var p = ax.l2p(d.x); + return (p > 1 && p < ax._length - 1); + } + var valsClipped = vals.filter(clipEnds); - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + // don't clip angular values + if(ax._id === 'angular') { + valsClipped = vals; } - return subplotCalcData; -}; + function drawTicks(container, tickpath) { + var ticks = container.selectAll('path.' + tcls) + .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); -_$get_data_436.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_451.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; + if(tickpath && ax.ticks) { + ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) + .classed('crisp', 1) + .call(_$color_301.stroke, ax.tickcolor) + .style('stroke-width', tickWidth + 'px') + .attr('d', tickpath); + ticks.attr('transform', transfn); + ticks.exit().remove(); + } + else ticks.remove(); + } - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + function drawLabels(container, position) { + // tick labels - for now just the main labels. + // TODO: mirror labels, esp for subplots + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); - } + if(!_$fastIsnumeric_135(position)) { + tickLabels.remove(); + drawAxTitle(); + return; + } + if(!ax.showticklabels) { + tickLabels.remove(); + drawAxTitle(); + calcBoundingBox(); + return; + } - return moduleCalcData; -}; + var labelx, labely, labelanchor, labelpos0, flipit; + if(axLetter === 'x') { + flipit = (axside === 'bottom') ? 1 : -1; + labelx = function(d) { return d.dx + labelShift * flipit; }; + labelpos0 = position + (labelStandoff + pad) * flipit; + labely = function(d) { + return d.dy + labelpos0 + d.fontSize * + ((axside === 'bottom') ? 1 : -0.2); + }; + labelanchor = function(angle) { + if(!_$fastIsnumeric_135(angle) || angle === 0 || angle === 180) { + return 'middle'; + } + return (angle * flipit < 0) ? 'end' : 'start'; + }; + } + else if(axLetter === 'y') { + flipit = (axside === 'right') ? 1 : -1; + labely = function(d) { + return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit; + }; + labelx = function(d) { + return d.dx + position + (labelStandoff + pad + + ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; + }; + labelanchor = function(angle) { + if(_$fastIsnumeric_135(angle) && Math.abs(angle) === 90) { + return 'middle'; + } + return axside === 'right' ? 'start' : 'end'; + }; + } + else if(axid === 'angular') { + ax._labelShift = labelShift; + ax._labelStandoff = labelStandoff; + ax._pad = pad; -/** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. - * - * @return {array} list of trace objects. - * - */ -_$get_data_436.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_451.subplotsRegistry[type]) return []; + labelx = ax._labelx; + labely = ax._labely; + labelanchor = ax._labelanchor; + } - var attr = _$registry_451.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; + var maxFontSize = 0, + autoangle = 0, + labelsReady = []; + tickLabels.enter().append('g').classed(tcls, 1) + .append('text') + // only so tex has predictable alignment that we can + // alter later + .attr('text-anchor', 'middle') + .each(function(d) { + var thisLabel = _$d3_71.select(this), + newPromise = gd._promises.length; + thisLabel + .call(_$svg_text_utils_449.positionText, labelx(d), labely(d)) + .call(_$drawing_326.font, d.font, d.fontSize, d.fontColor) + .text(d.text) + .call(_$svg_text_utils_449.convertToTspans, gd); + newPromise = gd._promises[newPromise]; + if(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, ax.tickangle); + })); + } + else { + // sync label: just position it now. + positionLabels(thisLabel, ax.tickangle); + } + }); + tickLabels.exit().remove(); - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; - } + tickLabels.each(function(d) { + maxFontSize = Math.max(maxFontSize, d.fontSize); + }); - for(var i = 0; i < data.length; i++) { - trace = data[i]; + if(axid === 'angular') { + tickLabels.each(function(d) { + _$d3_71.select(this).select('text') + .call(_$svg_text_utils_449.positionText, labelx(d), labely(d)); + }); + } - if(type === 'gl2d' && _$registry_451.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); + // How much to shift a multi-line label to center it vertically. + function getAnchorHeight(lineCount, lineHeight, angle) { + var h = (lineCount - 1) * lineHeight; + if(axLetter === 'x') { + if(angle < -60 || 60 < angle) { + return -0.5 * h; + } else if(axside === 'top') { + return -h; + } + } else { + angle *= axside === 'left' ? 1 : -1; + if(angle < -30) { + return -h; + } else if(angle < 30) { + return -0.5 * h; + } } + return 0; } - else { - if(trace[attr] === subplotId) subplotData.push(trace); - } - } - return subplotData; -}; + function positionLabels(s, angle) { + s.each(function(d) { + var anchor = labelanchor(angle, d); + var thisLabel = _$d3_71.select(this), + mathjaxGroup = thisLabel.select('.text-math-group'), + transform = transfn.call(thisLabel.node(), d) + + ((_$fastIsnumeric_135(angle) && +angle !== 0) ? + (' rotate(' + angle + ',' + labelx(d) + ',' + + (labely(d) - d.fontSize / 2) + ')') : + ''); + var anchorHeight = getAnchorHeight( + _$svg_text_utils_449.lineCount(thisLabel), + __LINE_SPACING_470 * d.fontSize, + _$fastIsnumeric_135(angle) ? +angle : 0); + if(anchorHeight) { + transform += ' translate(0, ' + anchorHeight + ')'; + } + if(mathjaxGroup.empty()) { + thisLabel.select('text').attr({ + transform: transform, + 'text-anchor': anchor + }); + } + else { + var mjShift = + _$drawing_326.bBox(mathjaxGroup.node()).width * + {end: -0.5, start: 0.5}[anchor]; + mathjaxGroup.attr('transform', transform + + (mjShift ? 'translate(' + mjShift + ',0)' : '')); + } + }); + } -var _$cartesian_418 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // 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, ax._lastangle || ax.tickangle); + function allLabelsReady() { + return labelsReady.length && Promise.all(labelsReady); + } -'use strict'; + function fixLabelOverlaps() { + positionLabels(tickLabels, ax.tickangle); -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$plots_444 = require('../plots'); */; -var getModuleCalcData = _$get_data_436.getModuleCalcData; + // check for auto-angling if x labels overlap + // don't auto-angle at all for log axes with + // base and digit format + if(axLetter === 'x' && !_$fastIsnumeric_135(ax.tickangle) && + (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { + var lbbArray = []; + tickLabels.each(function(d) { + var s = _$d3_71.select(this), + thisLabel = s.select('.text-math-group'), + x = ax.l2p(d.x); + if(thisLabel.empty()) thisLabel = s.select('text'); -/* removed: var _$axis_ids_410 = require('./axis_ids'); */; -/* removed: var _$constants_412 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_345 = require('../../constants/xmlns_namespaces'); */; + var bb = _$drawing_326.bBox(thisLabel.node()); -_$cartesian_418.name = 'cartesian'; + 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 + }); + }); + for(i = 0; i < lbbArray.length - 1; i++) { + if(_$lib_425.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + // any overlap at all - set 30 degrees + autoangle = 30; + break; + } + } + if(autoangle) { + var tickspacing = Math.abs( + (vals[vals.length - 1].x - vals[0].x) * ax._m + ) / (vals.length - 1); + if(tickspacing < maxFontSize * 2.5) { + autoangle = 90; + } + positionLabels(tickLabels, autoangle); + } + ax._lastangle = autoangle; + } -_$cartesian_418.attr = ['xaxis', 'yaxis']; + // update the axis title + // (so it can move out of the way if needed) + // TODO: separate out scoot so we don't need to do + // a full redraw of the title (mostly relevant for MathJax) + drawAxTitle(); + return axid + ' done'; + } -_$cartesian_418.idRoot = ['x', 'y']; + function calcBoundingBox() { + if(ax.showticklabels) { + var gdBB = gd.getBoundingClientRect(); + var bBox = container.node().getBoundingClientRect(); -_$cartesian_418.idRegex = _$constants_412.idRegex; + /* + * the way we're going to use this, the positioning that matters + * is relative to the origin of gd. This is important particularly + * if gd is scrollable, and may have been scrolled between the time + * we calculate this and the time we use it + */ -_$cartesian_418.attrRegex = _$constants_412.attrRegex; + ax._boundingBox = { + width: bBox.width, + height: bBox.height, + left: bBox.left - gdBB.left, + right: bBox.right - gdBB.left, + top: bBox.top - gdBB.top, + bottom: bBox.bottom - gdBB.top + }; + } else { + var gs = fullLayout._size; + var pos; -_$cartesian_418.attributes = _$attributes_405; + // set dummy bbox for ticklabel-less axes -_$cartesian_418.layoutAttributes = _$layout_attributes_419; + if(axLetter === 'x') { + pos = ax.anchor === 'free' ? + gs.t + gs.h * (1 - ax.position) : + gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]); -_$cartesian_418.supplyLayoutDefaults = _$supplyLayoutDefaults_420; + ax._boundingBox = { + top: pos, + bottom: pos, + left: ax._offset, + right: ax._offset + ax._length, + width: ax._length, + height: 0 + }; + } else { + pos = ax.anchor === 'free' ? + gs.l + gs.w * ax.position : + gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]]; -_$cartesian_418.transitionAxes = _$transitionAxes_430; + ax._boundingBox = { + left: pos, + right: pos, + bottom: ax._offset + ax._length, + top: ax._offset, + height: ax._length, + width: 0 + }; + } + } -_$cartesian_418.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; + /* + * for spikelines: what's the full domain of positions in the + * opposite direction that are associated with this axis? + * This means any axes that we make a subplot with, plus the + * position of the axis itself if it's free. + */ + if(subplots) { + var fullRange = ax._counterSpan = [Infinity, -Infinity]; - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } - - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_410.id2name(xi)] || {}).anchor; - if(!_$constants_412.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); - - if(!allY[yi]) { - allY[yi] = 1; - _$lib_363.pushUnique(yList, yi); - } - } - } + for(i = 0; i < subplots.length; i++) { + var subplot = fullLayout._plots[subplots[i]]; + var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis']; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_410.id2name(yi)] || {}).anchor; - if(!_$constants_412.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + extendRange(fullRange, [ + counterAxis._offset, + counterAxis._offset + counterAxis._length + ]); + } - if(!allX[xi]) { - allX[xi] = 1; - _$lib_363.pushUnique(xList, xi); + if(ax.anchor === 'free') { + extendRange(fullRange, (axLetter === 'x') ? + [ax._boundingBox.bottom, ax._boundingBox.top] : + [ax._boundingBox.right, ax._boundingBox.left]); + } } - } - } - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_412.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } + function extendRange(range, newRange) { + range[0] = Math.min(range[0], newRange[0]); + range[1] = Math.max(range[1], newRange[1]); } } - xi = xi ? _$axis_ids_410.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_410.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } -}; - -_$cartesian_418.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + function doAutoMargins() { + if(!ax.automargin) { return; } + if(axLetter !== 'x' && axLetter !== 'y') { return; } - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var s = ax.side[0]; + var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0}; - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); + if(axLetter === 'x') { + push.y = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 't' ? 1 : 0]); + push[s] += ax._boundingBox.height; + } + else { + push.x = (ax.anchor === 'free' ? ax.position : + ax._anchorAxis.domain[s === 'r' ? 1 : 0]); + push[s] += ax._boundingBox.width; } - }); - } - - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; - - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; - - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; - - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } - cdSubplot.push(cd); - } + if(ax.title !== fullLayout._dfltTitle[axLetter]) { + push[s] += ax.titlefont.size; + } - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; + var pushKey = ax._name + '.automargin'; + var prevPush = fullLayout._pushmargin[pushKey]; + if(!prevPush || prevPush[s].size < push[s]) { + _$plots_506.autoMargin(gd, pushKey, push); } } - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + var done = _$lib_425.syncOrAsync([ + allLabelsReady, + fixLabelOverlaps, + calcBoundingBox, + doAutoMargins + ]); + if(done && done.then) gd._promises.push(done); + return done; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; + function drawAxTitle() { + if(skipTitle) return; - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; + // now this only applies to regular cartesian axes; colorbars and + // others ALWAYS call doTicks with skipTitle=true so they can + // configure their own titles. - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + // rangeslider takes over a bottom title so drop it here + if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); - } -} + var avoid = { + selection: tickLabels, + side: ax.side + }; + var axLetter = axid.charAt(0); + var gs = gd._fullLayout._size; + var offsetBase = 1.5; + var fontSize = ax.titlefont.size; -_$cartesian_418.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + var transform, counterAxis, x, y; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + if(tickLabels.size()) { + var translation = _$drawing_326.getTranslate(tickLabels.node().parentNode); + avoid.offsetLeft = translation.x; + avoid.offsetTop = translation.y; + } + var titleStandoff = 10 + fontSize * offsetBase + + (ax.linewidth ? ax.linewidth - 1 : 0); - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; - } + if(axLetter === 'x') { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : + _$axis_ids_473.getFromId(gd, ax.anchor); - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + x = ax._offset + ax._length / 2; - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + if(ax.side === 'top') { + y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0); + } + else { + y = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1.5 : 0.5); + } + y += counterAxis._offset; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(!avoid.side) avoid.side = 'bottom'; + } + else { + counterAxis = (ax.anchor === 'free') ? + {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : + _$axis_ids_473.getFromId(gd, ax.anchor); - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + y = ax._offset + ax._length / 2; + if(ax.side === 'right') { + x = counterAxis._length + titleStandoff + + fontSize * (ax.showticklabels ? 1 : 0.5); + } + else { + x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0); } + x += counterAxis._offset; + + transform = {rotate: '-90', offset: 0}; + if(!avoid.side) avoid.side = 'left'; } - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + _$titles_394.draw(gd, axid + 'title', { + propContainer: ax, + propName: ax._name + '.title', + placeholder: fullLayout._dfltTitle[axLetter], + avoid: avoid, + transform: transform, + attributes: {x: x, y: y, 'text-anchor': 'middle'} + }); } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); - - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; - - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } - } + function traceHasBarsOrFill(trace, subplot) { + if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; + if(_$registry_514.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; } - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); + var zlcontainer = plotinfo.zerolinelayer; + var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; + var gridpath = ax._gridpath || ((axLetter === 'x' ? + ('M0,' + counteraxis._offset + 'v') : + ('M' + counteraxis._offset + ',0h') + ) + counteraxis._length); + var grid = gridcontainer.selectAll('path.' + gcls) + .data((ax.showgrid === false) ? [] : gridvals, datafn); + grid.enter().append('path').classed(gcls, 1) + .classed('crisp', 1) + .attr('d', gridpath) + .each(function(d) { + if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && + Math.abs(d.x) < ax.dtick / 100) { + _$d3_71.select(this).remove(); + } + }); + grid.attr('transform', transfn) + .call(_$color_301.stroke, ax.gridcolor || '#ddd') + .style('stroke-width', gridWidth + 'px'); + if(typeof gridpath === 'function') grid.attr('d', gridpath); + grid.exit().remove(); - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // zero line + if(zlcontainer) { + var hasBarsOrFill = false; + for(var i = 0; i < gd._fullData.length; i++) { + if(traceHasBarsOrFill(gd._fullData[i], subplot)) { + hasBarsOrFill = true; + break; + } } + var rng = _$lib_425.simpleMap(ax.range, ax.r2l), + showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && + (ax.type === 'linear' || ax.type === '-') && gridvals.length && + (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); + var zl = zlcontainer.selectAll('path.' + zcls) + .data(showZl ? [{x: 0, id: axid}] : []); + zl.enter().append('path').classed(zcls, 1).classed('zl', 1) + .classed('crisp', 1) + .attr('d', gridpath) + .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. + zlcontainer.selectAll('path').sort(function(da, db) { + return _$axis_ids_473.idSort(da.id, db.id); + }); + }); + zl.attr('transform', transfn) + .call(_$color_301.stroke, ax.zerolinecolor || _$color_301.defaultLine) + .style('stroke-width', zeroLineWidth + 'px'); + zl.exit().remove(); } } - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } + if(independent) { + drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen)); + if(ax._counteraxis) { + var fictionalPlotinfo = { + gridlayer: ax._gridlayer, + zerolinelayer: ax._zerolinelayer + }; + drawGrid(fictionalPlotinfo, ax._counteraxis); } + return drawLabels(ax._axislayer, ax._pos); } -}; - -_$cartesian_418.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); - - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_363.identity); + else if(fullLayout._has('cartesian')) { + subplots = axes.getSubplots(gd, ax); - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + // keep track of which subplots (by main conteraxis) we've already + // drawn grids for, so we don't overdraw overlaying subplots + var finishedGrids = {}; - subplotLayers.order(); + subplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var counterAxis = plotinfo[counterLetter + 'axis']; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + var mainCounterID = counterAxis._mainAxis._id; + if(finishedGrids[mainCounterID]) return; + finishedGrids[mainCounterID] = 1; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; + drawGrid(plotinfo, counterAxis, subplot); + }); - // keep ref to plot group - plotinfo.plotgroup = _$d3_68.select(this); + var mainSubplot = ax._mainSubplot; + var mainPlotinfo = fullLayout._plots[mainSubplot]; + var tickSubplots = []; - // initialize list of overlay subplots - plotinfo.overlays = []; + if(ax.ticks) { + var mainSign = ticksign[2]; + var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen); + if(ax._anchorAxis && ax.mirror && ax.mirror !== true) { + tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen); + } + drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); + tickSubplots = Object.keys(ax._linepositions || {}); } - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + tickSubplots.map(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; -_$cartesian_418.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_444.style(gd); -}; + var container = plotinfo[axLetter + 'axislayer']; -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + // [bottom or left, top or right] + // free and main are handled above + var linepositions = ax._linepositions[subplot] || []; - var subplotData = [], - overlays = []; + function tickPathSide(sidei) { + var tsign = ticksign[sidei]; + return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen); + } - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + drawTicks(container, tickPathSide(0) + tickPathSide(1)); + }); - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + var mainContainer = mainPlotinfo[axLetter + 'axislayer']; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); - } - else { - subplotData.push(subplot); - } + return drawLabels(mainContainer, ax._mainLinePosition); } +}; - // main subplots before overlays - subplotData = subplotData.concat(overlays); - - return subplotData; -} - -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_412.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_412.layerValue2layerClass[plotinfo.yaxis.layer]; - - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); - - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); - - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); - - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); - - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); - - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); - - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); - - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); +// swap all the presentation attributes of the axes showing these traces +axes.swap = function(gd, traces) { + var axGroups = makeAxisGroups(gd, traces); - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + for(var i = 0; i < axGroups.length; i++) { + swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); } - else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; +}; - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. +function makeAxisGroups(gd, traces) { + var groups = [], + i, + j; - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + for(i = 0; i < traces.length; i++) { + var groupsi = [], + xi = gd._fullData[traces[i]].xaxis, + yi = gd._fullData[traces[i]].yaxis; + if(!xi || !yi) continue; // not a 2D cartesian trace? - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + for(j = 0; j < groups.length; j++) { + if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { + groupsi.push(j); + } + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + if(!groupsi.length) { + groups.push({x: [xi], y: [yi]}); + continue; + } - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); + var group0 = groups[groupsi[0]], + groupj; - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + if(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]); } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_410.idSort); - - // common attributes for all subplots, overlays or not + return groups; +} - for(var i = 0; i < _$constants_412.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_412.traceLayerClasses[i]); +function mergeAxisGroups(intoSet, fromSet) { + for(var i = 0; i < fromSet.length; i++) { + if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); } - - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); - - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); } -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; - - var overlayIdsToRemove = {}; +function swapAxisGroup(gd, xIds, yIds) { + var i, + j, + xFullAxes = [], + yFullAxes = [], + layout = gd.layout; - layers.each(function(subplotId) { - var plotgroup = _$d3_68.select(this); + 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])); - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + var allAxKeys = Object.keys(xFullAxes[0]), + noSwapAttrs = [ + 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle' + ], + numericTypes = ['linear', 'log']; - overlayIdsToRemove[subplotId] = true; + for(i = 0; i < allAxKeys.length; i++) { + var keyi = allAxKeys[i], + xVal = xFullAxes[0][keyi], + yVal = yFullAxes[0][keyi], + allEqual = true, + coerceLinearX = false, + 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); + } + } - // do not remove individual axis s here - // as other subplots may need them - }); + // 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_425.swapAttrs(layout.annotations[i], ['?']); + } + } +} - // must remove overlaid subplot trace layers 'manually' +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_425.nestedProperty, + xVal = np(layout[xFullAxes[0]._name], key).get(), + yVal = np(layout[yFullAxes[0]._name], key).get(), + i; + if(key === 'title') { + // special handling of placeholder titles + if(xVal === dfltTitle.x) { + xVal = dfltTitle.y; + } + if(yVal === dfltTitle.y) { + yVal = dfltTitle.x; + } + } - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + 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); + } +} - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; +var _$hover_341 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; +'use strict'; - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); - } - } - } -} +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); -} +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$Events_415 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_436 = require('../../lib/override_cursor'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_514 = require('../../registry'); */; -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); +/* removed: var _$helpers_340 = require('./helpers'); */; +/* removed: var _$constants_338 = require('./constants'); */; - layer.enter().append(nodeType) - .classed(className, true); +// hover labels for multiple horizontal bars get tilted by some angle, +// then need to be offset differently if they overlap +var YANGLE = _$constants_338.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; - return layer; -} +// expansion of projected height +var YFACTOR = 1 / Math.sin(YA_RADIANS); -_$cartesian_418.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_68.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); +// to make the appropriate post-rotation x offset, +// you need both x and y offsets +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); +// size and display constants for hover text +var HOVERARROWSIZE = _$constants_338.HOVERARROWSIZE; +var HOVERTEXTPAD = _$constants_338.HOVERTEXTPAD; - image.attr({ - xmlns: _$xmlns_namespaces_345.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); - } +// fx.hover: highlight data on hover +// evt can be a mousemove event, or an object with data about what points +// to hover on +// {xpx,ypx[,hovermode]} - pixel locations from top left +// (with optional overriding hovermode) +// {xval,yval[,hovermode]} - data values +// [{curveNumber,(pointNumber|xval and/or yval)}] - +// array of specific points to highlight +// pointNumber is a single integer if gd.data[curveNumber] is 1D, +// or a two-element array if it's 2D +// xval and yval are data values, +// 1D data may specify either or both, +// 2D data must specify both +// subplot is an id string (default "xy") +// makes use of gl.hovermode, which can be: +// x (find the points with the closest x values, ie a column), +// closest (find the single closest point) +// internally there are two more that occasionally get used: +// y (pick out a row - only used for multiple horizontal bar charts) +// array (used when the user specifies an explicit +// array of points to hover on) +// +// We wrap the hovers in a timer, to limit their frequency. +// The actual rendering is done by private function _hover. +_$hover_341.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = _$lib_425.getGraphDiv(gd); - canvases.each(canvasToImage); + _$lib_425.throttle( + gd._fullLayout._uid + _$constants_338.HOVERID, + _$constants_338.HOVERMINTIME, + function() { _hover(gd, evt, subplot, noHoverEvent); } + ); }; -"use strict" +/* + * Draw a single hover item in a pre-existing svg container somewhere + * hoverItem should have keys: + * - x and y (or x0, x1, y0, and y1): + * the pixel position to mark, relative to opts.container + * - xLabel, yLabel, zLabel, text, and name: + * info to go in the label + * - color: + * the background color for the label. + * - idealAlign (optional): + * 'left' or 'right' for which side of the x/y box to try to put this on first + * - borderColor (optional): + * color for the border, defaults to strongest contrast with color + * - fontFamily (optional): + * string, the font for this label, defaults to constants.HOVERFONT + * - fontSize (optional): + * the label font size, defaults to constants.HOVERFONTSIZE + * - fontColor (optional): + * defaults to borderColor + * opts should have keys: + * - bgColor: + * the background color this is against, used if the trace is + * non-opaque, and for the name, which goes outside the box + * - container: + * a or element to add the hover label to + * - outerContainer: + * normally a parent of `container`, sets the bounding box to use to + * constrain the hover label and determine whether to show it on the left or right + */ +_$hover_341.loneHover = function loneHover(hoverItem, opts) { + var pointData = { + color: hoverItem.color || _$color_301.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, -function unique_pred(list, compare) { - var ptr = 1 - , len = list.length - , a=list[0], b=list[0] - for(var i=1; i0 - , 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") -} +// The actual implementation is here: +function _hover(gd, evt, subplot, noHoverEvent) { + if(!subplot) subplot = 'xy'; -// 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("")) + // if the user passed in an array of subplots, + // use those instead of finding overlayed plots + var subplots = Array.isArray(subplot) ? subplot : [subplot]; + + var fullLayout = gd._fullLayout; + var plots = fullLayout._plots || []; + var plotinfo = plots[subplot]; + var hasCartesian = fullLayout._has('cartesian'); + + // list of all overlaid subplots to look at + if(plotinfo) { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; + }); + + subplots = subplots.concat(overlayedSubplots); } - } - 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)) - } + if('ypx' in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + evt.pointerY = ypx + yaArray[0]._offset; + } + else { + // fire the beforehover event and quit if it returns false + // note that we're only calling this on real mouse events, so + // manual calls to fx.hover will always run. + if(_$Events_415.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - //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)) - } + var dbb = evt.target.getBoundingClientRect(); - //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() -} -var _$generateCWiseOp_65 = generateCWiseOp + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; -"use strict" + // in case hover was called from mouseout into hovertext, + // it's possible you're not actually over the plot anymore + if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { + return _$dragelement_323.unhoverRaw(gd, evt); + } + evt.pointerX = evt.offsetX; + evt.pointerY = evt.offsetY; + } -// The function below is called when constructing a cwise function object, and does the following: -// A function object is constructed which accepts as argument a compilation function and returns another function. -// It is this other function that is eventually returned by createThunk, and this function is the one that actually -// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. -// The compilation passed to the first function object is used for compiling new functions. -// Once this function object is created, it is called with compile as argument, where the first argument of compile -// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). -// So createThunk roughly works like this: -// function createThunk(proc) { -// var thunk = function(compileBound) { -// var CACHED = {} -// return function(arrays and scalars) { -// if (dtype and order of arrays in CACHED) { -// var func = CACHED[dtype and order of arrays] -// } else { -// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) -// } -// return func(arrays and scalars) -// } -// } -// return thunk(compile.bind1(proc)) -// } + if('xval' in evt) xvalArray = _$helpers_340.flat(subplots, evt.xval); + else xvalArray = _$helpers_340.p2c(xaArray, xpx); -/* removed: var _$generateCWiseOp_65 = require("./compile.js") */; + if('yval' in evt) yvalArray = _$helpers_340.flat(subplots, evt.yval); + else yvalArray = _$helpers_340.p2c(yaArray, ypx); -function createThunk(proc) { - var code = ["'use strict'", "var CACHED={}"] - var vars = [] - var thunkName = proc.funcName + "_cwise_thunk" - - //Build thunk - code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) - var typesig = [] - var string_typesig = [] - var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). - Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] - var shapeLengthConditions = [], shapeConditions = [] - // Process array arguments - for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) - shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) - shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") + if(!_$fastIsnumeric_135(xvalArray[0]) || !_$fastIsnumeric_135(yvalArray[0])) { + _$lib_425.warn('Fx.hover failed', evt, gd); + return _$dragelement_323.unhoverRaw(gd, evt); + } } - } - // Check for shape equality - if (proc.arrayArgs.length > 1) { - code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") - code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") - code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") - code.push("}") - } - // Process scalar arguments - 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") - } + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_340.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } - //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 + // within one trace mode can sometimes be overridden + mode = hovermode; - return _$createThunk_66(proc) -} + // container for new point, also used to pass info into module.hoverPoints + pointData = { + // trace properties + cd: cd, + trace: trace, + xa: xaArray[subploti], + ya: yaArray[subploti], -var _$compileCwise_64 = compileCwise + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, -var _$ndarrayOps_142 = {}; -"use strict" + // point properties - override all of these + index: false, // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance -/* removed: var _$compileCwise_64 = require("cwise-compiler") */; + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, -var EmptyProc = { - body: "", - args: [], - thisVars: [], - localVars: [] -} + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: undefined, + ySpike: undefined, -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] - _$ndarrayOps_142[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a","b","c"], - body: "a=b"+op+"c"}, - funcName: id - }) - _$ndarrayOps_142[id+"eq"] = makeOp({ - args: ["array","array"], - body: {args:["a","b"], - body:"a"+op+"=b"}, - rvalue: true, - funcName: id+"eq" - }) - _$ndarrayOps_142[id+"s"] = makeOp({ - args: ["array", "array", "scalar"], - body: {args:["a","b","s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - _$ndarrayOps_142[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] - _$ndarrayOps_142[id] = makeOp({ - args: ["array", "array"], - body: {args:["a","b"], - body:"a="+op+"b"}, - funcName: id - }) - _$ndarrayOps_142[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] - _$ndarrayOps_142[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a", "b", "c"], - body:"a=b"+op+"c"}, - funcName: id - }) - _$ndarrayOps_142[id+"s"] = makeOp({ - args: ["array","array","scalar"], - body: {args:["a", "b", "s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - _$ndarrayOps_142[id+"eq"] = makeOp({ - args: ["array", "array"], - body: {args:["a", "b"], - body:"a=a"+op+"b"}, - rvalue:true, - count:2, - funcName: id+"eq" - }) - _$ndarrayOps_142[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; i closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } -_$ndarrayOps_142.any = _$compileCwise_64({ - args:["array"], - pre: EmptyProc, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []}, - post: {args:[], localVars:[], thisVars:[], body:"return false"}, - funcName: "any" -}) + // Now if there is range to look in, find the points to draw the spikelines + // Do it only if there is no hoverData + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); + if(closestPoints) { + closestPoints = closestPoints.filter(function(point) { + // some hover points, like scatter fills, do not allow spikes, + // so will generate a hover point but without a valid spikeDistance + return point.spikeDistance <= spikedistance; + }); + } + if(closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes; + }); + if(closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if(_$fastIsnumeric_135(closestVPt.x0) && _$fastIsnumeric_135(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.vLinePoint = tmpPoint; + } + } + } -_$ndarrayOps_142.all = _$compileCwise_64({ - args:["array"], - pre: EmptyProc, - body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []}, - post: {args:[], localVars:[], thisVars:[], body:"return true"}, - funcName: "all" -}) + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes; + }); + if(closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if(_$fastIsnumeric_135(closestHPt.x0) && _$fastIsnumeric_135(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } + } -_$ndarrayOps_142.sum = _$compileCwise_64({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "sum" -}) + function selectClosestPoint(pointsData, spikedistance) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for(var i = 0; i < pointsData.length; i++) { + thisSpikeDistance = pointsData[i].spikeDistance; + if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { + resultPoint = pointsData[i]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } -_$ndarrayOps_142.prod = _$compileCwise_64({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "prod" -}) + function fillSpikePoint(point) { + if(!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } -_$ndarrayOps_142.norm2squared = _$compileCwise_64({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norm2squared" -}) - -_$ndarrayOps_142.norm2 = _$compileCwise_64({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"}, - funcName: "norm2" -}) - + var spikelineOpts = { + fullLayout: fullLayout, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + event: evt + }; + var oldspikepoints = gd._spikepoints, + newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; -_$ndarrayOps_142.norminf = _$compileCwise_64({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_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" -}) + // Now if it is not restricted by spikedistance option, set the points to draw the spikelines + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); -_$ndarrayOps_142.norm1 = _$compileCwise_64({ - 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" -}) + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } + } -_$ndarrayOps_142.sup = _$compileCwise_64({ - 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: [] } - }) + // if hoverData is empty check for the spikes to draw and quit if there are none + if(hoverData.length === 0) { + var result = _$dragelement_323.unhoverRaw(gd, evt); + if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } + return result; + } -_$ndarrayOps_142.inf = _$compileCwise_64({ - 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:[]} -}) + // lastly, emit custom hover/unhover events + var oldhoverdata = gd._hoverdata, + newhoverdata = []; -_$ndarrayOps_142.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" -}) + // pull out just the data that's useful to + // other people and send it to the event + for(itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + newhoverdata.push(_$helpers_340.makeEventData(pt, pt.trace, pt.cd)); + } -_$ndarrayOps_142.assign = makeOp({ - args:["array", "array"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assign" }) + gd._hoverdata = newhoverdata; -_$ndarrayOps_142.assigns = makeOp({ - args:["array", "scalar"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assigns" }) + // if there's more than one horz bar trace, + // rotate the labels so they don't overlap + var rotateLabels = hovermode === 'y' && searchData.length > 1; + var bgColor = _$color_301.combine( + fullLayout.plot_bgcolor || _$color_301.background, + fullLayout.paper_bgcolor + ); -_$ndarrayOps_142.equals = _$compileCwise_64({ - 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" -}) - + var labelOpts = { + hovermode: hovermode, + rotateLabels: rotateLabels, + bgColor: bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }; + var hoverLabels = createHoverText(hoverData, labelOpts, gd); -"use strict" + hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); -function iota(n) { - var result = new Array(n) - for(var i=0; i - * @license MIT - */ + // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true + // we should improve the "fx" API so other plots can use it without these hack. + if(evt.target && evt.target.tagName) { + var hasClickToShow = _$registry_514.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_436(_$d3_71.select(evt.target), hasClickToShow ? 'pointer' : ''); + } -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -var _$isBuffer_132 = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} + // don't emit events if called manually + if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} + if(oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); + } -// 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)) + gd.emit('plotly_hover', { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray + }); } -/* removed: var _$iota_130 = require("iota-array") */; -/* removed: var _$isBuffer_132 = require("is-buffer") */; +function createHoverText(hoverData, opts, gd) { + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; -var hasTypedArrays = ((typeof Float64Array) !== "undefined") + // opts.fontFamily/Size are used for the common label + // and as defaults for each hover label, though the individual labels + // can override this. + var fontFamily = opts.fontFamily || _$constants_338.HOVERFONT; + var fontSize = opts.fontSize || _$constants_338.HOVERFONTSIZE; -function compare1st(a, b) { - return a[0] - b[0] -} + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; + var t0 = c0[commonAttr]; + var t00 = (String(t0) || '').split(' ')[0]; + var outerContainerBB = outerContainer.node().getBoundingClientRect(); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; -function order() { - var stride = this.stride - var terms = new Array(stride.length) - var i - for(i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") - } else if(dimension === 3) { - code.push( -"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ -if(s0>s1){\ -if(s1>s2){\ -return [2,1,0];\ -}else if(s0>s2){\ -return [1,2,0];\ -}else{\ -return [1,0,2];\ -}\ -}else if(s0>s2){\ -return [2,0,1];\ -}else if(s2>s1){\ -return [0,1,2];\ -}else{\ -return [0,2,1];\ -}}})") - } - } else { - code.push("ORDER})") - } - } + lpath.style({ + fill: commonLabelOpts.bgcolor || _$color_301.defaultLine, + stroke: commonLabelOpts.bordercolor || _$color_301.background, + }); - //view.set(i0, ..., v): - code.push( -"proto.set=function "+className+"_set("+args.join(",")+",v){") - if(useGetters) { - code.push("return this.data.set("+index_str+",v)}") - } else { - code.push("return this.data["+index_str+"]=v}") - } + ltext.text(t0) + .call(_$drawing_326.font, + commonLabelOpts.font.family || fontFamily, + commonLabelOpts.font.size || fontSize, + commonLabelOpts.font.color || _$color_301.background + ) + .call(_$svg_text_utils_449.positionText, 0, 0) + .call(_$svg_text_utils_449.convertToTspans, gd); - //view.get(i0, ...): - code.push("proto.get=function "+className+"_get("+args.join(",")+"){") - if(useGetters) { - code.push("return this.data.get("+index_str+")}") - } else { - code.push("return this.data["+index_str+"]}") - } + label.attr('transform', ''); - //view.index: - code.push( - "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") + var tbb = ltext.node().getBoundingClientRect(); + if(hovermode === 'x') { + ltext.attr('text-anchor', 'middle') + .call(_$svg_text_utils_449.positionText, 0, (xa.side === 'top' ? + (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : + (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); - //view.hi(): - code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ - indices.map(function(i) { - return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") - }).join(",")+","+ - indices.map(function(i) { - return "this.stride["+i + "]" - }).join(",")+",this.offset)}") + var topsign = xa.side === 'top' ? '-' : ''; + lpath.attr('d', 'M0,0' + + 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + + 'H' + (HOVERTEXTPAD + tbb.width / 2) + + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + + 'H-' + (HOVERTEXTPAD + tbb.width / 2) + + 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); - //view.lo(): - var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) - var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) - code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) - for(var i=0; i=0){\ -d=i"+i+"|0;\ -b+=c"+i+"*d;\ -a"+i+"-=d}") - } - code.push("return new "+className+"(this.data,"+ - indices.map(function(i) { - return "a"+i - }).join(",")+","+ - indices.map(function(i) { - return "c"+i - }).join(",")+",b)}") + label.attr('transform', 'translate(' + + (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + + (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + } + else { + ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') + .call(_$svg_text_utils_449.positionText, + (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), + outerTop - tbb.top - tbb.height / 2); - //view.step(): - code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ - indices.map(function(i) { - return "a"+i+"=this.shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "b"+i+"=this.stride["+i+"]" - }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") - for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") - } - code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") + // show all the individual labels - //Add return statement - code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ - indices.map(function(i) { - return "shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "stride["+i+"]" - }).join(",")+",offset)}") + // first create the objects + var hoverLabels = container.selectAll('g.hovertext') + .data(hoverData, function(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); + }); + hoverLabels.enter().append('g') + .classed('hovertext', true) + .each(function() { + var g = _$d3_71.select(this); + // trace name label (rect and text.name) + g.append('rect') + .call(_$color_301.fill, _$color_301.addOpacity(bgColor, 0.8)); + g.append('text').classed('name', true); + // trace data label (path and text.nums) + g.append('path') + .style('stroke-width', '1px'); + g.append('text').classed('nums', true) + .call(_$drawing_326.font, fontFamily, fontSize); + }); + hoverLabels.exit().remove(); - //Compile procedure - var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) - return procedure(CACHED_CONSTRUCTORS[dtype], order) -} + // then put the text in, position the pointer to the data, + // and figure out sizes + hoverLabels.each(function(d) { + var g = _$d3_71.select(this).attr('transform', ''), + name = '', + text = ''; -function arrayDType(data) { - if(_$isBuffer_132(data)) { - return "buffer" - } - if(hasTypedArrays) { - switch(Object.prototype.toString.call(data)) { - case "[object Float64Array]": - return "float64" - case "[object Float32Array]": - return "float32" - case "[object Int8Array]": - return "int8" - case "[object Int16Array]": - return "int16" - case "[object Int32Array]": - return "int32" - case "[object Uint8Array]": - return "uint8" - case "[object Uint16Array]": - return "uint16" - case "[object Uint32Array]": - return "uint32" - case "[object Uint8ClampedArray]": - return "uint8_clamped" - } - } - if(Array.isArray(data)) { - return "array" - } - return "generic" -} + // combine possible non-opaque trace color with bgColor + var baseColor = _$color_301.opacity(d.color) ? d.color : _$color_301.defaultLine; + var traceColor = _$color_301.combine(baseColor, bgColor); -var CACHED_CONSTRUCTORS = { - "float32":[], - "float64":[], - "int8":[], - "int16":[], - "int32":[], - "uint8":[], - "uint16":[], - "uint32":[], - "array":[], - "uint8_clamped":[], - "buffer":[], - "generic":[] -} + // find a contrasting color for border and text + var contrastColor = d.borderColor || _$color_301.contrast(traceColor); -;(function() { - for(var id in CACHED_CONSTRUCTORS) { - CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) - } -}); + // to get custom 'name' labels pass cleanPoint + if(d.nameOverride !== undefined) d.name = d.nameOverride; -function wrappedNDArrayCtor(data, shape, stride, offset) { - if(data === undefined) { - var ctor = CACHED_CONSTRUCTORS.array[0] - return ctor([]) - } else if(typeof data === "number") { - data = [data] - } - if(shape === undefined) { - shape = [ data.length ] - } - var d = shape.length - if(stride === undefined) { - stride = new Array(d) - for(var i=d-1, sz=1; i>=0; --i) { - stride[i] = sz - sz *= shape[i] - } - } - if(offset === undefined) { - offset = 0 - for(var i=0; i -1 && name.length > nameLength) { + if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; + else name = name.substr(0, nameLength); + } + } -"use strict"; "use restrict"; + if(d.zLabel !== undefined) { + if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; + if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; + text += (text ? 'z: ' : '') + d.zLabel; + } + else if(showCommonLabel && d[hovermode + 'Label'] === t0) { + text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; + } + else if(d.xLabel === undefined) { + if(d.yLabel !== undefined) text = d.yLabel; + } + else if(d.yLabel === undefined) text = d.xLabel; + else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; -//Number of bits in an integer -var INT_BITS = 32; + if(d.text && !Array.isArray(d.text)) { + text += (text ? '
' : '') + d.text; + } -//Constants -_$twiddle_35.INT_BITS = INT_BITS; -_$twiddle_35.INT_MAX = 0x7fffffff; -_$twiddle_35.INT_MIN = -1<<(INT_BITS-1); + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; -//Returns -1, 0, +1 depending on sign of x -_$twiddle_35.sign = function(v) { - return (v > 0) - (v < 0); -} + // if 'text' is empty at this point, + // put 'name' in main label and don't show secondary label + if(text === '') { + // if 'name' is also empty, remove entire label + if(name === '') g.remove(); + text = name; + } -//Computes absolute value of integer -_$twiddle_35.abs = function(v) { - var mask = v >> (INT_BITS-1); - return (v ^ mask) - mask; -} + // main label + var tx = g.select('text.nums') + .call(_$drawing_326.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + d.fontColor || contrastColor) + .text(text) + .attr('data-notex', 1) + .call(_$svg_text_utils_449.positionText, 0, 0) + .call(_$svg_text_utils_449.convertToTspans, gd); -//Computes minimum of integers x and y -_$twiddle_35.min = function(x, y) { - return y ^ ((x ^ y) & -(x < y)); -} + var tx2 = g.select('text.name'), + tx2width = 0; -//Computes maximum of integers x and y -_$twiddle_35.max = function(x, y) { - return x ^ ((x ^ y) & -(x < y)); -} + // secondary label for non-empty 'name' + if(name && name !== text) { + tx2.call(_$drawing_326.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + traceColor) + .text(name) + .attr('data-notex', 1) + .call(_$svg_text_utils_449.positionText, 0, 0) + .call(_$svg_text_utils_449.convertToTspans, gd); + tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; + } + else { + tx2.remove(); + g.select('rect').remove(); + } -//Checks if a number is a power of two -_$twiddle_35.isPow2 = function(v) { - return !(v & (v-1)) && (!!v); -} + g.select('path') + .style({ + fill: traceColor, + stroke: contrastColor + }); + var tbb = tx.node().getBoundingClientRect(), + htx = d.xa._offset + (d.x0 + d.x1) / 2, + hty = d.ya._offset + (d.y0 + d.y1) / 2, + dx = Math.abs(d.x1 - d.x0), + dy = Math.abs(d.y1 - d.y0), + txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, + anchorStartOK, + anchorEndOK; -//Computes log base 2 of v -_$twiddle_35.log2 = function(v) { - var r, shift; - r = (v > 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); -} + d.ty0 = outerTop - tbb.top; + d.bx = tbb.width + 2 * HOVERTEXTPAD; + d.by = tbb.height + 2 * HOVERTEXTPAD; + d.anchor = 'start'; + d.txwidth = tbb.width; + d.tx2width = tx2width; + d.offset = 0; -//Computes log base 10 of v -_$twiddle_35.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} + if(rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + hty += dy / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } + else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + htx += dx / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } -//Counts number of bits -_$twiddle_35.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; -} + tx.attr('text-anchor', d.anchor); + if(tx2width) tx2.attr('text-anchor', d.anchor); + g.attr('transform', 'translate(' + htx + ',' + hty + ')' + + (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); + }); -//Counts number of trailing zeros -function countTrailingZeros(v) { - var c = 32; - v &= -v; - if (v) c--; - if (v & 0x0000FFFF) c -= 16; - if (v & 0x00FF00FF) c -= 8; - if (v & 0x0F0F0F0F) c -= 4; - if (v & 0x33333333) c -= 2; - if (v & 0x55555555) c -= 1; - return c; + return hoverLabels; } -_$twiddle_35.countTrailingZeros = countTrailingZeros; -//Rounds to next power of 2 -_$twiddle_35.nextPow2 = function(v) { - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; -} +// Make groups of touching points, and within each group +// move each point so that no labels overlap, but the average +// label position is the same as it was before moving. Indicentally, +// this is equivalent to saying all the labels are on equal linear +// springs about their initial position. Initially, each point is +// its own group, but as we find overlaps we will clump the points. +// +// Also, there are hard constraints at the edges of the graphs, +// that push all groups to the middle so they are visible. I don't +// know what happens if the group spans all the way from one edge to +// the other, though it hardly matters - there's just too much +// information then. +function hoverAvoidOverlaps(hoverData, ax, fullLayout) { + var nummoves = 0, -//Rounds down to previous power of 2 -_$twiddle_35.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); -} + // make groups of touching points + pointgroups = hoverData + .map(function(d, i) { + var axis = d[ax]; + return [{ + i: i, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, + pmin: 0, + pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) + }]; + }) + .sort(function(a, b) { return a[0].posref - b[0].posref; }), + donepositioning, + topOverlap, + bottomOverlap, + i, j, + pti, + sumdp; -//Computes parity of word -_$twiddle_35.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; -} + function constrainGroup(grp) { + var minPt = grp[0], + maxPt = grp[grp.length - 1]; -var REVERSE_TABLE = new Array(256); + // overlap with the top - positive vals are overlaps + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; -(function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; - } - tab[i] = (r << s) & 0xff; - } -})(REVERSE_TABLE); + // overlap with the bottom - positive vals are overlaps + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; -//Reverse bits in a 32 bit word -_$twiddle_35.reverse = function(v) { - return (REVERSE_TABLE[ v & 0xff] << 24) | - (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; -} + // check for min overlap first, so that we always + // see the largest labels + // allow for .01px overlap, so we don't get an + // infinite loop from rounding errors + if(topOverlap > 0.01) { + for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; + donepositioning = false; + } + if(bottomOverlap < 0.01) return; + if(topOverlap < -0.01) { + // make sure we're not pushing back and forth + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + donepositioning = false; + } + if(!donepositioning) return; -//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -_$twiddle_35.interleave2 = function(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; + // no room to fix positioning, delete off-screen points - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; + // first see how many points we need to delete + var deleteCount = 0; + for(i = 0; i < grp.length; i++) { + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } - return x | (y << 1); -} + // start by deleting points whose data is off screen + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; -//Extracts the nth interleaved component -_$twiddle_35.deinterleave2 = function(v, n) { - v = (v >>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; -} + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } + } + for(i = 0; i < grp.length; i++) { + if(deleteCount <= 0) break; + pti = grp[i]; + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; -//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -_$twiddle_35.interleave3 = function(x, y, z) { - x &= 0x3FF; - x = (x | (x<<16)) & 4278190335; - x = (x | (x<<8)) & 251719695; - x = (x | (x<<4)) & 3272356035; - x = (x | (x<<2)) & 1227133513; + // shift the whole group minus into this new space + bottomOverlap = pti.size * 2; + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + } + } + // then delete points that go off the bottom + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } + } + } - y &= 0x3FF; - y = (y | (y<<16)) & 4278190335; - y = (y | (y<<8)) & 251719695; - y = (y | (y<<4)) & 3272356035; - y = (y | (y<<2)) & 1227133513; - x |= (y << 1); - - z &= 0x3FF; - z = (z | (z<<16)) & 4278190335; - z = (z | (z<<8)) & 251719695; - z = (z | (z<<4)) & 3272356035; - z = (z | (z<<2)) & 1227133513; - - return x | (z << 2); -} + // loop through groups, combining them if they overlap, + // until nothing moves + while(!donepositioning && nummoves <= hoverData.length) { + // to avoid infinite loops, don't move more times + // than there are traces + nummoves++; -//Extracts nth interleaved component of a 3-tuple -_$twiddle_35.deinterleave3 = function(v, n) { - v = (v >>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; -} + // assume nothing will move in this iteration, + // reverse this if it does + donepositioning = true; + i = 0; + while(i < pointgroups.length - 1) { + // the higher (g0) and lower (g1) point group + var g0 = pointgroups[i], + g1 = pointgroups[i + 1], -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -_$twiddle_35.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); -} + // the lowest point in the higher group (p0) + // the highest point in the lower group (p1) + p0 = g0[g0.length - 1], + p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; + // Only group points that lie on the same axes + if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { + // push the new point(s) added to this group out of the way + for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; -var _$base64Js_17 = {}; -'use strict' + // add them to the group + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); -_$base64Js_17.byteLength = byteLength -_$base64Js_17.toByteArray = toByteArray -_$base64Js_17.fromByteArray = fromByteArray + // adjust for minimum average movement + sumdp = 0; + for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } + else i++; + } -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + // check if we're going off the plot on either side and fix + pointgroups.forEach(constrainGroup); + } -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i + // now put these offsets into hoverData + for(i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for(j = grp.length - 1; j >= 0; j--) { + var pt = grp[j], + hoverPt = hoverData[pt.i]; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } + } } -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 +function alignHoverText(hoverLabels, rotateLabels) { + // finally set the text positioning relative to the data and draw the + // box around it + hoverLabels.each(function(d) { + var g = _$d3_71.select(this); + if(d.del) { + g.remove(); + return; + } + var horzSign = d.anchor === 'end' ? -1 : 1, + tx = g.select('text.nums'), + alignShift = {start: 1, end: -1, middle: 0}[d.anchor], + txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), + tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), + offsetX = 0, + offsetY = d.offset; + if(d.anchor === 'middle') { + txx -= d.tx2width / 2; + tx2x += d.txwidth / 2 + HOVERTEXTPAD; + } + if(rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = d.offset * YSHIFTX; + } -function placeHoldersCount (b64) { - var len = b64.length - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + g.select('path').attr('d', d.anchor === 'middle' ? + // middle aligned: rect centered on data + ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + + 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : + // left or right aligned: side rect with arrow to data + ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + + 'v' + (d.by / 2 - HOVERARROWSIZE) + + 'h' + (horzSign * d.bx) + + 'v-' + d.by + + 'H' + (horzSign * HOVERARROWSIZE + offsetX) + + 'V' + (offsetY - HOVERARROWSIZE) + + 'Z')); - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 -} + tx.call(_$svg_text_utils_449.positionText, + txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); -function byteLength (b64) { - // base64 is 4/3 + up to two characters of the original data - return (b64.length * 3 / 4) - placeHoldersCount(b64) + if(d.tx2width) { + g.select('text.name') + .call(_$svg_text_utils_449.positionText, + tx2x + alignShift * HOVERTEXTPAD + offsetX, + offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + g.select('rect') + .call(_$drawing_326.setRect, + tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, + offsetY - d.by / 2 - 1, + d.tx2width, d.by + 2); + } + }); } -function toByteArray (b64) { - var i, l, tmp, placeHolders, arr - var len = b64.length - placeHolders = placeHoldersCount(b64) +function cleanPoint(d, hovermode) { + var index = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index] || {}; - arr = new Arr((len * 3 / 4) - placeHolders) + var getVal = Array.isArray(index) ? + function(calcKey, traceKey) { + return _$lib_425.castOption(cd0, index, calcKey) || + _$lib_425.extractOption({}, trace, '', traceKey); + } : + function(calcKey, traceKey) { + return _$lib_425.extractOption(cd, trace, calcKey, traceKey); + }; - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if(val) d[key] = val; + } - var L = 0 + fill('hoverinfo', 'hi', 'hoverinfo'); + fill('color', 'hbg', 'hoverlabel.bgcolor'); + fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); + fill('fontFamily', 'htf', 'hoverlabel.font.family'); + fill('fontSize', 'hts', 'hoverlabel.font.size'); + fill('fontColor', 'htc', 'hoverlabel.font.color'); + fill('nameLength', 'hnl', 'hoverlabel.namelength'); - for (i = 0; i < l; 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[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } + d.posref = hovermode === 'y' ? + (d.xa._offset + (d.x0 + d.x1) / 2) : + (d.ya._offset + (d.y0 + d.y1) / 2); - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[L++] = tmp & 0xFF - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[L++] = (tmp >> 8) & 0xFF - arr[L++] = tmp & 0xFF - } + // then constrain all the positions to be on the plot + d.x0 = _$lib_425.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_425.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_425.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_425.constrain(d.y1, 0, d.ya._length); - return arr -} + // and convert the x and y label values into formatted text + if(d.xLabelVal !== undefined) { + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_470.hoverLabelText(d.xa, d.xLabelVal); + d.xVal = d.xa.c2d(d.xLabelVal); + } + if(d.yLabelVal !== undefined) { + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_470.hoverLabelText(d.ya, d.yLabelVal); + d.yVal = d.ya.c2d(d.yLabelVal); + } -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} + // Traces like heatmaps generate the zLabel in their hoverPoints function + if(d.zLabelVal !== undefined && d.zLabel === undefined) { + d.zLabel = String(d.zLabelVal); + } -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('') -} + // for box means and error bars, add the range to the label + if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { + var xeText = _$axes_470.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + if(d.xerrneg !== undefined) { + d.xLabel += ' +' + xeText + ' / -' + + _$axes_470.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + else d.xLabel += ' ± ' + xeText; -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 + // small distance penalty for error bars, so that if there are + // traces with errors and some without, the error bar label will + // hoist up to the point + if(hovermode === 'x') d.distance += 1; + } + if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { + var yeText = _$axes_470.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + if(d.yerrneg !== undefined) { + d.yLabel += ' +' + yeText + ' / -' + + _$axes_470.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + } + else d.yLabel += ' ± ' + yeText; - // 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))) - } + if(hovermode === 'y') d.distance += 1; + } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - output += lookup[tmp >> 2] - output += lookup[(tmp << 4) & 0x3F] - output += '==' - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) - output += lookup[tmp >> 10] - output += lookup[(tmp >> 4) & 0x3F] - output += lookup[(tmp << 2) & 0x3F] - output += '=' - } + var infomode = d.hoverinfo || d.trace.hoverinfo; - parts.push(output) + if(infomode !== 'all') { + infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); + if(infomode.indexOf('x') === -1) d.xLabel = undefined; + if(infomode.indexOf('y') === -1) d.yLabel = undefined; + if(infomode.indexOf('z') === -1) d.zLabel = undefined; + if(infomode.indexOf('text') === -1) d.text = undefined; + if(infomode.indexOf('name') === -1) d.name = undefined; + } - return parts.join('') + return d; } -var _$ieee754_127 = {}; -_$ieee754_127.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} +function createSpikelines(closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var evt = opts.event; + var xa, + ya; - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; -_$ieee754_127.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + // Remove old spikeline items + container.selectAll('.spikeline').remove(); - value = Math.abs(value) + if(!(showX || showY)) return; - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } + var contrastColor = _$color_301.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } + // Horizontal line (to y-axis) + if(showY) { + var hLinePoint = closestPoints.hLinePoint, + hLinePointX, + hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + if(ySnap === 'cursor') { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = _$tinycolor_263.readability(hLinePoint.color, contrastColor) < 1.5 ? + _$color_301.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode, + yThickness = ya.spikethickness, + yColor = ya.spikecolor || dfltHLineColor, + yBB = ya._boundingBox, + xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, + xBase, + xEndSpike; - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { + if(yMode.indexOf('toaxis') !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; + } + if(yMode.indexOf('across') !== -1) { + xBase = ya._counterSpan[0]; + xEndSpike = ya._counterSpan[1]; + } - buffer[offset + i - d] |= s * 128 -} + // Foreground horizontal line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness, + 'stroke': yColor, + 'stroke-dasharray': _$drawing_326.dashStyle(ya.spikedash, yThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); -var _$buffer_46 = {}; -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ + // Background horizontal Line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + // Y axis marker + if(yMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), + 'cy': hLinePointY, + 'r': yThickness, + 'fill': yColor + }) + .classed('spikeline', true); + } + } -'use strict' + if(showX) { + var vLinePoint = closestPoints.vLinePoint, + vLinePointX, + vLinePointY; -/* removed: var _$base64Js_17 = require('base64-js') */; -/* removed: var _$ieee754_127 = require('ieee754') */; + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; -_$buffer_46.Buffer = Buffer -_$buffer_46.SlowBuffer = SlowBuffer -_$buffer_46.INSPECT_MAX_BYTES = 50 + if(xSnap === 'cursor') { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; + } + var dfltVLineColor = _$tinycolor_263.readability(vLinePoint.color, contrastColor) < 1.5 ? + _$color_301.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode, + xThickness = xa.spikethickness, + xColor = xa.spikecolor || dfltVLineColor, + xBB = xa._boundingBox, + yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, + yBase, + yEndSpike; -var K_MAX_LENGTH = 0x7fffffff -_$buffer_46.kMaxLength = K_MAX_LENGTH + if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { + if(xMode.indexOf('toaxis') !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if(xMode.indexOf('across') !== -1) { + yBase = xa._counterSpan[0]; + yEndSpike = xa._counterSpan[1]; + } -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + // Foreground vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness, + 'stroke': xColor, + 'stroke-dasharray': _$drawing_326.dashStyle(xa.spikedash, xThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} + // Background vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 - } catch (e) { - return false - } + // X axis marker + if(xMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': vLinePointX, + 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), + 'r': xThickness, + 'fill': xColor + }) + .classed('spikeline', true); + } + } } -Object.defineProperty(Buffer.prototype, 'parent', { - get: function () { - if (!(this instanceof Buffer)) { - return undefined - } - return this.buffer - } -}) +function hoverChanged(gd, evt, oldhoverdata) { + // don't emit any events if nothing changed + if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; -Object.defineProperty(Buffer.prototype, 'offset', { - get: function () { - if (!(this instanceof Buffer)) { - return undefined + for(var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i], + newPt = gd._hoverdata[i]; + if(oldPt.curveNumber !== newPt.curveNumber || + String(oldPt.pointNumber) !== String(newPt.pointNumber)) { + return true; + } } - return this.byteOffset - } -}) + return false; +} -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('Invalid typed array length') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf +function spikesChanged(gd, oldspikepoints) { + // don't relayout the plot because of new spikelines if spikelines points didn't change + if(!oldspikepoints) return true; + if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || + oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint + ) return true; + return false; } /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} +'use strict'; -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} +/* removed: var _$registry_514 = require('../../registry'); */; +var hover = _$hover_341.hover; -Buffer.poolSize = 8192 // not used by this implementation +var _$click_337 = function click(gd, evt, subplot) { + var annotationsDone = _$registry_514.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); -function from (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } + // 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); + } - if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } + function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } + if(gd._hoverdata && evt && evt.target) { + if(annotationsDone && annotationsDone.then) { + annotationsDone.then(emitClick); + } + else emitClick(); - return fromObject(value) -} + // why do we get a double event without this??? + if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); + } +}; /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array +'use strict'; -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} +/* removed: var _$lib_425 = require('../../lib'); */; -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} +var _$handleHoverLabelDefaults_342 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { + opts = opts || {}; + + coerce('hoverlabel.bgcolor', opts.bgcolor); + coerce('hoverlabel.bordercolor', opts.bordercolor); + coerce('hoverlabel.namelength', opts.namelength); + _$lib_425.coerceFont(coerce, 'hoverlabel.font', opts.font); +}; /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = __byteLength_46(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } +* Copyright 2012-2018, Plotly, Inc. +* All 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 buf -} +'use strict'; -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$attributes_335 = require('./attributes'); */; +/* removed: var _$handleHoverLabelDefaults_342 = require('./hoverlabel_defaults'); */; -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } +var _$supplyDefaults_339 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_425.coerce(traceIn, traceOut, _$attributes_335, attr, dflt); + } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } + _$handleHoverLabelDefaults_342(traceIn, traceOut, coerce, layout.hoverlabel); +}; - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} +'use strict'; -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$layout_attributes_344 = require('./layout_attributes'); */; - if (buf.length === 0) { - return buf +var _$supplyLayoutDefaults_345 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_425.coerce(layoutIn, layoutOut, _$layout_attributes_344, attr, dflt); } - obj.copy(buf, 0, 0, len) - return buf - } + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); - if (obj) { - if (ArrayBuffer.isView(obj) || 'length' in obj) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) + var hovermodeDflt; + if(layoutOut._has('cartesian')) { + // flag for 'horizontal' plots: + // determines the state of the mode bar 'compare' hovermode button + layoutOut._isHoriz = isHoriz(fullData); + hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; } + else hovermodeDflt = 'closest'; - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) + var hoverMode = coerce('hovermode', hovermodeDflt); + if(hoverMode) { + coerce('hoverdistance'); + coerce('spikedistance'); } - } - - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.') -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true -} + // if only mapbox or geo subplots is present on graph, + // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, + // so that the correct modebar button is active + var hasMapbox = layoutOut._has('mapbox'); + var hasGeo = layoutOut._has('geo'); + var len = layoutOut._basePlotModules.length; -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + if(layoutOut.dragmode === 'zoom' && ( + ((hasMapbox || hasGeo) && len === 1) || + (hasMapbox && hasGeo && len === 2) + )) { + layoutOut.dragmode = 'pan'; + } +}; - if (a === b) return 0 +function isHoriz(fullData) { + var out = true; - var x = a.length - var y = b.length + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break + if(trace.orientation !== 'h') { + out = false; + break; + } } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } + return out; } -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (list.length === 0) { - return Buffer.alloc(0) - } +'use strict'; - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$handleHoverLabelDefaults_342 = require('./hoverlabel_defaults'); */; +/* removed: var _$layout_attributes_344 = require('./layout_attributes'); */; - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (ArrayBuffer.isView(buf)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') +var _$supplyLayoutGlobalDefaults_346 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce(attr, dflt) { + return _$lib_425.coerce(layoutIn, layoutOut, _$layout_attributes_344, attr, dflt); } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function __byteLength_46 (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isArrayBuffer(string)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = __byteLength_46 + _$handleHoverLabelDefaults_342(layoutIn, layoutOut, coerce); +}; -function slowToString (encoding, start, end) { - var loweredCase = false +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. +'use strict'; - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$helpers_340 = require('./helpers'); */; +/* removed: var _$layout_attributes_344 = require('./layout_attributes'); */; - if (end === undefined || end > this.length) { - end = this.length - } +var _$fx_343 = { + moduleType: 'component', + name: 'fx', - if (end <= 0) { - return '' - } + constants: _$constants_338, + schema: { + layout: _$layout_attributes_344 + }, - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 + attributes: _$attributes_335, + layoutAttributes: _$layout_attributes_344, - if (end <= start) { - return '' - } + supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_346, + supplyDefaults: _$supplyDefaults_339, + supplyLayoutDefaults: _$supplyLayoutDefaults_345, - if (!encoding) encoding = 'utf8' + calc: _$calc_336, - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) + getDistanceFunction: _$helpers_340.getDistanceFunction, + getClosest: _$helpers_340.getClosest, + inbox: _$helpers_340.inbox, + quadrature: _$helpers_340.quadrature, + appendArrayPointValue: _$helpers_340.appendArrayPointValue, - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + castHoverOption: castHoverOption, + castHoverinfo: castHoverinfo, - case 'ascii': - return asciiSlice(this, start, end) + hover: _$hover_341.hover, + unhover: _$dragelement_323.unhover, - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + loneHover: _$hover_341.loneHover, + loneUnhover: loneUnhover, - case 'base64': - return base64Slice(this, start, end) + click: _$click_337 +}; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) +function loneUnhover(containerOrSelection) { + // duck type whether the arg is a d3 selection because ie9 doesn't + // handle instanceof like modern browsers do. + var selection = _$lib_425.isD3Selection(containerOrSelection) ? + containerOrSelection : + _$d3_71.select(containerOrSelection); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } + selection.selectAll('g.hovertext').remove(); + selection.selectAll('.spikeline').remove(); } -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} +// helpers for traces that use Fx.loneHover -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this +function castHoverOption(trace, ptNumber, attr) { + return _$lib_425.castOption(trace, ptNumber, 'hoverlabel.' + attr); } -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return _$lib_425.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + } -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this + return _$lib_425.castOption(trace, ptNumber, 'hoverinfo', _coerce); } -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -Buffer.prototype.toLocaleString = Buffer.prototype.toString +'use strict'; -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} +/** + * 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 + */ +var _$clearGlCanvases_411 = function clearGlCanvases(gd) { + var fullLayout = gd._fullLayout; -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = _$buffer_46.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); + }); + } +}; -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } +'use strict'; - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } +var FROM_BL = _$alignment_401.FROM_BL; - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 +var _$scaleZoom_486 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } - if (this === target) return 0 + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// - if (x < y) return -1 - if (y < x) return 1 - return 0 -} +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; +} - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } +var _$BuildLog_221 = BuildLog; - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// - throw new TypeError('val must be string, number or Buffer') -} +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - return -1 -} + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} + // categorize where intersection point is along A and B -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - var strLen = string.length + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; } -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} +var _$Epsilon_222 = Epsilon; -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + // 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] }); + } - if (!encoding) encoding = 'utf8' + // the first LineString is considered the outside + var out = LineString(coords[0]); - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + // 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]))); - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + return out; + } - case 'ascii': - return asciiWrite(this, string, offset, length) + 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'); + }, - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + // 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)); - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + // 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); + } - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + // calculate inside heirarchy + // + // _____________________ _______ roots -> A -> F + // | A | | F | | | + // | _______ _______ | | ___ | +-- B +-- G + // | | B | | C | | | | | | | | + // | | ___ | | ___ | | | | | | | +-- D + // | | | D | | | | E | | | | | G | | | + // | | |___| | | |___| | | | | | | +-- C + // | |_______| |_______| | | |___| | | + // |_____________________| |_______| +-- E - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} + function newNode(region){ + return { + region: region, + children: [] + }; + } -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} + var roots = newNode(null); -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return _$base64Js_17.fromByteArray(buf) - } else { - return _$base64Js_17.fromByteArray(buf.slice(start, end)) - } -} + 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; + } + } -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] + // 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--; + } + } - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 + // now we can add ourselves + root.children.push(node); + } - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint + // 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); + } - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } + // 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 - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - res.push(codePoint) - i += bytesPerSequence - } + 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; + } - return decodeCodePointsArray(res) -} + var geopolys = []; -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 + function 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 decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } + 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); + } - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) + // lastly, construct the approrpriate GeoJSON object - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} + 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 + }; + } +}; -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) +var _$GeoJSON_223 = GeoJSON; - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -function hexSlice (buf, start, end) { - var len = buf.length +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } +}; - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} +var _$LinkedList_225 = LinkedList; -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end +// +// this is the core work-horse +// - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } +/* removed: var _$LinkedList_225 = require('./linked-list'); */; - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm - if (end < start) end = start + // + // segment creation + // - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + // + // event logic + // - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } + var event_root = _$LinkedList_225.create(); - return val -} + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start - return val -} + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_225.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_225.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + if (buildLog) + buildLog.segmentChop(ev.seg, end); - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + // + // status logic + // - return val -} + var status_root = _$LinkedList_225.create(); -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } - if (val >= mul) val -= Math.pow(2, 8 * byteLength) + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } - return val -} + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} + if (buildLog) + buildLog.checkIntersection(seg1, seg2); -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} + var i = eps.linesIntersect(a1, a2, b1, b2); -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + if (i === false){ + // segments are parallel or coincident - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return _$ieee754_127.read(this, offset, true, 23, 4) -} + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return _$ieee754_127.read(this, offset, false, 23, 4) -} + var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return _$ieee754_127.read(this, offset, true, 52, 8) -} + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return _$ieee754_127.read(this, offset, false, 52, 8) -} + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } - return offset + byteLength -} + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + if (buildLog) + buildLog.vert(ev.pt[0]); - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } + if (ev.isStart){ - return offset + byteLength -} + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} + // merge ev.seg's fill information into eve.seg -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + if (buildLog) + buildLog.segmentUpdate(eve.seg); - return offset + byteLength -} + ev.other.remove(); + ev.remove(); + } -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } - return offset + byteLength -} + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_225.node({ ev: ev })); + } + else{ + var st = ev.status; -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} + if (buildLog) + buildLog.statusRemove(st.ev.seg); -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - _$ieee754_127.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} + // remove the status + st.remove(); -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} + // remove the event and continue + event_root.getHead().remove(); + } -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - _$ieee754_127.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} + if (buildLog) + buildLog.done(); -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} + return segments; + } -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } + + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; + + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it + + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; } -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start +var _$Intersecter_224 = Intersecter; - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; - var len = end - start + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } + if (buildLog) + buildLog.chainStart(seg); - return len -} + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } + if (next_match === second_match){ + // we matched a single chain - if (end <= start) { - return this - } + if (buildLog) + buildLog.chainMatch(first_match.index); - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop - if (!val) val = 0 + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : new Buffer(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - return this -} + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } -// HELPER FUNCTIONS -// ================ + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} + if (buildLog) + buildLog.chainClose(first_match.index); -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} + // we have a closed chain! + regions.push(chain); + return; + } -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) + // otherwise, we matched two chains, so we need to combine those chains together - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } - // valid lead - leadSurrogate = codePoint + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; - continue - } + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } - leadSurrogate = null + var F = first_match.index; + var S = second_match.index; - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } + if (buildLog) + buildLog.chainConnect(F, S); - return bytes -} + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray + return regions; } -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break +var _$SegmentChainer_226 = SegmentChainer; - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - return byteArray -} +// +// filter a list of segments based on boolean operations +// -function base64ToBytes (str) { - return _$base64Js_17.toByteArray(base64clean(str)) -} +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} + if (buildLog) + buildLog.selected(result); -// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check -// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 -function isArrayBuffer (obj) { - return obj instanceof ArrayBuffer || - (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && - typeof obj.byteLength === 'number') + return result; } -function numberIsNaN (obj) { - return obj !== obj // eslint-disable-line no-self-compare -} +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; -"use strict" +var _$SegmentSelector_227 = SegmentSelector; -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 [] -} +var buildLog = false; +var epsilon = _$Epsilon_222(); -var _$dupe_73 = dupe -var _$pool_207 = {}; -(function (global,Buffer){ -'use strict' +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_221(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v){ + return epsilon.epsilon(v); + }, -/* removed: var _$twiddle_35 = require('bit-twiddle') */; -/* removed: var _$dupe_73 = require('dup') */; + // core API + segments: function(poly){ + var i = _$Intersecter_224(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_224(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_227.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_227.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_227.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_227.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_227.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_226(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, -//Legacy pool support -if(!global.__TYPEDARRAY_POOL) { - global.__TYPEDARRAY_POOL = { - UINT8 : _$dupe_73([32, 0]) - , UINT16 : _$dupe_73([32, 0]) - , UINT32 : _$dupe_73([32, 0]) - , INT8 : _$dupe_73([32, 0]) - , INT16 : _$dupe_73([32, 0]) - , INT32 : _$dupe_73([32, 0]) - , FLOAT : _$dupe_73([32, 0]) - , DOUBLE : _$dupe_73([32, 0]) - , DATA : _$dupe_73([32, 0]) - , UINT8C : _$dupe_73([32, 0]) - , BUFFER : _$dupe_73([32, 0]) - } -} + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_223.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_223.fromPolygon(PolyBool, epsilon, poly); + }, -var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' -var POOL = global.__TYPEDARRAY_POOL + // 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); + } +}; -//Upgrade pool -if(!POOL.UINT8C) { - POOL.UINT8C = _$dupe_73([32, 0]) -} -if(!POOL.BUFFER) { - POOL.BUFFER = _$dupe_73([32, 0]) +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); } -//New technique: Only allocate from ArrayBufferView and Buffer -var DATA = POOL.DATA - , BUFFER = POOL.BUFFER +if (typeof window === 'object') + window.PolyBool = PolyBool; -_$pool_207.free = function free(array) { - if(Buffer.isBuffer(array)) { - BUFFER[_$twiddle_35.log2(array.length)].push(array) - } else { - if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { - array = array.buffer - } - if(!array) { - return - } - var n = array.length || array.byteLength - var log_n = _$twiddle_35.log2(n)|0 - DATA[log_n].push(array) - } -} +var _$PolyBool_220 = PolyBool; -function freeArrayBuffer(buffer) { - if(!buffer) { - return - } - var n = buffer.length || buffer.byteLength - var log_n = _$twiddle_35.log2(n) - DATA[log_n].push(buffer) -} +var _$polygon_437 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function freeTypedArray(array) { - freeArrayBuffer(array.buffer) -} -_$pool_207.freeUint8 = -_$pool_207.freeUint16 = -_$pool_207.freeUint32 = -_$pool_207.freeInt8 = -_$pool_207.freeInt16 = -_$pool_207.freeInt32 = -_$pool_207.freeFloat32 = -_$pool_207.freeFloat = -_$pool_207.freeFloat64 = -_$pool_207.freeDouble = -_$pool_207.freeUint8Clamped = -_$pool_207.freeDataView = freeTypedArray +'use strict'; -_$pool_207.freeArrayBuffer = freeArrayBuffer +var dot = _$matrix_431.dot; +var __BADNUM_437 = _$numerical_404.BADNUM; -_$pool_207.freeBuffer = function freeBuffer(array) { - BUFFER[_$twiddle_35.log2(array.length)].push(array) -} +var polygon = _$polygon_437 = {}; -_$pool_207.malloc = function malloc(n, dtype) { - if(dtype === undefined || dtype === 'arraybuffer') { - return mallocArrayBuffer(n) - } else { - switch(dtype) { - case 'uint8': - return mallocUint8(n) - case 'uint16': - return mallocUint16(n) - case 'uint32': - return mallocUint32(n) - case 'int8': - return mallocInt8(n) - case 'int16': - return mallocInt16(n) - case 'int32': - return mallocInt32(n) - case 'float': - case 'float32': - return mallocFloat(n) - case 'double': - case 'float64': - return mallocDouble(n) - case 'uint8_clamped': - return mallocUint8Clamped(n) - case 'buffer': - return mallocBuffer(n) - case 'data': - case 'dataview': - return mallocDataView(n) +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - default: - return null + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; + + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); } - } - return null -} -function mallocArrayBuffer(n) { - var n = _$twiddle_35.nextPow2(n) - var log_n = _$twiddle_35.log2(n) - var d = DATA[log_n] - if(d.length > 0) { - return d.pop() - } - return new ArrayBuffer(n) -} -_$pool_207.mallocArrayBuffer = mallocArrayBuffer + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed -function mallocUint8(n) { - return new Uint8Array(mallocArrayBuffer(n), 0, n) -} -_$pool_207.mallocUint8 = mallocUint8 + var isRect = false, + rectFirstEdgeTest; -function mallocUint16(n) { - return new Uint16Array(mallocArrayBuffer(2*n), 0, n) -} -_$pool_207.mallocUint16 = mallocUint16 + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; + } + } + } -function mallocUint32(n) { - return new Uint32Array(mallocArrayBuffer(4*n), 0, n) -} -_$pool_207.mallocUint32 = mallocUint32 + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; -function mallocInt8(n) { - return new Int8Array(mallocArrayBuffer(n), 0, n) -} -_$pool_207.mallocInt8 = mallocInt8 + if(x === __BADNUM_437 || x < xmin || x > xmax || y === __BADNUM_437 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; -function mallocInt16(n) { - return new Int16Array(mallocArrayBuffer(2*n), 0, n) -} -_$pool_207.mallocInt16 = mallocInt16 + return true; + } -function mallocInt32(n) { - return new Int32Array(mallocArrayBuffer(4*n), 0, n) -} -_$pool_207.mallocInt32 = mallocInt32 + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; -function mallocFloat(n) { - return new Float32Array(mallocArrayBuffer(4*n), 0, n) -} -_$pool_207.mallocFloat32 = _$pool_207.mallocFloat = mallocFloat + if(x === __BADNUM_437 || x < xmin || x > xmax || y === __BADNUM_437 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } -function mallocDouble(n) { - return new Float64Array(mallocArrayBuffer(8*n), 0, n) -} -_$pool_207.mallocFloat64 = _$pool_207.mallocDouble = mallocDouble + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; -function mallocUint8Clamped(n) { - if(hasUint8C) { - return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) - } else { - return mallocUint8(n) - } -} -_$pool_207.mallocUint8Clamped = mallocUint8Clamped + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); -function mallocDataView(n) { - return new DataView(mallocArrayBuffer(n), 0, n) -} -_$pool_207.mallocDataView = mallocDataView + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); -function mallocBuffer(n) { - n = _$twiddle_35.nextPow2(n) - var log_n = _$twiddle_35.log2(n) - var cache = BUFFER[log_n] - if(cache.length > 0) { - return cache.pop() - } - return new Buffer(n) -} -_$pool_207.mallocBuffer = mallocBuffer + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } -_$pool_207.clearCache = function clearCache() { - for(var i=0; i<32; ++i) { - POOL.UINT8[i].length = 0 - POOL.UINT16[i].length = 0 - POOL.UINT32[i].length = 0 - POOL.INT8[i].length = 0 - POOL.INT16[i].length = 0 - POOL.INT32[i].length = 0 - POOL.FLOAT[i].length = 0 - POOL.DOUBLE[i].length = 0 - POOL.UINT8C[i].length = 0 - DATA[i].length = 0 - BUFFER[i].length = 0 - } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_$buffer_46.Buffer) -"use strict" + if(y <= ycross && x !== xmini) crossings++; + } + } -/* removed: var _$pool_207 = require("typedarray-pool") */; -/* removed: var _$ndarrayOps_142 = require("ndarray-ops") */; -/* removed: var _$wrappedNDArrayCtor_143 = require("ndarray") */; + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; + } -var SUPPORTED_TYPES = [ - "uint8", - "uint8_clamped", - "uint16", - "uint32", - "int8", - "int16", - "int32", - "float32" ] + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; + } + } -function GLBuffer(gl, type, handle, length, usage) { - this.gl = gl - this.type = type - this.handle = handle - this.length = length - this.usage = usage -} + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; +}; -var proto = GLBuffer.prototype +/** + * Test multiple polygons + */ +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; -proto.bind = function() { - this.gl.bindBuffer(this.type, this.handle) -} + for(var i = 0; i < list.length; i++) { + 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); + } -proto.unbind = function() { - this.gl.bindBuffer(this.type, null) -} + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } -proto.dispose = function() { - this.gl.deleteBuffer(this.handle) -} + return yes; + } -function updateTypeArray(gl, type, len, usage, data, offset) { - var dataLen = data.length * data.BYTES_PER_ELEMENT - if(offset < 0) { - gl.bufferData(type, data, usage) - return dataLen - } - if(dataLen + offset > len) { - throw new Error("gl-buffer: If resizing buffer, must not specify offset") - } - gl.bufferSubData(type, offset, data) - return len -} + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; +}; -function makeScratchTypeArray(array, dtype) { - var res = _$pool_207.malloc(array.length, dtype) - var n = array.length - for(var i=0; i=0; --i) { - if(stride[i] !== n) { - return false - } - n *= shape[i] - } - return true -} + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); -proto.update = function(array, offset) { - if(typeof offset !== "number") { - offset = -1 - } - this.bind() - if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray - var dtype = array.dtype - if(SUPPORTED_TYPES.indexOf(dtype) < 0) { - dtype = "float32" - } - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - var ext = gl.getExtension('OES_element_index_uint') - if(ext && dtype !== "uint16") { - dtype = "uint32" - } else { - dtype = "uint16" - } - } - if(dtype === array.dtype && isPacked(array.shape, array.stride)) { - if(array.offset === 0 && array.data.length === array.shape[0]) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) - } - } else { - var tmp = _$pool_207.malloc(array.size, dtype) - var ndt = _$wrappedNDArrayCtor_143(tmp, array.shape) - _$ndarrayOps_142.assign(ndt, array) - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) - } - _$pool_207.free(tmp) - } - } else if(Array.isArray(array)) { //Vanilla array - var t - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - t = makeScratchTypeArray(array, "uint16") - } else { - t = makeScratchTypeArray(array, "float32") - } - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; } - _$pool_207.free(t) - } else if(typeof array === "object" && typeof array.length === "number") { //Typed array - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) - } else if(typeof array === "number" || array === undefined) { //Number/default - if(offset >= 0) { - throw new Error("gl-buffer: Cannot specify offset when resizing buffer") + return false; +}; + +/** + * Make a filtering polygon, to minimize the number of segments + * + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon + * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs + */ +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; + + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); + + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } + } } - array = array | 0 - if(array <= 0) { - array = 1 + + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); } - this.gl.bufferData(this.type, array|0, this.usage) - this.length = array - } else { //Error, case should not happen - throw new Error("gl-buffer: Invalid data type") - } -} -function __createBuffer_83(gl, data, type, usage) { - type = type || gl.ARRAY_BUFFER - usage = usage || gl.DYNAMIC_DRAW - if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { - throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") - } - if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { - throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") - } - var handle = gl.createBuffer() - var result = new GLBuffer(gl, type, handle, 0, usage) - result.update(data) - return result -} + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; +}; -var _$createBuffer_83 = __createBuffer_83 +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 _$browser_124 = function(strings) { - if (typeof strings === 'string') strings = [strings] - var exprs = [].slice.call(arguments,1) - var parts = [] - for (var i = 0; i < strings.length-1; i++) { - parts.push(strings[i], exprs[i] || '') - } - parts.push(strings[i]) - return parts.join('') -} -'use strict' - -/* removed: var _$browser_124 = require('glslify') */; - -var FRAGMENT = _$browser_124(["precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n"]) - -var _$shaders_98 = { - lineVert: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n"]), - lineFrag: FRAGMENT, - textVert: _$browser_124(["#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n"]), - textFrag: FRAGMENT, - gridVert: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n"]), - gridFrag: FRAGMENT, - boxVert: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n"]), - tickVert: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"]) -} +'use strict'; -function GLError (rawError, shortMessage, longMessage) { - this.shortMessage = shortMessage || '' - this.longMessage = longMessage || '' - this.rawError = rawError || '' - this.message = - 'gl-shader: ' + (shortMessage || rawError || '') + - (longMessage ? '\n'+longMessage : '') - this.stack = (new Error()).stack -} -GLError.prototype = new Error -GLError.prototype.name = 'GLError' -GLError.prototype.constructor = GLError -var _$GLError_108 = GLError +/* removed: var _$PolyBool_220 = require('polybooljs'); */; -'use strict' +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$color_301 = require('../../components/color'); */; +/* removed: var _$fx_343 = require('../../components/fx'); */; -var _$createAttributeWrapper_109 = createAttributeWrapper +/* removed: var _$polygon_437 = require('../../lib/polygon'); */; +/* removed: var _$throttle_450 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_340.makeEventData; +var getFromId = _$axis_ids_473.getFromId; +var __sortModules_487 = _$sort_modules_513.sortModules; -/* removed: var _$GLError_108 = require("./GLError") */; +/* removed: var _$constants_475 = require('./constants'); */; +var MINSELECT = _$constants_475.MINSELECT; -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 filteredPolygon = _$polygon_437.filter; +var polygonTester = _$polygon_437.tester; +var multipolygonTester = _$polygon_437.multitester; -var __proto_109 = ShaderAttribute.prototype +function getAxId(ax) { return ax._id; } -__proto_109.pointer = function setAttribPointer( - type - , normalized - , stride - , offset) { +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; - var self = this - var gl = self._gl - var location = self._locations[self._index] + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); - gl.vertexAttribPointer( - location - , self._dimension - , type || gl.FLOAT - , !!normalized - , stride || 0 - , offset || 0) - gl.enableVertexAttribArray(location) -} + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + } -__proto_109.set = function(x0, x1, x2, x3) { - return this._constFunc(this._locations[this._index], x0, x1, x2, x3) -} + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } -Object.defineProperty(__proto_109, '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 + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_475.BENDPX); } - return v|0 - } -}) -//Adds a vector attribute to obj -function addVectorAttribute( - gl - , wrapper - , index - , locations - , dimension - , obj - , name) { + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); - //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_108('', '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_108('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addMatrixAttribute( - gl - , wrapper - , locs - , locations - , d - , obj - , name) + ranges[ax._id] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(poly[axLetter + 'max']) + ].sort(ascending); + } + }; } else { - throw new _$GLError_108('', 'Unknown data type for attribute ' + name + ': ' + type) + 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)); + } + }; } - break } - } - return obj -} -'use strict' + dragOptions.moveFn = function(dx0, dy0) { + x1 = Math.max(0, Math.min(pw, dx0 + x0)); + y1 = Math.max(0, Math.min(ph, dy0 + y0)); -var _$makeReflectTypes_111 = makeReflectTypes + var dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); -//Construct type info for reflection. -// -// This iterates over the flattened list of uniform type values and smashes them into a JSON object. -// -// The leaves of the resulting object are either indices or type strings representing primitive glslify types -function makeReflectTypes(uniforms, useIndex) { - var obj = {} - for(var i=0; i 1) { - if(!(x[0] in o)) { - o[x[0]] = [] - } - o = o[x[0]] - for(var k=1; k 4) { - throw new _$GLError_108('', 'Invalid data type') - } - switch(type.charAt(0)) { - case 'b': - case 'i': - return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' - case 'v': - return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' - default: - throw new _$GLError_108('', 'Unrecognized data type for vector ' + name + ': ' + type) - } - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new _$GLError_108('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) - } - return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' - } else { - throw new _$GLError_108('', 'Unknown uniform data type for ' + name + ': ' + type) + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.selectedpoints = []; } - break - } - } - function enumerateIndices(prefix, type) { - if(typeof type !== 'object') { - return [ [prefix, type] ] + 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); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + fullData.selectedpoints.push(pt.pointIndex); + } + } } - var indices = [] - for(var id in type) { - var prop = type[id] - var tprefix = prefix - if(parseInt(id) + '' === id) { - tprefix += '[' + id + ']' - } else { - tprefix += '.' + id - } - if(typeof prop === 'object') { - indices.push.apply(indices, enumerateIndices(tprefix, prop)) - } else { - indices.push([tprefix, prop]) - } + else { + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + delete trace.selectedpoints; + delete trace._input.selectedpoints; + } } - return indices - } - function makeSetter(type) { - var code = [ 'return function updateProperty(obj){' ] - var indices = enumerateIndices('', type) - for(var i=0; i 4) { - throw new _$GLError_108('', 'Invalid data type') - } - if(type.charAt(0) === 'b') { - return makeVector(d, false) - } - return makeVector(d, 0) - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new _$GLError_108('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) - } - return makeVector(d*d, 0) + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); } else { - throw new _$GLError_108('', 'Unknown uniform data type for ' + name + ': ' + type) + lookup[name] = [searchInfo]; } - break } - } - function storeProperty(obj, prop, type) { - if(typeof type === 'object') { - var child = processObject(type) - Object.defineProperty(obj, prop, { - get: identity(child), - set: makeSetter(type), - enumerable: true, - configurable: false - }) - } else { - if(locations[type]) { - Object.defineProperty(obj, prop, { - get: makeGetter(type), - set: makeSetter(type), - enumerable: true, - configurable: false - }) - } else { - obj[prop] = defaultValue(uniforms[type].type) - } + var keys = Object.keys(lookup).sort(__sortModules_487); + + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_514.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } + } } - } +} - function processObject(obj) { - var result - if(Array.isArray(obj)) { - result = new Array(obj.length) - for(var i=0; i 1) { - for(var j=0; j - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; -'use strict'; + recomputeAxisLists(); -/** - * Results cache - */ + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } -var res = ''; -var cache; + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; -/** - * Expose `repeat` - */ + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_478(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_478(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; -var _$repeat_176 = repeat; + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; -/** - * 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 - */ + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_478(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); - } + if(numClicks === 2 && !singleEnd) doubleClick(); - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; + if(isMainDrag) { + _$fx_343.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } else if (res.length >= max) { - return res.substr(0, max); - } + if(ax.fixedrange) return; - while (max > res.length && num > 1) { - if (num & 1) { - res += str; + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; + + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_71.select(dragger) + .call(_$svg_text_utils_449.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_514.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; + + _$dragelement_323.init(dragOptions); + + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; + + // collected changes to be made to the plot by relayout at the end + var updates = {}; + + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_263(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; + + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); + + corners = makeCorners(zoomlayer, xs, ys); + + __clearSelect_478(zoomlayer); } - num >>= 1; - str += str; - } + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } - res += str; - res = res.substr(0, max); - return res; -} + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); -/*! - * pad-left - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); -'use strict'; + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); + } -/* removed: var _$repeat_176 = require('repeat-string'); */; + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; -var _$padLeft_147 = function padLeft(str, num, ch) { - ch = typeof ch !== 'undefined' ? (ch + '') : ' '; - return _$repeat_176(ch, num) + str; -}; -/* removed: var _$padLeft_147 = require('pad-left') */; + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; + } -var _$addLineNumbers_11 = addLineNumbers -function addLineNumbers (string, start, delim) { - start = typeof start === 'number' ? start : 1 - delim = delim || ': ' + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } - var lines = string.split(/\r?\n/) - var totalDigits = String(lines.length + start - 1).length - return lines.map(function (line, i) { - var c = i + start - var digits = String(c).length - var prefix = _$padLeft_147(c, totalDigits - digits) - return prefix + delim + line - }).join('\n') -} + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } -var _$numbers_84 = { - 0: 'NONE', - 1: 'ONE', - 2: 'LINE_LOOP', - 3: 'LINE_STRIP', - 4: 'TRIANGLES', - 5: 'TRIANGLE_STRIP', - 6: 'TRIANGLE_FAN', - 256: 'DEPTH_BUFFER_BIT', - 512: 'NEVER', - 513: 'LESS', - 514: 'EQUAL', - 515: 'LEQUAL', - 516: 'GREATER', - 517: 'NOTEQUAL', - 518: 'GEQUAL', - 519: 'ALWAYS', - 768: 'SRC_COLOR', - 769: 'ONE_MINUS_SRC_COLOR', - 770: 'SRC_ALPHA', - 771: 'ONE_MINUS_SRC_ALPHA', - 772: 'DST_ALPHA', - 773: 'ONE_MINUS_DST_ALPHA', - 774: 'DST_COLOR', - 775: 'ONE_MINUS_DST_COLOR', - 776: 'SRC_ALPHA_SATURATE', - 1024: 'STENCIL_BUFFER_BIT', - 1028: 'FRONT', - 1029: 'BACK', - 1032: 'FRONT_AND_BACK', - 1280: 'INVALID_ENUM', - 1281: 'INVALID_VALUE', - 1282: 'INVALID_OPERATION', - 1285: 'OUT_OF_MEMORY', - 1286: 'INVALID_FRAMEBUFFER_OPERATION', - 2304: 'CW', - 2305: 'CCW', - 2849: 'LINE_WIDTH', - 2884: 'CULL_FACE', - 2885: 'CULL_FACE_MODE', - 2886: 'FRONT_FACE', - 2928: 'DEPTH_RANGE', - 2929: 'DEPTH_TEST', - 2930: 'DEPTH_WRITEMASK', - 2931: 'DEPTH_CLEAR_VALUE', - 2932: 'DEPTH_FUNC', - 2960: 'STENCIL_TEST', - 2961: 'STENCIL_CLEAR_VALUE', - 2962: 'STENCIL_FUNC', - 2963: 'STENCIL_VALUE_MASK', - 2964: 'STENCIL_FAIL', - 2965: 'STENCIL_PASS_DEPTH_FAIL', - 2966: 'STENCIL_PASS_DEPTH_PASS', - 2967: 'STENCIL_REF', - 2968: 'STENCIL_WRITEMASK', - 2978: 'VIEWPORT', - 3024: 'DITHER', - 3042: 'BLEND', - 3088: 'SCISSOR_BOX', - 3089: 'SCISSOR_TEST', - 3106: 'COLOR_CLEAR_VALUE', - 3107: 'COLOR_WRITEMASK', - 3317: 'UNPACK_ALIGNMENT', - 3333: 'PACK_ALIGNMENT', - 3379: 'MAX_TEXTURE_SIZE', - 3386: 'MAX_VIEWPORT_DIMS', - 3408: 'SUBPIXEL_BITS', - 3410: 'RED_BITS', - 3411: 'GREEN_BITS', - 3412: 'BLUE_BITS', - 3413: 'ALPHA_BITS', - 3414: 'DEPTH_BITS', - 3415: 'STENCIL_BITS', - 3553: 'TEXTURE_2D', - 4352: 'DONT_CARE', - 4353: 'FASTEST', - 4354: 'NICEST', - 5120: 'BYTE', - 5121: 'UNSIGNED_BYTE', - 5122: 'SHORT', - 5123: 'UNSIGNED_SHORT', - 5124: 'INT', - 5125: 'UNSIGNED_INT', - 5126: 'FLOAT', - 5386: 'INVERT', - 5890: 'TEXTURE', - 6401: 'STENCIL_INDEX', - 6402: 'DEPTH_COMPONENT', - 6406: 'ALPHA', - 6407: 'RGB', - 6408: 'RGBA', - 6409: 'LUMINANCE', - 6410: 'LUMINANCE_ALPHA', - 7680: 'KEEP', - 7681: 'REPLACE', - 7682: 'INCR', - 7683: 'DECR', - 7936: 'VENDOR', - 7937: 'RENDERER', - 7938: 'VERSION', - 9728: 'NEAREST', - 9729: 'LINEAR', - 9984: 'NEAREST_MIPMAP_NEAREST', - 9985: 'LINEAR_MIPMAP_NEAREST', - 9986: 'NEAREST_MIPMAP_LINEAR', - 9987: 'LINEAR_MIPMAP_LINEAR', - 10240: 'TEXTURE_MAG_FILTER', - 10241: 'TEXTURE_MIN_FILTER', - 10242: 'TEXTURE_WRAP_S', - 10243: 'TEXTURE_WRAP_T', - 10497: 'REPEAT', - 10752: 'POLYGON_OFFSET_UNITS', - 16384: 'COLOR_BUFFER_BIT', - 32769: 'CONSTANT_COLOR', - 32770: 'ONE_MINUS_CONSTANT_COLOR', - 32771: 'CONSTANT_ALPHA', - 32772: 'ONE_MINUS_CONSTANT_ALPHA', - 32773: 'BLEND_COLOR', - 32774: 'FUNC_ADD', - 32777: 'BLEND_EQUATION_RGB', - 32778: 'FUNC_SUBTRACT', - 32779: 'FUNC_REVERSE_SUBTRACT', - 32819: 'UNSIGNED_SHORT_4_4_4_4', - 32820: 'UNSIGNED_SHORT_5_5_5_1', - 32823: 'POLYGON_OFFSET_FILL', - 32824: 'POLYGON_OFFSET_FACTOR', - 32854: 'RGBA4', - 32855: 'RGB5_A1', - 32873: 'TEXTURE_BINDING_2D', - 32926: 'SAMPLE_ALPHA_TO_COVERAGE', - 32928: 'SAMPLE_COVERAGE', - 32936: 'SAMPLE_BUFFERS', - 32937: 'SAMPLES', - 32938: 'SAMPLE_COVERAGE_VALUE', - 32939: 'SAMPLE_COVERAGE_INVERT', - 32968: 'BLEND_DST_RGB', - 32969: 'BLEND_SRC_RGB', - 32970: 'BLEND_DST_ALPHA', - 32971: 'BLEND_SRC_ALPHA', - 33071: 'CLAMP_TO_EDGE', - 33170: 'GENERATE_MIPMAP_HINT', - 33189: 'DEPTH_COMPONENT16', - 33306: 'DEPTH_STENCIL_ATTACHMENT', - 33635: 'UNSIGNED_SHORT_5_6_5', - 33648: 'MIRRORED_REPEAT', - 33901: 'ALIASED_POINT_SIZE_RANGE', - 33902: 'ALIASED_LINE_WIDTH_RANGE', - 33984: 'TEXTURE0', - 33985: 'TEXTURE1', - 33986: 'TEXTURE2', - 33987: 'TEXTURE3', - 33988: 'TEXTURE4', - 33989: 'TEXTURE5', - 33990: 'TEXTURE6', - 33991: 'TEXTURE7', - 33992: 'TEXTURE8', - 33993: 'TEXTURE9', - 33994: 'TEXTURE10', - 33995: 'TEXTURE11', - 33996: 'TEXTURE12', - 33997: 'TEXTURE13', - 33998: 'TEXTURE14', - 33999: 'TEXTURE15', - 34000: 'TEXTURE16', - 34001: 'TEXTURE17', - 34002: 'TEXTURE18', - 34003: 'TEXTURE19', - 34004: 'TEXTURE20', - 34005: 'TEXTURE21', - 34006: 'TEXTURE22', - 34007: 'TEXTURE23', - 34008: 'TEXTURE24', - 34009: 'TEXTURE25', - 34010: 'TEXTURE26', - 34011: 'TEXTURE27', - 34012: 'TEXTURE28', - 34013: 'TEXTURE29', - 34014: 'TEXTURE30', - 34015: 'TEXTURE31', - 34016: 'ACTIVE_TEXTURE', - 34024: 'MAX_RENDERBUFFER_SIZE', - 34041: 'DEPTH_STENCIL', - 34055: 'INCR_WRAP', - 34056: 'DECR_WRAP', - 34067: 'TEXTURE_CUBE_MAP', - 34068: 'TEXTURE_BINDING_CUBE_MAP', - 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', - 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', - 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', - 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', - 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', - 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', - 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', - 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', - 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', - 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', - 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', - 34342: 'CURRENT_VERTEX_ATTRIB', - 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', - 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', - 34467: 'COMPRESSED_TEXTURE_FORMATS', - 34660: 'BUFFER_SIZE', - 34661: 'BUFFER_USAGE', - 34816: 'STENCIL_BACK_FUNC', - 34817: 'STENCIL_BACK_FAIL', - 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', - 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', - 34877: 'BLEND_EQUATION_ALPHA', - 34921: 'MAX_VERTEX_ATTRIBS', - 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', - 34930: 'MAX_TEXTURE_IMAGE_UNITS', - 34962: 'ARRAY_BUFFER', - 34963: 'ELEMENT_ARRAY_BUFFER', - 34964: 'ARRAY_BUFFER_BINDING', - 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', - 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', - 35040: 'STREAM_DRAW', - 35044: 'STATIC_DRAW', - 35048: 'DYNAMIC_DRAW', - 35632: 'FRAGMENT_SHADER', - 35633: 'VERTEX_SHADER', - 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', - 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', - 35663: 'SHADER_TYPE', - 35664: 'FLOAT_VEC2', - 35665: 'FLOAT_VEC3', - 35666: 'FLOAT_VEC4', - 35667: 'INT_VEC2', - 35668: 'INT_VEC3', - 35669: 'INT_VEC4', - 35670: 'BOOL', - 35671: 'BOOL_VEC2', - 35672: 'BOOL_VEC3', - 35673: 'BOOL_VEC4', - 35674: 'FLOAT_MAT2', - 35675: 'FLOAT_MAT3', - 35676: 'FLOAT_MAT4', - 35678: 'SAMPLER_2D', - 35680: 'SAMPLER_CUBE', - 35712: 'DELETE_STATUS', - 35713: 'COMPILE_STATUS', - 35714: 'LINK_STATUS', - 35715: 'VALIDATE_STATUS', - 35716: 'INFO_LOG_LENGTH', - 35717: 'ATTACHED_SHADERS', - 35718: 'ACTIVE_UNIFORMS', - 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', - 35720: 'SHADER_SOURCE_LENGTH', - 35721: 'ACTIVE_ATTRIBUTES', - 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', - 35724: 'SHADING_LANGUAGE_VERSION', - 35725: 'CURRENT_PROGRAM', - 36003: 'STENCIL_BACK_REF', - 36004: 'STENCIL_BACK_VALUE_MASK', - 36005: 'STENCIL_BACK_WRITEMASK', - 36006: 'FRAMEBUFFER_BINDING', - 36007: 'RENDERBUFFER_BINDING', - 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', - 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', - 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', - 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', - 36053: 'FRAMEBUFFER_COMPLETE', - 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', - 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', - 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', - 36061: 'FRAMEBUFFER_UNSUPPORTED', - 36064: 'COLOR_ATTACHMENT0', - 36096: 'DEPTH_ATTACHMENT', - 36128: 'STENCIL_ATTACHMENT', - 36160: 'FRAMEBUFFER', - 36161: 'RENDERBUFFER', - 36162: 'RENDERBUFFER_WIDTH', - 36163: 'RENDERBUFFER_HEIGHT', - 36164: 'RENDERBUFFER_INTERNAL_FORMAT', - 36168: 'STENCIL_INDEX8', - 36176: 'RENDERBUFFER_RED_SIZE', - 36177: 'RENDERBUFFER_GREEN_SIZE', - 36178: 'RENDERBUFFER_BLUE_SIZE', - 36179: 'RENDERBUFFER_ALPHA_SIZE', - 36180: 'RENDERBUFFER_DEPTH_SIZE', - 36181: 'RENDERBUFFER_STENCIL_SIZE', - 36194: 'RGB565', - 36336: 'LOW_FLOAT', - 36337: 'MEDIUM_FLOAT', - 36338: 'HIGH_FLOAT', - 36339: 'LOW_INT', - 36340: 'MEDIUM_INT', - 36341: 'HIGH_INT', - 36346: 'SHADER_COMPILER', - 36347: 'MAX_VERTEX_UNIFORM_VECTORS', - 36348: 'MAX_VARYING_VECTORS', - 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', - 37440: 'UNPACK_FLIP_Y_WEBGL', - 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', - 37442: 'CONTEXT_LOST_WEBGL', - 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', - 37444: 'BROWSER_DEFAULT_WEBGL' -} + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } -/* removed: var _$numbers_84 = require('./1.0/numbers') */; + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_475.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; -var _$lookupConstant_85 = function lookupConstant (number) { - return _$numbers_84[number] -} + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } -var _$_atob_16 = function _atob(str) { - return atob(str) -} + if(redrawTimer === null) { + __clearSelect_478(zoomlayer); + } -var _$builtins_119 = [ - // 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' -] + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } -// 300es builtins/reserved words that were previously valid in v100 -/* removed: var _$builtins_119 = require('./builtins') */; + var pc = gd.querySelector('.plotly'); -// The texture2D|Cube functions have been removed -// And the gl_ features are updated -_$builtins_119 = _$builtins_119.slice().filter(function (b) { - return !/^(gl\_|texture)/.test(b) -}) + recomputeAxisLists(); -var _$builtins300es_118 = _$builtins_119.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' + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } - // 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' -]) + clearTimeout(redrawTimer); -var _$literals_121 = [ - // current - 'precision' - , 'highp' - , 'mediump' - , 'lowp' - , 'attribute' - , 'const' - , 'uniform' - , 'varying' - , 'break' - , 'continue' - , 'do' - , 'for' - , 'while' - , 'if' - , 'else' - , 'in' - , 'out' - , 'inout' - , 'float' - , 'int' - , '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' + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_425.log('Did not find wheel motion attributes: ', e); + return; + } - // 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' -] + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; -/* removed: var _$literals_121 = require('./literals') */; + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; -var _$literals300es_120 = _$literals_121.slice().concat([ - 'layout' - , 'centroid' - , 'smooth' - , 'case' - , 'mat2x2' - , 'mat2x3' - , 'mat2x4' - , 'mat3x2' - , 'mat3x3' - , 'mat3x4' - , 'mat4x2' - , 'mat4x3' - , 'mat4x4' - , 'uint' - , 'uvec2' - , 'uvec3' - , 'uvec4' - , 'samplerCubeShadow' - , 'sampler2DArray' - , 'sampler2DArrayShadow' - , 'isampler2D' - , 'isampler3D' - , 'isamplerCube' - , 'isampler2DArray' - , 'usampler2D' - , 'usampler3D' - , 'usamplerCube' - , 'usampler2DArray' - , 'coherent' - , 'restrict' - , 'readonly' - , 'writeonly' - , 'resource' - , 'atomic_uint' - , 'noperspective' - , 'patch' - , 'sample' - , 'subroutine' - , 'common' - , 'partition' - , 'active' - , 'filter' - , 'image1D' - , 'image2D' - , 'image3D' - , 'imageCube' - , 'iimage1D' - , 'iimage2D' - , 'iimage3D' - , 'iimageCube' - , 'uimage1D' - , 'uimage2D' - , 'uimage3D' - , 'uimageCube' - , 'image1DArray' - , 'image2DArray' - , 'iimage1DArray' - , 'iimage2DArray' - , 'uimage1DArray' - , 'uimage2DArray' - , 'image1DShadow' - , 'image2DShadow' - , 'image1DArrayShadow' - , 'image2DArrayShadow' - , 'imageBuffer' - , 'iimageBuffer' - , 'uimageBuffer' - , 'sampler1DArray' - , 'sampler1DArrayShadow' - , 'isampler1D' - , 'isampler1DArray' - , 'usampler1D' - , 'usampler1DArray' - , 'isampler2DRect' - , 'usampler2DRect' - , 'samplerBuffer' - , 'isamplerBuffer' - , 'usamplerBuffer' - , 'sampler2DMS' - , 'isampler2DMS' - , 'usampler2DMS' - , 'sampler2DMSArray' - , 'isampler2DMSArray' - , 'usampler2DMSArray' -]) + var axRange = _$lib_425.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } -var _$operators_122 = [ - '<<=' - , '>>=' - , '++' - , '--' - , '<<' - , '>>' - , '<=' - , '>=' - , '==' - , '!=' - , '&&' - , '||' - , '+=' - , '-=' - , '*=' - , '/=' - , '%=' - , '&=' - , '^^' - , '^=' - , '|=' - , '(' - , ')' - , '[' - , ']' - , '.' - , '!' - , '~' - , '*' - , '/' - , '%' - , '+' - , '-' - , '<' - , '>' - , '&' - , '^' - , '|' - , '?' - , ':' - , '=' - , ',' - , ';' - , '{' - , '}' -] + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; -var _$tokenize_117 = tokenize + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } -var __dummy_117$0 = 0 - , __dummy_117$1 = 0 - , __dummy_117$2 = 0 - , __dummy_117$3 = 0 - , __dummy_117$4 = 0 + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; -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 + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } -var map = [ - 'block-comment' - , 'line-comment' - , 'preprocessor' - , 'operator' - , 'integer' - , 'float' - , 'ident' - , 'builtin' - , 'keyword' - , 'whitespace' - , 'eof' - , 'integer' -] + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } -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 + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); - opt = opt || {} - var allBuiltins = _$builtins_119 - var allLiterals = _$literals_121 - if (opt.version === '300 es') { - allBuiltins = _$builtins300es_118 - allLiterals = _$literals300es_120 - } + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; - return function(data) { - tokens = [] - if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data) - return end() - } + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); - function token(data) { - if (data.length) { - tokens.push({ - type: map[mode] - , data: data - , position: start - , line: line - , column: col - }) + dragTail(zoomMode); + }, REDRAWDELAY); + + e.preventDefault(); + return; } - } - function write(chunk) { - i = 0 - input += chunk - len = input.length + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); + } - var last + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - while(c = input[i], i < len) { - last = i + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - 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 - } + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); - if(last !== i) { - switch(input[last]) { - case '\n': col = 0; ++line; break - default: ++col; break + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); } - } - } - total += i - input = input.slice(i) - return tokens - } + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - function end(chunk) { - if(content.length) { - token(content.join('')) - } + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - mode = EOF - token('(eof)') - return tokens - } + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - function normal() { - content = content.length ? [] : content + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; - if(last === '/' && c === '*') { - start = total + i - 1 - mode = BLOCK_COMMENT - last = c - return i + 1 - } + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_486(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_486(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } - if(last === '/' && c === '/') { - start = total + i - 1 - mode = LINE_COMMENT - last = c - return i + 1 + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); } - if(c === '#') { - mode = PREPROCESSOR - start = total + i - return i - } + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; - if(/\s/.test(c)) { - mode = WHITESPACE - start = total + i - return i - } + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } - isnum = /\d/.test(c) - isoperator = /[^\w_]/.test(c) + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } - start = total + i - mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN - return i - } + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_478(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } - function whitespace() { - if(/[^\s]/g.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } - content.push(c) - last = c - return i + 1 - } + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - function preprocessor() { - if((c === '\r' || c === '\n') && last !== '\\') { - token(content.join('')) - mode = NORMAL - return i - } - content.push(c) - last = c - return i + 1 - } + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } + } - function line_comment() { - return preprocessor() - } + // annotations and shapes 'draw' method is slow, + // use the finer-grained 'drawOne' method instead - function block_comment() { - if(c === '/' && last === '*') { - content.push(c) - token(content.join('')) - mode = NORMAL - return i + 1 + redrawObjs(gd._fullLayout.annotations || [], _$registry_514.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_514.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_514.getComponentMethod('images', 'draw'), true); } - content.push(c) - last = c - return i + 1 - } + function doubleClick() { + if(gd._transitioningWithDuration) return; - function operator() { - if(last === '.' && /\d/.test(c)) { - mode = FLOAT - return i - } + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; - if(last === '/' && c === '*') { - mode = BLOCK_COMMENT - return i - } + var ax, i, rangeInitial; - if(last === '/' && c === '/') { - mode = LINE_COMMENT - return i - } + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { - if(c === '.' && content.length) { - while(determine_operator(content)); + doubleClickConfig = 'autosize'; - mode = FLOAT - return i - } + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } - if(c === ';' || c === ')' || c === '(') { - if(content.length) while(determine_operator(content)); - token(c) - mode = NORMAL - return i + 1 + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); + + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } + + gd.emit('plotly_doubleclick', null); + _$registry_514.call('relayout', gd, attrs); } - 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 + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); + + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_425.syncOrAsync([ + _$plots_506.previousPromises, + function() { _$registry_514.call('relayout', gd, updates); } + ], gd); } - content.push(c) - last = c - return i + 1 - } + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; - function determine_operator(buf) { - var j = 0 - , idx - , res + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); - do { - idx = _$operators_122.indexOf(buf.slice(0, buf.length + j).join('')) - res = _$operators_122[idx] + var i, sp, xa, ya; - if(idx === -1) { - if(j-- + buf.length > 0) continue - res = buf.slice(0, 1).join('') - } + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_411(gd); + } - token(res) + if(hasSplom) { + _$registry_514.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; + } - start += res.length - content = content.slice(res.length) - return content.length - } while(1) - } + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_425.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_425.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } - function hex() { - if(/[^a-fA-F0-9]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; - content.push(c) - last = c - return i + 1 - } + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; - function integer() { - if(c === '.') { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } + var editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; - if(/[eE]/.test(c)) { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; - if(c === 'x' && content.length === 1 && content[0] === '0') { - mode = HEX - content.push(c) - last = c - return i + 1 - } + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } + + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } + + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_326.setTranslate, clipDx, clipDy) + .call(_$drawing_326.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_326.setTranslate, plotDx, plotDy) + .call(_$drawing_326.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_326.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_326.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_326.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_326.hideOutsideRangePoints, sp, '.bartext'); + } + } + } } - content.push(c) - last = c - return i + 1 - } + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; - function decimal() { - if(c === 'f') { - content.push(c) - last = c - i += 1 + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; } - if(/[eE]/.test(c)) { - content.push(c) - last = c - return i + 1 + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_486(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; } - if (c === '-' && /[eE]/.test(last)) { - content.push(c) - last = c - return i + 1 + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle']; } - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i + return dragger; +} + +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_425.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); + }); + + dragger3.call(_$setCursor_445, cursor); + + return dragger3.node(); +} + +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_71.select(dragger).call(_$drawing_326.setRect, x, y, w, h); + return dragger; +} + +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; } + return ''; +} - content.push(c) - last = c - return i + 1 - } +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - function readtoken() { - if(/[^\d\w_]/.test(c)) { - var contentstr = content.join('') - if(allLiterals.indexOf(contentstr) > -1) { - mode = KEYWORD - } else if(allBuiltins.indexOf(contentstr) > -1) { - mode = BUILTIN - } else { - mode = IDENT - } - token(content.join('')) - mode = NORMAL - return i + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_71.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_71.format('.' + String(dig) + 'g')(initialVal); } - content.push(c) - last = c - return i + 1 - } } -/* removed: var _$tokenize_117 = require('./index') */; +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; -var _$tokenizeString_123 = tokenizeString + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; -function tokenizeString(str, opt) { - var generator = _$tokenize_117(opt) - var tokens = [] + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } - tokens = tokens.concat(generator(str)) - tokens = tokens.concat(generator(null)) + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - return tokens + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } } -/* removed: var _$tokenizeString_123 = require('glsl-tokenizer') */; -/* removed: var _$_atob_16 = require('atob-lite') */; +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} -var _$getName_116 = getName +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} -function getName(src) { - var tokens = Array.isArray(src) - ? src - : _$tokenizeString_123(src) +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i] - if (token.type !== 'preprocessor') continue - var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) - if (!match) continue - if (!match[2]) continue +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} - var b64 = match[1] - var name = match[2] +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_301.background, + stroke: _$color_301.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} - return (b64 ? _$_atob_16(name) : name).trim() - } +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); } -var _$sprintf_193 = {}; -/* global window, exports, define */ +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); + } +} -!function() { - 'use strict' +function removeZoombox(gd) { + _$d3_71.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} - var re = { - not_string: /[^s]/, - not_bool: /[^t]/, - not_type: /[^T]/, - not_primitive: /[^v]/, - number: /[diefg]/, - numeric_arg: /[bcdiefguxX]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[\+\-]/ +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_425.notifier(_$lib_425._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; } +} - function sprintf(key) { - // `arguments` is not an array, but should be fine for this call - return sprintf_format(sprintf_parse(key), arguments) - } +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} - function vsprintf(fmt, argv) { - return sprintf.apply(null, [fmt].concat(argv || [])) - } +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} - function sprintf_format(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, match, pad, pad_character, pad_length, is_positive, sign - for (i = 0; i < tree_length; i++) { - if (typeof parse_tree[i] === 'string') { - output += parse_tree[i] - } - else if (Array.isArray(parse_tree[i])) { - match = parse_tree[i] // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor] - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k])) - } - arg = arg[match[2][k]] - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} - if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && arg instanceof Function) { - arg = arg() - } +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - if (re.numeric_arg.test(match[8]) && (typeof arg !== 'number' && isNaN(arg))) { - throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) - } +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; - if (re.number.test(match[8])) { - is_positive = arg >= 0 + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } } - switch (match[8]) { - case 'b': - arg = parseInt(arg, 10).toString(2) - break - case 'c': - arg = String.fromCharCode(parseInt(arg, 10)) - break - case 'd': - case 'i': - arg = parseInt(arg, 10) - break - case 'j': - arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) - break - case 'e': - arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential() - break - case 'f': - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) - break - case 'g': - arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg) - break - case 'o': - arg = (parseInt(arg, 10) >>> 0).toString(8) - break - case 's': - arg = String(arg) - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 't': - arg = String(!!arg) - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 'T': - arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 'u': - arg = parseInt(arg, 10) >>> 0 - break - case 'v': - arg = arg.valueOf() - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 'x': - arg = (parseInt(arg, 10) >>> 0).toString(16) - break - case 'X': - arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() - break - } - if (re.json.test(match[8])) { - output += arg + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; } - else { - if (re.number.test(match[8]) && (!is_positive || match[3])) { - sign = is_positive ? '+' : '-' - arg = arg.toString().replace(re.sign, '') - } - else { - sign = '' + } + } + + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; } - pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' ' - pad_length = match[6] - (sign + arg).length - pad = match[6] ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' - output += match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) } } } - return output } - var sprintf_cache = Object.create(null) - - function sprintf_parse(fmt) { - if (sprintf_cache[fmt]) { - return sprintf_cache[fmt] - } + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_425.extendFlat(xLinks, yLinks); + yLinks = {}; + } - var _fmt = fmt, match, parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree.push(match[0]) - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree.push('%') - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - } - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') - } - parse_tree.push(match) - } - else { - throw new SyntaxError('[sprintf] unexpected placeholder') - } - _fmt = _fmt.substring(match[0].length) - } - return sprintf_cache[fmt] = parse_tree + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_478(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; } - /** - * export to either browser or node.js - */ - /* eslint-disable quote-props */ - if (typeof _$sprintf_193 !== 'undefined') { - _$sprintf_193['sprintf'] = sprintf - _$sprintf_193['vsprintf'] = vsprintf + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_478(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; } - if (typeof window !== 'undefined') { - window['sprintf'] = sprintf - window['vsprintf'] = vsprintf - if (typeof define === 'function' && define['amd']) { - define(function() { - return { - 'sprintf': sprintf, - 'vsprintf': vsprintf - } - }) + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} + +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_183) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; + } + else { + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; + + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); } - /* eslint-enable quote-props */ -}() +} +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; +} -var sprintf = _$sprintf_193.sprintf; -/* removed: var _$lookupConstant_85 = require('gl-constants/lookup'); */; -/* removed: var _$getName_116 = require('glsl-shader-name'); */; -/* removed: var _$addLineNumbers_11 = require('add-line-numbers'); */; +var _$dragbox_478 = { + makeDragBox: makeDragBox, -var _$formatCompilerError_90 = formatCompilerError; + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, -function formatCompilerError(errLog, src, type) { - "use strict"; + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, - var name = _$getName_116(src) || 'of unknown name (see npm glsl-shader-name)'; + attachWheelEventHandler: attachWheelEventHandler +}; - var typeName = 'unknown type'; - if (type !== undefined) { - typeName = type === _$lookupConstant_85.FRAGMENT_SHADER ? 'fragment' : 'vertex' - } +var _$graph_interact_479 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 longForm = sprintf('Error compiling %s shader %s:\n', typeName, name); - var shortForm = sprintf("%s%s", longForm, errLog); - var errorStrings = errLog.split('\n'); - var errors = {}; +'use strict'; - 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; - } +/* removed: var _$d3_71 = require('d3'); */; - var lines = _$addLineNumbers_11(src).split('\n'); +/* removed: var _$fx_343 = require('../../components/fx'); */; +/* removed: var _$dragelement_323 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_445 = require('../../lib/setcursor'); */; - 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); - } +var __makeDragBox_479 = _$dragbox_478.makeDragBox; +var DRAGGERSIZE = _$constants_475.DRAGGERSIZE; + +_$graph_interact_479.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; + + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_71.select(gd).selectAll('.drag').remove(); + return; } - return { - long: longForm.trim(), - short: shortForm.trim() - }; -} + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !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'), + 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; -var _$hiddenStore_217 = hiddenStore; + // 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_479(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); -function hiddenStore(obj, key) { - var store = { identity: key }; - var valueOf = obj.valueOf; + 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) { + _$fx_343.hover(gd, evt, subplot); + } + }; - Object.defineProperty(obj, "valueOf", { - value: function (value) { - return value !== key ? - valueOf.apply(this, arguments) : store; - }, - writable: true - }); + _$fx_343.hover(gd, evt, subplot); - return store; -} + // 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; + }; -/* removed: var _$hiddenStore_217 = require('./hidden-store.js'); */; + /* + * 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; -var _$createStore_216 = createStore; + // 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; -function createStore() { - var key = {}; + _$dragelement_323.unhover(gd, evt); + }; - return function (obj) { - if ((typeof obj !== 'object' || obj === null) && - typeof obj !== 'function' - ) { - throw new Error('Weakmap-shim: Key must be object') + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_479(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_479(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_479(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_479(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_479(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_479(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_479(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_479(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_479(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_479(gd, plotinfo, x0, ya._offset, + DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } } + }); - var store = obj.valueOf(key); - return store && store.identity === key ? - store : _$hiddenStore_217(obj, key); - }; -} + // 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(); -// Original - @Gozola. -// https://gist.github.com/Gozala/1269991 -// This is a reimplemented version (with a few bug fixes). + hoverLayer.onmousemove = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_343.hover(gd, evt, fullLayout._hoversubplot); + }; -/* removed: var _$createStore_216 = require('./create-store.js'); */; + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_343.click(gd, evt); + }; -var _$weakMap_218 = weakMap; + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; -function weakMap() { - var privates = _$createStore_216(); + _$graph_interact_479.updateFx(fullLayout); +}; - return { - 'get': function (key, fallback) { - var store = privates(key) - return store.hasOwnProperty('value') ? - store.value : fallback - }, - 'set': function (key, value) { - privates(key).value = value; - return this; - }, - 'has': function(key) { - return 'value' in privates(key); - }, - 'delete': function (key) { - return delete privates(key).value; - } - } -} +// 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. +_$graph_interact_479.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_445(fullLayout._draggers, cursor); +}; -var _$shaderCache_113 = {}; -'use strict' +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -_$shaderCache_113.shader = getShaderReference -_$shaderCache_113.program = createProgram +'use strict'; -/* removed: var _$GLError_108 = require("./GLError") */; -/* removed: var _$formatCompilerError_90 = require('gl-format-compiler-error'); */; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; -var __weakMap_113 = typeof WeakMap === 'undefined' ? _$weakMap_218 : WeakMap -var CACHE = new __weakMap_113() + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } -var SHADER_COUNTER = 0 + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } + } -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 + return Object.keys(lookup); } -ShaderReference.prototype.dispose = function() { - if(--this.count === 0) { - var cache = this.cache - var gl = cache.gl +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_474 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; - //Remove program references - var programs = this.programs - for(var i=0, n=programs.length; i 0); - //Remove shader reference - gl.deleteShader(this.shader) - delete cache.shaders[(this.type === gl.FRAGMENT_SHADER)|0][this.src] - } -} + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; -function ContextCache(gl) { - this.gl = gl - this.shaders = [{}, {}] - this.programs = {} -} + var order = coerce('categoryorder', orderDefault); + var array; -var __proto_113 = ContextCache.prototype + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); + } -function compileShader(gl, type, src) { - var shader = gl.createShader(type) - gl.shaderSource(shader, src) - gl.compileShader(shader) - if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - var errLog = gl.getShaderInfoLog(shader) - try { - var fmt = _$formatCompilerError_90(errLog, src, type); - } catch (e){ - console.warn('Failed to format compiler error: ' + e); - throw new _$GLError_108(errLog, 'Error compiling shader:\n' + errLog) + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; } - throw new _$GLError_108(errLog, fmt.short, fmt.long) - } - return shader -} -__proto_113.getShaderReference = function(type, src) { - var gl = this.gl - var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0] - var shader = shaders[src] - if(!shader || !gl.isShader(shader.shader)) { - var shaderObj = compileShader(gl, type, src) - shader = shaders[src] = new ShaderReference( - SHADER_COUNTER++, - src, - type, - shaderObj, - [], - 1, - this) - } else { - shader.count += 1 - } - return shader -} + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } + } +}; -function linkProgram(gl, vshader, fshader, attribs, locations) { - var program = gl.createProgram() - gl.attachShader(program, vshader) - gl.attachShader(program, fshader) - for(var i=0; i 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) + if(!showZeroLine) { + delete containerOut.zerolinecolor; + delete containerOut.zerolinewidth; + } } - } +}; - this.gl.lastAttribCount = newAttribCount +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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.gl.useProgram(this.program) -} +'use strict'; -__proto_107.dispose = function() { +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; - // 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 +/* removed: var _$layout_attributes_482 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_491 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_490 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_489 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_474 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_484 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_488 = require('./set_convert'); */; - 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 -} +/** + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors + */ +var _$handleAxisDefaults_472 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; -function compareAttributes(a, b) { - if(a.name < b.name) { - return -1 - } - return 1 -} + var visible = coerce('visible', !options.cheateronly); -//Update export hook for glslify-live -__proto_107.update = function( - vertSource - , fragSource - , uniforms - , attributes) { + var axType = containerOut.type; - //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 - } + if(axType === 'date') { + var handleCalendarDefaults = _$registry_514.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); + } - var wrapper = this - var gl = wrapper.gl + _$setConvert_488(containerOut, layoutOut); - //Compile vertex and fragment shaders - var pvref = wrapper._vref - wrapper._vref = _$shaderCache_113.shader(gl, gl.VERTEX_SHADER, vertSource) - if(pvref) { - pvref.dispose() - } - wrapper.vertShader = wrapper._vref.shader - var pfref = this._fref - wrapper._fref = _$shaderCache_113.shader(gl, gl.FRAGMENT_SHADER, fragSource) - if(pfref) { - pfref.dispose() - } - wrapper.fragShader = wrapper._fref.shader + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - //If uniforms/attributes is not specified, use RT reflection - if(!uniforms || !attributes) { + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; - //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_108(errLog, 'Error linking program:' + errLog) - } + if(autoRange) coerce('rangemode'); - //Load data from runtime - uniforms = uniforms || _$runtimeReflect_112.uniforms(gl, testProgram) - attributes = attributes || _$runtimeReflect_112.attributes(gl, testProgram) + coerce('range'); + containerOut.cleanRange(); - //Release test program - gl.deleteProgram(testProgram) - } + _$handleCategoryOrderDefaults_474(containerIn, containerOut, coerce, options); - //Sort attributes lexicographically - // overrides undefined WebGL behavior for attribute locations - attributes = attributes.slice() - attributes.sort(compareAttributes) + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); - //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 - } - } + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; - //Rebuild program and recompute all uniform locations - var uniformLocations = new Array(uniforms.length) - function relink() { - wrapper.program = _$shaderCache_113.program( - gl - , wrapper._vref - , wrapper._fref - , attributeNames - , attributeLocations) + coerce('title', dfltTitle); + _$lib_425.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); - for(var i=0; i>>1,x=a[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){") + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + + var scaleanchor = _$lib_425.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes + } + }, 'scaleanchor'); + + 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, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); } - } 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("") -} + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_425.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.'); + } +}; -function compileBoundsSearch(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() -} +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. -var _$searchBounds_52 = { - ge: compileBoundsSearch(">=", false, "GE"), - gt: compileBoundsSearch(">", false, "GT"), - lt: compileBoundsSearch("<", true, "LT"), - le: compileBoundsSearch("<=", true, "LE"), - eq: compileBoundsSearch("-", true, "EQ", true) -} + var thisType = layoutOut[id2name(thisID)].type; -"use strict" + var i, j, idj, axj; -function __compileSearch_100(funcName, predicate, reversed, extraArgs, 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[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){") + var linkableAxes = []; + for(j = 0; j < allAxisIds.length; j++) { + idj = allAxisIds[j]; + if(idj === thisID) continue; + + axj = layoutOut[id2name(idj)]; + if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); } - } 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_100(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - __compileSearch_100("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_100("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[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}; } -var _$searchBounds_100 = { - ge: __compileBoundsSearch_100(">=", false, "GE"), - gt: __compileBoundsSearch_100(">", false, "GT"), - lt: __compileBoundsSearch_100("<", true, "LT"), - le: __compileBoundsSearch_100("<=", true, "LE"), - eq: __compileBoundsSearch_100("-", true, "EQ", true) + +/* + * 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; } -'use strict' - -var _$createGrid_96 = createGrid - -/* removed: var _$createBuffer_83 = require('gl-buffer') */; -/* removed: var _$createShader_107 = require('gl-shader') */; -/* removed: var _$searchBounds_100 = require('binary-search-bounds') */; -/* removed: var _$shaders_98 = require('./shaders') */; - -function Grid(plot, vbo, shader, tickShader) { - this.plot = plot - this.vbo = vbo - this.shader = shader - this.tickShader = tickShader - this.ticks = [[], []] -} - -function compareTickNum(a, b) { - return a - b -} - -var __proto_96 = Grid.prototype - -__proto_96.draw = (function() { - - var DATA_SHIFT = [0,0] - var DATA_SCALE = [0,0] - var DATA_AXIS = [0,0] - - return function() { - var plot = this.plot - var vbo = this.vbo - var shader = this.shader - var ticks = this.ticks - var gl = plot.gl - var bounds = plot._tickBounds - var dataBox = plot.dataBox - var viewPixels = plot.viewBox - var lineWidth = plot.gridLineWidth - var gridColor = plot.gridLineColor - var gridEnable = plot.gridLineEnable - var pixelRatio = plot.pixelRatio - - 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] - DATA_SCALE[i] = 2.0 * boundScale / dataWidth - DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth - } - - shader.bind() - vbo.bind() - shader.attributes.dataCoord.pointer() - shader.uniforms.dataShift = DATA_SHIFT - shader.uniforms.dataScale = DATA_SCALE - - var offset = 0 - for(var i=0; i<2; ++i) { - DATA_AXIS[0] = DATA_AXIS[1] = 0 - DATA_AXIS[i] = 1 - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.lineWidth = lineWidth[i] / (viewPixels[i+2] - viewPixels[i]) * pixelRatio - shader.uniforms.color = gridColor[i] - - var size = ticks[i].length * 6 - if(gridEnable[i] && size) { - gl.drawArrays(gl.TRIANGLES, offset, size) - } - offset += size - } - } -})() - -__proto_96.drawTickMarks = (function() { - var DATA_SHIFT = [0,0] - var DATA_SCALE = [0,0] - var X_AXIS = [1,0] - var Y_AXIS = [0,1] - var SCR_OFFSET = [0,0] - var TICK_SCALE = [0,0] - - return function() { - var plot = this.plot - var vbo = this.vbo - var shader = this.tickShader - var ticks = this.ticks - var gl = plot.gl - var bounds = plot._tickBounds - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - var screenBox = plot.screenBox - - var screenWidth = screenBox[2] - screenBox[0] - var screenHeight = screenBox[3] - screenBox[1] - var viewWidth = viewBox[2] - viewBox[0] - var viewHeight = viewBox[3] - viewBox[1] - - 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]) - DATA_SCALE[i] = 2.0 * boundScale / dataWidth - DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth - } - - DATA_SCALE[0] *= viewWidth / screenWidth - DATA_SHIFT[0] *= viewWidth / screenWidth - - DATA_SCALE[1] *= viewHeight / screenHeight - DATA_SHIFT[1] *= viewHeight / screenHeight - - shader.bind() - vbo.bind() - - shader.attributes.dataCoord.pointer() - - var uniforms = shader.uniforms - uniforms.dataShift = DATA_SHIFT - uniforms.dataScale = DATA_SCALE - - var tickMarkLength = plot.tickMarkLength - var tickMarkWidth = plot.tickMarkWidth - var tickMarkColor = plot.tickMarkColor - - var xTicksOffset = 0 - var yTicksOffset = ticks[0].length * 6 - - var xStart = Math.min(_$searchBounds_100.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xEnd = Math.min(_$searchBounds_100.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xOffset = xTicksOffset + 6 * xStart - var xCount = 6 * Math.max(0, xEnd - xStart) - - var yStart = Math.min(_$searchBounds_100.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yEnd = Math.min(_$searchBounds_100.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yOffset = yTicksOffset + 6 * yStart - var yCount = 6 * Math.max(0, yEnd - yStart) - - SCR_OFFSET[0] = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0 - SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkLength[1] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkWidth[1] * pixelRatio / screenHeight - - if(yCount) { - uniforms.color = tickMarkColor[1] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = Y_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, yOffset, yCount) - } - - SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 - SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight - - if(xCount) { - uniforms.color = tickMarkColor[0] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = X_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, xOffset, xCount) - } - - SCR_OFFSET[0] = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0 - SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkLength[3] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkWidth[3] * pixelRatio / screenHeight - - if(yCount) { - uniforms.color = tickMarkColor[3] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = Y_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, yOffset, yCount) - } - - SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 - SCR_OFFSET[1] = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkWidth[2] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkLength[2] * pixelRatio / screenHeight - - if(xCount) { - uniforms.color = tickMarkColor[2] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = X_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, xOffset, xCount) - } - } -})() - -__proto_96.update = (function() { - var OFFSET_X = [1, 1, -1, -1, 1, -1] - var OFFSET_Y = [1, -1, 1, 1, -1, -1] - - return function(options) { - var ticks = options.ticks - var bounds = options.bounds - var data = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length)) - - var zeroLineEnable = this.plot.zeroLineEnable - - var ptr = 0 - var gridTicks = [[], []] - for(var dim=0; dim<2; ++dim) { - var localTicks = gridTicks[dim] - var axisTicks = ticks[dim] - var lo = bounds[dim] - var hi = bounds[dim+2] - for(var i=0; i domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_425.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + } + coerce('layer'); -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + return containerOut; +}; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; +'use strict'; + +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$autoType_471 = require('./axis_autotype'); */; +var name2id = _$axis_ids_473.name2id; + +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_493 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); + + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); } }; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; -function __noop_166() {} + var id = ax._id; + var axLetter = id.charAt(0); -process.on = __noop_166; -process.addListener = __noop_166; -process.once = __noop_166; -process.off = __noop_166; -process.removeListener = __noop_166; -process.removeAllListeners = __noop_166; -process.emit = __noop_166; -process.prependListener = __noop_166; -process.prependOnceListener = __noop_166; + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; -process.listeners = function (name) { return [] } + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; -"use strict" + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; -var _$twoProduct_205 = twoProduct + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_514.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; -var SPLITTER = +(Math.pow(2, 27) + 1.0) + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); -function twoProduct(a, b, result) { - var x = a * b + if(trace[calAttr] !== calendar) calendar = undefined; + } - var c = SPLITTER * a - var abig = c - a - var ahi = c - abig - var alo = a - ahi - - var d = SPLITTER * b - var bbig = d - b - var bhi = d - bbig - var blo = b - bhi + ax.type = _$autoType_471(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_471(dim.values, calendar); + break; + } + } + } + else { + ax.type = _$autoType_471(d0[axLetter] || [d0[axLetter + '0']], calendar); + } +} - var err1 = x - (ahi * bhi) - var err2 = err1 - (alo * bhi) - var err3 = err2 - (ahi * blo) +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; - var y = alo * blo - err3 + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } - if(result) { - result[0] = y - result[1] = x - return result - } + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } + } + } +} - return [ y, x ] +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; } -"use strict" -var _$fastTwoSum_206 = fastTwoSum +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_514.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_514.traceIs(trace._fullInput || {}, 'candlestick'); -function fastTwoSum(a, b, result) { - var x = a + b - var bv = x - a - var av = x - bv - var br = b - bv - var ar = a - av - if(result) { - result[0] = ar + br - result[1] = x - return result - } - return [ar+br, x] + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); } -"use strict" -/* removed: var _$twoProduct_205 = require("two-product") */; -/* removed: var _$fastTwoSum_206 = require("two-sum") */; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 _$scaleLinearExpansion_180 = scaleLinearExpansion -function scaleLinearExpansion(e, scale) { - var n = e.length - if(n === 1) { - var ts = _$twoProduct_205(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_205(e[0], scale, q) - if(q[0]) { - g[count++] = q[0] - } - for(var i=1; i= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - } - } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - } - } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g -} -"use strict" -var _$linearExpansionSum_183 = linearExpansionSum +var _$supplyLayoutDefaults_483 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -//Easy case: Add two scalars -function __scalarScalar_183(a, b) { - var x = a + b - var bv = x - a - var av = x - bv - var br = b - bv - var ar = a - av - var y = ar + br - if(y) { - return [y, x] - } - return [x] -} + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -function linearExpansionSum(e, f) { - var ne = e.length|0 - var nf = f.length|0 - if(ne === 1 && nf === 1) { - return __scalarScalar_183(e[0], f[0]) - } - var n = ne + nf - var g = new Array(n) - var count = 0 - var eptr = 0 - var fptr = 0 - var abs = Math.abs - var ei = e[eptr] - var ea = abs(ei) - var fi = f[fptr] - var fa = abs(fi) - var a, b - if(ea < fa) { - b = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - b = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } - } - if((eptr < ne && ea < fa) || (fptr >= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } - } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } + if(!_$registry_514.traceIs(trace, 'cartesian') && !_$registry_514.traceIs(trace, 'gl2d')) { + continue; + } + + var xaName = _$axis_ids_473.id2name(trace.xaxis); + var yaName = _$axis_ids_473.id2name(trace.yaxis); + + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_514.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } + + // 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) xaCheater[xaName] = 1; + } + + // check for default formatting tweaks + if(_$registry_514.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } + + if(_$registry_514.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; + } } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_425.simpleMap(xIds, _$axis_ids_473.id2name); + var yNames = _$lib_425.simpleMap(yIds, _$axis_ids_473.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 plot_bgcolor = _$color_301.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_425.coerce(layoutIn, layoutOut, _$layout_attributes_504, 'plot_bgcolor'); } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + + var bgColor = _$color_301.combine(plot_bgcolor, layoutOut.paper_bgcolor); + + var axName, axLetter, axLayoutIn, axLayoutOut; + + function coerce(attr, dflt) { + return _$lib_425.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_482, attr, dflt); } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] + + function coerce2(attr, dflt) { + return _$lib_425.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_482, attr, dflt); } - } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = f[fptr] + + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; } - } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g -} -var _$inSphere_177 = {}; -"use strict" -/* removed: var _$twoProduct_205 = require("two-product") */; -/* removed: var _$linearExpansionSum_183 = require("robust-sum") */; -/* removed: var _$robustSubtract_182 = require("robust-subtract") */; -/* removed: var _$scaleLinearExpansion_180 = require("robust-scale") */; + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; -var NUM_EXPAND = 6 + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; -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("") - } -} + // first pass creates the containers, determines types, and handles most of the settings + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; -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) - } -} + if(!_$lib_425.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } -function sign(s) { - if(s & 1 !== 0) { - return "-" - } - return "" -} + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; -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 0) { - var b = stack.pop() - var a = stack.pop() + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; - //Find opposite pairs - var x = -1, y = -1 - var star = stars[a] - for(var i=1; i= 0) { - continue + updates[axisLetter] = update; + } + } + + return updates; } - //Flip the edge - triangulation.flip(a, b) + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - //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) - } -} + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; -'use strict' + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; -/* removed: var _$searchBounds_52 = require('binary-search-bounds') */; + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; -var _$classifyFaces_49 = classifyFaces + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); -function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) { - this.cells = cells - this.neighbor = neighbor - this.flags = flags - this.constraint = constraint - this.active = active - this.next = next - this.boundary = boundary -} + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; + } -var __proto_49 = FaceIndex.prototype + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; -function compareCell(a, b) { - return a[0] - b[0] || - a[1] - b[1] || - a[2] - b[2] -} + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } + } -__proto_49.locate = (function() { - var key = [0,0,0] - return function(a, b, c) { - var x = a, y = b, z = c - if(b < c) { - if(b < a) { - x = b - y = c - z = a - } - } else if(c < a) { - x = c - y = a - z = b + return affectedSubplots; } - if(x < 0) { - return -1 + + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); + + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); + + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } + + redrawObjs(fullLayout.annotations || [], _$registry_514.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_514.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_514.getComponentMethod('images', 'draw'), true); } - key[0] = x - key[1] = y - key[2] = z - return _$searchBounds_52.eq(this.cells, key, compareCell) - } -})() -function indexCells(triangulation, infinity) { - //First get cells and canonicalize - var cells = triangulation.cells() - var nc = cells.length - for(var i=0; i rect') + .call(_$drawing_326.setTranslate, 0, 0) + .call(_$drawing_326.setScale, 1, 1); - var side = 1 - var active = index.active - var next = index.next - var flags = index.flags - var cells = index.cells - var constraint = index.constraint - var neighbor = index.neighbor + subplot.plot + .call(_$drawing_326.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_326.setScale, 1, 1); - while(active.length > 0 || next.length > 0) { - while(active.length > 0) { - var t = active.pop() - if(flags[t] === -side) { - continue - } - flags[t] = side - var c = cells[t] - for(var j=0; j<3; ++j) { - var f = neighbor[3*t+j] - if(f >= 0 && flags[f] === 0) { - if(constraint[3*t+j]) { - next.push(f) - } else { - active.push(f) - flags[f] = side - } - } - } + 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_326.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_326.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_326.hideOutsideRangePoints, subplot); } - //Swap arrays and loop - var tmp = next - next = active - active = tmp - next.length = 0 - side = -side - } + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - var result = filterCells(cells, flags, target) - if(infinity) { - return result.concat(index.boundary) - } - return result -} + var viewBox = []; -var _$orientation_178 = {}; -"use strict" + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; -/* removed: var _$twoProduct_205 = require("two-product") */; -/* removed: var _$linearExpansionSum_183 = require("robust-sum") */; -/* removed: var _$scaleLinearExpansion_180 = require("robust-scale") */; -/* removed: var _$robustSubtract_182 = require("robust-subtract") */; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; -var __NUM_EXPAND_178 = 5 + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; + } -var EPSILON = 1.1102230246251565e-16 -var ERRBOUND3 = (3.0 + 16.0 * EPSILON) * EPSILON -var ERRBOUND4 = (7.0 + 56.0 * EPSILON) * EPSILON + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; -function __cofactor_178(m, c) { - var result = new Array(m.length-1) - for(var i=1; i>1 - return ["sum(", __generateSum_178(expr.slice(0, m)), ",", __generateSum_178(expr.slice(m)), ")"].join("") - } -} + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; -function __determinant_178(m) { - if(m.length === 2) { - return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] - } else { - var expr = [] - for(var i=0; i 0) { - if(r <= 0) { - return det - } else { - s = l + r - } - } else if(l < 0) { - if(r >= 0) { - return det - } else { - s = -(l + r) - } - } else { - return det - } - var tol = ERRBOUND3 * s - if(det >= tol || det <= -tol) { - return det - } - return orientation3Exact(a, b, c) - }, - function orientation4(a,b,c,d) { - var adx = a[0] - d[0] - var bdx = b[0] - d[0] - var cdx = c[0] - d[0] - var ady = a[1] - d[1] - var bdy = b[1] - d[1] - var cdy = c[1] - d[1] - var adz = a[2] - d[2] - var bdz = b[2] - d[2] - var cdz = c[2] - d[2] - var bdxcdy = bdx * cdy - var cdxbdy = cdx * bdy - var cdxady = cdx * ady - var adxcdy = adx * cdy - var adxbdy = adx * bdy - var bdxady = bdx * ady - var det = adz * (bdxcdy - cdxbdy) - + bdz * (cdxady - adxcdy) - + cdz * (adxbdy - bdxady) - var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) - + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) - + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) - var tol = ERRBOUND4 * permanent - if ((det > tol) || (-det > tol)) { - return det - } - return orientation4Exact(a,b,c,d) - } -] + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; -function slowOrient(args) { - var proc = __CACHED_178[args.length] - if(!proc) { - proc = __CACHED_178[args.length] = __orientation_178(args.length) - } - return proc.apply(undefined, args) -} + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; -function generateOrientationProc() { - while(__CACHED_178.length <= __NUM_EXPAND_178) { - __CACHED_178.push(__orientation_178(__CACHED_178.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=__NUM_EXPAND_178; ++i) { - args.push("a" + i) - procArgs.push("o" + i) - } - var code = [ - "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=__NUM_EXPAND_178; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") - } - code.push("}var s=new Array(arguments.length);for(var i=0;i 1 && orient( - points[lowerIds[m-2]], - points[lowerIds[m-1]], - p) > 0) { - cells.push( - [lowerIds[m-1], - lowerIds[m-2], - idx]) - m -= 1 + return _$registry_514.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); } - lowerIds.length = m - lowerIds.push(idx) - //Insert p into upper hull - var upperIds = hull.upperIds - var m = upperIds.length - while(m > 1 && orient( - points[upperIds[m-2]], - points[upperIds[m-1]], - p) < 0) { - cells.push( - [upperIds[m-2], - upperIds[m-1], - idx]) - m -= 1 - } - upperIds.length = m - upperIds.push(idx) - } -} + var t1, t2, raf; + var easeFn = _$d3_71.ease(transitionOpts.easing); -function findSplit(hull, edge) { - var d - if(hull.a[0] < edge.a[0]) { - d = orient(hull.a, hull.b, edge.a) - } else { - d = orient(edge.b, edge.a, hull.a) - } - if(d) { return d } - if(edge.b[0] < hull.b[0]) { - d = orient(hull.a, hull.b, edge.b) - } else { - d = orient(edge.b, edge.a, hull.b) - } - return d || hull.idx - edge.idx -} + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); -function splitHulls(hulls, points, event) { - var splitIdx = _$searchBounds_52.le(hulls, event, findSplit) - var hull = hulls[splitIdx] - var upperIds = hull.upperIds - var x = upperIds[upperIds.length-1] - hull.upperIds = [x] - hulls.splice(splitIdx+1, 0, - new PartialHull(event.a, event.b, event.idx, [x], upperIds)) -} + function doFrame() { + t2 = Date.now(); + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); -function mergeHulls(hulls, points, event) { - //Swap pointers for merge search - var tmp = event.a - event.a = event.b - event.b = tmp - var mergeIdx = _$searchBounds_52.eq(hulls, event, findSplit) - var upper = hulls[mergeIdx] - var lower = hulls[mergeIdx-1] - lower.upperIds = upper.upperIds - hulls.splice(mergeIdx, 1) -} + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); + } + } -function monotoneTriangulate(points, edges) { + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - var numPoints = points.length - var numEdges = edges.length + return Promise.resolve(); +}; - var events = [] +var _$get_data_498 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - //Create point events - for(var i=0; i b[0]) { - events.push( - new Event(b, a, EVENT_START, i), - new Event(a, b, EVENT_END, i)) - } - } +/* removed: var _$registry_514 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_475.SUBPLOT_PATTERN; - //Sort events - events.sort(compareEvent) +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_498.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_514.subplotsRegistry[type]; + if(!basePlotModule) return []; - //Initialize hull - var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52) - var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ] + var attr = basePlotModule.attr; + var subplotCalcData = []; - //Process events in order - var cells = [] - for(var i=0, numEvents=events.length; i= 0 - } -})() - -__proto_51.removeTriangle = function(i, j, k) { - var stars = this.stars - removePair(stars[i], j, k) - removePair(stars[j], k, i) - removePair(stars[k], i, j) -} + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } -__proto_51.addTriangle = function(i, j, k) { - var stars = this.stars - stars[i].push(j, k) - stars[j].push(k, i) - stars[k].push(i, j) -} + for(var i = 0; i < data.length; i++) { + trace = data[i]; -__proto_51.opposite = function(j, i) { - var list = this.stars[i] - for(var k=1, n=list.length; k 0) return left; - return right; - }; + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); } +} - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } +_$cartesian_481.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); + } } - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; } - if (number[0] === '-') { - this.negative = 1; + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; } - this.strip(); - - if (endian !== 'le') return; + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); - this._initArray(this.toArray(), base, endian); - }; + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } } - 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(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } } - if (endian !== 'le') return; + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); - 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; + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + } + } } - 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; - } + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - 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++; + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } } - } } - 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; +_$cartesian_481.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); - r <<= 4; + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_425.identity); - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; + subplotLayers.order(); - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - 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; - } + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; - 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; + // keep ref to plot group + plotinfo.plotgroup = _$d3_71.select(this); - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; + // initialize list of overlay subplots + plotinfo.overlays = []; - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; + makeSubplotLayer(gd, plotinfo); - // '0' - '9' - } else { - r += c; - } - } - return r; - } + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); + } - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; +_$cartesian_481.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_506.style(gd); +}; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; + } } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } + // main subplots before overlays + subplotData = subplotData.concat(overlays); - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; + return subplotData; +} - 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; - }; +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_475.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_475.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); - // 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(); - }; + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); - /* + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); - var zeros = []; - var groupSizes = []; - var groupBases = []; + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); - 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; + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - */ + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. - 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' - ]; + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - 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 - ]; + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - 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 - ]; + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - 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; + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); } - if (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); + // common attributes for all subplots, overlays or not - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_473.idSort); + + for(var i = 0; i < _$constants_475.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_475.traceLayerClasses[i]); } - } - 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'); - }; + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - 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; - }; + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; + var overlayIdsToRemove = {}; - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; + layers.each(function(subplotId) { + var plotgroup = _$d3_71.select(this); - 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'); + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); + overlayIdsToRemove[subplotId] = true; - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } + // do not remove individual axis s here + // as other subplots may need them + }); - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + // must remove overlaid subplot trace layers 'manually' - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); - res[i] = b; - } + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - for (; i < reqLength; i++) { - res[i] = 0; - } + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; + + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } + } } +} - return res; - }; +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); +} - 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; - }; - } +_$cartesian_481.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_71.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); - 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++; + image.attr({ + xmlns: _$xmlns_namespaces_406.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); } - 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; - }; + canvases.each(canvasToImage); +}; - function toBitArray (num) { - var w = new Array(num.bitLength()); +_$cartesian_481.updateFx = _$graph_interact_479.updateFx; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; +"use strict" - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; +function unique_pred(list, compare) { + var ptr = 1 + , len = list.length + , a=list[0], b=list[0] + for(var i=1; i0 + , code = [] + , vars = [] + , idx=0, pidx=0, i, j + for(i=0; i 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; + } + if (vars.length > 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") +} - 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; +// 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 < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; + } + for(var i=0; i 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--; +//Processes a block according to the given data types +// Replaces variable names by different ones, either "local" ones (that are then ferried in and out of the given array) or ones matching the arguments that the function performing the ultimate loop will accept. +function processBlock(block, proc, dtypes) { + var code = block.body + var pre = [] + var post = [] + for(var i=0; i 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); +function typeSummary(dtypes) { + var summary = new Array(dtypes.length) + var allEqual = true + for(var i=0; i= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); + if(t.charAt(0) === 0) { + summary[i] = "u" + t.charAt(1) + digits } else { - this.words[off] = this.words[off] & ~(1 << wbit); + summary[i] = t.charAt(0) + digits } - - 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(); + if(i > 0) { + allEqual = allEqual && summary[i] === summary[i-1] } + } + if(allEqual) { + return summary[0] + } + return summary.join("") +} - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; +//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>> 26; + //First create arguments for procedure + var arglist = ["SS"] // SS is the overall shape over which we iterate + var code = ["'use strict'"] + var vars = [] + + for(var j=0; j>> 26; + + for(var j=0; j 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)) + } - if (this.length > num.length) return this.clone().iadd(num); + //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)) + } - return num.clone().iadd(this); - }; + //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() +} +var _$generateCWiseOp_66 = generateCWiseOp - // 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(); +"use strict" - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } +// The function below is called when constructing a cwise function object, and does the following: +// A function object is constructed which accepts as argument a compilation function and returns another function. +// It is this other function that is eventually returned by createThunk, and this function is the one that actually +// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. +// The compilation passed to the first function object is used for compiling new functions. +// Once this function object is created, it is called with compile as argument, where the first argument of compile +// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). +// So createThunk roughly works like this: +// function createThunk(proc) { +// var thunk = function(compileBound) { +// var CACHED = {} +// return function(arrays and scalars) { +// if (dtype and order of arrays in CACHED) { +// var func = CACHED[dtype and order of arrays] +// } else { +// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) +// } +// return func(arrays and scalars) +// } +// } +// return thunk(compile.bind1(proc)) +// } - // At this point both numbers are positive - var cmp = this.cmp(num); +/* removed: var _$generateCWiseOp_66 = require("./compile.js") */; - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; +function createThunk(proc) { + var code = ["'use strict'", "var CACHED={}"] + var vars = [] + var thunkName = proc.funcName + "_cwise_thunk" + + //Build thunk + code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) + var typesig = [] + var string_typesig = [] + var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). + Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] + var shapeLengthConditions = [], shapeConditions = [] + // Process array arguments + for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) + shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) + shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") } + } + // Check for shape equality + if (proc.arrayArgs.length > 1) { + code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") + code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") + code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") + code.push("}") + } + // Process scalar arguments + for(var i=0; i b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } + if(proc.debug) { + console.log("-----Generated thunk:\n" + code.join("\n") + "\n----------") + } + + //Compile thunk + var thunk = new Function("compile", code.join("\n")) + return thunk(_$generateCWiseOp_66.bind(undefined, proc)) +} - 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; - } +var _$createThunk_67 = createThunk - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } +"use strict" - this.length = Math.max(this.length, i); +/* removed: var _$createThunk_67 = require("./lib/thunk.js") */; - if (a !== this) { - this.negative = 1; +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") + } - return this.strip(); - }; + //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 - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; + return _$createThunk_67(proc) +} - 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; +var _$compileCwise_65 = compileCwise - // 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 _$ndarrayOps_200 = {}; +"use strict" - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; +/* removed: var _$compileCwise_65 = require("cwise-compiler") */; - 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; +var EmptyProc = { + body: "", + args: [], + thisVars: [], + localVars: [] +} + +function fixup(x) { + if(!x) { + return EmptyProc + } + for(var i=0; i>> 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; +var assign_ops = { + add: "+", + sub: "-", + mul: "*", + div: "/", + mod: "%", + band: "&", + bor: "|", + bxor: "^", + lshift: "<<", + rshift: ">>", + rrshift: ">>>" +} +;(function(){ + for(var id in assign_ops) { + var op = assign_ops[id] + _$ndarrayOps_200[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a","b","c"], + body: "a=b"+op+"c"}, + funcName: id + }) + _$ndarrayOps_200[id+"eq"] = makeOp({ + args: ["array","array"], + body: {args:["a","b"], + body:"a"+op+"=b"}, + rvalue: true, + funcName: id+"eq" + }) + _$ndarrayOps_200[id+"s"] = makeOp({ + args: ["array", "array", "scalar"], + body: {args:["a","b","s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + _$ndarrayOps_200[id+"seq"] = makeOp({ + args: ["array","scalar"], + body: {args:["a","s"], + body:"a"+op+"=s"}, + rvalue: true, + funcName: id+"seq" + }) + } +})(); - 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; +var unary_ops = { + not: "!", + bnot: "~", + neg: "-", + recip: "1.0/" +} +;(function(){ + for(var id in unary_ops) { + var op = unary_ops[id] + _$ndarrayOps_200[id] = makeOp({ + args: ["array", "array"], + body: {args:["a","b"], + body:"a="+op+"b"}, + funcName: id + }) + _$ndarrayOps_200[id+"eq"] = makeOp({ + args: ["array"], + body: {args:["a"], + body:"a="+op+"a"}, + rvalue: true, + count: 2, + funcName: id+"eq" + }) } +})(); - 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; +var binary_ops = { + and: "&&", + or: "||", + eq: "===", + neq: "!==", + lt: "<", + gt: ">", + leq: "<=", + geq: ">=" +} +;(function() { + for(var id in binary_ops) { + var op = binary_ops[id] + _$ndarrayOps_200[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a", "b", "c"], + body:"a=b"+op+"c"}, + funcName: id + }) + _$ndarrayOps_200[id+"s"] = makeOp({ + args: ["array","array","scalar"], + body: {args:["a", "b", "s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + _$ndarrayOps_200[id+"eq"] = makeOp({ + args: ["array", "array"], + body: {args:["a", "b"], + body:"a=a"+op+"b"}, + rvalue:true, + count:2, + funcName: id+"eq" + }) + _$ndarrayOps_200[id+"seq"] = makeOp({ + args: ["array", "scalar"], + body: {args:["a","s"], + body:"a=a"+op+"s"}, + rvalue:true, + count:2, + funcName: id+"seq" + }) + } +})(); - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } +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" +}) - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; +_$ndarrayOps_200.norm1 = _$compileCwise_65({ + 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" +}) - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } +_$ndarrayOps_200.sup = _$compileCwise_65({ + 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: [] } + }) - return rb; - }; +_$ndarrayOps_200.inf = _$compileCwise_65({ + 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:[]} +}) - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; +_$ndarrayOps_200.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" +}) - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); +_$ndarrayOps_200.assign = makeOp({ + args:["array", "array"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assign" }) - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; +_$ndarrayOps_200.assigns = makeOp({ + args:["array", "scalar"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assigns" }) - 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]; +_$ndarrayOps_200.equals = _$compileCwise_65({ + 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" +}) - var rx = rtwdf_ * ro - itwdf_ * io; - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - rtws[p + j] = re + ro; - itws[p + j] = ie + io; +"use strict" - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; +function iota(n) { + var result = new Array(n) + for(var i=0; i + * @license MIT + */ - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +var _$isBuffer_189 = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} - 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++; - } +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} - return 1 << i + 1 + odd; - }; +// 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)) +} - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; +/* removed: var _$iota_187 = require("iota-array") */; +/* removed: var _$isBuffer_189 = require("is-buffer") */; - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; +var hasTypedArrays = ((typeof Float64Array) !== "undefined") - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; +function compare1st(a, b) { + return a[0] - b[0] +} - t = iws[i]; +function order() { + var stride = this.stride + var terms = new Array(stride.length) + var i + for(i=0; i>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + //view.order: + if(dimension === 1) { + code.push("proto.order=[0]") + } else { + code.push("Object.defineProperty(proto,'order',{get:") + if(dimension < 4) { + code.push("function "+className+"_order(){") + if(dimension === 2) { + code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})") + } else if(dimension === 3) { + code.push( +"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ +if(s0>s1){\ +if(s1>s2){\ +return [2,1,0];\ +}else if(s0>s2){\ +return [1,2,0];\ +}else{\ +return [1,0,2];\ +}\ +}else if(s0>s2){\ +return [2,0,1];\ +}else if(s2>s1){\ +return [0,1,2];\ +}else{\ +return [0,2,1];\ +}}})") + } + } else { + code.push("ORDER})") } + } - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } + //view.set(i0, ..., v): + code.push( +"proto.set=function "+className+"_set("+args.join(",")+",v){") + if(useGetters) { + code.push("return this.data.set("+index_str+",v)}") + } else { + code.push("return this.data["+index_str+"]=v}") + } - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; + //view.get(i0, ...): + code.push("proto.get=function "+className+"_get("+args.join(",")+"){") + if(useGetters) { + code.push("return this.data.get("+index_str+")}") + } else { + code.push("return this.data["+index_str+"]}") + } - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } + //view.index: + code.push( + "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") - return ph; - }; + //view.hi(): + code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ + indices.map(function(i) { + return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") + }).join(",")+","+ + indices.map(function(i) { + return "this.stride["+i + "]" + }).join(",")+",this.offset)}") - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); + //view.lo(): + var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) + var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) + code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) + for(var i=0; i=0){\ +d=i"+i+"|0;\ +b+=c"+i+"*d;\ +a"+i+"-=d}") + } + code.push("return new "+className+"(this.data,"+ + indices.map(function(i) { + return "a"+i + }).join(",")+","+ + indices.map(function(i) { + return "c"+i + }).join(",")+",b)}") - var rbt = this.makeRBT(N); + //view.step(): + code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ + indices.map(function(i) { + return "a"+i+"=this.shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "b"+i+"=this.stride["+i+"]" + }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") + for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + } + code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); + //Add return statement + code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ + indices.map(function(i) { + return "shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "stride["+i+"]" + }).join(",")+",offset)}") - var rmws = out.words; - rmws.length = N; + //Compile procedure + var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) + return procedure(CACHED_CONSTRUCTORS[dtype], order) +} - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); +function arrayDType(data) { + if(_$isBuffer_189(data)) { + return "buffer" + } + if(hasTypedArrays) { + switch(Object.prototype.toString.call(data)) { + case "[object Float64Array]": + return "float64" + case "[object Float32Array]": + return "float32" + case "[object Int8Array]": + return "int8" + case "[object Int16Array]": + return "int16" + case "[object Int32Array]": + return "int32" + case "[object Uint8Array]": + return "uint8" + case "[object Uint16Array]": + return "uint16" + case "[object Uint32Array]": + return "uint32" + case "[object Uint8ClampedArray]": + return "uint8_clamped" + } + } + if(Array.isArray(data)) { + return "array" + } + return "generic" +} - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); +var CACHED_CONSTRUCTORS = { + "float32":[], + "float64":[], + "int8":[], + "int16":[], + "int32":[], + "uint8":[], + "uint16":[], + "uint32":[], + "array":[], + "uint8_clamped":[], + "buffer":[], + "generic":[] +} - 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; +;(function() { + for(var id in CACHED_CONSTRUCTORS) { + CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) + } +}); + +function wrappedNDArrayCtor(data, shape, stride, offset) { + if(data === undefined) { + var ctor = CACHED_CONSTRUCTORS.array[0] + return ctor([]) + } else if(typeof data === "number") { + data = [data] + } + if(shape === undefined) { + shape = [ data.length ] + } + var d = shape.length + if(stride === undefined) { + stride = new Array(d) + for(var i=d-1, sz=1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } + } + if(offset === undefined) { + offset = 0 + for(var i=0; i 0) - (v < 0); +} - // 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; - } +//Computes absolute value of integer +_$twiddle_36.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } +//Computes minimum of integers x and y +_$twiddle_36.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} - return this; - }; +//Computes maximum of integers x and y +_$twiddle_36.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; +//Checks if a number is a power of two +_$twiddle_36.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; +//Computes log base 2 of v +_$twiddle_36.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; +//Computes log base 10 of v +_$twiddle_36.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); +//Counts number of bits +_$twiddle_36.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +_$twiddle_36.countTrailingZeros = countTrailingZeros; - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; +//Rounds to next power of 2 +_$twiddle_36.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} - res = res.mul(q); - } - } +//Rounds down to previous power of 2 +_$twiddle_36.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} - return res; - }; +//Computes parity of word +_$twiddle_36.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} - // 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; +var REVERSE_TABLE = new Array(256); - if (r !== 0) { - var carry = 0; +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); - 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); - } +//Reverse bits in a 32 bit word +_$twiddle_36.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} - if (carry) { - this.words[i] = carry; - this.length++; - } - } +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +_$twiddle_36.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; - for (i = 0; i < s; i++) { - this.words[i] = 0; - } + return x | (y << 1); +} - this.length += s; - } +//Extracts the nth interleaved component +_$twiddle_36.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} - return this.strip(); - }; - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +_$twiddle_36.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; - // 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; - } + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; +//Extracts nth interleaved component of a 3-tuple +_$twiddle_36.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} - h -= s; - h = Math.max(0, h); +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +_$twiddle_36.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} - // 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 _$base64Js_18 = {}; +'use strict' - 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; - } +_$base64Js_18.byteLength = byteLength +_$base64Js_18.toByteArray = toByteArray +_$base64Js_18.fromByteArray = fromByteArray - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} - return this.strip(); - }; +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return (b64.length * 3 / 4) - placeHoldersCount(b64) +} - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; +function toByteArray (b64) { + var i, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; + arr = new Arr((len * 3 / 4) - placeHolders) - // 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; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; + var L = 0 - // Check bit and return - var w = this.words[s]; + for (i = 0; i < l; 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[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } - return !!(w & q); - }; + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } - // 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; + return arr +} - assert(this.negative === 0, 'imaskn works only with positive numbers'); +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} - if (this.length <= s) { - return this; - } +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('') +} - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } + // 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))) + } - return this.strip(); - }; + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; + parts.push(output) - // 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); + return parts.join('') +} - // 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; - } +var _$ieee754_184 = {}; +_$ieee754_184.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } + i += d - // Add without checks - return this._iaddn(num); - }; + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - // 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); + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} - return this; - }; +_$ieee754_184.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - // 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); + value = Math.abs(value) - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 } - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 } + } - return this.strip(); - }; + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; + buffer[offset + i - d] |= s * 128 +} - BN.prototype.iabs = function iabs () { - this.negative = 0; +var _$buffer_47 = {}; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ - return this; - }; +'use strict' - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; +/* removed: var _$base64Js_18 = require('base64-js') */; +/* removed: var _$ieee754_184 = require('ieee754') */; - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; +_$buffer_47.Buffer = Buffer +_$buffer_47.SlowBuffer = SlowBuffer +_$buffer_47.INSPECT_MAX_BYTES = 50 - this._expand(len); +var K_MAX_LENGTH = 0x7fffffff +_$buffer_47.kMaxLength = K_MAX_LENGTH - 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 `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - if (carry === 0) return this.strip(); +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} - // 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; +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + get: function () { + if (!(this instanceof Buffer)) { + return undefined } - this.negative = 1; + return this.buffer + } +}) - return this.strip(); - }; +Object.defineProperty(Buffer.prototype, 'offset', { + get: function () { + if (!(this instanceof Buffer)) { + return undefined + } + return this.byteOffset + } +}) - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('Invalid typed array length') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} - var a = this.clone(); - var b = num; +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ - // 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; +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} - // Initialize quotient - var m = a.length - b.length; - var q; +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} - 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; - } - } +Buffer.poolSize = 8192 // not used by this implementation - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } +function from (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); + if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } - 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(); + return fromObject(value) +} - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} - return { - div: q || null, - mod: a - }; - }; +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array - // 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()); +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} - if (mode !== 'mod') { - div = res.div.neg(); - } +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} - return { - div: div, - mod: mod - }; - } +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } - if (mode !== 'mod') { - div = res.div.neg(); - } + var length = __byteLength_47(string, encoding) | 0 + var buf = createBuffer(length) - return { - div: div, - mod: res.mod - }; - } + var actual = buf.write(string, encoding) - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } + return buf +} - return { - div: res.div, - mod: mod - }; - } +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} - // Both numbers are positive at this point +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf } - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } + obj.copy(buf, 0, 0, len) + return buf + } - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; + if (obj) { + if (ArrayBuffer.isView(obj) || 'length' in obj) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) } + return fromArrayLike(obj) + } - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) } + } - return this._wordDiv(num, mode); - }; + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.') +} - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true +} - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; + if (a === b) return 0 - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var x = a.length + var y = b.length - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length } + } - return acc; - }; + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (ArrayBuffer.isView(buf)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); +function __byteLength_47 (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isArrayBuffer(string)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } - 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; + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true } + } +} +Buffer.byteLength = __byteLength_47 - return this.strip(); - }; +function slowToString (encoding, start, end) { + var loweredCase = false - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } - var x = this; - var y = p.clone(); + if (end === undefined || end > this.length) { + end = this.length + } - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } + if (end <= 0) { + return '' + } - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); + if (end <= start) { + return '' + } - var g = 0; + if (!encoding) encoding = 'utf8' - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) - var yp = y.clone(); - var xp = x.clone(); + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) - 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); - } + case 'ascii': + return asciiSlice(this, start, end) - A.iushrn(1); - B.iushrn(1); - } - } + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) - 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()); + case 'base64': + return base64Slice(this, start, end) - var a = this; - var b = p.clone(); + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true } + } +} - var x1 = new BN(1); - var x2 = new BN(0); +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true - var delta = b.clone(); +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} - 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); - } +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} - x1.iushrn(1); - } - } +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} - 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); - } +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} - x2.iushrn(1); - } - } +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } +Buffer.prototype.toLocaleString = Buffer.prototype.toString - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} - if (res.cmpn(0) < 0) { - res.iadd(p); - } +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = _$buffer_47.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} - return res; - }; +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 - 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; - } + if (this === target) return 0 - a.isub(b); - } while (true); + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) - return b.iushln(shift); - }; + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; + if (x < y) return -1 + if (y < x) return 1 + return 0 +} - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } - // 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; + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } - // 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; + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; + throw new TypeError('val must be string, number or Buffer') +} - this.strip(); +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } - assert(num <= 0x3ffffff, 'Number is too big'); + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } } - if (this.negative !== 0) return -res | 0; - return res; - }; + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } - // 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; + return -1 +} - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} - // 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; +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; + } - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; + var strLen = string.length - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining - 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); - }; + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; + if (!encoding) encoding = 'utf8' - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; + case 'ascii': + return asciiWrite(this, string, offset, length) - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} - 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); - }; +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} - 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); - }; +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return _$base64Js_18.fromByteArray(buf) + } else { + return _$base64Js_18.fromByteArray(buf.slice(start, end)) + } +} - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 - // 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); - }; + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } - // 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); - }; + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; + res.push(codePoint) + i += bytesPerSequence + } - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; + return decodeCodePointsArray(res) +} - // 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); +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 - this.tmp = this._tmp(); +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} - 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; +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} - 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(); - } +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - return r; - }; + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; +function hexSlice (buf, start, end) { + var len = buf.length - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) } - inherits(K256, MPrime); + return out +} - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } - 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; - } - }; + if (end < start) end = start - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} - // 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); - } +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul } - inherits(P224, MPrime); - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) } - inherits(P192, MPrime); - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul } - 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; + return val +} - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} - 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; +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} - return prime; - }; +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - // - // 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; - } - } + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - 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'); - }; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 - return this.m.sub(a)._forceRed(this); - }; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - Red.prototype.add = function add (a, b) { - this._verify2(a, b); + return val +} - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); + return val +} - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return _$ieee754_184.read(this, offset, true, 23, 4) +} - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return _$ieee754_184.read(this, offset, false, 23, 4) +} - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return _$ieee754_184.read(this, offset, true, 52, 8) +} - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return _$ieee754_184.read(this, offset, false, 52, 8) +} - // 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()); +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - // 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); + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } + return offset + byteLength +} - 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)); +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } - return r; - }; + return offset + byteLength +} - 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); - } - }; +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} - 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); - } +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} - 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); - } +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); + return offset + byteLength +} - return r === num ? r.clone() : r; - }; +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } - // - // Montgomery method engine - // + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } - BN.mont = function mont (num) { - return new Mont(num); - }; + return offset + byteLength +} - function Mont (m) { - Red.call(this, m); +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} - 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); +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + _$ieee754_184.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} - 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; +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} - return res._forceRed(this); - }; +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + _$ieee754_184.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} - 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); - } +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} - return res._forceRed(this); - }; +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start - 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); - }; -})("object" === 'undefined' || _$bn_37, this); + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 -_$bn_37 = _$bn_37.exports -'use strict' + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } -/* removed: var _$bn_37 = require('bn.js') */; + var len = end - start -var _$sign_23 = __sign_23 + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } -function __sign_23 (x) { - return x.cmp(new _$bn_37(0)) + return len } -var _$double_70 = {}; -(function (Buffer){ -var hasTypedArrays = false -if(typeof Float64Array !== "undefined") { - var DOUBLE_VIEW = new Float64Array(1) - , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) - DOUBLE_VIEW[0] = 1.0 - hasTypedArrays = true - if(UINT_VIEW[1] === 0x3ff00000) { - //Use little endian - _$double_70 = function doubleBitsLE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[0], UINT_VIEW[1] ] - } - function toDoubleLE(lo, hi) { - UINT_VIEW[0] = lo - UINT_VIEW[1] = hi - return DOUBLE_VIEW[0] - } - _$double_70.pack = toDoubleLE - function lowUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - _$double_70.lo = lowUintLE - function highUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - _$double_70.hi = highUintLE - } else if(UINT_VIEW[0] === 0x3ff00000) { - //Use big endian - _$double_70 = function doubleBitsBE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[1], UINT_VIEW[0] ] +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length } - function toDoubleBE(lo, hi) { - UINT_VIEW[1] = lo - UINT_VIEW[0] = hi - return DOUBLE_VIEW[0] + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') } - _$double_70.pack = toDoubleBE - function lowUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) } - _$double_70.lo = lowUintBE - function highUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } } - _$double_70.hi = highUintBE - } else { - hasTypedArrays = false - } -} -if(!hasTypedArrays) { - var buffer = new Buffer(8) - _$double_70 = function doubleBits(n) { - buffer.writeDoubleLE(n, 0, true) - return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] - } - function toDouble(lo, hi) { - buffer.writeUInt32LE(lo, 0, true) - buffer.writeUInt32LE(hi, 4, true) - return buffer.readDoubleLE(0, true) + } else if (typeof val === 'number') { + val = val & 255 } - _$double_70.pack = toDouble - function lowUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(0, true) + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') } - _$double_70.lo = lowUint - function highUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(4, true) + + if (end <= start) { + return this } - _$double_70.hi = highUint -} -_$double_70.sign = function(n) { - return _$double_70.hi(n) >>> 31 -} + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 -_$double_70.exponent = function(n) { - var b = _$double_70.hi(n) - return ((b<<1) >>> 21) - 1023 -} + if (!val) val = 0 -_$double_70.fraction = function(n) { - var lo = _$double_70.lo(n) - var hi = _$double_70.hi(n) - var b = hi & ((1<<20) - 1) - if(hi & 0x7ff00000) { - b += (1<<20) + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : new Buffer(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } } - return [lo, b] -} -_$double_70.denormalized = function(n) { - var hi = _$double_70.hi(n) - return !(hi & 0x7ff00000) + return this } -}).call(this,_$buffer_46.Buffer) -'use strict' -/* removed: var _$bn_37 = require('bn.js') */; -/* removed: var _$double_70 = require('double-bits') */; +// HELPER FUNCTIONS +// ================ -var _$num2bn_27 = num2bn +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g -function num2bn(x) { - var e = _$double_70.exponent(x) - if(e < 52) { - return new _$bn_37(x) - } else { - return (new _$bn_37(x * Math.pow(2, 52-e))).ushln(e-52) +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' } + return str } -'use strict' - -/* removed: var _$num2bn_27 = require('./num-to-bn') */; -/* removed: var _$sign_23 = require('./bn-sign') */; +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} -var _$rationalize_28 = rationalize +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] -function rationalize(numer, denom) { - var snumer = _$sign_23(numer) - var sdenom = _$sign_23(denom) - if(snumer === 0) { - return [_$num2bn_27(0), _$num2bn_27(1)] - } - if(sdenom === 0) { - return [_$num2bn_27(0), _$num2bn_27(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 ] -} + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) -'use strict' + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } -/* removed: var _$rationalize_28 = require('./lib/rationalize') */; + // valid lead + leadSurrogate = codePoint -var _$div_20 = div + continue + } -function div(a, b) { - return _$rationalize_28(a[0].mul(b[1]), a[1].mul(b[0])) -} + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } -'use strict' + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } -/* removed: var _$bn_37 = require('bn.js') */; + leadSurrogate = null -var _$isBN_26 = isBN + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } -//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) + return bytes } -'use strict' +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} -/* removed: var _$isBN_26 = require('./lib/is-bn') */; +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break -var _$isRat_22 = isRat + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } -function isRat(x) { - return Array.isArray(x) && x.length === 2 && _$isBN_26(x[0]) && _$isBN_26(x[1]) + return byteArray } -'use strict' - -/* removed: var _$bn_37 = require('bn.js') */; - -var _$str2BN_29 = str2BN +function base64ToBytes (str) { + return _$base64Js_18.toByteArray(base64clean(str)) +} -function str2BN(x) { - return new _$bn_37(x) +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i } -'use strict' +// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check +// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 +function isArrayBuffer (obj) { + return obj instanceof ArrayBuffer || + (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && + typeof obj.byteLength === 'number') +} -/* removed: var _$isRat_22 = require('./is-rat') */; -/* removed: var _$isBN_26 = require('./lib/is-bn') */; -/* removed: var _$num2bn_27 = require('./lib/num-to-bn') */; -/* removed: var _$str2BN_29 = require('./lib/str-to-bn') */; -/* removed: var _$rationalize_28 = require('./lib/rationalize') */; -/* removed: var _$div_20 = require('./div') */; +function numberIsNaN (obj) { + return obj !== obj // eslint-disable-line no-self-compare +} -var _$makeRational_21 = makeRational +"use strict" -function makeRational(numer, denom) { - if(_$isRat_22(numer)) { - if(denom) { - return _$div_20(numer, makeRational(denom)) - } - return [numer[0].clone(), numer[1].clone()] +function dupe_array(count, value, i) { + var c = count[i]|0 + if(c <= 0) { + return [] } - var shift = 0 - var a, b - if(_$isBN_26(numer)) { - a = numer.clone() - } else if(typeof numer === 'string') { - a = _$str2BN_29(numer) - } else if(numer === 0) { - return [_$num2bn_27(0), _$num2bn_27(1)] - } else if(numer === Math.floor(numer)) { - a = _$num2bn_27(numer) - } else { - while(numer !== Math.floor(numer)) { - numer = numer * Math.pow(2, 256) - shift -= 256 + var result = new Array(c), j + if(i === count.length-1) { + for(j=0; j 0) { - a = a.ushln(shift) - } else if(shift < 0) { - b = b.ushln(-shift) } - return _$rationalize_28(a, b) + return result } -'use strict' - -/* removed: var _$sign_23 = require('./bn-sign') */; - -var _$bn2num_24 = bn2num +function dupe_number(count, value) { + var result, i + result = new Array(count) + for(i=0; i 0) { + return dupe_number(count|0, value) + } + break + case "object": + if(typeof (count.length) === "number") { + return dupe_array(count, value, 0) + } + break } - return _$sign_23(b) * out + return [] } +var _$dupe_76 = dupe +var _$pool_269 = {}; +(function (global,Buffer){ 'use strict' -/* removed: var _$double_70 = require('double-bits') */; -var ctz = _$twiddle_35.countTrailingZeros - -var _$ctzNumber_25 = ctzNumber +/* removed: var _$twiddle_36 = require('bit-twiddle') */; +/* removed: var _$dupe_76 = require('dup') */; -//Counts the number of trailing zeros -function ctzNumber(x) { - var l = ctz(_$double_70.lo(x)) - if(l < 32) { - return l - } - var h = ctz(_$double_70.hi(x)) - if(h > 20) { - return 52 +//Legacy pool support +if(!global.__TYPEDARRAY_POOL) { + global.__TYPEDARRAY_POOL = { + UINT8 : _$dupe_76([32, 0]) + , UINT16 : _$dupe_76([32, 0]) + , UINT32 : _$dupe_76([32, 0]) + , INT8 : _$dupe_76([32, 0]) + , INT16 : _$dupe_76([32, 0]) + , INT32 : _$dupe_76([32, 0]) + , FLOAT : _$dupe_76([32, 0]) + , DOUBLE : _$dupe_76([32, 0]) + , DATA : _$dupe_76([32, 0]) + , UINT8C : _$dupe_76([32, 0]) + , BUFFER : _$dupe_76([32, 0]) } - return h + 32 } -'use strict' +var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' +var POOL = global.__TYPEDARRAY_POOL -/* removed: var _$bn2num_24 = require('./lib/bn-to-num') */; -/* removed: var _$ctzNumber_25 = require('./lib/ctz') */; +//Upgrade pool +if(!POOL.UINT8C) { + POOL.UINT8C = _$dupe_76([32, 0]) +} +if(!POOL.BUFFER) { + POOL.BUFFER = _$dupe_76([32, 0]) +} -var _$roundRat_33 = roundRat +//New technique: Only allocate from ArrayBufferView and Buffer +var DATA = POOL.DATA + , BUFFER = POOL.BUFFER -// 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_24(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 = _$ctzNumber_25(x) + 4 - var y = _$bn2num_24(ir.ushln(s).divRound(b)) - return sgn * (x + y * Math.pow(2, -s)) +_$pool_269.free = function free(array) { + if(Buffer.isBuffer(array)) { + BUFFER[_$twiddle_36.log2(array.length)].push(array) } else { - var ybits = b.bitLength() - ir.bitLength() + 53 - var y = _$bn2num_24(ir.ushln(ybits).divRound(b)) - if (ybits < 1023) { - return sgn * y * Math.pow(2, -ybits) + if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { + array = array.buffer } - y *= Math.pow(2, -1023) - return sgn * y * Math.pow(2, 1023 - ybits) + if(!array) { + return + } + var n = array.length || array.byteLength + var log_n = _$twiddle_36.log2(n)|0 + DATA[log_n].push(array) } } -var _$brute_39 = {}; -'use strict' - -var DIMENSION = 'd' -var AXIS = 'ax' -var VISIT = 'vv' -var FLIP = 'fp' - -var ELEM_SIZE = 'es' +function freeArrayBuffer(buffer) { + if(!buffer) { + return + } + var n = buffer.length || buffer.byteLength + var log_n = _$twiddle_36.log2(n) + DATA[log_n].push(buffer) +} -var RED_START = 'rs' -var RED_END = 're' -var RED_BOXES = 'rb' -var RED_INDEX = 'ri' -var RED_PTR = 'rp' +function freeTypedArray(array) { + freeArrayBuffer(array.buffer) +} -var BLUE_START = 'bs' -var BLUE_END = 'be' -var BLUE_BOXES = 'bb' -var BLUE_INDEX = 'bi' -var BLUE_PTR = 'bp' +_$pool_269.freeUint8 = +_$pool_269.freeUint16 = +_$pool_269.freeUint32 = +_$pool_269.freeInt8 = +_$pool_269.freeInt16 = +_$pool_269.freeInt32 = +_$pool_269.freeFloat32 = +_$pool_269.freeFloat = +_$pool_269.freeFloat64 = +_$pool_269.freeDouble = +_$pool_269.freeUint8Clamped = +_$pool_269.freeDataView = freeTypedArray -var RETVAL = 'rv' +_$pool_269.freeArrayBuffer = freeArrayBuffer -var INNER_LABEL = 'Q' +_$pool_269.freeBuffer = function freeBuffer(array) { + BUFFER[_$twiddle_36.log2(array.length)].push(array) +} -var ARGS = [ - DIMENSION, - AXIS, - VISIT, - RED_START, - RED_END, - RED_BOXES, - RED_INDEX, - BLUE_START, - BLUE_END, - BLUE_BOXES, - BLUE_INDEX -] +_$pool_269.malloc = function malloc(n, dtype) { + if(dtype === undefined || dtype === 'arraybuffer') { + return mallocArrayBuffer(n) + } else { + switch(dtype) { + case 'uint8': + return mallocUint8(n) + case 'uint16': + return mallocUint16(n) + case 'uint32': + return mallocUint32(n) + case 'int8': + return mallocInt8(n) + case 'int16': + return mallocInt16(n) + case 'int32': + return mallocInt32(n) + case 'float': + case 'float32': + return mallocFloat(n) + case 'double': + case 'float64': + return mallocDouble(n) + case 'uint8_clamped': + return mallocUint8Clamped(n) + case 'buffer': + return mallocBuffer(n) + case 'data': + case 'dataview': + return mallocDataView(n) -function generateBruteForce(redMajor, flip, full) { - var funcName = 'bruteForce' + - (redMajor ? 'Red' : 'Blue') + - (flip ? 'Flip' : '') + - (full ? 'Full' : '') + default: + return null + } + } + return null +} - var code = ['function ', funcName, '(', ARGS.join(), '){', - 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] +function mallocArrayBuffer(n) { + var n = _$twiddle_36.nextPow2(n) + var log_n = _$twiddle_36.log2(n) + var d = DATA[log_n] + if(d.length > 0) { + return d.pop() + } + return new ArrayBuffer(n) +} +_$pool_269.mallocArrayBuffer = mallocArrayBuffer - var redLoop = - 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + - 'i<' + RED_END +';' + - '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + - 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + - 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + - 'xi=' + RED_INDEX + '[i];' +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n) +} +_$pool_269.mallocUint8 = mallocUint8 - var blueLoop = - 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + - 'j<' + BLUE_END + ';' + - '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + - 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + - (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + - 'yi=' + BLUE_INDEX + '[j];' +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +_$pool_269.mallocUint16 = mallocUint16 - if(redMajor) { - code.push(redLoop, INNER_LABEL, ':', blueLoop) - } else { - code.push(blueLoop, INNER_LABEL, ':', redLoop) - } +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4*n), 0, n) +} +_$pool_269.mallocUint32 = mallocUint32 - if(full) { - code.push('if(y1 0) { + return cache.pop() } + return new Buffer(n) +} +_$pool_269.mallocBuffer = mallocBuffer - code.push('if(' + RED_END + '-' + RED_START + '>' + - BLUE_END + '-' + BLUE_START + '){') - - if(full) { - invoke(true, false) - code.push('}else{') - invoke(false, false) - } else { - code.push('if(' + FLIP + '){') - invoke(true, true) - code.push('}else{') - invoke(true, false) - code.push('}}else{if(' + FLIP + '){') - invoke(false, true) - code.push('}else{') - invoke(false, false) - code.push('}') +_$pool_269.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 } - code.push('}}return ' + funcName) - - var codeStr = prefix.join('') + code.join('') - var proc = new Function(codeStr) - return proc() } +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_$buffer_47.Buffer) +"use strict" +/* removed: var _$pool_269 = require("typedarray-pool") */; +/* removed: var _$ndarrayOps_200 = require("ndarray-ops") */; +/* removed: var _$wrappedNDArrayCtor_201 = require("ndarray") */; -_$brute_39.partial = bruteForcePlanner(false) -_$brute_39.full = bruteForcePlanner(true) -'use strict' +var SUPPORTED_TYPES = [ + "uint8", + "uint8_clamped", + "uint16", + "uint32", + "int8", + "int16", + "int32", + "float32" ] -var _$genPartition_42 = genPartition +function GLBuffer(gl, type, handle, length, usage) { + this.gl = gl + this.type = type + this.handle = handle + this.length = length + this.usage = usage +} -var __code_42 = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' +var proto = GLBuffer.prototype -function genPartition(predicate, args) { - var fargs ='abcdef'.split('').concat(args) - var reads = [] - if(predicate.indexOf('lo') >= 0) { - reads.push('lo=e[k+n]') - } - if(predicate.indexOf('hi') >= 0) { - reads.push('hi=e[k+o]') - } - fargs.push( - __code_42.replace('_', reads.join()) - .replace('$', predicate)) - return Function.apply(void 0, fargs) +proto.bind = function() { + this.gl.bindBuffer(this.type, this.handle) } -'use strict' -var _$findMedian_41 = findMedian +proto.unbind = function() { + this.gl.bindBuffer(this.type, null) +} -/* removed: var _$genPartition_42 = require('./partition') */; +proto.dispose = function() { + this.gl.deleteBuffer(this.handle) +} -var partitionStartLessThan = _$genPartition_42('lo len) { + throw new Error("gl-buffer: If resizing buffer, must not specify offset") + } + gl.bufferSubData(type, offset, data) + return len +} -var PARTITION_THRESHOLD = 8 //Cut off for using insertion sort in findMedian +function makeScratchTypeArray(array, dtype) { + var res = _$pool_269.malloc(array.length, dtype) + var n = array.length + for(var i=0; istart && boxes[ptr+axis] > x; - --j, ptr-=elemSize) { - //Swap - var aPtr = ptr - var bPtr = ptr+elemSize - for(var k=0; k=0; --i) { + if(stride[i] !== n) { + return false } + n *= shape[i] } + return true } -//Find median using quick select algorithm -// takes O(n) time with high probability -function findMedian(d, axis, start, end, boxes, ids) { - if(end <= start+1) { - return start +proto.update = function(array, offset) { + if(typeof offset !== "number") { + offset = -1 } - - var lo = start - var hi = end - var mid = ((end + start) >>> 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 + this.bind() + if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray + var dtype = array.dtype + if(SUPPORTED_TYPES.indexOf(dtype) < 0) { + dtype = "float32" } - - //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 + if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { + var ext = gl.getExtension('OES_element_index_uint') + if(ext && dtype !== "uint16") { + dtype = "uint32" } else { - pivot = pivot2 - value = value2 + dtype = "uint16" + } + } + if(dtype === array.dtype && isPacked(array.shape, array.stride)) { + if(array.offset === 0 && array.data.length === array.shape[0]) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) } } else { - if(value1 >= value2) { - pivot = pivot1 - value = value1 - } else if(value2 >= value0) { - pivot = pivot0 - value = value0 + var tmp = _$pool_269.malloc(array.size, dtype) + var ndt = _$wrappedNDArrayCtor_201(tmp, array.shape) + _$ndarrayOps_200.assign(ndt, array) + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) } else { - pivot = pivot2 - value = value2 + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) } + _$pool_269.free(tmp) } - - //Swap pivot to end of array - var aPtr = elemSize * (hi-1) - var bPtr = elemSize * pivot - for(var i=0; i= 0) { + throw new Error("gl-buffer: Cannot specify offset when resizing buffer") } + array = array | 0 + if(array <= 0) { + array = 1 + } + this.gl.bufferData(this.type, array|0, this.usage) + this.length = array + } else { //Error, case should not happen + throw new Error("gl-buffer: Invalid data type") } - - //Make sure pivot is at start - return partitionStartLessThan( - d, axis, - start, mid, boxes, ids, - boxes[elemSize*mid+axis]) } -'use strict'; - -//This code is extracted from ndarray-sort -//It is inlined here as a temporary workaround - -var _$wrapper_43 = wrapper; - -var INSERT_SORT_CUTOFF = 32 -function wrapper(data, n0) { - if (n0 <= 4*INSERT_SORT_CUTOFF) { - __insertionSort_43(0, n0 - 1, data); - } else { - quickSort(0, n0 - 1, data); +function __createBuffer_140(gl, data, type, usage) { + type = type || gl.ARRAY_BUFFER + usage = usage || gl.DYNAMIC_DRAW + if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { + throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") + } + if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { + throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") } + var handle = gl.createBuffer() + var result = new GLBuffer(gl, type, handle, 0, usage) + result.update(data) + return result } -function __insertionSort_43(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 +var _$createBuffer_140 = __createBuffer_140 + +var _$browser_181 = function(strings) { + if (typeof strings === 'string') strings = [strings] + var exprs = [].slice.call(arguments,1) + var parts = [] + for (var i = 0; i < strings.length-1; i++) { + parts.push(strings[i], exprs[i] || '') } + parts.push(strings[i]) + return parts.join('') } -function __swap_43(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 -} +'use strict' + +/* removed: var _$browser_181 = require('glslify') */; + +var FRAGMENT = _$browser_181(["precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n"]) + +var _$shaders_155 = { + lineVert: _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n"]), + lineFrag: FRAGMENT, + textVert: _$browser_181(["#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n"]), + textFrag: FRAGMENT, + gridVert: _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n"]), + gridFrag: FRAGMENT, + boxVert: _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n"]), + tickVert: _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"]) +} -function move(i, j, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[i+1] = data[j+1] +function GLError (rawError, shortMessage, longMessage) { + this.shortMessage = shortMessage || '' + this.longMessage = longMessage || '' + this.rawError = rawError || '' + this.message = + 'gl-shader: ' + (shortMessage || rawError || '') + + (longMessage ? '\n'+longMessage : '') + this.stack = (new Error()).stack } +GLError.prototype = new Error +GLError.prototype.name = 'GLError' +GLError.prototype.constructor = GLError +var _$GLError_165 = GLError -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 -} +'use strict' -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 +var _$createAttributeWrapper_166 = createAttributeWrapper + +/* removed: var _$GLError_165 = require("./GLError") */; + +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 } -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 +var __proto_166 = ShaderAttribute.prototype + +__proto_166.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) } -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 +__proto_166.set = function(x0, x1, x2, x3) { + return this._constFunc(this._locations[this._index], x0, x1, x2, x3) } -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 +Object.defineProperty(__proto_166, 'location', { + get: function() { + return this._locations[this._index] } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp + , set: function(v) { + if(v !== this._locations[this._index]) { + this._locations[this._index] = v|0 + this._wrapper.program = null + } + return v|0 } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp +}) + +//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_165('', '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_165('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addMatrixAttribute( + gl + , wrapper + , locs + , locations + , d + , obj + , name) + } else { + throw new _$GLError_165('', 'Unknown data type for attribute ' + name + ': ' + type) + } + break + } } + return obj } -//Remove an item from the active queue in O(1) -function sqPop(queue, index, count, item) { - var idx = index[item] - var top = queue[count-1] - queue[idx] = top - index[top] = idx -} +'use strict' -//Insert an item into the active queue in O(1) -function sqPush(queue, index, count, item) { - queue[count] = item - index[item] = count +var _$makeReflectTypes_168 = makeReflectTypes + +//Construct type info for reflection. +// +// This iterates over the flattened list of uniform type values and smashes them into a JSON object. +// +// The leaves of the resulting object are either indices or type strings representing primitive glslify types +function makeReflectTypes(uniforms, useIndex) { + var obj = {} + for(var i=0; i 1) { + if(!(x[0] in o)) { + o[x[0]] = [] + } + o = o[x[0]] + for(var k=1; kright - var n = ptr >>> 1 - _$wrapper_43(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - for(var i=0; i= BLUE_FLAG) { - //blue destroy event - e = (e-BLUE_FLAG)|0 - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) - } else if(e >= 0) { - //red destroy event - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) - } else if(e <= -BLUE_FLAG) { - //blue create event - e = (-e-BLUE_FLAG)|0 - for(var j=0; j 4) { + throw new _$GLError_165('', 'Invalid data type') + } + switch(type.charAt(0)) { + case 'b': + case 'i': + return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' + case 'v': + return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' + default: + throw new _$GLError_165('', 'Unrecognized data type for vector ' + name + ': ' + type) + } + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new _$GLError_165('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + } + return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' + } else { + throw new _$GLError_165('', 'Unknown uniform data type for ' + name + ': ' + type) } - } - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, e) + break } } -} - -//Complete sweep -function sweepComplete(d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 - - for(var i=redStart; iright - var n = ptr >>> 1 - _$wrapper_43(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - var commonActive = 0 - for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { - color = 2 - i += 1 + function enumerateIndices(prefix, type) { + if(typeof type !== 'object') { + return [ [prefix, type] ] } - - if(e < 0) { - //Create event - var id = -(e>>1) - 1 - - //Intersect with common - for(var j=0; j 4) { + throw new _$GLError_165('', 'Invalid data type') + } + if(type.charAt(0) === 'b') { + return makeVector(d, false) + } + return makeVector(d, 0) + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new _$GLError_165('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } + return makeVector(d*d, 0) + } else { + throw new _$GLError_165('', 'Unknown uniform data type for ' + name + ': ' + type) } + break + } + } + + function storeProperty(obj, prop, type) { + if(typeof type === 'object') { + var child = processObject(type) + Object.defineProperty(obj, prop, { + get: identity(child), + set: makeSetter(type), + enumerable: true, + configurable: false + }) + } else { + if(locations[type]) { + Object.defineProperty(obj, prop, { + get: makeGetter(type), + set: makeSetter(type), + enumerable: true, + configurable: false + }) + } else { + obj[prop] = defaultValue(uniforms[type].type) } + } + } - if(color === 0) { - //Red - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id) - } else if(color === 1) { - //Blue - sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id) - } else if(color === 2) { - //Both - sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id) + function processObject(obj) { + var result + if(Array.isArray(obj)) { + result = new Array(obj.length) + for(var i=0; i>1) - 1 - if(color === 0) { - //Red - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) - } else if(color === 1) { - //Blue - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) - } else if(color === 2) { - //Both - sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) + result = {} + for(var id in obj) { + storeProperty(result, id, obj[id]) } } + return result } -} -//Sweep and prune/scanline algorithm: -// Scan along axis, detect intersections -// Brute force all boxes along axis -function scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d - - var redShift = 1 - var blueShift = 1 - if(flip) { - blueShift = BLUE_FLAG - } else { - redShift = BLUE_FLAG + //Return data + var coallesced = _$makeReflectTypes_168(uniforms, true) + return { + get: identity(processObject(coallesced)), + set: makeSetter(coallesced), + enumerable: true, + configurable: true } +} - for(var i=redStart; iright - var n = ptr >>> 1 - _$wrapper_43(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - isRed = !flip - idx -= BLUE_FLAG - } else { - isRed = !!flip - idx -= 1 - } - if(isRed) { - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) - } else { - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] +_$runtimeReflect_169.uniforms = runtimeUniforms +_$runtimeReflect_169.attributes = runtimeAttributes -red_loop: - for(var j=0; j 1) { + for(var j=0; j + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - for(var i=redStart; iright - var n = ptr >>> 1 - _$wrapper_43(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG - } else { - idx -= 1 - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx +/** + * Results cache + */ - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] +var res = ''; +var cache; -red_loop: - for(var j=0; j 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 + */ - var retval = visit(redId, blueId) - if(retval !== void 0) { - return retval - } - } - } - } else { - var idx = e - BLUE_FLAG - for(var j=redActive-1; j>=0; --j) { - if(RED_SWEEP_QUEUE[j] === idx) { - for(var k=j+1; k= max) { + return res.substr(0, max); + } -//Partition functions -var partitionInteriorContainsInterval = _$genPartition_42( - '!(lo>=p0)&&!(p1>=hi)', - ['p0', 'p1']) + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } -var partitionStartEqual = _$genPartition_42( - 'lo===p0', - ['p0']) + num >>= 1; + str += str; + } -var __partitionStartLessThan_40 = _$genPartition_42( - 'lo + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT license. + */ -var partitionContainsPoint = _$genPartition_42( - 'lo<=p0&&p0<=hi', - ['p0']) +'use strict'; -var partitionContainsPointProper = _$genPartition_42( - '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_40( - 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_44.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_44.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) +var _$builtins_176 = [ + // 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' +] - //Lower dimensional case - if(redStart < red0) { +// 300es builtins/reserved words that were previously valid in v100 +/* removed: var _$builtins_176 = require('./builtins') */; - 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_44.sweepBipartite( - d, visit, - blueStart, blueEnd, blue, blueIndex, - redStart, red0, red, redIndex) - } else { - retval = _$sweep_44.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) - } - } +// The texture2D|Cube functions have been removed +// And the gl_ features are updated +_$builtins_176 = _$builtins_176.slice().filter(function (b) { + return !/^(gl\_|texture)/.test(b) +}) - //Divide and conquer phase - if(red0 < redEnd) { +var _$builtins300es_175 = _$builtins_176.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' - //Cut blue into 3 parts: - // - // Points < mid point - // Points = mid point - // Points > mid point - // - var blue0 = _$findMedian_41( - d, axis, - blueStart, blueEnd, blue, blueIndex) - var mid = blue[elemSize * blue0 + axis] - var blue1 = partitionStartEqual( - d, axis, - blue0, blueEnd, blue, blueIndex, - mid) + // 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' +]) - //Right case - if(blue1 < blueEnd) { - iterPush(top++, - axis, - red0, redEnd, - blue1, blueEnd, - (flip|4) + (full ? 16 : 0), - mid, hi) - } +var _$literals_178 = [ + // current + 'precision' + , 'highp' + , 'mediump' + , 'lowp' + , 'attribute' + , 'const' + , 'uniform' + , 'varying' + , 'break' + , 'continue' + , 'do' + , 'for' + , 'while' + , 'if' + , 'else' + , 'in' + , 'out' + , 'inout' + , 'float' + , 'int' + , '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' - //Left case - if(blueStart < blue0) { - iterPush(top++, - axis, - red0, redEnd, - blueStart, blue0, - (flip|2) + (full ? 16 : 0), - lo, mid) - } + // 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' +] - //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_44.sweepComplete( - d, visit, - red0, redX, red, redIndex, - blue0, blue1, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } +/* removed: var _$literals_178 = require('./literals') */; - //Normal sweep intersection: - // [redX, red1] with [blue0, blue1] - if(redX < red1) { - retval = _$sweep_44.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_44.sweepBipartite( - d, visit, - blue0, blue1, blue, blueIndex, - red0, red1, red, redIndex) - } else { - retval = _$sweep_44.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) - } - } - } - } - } - } -} -'use strict' +var _$literals300es_177 = _$literals_178.slice().concat([ + 'layout' + , 'centroid' + , 'smooth' + , 'case' + , 'mat2x2' + , 'mat2x3' + , 'mat2x4' + , 'mat3x2' + , 'mat3x3' + , 'mat3x4' + , 'mat4x2' + , 'mat4x3' + , 'mat4x4' + , 'uint' + , 'uvec2' + , 'uvec3' + , 'uvec4' + , 'samplerCubeShadow' + , 'sampler2DArray' + , 'sampler2DArrayShadow' + , 'isampler2D' + , 'isampler3D' + , 'isamplerCube' + , 'isampler2DArray' + , 'usampler2D' + , 'usampler3D' + , 'usamplerCube' + , 'usampler2DArray' + , 'coherent' + , 'restrict' + , 'readonly' + , 'writeonly' + , 'resource' + , 'atomic_uint' + , 'noperspective' + , 'patch' + , 'sample' + , 'subroutine' + , 'common' + , 'partition' + , 'active' + , 'filter' + , 'image1D' + , 'image2D' + , 'image3D' + , 'imageCube' + , 'iimage1D' + , 'iimage2D' + , 'iimage3D' + , 'iimageCube' + , 'uimage1D' + , 'uimage2D' + , 'uimage3D' + , 'uimageCube' + , 'image1DArray' + , 'image2DArray' + , 'iimage1DArray' + , 'iimage2DArray' + , 'uimage1DArray' + , 'uimage2DArray' + , 'image1DShadow' + , 'image2DShadow' + , 'image1DArrayShadow' + , 'image2DArrayShadow' + , 'imageBuffer' + , 'iimageBuffer' + , 'uimageBuffer' + , 'sampler1DArray' + , 'sampler1DArrayShadow' + , 'isampler1D' + , 'isampler1DArray' + , 'usampler1D' + , 'usampler1DArray' + , 'isampler2DRect' + , 'usampler2DRect' + , 'samplerBuffer' + , 'isamplerBuffer' + , 'usamplerBuffer' + , 'sampler2DMS' + , 'isampler2DMS' + , 'usampler2DMS' + , 'sampler2DMSArray' + , 'isampler2DMSArray' + , 'usampler2DMSArray' +]) + +var _$operators_179 = [ + '<<=' + , '>>=' + , '++' + , '--' + , '<<' + , '>>' + , '<=' + , '>=' + , '==' + , '!=' + , '&&' + , '||' + , '+=' + , '-=' + , '*=' + , '/=' + , '%=' + , '&=' + , '^^' + , '^=' + , '|=' + , '(' + , ')' + , '[' + , ']' + , '.' + , '!' + , '~' + , '*' + , '/' + , '%' + , '+' + , '-' + , '<' + , '>' + , '&' + , '^' + , '|' + , '?' + , ':' + , '=' + , ',' + , ';' + , '{' + , '}' +] -var _$boxIntersectWrapper_38 = boxIntersectWrapper +var _$tokenize_174 = tokenize -/* removed: var _$pool_207 = require('typedarray-pool') */; -/* removed: var _$sweep_44 = require('./lib/sweep') */; -/* removed: var _$boxIntersectIter_40 = require('./lib/intersect') */; +var __dummy_174$0 = 0 + , __dummy_174$1 = 0 + , __dummy_174$2 = 0 + , __dummy_174$3 = 0 + , __dummy_174$4 = 0 -function boxEmpty(d, box) { - for(var j=0; j>>1 - if(d <= 0) { - return + return function(data) { + tokens = [] + if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data) + return end() } - var retval + function token(data) { + if (data.length) { + tokens.push({ + type: map[mode] + , data: data + , position: start + , line: line + , column: col + }) + } + } - //Convert red boxes - var redList = _$pool_207.mallocDouble(2*d*n) - var redIds = _$pool_207.mallocInt32(n) - n = convertBoxes(red, d, redList, redIds) + function write(chunk) { + i = 0 + input += chunk + len = input.length - if(n > 0) { - if(d === 1 && full) { - //Special case: 1d complete - _$sweep_44.init(n) - retval = _$sweep_44.sweepComplete( - d, visit, - 0, n, redList, redIds, - 0, n, redList, redIds) - } else { + var last - //Convert blue boxes - var blueList = _$pool_207.mallocDouble(2*d*m) - var blueIds = _$pool_207.mallocInt32(m) - m = convertBoxes(blue, d, blueList, blueIds) + while(c = input[i], i < len) { + last = i - if(m > 0) { - _$sweep_44.init(n+m) + 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(d === 1) { - //Special case: 1d bipartite - retval = _$sweep_44.sweepBipartite( - d, visit, - 0, n, redList, redIds, - 0, m, blueList, blueIds) - } else { - //General case: d>1 - retval = _$boxIntersectIter_40( - d, visit, full, - n, redList, redIds, - m, blueList, blueIds) + if(last !== i) { + switch(input[last]) { + case '\n': col = 0; ++line; break + default: ++col; break } - - _$pool_207.free(blueList) - _$pool_207.free(blueIds) } } - _$pool_207.free(redList) - _$pool_207.free(redIds) + total += i + input = input.slice(i) + return tokens } - return retval -} - + function end(chunk) { + if(content.length) { + token(content.join('')) + } -var RESULT + mode = EOF + token('(eof)') + return tokens + } -function appendItem(i,j) { - RESULT.push([i,j]) -} + function normal() { + content = content.length ? [] : content -function intersectFullArray(x) { - RESULT = [] - boxIntersect(x, x, appendItem, true) - return RESULT -} + if(last === '/' && c === '*') { + start = total + i - 1 + mode = BLOCK_COMMENT + last = c + return i + 1 + } -function intersectBipartiteArray(x, y) { - RESULT = [] - boxIntersect(x, y, appendItem, false) - return RESULT -} + if(last === '/' && c === '/') { + start = total + i - 1 + mode = LINE_COMMENT + last = c + return i + 1 + } -//User-friendly wrapper, handle full input and no-visitor cases -function boxIntersectWrapper(arg0, arg1, arg2) { - var result - switch(arguments.length) { - case 1: - return intersectFullArray(arg0) - case 2: - if(typeof arg1 === 'function') { - return boxIntersect(arg0, arg0, arg1, true) - } else { - return intersectBipartiteArray(arg0, arg1) - } - case 3: - return boxIntersect(arg0, arg1, arg2, false) - default: - throw new Error('box-intersect: Invalid arguments') - } -} -'use strict' + if(c === '#') { + mode = PREPROCESSOR + start = total + i + return i + } -/* removed: var _$rationalize_28 = require('./lib/rationalize') */; + if(/\s/.test(c)) { + mode = WHITESPACE + start = total + i + return i + } -var _$mul_30 = mul + isnum = /\d/.test(c) + isoperator = /[^\w_]/.test(c) -function mul(a, b) { - return _$rationalize_28(a[0].mul(b[0]), a[1].mul(b[1])) -} + start = total + i + mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN + return i + } -'use strict' + function whitespace() { + if(/[^\s]/g.test(c)) { + token(content.join('')) + mode = NORMAL + return i + } + content.push(c) + last = c + return i + 1 + } -/* removed: var _$sign_23 = require('./lib/bn-sign') */; + function preprocessor() { + if((c === '\r' || c === '\n') && last !== '\\') { + token(content.join('')) + mode = NORMAL + return i + } + content.push(c) + last = c + return i + 1 + } -var _$sign_31 = __sign_31 + function line_comment() { + return preprocessor() + } -function __sign_31(x) { - return _$sign_23(x[0]) * _$sign_23(x[1]) -} + function block_comment() { + if(c === '/' && last === '*') { + content.push(c) + token(content.join('')) + mode = NORMAL + return i + 1 + } -'use strict' + content.push(c) + last = c + return i + 1 + } -/* removed: var _$rationalize_28 = require('./lib/rationalize') */; + function operator() { + if(last === '.' && /\d/.test(c)) { + mode = FLOAT + return i + } -var _$sub_32 = sub + if(last === '/' && c === '*') { + mode = BLOCK_COMMENT + return i + } -function sub(a, b) { - return _$rationalize_28(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) -} + if(last === '/' && c === '/') { + mode = LINE_COMMENT + return i + } -'use strict' + if(c === '.' && content.length) { + while(determine_operator(content)); -/* removed: var _$rationalize_28 = require('./lib/rationalize') */; + mode = FLOAT + return i + } -var _$add_18 = add + if(c === ';' || c === ')' || c === '(') { + if(content.length) while(determine_operator(content)); + token(c) + mode = NORMAL + return i + 1 + } -function add(a, b) { - return _$rationalize_28( - a[0].mul(b[1]).add(b[0].mul(a[1])), - a[1].mul(b[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 + } -'use strict' + content.push(c) + last = c + return i + 1 + } -/* removed: var _$add_18 = require('big-rat/add') */; + function determine_operator(buf) { + var j = 0 + , idx + , res -var _$add_167 = __add_167 + do { + idx = _$operators_179.indexOf(buf.slice(0, buf.length + j).join('')) + res = _$operators_179[idx] -function __add_167 (a, b) { - var n = a.length - var r = new Array(n) - for (var i=0; i 0) continue + res = buf.slice(0, 1).join('') + } -'use strict' + token(res) -/* removed: var _$makeRational_21 = require('big-rat') */; -/* removed: var _$mul_30 = require('big-rat/mul') */; + start += res.length + content = content.slice(res.length) + return content.length + } while(1) + } -var _$muls_169 = muls + function hex() { + if(/[^a-fA-F0-9]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i + } -function muls(a, x) { - var s = _$makeRational_21(x) - var n = a.length - var r = new Array(n) - for(var i=0; i -1) { + mode = KEYWORD + } else if(allBuiltins.indexOf(contentstr) > -1) { + mode = BUILTIN + } else { + mode = IDENT + } + token(content.join('')) + mode = NORMAL + return i + } + content.push(c) + last = c + return i + 1 + } +} - var baXdc = ratPerp(ba, dc) +/* removed: var _$tokenize_174 = require('./index') */; - if (_$sign_31(baXdc) === 0) { - return null - } +var _$tokenizeString_180 = tokenizeString - var ac = _$sub_170(a, c) - var dcXac = ratPerp(dc, ac) +function tokenizeString(str, opt) { + var generator = _$tokenize_174(opt) + var tokens = [] - var t = _$div_20(dcXac, baXdc) - var s = _$muls_169(ba, t) - var r = _$add_167(a, s) + tokens = tokens.concat(generator(str)) + tokens = tokens.concat(generator(null)) - return r + return tokens } -"use strict" +/* removed: var _$tokenizeString_180 = require('glsl-tokenizer') */; +/* removed: var _$_atob_17 = require('atob-lite') */; -/* removed: var _$double_70 = require("double-bits") */; +var _$getName_173 = getName -var SMALLEST_DENORM = Math.pow(2, -1074) -var UINT_MAX = (-1)>>>0 +function getName(src) { + var tokens = Array.isArray(src) + ? src + : _$tokenizeString_180(src) -var _$nextafter_144 = nextafter + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i] + if (token.type !== 'preprocessor') continue + var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) + if (!match) continue + if (!match[2]) continue -function nextafter(x, y) { - if(isNaN(x) || isNaN(y)) { - return NaN - } - if(x === y) { - return x + var b64 = match[1] + var name = match[2] + + return (b64 ? _$_atob_17(name) : name).trim() } - if(x === 0) { - if(y < 0) { - return -SMALLEST_DENORM - } else { - return SMALLEST_DENORM +} + +var _$sprintf_255 = {}; +/* global window, exports, define */ + +!function() { + 'use strict' + + var re = { + not_string: /[^s]/, + not_bool: /[^t]/, + not_type: /[^T]/, + not_primitive: /[^v]/, + number: /[diefg]/, + numeric_arg: /[bcdiefguxX]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ } - } - var hi = _$double_70.hi(x) - var lo = _$double_70.lo(x) - if((y > x) === (x > 0)) { - if(lo === UINT_MAX) { - hi += 1 - lo = 0 - } else { - lo += 1 + + function sprintf(key) { + // `arguments` is not an array, but should be fine for this call + return sprintf_format(sprintf_parse(key), arguments) } - } else { - if(lo === 0) { - lo = UINT_MAX - hi -= 1 - } else { - lo -= 1 + + function vsprintf(fmt, argv) { + return sprintf.apply(null, [fmt].concat(argv || [])) } - } - return _$double_70.pack(lo, hi) -} -'use strict' -var _$float2rat_168 = float2rat + function sprintf_format(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, match, pad, pad_character, pad_length, is_positive, sign + for (i = 0; i < tree_length; i++) { + if (typeof parse_tree[i] === 'string') { + output += parse_tree[i] + } + else if (Array.isArray(parse_tree[i])) { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } -/* removed: var _$makeRational_21 = require('big-rat') */; + if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && arg instanceof Function) { + arg = arg() + } -function float2rat(v) { - var result = new Array(v.length) - for(var i=0; i= 0 + } -var _$segmentsIntersect_181 = __segmentsIntersect_181 + switch (match[8]) { + case 'b': + arg = parseInt(arg, 10).toString(2) + break + case 'c': + arg = String.fromCharCode(parseInt(arg, 10)) + break + case 'd': + case 'i': + arg = parseInt(arg, 10) + break + case 'j': + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case 'e': + arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential() + break + case 'f': + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case 'g': + arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg) + break + case 'o': + arg = (parseInt(arg, 10) >>> 0).toString(8) + break + case 's': + arg = String(arg) + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 't': + arg = String(!!arg) + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 'T': + arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 'u': + arg = parseInt(arg, 10) >>> 0 + break + case 'v': + arg = arg.valueOf() + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 'x': + arg = (parseInt(arg, 10) >>> 0).toString(16) + break + case 'X': + arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output += arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? '+' : '-' + arg = arg.toString().replace(re.sign, '') + } + else { + sign = '' + } + pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' ' + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' + output += match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) + } + } + } + return output + } -var __orient_181 = _$orientation_178[3] + var sprintf_cache = Object.create(null) -function checkCollinear(a0, a1, b0, b1) { + function sprintf_parse(fmt) { + if (sprintf_cache[fmt]) { + return sprintf_cache[fmt] + } - 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 _fmt = fmt, match, parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree.push(match[0]) + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree.push('%') + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + } + else { + throw new SyntaxError('[sprintf] failed to parse named argument key') + } + } + } + else { + throw new SyntaxError('[sprintf] failed to parse named argument key') + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') + } + parse_tree.push(match) + } + else { + throw new SyntaxError('[sprintf] unexpected placeholder') + } + _fmt = _fmt.substring(match[0].length) + } + return sprintf_cache[fmt] = parse_tree + } - var x1 = b0[d] - var y1 = b1[d] - var l1 = Math.min(x1, y1) - var h1 = Math.max(x1, y1) + /** + * export to either browser or node.js + */ + /* eslint-disable quote-props */ + if (typeof _$sprintf_255 !== 'undefined') { + _$sprintf_255['sprintf'] = sprintf + _$sprintf_255['vsprintf'] = vsprintf + } + if (typeof window !== 'undefined') { + window['sprintf'] = sprintf + window['vsprintf'] = vsprintf - if(h1 < l0 || h0 < l1) { - return false + if (typeof define === 'function' && define['amd']) { + define(function() { + return { + 'sprintf': sprintf, + 'vsprintf': vsprintf + } + }) + } } - } + /* eslint-enable quote-props */ +}() - return true -} -function __segmentsIntersect_181(a0, a1, b0, b1) { - var x0 = __orient_181(a0, b0, b1) - var y0 = __orient_181(a1, b0, b1) - if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { - return false - } +var sprintf = _$sprintf_255.sprintf; +/* removed: var _$lookupConstant_142 = require('gl-constants/lookup'); */; +/* removed: var _$getName_173 = require('glsl-shader-name'); */; +/* removed: var _$addLineNumbers_12 = require('add-line-numbers'); */; - var x1 = __orient_181(b0, a0, a1) - var y1 = __orient_181(b1, a0, a1) - if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { - return false - } +var _$formatCompilerError_147 = formatCompilerError; - //Check for degenerate collinear case - if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { - return checkCollinear(a0, a1, b0, b1) - } +function formatCompilerError(errLog, src, type) { + "use strict"; - return true -} -"use strict"; "use restrict"; + var name = _$getName_173(src) || 'of unknown name (see npm glsl-shader-name)'; -var _$UnionFind_208 = UnionFind; + var typeName = 'unknown type'; + if (type !== undefined) { + typeName = type === _$lookupConstant_142.FRAGMENT_SHADER ? 'fragment' : 'vertex' + } -function UnionFind(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; i= 0; --i) { - var junction = junctions[i] - e = junction[0] +var _$shaderCache_170 = {}; +'use strict' - var edge = edges[e] - var s = edge[0] - var t = edge[1] +_$shaderCache_170.shader = getShaderReference +_$shaderCache_170.program = createProgram - // Check if edge is not lexicographically sorted - var a = floatPoints[s] - var b = floatPoints[t] - if (((a[0] - b[0]) || (a[1] - b[1])) < 0) { - var tmp = s - s = t - t = tmp - } +/* removed: var _$GLError_165 = require("./GLError") */; +/* removed: var _$formatCompilerError_147 = require('gl-format-compiler-error'); */; - // Split leading edge - edge[0] = s - var last = edge[1] = junction[1] +var __weakMap_170 = typeof WeakMap === 'undefined' ? _$weakMap_280 : WeakMap +var CACHE = new __weakMap_170() - // If we are grouping edges by color, remember to track data - var color - if (useColor) { - color = edge[2] - } +var SHADER_COUNTER = 0 - // Split other edges - while (i > 0 && junctions[i - 1][0] === e) { - var junction = junctions[--i] - var next = junction[1] - if (useColor) { - edges.push([last, next, color]) - } else { - edges.push([last, next]) +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 b[2]) { - return 1 +__proto_170.getProgram = function(vref, fref, attribs, locations) { + var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') + var prog = this.programs[token] + if(!prog || !this.gl.isProgram(prog)) { + this.programs[token] = prog = linkProgram( + this.gl, + vref.shader, + fref.shader, + attribs, + locations) + vref.programs.push(token) + fref.programs.push(token) } - return 0 + return prog } -// Remove duplicate edge labels -function dedupEdges (edges, labels, useColor) { - if (edges.length === 0) { - return - } - if (labels) { - for (var i = 0; i < edges.length; ++i) { - var e = edges[i] - var a = labels[e[0]] - var b = labels[e[1]] - e[0] = Math.min(a, b) - e[1] = Math.max(a, b) - } - } else { - for (var i = 0; i < edges.length; ++i) { - var e = edges[i] - var a = e[0] - var b = e[1] - e[0] = Math.min(a, b) - e[1] = Math.max(a, b) - } - } - if (useColor) { - edges.sort(compareLex3) - } else { - edges.sort(compareLex2) - } - var ptr = 1 - for (var i = 1; i < edges.length; ++i) { - var prev = edges[i - 1] - var next = edges[i] - if (next[0] === prev[0] && next[1] === prev[1] && - (!useColor || next[2] === prev[2])) { - continue - } - edges[ptr++] = next +function getCache(gl) { + var ctxCache = CACHE.get(gl) + if(!ctxCache) { + ctxCache = new ContextCache(gl) + CACHE.set(gl, ctxCache) } - edges.length = ptr + return ctxCache } -function preRound (points, edges, useColor) { - var labels = dedupPoints(points, [], boundPoints(points)) - dedupEdges(edges, labels, useColor) - return !!labels +function getShaderReference(gl, type, src) { + return getCache(gl).getShaderReference(type, src) } -// Repeat until convergence -function snapRound (points, edges, useColor) { - // 1. find edge crossings - var edgeBounds = boundEdges(points, edges) - var crossings = getCrossings(points, edges, edgeBounds) - - // 2. find t-junctions - var vertBounds = boundPoints(points) - var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) - - // 3. cut edges, construct rational points - var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) +function createProgram(gl, vref, fref, attribs, locations) { + return getCache(gl).getProgram(vref, fref, attribs, locations) +} - // 4. dedupe verts - var labels = dedupPoints(points, ratPoints, vertBounds) +'use strict' - // 5. dedupe edges - dedupEdges(edges, labels, useColor) +/* removed: var _$createUniformWrapper_167 = require('./lib/create-uniforms') */; +/* removed: var _$createAttributeWrapper_166 = require('./lib/create-attributes') */; +/* removed: var _$makeReflectTypes_168 = require('./lib/reflect') */; +/* removed: var _$shaderCache_170 = require('./lib/shader-cache') */; +/* removed: var _$runtimeReflect_169 = require('./lib/runtime-reflect') */; +/* removed: var _$GLError_165 = require("./lib/GLError") */; - // 6. check termination - if (!labels) { - return (crossings.length > 0 || tjunctions.length > 0) - } +//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 - // More iterations necessary - return true + //Default initialize these to null + this._vref = + this._fref = + this._relink = + this.vertShader = + this.fragShader = + this.program = + this.attributes = + this.uniforms = + this.types = null } -// Main loop, runs PSLG clean up until completion -function cleanPSLG (points, edges, colors) { - // If using colors, augment edges with color data - var prevEdges - if (colors) { - prevEdges = edges - var augEdges = new Array(edges.length) - for (var i = 0; i < edges.length; ++i) { - var e = edges[i] - augEdges[i] = [e[0], e[1], colors[i]] - } - edges = augEdges - } - - // First round: remove duplicate edges and points - var modified = preRound(points, edges, !!colors) +var __proto_164 = Shader.prototype - // Run snap rounding until convergence - while (snapRound(points, edges, !!colors)) { - modified = true +__proto_164.bind = function() { + if(!this.program) { + this._relink() } - // Strip color tags - if (!!colors && modified) { - prevEdges.length = 0 - colors.length = 0 - for (var i = 0; i < edges.length; ++i) { - var e = edges[i] - prevEdges.push([e[0], e[1]]) - colors.push(e[2]) + // 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) } } - return modified -} - -"use strict" + this.gl.lastAttribCount = newAttribCount -var _$edgeToAdjacency_75 = edgeToAdjacency + this.gl.useProgram(this.program) +} -/* removed: var _$unique_209 = require("uniq") */; +__proto_164.dispose = function() { -function edgeToAdjacency(edges, numVertices) { - var numEdges = edges.length - if(typeof numVertices !== "number") { - numVertices = 0 - for(var i=0; i 0) { return 1 } - return 0.0 -} -"use strict" + var wrapper = this + var gl = wrapper.gl -var _$compareAngle_63 = compareAngle + //Compile vertex and fragment shaders + var pvref = wrapper._vref + wrapper._vref = _$shaderCache_170.shader(gl, gl.VERTEX_SHADER, vertSource) + if(pvref) { + pvref.dispose() + } + wrapper.vertShader = wrapper._vref.shader + var pfref = this._fref + wrapper._fref = _$shaderCache_170.shader(gl, gl.FRAGMENT_SHADER, fragSource) + if(pfref) { + pfref.dispose() + } + wrapper.fragShader = wrapper._fref.shader -/* removed: var _$orientation_178 = require("robust-orientation") */; -/* removed: var _$signum_184 = require("signum") */; -/* removed: var _$fastTwoSum_206 = require("two-sum") */; -/* removed: var _$robustProduct_179 = require("robust-product") */; -/* removed: var _$linearExpansionSum_183 = require("robust-sum") */; + //If uniforms/attributes is not specified, use RT reflection + if(!uniforms || !attributes) { -function testInterior(a, b, c) { - var x0 = _$fastTwoSum_206(a[0], -b[0]) - var y0 = _$fastTwoSum_206(a[1], -b[1]) - var x1 = _$fastTwoSum_206(c[0], -b[0]) - var y1 = _$fastTwoSum_206(c[1], -b[1]) + //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_165(errLog, 'Error linking program:' + errLog) + } - var d = _$linearExpansionSum_183( - _$robustProduct_179(x0, x1), - _$robustProduct_179(y0, y1)) + //Load data from runtime + uniforms = uniforms || _$runtimeReflect_169.uniforms(gl, testProgram) + attributes = attributes || _$runtimeReflect_169.attributes(gl, testProgram) - return d[d.length-1] >= 0 -} + //Release test program + gl.deleteProgram(testProgram) + } -function compareAngle(a, b, c, d) { - var bcd = _$orientation_178(b, c, d) - if(bcd === 0) { - //Handle degenerate cases - var sabc = _$signum_184(_$orientation_178(a, b, c)) - var sabd = _$signum_184(_$orientation_178(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 + //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) { - 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 _$signum_184(sabd - sabc) - } - var abc = _$orientation_178(a, b, c) - if(abc > 0) { - if(bcd > 0 && _$orientation_178(a, b, d) > 0) { - return 1 - } - return -1 - } else if(abc < 0) { - if(bcd > 0 || _$orientation_178(a, b, d) > 0) { - return 1 - } - return -1 - } else { - var abd = _$orientation_178(a, b, d) - if(abd > 0) { - return 1 + attributeUnpacked.push({ + name: attr.name, + type: attr.type, + locations: locVector + }) } else { - if(testInterior(a, b, c)) { - return 1 + attributeUnpacked.push({ + name: attr.name, + type: attr.type, + locations: [ attributeLocations.length ] + }) + attributeNames.push(attr.name) + if(typeof attr.location === 'number') { + attributeLocations.push(attr.location|0) } else { - return -1 + attributeLocations.push(-1) } } } -} -"use strict" - -var _$planarDual_154 = planarDual - -/* removed: var _$compareAngle_63 = require("compare-angle") */; - -function planarDual(cells, positions) { - - var numVertices = positions.length|0 - var numEdges = cells.length - var adj = [new Array(numVertices), new Array(numVertices)] - for(var i=0; i= 0) { + curLocation += 1 + } + attributeLocations[i] = curLocation } } - //Remove a half edge - function cut(c, i) { - var a = adj[i][c[i]] - a.splice(a.indexOf(c), 1) - } - - //Find next vertex and cut edge - function next(a, b, noCut) { - var nextCell, nextVertex, nextDir - for(var i=0; i<2; ++i) { - if(adj[i][b].length > 0) { - nextCell = adj[i][b][0] - nextDir = i - break - } - } - nextVertex = nextCell[nextDir^1] + //Rebuild program and recompute all uniform locations + var uniformLocations = new Array(uniforms.length) + function relink() { + wrapper.program = _$shaderCache_170.program( + gl + , wrapper._vref + , wrapper._fref + , attributeNames + , attributeLocations) - for(var dir=0; dir<2; ++dir) { - var nbhd = adj[dir][b] - for(var k=0; k 0) { - nextCell = e - nextVertex = p - nextDir = dir - } - } - } - if(noCut) { - return nextVertex - } - if(nextCell) { - cut(nextCell, nextDir) + for(var i=0; i 0) { - var ni = adj[0][i].length - var ncycle = extractCycle(i,j) - if(shouldGlue(pcycle, ncycle)) { - //Glue together trivial cycles - pcycle.push.apply(pcycle, ncycle) - } else { - if(pcycle.length > 0) { - cycles.push(pcycle) - } - pcycle = ncycle - } - } - if(pcycle.length > 0) { - cycles.push(pcycle) - } - } + //Generate type info + wrapper.types = { + uniforms: _$makeReflectTypes_168(uniforms), + attributes: _$makeReflectTypes_168(attributes) } - //Combine paths and loops together - return cycles + //Generate attribute wrappers + wrapper.attributes = _$createAttributeWrapper_166( + gl + , wrapper + , attributeUnpacked + , attributeLocations) + + //Generate uniform wrappers + Object.defineProperty(wrapper, 'uniforms', _$createUniformWrapper_167( + gl + , wrapper + , uniforms + , uniformLocations)) } -'use strict' -var _$trimLeaves_155 = trimLeaves +//Compiles and links a shader program with the given attribute and vertex list +function createShader( + gl + , vertSource + , fragSource + , uniforms + , attributes) { -/* removed: var _$edgeToAdjacency_75 = require('edges-to-adjacency-list') */; + var shader = new Shader(gl) -function trimLeaves(edges, positions) { - var adj = _$edgeToAdjacency_75(edges, positions.length) - var live = new Array(positions.length) - var nbhd = new Array(positions.length) + shader.update( + vertSource + , fragSource + , uniforms + , attributes) - var dead = [] - for(var i=0; i 0) { - var v = dead.pop() - live[v] = false - var n = adj[v] - for(var i=0; i>>1,x=a", useNdarray ? ".get(m)" : "[m]"] + earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), + ";while(l<=h){var m=(l+h)>>>1,x=a[m]"] if(earlyOut) { if(predicate.indexOf("c") < 0) { code.push(";if(x===y){return m}else if(x<=y){") @@ -45618,12790 +44310,15728 @@ var m=(l+h)>>>1,x=a", useNdarray ? ".get(m)" : "[m]"] return code.join("") } -function __compileBoundsSearch_34(predicate, reversed, suffix, earlyOut) { +function compileBoundsSearch(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_34("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), - __compileSearch_34("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), - __compileSearch_34("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), - __compileSearch_34("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut), + compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], 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)\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?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 A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_34 = { - ge: __compileBoundsSearch_34(">=", false, "GE"), - gt: __compileBoundsSearch_34(">", false, "GT"), - lt: __compileBoundsSearch_34("<", true, "LT"), - le: __compileBoundsSearch_34("<=", true, "LE"), - eq: __compileBoundsSearch_34("-", true, "EQ", true) +var _$searchBounds_53 = { + ge: compileBoundsSearch(">=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) } "use strict" -/* removed: var _$searchBounds_34 = require("binary-search-bounds") */; - -var NOT_FOUND = 0 -var SUCCESS = 1 -var EMPTY = 2 - -var _$createWrapper_128 = 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_128 = 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 +function __compileSearch_157(funcName, predicate, reversed, extraArgs, 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[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;") } - intervals.splice(idx, 1) - rebuild(node, intervals) - return SUCCESS -} - -__proto_128.intervals = function(result) { - result.push.apply(result, this.leftPoints) - if(this.left) { - this.left.intervals(result) + if(reversed) { + code.push("l=m+1}else{h=m-1}") + } else { + code.push("h=m-1}else{l=m+1}") } - if(this.right) { - this.right.intervals(result) + code.push("}") + if(earlyOut) { + code.push("return -1};") + } else { + code.push("return i};") } - return result + return code.join("") } -__proto_128.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 = _$searchBounds_34.ge(this.leftPoints, interval, compareBegin) - var r = _$searchBounds_34.ge(this.rightPoints, interval, compareEnd) - this.leftPoints.splice(l, 0, interval) - this.rightPoints.splice(r, 0, interval) - } +function __compileBoundsSearch_157(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_157("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_157("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() } -__proto_128.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 _$searchBounds_157 = { + ge: __compileBoundsSearch_157(">=", false, "GE"), + gt: __compileBoundsSearch_157(">", false, "GT"), + lt: __compileBoundsSearch_157("<", true, "LT"), + le: __compileBoundsSearch_157("<=", true, "LE"), + eq: __compileBoundsSearch_157("-", true, "EQ", true) +} + +'use strict' + +var _$createGrid_153 = createGrid + +/* removed: var _$createBuffer_140 = require('gl-buffer') */; +/* removed: var _$createShader_164 = require('gl-shader') */; +/* removed: var _$searchBounds_157 = require('binary-search-bounds') */; +/* removed: var _$shaders_155 = require('./shaders') */; + +function Grid(plot, vbo, shader, tickShader) { + this.plot = plot + this.vbo = vbo + this.shader = shader + this.tickShader = tickShader + this.ticks = [[], []] +} + +function compareTickNum(a, b) { + return a - b +} + +var __proto_153 = Grid.prototype + +__proto_153.draw = (function() { + + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var DATA_AXIS = [0,0] + + return function() { + var plot = this.plot + var vbo = this.vbo + var shader = this.shader + var ticks = this.ticks + var gl = plot.gl + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var viewPixels = plot.viewBox + var lineWidth = plot.gridLineWidth + var gridColor = plot.gridLineColor + var gridEnable = plot.gridLineEnable + var pixelRatio = plot.pixelRatio + + 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] + DATA_SCALE[i] = 2.0 * boundScale / dataWidth + DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth + } + + shader.bind() + vbo.bind() + shader.attributes.dataCoord.pointer() + shader.uniforms.dataShift = DATA_SHIFT + shader.uniforms.dataScale = DATA_SCALE + + var offset = 0 + for(var i=0; i<2; ++i) { + DATA_AXIS[0] = DATA_AXIS[1] = 0 + DATA_AXIS[i] = 1 + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.lineWidth = lineWidth[i] / (viewPixels[i+2] - viewPixels[i]) * pixelRatio + shader.uniforms.color = gridColor[i] + + var size = ticks[i].length * 6 + if(gridEnable[i] && size) { + gl.drawArrays(gl.TRIANGLES, offset, size) + } + offset += size + } + } +})() + +__proto_153.drawTickMarks = (function() { + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var X_AXIS = [1,0] + var Y_AXIS = [0,1] + var SCR_OFFSET = [0,0] + var TICK_SCALE = [0,0] + + return function() { + var plot = this.plot + var vbo = this.vbo + var shader = this.tickShader + var ticks = this.ticks + var gl = plot.gl + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + var screenBox = plot.screenBox + + var screenWidth = screenBox[2] - screenBox[0] + var screenHeight = screenBox[3] - screenBox[1] + var viewWidth = viewBox[2] - viewBox[0] + var viewHeight = viewBox[3] - viewBox[1] + + 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]) + DATA_SCALE[i] = 2.0 * boundScale / dataWidth + DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth + } + + DATA_SCALE[0] *= viewWidth / screenWidth + DATA_SHIFT[0] *= viewWidth / screenWidth + + DATA_SCALE[1] *= viewHeight / screenHeight + DATA_SHIFT[1] *= viewHeight / screenHeight + + shader.bind() + vbo.bind() + + shader.attributes.dataCoord.pointer() + + var uniforms = shader.uniforms + uniforms.dataShift = DATA_SHIFT + uniforms.dataScale = DATA_SCALE + + var tickMarkLength = plot.tickMarkLength + var tickMarkWidth = plot.tickMarkWidth + var tickMarkColor = plot.tickMarkColor + + var xTicksOffset = 0 + var yTicksOffset = ticks[0].length * 6 + + var xStart = Math.min(_$searchBounds_157.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xEnd = Math.min(_$searchBounds_157.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xOffset = xTicksOffset + 6 * xStart + var xCount = 6 * Math.max(0, xEnd - xStart) + + var yStart = Math.min(_$searchBounds_157.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yEnd = Math.min(_$searchBounds_157.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yOffset = yTicksOffset + 6 * yStart + var yCount = 6 * Math.max(0, yEnd - yStart) + + SCR_OFFSET[0] = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0 + SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkLength[1] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkWidth[1] * pixelRatio / screenHeight + + if(yCount) { + uniforms.color = tickMarkColor[1] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = Y_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, yOffset, yCount) + } + + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight + + if(xCount) { + uniforms.color = tickMarkColor[0] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } + + SCR_OFFSET[0] = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0 + SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkLength[3] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkWidth[3] * pixelRatio / screenHeight + + if(yCount) { + uniforms.color = tickMarkColor[3] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = Y_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, yOffset, yCount) + } + + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[2] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[2] * pixelRatio / screenHeight + + if(xCount) { + uniforms.color = tickMarkColor[2] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } + } +})() + +__proto_153.update = (function() { + var OFFSET_X = [1, 1, -1, -1, 1, -1] + var OFFSET_Y = [1, -1, 1, 1, -1, -1] + + return function(options) { + var ticks = options.ticks + var bounds = options.bounds + var data = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length)) + + var zeroLineEnable = this.plot.zeroLineEnable + + var ptr = 0 + var gridTicks = [[], []] + for(var dim=0; dim<2; ++dim) { + var localTicks = gridTicks[dim] + var axisTicks = ticks[dim] + var lo = bounds[dim] + var hi = bounds[dim+2] + for(var i=0; i 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; } - var r = this.right.remove(interval) - if(r === EMPTY) { - this.right = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); } - return r - } else { - if(this.count === 1) { - if(this.leftPoints[0] === interval) { - return EMPTY - } else { - return NOT_FOUND - } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); } - 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 + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); } - 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 = _$searchBounds_34.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 } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); } - return reportRightRange(this.rightPoints, x, cb) - } else { - return reportRange(this.leftPoints, cb) - } -} - -__proto_128.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 drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; -function compareBegin(a, b) { - var d = a[0] - b[0] - if(d) { return d } - return a[1] - b[1] + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); } -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 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } } - } - - //Split center intervals - var leftPoints = centerIntervals - var rightPoints = centerIntervals.slice() - leftPoints.sort(compareBegin) - rightPoints.sort(compareEnd) - - return new IntervalTreeNode(mid, - createIntervalTree(leftIntervals), - createIntervalTree(rightIntervals), - leftPoints, - rightPoints) -} - -//User friendly wrapper that makes it possible to support empty trees -function IntervalTree(root) { - this.root = root -} - -var tproto = IntervalTree.prototype - -tproto.insert = function(interval) { - if(this.root) { - this.root.insert(interval) - } else { - this.root = new IntervalTreeNode(interval[0], null, null, [interval], [interval]) - } -} - -tproto.remove = function(interval) { - if(this.root) { - var r = this.root.remove(interval) - if(r === EMPTY) { - this.root = null + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); } - return r !== NOT_FOUND - } - return false -} +}; -tproto.queryPoint = function(p, cb) { - if(this.root) { - return this.root.queryPoint(p, cb) - } +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; } +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; -tproto.queryInterval = function(lo, hi, cb) { - if(lo <= hi && this.root) { - return this.root.queryInterval(lo, hi, cb) - } -} +function __noop_228() {} -Object.defineProperty(tproto, "count", { - get: function() { - if(this.root) { - return this.root.count - } - return 0 - } -}) +process.on = __noop_228; +process.addListener = __noop_228; +process.once = __noop_228; +process.off = __noop_228; +process.removeListener = __noop_228; +process.removeAllListeners = __noop_228; +process.emit = __noop_228; +process.prependListener = __noop_228; +process.prependOnceListener = __noop_228; -Object.defineProperty(tproto, "intervals", { - get: function() { - if(this.root) { - return this.root.intervals([]) - } - return [] - } -}) +process.listeners = function (name) { return [] } -function createWrapper(intervals) { - if(!intervals || intervals.length === 0) { - return new IntervalTree(null) - } - return new IntervalTree(createIntervalTree(intervals)) -} +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; -"use strict" +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -var _$createRBTree_80 = createRBTree +"use strict" -var RED = 0 -var BLACK = 1 +var _$twoProduct_267 = twoProduct -function RBNode(color, key, value, left, right, count) { - this._color = color - this.key = key - this.value = value - this.left = left - this.right = right - this._count = count -} +var SPLITTER = +(Math.pow(2, 27) + 1.0) -function cloneNode(node) { - return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) -} +function twoProduct(a, b, result) { + var x = a * b -function repaint(color, node) { - return new RBNode(color, node.key, node.value, node.left, node.right, node._count) -} + var c = SPLITTER * a + var abig = c - a + var ahi = c - abig + var alo = a - ahi -function recount(node) { - node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) -} + var d = SPLITTER * b + var bbig = d - b + var bhi = d - bbig + var blo = b - bhi -function RedBlackTree(compare, root) { - this._compare = compare - this.root = root -} + var err1 = x - (ahi * bhi) + var err2 = err1 - (alo * bhi) + var err3 = err2 - (ahi * blo) -var __proto_80 = RedBlackTree.prototype + var y = alo * blo - err3 -Object.defineProperty(__proto_80, "keys", { - get: function() { - var result = [] - this.forEach(function(k,v) { - result.push(k) - }) + if(result) { + result[0] = y + result[1] = x return result } -}) -Object.defineProperty(__proto_80, "values", { - get: function() { - var result = [] - this.forEach(function(k,v) { - result.push(v) - }) - return result - } -}) + return [ y, x ] +} +"use strict" -//Returns the number of nodes in the tree -Object.defineProperty(__proto_80, "length", { - get: function() { - if(this.root) { - return this.root._count - } - return 0 - } -}) +var _$fastTwoSum_268 = fastTwoSum -//Insert a new item into the tree -__proto_80.insert = function(key, value) { - var cmp = this._compare - //Find point to insert new node at - var n = this.root - var n_stack = [] - var d_stack = [] - while(n) { - var d = cmp(key, n.key) - n_stack.push(n) - d_stack.push(d) - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - //Rebuild path to leaf node - n_stack.push(new RBNode(RED, key, value, null, null, 1)) - for(var s=n_stack.length-2; s>=0; --s) { - var n = n_stack[s] - if(d_stack[s] <= 0) { - n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) - } else { - n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) - } - } - //Rebalance tree using rotations - //console.log("start insert", key, d_stack) - for(var s=n_stack.length-1; s>1; --s) { - var p = n_stack[s-1] - var n = n_stack[s] - if(p._color === BLACK || n._color === BLACK) { - break - } - var pp = n_stack[s-2] - if(pp.left === p) { - if(p.left === n) { - var y = pp.right - if(y && y._color === RED) { - //console.log("LLr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LLb") - pp._color = RED - pp.left = p.right - p._color = BLACK - p.right = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = p - } else { - ppp.right = p - } - } - break - } - } else { - var y = pp.right - if(y && y._color === RED) { - //console.log("LRr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LRb") - p.right = n.left - pp._color = RED - pp.left = n.right - n._color = BLACK - n.left = p - n.right = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = n - } else { - ppp.right = n - } - } - break - } - } - } else { - if(p.right === n) { - var y = pp.left - if(y && y._color === RED) { - //console.log("RRr", y.key) - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RRb") - pp._color = RED - pp.right = p.left - p._color = BLACK - p.left = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = p - } else { - ppp.left = p - } - } - break - } - } else { - var y = pp.left - if(y && y._color === RED) { - //console.log("RLr") - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RLb") - p.left = n.right - pp._color = RED - pp.right = n.left - n._color = BLACK - n.right = p - n.left = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = n - } else { - ppp.left = n - } - } - break - } - } - } - } - //Return new tree - n_stack[0]._color = BLACK - return new RedBlackTree(cmp, n_stack[0]) +function fastTwoSum(a, b, result) { + var x = a + b + var bv = x - a + var av = x - bv + var br = b - bv + var ar = a - av + if(result) { + result[0] = ar + br + result[1] = x + return result + } + return [ar+br, x] } +"use strict" +/* removed: var _$twoProduct_267 = require("two-product") */; +/* removed: var _$fastTwoSum_268 = require("two-sum") */; -//Visit all nodes inorder -function doVisitFull(visit, node) { - if(node.left) { - var v = doVisitFull(visit, node.left) - if(v) { return v } - } - var v = visit(node.key, node.value) - if(v) { return v } - if(node.right) { - return doVisitFull(visit, node.right) - } -} +var _$scaleLinearExpansion_244 = scaleLinearExpansion -//Visit half nodes in order -function doVisitHalf(lo, compare, visit, node) { - var l = compare(lo, node.key) - if(l <= 0) { - if(node.left) { - var v = doVisitHalf(lo, compare, visit, node.left) - if(v) { return v } +function scaleLinearExpansion(e, scale) { + var n = e.length + if(n === 1) { + var ts = _$twoProduct_267(e[0], scale) + if(ts[0]) { + return ts } - var v = visit(node.key, node.value) - if(v) { return v } + return [ ts[1] ] } - if(node.right) { - return doVisitHalf(lo, compare, visit, node.right) + var g = new Array(2 * n) + var q = [0.1, 0.1] + var t = [0.1, 0.1] + var count = 0 + _$twoProduct_267(e[0], scale, q) + if(q[0]) { + g[count++] = q[0] } -} - -//Visit all nodes within a range -function doVisit(lo, hi, compare, visit, node) { - var l = compare(lo, node.key) - var h = compare(hi, node.key) - var v - if(l <= 0) { - if(node.left) { - v = doVisit(lo, hi, compare, visit, node.left) - if(v) { return v } + for(var i=1; i 0) { - v = visit(node.key, node.value) - if(v) { return v } + var a = t[1] + var b = q[1] + var x = a + b + var bv = x - a + var y = b - bv + q[1] = x + if(y) { + g[count++] = y } } - if(h > 0 && node.right) { - return doVisit(lo, hi, compare, visit, node.right) + if(q[1]) { + g[count++] = q[1] } -} - - -__proto_80.forEach = function rbTreeForEach(visit, lo, hi) { - if(!this.root) { - return + if(count === 0) { + g[count++] = 0.0 } - switch(arguments.length) { - case 1: - return doVisitFull(visit, this.root) - break + g.length = count + return g +} +"use strict" - case 2: - return doVisitHalf(lo, this._compare, visit, this.root) - break +var _$robustSubtract_246 = robustSubtract - case 3: - if(this._compare(lo, hi) >= 0) { - return - } - return doVisit(lo, hi, this._compare, visit, this.root) - break +//Easy case: Add two scalars +function scalarScalar(a, b) { + var x = a + b + var bv = x - a + var av = x - bv + var br = b - bv + var ar = a - av + var y = ar + br + if(y) { + return [y, x] } + return [x] } -//First item in list -Object.defineProperty(__proto_80, "begin", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.left - } - return new RedBlackTreeIterator(this, stack) +function robustSubtract(e, f) { + var ne = e.length|0 + var nf = f.length|0 + if(ne === 1 && nf === 1) { + return scalarScalar(e[0], -f[0]) } -}) - -//Last item in list -Object.defineProperty(__proto_80, "end", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.right + var n = ne + nf + var g = new Array(n) + var count = 0 + var eptr = 0 + var fptr = 0 + var abs = Math.abs + var ei = e[eptr] + var ea = abs(ei) + var fi = -f[fptr] + var fa = abs(fi) + var a, b + if(ea < fa) { + b = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + b = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) } - return new RedBlackTreeIterator(this, stack) - } -}) - -//Find the ith item in the tree -__proto_80.at = function(idx) { - if(idx < 0) { - return new RedBlackTreeIterator(this, []) } - var n = this.root - var stack = [] - while(true) { - stack.push(n) - if(n.left) { - if(idx < n.left._count) { - n = n.left - continue - } - idx -= n.left._count + if((eptr < ne && ea < fa) || (fptr >= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) } - if(!idx) { - return new RedBlackTreeIterator(this, stack) + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) } - idx -= 1 - if(n.right) { - if(idx >= n.right._count) { - break + } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) } - n = n.right } else { - break + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x } - return new RedBlackTreeIterator(this, []) -} - -__proto_80.ge = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d <= 0) { - last_ptr = stack.length + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y } - if(d <= 0) { - n = n.left - } else { - n = n.right + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] } } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g } +"use strict" -__proto_80.gt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d < 0) { - last_ptr = stack.length - } - if(d < 0) { - n = n.left - } else { - n = n.right - } +var _$linearExpansionSum_247 = linearExpansionSum + +//Easy case: Add two scalars +function __scalarScalar_247(a, b) { + var x = a + b + var bv = x - a + var av = x - bv + var br = b - bv + var ar = a - av + var y = ar + br + if(y) { + return [y, x] } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + return [x] } -__proto_80.lt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d > 0) { - last_ptr = stack.length +function linearExpansionSum(e, f) { + var ne = e.length|0 + var nf = f.length|0 + if(ne === 1 && nf === 1) { + return __scalarScalar_247(e[0], f[0]) + } + var n = ne + nf + var g = new Array(n) + var count = 0 + var eptr = 0 + var fptr = 0 + var abs = Math.abs + var ei = e[eptr] + var ea = abs(ei) + var fi = f[fptr] + var fa = abs(fi) + var a, b + if(ea < fa) { + b = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) } - if(d <= 0) { - n = n.left - } else { - n = n.right + } else { + b = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) } } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} - -__proto_80.le = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d >= 0) { - last_ptr = stack.length + if((eptr < ne && ea < fa) || (fptr >= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) } - if(d < 0) { - n = n.left + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } + } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } } else { - n = n.right + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } + } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g } +var _$inSphere_241 = {}; +"use strict" -//Finds the item with key if it exists -__proto_80.find = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d === 0) { - return new RedBlackTreeIterator(this, stack) +/* removed: var _$twoProduct_267 = require("two-product") */; +/* removed: var _$linearExpansionSum_247 = require("robust-sum") */; +/* removed: var _$robustSubtract_246 = require("robust-subtract") */; +/* removed: var _$scaleLinearExpansion_244 = require("robust-scale") */; + +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("") } - return this } -//Returns the item at `key` -__proto_80.get = function(key) { - var cmp = this._compare - var n = this.root - while(n) { - var d = cmp(key, n.key) - if(d === 0) { - return n.value - } - if(d <= 0) { - n = n.left +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 { - n = n.right + return ["prod(", a, ",", b, ")"].join("") } + } else { + return makeProduct(b, a) } - return } -//Iterator for red black tree -function RedBlackTreeIterator(tree, stack) { - this.tree = tree - this._stack = stack +function sign(s) { + if(s & 1 !== 0) { + return "-" + } + return "" } -var iproto = RedBlackTreeIterator.prototype +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 0 +function makeSquare(d, n) { + var terms = [] + for(var i=0; i 0) { - return this._stack[this._stack.length-1] +function orientation(n) { + var pos = [] + var neg = [] + var m = matrix(n) + for(var i=0; i=0; --i) { - n = stack[i] - if(i === 0) { - n._color = BLACK - return - } - //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) - p = stack[i-1] - if(p.left === n) { - //console.log("left child") - s = p.right - if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.right = cloneNode(s) - z = s.right = cloneNode(s.right) - p.right = s.left - s.left = p - s.right = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - return - } else if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red") - s = p.right = cloneNode(s) - z = s.left = cloneNode(s.left) - p.right = z.left - s.left = z.right - z.left = p - z.right = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = z - } else { - pp.right = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent", p.right.value) - p._color = BLACK - p.right = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent", p.right.value) - p.right = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.right = s.left - s.left = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } else { - //console.log("right child") - s = p.left - if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red", p.value, p._color) - s = p.left = cloneNode(s) - z = s.left = cloneNode(s.left) - p.left = s.right - s.right = p - s.left = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - return - } else if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.left = cloneNode(s) - z = s.right = cloneNode(s.right) - p.left = z.right - s.right = z.left - z.right = p - z.left = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = z - } else { - pp.left = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent") - p._color = BLACK - p.left = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent") - p.left = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.left = s.right - s.right = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } +function generateInSphereTest() { + while(CACHED.length <= NUM_EXPAND) { + CACHED.push(orientation(CACHED.length)) } -} - -//Removes item at iterator from tree -iproto.remove = function() { - var stack = this._stack - if(stack.length === 0) { - return this.tree + var args = [] + var procArgs = ["slow"] + for(var i=0; i<=NUM_EXPAND; ++i) { + args.push("a" + i) + procArgs.push("o" + i) } - //First copy path to node - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - var n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } + var code = [ + "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" + ] + for(var i=2; i<=NUM_EXPAND; ++i) { + code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") } + code.push("}var s=new Array(arguments.length);for(var i=0;i=split; --i) { - n = cstack[i] - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - cstack[split-1].left = cstack[split] +var inCircle = _$inSphere_241[4] +/* removed: var _$searchBounds_53 = require('binary-search-bounds') */; + +var _$delaunayRefine_49 = delaunayRefine + +function testFlip(points, triangulation, stack, a, b, x) { + var y = triangulation.opposite(a, b) + + //Test boundary edge + if(y < 0) { + return } - //console.log("stack=", cstack.map(function(v) { return v.value })) - //Remove leaf node - n = cstack[cstack.length-1] - if(n._color === RED) { - //Easy case: removing red leaf - //console.log("RED leaf") - var p = cstack[cstack.length-2] - if(p.left === n) { - p.left = null - } else if(p.right === n) { - p.right = null - } - cstack.pop() - for(var i=0; i 0) { - return this._stack[this._stack.length-1].key - } + //Test if edge is constrained + if(triangulation.isConstraint(a, b)) { return - }, - enumerable: true -}) + } -//Returns value -Object.defineProperty(iproto, "value", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].value - } - return - }, - enumerable: true -}) + //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 = [] -//Returns the position of this iterator in the sorted list -Object.defineProperty(iproto, "index", { - get: function() { - var idx = 0 - var stack = this._stack - if(stack.length === 0) { - var r = this.tree.root - if(r) { - return r._count + var numPoints = points.length + var stars = triangulation.stars + for(var a=0; a=0; --s) { - if(stack[s+1] === stack[s].right) { - ++idx - if(stack[s].left) { - idx += stack[s].left._count + + //Check if edge is constrained + if(triangulation.isConstraint(a, b)) { + continue + } + + //Find opposite edge + var x = star[j-1], y = -1 + for(var k=1; k 0 && stack[stack.length-1].right === n) { - n = stack[stack.length-1] - stack.pop() - } - } -} + //If this is a boundary edge, don't flip it + if(y < 0) { + continue + } -//Checks if iterator is at end of tree -Object.defineProperty(iproto, "hasNext", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].right) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].left === stack[s]) { - return true + //If edge is in circle, flip it + if(inCircle(points[a], points[b], points[x], points[y]) < 0) { + stack.push(a, b) } } - return false } -}) -//Update value -iproto.update = function(value) { - var stack = this._stack - if(stack.length === 0) { - throw new Error("Can't update empty node!") - } - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + while(stack.length > 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 && stack[stack.length-1].left === n) { - n = stack[stack.length-1] - stack.pop() + + //If edge is now delaunay, then don't flip it + if(inCircle(points[a], points[b], points[x], points[y]) >= 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) } } -//Checks if iterator is at start of tree -Object.defineProperty(iproto, "hasPrev", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].left) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].right === stack[s]) { - return true - } - } - return false - } -}) +'use strict' -//Default comparison function -function defaultCompare(a, b) { - if(a < b) { - return -1 - } - if(a > b) { - return 1 - } - return 0 -} +/* removed: var _$searchBounds_53 = require('binary-search-bounds') */; -//Build a tree -function createRBTree(compare) { - return new RedBlackTree(compare || defaultCompare, null) +var _$classifyFaces_50 = classifyFaces + +function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) { + this.cells = cells + this.neighbor = neighbor + this.flags = flags + this.constraint = constraint + this.active = active + this.next = next + this.boundary = boundary } -"use strict" -var _$orderSegments_189 = orderSegments +var __proto_50 = FaceIndex.prototype -/* removed: var _$orientation_178 = require("robust-orientation") */; +function compareCell(a, b) { + return a[0] - b[0] || + a[1] - b[1] || + a[2] - b[2] +} -function horizontalOrder(a, b) { - var bl, br - if(b[0][0] < b[1][0]) { - bl = b[0] - br = b[1] - } else if(b[0][0] > b[1][0]) { - bl = b[1] - br = b[0] - } else { - var alo = Math.min(a[0][1], a[1][1]) - var ahi = Math.max(a[0][1], a[1][1]) - var blo = Math.min(b[0][1], b[1][1]) - var bhi = Math.max(b[0][1], b[1][1]) - if(ahi < blo) { - return ahi - blo +__proto_50.locate = (function() { + var key = [0,0,0] + return function(a, b, c) { + var x = a, y = b, z = c + if(b < c) { + if(b < a) { + x = b + y = c + z = a + } + } else if(c < a) { + x = c + y = a + z = b } - if(alo > bhi) { - return alo - bhi + if(x < 0) { + return -1 } - return ahi - bhi - } - var al, ar - if(a[0][1] < a[1][1]) { - al = a[0] - ar = a[1] - } else { - al = a[1] - ar = a[0] - } - var d = _$orientation_178(br, bl, al) - if(d) { - return d - } - d = _$orientation_178(br, bl, ar) - if(d) { - return d + key[0] = x + key[1] = y + key[2] = z + return _$searchBounds_53.eq(this.cells, key, compareCell) } - return ar - br -} +})() -function orderSegments(b, a) { - var al, ar - if(a[0][0] < a[1][0]) { - al = a[0] - ar = a[1] - } else if(a[0][0] > a[1][0]) { - al = a[1] - ar = a[0] - } else { - return horizontalOrder(a, b) +function indexCells(triangulation, infinity) { + //First get cells and canonicalize + var cells = triangulation.cells() + var nc = cells.length + for(var i=0; i b[1][0]) { - bl = b[1] - br = b[0] - } else { - return -horizontalOrder(b, a) + cells.sort(compareCell) + + //Initialize flag array + var flags = new Array(nc) + for(var i=0; i 0) { - if(d2 >= 0) { - return d1 - } - } else if(d2) { - return d2 + + //Build neighbor index, initialize queues + var active = [] + var next = [] + var neighbor = new Array(3*nc) + var constraint = new Array(3*nc) + var boundary = null + if(infinity) { + boundary = [] } - d1 = _$orientation_178(br, bl, ar) - d2 = _$orientation_178(br, bl, al) - if(d1 < 0) { - if(d2 <= 0) { - return d1 - } - } else if(d1 > 0) { - if(d2 >= 0) { - return d1 + var index = new FaceIndex( + cells, + neighbor, + constraint, + flags, + active, + next, + boundary) + for(var i=0; i 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 - } + if(target === 0) { + if(infinity) { + return index.cells.concat(index.boundary) } else { - if(p[0] !== seg[1][0]) { - return root - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } + return index.cells } } - return lastNode -} -__proto_190.castUp = function(p) { - var bucket = _$searchBounds_34.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_189(otherHitNode.key, lastSegment) > 0) { - lastSegment = otherHitNode.key - lastHit = otherHitNode.value - } - } else { - lastHit = otherHitNode.value - lastSegment = otherHitNode.key - } + var side = 1 + var active = index.active + var next = index.next + var flags = index.flags + var cells = index.cells + var constraint = index.constraint + var neighbor = index.neighbor + + while(active.length > 0 || next.length > 0) { + while(active.length > 0) { + var t = active.pop() + if(flags[t] === -side) { + continue } - } - var horiz = this.horizontal[bucket] - if(horiz.length > 0) { - var hbucket = _$searchBounds_34.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 = _$orientation_178(lastSegment[0], lastSegment[1], [p[0], e.y]) - if(lastSegment[0][0] > lastSegment[1][0]) { - o = -o - } - if(o > 0) { - lastHit = e.index - } + flags[t] = side + var c = cells[t] + for(var j=0; j<3; ++j) { + var f = neighbor[3*t+j] + if(f >= 0 && flags[f] === 0) { + if(constraint[3*t+j]) { + next.push(f) } else { - lastHit = e.index + active.push(f) + flags[f] = side } - } else if(e.y !== p[1]) { - lastHit = e.index } } } + + //Swap arrays and loop + var tmp = next + next = active + active = tmp + next.length = 0 + side = -side } - return lastHit -} -function IntervalSegment(y, index, start, closed) { - this.y = y - this.index = index - this.start = start - this.closed = closed + var result = filterCells(cells, flags, target) + if(infinity) { + return result.concat(index.boundary) + } + return result } -function __Event_190(x, segment, create, index) { - this.x = x - this.segment = segment - this.create = create - this.index = index -} +var _$orientation_242 = {}; +"use strict" +/* removed: var _$twoProduct_267 = require("two-product") */; +/* removed: var _$linearExpansionSum_247 = require("robust-sum") */; +/* removed: var _$scaleLinearExpansion_244 = require("robust-scale") */; +/* removed: var _$robustSubtract_246 = require("robust-subtract") */; -function createSlabDecomposition(segments) { - var numSegments = segments.length - var numEvents = 2 * numSegments - var events = new Array(numEvents) - for(var i=0; i>1 + return ["sum(", __generateSum_242(expr.slice(0, m)), ",", __generateSum_242(expr.slice(m)), ")"].join("") + } } -function intervalSearch(table) { - return function(x, y) { - var tree = table[x] - if(tree) { - return !!tree.queryPoint(y, visitInterval) +function __determinant_242(m) { + if(m.length === 2) { + return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] + } else { + var expr = [] + for(var i=0; i 0 && coordinates[bucket] === p[0]) { - root = slabs[bucket-1] +var orientation3Exact = __orientation_242(3) +var orientation4Exact = __orientation_242(4) + +var __CACHED_242 = [ + function orientation0() { return 0 }, + function orientation1() { return 0 }, + function orientation2(a, b) { + return b[0] - a[0] + }, + function orientation3(a, b, c) { + var l = (a[1] - c[1]) * (b[0] - c[0]) + var r = (a[0] - c[0]) * (b[1] - c[1]) + var det = l - r + var s + if(l > 0) { + if(r <= 0) { + return det } else { - return 1 + s = l + r } - } - var lastOrientation = 1 - while(root) { - var s = root.key - var o = __orient_157(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(l < 0) { + if(r >= 0) { + return det } else { - if(o > 0) { - root = root.left - } else if(o < 0) { - lastOrientation = 1 - root = root.right - } else { - return 0 - } + s = -(l + r) } + } else { + return det } - return lastOrientation + var tol = ERRBOUND3 * s + if(det >= tol || det <= -tol) { + return det + } + return orientation3Exact(a, b, c) + }, + function orientation4(a,b,c,d) { + var adx = a[0] - d[0] + var bdx = b[0] - d[0] + var cdx = c[0] - d[0] + var ady = a[1] - d[1] + var bdy = b[1] - d[1] + var cdy = c[1] - d[1] + var adz = a[2] - d[2] + var bdz = b[2] - d[2] + var cdz = c[2] - d[2] + var bdxcdy = bdx * cdy + var cdxbdy = cdx * bdy + var cdxady = cdx * ady + var adxcdy = adx * cdy + var adxbdy = adx * bdy + var bdxady = bdx * ady + var det = adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady) + var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) + var tol = ERRBOUND4 * permanent + if ((det > tol) || (-det > tol)) { + return det + } + return orientation4Exact(a,b,c,d) } -} +] -function classifyEmpty(p) { - return 1 +function slowOrient(args) { + var proc = __CACHED_242[args.length] + if(!proc) { + proc = __CACHED_242[args.length] = __orientation_242(args.length) + } + return proc.apply(undefined, args) } -function createClassifyVertical(testVertical) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 - } - return 1 +function generateOrientationProc() { + while(__CACHED_242.length <= __NUM_EXPAND_242) { + __CACHED_242.push(__orientation_242(__CACHED_242.length)) } -} + var args = [] + var procArgs = ["slow"] + for(var i=0; i<=__NUM_EXPAND_242; ++i) { + args.push("a" + i) + procArgs.push("o" + i) + } + var code = [ + "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" + ] + for(var i=2; i<=__NUM_EXPAND_242; ++i) { + code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") + } + code.push("}var s=new Array(arguments.length);for(var i=0;i 1 && orient( + points[lowerIds[m-2]], + points[lowerIds[m-1]], + p) > 0) { + cells.push( + [lowerIds[m-1], + lowerIds[m-2], + idx]) + m -= 1 + } + lowerIds.length = m + lowerIds.push(idx) -function makeArray(length, fill) { - var result = new Array(length) - for(var i=0; i 1 && orient( + points[upperIds[m-2]], + points[upperIds[m-1]], + p) < 0) { + cells.push( + [upperIds[m-2], + upperIds[m-1], + idx]) + m -= 1 + } + upperIds.length = m + upperIds.push(idx) } - return result } -function makeArrayOfArrays(length) { - var result = new Array(length) - for(var i=0; i 0 - } +function monotoneTriangulate(points, edges) { - //Extract all clockwise faces - faces = faces.filter(ccw) + var numPoints = points.length + var numEdges = edges.length - //Detect which loops are contained in one another to handle parent-of relation - var numFaces = faces.length - var parent = new Array(numFaces) - var containment = new Array(numFaces) - for(var i=0; i b[0]) { + events.push( + new Event(b, a, EVENT_START, i), + new Event(a, b, EVENT_END, i)) } } - function sharedBoundary(c) { - var n = c.length - for(var i=0; i 0) { - var top = toVisit.pop() - var nbhd = fadj[top] - _$unique_209(nbhd, function(a,b) { - return a-b - }) - var nnbhr = nbhd.length - var p = parity[top] - var polyline - if(p === 0) { - var c = faces[top] - polyline = [c] - } - for(var i=0; i= 0) { - continue - } - parity[f] = p^1 - toVisit.push(f) - if(p === 0) { - var c = faces[f] - if(!sharedBoundary(c)) { - c.reverse() - polyline.push(c) - } - } - } - if(p === 0) { - result.push(polyline) + //Process events in order + var cells = [] + for(var i=0, numEvents=events.length; i 0) - (v < 0); +function Triangulation(stars, edges) { + this.stars = stars + this.edges = edges } -//Computes absolute value of integer -_$twiddle_185.abs = function(v) { - var mask = v >> (__INT_BITS_185-1); - return (v ^ mask) - mask; -} +var __proto_52 = Triangulation.prototype -//Computes minimum of integers x and y -_$twiddle_185.min = function(x, y) { - return y ^ ((x ^ y) & -(x < y)); +function removePair(list, j, k) { + for(var i=1, n=list.length; i= 0 + } +})() + +__proto_52.removeTriangle = function(i, j, k) { + var stars = this.stars + removePair(stars[i], j, k) + removePair(stars[j], k, i) + removePair(stars[k], i, j) } -//Checks if a number is a power of two -_$twiddle_185.isPow2 = function(v) { - return !(v & (v-1)) && (!!v); +__proto_52.addTriangle = function(i, j, k) { + var stars = this.stars + stars[i].push(j, k) + stars[j].push(k, i) + stars[k].push(i, j) } -//Computes log base 2 of v -_$twiddle_185.log2 = function(v) { - var r, shift; - r = (v > 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); -} - -//Computes log base 10 of v -_$twiddle_185.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} - -//Counts number of bits -_$twiddle_185.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; -} - -//Counts number of trailing zeros -function __countTrailingZeros_185(v) { - var c = 32; - v &= -v; - if (v) c--; - if (v & 0x0000FFFF) c -= 16; - if (v & 0x00FF00FF) c -= 8; - if (v & 0x0F0F0F0F) c -= 4; - if (v & 0x33333333) c -= 2; - if (v & 0x55555555) c -= 1; - return c; -} -_$twiddle_185.countTrailingZeros = __countTrailingZeros_185; - -//Rounds to next power of 2 -_$twiddle_185.nextPow2 = function(v) { - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; +__proto_52.opposite = function(j, i) { + var list = this.stars[i] + for(var k=1, n=list.length; k>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); +__proto_52.flip = function(i, j) { + var a = this.opposite(i, j) + var b = this.opposite(j, i) + this.removeTriangle(i, j, a) + this.removeTriangle(j, i, b) + this.addTriangle(i, b, a) + this.addTriangle(j, a, b) } -//Computes parity of word -_$twiddle_185.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; +__proto_52.edges = function() { + var stars = this.stars + var result = [] + for(var i=0, n=stars.length; i>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; +__proto_52.cells = function() { + var stars = this.stars + var result = [] + for(var i=0, n=stars.length; i>> 8) & 0xff] << 16) | - (__REVERSE_TABLE_185[(v >>> 16) & 0xff] << 8) | - __REVERSE_TABLE_185[(v >>> 24) & 0xff]; +function createTriangulation(numVerts, edges) { + var stars = new Array(numVerts) + for(var i=0; i>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; +function canonicalizeEdge(e) { + return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] } - -//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -_$twiddle_185.interleave3 = function(x, y, z) { - x &= 0x3FF; - x = (x | (x<<16)) & 4278190335; - x = (x | (x<<8)) & 251719695; - x = (x | (x<<4)) & 3272356035; - x = (x | (x<<2)) & 1227133513; - - y &= 0x3FF; - y = (y | (y<<16)) & 4278190335; - y = (y | (y<<8)) & 251719695; - y = (y | (y<<4)) & 3272356035; - y = (y | (y<<2)) & 1227133513; - x |= (y << 1); - - z &= 0x3FF; - z = (z | (z<<16)) & 4278190335; - z = (z | (z<<8)) & 251719695; - z = (z | (z<<4)) & 3272356035; - z = (z | (z<<2)) & 1227133513; - - return x | (z << 2); +function compareEdge(a, b) { + return a[0]-b[0] || a[1]-b[1] } -//Extracts nth interleaved component of a 3-tuple -_$twiddle_185.deinterleave3 = function(v, n) { - v = (v >>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; +function canonicalizeEdges(edges) { + return edges.map(canonicalizeEdge).sort(compareEdge) } -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -_$twiddle_185.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (__countTrailingZeros_185(v) + 1)); +function getDefault(options, property, dflt) { + if(property in options) { + return options[property] + } + return dflt } +function cdt2d(points, edges, options) { -"use strict"; "use restrict"; + if(!Array.isArray(edges)) { + options = edges || {} + edges = [] + } else { + options = options || {} + edges = edges || [] + } -var _$UnionFind_187 = __UnionFind_187; + //Parse out options + var delaunay = !!getDefault(options, 'delaunay', true) + var interior = !!getDefault(options, 'interior', true) + var exterior = !!getDefault(options, 'exterior', true) + var infinity = !!getDefault(options, 'infinity', false) -function __UnionFind_187(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; 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 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); } - } - return r -} -_$topology_186.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 - } - } + if (typeof number === 'object') { + return this._initArray(number, base, endian); } - } - return index -} -_$topology_186.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_186(skeleton(cells, 0)), cells, 0) - } - var res = new Array(vertex_count) - for(var i=0; i= 2 && base <= 36); -//Enumerates all cells in the complex -function explode(cells) { - var result = [] - for(var i=0, il=cells.length; i>> k) & 1) { - b.push(c[k]) - } - } - result.push(b) + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') { + start++; } - } - return normalize(result) -} -_$topology_186.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> 1 + 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; } - return (i >> 1) - 1 - } - //Bubble element i down the heap - function heapDown(i) { - var w = heapWeight(i) - while(true) { - var tw = w - var left = 2*i + 1 - var right = 2*(i + 1) - var next = i - if(left < heapCount) { - var lw = heapWeight(left) - if(lw < tw) { - next = left - tw = lw + 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++; } } - if(right < heapCount) { - var rw = heapWeight(right) - if(rw < tw) { - next = right + } 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++; } } - if(next === i) { - return i - } - heapSwap(i, next) - i = next } - } + return this.strip(); + }; - //Bubbles element i up the heap - function heapUp(i) { - var w = heapWeight(i) - while(i > 0) { - var parent = heapParent(i) - if(parent >= 0) { - var pw = heapWeight(parent) - if(w < pw) { - heapSwap(i, parent) - i = parent - continue - } - } - return i - } - } + 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; - //Pop minimum element - function heapPop() { - if(heapCount > 0) { - var head = heap[0] - heapSwap(0, heapCount-1) - heapCount -= 1 - heapDown(0) - return head - } - return -1 - } + r <<= 4; - //Update heap item i - function heapUpdate(i, w) { - var a = heap[i] - if(weights[a] === w) { - return i + // '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; + } } - weights[a] = -Infinity - heapUp(i) - heapPop() - weights[a] = w - heapCount += 1 - return heapUp(heapCount-1) + return r; } - //Kills a vertex (assume vertex already removed from heap) - function kill(i) { - if(dead[i]) { - return - } - //Kill vertex - dead[i] = true - //Fixup topology - var s = inv[i] - var t = outv[i] - if(inv[t] >= 0) { - inv[t] = s - } - if(outv[s] >= 0) { - outv[s] = t + 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; } - //Update weights on s and t - if(index[s] >= 0) { - heapUpdate(index[s], computeWeight(s)) + 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(index[t] >= 0) { - heapUpdate(index[t], computeWeight(t)) + 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(); + }; - //Initialize weights and heap - var heap = [] - var index = new Array(n) - for(var i=0; i>1; i>=0; --i) { - heapDown(i) - } - - //Kill vertices - while(true) { - var hmin = heapPop() - if((hmin < 0) || (weights[hmin] > minArea)) { - break - } - kill(hmin) - } + 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; - //Build collapsed vertex table - var npositions = [] - for(var i=0; i= 49) { + r += c - 49 + 0xa; + + // 'A' + } else if (c >= 17) { + r += c - 17 + 0xa; + + // '0' - '9' + } else { + r += c; + } } + return r; } - var nv = npositions.length - function tortoiseHare(seq, start) { - if(seq[start] < 0) { - return start - } - var t = start - var h = start - do { - //Walk two steps with h - var nh = seq[h] - if(!dead[h] || nh < 0 || nh === h) { - break - } - h = nh - nh = seq[h] - if(!dead[h] || nh < 0 || nh === h) { - break - } - h = nh + BN.prototype._parseBase = function _parseBase (number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - //Walk one step with t - t = seq[t] - } while(t !== h) - //Compress cycles - for(var v=start; v!==h; v = seq[v]) { - seq[v] = h + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { + limbLen++; } - return h - } + limbLen--; + limbPow = (limbPow / base) | 0; - var ncells = [] - cells.forEach(function(c) { - var tin = tortoiseHare(inv, c[0]) - var tout = tortoiseHare(outv, c[1]) - if(tin >= 0 && tout >= 0 && tin !== tout) { - var cin = index[tin] - var cout = index[tout] - if(cin !== cout) { - ncells.push([ cin, cout ]) + 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); } } - }) - //Normalize result - _$topology_186.unique(_$topology_186.normalize(ncells)) + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); - //Return final list of cells - return { - positions: npositions, - edges: ncells - } -} -"use strict" + for (i = 0; i < mod; i++) { + pow *= base; + } -/* removed: var _$pool_207 = require("typedarray-pool") */; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + }; -var _$createSurfaceExtractor_141 = createSurfaceExtractor + 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; + }; -//Helper macros -function array(i) { - return "a" + i -} -function data(i) { - return "d" + i -} -function cube(i,bitmask) { - return "c" + i + "_" + bitmask -} -function shape(i) { - return "s" + i -} -function stride(i,j) { - return "t" + i + "_" + j -} -function offset(i) { - return "o" + i -} -function scalar(i) { - return "x" + i -} -function pointer(i) { - return "p" + i -} -function delta(i,bitmask) { - return "d" + i + "_" + bitmask -} -function index(i) { - return "i" + i -} -function step(i,j) { - return "u" + i + "_" + j -} -function pcube(bitmask) { - return "b" + bitmask -} -function qcube(bitmask) { - return "y" + bitmask -} -function pdelta(bitmask) { - return "e" + bitmask -} -function vert(i) { - return "v" + i -} -var VERTEX_IDS = "V" -var PHASES = "P" -var VERTEX_COUNT = "N" -var POOL_SIZE = "Q" -var POINTER = "X" -var TEMPORARY = "T" + BN.prototype.clone = function clone () { + var r = new BN(null); + this.copy(r); + return r; + }; -function permBitmask(dimension, mask, order) { - var r = 0 - for(var i=0; i 1 && this.words[this.length - 1] === 0) { + this.length--; + } + return this._normSign(); + }; - if(dimension < 2) { - throw new Error("ndarray-extract-contour: Dimension must be at least 2") - } + BN.prototype._normSign = function _normSign () { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; - var funcName = "extractContour" + order.join("_") - var code = [] - var vars = [] - var args = [] + BN.prototype.inspect = function inspect () { + return (this.red ? ''; + }; - //Assemble arguments - for(var i=0; i>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + off += 2; + if (off >= 26) { + off -= 26; + i--; } } - vars.push(delta(i,j) + "=(" + ptrStr.join("") + ")|0") - vars.push(cube(i,j) + "=0") - } - } - //Create step variables - for(var i=0; i 0) { - stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) + if (carry !== 0) { + out = carry.toString(16) + out; } - vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; } - } - //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<= 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 { - cubeDelta.unshift(cubeStep.join("*")) + out = r + out; } } - cubeStep.push(shape(order[k])) + if (this.isZero()) { + out = '0' + out; + } + while (out.length % padding !== 0) { + out = '0' + out; + } + if (this.negative !== 0) { + out = '-' + out; + } + return out; } - var signFlag = "" - if(cubeDelta[0].indexOf(shape(order[dimension-2])) < 0) { - signFlag = "-" + + 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'); } - var jperm = permBitmask(dimension, j, order) - vars.push(pdelta(jperm) + "=(-" + cubeDelta.join("-") + ")|0", - qcube(jperm) + "=(" + signFlag + cubeDelta.join("-") + ")|0", - pcube(jperm) + "=0") - } - vars.push(vert(0) + "=0", TEMPORARY + "=0") + return (this.negative !== 0) ? -ret : ret; + }; - function forLoopBegin(i, start) { - code.push("for(", index(order[i]), "=", start, ";", - index(order[i]), "<", shape(order[i]), ";", - "++", index(order[i]), "){") - } + BN.prototype.toJSON = function toJSON () { + return this.toString(16); + }; - function forLoopEnd(i) { - for(var j=0; j 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; + } } - code.push("}") + + 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; + }; } - function fillEmptySlice(k) { - for(var i=k-1; i>=0; --i) { - forLoopBegin(i, 0) + 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; } - var phaseFuncArgs = [] - for(var i=0; i>>= 7; } - for(var i=0; i>>= 4; } - code.push(PHASES, "[", POINTER, "++]=phase(", phaseFuncArgs.join(), ");") - for(var i=0; i>>= 2; } - for(var j=0; j>> wbit; } - //Read in phase - var phaseFuncArgs = [] - for(var i=0; i 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; i0; k=(k-1)&subset) { - faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") - } - faceArgs.push(vert(0)) - for(var k=0; k 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; } - - //Increment pointer, close off if statement - code.push("}", - POINTER, "+=1;") - } - function flip() { - for(var j=1; j<(1<0){", - index(order[i]), "=1;") - createLoop(i-1, mask|(1< 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--; } - if(i === dimension-1) { - code.push(POINTER, "=0;") - flip() + + // Handle complete words + for (var i = 0; i < bytesNeeded; i++) { + this.words[i] = ~this.words[i] & 0x3ffffff; } - forLoopBegin(i, 2) - createLoop(i-1, mask) - if(i === dimension-1) { - code.push("if(", index(order[dimension-1]), "&1){", - POINTER, "=0;}") - flip() + + // Handle the residue + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } - forLoopEnd(i) - code.push("}") - } - createLoop(dimension-1, 0) + // And remove leading zeroes + return this.strip(); + }; - //Release scratch memory - code.push("freeUint32(", VERTEX_IDS, ");freeUint32(", PHASES, ");") + BN.prototype.notn = function notn (width) { + return this.clone().inotn(width); + }; - //Compile and link procedure - var procedureCode = [ - "'use strict';", - "function ", funcName, "(", args.join(), "){", - "var ", vars.join(), ";", - code.join(""), - "}", - "return ", funcName ].join("") + // Set `bit` of `this` + BN.prototype.setn = function setn (bit, val) { + assert(typeof bit === 'number' && bit >= 0); - var proc = new Function( - "vertex", - "face", - "phase", - "mallocUint32", - "freeUint32", - procedureCode) - return proc( - vertexFunc, - faceFunc, - phaseFunc, - _$pool_207.mallocUint32, - _$pool_207.freeUint32) -} + var off = (bit / 26) | 0; + var wbit = bit % 26; -function createSurfaceExtractor(args) { - function error(msg) { - throw new Error("ndarray-extract-contour: " + msg) - } - if(typeof args !== "object") { - error("Must specify arguments") - } - var order = args.order - if(!Array.isArray(order)) { - error("Must specify order") - } - var arrays = args.arrayArguments||1 - if(arrays < 1) { - error("Must have at least one array argument") - } - var scalars = args.scalarArguments||0 - if(scalars < 0) { - error("Scalar arg count must be > 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 + this._expand(off + 1); + + if (val) { + this.words[off] = this.words[off] | (1 << wbit); } else { - typesig[i] = false + this.words[off] = this.words[off] & ~(1 << wbit); } - } - return compileSurfaceProcedure( - args.vertex, - args.cell, - args.phase, - scalars, - order, - typesig) -} -var _$gamma_81 = {}; -// 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 -]; + return this.strip(); + }; -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 -]; + // Add `num` to `this` in-place + BN.prototype.iadd = function iadd (num) { + var r; -// Spouge approximation (suitable for large arguments) -function lngamma(z) { + // negative + positive + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); - 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); -} + // positive + negative + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } -_$gamma_81 = function gamma (z) { - if (z < 0.5) { - return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); + // a.length > b.length + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - 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 - ; + 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]; + } } -}; -_$gamma_81.log = lngamma; + return this; + }; -"use strict" + // 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; + } -var _$permutationSign_151 = permutationSign + if (this.length > num.length) return this.clone().iadd(num); -var __BRUTE_FORCE_CUTOFF_151 = 32 + return num.clone().iadd(this); + }; -/* removed: var _$pool_207 = require("typedarray-pool") */; + // 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(); -function permutationSign(p) { - var n = p.length - if(n < __BRUTE_FORCE_CUTOFF_151) { - //Use quadratic algorithm for small n - var sgn = 1 - for(var i=0; i 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]; } } - _$pool_207.freeUint8(visited) - return sgn - } -} -"use strict" -function invertPermutation(pi, result) { - result = result || new Array(pi.length) - for(var 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_207.freeUint32(pinv) - _$pool_207.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 -} - -_$permutationRank_152.rank = rank -_$permutationRank_152.unrank = unrank - -"use strict" - -var _$triangulateCube_204 = triangulateCube - -/* removed: var _$permutationRank_152 = require("permutation-rank") */; -/* removed: var _$permutationSign_151 = require("permutation-parity") */; -/* removed: var _$gamma_81 = require("gamma") */; - -function triangulateCube(dimension) { - if(dimension < 0) { - return [ ] - } - if(dimension === 0) { - return [ [0] ] - } - var dfactorial = Math.round(_$gamma_81(dimension+1))|0 - var result = [] - for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", - "args": [{ - "name": "_inline_1_arg0_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg1_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg2_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg3_", - "lvalue": false, - "rvalue": true, - "count": 2 - }, { - "name": "_inline_1_arg4_", - "lvalue": false, - "rvalue": true, - "count": 1 - }], - "thisVars": [], - "localVars": ["_inline_1_da", "_inline_1_db"] - }, - funcName: 'zeroCrossings' -}) - -"use strict" - -var _$findZeroCrossings_221 = findZeroCrossings - -/* removed: var _$zcCore_220 = require("./lib/zc-core") */; - -function findZeroCrossings(array, level) { - var cross = [] - level = +level || 0.0 - _$zcCore_220(array.hi(array.shape[0]-1), cross, level) - return cross -} -"use strict" - -var _$surfaceNets_195 = surfaceNets + // Subtract `num` from `this` + BN.prototype.sub = function sub (num) { + return this.clone().isub(num); + }; -/* removed: var _$createSurfaceExtractor_141 = require("ndarray-extract-contour") */; -/* removed: var _$triangulateCube_204 = require("triangulate-hypercube") */; -/* removed: var _$findZeroCrossings_221 = require("zero-crossings") */; + 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; -function buildSurfaceNets(order, dtype) { - var dimension = order.length - var code = ["'use strict';"] - var funcName = "surfaceNets" + order.join("_") + "d" + dtype + // 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; - //Contour extraction function - code.push( - "var contour=genContour({", - "order:[", order.join(), "],", - "scalarArguments: 3,", - "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },") - if(dtype === "generic") { - code.push("getters:[0],") - } + var lo = r & 0x3ffffff; + var carry = (r / 0x4000000) | 0; + out.words[0] = lo; - //Generate vertex function - var cubeArgs = [] - var extraArgs = [] - for(var i=0; i>>7){") - } - for(var i=0; i<1<<(1< 128) { - if((i%128)===0) { - if(extraFuncs.length > 0) { - currentFunc.push("}}") - } - var efName = "vExtra" + extraFuncs.length - code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") - currentFunc = [ - "function ", efName, "(m,", extraArgs.join(), "){switch(m){" - ] - extraFuncs.push(currentFunc) - } - } - currentFunc.push("case ", (i&0x7f), ":") - var crossings = new Array(dimension) - var denoms = new Array(dimension) - var crossingCount = new Array(dimension) - var bias = new Array(dimension) - var totalCrossings = 0 - for(var j=0; j j) { - continue - } - if(!(i&(1< 0) { - cStr = "+" + crossingCount[k] + "*c" - } - var weight = 0.5 * (crossings[k].length / totalCrossings) - var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) - vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") - + 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; } - currentFunc.push("a.push([", vertexStr.join(), "]);", - "break;") - } - code.push("}},") - if(extraFuncs.length > 0) { - currentFunc.push("}}") - } - - //Create face function - var faceArgs = [] - for(var i=0; i<(1<<(dimension-1)); ++i) { - faceArgs.push("v" + i) - } - faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c") - code.push("cell:function cellFunc(", faceArgs.join(), "){") - - var facets = _$triangulateCube_204(dimension-1) - code.push("if(p0){b.push(", - facets.map(function(f) { - return "[" + f.map(function(v) { - return "v" + v - }) + "]" - }).join(), ")}else{b.push(", - facets.map(function(f) { - var e = f.slice() - e.reverse() - return "[" + e.map(function(v) { - return "v" + v - }) + "]" - }).join(), - ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";") - - for(var i=0; i>> 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; - var scale = 1.0 / size - if("lineHeight" in options) { - scale *= +options.lineHeight - } else if("width" in options) { - scale = options.width / (hi[0] - lo[0]) - } else if("height" in options) { - scale = options.height / (hi[1] - lo[1]) - } + 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; + }; - return positions.map(function(p) { - return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ] - }) -} - -function getPixels(canvas, context, str, size) { - var width = Math.ceil(context.measureText(str).width + 2*size)|0 - if(width > 8192) { - throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") - } - var height = 3 * size - if(canvas.height < height) { - canvas.height = height + // Polyfill comb + if (!Math.imul) { + comb10MulTo = smallMulTo; } - context.fillStyle = "#000" - context.fillRect(0, 0, canvas.width, canvas.height) + function bigMulTo (self, num, out) { + out.negative = num.negative ^ self.negative; + out.length = self.length + num.length; - context.fillStyle = "#fff" - context.fillText(str, size, 2*size) + 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; - //Cut pixels from image - var pixelData = context.getImageData(0, 0, width, height) - var pixels = _$wrappedNDArrayCtor_143(pixelData.data, [height, width, 4]) + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; - return pixels.pick(-1,-1,0).transpose(1,0) -} + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } -function getContour(pixels, doSimplify) { - var contour = _$surfaceNets_195(pixels, 128) - if(doSimplify) { - return _$simplifyPolygon_188(contour.cells, contour.positions, 0.25) + return out.strip(); } - return { - edges: contour.cells, - positions: contour.positions + + function jumboMulTo (self, num, out) { + var fftm = new FFTM(); + return fftm.mulp(self, num, out); } -} -function processPixelsImpl(pixels, options, size, simplify) { - //Extract contour - var contour = getContour(pixels, simplify) + 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); + } - //Apply warp to positions - var positions = transformPositions(contour.positions, options, size) - var edges = contour.edges - var flip = "ccw" === options.orientation + return res; + }; - //Clean up the PSLG, resolve self intersections, etc. - _$cleanPSLG_54(positions, edges) + // Cooley-Tukey algorithm for FFT + // slightly revisited to rely on looping instead of recursion - //If triangulate flag passed, triangulate the result - if(options.polygons || options.polygon || options.polyline) { - var result = _$planarGraphToPolyline_156(edges, positions) - var nresult = new Array(result.length) - for(var i=0; i>= 1; + } + + return rb; + }; + + // Performs "tweedling" phase, therefore 'emulating' + // behaviour of the recursive algorithm + FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { + for (var i = 0; i < 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; + } } - nloops[j] = nloop } - nresult[i] = nloops } - return nresult - } else if(options.triangles || options.triangulate || options.triangle) { - return { - cells: _$cdt2d_47(positions, edges, { - delaunay: false, - exterior: false, - interior: true - }), - positions: positions + }; + + 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++; } - } else { - return { - edges: edges, - positions: positions + + 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; } - } -} + }; -function processPixels(pixels, options, size) { - try { - return processPixelsImpl(pixels, options, size, true) - } catch(e) {} - try { - return processPixelsImpl(pixels, options, size, false) - } catch(e) {} - if(options.polygons || options.polyline || options.polygon) { - return [] - } - if(options.triangles || options.triangulate || options.triangle) { - return { - cells: [], - positions: [] + 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 { - edges: [], - positions: [] - } -} -function vectorizeText(str, canvas, context, options) { - var size = options.size || 64 - var family = options.font || "normal" + return ws; + }; - context.font = size + "px " + family - context.textAlign = "start" - context.textBaseline = "alphabetic" - context.direction = "ltr" + FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { + var carry = 0; + for (var i = 0; i < len; i++) { + carry = carry + (ws[i] | 0); - var pixels = getPixels(canvas, context, str, size) + rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; + rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; + } - return processPixels(pixels, options, size) -} + // Pad with zeroes + for (i = 2 * len; i < N; ++i) { + rws[i] = 0; + } -"use strict" + assert(carry === 0); + assert((carry & ~0x1fff) === 0); + }; -var _$createText_214 = createText + FFTM.prototype.stub = function stub (N) { + var ph = new Array(N); + for (var i = 0; i < N; i++) { + ph[i] = 0; + } -/* removed: var _$vtext_215 = require("./lib/vtext") */; -var defaultCanvas = null -var defaultContext = null + return ph; + }; -if(typeof document !== 'undefined') { - defaultCanvas = document.createElement('canvas') - defaultCanvas.width = 8192 - defaultCanvas.height = 1024 - defaultContext = defaultCanvas.getContext("2d") -} + FFTM.prototype.mulp = function mulp (x, y, out) { + var N = 2 * this.guessLen13b(x.length, y.length); -function createText(str, options) { - if((typeof options !== "object") || (options === null)) { - options = {} - } - return _$vtext_215( - str, - options.canvas || defaultCanvas, - options.context || defaultContext, - options) -} + var rbt = this.makeRBT(N); -var _$textGet_200 = {}; -(function (process){ -'use strict' + var _ = this.stub(N); -_$textGet_200 = textGet + var rws = new Array(N); + var rwst = new Array(N); + var iwst = new Array(N); -/* removed: var _$createText_214 = require('vectorize-text') */; + var nrws = new Array(N); + var nrwst = new Array(N); + var niwst = new Array(N); -var globals = window || process.global || {} -var __TEXT_CACHE = globals.__TEXT_CACHE || {} -globals.__TEXT_CACHE = {} + var rmws = out.words; + rmws.length = N; -function unwrap(mesh) { - var cells = mesh.cells - var positions = mesh.positions - var data = new Float32Array(cells.length * 6) - var ptr = 0 - var shapeX = 0 - for(var i=0; i0) { - shapeX += 0.02 - } - } + this.conjugate(rwst, iwst, N); + this.transform(rwst, iwst, rmws, _, N, rbt); + this.conjugate(rmws, _, N); + this.normalize13b(rmws, N); - var data = new Float32Array(bufferSize) - var ptr = 0 - var xOffset = -0.5 * shapeX - for(var i=0; i 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_99.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_99.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_99.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>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; + } -var linearTypes = null -var filterTypes = null -var wrapTypes = null + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } -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 - ] -} + return this; + }; -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)) -} + BN.prototype.muln = function muln (num) { + return this.clone().imuln(num); + }; -var convertFloatToUint8 = function(out, inp) { - _$ndarrayOps_142.muls(out, inp, 255.0) -} + // `this` * `this` + BN.prototype.sqr = function sqr () { + return this.mul(this); + }; -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 -} + // `this` * `this` in-place + BN.prototype.isqr = function isqr () { + return this.imul(this.clone()); + }; -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 + // Math.pow(`this`, `num`) + BN.prototype.pow = function pow (num) { + var w = toBitArray(num); + if (w.length === 0) return new BN(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 - } + // Skip leading zeroes + var res = this; + for (var i = 0; i < w.length; i++, res = res.sqr()) { + if (w[i] !== 0) break; } - ]) - 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 + 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); } } - ]) - this._shapeVector = shapeVector -} -var __proto_115 = Texture2D.prototype + return res; + }; -Object.defineProperties(__proto_115, { - 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 - } + // 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(filterTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown filter mode ' + v) + + if (carry) { + this.words[i] = carry; + this.length++; } - 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 (s !== 0) { + for (i = this.length - 1; i >= 0; i--) { + this.words[i + s] = this.words[i]; } - if(filterTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown filter mode ' + v) + + for (i = 0; i < s; i++) { + this.words[i] = 0; } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) - return this._magFilter = v + + this.length += s; } - }, - 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 + + 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; } - }, - 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) + + 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]; } - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v) - return this._wrapS = v + maskedWords.length = s; } - }, - 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) + + 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]; } - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v) - return this._wrapT = v + } else { + this.words[0] = 0; + this.length = 1; } - }, - 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) + 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; + } - return v + // Push carried bits as a mask + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; } - }, - 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] + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; } - }, - 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_115.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 -} + return this.strip(); + }; -__proto_115.dispose = function() { - this.gl.deleteTexture(this.handle) -} + BN.prototype.ishrn = function ishrn (bits, hint, extended) { + // TODO(indutny): implement me + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; -__proto_115.generateMipmap = function() { - this.bind() - this.gl.generateMipmap(this.gl.TEXTURE_2D) + // Shift-left + BN.prototype.shln = function shln (bits) { + return this.clone().ishln(bits); + }; - //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) + 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; } - } -} -__proto_115.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) + if (r !== 0) { + s++; } - } 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') + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; } - texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data) - } else { - throw new Error('gl-texture2d: Unsupported data type') - } -} + return this.strip(); + }; -function __isPacked_115(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]) -} + // Return only lowers bits of number + BN.prototype.maskn = function maskn (bits) { + return this.clone().imaskn(bits); + }; -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_115(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 = _$wrappedNDArrayCtor_143(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) + // 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; } - } 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)) + + 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 { - 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)) + this.words[i + 1]++; } } - } else { - //Need to do type conversion to pack data into buffer - var pack_buffer - if(ctype === gl.FLOAT) { - pack_buffer = _$pool_207.mallocFloat32(size) - } else { - pack_buffer = _$pool_207.mallocUint8(size) - } - var pack_view = _$wrappedNDArrayCtor_143(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) - if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { - convertFloatToUint8(pack_view, array) - } else { - _$ndarrayOps_142.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_207.freeFloat32(pack_buffer) - } else { - _$pool_207.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 -} + this.length = Math.max(this.length, i + 1); -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) -} + return this; + }; -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) -} + // 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); -//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_115(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 = _$wrappedNDArrayCtor_143(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') + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; } - } 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_207.malloc(size, dtype) - var buf_array = _$wrappedNDArrayCtor_143(buf_store, shape, stride, 0) - if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { - convertFloatToUint8(buf_array, array) + + this.words[0] -= num; + + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; } else { - _$ndarrayOps_142.assign(buf_array, array) + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } } - 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_207.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') -} + return this.strip(); + }; -'use strict' + BN.prototype.addn = function addn (num) { + return this.clone().iaddn(num); + }; -/* removed: var _$createTexture2D_115 = require('gl-texture2d') */; + BN.prototype.subn = function subn (num) { + return this.clone().isubn(num); + }; -var _$createFBO_89 = createFBO + BN.prototype.iabs = function iabs () { + this.negative = 0; -var colorAttachmentArrays = null -var FRAMEBUFFER_UNSUPPORTED -var FRAMEBUFFER_INCOMPLETE_ATTACHMENT -var FRAMEBUFFER_INCOMPLETE_DIMENSIONS -var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT + return this; + }; -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] -} + BN.prototype.abs = function abs () { + return this.clone().iabs(); + }; -function restoreFBOState(gl, data) { - gl.bindFramebuffer(gl.FRAMEBUFFER, data[0]) - gl.bindRenderbuffer(gl.RENDERBUFFER, data[1]) - gl.bindTexture(gl.TEXTURE_2D, data[2]) -} + BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { + var len = num.length + shift; + var i; -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> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; } - for(var j=i; j> 26; + this.words[i + shift] = w & 0x3ffffff; } - colorAttachmentArrays[i] = x - } -} -//Throw an appropriate error -function throwFBOError(status) { - switch(status){ - case FRAMEBUFFER_UNSUPPORTED: - throw new Error('gl-fbo: Framebuffer unsupported') - case FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - throw new Error('gl-fbo: Framebuffer incomplete attachment') - case FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - throw new Error('gl-fbo: Framebuffer incomplete dimensions') - case FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - throw new Error('gl-fbo: Framebuffer incomplete missing attachment') - default: - throw new Error('gl-fbo: Framebuffer failed for unspecified reason') - } -} + if (carry === 0) return this.strip(); -//Initialize a texture object -function __initTexture_89(gl, width, height, type, format, attachment) { - if(!type) { - return null - } - var result = _$createTexture2D_115(gl, width, height, format, type) - result.magFilter = gl.NEAREST - result.minFilter = gl.NEAREST - result.mipSamples = 1 - result.bind() - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, result.handle, 0) - return result -} + // 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; -//Initialize a render buffer object -function initRenderBuffer(gl, width, height, component, attachment) { - var result = gl.createRenderbuffer() - gl.bindRenderbuffer(gl.RENDERBUFFER, result) - gl.renderbufferStorage(gl.RENDERBUFFER, component, width, height) - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, result) - return result -} + return this.strip(); + }; -//Rebuild the frame buffer -function rebuildFBO(fbo) { + BN.prototype._wordDiv = function _wordDiv (num, mode) { + var shift = this.length - num.length; - //Save FBO state - var state = saveFBOState(fbo.gl) + var a = this.clone(); + var b = num; - var gl = fbo.gl - var handle = fbo.handle = gl.createFramebuffer() - var width = fbo._shape[0] - var height = fbo._shape[1] - var numColors = fbo.color.length - var ext = fbo._ext - var useStencil = fbo._useStencil - var useDepth = fbo._useDepth - var colorType = fbo._colorType + // 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; + } - //Bind the fbo - gl.bindFramebuffer(gl.FRAMEBUFFER, handle) + // Initialize quotient + var m = a.length - b.length; + var q; - //Allocate color buffers - for(var i=0; i 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_89(gl, width, height, - WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, - gl.DEPTH_STENCIL, - gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo.depth = __initTexture_89(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) + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } } - } - //Check frame buffer state - var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) - if(status !== gl.FRAMEBUFFER_COMPLETE) { + for (var j = m - 1; j >= 0; j--) { + var qj = (a.words[b.length + j] | 0) * 0x4000000 + + (a.words[b.length + j - 1] | 0); - //Release all partially allocated resources - fbo._destroyed = true + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); - //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') - } + return { + div: div, + mod: res.mod + }; + } - //Update shape - fbo._shape[0] = w - fbo._shape[1] = h + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); - //Save framebuffer state - var state = saveFBOState(gl) + if (mode !== 'div') { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } - //Resize framebuffer attachments - for(var i=0; i this.length || this.cmp(num) < 0) { + return { + div: new BN(0), + mod: this + }; + } -Object.defineProperties(__proto_89, { - 'shape': { - get: function() { - if(this._destroyed) { - return [0,0] - } - return this._shapeVector - }, - set: function(x) { - if(!Array.isArray(x)) { - x = [x|0, x|0] + // Very short reduction + if (num.length === 1) { + if (mode === 'div') { + return { + div: this.divn(num.words[0]), + mod: null + }; } - if(x.length !== 2) { - throw new Error('gl-fbo: Shape vector must be length 2') + + if (mode === 'mod') { + return { + div: null, + mod: new BN(this.modn(num.words[0])) + }; } - var w = x[0]|0 - var h = x[1]|0 - reshapeFBO(this, w, h) + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } - return [w, h] - }, - enumerable: false - }, - 'width': { - get: function() { - if(this._destroyed) { - return 0 - } - return this._shape[0] - }, - set: function(w) { - w = w|0 - reshapeFBO(this, w, this._shape[1]) - return w - }, - enumerable: false - }, - 'height': { - get: function() { - if(this._destroyed) { - return 0 - } - return this._shape[1] - }, - set: function(h) { - h = h|0 - reshapeFBO(this, this._shape[0], h) - return h - }, - enumerable: false - } -}) + return this._wordDiv(num, mode); + }; -__proto_89.bind = function() { - if(this._destroyed) { - return - } - var gl = this.gl - gl.bindFramebuffer(gl.FRAMEBUFFER, this.handle) - gl.viewport(0, 0, this._shape[0], this._shape[1]) -} + // Find `this` / `num` + BN.prototype.div = function div (num) { + return this.divmod(num, 'div', false).div; + }; -__proto_89.dispose = function() { - if(this._destroyed) { - return - } - this._destroyed = true - var gl = this.gl - gl.deleteFramebuffer(this.handle) - this.handle = null - if(this.depth) { - this.depth.dispose() - this.depth = null - } - if(this._depth_rb) { - gl.deleteRenderbuffer(this._depth_rb) - this._depth_rb = null - } - for(var i=0; i maxFBOSize || height < 0 || height > maxFBOSize) { - throw new Error('gl-fbo: Parameters are too large for FBO') - } + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - //Handle each option type - options = options || {} + // Round up + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; - //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') - } - } - } + BN.prototype.modn = function modn (num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; - //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 + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) { + acc = (p * acc + (this.words[i] | 0)) % num; } - } - - //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 acc; + }; - return new Framebuffer( - gl, - width, - height, - colorType, - numColors, - useDepth, - useStencil, - WEBGL_draw_buffers) -} + // In-place division by number + BN.prototype.idivn = function idivn (num) { + assert(num <= 0x3ffffff); -'use strict' + 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; + } -var _$createSelectBuffer_106 = createSelectBuffer + return this.strip(); + }; -/* removed: var _$createFBO_89 = require('gl-fbo') */; -/* removed: var _$pool_207 = require('typedarray-pool') */; -/* removed: var _$wrappedNDArrayCtor_143 = require('ndarray') */; + BN.prototype.divn = function divn (num) { + return this.clone().idivn(num); + }; -var nextPow2 = _$twiddle_35.nextPow2 + BN.prototype.egcd = function egcd (p) { + assert(p.negative === 0); + assert(!p.isZero()); -var selectRange = _$wrapper_67({"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_55_arg0_<255||_inline_55_arg1_<255||_inline_55_arg2_<255||_inline_55_arg3_<255){var _inline_55_l=_inline_55_arg4_-_inline_55_arg6_[0],_inline_55_a=_inline_55_arg5_-_inline_55_arg6_[1],_inline_55_f=_inline_55_l*_inline_55_l+_inline_55_a*_inline_55_a;_inline_55_f 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 this.fbo.shape.slice() - }, - set: function(v) { - if(!this.gl) { - return + + 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(); } - this.fbo.shape = v - var c = this.fbo.shape[0] - var r = this.fbo.shape[1] - if(r*c*4 > this.buffer.length) { - _$pool_207.free(this.buffer) - var buffer = this.buffer = _$pool_207.mallocUint8(nextPow2(r*c*4)) - for(var i=0; i 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); } } - return v - } -}) -__proto_106.begin = function() { - var gl = this.gl - var shape = this.shape - if(!gl) { - return - } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } - this.fbo.bind() - gl.clearColor(1,1,1,1) - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) -} + if (res.cmpn(0) < 0) { + res.iadd(p); + } -__proto_106.end = function() { - var gl = this.gl - if(!gl) { - return - } - gl.bindFramebuffer(gl.FRAMEBUFFER, null) - if(!this._readTimeout) { - clearTimeout(this._readTimeout) - } - this._readTimeout = setTimeout(this._readCallback, 1) -} + return res; + }; -__proto_106.query = function(x, y, radius) { - if(!this.gl) { - return null - } + BN.prototype.gcd = function gcd (num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); - var shape = this.fbo.shape.slice() + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; - x = x|0 - y = y|0 - if(typeof radius !== 'number') { - radius = 1.0 - } + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.iushrn(1); + b.iushrn(1); + } - var x0 = Math.min(Math.max(x - radius, 0), shape[0])|0 - var x1 = Math.min(Math.max(x + radius, 0), shape[0])|0 - var y0 = Math.min(Math.max(y - radius, 0), shape[1])|0 - var y1 = Math.min(Math.max(y + radius, 0), shape[1])|0 + do { + while (a.isEven()) { + a.iushrn(1); + } + while (b.isEven()) { + b.iushrn(1); + } - if(x1 <= x0 || y1 <= y0) { - return null - } + 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; + } - var dims = [x1-x0,y1-y0] - var region = _$wrappedNDArrayCtor_143( - this.buffer, - [dims[0], dims[1], 4], - [4, shape[0]*4, 1], - 4*(x0 + shape[0]*y0)); + a.isub(b); + } while (true); - var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius) - var dx = closest[0] - var dy = closest[1] - if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) { - return null - } + return b.iushln(shift); + }; - var c0 = region.get(dx, dy, 0) - var c1 = region.get(dx, dy, 1) - var c2 = region.get(dx, dy, 2) - var c3 = region.get(dx, dy, 3) + // Invert number in the field F(num) + BN.prototype.invm = function invm (num) { + return this.egcd(num).a.umod(num); + }; - return new SelectResult( - (dx + x0)|0, - (dy + y0)|0, - c0, - [c1, c2, c3], - Math.sqrt(closest[2])) -} + BN.prototype.isEven = function isEven () { + return (this.words[0] & 1) === 0; + }; -__proto_106.dispose = function() { - if(!this.gl) { - return - } - this.fbo.dispose() - _$pool_207.free(this.buffer) - this.gl = null - if(this._readTimeout) { - clearTimeout(this._readTimeout) - } -} + BN.prototype.isOdd = function isOdd () { + return (this.words[0] & 1) === 1; + }; -function createSelectBuffer(gl, shape) { - var fbo = _$createFBO_89(gl, shape) - var buffer = _$pool_207.mallocUint8(shape[0]*shape[1]*4) - return new SelectBuffer(gl, fbo, buffer) -} + // And first word and num + BN.prototype.andln = function andln (num) { + return this.words[0] & num; + }; -'use strict' - -var _$createGLPlot2D_101 = createGLPlot2D - -/* removed: var _$createSelectBuffer_106 = require('gl-select-static') */; - -/* removed: var _$createGrid_96 = require('./lib/grid') */; -/* removed: var _$createTextElements_99 = require('./lib/text') */; -/* removed: var _$createLines_97 = require('./lib/line') */; -/* removed: var _$createBoxes_95 = require('./lib/box') */; - -function GLPlot2D(gl, pickBuffer) { - this.gl = gl - this.pickBuffer = pickBuffer - - this.screenBox = [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] - this.viewBox = [0, 0, 0, 0] - this.dataBox = [-10, -10, 10, 10] - - this.gridLineEnable = [true,true] - this.gridLineWidth = [1,1] - this.gridLineColor = [[0,0,0,1], - [0,0,0,1]] - - this.pixelRatio = 1 - - this.tickMarkLength = [0,0,0,0] - this.tickMarkWidth = [0,0,0,0] - this.tickMarkColor = [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]] - - this.tickPad = [15,15,15,15] - this.tickAngle = [0,0,0,0] - this.tickEnable = [true,true,true,true] - this.tickColor = [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]] - - this.labelPad = [15,15,15,15] - this.labelAngle = [0,Math.PI/2,0,3.0*Math.PI/2] - this.labelEnable = [true,true,true,true] - this.labelColor = [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]] - - this.titleCenter = [0,0] - this.titleEnable = true - this.titleAngle = 0 - this.titleColor = [0,0,0,1] - - this.borderColor = [0,0,0,0] - this.backgroundColor = [0,0,0,0] - - this.zeroLineEnable = [true, true] - this.zeroLineWidth = [4, 4] - this.zeroLineColor = [[0, 0, 0, 1],[0, 0, 0, 1]] - - this.borderLineEnable = [true,true,true,true] - this.borderLineWidth = [2,2,2,2] - this.borderLineColor = [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]] - - //Drawing parameters - this.grid = null - this.text = null - this.line = null - this.box = null - this.objects = [] - this.overlays = [] - - this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] - - this.static = false - - this.dirty = false - this.pickDirty = false - this.pickDelay = 120 - this.pickRadius = 10 - this._pickTimeout = null - this._drawPick = this.drawPick.bind(this) - - this._depthCounter = 0 -} - -var __proto_101 = GLPlot2D.prototype - -__proto_101.setDirty = function() { - this.dirty = this.pickDirty = true -} - -__proto_101.setOverlayDirty = function() { - this.dirty = true -} - -__proto_101.nextDepthValue = function() { - return (this._depthCounter++) / 65536.0 -} - -function lerp(a, b, t) { - var s = 0.5 * (t + 1.0) - return Math.floor((1.0-s)*a + s*b)|0 -} - -__proto_101.draw = (function() { -var TICK_MARK_BOX = [0,0,0,0] -return function() { - var gl = this.gl - var screenBox = this.screenBox - var viewPixels = this.viewBox - var dataBox = this.dataBox - var pixelRatio = this.pixelRatio - var grid = this.grid - var line = this.line - var text = this.text - var objects = this.objects - - this._depthCounter = 0 - - if(this.pickDirty) { - if(this._pickTimeout) { - clearTimeout(this._pickTimeout) - } - this.pickDirty = false - this._pickTimeout = setTimeout(this._drawPick, this.pickDelay) - } - - if(!this.dirty) { - return - } - this.dirty = false - - gl.bindFramebuffer(gl.FRAMEBUFFER, null) - - //Turn on scissor - gl.enable(gl.SCISSOR_TEST) - - //Turn off depth buffer - gl.disable(gl.DEPTH_TEST) - gl.depthFunc(gl.LESS) - gl.depthMask(false) - - //Configure premultiplied alpha blending - gl.enable(gl.BLEND) - gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - - //Draw border - if (this.borderColor) { - gl.scissor( - screenBox[0], - screenBox[1], - screenBox[2]-screenBox[0], - screenBox[3]-screenBox[1]) - var borderColor = this.borderColor - gl.clearColor( - borderColor[0]*borderColor[3], - borderColor[1]*borderColor[3], - borderColor[2]*borderColor[3], - borderColor[3]) - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) - } - - //Draw center pane - gl.scissor( - viewPixels[0], - viewPixels[1], - viewPixels[2]-viewPixels[0], - viewPixels[3]-viewPixels[1]) - gl.viewport( - viewPixels[0], - viewPixels[1], - viewPixels[2]-viewPixels[0], - viewPixels[3]-viewPixels[1]) - var backgroundColor = this.backgroundColor - gl.clearColor( - backgroundColor[0]*backgroundColor[3], - backgroundColor[1]*backgroundColor[3], - backgroundColor[2]*backgroundColor[3], - backgroundColor[3]) - gl.clear(gl.COLOR_BUFFER_BIT) - - //Draw grid - grid.draw() - - //Draw zero lines separately - var zeroLineEnable = this.zeroLineEnable - var zeroLineColor = this.zeroLineColor - var zeroLineWidth = this.zeroLineWidth - if(zeroLineEnable[0] || zeroLineEnable[1]) { - line.bind() - for(var i=0; i<2; ++i) { - if(!zeroLineEnable[i] || - !(dataBox[i] <= 0 && dataBox[i+2] >= 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_101.addObject = function(object) { - if(this.objects.indexOf(object) < 0) { - this.objects.push(object) - this.setDirty() - } -} - -__proto_101.removeObject = function(object) { - var objects = this.objects - for(var i=0; i>> 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); + }; +})("object" === 'undefined' || _$bn_38, this); + +_$bn_38 = _$bn_38.exports +'use strict' + +/* removed: var _$bn_38 = require('bn.js') */; + +var _$sign_24 = __sign_24 + +function __sign_24 (x) { + return x.cmp(new _$bn_38(0)) +} + +var _$double_73 = {}; +(function (Buffer){ +var hasTypedArrays = false +if(typeof Float64Array !== "undefined") { + var DOUBLE_VIEW = new Float64Array(1) + , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) + DOUBLE_VIEW[0] = 1.0 + hasTypedArrays = true + if(UINT_VIEW[1] === 0x3ff00000) { + //Use little endian + _$double_73 = function doubleBitsLE(n) { + DOUBLE_VIEW[0] = n + return [ UINT_VIEW[0], UINT_VIEW[1] ] + } + function toDoubleLE(lo, hi) { + UINT_VIEW[0] = lo + UINT_VIEW[1] = hi + return DOUBLE_VIEW[0] + } + _$double_73.pack = toDoubleLE + function lowUintLE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[0] + } + _$double_73.lo = lowUintLE + function highUintLE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[1] + } + _$double_73.hi = highUintLE + } else if(UINT_VIEW[0] === 0x3ff00000) { + //Use big endian + _$double_73 = function doubleBitsBE(n) { + DOUBLE_VIEW[0] = n + return [ UINT_VIEW[1], UINT_VIEW[0] ] + } + function toDoubleBE(lo, hi) { + UINT_VIEW[1] = lo + UINT_VIEW[0] = hi + return DOUBLE_VIEW[0] + } + _$double_73.pack = toDoubleBE + function lowUintBE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[1] + } + _$double_73.lo = lowUintBE + function highUintBE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[0] + } + _$double_73.hi = highUintBE + } else { + hasTypedArrays = false + } +} +if(!hasTypedArrays) { + var buffer = new Buffer(8) + _$double_73 = function doubleBits(n) { + buffer.writeDoubleLE(n, 0, true) + return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] + } + function toDouble(lo, hi) { + buffer.writeUInt32LE(lo, 0, true) + buffer.writeUInt32LE(hi, 4, true) + return buffer.readDoubleLE(0, true) + } + _$double_73.pack = toDouble + function lowUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(0, true) + } + _$double_73.lo = lowUint + function highUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(4, true) + } + _$double_73.hi = highUint +} + +_$double_73.sign = function(n) { + return _$double_73.hi(n) >>> 31 +} + +_$double_73.exponent = function(n) { + var b = _$double_73.hi(n) + return ((b<<1) >>> 21) - 1023 +} + +_$double_73.fraction = function(n) { + var lo = _$double_73.lo(n) + var hi = _$double_73.hi(n) + var b = hi & ((1<<20) - 1) + if(hi & 0x7ff00000) { + b += (1<<20) + } + return [lo, b] +} + +_$double_73.denormalized = function(n) { + var hi = _$double_73.hi(n) + return !(hi & 0x7ff00000) +} +}).call(this,_$buffer_47.Buffer) +'use strict' + +/* removed: var _$bn_38 = require('bn.js') */; +/* removed: var _$double_73 = require('double-bits') */; + +var _$num2bn_28 = num2bn + +function num2bn(x) { + var e = _$double_73.exponent(x) + if(e < 52) { + return new _$bn_38(x) + } else { + return (new _$bn_38(x * Math.pow(2, 52-e))).ushln(e-52) + } +} + +'use strict' + +/* removed: var _$num2bn_28 = require('./num-to-bn') */; +/* removed: var _$sign_24 = require('./bn-sign') */; + +var _$rationalize_29 = rationalize + +function rationalize(numer, denom) { + var snumer = _$sign_24(numer) + var sdenom = _$sign_24(denom) + if(snumer === 0) { + return [_$num2bn_28(0), _$num2bn_28(1)] + } + if(sdenom === 0) { + return [_$num2bn_28(0), _$num2bn_28(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 ] +} + +'use strict' + +/* removed: var _$rationalize_29 = require('./lib/rationalize') */; + +var _$div_21 = div + +function div(a, b) { + return _$rationalize_29(a[0].mul(b[1]), a[1].mul(b[0])) +} + +'use strict' + +/* removed: var _$bn_38 = require('bn.js') */; + +var _$isBN_27 = 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) +} + +'use strict' + +/* removed: var _$isBN_27 = require('./lib/is-bn') */; + +var _$isRat_23 = isRat + +function isRat(x) { + return Array.isArray(x) && x.length === 2 && _$isBN_27(x[0]) && _$isBN_27(x[1]) +} + +'use strict' + +/* removed: var _$bn_38 = require('bn.js') */; + +var _$str2BN_30 = str2BN + +function str2BN(x) { + return new _$bn_38(x) +} + +'use strict' + +/* removed: var _$isRat_23 = require('./is-rat') */; +/* removed: var _$isBN_27 = require('./lib/is-bn') */; +/* removed: var _$num2bn_28 = require('./lib/num-to-bn') */; +/* removed: var _$str2BN_30 = require('./lib/str-to-bn') */; +/* removed: var _$rationalize_29 = require('./lib/rationalize') */; +/* removed: var _$div_21 = require('./div') */; + +var _$makeRational_22 = makeRational + +function makeRational(numer, denom) { + if(_$isRat_23(numer)) { + if(denom) { + return _$div_21(numer, makeRational(denom)) + } + return [numer[0].clone(), numer[1].clone()] + } + var shift = 0 + var a, b + if(_$isBN_27(numer)) { + a = numer.clone() + } else if(typeof numer === 'string') { + a = _$str2BN_30(numer) + } else if(numer === 0) { + return [_$num2bn_28(0), _$num2bn_28(1)] + } else if(numer === Math.floor(numer)) { + a = _$num2bn_28(numer) + } else { + while(numer !== Math.floor(numer)) { + numer = numer * Math.pow(2, 256) + shift -= 256 + } + a = _$num2bn_28(numer) + } + if(_$isRat_23(denom)) { + a.mul(denom[1]) + b = denom[0].clone() + } else if(_$isBN_27(denom)) { + b = denom.clone() + } else if(typeof denom === 'string') { + b = _$str2BN_30(denom) + } else if(!denom) { + b = _$num2bn_28(1) + } else if(denom === Math.floor(denom)) { + b = _$num2bn_28(denom) + } else { + while(denom !== Math.floor(denom)) { + denom = denom * Math.pow(2, 256) + shift += 256 + } + b = _$num2bn_28(denom) + } + if(shift > 0) { + a = a.ushln(shift) + } else if(shift < 0) { + b = b.ushln(-shift) + } + return _$rationalize_29(a, b) +} + +'use strict' + +/* removed: var _$sign_24 = require('./bn-sign') */; + +var _$bn2num_25 = bn2num + +//TODO: Make this better +function bn2num(b) { + var l = b.length + var words = b.words + var out = 0 + if (l === 1) { + out = words[0] + } else if (l === 2) { + out = words[0] + (words[1] * 0x4000000) + } else { + for (var i = 0; i < l; i++) { + var w = words[i] + out += w * Math.pow(0x4000000, i) + } + } + return _$sign_24(b) * out +} + +'use strict' + +/* removed: var _$double_73 = require('double-bits') */; +var ctz = _$twiddle_36.countTrailingZeros + +var _$ctzNumber_26 = ctzNumber + +//Counts the number of trailing zeros +function ctzNumber(x) { + var l = ctz(_$double_73.lo(x)) + if(l < 32) { + return l + } + var h = ctz(_$double_73.hi(x)) + if(h > 20) { + return 52 + } + return h + 32 +} + +'use strict' + +/* removed: var _$bn2num_25 = require('./lib/bn-to-num') */; +/* removed: var _$ctzNumber_26 = require('./lib/ctz') */; + +var _$roundRat_34 = 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_25(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 = _$ctzNumber_26(x) + 4 + var y = _$bn2num_25(ir.ushln(s).divRound(b)) + return sgn * (x + y * Math.pow(2, -s)) + } else { + var ybits = b.bitLength() - ir.bitLength() + 53 + var y = _$bn2num_25(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) + } +} + +var _$brute_40 = {}; +'use strict' + +var DIMENSION = 'd' +var AXIS = 'ax' +var VISIT = 'vv' +var FLIP = 'fp' + +var ELEM_SIZE = 'es' + +var RED_START = 'rs' +var RED_END = 're' +var RED_BOXES = 'rb' +var RED_INDEX = 'ri' +var RED_PTR = 'rp' + +var BLUE_START = 'bs' +var BLUE_END = 'be' +var BLUE_BOXES = 'bb' +var BLUE_INDEX = 'bi' +var BLUE_PTR = 'bp' + +var RETVAL = 'rv' + +var INNER_LABEL = 'Q' + +var ARGS = [ + DIMENSION, + AXIS, + VISIT, + RED_START, + RED_END, + RED_BOXES, + RED_INDEX, + BLUE_START, + BLUE_END, + BLUE_BOXES, + BLUE_INDEX +] + +function generateBruteForce(redMajor, flip, full) { + var funcName = 'bruteForce' + + (redMajor ? 'Red' : 'Blue') + + (flip ? 'Flip' : '') + + (full ? 'Full' : '') + + var code = ['function ', funcName, '(', ARGS.join(), '){', + 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] + + var redLoop = + 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + + 'i<' + RED_END +';' + + '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + + 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + + 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + + 'xi=' + RED_INDEX + '[i];' + + var blueLoop = + 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + + 'j<' + BLUE_END + ';' + + '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + + 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + + (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + + 'yi=' + BLUE_INDEX + '[j];' + + if(redMajor) { + code.push(redLoop, INNER_LABEL, ':', blueLoop) + } else { + code.push(blueLoop, INNER_LABEL, ':', redLoop) + } + + if(full) { + code.push('if(y1' + + BLUE_END + '-' + BLUE_START + '){') + + if(full) { + invoke(true, false) + code.push('}else{') + invoke(false, false) + } else { + code.push('if(' + FLIP + '){') + invoke(true, true) + code.push('}else{') + invoke(true, false) + code.push('}}else{if(' + FLIP + '){') + invoke(false, true) + code.push('}else{') + invoke(false, false) + code.push('}') + } + code.push('}}return ' + funcName) + + var codeStr = prefix.join('') + code.join('') + var proc = new Function(codeStr) + return proc() +} + + +_$brute_40.partial = bruteForcePlanner(false) +_$brute_40.full = bruteForcePlanner(true) +'use strict' + +var _$genPartition_43 = genPartition + +var __code_43 = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' + +function genPartition(predicate, args) { + var fargs ='abcdef'.split('').concat(args) + var reads = [] + if(predicate.indexOf('lo') >= 0) { + reads.push('lo=e[k+n]') + } + if(predicate.indexOf('hi') >= 0) { + reads.push('hi=e[k+o]') + } + fargs.push( + __code_43.replace('_', reads.join()) + .replace('$', predicate)) + return Function.apply(void 0, fargs) +} +'use strict' + +var _$findMedian_42 = findMedian + +/* removed: var _$genPartition_43 = require('./partition') */; + +var partitionStartLessThan = _$genPartition_43('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 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_44(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_44(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_44(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_44(left, less - 2, data); + } else { + quickSort(left, less - 2, data); + } + if (right - (great + 2) <= INSERT_SORT_CUTOFF) { + __insertionSort_44(great + 2, right, data); + } else { + quickSort(great + 2, right, data); + } + if (great - less <= INSERT_SORT_CUTOFF) { + __insertionSort_44(less, great, data); + } else { + quickSort(less, great, data); + } +} +'use strict' + +var _$sweep_45 = { + init: sqInit, + sweepBipartite: sweepBipartite, + sweepComplete: sweepComplete, + scanBipartite: scanBipartite, + scanComplete: scanComplete +} + +/* removed: var _$pool_269 = require('typedarray-pool') */; +/* removed: var _$twiddle_36 = require('bit-twiddle') */; +/* removed: var _$wrapper_44 = require('./sort') */; + +//Flag for blue +var BLUE_FLAG = (1<<28) + +//1D sweep event queue stuff (use pool to save space) +var INIT_CAPACITY = 1024 +var RED_SWEEP_QUEUE = _$pool_269.mallocInt32(INIT_CAPACITY) +var RED_SWEEP_INDEX = _$pool_269.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_QUEUE = _$pool_269.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_INDEX = _$pool_269.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_QUEUE = _$pool_269.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_INDEX = _$pool_269.mallocInt32(INIT_CAPACITY) +var SWEEP_EVENTS = _$pool_269.mallocDouble(INIT_CAPACITY * 8) + +//Reserves memory for the 1D sweep data structures +function sqInit(count) { + var rcount = _$twiddle_36.nextPow2(count) + if(RED_SWEEP_QUEUE.length < rcount) { + _$pool_269.free(RED_SWEEP_QUEUE) + RED_SWEEP_QUEUE = _$pool_269.mallocInt32(rcount) + } + if(RED_SWEEP_INDEX.length < rcount) { + _$pool_269.free(RED_SWEEP_INDEX) + RED_SWEEP_INDEX = _$pool_269.mallocInt32(rcount) + } + if(BLUE_SWEEP_QUEUE.length < rcount) { + _$pool_269.free(BLUE_SWEEP_QUEUE) + BLUE_SWEEP_QUEUE = _$pool_269.mallocInt32(rcount) + } + if(BLUE_SWEEP_INDEX.length < rcount) { + _$pool_269.free(BLUE_SWEEP_INDEX) + BLUE_SWEEP_INDEX = _$pool_269.mallocInt32(rcount) + } + if(COMMON_SWEEP_QUEUE.length < rcount) { + _$pool_269.free(COMMON_SWEEP_QUEUE) + COMMON_SWEEP_QUEUE = _$pool_269.mallocInt32(rcount) + } + if(COMMON_SWEEP_INDEX.length < rcount) { + _$pool_269.free(COMMON_SWEEP_INDEX) + COMMON_SWEEP_INDEX = _$pool_269.mallocInt32(rcount) + } + var eventLength = 8 * rcount + if(SWEEP_EVENTS.length < eventLength) { + _$pool_269.free(SWEEP_EVENTS) + SWEEP_EVENTS = _$pool_269.mallocDouble(eventLength) + } +} + +//Remove an item from the active queue in O(1) +function sqPop(queue, index, count, item) { + var idx = index[item] + var top = queue[count-1] + queue[idx] = top + index[top] = idx +} + +//Insert an item into the active queue in O(1) +function sqPush(queue, index, count, item) { + queue[count] = item + index[item] = count +} + +//Recursion base case: use 1D sweep algorithm +function sweepBipartite( + d, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + //store events as pairs [coordinate, idx] + // + // red create: -(idx+1) + // red destroy: idx + // blue create: -(idx+BLUE_FLAG) + // blue destroy: idx+BLUE_FLAG + // + var ptr = 0 + var elemSize = 2*d + var istart = d-1 + var iend = elemSize-1 + + for(var i=redStart; iright + var n = ptr >>> 1 + _$wrapper_44(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + for(var i=0; i= BLUE_FLAG) { + //blue destroy event + e = (e-BLUE_FLAG)|0 + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) + } else if(e >= 0) { + //red destroy event + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) + } else if(e <= -BLUE_FLAG) { + //blue create event + e = (-e-BLUE_FLAG)|0 + for(var j=0; jright + var n = ptr >>> 1 + _$wrapper_44(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + var commonActive = 0 + for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { + color = 2 + i += 1 + } + + if(e < 0) { + //Create event + var id = -(e>>1) - 1 + + //Intersect with common + for(var j=0; j>1) - 1 + if(color === 0) { + //Red + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) + } else if(color === 1) { + //Blue + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) + } else if(color === 2) { + //Both + sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) + } + } + } +} + +//Sweep and prune/scanline algorithm: +// Scan along axis, detect intersections +// Brute force all boxes along axis +function scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = axis + var iend = axis+d + + var redShift = 1 + var blueShift = 1 + if(flip) { + blueShift = BLUE_FLAG + } else { + redShift = BLUE_FLAG + } + + for(var i=redStart; iright + var n = ptr >>> 1 + _$wrapper_44(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + isRed = !flip + idx -= BLUE_FLAG + } else { + isRed = !!flip + idx -= 1 + } + if(isRed) { + sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) + } else { + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] + +red_loop: + for(var j=0; jright + var n = ptr >>> 1 + _$wrapper_44(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG + } else { + idx -= 1 + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] + +red_loop: + for(var j=0; j=0; --j) { + if(RED_SWEEP_QUEUE[j] === idx) { + for(var k=j+1; k=p0)&&!(p1>=hi)', + ['p0', 'p1']) + +var partitionStartEqual = _$genPartition_43( + 'lo===p0', + ['p0']) + +var __partitionStartLessThan_41 = _$genPartition_43( + 'lo 0) { - - //Draw border - var w = lineWidth * pixelRatio - boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) - boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) - boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) - boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) - } -} - -__proto_105.update = function(options) { - options = options || {} - - this.innerFill = !!options.innerFill - this.outerFill = !!options.outerFill - this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() - this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() - this.borderColor = (options.borderColor || [0,0,0,1]).slice() - this.borderWidth = options.borderWidth || 0 - this.selectBox = (options.selectBox || this.selectBox).slice() -} - -__proto_105.dispose = function() { - this.boxBuffer.dispose() - this.boxShader.dispose() - this.plot.removeOverlay(this) -} - -function createSelectBox(plot, options) { - var gl = plot.gl - var buffer = _$createBuffer_83(gl, [ - 0, 0, - 0, 1, - 1, 0, - 1, 1 ]) - var shader = _$createShader_107(gl, _$shaders_104.boxVertex, _$shaders_104.boxFragment) - var selectBox = new SelectBox(plot, buffer, shader) - selectBox.update(options) - plot.addOverlay(selectBox) - return selectBox -} + //Reserve memory for stack + iterInit(d, xSize + ySize) + + var top = 0 + var elemSize = 2 * d + var retval + + iterPush(top++, + 0, + 0, xSize, + 0, ySize, + initFull ? 16 : 0, + -Infinity, Infinity) + if(!initFull) { + iterPush(top++, + 0, + 0, ySize, + 0, xSize, + 1, + -Infinity, Infinity) + } + + while(top > 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_41( + 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_45.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_45.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_45.sweepBipartite( + d, visit, + blueStart, blueEnd, blue, blueIndex, + redStart, red0, red, redIndex) + } else { + retval = _$sweep_45.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_42( + 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_45.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_45.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_45.sweepBipartite( + d, visit, + blue0, blue1, blue, blueIndex, + red0, red1, red, redIndex) + } else { + retval = _$sweep_45.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) + } + } + } + } + } + } +} +'use strict' + +var _$boxIntersectWrapper_39 = boxIntersectWrapper + +/* removed: var _$pool_269 = require('typedarray-pool') */; +/* removed: var _$sweep_45 = require('./lib/sweep') */; +/* removed: var _$boxIntersectIter_41 = require('./lib/intersect') */; + +function boxEmpty(d, box) { + for(var j=0; j>>1 + if(d <= 0) { + return + } + + var retval + + //Convert red boxes + var redList = _$pool_269.mallocDouble(2*d*n) + var redIds = _$pool_269.mallocInt32(n) + n = convertBoxes(red, d, redList, redIds) + + if(n > 0) { + if(d === 1 && full) { + //Special case: 1d complete + _$sweep_45.init(n) + retval = _$sweep_45.sweepComplete( + d, visit, + 0, n, redList, redIds, + 0, n, redList, redIds) + } else { + + //Convert blue boxes + var blueList = _$pool_269.mallocDouble(2*d*m) + var blueIds = _$pool_269.mallocInt32(m) + m = convertBoxes(blue, d, blueList, blueIds) + + if(m > 0) { + _$sweep_45.init(n+m) + + if(d === 1) { + //Special case: 1d bipartite + retval = _$sweep_45.sweepBipartite( + d, visit, + 0, n, redList, redIds, + 0, m, blueList, blueIds) + } else { + //General case: d>1 + retval = _$boxIntersectIter_41( + d, visit, full, + n, redList, redIds, + m, blueList, blueIds) + } + + _$pool_269.free(blueList) + _$pool_269.free(blueIds) + } + } + + _$pool_269.free(redList) + _$pool_269.free(redIds) + } + + return retval +} + + +var RESULT + +function appendItem(i,j) { + RESULT.push([i,j]) +} + +function intersectFullArray(x) { + RESULT = [] + boxIntersect(x, x, appendItem, true) + return RESULT +} + +function intersectBipartiteArray(x, y) { + RESULT = [] + boxIntersect(x, y, appendItem, false) + return RESULT +} +//User-friendly wrapper, handle full input and no-visitor cases +function boxIntersectWrapper(arg0, arg1, arg2) { + var result + switch(arguments.length) { + case 1: + return intersectFullArray(arg0) + case 2: + if(typeof arg1 === 'function') { + return boxIntersect(arg0, arg0, arg1, true) + } else { + return intersectBipartiteArray(arg0, arg1) + } + case 3: + return boxIntersect(arg0, arg1, arg2, false) + default: + throw new Error('box-intersect: Invalid arguments') + } +} 'use strict' -var _$createSpikes2D_114 = createSpikes2D +/* removed: var _$rationalize_29 = require('./lib/rationalize') */; -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 _$mul_31 = mul + +function mul(a, b) { + return _$rationalize_29(a[0].mul(b[0]), a[1].mul(b[1])) } -var __proto_114 = GLSpikes2D.prototype +'use strict' -__proto_114.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() +/* removed: var _$sign_24 = require('./lib/bn-sign') */; + +var _$sign_32 = __sign_32 + +function __sign_32(x) { + return _$sign_24(x[0]) * _$sign_24(x[1]) } -__proto_114.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 +'use strict' - var dataBox = plot.dataBox - var viewPixels = plot.viewBox +/* removed: var _$rationalize_29 = require('./lib/rationalize') */; - line.bind() +var _$sub_33 = sub - if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] && - dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) { +function sub(a, b) { + return _$rationalize_29(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) +} - 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]) +'use strict' - if(spikeEnable[0]) { - line.drawLine( - centerX, centerY, - viewPixels[0], centerY, - spikeWidth[0], spikeColor[0]) +/* removed: var _$rationalize_29 = require('./lib/rationalize') */; + +var _$add_19 = add + +function add(a, b) { + return _$rationalize_29( + a[0].mul(b[1]).add(b[0].mul(a[1])), + a[1].mul(b[1])) +} + +'use strict' + +/* removed: var _$add_19 = require('big-rat/add') */; + +var _$add_230 = __add_230 + +function __add_230 (a, b) { + var n = a.length + var r = new Array(n) + for (var i=0; i>>0 + +var _$nextafter_202 = 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 } - if(spikeEnable[1]) { - line.drawLine( - centerX, centerY, - centerX, viewPixels[1], - spikeWidth[1], spikeColor[1]) + } + var hi = _$double_73.hi(x) + var lo = _$double_73.lo(x) + if((y > x) === (x > 0)) { + if(lo === UINT_MAX) { + hi += 1 + lo = 0 + } else { + lo += 1 } - if(spikeEnable[2]) { - line.drawLine( - centerX, centerY, - viewPixels[2], centerY, - spikeWidth[2], spikeColor[2]) + } else { + if(lo === 0) { + lo = UINT_MAX + hi -= 1 + } else { + lo -= 1 } - if(spikeEnable[3]) { - line.drawLine( - centerX, centerY, - centerX, viewPixels[3], - spikeWidth[3], spikeColor[3]) + } + return _$double_73.pack(lo, hi) +} +'use strict' + +var _$float2rat_231 = float2rat + +/* removed: var _$makeRational_22 = require('big-rat') */; + +function float2rat(v) { + var result = new Array(v.length) + for(var i=0; i 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { + return false + } + + var x1 = __orient_245(b0, a0, a1) + var y1 = __orient_245(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 } +"use strict"; "use restrict"; -function createSpikes2D(plot, options) { - var spikes = new GLSpikes2D(plot) - spikes.update(options) - plot.addOverlay(spikes) - return spikes +var _$UnionFind_270 = UnionFind; + +function UnionFind(count) { + this.roots = new Array(count); + this.ranks = new Array(count); + + for(var i=0; i= 0; --i) { + var junction = junctions[i] + e = junction[0] + + var edge = edges[e] + var s = edge[0] + var t = edge[1] + + // Check if edge is not lexicographically sorted + var a = floatPoints[s] + var b = floatPoints[t] + if (((a[0] - b[0]) || (a[1] - b[1])) < 0) { + var tmp = s + s = t + t = tmp + } + + // Split leading edge + edge[0] = s + var last = edge[1] = junction[1] + + // If we are grouping edges by color, remember to track data + var color + if (useColor) { + color = edge[2] + } + + // Split other edges + while (i > 0 && junctions[i - 1][0] === e) { + var junction = junctions[--i] + var next = junction[1] + if (useColor) { + edges.push([last, next, color]) + } else { + edges.push([last, next]) + } + last = next + } + + // Add final edge + if (useColor) { + edges.push([last, t, color]) + } else { + edges.push([last, t]) + } + } + + // Return constructed rational points + return ratPoints +} + +// Merge overlapping points +function dedupPoints (floatPoints, ratPoints, floatBounds) { + var numPoints = ratPoints.length + var uf = new _$UnionFind_270(numPoints) + + // Compute rational bounds + var bounds = [] + for (var i = 0; i < ratPoints.length; ++i) { + var p = ratPoints[i] + var xb = boundRat(p[0]) + var yb = boundRat(p[1]) + bounds.push([ + _$nextafter_202(xb[0], -Infinity), + _$nextafter_202(yb[0], -Infinity), + _$nextafter_202(xb[1], Infinity), + _$nextafter_202(yb[1], Infinity) + ]) + } + + // Link all points with over lapping boxes + _$boxIntersectWrapper_39(bounds, function (i, j) { + uf.link(i, j) + }) + + // Do 1 pass over points to combine points in label sets + var noDupes = true + var labels = new Array(numPoints) + for (var i = 0; i < numPoints; ++i) { + var j = uf.find(i) + if (j !== i) { + // Clear no-dupes flag, zero out label + noDupes = false + // Make each point the top-left point from its cell + floatPoints[j] = [ + Math.min(floatPoints[i][0], floatPoints[j][0]), + Math.min(floatPoints[i][1], floatPoints[j][1]) + ] } - } catch (e) { - gl = null } - return (gl || null) // ensure null on fail -} -/* removed: var _$getCanvasContext_82 = require('get-canvas-context') */; + // If no duplicates, return null to signal termination + if (noDupes) { + return null + } -var _$getWebGLContext_219 = function getWebGLContext (opt) { - return _$getCanvasContext_82('webgl', opt) -} + var ptr = 0 + for (var i = 0; i < numPoints; ++i) { + var j = uf.find(i) + if (j === i) { + labels[i] = ptr + floatPoints[ptr++] = floatPoints[i] + } else { + labels[i] = -1 + } + } -var _$client_131 = true; -var _$hasHover_125 = {}; -(function (global){ -'use strict' - -/* removed: var _$client_131 = require('is-browser') */; -var hasHover - -if (typeof global.matchMedia === 'function') { - hasHover = !global.matchMedia('(hover: none)').matches -} -else { - hasHover = _$client_131 -} - -_$hasHover_125 = hasHover + floatPoints.length = ptr -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -'use strict' - -/* removed: var _$client_131 = require('is-browser') */; - -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 -} - -var _$hasPassiveEvents_126 = _$client_131 && detect() + // Do a second pass to fix up missing labels + for (var i = 0; i < numPoints; ++i) { + if (labels[i] < 0) { + labels[i] = labels[uf.find(i)] + } + } -var rootPosition = { left: 0, top: 0 } + // Return resulting union-find data structure + return labels +} -var _$mouseEventOffset_138 = mouseEventOffset -function mouseEventOffset (ev, target, out) { - target = target || ev.currentTarget || ev.srcElement - if (!Array.isArray(out)) { - out = [ 0, 0 ] +function compareLex2 (a, b) { return (a[0] - b[0]) || (a[1] - b[1]) } +function compareLex3 (a, b) { + var d = (a[0] - b[0]) || (a[1] - b[1]) + if (d) { + return d } - var cx = ev.clientX || 0 - var cy = ev.clientY || 0 - var rect = getBoundingClientOffset(target) - out[0] = cx - rect.left - out[1] = cy - rect.top - return out + if (a[2] < b[2]) { + return -1 + } else if (a[2] > b[2]) { + return 1 + } + return 0 } -function getBoundingClientOffset (element) { - if (element === window || - element === document || - element === document.body) { - return rootPosition +// Remove duplicate edge labels +function dedupEdges (edges, labels, useColor) { + if (edges.length === 0) { + return + } + if (labels) { + for (var i = 0; i < edges.length; ++i) { + var e = edges[i] + var a = labels[e[0]] + var b = labels[e[1]] + e[0] = Math.min(a, b) + e[1] = Math.max(a, b) + } } else { - return element.getBoundingClientRect() + for (var i = 0; i < edges.length; ++i) { + var e = edges[i] + var a = e[0] + var b = e[1] + e[0] = Math.min(a, b) + e[1] = Math.max(a, b) + } + } + if (useColor) { + edges.sort(compareLex3) + } else { + edges.sort(compareLex2) + } + var ptr = 1 + for (var i = 1; i < edges.length; ++i) { + var prev = edges[i - 1] + var next = edges[i] + if (next[0] === prev[0] && next[1] === prev[1] && + (!useColor || next[2] === prev[2])) { + continue + } + edges[ptr++] = next } + edges.length = ptr } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function preRound (points, edges, useColor) { + var labels = dedupPoints(points, [], boundPoints(points)) + dedupEdges(edges, labels, useColor) + return !!labels +} +// Repeat until convergence +function snapRound (points, edges, useColor) { + // 1. find edge crossings + var edgeBounds = boundEdges(points, edges) + var crossings = getCrossings(points, edges, edgeBounds) -'use strict'; + // 2. find t-junctions + var vertBounds = boundPoints(points) + var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds) + // 3. cut edges, construct rational points + var ratPoints = cutEdges(points, edges, crossings, tjunctions, useColor) -// 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 -var _$align_259 = function align(v, dv, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0), - vmax = vmin + dv / (v1 - v0), - vc = (vmin + vmax) / 2; + // 4. dedupe verts + var labels = dedupPoints(points, ratPoints, vertBounds) - // explicitly specified anchor - if(anchor === 'left' || anchor === 'bottom') return vmin; - if(anchor === 'center' || anchor === 'middle') return vc; - if(anchor === 'right' || anchor === 'top') return vmax; + // 5. dedupe edges + dedupEdges(edges, labels, useColor) - // automatic based on position - if(vmin < (2 / 3) - vc) return vmin; - if(vmax > (4 / 3) - vc) return vmax; - return vc; -}; + // 6. check termination + if (!labels) { + return (crossings.length > 0 || tjunctions.length > 0) + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 iterations necessary + return true +} +// Main loop, runs PSLG clean up until completion +function cleanPSLG (points, edges, colors) { + // If using colors, augment edges with color data + var prevEdges + if (colors) { + prevEdges = edges + var augEdges = new Array(edges.length) + for (var i = 0; i < edges.length; ++i) { + var e = edges[i] + augEdges[i] = [e[0], e[1], colors[i]] + } + edges = augEdges + } -'use strict'; + // First round: remove duplicate edges and points + var modified = preRound(points, edges, !!colors) -/* removed: var _$lib_363 = require('../../lib'); */; + // Run snap rounding until convergence + while (snapRound(points, edges, !!colors)) { + modified = true + } + // Strip color tags + if (!!colors && modified) { + prevEdges.length = 0 + colors.length = 0 + for (var i = 0; i < edges.length; ++i) { + var e = edges[i] + prevEdges.push([e[0], e[1]]) + colors.push(e[2]) + } + } -// 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'] -]; + return modified +} -var _$getCursor_260 = 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_363.constrain(Math.floor(x * 3), 0, 2); +"use strict" - if(yanchor === 'bottom') y = 0; - else if(yanchor === 'middle') y = 1; - else if(yanchor === 'top') y = 2; - else y = _$lib_363.constrain(Math.floor(y * 3), 0, 2); +var _$edgeToAdjacency_78 = edgeToAdjacency - return cursorset[y][x]; -}; +/* removed: var _$unique_271 = require("uniq") */; -// 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. +function edgeToAdjacency(edges, numVertices) { + var numEdges = edges.length + if(typeof numVertices !== "number") { + numVertices = 0 + for(var i=0; i 0) { return 1 } + return 0.0 +} +"use strict" -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; +var _$compareAngle_64 = compareAngle -// 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. -EventEmitter.defaultMaxListeners = 10; +/* removed: var _$orientation_242 = require("robust-orientation") */; +/* removed: var _$signum_248 = require("signum") */; +/* removed: var _$fastTwoSum_268 = require("two-sum") */; +/* removed: var _$robustProduct_243 = require("robust-product") */; +/* removed: var _$linearExpansionSum_247 = require("robust-sum") */; -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; +function testInterior(a, b, c) { + var x0 = _$fastTwoSum_268(a[0], -b[0]) + var y0 = _$fastTwoSum_268(a[1], -b[1]) + var x1 = _$fastTwoSum_268(c[0], -b[0]) + var y1 = _$fastTwoSum_268(c[1], -b[1]) -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; + var d = _$linearExpansionSum_247( + _$robustProduct_243(x0, x1), + _$robustProduct_243(y0, y1)) - if (!this._events) - this._events = {}; + return d[d.length-1] >= 0 +} - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event +function compareAngle(a, b, c, d) { + var bcd = _$orientation_242(b, c, d) + if(bcd === 0) { + //Handle degenerate cases + var sabc = _$signum_248(_$orientation_242(a, b, c)) + var sabd = _$signum_248(_$orientation_242(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 { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; + return 1 + } + } else if(sabc === 0) { + if(sabd > 0) { + return 1 + } else if(testInterior(a, b, c)) { + return 1 + } else { + return -1 } } + return _$signum_248(sabd - sabc) } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); + var abc = _$orientation_242(a, b, c) + if(abc > 0) { + if(bcd > 0 && _$orientation_242(a, b, d) > 0) { + return 1 + } + return -1 + } else if(abc < 0) { + if(bcd > 0 || _$orientation_242(a, b, d) > 0) { + return 1 + } + return -1 + } else { + var abd = _$orientation_242(a, b, d) + if(abd > 0) { + return 1 + } else { + if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); } +} +"use strict" - return true; -}; +var _$planarDual_213 = planarDual -EventEmitter.prototype.addListener = function(type, listener) { - var m; +/* removed: var _$compareAngle_64 = require("compare-angle") */; - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +function planarDual(cells, positions) { - if (!this._events) - this._events = {}; + var numVertices = positions.length|0 + var numEdges = cells.length + var adj = [new Array(numVertices), new Array(numVertices)] + for(var i=0; i 0) { + nextCell = adj[i][b][0] + nextDir = i + break + } } + nextVertex = nextCell[nextDir^1] - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); + for(var dir=0; dir<2; ++dir) { + var nbhd = adj[dir][b] + for(var k=0; k 0) { + nextCell = e + nextVertex = p + nextDir = dir + } } } + if(noCut) { + return nextVertex + } + if(nextCell) { + cut(nextCell, nextDir) + } + return nextVertex } - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); + function extractCycle(v, dir) { + var e0 = adj[dir][v][0] + var cycle = [v] + cut(e0, dir) + var u = e0[dir^1] + var d0 = dir + while(true) { + while(u !== v) { + cycle.push(u) + u = next(cycle[cycle.length-2], u, false) + } + if(adj[0][v].length + adj[1][v].length === 0) { + break + } + var a = cycle[cycle.length-1] + var b = v + var c = cycle[1] + var d = next(a, b, true) + if(_$compareAngle_64(positions[a], positions[b], positions[c], positions[d]) < 0) { + break + } + cycle.push(v) + u = next(a, b) } + return cycle } - g.listener = listener; - this.on(type, g); + function shouldGlue(pcycle, ncycle) { + return (ncycle[1] === ncycle[ncycle.length-1]) + } - return this; -}; + for(var i=0; i 0) { + var ni = adj[0][i].length + var ncycle = extractCycle(i,j) + if(shouldGlue(pcycle, ncycle)) { + //Glue together trivial cycles + pcycle.push.apply(pcycle, ncycle) + } else { + if(pcycle.length > 0) { + cycles.push(pcycle) + } + pcycle = ncycle + } + } + if(pcycle.length > 0) { + cycles.push(pcycle) + } + } + } -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; + //Combine paths and loops together + return cycles +} +'use strict' - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +var _$trimLeaves_214 = trimLeaves - if (!this._events || !this._events[type]) - return this; +/* removed: var _$edgeToAdjacency_78 = require('edges-to-adjacency-list') */; - list = this._events[type]; - length = list.length; - position = -1; +function trimLeaves(edges, positions) { + var adj = _$edgeToAdjacency_78(edges, positions.length) + var live = new Array(positions.length) + var nbhd = new Array(positions.length) - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); + var dead = [] + for(var i=0; i 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; + while(dead.length > 0) { + var v = dead.pop() + live[v] = false + var n = adj[v] + for(var i=0; i>>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){") } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; + } else { + code.push(";if(", predicate, "){i=m;") } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); + if(reversed) { + code.push("l=m+1}else{h=m-1}") + } else { + code.push("h=m-1}else{l=m+1}") } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; + code.push("}") + if(earlyOut) { + code.push("return -1};") + } else { + code.push("return i};") } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; + return code.join("") } -function isObject(arg) { - return typeof arg === 'object' && arg !== null; +function __compileBoundsSearch_35(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_35("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), + __compileSearch_35("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), + __compileSearch_35("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), + __compileSearch_35("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() } -function isUndefined(arg) { - return arg === void 0; +var _$searchBounds_35 = { + ge: __compileBoundsSearch_35(">=", false, "GE"), + gt: __compileBoundsSearch_35(">", false, "GT"), + lt: __compileBoundsSearch_35("<", true, "LT"), + le: __compileBoundsSearch_35("<=", true, "LE"), + eq: __compileBoundsSearch_35("-", true, "EQ", true) } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* global jQuery:false */ - -var __EventEmitter_353 = _$EventEmitter_77.EventEmitter; +"use strict" -var Events = { +/* removed: var _$searchBounds_35 = require("binary-search-bounds") */; - init: function(plotObj) { +var NOT_FOUND = 0 +var SUCCESS = 1 +var EMPTY = 2 - /* - * If we have already instantiated an emitter for this plot - * return early. - */ - if(plotObj._ev instanceof __EventEmitter_353) return plotObj; +var _$createWrapper_185 = createWrapper - var ev = new __EventEmitter_353(); - var internalEv = new __EventEmitter_353(); +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 +} - /* - * Assign to plot._ev while we still live in a land - * where plot is a DOM element with stuff attached to it. - * In the future we can make plot the event emitter itself. - */ - plotObj._ev = ev; +var __proto_185 = IntervalTreeNode.prototype - /* - * Create a second event handler that will manage events *internally*. - * This allows parts of plotly to respond to thing like relayout without - * having to use the user-facing event handler. They cannot peacefully - * coexist on the same handler because a user invoking - * plotObj.removeAllListeners() would detach internal events, breaking - * plotly. - */ - plotObj._internalEv = internalEv; +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 +} - /* - * Assign bound methods from the ev to the plot object. These methods - * will reference the 'this' of plot._ev even though they are methods - * of plot. This will keep the event machinery away from the plot object - * which currently is often a DOM element but presents an API that will - * continue to function when plot becomes an emitter. Not all EventEmitter - * methods have been bound to `plot` as some do not currently add value to - * the Plotly event API. - */ - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); +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 +} - /* - * Create funtions for managing internal events. These are *only* triggered - * by the mirroring of external events via the emit function. - */ - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); +function rebuildWithInterval(node, interval) { + var intervals = node.intervals([]) + intervals.push(interval) + rebuild(node, intervals) +} - /* - * We must wrap emit to continue to support JQuery events. The idea - * is to check to see if the user is using JQuery events, if they are - * we emit JQuery events to trigger user handlers as well as the EventEmitter - * events. - */ - plotObj.emit = function(event, data) { - if(typeof jQuery !== 'undefined') { - jQuery(plotObj).trigger(event, data); - } +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 +} - ev.emit(event, data); - internalEv.emit(event, data); - }; +__proto_185.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 +} - return plotObj; - }, +__proto_185.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 = _$searchBounds_35.ge(this.leftPoints, interval, compareBegin) + var r = _$searchBounds_35.ge(this.rightPoints, interval, compareEnd) + this.leftPoints.splice(l, 0, interval) + this.rightPoints.splice(r, 0, interval) + } +} - /* - * This function behaves like jQueries triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - * - * Note: triggerHandler has been recommended for deprecation in v2.0.0, - * so the additional behavior of triggerHandler triggering internal events - * is deliberate excluded in order to avoid reinforcing more usage. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - /* - * If Jquery exists run all its handlers for this event and - * collect the return value of the LAST handler function - */ - if(typeof jQuery !== 'undefined') { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); +__proto_185.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 } - - /* - * Now run all the node style event handlers - */ - var ev = plotObj._ev; - if(!ev) return jQueryHandlerValue; - - var handlers = ev._events[event]; - if(!handlers) return jQueryHandlerValue; - - /* - * handlers can be function or an array of functions - */ - if(typeof handlers === 'function') handlers = [handlers]; - var lastHandler = handlers.pop(); - - /* - * Call all the handlers except the last one. - */ - for(var i = 0; i < handlers.length; i++) { - handlers[i](data); + 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 = _$searchBounds_35.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { + var r = cb(arr[i]) + if(r) { return r } + } +} - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; +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_185.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) + } +} -var _$Events_353 = Events; +function compareNumbers(a, b) { + return a - b +} -var _$unhover_262 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +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] +} -'use strict'; +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=0; --s) { + var n = n_stack[s] + if(d_stack[s] <= 0) { + n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) + } else { + n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) + } + } + //Rebalance tree using rotations + //console.log("start insert", key, d_stack) + for(var s=n_stack.length-1; s>1; --s) { + var p = n_stack[s-1] + var n = n_stack[s] + if(p._color === BLACK || n._color === BLACK) { + break + } + var pp = n_stack[s-2] + if(pp.left === p) { + if(p.left === n) { + var y = pp.right + if(y && y._color === RED) { + //console.log("LLr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LLb") + pp._color = RED + pp.left = p.right + p._color = BLACK + p.right = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = p + } else { + ppp.right = p + } + } + break + } + } else { + var y = pp.right + if(y && y._color === RED) { + //console.log("LRr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LRb") + p.right = n.left + pp._color = RED + pp.left = n.right + n._color = BLACK + n.left = p + n.right = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = n + } else { + ppp.right = n + } + } + break + } + } + } else { + if(p.right === n) { + var y = pp.left + if(y && y._color === RED) { + //console.log("RRr", y.key) + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RRb") + pp._color = RED + pp.right = p.left + p._color = BLACK + p.left = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = p + } else { + ppp.left = p + } + } + break + } + } else { + var y = pp.left + if(y && y._color === RED) { + //console.log("RLr") + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RLb") + p.left = n.right + pp._color = RED + pp.right = n.left + n._color = BLACK + n.right = p + n.left = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = n + } else { + ppp.left = n + } + } + break + } + } + } + } + //Return new tree + n_stack[0]._color = BLACK + return new RedBlackTree(cmp, n_stack[0]) +} - if(!gd._mouseDownTime) gd._mouseDownTime = 0; - element.style.pointerEvents = 'all'; +//Visit all nodes inorder +function doVisitFull(visit, node) { + if(node.left) { + var v = doVisitFull(visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + if(node.right) { + return doVisitFull(visit, node.right) + } +} - element.onmousedown = onStart; +//Visit half nodes in order +function doVisitHalf(lo, compare, visit, node) { + var l = compare(lo, node.key) + if(l <= 0) { + if(node.left) { + var v = doVisitHalf(lo, compare, visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + } + if(node.right) { + return doVisitHalf(lo, compare, visit, node.right) + } +} - if(!_$hasPassiveEvents_126) { - element.ontouchstart = onStart; +//Visit all nodes within a range +function doVisit(lo, hi, compare, visit, node) { + var l = compare(lo, node.key) + var h = compare(hi, node.key) + var v + if(l <= 0) { + if(node.left) { + v = doVisit(lo, hi, compare, visit, node.left) + if(v) { return v } } - else { - if(element._ontouchstart) { - element.removeEventListener('touchstart', element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener('touchstart', onStart, {passive: false}); + if(h > 0) { + v = visit(node.key, node.value) + if(v) { return v } } + } + if(h > 0 && node.right) { + return doVisit(lo, hi, compare, visit, node.right) + } +} - 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; +__proto_137.forEach = function rbTreeForEach(visit, lo, hi) { + if(!this.root) { + return + } + switch(arguments.length) { + case 1: + return doVisitFull(visit, this.root) + break - function onStart(e) { - e.preventDefault(); + case 2: + return doVisitHalf(lo, this._compare, visit, this.root) + break - // 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; + case 3: + if(this._compare(lo, hi) >= 0) { + return + } + return doVisit(lo, hi, this._compare, visit, this.root) + break + } +} - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { - // in a click train - numClicks += 1; - } - else { - // new click train - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } +//First item in list +Object.defineProperty(__proto_137, "begin", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.left + } + return new RedBlackTreeIterator(this, stack) + } +}) - if(options.prepFn) options.prepFn(e, startX, startY); +//Last item in list +Object.defineProperty(__proto_137, "end", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.right + } + return new RedBlackTreeIterator(this, stack) + } +}) - if(_$hasHover_125 && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } - else if(!_$hasHover_125) { - // 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; - } +//Find the ith item in the tree +__proto_137.at = function(idx) { + if(idx < 0) { + return new RedBlackTreeIterator(this, []) + } + var n = this.root + var stack = [] + while(true) { + stack.push(n) + if(n.left) { + if(idx < n.left._count) { + n = n.left + continue + } + idx -= n.left._count + } + if(!idx) { + return new RedBlackTreeIterator(this, stack) + } + idx -= 1 + if(n.right) { + if(idx >= n.right._count) { + break + } + n = n.right + } else { + break + } + } + return new RedBlackTreeIterator(this, []) +} - document.addEventListener('mousemove', onMove); - document.addEventListener('mouseup', onDone); - document.addEventListener('touchmove', onMove); - document.addEventListener('touchend', onDone); +__proto_137.ge = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d <= 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - return; +__proto_137.gt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d < 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - function onMove(e) { - e.preventDefault(); +__proto_137.lt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d > 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_412.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; +__proto_137.le = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d >= 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - if(dx || dy) { - gd._dragged = true; - dragElement.unhover(gd); - } +//Finds the item with key if it exists +__proto_137.find = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d === 0) { + return new RedBlackTreeIterator(this, stack) + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + return new RedBlackTreeIterator(this, []) +} - if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); +//Removes item with key from tree +__proto_137.remove = function(key) { + var iter = this.find(key) + if(iter) { + return iter.remove() + } + return this +} - return; +//Returns the item at `key` +__proto_137.get = function(key) { + var cmp = this._compare + var n = this.root + while(n) { + var d = cmp(key, n.key) + if(d === 0) { + return n.value + } + if(d <= 0) { + n = n.left + } else { + n = n.right } + } + return +} - function onDone(e) { - document.removeEventListener('mousemove', onMove); - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchmove', onMove); - document.removeEventListener('touchend', onDone); +//Iterator for red black tree +function RedBlackTreeIterator(tree, stack) { + this.tree = tree + this._stack = stack +} - e.preventDefault(); +var iproto = RedBlackTreeIterator.prototype + +//Test if iterator is valid +Object.defineProperty(iproto, "valid", { + get: function() { + return this._stack.length > 0 + } +}) + +//Node of the iterator +Object.defineProperty(iproto, "node", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1] + } + return null + }, + enumerable: true +}) + +//Makes a copy of an iterator +iproto.clone = function() { + return new RedBlackTreeIterator(this.tree, this._stack.slice()) +} + +//Swaps two nodes +function swapNode(n, v) { + n.key = v.key + n.value = v.value + n.left = v.left + n.right = v.right + n._color = v._color + n._count = v._count +} - if(_$hasHover_125) { - _$lib_363.removeElement(dragCover); +//Fix up a double black node in a tree +function fixDoubleBlack(stack) { + var n, p, s, z + for(var i=stack.length-1; i>=0; --i) { + n = stack[i] + if(i === 0) { + n._color = BLACK + return + } + //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) + p = stack[i-1] + if(p.left === n) { + //console.log("left child") + s = p.right + if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.right = cloneNode(s) + z = s.right = cloneNode(s.right) + p.right = s.left + s.left = p + s.right = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } } - else if(cursor) { - dragCover.documentElement.style.cursor = cursor; - cursor = null; + stack[i-1] = s + return + } else if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red") + s = p.right = cloneNode(s) + z = s.left = cloneNode(s.left) + p.right = z.left + s.left = z.right + z.left = p + z.right = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = z + } else { + pp.right = z + } } - - if(!gd._dragging) { - gd._dragged = false; - return; + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent", p.right.value) + p._color = BLACK + p.right = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent", p.right.value) + p.right = repaint(RED, s) + continue } - gd._dragging = false; - - // don't count as a dblClick unless the mouseUp is also within - // the dblclick delay - if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.right = s.left + s.left = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } } - - if(gd._dragged) { - if(options.doneFn) options.doneFn(e); + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } + } else { + //console.log("right child") + s = p.left + if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red", p.value, p._color) + s = p.left = cloneNode(s) + z = s.left = cloneNode(s.left) + p.left = s.right + s.right = p + s.left = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + return + } else if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.left = cloneNode(s) + z = s.right = cloneNode(s.right) + p.left = z.right + s.right = z.left + z.right = p + z.left = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = z + } else { + pp.left = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent") + p._color = BLACK + p.left = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent") + p.left = repaint(RED, s) + continue } - else { - 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); - } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.left = s.right + s.right = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } } - - finishDrag(gd); - - gd._dragged = false; - - return; + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } } -}; - -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 finishDrag(gd) { - gd._dragging = false; - if(gd._replotPending) _$registry_451.call('plot', gd); -} - -function pointerOffset(e) { - return _$mouseEventOffset_138( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); + } } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$registry_451 = require('../../registry'); */; - -var _$calc_274 = function calc(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; - - function makeCoerceHoverInfo(trace) { - return function(val) { - return _$lib_363.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); - }; +//Removes item at iterator from tree +iproto.remove = function() { + var stack = this._stack + if(stack.length === 0) { + return this.tree + } + //First copy path to node + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + var n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } + } - 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_451.traceIs(trace, 'pie')) continue; - - var fillFn = _$registry_451.traceIs(trace, '2dMap') ? paste : _$lib_363.fillArray; - - fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + //Get node + n = cstack[cstack.length-1] + //console.log("start remove: ", n.value) - if(!trace.hoverlabel) continue; + //If not leaf, then swap with previous node + if(n.left && n.right) { + //console.log("moving to leaf") - 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'); + //First walk to previous leaf + var split = cstack.length + n = n.left + while(n.right) { + cstack.push(n) + n = n.right } -}; + //Copy path to leaf + var v = cstack[split-1] + cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) + cstack[split-1].key = n.key + cstack[split-1].value = n.value -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_363.identity; + //Fix up stack + for(var i=cstack.length-2; i>=split; --i) { + n = cstack[i] + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + cstack[split-1].left = cstack[split] + } + //console.log("stack=", cstack.map(function(v) { return v.value })) - if(Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); + //Remove leaf node + n = cstack[cstack.length-1] + if(n._color === RED) { + //Easy case: removing red leaf + //console.log("RED leaf") + var p = cstack[cstack.length-2] + if(p.left === n) { + p.left = null + } else if(p.right === n) { + p.right = null + } + cstack.pop() + for(var i=0; i 0) { + return this._stack[this._stack.length-1].key + } + return + }, + enumerable: true +}) -'use strict'; +//Returns value +Object.defineProperty(iproto, "value", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1].value + } + return + }, + enumerable: true +}) -/* removed: var _$lib_363 = require('../../lib'); */; -// look for either subplot or xaxis and yaxis attributes -_$helpers_278.getSubplot = function getSubplot(trace) { - return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; -}; +//Returns the position of this iterator in the sorted list +Object.defineProperty(iproto, "index", { + get: function() { + var idx = 0 + var stack = this._stack + if(stack.length === 0) { + var r = this.tree.root + if(r) { + return r._count + } + return 0 + } else if(stack[stack.length-1].left) { + idx = stack[stack.length-1].left._count + } + for(var s=stack.length-2; s>=0; --s) { + if(stack[s+1] === stack[s].right) { + ++idx + if(stack[s].left) { + idx += stack[s].left._count + } + } + } + return idx + }, + enumerable: true +}) -// convenience functions for mapping all relevant axes -_$helpers_278.flat = function flat(subplots, v) { - var out = new Array(subplots.length); - for(var i = 0; i < subplots.length; i++) { - out[i] = v; +//Advances iterator to next element in list +iproto.next = function() { + var stack = this._stack + if(stack.length === 0) { + return + } + var n = stack[stack.length-1] + if(n.right) { + n = n.right + while(n) { + stack.push(n) + n = n.left } - return out; -}; + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].right === n) { + n = stack[stack.length-1] + stack.pop() + } + } +} -_$helpers_278.p2c = function p2c(axArray, v) { - var out = new Array(axArray.length); - for(var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); +//Checks if iterator is at end of tree +Object.defineProperty(iproto, "hasNext", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false } - return out; -}; + if(stack[stack.length-1].right) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].left === stack[s]) { + return true + } + } + return false + } +}) -_$helpers_278.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { - if(mode === 'closest') return dxy || _$helpers_278.quadrature(dx, dy); - return mode === 'x' ? dx : dy; -}; +//Update value +iproto.update = function(value) { + var stack = this._stack + if(stack.length === 0) { + throw new Error("Can't update empty node!") + } + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + } + return new RedBlackTree(this.tree._compare, cstack[0]) +} -_$helpers_278.getClosest = function getClosest(cd, distfn, pointData) { - // do we already have a point number? (array mode only) - if(pointData.index !== false) { - if(pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } - else pointData.index = false; +//Moves iterator backward one element +iproto.prev = function() { + var stack = this._stack + if(stack.length === 0) { + return + } + var n = stack[stack.length-1] + if(n.left) { + n = n.left + while(n) { + stack.push(n) + n = n.right } - else { - // apply the distance function to each data point - // this is the longest loop... if this bogs down, we may need - // to create pre-sorted data (by x or y), not sure how to - // do this for 'closest' - for(var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if(newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } - } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].left === n) { + n = stack[stack.length-1] + stack.pop() } - return pointData; -}; + } +} -/* - * pseudo-distance function for hover effects on areas: inside the region - * distance is finite (`passVal`), outside it's Infinity. - * - * @param {number} v0: signed difference between the current position and the left edge - * @param {number} v1: signed difference between the current position and the right edge - * @param {number} passVal: the value to return on success - */ -_$helpers_278.inbox = function inbox(v0, v1, passVal) { - return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; -}; +//Checks if iterator is at start of tree +Object.defineProperty(iproto, "hasPrev", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].left) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].right === stack[s]) { + return true + } + } + return false + } +}) -_$helpers_278.quadrature = function quadrature(dx, dy) { - return function(di) { - var x = dx(di), - y = dy(di); - return Math.sqrt(x * x + y * y); - }; -}; +//Default comparison function +function defaultCompare(a, b) { + if(a < b) { + return -1 + } + if(a > b) { + return 1 + } + return 0 +} -/** Fill event data point object for hover and selection. - * Invokes _module.eventData if present. - * - * N.B. note that point 'index' corresponds to input data array index - * whereas 'number' is its post-transform version. - * - * If the hovered/selected pt corresponds to an multiple input points - * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' - * are include in the event data. - * - * @param {object} pt - * @param {object} trace - * @param {object} cd - * @return {object} - */ -_$helpers_278.makeEventData = function makeEventData(pt, trace, cd) { - // hover uses 'index', select uses 'pointNumber' - var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; +//Build a tree +function createRBTree(compare) { + return new RedBlackTree(compare || defaultCompare, null) +} +"use strict" - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber: pointNumber - }; +var _$orderSegments_253 = orderSegments - if(trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; +/* removed: var _$orientation_242 = require("robust-orientation") */; - if(pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; +function horizontalOrder(a, b) { + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + var alo = Math.min(a[0][1], a[1][1]) + var ahi = Math.max(a[0][1], a[1][1]) + var blo = Math.min(b[0][1], b[1][1]) + var bhi = Math.max(b[0][1], b[1][1]) + if(ahi < blo) { + return ahi - blo } + if(alo > bhi) { + return alo - bhi + } + return ahi - bhi + } + var al, ar + if(a[0][1] < a[1][1]) { + al = a[0] + ar = a[1] + } else { + al = a[1] + ar = a[0] + } + var d = _$orientation_242(br, bl, al) + if(d) { + return d + } + d = _$orientation_242(br, bl, ar) + if(d) { + return d + } + return ar - br +} - if(trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if('xVal' in pt) out.x = pt.xVal; - else if('x' in pt) out.x = pt.x; - - if('yVal' in pt) out.y = pt.yVal; - else if('y' in pt) out.y = pt.y; - - if(pt.xa) out.xaxis = pt.xa; - if(pt.ya) out.yaxis = pt.ya; - if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; +function orderSegments(b, a) { + var al, ar + if(a[0][0] < a[1][0]) { + al = a[0] + ar = a[1] + } else if(a[0][0] > a[1][0]) { + al = a[1] + ar = a[0] + } else { + return horizontalOrder(a, b) + } + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + return -horizontalOrder(b, a) + } + var d1 = _$orientation_242(al, ar, br) + var d2 = _$orientation_242(al, ar, bl) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } - - _$helpers_278.appendArrayPointValue(out, trace, pointNumber); - - return out; -}; - -/** Appends values inside array attributes corresponding to given point number - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {number|Array(number)} pointNumber : point number. May be a length-2 array - * [row, col] to dig into 2D arrays - */ -_$helpers_278.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; - - if(!arrayAttrs) { - return; + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } - - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); - - if(pointData[key] === undefined) { - var val = _$lib_363.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); - - if(pointVal !== undefined) pointData[key] = pointVal; - } + } else if(d2) { + return d2 + } + d1 = _$orientation_242(br, bl, ar) + d2 = _$orientation_242(br, bl, al) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } -}; - -/** - * Appends values inside array attributes corresponding to given point number array - * For use when pointData references a plot entity that arose (or potentially arose) - * from multiple points in the input data - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. - * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays - */ -_$helpers_278.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; - - if(!arrayAttrs) { - return; + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } + } else if(d2) { + return d2 + } + return ar[0] - br[0] +} +"use strict" - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); +var _$createSlabDecomposition_254 = createSlabDecomposition - if(pointData[key] === undefined) { - var val = _$lib_363.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); +/* removed: var _$searchBounds_35 = require("binary-search-bounds") */; +/* removed: var _$createRBTree_137 = require("functional-red-black-tree") */; +/* removed: var _$orientation_242 = require("robust-orientation") */; +/* removed: var _$orderSegments_253 = require("./lib/order-segments") */; - for(var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); - } - pointData[key] = keyVal; - } - } -}; +function SlabDecomposition(slabs, coordinates, horizontal) { + this.slabs = slabs + this.coordinates = coordinates + this.horizontal = horizontal +} -var pointKeyMap = { - ids: 'id', - locations: 'location', - labels: 'label', - values: 'value', - 'marker.colors': 'color' -}; +var __proto_254 = SlabDecomposition.prototype -function getPointKey(astr) { - return pointKeyMap[astr] || astr; +function compareHorizontal(e, y) { + return e.y - y } -function getPointData(val, pointNumber) { - if(Array.isArray(pointNumber)) { - if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; +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 = _$orientation_242(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 { - return val[pointNumber]; + if(p[0] !== seg[1][0]) { + return root + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } } + } + return lastNode } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -// works with our CSS cursor classes (see css/_cursor.scss) -// to apply cursors to d3 single-element selections. -// omit cursor to revert to the default. -var _$setCursor_382 = function setCursor(el3, csr) { - (el3.attr('class') || '').split(' ').forEach(function(cls) { - if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); - }); - - if(csr) el3.classed('cursor-' + csr, true); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$setCursor_382 = require('./setcursor'); */; - -var STASHATTR = 'data-savedcursor'; -var NO_CURSOR = '!!'; - -/* - * works with our CSS cursor classes (see css/_cursor.scss) - * to override a previous cursor set on d3 single-element selections, - * by moving the name of the original cursor to the data-savedcursor attr. - * omit cursor to revert to the previously set value. - */ -var _$overrideCursor_374 = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if(csr) { - if(!savedCursor) { - var classes = (el3.attr('class') || '').split(' '); - for(var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if(cls.indexOf('cursor-') === 0) { - el3.attr(STASHATTR, cls.substr(7)) - .classed(cls, false); - } +__proto_254.castUp = function(p) { + var bucket = _$searchBounds_35.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_253(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 = _$searchBounds_35.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(!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); + if(e.y === p[1] && !e.start) { + hbucket = hbucket+1 + if(hbucket >= horiz.length) { + return lastHit + } + e = horiz[hbucket] } + } } - _$setCursor_382(el3, csr); - } - else if(savedCursor) { - el3.attr(STASHATTR, null); - - if(savedCursor === NO_CURSOR) _$setCursor_382(el3); - else _$setCursor_382(el3, savedCursor); + //Check if e is above/below last segment + if(e.start) { + if(lastSegment) { + var o = _$orientation_242(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 + } + } } -}; - -var _$hover_279 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$Events_353 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_374 = require('../../lib/override_cursor'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_451 = require('../../registry'); */; - -/* removed: var _$helpers_278 = require('./helpers'); */; -/* removed: var _$constants_276 = require('./constants'); */; - -// hover labels for multiple horizontal bars get tilted by some angle, -// then need to be offset differently if they overlap -var YANGLE = _$constants_276.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; - -// expansion of projected height -var YFACTOR = 1 / Math.sin(YA_RADIANS); - -// to make the appropriate post-rotation x offset, -// you need both x and y offsets -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); - -// size and display constants for hover text -var HOVERARROWSIZE = _$constants_276.HOVERARROWSIZE; -var HOVERTEXTPAD = _$constants_276.HOVERTEXTPAD; - -// fx.hover: highlight data on hover -// evt can be a mousemove event, or an object with data about what points -// to hover on -// {xpx,ypx[,hovermode]} - pixel locations from top left -// (with optional overriding hovermode) -// {xval,yval[,hovermode]} - data values -// [{curveNumber,(pointNumber|xval and/or yval)}] - -// array of specific points to highlight -// pointNumber is a single integer if gd.data[curveNumber] is 1D, -// or a two-element array if it's 2D -// xval and yval are data values, -// 1D data may specify either or both, -// 2D data must specify both -// subplot is an id string (default "xy") -// makes use of gl.hovermode, which can be: -// x (find the points with the closest x values, ie a column), -// closest (find the single closest point) -// internally there are two more that occasionally get used: -// y (pick out a row - only used for multiple horizontal bar charts) -// array (used when the user specifies an explicit -// array of points to hover on) -// -// We wrap the hovers in a timer, to limit their frequency. -// The actual rendering is done by private function _hover. -_$hover_279.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_363.getGraphDiv(gd); - - _$lib_363.throttle( - gd._fullLayout._uid + _$constants_276.HOVERID, - _$constants_276.HOVERMINTIME, - function() { _hover(gd, evt, subplot, noHoverEvent); } - ); -}; - -/* - * Draw a single hover item in a pre-existing svg container somewhere - * hoverItem should have keys: - * - x and y (or x0, x1, y0, and y1): - * the pixel position to mark, relative to opts.container - * - xLabel, yLabel, zLabel, text, and name: - * info to go in the label - * - color: - * the background color for the label. - * - idealAlign (optional): - * 'left' or 'right' for which side of the x/y box to try to put this on first - * - borderColor (optional): - * color for the border, defaults to strongest contrast with color - * - fontFamily (optional): - * string, the font for this label, defaults to constants.HOVERFONT - * - fontSize (optional): - * the label font size, defaults to constants.HOVERFONTSIZE - * - fontColor (optional): - * defaults to borderColor - * opts should have keys: - * - bgColor: - * the background color this is against, used if the trace is - * non-opaque, and for the name, which goes outside the box - * - container: - * a or element to add the hover label to - * - outerContainer: - * normally a parent of `container`, sets the bounding box to use to - * constrain the hover label and determine whether to show it on the left or right - */ -_$hover_279.loneHover = function loneHover(hoverItem, opts) { - var pointData = { - color: hoverItem.color || _$color_239.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, - - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, - - // filler to make createHoverText happy - trace: { - index: 0, - hoverinfo: '' - }, - xa: {_offset: 0}, - ya: {_offset: 0}, - index: 0 - }; - - var container3 = _$d3_68.select(opts.container), - outerContainer3 = opts.outerContainer ? - _$d3_68.select(opts.outerContainer) : container3; - - var fullOpts = { - hovermode: 'closest', - rotateLabels: false, - bgColor: opts.bgColor || _$color_239.background, - container: container3, - outerContainer: outerContainer3 - }; - - var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); - alignHoverText(hoverLabel, fullOpts.rotateLabels); - - return hoverLabel.node(); -}; - -// The actual implementation is here: -function _hover(gd, evt, subplot, noHoverEvent) { - if(!subplot) subplot = 'xy'; + } + return lastHit +} - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; +function IntervalSegment(y, index, start, closed) { + this.y = y + this.index = index + this.start = start + this.closed = closed +} - var fullLayout = gd._fullLayout; - var plots = fullLayout._plots || []; - var plotinfo = plots[subplot]; - var hasCartesian = fullLayout._has('cartesian'); +function __Event_254(x, segment, create, index) { + this.x = x + this.segment = segment + this.create = create + this.index = index +} - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); - subplots = subplots.concat(overlayedSubplots); +function createSlabDecomposition(segments) { + var numSegments = segments.length + var numEvents = 2 * numSegments + var events = new Array(numEvents) + 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_219(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 } - - // [x|y]px: the pixels (from top left) of the mouse location - // on the currently selected plot area - // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation - var hasUserCalledHover = !evt.target, - xpx, ypx; - - if(hasUserCalledHover) { - if('xpx' in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - evt.pointerX = xpx + xaArray[0]._offset; - - if('ypx' in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - evt.pointerY = ypx + yaArray[0]._offset; + } else { + if(o > 0) { + root = root.left + } else if(o < 0) { + lastOrientation = 1 + root = root.right + } else { + return 0 } - else { - // fire the beforehover event and quit if it returns false - // note that we're only calling this on real mouse events, so - // manual calls to fx.hover will always run. - if(_$Events_353.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } - - var dbb = evt.target.getBoundingClientRect(); + } + } + return lastOrientation + } +} - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; +function classifyEmpty(p) { + return 1 +} - // in case hover was called from mouseout into hovertext, - // it's possible you're not actually over the plot anymore - if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { - return _$dragelement_261.unhoverRaw(gd, evt); - } - evt.pointerX = evt.offsetX; - evt.pointerY = evt.offsetY; - } +function createClassifyVertical(testVertical) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return 1 + } +} - if('xval' in evt) xvalArray = _$helpers_278.flat(subplots, evt.xval); - else xvalArray = _$helpers_278.p2c(xaArray, xpx); +function createClassifyPointDegen(testVertical, testNormal) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return testNormal(p) + } +} - if('yval' in evt) yvalArray = _$helpers_278.flat(subplots, evt.yval); - else yvalArray = _$helpers_278.p2c(yaArray, ypx); +function preprocessPolygon(loops) { + //Compute number of loops + var numLoops = loops.length - if(!_$fastIsnumeric_78(xvalArray[0]) || !_$fastIsnumeric_78(yvalArray[0])) { - _$lib_363.warn('Fx.hover failed', evt, gd); - return _$dragelement_261.unhoverRaw(gd, evt); - } + //Unpack segments + var segments = [] + var vsegments = [] + var ptr = 0 + for(var i=0; i 0 + } - closedataPreviousLength = hoverData.length; + //Extract all clockwise faces + faces = faces.filter(ccw) - // for a highlighting array, figure out what - // we're searching for with this element - if(mode === 'array') { - var selection = evt[curvenum]; - if('pointNumber' in selection) { - pointData.index = selection.pointNumber; - mode = 'closest'; - } - else { - mode = ''; - if('xval' in selection) { - xval = selection.xval; - mode = 'x'; - } - if('yval' in selection) { - yval = selection.yval; - mode = mode ? 'closest' : 'y'; - } - } - } - else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; + //Detect which loops are contained in one another to handle parent-of relation + var numFaces = faces.length + var parent = new Array(numFaces) + var containment = new Array(numFaces) + for(var i=0; i closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; - } + //Build adjacency matrix for edges + var edgeAdjacency = {} + var internalVertices = makeArray(numVertices, false) + for(var i=0; i tmpPoint.spikeDistance)) { - spikePoints.vLinePoint = tmpPoint; - } - } - } + function sharedBoundary(c) { + var n = c.length + for(var i=0; i tmpPoint.spikeDistance)) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } - } - } + var toVisit = [] + var parity = makeArray(numFaces, -1) + for(var i=0; i 0) { + var top = toVisit.pop() + var nbhd = fadj[top] + _$unique_271(nbhd, function(a,b) { + return a-b + }) + var nnbhr = nbhd.length + var p = parity[top] + var polyline + if(p === 0) { + var c = faces[top] + polyline = [c] } - - function selectClosestPoint(pointsData, spikedistance) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for(var i = 0; i < pointsData.length; i++) { - thisSpikeDistance = pointsData[i].spikeDistance; - if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { - resultPoint = pointsData[i]; - minDistance = thisSpikeDistance; - } + for(var i=0; i= 0) { + continue + } + parity[f] = p^1 + toVisit.push(f) + if(p === 0) { + var c = faces[f] + if(!sharedBoundary(c)) { + c.reverse() + polyline.push(c) } - return resultPoint; + } } - - function fillSpikePoint(point) { - if(!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; + if(p === 0) { + result.push(polyline) } + } - var spikelineOpts = { - fullLayout: fullLayout, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - event: evt - }; - var oldspikepoints = gd._spikepoints, - newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; + return result +} +var _$twiddle_249 = {}; +/** + * Bit twiddling hacks for JavaScript. + * + * Author: Mikola Lysenko + * + * Ported from Stanford bit twiddling hack library: + * http://graphics.stanford.edu/~seander/bithacks.html + */ - // Now if it is not restricted by spikedistance option, set the points to draw the spikelines - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); +"use strict"; "use restrict"; - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); - } - } +//Number of bits in an integer +var __INT_BITS_249 = 32; - // if hoverData is empty check for the spikes to draw and quit if there are none - if(hoverData.length === 0) { - var result = _$dragelement_261.unhoverRaw(gd, evt); - if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } - return result; - } +//Constants +_$twiddle_249.INT_BITS = __INT_BITS_249; +_$twiddle_249.INT_MAX = 0x7fffffff; +_$twiddle_249.INT_MIN = -1<<(__INT_BITS_249-1); - if(hasCartesian) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } - } +//Returns -1, 0, +1 depending on sign of x +_$twiddle_249.sign = function(v) { + return (v > 0) - (v < 0); +} - hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); +//Computes absolute value of integer +_$twiddle_249.abs = function(v) { + var mask = v >> (__INT_BITS_249-1); + return (v ^ mask) - mask; +} - // lastly, emit custom hover/unhover events - var oldhoverdata = gd._hoverdata, - newhoverdata = []; +//Computes minimum of integers x and y +_$twiddle_249.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} - // pull out just the data that's useful to - // other people and send it to the event - for(itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - newhoverdata.push(_$helpers_278.makeEventData(pt, pt.trace, pt.cd)); - } +//Computes maximum of integers x and y +_$twiddle_249.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} - gd._hoverdata = newhoverdata; +//Checks if a number is a power of two +_$twiddle_249.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} - // if there's more than one horz bar trace, - // rotate the labels so they don't overlap - var rotateLabels = hovermode === 'y' && searchData.length > 1; +//Computes log base 2 of v +_$twiddle_249.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} - var bgColor = _$color_239.combine( - fullLayout.plot_bgcolor || _$color_239.background, - fullLayout.paper_bgcolor - ); +//Computes log base 10 of v +_$twiddle_249.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} - var labelOpts = { - hovermode: hovermode, - rotateLabels: rotateLabels, - bgColor: bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }; +//Counts number of bits +_$twiddle_249.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} - var hoverLabels = createHoverText(hoverData, labelOpts, gd); +//Counts number of trailing zeros +function __countTrailingZeros_249(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +_$twiddle_249.countTrailingZeros = __countTrailingZeros_249; - hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); +//Rounds to next power of 2 +_$twiddle_249.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} - alignHoverText(hoverLabels, rotateLabels); +//Rounds down to previous power of 2 +_$twiddle_249.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} - // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true - // we should improve the "fx" API so other plots can use it without these hack. - if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_451.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_374(_$d3_68.select(evt.target), hasClickToShow ? 'pointer' : ''); - } +//Computes parity of word +_$twiddle_249.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} - // don't emit events if called manually - if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; +var __REVERSE_TABLE_249 = new Array(256); - if(oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; } + tab[i] = (r << s) & 0xff; + } +})(__REVERSE_TABLE_249); - gd.emit('plotly_hover', { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); +//Reverse bits in a 32 bit word +_$twiddle_249.reverse = function(v) { + return (__REVERSE_TABLE_249[ v & 0xff] << 24) | + (__REVERSE_TABLE_249[(v >>> 8) & 0xff] << 16) | + (__REVERSE_TABLE_249[(v >>> 16) & 0xff] << 8) | + __REVERSE_TABLE_249[(v >>> 24) & 0xff]; } -function createHoverText(hoverData, opts, gd) { - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +_$twiddle_249.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; - // opts.fontFamily/Size are used for the common label - // and as defaults for each hover label, though the individual labels - // can override this. - var fontFamily = opts.fontFamily || _$constants_276.HOVERFONT; - var fontSize = opts.fontSize || _$constants_276.HOVERFONTSIZE; + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; - var t0 = c0[commonAttr]; - var t00 = (String(t0) || '').split(' ')[0]; - var outerContainerBB = outerContainer.node().getBoundingClientRect(); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; + return x | (y << 1); +} - // show the common label, if any, on the axis - // never show a common label in array mode, - // even if sometimes there could be one - var showCommonLabel = ( - (t0 !== undefined) && - (c0.distance <= opts.hoverdistance) && - (hovermode === 'x' || hovermode === 'y') - ); +//Extracts the nth interleaved component +_$twiddle_249.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} - // all hover traces hoverinfo must contain the hovermode - // to have common labels - if(showCommonLabel) { - var i, traceHoverinfo; - var allHaveZ = true; - for(i = 0; i < hoverData.length; i++) { - if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); - if(parts.indexOf('all') === -1 && - parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; - } - } +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +_$twiddle_249.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; - // xyz labels put all info in their main label, so have no need of a common label - if(allHaveZ) showCommonLabel = false; - } + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} - var commonLabel = container.selectAll('g.axistext') - .data(showCommonLabel ? [0] : []); - commonLabel.enter().append('g') - .classed('axistext', true); - commonLabel.exit().remove(); +//Extracts nth interleaved component of a 3-tuple +_$twiddle_249.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} - commonLabel.each(function() { - var label = _$d3_68.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +_$twiddle_249.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (__countTrailingZeros_249(v) + 1)); +} - lpath.enter().append('path') - .style({'stroke-width': '1px'}); - lpath.style({ - fill: commonLabelOpts.bgcolor || _$color_239.defaultLine, - stroke: commonLabelOpts.bordercolor || _$color_239.background, - }); +"use strict"; "use restrict"; - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); +var _$UnionFind_251 = __UnionFind_251; - ltext.text(t0) - .call(_$drawing_264.font, - commonLabelOpts.font.family || fontFamily, - commonLabelOpts.font.size || fontSize, - commonLabelOpts.font.color || _$color_239.background - ) - .call(_$svg_text_utils_386.positionText, 0, 0) - .call(_$svg_text_utils_386.convertToTspans, gd); +function __UnionFind_251(count) { + this.roots = new Array(count); + this.ranks = new Array(count); + + for(var i=0; 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 +} +_$topology_250.findCell = findCell; - if(nameLength > -1 && name.length > nameLength) { - if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; - else name = name.substr(0, nameLength); - } +//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 +} +_$topology_250.incidence = incidence - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; +//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_250(skeleton(cells, 0)), cells, 0) + } + var res = new Array(vertex_count) + for(var i=0; i'; - if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; - text += (text ? 'z: ' : '') + d.zLabel; - } - else if(showCommonLabel && d[hovermode + 'Label'] === t0) { - text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; - } - else if(d.xLabel === undefined) { - if(d.yLabel !== undefined) text = d.yLabel; +//Enumerates all cells in the complex +function explode(cells) { + var result = [] + for(var i=0, il=cells.length; i>> k) & 1) { + b.push(c[k]) } - else if(d.yLabel === undefined) text = d.xLabel; - else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; + } + result.push(b) + } + } + return normalize(result) +} +_$topology_250.explode = explode - if(d.text && !Array.isArray(d.text)) { - text += (text ? '
' : '') + d.text; +//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= 0; - if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - hty += dy / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } - else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - htx += dx / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } +var _$simplifyPolygon_252 = simplifyPolygon - tx.attr('text-anchor', d.anchor); - if(tx2width) tx2.attr('text-anchor', d.anchor); - g.attr('transform', 'translate(' + htx + ',' + hty + ')' + - (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); - }); +/* removed: var _$orientation_242 = require("robust-orientation") */; +/* removed: var _$topology_250 = require("simplicial-complex") */; - return hoverLabels; +function errorWeight(base, a, b) { + var area = Math.abs(_$orientation_242(base, a, b)) + var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2)) + return area / perim } -// Make groups of touching points, and within each group -// move each point so that no labels overlap, but the average -// label position is the same as it was before moving. Indicentally, -// this is equivalent to saying all the labels are on equal linear -// springs about their initial position. Initially, each point is -// its own group, but as we find overlaps we will clump the points. -// -// Also, there are hard constraints at the edges of the graphs, -// that push all groups to the middle so they are visible. I don't -// know what happens if the group spans all the way from one edge to -// the other, though it hardly matters - there's just too much -// information then. -function hoverAvoidOverlaps(hoverData, ax, fullLayout) { - var nummoves = 0, +function simplifyPolygon(cells, positions, minArea) { - // make groups of touching points - pointgroups = hoverData - .map(function(d, i) { - var axis = d[ax]; - return [{ - i: i, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, - pmin: 0, - pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) - }]; - }) - .sort(function(a, b) { return a[0].posref - b[0].posref; }), - donepositioning, - topOverlap, - bottomOverlap, - i, j, - pti, - sumdp; + var n = positions.length + var nc = cells.length + var inv = new Array(n) + var outv = new Array(n) + var weights = new Array(n) + var dead = new Array(n) + + //Initialize tables + for(var i=0; i 0.01) { - for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; - donepositioning = false; + //Returns the weight of node i on the heap + function heapWeight(i) { + return weights[heap[i]] + } + + function heapParent(i) { + if(i & 1) { + return (i - 1) >> 1 + } + return (i >> 1) - 1 + } + + //Bubble element i down the heap + function heapDown(i) { + var w = heapWeight(i) + while(true) { + var tw = w + var left = 2*i + 1 + var right = 2*(i + 1) + var next = i + if(left < heapCount) { + var lw = heapWeight(left) + if(lw < tw) { + next = left + tw = lw } - if(bottomOverlap < 0.01) return; - if(topOverlap < -0.01) { - // make sure we're not pushing back and forth - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - donepositioning = false; + } + if(right < heapCount) { + var rw = heapWeight(right) + if(rw < tw) { + next = right } - if(!donepositioning) return; + } + if(next === i) { + return i + } + heapSwap(i, next) + i = next + } + } + + //Bubbles element i up the heap + function heapUp(i) { + var w = heapWeight(i) + while(i > 0) { + var parent = heapParent(i) + if(parent >= 0) { + var pw = heapWeight(parent) + if(w < pw) { + heapSwap(i, parent) + i = parent + continue + } + } + return i + } + } - // no room to fix positioning, delete off-screen points + //Pop minimum element + function heapPop() { + if(heapCount > 0) { + var head = heap[0] + heapSwap(0, heapCount-1) + heapCount -= 1 + heapDown(0) + return head + } + return -1 + } - // first see how many points we need to delete - var deleteCount = 0; - for(i = 0; i < grp.length; i++) { - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; - } + //Update heap item i + function heapUpdate(i, w) { + var a = heap[i] + if(weights[a] === w) { + return i + } + weights[a] = -Infinity + heapUp(i) + heapPop() + weights[a] = w + heapCount += 1 + return heapUp(heapCount-1) + } - // start by deleting points whose data is off screen - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; + //Kills a vertex (assume vertex already removed from heap) + function kill(i) { + if(dead[i]) { + return + } + //Kill vertex + dead[i] = true + //Fixup topology + var s = inv[i] + var t = outv[i] + if(inv[t] >= 0) { + inv[t] = s + } + if(outv[s] >= 0) { + outv[s] = t + } - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; - } - } - for(i = 0; i < grp.length; i++) { - if(deleteCount <= 0) break; - pti = grp[i]; + //Update weights on s and t + if(index[s] >= 0) { + heapUpdate(index[s], computeWeight(s)) + } + if(index[t] >= 0) { + heapUpdate(index[t], computeWeight(t)) + } + } - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; + //Initialize weights and heap + var heap = [] + var index = new Array(n) + for(var i=0; i>1; i>=0; --i) { + heapDown(i) + } + + //Kill vertices + while(true) { + var hmin = heapPop() + if((hmin < 0) || (weights[hmin] > minArea)) { + break + } + kill(hmin) + } - // shift the whole group minus into this new space - bottomOverlap = pti.size * 2; - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - } - } - // then delete points that go off the bottom - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; - } - } + //Build collapsed vertex table + var npositions = [] + for(var i=0; i= 0 && tout >= 0 && tin !== tout) { + var cin = index[tin] + var cout = index[tout] + if(cin !== cout) { + ncells.push([ cin, cout ]) + } + } + }) - // Only group points that lie on the same axes - if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { - // push the new point(s) added to this group out of the way - for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; + //Normalize result + _$topology_250.unique(_$topology_250.normalize(ncells)) - // add them to the group - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); + //Return final list of cells + return { + positions: npositions, + edges: ncells + } +} +"use strict" - // adjust for minimum average movement - sumdp = 0; - for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; - } - else i++; - } +/* removed: var _$pool_269 = require("typedarray-pool") */; - // check if we're going off the plot on either side and fix - pointgroups.forEach(constrainGroup); - } +var _$createSurfaceExtractor_199 = createSurfaceExtractor - // now put these offsets into hoverData - for(i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for(j = grp.length - 1; j >= 0; j--) { - var pt = grp[j], - hoverPt = hoverData[pt.i]; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; - } +//Helper macros +function array(i) { + return "a" + i +} +function data(i) { + return "d" + i +} +function cube(i,bitmask) { + return "c" + i + "_" + bitmask +} +function shape(i) { + return "s" + i +} +function stride(i,j) { + return "t" + i + "_" + j +} +function offset(i) { + return "o" + i +} +function scalar(i) { + return "x" + i +} +function pointer(i) { + return "p" + i +} +function delta(i,bitmask) { + return "d" + i + "_" + bitmask +} +function index(i) { + return "i" + i +} +function step(i,j) { + return "u" + i + "_" + j +} +function pcube(bitmask) { + return "b" + bitmask +} +function qcube(bitmask) { + return "y" + bitmask +} +function pdelta(bitmask) { + return "e" + bitmask +} +function vert(i) { + return "v" + i +} +var VERTEX_IDS = "V" +var PHASES = "P" +var VERTEX_COUNT = "N" +var POOL_SIZE = "Q" +var POINTER = "X" +var TEMPORARY = "T" + +function permBitmask(dimension, mask, order) { + var r = 0 + for(var i=0; i 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) + "]") } - else d.yLabel += ' ± ' + yeText; - - if(hovermode === 'y') d.distance += 1; + 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) +} +var _$gamma_138 = {}; +// transliterated from the python snippet here: +// http://en.wikipedia.org/wiki/Lanczos_approximation - // Horizontal line (to y-axis) - if(showY) { - var hLinePoint = closestPoints.hLinePoint, - hLinePointX, - hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; +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 +]; - if(ySnap === 'cursor') { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; - } - var dfltHLineColor = _$tinycolor_201.readability(hLinePoint.color, contrastColor) < 1.5 ? - _$color_239.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode, - yThickness = ya.spikethickness, - yColor = ya.spikecolor || dfltHLineColor, - yBB = ya._boundingBox, - xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, - xBase, - xEndSpike; +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 +]; - if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { - if(yMode.indexOf('toaxis') !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; - } - if(yMode.indexOf('across') !== -1) { - xBase = ya._counterSpan[0]; - xEndSpike = ya._counterSpan[1]; - } +// Spouge approximation (suitable for large arguments) +function lngamma(z) { - // Foreground horizontal line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness, - 'stroke': yColor, - 'stroke-dasharray': _$drawing_264.dashStyle(ya.spikedash, yThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + 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); +} - // Background horizontal Line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } - // Y axis marker - if(yMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), - 'cy': hLinePointY, - 'r': yThickness, - 'fill': yColor - }) - .classed('spikeline', true); +_$gamma_138 = 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 + ; } +}; - if(showX) { - var vLinePoint = closestPoints.vLinePoint, - vLinePointX, - vLinePointY; +_$gamma_138.log = lngamma; - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; +"use strict" - if(xSnap === 'cursor') { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; - } - var dfltVLineColor = _$tinycolor_201.readability(vLinePoint.color, contrastColor) < 1.5 ? - _$color_239.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode, - xThickness = xa.spikethickness, - xColor = xa.spikecolor || dfltVLineColor, - xBB = xa._boundingBox, - yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, - yBase, - yEndSpike; +var _$permutationSign_210 = permutationSign - if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { - if(xMode.indexOf('toaxis') !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if(xMode.indexOf('across') !== -1) { - yBase = xa._counterSpan[0]; - yEndSpike = xa._counterSpan[1]; - } +var __BRUTE_FORCE_CUTOFF_210 = 32 - // Foreground vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness, - 'stroke': xColor, - 'stroke-dasharray': _$drawing_264.dashStyle(xa.spikedash, xThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); +/* removed: var _$pool_269 = require("typedarray-pool") */; - // Background vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); +function permutationSign(p) { + var n = p.length + if(n < __BRUTE_FORCE_CUTOFF_210) { + //Use quadratic algorithm for small n + var sgn = 1 + for(var i=0; i= 0; i--) { - var oldPt = oldhoverdata[i], - newPt = gd._hoverdata[i]; - if(oldPt.curveNumber !== newPt.curveNumber || - String(oldPt.pointNumber) !== String(newPt.pointNumber)) { - return true; - } - } - return false; +var _$invertPermutation_186 = invertPermutation +var _$permutationRank_211 = {}; +"use strict" + +/* removed: var _$pool_269 = require("typedarray-pool") */; +/* removed: var _$invertPermutation_186 = require("invert-permutation") */; + +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_269.mallocUint32(n) + var pinv = _$pool_269.mallocUint32(n) + var r = 0, s, t, i + _$invertPermutation_186(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_269.freeUint32(pinv) + _$pool_269.freeUint32(p) + return r } -function spikesChanged(gd, oldspikepoints) { - // don't relayout the plot because of new spikelines if spikelines points didn't change - if(!oldspikepoints) return true; - if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || - oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint - ) return true; - return false; +function 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 } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +_$permutationRank_211.rank = rank +_$permutationRank_211.unrank = unrank -'use strict'; +"use strict" -/* removed: var _$registry_451 = require('../../registry'); */; -var hover = _$hover_279.hover; +var _$triangulateCube_266 = triangulateCube -var _$click_275 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_451.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); +/* removed: var _$permutationRank_211 = require("permutation-rank") */; +/* removed: var _$permutationSign_210 = require("permutation-parity") */; +/* removed: var _$gamma_138 = require("gamma") */; - // 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 triangulateCube(dimension) { + if(dimension < 0) { + return [ ] + } + if(dimension === 0) { + return [ [0] ] + } + var dfactorial = Math.round(_$gamma_138(dimension+1))|0 + var result = [] + for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", + "args": [{ + "name": "_inline_1_arg0_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg1_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg2_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg3_", + "lvalue": false, + "rvalue": true, + "count": 2 + }, { + "name": "_inline_1_arg4_", + "lvalue": false, + "rvalue": true, + "count": 1 + }], + "thisVars": [], + "localVars": ["_inline_1_da", "_inline_1_db"] + }, + funcName: 'zeroCrossings' +}) -var _$supplyDefaults_277 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_273, attr, dflt); - } +"use strict" - _$handleHoverLabelDefaults_280(traceIn, traceOut, coerce, layout.hoverlabel); -}; +var _$findZeroCrossings_283 = findZeroCrossings -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +/* removed: var _$zcCore_282 = require("./lib/zc-core") */; -'use strict'; +function findZeroCrossings(array, level) { + var cross = [] + level = +level || 0.0 + _$zcCore_282(array.hi(array.shape[0]-1), cross, level) + return cross +} +"use strict" -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$layout_attributes_282 = require('./layout_attributes'); */; +var _$surfaceNets_257 = surfaceNets -var _$supplyLayoutDefaults_283 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_363.coerce(layoutIn, layoutOut, _$layout_attributes_282, attr, dflt); - } +/* removed: var _$createSurfaceExtractor_199 = require("ndarray-extract-contour") */; +/* removed: var _$triangulateCube_266 = require("triangulate-hypercube") */; +/* removed: var _$findZeroCrossings_283 = require("zero-crossings") */; - coerce('dragmode'); +function buildSurfaceNets(order, dtype) { + var dimension = order.length + var code = ["'use strict';"] + var funcName = "surfaceNets" + order.join("_") + "d" + dtype - var hovermodeDflt; - if(layoutOut._has('cartesian')) { - // flag for 'horizontal' plots: - // determines the state of the mode bar 'compare' hovermode button - layoutOut._isHoriz = isHoriz(fullData); - hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; - } - else hovermodeDflt = 'closest'; + //Contour extraction function + code.push( + "var contour=genContour({", + "order:[", order.join(), "],", + "scalarArguments: 3,", + "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },") + if(dtype === "generic") { + code.push("getters:[0],") + } - var hoverMode = coerce('hovermode', hovermodeDflt); - if(hoverMode) { - coerce('hoverdistance'); - coerce('spikedistance'); + //Generate vertex function + var cubeArgs = [] + var extraArgs = [] + for(var i=0; i>>7){") + } + for(var i=0; i<1<<(1< 128) { + if((i%128)===0) { + if(extraFuncs.length > 0) { + currentFunc.push("}}") + } + var efName = "vExtra" + extraFuncs.length + code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") + currentFunc = [ + "function ", efName, "(m,", extraArgs.join(), "){switch(m){" + ] + extraFuncs.push(currentFunc) + } } - - // if only mapbox or geo subplots is present on graph, - // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, - // so that the correct modebar button is active - var hasMapbox = layoutOut._has('mapbox'); - var hasGeo = layoutOut._has('geo'); - var len = layoutOut._basePlotModules.length; - - if(layoutOut.dragmode === 'zoom' && ( - ((hasMapbox || hasGeo) && len === 1) || - (hasMapbox && hasGeo && len === 2) - )) { - layoutOut.dragmode = 'pan'; + currentFunc.push("case ", (i&0x7f), ":") + var crossings = new Array(dimension) + var denoms = new Array(dimension) + var crossingCount = new Array(dimension) + var bias = new Array(dimension) + var totalCrossings = 0 + for(var j=0; j j) { + continue + } + if(!(i&(1< 0) { + cStr = "+" + crossingCount[k] + "*c" + } + var weight = 0.5 * (crossings[k].length / totalCrossings) + var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) + vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") + + } } + currentFunc.push("a.push([", vertexStr.join(), "]);", + "break;") + } + code.push("}},") + if(extraFuncs.length > 0) { + currentFunc.push("}}") + } - _$handleHoverLabelDefaults_280(layoutIn, layoutOut, coerce); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$helpers_278 = require('./helpers'); */; -/* removed: var _$layout_attributes_282 = require('./layout_attributes'); */; - -var _$fx_281 = { - moduleType: 'component', - name: 'fx', - - constants: _$constants_276, - schema: { - layout: _$layout_attributes_282 - }, + //Create face function + var faceArgs = [] + for(var i=0; i<(1<<(dimension-1)); ++i) { + faceArgs.push("v" + i) + } + faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c") + code.push("cell:function cellFunc(", faceArgs.join(), "){") - attributes: _$attributes_273, - layoutAttributes: _$layout_attributes_282, + var facets = _$triangulateCube_266(dimension-1) + code.push("if(p0){b.push(", + facets.map(function(f) { + return "[" + f.map(function(v) { + return "v" + v + }) + "]" + }).join(), ")}else{b.push(", + facets.map(function(f) { + var e = f.slice() + e.reverse() + return "[" + e.map(function(v) { + return "v" + v + }) + "]" + }).join(), + ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";") - supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_284, - supplyDefaults: _$supplyDefaults_277, - supplyLayoutDefaults: _$supplyLayoutDefaults_283, + for(var i=0; i 8192) { + throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") + } + var height = 3 * size + if(canvas.height < height) { + canvas.height = height + } -function fixSuperScript(x) { - var idx = 0; + context.fillStyle = "#000" + context.fillRect(0, 0, canvas.width, canvas.height) - while((idx = x.indexOf('', idx)) >= 0) { - var nidx = x.indexOf('', idx); - if(nidx < idx) break; + context.fillStyle = "#fff" + context.fillText(str, size, 2*size) - x = x.slice(0, idx) + _$toSuperScript_194(x.slice(idx + 5, nidx)) + x.slice(nidx + 6); - } + //Cut pixels from image + var pixelData = context.getImageData(0, 0, width, height) + var pixels = _$wrappedNDArrayCtor_201(pixelData.data, [height, width, 4]) - return x; + return pixels.pick(-1,-1,0).transpose(1,0) } -function fixBR(x) { - return x.replace(/\/g, '\n'); +function getContour(pixels, doSimplify) { + var contour = _$surfaceNets_257(pixels, 128) + if(doSimplify) { + return _$simplifyPolygon_252(contour.cells, contour.positions, 0.25) + } + return { + edges: contour.cells, + positions: contour.positions + } } -function stripTags(x) { - return x.replace(/\<.*\>/g, ''); -} +function processPixelsImpl(pixels, options, size, simplify) { + //Extract contour + var contour = getContour(pixels, simplify) -function fixEntities(x) { - var entityToUnicode = _$string_mappings_344.entityToUnicode; - var idx = 0; + //Apply warp to positions + var positions = transformPositions(contour.positions, options, size) + var edges = contour.edges + var flip = "ccw" === options.orientation - while((idx = x.indexOf('&', idx)) >= 0) { - var nidx = x.indexOf(';', idx); - if(nidx < idx) { - idx += 1; - continue; - } + //Clean up the PSLG, resolve self intersections, etc. + _$cleanPSLG_55(positions, edges) - var entity = entityToUnicode[x.slice(idx + 1, nidx)]; - if(entity) { - x = x.slice(0, idx) + entity + x.slice(nidx + 1); - } else { - x = x.slice(0, idx) + x.slice(nidx + 1); + //If triangulate flag passed, triangulate the result + if(options.polygons || options.polygon || options.polyline) { + var result = _$planarGraphToPolyline_215(edges, positions) + var nresult = new Array(result.length) + for(var i=0; i0) { + shapeX += 0.02 + } + } + var data = new Float32Array(bufferSize) + var ptr = 0 + var xOffset = -0.5 * shapeX + for(var i=0; i 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_156.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_156.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_156.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 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 +} - if(!ax._inputRange) ax._inputRange = ax.range.slice(); +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 - // set axis scale here so we can use _m rather than - // having to calculate it from length and range - ax.setScale(); + 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 - // 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); - } + 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 +} - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); +var __proto_172 = Texture2D.prototype - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; +Object.defineProperties(__proto_172, { + 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 } - - // 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_424(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_424(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 && ax._min.length && ax._max.length) { - /* - * 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_414(ax); - - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; - - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } - - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[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); - } - } + } + 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 } -}; - -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_414.clean = function cleanConstraints(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; - } + }, + 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) } - if(!isConstrained || ax.constrain !== 'domain') { - ax._input.domain = ax.domain = ax._inputDomain; - delete ax._inputDomain; + } + 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 + } + } +}) -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_414[ax.constraintoward]; - var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; +__proto_172.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 +} - ax.domain = ax._input.domain = [ - center + (inputDomain[0] - center) / factor, - center + (inputDomain[1] - center) / factor - ]; +__proto_172.dispose = function() { + this.gl.deleteTexture(this.handle) } -var _$mouse_139 = {}; -'use strict' +__proto_172.generateMipmap = function() { + this.bind() + this.gl.generateMipmap(this.gl.TEXTURE_2D) -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; ++i, l>>>=1) { + if(this._mipLevels.indexOf(i) < 0) { + this._mipLevels.push(i) + } + } +} + +__proto_172.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') } - return 0 } -_$mouse_139.buttons = mouseButtons -function mouseElement(ev) { - return ev.target || ev.srcElement || window -} -_$mouse_139.element = mouseElement -function mouseRelativeX(ev) { - if(typeof ev === 'object') { - if('offsetX' in ev) { - return ev.offsetX - } - var target = mouseElement(ev) - var bounds = target.getBoundingClientRect() - return ev.clientX - bounds.left +function __isPacked_172(shape, stride) { + if(shape.length === 3) { + return (stride[2] === 1) && + (stride[1] === shape[0]*shape[2]) && + (stride[0] === shape[2]) } - return 0 + return (stride[0] === 1) && + (stride[1] === shape[0]) } -_$mouse_139.x = mouseRelativeX -function mouseRelativeY(ev) { - if(typeof ev === 'object') { - if('offsetY' in ev) { - return ev.offsetY +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_172(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 = _$wrappedNDArrayCtor_201(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') } - var target = mouseElement(ev) - var bounds = target.getBoundingClientRect() - return ev.clientY - bounds.top + channels = shape[2] + } else { + throw new Error('gl-texture2d: Invalid shape for texture') } - return 0 -} -_$mouse_139.y = mouseRelativeY - -'use strict' - -var _$mouseListen_137 = mouseListen - -/* removed: var _$mouse_139 = require('mouse-event') */; - -function mouseListen (element, callback) { - if (!callback) { - callback = element - element = window + //For 1-channel textures allow conversion between formats + if((format === gl.LUMINANCE || format === gl.ALPHA) && + (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { + format = cformat } - - var buttonState = 0 - var x = 0 - var y = 0 - var mods = { - shift: false, - alt: false, - control: false, - meta: false + if(format !== cformat) { + throw new Error('gl-texture2d: Incompatible texture format for setPixels') } - var attached = false - - function updateMods (ev) { - var changed = false - if ('altKey' in ev) { - changed = changed || ev.altKey !== mods.alt - mods.alt = !!ev.altKey - } - if ('shiftKey' in ev) { - changed = changed || ev.shiftKey !== mods.shift - mods.shift = !!ev.shiftKey + 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)) + } } - if ('ctrlKey' in ev) { - changed = changed || ev.ctrlKey !== mods.control - mods.control = !!ev.ctrlKey + } else { + //Need to do type conversion to pack data into buffer + var pack_buffer + if(ctype === gl.FLOAT) { + pack_buffer = _$pool_269.mallocFloat32(size) + } else { + pack_buffer = _$pool_269.mallocUint8(size) } - if ('metaKey' in ev) { - changed = changed || ev.metaKey !== mods.meta - mods.meta = !!ev.metaKey + var pack_view = _$wrappedNDArrayCtor_201(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) + if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { + convertFloatToUint8(pack_view, array) + } else { + _$ndarrayOps_200.assign(pack_view, array) } - return changed - } - - function handleEvent (nextButtons, ev) { - var nextX = _$mouse_139.x(ev) - var nextY = _$mouse_139.y(ev) - if ('buttons' in ev) { - nextButtons = ev.buttons | 0 + 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 (nextButtons !== buttonState || - nextX !== x || - nextY !== y || - updateMods(ev)) { - buttonState = nextButtons | 0 - x = nextX || 0 - y = nextY || 0 - callback && callback(buttonState, x, y, mods) + if(ctype === gl.FLOAT) { + _$pool_269.freeFloat32(pack_buffer) + } else { + _$pool_269.freeUint8(pack_buffer) } } +} - function clearState (ev) { - handleEvent(0, ev) - } +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 handleBlur () { - if (buttonState || - x || - y || - mods.shift || - mods.alt || - mods.meta || - mods.control) { - x = y = 0 - buttonState = 0 - mods.shift = mods.alt = mods.control = mods.meta = false - callback && callback(0, 0, 0, mods) - } +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 handleMods (ev) { - if (updateMods(ev)) { - callback && callback(buttonState, x, y, mods) +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_172(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 = _$wrappedNDArrayCtor_201(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') } - - function handleMouseMove (ev) { - if (_$mouse_139.buttons(ev) === 0) { - handleEvent(0, ev) + 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_269.malloc(size, dtype) + var buf_array = _$wrappedNDArrayCtor_201(buf_store, shape, stride, 0) + if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { + convertFloatToUint8(buf_array, array) } else { - handleEvent(buttonState, ev) + _$ndarrayOps_200.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) } - - function handleMouseDown (ev) { - handleEvent(buttonState | _$mouse_139.buttons(ev), ev) + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) + if(!packed) { + _$pool_269.free(buf_store) } + return new Texture2D(gl, tex, shape[0], shape[1], format, type) +} - function handleMouseUp (ev) { - handleEvent(buttonState & ~_$mouse_139.buttons(ev), ev) +function createTexture2D(gl) { + if(arguments.length <= 1) { + throw new Error('gl-texture2d: Missing arguments for texture2d constructor') } - - function attachListeners () { - if (attached) { - return - } - attached = true - - element.addEventListener('mousemove', handleMouseMove) - - element.addEventListener('mousedown', handleMouseDown) - - element.addEventListener('mouseup', handleMouseUp) - - element.addEventListener('mouseleave', clearState) - element.addEventListener('mouseenter', clearState) - element.addEventListener('mouseout', clearState) - element.addEventListener('mouseover', clearState) - - element.addEventListener('blur', handleBlur) - - element.addEventListener('keyup', handleMods) - element.addEventListener('keydown', handleMods) - element.addEventListener('keypress', handleMods) - - if (element !== window) { - window.addEventListener('blur', handleBlur) - - window.addEventListener('keyup', handleMods) - window.addEventListener('keydown', handleMods) - window.addEventListener('keypress', handleMods) - } + if(!linearTypes) { + lazyInitLinearTypes(gl) } - - function detachListeners () { - if (!attached) { - return + 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) } - attached = false - - element.removeEventListener('mousemove', handleMouseMove) + } + throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') +} - element.removeEventListener('mousedown', handleMouseDown) +'use strict' - element.removeEventListener('mouseup', handleMouseUp) +/* removed: var _$createTexture2D_172 = require('gl-texture2d') */; - element.removeEventListener('mouseleave', clearState) - element.removeEventListener('mouseenter', clearState) - element.removeEventListener('mouseout', clearState) - element.removeEventListener('mouseover', clearState) +var _$createFBO_146 = createFBO - element.removeEventListener('blur', handleBlur) +var colorAttachmentArrays = null +var FRAMEBUFFER_UNSUPPORTED +var FRAMEBUFFER_INCOMPLETE_ATTACHMENT +var FRAMEBUFFER_INCOMPLETE_DIMENSIONS +var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT - element.removeEventListener('keyup', handleMods) - element.removeEventListener('keydown', handleMods) - element.removeEventListener('keypress', handleMods) +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] +} - if (element !== window) { - window.removeEventListener('blur', handleBlur) +function restoreFBOState(gl, data) { + gl.bindFramebuffer(gl.FRAMEBUFFER, data[0]) + gl.bindRenderbuffer(gl.RENDERBUFFER, data[1]) + gl.bindTexture(gl.TEXTURE_2D, data[2]) +} - window.removeEventListener('keyup', handleMods) - window.removeEventListener('keydown', handleMods) - window.removeEventListener('keypress', handleMods) +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_146(gl, width, height, + WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, + gl.DEPTH_STENCIL, + gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo.depth = __initTexture_146(gl, width, height, + gl.UNSIGNED_SHORT, + gl.DEPTH_COMPONENT, + gl.DEPTH_ATTACHMENT) } - dx *= scale - dy *= scale - dz *= scale - if(dx || dy || dz) { - return callback(dx, dy, dz, ev) + } 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) } } - element.addEventListener('wheel', listener) - return listener -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + //Check frame buffer state + var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) + if(status !== gl.FRAMEBUFFER_COMPLETE) { + //Release all partially allocated resources + fbo._destroyed = true -'use strict'; + //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') + } - var lastX = result.lastPos[0], - lastY = result.lastPos[1]; + //Update shape + fbo._shape[0] = w + fbo._shape[1] = h - var MINDRAG = _$constants_412.MINDRAG * plot.pixelRatio; - var MINZOOM = _$constants_412.MINZOOM * plot.pixelRatio; + //Save framebuffer state + var state = saveFBOState(gl) - var dx, dy; + //Resize framebuffer attachments + for(var i=0; i Math.abs(dy)) { - result.boxEnd[1] = result.boxStart[1] + - Math.abs(dx) * dydx * (dy >= 0 ? 1 : -1); + //Special case: Can accept an array as argument + if(Array.isArray(width)) { + options = height + height = width[1]|0 + width = width[0]|0 + } - // gl-select-box clips to the plot area bounds, - // which breaks the axis constraint, so don't allow - // this box to go out of bounds - if(result.boxEnd[1] < dataBox[1]) { - result.boxEnd[1] = dataBox[1]; - result.boxEnd[0] = result.boxStart[0] + - (dataBox[1] - result.boxStart[1]) / Math.abs(dydx); - } - else if(result.boxEnd[1] > dataBox[3]) { - result.boxEnd[1] = dataBox[3]; - result.boxEnd[0] = result.boxStart[0] + - (dataBox[3] - result.boxStart[1]) / Math.abs(dydx); - } - } - else { - result.boxEnd[0] = result.boxStart[0] + - Math.abs(dy) / dydx * (dx >= 0 ? 1 : -1); + if(typeof width !== 'number') { + throw new Error('gl-fbo: Missing shape parameter') + } - if(result.boxEnd[0] < dataBox[0]) { - result.boxEnd[0] = dataBox[0]; - result.boxEnd[1] = result.boxStart[1] + - (dataBox[0] - result.boxStart[0]) * Math.abs(dydx); - } - else if(result.boxEnd[0] > dataBox[2]) { - result.boxEnd[0] = dataBox[2]; - result.boxEnd[1] = result.boxStart[1] + - (dataBox[2] - result.boxStart[0]) * Math.abs(dydx); - } - } - } - // otherwise clamp small changes to the origin so we get 1D zoom - else { - if(smallDx) result.boxEnd[0] = result.boxStart[0]; - if(smallDy) result.boxEnd[1] = result.boxStart[1]; - } - } - else if(result.boxEnabled) { - dx = result.boxStart[0] !== result.boxEnd[0]; - dy = result.boxStart[1] !== result.boxEnd[1]; - if(dx || dy) { - if(dx) { - updateRange(0, result.boxStart[0], result.boxEnd[0]); - scene.xaxis.autorange = false; - } - if(dy) { - updateRange(1, result.boxStart[1], result.boxEnd[1]); - scene.yaxis.autorange = false; - } - scene.relayoutCallback(); - } - else { - scene.glplot.setDirty(); - } - result.boxEnabled = false; - result.boxInited = false; - } - // if box was inited but button released then - reset the box - else if(result.boxInited) { - result.boxInited = false; - } - break; + //Validate width/height properties + var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) + if(width < 0 || width > 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 + } + } - case 'pan': - result.boxEnabled = false; - result.boxInited = false; + //Check if we should use depth buffer + var useDepth = true + if('depth' in options) { + useDepth = !!options.depth + } - if(buttons) { - if(!result.panning) { - result.dragStart[0] = x; - result.dragStart[1] = y; - } + //Check if we should use a stencil buffer + var useStencil = false + if('stencil' in options) { + useStencil = !!options.stencil + } - if(Math.abs(result.dragStart[0] - x) < MINDRAG) x = result.dragStart[0]; - if(Math.abs(result.dragStart[1] - y) < MINDRAG) y = result.dragStart[1]; + return new Framebuffer( + gl, + width, + height, + colorType, + numColors, + useDepth, + useStencil, + WEBGL_draw_buffers) +} - dx = (lastX - x) * (dataBox[2] - dataBox[0]) / - (plot.viewBox[2] - plot.viewBox[0]); - dy = (lastY - y) * (dataBox[3] - dataBox[1]) / - (plot.viewBox[3] - plot.viewBox[1]); +'use strict' - dataBox[0] += dx; - dataBox[2] += dx; - dataBox[1] += dy; - dataBox[3] += dy; +var _$createSelectBuffer_163 = createSelectBuffer - scene.setRanges(dataBox); +/* removed: var _$createFBO_146 = require('gl-fbo') */; +/* removed: var _$pool_269 = require('typedarray-pool') */; +/* removed: var _$wrappedNDArrayCtor_201 = require('ndarray') */; - result.panning = true; - result.lastInputTime = Date.now(); - unSetAutoRange(); - scene.cameraChanged(); - scene.handleAnnotations(); - } - else if(result.panning) { - result.panning = false; - scene.relayoutCallback(); - } - break; - } +var nextPow2 = _$twiddle_36.nextPow2 - result.lastPos[0] = x; - result.lastPos[1] = y; +var selectRange = _$wrapper_68({"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_55_arg0_<255||_inline_55_arg1_<255||_inline_55_arg2_<255||_inline_55_arg3_<255){var _inline_55_l=_inline_55_arg4_-_inline_55_arg6_[0],_inline_55_a=_inline_55_arg5_-_inline_55_arg6_[1],_inline_55_f=_inline_55_l*_inline_55_l+_inline_55_a*_inline_55_a;_inline_55_f this.buffer.length) { + _$pool_269.free(this.buffer) + var buffer = this.buffer = _$pool_269.mallocUint8(nextPow2(r*c*4)) + for(var i=0; i max ? max : value) - : (value < max ? max : value > min ? min : value) -} + var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius) + var dx = closest[0] + var dy = closest[1] + if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) { + return null + } -'use strict' - -var _$colorName_57 = { - "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] -}; + var c0 = region.get(dx, dy, 0) + var c1 = region.get(dx, dy, 1) + var c2 = region.get(dx, dy, 2) + var c3 = region.get(dx, dy, 3) -var _$defined_69 = function () { - for (var i = 0; i < arguments.length; i++) { - if (arguments[i] !== undefined) return arguments[i]; - } -}; + return new SelectResult( + (dx + x0)|0, + (dy + y0)|0, + c0, + [c1, c2, c3], + Math.sqrt(closest[2])) +} -'use strict'; -var __toString_134 = Object.prototype.toString; +__proto_163.dispose = function() { + if(!this.gl) { + return + } + this.fbo.dispose() + _$pool_269.free(this.buffer) + this.gl = null + if(this._readTimeout) { + clearTimeout(this._readTimeout) + } +} -var _$isPlainObj_134 = function (x) { - var prototype; - return __toString_134.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); -}; +function createSelectBuffer(gl, shape) { + var fbo = _$createFBO_146(gl, shape) + var buffer = _$pool_269.mallocUint8(shape[0]*shape[1]*4) + return new SelectBuffer(gl, fbo, buffer) +} -var _$parse_59 = {}; -(function (global){ -/** - * @module color-parse - */ +'use strict' + +var _$createGLPlot2D_158 = createGLPlot2D + +/* removed: var _$createSelectBuffer_163 = require('gl-select-static') */; + +/* removed: var _$createGrid_153 = require('./lib/grid') */; +/* removed: var _$createTextElements_156 = require('./lib/text') */; +/* removed: var _$createLines_154 = require('./lib/line') */; +/* removed: var _$createBoxes_152 = require('./lib/box') */; + +function GLPlot2D(gl, pickBuffer) { + this.gl = gl + this.pickBuffer = pickBuffer + + this.screenBox = [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] + this.viewBox = [0, 0, 0, 0] + this.dataBox = [-10, -10, 10, 10] + + this.gridLineEnable = [true,true] + this.gridLineWidth = [1,1] + this.gridLineColor = [[0,0,0,1], + [0,0,0,1]] + + this.pixelRatio = 1 + + this.tickMarkLength = [0,0,0,0] + this.tickMarkWidth = [0,0,0,0] + this.tickMarkColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] + + this.tickPad = [15,15,15,15] + this.tickAngle = [0,0,0,0] + this.tickEnable = [true,true,true,true] + this.tickColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] + + this.labelPad = [15,15,15,15] + this.labelAngle = [0,Math.PI/2,0,3.0*Math.PI/2] + this.labelEnable = [true,true,true,true] + this.labelColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] + + this.titleCenter = [0,0] + this.titleEnable = true + this.titleAngle = 0 + this.titleColor = [0,0,0,1] + + this.borderColor = [0,0,0,0] + this.backgroundColor = [0,0,0,0] + + this.zeroLineEnable = [true, true] + this.zeroLineWidth = [4, 4] + this.zeroLineColor = [[0, 0, 0, 1],[0, 0, 0, 1]] + + this.borderLineEnable = [true,true,true,true] + this.borderLineWidth = [2,2,2,2] + this.borderLineColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] + + //Drawing parameters + this.grid = null + this.text = null + this.line = null + this.box = null + this.objects = [] + this.overlays = [] + + this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] + + this.static = false + + this.dirty = false + this.pickDirty = false + this.pickDelay = 120 + this.pickRadius = 10 + this._pickTimeout = null + this._drawPick = this.drawPick.bind(this) + + this._depthCounter = 0 +} + +var __proto_158 = GLPlot2D.prototype + +__proto_158.setDirty = function() { + this.dirty = this.pickDirty = true +} + +__proto_158.setOverlayDirty = function() { + this.dirty = true +} + +__proto_158.nextDepthValue = function() { + return (this._depthCounter++) / 65536.0 +} + +function lerp(a, b, t) { + var s = 0.5 * (t + 1.0) + return Math.floor((1.0-s)*a + s*b)|0 +} + +__proto_158.draw = (function() { +var TICK_MARK_BOX = [0,0,0,0] +return function() { + var gl = this.gl + var screenBox = this.screenBox + var viewPixels = this.viewBox + var dataBox = this.dataBox + var pixelRatio = this.pixelRatio + var grid = this.grid + var line = this.line + var text = this.text + var objects = this.objects + + this._depthCounter = 0 + + if(this.pickDirty) { + if(this._pickTimeout) { + clearTimeout(this._pickTimeout) + } + this.pickDirty = false + this._pickTimeout = setTimeout(this._drawPick, this.pickDelay) + } + + if(!this.dirty) { + return + } + this.dirty = false + + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + + //Turn on scissor + gl.enable(gl.SCISSOR_TEST) + + //Turn off depth buffer + gl.disable(gl.DEPTH_TEST) + gl.depthFunc(gl.LESS) + gl.depthMask(false) + + //Configure premultiplied alpha blending + gl.enable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + + //Draw border + if (this.borderColor) { + gl.scissor( + screenBox[0], + screenBox[1], + screenBox[2]-screenBox[0], + screenBox[3]-screenBox[1]) + var borderColor = this.borderColor + gl.clearColor( + borderColor[0]*borderColor[3], + borderColor[1]*borderColor[3], + borderColor[2]*borderColor[3], + borderColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) + } -'use strict' + //Draw center pane + gl.scissor( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + gl.viewport( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + var backgroundColor = this.backgroundColor + gl.clearColor( + backgroundColor[0]*backgroundColor[3], + backgroundColor[1]*backgroundColor[3], + backgroundColor[2]*backgroundColor[3], + backgroundColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT) -/* removed: var _$colorName_57 = require('color-name') */; -/* removed: var _$isPlainObj_134 = require('is-plain-obj') */; -/* removed: var _$defined_69 = require('defined') */; + //Draw grid + grid.draw() -_$parse_59 = parse + //Draw zero lines separately + var zeroLineEnable = this.zeroLineEnable + var zeroLineColor = this.zeroLineColor + var zeroLineWidth = this.zeroLineWidth + if(zeroLineEnable[0] || zeroLineEnable[1]) { + line.bind() + for(var i=0; i<2; ++i) { + if(!zeroLineEnable[i] || + !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) { + continue + } -/** - * Base hues - * http://dev.w3.org/csswg/css-color/#typedef-named-hue - */ -//FIXME: use external hue detector -var baseHues = { - red: 0, - orange: 60, - yellow: 120, - green: 180, - blue: 240, - purple: 300 -} + var zeroIntercept = screenBox[i] - + dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) -/** - * Parse color from the string passed - * - * @return {Object} A space indicator `space`, an array `values` and `alpha` - */ -function parse (cstr) { - var m, parts = [], alpha = 1, space + 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]) + } + } + } - if (typeof cstr === 'string') { - //keyword - if (_$colorName_57[cstr]) { - parts = _$colorName_57[cstr].slice() - space = 'rgb' - } + //Draw traces + for(var i=0; i - if (/%$/.test(x)) { - //alpha - if (i === size) return parseFloat(x) / 100 - //rgb - if (base === 'rgb') return parseFloat(x) * 255 / 100 - return parseFloat(x) - } - //hue - else if (base[i] === 'h') { - // - if (/deg$/.test(x)) { - return parseFloat(x) - } - // - else if (baseHues[x] !== undefined) { - return baseHues[x] - } - } - return parseFloat(x) - }) + //Draw other overlay elements (select boxes, etc.) + var overlays = this.overlays + for(var i=0; i 10 && /[0-9](?:\s|\/)/.test(cstr)) { - parts = cstr.match(/([0-9]+)/g).map(function (value) { - return parseFloat(value) - }) +__proto_158.drawPick = (function() { - space = cstr.match(/([a-z])/ig).join('').toLowerCase() - } - } +return function() { + if (this.static) return; - //numeric case - else if (typeof cstr === 'number') { - space = 'rgb' - parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff] - } + var pickBuffer = this.pickBuffer + var gl = this.gl - //object case - detects css cases of rgb and hsl - else if (_$isPlainObj_134(cstr)) { - var r = _$defined_69(cstr.r, cstr.red, cstr.R, null) + this._pickTimeout = null + pickBuffer.begin() - if (r !== null) { - space = 'rgb' - parts = [ - r, - _$defined_69(cstr.g, cstr.green, cstr.G), - _$defined_69(cstr.b, cstr.blue, cstr.B) - ] - } - else { - space = 'hsl' - parts = [ - _$defined_69(cstr.h, cstr.hue, cstr.H), - _$defined_69(cstr.s, cstr.saturation, cstr.S), - _$defined_69(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness) - ] - } + var pickOffset = 1 + var objects = this.objects + for(var i=0; i 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_62.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]; -}; - -/** @module color-rgba */ +})() -'use strict' +function deepClone(array) { + var result = array.slice() + 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_158.addObject = function(object) { + if(this.objects.indexOf(object) < 0) { + this.objects.push(object) + this.setDirty() + } +} + +__proto_158.removeObject = function(object) { + var objects = this.objects + for(var i=0; i 0) { + + //Draw border + var w = lineWidth * pixelRatio + boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) + boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) + boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) + boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) + } +} + +__proto_162.update = function(options) { + options = options || {} + + this.innerFill = !!options.innerFill + this.outerFill = !!options.outerFill + this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() + this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() + this.borderColor = (options.borderColor || [0,0,0,1]).slice() + this.borderWidth = options.borderWidth || 0 + this.selectBox = (options.selectBox || this.selectBox).slice() +} + +__proto_162.dispose = function() { + this.boxBuffer.dispose() + this.boxShader.dispose() + this.plot.removeOverlay(this) +} + +function createSelectBox(plot, options) { + var gl = plot.gl + var buffer = _$createBuffer_140(gl, [ + 0, 0, + 0, 1, + 1, 0, + 1, 1 ]) + var shader = _$createShader_164(gl, _$shaders_161.boxVertex, _$shaders_161.boxFragment) + var selectBox = new SelectBox(plot, buffer, shader) + selectBox.update(options) + plot.addOverlay(selectBox) + return selectBox +} - // update canvas size - this.updateSize(this.canvas); +'use strict' +var _$createSpikes2D_171 = createSpikes2D - // grab context and yank out pixels - var gl = this.glplot.gl, - w = gl.drawingBufferWidth, - h = gl.drawingBufferHeight; +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] +} - // force redraw - gl.clearColor(1, 1, 1, 0); - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); - this.glplot.setDirty(); - this.glplot.draw(); +var __proto_171 = GLSpikes2D.prototype - gl.bindFramebuffer(gl.FRAMEBUFFER, null); +__proto_171.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() +} - var pixels = new Uint8Array(w * h * 4); - gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels); +__proto_171.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 - // flip pixels - for(var j = 0, k = h - 1; j < k; ++j, --k) { - for(var i = 0; i < w; ++i) { - for(var l = 0; l < 4; ++l) { - var tmp = pixels[4 * (w * j + i) + l]; - pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l]; - pixels[4 * (w * k + i) + l] = tmp; - } - } - } + var dataBox = plot.dataBox + var viewPixels = plot.viewBox - var canvas = document.createElement('canvas'); - canvas.width = w; - canvas.height = h; + line.bind() - var context = canvas.getContext('2d'); - var imageData = context.createImageData(w, h); - imageData.data.set(pixels); - context.putImageData(imageData, 0, 0); + if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] && + dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) { - var dataURL; + 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]) - switch(format) { - case 'jpeg': - dataURL = canvas.toDataURL('image/jpeg'); - break; - case 'webp': - dataURL = canvas.toDataURL('image/webp'); - break; - default: - dataURL = canvas.toDataURL('image/png'); + if(spikeEnable[0]) { + line.drawLine( + centerX, centerY, + viewPixels[0], centerY, + spikeWidth[0], spikeColor[0]) } - - if(this.staticPlot) this.container.removeChild(STATIC_CANVAS); - - return dataURL; -}; - -__proto_440.updateSize = function(canvas) { - if(!canvas) canvas = this.canvas; - - var pixelRatio = this.pixelRatio, - fullLayout = this.fullLayout; - - var width = fullLayout.width, - height = fullLayout.height, - pixelWidth = Math.ceil(pixelRatio * width) |0, - pixelHeight = Math.ceil(pixelRatio * height) |0; - - // check for resize - if(canvas.width !== pixelWidth || canvas.height !== pixelHeight) { - canvas.width = pixelWidth; - canvas.height = pixelHeight; + if(spikeEnable[1]) { + line.drawLine( + centerX, centerY, + centerX, viewPixels[1], + spikeWidth[1], spikeColor[1]) } - - return canvas; -}; - -__proto_440.computeTickMarks = function() { - this.xaxis.setScale(); - this.yaxis.setScale(); - - var nextTicks = [ - _$axes_407.calcTicks(this.xaxis), - _$axes_407.calcTicks(this.yaxis) - ]; - - for(var j = 0; j < 2; ++j) { - for(var i = 0; i < nextTicks[j].length; ++i) { - // coercing tick value (may not be a string) to a string - nextTicks[j][i].text = _$convertHTMLToUnicode_361(nextTicks[j][i].text + ''); - } + if(spikeEnable[2]) { + line.drawLine( + centerX, centerY, + viewPixels[2], centerY, + spikeWidth[2], spikeColor[2]) } - - return nextTicks; -}; - -function __compareTicks_440(a, b) { - for(var i = 0; i < 2; ++i) { - var aticks = a[i], - bticks = b[i]; - - if(aticks.length !== bticks.length) return true; - - for(var j = 0; j < aticks.length; ++j) { - if(aticks[j].x !== bticks[j].x) return true; - } + if(spikeEnable[3]) { + line.drawLine( + centerX, centerY, + centerX, viewPixels[3], + spikeWidth[3], spikeColor[3]) } - - return false; + } } -__proto_440.updateRefs = function(newFullLayout) { - this.fullLayout = newFullLayout; - - var spmatch = this.id.match(__SUBPLOT_PATTERN_440); - var xaxisName = 'xaxis' + spmatch[1]; - var yaxisName = 'yaxis' + spmatch[2]; - - this.xaxis = this.fullLayout[xaxisName]; - this.yaxis = this.fullLayout[yaxisName]; -}; - -__proto_440.relayoutCallback = function() { - var graphDiv = this.graphDiv, - xaxis = this.xaxis, - yaxis = this.yaxis, - layout = graphDiv.layout; - - // update user layout - layout.xaxis.autorange = xaxis.autorange; - layout.xaxis.range = xaxis.range.slice(0); - layout.yaxis.autorange = yaxis.autorange; - layout.yaxis.range = yaxis.range.slice(0); - - // make a meaningful value to be passed on to the possible 'plotly_relayout' subscriber(s) - // scene.camera has no many useful projection or scale information - // helps determine which one is the latest input (if async) - var update = { - lastInputTime: this.camera.lastInputTime - }; - - update[xaxis._name] = xaxis.range.slice(0); - update[yaxis._name] = yaxis.range.slice(0); - - graphDiv.emit('plotly_relayout', update); -}; - -__proto_440.cameraChanged = function() { - var camera = this.camera; +__proto_171.dispose = function() { + this.plot.removeOverlay(this) +} - this.glplot.setDataBox(this.calcDataBox()); +function createSpikes2D(plot, options) { + var spikes = new GLSpikes2D(plot) + spikes.update(options) + plot.addOverlay(spikes) + return spikes +} - var nextTicks = this.computeTickMarks(); - var curTicks = this.glplotOptions.ticks; +var _$getCanvasContext_139 = getCanvasContext +function getCanvasContext (type, opts) { + if (typeof type !== 'string') { + throw new TypeError('must specify type string') + } - if(__compareTicks_440(nextTicks, curTicks)) { - this.glplotOptions.ticks = nextTicks; - this.glplotOptions.dataBox = camera.dataBox; - this.glplot.update(this.glplotOptions); - this.handleAnnotations(); - } -}; + opts = opts || {} -__proto_440.handleAnnotations = function() { - var gd = this.graphDiv, - annotations = this.fullLayout.annotations; + if (typeof document === 'undefined' && !opts.canvas) { + return null // check for Node + } - for(var i = 0; i < annotations.length; i++) { - var ann = annotations[i]; + var canvas = opts.canvas || document.createElement('canvas') + if (typeof opts.width === 'number') { + canvas.width = opts.width + } + if (typeof opts.height === 'number') { + canvas.height = opts.height + } - if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) { - _$registry_451.getComponentMethod('annotations', 'drawOne')(gd, i); - } + var attribs = opts + var gl + try { + var names = [ type ] + // prefix GL contexts + if (type.indexOf('webgl') === 0) { + names.push('experimental-' + type) } -}; - -__proto_440.destroy = function() { - if(!this.glplot) return; - - var traces = this.traces; - if(traces) { - Object.keys(traces).map(function(key) { - traces[key].dispose(); - delete traces[key]; - }); + for (var i = 0; i < names.length; i++) { + gl = canvas.getContext(names[i], attribs) + if (gl) return gl } + } catch (e) { + gl = null + } + return (gl || null) // ensure null on fail +} - this.glplot.dispose(); - - this.container.removeChild(this.svgContainer); - this.container.removeChild(this.mouseContainer); - - this.fullData = null; - this.glplot = null; - this.stopped = true; - this.camera.mouseListener.enabled = false; - this.mouseContainer.removeEventListener('wheel', this.camera.wheelListener); - this.camera = null; -}; - -__proto_440.plot = function(fullData, calcData, fullLayout) { - var glplot = this.glplot; - - this.updateRefs(fullLayout); - this.xaxis.clearCalc(); - this.yaxis.clearCalc(); - this.updateTraces(fullData, calcData); - this.updateFx(fullLayout.dragmode); - - var width = fullLayout.width, - height = fullLayout.height; - - this.updateSize(this.canvas); - - var options = this.glplotOptions; - options.merge(fullLayout); - options.screenBox = [0, 0, width, height]; - - var mockGraphDiv = {_fullLayout: { - _axisConstraintGroups: this.graphDiv._fullLayout._axisConstraintGroups, - xaxis: this.xaxis, - yaxis: this.yaxis - }}; - - cleanAxisConstraints(mockGraphDiv, this.xaxis); - cleanAxisConstraints(mockGraphDiv, this.yaxis); - - var size = fullLayout._size, - domainX = this.xaxis.domain, - domainY = this.yaxis.domain; +/* removed: var _$getCanvasContext_139 = require('get-canvas-context') */; - options.viewBox = [ - size.l + domainX[0] * size.w, - size.b + domainY[0] * size.h, - (width - size.r) - (1 - domainX[1]) * size.w, - (height - size.t) - (1 - domainY[1]) * size.h - ]; +var _$getWebGLContext_281 = function getWebGLContext (opt) { + return _$getCanvasContext_139('webgl', opt) +} - this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px'; - this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px'; - this.mouseContainer.height = size.h * (domainY[1] - domainY[0]); - this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px'; - this.mouseContainer.style.top = size.t + (1 - domainY[1]) * size.h + 'px'; +'use strict' - var ax, i; +var _$toSuperScript_256 = toSuperScript - for(i = 0; i < 2; ++i) { - ax = this[__AXES_440[i]]; - ax._length = options.viewBox[i + 2] - options.viewBox[i]; +var SUPERSCRIPTS = { + ' ': ' ', + '0': '⁰', + '1': '¹', + '2': '²', + '3': '³', + '4': '⁴', + '5': '⁵', + '6': '⁶', + '7': '⁷', + '8': '⁸', + '9': '⁹', + '+': '⁺', + '-': '⁻', + 'a': 'ᵃ', + 'b': 'ᵇ', + 'c': 'ᶜ', + 'd': 'ᵈ', + 'e': 'ᵉ', + 'f': 'ᶠ', + 'g': 'ᵍ', + 'h': 'ʰ', + 'i': 'ⁱ', + 'j': 'ʲ', + 'k': 'ᵏ', + 'l': 'ˡ', + 'm': 'ᵐ', + 'n': 'ⁿ', + 'o': 'ᵒ', + 'p': 'ᵖ', + 'r': 'ʳ', + 's': 'ˢ', + 't': 'ᵗ', + 'u': 'ᵘ', + 'v': 'ᵛ', + 'w': 'ʷ', + 'x': 'ˣ', + 'y': 'ʸ', + 'z': 'ᶻ' +} - __doAutoRange_440(ax); - ax.setScale(); +function toSuperScript(x) { + return x.split('').map(function(c) { + if(c in SUPERSCRIPTS) { + return SUPERSCRIPTS[c] } + return '' + }).join('') +} - enforceAxisConstraints(mockGraphDiv); - - options.ticks = this.computeTickMarks(); - - options.dataBox = this.calcDataBox(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - options.merge(fullLayout); - glplot.update(options); - // force redraw so that promise is returned when rendering is completed - this.glplot.draw(); -}; +'use strict'; -__proto_440.calcDataBox = function() { - var xaxis = this.xaxis, - yaxis = this.yaxis, - xrange = xaxis.range, - yrange = yaxis.range, - xr2l = xaxis.r2l, - yr2l = yaxis.r2l; +/* removed: var _$toSuperScript_256 = require('superscript-text'); */; +/* removed: var _$string_mappings_405 = require('../constants/string_mappings'); */; - return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])]; -}; +function fixSuperScript(x) { + var idx = 0; -__proto_440.setRanges = function(dataBox) { - var xaxis = this.xaxis, - yaxis = this.yaxis, - xl2r = xaxis.l2r, - yl2r = yaxis.l2r; + while((idx = x.indexOf('', idx)) >= 0) { + var nidx = x.indexOf('', idx); + if(nidx < idx) break; - xaxis.range = [xl2r(dataBox[0]), xl2r(dataBox[2])]; - yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])]; -}; + x = x.slice(0, idx) + _$toSuperScript_256(x.slice(idx + 5, nidx)) + x.slice(nidx + 6); + } -__proto_440.updateTraces = function(fullData, calcData) { - var traceIds = Object.keys(this.traces); - var i, j, fullTrace; + return x; +} - this.fullData = fullData; +function fixBR(x) { + return x.replace(/\/g, '\n'); +} - // remove empty traces - trace_id_loop: - for(i = 0; i < traceIds.length; i++) { - var oldUid = traceIds[i], - oldTrace = this.traces[oldUid]; +function stripTags(x) { + return x.replace(/\<.*\>/g, ''); +} - for(j = 0; j < fullData.length; j++) { - fullTrace = fullData[j]; +function fixEntities(x) { + var entityToUnicode = _$string_mappings_405.entityToUnicode; + var idx = 0; - if(fullTrace.uid === oldUid && fullTrace.type === oldTrace.type) { - continue trace_id_loop; - } + while((idx = x.indexOf('&', idx)) >= 0) { + var nidx = x.indexOf(';', idx); + if(nidx < idx) { + idx += 1; + continue; } - oldTrace.dispose(); - delete this.traces[oldUid]; - } - - // update / create trace objects - for(i = 0; i < fullData.length; i++) { - fullTrace = fullData[i]; - var calcTrace = calcData[i], - traceObj = this.traces[fullTrace.uid]; - - if(traceObj) traceObj.update(fullTrace, calcTrace); - else { - traceObj = fullTrace._module.plot(this, fullTrace, calcTrace); - this.traces[fullTrace.uid] = traceObj; + var entity = entityToUnicode[x.slice(idx + 1, nidx)]; + if(entity) { + x = x.slice(0, idx) + entity + x.slice(nidx + 1); + } else { + x = x.slice(0, idx) + x.slice(nidx + 1); } } - // order object per traces - this.glplot.objects.sort(function(a, b) { - return a._trace.index - b._trace.index; - }); -}; - -__proto_440.updateFx = function(dragmode) { - // switch to svg interactions in lasso/select mode - if(dragmode === 'lasso' || dragmode === 'select') { - this.pickCanvas.style['pointer-events'] = 'none'; - this.mouseContainer.style['pointer-events'] = 'none'; - } else { - this.pickCanvas.style['pointer-events'] = 'auto'; - this.mouseContainer.style['pointer-events'] = 'auto'; - } + return x; +} - // set proper cursor - if(dragmode === 'pan') { - this.mouseContainer.style.cursor = 'move'; - } - else if(dragmode === 'zoom') { - this.mouseContainer.style.cursor = 'crosshair'; - } - else { - this.mouseContainer.style.cursor = null; - } -}; +function convertHTMLToUnicode(html) { + return '' + + fixEntities( + stripTags( + fixSuperScript( + fixBR( + html)))); +} -__proto_440.emitPointAction = function(nextSelection, eventType) { - var uid = nextSelection.trace.uid; - var ptNumber = nextSelection.pointIndex; - var trace; +var _$convertHTMLToUnicode_423 = convertHTMLToUnicode; - for(var i = 0; i < this.fullData.length; i++) { - if(this.fullData[i].uid === uid) { - trace = this.fullData[i]; - } - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 pointData = { - x: nextSelection.traceCoord[0], - y: nextSelection.traceCoord[1], - curveNumber: trace.index, - pointNumber: ptNumber, - data: trace._input, - fullData: this.fullData, - xaxis: this.xaxis, - yaxis: this.yaxis - }; - _$fx_281.appendArrayPointValue(pointData, trace, ptNumber); +'use strict'; - this.graphDiv.emit(eventType, {points: [pointData]}); -}; +/* removed: var _$color_301 = require('../components/color'); */; -__proto_440.draw = function() { - if(this.stopped) return; +var __noop_446 = function() {}; - requestAnimationFrame(this.redraw); - var glplot = this.glplot, - camera = this.camera, - mouseListener = camera.mouseListener, - mouseUp = this.lastButtonState === 1 && mouseListener.buttons === 0, - fullLayout = this.fullLayout; +/** + * Prints a no webgl error message into the scene container + * @param {scene instance} scene + * + * Expects 'scene' to have property 'container' + * + */ +var _$showWebGlMsg_446 = function showWebGlMsg(scene) { + for(var prop in scene) { + if(typeof scene[prop] === 'function') scene[prop] = __noop_446; + } - this.lastButtonState = mouseListener.buttons; + scene.destroy = function() { + scene.container.parentNode.removeChild(scene.container); + }; - this.cameraChanged(); + var div = document.createElement('div'); + div.textContent = 'Webgl is not supported by your browser - visit http://get.webgl.org for more info'; + div.style.cursor = 'pointer'; + div.style.fontSize = '24px'; + div.style.color = _$color_301.defaults[0]; - var x = mouseListener.x * glplot.pixelRatio; - var y = this.canvas.height - glplot.pixelRatio * mouseListener.y; + scene.container.appendChild(div); + scene.container.style.background = '#FFFFFF'; + scene.container.onclick = function() { + window.open('http://get.webgl.org'); + }; - var result; + // return before setting up camera and onrender methods + return false; +}; - if(camera.boxEnabled && fullLayout.dragmode === 'zoom') { - this.selectBox.enabled = true; +var _$constraints_477 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 selectBox = this.selectBox.selectBox = [ - Math.min(camera.boxStart[0], camera.boxEnd[0]), - Math.min(camera.boxStart[1], camera.boxEnd[1]), - Math.max(camera.boxStart[0], camera.boxEnd[0]), - Math.max(camera.boxStart[1], camera.boxEnd[1]) - ]; - // 1D zoom - for(var i = 0; i < 2; i++) { - if(camera.boxStart[i] === camera.boxEnd[i]) { - selectBox[i] = glplot.dataBox[i]; - selectBox[i + 2] = glplot.dataBox[i + 2]; - } - } +'use strict'; - glplot.setDirty(); - } - else if(!camera.panning && this.isMouseOver) { - this.selectBox.enabled = false; +var __id2name_477 = _$axis_ids_473.id2name; +/* removed: var _$scaleZoom_486 = require('./scale_zoom'); */; +var __makePadFn_477 = _$autorange_469.makePadFn; - var size = fullLayout._size, - domainX = this.xaxis.domain, - domainY = this.yaxis.domain; +var ALMOST_EQUAL = _$numerical_404.ALMOST_EQUAL; - result = glplot.pick( - (x / glplot.pixelRatio) + size.l + domainX[0] * size.w, - (y / glplot.pixelRatio) - (size.t + (1 - domainY[1]) * size.h) - ); +var __FROM_BL_477 = _$alignment_401.FROM_BL; - var nextSelection = result && result.object._trace.handlePick(result); - if(nextSelection && mouseUp) { - this.emitPointAction(nextSelection, 'plotly_click'); - } +_$constraints_477.enforce = function enforceAxisConstraints(gd) { + var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(result && result.object._trace.hoverinfo !== 'skip' && fullLayout.hovermode) { + var i, j, axisID, ax, normScale, mode, factor; - if(nextSelection && ( - !this.lastPickResult || - this.lastPickResult.traceUid !== nextSelection.trace.uid || - this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] || - this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1]) - ) { - var selection = nextSelection; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - this.lastPickResult = { - traceUid: nextSelection.trace ? nextSelection.trace.uid : null, - dataCoord: nextSelection.dataCoord.slice() - }; - this.spikes.update({ center: result.dataCoord }); + 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; - selection.screenCoord = [ - ((glplot.viewBox[2] - glplot.viewBox[0]) * - (result.dataCoord[0] - glplot.dataBox[0]) / - (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) / - glplot.pixelRatio, - (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) * - (result.dataCoord[1] - glplot.dataBox[1]) / - (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) / - glplot.pixelRatio - ]; + // 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_477(axisID)]; - // this needs to happen before the next block that deletes traceCoord data - // also it's important to copy, otherwise data is lost by the time event data is read - this.emitPointAction(nextSelection, 'plotly_hover'); + if(ax._inputDomain) ax.domain = ax._inputDomain.slice(); + else ax._inputDomain = ax.domain.slice(); - var trace = this.fullData[selection.trace.index] || {}; - var ptNumber = selection.pointIndex; - var hoverinfo = _$fx_281.castHoverinfo(trace, fullLayout, ptNumber); + if(!ax._inputRange) ax._inputRange = ax.range.slice(); - if(hoverinfo && hoverinfo !== 'all') { - var parts = hoverinfo.split('+'); - if(parts.indexOf('x') === -1) selection.traceCoord[0] = undefined; - if(parts.indexOf('y') === -1) selection.traceCoord[1] = undefined; - if(parts.indexOf('z') === -1) selection.traceCoord[2] = undefined; - if(parts.indexOf('text') === -1) selection.textLabel = undefined; - if(parts.indexOf('name') === -1) selection.name = undefined; - } + // set axis scale here so we can use _m rather than + // having to calculate it from length and range + ax.setScale(); - _$fx_281.loneHover({ - x: selection.screenCoord[0], - y: selection.screenCoord[1], - xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]), - yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]), - zLabel: selection.traceCoord[2], - text: selection.textLabel, - name: selection.name, - color: _$fx_281.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color, - borderColor: _$fx_281.castHoverOption(trace, ptNumber, 'bordercolor'), - fontFamily: _$fx_281.castHoverOption(trace, ptNumber, 'font.family'), - fontSize: _$fx_281.castHoverOption(trace, ptNumber, 'font.size'), - fontColor: _$fx_281.castHoverOption(trace, ptNumber, 'font.color') - }, { - container: this.svgContainer, - gd: this.graphDiv - }); + // 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); } - } - } - // Remove hover effects if we're not over a point OR - // if we're zooming or panning (in which case result is not set) - if(!result) { - this.unhover(); - } + // this has served its purpose, so remove it + delete ax._constraintShrinkable; + maxScale = Math.max(maxScale, normScale); - glplot.draw(); -}; + if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + } -__proto_440.unhover = function() { - if(this.lastPickResult) { - this.spikes.update({}); - this.lastPickResult = null; - this.graphDiv.emit('plotly_unhover'); - _$fx_281.loneUnhover(this.svgContainer); - } -}; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; -__proto_440.hoverFormatter = function(axisName, val) { - if(val === undefined) return undefined; + // 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; - var axis = this[axisName]; - return _$axes_407.tickText(axis, axis.c2l(val), 'hover').text; -}; + // 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; -var _$gl2d_439 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(mode === 'range') { + _$scaleZoom_486(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])); -'use strict'; + factor /= domainShrunk; -var __overrideAll_439 = _$edit_types_392.overrideAll; + 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_486(ax, factor); + continue; + } -/* removed: var _$Scene2D_440 = require('./scene2d'); */; -/* removed: var _$layout_attributes_442 = require('../layout_attributes'); */; -/* removed: var _$xmlns_namespaces_345 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$constants_412 = require('../cartesian/constants'); */; -/* removed: var _$cartesian_418 = require('../cartesian'); */; -/* removed: var _$layout_attributes_282 = require('../../components/fx/layout_attributes'); */; -var getSubplotData = _$get_data_436.getSubplotData; + 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; + } -_$gl2d_439.name = 'gl2d'; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_477(ax); -_$gl2d_439.attr = ['xaxis', 'yaxis']; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; -_$gl2d_439.idRoot = ['x', 'y']; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } -_$gl2d_439.idRegex = _$constants_412.idRegex; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } -_$gl2d_439.attrRegex = _$constants_412.attrRegex; + var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); + factor /= domainExpand; -_$gl2d_439.attributes = _$attributes_405; + rangeMin = ax.l2r(rangeMin); + rangeMax = ax.l2r(rangeMax); + ax.range = ax._input.range = (rl0 < rl1) ? + [rangeMin, rangeMax] : [rangeMax, rangeMin]; + } -_$gl2d_439.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { - if(!layoutOut._has('cartesian')) { - _$cartesian_418.supplyLayoutDefaults(layoutIn, layoutOut, fullData); + updateDomain(ax, factor); + } + } + } } }; -// 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 -_$gl2d_439.layoutAttrOverrides = __overrideAll_439(_$cartesian_418.layoutAttributes, 'plot', 'from-root'); - -// similar overrides for base plot attributes (and those added by components) -_$gl2d_439.baseLayoutAttrOverrides = __overrideAll_439({ - plot_bgcolor: _$layout_attributes_442.plot_bgcolor, - hoverlabel: _$layout_attributes_282.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'); - -_$gl2d_439.plot = function plotGl2d(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], - subplotObj = fullLayout._plots[subplotId], - fullSubplotData = getSubplotData(fullData, 'gl2d', subplotId); +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_477.clean = function cleanConstraints(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; + } + } +}; - // ref. to corresp. Scene instance - var scene = subplotObj._scene2d; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_477[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // If Scene is not instantiated, create one! - if(scene === undefined) { - scene = new _$Scene2D_440({ - id: subplotId, - graphDiv: gd, - container: gd.querySelector('.gl-container'), - staticPlot: gd._context.staticPlot, - plotGlPixelRatio: gd._context.plotGlPixelRatio - }, - fullLayout - ); + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} - // set ref to Scene instance - subplotObj._scene2d = scene; - } +var _$mouse_197 = {}; +'use strict' - scene.plot(fullSubplotData, gd.calcdata, fullLayout, gd.layout); +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<=', '>', '<='], - COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], - INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], - SET_OPS: ['{}', '}{'], - CONSTRAINT_REDUCTION: { - // for contour constraints, open/closed endpoints are equivalent - '=': '=', + if ('shiftKey' in ev) { + changed = changed || ev.shiftKey !== mods.shift + mods.shift = !!ev.shiftKey + } + if ('ctrlKey' in ev) { + changed = changed || ev.ctrlKey !== mods.control + mods.control = !!ev.ctrlKey + } + if ('metaKey' in ev) { + changed = changed || ev.metaKey !== mods.meta + mods.meta = !!ev.metaKey + } + return changed + } - '<': '<', - '<=': '<', + function handleEvent (nextButtons, ev) { + var nextX = _$mouse_197.x(ev) + var nextY = _$mouse_197.y(ev) + if ('buttons' in ev) { + nextButtons = ev.buttons | 0 + } + if (nextButtons !== buttonState || + nextX !== x || + nextY !== y || + updateMods(ev)) { + buttonState = nextButtons | 0 + x = nextX || 0 + y = nextY || 0 + callback && callback(buttonState, x, y, mods) + } + } - '>': '>', - '>=': '>', + function clearState (ev) { + handleEvent(0, ev) + } - '[]': '[]', - '()': '[]', - '[)': '[]', - '(]': '[]', + function handleBlur () { + if (buttonState || + x || + y || + mods.shift || + mods.alt || + mods.meta || + mods.control) { + x = y = 0 + buttonState = 0 + mods.shift = mods.alt = mods.control = mods.meta = false + callback && callback(0, 0, 0, mods) + } + } - '][': '][', - ')(': '][', - '](': '][', - ')[': '][' + function handleMods (ev) { + if (updateMods(ev)) { + callback && callback(buttonState, x, y, mods) } -}; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function handleMouseMove (ev) { + if (_$mouse_197.buttons(ev) === 0) { + handleEvent(0, ev) + } else { + handleEvent(buttonState, ev) + } + } -'use strict'; + function handleMouseDown (ev) { + handleEvent(buttonState | _$mouse_197.buttons(ev), ev) + } -/* removed: var _$attributes_512 = require('../scatter/attributes'); */; -/* removed: var _$attributes_245 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_240 = require('../../components/colorbar/attributes'); */; + function handleMouseUp (ev) { + handleEvent(buttonState & ~_$mouse_197.buttons(ev), ev) + } -var __extendFlat_473 = _$extend_354.extendFlat; + function attachListeners () { + if (attached) { + return + } + attached = true -var _$attributes_473 = __extendFlat_473({}, { - z: { - valType: 'data_array', - editType: 'calc', - - }, - x: __extendFlat_473({}, _$attributes_512.x, {impliedEdits: {xtype: 'array'}}), - x0: __extendFlat_473({}, _$attributes_512.x0, {impliedEdits: {xtype: 'scaled'}}), - dx: __extendFlat_473({}, _$attributes_512.dx, {impliedEdits: {xtype: 'scaled'}}), - y: __extendFlat_473({}, _$attributes_512.y, {impliedEdits: {ytype: 'array'}}), - y0: __extendFlat_473({}, _$attributes_512.y0, {impliedEdits: {ytype: 'scaled'}}), - dy: __extendFlat_473({}, _$attributes_512.dy, {impliedEdits: {ytype: 'scaled'}}), + element.addEventListener('mousemove', handleMouseMove) - text: { - 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', - - }, - connectgaps: { - valType: 'boolean', - dflt: false, - - 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', - - }, -}, - _$attributes_245, - { autocolorscale: __extendFlat_473({}, _$attributes_245.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_240 } -); + element.addEventListener('mousedown', handleMouseDown) -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + element.addEventListener('mouseup', handleMouseUp) -'use strict'; + element.addEventListener('mouseleave', clearState) + element.addEventListener('mouseenter', clearState) + element.addEventListener('mouseout', clearState) + element.addEventListener('mouseover', clearState) -/* removed: var _$attributes_473 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_512 = require('../scatter/attributes'); */; -/* removed: var _$attributes_245 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_240 = require('../../components/colorbar/attributes'); */; -var __dash_460 = _$attributes_263.dash; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -var __extendFlat_460 = _$extend_354.extendFlat; - -/* removed: var _$filter_ops_340 = require('../../constants/filter_ops'); */; -var COMPARISON_OPS2 = _$filter_ops_340.COMPARISON_OPS2; -var INTERVAL_OPS = _$filter_ops_340.INTERVAL_OPS; - -var scatterLineAttrs = _$attributes_512.line; - -var _$attributes_460 = __extendFlat_460({ - z: _$attributes_473.z, - x: _$attributes_473.x, - x0: _$attributes_473.x0, - dx: _$attributes_473.dx, - y: _$attributes_473.y, - y0: _$attributes_473.y0, - dy: _$attributes_473.dy, - text: _$attributes_473.text, - transpose: _$attributes_473.transpose, - xtype: _$attributes_473.xtype, - ytype: _$attributes_473.ytype, - zhoverformat: _$attributes_473.zhoverformat, - - connectgaps: _$attributes_473.connectgaps, + element.addEventListener('blur', handleBlur) - fillcolor: { - valType: 'color', - - editType: 'calc', - - }, + element.addEventListener('keyup', handleMods) + element.addEventListener('keydown', handleMods) + element.addEventListener('keypress', handleMods) - 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', - - }, + if (element !== window) { + window.addEventListener('blur', handleBlur) - 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: _$font_attributes_434({ - 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} - }, + window.addEventListener('keyup', handleMods) + window.addEventListener('keydown', handleMods) + window.addEventListener('keypress', handleMods) + } + } - line: { - color: __extendFlat_460({}, scatterLineAttrs.color, { - editType: 'style+colorbars', - - }), - width: __extendFlat_460({}, scatterLineAttrs.width, { - editType: 'style+colorbars' - }), - dash: __dash_460, - smoothing: __extendFlat_460({}, scatterLineAttrs.smoothing, { - - }), - editType: 'plot' + function detachListeners () { + if (!attached) { + return } -}, - _$attributes_245, { - autocolorscale: __extendFlat_460({}, _$attributes_245.autocolorscale, {dflt: false}), - zmin: __extendFlat_460({}, _$attributes_245.zmin, {editType: 'calc'}), - zmax: __extendFlat_460({}, _$attributes_245.zmax, {editType: 'calc'}) - }, - { colorbar: _$attributes_240 } -); + attached = false -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + element.removeEventListener('mousemove', handleMouseMove) + element.removeEventListener('mousedown', handleMouseDown) -'use strict'; + element.removeEventListener('mouseup', handleMouseUp) -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -var __extendFlat_469 = _$lib_363.extendFlat; + element.removeEventListener('mouseleave', clearState) + element.removeEventListener('mouseenter', clearState) + element.removeEventListener('mouseout', clearState) + element.removeEventListener('mouseover', clearState) + element.removeEventListener('blur', handleBlur) -var _$setContours_469 = function setContours(trace) { - var contours = trace.contours; + element.removeEventListener('keyup', handleMods) + element.removeEventListener('keydown', handleMods) + element.removeEventListener('keypress', handleMods) - // check if we need to auto-choose contour levels - if(trace.autocontour) { - var dummyAx = autoContours(trace.zmin, trace.zmax, trace.ncontours); + if (element !== window) { + window.removeEventListener('blur', handleBlur) - contours.size = dummyAx.dtick; + window.removeEventListener('keyup', handleMods) + window.removeEventListener('keydown', handleMods) + window.removeEventListener('keypress', handleMods) + } + } - contours.start = _$axes_407.tickFirst(dummyAx); - dummyAx.range.reverse(); - contours.end = _$axes_407.tickFirst(dummyAx); + // Attach listeners + attachListeners() - if(contours.start === trace.zmin) contours.start += contours.size; - if(contours.end === trace.zmax) contours.end -= contours.size; + var result = { + element: element + } - // if you set a small ncontours, *and* the ends are exactly on zmin/zmax - // there's an edge case where start > end now. Make sure there's at least - // one meaningful contour, put it midway between the crossed values - if(contours.start > contours.end) { - contours.start = contours.end = (contours.start + contours.end) / 2; + Object.defineProperties(result, { + enabled: { + get: function () { return attached }, + set: function (f) { + if (f) { + attachListeners() + } else { + detachListeners() } + }, + enumerable: true + }, + buttons: { + get: function () { return buttonState }, + enumerable: true + }, + x: { + get: function () { return x }, + enumerable: true + }, + y: { + get: function () { return y }, + enumerable: true + }, + mods: { + get: function () { return mods }, + enumerable: true + } + }) - // copy auto-contour info back to the source data. - // previously we copied the whole contours object back, but that had - // other info (coloring, showlines) that should be left to supplyDefaults - if(!trace._input.contours) trace._input.contours = {}; - __extendFlat_469(trace._input.contours, { - start: contours.start, - end: contours.end, - size: contours.size - }); - trace._input.autocontour = true; - } - else if(contours.type !== 'constraint') { - // sanity checks on manually-supplied start/end/size - var start = contours.start, - end = contours.end, - inputContours = trace._input.contours; - - if(start > end) { - contours.start = inputContours.start = end; - end = contours.end = inputContours.end = start; - start = contours.start; - } + return result +} - if(!(contours.size > 0)) { - var sizeOut; - if(start === end) sizeOut = 1; - else sizeOut = autoContours(start, end, trace.ncontours).dtick; +var _$parseUnit_208 = function parseUnit(str, out) { + if (!out) + out = [ 0, '' ] - inputContours.size = contours.size = sizeOut; - } - } -}; + str = String(str) + var num = parseFloat(str, 10) + out[0] = num + out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || '' + return out +} +'use strict' +/* removed: var _$parseUnit_208 = require('parse-unit') */; -/* - * autoContours: make a dummy axis object with dtick we can use - * as contours.size, and if needed we can use Axes.tickFirst - * with this axis object to calculate the start and end too - * - * start: the value to start the contours at - * end: the value to end at (must be > start) - * ncontours: max number of contours to make, like roughDTick - * - * returns: an axis object - */ -function autoContours(start, end, ncontours) { - var dummyAx = { - type: 'linear', - range: [start, end] - }; +var _$toPX_265 = toPX - _$axes_407.autoTicks( - dummyAx, - (end - start) / (ncontours || 15) - ); +var PIXELS_PER_INCH = 96 - return dummyAx; +function getPropertyInPX(element, prop) { + var parts = _$parseUnit_208(getComputedStyle(element).getPropertyValue(prop)) + return parts[0] * toPX(parts[1], element) } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +//This brutal hack is needed +function getSizeBrutal(unit, element) { + var testDIV = document.createElement('div') + testDIV.style['font-size'] = '128' + unit + element.appendChild(testDIV) + var size = getPropertyInPX(testDIV, 'font-size') / 128 + element.removeChild(testDIV) + return size +} -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +function toPX(str, element) { + element = element || document.body + str = (str || 'px').trim().toLowerCase() + if(element === window || element === document) { + element = document.body + } + switch(str) { + case '%': //Ambiguous, not sure if we should use width or height + return element.clientHeight / 100.0 + case 'ch': + case 'ex': + return getSizeBrutal(str, element) + case 'em': + return getPropertyInPX(element, 'font-size') + case 'rem': + return getPropertyInPX(document.body, 'font-size') + case 'vw': + return window.innerWidth/100 + case 'vh': + return window.innerHeight/100 + case 'vmin': + return Math.min(window.innerWidth, window.innerHeight) / 100 + case 'vmax': + return Math.max(window.innerWidth, window.innerHeight) / 100 + case 'in': + return PIXELS_PER_INCH + case 'cm': + return PIXELS_PER_INCH / 2.54 + case 'mm': + return PIXELS_PER_INCH / 25.4 + case 'pt': + return PIXELS_PER_INCH / 72 + case 'pc': + return PIXELS_PER_INCH / 6 + } + return 1 +} +'use strict' -var _$clean2dArray_475 = function clean2dArray(zOld, transpose) { - var rowlen, collen, getCollen, old2new, i, j; +/* removed: var _$toPX_265 = require('to-px') */; - function cleanZvalue(v) { - if(!_$fastIsnumeric_78(v)) return undefined; - return +v; - } +var _$mouseWheelListen_198 = mouseWheelListen - if(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]; }; +function mouseWheelListen(element, callback, noScroll) { + if(typeof element === 'function') { + noScroll = !!callback + callback = element + element = window + } + var lineHeight = _$toPX_265('ex', element) + var listener = function(ev) { + if(noScroll) { + ev.preventDefault() } - else { - rowlen = zOld.length; - getCollen = function(zOld, i) { return zOld[i].length; }; - old2new = function(zOld, i, j) { return zOld[i][j]; }; + var dx = ev.deltaX || 0 + var dy = ev.deltaY || 0 + var dz = ev.deltaZ || 0 + var mode = ev.deltaMode + var scale = 1 + switch(mode) { + case 1: + scale = lineHeight + break + case 2: + scale = window.innerHeight + break } - - var zNew = new Array(rowlen); - - for(i = 0; i < rowlen; i++) { - collen = getCollen(zOld, i); - zNew[i] = new Array(collen); - for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); + dx *= scale + dy *= scale + dz *= scale + if(dx || dy || dz) { + return callback(dx, dy, dz, ev) } - - return zNew; -}; + } + element.addEventListener('wheel', listener) + return listener +} /** * Copyright 2012-2018, Plotly, Inc. @@ -58414,433 +60044,896 @@ var _$clean2dArray_475 = function clean2dArray(zOld, transpose) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -var __BADNUM_477 = _$numerical_343.BADNUM; +/* removed: var _$mouseListen_195 = require('mouse-change'); */; +/* removed: var _$mouseWheelListen_198 = require('mouse-wheel'); */; +/* removed: var _$mouseEventOffset_196 = require('mouse-event-offset'); */; +/* removed: var _$constants_475 = require('../cartesian/constants'); */; +/* removed: var _$hasPassiveEvents_183 = require('has-passive-events'); */; -var _$convertColumnData_477 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { - var1Name = var1Name || 'x'; - var2Name = var2Name || 'y'; - arrayVarNames = arrayVarNames || ['z']; +var _$createCamera_499 = createCamera; - var col1 = trace[var1Name].slice(), - col2 = trace[var2Name].slice(), - textCol = trace.text, - colLen = Math.min(col1.length, col2.length), - hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), - col1Calendar = trace[var1Name + 'calendar'], - col2Calendar = trace[var2Name + 'calendar']; +function Camera2D(element, plot) { + this.element = element; + this.plot = plot; + this.mouseListener = null; + this.wheelListener = null; + this.lastInputTime = Date.now(); + this.lastPos = [0, 0]; + this.boxEnabled = false; + this.boxInited = false; + this.boxStart = [0, 0]; + this.boxEnd = [0, 0]; + this.dragStart = [0, 0]; +} - var i, j, arrayVar, newArray, arrayVarName; - for(i = 0; i < arrayVarNames.length; i++) { - arrayVar = trace[arrayVarNames[i]]; - if(arrayVar) colLen = Math.min(colLen, arrayVar.length); - } +function createCamera(scene) { + var element = scene.mouseContainer, + plot = scene.glplot, + result = new Camera2D(element, plot); - if(colLen < col1.length) col1 = col1.slice(0, colLen); - if(colLen < col2.length) col2 = col2.slice(0, colLen); + function unSetAutoRange() { + scene.xaxis.autorange = false; + scene.yaxis.autorange = false; + } - for(i = 0; i < colLen; i++) { - col1[i] = ax1.d2c(col1[i], 0, col1Calendar); - col2[i] = ax2.d2c(col2[i], 0, col2Calendar); + function getSubplotConstraint() { + // note: this assumes we only have one x and one y axis on this subplot + // when this constraint is lifted this block won't make sense + var constraints = scene.graphDiv._fullLayout._axisConstraintGroups; + var xaId = scene.xaxis._id; + var yaId = scene.yaxis._id; + for(var i = 0; i < constraints.length; i++) { + if(constraints[i][xaId] !== -1) { + if(constraints[i][yaId] !== -1) return true; + break; + } + } + return false; } - var col1dv = _$lib_363.distinctVals(col1), - col1vals = col1dv.vals, - col2dv = _$lib_363.distinctVals(col2), - col2vals = col2dv.vals, - newArrays = []; + result.mouseListener = _$mouseListen_195(element, handleInteraction); - for(i = 0; i < arrayVarNames.length; i++) { - newArrays[i] = _$lib_363.init2dArray(col2vals.length, col1vals.length); - } + // enable simple touch interactions + element.addEventListener('touchstart', function(ev) { + var xy = _$mouseEventOffset_196(ev.changedTouches[0], element); + handleInteraction(0, xy[0], xy[1]); + handleInteraction(1, xy[0], xy[1]); - var i1, i2, text; + ev.preventDefault(); + }, _$hasPassiveEvents_183 ? {passive: false} : false); + element.addEventListener('touchmove', function(ev) { + ev.preventDefault(); + var xy = _$mouseEventOffset_196(ev.changedTouches[0], element); + handleInteraction(1, xy[0], xy[1]); - if(hasColumnText) text = _$lib_363.init2dArray(col2vals.length, col1vals.length); + ev.preventDefault(); + }, _$hasPassiveEvents_183 ? {passive: false} : false); + element.addEventListener('touchend', function(ev) { + handleInteraction(0, result.lastPos[0], result.lastPos[1]); - for(i = 0; i < colLen; i++) { - if(col1[i] !== __BADNUM_477 && col2[i] !== __BADNUM_477) { - i1 = _$lib_363.findBin(col1[i] + col1dv.minDiff / 2, col1vals); - i2 = _$lib_363.findBin(col2[i] + col2dv.minDiff / 2, col2vals); + ev.preventDefault(); + }, _$hasPassiveEvents_183 ? {passive: false} : false); - for(j = 0; j < arrayVarNames.length; j++) { - arrayVarName = arrayVarNames[j]; - arrayVar = trace[arrayVarName]; - newArray = newArrays[j]; - newArray[i2][i1] = arrayVar[i]; - } + function handleInteraction(buttons, x, y) { + var dataBox = scene.calcDataBox(), + viewBox = plot.viewBox; - if(hasColumnText) text[i2][i1] = textCol[i]; - } - } + var lastX = result.lastPos[0], + lastY = result.lastPos[1]; - // hack for Plotly.react - save the input arrays for diffing purposes - trace['_input_' + var1Name] = trace[var1Name]; - trace['_input_' + var2Name] = trace[var2Name]; - trace[var1Name] = col1vals; - trace[var2Name] = col2vals; - for(j = 0; j < arrayVarNames.length; j++) { - trace['_input_' + arrayVarNames[j]] = trace[arrayVarNames[j]]; - trace[arrayVarNames[j]] = newArrays[j]; - } - if(hasColumnText) trace.text = text; -}; + var MINDRAG = _$constants_475.MINDRAG * plot.pixelRatio; + var MINZOOM = _$constants_475.MINZOOM * plot.pixelRatio; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 dx, dy; + + x *= plot.pixelRatio; + y *= plot.pixelRatio; + // mouseChange gives y about top; convert to about bottom + y = (viewBox[3] - viewBox[1]) - y; -'use strict'; + function updateRange(i0, start, end) { + var range0 = Math.min(start, end), + range1 = Math.max(start, end); -var _$maxRowLength_483 = function maxRowLength(z) { - var len = 0; + if(range0 !== range1) { + dataBox[i0] = range0; + dataBox[i0 + 2] = range1; + result.dataBox = dataBox; + scene.setRanges(dataBox); + } + else { + scene.selectBox.selectBox = [0, 0, 1, 1]; + scene.glplot.setDirty(); + } + } - for(var i = 0; i < z.length; i++) { - len = Math.max(len, z[i].length); - } + switch(scene.fullLayout.dragmode) { + case 'zoom': + if(buttons) { + var dataX = x / + (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) + + dataBox[0]; + var dataY = y / + (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) + + dataBox[1]; - return len; -}; + if(!result.boxInited) { + result.boxStart[0] = dataX; + result.boxStart[1] = dataY; + result.dragStart[0] = x; + result.dragStart[1] = y; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + result.boxEnd[0] = dataX; + result.boxEnd[1] = dataY; -'use strict'; + // we need to mark the box as initialized right away + // so that we can tell the start and end points apart + result.boxInited = true; -/* removed: var _$maxRowLength_483 = require('./max_row_length'); */; + // but don't actually enable the box until the cursor moves + if(!result.boxEnabled && ( + result.boxStart[0] !== result.boxEnd[0] || + result.boxStart[1] !== result.boxEnd[1]) + ) { + result.boxEnabled = true; + } -/* 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 - */ -var _$findEmpties_479 = function findEmpties(z) { - var empties = [], - neighborHash = {}, - noNeighborList = [], - nextRow = z[0], - row = [], - blank = [0, 0, 0], - rowLength = _$maxRowLength_483(z), - prevRow, - i, - j, - thisPt, - p, - neighborCount, - newNeighborHash, - foundNewNeighbors; + // constrain aspect ratio if the axes require it + var smallDx = Math.abs(result.dragStart[0] - x) < MINZOOM; + var smallDy = Math.abs(result.dragStart[1] - y) < MINZOOM; + if(getSubplotConstraint() && !(smallDx && smallDy)) { + dx = result.boxEnd[0] - result.boxStart[0]; + dy = result.boxEnd[1] - result.boxStart[1]; + var dydx = (dataBox[3] - dataBox[1]) / (dataBox[2] - dataBox[0]); - 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(Math.abs(dx * dydx) > Math.abs(dy)) { + result.boxEnd[1] = result.boxStart[1] + + Math.abs(dx) * dydx * (dy >= 0 ? 1 : -1); - 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++; + // gl-select-box clips to the plot area bounds, + // which breaks the axis constraint, so don't allow + // this box to go out of bounds + if(result.boxEnd[1] < dataBox[1]) { + result.boxEnd[1] = dataBox[1]; + result.boxEnd[0] = result.boxStart[0] + + (dataBox[1] - result.boxStart[1]) / Math.abs(dydx); + } + else if(result.boxEnd[1] > dataBox[3]) { + result.boxEnd[1] = dataBox[3]; + result.boxEnd[0] = result.boxStart[0] + + (dataBox[3] - result.boxStart[1]) / Math.abs(dydx); + } + } + else { + result.boxEnd[0] = result.boxStart[0] + + Math.abs(dy) / dydx * (dx >= 0 ? 1 : -1); - // if all neighbors that could exist do, we don't - // need this for finding farther neighbors - if(neighborCount < 4) { - neighborHash[[i, j]] = [i, j, neighborCount]; + if(result.boxEnd[0] < dataBox[0]) { + result.boxEnd[0] = dataBox[0]; + result.boxEnd[1] = result.boxStart[1] + + (dataBox[0] - result.boxStart[0]) * Math.abs(dydx); + } + else if(result.boxEnd[0] > dataBox[2]) { + result.boxEnd[0] = dataBox[2]; + result.boxEnd[1] = result.boxStart[1] + + (dataBox[2] - result.boxStart[0]) * Math.abs(dydx); + } + } + } + // otherwise clamp small changes to the origin so we get 1D zoom + else { + if(smallDx) result.boxEnd[0] = result.boxStart[0]; + if(smallDy) result.boxEnd[1] = result.boxStart[1]; } - - empties.push([i, j, neighborCount]); } - else noNeighborList.push([i, j]); - } - } - } + else if(result.boxEnabled) { + dx = result.boxStart[0] !== result.boxEnd[0]; + dy = result.boxStart[1] !== result.boxEnd[1]; + if(dx || dy) { + if(dx) { + updateRange(0, result.boxStart[0], result.boxEnd[0]); + scene.xaxis.autorange = false; + } + if(dy) { + updateRange(1, result.boxStart[1], result.boxEnd[1]); + scene.yaxis.autorange = false; + } + scene.relayoutCallback(); + } + else { + scene.glplot.setDirty(); + } + result.boxEnabled = false; + result.boxInited = false; + } + // if box was inited but button released then - reset the box + else if(result.boxInited) { + result.boxInited = false; + } + break; - while(noNeighborList.length) { - newNeighborHash = {}; - foundNewNeighbors = false; + case 'pan': + result.boxEnabled = false; + result.boxInited = 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]; + if(buttons) { + if(!result.panning) { + result.dragStart[0] = x; + result.dragStart[1] = y; + } - 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(Math.abs(result.dragStart[0] - x) < MINDRAG) x = result.dragStart[0]; + if(Math.abs(result.dragStart[1] - y) < MINDRAG) y = result.dragStart[1]; - if(neighborCount) { - newNeighborHash[thisPt] = [i, j, neighborCount]; - noNeighborList.splice(p, 1); - foundNewNeighbors = true; - } - } + dx = (lastX - x) * (dataBox[2] - dataBox[0]) / + (plot.viewBox[2] - plot.viewBox[0]); + dy = (lastY - y) * (dataBox[3] - dataBox[1]) / + (plot.viewBox[3] - plot.viewBox[1]); - if(!foundNewNeighbors) { - throw 'findEmpties iterated with no new neighbors'; - } + dataBox[0] += dx; + dataBox[2] += dx; + dataBox[1] += dy; + dataBox[3] += dy; - // put these new cells into the main neighbor list - for(thisPt in newNeighborHash) { - neighborHash[thisPt] = newNeighborHash[thisPt]; - empties.push(newNeighborHash[thisPt]); + scene.setRanges(dataBox); + + result.panning = true; + result.lastInputTime = Date.now(); + unSetAutoRange(); + scene.cameraChanged(); + scene.handleAnnotations(); + } + else if(result.panning) { + result.panning = false; + scene.relayoutCallback(); + } + break; } + + result.lastPos[0] = x; + result.lastPos[1] = y; } - // sort the full list in descending order of neighbor count - return empties.sort(function(a, b) { return b[2] - a[2]; }); -}; + result.wheelListener = _$mouseWheelListen_198(element, function(dx, dy) { + if(!scene.scrollZoom) return false; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 dataBox = scene.calcDataBox(), + viewBox = plot.viewBox; -'use strict'; + var lastX = result.lastPos[0], + lastY = result.lastPos[1]; + + var scale = Math.exp(5.0 * dy / (viewBox[3] - viewBox[1])); + + var cx = lastX / + (viewBox[2] - viewBox[0]) * (dataBox[2] - dataBox[0]) + + dataBox[0]; + var cy = lastY / + (viewBox[3] - viewBox[1]) * (dataBox[3] - dataBox[1]) + + dataBox[1]; -var __isArrayOrTypedArray_480 = _$lib_363.isArrayOrTypedArray; + dataBox[0] = (dataBox[0] - cx) * scale + cx; + dataBox[2] = (dataBox[2] - cx) * scale + cx; + dataBox[1] = (dataBox[1] - cy) * scale + cy; + dataBox[3] = (dataBox[3] - cy) * scale + cy; -var _$has_columns_480 = function(trace) { - return !__isArrayOrTypedArray_480(trace.z[0]); -}; + scene.setRanges(dataBox); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + result.lastInputTime = Date.now(); + unSetAutoRange(); + scene.cameraChanged(); + scene.handleAnnotations(); + scene.relayoutCallback(); -'use strict'; + return true; + }, true); -/* removed: var _$lib_363 = require('../../lib'); */; + return result; +} -var INTERPTHRESHOLD = 1e-2, - NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; +var _$clamp_54 = clamp -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); +function clamp(value, min, max) { + return min < max + ? (value < min ? min : value > max ? max : value) + : (value < max ? max : value > min ? min : value) } -var _$interp2d_481 = function interp2d(z, emptyPoints, savedInterpZ) { - // fill in any missing data in 2D array z 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) - var maxFractionalChange = 1, - i, - thisPt; - - if(Array.isArray(savedInterpZ)) { - for(i = 0; i < emptyPoints.length; i++) { - thisPt = emptyPoints[i]; - z[thisPt[0]][thisPt[1]] = savedInterpZ[thisPt[0]][thisPt[1]]; - } - } - else { - // one pass to fill in a starting value for all the empties - iterateInterp2d(z, emptyPoints); - } +'use strict' + +var _$colorName_58 = { + "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] +}; - // we're don't need to iterate lone empties - remove them - for(i = 0; i < emptyPoints.length; i++) { - if(emptyPoints[i][2] < 4) break; +var _$defined_72 = function () { + for (var i = 0; i < arguments.length; i++) { + if (arguments[i] !== undefined) return arguments[i]; } - // 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_363.log('interp2d didn\'t converge quickly', maxFractionalChange); - } +'use strict'; +var __toString_192 = Object.prototype.toString; - return z; +var _$isPlainObj_192 = function (x) { + var prototype; + return __toString_192.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); }; -function iterateInterp2d(z, emptyPoints, overshoot) { - var maxFractionalChange = 0, - thisPt, - i, - j, - p, - q, - neighborShift, - neighborRow, - neighborVal, - neighborCount, - neighborSum, - initialVal, - minNeighbor, - maxNeighbor; +var _$parse_60 = {}; +(function (global){ +/** + * @module color-parse + */ + +'use strict' + +/* removed: var _$colorName_58 = require('color-name') */; +/* removed: var _$isPlainObj_192 = require('is-plain-obj') */; +/* removed: var _$defined_72 = require('defined') */; + +_$parse_60 = parse + +/** + * Base hues + * http://dev.w3.org/csswg/css-color/#typedef-named-hue + */ +//FIXME: use external hue detector +var baseHues = { + red: 0, + orange: 60, + yellow: 120, + green: 180, + blue: 240, + purple: 300 +} + +/** + * Parse color from the string passed + * + * @return {Object} A space indicator `space`, an array `values` and `alpha` + */ +function parse (cstr) { + var m, parts = [], alpha = 1, space + + if (typeof cstr === 'string') { + //keyword + if (_$colorName_58[cstr]) { + parts = _$colorName_58[cstr].slice() + space = 'rgb' + } + + //reserved words + else if (cstr === 'transparent') { + alpha = 0 + space = 'rgb' + parts = [0,0,0] + } + + //hex + else if (/^#[A-Fa-f0-9]+$/.test(cstr)) { + var base = cstr.slice(1) + var size = base.length + var isShort = size <= 4 + alpha = 1 + + if (isShort) { + parts = [ + parseInt(base[0] + base[0], 16), + parseInt(base[1] + base[1], 16), + parseInt(base[2] + base[2], 16) + ] + if (size === 4) { + alpha = parseInt(base[3] + base[3], 16) / 255 + } + } + else { + parts = [ + parseInt(base[0] + base[1], 16), + parseInt(base[2] + base[3], 16), + parseInt(base[4] + base[5], 16) + ] + if (size === 8) { + alpha = parseInt(base[6] + base[7], 16) / 255 + } + } + + if (!parts[0]) parts[0] = 0 + if (!parts[1]) parts[1] = 0 + if (!parts[2]) parts[2] = 0 + + space = 'rgb' + } + + //color space + else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) { + var name = m[1] + var base = name.replace(/a$/, '') + space = base + var size = base === 'cmyk' ? 4 : base === 'gray' ? 1 : 3 + parts = m[2].trim() + .split(/\s*,\s*/) + .map(function (x, i) { + // + if (/%$/.test(x)) { + //alpha + if (i === size) return parseFloat(x) / 100 + //rgb + if (base === 'rgb') return parseFloat(x) * 255 / 100 + return parseFloat(x) + } + //hue + else if (base[i] === 'h') { + // + if (/deg$/.test(x)) { + return parseFloat(x) + } + // + else if (baseHues[x] !== undefined) { + return baseHues[x] + } + } + return parseFloat(x) + }) + + if (name === base) parts.push(1) + alpha = parts[size] === undefined ? 1 : parts[size] + parts = parts.slice(0, size) + } + + //named channels case + else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) { + parts = cstr.match(/([0-9]+)/g).map(function (value) { + return parseFloat(value) + }) + + space = cstr.match(/([a-z])/ig).join('').toLowerCase() + } + } + + //numeric case + else if (typeof cstr === 'number') { + space = 'rgb' + parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff] + } + + //object case - detects css cases of rgb and hsl + else if (_$isPlainObj_192(cstr)) { + var r = _$defined_72(cstr.r, cstr.red, cstr.R, null) + + if (r !== null) { + space = 'rgb' + parts = [ + r, + _$defined_72(cstr.g, cstr.green, cstr.G), + _$defined_72(cstr.b, cstr.blue, cstr.B) + ] + } + else { + space = 'hsl' + parts = [ + _$defined_72(cstr.h, cstr.hue, cstr.H), + _$defined_72(cstr.s, cstr.saturation, cstr.S), + _$defined_72(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness) + ] + } + + alpha = _$defined_72(cstr.a, cstr.alpha, cstr.opacity, 1) + + if (cstr.opacity != null) alpha /= 100 + } + + //array + else if (Array.isArray(cstr) || global.ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(cstr)) { + parts = [cstr[0], cstr[1], cstr[2]] + space = 'rgb' + alpha = cstr.length === 4 ? cstr[3] : 1 + } + + return { + space: space, + values: parts, + alpha: alpha + } +} - for(p = 0; p < emptyPoints.length; p++) { - thisPt = emptyPoints[p]; - i = thisPt[0]; - j = thisPt[1]; - initialVal = z[i][j]; - neighborSum = 0; - neighborCount = 0; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +/** + * RGB space. + * + * @module color-space/rgb + */ +'use strict' - 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; - } - } +var _$rgb_63 = { + name: 'rgb', + min: [0,0,0], + max: [255,255,255], + channel: ['red', 'green', 'blue'], + alias: ['RGB'] +}; - if(neighborCount === 0) { - throw 'iterateInterp2d order is wrong: no defined neighbors'; - } +/** + * @module color-space/hsl + */ +'use strict' - // 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; +/* removed: var _$rgb_63 = require('./rgb'); */; - 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; +var _$hsl_62 = { + name: 'hsl', + min: [0,0,0], + max: [360,100,100], + channel: ['hue', 'saturation', 'lightness'], + alias: ['HSL'], - if(maxNeighbor > minNeighbor) { - maxFractionalChange = Math.max(maxFractionalChange, - Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor)); - } - } - } + rgb: function(hsl) { + var h = hsl[0] / 360, + s = hsl[1] / 100, + l = hsl[2] / 100, + t1, t2, t3, rgb, val; - return maxFractionalChange; -} + if (s === 0) { + val = l * 255; + return [val, val, val]; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (l < 0.5) { + t2 = l * (1 + s); + } + else { + t2 = l + s - l * s; + } + t1 = 2 * l - t2; -'use strict'; + 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; + } -/* removed: var _$registry_451 = require('../../registry'); */; -var __isArrayOrTypedArray_482 = _$lib_363.isArrayOrTypedArray; + rgb[i] = val * 255; + } -var _$makeBoundArray_482 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { - var arrayOut = [], - isContour = _$registry_451.traceIs(trace, 'contour'), - isHist = _$registry_451.traceIs(trace, 'histogram'), - isGL2D = _$registry_451.traceIs(trace, 'gl2d'), - v0, - dv, - i; + return rgb; + } +}; - var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_482(arrayIn) && arrayIn.length > 1; - if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) { - var len = arrayIn.length; +//extend rgb +_$rgb_63.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; - // given vals are brick centers - // hopefully length === numbricks, but use this method even if too few are supplied - // and extend it linearly based on the last two points - if(len <= numbricks) { - // contour plots only want the centers - if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks); - else if(numbricks === 1) { - arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5]; - } - else { - arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]]; + 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; + } - for(i = 1; i < len; i++) { - arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5); - } + h = Math.min(h * 60, 360); - arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]); - } + if (h < 0) { + h += 360; + } - if(len < numbricks) { - var lastPt = arrayOut[arrayOut.length - 1], - delta = lastPt - arrayOut[arrayOut.length - 2]; + l = (min + max) / 2; - for(i = len; i < numbricks; i++) { - lastPt += delta; - arrayOut.push(lastPt); - } - } - } - else { - // hopefully length === numbricks+1, but do something regardless: - // given vals are brick boundaries - return isContour ? - arrayIn.slice(0, numbricks) : // we must be strict for contours - arrayIn.slice(0, numbricks + 1); - } - } - else { - dv = dvIn || 1; + if (max === min) { + s = 0; + } + else if (l <= 0.5) { + s = delta / (max + min); + } + else { + s = delta / (2 - max - min); + } - var calendar = trace[ax._id.charAt(0) + 'calendar']; + return [h, s * 100, l * 100]; +}; - if(isHist || ax.type === 'category') v0 = ax.r2c(v0In, 0, calendar) || 0; - else if(__isArrayOrTypedArray_482(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; - else if(v0In === undefined) v0 = 0; - else v0 = ax.d2c(v0In, 0, calendar); +/** @module color-rgba */ + +'use strict' + +/* removed: var _$parse_60 = require('color-parse') */; +/* removed: var _$hsl_62 = require('color-space/hsl') */; +/* removed: var _$clamp_54 = require('clamp') */; + +var _$rgba_61 = function rgba (color) { + var values, i, l + + if (typeof color !== 'string') throw Error('Argument should be a string') + + //attempt to parse non-array arguments + var parsed = _$parse_60(color) + + if (!parsed.space) return [] + + values = Array(3) + values[0] = _$clamp_54(parsed.values[0], 0, 255) + values[1] = _$clamp_54(parsed.values[1], 0, 255) + values[2] = _$clamp_54(parsed.values[2], 0, 255) + + if (parsed.space[0] === 'h') { + values = _$hsl_62.rgb(values) + } + + values.push(_$clamp_54(parsed.alpha, 0, 1)) + + return values +} - for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) { - arrayOut.push(v0 + dv * i); - } - } +var _$dtype_75 = 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 + } +} - return arrayOut; -}; +/** @module color-rgba */ + +'use strict' + +/* removed: var _$rgba_61 = require('color-rgba') */; +/* removed: var _$clamp_54 = require('clamp') */; +/* removed: var _$dtype_75 = require('dtype') */; + +var _$normalize_59 = 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_75(type) + var output = new Ctor(4) + + //same class does not change values + if (color instanceof Ctor) { + if (Array.isArray(color)) { + return color.slice() + } + + output.set(color) + + return output + } + + var normalize = type !== 'uint8' && type !== 'uint8_clamped' + + //consider uint8 array as 0..255 channel values + if (color instanceof Uint8Array || color instanceof Uint8ClampedArray) { + 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 + } + + //attempt to parse non-array arguments + if (!color.length || typeof color === 'string') { + color = _$rgba_61(color) + color[0] /= 255 + color[1] /= 255 + color[2] /= 255 + } + + //consider every other array type as 0..1 float values + if (!normalize) { + output[0] = _$clamp_54(Math.round(color[0] * 255), 0, 255) + output[1] = _$clamp_54(Math.round(color[1] * 255), 0, 255) + output[2] = _$clamp_54(Math.round(color[2] * 255), 0, 255) + output[3] = color[3] == null ? 255 : _$clamp_54(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 +} /** * Copyright 2012-2018, Plotly, Inc. @@ -58853,19 +60946,14 @@ var _$makeBoundArray_482 = function makeBoundArray(trace, arrayIn, v0In, dvIn, n 'use strict'; +/* removed: var _$normalize_59 = require('color-normalize'); */; -var _$doAvg_489 = function doAvg(size, counts) { - var nMax = size.length, - total = 0; - for(var i = 0; i < nMax; i++) { - if(counts[i]) { - size[i] /= counts[i]; - total += size[i]; - } - else size[i] = null; - } - return total; -}; +function str2RgbaArray(color) { + if(!color) return [0, 0, 0, 1]; + return _$normalize_59(color); +} + +var _$str2RgbaArray_448 = str2RgbaArray; /** * Copyright 2012-2018, Plotly, Inc. @@ -58878,360 +60966,240 @@ var _$doAvg_489 = function doAvg(size, counts) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$axes_470 = require('../cartesian/axes'); */; +/* removed: var _$convertHTMLToUnicode_423 = require('../../lib/html2unicode'); */; +/* removed: var _$str2RgbaArray_448 = require('../../lib/str2rgbarray'); */; -var _$bin_functions_490 = { - count: function(n, i, size) { - size[n]++; - return 1; - }, +function Axes2DOptions(scene) { + this.scene = scene; + this.gl = scene.gl; + this.pixelRatio = scene.pixelRatio; - sum: function(n, i, size, counterData) { - var v = counterData[i]; - if(_$fastIsnumeric_78(v)) { - v = Number(v); - size[n] += v; - return v; - } - return 0; - }, + this.screenBox = [0, 0, 1, 1]; + this.viewBox = [0, 0, 1, 1]; + this.dataBox = [-1, -1, 1, 1]; - avg: function(n, i, size, counterData, counts) { - var v = counterData[i]; - if(_$fastIsnumeric_78(v)) { - v = Number(v); - size[n] += v; - counts[n]++; - } - return 0; - }, + this.borderLineEnable = [false, false, false, false]; + this.borderLineWidth = [1, 1, 1, 1]; + this.borderLineColor = [ + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1] + ]; - min: function(n, i, size, counterData) { - var v = counterData[i]; - if(_$fastIsnumeric_78(v)) { - v = Number(v); - if(!_$fastIsnumeric_78(size[n])) { - size[n] = v; - return v; - } - else if(size[n] > v) { - var delta = v - size[n]; - size[n] = v; - return delta; - } - } - return 0; - }, + this.ticks = [[], []]; + this.tickEnable = [true, true, false, false]; + this.tickPad = [15, 15, 15, 15]; + this.tickAngle = [0, 0, 0, 0]; + this.tickColor = [ + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1] + ]; + this.tickMarkLength = [0, 0, 0, 0]; + this.tickMarkWidth = [0, 0, 0, 0]; + this.tickMarkColor = [ + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1] + ]; - max: function(n, i, size, counterData) { - var v = counterData[i]; - if(_$fastIsnumeric_78(v)) { - v = Number(v); - if(!_$fastIsnumeric_78(size[n])) { - size[n] = v; - return v; - } - else if(size[n] < v) { - var delta = v - size[n]; - size[n] = v; - return delta; - } - } - return 0; - } -}; + this.labels = ['x', 'y']; + this.labelEnable = [true, true, false, false]; + this.labelAngle = [0, Math.PI / 2, 0, 3.0 * Math.PI / 2]; + this.labelPad = [15, 15, 15, 15]; + this.labelSize = [12, 12]; + this.labelFont = ['sans-serif', 'sans-serif']; + this.labelColor = [ + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1], + [0, 0, 0, 1] + ]; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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.title = ''; + this.titleEnable = true; + this.titleCenter = [0, 0, 0, 0]; + this.titleAngle = 0; + this.titleColor = [0, 0, 0, 1]; + this.titleFont = 'sans-serif'; + this.titleSize = 18; + this.gridLineEnable = [true, true]; + this.gridLineColor = [ + [0, 0, 0, 0.5], + [0, 0, 0, 0.5] + ]; + this.gridLineWidth = [1, 1]; -'use strict'; + this.zeroLineEnable = [true, true]; + this.zeroLineWidth = [1, 1]; + this.zeroLineColor = [ + [0, 0, 0, 1], + [0, 0, 0, 1] + ]; -/* removed: var _$numerical_343 = require('../../constants/numerical'); */; -var oneYear = _$numerical_343.ONEAVGYEAR; -var oneMonth = _$numerical_343.ONEAVGMONTH; -var oneDay = _$numerical_343.ONEDAY; -var oneHour = _$numerical_343.ONEHOUR; -var oneMin = _$numerical_343.ONEMIN; -var oneSec = _$numerical_343.ONESEC; -var tickIncrement = _$axes_407.tickIncrement; + this.borderColor = false; + this.backgroundColor = [0, 0, 0, 0]; + this.static = this.scene.staticPlot; +} -/* - * 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` - */ -var _$getBinSpanLabelRound_491 = 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) - ); +var __proto_500 = Axes2DOptions.prototype; - // 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; - } +var AXES = ['xaxis', 'yaxis']; - if(pa.type === 'date' && digit > oneDay) { - var dashExclude = (digit === oneYear) ? 1 : 6; - var increment = (digit === oneYear) ? 'M12' : 'M1'; +__proto_500.merge = function(options) { - 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); + // titles are rendered in SVG + this.titleEnable = false; + this.backgroundColor = _$str2RgbaArray_448(options.plot_bgcolor); - if(roundedV < v) { - var nextV = tickIncrement(roundedV, increment, false, calendar); - if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV; - } + var axisName, ax, axTitle, axMirror; + var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks; + var i, j; - if(isRightEdge && disambiguateEdges) { - return tickIncrement(roundedV, increment, true, calendar); - } + for(i = 0; i < 2; ++i) { + axisName = AXES[i]; + var axisLetter = axisName.charAt(0); - return roundedV; - }; - } + // get options relevant to this subplot, + // '_name' is e.g. xaxis, xaxis2, yaxis, yaxis4 ... + ax = options[this.scene[axisName]._name]; - 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; - }; -}; + axTitle = ax.title === this.scene.fullLayout._dfltTitle[axisLetter] ? '' : ax.title; -/* - * 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; + for(j = 0; j <= 2; j += 2) { + this.labelEnable[i + j] = false; + this.labels[i + j] = _$convertHTMLToUnicode_423(axTitle); + this.labelColor[i + j] = _$str2RgbaArray_448(ax.titlefont.color); + this.labelFont[i + j] = ax.titlefont.family; + this.labelSize[i + j] = ax.titlefont.size; + this.labelPad[i + j] = this.getLabelPad(axisName, ax); - 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; -} + this.tickEnable[i + j] = false; + this.tickColor[i + j] = _$str2RgbaArray_448((ax.tickfont || {}).color); + this.tickAngle[i + j] = (ax.tickangle === 'auto') ? + 0 : + Math.PI * -ax.tickangle / 180; + this.tickPad[i + j] = this.getTickPad(ax); -/* - * 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; + this.tickMarkLength[i + j] = 0; + this.tickMarkWidth[i + j] = ax.tickwidth || 0; + this.tickMarkColor[i + j] = _$str2RgbaArray_448(ax.tickcolor); + + this.borderLineEnable[i + j] = false; + this.borderLineColor[i + j] = _$str2RgbaArray_448(ax.linecolor); + this.borderLineWidth[i + j] = ax.linewidth || 0; } - if(dv > oneHour) return oneHour; - if(dv > oneMin) return oneMin; - return oneSec; - } - return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10)); -} + hasSharedAxis = this.hasSharedAxis(ax); + hasAxisInDfltPos = this.hasAxisInDfltPos(axisName, ax) && !hasSharedAxis; + hasAxisInAltrPos = this.hasAxisInAltrPos(axisName, ax) && !hasSharedAxis; -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]; + axMirror = ax.mirror || false; + mirrorLines = hasSharedAxis ? + (String(axMirror).indexOf('all') !== -1) : // 'all' or 'allticks' + !!axMirror; // all but false + mirrorTicks = hasSharedAxis ? + (axMirror === 'allticks') : + (String(axMirror).indexOf('ticks') !== -1); // 'ticks' or 'allticks' - } - return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1; -} + // Axis titles and tick labels can only appear of one side of the scene + // and are never show on subplots that share existing axes. + + if(hasAxisInDfltPos) this.labelEnable[i] = true; + else if(hasAxisInAltrPos) this.labelEnable[i + 2] = true; + + if(hasAxisInDfltPos) this.tickEnable[i] = ax.showticklabels; + else if(hasAxisInAltrPos) this.tickEnable[i + 2] = ax.showticklabels; -function dateParts(v, pa, calendar) { - var parts = pa.c2d(v, oneYear, calendar).split('-'); - if(parts[0] === '') { - parts.unshift(); - parts[0] = '-' + parts[0]; - } - return parts; -} + // Grid lines and ticks can appear on both sides of the scene + // and can appear on subplot that share existing axes via `ax.mirror`. -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(hasAxisInDfltPos || mirrorLines) this.borderLineEnable[i] = ax.showline; + if(hasAxisInAltrPos || mirrorLines) this.borderLineEnable[i + 2] = ax.showline; + if(hasAxisInDfltPos || mirrorTicks) this.tickMarkLength[i] = this.getTickMarkLength(ax); + if(hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i + 2] = this.getTickMarkLength(ax); -'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -var cleanDate = _$lib_363.cleanDate; -/* removed: var _$numerical_343 = require('../../constants/numerical'); */; -var __ONEDAY_492 = _$numerical_343.ONEDAY; -var __BADNUM_492 = _$numerical_343.BADNUM; + this.gridLineEnable[i] = ax.showgrid; + this.gridLineColor[i] = _$str2RgbaArray_448(ax.gridcolor); + this.gridLineWidth[i] = ax.gridwidth; -/* - * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) - * Mutates trace so all these attributes are valid. - * - * Normally this kind of thing would happen during supplyDefaults, but - * in this case we need to know the axis type, and axis type isn't set until - * after trace supplyDefaults are completed. So this gets called during the - * calc step, when data are inserted into bins. - */ -var _$cleanBins_492 = function cleanBins(trace, ax, binDirection) { - var axType = ax.type, - binAttr = binDirection + 'bins', - bins = trace[binAttr]; + this.zeroLineEnable[i] = ax.zeroline; + this.zeroLineColor[i] = _$str2RgbaArray_448(ax.zerolinecolor); + this.zeroLineWidth[i] = ax.zerolinewidth; + } +}; - if(!bins) bins = trace[binAttr] = {}; +// is an axis shared with an already-drawn subplot ? +__proto_500.hasSharedAxis = function(ax) { + var scene = this.scene; + var subplotIds = scene.fullLayout._subplots.gl2d; + var list = _$axes_470.findSubplotsWithAxis(subplotIds, ax); - var cleanBound = (axType === 'date') ? - function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_492, bins.calendar) : null; } : - function(v) { return _$fastIsnumeric_78(v) ? Number(v) : null; }; + // if index === 0, then the subplot is already drawn as subplots + // are drawn in order. + return (list.indexOf(scene.id) !== 0); +}; - bins.start = cleanBound(bins.start); - bins.end = cleanBound(bins.end); +// has an axis in default position (i.e. bottom/left) ? +__proto_500.hasAxisInDfltPos = function(axisName, ax) { + var axSide = ax.side; - // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) - // but without the extra string options for log axes - // ie the only strings we accept are M for months - var sizeDflt = (axType === 'date') ? __ONEDAY_492 : 1, - binSize = bins.size; + if(axisName === 'xaxis') return (axSide === 'bottom'); + else if(axisName === 'yaxis') return (axSide === 'left'); +}; - if(_$fastIsnumeric_78(binSize)) { - bins.size = (binSize > 0) ? Number(binSize) : sizeDflt; - } - else if(typeof binSize !== 'string') { - bins.size = sizeDflt; - } - else { - // date special case: "M" gives bins every (integer) n months - var prefix = binSize.charAt(0), - sizeNum = binSize.substr(1); +// has an axis in alternate position (i.e. top/right) ? +__proto_500.hasAxisInAltrPos = function(axisName, ax) { + var axSide = ax.side; - sizeNum = _$fastIsnumeric_78(sizeNum) ? Number(sizeNum) : 0; - if((sizeNum <= 0) || !( - axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum) - )) { - bins.size = sizeDflt; - } - } + if(axisName === 'xaxis') return (axSide === 'top'); + else if(axisName === 'yaxis') return (axSide === 'right'); +}; - var autoBinAttr = 'autobin' + binDirection; +__proto_500.getLabelPad = function(axisName, ax) { + var offsetBase = 1.5, + fontSize = ax.titlefont.size, + showticklabels = ax.showticklabels; - if(typeof trace[autoBinAttr] !== 'boolean') { - trace[autoBinAttr] = trace._fullInput[autoBinAttr] = trace._input[autoBinAttr] = !( - (bins.start || bins.start === 0) && - (bins.end || bins.end === 0) - ); + if(axisName === 'xaxis') { + return (ax.side === 'top') ? + -10 + fontSize * (offsetBase + (showticklabels ? 1 : 0)) : + -10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0)); } - - if(!trace[autoBinAttr]) { - delete trace['nbins' + binDirection]; - delete trace._fullInput['nbins' + binDirection]; + else if(axisName === 'yaxis') { + return (ax.side === 'right') ? + 10 + fontSize * (offsetBase + (showticklabels ? 1 : 0.5)) : + 10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0)); } }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - +__proto_500.getTickPad = function(ax) { + return (ax.ticks === 'outside') ? 10 + ax.ticklen : 15; +}; -'use strict'; +__proto_500.getTickMarkLength = function(ax) { + if(!ax.ticks) return 0; + var ticklen = ax.ticklen; -var _$norm_functions_493 = { - percent: function(size, total) { - var nMax = size.length, - norm = 100 / total; - for(var n = 0; n < nMax; n++) size[n] *= norm; - }, - probability: function(size, total) { - var nMax = size.length; - for(var n = 0; n < nMax; n++) size[n] /= total; - }, - density: function(size, total, inc, yinc) { - var nMax = size.length; - yinc = yinc || 1; - for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc; - }, - 'probability density': function(size, total, inc, yinc) { - var nMax = size.length; - if(yinc) total /= yinc; - for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total; - } + return (ax.ticks === 'inside') ? -ticklen : ticklen; }; + +function createAxes2D(scene) { + return new Axes2DOptions(scene); +} + +var _$createAxes2D_500 = createAxes2D; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -59243,1201 +61211,712 @@ var _$norm_functions_493 = { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$bin_functions_490 = require('../histogram/bin_functions'); */; -/* removed: var _$norm_functions_493 = require('../histogram/norm_functions'); */; -/* removed: var _$doAvg_489 = require('../histogram/average'); */; -/* removed: var _$cleanBins_492 = require('../histogram/clean_bins'); */; -/* removed: var _$getBinSpanLabelRound_491 = require('../histogram/bin_label_vals'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_343 = require('../../components/fx'); */; + +/* removed: var _$createGLPlot2D_158 = require('gl-plot2d'); */; +/* removed: var _$createSpikes2D_171 = require('gl-spikes2d'); */; +/* removed: var _$createSelectBox_162 = require('gl-select-box'); */; +/* removed: var _$getWebGLContext_281 = require('webgl-context'); */; + +/* removed: var _$createAxes2D_500 = require('./convert'); */; +/* removed: var _$createCamera_499 = require('./camera'); */; +/* removed: var _$convertHTMLToUnicode_423 = require('../../lib/html2unicode'); */; +/* removed: var _$showWebGlMsg_446 = require('../../lib/show_no_webgl_msg'); */; +/* removed: var _$constraints_477 = require('../cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_477.enforce; +var cleanAxisConstraints = _$constraints_477.clean; +var __doAutoRange_502 = _$autorange_469.doAutoRange; + +var __AXES_502 = ['xaxis', 'yaxis']; +var STATIC_CANVAS, STATIC_CONTEXT; +var __SUBPLOT_PATTERN_502 = _$constants_475.SUBPLOT_PATTERN; -var _$calc_494 = function calc(gd, trace) { - var xa = _$axes_407.getFromId(gd, trace.xaxis || 'x'); - var x = trace.x ? xa.makeCalcdata(trace, 'x') : []; - var ya = _$axes_407.getFromId(gd, trace.yaxis || 'y'); - var y = trace.y ? ya.makeCalcdata(trace, 'y') : []; - 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; +function Scene2D(options, fullLayout) { + this.container = options.container; + this.graphDiv = options.graphDiv; + this.pixelRatio = options.plotGlPixelRatio || window.devicePixelRatio; + this.id = options.id; + this.staticPlot = !!options.staticPlot; + this.scrollZoom = this.graphDiv._context.scrollZoom; - var serieslen = Math.min(x.length, y.length); - if(x.length > serieslen) x.splice(serieslen, x.length - serieslen); - if(y.length > serieslen) y.splice(serieslen, y.length - serieslen); + this.fullData = null; + this.updateRefs(fullLayout); - // calculate the bins - cleanAndAutobin(trace, 'x', x, xa, xr2c, xc2r, xcalendar); - cleanAndAutobin(trace, 'y', y, ya, yr2c, yc2r, ycalendar); + this.makeFramework(); - // make the empty bin array & scale the map - var z = []; - var onecol = []; - var zerocol = []; - var nonuniformBinsX = (typeof(trace.xbins.size) === 'string'); - var nonuniformBinsY = (typeof(trace.ybins.size) === 'string'); - var xEdges = []; - var yEdges = []; - var xbins = nonuniformBinsX ? xEdges : trace.xbins; - var ybins = nonuniformBinsY ? yEdges : trace.ybins; - 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 = _$bin_functions_490.count; - var normfunc = _$norm_functions_493[norm]; - var doavg = false; - var xinc = []; - var yinc = []; + // update options + this.glplotOptions = _$createAxes2D_500(this); + this.glplotOptions.merge(fullLayout); - // 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 = _$bin_functions_490[func]; - } + // create the plot + this.glplot = _$createGLPlot2D_158(this.glplotOptions); - // decrease end a little in case of rounding errors - var binSpec = trace.xbins, - binStart = xr2c(binSpec.start), - binEnd = xr2c(binSpec.end) + - (binStart - _$axes_407.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; + // create camera + this.camera = _$createCamera_499(this); - for(i = binStart; i < binEnd; i = _$axes_407.tickIncrement(i, binSpec.size, false, xcalendar)) { - onecol.push(sizeinit); - xEdges.push(i); - if(doavg) zerocol.push(0); - } - xEdges.push(i); + // trace set + this.traces = {}; - var nx = onecol.length; - var x0c = xr2c(trace.xbins.start); - var dx = (i - x0c) / nx; - var x0 = xc2r(x0c + dx / 2); + // create axes spikes + this.spikes = _$createSpikes2D_171(this.glplot); - binSpec = trace.ybins; - binStart = yr2c(binSpec.start); - binEnd = yr2c(binSpec.end) + - (binStart - _$axes_407.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; + this.selectBox = _$createSelectBox_162(this.glplot, { + innerFill: false, + outerFill: true + }); - for(i = binStart; i < binEnd; i = _$axes_407.tickIncrement(i, binSpec.size, 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); + // last button state + this.lastButtonState = 0; - var ny = z.length; - var y0c = yr2c(trace.ybins.start); - var dy = (i - y0c) / ny; - var y0 = yc2r(y0c + dy / 2); + // last pick result + this.pickResult = null; - if(densitynorm) { - xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX); - yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY); - } + // is the mouse over the plot? + // it's OK if this says true when it's not, so long as + // when we get a mouseout we set it to false before handling + this.isMouseOver = true; - // 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); + // flag to stop render loop + this.stopped = false; - // 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 = x[i]; - var yi = y[i]; - n = _$lib_363.findBin(xi, xbins); - m = _$lib_363.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); + // redraw the plot + this.redraw = this.draw.bind(this); + this.redraw(); +} - if(uniqueValsPerX) { - if(xVals[n] === undefined) xVals[n] = xi; - else if(xVals[n] !== xi) uniqueValsPerX = false; - } - if(uniqueValsPerY) { - if(yVals[n] === undefined) yVals[n] = yi; - else if(yVals[n] !== yi) uniqueValsPerY = false; - } +var _$Scene2D_502 = Scene2D; - 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_489(z[m], counts[m]); - } - if(normfunc) { - for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); - } +var __proto_502 = Scene2D.prototype; - return { - x: x, - xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar), - x0: x0, - dx: dx, - y: y, - yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar), - y0: y0, - dy: dy, - z: z, - pts: inputPoints - }; -}; +__proto_502.makeFramework = function() { -function cleanAndAutobin(trace, axLetter, data, ax, r2c, c2r, calendar) { - var binSpecAttr = axLetter + 'bins'; - var autoBinAttr = 'autobin' + axLetter; - var binSpec = trace[binSpecAttr]; + // create canvas and gl context + if(this.staticPlot) { + if(!STATIC_CONTEXT) { + STATIC_CANVAS = document.createElement('canvas'); - _$cleanBins_492(trace, ax, axLetter); + STATIC_CONTEXT = _$getWebGLContext_281({ + canvas: STATIC_CANVAS, + preserveDrawingBuffer: false, + premultipliedAlpha: true, + antialias: true + }); - if(trace[autoBinAttr] || !binSpec || binSpec.start === null || binSpec.end === null) { - binSpec = _$axes_407.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); - if(trace.type === 'histogram2dcontour') { - // the "true" last argument reverses the tick direction (which we can't - // just do with a minus sign because of month bins) - binSpec.start = c2r(_$axes_407.tickIncrement( - r2c(binSpec.start), binSpec.size, true, calendar)); - binSpec.end = c2r(_$axes_407.tickIncrement( - r2c(binSpec.end), binSpec.size, false, calendar)); + if(!STATIC_CONTEXT) { + throw new Error('Error creating static canvas/context for image server'); + } } - // copy bin info back to the source data. - trace._input[binSpecAttr] = trace[binSpecAttr] = binSpec; - // note that it's possible to get here with an explicit autobin: false - // if the bins were not specified. - // in that case this will remain in the trace, so that future updates - // which would change the autobinning will not do so. - trace._input[autoBinAttr] = trace[autoBinAttr]; - } -} - -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]); + this.canvas = STATIC_CANVAS; + this.gl = STATIC_CONTEXT; } else { - var inc = 1 / dv; - for(i = 0; i < len; i++) out[i] = inc; - } - return out; -} + var liveCanvas = this.container.querySelector('.gl-canvas-focus'); -function binsToCalc(r2c, bins) { - return { - start: r2c(bins.start), - end: r2c(bins.end), - size: bins.size - }; -} + var gl = _$getWebGLContext_281({ + canvas: liveCanvas, + preserveDrawingBuffer: true, + premultipliedAlpha: true + }); -function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { - var i; - var len = edges.length - 1; - var out = new Array(len); - if(uniqueVals) { - for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]]; - } - else { - var roundFn = _$getBinSpanLabelRound_491(gapLow, gapHigh, edges, ax, calendar); - for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)]; + if(!gl) _$showWebGlMsg_446(this); + + this.canvas = liveCanvas; + this.gl = gl; } - return out; -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // position the canvas + var canvas = this.canvas; + canvas.style.width = '100%'; + canvas.style.height = '100%'; + canvas.style.position = 'absolute'; + canvas.style.top = '0px'; + canvas.style.left = '0px'; + canvas.style['pointer-events'] = 'none'; -'use strict'; + this.updateSize(canvas); -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; + // disabling user select on the canvas + // sanitizes double-clicks interactions + // ref: https://github.com/plotly/plotly.js/issues/744 + canvas.className += ' user-select-none'; -/* removed: var _$calc_494 = require('../histogram2d/calc'); */; -/* removed: var _$calc_246 = require('../../components/colorscale/calc'); */; -/* removed: var _$has_columns_480 = require('./has_columns'); */; -/* removed: var _$convertColumnData_477 = require('./convert_column_xyz'); */; -/* removed: var _$maxRowLength_483 = require('./max_row_length'); */; -/* removed: var _$clean2dArray_475 = require('./clean_2d_array'); */; -/* removed: var _$interp2d_481 = require('./interp2d'); */; -/* removed: var _$findEmpties_479 = require('./find_empties'); */; -/* removed: var _$makeBoundArray_482 = require('./make_bound_array'); */; + // create SVG container for hover text + var svgContainer = this.svgContainer = document.createElementNS( + 'http://www.w3.org/2000/svg', + 'svg'); + svgContainer.style.position = 'absolute'; + svgContainer.style.top = svgContainer.style.left = '0px'; + svgContainer.style.width = svgContainer.style.height = '100%'; + svgContainer.style['z-index'] = 20; + svgContainer.style['pointer-events'] = 'none'; + // create div to catch the mouse event + var mouseContainer = this.mouseContainer = document.createElement('div'); + mouseContainer.style.position = 'absolute'; + mouseContainer.style['pointer-events'] = 'auto'; -var _$calc_474 = 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_407.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_407.getFromId(gd, trace.yaxis || 'y'), - isContour = _$registry_451.traceIs(trace, 'contour'), - isHist = _$registry_451.traceIs(trace, 'histogram'), - isGL2D = _$registry_451.traceIs(trace, 'gl2d'), - zsmooth = isContour ? 'best' : trace.zsmooth, - x, - x0, - dx, - y, - y0, - dy, - z, - i, - binned; + this.pickCanvas = this.container.querySelector('.gl-canvas-pick'); - // cancel minimum tick spacings (only applies to bars and boxes) - xa._minDtick = 0; - ya._minDtick = 0; - if(isHist) { - binned = _$calc_494(gd, trace); - x = binned.x; - x0 = binned.x0; - dx = binned.dx; - y = binned.y; - y0 = binned.y0; - dy = binned.dy; - z = binned.z; - } - else { - if(_$has_columns_480(trace)) { - _$convertColumnData_477(trace, xa, ya, 'x', 'y', ['z']); - x = trace.x; - y = trace.y; - } else { - x = trace.x ? xa.makeCalcdata(trace, 'x') : []; - y = trace.y ? ya.makeCalcdata(trace, 'y') : []; - } + // append canvas, hover svg and mouse div to container + var container = this.container; + container.appendChild(svgContainer); + container.appendChild(mouseContainer); - x0 = trace.x0 || 0; - dx = trace.dx || 1; - y0 = trace.y0 || 0; - dy = trace.dy || 1; + var self = this; + mouseContainer.addEventListener('mouseout', function() { + self.isMouseOver = false; + self.unhover(); + }); + mouseContainer.addEventListener('mouseover', function() { + self.isMouseOver = true; + }); +}; - z = _$clean2dArray_475(trace.z, trace.transpose); +__proto_502.toImage = function(format) { + if(!format) format = 'png'; - if(isContour || trace.connectgaps) { - trace._emptypoints = _$findEmpties_479(z); - trace._interpz = _$interp2d_481(z, trace._emptypoints, trace._interpz); - } - } + this.stopped = true; - function noZsmooth(msg) { - zsmooth = trace._input.zsmooth = trace.zsmooth = false; - _$lib_363.warn('cannot use zsmooth: "fast": ' + msg); - } + if(this.staticPlot) this.container.appendChild(STATIC_CANVAS); - // 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), - 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), - 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; - } - } - } - } - } + // update canvas size + this.updateSize(this.canvas); + + + // grab context and yank out pixels + var gl = this.glplot.gl, + w = gl.drawingBufferWidth, + h = gl.drawingBufferHeight; + + // force redraw + gl.clearColor(1, 1, 1, 0); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + this.glplot.setDirty(); + this.glplot.draw(); + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); - // create arrays of brick boundaries, to be used by autorange and heatmap.plot - var xlen = _$maxRowLength_483(z); - var xIn = trace.xtype === 'scaled' ? '' : x; - var xArray = _$makeBoundArray_482(trace, xIn, x0, dx, xlen, xa); - var yIn = trace.ytype === 'scaled' ? '' : y; - var yArray = _$makeBoundArray_482(trace, yIn, y0, dy, z.length, ya); + var pixels = new Uint8Array(w * h * 4); + gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels); - // handled in gl2d convert step - if(!isGL2D) { - _$axes_407.expand(xa, xArray); - _$axes_407.expand(ya, yArray); + // flip pixels + for(var j = 0, k = h - 1; j < k; ++j, --k) { + for(var i = 0; i < w; ++i) { + for(var l = 0; l < 4; ++l) { + var tmp = pixels[4 * (w * j + i) + l]; + pixels[4 * (w * j + i) + l] = pixels[4 * (w * k + i) + l]; + pixels[4 * (w * k + i) + l] = tmp; + } + } } - var cd0 = { - x: xArray, - y: yArray, - z: z, - text: trace.text - }; + var canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; - if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn; - if(yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn; + var context = canvas.getContext('2d'); + var imageData = context.createImageData(w, h); + imageData.data.set(pixels); + context.putImageData(imageData, 0, 0); - if(isHist) { - cd0.xRanges = binned.xRanges; - cd0.yRanges = binned.yRanges; - cd0.pts = binned.pts; - } + var dataURL; - // auto-z and autocolorscale if applicable - if(!isContour || trace.contours.type !== 'constraint') { - _$calc_246(trace, z, '', 'z'); + switch(format) { + case 'jpeg': + dataURL = canvas.toDataURL('image/jpeg'); + break; + case 'webp': + dataURL = canvas.toDataURL('image/webp'); + break; + default: + dataURL = canvas.toDataURL('image/png'); } - if(isContour && trace.contours && trace.contours.coloring === 'heatmap') { - var dummyTrace = { - type: trace.type === 'contour' ? 'heatmap' : 'histogram2d', - xcalendar: trace.xcalendar, - ycalendar: trace.ycalendar - }; - cd0.xfill = _$makeBoundArray_482(dummyTrace, xIn, x0, dx, xlen, xa); - cd0.yfill = _$makeBoundArray_482(dummyTrace, yIn, y0, dy, z.length, ya); - } + if(this.staticPlot) this.container.removeChild(STATIC_CANVAS); - return [cd0]; + return dataURL; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +__proto_502.updateSize = function(canvas) { + if(!canvas) canvas = this.canvas; + var pixelRatio = this.pixelRatio, + fullLayout = this.fullLayout; -'use strict'; + var width = fullLayout.width, + height = fullLayout.height, + pixelWidth = Math.ceil(pixelRatio * width) |0, + pixelHeight = Math.ceil(pixelRatio * height) |0; -/* removed: var _$calc_474 = require('../heatmap/calc'); */; -/* removed: var _$setContours_469 = require('./set_contours'); */; + // check for resize + if(canvas.width !== pixelWidth || canvas.height !== pixelHeight) { + canvas.width = pixelWidth; + canvas.height = pixelHeight; + } -// 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 -var _$calc_461 = function calc(gd, trace) { - var cd = _$calc_474(gd, trace); - _$setContours_469(trace); - return cd; + return canvas; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +__proto_502.computeTickMarks = function() { + this.xaxis.setScale(); + this.yaxis.setScale(); -'use strict'; + var nextTicks = [ + _$axes_470.calcTicks(this.xaxis), + _$axes_470.calcTicks(this.yaxis) + ]; -var _$constants_241 = { - cn: { - colorbar: 'colorbar', - cbbg: 'cbbg', - cbfill: 'cbfill', - cbfills: 'cbfills', - cbline: 'cbline', - cblines: 'cblines', - cbaxis: 'cbaxis', - cbtitleunshift: 'cbtitleunshift', - cbtitle: 'cbtitle', - cboutline: 'cboutline', - crisp: 'crisp', - jsPlaceholder: 'js-placeholder' + for(var j = 0; j < 2; ++j) { + for(var i = 0; i < nextTicks[j].length; ++i) { + // coercing tick value (may not be a string) to a string + nextTicks[j][i].text = _$convertHTMLToUnicode_423(nextTicks[j][i].text + ''); + } } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; + return nextTicks; +}; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; - -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -var __extendFlat_243 = _$extend_354.extendFlat; -/* removed: var _$setCursor_382 = require('../../lib/setcursor'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$titles_332 = require('../titles'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -var __LINE_SPACING_243 = _$alignment_339.LINE_SPACING; - -/* removed: var _$handleAxisDefaults_409 = require('../../plots/cartesian/axis_defaults'); */; -/* removed: var _$handlePositionDefaults_423 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_419 = require('../../plots/cartesian/layout_attributes'); */; - -/* removed: var _$attributes_240 = require('./attributes'); */; -var cn = _$constants_241.cn; - -var _$draw_243 = function draw(gd, id) { - // opts: options object, containing everything from attributes - // plus a few others that are the equivalent of the colorbar "data" - var opts = {}; - Object.keys(_$attributes_240).forEach(function(k) { - opts[k] = null; - }); - // fillcolor can be a d3 scale, domain is z values, range is colors - // or leave it out for no fill, - // or set to a string constant for single-color fill - opts.fillcolor = null; - // line.color has the same options as fillcolor - opts.line = {color: null, width: null, dash: null}; - // levels of lines to draw. - // note that this DOES NOT determine the extent of the bar - // that's given by the domain of fillcolor - // (or line.color if no fillcolor domain) - opts.levels = {start: null, end: null, size: null}; - // separate fill levels (for example, heatmap coloring of a - // contour map) if this is omitted, fillcolors will be - // evaluated halfway between levels - opts.filllevels = null; +function __compareTicks_502(a, b) { + for(var i = 0; i < 2; ++i) { + var aticks = a[i], + bticks = b[i]; - function component() { - var fullLayout = gd._fullLayout, - gs = fullLayout._size; - if((typeof opts.fillcolor !== 'function') && - (typeof opts.line.color !== 'function')) { - fullLayout._infolayer.selectAll('g.' + id).remove(); - return; - } - var zrange = _$d3_68.extent(((typeof opts.fillcolor === 'function') ? - opts.fillcolor : opts.line.color).domain()); - var linelevels = []; - var filllevels = []; - var linecolormap = typeof opts.line.color === 'function' ? - opts.line.color : function() { return opts.line.color; }; - var fillcolormap = typeof opts.fillcolor === 'function' ? - opts.fillcolor : function() { return opts.fillcolor; }; - var l; - var i; + if(aticks.length !== bticks.length) return true; - var l0 = opts.levels.end + opts.levels.size / 100, - ls = opts.levels.size, - zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), - zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); - for(i = 0; i < 1e5; i++) { - l = opts.levels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zr0 && l < zr1) linelevels.push(l); + for(var j = 0; j < aticks.length; ++j) { + if(aticks[j].x !== bticks[j].x) return true; } + } - if(typeof opts.fillcolor === 'function') { - if(opts.filllevels) { - l0 = opts.filllevels.end + opts.filllevels.size / 100; - ls = opts.filllevels.size; - for(i = 0; i < 1e5; i++) { - l = opts.filllevels.start + i * ls; - if(ls > 0 ? (l >= l0) : (l <= l0)) break; - if(l > zrange[0] && l < zrange[1]) filllevels.push(l); - } - } - else { - filllevels = linelevels.map(function(v) { - return v - opts.levels.size / 2; - }); - filllevels.push(filllevels[filllevels.length - 1] + - opts.levels.size); - } - } - else if(opts.fillcolor && typeof opts.fillcolor === 'string') { - // doesn't matter what this value is, with a single value - // we'll make a single fill rect covering the whole bar - filllevels = [0]; - } + return false; +} - if(opts.levels.size < 0) { - linelevels.reverse(); - filllevels.reverse(); - } +__proto_502.updateRefs = function(newFullLayout) { + this.fullLayout = newFullLayout; - // now make a Plotly Axes object to scale with and draw ticks - // TODO: does not support orientation other than right + var spmatch = this.id.match(__SUBPLOT_PATTERN_502); + var xaxisName = 'xaxis' + spmatch[1]; + var yaxisName = 'yaxis' + spmatch[2]; - // we calculate pixel sizes based on the specified graph size, - // not the actual (in case something pushed the margins around) - // which is a little odd but avoids an odd iterative effect - // when the colorbar itself is pushing the margins. - // but then the fractional size is calculated based on the - // actual graph size, so that the axes will size correctly. - var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, - originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, - thickPx = Math.round(opts.thickness * - (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), - thickFrac = thickPx / gs.w, - lenPx = Math.round(opts.len * - (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), - lenFrac = lenPx / gs.h, - xpadFrac = opts.xpad / gs.w, - yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, - ypadFrac = opts.ypad / gs.h, + this.xaxis = this.fullLayout[xaxisName]; + this.yaxis = this.fullLayout[yaxisName]; +}; - // x positioning: do it initially just for left anchor, - // then fix at the end (since we don't know the width yet) - xLeft = Math.round(opts.x * gs.w + opts.xpad), - // for dragging... this is getting a little muddled... - xLeftFrac = opts.x - thickFrac * - ({middle: 0.5, right: 1}[opts.xanchor]||0), +__proto_502.relayoutCallback = function() { + var graphDiv = this.graphDiv, + xaxis = this.xaxis, + yaxis = this.yaxis, + layout = graphDiv.layout; - // y positioning we can do correctly from the start - yBottomFrac = opts.y + lenFrac * - (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), - yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), - yTopPx = yBottomPx - lenPx, - titleEl, - cbAxisIn = { - type: 'linear', - range: zrange, - tickmode: opts.tickmode, - nticks: opts.nticks, - tick0: opts.tick0, - dtick: opts.dtick, - tickvals: opts.tickvals, - ticktext: opts.ticktext, - ticks: opts.ticks, - ticklen: opts.ticklen, - tickwidth: opts.tickwidth, - tickcolor: opts.tickcolor, - showticklabels: opts.showticklabels, - tickfont: opts.tickfont, - tickangle: opts.tickangle, - tickformat: opts.tickformat, - exponentformat: opts.exponentformat, - separatethousands: opts.separatethousands, - showexponent: opts.showexponent, - showtickprefix: opts.showtickprefix, - tickprefix: opts.tickprefix, - showticksuffix: opts.showticksuffix, - ticksuffix: opts.ticksuffix, - title: opts.title, - titlefont: opts.titlefont, - showline: true, - anchor: 'free', - position: 1 - }, - cbAxisOut = { - type: 'linear', - _id: 'y' + id - }, - axisOptions = { - letter: 'y', - font: fullLayout.font, - noHover: true, - calendar: fullLayout.calendar // not really necessary (yet?) - }; + // update user layout + layout.xaxis.autorange = xaxis.autorange; + layout.xaxis.range = xaxis.range.slice(0); + layout.yaxis.autorange = yaxis.autorange; + layout.yaxis.range = yaxis.range.slice(0); - // Coerce w.r.t. Axes layoutAttributes: - // re-use axes.js logic without updating _fullData - function coerce(attr, dflt) { - return _$lib_363.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_419, attr, dflt); - } + // make a meaningful value to be passed on to the possible 'plotly_relayout' subscriber(s) + // scene.camera has no many useful projection or scale information + // helps determine which one is the latest input (if async) + var update = { + lastInputTime: this.camera.lastInputTime + }; - // Prepare the Plotly axis object - _$handleAxisDefaults_409(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); - _$handlePositionDefaults_423(cbAxisIn, cbAxisOut, coerce, axisOptions); + update[xaxis._name] = xaxis.range.slice(0); + update[yaxis._name] = yaxis.range.slice(0); - // position can't go in through supplyDefaults - // because that restricts it to [0,1] - cbAxisOut.position = opts.x + xpadFrac + thickFrac; + graphDiv.emit('plotly_relayout', update); +}; - // save for other callers to access this axis - component.axis = cbAxisOut; +__proto_502.cameraChanged = function() { + var camera = this.camera; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - cbAxisOut.titleside = opts.titleside; - cbAxisOut.titlex = opts.x + xpadFrac; - cbAxisOut.titley = yBottomFrac + - (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); - } + this.glplot.setDataBox(this.calcDataBox()); - if(opts.line.color && opts.tickmode === 'auto') { - cbAxisOut.tickmode = 'linear'; - cbAxisOut.tick0 = opts.levels.start; - var dtick = opts.levels.size; - // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_363.constrain( - (yBottomPx - yTopPx) / 50, 4, 15) + 1, - dtFactor = (zrange[1] - zrange[0]) / - ((opts.nticks || autoNtick) * dtick); - if(dtFactor > 1) { - var dtexp = Math.pow(10, Math.floor( - Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_363.roundUp(dtFactor / dtexp, [2, 5, 10]); - // if the contours are at round multiples, reset tick0 - // so they're still at round multiples. Otherwise, - // keep the first label on the first contour level - if((Math.abs(opts.levels.start) / - opts.levels.size + 1e-6) % 1 < 2e-6) { - cbAxisOut.tick0 = 0; - } - } - cbAxisOut.dtick = dtick; - } + var nextTicks = this.computeTickMarks(); + var curTicks = this.glplotOptions.ticks; - // set domain after init, because we may want to - // allow it outside [0,1] - cbAxisOut.domain = [ - yBottomFrac + ypadFrac, - yBottomFrac + lenFrac - ypadFrac - ]; - cbAxisOut.setScale(); + if(__compareTicks_502(nextTicks, curTicks)) { + this.glplotOptions.ticks = nextTicks; + this.glplotOptions.dataBox = camera.dataBox; + this.glplot.update(this.glplotOptions); + this.handleAnnotations(); + } +}; - // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_68.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); - container.attr('transform', 'translate(' + Math.round(gs.l) + - ',' + Math.round(gs.t) + ')'); - // TODO: this opposite transform is a hack until we make it - // more rational which items get this offset - var titleCont = container.select('.cbtitleunshift') - .attr('transform', 'translate(-' + - Math.round(gs.l) + ',-' + - Math.round(gs.t) + ')'); +__proto_502.handleAnnotations = function() { + var gd = this.graphDiv, + annotations = this.fullLayout.annotations; - cbAxisOut._axislayer = container.select('.cbaxis'); - var titleHeight = 0; - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // draw the title so we know how much room it needs - // when we squish the axis. This one only applies to - // top or bottom titles, not right side. - var x = gs.l + (opts.x + xpadFrac) * gs.w, - fontSize = cbAxisOut.titlefont.size, - y; + for(var i = 0; i < annotations.length; i++) { + var ann = annotations[i]; - if(opts.titleside === 'top') { - y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + - gs.t + 3 + fontSize * 0.75; - } - else { - y = (1 - (yBottomFrac + ypadFrac)) * gs.h + - gs.t - 3 - fontSize * 0.25; - } - drawTitle(cbAxisOut._id + 'title', { - attributes: {x: x, y: y, 'text-anchor': 'start'} - }); + if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) { + _$registry_514.getComponentMethod('annotations', 'drawOne')(gd, i); } + } +}; - function drawAxis() { - if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { - // squish the axis top to make room for the title - var titleGroup = container.select('.cbtitle'), - titleText = titleGroup.select('text'), - titleTrans = - [-opts.outlinewidth / 2, opts.outlinewidth / 2], - mathJaxNode = titleGroup - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - lineSize = 15.6; - if(titleText.node()) { - lineSize = - parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_243; - } - if(mathJaxNode) { - titleHeight = _$drawing_264.bBox(mathJaxNode).height; - if(titleHeight > lineSize) { - // not entirely sure how mathjax is doing - // vertical alignment, but this seems to work. - titleTrans[1] -= (titleHeight - lineSize) / 2; - } - } - else if(titleText.node() && - !titleText.classed(cn.jsPlaceholder)) { - titleHeight = _$drawing_264.bBox(titleText.node()).height; - } - if(titleHeight) { - // buffer btwn colorbar and title - // TODO: configurable - titleHeight += 5; - - if(opts.titleside === 'top') { - cbAxisOut.domain[1] -= titleHeight / gs.h; - titleTrans[1] *= -1; - } - else { - cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_386.lineCount(titleText); - titleTrans[1] += (1 - nlines) * lineSize; - } - - titleGroup.attr('transform', - 'translate(' + titleTrans + ')'); - - cbAxisOut.setScale(); - } - } +__proto_502.destroy = function() { + if(!this.glplot) return; - container.selectAll('.cbfills,.cblines') - .attr('transform', 'translate(0,' + - Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); + var traces = this.traces; - cbAxisOut._axislayer.attr('transform', 'translate(0,' + - Math.round(-gs.t) + ')'); + if(traces) { + Object.keys(traces).map(function(key) { + traces[key].dispose(); + delete traces[key]; + }); + } - var fills = container.select('.cbfills') - .selectAll('rect.cbfill') - .data(filllevels); - fills.enter().append('rect') - .classed(cn.cbfill, true) - .style('stroke', 'none'); - fills.exit().remove(); - fills.each(function(d, i) { - var z = [ - (i === 0) ? zrange[0] : - (filllevels[i] + filllevels[i - 1]) / 2, - (i === filllevels.length - 1) ? zrange[1] : - (filllevels[i] + filllevels[i + 1]) / 2 - ] - .map(cbAxisOut.c2p) - .map(Math.round); + this.glplot.dispose(); - // offset the side adjoining the next rectangle so they - // overlap, to prevent antialiasing gaps - if(i !== filllevels.length - 1) { - z[1] += (z[1] > z[0]) ? 1 : -1; - } + this.container.removeChild(this.svgContainer); + this.container.removeChild(this.mouseContainer); + this.fullData = null; + this.glplot = null; + this.stopped = true; + this.camera.mouseListener.enabled = false; + this.mouseContainer.removeEventListener('wheel', this.camera.wheelListener); + this.camera = null; +}; - // Tinycolor can't handle exponents and - // at this scale, removing it makes no difference. - var colorString = fillcolormap(d).replace('e-', ''), - opaqueColor = _$tinycolor_201(colorString).toHexString(); +__proto_502.plot = function(fullData, calcData, fullLayout) { + var glplot = this.glplot; - // Colorbar cannot currently support opacities so we - // use an opaque fill even when alpha channels present - _$d3_68.select(this).attr({ - x: xLeft, - width: Math.max(thickPx, 2), - y: _$d3_68.min(z), - height: Math.max(_$d3_68.max(z) - _$d3_68.min(z), 2), - fill: opaqueColor - }); - }); + this.updateRefs(fullLayout); + this.xaxis.clearCalc(); + this.yaxis.clearCalc(); + this.updateTraces(fullData, calcData); + this.updateFx(fullLayout.dragmode); - var lines = container.select('.cblines') - .selectAll('path.cbline') - .data(opts.line.color && opts.line.width ? - linelevels : []); - lines.enter().append('path') - .classed(cn.cbline, true); - lines.exit().remove(); - lines.each(function(d) { - _$d3_68.select(this) - .attr('d', 'M' + xLeft + ',' + - (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + - 'h' + thickPx) - .call(_$drawing_264.lineGroupStyle, - opts.line.width, linecolormap(d), opts.line.dash); - }); + var width = fullLayout.width, + height = fullLayout.height; - // force full redraw of labels and ticks - cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') - .remove(); + this.updateSize(this.canvas); - cbAxisOut._pos = xLeft + thickPx + - (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); - cbAxisOut.side = 'right'; + var options = this.glplotOptions; + options.merge(fullLayout); + options.screenBox = [0, 0, width, height]; - // separate out axis and title drawing, - // so we don't need such complicated logic in Titles.draw - // if title is on the top or bottom, we've already drawn it - // this title call only handles side=right - return _$lib_363.syncOrAsync([ - function() { - return _$axes_407.doTicks(gd, cbAxisOut, true); - }, - function() { - if(['top', 'bottom'].indexOf(opts.titleside) === -1) { - var fontSize = cbAxisOut.titlefont.size, - y = cbAxisOut._offset + cbAxisOut._length / 2, - x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? - 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : - -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); + var mockGraphDiv = {_fullLayout: { + _axisConstraintGroups: this.graphDiv._fullLayout._axisConstraintGroups, + xaxis: this.xaxis, + yaxis: this.yaxis + }}; - // the 'h' + is a hack to get around the fact that - // convertToTspans rotates any 'y...' class by 90 degrees. - // TODO: find a better way to control this. - drawTitle('h' + cbAxisOut._id + 'title', { - avoid: { - selection: _$d3_68.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), - side: opts.titleside, - offsetLeft: gs.l, - offsetTop: 0, - maxShift: fullLayout.width - }, - attributes: {x: x, y: y, 'text-anchor': 'middle'}, - transform: {rotate: '-90', offset: 0} - }); - } - }]); - } + cleanAxisConstraints(mockGraphDiv, this.xaxis); + cleanAxisConstraints(mockGraphDiv, this.yaxis); - function drawTitle(titleClass, titleOpts) { - var trace = getTrace(), - propName; - if(_$registry_451.traceIs(trace, 'markerColorscale')) { - propName = 'marker.colorbar.title'; - } - else propName = 'colorbar.title'; + var size = fullLayout._size, + domainX = this.xaxis.domain, + domainY = this.yaxis.domain; - var dfltTitleOpts = { - propContainer: cbAxisOut, - propName: propName, - traceIndex: trace.index, - placeholder: fullLayout._dfltTitle.colorbar, - containerGroup: container.select('.cbtitle') - }; + options.viewBox = [ + size.l + domainX[0] * size.w, + size.b + domainY[0] * size.h, + (width - size.r) - (1 - domainX[1]) * size.w, + (height - size.t) - (1 - domainY[1]) * size.h + ]; - // this class-to-rotate thing with convertToTspans is - // getting hackier and hackier... delete groups with the - // wrong class (in case earlier the colorbar was drawn on - // a different side, I think?) - var otherClass = titleClass.charAt(0) === 'h' ? - titleClass.substr(1) : ('h' + titleClass); - container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') - .remove(); + this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px'; + this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px'; + this.mouseContainer.height = size.h * (domainY[1] - domainY[0]); + this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px'; + this.mouseContainer.style.top = size.t + (1 - domainY[1]) * size.h + 'px'; - _$titles_332.draw(gd, titleClass, - __extendFlat_243(dfltTitleOpts, titleOpts || {})); - } + var ax, i; - function positionCB() { - // wait for the axis & title to finish rendering before - // continuing positioning - // TODO: why are we redrawing multiple times now with this? - // I guess autoMargin doesn't like being post-promise? - var innerWidth = thickPx + opts.outlinewidth / 2 + - _$drawing_264.bBox(cbAxisOut._axislayer.node()).width; - titleEl = titleCont.select('text'); - if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { - var mathJaxNode = titleCont - .select('.h' + cbAxisOut._id + 'title-math-group') - .node(), - titleWidth; - if(mathJaxNode && - ['top', 'bottom'].indexOf(opts.titleside) !== -1) { - titleWidth = _$drawing_264.bBox(mathJaxNode).width; - } - else { - // note: the formula below works for all titlesides, - // (except for top/bottom mathjax, above) - // but the weird gs.l is because the titleunshift - // transform gets removed by Drawing.bBox - titleWidth = - _$drawing_264.bBox(titleCont.node()).right - - xLeft - gs.l; - } - innerWidth = Math.max(innerWidth, titleWidth); - } + for(i = 0; i < 2; ++i) { + ax = this[__AXES_502[i]]; + ax._length = options.viewBox[i + 2] - options.viewBox[i]; - var outerwidth = 2 * opts.xpad + innerWidth + - opts.borderwidth + opts.outlinewidth / 2, - outerheight = yBottomPx - yTopPx; + __doAutoRange_502(ax); + ax.setScale(); + } - container.select('.cbbg').attr({ - x: xLeft - opts.xpad - - (opts.borderwidth + opts.outlinewidth) / 2, - y: yTopPx - yExtraPx, - width: Math.max(outerwidth, 2), - height: Math.max(outerheight + 2 * yExtraPx, 2) - }) - .call(_$color_239.fill, opts.bgcolor) - .call(_$color_239.stroke, opts.bordercolor) - .style({'stroke-width': opts.borderwidth}); + enforceAxisConstraints(mockGraphDiv); - container.selectAll('.cboutline').attr({ - x: xLeft, - y: yTopPx + opts.ypad + - (opts.titleside === 'top' ? titleHeight : 0), - width: Math.max(thickPx, 2), - height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) - }) - .call(_$color_239.stroke, opts.outlinecolor) - .style({ - fill: 'None', - 'stroke-width': opts.outlinewidth - }); + options.ticks = this.computeTickMarks(); - // fix positioning for xanchor!='left' - var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * - outerwidth; - container.attr('transform', - 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); + options.dataBox = this.calcDataBox(); - // auto margin adjustment - _$plots_444.autoMargin(gd, id, { - x: opts.x, - y: opts.y, - l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), - r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), - t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), - b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) - }); - } + options.merge(fullLayout); + glplot.update(options); - var cbDone = _$lib_363.syncOrAsync([ - _$plots_444.previousPromises, - drawAxis, - _$plots_444.previousPromises, - positionCB - ], gd); + // force redraw so that promise is returned when rendering is completed + this.glplot.draw(); +}; - if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); +__proto_502.calcDataBox = function() { + var xaxis = this.xaxis, + yaxis = this.yaxis, + xrange = xaxis.range, + yrange = yaxis.range, + xr2l = xaxis.r2l, + yr2l = yaxis.r2l; - // dragging... - if(gd._context.edits.colorbarPosition) { - var t0, - xf, - yf; + return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])]; +}; - _$dragelement_261.init({ - element: container.node(), - gd: gd, - prepFn: function() { - t0 = container.attr('transform'); - _$setCursor_382(container); - }, - moveFn: function(dx, dy) { - container.attr('transform', - t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); +__proto_502.setRanges = function(dataBox) { + var xaxis = this.xaxis, + yaxis = this.yaxis, + xl2r = xaxis.l2r, + yl2r = yaxis.l2r; - xf = _$dragelement_261.align(xLeftFrac + (dx / gs.w), thickFrac, - 0, 1, opts.xanchor); - yf = _$dragelement_261.align(yBottomFrac - (dy / gs.h), lenFrac, - 0, 1, opts.yanchor); + xaxis.range = [xl2r(dataBox[0]), xl2r(dataBox[2])]; + yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])]; +}; - var csr = _$dragelement_261.getCursor(xf, yf, - opts.xanchor, opts.yanchor); - _$setCursor_382(container, csr); - }, - doneFn: function() { - _$setCursor_382(container); +__proto_502.updateTraces = function(fullData, calcData) { + var traceIds = Object.keys(this.traces); + var i, j, fullTrace; - if(xf !== undefined && yf !== undefined) { - _$registry_451.call('restyle', - gd, - {'colorbar.x': xf, 'colorbar.y': yf}, - getTrace().index - ); - } - } - }); + this.fullData = fullData; + + // remove empty traces + trace_id_loop: + for(i = 0; i < traceIds.length; i++) { + var oldUid = traceIds[i], + oldTrace = this.traces[oldUid]; + + for(j = 0; j < fullData.length; j++) { + fullTrace = fullData[j]; + + if(fullTrace.uid === oldUid && fullTrace.type === oldTrace.type) { + continue trace_id_loop; + } } - return cbDone; + + oldTrace.dispose(); + delete this.traces[oldUid]; } - function getTrace() { - var idNum = id.substr(2), - i, - trace; - for(i = 0; i < gd._fullData.length; i++) { - trace = gd._fullData[i]; - if(trace.uid === idNum) return trace; + // update / create trace objects + for(i = 0; i < fullData.length; i++) { + fullTrace = fullData[i]; + var calcTrace = calcData[i], + traceObj = this.traces[fullTrace.uid]; + + if(traceObj) traceObj.update(fullTrace, calcTrace); + else { + traceObj = fullTrace._module.plot(this, fullTrace, calcTrace); + this.traces[fullTrace.uid] = traceObj; } } - // setter/getters for every item defined in opts - Object.keys(opts).forEach(function(name) { - component[name] = function(v) { - // getter - if(!arguments.length) return opts[name]; + // order object per traces + this.glplot.objects.sort(function(a, b) { + return a._trace.index - b._trace.index; + }); +}; - // setter - for multi-part properties, - // set only the parts that are provided - opts[name] = _$lib_363.isPlainObject(opts[name]) ? - _$lib_363.extendFlat(opts[name], v) : - v; +__proto_502.updateFx = function(dragmode) { + // switch to svg interactions in lasso/select mode + if(dragmode === 'lasso' || dragmode === 'select') { + this.pickCanvas.style['pointer-events'] = 'none'; + this.mouseContainer.style['pointer-events'] = 'none'; + } else { + this.pickCanvas.style['pointer-events'] = 'auto'; + this.mouseContainer.style['pointer-events'] = 'auto'; + } - return component; - }; - }); + // set proper cursor + if(dragmode === 'pan') { + this.mouseContainer.style.cursor = 'move'; + } + else if(dragmode === 'zoom') { + this.mouseContainer.style.cursor = 'crosshair'; + } + else { + this.mouseContainer.style.cursor = null; + } +}; - // or use .options to set multiple options at once via a dictionary - component.options = function(o) { - Object.keys(o).forEach(function(name) { - // in case something random comes through - // that's not an option, ignore it - if(typeof component[name] === 'function') { - component[name](o[name]); - } - }); - return component; +__proto_502.emitPointAction = function(nextSelection, eventType) { + var uid = nextSelection.trace.uid; + var ptNumber = nextSelection.pointIndex; + var trace; + + for(var i = 0; i < this.fullData.length; i++) { + if(this.fullData[i].uid === uid) { + trace = this.fullData[i]; + } + } + + var pointData = { + x: nextSelection.traceCoord[0], + y: nextSelection.traceCoord[1], + curveNumber: trace.index, + pointNumber: ptNumber, + data: trace._input, + fullData: this.fullData, + xaxis: this.xaxis, + yaxis: this.yaxis }; - component._opts = opts; + _$fx_343.appendArrayPointValue(pointData, trace, ptNumber); - return component; + this.graphDiv.emit(eventType, {points: [pointData]}); }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +__proto_502.draw = function() { + if(this.stopped) return; + requestAnimationFrame(this.redraw); -'use strict'; + var glplot = this.glplot, + camera = this.camera, + mouseListener = camera.mouseListener, + mouseUp = this.lastButtonState === 1 && mouseListener.buttons === 0, + fullLayout = this.fullLayout; -/* - * tiny helper to move the end of the contours a little to prevent - * losing the last contour to rounding errors - */ -var _$endPlus_466 = function endPlus(contours) { - return contours.end + contours.size / 1e6; -}; + this.lastButtonState = mouseListener.buttons; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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.cameraChanged(); + var x = mouseListener.x * glplot.pixelRatio; + var y = this.canvas.height - glplot.pixelRatio * mouseListener.y; -'use strict'; + var result; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$colorscale_254 = require('../../components/colorscale'); */; -/* removed: var _$endPlus_466 = require('./end_plus'); */; + if(camera.boxEnabled && fullLayout.dragmode === 'zoom') { + this.selectBox.enabled = true; -var _$makeColorMap_468 = function makeColorMap(trace) { - var contours = trace.contours, - start = contours.start, - end = _$endPlus_466(contours), - cs = contours.size || 1, - nc = Math.floor((end - start) / cs) + 1, - extra = contours.coloring === 'lines' ? 0 : 1; + var selectBox = this.selectBox.selectBox = [ + Math.min(camera.boxStart[0], camera.boxEnd[0]), + Math.min(camera.boxStart[1], camera.boxEnd[1]), + Math.max(camera.boxStart[0], camera.boxEnd[0]), + Math.max(camera.boxStart[1], camera.boxEnd[1]) + ]; - if(!isFinite(cs)) { - cs = 1; - nc = 1; + // 1D zoom + for(var i = 0; i < 2; i++) { + if(camera.boxStart[i] === camera.boxEnd[i]) { + selectBox[i] = glplot.dataBox[i]; + selectBox[i + 2] = glplot.dataBox[i + 2]; + } + } + + glplot.setDirty(); } + else if(!camera.panning && this.isMouseOver) { + this.selectBox.enabled = false; - var scl = trace.colorscale, - len = scl.length; + var size = fullLayout._size, + domainX = this.xaxis.domain, + domainY = this.yaxis.domain; - var domain = new Array(len), - range = new Array(len); + result = glplot.pick( + (x / glplot.pixelRatio) + size.l + domainX[0] * size.w, + (y / glplot.pixelRatio) - (size.t + (1 - domainY[1]) * size.h) + ); - var si, i; + var nextSelection = result && result.object._trace.handlePick(result); - if(contours.coloring === 'heatmap') { - if(trace.zauto && trace.autocontour === false) { - trace.zmin = start - cs / 2; - trace.zmax = trace.zmin + nc * cs; + if(nextSelection && mouseUp) { + this.emitPointAction(nextSelection, 'plotly_click'); } - for(i = 0; i < len; i++) { - si = scl[i]; + if(result && result.object._trace.hoverinfo !== 'skip' && fullLayout.hovermode) { - domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin; - range[i] = si[1]; - } + if(nextSelection && ( + !this.lastPickResult || + this.lastPickResult.traceUid !== nextSelection.trace.uid || + this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] || + this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1]) + ) { + var selection = nextSelection; - // do the contours extend beyond the colorscale? - // if so, extend the colorscale with constants - var zRange = _$d3_68.extent([trace.zmin, trace.zmax, contours.start, - contours.start + cs * (nc - 1)]), - zmin = zRange[trace.zmin < trace.zmax ? 0 : 1], - zmax = zRange[trace.zmin < trace.zmax ? 1 : 0]; + this.lastPickResult = { + traceUid: nextSelection.trace ? nextSelection.trace.uid : null, + dataCoord: nextSelection.dataCoord.slice() + }; + this.spikes.update({ center: result.dataCoord }); - if(zmin !== trace.zmin) { - domain.splice(0, 0, zmin); - range.splice(0, 0, Range[0]); - } + selection.screenCoord = [ + ((glplot.viewBox[2] - glplot.viewBox[0]) * + (result.dataCoord[0] - glplot.dataBox[0]) / + (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) / + glplot.pixelRatio, + (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) * + (result.dataCoord[1] - glplot.dataBox[1]) / + (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) / + glplot.pixelRatio + ]; - if(zmax !== trace.zmax) { - domain.push(zmax); - range.push(range[range.length - 1]); + // this needs to happen before the next block that deletes traceCoord data + // also it's important to copy, otherwise data is lost by the time event data is read + this.emitPointAction(nextSelection, 'plotly_hover'); + + var trace = this.fullData[selection.trace.index] || {}; + var ptNumber = selection.pointIndex; + var hoverinfo = _$fx_343.castHoverinfo(trace, fullLayout, ptNumber); + + if(hoverinfo && hoverinfo !== 'all') { + var parts = hoverinfo.split('+'); + if(parts.indexOf('x') === -1) selection.traceCoord[0] = undefined; + if(parts.indexOf('y') === -1) selection.traceCoord[1] = undefined; + if(parts.indexOf('z') === -1) selection.traceCoord[2] = undefined; + if(parts.indexOf('text') === -1) selection.textLabel = undefined; + if(parts.indexOf('name') === -1) selection.name = undefined; + } + + _$fx_343.loneHover({ + x: selection.screenCoord[0], + y: selection.screenCoord[1], + xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]), + yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]), + zLabel: selection.traceCoord[2], + text: selection.textLabel, + name: selection.name, + color: _$fx_343.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color, + borderColor: _$fx_343.castHoverOption(trace, ptNumber, 'bordercolor'), + fontFamily: _$fx_343.castHoverOption(trace, ptNumber, 'font.family'), + fontSize: _$fx_343.castHoverOption(trace, ptNumber, 'font.size'), + fontColor: _$fx_343.castHoverOption(trace, ptNumber, 'font.color') + }, { + container: this.svgContainer, + gd: this.graphDiv + }); + } } } - else { - for(i = 0; i < len; i++) { - si = scl[i]; - domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start; - range[i] = si[1]; - } + // Remove hover effects if we're not over a point OR + // if we're zooming or panning (in which case result is not set) + if(!result) { + this.unhover(); } - return _$colorscale_254.makeColorScaleFunc({ - domain: domain, - range: range, - }, { - noNumericCheck: true - }); + glplot.draw(); +}; + +__proto_502.unhover = function() { + if(this.lastPickResult) { + this.spikes.update({}); + this.lastPickResult = null; + this.graphDiv.emit('plotly_unhover'); + _$fx_343.loneUnhover(this.svgContainer); + } +}; + +__proto_502.hoverFormatter = function(axisName, val) { + if(val === undefined) return undefined; + + var axis = this[axisName]; + return _$axes_470.tickText(axis, axis.c2l(val), 'hover').text; }; +var _$gl2d_501 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -60449,83 +61928,142 @@ var _$makeColorMap_468 = function makeColorMap(trace) { 'use strict'; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$draw_243 = require('../../components/colorbar/draw'); */; +var __overrideAll_501 = _$edit_types_455.overrideAll; + +/* removed: var _$Scene2D_502 = require('./scene2d'); */; +/* removed: var _$layout_attributes_504 = require('../layout_attributes'); */; +/* removed: var _$xmlns_namespaces_406 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$constants_475 = require('../cartesian/constants'); */; +/* removed: var _$cartesian_481 = require('../cartesian'); */; +/* removed: var _$layout_attributes_344 = require('../../components/fx/layout_attributes'); */; +var getSubplotData = _$get_data_498.getSubplotData; + +_$gl2d_501.name = 'gl2d'; + +_$gl2d_501.attr = ['xaxis', 'yaxis']; + +_$gl2d_501.idRoot = ['x', 'y']; + +_$gl2d_501.idRegex = _$constants_475.idRegex; + +_$gl2d_501.attrRegex = _$constants_475.attrRegex; + +_$gl2d_501.attributes = _$attributes_468; + +_$gl2d_501.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { + if(!layoutOut._has('cartesian')) { + _$cartesian_481.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 +_$gl2d_501.layoutAttrOverrides = __overrideAll_501(_$cartesian_481.layoutAttributes, 'plot', 'from-root'); + +// similar overrides for base plot attributes (and those added by components) +_$gl2d_501.baseLayoutAttrOverrides = __overrideAll_501({ + plot_bgcolor: _$layout_attributes_504.plot_bgcolor, + hoverlabel: _$layout_attributes_344.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'); + +_$gl2d_501.plot = function plotGl2d(gd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; + var subplotIds = fullLayout._subplots.gl2d; -/* removed: var _$makeColorMap_468 = require('./make_color_map'); */; -/* removed: var _$endPlus_466 = require('./end_plus'); */; + for(var i = 0; i < subplotIds.length; i++) { + var subplotId = subplotIds[i], + subplotObj = fullLayout._plots[subplotId], + fullSubplotData = getSubplotData(fullData, 'gl2d', subplotId); + // ref. to corresp. Scene instance + var scene = subplotObj._scene2d; -var _$colorbar_462 = function colorbar(gd, cd) { - var trace = cd[0].trace, - cbId = 'cb' + trace.uid; + // If Scene is not instantiated, create one! + if(scene === undefined) { + scene = new _$Scene2D_502({ + id: subplotId, + graphDiv: gd, + container: gd.querySelector('.gl-container'), + staticPlot: gd._context.staticPlot, + plotGlPixelRatio: gd._context.plotGlPixelRatio + }, + fullLayout + ); - gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); + // set ref to Scene instance + subplotObj._scene2d = scene; + } - if(!trace.showscale) { - _$plots_444.autoMargin(gd, cbId); - return; + scene.plot(fullSubplotData, gd.calcdata, fullLayout, gd.layout); } +}; - var cb = _$draw_243(gd, cbId); - cd[0].t.cb = cb; +_$gl2d_501.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldSceneKeys = oldFullLayout._subplots.gl2d || []; - var contours = trace.contours, - line = trace.line, - cs = contours.size || 1, - coloring = contours.coloring; + for(var i = 0; i < oldSceneKeys.length; i++) { + var id = oldSceneKeys[i], + oldSubplot = oldFullLayout._plots[id]; - var colorMap = _$makeColorMap_468(trace, {isColorbar: true}); + // old subplot wasn't gl2d; nothing to do + if(!oldSubplot._scene2d) continue; - if(coloring === 'heatmap') { - cb.filllevels({ - start: trace.zmin, - end: trace.zmax, - size: (trace.zmax - trace.zmin) / 254 - }); + // 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]; + } } - cb.fillcolor((coloring === 'fill' || coloring === 'heatmap') ? colorMap : '') - .line({ - color: coloring === 'lines' ? colorMap : line.color, - width: contours.showlines !== false ? line.width : 0, - dash: line.dash - }) - .levels({ - start: contours.start, - end: _$endPlus_466(contours), - size: cs - }) - .options(trace.colorbar)(); + // since we use cartesian interactions, do cartesian clean + _$cartesian_481.clean.apply(this, arguments); }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +_$gl2d_501.drawFramework = function(gd) { + if(!gd._context.staticPlot) { + _$cartesian_481.drawFramework(gd); + } +}; +_$gl2d_501.toSVG = function(gd) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots.gl2d; -'use strict'; + for(var i = 0; i < subplotIds.length; i++) { + var subplot = fullLayout._plots[subplotIds[i]], + scene = subplot._scene2d; -/* removed: var _$lib_363 = require('../../lib'); */; + var imageData = scene.toImage('png'); + var image = fullLayout._glimages.append('svg:image'); -var _$handleLabelDefaults_467 = function handleLabelDefaults(coerce, layout, lineColor, opts) { - if(!opts) opts = {}; - var showLabels = coerce('contours.showlabels'); - if(showLabels) { - var globalFont = layout.font; - _$lib_363.coerceFont(coerce, 'contours.labelfont', { - family: globalFont.family, - size: globalFont.size, - color: lineColor + image.attr({ + xmlns: _$xmlns_namespaces_406.svg, + 'xlink:href': imageData, + x: 0, + y: 0, + width: '100%', + height: '100%', + preserveAspectRatio: 'none' }); - coerce('contours.labelformat'); + + scene.destroy(); } +}; - if(opts.hasHover !== false) coerce('zhoverformat'); +_$gl2d_501.updateFx = function(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); + } }; /** @@ -60536,92 +62074,35 @@ var _$handleLabelDefaults_467 = function handleLabelDefaults(coerce, layout, lin * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$handleLabelDefaults_467 = require('./label_defaults'); */; - -/* removed: var _$color_239 = require('../../components/color'); */; -var addOpacity = _$color_239.addOpacity; -var opacity = _$color_239.opacity; - -/* removed: var _$filter_ops_340 = require('../../constants/filter_ops'); */; -var CONSTRAINT_REDUCTION = _$filter_ops_340.CONSTRAINT_REDUCTION; -var __COMPARISON_OPS2_463 = _$filter_ops_340.COMPARISON_OPS2; - -var _$handleConstraintDefaults_463 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { - var contours = traceOut.contours; - var showLines, lineColor, fillColor; +var _$filter_ops_402 = { + COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='], + COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], + INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], + SET_OPS: ['{}', '}{'], + CONSTRAINT_REDUCTION: { + // for contour constraints, open/closed endpoints are equivalent + '=': '=', - var operation = coerce('contours.operation'); - contours._operation = CONSTRAINT_REDUCTION[operation]; + '<': '<', + '<=': '<', - handleConstraintValueDefaults(coerce, contours); + '>': '>', + '>=': '>', - if(operation === '=') { - showLines = contours.showlines = true; - } - else { - showLines = coerce('contours.showlines'); - fillColor = coerce('fillcolor', addOpacity( - (traceIn.line || {}).color || defaultColor, 0.5 - )); - } + '[]': '[]', + '()': '[]', + '[)': '[]', + '(]': '[]', - if(showLines) { - var lineDfltColor = fillColor && opacity(fillColor) ? - addOpacity(traceOut.fillcolor, 1) : - defaultColor; - lineColor = coerce('line.color', lineDfltColor); - coerce('line.width', 2); - coerce('line.dash'); + '][': '][', + ')(': '][', + '](': '][', + ')[': '][' } - - coerce('line.smoothing'); - - _$handleLabelDefaults_467(coerce, layout, lineColor, opts); }; -function handleConstraintValueDefaults(coerce, contours) { - var zvalue; - - if(__COMPARISON_OPS2_463.indexOf(contours.operation) === -1) { - // Requires an array of two numbers: - coerce('contours.value', [0, 1]); - - if(!Array.isArray(contours.value)) { - if(_$fastIsnumeric_78(contours.value)) { - zvalue = parseFloat(contours.value); - contours.value = [zvalue, zvalue + 1]; - } - } else if(contours.value.length > 2) { - contours.value = contours.value.slice(2); - } else if(contours.length === 0) { - contours.value = [0, 1]; - } else if(contours.length < 2) { - zvalue = parseFloat(contours.value[0]); - contours.value = [zvalue, zvalue + 1]; - } else { - contours.value = [ - parseFloat(contours.value[0]), - parseFloat(contours.value[1]) - ]; - } - } else { - // Requires a single scalar: - coerce('contours.value', 0); - - if(!_$fastIsnumeric_78(contours.value)) { - if(Array.isArray(contours.value)) { - contours.value = parseFloat(contours.value[0]); - } else { - contours.value = 0; - } - } - } -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -60632,23 +62113,94 @@ function handleConstraintValueDefaults(coerce, contours) { 'use strict'; -var _$handleContourDefaults_464 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { - var contourStart = coerce2('contours.start'); - var contourEnd = coerce2('contours.end'); - var missingEnd = (contourStart === false) || (contourEnd === false); +/* removed: var _$attributes_576 = require('../scatter/attributes'); */; +/* removed: var _$attributes_307 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_302 = require('../../components/colorbar/attributes'); */; - // normally we only need size if autocontour is off. But contour.calc - // pushes its calculated contour size back to the input trace, so for - // things like restyle that can call supplyDefaults without calc - // after the initial draw, we can just reuse the previous calculation - var contourSize = coerce('contours.size'); - var autoContour; +var __extendFlat_536 = _$extend_416.extendFlat; - if(missingEnd) autoContour = traceOut.autocontour = true; - else autoContour = coerce('autocontour', false); +var _$attributes_536 = __extendFlat_536({}, { + z: { + valType: 'data_array', + editType: 'calc', + + }, + x: __extendFlat_536({}, _$attributes_576.x, {impliedEdits: {xtype: 'array'}}), + x0: __extendFlat_536({}, _$attributes_576.x0, {impliedEdits: {xtype: 'scaled'}}), + dx: __extendFlat_536({}, _$attributes_576.dx, {impliedEdits: {xtype: 'scaled'}}), + y: __extendFlat_536({}, _$attributes_576.y, {impliedEdits: {ytype: 'array'}}), + y0: __extendFlat_536({}, _$attributes_576.y0, {impliedEdits: {ytype: 'scaled'}}), + dy: __extendFlat_536({}, _$attributes_576.dy, {impliedEdits: {ytype: 'scaled'}}), - if(autoContour || !contourSize) coerce('ncontours'); -}; + text: { + 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', + + }, + connectgaps: { + valType: 'boolean', + dflt: false, + + 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', + + }, +}, + _$attributes_307, + { autocolorscale: __extendFlat_536({}, _$attributes_307.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_302 } +); /** * Copyright 2012-2018, Plotly, Inc. @@ -60658,36 +62210,175 @@ var _$handleContourDefaults_464 = function handleContourDefaults(traceIn, traceO * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$colorScaleDefaults_249 = require('../../components/colorscale/defaults'); */; -/* removed: var _$handleLabelDefaults_467 = require('./label_defaults'); */; - +/* removed: var _$attributes_536 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_576 = require('../scatter/attributes'); */; +/* removed: var _$attributes_307 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_302 = require('../../components/colorbar/attributes'); */; +var __dash_523 = _$attributes_325.dash; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +var __extendFlat_523 = _$extend_416.extendFlat; + +/* removed: var _$filter_ops_402 = require('../../constants/filter_ops'); */; +var COMPARISON_OPS2 = _$filter_ops_402.COMPARISON_OPS2; +var INTERVAL_OPS = _$filter_ops_402.INTERVAL_OPS; + +var scatterLineAttrs = _$attributes_576.line; + +var _$attributes_523 = __extendFlat_523({ + z: _$attributes_536.z, + x: _$attributes_536.x, + x0: _$attributes_536.x0, + dx: _$attributes_536.dx, + y: _$attributes_536.y, + y0: _$attributes_536.y0, + dy: _$attributes_536.dy, + text: _$attributes_536.text, + transpose: _$attributes_536.transpose, + xtype: _$attributes_536.xtype, + ytype: _$attributes_536.ytype, + zhoverformat: _$attributes_536.zhoverformat, + + connectgaps: _$attributes_536.connectgaps, -var _$handleStyleDefaults_470 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { - var coloring = coerce('contours.coloring'); + fillcolor: { + valType: 'color', + + editType: 'calc', + + }, - var showLines; - var lineColor = ''; - if(coloring === 'fill') showLines = coerce('contours.showlines'); + 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', + + }, - if(showLines !== false) { - if(coloring !== 'lines') lineColor = coerce('line.color', '#000'); - coerce('line.width', 0.5); - coerce('line.dash'); - } + 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: _$font_attributes_496({ + 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} + }, - if(coloring !== 'none') { - _$colorScaleDefaults_249( - traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} - ); + line: { + color: __extendFlat_523({}, scatterLineAttrs.color, { + editType: 'style+colorbars', + + }), + width: __extendFlat_523({}, scatterLineAttrs.width, { + editType: 'style+colorbars' + }), + dash: __dash_523, + smoothing: __extendFlat_523({}, scatterLineAttrs.smoothing, { + + }), + editType: 'plot' } - - coerce('line.smoothing'); - - _$handleLabelDefaults_467(coerce, layout, lineColor, opts); -}; +}, + _$attributes_307, { + autocolorscale: __extendFlat_523({}, _$attributes_307.autocolorscale, {dflt: false}), + zmin: __extendFlat_523({}, _$attributes_307.zmin, {editType: 'calc'}), + zmax: __extendFlat_523({}, _$attributes_307.zmax, {editType: 'calc'}) + }, + { colorbar: _$attributes_302 } +); /** * Copyright 2012-2018, Plotly, Inc. @@ -60700,87 +62391,90 @@ var _$handleStyleDefaults_470 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_485 = _$lib_363.isArrayOrTypedArray; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$has_columns_480 = require('./has_columns'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +var __extendFlat_532 = _$lib_425.extendFlat; -var _$handleXYZDefaults_485 = 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(_$has_columns_480(traceIn)) { - x = coerce(xName); - y = coerce(yName); - // column z must be accompanied by xName and yName arrays - if(!x || !y) return 0; - } - else { - x = coordDefaults(xName, coerce); - y = coordDefaults(yName, coerce); +var _$setContours_532 = function setContours(trace) { + var contours = trace.contours; - // TODO put z validation elsewhere - if(!isValidZ(z)) return 0; + // check if we need to auto-choose contour levels + if(trace.autocontour) { + var dummyAx = autoContours(trace.zmin, trace.zmax, trace.ncontours); - coerce('transpose'); - } + contours.size = dummyAx.dtick; - var handleCalendarDefaults = _$registry_451.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout); + contours.start = _$axes_470.tickFirst(dummyAx); + dummyAx.range.reverse(); + contours.end = _$axes_470.tickFirst(dummyAx); - return traceOut.z.length; -}; + if(contours.start === trace.zmin) contours.start += contours.size; + if(contours.end === trace.zmax) contours.end -= contours.size; -function coordDefaults(coordStr, coerce) { - var coord = coerce(coordStr), - coordType = coord ? - coerce(coordStr + 'type', 'array') : - 'scaled'; + // if you set a small ncontours, *and* the ends are exactly on zmin/zmax + // there's an edge case where start > end now. Make sure there's at least + // one meaningful contour, put it midway between the crossed values + if(contours.start > contours.end) { + contours.start = contours.end = (contours.start + contours.end) / 2; + } - if(coordType === 'scaled') { - coerce(coordStr + '0'); - coerce('d' + coordStr); + // copy auto-contour info back to the source data. + // previously we copied the whole contours object back, but that had + // other info (coloring, showlines) that should be left to supplyDefaults + if(!trace._input.contours) trace._input.contours = {}; + __extendFlat_532(trace._input.contours, { + start: contours.start, + end: contours.end, + size: contours.size + }); + trace._input.autocontour = true; } + else if(contours.type !== 'constraint') { + // sanity checks on manually-supplied start/end/size + var start = contours.start, + end = contours.end, + inputContours = trace._input.contours; - return coord; -} - -function isValidZ(z) { - var allRowsAreArrays = true, - oneRowIsFilled = false, - hasOneNumber = false, - zi; + if(start > end) { + contours.start = inputContours.start = end; + end = contours.end = inputContours.end = start; + start = contours.start; + } - /* - * Without this step: - * - * hasOneNumber = false breaks contour but not heatmap - * allRowsAreArrays = false breaks contour but not heatmap - * oneRowIsFilled = false breaks both - */ + if(!(contours.size > 0)) { + var sizeOut; + if(start === end) sizeOut = 1; + else sizeOut = autoContours(start, end, trace.ncontours).dtick; - for(var i = 0; i < z.length; i++) { - zi = z[i]; - if(!__isArrayOrTypedArray_485(zi)) { - allRowsAreArrays = false; - break; - } - if(zi.length > 0) oneRowIsFilled = true; - for(var j = 0; j < zi.length; j++) { - if(_$fastIsnumeric_78(zi[j])) { - hasOneNumber = true; - break; - } + inputContours.size = contours.size = sizeOut; } } +}; + + +/* + * autoContours: make a dummy axis object with dtick we can use + * as contours.size, and if needed we can use Axes.tickFirst + * with this axis object to calculate the start and end too + * + * start: the value to start the contours at + * end: the value to end at (must be > start) + * ncontours: max number of contours to make, like roughDTick + * + * returns: an axis object + */ +function autoContours(start, end, ncontours) { + var dummyAx = { + type: 'linear', + range: [start, end] + }; - return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); + _$axes_470.autoTicks( + dummyAx, + (end - start) / (ncontours || 15) + ); + + return dummyAx; } /** @@ -60791,913 +62485,117 @@ function isValidZ(z) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; - -/* removed: var _$has_columns_480 = require('../heatmap/has_columns'); */; -/* removed: var _$handleXYZDefaults_485 = require('../heatmap/xyz_defaults'); */; -/* removed: var _$handleConstraintDefaults_463 = require('./constraint_defaults'); */; -/* removed: var _$handleContourDefaults_464 = require('./contours_defaults'); */; -/* removed: var _$handleStyleDefaults_470 = require('./style_defaults'); */; -/* removed: var _$attributes_460 = require('./attributes'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +var _$clean2dArray_538 = function clean2dArray(zOld, transpose) { + var rowlen, collen, getCollen, old2new, i, j; -var _$supplyDefaults_465 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_460, attr, dflt); + function cleanZvalue(v) { + if(!_$fastIsnumeric_135(v)) return undefined; + return +v; } - function coerce2(attr) { - return _$lib_363.coerce2(traceIn, traceOut, _$attributes_460, attr); + if(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]; }; } - - var len = _$handleXYZDefaults_485(traceIn, traceOut, coerce, layout); - if(!len) { - traceOut.visible = false; - return; + else { + rowlen = zOld.length; + getCollen = function(zOld, i) { return zOld[i].length; }; + old2new = function(zOld, i, j) { return zOld[i][j]; }; } - coerce('text'); - var isConstraint = (coerce('contours.type') === 'constraint'); - coerce('connectgaps', _$has_columns_480(traceOut)); - - // trace-level showlegend has already been set, but is only allowed if this is a constraint - if(!isConstraint) delete traceOut.showlegend; + var zNew = new Array(rowlen); - if(isConstraint) { - _$handleConstraintDefaults_463(traceIn, traceOut, coerce, layout, defaultColor); - } - else { - _$handleContourDefaults_464(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_470(traceIn, traceOut, coerce, layout); + for(i = 0; i < rowlen; i++) { + collen = getCollen(zOld, i); + zNew[i] = new Array(collen); + for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); } + + return zNew; }; -'use strict' - -/* removed: var _$browser_124 = require('glslify') */; - -var _$shaders_87 = { - fragment: _$browser_124(["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: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 tangent;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 screenShape;\nuniform float lineWidth;\nuniform float pointSize;\n\nvarying vec4 fragColor;\n\nvoid main() {\n fragColor = color;\n\n vec3 vPosition = viewTransform * vec3(position, 1.0);\n vec2 vTangent = normalize(viewTransform * vec3(tangent, 0)).xy;\n vec2 offset = vec2(vTangent.y, -vTangent.x) / screenShape;\n\n gl_Position = vec4(\n vPosition.xy + offset * lineWidth * vPosition.z,\n 0,\n vPosition.z);\n\n gl_PointSize = pointSize;\n}\n"]), - fillVertex: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\n\nvarying vec4 fragColor;\n\nvoid main() {\n fragColor = color;\n vec3 vPosition = viewTransform * vec3(position, 1.0);\n gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]) -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -"use strict" -function __compileSearch_88(funcName, predicate, reversed, extraArgs, 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[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("") -} +'use strict'; -function __compileBoundsSearch_88(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - __compileSearch_88("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_88("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() -} +/* removed: var _$lib_425 = require('../../lib'); */; +var __BADNUM_540 = _$numerical_404.BADNUM; -var _$searchBounds_88 = { - ge: __compileBoundsSearch_88(">=", false, "GE"), - gt: __compileBoundsSearch_88(">", false, "GT"), - lt: __compileBoundsSearch_88("<", true, "LT"), - le: __compileBoundsSearch_88("<=", true, "LE"), - eq: __compileBoundsSearch_88("-", true, "EQ", true) -} +var _$convertColumnData_540 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { + var col1 = trace[var1Name].slice(), + col2 = trace[var2Name].slice(), + textCol = trace.text, + colLen = Math.min(col1.length, col2.length), + hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), + col1Calendar = trace[var1Name + 'calendar'], + col2Calendar = trace[var2Name + 'calendar']; -'use strict' - -var _$createContour2D_86 = createContour2D - -/* removed: var _$iota_130 = require('iota-array') */; -/* removed: var _$createShader_107 = require('gl-shader') */; -/* removed: var _$createBuffer_83 = require('gl-buffer') */; -/* removed: var _$wrappedNDArrayCtor_143 = require('ndarray') */; -/* removed: var _$surfaceNets_195 = require('surface-nets') */; -/* removed: var _$cdt2d_47 = require('cdt2d') */; -/* removed: var _$cleanPSLG_54 = require('clean-pslg') */; -/* removed: var _$searchBounds_88 = require('binary-search-bounds') */; - -/* removed: var _$shaders_87 = require('./lib/shaders') */; - -function GLContour2D ( - plot, - shader, - fillShader, - positionBuffer, - colorBuffer, - idBuffer, - fillPositionBuffer, - fillColorBuffer) { - this.plot = plot - this.shader = shader - this.fillShader = fillShader - this.positionBuffer = positionBuffer - this.colorBuffer = colorBuffer - this.idBuffer = idBuffer - this.fillPositionBuffer = fillPositionBuffer - this.fillColorBuffer = fillColorBuffer - this.fillVerts = 0 - this.shape = [0, 0] - this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - this.numVertices = 0 - this.lineWidth = 1 -} - -var __proto_86 = GLContour2D.prototype - -var WEIGHTS = [ - 1, 0, - 0, 0, - 0, 1, - 1, 0, - 1, 1, - 0, 1 -] - -__proto_86.draw = (function () { - var MATRIX = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] - - var SCREEN_SHAPE = [0, 0] - - return function () { - var plot = this.plot - var shader = this.shader - var fillShader = this.fillShader - var bounds = this.bounds - var numVertices = this.numVertices - var fillVerts = this.fillVerts - - var uniforms, attributes - - var gl = plot.gl - var viewBox = plot.viewBox - var dataBox = plot.dataBox - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - - SCREEN_SHAPE[0] = viewBox[2] - viewBox[0] - SCREEN_SHAPE[1] = viewBox[3] - viewBox[1] - - if (fillVerts > 0) { - fillShader.bind() - - uniforms = fillShader.uniforms - uniforms.viewTransform = MATRIX - uniforms.screenShape = SCREEN_SHAPE - - attributes = shader.attributes - this.fillPositionBuffer.bind() - attributes.position.pointer() - - this.fillColorBuffer.bind() - attributes.color.pointer(gl.UNSIGNED_BYTE, true) - - gl.drawArrays(gl.TRIANGLES, 0, fillVerts) - } - - if (numVertices > 0) { - shader.bind() - - var lineWidth = this.lineWidth * plot.pixelRatio - - uniforms = shader.uniforms - uniforms.viewTransform = MATRIX - uniforms.screenShape = SCREEN_SHAPE - uniforms.lineWidth = lineWidth - uniforms.pointSize = 1000 - - attributes = shader.attributes - - // Draw lines - this.positionBuffer.bind() - attributes.position.pointer(gl.FLOAT, false, 16, 0) - attributes.tangent.pointer(gl.FLOAT, false, 16, 8) - - this.colorBuffer.bind() - attributes.color.pointer(gl.UNSIGNED_BYTE, true) - - gl.drawArrays(gl.TRIANGLES, 0, numVertices) - - // Draw end caps - uniforms.lineWidth = 0 - uniforms.pointSize = lineWidth - - this.positionBuffer.bind() - attributes.position.pointer(gl.FLOAT, false, 16 * 3, 0) - attributes.tangent.pointer(gl.FLOAT, false, 16 * 3, 8) - - this.colorBuffer.bind() - attributes.color.pointer(gl.UNSIGNED_BYTE, true, 4 * 3, 0) - - gl.drawArrays(gl.POINTS, 0, numVertices / 3) - } - } -})() - -__proto_86.drawPick = (function () { - return function (pickOffset) { - return pickOffset - } -})() - -__proto_86.pick = function (x, y, value) { - return null -} - -function interpolate (array, point) { - var idx = Math.floor(point) - if (idx < 0) { - return array[0] - } else if (idx >= array.length - 1) { - return array[array.length - 1] - } - var t = point - idx - return (1.0 - t) * array[idx] + t * array[idx + 1] -} - -__proto_86.update = function (options) { - options = options || {} - - var shape = options.shape || [0, 0] - - var x = options.x || _$iota_130(shape[0]) - var y = options.y || _$iota_130(shape[1]) - var z = options.z || new Float32Array(shape[0] * shape[1]) - - var levels = options.levels || [] - var levelColors = options.levelColors || [] - - var bounds = this.bounds - var lox = bounds[0] = x[0] - var loy = bounds[1] = y[0] - var hix = bounds[2] = x[x.length - 1] - var hiy = bounds[3] = y[y.length - 1] - - if (lox === hix) { - bounds[2] += 1 - hix += 1 - } - if (loy === hiy) { - bounds[3] += 1 - hiy += 1 - } - - var xs = 1.0 / (hix - lox) - var ys = 1.0 / (hiy - loy) - - this.lineWidth = options.lineWidth || 1 - - var zarray = _$wrappedNDArrayCtor_143(z, shape) - - var positions = [] - var colors = [] - var ids = [] - - var fillCells = [] - var fillPositions = [ - [0, 0], - [shape[0] - 1, 0], - [0, shape[1] - 1], - [shape[0] - 1, shape[1] - 1] - ] - - function intersect (level, x, a, b) { - var d = (b - a) - if (Math.abs(d) < 1e-6) { - return x - } - return Math.floor(x) + Math.max(0.001, Math.min(0.999, (level - a) / d)) - } - - for (var i = 0; i < levels.length; ++i) { - var level = levels[i] - if (i > 0 && level === levels[i - 1]) { - continue - } - var contour = _$surfaceNets_195(zarray, level) - - var c_r = (255 * levelColors[4 * i]) | 0 - var c_g = (255 * levelColors[4 * i + 1]) | 0 - var c_b = (255 * levelColors[4 * i + 2]) | 0 - var c_a = (255 * levelColors[4 * i + 3]) | 0 - - var c_cells = contour.cells - var c_positions = contour.positions - - // Fix boundaries - var in_degree = Array(c_positions.length) - for (var j = 0; j < in_degree.length; ++j) { - in_degree[j] = 0 - } - for (j = 0; j < c_cells.length; ++j) { - var edge = c_cells[j] - in_degree[edge[0]] += 1 - in_degree[edge[1]] += 1 - } - - for (j = 0; j < in_degree.length; ++j) { - var deg = in_degree[j] - if (deg === 0) { - continue - } - var pp = c_positions[j] - in_degree[j] = fillPositions.length - fillPositions.push(pp) - if (deg > 1) { - continue - } - var ppx = pp[0] - var ppy = pp[1] - var z00 = zarray.get(Math.floor(ppx), Math.floor(ppy)) - var z01 = zarray.get(Math.floor(ppx), Math.ceil(ppy)) - var z10 = zarray.get(Math.ceil(ppx), Math.floor(ppy)) - var z11 = zarray.get(Math.ceil(ppx), Math.ceil(ppy)) - var intercept - if (Math.floor(pp[0]) === 0 && - ((z00 <= level) !== (z01 < level))) { - intercept = [0, intersect(level, pp[1], z00, z01)] - } else if (Math.ceil(pp[0]) === shape[0] - 1 && - ((z10 <= level) !== (z11 < level))) { - intercept = [shape[0] - 1, intersect(level, pp[1], z10, z11)] - } else if (Math.floor(pp[1]) === 0 && - ((z00 <= level) !== (z10 < level))) { - intercept = [intersect(level, pp[0], z00, z10), 0] - } else if (Math.ceil(pp[1]) === shape[1] - 1 && - ((z01 <= level) !== (z11 < level))) { - intercept = [intersect(level, pp[0], z01, z11), shape[1] - 1] - } - if (intercept) { - c_cells.push([j, c_positions.length]) - in_degree.push(fillPositions.length) - c_positions.push(intercept) - } - } - - for (j = 0; j < c_cells.length; ++j) { - var e = c_cells[j] - var a = c_positions[e[0]] - var b = c_positions[e[1]] - - fillCells.push([in_degree[e[0]], in_degree[e[1]]]) - - var pointId = Math.round(a[0]) + shape[0] * Math.round(a[1]) - - var ax = interpolate(x, a[0]) - var ay = interpolate(y, a[1]) - var bx = interpolate(x, b[0]) - var by = interpolate(y, b[1]) - - ax = xs * (ax - lox) - ay = ys * (ay - loy) - bx = xs * (bx - lox) - by = ys * (by - loy) - - var dx = ax - bx - var dy = ay - by - - for (var k = 0; k < WEIGHTS.length; k += 2) { - var wx = WEIGHTS[k] - var wix = 1.0 - wx - var wy = 2.0 * WEIGHTS[k + 1] - 1.0 - - positions.push( - wix * ax + wx * bx, wix * ay + wx * by, - wy * dx, wy * dy) - colors.push(c_r, c_g, c_b, c_a) - ids.push(pointId) - } - } - } - - this.positionBuffer.update(new Float32Array(positions)) - this.colorBuffer.update(new Uint8Array(colors)) - this.idBuffer.update(new Uint32Array(ids)) - this.numVertices = ids.length - - var fillColors = options.fillColors - var fillCellColors = [] - var fillCellPositions = [] - var fillVerts = 0 - - if (fillColors) { - _$cleanPSLG_54(fillPositions, fillCells) - var fillMesh = _$cdt2d_47(fillPositions, fillCells, { - delaunay: false - }) - for (i = 0; i < fillMesh.length; ++i) { - var cell = fillMesh[i] - var cx = 0 - var cy = 0 - - for (j = 0; j < 3; ++j) { - var p = fillPositions[cell[j]] - var px = interpolate(x, p[0]) - var py = interpolate(y, p[1]) - cx += p[0] - cy += p[1] - fillCellPositions.push( - xs * (px - lox), - ys * (py - loy)) - } - - // Compute centroid of triangle - cx /= 3 - cy /= 3 - - // Sample height field at triangle centroid - var cxi = Math.floor(cx) - var cyi = Math.floor(cy) - var cxf = cx - cxi - var cyf = cy - cyi - - var c00 = zarray.get(cxi, cyi) - var c01 = zarray.get(cxi, cyi + 1) - var c10 = zarray.get(cxi + 1, cyi) - var c11 = zarray.get(cxi + 1, cyi + 1) - - var zlevel = - (1 - cyf) * ((1 - cxf) * c00 + cxf * c10) + - cyf * ((1 - cxf) * c01 + cxf * c11) - - // Color triangle using centroid data - var l = _$searchBounds_88.le(levels, zlevel) + 1 - var cr = (255 * fillColors[4 * l + 0]) | 0 - var cg = (255 * fillColors[4 * l + 1]) | 0 - var cb = (255 * fillColors[4 * l + 2]) | 0 - var ca = (255 * fillColors[4 * l + 3]) | 0 - - fillCellColors.push( - cr, cg, cb, ca, - cr, cg, cb, ca, - cr, cg, cb, ca) - - fillVerts += 3 - } - - this.fillPositionBuffer.update(new Float32Array(fillCellPositions)) - this.fillColorBuffer.update(new Uint8Array(fillCellColors)) - - this.fillVerts = fillVerts - } -} - -__proto_86.dispose = function () { - this.plot.removeObject(this) -} - -function createContour2D (plot, options) { - var gl = plot.gl - - var shader = _$createShader_107(gl, _$shaders_87.vertex, _$shaders_87.fragment) - var fillShader = _$createShader_107(gl, _$shaders_87.fillVertex, _$shaders_87.fragment) - - var positionBuffer = _$createBuffer_83(gl) - var colorBuffer = _$createBuffer_83(gl) - var idBuffer = _$createBuffer_83(gl) - - var fillPositionBuffer = _$createBuffer_83(gl) - var fillColorBuffer = _$createBuffer_83(gl) - - var contours = new GLContour2D( - plot, - shader, - fillShader, - positionBuffer, - colorBuffer, - idBuffer, - fillPositionBuffer, - fillColorBuffer) - - contours.update(options) - plot.addObject(contours) - - return contours -} + var i, j, arrayVar, newArray, arrayVarName; -'use strict' - -/* removed: var _$browser_124 = require('glslify') */; - -var _$shaders_92 = { - fragment: _$browser_124(["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: _$browser_124(["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: _$browser_124(["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: _$browser_124(["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"]) -} + for(i = 0; i < arrayVarNames.length; i++) { + arrayVar = trace[arrayVarNames[i]]; + if(arrayVar) colLen = Math.min(colLen, arrayVar.length); + } + + if(colLen < col1.length) col1 = col1.slice(0, colLen); + if(colLen < col2.length) col2 = col2.slice(0, colLen); + + for(i = 0; i < colLen; i++) { + col1[i] = ax1.d2c(col1[i], 0, col1Calendar); + col2[i] = ax2.d2c(col2[i], 0, col2Calendar); + } -"use strict" + var col1dv = _$lib_425.distinctVals(col1), + col1vals = col1dv.vals, + col2dv = _$lib_425.distinctVals(col2), + col2vals = col2dv.vals, + newArrays = []; -function __compileSearch_93(funcName, predicate, reversed, extraArgs, 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[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){") + for(i = 0; i < arrayVarNames.length; i++) { + newArrays[i] = _$lib_425.init2dArray(col2vals.length, col1vals.length); } - } 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_93(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - __compileSearch_93("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_93("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() -} + var i1, i2, text; -var _$searchBounds_93 = { - ge: __compileBoundsSearch_93(">=", false, "GE"), - gt: __compileBoundsSearch_93(">", false, "GT"), - lt: __compileBoundsSearch_93("<", true, "LT"), - le: __compileBoundsSearch_93("<=", true, "LE"), - eq: __compileBoundsSearch_93("-", true, "EQ", true) -} + if(hasColumnText) text = _$lib_425.init2dArray(col2vals.length, col1vals.length); -'use strict' - -var _$createHeatmap2D_91 = createHeatmap2D - -/* removed: var _$searchBounds_93 = require('binary-search-bounds') */; -/* removed: var _$iota_130 = require('iota-array') */; -/* removed: var _$pool_207 = require('typedarray-pool') */; -/* removed: var _$createShader_107 = require('gl-shader') */; -/* removed: var _$createBuffer_83 = require('gl-buffer') */; - -/* removed: var _$shaders_92 = require('./lib/shaders') */; - -function GLHeatmap2D ( - plot, - shader, - pickShader, - positionBuffer, - weightBuffer, - colorBuffer, - idBuffer) { - this.plot = plot - this.shader = shader - this.pickShader = pickShader - this.positionBuffer = positionBuffer - this.weightBuffer = weightBuffer - this.colorBuffer = colorBuffer - this.idBuffer = idBuffer - this.xData = [] - this.yData = [] - this.shape = [0, 0] - this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - this.pickOffset = 0 -} - -var __proto_91 = GLHeatmap2D.prototype - -var __WEIGHTS_91 = [ - 0, 0, - 1, 0, - 0, 1, - 1, 0, - 1, 1, - 0, 1 -] - -__proto_91.draw = (function () { - var MATRIX = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] - - return function () { - var plot = this.plot - var shader = this.shader - var bounds = this.bounds - var numVertices = this.numVertices - - if (numVertices <= 0) { - return - } - - var gl = plot.gl - var dataBox = plot.dataBox - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - - shader.bind() - - var uniforms = shader.uniforms - uniforms.viewTransform = MATRIX - - uniforms.shape = this.shape - - var attributes = shader.attributes - this.positionBuffer.bind() - attributes.position.pointer() - - this.weightBuffer.bind() - attributes.weight.pointer(gl.UNSIGNED_BYTE, false) - - this.colorBuffer.bind() - attributes.color.pointer(gl.UNSIGNED_BYTE, true) - - gl.drawArrays(gl.TRIANGLES, 0, numVertices) - } -})() - -__proto_91.drawPick = (function () { - var MATRIX = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] - - var PICK_VECTOR = [0, 0, 0, 0] - - return function (pickOffset) { - var plot = this.plot - var shader = this.pickShader - var bounds = this.bounds - var numVertices = this.numVertices - - if (numVertices <= 0) { - return - } - - var gl = plot.gl - var dataBox = plot.dataBox - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - - for (var i = 0; i < 4; ++i) { - PICK_VECTOR[i] = (pickOffset >> (i * 8)) & 0xff - } - - this.pickOffset = pickOffset - - shader.bind() - - var uniforms = shader.uniforms - uniforms.viewTransform = MATRIX - uniforms.pickOffset = PICK_VECTOR - uniforms.shape = this.shape - - var attributes = shader.attributes - this.positionBuffer.bind() - attributes.position.pointer() - - this.weightBuffer.bind() - attributes.weight.pointer(gl.UNSIGNED_BYTE, false) - - this.idBuffer.bind() - attributes.pickId.pointer(gl.UNSIGNED_BYTE, false) - - gl.drawArrays(gl.TRIANGLES, 0, numVertices) - - return pickOffset + this.shape[0] * this.shape[1] - } -})() - -__proto_91.pick = function (x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.shape[0] * this.shape[1] - if (value < pickOffset || value >= pickOffset + pointCount) { - return null - } - var pointId = value - pickOffset - var xData = this.xData - var yData = this.yData - return { - object: this, - pointId: pointId, - dataCoord: [ - xData[pointId % this.shape[0]], - yData[(pointId / this.shape[0]) | 0]] - } -} - -__proto_91.update = function (options) { - options = options || {} - - var shape = options.shape || [0, 0] - - var x = options.x || _$iota_130(shape[0]) - var y = options.y || _$iota_130(shape[1]) - var z = options.z || new Float32Array(shape[0] * shape[1]) - - this.xData = x - this.yData = y - - var colorLevels = options.colorLevels || [0] - var colorValues = options.colorValues || [0, 0, 0, 1] - var colorCount = colorLevels.length - - var bounds = this.bounds - var lox = bounds[0] = x[0] - var loy = bounds[1] = y[0] - var hix = bounds[2] = x[x.length - 1] - var hiy = bounds[3] = y[y.length - 1] - - var xs = 1.0 / (hix - lox) - var ys = 1.0 / (hiy - loy) - - var numX = shape[0] - var numY = shape[1] - - this.shape = [numX, numY] - - var numVerts = (numX - 1) * (numY - 1) * (__WEIGHTS_91.length >>> 1) - - this.numVertices = numVerts - - var colors = _$pool_207.mallocUint8(numVerts * 4) - var positions = _$pool_207.mallocFloat32(numVerts * 2) - var weights = _$pool_207.mallocUint8 (numVerts * 2) - var ids = _$pool_207.mallocUint32(numVerts) - - var ptr = 0 - - for (var j = 0; j < numY - 1; ++j) { - var yc0 = ys * (y[j] - loy) - var yc1 = ys * (y[j + 1] - loy) - for (var i = 0; i < numX - 1; ++i) { - var xc0 = xs * (x[i] - lox) - var xc1 = xs * (x[i + 1] - lox) - - for (var dd = 0; dd < __WEIGHTS_91.length; dd += 2) { - var dx = __WEIGHTS_91[dd] - var dy = __WEIGHTS_91[dd + 1] - var offset = (j + dy) * numX + (i + dx) - var zc = z[offset] - var colorIdx = _$searchBounds_93.le(colorLevels, zc) - var r, g, b, a - if (colorIdx < 0) { - r = colorValues[0] - g = colorValues[1] - b = colorValues[2] - a = colorValues[3] - } else if (colorIdx === colorCount - 1) { - r = colorValues[4 * colorCount - 4] - g = colorValues[4 * colorCount - 3] - b = colorValues[4 * colorCount - 2] - a = colorValues[4 * colorCount - 1] - } else { - var t = (zc - colorLevels[colorIdx]) / - (colorLevels[colorIdx + 1] - colorLevels[colorIdx]) - var ti = 1.0 - t - var i0 = 4 * colorIdx - var i1 = 4 * (colorIdx + 1) - r = ti * colorValues[i0] + t * colorValues[i1] - g = ti * colorValues[i0 + 1] + t * colorValues[i1 + 1] - b = ti * colorValues[i0 + 2] + t * colorValues[i1 + 2] - a = ti * colorValues[i0 + 3] + t * colorValues[i1 + 3] - } - - colors[4 * ptr] = 255 * r - colors[4 * ptr + 1] = 255 * g - colors[4 * ptr + 2] = 255 * b - colors[4 * ptr + 3] = 255 * a - - positions[2*ptr] = xc0*.5 + xc1*.5; - positions[2*ptr+1] = yc0*.5 + yc1*.5; - - weights[2*ptr] = dx; - weights[2*ptr+1] = dy; - - ids[ptr] = j * numX + i - - ptr += 1 - } - } - } - - this.positionBuffer.update(positions) - this.weightBuffer.update(weights) - this.colorBuffer.update(colors) - this.idBuffer.update(ids) - - _$pool_207.free(positions) - _$pool_207.free(colors) - _$pool_207.free(weights) - _$pool_207.free(ids) -} - -__proto_91.dispose = function () { - this.shader.dispose() - this.pickShader.dispose() - this.positionBuffer.dispose() - this.weightBuffer.dispose() - this.colorBuffer.dispose() - this.idBuffer.dispose() - this.plot.removeObject(this) -} - -function createHeatmap2D (plot, options) { - var gl = plot.gl - - var shader = _$createShader_107(gl, _$shaders_92.vertex, _$shaders_92.fragment) - var pickShader = _$createShader_107(gl, _$shaders_92.pickVertex, _$shaders_92.pickFragment) - - var positionBuffer = _$createBuffer_83(gl) - var weightBuffer = _$createBuffer_83(gl) - var colorBuffer = _$createBuffer_83(gl) - var idBuffer = _$createBuffer_83(gl) - - var heatmap = new GLHeatmap2D( - plot, - shader, - pickShader, - positionBuffer, - weightBuffer, - colorBuffer, - idBuffer) - - heatmap.update(options) - plot.addObject(heatmap) - - return heatmap -} + for(i = 0; i < colLen; i++) { + if(col1[i] !== __BADNUM_540 && col2[i] !== __BADNUM_540) { + i1 = _$lib_425.findBin(col1[i] + col1dv.minDiff / 2, col1vals); + i2 = _$lib_425.findBin(col2[i] + col2dv.minDiff / 2, col2vals); + + for(j = 0; j < arrayVarNames.length; j++) { + arrayVarName = arrayVarNames[j]; + arrayVar = trace[arrayVarName]; + newArray = newArrays[j]; + newArray[i2][i1] = arrayVar[i]; + } + + if(hasColumnText) text[i2][i1] = textCol[i]; + } + } + + trace['_' + var1Name] = col1vals; + trace['_' + var2Name] = col2vals; + for(j = 0; j < arrayVarNames.length; j++) { + trace['_' + arrayVarNames[j]] = newArrays[j]; + } + if(hasColumnText) trace._text = text; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -61710,182 +62608,268 @@ function createHeatmap2D (plot, options) { 'use strict'; -/* removed: var _$createContour2D_86 = require('gl-contour2d'); */; -/* removed: var _$createHeatmap2D_91 = require('gl-heatmap2d'); */; +var _$maxRowLength_546 = function maxRowLength(z) { + var len = 0; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$makeColorMap_468 = require('../contour/make_color_map'); */; -/* removed: var _$str2RgbaArray_385 = require('../../lib/str2rgbarray'); */; + for(var i = 0; i < z.length; i++) { + len = Math.max(len, z[i].length); + } + return len; +}; -function Contour(scene, uid) { - this.scene = scene; - this.uid = uid; - this.type = 'contourgl'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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.name = ''; - this.hoverinfo = 'all'; +'use strict'; - this.xData = []; - this.yData = []; - this.zData = []; - this.textLabels = []; +/* removed: var _$maxRowLength_546 = require('./max_row_length'); */; - this.idToIndex = []; - this.bounds = [0, 0, 0, 0]; +/* 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 + */ +var _$findEmpties_542 = function findEmpties(z) { + var empties = [], + neighborHash = {}, + noNeighborList = [], + nextRow = z[0], + row = [], + blank = [0, 0, 0], + rowLength = _$maxRowLength_546(z), + prevRow, + i, + j, + thisPt, + p, + neighborCount, + newNeighborHash, + foundNewNeighbors; - this.contourOptions = { - z: new Float32Array(0), - x: [], - y: [], - shape: [0, 0], - levels: [0], - levelColors: [0, 0, 0, 1], - lineWidth: 1 - }; - this.contour = _$createContour2D_86(scene.glplot, this.contourOptions); - this.contour._trace = this; + 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); - this.heatmapOptions = { - z: new Float32Array(0), - x: [], - y: [], - shape: [0, 0], - colorLevels: [0], - colorValues: [0, 0, 0, 0] - }; - this.heatmap = _$createHeatmap2D_91(scene.glplot, this.heatmapOptions); - this.heatmap._trace = this; -} + 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++; -var __proto_471 = Contour.prototype; + // 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]; + } -__proto_471.handlePick = function(pickResult) { - var options = this.heatmapOptions, - shape = options.shape, - index = pickResult.pointId, - xIndex = index % shape[0], - yIndex = Math.floor(index / shape[0]), - zIndex = index; + empties.push([i, j, neighborCount]); + } + else noNeighborList.push([i, j]); + } + } + } - return { - trace: this, - dataCoord: pickResult.dataCoord, - traceCoord: [ - options.x[xIndex], - options.y[yIndex], - options.z[zIndex] - ], - textLabel: this.textLabels[index], - name: this.name, - pointIndex: [yIndex, xIndex], - hoverinfo: this.hoverinfo - }; + 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]; }); }; -__proto_471.update = function(fullTrace, calcTrace) { - var calcPt = calcTrace[0]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var __isArrayOrTypedArray_543 = _$lib_425.isArrayOrTypedArray; + +var _$has_columns_543 = function(trace) { + return !__isArrayOrTypedArray_543(trace.z[0]); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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.index = fullTrace.index; - this.name = fullTrace.name; - this.hoverinfo = fullTrace.hoverinfo; +'use strict'; - // convert z from 2D -> 1D - var z = calcPt.z, - rowLen = z[0].length, - colLen = z.length, - colorOptions; +/* removed: var _$lib_425 = require('../../lib'); */; - this.contourOptions.z = flattenZ(z, rowLen, colLen); - this.heatmapOptions.z = [].concat.apply([], z); +var INTERPTHRESHOLD = 1e-2, + NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - this.contourOptions.shape = this.heatmapOptions.shape = [rowLen, colLen]; +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); +} - this.contourOptions.x = this.heatmapOptions.x = calcPt.x; - this.contourOptions.y = this.heatmapOptions.y = calcPt.y; +var _$interp2d_544 = function interp2d(z, emptyPoints, savedInterpZ) { + // fill in any missing data in 2D array z 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) + var maxFractionalChange = 1, + i, + thisPt; - // pass on fill information - if(fullTrace.contours.coloring === 'fill') { - colorOptions = convertColorScale(fullTrace, {fill: true}); - this.contourOptions.levels = colorOptions.levels.slice(1); - // though gl-contour2d automatically defaults to a transparent layer for the last - // band color, it's set manually here in case the gl-contour2 API changes - this.contourOptions.fillColors = colorOptions.levelColors; - this.contourOptions.levelColors = [].concat.apply([], this.contourOptions.levels.map(function() { - return [0.25, 0.25, 0.25, 1.0]; - })); - } else { - colorOptions = convertColorScale(fullTrace, {fill: false}); - this.contourOptions.levels = colorOptions.levels; - this.contourOptions.levelColors = colorOptions.levelColors; + if(Array.isArray(savedInterpZ)) { + for(i = 0; i < emptyPoints.length; i++) { + thisPt = emptyPoints[i]; + z[thisPt[0]][thisPt[1]] = savedInterpZ[thisPt[0]][thisPt[1]]; + } + } + else { + // one pass to fill in a starting value for all the empties + iterateInterp2d(z, emptyPoints); } - // convert text from 2D -> 1D - this.textLabels = [].concat.apply([], fullTrace.text); + // 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); - this.contour.update(this.contourOptions); - this.heatmap.update(this.heatmapOptions); + for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) { + maxFractionalChange = iterateInterp2d(z, emptyPoints, + correctionOvershoot(maxFractionalChange)); + } + if(maxFractionalChange > INTERPTHRESHOLD) { + _$lib_425.log('interp2d didn\'t converge quickly', maxFractionalChange); + } - // expand axes - _$axes_407.expand(this.scene.xaxis, calcPt.x); - _$axes_407.expand(this.scene.yaxis, calcPt.y); + return z; }; -__proto_471.dispose = function() { - this.contour.dispose(); - this.heatmap.dispose(); -}; +function iterateInterp2d(z, emptyPoints, overshoot) { + var maxFractionalChange = 0, + thisPt, + i, + j, + p, + q, + neighborShift, + neighborRow, + neighborVal, + neighborCount, + neighborSum, + initialVal, + minNeighbor, + maxNeighbor; -function flattenZ(zIn, rowLen, colLen) { - var zOut = new Float32Array(rowLen * colLen); - var pt = 0; + 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(var i = 0; i < rowLen; i++) { - for(var j = 0; j < colLen; j++) { - zOut[pt++] = zIn[j][i]; + 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; + } } - } - - return zOut; -} - -function convertColorScale(fullTrace, options) { - var contours = fullTrace.contours, - start = contours.start, - end = contours.end, - cs = contours.size || 1, - fill = options.fill; - var colorMap = _$makeColorMap_468(fullTrace); + if(neighborCount === 0) { + throw 'iterateInterp2d order is wrong: no defined neighbors'; + } - var N = Math.floor((end - start) / cs) + (fill ? 2 : 1), // for K thresholds (contour linees) there are K+1 areas - levels = new Array(N), - levelColors = new Array(4 * N); + // 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; - for(var i = 0; i < N; i++) { - var level = levels[i] = start + cs * (i) - (fill ? cs / 2 : 0); // in case of fill, use band midpoint - var color = _$str2RgbaArray_385(colorMap(level)); + 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; - for(var j = 0; j < 4; j++) { - levelColors[(4 * i) + j] = color[j]; + if(maxNeighbor > minNeighbor) { + maxFractionalChange = Math.max(maxFractionalChange, + Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor)); + } } } - return { - levels: levels, - levelColors: levelColors - }; -} - -function createContour(scene, fullTrace, calcTrace) { - var plot = new Contour(scene, fullTrace.uid); - plot.update(fullTrace, calcTrace); - - return plot; + return maxFractionalChange; } -var _$createContour_471 = createContour; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -61894,29 +62878,79 @@ var _$createContour_471 = createContour; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var __overrideAll_472 = _$edit_types_392.overrideAll; +/* removed: var _$registry_514 = require('../../registry'); */; +var __isArrayOrTypedArray_545 = _$lib_425.isArrayOrTypedArray; -var ContourGl = {}; +var _$makeBoundArray_545 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { + var arrayOut = [], + isContour = _$registry_514.traceIs(trace, 'contour'), + isHist = _$registry_514.traceIs(trace, 'histogram'), + isGL2D = _$registry_514.traceIs(trace, 'gl2d'), + v0, + dv, + i; -ContourGl.attributes = __overrideAll_472(_$attributes_460, 'calc', 'nested'); -ContourGl.supplyDefaults = _$supplyDefaults_465; -ContourGl.colorbar = _$colorbar_462; + var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_545(arrayIn) && arrayIn.length > 1; -ContourGl.calc = _$calc_461; -ContourGl.plot = _$createContour_471; + if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) { + var len = arrayIn.length; -ContourGl.moduleType = 'trace'; -ContourGl.name = 'contourgl'; -ContourGl.basePlotModule = _$gl2d_439; -ContourGl.categories = ['gl', 'gl2d', '2dMap']; -ContourGl.meta = { - -}; + // given vals are brick centers + // hopefully length === numbricks, but use this method even if too few are supplied + // and extend it linearly based on the last two points + if(len <= numbricks) { + // contour plots only want the centers + if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks); + else if(numbricks === 1) { + arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5]; + } + else { + arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]]; + + for(i = 1; i < len; i++) { + arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5); + } + + arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]); + } + + if(len < numbricks) { + var lastPt = arrayOut[arrayOut.length - 1], + delta = lastPt - arrayOut[arrayOut.length - 2]; + + for(i = len; i < numbricks; i++) { + lastPt += delta; + arrayOut.push(lastPt); + } + } + } + else { + // hopefully length === numbricks+1, but do something regardless: + // given vals are brick boundaries + return isContour ? + arrayIn.slice(0, numbricks) : // we must be strict for contours + arrayIn.slice(0, numbricks + 1); + } + } + else { + dv = dvIn || 1; + + var calendar = trace[ax._id.charAt(0) + 'calendar']; + + if(isHist || ax.type === 'category') v0 = ax.r2c(v0In, 0, calendar) || 0; + else if(__isArrayOrTypedArray_545(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; + else if(v0In === undefined) v0 = 0; + else v0 = ax.d2c(v0In, 0, calendar); + + for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) { + arrayOut.push(v0 + dv * i); + } + } -var _$ContourGl_472 = ContourGl; + return arrayOut; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -61926,1427 +62960,1494 @@ var _$ContourGl_472 = ContourGl; * LICENSE file in the root directory of this source tree. */ -'use strict'; - -var _$contourgl_3 = _$ContourGl_472; -var _$plotcss_1 = {}; 'use strict'; -/* removed: var _$lib_363 = require('../src/lib'); */; -var rules = { - "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", - "X .modebar--hover": "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": "opacity:1;", - "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", - "X .modebar-group:first-child": "margin-left:0px;", - "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", - "X .modebar-btn svg": "position:relative;top:2px;", - "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", - "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", - "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", - "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", - "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 .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_363.addStyleRule(fullSelector, rules[selector]); -} - -'use strict'; -var _$ploticon_2 = { - 'undo': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'home': { - 'width': 928.6, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'camera-retro': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoombox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'pan': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_plus': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'zoom_minus': { - 'width': 1000, - 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', - 'ascent': 850, - 'descent': -150 - }, - 'autoscale': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_basic': { - 'width': 1500, - 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', - 'ascent': 850, - 'descent': -150 - }, - 'tooltip_compare': { - 'width': 1125, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'plotlylogo': { - 'width': 1542, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'z-axis': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - '3d_rotate': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'camera': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'movie': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'question': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'disk': { - 'width': 857.1, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'lasso': { - 'width': 1031, - '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', - 'ascent': 850, - 'descent': -150 - }, - 'selectbox': { - 'width': 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', - 'ascent': 850, - 'descent': -150 - }, - 'spikeline': { - 'width': 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', - 'ascent': 850, - 'descent': -150 +var _$doAvg_552 = function doAvg(size, counts) { + var nMax = size.length, + total = 0; + for(var i = 0; i < nMax; i++) { + if(counts[i]) { + size[i] /= counts[i]; + total += size[i]; + } + else size[i] = null; } + return total; }; -var _$es6Promise_76 = { exports: {} }; -(function (process,global){ -/*! - * @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 - */ +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -(function (global, factory) { - typeof _$es6Promise_76.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_76.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ES6Promise = factory()); -}(this, (function () { 'use strict'; -function objectOrFunction(x) { - return typeof x === 'function' || typeof x === 'object' && x !== null; -} +'use strict'; -function isFunction(x) { - return typeof x === 'function'; -} +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -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 _$bin_functions_553 = { + count: function(n, i, size) { + size[n]++; + return 1; + }, -var len = 0; -var vertxNext = undefined; -var customSchedulerFn = undefined; + sum: function(n, i, size, counterData) { + var v = counterData[i]; + if(_$fastIsnumeric_135(v)) { + v = Number(v); + size[n] += v; + return v; + } + return 0; + }, -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(); + avg: function(n, i, size, counterData, counts) { + var v = counterData[i]; + if(_$fastIsnumeric_135(v)) { + v = Number(v); + size[n] += v; + counts[n]++; + } + return 0; + }, + + min: function(n, i, size, counterData) { + var v = counterData[i]; + if(_$fastIsnumeric_135(v)) { + v = Number(v); + if(!_$fastIsnumeric_135(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(_$fastIsnumeric_135(v)) { + v = Number(v); + if(!_$fastIsnumeric_135(size[n])) { + size[n] = v; + return v; + } + else if(size[n] < v) { + var delta = v - size[n]; + size[n] = v; + return delta; + } + } + return 0; } - } }; -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; -} - -function setAsap(asapFn) { - asap = asapFn; -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 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'; +'use strict'; -// 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); - }; -} +/* removed: var _$numerical_404 = require('../../constants/numerical'); */; +var oneYear = _$numerical_404.ONEAVGYEAR; +var oneMonth = _$numerical_404.ONEAVGMONTH; +var oneDay = _$numerical_404.ONEDAY; +var oneHour = _$numerical_404.ONEHOUR; +var oneMin = _$numerical_404.ONEMIN; +var oneSec = _$numerical_404.ONESEC; +var tickIncrement = _$axes_470.tickIncrement; -// 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 }); +/* + * 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` + */ +var _$getBinSpanLabelRound_554 = 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) + ); - return function () { - node.data = iterations = ++iterations % 2; - }; -} + // 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; + } -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); - }; -} + if(pa.type === 'date' && digit > oneDay) { + var dashExclude = (digit === oneYear) ? 1 : 6; + var increment = (digit === oneYear) ? 'M12' : 'M1'; -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); - }; -} + 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); -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; + if(roundedV < v) { + var nextV = tickIncrement(roundedV, increment, false, calendar); + if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV; + } - callback(arg); + if(isRightEdge && disambiguateEdges) { + return tickIncrement(roundedV, increment, true, calendar); + } - queue[i] = undefined; - queue[i + 1] = undefined; - } + return roundedV; + }; + } - len = 0; -} + 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; + }; +}; -function attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} +/* + * 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 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 && typeof require === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); + 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; } -function then(onFulfillment, onRejection) { - var _arguments = arguments; - - var parent = this; - - var child = new this.constructor(noop); +/* + * 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 (child[PROMISE_ID] === undefined) { - makePromise(child); - } + if(dv > oneHour) return oneHour; + if(dv > oneMin) return oneMin; + return oneSec; + } + return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10)); +} - var _state = parent._state; +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]; - if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } + } + return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1; +} - return child; +function dateParts(v, pa, calendar) { + var parts = pa.c2d(v, oneYear, calendar).split('-'); + if(parts[0] === '') { + parts.unshift(); + parts[0] = '-' + parts[0]; + } + return parts; } /** - `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 - }); - ``` +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - Instead of writing the above, your code now simply becomes the following: - ```javascript - let promise = Promise.resolve(1); +'use strict'; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +var cleanDate = _$lib_425.cleanDate; +/* removed: var _$numerical_404 = require('../../constants/numerical'); */; +var __ONEDAY_555 = _$numerical_404.ONEDAY; +var __BADNUM_555 = _$numerical_404.BADNUM; - promise.then(function(value){ - // value === 1 - }); - ``` +/* + * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) + * Mutates trace so all these attributes are valid. + * + * Normally this kind of thing would happen during supplyDefaults, but + * in this case we need to know the axis type, and axis type isn't set until + * after trace supplyDefaults are completed. So this gets called during the + * calc step, when data are inserted into bins. + */ +var _$cleanBins_555 = function cleanBins(trace, ax, binDirection) { + var axType = ax.type, + binAttr = binDirection + 'bins', + bins = trace[binAttr]; - @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(!bins) bins = trace[binAttr] = {}; - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } + var cleanBound = (axType === 'date') ? + function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_555, bins.calendar) : null; } : + function(v) { return _$fastIsnumeric_135(v) ? Number(v) : null; }; - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; -} + bins.start = cleanBound(bins.start); + bins.end = cleanBound(bins.end); -var PROMISE_ID = Math.random().toString(36).substring(16); + // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) + // but without the extra string options for log axes + // ie the only strings we accept are M for months + var sizeDflt = (axType === 'date') ? __ONEDAY_555 : 1, + binSize = bins.size; -function noop() {} + if(_$fastIsnumeric_135(binSize)) { + bins.size = (binSize > 0) ? Number(binSize) : sizeDflt; + } + else if(typeof binSize !== 'string') { + bins.size = sizeDflt; + } + else { + // date special case: "M" gives bins every (integer) n months + var prefix = binSize.charAt(0), + sizeNum = binSize.substr(1); -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; + sizeNum = _$fastIsnumeric_135(sizeNum) ? Number(sizeNum) : 0; + if((sizeNum <= 0) || !( + axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum) + )) { + bins.size = sizeDflt; + } + } -var GET_THEN_ERROR = new ErrorObject(); + var autoBinAttr = 'autobin' + binDirection; -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} + if(typeof trace[autoBinAttr] !== 'boolean') { + trace[autoBinAttr] = trace._fullInput[autoBinAttr] = trace._input[autoBinAttr] = !( + (bins.start || bins.start === 0) && + (bins.end || bins.end === 0) + ); + } -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} + if(!trace[autoBinAttr]) { + delete trace['nbins' + binDirection]; + delete trace._fullInput['nbins' + binDirection]; + } +}; -function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -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; +'use strict'; - _reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - if (!sealed && error) { - sealed = true; - _reject(promise, error); +var _$norm_functions_556 = { + percent: function(size, total) { + var nMax = size.length, + norm = 100 / total; + for(var n = 0; n < nMax; n++) size[n] *= norm; + }, + probability: function(size, total) { + var nMax = size.length; + for(var n = 0; n < nMax; n++) size[n] /= total; + }, + density: function(size, total, inc, yinc) { + var nMax = size.length; + yinc = yinc || 1; + for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc; + }, + 'probability density': function(size, total, inc, yinc) { + var nMax = size.length; + if(yinc) total /= yinc; + for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total; } - }, 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); - }); - } -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -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); - } -} +'use strict'; -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; - publish(promise); -} +/* removed: var _$bin_functions_553 = require('../histogram/bin_functions'); */; +/* removed: var _$norm_functions_556 = require('../histogram/norm_functions'); */; +/* removed: var _$doAvg_552 = require('../histogram/average'); */; +/* removed: var _$cleanBins_555 = require('../histogram/clean_bins'); */; +/* removed: var _$getBinSpanLabelRound_554 = require('../histogram/bin_label_vals'); */; -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } - promise._result = value; - promise._state = FULFILLED; +var _$calc_557 = function calc(gd, trace) { + var xa = _$axes_470.getFromId(gd, trace.xaxis || 'x'); + var x = trace.x ? xa.makeCalcdata(trace, 'x') : []; + var ya = _$axes_470.getFromId(gd, trace.yaxis || 'y'); + var y = trace.y ? ya.makeCalcdata(trace, 'y') : []; + 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); }; - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} + var i, j, n, m; -function _reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; + var serieslen = Math.min(x.length, y.length); + if(x.length > serieslen) x.splice(serieslen, x.length - serieslen); + if(y.length > serieslen) y.splice(serieslen, y.length - serieslen); - asap(publishRejection, promise); -} + // calculate the bins + cleanAndAutobin(trace, 'x', x, xa, xr2c, xc2r, xcalendar); + cleanAndAutobin(trace, 'y', y, ya, yr2c, yc2r, ycalendar); -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; + // make the empty bin array & scale the map + var z = []; + var onecol = []; + var zerocol = []; + var nonuniformBinsX = (typeof(trace.xbins.size) === 'string'); + var nonuniformBinsY = (typeof(trace.ybins.size) === 'string'); + var xEdges = []; + var yEdges = []; + var xbins = nonuniformBinsX ? xEdges : trace.xbins; + var ybins = nonuniformBinsY ? yEdges : trace.ybins; + 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 = _$bin_functions_553.count; + var normfunc = _$norm_functions_556[norm]; + var doavg = false; + var xinc = []; + var yinc = []; - parent._onerror = null; + // 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 = _$bin_functions_553[func]; + } - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; + // decrease end a little in case of rounding errors + var binSpec = trace.xbins, + binStart = xr2c(binSpec.start), + binEnd = xr2c(binSpec.end) + + (binStart - _$axes_470.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; - if (length === 0 && parent._state) { - asap(publish, parent); - } -} + for(i = binStart; i < binEnd; i = _$axes_470.tickIncrement(i, binSpec.size, false, xcalendar)) { + onecol.push(sizeinit); + xEdges.push(i); + if(doavg) zerocol.push(0); + } + xEdges.push(i); -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; + var nx = onecol.length; + var x0c = xr2c(trace.xbins.start); + var dx = (i - x0c) / nx; + var x0 = xc2r(x0c + dx / 2); - if (subscribers.length === 0) { - return; - } + binSpec = trace.ybins; + binStart = yr2c(binSpec.start); + binEnd = yr2c(binSpec.end) + + (binStart - _$axes_470.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; - var child = undefined, - callback = undefined, - detail = promise._result; + for(i = binStart; i < binEnd; i = _$axes_470.tickIncrement(i, binSpec.size, 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); - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; + var ny = z.length; + var y0c = yr2c(trace.ybins.start); + var dy = (i - y0c) / ny; + var y0 = yc2r(y0c + dy / 2); - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); + if(densitynorm) { + xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX); + yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY); } - } - promise._subscribers.length = 0; -} + // 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); -function ErrorObject() { - this.error = null; -} + // 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 = x[i]; + var yi = y[i]; + n = _$lib_425.findBin(xi, xbins); + m = _$lib_425.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); -var TRY_CATCH_ERROR = new ErrorObject(); + if(uniqueValsPerX) { + if(xVals[n] === undefined) xVals[n] = xi; + else if(xVals[n] !== xi) uniqueValsPerX = false; + } + if(uniqueValsPerY) { + if(yVals[n] === undefined) yVals[n] = yi; + else if(yVals[n] !== yi) uniqueValsPerY = false; + } -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} + 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_552(z[m], counts[m]); + } + if(normfunc) { + for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); + } -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; + return { + x: x, + xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar), + x0: x0, + dx: dx, + y: y, + yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar), + y0: y0, + dy: dy, + z: z, + pts: inputPoints + }; +}; - if (hasCallback) { - value = tryCatch(callback, detail); +function cleanAndAutobin(trace, axLetter, data, ax, r2c, c2r, calendar) { + var binSpecAttr = axLetter + 'bins'; + var autoBinAttr = 'autobin' + axLetter; + var binSpec = trace[binSpecAttr]; - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } + _$cleanBins_555(trace, ax, axLetter); - if (promise === value) { - _reject(promise, cannotReturnOwn()); - return; - } - } else { - value = detail; - succeeded = true; - } + if(trace[autoBinAttr] || !binSpec || binSpec.start === null || binSpec.end === null) { + binSpec = _$axes_470.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); + if(trace.type === 'histogram2dcontour') { + // the "true" last argument reverses the tick direction (which we can't + // just do with a minus sign because of month bins) + binSpec.start = c2r(_$axes_470.tickIncrement( + r2c(binSpec.start), binSpec.size, true, calendar)); + binSpec.end = c2r(_$axes_470.tickIncrement( + r2c(binSpec.end), binSpec.size, false, calendar)); + } - 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); + // copy bin info back to the source data. + trace._input[binSpecAttr] = trace[binSpecAttr] = binSpec; + // note that it's possible to get here with an explicit autobin: false + // if the bins were not specified. + // in that case this will remain in the trace, so that future updates + // which would change the autobinning will not do so. + trace._input[autoBinAttr] = trace[autoBinAttr]; } } -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value) { - _resolve(promise, value); - }, function rejectPromise(reason) { - _reject(promise, reason); - }); - } catch (e) { - _reject(promise, e); - } +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; } -var id = 0; -function nextId() { - return id++; +function binsToCalc(r2c, bins) { + return { + start: r2c(bins.start), + end: r2c(bins.end), + size: bins.size + }; } -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; +function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { + var i; + var len = edges.length - 1; + var out = new Array(len); + if(uniqueVals) { + for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]]; + } + else { + var roundFn = _$getBinSpanLabelRound_554(gapLow, gapHigh, edges, ax, calendar); + for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)]; + } + return out; } -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; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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._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()); - } -} +'use strict'; -function validationError() { - return new Error('Array Methods must be provided an Array'); -}; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; -Enumerator.prototype._enumerate = function () { - var length = this.length; - var _input = this._input; +/* removed: var _$calc_557 = require('../histogram2d/calc'); */; +/* removed: var _$calc_308 = require('../../components/colorscale/calc'); */; +/* removed: var _$has_columns_543 = require('./has_columns'); */; +/* removed: var _$convertColumnData_540 = require('./convert_column_xyz'); */; +/* removed: var _$maxRowLength_546 = require('./max_row_length'); */; +/* removed: var _$clean2dArray_538 = require('./clean_2d_array'); */; +/* removed: var _$interp2d_544 = require('./interp2d'); */; +/* removed: var _$findEmpties_542 = require('./find_empties'); */; +/* removed: var _$makeBoundArray_545 = require('./make_bound_array'); */; - 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; +var _$calc_537 = 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_470.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_470.getFromId(gd, trace.yaxis || 'y'), + isContour = _$registry_514.traceIs(trace, 'contour'), + isHist = _$registry_514.traceIs(trace, 'histogram'), + isGL2D = _$registry_514.traceIs(trace, 'gl2d'), + zsmooth = isContour ? 'best' : trace.zsmooth, + x, + x0, + dx, + y, + y0, + dy, + z, + i, + binned; - if (resolve$$ === resolve) { - var _then = getThen(entry); + // cancel minimum tick spacings (only applies to bars and boxes) + xa._minDtick = 0; + ya._minDtick = 0; - 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); + if(isHist) { + binned = _$calc_557(gd, trace); + x = binned.x; + x0 = binned.x0; + dx = binned.dx; + y = binned.y; + y0 = binned.y0; + dy = binned.dy; + z = binned.z; } - } else { - this._willSettleAt(resolve$$(entry), i); - } -}; + else { + var zIn = trace.z; + if(_$has_columns_543(trace)) { + _$convertColumnData_540(trace, xa, ya, 'x', 'y', ['z']); + x = trace._x; + y = trace._y; + zIn = trace._z; + } else { + x = trace.x ? xa.makeCalcdata(trace, 'x') : []; + y = trace.y ? ya.makeCalcdata(trace, 'y') : []; + } -Enumerator.prototype._settledAt = function (state, i, value) { - var promise = this.promise; + x0 = trace.x0 || 0; + dx = trace.dx || 1; + y0 = trace.y0 || 0; + dy = trace.dy || 1; - if (promise._state === PENDING) { - this._remaining--; + z = _$clean2dArray_538(zIn, trace.transpose); - if (state === REJECTED) { - _reject(promise, value); - } else { - this._result[i] = value; + if(isContour || trace.connectgaps) { + trace._emptypoints = _$findEmpties_542(z); + trace._interpz = _$interp2d_544(z, trace._emptypoints, trace._interpz); + } } - } - - 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); - }); -}; + function noZsmooth(msg) { + zsmooth = trace._input.zsmooth = trace.zsmooth = false; + _$lib_425.warn('cannot use zsmooth: "fast": ' + msg); + } -/** - `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. + // 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), + 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), + 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; + } + } + } + } + } - Example: + // create arrays of brick boundaries, to be used by autorange and heatmap.plot + var xlen = _$maxRowLength_546(z); + var xIn = trace.xtype === 'scaled' ? '' : x; + var xArray = _$makeBoundArray_545(trace, xIn, x0, dx, xlen, xa); + var yIn = trace.ytype === 'scaled' ? '' : y; + var yArray = _$makeBoundArray_545(trace, yIn, y0, dy, z.length, ya); - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; + // handled in gl2d convert step + if(!isGL2D) { + _$axes_470.expand(xa, xArray); + _$axes_470.expand(ya, yArray); + } - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` + var cd0 = { + x: xArray, + y: yArray, + z: z, + text: trace._text || trace.text + }; - 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: + if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn; + if(yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn; - Example: + if(isHist) { + cd0.xRanges = binned.xRanges; + cd0.yRanges = binned.yRanges; + cd0.pts = binned.pts; + } - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; + // auto-z and autocolorscale if applicable + if(!isContour || trace.contours.type !== 'constraint') { + _$calc_308(trace, z, '', 'z'); + } - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` + 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_545(dummyTrace, xIn, x0, dx, xlen, xa); + cd0.yfill = _$makeBoundArray_545(dummyTrace, yIn, y0, dy, z.length, ya); + } - @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; -} + return [cd0]; +}; /** - `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); - }); +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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: +'use strict'; - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); +/* removed: var _$calc_537 = require('../heatmap/calc'); */; +/* removed: var _$setContours_532 = require('./set_contours'); */; - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); +// 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 +var _$calc_524 = function calc(gd, trace) { + var cd = _$calc_537(gd, trace); + _$setContours_532(trace); + return cd; +}; - 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 - }); - ``` +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - An example real-world use case is implementing timeouts: +'use strict'; - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` +var _$constants_303 = { + cn: { + colorbar: 'colorbar', + cbbg: 'cbbg', + cbfill: 'cbfill', + cbfills: 'cbfills', + cbline: 'cbline', + cblines: 'cblines', + cbaxis: 'cbaxis', + cbtitleunshift: 'cbtitleunshift', + cbtitle: 'cbtitle', + cboutline: 'cboutline', + crisp: 'crisp', + jsPlaceholder: 'js-placeholder' + } +}; - @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. +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. */ -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); - } + +'use strict'; + +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$tinycolor_263 = require('tinycolor2'); */; + +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +var __extendFlat_305 = _$extend_416.extendFlat; +/* removed: var _$setCursor_445 = require('../../lib/setcursor'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$titles_394 = require('../titles'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +var __LINE_SPACING_305 = _$alignment_401.LINE_SPACING; + +/* removed: var _$handleAxisDefaults_472 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handlePositionDefaults_485 = require('../../plots/cartesian/position_defaults'); */; +/* removed: var _$layout_attributes_482 = require('../../plots/cartesian/layout_attributes'); */; + +/* removed: var _$attributes_302 = require('./attributes'); */; +var cn = _$constants_303.cn; + +var _$draw_305 = function draw(gd, id) { + // opts: options object, containing everything from attributes + // plus a few others that are the equivalent of the colorbar "data" + var opts = {}; + Object.keys(_$attributes_302).forEach(function(k) { + opts[k] = null; }); - } -} + // fillcolor can be a d3 scale, domain is z values, range is colors + // or leave it out for no fill, + // or set to a string constant for single-color fill + opts.fillcolor = null; + // line.color has the same options as fillcolor + opts.line = {color: null, width: null, dash: null}; + // levels of lines to draw. + // note that this DOES NOT determine the extent of the bar + // that's given by the domain of fillcolor + // (or line.color if no fillcolor domain) + opts.levels = {start: null, end: null, size: null}; + // separate fill levels (for example, heatmap coloring of a + // contour map) if this is omitted, fillcolors will be + // evaluated halfway between levels + opts.filllevels = null; -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: + function component() { + var fullLayout = gd._fullLayout, + gs = fullLayout._size; + if((typeof opts.fillcolor !== 'function') && + (typeof opts.line.color !== 'function')) { + fullLayout._infolayer.selectAll('g.' + id).remove(); + return; + } + var zrange = _$d3_71.extent(((typeof opts.fillcolor === 'function') ? + opts.fillcolor : opts.line.color).domain()); + var linelevels = []; + var filllevels = []; + var linecolormap = typeof opts.line.color === 'function' ? + opts.line.color : function() { return opts.line.color; }; + var fillcolormap = typeof opts.fillcolor === 'function' ? + opts.fillcolor : function() { return opts.fillcolor; }; + var l; + var i; - ```javascript - let promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); + var l0 = opts.levels.end + opts.levels.size / 100, + ls = opts.levels.size, + zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]), + zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]); + for(i = 0; i < 1e5; i++) { + l = opts.levels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zr0 && l < zr1) linelevels.push(l); + } - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + if(typeof opts.fillcolor === 'function') { + if(opts.filllevels) { + l0 = opts.filllevels.end + opts.filllevels.size / 100; + ls = opts.filllevels.size; + for(i = 0; i < 1e5; i++) { + l = opts.filllevels.start + i * ls; + if(ls > 0 ? (l >= l0) : (l <= l0)) break; + if(l > zrange[0] && l < zrange[1]) filllevels.push(l); + } + } + else { + filllevels = linelevels.map(function(v) { + return v - opts.levels.size / 2; + }); + filllevels.push(filllevels[filllevels.length - 1] + + opts.levels.size); + } + } + else if(opts.fillcolor && typeof opts.fillcolor === 'string') { + // doesn't matter what this value is, with a single value + // we'll make a single fill rect covering the whole bar + filllevels = [0]; + } - Instead of writing the above, your code now simply becomes the following: + if(opts.levels.size < 0) { + linelevels.reverse(); + filllevels.reverse(); + } - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); + // now make a Plotly Axes object to scale with and draw ticks + // TODO: does not support orientation other than right - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` + // we calculate pixel sizes based on the specified graph size, + // not the actual (in case something pushed the margins around) + // which is a little odd but avoids an odd iterative effect + // when the colorbar itself is pushing the margins. + // but then the fractional size is calculated based on the + // actual graph size, so that the axes will size correctly. + var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b, + originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r, + thickPx = Math.round(opts.thickness * + (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)), + thickFrac = thickPx / gs.w, + lenPx = Math.round(opts.len * + (opts.lenmode === 'fraction' ? originalPlotHeight : 1)), + lenFrac = lenPx / gs.h, + xpadFrac = opts.xpad / gs.w, + yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2, + ypadFrac = opts.ypad / gs.h, - @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; -} + // x positioning: do it initially just for left anchor, + // then fix at the end (since we don't know the width yet) + xLeft = Math.round(opts.x * gs.w + opts.xpad), + // for dragging... this is getting a little muddled... + xLeftFrac = opts.x - thickFrac * + ({middle: 0.5, right: 1}[opts.xanchor]||0), -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} + // y positioning we can do correctly from the start + yBottomFrac = opts.y + lenFrac * + (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5), + yBottomPx = Math.round(gs.h * (1 - yBottomFrac)), + yTopPx = yBottomPx - lenPx, + titleEl, + cbAxisIn = { + type: 'linear', + range: zrange, + tickmode: opts.tickmode, + nticks: opts.nticks, + tick0: opts.tick0, + dtick: opts.dtick, + tickvals: opts.tickvals, + ticktext: opts.ticktext, + ticks: opts.ticks, + ticklen: opts.ticklen, + tickwidth: opts.tickwidth, + tickcolor: opts.tickcolor, + showticklabels: opts.showticklabels, + tickfont: opts.tickfont, + tickangle: opts.tickangle, + tickformat: opts.tickformat, + exponentformat: opts.exponentformat, + separatethousands: opts.separatethousands, + showexponent: opts.showexponent, + showtickprefix: opts.showtickprefix, + tickprefix: opts.tickprefix, + showticksuffix: opts.showticksuffix, + ticksuffix: opts.ticksuffix, + title: opts.title, + titlefont: opts.titlefont, + showline: true, + anchor: 'free', + position: 1 + }, + cbAxisOut = { + type: 'linear', + _id: 'y' + id + }, + axisOptions = { + letter: 'y', + font: fullLayout.font, + noHover: true, + calendar: fullLayout.calendar // not really necessary (yet?) + }; -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} + // Coerce w.r.t. Axes layoutAttributes: + // re-use axes.js logic without updating _fullData + function coerce(attr, dflt) { + return _$lib_425.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_482, attr, dflt); + } -/** - 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. + // Prepare the Plotly axis object + _$handleAxisDefaults_472(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handlePositionDefaults_485(cbAxisIn, cbAxisOut, coerce, axisOptions); - Terminology - ----------- + // position can't go in through supplyDefaults + // because that restricts it to [0,1] + cbAxisOut.position = opts.x + xpadFrac + thickFrac; - - `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. + // save for other callers to access this axis + component.axis = cbAxisOut; - A promise can be in one of three states: pending, fulfilled, or rejected. + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + cbAxisOut.titleside = opts.titleside; + cbAxisOut.titlex = opts.x + xpadFrac; + cbAxisOut.titley = yBottomFrac + + (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac); + } - 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. + if(opts.line.color && opts.tickmode === 'auto') { + cbAxisOut.tickmode = 'linear'; + cbAxisOut.tick0 = opts.levels.start; + var dtick = opts.levels.size; + // expand if too many contours, so we don't get too many ticks + var autoNtick = _$lib_425.constrain( + (yBottomPx - yTopPx) / 50, 4, 15) + 1, + dtFactor = (zrange[1] - zrange[0]) / + ((opts.nticks || autoNtick) * dtick); + if(dtFactor > 1) { + var dtexp = Math.pow(10, Math.floor( + Math.log(dtFactor) / Math.LN10)); + dtick *= dtexp * _$lib_425.roundUp(dtFactor / dtexp, [2, 5, 10]); + // if the contours are at round multiples, reset tick0 + // so they're still at round multiples. Otherwise, + // keep the first label on the first contour level + if((Math.abs(opts.levels.start) / + opts.levels.size + 1e-6) % 1 < 2e-6) { + cbAxisOut.tick0 = 0; + } + } + cbAxisOut.dtick = dtick; + } - 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. + // set domain after init, because we may want to + // allow it outside [0,1] + cbAxisOut.domain = [ + yBottomFrac + ypadFrac, + yBottomFrac + lenFrac - ypadFrac + ]; + cbAxisOut.setScale(); + // now draw the elements + var container = _$lib_425.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_71.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); - Basic Usage: - ------------ + container.attr('transform', 'translate(' + Math.round(gs.l) + + ',' + Math.round(gs.t) + ')'); + // TODO: this opposite transform is a hack until we make it + // more rational which items get this offset + var titleCont = container.select('.cbtitleunshift') + .attr('transform', 'translate(-' + + Math.round(gs.l) + ',-' + + Math.round(gs.t) + ')'); - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); + cbAxisOut._axislayer = container.select('.cbaxis'); + var titleHeight = 0; + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // draw the title so we know how much room it needs + // when we squish the axis. This one only applies to + // top or bottom titles, not right side. + var x = gs.l + (opts.x + xpadFrac) * gs.w, + fontSize = cbAxisOut.titlefont.size, + y; - // on failure - reject(reason); - }); + if(opts.titleside === 'top') { + y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h + + gs.t + 3 + fontSize * 0.75; + } + else { + y = (1 - (yBottomFrac + ypadFrac)) * gs.h + + gs.t - 3 - fontSize * 0.25; + } + drawTitle(cbAxisOut._id + 'title', { + attributes: {x: x, y: y, 'text-anchor': 'start'} + }); + } - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + function drawAxis() { + if(['top', 'bottom'].indexOf(opts.titleside) !== -1) { + // squish the axis top to make room for the title + var titleGroup = container.select('.cbtitle'), + titleText = titleGroup.select('text'), + titleTrans = + [-opts.outlinewidth / 2, opts.outlinewidth / 2], + mathJaxNode = titleGroup + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + lineSize = 15.6; + if(titleText.node()) { + lineSize = + parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_305; + } + if(mathJaxNode) { + titleHeight = _$drawing_326.bBox(mathJaxNode).height; + if(titleHeight > lineSize) { + // not entirely sure how mathjax is doing + // vertical alignment, but this seems to work. + titleTrans[1] -= (titleHeight - lineSize) / 2; + } + } + else if(titleText.node() && + !titleText.classed(cn.jsPlaceholder)) { + titleHeight = _$drawing_326.bBox(titleText.node()).height; + } + if(titleHeight) { + // buffer btwn colorbar and title + // TODO: configurable + titleHeight += 5; - Advanced Usage: - --------------- + if(opts.titleside === 'top') { + cbAxisOut.domain[1] -= titleHeight / gs.h; + titleTrans[1] *= -1; + } + else { + cbAxisOut.domain[0] += titleHeight / gs.h; + var nlines = _$svg_text_utils_449.lineCount(titleText); + titleTrans[1] += (1 - nlines) * lineSize; + } - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + titleGroup.attr('transform', + 'translate(' + titleTrans + ')'); - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); + cbAxisOut.setScale(); + } + } - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + container.selectAll('.cbfills,.cblines') + .attr('transform', 'translate(0,' + + Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')'); - 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 + ']')); - } - } - }; - }); - } + cbAxisOut._axislayer.attr('transform', 'translate(0,' + + Math.round(-gs.t) + ')'); - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + var fills = container.select('.cbfills') + .selectAll('rect.cbfill') + .data(filllevels); + fills.enter().append('rect') + .classed(cn.cbfill, true) + .style('stroke', 'none'); + fills.exit().remove(); + fills.each(function(d, i) { + var z = [ + (i === 0) ? zrange[0] : + (filllevels[i] + filllevels[i - 1]) / 2, + (i === filllevels.length - 1) ? zrange[1] : + (filllevels[i] + filllevels[i + 1]) / 2 + ] + .map(cbAxisOut.c2p) + .map(Math.round); + + // offset the side adjoining the next rectangle so they + // overlap, to prevent antialiasing gaps + if(i !== filllevels.length - 1) { + z[1] += (z[1] > z[0]) ? 1 : -1; + } + + + // Tinycolor can't handle exponents and + // at this scale, removing it makes no difference. + var colorString = fillcolormap(d).replace('e-', ''), + opaqueColor = _$tinycolor_263(colorString).toHexString(); + + // Colorbar cannot currently support opacities so we + // use an opaque fill even when alpha channels present + _$d3_71.select(this).attr({ + x: xLeft, + width: Math.max(thickPx, 2), + y: _$d3_71.min(z), + height: Math.max(_$d3_71.max(z) - _$d3_71.min(z), 2), + fill: opaqueColor + }); + }); + + var lines = container.select('.cblines') + .selectAll('path.cbline') + .data(opts.line.color && opts.line.width ? + linelevels : []); + lines.enter().append('path') + .classed(cn.cbline, true); + lines.exit().remove(); + lines.each(function(d) { + _$d3_71.select(this) + .attr('d', 'M' + xLeft + ',' + + (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + + 'h' + thickPx) + .call(_$drawing_326.lineGroupStyle, + opts.line.width, linecolormap(d), opts.line.dash); + }); - Unlike callbacks, promises are great composable primitives. + // force full redraw of labels and ticks + cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path') + .remove(); - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON + cbAxisOut._pos = xLeft + thickPx + + (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0); + cbAxisOut.side = 'right'; - return values; - }); - ``` + // separate out axis and title drawing, + // so we don't need such complicated logic in Titles.draw + // if title is on the top or bottom, we've already drawn it + // this title call only handles side=right + return _$lib_425.syncOrAsync([ + function() { + return _$axes_470.doTicks(gd, cbAxisOut, true); + }, + function() { + if(['top', 'bottom'].indexOf(opts.titleside) === -1) { + var fontSize = cbAxisOut.titlefont.size, + y = cbAxisOut._offset + cbAxisOut._length / 2, + x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ? + 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) : + -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0))); - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; + // the 'h' + is a hack to get around the fact that + // convertToTspans rotates any 'y...' class by 90 degrees. + // TODO: find a better way to control this. + drawTitle('h' + cbAxisOut._id + 'title', { + avoid: { + selection: _$d3_71.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), + side: opts.titleside, + offsetLeft: gs.l, + offsetTop: 0, + maxShift: fullLayout.width + }, + attributes: {x: x, y: y, 'text-anchor': 'middle'}, + transform: {rotate: '-90', offset: 0} + }); + } + }]); + } - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise ? initializePromise(this, resolver) : needsNew(); - } -} + function drawTitle(titleClass, titleOpts) { + var trace = getTrace(), + propName; + if(_$registry_514.traceIs(trace, 'markerColorscale')) { + propName = 'marker.colorbar.title'; + } + else propName = 'colorbar.title'; -Promise.all = all; -Promise.race = race; -Promise.resolve = resolve; -Promise.reject = reject; -Promise._setScheduler = setScheduler; -Promise._setAsap = setAsap; -Promise._asap = asap; + var dfltTitleOpts = { + propContainer: cbAxisOut, + propName: propName, + traceIndex: trace.index, + placeholder: fullLayout._dfltTitle.colorbar, + containerGroup: container.select('.cbtitle') + }; -Promise.prototype = { - constructor: Promise, + // this class-to-rotate thing with convertToTspans is + // getting hackier and hackier... delete groups with the + // wrong class (in case earlier the colorbar was drawn on + // a different side, I think?) + var otherClass = titleClass.charAt(0) === 'h' ? + titleClass.substr(1) : ('h' + titleClass); + container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') + .remove(); - /** - 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); + _$titles_394.draw(gd, titleClass, + __extendFlat_305(dfltTitleOpts, titleOpts || {})); } - // 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 positionCB() { + // wait for the axis & title to finish rendering before + // continuing positioning + // TODO: why are we redrawing multiple times now with this? + // I guess autoMargin doesn't like being post-promise? + var innerWidth = thickPx + opts.outlinewidth / 2 + + _$drawing_326.bBox(cbAxisOut._axislayer.node()).width; + titleEl = titleCont.select('text'); + if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { + var mathJaxNode = titleCont + .select('.h' + cbAxisOut._id + 'title-math-group') + .node(), + titleWidth; + if(mathJaxNode && + ['top', 'bottom'].indexOf(opts.titleside) !== -1) { + titleWidth = _$drawing_326.bBox(mathJaxNode).width; + } + else { + // note: the formula below works for all titlesides, + // (except for top/bottom mathjax, above) + // but the weird gs.l is because the titleunshift + // transform gets removed by Drawing.bBox + titleWidth = + _$drawing_326.bBox(titleCont.node()).right - + xLeft - gs.l; + } + innerWidth = Math.max(innerWidth, titleWidth); + } -function polyfill() { - var local = undefined; + var outerwidth = 2 * opts.xpad + innerWidth + + opts.borderwidth + opts.outlinewidth / 2, + outerheight = yBottomPx - yTopPx; - 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'); - } - } + container.select('.cbbg').attr({ + x: xLeft - opts.xpad - + (opts.borderwidth + opts.outlinewidth) / 2, + y: yTopPx - yExtraPx, + width: Math.max(outerwidth, 2), + height: Math.max(outerheight + 2 * yExtraPx, 2) + }) + .call(_$color_301.fill, opts.bgcolor) + .call(_$color_301.stroke, opts.bordercolor) + .style({'stroke-width': opts.borderwidth}); - var P = local.Promise; + container.selectAll('.cboutline').attr({ + x: xLeft, + y: yTopPx + opts.ypad + + (opts.titleside === 'top' ? titleHeight : 0), + width: Math.max(thickPx, 2), + height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) + }) + .call(_$color_301.stroke, opts.outlinecolor) + .style({ + fill: 'None', + 'stroke-width': opts.outlinewidth + }); - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } + // fix positioning for xanchor!='left' + var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) * + outerwidth; + container.attr('transform', + 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); - if (promiseToString === '[object Promise]' && !P.cast) { - return; + // auto margin adjustment + _$plots_506.autoMargin(gd, id, { + x: opts.x, + y: opts.y, + l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), + r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0), + t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0), + b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0) + }); } - } - local.Promise = Promise; -} + var cbDone = _$lib_425.syncOrAsync([ + _$plots_506.previousPromises, + drawAxis, + _$plots_506.previousPromises, + positionCB + ], gd); -polyfill(); -// Strange compat.. -Promise.polyfill = polyfill; -Promise.Promise = Promise; + if(cbDone && cbDone.then) (gd._promises || []).push(cbDone); -return Promise; + // dragging... + if(gd._context.edits.colorbarPosition) { + var t0, + xf, + yf; -}))); -//# sourceMappingURL=es6-promise.map -}).call(this,_$browser_166,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$es6Promise_76 = _$es6Promise_76.exports -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + _$dragelement_323.init({ + element: container.node(), + gd: gd, + prepFn: function() { + t0 = container.attr('transform'); + _$setCursor_445(container); + }, + moveFn: function(dx, dy) { + container.attr('transform', + t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); -'use strict'; + xf = _$dragelement_323.align(xLeftFrac + (dx / gs.w), thickFrac, + 0, 1, opts.xanchor); + yf = _$dragelement_323.align(yBottomFrac - (dy / gs.h), lenFrac, + 0, 1, opts.yanchor); -/** - * All paths are tuned for maximum scalability of the arrowhead, - * ie throughout arrowwidth=0.3..3 the head is joined smoothly - * to the line, with the line coming from the left and ending at (0, 0). - * - * `backoff` is the distance to move the arrowhead and the end of the line, - * in order that the arrowhead points to the desired place, either at - * the tip of the arrow or (in the case of circle or square) - * the center of the symbol. - * - * `noRotate`, if truthy, says that this arrowhead should not rotate with the - * arrow. That's the case for squares, which should always be straight, and - * circles, for which it's irrelevant. - */ + var csr = _$dragelement_323.getCursor(xf, yf, + opts.xanchor, opts.yanchor); + _$setCursor_445(container, csr); + }, + doneFn: function() { + _$setCursor_445(container); -var _$arrow_paths_223 = [ - // no arrow - { - path: '', - backoff: 0 - }, - // wide with flat back - { - path: 'M-2.4,-3V3L0.6,0Z', - backoff: 0.6 - }, - // narrower with flat back - { - path: 'M-3.7,-2.5V2.5L1.3,0Z', - backoff: 1.3 - }, - // barbed - { - path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', - backoff: 1.55 - }, - // wide line-drawn - { - path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', - backoff: 1.6 - }, - // narrower line-drawn - { - path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', - backoff: 2 - }, - // circle - { - path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', - backoff: 0, - noRotate: true - }, - // square - { - path: 'M2,2V-2H-2V2Z', - backoff: 0, - noRotate: true + if(xf !== undefined && yf !== undefined) { + _$registry_514.call('restyle', + gd, + {'colorbar.x': xf, 'colorbar.y': yf}, + getTrace().index + ); + } + } + }); + } + return cbDone; + } + + function getTrace() { + var idNum = id.substr(2), + i, + trace; + for(i = 0; i < gd._fullData.length; i++) { + trace = gd._fullData[i]; + if(trace.uid === idNum) return trace; + } } -]; + + // setter/getters for every item defined in opts + Object.keys(opts).forEach(function(name) { + component[name] = function(v) { + // getter + if(!arguments.length) return opts[name]; + + // setter - for multi-part properties, + // set only the parts that are provided + opts[name] = _$lib_425.isPlainObject(opts[name]) ? + _$lib_425.extendFlat(opts[name], v) : + v; + + return component; + }; + }); + + // or use .options to set multiple options at once via a dictionary + component.options = function(o) { + Object.keys(o).forEach(function(name) { + // in case something random comes through + // that's not an option, ignore it + if(typeof component[name] === 'function') { + component[name](o[name]); + } + }); + return component; + }; + + component._opts = opts; + + return component; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -63356,351 +64457,15 @@ var _$arrow_paths_223 = [ * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$arrow_paths_223 = require('./arrow_paths'); */; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_412 = require('../../plots/cartesian/constants'); */; - - -var _$attributes_224 = { - _isLinkedToArray: 'annotation', - - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, - text: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, - textangle: { - valType: 'angle', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - font: _$font_attributes_434({ - editType: 'calcIfAutorange+arraydraw', - colorEditType: 'arraydraw', - - }), - width: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - height: { - valType: 'number', - min: 1, - dflt: null, - - editType: 'calcIfAutorange+arraydraw', - - }, - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - align: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'center', - - editType: 'arraydraw', - - }, - valign: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'middle', - - editType: 'arraydraw', - - }, - bgcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - borderpad: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - // arrow - showarrow: { - valType: 'boolean', - dflt: true, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - arrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_223.length, - dflt: 1, - - editType: 'arraydraw', - - }, - startarrowhead: { - valType: 'integer', - min: 0, - max: _$arrow_paths_223.length, - dflt: 1, - - editType: 'arraydraw', - - }, - arrowside: { - valType: 'flaglist', - flags: ['end', 'start'], - extras: ['none'], - dflt: 'end', - - editType: 'arraydraw', - - }, - arrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - startarrowsize: { - valType: 'number', - min: 0.3, - dflt: 1, - - editType: 'calcIfAutorange+arraydraw', - - }, - arrowwidth: { - valType: 'number', - min: 0.1, - - editType: 'calcIfAutorange+arraydraw', - - }, - standoff: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - startstandoff: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - ax: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - ay: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - axref: { - valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_412.idRegex.x.toString() - ], - - editType: 'calc', - - }, - ayref: { - valType: 'enumerated', - dflt: 'pixel', - values: [ - 'pixel', - _$constants_412.idRegex.y.toString() - ], - - editType: 'calc', - - }, - // positioning - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_412.idRegex.x.toString() - ], - - editType: 'calc', - - }, - x: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - - }, - xshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_412.idRegex.y.toString() - ], - - editType: 'calc', - - }, - y: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', - - editType: 'calcIfAutorange+arraydraw', - - }, - yshift: { - valType: 'number', - dflt: 0, - - editType: 'calcIfAutorange+arraydraw', - - }, - clicktoshow: { - valType: 'enumerated', - values: [false, 'onoff', 'onout'], - dflt: false, - - editType: 'arraydraw', - - }, - xclick: { - valType: 'any', - - editType: 'arraydraw', - - }, - yclick: { - valType: 'any', - - editType: 'arraydraw', - - }, - hovertext: { - valType: 'string', - - editType: 'arraydraw', - - }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - bordercolor: { - valType: 'color', - - editType: 'arraydraw', - - }, - font: _$font_attributes_434({ - editType: 'arraydraw', - - }), - editType: 'arraydraw' - }, - captureevents: { - valType: 'boolean', - - editType: 'arraydraw', - - }, - editType: 'calc', +'use strict'; - _deprecated: { - ref: { - valType: 'string', - - editType: 'calc', - - } - } +/* + * tiny helper to move the end of the contours a little to prevent + * losing the last contour to rounding errors + */ +var _$endPlus_529 = function endPlus(contours) { + return contours.end + contours.size / 1e6; }; /** @@ -63714,146 +64479,166 @@ var _$attributes_224 = { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$colorscale_316 = require('../../components/colorscale'); */; +/* removed: var _$endPlus_529 = require('./end_plus'); */; -/* removed: var _$color_239 = require('../color'); */; - -/* removed: var _$arrow_paths_223 = require('./arrow_paths'); */; +var _$makeColorMap_531 = function makeColorMap(trace) { + var contours = trace.contours, + start = contours.start, + end = _$endPlus_529(contours), + cs = contours.size || 1, + nc = Math.floor((end - start) / cs) + 1, + extra = contours.coloring === 'lines' ? 0 : 1; -/** - * 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. - */ -var _$drawArrowHead_231 = function drawArrowHead(el3, ends, options) { - var el = el3.node(); - var headStyle = _$arrow_paths_223[options.arrowhead || 0]; - var startHeadStyle = _$arrow_paths_223[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; + if(!isFinite(cs)) { + cs = 1; + nc = 1; + } - var start, end, startRot, endRot; + var scl = trace.colorscale, + len = scl.length; - if(el.nodeName === 'line') { - start = {x: +el3.attr('x1'), y: +el3.attr('y1')}; - end = {x: +el3.attr('x2'), y: +el3.attr('y2')}; + var domain = new Array(len), + range = new Array(len); - var dx = start.x - end.x; - var dy = start.y - end.y; + var si, i; - startRot = Math.atan2(dy, dx); - endRot = startRot + Math.PI; - if(backOff && startBackOff) { - if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) { - hideLine(); - return; - } + if(contours.coloring === 'heatmap') { + if(trace.zauto && trace.autocontour === false) { + trace.zmin = start - cs / 2; + trace.zmax = trace.zmin + nc * cs; } - if(backOff) { - if(backOff * backOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var backOffX = backOff * Math.cos(startRot), - backOffY = backOff * Math.sin(startRot); - - end.x += backOffX; - end.y += backOffY; - el3.attr({x2: end.x, y2: end.y}); + for(i = 0; i < len; i++) { + si = scl[i]; + domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin; + range[i] = si[1]; } - if(startBackOff) { - if(startBackOff * startBackOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var startBackOffX = startBackOff * Math.cos(startRot), - startbackOffY = startBackOff * Math.sin(startRot); + // do the contours extend beyond the colorscale? + // if so, extend the colorscale with constants + var zRange = _$d3_71.extent([trace.zmin, trace.zmax, contours.start, + contours.start + cs * (nc - 1)]), + zmin = zRange[trace.zmin < trace.zmax ? 0 : 1], + zmax = zRange[trace.zmin < trace.zmax ? 1 : 0]; - start.x -= startBackOffX; - start.y -= startbackOffY; - el3.attr({x1: start.x, y1: start.y}); + if(zmin !== trace.zmin) { + domain.splice(0, 0, zmin); + range.splice(0, 0, Range[0]); + } + if(zmax !== trace.zmax) { + domain.push(zmax); + range.push(range[range.length - 1]); } } - 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 - dashArray = ''; + else { + for(i = 0; i < len; i++) { + si = scl[i]; - if(pathlen < backOff + startBackOff) { - hideLine(); - return; + domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start; + range[i] = si[1]; } + } + + return _$colorscale_316.makeColorScaleFunc({ + domain: domain, + range: range, + }, { + noNumericCheck: true + }); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$draw_305 = require('../../components/colorbar/draw'); */; + +/* removed: var _$makeColorMap_531 = require('./make_color_map'); */; +/* removed: var _$endPlus_529 = require('./end_plus'); */; - var start0 = el.getPointAtLength(0); - var dstart = el.getPointAtLength(0.1); +var _$colorbar_525 = function colorbar(gd, cd) { + var trace = cd[0].trace, + cbId = 'cb' + trace.uid; + + gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); + + if(!trace.showscale) { + _$plots_506.autoMargin(gd, cbId); + return; + } + + var cb = _$draw_305(gd, cbId); + cd[0].t.cb = cb; - startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); - start = el.getPointAtLength(Math.min(startBackOff, pathlen)); + var contours = trace.contours, + line = trace.line, + cs = contours.size || 1, + coloring = contours.coloring; - dashArray = '0px,' + startBackOff + 'px,'; + var colorMap = _$makeColorMap_531(trace, {isColorbar: true}); - var end0 = el.getPointAtLength(pathlen); - var dend = el.getPointAtLength(pathlen - 0.1); + if(coloring === 'heatmap') { + cb.filllevels({ + start: trace.zmin, + end: trace.zmax, + size: (trace.zmax - trace.zmin) / 254 + }); + } - endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); - end = el.getPointAtLength(Math.max(0, pathlen - backOff)); + cb.fillcolor((coloring === 'fill' || coloring === 'heatmap') ? colorMap : '') + .line({ + color: coloring === 'lines' ? colorMap : line.color, + width: contours.showlines !== false ? line.width : 0, + dash: line.dash + }) + .levels({ + start: contours.start, + end: _$endPlus_529(contours), + size: cs + }) + .options(trace.colorbar)(); +}; - var shortening = dashArray ? startBackOff + backOff : backOff; - dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - el3.style('stroke-dasharray', dashArray); - } - function hideLine() { el3.style('stroke-dasharray', '0px,100px'); } +'use strict'; - function drawhead(arrowHeadStyle, p, rot, arrowScale) { - if(!arrowHeadStyle.path) return; - if(arrowHeadStyle.noRotate) rot = 0; +/* removed: var _$lib_425 = require('../../lib'); */; - _$d3_68.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_239.rgb(options.arrowcolor), - 'stroke-width': 0 - }); +var _$handleLabelDefaults_530 = function handleLabelDefaults(coerce, layout, lineColor, opts) { + if(!opts) opts = {}; + var showLabels = coerce('contours.showlabels'); + if(showLabels) { + var globalFont = layout.font; + _$lib_425.coerceFont(coerce, 'contours.labelfont', { + family: globalFont.family, + size: globalFont.size, + color: lineColor + }); + coerce('contours.labelformat'); } - if(doStart) drawhead(startHeadStyle, start, startRot, startScale); - if(doEnd) drawhead(headStyle, end, endRot, scale); + if(opts.hasHover !== false) coerce('zhoverformat'); }; /** @@ -63864,704 +64649,1356 @@ var _$drawArrowHead_231 = function drawArrowHead(el3, ends, options) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$handleLabelDefaults_530 = require('./label_defaults'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$fx_281 = require('../fx'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_382 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$drawArrowHead_231 = require('./draw_arrow_head'); */; +/* removed: var _$color_301 = require('../../components/color'); */; +var addOpacity = _$color_301.addOpacity; +var opacity = _$color_301.opacity; -// Annotations are stored in gd.layout.annotations, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one +/* removed: var _$filter_ops_402 = require('../../constants/filter_ops'); */; +var CONSTRAINT_REDUCTION = _$filter_ops_402.CONSTRAINT_REDUCTION; +var __COMPARISON_OPS2_526 = _$filter_ops_402.COMPARISON_OPS2; -var _$draw_230 = { - draw: __draw_230, - drawOne: drawOne, - drawRaw: drawRaw -}; +var _$handleConstraintDefaults_526 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { + var contours = traceOut.contours; + var showLines, lineColor, fillColor; -/* - * draw: draw all annotations without any new modifications - */ -function __draw_230(gd) { - var fullLayout = gd._fullLayout; + var operation = coerce('contours.operation'); + contours._operation = CONSTRAINT_REDUCTION[operation]; - fullLayout._infolayer.selectAll('.annotation').remove(); + handleConstraintValueDefaults(coerce, contours); - for(var i = 0; i < fullLayout.annotations.length; i++) { - if(fullLayout.annotations[i].visible) { - drawOne(gd, i); - } + if(operation === '=') { + showLines = contours.showlines = true; + } + else { + showLines = coerce('contours.showlines'); + fillColor = coerce('fillcolor', addOpacity( + (traceIn.line || {}).color || defaultColor, 0.5 + )); } - return _$plots_444.previousPromises(gd); -} + if(showLines) { + var lineDfltColor = fillColor && opacity(fillColor) ? + addOpacity(traceOut.fillcolor, 1) : + defaultColor; + lineColor = coerce('line.color', lineDfltColor); + coerce('line.width', 2); + coerce('line.dash'); + } -/* - * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications - * - * index (int): the annotation to draw - */ -function drawOne(gd, index) { - var fullLayout = gd._fullLayout; - var options = fullLayout.annotations[index] || {}; - var xa = _$axes_407.getFromId(gd, options.xref); - var ya = _$axes_407.getFromId(gd, options.yref); + coerce('line.smoothing'); - drawRaw(gd, options, index, false, xa, ya); -} + _$handleLabelDefaults_530(coerce, layout, lineColor, opts); +}; -/** - * drawRaw: draw a single annotation, potentially with modifications - * - * @param {DOM element} gd - * @param {object} options : this annotation's fullLayout options - * @param {integer} index : index in 'annotations' container of the annotation to draw - * @param {string} subplotId : id of the annotation's subplot - * - use false for 2d (i.e. cartesian or paper-ref) annotations - * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px - * @param {object | undefined} ya : ... y-axis - */ -function drawRaw(gd, options, index, subplotId, xa, ya) { - var fullLayout = gd._fullLayout; - var gs = gd._fullLayout._size; - var edits = gd._context.edits; +function handleConstraintValueDefaults(coerce, contours) { + var zvalue; - var className; - var annbase; + if(__COMPARISON_OPS2_526.indexOf(contours.operation) === -1) { + // Requires an array of two numbers: + coerce('contours.value', [0, 1]); - if(subplotId) { - className = 'annotation-' + subplotId; - annbase = subplotId + '.annotations[' + index + ']'; + if(!Array.isArray(contours.value)) { + if(_$fastIsnumeric_135(contours.value)) { + zvalue = parseFloat(contours.value); + contours.value = [zvalue, zvalue + 1]; + } + } else if(contours.value.length > 2) { + contours.value = contours.value.slice(2); + } else if(contours.length === 0) { + contours.value = [0, 1]; + } else if(contours.length < 2) { + zvalue = parseFloat(contours.value[0]); + contours.value = [zvalue, zvalue + 1]; + } else { + contours.value = [ + parseFloat(contours.value[0]), + parseFloat(contours.value[1]) + ]; + } } else { - className = 'annotation'; - annbase = 'annotations[' + index + ']'; + // Requires a single scalar: + coerce('contours.value', 0); + + if(!_$fastIsnumeric_135(contours.value)) { + if(Array.isArray(contours.value)) { + contours.value = parseFloat(contours.value[0]); + } else { + contours.value = 0; + } + } } +} - // remove the existing annotation if there is one - fullLayout._infolayer - .selectAll('.' + className + '[data-index="' + index + '"]') - .remove(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 annClipID = 'clip' + fullLayout._uid + '_ann' + index; +'use strict'; - // this annotation is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!options._input || options.visible === false) { - _$d3_68.selectAll('#' + annClipID).remove(); - return; - } +var _$handleContourDefaults_527 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { + var contourStart = coerce2('contours.start'); + var contourEnd = coerce2('contours.end'); + var missingEnd = (contourStart === false) || (contourEnd === false); - // calculated pixel positions - // x & y each will get text, head, and tail as appropriate - var annPosPx = {x: {}, y: {}}, - textangle = +options.textangle || 0; + // normally we only need size if autocontour is off. But contour.calc + // pushes its calculated contour size back to the input trace, so for + // things like restyle that can call supplyDefaults without calc + // after the initial draw, we can just reuse the previous calculation + var contourSize = coerce('contours.size'); + var autoContour; - // create the components - // made a single group to contain all, so opacity can work right - // with border/arrow together this could handle a whole bunch of - // cleanup at this point, but works for now - var annGroup = fullLayout._infolayer.append('g') - .classed(className, true) - .attr('data-index', String(index)) - .style('opacity', options.opacity); + if(missingEnd) autoContour = traceOut.autocontour = true; + else autoContour = coerce('autocontour', false); - // another group for text+background so that they can rotate together - var annTextGroup = annGroup.append('g') - .classed('annotation-text-g', true); + if(autoContour || !contourSize) coerce('ncontours'); +}; - var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; - var textEvents = options.captureevents || edits.annotationText || editTextPosition; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 annTextGroupInner = annTextGroup.append('g') - .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_382, 'default') - .on('click', function() { - gd._dragging = false; - var eventData = { - index: index, - annotation: options._input, - fullAnnotation: options, - event: _$d3_68.event - }; +'use strict'; - if(subplotId) { - eventData.subplotId = subplotId; - } +/* removed: var _$colorScaleDefaults_311 = require('../../components/colorscale/defaults'); */; +/* removed: var _$handleLabelDefaults_530 = require('./label_defaults'); */; - gd.emit('plotly_clickannotation', eventData); - }); - if(options.hovertext) { - annTextGroupInner - .on('mouseover', function() { - var hoverOptions = options.hoverlabel; - var hoverFont = hoverOptions.font; - var bBox = this.getBoundingClientRect(); - var bBoxRef = gd.getBoundingClientRect(); +var _$handleStyleDefaults_533 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { + var coloring = coerce('contours.coloring'); - _$fx_281.loneHover({ - x0: bBox.left - bBoxRef.left, - x1: bBox.right - bBoxRef.left, - y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, - text: options.hovertext, - color: hoverOptions.bgcolor, - borderColor: hoverOptions.bordercolor, - fontFamily: hoverFont.family, - fontSize: hoverFont.size, - fontColor: hoverFont.color - }, { - container: fullLayout._hoverlayer.node(), - outerContainer: fullLayout._paper.node(), - gd: gd - }); - }) - .on('mouseout', function() { - _$fx_281.loneUnhover(fullLayout._hoverlayer.node()); - }); + 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'); } - var borderwidth = options.borderwidth, - borderpad = options.borderpad, - borderfull = borderwidth + borderpad; + if(coloring !== 'none') { + _$colorScaleDefaults_311( + traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} + ); + } - var annTextBG = annTextGroupInner.append('rect') - .attr('class', 'bg') - .style('stroke-width', borderwidth + 'px') - .call(_$color_239.stroke, options.bordercolor) - .call(_$color_239.fill, options.bgcolor); + coerce('line.smoothing'); - var isSizeConstrained = options.width || options.height; + _$handleLabelDefaults_530(coerce, layout, lineColor, opts); +}; - var annTextClip = fullLayout._topclips - .selectAll('#' + annClipID) - .data(isSizeConstrained ? [0] : []); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - annTextClip.enter().append('clipPath') - .classed('annclip', true) - .attr('id', annClipID) - .append('rect'); - annTextClip.exit().remove(); - var font = options.font; +'use strict'; - var annText = annTextGroupInner.append('text') - .classed('annotation-text', true) - .text(options.text); +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_548 = _$lib_425.isArrayOrTypedArray; - function textLayout(s) { - s.call(_$drawing_264.font, font) - .attr({ - 'text-anchor': { - left: 'start', - right: 'end' - }[options.align] || 'middle' - }); +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$has_columns_543 = require('./has_columns'); */; - _$svg_text_utils_386.convertToTspans(s, gd, drawGraphicalElements); - return s; +var _$handleXYZDefaults_548 = 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(_$has_columns_543(traceIn)) { + x = coerce(xName); + y = coerce(yName); + + // column z must be accompanied by xName and yName arrays + if(!x || !y) return 0; } + else { + x = coordDefaults(xName, coerce); + y = coordDefaults(yName, coerce); - function drawGraphicalElements() { - // if the text has *only* a link, make the whole box into a link - var anchor3 = annText.selectAll('a'); - if(anchor3.size() === 1 && anchor3.text() === annText.text()) { - var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ - 'xlink:xlink:href': anchor3.attr('xlink:href'), - 'xlink:xlink:show': anchor3.attr('xlink:show') - }) - .style({cursor: 'pointer'}); + // TODO put z validation elsewhere + if(!isValidZ(z)) return 0; - wholeLink.node().appendChild(annTextBG.node()); - } + coerce('transpose'); + } - var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); - var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = _$drawing_264.bBox( - (hasMathjax ? mathjaxGroup : annText).node()); - var textWidth = anntextBB.width; - var textHeight = anntextBB.height; - var annWidth = options.width || textWidth; - var annHeight = options.height || textHeight; - var outerWidth = Math.round(annWidth + 2 * borderfull); - var outerHeight = Math.round(annHeight + 2 * borderfull); + var handleCalendarDefaults = _$registry_514.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout); + return traceOut.z.length; +}; - // save size in the annotation object for use by autoscale - options._w = annWidth; - options._h = annHeight; +function coordDefaults(coordStr, coerce) { + var coord = coerce(coordStr), + coordType = coord ? + coerce(coordStr + 'type', 'array') : + 'scaled'; - function shiftFraction(v, anchor) { - if(anchor === 'auto') { - if(v < 1 / 3) anchor = 'left'; - else if(v > 2 / 3) anchor = 'right'; - else anchor = 'center'; + if(coordType === 'scaled') { + coerce(coordStr + '0'); + coerce('d' + coordStr); + } + + return coord; +} + +function isValidZ(z) { + var allRowsAreArrays = true, + oneRowIsFilled = false, + hasOneNumber = false, + 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(!__isArrayOrTypedArray_548(zi)) { + allRowsAreArrays = false; + break; + } + if(zi.length > 0) oneRowIsFilled = true; + for(var j = 0; j < zi.length; j++) { + if(_$fastIsnumeric_135(zi[j])) { + hasOneNumber = true; + break; } - 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']; + return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); +} - for(var i = 0; i < letters.length; i++) { - var axLetter = letters[i], - axRef = options[axLetter + 'ref'] || axLetter, - tailRef = options['a' + axLetter + 'ref'], - ax = {x: xa, y: ya}[axLetter], - dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, - // note that these two can be either positive or negative - annSizeFromWidth = outerWidth * Math.cos(dimAngle), - annSizeFromHeight = outerHeight * Math.sin(dimAngle), - // but this one is the positive total size - annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), - anchor = options[axLetter + 'anchor'], - overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), - posPx = annPosPx[axLetter], - basePx, - textPadShift, - alignPosition, - autoAlignFraction, - textShift; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - /* - * calculate the *primary* pixel position - * which is the arrowhead if there is one, - * otherwise the text anchor point - */ - if(ax) { - /* - * hide the annotation if it's pointing outside the visible plot - * as long as the axis isn't autoranged - then we need to draw it - * anyway to get its bounding box. When we're dragging, an axis can - * still look autoranged even though it won't be when the drag finishes. - */ - var posFraction = ax.r2fraction(options[axLetter]); - if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { - if(tailRef === axRef) { - posFraction = ax.r2fraction(options['a' + axLetter]); - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - } - } - else { - annotationIsOffscreen = true; - } - if(annotationIsOffscreen) continue; - } - 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; - } +'use strict'; - // now translate this into pixel positions of head, tail, and text - // as well as paddings for autorange - if(options.showarrow) { - posPx.head = basePx; +/* removed: var _$lib_425 = require('../../lib'); */; - var arrowLength = options['a' + axLetter]; +/* removed: var _$has_columns_543 = require('../heatmap/has_columns'); */; +/* removed: var _$handleXYZDefaults_548 = require('../heatmap/xyz_defaults'); */; +/* removed: var _$handleConstraintDefaults_526 = require('./constraint_defaults'); */; +/* removed: var _$handleContourDefaults_527 = require('./contours_defaults'); */; +/* removed: var _$handleStyleDefaults_533 = require('./style_defaults'); */; +/* removed: var _$attributes_523 = require('./attributes'); */; - // 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; - } +var _$supplyDefaults_528 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_425.coerce(traceIn, traceOut, _$attributes_523, attr, dflt); + } - posPx.text = posPx.tail + textShift; + function coerce2(attr) { + return _$lib_425.coerce2(traceIn, traceOut, _$attributes_523, attr); + } - // 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_363.constrain(posPx.head, 1, maxPx - 1); - } - if(tailRef === 'pixel') { - var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), - 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; - } - } + var len = _$handleXYZDefaults_548(traceIn, traceOut, coerce, layout); + if(!len) { + traceOut.visible = false; + return; + } - 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; - } + coerce('text'); + var isConstraint = (coerce('contours.type') === 'constraint'); + coerce('connectgaps', _$has_columns_543(traceOut)); - posPx.text += overallShift; - textShift += overallShift; - textPadShift += overallShift; + // trace-level showlegend has already been set, but is only allowed if this is a constraint + if(!isConstraint) delete traceOut.showlegend; - // padplus/minus are used by autorange - options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift; - options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift; + if(isConstraint) { + _$handleConstraintDefaults_526(traceIn, traceOut, coerce, layout, defaultColor); + } + else { + _$handleContourDefaults_527(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_533(traceIn, traceOut, coerce, layout); + } +}; - // size/shift are used during dragging - options['_' + axLetter + 'size'] = annSize; - options['_' + axLetter + 'shift'] = textShift; - } +'use strict' + +/* removed: var _$browser_181 = require('glslify') */; + +var _$shaders_144 = { + fragment: _$browser_181(["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: _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 tangent;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 screenShape;\nuniform float lineWidth;\nuniform float pointSize;\n\nvarying vec4 fragColor;\n\nvoid main() {\n fragColor = color;\n\n vec3 vPosition = viewTransform * vec3(position, 1.0);\n vec2 vTangent = normalize(viewTransform * vec3(tangent, 0)).xy;\n vec2 offset = vec2(vTangent.y, -vTangent.x) / screenShape;\n\n gl_Position = vec4(\n vPosition.xy + offset * lineWidth * vPosition.z,\n 0,\n vPosition.z);\n\n gl_PointSize = pointSize;\n}\n"]), + fillVertex: _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\n\nvarying vec4 fragColor;\n\nvoid main() {\n fragColor = color;\n vec3 vPosition = viewTransform * vec3(position, 1.0);\n gl_Position = vec4(vPosition.xy, 0, vPosition.z);\n}\n"]) +} - if(annotationIsOffscreen) { - annTextGroupInner.remove(); - return; - } +"use strict" - var xShift = 0; - var yShift = 0; +function __compileSearch_145(funcName, predicate, reversed, extraArgs, 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[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("") +} - 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); - } +function __compileBoundsSearch_145(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_145("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_145("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() +} - if(hasMathjax) { - mathjaxGroup.select('svg').attr({ - x: borderfull + xShift - 1, - y: borderfull + yShift - }) - .call(_$drawing_264.setClipUrl, isSizeConstrained ? annClipID : null); - } - else { - var texty = borderfull + yShift - anntextBB.top; - var textx = borderfull + xShift - anntextBB.left; +var _$searchBounds_145 = { + ge: __compileBoundsSearch_145(">=", false, "GE"), + gt: __compileBoundsSearch_145(">", false, "GT"), + lt: __compileBoundsSearch_145("<", true, "LT"), + le: __compileBoundsSearch_145("<=", true, "LE"), + eq: __compileBoundsSearch_145("-", true, "EQ", true) +} - annText.call(_$svg_text_utils_386.positionText, textx, texty) - .call(_$drawing_264.setClipUrl, isSizeConstrained ? annClipID : null); - } +'use strict' + +var _$createContour2D_143 = createContour2D + +/* removed: var _$iota_187 = require('iota-array') */; +/* removed: var _$createShader_164 = require('gl-shader') */; +/* removed: var _$createBuffer_140 = require('gl-buffer') */; +/* removed: var _$wrappedNDArrayCtor_201 = require('ndarray') */; +/* removed: var _$surfaceNets_257 = require('surface-nets') */; +/* removed: var _$cdt2d_48 = require('cdt2d') */; +/* removed: var _$cleanPSLG_55 = require('clean-pslg') */; +/* removed: var _$searchBounds_145 = require('binary-search-bounds') */; + +/* removed: var _$shaders_144 = require('./lib/shaders') */; + +function GLContour2D ( + plot, + shader, + fillShader, + positionBuffer, + colorBuffer, + idBuffer, + fillPositionBuffer, + fillColorBuffer) { + this.plot = plot + this.shader = shader + this.fillShader = fillShader + this.positionBuffer = positionBuffer + this.colorBuffer = colorBuffer + this.idBuffer = idBuffer + this.fillPositionBuffer = fillPositionBuffer + this.fillColorBuffer = fillColorBuffer + this.fillVerts = 0 + this.shape = [0, 0] + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + this.numVertices = 0 + this.lineWidth = 1 +} + +var __proto_143 = GLContour2D.prototype + +var WEIGHTS = [ + 1, 0, + 0, 0, + 0, 1, + 1, 0, + 1, 1, + 0, 1 +] + +__proto_143.draw = (function () { + var MATRIX = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + + var SCREEN_SHAPE = [0, 0] + + return function () { + var plot = this.plot + var shader = this.shader + var fillShader = this.fillShader + var bounds = this.bounds + var numVertices = this.numVertices + var fillVerts = this.fillVerts + + var uniforms, attributes + + var gl = plot.gl + var viewBox = plot.viewBox + var dataBox = plot.dataBox + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + SCREEN_SHAPE[0] = viewBox[2] - viewBox[0] + SCREEN_SHAPE[1] = viewBox[3] - viewBox[1] + + if (fillVerts > 0) { + fillShader.bind() + + uniforms = fillShader.uniforms + uniforms.viewTransform = MATRIX + uniforms.screenShape = SCREEN_SHAPE + + attributes = shader.attributes + this.fillPositionBuffer.bind() + attributes.position.pointer() + + this.fillColorBuffer.bind() + attributes.color.pointer(gl.UNSIGNED_BYTE, true) + + gl.drawArrays(gl.TRIANGLES, 0, fillVerts) + } + + if (numVertices > 0) { + shader.bind() + + var lineWidth = this.lineWidth * plot.pixelRatio + + uniforms = shader.uniforms + uniforms.viewTransform = MATRIX + uniforms.screenShape = SCREEN_SHAPE + uniforms.lineWidth = lineWidth + uniforms.pointSize = 1000 + + attributes = shader.attributes + + // Draw lines + this.positionBuffer.bind() + attributes.position.pointer(gl.FLOAT, false, 16, 0) + attributes.tangent.pointer(gl.FLOAT, false, 16, 8) + + this.colorBuffer.bind() + attributes.color.pointer(gl.UNSIGNED_BYTE, true) + + gl.drawArrays(gl.TRIANGLES, 0, numVertices) + + // Draw end caps + uniforms.lineWidth = 0 + uniforms.pointSize = lineWidth + + this.positionBuffer.bind() + attributes.position.pointer(gl.FLOAT, false, 16 * 3, 0) + attributes.tangent.pointer(gl.FLOAT, false, 16 * 3, 8) + + this.colorBuffer.bind() + attributes.color.pointer(gl.UNSIGNED_BYTE, true, 4 * 3, 0) + + gl.drawArrays(gl.POINTS, 0, numVertices / 3) + } + } +})() + +__proto_143.drawPick = (function () { + return function (pickOffset) { + return pickOffset + } +})() + +__proto_143.pick = function (x, y, value) { + return null +} + +function interpolate (array, point) { + var idx = Math.floor(point) + if (idx < 0) { + return array[0] + } else if (idx >= array.length - 1) { + return array[array.length - 1] + } + var t = point - idx + return (1.0 - t) * array[idx] + t * array[idx + 1] +} + +__proto_143.update = function (options) { + options = options || {} + + var shape = options.shape || [0, 0] + + var x = options.x || _$iota_187(shape[0]) + var y = options.y || _$iota_187(shape[1]) + var z = options.z || new Float32Array(shape[0] * shape[1]) + + var levels = options.levels || [] + var levelColors = options.levelColors || [] + + var bounds = this.bounds + var lox = bounds[0] = x[0] + var loy = bounds[1] = y[0] + var hix = bounds[2] = x[x.length - 1] + var hiy = bounds[3] = y[y.length - 1] + + if (lox === hix) { + bounds[2] += 1 + hix += 1 + } + if (loy === hiy) { + bounds[3] += 1 + hiy += 1 + } + + var xs = 1.0 / (hix - lox) + var ys = 1.0 / (hiy - loy) + + this.lineWidth = options.lineWidth || 1 + + var zarray = _$wrappedNDArrayCtor_201(z, shape) + + var positions = [] + var colors = [] + var ids = [] + + var fillCells = [] + var fillPositions = [ + [0, 0], + [shape[0] - 1, 0], + [0, shape[1] - 1], + [shape[0] - 1, shape[1] - 1] + ] + + function intersect (level, x, a, b) { + var d = (b - a) + if (Math.abs(d) < 1e-6) { + return x + } + return Math.floor(x) + Math.max(0.001, Math.min(0.999, (level - a) / d)) + } + + for (var i = 0; i < levels.length; ++i) { + var level = levels[i] + if (i > 0 && level === levels[i - 1]) { + continue + } + var contour = _$surfaceNets_257(zarray, level) + + var c_r = (255 * levelColors[4 * i]) | 0 + var c_g = (255 * levelColors[4 * i + 1]) | 0 + var c_b = (255 * levelColors[4 * i + 2]) | 0 + var c_a = (255 * levelColors[4 * i + 3]) | 0 + + var c_cells = contour.cells + var c_positions = contour.positions + + // Fix boundaries + var in_degree = Array(c_positions.length) + for (var j = 0; j < in_degree.length; ++j) { + in_degree[j] = 0 + } + for (j = 0; j < c_cells.length; ++j) { + var edge = c_cells[j] + in_degree[edge[0]] += 1 + in_degree[edge[1]] += 1 + } + + for (j = 0; j < in_degree.length; ++j) { + var deg = in_degree[j] + if (deg === 0) { + continue + } + var pp = c_positions[j] + in_degree[j] = fillPositions.length + fillPositions.push(pp) + if (deg > 1) { + continue + } + var ppx = pp[0] + var ppy = pp[1] + var z00 = zarray.get(Math.floor(ppx), Math.floor(ppy)) + var z01 = zarray.get(Math.floor(ppx), Math.ceil(ppy)) + var z10 = zarray.get(Math.ceil(ppx), Math.floor(ppy)) + var z11 = zarray.get(Math.ceil(ppx), Math.ceil(ppy)) + var intercept + if (Math.floor(pp[0]) === 0 && + ((z00 <= level) !== (z01 < level))) { + intercept = [0, intersect(level, pp[1], z00, z01)] + } else if (Math.ceil(pp[0]) === shape[0] - 1 && + ((z10 <= level) !== (z11 < level))) { + intercept = [shape[0] - 1, intersect(level, pp[1], z10, z11)] + } else if (Math.floor(pp[1]) === 0 && + ((z00 <= level) !== (z10 < level))) { + intercept = [intersect(level, pp[0], z00, z10), 0] + } else if (Math.ceil(pp[1]) === shape[1] - 1 && + ((z01 <= level) !== (z11 < level))) { + intercept = [intersect(level, pp[0], z01, z11), shape[1] - 1] + } + if (intercept) { + c_cells.push([j, c_positions.length]) + in_degree.push(fillPositions.length) + c_positions.push(intercept) + } + } + + for (j = 0; j < c_cells.length; ++j) { + var e = c_cells[j] + var a = c_positions[e[0]] + var b = c_positions[e[1]] + + fillCells.push([in_degree[e[0]], in_degree[e[1]]]) + + var pointId = Math.round(a[0]) + shape[0] * Math.round(a[1]) + + var ax = interpolate(x, a[0]) + var ay = interpolate(y, a[1]) + var bx = interpolate(x, b[0]) + var by = interpolate(y, b[1]) + + ax = xs * (ax - lox) + ay = ys * (ay - loy) + bx = xs * (bx - lox) + by = ys * (by - loy) + + var dx = ax - bx + var dy = ay - by + + for (var k = 0; k < WEIGHTS.length; k += 2) { + var wx = WEIGHTS[k] + var wix = 1.0 - wx + var wy = 2.0 * WEIGHTS[k + 1] - 1.0 + + positions.push( + wix * ax + wx * bx, wix * ay + wx * by, + wy * dx, wy * dy) + colors.push(c_r, c_g, c_b, c_a) + ids.push(pointId) + } + } + } + + this.positionBuffer.update(new Float32Array(positions)) + this.colorBuffer.update(new Uint8Array(colors)) + this.idBuffer.update(new Uint32Array(ids)) + this.numVertices = ids.length + + var fillColors = options.fillColors + var fillCellColors = [] + var fillCellPositions = [] + var fillVerts = 0 + + if (fillColors) { + _$cleanPSLG_55(fillPositions, fillCells) + var fillMesh = _$cdt2d_48(fillPositions, fillCells, { + delaunay: false + }) + for (i = 0; i < fillMesh.length; ++i) { + var cell = fillMesh[i] + var cx = 0 + var cy = 0 + + for (j = 0; j < 3; ++j) { + var p = fillPositions[cell[j]] + var px = interpolate(x, p[0]) + var py = interpolate(y, p[1]) + cx += p[0] + cy += p[1] + fillCellPositions.push( + xs * (px - lox), + ys * (py - loy)) + } + + // Compute centroid of triangle + cx /= 3 + cy /= 3 + + // Sample height field at triangle centroid + var cxi = Math.floor(cx) + var cyi = Math.floor(cy) + var cxf = cx - cxi + var cyf = cy - cyi + + var c00 = zarray.get(cxi, cyi) + var c01 = zarray.get(cxi, cyi + 1) + var c10 = zarray.get(cxi + 1, cyi) + var c11 = zarray.get(cxi + 1, cyi + 1) + + var zlevel = + (1 - cyf) * ((1 - cxf) * c00 + cxf * c10) + + cyf * ((1 - cxf) * c01 + cxf * c11) + + // Color triangle using centroid data + var l = _$searchBounds_145.le(levels, zlevel) + 1 + var cr = (255 * fillColors[4 * l + 0]) | 0 + var cg = (255 * fillColors[4 * l + 1]) | 0 + var cb = (255 * fillColors[4 * l + 2]) | 0 + var ca = (255 * fillColors[4 * l + 3]) | 0 + + fillCellColors.push( + cr, cg, cb, ca, + cr, cg, cb, ca, + cr, cg, cb, ca) + + fillVerts += 3 + } + + this.fillPositionBuffer.update(new Float32Array(fillCellPositions)) + this.fillColorBuffer.update(new Uint8Array(fillCellColors)) + + this.fillVerts = fillVerts + } +} + +__proto_143.dispose = function () { + this.plot.removeObject(this) +} + +function createContour2D (plot, options) { + var gl = plot.gl + + var shader = _$createShader_164(gl, _$shaders_144.vertex, _$shaders_144.fragment) + var fillShader = _$createShader_164(gl, _$shaders_144.fillVertex, _$shaders_144.fragment) + + var positionBuffer = _$createBuffer_140(gl) + var colorBuffer = _$createBuffer_140(gl) + var idBuffer = _$createBuffer_140(gl) + + var fillPositionBuffer = _$createBuffer_140(gl) + var fillColorBuffer = _$createBuffer_140(gl) + + var contours = new GLContour2D( + plot, + shader, + fillShader, + positionBuffer, + colorBuffer, + idBuffer, + fillPositionBuffer, + fillColorBuffer) + + contours.update(options) + plot.addObject(contours) + + return contours +} - annTextClip.select('rect').call(_$drawing_264.setRect, borderfull, borderfull, - annWidth, annHeight); +'use strict' + +/* removed: var _$browser_181 = require('glslify') */; + +var _$shaders_149 = { + fragment: _$browser_181(["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: _$browser_181(["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: _$browser_181(["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: _$browser_181(["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"]) +} - annTextBG.call(_$drawing_264.setRect, borderwidth / 2, borderwidth / 2, - outerWidth - borderwidth, outerHeight - borderwidth); +"use strict" - annTextGroupInner.call(_$drawing_264.setTranslate, - Math.round(annPosPx.x.text - outerWidth / 2), - Math.round(annPosPx.y.text - outerHeight / 2)); +function __compileSearch_150(funcName, predicate, reversed, extraArgs, 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[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("") +} - /* - * 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 + ')'}); +function __compileBoundsSearch_150(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_150("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_150("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() +} - /* - * 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 _$searchBounds_150 = { + ge: __compileBoundsSearch_150(">=", false, "GE"), + gt: __compileBoundsSearch_150(">", false, "GT"), + lt: __compileBoundsSearch_150("<", true, "LT"), + le: __compileBoundsSearch_150("<=", true, "LE"), + eq: __compileBoundsSearch_150("-", true, "EQ", true) +} - var headX = annPosPx.x.head, - headY = annPosPx.y.head, - tailX = annPosPx.x.tail + dx, - tailY = annPosPx.y.tail + dy, - textX = annPosPx.x.text + dx, - textY = annPosPx.y.text + dy, +'use strict' + +var _$createHeatmap2D_148 = createHeatmap2D + +/* removed: var _$searchBounds_150 = require('binary-search-bounds') */; +/* removed: var _$iota_187 = require('iota-array') */; +/* removed: var _$pool_269 = require('typedarray-pool') */; +/* removed: var _$createShader_164 = require('gl-shader') */; +/* removed: var _$createBuffer_140 = require('gl-buffer') */; + +/* removed: var _$shaders_149 = require('./lib/shaders') */; + +function GLHeatmap2D ( + plot, + shader, + pickShader, + positionBuffer, + weightBuffer, + colorBuffer, + idBuffer) { + this.plot = plot + this.shader = shader + this.pickShader = pickShader + this.positionBuffer = positionBuffer + this.weightBuffer = weightBuffer + this.colorBuffer = colorBuffer + this.idBuffer = idBuffer + this.xData = [] + this.yData = [] + this.shape = [0, 0] + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + this.pickOffset = 0 +} + +var __proto_148 = GLHeatmap2D.prototype + +var __WEIGHTS_148 = [ + 0, 0, + 1, 0, + 0, 1, + 1, 0, + 1, 1, + 0, 1 +] + +__proto_148.draw = (function () { + var MATRIX = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + + return function () { + var plot = this.plot + var shader = this.shader + var bounds = this.bounds + var numVertices = this.numVertices + + if (numVertices <= 0) { + return + } + + var gl = plot.gl + var dataBox = plot.dataBox + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + shader.bind() + + var uniforms = shader.uniforms + uniforms.viewTransform = MATRIX + + uniforms.shape = this.shape + + var attributes = shader.attributes + this.positionBuffer.bind() + attributes.position.pointer() + + this.weightBuffer.bind() + attributes.weight.pointer(gl.UNSIGNED_BYTE, false) + + this.colorBuffer.bind() + attributes.color.pointer(gl.UNSIGNED_BYTE, true) + + gl.drawArrays(gl.TRIANGLES, 0, numVertices) + } +})() + +__proto_148.drawPick = (function () { + var MATRIX = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + + var PICK_VECTOR = [0, 0, 0, 0] + + return function (pickOffset) { + var plot = this.plot + var shader = this.pickShader + var bounds = this.bounds + var numVertices = this.numVertices + + if (numVertices <= 0) { + return + } + + var gl = plot.gl + var dataBox = plot.dataBox + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + for (var i = 0; i < 4; ++i) { + PICK_VECTOR[i] = (pickOffset >> (i * 8)) & 0xff + } + + this.pickOffset = pickOffset + + shader.bind() + + var uniforms = shader.uniforms + uniforms.viewTransform = MATRIX + uniforms.pickOffset = PICK_VECTOR + uniforms.shape = this.shape + + var attributes = shader.attributes + this.positionBuffer.bind() + attributes.position.pointer() + + this.weightBuffer.bind() + attributes.weight.pointer(gl.UNSIGNED_BYTE, false) + + this.idBuffer.bind() + attributes.pickId.pointer(gl.UNSIGNED_BYTE, false) + + gl.drawArrays(gl.TRIANGLES, 0, numVertices) + + return pickOffset + this.shape[0] * this.shape[1] + } +})() + +__proto_148.pick = function (x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.shape[0] * this.shape[1] + if (value < pickOffset || value >= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var xData = this.xData + var yData = this.yData + return { + object: this, + pointId: pointId, + dataCoord: [ + xData[pointId % this.shape[0]], + yData[(pointId / this.shape[0]) | 0]] + } +} + +__proto_148.update = function (options) { + options = options || {} + + var shape = options.shape || [0, 0] + + var x = options.x || _$iota_187(shape[0]) + var y = options.y || _$iota_187(shape[1]) + var z = options.z || new Float32Array(shape[0] * shape[1]) + + this.xData = x + this.yData = y + + var colorLevels = options.colorLevels || [0] + var colorValues = options.colorValues || [0, 0, 0, 1] + var colorCount = colorLevels.length + + var bounds = this.bounds + var lox = bounds[0] = x[0] + var loy = bounds[1] = y[0] + var hix = bounds[2] = x[x.length - 1] + var hiy = bounds[3] = y[y.length - 1] + + var xs = 1.0 / (hix - lox) + var ys = 1.0 / (hiy - loy) + + var numX = shape[0] + var numY = shape[1] + + this.shape = [numX, numY] + + var numVerts = (numX - 1) * (numY - 1) * (__WEIGHTS_148.length >>> 1) + + this.numVertices = numVerts + + var colors = _$pool_269.mallocUint8(numVerts * 4) + var positions = _$pool_269.mallocFloat32(numVerts * 2) + var weights = _$pool_269.mallocUint8 (numVerts * 2) + var ids = _$pool_269.mallocUint32(numVerts) + + var ptr = 0 + + for (var j = 0; j < numY - 1; ++j) { + var yc0 = ys * (y[j] - loy) + var yc1 = ys * (y[j + 1] - loy) + for (var i = 0; i < numX - 1; ++i) { + var xc0 = xs * (x[i] - lox) + var xc1 = xs * (x[i + 1] - lox) + + for (var dd = 0; dd < __WEIGHTS_148.length; dd += 2) { + var dx = __WEIGHTS_148[dd] + var dy = __WEIGHTS_148[dd + 1] + var offset = (j + dy) * numX + (i + dx) + var zc = z[offset] + var colorIdx = _$searchBounds_150.le(colorLevels, zc) + var r, g, b, a + if (colorIdx < 0) { + r = colorValues[0] + g = colorValues[1] + b = colorValues[2] + a = colorValues[3] + } else if (colorIdx === colorCount - 1) { + r = colorValues[4 * colorCount - 4] + g = colorValues[4 * colorCount - 3] + b = colorValues[4 * colorCount - 2] + a = colorValues[4 * colorCount - 1] + } else { + var t = (zc - colorLevels[colorIdx]) / + (colorLevels[colorIdx + 1] - colorLevels[colorIdx]) + var ti = 1.0 - t + var i0 = 4 * colorIdx + var i1 = 4 * (colorIdx + 1) + r = ti * colorValues[i0] + t * colorValues[i1] + g = ti * colorValues[i0 + 1] + t * colorValues[i1 + 1] + b = ti * colorValues[i0 + 2] + t * colorValues[i1 + 2] + a = ti * colorValues[i0 + 3] + t * colorValues[i1 + 3] + } + + colors[4 * ptr] = 255 * r + colors[4 * ptr + 1] = 255 * g + colors[4 * ptr + 2] = 255 * b + colors[4 * ptr + 3] = 255 * a + + positions[2*ptr] = xc0*.5 + xc1*.5; + positions[2*ptr+1] = yc0*.5 + yc1*.5; + + weights[2*ptr] = dx; + weights[2*ptr+1] = dy; + + ids[ptr] = j * numX + i + + ptr += 1 + } + } + } + + this.positionBuffer.update(positions) + this.weightBuffer.update(weights) + this.colorBuffer.update(colors) + this.idBuffer.update(ids) + + _$pool_269.free(positions) + _$pool_269.free(colors) + _$pool_269.free(weights) + _$pool_269.free(ids) +} + +__proto_148.dispose = function () { + this.shader.dispose() + this.pickShader.dispose() + this.positionBuffer.dispose() + this.weightBuffer.dispose() + this.colorBuffer.dispose() + this.idBuffer.dispose() + this.plot.removeObject(this) +} + +function createHeatmap2D (plot, options) { + var gl = plot.gl + + var shader = _$createShader_164(gl, _$shaders_149.vertex, _$shaders_149.fragment) + var pickShader = _$createShader_164(gl, _$shaders_149.pickVertex, _$shaders_149.pickFragment) + + var positionBuffer = _$createBuffer_140(gl) + var weightBuffer = _$createBuffer_140(gl) + var colorBuffer = _$createBuffer_140(gl) + var idBuffer = _$createBuffer_140(gl) + + var heatmap = new GLHeatmap2D( + plot, + shader, + pickShader, + positionBuffer, + weightBuffer, + colorBuffer, + idBuffer) + + heatmap.update(options) + plot.addObject(heatmap) + + return heatmap +} - // find the edge of the text box, where we'll start the arrow: - // create transform matrix to rotate the text box corners - transform = _$lib_363.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_363.apply2DTransform(transform), - applyTransform2 = _$lib_363.apply2DTransform2(transform), +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // calculate and transform bounding box - width = +annTextBG.attr('width'), - height = +annTextBG.attr('height'), - xLeft = textX - 0.5 * width, - xRight = xLeft + width, - yTop = textY - 0.5 * height, - yBottom = yTop + height, - 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_363.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; - } +'use strict'; - edges.forEach(function(x) { - var p = _$lib_363.segmentsIntersect(tailX, tailY, headX, headY, - x[0], x[1], x[2], x[3]); - if(p) { - tailX = p.x; - tailY = p.y; - } - }); +/* removed: var _$createContour2D_143 = require('gl-contour2d'); */; +/* removed: var _$createHeatmap2D_148 = require('gl-heatmap2d'); */; - var strokewidth = options.arrowwidth, - arrowColor = options.arrowcolor, - arrowSide = options.arrowside; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$makeColorMap_531 = require('../contour/make_color_map'); */; +/* removed: var _$str2RgbaArray_448 = require('../../lib/str2rgbarray'); */; - var arrowGroup = annGroup.append('g') - .style({opacity: _$color_239.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_239.stroke, _$color_239.rgb(arrowColor)); +function Contour(scene, uid) { + this.scene = scene; + this.uid = uid; + this.type = 'contourgl'; - _$drawArrowHead_231(arrow, arrowSide, options); + this.name = ''; + this.hoverinfo = 'all'; - // 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) - .attr({ - d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), - transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' - }) - .style('stroke-width', (strokewidth + 6) + 'px') - .call(_$color_239.stroke, 'rgba(0,0,0,0)') - .call(_$color_239.fill, 'rgba(0,0,0,0)'); + this.xData = []; + this.yData = []; + this.zData = []; + this.textLabels = []; - var update, - annx0, - anny0; + this.idToIndex = []; + this.bounds = [0, 0, 0, 0]; - // dragger for the arrow & head: translates the whole thing - // (head/tail/text) all together - _$dragelement_261.init({ - element: arrowDrag.node(), - gd: gd, - prepFn: function() { - var pos = _$drawing_264.getTranslate(annTextGroupInner); + this.contourOptions = { + z: new Float32Array(0), + x: [], + y: [], + shape: [0, 0], + levels: [0], + levelColors: [0, 0, 0, 1], + lineWidth: 1 + }; + this.contour = _$createContour2D_143(scene.glplot, this.contourOptions); + this.contour._trace = this; - annx0 = pos.x; - anny0 = pos.y; - update = {}; - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } - }, - moveFn: function(dx, dy) { - var annxy0 = applyTransform(annx0, anny0), - xcenter = annxy0[0] + dx, - ycenter = annxy0[1] + dy; - annTextGroupInner.call(_$drawing_264.setTranslate, xcenter, ycenter); + this.heatmapOptions = { + z: new Float32Array(0), + x: [], + y: [], + shape: [0, 0], + colorLevels: [0], + colorValues: [0, 0, 0, 0] + }; + this.heatmap = _$createHeatmap2D_148(scene.glplot, this.heatmapOptions); + this.heatmap._trace = this; +} - update[annbase + '.x'] = xa ? - xa.p2r(xa.r2p(options.x) + dx) : - (options.x + (dx / gs.w)); - update[annbase + '.y'] = ya ? - ya.p2r(ya.r2p(options.y) + dy) : - (options.y - (dy / gs.h)); +var __proto_534 = Contour.prototype; - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } +__proto_534.handlePick = function(pickResult) { + var options = this.heatmapOptions, + shape = options.shape, + index = pickResult.pointId, + xIndex = index % shape[0], + yIndex = Math.floor(index / shape[0]), + zIndex = index; - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } + return { + trace: this, + dataCoord: pickResult.dataCoord, + traceCoord: [ + options.x[xIndex], + options.y[yIndex], + options.z[zIndex] + ], + textLabel: this.textLabels[index], + name: this.name, + pointIndex: [yIndex, xIndex], + hoverinfo: this.hoverinfo + }; +}; - arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); - annTextGroup.attr({ - transform: 'rotate(' + textangle + ',' + - xcenter + ',' + ycenter + ')' - }); - }, - doneFn: function() { - _$registry_451.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } - }; +__proto_534.update = function(fullTrace, calcTrace) { + var calcPt = calcTrace[0]; - if(options.showarrow) drawArrow(0, 0); + this.index = fullTrace.index; + this.name = fullTrace.name; + this.hoverinfo = fullTrace.hoverinfo; - // user dragging the annotation (text, not arrow) - if(editTextPosition) { - var update, - baseTextTransform; + // convert z from 2D -> 1D + var z = calcPt.z, + rowLen = z[0].length, + colLen = z.length, + colorOptions; - // dragger for the textbox: if there's an arrow, just drag the - // textbox and tail, leave the head untouched - _$dragelement_261.init({ - element: annTextGroupInner.node(), - gd: gd, - prepFn: function() { - baseTextTransform = annTextGroup.attr('transform'); - update = {}; - }, - moveFn: function(dx, dy) { - var csr = 'pointer'; - if(options.showarrow) { - if(options.axref === options.xref) { - update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); - } else { - update[annbase + '.ax'] = options.ax + dx; - } + this.contourOptions.z = flattenZ(z, rowLen, colLen); + this.heatmapOptions.z = [].concat.apply([], z); - if(options.ayref === options.yref) { - update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); - } else { - update[annbase + '.ay'] = options.ay + dy; - } + this.contourOptions.shape = this.heatmapOptions.shape = [rowLen, colLen]; - drawArrow(dx, dy); - } - else if(!subplotId) { - if(xa) { - update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); + this.contourOptions.x = this.heatmapOptions.x = calcPt.x; + this.contourOptions.y = this.heatmapOptions.y = calcPt.y; - } else { - var widthFraction = options._xsize / gs.w, - xLeft = options.x + (options._xshift - options.xshift) / gs.w - - widthFraction / 2; + // pass on fill information + if(fullTrace.contours.coloring === 'fill') { + colorOptions = convertColorScale(fullTrace, {fill: true}); + this.contourOptions.levels = colorOptions.levels.slice(1); + // though gl-contour2d automatically defaults to a transparent layer for the last + // band color, it's set manually here in case the gl-contour2 API changes + this.contourOptions.fillColors = colorOptions.levelColors; + this.contourOptions.levelColors = [].concat.apply([], this.contourOptions.levels.map(function() { + return [0.25, 0.25, 0.25, 1.0]; + })); + } else { + colorOptions = convertColorScale(fullTrace, {fill: false}); + this.contourOptions.levels = colorOptions.levels; + this.contourOptions.levelColors = colorOptions.levelColors; + } - update[annbase + '.x'] = _$dragelement_261.align(xLeft + dx / gs.w, - widthFraction, 0, 1, options.xanchor); - } + // convert text from 2D -> 1D + this.textLabels = [].concat.apply([], fullTrace.text); - if(ya) { - update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); - } else { - var heightFraction = options._ysize / gs.h, - yBottom = options.y - (options._yshift + options.yshift) / gs.h - - heightFraction / 2; + this.contour.update(this.contourOptions); + this.heatmap.update(this.heatmapOptions); - update[annbase + '.y'] = _$dragelement_261.align(yBottom - dy / gs.h, - heightFraction, 0, 1, options.yanchor); - } - if(!xa || !ya) { - csr = _$dragelement_261.getCursor( - xa ? 0.5 : update[annbase + '.x'], - ya ? 0.5 : update[annbase + '.y'], - options.xanchor, options.yanchor - ); - } - } - else return; + // expand axes + _$axes_470.expand(this.scene.xaxis, calcPt.x); + _$axes_470.expand(this.scene.yaxis, calcPt.y); +}; - annTextGroup.attr({ - transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform - }); +__proto_534.dispose = function() { + this.contour.dispose(); + this.heatmap.dispose(); +}; - _$setCursor_382(annTextGroupInner, csr); - }, - doneFn: function() { - _$setCursor_382(annTextGroupInner); - _$registry_451.call('relayout', gd, update); - var notesBox = document.querySelector('.js-notes-box-panel'); - if(notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); +function flattenZ(zIn, rowLen, colLen) { + var zOut = new Float32Array(rowLen * colLen); + var pt = 0; + + for(var i = 0; i < rowLen; i++) { + for(var j = 0; j < colLen; j++) { + zOut[pt++] = zIn[j][i]; } } - if(edits.annotationText) { - annText.call(_$svg_text_utils_386.makeEditable, {delegate: annTextGroupInner, gd: gd}) - .call(textLayout) - .on('edit', function(_text) { - options.text = _text; - this.call(textLayout); + return zOut; +} - var update = {}; - update[annbase + '.text'] = options.text; +function convertColorScale(fullTrace, options) { + var contours = fullTrace.contours, + start = contours.start, + end = contours.end, + cs = contours.size || 1, + fill = options.fill; - if(xa && xa.autorange) { - update[xa._name + '.autorange'] = true; - } - if(ya && ya.autorange) { - update[ya._name + '.autorange'] = true; - } + var colorMap = _$makeColorMap_531(fullTrace); - _$registry_451.call('relayout', gd, update); - }); + var N = Math.floor((end - start) / cs) + (fill ? 2 : 1), // for K thresholds (contour linees) there are K+1 areas + levels = new Array(N), + levelColors = new Array(4 * N); + + for(var i = 0; i < N; i++) { + var level = levels[i] = start + cs * (i) - (fill ? cs / 2 : 0); // in case of fill, use band midpoint + var color = _$str2RgbaArray_448(colorMap(level)); + + for(var j = 0; j < 4; j++) { + levelColors[(4 * i) + j] = color[j]; + } } - else annText.call(textLayout); + + return { + levels: levels, + levelColors: levelColors + }; } +function createContour(scene, fullTrace, calcTrace) { + var plot = new Contour(scene, fullTrace.uid); + plot.update(fullTrace, calcTrace); + + return plot; +} + +var _$createContour_534 = createContour; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -64573,105 +66010,26 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; +var __overrideAll_535 = _$edit_types_455.overrideAll; -var __draw_225 = _$draw_230.draw; - - -var _$calcAutorange_225 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - annotationList = _$lib_363.filterVisible(fullLayout.annotations); +var ContourGl = {}; - if(!annotationList.length || !gd._fullData.length) return; +ContourGl.attributes = __overrideAll_535(_$attributes_523, 'calc', 'nested'); +ContourGl.supplyDefaults = _$supplyDefaults_528; +ContourGl.colorbar = _$colorbar_525; - var annotationAxes = {}; - annotationList.forEach(function(ann) { - annotationAxes[ann.xref] = 1; - annotationAxes[ann.yref] = 1; - }); +ContourGl.calc = _$calc_524; +ContourGl.plot = _$createContour_534; - for(var axId in annotationAxes) { - var ax = _$axes_407.getFromId(gd, axId); - if(ax && ax.autorange) { - return _$lib_363.syncOrAsync([ - __draw_225, - annAutorange - ], gd); - } - } +ContourGl.moduleType = 'trace'; +ContourGl.name = 'contourgl'; +ContourGl.basePlotModule = _$gl2d_501; +ContourGl.categories = ['gl', 'gl2d', '2dMap']; +ContourGl.meta = { + }; -function annAutorange(gd) { - var fullLayout = gd._fullLayout; - - // find the bounding boxes for each of these annotations' - // relative to their anchor points - // use the arrow and the text bg rectangle, - // as the whole anno may include hidden text in its bbox - _$lib_363.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_407.getFromId(gd, ann.xref), - ya = _$axes_407.getFromId(gd, ann.yref), - headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, - startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - - var headPlus, headMinus, startHeadPlus, startHeadMinus; - - if(xa && xa.autorange) { - headPlus = headSize + ann.xshift; - headMinus = headSize - ann.xshift; - startHeadPlus = startHeadSize + ann.xshift; - startHeadMinus = startHeadSize - ann.xshift; - - if(ann.axref === ann.xref) { - // expand for the arrowhead (padded by arrowhead) - _$axes_407.expand(xa, [xa.r2c(ann.x)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - // again for the textbox (padded by textbox) - _$axes_407.expand(xa, [xa.r2c(ann.ax)], { - ppadplus: Math.max(ann._xpadplus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, startHeadMinus) - }); - } - else { - startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; - startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_407.expand(xa, [xa.r2c(ann.x)], { - ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) - }); - } - } - - if(ya && ya.autorange) { - headPlus = headSize - ann.yshift; - headMinus = headSize + ann.yshift; - startHeadPlus = startHeadSize - ann.yshift; - startHeadMinus = startHeadSize + ann.yshift; - - if(ann.ayref === ann.yref) { - _$axes_407.expand(ya, [ya.r2c(ann.y)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - _$axes_407.expand(ya, [ya.r2c(ann.ay)], { - ppadplus: Math.max(ann._ypadplus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, startHeadMinus) - }); - } - else { - startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; - startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_407.expand(ya, [ya.r2c(ann.y)], { - ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), - ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) - }); - } - } - }); -} +var _$ContourGl_535 = ContourGl; /** * Copyright 2012-2018, Plotly, Inc. @@ -64683,887 +66041,1356 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; - -var _$click_226 = { - 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), - onSet = toggleSets.on, - offSet = toggleSets.off.concat(toggleSets.explicitOff), - update = {}, - i; - - if(!(onSet.length || offSet.length)) return; +var _$contourgl_3 = _$ContourGl_535; - for(i = 0; i < onSet.length; i++) { - update['annotations[' + onSet[i] + '].visible'] = true; - } +var _$plotcss_1 = {}; +'use strict'; - for(i = 0; i < offSet.length; i++) { - update['annotations[' + offSet[i] + '].visible'] = false; - } +/* removed: var _$lib_425 = require('../src/lib'); */; +var rules = { + "X,X div": "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 .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);", + "X .modebar--hover": "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": "opacity:1;", + "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", + "X .modebar-group:first-child": "margin-left:0px;", + "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;", + "X .modebar-btn svg": "position:relative;top:2px;", + "X .modebar-btn path": "fill:rgba(0,31,95,0.3);", + "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);", + "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;", + "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;", + "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 .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;" +}; - return _$registry_451.call('update', gd, {}, update); +for(var selector in rules) { + var fullSelector = selector.replace(/^,/,' ,') + .replace(/X/g, '.js-plotly-plot .plotly') + .replace(/Y/g, '.plotly-notifier'); + _$lib_425.addStyleRule(fullSelector, rules[selector]); } -/* - * 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, - onSet = [], - offSet = [], - explicitOffSet = [], - 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; - } - } +'use strict'; - if(j === hoverLen) { - // no match - only turn this annotation OFF, and only if - // showmode is 'onout' - if(anni.visible && showMode === 'onout') offSet.push(i); - } - } +var _$ploticon_2 = { + 'undo': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'home': { + 'width': 928.6, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'camera-retro': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoombox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'pan': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoom_plus': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'zoom_minus': { + 'width': 1000, + 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z', + 'ascent': 850, + 'descent': -150 + }, + 'autoscale': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'tooltip_basic': { + 'width': 1500, + 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z', + 'ascent': 850, + 'descent': -150 + }, + 'tooltip_compare': { + 'width': 1125, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'plotlylogo': { + 'width': 1542, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'z-axis': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + '3d_rotate': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'camera': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'movie': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'question': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'disk': { + 'width': 857.1, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'lasso': { + 'width': 1031, + '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', + 'ascent': 850, + 'descent': -150 + }, + 'selectbox': { + 'width': 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', + 'ascent': 850, + 'descent': -150 + }, + 'spikeline': { + 'width': 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', + 'ascent': 850, + 'descent': -150 } +}; - return {on: onSet, off: offSet, explicitOff: explicitOffSet}; +var _$es6Promise_124 = { exports: {} }; +(function (process,global){ +/*! + * @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) { + typeof _$es6Promise_124.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_124.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; } -// to handle log axes until v2 -function clickData2r(d, ax) { - return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); +function isFunction(x) { + return typeof x === 'function'; } -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} +var isArray = _isArray; -'use strict'; +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_388 = require('../../lib/to_log_range'); */; +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(); + } + } +}; -/* - * 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. - */ -var _$convertCoords_228 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} - var toLog = (newType === 'log') && (ax.type === 'linear'), - fromLog = (newType === 'linear') && (ax.type === 'log'); +function setAsap(asapFn) { + asap = asapFn; +} - if(!(toLog || fromLog)) return; +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]'; - var annotations = gd._fullLayout.annotations, - axLetter = ax._id.charAt(0), - ann, - attrPrefix; +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; - function convert(attr) { - var currentVal = ann[attr], - newVal = null; +// 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); + }; +} - if(toLog) newVal = _$toLogRange_388(currentVal, ax.range); - else newVal = Math.pow(10, currentVal); +// vertx +function useVertxTimer() { + return function () { + vertxNext(flush); + }; +} - // if conversion failed, delete the value so it gets a default value - if(!_$fastIsnumeric_78(newVal)) newVal = null; +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); - doExtra(attrPrefix + attr, newVal); - } + return function () { + node.data = iterations = ++iterations % 2; + }; +} - for(var i = 0; i < annotations.length; i++) { - ann = annotations[i]; - attrPrefix = 'annotations[' + i + '].'; +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} - if(ann[axLetter + 'ref'] === ax._id) convert(axLetter); - if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter); - } -}; +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); + }; +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; -'use strict'; + callback(arg); -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$color_239 = require('../color'); */; + queue[i] = undefined; + queue[i + 1] = undefined; + } -// defaults common to 'annotations' and 'annotations3d' -var _$handleAnnotationCommonDefaults_227 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { - coerce('opacity'); - var bgColor = coerce('bgcolor'); + len = 0; +} - var borderColor = coerce('bordercolor'); - var borderOpacity = _$color_239.opacity(borderColor); +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} - coerce('borderpad'); +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 && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} - var borderWidth = coerce('borderwidth'); - var showArrow = coerce('showarrow'); +function then(onFulfillment, onRejection) { + var _arguments = arguments; - coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); - coerce('textangle'); - _$lib_363.coerceFont(coerce, 'font', fullLayout.font); + var parent = this; - coerce('width'); - coerce('align'); + var child = new this.constructor(noop); - var h = coerce('height'); - if(h) coerce('valign'); + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } - if(showArrow) { - var arrowside = coerce('arrowside'); - var arrowhead; - var arrowsize; + var _state = parent._state; - if(arrowside.indexOf('end') !== -1) { - arrowhead = coerce('arrowhead'); - arrowsize = coerce('arrowsize'); - } + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } - if(arrowside.indexOf('start') !== -1) { - coerce('startarrowhead', arrowhead); - coerce('startarrowsize', arrowsize); - } - coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_239.defaultLine); - coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); - coerce('standoff'); - coerce('startstandoff'); + return child; +} - } +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: - var hoverText = coerce('hovertext'); - var globalHoverLabel = fullLayout.hoverlabel || {}; + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); - if(hoverText) { - var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || - (_$color_239.opacity(bgColor) ? _$color_239.rgb(bgColor) : _$color_239.defaultLine) - ); + promise.then(function(value){ + // value === 1 + }); + ``` - var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || - _$color_239.contrast(hoverBG) - ); + Instead of writing the above, your code now simply becomes the following: - _$lib_363.coerceFont(coerce, 'hoverlabel.font', { - family: globalHoverLabel.font.family, - size: globalHoverLabel.font.size, - color: globalHoverLabel.font.color || hoverBorder - }); - } + ```javascript + let promise = Promise.resolve(1); - coerce('captureevents', !!hoverText); -}; + promise.then(function(value){ + // value === 1 + }); + ``` -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. + @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; + } -'use strict'; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleAnnotationCommonDefaults_227 = require('./common_defaults'); */; -/* removed: var _$attributes_224 = require('./attributes'); */; - - -var _$handleAnnotationDefaults_222 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} - function coerce(attr, dflt) { - return _$lib_363.coerce(annIn, annOut, _$attributes_224, attr, dflt); - } +var PROMISE_ID = Math.random().toString(36).substring(16); - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - var clickToShow = coerce('clicktoshow'); +function noop() {} - if(!(visible || clickToShow)) return annOut; +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; - _$handleAnnotationCommonDefaults_227(annIn, annOut, fullLayout, coerce); +var GET_THEN_ERROR = new ErrorObject(); - var showArrow = annOut.showarrow; +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} - // positioning - var axLetters = ['x', 'y'], - arrowPosDflt = [-10, -30], - gdMock = {_fullLayout: fullLayout}; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i]; +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} - // xref, yref - var axRef = _$axes_407.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} - // x, y - _$axes_407.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} - if(showArrow) { - var arrowPosAttr = 'a' + axLetter, - // axref, ayref - aaxRef = _$axes_407.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); +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; - // for now the arrow can only be on the same axis or specified as pixels - // TODO: sometime it might be interesting to allow it to be on *any* axis - // but that would require updates to drawing & autorange code and maybe more - if(aaxRef !== 'pixel' && aaxRef !== axRef) { - aaxRef = annOut[arrowPosAttr] = 'pixel'; - } + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); - // ax, ay - var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_407.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); - } + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} - // xanchor, yanchor - coerce(axLetter + 'anchor'); +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); + }); + } +} - // xshift, yshift - coerce(axLetter + 'shift'); +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); } + } +} - // if you have one coordinate you should have both - _$lib_363.noneOrAll(annIn, annOut, ['x', 'y']); +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} - // if you have one part of arrow length you should have both - if(showArrow) { - _$lib_363.noneOrAll(annIn, annOut, ['ax', 'ay']); - } +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } - if(clickToShow) { - var xClick = coerce('xclick'); - var yClick = coerce('yclick'); + publish(promise); +} - // put the actual click data to bind to into private attributes - // so we don't have to do this little bit of logic on every hover event - annOut._xclick = (xClick === undefined) ? - annOut.x : - _$axes_407.cleanPosition(xClick, gdMock, annOut.xref); - annOut._yclick = (yClick === undefined) ? - annOut.y : - _$axes_407.cleanPosition(yClick, gdMock, annOut.yref); - } +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } - return annOut; -}; + promise._result = value; + promise._state = FULFILLED; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} -'use strict'; +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; -/* removed: var _$lib_363 = require('../lib'); */; + asap(publishRejection, promise); +} -/** Convenience wrapper for making array container logic DRY and consistent - * - * @param {object} parentObjIn - * user input object where the container in question is linked - * (i.e. either a user trace object or the user layout object) - * - * @param {object} parentObjOut - * full object where the coerced container will be linked - * (i.e. either a full trace object or the full layout object) - * - * @param {object} opts - * options object: - * - name {string} - * name of the key linking the container in question - * - handleItemDefaults {function} - * defaults method to be called on each item in the array container in question - * - * Its arguments are: - * - itemIn {object} item in user layout - * - itemOut {object} item in full layout - * - parentObj {object} (as in closure) - * - opts {object} (as in closure) - * - itemOpts {object} - * - itemIsNotPlainObject {boolean} - * N.B. - * - * - opts is passed to handleItemDefaults so it can also store - * links to supplementary data (e.g. fullData for layout components) - * - */ -var _$handleArrayContainerDefaults_403 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { - var name = opts.name; +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; - var previousContOut = parentObjOut[name]; + parent._onerror = null; - var contIn = _$lib_363.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], - contOut = parentObjOut[name] = [], - i; + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} - for(i = 0; i < contIn.length; i++) { - var itemIn = contIn[i], - itemOut = {}, - itemOpts = {}; +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; - if(!_$lib_363.isPlainObject(itemIn)) { - itemOpts.itemIsNotPlainObject = true; - itemIn = {}; - } + if (subscribers.length === 0) { + return; + } - opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); + var child = undefined, + callback = undefined, + detail = promise._result; - itemOut._input = itemIn; - itemOut._index = i; + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; - contOut.push(itemOut); + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); } + } - // in case this array gets its defaults rebuilt independent of the whole layout, - // relink the private keys just for this array. - if(_$lib_363.isArrayOrTypedArray(previousContOut)) { - var len = Math.min(previousContOut.length, contOut.length); - for(i = 0; i < len; i++) { - _$lib_363.relinkPrivateKeys(contOut[i], previousContOut[i]); - } - } -}; + promise._subscribers.length = 0; +} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function ErrorObject() { + this.error = null; +} +var TRY_CATCH_ERROR = new ErrorObject(); -'use strict'; +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} -/* removed: var _$handleArrayContainerDefaults_403 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationDefaults_222 = require('./annotation_defaults'); */; +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + if (hasCallback) { + value = tryCatch(callback, detail); -var _$supplyLayoutDefaults_229 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'annotations', - handleItemDefaults: _$handleAnnotationDefaults_222 - }; + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } - _$handleArrayContainerDefaults_403(layoutIn, layoutOut, opts); -}; + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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); + } +} -'use strict'; +var id = 0; +function nextId() { + return id++; +} -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} -/** - * 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 - */ -var _$makeIncludeComponents_417 = function makeIncludeComponents(containerArrayName) { - return function includeComponents(layoutIn, layoutOut) { - var array = layoutIn[containerArrayName]; - if(!Array.isArray(array)) return; +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); - var Cartesian = _$registry_451.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'); + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } - for(var i = 0; i < array.length; i++) { - var itemi = array[i]; - if(!_$lib_363.isPlainObject(itemi)) continue; + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; - var xref = itemi.xref; - var yref = itemi.yref; + this._result = new Array(this.length); - var hasXref = idRegex.x.test(xref); - var hasYref = idRegex.y.test(yref); - if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_363.pushUnique(layoutOut._basePlotModules, Cartesian); + 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()); + } +} - 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; - } +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; - /* - * 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); - } - } - } - }; +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); + } }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + if (resolve$$ === resolve) { + var _then = getThen(entry); -'use strict'; + 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); + } +}; -/* removed: var _$draw_230 = require('./draw'); */; -/* removed: var _$click_226 = require('./click'); */; +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; -var _$annotations_232 = { - moduleType: 'component', - name: 'annotations', + if (promise._state === PENDING) { + this._remaining--; - layoutAttributes: _$attributes_224, - supplyLayoutDefaults: _$supplyLayoutDefaults_229, - includeBasePlot: _$makeIncludeComponents_417('annotations'), + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } - calcAutorange: _$calcAutorange_225, - draw: _$draw_230.draw, - drawOne: _$draw_230.drawOne, - drawRaw: _$draw_230.drawRaw, + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; - hasClickToShow: _$click_226.hasClickToShow, - onClick: _$click_226.onClick, +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; - convertCoords: _$convertCoords_228 + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); }; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `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: -'use strict'; + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; -/* removed: var _$attributes_224 = require('../annotations/attributes'); */; -var __overrideAll_233 = _$edit_types_392.overrideAll; + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` -var _$attributes_233 = __overrideAll_233({ - _isLinkedToArray: 'annotation', + 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: - visible: _$attributes_224.visible, - x: { - valType: 'any', - - - }, - y: { - valType: 'any', - - - }, - z: { - valType: 'any', - - - }, - ax: { - valType: 'number', - - - }, - ay: { - valType: 'number', - - - }, + Example: - xanchor: _$attributes_224.xanchor, - xshift: _$attributes_224.xshift, - yanchor: _$attributes_224.yanchor, - yshift: _$attributes_224.yshift, - - text: _$attributes_224.text, - textangle: _$attributes_224.textangle, - font: _$attributes_224.font, - width: _$attributes_224.width, - height: _$attributes_224.height, - opacity: _$attributes_224.opacity, - align: _$attributes_224.align, - valign: _$attributes_224.valign, - bgcolor: _$attributes_224.bgcolor, - bordercolor: _$attributes_224.bordercolor, - borderpad: _$attributes_224.borderpad, - borderwidth: _$attributes_224.borderwidth, - showarrow: _$attributes_224.showarrow, - arrowcolor: _$attributes_224.arrowcolor, - arrowhead: _$attributes_224.arrowhead, - startarrowhead: _$attributes_224.startarrowhead, - arrowside: _$attributes_224.arrowside, - arrowsize: _$attributes_224.arrowsize, - startarrowsize: _$attributes_224.startarrowsize, - arrowwidth: _$attributes_224.arrowwidth, - standoff: _$attributes_224.standoff, - startstandoff: _$attributes_224.startstandoff, - hovertext: _$attributes_224.hovertext, - hoverlabel: _$attributes_224.hoverlabel, - captureevents: _$attributes_224.captureevents, + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; - // maybes later? - // clicktoshow: annAtts.clicktoshow, - // xclick: annAtts.xclick, - // yclick: annAtts.yclick, + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` - // not needed! - // axref: 'pixel' - // ayref: 'pixel' - // xref: 'x' - // yref: 'y - // zref: 'z' -}, 'calc', 'from-root'); + @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; +} /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. -'use strict'; + Example: -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); -var _$convert_234 = function convert(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var anns = fullSceneLayout.annotations; + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); - for(var i = 0; i < anns.length; i++) { - mockAnnAxes(anns[i], scene); - } + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` - scene.fullLayout._infolayer - .selectAll('.annotation-' + scene.id) - .remove(); -}; + `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: -function mockAnnAxes(ann, scene) { - var fullSceneLayout = scene.fullSceneLayout; - var domain = fullSceneLayout.domain; - var size = scene.fullLayout._size; + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); - var base = { - // this gets fill in on render - pdata: null, + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); - // to get setConvert to not execute cleanly - type: 'linear', + 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 + }); + ``` - // don't try to update them on `editable: true` - autorange: false, + An example real-world use case is implementing timeouts: - // set infinite range so that annotation draw routine - // does not try to remove 'outside-range' annotations, - // this case is handled in the render loop - range: [-Infinity, Infinity] - }; + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` - ann._xa = {}; - _$lib_363.extendFlat(ann._xa, base); - _$axes_407.setConvert(ann._xa); - ann._xa._offset = size.l + domain.x[0] * size.w; - ann._xa.l2p = function() { - return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); - }; + @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; - ann._ya = {}; - _$lib_363.extendFlat(ann._ya, base); - _$axes_407.setConvert(ann._ya); - ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; - ann._ya.l2p = function() { - return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); - }; + 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); + } + }); + } } /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: -'use strict'; + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_403 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationCommonDefaults_227 = require('../annotations/common_defaults'); */; -/* removed: var _$attributes_233 = require('./attributes'); */; + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` -var _$handleDefaults_235 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_403(sceneLayoutIn, sceneLayoutOut, { - name: 'annotations', - handleItemDefaults: __handleAnnotationDefaults_235, - fullLayout: opts.fullLayout - }); -}; + Instead of writing the above, your code now simply becomes the following: -function __handleAnnotationDefaults_235(annIn, annOut, sceneLayout, opts, itemOpts) { - function coerce(attr, dflt) { - return _$lib_363.coerce(annIn, annOut, _$attributes_233, attr, dflt); - } + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); - function coercePosition(axLetter) { - var axName = axLetter + 'axis'; + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` - // mock in such way that getFromId grabs correct 3D axis - var gdMock = { _fullLayout: {} }; - gdMock._fullLayout[axName] = sceneLayout[axName]; + @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'); +} - return _$axes_407.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); - } +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. - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - if(!visible) return annOut; + Terminology + ----------- - _$handleAnnotationCommonDefaults_227(annIn, annOut, opts.fullLayout, coerce); + - `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. - coercePosition('x'); - coercePosition('y'); - coercePosition('z'); + A promise can be in one of three states: pending, fulfilled, or rejected. - // if you have one coordinate you should all three - _$lib_363.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + 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. - // hard-set here for completeness - annOut.xref = 'x'; - annOut.yref = 'y'; - annOut.zref = 'z'; + 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. - coerce('xanchor'); - coerce('yanchor'); - coerce('xshift'); - coerce('yshift'); - if(annOut.showarrow) { - annOut.axref = 'pixel'; - annOut.ayref = 'pixel'; + Basic Usage: + ------------ - // TODO maybe default values should be bigger than the 2D case? - coerce('ax', -10); - coerce('ay', -30); + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); - // if you have one part of arrow length you should have both - _$lib_363.noneOrAll(annIn, annOut, ['ax', 'ay']); - } + // on failure + reject(reason); + }); - return annOut; -} + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + Advanced Usage: + --------------- + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. -'use strict'; + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); -function xformMatrix(m, v) { - var out = [0, 0, 0, 0]; - var i, j; + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); - for(i = 0; i < 4; ++i) { - for(j = 0; j < 4; ++j) { - out[j] += m[4 * i + j] * v[i]; + 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 + ']')); + } } - } + }; + }); + } - return out; -} + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` -function project(camera, v) { - var p = xformMatrix(camera.projection, - xformMatrix(camera.view, - xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); - return p; -} + Unlike callbacks, promises are great composable primitives. -var _$project_441 = project; + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor */ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; -'use strict'; + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} -var __drawRaw_236 = _$draw_230.drawRaw; -/* removed: var _$project_441 = require('../../plots/gl3d/project'); */; -var axLetters = ['x', 'y', 'z']; +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; -var _$draw_236 = function draw(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var dataScale = scene.dataScale; - var anns = fullSceneLayout.annotations; +Promise.prototype = { + constructor: Promise, - for(var i = 0; i < anns.length; i++) { - var ann = anns[i]; - var annotationIsOffscreen = false; + /** + 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, - for(var j = 0; j < 3; j++) { - var axLetter = axLetters[j]; - var pos = ann[axLetter]; - var ax = fullSceneLayout[axLetter + 'axis']; - var posFraction = ax.r2fraction(pos); + /** + `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); + } +}; - if(posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - break; - } +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'); } + } - if(annotationIsOffscreen) { - scene.fullLayout._infolayer - .select('.annotation-' + scene.id + '[data-index="' + i + '"]') - .remove(); - } else { - ann._pdata = _$project_441(scene.glplot.cameraParams, [ - fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], - fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], - fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] - ]); + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } - __drawRaw_236(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + 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 +}).call(this,_$browser_228,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +_$es6Promise_124 = _$es6Promise_124.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -65574,42 +67401,65 @@ var _$draw_236 = function draw(scene) { 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; - -var _$annotations3d_237 = { - moduleType: 'component', - name: 'annotations3d', +/** + * All paths are tuned for maximum scalability of the arrowhead, + * ie throughout arrowwidth=0.3..3 the head is joined smoothly + * to the line, with the line coming from the left and ending at (0, 0). + * + * `backoff` is the distance to move the arrowhead and the end of the line, + * in order that the arrowhead points to the desired place, either at + * the tip of the arrow or (in the case of circle or square) + * the center of the symbol. + * + * `noRotate`, if truthy, says that this arrowhead should not rotate with the + * arrow. That's the case for squares, which should always be straight, and + * circles, for which it's irrelevant. + */ - schema: { - subplots: { - scene: {annotations: _$attributes_233} - } +var _$arrow_paths_285 = [ + // no arrow + { + path: '', + backoff: 0 }, - - layoutAttributes: _$attributes_233, - handleDefaults: _$handleDefaults_235, - includeBasePlot: includeGL3D, - - convert: _$convert_234, - draw: _$draw_236 -}; - -function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_451.subplotsRegistry.gl3d; - if(!GL3D) return; - - var attrRegex = GL3D.attrRegex; - - var keys = Object.keys(layoutIn); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; - if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_363.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_363.pushUnique(layoutOut._subplots.gl3d, k); - } + // wide with flat back + { + path: 'M-2.4,-3V3L0.6,0Z', + backoff: 0.6 + }, + // narrower with flat back + { + path: 'M-3.7,-2.5V2.5L1.3,0Z', + backoff: 1.3 + }, + // barbed + { + path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z', + backoff: 1.55 + }, + // wide line-drawn + { + path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z', + backoff: 1.6 + }, + // narrower line-drawn + { + path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z', + backoff: 2 + }, + // circle + { + path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z', + backoff: 0, + noRotate: true + }, + // square + { + path: 'M2,2V-2H-2V2Z', + backoff: 0, + noRotate: true } -} +]; /** * Copyright 2012-2018, Plotly, Inc. @@ -65621,105 +67471,346 @@ function includeGL3D(layoutIn, layoutOut) { 'use strict'; +/* removed: var _$arrow_paths_285 = require('./arrow_paths'); */; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +/* removed: var _$constants_475 = require('../../plots/cartesian/constants'); */; + + +var _$attributes_286 = { + _isLinkedToArray: 'annotation', -var _$attributes_266 = { visible: { valType: 'boolean', - editType: 'calc', + dflt: true, + editType: 'calcIfAutorange+arraydraw', }, - type: { + + text: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, + textangle: { + valType: 'angle', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + font: _$font_attributes_496({ + editType: 'calcIfAutorange+arraydraw', + colorEditType: 'arraydraw', + + }), + width: { + valType: 'number', + min: 1, + dflt: null, + + editType: 'calcIfAutorange+arraydraw', + + }, + height: { + valType: 'number', + min: 1, + dflt: null, + + editType: 'calcIfAutorange+arraydraw', + + }, + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + + }, + align: { valType: 'enumerated', - values: ['percent', 'constant', 'sqrt', 'data'], + values: ['left', 'center', 'right'], + dflt: 'center', - editType: 'calc', + editType: 'arraydraw', }, - symmetric: { - valType: 'boolean', + valign: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'middle', - editType: 'calc', + editType: 'arraydraw', }, - array: { - valType: 'data_array', - editType: 'calc', + bgcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', }, - arrayminus: { - valType: 'data_array', - editType: 'calc', + bordercolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', }, - value: { + borderpad: { valType: 'number', min: 0, - dflt: 10, + dflt: 1, - editType: 'calc', + editType: 'calcIfAutorange+arraydraw', }, - valueminus: { + borderwidth: { valType: 'number', min: 0, - dflt: 10, + dflt: 1, - editType: 'calc', + editType: 'calcIfAutorange+arraydraw', }, - traceref: { + // arrow + showarrow: { + valType: 'boolean', + dflt: true, + + editType: 'calcIfAutorange+arraydraw', + + }, + arrowcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + arrowhead: { valType: 'integer', min: 0, - dflt: 0, + max: _$arrow_paths_285.length, + dflt: 1, + + editType: 'arraydraw', - editType: 'style' }, - tracerefminus: { + startarrowhead: { valType: 'integer', min: 0, - dflt: 0, + max: _$arrow_paths_285.length, + dflt: 1, + + editType: 'arraydraw', - editType: 'style' }, - copy_ystyle: { - valType: 'boolean', + arrowside: { + valType: 'flaglist', + flags: ['end', 'start'], + extras: ['none'], + dflt: 'end', + + editType: 'arraydraw', - editType: 'plot' }, - copy_zstyle: { - valType: 'boolean', + arrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, + + editType: 'calcIfAutorange+arraydraw', - editType: 'style' }, - color: { - valType: 'color', + startarrowsize: { + valType: 'number', + min: 0.3, + dflt: 1, - editType: 'style', + editType: 'calcIfAutorange+arraydraw', }, - thickness: { + arrowwidth: { + valType: 'number', + min: 0.1, + + editType: 'calcIfAutorange+arraydraw', + + }, + standoff: { valType: 'number', min: 0, - dflt: 2, + dflt: 0, - editType: 'style', + editType: 'calcIfAutorange+arraydraw', }, - width: { + startstandoff: { valType: 'number', min: 0, + dflt: 0, - editType: 'plot', + editType: 'calcIfAutorange+arraydraw', + + }, + ax: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + ay: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + axref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_475.idRegex.x.toString() + ], + + editType: 'calc', + + }, + ayref: { + valType: 'enumerated', + dflt: 'pixel', + values: [ + 'pixel', + _$constants_475.idRegex.y.toString() + ], + + editType: 'calc', + + }, + // positioning + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_475.idRegex.x.toString() + ], + + editType: 'calc', + + }, + x: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + xshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_475.idRegex.y.toString() + ], + + editType: 'calc', + + }, + y: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'auto', + + editType: 'calcIfAutorange+arraydraw', + + }, + yshift: { + valType: 'number', + dflt: 0, + + editType: 'calcIfAutorange+arraydraw', + + }, + clicktoshow: { + valType: 'enumerated', + values: [false, 'onoff', 'onout'], + dflt: false, + + editType: 'arraydraw', + + }, + xclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + yclick: { + valType: 'any', + + editType: 'arraydraw', + + }, + hovertext: { + valType: 'string', + + editType: 'arraydraw', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + bordercolor: { + valType: 'color', + + editType: 'arraydraw', + + }, + font: _$font_attributes_496({ + editType: 'arraydraw', + + }), + editType: 'arraydraw' + }, + captureevents: { + valType: 'boolean', + + editType: 'arraydraw', }, editType: 'calc', _deprecated: { - opacity: { - valType: 'number', + ref: { + valType: 'string', - editType: 'style', + editType: 'calc', } } @@ -65736,232 +67827,146 @@ var _$attributes_266 = { 'use strict'; +/* removed: var _$d3_71 = require('d3'); */; -/** - * 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 " - */ -var _$makeComputeError_268 = function makeComputeError(opts) { - var type = opts.type, - 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), - computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); +/* removed: var _$color_301 = require('../color'); */; - 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) - ]; - }; - } - } -}; +/* removed: var _$arrow_paths_285 = require('./arrow_paths'); */; /** - * Compute error bar magnitude (for all types except data) + * Add arrowhead(s) to a path or line element * - * @param {string} type error bar type - * @param {numeric} value error bar value + * @param {d3.selection} el3: a d3-selected line or path element * - * @return {function} : - * @param {numeric} dataPt + * @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. */ -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)); - }; - } -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$makeComputeError_268 = require('./compute_error'); */; - - -var _$calc_267 = function calc(gd) { - var calcdata = gd.calcdata; - - for(var i = 0; i < calcdata.length; i++) { - var calcTrace = calcdata[i], - trace = calcTrace[0].trace; - - if(!_$registry_451.traceIs(trace, 'errorBarsOK')) continue; - - var xa = _$axes_407.getFromId(gd, trace.xaxis), - ya = _$axes_407.getFromId(gd, trace.yaxis); +var _$drawArrowHead_293 = function drawArrowHead(el3, ends, options) { + var el = el3.node(); + var headStyle = _$arrow_paths_285[options.arrowhead || 0]; + var startHeadStyle = _$arrow_paths_285[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; - calcOneAxis(calcTrace, trace, xa, 'x'); - calcOneAxis(calcTrace, trace, ya, 'y'); - } -}; + var start, end, startRot, endRot; -function calcOneAxis(calcTrace, trace, axis, coord) { - var opts = trace['error_' + coord] || {}, - isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), - vals = []; + if(el.nodeName === 'line') { + start = {x: +el3.attr('x1'), y: +el3.attr('y1')}; + end = {x: +el3.attr('x2'), y: +el3.attr('y2')}; - if(!isVisible) return; + var dx = start.x - end.x; + var dy = start.y - end.y; - var computeError = _$makeComputeError_268(opts); + startRot = Math.atan2(dy, dx); + endRot = startRot + Math.PI; + if(backOff && startBackOff) { + if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) { + hideLine(); + return; + } + } - for(var i = 0; i < calcTrace.length; i++) { - var calcPt = calcTrace[i], - calcCoord = calcPt[coord]; + if(backOff) { + if(backOff * backOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var backOffX = backOff * Math.cos(startRot), + backOffY = backOff * Math.sin(startRot); - if(!_$fastIsnumeric_78(axis.c2l(calcCoord))) continue; + end.x += backOffX; + end.y += backOffY; + el3.attr({x2: end.x, y2: end.y}); - var errors = computeError(calcCoord, i); - if(_$fastIsnumeric_78(errors[0]) && _$fastIsnumeric_78(errors[1])) { - var shoe = calcPt[coord + 's'] = calcCoord - errors[0], - hat = calcPt[coord + 'h'] = calcCoord + errors[1]; - vals.push(shoe, hat); } - } - - _$axes_407.expand(axis, vals, {padded: true}); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ -'use strict'; + if(startBackOff) { + if(startBackOff * startBackOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var startBackOffX = startBackOff * Math.cos(startRot), + startbackOffY = startBackOff * Math.sin(startRot); -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; + start.x -= startBackOffX; + start.y -= startbackOffY; + el3.attr({x1: start.x, y1: start.y}); -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; + } + } + 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 + dashArray = ''; -/* removed: var _$attributes_266 = require('./attributes'); */; + if(pathlen < backOff + startBackOff) { + hideLine(); + return; + } -var _$defaults_269 = function(traceIn, traceOut, defaultColor, opts) { - var objName = 'error_' + opts.axis, - containerOut = traceOut[objName] = {}, - containerIn = traceIn[objName] || {}; + var start0 = el.getPointAtLength(0); + var dstart = el.getPointAtLength(0.1); - function coerce(attr, dflt) { - return _$lib_363.coerce(containerIn, containerOut, _$attributes_266, attr, dflt); - } + startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); + start = el.getPointAtLength(Math.min(startBackOff, pathlen)); - var hasErrorBars = ( - containerIn.array !== undefined || - containerIn.value !== undefined || - containerIn.type === 'sqrt' - ); + dashArray = '0px,' + startBackOff + 'px,'; - var visible = coerce('visible', hasErrorBars); + var end0 = el.getPointAtLength(pathlen); + var dend = el.getPointAtLength(pathlen - 0.1); - if(visible === false) return; + endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); + end = el.getPointAtLength(Math.max(0, pathlen - backOff)); - var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), - symmetric = true; + var shortening = dashArray ? startBackOff + backOff : backOff; + dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px'; - if(type !== 'sqrt') { - symmetric = coerce('symmetric', - !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); + el3.style('stroke-dasharray', dashArray); } - 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'); - } + function hideLine() { el3.style('stroke-dasharray', '0px,100px'); } - var copyAttr = 'copy_' + opts.inherit + 'style'; - if(opts.inherit) { - var inheritObj = traceOut['error_' + opts.inherit]; - if((inheritObj || {}).visible) { - coerce(copyAttr, !(containerIn.color || - _$fastIsnumeric_78(containerIn.thickness) || - _$fastIsnumeric_78(containerIn.width))); - } - } - if(!opts.inherit || !containerOut[copyAttr]) { - coerce('color', defaultColor); - coerce('thickness'); - coerce('width', _$registry_451.traceIs(traceOut, 'gl3d') ? 0 : 4); + function drawhead(arrowHeadStyle, p, rot, arrowScale) { + if(!arrowHeadStyle.path) return; + if(arrowHeadStyle.noRotate) rot = 0; + + _$d3_71.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_301.rgb(options.arrowcolor), + 'stroke-width': 0 + }); } + + if(doStart) drawhead(startHeadStyle, start, startRot, startScale); + if(doEnd) drawhead(headStyle, end, endRot, scale); }; /** @@ -65972,762 +67977,815 @@ var _$defaults_269 = function(traceIn, traceOut, defaultColor, opts) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$d3_71 = require('d3'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$subtypes_534 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$fx_343 = require('../fx'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_445 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$drawArrowHead_293 = require('./draw_arrow_head'); */; -var _$plot_271 = function plot(traces, plotinfo, transitionOpts) { - var isNew; - - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; +// Annotations are stored in gd.layout.annotations, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - var hasAnimation = transitionOpts && transitionOpts.duration > 0; +var _$draw_292 = { + draw: __draw_292, + drawOne: drawOne, + drawRaw: drawRaw +}; - 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 - xObj = trace.error_x || {}, - yObj = trace.error_y || {}; +/* + * draw: draw all annotations without any new modifications + */ +function __draw_292(gd) { + var fullLayout = gd._fullLayout; - var keyFunc; + fullLayout._infolayer.selectAll('.annotation').remove(); - if(trace.ids) { - keyFunc = function(d) {return d.id;}; + for(var i = 0; i < fullLayout.annotations.length; i++) { + if(fullLayout.annotations[i].visible) { + drawOne(gd, i); } + } - var sparse = ( - _$subtypes_534.hasMarkers(trace) && - trace.marker.maxdisplayed > 0 - ); - - if(!yObj.visible && !xObj.visible) d = []; + return _$plots_506.previousPromises(gd); +} - var errorbars = _$d3_68.select(this).selectAll('g.errorbar') - .data(d, keyFunc); +/* + * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications + * + * index (int): the annotation to draw + */ +function drawOne(gd, index) { + var fullLayout = gd._fullLayout; + var options = fullLayout.annotations[index] || {}; + var xa = _$axes_470.getFromId(gd, options.xref); + var ya = _$axes_470.getFromId(gd, options.yref); - errorbars.exit().remove(); + drawRaw(gd, options, index, false, xa, ya); +} - if(!d.length) return; +/** + * drawRaw: draw a single annotation, potentially with modifications + * + * @param {DOM element} gd + * @param {object} options : this annotation's fullLayout options + * @param {integer} index : index in 'annotations' container of the annotation to draw + * @param {string} subplotId : id of the annotation's subplot + * - use false for 2d (i.e. cartesian or paper-ref) annotations + * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px + * @param {object | undefined} ya : ... y-axis + */ +function drawRaw(gd, options, index, subplotId, xa, ya) { + var fullLayout = gd._fullLayout; + var gs = gd._fullLayout._size; + var edits = gd._context.edits; - if(!xObj.visible) errorbars.selectAll('path.xerror').remove(); - if(!yObj.visible) errorbars.selectAll('path.yerror').remove(); + var className; + var annbase; - errorbars.style('opacity', 1); + if(subplotId) { + className = 'annotation-' + subplotId; + annbase = subplotId + '.annotations[' + index + ']'; + } else { + className = 'annotation'; + annbase = 'annotations[' + index + ']'; + } - var enter = errorbars.enter().append('g') - .classed('errorbar', true); + // remove the existing annotation if there is one + fullLayout._infolayer + .selectAll('.' + className + '[data-index="' + index + '"]') + .remove(); - if(hasAnimation) { - enter.style('opacity', 0).transition() - .duration(transitionOpts.duration) - .style('opacity', 1); - } + var annClipID = 'clip' + fullLayout._uid + '_ann' + index; - _$drawing_264.setClipUrl(errorbars, plotinfo.layerClipId); + // this annotation is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!options._input || options.visible === false) { + _$d3_71.selectAll('#' + annClipID).remove(); + return; + } - errorbars.each(function(d) { - var errorbar = _$d3_68.select(this); - var coords = errorCoords(d, xa, ya); + // calculated pixel positions + // x & y each will get text, head, and tail as appropriate + var annPosPx = {x: {}, y: {}}, + textangle = +options.textangle || 0; - if(sparse && !d.vis) return; + // create the components + // made a single group to contain all, so opacity can work right + // with border/arrow together this could handle a whole bunch of + // cleanup at this point, but works for now + var annGroup = fullLayout._infolayer.append('g') + .classed(className, true) + .attr('data-index', String(index)) + .style('opacity', options.opacity); - var path; + // another group for text+background so that they can rotate together + var annTextGroup = annGroup.append('g') + .classed('annotation-text-g', true); - var yerror = errorbar.select('path.yerror'); - if(yObj.visible && _$fastIsnumeric_78(coords.x) && - _$fastIsnumeric_78(coords.yh) && - _$fastIsnumeric_78(coords.ys)) { - var yw = yObj.width; + var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition']; + var textEvents = options.captureevents || edits.annotationText || editTextPosition; - path = 'M' + (coords.x - yw) + ',' + - coords.yh + 'h' + (2 * yw) + // hat - 'm-' + yw + ',0V' + coords.ys; // bar + var annTextGroupInner = annTextGroup.append('g') + .style('pointer-events', textEvents ? 'all' : null) + .call(_$setCursor_445, 'default') + .on('click', function() { + gd._dragging = false; + var eventData = { + index: index, + annotation: options._input, + fullAnnotation: options, + event: _$d3_71.event + }; - if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe + if(subplotId) { + eventData.subplotId = subplotId; + } - isNew = !yerror.size(); + gd.emit('plotly_clickannotation', eventData); + }); - 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); - } + if(options.hovertext) { + annTextGroupInner + .on('mouseover', function() { + var hoverOptions = options.hoverlabel; + var hoverFont = hoverOptions.font; + var bBox = this.getBoundingClientRect(); + var bBoxRef = gd.getBoundingClientRect(); - yerror.attr('d', path); - } - else yerror.remove(); + _$fx_343.loneHover({ + x0: bBox.left - bBoxRef.left, + x1: bBox.right - bBoxRef.left, + y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, + text: options.hovertext, + color: hoverOptions.bgcolor, + borderColor: hoverOptions.bordercolor, + fontFamily: hoverFont.family, + fontSize: hoverFont.size, + fontColor: hoverFont.color + }, { + container: fullLayout._hoverlayer.node(), + outerContainer: fullLayout._paper.node(), + gd: gd + }); + }) + .on('mouseout', function() { + _$fx_343.loneUnhover(fullLayout._hoverlayer.node()); + }); + } - var xerror = errorbar.select('path.xerror'); - if(xObj.visible && _$fastIsnumeric_78(coords.y) && - _$fastIsnumeric_78(coords.xh) && - _$fastIsnumeric_78(coords.xs)) { - var xw = (xObj.copy_ystyle ? yObj : xObj).width; + var borderwidth = options.borderwidth, + borderpad = options.borderpad, + borderfull = borderwidth + borderpad; - path = 'M' + coords.xh + ',' + - (coords.y - xw) + 'v' + (2 * xw) + // hat - 'm0,-' + xw + 'H' + coords.xs; // bar + var annTextBG = annTextGroupInner.append('rect') + .attr('class', 'bg') + .style('stroke-width', borderwidth + 'px') + .call(_$color_301.stroke, options.bordercolor) + .call(_$color_301.fill, options.bgcolor); - if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe + var isSizeConstrained = options.width || options.height; - isNew = !xerror.size(); + var annTextClip = fullLayout._topclips + .selectAll('#' + annClipID) + .data(isSizeConstrained ? [0] : []); - 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); - } + annTextClip.enter().append('clipPath') + .classed('annclip', true) + .attr('id', annClipID) + .append('rect'); + annTextClip.exit().remove(); - xerror.attr('d', path); - } - else xerror.remove(); - }); - }); -}; + var font = options.font; -// 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) - }; + var annText = annTextGroupInner.append('text') + .classed('annotation-text', true) + .text(options.text); - // 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); + function textLayout(s) { + s.call(_$drawing_326.font, font) + .attr({ + 'text-anchor': { + left: 'start', + right: 'end' + }[options.align] || 'middle' + }); - // if the shoes go off-scale (ie log scale, error bars past zero) - // clip the bar and hide the shoes - if(!_$fastIsnumeric_78(out.ys)) { - out.noYS = true; - out.ys = ya.c2p(d.ys, true); - } + _$svg_text_utils_449.convertToTspans(s, gd, drawGraphicalElements); + return s; } - if(d.xh !== undefined) { - out.xh = xa.c2p(d.xh); - out.xs = xa.c2p(d.xs); + function drawGraphicalElements() { + // if the text has *only* a link, make the whole box into a link + var anchor3 = annText.selectAll('a'); + if(anchor3.size() === 1 && anchor3.text() === annText.text()) { + var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({ + 'xlink:xlink:href': anchor3.attr('xlink:href'), + 'xlink:xlink:show': anchor3.attr('xlink:show') + }) + .style({cursor: 'pointer'}); - if(!_$fastIsnumeric_78(out.xs)) { - out.noXS = true; - out.xs = xa.c2p(d.xs, true); + wholeLink.node().appendChild(annTextBG.node()); } - } - return out; -} + var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); + var hasMathjax = !mathjaxGroup.empty(); + var anntextBB = _$drawing_326.bBox( + (hasMathjax ? mathjaxGroup : annText).node()); + var textWidth = anntextBB.width; + var textHeight = anntextBB.height; + var annWidth = options.width || textWidth; + var annHeight = options.height || textHeight; + var outerWidth = Math.round(annWidth + 2 * borderfull); + var outerHeight = Math.round(annHeight + 2 * borderfull); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // save size in the annotation object for use by autoscale + options._w = annWidth; + options._h = annHeight; -'use strict'; + function shiftFraction(v, anchor) { + if(anchor === 'auto') { + if(v < 1 / 3) anchor = 'left'; + else if(v > 2 / 3) anchor = 'right'; + else anchor = 'center'; + } + return { + center: 0, + middle: 0, + left: 0.5, + bottom: -0.5, + right: -0.5, + top: 0.5 + }[anchor]; + } -/* removed: var _$d3_68 = require('d3'); */; + var annotationIsOffscreen = false; + var letters = ['x', 'y']; -/* removed: var _$color_239 = require('../color'); */; + for(var i = 0; i < letters.length; i++) { + var axLetter = letters[i], + axRef = options[axLetter + 'ref'] || axLetter, + tailRef = options['a' + axLetter + 'ref'], + ax = {x: xa, y: ya}[axLetter], + dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180, + // note that these two can be either positive or negative + annSizeFromWidth = outerWidth * Math.cos(dimAngle), + annSizeFromHeight = outerHeight * Math.sin(dimAngle), + // but this one is the positive total size + annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight), + anchor = options[axLetter + 'anchor'], + overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1), + posPx = annPosPx[axLetter], + basePx, + textPadShift, + alignPosition, + autoAlignFraction, + textShift; + /* + * calculate the *primary* pixel position + * which is the arrowhead if there is one, + * otherwise the text anchor point + */ + if(ax) { + /* + * hide the annotation if it's pointing outside the visible plot + * as long as the axis isn't autoranged - then we need to draw it + * anyway to get its bounding box. When we're dragging, an axis can + * still look autoranged even though it won't be when the drag finishes. + */ + var posFraction = ax.r2fraction(options[axLetter]); + if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) { + if(tailRef === axRef) { + posFraction = ax.r2fraction(options['a' + axLetter]); + if(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + } + } + else { + annotationIsOffscreen = true; + } -var _$style_272 = function style(traces) { - traces.each(function(d) { - var trace = d[0].trace, - yObj = trace.error_y || {}, - xObj = trace.error_x || {}; + if(annotationIsOffscreen) continue; + } + 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; + } - var s = _$d3_68.select(this); + // now translate this into pixel positions of head, tail, and text + // as well as paddings for autorange + if(options.showarrow) { + posPx.head = basePx; - s.selectAll('path.yerror') - .style('stroke-width', yObj.thickness + 'px') - .call(_$color_239.stroke, yObj.color); + var arrowLength = options['a' + axLetter]; - if(xObj.copy_ystyle) xObj = yObj; + // with an arrow, the text rotates around the anchor point + textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - + annSizeFromHeight * shiftFraction(0.5, options.yanchor); - s.selectAll('path.xerror') - .style('stroke-width', xObj.thickness + 'px') - .call(_$color_239.stroke, xObj.color); - }); -}; + 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; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + posPx.text = posPx.tail + textShift; -'use strict'; + // 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_425.constrain(posPx.head, 1, maxPx - 1); + } + if(tailRef === 'pixel') { + var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), + 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; + } -/* removed: var _$lib_363 = require('../../lib'); */; -var __overrideAll_270 = _$edit_types_392.overrideAll; + posPx.text += overallShift; + textShift += overallShift; + textPadShift += overallShift; -/* removed: var _$attributes_266 = require('./attributes'); */; -/* removed: var _$calc_267 = require('./calc'); */; + // padplus/minus are used by autorange + options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift; + options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift; -var xyAttrs = { - error_x: _$lib_363.extendFlat({}, _$attributes_266), - error_y: _$lib_363.extendFlat({}, _$attributes_266) -}; -delete xyAttrs.error_x.copy_zstyle; -delete xyAttrs.error_y.copy_zstyle; -delete xyAttrs.error_y.copy_ystyle; + // size/shift are used during dragging + options['_' + axLetter + 'size'] = annSize; + options['_' + axLetter + 'shift'] = textShift; + } -var xyzAttrs = { - error_x: _$lib_363.extendFlat({}, _$attributes_266), - error_y: _$lib_363.extendFlat({}, _$attributes_266), - error_z: _$lib_363.extendFlat({}, _$attributes_266) -}; -delete xyzAttrs.error_x.copy_ystyle; -delete xyzAttrs.error_y.copy_ystyle; -delete xyzAttrs.error_z.copy_ystyle; -delete xyzAttrs.error_z.copy_zstyle; + if(annotationIsOffscreen) { + annTextGroupInner.remove(); + return; + } -var _$errorbars_270 = { - moduleType: 'component', - name: 'errorbars', + var xShift = 0; + var yShift = 0; - schema: { - traces: { - scatter: xyAttrs, - bar: xyAttrs, - histogram: xyAttrs, - scatter3d: __overrideAll_270(xyzAttrs, 'calc', 'nested'), - scattergl: __overrideAll_270(xyAttrs, 'calc', 'nested') + 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); } - }, - - supplyDefaults: _$defaults_269, - calc: _$calc_267, - calcFromTrace: calcFromTrace, + if(hasMathjax) { + mathjaxGroup.select('svg').attr({ + x: borderfull + xShift - 1, + y: borderfull + yShift + }) + .call(_$drawing_326.setClipUrl, isSizeConstrained ? annClipID : null); + } + else { + var texty = borderfull + yShift - anntextBB.top; + var textx = borderfull + xShift - anntextBB.left; - plot: _$plot_271, - style: _$style_272, - hoverInfo: hoverInfo -}; + annText.call(_$svg_text_utils_449.positionText, textx, texty) + .call(_$drawing_326.setClipUrl, isSizeConstrained ? annClipID : null); + } -function calcFromTrace(trace, layout) { - var x = trace.x || [], - y = trace.y || [], - len = x.length || y.length; + annTextClip.select('rect').call(_$drawing_326.setRect, borderfull, borderfull, + annWidth, annHeight); - var calcdataMock = new Array(len); + annTextBG.call(_$drawing_326.setRect, borderwidth / 2, borderwidth / 2, + outerWidth - borderwidth, outerHeight - borderwidth); - for(var i = 0; i < len; i++) { - calcdataMock[i] = { - x: x[i], - y: y[i] - }; - } + annTextGroupInner.call(_$drawing_326.setTranslate, + Math.round(annPosPx.x.text - outerWidth / 2), + Math.round(annPosPx.y.text - outerHeight / 2)); - calcdataMock[0].trace = trace; + /* + * 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 + ')'}); - _$calc_267({ - calcdata: [calcdataMock], - _fullLayout: layout - }); + /* + * 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(); - return calcdataMock; -} + var headX = annPosPx.x.head, + headY = annPosPx.y.head, + tailX = annPosPx.x.tail + dx, + tailY = annPosPx.y.tail + dy, + textX = annPosPx.x.text + dx, + textY = annPosPx.y.text + dy, -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; - } -} + // find the edge of the text box, where we'll start the arrow: + // create transform matrix to rotate the text box corners + transform = _$lib_425.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_425.apply2DTransform(transform), + applyTransform2 = _$lib_425.apply2DTransform2(transform), -var _$domain_433 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // calculate and transform bounding box + width = +annTextBG.attr('width'), + height = +annTextBG.attr('height'), + xLeft = textX - 0.5 * width, + xRight = xLeft + width, + yTop = textY - 0.5 * height, + yBottom = yTop + height, + edges = [ + [xLeft, yTop, xLeft, yBottom], + [xLeft, yBottom, xRight, yBottom], + [xRight, yBottom, xRight, yTop], + [xRight, yTop, xLeft, yTop] + ].map(applyTransform2); -'use strict'; + // 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_425.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; + } -var __extendFlat_433 = _$extend_354.extendFlat; + edges.forEach(function(x) { + var p = _$lib_425.segmentsIntersect(tailX, tailY, headX, headY, + x[0], x[1], x[2], x[3]); + if(p) { + tailX = p.x; + tailY = p.y; + } + }); -/** - * 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 - */ -_$domain_433.attributes = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; + var strokewidth = options.arrowwidth, + arrowColor = options.arrowcolor, + arrowSide = options.arrowside; - 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 arrowGroup = annGroup.append('g') + .style({opacity: _$color_301.opacity(arrowColor)}) + .classed('annotation-arrow-g', true); - var namePart = opts.name ? opts.name + ' ' : ''; - var contPart = opts.trace ? 'trace ' : 'subplot '; - var descPart = extra.description ? ' ' + extra.description : ''; + var arrow = arrowGroup.append('path') + .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY) + .style('stroke-width', strokewidth + 'px') + .call(_$color_301.stroke, _$color_301.rgb(arrowColor)); - var out = { - x: __extendFlat_433({}, base, { - - }), - y: __extendFlat_433({}, base, { - - }), - editType: opts.editType - }; + _$drawArrowHead_293(arrow, arrowSide, options); - 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, - - }; - } + // 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) + .attr({ + d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY), + transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' + }) + .style('stroke-width', (strokewidth + 6) + 'px') + .call(_$color_301.stroke, 'rgba(0,0,0,0)') + .call(_$color_301.fill, 'rgba(0,0,0,0)'); - return out; -}; + var update, + annx0, + anny0; -_$domain_433.defaults = function(containerOut, layout, coerce, dfltDomains) { - var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; - var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; + // dragger for the arrow & head: translates the whole thing + // (head/tail/text) all together + _$dragelement_323.init({ + element: arrowDrag.node(), + gd: gd, + prepFn: function() { + var pos = _$drawing_326.getTranslate(annTextGroupInner); - 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; - } + annx0 = pos.x; + anny0 = pos.y; + update = {}; + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + }, + moveFn: function(dx, dy) { + var annxy0 = applyTransform(annx0, anny0), + xcenter = annxy0[0] + dx, + ycenter = annxy0[1] + dy; + annTextGroupInner.call(_$drawing_326.setTranslate, xcenter, ycenter); - var row = coerce('domain.row'); - if(row !== undefined) { - if(row < grid.rows) dfltY = grid._domains.y[row]; - else delete containerOut.domain.row; - } - } + update[annbase + '.x'] = xa ? + xa.p2r(xa.r2p(options.x) + dx) : + (options.x + (dx / gs.w)); + update[annbase + '.y'] = ya ? + ya.p2r(ya.r2p(options.y) + dy) : + (options.y - (dy / gs.h)); - coerce('domain.x', dfltX); - coerce('domain.y', dfltY); -}; + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } -'use strict'; + arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')'); + annTextGroup.attr({ + transform: 'rotate(' + textangle + ',' + + xcenter + ',' + ycenter + ')' + }); + }, + doneFn: function() { + _$registry_514.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } + }; -/* removed: var _$lib_363 = require('../../lib'); */; -var __counterRegex_285 = _$regex_378.counter; -var domainAttrs = _$domain_433.attributes; -var cartesianIdRegex = _$constants_412.idRegex; + if(options.showarrow) drawArrow(0, 0); -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_285('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: 'ticks', - - }, - yside: { - valType: 'enumerated', - values: ['left', 'left plot', 'right plot', 'right'], - dflt: 'left plot', - - editType: 'ticks', - - }, - editType: 'plot' -}; + // user dragging the annotation (text, not arrow) + if(editTextPosition) { + var update, + baseTextTransform; -// 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; - if(!gridIn) return; + // dragger for the textbox: if there's an arrow, just drag the + // textbox and tail, leave the head untouched + _$dragelement_323.init({ + element: annTextGroupInner.node(), + gd: gd, + prepFn: function() { + baseTextTransform = annTextGroup.attr('transform'); + update = {}; + }, + moveFn: function(dx, dy) { + var csr = 'pointer'; + if(options.showarrow) { + if(options.axref === options.xref) { + update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx); + } else { + update[annbase + '.ax'] = options.ax + dx; + } - var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]); - var hasXaxes = Array.isArray(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + if(options.ayref === options.yref) { + update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy); + } else { + update[annbase + '.ay'] = options.ay + dy; + } - var dfltRows, dfltColumns; + drawArrow(dx, dy); + } + else if(!subplotId) { + if(xa) { + update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx); - if(hasSubplotGrid) { - dfltRows = gridIn.subplots.length; - dfltColumns = gridIn.subplots[0].length; - } - else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; - } + } else { + var widthFraction = options._xsize / gs.w, + xLeft = options.x + (options._xshift - options.xshift) / gs.w - + widthFraction / 2; - var gridOut = layoutOut.grid = {}; + update[annbase + '.x'] = _$dragelement_323.align(xLeft + dx / gs.w, + widthFraction, 0, 1, options.xanchor); + } - function coerce(attr, dflt) { - return _$lib_363.coerce(gridIn, gridOut, gridAttrs, attr, dflt); - } + if(ya) { + update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy); + } else { + var heightFraction = options._ysize / gs.h, + yBottom = options.y - (options._yshift + options.yshift) / gs.h - + heightFraction / 2; - var rows = coerce('rows', dfltRows); - var columns = coerce('columns', dfltColumns); + update[annbase + '.y'] = _$dragelement_323.align(yBottom - dy / gs.h, + heightFraction, 0, 1, options.yanchor); + } + if(!xa || !ya) { + csr = _$dragelement_323.getCursor( + xa ? 0.5 : update[annbase + '.x'], + ya ? 0.5 : update[annbase + '.y'], + options.xanchor, options.yanchor + ); + } + } + else return; - if(!(rows * columns > 1)) return; + annTextGroup.attr({ + transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform + }); - if(!hasSubplotGrid && !hasXaxes && !hasYaxes) { - var useDefaultSubplots = coerce('pattern') === 'independent'; - if(useDefaultSubplots) hasSubplotGrid = true; + _$setCursor_445(annTextGroupInner, csr); + }, + doneFn: function() { + _$setCursor_445(annTextGroupInner); + _$registry_514.call('relayout', gd, update); + var notesBox = document.querySelector('.js-notes-box-panel'); + if(notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } } - gridOut._hasSubplotGrid = hasSubplotGrid; - - var rowOrder = coerce('roworder'); - var reversed = rowOrder === 'top to bottom'; - gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) - }; -} + if(edits.annotationText) { + annText.call(_$svg_text_utils_449.makeEditable, {delegate: annTextGroupInner, gd: gd}) + .call(textLayout) + .on('edit', function(_text) { + options.text = _text; + this.call(textLayout); -// coerce x or y sizing attributes and return an array of domains for this direction -function fillGridPositions(axLetter, coerce, dfltGap, len, reversed) { - var dirGap = coerce(axLetter + 'gap', dfltGap); - var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + var update = {}; + update[annbase + '.text'] = options.text; - 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]; + if(xa && xa.autorange) { + update[xa._name + '.autorange'] = true; + } + if(ya && ya.autorange) { + update[ya._name + '.autorange'] = true; + } + + _$registry_514.call('relayout', gd, update); + }); } - return out; + else annText.call(textLayout); } -// 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; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 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; +'use strict'; - var axisMap = gridOut._axisMap = {}; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; - if(hasSubplotGrid) { - var subplotsIn = gridIn.subplots || []; - subplotsOut = gridOut.subplots = new Array(rows); - var index = 1; +var __draw_287 = _$draw_292.draw; - 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] = ''; +var _$calcAutorange_287 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + annotationList = _$lib_425.filterVisible(fullLayout.annotations); - 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; - } + if(!annotationList.length || !gd._fullData.length) return; - rowOut[j] = subplotId; - axisMap[xId] = j; - axisMap[yId] = i; - } - } + var annotationAxes = {}; + annotationList.forEach(function(ann) { + annotationAxes[ann.xref] = 1; + annotationAxes[ann.yref] = 1; + }); + + for(var axId in annotationAxes) { + var ax = _$axes_470.getFromId(gd, axId); + if(ax && ax.autorange) { + return _$lib_425.syncOrAsync([ + __draw_287, + annAutorange + ], gd); } } - else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); - } +}; - var anchors = gridOut._anchors = {}; - var reversed = gridOut.roworder === 'top to bottom'; +function annAutorange(gd) { + var fullLayout = gd._fullLayout; - for(var axisId in axisMap) { - var axLetter = axisId.charAt(0); - var side = gridOut[axLetter + 'side']; + // find the bounding boxes for each of these annotations' + // relative to their anchor points + // use the arrow and the text bg rectangle, + // as the whole anno may include hidden text in its bbox + _$lib_425.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_470.getFromId(gd, ann.xref), + ya = _$axes_470.getFromId(gd, ann.yref), + headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, + startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - var i0, inc, iFinal; + var headPlus, headMinus, startHeadPlus, startHeadMinus; - 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; - } - } + if(xa && xa.autorange) { + headPlus = headSize + ann.xshift; + headMinus = headSize - ann.xshift; + startHeadPlus = startHeadSize + ann.xshift; + startHeadMinus = startHeadSize - ann.xshift; + + if(ann.axref === ann.xref) { + // expand for the arrowhead (padded by arrowhead) + _$axes_470.expand(xa, [xa.r2c(ann.x)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + // again for the textbox (padded by textbox) + _$axes_470.expand(xa, [xa.r2c(ann.ax)], { + ppadplus: Math.max(ann._xpadplus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, startHeadMinus) + }); } else { - for(i = i0; i !== iFinal; i += inc) { - yId = gridOut.yaxes[i]; - if(subplots.cartesian.indexOf(axisId + yId) !== -1) { - anchors[axisId] = yId; - break; - } - } + startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; + startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; + _$axes_470.expand(xa, [xa.r2c(ann.x)], { + ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) + }); } } - 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; - } - } + + if(ya && ya.autorange) { + headPlus = headSize - ann.yshift; + headMinus = headSize + ann.yshift; + startHeadPlus = startHeadSize - ann.yshift; + startHeadMinus = startHeadSize + ann.yshift; + + if(ann.ayref === ann.yref) { + _$axes_470.expand(ya, [ya.r2c(ann.y)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + _$axes_470.expand(ya, [ya.r2c(ann.ay)], { + ppadplus: Math.max(ann._ypadplus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, startHeadMinus) + }); } else { - for(i = i0; i !== iFinal; i += inc) { - xId = gridOut.xaxes[i]; - if(subplots.cartesian.indexOf(xId + axisId) !== -1) { - anchors[axisId] = xId; - break; - } - } + startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; + startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; + _$axes_470.expand(ya, [ya.r2c(ann.y)], { + ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), + ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) + }); } } - } -} - -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; + }); } -var _$grid_285 = { - moduleType: 'component', - name: 'grid', - - schema: { - layout: {grid: gridAttrs} - }, - - layoutAttributes: gridAttrs, - sizeDefaults: sizeDefaults, - contentDefaults: contentDefaults -}; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -66738,130 +68796,126 @@ var _$grid_285 = { 'use strict'; -/* removed: var _$constants_412 = require('../../plots/cartesian/constants'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +var _$click_288 = { + hasClickToShow: hasClickToShow, + onClick: onClick +}; -var _$attributes_286 = { - _isLinkedToArray: 'image', +/* + * 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; +} - visible: { - valType: 'boolean', - - dflt: true, - editType: 'arraydraw', - - }, +/* + * 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), + onSet = toggleSets.on, + offSet = toggleSets.off.concat(toggleSets.explicitOff), + update = {}, + i; - source: { - valType: 'string', - - editType: 'arraydraw', - - }, + if(!(onSet.length || offSet.length)) return; - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, + for(i = 0; i < onSet.length; i++) { + update['annotations[' + onSet[i] + '].visible'] = true; + } - sizex: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, + for(i = 0; i < offSet.length; i++) { + update['annotations[' + offSet[i] + '].visible'] = false; + } - sizey: { - valType: 'number', - - dflt: 0, - editType: 'arraydraw', - - }, + return _$registry_514.call('update', gd, {}, update); +} - sizing: { - valType: 'enumerated', - values: ['fill', 'contain', 'stretch'], - dflt: 'contain', - - editType: 'arraydraw', - - }, +/* + * 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, + onSet = [], + offSet = [], + explicitOffSet = [], + hoverLen = (hoverData || []).length; - opacity: { - valType: 'number', - - min: 0, - max: 1, - dflt: 1, - editType: 'arraydraw', - - }, + var i, j, anni, showMode, pointj, xa, ya, toggleType; - x: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, + for(i = 0; i < annotations.length; i++) { + anni = annotations[i]; + showMode = anni.clicktoshow; - y: { - valType: 'any', - - dflt: 0, - editType: 'arraydraw', - - }, + if(showMode) { + for(j = 0; j < hoverLen; j++) { + pointj = hoverData[j]; + xa = pointj.xaxis; + ya = pointj.yaxis; - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - editType: 'arraydraw', - - }, + 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; + } + } - yanchor: { - valType: 'enumerated', - values: ['top', 'middle', 'bottom'], - dflt: 'top', - - editType: 'arraydraw', - - }, + if(j === hoverLen) { + // no match - only turn this annotation OFF, and only if + // showmode is 'onout' + if(anni.visible && showMode === 'onout') offSet.push(i); + } + } + } - xref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_412.idRegex.x.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, + return {on: onSet, off: offSet, explicitOff: explicitOffSet}; +} - yref: { - valType: 'enumerated', - values: [ - 'paper', - _$constants_412.idRegex.y.toString() - ], - dflt: 'paper', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; +// to handle log axes until v2 +function clickData2r(d, ax) { + return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -66874,19 +68928,14 @@ var _$attributes_286 = { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_388 = require('../../lib/to_log_range'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_451 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear - * you need to alter any images on that axis to keep them + * 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 (or perhaps size will still need conversion?) - * we convert size by declaring that the maximum extent *in data units* should be - * the same, assuming the image is anchored by its center (could remove that restriction - * if we think it's important) even though the actual left and right values will not be - * quite the same since the scale becomes nonlinear (and central anchor means the pixel - * center of the image, not the data units center) + * In v2.0 this will become obsolete * * gd: the plot div * ax: the axis being changed @@ -66895,7 +68944,7 @@ var _$attributes_286 = { * Use this to make the changes as it's aware if any other changes in the * same relayout call should override this conversion. */ -var _$convertCoords_287 = function convertCoords(gd, ax, newType, doExtra) { +var _$convertCoords_290 = function convertCoords(gd, ax, newType, doExtra) { ax = ax || {}; var toLog = (newType === 'log') && (ax.type === 'linear'), @@ -66903,107 +68952,32 @@ var _$convertCoords_287 = function convertCoords(gd, ax, newType, doExtra) { if(!(toLog || fromLog)) return; - var images = gd._fullLayout.images, + var annotations = gd._fullLayout.annotations, axLetter = ax._id.charAt(0), - image, - attrPrefix; - - for(var i = 0; i < images.length; i++) { - image = images[i]; - attrPrefix = 'images[' + i + '].'; - - if(image[axLetter + 'ref'] === ax._id) { - var currentPos = image[axLetter], - currentSize = image['size' + axLetter], - newPos = null, - newSize = null; - - if(toLog) { - newPos = _$toLogRange_388(currentPos, ax.range); - - // this is the inverse of the conversion we do in fromLog below - // so that the conversion is reversible (notice the fromLog conversion - // is like sinh, and this one looks like arcsinh) - var dx = currentSize / Math.pow(10, newPos) / 2; - newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; - } - else { - newPos = Math.pow(10, currentPos); - newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); - } - - // if conversion failed, delete the value so it can get a default later on - if(!_$fastIsnumeric_78(newPos)) { - newPos = null; - newSize = null; - } - else if(!_$fastIsnumeric_78(newSize)) newSize = null; - - doExtra(attrPrefix + axLetter, newPos); - doExtra(attrPrefix + 'size' + axLetter, newSize); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_403 = require('../../plots/array_container_defaults'); */; - -/* removed: var _$attributes_286 = require('./attributes'); */; -var __name_288 = 'images'; - -var _$supplyLayoutDefaults_288 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_288, - handleItemDefaults: imageDefaults - }; - - _$handleArrayContainerDefaults_403(layoutIn, layoutOut, opts); -}; - - -function imageDefaults(imageIn, imageOut, fullLayout) { - - function coerce(attr, dflt) { - return _$lib_363.coerce(imageIn, imageOut, _$attributes_286, attr, dflt); - } + ann, + attrPrefix; - var source = coerce('source'); - var visible = coerce('visible', !!source); + function convert(attr) { + var currentVal = ann[attr], + newVal = null; - if(!visible) return imageOut; + if(toLog) newVal = _$toLogRange_451(currentVal, ax.range); + else newVal = Math.pow(10, currentVal); - coerce('layer'); - coerce('xanchor'); - coerce('yanchor'); - coerce('sizex'); - coerce('sizey'); - coerce('sizing'); - coerce('opacity'); + // if conversion failed, delete the value so it gets a default value + if(!_$fastIsnumeric_135(newVal)) newVal = null; - var gdMock = { _fullLayout: fullLayout }, - axLetters = ['x', 'y']; + doExtra(attrPrefix + attr, newVal); + } - for(var i = 0; i < 2; i++) { - // 'paper' is the fallback axref - var axLetter = axLetters[i], - axRef = _$axes_407.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + for(var i = 0; i < annotations.length; i++) { + ann = annotations[i]; + attrPrefix = 'annotations[' + i + '].'; - _$axes_407.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + if(ann[axLetter + 'ref'] === ax._id) convert(axLetter); + if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter); } - - return imageOut; -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -67015,214 +68989,169 @@ function imageDefaults(imageIn, imageOut, fullLayout) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$xmlns_namespaces_345 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$color_301 = require('../color'); */; -var _$draw_289 = function draw(gd) { - var fullLayout = gd._fullLayout, - imageDataAbove = [], - imageDataSubplot = {}, - imageDataBelow = [], - subplot, - i; +// defaults common to 'annotations' and 'annotations3d' +var _$handleAnnotationCommonDefaults_289 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { + coerce('opacity'); + var bgColor = coerce('bgcolor'); - // Sort into top, subplot, and bottom layers - for(i = 0; i < fullLayout.images.length; i++) { - var img = fullLayout.images[i]; + var borderColor = coerce('bordercolor'); + var borderOpacity = _$color_301.opacity(borderColor); - if(img.visible) { - if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { - subplot = img.xref + img.yref; + coerce('borderpad'); - var plotinfo = fullLayout._plots[subplot]; + var borderWidth = coerce('borderwidth'); + var showArrow = coerce('showarrow'); - if(!plotinfo) { - // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the image to an x / y axis combination - // that doesn't have any data on it (and layer is below) - imageDataBelow.push(img); - continue; - } + coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); + coerce('textangle'); + _$lib_425.coerceFont(coerce, 'font', fullLayout.font); - if(plotinfo.mainplot) { - subplot = plotinfo.mainplot.id; - } + coerce('width'); + coerce('align'); - if(!imageDataSubplot[subplot]) { - imageDataSubplot[subplot] = []; - } - imageDataSubplot[subplot].push(img); - } else if(img.layer === 'above') { - imageDataAbove.push(img); - } else { - imageDataBelow.push(img); - } - } - } + var h = coerce('height'); + if(h) coerce('valign'); + if(showArrow) { + var arrowside = coerce('arrowside'); + var arrowhead; + var arrowsize; - var anchors = { - x: { - left: { sizing: 'xMin', offset: 0 }, - center: { sizing: 'xMid', offset: -1 / 2 }, - right: { sizing: 'xMax', offset: -1 } - }, - y: { - top: { sizing: 'YMin', offset: 0 }, - middle: { sizing: 'YMid', offset: -1 / 2 }, - bottom: { sizing: 'YMax', offset: -1 } + if(arrowside.indexOf('end') !== -1) { + arrowhead = coerce('arrowhead'); + arrowsize = coerce('arrowsize'); } - }; - - - // Images must be converted to dataURL's for exporting. - function setImage(d) { - var thisImage = _$d3_68.select(this); - if(this.img && this.img.src === d.source) { - return; + if(arrowside.indexOf('start') !== -1) { + coerce('startarrowhead', arrowhead); + coerce('startarrowsize', arrowsize); } + coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_301.defaultLine); + coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); + coerce('standoff'); + coerce('startstandoff'); - thisImage.attr('xmlns', _$xmlns_namespaces_345.svg); + } - var imagePromise = new Promise(function(resolve) { + var hoverText = coerce('hovertext'); + var globalHoverLabel = fullLayout.hoverlabel || {}; - var img = new Image(); - this.img = img; + if(hoverText) { + var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || + (_$color_301.opacity(bgColor) ? _$color_301.rgb(bgColor) : _$color_301.defaultLine) + ); - // If not set, a `tainted canvas` error is thrown - img.setAttribute('crossOrigin', 'anonymous'); - img.onerror = errorHandler; - img.onload = function() { - var canvas = document.createElement('canvas'); - canvas.width = this.width; - canvas.height = this.height; + var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || + _$color_301.contrast(hoverBG) + ); - var ctx = canvas.getContext('2d'); - ctx.drawImage(this, 0, 0); + _$lib_425.coerceFont(coerce, 'hoverlabel.font', { + family: globalHoverLabel.font.family, + size: globalHoverLabel.font.size, + color: globalHoverLabel.font.color || hoverBorder + }); + } - var dataURL = canvas.toDataURL('image/png'); + coerce('captureevents', !!hoverText); +}; - thisImage.attr('xlink:href', dataURL); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // resolve promise in onload handler instead of on 'load' to support IE11 - // see https://github.com/plotly/plotly.js/issues/1685 - // for more details - resolve(); - }; +'use strict'; - thisImage.on('error', errorHandler); +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleAnnotationCommonDefaults_289 = require('./common_defaults'); */; +/* removed: var _$attributes_286 = require('./attributes'); */; - img.src = d.source; - function errorHandler() { - thisImage.remove(); - resolve(); - } - }.bind(this)); +var _$handleAnnotationDefaults_284 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; - gd._promises.push(imagePromise); + function coerce(attr, dflt) { + return _$lib_425.coerce(annIn, annOut, _$attributes_286, attr, dflt); } - function applyAttributes(d) { - var thisImage = _$d3_68.select(this); - - // Axes if specified - var xa = _$axes_407.getFromId(gd, d.xref), - ya = _$axes_407.getFromId(gd, d.yref); + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + var clickToShow = coerce('clicktoshow'); - var size = fullLayout._size, - width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, - height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; + if(!(visible || clickToShow)) return annOut; - // Offsets for anchor positioning - var xOffset = width * anchors.x[d.xanchor].offset, - yOffset = height * anchors.y[d.yanchor].offset; + _$handleAnnotationCommonDefaults_289(annIn, annOut, fullLayout, coerce); - var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; + var showArrow = annOut.showarrow; - // Final positions - var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, - yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; + // positioning + var axLetters = ['x', 'y'], + arrowPosDflt = [-10, -30], + gdMock = {_fullLayout: fullLayout}; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i]; + // xref, yref + var axRef = _$axes_470.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); - // Construct the proper aspectRatio attribute - switch(d.sizing) { - case 'fill': - sizing += ' slice'; - break; + // x, y + _$axes_470.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); - case 'stretch': - sizing = 'none'; - break; - } + if(showArrow) { + var arrowPosAttr = 'a' + axLetter, + // axref, ayref + aaxRef = _$axes_470.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); - thisImage.attr({ - x: xPos, - y: yPos, - width: width, - height: height, - preserveAspectRatio: sizing, - opacity: d.opacity - }); + // for now the arrow can only be on the same axis or specified as pixels + // TODO: sometime it might be interesting to allow it to be on *any* axis + // but that would require updates to drawing & autorange code and maybe more + if(aaxRef !== 'pixel' && aaxRef !== axRef) { + aaxRef = annOut[arrowPosAttr] = 'pixel'; + } + // ax, ay + var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; + _$axes_470.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + } - // Set proper clipping on images - var xId = xa ? xa._id : '', - yId = ya ? ya._id : '', - clipAxes = xId + yId; + // xanchor, yanchor + coerce(axLetter + 'anchor'); - thisImage.call(_$drawing_264.setClipUrl, clipAxes ? - ('clip' + fullLayout._uid + clipAxes) : - null - ); + // xshift, yshift + coerce(axLetter + 'shift'); } - var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') - .data(imageDataBelow), - imagesAbove = fullLayout._imageUpperLayer.selectAll('image') - .data(imageDataAbove); - - imagesBelow.enter().append('image'); - imagesAbove.enter().append('image'); - - imagesBelow.exit().remove(); - imagesAbove.exit().remove(); - - imagesBelow.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - imagesAbove.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); - - var allSubplots = Object.keys(fullLayout._plots); - for(i = 0; i < allSubplots.length; i++) { - subplot = allSubplots[i]; - var subplotObj = fullLayout._plots[subplot]; - - // filter out overlaid plots (which havd their images on the main plot) - // and gl2d plots (which don't support below images, at least not yet) - if(!subplotObj.imagelayer) continue; + // if you have one coordinate you should have both + _$lib_425.noneOrAll(annIn, annOut, ['x', 'y']); - var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') - // even if there are no images on this subplot, we need to run - // enter and exit in case there were previously - .data(imageDataSubplot[subplot] || []); + // if you have one part of arrow length you should have both + if(showArrow) { + _$lib_425.noneOrAll(annIn, annOut, ['ax', 'ay']); + } - imagesOnSubplot.enter().append('image'); - imagesOnSubplot.exit().remove(); + if(clickToShow) { + var xClick = coerce('xclick'); + var yClick = coerce('yclick'); - imagesOnSubplot.each(function(d) { - setImage.bind(this)(d); - applyAttributes.bind(this)(d); - }); + // put the actual click data to bind to into private attributes + // so we don't have to do this little bit of logic on every hover event + annOut._xclick = (xClick === undefined) ? + annOut.x : + _$axes_470.cleanPosition(xClick, gdMock, annOut.xref); + annOut._yclick = (yClick === undefined) ? + annOut.y : + _$axes_470.cleanPosition(yClick, gdMock, annOut.yref); } + + return annOut; }; /** @@ -67235,121 +69164,75 @@ var _$draw_289 = function draw(gd) { 'use strict'; -var _$images_290 = { - moduleType: 'component', - name: 'images', +/* removed: var _$lib_425 = require('../lib'); */; - layoutAttributes: _$attributes_286, - supplyLayoutDefaults: _$supplyLayoutDefaults_288, - includeBasePlot: _$makeIncludeComponents_417('images'), +/** Convenience wrapper for making array container logic DRY and consistent + * + * @param {object} parentObjIn + * user input object where the container in question is linked + * (i.e. either a user trace object or the user layout object) + * + * @param {object} parentObjOut + * full object where the coerced container will be linked + * (i.e. either a full trace object or the full layout object) + * + * @param {object} opts + * options object: + * - name {string} + * name of the key linking the container in question + * - handleItemDefaults {function} + * defaults method to be called on each item in the array container in question + * + * Its arguments are: + * - itemIn {object} item in user layout + * - itemOut {object} item in full layout + * - parentObj {object} (as in closure) + * - opts {object} (as in closure) + * - itemOpts {object} + * - itemIsNotPlainObject {boolean} + * N.B. + * + * - opts is passed to handleItemDefaults so it can also store + * links to supplementary data (e.g. fullData for layout components) + * + */ +var _$handleArrayContainerDefaults_466 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { + var name = opts.name; - draw: _$draw_289, + var previousContOut = parentObjOut[name]; - convertCoords: _$convertCoords_287 -}; + var contIn = _$lib_425.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + contOut = parentObjOut[name] = [], + i; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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(i = 0; i < contIn.length; i++) { + var itemIn = contIn[i], + itemOut = {}, + itemOpts = {}; -'use strict'; + if(!_$lib_425.isPlainObject(itemIn)) { + itemOpts.itemIsNotPlainObject = true; + itemIn = {}; + } -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_238 = require('../color/attributes'); */; + opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts); + itemOut._input = itemIn; + itemOut._index = i; -var _$attributes_292 = { - bgcolor: { - valType: 'color', - - editType: 'legend', - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_238.defaultLine, - - editType: 'legend', - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, - - editType: 'legend', - - }, - font: _$font_attributes_434({ - editType: 'legend', - - }), - orientation: { - valType: 'enumerated', - values: ['v', 'h'], - dflt: 'v', - - editType: 'legend', - - }, - traceorder: { - valType: 'flaglist', - flags: ['reversed', 'grouped'], - extras: ['normal'], - - editType: 'legend', - - }, - tracegroupgap: { - valType: 'number', - min: 0, - dflt: 10, - - editType: 'legend', - - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 1.02, - - editType: 'legend', - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - - editType: 'legend', - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, - - editType: 'legend', - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'auto', - - editType: 'legend', - - }, - editType: 'legend' + contOut.push(itemOut); + } + + // in case this array gets its defaults rebuilt independent of the whole layout, + // relink the private keys just for this array. + if(_$lib_425.isArrayOrTypedArray(previousContOut)) { + var len = Math.min(previousContOut.length, contOut.length); + for(i = 0; i < len; i++) { + _$lib_425.relinkPrivateKeys(contOut[i], previousContOut[i]); + } + } }; -var _$helpers_298 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67361,26 +69244,17 @@ var _$helpers_298 = {}; 'use strict'; -_$helpers_298.legendGetsTrace = function legendGetsTrace(trace) { - // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? - // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. - - // Note that we explicitly include showlegend: false, so a trace that *could* be - // in the legend but is not shown still counts toward the two traces you need to - // ensure the legend is shown by default, because this can still help disambiguate. - return trace.visible && (trace.showlegend !== undefined); -}; +/* removed: var _$handleArrayContainerDefaults_466 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationDefaults_284 = require('./annotation_defaults'); */; -_$helpers_298.isGrouped = function isGrouped(legendLayout) { - return (legendLayout.traceorder || '').indexOf('grouped') !== -1; -}; -_$helpers_298.isVertical = function isVertical(legendLayout) { - return legendLayout.orientation !== 'h'; -}; +var _$supplyLayoutDefaults_291 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'annotations', + handleItemDefaults: _$handleAnnotationDefaults_284 + }; -_$helpers_298.isReversed = function isReversed(legendLayout) { - return (legendLayout.traceorder || '').indexOf('reversed') !== -1; + _$handleArrayContainerDefaults_466(layoutIn, layoutOut, opts); }; /** @@ -67394,88 +69268,102 @@ _$helpers_298.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; - -/* removed: var _$attributes_292 = require('./attributes'); */; -/* removed: var _$layout_attributes_442 = require('../../plots/layout_attributes'); */; -/* removed: var _$helpers_298 = require('./helpers'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/** + * 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 + */ +var _$makeIncludeComponents_480 = function makeIncludeComponents(containerArrayName) { + return function includeComponents(layoutIn, layoutOut) { + var array = layoutIn[containerArrayName]; + if(!Array.isArray(array)) return; -var _$legendDefaults_294 = function legendDefaults(layoutIn, layoutOut, fullData) { - var containerIn = layoutIn.legend || {}; - var containerOut = {}; + var Cartesian = _$registry_514.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'); - var visibleTraces = 0; - var defaultOrder = 'normal'; + for(var i = 0; i < array.length; i++) { + var itemi = array[i]; + if(!_$lib_425.isPlainObject(itemi)) continue; - var defaultX, defaultY, defaultXAnchor, defaultYAnchor; + var xref = itemi.xref; + var yref = itemi.yref; - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + var hasXref = idRegex.x.test(xref); + var hasYref = idRegex.y.test(yref); + if(hasXref || hasYref) { + if(!hasCartesianOrGL2D) _$lib_425.pushUnique(layoutOut._basePlotModules, Cartesian); - if(_$helpers_298.legendGetsTrace(trace)) { - visibleTraces++; - // always show the legend by default if there's a pie - if(_$registry_451.traceIs(trace, 'pie')) visibleTraces++; - } + 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; + } - if((_$registry_451.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || - ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { - defaultOrder = _$helpers_298.isGrouped({traceorder: defaultOrder}) ? - 'grouped+reversed' : 'reversed'; + /* + * 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); + } + } } + }; +}; - if(trace.legendgroup !== undefined && trace.legendgroup !== '') { - defaultOrder = _$helpers_298.isReversed({traceorder: defaultOrder}) ? - 'reversed+grouped' : 'grouped'; - } - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function coerce(attr, dflt) { - return _$lib_363.coerce(containerIn, containerOut, _$attributes_292, attr, dflt); - } - var showLegend = _$lib_363.coerce(layoutIn, layoutOut, - _$layout_attributes_442, 'showlegend', visibleTraces > 1); +'use strict'; - if(showLegend === false) return; +/* removed: var _$draw_292 = require('./draw'); */; +/* removed: var _$click_288 = require('./click'); */; - layoutOut.legend = containerOut; +var _$annotations_294 = { + moduleType: 'component', + name: 'annotations', - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - _$lib_363.coerceFont(coerce, 'font', layoutOut.font); + layoutAttributes: _$attributes_286, + supplyLayoutDefaults: _$supplyLayoutDefaults_291, + includeBasePlot: _$makeIncludeComponents_480('annotations'), - coerce('orientation'); - if(containerOut.orientation === 'h') { - var xaxis = layoutIn.xaxis; - if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = 1.1; - defaultYAnchor = 'bottom'; - } - else { - defaultX = 0; - defaultXAnchor = 'left'; - defaultY = -0.1; - defaultYAnchor = 'top'; - } - } + calcAutorange: _$calcAutorange_287, + draw: _$draw_292.draw, + drawOne: _$draw_292.drawOne, + drawRaw: _$draw_292.drawRaw, - coerce('traceorder', defaultOrder); - if(_$helpers_298.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); + hasClickToShow: _$click_288.hasClickToShow, + onClick: _$click_288.onClick, - coerce('x', defaultX); - coerce('xanchor', defaultXAnchor); - coerce('y', defaultY); - coerce('yanchor', defaultYAnchor); - _$lib_363.noneOrAll(containerIn, containerOut, ['x', 'y']); + convertCoords: _$convertCoords_290 }; -var _$anchor_utils_291 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67487,42 +69375,82 @@ var _$anchor_utils_291 = {}; 'use strict'; +/* removed: var _$attributes_286 = require('../annotations/attributes'); */; +var __overrideAll_295 = _$edit_types_455.overrideAll; -/** - * 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. - */ +var _$attributes_295 = __overrideAll_295({ + _isLinkedToArray: 'annotation', -_$anchor_utils_291.isRightAnchor = function isRightAnchor(opts) { - return ( - opts.xanchor === 'right' || - (opts.xanchor === 'auto' && opts.x >= 2 / 3) - ); -}; + visible: _$attributes_286.visible, + x: { + valType: 'any', + + + }, + y: { + valType: 'any', + + + }, + z: { + valType: 'any', + + + }, + ax: { + valType: 'number', + + + }, + ay: { + valType: 'number', + + + }, -_$anchor_utils_291.isCenterAnchor = function isCenterAnchor(opts) { - return ( - opts.xanchor === 'center' || - (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) - ); -}; + xanchor: _$attributes_286.xanchor, + xshift: _$attributes_286.xshift, + yanchor: _$attributes_286.yanchor, + yshift: _$attributes_286.yshift, + + text: _$attributes_286.text, + textangle: _$attributes_286.textangle, + font: _$attributes_286.font, + width: _$attributes_286.width, + height: _$attributes_286.height, + opacity: _$attributes_286.opacity, + align: _$attributes_286.align, + valign: _$attributes_286.valign, + bgcolor: _$attributes_286.bgcolor, + bordercolor: _$attributes_286.bordercolor, + borderpad: _$attributes_286.borderpad, + borderwidth: _$attributes_286.borderwidth, + showarrow: _$attributes_286.showarrow, + arrowcolor: _$attributes_286.arrowcolor, + arrowhead: _$attributes_286.arrowhead, + startarrowhead: _$attributes_286.startarrowhead, + arrowside: _$attributes_286.arrowside, + arrowsize: _$attributes_286.arrowsize, + startarrowsize: _$attributes_286.startarrowsize, + arrowwidth: _$attributes_286.arrowwidth, + standoff: _$attributes_286.standoff, + startstandoff: _$attributes_286.startstandoff, + hovertext: _$attributes_286.hovertext, + hoverlabel: _$attributes_286.hoverlabel, + captureevents: _$attributes_286.captureevents, -_$anchor_utils_291.isBottomAnchor = function isBottomAnchor(opts) { - return ( - opts.yanchor === 'bottom' || - (opts.yanchor === 'auto' && opts.y <= 1 / 3) - ); -}; + // maybes later? + // clicktoshow: annAtts.clicktoshow, + // xclick: annAtts.xclick, + // yclick: annAtts.yclick, -_$anchor_utils_291.isMiddleAnchor = function isMiddleAnchor(opts) { - return ( - opts.yanchor === 'middle' || - (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) - ); -}; + // not needed! + // axref: 'pixel' + // ayref: 'pixel' + // xref: 'x' + // yref: 'y + // zref: 'z' +}, 'calc', 'from-root'); /** * Copyright 2012-2018, Plotly, Inc. @@ -67534,13 +69462,60 @@ _$anchor_utils_291.isMiddleAnchor = function isMiddleAnchor(opts) { 'use strict'; -var _$constants_293 = { - scrollBarWidth: 6, - scrollBarMinHeight: 20, - scrollBarColor: '#808BA4', - scrollBarMargin: 4 +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; + +var _$convert_296 = function convert(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var anns = fullSceneLayout.annotations; + + for(var i = 0; i < anns.length; i++) { + mockAnnAxes(anns[i], scene); + } + + scene.fullLayout._infolayer + .selectAll('.annotation-' + scene.id) + .remove(); }; +function mockAnnAxes(ann, scene) { + var fullSceneLayout = scene.fullSceneLayout; + var domain = fullSceneLayout.domain; + var size = scene.fullLayout._size; + + var base = { + // this gets fill in on render + pdata: null, + + // to get setConvert to not execute cleanly + type: 'linear', + + // don't try to update them on `editable: true` + autorange: false, + + // set infinite range so that annotation draw routine + // does not try to remove 'outside-range' annotations, + // this case is handled in the render loop + range: [-Infinity, Infinity] + }; + + ann._xa = {}; + _$lib_425.extendFlat(ann._xa, base); + _$axes_470.setConvert(ann._xa); + ann._xa._offset = size.l + domain.x[0] * size.w; + ann._xa.l2p = function() { + return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); + }; + + ann._ya = {}; + _$lib_425.extendFlat(ann._ya, base); + _$axes_470.setConvert(ann._ya); + ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; + ann._ya.l2p = function() { + return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); + }; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67549,101 +69524,74 @@ var _$constants_293 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$helpers_298 = require('./helpers'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_466 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationCommonDefaults_289 = require('../annotations/common_defaults'); */; +/* removed: var _$attributes_295 = require('./attributes'); */; +var _$handleDefaults_297 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + _$handleArrayContainerDefaults_466(sceneLayoutIn, sceneLayoutOut, { + name: 'annotations', + handleItemDefaults: __handleAnnotationDefaults_297, + fullLayout: opts.fullLayout + }); +}; -var _$getLegendData_296 = function getLegendData(calcdata, opts) { - var lgroupToTraces = {}, - lgroups = [], - hasOneNonBlankGroup = false, - slicesShown = {}, - lgroupi = 0; +function __handleAnnotationDefaults_297(annIn, annOut, sceneLayout, opts, itemOpts) { + function coerce(attr, dflt) { + return _$lib_425.coerce(annIn, annOut, _$attributes_295, attr, dflt); + } - var i, j; + function coercePosition(axLetter) { + var axName = axLetter + 'axis'; - function addOneItem(legendGroup, legendItem) { - // each '' legend group is treated as a separate group - if(legendGroup === '' || !_$helpers_298.isGrouped(opts)) { - var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? + // mock in such way that getFromId grabs correct 3D axis + var gdMock = { _fullLayout: {} }; + gdMock._fullLayout[axName] = sceneLayout[axName]; - lgroups.push(uniqueGroup); - lgroupToTraces[uniqueGroup] = [[legendItem]]; - lgroupi++; - } - else if(lgroups.indexOf(legendGroup) === -1) { - lgroups.push(legendGroup); - hasOneNonBlankGroup = true; - lgroupToTraces[legendGroup] = [[legendItem]]; - } - else lgroupToTraces[legendGroup].push([legendItem]); + return _$axes_470.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } - // build an { legendgroup: [cd0, cd0], ... } object - for(i = 0; i < calcdata.length; i++) { - var cd = calcdata[i], - cd0 = cd[0], - trace = cd0.trace, - lgroup = trace.legendgroup; - - if(!_$helpers_298.legendGetsTrace(trace) || !trace.showlegend) continue; - - if(_$registry_451.traceIs(trace, 'pie')) { - if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; - for(j = 0; j < cd.length; j++) { - var labelj = cd[j].label; + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + if(!visible) return annOut; - if(!slicesShown[lgroup][labelj]) { - addOneItem(lgroup, { - label: labelj, - color: cd[j].color, - i: cd[j].i, - trace: trace - }); + _$handleAnnotationCommonDefaults_289(annIn, annOut, opts.fullLayout, coerce); - slicesShown[lgroup][labelj] = true; - } - } - } + coercePosition('x'); + coercePosition('y'); + coercePosition('z'); - else addOneItem(lgroup, cd0); - } + // if you have one coordinate you should all three + _$lib_425.noneOrAll(annIn, annOut, ['x', 'y', 'z']); - // won't draw a legend in this case - if(!lgroups.length) return []; + // hard-set here for completeness + annOut.xref = 'x'; + annOut.yref = 'y'; + annOut.zref = 'z'; - // rearrange lgroupToTraces into a d3-friendly array of arrays - var lgroupsLength = lgroups.length, - ltraces, - legendData; + coerce('xanchor'); + coerce('yanchor'); + coerce('xshift'); + coerce('yshift'); - if(hasOneNonBlankGroup && _$helpers_298.isGrouped(opts)) { - legendData = new Array(lgroupsLength); + if(annOut.showarrow) { + annOut.axref = 'pixel'; + annOut.ayref = 'pixel'; - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]]; - legendData[i] = _$helpers_298.isReversed(opts) ? ltraces.reverse() : ltraces; - } - } - else { - // collapse all groups into one if all groups are blank - legendData = [new Array(lgroupsLength)]; + // TODO maybe default values should be bigger than the 2D case? + coerce('ax', -10); + coerce('ay', -30); - for(i = 0; i < lgroupsLength; i++) { - ltraces = lgroupToTraces[lgroups[i]][0]; - legendData[0][_$helpers_298.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; - } - lgroupsLength = 1; + // if you have one part of arrow length you should have both + _$lib_425.noneOrAll(annIn, annOut, ['ax', 'ay']); } - // needed in repositionLegend - opts._lgroupsLength = lgroupsLength; - return legendData; -}; + return annOut; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -67653,222 +69601,243 @@ var _$getLegendData_296 = function getLegendData(calcdata, opts) { * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$registry_451 = require('../../registry'); */; +'use strict'; -var SHOWISOLATETIP = true; +function xformMatrix(m, v) { + var out = [0, 0, 0, 0]; + var i, j; -var _$handleClick_297 = function handleClick(g, gd, numClicks) { - if(gd._dragged || gd._editing) return; + for(i = 0; i < 4; ++i) { + for(j = 0; j < 4; ++j) { + out[j] += m[4 * i + j] * v[i]; + } + } - var hiddenSlices = gd._fullLayout.hiddenlabels ? - gd._fullLayout.hiddenlabels.slice() : - []; + return out; +} - var legendItem = g.data()[0][0]; - var fullData = gd._fullData; - var fullTrace = legendItem.trace; - var legendgroup = fullTrace.legendgroup; +function project(camera, v) { + var p = xformMatrix(camera.projection, + xformMatrix(camera.view, + xformMatrix(camera.model, [v[0], v[1], v[2], 1]))); + return p; +} - var i, j, kcont, key, keys, val; - var attrUpdate = {}; - var attrIndices = []; - var carrs = []; - var carrIdx = []; +var _$project_503 = project; - function insertUpdate(traceIndex, key, value) { - var attrIndex = attrIndices.indexOf(traceIndex); - var valueArray = attrUpdate[key]; - if(!valueArray) { - valueArray = attrUpdate[key] = []; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(attrIndices.indexOf(traceIndex) === -1) { - attrIndices.push(traceIndex); - attrIndex = attrIndices.length - 1; - } +'use strict'; - valueArray[attrIndex] = value; +var __drawRaw_298 = _$draw_292.drawRaw; +/* removed: var _$project_503 = require('../../plots/gl3d/project'); */; +var axLetters = ['x', 'y', 'z']; - return attrIndex; - } +var _$draw_298 = function draw(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var dataScale = scene.dataScale; + var anns = fullSceneLayout.annotations; - function setVisibility(fullTrace, visibility) { - var fullInput = fullTrace._fullInput; - if(_$registry_451.hasTransform(fullInput, 'groupby')) { - var kcont = carrs[fullInput.index]; - if(!kcont) { - var groupbyIndices = _$registry_451.getTransformIndices(fullInput, 'groupby'); - var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_363.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); - carrs[fullInput.index] = kcont; - } + for(var i = 0; i < anns.length; i++) { + var ann = anns[i]; + var annotationIsOffscreen = false; - var curState = kcont.get(fullTrace._group); + for(var j = 0; j < 3; j++) { + var axLetter = axLetters[j]; + var pos = ann[axLetter]; + var ax = fullSceneLayout[axLetter + 'axis']; + var posFraction = ax.r2fraction(pos); - // If 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(posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + break; } + } - 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); + if(annotationIsOffscreen) { + scene.fullLayout._infolayer + .select('.annotation-' + scene.id + '[data-index="' + i + '"]') + .remove(); } else { - // false -> false (not possible since will not be visible in legend) - // true -> legendonly - // legendonly -> true - var nextVisibility = fullInput.visible === false ? false : visibility; + ann._pdata = _$project_503(scene.glplot.cameraParams, [ + fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], + fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], + fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] + ]); - insertUpdate(fullInput.index, 'visible', nextVisibility); + __drawRaw_298(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); } } +}; - if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_363.notifier(_$lib_363._(gd, 'Double-click on legend to isolate one trace'), 'long'); - SHOWISOLATETIP = false; - } else { - SHOWISOLATETIP = false; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(_$registry_451.traceIs(fullTrace, 'pie')) { - var thisLabel = legendItem.label, - thisLabelIndex = hiddenSlices.indexOf(thisLabel); +'use strict'; - if(numClicks === 1) { - if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); - else hiddenSlices.splice(thisLabelIndex, 1); - } else if(numClicks === 2) { - 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 = []; - } - } +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; - _$registry_451.call('relayout', 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); - } - } - } +var _$annotations3d_299 = { + moduleType: 'component', + name: 'annotations3d', - if(numClicks === 1) { - var nextVisibility; + schema: { + subplots: { + scene: {annotations: _$attributes_295} + } + }, - switch(fullTrace.visible) { - case true: - nextVisibility = 'legendonly'; - break; - case false: - nextVisibility = false; - break; - case 'legendonly': - nextVisibility = true; - break; - } + layoutAttributes: _$attributes_295, + handleDefaults: _$handleDefaults_297, + includeBasePlot: includeGL3D, - 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(numClicks === 2) { - // 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, otherState; - var isIsolated = true; - for(i = 0; i < fullData.length; i++) { - isClicked = fullData[i] === fullTrace; - if(isClicked) continue; + convert: _$convert_296, + draw: _$draw_298 +}; - isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); +function includeGL3D(layoutIn, layoutOut) { + var GL3D = _$registry_514.subplotsRegistry.gl3d; + if(!GL3D) return; - if(!isInGroup && fullData[i].visible === true && !_$registry_451.traceIs(fullData[i], 'notLegendIsolatable')) { - isIsolated = false; - break; - } - } + var attrRegex = GL3D.attrRegex; - for(i = 0; i < fullData.length; i++) { - // False is sticky; we don't change it. - if(fullData[i].visible === false) continue; + var keys = Object.keys(layoutIn); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { + _$lib_425.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_425.pushUnique(layoutOut._subplots.gl3d, k); + } + } +} - if(_$registry_451.traceIs(fullData[i], 'notLegendIsolatable')) { - continue; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - switch(fullTrace.visible) { - case 'legendonly': - setVisibility(fullData[i], true); - break; - case true: - otherState = isIsolated ? true : 'legendonly'; - isClicked = fullData[i] === fullTrace; - isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); - setVisibility(fullData[i], isInGroup ? true : otherState); - break; - } - } - } +'use strict'; - 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]; - } - } +var _$attributes_328 = { + visible: { + valType: 'boolean', + + editType: 'calc', + + }, + type: { + valType: 'enumerated', + values: ['percent', 'constant', 'sqrt', 'data'], + + editType: 'calc', + + }, + symmetric: { + valType: 'boolean', + + editType: 'calc', + + }, + array: { + valType: 'data_array', + editType: 'calc', + + }, + arrayminus: { + valType: 'data_array', + editType: 'calc', + + }, + value: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'calc', + + }, + valueminus: { + valType: 'number', + min: 0, + dflt: 10, + + editType: 'calc', + + }, + traceref: { + valType: 'integer', + min: 0, + dflt: 0, + + editType: 'style' + }, + tracerefminus: { + valType: 'integer', + min: 0, + dflt: 0, + + editType: 'style' + }, + copy_ystyle: { + valType: 'boolean', + + editType: 'plot' + }, + copy_zstyle: { + valType: 'boolean', + + editType: 'style' + }, + color: { + valType: 'color', + + editType: 'style', + + }, + thickness: { + valType: 'number', + min: 0, + dflt: 2, + + editType: 'style', + + }, + width: { + valType: 'number', + min: 0, + + editType: 'plot', + + }, + editType: 'calc', - // 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; - } - } + _deprecated: { + opacity: { + valType: 'number', + + editType: 'style', + } - - _$registry_451.call('restyle', gd, attrUpdate, attrIndices); } }; -var _$helpers_505 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67877,61 +69846,100 @@ var _$helpers_505 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -_$helpers_505.formatPiePercent = function formatPiePercent(v, separators) { - var vRounded = (v * 100).toPrecision(3); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_363.numSeparate(vRounded, separators) + '%'; -}; +/** + * 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 " + */ +var _$makeComputeError_330 = function makeComputeError(opts) { + var type = opts.type, + symmetric = opts.symmetric; -_$helpers_505.formatPieValue = function formatPieValue(v, separators) { - var vRounded = v.toPrecision(10); - if(vRounded.lastIndexOf('.') !== -1) { - vRounded = vRounded.replace(/[.]?0+$/, ''); - } - return _$lib_363.numSeparate(vRounded, separators); -}; + if(type === 'data') { + var array = opts.array || []; -_$helpers_505.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) return v; + 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), + computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); -_$helpers_505.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_505.getFirstFilled(item, indices); - else if(item) return item; + 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) + ]; + }; + } + } }; /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$color_239 = require('../../components/color'); */; -var castOption = _$helpers_505.castOption; - -var _$styleOne_506 = function styleOne(s, pt, trace) { - var line = trace.marker.line; - var lineColor = castOption(line.color, pt.pts) || _$color_239.defaultLine; - var lineWidth = castOption(line.width, pt.pts) || 0; - - s.style({'stroke-width': lineWidth}) - .call(_$color_239.fill, pt.color) - .call(_$color_239.stroke, lineColor); -}; + * 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)); + }; + } +} /** * Copyright 2012-2018, Plotly, Inc. @@ -67944,225 +69952,128 @@ var _$styleOne_506 = function styleOne(s, pt, trace) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$color_239 = require('../color'); */; - -/* removed: var _$subtypes_534 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_506 = require('../../traces/pie/style_one'); */; - +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -var _$style_300 = function style(s, gd) { - s.each(function(d) { - var traceGroup = _$d3_68.select(this); - - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); - layers.style('opacity', d[0].trace.opacity); - - var fill = layers - .selectAll('g.legendfill') - .data([d]); - fill.enter().append('g') - .classed('legendfill', true); +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; - var line = layers - .selectAll('g.legendlines') - .data([d]); - line.enter().append('g') - .classed('legendlines', true); +/* removed: var _$makeComputeError_330 = require('./compute_error'); */; - var symbol = layers - .selectAll('g.legendsymbols') - .data([d]); - symbol.enter().append('g') - .classed('legendsymbols', true); - symbol.selectAll('g.legendpoints') - .data([d]) - .enter().append('g') - .classed('legendpoints', true); - }) - .each(styleBars) - .each(styleBoxes) - .each(stylePies) - .each(styleLines) - .each(stylePoints); +var _$calc_329 = function calc(gd) { + var calcdata = gd.calcdata; - function styleLines(d) { - var trace = d[0].trace; - var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_534.hasLines(trace); - var contours = trace.contours; + for(var i = 0; i < calcdata.length; i++) { + var calcTrace = calcdata[i], + trace = calcTrace[0].trace; - if(contours && contours.type === 'constraint') { - showLine = contours.showlines; - showFill = contours._operation !== '='; - } + if(!_$registry_514.traceIs(trace, 'errorBarsOK')) continue; - var fill = _$d3_68.select(this).select('.legendfill').selectAll('path') - .data(showFill ? [d] : []); - fill.enter().append('path').classed('js-fill', true); - fill.exit().remove(); - fill.attr('d', 'M5,0h30v6h-30z') - .call(_$drawing_264.fillGroupStyle); + var xa = _$axes_470.getFromId(gd, trace.xaxis), + ya = _$axes_470.getFromId(gd, trace.yaxis); - var line = _$d3_68.select(this).select('.legendlines').selectAll('path') - .data(showLine ? [d] : []); - line.enter().append('path').classed('js-line', true) - .attr('d', 'M5,0h30'); - line.exit().remove(); - line.call(_$drawing_264.lineGroupStyle); + calcOneAxis(calcTrace, trace, xa, 'x'); + calcOneAxis(calcTrace, trace, ya, 'y'); } +}; - function stylePoints(d) { - var d0 = d[0], - trace = d0.trace, - showMarkers = _$subtypes_534.hasMarkers(trace), - showText = _$subtypes_534.hasText(trace), - showLines = _$subtypes_534.hasLines(trace); +function calcOneAxis(calcTrace, trace, axis, coord) { + var opts = trace['error_' + coord] || {}, + isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1), + vals = []; - var dMod, tMod; + if(!isVisible) return; - // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; - // use d0.trace to infer arrayOk attributes + var computeError = _$makeComputeError_330(opts); - function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_363.nestedProperty(trace, attrIn).get(), - valToBound = (Array.isArray(valIn) && arrayToValFn) ? - arrayToValFn(valIn) : valIn; + for(var i = 0; i < calcTrace.length; i++) { + var calcPt = calcTrace[i], + calcCoord = calcPt[coord]; - if(bounds) { - if(valToBound < bounds[0]) return bounds[0]; - else if(valToBound > bounds[1]) return bounds[1]; - } - return valToBound; - } + if(!_$fastIsnumeric_135(axis.c2l(calcCoord))) continue; - function pickFirst(array) { return array[0]; } + var errors = computeError(calcCoord, i); + if(_$fastIsnumeric_135(errors[0]) && _$fastIsnumeric_135(errors[1])) { + var shoe = calcPt[coord + 's'] = calcCoord - errors[0], + hat = calcPt[coord + 'h'] = calcCoord + errors[1]; + vals.push(shoe, hat); + } + } - // constrain text, markers, etc so they'll fit on the legend - if(showMarkers || showText || showLines) { - var dEdit = {}, - tEdit = {}; + _$axes_470.expand(axis, vals, {padded: true}); +} - if(showMarkers) { - dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_363.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_363.mean, [2, 16]); - dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_363.mean, [0, 5]); - tEdit.marker = { - sizeref: 1, - sizemin: 1, - sizemode: 'diameter' - }; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(showLines) { - tEdit.line = { - width: boundVal('line.width', pickFirst, [0, 10]) - }; - } +'use strict'; - if(showText) { - dEdit.tx = 'Aa'; - dEdit.tp = boundVal('textposition', pickFirst); - dEdit.ts = 10; - dEdit.tc = boundVal('textfont.color', pickFirst); - dEdit.tf = boundVal('textfont.family', pickFirst); - } +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; - dMod = [_$lib_363.minExtend(d0, dEdit)]; - tMod = _$lib_363.minExtend(trace, tEdit); - } +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; - var ptgroup = _$d3_68.select(this).select('g.legendpoints'); +/* removed: var _$attributes_328 = require('./attributes'); */; - var pts = ptgroup.selectAll('path.scatterpts') - .data(showMarkers ? dMod : []); - pts.enter().append('path').classed('scatterpts', true) - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.call(_$drawing_264.pointStyle, tMod, gd); - // 'mrc' is set in pointStyle and used in textPointStyle: - // constrain it here - if(showMarkers) dMod[0].mrc = 3; +var _$defaults_331 = function(traceIn, traceOut, defaultColor, opts) { + var objName = 'error_' + opts.axis, + containerOut = traceOut[objName] = {}, + containerIn = traceIn[objName] || {}; - var txt = ptgroup.selectAll('g.pointtext') - .data(showText ? dMod : []); - txt.enter() - .append('g').classed('pointtext', true) - .append('text').attr('transform', 'translate(20,0)'); - txt.exit().remove(); - txt.selectAll('text').call(_$drawing_264.textPointStyle, tMod, gd); + function coerce(attr, dflt) { + return _$lib_425.coerce(containerIn, containerOut, _$attributes_328, attr, dflt); } - function styleBars(d) { - var trace = d[0].trace, - marker = trace.marker || {}, - markerLine = marker.line || {}, - barpath = _$d3_68.select(this).select('g.legendpoints') - .selectAll('path.legendbar') - .data(_$registry_451.traceIs(trace, 'bar') ? [d] : []); - barpath.enter().append('path').classed('legendbar', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - barpath.exit().remove(); - barpath.each(function(d) { - var p = _$d3_68.select(this), - d0 = d[0], - w = (d0.mlw + 1 || markerLine.width + 1) - 1; - - p.style('stroke-width', w + 'px') - .call(_$color_239.fill, d0.mc || marker.color); + var hasErrorBars = ( + containerIn.array !== undefined || + containerIn.value !== undefined || + containerIn.type === 'sqrt' + ); - if(w) { - p.call(_$color_239.stroke, d0.mlc || markerLine.color); - } - }); - } + var visible = coerce('visible', hasErrorBars); - function styleBoxes(d) { - var trace = d[0].trace, - pts = _$d3_68.select(this).select('g.legendpoints') - .selectAll('path.legendbox') - .data(_$registry_451.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendbox', true) - // if we want the median bar, prepend M6,0H-6 - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); - pts.each(function() { - var w = trace.line.width, - p = _$d3_68.select(this); + if(visible === false) return; - p.style('stroke-width', w + 'px') - .call(_$color_239.fill, trace.fillcolor); + var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'), + symmetric = true; - if(w) { - p.call(_$color_239.stroke, trace.line.color); - } - }); + if(type !== 'sqrt') { + symmetric = coerce('symmetric', + !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn)); } - function stylePies(d) { - var trace = d[0].trace, - pts = _$d3_68.select(this).select('g.legendpoints') - .selectAll('path.legendpie') - .data(_$registry_451.traceIs(trace, 'pie') && trace.visible ? [d] : []); - pts.enter().append('path').classed('legendpie', true) - .attr('d', 'M6,6H-6V-6H6Z') - .attr('transform', 'translate(20,0)'); - pts.exit().remove(); + 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'); + } - if(pts.size()) pts.call(_$styleOne_506, d[0], trace); + var copyAttr = 'copy_' + opts.inherit + 'style'; + if(opts.inherit) { + var inheritObj = traceOut['error_' + opts.inherit]; + if((inheritObj || {}).visible) { + coerce(copyAttr, !(containerIn.color || + _$fastIsnumeric_135(containerIn.thickness) || + _$fastIsnumeric_135(containerIn.width))); + } + } + if(!opts.inherit || !containerOut[copyAttr]) { + coerce('color', defaultColor); + coerce('thickness'); + coerce('width', _$registry_514.traceIs(traceOut, 'gl3d') ? 0 : 4); } }; @@ -68174,752 +70085,786 @@ var _$style_300 = function style(s, gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$handleClick_297 = require('./handle_click'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$subtypes_598 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$constants_293 = require('./constants'); */; -/* removed: var _$interactions_342 = require('../../constants/interactions'); */; -/* removed: var _$alignment_339 = require('../../constants/alignment'); */; -var __LINE_SPACING_295 = _$alignment_339.LINE_SPACING; -var FROM_TL = _$alignment_339.FROM_TL; -var FROM_BR = _$alignment_339.FROM_BR; +var _$plot_333 = function plot(traces, plotinfo, transitionOpts) { + var isNew; -/* removed: var _$getLegendData_296 = require('./get_legend_data'); */; -/* removed: var _$style_300 = require('./style'); */; -/* removed: var _$helpers_298 = require('./helpers'); */; -/* removed: var _$anchor_utils_291 = require('./anchor_utils'); */; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -var DBLCLICKDELAY = _$interactions_342.DBLCLICKDELAY; + var hasAnimation = transitionOpts && transitionOpts.duration > 0; -var _$draw_295 = function draw(gd) { - var fullLayout = gd._fullLayout; - var clipId = 'legend' + fullLayout._uid; + 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 + xObj = trace.error_x || {}, + yObj = trace.error_y || {}; - if(!fullLayout._infolayer || !gd.calcdata) return; + var keyFunc; - if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; + if(trace.ids) { + keyFunc = function(d) {return d.id;}; + } - var opts = fullLayout.legend, - legendData = fullLayout.showlegend && _$getLegendData_296(gd.calcdata, opts), - hiddenSlices = fullLayout.hiddenlabels || []; + var sparse = ( + _$subtypes_598.hasMarkers(trace) && + trace.marker.maxdisplayed > 0 + ); - if(!fullLayout.showlegend || !legendData.length) { - fullLayout._infolayer.selectAll('.legend').remove(); - fullLayout._topdefs.select('#' + clipId).remove(); + if(!yObj.visible && !xObj.visible) d = []; - _$plots_444.autoMargin(gd, 'legend'); - return; - } + var errorbars = _$d3_71.select(this).selectAll('g.errorbar') + .data(d, keyFunc); - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); + errorbars.exit().remove(); - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); + if(!d.length) return; - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); + if(!xObj.visible) errorbars.selectAll('path.xerror').remove(); + if(!yObj.visible) errorbars.selectAll('path.yerror').remove(); - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + errorbars.style('opacity', 1); - var bg = legend.selectAll('rect.bg') - .data([0]); + var enter = errorbars.enter().append('g') + .classed('errorbar', true); - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' - }); + if(hasAnimation) { + enter.style('opacity', 0).transition() + .duration(transitionOpts.duration) + .style('opacity', 1); + } - bg.call(_$color_239.stroke, opts.bordercolor) - .call(_$color_239.fill, opts.bgcolor) - .style('stroke-width', opts.borderwidth + 'px'); + _$drawing_326.setClipUrl(errorbars, plotinfo.layerClipId); - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); + errorbars.each(function(d) { + var errorbar = _$d3_71.select(this); + var coords = errorCoords(d, xa, ya); - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); + if(sparse && !d.vis) return; - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); + var path; - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', - rx: 20, - ry: 3, - width: 0, - height: 0 - }) - .call(_$color_239.fill, '#808BA4'); + var yerror = errorbar.select('path.yerror'); + if(yObj.visible && _$fastIsnumeric_135(coords.x) && + _$fastIsnumeric_135(coords.yh) && + _$fastIsnumeric_135(coords.ys)) { + var yw = yObj.width; - var groups = scrollBox.selectAll('g.groups') - .data(legendData); + path = 'M' + (coords.x - yw) + ',' + + coords.yh + 'h' + (2 * yw) + // hat + 'm-' + yw + ',0V' + coords.ys; // bar - groups.enter().append('g') - .attr('class', 'groups'); - groups.exit().remove(); + if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe - var traces = groups.selectAll('g.traces') - .data(_$lib_363.identity); + isNew = !yerror.size(); - traces.enter().append('g').attr('class', 'traces'); - traces.exit().remove(); + 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); + } - traces.call(_$style_300, gd) - .style('opacity', function(d) { - var trace = d[0].trace; - if(_$registry_451.traceIs(trace, 'pie')) { - return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; - } else { - return trace.visible === 'legendonly' ? 0.5 : 1; - } - }) - .each(function() { - _$d3_68.select(this) - .call(drawTexts, gd) - .call(setupTraceToggle, gd); - }); + yerror.attr('d', path); + } + else yerror.remove(); - var firstRender = legend.enter().size() !== 0; - if(firstRender) { - computeLegendDimensions(gd, groups, traces); - expandMargin(gd); - } + var xerror = errorbar.select('path.xerror'); + if(xObj.visible && _$fastIsnumeric_135(coords.y) && + _$fastIsnumeric_135(coords.xh) && + _$fastIsnumeric_135(coords.xs)) { + var xw = (xObj.copy_ystyle ? yObj : xObj).width; - // Position and size the legend - var lxMin = 0, - lxMax = fullLayout.width, - lyMin = 0, - lyMax = fullLayout.height; + path = 'M' + coords.xh + ',' + + (coords.y - xw) + 'v' + (2 * xw) + // hat + 'm0,-' + xw + 'H' + coords.xs; // bar - computeLegendDimensions(gd, groups, traces); + if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe - if(opts._height > lyMax) { - // If the legend doesn't fit in the plot area, - // do not expand the vertical margins. - expandHorizontalMargin(gd); - } else { - expandMargin(gd); - } + isNew = !xerror.size(); - // Scroll section must be executed after repositionLegend. - // It requires the legend width, height, x and y to position the scrollbox - // and these values are mutated in repositionLegend. - var gs = fullLayout._size, - lx = gs.l + gs.w * opts.x, - ly = gs.t + gs.h * (1 - opts.y); + 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); + } - if(_$anchor_utils_291.isRightAnchor(opts)) { - lx -= opts._width; - } - else if(_$anchor_utils_291.isCenterAnchor(opts)) { - lx -= opts._width / 2; - } + xerror.attr('d', path); + } + else xerror.remove(); + }); + }); +}; - if(_$anchor_utils_291.isBottomAnchor(opts)) { - ly -= opts._height; - } - else if(_$anchor_utils_291.isMiddleAnchor(opts)) { - ly -= opts._height / 2; - } +// 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) + }; - // Make sure the legend left and right sides are visible - var legendWidth = opts._width, - legendWidthMax = gs.w; + // 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(legendWidth > legendWidthMax) { - lx = gs.l; - legendWidth = legendWidthMax; - } - else { - if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; - if(lx < lxMin) lx = lxMin; - legendWidth = Math.min(lxMax - lx, opts._width); + // if the shoes go off-scale (ie log scale, error bars past zero) + // clip the bar and hide the shoes + if(!_$fastIsnumeric_135(out.ys)) { + out.noYS = true; + out.ys = ya.c2p(d.ys, true); + } } - // Make sure the legend top and bottom are visible - // (legends with a scroll bar are not allowed to stretch beyond the extended - // margins) - var legendHeight = opts._height, - legendHeightMax = gs.h; + if(d.xh !== undefined) { + out.xh = xa.c2p(d.xh); + out.xs = xa.c2p(d.xs); - if(legendHeight > legendHeightMax) { - ly = gs.t; - legendHeight = legendHeightMax; - } - else { - if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; - if(ly < lyMin) ly = lyMin; - legendHeight = Math.min(lyMax - ly, opts._height); + if(!_$fastIsnumeric_135(out.xs)) { + out.noXS = true; + out.xs = xa.c2p(d.xs, true); + } } - // Set size and position of all the elements that make up a legend: - // legend, background and border, scroll box and scroll bar - _$drawing_264.setTranslate(legend, lx, ly); + return out; +} - // to be safe, remove previous listeners - scrollBar.on('.drag', null); - legend.on('wheel', null); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(opts._height <= legendHeight || gd._context.staticPlot) { - // if scrollbar should not be shown. - bg.attr({ - width: legendWidth - opts.borderwidth, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); - _$drawing_264.setTranslate(scrollBox, 0, 0); +'use strict'; - clipPath.select('rect').attr({ - width: legendWidth - 2 * opts.borderwidth, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth - }); +/* removed: var _$d3_71 = require('d3'); */; - _$drawing_264.setClipUrl(scrollBox, clipId); +/* removed: var _$color_301 = require('../color'); */; - _$drawing_264.setRect(scrollBar, 0, 0, 0, 0); - delete opts._scrollY; - } - else { - var scrollBarHeight = Math.max(_$constants_293.scrollBarMinHeight, - legendHeight * legendHeight / opts._height); - var scrollBarYMax = legendHeight - - scrollBarHeight - - 2 * _$constants_293.scrollBarMargin; - var scrollBoxYMax = opts._height - legendHeight; - var scrollRatio = scrollBarYMax / scrollBoxYMax; - var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); +var _$style_334 = function style(traces) { + traces.each(function(d) { + var trace = d[0].trace, + yObj = trace.error_y || {}, + xObj = trace.error_x || {}; - // increase the background and clip-path width - // by the scrollbar width and margin - bg.attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_293.scrollBarWidth + - _$constants_293.scrollBarMargin, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); + var s = _$d3_71.select(this); - clipPath.select('rect').attr({ - width: legendWidth - - 2 * opts.borderwidth + - _$constants_293.scrollBarWidth + - _$constants_293.scrollBarMargin, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth + scrollBoxY - }); + s.selectAll('path.yerror') + .style('stroke-width', yObj.thickness + 'px') + .call(_$color_301.stroke, yObj.color); - _$drawing_264.setClipUrl(scrollBox, clipId); + if(xObj.copy_ystyle) xObj = yObj; - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + s.selectAll('path.xerror') + .style('stroke-width', xObj.thickness + 'px') + .call(_$color_301.stroke, xObj.color); + }); +}; - legend.on('wheel', function() { - scrollBoxY = _$lib_363.constrain( - opts._scrollY + - _$d3_68.event.deltaY / scrollBarYMax * scrollBoxYMax, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - _$d3_68.event.preventDefault(); - } - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 eventY0, scrollBoxY0; +'use strict'; - var drag = _$d3_68.behavior.drag() - .on('dragstart', function() { - eventY0 = _$d3_68.event.sourceEvent.clientY; - scrollBoxY0 = scrollBoxY; - }) - .on('drag', function() { - var e = _$d3_68.event.sourceEvent; - if(e.buttons === 2 || e.ctrlKey) return; +/* removed: var _$lib_425 = require('../../lib'); */; +var __overrideAll_332 = _$edit_types_455.overrideAll; - scrollBoxY = _$lib_363.constrain( - (e.clientY - eventY0) / scrollRatio + scrollBoxY0, - 0, scrollBoxYMax); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - }); +/* removed: var _$attributes_328 = require('./attributes'); */; +/* removed: var _$calc_329 = require('./calc'); */; - scrollBar.call(drag); - } +var xyAttrs = { + error_x: _$lib_425.extendFlat({}, _$attributes_328), + error_y: _$lib_425.extendFlat({}, _$attributes_328) +}; +delete xyAttrs.error_x.copy_zstyle; +delete xyAttrs.error_y.copy_zstyle; +delete xyAttrs.error_y.copy_ystyle; +var xyzAttrs = { + error_x: _$lib_425.extendFlat({}, _$attributes_328), + error_y: _$lib_425.extendFlat({}, _$attributes_328), + error_z: _$lib_425.extendFlat({}, _$attributes_328) +}; +delete xyzAttrs.error_x.copy_ystyle; +delete xyzAttrs.error_y.copy_ystyle; +delete xyzAttrs.error_z.copy_ystyle; +delete xyzAttrs.error_z.copy_zstyle; - function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { - opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; - _$drawing_264.setTranslate(scrollBox, 0, -scrollBoxY); +var _$errorbars_332 = { + moduleType: 'component', + name: 'errorbars', - _$drawing_264.setRect( - scrollBar, - legendWidth, - _$constants_293.scrollBarMargin + scrollBoxY * scrollRatio, - _$constants_293.scrollBarWidth, - scrollBarHeight - ); - clipPath.select('rect').attr({ - y: opts.borderwidth + scrollBoxY - }); - } + schema: { + traces: { + scatter: xyAttrs, + bar: xyAttrs, + histogram: xyAttrs, + scatter3d: __overrideAll_332(xyzAttrs, 'calc', 'nested'), + scattergl: __overrideAll_332(xyAttrs, 'calc', 'nested') + } + }, - if(gd._context.edits.legendPosition) { - var xf, yf, x0, y0; + supplyDefaults: _$defaults_331, - legend.classed('cursor-move', true); + calc: _$calc_329, + calcFromTrace: calcFromTrace, - _$dragelement_261.init({ - element: legend.node(), - gd: gd, - prepFn: function() { - var transform = _$drawing_264.getTranslate(legend); + plot: _$plot_333, + style: _$style_334, + hoverInfo: hoverInfo +}; - x0 = transform.x; - y0 = transform.y; - }, - moveFn: function(dx, dy) { - var newX = x0 + dx, - newY = y0 + dy; +function calcFromTrace(trace, layout) { + var x = trace.x || [], + y = trace.y || [], + len = x.length || y.length; - _$drawing_264.setTranslate(legend, newX, newY); + var calcdataMock = new Array(len); - xf = _$dragelement_261.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); - yf = _$dragelement_261.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); - }, - doneFn: function() { - if(xf !== undefined && yf !== undefined) { - _$registry_451.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); - } - }, - clickFn: function(numClicks, e) { - var clickedTrace = - fullLayout._infolayer.selectAll('g.traces').filter(function() { - var bbox = this.getBoundingClientRect(); - return (e.clientX >= bbox.left && e.clientX <= bbox.right && - e.clientY >= bbox.top && e.clientY <= bbox.bottom); - }); - if(clickedTrace.size() > 0) { - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { - _$handleClick_297(clickedTrace, gd, numClicks); - }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - _$handleClick_297(clickedTrace, gd, numClicks); - } - } - } - }); + for(var i = 0; i < len; i++) { + calcdataMock[i] = { + x: x[i], + y: y[i] + }; } -}; - -function drawTexts(g, gd) { - var legendItem = g.data()[0][0], - fullLayout = gd._fullLayout, - trace = legendItem.trace, - isPie = _$registry_451.traceIs(trace, 'pie'), - traceIndex = trace.index, - name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); + calcdataMock[0].trace = trace; - text.enter().append('text').classed('legendtext', true); + _$calc_329({ + calcdata: [calcdataMock], + _fullLayout: layout + }); - text.attr('text-anchor', 'start') - .classed('user-select-none', true) - .call(_$drawing_264.font, fullLayout.legend.font) - .text(name); + return calcdataMock; +} - function textLayout(s) { - _$svg_text_utils_386.convertToTspans(s, gd, function() { - computeTextDimensions(g, gd); - }); +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; } +} - if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_386.makeEditable, {gd: gd}) - .call(textLayout) - .on('edit', function(text) { - this.text(text) - .call(textLayout); +var _$domain_495 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 origText = text; +'use strict'; - if(!this.text()) text = ' \u0020\u0020 '; +var __extendFlat_495 = _$extend_416.extendFlat; - var transforms, direction; - var fullInput = legendItem.trace._fullInput || {}; - var update = {}; +/** + * 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 + */ +_$domain_495.attributes = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_451.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_451.getTransformIndices(fullInput, 'groupby'); - var index = groupbyIndices[groupbyIndices.length - 1]; + 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 kcont = _$lib_363.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + var namePart = opts.name ? opts.name + ' ' : ''; + var contPart = opts.trace ? 'trace ' : 'subplot '; + var descPart = extra.description ? ' ' + extra.description : ''; - if(origText === '') { - kcont.remove(legendItem.trace._group); - } else { - kcont.set(legendItem.trace._group, text); - } + var out = { + x: __extendFlat_495({}, base, { + + }), + y: __extendFlat_495({}, base, { + + }), + editType: opts.editType + }; - update = kcont.constructUpdate(); - } else { - update.name = text; - } + 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 _$registry_451.call('restyle', gd, update, traceIndex); - }); - } else { - textLayout(text); + return out; +}; + +_$domain_495.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; + } } -} -function setupTraceToggle(g, gd) { - var newMouseDownTime, - numClicks = 1; + coerce('domain.x', dfltX); + coerce('domain.y', dfltY); +}; - var traceToggle = g.selectAll('rect') - .data([0]); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_239.fill, 'rgba(0,0,0,0)'); +'use strict'; +/* removed: var _$lib_425 = require('../../lib'); */; +var __counterRegex_347 = _$regex_441.counter; +var domainAttrs = _$domain_495.attributes; +var cartesianIdRegex = _$constants_475.idRegex; - traceToggle.on('mousedown', function() { - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { - // 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; +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_347('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' +}; - if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } +function getAxes(layout, grid, axLetter) { + var gridVal = grid[axLetter + 'axes']; + var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {}); - if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { _$handleClick_297(g, gd, numClicks); }, DBLCLICKDELAY); - } else if(numClicks === 2) { - if(legend._clickTimeout) { - clearTimeout(legend._clickTimeout); - } - gd._legendMouseDownTime = 0; - _$handleClick_297(g, gd, numClicks); - } - }); + if(Array.isArray(gridVal)) return gridVal; + if(splomVal.length) return splomVal; } -function computeTextDimensions(g, gd) { - var legendItem = g.data()[0][0]; - - if(!legendItem.trace.showlegend) { - g.remove(); - return; - } +// 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'); - var mathjaxGroup = g.select('g[class*=math-group]'); - var mathjaxNode = mathjaxGroup.node(); - var opts = gd._fullLayout.legend; - var lineHeight = opts.font.size * __LINE_SPACING_295; - var height, width; + if(!layoutIn.grid && !xAxes && !yAxes) return; - if(mathjaxNode) { - var mathjaxBB = _$drawing_264.bBox(mathjaxNode); + 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 + ); - height = mathjaxBB.height; - width = mathjaxBB.width; + var dfltRows, dfltColumns; - _$drawing_264.setTranslate(mathjaxGroup, 0, (height / 4)); + if(hasSubplotGrid) { + dfltRows = gridIn.subplots.length; + dfltColumns = gridIn.subplots[0].length; } else { - var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_386.lineCount(text); - var textNode = text.node(); - - height = lineHeight * textLines; - width = textNode ? _$drawing_264.bBox(textNode).width : 0; - - // approximation to height offset to center the font - // to avoid getBoundingClientRect - var textY = lineHeight * (0.3 + (1 - textLines) / 2); - // TODO: this 40 should go in a constants file (along with other - // values related to the legend symbol size) - _$svg_text_utils_386.positionText(text, 40, textY); + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } - height = Math.max(height, 16) + 3; - - legendItem.height = height; - legendItem.width = width; -} + var gridOut = layoutOut.grid = {}; -function computeLegendDimensions(gd, groups, traces) { - var fullLayout = gd._fullLayout; - var opts = fullLayout.legend; - var borderwidth = opts.borderwidth; - var isGrouped = _$helpers_298.isGrouped(opts); + function coerce(attr, dflt) { + return _$lib_425.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + } - var extraWidth = 0; + var rows = coerce('rows', dfltRows); + var columns = coerce('columns', dfltColumns); - opts._width = 0; - opts._height = 0; + if(!(rows * columns > 1)) return; - if(_$helpers_298.isVertical(opts)) { - if(isGrouped) { - groups.each(function(d, i) { - _$drawing_264.setTranslate(this, 0, i * opts.tracegroupgap); - }); - } + if(!hasSubplotGrid && !hasXaxes && !hasYaxes) { + var useDefaultSubplots = coerce('pattern') === 'independent'; + if(useDefaultSubplots) hasSubplotGrid = true; + } + gridOut._hasSubplotGrid = hasSubplotGrid; - traces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height, - textWidth = legendItem.width; + var rowOrder = coerce('roworder'); + var reversed = rowOrder === 'top to bottom'; - _$drawing_264.setTranslate(this, - borderwidth, - (5 + borderwidth + opts._height + textHeight / 2)); + var dfltGapX = hasSubplotGrid ? 0.2 : 0.1; + var dfltGapY = hasSubplotGrid ? 0.3 : 0.1; - opts._height += textHeight; - opts._width = Math.max(opts._width, textWidth); - }); + var dfltSideX, dfltSideY; + if(isSplomGenerated) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } - opts._width += 45 + borderwidth * 2; - opts._height += 10 + borderwidth * 2; + gridOut._domains = { + x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns), + y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed) + }; +} - if(isGrouped) { - opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; - } +// 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); - extraWidth = 40; + 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]; } - else if(isGrouped) { - var groupXOffsets = [opts._width], - groupData = groups.data(); - - for(var i = 0, n = groupData.length; i < n; i++) { - var textWidths = groupData[i].map(function(legendItemArray) { - return legendItemArray[0].width; - }); - - var groupWidth = 40 + Math.max.apply(null, textWidths); + return out; +} - opts._width += opts.tracegroupgap + groupWidth; +// 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; - groupXOffsets.push(opts._width); - } + 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'; - groups.each(function(d, i) { - _$drawing_264.setTranslate(this, groupXOffsets[i], 0); - }); + var i, j, xId, yId, subplotId, subplotsOut, yPos; - groups.each(function() { - var group = _$d3_68.select(this), - groupTraces = group.selectAll('g.traces'), - groupHeight = 0; + var axisMap = gridOut._axisMap = {}; - groupTraces.each(function(d) { - var legendItem = d[0], - textHeight = legendItem.height; + if(hasSubplotGrid) { + var subplotsIn = gridIn.subplots || []; + subplotsOut = gridOut.subplots = new Array(rows); + var index = 1; - _$drawing_264.setTranslate(this, - 0, - (5 + borderwidth + groupHeight + textHeight / 2)); + 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]; - groupHeight += textHeight; - }); + rowOut[j] = ''; - opts._height = Math.max(opts._height, groupHeight); - }); + 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; + } - opts._height += 10 + borderwidth * 2; - opts._width += borderwidth * 2; + rowOut[j] = subplotId; + axisMap[xId] = j; + axisMap[yId] = i; + } + } + } } else { - var rowHeight = 0, - maxTraceHeight = 0, - maxTraceWidth = 0, - offsetX = 0, - fullTracesWidth = 0, - traceGap = opts.tracegroupgap || 5, - oneRowLegend; - - // calculate largest width for traces and use for width of all legend items - traces.each(function(d) { - maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); - fullTracesWidth += 40 + d[0].width + traceGap; - }); - - // check if legend fits in one row - oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; - traces.each(function(d) { - var legendItem = d[0], - traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; - - if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { - offsetX = 0; - rowHeight = rowHeight + maxTraceHeight; - opts._height = opts._height + maxTraceHeight; - // reset for next row - maxTraceHeight = 0; - } - - _$drawing_264.setTranslate(this, - (borderwidth + offsetX), - (5 + borderwidth + legendItem.height / 2) + rowHeight); + 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'); + } - opts._width += traceGap + traceWidth; - opts._height = Math.max(opts._height, legendItem.height); + var anchors = gridOut._anchors = {}; + var reversed = gridOut.roworder === 'top to bottom'; - // keep track of tallest trace in group - offsetX += traceGap + traceWidth; - maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); - }); + for(var axisId in axisMap) { + var axLetter = axisId.charAt(0); + var side = gridOut[axLetter + 'side']; - opts._width += borderwidth * 2; - opts._height += 10 + borderwidth * 2; + 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; + } + } + } + } } - - // make sure we're only getting full pixels - opts._width = Math.ceil(opts._width); - opts._height = Math.ceil(opts._height); - - traces.each(function(d) { - var legendItem = d[0], - bg = _$d3_68.select(this).select('.legendtoggle'); - - _$drawing_264.setRect(bg, - 0, - -legendItem.height / 2, - (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, - legendItem.height - ); - }); } -function expandMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; - - var xanchor = 'left'; - if(_$anchor_utils_291.isRightAnchor(opts)) { - xanchor = 'right'; - } - else if(_$anchor_utils_291.isCenterAnchor(opts)) { - xanchor = 'center'; - } +function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { + var out = new Array(len); + var i; - var yanchor = 'top'; - if(_$anchor_utils_291.isBottomAnchor(opts)) { - yanchor = 'bottom'; - } - else if(_$anchor_utils_291.isMiddleAnchor(opts)) { - yanchor = 'middle'; + function fillOneAxis(i, axisId) { + if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) { + out[i] = axisId; + axisMap[axisId] = i; + } + else out[i] = ''; } - // lastly check if the margin auto-expand has changed - _$plots_444.autoMargin(gd, 'legend', { - x: opts.x, - y: opts.y, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: opts._height * (FROM_BR[yanchor]), - t: opts._height * (FROM_TL[yanchor]) - }); -} - -function expandHorizontalMargin(gd) { - var fullLayout = gd._fullLayout, - opts = fullLayout.legend; - - var xanchor = 'left'; - if(_$anchor_utils_291.isRightAnchor(opts)) { - xanchor = 'right'; + if(Array.isArray(axesIn)) { + for(i = 0; i < len; i++) { + fillOneAxis(i, axesIn[i]); + } } - else if(_$anchor_utils_291.isCenterAnchor(opts)) { - xanchor = 'center'; + else { + // default axis list is the first `len` axis ids + fillOneAxis(0, axLetter); + for(i = 1; i < len; i++) { + fillOneAxis(i, axLetter + (i + 1)); + } } - // lastly check if the margin auto-expand has changed - _$plots_444.autoMargin(gd, 'legend', { - x: opts.x, - y: 0.5, - l: opts._width * (FROM_TL[xanchor]), - r: opts._width * (FROM_BR[xanchor]), - b: 0, - t: 0 - }); + return out; } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - - -var _$legend_299 = { +var _$grid_347 = { moduleType: 'component', - name: 'legend', + name: 'grid', - layoutAttributes: _$attributes_292, - supplyLayoutDefaults: _$legendDefaults_294, + schema: { + layout: {grid: gridAttrs} + }, - draw: _$draw_295, - style: _$style_300 + layoutAttributes: gridAttrs, + sizeDefaults: sizeDefaults, + contentDefaults: contentDefaults }; /** @@ -68932,139 +70877,129 @@ var _$legend_299 = { 'use strict'; +/* removed: var _$constants_475 = require('../../plots/cartesian/constants'); */; -var _$button_attributes_306 = { - step: { - valType: 'enumerated', - - values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], - dflt: 'month', - editType: 'plot', - - }, - stepmode: { - valType: 'enumerated', + +var _$attributes_348 = { + _isLinkedToArray: 'image', + + visible: { + valType: 'boolean', - values: ['backward', 'todate'], - dflt: 'backward', - editType: 'plot', + dflt: true, + editType: 'arraydraw', }, - count: { - valType: 'number', + + source: { + valType: 'string', - min: 0, - dflt: 1, - editType: 'plot', + editType: 'arraydraw', }, - label: { - valType: 'string', + + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', - editType: 'plot', + editType: 'arraydraw', }, - editType: 'plot' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_238 = require('../color/attributes'); */; -var __extendFlat_305 = _$extend_354.extendFlat; -/* removed: var _$button_attributes_306 = require('./button_attributes'); */; - -_$button_attributes_306 = __extendFlat_305(_$button_attributes_306, { - _isLinkedToArray: 'button', - - -}); -var _$attributes_305 = { - visible: { - valType: 'boolean', + sizex: { + valType: 'number', - editType: 'plot', + dflt: 0, + editType: 'arraydraw', }, - buttons: _$button_attributes_306, - - x: { + sizey: { valType: 'number', - min: -2, - max: 3, - editType: 'plot', + dflt: 0, + editType: 'arraydraw', }, - xanchor: { + + sizing: { valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', + values: ['fill', 'contain', 'stretch'], + dflt: 'contain', - editType: 'plot', + editType: 'arraydraw', }, - y: { + + opacity: { valType: 'number', - min: -2, - max: 3, - editType: 'plot', + min: 0, + max: 1, + dflt: 1, + editType: 'arraydraw', }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'bottom', + + x: { + valType: 'any', - editType: 'plot', + dflt: 0, + editType: 'arraydraw', }, - font: _$font_attributes_434({ - editType: 'plot', + y: { + valType: 'any', - }), + dflt: 0, + editType: 'arraydraw', + + }, - bgcolor: { - valType: 'color', - dflt: _$attributes_238.lightLine, + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', - editType: 'plot', + editType: 'arraydraw', }, - activecolor: { - valType: 'color', + + yanchor: { + valType: 'enumerated', + values: ['top', 'middle', 'bottom'], + dflt: 'top', - editType: 'plot', + editType: 'arraydraw', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_238.defaultLine, + + xref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_475.idRegex.x.toString() + ], + dflt: 'paper', - editType: 'plot', + editType: 'arraydraw', }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 0, + + yref: { + valType: 'enumerated', + values: [ + 'paper', + _$constants_475.idRegex.y.toString() + ], + dflt: 'paper', - editType: 'plot', + editType: 'arraydraw', }, - editType: 'plot' + editType: 'arraydraw' }; /** @@ -69075,123 +71010,79 @@ var _$attributes_305 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - - -var _$constants_307 = { - - // 'y' position pad above counter axis domain - yPad: 0.02, - - // minimum button width (regardless of text size) - minButtonWidth: 30, - - // buttons rect radii - rx: 3, - ry: 3, - - // light fraction used to compute the 'activecolor' default - lightAmount: 25, - darkAmount: 10 -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$color_239 = require('../color'); */; - -/* removed: var _$attributes_305 = require('./attributes'); */; -/* removed: var _$button_attributes_306 = require('./button_attributes'); */; -/* removed: var _$constants_307 = require('./constants'); */; - - -var _$handleDefaults_308 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { - var selectorIn = containerIn.rangeselector || {}, - selectorOut = containerOut.rangeselector = {}; - - function coerce(attr, dflt) { - return _$lib_363.coerce(selectorIn, selectorOut, _$attributes_305, attr, dflt); - } - - var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; - - var posDflt = getPosDflt(containerOut, layout, counterAxes); - coerce('x', posDflt[0]); - coerce('y', posDflt[1]); - _$lib_363.noneOrAll(containerIn, containerOut, ['x', 'y']); - - coerce('xanchor'); - coerce('yanchor'); +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_451 = require('../../lib/to_log_range'); */; - _$lib_363.coerceFont(coerce, 'font', layout.font); +/* + * convertCoords: when converting an axis between log and linear + * you need to alter any images on that axis to keep them + * pointing at the same data point. + * In v2.0 this will become obsolete (or perhaps size will still need conversion?) + * we convert size by declaring that the maximum extent *in data units* should be + * the same, assuming the image is anchored by its center (could remove that restriction + * if we think it's important) even though the actual left and right values will not be + * quite the same since the scale becomes nonlinear (and central anchor means the pixel + * center of the image, not the data units center) + * + * gd: the plot div + * ax: the axis being changed + * newType: the type it's getting + * doExtra: function(attr, val) from inside relayout that sets the attribute. + * Use this to make the changes as it's aware if any other changes in the + * same relayout call should override this conversion. + */ +var _$convertCoords_349 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; - var bgColor = coerce('bgcolor'); - coerce('activecolor', _$color_239.contrast(bgColor, _$constants_307.lightAmount, _$constants_307.darkAmount)); - coerce('bordercolor'); - coerce('borderwidth'); -}; + var toLog = (newType === 'log') && (ax.type === 'linear'), + fromLog = (newType === 'linear') && (ax.type === 'log'); -function buttonsDefaults(containerIn, containerOut, calendar) { - var buttonsIn = containerIn.buttons || [], - buttonsOut = containerOut.buttons = []; + if(!(toLog || fromLog)) return; - var buttonIn, buttonOut; + var images = gd._fullLayout.images, + axLetter = ax._id.charAt(0), + image, + attrPrefix; - function coerce(attr, dflt) { - return _$lib_363.coerce(buttonIn, buttonOut, _$button_attributes_306, attr, dflt); - } + for(var i = 0; i < images.length; i++) { + image = images[i]; + attrPrefix = 'images[' + i + '].'; - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + if(image[axLetter + 'ref'] === ax._id) { + var currentPos = image[axLetter], + currentSize = image['size' + axLetter], + newPos = null, + newSize = null; - if(!_$lib_363.isPlainObject(buttonIn)) continue; + if(toLog) { + newPos = _$toLogRange_451(currentPos, ax.range); - var step = coerce('step'); - if(step !== 'all') { - if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { - buttonOut.stepmode = 'backward'; + // this is the inverse of the conversion we do in fromLog below + // so that the conversion is reversible (notice the fromLog conversion + // is like sinh, and this one looks like arcsinh) + var dx = currentSize / Math.pow(10, newPos) / 2; + newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; } else { - coerce('stepmode'); + newPos = Math.pow(10, currentPos); + newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); } - coerce('count'); - } - - coerce('label'); - - buttonOut._index = i; - buttonsOut.push(buttonOut); - } - - return buttonsOut; -} - -function getPosDflt(containerOut, layout, counterAxes) { - var anchoredList = counterAxes.filter(function(ax) { - return layout[ax].anchor === containerOut._id; - }); + // if conversion failed, delete the value so it can get a default later on + if(!_$fastIsnumeric_135(newPos)) { + newPos = null; + newSize = null; + } + else if(!_$fastIsnumeric_135(newSize)) newSize = null; - var posY = 0; - for(var i = 0; i < anchoredList.length; i++) { - var domain = layout[anchoredList[i]].domain; - if(domain) posY = Math.max(domain[1], posY); + doExtra(attrPrefix + axLetter, newPos); + doExtra(attrPrefix + 'size' + axLetter, newSize); + } } - - return [containerOut.domain[0], posY + _$constants_307.yPad]; -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -69201,52 +71092,56 @@ function getPosDflt(containerOut, layout, counterAxes) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_466 = require('../../plots/array_container_defaults'); */; -var _$getUpdateObject_310 = function getUpdateObject(axisLayout, buttonLayout) { - var axName = axisLayout._name; - var update = {}; - - if(buttonLayout.step === 'all') { - update[axName + '.autorange'] = true; - } - else { - var xrange = getXRange(axisLayout, buttonLayout); +/* removed: var _$attributes_348 = require('./attributes'); */; +var __name_350 = 'images'; - update[axName + '.range[0]'] = xrange[0]; - update[axName + '.range[1]'] = xrange[1]; - } +var _$supplyLayoutDefaults_350 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_350, + handleItemDefaults: imageDefaults + }; - return update; + _$handleArrayContainerDefaults_466(layoutIn, layoutOut, opts); }; -function getXRange(axisLayout, buttonLayout) { - var currentRange = axisLayout.range; - var base = new Date(axisLayout.r2l(currentRange[1])); - var step = buttonLayout.step, - count = buttonLayout.count; +function imageDefaults(imageIn, imageOut, fullLayout) { - var range0; + function coerce(attr, dflt) { + return _$lib_425.coerce(imageIn, imageOut, _$attributes_348, attr, dflt); + } - switch(buttonLayout.stepmode) { - case 'backward': - range0 = axisLayout.l2r(+_$d3_68.time[step].utc.offset(base, -count)); - break; + var source = coerce('source'); + var visible = coerce('visible', !!source); - case 'todate': - var base2 = _$d3_68.time[step].utc.offset(base, -count); + if(!visible) return imageOut; - range0 = axisLayout.l2r(+_$d3_68.time[step].utc.ceil(base2)); - break; - } + coerce('layer'); + coerce('xanchor'); + coerce('yanchor'); + coerce('sizex'); + coerce('sizey'); + coerce('sizing'); + coerce('opacity'); - var range1 = currentRange[1]; + var gdMock = { _fullLayout: fullLayout }, + axLetters = ['x', 'y']; - return [range0, range1]; + for(var i = 0; i < 2; i++) { + // 'paper' is the fallback axref + var axLetter = axLetters[i], + axRef = _$axes_470.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + + _$axes_470.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + } + + return imageOut; } /** @@ -69259,258 +71154,215 @@ function getXRange(axisLayout, buttonLayout) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_410 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$anchor_utils_291 = require('../legend/anchor_utils'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$xmlns_namespaces_406 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$alignment_339 = require('../../constants/alignment'); */; -var __LINE_SPACING_309 = _$alignment_339.LINE_SPACING; -var __FROM_TL_309 = _$alignment_339.FROM_TL; -var __FROM_BR_309 = _$alignment_339.FROM_BR; - -/* removed: var _$constants_307 = require('./constants'); */; -/* removed: var _$getUpdateObject_310 = require('./get_update_object'); */; - - -var _$draw_309 = function draw(gd) { - var fullLayout = gd._fullLayout; +var _$draw_351 = function draw(gd) { + var fullLayout = gd._fullLayout, + imageDataAbove = [], + imageDataSubplot = {}, + imageDataBelow = [], + subplot, + i; - var selectors = fullLayout._infolayer.selectAll('.rangeselector') - .data(makeSelectorData(gd), selectorKeyFunc); + // Sort into top, subplot, and bottom layers + for(i = 0; i < fullLayout.images.length; i++) { + var img = fullLayout.images[i]; - selectors.enter().append('g') - .classed('rangeselector', true); + if(img.visible) { + if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') { + subplot = img.xref + img.yref; - selectors.exit().remove(); + var plotinfo = fullLayout._plots[subplot]; - selectors.style({ - cursor: 'pointer', - 'pointer-events': 'all' - }); + if(!plotinfo) { + // Fall back to _imageLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the image to an x / y axis combination + // that doesn't have any data on it (and layer is below) + imageDataBelow.push(img); + continue; + } - selectors.each(function(d) { - var selector = _$d3_68.select(this), - axisLayout = d, - selectorLayout = axisLayout.rangeselector; + if(plotinfo.mainplot) { + subplot = plotinfo.mainplot.id; + } - var buttons = selector.selectAll('g.button') - .data(selectorLayout.buttons); + if(!imageDataSubplot[subplot]) { + imageDataSubplot[subplot] = []; + } + imageDataSubplot[subplot].push(img); + } else if(img.layer === 'above') { + imageDataAbove.push(img); + } else { + imageDataBelow.push(img); + } + } + } - buttons.enter().append('g') - .classed('button', true); - buttons.exit().remove(); + var anchors = { + x: { + left: { sizing: 'xMin', offset: 0 }, + center: { sizing: 'xMid', offset: -1 / 2 }, + right: { sizing: 'xMax', offset: -1 } + }, + y: { + top: { sizing: 'YMin', offset: 0 }, + middle: { sizing: 'YMid', offset: -1 / 2 }, + bottom: { sizing: 'YMax', offset: -1 } + } + }; - buttons.each(function(d) { - var button = _$d3_68.select(this); - var update = _$getUpdateObject_310(axisLayout, d); - d._isActive = isActive(axisLayout, d, update); + // Images must be converted to dataURL's for exporting. + function setImage(d) { + var thisImage = _$d3_71.select(this); - button.call(drawButtonRect, selectorLayout, d); - button.call(drawButtonText, selectorLayout, d, gd); + if(this.img && this.img.src === d.source) { + return; + } - button.on('click', function() { - if(gd._dragged) return; + thisImage.attr('xmlns', _$xmlns_namespaces_406.svg); - _$registry_451.call('relayout', gd, update); - }); + var imagePromise = new Promise(function(resolve) { - button.on('mouseover', function() { - d._isHovered = true; - button.call(drawButtonRect, selectorLayout, d); - }); + var img = new Image(); + this.img = img; - button.on('mouseout', function() { - d._isHovered = false; - button.call(drawButtonRect, selectorLayout, d); - }); - }); + // If not set, a `tainted canvas` error is thrown + img.setAttribute('crossOrigin', 'anonymous'); + img.onerror = errorHandler; + img.onload = function() { + var canvas = document.createElement('canvas'); + canvas.width = this.width; + canvas.height = this.height; - reposition(gd, buttons, selectorLayout, axisLayout._name, selector); - }); + var ctx = canvas.getContext('2d'); + ctx.drawImage(this, 0, 0); -}; + var dataURL = canvas.toDataURL('image/png'); -function makeSelectorData(gd) { - var axes = _$axis_ids_410.list(gd, 'x', true); - var data = []; + thisImage.attr('xlink:href', dataURL); - for(var i = 0; i < axes.length; i++) { - var axis = axes[i]; + // resolve promise in onload handler instead of on 'load' to support IE11 + // see https://github.com/plotly/plotly.js/issues/1685 + // for more details + resolve(); + }; - if(axis.rangeselector && axis.rangeselector.visible) { - data.push(axis); - } - } - return data; -} + thisImage.on('error', errorHandler); -function selectorKeyFunc(d) { - return d._id; -} + img.src = d.source; -function isActive(axisLayout, opts, update) { - if(opts.step === 'all') { - return axisLayout.autorange === true; - } - else { - var keys = Object.keys(update); + function errorHandler() { + thisImage.remove(); + resolve(); + } + }.bind(this)); - return ( - axisLayout.range[0] === update[keys[0]] && - axisLayout.range[1] === update[keys[1]] - ); + gd._promises.push(imagePromise); } -} - -function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - rect.attr('shape-rendering', 'crispEdges'); + function applyAttributes(d) { + var thisImage = _$d3_71.select(this); - rect.attr({ - 'rx': _$constants_307.rx, - 'ry': _$constants_307.ry - }); + // Axes if specified + var xa = _$axes_470.getFromId(gd, d.xref), + ya = _$axes_470.getFromId(gd, d.yref); - rect.call(_$color_239.stroke, selectorLayout.bordercolor) - .call(_$color_239.fill, getFillColor(selectorLayout, d)) - .style('stroke-width', selectorLayout.borderwidth + 'px'); -} + var size = fullLayout._size, + width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, + height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h; -function getFillColor(selectorLayout, d) { - return (d._isActive || d._isHovered) ? - selectorLayout.activecolor : - selectorLayout.bgcolor; -} + // Offsets for anchor positioning + var xOffset = width * anchors.x[d.xanchor].offset, + yOffset = height * anchors.y[d.yanchor].offset; -function drawButtonText(button, selectorLayout, d, gd) { - function textLayout(s) { - _$svg_text_utils_386.convertToTspans(s, gd); - } + var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; - var text = button.selectAll('text') - .data([0]); + // Final positions + var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset, + yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset; - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - text.attr('text-anchor', 'middle'); + // Construct the proper aspectRatio attribute + switch(d.sizing) { + case 'fill': + sizing += ' slice'; + break; - text.call(_$drawing_264.font, selectorLayout.font) - .text(getLabel(d)) - .call(textLayout); -} + case 'stretch': + sizing = 'none'; + break; + } -function getLabel(opts) { - if(opts.label) return opts.label; + thisImage.attr({ + x: xPos, + y: yPos, + width: width, + height: height, + preserveAspectRatio: sizing, + opacity: d.opacity + }); - if(opts.step === 'all') return 'all'; - return opts.count + opts.step.charAt(0); -} + // Set proper clipping on images + var xId = xa ? xa._id : '', + yId = ya ? ya._id : '', + clipAxes = xId + yId; -function reposition(gd, buttons, opts, axName, selector) { - var width = 0; - var height = 0; + thisImage.call(_$drawing_326.setClipUrl, clipAxes ? + ('clip' + fullLayout._uid + clipAxes) : + null + ); + } - var borderWidth = opts.borderwidth; + var imagesBelow = fullLayout._imageLowerLayer.selectAll('image') + .data(imageDataBelow), + imagesAbove = fullLayout._imageUpperLayer.selectAll('image') + .data(imageDataAbove); - buttons.each(function() { - var button = _$d3_68.select(this); - var text = button.select('.selector-text'); + imagesBelow.enter().append('image'); + imagesAbove.enter().append('image'); - var tHeight = opts.font.size * __LINE_SPACING_309; - var hEff = Math.max(tHeight * _$svg_text_utils_386.lineCount(text), 16) + 3; + imagesBelow.exit().remove(); + imagesAbove.exit().remove(); - height = Math.max(height, hEff); + imagesBelow.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); }); - - buttons.each(function() { - var button = _$d3_68.select(this); - var rect = button.select('.selector-rect'); - var text = button.select('.selector-text'); - - var tWidth = text.node() && _$drawing_264.bBox(text.node()).width; - var tHeight = opts.font.size * __LINE_SPACING_309; - var tLines = _$svg_text_utils_386.lineCount(text); - - var wEff = Math.max(tWidth + 10, _$constants_307.minButtonWidth); - - // TODO add MathJax support - - // TODO add buttongap attribute - - button.attr('transform', 'translate(' + - (borderWidth + width) + ',' + borderWidth + - ')'); - - rect.attr({ - x: 0, - y: 0, - width: wEff, - height: height - }); - - _$svg_text_utils_386.positionText(text, wEff / 2, - height / 2 - ((tLines - 1) * tHeight / 2) + 3); - - width += wEff + 5; + imagesAbove.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); }); - var graphSize = gd._fullLayout._size; - var lx = graphSize.l + graphSize.w * opts.x; - var ly = graphSize.t + graphSize.h * (1 - opts.y); - - var xanchor = 'left'; - if(_$anchor_utils_291.isRightAnchor(opts)) { - lx -= width; - xanchor = 'right'; - } - if(_$anchor_utils_291.isCenterAnchor(opts)) { - lx -= width / 2; - xanchor = 'center'; - } - - var yanchor = 'top'; - if(_$anchor_utils_291.isBottomAnchor(opts)) { - ly -= height; - yanchor = 'bottom'; - } - if(_$anchor_utils_291.isMiddleAnchor(opts)) { - ly -= height / 2; - yanchor = 'middle'; - } + var allSubplots = Object.keys(fullLayout._plots); + for(i = 0; i < allSubplots.length; i++) { + subplot = allSubplots[i]; + var subplotObj = fullLayout._plots[subplot]; - width = Math.ceil(width); - height = Math.ceil(height); - lx = Math.round(lx); - ly = Math.round(ly); + // filter out overlaid plots (which havd their images on the main plot) + // and gl2d plots (which don't support below images, at least not yet) + if(!subplotObj.imagelayer) continue; - _$plots_444.autoMargin(gd, axName + '-range-selector', { - x: opts.x, - y: opts.y, - l: width * __FROM_TL_309[xanchor], - r: width * __FROM_BR_309[xanchor], - b: height * __FROM_BR_309[yanchor], - t: height * __FROM_TL_309[yanchor] - }); + var imagesOnSubplot = subplotObj.imagelayer.selectAll('image') + // even if there are no images on this subplot, we need to run + // enter and exit in case there were previously + .data(imageDataSubplot[subplot] || []); - selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); -} + imagesOnSubplot.enter().append('image'); + imagesOnSubplot.exit().remove(); + + imagesOnSubplot.each(function(d) { + setImage.bind(this)(d); + applyAttributes.bind(this)(d); + }); + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -69522,20 +71374,17 @@ function reposition(gd, buttons, opts, axName, selector) { 'use strict'; -var _$rangeselector_311 = { +var _$images_352 = { moduleType: 'component', - name: 'rangeselector', + name: 'images', - schema: { - subplots: { - xaxis: {rangeselector: _$attributes_305} - } - }, + layoutAttributes: _$attributes_348, + supplyLayoutDefaults: _$supplyLayoutDefaults_350, + includeBasePlot: _$makeIncludeComponents_480('images'), - layoutAttributes: _$attributes_305, - handleDefaults: _$handleDefaults_308, + draw: _$draw_351, - draw: _$draw_309 + convertCoords: _$convertCoords_349 }; /** @@ -69548,197 +71397,98 @@ var _$rangeselector_311 = { 'use strict'; -/* removed: var _$attributes_238 = require('../color/attributes'); */; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_300 = require('../color/attributes'); */; -var _$attributes_312 = { + +var _$attributes_354 = { bgcolor: { valType: 'color', - dflt: _$attributes_238.background, - editType: 'plot', + editType: 'legend', }, bordercolor: { valType: 'color', - dflt: _$attributes_238.defaultLine, + dflt: _$attributes_300.defaultLine, - editType: 'plot', + editType: 'legend', }, borderwidth: { - valType: 'integer', - dflt: 0, + valType: 'number', min: 0, + dflt: 0, - editType: 'plot', + editType: 'legend', }, - autorange: { - valType: 'boolean', - dflt: true, + font: _$font_attributes_496({ + editType: 'legend', - editType: 'calc', - impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, + }), + orientation: { + valType: 'enumerated', + values: ['v', 'h'], + dflt: 'v', + + editType: 'legend', }, - range: { - valType: 'info_array', + traceorder: { + valType: 'flaglist', + flags: ['reversed', 'grouped'], + extras: ['normal'], - items: [ - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} - ], - editType: 'calc', - impliedEdits: {'autorange': false}, + editType: 'legend', }, - thickness: { + tracegroupgap: { valType: 'number', - dflt: 0.15, min: 0, - max: 1, + dflt: 10, - editType: 'plot', + editType: 'legend', }, - visible: { - valType: 'boolean', - dflt: true, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 1.02, - editType: 'calc', + editType: 'legend', }, - editType: 'calc' -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$constants_314 = { - - // attribute container name - name: 'rangeslider', - - // class names - - containerClassName: 'rangeslider-container', - bgClassName: 'rangeslider-bg', - rangePlotClassName: 'rangeslider-rangeplot', - - maskMinClassName: 'rangeslider-mask-min', - maskMaxClassName: 'rangeslider-mask-max', - slideBoxClassName: 'rangeslider-slidebox', - - grabberMinClassName: 'rangeslider-grabber-min', - grabAreaMinClassName: 'rangeslider-grabarea-min', - handleMinClassName: 'rangeslider-handle-min', - - grabberMaxClassName: 'rangeslider-grabber-max', - grabAreaMaxClassName: 'rangeslider-grabarea-max', - handleMaxClassName: 'rangeslider-handle-max', - - maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', - maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', - - // style constants - - maskColor: 'rgba(0,0,0,0.4)', - maskOppAxisColor: 'rgba(0,0,0,0.2)', - - slideBoxFill: 'transparent', - slideBoxCursor: 'ew-resize', - - grabAreaFill: 'transparent', - grabAreaCursor: 'col-resize', - grabAreaWidth: 10, - - handleWidth: 4, - handleRadius: 1, - handleStrokeWidth: 1, - - extraPad: 15 -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var listAxes = _$axis_ids_410.list; -var __getAutoRange_313 = _$autorange_406.getAutoRange; -/* removed: var _$constants_314 = require('./constants'); */; - -var _$calcAutorange_313 = 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], - opts = ax[_$constants_314.name]; - - // Don't try calling getAutoRange if _min and _max are filled in. - // This happens on updates where the calc step is skipped. - - if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { - opts._input.autorange = true; - opts._input.range = opts.range = __getAutoRange_313(ax); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$oppaxis_attributes_318 = { - // 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: { + xanchor: { valType: 'enumerated', - values: ['auto', 'fixed', 'match'], - dflt: 'match', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', - editType: 'calc', + editType: 'legend', }, - range: { - valType: 'info_array', + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, - items: [ - {valType: 'any', editType: 'plot'}, - {valType: 'any', editType: 'plot'} - ], - editType: 'plot', + editType: 'legend', }, - editType: 'calc' + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'auto', + + editType: 'legend', + + }, + editType: 'legend' }; +var _$helpers_360 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -69747,77 +71497,29 @@ var _$oppaxis_attributes_318 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$attributes_312 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_318 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_410 = require('../../plots/cartesian/axis_ids'); */; - -var _$handleDefaults_315 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; - - // not super proud of this (maybe store _ in axis object instead - if(!_$lib_363.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; - } - - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; - - function coerce(attr, dflt) { - return _$lib_363.coerce(containerIn, containerOut, _$attributes_312, attr, dflt); - } - - function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_363.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_318, attr, dflt); - } - - var visible = coerce('visible'); - if(!visible) return; - - coerce('bgcolor', layoutOut.plot_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('thickness'); - - axOut._rangesliderAutorange = 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')) === _$axis_ids_410.name2id(axName); - }) - .map(function(subplotId) { - return subplotId.substr(subplotId.indexOf('y'), subplotId.length); - }); - var yNames = _$lib_363.simpleMap(yIds, _$axis_ids_410.id2name); - for(var i = 0; i < yNames.length; i++) { - var yName = yNames[i]; +'use strict'; - var rangeContainerIn = containerIn[yName] || {}; - var rangeContainerOut = containerOut[yName] = {}; +_$helpers_360.legendGetsTrace = function legendGetsTrace(trace) { + // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? + // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. - var yAxOut = layoutOut[yName]; + // Note that we explicitly include showlegend: false, so a trace that *could* be + // in the legend but is not shown still counts toward the two traces you need to + // ensure the legend is shown by default, because this can still help disambiguate. + return trace.visible && (trace.showlegend !== undefined); +}; - var rangemodeDflt; - if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { - rangemodeDflt = 'fixed'; - } +_$helpers_360.isGrouped = function isGrouped(legendLayout) { + return (legendLayout.traceorder || '').indexOf('grouped') !== -1; +}; - var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); - if(rangeMode !== 'match') { - coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); - } - yAxOut._rangesliderAutorange = (rangeMode === 'auto'); - } - } +_$helpers_360.isVertical = function isVertical(legendLayout) { + return legendLayout.orientation !== 'h'; +}; - // to map back range slider (auto) range - containerOut._input = containerIn; +_$helpers_360.isReversed = function isReversed(legendLayout) { + return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; /** @@ -69828,647 +71530,484 @@ var _$handleDefaults_315 = function handleDefaults(layoutIn, layoutOut, axName) * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$titles_332 = require('../titles'); */; - -/* removed: var _$cartesian_418 = require('../../plots/cartesian'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$setCursor_382 = require('../../lib/setcursor'); */; - -/* removed: var _$constants_314 = require('./constants'); */; - -var _$draw_316 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); - - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ - - function keyFunction(axisOpts) { - return axisOpts._name; - } - - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_314.containerClassName) - .data(rangeSliderData, keyFunction); - - rangeSliders.enter().append('g') - .classed(_$constants_314.containerClassName, true) - .attr('pointer-events', 'all'); - - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_68.select(this), - opts = axisOpts[_$constants_314.name]; - - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); - - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); - - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; - - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_68.select(this), - opts = axisOpts[_$constants_314.name], - oppAxisOpts = fullLayout[_$axes_407.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_407.id2name(axisOpts.anchor)]; - - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; - - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } - - axisOpts.cleanRange('rangeslider.range'); - - - // update range slider dimensions - - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; - - var oppBottom = Infinity; - var subplotData = _$axes_407.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_407.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); - } - - opts._id = _$constants_314.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; - - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); - - var x = Math.round(margin.l + (graphSize.w * domain[0])); - - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_314.extraPad - ); - - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); - - // update data <--> pixel coordinate conversion methods - - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; - - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; - - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; - }; - - opts._rl = [range0, range1]; - - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; - - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; - } - - // update inner nodes - - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); - - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); - - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_332.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' - } - }); - } - - // update margins - _$plots_444.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_314.extraPad + opts._offsetShift * 2 - }); - }); -}; - -function makeRangeSliderData(fullLayout) { - var axes = _$axes_407.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_314.name, - out = []; - - if(fullLayout._has('gl2d')) return out; - - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; - - if(ax[name] && ax[name].visible) out.push(ax); - } - - return out; -} - -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_314.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_314.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_314.grabAreaMaxClassName).node(); - - rangeSlider.on('mousedown', function() { - var event = _$d3_68.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); - - var dragCover = _$dragelement_261.coverSlip(); - - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); - - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; - - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; - - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; - - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } +'use strict'; - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; +/* removed: var _$attributes_354 = require('./attributes'); */; +/* removed: var _$layout_attributes_504 = require('../../plots/layout_attributes'); */; +/* removed: var _$helpers_360 = require('./helpers'); */; - _$setCursor_382(_$d3_68.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); - } - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_363.removeElement(dragCover); - } - }); -} +var _$legendDefaults_356 = function legendDefaults(layoutIn, layoutOut, fullData) { + var containerIn = layoutIn.legend || {}; + var containerOut = {}; -function setDataRange(rangeSlider, gd, axisOpts, opts) { + var visibleTraces = 0; + var defaultOrder = 'normal'; - function clamp(v) { - return axisOpts.l2r(_$lib_363.constrain(v, opts._rl[0], opts._rl[1])); - } + var defaultX, defaultY, defaultXAnchor, defaultYAnchor; - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; - window.requestAnimationFrame(function() { - _$registry_451.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} + if(_$helpers_360.legendGetsTrace(trace)) { + visibleTraces++; + // always show the legend by default if there's a pie + if(_$registry_514.traceIs(trace, 'pie')) visibleTraces++; + } -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_314.handleWidth / 2; + if((_$registry_514.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { + defaultOrder = _$helpers_360.isGrouped({traceorder: defaultOrder}) ? + 'grouped+reversed' : 'reversed'; + } - function clamp(v) { - return _$lib_363.constrain(v, 0, opts._width); + if(trace.legendgroup !== undefined && trace.legendgroup !== '') { + defaultOrder = _$helpers_360.isReversed({traceorder: defaultOrder}) ? + 'reversed+grouped' : 'grouped'; + } } - function clampOppAxis(v) { - return _$lib_363.constrain(v, 0, opts._height); + function coerce(attr, dflt) { + return _$lib_425.coerce(containerIn, containerOut, _$attributes_354, attr, dflt); } - function clampHandle(v) { - return _$lib_363.constrain(v, -hw2, opts._width + hw2); - } + var showLegend = _$lib_425.coerce(layoutIn, layoutOut, + _$layout_attributes_504, 'showlegend', visibleTraces > 1); - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + if(showLegend === false) return; - rangeSlider.select('rect.' + _$constants_314.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); + layoutOut.legend = containerOut; - rangeSlider.select('rect.' + _$constants_314.maskMinClassName) - .attr('width', pixelMin); + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); + _$lib_425.coerceFont(coerce, 'font', layoutOut.font); - rangeSlider.select('rect.' + _$constants_314.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + coerce('orientation'); + if(containerOut.orientation === 'h') { + var xaxis = layoutIn.xaxis; + if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = 1.1; + defaultYAnchor = 'bottom'; + } + else { + defaultX = 0; + defaultXAnchor = 'left'; + defaultY = -0.1; + defaultYAnchor = 'top'; + } + } - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + coerce('traceorder', defaultOrder); + if(_$helpers_360.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); - rangeSlider.select('rect.' + _$constants_314.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + coerce('x', defaultX); + coerce('xanchor', defaultXAnchor); + coerce('y', defaultY); + coerce('yanchor', defaultYAnchor); + _$lib_425.noneOrAll(containerIn, containerOut, ['x', 'y']); +}; - rangeSlider.select('rect.' + _$constants_314.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); +var _$anchor_utils_353 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - rangeSlider.select('rect.' + _$constants_314.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); - } - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; +'use strict'; - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - rangeSlider.select('g.' + _$constants_314.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); +/** + * 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. + */ - rangeSlider.select('g.' + _$constants_314.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} +_$anchor_utils_353.isRightAnchor = function isRightAnchor(opts) { + return ( + opts.xanchor === 'right' || + (opts.xanchor === 'auto' && opts.x >= 2 / 3) + ); +}; -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_314.bgClassName) - .data([0]); +_$anchor_utils_353.isCenterAnchor = function isCenterAnchor(opts) { + return ( + opts.xanchor === 'center' || + (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) + ); +}; - bg.enter().append('rect') - .classed(_$constants_314.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); +_$anchor_utils_353.isBottomAnchor = function isBottomAnchor(opts) { + return ( + opts.yanchor === 'bottom' || + (opts.yanchor === 'auto' && opts.y <= 1 / 3) + ); +}; - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; +_$anchor_utils_353.isMiddleAnchor = function isMiddleAnchor(opts) { + return ( + opts.yanchor === 'middle' || + (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) + ); +}; - var offsetShift = -opts._offsetShift; - var lw = _$drawing_264.crispRound(gd, opts.borderwidth); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} +'use strict'; -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; +var _$constants_355 = { + scrollBarWidth: 6, + scrollBarMinHeight: 20, + scrollBarColor: '#808BA4', + scrollBarMargin: 4 +}; - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); -} +'use strict'; -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_407.getSubplots(gd, axisOpts), - calcData = gd.calcdata; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$helpers_360 = require('./helpers'); */; - var rangePlots = rangeSlider.selectAll('g.' + _$constants_314.rangePlotClassName) - .data(subplotData, _$lib_363.identity); - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_314.rangePlotClassName + ' ' + id; }) - .call(_$drawing_264.setClipUrl, opts._clipId); +var _$getLegendData_358 = function getLegendData(calcdata, opts) { + var lgroupToTraces = {}, + lgroups = [], + hasOneNonBlankGroup = false, + slicesShown = {}, + lgroupi = 0; - rangePlots.order(); + var i, j; - rangePlots.exit().remove(); + function addOneItem(legendGroup, legendItem) { + // each '' legend group is treated as a separate group + if(legendGroup === '' || !_$helpers_360.isGrouped(opts)) { + var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? - var mainplotinfo; + lgroups.push(uniqueGroup); + lgroupToTraces[uniqueGroup] = [[legendItem]]; + lgroupi++; + } + else if(lgroups.indexOf(legendGroup) === -1) { + lgroups.push(legendGroup); + hasOneNonBlankGroup = true; + lgroupToTraces[legendGroup] = [[legendItem]]; + } + else lgroupToTraces[legendGroup].push([legendItem]); + } - rangePlots.each(function(id, i) { - var plotgroup = _$d3_68.select(this), - isMainPlot = (i === 0); + // build an { legendgroup: [cd0, cd0], ... } object + for(i = 0; i < calcdata.length; i++) { + var cd = calcdata[i], + cd0 = cd[0], + trace = cd0.trace, + lgroup = trace.legendgroup; - var oppAxisOpts = _$axes_407.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; + if(!_$helpers_360.legendGetsTrace(trace) || !trace.showlegend) continue; - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + if(_$registry_514.traceIs(trace, 'pie')) { + if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; + for(j = 0; j < cd.length; j++) { + var labelj = cd[j].label; - _$plots_444.supplyDefaults(mockFigure); + if(!slicesShown[lgroup][labelj]) { + addOneItem(lgroup, { + label: labelj, + color: cd[j].color, + i: cd[j].i, + trace: trace + }); - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; + slicesShown[lgroup][labelj] = true; + } + } + } - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya - }; + else addOneItem(lgroup, cd0); + } - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; - } + // won't draw a legend in this case + if(!lgroups.length) return []; - _$cartesian_418.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); -} + // rearrange lgroupToTraces into a d3-friendly array of arrays + var lgroupsLength = lgroups.length, + ltraces, + legendData; -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; + if(hasOneNonBlankGroup && _$helpers_360.isGrouped(opts)) { + legendData = new Array(lgroupsLength); - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]]; + legendData[i] = _$helpers_360.isReversed(opts) ? ltraces.reverse() : ltraces; + } + } + else { + // collapse all groups into one if all groups are blank + legendData = [new Array(lgroupsLength)]; - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); + for(i = 0; i < lgroupsLength; i++) { + ltraces = lgroupToTraces[lgroups[i]][0]; + legendData[0][_$helpers_360.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; } + lgroupsLength = 1; } - return out; -} + // needed in repositionLegend + opts._lgroupsLength = lgroupsLength; + return legendData; +}; -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_314.maskMinClassName) - .data([0]); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - maskMin.enter().append('rect') - .classed(_$constants_314.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); +'use strict'; - maskMin - .attr('height', opts._height) - .call(_$color_239.fill, _$constants_314.maskColor); +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$registry_514 = require('../../registry'); */; - var maskMax = rangeSlider.selectAll('rect.' + _$constants_314.maskMaxClassName) - .data([0]); +var SHOWISOLATETIP = true; - maskMax.enter().append('rect') - .classed(_$constants_314.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); +var _$handleClick_359 = function handleClick(g, gd, numClicks) { + if(gd._dragged || gd._editing) return; - maskMax - .attr('height', opts._height) - .call(_$color_239.fill, _$constants_314.maskColor); + var hiddenSlices = gd._fullLayout.hiddenlabels ? + gd._fullLayout.hiddenlabels.slice() : + []; - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_314.maskMinOppAxisClassName) - .data([0]); + var legendItem = g.data()[0][0]; + var fullData = gd._fullData; + var fullTrace = legendItem.trace; + var legendgroup = fullTrace.legendgroup; - maskMinOppAxis.enter().append('rect') - .classed(_$constants_314.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var i, j, kcont, key, keys, val; + var attrUpdate = {}; + var attrIndices = []; + var carrs = []; + var carrIdx = []; - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_239.fill, _$constants_314.maskOppAxisColor); + function insertUpdate(traceIndex, key, value) { + var attrIndex = attrIndices.indexOf(traceIndex); + var valueArray = attrUpdate[key]; + if(!valueArray) { + valueArray = attrUpdate[key] = []; + } - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_314.maskMaxOppAxisClassName) - .data([0]); + if(attrIndices.indexOf(traceIndex) === -1) { + attrIndices.push(traceIndex); + attrIndex = attrIndices.length - 1; + } - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_314.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + valueArray[attrIndex] = value; - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_314.maskOppBorder) - .call(_$color_239.fill, _$constants_314.maskOppAxisColor); + return attrIndex; } -} - -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; - var slideBox = rangeSlider.selectAll('rect.' + _$constants_314.slideBoxClassName) - .data([0]); + function setVisibility(fullTrace, visibility) { + var fullInput = fullTrace._fullInput; + if(_$registry_514.hasTransform(fullInput, 'groupby')) { + var kcont = carrs[fullInput.index]; + if(!kcont) { + var groupbyIndices = _$registry_514.getTransformIndices(fullInput, 'groupby'); + var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; + kcont = _$lib_425.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + carrs[fullInput.index] = kcont; + } - slideBox.enter().append('rect') - .classed(_$constants_314.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_314.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); + var curState = kcont.get(fullTrace._group); - slideBox.attr({ - height: opts._height, - fill: _$constants_314.slideBoxFill - }); -} + // 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; + } -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + 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); + } + } - var grabberMin = rangeSlider.selectAll('g.' + _$constants_314.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_314.grabberMinClassName, true); + if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { + _$lib_425.notifier(_$lib_425._(gd, 'Double-click on legend to isolate one trace'), 'long'); + SHOWISOLATETIP = false; + } else { + SHOWISOLATETIP = false; + } - var grabberMax = rangeSlider.selectAll('g.' + _$constants_314.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_314.grabberMaxClassName, true); + if(_$registry_514.traceIs(fullTrace, 'pie')) { + var thisLabel = legendItem.label, + thisLabelIndex = hiddenSlices.indexOf(thisLabel); - // + if(numClicks === 1) { + if(thisLabelIndex === -1) hiddenSlices.push(thisLabel); + else hiddenSlices.splice(thisLabelIndex, 1); + } else if(numClicks === 2) { + 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 = []; + } + } - var handleFixAttrs = { - x: 0, - width: _$constants_314.handleWidth, - rx: _$constants_314.handleRadius, - fill: _$color_239.background, - stroke: _$color_239.defaultLine, - 'stroke-width': _$constants_314.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; + _$registry_514.call('relayout', 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); + } + } + } - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; + if(numClicks === 1) { + var nextVisibility; - var handleMin = grabberMin.selectAll('rect.' + _$constants_314.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_314.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); + switch(fullTrace.visible) { + case true: + nextVisibility = 'legendonly'; + break; + case false: + nextVisibility = false; + break; + case 'legendonly': + nextVisibility = true; + break; + } - var handleMax = grabberMax.selectAll('rect.' + _$constants_314.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_314.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); + 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(numClicks === 2) { + // 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, otherState; + var isIsolated = true; + for(i = 0; i < fullData.length; i++) { + isClicked = fullData[i] === fullTrace; + if(isClicked) continue; - // + isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - if(gd._context.staticPlot) return; + if(!isInGroup && fullData[i].visible === true && !_$registry_514.traceIs(fullData[i], 'notLegendIsolatable')) { + isIsolated = false; + break; + } + } - var grabAreaFixAttrs = { - width: _$constants_314.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_314.grabAreaFill, - cursor: _$constants_314.grabAreaCursor - }; + for(i = 0; i < fullData.length; i++) { + // False is sticky; we don't change it. + if(fullData[i].visible === false) continue; - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_314.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_314.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); + if(_$registry_514.traceIs(fullData[i], 'notLegendIsolatable')) { + continue; + } - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_314.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_314.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); -} + switch(fullTrace.visible) { + case 'legendonly': + setVisibility(fullData[i], true); + break; + case true: + otherState = isIsolated ? true : 'legendonly'; + isClicked = fullData[i] === fullTrace; + isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup); + setVisibility(fullData[i], isInGroup ? true : otherState); + break; + } + } + } -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + for(i = 0; i < carrs.length; i++) { + kcont = carrs[i]; + if(!kcont) continue; + var update = kcont.constructUpdate(); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + 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]; + } + } - if(k.indexOf(_$constants_314.name) !== -1) { - _$plots_444.autoMargin(gd, k); + // 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_514.call('restyle', gd, attrUpdate, attrIndices); } -} +}; +var _$helpers_569 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -70479,28 +72018,35 @@ function clearPushMargins(gd) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$attributes_312 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_318 = require('./oppaxis_attributes'); */; +/* removed: var _$lib_425 = require('../../lib'); */; -var _$rangeslider_317 = { - moduleType: 'component', - name: 'rangeslider', +_$helpers_569.formatPiePercent = function formatPiePercent(v, separators) { + var vRounded = (v * 100).toPrecision(3); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_425.numSeparate(vRounded, separators) + '%'; +}; - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_363.extendFlat({}, _$attributes_312, { - yaxis: _$oppaxis_attributes_318 - }) - } - } - }, +_$helpers_569.formatPieValue = function formatPieValue(v, separators) { + var vRounded = v.toPrecision(10); + if(vRounded.lastIndexOf('.') !== -1) { + vRounded = vRounded.replace(/[.]?0+$/, ''); + } + return _$lib_425.numSeparate(vRounded, separators); +}; + +_$helpers_569.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) return v; + } +}; - layoutAttributes: _$attributes_312, - handleDefaults: _$handleDefaults_315, - calcAutorange: _$calcAutorange_313, - draw: _$draw_316 +_$helpers_569.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_569.getFirstFilled(item, indices); + else if(item) return item; }; /** @@ -70513,102 +72059,17 @@ var _$rangeslider_317 = { 'use strict'; -/* removed: var _$attributes_224 = require('../annotations/attributes'); */; -var __scatterLineAttrs_319 = _$attributes_512.line; -var __dash_319 = _$attributes_263.dash; -var __extendFlat_319 = _$extend_354.extendFlat; - -var _$attributes_319 = { - _isLinkedToArray: 'shape', - - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, - - type: { - valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], - - editType: 'calcIfAutorange+arraydraw', - - }, - - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, - - xref: __extendFlat_319({}, _$attributes_224.xref, { - - }), - x0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - x1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - - yref: __extendFlat_319({}, _$attributes_224.yref, { - - }), - y0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - y1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, +/* removed: var _$color_301 = require('../../components/color'); */; +var castOption = _$helpers_569.castOption; - path: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, +var _$styleOne_570 = function styleOne(s, pt, trace) { + var line = trace.marker.line; + var lineColor = castOption(line.color, pt.pts) || _$color_301.defaultLine; + var lineWidth = castOption(line.width, pt.pts) || 0; - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - line: { - color: __extendFlat_319({}, __scatterLineAttrs_319.color, {editType: 'arraydraw'}), - width: __extendFlat_319({}, __scatterLineAttrs_319.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_319({}, __dash_319, {editType: 'arraydraw'}), - - editType: 'calcIfAutorange+arraydraw' - }, - fillcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' + s.style({'stroke-width': lineWidth}) + .call(_$color_301.fill, pt.color) + .call(_$color_301.stroke, lineColor); }; /** @@ -70619,140 +72080,280 @@ var _$attributes_319 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$d3_71 = require('d3'); */; -var _$constants_321 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$color_301 = require('../color'); */; - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, +/* removed: var _$subtypes_598 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_570 = require('../../traces/pie/style_one'); */; - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} - }, +var _$style_362 = function style(s, gd) { + s.each(function(d) { + var traceGroup = _$d3_71.select(this); - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 + var layers = _$lib_425.ensureSingle(traceGroup, 'g', 'layers'); + layers.style('opacity', d[0].trace.opacity); + + var fill = layers + .selectAll('g.legendfill') + .data([d]); + fill.enter().append('g') + .classed('legendfill', true); + + var line = layers + .selectAll('g.legendlines') + .data([d]); + line.enter().append('g') + .classed('legendlines', true); + + var symbol = layers + .selectAll('g.legendsymbols') + .data([d]); + symbol.enter().append('g') + .classed('legendsymbols', true); + + symbol.selectAll('g.legendpoints') + .data([d]) + .enter().append('g') + .classed('legendpoints', true); + }) + .each(styleBars) + .each(styleBoxes) + .each(stylePies) + .each(styleLines) + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); + + function styleLines(d) { + var trace = d[0].trace; + var showFill = trace.visible && trace.fill && trace.fill !== 'none'; + var showLine = _$subtypes_598.hasLines(trace); + var contours = trace.contours; + + if(contours && contours.type === 'constraint') { + showLine = contours.showlines; + showFill = contours._operation !== '='; + } + + var fill = _$d3_71.select(this).select('.legendfill').selectAll('path') + .data(showFill ? [d] : []); + fill.enter().append('path').classed('js-fill', true); + fill.exit().remove(); + fill.attr('d', 'M5,0h30v6h-30z') + .call(_$drawing_326.fillGroupStyle); + + var line = _$d3_71.select(this).select('.legendlines').selectAll('path') + .data(showLine ? [d] : []); + line.enter().append('path').classed('js-line', true) + .attr('d', 'M5,0h30'); + line.exit().remove(); + line.call(_$drawing_326.lineGroupStyle); } -}; -var _$helpers_324 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function stylePoints(d) { + var d0 = d[0], + trace = d0.trace, + showMarkers = _$subtypes_598.hasMarkers(trace), + showText = _$subtypes_598.hasText(trace), + showLines = _$subtypes_598.hasLines(trace); + var dMod, tMod; -'use strict'; + // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet; + // use d0.trace to infer arrayOk attributes -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. + function boundVal(attrIn, arrayToValFn, bounds) { + var valIn = _$lib_425.nestedProperty(trace, attrIn).get(), + valToBound = (Array.isArray(valIn) && arrayToValFn) ? + arrayToValFn(valIn) : valIn; -_$helpers_324.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; + if(bounds) { + if(valToBound < bounds[0]) return bounds[0]; + else if(valToBound > bounds[1]) return bounds[1]; + } + return valToBound; + } -_$helpers_324.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; + function pickFirst(array) { return array[0]; } -_$helpers_324.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; + // constrain text, markers, etc so they'll fit on the legend + if(showMarkers || showText || showLines) { + var dEdit = {}, + tEdit = {}; -_$helpers_324.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; + if(showMarkers) { + dEdit.mc = boundVal('marker.color', pickFirst); + dEdit.mo = boundVal('marker.opacity', _$lib_425.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_425.mean, [2, 16]); + dEdit.mlc = boundVal('marker.line.color', pickFirst); + dEdit.mlw = boundVal('marker.line.width', _$lib_425.mean, [0, 5]); + tEdit.marker = { + sizeref: 1, + sizemin: 1, + sizemode: 'diameter' + }; + } -_$helpers_324.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; + if(showLines) { + tEdit.line = { + width: boundVal('line.width', pickFirst, [0, 10]) + }; + } - if(axis) { - var d2r = _$helpers_324.shapePositionToRange(axis); + if(showText) { + dEdit.tx = 'Aa'; + dEdit.tp = boundVal('textposition', pickFirst); + dEdit.ts = 10; + dEdit.tc = boundVal('textfont.color', pickFirst); + dEdit.tf = boundVal('textfont.family', pickFirst); + } - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; + dMod = [_$lib_425.minExtend(d0, dEdit)]; + tMod = _$lib_425.minExtend(trace, tEdit); + } - if(axis.type === 'date') dataToPixel = _$helpers_324.decodeDate(dataToPixel); - } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + var ptgroup = _$d3_71.select(this).select('g.legendpoints'); + + var pts = ptgroup.selectAll('path.scatterpts') + .data(showMarkers ? dMod : []); + pts.enter().append('path').classed('scatterpts', true) + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.call(_$drawing_326.pointStyle, tMod, gd); + + // 'mrc' is set in pointStyle and used in textPointStyle: + // constrain it here + if(showMarkers) dMod[0].mrc = 3; + + var txt = ptgroup.selectAll('g.pointtext') + .data(showText ? dMod : []); + txt.enter() + .append('g').classed('pointtext', true) + .append('text').attr('transform', 'translate(20,0)'); + txt.exit().remove(); + txt.selectAll('text').call(_$drawing_326.textPointStyle, tMod, gd); } - else { - dataToPixel = function(v) { return gs.l + gs.w * v; }; + + function styleBars(d) { + var trace = d[0].trace, + marker = trace.marker || {}, + markerLine = marker.line || {}, + barpath = _$d3_71.select(this).select('g.legendpoints') + .selectAll('path.legendbar') + .data(_$registry_514.traceIs(trace, 'bar') ? [d] : []); + barpath.enter().append('path').classed('legendbar', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + barpath.exit().remove(); + barpath.each(function(d) { + var p = _$d3_71.select(this), + d0 = d[0], + w = (d0.mlw + 1 || markerLine.width + 1) - 1; + + p.style('stroke-width', w + 'px') + .call(_$color_301.fill, d0.mc || marker.color); + + if(w) { + p.call(_$color_301.stroke, d0.mlc || markerLine.color); + } + }); } - return dataToPixel; -}; + function styleBoxes(d) { + var trace = d[0].trace, + pts = _$d3_71.select(this).select('g.legendpoints') + .selectAll('path.legendbox') + .data(_$registry_514.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendbox', true) + // if we want the median bar, prepend M6,0H-6 + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + pts.each(function() { + var w = trace.line.width, + p = _$d3_71.select(this); -_$helpers_324.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; + p.style('stroke-width', w + 'px') + .call(_$color_301.fill, trace.fillcolor); - if(axis) { - var r2d = _$helpers_324.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + if(w) { + _$color_301.stroke(p, trace.line.color); + } + }); } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_71.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_71.select(this); + + p.style('stroke-width', w + 'px') + .call(_$color_301.fill, container.fillcolor); + + if(w) { + _$color_301.stroke(p, container.line.color); + } + }); } - else { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; + + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_71.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_71.select(this); + + p.style('fill', 'none') + .call(_$drawing_326.dashLine, container.line.dash, w); + + if(w) { + _$color_301.stroke(p, container.line.color); + } + }); } - return pixelToData; + function stylePies(d) { + var trace = d[0].trace, + pts = _$d3_71.select(this).select('g.legendpoints') + .selectAll('path.legendpie') + .data(_$registry_514.traceIs(trace, 'pie') && trace.visible ? [d] : []); + pts.enter().append('path').classed('legendpie', true) + .attr('d', 'M6,6H-6V-6H6Z') + .attr('transform', 'translate(20,0)'); + pts.exit().remove(); + + if(pts.size()) pts.call(_$styleOne_570, d[0], trace); + } }; /** @@ -70763,567 +72364,693 @@ _$helpers_324.getPixelToData = function(gd, axis, isVertical) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; +/* removed: var _$d3_71 = require('d3'); */; -/* removed: var _$constants_321 = require('./constants'); */; -/* removed: var _$helpers_324 = require('./helpers'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$handleClick_359 = require('./handle_click'); */; +/* removed: var _$constants_355 = require('./constants'); */; +/* removed: var _$interactions_403 = require('../../constants/interactions'); */; +/* removed: var _$alignment_401 = require('../../constants/alignment'); */; +var __LINE_SPACING_357 = _$alignment_401.LINE_SPACING; +var __FROM_TL_357 = _$alignment_401.FROM_TL; +var FROM_BR = _$alignment_401.FROM_BR; -var _$calcAutorange_320 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_363.filterVisible(fullLayout.shapes); +/* removed: var _$getLegendData_358 = require('./get_legend_data'); */; +/* removed: var _$style_362 = require('./style'); */; +/* removed: var _$helpers_360 = require('./helpers'); */; +/* removed: var _$anchor_utils_353 = require('./anchor_utils'); */; - if(!shapeList.length || !gd._fullData.length) return; +var DBLCLICKDELAY = _$interactions_403.DBLCLICKDELAY; - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; +var _$draw_357 = function draw(gd) { + var fullLayout = gd._fullLayout; + var clipId = 'legend' + fullLayout._uid; - var ax, bounds; + if(!fullLayout._infolayer || !gd.calcdata) return; - if(shape.xref !== 'paper') { - ax = _$axes_407.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_321.paramIsX); - if(bounds) _$axes_407.expand(ax, bounds, {ppad: ppad}); - } + if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; - if(shape.yref !== 'paper') { - ax = _$axes_407.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_321.paramIsY); - if(bounds) _$axes_407.expand(ax, bounds, {ppad: ppad}); - } + var opts = fullLayout.legend, + legendData = fullLayout.showlegend && _$getLegendData_358(gd.calcdata, opts), + hiddenSlices = fullLayout.hiddenlabels || []; + + if(!fullLayout.showlegend || !legendData.length) { + fullLayout._infolayer.selectAll('.legend').remove(); + fullLayout._topdefs.select('#' + clipId).remove(); + + _$plots_506.autoMargin(gd, 'legend'); + return; + } + + var firstRender = false; + var legend = _$lib_425.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); + + var clipPath = _$lib_425.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); + + var bg = _$lib_425.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); + + bg.call(_$color_301.stroke, opts.bordercolor) + .call(_$color_301.fill, opts.bgcolor) + .style('stroke-width', opts.borderwidth + 'px'); + + var scrollBox = _$lib_425.ensureSingle(legend, 'g', 'scrollbox'); + + var scrollBar = _$lib_425.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ + rx: 20, + ry: 3, + width: 0, + height: 0 + }) + .call(_$color_301.fill, '#808BA4'); + }); + + var groups = scrollBox.selectAll('g.groups') + .data(legendData); + + groups.enter().append('g') + .attr('class', 'groups'); + + groups.exit().remove(); + + var traces = groups.selectAll('g.traces') + .data(_$lib_425.identity); + + traces.enter().append('g').attr('class', 'traces'); + traces.exit().remove(); + + traces.call(_$style_362, gd) + .style('opacity', function(d) { + var trace = d[0].trace; + if(_$registry_514.traceIs(trace, 'pie')) { + return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; + } else { + return trace.visible === 'legendonly' ? 0.5 : 1; + } + }) + .each(function() { + _$d3_71.select(this) + .call(drawTexts, gd) + .call(setupTraceToggle, gd); + }); + + if(firstRender) { + computeLegendDimensions(gd, groups, traces); + expandMargin(gd); + } + + // Position and size the legend + var lxMin = 0, + lxMax = fullLayout.width, + lyMin = 0, + lyMax = fullLayout.height; + + computeLegendDimensions(gd, groups, traces); + + if(opts._height > lyMax) { + // If the legend doesn't fit in the plot area, + // do not expand the vertical margins. + expandHorizontalMargin(gd); + } else { + expandMargin(gd); + } + + // Scroll section must be executed after repositionLegend. + // It requires the legend width, height, x and y to position the scrollbox + // and these values are mutated in repositionLegend. + var gs = fullLayout._size, + lx = gs.l + gs.w * opts.x, + ly = gs.t + gs.h * (1 - opts.y); + + if(_$anchor_utils_353.isRightAnchor(opts)) { + lx -= opts._width; + } + else if(_$anchor_utils_353.isCenterAnchor(opts)) { + lx -= opts._width / 2; + } + + if(_$anchor_utils_353.isBottomAnchor(opts)) { + ly -= opts._height; + } + else if(_$anchor_utils_353.isMiddleAnchor(opts)) { + ly -= opts._height / 2; + } + + // Make sure the legend left and right sides are visible + var legendWidth = opts._width, + legendWidthMax = gs.w; + + if(legendWidth > legendWidthMax) { + lx = gs.l; + legendWidth = legendWidthMax; + } + else { + if(lx + legendWidth > lxMax) lx = lxMax - legendWidth; + if(lx < lxMin) lx = lxMin; + legendWidth = Math.min(lxMax - lx, opts._width); + } + + // Make sure the legend top and bottom are visible + // (legends with a scroll bar are not allowed to stretch beyond the extended + // margins) + var legendHeight = opts._height, + legendHeightMax = gs.h; + + if(legendHeight > legendHeightMax) { + ly = gs.t; + legendHeight = legendHeightMax; + } + else { + if(ly + legendHeight > lyMax) ly = lyMax - legendHeight; + if(ly < lyMin) ly = lyMin; + legendHeight = Math.min(lyMax - ly, opts._height); } -}; -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; + // Set size and position of all the elements that make up a legend: + // legend, background and border, scroll box and scroll bar + _$drawing_326.setTranslate(legend, lx, ly); - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; + // to be safe, remove previous listeners + scrollBar.on('.drag', null); + legend.on('wheel', null); - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_321.segmentRE), - i, - segment, - drawnParam, - params, - val; + if(opts._height <= legendHeight || gd._context.staticPlot) { + // if scrollbar should not be shown. + bg.attr({ + width: legendWidth - opts.borderwidth, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - if(ax.type === 'date') convertVal = _$helpers_324.decodeDate(convertVal); + _$drawing_326.setTranslate(scrollBox, 0, 0); - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; + clipPath.select('rect').attr({ + width: legendWidth - 2 * opts.borderwidth, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + }); - params = segments[i].substr(1).match(_$constants_321.paramRE); - if(!params || params.length < drawnParam) continue; + _$drawing_326.setClipUrl(scrollBox, clipId); - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; + _$drawing_326.setRect(scrollBar, 0, 0, 0, 0); + delete opts._scrollY; } - if(max >= min) return [min, max]; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + else { + var scrollBarHeight = Math.max(_$constants_355.scrollBarMinHeight, + legendHeight * legendHeight / opts._height); + var scrollBarYMax = legendHeight - + scrollBarHeight - + 2 * _$constants_355.scrollBarMargin; + var scrollBoxYMax = opts._height - legendHeight; + var scrollRatio = scrollBarYMax / scrollBoxYMax; + var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax); -'use strict'; + // increase the background and clip-path width + // by the scrollbar width and margin + bg.attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_355.scrollBarWidth + + _$constants_355.scrollBarMargin, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; + clipPath.select('rect').attr({ + width: legendWidth - + 2 * opts.borderwidth + + _$constants_355.scrollBarWidth + + _$constants_355.scrollBarMargin, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth, + y: opts.borderwidth + scrollBoxY + }); -/* removed: var _$attributes_319 = require('./attributes'); */; -/* removed: var _$helpers_324 = require('./helpers'); */; + _$drawing_326.setClipUrl(scrollBox, clipId); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); -var _$handleShapeDefaults_326 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + legend.on('wheel', function() { + scrollBoxY = _$lib_425.constrain( + opts._scrollY + + _$d3_71.event.deltaY / scrollBarYMax * scrollBoxYMax, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { + _$d3_71.event.preventDefault(); + } + }); - function coerce(attr, dflt) { - return _$lib_363.coerce(shapeIn, shapeOut, _$attributes_319, attr, dflt); - } + var eventY0, scrollBoxY0; - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + var drag = _$d3_71.behavior.drag() + .on('dragstart', function() { + eventY0 = _$d3_71.event.sourceEvent.clientY; + scrollBoxY0 = scrollBoxY; + }) + .on('drag', function() { + var e = _$d3_71.event.sourceEvent; + if(e.buttons === 2 || e.ctrlKey) return; - if(!visible) return shapeOut; + scrollBoxY = _$lib_425.constrain( + (e.clientY - eventY0) / scrollRatio + scrollBoxY0, + 0, scrollBoxYMax); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + }); - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); + scrollBar.call(drag); + } - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { + opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; + _$drawing_326.setTranslate(scrollBox, 0, -scrollBoxY); - // xref, yref - var axRef = _$axes_407.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + _$drawing_326.setRect( + scrollBar, + legendWidth, + _$constants_355.scrollBarMargin + scrollBoxY * scrollRatio, + _$constants_355.scrollBarWidth, + scrollBarHeight + ); + clipPath.select('rect').attr({ + y: opts.borderwidth + scrollBoxY + }); + } - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + if(gd._context.edits.legendPosition) { + var xf, yf, x0, y0; - if(axRef !== 'paper') { - ax = _$axes_407.getFromId(gdMock, axRef); - r2pos = _$helpers_324.rangeToShapePosition(ax); - pos2r = _$helpers_324.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_363.identity; - } + legend.classed('cursor-move', true); - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); + _$dragelement_323.init({ + element: legend.node(), + gd: gd, + prepFn: function() { + var transform = _$drawing_326.getTranslate(legend); - // x0, x1 (and y0, y1) - _$axes_407.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_407.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + x0 = transform.x; + y0 = transform.y; + }, + moveFn: function(dx, dy) { + var newX = x0 + dx, + newY = y0 + dy; - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; - } - } + _$drawing_326.setTranslate(legend, newX, newY); - if(shapeType === 'path') { - coerce('path'); - } - else { - _$lib_363.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + xf = _$dragelement_323.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); + yf = _$dragelement_323.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); + }, + doneFn: function() { + if(xf !== undefined && yf !== undefined) { + _$registry_514.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + } + }, + clickFn: function(numClicks, e) { + var clickedTrace = + fullLayout._infolayer.selectAll('g.traces').filter(function() { + var bbox = this.getBoundingClientRect(); + return (e.clientX >= bbox.left && e.clientX <= bbox.right && + e.clientY >= bbox.top && e.clientY <= bbox.bottom); + }); + if(clickedTrace.size() > 0) { + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { + _$handleClick_359(clickedTrace, gd, numClicks); + }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + _$handleClick_359(clickedTrace, gd, numClicks); + } + } + } + }); } - - return shapeOut; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; +function drawTexts(g, gd) { + var legendItem = g.data()[0][0], + fullLayout = gd._fullLayout, + trace = legendItem.trace, + isPie = _$registry_514.traceIs(trace, 'pie'), + traceIndex = trace.index, + name = isPie ? legendItem.label : trace.name; -/* removed: var _$handleArrayContainerDefaults_403 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_326 = require('./shape_defaults'); */; + var text = _$lib_425.ensureSingle(g, 'text', 'legendtext'); + text.attr('text-anchor', 'start') + .classed('user-select-none', true) + .call(_$drawing_326.font, fullLayout.legend.font) + .text(name); -var _$supplyLayoutDefaults_322 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_326 - }; + function textLayout(s) { + _$svg_text_utils_449.convertToTspans(s, gd, function() { + computeTextDimensions(g, gd); + }); + } - _$handleArrayContainerDefaults_403(layoutIn, layoutOut, opts); -}; + if(gd._context.edits.legendText && !isPie) { + text.call(_$svg_text_utils_449.makeEditable, {gd: gd}) + .call(textLayout) + .on('edit', function(text) { + this.text(text) + .call(textLayout); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 origText = text; + if(!this.text()) text = ' \u0020\u0020 '; -'use strict'; + var fullInput = legendItem.trace._fullInput || {}; + var update = {}; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; + if(_$registry_514.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_514.getTransformIndices(fullInput, 'groupby'); + var index = groupbyIndices[groupbyIndices.length - 1]; -/* removed: var _$dragelement_261 = require('../dragelement'); */; -/* removed: var _$setCursor_382 = require('../../lib/setcursor'); */; + var kcont = _$lib_425.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); -/* removed: var _$constants_321 = require('./constants'); */; -/* removed: var _$helpers_324 = require('./helpers'); */; + if(origText === '') { + kcont.remove(legendItem.trace._group); + } else { + kcont.set(legendItem.trace._group, text); + } + update = kcont.constructUpdate(); + } else { + update.name = text; + } -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one + return _$registry_514.call('restyle', gd, update, traceIndex); + }); + } else { + textLayout(text); + } +} -var _$draw_323 = { - draw: __draw_323, - drawOne: __drawOne_323 -}; +function setupTraceToggle(g, gd) { + var newMouseDownTime, + numClicks = 1; -function __draw_323(gd) { - var fullLayout = gd._fullLayout; + var traceToggle = _$lib_425.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_301.fill, 'rgba(0,0,0,0)'); + }); - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + traceToggle.on('mousedown', function() { + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) { + // 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; - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_323(gd, i); + if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); } - } - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); + if(numClicks === 1) { + legend._clickTimeout = setTimeout(function() { _$handleClick_359(g, gd, numClicks); }, DBLCLICKDELAY); + } else if(numClicks === 2) { + if(legend._clickTimeout) { + clearTimeout(legend._clickTimeout); + } + gd._legendMouseDownTime = 0; + _$handleClick_359(g, gd, numClicks); + } + }); } -function __drawOne_323(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); +function computeTextDimensions(g, gd) { + var legendItem = g.data()[0][0]; - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; + if(!legendItem.trace.showlegend) { + g.remove(); + return; + } - // this shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; + var mathjaxGroup = g.select('g[class*=math-group]'); + var mathjaxNode = mathjaxGroup.node(); + var opts = gd._fullLayout.legend; + var lineHeight = opts.font.size * __LINE_SPACING_357; + var height, width; - if(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); + if(mathjaxNode) { + var mathjaxBB = _$drawing_326.bBox(mathjaxNode); + + height = mathjaxBB.height; + width = mathjaxBB.width; + + _$drawing_326.setTranslate(mathjaxGroup, 0, (height / 4)); } else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } - } - - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; + var text = g.select('.legendtext'); + var textLines = _$svg_text_utils_449.lineCount(text); + var textNode = text.node(); - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_239.stroke, lineColor) - .call(_$color_239.fill, options.fillcolor) - .call(_$drawing_264.dashLine, options.line.dash, options.line.width); + height = lineHeight * textLines; + width = textNode ? _$drawing_326.bBox(textNode).width : 0; - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); + // approximation to height offset to center the font + // to avoid getBoundingClientRect + var textY = lineHeight * (0.3 + (1 - textLines) / 2); + // TODO: this 40 should go in a constants file (along with other + // values related to the legend symbol size) + _$svg_text_utils_449.positionText(text, 40, textY); + } - path.call(_$drawing_264.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); + height = Math.max(height, 16) + 3; - if(gd._context.edits.shapePosition) __setupDragElement_323(gd, path, options, index); - } + legendItem.height = height; + legendItem.width = width; } -function __setupDragElement_323(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; +function computeLegendDimensions(gd, groups, traces) { + var fullLayout = gd._fullLayout; + var opts = fullLayout.legend; + var borderwidth = opts.borderwidth; + var isGrouped = _$helpers_360.isGrouped(opts); - var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; + var extraWidth = 0; - var xa, ya, x2p, y2p, p2x, p2y; + opts._width = 0; + opts._height = 0; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag - }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; + if(_$helpers_360.isVertical(opts)) { + if(isGrouped) { + groups.each(function(d, i) { + _$drawing_326.setTranslate(this, 0, i * opts.tracegroupgap); + }); + } - _$dragelement_261.init(dragOptions); + traces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height, + textWidth = legendItem.width; - shapePath.node().onmousemove = updateDragMode; + _$drawing_326.setTranslate(this, + borderwidth, + (5 + borderwidth + opts._height + textHeight / 2)); - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_261.getCursor(x / w, 1 - y / h) : - 'move'; + opts._height += textHeight; + opts._width = Math.max(opts._width, textWidth); + }); - _$setCursor_382(shapePath, cursor); + opts._width += 45 + borderwidth * 2; + opts._height += 10 + borderwidth * 2; - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; - } + if(isGrouped) { + opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap; + } - function startDrag(evt) { - // setup conversion functions - xa = _$axes_407.getFromId(gd, shapeOptions.xref); - ya = _$axes_407.getFromId(gd, shapeOptions.yref); + extraWidth = 40; + } + else if(isGrouped) { + var groupXOffsets = [opts._width], + groupData = groups.data(); - x2p = _$helpers_324.getDataToPixel(gd, xa); - y2p = _$helpers_324.getDataToPixel(gd, ya, true); - p2x = _$helpers_324.getPixelToData(gd, xa); - p2y = _$helpers_324.getPixelToData(gd, ya, true); + for(var i = 0, n = groupData.length; i < n; i++) { + var textWidths = groupData[i].map(function(legendItemArray) { + return legendItemArray[0].width; + }); - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; - } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + var groupWidth = 40 + Math.max.apply(null, textWidths); - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } + opts._width += opts.tracegroupgap + groupWidth; - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; - } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + groupXOffsets.push(opts._width); } - update = {}; + groups.each(function(d, i) { + _$drawing_326.setTranslate(this, groupXOffsets[i], 0); + }); - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; - } + groups.each(function() { + var group = _$d3_71.select(this), + groupTraces = group.selectAll('g.traces'), + groupHeight = 0; - function endDrag() { - _$setCursor_382(shapePath); - _$registry_451.call('relayout', gd, update); - } + groupTraces.each(function(d) { + var legendItem = d[0], + textHeight = legendItem.height; - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_324.encodeDate(moveX); + _$drawing_326.setTranslate(this, + 0, + (5 + borderwidth + groupHeight + textHeight / 2)); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_324.encodeDate(moveY); + groupHeight += textHeight; + }); - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } + opts._height = Math.max(opts._height, groupHeight); + }); - shapePath.attr('d', getPathString(gd, shapeOptions)); + opts._height += 10 + borderwidth * 2; + opts._width += borderwidth * 2; } + else { + var rowHeight = 0, + maxTraceHeight = 0, + maxTraceWidth = 0, + offsetX = 0, + fullTracesWidth = 0, + traceGap = opts.tracegroupgap || 5, + oneRowLegend; - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_324.encodeDate(moveX); - - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_324.encodeDate(moveY); - - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; + // calculate largest width for traces and use for width of all legend items + traces.each(function(d) { + maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth); + fullTracesWidth += 40 + d[0].width + traceGap; + }); - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + // check if legend fits in one row + oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap; + traces.each(function(d) { + var legendItem = d[0], + traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth; - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); + if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) { + offsetX = 0; + rowHeight = rowHeight + maxTraceHeight; + opts._height = opts._height + maxTraceHeight; + // reset for next row + maxTraceHeight = 0; } - } - shapePath.attr('d', getPathString(gd, shapeOptions)); - } -} + _$drawing_326.setTranslate(this, + (borderwidth + offsetX), + (5 + borderwidth + legendItem.height / 2) + rowHeight); -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_407.getFromId(gd, options.xref), - ya = _$axes_407.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; + opts._width += traceGap + traceWidth; + opts._height = Math.max(opts._height, legendItem.height); - if(xa) { - x2r = _$helpers_324.shapePositionToRange(xa); - x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; - } - else { - x2p = function(v) { return gs.l + gs.w * v; }; - } + // keep track of tallest trace in group + offsetX += traceGap + traceWidth; + maxTraceHeight = Math.max(legendItem.height, maxTraceHeight); + }); - if(ya) { - y2r = _$helpers_324.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + opts._width += borderwidth * 2; + opts._height += 10 + borderwidth * 2; - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_324.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_324.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); } - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; -} + // make sure we're only getting full pixels + opts._width = Math.ceil(opts._width); + opts._height = Math.ceil(opts._height); + traces.each(function(d) { + var legendItem = d[0], + bg = _$d3_71.select(this).select('.legendtoggle'); -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_321.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_321.paramIsX[segmentType], - yParams = _$constants_321.paramIsY[segmentType], - nParams = _$constants_321.numParams[segmentType]; + _$drawing_326.setRect(bg, + 0, + -legendItem.height / 2, + (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, + legendItem.height + ); + }); +} - var paramString = segment.substr(1).replace(_$constants_321.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; +function expandMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - if(paramNumber > nParams) param = 'X'; - return param; - }); + var xanchor = 'left'; + if(_$anchor_utils_353.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_353.isCenterAnchor(opts)) { + xanchor = 'center'; + } - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_363.log('Ignoring extra params in segment ' + segment); - } + var yanchor = 'top'; + if(_$anchor_utils_353.isBottomAnchor(opts)) { + yanchor = 'bottom'; + } + else if(_$anchor_utils_353.isMiddleAnchor(opts)) { + yanchor = 'middle'; + } - return segmentType + paramString; + // lastly check if the margin auto-expand has changed + _$plots_506.autoMargin(gd, 'legend', { + x: opts.x, + y: opts.y, + l: opts._width * (__FROM_TL_357[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: opts._height * (FROM_BR[yanchor]), + t: opts._height * (__FROM_TL_357[yanchor]) }); } -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_321.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_321.paramIsX[segmentType], - yParams = _$constants_321.paramIsY[segmentType], - nParams = _$constants_321.numParams[segmentType]; - - var paramString = segment.substr(1).replace(_$constants_321.paramRE, function(param) { - if(paramNumber >= nParams) return param; - - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); - - paramNumber++; +function expandHorizontalMargin(gd) { + var fullLayout = gd._fullLayout, + opts = fullLayout.legend; - return param; - }); + var xanchor = 'left'; + if(_$anchor_utils_353.isRightAnchor(opts)) { + xanchor = 'right'; + } + else if(_$anchor_utils_353.isCenterAnchor(opts)) { + xanchor = 'center'; + } - return segmentType + paramString; + // lastly check if the margin auto-expand has changed + _$plots_506.autoMargin(gd, 'legend', { + x: opts.x, + y: 0.5, + l: opts._width * (__FROM_TL_357[xanchor]), + r: opts._width * (FROM_BR[xanchor]), + b: 0, + t: 0 }); } @@ -71338,19 +73065,16 @@ function movePath(pathIn, moveX, moveY) { 'use strict'; -/* removed: var _$draw_323 = require('./draw'); */; -var _$shapes_325 = { +var _$legend_361 = { moduleType: 'component', - name: 'shapes', + name: 'legend', - layoutAttributes: _$attributes_319, - supplyLayoutDefaults: _$supplyLayoutDefaults_322, - includeBasePlot: _$makeIncludeComponents_417('shapes'), + layoutAttributes: _$attributes_354, + supplyLayoutDefaults: _$legendDefaults_356, - calcAutorange: _$calcAutorange_320, - draw: _$draw_323.draw, - drawOne: _$draw_323.drawOne + draw: _$draw_357, + style: _$style_362 }; /** @@ -71361,134 +73085,41 @@ var _$shapes_325 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var _$constants_328 = { - - // layout attribute name - name: 'sliders', - - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', - - railHeight: 5, - - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', - - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', - - // min item width / height - minWidth: 30, - minHeight: 30, - - // padding around item text - textPadX: 40, - - // arrow offset off right edge - arrowOffsetX: 4, - - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', - - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, - - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, - - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', - - labelPadding: 8, - labelOffset: 0, - - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, - - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, - - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_443 = { - t: { - valType: 'number', - dflt: 0, +var _$button_attributes_368 = { + step: { + valType: 'enumerated', - editType: 'arraydraw', + values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'], + dflt: 'month', + editType: 'plot', }, - r: { - valType: 'number', - dflt: 0, + stepmode: { + valType: 'enumerated', - editType: 'arraydraw', + values: ['backward', 'todate'], + dflt: 'backward', + editType: 'plot', }, - b: { + count: { valType: 'number', - dflt: 0, - editType: 'arraydraw', + min: 0, + dflt: 1, + editType: 'plot', }, - l: { - valType: 'number', - dflt: 0, + label: { + valType: 'string', - editType: 'arraydraw', + editType: 'plot', }, - editType: 'arraydraw' + editType: 'plot' }; /** @@ -71501,234 +73132,95 @@ var _$pad_attributes_443 = { 'use strict'; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_443 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_327 = _$extend_354.extendDeepAll; -var __overrideAll_327 = _$edit_types_392.overrideAll; -/* removed: var _$animation_attributes_402 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_328 = require('./constants'); */; - -var stepsAttrs = { - _isLinkedToArray: 'step', +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_300 = require('../color/attributes'); */; +var __extendFlat_367 = _$extend_416.extendFlat; +/* removed: var _$button_attributes_368 = require('./button_attributes'); */; - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], - - }, - label: { - valType: 'string', - - - }, - value: { - valType: 'string', - - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; +_$button_attributes_368 = __extendFlat_367(_$button_attributes_368, { + _isLinkedToArray: 'button', -var _$attributes_327 = __overrideAll_327({ - _isLinkedToArray: 'slider', + +}); +var _$attributes_367 = { visible: { valType: 'boolean', - dflt: true, - - }, - - active: { - valType: 'number', - - min: 0, - dflt: 0, + editType: 'plot', }, - steps: stepsAttrs, + buttons: _$button_attributes_368, - lenmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], - - dflt: 'fraction', - - }, - len: { - valType: 'number', - min: 0, - dflt: 1, - - - }, x: { valType: 'number', min: -2, max: 3, - dflt: 0, + editType: 'plot', }, - pad: __extendDeepAll_327({}, _$pad_attributes_443, { - - }, {t: {dflt: 20}}), xanchor: { valType: 'enumerated', values: ['auto', 'left', 'center', 'right'], dflt: 'left', + editType: 'plot', }, y: { valType: 'number', min: -2, max: 3, - dflt: 0, + editType: 'plot', }, yanchor: { valType: 'enumerated', values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', + dflt: 'bottom', + editType: 'plot', }, - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_402.transition.easing.values, - - dflt: 'cubic-in-out', - - } - }, - - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, - - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, - - offset: { - valType: 'number', - dflt: 10, - - - }, - - prefix: { - valType: 'string', - - - }, - - suffix: { - valType: 'string', - - - }, - - font: _$font_attributes_434({ - - }) - }, - - font: _$font_attributes_434({ + font: _$font_attributes_496({ + editType: 'plot', }), - activebgcolor: { + bgcolor: { valType: 'color', + dflt: _$attributes_300.lightLine, - dflt: _$constants_328.gripBgActiveColor, + editType: 'plot', }, - bgcolor: { + activecolor: { valType: 'color', - dflt: _$constants_328.railBgColor, + editType: 'plot', }, bordercolor: { valType: 'color', - dflt: _$constants_328.railBorderColor, + dflt: _$attributes_300.defaultLine, + editType: 'plot', }, borderwidth: { valType: 'number', min: 0, - dflt: _$constants_328.railBorderWidth, - - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_328.tickLength, - - - }, - tickcolor: { - valType: 'color', - dflt: _$constants_328.tickColor, - - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, + dflt: 0, + editType: 'plot', }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_328.minorTickLength, - - - } -}, 'arraydraw', 'from-root'); + editType: 'plot' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -71740,109 +73232,23 @@ var _$attributes_327 = __overrideAll_327({ 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_403 = require('../../plots/array_container_defaults'); */; - -/* removed: var _$attributes_327 = require('./attributes'); */; -/* removed: var _$constants_328 = require('./constants'); */; - -var __name_329 = _$constants_328.name; -var stepAttrs = _$attributes_327.steps; - - -var _$slidersDefaults_329 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_329, - handleItemDefaults: sliderDefaults - }; - - _$handleArrayContainerDefaults_403(layoutIn, layoutOut, opts); -}; - -function sliderDefaults(sliderIn, sliderOut, layoutOut) { - - function coerce(attr, dflt) { - return _$lib_363.coerce(sliderIn, sliderOut, _$attributes_327, attr, dflt); - } - - var steps = stepsDefaults(sliderIn, sliderOut); - - var visible = coerce('visible', steps.length > 0); - if(!visible) return; - - coerce('active'); - - coerce('x'); - coerce('y'); - _$lib_363.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_363.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_363.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 stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; - - var valueIn, valueOut; - - function coerce(attr, dflt) { - return _$lib_363.coerce(valueIn, valueOut, stepAttrs, attr, dflt); - } - - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; - - coerce('method'); - if(!_$lib_363.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; - } +var _$constants_369 = { - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); + // 'y' position pad above counter axis domain + yPad: 0.02, - valuesOut.push(valueOut); - } + // minimum button width (regardless of text size) + minButtonWidth: 30, - return valuesOut; -} + // buttons rect radii + rx: 3, + ry: 3, + + // light fraction used to compute the 'activecolor' default + lightAmount: 25, + darkAmount: 10 +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -71852,627 +73258,406 @@ function stepsDefaults(sliderIn, sliderOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_291 = require('../legend/anchor_utils'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$color_301 = require('../color'); */; -/* removed: var _$constants_328 = require('./constants'); */; -/* removed: var _$alignment_339 = require('../../constants/alignment'); */; -var __LINE_SPACING_330 = _$alignment_339.LINE_SPACING; -var __FROM_TL_330 = _$alignment_339.FROM_TL; -var __FROM_BR_330 = _$alignment_339.FROM_BR; +/* removed: var _$attributes_367 = require('./attributes'); */; +/* removed: var _$button_attributes_368 = require('./button_attributes'); */; +/* removed: var _$constants_369 = require('./constants'); */; -var _$draw_330 = function draw(gd) { - var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); - - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_328.containerClassName) - .data(sliderData.length > 0 ? [0] : []); +var _$handleDefaults_370 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { + var selectorIn = containerIn.rangeselector || {}, + selectorOut = containerOut.rangeselector = {}; - sliders.enter().append('g') - .classed(_$constants_328.containerClassName, true) - .style('cursor', 'ew-resize'); + function coerce(attr, dflt) { + return _$lib_425.coerce(selectorIn, selectorOut, _$attributes_367, attr, dflt); + } - sliders.exit().remove(); + var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_330(gd); + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; - // Return early if no menus visible: - if(sliderData.length === 0) return; + var posDflt = getPosDflt(containerOut, layout, counterAxes); + coerce('x', posDflt[0]); + coerce('y', posDflt[1]); + _$lib_425.noneOrAll(containerIn, containerOut, ['x', 'y']); - var sliderGroups = sliders.selectAll('g.' + _$constants_328.groupClassName) - .data(sliderData, keyFunction); + coerce('xanchor'); + coerce('yanchor'); - sliderGroups.enter().append('g') - .classed(_$constants_328.groupClassName, true); + _$lib_425.coerceFont(coerce, 'font', layout.font); - sliderGroups.exit().each(function(sliderOpts) { - _$d3_68.select(this).remove(); + var bgColor = coerce('bgcolor'); + coerce('activecolor', _$color_301.contrast(bgColor, _$constants_369.lightAmount, _$constants_369.darkAmount)); + coerce('bordercolor'); + coerce('borderwidth'); +}; - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; +function buttonsDefaults(containerIn, containerOut, calendar) { + var buttonsIn = containerIn.buttons || [], + buttonsOut = containerOut.buttons = []; - _$plots_444.autoMargin(gd, _$constants_328.autoMarginIdRoot + sliderOpts._index); - }); + var buttonIn, buttonOut; - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); + function coerce(attr, dflt) { + return _$lib_425.coerce(buttonIn, buttonOut, _$button_attributes_368, attr, dflt); } - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; - - var gSlider = _$d3_68.select(this); - - computeLabelSteps(sliderOpts); - - _$plots_444.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; - if(opts.active === data.index) return; - if(opts._dragging) return; + if(!_$lib_425.isPlainObject(buttonIn)) continue; - setActive(gd, gSlider, opts, data.index, false, true); - }); + var step = coerce('step'); + if(step !== 'all') { + if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) { + buttonOut.stepmode = 'backward'; + } + else { + coerce('stepmode'); + } - drawSlider(gd, _$d3_68.select(this), sliderOpts); - }); -}; + coerce('count'); + } -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_328.name], - sliderData = []; + coerce('label'); - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); + buttonOut._index = i; + buttonsOut.push(buttonOut); } - return sliderData; -} - -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; + return buttonsOut; } -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_264.tester.selectAll('g.' + _$constants_328.labelGroupClass) - .data(sliderOpts.steps); - - sliderLabels.enter().append('g') - .classed(_$constants_328.labelGroupClass, true); - - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_68.select(this); - - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); - - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_264.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); - } +function getPosDflt(containerOut, layout, counterAxes) { + var anchoredList = counterAxes.filter(function(ax) { + return layout[ax].anchor === containerOut._id; }); - sliderLabels.remove(); - - var dims = sliderOpts._dims = {}; - - dims.inputAreaWidth = Math.max( - _$constants_328.railWidth, - _$constants_328.gripHeight - ); - - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); - - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; + var posY = 0; + for(var i = 0; i < anchoredList.length; i++) { + var domain = layout[anchoredList[i]].domain; + if(domain) posY = Math.max(domain[1], posY); } - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - - var textableInputLength = dims.inputAreaLength - 2 * _$constants_328.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_328.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; - - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; - - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_264.tester.append('g'); + return [containerOut.domain[0], posY + _$constants_369.yPad]; +} - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_264.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_386.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; - dummyGroup.remove(); - } +'use strict'; - dims.height = dims.currentValueTotalHeight + _$constants_328.tickOffset + sliderOpts.ticklen + _$constants_328.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; +/* removed: var _$d3_71 = require('d3'); */; - var xanchor = 'left'; - if(_$anchor_utils_291.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_291.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } +var _$getUpdateObject_372 = function getUpdateObject(axisLayout, buttonLayout) { + var axName = axisLayout._name; + var update = {}; - var yanchor = 'top'; - if(_$anchor_utils_291.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_291.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; + if(buttonLayout.step === 'all') { + update[axName + '.autorange'] = true; } + else { + var xrange = getXRange(axisLayout, buttonLayout); - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); - - _$plots_444.autoMargin(gd, _$constants_328.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_330[xanchor], - r: dims.outerLength * __FROM_BR_330[xanchor], - b: dims.height * __FROM_BR_330[yanchor], - t: dims.height * __FROM_TL_330[yanchor] - }); -} - -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; + update[axName + '.range[0]'] = xrange[0]; + update[axName + '.range[1]'] = xrange[1]; } - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); - - var dims = sliderOpts._dims; - - // Position the rectangle: - _$drawing_264.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); - - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); + return update; +}; -} +function getXRange(axisLayout, buttonLayout) { + var currentRange = axisLayout.range; + var base = new Date(axisLayout.r2l(currentRange[1])); -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; + var step = buttonLayout.step, + count = buttonLayout.count; - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; + var range0; - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_328.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; + switch(buttonLayout.stepmode) { + case 'backward': + range0 = axisLayout.l2r(+_$d3_71.time[step].utc.offset(base, -count)); break; - default: - x0 = _$constants_328.currentValueInset; - textAnchor = 'left'; - } - - text.enter().append('text') - .classed(_$constants_328.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; - - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } + case 'todate': + var base2 = _$d3_71.time[step].utc.offset(base, -count); - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; + range0 = axisLayout.l2r(+_$d3_71.time[step].utc.ceil(base2)); + break; } - text.call(_$drawing_264.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_386.convertToTspans, sliderOpts._gd); - - var lines = _$svg_text_utils_386.lineCount(text); - - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_330; - - _$svg_text_utils_386.positionText(text, x0, y0); - - return text; -} - -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_328.gripRectClass) - .data([0]); - - grip.enter().append('rect') - .classed(_$constants_328.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + var range1 = currentRange[1]; - grip.attr({ - width: _$constants_328.gripWidth, - height: _$constants_328.gripHeight, - rx: _$constants_328.gripRadius, - ry: _$constants_328.gripRadius, - }) - .call(_$color_239.stroke, sliderOpts.bordercolor) - .call(_$color_239.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + return [range0, range1]; } -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - text.enter().append('text') - .classed(_$constants_328.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); +'use strict'; - text.call(_$drawing_264.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_386.convertToTspans, sliderOpts._gd); +/* removed: var _$d3_71 = require('d3'); */; - return text; -} +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$anchor_utils_353 = require('../legend/anchor_utils'); */; -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_328.labelsClass) - .data([0]); - var dims = sliderOpts._dims; +/* removed: var _$alignment_401 = require('../../constants/alignment'); */; +var __LINE_SPACING_371 = _$alignment_401.LINE_SPACING; +var __FROM_TL_371 = _$alignment_401.FROM_TL; +var __FROM_BR_371 = _$alignment_401.FROM_BR; - labels.enter().append('g') - .classed(_$constants_328.labelsClass, true); +/* removed: var _$constants_369 = require('./constants'); */; +/* removed: var _$getUpdateObject_372 = require('./get_update_object'); */; - var labelItems = labels.selectAll('g.' + _$constants_328.labelGroupClass) - .data(dims.labelSteps); - labelItems.enter().append('g') - .classed(_$constants_328.labelGroupClass, true); +var _$draw_371 = function draw(gd) { + var fullLayout = gd._fullLayout; - labelItems.exit().remove(); + var selectors = fullLayout._infolayer.selectAll('.rangeselector') + .data(makeSelectorData(gd), selectorKeyFunc); - labelItems.each(function(d) { - var item = _$d3_68.select(this); + selectors.enter().append('g') + .classed('rangeselector', true); - item.call(drawLabel, d, sliderOpts); + selectors.exit().remove(); - _$drawing_264.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_328.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_330 + - _$constants_328.labelOffset + - dims.currentValueTotalHeight - ); + selectors.style({ + cursor: 'pointer', + 'pointer-events': 'all' }); -} - -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + selectors.each(function(d) { + var selector = _$d3_71.select(this), + axisLayout = d, + selectorLayout = axisLayout.rangeselector; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); - } -} + var buttons = selector.selectAll('g.button') + .data(selectorLayout.buttons); -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; + buttons.enter().append('g') + .classed('button', true); - var step = sliderOpts.steps[sliderOpts.active]; + buttons.exit().remove(); - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + buttons.each(function(d) { + var button = _$d3_71.select(this); + var update = _$getUpdateObject_372(axisLayout, d); - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive - }); + d._isActive = isActive(axisLayout, d, update); - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; + button.call(drawButtonRect, selectorLayout, d); + button.call(drawButtonText, selectorLayout, d, gd); - if(_step.execute) { - _$plots_444.executeAPICommand(gd, _step.method, _step.args); - } + button.on('click', function() { + if(gd._dragged) return; - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; + _$registry_514.call('relayout', gd, update); }); - } - } -} - -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_68.select(gd); - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; - } + button.on('mouseover', function() { + d._isHovered = true; + button.call(drawButtonRect, selectorLayout, d); + }); - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); + button.on('mouseout', function() { + d._isHovered = false; + button.call(drawButtonRect, selectorLayout, d); + }); + }); - var grip = sliderGroup.select('.' + _$constants_328.gripRectClass); + reposition(gd, buttons, selectorLayout, axisLayout._name, selector); + }); - _$d3_68.event.stopPropagation(); - _$d3_68.event.preventDefault(); - grip.call(_$color_239.fill, sliderOpts.activebgcolor); +}; - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_68.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; +function makeSelectorData(gd) { + var axes = _$axis_ids_473.list(gd, 'x', true); + var data = []; - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_68.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + for(var i = 0; i < axes.length; i++) { + var axis = axes[i]; - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_239.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + if(axis.rangeselector && axis.rangeselector.visible) { + data.push(axis); + } + } - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); + return data; } -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_328.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; +function selectorKeyFunc(d) { + return d._id; +} - tick.enter().append('rect') - .classed(_$constants_328.tickRectClass, true); +function isActive(axisLayout, opts, update) { + if(opts.step === 'all') { + return axisLayout.autorange === true; + } + else { + var keys = Object.keys(update); - tick.exit().remove(); + return ( + axisLayout.range[0] === update[keys[0]] && + axisLayout.range[1] === update[keys[1]] + ); + } +} - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' +function drawButtonRect(button, selectorLayout, d) { + var rect = _$lib_425.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); }); - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_68.select(this); - - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_239.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - - _$drawing_264.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_328.tickOffset : _$constants_328.minorTickOffset) + dims.currentValueTotalHeight - ); + rect.attr({ + 'rx': _$constants_369.rx, + 'ry': _$constants_369.ry }); + rect.call(_$color_301.stroke, selectorLayout.bordercolor) + .call(_$color_301.fill, getFillColor(selectorLayout, d)) + .style('stroke-width', selectorLayout.borderwidth + 'px'); } -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; +function getFillColor(selectorLayout, d) { + return (d._isActive || d._isHovered) ? + selectorLayout.activecolor : + selectorLayout.bgcolor; +} - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); +function drawButtonText(button, selectorLayout, d, gd) { + function textLayout(s) { + _$svg_text_utils_449.convertToTspans(s, gd); } -} -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_328.gripRectClass); + var text = _$lib_425.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); - var x = normalizedValueToPosition(sliderOpts, position); + text.call(_$drawing_326.font, selectorLayout.font) + .text(getLabel(d)) + .call(textLayout); +} - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; +function getLabel(opts) { + if(opts.label) return opts.label; - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); - } + if(opts.step === 'all') return 'all'; - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_328.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); + return opts.count + opts.step.charAt(0); } -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_328.stepInset + - (dims.inputAreaLength - 2 * _$constants_328.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} +function reposition(gd, buttons, opts, axName, selector) { + var width = 0; + var height = 0; -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_328.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_328.stepInset - 2 * dims.inputAreaStart))); -} + var borderWidth = opts.borderwidth; -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_328.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; + buttons.each(function() { + var button = _$d3_71.select(this); + var text = button.select('.selector-text'); - rect.enter().append('rect') - .classed(_$constants_328.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + var tHeight = opts.font.size * __LINE_SPACING_371; + var hEff = Math.max(tHeight * _$svg_text_utils_449.lineCount(text), 16) + 3; - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_328.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_239.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + height = Math.max(height, hEff); + }); - _$drawing_264.setTranslate(rect, 0, dims.currentValueTotalHeight); -} + buttons.each(function() { + var button = _$d3_71.select(this); + var rect = button.select('.selector-rect'); + var text = button.select('.selector-text'); -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_328.railRectClass) - .data([0]); - var dims = sliderOpts._dims; + var tWidth = text.node() && _$drawing_326.bBox(text.node()).width; + var tHeight = opts.font.size * __LINE_SPACING_371; + var tLines = _$svg_text_utils_449.lineCount(text); - rect.enter().append('rect') - .classed(_$constants_328.railRectClass, true); + var wEff = Math.max(tWidth + 10, _$constants_369.minButtonWidth); - var computedLength = dims.inputAreaLength - _$constants_328.railInset * 2; + // TODO add MathJax support - rect.attr({ - width: computedLength, - height: _$constants_328.railWidth, - rx: _$constants_328.railRadius, - ry: _$constants_328.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_239.stroke, sliderOpts.bordercolor) - .call(_$color_239.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + // TODO add buttongap attribute - _$drawing_264.setTranslate(rect, - _$constants_328.railInset, - (dims.inputAreaWidth - _$constants_328.railWidth) * 0.5 + dims.currentValueTotalHeight - ); -} + button.attr('transform', 'translate(' + + (borderWidth + width) + ',' + borderWidth + + ')'); -function __clearPushMargins_330(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + rect.attr({ + x: 0, + y: 0, + width: wEff, + height: height + }); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + _$svg_text_utils_449.positionText(text, wEff / 2, + height / 2 - ((tLines - 1) * tHeight / 2) + 3); - if(k.indexOf(_$constants_328.autoMarginIdRoot) !== -1) { - _$plots_444.autoMargin(gd, k); - } + width += wEff + 5; + }); + + var graphSize = gd._fullLayout._size; + var lx = graphSize.l + graphSize.w * opts.x; + var ly = graphSize.t + graphSize.h * (1 - opts.y); + + var xanchor = 'left'; + if(_$anchor_utils_353.isRightAnchor(opts)) { + lx -= width; + xanchor = 'right'; + } + if(_$anchor_utils_353.isCenterAnchor(opts)) { + lx -= width / 2; + xanchor = 'center'; + } + + var yanchor = 'top'; + if(_$anchor_utils_353.isBottomAnchor(opts)) { + ly -= height; + yanchor = 'bottom'; + } + if(_$anchor_utils_353.isMiddleAnchor(opts)) { + ly -= height / 2; + yanchor = 'middle'; } + + width = Math.ceil(width); + height = Math.ceil(height); + lx = Math.round(lx); + ly = Math.round(ly); + + _$plots_506.autoMargin(gd, axName + '-range-selector', { + x: opts.x, + y: opts.y, + l: width * __FROM_TL_371[xanchor], + r: width * __FROM_BR_371[xanchor], + b: height * __FROM_BR_371[yanchor], + t: height * __FROM_TL_371[yanchor] + }); + + selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); } /** @@ -72485,16 +73670,20 @@ function __clearPushMargins_330(gd) { 'use strict'; -/* removed: var _$constants_328 = require('./constants'); */; - -var _$sliders_331 = { +var _$rangeselector_373 = { moduleType: 'component', - name: _$constants_328.name, + name: 'rangeselector', + + schema: { + subplots: { + xaxis: {rangeselector: _$attributes_367} + } + }, - layoutAttributes: _$attributes_327, - supplyLayoutDefaults: _$slidersDefaults_329, + layoutAttributes: _$attributes_367, + handleDefaults: _$handleDefaults_370, - draw: _$draw_330 + draw: _$draw_371 }; /** @@ -72507,149 +73696,196 @@ var _$sliders_331 = { 'use strict'; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_238 = require('../color/attributes'); */; -var __extendFlat_333 = _$extend_354.extendFlat; -var __overrideAll_333 = _$edit_types_392.overrideAll; -/* removed: var _$pad_attributes_443 = require('../../plots/pad_attributes'); */; +/* removed: var _$attributes_300 = require('../color/attributes'); */; -var buttonsAttrs = { - _isLinkedToArray: 'button', - - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', +var _$attributes_374 = { + bgcolor: { + valType: 'color', + dflt: _$attributes_300.background, + editType: 'plot', }, - args: { - valType: 'info_array', + bordercolor: { + valType: 'color', + dflt: _$attributes_300.defaultLine, - freeLength: true, - items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} - ], + editType: 'plot', }, - label: { - valType: 'string', + borderwidth: { + valType: 'integer', + dflt: 0, + min: 0, - dflt: '', + editType: 'plot', }, - execute: { + autorange: { valType: 'boolean', - dflt: true, - } -}; - -var _$attributes_333 = __overrideAll_333({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - - visible: { - valType: 'boolean', - - - }, - - type: { - valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', - + editType: 'calc', + impliedEdits: {'range[0]': undefined, 'range[1]': undefined}, }, - - direction: { - valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', + range: { + valType: 'info_array', + items: [ + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}} + ], + editType: 'calc', + impliedEdits: {'autorange': false}, }, - - active: { - valType: 'integer', + thickness: { + valType: 'number', + dflt: 0.15, + min: 0, + max: 1, - min: -1, - dflt: 0, + editType: 'plot', }, - - showactive: { + visible: { valType: 'boolean', - dflt: true, + editType: 'calc', + }, + editType: 'calc' +}; - buttons: buttonsAttrs, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - x: { - valType: 'number', - min: -2, - max: 3, - dflt: -0.05, - - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'right', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, - - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, +'use strict'; - pad: __extendFlat_333({}, _$pad_attributes_443, { - - }), +var _$constants_376 = { - font: _$font_attributes_434({ - - }), + // attribute container name + name: 'rangeslider', - bgcolor: { - valType: 'color', + // class names + + containerClassName: 'rangeslider-container', + bgClassName: 'rangeslider-bg', + rangePlotClassName: 'rangeslider-rangeplot', + + maskMinClassName: 'rangeslider-mask-min', + maskMaxClassName: 'rangeslider-mask-max', + slideBoxClassName: 'rangeslider-slidebox', + + grabberMinClassName: 'rangeslider-grabber-min', + grabAreaMinClassName: 'rangeslider-grabarea-min', + handleMinClassName: 'rangeslider-handle-min', + + grabberMaxClassName: 'rangeslider-grabber-max', + grabAreaMaxClassName: 'rangeslider-grabarea-max', + handleMaxClassName: 'rangeslider-handle-max', + + maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis', + maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis', + + // style constants + + maskColor: 'rgba(0,0,0,0.4)', + maskOppAxisColor: 'rgba(0,0,0,0.2)', + + slideBoxFill: 'transparent', + slideBoxCursor: 'ew-resize', + + grabAreaFill: 'transparent', + grabAreaCursor: 'col-resize', + grabAreaWidth: 10, + + handleWidth: 4, + handleRadius: 1, + handleStrokeWidth: 1, + + extraPad: 15 +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var listAxes = _$axis_ids_473.list; +var __getAutoRange_375 = _$autorange_469.getAutoRange; +/* removed: var _$constants_376 = require('./constants'); */; + +var _$calcAutorange_375 = 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], + opts = ax[_$constants_376.name]; + + // Don't try calling getAutoRange if _min and _max are filled in. + // This happens on updates where the calc step is skipped. + + if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { + opts._input.autorange = true; + opts._input.range = opts.range = __getAutoRange_375(ax); + } + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$oppaxis_attributes_380 = { + // 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', }, - bordercolor: { - valType: 'color', - dflt: _$attributes_238.borderLine, + range: { + valType: 'info_array', + items: [ + {valType: 'any', editType: 'plot'}, + {valType: 'any', editType: 'plot'} + ], + editType: 'plot', }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'arraydraw', - - } -}, 'arraydraw', 'from-root'); + editType: 'calc' +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -72659,76 +73895,79 @@ var _$attributes_333 = __overrideAll_333({ * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$attributes_374 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_380 = require('./oppaxis_attributes'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; -var _$constants_334 = { - - // 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', +var _$handleDefaults_377 = function handleDefaults(layoutIn, layoutOut, axName) { + var axIn = layoutIn[axName]; + var axOut = layoutOut[axName]; - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'updatemenu-', + if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; - // options when 'active: -1' - blankHeaderOpts: { label: ' ' }, + // not super proud of this (maybe store _ in axis object instead + if(!_$lib_425.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; + } - // min item width / height - minWidth: 30, - minHeight: 30, + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; - // padding around item text - textPadX: 24, - arrowPadX: 16, + function coerce(attr, dflt) { + return _$lib_425.coerce(containerIn, containerOut, _$attributes_374, attr, dflt); + } - // item rect radii - rx: 2, - ry: 2, + function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { + return _$lib_425.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_380, attr, dflt); + } - // item text x offset off left edge - textOffsetX: 12, + var visible = coerce('visible'); + if(!visible) return; - // item text y offset (w.r.t. middle) - textOffsetY: 3, + coerce('bgcolor', layoutOut.plot_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('thickness'); - // arrow offset off right edge - arrowOffsetX: 4, + axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range)); + coerce('range'); - // gap between header and buttons - gapButtonHeader: 5, + var subplots = layoutOut._subplots; + if(subplots) { + var yIds = subplots.cartesian + .filter(function(subplotId) { + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_473.name2id(axName); + }) + .map(function(subplotId) { + return subplotId.substr(subplotId.indexOf('y'), subplotId.length); + }); + var yNames = _$lib_425.simpleMap(yIds, _$axis_ids_473.id2name); + for(var i = 0; i < yNames.length; i++) { + var yName = yNames[i]; - // gap between between buttons - gapButton: 2, + var rangeContainerIn = containerIn[yName] || {}; + var rangeContainerOut = containerOut[yName] = {}; - // color given to active buttons - activeColor: '#F4FAFF', + var yAxOut = layoutOut[yName]; - // color given to hovered buttons - hoverColor: '#F4FAFF', + var rangemodeDflt; + if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { + rangemodeDflt = 'fixed'; + } - // symbol for menu open arrow - arrowSymbol: { - left: '◄', - right: '►', - up: '▲', - down: '▼' + var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt); + if(rangeMode !== 'match') { + coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice()); + } + yAxOut._rangesliderAutorange = (rangeMode === 'auto'); + } } + + // to map back range slider (auto) range + containerOut._input = containerIn; }; /** @@ -72741,560 +73980,613 @@ var _$constants_334 = { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_403 = require('../../plots/array_container_defaults'); */; +/* removed: var _$d3_71 = require('d3'); */; -/* removed: var _$attributes_333 = require('./attributes'); */; -/* removed: var _$constants_334 = require('./constants'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; -var __name_335 = _$constants_334.name; -var __buttonAttrs_335 = _$attributes_333.buttons; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$titles_394 = require('../titles'); */; +/* removed: var _$cartesian_481 = require('../../plots/cartesian'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; -var _$updateMenusDefaults_335 = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_335, - handleItemDefaults: menuDefaults - }; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$setCursor_445 = require('../../lib/setcursor'); */; + +/* removed: var _$constants_376 = require('./constants'); */; + +var _$draw_378 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); + + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ + + function keyFunction(axisOpts) { + return axisOpts._name; + } + + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_376.containerClassName) + .data(rangeSliderData, keyFunction); + + rangeSliders.enter().append('g') + .classed(_$constants_376.containerClassName, true) + .attr('pointer-events', 'all'); + + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_71.select(this), + opts = axisOpts[_$constants_376.name]; + + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); + }); + + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); + + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; + + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_71.select(this), + opts = axisOpts[_$constants_376.name], + oppAxisOpts = fullLayout[_$axes_470.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_470.id2name(axisOpts.anchor)]; + + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; + + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); + } + + axisOpts.cleanRange('rangeslider.range'); + + + // update range slider dimensions + + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; + + var oppBottom = Infinity; + var subplotData = _$axes_470.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_470.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); + } + + opts._id = _$constants_376.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; + + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); + + var x = Math.round(margin.l + (graphSize.w * domain[0])); - _$handleArrayContainerDefaults_403(layoutIn, layoutOut, opts); -}; + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_376.extraPad + ); -function menuDefaults(menuIn, menuOut, layoutOut) { + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); - function coerce(attr, dflt) { - return _$lib_363.coerce(menuIn, menuOut, _$attributes_333, attr, dflt); - } + // update data <--> pixel coordinate conversion methods - var buttons = __buttonsDefaults_335(menuIn, menuOut); + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; - coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - coerce('x'); - coerce('y'); - _$lib_363.noneOrAll(menuIn, menuOut, ['x', 'y']); + opts._rl = [range0, range1]; - coerce('xanchor'); - coerce('yanchor'); + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; + } - _$lib_363.coerceFont(coerce, 'font', layoutOut.font); + // update inner nodes - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); -} + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); -function __buttonsDefaults_335(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); - var buttonIn, buttonOut; + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - function coerce(attr, dflt) { - return _$lib_363.coerce(buttonIn, buttonOut, __buttonAttrs_335, attr, dflt); - } + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_394.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); + } - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + // update margins + _$plots_506.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_376.extraPad + opts._offsetShift * 2 + }); + }); +}; - coerce('method'); +function makeRangeSliderData(fullLayout) { + var axes = _$axes_470.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_376.name, + out = []; - if(!_$lib_363.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { - continue; - } + if(fullLayout._has('gl2d')) return out; - coerce('args'); - coerce('label'); - coerce('execute'); + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - buttonOut._index = i; - buttonsOut.push(buttonOut); + if(ax[name] && ax[name].visible) out.push(ax); } - return buttonsOut; + return out; } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_376.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_376.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_376.grabAreaMaxClassName).node(); -'use strict'; + rangeSlider.on('mousedown', function() { + var event = _$d3_71.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); + + var dragCover = _$dragelement_323.coverSlip(); + + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); -var _$ScrollBox_338 = ScrollBox; + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; -/* removed: var _$d3_68 = require('d3'); */; + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; -/* removed: var _$lib_363 = require('../../lib'); */; + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); + _$setCursor_445(_$d3_71.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); + } - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_425.removeElement(dragCover); + } + }); } -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; +function setDataRange(rangeSlider, gd, axisOpts, opts) { -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; + function clamp(v) { + return axisOpts.l2r(_$lib_425.constrain(v, opts._rl[0], opts._rl[1])); + } - // compute position of scrollbox - this.position = position; + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; + window.requestAnimationFrame(function() { + _$registry_514.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); +} - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; - } +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_376.handleWidth / 2; - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; + function clamp(v) { + return _$lib_425.constrain(v, 0, opts._width); + } - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } + function clampOppAxis(v) { + return _$lib_425.constrain(v, 0, opts._height); } - else { - boxT = t; - boxB = boxT + boxH; - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; - } + function clampHandle(v) { + return _$lib_425.constrain(v, -hw2, opts._width + hw2); } - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; + rangeSlider.select('rect.' + _$constants_376.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + rangeSlider.select('rect.' + _$constants_376.maskMinClassName) + .attr('width', pixelMin); - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); + rangeSlider.select('rect.' + _$constants_376.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - hbar.exit() - .on('.drag', null) - .remove(); + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_239.fill, ScrollBox.barColor); + rangeSlider.select('rect.' + _$constants_376.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH - }); + rangeSlider.select('rect.' + _$constants_376.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; + rangeSlider.select('rect.' + _$constants_376.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); } - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; - - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - vbar.exit() - .on('.drag', null) - .remove(); + rangeSlider.select('g.' + _$constants_376.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_239.fill, ScrollBox.barColor); + rangeSlider.select('g.' + _$constants_376.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); +} - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_425.ensureSingle(rangeSlider, 'rect', _$constants_376.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' }); + }); - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + var offsetShift = -opts._offsetShift; + var lw = _$drawing_326.crispRound(gd, opts.borderwidth); - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw + }); +} - clipPath.exit().remove(); +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + var clipPath = _$lib_425.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); +} - this.container.call(_$drawing_264.setClipUrl, clipId); +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_470.getSubplots(gd, axisOpts), + calcData = gd.calcdata; - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } - else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_264.setClipUrl, null); - delete this._clipRect; - } + var rangePlots = rangeSlider.selectAll('g.' + _$constants_376.rangePlotClassName) + .data(subplotData, _$lib_425.identity); - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_68.behavior.drag() - .on('dragstart', function() { - _$d3_68.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_376.rangePlotClassName + ' ' + id; }) + .call(_$drawing_326.setClipUrl, opts._clipId); - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + rangePlots.order(); - var onBarDrag = _$d3_68.behavior.drag() - .on('dragstart', function() { - _$d3_68.event.sourceEvent.preventDefault(); - _$d3_68.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + rangePlots.exit().remove(); - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); - } + var mainplotinfo; - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); - } - } + rangePlots.each(function(id, i) { + var plotgroup = _$d3_71.select(this), + isMainPlot = (i === 0); - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + var oppAxisOpts = _$axes_470.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_264.setClipUrl, null); - delete this._clipRect; - } + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } -}; + _$plots_506.supplyDefaults(mockFigure); -/** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; - if(this.hbar) { - translateX -= _$d3_68.event.dx; - } + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; - if(this.vbar) { - translateY -= _$d3_68.event.dy; - } + if(isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; + } - this.setTranslate(translateX, translateY); -}; + _$cartesian_481.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + }); +} -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; - if(this.hbar) { - translateX += _$d3_68.event.deltaY; - } + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; - if(this.vbar) { - translateY += _$d3_68.event.deltaY; + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } } - this.setTranslate(translateX, translateY); -}; + return out; +} -/** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_425.ensureSingle(rangeSlider, 'rect', _$constants_376.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_363.constrain(_$d3_68.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); + maskMin + .attr('height', opts._height) + .call(_$color_301.fill, _$constants_376.maskColor); - var translateXMax = this.position.w - this._box.w; + var maskMax = _$lib_425.ensureSingle(rangeSlider, 'rect', _$constants_376.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - translateX = xf * translateXMax; - } + maskMax + .attr('height', opts._height) + .call(_$color_301.fill, _$constants_376.maskColor); - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_363.constrain(_$d3_68.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_425.ensureSingle(rangeSlider, 'rect', _$constants_376.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - var translateYMax = this.position.h - this._box.h; + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_301.fill, _$constants_376.maskOppAxisColor); - translateY = yf * translateYMax; + var maskMaxOppAxis = _$lib_425.ensureSingle(rangeSlider, 'rect', _$constants_376.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); + + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_376.maskOppBorder) + .call(_$color_301.fill, _$constants_376.maskOppAxisColor); } +} - this.setTranslate(translateX, translateY); -}; +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; -/** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; + var slideBox = _$lib_425.ensureSingle(rangeSlider, 'rect', _$constants_376.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_376.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); - translateX = _$lib_363.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_363.constrain(translateY || 0, 0, translateYMax); + slideBox.attr({ + height: opts._height, + fill: _$constants_376.slideBoxFill + }); +} - this.translateX = translateX; - this.translateY = translateY; +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_425.ensureSingle(rangeSlider, 'g', _$constants_376.grabberMinClassName); + var grabberMax = _$lib_425.ensureSingle(rangeSlider, 'g', _$constants_376.grabberMaxClassName); - this.container.call(_$drawing_264.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); + // + var handleFixAttrs = { + x: 0, + width: _$constants_376.handleWidth, + rx: _$constants_376.handleRadius, + fill: _$color_301.background, + stroke: _$color_301.defaultLine, + 'stroke-width': _$constants_376.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_425.ensureSingle(grabberMin, 'rect', _$constants_376.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMin.attr(handleDynamicAttrs); - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) - }); - } + var handleMax = _$lib_425.ensureSingle(grabberMax, 'rect', _$constants_376.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); - if(this.hbar) { - var xf = translateX / translateXMax; + // + if(gd._context.staticPlot) return; - this.hbar.call(_$drawing_264.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); - } + var grabAreaFixAttrs = { + width: _$constants_376.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_376.grabAreaFill, + cursor: _$constants_376.grabAreaCursor + }; - if(this.vbar) { - var yf = translateY / translateYMax; + var grabAreaMin = _$lib_425.ensureSingle(grabberMin, 'rect', _$constants_376.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMin.attr('height', opts._height); - this.vbar.call(_$drawing_264.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); + var grabAreaMax = _$lib_425.ensureSingle(grabberMax, 'rect', _$constants_376.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMax.attr('height', opts._height); +} + +function clearPushMargins(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); + + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; + + if(k.indexOf(_$constants_376.name) !== -1) { + _$plots_506.autoMargin(gd, k); + } } -}; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -73304,1636 +74596,1565 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$color_239 = require('../color'); */; -/* removed: var _$drawing_264 = require('../drawing'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_291 = require('../legend/anchor_utils'); */; - -var __LINE_SPACING_336 = _$alignment_339.LINE_SPACING; - -/* removed: var _$constants_334 = require('./constants'); */; -/* removed: var _$ScrollBox_338 = require('./scrollbox'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$attributes_374 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_380 = require('./oppaxis_attributes'); */; -var _$draw_336 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); - - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ +var _$rangeslider_379 = { + moduleType: 'component', + name: 'rangeslider', - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_334.containerClassName) - .data(menuData.length > 0 ? [0] : []); + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_425.extendFlat({}, _$attributes_374, { + yaxis: _$oppaxis_attributes_380 + }) + } + } + }, - menus.enter().append('g') - .classed(_$constants_334.containerClassName, true) - .style('cursor', 'pointer'); + layoutAttributes: _$attributes_374, + handleDefaults: _$handleDefaults_377, + calcAutorange: _$calcAutorange_375, + draw: _$draw_378 +}; - menus.exit().remove(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 push margin object(s) - if(menus.exit().size()) __clearPushMargins_336(gd); +'use strict'; - // return early if no update menus are visible - if(menuData.length === 0) return; +/* removed: var _$attributes_286 = require('../annotations/attributes'); */; +var __scatterLineAttrs_381 = _$attributes_576.line; +var __dash_381 = _$attributes_325.dash; +var __extendFlat_381 = _$extend_416.extendFlat; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_334.headerGroupClassName) - .data(menuData, __keyFunction_336); +var _$attributes_381 = { + _isLinkedToArray: 'shape', - headerGroups.enter().append('g') - .classed(_$constants_334.headerGroupClassName, true); + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calcIfAutorange+arraydraw', + + }, - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_334.dropdownButtonGroupClassName) - .data([0]); + type: { + valType: 'enumerated', + values: ['circle', 'rect', 'path', 'line'], + + editType: 'calcIfAutorange+arraydraw', + + }, - gButton.enter().append('g') - .classed(_$constants_334.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_336(gd, menuOpts); - } + xref: __extendFlat_381({}, _$attributes_286.xref, { + + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_338(gd, gButton, scrollBoxId); + yref: __extendFlat_381({}, _$attributes_286.yref, { + + }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); + path: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, - gButton - .call(removeAllButtons) - .attr(_$constants_334.menuIndexAttrName, '-1'); - } + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + + }, + line: { + color: __extendFlat_381({}, __scatterLineAttrs_381.color, {editType: 'arraydraw'}), + width: __extendFlat_381({}, __scatterLineAttrs_381.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_381({}, __dash_381, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; - headerGroups.exit().each(function(menuOpts) { - _$d3_68.select(this).remove(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - gButton - .call(removeAllButtons) - .attr(_$constants_334.menuIndexAttrName, '-1'); - _$plots_444.autoMargin(gd, _$constants_334.autoMarginIdRoot + menuOpts._index); - }); +'use strict'; - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_68.select(this); - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_444.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_336(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); - }); +var _$constants_383 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - // if this menu is active, update the dropdown container - if(__isActive_336(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); - } + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, - }); + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 + } }; +var _$helpers_386 = {}; /** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_334.name]; - var menuData = []; - - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - - if(item.visible) menuData.push(item); - } - - return menuData; -} - -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_336(menuOpts) { - return menuOpts._index; -} - -function isFolded(gButton) { - return +gButton.attr(_$constants_334.menuIndexAttrName) === -1; -} +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function __isActive_336(gButton, menuOpts) { - return +gButton.attr(_$constants_334.menuIndexAttrName) === menuOpts._index; -} -function __setActive_336(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; +'use strict'; - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_334.menuIndexAttrName, '-1'); +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); +_$helpers_386.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; +}; - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } -} +_$helpers_386.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; +}; -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_334.headerClassName) - .data([0]); - var dims = menuOpts._dims; +_$helpers_386.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); + }; +}; - header.enter().append('g') - .classed(_$constants_334.headerClassName, true) - .style('pointer-events', 'all'); +_$helpers_386.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; +}; - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_334.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; +_$helpers_386.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); + if(axis) { + var d2r = _$helpers_386.shapePositionToRange(axis); - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_334.headerArrowClassName) - .data([0]); + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; - arrow.enter().append('text') - .classed(_$constants_334.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_264.font, menuOpts.font) - .text(_$constants_334.arrowSymbol[menuOpts.direction]); + if(axis.type === 'date') dataToPixel = _$helpers_386.decodeDate(dataToPixel); + } + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; + } + else { + dataToPixel = function(v) { return gs.l + gs.w * v; }; + } - arrow.attr({ - x: dims.headerWidth - _$constants_334.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_334.textOffsetY + menuOpts.pad.t - }); + return dataToPixel; +}; - header.on('click', function() { - gButton.call(removeAllButtons); +_$helpers_386.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; + if(axis) { + var r2d = _$helpers_386.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + } + else { + pixelToData = function(p) { return (p - gs.l) / gs.w; }; + } - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_334.menuIndexAttrName, - __isActive_336(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); + return pixelToData; +}; - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - }); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - header.on('mouseover', function() { - header.call(styleOnMouseOver); - }); - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); +'use strict'; - // translate header group - _$drawing_264.setTranslate(gHeader, dims.lx, dims.ly); -} +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); - } +/* removed: var _$constants_383 = require('./constants'); */; +/* removed: var _$helpers_386 = require('./helpers'); */; - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; - var klass = menuOpts.type === 'dropdown' ? _$constants_334.dropdownButtonClassName : _$constants_334.buttonClassName; +var _$calcAutorange_382 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + shapeList = _$lib_425.filterVisible(fullLayout.shapes); - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); + if(!shapeList.length || !gd._fullData.length) return; - var enter = buttons.enter().append('g') - .classed(klass, true); + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; - var exit = buttons.exit(); + var ax, bounds; - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_470.getFromId(gd, shape.xref); - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); - } + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_383.paramIsX); - var x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; + if(bounds) _$axes_470.expand(ax, bounds, calcXPaddingOptions(shape)); + } - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_470.getFromId(gd, shape.yref); - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_334.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_334.gapButtonHeader; + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_383.paramIsY); + if(bounds) _$axes_470.expand(ax, bounds, calcYPaddingOptions(shape)); } } +}; - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_334.gapButtonHeader + _$constants_334.gapButton - dims.openHeight; - } +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_334.gapButtonHeader + _$constants_334.gapButton - dims.openWidth; - } +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_334.gapButton, - xPad: _$constants_334.gapButton, - index: 0, - }; +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_383.paramIsY : _$constants_383.paramIsX) : + [v0, v1]; + var maxValue = _$lib_425.aggNums(Math.max, null, coords), + minValue = _$lib_425.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_68.select(this); + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; - button.on('click', function() { - // skip `dragend` events - if(_$d3_68.event.defaultPrevented) return; + var segments = path.match(_$constants_383.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - __setActive_336(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + var params = segment.substr(1).match(_$constants_383.paramRE); + if(!params || params.length < relevantParamIdx) return; - if(buttonOpts.execute) { - _$plots_444.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); - } + extractedCoordinates.push(params[relevantParamIdx]); + }); - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); - }); + return extractedCoordinates; +} - button.on('mouseover', function() { - button.call(styleOnMouseOver); - }); +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); - }); + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; - buttons.call(styleButtons, menuOpts); + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_383.segmentRE), + i, + segment, + drawnParam, + params, + val; - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); - } + if(ax.type === 'date') convertVal = _$helpers_386.decodeDate(convertVal); - scrollBoxPosition.direction = menuOpts.direction; + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); - } + params = segments[i].substr(1).match(_$constants_383.paramRE); + if(!params || params.length < drawnParam) continue; + + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; } + if(max >= min) return [min, max]; } -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_334.gapButton; - } - } - else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_334.gapButton; - } - } - scrollBox.enable(position, translateX, translateY); +'use strict'; - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } -} +/* removed: var _$attributes_381 = require('./attributes'); */; +/* removed: var _$helpers_386 = require('./helpers'); */; -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } +var _$handleShapeDefaults_388 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); + function coerce(attr, dflt) { + return _$lib_425.coerce(shapeIn, shapeOut, _$attributes_381, attr, dflt); } -} -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); -} + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); + if(!visible) return shapeOut; - rect.enter().append('rect') - .classed(_$constants_334.itemRectClassName, true) - .attr({ - rx: _$constants_334.rx, - ry: _$constants_334.ry, - 'shape-rendering': 'crispEdges' - }); + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - rect.call(_$color_239.stroke, menuOpts.bordercolor) - .call(_$color_239.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); -} + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - text.enter().append('text') - .classed(_$constants_334.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + // xref, yref + var axRef = _$axes_470.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - text.call(_$drawing_264.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_386.convertToTspans, gd); -} + if(axRef !== 'paper') { + ax = _$axes_470.getFromId(gdMock, axRef); + r2pos = _$helpers_386.rangeToShapePosition(ax); + pos2r = _$helpers_386.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_425.identity; + } -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; - buttons.each(function(buttonOpts, i) { - var button = _$d3_68.select(this); + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_334.itemRectClassName) - .call(_$color_239.fill, _$constants_334.activeColor); + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_470.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_470.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; } - }); -} -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_334.itemRectClassName) - .call(_$color_239.fill, _$constants_334.hoverColor); -} + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_334.itemRectClassName) - .call(_$color_239.fill, menuOpts.bgcolor); -} + _$axes_470.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); -// find item dimensions (this mutates menuOpts) -function __findDimensions_336(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; + } + } - var fakeButtons = _$drawing_264.tester.selectAll('g.' + _$constants_334.dropdownButtonClassName) - .data(menuOpts.buttons); + if(shapeType === 'path') { + coerce('path'); + } + else { + _$lib_425.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + } - fakeButtons.enter().append('g') - .classed(_$constants_334.dropdownButtonClassName, true); + return shapeOut; +}; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_68.select(this); - button.call(drawItem, menuOpts, buttonOpts, gd); +'use strict'; - var text = button.select('.' + _$constants_334.itemTextClassName); +/* removed: var _$handleArrayContainerDefaults_466 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_388 = require('./shape_defaults'); */; - // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_264.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_334.textPadX, _$constants_334.minWidth); - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_336; - var tLines = _$svg_text_utils_386.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_334.minHeight) + _$constants_334.textOffsetY; +var _$supplyLayoutDefaults_384 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_388 + }; - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); + _$handleArrayContainerDefaults_466(layoutIn, layoutOut, opts); +}; - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_334.gapButton; - dims.openHeight += hEff + _$constants_334.gapButton; - } else { - dims.totalWidth += wEff + _$constants_334.gapButton; - dims.openWidth += wEff + _$constants_334.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; - } - }); +'use strict'; - if(isVertical) { - dims.totalHeight -= _$constants_334.gapButton; - } else { - dims.totalWidth -= _$constants_334.gapButton; - } +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$dragelement_323 = require('../dragelement'); */; +/* removed: var _$setCursor_445 = require('../../lib/setcursor'); */; - dims.headerWidth = dims.width1 + _$constants_334.arrowPadX; - dims.headerHeight = dims.height1; +/* removed: var _$constants_383 = require('./constants'); */; +/* removed: var _$helpers_386 = require('./helpers'); */; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_334.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_334.arrowPadX; - } - fakeButtons.remove(); +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; +var _$draw_385 = { + draw: __draw_385, + drawOne: __drawOne_385 +}; - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); +function __draw_385(gd) { + var fullLayout = gd._fullLayout; - var xanchor = 'left'; - if(_$anchor_utils_291.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = 'right'; - } - if(_$anchor_utils_291.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = 'center'; - } + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); - var yanchor = 'top'; - if(_$anchor_utils_291.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = 'bottom'; - } - if(_$anchor_utils_291.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = 'middle'; + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); } - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_385(gd, i); + } + } - _$plots_444.autoMargin(gd, _$constants_334.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); } -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_334.itemRectClassName); - var text = item.select('.' + _$constants_334.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; - - _$drawing_264.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); - - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); - - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight - }); +function __drawOne_385(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - var tHeight = menuOpts.font.size * __LINE_SPACING_336; - var tLines = _$svg_text_utils_386.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; - _$svg_text_utils_386.positionText(text, _$constants_334.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_334.textOffsetY); + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); + } } - posOpts.index++; -} + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_334.dropdownButtonClassName).remove(); -} + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_301.stroke, lineColor) + .call(_$color_301.fill, options.fillcolor) + .call(_$drawing_326.dashLine, options.line.dash, options.line.width); -function __clearPushMargins_336(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + path.call(_$drawing_326.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null + ); - if(k.indexOf(_$constants_334.autoMarginIdRoot) !== -1) { - _$plots_444.autoMargin(gd, k); - } + if(gd._context.edits.shapePosition) __setupDragElement_385(gd, path, options, index); } } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +function __setupDragElement_385(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; -/* removed: var _$constants_334 = require('./constants'); */; + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; -var _$updatemenus_337 = { - moduleType: 'component', - name: _$constants_334.name, + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; - layoutAttributes: _$attributes_333, - supplyLayoutDefaults: _$updateMenusDefaults_335, + var xa, ya, x2p, y2p, p2x, p2y; - draw: _$draw_336 -}; + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; -var _$mathjax_config_347 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + _$dragelement_323.init(dragOptions); -'use strict'; + shapePath.node().onmousemove = updateDragMode; -/* global MathJax:false */ + function updateDragMode(evt) { + // element might not be on screen at time of setup, + // so obtain bounding box here + var dragBBox = dragOptions.element.getBoundingClientRect(); -/** - * Check and configure MathJax - */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_347.MathJax = true; + // choose 'move' or 'resize' + // based on initial position of cursor within the drag element + var w = dragBBox.right - dragBBox.left, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_323.getCursor(x / w, 1 - y / h) : + 'move'; - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] - } - }); + _$setCursor_445(shapePath, cursor); - MathJax.Hub.Configured(); -} else { - _$mathjax_config_347.MathJax = false; -} + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function startDrag(evt) { + // setup conversion functions + xa = _$axes_470.getFromId(gd, shapeOptions.xref); + ya = _$axes_470.getFromId(gd, shapeOptions.yref); + x2p = _$helpers_386.getDataToPixel(gd, xa); + y2p = _$helpers_386.getDataToPixel(gd, ya, true); + p2x = _$helpers_386.getPixelToData(gd, xa); + p2y = _$helpers_386.getPixelToData(gd, ya, true); -'use strict'; + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; -/* removed: var _$lib_363 = require('../lib'); */; -/* removed: var _$plot_config_397 = require('../plot_api/plot_config'); */; + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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); -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; + } - for(var i = 0; i < args.length; i++) { - arg = args[i]; + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.x0'; optE = 'x0'; + } - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_363.extendDeep([], arg) : - _$lib_363.extendDeepAll({}, arg); + // 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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; } - else copy[i] = arg; - } - return copy; -} + update = {}; + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; + } -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + function endDrag() { + _$setCursor_445(shapePath); + _$registry_514.call('relayout', gd, update); + } + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; -var __queue_377 = {}; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_386.encodeDate(moveX); + } -// TODO: disable/enable undo and redo buttons appropriately + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_386.encodeDate(moveY); + } -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_377.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; + shapePath.attr('d', getPathString(gd, shapeOptions)); } - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; - } - gd.undoQueue.beginSequence = false; + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); - } + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_386.encodeDate(moveX); + } - if(gd.undoQueue.queue.length > _$plot_config_397.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; - } -}; + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_386.encodeDate(moveY); + } -/** - * Begin a sequence of undoQueue changes - * - * @param gd - */ -__queue_377.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; -/** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended - * - * @param gd - */ -__queue_377.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; -}; + // 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; -/** - * Move one step back in the undo queue, and undo the object there. - * - * @param gd - */ -__queue_377.undo = function undo(gd) { - var queueObj, i; + // 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; + shapePath.attr('d', getPathString(gd, shapeOptions)); } +} - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; - - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_470.getFromId(gd, options.xref), + ya = _$axes_470.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_377.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + if(xa) { + x2r = _$helpers_386.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; + } + else { + x2p = function(v) { return gs.l + gs.w * v; }; } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; - -/** - * Redo the current object in the undo, then move forward in the queue. - * - * @param gd - */ -__queue_377.redo = function redo(gd) { - var queueObj, i; - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; + if(ya) { + y2r = _$helpers_386.shapePositionToRange(ya); + y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; + else { + y2p = function(v) { return gs.t + gs.h * (1 - v); }; } - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_377.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_386.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_386.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; - - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; -}; -/** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. - * - * @param gd - * @param func - * @param args - */ -__queue_377.plotDo = function(gd, func, args) { - gd.autoplay = true; + 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); + } - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); + 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); + } - // call the supplied function - func.apply(null, args); -}; + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; +} -var _$queue_377 = __queue_377; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; -'use strict'; -var _$localeEnUs_389 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' - }, - format: { - date: '%m/%d/%Y' - } -}; + return pathIn.replace(_$constants_383.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_383.paramIsX[segmentType], + yParams = _$constants_383.paramIsY[segmentType], + nParams = _$constants_383.numParams[segmentType]; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 paramString = segment.substr(1).replace(_$constants_383.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++; -'use strict'; + if(paramNumber > nParams) param = 'X'; + return param; + }); -var _$localeEn_390 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' - } -}; + if(paramNumber > nParams) { + paramString = paramString.replace(/[\s,]*X.*/, ''); + _$lib_425.log('Ignoring extra params in segment ' + segment); + } -var _$fromQuat_94 = fromQuat; + return segmentType + paramString; + }); +} -/** - * 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, +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_383.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_383.paramIsX[segmentType], + yParams = _$constants_383.paramIsY[segmentType], + nParams = _$constants_383.numParams[segmentType]; - 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; + var paramString = segment.substr(1).replace(_$constants_383.paramRE, function(param) { + if(paramNumber >= nParams) return param; - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; + if(xParams[paramNumber]) param = moveX(param); + else if(yParams[paramNumber]) param = moveY(param); - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + paramNumber++; - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + return param; + }); - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + return segmentType + paramString; + }); +} - return out; -}; -var _$helpers_393 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_94 = require('gl-mat4/fromQuat'); */; - -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$lib_363 = require('../lib'); */; -/* removed: var _$plots_444 = require('../plots/plots'); */; -/* removed: var _$axis_ids_410 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_410.cleanId; -var getFromTrace = _$axis_ids_410.getFromTrace; -/* removed: var _$color_239 = require('../components/color'); */; - - -// clear the promise queue if one of them got rejected -_$helpers_393.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_363.log('Clearing previous rejected promises from queue.'); - } - - gd._promises = []; -}; - -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_393.cleanLayout = function(layout) { - var i, j; - - if(!layout) layout = {}; - - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; - } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; - } - - var axisAttrRegex = (_$plots_444.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_444.subplotsRegistry.gl3d || {}).attrRegex; - - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; - - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); - - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories +*/ - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; - } - } +'use strict'; - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; +/* removed: var _$draw_385 = require('./draw'); */; - // clean old Camera coords - var cameraposition = scene.cameraposition; +var _$shapes_387 = { + moduleType: 'component', + name: 'shapes', - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_94([], rotation), - eye = []; + layoutAttributes: _$attributes_381, + supplyLayoutDefaults: _$supplyLayoutDefaults_384, + includeBasePlot: _$makeIncludeComponents_480('shapes'), - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } + calcAutorange: _$calcAutorange_382, + draw: _$draw_385.draw, + drawOne: _$draw_385.drawOne +}; - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - delete scene.cameraposition; - } - } - } - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; +'use strict'; - if(!_$lib_363.isPlainObject(ann)) continue; - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } +var _$constants_390 = { - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); - } + // layout attribute name + name: 'sliders', - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', - if(!_$lib_363.isPlainObject(shape)) continue; + railHeight: 5, - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); - } + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; - } - } + // min item width / height + minWidth: 30, + minHeight: 30, - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + // padding around item text + textPadX: 40, - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_239.clean(layout); + // arrow offset off right edge + arrowOffsetX: 4, - return layout; + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', + + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, + + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, + + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', + + labelPadding: 8, + labelOffset: 0, + + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, + + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, + + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, }; -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); - } -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_393.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); +'use strict'; - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_505 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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(i = 0; i < 100; i++) { - newUid = _$lib_363.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_363.randstr(uids); - uids.push(trace.uid); - } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); +'use strict'; - // BACKWARD COMPATIBILITY FIXES +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_505 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_389 = _$extend_416.extendDeepAll; +var __overrideAll_389 = _$edit_types_455.overrideAll; +/* removed: var _$animation_attributes_465 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_390 = require('./constants'); */; - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } +var stepsAttrs = { + _isLinkedToArray: 'step', - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_239.defaults, - yeColor = trace.error_y.color || - (_$registry_451.traceIs(trace, 'bar') ? _$color_239.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_239.addOpacity( - _$color_239.rgb(yeColor), - _$color_239.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } + ], + + }, + label: { + valType: 'string', + + + }, + value: { + valType: 'string', + + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_451.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_393.swapXYData(trace); - } - delete trace.bardir; - } +var _$attributes_389 = __overrideAll_389({ + _isLinkedToArray: 'slider', - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_393.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; - } + visible: { + valType: 'boolean', + + dflt: true, + + }, - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } + active: { + valType: 'number', + + min: 0, + dflt: 0, + + }, - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + steps: stepsAttrs, - // scene ids scene1 -> scene - if(_$registry_451.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_444.subplotsRegistry.gl3d.cleanId(trace.scene); - } + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], + + dflt: 'fraction', + + }, + len: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + pad: __extendDeepAll_389({}, _$pad_attributes_505, { + + }, {t: {dflt: 20}}), + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - if(!_$registry_451.traceIs(trace, 'pie') && !_$registry_451.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_465.transition.easing.values, + + dflt: 'cubic-in-out', + } + }, - // fix typo in colorscale definition - if(_$registry_451.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_451.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_363.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; + offset: { + valType: 'number', + dflt: 10, + + + }, - if(!_$lib_363.isPlainObject(opts)) continue; + prefix: { + valType: 'string', + + + }, - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } + suffix: { + valType: 'string', + + + }, - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } - } + font: _$font_attributes_496({ + + }) + }, - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; + font: _$font_attributes_496({ + + }), - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + activebgcolor: { + valType: 'color', + + dflt: _$constants_390.gripBgActiveColor, + + }, + bgcolor: { + valType: 'color', + + dflt: _$constants_390.railBgColor, + + }, + bordercolor: { + valType: 'color', + dflt: _$constants_390.railBorderColor, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_390.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_390.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_390.tickColor, + + + }, + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_390.minorTickLength, + + + } +}, 'arraydraw', 'from-root'); - if(!_$lib_363.isPlainObject(transform)) continue; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } +'use strict'; - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_466 = require('../../plots/array_container_defaults'); */; - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; +/* removed: var _$attributes_389 = require('./attributes'); */; +/* removed: var _$constants_390 = require('./constants'); */; - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); +var __name_391 = _$constants_390.name; +var stepAttrs = _$attributes_389.steps; - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } - } - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; - } +var _$slidersDefaults_391 = function slidersDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_391, + handleItemDefaults: sliderDefaults + }; - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_239.clean(trace); - } + _$handleArrayContainerDefaults_466(layoutIn, layoutOut, opts); }; -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; +function sliderDefaults(sliderIn, sliderOut, layoutOut) { - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + function coerce(attr, dflt) { + return _$lib_425.coerce(sliderIn, sliderOut, _$attributes_389, attr, dflt); + } - return posY + ' ' + posX; -} + var steps = stepsDefaults(sliderIn, sliderOut); -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); -} + var visible = coerce('visible', steps.length > 0); + if(!visible) return; + coerce('active'); -// swap all the data and data attributes associated with x and y -_$helpers_393.swapXYData = function(trace) { - var i; - _$lib_363.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_363.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_363.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); - } - } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; - } - trace.hoverinfo = hoverInfoParts.join('+'); - } -}; + coerce('x'); + coerce('y'); + _$lib_425.noneOrAll(sliderIn, sliderOut, ['x', 'y']); -// coerce traceIndices input to array of trace indices -_$helpers_393.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_78(traceIndices)) { - return [traceIndices]; - } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); - } + coerce('xanchor'); + coerce('yanchor'); - return traceIndices; -}; + coerce('len'); + coerce('lenmode'); -/** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_393.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); - var pLastIsNumber = _$fastIsnumeric_78(pLast); + _$lib_425.coerceFont(coerce, 'font', layoutOut.font); - // delete item - if(pLastIsNumber && newVal === null) { + var currentValueIsVisible = coerce('currentvalue.visible'); - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_363.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); + if(currentValueIsVisible) { + coerce('currentvalue.xanchor'); + coerce('currentvalue.prefix'); + coerce('currentvalue.suffix'); + coerce('currentvalue.offset'); - // Note that nested property clears null / undefined at end of - // array container, but not within them. + _$lib_425.coerceFont(coerce, 'currentvalue.font', sliderOut.font); } - // create item - else if(pLastIsNumber && np.get() === undefined) { - - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; - np.set(newVal); - } - // update item - else { + coerce('transition.duration'); + coerce('transition.easing'); - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); - } -}; + coerce('bgcolor'); + coerce('activebgcolor'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('ticklen'); + coerce('tickwidth'); + coerce('tickcolor'); + coerce('minorticklen'); +} -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; +function stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); -} + var valueIn, valueOut; -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_393.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); + function coerce(attr, dflt) { + return _$lib_425.coerce(valueIn, valueOut, stepAttrs, attr, dflt); } - return false; -}; -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_393 = ['x', 'y', 'z']; -_$helpers_393.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_393[j]); + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; + coerce('method'); - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_363.nestedProperty(gd.layout, typeAttr).set(null); - } - } + if(!_$lib_425.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + continue; } - } -}; -_$helpers_393.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; - } + coerce('args'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); + coerce('execute'); + + valuesOut.push(valueOut); } -}; -var _$manage_arrays_395 = {}; + return valuesOut; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -74942,816 +76163,606 @@ var _$manage_arrays_395 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$nestedProperty_371 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_365 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_372 = require('../lib/noop'); */; -/* removed: var _$loggers_368 = require('../lib/loggers'); */; -var sorterAsc = _$search_381.sorterAsc; -/* removed: var _$registry_451 = require('../registry'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_353 = require('../legend/anchor_utils'); */; -_$manage_arrays_395.containerArrayMatch = _$containerArrayMatch_391; +/* removed: var _$constants_390 = require('./constants'); */; +/* removed: var _$alignment_401 = require('../../constants/alignment'); */; +var __LINE_SPACING_392 = _$alignment_401.LINE_SPACING; +var __FROM_TL_392 = _$alignment_401.FROM_TL; +var __FROM_BR_392 = _$alignment_401.FROM_BR; -var isAddVal = _$manage_arrays_395.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_365(val); -}; +var _$draw_392 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); -var isRemoveVal = _$manage_arrays_395.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_390.containerClassName) + .data(sliderData.length > 0 ? [0] : []); -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_395.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_451.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_451.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_451.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_372) || - (draw === _$noop_372), - layout = gd.layout, - fullLayout = gd._fullLayout; + sliders.enter().append('g') + .classed(_$constants_390.containerClassName, true) + .style('cursor', 'ew-resize'); - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_368.warn('Full array edits are incompatible with other edits', - componentType); - } + sliders.exit().remove(); - var fullVal = edits['']['']; + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_392(gd); - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); - else { - _$loggers_368.warn('Unrecognized full array edit value', componentType, fullVal); - return true; - } + // Return early if no menus visible: + if(sliderData.length === 0) return; - if(replotLater) return false; + var sliderGroups = sliders.selectAll('g.' + _$constants_390.groupClassName) + .data(sliderData, keyFunction); - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; - } + sliderGroups.enter().append('g') + .classed(_$constants_390.groupClassName, true); - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_371(fullLayout, componentType).get(); + sliderGroups.exit().each(function(sliderOpts) { + _$d3_71.select(this).remove(); - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + _$plots_506.autoMargin(gd, _$constants_390.autoMarginIdRoot + sliderOpts._index); + }); - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_368.warn('index out of range', componentType, componentNum); - continue; - } + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); + } - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_368.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_368.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } + var gSlider = _$d3_71.select(this); - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_371(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } - } + computeLabelSteps(sliderOpts); - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); - } + _$plots_506.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); + if(opts.active === data.index) return; + if(opts._dragging) return; - if(replotLater) return false; + setActive(gd, gSlider, opts, data.index, false, true); + }); - supplyComponentDefaults(layout, fullLayout); + drawSlider(gd, _$d3_71.select(this), sliderOpts); + }); +}; - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_372) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); - } +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_390.name], + sliderData = []; + + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); } - else draw(gd); - return true; -}; + return sliderData; +} -var _$buttons_301 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 is set in the defaults step: +function keyFunction(opts) { + return opts._index; +} +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_326.tester.selectAll('g.' + _$constants_390.labelGroupClass) + .data(sliderOpts.steps); -'use strict'; + sliderLabels.enter().append('g') + .classed(_$constants_390.labelGroupClass, true); -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_410 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_71.select(this); -var ____301 = _$lib_363._; + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); -var modeBarButtons = _$buttons_301 = {}; + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_326.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + } + }); -/** - * 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? - */ + sliderLabels.remove(); -modeBarButtons.toImage = { - name: 'toImage', - title: function(gd) { return ____301(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; + var dims = sliderOpts._dims = {}; - _$lib_363.notifier(____301(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + dims.inputAreaWidth = Math.max( + _$constants_390.railWidth, + _$constants_390.gripHeight + ); - if(_$lib_363.isIE()) { - _$lib_363.notifier(____301(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; - } + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); - _$registry_451.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_363.notifier(____301(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_363.notifier(____301(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; } -}; -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____301(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_444.sendDataToCloud(gd); - } -}; + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____301(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian -}; + var textableInputLength = dims.inputAreaLength - 2 * _$constants_390.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_390.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____301(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian -}; + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____301(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_326.tester.append('g'); -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____301(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian -}; + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_326.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_449.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____301(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian -}; + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____301(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian -}; + dummyGroup.remove(); + } -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____301(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian -}; + dims.height = dims.currentValueTotalHeight + _$constants_390.tickOffset + sliderOpts.ticklen + _$constants_390.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____301(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian -}; + var xanchor = 'left'; + if(_$anchor_utils_353.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; + } + if(_$anchor_utils_353.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; + } -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____301(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian -}; + var yanchor = 'top'; + if(_$anchor_utils_353.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_353.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; + } -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____301(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; - }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian -}; + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); -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 = _$axis_ids_410.list(gd, null, true); - var allSpikesEnabled = 'on'; + _$plots_506.autoMargin(gd, _$constants_390.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_392[xanchor], + r: dims.outerLength * __FROM_BR_392[xanchor], + b: dims.height * __FROM_BR_392[yanchor], + t: dims.height * __FROM_TL_392[yanchor] + }); +} - var ax, i; +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; + } - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); - var axName; + var dims = sliderOpts._dims; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; + // Position the rectangle: + _$drawing_326.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); - 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]; - } - 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]), - ]; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); - 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]); - } - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; - aobj[astr] = val; + var dims = sliderOpts._dims; + var x0, textAnchor; + + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_390.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_390.currentValueInset; + textAnchor = 'left'; } - _$registry_451.call('relayout', gd, aobj); -} + var text = _$lib_425.ensureSingle(sliderGroup, 'text', _$constants_390.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____301(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d -}; + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____301(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d -}; + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; + } -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____301(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d -}; + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; + } -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____301(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['z-axis'], - click: handleDrag3d -}; + text.call(_$drawing_326.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_449.convertToTspans, sliderOpts._gd); -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 lines = _$svg_text_utils_449.lineCount(text); - var parts = attr.split('.'); + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_392; - for(var i = 0; i < sceneIds.length; i++) { - layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; - } + _$svg_text_utils_449.positionText(text, x0, y0); - // for multi-type subplots - var val2d = (val === 'pan') ? val : 'zoom'; - layoutUpdate.dragmode = val2d; + return text; +} + +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_425.ensureSingle(sliderGroup, 'rect', _$constants_390.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - _$registry_451.call('relayout', gd, layoutUpdate); + grip.attr({ + width: _$constants_390.gripWidth, + height: _$constants_390.gripHeight, + rx: _$constants_390.gripRadius, + ry: _$constants_390.gripRadius, + }) + .call(_$color_301.stroke, sliderOpts.bordercolor) + .call(_$color_301.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); } -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____301(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; +function drawLabel(item, data, sliderOpts) { + var text = _$lib_425.ensureSingle(item, 'text', _$constants_390.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____301(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d -}; + text.call(_$drawing_326.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_449.convertToTspans, sliderOpts._gd); -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 = {}; + return text; +} - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_425.ensureSingle(sliderGroup, 'g', _$constants_390.labelsClass); + var dims = sliderOpts._dims; - if(attr === 'resetDefault') { - aobj[key] = null; - } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_363.extendDeep({}, scene.cameraInitial); - } - } + var labelItems = labels.selectAll('g.' + _$constants_390.labelGroupClass) + .data(dims.labelSteps); - _$registry_451.call('relayout', gd, aobj); -} + labelItems.enter().append('g') + .classed(_$constants_390.labelGroupClass, true); -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____301(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; + labelItems.exit().remove(); -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; + labelItems.each(function(d) { + var item = _$d3_71.select(this); - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + item.call(drawLabel, d, sliderOpts); - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; + _$drawing_326.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_390.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_392 + + _$constants_390.labelOffset + + dims.currentValueTotalHeight + ); + }); - if(val) { - layoutUpdate = _$lib_363.extendDeep(layout, val); - button._previousVal = null; +} + +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); + + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); } - else { - layoutUpdate = { - 'allaxes.showspikes': false - }; +} - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + var step = sliderOpts.steps[sliderOpts.active]; - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); + + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; + + if(_step.execute) { + _$plots_506.executeAPICommand(gd, _step.method, _step.args); } - } - } - button._previousVal = _$lib_363.extendDeep({}, currentSpikes); + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } } - - _$registry_451.call('relayout', gd, layoutUpdate); } -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____301(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_71.select(gd); -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____301(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; + } -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____301(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo -}; + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____301(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + var grip = sliderGroup.select('.' + _$constants_390.gripRectClass); -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; + _$d3_71.event.stopPropagation(); + _$d3_71.event.preventDefault(); + grip.call(_$color_301.fill, sliderOpts.activebgcolor); - for(var i = 0; i < geoIds.length; i++) { - var id = geoIds[i]; - var geoLayout = fullLayout[id]; + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_71.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; - if(attr === 'zoom') { - var scale = geoLayout.projection.scale; - var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_71.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); + }); + + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_301.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); - _$registry_451.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); - } - } + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); + }); } -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____301(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_390.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____301(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + tick.enter().append('rect') + .classed(_$constants_390.tickRectClass, true); -function toggleHover(gd) { - var fullLayout = gd._fullLayout; + tick.exit().remove(); - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; - } - else onHoverVal = 'closest'; + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_71.select(this); - _$registry_451.call('relayout', gd, 'hovermode', newHover); -} + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_301.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); -// buttons when more then one plot types are present + _$drawing_326.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_390.tickOffset : _$constants_390.minorTickOffset) + dims.currentValueTotalHeight + ); + }); -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____301(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); +} - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; + + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); } -}; +} -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____301(gd, 'Reset views'); }, - icon: _$ploticon_2.home, - click: function(gd, ev) { - var button = ev.currentTarget; +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_390.gripRectClass); - button.setAttribute('data-attr', 'zoom'); - button.setAttribute('data-val', 'reset'); - handleCartesian(gd, ev); + var x = normalizedValueToPosition(sliderOpts, position); - button.setAttribute('data-attr', 'resetLastSave'); - handleCamera3d(gd, ev); + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; - resetView(gd, 'geo'); - resetView(gd, 'mapbox'); + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); } -}; -modeBarButtons.toggleSpikelines = { - name: 'toggleSpikelines', - title: function(gd) { return ____301(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_390.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); +} - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_390.stepInset + + (dims.inputAreaLength - 2 * _$constants_390.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} - var aobj = setSpikelineVisibility(gd); +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_390.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_390.stepInset - 2 * dims.inputAreaStart))); +} - _$registry_451.call('relayout', gd, aobj); - } -}; +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_425.ensureSingle(sliderGroup, 'rect', _$constants_390.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_410.list(gd, null, true); - var aobj = {}; + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_390.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_301.fill, sliderOpts.bgcolor) + .attr('opacity', 0); - var ax, axName; + _$drawing_326.setTranslate(rect, 0, dims.currentValueTotalHeight); +} - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; - } +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_390.railInset * 2; + var rect = _$lib_425.ensureSingle(sliderGroup, 'rect', _$constants_390.railRectClass); - return aobj; -} + rect.attr({ + width: computedLength, + height: _$constants_390.railWidth, + rx: _$constants_390.railRadius, + ry: _$constants_390.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_301.stroke, sliderOpts.bordercolor) + .call(_$color_301.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____301(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); - } -}; + _$drawing_326.setTranslate(rect, + _$constants_390.railInset, + (dims.inputAreaWidth - _$constants_390.railWidth) * 0.5 + dims.currentValueTotalHeight + ); +} -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; +function __clearPushMargins_392(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); - 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 i = 0; i < keys.length; i++) { + var k = keys[i]; - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; + if(k.indexOf(_$constants_390.autoMarginIdRoot) !== -1) { + _$plots_506.autoMargin(gd, k); } } - - _$registry_451.call('relayout', gd, aObj); } /** @@ -75762,294 +76773,349 @@ function resetView(gd, subplotType) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; +/* removed: var _$constants_390 = require('./constants'); */; +var _$sliders_393 = { + moduleType: 'component', + name: _$constants_390.name, -/** - * 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'); + layoutAttributes: _$attributes_389, + supplyLayoutDefaults: _$slidersDefaults_391, - this.update(opts.graphInfo, opts.buttons); + draw: _$draw_392 +}; - this.container.appendChild(this.element); -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 __proto_304 = ModeBar.prototype; +'use strict'; -/** - * 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_304.update = function(graphInfo, buttons) { - this.graphInfo = graphInfo; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_300 = require('../color/attributes'); */; +var __extendFlat_395 = _$extend_416.extendFlat; +var __overrideAll_395 = _$edit_types_455.overrideAll; +/* removed: var _$pad_attributes_505 = require('../../plots/pad_attributes'); */; - var context = this.graphInfo._context; +var buttonsAttrs = { + _isLinkedToArray: 'button', - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + } - else this.element.className = 'modebar'; +}; - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); +var _$attributes_395 = __overrideAll_395({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); + visible: { + valType: 'boolean', + + + }, - this.updateButtons(buttons); + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; - } - } + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, - this.updateActiveButton(); -}; + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, -__proto_304.updateButtons = function(buttons) { - var _this = this; + showactive: { + valType: 'boolean', + + dflt: true, + + }, - this.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; + buttons: buttonsAttrs, - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - 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); + pad: __extendFlat_395({}, _$pad_attributes_505, { + + }), - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); + font: _$font_attributes_496({ + + }), - _this.element.appendChild(group); - }); -}; + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_300.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + + } +}, 'arraydraw', 'from-root'); /** - * Empty div for containing a group of buttons - * @Return {HTMLelement} - */ -__proto_304.createGroup = function() { - var group = document.createElement('div'); - group.className = 'modebar-group'; +* Copyright 2012-2018, Plotly, Inc. +* All 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 group; -}; -/** - * Create a new button div and set constant and configurable attributes - * @Param {object} config (see ./buttons.js for more info) - * @Return {HTMLelement} - */ -__proto_304.createButton = function(config) { - var _this = this, - button = document.createElement('a'); +'use strict'; - 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); +var _$constants_396 = { - if(title || title === 0) button.setAttribute('data-title', title); + // layout attribute name + name: 'updatemenus', - if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); + // 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', - var val = config.val; - if(val !== undefined) { - if(typeof val === 'function') val = val(this.graphInfo); - button.setAttribute('data-val', val); - } + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'updatemenu-active-index', - 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); + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'updatemenu-', - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); - } + // options when 'active: -1' + blankHeaderOpts: { label: ' ' }, - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_68.select(button).classed('active', true); + // min item width / height + minWidth: 30, + minHeight: 30, - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - button.setAttribute('data-gravity', config.gravity || 'n'); + // padding around item text + textPadX: 24, + arrowPadX: 16, - return button; -}; + // item rect radii + rx: 2, + ry: 2, -/** - * Add an icon to a button - * @Param {object} thisIcon - * @Param {number} thisIcon.width - * @Param {string} thisIcon.path - * @Return {HTMLelement} - */ -__proto_304.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); + // item text x offset off left edge + textOffsetX: 12, - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); + // item text y offset (w.r.t. middle) + textOffsetY: 3, - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; + // arrow offset off right edge + arrowOffsetX: 4, - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); + // gap between header and buttons + gapButtonHeader: 5, - return icon; + // 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: '▼' + } }; /** - * Updates active button with attribute specified in layout - * @Param {object} graphInfo plot object containing data and layout - * @Return {HTMLelement} - */ -__proto_304.updateActiveButton = function(buttonClicked) { - var fullLayout = this.graphInfo._fullLayout, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_466 = require('../../plots/array_container_defaults'); */; - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_68.select(button); +/* removed: var _$attributes_395 = require('./attributes'); */; +/* removed: var _$constants_396 = require('./constants'); */; - // 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_363.nestedProperty(fullLayout, dataAttr).get(); +var __name_397 = _$constants_396.name; +var __buttonAttrs_397 = _$attributes_395.buttons; - button3.classed('active', val === thisval); - } - }); +var _$updateMenusDefaults_397 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_397, + handleItemDefaults: menuDefaults + }; + + _$handleArrayContainerDefaults_466(layoutIn, layoutOut, opts); }; -/** - * Check if modeBar is configured as button configuration argument - * - * @Param {object} buttons 2d array of grouped button config objects - * @Return {boolean} - */ -__proto_304.hasButtons = function(buttons) { - var currentButtons = this.buttons; +function menuDefaults(menuIn, menuOut, layoutOut) { - if(!currentButtons) return false; + function coerce(attr, dflt) { + return _$lib_425.coerce(menuIn, menuOut, _$attributes_395, attr, dflt); + } - if(buttons.length !== currentButtons.length) return false; + var buttons = __buttonsDefaults_397(menuIn, menuOut); - 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; - } - } + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; - return true; -}; + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -__proto_304.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); + coerce('x'); + coerce('y'); + _$lib_425.noneOrAll(menuIn, menuOut, ['x', 'y']); - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_363._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; + coerce('xanchor'); + coerce('yanchor'); - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); - group.appendChild(a); - return group; -}; + _$lib_425.coerceFont(coerce, 'font', layoutOut.font); -__proto_304.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} + +function __buttonsDefaults_397(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; + + var buttonIn, buttonOut; + + function coerce(attr, dflt) { + return _$lib_425.coerce(buttonIn, buttonOut, __buttonAttrs_397, attr, dflt); } - this.hasLogo = false; -}; + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; -__proto_304.destroy = function() { - _$lib_363.removeElement(this.container.querySelector('.modebar')); -}; + coerce('method'); -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; + if(!_$lib_425.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); + coerce('args'); + coerce('label'); + coerce('execute'); - if(fullLayout._privateplot) { - _$d3_68.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); + buttonOut._index = i; + buttonsOut.push(buttonOut); } - return modeBar; + return buttonsOut; } -var _$createModeBar_304 = createModeBar; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -76058,253 +77124,468 @@ var _$createModeBar_304 = createModeBar; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$axis_ids_410 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_534 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_451 = require('../../registry'); */; +var _$ScrollBox_400 = ScrollBox; -/* removed: var _$createModeBar_304 = require('./modebar'); */; -/* removed: var _$buttons_301 = require('./buttons'); */; +/* removed: var _$d3_71 = require('d3'); */; + +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; + +/* removed: var _$lib_425 = require('../../lib'); */; /** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. + * Helper class to setup a scroll box * - * @param {object} gd main plot object + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box + */ +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; + + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection + + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); + + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} + +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; + +/** + * If needed, setup a clip path and scrollbars * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) */ -var _$manageModeBar_303 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; + // compute position of scrollbox + this.position = position; + + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; + + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; } - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; + + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; + } } + else { + boxT = t; + boxB = boxT + boxH; - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; + } + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; + } } - var customButtons = context.modeBarButtons; - var buttonGroups; + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; + + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); + + hbar.exit() + .on('.drag', null) + .remove(); + + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_301.fill, ScrollBox.barColor); + + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); + + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; } else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_304(gd, buttonGroups); -}; - -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; - var groups = []; + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); - function addGroup(newGroup) { - if(!newGroup.length) return; + vbar.exit() + .on('.drag', null) + .remove(); - var out = []; + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_301.fill, ScrollBox.barColor); - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_301[button]); - } + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); - groups.push(out); + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; + } + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; + clipPath.exit().remove(); + + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); + + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); + + this.container.call(_$drawing_326.setClipUrl, clipId); + + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_326.setClipUrl, null); + delete this._clipRect; } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; + + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_71.behavior.drag() + .on('dragstart', function() { + _$d3_71.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); + + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); + + var onBarDrag = _$d3_71.behavior.drag() + .on('dragstart', function() { + _$d3_71.event.sourceEvent.preventDefault(); + _$d3_71.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); + + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } + + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; + + // set scrollbox translation + this.setTranslate(translateX, translateY); +}; + +/** + * If present, remove clip-path and scrollbars + * + * @method + */ +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_326.setClipUrl, null); + delete this._clipRect; } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; + + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; + + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; +}; + +/** + * Handles scroll box drag events + * + * @method + */ +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX -= _$d3_71.event.dx; } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + + if(this.vbar) { + translateY -= _$d3_71.event.dy; } - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + this.setTranslate(translateX, translateY); +}; + +/** + * Handles scroll box wheel events + * + * @method + */ +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX += _$d3_71.event.deltaY; } - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; - } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); + if(this.vbar) { + translateY += _$d3_71.event.deltaY; } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); + this.setTranslate(translateX, translateY); +}; - return appendButtonsToGroups(groups, buttonsToAdd); -} +/** + * Handles scroll bar drag events + * + * @method + */ +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_410.list({_fullLayout: fullLayout}, null, true); + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_425.constrain(_$d3_71.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } + var translateXMax = this.position.w - this._box.w; + + translateX = xf * translateXMax; } - return true; -} + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_425.constrain(_$d3_71.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; + var translateYMax = this.position.h - this._box.h; - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; + translateY = yf * translateYMax; + } - var trace = fullData[i]; + this.setTranslate(translateX, translateY); +}; - if(!trace._module || !trace._module.selectPoints) continue; +/** + * Set clip path and scroll bar translate transform + * + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; - if(_$registry_451.traceIs(trace, 'scatter-like')) { - if(_$subtypes_534.hasMarkers(trace) || _$subtypes_534.hasText(trace)) { - selectable = true; - } - } else if(_$registry_451.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; - } + translateX = _$lib_425.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_425.constrain(translateY || 0, 0, translateYMax); - return selectable; -} + this.translateX = translateX; + this.translateY = translateY; -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } - } - else groups.push(buttons); + this.container.call(_$drawing_326.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); + + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); } - return groups; -} + if(this.hbar) { + var xf = translateX / translateXMax; -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; + this.hbar.call(_$drawing_326.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); + } - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + if(this.vbar) { + var yf = translateY / translateYMax; - if(typeof button === 'string') { - if(_$buttons_301[button] !== undefined) { - customButtons[i][j] = _$buttons_301[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } + this.vbar.call(_$drawing_326.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); } +}; - return customButtons; -} - -var _$modebar_302 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -76316,1618 +77597,1045 @@ var _$modebar_302 = {}; 'use strict'; -_$modebar_302.manage = _$manageModeBar_303; +/* removed: var _$d3_71 = require('d3'); */; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$color_301 = require('../color'); */; +/* removed: var _$drawing_326 = require('../drawing'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$svg_text_utils_449 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_353 = require('../legend/anchor_utils'); */; -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// +var __LINE_SPACING_398 = _$alignment_401.LINE_SPACING; -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; +/* removed: var _$constants_396 = require('./constants'); */; +/* removed: var _$ScrollBox_400 = require('./scrollbox'); */; - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } +var _$draw_398 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ -var _$BuildLog_159 = BuildLog; + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_396.containerClassName) + .data(menuData.length > 0 ? [0] : []); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + menus.enter().append('g') + .classed(_$constants_396.containerClassName, true) + .style('cursor', 'pointer'); -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + menus.exit().remove(); -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_398(gd); - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + // return early if no update menus are visible + if(menuData.length === 0) return; - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_396.headerGroupClassName) + .data(menuData, __keyFunction_398); - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; + headerGroups.enter().append('g') + .classed(_$constants_396.headerGroupClassName, true); - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident + // draw dropdown button container + var gButton = _$lib_425.ensureSingle(menus, 'g', _$constants_396.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_398(gd, menuOpts); + } - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_400(gd, gButton, scrollBoxId); - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); - // categorize where intersection point is along A and B + gButton + .call(removeAllButtons) + .attr(_$constants_396.menuIndexAttrName, '-1'); + } - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + headerGroups.exit().each(function(menuOpts) { + _$d3_71.select(this).remove(); - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + gButton + .call(removeAllButtons) + .attr(_$constants_396.menuIndexAttrName, '-1'); - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + _$plots_506.autoMargin(gd, _$constants_396.autoMarginIdRoot + menuOpts._index); + }); - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_71.select(this); - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_506.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_398(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); + + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + + // if this menu is active, update the dropdown container + if(__isActive_398(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); + } + + }); +}; + +/** + * get only visible menus for display + */ +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_396.name]; + var menuData = []; + + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + + if(item.visible) menuData.push(item); + } + + return menuData; } -var _$Epsilon_160 = Epsilon; +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_398(menuOpts) { + return menuOpts._index; +} -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +function isFolded(gButton) { + return +gButton.attr(_$constants_396.menuIndexAttrName) === -1; +} -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// +function __isActive_398(gButton, menuOpts) { + return +gButton.attr(_$constants_396.menuIndexAttrName) === menuOpts._index; +} -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ +function __setActive_398(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; + + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); + } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_396.menuIndexAttrName, '-1'); - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - // 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] }); - } + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } +} - // the first LineString is considered the outside - var out = LineString(coords[0]); +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_425.ensureSingle(gHeader, 'g', _$constants_396.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); - // 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]))); + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_396.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; - return out; - } + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); - 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'); - }, + // draw drop arrow at the right edge + var arrow = _$lib_425.ensureSingle(gHeader, 'text', _$constants_396.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_326.font, menuOpts.font) + .text(_$constants_396.arrowSymbol[menuOpts.direction]); + }); - // 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)); + arrow.attr({ + x: dims.headerWidth - _$constants_396.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_396.textOffsetY + menuOpts.pad.t + }); - // 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); - } + header.on('click', function() { + gButton.call(removeAllButtons); - // 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: [] - }; - } + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_396.menuIndexAttrName, + __isActive_398(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); - var roots = newNode(null); + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); - 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; - } - } + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); - // 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--; - } - } + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); - // now we can add ourselves - root.children.push(node); - } + // translate header group + _$drawing_326.setTranslate(gHeader, dims.lx, dims.ly); +} - // 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); - } +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } - // 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 + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; - // while we're at it, exteriors are counter-clockwise, and interiors are clockwise + var klass = menuOpts.type === 'dropdown' ? _$constants_396.dropdownButtonClassName : _$constants_396.buttonClassName; - 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 buttons = gButton.selectAll('g.' + klass) + .data(buttonData); - var geopolys = []; + var enter = buttons.enter().append('g') + .classed(klass, true); - 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])); - } + var exit = buttons.exit(); - 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); - } + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); + } - // lastly, construct the approrpriate GeoJSON object + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; - 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 - }; - } -}; + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; -var _$GeoJSON_161 = GeoJSON; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_396.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_396.gapButtonHeader; + } + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_396.gapButtonHeader + _$constants_396.gapButton - dims.openHeight; + } -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_396.gapButtonHeader + _$constants_396.gapButton - dims.openWidth; + } -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_396.gapButton, + xPad: _$constants_396.gapButton, + index: 0, + }; -var _$LinkedList_163 = LinkedList; + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_71.select(this); -// -// this is the core work-horse -// + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); -/* removed: var _$LinkedList_163 = require('./linked-list'); */; + button.on('click', function() { + // skip `dragend` events + if(_$d3_71.event.defaultPrevented) return; -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm + __setActive_398(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - // - // segment creation - // + if(buttonOpts.execute) { + _$plots_506.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); - // - // event logic - // + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); - var event_root = _$LinkedList_163.create(); + buttons.call(styleButtons, menuOpts); - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + } - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + scrollBoxPosition.direction = menuOpts.direction; - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } +} - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_396.gapButton; + } + } + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_396.gapButton; + } + } - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_163.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } + scrollBox.enable(position, translateX, translateY); - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_163.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } +} - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; - if (buildLog) - buildLog.segmentChop(ev.seg, end); + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); + } +} - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); +} - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used +function drawItemRect(item, menuOpts) { + var rect = _$lib_425.ensureSingle(item, 'rect', _$constants_396.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_396.rx, + ry: _$constants_396.ry, + 'shape-rendering': 'crispEdges' + }); + }); - // - // status logic - // + rect.call(_$color_301.stroke, menuOpts.bordercolor) + .call(_$color_301.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} - var status_root = _$LinkedList_163.create(); +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_425.ensureSingle(item, 'text', _$constants_396.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; + text.call(_$drawing_326.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_449.convertToTspans, gd); +} - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + buttons.each(function(buttonOpts, i) { + var button = _$d3_71.select(this); - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_396.itemRectClassName) + .call(_$color_301.fill, _$constants_396.activeColor); + } + }); +} - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_396.itemRectClassName) + .call(_$color_301.fill, _$constants_396.hoverColor); +} - if (buildLog) - buildLog.checkIntersection(seg1, seg2); +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_396.itemRectClassName) + .call(_$color_301.fill, menuOpts.bgcolor); +} - var i = eps.linesIntersect(a1, a2, b1, b2); +// find item dimensions (this mutates menuOpts) +function __findDimensions_398(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; - if (i === false){ - // segments are parallel or coincident + var fakeButtons = _$drawing_326.tester.selectAll('g.' + _$constants_396.dropdownButtonClassName) + .data(menuOpts.buttons); - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) + fakeButtons.enter().append('g') + .classed(_$constants_396.dropdownButtonClassName, true); - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_71.select(this); - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal + button.call(drawItem, menuOpts, buttonOpts, gd); - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); + var text = button.select('.' + _$constants_396.itemTextClassName); - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_326.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_396.textPadX, _$constants_396.minWidth); - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_398; + var tLines = _$svg_text_utils_449.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_396.minHeight) + _$constants_396.textOffsetY; - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_396.gapButton; + dims.openHeight += hEff + _$constants_396.gapButton; + } else { + dims.totalWidth += wEff + _$constants_396.gapButton; + dims.openWidth += wEff + _$constants_396.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); - if (buildLog) - buildLog.vert(ev.pt[0]); + if(isVertical) { + dims.totalHeight -= _$constants_396.gapButton; + } else { + dims.totalWidth -= _$constants_396.gapButton; + } - if (ev.isStart){ - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + dims.headerWidth = dims.width1 + _$constants_396.arrowPadX; + dims.headerHeight = dims.height1; - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_396.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_396.arrowPadX; + } - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + fakeButtons.remove(); - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - // merge ev.seg's fill information into eve.seg + var xanchor = 'left'; + if(_$anchor_utils_353.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_353.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + var yanchor = 'top'; + if(_$anchor_utils_353.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_353.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - if (buildLog) - buildLog.segmentUpdate(eve.seg); + _$plots_506.autoMargin(gd, _$constants_396.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); +} - ev.other.remove(); - ev.remove(); - } +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_396.itemRectClassName); + var text = item.select('.' + _$constants_396.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } + _$drawing_326.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var tHeight = menuOpts.font.size * __LINE_SPACING_398; + var tLines = _$svg_text_utils_449.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + _$svg_text_utils_449.positionText(text, _$constants_396.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_396.textOffsetY); - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; + } - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_163.node({ ev: ev })); - } - else{ - var st = ev.status; + posOpts.index++; +} - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_396.dropdownButtonClassName).remove(); +} - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); +function __clearPushMargins_398(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - if (buildLog) - buildLog.statusRemove(st.ev.seg); + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - // remove the status - st.remove(); + if(k.indexOf(_$constants_396.autoMarginIdRoot) !== -1) { + _$plots_506.autoMargin(gd, k); + } + } +} - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 the event and continue - event_root.getHead().remove(); - } +'use strict'; - if (buildLog) - buildLog.done(); +/* removed: var _$constants_396 = require('./constants'); */; - return segments; - } +var _$updatemenus_399 = { + moduleType: 'component', + name: _$constants_396.name, - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } + layoutAttributes: _$attributes_395, + supplyLayoutDefaults: _$updateMenusDefaults_397, - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; + draw: _$draw_398 +}; - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it +var _$mathjax_config_408 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; -} +'use strict'; -var _$Intersecter_162 = Intersecter; +/* global MathJax:false */ -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_408.MathJax = true; -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; + MathJax.Hub.Configured(); +} else { + _$mathjax_config_408.MathJax = false; +} - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (buildLog) - buildLog.chainStart(seg); - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } +'use strict'; - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$plot_config_460 = require('../plot_api/plot_config'); */; - if (next_match === second_match){ - // we matched a single chain - if (buildLog) - buildLog.chainMatch(first_match.index); +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop + for(var i = 0; i < args.length; i++) { + arg = args[i]; - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_425.extendDeep([], arg) : + _$lib_425.extendDeepAll({}, arg); + } + else copy[i] = arg; + } - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + return copy; +} - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } - if (buildLog) - buildLog.chainClose(first_match.index); +var __queue_440 = {}; - // we have a closed chain! - regions.push(chain); - return; - } +// TODO: disable/enable undo and redo buttons appropriately - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } +/** + * Add an item to the undoQueue for a graphDiv + * + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with + */ +__queue_440.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; - // otherwise, we matched two chains, so we need to combine those chains together + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } + if(gd.undoQueue.queue.length > _$plot_config_460.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_440.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; - var F = first_match.index; - var S = second_match.index; +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_440.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; +}; - if (buildLog) - buildLog.chainConnect(F, S); +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_440.undo = function undo(gd) { + var queueObj, i; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } - return regions; -} + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; -var _$SegmentChainer_164 = SegmentChainer; + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_440.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; -// -// filter a list of segments based on boolean operations -// +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd + */ +__queue_440.redo = function redo(gd) { + var queueObj, i; -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } - if (buildLog) - buildLog.selected(result); + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - return result; -} + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_440.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; }; -var _$SegmentSelector_165 = SegmentSelector; +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_440.plotDo = function(gd, func, args) { + gd.autoplay = true; + + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs - */ + // call the supplied function + func.apply(null, args); +}; -/* removed: var _$BuildLog_159 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_160 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_162 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_164 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_165 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_161 = require('./lib/geojson'); */; +var _$queue_440 = __queue_440; -var buildLog = false; -var epsilon = _$Epsilon_160(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_159(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, +'use strict'; - // core API - segments: function(poly){ - var i = _$Intersecter_162(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_162(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_165.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_165.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_165.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_165.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_165.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_164(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, +var _$localeEnUs_452 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } +}; - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_161.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_161.fromPolygon(PolyBool, epsilon, poly); - }, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // 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); - } +'use strict'; + +var _$localeEn_453 = { + 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' + } }; -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); -} +var _$fromQuat_151 = fromQuat; -if (typeof window === 'object') - window.PolyBool = PolyBool; +/** + * 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; -var _$PolyBool_158 = PolyBool; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; -var _$polygon_375 = {}; + return out; +}; +var _$helpers_456 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -77939,684 +78647,841 @@ var _$polygon_375 = {}; 'use strict'; -var dot = _$matrix_369.dot; -var __BADNUM_375 = _$numerical_343.BADNUM; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_151 = require('gl-mat4/fromQuat'); */; -var polygon = _$polygon_375 = {}; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$plots_506 = require('../plots/plots'); */; +/* removed: var _$axis_ids_473 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_473.cleanId; +var getFromTrace = _$axis_ids_473.getFromTrace; +/* removed: var _$color_301 = require('../components/color'); */; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; +// clear the promise queue if one of them got rejected +_$helpers_456.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_425.log('Clearing previous rejected promises from queue.'); + } - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); + gd._promises = []; +}; + +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_456.cleanLayout = function(layout) { + var i, j; + + if(!layout) layout = {}; + + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; } - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed + var axisAttrRegex = (_$plots_506.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_506.subplotsRegistry.gl3d || {}).attrRegex; - var isRect = false, - rectFirstEdgeTest; + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[i]; - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories + + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; + + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; + } + delete ax.autotick; } } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; + + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; + + // clean old Camera coords + var cameraposition = scene.cameraposition; + + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_151([], rotation), + eye = []; + + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } + + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; + + delete scene.cameraposition; } } } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; - if(x === __BADNUM_375 || x < xmin || x > xmax || y === __BADNUM_375 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(!_$lib_425.isPlainObject(ann)) continue; + + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; + } + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; - return true; + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); } - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; + + if(!_$lib_425.isPlainObject(shape)) continue; + + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); + } + + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } + + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } + + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_301.clean(layout); + + return layout; +}; + +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); + } +} + +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_456.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); + + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; + + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; + + for(i = 0; i < 100; i++) { + newUid = _$lib_425.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_425.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); + + // BACKWARD COMPATIBILITY FIXES + + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } + + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_301.defaults, + yeColor = trace.error_y.color || + (_$registry_514.traceIs(trace, 'bar') ? _$color_301.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_301.addOpacity( + _$color_301.rgb(yeColor), + _$color_301.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; + } + + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_514.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_456.swapXYData(trace); + } + delete trace.bardir; + } + + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_456.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } + + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } + + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + + // scene ids scene1 -> scene + if(_$registry_514.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_506.subplotsRegistry.gl3d.cleanId(trace.scene); + } + + if(!_$registry_514.traceIs(trace, 'pie') && !_$registry_514.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } + + // fix typo in colorscale definition + if(_$registry_514.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_514.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } + + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_425.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; + + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; + + if(!_$lib_425.isPlainObject(opts)) continue; + + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } - if(x === __BADNUM_375 || x < xmin || x > xmax || y === __BADNUM_375 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } } - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; } - // inside the bounding box, check the actual line intercept - else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); + } - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; - if(y <= ycross && x !== xmini) crossings++; - } - } + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } + if(!_$lib_425.isPlainObject(transform)) continue; - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; - } - } + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; - for(var i = 0; i < list.length; i++) { - 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); - } + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } } } - return yes; - } + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_301.clean(trace); + } }; -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; +function cleanFinanceDir(dirContainer) { + if(!_$lib_425.isPlainObject(dirContainer)) return false; - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); + var dirName = dirContainer.name; - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; - } - return false; -}; + delete dirContainer.name; + delete dirContainer.showlegend; -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); +} - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; - } - } - } + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; } - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 out = name1.substr(0, i); + return out.trim(); +} -'use strict'; +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; -/* removed: var _$PolyBool_158 = require('polybooljs'); */; -/* removed: var _$polygon_375 = require('../../lib/polygon'); */; -/* removed: var _$throttle_387 = require('../../lib/throttle'); */; -/* removed: var _$color_239 = require('../../components/color'); */; -var makeEventData = _$helpers_278.makeEventData; -/* removed: var _$fx_281 = require('../../components/fx'); */; + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; -/* removed: var _$axes_407 = require('./axes'); */; -/* removed: var _$constants_412 = require('./constants'); */; + return posY + ' ' + posX; +} -var filteredPolygon = _$polygon_375.filter; -var polygonTester = _$polygon_375.tester; -var multipolygonTester = _$polygon_375.multitester; -var MINSELECT = _$constants_412.MINSELECT; +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} -function getAxId(ax) { return ax._id; } -var _$prepSelect_425 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; +// swap all the data and data attributes associated with x and y +_$helpers_456.swapXYData = function(trace) { + var i; + _$lib_425.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_425.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_425.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); } +}; - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_412.BENDPX); +// coerce traceIndices input to array of trace indices +_$helpers_456.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_135(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); } - 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'); + return traceIndices; +}; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_239.background, - stroke: _$color_239.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * + */ +_$helpers_456.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; + var pLastIsNumber = _$fastIsnumeric_135(pLast); - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_412.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; + // delete item + if(pLastIsNumber && newVal === null) { - 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; + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_425.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_407.getFromId(gd, trace.xaxis), - yaxis: _$axes_407.getFromId(gd, trace.yaxis) - }); - } + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; + + np.set(newVal); } + // update item + else { - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); } +}; - function ascending(a, b) { return a - b; } +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); +} - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_456.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_456 = ['x', 'y', 'z']; +_$helpers_456.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_456[j]); - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; + var typeAttr = axAttr + '.type'; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_425.nestedProperty(gd.layout, typeAttr).set(null); } - }; - } - } - - 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), - dy = Math.abs(y1 - y0); - - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } + } +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); +_$helpers_456.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); + } +}; - _$throttle_387.throttle( - throttleID, - _$constants_412.SELECTDELAY, - function() { - selection = []; +var _$manage_arrays_458 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); +'use strict'; - thisSelection = fillSelectionItem(traceSelection, searchInfo); +/* removed: var _$nestedProperty_433 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_427 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_434 = require('../lib/noop'); */; +/* removed: var _$loggers_430 = require('../lib/loggers'); */; +var sorterAsc = _$search_444.sorterAsc; +/* removed: var _$registry_514 = require('../registry'); */; - 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); - } - ); - }; +_$manage_arrays_458.containerArrayMatch = _$containerArrayMatch_454; - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); +var isAddVal = _$manage_arrays_458.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_427(val); +}; - _$throttle_387.done(throttleID).then(function() { - _$throttle_387.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); - } +var isRemoveVal = _$manage_arrays_458.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); - } - else { - // 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. - gd.emit('plotly_selected', undefined); - } +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. + * + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items + * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. + */ +_$manage_arrays_458.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_514.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_514.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_514.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_434) || + (draw === _$noop_434), + layout = gd.layout, + fullLayout = gd._fullLayout; - _$fx_281.click(gd, evt); - }); - }; + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_430.warn('Full array edits are incompatible with other edits', + componentType); + } - dragOptions.doneFn = function() { - corners.remove(); + var fullVal = edits['']['']; - _$throttle_387.done(throttleID).then(function() { - _$throttle_387.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_430.warn('Unrecognized full array edit value', componentType, fullVal); + return true; + } - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); + if(replotLater) return false; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; -}; + supplyComponentDefaults(layout, fullLayout); + draw(gd); + return true; + } -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_433(fullLayout, componentType).get(); - if(eventData) { - var pts = eventData.points || []; + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); + + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_430.warn('index out of range', componentType, componentNum); + continue; } - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_430.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); + } - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); + } + else { + _$loggers_430.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); } - } - } - else { - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); + if(firstIndexChange === -1) firstIndexChange = componentNum; + } + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_433(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } } - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } -} - -function mergePolygons(list, poly, subtract) { - var res; - - if(subtract) { - res = _$PolyBool_158.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); - - return res.regions; + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - res = _$PolyBool_158.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - return res.regions; -} + if(replotLater) return false; -function fillSelectionItem(selection, searchInfo) { - if(Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; + supplyComponentDefaults(layout, fullLayout); - for(var i = 0; i < selection.length; i++) { - selection[i] = makeEventData(selection[i], trace, cd); + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_434) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); + } + } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); } } + else draw(gd); - return selection; -} + return true; +}; +var _$buttons_363 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -78628,1091 +79493,896 @@ function fillSelectionItem(selection, searchInfo) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$tinycolor_201 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_126 = require('has-passive-events'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$svg_text_utils_386 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_239 = require('../../components/color'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; -/* removed: var _$fx_281 = require('../../components/fx'); */; -/* removed: var _$setCursor_382 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_261 = require('../../components/dragelement'); */; -var __FROM_TL_415 = _$alignment_339.FROM_TL; - -/* removed: var _$plots_444 = require('../plots'); */; - -var doTicks = _$axes_407.doTicks; -var getFromId = _$axis_ids_410.getFromId; -/* removed: var _$prepSelect_425 = require('./select'); */; -/* removed: var _$scaleZoom_424 = require('./scale_zoom'); */; - -/* removed: var _$constants_412 = require('./constants'); */; -var MINDRAG = _$constants_412.MINDRAG; -var MINZOOM = _$constants_412.MINZOOM; - +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +var ____363 = _$lib_425._; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px - var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; +var modeBarButtons = _$buttons_363 = {}; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; +/** + * 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? + */ - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____363(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$lib_425.notifier(____363(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); + if(_$lib_425.isIE()) { + _$lib_425.notifier(____363(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; + } - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; + _$registry_514.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_425.notifier(____363(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_425.notifier(____363(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); + } +}; - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____363(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_506.sendDataToCloud(gd); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____363(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____363(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____363(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian +}; - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } - } +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____363(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - recomputeAxisLists(); +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____363(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian +}; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____363(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian +}; - var allFixedRanges = !yActive && !xActive; +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____363(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; - } +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____363(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____363(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____363(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; +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 = _$axis_ids_473.list(gd, null, true); + var allSpikesEnabled = 'on'; - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_425(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; + var ax, i; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + var axName; - if(numClicks === 2 && !singleEnd) doubleClick(); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(isMainDrag) { - _$fx_281.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; + 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]; + } + 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]), + ]; - if(ax.fixedrange) return; + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); } - else if(ew === 'e') hAlign = 'right'; - - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_68.select(dragger) - .call(_$svg_text_utils_386.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_451.call('relayout', gd, attrStr, v); - } - }); + } + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; } } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; } - }; - _$dragelement_261.init(dragOptions); + aobj[astr] = val; + } - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + _$registry_514.call('relayout', gd, aobj); +} - // collected changes to be made to the plot by relayout at the end - var updates = {}; +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____363(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d +}; - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_201(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____363(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d +}; - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____363(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - corners = makeCorners(zoomlayer, xs, ys); +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____363(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['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('.'); - clearSelect(zoomlayer); + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); + _$registry_514.call('relayout', gd, layoutUpdate); +} - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____363(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____363(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.movie, + click: handleCamera3d +}; - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); +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], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; + + if(attr === 'resetDefault') { + aobj[key] = null; } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_425.extendDeep({}, scene.cameraInitial); } - box.w = box.r - box.l; - box.h = box.b - box.t; - - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; } - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } + _$registry_514.call('relayout', gd, aobj); +} - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____363(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); - } +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_412.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; - if(redrawTimer === null) { - clearSelect(zoomlayer); - } + if(val) { + layoutUpdate = _$lib_425.extendDeep(layout, val); + button._previousVal = null; + } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; - var pc = gd.querySelector('.plotly'); + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; - recomputeAxisLists(); + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + } + } } - clearTimeout(redrawTimer); + button._previousVal = _$lib_425.extendDeep({}, currentSpikes); + } - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_363.log('Did not find wheel motion attributes: ', e); - return; - } + _$registry_514.call('relayout', gd, layoutUpdate); +} - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____363(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____363(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; - var axRange = _$lib_363.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____363(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____363(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); +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; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + _$registry_514.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); } + } +} - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); - - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; - - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____363(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; - dragTail(zoomMode); - }, REDRAWDELAY); +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____363(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; - e.preventDefault(); - return; - } +function toggleHover(gd) { + var fullLayout = gd._fullLayout; - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; } + else onHoverVal = 'closest'; - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - recomputeAxisLists(); + _$registry_514.call('relayout', gd, 'hovermode', newHover); +} - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } +// buttons when more then one plot types are present - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____363(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____363(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); + } +}; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_424(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_424(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____363(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - updateSubplots([x0, y0, pw - dx, ph - dy]); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - ticksAndAnnotations(yActive, xActive); + var aobj = setSpikelineVisibility(gd); + + _$registry_514.call('relayout', gd, aobj); } +}; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_473.list(gd, null, true); + var aobj = {}; - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); - } - } + var ax, axName; - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); - } + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + return aobj; +} - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____363(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + 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); - redrawObjs(fullLayout.annotations || [], _$registry_451.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_451.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_451.getComponentMethod('images', 'draw'), true); + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + _$registry_514.call('relayout', gd, aObj); +} - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 ax, i, rangeInitial; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { +'use strict'; - doubleClickConfig = 'autosize'; +/* removed: var _$d3_71 = require('d3'); */; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +/** + * 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'); - for(i = 0; i < axList.length; i++) { - ax = axList[i]; + this.update(opts.graphInfo, opts.buttons); - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + this.container.appendChild(this.element); +} - gd.emit('plotly_doubleclick', null); - _$registry_451.call('relayout', gd, attrs); - } +var __proto_366 = ModeBar.prototype; - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); +/** + * 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_366.update = function(graphInfo, buttons) { + this.graphInfo = graphInfo; - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_363.syncOrAsync([ - _$plots_444.previousPromises, - function() { _$registry_451.call('relayout', gd, updates); } - ], gd); - } + var context = this.graphInfo._context; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; + } + else this.element.className = 'modebar'; - var i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } + this.updateButtons(buttons); - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_424(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_415[ax.constraintoward || 'middle']; - } + this.updateActiveButton(); +}; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); - } +__proto_366.updateButtons = function(buttons) { + var _this = this; - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_363.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_363.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); + buttonGroup.forEach(function(buttonConfig) { + var buttonName = buttonConfig.name; + if(!buttonName) { + throw new Error('must provide button \'name\' in button config'); } - - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; + if(_this.buttonsNames.indexOf(buttonName) !== -1) { + throw new Error('button name \'' + buttonName + '\' is taken'); } + _this.buttonsNames.push(buttonName); - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; - - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; - - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_264.setTranslate, clipDx, clipDy) - .call(_$drawing_264.setScale, xScaleFactor2, yScaleFactor2); - - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); - - subplot.plot - .call(_$drawing_264.setTranslate, plotDx, plotDy) - .call(_$drawing_264.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_264.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_264.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_264.hideOutsideRangePoints, subplot); + _this.element.appendChild(group); + }); +}; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_264.hideOutsideRangePoints, subplot, '.bartext'); - } - } +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +__proto_366.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - return dragger; -} + return group; +}; -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); +/** + * Create a new button div and set constant and configurable attributes + * @Param {object} config (see ./buttons.js for more info) + * @Return {HTMLelement} + */ +__proto_366.createButton = function(config) { + var _this = this, + button = document.createElement('a'); - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - dragger3.call(_$setCursor_382, cursor); + 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); - return dragger3.node(); -} + if(title || title === 0) button.setAttribute('data-title', title); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_68.select(dragger).call(_$drawing_264.setRect, x, y, w, h); - return dragger; -} + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; - } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_68.format('.' + dig + 'g')(Math.pow(10, initialVal)); - } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_68.format('.' + String(dig) + 'g')(initialVal); + 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); -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_71.select(button).classed('active', true); - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + return button; +}; - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } -} +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +__proto_366.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); -function dragAxList(axList, pix) { - for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; - } - } -} + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; -} + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} + return icon; +}; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_239.background, - stroke: _$color_239.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} +/** + * Updates active button with attribute specified in layout + * @Param {object} graphInfo plot object containing data and layout + * @Return {HTMLelement} + */ +__proto_366.updateActiveButton = function(buttonClicked) { + var fullLayout = this.graphInfo._fullLayout, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_71.select(button); -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + // 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_425.nestedProperty(fullLayout, dataAttr).get(); -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); - } -} + button3.classed('active', val === thisval); + } -function removeZoombox(gd) { - _$d3_68.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); -} + }); +}; -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_363.notifier(_$lib_363._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; - } -} +/** + * Check if modeBar is configured as button configuration argument + * + * @Param {object} buttons 2d array of grouped button config objects + * @Return {boolean} + */ +__proto_366.hasButtons = function(buttons) { + var currentButtons = this.buttons; -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} + if(!currentButtons) return false; -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} + if(buttons.length !== currentButtons.length) return false; -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} + 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; + } + } -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; -} + return true; +}; -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +__proto_366.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_425._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; - } - } - } + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } - } - } - } - } + group.appendChild(a); + return group; +}; - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_363.extendFlat(xLinks, yLinks); - yLinks = {}; +__proto_366.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_126) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; + this.hasLogo = false; +}; - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; +__proto_366.destroy = function() { + _$lib_425.removeElement(this.container.querySelector('.modebar')); +}; - element.addEventListener(wheelEventName, handler, {passive: false}); - } -} +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; -var _$dragbox_415 = { - makeDragBox: makeDragBox, + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, + if(fullLayout._privateplot) { + _$d3_71.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); + } - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, + return modeBar; +} - attachWheelEventHandler: attachWheelEventHandler -}; +var _$createModeBar_366 = createModeBar; /** * Copyright 2012-2018, Plotly, Inc. @@ -79725,152 +80395,264 @@ var _$dragbox_415 = { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; - -/* removed: var _$fx_281 = require('../../components/fx'); */; -/* removed: var _$dragelement_261 = require('../../components/dragelement'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_598 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_514 = require('../../registry'); */; -/* removed: var _$constants_412 = require('./constants'); */; -var __makeDragBox_416 = _$dragbox_415.makeDragBox; +/* removed: var _$createModeBar_366 = require('./modebar'); */; +/* removed: var _$buttons_363 = require('./buttons'); */; -var _$initInteractions_416 = function initInteractions(gd) { - var fullLayout = gd._fullLayout; +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_365 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_68.select(gd).selectAll('.drag').remove(); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; + } return; } - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - 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'), - 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)); + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } + + var customButtons = context.modeBarButtons; + var buttonGroups; + + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } + + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_366(gd, buttonGroups); +}; + +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; + + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); + + var groups = []; + + function addGroup(newGroup) { + if(!newGroup.length) return; + + var out = []; + + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_363[button]); } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + groups.push(out); + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); - var DRAGGERSIZE = _$constants_412.DRAGGERSIZE; + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; - // 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_416(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; + } + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; + } + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; + } + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + } - 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) { - _$fx_281.hover(gd, evt, subplot); - } - }; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - _$fx_281.hover(gd, evt, subplot); + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); + } - // 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; - }; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - /* - * 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; + return appendButtonsToGroups(groups, buttonsToAdd); +} - // 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; +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_473.list({_fullLayout: fullLayout}, null, true); - _$dragelement_261.unhover(gd, evt); - }; + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) { + return false; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_416(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_416(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_416(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_416(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + return true; +} + +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; + + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; + + var trace = fullData[i]; + + if(!trace._module || !trace._module.selectPoints) continue; + + if(_$registry_514.traceIs(trace, 'scatter-like')) { + if(_$subtypes_598.hasMarkers(trace) || _$subtypes_598.hasText(trace)) { + selectable = true; + } + } else if(_$registry_514.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; } } - 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_416(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_416(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_416(gd, plotinfo, xa._offset + xa._length * 0.9, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'e'); + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; + } + + return selectable; +} + +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); } - // 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_416(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_416(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_416(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } + else groups.push(buttons); + } + + return groups; +} + +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; + + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; + + if(typeof button === 'string') { + if(_$buttons_363[button] !== undefined) { + customButtons[i][j] = _$buttons_363[button]; + } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); + } } } - }); + } - // 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(); + return customButtons; +} - hoverLayer.onmousemove = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_281.hover(gd, evt, fullLayout._hoversubplot); - }; +var _$modebar_364 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_281.click(gd, evt); - }; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; +'use strict'; -var _$subroutines_399 = {}; +_$modebar_364.manage = _$manageModeBar_365; + +var _$subroutines_462 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -79881,22 +80663,28 @@ var _$subroutines_399 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$plots_444 = require('../plots/plots'); */; -/* removed: var _$lib_363 = require('../lib'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$plots_506 = require('../plots/plots'); */; + +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$clearGlCanvases_411 = require('../lib/clear_gl_canvases'); */; -/* removed: var _$color_239 = require('../components/color'); */; -/* removed: var _$drawing_264 = require('../components/drawing'); */; -/* removed: var _$titles_332 = require('../components/titles'); */; -/* removed: var _$modebar_302 = require('../components/modebar'); */; -/* removed: var _$axes_407 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_416 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_412 = require('../plots/cartesian/constants'); */; -/* removed: var _$alignment_339 = require('../constants/alignment'); */; +/* removed: var _$color_301 = require('../components/color'); */; +/* removed: var _$drawing_326 = require('../components/drawing'); */; +/* removed: var _$titles_394 = require('../components/titles'); */; +/* removed: var _$modebar_364 = require('../components/modebar'); */; -_$subroutines_399.layoutStyles = function(gd) { - return _$lib_363.syncOrAsync([_$plots_444.doAutoMargin, _$subroutines_399.lsInner], gd); +/* removed: var _$axes_470 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_475 = require('../plots/cartesian/constants'); */; +/* removed: var _$alignment_401 = require('../constants/alignment'); */; +/* removed: var _$constraints_477 = require('../plots/cartesian/constraints'); */; +var __enforceAxisConstraints_462 = _$constraints_477.enforce; +var __cleanAxisConstraints_462 = _$constraints_477.clean; +var __doAutoRange_462 = _$autorange_469.doAutoRange; + +_$subroutines_462.layoutStyles = function(gd) { + return _$lib_425.syncOrAsync([_$plots_506.doAutoMargin, _$subroutines_462.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -79914,11 +80702,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_399.lsInner = function(gd) { +_$subroutines_462.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_407.list(gd); + var axList = _$axes_470.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -79953,7 +80741,7 @@ _$subroutines_399.lsInner = function(gd) { ax._linepositions = {}; // stash crispRounded linewidth so we don't need to pass gd all over the place - ax._lw = _$drawing_264.crispRound(gd, ax.linewidth, 1); + ax._lw = _$drawing_326.crispRound(gd, ax.linewidth, 1); // figure out the main axis line and main mirror line position. // it's easier to follow the logic if we handle these separately from @@ -79962,7 +80750,7 @@ _$subroutines_399.lsInner = function(gd) { ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side); ax._mainMirrorPosition = (ax.mirror && counterAx) ? getLinePosition(ax, counterAx, - _$alignment_339.OPPOSITE_SIDE[ax.side]) : null; + _$alignment_401.OPPOSITE_SIDE[ax.side]) : null; } fullLayout._paperdiv @@ -79971,7 +80759,7 @@ _$subroutines_399.lsInner = function(gd) { height: fullLayout.height + 'px' }) .selectAll('.main-svg') - .call(_$drawing_264.setSize, fullLayout.width, fullLayout.height); + .call(_$drawing_326.setSize, fullLayout.width, fullLayout.height); gd._context.setBackground(gd, fullLayout.paper_bgcolor); @@ -79997,31 +80785,17 @@ _$subroutines_399.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_425.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -80035,7 +80809,7 @@ _$subroutines_399.lsInner = function(gd) { lowerBackgrounds.exit().remove(); lowerBackgrounds.each(function(subplot) { - fullLayout._plots[subplot].bg = _$d3_68.select(this); + fullLayout._plots[subplot].bg = _$d3_71.select(this); }); subplotSelection.each(function(subplot) { @@ -80045,51 +80819,45 @@ _$subroutines_399.lsInner = function(gd) { if(plotinfo.bg && hasSVGCartesian) { plotinfo.bg - .call(_$drawing_264.setRect, + .call(_$drawing_326.setRect, xa._offset - pad, ya._offset - pad, xa._length + 2 * pad, ya._length + 2 * pad) - .call(_$color_239.fill, fullLayout.plot_bgcolor) + .call(_$color_301.fill, fullLayout.plot_bgcolor) .style('stroke-width', 0); } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_425.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); - _$drawing_264.setTranslate(plotinfo.plot, xa._offset, ya._offset); + _$drawing_326.setTranslate(plotinfo.plot, xa._offset, ya._offset); var plotClipId; var layerClipId; if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } - _$drawing_264.setClipUrl(plotinfo.plot, plotClipId); + _$drawing_326.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_412.traceLayerClasses.length; i++) { - var layer = _$constants_412.traceLayerClasses[i]; + for(i = 0; i < _$constants_475.traceLayerClasses.length; i++) { + var layer = _$constants_475.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { - plotinfo.plot.selectAll('g.' + layer).call(_$drawing_264.setClipUrl, layerClipId); + plotinfo.plot.selectAll('g.' + layer).call(_$drawing_326.setClipUrl, layerClipId); } } @@ -80168,7 +80936,7 @@ _$subroutines_399.lsInner = function(gd) { plotinfo.xlines .style('stroke-width', xa._lw + 'px') - .call(_$color_239.stroke, xa.showline ? + .call(_$color_301.stroke, xa.showline ? xa.linecolor : 'rgba(0,0,0,0)'); } plotinfo.xlines.attr('d', xPath); @@ -80205,15 +80973,15 @@ _$subroutines_399.lsInner = function(gd) { plotinfo.ylines .style('stroke-width', ya._lw + 'px') - .call(_$color_239.stroke, ya.showline ? + .call(_$color_301.stroke, ya.showline ? ya.linecolor : 'rgba(0,0,0,0)'); } plotinfo.ylines.attr('d', yPath); }); - _$axes_407.makeClipPaths(gd); - _$subroutines_399.drawMainTitle(gd); - _$modebar_302.manage(gd); + _$axes_470.makeClipPaths(gd); + _$subroutines_462.drawMainTitle(gd); + _$modebar_364.manage(gd); return gd._promises.length && Promise.all(gd._promises); }; @@ -80243,7 +81011,7 @@ function shouldShowLineThisSide(ax, side, counterAx) { // in order to handle cases where the user forgot to anchor this axis correctly // (because its default anchor has the same domain on the relevant end) // check whether the relevant position is the same. - var sideIndex = _$alignment_339.FROM_BL[side]; + var sideIndex = _$alignment_401.FROM_BL[side]; if(counterAx.side === side) { return anchorAx.domain[sideIndex] === ax.domain[sideIndex]; } @@ -80269,10 +81037,10 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_399.drawMainTitle = function(gd) { +_$subroutines_462.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; - _$titles_332.draw(gd, 'gtitle', { + _$titles_394.draw(gd, 'gtitle', { propContainer: fullLayout, propName: 'title', placeholder: fullLayout._dfltTitle.plot, @@ -80288,7 +81056,7 @@ _$subroutines_399.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_399.doTraceStyle = function(gd) { +_$subroutines_462.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -80297,13 +81065,13 @@ _$subroutines_399.doTraceStyle = function(gd) { if(arraysToCalcdata) arraysToCalcdata(cdi, cdi[0].trace); } - _$plots_444.style(gd); - _$registry_451.getComponentMethod('legend', 'draw')(gd); + _$plots_506.style(gd); + _$registry_514.getComponentMethod('legend', 'draw')(gd); - return _$plots_444.previousPromises(gd); + return _$plots_506.previousPromises(gd); }; -_$subroutines_399.doColorBars = function(gd) { +_$subroutines_462.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -80311,7 +81079,7 @@ _$subroutines_399.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_451.traceIs(trace, 'contour')) { + if(_$registry_514.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -80320,49 +81088,54 @@ _$subroutines_399.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_451.traceIs(trace, 'markerColorscale')) { + if(_$registry_514.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); } } - return _$plots_444.previousPromises(gd); + return _$plots_506.previousPromises(gd); }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_399.layoutReplot = function(gd) { +_$subroutines_462.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_451.call('plot', gd, '', layout); + return _$registry_514.call('plot', gd, '', layout); }; -_$subroutines_399.doLegend = function(gd) { - _$registry_451.getComponentMethod('legend', 'draw')(gd); - return _$plots_444.previousPromises(gd); +_$subroutines_462.doLegend = function(gd) { + _$registry_514.getComponentMethod('legend', 'draw')(gd); + return _$plots_506.previousPromises(gd); }; -_$subroutines_399.doTicksRelayout = function(gd) { - _$axes_407.doTicks(gd, 'redraw'); - _$subroutines_399.drawMainTitle(gd); - return _$plots_444.previousPromises(gd); +_$subroutines_462.doTicksRelayout = function(gd) { + _$axes_470.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_411(gd); + _$registry_514.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_462.drawMainTitle(gd); + return _$plots_506.previousPromises(gd); }; -_$subroutines_399.doModeBar = function(gd) { +_$subroutines_462.doModeBar = function(gd) { var fullLayout = gd._fullLayout; - _$modebar_302.manage(gd); - _$initInteractions_416(gd); + _$modebar_364.manage(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; if(updateFx) updateFx(fullLayout); } - return _$plots_444.previousPromises(gd); + return _$plots_506.previousPromises(gd); }; -_$subroutines_399.doCamera = function(gd) { +_$subroutines_462.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -80374,7 +81147,88 @@ _$subroutines_399.doCamera = function(gd) { } }; -var _$micropolar_448 = {}; +_$subroutines_462.drawData = function(gd) { + var fullLayout = gd._fullLayout; + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; + + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_514.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); + + fullLayout._paper + .selectAll(query) + .remove(); + + rangesliderContainers + .selectAll(query) + .remove(); + } + + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } + + _$clearGlCanvases_411(gd); + + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } + + // styling separate from drawing + _$plots_506.style(gd); + + // show annotations and shapes + _$registry_514.getComponentMethod('shapes', 'draw')(gd); + _$registry_514.getComponentMethod('annotations', 'draw')(gd); + + // Mark the first render as complete + fullLayout._replotting = false; + + return _$plots_506.previousPromises(gd); +}; + +_$subroutines_462.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_470.list(gd, '', true); + + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + __cleanAxisConstraints_462(gd, ax); + __doAutoRange_462(ax); + } + + __enforceAxisConstraints_462(gd); +}; + +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_462.finalDraw = function(gd) { + _$registry_514.getComponentMethod('shapes', 'draw')(gd); + _$registry_514.getComponentMethod('images', 'draw')(gd); + _$registry_514.getComponentMethod('annotations', 'draw')(gd); + _$registry_514.getComponentMethod('legend', 'draw')(gd); + _$registry_514.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_514.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_514.getComponentMethod('sliders', 'draw')(gd); + _$registry_514.getComponentMethod('updatemenus', 'draw')(gd); +}; + +var _$micropolar_510 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -80383,25 +81237,25 @@ var _$micropolar_448 = {}; * LICENSE file in the root directory of this source tree. */ -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$lib_363 = require('../../../lib'); */; -var __extendDeepAll_448 = _$lib_363.extendDeepAll; -var __MID_SHIFT_448 = _$alignment_339.MID_SHIFT; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$lib_425 = require('../../../lib'); */; +var __extendDeepAll_510 = _$lib_425.extendDeepAll; +var __MID_SHIFT_510 = _$alignment_401.MID_SHIFT; -var µ = _$micropolar_448 = { version: '0.2.2' }; +var µ = _$micropolar_510 = { version: '0.2.2' }; µ.Axis = function module() { var config = { data: [], layout: {} }, inputConfig = {}, liveConfig = {}; - var svg, container, dispatch = _$d3_68.dispatch('hover'), radialScale, angularScale; + var svg, container, dispatch = _$d3_71.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_68.select(container); + if (typeof container == 'string' || container.nodeName) container = _$d3_71.select(container); container.datum(data).each(function(_data, _index) { var dataOriginal = _data.slice(); liveConfig = { @@ -80415,7 +81269,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length; } if (!d.strokeColor) { - d.strokeColor = d.geometry === 'LinePlot' ? d.color : _$d3_68.rgb(d.color).darker().toString(); + d.strokeColor = d.geometry === 'LinePlot' ? d.color : _$d3_71.rgb(d.color).darker().toString(); } liveConfig.data[i].color = d.color; liveConfig.data[i].strokeColor = d.strokeColor; @@ -80432,7 +81286,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return d; }); if (isStacked) { - var grouped = _$d3_68.nest().key(function(d, i) { + var grouped = _$d3_71.nest().key(function(d, i) { return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked'; }).entries(dataWithGroupId); var dataYStack = []; @@ -80449,7 +81303,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return d.values; } }); - data = _$d3_68.merge(stacked); + data = _$d3_71.merge(stacked); } data.forEach(function(d, i) { d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ]; @@ -80460,13 +81314,13 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ]; var extent; if (isStacked) { - var highestStackedValue = _$d3_68.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); + var highestStackedValue = _$d3_71.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); extent = [ 0, highestStackedValue ]; - } else extent = _$d3_68.extent(µ.util.flattenArray(data.map(function(d, i) { + } else extent = _$d3_71.extent(µ.util.flattenArray(data.map(function(d, i) { return d.r; }))); if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0; - radialScale = _$d3_68.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]); + radialScale = _$d3_71.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; @@ -80476,7 +81330,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; if (isOrdinal) { angularDataMerged = µ.util.deduplicate(angularDataMerged); ticks = angularDataMerged.slice(); - angularDataMerged = _$d3_68.range(angularDataMerged.length); + angularDataMerged = _$d3_71.range(angularDataMerged.length); data = data.map(function(d, i) { var result = d; d.t = [ angularDataMerged ]; @@ -80489,7 +81343,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }).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_68.extent(angularDataMerged); + var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : _$d3_71.extent(angularDataMerged); var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]); if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0; var angularDomainWithPadding = angularDomain.slice(); @@ -80502,19 +81356,19 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; 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_68.range.apply(this, angularDomainWithPadding); + var angularAxisRange = _$d3_71.range.apply(this, angularDomainWithPadding); angularAxisRange = angularAxisRange.map(function(d, i) { return parseFloat(d.toPrecision(12)); }); - angularScale = _$d3_68.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]); + angularScale = _$d3_71.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_68.select(this).select('svg.chart-root'); + svg = _$d3_71.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_68.select(newSvg); + svg = _$d3_71.select(newSvg); } svg.select('.guides-group').style({ 'pointer-events': 'none' @@ -80557,7 +81411,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; data: data.map(function(d, i) { return d.name || 'Element' + i; }), - legendConfig: __extendDeepAll_448({}, + legendConfig: __extendDeepAll_510({}, µ.Legend.defaultConfig().legendConfig, { container: legendContainer, @@ -80622,7 +81476,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return angularScale(d) % 360 + axisConfig.orientation; } if (axisConfig.radialAxis.visible) { - var axis = _$d3_68.svg.axis().scale(radialScale).ticks(5).tickSize(5); + var axis = _$d3_71.svg.axis().scale(radialScale).ticks(5).tickSize(5); radialAxis.call(axis).attr({ transform: 'rotate(' + axisConfig.radialAxis.orientation + ')' }); @@ -80673,7 +81527,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle); var ticksText = angularAxis.select('text.axis-text').attr({ x: radius + axisConfig.labelOffset, - dy: __MID_SHIFT_448 + 'em', + dy: __MID_SHIFT_510 + 'em', transform: function(d, i) { var angle = currentAngle(d, i); var rad = radius + axisConfig.labelOffset; @@ -80693,7 +81547,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; if (i % (axisConfig.minorTicks + 1) != 0) return ''; return axisConfig.angularAxis.rewriteTicks(this.textContent, i); }); - var rightmostTickEndX = _$d3_68.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { + var rightmostTickEndX = _$d3_71.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { return d.getCTM().e + d.getBBox().width; })); legendContainer.attr({ @@ -80725,7 +81579,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; geometryConfig: geometryConfig }); }); - var geometryConfigsGrouped = _$d3_68.nest().key(function(d, i) { + var geometryConfigsGrouped = _$d3_71.nest().key(function(d, i) { return typeof d.data.groupId != 'undefined' || 'unstacked'; }).entries(geometryConfigs); var geometryConfigsGrouped2 = []; @@ -80738,7 +81592,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; 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_448(µ[geometry].defaultConfig(), dB); + return __extendDeepAll_510(µ[geometry].defaultConfig(), dB); }); µ[geometry]().config(finalGeometryConfig)(); }); @@ -80808,7 +81662,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; radialTooltip.hide(); }); svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) { - var el = _$d3_68.select(this); + var el = _$d3_71.select(this); var color = this.style.fill; var newColor = 'black'; var opacity = this.style.opacity || 1; @@ -80819,7 +81673,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; el.attr({ 'data-fill': color }); - newColor = _$d3_68.hsl(color).darker().toString(); + newColor = _$d3_71.hsl(color).darker().toString(); el.style({ fill: newColor, opacity: 1 @@ -80842,18 +81696,18 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; el.attr({ 'data-stroke': color }); - newColor = _$d3_68.hsl(color).darker().toString(); + newColor = _$d3_71.hsl(color).darker().toString(); el.style({ stroke: newColor, opacity: 1 }); } }).on('mousemove.tooltip', function(d, i) { - if (_$d3_68.event.which != 0) return false; - if (_$d3_68.select(this).attr('data-fill')) geometryTooltip.show(); + if (_$d3_71.event.which != 0) return false; + if (_$d3_71.select(this).attr('data-fill')) geometryTooltip.show(); }).on('mouseout.tooltip', function(d, i) { geometryTooltip.hide(); - var el = _$d3_68.select(this); + var el = _$d3_71.select(this); var fillColor = el.attr('data-fill'); if (fillColor) el.style({ fill: fillColor, @@ -80875,11 +81729,11 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; var xClone = µ.util.cloneJson(_x); xClone.data.forEach(function(d, i) { if (!config.data[i]) config.data[i] = {}; - __extendDeepAll_448(config.data[i], µ.Axis.defaultConfig().data[0]); - __extendDeepAll_448(config.data[i], d); + __extendDeepAll_510(config.data[i], µ.Axis.defaultConfig().data[0]); + __extendDeepAll_510(config.data[i], d); }); - __extendDeepAll_448(config.layout, µ.Axis.defaultConfig().layout); - __extendDeepAll_448(config.layout, xClone.layout); + __extendDeepAll_510(config.layout, µ.Axis.defaultConfig().layout); + __extendDeepAll_510(config.layout, xClone.layout); return this; }; exports.getLiveConfig = function() { @@ -80897,7 +81751,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; exports.svg = function() { return svg; }; - _$d3_68.rebind(exports, dispatch, 'on'); + _$d3_71.rebind(exports, dispatch, 'on'); return exports; }; @@ -80916,7 +81770,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; opacity: 1 } ], layout: { - defaultColorRange: _$d3_68.scale.category10().range(), + defaultColorRange: _$d3_71.scale.category10().range(), title: null, height: 450, width: 500, @@ -80997,7 +81851,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; µ.util.dataFromEquation2 = function(_equation, _step) { var step = _step || 6; - var data = _$d3_68.range(0, 360 + step, step).map(function(deg, index) { + var data = _$d3_71.range(0, 360 + step, step).map(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); return [ deg, radius ]; @@ -81008,7 +81862,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; µ.util.dataFromEquation = function(_equation, _step, _name) { var step = _step || 6; var t = [], r = []; - _$d3_68.range(0, 360 + step, step).forEach(function(deg, index) { + _$d3_71.range(0, 360 + step, step).forEach(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); t.push(deg); @@ -81025,7 +81879,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; µ.util.ensureArray = function(_val, _count) { if (typeof _val === 'undefined') return null; var arr = [].concat(_val); - return _$d3_68.range(_count).map(function(d, i) { + return _$d3_71.range(_count).map(function(d, i) { return arr[i] || arr[0]; }); }; @@ -81048,8 +81902,8 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }; µ.util.sumArrays = function(a, b) { - return _$d3_68.zip(a, b).map(function(d, i) { - return _$d3_68.sum(d); + return _$d3_71.zip(a, b).map(function(d, i) { + return _$d3_71.sum(d); }); }; @@ -81092,7 +81946,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }; µ.util.getMousePos = function(_referenceElement) { - var mousePos = _$d3_68.mouse(_referenceElement.node()); + var mousePos = _$d3_71.mouse(_referenceElement.node()); var mouseX = mousePos[0]; var mouseY = mousePos[1]; var mouse = {}; @@ -81147,7 +82001,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; µ.PolyChart = function module() { var config = [ µ.PolyChart.defaultConfig() ]; - var dispatch = _$d3_68.dispatch('hover'); + var dispatch = _$d3_71.dispatch('hover'); var dashArray = { solid: 'none', dash: [ 5, 2 ], @@ -81157,11 +82011,11 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; function exports() { var geometryConfig = config[0].geometryConfig; var container = geometryConfig.container; - if (typeof container == 'string') container = _$d3_68.select(container); + if (typeof container == 'string') container = _$d3_71.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_68.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return _$d3_68.zip(d.data.t[0], d.data.r[0]); + if (isStack) return _$d3_71.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return _$d3_71.zip(d.data.t[0], d.data.r[0]); }); var angularScale = geometryConfig.angularScale; var domainMin = geometryConfig.radialScale.domain()[0]; @@ -81171,7 +82025,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0); var stackTop = geometryConfig.radialScale(d[2] || 0); var w = dataConfig.barWidth; - _$d3_68.select(this).attr({ + _$d3_71.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) { @@ -81181,8 +82035,8 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }; generator.dot = function(d, i, pI) { var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d; - var symbol = _$d3_68.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); - _$d3_68.select(this).attr({ + var symbol = _$d3_71.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); + _$d3_71.select(this).attr({ 'class': 'mark dot', d: symbol, transform: function(d, i) { @@ -81191,7 +82045,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; } }); }; - var line = _$d3_68.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) { + var line = _$d3_71.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; @@ -81200,7 +82054,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; var lineData = d[2] ? data[pI].map(function(d, i) { return [ d[0], d[1] + d[2] ]; }) : data[pI]; - _$d3_68.select(this).each(generator['dot']).style({ + _$d3_71.select(this).each(generator['dot']).style({ opacity: function(dB, iB) { return +_config[pI].data.dotVisible; }, @@ -81209,7 +82063,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; 'class': 'mark dot' }); if (i > 0) return; - var lineSelection = _$d3_68.select(this.parentNode).selectAll('path.line').data([ 0 ]); + var lineSelection = _$d3_71.select(this.parentNode).selectAll('path.line').data([ 0 ]); lineSelection.enter().insert('path'); lineSelection.attr({ 'class': 'line', @@ -81242,7 +82096,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }; var angularRange = geometryConfig.angularScale.range(); var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180; - var arc = _$d3_68.svg.arc().startAngle(function(d) { + var arc = _$d3_71.svg.arc().startAngle(function(d) { return -triangleAngle / 2; }).endAngle(function(d) { return triangleAngle / 2; @@ -81252,7 +82106,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]); }); generator.arc = function(d, i, pI) { - _$d3_68.select(this).attr({ + _$d3_71.select(this).attr({ 'class': 'mark arc', d: arc, transform: function(d, i) { @@ -81280,7 +82134,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none'; } }; - var geometryLayer = _$d3_68.select(this).selectAll('g.layer').data(data); + var geometryLayer = _$d3_71.select(this).selectAll('g.layer').data(data); geometryLayer.enter().append('g').attr({ 'class': 'layer' }); @@ -81315,15 +82169,15 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; if (!arguments.length) return config; _x.forEach(function(d, i) { if (!config[i]) config[i] = {}; - __extendDeepAll_448(config[i], µ.PolyChart.defaultConfig()); - __extendDeepAll_448(config[i], d); + __extendDeepAll_510(config[i], µ.PolyChart.defaultConfig()); + __extendDeepAll_510(config[i], d); }); return this; }; exports.getColorScale = function() { return colorScale; }; - _$d3_68.rebind(exports, dispatch, 'on'); + _$d3_71.rebind(exports, dispatch, 'on'); return exports; }; @@ -81354,7 +82208,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; container: 'body', radialScale: null, angularScale: null, - colorScale: _$d3_68.scale.category20() + colorScale: _$d3_71.scale.category20() } }; return config; @@ -81415,24 +82269,24 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; µ.Legend = function module() { var config = µ.Legend.defaultConfig(); - var dispatch = _$d3_68.dispatch('hover'); + var dispatch = _$d3_71.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_448({}, legendConfig.elements[i]); + var element = __extendDeepAll_510({}, legendConfig.elements[i]); element.name = dB; element.color = [].concat(legendConfig.elements[i].color)[iB]; return element; }); }); - var data = _$d3_68.merge(flattenData); + var data = _$d3_71.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_68.select(container); + if (typeof container == 'string' || container.nodeName) container = _$d3_71.select(container); var colors = data.map(function(d, i) { return d.color; }); @@ -81450,14 +82304,14 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }); svgEnter.append('g').classed('legend-axis', true); svgEnter.append('g').classed('legend-marks', true); - var dataNumbered = _$d3_68.range(data.length); - var colorScale = _$d3_68.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); - var dataScale = _$d3_68.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]); + var dataNumbered = _$d3_71.range(data.length); + var colorScale = _$d3_71.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); + var dataScale = _$d3_71.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_68.svg.symbolTypes.indexOf(_type) != -1) return _$d3_68.svg.symbol().type(_type).size(squareSize)(); else return _$d3_68.svg.symbol().type('square').size(squareSize)(); + } else if (_$d3_71.svg.symbolTypes.indexOf(_type) != -1) return _$d3_71.svg.symbol().type(_type).size(squareSize)(); else return _$d3_71.svg.symbol().type('square').size(squareSize)(); }; if (isContinuous) { var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({ @@ -81499,7 +82353,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; }); legendElement.exit().remove(); } - var legendAxis = _$d3_68.svg.axis().scale(dataScale).orient('right'); + var legendAxis = _$d3_71.svg.axis().scale(dataScale).orient('right'); var axis = svg.select('g.legend-axis').attr({ transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')' }).call(legendAxis); @@ -81521,10 +82375,10 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; } exports.config = function(_x) { if (!arguments.length) return config; - __extendDeepAll_448(config, _x); + __extendDeepAll_510(config, _x); return this; }; - _$d3_68.rebind(exports, dispatch, 'on'); + _$d3_71.rebind(exports, dispatch, 'on'); return exports; }; @@ -81584,7 +82438,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return exports; }; exports.text = function(_text) { - var l = _$d3_68.hsl(config.color).l; + var l = _$d3_71.hsl(config.color).l; var strokeColor = l >= .5 ? '#aaa' : 'white'; var fillColor = l >= .5 ? 'black' : 'white'; var text = _text || ''; @@ -81636,7 +82490,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; return exports; }; exports.config = function(_x) { - __extendDeepAll_448(config, _x); + __extendDeepAll_510(config, _x); return exports; }; return exports; @@ -81652,7 +82506,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; var outputConfig = {}; if (_inputConfig.data) { outputConfig.data = _inputConfig.data.map(function(d, i) { - var r = __extendDeepAll_448({}, d); + var r = __extendDeepAll_510({}, d); var toTranslate = [ [ r, [ 'marker', 'color' ], [ 'color' ] ], [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ], @@ -81706,7 +82560,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; } } if (_inputConfig.layout) { - var r = __extendDeepAll_448({}, _inputConfig.layout); + var r = __extendDeepAll_510({}, _inputConfig.layout); var toTranslate = [ [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ], [ r, [ 'showlegend' ], [ 'showLegend' ] ], @@ -81767,7 +82621,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; var source = [ 't', 'r', 'b', 'l', 'pad' ]; var target = [ 'top', 'right', 'bottom', 'left', 'pad' ]; var margin = {}; - _$d3_68.entries(r.margin).forEach(function(dB, iB) { + _$d3_71.entries(r.margin).forEach(function(dB, iB) { margin[target[source.indexOf(dB.key)]] = dB.value; }); r.margin = margin; @@ -81806,7 +82660,7 @@ var µ = _$micropolar_448 = { version: '0.2.2' }; // Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager // Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com -var _$UndoManager_450 = function UndoManager() { +var _$UndoManager_512 = function UndoManager() { var undoCommands = [], index = -1, isExecuting = false, @@ -81859,7 +82713,7 @@ var _$UndoManager_450 = function UndoManager() { }; }; -var _$micropolar_manager_449 = {}; +var _$micropolar_manager_511 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -81872,30 +82726,30 @@ var _$micropolar_manager_449 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$lib_363 = require('../../../lib'); */; -/* removed: var _$color_239 = require('../../../components/color'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$lib_425 = require('../../../lib'); */; +/* removed: var _$color_301 = require('../../../components/color'); */; -/* removed: var _$micropolar_448 = require('./micropolar'); */; -/* removed: var _$UndoManager_450 = require('./undo_manager'); */; -var __extendDeepAll_449 = _$lib_363.extendDeepAll; +/* removed: var _$micropolar_510 = require('./micropolar'); */; +/* removed: var _$UndoManager_512 = require('./undo_manager'); */; +var __extendDeepAll_511 = _$lib_425.extendDeepAll; -var manager = _$micropolar_manager_449 = {}; +var manager = _$micropolar_manager_511 = {}; manager.framework = function(_gd) { var config, previousConfigClone, plot, convertedInput, container; - var undoManager = new _$UndoManager_450(); + var undoManager = new _$UndoManager_512(); function exports(_inputConfig, _container) { if(_container) container = _container; - _$d3_68.select(_$d3_68.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); + _$d3_71.select(_$d3_71.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); config = (!config) ? _inputConfig : - __extendDeepAll_449(config, _inputConfig); + __extendDeepAll_511(config, _inputConfig); - if(!plot) plot = _$micropolar_448.Axis(); - convertedInput = _$micropolar_448.adapter.plotly().convert(config); + if(!plot) plot = _$micropolar_510.Axis(); + convertedInput = _$micropolar_510.adapter.plotly().convert(config); plot.config(convertedInput).render(container); _gd.data = config.data; _gd.layout = config.layout; @@ -81906,12 +82760,12 @@ manager.framework = function(_gd) { exports.svg = function() { return plot.svg(); }; exports.getConfig = function() { return config; }; exports.getLiveConfig = function() { - return _$micropolar_448.adapter.plotly().convert(plot.getLiveConfig(), true); + return _$micropolar_510.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_448.util.cloneJson(config); + var configClone = _$micropolar_510.util.cloneJson(config); (function(_configClone, _previousConfigClone) { undoManager.add({ undo: function() { @@ -81922,7 +82776,7 @@ manager.framework = function(_gd) { } }); })(configClone, previousConfigClone); - previousConfigClone = _$micropolar_448.util.cloneJson(configClone); + previousConfigClone = _$micropolar_510.util.cloneJson(configClone); }; exports.undo = function() { undoManager.undo(); }; exports.redo = function() { undoManager.redo(); }; @@ -81930,22 +82784,22 @@ manager.framework = function(_gd) { }; manager.fillLayout = function(_gd) { - var container = _$d3_68.select(_gd).selectAll('.plot-container'), + var container = _$d3_71.select(_gd).selectAll('.plot-container'), paperDiv = container.selectAll('.svg-container'), paper = _gd.framework && _gd.framework.svg && _gd.framework.svg(), dflts = { width: 800, height: 600, - paper_bgcolor: _$color_239.background, + paper_bgcolor: _$color_301.background, _container: container, _paperdiv: paperDiv, _paper: paper }; - _gd._fullLayout = __extendDeepAll_449(dflts, _gd.layout); + _gd._fullLayout = __extendDeepAll_511(dflts, _gd.layout); }; -var _$legacy_447 = {}; +var _$legacy_509 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -81956,11 +82810,11 @@ var _$legacy_447 = {}; 'use strict'; -var Polar = _$legacy_447 = _$micropolar_448; +var Polar = _$legacy_509 = _$micropolar_510; -Polar.manager = _$micropolar_manager_449; +Polar.manager = _$micropolar_manager_511; -var _$plot_api_396 = {}; +var _$plot_api_459 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -81973,37 +82827,33 @@ var _$plot_api_396 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$hasHover_125 = require('has-hover'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$hasHover_182 = require('has-hover'); */; -/* removed: var _$lib_363 = require('../lib'); */; -/* removed: var _$Events_353 = require('../lib/events'); */; -/* removed: var _$queue_377 = require('../lib/queue'); */; +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$Events_415 = require('../lib/events'); */; +/* removed: var _$queue_440 = require('../lib/queue'); */; -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$plot_schema_398 = require('./plot_schema'); */; -/* removed: var _$plots_444 = require('../plots/plots'); */; -/* removed: var _$legacy_447 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_416 = require('../plots/cartesian/graph_interact'); */; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$plot_schema_461 = require('./plot_schema'); */; +/* removed: var _$plots_506 = require('../plots/plots'); */; +/* removed: var _$legacy_509 = require('../plots/polar/legacy'); */; -/* removed: var _$axes_407 = require('../plots/cartesian/axes'); */; -/* removed: var _$drawing_264 = require('../components/drawing'); */; -/* removed: var _$color_239 = require('../components/color'); */; -/* removed: var _$xmlns_namespaces_345 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_386 = require('../lib/svg_text_utils'); */; +/* removed: var _$axes_470 = require('../plots/cartesian/axes'); */; +/* removed: var _$drawing_326 = require('../components/drawing'); */; +/* removed: var _$color_301 = require('../components/color'); */; +var initInteractions = _$graph_interact_479.initInteractions; +/* removed: var _$xmlns_namespaces_406 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$svg_text_utils_449 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_397 = require('./plot_config'); */; -/* removed: var _$manage_arrays_395 = require('./manage_arrays'); */; -/* removed: var _$helpers_393 = require('./helpers'); */; -/* removed: var _$subroutines_399 = require('./subroutines'); */; -/* removed: var _$edit_types_392 = require('./edit_types'); */; +/* removed: var _$plot_config_460 = require('./plot_config'); */; +/* removed: var _$manage_arrays_458 = require('./manage_arrays'); */; +/* removed: var _$helpers_456 = require('./helpers'); */; +/* removed: var _$subroutines_462 = require('./subroutines'); */; +/* removed: var _$edit_types_455 = require('./edit_types'); */; -/* removed: var _$constants_412 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_414 = require('../plots/cartesian/constraints'); */; -var __enforceAxisConstraints_396 = _$constraints_414.enforce; -var __cleanAxisConstraints_396 = _$constraints_414.clean; -var __doAutoRange_396 = _$autorange_406.doAutoRange; +var AX_NAME_PATTERN = _$constants_475.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -82029,15 +82879,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_396.plot = function(gd, data, layout, config) { +_$plot_api_459.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_363.getGraphDiv(gd); + gd = _$lib_425.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_353.init(gd); + _$Events_415.init(gd); - if(_$lib_363.isPlainObject(data)) { + if(_$lib_425.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -82045,19 +82895,19 @@ _$plot_api_396.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_353.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_415.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_363.isPlotDiv(gd)) { - _$lib_363.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_425.isPlotDiv(gd)) { + _$lib_425.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_396.addFrames(gd, frames); + return _$plot_api_459.addFrames(gd, frames); } } @@ -82069,12 +82919,15 @@ _$plot_api_396.plot = function(gd, data, layout, config) { // hook class for plots main container (in case of plotly.js // this won't be #embedded-graph or .js-tab-contents) - _$d3_68.select(gd).classed('js-plotly-plot', true); + _$d3_71.select(gd).classed('js-plotly-plot', true); // off-screen getBoundingClientRect testing space, // in #js-plotly-tester (and stored as Drawing.tester) // so we can share cached text across tabs - _$drawing_264.makeTester(); + _$drawing_326.makeTester(); + + // clear stashed base url + delete _$drawing_326.baseUrl; // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then @@ -82087,7 +82940,7 @@ _$plot_api_396.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_393.cleanData(data, gd.data); + _$helpers_456.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -82098,7 +82951,7 @@ _$plot_api_396.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_393.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_456.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -82112,7 +82965,7 @@ _$plot_api_396.plot = function(gd, data, layout, config) { gd._replotPending = false; } - _$plots_444.supplyDefaults(gd); + _$plots_506.supplyDefaults(gd); var fullLayout = gd._fullLayout; @@ -82120,7 +82973,7 @@ _$plot_api_396.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_363.log('Legacy polar charts are deprecated!'); + _$lib_425.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -82138,17 +82991,17 @@ _$plot_api_396.plot = function(gd, data, layout, config) { } // clear gradient defs on each .plot call, because we know we'll loop through all traces - _$drawing_264.initGradients(gd); + _$drawing_326.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_407.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_470.saveShowSpikeInitial(gd); // prepare the data and find the autorange // generate calcdata, if we need to // to force redoing calcdata, just delete it before calling Plotly.plot var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length; - if(recalc) _$plots_444.doCalcdata(gd); + if(recalc) _$plots_506.doCalcdata(gd); // in case it has changed, attach fullData traces to calcdata for(var i = 0; i < gd.calcdata.length; i++) { @@ -82208,9 +83061,7 @@ _$plot_api_396.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_363.syncOrAsync([ - _$subroutines_399.layoutStyles - ], gd); + return _$plots_506.previousPromises(gd); } // draw anything that can affect margins. @@ -82218,31 +83069,31 @@ _$plot_api_396.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_451.getComponentMethod('legend', 'draw')(gd); - _$registry_451.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_451.getComponentMethod('sliders', 'draw')(gd); - _$registry_451.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_514.getComponentMethod('legend', 'draw')(gd); + _$registry_514.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_514.getComponentMethod('sliders', 'draw')(gd); + _$registry_514.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; trace = cd[0].trace; if(trace.visible !== true || !trace._module.colorbar) { - _$plots_444.autoMargin(gd, 'cb' + trace.uid); + _$plots_506.autoMargin(gd, 'cb' + trace.uid); } else trace._module.colorbar(gd, cd); } - _$plots_444.doAutoMargin(gd); - return _$plots_444.previousPromises(gd); + _$plots_506.doAutoMargin(gd); + return _$plots_506.previousPromises(gd); } // in case the margins changed, draw margin pushers again function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_363.syncOrAsync([ + return _$lib_425.syncOrAsync([ marginPushers, - _$subroutines_399.layoutStyles + _$subroutines_462.layoutStyles ], gd); } @@ -82263,7 +83114,7 @@ _$plot_api_396.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_363.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_425.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -82277,136 +83128,55 @@ _$plot_api_396.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_451.getComponentMethod('errorbars', 'calc')(gd); + _$registry_514.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_363.syncOrAsync([ - _$registry_451.getComponentMethod('shapes', 'calcAutorange'), - _$registry_451.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_425.syncOrAsync([ + _$registry_514.getComponentMethod('shapes', 'calcAutorange'), + _$registry_514.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_451.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_514.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_407.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - __cleanAxisConstraints_396(gd, ax); - - __doAutoRange_396(ax); - } - - __enforceAxisConstraints_396(gd); + _$subroutines_462.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_407.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_470.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_407.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_451.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_444.style(gd); - - // show annotations and shapes - _$registry_451.getComponentMethod('shapes', 'draw')(gd); - _$registry_451.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_444.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_444.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_451.getComponentMethod('shapes', 'draw')(gd); - _$registry_451.getComponentMethod('images', 'draw')(gd); - _$registry_451.getComponentMethod('annotations', 'draw')(gd); - _$registry_451.getComponentMethod('legend', 'draw')(gd); - _$registry_451.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_451.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_451.getComponentMethod('sliders', 'draw')(gd); - _$registry_451.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_470.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ - _$plots_444.previousPromises, + _$plots_506.previousPromises, addFrames, drawFramework, marginPushers, marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_399.layoutStyles); + seq.push(_$subroutines_462.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_416, - _$plots_444.rehover, - _$plots_444.previousPromises + _$subroutines_462.drawData, + _$subroutines_462.finalDraw, + initInteractions, + _$plots_506.addLinks, + _$plots_506.rehover, + _$plots_506.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_363.syncOrAsync(seq, gd); + var plotDone = _$lib_425.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -82415,25 +83185,25 @@ _$plot_api_396.plot = function(gd, data, layout, config) { }); }; -_$plot_api_396.setPlotConfig = function setPlotConfig(obj) { - return _$lib_363.extendFlat(_$plot_config_397, obj); +_$plot_api_459.setPlotConfig = function setPlotConfig(obj) { + return _$lib_425.extendFlat(_$plot_config_460, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_363.error(e); + _$lib_425.error(e); } } function opaqueSetBackground(gd, bgColor) { - var blend = _$color_239.combine(bgColor, 'white'); + var blend = _$color_301.combine(bgColor, 'white'); setBackground(gd, blend); } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_363.extendDeep({}, _$plot_config_397); + if(!gd._context) gd._context = _$lib_425.extendDeep({}, _$plot_config_460); var context = gd._context; var i, keys, key; @@ -82494,7 +83264,7 @@ function setPlotContext(gd, config) { } // make sure hover-only devices have mode bar visible - if(context.displayModeBar === 'hover' && !_$hasHover_125) { + if(context.displayModeBar === 'hover' && !_$hasHover_182) { context.displayModeBar = true; } @@ -82506,7 +83276,7 @@ function setPlotContext(gd, config) { function plotPolar(gd, data, layout) { // build or reuse the container skeleton - var plotContainer = _$d3_68.select(gd).selectAll('.plot-container') + var plotContainer = _$d3_71.select(gd).selectAll('.plot-container') .data([0]); plotContainer.enter() .insert('div', ':first-child') @@ -82523,7 +83293,7 @@ function plotPolar(gd, data, layout) { // fulfill gd requirements if(data) gd.data = data; if(layout) gd.layout = layout; - _$legacy_447.manager.fillLayout(gd); + _$legacy_509.manager.fillLayout(gd); // resize canvas paperDiv.style({ @@ -82532,7 +83302,7 @@ function plotPolar(gd, data, layout) { }); // instantiate framework - gd.framework = _$legacy_447.manager.framework(gd); + gd.framework = _$legacy_509.manager.framework(gd); // plot gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node()); @@ -82549,7 +83319,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_386.convertToTspans, gd); + this.call(_$svg_text_utils_449.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -82558,7 +83328,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_363._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_425._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -82567,17 +83337,17 @@ function plotPolar(gd, data, layout) { .text(placeholderText) .style({opacity: opacity}) .on('mouseover.opacity', function() { - _$d3_68.select(this).transition().duration(100) + _$d3_71.select(this).transition().duration(100) .style('opacity', 1); }) .on('mouseout.opacity', function() { - _$d3_68.select(this).transition().duration(1000) + _$d3_71.select(this).transition().duration(1000) .style('opacity', 0); }); } var setContenteditable = function() { - this.call(_$svg_text_utils_386.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_449.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -82593,24 +83363,24 @@ function plotPolar(gd, data, layout) { } gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor); - _$plots_444.addLinks(gd); + _$plots_506.addLinks(gd); return Promise.resolve(); } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_396.redraw = function(gd) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.redraw = function(gd) { + gd = _$lib_425.getGraphDiv(gd); - if(!_$lib_363.isPlotDiv(gd)) { + if(!_$lib_425.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_393.cleanData(gd.data, gd.data); - _$helpers_393.cleanLayout(gd.layout); + _$helpers_456.cleanData(gd.data, gd.data); + _$helpers_456.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_396.plot(gd).then(function() { + return _$plot_api_459.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -82624,14 +83394,14 @@ _$plot_api_396.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_396.newPlot = function(gd, data, layout, config) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.newPlot = function(gd, data, layout, config) { + gd = _$lib_425.getGraphDiv(gd); // remove gl contexts - _$plots_444.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_506.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); - _$plots_444.purge(gd); - return _$plot_api_396.plot(gd, data, layout, config); + _$plots_506.purge(gd); + return _$plot_api_459.plot(gd, data, layout, config); }; /** @@ -82784,12 +83554,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_363.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_425.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_363.isPlainObject(update)) { + if(!_$lib_425.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -82832,7 +83602,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_363.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_425.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -82852,7 +83622,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_363.nestedProperty(trace, key); + prop = _$lib_425.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -82861,10 +83631,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_363.isArrayOrTypedArray(insert)) { + if(!_$lib_425.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_363.isArrayOrTypedArray(target)) { + if(!_$lib_425.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -82878,7 +83648,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints; // could have chosen null here, -1 just tells us to not take a window - if(!_$fastIsnumeric_78(maxp)) maxp = -1; + if(!_$fastIsnumeric_135(maxp)) maxp = -1; /* * Wrap the nestedProperty in an object containing required data @@ -82959,13 +83729,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_396.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_425.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_363.isTypedArray(target)) { + if(_$lib_425.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -83010,20 +83780,20 @@ _$plot_api_396.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_396.redraw(gd); + var promise = _$plot_api_459.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_377.add(gd, _$plot_api_396.prependTraces, undoArgs, extendTraces, arguments); + _$queue_440.add(gd, _$plot_api_459.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_396.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_425.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_363.isTypedArray(target)) { + if(_$lib_425.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -83067,9 +83837,9 @@ _$plot_api_396.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_396.redraw(gd); + var promise = _$plot_api_459.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_377.add(gd, _$plot_api_396.extendTraces, undoArgs, prependTraces, arguments); + _$queue_440.add(gd, _$plot_api_459.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -83083,11 +83853,11 @@ _$plot_api_396.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_396.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_425.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_396.deleteTraces, + undoFunc = _$plot_api_459.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -83104,10 +83874,10 @@ _$plot_api_396.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_363.extendFlat({}, trace); + return _$lib_425.extendFlat({}, trace); }); - _$helpers_393.cleanData(traces, gd.data); + _$helpers_456.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -83122,8 +83892,8 @@ _$plot_api_396.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_396.redraw(gd); - _$queue_377.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_459.redraw(gd); + _$queue_440.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -83146,10 +83916,10 @@ _$plot_api_396.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_377.startSequence(gd); - _$queue_377.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_396.moveTraces(gd, currentIndices, newIndices); - _$queue_377.stopSequence(gd); + _$queue_440.startSequence(gd); + _$queue_440.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_459.moveTraces(gd, currentIndices, newIndices); + _$queue_440.stopSequence(gd); return promise; }; @@ -83160,11 +83930,11 @@ _$plot_api_396.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_396.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_425.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_396.addTraces, + undoFunc = _$plot_api_459.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -83183,14 +83953,14 @@ _$plot_api_396.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_363.sorterDes); + indices.sort(_$lib_425.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_396.redraw(gd); - _$queue_377.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_459.redraw(gd); + _$queue_440.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -83226,8 +83996,8 @@ _$plot_api_396.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_396.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_425.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -83287,8 +84057,8 @@ _$plot_api_396.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_396.redraw(gd); - _$queue_377.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_459.redraw(gd); + _$queue_440.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -83323,55 +84093,55 @@ _$plot_api_396.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_396.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_363.getGraphDiv(gd); - _$helpers_393.clearPromiseQueue(gd); +_$plot_api_459.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_425.getGraphDiv(gd); + _$helpers_456.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_363.isPlainObject(astr)) { + else if(_$lib_425.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_363.extendFlat({}, astr); + aobj = _$lib_425.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_363.warn('Restyle fail.', astr, val, _traces); + _$lib_425.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_393.coerceTraceIndices(gd, _traces); + var traces = _$helpers_456.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_393.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_456.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_396.plot); + seq.push(_$plot_api_459.plot); } else { - seq.push(_$plots_444.previousPromises); + seq.push(_$plots_506.previousPromises); - _$plots_444.supplyDefaults(gd); + _$plots_506.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_399.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_399.doColorBars); + if(flags.style) seq.push(_$subroutines_462.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_462.doColorBars); } - seq.push(_$plots_444.rehover); + seq.push(_$plots_506.rehover); - _$queue_377.add(gd, + _$queue_440.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_363.syncOrAsync(seq, gd); + var plotDone = _$lib_425.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -83394,7 +84164,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_392.traceFlags(); + var flags = _$edit_types_455.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -83407,7 +84177,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_407.id2name(axid); + var axName = _$axes_470.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -83426,13 +84196,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_393.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_456.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_363.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_425.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_363.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_425.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -83449,7 +84219,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_393.hasParent(aobj, ai)) { + if(_$helpers_456.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -83464,7 +84234,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_363.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_425.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -83480,17 +84250,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_363.nestedProperty(cont, ai); + param = _$lib_425.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_398.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_461.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_363.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_425.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -83530,19 +84300,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_363.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_363.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_363.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_425.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_425.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_425.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_363.nestedProperty(cont, 'marker.color') - .set(_$lib_363.nestedProperty(cont, 'marker.colors').get()); + _$lib_425.nestedProperty(cont, 'marker.color') + .set(_$lib_425.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_451.traceIs(cont, 'cartesian')) { - _$lib_363.nestedProperty(cont, 'marker.colors') - .set(_$lib_363.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_514.traceIs(cont, 'cartesian')) { + _$lib_425.nestedProperty(cont, 'marker.colors') + .set(_$lib_425.nestedProperty(cont, 'marker.color').get()); } } @@ -83571,23 +84341,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_393.swapXYData(cont); + _$helpers_456.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } - else if(_$plots_444.dataArrayContainers.indexOf(param.parts[0]) !== -1) { + else if(_$plots_506.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_393.manageArrayContainers(param, newVal, undoit); + _$helpers_456.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_363.isArrayOrTypedArray(newVal) || _$lib_363.isArrayOrTypedArray(oldVal)) + _$lib_425.isArrayOrTypedArray(newVal) || _$lib_425.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_392.update(flags, valObject); + else _$edit_types_455.update(flags, valObject); } else { /* @@ -83606,12 +84376,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_407.swap(gd, traces); + _$axes_470.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_363.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_425.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -83626,7 +84396,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_451.traceIs(trace, 'cartesian')) { + if(_$registry_514.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -83643,7 +84413,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_407.list(gd); + var axList = _$axes_470.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -83664,7 +84434,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_363.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_425.extendDeepNoArrays([], [redoit, traces]) }; } @@ -83688,9 +84458,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_396.relayout = function relayout(gd, astr, val) { - gd = _$lib_363.getGraphDiv(gd); - _$helpers_393.clearPromiseQueue(gd); +_$plot_api_459.relayout = function relayout(gd, astr, val) { + gd = _$lib_425.getGraphDiv(gd); + _$helpers_456.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -83699,50 +84469,74 @@ _$plot_api_396.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_363.isPlainObject(astr)) { - aobj = _$lib_363.extendFlat({}, astr); + } else if(_$lib_425.isPlainObject(astr)) { + aobj = _$lib_425.extendFlat({}, astr); } else { - _$lib_363.warn('Relayout fail.', astr, val); + _$lib_425.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_393.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_456.clearAxisAutomargins(gd); // fill in redraw sequence // even if we don't have anything left in aobj, // something may have happened within relayout that we // need to wait for - var seq = [_$plots_444.previousPromises]; + var seq = [_$plots_506.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_399.layoutReplot); + seq.push(_$subroutines_462.layoutReplot); } else if(Object.keys(aobj).length) { - _$plots_444.supplyDefaults(gd); + _$plots_506.supplyDefaults(gd); + + if(flags.legend) seq.push(_$subroutines_462.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_462.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_462.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_462.doTicksRelayout, + _$subroutines_462.drawData, + _$subroutines_462.finalDraw + ); + } - if(flags.legend) seq.push(_$subroutines_399.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_399.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_399.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_399.doModeBar); - if(flags.camera) seq.push(_$subroutines_399.doCamera); + if(flags.ticks) seq.push(_$subroutines_462.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_462.doModeBar); + if(flags.camera) seq.push(_$subroutines_462.doCamera); } - seq.push(_$plots_444.rehover); + seq.push(_$plots_506.rehover); - _$queue_377.add(gd, + _$queue_440.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_363.syncOrAsync(seq, gd); + var plotDone = _$lib_425.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -83755,7 +84549,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_407.list(gd), + axes = _$axes_470.list(gd), arrayEdits = {}, arrayStr, i, @@ -83778,7 +84572,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_392.layoutFlags(); + var flags = _$edit_types_455.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -83797,9 +84591,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_393.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_456.hasParent(aobj, attr)) return; - var p = _$lib_363.nestedProperty(layout, attr); + var p = _$lib_425.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -83813,18 +84607,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_407.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_470.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_393.hasParent(aobj, ai)) { + if(_$helpers_456.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_363.nestedProperty(layout, ai); + var p = _$lib_425.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -83836,8 +84630,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_363.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_363.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_425.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_425.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -83848,11 +84642,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_398.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_461.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_363.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_425.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -83866,12 +84660,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_363.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_425.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_363.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_363.nestedProperty(fullLayout, ptrunk).get(); + _$lib_425.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_425.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -83879,7 +84673,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_363.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_425.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -83939,8 +84733,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_451.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_451.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_514.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_514.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -83948,18 +84742,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_363.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_425.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_412.AX_NAME_PATTERN)) { - var fullProp = _$lib_363.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_425.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_451.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_451.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_514.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_514.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -83968,12 +84762,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_395.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_458.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_363.nestedProperty(layout, arrayStr); + var componentArray = _$lib_425.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -83983,28 +84777,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_392.update(flags, updateValObject); + else _$edit_types_455.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_395.isAddVal(vi)) { + if(_$manage_arrays_458.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_395.isRemoveVal(vi)) { + else if(_$manage_arrays_458.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_363.warn('unrecognized full object value', aobj); + else _$lib_425.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_392.update(flags, updateValObject); - + else { + _$edit_types_455.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -84033,7 +84828,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_392.update(flags, valObject); + else if(valObject) _$edit_types_455.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -84042,8 +84837,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_395.applyContainerArrayChanges(gd, - _$lib_363.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_458.applyContainerArrayChanges(gd, + _$lib_425.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -84061,7 +84856,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_407.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_470.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -84085,7 +84880,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_363.extendDeep({}, redoit) + eventData: _$lib_425.extendDeep({}, redoit) }; } @@ -84100,16 +84895,16 @@ function updateAutosize(gd) { var oldHeight = fullLayout.height; // calculate autosizing - if(gd.layout.autosize) _$plots_444.plotAutoSize(gd, gd.layout, fullLayout); + if(gd.layout.autosize) _$plots_506.plotAutoSize(gd, gd.layout, fullLayout); return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight); } // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_363.isPlainObject(obj)) return false; + if(!_$lib_425.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_407.getFromId(gd, axRef); + ax = _$axes_470.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -84119,7 +84914,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_407.getFromId(gd, axLetter); + ax = _$axes_470.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -84139,32 +84934,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_396.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_363.getGraphDiv(gd); - _$helpers_393.clearPromiseQueue(gd); +_$plot_api_459.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_425.getGraphDiv(gd); + _$helpers_456.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_363.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_363.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_425.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_425.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_393.coerceTraceIndices(gd, _traces); + var traces = _$helpers_456.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_363.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_425.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_363.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_425.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_393.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_393.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_456.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_456.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -84178,35 +84973,43 @@ _$plot_api_396.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_396.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_459.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_396.plot); + seq.push(_$plot_api_459.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_399.layoutReplot); + seq.push(_$subroutines_462.layoutReplot); } else { - seq.push(_$plots_444.previousPromises); - _$plots_444.supplyDefaults(gd); - - if(restyleFlags.style) seq.push(_$subroutines_399.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_399.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_399.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_399.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_399.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_399.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_399.doCamera); + seq.push(_$plots_506.previousPromises); + _$plots_506.supplyDefaults(gd); + + if(restyleFlags.style) seq.push(_$subroutines_462.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_462.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_462.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_462.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_462.doAutoRangeAndConstraints, + _$subroutines_462.doTicksRelayout, + _$subroutines_462.drawData, + _$subroutines_462.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_462.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_462.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_462.doCamera); } - seq.push(_$plots_444.rehover); + seq.push(_$plots_506.rehover); - _$queue_377.add(gd, + _$queue_440.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_363.syncOrAsync(seq, gd); + var plotDone = _$lib_425.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -84242,23 +85045,23 @@ _$plot_api_396.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_396.react = function(gd, data, layout, config) { +_$plot_api_459.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_396.addFrames(gd, frames); } + function addFrames() { return _$plot_api_459.addFrames(gd, frames); } - gd = _$lib_363.getGraphDiv(gd); + gd = _$lib_425.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_363.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_396.newPlot(gd, data, layout, config); + if(!_$lib_425.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_459.newPlot(gd, data, layout, config); } else { - if(_$lib_363.isPlainObject(data)) { + if(_$lib_425.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -84270,18 +85073,18 @@ _$plot_api_396.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_363.extendDeep({}, gd._context); + var oldConfig = _$lib_425.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_393.cleanData(gd.data, []); + _$helpers_456.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_393.cleanLayout(gd.layout); + _$helpers_456.cleanLayout(gd.layout); - _$plots_444.supplyDefaults(gd); + _$plots_506.supplyDefaults(gd); var newFullData = gd._fullData; var newFullLayout = gd._fullLayout; @@ -84303,7 +85106,7 @@ _$plot_api_396.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_393.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_456.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -84313,27 +85116,27 @@ _$plot_api_396.react = function(gd, data, layout, config) { if(frames) { gd._transitionData = {}; - _$plots_444.createTransitionData(gd); + _$plots_506.createTransitionData(gd); seq.push(addFrames); } if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_396.plot); + seq.push(_$plot_api_459.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_451.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_363.noop) { + var drawOne = _$registry_514.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_425.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_451.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_363.noop) { + var draw = _$registry_514.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_425.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -84341,19 +85144,27 @@ _$plot_api_396.react = function(gd, data, layout, config) { } } - seq.push(_$plots_444.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_399.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_399.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_399.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_399.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_399.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_399.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_399.doCamera); + seq.push(_$plots_506.previousPromises); + if(restyleFlags.style) seq.push(_$subroutines_462.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_462.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_462.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_462.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_462.doAutoRangeAndConstraints, + _$subroutines_462.doTicksRelayout, + _$subroutines_462.drawData, + _$subroutines_462.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_462.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_462.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_462.doCamera); } - seq.push(_$plots_444.rehover); + seq.push(_$plots_506.rehover); - plotDone = _$lib_363.syncOrAsync(seq, gd); + plotDone = _$lib_425.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -84376,12 +85187,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_392.traceFlags(); + var flags = _$edit_types_455.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_398.getTraceValObject(trace, parts); + return _$plot_schema_461.getTraceValObject(trace, parts); } var diffOpts = { @@ -84391,11 +85202,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_407.getFromId(gd, trace.xaxis).autorange || - _$axes_407.getFromId(gd, trace.yaxis).autorange + _$axes_470.getFromId(gd, trace.xaxis).autorange || + _$axes_470.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -84408,11 +85225,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_392.layoutFlags(); + var flags = _$edit_types_455.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_398.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_461.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -84451,10 +85268,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_363.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_425.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_392.update(flags, valObject); + _$edit_types_455.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -84534,7 +85351,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_363.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_425.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -84546,7 +85363,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_363.isPlainObject(oldVal)) { + else if(!valType && _$lib_425.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -84600,7 +85417,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_363.isPlainObject(oldVal) && _$lib_363.isPlainObject(newVal)) { + if(_$lib_425.isPlainObject(oldVal) && _$lib_425.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -84611,7 +85428,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_363.isPlainObject(oldVal[i]) && _$lib_363.isPlainObject(newVal[i])) { + if(_$lib_425.isPlainObject(oldVal[i]) && _$lib_425.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -84656,10 +85473,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_425.getGraphDiv(gd); - if(!_$lib_363.isPlotDiv(gd)) { + if(!_$lib_425.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -84675,7 +85492,7 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts trans._frameQueue = []; } - animationOpts = _$plots_444.supplyAnimationDefaults(animationOpts); + animationOpts = _$plots_506.supplyAnimationDefaults(animationOpts); var transitionOpts = animationOpts.transition; var frameOpts = animationOpts.frame; @@ -84749,7 +85566,7 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts if(frameList[i].type === 'byname') { // If it's a named frame, compute it: - computedFrame = _$plots_444.computeFrame(gd, frameList[i].name); + computedFrame = _$plots_506.computeFrame(gd, frameList[i].name); } else { // Otherwise we must have been given a simple object, so treat // the input itself as the computed frame. @@ -84830,10 +85647,10 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts // This is simply called and it's left to .transition to decide how to manage // interrupting current transitions. That means we don't need to worry about // how it resolves or what happens after this: - _$plots_444.transition(gd, + _$plots_506.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_393.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_456.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -84903,13 +85720,13 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_363.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_425.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_363.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_425.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -84938,10 +85755,10 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_363.isPlainObject(frameOrName)) { + } else if(_$lib_425.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_363.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_425.extendFlat({}, frameOrName)) }); } } @@ -84951,7 +85768,7 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_363.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_425.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -85020,14 +85837,14 @@ _$plot_api_396.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_396.addFrames = function(gd, frameList, indices) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.addFrames = function(gd, frameList, indices) { + gd = _$lib_425.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_363.isPlotDiv(gd)) { + if(!_$lib_425.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -85054,7 +85871,7 @@ _$plot_api_396.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_363.isPlainObject(frameList[i])) continue; + if(!_$lib_425.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -85066,14 +85883,14 @@ _$plot_api_396.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_363.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_425.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_363.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_425.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -85082,7 +85899,7 @@ _$plot_api_396.addFrames = function(gd, frameList, indices) { _frameHashLocal[lookupName] = {name: lookupName}; insertions.push({ - frame: _$plots_444.supplyFrameDefaults(frameList[i]), + frame: _$plots_506.supplyFrameDefaults(frameList[i]), index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i }); } @@ -85102,7 +85919,7 @@ _$plot_api_396.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_363.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_425.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -85130,14 +85947,14 @@ _$plot_api_396.addFrames = function(gd, frameList, indices) { } } - var undoFunc = _$plots_444.modifyFrames, - redoFunc = _$plots_444.modifyFrames, + var undoFunc = _$plots_506.modifyFrames, + redoFunc = _$plots_506.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_377) _$queue_377.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_440) _$queue_440.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return _$plots_444.modifyFrames(gd, ops); + return _$plots_506.modifyFrames(gd, ops); }; /** @@ -85149,10 +85966,10 @@ _$plot_api_396.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_396.deleteFrames = function(gd, frameList) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.deleteFrames = function(gd, frameList) { + gd = _$lib_425.getGraphDiv(gd); - if(!_$lib_363.isPlotDiv(gd)) { + if(!_$lib_425.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -85177,14 +85994,14 @@ _$plot_api_396.deleteFrames = function(gd, frameList) { revops.unshift({type: 'insert', index: idx, value: _frames[idx]}); } - var undoFunc = _$plots_444.modifyFrames, - redoFunc = _$plots_444.modifyFrames, + var undoFunc = _$plots_506.modifyFrames, + redoFunc = _$plots_506.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_377) _$queue_377.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_440) _$queue_440.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return _$plots_444.modifyFrames(gd, ops); + return _$plots_506.modifyFrames(gd, ops); }; /** @@ -85193,20 +86010,21 @@ _$plot_api_396.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_396.purge = function purge(gd) { - gd = _$lib_363.getGraphDiv(gd); +_$plot_api_459.purge = function purge(gd) { + gd = _$lib_425.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_444.cleanPlot([], {}, fullData, fullLayout); + _$plots_506.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties - _$plots_444.purge(gd); + _$plots_506.purge(gd); // purge event emitter methods - _$Events_353.purge(gd); + _$Events_415.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -85221,7 +86039,7 @@ _$plot_api_396.purge = function purge(gd) { // makePlotFramework: Create the plot container and axes // ------------------------------------------------------- function makePlotFramework(gd) { - var gd3 = _$d3_68.select(gd); + var gd3 = _$d3_71.select(gd); var fullLayout = gd._fullLayout; // Plot container @@ -85261,14 +86079,14 @@ function makePlotFramework(gd) { if(!fullLayout._uid) { var otherUids = []; - _$d3_68.selectAll('defs').each(function() { + _$d3_71.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_363.randstr(otherUids); + fullLayout._uid = _$lib_425.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') - .attr(_$xmlns_namespaces_345.svgAttrs); + .attr(_$xmlns_namespaces_406.svgAttrs); fullLayout._defs = fullLayout._paper.append('defs') .attr('id', 'defs-' + fullLayout._uid); @@ -85340,7 +86158,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_455 = {}; +var _$helpers_518 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -85352,7 +86170,7 @@ var _$helpers_455 = {}; 'use strict'; -_$helpers_455.getDelay = function(fullLayout) { +_$helpers_518.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -85362,7 +86180,7 @@ _$helpers_455.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_455.getRedrawFunc = function(gd) { +_$helpers_518.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -85387,11 +86205,11 @@ _$helpers_455.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_363 = require('../lib'); */; -var __EventEmitter_457 = _$EventEmitter_77.EventEmitter; +/* removed: var _$lib_425 = require('../lib'); */; +var __EventEmitter_520 = _$EventEmitter_134.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_457(); + var ev = opts.emitter || new __EventEmitter_520(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -85399,7 +86217,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_363.isIE() && format !== 'svg') { + if(_$lib_425.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -85490,7 +86308,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_457 = svgToImg; +var _$svgToImg_520 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -85503,19 +86321,19 @@ var _$svgToImg_457 = svgToImg; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$d3_71 = require('d3'); */; -/* removed: var _$lib_363 = require('../lib'); */; -/* removed: var _$drawing_264 = require('../components/drawing'); */; -/* removed: var _$color_239 = require('../components/color'); */; +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$drawing_326 = require('../components/drawing'); */; +/* removed: var _$color_301 = require('../components/color'); */; -/* removed: var _$xmlns_namespaces_345 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$xmlns_namespaces_406 = require('../constants/xmlns_namespaces'); */; var DOUBLEQUOTE_REGEX = /"/g; var DUMMY_SUB = 'TOBESTRIPPED'; var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g'); function htmlEntityDecode(s) { - var hiddenDiv = _$d3_68.select('body').append('div').style({display: 'none'}).html(''); + var hiddenDiv = _$d3_71.select('body').append('div').style({display: 'none'}).html(''); var replaced = s.replace(/(&[^;]*;)/gi, function(d) { if(d === '<') { return '<'; } // special handling for brackets if(d === '&rt;') { return '>'; } @@ -85530,7 +86348,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_459 = function toSVG(gd, format, scale) { +var _$toSVG_522 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -85544,8 +86362,8 @@ var _$toSVG_459 = function toSVG(gd, format, scale) { // have to remove them, and providing the right namespaces in the svg to // begin with svg.insert('rect', ':first-child') - .call(_$drawing_264.setRect, 0, 0, width, height) - .call(_$color_239.fill, fullLayout.paper_bgcolor); + .call(_$drawing_326.setRect, 0, 0, width, height) + .call(_$color_301.fill, fullLayout.paper_bgcolor); // subplot-specific to-SVG methods // which notably add the contents of the gl-container @@ -85585,7 +86403,7 @@ var _$toSVG_459 = function toSVG(gd, format, scale) { svg.selectAll('text') .attr({'data-unformatted': null, 'data-math': null}) .each(function() { - var txt = _$d3_68.select(this); + var txt = _$d3_71.select(this); // hidden text is pre-formatting mathjax, the browser ignores it // but in a static plot it's useless and it can confuse batik @@ -85611,7 +86429,7 @@ var _$toSVG_459 = function toSVG(gd, format, scale) { }); svg.selectAll('.point,.scatterpts').each(function() { - var pt = _$d3_68.select(this); + var pt = _$d3_71.select(this); var fill = this.style.fill; // similar to font family styles above, @@ -85630,8 +86448,8 @@ var _$toSVG_459 = function toSVG(gd, format, scale) { // fix for IE namespacing quirk? // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie - svg.node().setAttributeNS(_$xmlns_namespaces_345.xmlns, 'xmlns', _$xmlns_namespaces_345.svg); - svg.node().setAttributeNS(_$xmlns_namespaces_345.xmlns, 'xmlns:xlink', _$xmlns_namespaces_345.xlink); + svg.node().setAttributeNS(_$xmlns_namespaces_406.xmlns, 'xmlns', _$xmlns_namespaces_406.svg); + svg.node().setAttributeNS(_$xmlns_namespaces_406.xmlns, 'xmlns:xlink', _$xmlns_namespaces_406.xlink); if(format === 'svg' && scale) { svg.attr('width', scale * width); @@ -85653,7 +86471,7 @@ var _$toSVG_459 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_363.isIE()) { + if(_$lib_425.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -85678,14 +86496,14 @@ var _$toSVG_459 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_396 = require('./plot_api'); */; -/* removed: var _$lib_363 = require('../lib'); */; +/* removed: var _$plot_api_459 = require('./plot_api'); */; +/* removed: var _$lib_425 = require('../lib'); */; -/* removed: var _$helpers_455 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_459 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_457 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_518 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_522 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_520 = require('../snapshot/svgtoimg'); */; -var __attrs_400 = { +var __attrs_463 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -85738,19 +86556,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_363.isPlainObject(gd)) { + if(_$lib_425.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_363.getGraphDiv(gd); - data = _$lib_363.extendDeep([], gd.data); - layout = _$lib_363.extendDeep({}, gd.layout); + gd = _$lib_425.getGraphDiv(gd); + data = _$lib_425.extendDeep([], gd.data); + layout = _$lib_425.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_363.validate(opts[attr], __attrs_400[attr]); + return !(attr in opts) || _$lib_425.validate(opts[attr], __attrs_463[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -85764,7 +86582,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_363.coerce(opts, fullOpts, __attrs_400, attr, dflt); + return _$lib_425.coerce(opts, fullOpts, __attrs_463, attr, dflt); } var format = coerce('format'); @@ -85781,31 +86599,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_363.extendFlat({}, layout); + var layoutImage = _$lib_425.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_363.extendFlat({}, config, { + var configImage = _$lib_425.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_455.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_518.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_455.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_518.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_459(clonedGd, format, scale); + var svg = _$toSVG_522(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_396.purge(clonedGd); + _$plot_api_459.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -85817,9 +86635,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_363.randstr(); + canvas.id = _$lib_425.randstr(); - _$svgToImg_457({ + _$svgToImg_520({ format: format, width: width, height: height, @@ -85846,7 +86664,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_396.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_459.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -85855,7 +86673,7 @@ function toImage(gd, opts) { }); } -var _$toImage_400 = toImage; +var _$toImage_463 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -85867,14 +86685,14 @@ var _$toImage_400 = toImage; 'use strict'; -/* removed: var _$lib_363 = require('../lib'); */; -/* removed: var _$plots_444 = require('../plots/plots'); */; -/* removed: var _$plot_schema_398 = require('./plot_schema'); */; -/* removed: var _$plot_config_397 = require('./plot_config'); */; +/* removed: var _$lib_425 = require('../lib'); */; +/* removed: var _$plots_506 = require('../plots/plots'); */; +/* removed: var _$plot_schema_461 = require('./plot_schema'); */; +/* removed: var _$plot_config_460 = require('./plot_config'); */; -var __isPlainObject_401 = _$lib_363.isPlainObject; -var __isArray_401 = Array.isArray; -var __isArrayOrTypedArray_401 = _$lib_363.isArrayOrTypedArray; +var __isPlainObject_464 = _$lib_425.isPlainObject; +var __isArray_464 = Array.isArray; +var __isArrayOrTypedArray_464 = _$lib_425.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -85897,15 +86715,15 @@ var __isArrayOrTypedArray_401 = _$lib_363.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_401 = function valiate(data, layout) { - var schema = _$plot_schema_398.get(); +var _$valiate_464 = function valiate(data, layout) { + var schema = _$plot_schema_461.get(); var errorList = []; - var gd = {_context: _$lib_363.extendFlat({}, _$plot_config_397)}; + var gd = {_context: _$lib_425.extendFlat({}, _$plot_config_460)}; var dataIn, layoutIn; - if(__isArray_401(data)) { - gd.data = _$lib_363.extendDeep([], data); + if(__isArray_464(data)) { + gd.data = _$lib_425.extendDeep([], data); dataIn = data; } else { @@ -85914,8 +86732,8 @@ var _$valiate_401 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_401(layout)) { - gd.layout = _$lib_363.extendDeep({}, layout); + if(__isPlainObject_464(layout)) { + gd.layout = _$lib_425.extendDeep({}, layout); layoutIn = layout; } else { @@ -85930,7 +86748,7 @@ var _$valiate_401 = function valiate(data, layout) { // gd.data and gd.layout after supplyDefaults as some attributes // in gd.data and gd.layout (still) get mutated during this step. - _$plots_444.supplyDefaults(gd); + _$plots_506.supplyDefaults(gd); var dataOut = gd._fullData, len = dataIn.length; @@ -85939,7 +86757,7 @@ var _$valiate_401 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_401(traceIn)) { + if(!__isPlainObject_464(traceIn)) { errorList.push(format('object', base)); continue; } @@ -85959,13 +86777,13 @@ var _$valiate_401 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_401(traceIn, traceOut, traceSchema, errorList, base); + __crawl_464(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_401(transformsIn)) { + if(!__isArray_464(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -85975,7 +86793,7 @@ var _$valiate_401 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_401(transformsIn[j])) { + if(!__isPlainObject_464(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -85990,7 +86808,7 @@ var _$valiate_401 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_401(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_464(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -85998,13 +86816,13 @@ var _$valiate_401 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_401(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_464(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_401(objIn, objOut, schema, list, base, path) { +function __crawl_464(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -86029,10 +86847,10 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_401(valIn) && __isPlainObject_401(valOut)) { - __crawl_401(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_464(valIn) && __isPlainObject_464(valOut)) { + __crawl_464(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_401(valIn)) { + else if(isInfoArray && __isArray_464(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -86042,7 +86860,7 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_401(valIn[n])) { + if(__isArray_464(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -86051,7 +86869,7 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_363.validate(valInPart, item)) { + if(!_$lib_425.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -86069,7 +86887,7 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_363.validate(valInPart, item)) { + if(!_$lib_425.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -86078,7 +86896,7 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_401(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_464(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -86092,9 +86910,9 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_401(valIn[_index]) && __isPlainObject_401(valOut[j])) { + if(__isPlainObject_464(valIn[_index]) && __isPlainObject_464(valOut[j])) { indexList.push(_index); - __crawl_401(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_464(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -86103,7 +86921,7 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_401(valIn[j])) { + if(!__isPlainObject_464(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -86111,16 +86929,16 @@ function __crawl_401(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_401(valIn) && __isPlainObject_401(valOut)) { + else if(!__isPlainObject_464(valIn) && __isPlainObject_464(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_401(valIn) && __isArrayOrTypedArray_401(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_464(valIn) && __isArrayOrTypedArray_464(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_363.validate(valIn, nestedSchema)) { + else if(!_$lib_425.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -86140,7 +86958,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_363.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_425.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -86172,7 +86990,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_401(valIn) ? 'container' : 'key'; + var target = __isPlainObject_464(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -86198,7 +87016,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_401(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_464(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -86211,7 +87029,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_401(base)) { + if(__isArray_464(base)) { container = base[0]; trace = base[1]; } @@ -86224,7 +87042,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_363.log(msg); + _$lib_425.log(msg); return { code: code, @@ -86254,7 +87072,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_363.counterRegex('([a-z]+)'); +var idRegex = _$lib_425.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -86266,7 +87084,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_401(path)) return String(path); + if(!__isArray_464(path)) return String(path); var astr = ''; @@ -86355,7 +87173,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_454 = fileSaver; +var _$fileSaver_517 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -86368,9 +87186,9 @@ var _$fileSaver_454 = fileSaver; 'use strict'; -/* removed: var _$toImage_400 = require('../plot_api/to_image'); */; -/* removed: var _$lib_363 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_454 = require('./filesaver'); */; +/* removed: var _$toImage_463 = require('../plot_api/to_image'); */; +/* removed: var _$lib_425 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_517 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -86398,19 +87216,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_363.isIE() && opts.format !== 'svg') { + if(_$lib_425.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_400(gd, opts); + var promise = _$toImage_463(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_454(result, filename); + return _$fileSaver_517(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -86420,9 +87238,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_453 = downloadImage; +var _$downloadImage_516 = downloadImage; -var _$plot_api_394 = {}; +var _$plot_api_457 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -86433,29 +87251,29 @@ var _$plot_api_394 = {}; 'use strict'; -/* removed: var _$plot_api_396 = require('./plot_api'); */; - -_$plot_api_394.plot = _$plot_api_396.plot; -_$plot_api_394.newPlot = _$plot_api_396.newPlot; -_$plot_api_394.restyle = _$plot_api_396.restyle; -_$plot_api_394.relayout = _$plot_api_396.relayout; -_$plot_api_394.redraw = _$plot_api_396.redraw; -_$plot_api_394.update = _$plot_api_396.update; -_$plot_api_394.react = _$plot_api_396.react; -_$plot_api_394.extendTraces = _$plot_api_396.extendTraces; -_$plot_api_394.prependTraces = _$plot_api_396.prependTraces; -_$plot_api_394.addTraces = _$plot_api_396.addTraces; -_$plot_api_394.deleteTraces = _$plot_api_396.deleteTraces; -_$plot_api_394.moveTraces = _$plot_api_396.moveTraces; -_$plot_api_394.purge = _$plot_api_396.purge; -_$plot_api_394.addFrames = _$plot_api_396.addFrames; -_$plot_api_394.deleteFrames = _$plot_api_396.deleteFrames; -_$plot_api_394.animate = _$plot_api_396.animate; -_$plot_api_394.setPlotConfig = _$plot_api_396.setPlotConfig; - -_$plot_api_394.toImage = _$toImage_400; -_$plot_api_394.validate = _$valiate_401; -_$plot_api_394.downloadImage = _$downloadImage_453; +/* removed: var _$plot_api_459 = require('./plot_api'); */; + +_$plot_api_457.plot = _$plot_api_459.plot; +_$plot_api_457.newPlot = _$plot_api_459.newPlot; +_$plot_api_457.restyle = _$plot_api_459.restyle; +_$plot_api_457.relayout = _$plot_api_459.relayout; +_$plot_api_457.redraw = _$plot_api_459.redraw; +_$plot_api_457.update = _$plot_api_459.update; +_$plot_api_457.react = _$plot_api_459.react; +_$plot_api_457.extendTraces = _$plot_api_459.extendTraces; +_$plot_api_457.prependTraces = _$plot_api_459.prependTraces; +_$plot_api_457.addTraces = _$plot_api_459.addTraces; +_$plot_api_457.deleteTraces = _$plot_api_459.deleteTraces; +_$plot_api_457.moveTraces = _$plot_api_459.moveTraces; +_$plot_api_457.purge = _$plot_api_459.purge; +_$plot_api_457.addFrames = _$plot_api_459.addFrames; +_$plot_api_457.deleteFrames = _$plot_api_459.deleteFrames; +_$plot_api_457.animate = _$plot_api_459.animate; +_$plot_api_457.setPlotConfig = _$plot_api_459.setPlotConfig; + +_$plot_api_457.toImage = _$toImage_463; +_$plot_api_457.validate = _$valiate_464; +_$plot_api_457.downloadImage = _$downloadImage_516; /** * Copyright 2012-2018, Plotly, Inc. @@ -86468,10 +87286,10 @@ _$plot_api_394.downloadImage = _$downloadImage_453; 'use strict'; -/* removed: var _$lib_363 = require('../lib'); */; +/* removed: var _$lib_425 = require('../lib'); */; -var __extendFlat_452 = _$lib_363.extendFlat; -var extendDeep = _$lib_363.extendDeep; +var __extendFlat_515 = _$lib_425.extendFlat; +var extendDeep = _$lib_425.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -86516,7 +87334,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_452 = function clonePlot(graphObj, options) { +var _$clonePlot_515 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -86589,9 +87407,9 @@ var _$clonePlot_452 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_452(scene.xaxis, axesImageOverride); - __extendFlat_452(scene.yaxis, axesImageOverride); - __extendFlat_452(scene.zaxis, axesImageOverride); + __extendFlat_515(scene.xaxis, axesImageOverride); + __extendFlat_515(scene.yaxis, axesImageOverride); + __extendFlat_515(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -86640,27 +87458,27 @@ var _$clonePlot_452 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_458 = _$EventEmitter_77.EventEmitter; +var __EventEmitter_521 = _$EventEmitter_134.EventEmitter; -/* removed: var _$registry_451 = require('../registry'); */; -/* removed: var _$lib_363 = require('../lib'); */; +/* removed: var _$registry_514 = require('../registry'); */; +/* removed: var _$lib_425 = require('../lib'); */; -/* removed: var _$helpers_455 = require('./helpers'); */; -/* removed: var _$clonePlot_452 = require('./cloneplot'); */; -/* removed: var _$toSVG_459 = require('./tosvg'); */; -/* removed: var _$svgToImg_457 = require('./svgtoimg'); */; +/* removed: var _$helpers_518 = require('./helpers'); */; +/* removed: var _$clonePlot_515 = require('./cloneplot'); */; +/* removed: var _$toSVG_522 = require('./tosvg'); */; +/* removed: var _$svgToImg_520 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_458(gd, opts) { +function __toImage_521(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_458(); + var ev = new __EventEmitter_521(); - var clone = _$clonePlot_452(gd, {format: 'png'}); + var clone = _$clonePlot_515(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -86669,15 +87487,15 @@ function __toImage_458(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_455.getDelay(clonedGd._fullLayout); + var delay = _$helpers_518.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_459(clonedGd); + var svg = _$toSVG_522(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_363.randstr(); + canvas.id = _$lib_425.randstr(); - ev = _$svgToImg_457({ + ev = _$svgToImg_520({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -86693,9 +87511,9 @@ function __toImage_458(gd, opts) { }, delay); } - var redrawFunc = _$helpers_455.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_518.getRedrawFunc(clonedGd); - _$registry_451.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_514.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -86706,7 +87524,7 @@ function __toImage_458(gd, opts) { return ev; } -var _$toImage_458 = __toImage_458; +var _$toImage_521 = __toImage_521; /** * Copyright 2012-2018, Plotly, Inc. @@ -86719,19 +87537,19 @@ var _$toImage_458 = __toImage_458; 'use strict'; -/* removed: var _$helpers_455 = require('./helpers'); */; +/* removed: var _$helpers_518 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_455.getDelay, - getRedrawFunc: _$helpers_455.getRedrawFunc, - clone: _$clonePlot_452, - toSVG: _$toSVG_459, - svgToImg: _$svgToImg_457, - toImage: _$toImage_458, - downloadImage: _$downloadImage_453 + getDelay: _$helpers_518.getDelay, + getRedrawFunc: _$helpers_518.getRedrawFunc, + clone: _$clonePlot_515, + toSVG: _$toSVG_522, + svgToImg: _$svgToImg_520, + toImage: _$toImage_521, + downloadImage: _$downloadImage_516 }; -var _$Snapshot_456 = Snapshot; +var _$Snapshot_519 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -86744,42 +87562,42 @@ var _$Snapshot_456 = Snapshot; 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_511 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_575 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_363.mergeArray(trace.text, cd, 'tx'); - _$lib_363.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_363.mergeArray(trace.customdata, cd, 'data'); - _$lib_363.mergeArray(trace.textposition, cd, 'tp'); + _$lib_425.mergeArray(trace.text, cd, 'tx'); + _$lib_425.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_425.mergeArray(trace.customdata, cd, 'data'); + _$lib_425.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_363.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_363.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_363.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_425.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_425.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_425.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_363.mergeArray(marker.size, cd, 'ms'); - _$lib_363.mergeArray(marker.opacity, cd, 'mo'); - _$lib_363.mergeArray(marker.symbol, cd, 'mx'); - _$lib_363.mergeArray(marker.color, cd, 'mc'); + _$lib_425.mergeArray(marker.size, cd, 'ms'); + _$lib_425.mergeArray(marker.opacity, cd, 'mo'); + _$lib_425.mergeArray(marker.symbol, cd, 'mx'); + _$lib_425.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_363.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_363.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_425.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_425.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_363.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_363.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_425.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_425.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -86794,11 +87612,11 @@ var _$arraysToCalcdata_511 = function arraysToCalcdata(cd, trace) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; -var _$calcSelection_514 = function calcSelection(cd, trace) { - if(_$lib_363.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_363.tagSelected(cd, trace); +var _$calcSelection_578 = function calcSelection(cd, trace) { + if(_$lib_425.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_425.tagSelected(cd, trace); } }; @@ -86813,23 +87631,23 @@ var _$calcSelection_514 = function calcSelection(cd, trace) { 'use strict'; -/* removed: var _$hasColorscale_253 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_246 = require('../../components/colorscale/calc'); */; +/* removed: var _$hasColorscale_315 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_308 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_534 = require('./subtypes'); */; +/* removed: var _$subtypes_598 = require('./subtypes'); */; -var _$calcMarkerColorscale_517 = function calcMarkerColorscale(trace) { - if(_$subtypes_534.hasLines(trace) && _$hasColorscale_253(trace, 'line')) { - _$calc_246(trace, trace.line.color, 'line', 'c'); +var _$calcMarkerColorscale_581 = function calcMarkerColorscale(trace) { + if(_$subtypes_598.hasLines(trace) && _$hasColorscale_315(trace, 'line')) { + _$calc_308(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_534.hasMarkers(trace)) { - if(_$hasColorscale_253(trace, 'marker')) { - _$calc_246(trace, trace.marker.color, 'marker', 'c'); + if(_$subtypes_598.hasMarkers(trace)) { + if(_$hasColorscale_315(trace, 'marker')) { + _$calc_308(trace, trace.marker.color, 'marker', 'c'); } - if(_$hasColorscale_253(trace, 'marker.line')) { - _$calc_246(trace, trace.marker.line.color, 'marker.line', 'c'); + if(_$hasColorscale_315(trace, 'marker.line')) { + _$calc_308(trace, trace.marker.line.color, 'marker.line', 'c'); } } }; @@ -86844,20 +87662,20 @@ var _$calcMarkerColorscale_517 = function calcMarkerColorscale(trace) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_513 = _$lib_363.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_577 = _$lib_425.isArrayOrTypedArray; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -var __BADNUM_513 = _$numerical_343.BADNUM; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +var __BADNUM_577 = _$numerical_404.BADNUM; -/* removed: var _$subtypes_534 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_517 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_511 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_514 = require('./calc_selection'); */; +/* removed: var _$subtypes_598 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_581 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_575 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_578 = require('./calc_selection'); */; -function __calc_513(gd, trace) { - var xa = _$axes_407.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_407.getFromId(gd, trace.yaxis || 'y'); +function __calc_577(gd, trace) { + var xa = _$axes_470.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_470.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -86867,18 +87685,18 @@ function __calc_513(gd, trace) { calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); for(var i = 0; i < serieslen; i++) { - cd[i] = (_$fastIsnumeric_78(x[i]) && _$fastIsnumeric_78(y[i])) ? + cd[i] = (_$fastIsnumeric_135(x[i]) && _$fastIsnumeric_135(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_513, y: __BADNUM_513}; + {x: __BADNUM_577, y: __BADNUM_577}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_511(cd, trace); - _$calcMarkerColorscale_517(trace); - _$calcSelection_514(cd, trace); + _$arraysToCalcdata_575(cd, trace); + _$calcMarkerColorscale_581(trace); + _$calcSelection_578(cd, trace); gd.firstscatter = false; return cd; @@ -86911,9 +87729,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_534.hasMarkers(trace) && !_$subtypes_534.hasText(trace)) + (!_$subtypes_598.hasMarkers(trace) && !_$subtypes_598.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -86932,12 +87750,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_407.expand(xa, x, xOptions); - _$axes_407.expand(ya, y, yOptions); + _$axes_470.expand(xa, x, xOptions); + _$axes_470.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_534.hasMarkers(trace)) return; + if(!_$subtypes_598.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -86955,10 +87773,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_513(marker.size)) { + if(__isArrayOrTypedArray_577(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_407.setConvert(ax); + _$axes_470.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -86973,8 +87791,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_513 = { - calc: __calc_513, +var _$calc_577 = { + calc: __calc_577, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -86992,7 +87810,7 @@ var _$calc_513 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_515 = function cleanData(fullData) { +var _$cleanData_579 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -87028,15 +87846,15 @@ var _$cleanData_515 = function cleanData(fullData) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$colorscale_254 = require('../../components/colorscale'); */; -/* removed: var _$draw_243 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$colorscale_316 = require('../../components/colorscale'); */; +/* removed: var _$draw_305 = require('../../components/colorbar/draw'); */; -var _$colorbar_516 = function colorbar(gd, cd) { +var _$colorbar_580 = function colorbar(gd, cd) { var trace = cd[0].trace, marker = trace.marker, cbId = 'cb' + trace.uid; @@ -87046,7 +87864,7 @@ var _$colorbar_516 = function colorbar(gd, cd) { // TODO make Colorbar.draw support multiple colorbar per trace if((marker === undefined) || !marker.showscale) { - _$plots_444.autoMargin(gd, cbId); + _$plots_506.autoMargin(gd, cbId); return; } @@ -87054,12 +87872,12 @@ var _$colorbar_516 = function colorbar(gd, cd) { cmin = marker.cmin, cmax = marker.cmax; - if(!_$fastIsnumeric_78(cmin)) cmin = _$lib_363.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_78(cmax)) cmax = _$lib_363.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_135(cmin)) cmin = _$lib_425.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_135(cmax)) cmax = _$lib_425.aggNums(Math.max, null, vals); - var cb = cd[0].t.cb = _$draw_243(gd, cbId); - var sclFunc = _$colorscale_254.makeColorScaleFunc( - _$colorscale_254.extractScale( + var cb = cd[0].t.cb = _$draw_305(gd, cbId); + var sclFunc = _$colorscale_316.makeColorScaleFunc( + _$colorscale_316.extractScale( marker.colorscale, cmin, cmax @@ -87083,10 +87901,10 @@ var _$colorbar_516 = function colorbar(gd, cd) { 'use strict'; -/* removed: var _$color_239 = require('../../components/color'); */; -var __isArrayOrTypedArray_521 = _$lib_363.isArrayOrTypedArray; +/* removed: var _$color_301 = require('../../components/color'); */; +var __isArrayOrTypedArray_585 = _$lib_425.isArrayOrTypedArray; -var _$fillColorDefaults_521 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_585 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -87094,15 +87912,15 @@ var _$fillColorDefaults_521 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_521(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_585(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_521(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_585(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } - coerce('fillcolor', _$color_239.addOpacity( + coerce('fillcolor', _$color_301.addOpacity( (traceOut.line || {}).color || inheritColorFromMarker || defaultColor, 0.5 @@ -87119,20 +87937,20 @@ var _$fillColorDefaults_521 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_525 = _$lib_363.isArrayOrTypedArray; -/* removed: var _$hasColorscale_253 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_249 = require('../../components/colorscale/defaults'); */; +var __isArrayOrTypedArray_589 = _$lib_425.isArrayOrTypedArray; +/* removed: var _$hasColorscale_315 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_311 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_525 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_589 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); - if(_$hasColorscale_253(traceIn, 'line')) { - _$colorScaleDefaults_249(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); + if(_$hasColorscale_315(traceIn, 'line')) { + _$colorScaleDefaults_311(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_525(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_589(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -87153,7 +87971,7 @@ var _$lineDefaults_525 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_527 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_591 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -87169,11 +87987,11 @@ var _$handleLineShapeDefaults_527 = function handleLineShapeDefaults(traceIn, tr 'use strict'; -/* removed: var _$color_239 = require('../../components/color'); */; -/* removed: var _$hasColorscale_253 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_249 = require('../../components/colorscale/defaults'); */; +/* removed: var _$color_301 = require('../../components/color'); */; +/* removed: var _$hasColorscale_315 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_311 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_534 = require('./subtypes'); */; +/* removed: var _$subtypes_598 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -87181,8 +87999,8 @@ var _$handleLineShapeDefaults_527 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_530 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_534.isBubble(traceIn), +var _$markerDefaults_594 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_598.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -87196,8 +88014,8 @@ var _$markerDefaults_530 = function markerDefaults(traceIn, traceOut, defaultCol coerce('marker.size'); coerce('marker.color', defaultColor); - if(_$hasColorscale_253(traceIn, 'marker')) { - _$colorScaleDefaults_249(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); + if(_$hasColorscale_315(traceIn, 'marker')) { + _$colorScaleDefaults_311(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); } if(!opts.noSelect) { @@ -87215,12 +88033,12 @@ var _$markerDefaults_530 = function markerDefaults(traceIn, traceOut, defaultCol if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) { defaultMLC = lineColor; } - else if(isBubble) defaultMLC = _$color_239.background; - else defaultMLC = _$color_239.defaultLine; + else if(isBubble) defaultMLC = _$color_301.background; + else defaultMLC = _$color_301.defaultLine; coerce('marker.line.color', defaultMLC); - if(_$hasColorscale_253(traceIn, 'marker.line')) { - _$colorScaleDefaults_249(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}); + if(_$hasColorscale_315(traceIn, 'marker.line')) { + _$colorScaleDefaults_311(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}); } coerce('marker.line.width', isBubble ? 1 : 0); @@ -87251,17 +88069,17 @@ var _$markerDefaults_530 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_535 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_599 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_363.coerceFont(coerce, 'textfont', layout.font); + _$lib_425.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -87280,15 +88098,15 @@ var _$text_defaults_535 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$registry_451 = require('../../registry'); */; +/* removed: var _$registry_514 = require('../../registry'); */; -var _$handleXYDefaults_536 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { +var _$handleXYDefaults_600 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { var len, x = coerce('x'), y = coerce('y'); - var handleCalendarDefaults = _$registry_451.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_514.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); if(x) { @@ -87324,27 +88142,27 @@ var _$handleXYDefaults_536 = function handleXYDefaults(traceIn, traceOut, layout 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$registry_451 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$registry_514 = require('../../registry'); */; -/* removed: var _$attributes_512 = require('./attributes'); */; -/* removed: var _$constants_518 = require('./constants'); */; -/* removed: var _$subtypes_534 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_536 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_530 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_525 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_527 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_535 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_521 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_576 = require('./attributes'); */; +/* removed: var _$constants_582 = require('./constants'); */; +/* removed: var _$subtypes_598 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_600 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_594 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_589 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_591 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_599 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_585 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_519 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_583 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_512, attr, dflt); + return _$lib_425.coerce(traceIn, traceOut, _$attributes_576, attr, dflt); } - var len = _$handleXYDefaults_536(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_600(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_518.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_582.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -87354,24 +88172,24 @@ var _$supplyDefaults_519 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_534.hasLines(traceOut)) { - _$lineDefaults_525(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_527(traceIn, traceOut, coerce); + if(_$subtypes_598.hasLines(traceOut)) { + _$lineDefaults_589(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_591(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_534.hasMarkers(traceOut)) { - _$markerDefaults_530(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_598.hasMarkers(traceOut)) { + _$markerDefaults_594(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_534.hasText(traceOut)) { - _$text_defaults_535(traceIn, traceOut, layout, coerce); + if(_$subtypes_598.hasText(traceOut)) { + _$text_defaults_599(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_534.hasMarkers(traceOut) || _$subtypes_534.hasText(traceOut)) { + if(_$subtypes_598.hasMarkers(traceOut) || _$subtypes_598.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -87379,8 +88197,8 @@ var _$supplyDefaults_519 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_521(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_534.hasLines(traceOut)) _$handleLineShapeDefaults_527(traceIn, traceOut, coerce); + _$fillColorDefaults_585(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_598.hasLines(traceOut)) _$handleLineShapeDefaults_591(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -87388,11 +88206,11 @@ var _$supplyDefaults_519 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_451.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_514.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_363.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_425.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -87405,7 +88223,7 @@ var _$supplyDefaults_519 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; /** Fill hover 'pointData' container with 'correct' hover text value * @@ -87420,15 +88238,15 @@ var _$supplyDefaults_519 = function supplyDefaults(traceIn, traceOut, defaultCol * @param {object} trace * @param {object || array} contOut (mutated here) */ -var _$fillHoverText_520 = function fillHoverText(calcPt, trace, contOut) { +var _$fillHoverText_584 = function fillHoverText(calcPt, trace, contOut) { var fill = Array.isArray(contOut) ? function(v) { contOut.push(v); } : function(v) { contOut.text = v; }; - var htx = _$lib_363.extractOption(calcPt, trace, 'htx', 'hovertext'); + var htx = _$lib_425.extractOption(calcPt, trace, 'htx', 'hovertext'); if(isValid(htx)) return fill(htx); - var tx = _$lib_363.extractOption(calcPt, trace, 'tx', 'text'); + var tx = _$lib_425.extractOption(calcPt, trace, 'tx', 'text'); if(isValid(tx)) return fill(tx); }; @@ -87448,18 +88266,18 @@ function isValid(v) { 'use strict'; -/* removed: var _$color_239 = require('../../components/color'); */; -/* removed: var _$subtypes_534 = require('./subtypes'); */; +/* removed: var _$color_301 = require('../../components/color'); */; +/* removed: var _$subtypes_598 = require('./subtypes'); */; -var _$getTraceColor_522 = function getTraceColor(trace, di) { +var _$getTraceColor_586 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes if(trace.mode === 'lines') { lc = trace.line.color; - return (lc && _$color_239.opacity(lc)) ? + return (lc && _$color_301.opacity(lc)) ? lc : trace.fillcolor; } else if(trace.mode === 'none') { @@ -87469,21 +88287,21 @@ var _$getTraceColor_522 = function getTraceColor(trace, di) { var mc = di.mcc || (trace.marker || {}).color, mlc = di.mlcc || ((trace.marker || {}).line || {}).color; - tc = (mc && _$color_239.opacity(mc)) ? mc : - (mlc && _$color_239.opacity(mlc) && + tc = (mc && _$color_301.opacity(mc)) ? mc : + (mlc && _$color_301.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : ''; if(tc) { // make sure the points aren't TOO transparent - if(_$color_239.opacity(tc) < 0.3) { - return _$color_239.addOpacity(tc, 0.3); + if(_$color_301.opacity(tc) < 0.3) { + return _$color_301.addOpacity(tc, 0.3); } else return tc; } else { lc = (trace.line || {}).color; - return (lc && _$color_239.opacity(lc) && - _$subtypes_534.hasLines(trace) && trace.line.width) ? + return (lc && _$color_301.opacity(lc) && + _$subtypes_598.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -87499,14 +88317,14 @@ var _$getTraceColor_522 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$fx_281 = require('../../components/fx'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$getTraceColor_522 = require('./get_trace_color'); */; -/* removed: var _$color_239 = require('../../components/color'); */; -/* removed: var _$fillHoverText_520 = require('./fill_hover_text'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$fx_343 = require('../../components/fx'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$getTraceColor_586 = require('./get_trace_color'); */; +/* removed: var _$color_301 = require('../../components/color'); */; +/* removed: var _$fillHoverText_584 = require('./fill_hover_text'); */; -var _$hoverPoints_523 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_587 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -87546,9 +88364,9 @@ var _$hoverPoints_523 = function hoverPoints(pointData, xval, yval, hovermode) { var dy = ya.c2p(di.y) - ypx; return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad); }; - var distfn = _$fx_281.getDistanceFunction(hovermode, dx, dy, dxy); + var distfn = _$fx_343.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_281.getClosest(cd, distfn, pointData); + _$fx_343.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index !== false) { @@ -87559,8 +88377,8 @@ var _$hoverPoints_523 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_363.extendFlat(pointData, { - color: _$getTraceColor_522(trace, di), + _$lib_425.extendFlat(pointData, { + color: _$getTraceColor_586(trace, di), x0: xc - rad, x1: xc + rad, @@ -87573,8 +88391,8 @@ var _$hoverPoints_523 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_520(di, trace, pointData); - _$registry_451.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_584(di, trace, pointData); + _$registry_514.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -87640,13 +88458,13 @@ var _$hoverPoints_523 = function hoverPoints(pointData, xval, yval, hovermode) { xmax = Math.min(xmax, xa._length); // get only fill or line color for the hover color - var color = _$color_239.defaultLine; - if(_$color_239.opacity(trace.fillcolor)) color = trace.fillcolor; - else if(_$color_239.opacity((trace.line || {}).color)) { + var color = _$color_301.defaultLine; + if(_$color_301.opacity(trace.fillcolor)) color = trace.fillcolor; + else if(_$color_301.opacity((trace.line || {}).color)) { color = trace.line.color; } - _$lib_363.extendFlat(pointData, { + _$lib_425.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -87680,14 +88498,14 @@ var _$hoverPoints_523 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_526 = _$numerical_343.BADNUM; -/* removed: var _$lib_363 = require('../../lib'); */; -var __segmentsIntersect_526 = _$lib_363.segmentsIntersect; -var constrain = _$lib_363.constrain; -/* removed: var _$constants_518 = require('./constants'); */; +var __BADNUM_590 = _$numerical_404.BADNUM; +/* removed: var _$lib_425 = require('../../lib'); */; +var __segmentsIntersect_590 = _$lib_425.segmentsIntersect; +var constrain = _$lib_425.constrain; +/* removed: var _$constants_582 = require('./constants'); */; -var _$linePoints_526 = function linePoints(d, opts) { +var _$linePoints_590 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -87696,7 +88514,7 @@ var _$linePoints_526 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_518.minTolerance; + var minTolerance = _$constants_582.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -87734,7 +88552,7 @@ var _$linePoints_526 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_526 || y === __BADNUM_526) return di.intoCenter || false; + if(x === __BADNUM_590 || y === __BADNUM_590) return di.intoCenter || false; return [x, y]; } @@ -87742,7 +88560,7 @@ var _$linePoints_526 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_518.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_582.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -87754,7 +88572,7 @@ var _$linePoints_526 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_518.maxScreensAway; + var maxScreensAway = _$constants_582.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -87783,7 +88601,7 @@ var _$linePoints_526 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_526(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_590(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -87837,7 +88655,7 @@ var _$linePoints_526 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_363.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_425.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -88090,7 +88908,7 @@ var _$linePoints_526 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_528 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_592 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -88130,19 +88948,19 @@ var _$linkTraces_528 = function linkTraces(gd, plotinfo, cdscatter) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; +/* removed: var _$d3_71 = require('d3'); */; -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$drawing_326 = require('../../components/drawing'); */; -/* removed: var _$subtypes_534 = require('./subtypes'); */; -/* removed: var _$linePoints_526 = require('./line_points'); */; -/* removed: var _$linkTraces_528 = require('./link_traces'); */; -var __polygonTester_531 = _$polygon_375.tester; +/* removed: var _$subtypes_598 = require('./subtypes'); */; +/* removed: var _$linePoints_590 = require('./line_points'); */; +/* removed: var _$linkTraces_592 = require('./link_traces'); */; +var __polygonTester_595 = _$polygon_437.tester; -var _$plot_531 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_595 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -88151,9 +88969,8 @@ var _$plot_531 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -88165,7 +88982,7 @@ var _$plot_531 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_528(gd, plotinfo, cdscatter); + _$linkTraces_592(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -88190,7 +89007,7 @@ var _$plot_531 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo onComplete = makeOnCompleteCallback(); } - var transition = _$d3_68.transition() + var transition = _$d3_71.transition() .duration(transitionOpts.duration) .ease(transitionOpts.easing) .each('end', function() { @@ -88204,12 +89021,12 @@ var _$plot_531 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_531(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_595(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_531(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_595(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -88225,7 +89042,7 @@ function createFills(gd, scatterlayer, plotinfo) { var trace; scatterlayer.selectAll('g.trace').each(function(d) { - var tr = _$d3_68.select(this); + var tr = _$d3_71.select(this); // Loop only over the traces being redrawn: trace = d[0].trace; @@ -88260,11 +89077,11 @@ function createFills(gd, scatterlayer, plotinfo) { trace._ownFill = null; } - tr.selectAll('.js-fill').call(_$drawing_264.setClipUrl, plotinfo.layerClipId); + tr.selectAll('.js-fill').call(_$drawing_326.setClipUrl, plotinfo.layerClipId); }); } -function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_595(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -88283,10 +89100,10 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = cdscatter[0].trace, line = trace.line, - tr = _$d3_68.select(element); + tr = _$d3_71.select(element); // error bars are at the bottom - _$registry_451.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_514.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -88298,7 +89115,7 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -88324,11 +89141,11 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_363.noop; + makeUpdate = _$lib_425.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_534.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_598.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -88336,8 +89153,8 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran } if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = _$drawing_264.steps(line.shape); - revpathbase = _$drawing_264.steps( + pathfn = _$drawing_326.steps(line.shape); + revpathbase = _$drawing_326.steps( line.shape.split('').reverse().join('') ); } @@ -88347,10 +89164,10 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { // identical start and end points: treat it as a // closed curve so we don't get a kink - return _$drawing_264.smoothclosed(pts.slice(1), line.smoothing); + return _$drawing_326.smoothclosed(pts.slice(1), line.smoothing); } else { - return _$drawing_264.smoothopen(pts, line.smoothing); + return _$drawing_326.smoothopen(pts, line.smoothing); } }; } @@ -88365,7 +89182,7 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_526(cdscatter, { + segments = _$linePoints_590(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -88380,7 +89197,7 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_531(segments[i]); + trace._polygons[i] = __polygonTester_595(segments[i]); } if(segments.length) { @@ -88406,8 +89223,8 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_534.hasLines(trace) && pts.length > 1) { - var el = _$d3_68.select(this); + if(_$subtypes_598.hasLines(trace) && pts.length > 1) { + var el = _$d3_71.select(this); // This makes the coloring work correctly: el.datum(cdscatter); @@ -88415,12 +89232,12 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(isEnter) { transition(el.style('opacity', 0) .attr('d', thispath) - .call(_$drawing_264.lineGroupStyle)) + .call(_$drawing_326.lineGroupStyle)) .style('opacity', 1); } else { var sel = transition(el); sel.attr('d', thispath); - _$drawing_264.singleLineStyle(cdscatter, sel); + _$drawing_326.singleLineStyle(cdscatter, sel); } } }; @@ -88438,10 +89255,10 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran lineJoin.enter().append('path') .classed('js-line', true) .style('vector-effect', 'non-scaling-stroke') - .call(_$drawing_264.lineGroupStyle) + .call(_$drawing_326.lineGroupStyle) .each(makeUpdate(true)); - _$drawing_264.setClipUrl(lineJoin, plotinfo.layerClipId); + _$drawing_326.setClipUrl(lineJoin, plotinfo.layerClipId); function clearFill(selection) { transition(selection).attr('d', 'M0,0Z'); @@ -88464,11 +89281,11 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // the points on the axes are the first two points. Otherwise // animations get a little crazy if the number of points changes. transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1)) - .call(_$drawing_264.singleFillStyle); + .call(_$drawing_326.singleFillStyle); } else { // fill to self: just join the path to itself transition(ownFillEl3).attr('d', fullpath + 'Z') - .call(_$drawing_264.singleFillStyle); + .call(_$drawing_326.singleFillStyle); } } } @@ -88481,7 +89298,7 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z') - .call(_$drawing_264.singleFillStyle); + .call(_$drawing_326.singleFillStyle); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -88490,7 +89307,7 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // things depending on whether the new endpoint projects onto the // existing curve or off the end of it transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z') - .call(_$drawing_264.singleFillStyle); + .call(_$drawing_326.singleFillStyle); } trace._polygons = trace._polygons.concat(prevPolygons); } @@ -88532,20 +89349,20 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var join, selection, hasNode; var trace = d[0].trace, - s = _$d3_68.select(this), - showMarkers = _$subtypes_534.hasMarkers(trace), - showText = _$subtypes_534.hasText(trace); + s = _$d3_71.select(this), + showMarkers = _$subtypes_598.hasMarkers(trace), + showText = _$subtypes_598.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_363.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_425.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_363.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_425.identity; } // marker points @@ -88559,28 +89376,28 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(hasTransition) { enter - .call(_$drawing_264.pointStyle, trace, gd) - .call(_$drawing_264.translatePoints, xa, ya) + .call(_$drawing_326.pointStyle, trace, gd) + .call(_$drawing_326.translatePoints, xa, ya) .style('opacity', 0) .transition() .style('opacity', 1); } - var markerScale = showMarkers && _$drawing_264.tryColorscale(trace.marker, ''); - var lineScale = showMarkers && _$drawing_264.tryColorscale(trace.marker, 'line'); + var markerScale = showMarkers && _$drawing_326.tryColorscale(trace.marker, ''); + var lineScale = showMarkers && _$drawing_326.tryColorscale(trace.marker, 'line'); join.order(); join.each(function(d) { - var el = _$d3_68.select(this); + var el = _$d3_71.select(this); var sel = transition(el); - hasNode = _$drawing_264.translatePoint(d, sel, xa, ya); + hasNode = _$drawing_326.translatePoint(d, sel, xa, ya); if(hasNode) { - _$drawing_264.singlePointStyle(d, sel, trace, markerScale, lineScale, gd); + _$drawing_326.singlePointStyle(d, sel, trace, markerScale, lineScale, gd); if(plotinfo.layerClipId) { - _$drawing_264.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_326.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar); } if(trace.customdata) { @@ -88610,13 +89427,13 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran join.order(); join.each(function(d) { - var g = _$d3_68.select(this); + var g = _$d3_71.select(this); var sel = transition(g.select('text')); - hasNode = _$drawing_264.translatePoint(d, sel, xa, ya); + hasNode = _$drawing_326.translatePoint(d, sel, xa, ya); if(hasNode) { if(plotinfo.layerClipId) { - _$drawing_264.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_326.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar); } } else { g.remove(); @@ -88624,15 +89441,15 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran }); join.selectAll('text') - .call(_$drawing_264.textPointStyle, trace, gd) + .call(_$drawing_326.textPointStyle, trace, gd) .each(function(d) { // This just *has* to be totally custom becuase of SVG text positioning :( // It's obviously copied from translatePoint; we just can't use that var x = xa.c2p(d.x); var y = ya.c2p(d.y); - _$d3_68.select(this).selectAll('tspan.line').each(function() { - transition(_$d3_68.select(this)).attr({x: x, y: y}); + _$d3_71.select(this).selectAll('tspan.line').each(function() { + transition(_$d3_71.select(this)).attr({x: x, y: y}); }); }); @@ -88659,18 +89476,18 @@ function __plotOne_531(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // on `plotinfo._hasClipOnAxisFalse === true` subplots join.each(function(d) { var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_264.setClipUrl(_$d3_68.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + _$drawing_326.setClipUrl(_$d3_71.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); }); } function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_68.extent(_$lib_363.simpleMap(xa.range, xa.r2c)), - yr = _$d3_68.extent(_$lib_363.simpleMap(ya.range, ya.r2c)); + xr = _$d3_71.extent(_$lib_425.simpleMap(xa.range, xa.r2c)), + yr = _$d3_71.extent(_$lib_425.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_534.hasMarkers(trace)) return; + if(!_$subtypes_598.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -88685,7 +89502,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_534.hasMarkers(tracei) && + if(_$subtypes_598.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -88716,9 +89533,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_534 = require('./subtypes'); */; +/* removed: var _$subtypes_598 = require('./subtypes'); */; -var _$selectPoints_532 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_596 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -88729,7 +89546,7 @@ var _$selectPoints_532 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_534.hasMarkers(trace) && !_$subtypes_534.hasText(trace)); + var hasOnlyLines = (!_$subtypes_598.hasMarkers(trace) && !_$subtypes_598.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -88770,44 +89587,44 @@ var _$selectPoints_532 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; -/* removed: var _$registry_451 = require('../../registry'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$drawing_326 = require('../../components/drawing'); */; +/* removed: var _$registry_514 = require('../../registry'); */; -function __style_533(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_68.select(gd).selectAll('g.trace.scatter'); +function __style_597(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_71.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_68.select(this); + var sel = _$d3_71.select(this); var trace = d.trace || d[0].trace; stylePoints(sel, trace, gd); }); s.selectAll('g.trace path.js-line') - .call(_$drawing_264.lineGroupStyle); + .call(_$drawing_326.lineGroupStyle); s.selectAll('g.trace path.js-fill') - .call(_$drawing_264.fillGroupStyle); + .call(_$drawing_326.fillGroupStyle); - _$registry_451.getComponentMethod('errorbars', 'style')(s); + _$registry_514.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { var pts = sel.selectAll('path.point'); var txs = sel.selectAll('text'); - _$drawing_264.pointStyle(pts, trace, gd); - _$drawing_264.textPointStyle(txs, trace, gd); - _$drawing_264.selectedPointStyle(pts, trace); - _$drawing_264.selectedTextStyle(txs, trace); + _$drawing_326.pointStyle(pts, trace, gd); + _$drawing_326.textPointStyle(txs, trace, gd); + _$drawing_326.selectedPointStyle(pts, trace); + _$drawing_326.selectedTextStyle(txs, trace); } -var _$style_533 = { - style: __style_533, +var _$style_597 = { + style: __style_597, stylePoints: stylePoints }; @@ -88824,37 +89641,37 @@ var _$style_533 = { var Scatter = {}; -/* removed: var _$subtypes_534 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_534.hasLines; -Scatter.hasMarkers = _$subtypes_534.hasMarkers; -Scatter.hasText = _$subtypes_534.hasText; -Scatter.isBubble = _$subtypes_534.isBubble; +/* removed: var _$subtypes_598 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_598.hasLines; +Scatter.hasMarkers = _$subtypes_598.hasMarkers; +Scatter.hasText = _$subtypes_598.hasText; +Scatter.isBubble = _$subtypes_598.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_512; -Scatter.supplyDefaults = _$supplyDefaults_519; -Scatter.cleanData = _$cleanData_515; -Scatter.calc = _$calc_513.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_511; -Scatter.plot = _$plot_531; -Scatter.colorbar = _$colorbar_516; -Scatter.style = _$style_533.style; -Scatter.hoverPoints = _$hoverPoints_523; -Scatter.selectPoints = _$selectPoints_532; +Scatter.attributes = _$attributes_576; +Scatter.supplyDefaults = _$supplyDefaults_583; +Scatter.cleanData = _$cleanData_579; +Scatter.calc = _$calc_577.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_575; +Scatter.plot = _$plot_595; +Scatter.colorbar = _$colorbar_580; +Scatter.style = _$style_597.style; +Scatter.hoverPoints = _$hoverPoints_587; +Scatter.selectPoints = _$selectPoints_596; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_418; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_481; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_524 = Scatter; +var _$Scatter_588 = Scatter; -var _$core_346 = {}; +var _$core_407 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -88866,71 +89683,71 @@ var _$core_346 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_346.version = '1.35.2'; +_$core_407.version = '1.36.0'; // inject promise polyfill -_$es6Promise_76.polyfill(); +_$es6Promise_124.polyfill(); // inject plot css _$plotcss_1; // inject default MathJax config -_$mathjax_config_347; +_$mathjax_config_408; // include registry module and expose register method -/* removed: var _$registry_451 = require('./registry'); */; -var register = _$core_346.register = _$registry_451.register; +/* removed: var _$registry_514 = require('./registry'); */; +var register = _$core_407.register = _$registry_514.register; // expose plot api methods -/* removed: var _$plot_api_394 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_394); -for(var __i_346 = 0; __i_346 < methodNames.length; __i_346++) { - var __name_346 = methodNames[__i_346]; - _$core_346[__name_346] = _$plot_api_394[__name_346]; +/* removed: var _$plot_api_457 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_457); +for(var __i_407 = 0; __i_407 < methodNames.length; __i_407++) { + var __name_407 = methodNames[__i_407]; + _$core_407[__name_407] = _$plot_api_457[__name_407]; register({ moduleType: 'apiMethod', - name: __name_346, - fn: _$plot_api_394[__name_346] + name: __name_407, + fn: _$plot_api_457[__name_407] }); } // scatter is the only trace included by default -register(_$Scatter_524); +register(_$Scatter_588); // register all registrable components modules register([ - _$fx_281, - _$legend_299, - _$annotations_232, - _$annotations3d_237, - _$shapes_325, - _$images_290, - _$updatemenus_337, - _$sliders_331, - _$rangeslider_317, - _$rangeselector_311, - _$grid_285, - _$errorbars_270 + _$fx_343, + _$legend_361, + _$annotations_294, + _$annotations3d_299, + _$shapes_387, + _$images_352, + _$updatemenus_399, + _$sliders_393, + _$rangeslider_379, + _$rangeselector_373, + _$grid_347, + _$errorbars_332 ]); // locales en and en-US are required for default behavior register([ - _$localeEn_390, - _$localeEnUs_389 + _$localeEn_453, + _$localeEnUs_452 ]); // plot icons -_$core_346.Icons = _$ploticon_2; +_$core_407.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk -_$core_346.Plots = _$plots_444; -_$core_346.Fx = _$fx_281; -_$core_346.Snapshot = _$Snapshot_456; -_$core_346.PlotSchema = _$plot_schema_398; -_$core_346.Queue = _$queue_377; +_$core_407.Plots = _$plots_506; +_$core_407.Fx = _$fx_343; +_$core_407.Snapshot = _$Snapshot_519; +_$core_407.PlotSchema = _$plot_schema_461; +_$core_407.Queue = _$queue_440; // export d3 used in the bundle -_$core_346.d3 = _$d3_68; +_$core_407.d3 = _$d3_71; /** * Copyright 2012-2018, Plotly, Inc. @@ -88942,7 +89759,7 @@ _$core_346.d3 = _$d3_68; 'use strict'; -var _$core_4 = _$core_346; +var _$core_4 = _$core_407; /** * Copyright 2012-2018, Plotly, Inc. @@ -88955,33 +89772,33 @@ var _$core_4 = _$core_346; 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$colorscale_254 = require('../../components/colorscale'); */; -/* removed: var _$draw_243 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$colorscale_316 = require('../../components/colorscale'); */; +/* removed: var _$draw_305 = require('../../components/colorbar/draw'); */; -var _$colorbar_476 = function colorbar(gd, cd) { +var _$colorbar_539 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, zmin = trace.zmin, zmax = trace.zmax; - if(!_$fastIsnumeric_78(zmin)) zmin = _$lib_363.aggNums(Math.min, null, trace.z); - if(!_$fastIsnumeric_78(zmax)) zmax = _$lib_363.aggNums(Math.max, null, trace.z); + if(!_$fastIsnumeric_135(zmin)) zmin = _$lib_425.aggNums(Math.min, null, trace.z); + if(!_$fastIsnumeric_135(zmax)) zmax = _$lib_425.aggNums(Math.max, null, trace.z); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_444.autoMargin(gd, cbId); + _$plots_506.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_243(gd, cbId); - var sclFunc = _$colorscale_254.makeColorScaleFunc( - _$colorscale_254.extractScale( + var cb = cd[0].t.cb = _$draw_305(gd, cbId); + var sclFunc = _$colorscale_316.makeColorScaleFunc( + _$colorscale_316.extractScale( trace.colorscale, zmin, zmax @@ -89005,7 +89822,7 @@ var _$colorbar_476 = function colorbar(gd, cd) { 'use strict'; -var _$handleStyleDefaults_484 = function handleStyleDefaults(traceIn, traceOut, coerce) { +var _$handleStyleDefaults_547 = function handleStyleDefaults(traceIn, traceOut, coerce) { var zsmooth = coerce('zsmooth'); if(zsmooth === false) { // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect. @@ -89027,21 +89844,21 @@ var _$handleStyleDefaults_484 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; -/* removed: var _$has_columns_480 = require('./has_columns'); */; -/* removed: var _$handleXYZDefaults_485 = require('./xyz_defaults'); */; -/* removed: var _$handleStyleDefaults_484 = require('./style_defaults'); */; -/* removed: var _$colorScaleDefaults_249 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_473 = require('./attributes'); */; +/* removed: var _$has_columns_543 = require('./has_columns'); */; +/* removed: var _$handleXYZDefaults_548 = require('./xyz_defaults'); */; +/* removed: var _$handleStyleDefaults_547 = require('./style_defaults'); */; +/* removed: var _$colorScaleDefaults_311 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_536 = require('./attributes'); */; -var _$supplyDefaults_478 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_541 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_473, attr, dflt); + return _$lib_425.coerce(traceIn, traceOut, _$attributes_536, attr, dflt); } - var len = _$handleXYZDefaults_485(traceIn, traceOut, coerce, layout); + var len = _$handleXYZDefaults_548(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -89049,11 +89866,11 @@ var _$supplyDefaults_478 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); - _$handleStyleDefaults_484(traceIn, traceOut, coerce, layout); + _$handleStyleDefaults_547(traceIn, traceOut, coerce, layout); - coerce('connectgaps', _$has_columns_480(traceOut) && (traceOut.zsmooth !== false)); + coerce('connectgaps', _$has_columns_543(traceOut) && (traceOut.zsmooth !== false)); - _$colorScaleDefaults_249(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); + _$colorScaleDefaults_311(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; /** @@ -89067,12 +89884,12 @@ var _$supplyDefaults_478 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$attributes_473 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_245 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_240 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_536 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_307 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_302 = require('../../components/colorbar/attributes'); */; -var __extendFlat_486 = _$extend_354.extendFlat; -var __overrideAll_486 = _$edit_types_392.overrideAll; +var __extendFlat_549 = _$extend_416.extendFlat; +var __overrideAll_549 = _$edit_types_455.overrideAll; var commonList = [ @@ -89083,21 +89900,21 @@ var commonList = [ 'xtype', 'ytype' ]; -var __attrs_486 = {}; +var __attrs_549 = {}; -for(var __i_486 = 0; __i_486 < commonList.length; __i_486++) { - var k = commonList[__i_486]; - __attrs_486[k] = _$attributes_473[k]; +for(var __i_549 = 0; __i_549 < commonList.length; __i_549++) { + var k = commonList[__i_549]; + __attrs_549[k] = _$attributes_536[k]; } -__extendFlat_486( - __attrs_486, - _$attributes_245, - { autocolorscale: __extendFlat_486({}, _$attributes_245.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_240 } +__extendFlat_549( + __attrs_549, + _$attributes_307, + { autocolorscale: __extendFlat_549({}, _$attributes_307.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_302 } ); -var _$attributes_486 = __overrideAll_486(__attrs_486, 'calc', 'nested'); +var _$attributes_549 = __overrideAll_549(__attrs_549, 'calc', 'nested'); /** * Copyright 2012-2018, Plotly, Inc. @@ -89110,9 +89927,9 @@ var _$attributes_486 = __overrideAll_486(__attrs_486, 'calc', 'nested'); 'use strict'; -/* removed: var _$createHeatmap2D_91 = require('gl-heatmap2d'); */; -/* removed: var _$axes_407 = require('../../plots/cartesian/axes'); */; -/* removed: var _$str2RgbaArray_385 = require('../../lib/str2rgbarray'); */; +/* removed: var _$createHeatmap2D_148 = require('gl-heatmap2d'); */; +/* removed: var _$axes_470 = require('../../plots/cartesian/axes'); */; +/* removed: var _$str2RgbaArray_448 = require('../../lib/str2rgbarray'); */; function Heatmap(scene, uid) { @@ -89140,13 +89957,13 @@ function Heatmap(scene, uid) { colorValues: [0, 0, 0, 1] }; - this.heatmap = _$createHeatmap2D_91(scene.glplot, this.options); + this.heatmap = _$createHeatmap2D_148(scene.glplot, this.options); this.heatmap._trace = this; } -var __proto_487 = Heatmap.prototype; +var __proto_550 = Heatmap.prototype; -__proto_487.handlePick = function(pickResult) { +__proto_550.handlePick = function(pickResult) { var options = this.options, shape = options.shape, index = pickResult.pointId, @@ -89169,7 +89986,7 @@ __proto_487.handlePick = function(pickResult) { }; }; -__proto_487.update = function(fullTrace, calcTrace) { +__proto_550.update = function(fullTrace, calcTrace) { var calcPt = calcTrace[0]; this.index = fullTrace.index; @@ -89196,11 +90013,11 @@ __proto_487.update = function(fullTrace, calcTrace) { this.heatmap.update(this.options); - _$axes_407.expand(this.scene.xaxis, calcPt.x); - _$axes_407.expand(this.scene.yaxis, calcPt.y); + _$axes_470.expand(this.scene.xaxis, calcPt.x); + _$axes_470.expand(this.scene.yaxis, calcPt.y); }; -__proto_487.dispose = function() { +__proto_550.dispose = function() { this.heatmap.dispose(); }; @@ -89215,7 +90032,7 @@ function convertColorscale(fullTrace) { for(var i = 0; i < N; i++) { var si = scl[i]; - var color = _$str2RgbaArray_385(si[1]); + var color = _$str2RgbaArray_448(si[1]); domain[i] = zmin + si[0] * (zmax - zmin); @@ -89236,7 +90053,7 @@ function createHeatmap(scene, fullTrace, calcTrace) { return plot; } -var _$createHeatmap_487 = createHeatmap; +var _$createHeatmap_550 = createHeatmap; /** * Copyright 2012-2018, Plotly, Inc. @@ -89251,22 +90068,22 @@ var _$createHeatmap_487 = createHeatmap; var HeatmapGl = {}; -HeatmapGl.attributes = _$attributes_486; -HeatmapGl.supplyDefaults = _$supplyDefaults_478; -HeatmapGl.colorbar = _$colorbar_476; +HeatmapGl.attributes = _$attributes_549; +HeatmapGl.supplyDefaults = _$supplyDefaults_541; +HeatmapGl.colorbar = _$colorbar_539; -HeatmapGl.calc = _$calc_474; -HeatmapGl.plot = _$createHeatmap_487; +HeatmapGl.calc = _$calc_537; +HeatmapGl.plot = _$createHeatmap_550; HeatmapGl.moduleType = 'trace'; HeatmapGl.name = 'heatmapgl'; -HeatmapGl.basePlotModule = _$gl2d_439; +HeatmapGl.basePlotModule = _$gl2d_501; HeatmapGl.categories = ['gl', 'gl2d', '2dMap']; HeatmapGl.meta = { }; -var _$HeatmapGl_488 = HeatmapGl; +var _$HeatmapGl_551 = HeatmapGl; /** * Copyright 2012-2018, Plotly, Inc. @@ -89278,7 +90095,7 @@ var _$HeatmapGl_488 = HeatmapGl; 'use strict'; -var _$heatmapgl_5 = _$HeatmapGl_488; +var _$heatmapgl_5 = _$HeatmapGl_551; /** * Copyright 2012-2018, Plotly, Inc. @@ -89290,29 +90107,29 @@ var _$heatmapgl_5 = _$HeatmapGl_488; 'use strict'; -/* removed: var _$makeColorScaleAttributes_247 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_240 = require('../../components/colorbar/attributes'); */; -/* removed: var _$scales_258 = require('../../components/colorscale/scales'); */; -/* removed: var _$layout_attributes_419 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_434 = require('../../plots/font_attributes'); */; -var __domainAttrs_495 = _$domain_433.attributes; +/* removed: var _$makeColorScaleAttributes_309 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_302 = require('../../components/colorbar/attributes'); */; +/* removed: var _$scales_320 = require('../../components/colorscale/scales'); */; +/* removed: var _$layout_attributes_482 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_496 = require('../../plots/font_attributes'); */; +var __domainAttrs_558 = _$domain_495.attributes; -/* removed: var _$extend_354 = require('../../lib/extend'); */; -var __extendDeepAll_495 = _$extend_354.extendDeepAll; -var __extendFlat_495 = _$extend_354.extendFlat; +/* removed: var _$extend_416 = require('../../lib/extend'); */; +var __extendDeepAll_558 = _$extend_416.extendDeepAll; +var __extendFlat_558 = _$extend_416.extendFlat; -var _$attributes_495 = { - domain: __domainAttrs_495({name: 'parcoords', trace: true, editType: 'calc'}), +var _$attributes_558 = { + domain: __domainAttrs_558({name: 'parcoords', trace: true, editType: 'calc'}), - labelfont: _$font_attributes_434({ + labelfont: _$font_attributes_496({ editType: 'calc', }), - tickfont: _$font_attributes_434({ + tickfont: _$font_attributes_496({ editType: 'calc', }), - rangefont: _$font_attributes_434({ + rangefont: _$font_attributes_496({ editType: 'calc', }), @@ -89325,8 +90142,10 @@ var _$attributes_495 = { editType: 'calc', }, - tickvals: __extendFlat_495({}, _$layout_attributes_419.tickvals, {editType: 'calc'}), - ticktext: __extendFlat_495({}, _$layout_attributes_419.ticktext, {editType: 'calc'}), + // TODO: better way to determine ordinal vs continuous axes, + // so users can use tickvals/ticktext with a continuous axis. + tickvals: __extendFlat_558({}, _$layout_attributes_482.tickvals, {editType: 'calc'}), + ticktext: __extendFlat_558({}, _$layout_attributes_482.ticktext, {editType: 'calc'}), tickformat: { valType: 'string', dflt: '3s', @@ -89354,12 +90173,21 @@ var _$attributes_495 = { constraintrange: { valType: 'info_array', + freeLength: true, + dimensions: '1-2', items: [ {valType: 'number', editType: 'calc'}, {valType: 'number', editType: 'calc'} ], editType: 'calc', + }, + multiselect: { + valType: 'boolean', + dflt: true, + + editType: 'calc', + }, values: { valType: 'data_array', @@ -89371,14 +90199,14 @@ var _$attributes_495 = { }, - line: __extendFlat_495( + line: __extendFlat_558( // the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white) // autocolorscale therefore defaults to false too, to avoid being overridden by the blue-white-red autocolor palette - __extendDeepAll_495( - _$makeColorScaleAttributes_247('line', 'calc'), + __extendDeepAll_558( + _$makeColorScaleAttributes_309('line', 'calc'), { - colorscale: {dflt: _$scales_258.Viridis}, + colorscale: {dflt: _$scales_320.Viridis}, autocolorscale: { dflt: false, @@ -89394,14 +90222,14 @@ var _$attributes_495 = { editType: 'calc', }, - colorbar: _$attributes_240, + colorbar: _$attributes_302, editType: 'calc' } ) }; -var _$regl_175 = { exports: {} }; -(function(da,ea){"object"===typeof _$regl_175.exports&&"undefined"!=="object"?_$regl_175.exports=ea():"function"===typeof define&&define.amd?define(ea):da.createREGL=ea()})(this,function(){function da(a,b){this.id=vb++;this.type=a;this.data=b}function ea(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1= 0; i--) { + var aNext = a[i]; + + // very close to the previous - snap down to it + if(v > closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev); + if(v > aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev); + + aPrevPrev = aPrev; + aPrev = 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', -_$constants_563.bar.captureWidth / 2) + .attr('width', _$constants_563.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 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 = _$constants_563.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_71.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_71.select(root).selectAll('.highlight, .highlight-shadow'); + var barToStyle = tweenCallback ? bar.transition().duration(_$constants_563.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 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_71.event.preventDefault(); + if(!d.parent.inBrushDrag) { + var y = d.height - _$d3_71.mouse(this)[1] - 2 * _$constants_563.verticalPadding; + var interval = getInterval(d, y); + + var cursor = 'crosshair'; + if(interval.clickableOrdinalRange) cursor = 'pointer'; + else if(interval.region) cursor = interval.region + '-resize'; + _$d3_71.select(document.body) + .style('cursor', cursor); + } + }) + .on('mouseleave', function(d) { + if(!d.parent.inBrushDrag) clearCursor(); + }) + .call(_$d3_71.behavior.drag() + .on('dragstart', function(d) { + _$d3_71.event.sourceEvent.stopPropagation(); + var y = d.height - _$d3_71.mouse(this)[1] - 2 * _$constants_563.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] - _$constants_563.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(); + }) + .on('drag', function(d) { + _$d3_71.event.sourceEvent.stopPropagation(); + var y = d.height - _$d3_71.mouse(this)[1] - 2 * _$constants_563.verticalPadding; + var s = d.brush.svgBrush; + s.wasDragged = 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); + } + + // take care of the parcoords axis height constraint: bar can't breach it + var bottomViolation = Math.max(0, -s.newExtent[0]); + var topViolation = Math.max(0, s.newExtent[1] - 1); + s.newExtent[0] += bottomViolation; + s.newExtent[1] -= topViolation; + if(s.grabbingBar) { + // in case of bar dragging (non-resizing interaction, unlike north/south resize or new bar creation) + // the constraint adjustment must apply to the other end of the bar as well, otherwise it'd + // shorten or lengthen + s.newExtent[1] += bottomViolation; + s.newExtent[0] -= topViolation; + } + + d.brush.filterSpecified = true; + s.extent = s.stayingIntervals.concat([s.newExtent]); + s.brushCallback(d); + renderHighlight(this.parentNode); + }) + .on('dragend', function(d) { + var e = _$d3_71.event; + e.sourceEvent.stopPropagation(); + var brush = d.brush; + var filter = brush.filter; + var s = brush.svgBrush; + 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(this.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 = [ + ordinalScaleSnapLo(a, s.newExtent[0], s.stayingIntervals), + ordinalScaleSnapHi(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(this.parentNode, mergeIntervals); + } + else { + // if no new interval, don't animate, just redraw the highlight immediately + mergeIntervals(); + renderHighlight(this.parentNode); + } + } else { + mergeIntervals(); // merging intervals immediately + } + s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []); + }) + ); +} + +function startAsc(a, b) { return a[0] - b[0]; } + +function renderAxisBrush(axisBrush) { + + var background = axisBrush.selectAll('.background').data(__repeat_559); + + 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 ' + _$constants_563.verticalPadding + ')'); + + background + .call(attachDragBehavior) + .attr('height', function(d) { + return d.height - _$constants_563.verticalPadding; + }); + + var highlightShadow = axisBrush.selectAll('.highlight-shadow').data(__repeat_559); // we have a set here, can't call it `extent` + + highlightShadow.enter() + .append('line') + .classed('highlight-shadow', true) + .attr('x', -_$constants_563.bar.width / 2) + .attr('stroke-width', _$constants_563.bar.width + _$constants_563.bar.strokeWidth) + .attr('stroke', _$constants_563.bar.strokeColor) + .attr('opacity', _$constants_563.bar.strokeOpacity) + .attr('stroke-linecap', 'butt'); + + highlightShadow + .attr('y1', function(d) { return d.height; }) + .call(styleHighlight); + + var highlight = axisBrush.selectAll('.highlight').data(__repeat_559); // we have a set here, can't call it `extent` + + highlight.enter() + .append('line') + .classed('highlight', true) + .attr('x', -_$constants_563.bar.width / 2) + .attr('stroke-width', _$constants_563.bar.width - _$constants_563.bar.strokeWidth) + .attr('stroke', _$constants_563.bar.fillColor) + .attr('opacity', _$constants_563.bar.fillOpacity) + .attr('stroke-linecap', 'butt'); + + highlight + .attr('y1', function(d) { return d.height; }) + .call(styleHighlight); +} + +function ensureAxisBrush(axisOverlays) { + var axisBrush = axisOverlays.selectAll('.' + _$constants_563.cn.axisBrush) + .data(__repeat_559, keyFun); + + axisBrush.enter() + .append('g') + .classed(_$constants_563.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 = [[0, 1]]; +} + +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); + 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 = [ + ordinalScaleSnapLo(sortedTickVals, ri[0], []), + ordinalScaleSnapHi(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]; +} + +var _$axisbrush_559 = { + makeBrush: makeBrush, + ensureAxisBrush: ensureAxisBrush, + cleanRanges: cleanRanges +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$browser_181 = require('glslify'); */; +var vertexShaderSource = _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]); +var contextShaderSource = _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depth,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]); +var pickVertexShaderSource = _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n fragColor = vec4(pf.rgb, 1.0);\n}\n"]); +var fragmentShaderSource = _$browser_181(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]); + +/* removed: var _$lib_425 = require('../../lib'); */; + +// don't change; otherwise near/far plane lines are lost +var depthLimitEpsilon = 1e-6; +// just enough buffer for an extra bit at single-precision floating point +// which on [0, 1] is 6e-8 (1/2^24) +var filterEpsilon = 1e-7; + +// precision of multiselect is the full range divided into this many parts +var maskHeight = 2048; var gpuDimensionCount = 64; var sectionVertexCount = 2; var vec4NumberCount = 4; +var bitsPerByte = 8; +var channelCount = gpuDimensionCount / bitsPerByte; // == 8 bytes needed to have 64 bits var contextColor = [119, 119, 119]; // middle gray to not drawn the focus; looks good on a black or white background var dummyPixel = new Uint8Array(4); var pickPixel = new Uint8Array(4); +var paletteTextureConfig = { + shape: [256, 1], + format: 'rgba', + type: 'uint8', + mag: 'nearest', + min: 'nearest' +}; + function ensureDraw(regl) { regl.read({ x: 0, @@ -89756,7 +91179,8 @@ function calcPickColor(j, rgbIndex) { return (j >>> 8 * rgbIndex) % 256 / 255; } -function makePoints(sampleCount, dimensionCount, dimensions, color) { +function makePoints(sampleCount, dimensions, color) { + var dimensionCount = dimensions.length; var points = []; for(var j = 0; j < sampleCount; j++) { @@ -89775,7 +91199,6 @@ function makePoints(sampleCount, dimensionCount, dimensions, color) { } function makeVecAttr(sampleCount, points, vecIndex) { - var i, j, k; var pointPairs = []; @@ -89793,36 +91216,26 @@ function makeVecAttr(sampleCount, points, vecIndex) { return pointPairs; } -function makeAttributes(sampleCount, points) { - - var vecIndices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - var vectors = vecIndices.map(function(vecIndex) {return makeVecAttr(sampleCount, points, vecIndex);}); +function setAttributes(attributes, sampleCount, points) { + for(var i = 0; i < 16; i++) { + attributes['p' + i.toString(16)](makeVecAttr(sampleCount, points, i)); + } +} +function emptyAttributes(regl) { var attributes = {}; - vectors.forEach(function(v, vecIndex) { - attributes['p' + vecIndex.toString(16)] = v; - }); - + for(var i = 0; i < 16; i++) { + attributes['p' + i.toString(16)] = regl.buffer({usage: 'dynamic', type: 'float', data: null}); + } return attributes; } -function valid(i, offset, panelCount) { - return i + offset <= panelCount; -} - -var _$lines_502 = function(canvasGL, d, scatter) { - var model = d.model, - vm = d.viewModel, - domain = model.domain; +var _$lines_566 = function(canvasGL, d) { + // context & pick describe which canvas we're talking about - won't change with new data + var context = d.context; + var pick = d.pick; - var lines = model.lines, - canvasWidth = model.canvasWidth, - canvasHeight = model.canvasHeight, - initialDimensions = vm.dimensions, - initialPanels = vm.panels, - unitToColor = model.unitToColor, - context = d.context, - pick = d.pick; + var regl = d.regl; var renderState = { currentRafs: {}, @@ -89830,39 +91243,23 @@ var _$lines_502 = function(canvasGL, d, scatter) { clearOnly: false }; - var initialDims = initialDimensions.slice(); - - var dimensionCount = initialDims.length; - var sampleCount = initialDims[0] ? initialDims[0].values.length : 0; - - var focusAlphaBlending = context; - - var color = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color; - var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3)); - var overdrag = lines.canvasOverdrag; - - var panelCount = initialPanels.length; + // 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 points = makePoints(sampleCount, dimensionCount, initialDims, color); - var attributes = makeAttributes(sampleCount, points); - - var regl = d.regl; - - var paletteTexture = regl.texture({ - shape: [256, 1], - format: 'rgba', - type: 'uint8', - mag: 'nearest', - min: 'nearest', - data: palette(unitToColor, context, Math.round((context ? contextOpacity : 1) * 255)) - }); + update(d); var glAes = regl({ profile: false, blend: { - enable: focusAlphaBlending, + enable: context, func: { srcRGB: 'src alpha', dstRGB: 'one minus src alpha', @@ -89877,7 +91274,7 @@ var _$lines_502 = function(canvasGL, d, scatter) { }, depth: { - enable: !focusAlphaBlending, + enable: !context, mask: true, func: 'less', range: [0, 1] @@ -89908,7 +91305,7 @@ var _$lines_502 = function(canvasGL, d, scatter) { dither: false, - vert: pick ? pickVertexShaderSource : vertexShaderSource, + vert: pick ? pickVertexShaderSource : context ? contextShaderSource : vertexShaderSource, frag: fragmentShaderSource, @@ -89936,13 +91333,32 @@ var _$lines_502 = function(canvasGL, d, scatter) { loD: regl.prop('loD'), hiD: regl.prop('hiD'), palette: paletteTexture, - colorClamp: regl.prop('colorClamp'), - scatter: regl.prop('scatter') + mask: regl.prop('maskTexture'), + maskHeight: regl.prop('maskHeight'), + colorClamp: regl.prop('colorClamp') }, 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 = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color; + var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3)); + + var points = makePoints(sampleCount, initialDims, color); + setAttributes(attributes, sampleCount, points); + + paletteTexture = regl.texture(_$lib_425.extendFlat({ + data: palette(model.unitToColor, context, Math.round((context ? contextOpacity : 1) * 255)) + }, paletteTextureConfig)); + } + var colorClamp = [0, 1]; function setColorDomain(unitDomain) { @@ -89952,26 +91368,27 @@ var _$lines_502 = function(canvasGL, d, scatter) { var previousAxisOrder = []; - function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, scatter, I, leftmost, rightmost) { + function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, I, leftmost, rightmost, constraints) { var loHi, abcd, d, index; var leftRight = [i, ii]; - var filterEpsilon = _$constants_499.verticalPadding / canvasPanelSizeY; var dims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); - var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); for(loHi = 0; loHi < 2; loHi++) { index = leftRight[loHi]; for(abcd = 0; abcd < 4; abcd++) { for(d = 0; d < 16; d++) { - var dimP = d + 16 * abcd; dims[loHi][abcd][d] = d + 16 * abcd === index ? 1 : 0; - lims[loHi][abcd][d] = (!context && valid(d, 16 * abcd, panelCount) ? initialDims[dimP === 0 ? 0 : 1 + ((dimP - 1) % (initialDims.length - 1))].filter[loHi] : loHi) + (2 * loHi - 1) * filterEpsilon; } } } - return { + var overdrag = model.lines.canvasOverdrag; + var domain = model.domain; + var canvasWidth = model.canvasWidth; + var canvasHeight = model.canvasHeight; + + var itemModel = _$lib_425.extendFlat({ key: crossfilterDimensionIndex, resolution: [canvasWidth, canvasHeight], viewBoxPosition: [x + overdrag, y], @@ -89988,17 +91405,7 @@ var _$lines_502 = function(canvasGL, d, scatter) { dim2C: dims[1][2], dim2D: dims[1][3], - loA: lims[0][0], - loB: lims[0][1], - loC: lims[0][2], - loD: lims[0][3], - hiA: lims[1][0], - hiB: lims[1][1], - hiC: lims[1][2], - hiD: lims[1][3], - colorClamp: colorClamp, - scatter: scatter || 0, scissorX: (I === leftmost ? 0 : x + overdrag) + (model.pad.l - overdrag) + model.layoutWidth * domain.x[0], scissorWidth: (I === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (I === leftmost ? x + overdrag : 0), @@ -90009,11 +91416,87 @@ var _$lines_502 = function(canvasGL, d, scatter) { viewportY: model.pad.b + model.layoutHeight * domain.y[0], viewportWidth: canvasWidth, viewportHeight: canvasHeight + }, constraints); + + return itemModel; + } + + function makeConstraints() { + var loHi, abcd, d; + + var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); + + for(loHi = 0; loHi < 2; loHi++) { + for(abcd = 0; abcd < 4; abcd++) { + for(d = 0; d < 16; d++) { + var dimP = d + 16 * abcd; + var lim; + if(dimP < initialDims.length) { + lim = initialDims[dimP].brush.filter.getBounds()[loHi]; + } + else lim = loHi; + lims[loHi][abcd][d] = lim + (2 * loHi - 1) * filterEpsilon; + } + } + } + + function expandedPixelRange(dim, bounds) { + var maskHMinus = maskHeight - 1; + return [ + Math.max(0, Math.floor(bounds[0] * maskHMinus)), + Math.min(maskHMinus, Math.ceil(bounds[1] * maskHMinus)) + ]; + } + + var mask = Array.apply(null, new Array(maskHeight * channelCount)).map(function() { + return 255; + }); + for(var dimIndex = 0; dimIndex < initialDims.length; dimIndex++) { + var bitIndex = dimIndex % bitsPerByte; + var byteIndex = (dimIndex - bitIndex) / bitsPerByte; + var bitMask = Math.pow(2, bitIndex); + var dim = initialDims[dimIndex]; + var ranges = dim.brush.filter.get(); + if(ranges.length < 2) continue; // bail if the bounding box based filter is sufficient + + var prevEnd = expandedPixelRange(dim, ranges[0])[1]; + for(var ri = 1; ri < ranges.length; ri++) { + var nextRange = expandedPixelRange(dim, ranges[ri]); + for(var pi = prevEnd + 1; pi < nextRange[0]; pi++) { + mask[pi * channelCount + byteIndex] &= ~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: [channelCount, 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: lims[0][0], + loB: lims[0][1], + loC: lims[0][2], + loD: lims[0][3], + hiA: lims[1][0], + hiB: lims[1][1], + hiC: lims[1][2], + hiD: lims[1][3] }; } function renderGLParcoords(panels, setChanged, clearOnly) { - + var panelCount = panels.length; var I; var leftmost, rightmost, lowestX = Infinity, highestX = -Infinity; @@ -90031,8 +91514,9 @@ var _$lines_502 = function(canvasGL, d, scatter) { if(panelCount === 0) { // clear canvas here, as the panel iteration below will not enter the loop body - clear(regl, 0, 0, canvasWidth, canvasHeight); + clear(regl, 0, 0, model.canvasWidth, model.canvasHeight); } + var constraints = context ? {} : makeConstraints(); for(I = 0; I < panelCount; I++) { var panel = panels[I]; @@ -90047,9 +91531,9 @@ var _$lines_502 = function(canvasGL, d, scatter) { var xTo = x + panelSizeX; if(setChanged || !previousAxisOrder[i] || previousAxisOrder[i][0] !== x || previousAxisOrder[i][1] !== xTo) { previousAxisOrder[i] = [x, xTo]; - var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, scatter || dim1.scatter ? 1 : 0, I, leftmost, rightmost); + var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, I, leftmost, rightmost, constraints); renderState.clearOnly = clearOnly; - renderBlock(regl, glAes, renderState, setChanged ? lines.blockLineCount : sampleCount, sampleCount, item); + renderBlock(regl, glAes, renderState, setChanged ? model.lines.blockLineCount : sampleCount, sampleCount, item); } } } @@ -90080,6 +91564,8 @@ var _$lines_502 = function(canvasGL, d, scatter) { function destroy() { canvasGL.style['pointer-events'] = 'none'; paletteTexture.destroy(); + if(maskTexture) maskTexture.destroy(); + for(var k in attributes) attributes[k].destroy(); } return { @@ -90087,7 +91573,8 @@ var _$lines_502 = function(canvasGL, d, scatter) { render: renderGLParcoords, readPixel: readPixel, readPixels: readPixels, - destroy: destroy + destroy: destroy, + update: update }; }; @@ -90101,21 +91588,23 @@ var _$lines_502 = function(canvasGL, d, scatter) { 'use strict'; -/* removed: var _$lines_502 = require('./lines'); */; -/* removed: var _$constants_499 = require('./constants'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$d3_68 = require('d3'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; -var keyFun = _$gup_360.keyFun; -var __repeat_503 = _$gup_360.repeat; -var unwrap = _$gup_360.unwrap; +/* removed: var _$lines_566 = require('./lines'); */; +/* removed: var _$constants_563 = require('./constants'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$d3_71 = require('d3'); */; +/* removed: var _$drawing_326 = require('../../components/drawing'); */; +/* removed: var _$gup_422 = require('../../lib/gup'); */; +var __keyFun_567 = _$gup_422.keyFun; +var __repeat_567 = _$gup_422.repeat; +var unwrap = _$gup_422.unwrap; +/* removed: var _$axisbrush_559 = require('./axisbrush'); */; -function visible(dimension) {return !('visible' in dimension) || dimension.visible;} +function visible(dimension) { return !('visible' in dimension) || dimension.visible; } function dimensionExtent(dimension) { - var lo = dimension.range ? dimension.range[0] : _$lib_363.aggNums(Math.min, null, dimension.values, dimension._length); - var hi = dimension.range ? dimension.range[1] : _$lib_363.aggNums(Math.max, null, dimension.values, dimension._length); + var lo = dimension.range ? dimension.range[0] : _$lib_425.aggNums(Math.min, null, dimension.values, dimension._length); + var hi = dimension.range ? dimension.range[1] : _$lib_425.aggNums(Math.max, null, dimension.values, dimension._length); if(isNaN(lo) || !isFinite(lo)) { lo = 0; @@ -90127,10 +91616,7 @@ function dimensionExtent(dimension) { // avoid a degenerate (zero-width) domain if(lo === hi) { - if(lo === void(0)) { - lo = 0; - hi = 1; - } else if(lo === 0) { + if(lo === 0) { // no use to multiplying zero, so add/subtract in this case lo -= 1; hi += 1; @@ -90144,68 +91630,63 @@ function dimensionExtent(dimension) { return [lo, hi]; } -function ordinalScaleSnap(scale, v) { - var i, a, prevDiff, prevValue, diff; - for(i = 0, a = scale.range(), prevDiff = Infinity, prevValue = a[0], diff; i < a.length; i++) { - if((diff = Math.abs(a[i] - v)) > prevDiff) { - return prevValue; - } - prevDiff = diff; - prevValue = a[i]; - } - return a[a.length - 1]; -} - function toText(formatter, texts) { - return function(v, i) { - if(texts) { + if(texts) { + return function(v, i) { var text = texts[i]; - if(text === null || text === undefined) { - return formatter(v); - } else { - return text; - } - } else { - return formatter(v); - } - }; + if(text === null || text === undefined) return formatter(v); + return text; + }; + } + return formatter; } -function domainScale(height, padding, dimension) { +function domainScale(height, padding, dimension, tickvals, ticktext) { var extent = dimensionExtent(dimension); - var texts = dimension.ticktext; - return dimension.tickvals ? - _$d3_68.scale.ordinal() - .domain(dimension.tickvals.map(toText(_$d3_68.format(dimension.tickformat), texts))) - .range(dimension.tickvals - .map(function(d) {return (d - extent[0]) / (extent[1] - extent[0]);}) - .map(function(d) {return (height - padding + d * (padding - (height - padding)));})) : - _$d3_68.scale.linear() - .domain(extent) - .range([height - padding, padding]); + if(tickvals) { + return _$d3_71.scale.ordinal() + .domain(tickvals.map(toText(_$d3_71.format(dimension.tickformat), ticktext))) + .range(tickvals + .map(function(d) { + var unitVal = (d - extent[0]) / (extent[1] - extent[0]); + return (height - padding + unitVal * (2 * padding - height)); + }) + ); + } + return _$d3_71.scale.linear() + .domain(extent) + .range([height - padding, padding]); } -function unitScale(height, padding) {return _$d3_68.scale.linear().range([height - padding, padding]);} -function domainToUnitScale(dimension) {return _$d3_68.scale.linear().domain(dimensionExtent(dimension));} +function unitToPaddedPx(height, padding) { return _$d3_71.scale.linear().range([padding, height - padding]); } + +function domainToPaddedUnitScale(dimension, padFraction) { + return _$d3_71.scale.linear() + .domain(dimensionExtent(dimension)) + .range([padFraction, 1 - padFraction]); +} function ordinalScale(dimension) { + if(!dimension.tickvals) return; + var extent = dimensionExtent(dimension); - return dimension.tickvals && _$d3_68.scale.ordinal() - .domain(dimension.tickvals) - .range(dimension.tickvals.map(function(d) {return (d - extent[0]) / (extent[1] - extent[0]);})); + return _$d3_71.scale.ordinal() + .domain(dimension.tickvals) + .range(dimension.tickvals.map(function(d) { + return (d - extent[0]) / (extent[1] - extent[0]); + })); } function unitToColorScale(cscale) { - var colorStops = cscale.map(function(d) {return d[0];}); - var colorStrings = cscale.map(function(d) {return d[1];}); - var colorTuples = colorStrings.map(function(c) {return _$d3_68.rgb(c);}); - var prop = function(n) {return function(o) {return o[n];};}; + var colorStops = cscale.map(function(d) { return d[0]; }); + var colorTuples = cscale.map(function(d) { return _$d3_71.rgb(d[1]); }); + var prop = function(n) { return function(o) { return o[n]; }; }; // We can't use d3 color interpolation as we may have non-uniform color palette raster // (various color stop distances). var polylinearUnitScales = 'rgb'.split('').map(function(key) { - return _$d3_68.scale.linear() + return _$d3_71.scale.linear() .clamp(true) .domain(colorStops) .range(colorTuples.map(prop(key))); @@ -90218,6 +91699,12 @@ function unitToColorScale(cscale) { }; } +function someFiltersActive(view) { + return view.dimensions.some(function(p) { + return p.brush.filterSpecified; + }); +} + function model(layout, d, i) { var cd0 = unwrap(d), trace = cd0.trace, @@ -90231,14 +91718,14 @@ function model(layout, d, i) { tickFont = trace.tickfont, rangeFont = trace.rangefont; - var lines = _$lib_363.extendDeep({}, line, { - color: lineColor.map(domainToUnitScale({ + var lines = _$lib_425.extendDeepNoArrays({}, line, { + color: lineColor.map(_$d3_71.scale.linear().domain(dimensionExtent({ values: lineColor, range: [line.cmin, line.cmax], _length: trace._commonLength - })), - blockLineCount: _$constants_499.blockLineCount, - canvasOverdrag: _$constants_499.overdrag * _$constants_499.canvasPixelRatio + }))), + blockLineCount: _$constants_563.blockLineCount, + canvasOverdrag: _$constants_563.overdrag * _$constants_563.canvasPixelRatio }); var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0])); @@ -90252,7 +91739,7 @@ function model(layout, d, i) { key: i, colCount: dimensions.filter(visible).length, dimensions: dimensions, - tickDistance: _$constants_499.tickDistance, + tickDistance: _$constants_563.tickDistance, unitToColor: unitToColorScale(cscale), lines: lines, labelFont: labelFont, @@ -90264,15 +91751,15 @@ function model(layout, d, i) { translateX: domain.x[0] * width, translateY: layout.height - domain.y[1] * layout.height, pad: pad, - canvasWidth: rowContentWidth * _$constants_499.canvasPixelRatio + 2 * lines.canvasOverdrag, - canvasHeight: rowHeight * _$constants_499.canvasPixelRatio, + canvasWidth: rowContentWidth * _$constants_563.canvasPixelRatio + 2 * lines.canvasOverdrag, + canvasHeight: rowHeight * _$constants_563.canvasPixelRatio, width: rowContentWidth, height: rowHeight, - canvasPixelRatio: _$constants_499.canvasPixelRatio + canvasPixelRatio: _$constants_563.canvasPixelRatio }; } -function viewModel(model) { +function viewModel(state, callbacks, model) { var width = model.width; var height = model.height; @@ -90281,53 +91768,128 @@ function viewModel(model) { var xScale = function(d) {return width * d / Math.max(1, model.colCount - 1);}; - var unitPad = _$constants_499.verticalPadding / (height * canvasPixelRatio); - var unitPadScale = (1 - 2 * unitPad); - var paddedUnitScale = function(d) {return unitPad + unitPadScale * d;}; + var unitPad = _$constants_563.verticalPadding / height; + var _unitToPaddedPx = unitToPaddedPx(height, _$constants_563.verticalPadding); var viewModel = { key: model.key, xScale: xScale, - model: model + model: model, + inBrushDrag: false // consider factoring it out and putting it in a centralized global-ish gesture state object }; var uniqueKeys = {}; viewModel.dimensions = dimensions.filter(visible).map(function(dimension, i) { - var domainToUnit = domainToUnitScale(dimension); + var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad); var foundKey = uniqueKeys[dimension.label]; uniqueKeys[dimension.label] = (foundKey || 0) + 1; var key = dimension.label + (foundKey ? '__' + foundKey : ''); + var specifiedConstraint = dimension.constraintrange; + var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length; + if(filterRangeSpecified && !Array.isArray(specifiedConstraint[0])) { + specifiedConstraint = [specifiedConstraint]; + } + var filterRange = filterRangeSpecified ? + specifiedConstraint.map(function(d) { return d.map(domainToPaddedUnit); }) : + [[0, 1]]; + var brushMove = function() { + var p = viewModel; + p.focusLayer && p.focusLayer.render(p.panels, true); + var filtersActive = someFiltersActive(p); + if(!state.contextShown() && filtersActive) { + p.contextLayer && p.contextLayer.render(p.panels, true); + state.contextShown(true); + } else if(state.contextShown() && !filtersActive) { + p.contextLayer && p.contextLayer.render(p.panels, true, true); + state.contextShown(false); + } + }; var truncatedValues = dimension.values; if(truncatedValues.length > dimension._length) { truncatedValues = truncatedValues.slice(0, dimension._length); } + var tickvals = dimension.tickvals; + var ticktext; + function makeTickItem(v, i) { return {val: v, text: ticktext[i]}; } + function sortTickItem(a, b) { return a.val - b.val; } + if(Array.isArray(tickvals) && tickvals.length) { + ticktext = dimension.ticktext; + + // ensure ticktext and tickvals have same length + if(!Array.isArray(ticktext) || !ticktext.length) { + ticktext = tickvals.map(_$d3_71.format(dimension.tickformat)); + } + else if(ticktext.length > tickvals.length) { + ticktext = ticktext.slice(0, tickvals.length); + } + else if(tickvals.length > ticktext.length) { + tickvals = tickvals.slice(0, ticktext.length); + } + + // check if we need to sort tickvals/ticktext + for(var j = 1; j < tickvals.length; j++) { + if(tickvals[j] < tickvals[j - 1]) { + var tickItems = tickvals.map(makeTickItem).sort(sortTickItem); + for(var k = 0; k < tickvals.length; k++) { + tickvals[k] = tickItems[k].val; + ticktext[k] = tickItems[k].text; + } + break; + } + } + } + else tickvals = undefined; + return { key: key, label: dimension.label, tickFormat: dimension.tickformat, - tickvals: dimension.tickvals, - ticktext: dimension.ticktext, - ordinal: !!dimension.tickvals, - scatter: _$constants_499.scatter || dimension.scatter, + tickvals: tickvals, + ticktext: ticktext, + ordinal: !!tickvals, + multiselect: dimension.multiselect, xIndex: i, crossfilterDimensionIndex: i, visibleIndex: dimension._index, height: height, values: truncatedValues, - paddedUnitValues: truncatedValues.map(domainToUnit).map(paddedUnitScale), + paddedUnitValues: truncatedValues.map(domainToPaddedUnit), + unitTickvals: tickvals && tickvals.map(domainToPaddedUnit), xScale: xScale, x: xScale(i), canvasX: xScale(i) * canvasPixelRatio, - unitScale: unitScale(height, _$constants_499.verticalPadding), - domainScale: domainScale(height, _$constants_499.verticalPadding, dimension), + unitToPaddedPx: _unitToPaddedPx, + domainScale: domainScale(height, _$constants_563.verticalPadding, dimension, tickvals, ticktext), ordinalScale: ordinalScale(dimension), - domainToUnitScale: domainToUnit, - filter: dimension.constraintrange ? dimension.constraintrange.map(domainToUnit) : [0, 1], parent: viewModel, - model: model + model: model, + brush: _$axisbrush_559.makeBrush( + state, + filterRangeSpecified, + filterRange, + function() { + state.linePickActive(false); + }, + brushMove, + function(f) { + var p = viewModel; + p.focusLayer.render(p.panels, true); + p.pickLayer && p.pickLayer.render(p.panels, true); + state.linePickActive(true); + if(callbacks && callbacks.filterChanged) { + var invScale = domainToPaddedUnit.invert; + + // update gd.data as if a Plotly.restyle were fired + var newRanges = f.map(function(r) { + return r.map(invScale).sort(_$lib_425.sorterAsc); + }).sort(function(a, b) { return a[0] - b[0]; }); + callbacks.filterChanged(p.key, dimension._index, newRanges); + } + } + ) }; }); @@ -90336,61 +91898,32 @@ function viewModel(model) { function styleExtentTexts(selection) { selection - .classed(_$constants_499.cn.axisExtentText, true) + .classed(_$constants_563.cn.axisExtentText, true) .attr('text-anchor', 'middle') .style('cursor', 'default') .style('user-select', 'none'); } -var _$parcoords_503 = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) { - var domainBrushing = false; +function parcoordsInteractionState() { var linePickActive = true; + var contextShown = false; + return { + linePickActive: function(val) {return arguments.length ? linePickActive = !!val : linePickActive;}, + contextShown: function(val) {return arguments.length ? contextShown = !!val : contextShown;} + }; +} - function enterSvgDefs(root) { - var defs = root.selectAll('defs') - .data(__repeat_503, keyFun); - - defs.enter() - .append('defs'); - - var filterBarPattern = defs.selectAll('#' + _$constants_499.id.filterBarPattern) - .data(__repeat_503, keyFun); - - filterBarPattern.enter() - .append('pattern') - .attr('id', _$constants_499.id.filterBarPattern) - .attr('patternUnits', 'userSpaceOnUse'); - - filterBarPattern - .attr('x', -_$constants_499.bar.width) - .attr('width', _$constants_499.bar.capturewidth) - .attr('height', function(d) {return d.model.height;}); - - var filterBarPatternGlyph = filterBarPattern.selectAll('rect') - .data(__repeat_503, keyFun); - - filterBarPatternGlyph.enter() - .append('rect') - .attr('shape-rendering', 'crispEdges'); +var _$parcoords_567 = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) { - filterBarPatternGlyph - .attr('height', function(d) {return d.model.height;}) - .attr('width', _$constants_499.bar.width) - .attr('x', _$constants_499.bar.width / 2) - .attr('fill', _$constants_499.bar.fillcolor) - .attr('fill-opacity', _$constants_499.bar.fillopacity) - .attr('stroke', _$constants_499.bar.strokecolor) - .attr('stroke-opacity', _$constants_499.bar.strokeopacity) - .attr('stroke-width', _$constants_499.bar.strokewidth); - } + var state = parcoordsInteractionState(); var vm = styledData .filter(function(d) { return unwrap(d).trace.visible; }) .map(model.bind(0, layout)) - .map(viewModel); + .map(viewModel.bind(0, state, callbacks)); parcoordsLineLayers.each(function(d, i) { - return _$lib_363.extendFlat(d, vm[i]); + return _$lib_425.extendFlat(d, vm[i]); }); var parcoordsLineLayer = parcoordsLineLayers.selectAll('.gl-canvas') @@ -90400,21 +91933,19 @@ var _$parcoords_503 = function(root, svg, parcoordsLineLayers, styledData, layou d.model = d.viewModel ? d.viewModel.model : null; }); - var tweakables = {renderers: [], dimensions: []}; - var lastHovered = null; - parcoordsLineLayer - .filter(function(d) { - return d.pick; - }) + var pickLayer = parcoordsLineLayer.filter(function(d) {return d.pick;}); + + // emit hover / unhover event + pickLayer .style('pointer-events', 'auto') .on('mousemove', function(d) { - if(linePickActive && d.lineLayer && callbacks && callbacks.hover) { - var event = _$d3_68.event; + if(state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) { + var event = _$d3_71.event; var cw = this.width; var ch = this.height; - var pointer = _$d3_68.mouse(this); + var pointer = _$d3_71.mouse(this); var x = pointer[0]; var y = pointer[1]; @@ -90448,193 +91979,145 @@ var _$parcoords_503 = function(root, svg, parcoordsLineLayers, styledData, layou .style('opacity', function(d) {return d.pick ? 0.01 : 1;}); svg.style('background', 'rgba(255, 255, 255, 0)'); - var parcoordsControlOverlay = svg.selectAll('.' + _$constants_499.cn.parcoords) - .data(vm, keyFun); + var parcoordsControlOverlay = svg.selectAll('.' + _$constants_563.cn.parcoords) + .data(vm, __keyFun_567); parcoordsControlOverlay.exit().remove(); parcoordsControlOverlay.enter() .append('g') - .classed(_$constants_499.cn.parcoords, true) - .attr('overflow', 'visible') - .style('box-sizing', 'content-box') - .style('position', 'absolute') - .style('left', 0) - .style('overflow', 'visible') + .classed(_$constants_563.cn.parcoords, true) .style('shape-rendering', 'crispEdges') - .style('pointer-events', 'none') - .call(enterSvgDefs); + .style('pointer-events', 'none'); - parcoordsControlOverlay - .attr('width', function(d) {return d.model.width + d.model.pad.l + d.model.pad.r;}) - .attr('height', function(d) {return d.model.height + d.model.pad.t + d.model.pad.b;}) - .attr('transform', function(d) { - return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')'; - }); + parcoordsControlOverlay.attr('transform', function(d) { + return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')'; + }); - var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + _$constants_499.cn.parcoordsControlView) - .data(__repeat_503, keyFun); + var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + _$constants_563.cn.parcoordsControlView) + .data(__repeat_567, __keyFun_567); parcoordsControlView.enter() .append('g') - .classed(_$constants_499.cn.parcoordsControlView, true) - .style('box-sizing', 'content-box'); - - parcoordsControlView - .attr('transform', function(d) {return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')';}); + .classed(_$constants_563.cn.parcoordsControlView, true); - var yAxis = parcoordsControlView.selectAll('.' + _$constants_499.cn.yAxis) - .data(function(vm) {return vm.dimensions;}, keyFun); + parcoordsControlView.attr('transform', function(d) { + return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')'; + }); - function someFiltersActive(view) { - return view.dimensions.some(function(p) {return p.filter[0] !== 0 || p.filter[1] !== 1;}); - } + var yAxis = parcoordsControlView.selectAll('.' + _$constants_563.cn.yAxis) + .data(function(vm) { return vm.dimensions; }, __keyFun_567); - function updatePanelLayoutParcoords(yAxis, vm) { - var panels = vm.panels || (vm.panels = []); - var yAxes = yAxis.each(function(d) {return d;})[vm.key].map(function(e) {return e.__data__;}); - var panelCount = yAxes.length - 1; - var rowCount = 1; - for(var row = 0; row < rowCount; row++) { - for(var p = 0; p < panelCount; p++) { - var panel = panels[p + row * panelCount] || (panels[p + row * panelCount] = {}); - var dim1 = yAxes[p]; - var dim2 = yAxes[p + 1]; - panel.dim1 = dim1; - panel.dim2 = dim2; - panel.canvasX = dim1.canvasX; - panel.panelSizeX = dim2.canvasX - dim1.canvasX; - panel.panelSizeY = vm.model.canvasHeight / rowCount; - panel.y = row * panel.panelSizeY; - panel.canvasY = vm.model.canvasHeight - panel.y - panel.panelSizeY; - } - } - } - - function updatePanelLayoutScatter(yAxis, vm) { + function updatePanelLayout(yAxis, vm) { var panels = vm.panels || (vm.panels = []); - var yAxes = yAxis.each(function(d) {return d;})[vm.key].map(function(e) {return e.__data__;}); - var panelCount = yAxes.length - 1; - var rowCount = panelCount; - for(var row = 0; row < panelCount; row++) { - for(var p = 0; p < panelCount; p++) { - var panel = panels[p + row * panelCount] || (panels[p + row * panelCount] = {}); - var dim1 = yAxes[p]; - var dim2 = yAxes[p + 1]; - panel.dim1 = yAxes[row + 1]; - panel.dim2 = dim2; - panel.canvasX = dim1.canvasX; - panel.panelSizeX = dim2.canvasX - dim1.canvasX; - panel.panelSizeY = vm.model.canvasHeight / rowCount; - panel.y = row * panel.panelSizeY; - panel.canvasY = vm.model.canvasHeight - panel.y - panel.panelSizeY; - } + var dimData = yAxis.data(); + var panelCount = dimData.length - 1; + for(var p = 0; p < panelCount; p++) { + var panel = panels[p] || (panels[p] = {}); + var dim1 = dimData[p]; + var dim2 = dimData[p + 1]; + panel.dim1 = dim1; + panel.dim2 = dim2; + panel.canvasX = dim1.canvasX; + panel.panelSizeX = dim2.canvasX - dim1.canvasX; + panel.panelSizeY = vm.model.canvasHeight; + panel.y = 0; + panel.canvasY = 0; } } - function updatePanelLayout(yAxis, vm) { - return (_$constants_499.scatter ? updatePanelLayoutScatter : updatePanelLayoutParcoords)(yAxis, vm); - } - yAxis.enter() .append('g') - .classed(_$constants_499.cn.yAxis, true) - .each(function(d) {tweakables.dimensions.push(d);}); + .classed(_$constants_563.cn.yAxis, true); parcoordsControlView.each(function(vm) { updatePanelLayout(yAxis, vm); }); parcoordsLineLayer - .filter(function(d) {return !!d.viewModel;}) .each(function(d) { - d.lineLayer = _$lines_502(this, d, _$constants_499.scatter); - d.viewModel[d.key] = d.lineLayer; - tweakables.renderers.push(function() {d.lineLayer.render(d.viewModel.panels, true);}); - d.lineLayer.render(d.viewModel.panels, !d.context); + if(d.viewModel) { + if(d.lineLayer) d.lineLayer.update(d); + else d.lineLayer = _$lines_566(this, d); + + d.viewModel[d.key] = d.lineLayer; + d.lineLayer.render(d.viewModel.panels, !d.context); + } }); - yAxis - .attr('transform', function(d) {return 'translate(' + d.xScale(d.xIndex) + ', 0)';}); + yAxis.attr('transform', function(d) { + return 'translate(' + d.xScale(d.xIndex) + ', 0)'; + }); - yAxis - .call(_$d3_68.behavior.drag() - .origin(function(d) {return d;}) - .on('drag', function(d) { - var p = d.parent; - linePickActive = false; - if(domainBrushing) { - return; - } - d.x = Math.max(-_$constants_499.overdrag, Math.min(d.model.width + _$constants_499.overdrag, _$d3_68.event.x)); - d.canvasX = d.x * d.model.canvasPixelRatio; - yAxis - .sort(function(a, b) {return a.x - b.x;}) - .each(function(dd, i) { - dd.xIndex = i; - dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex); - dd.canvasX = dd.x * dd.model.canvasPixelRatio; - }); + // drag column for reordering columns + yAxis.call(_$d3_71.behavior.drag() + .origin(function(d) { return d; }) + .on('drag', function(d) { + var p = d.parent; + state.linePickActive(false); + d.x = Math.max(-_$constants_563.overdrag, Math.min(d.model.width + _$constants_563.overdrag, _$d3_71.event.x)); + d.canvasX = d.x * d.model.canvasPixelRatio; + yAxis + .sort(function(a, b) { return a.x - b.x; }) + .each(function(dd, i) { + dd.xIndex = i; + dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex); + dd.canvasX = dd.x * dd.model.canvasPixelRatio; + }); - updatePanelLayout(yAxis, p); + updatePanelLayout(yAxis, p); - yAxis.filter(function(dd) {return Math.abs(d.xIndex - dd.xIndex) !== 0;}) - .attr('transform', function(d) {return 'translate(' + d.xScale(d.xIndex) + ', 0)';}); - _$d3_68.select(this).attr('transform', 'translate(' + d.x + ', 0)'); - yAxis.each(function(dd, i, ii) {if(ii === d.parent.key) p.dimensions[i] = dd;}); - p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); - p.focusLayer.render && p.focusLayer.render(p.panels); - }) - .on('dragend', function(d) { - var p = d.parent; - if(domainBrushing) { - if(domainBrushing === 'ending') { - domainBrushing = false; - } - return; - } - d.x = d.xScale(d.xIndex); - d.canvasX = d.x * d.model.canvasPixelRatio; - updatePanelLayout(yAxis, p); - _$d3_68.select(this) - .attr('transform', function(d) {return 'translate(' + d.x + ', 0)';}); - p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); - p.focusLayer && p.focusLayer.render(p.panels); - p.pickLayer && p.pickLayer.render(p.panels, true); - linePickActive = true; - - if(callbacks && callbacks.axesMoved) { - callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;})); - } - }) - ); + yAxis.filter(function(dd) { return Math.abs(d.xIndex - dd.xIndex) !== 0; }) + .attr('transform', function(d) { return 'translate(' + d.xScale(d.xIndex) + ', 0)'; }); + _$d3_71.select(this).attr('transform', 'translate(' + d.x + ', 0)'); + yAxis.each(function(dd, i, ii) { if(ii === d.parent.key) p.dimensions[i] = dd; }); + p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); + p.focusLayer.render && p.focusLayer.render(p.panels); + }) + .on('dragend', function(d) { + var p = d.parent; + d.x = d.xScale(d.xIndex); + d.canvasX = d.x * d.model.canvasPixelRatio; + updatePanelLayout(yAxis, p); + _$d3_71.select(this) + .attr('transform', function(d) { return 'translate(' + d.x + ', 0)'; }); + p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); + p.focusLayer && p.focusLayer.render(p.panels); + p.pickLayer && p.pickLayer.render(p.panels, true); + state.linePickActive(true); + + if(callbacks && callbacks.axesMoved) { + callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;})); + } + }) + ); yAxis.exit() .remove(); - var axisOverlays = yAxis.selectAll('.' + _$constants_499.cn.axisOverlays) - .data(__repeat_503, keyFun); + var axisOverlays = yAxis.selectAll('.' + _$constants_563.cn.axisOverlays) + .data(__repeat_567, __keyFun_567); axisOverlays.enter() .append('g') - .classed(_$constants_499.cn.axisOverlays, true); + .classed(_$constants_563.cn.axisOverlays, true); - axisOverlays.selectAll('.' + _$constants_499.cn.axis).remove(); + axisOverlays.selectAll('.' + _$constants_563.cn.axis).remove(); - var axis = axisOverlays.selectAll('.' + _$constants_499.cn.axis) - .data(__repeat_503, keyFun); + var axis = axisOverlays.selectAll('.' + _$constants_563.cn.axis) + .data(__repeat_567, __keyFun_567); axis.enter() .append('g') - .classed(_$constants_499.cn.axis, true); + .classed(_$constants_563.cn.axis, true); axis .each(function(d) { var wantedTickCount = d.model.height / d.model.tickDistance; var scale = d.domainScale; var sdom = scale.domain(); - _$d3_68.select(this) - .call(_$d3_68.svg.axis() + _$d3_71.select(this) + .call(_$d3_71.svg.axis() .orient('left') .tickSize(4) .outerTickSize(2) @@ -90642,221 +92125,108 @@ var _$parcoords_503 = function(root, svg, parcoordsLineLayers, styledData, layou .tickValues(d.ordinal ? // and this works for ordinal scales sdom : null) - .tickFormat(d.ordinal ? function(d) {return d;} : null) + .tickFormat(d.ordinal ? function(d) { return d; } : null) .scale(scale)); - _$drawing_264.font(axis.selectAll('text'), d.model.tickFont); + _$drawing_326.font(axis.selectAll('text'), d.model.tickFont); }); - axis - .selectAll('.domain, .tick>line') + axis.selectAll('.domain, .tick>line') .attr('fill', 'none') .attr('stroke', 'black') .attr('stroke-opacity', 0.25) .attr('stroke-width', '1px'); - axis - .selectAll('text') + axis.selectAll('text') .style('text-shadow', '1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff') .style('cursor', 'default') .style('user-select', 'none'); - var axisHeading = axisOverlays.selectAll('.' + _$constants_499.cn.axisHeading) - .data(__repeat_503, keyFun); + var axisHeading = axisOverlays.selectAll('.' + _$constants_563.cn.axisHeading) + .data(__repeat_567, __keyFun_567); axisHeading.enter() .append('g') - .classed(_$constants_499.cn.axisHeading, true); + .classed(_$constants_563.cn.axisHeading, true); - var axisTitle = axisHeading.selectAll('.' + _$constants_499.cn.axisTitle) - .data(__repeat_503, keyFun); + var axisTitle = axisHeading.selectAll('.' + _$constants_563.cn.axisTitle) + .data(__repeat_567, __keyFun_567); axisTitle.enter() .append('text') - .classed(_$constants_499.cn.axisTitle, true) + .classed(_$constants_563.cn.axisTitle, true) .attr('text-anchor', 'middle') .style('cursor', 'ew-resize') .style('user-select', 'none') .style('pointer-events', 'auto'); axisTitle - .attr('transform', 'translate(0,' + -_$constants_499.axisTitleOffset + ')') - .text(function(d) {return d.label;}) - .each(function(d) {_$drawing_264.font(axisTitle, d.model.labelFont);}); + .attr('transform', 'translate(0,' + -_$constants_563.axisTitleOffset + ')') + .text(function(d) { return d.label; }) + .each(function(d) { _$drawing_326.font(_$d3_71.select(this), d.model.labelFont); }); - var axisExtent = axisOverlays.selectAll('.' + _$constants_499.cn.axisExtent) - .data(__repeat_503, keyFun); + var axisExtent = axisOverlays.selectAll('.' + _$constants_563.cn.axisExtent) + .data(__repeat_567, __keyFun_567); axisExtent.enter() .append('g') - .classed(_$constants_499.cn.axisExtent, true); + .classed(_$constants_563.cn.axisExtent, true); - var axisExtentTop = axisExtent.selectAll('.' + _$constants_499.cn.axisExtentTop) - .data(__repeat_503, keyFun); + var axisExtentTop = axisExtent.selectAll('.' + _$constants_563.cn.axisExtentTop) + .data(__repeat_567, __keyFun_567); axisExtentTop.enter() .append('g') - .classed(_$constants_499.cn.axisExtentTop, true); + .classed(_$constants_563.cn.axisExtentTop, true); axisExtentTop - .attr('transform', 'translate(' + 0 + ',' + -_$constants_499.axisExtentOffset + ')'); + .attr('transform', 'translate(' + 0 + ',' + -_$constants_563.axisExtentOffset + ')'); - var axisExtentTopText = axisExtentTop.selectAll('.' + _$constants_499.cn.axisExtentTopText) - .data(__repeat_503, keyFun); + var axisExtentTopText = axisExtentTop.selectAll('.' + _$constants_563.cn.axisExtentTopText) + .data(__repeat_567, __keyFun_567); - function formatExtreme(d) { - return d.ordinal ? function() {return '';} : _$d3_68.format(d.tickFormat); + function extremeText(d, isTop) { + if(d.ordinal) return ''; + var domain = d.domainScale.domain(); + return _$d3_71.format(d.tickFormat)(domain[isTop ? domain.length - 1 : 0]); } axisExtentTopText.enter() .append('text') - .classed(_$constants_499.cn.axisExtentTopText, true) + .classed(_$constants_563.cn.axisExtentTopText, true) .call(styleExtentTexts); axisExtentTopText - .text(function(d) {return formatExtreme(d)(d.domainScale.domain().slice(-1)[0]);}) - .each(function(d) {_$drawing_264.font(axisExtentTopText, d.model.rangeFont);}); + .text(function(d) { return extremeText(d, true); }) + .each(function(d) { _$drawing_326.font(_$d3_71.select(this), d.model.rangeFont); }); - var axisExtentBottom = axisExtent.selectAll('.' + _$constants_499.cn.axisExtentBottom) - .data(__repeat_503, keyFun); + var axisExtentBottom = axisExtent.selectAll('.' + _$constants_563.cn.axisExtentBottom) + .data(__repeat_567, __keyFun_567); axisExtentBottom.enter() .append('g') - .classed(_$constants_499.cn.axisExtentBottom, true); + .classed(_$constants_563.cn.axisExtentBottom, true); axisExtentBottom - .attr('transform', function(d) {return 'translate(' + 0 + ',' + (d.model.height + _$constants_499.axisExtentOffset) + ')';}); + .attr('transform', function(d) { + return 'translate(' + 0 + ',' + (d.model.height + _$constants_563.axisExtentOffset) + ')'; + }); - var axisExtentBottomText = axisExtentBottom.selectAll('.' + _$constants_499.cn.axisExtentBottomText) - .data(__repeat_503, keyFun); + var axisExtentBottomText = axisExtentBottom.selectAll('.' + _$constants_563.cn.axisExtentBottomText) + .data(__repeat_567, __keyFun_567); axisExtentBottomText.enter() .append('text') - .classed(_$constants_499.cn.axisExtentBottomText, true) + .classed(_$constants_563.cn.axisExtentBottomText, true) .attr('dy', '0.75em') .call(styleExtentTexts); axisExtentBottomText - .text(function(d) {return formatExtreme(d)(d.domainScale.domain()[0]);}) - .each(function(d) {_$drawing_264.font(axisExtentBottomText, d.model.rangeFont);}); - - var axisBrush = axisOverlays.selectAll('.' + _$constants_499.cn.axisBrush) - .data(__repeat_503, keyFun); - - var axisBrushEnter = axisBrush.enter() - .append('g') - .classed(_$constants_499.cn.axisBrush, true); - - axisBrush - .each(function(d) { - if(!d.brush) { - d.brush = _$d3_68.svg.brush() - .y(d.unitScale) - .on('brushstart', axisBrushStarted) - .on('brush', axisBrushMoved) - .on('brushend', axisBrushEnded); - if(d.filter[0] !== 0 || d.filter[1] !== 1) { - d.brush.extent(d.filter); - } - _$d3_68.select(this).call(d.brush); - } - }); + .text(function(d) { return extremeText(d); }) + .each(function(d) { _$drawing_326.font(_$d3_71.select(this), d.model.rangeFont); }); - axisBrushEnter - .selectAll('rect') - .attr('x', -_$constants_499.bar.capturewidth / 2) - .attr('width', _$constants_499.bar.capturewidth); - - axisBrushEnter - .selectAll('rect.extent') - .attr('fill', 'url(#' + _$constants_499.id.filterBarPattern + ')') - .style('cursor', 'ns-resize') - .filter(function(d) {return d.filter[0] === 0 && d.filter[1] === 1;}) - .attr('y', -100); // // zero-size rectangle pointer issue workaround - - axisBrushEnter - .selectAll('.resize rect') - .attr('height', _$constants_499.bar.handleheight) - .attr('opacity', 0) - .style('visibility', 'visible'); - - axisBrushEnter - .selectAll('.resize.n rect') - .style('cursor', 'n-resize') - .attr('y', _$constants_499.bar.handleoverlap - _$constants_499.bar.handleheight); - - axisBrushEnter - .selectAll('.resize.s rect') - .style('cursor', 's-resize') - .attr('y', _$constants_499.bar.handleoverlap); - - var justStarted = false; - var contextShown = false; - - function axisBrushStarted() { - justStarted = true; - domainBrushing = true; - } - - function axisBrushMoved(dimension) { - linePickActive = false; - var p = dimension.parent; - var extent = dimension.brush.extent(); - var dimensions = p.dimensions; - var filter = dimensions[dimension.xIndex].filter; - var reset = justStarted && (extent[0] === extent[1]); - if(reset) { - dimension.brush.clear(); - _$d3_68.select(this).select('rect.extent').attr('y', -100); // zero-size rectangle pointer issue workaround - } - var newExtent = reset ? [0, 1] : extent.slice(); - if(newExtent[0] !== filter[0] || newExtent[1] !== filter[1]) { - dimensions[dimension.xIndex].filter = newExtent; - p.focusLayer && p.focusLayer.render(p.panels, true); - var filtersActive = someFiltersActive(p); - if(!contextShown && filtersActive) { - p.contextLayer && p.contextLayer.render(p.panels, true); - contextShown = true; - } else if(contextShown && !filtersActive) { - p.contextLayer && p.contextLayer.render(p.panels, true, true); - contextShown = false; - } - } - justStarted = false; - } - - function axisBrushEnded(dimension) { - var p = dimension.parent; - var extent = dimension.brush.extent(); - var empty = extent[0] === extent[1]; - var dimensions = p.dimensions; - var f = dimensions[dimension.xIndex].filter; - if(!empty && dimension.ordinal) { - f[0] = ordinalScaleSnap(dimension.ordinalScale, f[0]); - f[1] = ordinalScaleSnap(dimension.ordinalScale, f[1]); - if(f[0] === f[1]) { - f[0] = Math.max(0, f[0] - 0.05); - f[1] = Math.min(1, f[1] + 0.05); - } - _$d3_68.select(this).transition().duration(150).call(dimension.brush.extent(f)); - p.focusLayer.render(p.panels, true); - } - p.pickLayer && p.pickLayer.render(p.panels, true); - linePickActive = true; - domainBrushing = 'ending'; - if(callbacks && callbacks.filterChanged) { - var invScale = dimension.domainToUnitScale.invert; - - // update gd.data as if a Plotly.restyle were fired - var newRange = f.map(invScale); - callbacks.filterChanged(p.key, dimension.visibleIndex, newRange); - } - } - - return tweakables; + _$axisbrush_559.ensureAxisBrush(axisOverlays); }; -var _$plot_504 = {}; -(function (global){ /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -90867,27 +92237,16 @@ var _$plot_504 = {}; 'use strict'; -/* removed: var _$parcoords_503 = require('./parcoords'); */; -/* removed: var _$regl_175 = require('regl'); */; +/* removed: var _$parcoords_567 = require('./parcoords'); */; +/* removed: var _$prepareRegl_438 = require('../../lib/prepare_regl'); */; -_$plot_504 = function plot(gd, cdparcoords) { +var _$plot_568 = function plot(gd, cdparcoords) { var fullLayout = gd._fullLayout; var svg = fullLayout._toppaper; var root = fullLayout._paperdiv; var container = fullLayout._glcontainer; - // make sure proper regl instances are created - fullLayout._glcanvas.each(function(d) { - if(d.regl) return; - d.regl = _$regl_175({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio - }); - }); + _$prepareRegl_438(gd); var gdDimensions = {}; var gdDimensionsOriginalOrder = {}; @@ -90899,21 +92258,28 @@ _$plot_504 = function plot(gd, cdparcoords) { gdDimensionsOriginalOrder[i] = gd.data[i].dimensions.slice(); }); - var filterChanged = function(i, originalDimensionIndex, newRange) { + var filterChanged = function(i, originalDimensionIndex, 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 gdDimension = gdDimensionsOriginalOrder[i][originalDimensionIndex]; - var gdConstraintRange = gdDimension.constraintrange; - - if(!gdConstraintRange || gdConstraintRange.length !== 2) { - gdConstraintRange = gdDimension.constraintrange = []; + var newConstraints = newRanges.map(function(r) { return r.slice(); }); + if(!newConstraints.length) { + delete gdDimension.constraintrange; + newConstraints = null; + } + else { + if(newConstraints.length === 1) newConstraints = newConstraints[0]; + gdDimension.constraintrange = newConstraints; + // wrap in another array for restyle event data + newConstraints = [newConstraints]; } - gdConstraintRange[0] = newRange[0]; - gdConstraintRange[1] = newRange[1]; - gd.emit('plotly_restyle'); + var restyleData = {}; + var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange'; + restyleData[aStr] = newConstraints; + gd.emit('plotly_restyle', [restyleData, [i]]); }; var hover = function(eventData) { @@ -90968,7 +92334,7 @@ _$plot_504 = function plot(gd, cdparcoords) { gd.emit('plotly_restyle'); }; - _$parcoords_503( + _$parcoords_567( root, svg, container, @@ -90991,8 +92357,7 @@ _$plot_504 = function plot(gd, cdparcoords) { }); }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$base_plot_496 = {}; +var _$base_plot_560 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -91003,21 +92368,21 @@ var _$base_plot_496 = {}; 'use strict'; -/* removed: var _$d3_68 = require('d3'); */; -var __getModuleCalcData_496 = _$get_data_436.getModuleCalcData; -/* removed: var _$plot_504 = require('./plot'); */; -/* removed: var _$xmlns_namespaces_345 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_71 = require('d3'); */; +var __getModuleCalcData_560 = _$get_data_498.getModuleCalcData; +/* removed: var _$plot_568 = require('./plot'); */; +/* removed: var _$xmlns_namespaces_406 = require('../../constants/xmlns_namespaces'); */; var PARCOORDS = 'parcoords'; -_$base_plot_496.name = PARCOORDS; +_$base_plot_560.name = PARCOORDS; -_$base_plot_496.plot = function(gd) { - var calcData = __getModuleCalcData_496(gd.calcdata, PARCOORDS); - if(calcData.length) _$plot_504(gd, calcData); +_$base_plot_560.plot = function(gd) { + var calcData = __getModuleCalcData_560(gd.calcdata, PARCOORDS)[0]; + if(calcData.length) _$plot_568(gd, calcData); }; -_$base_plot_496.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_560.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadParcoords = (oldFullLayout._has && oldFullLayout._has(PARCOORDS)); var hasParcoords = (newFullLayout._has && newFullLayout._has(PARCOORDS)); @@ -91027,9 +92392,9 @@ _$base_plot_496.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -_$base_plot_496.toSVG = function(gd) { +_$base_plot_560.toSVG = function(gd) { var imageRoot = gd._fullLayout._glimages; - var root = _$d3_68.select(gd).selectAll('.svg-container'); + var root = _$d3_71.select(gd).selectAll('.svg-container'); var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) .selectAll('.gl-canvas-context, .gl-canvas-focus'); @@ -91039,7 +92404,7 @@ _$base_plot_496.toSVG = function(gd) { var image = imageRoot.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_345.svg, + xmlns: _$xmlns_namespaces_406.svg, 'xlink:href': imageData, preserveAspectRatio: 'none', x: 0, @@ -91056,7 +92421,7 @@ _$base_plot_496.toSVG = function(gd) { // on a subsequent interaction. // Firefox works fine without this workaround window.setTimeout(function() { - _$d3_68.selectAll('#filterBarPattern') + _$d3_71.selectAll('#filterBarPattern') .attr('id', 'filterBarPattern'); }, 60); }; @@ -91071,21 +92436,21 @@ _$base_plot_496.toSVG = function(gd) { 'use strict'; -/* removed: var _$hasColorscale_253 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_246 = require('../../components/colorscale/calc'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -var __wrap_497 = _$gup_360.wrap; +/* removed: var _$hasColorscale_315 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_308 = require('../../components/colorscale/calc'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +var __wrap_561 = _$gup_422.wrap; -var _$calc_497 = function calc(gd, trace) { - var cs = !!trace.line.colorscale && _$lib_363.isArrayOrTypedArray(trace.line.color); +var _$calc_561 = function calc(gd, trace) { + var cs = !!trace.line.colorscale && _$lib_425.isArrayOrTypedArray(trace.line.color); var color = cs ? trace.line.color : constHalf(trace._commonLength); var cscale = cs ? trace.line.colorscale : [[0, trace.line.color], [1, trace.line.color]]; - if(_$hasColorscale_253(trace, 'line')) { - _$calc_246(trace, color, 'line', 'c'); + if(_$hasColorscale_315(trace, 'line')) { + _$calc_308(trace, color, 'line', 'c'); } - return __wrap_497({ + return __wrap_561({ lineColor: color, cscale: cscale }); @@ -91110,15 +92475,15 @@ function constHalf(len) { 'use strict'; -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$plots_444 = require('../../plots/plots'); */; -/* removed: var _$colorscale_254 = require('../../components/colorscale'); */; -/* removed: var _$draw_243 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$plots_506 = require('../../plots/plots'); */; +/* removed: var _$colorscale_316 = require('../../components/colorscale'); */; +/* removed: var _$draw_305 = require('../../components/colorbar/draw'); */; -var _$colorbar_498 = function colorbar(gd, cd) { +var _$colorbar_562 = function colorbar(gd, cd) { var trace = cd[0].trace, line = trace.line, cbId = 'cb' + trace.uid; @@ -91126,7 +92491,7 @@ var _$colorbar_498 = function colorbar(gd, cd) { gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if((line === undefined) || !line.showscale) { - _$plots_444.autoMargin(gd, cbId); + _$plots_506.autoMargin(gd, cbId); return; } @@ -91134,12 +92499,12 @@ var _$colorbar_498 = function colorbar(gd, cd) { cmin = line.cmin, cmax = line.cmax; - if(!_$fastIsnumeric_78(cmin)) cmin = _$lib_363.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_78(cmax)) cmax = _$lib_363.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_135(cmin)) cmin = _$lib_425.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_135(cmax)) cmax = _$lib_425.aggNums(Math.max, null, vals); - var cb = cd[0].t.cb = _$draw_243(gd, cbId); - var sclFunc = _$colorscale_254.makeColorScaleFunc( - _$colorscale_254.extractScale( + var cb = cd[0].t.cb = _$draw_305(gd, cbId); + var sclFunc = _$colorscale_316.makeColorScaleFunc( + _$colorscale_316.extractScale( line.colorscale, cmin, cmax @@ -91162,20 +92527,21 @@ var _$colorbar_498 = function colorbar(gd, cd) { 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$attributes_495 = require('./attributes'); */; -/* removed: var _$hasColorscale_253 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_249 = require('../../components/colorscale/defaults'); */; -var maxDimensionCount = _$constants_499.maxDimensionCount; -var handleDomainDefaults = _$domain_433.defaults; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$attributes_558 = require('./attributes'); */; +/* removed: var _$hasColorscale_315 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_311 = require('../../components/colorscale/defaults'); */; +var maxDimensionCount = _$constants_563.maxDimensionCount; +var handleDomainDefaults = _$domain_495.defaults; +/* removed: var _$axisbrush_559 = require('./axisbrush'); */; -function __handleLineDefaults_500(traceIn, traceOut, defaultColor, layout, coerce) { +function __handleLineDefaults_564(traceIn, traceOut, defaultColor, layout, coerce) { var lineColor = coerce('line.color', defaultColor); - if(_$hasColorscale_253(traceIn, 'line') && _$lib_363.isArrayOrTypedArray(lineColor)) { + if(_$hasColorscale_315(traceIn, 'line') && _$lib_425.isArrayOrTypedArray(lineColor)) { if(lineColor.length) { coerce('line.colorscale'); - _$colorScaleDefaults_249(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); + _$colorScaleDefaults_311(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); // TODO: I think it would be better to keep showing lines beyond the last line color // but I'm not sure what color to give these lines - probably black or white // depending on the background color? @@ -91195,19 +92561,19 @@ function dimensionsDefaults(traceIn, traceOut) { var commonLength = Infinity; if(dimensionsIn.length > maxDimensionCount) { - _$lib_363.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment'); + _$lib_425.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment'); dimensionsIn.splice(maxDimensionCount); } function coerce(attr, dflt) { - return _$lib_363.coerce(dimensionIn, dimensionOut, _$attributes_495.dimensions, attr, dflt); + return _$lib_425.coerce(dimensionIn, dimensionOut, _$attributes_558.dimensions, attr, dflt); } for(i = 0; i < dimensionsIn.length; i++) { dimensionIn = dimensionsIn[i]; dimensionOut = {}; - if(!_$lib_363.isPlainObject(dimensionIn)) { + if(!_$lib_425.isPlainObject(dimensionIn)) { continue; } @@ -91223,7 +92589,12 @@ function dimensionsDefaults(traceIn, traceOut) { coerce('ticktext'); coerce('tickformat'); coerce('range'); - coerce('constraintrange'); + + coerce('multiselect'); + var constraintRange = coerce('constraintrange'); + if(constraintRange) { + dimensionOut.constraintrange = _$axisbrush_559.cleanRanges(constraintRange, dimensionOut); + } commonLength = Math.min(commonLength, values.length); } @@ -91237,14 +92608,14 @@ function dimensionsDefaults(traceIn, traceOut) { return dimensionsOut; } -var _$supplyDefaults_500 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_564 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_495, attr, dflt); + return _$lib_425.coerce(traceIn, traceOut, _$attributes_558, attr, dflt); } var dimensions = dimensionsDefaults(traceIn, traceOut); - __handleLineDefaults_500(traceIn, traceOut, defaultColor, layout, coerce); + __handleLineDefaults_564(traceIn, traceOut, defaultColor, layout, coerce); handleDomainDefaults(traceOut, layout, coerce); @@ -91267,9 +92638,9 @@ var _$supplyDefaults_500 = function supplyDefaults(traceIn, traceOut, defaultCol color: layout.font.color }; - _$lib_363.coerceFont(coerce, 'labelfont', fontDflt); - _$lib_363.coerceFont(coerce, 'tickfont', fontDflt); - _$lib_363.coerceFont(coerce, 'rangefont', fontDflt); + _$lib_425.coerceFont(coerce, 'labelfont', fontDflt); + _$lib_425.coerceFont(coerce, 'tickfont', fontDflt); + _$lib_425.coerceFont(coerce, 'rangefont', fontDflt); }; /** @@ -91284,21 +92655,21 @@ var _$supplyDefaults_500 = function supplyDefaults(traceIn, traceOut, defaultCol var Parcoords = {}; -Parcoords.attributes = _$attributes_495; -Parcoords.supplyDefaults = _$supplyDefaults_500; -Parcoords.calc = _$calc_497; -Parcoords.plot = _$plot_504; -Parcoords.colorbar = _$colorbar_498; +Parcoords.attributes = _$attributes_558; +Parcoords.supplyDefaults = _$supplyDefaults_564; +Parcoords.calc = _$calc_561; +Parcoords.plot = _$plot_568; +Parcoords.colorbar = _$colorbar_562; Parcoords.moduleType = 'trace'; Parcoords.name = 'parcoords'; -Parcoords.basePlotModule = _$base_plot_496; +Parcoords.basePlotModule = _$base_plot_560; Parcoords.categories = ['gl', 'regl', 'noOpacity']; Parcoords.meta = { }; -var _$Parcoords_501 = Parcoords; +var _$Parcoords_565 = Parcoords; /** * Copyright 2012-2018, Plotly, Inc. @@ -91310,7 +92681,7 @@ var _$Parcoords_501 = Parcoords; 'use strict'; -var _$parcoords_7 = _$Parcoords_501; +var _$parcoords_7 = _$Parcoords_565; /** * Copyright 2012-2018, Plotly, Inc. @@ -91322,11 +92693,11 @@ var _$parcoords_7 = _$Parcoords_501; 'use strict'; -/* removed: var _$attributes_512 = require('../scatter/attributes'); */; +/* removed: var _$attributes_576 = require('../scatter/attributes'); */; -var _$attributes_507 = { - x: _$attributes_512.x, - y: _$attributes_512.y, +var _$attributes_571 = { + x: _$attributes_576.x, + y: _$attributes_576.y, xy: { valType: 'data_array', editType: 'calc', @@ -91347,7 +92718,7 @@ var _$attributes_507 = { editType: 'calc', }, - text: _$attributes_512.text, + text: _$attributes_576.text, marker: { color: { valType: 'color', @@ -91413,24 +92784,24 @@ var _$attributes_507 = { } }; -var _$shader_102 = {}; -/* removed: var _$browser_124 = require('glslify') */; +var _$shader_159 = {}; +/* removed: var _$browser_181 = require('glslify') */; -_$shader_102.pointVertex = _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]) -_$shader_102.pointFragment = _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]) -_$shader_102.pickVertex = _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]) -_$shader_102.pickFragment = _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]) +_$shader_159.pointVertex = _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]) +_$shader_159.pointFragment = _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]) +_$shader_159.pickVertex = _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]) +_$shader_159.pickFragment = _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]) 'use strict' -/* removed: var _$createShader_107 = require('gl-shader') */; -/* removed: var _$createBuffer_83 = require('gl-buffer') */; +/* removed: var _$createShader_164 = require('gl-shader') */; +/* removed: var _$createBuffer_140 = require('gl-buffer') */; -/* removed: var _$pool_207 = require('typedarray-pool') */; +/* removed: var _$pool_269 = require('typedarray-pool') */; -/* removed: var _$shader_102 = require('./lib/shader') */; +/* removed: var _$shader_159 = require('./lib/shader') */; -var _$createPointcloud2D_103 = createPointcloud2D +var _$createPointcloud2D_160 = createPointcloud2D function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) { this.plot = plot @@ -91450,9 +92821,9 @@ function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) { this.points = null } -var __proto_103 = Pointcloud2D.prototype +var __proto_160 = Pointcloud2D.prototype -__proto_103.dispose = function() { +__proto_160.dispose = function() { this.shader.dispose() this.pickShader.dispose() this.offsetBuffer.dispose() @@ -91460,7 +92831,7 @@ __proto_103.dispose = function() { this.plot.removeObject(this) } -__proto_103.update = function(options) { +__proto_160.update = function(options) { var i @@ -91490,8 +92861,8 @@ __proto_103.update = function(options) { var idStraightThrough = options.idToIndex instanceof Int32Array && options.idToIndex.length >= pointCount // permit larger to help reuse var data = options.positions - var packed = dataStraightThrough ? data : _$pool_207.mallocFloat32(data.length) - var packedId = idStraightThrough ? options.idToIndex : _$pool_207.mallocInt32(pointCount) + var packed = dataStraightThrough ? data : _$pool_269.mallocFloat32(data.length) + var packedId = idStraightThrough ? options.idToIndex : _$pool_269.mallocInt32(pointCount) if(!dataStraightThrough) { packed.set(data) @@ -91510,11 +92881,11 @@ __proto_103.update = function(options) { this.pickBuffer.update(packedId) if(!dataStraightThrough) { - _$pool_207.free(packed) + _$pool_269.free(packed) } if(!idStraightThrough) { - _$pool_207.free(packedId) + _$pool_269.free(packedId) } this.pointCount = pointCount @@ -91534,7 +92905,7 @@ function count(points, dataBox) { return visiblePointCountEstimate } -__proto_103.unifiedDraw = (function() { +__proto_160.unifiedDraw = (function() { var MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1] @@ -91606,10 +92977,10 @@ return function(pickOffset) { } })() -__proto_103.draw = __proto_103.unifiedDraw -__proto_103.drawPick = __proto_103.unifiedDraw +__proto_160.draw = __proto_160.unifiedDraw +__proto_160.drawPick = __proto_160.unifiedDraw -__proto_103.pick = function(x, y, value) { +__proto_160.pick = function(x, y, value) { var pickOffset = this.pickOffset var pointCount = this.pointCount if(value < pickOffset || value >= pickOffset + pointCount) { @@ -91626,10 +92997,10 @@ __proto_103.pick = function(x, y, value) { function createPointcloud2D(plot, options) { var gl = plot.gl - var buffer = _$createBuffer_83(gl) - var pickBuffer = _$createBuffer_83(gl) - var shader = _$createShader_107(gl, _$shader_102.pointVertex, _$shader_102.pointFragment) - var pickShader = _$createShader_107(gl, _$shader_102.pickVertex, _$shader_102.pickFragment) + var buffer = _$createBuffer_140(gl) + var pickBuffer = _$createBuffer_140(gl) + var shader = _$createShader_164(gl, _$shader_159.pointVertex, _$shader_159.pointFragment) + var pickShader = _$createShader_164(gl, _$shader_159.pickVertex, _$shader_159.pickFragment) var result = new Pointcloud2D(plot, buffer, pickBuffer, shader, pickShader) result.update(options) @@ -91650,11 +93021,11 @@ function createPointcloud2D(plot, options) { 'use strict'; -/* removed: var _$createPointcloud2D_103 = require('gl-pointcloud2d'); */; +/* removed: var _$createPointcloud2D_160 = require('gl-pointcloud2d'); */; -/* removed: var _$str2RgbaArray_385 = require('../../lib/str2rgbarray'); */; -var expandAxis = _$autorange_406.expand; -/* removed: var _$getTraceColor_522 = require('../scatter/get_trace_color'); */; +/* removed: var _$str2RgbaArray_448 = require('../../lib/str2rgbarray'); */; +var expandAxis = _$autorange_469.expand; +/* removed: var _$getTraceColor_586 = require('../scatter/get_trace_color'); */; function Pointcloud(scene, uid) { this.scene = scene; @@ -91682,13 +93053,13 @@ function Pointcloud(scene, uid) { areaRatio: 1, borderColor: [0, 0, 0, 1] }; - this.pointcloud = _$createPointcloud2D_103(scene.glplot, this.pointcloudOptions); + this.pointcloud = _$createPointcloud2D_160(scene.glplot, this.pointcloudOptions); this.pointcloud._trace = this; // scene2d requires this prop } -var __proto_508 = Pointcloud.prototype; +var __proto_572 = Pointcloud.prototype; -__proto_508.handlePick = function(pickResult) { +__proto_572.handlePick = function(pickResult) { var index = this.idToIndex[pickResult.pointId]; // prefer the readout from XY, if present @@ -91708,7 +93079,7 @@ __proto_508.handlePick = function(pickResult) { }; }; -__proto_508.update = function(options) { +__proto_572.update = function(options) { this.index = options.index; this.textLabels = options.text; this.name = options.name; @@ -91717,10 +93088,10 @@ __proto_508.update = function(options) { this.updateFast(options); - this.color = _$getTraceColor_522(options, {}); + this.color = _$getTraceColor_586(options, {}); }; -__proto_508.updateFast = function(options) { +__proto_572.updateFast = function(options) { var x = this.xData = this.pickXData = options.x; var y = this.yData = this.pickYData = options.y; var xy = this.pickXYData = options.xy; @@ -91809,8 +93180,8 @@ __proto_508.updateFast = function(options) { this.pointcloudOptions.positions = positions; - var markerColor = _$str2RgbaArray_385(options.marker.color), - borderColor = _$str2RgbaArray_385(options.marker.border.color), + var markerColor = _$str2RgbaArray_448(options.marker.color), + borderColor = _$str2RgbaArray_448(options.marker.border.color), opacity = options.opacity * options.marker.opacity; markerColor[3] *= opacity; @@ -91840,14 +93211,14 @@ __proto_508.updateFast = function(options) { this.expandAxesFast(bounds, markerSizeMax / 2); // avoid axis reexpand just because of the adaptive point size }; -__proto_508.expandAxesFast = function(bounds, markerSize) { +__proto_572.expandAxesFast = function(bounds, markerSize) { var pad = markerSize || 0.5; expandAxis(this.scene.xaxis, [bounds[0], bounds[2]], {ppad: pad}); expandAxis(this.scene.yaxis, [bounds[1], bounds[3]], {ppad: pad}); }; -__proto_508.dispose = function() { +__proto_572.dispose = function() { this.pointcloud.dispose(); }; @@ -91857,7 +93228,7 @@ function createPointcloud(scene, data) { return plot; } -var _$createPointcloud_508 = createPointcloud; +var _$createPointcloud_572 = createPointcloud; /** * Copyright 2012-2018, Plotly, Inc. @@ -91870,13 +93241,13 @@ var _$createPointcloud_508 = createPointcloud; 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; +/* removed: var _$lib_425 = require('../../lib'); */; -/* removed: var _$attributes_507 = require('./attributes'); */; +/* removed: var _$attributes_571 = require('./attributes'); */; -var _$supplyDefaults_509 = function supplyDefaults(traceIn, traceOut, defaultColor) { +var _$supplyDefaults_573 = function supplyDefaults(traceIn, traceOut, defaultColor) { function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_507, attr, dflt); + return _$lib_425.coerce(traceIn, traceOut, _$attributes_571, attr, dflt); } coerce('x'); @@ -91913,8 +93284,8 @@ var _$supplyDefaults_509 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$arraysToCalcdata_511 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcMarkerColorscale_517 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_575 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcMarkerColorscale_581 = require('../scatter/colorscale_calc'); */; /** @@ -91922,11 +93293,11 @@ var _$supplyDefaults_509 = function supplyDefaults(traceIn, traceOut, defaultCol * calcdata the way Scatter.plot does, so that legends and * popovers know what to do with them. */ -var _$calc_537 = function calc(gd, trace) { +var _$calc_601 = function calc(gd, trace) { var cd = [{x: false, y: false, trace: trace, t: {}}]; - _$arraysToCalcdata_511(cd, trace); - _$calcMarkerColorscale_517(trace); + _$arraysToCalcdata_575(cd, trace); + _$calcMarkerColorscale_581(trace); return cd; }; @@ -91943,22 +93314,22 @@ var _$calc_537 = function calc(gd, trace) { var pointcloud = {}; -pointcloud.attributes = _$attributes_507; -pointcloud.supplyDefaults = _$supplyDefaults_509; +pointcloud.attributes = _$attributes_571; +pointcloud.supplyDefaults = _$supplyDefaults_573; // reuse the Scatter3D 'dummy' calc step so that legends know what to do -pointcloud.calc = _$calc_537; -pointcloud.plot = _$createPointcloud_508; +pointcloud.calc = _$calc_601; +pointcloud.plot = _$createPointcloud_572; pointcloud.moduleType = 'trace'; pointcloud.name = 'pointcloud'; -pointcloud.basePlotModule = _$gl2d_439; +pointcloud.basePlotModule = _$gl2d_501; pointcloud.categories = ['gl', 'gl2d', 'showLegend']; pointcloud.meta = { }; -var _$pointcloud_510 = pointcloud; +var _$pointcloud_574 = pointcloud; /** * Copyright 2012-2018, Plotly, Inc. @@ -91970,10 +93341,10 @@ var _$pointcloud_510 = pointcloud; 'use strict'; -var _$pointcloud_8 = _$pointcloud_510; +var _$pointcloud_8 = _$pointcloud_574; -var _$newArray_14 = function newArray(start, end) { +var _$newArray_15 = function newArray(start, end) { var n0 = typeof start === 'number', n1 = typeof end === 'number' @@ -91996,199 +93367,11 @@ var _$newArray_14 = function newArray(start, end) { a[i] = c return a } -/** - * @module kdgrass - * - * Static kdbush - */ - 'use strict' -var _$KDTree_136 = KDTree - -//optimized kdbush -function KDTree(points, nodeSize) { - if (!(this instanceof KDTree)) return new KDTree(points, nodeSize) - - this.nodeSize = nodeSize || 64; - - this.coords = points.slice(); - - var l = Math.floor(points.length / 2) - this.ids = Array(l); - - for (var i = 0; i < l; i++) { - this.ids[i] = i; - } - - sortKD(this.ids, this.coords, this.nodeSize, 0, this.ids.length - 1, 0); -} - - -KDTree.prototype.range = function range(minX, minY, maxX, maxY) { - var ids = this.ids, coords = this.coords, nodeSize = this.nodeSize - var stack = [0, ids.length - 1, 0]; - var result = []; - var x, y; - - while (stack.length) { - var axis = stack.pop(); - var right = stack.pop(); - var left = stack.pop(); - - if (right - left <= nodeSize) { - for (var i = left; i <= right; i++) { - x = coords[2 * i]; - y = coords[2 * i + 1]; - if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); - } - continue; - } - - var m = Math.floor((left + right) / 2); - - x = coords[2 * m]; - y = coords[2 * m + 1]; - - if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); - - var nextAxis = (axis + 1) % 2; - - if (axis === 0 ? minX <= x : minY <= y) { - stack.push(left); - stack.push(m - 1); - stack.push(nextAxis); - } - if (axis === 0 ? maxX >= x : maxY >= y) { - stack.push(m + 1); - stack.push(right); - stack.push(nextAxis); - } - } - - return result; -} - - -KDTree.prototype.within = function within(qx, qy, r) { - var ids = this.ids, coords = this.coords, nodeSize = this.nodeSize - var stack = [0, ids.length - 1, 0]; - var result = []; - var r2 = r * r; - - while (stack.length) { - var axis = stack.pop(); - var right = stack.pop(); - var left = stack.pop(); - - if (right - left <= nodeSize) { - for (var i = left; i <= right; i++) { - if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); - } - continue; - } - - var m = Math.floor((left + right) / 2); - - var x = coords[2 * m]; - var y = coords[2 * m + 1]; - - if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); - - var nextAxis = (axis + 1) % 2; - - if (axis === 0 ? qx - r <= x : qy - r <= y) { - stack.push(left); - stack.push(m - 1); - stack.push(nextAxis); - } - if (axis === 0 ? qx + r >= x : qy + r >= y) { - stack.push(m + 1); - stack.push(right); - stack.push(nextAxis); - } - } - - return result; -} - -function sqDist(ax, ay, bx, by) { - var dx = ax - bx; - var dy = ay - by; - return dx * dx + dy * dy; -} - - -function sortKD(ids, coords, nodeSize, left, right, depth) { - if (right - left <= nodeSize) return; - - var m = Math.floor((left + right) / 2); - - __select_136(ids, coords, m, left, right, depth % 2); - - sortKD(ids, coords, nodeSize, left, m - 1, depth + 1); - sortKD(ids, coords, nodeSize, m + 1, right, depth + 1); -} - -function __select_136(ids, coords, k, left, right, inc) { - - while (right > left) { - if (right - left > 600) { - var n = right - left + 1; - var m = k - left + 1; - var z = Math.log(n); - var s = 0.5 * Math.exp(2 * z / 3); - var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); - var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); - var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); - __select_136(ids, coords, k, newLeft, newRight, inc); - } - - var t = coords[2 * k + inc]; - var i = left; - var j = right; - - swapItem(ids, coords, left, k); - if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right); - - while (i < j) { - swapItem(ids, coords, i, j); - i++; - j--; - while (coords[2 * i + inc] < t) i++; - while (coords[2 * j + inc] > t) j--; - } - - if (coords[2 * left + inc] === t) swapItem(ids, coords, left, j); - else { - j++; - swapItem(ids, coords, j, right); - } - - if (j <= k) left = j + 1; - if (k <= j) right = j - 1; - } -} - -function swapItem(ids, coords, i, j) { - __swap_136(ids, i, j); - __swap_136(coords, 2 * i, 2 * j); - __swap_136(coords, 2 * i + 1, 2 * j + 1); -} - -function __swap_136(arr, i, j) { - var tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; -} - - - -'use strict' - -var _$normalize_12 = __normalize_12; +var _$normalize_13 = __normalize_13; -function __normalize_12 (arr, dim) { +function __normalize_13 (arr, dim) { if (!arr || arr.length == null) throw Error('Argument should be an array') if (dim == null) dim = 1 @@ -92212,8 +93395,8 @@ function __normalize_12 (arr, dim) { } /*eslint new-cap:0*/ -/* removed: var _$dtype_72 = require('dtype') */; -var _$flattenVertexData_79 = flattenVertexData +/* removed: var _$dtype_75 = require('dtype') */; +var _$flattenVertexData_136 = flattenVertexData function flattenVertexData (data, output, offset) { if (!data) throw new TypeError('must specify data as first parameter') offset = +(offset || 0) | 0 @@ -92224,7 +93407,7 @@ function flattenVertexData (data, output, offset) { // no output specified, create a new typed array if (!output || typeof output === 'string') { - output = new (_$dtype_72(output || 'float32'))(length + offset) + output = new (_$dtype_75(output || 'float32'))(length + offset) } var dstLength = output.length - offset @@ -92241,7 +93424,7 @@ function flattenVertexData (data, output, offset) { } else { if (!output || typeof output === 'string') { // no output, create a new one - var Ctor = _$dtype_72(output || 'float32') + var Ctor = _$dtype_75(output || 'float32') if (offset === 0) { output = new Ctor(data) } else { @@ -92257,6 +93440,581 @@ function flattenVertexData (data, output, offset) { return output } +'use strict'; +var _$isObj_191 = function (x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); +}; + +'use strict'; +var _$mathLog2_194 = Math.log2 || function (x) { + return Math.log(x) * Math.LOG2E; +}; + +'use strict' + + +var _$pick_212 = function pick (src, props, keepRest) { + var result = {}, prop, i + + if (typeof props === 'string') props = toList(props) + if (Array.isArray(props)) { + var res = {} + for (i = 0; i < props.length; i++) { + res[props[i]] = true + } + props = res + } + + // convert strings to lists + for (prop in props) { + props[prop] = toList(props[prop]) + } + + // keep-rest strategy requires unmatched props to be preserved + var occupied = {} + + for (prop in props) { + var aliases = props[prop] + + if (Array.isArray(aliases)) { + for (i = 0; i < aliases.length; i++) { + var alias = aliases[i] + + if (keepRest) { + occupied[alias] = true + } + + if (alias in src) { + result[prop] = src[alias] + + if (keepRest) { + for (var j = i; j < aliases.length; j++) { + occupied[aliases[j]] = true + } + } + + break + } + } + } + else if (prop in src) { + if (props[prop]) { + result[prop] = src[prop] + } + + if (keepRest) { + occupied[prop] = true + } + } + } + + if (keepRest) { + for (prop in src) { + if (occupied[prop]) continue + result[prop] = src[prop] + } + } + + return result +} + +var __CACHE_212 = {} + +function toList(arg) { + if (__CACHE_212[arg]) return __CACHE_212[arg] + if (typeof arg === 'string') { + arg = __CACHE_212[arg] = arg.split(/\s*,\s*|\s+/) + } + return arg +} + +'use strict' + +/* removed: var _$pick_212 = require('pick-by-alias') */; + +var _$parseRect_206 = 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_212(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 +} + +"use strict" + +function __compileSearch_217(funcName, predicate, reversed, extraArgs, 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[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_217(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_217("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_217("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() +} + +var _$searchBounds_217 = { + ge: __compileBoundsSearch_217(">=", false, "GE"), + gt: __compileBoundsSearch_217(">", false, "GT"), + lt: __compileBoundsSearch_217("<", true, "LT"), + le: __compileBoundsSearch_217("<=", true, "LE"), + eq: __compileBoundsSearch_217("-", true, "EQ", true) +} + +/** + * @module point-cluster/quad + * + * Bucket based quad tree clustering + */ + +'use strict' + +/* removed: var _$searchBounds_217 = require('binary-search-bounds') */; +/* removed: var _$clamp_54 = require('clamp') */; +/* removed: var _$parseRect_206 = require('parse-rect') */; +/* removed: var _$normalize_13 = require('array-bounds') */; +/* removed: var _$pick_212 = require('pick-by-alias') */; +/* removed: var _$defined_72 = require('defined') */; +/* removed: var _$flattenVertexData_136 = require('flatten-vertex-data') */; +/* removed: var _$isObj_191 = require('is-obj') */; +/* removed: var _$dtype_75 = require('dtype') */; +/* removed: var _$mathLog2_194 = require('math-log2') */; + + +var _$cluster_218 = function cluster (srcPoints, options) { + if (!options) { options = {} } + + srcPoints = _$flattenVertexData_136(srcPoints, 'float64') + + options = _$pick_212(options, { + bounds: 'range bounds dataBox databox', + maxDepth: 'depth maxDepth maxdepth level maxLevel maxlevel levels', + dtype: 'type dtype format out dst output destination' + // sort: 'sortBy sortby sort', + // pick: 'pick levelPoint', + // nodeSize: 'node nodeSize minNodeSize minSize size' + }) + + // let nodeSize = defined(options.nodeSize, 1) + var maxDepth = _$defined_72(options.maxDepth, 255) + var bounds = _$defined_72(options.bounds, _$normalize_13(srcPoints, 2)) + if (bounds[0] === bounds[2]) { bounds[2]++ } + if (bounds[1] === bounds[3]) { bounds[3]++ } + + var points = __normalize_218(srcPoints, bounds) + + // init variables + var n = srcPoints.length >>> 1 + var ids + if (!options.dtype) { options.dtype = 'array' } + + if (typeof options.dtype === 'string') { + ids = new (_$dtype_75(options.dtype))(n) + } + else if (options.dtype) { + ids = options.dtype + if (Array.isArray(ids)) { ids.length = n } + } + for (var i = 0; i < n; ++i) { + ids[i] = i + } + + // point indexes for levels [0: [a,b,c,d], 1: [a,b,c,d,e,f,...], ...] + var levels = [] + + // starting indexes of subranges in sub levels, levels.length * 4 + var sublevels = [] + + // unique group ids, sorted in z-curve fashion within levels + var groups = [] + + // level offsets in `ids` + var offsets = [] + + + // sort points + sort(0, 0, 1, ids, 0, 1) + + + // return reordered ids with provided methods + // save level offsets in output buffer + var offset = 0 + for (var level = 0; level < levels.length; level++) { + var levelItems = levels[level] + if (ids.set) { ids.set(levelItems, offset) } + else { + for (var i$1 = 0, l = levelItems.length; i$1 < l; i$1++) { + ids[i$1 + offset] = levelItems[i$1] + } + } + var nextOffset = offset + levels[level].length + offsets[level] = [offset, nextOffset] + offset = nextOffset + } + + ids.range = range + + return ids + + + + // FIXME: it is possible to create one typed array heap and reuse that to avoid memory blow + function sort (x, y, diam, ids, level, group) { + if (!ids.length) { return null } + + // save first point as level representative + var levelItems = levels[level] || (levels[level] = []) + var levelGroups = groups[level] || (groups[level] = []) + var sublevel = sublevels[level] || (sublevels[level] = []) + var offset = levelItems.length + + level++ + + // max depth reached - put all items into a first group + if (level > maxDepth) { + for (var i = 0; i < ids.length; i++) { + levelItems.push(ids[i]) + levelGroups.push(group) + sublevel.push(null, null, null, null) + } + + return offset + } + + levelItems.push(ids[0]) + levelGroups.push(group) + + if (ids.length <= 1) { + sublevel.push(null, null, null, null) + return offset + } + + + var d2 = diam * .5 + var cx = x + d2, cy = y + d2 + + // distribute points by 4 buckets + var lolo = [], lohi = [], hilo = [], hihi = [] + + for (var i$1 = 1, l = ids.length; i$1 < l; i$1++) { + var idx = ids[i$1], + x$1 = points[idx * 2], + y$1 = points[idx * 2 + 1] + x$1 < cx ? (y$1 < cy ? lolo.push(idx) : lohi.push(idx)) : (y$1 < cy ? hilo.push(idx) : hihi.push(idx)) + } + + group <<= 2 + sublevel.push( + sort(x, y, d2, lolo, level, group), + sort(x, cy, d2, lohi, level, group + 1), + sort(cx, y, d2, hilo, level, group + 2), + sort(cx, cy, d2, hihi, level, group + 3) + ) + + return offset + } + + // get all points within the passed range + function range () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var options + + if (_$isObj_191(args[args.length - 1])) { + var arg = args.pop() + + // detect if that was a rect object + if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) { + args = [arg] + options = {} + } + + options = _$pick_212(arg, { + level: 'level maxLevel', + d: 'd diam diameter r radius px pxSize pixel pixelSize maxD size minSize', + lod: 'lod details ranges offsets' + }) + } + else { + options = {} + } + + if (!args.length) { args = bounds } + + var box = _$parseRect_206.apply( void 0, args ) + + var ref = [ + Math.min(box.x, box.x + box.width), + Math.min(box.y, box.y + box.height), + Math.max(box.x, box.x + box.width), + Math.max(box.y, box.y + box.height) + ]; + var minX = ref[0]; + var minY = ref[1]; + var maxX = ref[2]; + var maxY = ref[3]; + + var ref$1 = __normalize_218([minX, minY, maxX, maxY], bounds ); + var nminX = ref$1[0]; + var nminY = ref$1[1]; + var nmaxX = ref$1[2]; + var nmaxY = ref$1[3]; + + var maxLevel = _$defined_72(options.level, levels.length) + + // limit maxLevel by px size + if (options.d != null) { + var d + if (typeof options.d === 'number') { d = [options.d, options.d] } + else if (options.d.length) { d = options.d } + + maxLevel = Math.min( + Math.ceil(-_$mathLog2_194(Math.abs(d[0]) / (bounds[2] - bounds[0]))), + Math.ceil(-_$mathLog2_194(Math.abs(d[1]) / (bounds[3] - bounds[1]))), + maxLevel + ) + } + + // return levels of details + if (options.lod) { + return lod(nminX, nminY, nmaxX, nmaxY, maxLevel) + } + + + + // do selection ids + var selection = [] + + // FIXME: probably we can do LOD here beforehead + select( 0, 0, 1, 0, 0, 1) + + function select ( lox, loy, d, level, from, to ) { + if (from === null || to === null) { return } + + var hix = lox + d + var hiy = loy + d + + // if box does not intersect level - ignore + if ( nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy ) { return } + if ( level >= maxLevel ) { return } + if ( from === to ) { return } + + // if points fall into box range - take it + var levelItems = levels[level] + + if (to === undefined) { to = levelItems.length } + + for (var i = from; i < to; i++) { + var id = levelItems[i] + + var px = srcPoints[ id * 2 ] + var py = srcPoints[ id * 2 + 1 ] + + if ( px >= minX && px <= maxX && py >= minY && py <= maxY ) {selection.push(id) + } + } + + // for every subsection do select + var offsets = sublevels[ level ] + var off0 = offsets[ from * 4 + 0 ] + var off1 = offsets[ from * 4 + 1 ] + var off2 = offsets[ from * 4 + 2 ] + var off3 = offsets[ from * 4 + 3 ] + var end = nextOffset(offsets, from + 1) + + var d2 = d * .5 + var nextLevel = level + 1 + select( lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end) + select( lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end) + select( lox + d2, loy, d2, nextLevel, off2, off3 || end) + select( lox + d2, loy + d2, d2, nextLevel, off3, end) + } + + function nextOffset(offsets, from) { + var offset = null, i = 0 + while(offset === null) { + offset = offsets[ from * 4 + i ] + i++ + if (i > offsets.length) { return null } + } + return offset + } + + return selection + } + + // get range offsets within levels to render lods appropriate for zoom level + // TODO: it is possible to store minSize of a point to optimize neede level calc + function lod (lox, loy, hix, hiy, maxLevel) { + var ranges = [] + + for (var level = 0; level < maxLevel; level++) { + var levelGroups = groups[level] + var from = offsets[level][0] + + var levelGroupStart = group(lox, loy, level) + var levelGroupEnd = group(hix, hiy, level) + + // FIXME: utilize sublevels to speed up search range here + var startOffset = _$searchBounds_217.ge(levelGroups, levelGroupStart) + var endOffset = _$searchBounds_217.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1) + + ranges[level] = [startOffset + from, endOffset + from] + } + + return ranges + } + + // get group id closest to the x,y coordinate, corresponding to a level + function group (x, y, level) { + var group = 1 + + var cx = .5, cy = .5 + var diam = .5 + + for (var i = 0; i < level; i++) { + group <<= 2 + + group += x < cx ? (y < cy ? 0 : 1) : (y < cy ? 2 : 3) + + diam *= .5 + + cx += x < cx ? -diam : diam + cy += y < cy ? -diam : diam + } + + return group + } +} + + +// normalize points by bounds +function __normalize_218 (pts, bounds) { + var lox = bounds[0]; + var loy = bounds[1]; + var hix = bounds[2]; + var hiy = bounds[3]; + var scaleX = 1.0 / (hix - lox) + var scaleY = 1.0 / (hiy - loy) + var result = new Array(pts.length) + + for (var i = 0, n = pts.length / 2; i < n; i++) { + result[2*i] = _$clamp_54((pts[2*i] - lox) * scaleX, 0, 1) + result[2*i+1] = _$clamp_54((pts[2*i+1] - loy) * scaleY, 0, 1) + } + + return result +} +'use strict' + +var _$pointCluster_216 = _$cluster_218 /* object-assign (c) Sindre Sorhus @@ -92321,7 +94079,7 @@ function shouldUseNative() { } } -var _$objectAssign_146 = shouldUseNative() ? Object.assign : function (target, source) { +var _$objectAssign_204 = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; @@ -92348,94 +94106,16 @@ var _$objectAssign_146 = shouldUseNative() ? Object.assign : function (target, s return to; }; -'use strict' - - -var _$pick_153 = function pick (src, props, keepRest) { - var result = {}, prop, i - - if (typeof props === 'string') props = toList(props) - if (Array.isArray(props)) { - var res = {} - for (i = 0; i < props.length; i++) { - res[props[i]] = true - } - props = res - } - - // convert strings to lists - for (prop in props) { - props[prop] = toList(props[prop]) - } - - // keep-rest strategy requires unmatched props to be preserved - var occupied = {} - - for (prop in props) { - var aliases = props[prop] - - if (Array.isArray(aliases)) { - for (i = 0; i < aliases.length; i++) { - var alias = aliases[i] - - if (keepRest) { - occupied[alias] = true - } - - if (alias in src) { - result[prop] = src[alias] - - if (keepRest) { - for (var j = i; j < aliases.length; j++) { - occupied[aliases[j]] = true - } - } - - break - } - } - } - else if (prop in src) { - if (props[prop]) { - result[prop] = src[prop] - } - - if (keepRest) { - occupied[prop] = true - } - } - } - - if (keepRest) { - for (prop in src) { - if (occupied[prop]) continue - result[prop] = src[prop] - } - } - - return result -} - -var __CACHE_153 = {} - -function toList(arg) { - if (__CACHE_153[arg]) return __CACHE_153[arg] - if (typeof arg === 'string') { - arg = __CACHE_153[arg] = arg.split(/\s*,\s*|\s+/) - } - return arg -} - -var _$toFloat32_202 = {}; +var _$toFloat32_264 = {}; /* @module to-float32 */ 'use strict' -_$toFloat32_202 = float32 -_$toFloat32_202.float32 = -_$toFloat32_202.float = float32 -_$toFloat32_202.fract32 = -_$toFloat32_202.fract = fract32 +_$toFloat32_264 = float32 +_$toFloat32_264.float32 = +_$toFloat32_264.float = float32 +_$toFloat32_264.fract32 = +_$toFloat32_264.fract = fract32 // return fractional part of float32 array function fract32 (arr) { @@ -92468,7 +94148,7 @@ function float32 (arr) { 'use strict' -var _$updateDiff_210 = function updateDiff (obj, diff, mappers) { +var _$updateDiff_272 = function updateDiff (obj, diff, mappers) { if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2) for (var i = 0, l = mappers.length; i < l; i++) { @@ -92496,19 +94176,19 @@ var _$updateDiff_210 = function updateDiff (obj, diff, mappers) { 'use strict' -/* removed: var _$normalize_12 = require('array-bounds') */; -/* removed: var _$normalize_58 = require('color-normalize') */; -/* removed: var _$updateDiff_210 = require('update-diff') */; -/* removed: var _$pick_153 = require('pick-by-alias') */; -/* removed: var _$objectAssign_146 = require('object-assign') */; -/* removed: var _$flattenVertexData_79 = require('flatten-vertex-data') */; -/* removed: var _$toFloat32_202 = require('to-float32'); */; -var __float32_171 = _$toFloat32_202.float32; -var __fract32_171 = _$toFloat32_202.fract32; +/* removed: var _$normalize_13 = require('array-bounds') */; +/* removed: var _$normalize_59 = require('color-normalize') */; +/* removed: var _$updateDiff_272 = require('update-diff') */; +/* removed: var _$pick_212 = require('pick-by-alias') */; +/* removed: var _$objectAssign_204 = require('object-assign') */; +/* removed: var _$flattenVertexData_136 = require('flatten-vertex-data') */; +/* removed: var _$toFloat32_264 = require('to-float32'); */; +var __float32_234 = _$toFloat32_264.float32; +var __fract32_234 = _$toFloat32_264.fract32; -var _$Error2D_171 = Error2D +var _$Error2D_234 = Error2D -var __WEIGHTS_171 = [ +var __WEIGHTS_234 = [ //direction, lineWidth shift, capSize shift // x-error bar @@ -92626,7 +94306,7 @@ function Error2D (regl, options) { meshBuffer = regl.buffer({ usage: 'static', type: 'float', - data: __WEIGHTS_171 + data: __WEIGHTS_234 }) update(options) @@ -92719,11 +94399,11 @@ function Error2D (regl, options) { stencil: false, instances: regl.prop('count'), - count: __WEIGHTS_171.length + count: __WEIGHTS_234.length }) //expose API - _$objectAssign_146(error2d, { + _$objectAssign_204(error2d, { update: update, draw: draw, destroy: destroy, @@ -92818,7 +94498,7 @@ function Error2D (regl, options) { else if (typeof options[0] === 'number') { options = {positions: options} } //copy options to avoid mutation & handle aliases - options = _$pick_153(options, { + options = _$pick_212(options, { color: 'color colors fill', capSize: 'capSize cap capsize cap-size', lineWidth: 'lineWidth line-width width line thickness', @@ -92838,23 +94518,23 @@ function Error2D (regl, options) { translateFract: null, draw: true } - options = _$objectAssign_146({}, defaults, options) + options = _$objectAssign_204({}, defaults, options) } - _$updateDiff_210(group, options, [{ + _$updateDiff_272(group, options, [{ lineWidth: function (v) { return +v * .5; }, capSize: function (v) { return +v * .5; }, opacity: parseFloat, errors: function (errors) { - errors = _$flattenVertexData_79(errors) + errors = _$flattenVertexData_136(errors) errorCount += errors.length return errors }, positions: function (positions, state) { - positions = _$flattenVertexData_79(positions, 'float64') + positions = _$flattenVertexData_136(positions, 'float64') state.count = Math.floor(positions.length / 2) - state.bounds = _$normalize_12(positions, 2) + state.bounds = _$normalize_13(positions, 2) state.offset = pointCount pointCount += state.count @@ -92882,7 +94562,7 @@ function Error2D (regl, options) { //convert colors to float arrays for (var i$1 = 0; i$1 < count; i$1++) { - var c = _$normalize_58(colors[i$1], 'uint8') + var c = _$normalize_59(colors[i$1], 'uint8') colorData.set(c, i$1 * 4) } @@ -92896,8 +94576,8 @@ function Error2D (regl, options) { state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] state.translate = [-range[0], -range[1]] - state.scaleFract = __fract32_171(state.scale) - state.translateFract = __fract32_171(state.translate) + state.scaleFract = __fract32_234(state.scale) + state.translateFract = __fract32_234(state.translate) return range }, @@ -92963,8 +94643,8 @@ function Error2D (regl, options) { positionData.set(positions, offset * 2) }) - positionBuffer(__float32_171(positionData)) - positionFractBuffer(__fract32_171(positionData)) + positionBuffer(__float32_234(positionData)) + positionFractBuffer(__fract32_234(positionData)) colorBuffer(colorData) errorBuffer(errorData) } @@ -92981,15 +94661,15 @@ function Error2D (regl, options) { } 'use strict' -/* removed: var _$normalize_12 = require('array-bounds') */; +/* removed: var _$normalize_13 = require('array-bounds') */; -var _$normalize_13 = __normalize_13; +var _$normalize_14 = __normalize_14; -function __normalize_13 (arr, dim, bounds) { +function __normalize_14 (arr, dim, bounds) { if (!arr || arr.length == null) throw Error('Argument should be an array') if (dim == null) dim = 1 - if (bounds == null) bounds = _$normalize_12(arr, dim) + if (bounds == null) bounds = _$normalize_13(arr, dim) for (var offset = 0; offset < dim; offset++) { var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length; @@ -93020,11 +94700,11 @@ function __normalize_13 (arr, dim, bounds) { return arr; } -var _$earcut_74 = {}; +var _$earcut_77 = {}; 'use strict'; -_$earcut_74 = earcut; -_$earcut_74.default = earcut; +_$earcut_77 = earcut; +_$earcut_77.default = earcut; function earcut(data, holeIndices, dim) { @@ -93510,291 +95190,2221 @@ function intersects(p1, q1, p2, q2) { area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 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); +// 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) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice 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; +}; + +'use strict'; + +var _$isImplemented_131 = function () { + var weakMap, x; + if (typeof WeakMap !== 'function') return false; + try { + // WebKit doesn't support arguments and crashes + weakMap = new WeakMap([[x = {}, '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(x) !== 'one') return false; + + return true; +}; + +"use strict"; + +var _$isImplemented_93 = 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"; +}; + +"use strict"; + +var _$isImplemented_102 = function () { + try { + Object.keys("primitive"); + return true; + } catch (e) { + return false; +} +}; + +"use strict"; + +// eslint-disable-next-line no-empty-function +var _$noop_85 = function () {}; + +"use strict"; + +var _undefined = _$noop_85(); // Support ES3 engines + +var _$isValue_100 = function (val) { + return (val !== _undefined) && (val !== null); +}; + +"use strict"; + +/* removed: var _$isValue_100 = require("../is-value"); */; + +var keys = Object.keys; + +var _$shim_103 = function (object) { + return keys(_$isValue_100(object) ? Object(object) : object); +}; + +"use strict"; + +var _$keys_101 = _$isImplemented_102() + ? Object.keys + : _$shim_103; + +"use strict"; + +/* removed: var _$isValue_100 = require("./is-value"); */; + +var _$validValue_111 = function (value) { + if (!_$isValue_100(value)) throw new TypeError("Cannot use null or undefined"); + return value; +}; + +"use strict"; + +var __dummy_94$0 = 0 + , __dummy_94$1 = 0 + , max = Math.max; + +var _$shim_94 = function (dest, src /*, …srcn*/) { + var error, i, length = max(arguments.length, 2), assign; + dest = Object(_$validValue_111(dest)); + assign = function (key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + _$keys_101(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; + +"use strict"; + +var _$assign_92 = _$isImplemented_93() + ? Object.assign + : _$shim_94; + +// Deprecated + +"use strict"; + +var _$isCallable_98 = function (obj) { + return typeof obj === "function"; +}; + +"use strict"; + +/* removed: var _$isValue_100 = require("./is-value"); */; + +var forEach = Array.prototype.forEach, create = Object.create; + +var __process_105 = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +// eslint-disable-next-line no-unused-vars +var _$normalizeOptions_105 = function (opts1 /*, …options*/) { + var result = create(null); + forEach.call(arguments, function (options) { + if (!_$isValue_100(options)) return; + __process_105(Object(options), result); + }); + return result; +}; + +"use strict"; + +var str = "razdwatrzy"; + +var _$isImplemented_113 = function () { + if (typeof str.contains !== "function") return false; + return (str.contains("dwa") === true) && (str.contains("foo") === false); +}; + +"use strict"; + +var indexOf = String.prototype.indexOf; + +var _$shim_114 = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; + +"use strict"; + +var _$contains_112 = _$isImplemented_113() + ? String.prototype.contains + : _$shim_114; + +var _$d_70 = {}; +'use strict'; + +var __dummy_70$0 = 0 + , __dummy_70$1 = 0 + , __dummy_70$2 = 0 + , __dummy_70$3 = 0 + + , d; + +d = _$d_70 = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = _$contains_112.call(dscr, 'c'); + e = _$contains_112.call(dscr, 'e'); + w = _$contains_112.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : _$assign_92(_$normalizeOptions_105(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!_$isCallable_98(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!_$isCallable_98(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = _$contains_112.call(dscr, 'c'); + e = _$contains_112.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : _$assign_92(_$normalizeOptions_105(options), desc); +}; + +"use strict"; + +var __create_107 = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; + +var _$isImplemented_107 = function (/* CustomCreate*/) { + var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || __create_107; + if (typeof setPrototypeOf !== "function") return false; + return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject; +}; + +"use strict"; + +/* removed: var _$isValue_100 = require("./is-value"); */; + +var __map_99 = { function: true, object: true }; + +var _$isObject_99 = function (value) { + return (_$isValue_100(value) && __map_99[typeof value]) || false; +}; + +"use strict"; + +var _$setPrototypeOf_106 = _$isImplemented_107() + ? Object.setPrototypeOf + : _$shim_108({}); + +"use strict"; + +/* removed: var _$isObject_99 = require("./is-object"); */; + +var _$validObject_110 = function (value) { + if (!_$isObject_99(value)) throw new TypeError(value + " is not an Object"); + return value; +}; + +"use strict"; + +var generated = Object.create(null), random = Math.random; + +var _$randomUniq_116 = function () { + var str; + do { + str = random() + .toString(36) + .slice(2); + } while (generated[str]); + return str; +}; + +"use strict"; + +var objToString = Object.prototype.toString + , id = objToString.call( + (function () { + return arguments; + })() +); + +var _$isArguments_83 = function (value) { + return objToString.call(value) === id; +}; + +"use strict"; + +var _$validCallable_109 = function (fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; +}; + +"use strict"; + +var __objToString_115 = Object.prototype.toString, __id_115 = __objToString_115.call(""); + +var _$isString_115 = function (value) { + return ( + typeof value === "string" || + (value && + typeof value === "object" && + (value instanceof String || __objToString_115.call(value) === __id_115)) || + false + ); +}; + +"use strict"; + +var _$isImplemented_81 = 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")); +}; + +"use strict"; + +var __objToString_84 = Object.prototype.toString, __id_84 = __objToString_84.call(_$noop_85); + +var _$isFunction_84 = function (value) { + return typeof value === "function" && __objToString_84.call(value) === __id_84; +}; + +"use strict"; + +var _$isImplemented_87 = function () { + var sign = Math.sign; + if (typeof sign !== "function") return false; + return (sign(10) === 1) && (sign(-20) === -1); +}; + +"use strict"; + +var _$shim_88 = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return value > 0 ? 1 : -1; +}; + +"use strict"; + +var _$sign_86 = _$isImplemented_87() + ? Math.sign + : _$shim_88; + +"use strict"; + +var __dummy_89$0 = 0 + + , abs = Math.abs, floor = Math.floor; + +var _$toInteger_89 = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if ((value === 0) || !isFinite(value)) return value; + return _$sign_86(value) * floor(abs(value)); +}; + +"use strict"; + +var __dummy_90$0 = 0 + + , __max_90 = Math.max; + +var _$toPosInteger_90 = function (value) { + return __max_90(0, _$toInteger_89(value)); +}; + +'use strict'; + +var validTypes = { object: true, symbol: true }; + +var _$isImplemented_126 = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + + // Return 'true' also for polyfills + if (!validTypes[typeof Symbol.iterator]) return false; + if (!validTypes[typeof Symbol.toPrimitive]) return false; + if (!validTypes[typeof Symbol.toStringTag]) return false; + + return true; +}; + +'use strict'; + +var _$isSymbol_127 = function (x) { + if (!x) return false; + if (typeof x === 'symbol') return true; + if (!x.constructor) return false; + if (x.constructor.name !== 'Symbol') return false; + return (x[x.constructor.toStringTag] === 'Symbol'); +}; + +'use strict'; + +/* removed: var _$isSymbol_127 = require('./is-symbol'); */; + +var _$validateSymbol_129 = function (value) { + if (!_$isSymbol_127(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; + +// ES2015 Symbol polyfill for environments that do not (or partially) support it + +'use strict'; + +var __dummy_128$0 = 0 + , __dummy_128$1 = 0 + + , __create_128 = Object.create, defineProperties = Object.defineProperties + , __defineProperty_128 = Object.defineProperty, objPrototype = Object.prototype + , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = __create_128(null) + , isNativeSafe; + +if (typeof Symbol === 'function') { + NativeSymbol = Symbol; + try { + String(NativeSymbol()); + isNativeSafe = true; + } catch (ignore) {} +} + +var generateName = (function () { + var created = __create_128(null); + return function (desc) { + var postfix = 0, name, ie11BugWorkaround; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + __defineProperty_128(objPrototype, name, _$d_70.gs(null, function (value) { + // For IE11 issue see: + // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ + // ie11-broken-getters-on-dom-objects + // https://github.com/medikoo/es6-symbol/issues/12 + if (ie11BugWorkaround) return; + ie11BugWorkaround = true; + __defineProperty_128(this, name, _$d_70(value)); + ie11BugWorkaround = false; + })); + return name; + }; +}()); + +// Internal constructor (not one exposed) for creating Symbol instances. +// This one is used to ensure that `someSymbol instanceof Symbol` always return false +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor'); + return SymbolPolyfill(description); +}; + +// Exposed `Symbol` constructor +// (returns instances of HiddenSymbol) +var _$polyfill_128 = SymbolPolyfill = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor'); + if (isNativeSafe) return NativeSymbol(description); + symbol = __create_128(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: _$d_70('', description), + __name__: _$d_70('', generateName(description)) + }); +}; +defineProperties(SymbolPolyfill, { + for: _$d_70(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = SymbolPolyfill(String(key))); + }), + keyFor: _$d_70(function (s) { + var key; + _$validateSymbol_129(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + + // To ensure proper interoperability with other native functions (e.g. Array.from) + // fallback to eventual native implementation of given symbol + hasInstance: _$d_70('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')), + isConcatSpreadable: _$d_70('', (NativeSymbol && NativeSymbol.isConcatSpreadable) || + SymbolPolyfill('isConcatSpreadable')), + iterator: _$d_70('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')), + match: _$d_70('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')), + replace: _$d_70('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')), + search: _$d_70('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')), + species: _$d_70('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')), + split: _$d_70('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')), + toPrimitive: _$d_70('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')), + toStringTag: _$d_70('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')), + unscopables: _$d_70('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables')) +}); + +// Internal tweaks for real symbol producer +defineProperties(HiddenSymbol.prototype, { + constructor: _$d_70(SymbolPolyfill), + toString: _$d_70('', function () { return this.__name__; }) +}); + +// Proper implementation of methods exposed on Symbol.prototype +// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype +defineProperties(SymbolPolyfill.prototype, { + toString: _$d_70(function () { return 'Symbol (' + _$validateSymbol_129(this).__description__ + ')'; }), + valueOf: _$d_70(function () { return _$validateSymbol_129(this); }) +}); +__defineProperty_128(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, _$d_70('', function () { + var symbol = _$validateSymbol_129(this); + if (typeof symbol === 'symbol') return symbol; + return symbol.toString(); +})); +__defineProperty_128(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, _$d_70('c', 'Symbol')); + +// Proper implementaton of toPrimitive and toStringTag for returned symbol instances +__defineProperty_128(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, + _$d_70('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); + +// Note: It's important to define `toPrimitive` as last one, as some implementations +// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) +// And that may invoke error in definition flow: +// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 +__defineProperty_128(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, + _$d_70('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); + +'use strict'; + +var _$es6Symbol_125 = _$isImplemented_126() ? Symbol : _$polyfill_128; + +"use strict"; + +var iteratorSymbol = _$es6Symbol_125.iterator + , __dummy_82$0 = 0 + , __dummy_82$1 = 0 + , __dummy_82$2 = 0 + , __dummy_82$3 = 0 + , __dummy_82$4 = 0 + , __dummy_82$5 = 0 + , __dummy_82$6 = 0 + , __isArray_82 = Array.isArray + , call = Function.prototype.call + , desc = { configurable: true, enumerable: true, writable: true, value: null } + , __defineProperty_82 = Object.defineProperty; + +// eslint-disable-next-line complexity +var _$shim_82 = function (arrayLike /*, mapFn, thisArg*/) { + var mapFn = arguments[1] + , thisArg = arguments[2] + , Context + , i + , j + , arr + , length + , code + , iterator + , result + , getIterator + , value; + + arrayLike = Object(_$validValue_111(arrayLike)); + + if (_$isValue_100(mapFn)) _$validCallable_109(mapFn); + if (!this || this === Array || !_$isFunction_84(this)) { + // Result: Plain array + if (!mapFn) { + if (_$isArguments_83(arrayLike)) { + // Source: Arguments + length = arrayLike.length; + if (length !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (__isArray_82(arrayLike)) { + // Source: Array + arr = new Array(length = arrayLike.length); + for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + // Result: Non plain array + Context = this; + } + + if (!__isArray_82(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { + // Source: Iterator + iterator = _$validCallable_109(getIterator).call(arrayLike); + if (Context) arr = new Context(); + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (Context) { + desc.value = value; + __defineProperty_82(arr, i, desc); + } else { + arr[i] = value; + } + result = iterator.next(); + ++i; + } + length = i; + } else if (_$isString_115(arrayLike)) { + // Source: String + length = arrayLike.length; + if (Context) arr = new Context(); + for (i = 0, j = 0; i < length; ++i) { + value = arrayLike[i]; + if (i + 1 < length) { + code = value.charCodeAt(0); + // eslint-disable-next-line max-depth + if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (Context) { + desc.value = value; + __defineProperty_82(arr, j, desc); + } else { + arr[j] = value; + } + ++j; + } + length = j; + } + } + if (length === undefined) { + // Source: array or array-like + length = _$toPosInteger_90(arrayLike.length); + if (Context) arr = new Context(length); + for (i = 0; i < length; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (Context) { + desc.value = value; + __defineProperty_82(arr, i, desc); + } else { + arr[i] = value; + } + } + } + if (Context) { + desc.value = null; + arr.length = length; + } + return arr; +}; + +"use strict"; + +var _$from_80 = _$isImplemented_81() + ? Array.from + : _$shim_82; + +"use strict"; + +var __dummy_95$0 = 0 + , __dummy_95$1 = 0 + , __dummy_95$2 = 0; + +var _$copy_95 = function (obj/*, propertyNames, options*/) { + var copy = Object(_$validValue_111(obj)), propertyNames = arguments[1], options = Object(arguments[2]); + if (copy !== obj && !propertyNames) return copy; + var result = {}; + if (propertyNames) { + _$from_80(propertyNames, function (propertyName) { + if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; + }); + } else { + _$assign_92(result, obj); + } + return result; +}; + +// Internal method, used by iteration functions. +// Calls a function for each key-value pair found in object +// Optionally takes compareFn to iterate object in specific order + +"use strict"; + +var __dummy_91$0 = 0 + , __dummy_91$1 = 0 + , bind = Function.prototype.bind + , __call_91 = Function.prototype.call + , __keys_91 = Object.keys + , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +var _$_iterate_91 = function (method, defVal) { + return function (obj, cb /*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(_$validValue_111(obj)); + _$validCallable_109(cb); + + list = __keys_91(obj); + if (compareFn) { + list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); + } + if (typeof method !== "function") method = list[method]; + return __call_91.call(method, list, function (key, index) { + if (!objPropertyIsEnumerable.call(obj, key)) return defVal; + return __call_91.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; + +"use strict"; + +var _$forEach_97 = _$_iterate_91("forEach"); + +"use strict"; + +var __dummy_104$0 = 0 + , __dummy_104$1 = 0 + , __call_104 = Function.prototype.call; + +var _$map_104 = function (obj, cb /*, thisArg*/) { + var result = {}, thisArg = arguments[2]; + _$validCallable_109(cb); + _$forEach_97(obj, function (value, key, targetObj, index) { + result[key] = __call_104.call(cb, thisArg, value, key, targetObj, index); + }); + return result; +}; + +'use strict'; + +var __dummy_69$0 = 0 + , __dummy_69$1 = 0 + , __dummy_69$2 = 0 + , __dummy_69$3 = 0 + , __dummy_69$4 = 0 + , __dummy_69$5 = 0 + + , __bind_69 = Function.prototype.bind, __defineProperty_69 = Object.defineProperty + , __hasOwnProperty_69 = Object.prototype.hasOwnProperty + , define; + +define = function (name, desc, options) { + var value = _$validValue_111(desc) && _$validCallable_109(desc.value), dgs; + dgs = _$copy_95(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function () { + if (!options.overwriteDefinition && __hasOwnProperty_69.call(this, name)) return value; + desc.value = __bind_69.call(value, options.resolveContext ? options.resolveContext(this) : this); + __defineProperty_69(this, name, desc); + return this[name]; + }; + return dgs; +}; + +var _$autoBind_69 = function (props/*, options*/) { + var options = _$normalizeOptions_105(arguments[1]); + if (options.resolveContext != null) _$validCallable_109(options.resolveContext); + return _$map_104(props, function (desc, name) { return define(name, desc, options); }); +}; + +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear + +"use strict"; + +/* removed: var _$validValue_111 = require("../../object/valid-value"); */; + +var _$clear_79 = function () { + _$validValue_111(this).length = 0; + return this; +}; + +"use strict"; + +var __dummy_120$0 = 0 + , __dummy_120$1 = 0 + , __dummy_120$2 = 0 + , __dummy_120$3 = 0 + , __dummy_120$4 = 0 + , __dummy_120$5 = 0 + , __dummy_120$6 = 0; + +var __defineProperty_120 = Object.defineProperty, __defineProperties_120 = Object.defineProperties, Iterator; + +var _$es6Iterator_120 = Iterator = function (list, context) { + if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); + __defineProperties_120(this, { + __list__: _$d_70("w", _$validValue_111(list)), + __context__: _$d_70("w", context), + __nextIndex__: _$d_70("w", 0) + }); + if (!context) return; + _$validCallable_109(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_120( + Iterator.prototype, + _$assign_92( + { + _next: _$d_70(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_70(function () { + return this._createResult(this._next()); + }), + _createResult: _$d_70(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: _$d_70(function (i) { + return this.__list__[i]; + }), + _unBind: _$d_70(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_70(function () { + return "[object " + (this[_$es6Symbol_125.toStringTag] || "Object") + "]"; + }) + }, + _$autoBind_69({ + _onAdd: _$d_70(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + __defineProperty_120(this, "__redo__", _$d_70("c", [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: _$d_70(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_70(function () { + if (this.__redo__) _$clear_79.call(this.__redo__); + this.__nextIndex__ = 0; + }) + }) + ) +); + +__defineProperty_120( + Iterator.prototype, + _$es6Symbol_125.iterator, + _$d_70(function () { + return this; + }) +); + +var _$array_117 = {}; +"use strict"; + +var __dummy_117$0 = 0 + , __dummy_117$1 = 0 + , __dummy_117$2 = 0 + , __dummy_117$3 = 0 + , __dummy_117$4 = 0; + +var __defineProperty_117 = Object.defineProperty, ArrayIterator; - return false; -} +ArrayIterator = _$array_117 = function (arr, kind) { + if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); + _$es6Iterator_120.call(this, arr); + if (!kind) kind = "value"; + else if (_$contains_112.call(kind, "key+value")) kind = "key+value"; + else if (_$contains_112.call(kind, "key")) kind = "key"; + else kind = "value"; + __defineProperty_117(this, "__kind__", _$d_70("", kind)); +}; +if (_$setPrototypeOf_106) _$setPrototypeOf_106(ArrayIterator, _$es6Iterator_120); -// 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; -} +// Internal %ArrayIteratorPrototype% doesn't expose its constructor +delete ArrayIterator.prototype.constructor; -// 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); +ArrayIterator.prototype = Object.create(_$es6Iterator_120.prototype, { + _resolve: _$d_70(function (i) { + if (this.__kind__ === "value") return this.__list__[i]; + if (this.__kind__ === "key+value") return [i, this.__list__[i]]; + return i; + }) +}); +__defineProperty_117(ArrayIterator.prototype, _$es6Symbol_125.toStringTag, _$d_70("c", "Array Iterator")); - return inside; -} +var _$string_122 = {}; +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols -// 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; +"use strict"; - a.next = b; - b.prev = a; +var __dummy_122$0 = 0 + , __dummy_122$1 = 0 + , __dummy_122$2 = 0 + , __dummy_122$3 = 0; + +var __defineProperty_122 = Object.defineProperty, StringIterator; + +StringIterator = _$string_122 = function (str) { + if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); + str = String(str); + _$es6Iterator_120.call(this, str); + __defineProperty_122(this, "__length__", _$d_70("", str.length)); +}; +if (_$setPrototypeOf_106) _$setPrototypeOf_106(StringIterator, _$es6Iterator_120); + +// Internal %ArrayIteratorPrototype% doesn't expose its constructor +delete StringIterator.prototype.constructor; + +StringIterator.prototype = Object.create(_$es6Iterator_120.prototype, { + _next: _$d_70(function () { + if (!this.__list__) return undefined; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + return undefined; + }), + _resolve: _$d_70(function (i) { + var char = this.__list__[i], code; + if (this.__nextIndex__ === this.__length__) return char; + code = char.charCodeAt(0); + if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++]; + return char; + }) +}); +__defineProperty_122(StringIterator.prototype, _$es6Symbol_125.toStringTag, _$d_70("c", "String Iterator")); - a2.next = an; - an.prev = a2; +"use strict"; - b2.next = a2; - a2.prev = b2; +var __dummy_121$0 = 0 + , __dummy_121$1 = 0 + , __dummy_121$2 = 0; - bp.next = b2; - b2.prev = bp; +var __iteratorSymbol_121 = _$es6Symbol_125.iterator + , __isArray_121 = Array.isArray; - return b2; -} +var _$isIterable_121 = function (value) { + if (!_$isValue_100(value)) return false; + if (__isArray_121(value)) return true; + if (_$isString_115(value)) return true; + if (_$isArguments_83(value)) return true; + return typeof value[__iteratorSymbol_121] === "function"; +}; -// 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); +"use strict"; - if (!last) { - p.prev = p; - p.next = p; +/* removed: var _$isIterable_121 = require("./is-iterable"); */; - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} +var _$validIterable_123 = function (value) { + if (!_$isIterable_121(value)) throw new TypeError(value + " is not iterable"); + return value; +}; -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; +"use strict"; - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} +var __dummy_119$0 = 0 + , __dummy_119$1 = 0 + , __dummy_119$2 = 0 + , __dummy_119$3 = 0 + , __dummy_119$4 = 0 + , __iteratorSymbol_119 = _$es6Symbol_125.iterator; -function Node(i, x, y) { - // vertice index in coordinates array - this.i = i; +var _$get_119 = function (obj) { + if (typeof _$validIterable_123(obj)[__iteratorSymbol_119] === "function") return obj[__iteratorSymbol_119](); + if (_$isArguments_83(obj)) return new _$array_117(obj); + if (_$isString_115(obj)) return new _$string_122(obj); + return new _$array_117(obj); +}; - // vertex coordinates - this.x = x; - this.y = y; +"use strict"; - // previous and next vertice nodes in a polygon ring - this.prev = null; - this.next = null; +var __dummy_118$0 = 0 + , __dummy_118$1 = 0 + , __dummy_118$2 = 0 + , __dummy_118$3 = 0; - // z-order curve value - this.z = null; +var __isArray_118 = Array.isArray, __call_118 = Function.prototype.call, some = Array.prototype.some; - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; +var _$forOf_118 = function (iterable, cb /*, thisArg*/) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code; + if (__isArray_118(iterable) || _$isArguments_83(iterable)) mode = "array"; + else if (_$isString_115(iterable)) mode = "string"; + else iterable = _$get_119(iterable); - // indicates whether this is a steiner point - this.steiner = false; -} + _$validCallable_109(cb); + doBreak = function () { + broken = true; + }; + if (mode === "array") { + some.call(iterable, function (value) { + __call_118.call(cb, thisArg, value, doBreak); + return broken; + }); + return; + } + if (mode === "string") { + length = iterable.length; + for (i = 0; i < length; ++i) { + char = iterable[i]; + if (i + 1 < length) { + code = char.charCodeAt(0); + if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i]; + } + __call_118.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); -// 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; + while (!result.done) { + __call_118.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } +}; - 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)); - } - } +// Exports true if environment provides native `WeakMap` implementation, whatever that is. - 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])); - } +'use strict'; - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); +var _$isNativeImplemented_132 = (function () { + if (typeof WeakMap !== 'function') return false; + return (Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'); +}()); + +'use strict'; + +var __dummy_133$0 = 0 + , __dummy_133$1 = 0 + , __dummy_133$2 = 0 + , __dummy_133$3 = 0 + , __dummy_133$4 = 0 + , __dummy_133$5 = 0 + , __dummy_133$6 = 0 + , toStringTagSymbol = _$es6Symbol_125.toStringTag + , __dummy_133$7 = 0 + + , __isArray_133 = Array.isArray, __defineProperty_133 = Object.defineProperty + , __hasOwnProperty_133 = Object.prototype.hasOwnProperty, __getPrototypeOf_133 = Object.getPrototypeOf + , WeakMapPoly; + +var _$polyfill_133 = WeakMapPoly = function (/*iterable*/) { + var iterable = arguments[0], self; + if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\''); + if (_$isNativeImplemented_132 && _$setPrototypeOf_106 && (WeakMap !== WeakMapPoly)) { + self = _$setPrototypeOf_106(new WeakMap(), __getPrototypeOf_133(this)); + } else { + self = this; + } + if (iterable != null) { + if (!__isArray_133(iterable)) iterable = _$get_119(iterable); + } + __defineProperty_133(self, '__weakMapData__', _$d_70('c', '$weakMap$' + _$randomUniq_116())); + if (!iterable) return self; + _$forOf_118(iterable, function (val) { + _$validValue_111(val); + self.set(val[0], val[1]); + }); + return self; }; -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; +if (_$isNativeImplemented_132) { + if (_$setPrototypeOf_106) _$setPrototypeOf_106(WeakMapPoly, WeakMap); + WeakMapPoly.prototype = Object.create(WeakMap.prototype, { + constructor: _$d_70(WeakMapPoly) + }); } -// 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; +Object.defineProperties(WeakMapPoly.prototype, { + delete: _$d_70(function (key) { + if (__hasOwnProperty_133.call(_$validObject_110(key), this.__weakMapData__)) { + delete key[this.__weakMapData__]; + return true; + } + return false; + }), + get: _$d_70(function (key) { + if (__hasOwnProperty_133.call(_$validObject_110(key), this.__weakMapData__)) { + return key[this.__weakMapData__]; + } + }), + has: _$d_70(function (key) { + return __hasOwnProperty_133.call(_$validObject_110(key), this.__weakMapData__); + }), + set: _$d_70(function (key, value) { + __defineProperty_133(_$validObject_110(key), this.__weakMapData__, _$d_70('c', value)); + return this; + }), + toString: _$d_70(function () { return '[object WeakMap]'; }) +}); +__defineProperty_133(WeakMapPoly.prototype, toStringTagSymbol, _$d_70('c', 'WeakMap')); + +'use strict'; + +var _$es6WeakMap_130 = _$isImplemented_131() ? WeakMap : _$polyfill_133; + +'use strict' + + +/* removed: var _$normalize_59 = require('color-normalize') */; +/* removed: var _$normalize_13 = require('array-bounds') */; +/* removed: var _$objectAssign_204 = require('object-assign') */; +/* removed: var _$browser_181 = require('glslify') */; +/* removed: var _$pick_212 = require('pick-by-alias') */; +/* removed: var _$flattenVertexData_136 = require('flatten-vertex-data') */; +/* removed: var _$earcut_77 = require('earcut') */; +/* removed: var _$normalize_14 = require('array-normalize') */; +/* removed: var _$toFloat32_264 = require('to-float32'); */; +var __float32_235 = _$toFloat32_264.float32; +var __fract32_235 = _$toFloat32_264.fract32; +/* removed: var _$es6WeakMap_130 = require('es6-weak-map') */; +/* removed: var _$parseRect_206 = require('parse-rect') */; + + +var _$Line2D_235 = Line2D + + +/** @constructor */ +function Line2D (regl, options) { + if (!(this instanceof Line2D)) { return new Line2D(regl, options) } + + if (typeof regl === 'function') { + if (!options) { options = {} } + options.regl = regl + } + else { + options = regl + } + if (options.length) { options.positions = options } + regl = options.regl + + if (!regl.hasExtension('ANGLE_instanced_arrays')) { + throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled'); + } + + // persistent variables + this.gl = regl._gl + this.regl = regl + + // list of options for lines + this.passes = [] + + // cached shaders instance + this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl) + + + // init defaults + this.update(options) +} + + +Line2D.dashMult = 2 +Line2D.maxPatternLength = 256 +Line2D.precisionThreshold = 3e6 +Line2D.maxPoints = 1e4 + + + +// cache of created draw calls per-regl instance +Line2D.shaders = new _$es6WeakMap_130() + + +// create static shaders once +Line2D.createShaders = function (regl) { + var offsetBuffer = regl.buffer({ + usage: 'static', + type: 'float', + data: [0,1, 0,0, 1,1, 1,0] + }) + + var shaderOptions = { + primitive: 'triangle strip', + instances: regl.prop('count'), + count: 4, + offset: 0, + + uniforms: { + miterMode: function (ctx, prop) { return prop.join === 'round' ? 2 : 1; }, + miterLimit: regl.prop('miterLimit'), + scale: regl.prop('scale'), + scaleFract: regl.prop('scaleFract'), + translateFract: regl.prop('translateFract'), + translate: regl.prop('translate'), + thickness: regl.prop('thickness'), + dashPattern: regl.prop('dashTexture'), + opacity: regl.prop('opacity'), + pixelRatio: regl.context('pixelRatio'), + id: regl.prop('id'), + dashSize: regl.prop('dashLength'), + viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; } + }, + + blend: { + enable: true, + color: [0,0,0,0], + equation: { + rgb: 'add', + alpha: 'add' + }, + func: { + srcRGB: 'src alpha', + dstRGB: 'one minus src alpha', + srcAlpha: 'one minus dst alpha', + dstAlpha: 'one' + } + }, + depth: { + // FIXME: that fills up stencil buffer + enable: function (ctx, prop) { + return !prop.overlay + } + }, + stencil: {enable: false}, + scissor: { + enable: true, + box: regl.prop('viewport') + }, + viewport: regl.prop('viewport') + } + + + // simplified rectangular line shader + var drawRectLine = regl(_$objectAssign_204({ + vert: _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), + frag: _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + + attributes: { + // if point is at the end of segment + lineEnd: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 0 + }, + // if point is at the top of segment + lineTop: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 4 + }, + // beginning of line coordinate + aCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 8, + divisor: 1 + }, + // end of line coordinate + bCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 16, + divisor: 1 + }, + aCoordFract: { + buffer: regl.prop('positionFractBuffer'), + stride: 8, + offset: 8, + divisor: 1 + }, + bCoordFract: { + buffer: regl.prop('positionFractBuffer'), + stride: 8, + offset: 16, + divisor: 1 + }, + color: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 0, + divisor: 1 + } + } + }, shaderOptions)) + + // create regl draw + var drawMiterLine + + try { + drawMiterLine = regl(_$objectAssign_204({ + // culling removes polygon creasing + cull: { + enable: true, + face: 'back' + }, + + vert: _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n\t// adjust scale for horizontal bars\n\tvec2 scale = max(scale, MIN_DIFF);\n\tvec2 scaleRatio = scale * viewport.zw;\n\n\tvec2 normalWidth = thickness / (scale * viewport.zw);\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]), + frag: _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + + attributes: { + // is line end + lineEnd: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 0 + }, + // is line top + lineTop: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 4 + }, + // left color + aColor: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 0, + divisor: 1 + }, + // right color + bColor: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 4, + divisor: 1 + }, + prevCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 0, + divisor: 1 + }, + aCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 8, + divisor: 1 + }, + bCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 16, + divisor: 1 + }, + nextCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 24, + divisor: 1 + } + } + }, shaderOptions)) + } catch (e) { + // IE/bad Webkit fallback + drawMiterLine = drawRectLine + } + + // fill shader + var drawFill = regl({ + primitive: 'triangle', + elements: function (ctx, prop) { return prop.triangles; }, + offset: 0, + + vert: _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]), + frag: _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]), + + uniforms: { + scale: regl.prop('scale'), + color: regl.prop('fill'), + scaleFract: regl.prop('scaleFract'), + translateFract: regl.prop('translateFract'), + translate: regl.prop('translate'), + opacity: regl.prop('opacity'), + pixelRatio: regl.context('pixelRatio'), + id: regl.prop('id'), + viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; } + }, + + attributes: { + position: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 8 + }, + positionFract: { + buffer: regl.prop('positionFractBuffer'), + stride: 8, + offset: 8 + } + }, + + blend: shaderOptions.blend, + + depth: { enable: false }, + scissor: shaderOptions.scissor, + stencil: shaderOptions.stencil, + viewport: shaderOptions.viewport + }) + + return { + fill: drawFill, rect: drawRectLine, miter: drawMiterLine + } +} + + +// used to for new lines instances +Line2D.defaults = { + dashes: null, + join: 'miter', + miterLimit: 1, + thickness: 10, + cap: 'square', + color: 'black', + opacity: 1, + overlay: false, + viewport: null, + range: null, + close: false, + fill: null +} + + +Line2D.prototype.render = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (args.length) { + (ref = this).update.apply(ref, args) + } + + this.draw() + var ref; +} + + +Line2D.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + // render multiple polylines via regl batch + (args.length ? args : this.passes).forEach(function (s, i) { + // render array pass as a list of passes + if (s && Array.isArray(s)) { return (ref = this$1).draw.apply(ref, s) } + + if (typeof s === 'number') { s = this$1.passes[s] } + + if (!(s && s.count > 1 && s.opacity)) { return } + + this$1.regl._refresh() + + if (s.fill && s.triangles && s.triangles.length > 2) { + this$1.shaders.fill(s) + } + + if (!s.thickness) { return } + + // high scale is only available for rect mode with precision + if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) { + this$1.shaders.rect(s) + } + + // thin this.passes or too many points are rendered as simplified rect shader + else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints))) { + this$1.shaders.rect(s) + } + else { + this$1.shaders.miter(s) + } + var ref; + }) + + return this +} + + +Line2D.prototype.update = function (options) { + var this$1 = this; + + if (!options) { return } + + if (options.length != null) { + if (typeof options[0] === 'number') { options = [{positions: options}] } + } + + // make options a batch + else if (!Array.isArray(options)) { options = [options] } + + var ref = this; + var regl = ref.regl; + var gl = ref.gl; + + // process per-line settings + options.forEach(function (o, i) { + var state = this$1.passes[i] + + if (o === undefined) { return } + + // null-argument removes pass + if (o === null) { + this$1.passes[i] = null + return + } + + if (typeof o[0] === 'number') { o = {positions: o} } + + // handle aliases + o = _$pick_212(o, { + positions: 'positions points data coords', + thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth', + join: 'lineJoin linejoin join type mode', + miterLimit: 'miterlimit miterLimit', + dashes: 'dash dashes dasharray dash-array dashArray', + color: 'color colour stroke colors colours stroke-color strokeColor', + fill: 'fill fill-color fillColor', + opacity: 'alpha opacity', + overlay: 'overlay crease overlap intersect', + close: 'closed close closed-path closePath', + range: 'range dataBox', + viewport: 'viewport viewBox', + hole: 'holes hole hollow' + }) + + // init state + if (!state) { + this$1.passes[i] = state = { + id: i, + scale: null, + scaleFract: null, + translate: null, + translateFract: null, + count: 0, + hole: [], + + dashLength: 1, + dashTexture: regl.texture({ + channels: 1, + data: new Uint8Array([255]), + width: 1, + height: 1, + mag: 'linear', + min: 'linear' + }), + + colorBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8', + data: null + }), + positionBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }), + positionFractBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }) + } + + o = _$objectAssign_204({}, Line2D.defaults, o) + } + if (o.thickness != null) { state.thickness = parseFloat(o.thickness) } + if (o.opacity != null) { state.opacity = parseFloat(o.opacity) } + if (o.miterLimit != null) { state.miterLimit = parseFloat(o.miterLimit) } + if (o.overlay != null) { state.overlay = !!o.overlay } + if (o.join != null) { state.join = o.join } + if (o.hole != null) { state.hole = o.hole } + if (o.fill != null) { state.fill = !o.fill ? null : _$normalize_59(o.fill, 'uint8') } + if (o.viewport != null) { state.viewport = _$parseRect_206(o.viewport) } + + if (!state.viewport) { + state.viewport = _$parseRect_206([ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]) + } + + if (o.close != null) { state.close = o.close } + + // reset positions + if (o.positions === null) { o.positions = [] } + if (o.positions) { + var positions, count + + // if positions are an object with x/y + if (o.positions.x && o.positions.y) { + var xPos = o.positions.x + var yPos = o.positions.y + count = state.count = Math.max( + xPos.length, + yPos.length + ) + positions = new Float64Array(count * 2) + for (var i$1 = 0; i$1 < count; i$1++) { + positions[i$1 * 2] = xPos[i$1] + positions[i$1 * 2 + 1] = yPos[i$1] + } + } + else { + positions = _$flattenVertexData_136(o.positions, 'float64') + count = state.count = Math.floor(positions.length / 2) + } + + var bounds = state.bounds = _$normalize_13(positions, 2) + + // create fill positions + // FIXME: fill positions can be set only along with positions + if (state.fill) { + var pos = [] + + // filter bad vertices and remap triangles to ensure shape + var ids = {} + var lastId = 0 + + for (var i$2 = 0, ptr = 0, l = state.count; i$2 < l; i$2++) { + var x = positions[i$2*2] + var y = positions[i$2*2 + 1] + if (isNaN(x) || isNaN(y) || x == null || y == null) { + x = positions[lastId*2] + y = positions[lastId*2 + 1] + ids[i$2] = lastId + } + else { + lastId = i$2 + } + pos[ptr++] = x + pos[ptr++] = y + } + + var triangles = _$earcut_77(pos, state.hole || []) + + for (var i$3 = 0, l$1 = triangles.length; i$3 < l$1; i$3++) { + if (ids[triangles[i$3]] != null) { triangles[i$3] = ids[triangles[i$3]] } + } + + state.triangles = triangles + } + + // update position buffers + var npos = new Float64Array(positions) + _$normalize_14(npos, 2, bounds) + + var positionData = new Float64Array(count * 2 + 6) + + // rotate first segment join + if (state.close) { + if (positions[0] === positions[count*2 - 2] && + positions[1] === positions[count*2 - 1]) { + positionData[0] = npos[count*2 - 4] + positionData[1] = npos[count*2 - 3] + } + else { + positionData[0] = npos[count*2 - 2] + positionData[1] = npos[count*2 - 1] + } + } + else { + positionData[0] = npos[0] + positionData[1] = npos[1] + } + + positionData.set(npos, 2) + + // add last segment + if (state.close) { + // ignore coinciding start/end + if (positions[0] === positions[count*2 - 2] && + positions[1] === positions[count*2 - 1]) { + positionData[count*2 + 2] = npos[2] + positionData[count*2 + 3] = npos[3] + state.count -= 1 + } + else { + positionData[count*2 + 2] = npos[0] + positionData[count*2 + 3] = npos[1] + positionData[count*2 + 4] = npos[2] + positionData[count*2 + 5] = npos[3] + } + } + // add stub + else { + positionData[count*2 + 2] = npos[count*2 - 2] + positionData[count*2 + 3] = npos[count*2 - 1] + positionData[count*2 + 4] = npos[count*2 - 2] + positionData[count*2 + 5] = npos[count*2 - 1] + } + + state.positionBuffer(__float32_235(positionData)) + state.positionFractBuffer(__fract32_235(positionData)) + } + + if (o.range) { + state.range = o.range + } else if (!state.range) { + state.range = state.bounds + } + + if ((o.range || o.positions) && state.count) { + var bounds$1 = state.bounds + + var boundsW = bounds$1[2] - bounds$1[0], + boundsH = bounds$1[3] - bounds$1[1] + + var rangeW = state.range[2] - state.range[0], + rangeH = state.range[3] - state.range[1] + + state.scale = [ + boundsW / rangeW, + boundsH / rangeH + ] + state.translate = [ + -state.range[0] / rangeW + bounds$1[0] / rangeW || 0, + -state.range[1] / rangeH + bounds$1[1] / rangeH || 0 + ] + + state.scaleFract = __fract32_235(state.scale) + state.translateFract = __fract32_235(state.translate) + } + + if (o.dashes) { + var dashLength = 0., dashData + + if (!o.dashes || o.dashes.length < 2) { + dashLength = 1. + dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]) + } + + else { + dashLength = 0.; + for(var i$4 = 0; i$4 < o.dashes.length; ++i$4) { + dashLength += o.dashes[i$4] + } + dashData = new Uint8Array(dashLength * Line2D.dashMult) + var ptr$1 = 0 + var fillColor = 255 + + // repeat texture two times to provide smooth 0-step + for (var k = 0; k < 2; k++) { + for(var i$5 = 0; i$5 < o.dashes.length; ++i$5) { + for(var j = 0, l$2 = o.dashes[i$5] * Line2D.dashMult * .5; j < l$2; ++j) { + dashData[ptr$1++] = fillColor + } + fillColor ^= 255 + } + } + } + + state.dashLength = dashLength + state.dashTexture({ + channels: 1, + data: dashData, + width: dashData.length, + height: 1, + mag: 'linear', + min: 'linear' + }, 0, 0) + } + + if (o.color) { + var count$1 = state.count + var colors = o.color + + if (!colors) { colors = 'transparent' } + + var colorData = new Uint8Array(count$1 * 4 + 4) + + // convert colors to typed arrays + if (!Array.isArray(colors) || typeof colors[0] === 'number') { + var c = _$normalize_59(colors, 'uint8') + + for (var i$6 = 0; i$6 < count$1 + 1; i$6++) { + colorData.set(c, i$6 * 4) + } + } else { + for (var i$7 = 0; i$7 < count$1; i$7++) { + var c$1 = _$normalize_59(colors[i$7], 'uint8') + colorData.set(c$1, i$7 * 4) + } + colorData.set(_$normalize_59(colors[0], 'uint8'), count$1 * 4) + } + + state.colorBuffer({ + usage: 'dynamic', + type: 'uint8', + data: colorData + }) + } + }) + + // remove unmentioned passes + if (options.length < this.passes.length) { + for (var i = options.length; i < this.passes.length; i++) { + var pass = this$1.passes[i] + if (!pass) { continue } + pass.colorBuffer.destroy() + pass.positionBuffer.destroy() + pass.dashTexture.destroy() + } + this.passes.length = options.length + } + + // remove null items + this.passes = this.passes.filter(Boolean) + + return this +} + +Line2D.prototype.destroy = function () { + this.passes.forEach(function (pass) { + pass.colorBuffer.destroy() + pass.positionBuffer.destroy() + pass.dashTexture.destroy() + }) + + this.passes.length = 0 + + return this +} +var _$colorId_57 = {}; +/** @module color-id */ + +'use strict' + +/* removed: var _$clamp_54 = require('clamp') */; + +_$colorId_57 = toNumber +_$colorId_57.to = toNumber +_$colorId_57.from = fromNumber + +function toNumber (rgba, normalized) { + if(normalized == null) normalized = true + + var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3] + + if (a == null) a = normalized ? 1 : 255 + + if (normalized) { + r *= 255 + g *= 255 + b *= 255 + a *= 255 + } + + r = _$clamp_54(r, 0, 255) & 0xFF + g = _$clamp_54(g, 0, 255) & 0xFF + b = _$clamp_54(b, 0, 255) & 0xFF + a = _$clamp_54(a, 0, 255) & 0xFF + + //hi-order shift converts to -1, so we can't use <<24 + var n = (r * 0x01000000) + (g << 16) + (b << 8) + (a) + + return n +} + +function fromNumber (n, normalized) { + n = +n + + var r = n >>> 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] +} - 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; -}; +'use strict'; +var _$isIexplorer_190 = typeof navigator !== 'undefined' && + (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); 'use strict' -/* removed: var _$normalize_58 = require('color-normalize') */; -/* removed: var _$normalize_12 = require('array-bounds') */; -/* removed: var _$objectAssign_146 = require('object-assign') */; -/* removed: var _$browser_124 = require('glslify') */; -/* removed: var _$pick_153 = require('pick-by-alias') */; -/* removed: var _$updateDiff_210 = require('update-diff') */; -/* removed: var _$flattenVertexData_79 = require('flatten-vertex-data') */; -/* removed: var _$earcut_74 = require('earcut') */; -/* removed: var _$normalize_13 = require('array-normalize') */; +/* removed: var _$normalize_59 = require('color-normalize') */; +/* removed: var _$normalize_13 = require('array-bounds') */; +/* removed: var _$colorId_57 = require('color-id') */; +/* removed: var _$pointCluster_216 = require('point-cluster') */; +/* removed: var _$objectAssign_204 = require('object-assign') */; +/* removed: var _$browser_181 = require('glslify') */; +/* removed: var _$pick_212 = require('pick-by-alias') */; +/* removed: var _$updateDiff_272 = require('update-diff') */; +/* removed: var _$flattenVertexData_136 = require('flatten-vertex-data') */; +/* removed: var _$isIexplorer_190 = require('is-iexplorer') */; +/* removed: var _$toFloat32_264 = require('to-float32'); */; +var __float32_237 = _$toFloat32_264.float32; +var __fract32_237 = _$toFloat32_264.fract32; +/* removed: var _$parseRect_206 = require('parse-rect') */; + -var _$createLine_172 = __createLine_172 +var _$Scatter_237 = __Scatter_237 -var MAX_SCALE = 1e10; +function __Scatter_237 (regl, options) { + var this$1 = this; + if (!(this instanceof __Scatter_237)) { return new __Scatter_237(regl, options) } -function __createLine_172 (regl, options) { if (typeof regl === 'function') { if (!options) { options = {} } options.regl = regl } else { options = regl + regl = null } - if (options.length) { options.positions = options } - regl = options.regl - if (!regl.hasExtension('ANGLE_instanced_arrays')) { - throw Error('regl-error2d: `ANGLE_instanced_arrays` extension should be enabled'); - } + if (options && options.length) { options.positions = options } + + regl = options.regl // persistent variables - var gl = regl._gl, drawMiterLine, drawRectLine, drawFill, colorBuffer, offsetBuffer, positionBuffer, positionFractBuffer, dashTexture, - - // used to for new lines instances - defaults = { - positions: [], - dashes: null, - join: null, - miterLimit: 1, - thickness: 10, - cap: 'square', - color: 'black', - opacity: 1, - overlay: false, - viewport: null, - range: null, - close: null, - fill: null - }, + var gl = regl._gl, paletteTexture, palette = [], paletteIds = {}, + + // state + groups = [], - // list of options for lines - lines = [] + // textures for marker keys + markerTextures = [null], + markerCache = [null] - var dashMult = 2, maxPatternLength = 256, maxLinesNumber = 2048, precisionThreshold = 3e6, maxPoints = 1e4 + var maxColors = 255, maxSize = 100 + // direct color buffer mode + // IE does not support palette anyways + this.tooManyColors = _$isIexplorer_190 - // color per-point - colorBuffer = regl.buffer({ - usage: 'dynamic', + // texture with color palette + paletteTexture = regl.texture({ + data: new Uint8Array(maxColors * 4), + width: maxColors, + height: 1, type: 'uint8', - data: null - }) - offsetBuffer = regl.buffer({ - usage: 'static', - type: 'float', - data: [0,1, 0,0, 1,1, 1,0] - }) - positionBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - positionFractBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null + format: 'rgba', + wrapS: 'clamp', + wrapT: 'clamp', + mag: 'nearest', + min: 'nearest' }) - dashTexture = regl.texture({ - channels: 1, - data: new Uint8Array(maxPatternLength * maxLinesNumber), - width: maxPatternLength, - height: maxLinesNumber, - mag: 'linear', - min: 'linear' + + _$objectAssign_204(this, { + regl: regl, + gl: gl, + groups: groups, + markerCache: markerCache, + markerTextures: markerTextures, + palette: palette, + paletteIds: paletteIds, + paletteTexture: paletteTexture, + maxColors: maxColors, + maxSize: maxSize, + canvas: gl.canvas }) - // init defaults - update(options) + this.update(options) + // common shader options var shaderOptions = { - primitive: 'triangle strip', - instances: regl.prop('count'), - count: 4, - offset: 0, - uniforms: { - miterMode: function (ctx, prop) { return prop.join === 'round' ? 2 : 1; }, - miterLimit: regl.prop('miterLimit'), + pixelRatio: regl.context('pixelRatio'), + palette: paletteTexture, + paletteSize: function (ctx, prop) { return [this$1.tooManyColors ? 0 : maxColors, paletteTexture.height]; }, scale: regl.prop('scale'), scaleFract: regl.prop('scaleFract'), - translateFract: regl.prop('translateFract'), translate: regl.prop('translate'), - thickness: regl.prop('thickness'), - dashPattern: dashTexture, - dashLength: regl.prop('dashLength'), - dashShape: [maxPatternLength, maxLinesNumber], + translateFract: regl.prop('translateFract'), opacity: regl.prop('opacity'), - pixelRatio: regl.context('pixelRatio'), - id: regl.prop('id'), - scaleRatio: regl.prop('scaleRatio'), - viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; } + marker: regl.prop('markerTexture'), + }, + + attributes: { + // FIXME: optimize these parts + x: function (ctx, prop) { return prop.xAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 0 + }; }, + y: function (ctx, prop) { return prop.yAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 4 + }; }, + xFract: function (ctx, prop) { return prop.xAttr ? { constant: [0, 0] } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 0 + }; }, + yFract: function (ctx, prop) { return prop.yAttr ? { constant: [0, 0] } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 4 + }; }, + size: function (ctx, prop) { return prop.size.length ? { + buffer: prop.sizeBuffer, + stride: 2, + offset: 0 + } : { + constant: [ Math.round(prop.size * 255 / this$1.maxSize) ] + }; }, + borderSize: function (ctx, prop) { return prop.borderSize.length ? { + buffer: prop.sizeBuffer, + stride: 2, + offset: 1 + } : { + constant: [ Math.round(prop.borderSize * 255 / this$1.maxSize) ] + }; }, + colorId: function (ctx, prop) { return prop.color.length ? { + buffer: prop.colorBuffer, + stride: this$1.tooManyColors ? 8 : 4, + offset: 0 + } : { + constant: this$1.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [ prop.color ] + }; }, + borderColorId: function (ctx, prop) { return prop.borderColor.length ? { + buffer: prop.colorBuffer, + stride: this$1.tooManyColors ? 8 : 4, + offset: this$1.tooManyColors ? 4 : 2 + } : { + constant: this$1.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [ prop.borderColor ] + }; }, + isActive: function (ctx, prop) { return prop.activation === true ? { constant: [1] } : prop.activation ? prop.activation : { constant: [0] }; } }, blend: { enable: true, - color: [0,0,0,0], - equation: { - rgb: 'add', - alpha: 'add' - }, + color: [0,0,0,1], + + // photoshop blending func: { srcRGB: 'src alpha', dstRGB: 'one minus src alpha', @@ -93802,4281 +97412,4928 @@ function __createLine_172 (regl, options) { dstAlpha: 'one' } }, - depth: { - enable: function (ctx, prop) { - return !prop.overlay - } - }, + scissor: { enable: true, box: regl.prop('viewport') }, - stencil: false, - viewport: regl.prop('viewport') - } + viewport: regl.prop('viewport'), - // create regl draw - drawMiterLine = regl(_$objectAssign_146({ - // culling removes polygon creasing - cull: { - enable: true, - face: 'back' - }, + stencil: {enable: false}, + depth: {enable: false}, - vert: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, dashLength, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIST = 1.;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevDirection = normalize(prevDiff);\n\tvec2 currDirection = normalize(currDiff);\n\tvec2 nextDirection = normalize(nextDiff);\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tif (prevDirection == currDirection) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (nextDirection == currDirection) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]), - frag: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + elements: regl.prop('elements'), + count: regl.prop('count'), + offset: regl.prop('offset'), - attributes: { - lineEnd: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 0 - }, - lineTop: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 4 - }, - aColor: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4; }, - divisor: 1 - }, - bColor: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4 + 4; }, - divisor: 1 - }, - prevCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return prop.offset * 8; }, - divisor: 1 - }, - aCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, - divisor: 1 - }, - bCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, - divisor: 1 - }, - nextCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 24 + prop.offset * 8; }, - divisor: 1 - } - } - }, shaderOptions)) + primitive: 'points' + } - // simplified rectangular line shader - drawRectLine = regl(_$objectAssign_146({ - vert: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\t// vec2 scaleRatio = scale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scaleRatio);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), - frag: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + // draw sdf-marker + var markerOptions = _$objectAssign_204({}, shaderOptions) + markerOptions.frag = _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]) + markerOptions.vert = _$browser_181(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n fragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]) - attributes: { - lineEnd: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 0 - }, - lineTop: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 4 - }, - aCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, - divisor: 1 - }, - bCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, - divisor: 1 - }, - aCoordFract: { - buffer: positionFractBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, - divisor: 1 - }, - bCoordFract: { - buffer: positionFractBuffer, - stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, - divisor: 1 - }, - color: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4; }, - divisor: 1 - } - } - }, shaderOptions)) + try { + this.drawMarker = regl(markerOptions) + } catch (e) { + } + // draw circle + var circleOptions = _$objectAssign_204({}, shaderOptions) + circleOptions.frag = _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]) + circleOptions.vert = _$browser_181(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]) - // fill shader - drawFill = regl({ - primitive: 'triangle', - elements: function (ctx, prop) { return prop.triangles; }, - offset: 0, + // polyfill IE + if (_$isIexplorer_190) { circleOptions.frag = circleOptions.frag.replace('smoothstep', 'smoothStep') } - vert: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), - frag: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= opacity;\n}\n"]), + this.drawCircle = regl(circleOptions) +} - uniforms: { - scale: regl.prop('scale'), - color: regl.prop('fill'), - scaleFract: regl.prop('scaleFract'), - translateFract: regl.prop('translateFract'), - translate: regl.prop('translate'), - opacity: regl.prop('opacity'), - pixelRatio: regl.context('pixelRatio'), - id: regl.prop('id'), - viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; } - }, +// single pass defaults +__Scatter_237.defaults = { + color: 'black', + borderColor: 'transparent', + borderSize: 0, + size: 12, + opacity: 1, + marker: undefined, + viewport: null, + range: null, + pixelSize: null, + count: 0, + offset: 0, + bounds: null, + positions: [], + snap: 1e4 +} - attributes: { - position: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; } - }, - positionFract: { - buffer: positionFractBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; } - } - }, - blend: shaderOptions.blend, +// update & redraw +__Scatter_237.prototype.render = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - depth: { - enable: false - }, - scissor: shaderOptions.scissor, - stencil: shaderOptions.stencil, - viewport: shaderOptions.viewport - }) + if (args.length) { + (ref = this).update.apply(ref, args) + } - // expose API - _$objectAssign_146(line2d, { - update: update, - draw: draw, - destroy: destroy, - regl: regl, - gl: gl, - canvas: gl.canvas, - lines: lines - }) + this.draw() - function line2d (opts) { - // update - if (opts) { - update(opts) - } + return this + var ref; +} - // destroy - else if (opts === null) { - destroy() - } - draw() - } +// draw all groups or only indicated ones +__Scatter_237.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - function draw (options) { - if (typeof options === 'number') { return drawLine(options) } + var ref = this; + var groups = ref.groups; - // make options a batch - if (options && !Array.isArray(options)) { options = [options] } + // if directly array passed - treat as passes + if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) { + args = args[0] + } - // render multiple polylines via regl batch - lines.forEach(function (s, i) { - drawLine(i) + if (args.length) { + for (var i = 0; i < args.length; i++) { + this$1.drawItem(i, args[i]) + } + } + // draw all passes + else { + groups.forEach(function (group, i) { + this$1.drawItem(i) }) } - // draw single line by id - function drawLine (s) { - if (typeof s === 'number') { s = lines[s] } + return this +} - if (!(s && s.count && s.opacity && s.positions && s.positions.length > 2)) { return } +// draw specific scatter group +__Scatter_237.prototype.drawItem = function (id, els) { + var this$1 = this; + + var ref = this; + var groups = ref.groups; + var group = groups[id] + + // debug viewport + // let { viewport } = group + // gl.enable(gl.SCISSOR_TEST); + // gl.scissor(viewport.x, viewport.y, viewport.width, viewport.height); + // gl.clearColor(0, 0, 0, .5); + // gl.clear(gl.COLOR_BUFFER_BIT); + + if (typeof els === 'number') { + id = els + group = groups[els] + els = null + } - regl._refresh() + if (!(group && group.count && group.opacity)) { return } - if (s.fill && s.triangles && s.triangles.length > 2) { - drawFill(s) - } + // draw circles + if (group.activation[0]) { + // TODO: optimize this performance by making groups and regl.this props + this.drawCircle(this.getMarkerDrawOptions(0, group, els)) + } - if (!s.thickness || !s.color) { return } + // draw all other available markers + var batch = [] - s.scaleRatio = [ - s.scale[0] * s.viewport.width, - s.scale[1] * s.viewport.height - ] + for (var i = 1; i < group.activation.length; i++) { + if (!group.activation[i] || (group.activation[i] !== true && !group.activation[i].data.length)) { continue } - // high scale is only available for rect mode with precision - if (s.scaleRatio[0] > precisionThreshold || s.scaleRatio[1] > precisionThreshold) { - drawRectLine(s) - } + batch.push.apply(batch, this$1.getMarkerDrawOptions(i, group, els)) + } + + if (batch.length) { + this.drawMarker(batch) + } +} - // thin lines or too many points are rendered as simplified rect shader - else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.positions.length >= maxPoints))) { - drawRectLine(s) +// get options for the marker ids +__Scatter_237.prototype.getMarkerDrawOptions = function(markerId, group, elements) { + var this$1 = this; + + var range = group.range; + var tree = group.tree; + var viewport = group.viewport; + var activation = group.activation; + var selectionBuffer = group.selectionBuffer; + var count = group.count; + var ref = this; + var regl = ref.regl; + + // direct points + if (!tree) { + // if elements array - draw unclustered points + if (elements) { + return [_$objectAssign_204({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + count: elements.length, + elements: elements, + offset: 0 + })] } - else { - drawMiterLine(s) + + return [ _$objectAssign_204({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + offset: 0 + }) ] + } + + // clustered points + var batch = [] + + var lod = tree.range(range, { lod: true, px: [ + (range[2] - range[0]) / viewport.width, + (range[3] - range[1]) / viewport.height + ]}) + + // enable elements by using selection buffer + if (elements) { + var markerActivation = activation[markerId] + var mask = markerActivation.data + var data = new Uint8Array(count) + for (var i = 0; i < elements.length; i++) { + var id = elements[i] + data[id] = mask ? mask[id] : 1 } + selectionBuffer.subdata(data) + } - if (s.after) { s.after(s) } + for (var l = lod.length; l--;) { + var ref$1 = lod[l]; + var from = ref$1[0]; + var to = ref$1[1]; + + batch.push(_$objectAssign_204({}, group, { + markerTexture: this$1.markerTextures[markerId], + activation: elements ? selectionBuffer : activation[markerId], + offset: from, + count: to - from, + + // send tree elements + elements: group.elements + })) } - function update (options) { - if (!options) { return } + return batch +} - if (options.length != null) { - if (typeof options[0] === 'number') { options = [{positions: options}] } +// update groups options +__Scatter_237.prototype.update = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { return } + + // passes are as single array + if (args.length === 1 && Array.isArray(args[0])) { args = args[0] } + + var ref = this; + var groups = ref.groups; + var gl = ref.gl; + var regl = ref.regl; + var maxSize = ref.maxSize; + var maxColors = ref.maxColors; + var palette = ref.palette; + + this.groups = groups = args.map(function (options, i) { + var group = groups[i] + + if (options === undefined) { return group } + + if (options === null) { options = { positions: null } } + else if (typeof options === 'function') { options = { ondraw: options } } + else if (typeof options[0] === 'number') { options = { positions: options } } + + // copy options to avoid mutation & handle aliases + options = _$pick_212(options, { + positions: 'positions data points', + snap: 'snap cluster lod tree', + size: 'sizes size radius', + borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline', + color: 'colors color fill fill-color fillColor', + borderColor: 'borderColors borderColor stroke stroke-color strokeColor', + marker: 'markers marker shape', + range: 'range dataBox databox', + viewport: 'viewport viewPort viewBox viewbox', + opacity: 'opacity alpha transparency', + bounds: 'bound bounds boundaries limits' + }) + + if (options.positions === null) { options.positions = [] } + + if (!group) { + groups[i] = group = { + id: i, + scale: null, + translate: null, + scaleFract: null, + translateFract: null, + + // buffers for active markers + activation: [], + + // buffer for filtered markers + selectionBuffer: regl.buffer({ + usage: 'stream', + type: 'uint8' + }), + + // buffers with data: it is faster to switch them per-pass + // than provide one congregate buffer + sizeBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8' + }), + colorBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8' + }), + positionBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float' + }), + positionFractBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float' + }) + } + options = _$objectAssign_204({}, __Scatter_237.defaults, options) } - // make options a batch - else if (!Array.isArray(options)) { options = [options] } + // force update triggers + if (options.positions && !('marker' in options)) { + options.marker = group.marker + delete group.marker + } + + // updating markers cause recalculating snapping + if (options.marker && !('positions' in options)) { + options.positions = group.positions + delete group.positions + } // global count of points - var pointCount = 0 + var hasSize = 0, hasColor = 0 + + _$updateDiff_272(group, options, [{ + snap: true, + size: function (s, group) { + if (s == null) { s = __Scatter_237.defaults.size } + hasSize += s && s.length ? 1 : 0 + return s + }, + borderSize: function (s, group) { + if (s == null) { s = __Scatter_237.defaults.borderSize } + hasSize += s && s.length ? 1 : 0 + return s + }, + opacity: parseFloat, + + // add colors to palette, save references + color: function (c, group) { + if (c == null) { c = __Scatter_237.defaults.color } + c = this$1.updateColor(c) + hasColor++ + return c + }, + borderColor: function (c, group) { + if (c == null) { c = __Scatter_237.defaults.borderColor } + c = this$1.updateColor(c) + hasColor++ + return c + }, - // process per-line settings - line2d.lines = lines = options.map(function (options, i) { - var state = lines[i] + bounds: function (bounds, group, options) { + if (!('range' in options)) { options.range = null } + return bounds + }, - if (options === undefined) { return state } + positions: function (positions, group, options) { + var snap = options.snap; + var positionBuffer = group.positionBuffer; + var positionFractBuffer = group.positionFractBuffer; + var selectionBuffer = group.selectionBuffer; + + // separate buffers for x/y coordinates + if (positions.x || positions.y) { + if (positions.x.length) { + group.xAttr = { + buffer: regl.buffer(positions.x), + offset: 0, + stride: 4, + count: positions.x.length + } + } + else { + group.xAttr = { + buffer: positions.x.buffer, + offset: positions.x.offset * 4 || 0, + stride: (positions.x.stride || 1) * 4, + count: positions.x.count + } + } + if (positions.y.length) { + group.yAttr = { + buffer: regl.buffer(positions.y), + offset: 0, + stride: 4, + count: positions.y.length + } + } + else { + group.yAttr = { + buffer: positions.y.buffer, + offset: positions.y.offset * 4 || 0, + stride: (positions.y.stride || 1) * 4, + count: positions.y.count + } + } + group.count = Math.max(group.xAttr.count, group.yAttr.count) - // null-argument resets positions - if (options === null) { options = { positions: null } } - else if (typeof options === 'function') { options = {after: options} } - else if (typeof options[0] === 'number') { options = {positions: options} } + return positions + } - // reduce by aliases - options = _$pick_153(options, { - positions: 'positions points data coords', - thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth', - join: 'lineJoin linejoin join type mode', - miterLimit: 'miterlimit miterLimit', - dashes: 'dash dashes dasharray dash-array dashArray', - color: 'color stroke colors stroke-color strokeColor', - fill: 'fill fill-color fillColor', - opacity: 'alpha opacity', - overlay: 'overlay crease overlap intersect', - close: 'closed close closed-path closePath', - range: 'range dataBox', - viewport: 'viewport viewBox', - hole: 'holes hole hollow', - after: 'after callback done pass' - }) + positions = _$flattenVertexData_136(positions, 'float64') - // reset positions - if (options.positions === null) { options.positions = [] } + var count = group.count = Math.floor(positions.length / 2) + var bounds = group.bounds = count ? _$normalize_13(positions, 2) : null - if (!state) { - lines[i] = state = { - id: i, - scale: null, - scaleFract: null, - translate: null, - translateFract: null, - count: 0, - offset: 0, - dashLength: 0, - hole: true + // if range is not provided updated - recalc it + if (!options.range && !group.range) { + delete group.range + options.range = bounds } - options = _$objectAssign_146({}, defaults, options) - } + // reset marker + if (!options.marker && !group.marker) { + delete group.marker; + options.marker = null; + } - // calculate state values - _$updateDiff_210(state, options, [{ - thickness: parseFloat, - opacity: parseFloat, - miterLimit: parseFloat, - overlay: Boolean, - join: function (j) { return j; }, - after: function (fn) { return fn; }, - hole: function (h) { return h || []; }, - - positions: function (positions, state, options) { - positions = _$flattenVertexData_79(positions, 'float64') - - var count = Math.floor(positions.length / 2) - var bounds = _$normalize_12(positions, 2) + // build cluster tree if required + if (snap && (snap === true || count > snap)) { + group.tree = _$pointCluster_216(positions, { bounds: bounds }) + } + // existing tree instance + else if (snap && snap.length) { + group.tree = snap + } - // FIXME: make it dynamic - if (!state.range && !options.range) { - options.range = bounds + if (group.tree) { + var opts = { + primitive: 'points', + usage: 'static', + data: group.tree, + type: 'uint32' } + if (group.elements) { group.elements(opts) } + else { group.elements = regl.elements(opts) } + } - state.count = count - state.bounds = bounds + // update position buffers + positionBuffer({ + data: __float32_237(positions), + usage: 'dynamic' + }) + positionFractBuffer({ + data: __fract32_237(positions), + usage: 'dynamic' + }) - pointCount += count + // expand selectionBuffer + selectionBuffer({ + data: new Uint8Array(count), + type: 'uint8', + usage: 'stream' + }) - return positions - }, + return positions + } + }, { + // create marker ids corresponding to known marker textures + marker: function (markers, group, options) { + var activation = group.activation; + + // reset marker elements + activation.forEach(function (buffer) { return buffer && buffer.destroy && buffer.destroy(); }) + activation.length = 0 + + // single sdf marker + if (!markers || typeof markers[0] === 'number') { + var id = this$1.addMarker(markers) + activation[id] = true + } - fill: function (c) { - return !c ? null : _$normalize_58(c, 'uint8') - }, + // per-point markers use mask buffers to enable markers in vert shader + else { + var markerMasks = [] + + for (var i = 0, l = Math.min(markers.length, group.count); i < l; i++) { + var id$1 = this$1.addMarker(markers[i]) - dashes: function (dashes, state, options) { - var dashLength = state.dashLength, - dashData + if (!markerMasks[id$1]) { markerMasks[id$1] = new Uint8Array(group.count) } - if (!dashes || dashes.length < 2) { - dashLength = 1. - dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]) + // enable marker by default + markerMasks[id$1][i] = 1 } - else { - dashLength = 0.; - for(var i = 0; i < dashes.length; ++i) { - dashLength += dashes[i] + for (var id$2 = 0; id$2 < markerMasks.length; id$2++) { + if (!markerMasks[id$2]) { continue } + + var opts = { + data: markerMasks[id$2], + type: 'uint8', + usage: 'static' } - dashData = new Uint8Array(dashLength * dashMult) - var ptr = 0 - var fillColor = 255 - - // repeat texture two times to provide smooth 0-step - for (var k = 0; k < 2; k++) { - for(var i$1 = 0; i$1 < dashes.length; ++i$1) { - for(var j = 0, l = dashes[i$1] * dashMult * .5; j < l; ++j) { - dashData[ptr++] = fillColor - } - fillColor ^= 255 - } + if (!activation[id$2]) { + activation[id$2] = regl.buffer(opts) } + else { + activation[id$2](opts) + } + + activation[id$2].data = markerMasks[id$2] } + } - dashTexture.subimage({ - // channels: 1, - data: dashData, - width: dashData.length, - height: 1 - }, 0, state.id) + return markers + }, - state.dashLength = dashLength + range: function (range, group, options) { + var bounds = group.bounds - return dashData - } + // FIXME: why do we need this? + if (!bounds) { return } + if (!range) { range = bounds } + + group.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] + group.translate = [-range[0], -range[1]] + + group.scaleFract = __fract32_237(group.scale) + group.translateFract = __fract32_237(group.translate) + + return range }, - // dependent properties & complement actions - { - close: function (close, state, options) { - if (close != null) { return close } - if (state.positions.length >= 4 && - state.positions[0] === state.positions[state.positions.length - 2] && - state.positions[1] === state.positions[state.positions.length - 1]) { - return true + viewport: function (vp) { + var rect = _$parseRect_206(vp || [ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]) + + // normalize viewport to the canvas coordinates + // rect.y = gl.drawingBufferHeight - rect.height - rect.y + + return rect + } + }]) + + // update size buffer, if needed + if (hasSize) { + var count = group.count; + var size = group.size; + var borderSize = group.borderSize; + var sizeBuffer = group.sizeBuffer; + + var sizes = new Uint8Array(count*2) + if (size.length || borderSize.length) { + for (var i$1 = 0; i$1 < count; i$1++) { + // we downscale size to allow for fractions + sizes[i$1*2] = Math.round((size[i$1] == null ? size : size[i$1]) * 255 / maxSize) + sizes[i$1*2 + 1] = Math.round((borderSize[i$1] == null ? borderSize : borderSize[i$1]) * 255 / maxSize) + } + } + sizeBuffer({ + data: sizes, + usage: 'dynamic' + }) + } + + // update color buffer if needed + if (hasColor) { + var count$1 = group.count; + var color = group.color; + var borderColor = group.borderColor; + var colorBuffer = group.colorBuffer; + var colors + + // if too many colors - put colors to buffer directly + if (this$1.tooManyColors) { + if (color.length || borderColor.length) { + colors = new Uint8Array(count$1 * 8) + for (var i$2 = 0; i$2 < count$1; i$2++) { + var colorId = color[i$2] + colors[i$2*8] = palette[colorId*4] + colors[i$2*8 + 1] = palette[colorId*4 + 1] + colors[i$2*8 + 2] = palette[colorId*4 + 2] + colors[i$2*8 + 3] = palette[colorId*4 + 3] + + var borderColorId = borderColor[i$2] + colors[i$2*8 + 4] = palette[borderColorId*4] + colors[i$2*8 + 5] = palette[borderColorId*4 + 1] + colors[i$2*8 + 6] = palette[borderColorId*4 + 2] + colors[i$2*8 + 7] = palette[borderColorId*4 + 3] } - return false - }, + } + } - positions: function (p, state, options) { - if (state.fill && p.length) { - var pos = [] - - // filter bad vertices and remap triangles to ensure shape - var ids = {} - var lastId = 0 - - for (var i = 0, ptr = 0, l = state.count; i < l; i++) { - var x = state.positions[i*2] - var y = state.positions[i*2 + 1] - if (Number.isNaN(x) || Number.isNaN(y)) { - x = state.positions[lastId*2] - y = state.positions[lastId*2 + 1] - ids[i] = lastId - } - else { - lastId = i - } - pos[ptr++] = x - pos[ptr++] = y + // if limited amount of colors - keep palette color picking + // that saves significant memory + else { + if (color.length || borderColor.length) { + // we need slight data increase by 2 due to vec4 borderId in shader + colors = new Uint8Array(count$1 * 4 + 2) + for (var i$3 = 0; i$3 < count$1; i$3++) { + // put color coords in palette texture + if (color[i$3] != null) { + colors[i$3*4] = color[i$3] % maxColors + colors[i$3*4 + 1] = Math.floor(color[i$3] / maxColors) } + if (borderColor[i$3] != null) { + colors[i$3*4 + 2] = borderColor[i$3] % maxColors + colors[i$3*4 + 3] = Math.floor(borderColor[i$3] / maxColors) + } + } + } + } - var triangles = _$earcut_74(pos, state.hole) + colorBuffer({ + data: colors, + type: 'uint8', + usage: 'dynamic' + }) + } - for (var i$1 = 0, l$1 = triangles.length; i$1 < l$1; i$1++) { - if (ids[triangles[i$1]] != null) { triangles[i$1] = ids[triangles[i$1]] } - } + return group + }) +} - state.triangles = triangles - } - return state.positions - }, - color: function (colors, state, options) { - var count = state.count +// get (and create) marker texture id +__Scatter_237.prototype.addMarker = function (sdf) { + var ref = this; + var markerTextures = ref.markerTextures; + var regl = ref.regl; + var markerCache = ref.markerCache; - if (!colors) { colors = 'transparent' } + var pos = sdf == null ? 0 : markerCache.indexOf(sdf) - // 'black' or [0,0,0,0] case - if (!Array.isArray(colors) || typeof colors[0] === 'number') { - var color = colors; - colors = Array(count); - for (var i = 0; i < count; i++) { - colors[i] = color - } - } + if (pos >= 0) { return pos } - if (colors.length < count) { throw Error('Not enough colors') } + // convert sdf to 0..255 range + var distArr + if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { + distArr = sdf + } + else { + distArr = new Uint8Array(sdf.length) + for (var i = 0, l = sdf.length; i < l; i++) { + distArr[i] = sdf[i] * 255 + } + } - var colorData = new Uint8Array(count * 4 + 4) + var radius = Math.floor(Math.sqrt(distArr.length)) - // convert colors to float arrays - for (var i$1 = 0; i$1 < count; i$1++) { - var c = _$normalize_58(colors[i$1], 'uint8') - colorData.set(c, i$1 * 4) - } + pos = markerTextures.length - return colorData - }, + markerCache.push(sdf) + markerTextures.push(regl.texture({ + channels: 1, + data: distArr, + radius: radius, + mag: 'linear', + min: 'linear' + })) - range: function (range, state, options) { - if (!state.count) { return null } + return pos +} - var bounds = state.bounds - if (!range) { range = bounds } +// register color to palette, return it's index or list of indexes +__Scatter_237.prototype.updateColor = function (colors) { + var ref = this; + var paletteIds = ref.paletteIds; + var palette = ref.palette; + var maxColors = ref.maxColors; - var boundsW = bounds[2] - bounds[0], - boundsH = bounds[3] - bounds[1] + if (!Array.isArray(colors)) { + colors = [colors] + } - var rangeW = range[2] - range[0], - rangeH = range[3] - range[1] + var idx = [] - state.scale = [ - boundsW / rangeW, - boundsH / rangeH - ] - state.translate = [ - -range[0] / rangeW + bounds[0] / rangeW || 0, - -range[1] / rangeH + bounds[1] / rangeH || 0 - ] + // if color groups - flatten them + if (typeof colors[0] === 'number') { + var grouped = [] - state.scaleFract = __fract32_172(state.scale) - state.translateFract = __fract32_172(state.translate) + if (Array.isArray(colors)) { + for (var i = 0; i < colors.length; i+=4) { + grouped.push(colors.slice(i, i+4)) + } + } + else { + for (var i$1 = 0; i$1 < colors.length; i$1+=4) { + grouped.push(colors.subarray(i$1, i$1+4)) + } + } - return range - }, + colors = grouped + } - viewport: function (vp) { - var viewport + for (var i$2 = 0; i$2 < colors.length; i$2++) { + var color = colors[i$2] + + color = _$normalize_59(color, 'uint8') + + var id = _$colorId_57(color, false) + + // if new color - save it + if (paletteIds[id] == null) { + var pos = palette.length + paletteIds[id] = Math.floor(pos / 4) + palette[pos] = color[0] + palette[pos+1] = color[1] + palette[pos+2] = color[2] + palette[pos+3] = color[3] + } + + idx[i$2] = paletteIds[id] + } + + // detect if too many colors in palette + if (!this.tooManyColors && palette.length > maxColors * maxColors * 4) { this.tooManyColors = true } + + // limit max color + this.updatePalette(palette) + + // keep static index for single-color property + return idx.length === 1 ? idx[0] : idx +} + +__Scatter_237.prototype.updatePalette = function (palette) { + if (this.tooManyColors) { return } + + var ref = this; + var maxColors = ref.maxColors; + var paletteTexture = ref.paletteTexture; + + var requiredHeight = Math.ceil(palette.length * .25 / maxColors) + + // pad data + if (requiredHeight > 1) { + palette = palette.slice() + for (var i = (palette.length * .25) % maxColors; i < requiredHeight * maxColors; i++) { + palette.push(0, 0, 0, 0) + } + } + + // ensure height + if (paletteTexture.height < requiredHeight) { + paletteTexture.resize(maxColors, requiredHeight) + } + + // update full data + paletteTexture.subimage({ + width: Math.min(palette.length * .25, maxColors), + height: requiredHeight, + data: palette + }, 0, 0) +} + +// remove unused stuff +__Scatter_237.prototype.destroy = function () { + this.groups.forEach(function (group) { + group.sizeBuffer.destroy() + group.positionBuffer.destroy() + group.positionFractBuffer.destroy() + group.colorBuffer.destroy() + group.activation.forEach(function (b) { return b && b.destroy && b.destroy(); }) + group.selectionBuffer.destroy() + + if (group.elements) { group.elements.destroy() } + }) + this.groups.length = 0 + + this.paletteTexture.destroy() + + this.markerTextures.forEach(function (txt) { return txt && txt.destroy && txt.destroy(); }) + + return this +} +'use strict' + +/* removed: var _$Scatter_237 = require('./scatter') */; +/* removed: var _$objectAssign_204 = require('object-assign') */; + +var _$reglScatter2d_236 = function (regl, options) { + var scatter = new _$Scatter_237(regl, options) + + var render = scatter.render.bind(scatter) + + // expose API + _$objectAssign_204(render, { + render: render, + update: scatter.update.bind(scatter), + draw: scatter.draw.bind(scatter), + destroy: scatter.destroy.bind(scatter), + regl: scatter.regl, + gl: scatter.gl, + canvas: scatter.gl.canvas, + groups: scatter.groups, + markers: scatter.markerCache, + palette: scatter.palette + }) + + return render +} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var SYMBOL_SIZE = 20; + +var _$constants_603 = { + TOO_MANY_POINTS: 1e5, + + SYMBOL_SDF_SIZE: 200, + SYMBOL_SIZE: SYMBOL_SIZE, + SYMBOL_STROKE: SYMBOL_SIZE / 20, + + DOT_RE: /-dot/, + OPEN_RE: /-open/, + + DASHES: { + solid: [1], + dot: [1, 1], + dash: [4, 1], + longdash: [8, 1], + dashdot: [4, 1, 1, 1], + longdashdot: [8, 1, 1, 1] + } +}; + +var _$attributes_602 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$attributes_467 = require('../../plots/attributes'); */; +/* removed: var _$attributes_576 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_309 = require('../../components/colorscale/color_attributes'); */; + +var __extendFlat_602 = _$extend_416.extendFlat; +var __overrideAll_602 = _$edit_types_455.overrideAll; +var DASHES = _$constants_603.DASHES; + +var __scatterLineAttrs_602 = _$attributes_576.line; +var __scatterMarkerAttrs_602 = _$attributes_576.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_602.line; + +var __attrs_602 = _$attributes_602 = __overrideAll_602({ + x: _$attributes_576.x, + x0: _$attributes_576.x0, + dx: _$attributes_576.dx, + y: _$attributes_576.y, + y0: _$attributes_576.y0, + dy: _$attributes_576.dy, + + text: __extendFlat_602({}, _$attributes_576.text, { + + }), + mode: { + valType: 'flaglist', + flags: ['lines', 'markers'], + extras: ['none'], + + + }, + line: { + color: __scatterLineAttrs_602.color, + width: __scatterLineAttrs_602.width, + dash: { + valType: 'enumerated', + values: Object.keys(DASHES), + dflt: 'solid', + + + } + }, + marker: __extendFlat_602({}, _$makeColorScaleAttributes_309('marker'), { + symbol: __scatterMarkerAttrs_602.symbol, + size: __scatterMarkerAttrs_602.size, + sizeref: __scatterMarkerAttrs_602.sizeref, + sizemin: __scatterMarkerAttrs_602.sizemin, + sizemode: __scatterMarkerAttrs_602.sizemode, + opacity: __scatterMarkerAttrs_602.opacity, + showscale: __scatterMarkerAttrs_602.showscale, + colorbar: __scatterMarkerAttrs_602.colorbar, + line: __extendFlat_602({}, _$makeColorScaleAttributes_309('marker.line'), { + width: scatterMarkerLineAttrs.width + }) + }), + connectgaps: _$attributes_576.connectgaps, + fill: _$attributes_576.fill, + fillcolor: _$attributes_576.fillcolor, + + hoveron: _$attributes_576.hoveron, + + selected: { + marker: _$attributes_576.selected.marker + }, + unselected: { + marker: _$attributes_576.unselected.marker + }, + + opacity: _$attributes_467.opacity + +}, 'calc', 'nested'); + +__attrs_602.x.editType = __attrs_602.y.editType = __attrs_602.x0.editType = __attrs_602.y0.editType = 'calc+clearAxisTypes'; + +'use strict' - if (Array.isArray(vp)) { - viewport = { - x: vp[0], - y: vp[1], - width: vp[2] - vp[0], - height: vp[3] - vp[1] - } - } - else if (vp) { - viewport = { - x: vp.x || vp.left || 0, - y: vp.y || vp.top || 0 - } +/* removed: var _$clamp_54 = require('clamp') */; - if (vp.right) { viewport.width = vp.right - viewport.x } - else { viewport.width = vp.w || vp.width || 0 } +var _$calcSDF_37 = calcSDF - if (vp.bottom) { viewport.height = vp.bottom - viewport.y } - else { viewport.height = vp.h || vp.height || 0 } - } - else { - viewport = { - x: 0, y: 0, - width: gl.drawingBufferWidth, - height: gl.drawingBufferHeight - } - } +var INF = 1e20; - return viewport - } - }]) +function calcSDF(src, options) { + if (!options) options = {} - return state - }) + var cutoff = options.cutoff == null ? 0.25 : options.cutoff + var radius = options.radius == null ? 8 : options.radius + var channel = options.channel || 0 + var w, h, size, data, intData, stride, ctx, canvas, imgData, i, l - // put collected data into buffers - // FIXME: possible optimization is updating only segment subdata - if (pointCount) { - var len = pointCount * 2 + lines.length * 6; - var positionData = new Float64Array(len) - var offset = 0 - var colorData = new Uint8Array(len * 2) + // handle image container + if (ArrayBuffer.isView(src) || Array.isArray(src)) { + if (!options.width || !options.height) throw Error('For raw data width and height should be provided by options') + w = options.width, h = options.height + data = src - lines.forEach(function (state, i) { - if (!state) { return } + if (!options.stride) stride = Math.floor(src.length / w / h) + else stride = options.stride + } + else { + if (window.HTMLCanvasElement && src instanceof window.HTMLCanvasElement) { + canvas = src + ctx = canvas.getContext('2d') + w = canvas.width, h = canvas.height + imgData = ctx.getImageData(0, 0, w, h) + data = imgData.data + stride = 4 + } + else if (window.CanvasRenderingContext2D && src instanceof window.CanvasRenderingContext2D) { + canvas = src.canvas + ctx = src + w = canvas.width, h = canvas.height + imgData = ctx.getImageData(0, 0, w, h) + data = imgData.data + stride = 4 + } + else if (window.ImageData && src instanceof window.ImageData) { + imgData = src + w = src.width, h = src.height + data = imgData.data + stride = 4 + } + } - var positions = state.positions; - var count = state.count; - var color = state.color; - state.offset = offset + size = Math.max(w, h) - if (!count) { return } + //convert int data to floats + if ((window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray) || (window.Uint8Array && data instanceof window.Uint8Array)) { + intData = data + data = Array(w*h) - // provide normalized positions - var npos = new Float64Array(positions.length) - npos.set(positions) - _$normalize_13(npos, 2, state.bounds) - - // rotate first segment join - if (state.close) { - if (positions[0] === positions[count*2 - 2] && - positions[1] === positions[count*2 - 1]) { - positionData[offset*2 + 0] = npos[count*2 - 4] - positionData[offset*2 + 1] = npos[count*2 - 3] - } - else { - positionData[offset*2 + 0] = npos[count*2 - 2] - positionData[offset*2 + 1] = npos[count*2 - 1] - } - } - else { - positionData[offset*2 + 0] = npos[0] - positionData[offset*2 + 1] = npos[1] - } - colorData[offset*4 + 0] = color[0] - colorData[offset*4 + 1] = color[1] - colorData[offset*4 + 2] = color[2] - colorData[offset*4 + 3] = color[3] - - positionData.set(npos, offset * 2 + 2) - colorData.set(color, offset * 4 + 4) - - // add last segment - if (state.close) { - // ignore coinciding start/end - if (positions[0] === positions[count*2 - 2] && - positions[1] === positions[count*2 - 1]) { - positionData[offset*2 + count*2 + 2] = npos[2] - positionData[offset*2 + count*2 + 3] = npos[3] - offset += count + 2 - state.count -= 1 - } - else { - positionData[offset*2 + count*2 + 2] = npos[0] - positionData[offset*2 + count*2 + 3] = npos[1] - positionData[offset*2 + count*2 + 4] = npos[2] - positionData[offset*2 + count*2 + 5] = npos[3] - offset += count + 3 - } - } - // add stub - else { - positionData[offset*2 + count*2 + 2] = npos[count*2 - 2] - positionData[offset*2 + count*2 + 3] = npos[count*2 - 1] - positionData[offset*2 + count*2 + 4] = npos[count*2 - 2] - positionData[offset*2 + count*2 + 5] = npos[count*2 - 1] - offset += count + 3 - } - }) + for (i = 0, l = intData.length; i < l; i++) { + data[i] = intData[i*stride + channel] / 255 + } + } + else { + if (stride !== 1) throw Error('Raw data can have only 1 value per pixel') + } - colorBuffer(colorData) - positionBuffer(__float32_172(positionData)) - positionFractBuffer(__fract32_172(positionData)) - } + // temporary arrays for the distance transform + var gridOuter = Array(w * h) + var gridInner = Array(w * h) + var f = Array(size) + var d = Array(size) + var z = Array(size + 1) + var v = Array(size) - return line2d - } + for (i = 0, l = w * h; i < l; i++) { + var a = data[i] + gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2) + gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2) + } - function destroy () { - lines.length = 0 - colorBuffer.destroy() - offsetBuffer.destroy() - positionBuffer.destroy() - dashTexture.destroy() - } + edt(gridOuter, w, h, f, d, v, z) + edt(gridInner, w, h, f, d, v, z) - return line2d -} + var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h) + for (i = 0, l = w*h; i < l; i++) { + dist[i] = _$clamp_54(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1) + } -// return fractional part of float32 array -function __fract32_172 (arr) { - var fract = new Float32Array(arr.length) - fract.set(arr) - for (var i = 0, l = fract.length; i < l; i++) { - fract[i] = arr[i] - fract[i] - } - return fract + return dist } -function __float32_172 (arr) { - if (arr instanceof Float32Array) { return arr } - var float = new Float32Array(arr) - float.set(arr) - return float +// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/ +function edt(data, width, height, f, d, v, z) { + for (var x = 0; x < width; x++) { + for (var y = 0; y < height; y++) { + f[y] = data[y * width + x] + } + edt1d(f, d, v, z, height) + for (y = 0; y < height; y++) { + data[y * width + x] = d[y] + } + } + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + f[x] = data[y * width + x] + } + edt1d(f, d, v, z, width) + for (x = 0; x < width; x++) { + data[y * width + x] = Math.sqrt(d[x]) + } + } } -var _$colorId_56 = {}; -/** @module color-id */ - -'use strict' - -/* removed: var _$clamp_53 = require('clamp') */; - -_$colorId_56 = toNumber -_$colorId_56.to = toNumber -_$colorId_56.from = fromNumber - -function toNumber (rgba, normalized) { - if(normalized == null) normalized = true - - var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3] - - if (a == null) a = normalized ? 1 : 255 - - if (normalized) { - r *= 255 - g *= 255 - b *= 255 - a *= 255 - } - r = _$clamp_53(r, 0, 255) & 0xFF - g = _$clamp_53(g, 0, 255) & 0xFF - b = _$clamp_53(b, 0, 255) & 0xFF - a = _$clamp_53(a, 0, 255) & 0xFF +// 1D squared distance transform +function edt1d(f, d, v, z, n) { + v[0] = 0; + z[0] = -INF + z[1] = +INF - //hi-order shift converts to -1, so we can't use <<24 - var n = (r * 0x01000000) + (g << 16) + (b << 8) + (a) + for (var q = 1, k = 0; q < n; q++) { + var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]) + while (s <= z[k]) { + k-- + s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]) + } + k++ + v[k] = q + z[k] = s + z[k + 1] = +INF + } - return n + for (q = 0, k = 0; q < n; q++) { + while (z[k + 1] < q) k++ + d[q] = (q - v[k]) * (q - v[k]) + f[v[k]] + } } + + +var _$absolutize_11 = absolutize + +/** + * redefine `path` with absolute coordinates + * + * @param {Array} path + * @return {Array} + */ + +function absolutize(path){ + var startX = 0 + var startY = 0 + var x = 0 + var y = 0 + + return path.map(function(seg){ + seg = seg.slice() + var type = seg[0] + var command = type.toUpperCase() + + // is relative + if (type != command) { + seg[0] = command + switch (type) { + case 'a': + seg[6] += x + seg[7] += y + break + case 'v': + seg[1] += y + break + case 'h': + seg[1] += x + break + default: + for (var i = 1; i < seg.length;) { + seg[i++] += x + seg[i++] += y + } + } + } + + // update cursor state + switch (command) { + case 'Z': + x = startX + y = startY + break + case 'H': + x = seg[1] + break + case 'V': + y = seg[1] + break + case 'M': + x = startX = seg[1] + y = startY = seg[2] + break + default: + x = seg[seg.length - 2] + y = seg[seg.length - 1] + } + + return seg + }) +} + + +var π = Math.PI +var _120 = radians(120) + +var _$normalize_203 = __normalize_203 + +/** + * describe `path` in terms of cubic bézier + * curves and move commands + * + * @param {Array} path + * @return {Array} + */ + +function __normalize_203(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 + + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + seg = arc(x, y,seg[1],seg[2],radians(seg[3]),seg[4],seg[5],seg[6],seg[7]) + // split multi part + seg.unshift('C') + if (seg.length > 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_203(x1, y1, -angle) + x1 = xy.x + y1 = xy.y + xy = __rotate_203(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_203(curve[i], curve[i+1], angle) + curve[i++] = rot.x + curve[i++] = rot.y + } + return curve +} + +function __rotate_203(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) +} + +/* removed: var _$absolutize_11 = require('abs-svg-path') */; +/* removed: var _$normalize_203 = require('normalize-svg-path') */; + +var methods = { + 'M': 'moveTo', + 'C': 'bezierCurveTo' +} + +var _$drawSvgPath_74 = function(context, segments) { + context.beginPath() + + // Make path easy to reproduce. + _$normalize_203(_$absolutize_11(segments)).forEach( + function(segment) { + var command = segment[0] + var args = segment.slice(1) + + // Convert the path command to a context method. + context[methods[command]].apply(context, args) + } + ) + + context.closePath() +} + +'use strict' -function fromNumber (n, normalized) { - n = +n +var _$isPath_193 = function isPath(str) { + if (typeof str !== 'string') return false - var r = n >>> 24 - var g = (n & 0x00ff0000) >>> 16 - var b = (n & 0x0000ff00) >>> 8 - var a = n & 0x000000ff + str = str.trim() - if (normalized === false) return [r, g, b, a] + // https://www.w3.org/TR/SVG/paths.html#PathDataBNF + if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str) && /[\dz]$/i.test(str) && str.length > 4) return true - return [r/255, g/255, b/255, a/255] + return false } + +var _$parse_207 = __parse_207 + +/** + * expected argument lengths + * @type {Object} + */ + +var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} + +/** + * segment pattern + * @type {RegExp} + */ + +var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig + +/** + * parse an svg path data string. Generates an Array + * of commands where each command is an Array of the + * form `[command, arg1, arg2, ...]` + * + * @param {String} path + * @return {Array} + */ + +function __parse_207(path) { + var data = [] + path.replace(segment, function(_, command, args){ + var type = command.toLowerCase() + args = parseValues(args) + + // overloaded moveTo + if (type == 'm' && args.length > 2) { + data.push([command].concat(args.splice(0, 2))) + type = 'l' + command = command == 'm' ? 'l' : 'L' + } + + while (true) { + if (args.length == length[type]) { + args.unshift(command) + return data.push(args) + } + if (args.length < length[type]) throw new Error('malformed path data') + data.push([command].concat(args.splice(0, length[type]))) + } + }) + return data +} + +var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig + +function parseValues(args) { + var numbers = args.match(number) + return numbers ? numbers.map(Number) : [] +} + +var _$inherits_browser_273 = {}; +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + _$inherits_browser_273 = 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 + _$inherits_browser_273 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +var _$isBuffer_274 = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +var _$util_275 = {}; +(function (process,global){ +// 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 formatRegExp = /%[sdj%]/g; +_$util_275.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. +_$util_275.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return _$util_275.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + 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; +_$util_275.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.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 = _$util_275.format.apply(_$util_275, 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 + _$util_275._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); +} +_$util_275.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 !== _$util_275.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); +} +_$util_275.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +_$util_275.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +_$util_275.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +_$util_275.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +_$util_275.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +_$util_275.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +_$util_275.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +_$util_275.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +_$util_275.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +_$util_275.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +_$util_275.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +_$util_275.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +_$util_275.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'; +} +_$util_275.isPrimitive = isPrimitive; + +_$util_275.isBuffer = _$isBuffer_274; + +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 +_$util_275.log = function() { + console.log('%s - %s', timestamp(), _$util_275.format.apply(_$util_275, 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. + */ +_$util_275.inherits = _$inherits_browser_273; + +_$util_275._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); +} + +}).call(this,_$browser_228,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +var _$assert_16 = {}; +(function (global){ 'use strict'; -var _$isIexplorer_133 = typeof navigator !== 'undefined' && - (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); -'use strict' - -/* removed: var _$pick_153 = require('pick-by-alias') */; - -var _$parseRect_148 = 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) - } - - // 0, 0, 100, 100 - array-like - if (arg.length && typeof arg[0] === 'number') { - if (arg.length === 2) { - rect = { - width: arg[0], - height: arg[1], - x: 0, - y: 0 - } - } - else { - rect = { - x: arg[0], - y: arg[1], - width: (arg[2] - arg[0]) || 0, - height: (arg[3] - arg[1]) || 0 - } - } - } - else if (arg) { - arg = _$pick_153(arg, { - left: 'x l left Left', - top: 'y t top Top', - width: 'w width', - height: 'h height', - bottom: 'b bottom', - right: 'r 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 -} +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: -"use strict" +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } -function __compileSearch_174(funcName, predicate, reversed, extraArgs, 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[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){") + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +/* removed: var _$util_275 = require('util/'); */; +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = _$assert_16 = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!_$util_275.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; } else { - code.push(";if(", predicate, "){i=m;") + this.message = getMessage(this); + this.generatedMessage = true; } - if(reversed) { - code.push("l=m+1}else{h=m-1}") + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); } else { - code.push("h=m-1}else{l=m+1}") + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } } - code.push("}") - if(earlyOut) { - code.push("return -1};") +}; + +// assert.AssertionError instanceof Error +_$util_275.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); } else { - code.push("return i};") + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !_$util_275.isFunction(something)) { + return _$util_275.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (_$util_275.isDate(actual) && _$util_275.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (_$util_275.isRegExp(actual) && _$util_275.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); } - return code.join("") } -function __compileBoundsSearch_174(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - __compileSearch_174("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_174("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; } -var _$searchBounds_174 = { - ge: __compileBoundsSearch_174(">=", false, "GE"), - gt: __compileBoundsSearch_174(">", false, "GT"), - lt: __compileBoundsSearch_174("<", true, "LT"), - le: __compileBoundsSearch_174("<=", true, "LE"), - eq: __compileBoundsSearch_174("-", true, "EQ", true) +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (_$util_275.isPrimitive(a) || _$util_275.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; } -'use strict' - -var _$sortLevels_191 = sortLevels - -var __INSERT_SORT_CUTOFF_191 = 32 - -function sortLevels(data_levels, data_points, data_ids, data_weights, n0) { - if (n0 <= 4*__INSERT_SORT_CUTOFF_191) { - __insertionSort_191(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_191(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } -} - -function __insertionSort_191(left, right, data_levels, data_points, data_ids, data_weights) { - for(var i=left+1; i<=right; ++i) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - var j = i - while(j > left) { - var b_level = data_levels[j-1] - var b_x = data_points[2*(j-1)] - if(((b_level - a_level) || (a_x - b_x)) >= 0) { - break - } - data_levels[j] = b_level - data_points[2*j] = b_x - data_points[2*j+1] = data_points[2*j-1] - data_ids[j] = data_ids[j-1] - data_weights[j] = data_weights[j-1] - j -= 1 - } - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight - } -} - -function __swap_191(i, j, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} - -function __move_191(i, j, data_levels, data_points, data_ids, data_weights) { - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] -} - -function __rotate_191(i, j, k, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = data_levels[k] - data_points[2*j] = data_points[2*k] - data_points[2*j+1] = data_points[2*k+1] - data_ids[j] = data_ids[k] - data_weights[j] = data_weights[k] - - data_levels[k] = a_level - data_points[2*k] = a_x - data_points[2*k+1] = a_y - data_ids[k] = a_id - data_weights[k] = a_weight -} - -function __shufflePivot_191( - i, j, - a_level, a_x, a_y, a_id, a_weight, - data_levels, data_points, data_ids, data_weights) { - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} - -function __compare_191(i, j, data_levels, data_points, data_ids) { - return ((data_levels[i] - data_levels[j]) || - (data_points[2*j] - data_points[2*i]) || - (data_ids[i] - data_ids[j])) < 0 -} - -function __comparePivot_191(i, level, x, y, id, data_levels, data_points, data_ids) { - return ((level - data_levels[i]) || - (data_points[2*i] - x) || - (id - data_ids[i])) < 0 -} - -function __quickSort_191(left, right, data_levels, data_points, data_ids, data_weights) { - 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_191(el1, el2, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el2 - el2 = tmp - } - if(__compare_191(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - if(__compare_191(el1, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el3 - el3 = tmp - } - if(__compare_191(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(__compare_191(el1, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el4 - el4 = tmp - } - if(__compare_191(el3, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el3 - el3 = el4 - el4 = tmp - } - if(__compare_191(el2, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el5 - el5 = tmp - } - if(__compare_191(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(__compare_191(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - - var pivot1_level = data_levels[el2] - var pivot1_x = data_points[2*el2] - var pivot1_y = data_points[2*el2+1] - var pivot1_id = data_ids[el2] - var pivot1_weight = data_weights[el2] - - var pivot2_level = data_levels[el4] - var pivot2_x = data_points[2*el4] - var pivot2_y = data_points[2*el4+1] - var pivot2_id = data_ids[el4] - var pivot2_weight = data_weights[el4] - - var ptr0 = el1 - var ptr2 = el3 - var ptr4 = el5 - var ptr5 = index1 - var ptr6 = index3 - var ptr7 = index5 - - var level_x = data_levels[ptr0] - var level_y = data_levels[ptr2] - var level_z = data_levels[ptr4] - data_levels[ptr5] = level_x - data_levels[ptr6] = level_y - data_levels[ptr7] = level_z - - for (var i1 = 0; i1 < 2; ++i1) { - var x = data_points[2*ptr0+i1] - var y = data_points[2*ptr2+i1] - var z = data_points[2*ptr4+i1] - data_points[2*ptr5+i1] = x - data_points[2*ptr6+i1] = y - data_points[2*ptr7+i1] = z - } - - var id_x = data_ids[ptr0] - var id_y = data_ids[ptr2] - var id_z = data_ids[ptr4] - data_ids[ptr5] = id_x - data_ids[ptr6] = id_y - data_ids[ptr7] = id_z - - var weight_x = data_weights[ptr0] - var weight_y = data_weights[ptr2] - var weight_z = data_weights[ptr4] - data_weights[ptr5] = weight_x - data_weights[ptr6] = weight_y - data_weights[ptr7] = weight_z - - __move_191(index2, left, data_levels, data_points, data_ids, data_weights) - __move_191(index4, right, data_levels, data_points, data_ids, data_weights) - for (var k = less; k <= great; ++k) { - if (__comparePivot_191(k, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - if (k !== less) { - __swap_191(k, less, data_levels, data_points, data_ids, data_weights) - } - ++less; - } else { - if (!__comparePivot_191(k, - pivot2_level, pivot2_x, pivot2_y, pivot2_id, - data_levels, data_points, data_ids)) { - while (true) { - if (!__comparePivot_191(great, - pivot2_level, pivot2_x, pivot2_y, pivot2_id, - data_levels, data_points, data_ids)) { - if (--great < k) { - break; - } - continue; - } else { - if (__comparePivot_191(great, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - __rotate_191(k, less, great, data_levels, data_points, data_ids, data_weights) - ++less; - --great; - } else { - __swap_191(k, great, data_levels, data_points, data_ids, data_weights) - --great; - } - break; - } - } - } - } - } - __shufflePivot_191(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) - __shufflePivot_191(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) - if (less - 2 - left <= __INSERT_SORT_CUTOFF_191) { - __insertionSort_191(left, less - 2, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_191(left, less - 2, data_levels, data_points, data_ids, data_weights) - } - if (right - (great + 2) <= __INSERT_SORT_CUTOFF_191) { - __insertionSort_191(great + 2, right, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_191(great + 2, right, data_levels, data_points, data_ids, data_weights) - } - if (great - less <= __INSERT_SORT_CUTOFF_191) { - __insertionSort_191(less, great, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_191(less, great, data_levels, data_points, data_ids, data_weights) - } -} +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); -'use strict' - -/* removed: var _$sortLevels_191 = require('./lib/sort') */; -/* removed: var _$normalize_12 = require('array-bounds') */; - -var _$snapPoints_192 = snapPoints - -function partition(points, ids, start, end, lox, loy, hix, hiy) { - var mid = start - for(var i=start; i>> 1 - if(n < 1) { - return [] - } - - if (!ids) ids = Array(n) - if (!weights) weights = Array(n) - if (!bounds) bounds = [] - - for(var i=0; i= bounds[2] || bounds[1] >= bounds[3]) { - var b = _$normalize_12(points, 2) - - if(b[0] === b[2]) { - b[2] += 1 - } - if(b[1] === b[3]) { - b[3] += 1 - } - - bounds[0] = b[0] - bounds[1] = b[1] - bounds[2] = b[2] - bounds[3] = b[3] - } - - var lox = bounds[0] - var loy = bounds[1] - var hix = bounds[2] - var hiy = bounds[3] - - //Calculate diameter - var scaleX = 1.0 / (hix - lox) - var scaleY = 1.0 / (hiy - loy) - var diam = Math.max(hix - lox, hiy - loy) - - - - var levels = new Int32Array(n) - var ptr = 0 - - function snapRec(x, y, diam, start, end, level) { - var diam_2 = diam * 0.5 - var offset = start + 1 - var count = end - start - weights[ptr] = count - levels[ptr++] = level - for(var i=0; i<2; ++i) { - for(var j=0; j<2; ++j) { - var nx = x+i*diam_2 - var ny = y+j*diam_2 - var nextOffset = partition( - points - , ids - , offset - , end - , nx, ny - , nx+diam_2, ny+diam_2) - if(nextOffset === offset) { - continue - } - if(nextOffset - offset >= Math.max(0.9 * count, 32)) { - var mid = (end + start)>>>1 - snapRec(nx, ny, diam_2, offset, mid, level+1) - offset = mid - } - snapRec(nx, ny, diam_2, offset, nextOffset, level+1) - offset = nextOffset - } - } - } - snapRec(lox, loy, diam, 0, n, 0) - _$sortLevels_191(levels, points, ids, weights, n) - - var lod = [] - var lastLevel = 0 - var prevOffset = n - for(var ptr=n-1; ptr>=0; --ptr) { - points[2*ptr] = (points[2*ptr] - lox) * scaleX - points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY - - var level = levels[ptr] - if(level === lastLevel) { - continue - } - - lod.push(new SnapInterval( - diam * Math.pow(0.5, level), - ptr+1, - prevOffset - (ptr+1) - )) - prevOffset = ptr+1 - - lastLevel = level - } - - lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) - - return lod -} +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; -'use strict' - -/* removed: var _$normalize_58 = require('color-normalize') */; -/* removed: var _$normalize_12 = require('array-bounds') */; -/* removed: var _$colorId_56 = require('color-id') */; -/* removed: var _$snapPoints_192 = require('snap-points-2d') */; -/* removed: var _$objectAssign_146 = require('object-assign') */; -/* removed: var _$browser_124 = require('glslify') */; -/* removed: var _$searchBounds_174 = require('binary-search-bounds') */; -/* removed: var _$pick_153 = require('pick-by-alias') */; -/* removed: var _$updateDiff_210 = require('update-diff') */; -/* removed: var _$flattenVertexData_79 = require('flatten-vertex-data') */; -/* removed: var _$isIexplorer_133 = require('is-iexplorer') */; -/* removed: var _$toFloat32_202 = require('to-float32'); */; -var __float32_173 = _$toFloat32_202.float32; -var __fract32_173 = _$toFloat32_202.fract32; -/* removed: var _$newArray_14 = require('array-range') */; -/* removed: var _$parseRect_148 = require('parse-rect') */; - -var _$Scatter_173 = __Scatter_173 - - -function __Scatter_173 (regl, options) { - if (typeof regl === 'function') { - if (!options) { options = {} } - options.regl = regl - } - else { - options = regl - regl = null - } - - if (options && options.length) { options.positions = options } - regl = options.regl - - // persistent variables - var gl = regl._gl, - drawMarker, drawCircle, - sizeBuffer, positionBuffer, positionFractBuffer, colorBuffer, - paletteTexture, palette = [], paletteIds = {}, - defaults = { - color: 'black', - borderColor: 'transparent', - borderSize: 1, - size: 12, - opacity: 1, - marker: undefined, - viewport: null, - range: null, - pixelSize: null, - offset: 0, - count: 0, - bounds: null, - positions: [], - snap: 1e4 - }, - - // state - groups = [], - - // textures for marker keys - markerTextures = [null], - markerCache = [null] - - var maxColors = 4096, maxSize = 100 - - // texture with color palette - paletteTexture = regl.texture({ - data: new Uint8Array(maxColors * 4), - width: maxColors, - height: 1, - type: 'uint8', - format: 'rgba', - wrapS: 'clamp', - wrapT: 'clamp', - mag: 'nearest', - min: 'nearest' - }) - - // buffers to reuse - sizeBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - colorBuffer = regl.buffer({ - usage: 'dynamic', - type: 'uint16', - data: null - }) - positionBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - positionFractBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - - // fast-create from existing regl-scatter instance - if (options.clone) { - groups = options.clone.groups.map(function (group) { - group = _$objectAssign_146({}, group) - if (group.markerIds) { - group.markerIds = group.markerIds.map(function (ids) { - // recreate regl elements here - var newIds = ids.slice() - newIds.lod = ids.lod - newIds.snap = ids.snap - newIds.data = ids.data - newIds.id = ids.id - newIds.x = ids.x - newIds.w = ids.w - newIds.elements = regl.elements({ - primitive: 'points', - type: 'uint32', - data: ids.data - }) - return newIds - }) - } - return group - }) - - // create marker textures - options.clone.markers.forEach(function (markers) { - addMarker(markers) - }) - // clone palette texture - updatePalette(options.clone.palette) - updateBuffers({point: true, color: true, size: true}) - } - // full create from options - else { - update(options) - } - - - // common shader options - var shaderOptions = { - uniforms: { - pixelRatio: regl.context('pixelRatio'), - palette: paletteTexture, - paletteSize: function (ctx, prop) { return [maxColors, paletteTexture.height]; }, - scale: regl.prop('scale'), - scaleFract: regl.prop('scaleFract'), - translate: regl.prop('translate'), - translateFract: regl.prop('translateFract'), - opacity: regl.prop('opacity'), - marker: regl.prop('marker'), - }, - - attributes: { - position: positionBuffer, - positionFract: positionFractBuffer, - size: function (ctx, prop) { return prop.size.length ? { - buffer: sizeBuffer, - stride: 2, - offset: 0 - } : {constant: [Math.round(prop.size * 255 / maxSize)]}; }, - borderSize: function (ctx, prop) { return prop.borderSize.length ? { - buffer: sizeBuffer, - stride: 2, - offset: 1 - } : {constant: [Math.round(prop.borderSize * 255 / maxSize)]}; }, - colorId: function (ctx, prop) { return prop.color.length ? { - buffer: colorBuffer, - stride: 8, - offset: 0 - } : {constant: [prop.color]}; }, - borderColorId: function (ctx, prop) { return prop.borderColor.length ? { - buffer: colorBuffer, - stride: 8, - offset: 4 - } : {constant: [prop.borderColor]}; } - }, - - - blend: { - enable: true, - color: [0,0,0,1], - func: { - srcRGB: 'src alpha', - dstRGB: 'one minus src alpha', - srcAlpha: 'one minus dst alpha', - dstAlpha: 'one' - } - }, - - scissor: { - enable: true, - box: regl.prop('viewport') - }, - viewport: regl.prop('viewport'), - - stencil: {enable: false}, - depth: {enable: false}, - - - elements: regl.prop('elements'), - count: regl.prop('count'), - offset: regl.prop('offset'), - - primitive: 'points' - } - - // IE11 shader workaround - if (_$isIexplorer_133) { - drawCircle = regl(_$objectAssign_146({}, shaderOptions, { - frag: _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n\n float centerFraction = fragBorderSize == 0. ? 2. : fragSize / (fragSize + fragBorderSize + 1.25);\n\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, 1.);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"]), - vert: _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nvoid main() {\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n fragBorderSize = borderSize;\n fragSize = size;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragWidth = 1. / gl_PointSize;\n}\n"]), - uniforms: { - // FIXME: generate attribute color data - color: function (ctx, p) { - var id = p.color.length ? p.color[0] : p.color; - return palette.slice(id * 4, id * 4 + 4).map(function (v) { return v / 255; }) - }, - borderColor: function (ctx, p) { - var id = p.borderColor.length ? p.borderColor[0] : p.borderColor; - return palette.slice(id * 4, id * 4 + 4).map(function (v) { return v / 255; }) - }, - pixelRatio: regl.context('pixelRatio'), - palette: paletteTexture, - paletteSize: function (ctx, prop) { return [maxColors, paletteTexture.height]; }, - scale: regl.prop('scale'), - scaleFract: regl.prop('scaleFract'), - translate: regl.prop('translate'), - translateFract: regl.prop('translateFract'), - opacity: regl.prop('opacity'), - marker: regl.prop('marker') - }, - attributes: { - position: positionBuffer, - positionFract: positionFractBuffer, - size: shaderOptions.attributes.size, - borderSize: shaderOptions.attributes.borderSize - } - })) - } - else { - // draw sdf-marker - var markerOptions = _$objectAssign_146({}, shaderOptions) - markerOptions.frag = _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n //max-distance alpha\n if (dist < 0.003) discard;\n\n //null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]) - markerOptions.vert = _$browser_124(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n\t\tfragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]) - - drawMarker = regl(markerOptions) - - // draw circle - var circleOptions = _$objectAssign_146({}, shaderOptions) - circleOptions.frag = _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif(radius > 1.0 + delta) {\n\t\tdiscard;\n\t\treturn;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]) - circleOptions.vert = _$browser_124(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]) - - drawCircle = regl(circleOptions) - } - - // expose API - _$objectAssign_146(scatter2d, { - update: update, - draw: draw, - destroy: destroy, - regl: regl, - gl: gl, - canvas: gl.canvas, - groups: groups, - markers: markerCache, - palette: palette - }) - - - // main update/draw function - function scatter2d (opts) { - // update - if (opts) { - update(opts) - } - - // destroy - else if (opts === null) { - destroy() - } - - draw() - } - - // draw all groups or only indicated ones - function draw (opts) { - if (typeof opts === 'number') { return drawGroup(opts) } - - // highlight elements - if (Array.isArray(opts)) { - opts.forEach(function (els, i) { - if (els == null) { return } - if (els.length) { return drawGroup(els, i) } - return drawGroup(els) - }) - return - } - - // make options a batch - groups.forEach(function (group, i) { - if (!group) { return } - - drawGroup(i) - }) - } - - // draw specific scatter group - function drawGroup (group, id) { - if (typeof group === 'number') { group = groups[group] } - - var els - - if (Array.isArray(group)) { - els = group - group = groups[id] - } - - if (!(group && group.count && group.opacity)) { return } - - // if subset of elements to redraw passed - form a whitelist - var whitelist - if (els) { - whitelist = Array(group.count); - - for (var i = 0; i < els.length; i++) { - whitelist[els[i]] = true - } - } - - // draw circles - // FIXME remove regl._refresh hooks once regl issue #427 is fixed - if (group.markerIds[0]) { - regl._refresh() - - var opts = getMarkerDrawOptions(group.markerIds[0], group, whitelist) - - drawCircle(opts) - } - - // draw all other available markers - var batch = [] - for (var i$1 = 1; i$1 < group.markerIds.length; i$1++) { - var ids = group.markerIds[i$1] - - if (!ids || !ids.length) { continue } - - [].push.apply(batch, getMarkerDrawOptions(ids, group, whitelist)) - } - - if (batch.length) { - regl._refresh() - drawMarker(batch) - } - } - - // get options for the marker ids - function getMarkerDrawOptions(ids, group, whitelist) { - var range = group.range; - var offset = group.offset; - // unsnapped options - if (!ids.snap) { - var elements = whitelist ? filter(ids.data, whitelist) : ids.elements; - - return [_$objectAssign_146({}, group, { - elements: elements, - offset: 0, - count: whitelist ? elements.length : ids.length, - marker: markerTextures[ids.id] - })] - } - - // scales batch - var batch = [] - var lod = ids.lod; - var x = ids.x; - var id = ids.id; - - var pixelSize = Math.min((range[2] - range[0]) / group.viewport.width, (range[3] - range[1]) / group.viewport.height) - - for (var scaleNum = lod.length; scaleNum--;) { - var level = lod[scaleNum] - - // FIXME: use minSize-adaptive coeff here, if makes sense, mb we need dist tho - if (level.pixelSize && level.pixelSize < pixelSize && scaleNum > 1) { - continue - } - - var intervalStart = level.offset - var intervalEnd = level.count + intervalStart - - var startOffset = _$searchBounds_174.ge(x, range[0], intervalStart, intervalEnd - 1) - var endOffset = _$searchBounds_174.lt(x, range[2], startOffset, intervalEnd - 1) + 1 - - if (endOffset <= startOffset) { continue } - - // whitelisted level requires subelements from the range - if (whitelist) { - var elements$1 = filter(ids.data.subarray(startOffset, endOffset), whitelist) - - batch.push(_$objectAssign_146({}, group, { - elements: elements$1, - marker: markerTextures[id], - offset: 0, - count: elements$1.length - })) - } - else { - batch.push(_$objectAssign_146({}, group, { - elements: ids.elements, - marker: markerTextures[id], - offset: startOffset, - count: endOffset - startOffset - })) - } - } - - function filter(offsets, whitelist) { - var subEls = [] - for (var i = 0, l = offsets.length; i < l; i++) { - var el = offsets[i] - var id = el - offset - if (whitelist[id]) { - subEls.push(el) - } - } - return subEls - } - - return batch - } - - // update groups options - function update (options) { - if (!options) { return } - - // direct points argument - if (options.length != null) { - if (typeof options[0] === 'number') { options = [{positions: options}] } - } - // make options a batch - else if (!Array.isArray(options)) { options = [options] } - - // global count of points - var pointCount = 0, sizeCount = 0, colorCount = 0 - - scatter2d.groups = groups = options.map(function (options, i) { - var group = groups[i] - - if (options === undefined) { return group } - - if (options === null) { options = { positions: null } } - else if (typeof options === 'function') { options = {after: options} } - else if (typeof options[0] === 'number') { options = {positions: options} } - - // copy options to avoid mutation & handle aliases - options = _$pick_153(options, { - positions: 'positions data points', - snap: 'snap cluster', - size: 'sizes size radius', - borderSize: 'borderSizes borderSize stroke-width strokeWidth outline', - color: 'colors color fill fill-color fillColor', - borderColor: 'borderColors borderColor stroke stroke-color strokeColor', - palette: 'palette swatch', - marker: 'markers marker shape', - range: 'range dataBox', - viewport: 'viewport viewBox', - opacity: 'opacity alpha' - }) - - if (options.positions === null) { options.positions = [] } - - if (!group) { - groups[i] = group = { - id: i, - scale: null, - translate: null, - scaleFract: null, - translateFract: null, - - // list of ids corresponding to markers, with inner props - markerIds: [] - } - options = _$objectAssign_146({}, defaults, options) - } - - // force update triggers - if (options.positions && !('marker' in options)) { - options.marker = group.marker - delete group.marker - } - - // updating markers cause recalculating snapping - if (options.marker && !('positions' in options)) { - options.positions = group.positions - delete group.positions - } - - _$updateDiff_210(group, options, [{ - snap: true, - size: function (s) { - sizeCount += s.length ? 1 : 0 - return s - }, - borderSize: function (s) { - sizeCount += s.length ? 1 : 0 - return s - }, - opacity: parseFloat, - - // add colors to palette, save references - color: function (c) { - c = updateColor(c) - colorCount++ - return c - }, - borderColor: function (c) { - c = updateColor(c) - colorCount++ - return c - }, - - positions: function (positions, group, options) { - positions = _$flattenVertexData_79(positions, 'float64') - - var count = group.count = Math.floor(positions.length / 2) - var bounds = group.bounds = count ? _$normalize_12(positions, 2) : null - - // if range is not provided updated - recalc it - if (!options.range && !group.range) { - delete group.range - options.range = bounds - } - - group.offset = pointCount - pointCount += count - - // reset marker - if (!options.marker && !group.marker) { - delete group.marker; - options.marker = null; - } - - return positions - } - }, { - // create marker ids corresponding to known marker textures - marker: function (markers, group, options) { - // reset marker elements - group.markerIds.length = 0 - - // single sdf marker - if (!markers || typeof markers[0] === 'number') { - var id = addMarker(markers) - - var elements = _$newArray_14(group.count) - - group.markerIds[id] = elements - } - // per-point markers - else { - for (var i = 0, l = markers.length; i < l; i++) { - var id$1 = addMarker(markers[i]) - - if (!group.markerIds[id$1]) { group.markerIds[id$1] = [] } - group.markerIds[id$1].push(i) - } - } - - return markers - } - }, { - // recalculate per-marker snapping - // first, it is faster to snap 100 points 100 times than 10000 points once (practically, not theoretically) - // second, it is easier to subset render per-marker than per-generic set - positions: function (positions, group) { - var markerIds = group.markerIds; - var snap = group.snap; - var bounds = group.bounds; - var offset = group.offset; - - for (var i = 0; i < markerIds.length; i++) { - var ids = markerIds[i] - if (!ids || !ids.length) { continue } - - var l = ids.length, els = (void 0) - - ids.id = i; - - if (snap && (snap === true || l > snap)) { - ids.snap = true - var x = ids.x = Array(l) - var w = ids.w = Array(l) - var markerPoints = (void 0) - - // multimarker snapping is computationally more intense - if (markerIds.length > 1) { - markerPoints = Array(l * 2) - - for (var i$1 = 0; i$1 < l; i$1++) { - var id = ids[i$1] - markerPoints[i$1 * 2] = positions[id * 2] - markerPoints[i$1 * 2 + 1] = positions[id * 2 + 1] - } - } - else { - markerPoints = new Float64Array(positions.length) - markerPoints.set(positions) - } - - // shuffled_id: real_id - var i2id = new Uint32Array(l) - - ids.lod = _$snapPoints_192(markerPoints, i2id, w, bounds) - - els = new Uint32Array(l) - for (var i$2 = 0; i$2 < l; i$2++) { - var id$1 = i2id[i$2], iid = ids[id$1] - els[i$2] = iid + offset - x[i$2] = positions[iid * 2] - } - } - else { - els = new Uint32Array(l) - for (var i$3 = 0; i$3 < l; i$3++) { - els[i$3] = ids[i$3] + offset - } - } - - ids.data = els; - ids.elements = regl.elements({ - primitive: 'points', - type: 'uint32', - data: els - }) - } - }, - - range: function (range, group, options) { - var bounds = group.bounds - - if (!bounds) { return } - if (!range) { range = bounds } - - group.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] - group.translate = [-range[0], -range[1]] - - group.scaleFract = __fract32_173(group.scale) - group.translateFract = __fract32_173(group.translate) - - return range - }, - - viewport: function (vp) { - return _$parseRect_148(vp || [ - gl.drawingBufferWidth, - gl.drawingBufferHeight - ]) - } - }]) - - return group - }) - - updateBuffers({ - point: pointCount, - size: sizeCount, - color: colorCount - }) - } - - // update buffers data based on existing groups - function updateBuffers(ref) { - var point = ref.point; - var size = ref.size; - var color = ref.color; - - // put point/color data into buffers, if updated any of them - var len = groups.reduce(function (acc, group, i) { - return acc + (group ? group.count : 0) - }, 0) - - if (point) { - var positionData = new Float32Array(len * 2) - var positionFractData = new Float32Array(len * 2) - - groups.forEach(function (group, i) { - if (!group) { return } - var positions = group.positions; - var count = group.count; - var offset = group.offset; - if (!count) { return } - positionData.set(__float32_173(positions), offset * 2) - positionFractData.set(__fract32_173(positions), offset * 2) - }) - - positionBuffer(positionData) - positionFractBuffer(positionFractData) - } - - if (size) { - var sizeData = new Uint8Array(len * 2) - - groups.forEach(function (group, i) { - if (!group) { return } - var count = group.count; - var offset = group.offset; - var size = group.size; - var borderSize = group.borderSize; - if (!count) { return } - - if (size.length || borderSize.length) { - var sizes = new Uint8Array(count*2) - for (var i$1 = 0; i$1 < count; i$1++) { - // we downscale size to allow for fractions - sizes[i$1*2] = Math.round((size[i$1] == null ? size : size[i$1]) * 255 / maxSize) - sizes[i$1*2 + 1] = Math.round((borderSize[i$1] == null ? borderSize : borderSize[i$1]) * 255 / maxSize) - } - sizeData.set(sizes, offset * 2) - } - }) - sizeBuffer(sizeData) - } - - if (color) { - var colorData = new Uint16Array(len * 4) - - groups.forEach(function (group, i) { - if (!group) { return } - var count = group.count; - var offset = group.offset; - var color = group.color; - var borderColor = group.borderColor; - if (!count) { return } - - if (color.length || borderColor.length) { - var colorIds = new Uint16Array(count * 4) - for (var i$1 = 0; i$1 < count; i$1++) { - if (color[i$1] != null) { - colorIds[i$1*4] = color[i$1] % maxColors - colorIds[i$1*4 + 1] = Math.floor(color[i$1] / maxColors) - } - if (borderColor[i$1] != null) { - colorIds[i$1*4 + 2] = borderColor[i$1] % maxColors - colorIds[i$1*4 + 3] = Math.floor(borderColor[i$1] / maxColors) - } - } - - colorData.set(colorIds, offset * 4) - } - }) - - - colorBuffer(colorData) - } - } +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && _$util_275.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +var _$cjs_258 = {}; +"use strict"; + +Object.defineProperty(_$cjs_258, "__esModule", { + value: true +}); + +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) { + var a = 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 umag = Math.sqrt(ux * ux + uy * uy); + var vmag = Math.sqrt(ux * ux + uy * uy); + var dot = ux * vx + uy * vy; + + var div = dot / (umag * vmag); + + if (div > 1) { + div = 1; + } + + if (div < -1) { + div = -1; + } + + return sign * Math.acos(div); +}; + +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]; + + var segments = Math.max(Math.ceil(Math.abs(ang2) / (TAU / 4)), 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 }; + }); +}; + +_$cjs_258.default = arcToBezier; +_$cjs_258 = _$cjs_258["default"]; +'use strict' - // get (and create) marker texture id - function addMarker (sdf) { - var pos = sdf == null ? 0 : markerCache.indexOf(sdf) +var _$normalize_260 = __normalize_260 - if (pos >= 0) { return pos } +/* removed: var _$cjs_258 = require('svg-arc-to-cubic-bezier') */; - // convert sdf to 0..255 range - var distArr - if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { - distArr = sdf - } - else { - distArr = new Uint8Array(sdf.length) - for (var i = 0, l = sdf.length; i < l; i++) { - distArr[i] = sdf[i] * 255 - } - } +function __normalize_260(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 - var radius = Math.floor(Math.sqrt(distArr.length)) + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] - pos = markerTextures.length + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + var curves = _$cjs_258({ + px: x, + py: y, + cx: seg[6], + cy: seg[7], + rx: seg[1], + ry: seg[2], + xAxisRotation: seg[3], + largeArcFlag: seg[4], + sweepFlag: seg[5] + }) - markerCache.push(sdf) - markerTextures.push(regl.texture({ - channels: 1, - data: distArr, - radius: radius, - mag: 'linear', - min: 'linear' - })) + // null-curves + if (!curves.length) continue - return pos - } + for (var j = 0, c; j < curves.length; j++) { + c = curves[j] + seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y] + if (j < curves.length - 1) result.push(seg) + } - // register color to palette, return it's index or list of indexes - function updateColor (colors) { - if (!Array.isArray(colors)) { - colors = [colors] - } + 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_260(x, y, quadX, quadY, seg[1], seg[2]) + break + case 'Q': + quadX = seg[1] + quadY = seg[2] + seg = __quadratic_260(x, y, seg[1], seg[2], seg[3], seg[4]) + break + case 'L': + seg = __line_260(x, y, seg[1], seg[2]) + break + case 'H': + seg = __line_260(x, y, seg[1], y) + break + case 'V': + seg = __line_260(x, y, x, seg[1]) + break + case 'Z': + seg = __line_260(x, y, startX, startY) + break + } - var idx = [] + // 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) + } - for (var i = 0; i < colors.length; i++) { - var color = colors[i] + return result +} - // idx colors directly - if (typeof color === 'number') { - idx[i] = color - continue - } +function __line_260(x1, y1, x2, y2){ + return ['C', x1, y1, x2, y2, x2, y2] +} - color = _$normalize_58(color, 'uint8') +function __quadratic_260(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 + ] +} + +'use strict' - var id = _$colorId_56(color, false) +/* removed: var _$parse_207 = require('parse-svg-path') */; +/* removed: var _$absolutize_11 = require('abs-svg-path') */; +/* removed: var _$normalize_260 = require('normalize-svg-path') */; +/* removed: var _$isPath_193 = require('is-svg-path') */; +/* removed: var _$assert_16 = require('assert') */; - // if new color - save it - if (paletteIds[id] == null) { - var pos = palette.length - paletteIds[id] = Math.floor(pos / 4) - palette[pos] = color[0] - palette[pos+1] = color[1] - palette[pos+2] = color[2] - palette[pos+3] = color[3] - } +var _$pathBounds_259 = pathBounds - idx[i] = paletteIds[id] - } - // limit max color - updatePalette(palette) +function pathBounds(path) { + // ES6 string tpl call + if (Array.isArray(path) && path.length === 1 && typeof path[0] === 'string') path = path[0] - // keep static index for single-color property - return idx.length === 1 ? idx[0] : idx - } + // svg path string + if (typeof path === 'string') { + _$assert_16(_$isPath_193(path), 'String is not an SVG path.') + path = _$parse_207(path) + } - function updatePalette(palette) { - var requiredHeight = Math.ceil(palette.length * .25 / maxColors) + _$assert_16(Array.isArray(path), 'Argument should be a string or an array of path segments.') - // pad data - if (requiredHeight > 1) { - palette = palette.slice() - for (var i = (palette.length * .25) % maxColors; i < requiredHeight * maxColors; i++) { - palette.push(0, 0, 0, 0) - } - } + path = _$absolutize_11(path) + path = _$normalize_260(path) - // ensure height - if (paletteTexture.height < requiredHeight) { - paletteTexture.resize(maxColors, requiredHeight) - } + if (!path.length) return [0, 0, 0, 0] - // update full data - paletteTexture.subimage({ - width: Math.min(palette.length * .25, maxColors), - height: requiredHeight, - data: palette - }, 0, 0) - } + var bounds = [Infinity, Infinity, -Infinity, -Infinity] - // remove unused stuff - function destroy () { - groups.length = 0 + for (var i = 0, l = path.length; i < l; i++) { + var points = path[i].slice(1) - sizeBuffer.destroy() - positionBuffer.destroy() - positionFractBuffer.destroy() - colorBuffer.destroy() - paletteTexture.destroy() - } + for (var j = 0; j < points.length; j += 2) { + if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0] + if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1] + if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0] + if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1] + } + } - return scatter2d + return bounds } + +var _$pathSdf_261 = {}; +(function (global){ 'use strict' -/* removed: var _$clamp_53 = require('clamp') */; - -var _$calcSDF_36 = calcSDF - -var INF = 1e20; - -function calcSDF(src, options) { - if (!options) options = {} +/* removed: var _$pathBounds_259 = require('svg-path-bounds') */; +/* removed: var _$parse_207 = require('parse-svg-path') */; +/* removed: var _$drawSvgPath_74 = require('draw-svg-path') */; +/* removed: var _$isPath_193 = require('is-svg-path') */; +/* removed: var _$calcSDF_37 = require('bitmap-sdf') */; - var cutoff = options.cutoff == null ? 0.25 : options.cutoff - var radius = options.radius == null ? 8 : options.radius - var channel = options.channel || 0 - var w, h, size, data, intData, stride, ctx, canvas, imgData, i, l +var canvas = document.createElement('canvas') +var ctx = canvas.getContext('2d') - // handle image container - if (ArrayBuffer.isView(src) || Array.isArray(src)) { - if (!options.width || !options.height) throw Error('For raw data width and height should be provided by options') - w = options.width, h = options.height - data = src - if (!options.stride) stride = Math.floor(src.length / w / h) - else stride = options.stride - } - else { - if (window.HTMLCanvasElement && src instanceof window.HTMLCanvasElement) { - canvas = src - ctx = canvas.getContext('2d') - w = canvas.width, h = canvas.height - imgData = ctx.getImageData(0, 0, w, h) - data = imgData.data - stride = 4 - } - else if (window.CanvasRenderingContext2D && src instanceof window.CanvasRenderingContext2D) { - canvas = src.canvas - ctx = src - w = canvas.width, h = canvas.height - imgData = ctx.getImageData(0, 0, w, h) - data = imgData.data - stride = 4 - } - else if (window.ImageData && src instanceof window.ImageData) { - imgData = src - w = src.width, h = src.height - data = imgData.data - stride = 4 - } - } +_$pathSdf_261 = pathSdf - size = Math.max(w, h) +function pathSdf (path, options) { + if (!_$isPath_193(path)) throw Error('Argument should be valid svg path string') - //convert int data to floats - if ((window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray) || (window.Uint8Array && data instanceof window.Uint8Array)) { - intData = data - data = Array(w*h) + if (!options) options = {} - for (i = 0, l = intData.length; i < l; i++) { - data[i] = intData[i*stride + channel] / 255 - } - } - else { - if (stride !== 1) throw Error('Raw data can have only 1 value per pixel') - } + var w, h + if (options.shape) { + w = options.shape[0] + h = options.shape[1] + } + else { + w = canvas.width = options.w || options.width || 200 + h = canvas.height = options.h || options.height || 200 + } + var size = Math.min(w, h) - // temporary arrays for the distance transform - var gridOuter = Array(w * h) - var gridInner = Array(w * h) - var f = Array(size) - var d = Array(size) - var z = Array(size + 1) - var v = Array(size) + var stroke = options.stroke || 0 - for (i = 0, l = w * h; i < l; i++) { - var a = data[i] - gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2) - gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2) - } + var viewbox = options.viewbox || options.viewBox || _$pathBounds_259(path) + var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])] + var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2 - edt(gridOuter, w, h, f, d, v, z) - edt(gridInner, w, h, f, d, v, z) + //clear ctx + ctx.fillStyle = 'black' + ctx.fillRect(0, 0, w, h) - var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h) + ctx.fillStyle = 'white' - for (i = 0, l = w*h; i < l; i++) { - dist[i] = _$clamp_53(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1) - } + if (stroke) { + if (typeof stroke != 'number') stroke = 1 + if (stroke > 0) { + ctx.strokeStyle = 'white' + } + else { + ctx.strokeStyle = 'black' + } - return dist -} + ctx.lineWidth = Math.abs(stroke) + } -// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/dt/ -function edt(data, width, height, f, d, v, z) { - for (var x = 0; x < width; x++) { - for (var y = 0; y < height; y++) { - f[y] = data[y * width + x] - } - edt1d(f, d, v, z, height) - for (y = 0; y < height; y++) { - data[y * width + x] = d[y] - } - } - for (y = 0; y < height; y++) { - for (x = 0; x < width; x++) { - f[x] = data[y * width + x] - } - edt1d(f, d, v, z, width) - for (x = 0; x < width; x++) { - data[y * width + x] = Math.sqrt(d[x]) - } - } -} + ctx.translate(w * .5, h * .5) + ctx.scale(maxScale, maxScale) -// 1D squared distance transform -function edt1d(f, d, v, z, n) { - v[0] = 0; - z[0] = -INF - z[1] = +INF + //if canvas svg paths api is available + if (global.Path2D) { + var path2d = new Path2D(path) + ctx.fill(path2d) + stroke && ctx.stroke(path2d) + } + //fallback to bezier-curves + else { + var segments = _$parse_207(path) + _$drawSvgPath_74(ctx, segments) + ctx.fill() + stroke && ctx.stroke() + } - for (var q = 1, k = 0; q < n; q++) { - var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]) - while (s <= z[k]) { - k-- - s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]) - } - k++ - v[k] = q - z[k] = s - z[k + 1] = +INF - } + ctx.setTransform(1, 0, 0, 1, 0, 0); - for (q = 0, k = 0; q < n; q++) { - while (z[k + 1] < q) k++ - d[q] = (q - v[k]) * (q - v[k]) + f[v[k]] - } + var data = _$calcSDF_37(ctx, { + cutoff: options.cutoff != null ? options.cutoff : .5, + radius: options.radius != null ? options.radius : size * .5 + }) + + return data } - -var _$absolutize_10 = absolutize - -/** - * redefine `path` with absolute coordinates - * - * @param {Array} path - * @return {Array} - */ - -function absolutize(path){ - var startX = 0 - var startY = 0 - var x = 0 - var y = 0 - - return path.map(function(seg){ - seg = seg.slice() - var type = seg[0] - var command = type.toUpperCase() - - // is relative - if (type != command) { - seg[0] = command - switch (type) { - case 'a': - seg[6] += x - seg[7] += y - break - case 'v': - seg[1] += y - break - case 'h': - seg[1] += x - break - default: - for (var i = 1; i < seg.length;) { - seg[i++] += x - seg[i++] += y - } - } - } - - // update cursor state - switch (command) { - case 'Z': - x = startX - y = startY - break - case 'H': - x = seg[1] - break - case 'V': - y = seg[1] - break - case 'M': - x = startX = seg[1] - y = startY = seg[2] - break - default: - x = seg[seg.length - 2] - y = seg[seg.length - 1] - } - - return seg - }) -} - - -var π = Math.PI -var _120 = radians(120) - -var _$normalize_145 = __normalize_145 - +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) /** - * describe `path` in terms of cubic bézier - * curves and move commands - * - * @param {Array} path - * @return {Array} - */ +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -function __normalize_145(path){ - // init state - var prev - var result = [] - var bezierX = 0 - var bezierY = 0 - var startX = 0 - var startY = 0 - var quadX = null - var quadY = null - var x = 0 - var y = 0 - for (var i = 0, len = path.length; i < len; i++) { - var seg = path[i] - var command = seg[0] - switch (command) { - case 'M': - startX = seg[1] - startY = seg[2] - break - case 'A': - seg = arc(x, y,seg[1],seg[2],radians(seg[3]),seg[4],seg[5],seg[6],seg[7]) - // split multi part - seg.unshift('C') - if (seg.length > 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 - } +'use strict'; - // 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) - } +/* removed: var _$fastIsnumeric_135 = require('fast-isnumeric'); */; +/* removed: var _$normalize_59 = require('color-normalize'); */; - return result -} +/* removed: var _$colorscale_316 = require('../components/colorscale'); */; +var colorDflt = _$attributes_300.defaultLine; -function line(x1, y1, x2, y2){ - return ['C', x1, y1, x2, y2, x2, y2] -} +var colorDfltRgba = _$normalize_59(colorDflt); +var opacityDflt = 1; -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 - ] +function calculateColor(colorIn, opacityIn) { + var colorOut = colorIn; + colorOut[3] *= opacityIn; + return colorOut; } -// 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 validateColor(colorIn) { + if(_$fastIsnumeric_135(colorIn)) return colorDfltRgba; -function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { - if (!recursive) { - var xy = __rotate_145(x1, y1, -angle) - x1 = xy.x - y1 = xy.y - xy = __rotate_145(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)) + var colorOut = _$normalize_59(colorIn); - 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_145(curve[i], curve[i+1], angle) - curve[i++] = rot.x - curve[i++] = rot.y - } - return curve + return colorOut.length ? colorOut : colorDfltRgba; } -function __rotate_145(x, y, rad){ - return { - x: x * Math.cos(rad) - y * Math.sin(rad), - y: x * Math.sin(rad) + y * Math.cos(rad) - } +function validateOpacity(opacityIn) { + return _$fastIsnumeric_135(opacityIn) ? opacityIn : opacityDflt; } -function radians(degress){ - return degress * (π / 180) -} +function formatColor(containerIn, opacityIn, len) { + var colorIn = containerIn.color, + isArrayColorIn = Array.isArray(colorIn), + isArrayOpacityIn = Array.isArray(opacityIn), + colorOut = []; -/* removed: var _$absolutize_10 = require('abs-svg-path') */; -/* removed: var _$normalize_145 = require('normalize-svg-path') */; + var sclFunc, getColor, getOpacity, colori, opacityi; -var methods = { - 'M': 'moveTo', - 'C': 'bezierCurveTo' -} + if(containerIn.colorscale !== undefined) { + sclFunc = _$colorscale_316.makeColorScaleFunc( + _$colorscale_316.extractScale( + containerIn.colorscale, + containerIn.cmin, + containerIn.cmax + ) + ); + } + else { + sclFunc = validateColor; + } -var _$drawSvgPath_71 = function(context, segments) { - context.beginPath() + if(isArrayColorIn) { + getColor = function(c, i) { + // FIXME: there is double work, considering that sclFunc does the opposite + return c[i] === undefined ? colorDfltRgba : _$normalize_59(sclFunc(c[i])); + }; + } + else getColor = validateColor; - // Make path easy to reproduce. - _$normalize_145(_$absolutize_10(segments)).forEach( - function(segment) { - var command = segment[0] - var args = segment.slice(1) + if(isArrayOpacityIn) { + getOpacity = function(o, i) { + return o[i] === undefined ? opacityDflt : validateOpacity(o[i]); + }; + } + else getOpacity = validateOpacity; - // Convert the path command to a context method. - context[methods[command]].apply(context, args) + 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(_$normalize_59(colorIn), opacityIn); - context.closePath() + return colorOut; } -'use strict' - -var _$isPath_135 = function isPath(str) { - if (typeof str !== 'string') return false - - str = str.trim() - - // https://www.w3.org/TR/SVG/paths.html#PathDataBNF - if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str) && /[\dz]$/i.test(str) && str.length > 4) return true - - return false -} - - -var _$parse_149 = __parse_149 +var _$formatColor_421 = formatColor; /** - * expected argument lengths - * @type {Object} - */ +* Copyright 2012-2018, Plotly, Inc. +* All 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 length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} +'use strict'; -/** - * segment pattern - * @type {RegExp} - */ +/* removed: var _$pathSdf_261 = require('svg-path-sdf'); */; +/* removed: var _$normalize_59 = require('color-normalize'); */; -var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$drawing_326 = require('../../components/drawing'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; -/** - * parse an svg path data string. Generates an Array - * of commands where each command is an Array of the - * form `[command, arg1, arg2, ...]` - * - * @param {String} path - * @return {Array} - */ +/* removed: var _$formatColor_421 = require('../../lib/gl_format_color'); */; +/* removed: var _$subtypes_598 = require('../scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_593 = require('../scatter/make_bubble_size_func'); */; -function __parse_149(path) { - var data = [] - path.replace(segment, function(_, command, args){ - var type = command.toLowerCase() - args = parseValues(args) +/* removed: var _$constants_603 = require('./constants'); */; +var __DESELECTDIM_604 = _$interactions_403.DESELECTDIM; - // overloaded moveTo - if (type == 'm' && args.length > 2) { - data.push([command].concat(args.splice(0, 2))) - type = 'l' - command = command == 'm' ? 'l' : 'L' - } +function convertStyle(gd, trace) { + var i; - while (true) { - if (args.length == length[type]) { - args.unshift(command) - return data.push(args) - } - if (args.length < length[type]) throw new Error('malformed path data') - data.push([command].concat(args.splice(0, length[type]))) - } - }) - return data -} + var opts = { + marker: undefined, + line: undefined, + fill: undefined, + errorX: undefined, + errorY: undefined, + selected: undefined, + unselected: undefined + }; -var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig + if(trace.visible !== true) return opts; -function parseValues(args) { - var numbers = args.match(number) - return numbers ? numbers.map(Number) : [] -} + if(_$subtypes_598.hasMarkers(trace)) { + opts.marker = convertMarkerStyle(trace); + opts.selected = convertMarkerSelection(trace, trace.selected); + opts.unselected = convertMarkerSelection(trace, trace.unselected); -var _$inherits_browser_211 = {}; -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - _$inherits_browser_211 = 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 - _$inherits_browser_211 = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} + if(!trace.unselected && Array.isArray(trace.marker.opacity)) { + var mo = trace.marker.opacity; + opts.unselected.opacity = new Array(mo.length); + for(i = 0; i < mo.length; i++) { + opts.unselected.opacity[i] = __DESELECTDIM_604 * mo[i]; + } + } + } -var _$isBuffer_212 = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -var _$util_213 = {}; -(function (process,global){ -// 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. + if(_$subtypes_598.hasLines(trace)) { + opts.line = { + overlay: true, + thickness: trace.line.width, + color: trace.line.color, + opacity: trace.opacity + }; + + var dashes = (_$constants_603.DASHES[trace.line.dash] || [1]).slice(); + for(i = 0; i < dashes.length; ++i) { + dashes[i] *= trace.line.width; + } + opts.line.dashes = dashes; + } -var formatRegExp = /%[sdj%]/g; -_$util_213.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); + if(trace.error_x && trace.error_x.visible) { + opts.errorX = convertErrorBarStyle(trace, trace.error_x); } - 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]'; + if(trace.error_y && trace.error_y.visible) { + opts.errorY = convertErrorBarStyle(trace, trace.error_y); + } + + if(!!trace.fill && trace.fill !== 'none') { + opts.fill = { + closed: true, + fill: trace.fillcolor, + thickness: 0 + }; + } + + return opts; +} + +function convertMarkerStyle(trace) { + var count = trace._length || trace._commonLength; + var optsIn = trace.marker; + var optsOut = {}; + var i; + + var multiSymbol = Array.isArray(optsIn.symbol); + var multiColor = _$lib_425.isArrayOrTypedArray(optsIn.color); + var multiLineColor = _$lib_425.isArrayOrTypedArray(optsIn.line.color); + var multiOpacity = _$lib_425.isArrayOrTypedArray(optsIn.opacity); + var multiSize = _$lib_425.isArrayOrTypedArray(optsIn.size); + var multiLineWidth = _$lib_425.isArrayOrTypedArray(optsIn.line.width); + + var isOpen; + if(!multiSymbol) isOpen = _$constants_603.OPEN_RE.test(optsIn.symbol); + + // prepare colors + if(multiSymbol || multiColor || multiLineColor || multiOpacity) { + optsOut.colors = new Array(count); + optsOut.borderColors = new Array(count); + + var colors = _$formatColor_421(optsIn, optsIn.opacity, count); + var borderColors = _$formatColor_421(optsIn.line, optsIn.opacity, count); + + if(!Array.isArray(borderColors[0])) { + var borderColor = borderColors; + borderColors = Array(count); + for(i = 0; i < count; i++) { + borderColors[i] = borderColor; + } } - default: - return x; + if(!Array.isArray(colors[0])) { + var color = colors; + colors = Array(count); + for(i = 0; i < count; i++) { + colors[i] = color; + } + } + + optsOut.colors = colors; + optsOut.borderColors = borderColors; + + for(i = 0; i < count; i++) { + if(multiSymbol) { + var symbol = optsIn.symbol[i]; + isOpen = _$constants_603.OPEN_RE.test(symbol); + } + if(isOpen) { + borderColors[i] = colors[i].slice(); + colors[i] = colors[i].slice(); + colors[i][3] = 0; + } + } + + optsOut.opacity = trace.opacity; + } else { + if(isOpen) { + optsOut.color = _$normalize_59(optsIn.color, 'uint8'); + optsOut.color[3] = 0; + optsOut.borderColor = _$normalize_59(optsIn.color, 'uint8'); + } else { + optsOut.color = _$normalize_59(optsIn.color, 'uint8'); + optsOut.borderColor = _$normalize_59(optsIn.line.color, 'uint8'); + } + + optsOut.opacity = trace.opacity * optsIn.opacity; } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; + + // prepare symbols + if(multiSymbol) { + optsOut.markers = new Array(count); + for(i = 0; i < count; i++) { + optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]); + } } else { - str += ' ' + inspect(x); + optsOut.marker = getSymbolSdf(optsIn.symbol); } - } - return str; -}; + // prepare sizes + var markerSizeFunc = _$makeBubbleSizeFn_593(trace); + var s; -// 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. -_$util_213.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return _$util_213.deprecate(fn, msg).apply(this, arguments); - }; - } + if(multiSize || multiLineWidth) { + var sizes = optsOut.sizes = new Array(count); + var borderSizes = optsOut.borderSizes = new Array(count); + var sizeTotal = 0; + var sizeAvg; - if (process.noDeprecation === true) { - return fn; - } + if(multiSize) { + for(i = 0; i < count; i++) { + sizes[i] = markerSizeFunc(optsIn.size[i]); + sizeTotal += sizes[i]; + } + sizeAvg = sizeTotal / count; + } else { + s = markerSizeFunc(optsIn.size); + for(i = 0; i < count; i++) { + sizes[i] = s; + } + } - 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; + // See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798 + if(multiLineWidth) { + for(i = 0; i < count; i++) { + borderSizes[i] = markerSizeFunc(optsIn.line.width[i]); + } + } else { + s = markerSizeFunc(optsIn.line.width); + for(i = 0; i < count; i++) { + borderSizes[i] = s; + } + } + + optsOut.sizeAvg = sizeAvg; + } else { + optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10); + optsOut.borderSizes = markerSizeFunc(optsIn.line.width); } - return fn.apply(this, arguments); - } - return deprecated; -}; + return optsOut; +} +function convertMarkerSelection(trace, target) { + var optsIn = trace.marker; + var optsOut = {}; -var debugs = {}; -var debugEnviron; -_$util_213.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.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 = _$util_213.format.apply(_$util_213, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; + if(!target) return optsOut; + + if(target.marker && target.marker.symbol) { + optsOut = convertMarkerStyle(_$lib_425.extendFlat({}, optsIn, target.marker)); + } else if(target.marker) { + if(target.marker.size) optsOut.sizes = target.marker.size; + if(target.marker.color) optsOut.colors = target.marker.color; + if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity; } - } - return debugs[set]; -}; + return optsOut; +} + +function convertErrorBarStyle(trace, target) { + var optsOut = { + capSize: target.width * 2, + lineWidth: target.thickness, + color: target.color + }; -/** - * 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 - _$util_213._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); + if(target.copy_ystyle) { + optsOut = trace.error_y; + } + + return optsOut; } -_$util_213.inspect = inspect; +var SYMBOL_SDF_SIZE = _$constants_603.SYMBOL_SDF_SIZE; +var __SYMBOL_SIZE_604 = _$constants_603.SYMBOL_SIZE; +var SYMBOL_STROKE = _$constants_603.SYMBOL_STROKE; +var SYMBOL_SDF = {}; +var SYMBOL_SVG_CIRCLE = _$drawing_326.symbolFuncs[0](__SYMBOL_SIZE_604 * 0.05); -// 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] -}; +function getSymbolSdf(symbol) { + if(symbol === 'circle') return null; -// 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' -}; + var symbolPath, symbolSdf; + var symbolNumber = _$drawing_326.symbolNumber(symbol); + var symbolFunc = _$drawing_326.symbolFuncs[symbolNumber % 100]; + var symbolNoDot = !!_$drawing_326.symbolNoDot[symbolNumber % 100]; + var symbolNoFill = !!_$drawing_326.symbolNoFill[symbolNumber % 100]; + var isDot = _$constants_603.DOT_RE.test(symbol); -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + // get symbol sdf from cache or generate it + if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol]; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} + if(isDot && !symbolNoDot) { + symbolPath = symbolFunc(__SYMBOL_SIZE_604 * 1.1) + SYMBOL_SVG_CIRCLE; + } + else { + symbolPath = symbolFunc(__SYMBOL_SIZE_604); + } + symbolSdf = _$pathSdf_261(symbolPath, { + w: SYMBOL_SDF_SIZE, + h: SYMBOL_SDF_SIZE, + viewBox: [-__SYMBOL_SIZE_604, -__SYMBOL_SIZE_604, __SYMBOL_SIZE_604, __SYMBOL_SIZE_604], + stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE + }); + SYMBOL_SDF[symbol] = symbolSdf; -function stylizeNoColor(str, styleType) { - return str; + return symbolSdf || null; } +function convertLinePositions(gd, trace, positions) { + var count = positions.length / 2; + var linePositions; + var i; -function arrayToHash(array) { - var hash = {}; + if(_$subtypes_598.hasLines(trace) && count) { + if(trace.line.shape === 'hv') { + linePositions = []; + for(i = 0; i < count - 1; i++) { + if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + } + else { + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 1]); + linePositions.push(positions[i * 2 + 2]); + linePositions.push(positions[i * 2 + 1]); + } + } + linePositions.push(positions[positions.length - 2]); + linePositions.push(positions[positions.length - 1]); + } else if(trace.line.shape === 'vh') { + linePositions = []; + for(i = 0; i < count - 1; i++) { + if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + } + else { + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 1]); + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 3]); + } + } + linePositions.push(positions[positions.length - 2]); + linePositions.push(positions[positions.length - 1]); + } else { + linePositions = positions; + } + } - array.forEach(function(val, idx) { - hash[val] = true; - }); + // If we have data with gaps, we ought to use rect joins + // FIXME: get rid of this + var hasNaN = false; + for(i = 0; i < linePositions.length; i++) { + if(isNaN(linePositions[i])) { + hasNaN = true; + break; + } + } - return hash; -} + var join = (hasNaN || linePositions.length > _$constants_603.TOO_MANY_POINTS) ? 'rect' : + _$subtypes_598.hasMarkers(trace) ? 'rect' : 'round'; + // fill gaps + if(hasNaN && trace.connectgaps) { + var lastX = linePositions[0]; + var lastY = linePositions[1]; -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 !== _$util_213.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); + for(i = 0; i < linePositions.length; i += 2) { + if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { + linePositions[i] = lastX; + linePositions[i + 1] = lastY; + } + else { + lastX = linePositions[i]; + lastY = linePositions[i + 1]; + } + } } - return ret; - } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + return { + join: join, + positions: linePositions + }; +} - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); +function convertErrorBarPositions(gd, trace, positions) { + var calcFromTrace = _$registry_514.getComponentMethod('errorbars', 'calcFromTrace'); + var vals = calcFromTrace(trace, gd._fullLayout); + var count = positions.length / 2; + var out = {}; - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + function put(axLetter) { + var errors = new Float64Array(4 * count); + var ax = _$axis_ids_473.getFromId(gd, trace[axLetter + 'axis']); + var pOffset = {x: 0, y: 1}[axLetter]; + var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter]; - // 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); - } + for(var i = 0, p = 0; i < count; i++, p += 4) { + errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0; + errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0; + errors[p + eOffset[2]] = 0; + errors[p + eOffset[3]] = 0; + } - // 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'); + return errors; } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + + + if(trace.error_x && trace.error_x.visible) { + out.x = { + positions: positions, + errors: put('x') + }; } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); + if(trace.error_y && trace.error_y.visible) { + out.y = { + positions: positions, + errors: put('y') + }; } - if (isError(value)) { - return formatError(value); + + return out; +} + +var _$convert_604 = { + convertStyle: convertStyle, + convertMarkerStyle: convertMarkerStyle, + convertMarkerSelection: convertMarkerSelection, + convertLinePositions: convertLinePositions, + convertErrorBarPositions: convertErrorBarPositions +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$registry_514 = require('../../registry'); */; + +/* removed: var _$attributes_602 = require('./attributes'); */; +/* removed: var _$constants_582 = require('../scatter/constants'); */; +/* removed: var _$subtypes_598 = require('../scatter/subtypes'); */; +/* removed: var _$handleXYDefaults_600 = require('../scatter/xy_defaults'); */; +/* removed: var _$markerDefaults_594 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_589 = require('../scatter/line_defaults'); */; +/* removed: var _$fillColorDefaults_585 = require('../scatter/fillcolor_defaults'); */; + +var _$supplyDefaults_605 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_425.coerce(traceIn, traceOut, _$attributes_602, attr, dflt); } - } - var base = '', array = false, braces = ['{', '}']; + var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false; + var isBubble = _$subtypes_598.isBubble(traceIn); - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + var len = _$handleXYDefaults_600(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; + } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + coerce('text'); + coerce('mode', len < _$constants_582.PTS_LINESONLY ? 'lines+markers' : 'lines'); - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + if(_$subtypes_598.hasLines(traceOut)) { + coerce('connectgaps'); + _$lineDefaults_589(traceIn, traceOut, defaultColor, layout, coerce); + } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + var dfltHoverOn = []; - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + if(_$subtypes_598.hasMarkers(traceOut)) { + _$markerDefaults_594(traceIn, traceOut, defaultColor, layout, coerce); + coerce('marker.line.width', isOpen || isBubble ? 1 : 0); + dfltHoverOn.push('points'); + } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + coerce('fill'); + if(traceOut.fill !== 'none') { + _$fillColorDefaults_585(traceIn, traceOut, defaultColor, coerce); + } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); + if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { + dfltHoverOn.push('fills'); } - } - ctx.seen.push(value); + coerce('hoveron', dfltHoverOn.join('+') || 'points'); - 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); - }); - } + var errorBarsSupplyDefaults = _$registry_514.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - ctx.seen.pop(); + _$lib_425.coerceSelectionMarkerOpacity(traceOut, coerce); +}; - return reduceToSingleString(output, base, braces); -} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ +'use strict'; -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'); -} +/* removed: var _$reglScatter2d_236 = require('regl-scatter2d'); */; +/* removed: var _$Line2D_235 = require('regl-line2d'); */; +/* removed: var _$Error2D_234 = require('regl-error2d'); */; +/* removed: var _$pointCluster_216 = require('point-cluster'); */; +/* removed: var _$newArray_15 = require('array-range'); */; + +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$prepareRegl_438 = require('../../lib/prepare_regl'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; + +/* removed: var _$subtypes_598 = require('../scatter/subtypes'); */; +var __calcMarkerSize_606 = _$calc_577.calcMarkerSize; +var __calcAxisExpansion_606 = _$calc_577.calcAxisExpansion; +/* removed: var _$calcMarkerColorscale_581 = require('../scatter/colorscale_calc'); */; +/* removed: var _$linkTraces_592 = require('../scatter/link_traces'); */; +/* removed: var _$getTraceColor_586 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_584 = require('../scatter/fill_hover_text'); */; + +var __convertStyle_606 = _$convert_604.convertStyle; +var __convertLinePositions_606 = _$convert_604.convertLinePositions; +var __convertErrorBarPositions_606 = _$convert_604.convertErrorBarPositions; + +var __BADNUM_606 = _$numerical_404.BADNUM; +var TOO_MANY_POINTS = _$constants_603.TOO_MANY_POINTS; + +function __calc_606(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axis_ids_473.getFromId(gd, trace.xaxis); + var ya = _$axis_ids_473.getFromId(gd, trace.yaxis); + var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; + var count = trace._length; + var count2 = count * 2; + var stash = {}; + var i, xx, yy; + var x = xa.makeCalcdata(trace, 'x'); + var y = ya.makeCalcdata(trace, 'y'); -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} + // we need hi-precision for scatter2d, + // regl-scatter2d uses NaNs for bad/missing values + var positions = new Array(count2); + for(i = 0; i < count; i++) { + xx = x[i]; + yy = y[i]; + positions[i * 2] = xx === __BADNUM_606 ? NaN : xx; + positions[i * 2 + 1] = yy === __BADNUM_606 ? NaN : yy; + } + if(xa.type === 'log') { + for(i = 0; i < count2; i += 2) { + positions[i] = xa.c2l(positions[i]); + } + } + if(ya.type === 'log') { + for(i = 1; i < count2; i += 2) { + positions[i] = ya.c2l(positions[i]); + } + } -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)); + // we don't build a tree for log axes since it takes long to convert log2px + // and it is also + if(xa.type !== 'log' && ya.type !== 'log') { + // FIXME: delegate this to webworker + stash.tree = _$pointCluster_216(positions); } else { - output.push(''); + var ids = stash.ids = new Array(count); + for(i = 0; i < count; i++) { + ids[i] = i; + } } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); + + // create scene options and scene + _$calcMarkerColorscale_581(trace); + var opts = sceneOptions(gd, subplot, trace, positions); + var scene = sceneUpdate(gd, subplot); + + // Re-use SVG scatter axis expansion routine except + // for graph with very large number of points where it + // performs poorly. + // In big data case, fake Axes.expand outputs with data bounds, + // and an average size for array marker.size inputs. + var ppad; + if(count < TOO_MANY_POINTS) { + ppad = __calcMarkerSize_606(trace, count); + } else if(opts.marker) { + ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3)); } - }); - return output; + __calcAxisExpansion_606(gd, trace, xa, ya, x, y, ppad); + + // set flags to create scene renderers + if(opts.fill && !scene.fill2d) scene.fill2d = true; + if(opts.marker && !scene.scatter2d) scene.scatter2d = true; + if(opts.line && !scene.line2d) scene.line2d = true; + if((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true; + + // FIXME: organize it in a more appropriate manner, probably in sceneOptions + // put point-cluster instance for optimized regl calc + if(opts.marker && count >= TOO_MANY_POINTS) { + opts.marker.cluster = stash.tree; + } + + // save scene opts batch + scene.lineOptions.push(opts.line); + scene.errorXOptions.push(opts.errorX); + scene.errorYOptions.push(opts.errorY); + scene.fillOptions.push(opts.fill); + scene.markerOptions.push(opts.marker); + scene.selectedOptions.push(opts.selected); + scene.unselectedOptions.push(opts.unselected); + scene.count++; + + // stash scene ref + stash._scene = scene; + stash.index = scene.count - 1; + stash.x = x; + stash.y = y; + stash.positions = positions; + stash.count = count; + + gd.firstscatter = false; + return [{x: false, y: false, t: stash, trace: trace}]; } +// create scene options +function sceneOptions(gd, subplot, trace, positions) { + var opts = __convertStyle_606(gd, trace); -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'); + if(opts.marker) { + opts.marker.positions = positions; } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); + + if(opts.line && positions.length > 1) { + _$lib_425.extendFlat( + opts.line, + __convertLinePositions_606(gd, trace, positions) + ); } - } - 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'); + + if(opts.errorX || opts.errorY) { + var errors = __convertErrorBarPositions_606(gd, trace, positions); + + if(opts.errorX) { + _$lib_425.extendFlat(opts.errorX, errors.x); + } + if(opts.errorY) { + _$lib_425.extendFlat(opts.errorY, errors.y); } - } - } 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; + return opts; } +// make sure scene exists on subplot, return it +function sceneUpdate(gd, subplot) { + var scene = subplot._scene; + var fullLayout = gd._fullLayout; -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); + var reset = { + // 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: [], + selectedOptions: [], + unselectedOptions: [], + errorXOptions: [], + errorYOptions: [] + }; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + var first = { + selectBatch: null, + unselectBatch: null, + // regl- component stubs, initialized in dirty plot call + fill2d: false, + scatter2d: false, + error2d: false, + line2d: false, + select2d: null + }; - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} + if(!subplot._scene) { + scene = subplot._scene = _$lib_425.extendFlat({}, reset, first); + // apply new option to all regl components (used on drag) + scene.update = function update(opt) { + var opts = new Array(scene.count); + for(var i = 0; i < scene.count; i++) { + opts[i] = opt; + } -// 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); -} -_$util_213.isArray = isArray; + 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); -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -_$util_213.isBoolean = isBoolean; + scene.draw(); + }; -function isNull(arg) { - return arg === null; -} -_$util_213.isNull = isNull; + // draw traces in proper order + scene.draw = function draw() { + var i; + for(i = 0; i < scene.count; i++) { + if(scene.fill2d && scene.fillOptions[i]) { + // must do all fills first + scene.fill2d.draw(i); + } + } + for(i = 0; i < scene.count; i++) { + if(scene.line2d && scene.lineOptions[i]) { + scene.line2d.draw(i); + } + if(scene.error2d && scene.errorXOptions[i]) { + scene.error2d.draw(i); + } + if(scene.error2d && scene.errorYOptions[i]) { + scene.error2d.draw(i + scene.count); + } + if(scene.scatter2d && scene.markerOptions[i] && (!scene.selectBatch || !scene.selectBatch[i])) { + // traces in no-selection mode + scene.scatter2d.draw(i); + } + } -function isNullOrUndefined(arg) { - return arg == null; -} -_$util_213.isNullOrUndefined = isNullOrUndefined; + // draw traces in selection mode + if(scene.scatter2d && scene.select2d && scene.selectBatch) { + scene.select2d.draw(scene.selectBatch); + scene.scatter2d.draw(scene.unselectBatch); + } -function isNumber(arg) { - return typeof arg === 'number'; -} -_$util_213.isNumber = isNumber; + scene.dirty = false; + }; -function isString(arg) { - return typeof arg === 'string'; -} -_$util_213.isString = isString; + // make sure canvas is clear + scene.clear = function clear() { + var vpSize = fullLayout._size; + var width = fullLayout.width; + var height = fullLayout.height; + var xaxis = subplot.xaxis; + var yaxis = subplot.yaxis; + var vp = [ + vpSize.l + xaxis.domain[0] * vpSize.w, + vpSize.b + yaxis.domain[0] * vpSize.h, + (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, + (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h + ]; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -_$util_213.isSymbol = isSymbol; + var gl, regl; -function isUndefined(arg) { - return arg === void 0; -} -_$util_213.isUndefined = isUndefined; + if(scene.select2d) { + regl = scene.select2d.regl; + gl = regl._gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -_$util_213.isRegExp = isRegExp; + if(scene.scatter2d) { + regl = scene.scatter2d.regl; + gl = regl._gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + }; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -_$util_213.isObject = isObject; + // remove scene resources + scene.destroy = function destroy() { + if(scene.fill2d) scene.fill2d.destroy(); + if(scene.scatter2d) scene.scatter2d.destroy(); + if(scene.error2d) scene.error2d.destroy(); + if(scene.line2d) scene.line2d.destroy(); + if(scene.select2d) scene.select2d.destroy(); -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -_$util_213.isDate = isDate; + scene.lineOptions = null; + scene.fillOptions = null; + scene.markerOptions = null; + scene.selectedOptions = null; + scene.unselectedOptions = null; + scene.errorXOptions = null; + scene.errorYOptions = null; + scene.selectBatch = null; + scene.unselectBatch = null; -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -_$util_213.isError = isError; + // 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; + }; + } -function isFunction(arg) { - return typeof arg === 'function'; -} -_$util_213.isFunction = isFunction; + // In case if we have scene from the last calc - reset data + if(!scene.dirty) { + _$lib_425.extendFlat(scene, reset); + } -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; + return scene; } -_$util_213.isPrimitive = isPrimitive; -_$util_213.isBuffer = _$isBuffer_212; +function plot(gd, subplot, cdata) { + if(!cdata.length) return; -function objectToString(o) { - return Object.prototype.toString.call(o); -} + var fullLayout = gd._fullLayout; + var scene = cdata[0][0].t._scene; + var dragmode = fullLayout.dragmode; + // we may have more subplots than initialized data due to Axes.getSubplots method + if(!scene) return; -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} + var vpSize = fullLayout._size; + var width = fullLayout.width; + var height = fullLayout.height; + _$prepareRegl_438(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']); + var regl = fullLayout._glcanvas.data()[0].regl; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + // that is needed for fills + _$linkTraces_592(gd, subplot, cdata); -// 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(' '); -} + if(scene.dirty) { + // make sure scenes are created + if(scene.error2d === true) { + scene.error2d = _$Error2D_234(regl); + } + if(scene.line2d === true) { + scene.line2d = _$Line2D_235(regl); + } + if(scene.scatter2d === true) { + scene.scatter2d = _$reglScatter2d_236(regl); + } + if(scene.fill2d === true) { + scene.fill2d = _$Line2D_235(regl); + } + // update main marker options + if(scene.line2d) { + 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 + if(scene.fill2d) { + scene.fillOptions = scene.fillOptions.map(function(fillOptions, i) { + var cdscatter = cdata[i]; + if(!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return null; + var cd = cdscatter[0]; + var trace = cd.trace; + var stash = cd.t; + var lineOptions = scene.lineOptions[i]; + var last, j; -// log is just a thin wrapper to console.log that prepends a timestamp -_$util_213.log = function() { - console.log('%s - %s', timestamp(), _$util_213.format.apply(_$util_213, arguments)); -}; + var pos = [], srcPos = (lineOptions && lineOptions.positions) || stash.positions; + if(trace.fill === 'tozeroy') { + pos = [srcPos[0], 0]; + pos = pos.concat(srcPos); + pos.push(srcPos[srcPos.length - 2]); + pos.push(0); + } + else if(trace.fill === 'tozerox') { + pos = [0, srcPos[1]]; + pos = pos.concat(srcPos); + pos.push(0); + pos.push(srcPos[srcPos.length - 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; -/** - * 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. - */ -_$util_213.inherits = _$inherits_browser_211; + if(nextTrace) { + var nextOptions = scene.lineOptions[i + 1]; -_$util_213._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + if(nextOptions) { + var nextPos = nextOptions.positions; + if(trace.fill === 'tonexty') { + pos = srcPos.slice(); - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; + for(i = Math.floor(nextPos.length / 2); i--;) { + var xx = nextPos[i * 2], yy = nextPos[i * 2 + 1]; + if(isNaN(xx) || isNaN(yy)) continue; + pos.push(xx); + pos.push(yy); + } + fillOptions.fill = nextTrace.fillcolor; + } + } + } + } -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} + // detect prev trace positions to exclude from current fill + if(trace._prevtrace && trace._prevtrace.fill === 'tonext') { + var prevLinePos = scene.lineOptions[i - 1].positions; -}).call(this,_$browser_166,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$assert_15 = {}; -(function (global){ -'use strict'; + // 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; + } + } -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: + pos = pos.concat(prevLinePos); + fillOptions.hole = hole; + } -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } + fillOptions.opacity = trace.opacity; + fillOptions.positions = pos; - var x = a.length; - var y = b.length; + return fillOptions; + }); - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; + scene.fill2d.update(scene.fillOptions); + } } - } - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); -} + var selectMode = dragmode === 'lasso' || dragmode === 'select'; + scene.selectBatch = null; + scene.unselectBatch = null; -// based on node assert, original notice: + // provide viewport and range + var vpRange = cdata.map(function(cdscatter) { + if(!cdscatter || !cdscatter[0] || !cdscatter[0].trace) return; + var cd = cdscatter[0]; + var trace = cd.trace; + var stash = cd.t; + var id = stash.index; + var x = stash.x; + var y = stash.y; -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + var xaxis = subplot.xaxis || _$axis_ids_473.getFromId(gd, trace.xaxis || 'x'); + var yaxis = subplot.yaxis || _$axis_ids_473.getFromId(gd, trace.yaxis || 'y'); + var i; -/* removed: var _$util_213 = require('util/'); */; -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); -} -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; - } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. + var range = [ + (xaxis._rl || xaxis.range)[0], + (yaxis._rl || yaxis.range)[0], + (xaxis._rl || xaxis.range)[1], + (yaxis._rl || yaxis.range)[1] + ]; -var assert = _$assert_15 = ok; + var viewport = [ + vpSize.l + xaxis.domain[0] * vpSize.w, + vpSize.b + yaxis.domain[0] * vpSize.h, + (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, + (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h + ]; -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) + if(trace.selectedpoints || selectMode) { + if(!selectMode) selectMode = true; -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!_$util_213.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } + // regenerate scene batch, if traces number changed during selection + if(trace.selectedpoints) { + scene.selectBatch[id] = trace.selectedpoints; - this.stack = out; + var selPts = trace.selectedpoints; + var selDict = {}; + for(i = 0; i < selPts.length; i++) { + selDict[selPts[i]] = true; + } + var unselPts = []; + for(i = 0; i < stash.count; i++) { + if(!selDict[i]) unselPts.push(i); + } + scene.unselectBatch[id] = unselPts; + } + + // precalculate px coords since we are not going to pan during select + var xpx = new Array(stash.count); + var ypx = new Array(stash.count); + for(i = 0; i < stash.count; i++) { + xpx[i] = xaxis.c2p(x[i]); + ypx[i] = yaxis.c2p(y[i]); + } + stash.xpx = xpx; + stash.ypx = ypx; + } + else { + stash.xpx = stash.ypx = null; + } + + return trace.visible ? { + viewport: viewport, + range: range + } : null; + }); + + if(selectMode) { + // create select2d + if(!scene.select2d) { + // create scatter instance by cloning scatter2d + scene.select2d = _$reglScatter2d_236(fullLayout._glcanvas.data()[1].regl); + } + + if(scene.scatter2d && scene.selectBatch && scene.selectBatch.length) { + // update only traces with selection + scene.scatter2d.update(scene.unselectedOptions.map(function(opts, i) { + return scene.selectBatch[i] ? opts : null; + })); + } + + if(scene.select2d) { + scene.select2d.update(scene.markerOptions); + scene.select2d.update(scene.selectedOptions); + } } - } -}; -// assert.AssertionError instanceof Error -_$util_213.inherits(assert.AssertionError, Error); + // uploat 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); + } -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !_$util_213.isFunction(something)) { - return _$util_213.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); + scene.draw(); + + return; } -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. +function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var stash = cd[0].t; + var trace = cd[0].trace; + var xa = pointData.xa; + var ya = pointData.ya; + var x = stash.x; + var y = stash.y; + var xpx = xa.c2p(xval); + var ypx = ya.c2p(yval); + var maxDistance = pointData.distance; + var ids; -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. + // FIXME: make sure this is a proper way to calc search radius + if(stash.tree) { + var xl = xa.p2c(xpx - maxDistance); + var xr = xa.p2c(xpx + maxDistance); + var yl = ya.p2c(ypx - maxDistance); + var yr = ya.p2c(ypx + maxDistance); -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} + if(hovermode === 'x') { + ids = stash.tree.range( + Math.min(xl, xr), Math.min(ya._rl[0], ya._rl[1]), + Math.max(xl, xr), Math.max(ya._rl[0], ya._rl[1]) + ); + } + else { + ids = stash.tree.range( + Math.min(xl, xr), Math.min(yl, yr), + Math.max(xl, xr), Math.max(yl, yr) + ); + } + } + else if(stash.ids) { + ids = stash.ids; + } + else return [pointData]; -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; + // pick the id closest to the point + // note that point possibly may not be found + var id, ptx, pty, i, dx, dy, dist, dxy; -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. + var minDist = maxDistance; + if(hovermode === 'x') { + for(i = 0; i < ids.length; i++) { + ptx = x[ids[i]]; + dx = Math.abs(xa.c2p(ptx) - xpx); + if(dx < minDist) { + minDist = dx; + dy = ya.c2p(y[ids[i]]) - ypx; + dxy = Math.sqrt(dx * dx + dy * dy); + id = ids[i]; + } + } + } + else { + for(i = 0; i < ids.length; i++) { + ptx = x[ids[i]]; + pty = y[ids[i]]; + dx = xa.c2p(ptx) - xpx; + dy = ya.c2p(pty) - ypx; -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; + dist = Math.sqrt(dx * dx + dy * dy); + if(dist < minDist) { + minDist = dxy = dist; + id = ids[i]; + } + } + } -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); + pointData.index = id; + pointData.distance = minDist; + pointData.dxy = dxy; -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; + if(id === undefined) return [pointData]; -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); + calcHover(pointData, x, y, trace); -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; + return [pointData]; +} -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; +function calcHover(pointData, x, y, trace) { + var xa = pointData.xa; + var ya = pointData.ya; + var minDist = pointData.distance; + var dxy = pointData.dxy; + var id = pointData.index; -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; + // the closest data point + var di = { + pointNumber: id, + x: x[id], + y: y[id] + }; -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; + // that is single-item arrays_to_calcdata excerpt, since we are doing it for a single point and we don't have to do it beforehead for 1e6 points + di.tx = Array.isArray(trace.text) ? trace.text[id] : trace.text; + di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext; + di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata; + di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition; - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (_$util_213.isDate(actual) && _$util_213.isDate(expected)) { - return actual.getTime() === expected.getTime(); + var font = trace.textfont; + if(font) { + di.ts = Array.isArray(font.size) ? font.size[id] : font.size; + di.tc = Array.isArray(font.color) ? font.color[id] : font.color; + di.tf = Array.isArray(font.family) ? font.family[id] : font.family; + } - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (_$util_213.isRegExp(actual) && _$util_213.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; + var marker = trace.marker; + if(marker) { + di.ms = _$lib_425.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size; + di.mo = _$lib_425.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity; + di.mx = Array.isArray(marker.symbol) ? marker.symbol[id] : marker.symbol; + di.mc = _$lib_425.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color; + } - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; + var line = marker && marker.line; + if(line) { + di.mlc = Array.isArray(line.color) ? line.color[id] : line.color; + di.mlw = _$lib_425.isArrayOrTypedArray(line.width) ? line.width[id] : line.width; + } - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; + var grad = marker && marker.gradient; + if(grad && grad.type !== 'none') { + di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type; + di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color; + } - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; + var xp = xa.c2p(di.x, true); + var yp = ya.c2p(di.y, true); + var rad = di.mrc || 1; - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } + var hoverlabel = trace.hoverlabel; + + if(hoverlabel) { + di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor; + di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor; + di.hts = Array.isArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size; + di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color; + di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family; + di.hnl = Array.isArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength; + } + var hoverinfo = trace.hoverinfo; + if(hoverinfo) { + di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo; } - memos.actual.push(actual); - memos.expected.push(expected); + var fakeCd = {}; + fakeCd[pointData.index] = di; - return objEquiv(actual, expected, strict, memos); - } -} + _$lib_425.extendFlat(pointData, { + color: _$getTraceColor_586(trace, di), -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} + x0: xp - rad, + x1: xp + rad, + xLabelVal: di.x, -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (_$util_213.isPrimitive(a) || _$util_213.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; -} + y0: yp - rad, + y1: yp + rad, + yLabelVal: di.y, -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); + cd: fakeCd, + distance: minDist, + spikeDistance: dxy + }); -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; + if(di.htx) pointData.text = di.htx; + else if(di.tx) pointData.text = di.tx; + else if(trace.text) pointData.text = trace.text; -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } -} + _$fillHoverText_584(di, trace, pointData); + _$registry_514.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + return pointData; +} -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; +function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var selection = []; + var trace = cd[0].trace; + var stash = cd[0].t; + var x = stash.x; + var y = stash.y; + var scene = stash._scene; -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + if(!scene) return selection; -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; + var hasOnlyLines = (!_$subtypes_598.hasMarkers(trace) && !_$subtypes_598.hasText(trace)); + if(trace.visible !== true || hasOnlyLines) return selection; -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } + // degenerate polygon does not enable selection + // filter out points by visible scatter ones + var els = null; + var unels = null; + var i; + if(polygon !== false && !polygon.degenerate) { + els = [], unels = []; + for(i = 0; i < stash.count; i++) { + if(polygon.contains([stash.xpx[i], stash.ypx[i]])) { + els.push(i); + selection.push({ + pointNumber: i, + x: x[i], + y: y[i] + }); + } + else { + unels.push(i); + } + } + } else { + unels = _$newArray_15(stash.count); + } - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } + // make sure selectBatch is created + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } - try { - if (actual instanceof expected) { - return true; + if(!scene.selectBatch[stash.index]) { + // enter every trace select mode + for(i = 0; i < scene.count; i++) { + scene.selectBatch[i] = []; + scene.unselectBatch[i] = []; + } + // we should turn scatter2d into unselected once we have any points selected + scene.scatter2d.update(scene.unselectedOptions); } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } - - if (Error.isPrototypeOf(expected)) { - return false; - } - return expected.call({}, actual) === true; -} + scene.selectBatch[stash.index] = els; + scene.unselectBatch[stash.index] = unels; -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; + return selection; } -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } - - if (typeof expected === 'string') { - message = expected; - expected = null; - } - - actual = _tryBlock(block); +function __style_606(gd, cds) { + if(!cds) return; - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + var stash = cds[0][0].t; + var scene = stash._scene; - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } + // don't clear the subplot if there are splom traces + // on the graph + if(!gd._fullLayout._has('splom')) { + scene.clear(); + } - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && _$util_213.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; + scene.draw(); +} - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } +var _$scattergl_606 = { + moduleType: 'trace', + name: 'scattergl', + basePlotModule: _$cartesian_481, + categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'markerColorscale', 'showLegend', 'scatter-like'], - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} + attributes: _$attributes_602, + supplyDefaults: _$supplyDefaults_605, + cleanData: _$cleanData_579, + colorbar: _$colorbar_580, + calc: __calc_606, + plot: plot, + hoverPoints: hoverPoints, + style: __style_606, + selectPoints: selectPoints, -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); + sceneOptions: sceneOptions, + sceneUpdate: sceneUpdate, + calcHover: calcHover, -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); + meta: { + + + } }; -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -assert.ifError = function(err) { if (err) throw err; }; +'use strict'; -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); +var _$scattergl_9 = _$scattergl_606; + +var _$performanceNow_209 = {}; +(function (process){ +// Generated by CoffeeScript 1.12.2 +(function() { + var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; + + if ((typeof performance !== "undefined" && performance !== null) && performance.now) { + _$performanceNow_209 = function() { + return performance.now(); + }; + } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { + _$performanceNow_209 = 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) { + _$performanceNow_209 = function() { + return Date.now() - loadTime; + }; + loadTime = Date.now(); + } else { + _$performanceNow_209 = function() { + return new Date().getTime() - loadTime; + }; + loadTime = new Date().getTime(); } - return keys; -}; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$cjs_196 = {}; -"use strict"; +}).call(this); -Object.defineProperty(_$cjs_196, "__esModule", { - value: true -}); +//# sourceMappingURL=performance-now.js.map -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"); } }; }(); +}).call(this,_$browser_228) +var _$raf_229 = {}; +(function (global){ +var __dummy_229$0 = 0 + , root = typeof window === 'undefined' ? global : window + , vendors = ['moz', 'webkit'] + , suffix = 'AnimationFrame' + , raf = root['request' + suffix] + , caf = root['cancel' + suffix] || root['cancelRequest' + suffix] + +for(var i = 0; !raf && i < vendors.length; i++) { + raf = root[vendors[i] + 'Request' + suffix] + caf = root[vendors[i] + 'Cancel' + suffix] + || root[vendors[i] + 'CancelRequest' + suffix] +} + +// Some versions of FF have rAF but not cAF +if(!raf || !caf) { + var last = 0 + , id = 0 + , queue = [] + , frameDuration = 1000 / 60 + + raf = function(callback) { + if(queue.length === 0) { + var _now = _$performanceNow_209() + , next = Math.max(0, frameDuration - (_now - last)) + last = next + _now + setTimeout(function() { + var cp = queue.slice(0) + // Clear queue here to prevent + // callbacks from appending listeners + // to the current frame's queue + queue.length = 0 + for(var i = 0; i < cp.length; i++) { + if(!cp[i].cancelled) { + try{ + cp[i].callback(last) + } catch(e) { + setTimeout(function() { throw e }, 0) + } + } + } + }, Math.round(next)) + } + queue.push({ + handle: ++id, + callback: callback, + cancelled: false + }) + return id + } -var TAU = Math.PI * 2; + caf = function(handle) { + for(var i = 0; i < queue.length; i++) { + if(queue[i].handle === handle) { + queue[i].cancelled = true + } + } + } +} -var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) { - var x = _ref.x, - y = _ref.y; +_$raf_229 = function(fn) { + // Wrap in a new function to prevent + // `cancel` potentially being assigned + // to the native rAF function + return raf.call(root, fn) +} +_$raf_229.cancel = function() { + caf.apply(root, arguments) +} +_$raf_229.polyfill = function(object) { + if (!object) { + object = root; + } + object.requestAnimationFrame = raf + object.cancelAnimationFrame = caf +} - x *= rx; - y *= ry; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' - var xp = cosphi * x - sinphi * y; - var yp = sinphi * x + cosphi * y; - return { - x: xp + centerx, - y: yp + centery - }; -}; +/* removed: var _$Scatter_237 = require('regl-scatter2d/scatter') */; +/* removed: var _$flattenVertexData_136 = require('flatten-vertex-data') */; +/* removed: var _$pick_212 = require('pick-by-alias') */; +/* removed: var _$normalize_13 = require('array-bounds') */; +/* removed: var _$raf_229 = require('raf') */; +/* removed: var _$newArray_15 = require('array-range') */; +/* removed: var _$parseRect_206 = require('parse-rect') */; -var approxUnitArc = function approxUnitArc(ang1, ang2) { - var a = 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); +var _$SPLOM_238 = SPLOM - 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 umag = Math.sqrt(ux * ux + uy * uy); - var vmag = Math.sqrt(ux * ux + uy * uy); - var dot = ux * vx + uy * vy; +// @constructor +function SPLOM (regl, options) { + if (!(this instanceof SPLOM)) { return new SPLOM(regl, options) } - var div = dot / (umag * vmag); + // render passes + this.traces = [] - if (div > 1) { - div = 1; - } + // passes for scatter, combined across traces + this.passes = {} - if (div < -1) { - div = -1; - } + this.regl = regl - return sign * Math.acos(div); -}; + // main scatter drawing instance + this.scatter = _$Scatter_237(regl) -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); + this.canvas = this.scatter.canvas +} - var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; - if (radicant < 0) { - radicant = 0; - } +// update & draw passes once per frame +SPLOM.prototype.render = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - radicant /= rxsq * pypsq + rysq * pxpsq; - radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + if (args.length) { + (ref = this).update.apply(ref, args) + } - var centerxp = radicant * rx / ry * pyp; - var centeryp = radicant * -ry / rx * pxp; + if (this.regl.attributes.preserveDrawingBuffer) { return this.draw() } - var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; - var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + // make sure draw is not called more often than once a frame + if (this.dirty) { + if (this.planned == null) { + this.planned = _$raf_229(function () { + this$1.draw() + this$1.dirty = true + this$1.planned = null + }) + } + } + else { + this.draw() + this.dirty = true + _$raf_229(function () { + this$1.dirty = false + }) + } - var vx1 = (pxp - centerxp) / rx; - var vy1 = (pyp - centeryp) / ry; - var vx2 = (-pxp - centerxp) / rx; - var vy2 = (-pyp - centeryp) / ry; + return this + var ref; +} - var ang1 = vectorAngle(1, 0, vx1, vy1); - var ang2 = vectorAngle(vx1, vy1, vx2, vy2); - if (sweepFlag === 0 && ang2 > 0) { - ang2 -= TAU; - } +// update passes +SPLOM.prototype.update = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - if (sweepFlag === 1 && ang2 < 0) { - ang2 += TAU; - } + if (!args.length) { return } - return [centerx, centery, ang1, ang2]; -}; + for (var i = 0; i < args.length; i++) { + this$1.updateItem(i, args[i]) + } -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; + // remove nulled passes + this.traces = this.traces.filter(Boolean) + + // FIXME: update passes independently + var passes = [] + var offset = 0 + for (var i$1 = 0; i$1 < this.traces.length; i$1++) { + var trace = this$1.traces[i$1] + var tracePasses = this$1.traces[i$1].passes + for (var j = 0; j < tracePasses.length; j++) { + passes.push(this$1.passes[tracePasses[j]]) + } + // save offset of passes + trace.passOffset = offset + offset += trace.passes.length + } - var curves = []; + (ref = this.scatter).update.apply(ref, passes) - if (rx === 0 || ry === 0) { - return []; - } + return this + var ref; +} - 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; +// update trace by index, not supposed to be called directly +SPLOM.prototype.updateItem = function (i, options) { + var this$1 = this; - if (pxp === 0 && pyp === 0) { - return []; - } + var ref = this; + var regl = ref.regl; - rx = Math.abs(rx); - ry = Math.abs(ry); + // remove pass if null + if (options === null) { + this.traces[i] = null + return this + } - var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + if (!options) { return this } + + var o = _$pick_212(options, { + data: 'data items columns rows values dimensions samples x', + snap: 'snap cluster', + size: 'sizes size radius', + color: 'colors color fill fill-color fillColor', + opacity: 'opacity alpha transparency opaque', + borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline', + borderColor: 'borderColors borderColor bordercolor stroke stroke-color strokeColor', + marker: 'markers marker shape', + range: 'range ranges databox dataBox', + viewport: 'viewport viewBox viewbox', + domain: 'domain domains area areas', + padding: 'pad padding paddings pads margin margins', + transpose: 'transpose transposed', + diagonal: 'diagonal diag showDiagonal', + upper: 'upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf', + lower: 'lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower' + }) - if (lambda > 1) { - rx *= Math.sqrt(lambda); - ry *= Math.sqrt(lambda); - } + // we provide regl buffer per-trace, since trace data can be changed + var trace = (this.traces[i] || (this.traces[i] = { + id: i, + buffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }), + color: 'black', + marker: null, + size: 12, + borderColor: 'transparent', + borderSize: 1, + viewport: _$parseRect_206([regl._gl.drawingBufferWidth, regl._gl.drawingBufferHeight]), + padding: [0, 0, 0, 0], + opacity: 1, + diagonal: true, + upper: true, + lower: true + })) + + + // save styles + if (o.color != null) { + trace.color = o.color + } + if (o.size != null) { + trace.size = o.size + } + if (o.marker != null) { + trace.marker = o.marker + } + if (o.borderColor != null) { + trace.borderColor = o.borderColor + } + if (o.borderSize != null) { + trace.borderSize = o.borderSize + } + if (o.opacity != null) { + trace.opacity = o.opacity + } + if (o.viewport) { + trace.viewport = _$parseRect_206(o.viewport) + } + if (o.diagonal != null) { trace.diagonal = o.diagonal } + if (o.upper != null) { trace.upper = o.upper } + if (o.lower != null) { trace.lower = o.lower } - 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]; + // put flattened data into buffer + if (o.data) { + trace.buffer(_$flattenVertexData_136(o.data)) + trace.columns = o.data.length + trace.count = o.data[0].length - var segments = Math.max(Math.ceil(Math.abs(ang2) / (TAU / 4)), 1); + // detect bounds per-column + trace.bounds = [] - ang2 /= segments; + for (var i$1 = 0; i$1 < trace.columns; i$1++) { + trace.bounds[i$1] = _$normalize_13(o.data[i$1], 1) + } + } - for (var i = 0; i < segments; i++) { - curves.push(approxUnitArc(ang1, ang2)); - ang1 += ang2; - } + // add proper range updating markers + var multirange + if (o.range) { + trace.range = o.range + multirange = trace.range && typeof trace.range[0] !== 'number' + } - return curves.map(function (curve) { - var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), - x1 = _mapToEllipse.x, - y1 = _mapToEllipse.y; + if (o.domain) { + trace.domain = o.domain + } + var multipadding = false + if (o.padding != null) { + // multiple paddings + if (Array.isArray(o.padding) && o.padding.length === trace.columns && typeof o.padding[o.padding.length - 1] === 'number') { + trace.padding = o.padding.map(getPad) + multipadding = true + } + // single padding + else { + trace.padding = getPad(o.padding) + } + } - var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), - x2 = _mapToEllipse2.x, - y2 = _mapToEllipse2.y; + // create passes + var m = trace.columns + var n = trace.count - var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), - x = _mapToEllipse3.x, - y = _mapToEllipse3.y; + var w = trace.viewport.width + var h = trace.viewport.height + var left = trace.viewport.x + var top = trace.viewport.y + var iw = w / m + var ih = h / m - return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; - }); -}; + trace.passes = [] -_$cjs_196.default = arcToBezier; -_$cjs_196 = _$cjs_196["default"]; -'use strict' - -var _$normalize_198 = __normalize_198 - -/* removed: var _$cjs_196 = require('svg-arc-to-cubic-bezier') */; - -function __normalize_198(path){ - // init state - var prev - var result = [] - var bezierX = 0 - var bezierY = 0 - var startX = 0 - var startY = 0 - var quadX = null - var quadY = null - var x = 0 - var y = 0 - - for (var i = 0, len = path.length; i < len; i++) { - var seg = path[i] - var command = seg[0] - - switch (command) { - case 'M': - startX = seg[1] - startY = seg[2] - break - case 'A': - var curves = _$cjs_196({ - px: x, - py: y, - cx: seg[6], - cy: seg[7], - rx: seg[1], - ry: seg[2], - xAxisRotation: seg[3], - largeArcFlag: seg[4], - sweepFlag: seg[5] - }) - - // null-curves - if (!curves.length) continue - - for (var j = 0, c; j < curves.length; j++) { - c = curves[j] - seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y] - if (j < curves.length - 1) result.push(seg) - } - - 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_198(x, y, quadX, quadY, seg[1], seg[2]) - break - case 'Q': - quadX = seg[1] - quadY = seg[2] - seg = __quadratic_198(x, y, seg[1], seg[2], seg[3], seg[4]) - break - case 'L': - seg = __line_198(x, y, seg[1], seg[2]) - break - case 'H': - seg = __line_198(x, y, seg[1], y) - break - case 'V': - seg = __line_198(x, y, x, seg[1]) - break - case 'Z': - seg = __line_198(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_198(x1, y1, x2, y2){ - return ['C', x1, y1, x2, y2, x2, y2] -} - -function __quadratic_198(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 - ] -} + for (var i$2 = 0; i$2 < m; i$2++) { + for (var j = 0; j < m; j++) { + if (!trace.diagonal && j === i$2) { continue } + if (!trace.upper && i$2 > j) { continue } + if (!trace.lower && i$2 < j) { continue } -'use strict' - -/* removed: var _$parse_149 = require('parse-svg-path') */; -/* removed: var _$absolutize_10 = require('abs-svg-path') */; -/* removed: var _$normalize_198 = require('normalize-svg-path') */; -/* removed: var _$isPath_135 = require('is-svg-path') */; -/* removed: var _$assert_15 = require('assert') */; - -var _$pathBounds_197 = pathBounds - - -function pathBounds(path) { - // ES6 string tpl call - if (Array.isArray(path) && path.length === 1 && typeof path[0] === 'string') path = path[0] - - // svg path string - if (typeof path === 'string') { - _$assert_15(_$isPath_135(path), 'String is not an SVG path.') - path = _$parse_149(path) - } - - _$assert_15(Array.isArray(path), 'Argument should be a string or an array of path segments.') - - path = _$absolutize_10(path) - path = _$normalize_198(path) - - if (!path.length) return [0, 0, 0, 0] - - var bounds = [Infinity, Infinity, -Infinity, -Infinity] - - for (var i = 0, l = path.length; i < l; i++) { - var points = path[i].slice(1) - - for (var j = 0; j < points.length; j += 2) { - if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0] - if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1] - if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0] - if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1] - } - } - - return bounds -} + var key = passId(trace.id, i$2, j) -var _$pathSdf_199 = {}; -(function (global){ -'use strict' - -/* removed: var _$pathBounds_197 = require('svg-path-bounds') */; -/* removed: var _$parse_149 = require('parse-svg-path') */; -/* removed: var _$drawSvgPath_71 = require('draw-svg-path') */; -/* removed: var _$isPath_135 = require('is-svg-path') */; -/* removed: var _$calcSDF_36 = require('bitmap-sdf') */; - -var canvas = document.createElement('canvas') -var ctx = canvas.getContext('2d') - - -_$pathSdf_199 = pathSdf - -function pathSdf (path, options) { - if (!_$isPath_135(path)) throw Error('Argument should be valid svg path string') - - if (!options) options = {} - - var w, h - if (options.shape) { - w = options.shape[0] - h = options.shape[1] - } - else { - w = canvas.width = options.w || options.width || 200 - h = canvas.height = options.h || options.height || 200 - } - var size = Math.min(w, h) - - var stroke = options.stroke || 0 - - var viewbox = options.viewbox || options.viewBox || _$pathBounds_197(path) - var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])] - var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2 - - //clear ctx - ctx.fillStyle = 'black' - ctx.fillRect(0, 0, w, h) - - ctx.fillStyle = 'white' - - if (stroke) { - if (typeof stroke != 'number') stroke = 1 - if (stroke > 0) { - ctx.strokeStyle = 'white' - } - else { - ctx.strokeStyle = 'black' - } - - ctx.lineWidth = Math.abs(stroke) - } - - ctx.translate(w * .5, h * .5) - ctx.scale(maxScale, maxScale) - - //if canvas svg paths api is available - if (global.Path2D) { - var path2d = new Path2D(path) - ctx.fill(path2d) - stroke && ctx.stroke(path2d) - } - //fallback to bezier-curves - else { - var segments = _$parse_149(path) - _$drawSvgPath_71(ctx, segments) - ctx.fill() - stroke && ctx.stroke() - } - - ctx.setTransform(1, 0, 0, 1, 0, 0); - - var data = _$calcSDF_36(ctx, { - cutoff: options.cutoff != null ? options.cutoff : .5, - radius: options.radius != null ? options.radius : size * .5 - }) - - return data -} + var pass = this$1.passes[key] || (this$1.passes[key] = {}) -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (o.data) { + if (o.transpose) { + pass.positions = { + x: {buffer: trace.buffer, offset: j, count: n, stride: m}, + y: {buffer: trace.buffer, offset: i$2, count: n, stride: m} + } + } + else { + pass.positions = { + x: {buffer: trace.buffer, offset: j * n, count: n}, + y: {buffer: trace.buffer, offset: i$2 * n, count: n} + } + } + pass.bounds = getBox(trace.bounds, i$2, j) + } -'use strict'; + if (o.domain || o.viewport || o.data) { + var pad = multipadding ? getBox(trace.padding, i$2, j) : trace.padding + if (trace.domain) { + var ref$1 = getBox(trace.domain, i$2, j); + var lox = ref$1[0]; + var loy = ref$1[1]; + var hix = ref$1[2]; + var hiy = ref$1[3]; + + pass.viewport = [ + left + lox * w + pad[0], + top + loy * h + pad[1], + left + hix * w - pad[2], + top + hiy * h - pad[3] + ] + } + // consider auto-domain equipartial + else { + pass.viewport = [ + left + j * iw + iw * pad[0], + top + i$2 * ih + ih * pad[1], + left + (j + 1) * iw - iw * pad[2], + top + (i$2 + 1) * ih - ih * pad[3] + ] + } + } -var _$gl2d_dashes_341 = { - solid: [1], - dot: [1, 1], - dash: [4, 1], - longdash: [8, 1], - dashdot: [4, 1, 1, 1], - longdashdot: [8, 1, 1, 1] -}; + if (o.color) { pass.color = trace.color } + if (o.size) { pass.size = trace.size } + if (o.marker) { pass.marker = trace.marker } + if (o.borderSize) { pass.borderSize = trace.borderSize } + if (o.borderColor) { pass.borderColor = trace.borderColor } + if (o.opacity) { pass.opacity = trace.opacity } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (o.range) { + pass.range = multirange ? getBox(trace.range, i$2, j) : trace.range || pass.bounds + } + trace.passes.push(key) + } + } -'use strict'; + return this +} -/* removed: var _$fastIsnumeric_78 = require('fast-isnumeric'); */; -/* removed: var _$normalize_58 = require('color-normalize'); */; -/* removed: var _$colorscale_254 = require('../components/colorscale'); */; -var colorDflt = _$attributes_238.defaultLine; +// draw all or passed passes +SPLOM.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; -var colorDfltRgba = _$normalize_58(colorDflt); -var opacityDflt = 1; + if (!args.length) { + this.scatter.draw() + } + else { + var idx = [] + for (var i = 0; i < args.length; i++) { + // draw(0, 2, 5) - draw traces + if (typeof args[i] === 'number' ) { + var ref = this$1.traces[args[i]]; + var passes = ref.passes; + var passOffset = ref.passOffset; + idx.push.apply(idx, _$newArray_15(passOffset, passOffset + passes.length)) + } + // draw([0, 1, 2 ...], [3, 4, 5]) - draw points + else if (args[i].length) { + var els = args[i] + var ref$1 = this$1.traces[i]; + var passes$1 = ref$1.passes; + var passOffset$1 = ref$1.passOffset; + passes$1 = passes$1.map(function (passId, i) { + idx[passOffset$1 + i] = els + }) + } + } + (ref$2 = this.scatter).draw.apply(ref$2, idx) + } -function calculateColor(colorIn, opacityIn) { - var colorOut = colorIn; - colorOut[3] *= opacityIn; - return colorOut; + return this + var ref$2; } -function validateColor(colorIn) { - if(_$fastIsnumeric_78(colorIn)) return colorDfltRgba; - var colorOut = _$normalize_58(colorIn); +// dispose resources +SPLOM.prototype.destroy = function () { + this.traces.forEach(function (trace) { + if (trace.buffer && trace.buffer.destroy) { trace.buffer.destroy() } + }) + this.traces = null + this.passes = null - return colorOut.length ? colorOut : colorDfltRgba; -} + this.scatter.destroy() -function validateOpacity(opacityIn) { - return _$fastIsnumeric_78(opacityIn) ? opacityIn : opacityDflt; + return this } -function formatColor(containerIn, opacityIn, len) { - var colorIn = containerIn.color, - isArrayColorIn = Array.isArray(colorIn), - isArrayOpacityIn = Array.isArray(opacityIn), - colorOut = []; - var sclFunc, getColor, getOpacity, colori, opacityi; +// return pass corresponding to trace i- j- square +function passId (trace, i, j) { + var id = (trace.id != null ? trace.id : trace) + var n = i + var m = j + var key = id << 16 | (n & 0xff) << 8 | m & 0xff - if(containerIn.colorscale !== undefined) { - sclFunc = _$colorscale_254.makeColorScaleFunc( - _$colorscale_254.extractScale( - containerIn.colorscale, - containerIn.cmin, - containerIn.cmax - ) - ); - } - else { - sclFunc = validateColor; - } + return key +} - if(isArrayColorIn) { - getColor = function(c, i) { - // FIXME: there is double work, considering that sclFunc does the opposite - return c[i] === undefined ? colorDfltRgba : _$normalize_58(sclFunc(c[i])); - }; - } - else getColor = validateColor; - if(isArrayOpacityIn) { - getOpacity = function(o, i) { - return o[i] === undefined ? opacityDflt : validateOpacity(o[i]); - }; - } - else getOpacity = validateOpacity; +// return bounding box corresponding to a pass +function getBox (items, i, j) { + var ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy + var iitem = items[i], jitem = items[j] - 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(_$normalize_58(colorIn), opacityIn); + if (iitem.length > 2) { + ilox = iitem[0] + ihix = iitem[2] + iloy = iitem[1] + ihiy = iitem[3] + } + else if (iitem.length) { + ilox = iloy = iitem[0] + ihix = ihiy = iitem[1] + } + else { + ilox = iitem.x + iloy = iitem.y + ihix = iitem.x + iitem.width + ihiy = iitem.y + iitem.height + } - return colorOut; + if (jitem.length > 2) { + jlox = jitem[0] + jhix = jitem[2] + jloy = jitem[1] + jhiy = jitem[3] + } + else if (jitem.length) { + jlox = jloy = jitem[0] + jhix = jhiy = jitem[1] + } + else { + jlox = jitem.x + jloy = jitem.y + jhix = jitem.x + jitem.width + jhiy = jitem.y + jitem.height + } + + return [ jlox, iloy, jhix, ihiy ] } -var _$formatColor_359 = formatColor; -var _$attributes_538 = {}; +function getPad (arg) { + if (typeof arg === 'number') { return [arg, arg, arg, arg] } + else if (arg.length === 2) { return [arg[0], arg[1], arg[0], arg[1]] } + else { + var box = _$parseRect_206(arg) + return [box.x, box.y, box.x + box.width, box.y + box.height] + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -98087,78 +102344,107 @@ var _$attributes_538 = {}; 'use strict'; -/* removed: var _$attributes_404 = require('../../plots/attributes'); */; -/* removed: var _$attributes_512 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_247 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_602 = require('../scattergl/attributes'); */; +var __cartesianIdRegex_607 = _$constants_475.idRegex; + +function makeAxesValObject(axLetter) { + return { + valType: 'info_array', + freeLength: true, + + editType: 'calc', + items: { + valType: 'subplotid', + regex: __cartesianIdRegex_607[axLetter], + editType: 'plot' + }, + + }; +} + +var _$attributes_607 = { + dimensions: { + _isLinkedToArray: 'dimension', -/* removed: var _$gl2d_dashes_341 = require('../../constants/gl2d_dashes'); */; -var __extendFlat_538 = _$extend_354.extendFlat; -var __overrideAll_538 = _$edit_types_392.overrideAll; + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + + }, + label: { + valType: 'string', + + editType: 'calc', + + }, + values: { + valType: 'data_array', + + editType: 'calc+clearAxisTypes', + + }, -var __scatterLineAttrs_538 = _$attributes_512.line, - __scatterMarkerAttrs_538 = _$attributes_512.marker, - scatterMarkerLineAttrs = __scatterMarkerAttrs_538.line; + // 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 -var __attrs_538 = _$attributes_538 = __overrideAll_538({ - x: _$attributes_512.x, - x0: _$attributes_512.x0, - dx: _$attributes_512.dx, - y: _$attributes_512.y, - y0: _$attributes_512.y0, - dy: _$attributes_512.dy, + // maybe more axis defaulting option e.g. `showgrid: false` - text: __extendFlat_538({}, _$attributes_512.text, { - - }), - mode: { - valType: 'flaglist', - flags: ['lines', 'markers'], - extras: ['none'], - - + editType: 'calc+clearAxisTypes' }, - line: { - color: __scatterLineAttrs_538.color, - width: __scatterLineAttrs_538.width, - dash: { - valType: 'enumerated', - values: Object.keys(_$gl2d_dashes_341), - dflt: 'solid', + + // mode: {}, (only 'markers' for now) + + text: _$attributes_602.text, + marker: _$attributes_602.marker, + + xaxes: makeAxesValObject('x'), + yaxes: makeAxesValObject('y'), + + diagonal: { + visible: { + valType: 'boolean', + dflt: true, + editType: 'calc', - } + }, + + // type: 'scattergl' | 'histogram' | 'box' | 'violin' + // ... + // more options + + editType: 'calc' }, - marker: __extendFlat_538({}, _$makeColorScaleAttributes_247('marker'), { - symbol: __scatterMarkerAttrs_538.symbol, - size: __scatterMarkerAttrs_538.size, - sizeref: __scatterMarkerAttrs_538.sizeref, - sizemin: __scatterMarkerAttrs_538.sizemin, - sizemode: __scatterMarkerAttrs_538.sizemode, - opacity: __scatterMarkerAttrs_538.opacity, - showscale: __scatterMarkerAttrs_538.showscale, - colorbar: __scatterMarkerAttrs_538.colorbar, - line: __extendFlat_538({}, _$makeColorScaleAttributes_247('marker.line'), { - width: scatterMarkerLineAttrs.width - }) - }), - connectgaps: _$attributes_512.connectgaps, - fill: _$attributes_512.fill, - fillcolor: _$attributes_512.fillcolor, - hoveron: _$attributes_512.hoveron, + showupperhalf: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + + }, + showlowerhalf: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + + }, selected: { - marker: _$attributes_512.selected.marker + marker: _$attributes_602.selected.marker, + editType: 'calc' }, unselected: { - marker: _$attributes_512.unselected.marker + marker: _$attributes_602.unselected.marker, + editType: 'calc' }, - opacity: _$attributes_404.opacity - -}, 'calc', 'nested'); - -__attrs_538.x.editType = __attrs_538.y.editType = __attrs_538.x0.editType = __attrs_538.y0.editType = 'calc+clearAxisTypes'; + opacity: _$attributes_602.opacity +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -98170,1175 +102456,797 @@ __attrs_538.x.editType = __attrs_538.y.editType = __attrs_538.x0.editType = __at 'use strict'; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$registry_451 = require('../../registry'); */; - -/* removed: var _$attributes_538 = require('./attributes'); */; -/* removed: var _$constants_518 = require('../scatter/constants'); */; -/* removed: var _$subtypes_534 = require('../scatter/subtypes'); */; -/* removed: var _$handleXYDefaults_536 = require('../scatter/xy_defaults'); */; -/* removed: var _$markerDefaults_530 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_525 = require('../scatter/line_defaults'); */; -/* removed: var _$fillColorDefaults_521 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$Line2D_235 = require('regl-line2d'); */; -var _$supplyDefaults_539 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_363.coerce(traceIn, traceOut, _$attributes_538, attr, dflt); - } +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$prepareRegl_438 = require('../../lib/prepare_regl'); */; +var __getModuleCalcData_608 = _$get_data_498.getModuleCalcData; +/* removed: var _$cartesian_481 = require('../../plots/cartesian'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; - var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false; - var isBubble = _$subtypes_534.isBubble(traceIn); +var __SPLOM_608 = 'splom'; - var len = _$handleXYDefaults_536(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; - } +function __plot_608(gd) { + var fullLayout = gd._fullLayout; + var _module = _$registry_514.getModule(__SPLOM_608); + var splomCalcData = __getModuleCalcData_608(gd.calcdata, _module)[0]; - coerce('text'); - coerce('mode', len < _$constants_518.PTS_LINESONLY ? 'lines+markers' : 'lines'); + _$prepareRegl_438(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']); - if(_$subtypes_534.hasLines(traceOut)) { - coerce('connectgaps'); - _$lineDefaults_525(traceIn, traceOut, defaultColor, layout, coerce); + if(fullLayout._hasOnlyLargeSploms) { + drawGrid(gd); } - var dfltHoverOn = []; - - if(_$subtypes_534.hasMarkers(traceOut)) { - _$markerDefaults_530(traceIn, traceOut, defaultColor, layout, coerce); - coerce('marker.line.width', isOpen || isBubble ? 1 : 0); - dfltHoverOn.push('points'); - } + _module.plot(gd, {}, splomCalcData); +} - coerce('fill'); - if(traceOut.fill !== 'none') { - _$fillColorDefaults_521(traceIn, traceOut, defaultColor, coerce); - } +function drag(gd) { + var cd = gd.calcdata; + var fullLayout = gd._fullLayout; - if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { - dfltHoverOn.push('fills'); + if(fullLayout._hasOnlyLargeSploms) { + drawGrid(gd); } - coerce('hoveron', dfltHoverOn.join('+') || 'points'); - - var errorBarsSupplyDefaults = _$registry_451.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - - _$lib_363.coerceSelectionMarkerOpacity(traceOut, coerce); -}; - -var _$scattergl_540 = {}; -(function (global){ -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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(var i = 0; i < cd.length; i++) { + var cd0 = cd[i][0]; + var trace = cd0.trace; + var scene = cd0.t._scene; -'use strict'; + if(trace.type === 'splom' && scene && scene.matrix) { + dragOne(gd, trace, scene); + } + } +} -/* removed: var _$regl_175 = require('regl'); */; -/* removed: var _$Scatter_173 = require('regl-scatter2d'); */; -/* removed: var _$createLine_172 = require('regl-line2d'); */; -/* removed: var _$Error2D_171 = require('regl-error2d'); */; -/* removed: var _$KDTree_136 = require('kdgrass'); */; -/* removed: var _$normalize_58 = require('color-normalize'); */; -/* removed: var _$pathSdf_199 = require('svg-path-sdf'); */; -/* removed: var _$newArray_14 = require('array-range'); */; - -/* removed: var _$registry_451 = require('../../registry'); */; -/* removed: var _$lib_363 = require('../../lib'); */; -/* removed: var _$axis_ids_410 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$drawing_264 = require('../../components/drawing'); */; -/* removed: var _$formatColor_359 = require('../../lib/gl_format_color'); */; - -/* removed: var _$subtypes_534 = require('../scatter/subtypes'); */; -var calcMarkerSize = _$calc_513.calcMarkerSize; -var calcAxisExpansion = _$calc_513.calcAxisExpansion; -/* removed: var _$calcMarkerColorscale_517 = require('../scatter/colorscale_calc'); */; -/* removed: var _$makeBubbleSizeFn_529 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$linkTraces_528 = require('../scatter/link_traces'); */; -/* removed: var _$getTraceColor_522 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_520 = require('../scatter/fill_hover_text'); */; - -/* removed: var _$gl2d_dashes_341 = require('../../constants/gl2d_dashes'); */; -var BADNUM = _$numerical_343.BADNUM; -var SYMBOL_SDF_SIZE = 200; -var SYMBOL_SIZE = 20; -var SYMBOL_STROKE = SYMBOL_SIZE / 20; -var SYMBOL_SDF = {}; -var SYMBOL_SVG_CIRCLE = _$drawing_264.symbolFuncs[0](SYMBOL_SIZE * 0.05); -var TOO_MANY_POINTS = 1e5; -var DOT_RE = /-dot/; -var OPEN_RE = /-open/; +function dragOne(gd, trace, scene) { + var dimensions = trace.dimensions; + var visibleLength = scene.matrixOptions.data.length; + var ranges = new Array(visibleLength); -function calc(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = _$axis_ids_410.getFromId(gd, trace.xaxis); - var ya = _$axis_ids_410.getFromId(gd, trace.yaxis); - var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; - var count = trace._length; - var count2 = count * 2; - var stash = {}; - var i, xx, yy; + for(var i = 0, k = 0; i < dimensions.length; i++) { + if(dimensions[i].visible) { + var rng = ranges[k] = new Array(4); - var x = xa.makeCalcdata(trace, 'x'); - var y = ya.makeCalcdata(trace, 'y'); + var xa = _$axis_ids_473.getFromId(gd, trace._diag[i][0]); + if(xa) { + rng[0] = xa.r2l(xa.range[0]); + rng[2] = xa.r2l(xa.range[1]); + } - // we need hi-precision for scatter2d, - // regl-scatter2d uses NaNs for bad/missing values - var positions = new Array(count2); - for(i = 0; i < count; i++) { - xx = x[i]; - yy = y[i]; - positions[i * 2] = xx === BADNUM ? NaN : xx; - positions[i * 2 + 1] = yy === BADNUM ? NaN : yy; - } + var ya = _$axis_ids_473.getFromId(gd, trace._diag[i][1]); + if(ya) { + rng[1] = ya.r2l(ya.range[0]); + rng[3] = ya.r2l(ya.range[1]); + } - if(xa.type === 'log') { - for(i = 0; i < count2; i += 2) { - positions[i] = xa.c2l(positions[i]); - } - } - if(ya.type === 'log') { - for(i = 1; i < count2; i += 2) { - positions[i] = ya.c2l(positions[i]); + k++; } } - // we don't build a tree for log axes since it takes long to convert log2px - // and it is also - if(xa.type !== 'log' && ya.type !== 'log') { - // FIXME: delegate this to webworker - stash.tree = _$KDTree_136(positions, 512); + if(scene.selectBatch) { + scene.matrix.update({ranges: ranges}, {ranges: ranges}); + scene.matrix.draw(scene.unselectBatch, scene.selectBatch); } else { - var ids = stash.ids = new Array(count); - for(i = 0; i < count; i++) { - ids[i] = i; - } + scene.matrix.update({ranges: ranges}); + scene.matrix.draw(); } +} - // create scene options and scene - _$calcMarkerColorscale_517(trace); - var options = sceneOptions(gd, subplot, trace, positions); - var markerOptions = options.marker; - var scene = sceneUpdate(gd, subplot); - var ppad; +function drawGrid(gd) { + var fullLayout = gd._fullLayout; + var regl = fullLayout._glcanvas.data()[0].regl; + var splomGrid = fullLayout._splomGrid; - // Re-use SVG scatter axis expansion routine except - // for graph with very large number of points where it - // performs poorly. - // In big data case, fake Axes.expand outputs with data bounds, - // and an average size for array marker.size inputs. - if(count < TOO_MANY_POINTS) { - ppad = calcMarkerSize(trace, count); - } else if(markerOptions) { - ppad = 2 * (markerOptions.sizeAvg || Math.max(markerOptions.size, 3)); + if(!splomGrid) { + splomGrid = fullLayout._splomGrid = _$Line2D_235(regl); } - calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); - // set flags to create scene renderers - if(options.fill && !scene.fill2d) scene.fill2d = true; - if(options.marker && !scene.scatter2d) scene.scatter2d = true; - if(options.line && !scene.line2d) scene.line2d = true; - if((options.errorX || options.errorY) && !scene.error2d) scene.error2d = true; - - // save scene options batch - scene.lineOptions.push(options.line); - scene.errorXOptions.push(options.errorX); - scene.errorYOptions.push(options.errorY); - scene.fillOptions.push(options.fill); - scene.markerOptions.push(options.marker); - scene.selectedOptions.push(options.selected); - scene.unselectedOptions.push(options.unselected); - scene.count++; - - // stash scene ref - stash.scene = scene; - stash.index = scene.count - 1; - stash.x = x; - stash.y = y; - stash.positions = positions; - stash.count = count; - - gd.firstscatter = false; - return [{x: false, y: false, t: stash, trace: trace}]; + splomGrid.update(makeGridData(gd)); + splomGrid.draw(); } -// create scene options -function sceneOptions(gd, subplot, trace, positions) { +function makeGridData(gd) { var fullLayout = gd._fullLayout; - var count = positions.length / 2; - var markerOpts = trace.marker; - var i; - - var hasLines, hasErrorX, hasErrorY, hasMarkers, hasFill; - - if(trace.visible !== true) { - hasLines = false; - hasErrorX = false; - hasErrorY = false; - hasMarkers = false; - hasFill = false; - } else { - hasLines = _$subtypes_534.hasLines(trace) && positions.length > 1; - hasErrorX = trace.error_x && trace.error_x.visible === true; - hasErrorY = trace.error_y && trace.error_y.visible === true; - hasMarkers = _$subtypes_534.hasMarkers(trace); - hasFill = !!trace.fill && trace.fill !== 'none'; - } - - var lineOptions, markerOptions, fillOptions; - var errorXOptions, errorYOptions; - var selectedOptions, unselectedOptions; - var linePositions; + var gs = fullLayout._size; + var fullView = [0, 0, fullLayout.width, fullLayout.height]; + var lookup = {}; + var k; - if(hasErrorX || hasErrorY) { - var calcFromTrace = _$registry_451.getComponentMethod('errorbars', 'calcFromTrace'); - var errorVals = calcFromTrace(trace, fullLayout); + function push(prefix, ax, x0, x1, y0, y1) { + var lcolor = ax[prefix + 'color']; + var lwidth = ax[prefix + 'width']; + var key = String(lcolor + lwidth); - if(hasErrorX) { - errorXOptions = makeErrorOptions('x', trace.error_x, errorVals); - } - if(hasErrorY) { - errorYOptions = makeErrorOptions('y', trace.error_y, errorVals); + if(key in lookup) { + lookup[key].data.push(NaN, NaN, x0, x1, y0, y1); + } else { + lookup[key] = { + data: [x0, x1, y0, y1], + join: 'rect', + thickness: lwidth, + color: lcolor, + viewport: fullView, + range: fullView, + overlay: false + }; } } - if(hasLines) { - lineOptions = {}; - lineOptions.thickness = trace.line.width; - lineOptions.color = trace.line.color; - lineOptions.opacity = trace.opacity; - lineOptions.overlay = true; + for(k in fullLayout._splomSubplots) { + var sp = fullLayout._plots[k]; + var xa = sp.xaxis; + var ya = sp.yaxis; + var xVals = xa._vals; + var yVals = ya._vals; + // ya.l2p assumes top-to-bottom coordinate system (a la SVG), + // we need to compute bottom-to-top offsets and slopes: + var yOffset = gs.b + ya.domain[0] * gs.h; + var ym = -ya._m; + var yb = -ym * ya.r2l(ya.range[0], ya.calendar); + var x, y; - var dashes = (_$gl2d_dashes_341[trace.line.dash] || [1]).slice(); - for(i = 0; i < dashes.length; ++i) dashes[i] *= lineOptions.thickness; - lineOptions.dashes = dashes; - - if(trace.line.shape === 'hv') { - linePositions = []; - for(i = 0; i < Math.floor(positions.length / 2) - 1; i++) { - if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - } - else { - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 1]); - linePositions.push(positions[i * 2 + 2]); - linePositions.push(positions[i * 2 + 1]); - } - } - linePositions.push(positions[positions.length - 2]); - linePositions.push(positions[positions.length - 1]); - } - else if(trace.line.shape === 'vh') { - linePositions = []; - for(i = 0; i < Math.floor(positions.length / 2) - 1; i++) { - if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - } - else { - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 1]); - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 3]); - } + if(xa.showgrid) { + for(k = 0; k < xVals.length; k++) { + x = xa._offset + xa.l2p(xVals[k].x); + push('grid', xa, x, yOffset, x, yOffset + ya._length); } - linePositions.push(positions[positions.length - 2]); - linePositions.push(positions[positions.length - 1]); } - else { - linePositions = positions; + if(showZeroLine(xa)) { + x = xa._offset + xa.l2p(0); + push('zeroline', xa, x, yOffset, x, yOffset + ya._length); } - - // If we have data with gaps, we ought to use rect joins - // FIXME: get rid of this - var hasNaN = false; - for(i = 0; i < linePositions.length; i++) { - if(isNaN(linePositions[i])) { - hasNaN = true; - break; + if(ya.showgrid) { + for(k = 0; k < yVals.length; k++) { + y = yOffset + yb + ym * yVals[k].x; + push('grid', ya, xa._offset, y, xa._offset + xa._length, y); } } - - lineOptions.join = (hasNaN || linePositions.length > TOO_MANY_POINTS) ? 'rect' : - hasMarkers ? 'rect' : 'round'; - - // fill gaps - if(hasNaN && trace.connectgaps) { - var lastX = linePositions[0], lastY = linePositions[1]; - for(i = 0; i < linePositions.length; i += 2) { - if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { - linePositions[i] = lastX; - linePositions[i + 1] = lastY; - } - else { - lastX = linePositions[i]; - lastY = linePositions[i + 1]; - } - } + if(showZeroLine(ya)) { + y = yOffset + yb + 0; + push('zeroline', ya, xa._offset, y, xa._offset + xa._length, y); } - - lineOptions.positions = linePositions; - } - - if(hasFill) { - fillOptions = {}; - fillOptions.fill = trace.fillcolor; - fillOptions.thickness = 0; - fillOptions.closed = true; } - if(hasMarkers) { - markerOptions = makeMarkerOptions(markerOpts); - selectedOptions = makeSelectedOptions(trace.selected, markerOpts); - unselectedOptions = makeSelectedOptions(trace.unselected, markerOpts); - markerOptions.positions = positions; + var gridBatches = []; + for(k in lookup) { + gridBatches.push(lookup[k]); } - function makeErrorOptions(axLetter, errorOpts, vals) { - var options = {}; - options.positions = positions; - - var ax = _$axis_ids_410.getFromId(gd, trace[axLetter + 'axis']); - var errors = options.errors = new Float64Array(4 * count); - var pOffset = {x: 0, y: 1}[axLetter]; - var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter]; - - for(var i = 0, p = 0; i < count; i++, p += 4) { - errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0; - errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0; - errors[p + eOffset[2]] = 0; - errors[p + eOffset[3]] = 0; - } - - if(errorOpts.copy_ystyle) { - errorOpts = trace.error_y; - } + return gridBatches; +} - options.capSize = errorOpts.width * 2; - options.lineWidth = errorOpts.thickness; - options.color = errorOpts.color; +// just like in Axes.doTicks but without the loop over traces +function showZeroLine(ax) { + var rng = _$lib_425.simpleMap(ax.range, ax.r2l); + var p0 = ax.l2p(0); - return options; - } + return ( + ax.zeroline && + ax._vals && ax._vals.length && + (rng[0] * rng[1] <= 0) && + (ax.type === 'linear' || ax.type === '-') && + ((p0 > 1 && p0 < ax._length - 1) || !ax.showline) + ); +} - function makeSelectedOptions(selected, markerOpts) { - var options = {}; +function clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; - if(!selected) return options; + var hadSplom, hasSplom; + var i; - if(selected.marker && selected.marker.symbol) { - options = makeMarkerOptions(_$lib_363.extendFlat({}, markerOpts, selected.marker)); + for(i = 0; i < oldModules.length; i++) { + if(oldModules[i].name === 'splom') { + hadSplom = true; + break; } - - // shortcut simple selection logic - else { - options = {}; - if(selected.marker.size) options.sizes = selected.marker.size; - if(selected.marker.color) options.colors = selected.marker.color; - if(selected.marker.opacity !== undefined) options.opacity = selected.marker.opacity; + } + for(i = 0; i < newModules.length; i++) { + if(newModules[i].name === 'splom') { + hasSplom = true; + break; } - - return options; } - function makeMarkerOptions(markerOpts) { - var markerOptions = {}; - var i; - - var multiSymbol = Array.isArray(markerOpts.symbol); - var multiColor = _$lib_363.isArrayOrTypedArray(markerOpts.color); - var multiLineColor = _$lib_363.isArrayOrTypedArray(markerOpts.line.color); - var multiOpacity = _$lib_363.isArrayOrTypedArray(markerOpts.opacity); - var multiSize = _$lib_363.isArrayOrTypedArray(markerOpts.size); - var multiLineWidth = _$lib_363.isArrayOrTypedArray(markerOpts.line.width); - - var isOpen; - if(!multiSymbol) isOpen = OPEN_RE.test(markerOpts.symbol); - - // prepare colors - if(multiSymbol || multiColor || multiLineColor || multiOpacity) { - markerOptions.colors = new Array(count); - markerOptions.borderColors = new Array(count); - var colors = _$formatColor_359(markerOpts, markerOpts.opacity, count); - var borderColors = _$formatColor_359(markerOpts.line, markerOpts.opacity, count); - - if(!Array.isArray(borderColors[0])) { - var borderColor = borderColors; - borderColors = Array(count); - for(i = 0; i < count; i++) { - borderColors[i] = borderColor; - } - } - if(!Array.isArray(colors[0])) { - var color = colors; - colors = Array(count); - for(i = 0; i < count; i++) { - colors[i] = color; - } - } - - markerOptions.colors = colors; - markerOptions.borderColors = borderColors; + if(hadSplom && !hasSplom) { + for(i = 0; i < oldCalcdata.length; i++) { + var cd0 = oldCalcdata[i][0]; + var trace = cd0.trace; + var scene = cd0.t._scene; - for(i = 0; i < count; i++) { - if(multiSymbol) { - var symbol = markerOpts.symbol[i]; - isOpen = OPEN_RE.test(symbol); - } - if(isOpen) { - borderColors[i] = colors[i].slice(); - colors[i] = colors[i].slice(); - colors[i][3] = 0; - } + if(trace.type === 'splom' && scene && scene.matrix) { + scene.matrix.destroy(); + cd0.t._scene = null; } - - markerOptions.opacity = trace.opacity; } - else { - if(isOpen) { - markerOptions.color = _$normalize_58(markerOpts.color, 'uint8'); - markerOptions.color[3] = 0; - markerOptions.borderColor = _$normalize_58(markerOpts.color, 'uint8'); - } else { - markerOptions.color = _$normalize_58(markerOpts.color, 'uint8'); - markerOptions.borderColor = _$normalize_58(markerOpts.line.color, 'uint8'); - } + } - markerOptions.opacity = trace.opacity * markerOpts.opacity; - } + if(oldFullLayout._splomGrid && + (!newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms)) { + oldFullLayout._splomGrid.destroy(); + oldFullLayout._splomGrid = null; + } - // prepare symbols - if(multiSymbol) { - markerOptions.markers = new Array(count); - for(i = 0; i < count; i++) { - markerOptions.markers[i] = getSymbolSdf(markerOpts.symbol[i]); - } - } else { - markerOptions.marker = getSymbolSdf(markerOpts.symbol); - } + _$cartesian_481.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); +} - // prepare sizes - var markerSizeFunc = _$makeBubbleSizeFn_529(trace); - var s; +var _$base_plot_608 = { + name: __SPLOM_608, + attr: _$cartesian_481.attr, + attrRegex: _$cartesian_481.attrRegex, + layoutAttributes: _$cartesian_481.layoutAttributes, + supplyLayoutDefaults: _$cartesian_481.supplyLayoutDefaults, + drawFramework: _$cartesian_481.drawFramework, + plot: __plot_608, + drag: drag, + clean: clean, + updateFx: _$cartesian_481.updateFx, + toSVG: _$cartesian_481.toSVG +}; - if(multiSize || multiLineWidth) { - var sizes = markerOptions.sizes = new Array(count); - var borderSizes = markerOptions.borderSizes = new Array(count); - var sizeTotal = 0; - var sizeAvg; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(multiSize) { - for(i = 0; i < count; i++) { - sizes[i] = markerSizeFunc(markerOpts.size[i]); - sizeTotal += sizes[i]; - } - sizeAvg = sizeTotal / count; - } else { - s = markerSizeFunc(markerOpts.size); - for(i = 0; i < count; i++) { - sizes[i] = s; - } - } +'use strict'; - // See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798 - if(multiLineWidth) { - for(i = 0; i < count; i++) { - borderSizes[i] = markerSizeFunc(markerOpts.line.width[i]); - } - } else { - s = markerSizeFunc(markerOpts.line.width); - for(i = 0; i < count; i++) { - borderSizes[i] = s; - } - } +/* removed: var _$lib_425 = require('../../lib'); */; - markerOptions.sizeAvg = sizeAvg; - } else { - markerOptions.size = markerSizeFunc(markerOpts && markerOpts.size || 10); - markerOptions.borderSizes = markerSizeFunc(markerOpts.line.width); - } +/* removed: var _$attributes_607 = require('./attributes'); */; +/* removed: var _$subtypes_598 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_594 = require('../scatter/marker_defaults'); */; +var OPEN_RE = /-open/; - return markerOptions; +var _$supplyDefaults_609 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_425.coerce(traceIn, traceOut, _$attributes_607, attr, dflt); } - return { - line: lineOptions, - marker: markerOptions, - errorX: errorXOptions, - errorY: errorYOptions, - fill: fillOptions, - selected: selectedOptions, - unselected: unselectedOptions - }; -} - -// make sure scene exists on subplot, return it -function sceneUpdate(gd, subplot) { - var scene = subplot._scene; - var fullLayout = gd._fullLayout; - - var reset = { - // 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: [], - selectedOptions: [], - unselectedOptions: [], - errorXOptions: [], - errorYOptions: [] - }; - - var first = { - selectBatch: null, - unselectBatch: null, - // regl- component stubs, initialized in dirty plot call - fill2d: false, - scatter2d: false, - error2d: false, - line2d: false, - select2d: null - }; + var dimLength = handleDimensionsDefaults(traceIn, traceOut); - if(!subplot._scene) { - scene = subplot._scene = _$lib_363.extendFlat({}, reset, first); + var showDiag = coerce('diagonal.visible'); + var showUpper = coerce('showupperhalf'); + var showLower = coerce('showlowerhalf'); - // apply new option to all regl components (used on drag) - scene.update = function update(opt) { - var opts = new Array(scene.count); - for(var i = 0; i < scene.count; i++) { - opts[i] = opt; - } + if(!dimLength || (!showDiag && !showUpper && !showLower)) { + traceOut.visible = false; + return; + } - 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); + coerce('text'); - scene.draw(); - }; + _$markerDefaults_594(traceIn, traceOut, defaultColor, layout, coerce); - // draw traces in proper order - scene.draw = function draw() { - var i; - for(i = 0; i < scene.count; i++) { - if(scene.fill2d && scene.fillOptions[i]) { - // must do all fills first - scene.fill2d.draw(i); - } - } - for(i = 0; i < scene.count; i++) { - if(scene.line2d && scene.lineOptions[i]) { - scene.line2d.draw(i); - } - if(scene.error2d && scene.errorXOptions[i]) { - scene.error2d.draw(i); - } - if(scene.error2d && scene.errorYOptions[i]) { - scene.error2d.draw(i + scene.count); - } - if(scene.scatter2d && scene.markerOptions[i] && (!scene.selectBatch || !scene.selectBatch[i])) { - // traces in no-selection mode - scene.scatter2d.draw(i); - } - } + var isOpen = OPEN_RE.test(traceOut.marker.symbol); + var isBubble = _$subtypes_598.isBubble(traceOut); + coerce('marker.line.width', isOpen || isBubble ? 1 : 0); - // draw traces in selection mode - if(scene.scatter2d && scene.select2d && scene.selectBatch) { - scene.select2d.draw(scene.selectBatch); - scene.scatter2d.draw(scene.unselectBatch); - } + __handleAxisDefaults_609(traceIn, traceOut, layout, coerce); - scene.dirty = false; - }; + _$lib_425.coerceSelectionMarkerOpacity(traceOut, coerce); +}; - // make sure canvas is clear - scene.clear = function clear() { - var vpSize = fullLayout._size; - var width = fullLayout.width; - var height = fullLayout.height; - var xaxis = subplot.xaxis; - var yaxis = subplot.yaxis; - var vp, gl, regl; - - // multisubplot case - if(xaxis && xaxis.domain && yaxis && yaxis.domain) { - vp = [ - vpSize.l + xaxis.domain[0] * vpSize.w, - vpSize.b + yaxis.domain[0] * vpSize.h, - (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, - (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h - ]; - } - else { - vp = [ - vpSize.l, - vpSize.b, - (width - vpSize.r), - (height - vpSize.t) - ]; - } +function handleDimensionsDefaults(traceIn, traceOut) { + var dimensionsIn = traceIn.dimensions; + if(!Array.isArray(dimensionsIn)) return 0; - if(scene.select2d) { - regl = scene.select2d.regl; - gl = regl._gl; - gl.enable(gl.SCISSOR_TEST); - gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } + var dimLength = dimensionsIn.length; + var commonLength = 0; + var dimensionsOut = traceOut.dimensions = new Array(dimLength); + var dimIn; + var dimOut; + var i; - if(scene.scatter2d) { - regl = scene.scatter2d.regl; - gl = regl._gl; - gl.enable(gl.SCISSOR_TEST); - gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - }; + function coerce(attr, dflt) { + return _$lib_425.coerce(dimIn, dimOut, _$attributes_607.dimensions, attr, dflt); + } - // remove selection - scene.clearSelect = function clearSelect() { - if(!scene.selectBatch) return; - scene.selectBatch = null; - scene.unselectBatch = null; - scene.scatter2d.update(scene.markerOptions); - scene.clear(); - scene.draw(); - }; + for(i = 0; i < dimLength; i++) { + dimIn = dimensionsIn[i]; + dimOut = dimensionsOut[i] = {}; - // remove scene resources - scene.destroy = function destroy() { - if(scene.fill2d) scene.fill2d.destroy(); - if(scene.scatter2d) scene.scatter2d.destroy(); - if(scene.error2d) scene.error2d.destroy(); - if(scene.line2d) scene.line2d.destroy(); - if(scene.select2d) scene.select2d.destroy(); + // coerce label even if dimensions may be `visible: false`, + // to fill in axis title defaults + coerce('label'); - scene.lineOptions = null; - scene.fillOptions = null; - scene.markerOptions = null; - scene.selectedOptions = null; - scene.unselectedOptions = null; - scene.errorXOptions = null; - scene.errorYOptions = null; - scene.selectBatch = null; - scene.unselectBatch = null; + // wait until plot step to filter out visible false dimensions + var visible = coerce('visible'); + if(!visible) continue; - // 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; - }; + var values = coerce('values'); + if(!values || !values.length) { + dimOut.visible = false; + continue; + } + + commonLength = Math.max(commonLength, values.length); + dimOut._index = i; } - // In case if we have scene from the last calc - reset data - if(!scene.dirty) { - _$lib_363.extendFlat(scene, reset); + for(i = 0; i < dimLength; i++) { + dimOut = dimensionsOut[i]; + if(dimOut.visible) dimOut._length = commonLength; } - return scene; + traceOut._commonLength = commonLength; + + return dimensionsOut.length; } -function getSymbolSdf(symbol) { - if(symbol === 'circle') return null; +function __handleAxisDefaults_609(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 symbolPath, symbolSdf; - var symbolNumber = _$drawing_264.symbolNumber(symbol); - var symbolFunc = _$drawing_264.symbolFuncs[symbolNumber % 100]; - var symbolNoDot = !!_$drawing_264.symbolNoDot[symbolNumber % 100]; - var symbolNoFill = !!_$drawing_264.symbolNoFill[symbolNumber % 100]; + // N.B. one less x axis AND one less y axis when hiding one half and the diagonal + var axDfltLength = !showDiag && (!showUpper || !showLower) ? dimLength - 1 : dimLength; - var isDot = DOT_RE.test(symbol); + var xaxes = coerce('xaxes', fillAxisIdArray('x', axDfltLength)); + var yaxes = coerce('yaxes', fillAxisIdArray('y', axDfltLength)); - // get symbol sdf from cache or generate it - if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol]; + // to avoid costly indexOf + traceOut._xaxes = arrayToHashObject(xaxes); + traceOut._yaxes = arrayToHashObject(yaxes); - if(isDot && !symbolNoDot) { - symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE; - } - else { - symbolPath = symbolFunc(SYMBOL_SIZE); + // allow users to under-specify number of axes + var axLength = Math.min(axDfltLength, xaxes.length, yaxes.length); + + // fill in splom subplot keys + for(i = 0; i < axLength; i++) { + for(j = 0; j < axLength; j++) { + var id = [xaxes[i] + yaxes[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; + } + } } - symbolSdf = _$pathSdf_199(symbolPath, { - w: SYMBOL_SDF_SIZE, - h: SYMBOL_SDF_SIZE, - viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE], - stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE - }); - SYMBOL_SDF[symbol] = symbolSdf; + // 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); - return symbolSdf || null; + // cases where showDiag and showLower or showUpper are false + // no special treatment as the xaxes and yaxes items no longer match + // the dimensions items 1-to-1 + var xShift = !showDiag && !showLower ? -1 : 0; + var yShift = !showDiag && !showUpper ? -1 : 0; + + for(i = 0; i < dimLength; i++) { + var dim = dimensions[i]; + var xa = xaxes[i + xShift]; + var ya = yaxes[i + yShift]; + + fillAxisStash(layout, xa, dim); + fillAxisStash(layout, ya, dim); + + // note that some the entries here may be undefined + diag[i] = [xa, ya]; + } } -function plot(gd, subplot, cdata) { - if(!cdata.length) return; +function fillAxisIdArray(axLetter, len) { + var out = new Array(len); - var fullLayout = gd._fullLayout; - var scene = cdata[0][0].t.scene; - var dragmode = fullLayout.dragmode; + for(var i = 0; i < len; i++) { + out[i] = axLetter + (i ? i + 1 : ''); + } - // we may have more subplots than initialized data due to Axes.getSubplots method - if(!scene) return; + return out; +} - var vpSize = fullLayout._size; - var width = fullLayout.width; - var height = fullLayout.height; +function fillAxisStash(layout, axId, dim) { + if(!axId) return; - // make sure proper regl instances are created - fullLayout._glcanvas.each(function(d) { - if(d.regl || d.pick) return; - d.regl = _$regl_175({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - extensions: ['ANGLE_instanced_arrays', 'OES_element_index_uint'], - pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio - }); - }); + var axLetter = axId.charAt(0); + var stash = layout._splomAxes[axLetter]; - var regl = fullLayout._glcanvas.data()[0].regl; + if(!(axId in stash)) { + stash[axId] = (dim || {}).label || ''; + } +} - // that is needed for fills - _$linkTraces_528(gd, subplot, cdata); +function arrayToHashObject(arr) { + var obj = {}; + for(var i = 0; i < arr.length; i++) { + obj[arr[i]] = 1; + } + return obj; +} - if(scene.dirty) { - // make sure scenes are created - if(scene.error2d === true) { - scene.error2d = _$Error2D_171(regl); - } - if(scene.line2d === true) { - scene.line2d = _$createLine_172(regl); - } - if(scene.scatter2d === true) { - scene.scatter2d = _$Scatter_173(regl); - } - if(scene.fill2d === true) { - scene.fill2d = _$createLine_172(regl); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // update main marker options - if(scene.line2d) { - 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 - if(scene.fill2d) { - scene.fillOptions = scene.fillOptions.map(function(fillOptions, i) { - var cdscatter = cdata[i]; - if(!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return null; - var cd = cdscatter[0]; - var trace = cd.trace; - var stash = cd.t; - var lineOptions = scene.lineOptions[i]; - var last, j; +'use strict'; - var pos = [], srcPos = (lineOptions && lineOptions.positions) || stash.positions; +/* removed: var _$SPLOM_238 = require('regl-splom'); */; +/* removed: var _$newArray_15 = require('array-range'); */; - if(trace.fill === 'tozeroy') { - pos = [srcPos[0], 0]; - pos = pos.concat(srcPos); - pos.push(srcPos[srcPos.length - 2]); - pos.push(0); - } - else if(trace.fill === 'tozerox') { - pos = [0, srcPos[1]]; - pos = pos.concat(srcPos); - pos.push(0); - pos.push(srcPos[srcPos.length - 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; +/* removed: var _$registry_514 = require('../../registry'); */; +/* removed: var _$grid_347 = require('../../components/grid'); */; +/* removed: var _$lib_425 = require('../../lib'); */; +/* removed: var _$axis_ids_473 = require('../../plots/cartesian/axis_ids'); */; - if(nextTrace) { - var nextOptions = scene.lineOptions[i + 1]; +/* removed: var _$subtypes_598 = require('../scatter/subtypes'); */; +var __calcMarkerSize_610 = _$calc_577.calcMarkerSize; +var __calcAxisExpansion_610 = _$calc_577.calcAxisExpansion; +/* removed: var _$calcMarkerColorscale_581 = require('../scatter/colorscale_calc'); */; +var __convertMarkerSelection_610 = _$convert_604.convertMarkerSelection; +var __convertMarkerStyle_610 = _$convert_604.convertMarkerStyle; +var __calcHover_610 = _$scattergl_606.calcHover; - if(nextOptions) { - var nextPos = nextOptions.positions; - if(trace.fill === 'tonexty') { - pos = srcPos.slice(); +var __BADNUM_610 = _$numerical_404.BADNUM; +var __TOO_MANY_POINTS_610 = _$constants_603.TOO_MANY_POINTS; - for(i = Math.floor(nextPos.length / 2); i--;) { - var xx = nextPos[i * 2], yy = nextPos[i * 2 + 1]; - if(isNaN(xx) || isNaN(yy)) continue; - pos.push(xx); - pos.push(yy); - } - fillOptions.fill = nextTrace.fillcolor; - } - } - } - } +function __calc_610(gd, trace) { + var dimensions = trace.dimensions; + var commonLength = trace._commonLength; + var stash = {}; + var opts = {}; + // 'c' for calculated, 'l' for linear, + // only differ here for log axes, pass ldata to createMatrix as 'data' + var cdata = opts.cdata = []; + var ldata = opts.data = []; + var i, k, dim; + + for(i = 0; i < dimensions.length; i++) { + dim = dimensions[i]; + + if(dim.visible) { + var axId = trace._diag[i][0] || trace._diag[i][1]; + var ax = _$axis_ids_473.getFromId(gd, axId); + if(ax) { + var ccol = makeCalcdata(ax, trace, dim); + var lcol = ax.type === 'log' ? _$lib_425.simpleMap(ccol, ax.c2l) : ccol; + cdata.push(ccol); + ldata.push(lcol); + } + } + } - // detect prev trace positions to exclude from current fill - if(trace._prevtrace && trace._prevtrace.fill === 'tonext') { - var prevLinePos = scene.lineOptions[i - 1].positions; + _$calcMarkerColorscale_581(trace); + _$lib_425.extendFlat(opts, __convertMarkerStyle_610(trace)); - // 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; - } - } + var visibleLength = cdata.length; + var hasTooManyPoints = (visibleLength * commonLength) > __TOO_MANY_POINTS_610; - pos = pos.concat(prevLinePos); - fillOptions.hole = hole; - } + for(i = 0, k = 0; i < dimensions.length; i++) { + dim = dimensions[i]; - fillOptions.opacity = trace.opacity; - fillOptions.positions = pos; + if(dim.visible) { + var xa = _$axis_ids_473.getFromId(gd, trace._diag[i][0]) || {}; + var ya = _$axis_ids_473.getFromId(gd, trace._diag[i][1]) || {}; - return fillOptions; - }); + // Re-use SVG scatter axis expansion routine except + // for graph with very large number of points where it + // performs poorly. + // In big data case, fake Axes.expand outputs with data bounds, + // and an average size for array marker.size inputs. + var ppad; + if(hasTooManyPoints) { + ppad = 2 * (opts.sizeAvg || Math.max(opts.size, 3)); + } else { + ppad = __calcMarkerSize_610(trace, commonLength); + } - scene.fill2d.update(scene.fillOptions); + __calcAxisExpansion_610(gd, trace, xa, ya, cdata[k], cdata[k], ppad); + k++; } } - var selectMode = dragmode === 'lasso' || dragmode === 'select'; + var scene = stash._scene = __sceneUpdate_610(gd, stash); + if(!scene.matrix) scene.matrix = true; + scene.matrixOptions = opts; - // provide viewport and range - var vpRange = cdata.map(function(cdscatter) { - if(!cdscatter || !cdscatter[0] || !cdscatter[0].trace) return; - var cd = cdscatter[0]; - var trace = cd.trace; - var stash = cd.t; - var id = stash.index; - var x = stash.x; - var y = stash.y; + scene.selectedOptions = __convertMarkerSelection_610(trace, trace.selected); + scene.unselectedOptions = __convertMarkerSelection_610(trace, trace.unselected); - var xaxis = subplot.xaxis || _$axis_ids_410.getFromId(gd, trace.xaxis || 'x'); - var yaxis = subplot.yaxis || _$axis_ids_410.getFromId(gd, trace.yaxis || 'y'); - var i; + return [{x: false, y: false, t: stash, trace: trace}]; +} - var range = [ - (xaxis._rl || xaxis.range)[0], - (yaxis._rl || yaxis.range)[0], - (xaxis._rl || xaxis.range)[1], - (yaxis._rl || yaxis.range)[1] - ]; +function makeCalcdata(ax, trace, dim) { + // call makeCalcdata with fake input + var ccol = ax.makeCalcdata({ + v: dim.values, + vcalendar: trace.calendar + }, 'v'); - var viewport = [ - vpSize.l + xaxis.domain[0] * vpSize.w, - vpSize.b + yaxis.domain[0] * vpSize.h, - (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, - (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h - ]; + for(var i = 0; i < ccol.length; i++) { + ccol[i] = ccol[i] === __BADNUM_610 ? NaN : ccol[i]; + } - if(trace.selectedpoints || selectMode) { - if(!selectMode) selectMode = true; + return ccol; +} - if(!scene.selectBatch) scene.selectBatch = []; - if(!scene.unselectBatch) scene.unselectBatch = []; +function __sceneUpdate_610(gd, stash) { + var scene = stash._scene; - // regenerate scene batch, if traces number changed during selection - if(trace.selectedpoints) { - scene.selectBatch[id] = trace.selectedpoints; + var reset = { + dirty: true + }; - var selPts = trace.selectedpoints; - var selDict = {}; - for(i = 0; i < selPts.length; i++) { - selDict[selPts[i]] = true; - } - var unselPts = []; - for(i = 0; i < stash.count; i++) { - if(!selDict[i]) unselPts.push(i); - } - scene.unselectBatch[id] = unselPts; + var first = { + selectBatch: null, + unselectBatch: null, + matrix: false, + select: null + }; + + if(!scene) { + scene = stash._scene = _$lib_425.extendFlat({}, reset, first); + + scene.draw = function draw() { + // draw traces in selection mode + if(scene.matrix && scene.selectBatch) { + scene.matrix.draw(scene.unselectBatch, scene.selectBatch); } - // precalculate px coords since we are not going to pan during select - var xpx = new Array(stash.count); - var ypx = new Array(stash.count); - for(i = 0; i < stash.count; i++) { - xpx[i] = xaxis.c2p(x[i]); - ypx[i] = yaxis.c2p(y[i]); + else if(scene.matrix) { + scene.matrix.draw(); } - stash.xpx = xpx; - stash.ypx = ypx; - } - else { - stash.xpx = stash.ypx = null; - } - return trace.visible ? { - viewport: viewport, - range: range - } : null; - }); + scene.dirty = false; + }; - if(selectMode) { - // create select2d - if(!scene.select2d) { - // create scatter instance by cloning scatter2d - scene.select2d = _$Scatter_173(fullLayout._glcanvas.data()[1].regl, {clone: scene.scatter2d}); - } + // remove scene resources + scene.destroy = function destroy() { + if(scene.matrix) scene.matrix.destroy(); - if(scene.scatter2d && scene.selectBatch && scene.selectBatch.length) { - // update only traces with selection - scene.scatter2d.update(scene.unselectedOptions.map(function(opts, i) { - return scene.selectBatch[i] ? opts : null; - })); - } + scene.matrixOptions = null; + scene.selectBatch = null; + scene.unselectBatch = null; - if(scene.select2d) { - scene.select2d.update(scene.markerOptions); - scene.select2d.update(scene.selectedOptions); - } + stash._scene = null; + }; } - // uploat 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); + // In case if we have scene from the last calc - reset data + if(!scene.dirty) { + _$lib_425.extendFlat(scene, reset); } - scene.draw(); + return scene; +} - return; +function __plot_610(gd, _, splomCalcData) { + if(!splomCalcData.length) return; + + for(var i = 0; i < splomCalcData.length; i++) { + __plotOne_610(gd, splomCalcData[i][0]); + } } -function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var stash = cd[0].t; - var trace = cd[0].trace; - var xa = pointData.xa; - var ya = pointData.ya; - var x = stash.x; - var y = stash.y; - var xpx = xa.c2p(xval); - var ypx = ya.c2p(yval); - var maxDistance = pointData.distance; - var ids; +function __plotOne_610(gd, cd0) { + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var trace = cd0.trace; + var stash = cd0.t; + var scene = stash._scene; + var matrixOpts = scene.matrixOptions; + var cdata = matrixOpts.cdata; + var regl = fullLayout._glcanvas.data()[0].regl; + var dragmode = fullLayout.dragmode; + var xa, ya; + var i, j, k; - // FIXME: make sure this is a proper way to calc search radius - if(stash.tree) { - var xl = xa.p2c(xpx - maxDistance); - var xr = xa.p2c(xpx + maxDistance); - var yl = ya.p2c(ypx - maxDistance); - var yr = ya.p2c(ypx + maxDistance); + if(cdata.length === 0) return; - if(hovermode === 'x') { - ids = stash.tree.range( - Math.min(xl, xr), Math.min(ya._rl[0], ya._rl[1]), - Math.max(xl, xr), Math.max(ya._rl[0], ya._rl[1]) - ); - } - else { - ids = stash.tree.range( - Math.min(xl, xr), Math.min(yl, yr), - Math.max(xl, xr), Math.max(yl, yr) - ); - } - } - else if(stash.ids) { - ids = stash.ids; - } - else return [pointData]; + // augment options with proper upper/lower halves + // regl-splom's default grid starts from bottom-left + matrixOpts.lower = trace.showupperhalf; + matrixOpts.upper = trace.showlowerhalf; + matrixOpts.diagonal = trace.diagonal.visible; - // pick the id closest to the point - // note that point possibly may not be found - var minDist = maxDistance; - var id, ptx, pty, i, dx, dy, dist, dxy; + var dimensions = trace.dimensions; + var visibleLength = cdata.length; + var viewOpts = {}; + viewOpts.ranges = new Array(visibleLength); + viewOpts.domains = new Array(visibleLength); - if(hovermode === 'x') { - for(i = 0; i < ids.length; i++) { - ptx = x[ids[i]]; - dx = Math.abs(xa.c2p(ptx) - xpx); - if(dx < minDist) { - minDist = dx; - dy = ya.c2p(y[ids[i]]) - ypx; - dxy = Math.sqrt(dx * dx + dy * dy); - id = ids[i]; + for(i = 0, k = 0; i < dimensions.length; i++) { + if(trace.dimensions[i].visible) { + var rng = viewOpts.ranges[k] = new Array(4); + var dmn = viewOpts.domains[k] = new Array(4); + + xa = _$axis_ids_473.getFromId(gd, trace._diag[i][0]); + if(xa) { + rng[0] = xa._rl[0]; + rng[2] = xa._rl[1]; + dmn[0] = xa.domain[0]; + dmn[2] = xa.domain[1]; } - } - } - else { - for(i = 0; i < ids.length; i++) { - ptx = x[ids[i]]; - pty = y[ids[i]]; - dx = xa.c2p(ptx) - xpx; - dy = ya.c2p(pty) - ypx; - dist = Math.sqrt(dx * dx + dy * dy); - if(dist < minDist) { - minDist = dxy = dist; - id = ids[i]; + ya = _$axis_ids_473.getFromId(gd, trace._diag[i][1]); + if(ya) { + rng[1] = ya._rl[0]; + rng[3] = ya._rl[1]; + dmn[1] = ya.domain[0]; + dmn[3] = ya.domain[1]; } + + k++; } } - pointData.index = id; + viewOpts.viewport = [gs.l, gs.b, gs.w + gs.l, gs.h + gs.b]; - if(id === undefined) return [pointData]; + if(scene.matrix === true) { + scene.matrix = _$SPLOM_238(regl); + } - // the closest data point - var di = { - pointNumber: id, - x: x[id], - y: y[id] - }; + var selectMode = dragmode === 'lasso' || dragmode === 'select' || !!trace.selectedpoints; + scene.selectBatch = null; + scene.unselectBatch = null; - // that is single-item arrays_to_calcdata excerpt, since we are doing it for a single point and we don't have to do it beforehead for 1e6 points - di.tx = Array.isArray(trace.text) ? trace.text[id] : trace.text; - di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext; - di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata; - di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition; + if(selectMode) { + var commonLength = trace._commonLength; - var font = trace.textfont; - if(font) { - di.ts = Array.isArray(font.size) ? font.size[id] : font.size; - di.tc = Array.isArray(font.color) ? font.color[id] : font.color; - di.tf = Array.isArray(font.family) ? font.family[id] : font.family; - } + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } - var marker = trace.marker; - if(marker) { - di.ms = _$lib_363.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size; - di.mo = _$lib_363.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity; - di.mx = Array.isArray(marker.symbol) ? marker.symbol[id] : marker.symbol; - di.mc = _$lib_363.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color; - } + // regenerate scene batch, if traces number changed during selection + if(trace.selectedpoints) { + scene.selectBatch = trace.selectedpoints; - var line = marker && marker.line; - if(line) { - di.mlc = Array.isArray(line.color) ? line.color[id] : line.color; - di.mlw = _$lib_363.isArrayOrTypedArray(line.width) ? line.width[id] : line.width; - } + var selPts = trace.selectedpoints; + var selDict = {}; + for(i = 0; i < selPts.length; i++) { + selDict[selPts[i]] = true; + } + var unselPts = []; + for(i = 0; i < commonLength; i++) { + if(!selDict[i]) unselPts.push(i); + } + scene.unselectBatch = unselPts; + } - var grad = marker && marker.gradient; - if(grad && grad.type !== 'none') { - di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type; - di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color; - } + // precalculate px coords since we are not going to pan during select + var xpx = stash.xpx = new Array(visibleLength); + var ypx = stash.ypx = new Array(visibleLength); - var xp = xa.c2p(di.x, true); - var yp = ya.c2p(di.y, true); - var rad = di.mrc || 1; + for(i = 0, k = 0; i < dimensions.length; i++) { + if(trace.dimensions[i].visible) { + xa = _$axis_ids_473.getFromId(gd, trace._diag[i][0]); + if(xa) { + xpx[k] = new Array(commonLength); + for(j = 0; j < commonLength; j++) { + xpx[k][j] = xa.c2p(cdata[k][j]); + } + } - var hoverlabel = trace.hoverlabel; + ya = _$axis_ids_473.getFromId(gd, trace._diag[i][1]); + if(ya) { + ypx[k] = new Array(commonLength); + for(j = 0; j < commonLength; j++) { + ypx[k][j] = ya.c2p(cdata[k][j]); + } + } - if(hoverlabel) { - di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor; - di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor; - di.hts = Array.isArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size; - di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color; - di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family; - di.hnl = Array.isArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength; + k++; + } + } + + if(scene.selectBatch) { + scene.matrix.update(matrixOpts, matrixOpts); + scene.matrix.update(scene.unselectedOptions, scene.selectedOptions); + scene.matrix.update(viewOpts, viewOpts); + } + else { + // delete selection pass + scene.matrix.update(viewOpts, null); + } } - var hoverinfo = trace.hoverinfo; - if(hoverinfo) { - di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo; + else { + scene.matrix.update(matrixOpts); + scene.matrix.update(viewOpts); + stash.xpx = stash.ypx = null; } - var fakeCd = {}; - fakeCd[pointData.index] = di; + scene.draw(); +} - _$lib_363.extendFlat(pointData, { - color: _$getTraceColor_522(trace, di), +function __hoverPoints_610(pointData, xval, yval) { + var cd = pointData.cd; + var trace = cd[0].trace; + var stash = cd[0].t; + var scene = stash._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; - x0: xp - rad, - x1: xp + rad, - xLabelVal: di.x, + var xi = getDimIndex(trace, xa); + var yi = getDimIndex(trace, ya); + if(xi === false || yi === false) return [pointData]; - y0: yp - rad, - y1: yp + rad, - yLabelVal: di.y, + var x = cdata[xi]; + var y = cdata[yi]; - cd: fakeCd, - distance: minDist, - spikeDistance: dxy - }); + var id, dxy; + var minDist = maxDistance; - if(di.htx) pointData.text = di.htx; - else if(di.tx) pointData.text = di.tx; - else if(trace.text) pointData.text = trace.text; + 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; - _$fillHoverText_520(di, trace, pointData); - _$registry_451.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + if(id === undefined) return [pointData]; + + __calcHover_610(pointData, x, y, trace); return [pointData]; } -function selectPoints(searchInfo, polygon) { +function __selectPoints_610(searchInfo, polygon) { var cd = searchInfo.cd; - var selection = []; var trace = cd[0].trace; var stash = cd[0].t; - var x = stash.x; - var y = stash.y; - var scene = stash.scene; + var scene = stash._scene; + var cdata = scene.matrixOptions.cdata; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; if(!scene) return selection; - var hasOnlyLines = (!_$subtypes_534.hasMarkers(trace) && !_$subtypes_534.hasText(trace)); + var hasOnlyLines = (!_$subtypes_598.hasMarkers(trace) && !_$subtypes_598.hasText(trace)); if(trace.visible !== true || hasOnlyLines) return selection; + var xi = getDimIndex(trace, xa); + var yi = 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]; + // degenerate polygon does not enable selection // filter out points by visible scatter ones var els = null; var unels = null; - var i; if(polygon !== false && !polygon.degenerate) { els = [], unels = []; - for(i = 0; i < stash.count; i++) { - if(polygon.contains([stash.xpx[i], stash.ypx[i]])) { + for(i = 0; i < x.length; i++) { + if(polygon.contains([xpx[i], ypx[i]])) { els.push(i); selection.push({ pointNumber: i, @@ -99351,7 +103259,7 @@ function selectPoints(searchInfo, polygon) { } } } else { - unels = _$newArray_14(stash.count); + unels = _$newArray_15(stash.count); } // make sure selectBatch is created @@ -99360,57 +103268,90 @@ function selectPoints(searchInfo, polygon) { scene.unselectBatch = []; } - if(!scene.selectBatch[stash.index]) { + if(!scene.selectBatch) { // enter every trace select mode for(i = 0; i < scene.count; i++) { - scene.selectBatch[i] = []; - scene.unselectBatch[i] = []; + scene.selectBatch = []; + scene.unselectBatch = []; } // we should turn scatter2d into unselected once we have any points selected - scene.scatter2d.update(scene.unselectedOptions); + scene.matrix.update(scene.unselectedOptions, scene.selectedOptions); } - scene.selectBatch[stash.index] = els; - scene.unselectBatch[stash.index] = unels; + scene.selectBatch = els; + scene.unselectBatch = unels; + return selection; } -function style(gd, cd) { - if(cd) { - var stash = cd[0].t; - var scene = stash.scene; - scene.clear(); +function __style_610(gd, cds) { + if(!cds) return; + + var fullLayout = gd._fullLayout; + var cd0 = cds[0]; + var scene0 = cd0[0].t._scene; + scene0.matrix.regl.clear({color: true, depth: true}); + + if(fullLayout._splomGrid) { + fullLayout._splomGrid.draw(); + } + + for(var i = 0; i < cds.length; i++) { + var scene = cds[i][0].t._scene; scene.draw(); } + + // redraw all subplot with scattergl traces, + // as we cleared the whole canvas above + if(fullLayout._has('cartesian')) { + for(var k in fullLayout._plots) { + var sp = fullLayout._plots[k]; + if(sp._scene) sp._scene.draw(); + } + } +} + +function getDimIndex(trace, ax) { + var axId = ax._id; + var axLetter = axId.charAt(0); + var ind = {x: 0, y: 1}[axLetter]; + var dimensions = trace.dimensions; + + for(var i = 0, k = 0; i < dimensions.length; i++) { + if(dimensions[i].visible) { + if(trace._diag[i][ind] === axId) return k; + k++; + } + } + return false; } -_$scattergl_540 = { +var _$splom_610 = { moduleType: 'trace', - name: 'scattergl', - basePlotModule: _$cartesian_418, - categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'markerColorscale', 'showLegend', 'scatter-like'], + name: 'splom', - attributes: _$attributes_538, - supplyDefaults: _$supplyDefaults_539, - cleanData: _$cleanData_515, - colorbar: _$colorbar_516, - calc: calc, - plot: plot, - hoverPoints: hoverPoints, - style: style, - selectPoints: selectPoints, + basePlotModule: _$base_plot_608, + categories: ['gl', 'regl', 'cartesian', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], - sceneOptions: sceneOptions, - sceneUpdate: sceneUpdate, + attributes: _$attributes_607, + supplyDefaults: _$supplyDefaults_609, + + calc: __calc_610, + plot: __plot_610, + hoverPoints: __hoverPoints_610, + selectPoints: __selectPoints_610, + style: __style_610, meta: { - } }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +// splom traces use the 'grid' component to generate their axes, +// register it here +_$registry_514.register(_$grid_347); + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -99421,7 +103362,7 @@ _$scattergl_540 = { 'use strict'; -var _$scattergl_9 = _$scattergl_540; +var _$splom_10 = _$splom_610; /** * Copyright 2012-2018, Plotly, Inc. @@ -99437,6 +103378,7 @@ var _$scattergl_9 = _$scattergl_540; _$core_4.register([ _$scattergl_9, + _$splom_10, _$pointcloud_8, _$heatmapgl_5, _$contourgl_3, diff --git a/dist/plotly-gl2d.min.js b/dist/plotly-gl2d.min.js index c1b4b927e5e..33cd132527d 100644 --- a/dist/plotly-gl2d.min.js +++ b/dist/plotly-gl2d.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (gl2d - minified) v1.35.2 +* plotly.js (gl2d - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){var t={exports:{}};!function(){var e={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},a=this.document;function i(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(a)try{n(a.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var l=this.Element.prototype,s=l.setAttribute,u=l.setAttributeNS,c=this.CSSStyleDeclaration.prototype,f=c.setProperty;l.setAttribute=function(t,e){s.call(this,t,e+"")},l.setAttributeNS=function(t,e,r){u.call(this,t,e,r+"")},c.setProperty=function(t,e,r){f.call(this,t,e+"",r)}}function h(t,e){return te?1:t>=e?0:NaN}function d(t){return null===t?NaN:+t}function p(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n>>1;t(e[i],r)<0?n=i+1:a=i}return n},right:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n>>1;t(e[i],r)>0?a=i:n=i+1}return n}}}e.ascending=h,e.descending=function(t,e){return et?1:e>=t?0:NaN},e.min=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++an&&(r=n)}else{for(;++a=n){r=n;break}for(;++an&&(r=n)}return r},e.max=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++ar&&(r=n)}else{for(;++a=n){r=n;break}for(;++ar&&(r=n)}return r},e.extent=function(t,e){var r,n,a,i=-1,o=t.length;if(1===arguments.length){for(;++i=n){r=a=n;break}for(;++in&&(r=n),a=n){r=a=n;break}for(;++in&&(r=n),a1)return o/(s-1)},e.deviation=function(){var t=e.variance.apply(this,arguments);return t?Math.sqrt(t):t};var v=g(h);function m(t){return t.length}e.bisectLeft=v.left,e.bisect=e.bisectRight=v.right,e.bisector=function(t){return g(1===t.length?function(e,r){return h(t(e),r)}:t)},e.shuffle=function(t,e,r){(i=arguments.length)<3&&(r=t.length,i<2&&(e=0));for(var n,a,i=r-e;i;)a=Math.random()*i--|0,n=t[i+e],t[i+e]=t[a+e],t[a+e]=n;return t},e.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},e.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],a=new Array(r<0?0:r);e=0;)for(e=(n=t[a]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}e.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,a=[],i=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=i,e*=i,(r*=i)<0)for(;(n=t+r*++o)>e;)a.push(n/i);else for(;(n=t+r*++o)=a.length)return r?r.call(n,i):t?i.sort(t):i;for(var s,u,c,f,h=-1,d=i.length,p=a[l++],g=new b;++h=a.length)return e;var n=[],o=i[r++];return e.forEach(function(e,a){n.push({key:e,values:t(a,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(e.map,t,0),0)},n.key=function(t){return a.push(t),n},n.sortKeys=function(t){return i[a.length-1]=t,n},n.sortValues=function(e){return t=e,n},n.rollup=function(t){return r=t,n},n},e.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},e.event=null,e.requote=function(t){return t.replace(U,"\\$&")};var U=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,V={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function H(t){return V(t,W),t}var q=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},X=function(t,e){var r=t.matches||t[D(t,"matchesSelector")];return(X=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(q=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,X=Sizzle.matchesSelector),e.selection=function(){return e.select(a.documentElement)};var W=e.selection.prototype=[];function Y(t){return"function"==typeof t?t:function(){return q(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}W.select=function(t){var e,r,n,a,i=[];t=Y(t);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),Q.hasOwnProperty(r)?{space:Q[r],local:t}:t}},W.attr=function(t,r){if(arguments.length<2){if("string"==typeof t){var n=this.node();return(t=e.ns.qualify(t)).local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(r in t)this.each($(r,t[r]));return this}return this.each($(t,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,a=-1;if(e=r.classList){for(;++a=0;)(r=n[a])&&(i&&i!==r.nextSibling&&i.parentNode.insertBefore(r,i),i=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=h);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(t=t.slice(0,o));var s=pt.get(t);function u(){var e=this[i];e&&(this.removeEventListener(t,e,e.$),delete this[i])}return s&&(t=s,l=vt),o?r?function(){var e=l(r,n(arguments));u.call(this),this.addEventListener(t,this[i]=e,e.$=a),e._=r}:u:r?P:function(){var r,n=new RegExp("^__on([^.]+)"+e.requote(t)+"$");for(var a in this)if(r=a.match(n)){var i=this[a];this.removeEventListener(r[1],i,i.$),delete this[a]}}}e.selection.enter=ft,e.selection.enter.prototype=ht,ht.append=W.append,ht.empty=W.empty,ht.node=W.node,ht.call=W.call,ht.size=W.size,ht.select=function(t){for(var e,r,n,a,i,o=[],l=-1,s=this.length;++l=n&&(n=e+1);!(o=l[n])&&++n0?1:t<0?-1:0}function Rt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function Dt(t){return t>1?0:t<-1?Tt:Math.acos(t)}function It(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function Pt(t){return((t=Math.exp(t))+1/t)/2}function Ft(t){return(t=Math.sin(t/2))*t}var zt=Math.SQRT2;e.interpolateZoom=function(t,e){var r,n,a=t[0],i=t[1],o=t[2],l=e[0],s=e[1],u=e[2],c=l-a,f=s-i,h=c*c+f*f;if(h0&&(t=t.transition().duration(g)),t.call(w.event)}function E(){u&&u.domain(s.range().map(function(t){return(t-h.x)/h.k}).map(s.invert)),f&&f.domain(c.range().map(function(t){return(t-h.y)/h.k}).map(c.invert))}function C(t){v++||t({type:"zoomstart"})}function S(t){E(),t({type:"zoom",scale:h.k,translate:[h.x,h.y]})}function L(t){--v||(t({type:"zoomend"}),r=null)}function O(){var t=this,r=_.of(t,arguments),n=0,a=e.select(o(t)).on(y,function(){n=1,T(e.mouse(t),i),S(r)}).on(x,function(){a.on(y,null).on(x,null),l(n),L(r)}),i=A(e.mouse(t)),l=xt(t);ll.call(t),C(r)}function R(){var t,r=this,n=_.of(r,arguments),a={},i=0,o=".zoom-"+e.event.changedTouches[0].identifier,s="touchmove"+o,u="touchend"+o,c=[],f=e.select(r),d=xt(r);function p(){var n=e.touches(r);return t=h.k,n.forEach(function(t){t.identifier in a&&(a[t.identifier]=A(t))}),n}function g(){var t=e.event.target;e.select(t).on(s,v).on(u,y),c.push(t);for(var n=e.event.changedTouches,o=0,f=n.length;o1){m=d[0];var x=d[1],b=m[0]-x[0],_=m[1]-x[1];i=b*b+_*_}}function v(){var o,s,u,c,f=e.touches(r);ll.call(r);for(var h=0,d=f.length;h360?t-=360:t<0&&(t+=360),t<60?n+(a-n)*t/60:t<180?a:t<240?n+(a-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(a=r<=.5?r*(1+e):r+e-r*e),new ie(i(t+120),i(t),i(t-120))}function Gt(t,r,n){return this instanceof Gt?(this.h=+t,this.c=+r,void(this.l=+n)):arguments.length<2?t instanceof Gt?new Gt(t.h,t.c,t.l):ee(t instanceof Yt?t.l:(t=he((t=e.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new Gt(t,r,n)}Ht.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,this.l/t)},Ht.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,t*this.l)},Ht.rgb=function(){return qt(this.h,this.s,this.l)},e.hcl=Gt;var Xt=Gt.prototype=new Ut;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Yt(r,Math.cos(t*=St)*e,Math.sin(t)*e)}function Yt(t,e,r){return this instanceof Yt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Yt?new Yt(t.l,t.a,t.b):t instanceof Gt?Wt(t.h,t.c,t.l):he((t=ie(t)).r,t.g,t.b):new Yt(t,e,r)}Xt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Xt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Xt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},e.lab=Yt;var Zt=18,Jt=.95047,Qt=1,$t=1.08883,Kt=Yt.prototype=new Ut;function te(t,e,r){var n=(t+16)/116,a=n+e/500,i=n-r/200;return new ie(ae(3.2404542*(a=re(a)*Jt)-1.5371385*(n=re(n)*Qt)-.4985314*(i=re(i)*$t)),ae(-.969266*a+1.8760108*n+.041556*i),ae(.0556434*a-.2040259*n+1.0572252*i))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ae(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ie(t,e,r){return this instanceof ie?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ie?new ie(t.r,t.g,t.b):ce(""+t,ie,qt):new ie(t,e,r)}function oe(t){return new ie(t>>16,t>>8&255,255&t)}function le(t){return oe(t)+""}Kt.brighter=function(t){return new Yt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},Kt.darker=function(t){return new Yt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},Kt.rgb=function(){return te(this.l,this.a,this.b)},e.rgb=ie;var se=ie.prototype=new Ut;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,a,i,o=0,l=0,s=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(a=n[2].split(","),n[1]){case"hsl":return r(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return e(pe(a[0]),pe(a[1]),pe(a[2]))}return(i=ge.get(t))?e(i.r,i.g,i.b):(null==t||"#"!==t.charAt(0)||isNaN(i=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===t.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),e(o,l,s))}function fe(t,e,r){var n,a,i=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),n=t==o?(e-r)/l+(e0&&s<1?0:n),new Vt(n,a,s)}function he(t,e,r){var n=ne((.4124564*(t=de(t))+.3575761*(e=de(e))+.1804375*(r=de(r)))/Jt),a=ne((.2126729*t+.7151522*e+.072175*r)/Qt);return Yt(116*a-16,500*(n-a),200*(a-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function de(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function pe(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}se.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,a=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=a.call(o,u)}catch(t){return void l.error.call(o,t)}l.load.call(o,t)}else l.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(t)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=f:u.onreadystatechange=function(){u.readyState>3&&f()},u.onprogress=function(t){var r=e.event;e.event=t;try{l.progress.call(o,u)}finally{e.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return a=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(e,n,a){if(2===arguments.length&&"function"==typeof n&&(a=n,n=null),u.open(e,t,!0),null==r||"accept"in s||(s.accept=r+",*/*"),u.setRequestHeader)for(var i in s)u.setRequestHeader(i,s[i]);return null!=r&&u.overrideMimeType&&u.overrideMimeType(r),null!=c&&(u.responseType=c),null!=a&&o.on("error",a).on("load",function(t){a(null,t)}),l.beforesend.call(o,u),u.send(null==n?null:n),o},o.abort=function(){return u.abort(),o},e.rebind(o,l,"on"),null==i?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(i))}ge.forEach(function(t,e){ge.set(t,oe(e))}),e.functor=ve,e.xhr=me(O),e.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function a(t,r,n){arguments.length<3&&(n=r,r=null);var a=ye(t,e,null==r?i:o(r),n);return a.row=function(t){return arguments.length?a.response(null==(r=t)?i:o(t)):r},a}function i(t){return a.parse(t.responseText)}function o(t){return function(e){return a.parse(e.responseText,t)}}function l(e){return e.map(s).join(t)}function s(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return a.parse=function(t,e){var r;return a.parseRows(t,function(t,n){if(r)return r(t,n-1);var a=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(a(t),r)}:a})},a.parseRows=function(t,e){var r,a,i={},o={},l=[],s=t.length,u=0,c=0;function f(){if(u>=s)return o;if(a)return a=!1,i;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),_e=0):(_e=1,Ae(Te))}function ke(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Ee(){for(var t,e=xe,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});e.formatPrefix=function(t,r){var n=0;return(t=+t)&&(t<0&&(t*=-1),r&&(t=e.round(t,Ce(t,r))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Se[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Oe=e.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,r){return(t=e.round(t,Ce(t,r))).toFixed(Math.max(0,Math.min(20,Ce(t*(1+1e-15),r))))}});function Re(t){return t+""}var De=e.time={},Ie=Date;function Pe(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Pe.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(){Fe.setUTCDate.apply(this._,arguments)},setDay:function(){Fe.setUTCDay.apply(this._,arguments)},setFullYear:function(){Fe.setUTCFullYear.apply(this._,arguments)},setHours:function(){Fe.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Fe.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Fe.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Fe.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Fe.setUTCSeconds.apply(this._,arguments)},setTime:function(){Fe.setTime.apply(this._,arguments)}};var Fe=Date.prototype;function ze(t,e,r){function n(e){var r=t(e),n=i(r,1);return e-r1)for(;o68?1900:2e3),r+a[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ar(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,a=y(e)%60;return r+Ve(n,"0",2)+Ve(a,"0",2)}function ir(t,e,r){Ue.lastIndex=0;var n=Ue.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&l>0&&(s+l+1>e&&(l=Math.max(1,e-s)),i.push(t.substring(r-=l,r+l)),!((s+=l+1)>e));)l=a[o=(o+1)%a.length];return i.reverse().join(n)}:O;return function(t){var n=Le.exec(t),a=n[1]||" ",l=n[2]||">",s=n[3]||"-",u=n[4]||"",c=n[5],f=+n[6],h=n[7],d=n[8],p=n[9],g=1,v="",m="",y=!1,x=!0;switch(d&&(d=+d.substring(1)),(c||"0"===a&&"="===l)&&(c=a="0",l="="),p){case"n":h=!0,p="g";break;case"%":g=100,m="%",p="f";break;case"p":g=100,m="%",p="r";break;case"b":case"o":case"x":case"X":"#"===u&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":y=!0,d=0;break;case"s":g=-1,p="r"}"$"===u&&(v=i[0],m=i[1]),"r"!=p||d||(p="g"),null!=d&&("g"==p?d=Math.max(1,Math.min(21,d)):"e"!=p&&"f"!=p||(d=Math.max(0,Math.min(20,d)))),p=Oe.get(p)||Re;var b=c&&h;return function(t){var n=m;if(y&&t%1)return"";var i=t<0||0===t&&1/t<0?(t=-t,"-"):"-"===s?"":s;if(g<0){var u=e.formatPrefix(t,d);t=u.scale(t),n=u.symbol+m}else t*=g;var _,w,A=(t=p(t,d)).lastIndexOf(".");if(A<0){var M=x?t.lastIndexOf("e"):-1;M<0?(_=t,w=""):(_=t.substring(0,M),w=t.substring(M))}else _=t.substring(0,A),w=r+t.substring(A+1);!c&&h&&(_=o(_,1/0));var T=v.length+_.length+w.length+(b?0:i.length),k=T"===l?k+i+t:"^"===l?k.substring(0,T>>=1)+i+t+k.substring(T):i+(b?t:k+t))+n}}}(t),timeFormat:function(t){var r=t.dateTime,n=t.date,a=t.time,i=t.periods,o=t.days,l=t.shortDays,s=t.months,u=t.shortMonths;function c(t){var e=t.length;function r(r){for(var n,a,i,o=[],l=-1,s=0;++l=u)return-1;if(37===(a=e.charCodeAt(l++))){if(o=e.charAt(l++),!(i=w[o in Be?e.charAt(l++):o])||(n=i(t,r,n))<0)return-1}else if(a!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(Ie=Pe);return r._=t,e(r)}finally{Ie=Date}}return r.parse=function(t){try{Ie=Pe;var r=e.parse(t);return r&&r._}finally{Ie=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var h=e.map(),d=He(o),p=qe(o),g=He(l),v=qe(l),m=He(s),y=qe(s),x=He(u),b=qe(u);i.forEach(function(t,e){h.set(t.toLowerCase(),e)});var _={a:function(t){return l[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:c(r),d:function(t,e){return Ve(t.getDate(),e,2)},e:function(t,e){return Ve(t.getDate(),e,2)},H:function(t,e){return Ve(t.getHours(),e,2)},I:function(t,e){return Ve(t.getHours()%12||12,e,2)},j:function(t,e){return Ve(1+De.dayOfYear(t),e,3)},L:function(t,e){return Ve(t.getMilliseconds(),e,3)},m:function(t,e){return Ve(t.getMonth()+1,e,2)},M:function(t,e){return Ve(t.getMinutes(),e,2)},p:function(t){return i[+(t.getHours()>=12)]},S:function(t,e){return Ve(t.getSeconds(),e,2)},U:function(t,e){return Ve(De.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ve(De.mondayOfYear(t),e,2)},x:c(n),X:c(a),y:function(t,e){return Ve(t.getFullYear()%100,e,2)},Y:function(t,e){return Ve(t.getFullYear()%1e4,e,4)},Z:ar,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){d.lastIndex=0;var n=d.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return f(t,_.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Ke,L:nr,m:Qe,M:er,p:function(t,e,r){var n=h.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Xe,w:Ge,W:We,x:function(t,e,r){return f(t,_.x.toString(),e,r)},X:function(t,e,r){return f(t,_.X.toString(),e,r)},y:Ze,Y:Ye,Z:Je,"%":ir};return c}(t)}};var lr=e.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"]});function sr(){}e.format=lr.numberFormat,e.geo={},sr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new sr;function cr(t,e,r){var n=r.s=t+e,a=n-t,i=n-a;r.t=t-i+(e-a)}function fr(t,e){t&&dr.hasOwnProperty(t.type)&&dr[t.type](t,e)}e.geo.stream=function(t,e){t&&hr.hasOwnProperty(t.type)?hr[t.type](t,e):fr(t,e)};var hr={Feature:function(t,e){fr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,a=r.length;++n=0?1:-1,l=o*i,s=Math.cos(e),u=Math.sin(e),c=a*u,f=n*s+c*Math.cos(l),h=c*o*Math.sin(l);Cr.add(Math.atan2(h,f)),r=t,n=s,a=u}Sr.point=function(o,l){Sr.point=i,r=(t=o)*St,n=Math.cos(l=(e=l)*St/2+Tt/4),a=Math.sin(l)},Sr.lineEnd=function(){i(t,e)}}function Or(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Rr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Dr(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Ir(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Pr(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Fr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function zr(t){return[Math.atan2(t[1],t[0]),It(t[2])]}function Nr(t,e){return y(t[0]-e[0])At?a=90:u<-At&&(r=-90),f[0]=t,f[1]=n}};function d(e,i){c.push(f=[t=e,n=e]),ia&&(a=i)}function p(e,o){var l=Or([e*St,o*St]);if(s){var u=Dr(s,l),c=Dr([u[1],-u[0],0],u);Fr(c),c=zr(c);var f=e-i,h=f>0?1:-1,p=c[0]*Lt*h,g=y(f)>180;if(g^(h*ia&&(a=v);else if(g^(h*i<(p=(p+360)%360-180)&&pa&&(a=o);g?e_(t,n)&&(n=e):_(e,n)>_(t,n)&&(t=e):n>=t?(en&&(n=e)):e>i?_(t,e)>_(t,n)&&(n=e):_(e,n)>_(t,n)&&(t=e)}else d(e,o);s=l,i=e}function g(){h.point=p}function v(){f[0]=t,f[1]=n,h.point=d,s=null}function m(t,e){if(s){var r=t-i;u+=y(r)>180?r+(r>0?360:-360):r}else o=t,l=e;Sr.point(t,e),p(t,e)}function x(){Sr.lineStart()}function b(){m(o,l),Sr.lineEnd(),y(u)>At&&(t=-(n=180)),f[0]=t,f[1]=n,s=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function A(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(g[0],g[1])&&(g[1]=d[1]),_(d[0],g[1])>_(g[0],g[1])&&(g[0]=d[0])):l.push(g=d);for(var s,u,d,p=-1/0,g=(o=0,l[u=l.length-1]);o<=u;g=d,++o)d=l[o],(s=_(g[1],d[0]))>p&&(p=s,t=d[0],n=g[1])}return c=f=null,t===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[t,r],[n,a]]}}(),e.geo.centroid=function(t){mr=yr=xr=br=_r=wr=Ar=Mr=Tr=kr=Er=0,e.geo.stream(t,Br);var r=Tr,n=kr,a=Er,i=r*r+n*n+a*a;return i=0;--l)a.point((f=c[l])[0],f[1]);else n(d.x,d.p.x,-1,a);d=d.p}c=(d=d.o).z,p=!p}while(!d.v);a.lineEnd()}}}function Yr(t){if(e=t.length){for(var e,r,n=0,a=t[0];++n=0?1:-1,A=w*_,M=A>Tt,T=p*x;if(Cr.add(Math.atan2(T*w*Math.sin(A),g*b+T*Math.cos(A))),i+=M?_+w*kt:_,M^h>=r^m>=r){var k=Dr(Or(f),Or(t));Fr(k);var E=Dr(a,k);Fr(E);var C=(M^_>=0?-1:1)*It(E[2]);(n>C||n===C&&(k[0]||k[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;h=m,p=x,g=b,f=t}}return(i<-At||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&e&&r.push(r.pop().concat(r.shift())),l.push(r.filter(Qr))}return c}}function Qr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:P,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Kr(t,e){return((t=t.x)[0]<0?t[1]-Ct-At:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-At:Ct-e[1])}var tn=Jr(Xr,function(t){var e,r=NaN,n=NaN,a=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(i,o){var l=i>0?Tt:-Tt,s=y(i-r);y(s-Tt)0?Ct:-Ct),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),t.point(i,n),e=0):a!==l&&s>=Tt&&(y(r-a)At?Math.atan((Math.sin(e)*(i=Math.cos(n))*Math.sin(r)-Math.sin(n)*(a=Math.cos(e))*Math.sin(t))/(a*i*o)):(e+n)/2}(r,n,i,o),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),e=0),t.point(r=i,n=o),a=l},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var a;if(null==t)a=r*Ct,n.point(-Tt,a),n.point(0,a),n.point(Tt,a),n.point(Tt,0),n.point(Tt,-a),n.point(0,-a),n.point(-Tt,-a),n.point(-Tt,0),n.point(-Tt,a);else if(y(t[0]-e[0])>At){var i=t[0]0)){if(i/=h,h<0){if(i0){if(i>f)return;i>c&&(c=i)}if(i=r-s,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>c&&(c=i)}else if(h>0){if(i0)){if(i/=d,d<0){if(i0){if(i>f)return;i>c&&(c=i)}if(i=n-u,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>c&&(c=i)}else if(d>0){if(i0&&(a.a={x:s+c*h,y:u+c*d}),f<1&&(a.b={x:s+f*h,y:u+f*d}),a}}}}}}var rn=1e9;function nn(t,r,n,a){return function(s){var u,c,f,h,d,p,g,v,m,y,x,b=s,_=$r(),w=en(t,r,n,a),A={point:k,lineStart:function(){A.point=E,c&&c.push(f=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){u&&(E(h,d),p&&m&&_.rejoin(),u.push(_.buffer()));A.point=k,m&&s.lineEnd()},polygonStart:function(){s=_,u=[],c=[],x=!0},polygonEnd:function(){s=b,u=e.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],a=0;an&&Rt(u,i,t)>0&&++e:i[1]<=n&&Rt(u,i,t)<0&&--e,u=i;return 0!==e}([t,a]),n=x&&r,i=u.length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Wr(u,o,r,M,s),s.polygonEnd()),u=c=f=null}};function M(e,o,s,u){var c=0,f=0;if(null==e||(c=i(e,s))!==(f=i(o,s))||l(e,o)<0^s>0)do{u.point(0===c||3===c?t:n,c>1?a:r)}while((c=(c+s+4)%4)!==f);else u.point(o[0],o[1])}function T(e,i){return t<=e&&e<=n&&r<=i&&i<=a}function k(t,e){T(t,e)&&s.point(t,e)}function E(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&f.push([t,e]),y)h=t,d=e,p=r,y=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&m)s.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),x=!1):r&&(s.lineStart(),s.point(t,e),x=!1)}g=t,v=e,m=r}return A};function i(e,a){return y(e[0]-t)0?0:3:y(e[0]-n)0?2:1:y(e[1]-r)0?1:0:a>0?3:2}function o(t,e){return l(t.x,e.x)}function l(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=En(t),a=n(e,r);return a.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},a}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,a=1+r*(2*n-r),i=Math.sqrt(a)/n;function o(t,e){var r=Math.sqrt(a-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),i-r*Math.cos(t)]}return o.invert=function(t,e){var r=i-e;return[Math.atan2(t,r)/n,It((a-(t*t+r*r)*n*n)/(2*n))]},o}e.geo.clipExtent=function(){var t,e,r,n,a,i,o={stream:function(t){return a&&(a.valid=!1),(a=i(t)).valid=!0,a},extent:function(l){return arguments.length?(i=nn(t=+l[0][0],e=+l[0][1],r=+l[1][0],n=+l[1][1]),a&&(a.valid=!1,a=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(e.geo.conicEqualArea=function(){return an(on)}).raw=on,e.geo.albers=function(){return e.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},e.geo.albersUsa=function(){var t,r,n,a,i=e.geo.albers(),o=e.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=e.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(e,r){t=[e,r]}};function u(e){var i=e[0],o=e[1];return t=null,r(i,o),t||(n(i,o),t)||a(i,o),t}return u.invert=function(t){var e=i.scale(),r=i.translate(),n=(t[0]-r[0])/e,a=(t[1]-r[1])/e;return(a>=.12&&a<.234&&n>=-.425&&n<-.214?o:a>=.166&&a<.234&&n>=-.214&&n<-.115?l:i).invert(t)},u.stream=function(t){var e=i.stream(t),r=o.stream(t),n=l.stream(t);return{point:function(t,a){e.point(t,a),r.point(t,a),n.point(t,a)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),l.precision(t),u):i.precision()},u.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),l.scale(t),u.translate(i.translate())):i.scale()},u.translate=function(t){if(!arguments.length)return i.translate();var e=i.scale(),c=+t[0],f=+t[1];return r=i.translate(t).clipExtent([[c-.455*e,f-.238*e],[c+.455*e,f+.238*e]]).stream(s).point,n=o.translate([c-.307*e,f+.201*e]).clipExtent([[c-.425*e+At,f+.12*e+At],[c-.214*e-At,f+.234*e-At]]).stream(s).point,a=l.translate([c-.205*e,f+.212*e]).clipExtent([[c-.214*e+At,f+.166*e+At],[c-.115*e-At,f+.234*e-At]]).stream(s).point,u},u.scale(1070)};var ln,sn,un,cn,fn,hn,dn={point:P,lineStart:P,lineEnd:P,polygonStart:function(){sn=0,dn.lineStart=pn},polygonEnd:function(){dn.lineStart=dn.lineEnd=dn.point=P,ln+=y(sn/2)}};function pn(){var t,e,r,n;function a(t,e){sn+=n*t-r*e,r=t,n=e}dn.point=function(i,o){dn.point=a,t=r=i,e=n=o},dn.lineEnd=function(){a(t,e)}}var gn={point:function(t,e){tfn&&(fn=t);ehn&&(hn=e)},lineStart:P,lineEnd:P,polygonStart:P,polygonEnd:P};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,yn={point:xn,lineStart:bn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=xn,yn.lineStart=bn,yn.lineEnd=_n}};function xn(t,e){xr+=t,br+=e,++_r}function bn(){var t,e;function r(r,n){var a=r-t,i=n-e,o=Math.sqrt(a*a+i*i);wr+=o*(t+r)/2,Ar+=o*(e+n)/2,Mr+=o,xn(t=r,e=n)}yn.point=function(n,a){yn.point=r,xn(t=n,e=a)}}function _n(){yn.point=xn}function wn(){var t,e,r,n;function a(t,e){var a=t-r,i=e-n,o=Math.sqrt(a*a+i*i);wr+=o*(r+t)/2,Ar+=o*(n+e)/2,Mr+=o,Tr+=(o=n*t-r*e)*(r+t),kr+=o*(n+e),Er+=3*o,xn(r=t,n=e)}yn.point=function(i,o){yn.point=a,xn(t=r=i,e=n=o)},yn.lineEnd=function(){a(t,e)}}function An(t){var e=.5,r=Math.cos(30*St),n=16;function a(e){return(n?function(e){var r,a,o,l,s,u,c,f,h,d,p,g,v={point:m,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){f=NaN,v.point=x,e.lineStart()}function x(r,a){var o=Or([r,a]),l=t(r,a);i(f,h,c,d,p,g,f=l[0],h=l[1],c=r,d=o[0],p=o[1],g=o[2],n,e),e.point(f,h)}function b(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=A}function w(t,e){x(r=t,e),a=f,o=h,l=d,s=p,u=g,v.point=x}function A(){i(f,h,c,d,p,g,a,o,r,l,s,u,n,e),v.lineEnd=b,b()}return v}:function(e){return Tn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function i(n,a,o,l,s,u,c,f,h,d,p,g,v,m){var x=c-n,b=f-a,_=x*x+b*b;if(_>4*e&&v--){var w=l+d,A=s+p,M=u+g,T=Math.sqrt(w*w+A*A+M*M),k=Math.asin(M/=T),E=y(y(M)-1)e||y((x*O+b*R)/_-.5)>.3||l*d+s*p+u*g0&&16,a):Math.sqrt(e)},a}function Mn(t){this.stream=t}function Tn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function kn(t){return En(function(){return t})()}function En(t){var r,n,a,i,o,l,s=An(function(t,e){return[(t=r(t,e))[0]*u+i,o-t[1]*u]}),u=150,c=480,f=250,h=0,d=0,p=0,g=0,v=0,m=tn,x=O,b=null,_=null;function w(t){return[(t=a(t[0]*St,t[1]*St))[0]*u+i,o-t[1]*u]}function A(t){return(t=a.invert((t[0]-i)/u,(o-t[1])/u))&&[t[0]*Lt,t[1]*Lt]}function M(){a=Gr(n=On(p,g,v),r);var t=r(h,d);return i=c-t[0]*u,o=f+t[1]*u,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(t){return l&&(l.valid=!1),(l=Cn(m(n,s(x(t))))).valid=!0,l},w.clipAngle=function(t){return arguments.length?(m=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>At;return Jr(a,function(t){var e,l,s,u,c;return{lineStart:function(){u=s=!1,c=1},point:function(f,h){var d,p=[f,h],g=a(f,h),v=r?g?0:o(f,h):g?o(f+(f<0?Tt:-Tt),h):0;if(!e&&(u=s=g)&&t.lineStart(),g!==s&&(d=i(e,p),(Nr(e,d)||Nr(p,d))&&(p[0]+=At,p[1]+=At,g=a(p[0],p[1]))),g!==s)c=0,g?(t.lineStart(),d=i(p,e),t.point(d[0],d[1])):(d=i(e,p),t.point(d[0],d[1]),t.lineEnd()),e=d;else if(n&&e&&r^g){var m;v&l||!(m=i(p,e,!0))||(c=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&Nr(e,p)||t.point(p[0],p[1]),e=p,s=g,l=v},lineEnd:function(){s&&t.lineEnd(),e=null},clean:function(){return c|(u&&s)<<1}}},Pn(t,6*St),r?[0,-t]:[-Tt,t-Tt]);function a(t,r){return Math.cos(t)*Math.cos(r)>e}function i(t,r,n){var a=[1,0,0],i=Dr(Or(t),Or(r)),o=Rr(i,i),l=i[0],s=o-l*l;if(!s)return!n&&t;var u=e*o/s,c=-e*l/s,f=Dr(a,i),h=Pr(a,u);Ir(h,Pr(i,c));var d=f,p=Rr(h,d),g=Rr(d,d),v=p*p-g*(Rr(h,h)-1);if(!(v<0)){var m=Math.sqrt(v),x=Pr(d,(-p-m)/g);if(Ir(x,h),x=zr(x),!n)return x;var b,_=t[0],w=r[0],A=t[1],M=r[1];w<_&&(b=_,_=w,w=b);var T=w-_,k=y(T-Tt)0^x[1]<(y(x[0]-_)Tt^(_<=x[0]&&x[0]<=w)){var E=Pr(d,(-p+m)/g);return Ir(E,h),[x,zr(E)]}}}function o(e,n){var a=r?t:Tt-t,i=0;return e<-a?i|=1:e>a&&(i|=2),n<-a?i|=4:n>a&&(i|=8),i}}((b=+t)*St),T()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):O,T()):_},w.scale=function(t){return arguments.length?(u=+t,M()):u},w.translate=function(t){return arguments.length?(c=+t[0],f=+t[1],M()):[c,f]},w.center=function(t){return arguments.length?(h=t[0]%360*St,d=t[1]%360*St,M()):[h*Lt,d*Lt]},w.rotate=function(t){return arguments.length?(p=t[0]%360*St,g=t[1]%360*St,v=t.length>2?t[2]%360*St:0,M()):[p*Lt,g*Lt,v*Lt]},e.rebind(w,s,"precision"),function(){return r=t.apply(this,arguments),w.invert=r.invert&&A,M()}}function Cn(t){return Tn(t,function(e,r){t.point(e*St,r*St)})}function Sn(t,e){return[t,e]}function Ln(t,e){return[t>Tt?t-kt:t<-Tt?t+kt:t,e]}function On(t,e,r){return t?e||r?Gr(Dn(t),In(e,r)):Dn(t):e||r?In(e,r):Ln}function Rn(t){return function(e,r){return[(e+=t)>Tt?e-kt:e<-Tt?e+kt:e,r]}}function Dn(t){var e=Rn(t);return e.invert=Rn(-t),e}function In(t,e){var r=Math.cos(t),n=Math.sin(t),a=Math.cos(e),i=Math.sin(e);function o(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,u=Math.sin(e),c=u*r+l*n;return[Math.atan2(s*a-c*i,l*r-u*n),It(c*a+s*i)]}return o.invert=function(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,u=Math.sin(e),c=u*a-s*i;return[Math.atan2(s*a+u*i,l*r+c*n),It(c*r-l*n)]},o}function Pn(t,e){var r=Math.cos(t),n=Math.sin(t);return function(a,i,o,l){var s=o*e;null!=a?(a=Fn(r,a),i=Fn(r,i),(o>0?ai)&&(a+=o*kt)):(a=t+o*kt,i=t-.5*s);for(var u,c=a;o>0?c>i:c2?t[2]*St:0),e.invert=function(e){return(e=t.invert(e[0]*St,e[1]*St))[0]*=Lt,e[1]*=Lt,e},e},Ln.invert=Sn,e.geo.circle=function(){var t,e,r=[0,0],n=6;function a(){var t="function"==typeof r?r.apply(this,arguments):r,n=On(-t[0]*St,-t[1]*St,0).invert,a=[];return e(null,null,1,{point:function(t,e){a.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(t){return arguments.length?(r=t,a):r},a.angle=function(r){return arguments.length?(e=Pn((t=+r)*St,n*St),a):t},a.precision=function(r){return arguments.length?(e=Pn(t*St,(n=+r)*St),a):n},a.angle(90)},e.geo.distance=function(t,e){var r,n=(e[0]-t[0])*St,a=t[1]*St,i=e[1]*St,o=Math.sin(n),l=Math.cos(n),s=Math.sin(a),u=Math.cos(a),c=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((r=f*o)*r+(r=u*c-s*f*l)*r),s*c+u*f*l)},e.geo.graticule=function(){var t,r,n,a,i,o,l,s,u,c,f,h,d=10,p=d,g=90,v=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return e.range(Math.ceil(a/g)*g,n,g).map(f).concat(e.range(Math.ceil(s/v)*v,l,v).map(h)).concat(e.range(Math.ceil(r/d)*d,t,d).filter(function(t){return y(t%g)>At}).map(u)).concat(e.range(Math.ceil(o/p)*p,i,p).filter(function(t){return y(t%v)>At}).map(c))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(h(l).slice(1),f(n).reverse().slice(1),h(s).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(a=+t[0][0],n=+t[1][0],s=+t[0][1],l=+t[1][1],a>n&&(t=a,a=n,n=t),s>l&&(t=s,s=l,l=t),x.precision(m)):[[a,s],[n,l]]},x.minorExtent=function(e){return arguments.length?(r=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],r>t&&(e=r,r=t,t=e),o>i&&(e=o,o=i,i=e),x.precision(m)):[[r,o],[t,i]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],x):[g,v]},x.minorStep=function(t){return arguments.length?(d=+t[0],p=+t[1],x):[d,p]},x.precision=function(e){return arguments.length?(m=+e,u=zn(o,i,90),c=Nn(r,t,m),f=zn(s,l,90),h=Nn(a,n,m),x):m},x.majorExtent([[-180,-90+At],[180,90-At]]).minorExtent([[-180,-80-At],[180,80+At]])},e.geo.greatArc=function(){var t,r,n=Bn,a=jn;function i(){return{type:"LineString",coordinates:[t||n.apply(this,arguments),r||a.apply(this,arguments)]}}return i.distance=function(){return e.geo.distance(t||n.apply(this,arguments),r||a.apply(this,arguments))},i.source=function(e){return arguments.length?(n=e,t="function"==typeof e?null:e,i):n},i.target=function(t){return arguments.length?(a=t,r="function"==typeof t?null:t,i):a},i.precision=function(){return arguments.length?i:0},i},e.geo.interpolate=function(t,e){return r=t[0]*St,n=t[1]*St,a=e[0]*St,i=e[1]*St,o=Math.cos(n),l=Math.sin(n),s=Math.cos(i),u=Math.sin(i),c=o*Math.cos(r),f=o*Math.sin(r),h=s*Math.cos(a),d=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Ft(i-n)+o*s*Ft(a-r))),g=1/Math.sin(p),(v=p?function(t){var e=Math.sin(t*=p)*g,r=Math.sin(p-t)*g,n=r*c+e*h,a=r*f+e*d,i=r*l+e*u;return[Math.atan2(a,n)*Lt,Math.atan2(i,Math.sqrt(n*n+a*a))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=p,v;var r,n,a,i,o,l,s,u,c,f,h,d,p,g,v},e.geo.length=function(t){return mn=0,e.geo.stream(t,Un),mn};var Un={sphere:P,point:P,lineStart:function(){var t,e,r;function n(n,a){var i=Math.sin(a*=St),o=Math.cos(a),l=y((n*=St)-t),s=Math.cos(l);mn+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=r*i-e*o*s)*l),e*i+r*o*s),t=n,e=i,r=o}Un.point=function(a,i){t=a*St,e=Math.sin(i*=St),r=Math.cos(i),Un.point=n},Un.lineEnd=function(){Un.point=Un.lineEnd=P}},lineEnd:P,polygonStart:P,polygonEnd:P};function Vn(t,e){function r(e,r){var n=Math.cos(e),a=Math.cos(r),i=t(n*a);return[i*a*Math.sin(e),i*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),a=e(n),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(t*i,n*o),Math.asin(n&&r*i/n)]},r}var Hn=Vn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(e.geo.azimuthalEqualArea=function(){return kn(Hn)}).raw=Hn;var qn=Vn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},O);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},a=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),i=r*Math.pow(n(t),a)/a;if(!a)return Yn;function o(t,e){i>0?e<-Ct+At&&(e=-Ct+At):e>Ct-At&&(e=Ct-At);var r=i/Math.pow(n(e),a);return[r*Math.sin(a*t),i-r*Math.cos(a*t)]}return o.invert=function(t,e){var r=i-e,n=Ot(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(i/n,1/a))-Ct]},o}function Xn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),a=r/n+t;if(y(n)1&&Rt(t[r[n-2]],t[r[n-1]],t[a])<=0;)--n;r[n++]=a}return r.slice(0,n)}function ra(t,e){return t[0]-e[0]||t[1]-e[1]}(e.geo.stereographic=function(){return kn(Qn)}).raw=Qn,$n.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(e.geo.transverseMercator=function(){var t=Zn($n),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=$n,e.geom={},e.geom.hull=function(t){var e=Kn,r=ta;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,a=ve(e),i=ve(r),o=t.length,l=[],s=[];for(n=0;n=0;--n)d.push(t[l[u[n]][2]]);for(n=+f;nAt)l=l.L;else{if(!((a=i-xa(l,o))>At)){n>-At?(e=l.P,r=l):a>-At?(e=l,r=l.N):e=r=l;break}if(!l.R){e=l;break}l=l.R}var s=pa(t);if(ua.insert(e,s),e||r){if(e===r)return Aa(e),r=pa(e.site),ua.insert(s,r),s.edge=r.edge=ka(e.site,s.site),wa(e),void wa(r);if(r){Aa(e),Aa(r);var u=e.site,c=u.x,f=u.y,h=t.x-c,d=t.y-f,p=r.site,g=p.x-c,v=p.y-f,m=2*(h*v-d*g),y=h*h+d*d,x=g*g+v*v,b={x:(v*y-d*x)/m+c,y:(h*x-g*y)/m+f};Ea(r.edge,u,p,b),s.edge=ka(u,t,null,b),r.edge=ka(t,p,null,b),wa(e),wa(r)}else s.edge=ka(e.site,s.site)}}function ya(t,e){var r=t.site,n=r.x,a=r.y,i=a-e;if(!i)return n;var o=t.P;if(!o)return-1/0;var l=(r=o.site).x,s=r.y,u=s-e;if(!u)return l;var c=l-n,f=1/i-1/u,h=c/u;return f?(-h+Math.sqrt(h*h-2*f*(c*c/(-2*u)-s+u/2+a-i/2)))/f+n:(n+l)/2}function xa(t,e){var r=t.N;if(r)return ya(r,e);var n=t.site;return n.y===e?n.x:1/0}function ba(t){this.site=t,this.edges=[]}function _a(t,e){return e.angle-t.angle}function wa(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,a=t.site,i=r.site;if(n!==i){var o=a.x,l=a.y,s=n.x-o,u=n.y-l,c=i.x-o,f=2*(s*(v=i.y-l)-u*c);if(!(f>=-Mt)){var h=s*s+u*u,d=c*c+v*v,p=(v*h-u*d)/f,g=(s*d-c*h)/f,v=g+l,m=da.pop()||new function(){La(this),this.x=this.y=this.arc=this.site=this.cy=null};m.arc=t,m.site=a,m.x=p+o,m.y=v+Math.sqrt(p*p+g*g),m.cy=v,t.circle=m;for(var y=null,x=fa._;x;)if(m.y=l)return;if(h>p){if(i){if(i.y>=u)return}else i={x:v,y:s};r={x:v,y:u}}else{if(i){if(i.y1)if(h>p){if(i){if(i.y>=u)return}else i={x:(s-a)/n,y:s};r={x:(u-a)/n,y:u}}else{if(i){if(i.y=l)return}else i={x:o,y:n*o+a};r={x:l,y:n*l+a}}else{if(i){if(i.xAt||y(a-r)>At)&&(l.splice(o,0,new Ca((m=i.site,x=c,b=y(n-f)At?{x:f,y:y(e-f)At?{x:y(r-p)At?{x:h,y:y(e-h)At?{x:y(r-d)=r&&u.x<=a&&u.y>=n&&u.y<=o?[[r,o],[a,o],[a,n],[r,n]]:[]).point=t[l]}),e}function l(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/At)*At,y:Math.round(a(t,e)/At)*At,i:e}})}return o.links=function(t){return Ia(l(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Ia(l(t)).cells.forEach(function(r,n){for(var a,i,o,l,s=r.site,u=r.edges.sort(_a),c=-1,f=u.length,h=u[f-1].edge,d=h.l===s?h.r:h.l;++ci&&(a=e.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(r=r[0])===(n=n[0])?l[o]?l[o]+=n:l[++o]=n:(l[++o]=null,s.push({i:o,x:Ua(r,n)})),i=qa.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),u.push(s.x),c.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),u.push(b),c.push(_)}var w=g-d,A=v-p;function M(t,e,r,n,a,i,o,l){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var s=t.x,u=t.y;if(null!=s)if(y(s-r)+y(u-n)<.01)T(t,e,r,n,a,i,o,l);else{var c=t.point;t.x=t.y=t.point=null,T(t,c,s,u,a,i,o,l),T(t,e,r,n,a,i,o,l)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,a,i,o,l)}function T(t,e,r,n,a,i,o,l){var s=.5*(a+o),u=.5*(i+l),c=r>=s,f=n>=u,h=f<<1|c;t.leaf=!1,t=t.nodes[h]||(t.nodes[h]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(k,t,+m(t,++f),+x(t,f),d,p,g,v)}}),c?a=s:o=s,f?i=u:l=u,M(t,e,r,n,a,i,o,l)}w>A?v=p+w:g=d+A;var k={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(k,t,+m(t,++f),+x(t,f),d,p,g,v)}};if(k.visit=function(t){!function t(e,r,n,a,i,o){if(!e(r,n,a,i,o)){var l=.5*(n+i),s=.5*(a+o),u=r.nodes;u[0]&&t(e,u[0],n,a,l,s),u[1]&&t(e,u[1],l,a,i,s),u[2]&&t(e,u[2],n,s,l,o),u[3]&&t(e,u[3],l,s,i,o)}}(t,k,d,p,g,v)},k.find=function(t){return function(t,e,r,n,a,i,o){var l,s=1/0;return function t(u,c,f,h,d){if(!(c>i||f>o||h=_)<<1|e>=b,A=w+4;w=0&&!(n=e.interpolators[a](t,r)););return n}function Xa(t,e){var r,n=[],a=[],i=t.length,o=e.length,l=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ei(t){return 1-Math.cos(t*Ct)}function ri(t){return Math.pow(2,10*(t-1))}function ni(t){return 1-Math.sqrt(1-t*t)}function ai(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}function ii(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oi(t){var e,r,n,a=[t.a,t.b],i=[t.c,t.d],o=si(a),l=li(a,i),s=si(((e=i)[0]+=(n=-l)*(r=a)[0],e[1]+=n*r[1],e))||0;a[0]*i[1]=0?t.slice(0,n):t,i=n>=0?t.slice(n+1):"in";return a=Ya.get(a)||Wa,i=Za.get(i)||O,e=i(a.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},e.interpolateHcl=function(t,r){t=e.hcl(t),r=e.hcl(r);var n=t.h,a=t.c,i=t.l,o=r.h-n,l=r.c-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.c:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Wt(n+o*t,a+l*t,i+s*t)+""}},e.interpolateHsl=function(t,r){t=e.hsl(t),r=e.hsl(r);var n=t.h,a=t.s,i=t.l,o=r.h-n,l=r.s-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.s:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return qt(n+o*t,a+l*t,i+s*t)+""}},e.interpolateLab=function(t,r){t=e.lab(t),r=e.lab(r);var n=t.l,a=t.a,i=t.b,o=r.l-n,l=r.a-a,s=r.b-i;return function(t){return te(n+o*t,a+l*t,i+s*t)+""}},e.interpolateRound=ii,e.transform=function(t){var r=a.createElementNS(e.ns.prefix.svg,"g");return(e.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oi(e?e.matrix:ui)})(t)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ui={a:1,b:0,c:0,d:1,e:0,f:0};function ci(t){return t.length?t.pop()+",":""}function fi(t,r){var n=[],a=[];return t=e.transform(t),r=e.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push("translate(",null,",",null,")");n.push({i:a-4,x:Ua(t[0],e[0])},{i:a-2,x:Ua(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(t.translate,r.translate,n,a),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ci(r)+"rotate(",null,")")-2,x:Ua(t,e)})):e&&r.push(ci(r)+"rotate("+e+")")}(t.rotate,r.rotate,n,a),function(t,e,r,n){t!==e?n.push({i:r.push(ci(r)+"skewX(",null,")")-2,x:Ua(t,e)}):e&&r.push(ci(r)+"skewX("+e+")")}(t.skew,r.skew,n,a),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push(ci(r)+"scale(",null,",",null,")");n.push({i:a-4,x:Ua(t[0],e[0])},{i:a-2,x:Ua(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ci(r)+"scale("+e+")")}(t.scale,r.scale,n,a),t=r=null,function(t){for(var e,r=-1,i=a.length;++r0?n=e:(t.c=null,t.t=NaN,t=null,s.end({type:"end",alpha:n=0})):e>0&&(s.start({type:"start",alpha:n=e}),t=Me(l.tick)),l):n},l.start=function(){var t,e,r,n=m.length,s=y.length,c=u[0],p=u[1];for(t=0;t=0;)r.push(a[n])}function Ti(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(i=t.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(c=u[s]),c.parent=i,c.depth=i.depth+1;r&&(i.value=0),i.children=u}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Ti(a,function(e){var n,a;t&&(n=e.children)&&n.sort(t),r&&(a=e.parent)&&(a.value+=e.value)}),l}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Mi(t,function(t){t.children&&(t.value=0)}),Ti(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},e.layout.partition=function(){var t=e.layout.hierarchy(),r=[1,1];function n(e,n){var a=t.call(this,e,n);return function t(e,r,n,a){var i=e.children;if(e.x=r,e.y=e.depth*a,e.dx=n,e.dy=a,i&&(o=i.length)){var o,l,s,u=-1;for(n=e.value?n/e.value:0;++ul&&(l=n),o.push(n)}for(r=0;ra&&(n=r,a=e);return n}function Bi(t){return t.reduce(ji,0)}function ji(t,e){return t+e[1]}function Ui(t,e){return Vi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Vi(t,e){for(var r=-1,n=+t[0],a=(t[1]-n)/e,i=[];++r<=e;)i[r]=a*r+n;return i}function Hi(t){return[e.min(t),e.max(t)]}function qi(t,e){return t.value-e.value}function Gi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Xi(t,e){t._pack_next=e,e._pack_prev=t}function Wi(t,e){var r=e.x-t.x,n=e.y-t.y,a=t.r+e.r;return.999*a*a>r*r+n*n}function Yi(t){if((e=t.children)&&(s=e.length)){var e,r,n,a,i,o,l,s,u=1/0,c=-1/0,f=1/0,h=-1/0;if(e.forEach(Zi),(r=e[0]).x=-r.r,r.y=0,x(r),s>1&&((n=e[1]).x=n.r,n.y=0,x(n),s>2))for(Qi(r,n,a=e[2]),x(a),Gi(r,a),r._pack_prev=a,Gi(a,n),n=r._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=u[e.bisect(h,s,1,p)-1]).y+=g,l.push(i[o]));return u}return i.value=function(t){return arguments.length?(r=t,i):r},i.range=function(t){return arguments.length?(n=ve(t),i):n},i.bins=function(t){return arguments.length?(a="number"==typeof t?function(e){return Vi(e,t)}:ve(t),i):a},i.frequency=function(e){return arguments.length?(t=!!e,i):t},i},e.layout.pack=function(){var t,r=e.layout.hierarchy().sort(qi),n=0,a=[1,1];function i(e,i){var o=r.call(this,e,i),l=o[0],s=a[0],u=a[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(l.x=l.y=0,Ti(l,function(t){t.r=+c(t.value)}),Ti(l,Yi),n){var f=n*(t?1:Math.max(2*l.r/s,2*l.r/u))/2;Ti(l,function(t){t.r+=f}),Ti(l,Yi),Ti(l,function(t){t.r-=f})}return function t(e,r,n,a){var i=e.children;e.x=r+=a*e.x;e.y=n+=a*e.y;e.r*=a;if(i)for(var o=-1,l=i.length;++od.x&&(d=t),t.depth>p.depth&&(p=t)});var g=r(h,d)/2-h.x,v=n[0]/(d.x+r(d,h)/2+g),m=n[1]/(p.depth||1);Mi(c,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return u}function o(t){var e=t.children,n=t.parent.children,a=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,a=t.children,i=a.length;for(;--i>=0;)(e=a[i]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var i=(e[0].z+e[e.length-1].z)/2;a?(t.z=a.z+r(t._,a._),t.m=t.z-i):t.z=i}else a&&(t.z=a.z+r(t._,a._));t.parent.A=function(t,e,n){if(e){for(var a,i=t,o=t,l=e,s=i.parent.children[0],u=i.m,c=o.m,f=l.m,h=s.m;l=to(l),i=Ki(i),l&&i;)s=Ki(s),(o=to(o)).a=t,(a=l.z+f-i.z-u+r(l._,i._))>0&&(eo(ro(l,t,n),t,a),u+=a,c+=a),f+=l.m,u+=i.m,h+=s.m,c+=o.m;l&&!to(o)&&(o.t=l,o.m+=f-c),i&&!Ki(s)&&(s.t=i,s.m+=u-h,n=t)}return n}(t,a,t.parent.A||n[0])}function l(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function s(t){t.x*=n[0],t.y=t.depth*n[1]}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t)?s:null,i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null==(n=t)?null:s,i):a?n:null},Ai(i,t)},e.layout.cluster=function(){var t=e.layout.hierarchy().sort(null).value(null),r=$i,n=[1,1],a=!1;function i(i,o){var l,s=t.call(this,i,o),u=s[0],c=0;Ti(u,function(t){var n=t.children;n&&n.length?(t.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),t.y=function(t){return 1+e.max(t,function(t){return t.y})}(n)):(t.x=l?c+=r(t,l):0,t.y=0,l=t)});var f=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),h=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),d=f.x-r(f,h)/2,p=h.x+r(h,f)/2;return Ti(u,a?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-d)/(p-d)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),s}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t),i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null!=(n=t),i):a?n:null},Ai(i,t)},e.layout.treemap=function(){var t,r=e.layout.hierarchy(),n=Math.round,a=[1,1],i=null,o=no,l=!1,s="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,a=-1,i=t.length;++a0;)l.push(r=u[a-1]),l.area+=r.area,"squarify"!==s||(n=d(l,g))<=h?(u.pop(),h=n):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,h=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),e.forEach(f)}}function h(t){var e=t.children;if(e&&e.length){var r,n=o(t),a=e.slice(),i=[];for(c(a,n.dx*n.dy/t.value),i.area=0;r=a.pop();)i.push(r),i.area+=r.area,null!=r.z&&(p(i,r.z?n.dx:n.dy,n,!a.length),i.length=i.area=0);e.forEach(h)}}function d(t,e){for(var r,n=t.area,a=0,i=1/0,o=-1,l=t.length;++oa&&(a=r));return e*=e,(n*=n)?Math.max(e*a*u/n,n/(e*i*u)):1/0}function p(t,e,r,a){var i,o=-1,l=t.length,s=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((a||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var t=e.random.normal.apply(e,arguments);return function(){return Math.exp(t())}},bates:function(t){var r=e.random.irwinHall(t);return function(){return r()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?fo:lo,l=a?di:hi;return i=t(e,r,l,n),o=t(r,e,l,Ga),s}function s(t){return i(t)}s.invert=function(t){return o(t)};s.domain=function(t){return arguments.length?(e=t.map(Number),l()):e};s.range=function(t){return arguments.length?(r=t,l()):r};s.rangeRound=function(t){return s.range(t).interpolate(ii)};s.clamp=function(t){return arguments.length?(a=t,l()):a};s.interpolate=function(t){return arguments.length?(n=t,l()):n};s.ticks=function(t){return vo(e,t)};s.tickFormat=function(t,r){return mo(e,t,r)};s.nice=function(t){return po(e,t),l()};s.copy=function(){return t(e,r,n,a)};return l()}([0,1],[0,1],Ga,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function xo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}e.scale.log=function(){return function t(r,n,a,i){function o(t){return(a?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function l(t){return a?Math.pow(n,t):-Math.pow(n,-t)}function s(t){return r(o(t))}s.invert=function(t){return l(r.invert(t))};s.domain=function(t){return arguments.length?(a=t[0]>=0,r.domain((i=t.map(Number)).map(o)),s):i};s.base=function(t){return arguments.length?(n=+t,r.domain(i.map(o)),s):n};s.nice=function(){var t=so(i.map(o),a?Math:_o);return r.domain(t),i=t.map(l),s};s.ticks=function(){var t=io(i),e=[],r=t[0],s=t[1],u=Math.floor(o(r)),c=Math.ceil(o(s)),f=n%1?2:n;if(isFinite(c-u)){if(a){for(;u0;h--)e.push(l(u)*h);for(u=0;e[u]s;c--);e=e.slice(u,c)}return e};s.tickFormat=function(t,r){if(!arguments.length)return bo;arguments.length<2?r=bo:"function"!=typeof r&&(r=e.format(r));var a=Math.max(1,n*t/s.ticks().length);return function(t){var e=t/l(Math.round(o(t)));return e*n0?a[t-1]:r[0],tf?0:1;if(u=Et)return s(u,d)+(l?s(l,1-d):"")+"Z";var p,g,v,m,y,x,b,_,w,A,M,T,k=0,E=0,C=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Co?Math.sqrt(l*l+u*u):+n.apply(this,arguments),d||(E*=-1),u&&(E=It(v/u*Math.sin(m))),l&&(k=It(v/l*Math.sin(m)))),u){y=u*Math.cos(c+E),x=u*Math.sin(c+E),b=u*Math.cos(f-E),_=u*Math.sin(f-E);var S=Math.abs(f-c-2*E)<=Tt?0:1;if(E&&Io(y,x,b,_)===d^S){var L=(c+f)/2;y=u*Math.cos(L),x=u*Math.sin(L),b=_=null}}else y=x=0;if(l){w=l*Math.cos(f-k),A=l*Math.sin(f-k),M=l*Math.cos(c+k),T=l*Math.sin(c+k);var O=Math.abs(c-f+2*k)<=Tt?0:1;if(k&&Io(w,A,M,T)===1-d^O){var R=(c+f)/2;w=l*Math.cos(R),A=l*Math.sin(R),M=T=null}}else w=A=0;if(h>At&&(p=Math.min(Math.abs(u-l)/2,+r.apply(this,arguments)))>.001){g=l0?0:1}function Po(t,e,r,n,a){var i=t[0]-e[0],o=t[1]-e[1],l=(a?n:-n)/Math.sqrt(i*i+o*o),s=l*o,u=-l*i,c=t[0]+s,f=t[1]+u,h=e[0]+s,d=e[1]+u,p=(c+h)/2,g=(f+d)/2,v=h-c,m=d-f,y=v*v+m*m,x=r-n,b=c*d-h*f,_=(m<0?-1:1)*Math.sqrt(Math.max(0,x*x*y-b*b)),w=(b*m-v*_)/y,A=(-b*v-m*_)/y,M=(b*m+v*_)/y,T=(-b*v+m*_)/y,k=w-p,E=A-g,C=M-p,S=T-g;return k*k+E*E>C*C+S*S&&(w=M,A=T),[[w-s,A-u],[w*r/x,A*r/x]]}function Fo(t){var e=Kn,r=ta,n=Xr,a=No,i=a.key,o=.7;function l(i){var l,s=[],u=[],c=-1,f=i.length,h=ve(e),d=ve(r);function p(){s.push("M",a(t(u),o))}for(;++c1&&a.push("H",n[0]);return a.join("")},"step-before":jo,"step-after":Uo,basis:qo,"basis-open":function(t){if(t.length<4)return No(t);var e,r=[],n=-1,a=t.length,i=[0],o=[0];for(;++n<3;)e=t[n],i.push(e[0]),o.push(e[1]);r.push(Go(Yo,i)+","+Go(Yo,o)),--n;for(;++n9&&(a=3*e/Math.sqrt(a),o[l]=a*r,o[l+1]=a*n));l=-1;for(;++l<=s;)a=(t[Math.min(s,l+1)][0]-t[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(t))}});function No(t){return t.length>1?t.join("L"):t+"Z"}function Bo(t){return t.join("L")+"Z"}function jo(t){for(var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];++e1){l=e[1],i=t[s],s++,n+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var u=2;uTt)+",1 "+e}function s(t,e,r,n){return"Q 0,0 "+n}return i.radius=function(t){return arguments.length?(r=ve(t),i):r},i.source=function(e){return arguments.length?(t=ve(e),i):t},i.target=function(t){return arguments.length?(e=ve(t),i):e},i.startAngle=function(t){return arguments.length?(n=ve(t),i):n},i.endAngle=function(t){return arguments.length?(a=ve(t),i):a},i},e.svg.diagonal=function(){var t=Bn,e=jn,r=tl;function n(n,a){var i=t.call(this,n,a),o=e.call(this,n,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(r))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},e.svg.diagonal.radial=function(){var t=e.svg.diagonal(),r=tl,n=t.projection;return t.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},t},e.svg.symbol=function(){var t=rl,e=el;function r(r,n){return(al.get(t.call(this,r,n))||nl)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var al=e.map({circle:nl,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*ol)),r=e*ol;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/il),r=e*il/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/il),r=e*il/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});e.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*St);W.transition=function(t){for(var e,r,n=cl||++dl,a=vl(t),i=[],o=fl||{time:Date.now(),ease:ti,delay:0,duration:250},l=-1,s=this.length;++l0;)u[--h].call(t,o);if(i>=1)return f.event&&f.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}f||(i=a.time,o=Me(function(t){var e=f.delay;if(o.t=e+i,e<=t)return h(t-e);o.c=h},0,i),f=c[n]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:e},a=null,++c.count)}hl.call=W.call,hl.empty=W.empty,hl.node=W.node,hl.size=W.size,e.transition=function(t,r){return t&&t.transition?cl?t.transition(r):t:e.selection().transition(t)},e.transition.prototype=hl,hl.select=function(t){var e,r,n,a=this.id,i=this.namespace,o=[];t=Y(t);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(t){t.select(".extent").attr("y",s[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,m=this,y=e.select(e.event.target),x=n.of(m,arguments),b=e.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&a,A=!/^(e|w)$/.test(_)&&i,M=y.classed("extent"),T=xt(m),k=e.mouse(m),E=e.select(o(m)).on("keydown.brush",function(){32==e.event.keyCode&&(M||(f=null,k[0]-=l[1],k[1]-=s[1],M=2),N())}).on("keyup.brush",function(){32==e.event.keyCode&&2==M&&(k[0]+=l[1],k[1]+=s[1],M=0,N())});if(e.event.changedTouches?E.on("touchmove.brush",L).on("touchend.brush",R):E.on("mousemove.brush",L).on("mouseup.brush",R),b.interrupt().selectAll("*").interrupt(),M)k[0]=l[0]-k[0],k[1]=s[0]-k[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-k[0],s[1-S]-k[1]],k[0]=l[C],k[1]=s[S]}else e.event.altKey&&(f=k.slice());function L(){var t=e.mouse(m),r=!1;v&&(t[0]+=v[0],t[1]+=v[1]),M||(e.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),k[0]=l[+(t[0]1?{floor:function(e){for(;l(e=t.floor(e));)e=Sl(e-1);return e},ceil:function(e){for(;l(e=t.ceil(e));)e=Sl(+e+1);return e}}:t))},a.ticks=function(t,e){var r=io(a.domain()),n=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Sl(+r[1]+1),e<1?1:e)},a.tickFormat=function(){return n},a.copy=function(){return Cl(t.copy(),r,n)},ho(a,t)}function Sl(t){return new Date(t)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?El:kl,El.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},El.toString=kl.toString,De.second=ze(function(t){return new Ie(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),De.seconds=De.second.range,De.seconds.utc=De.second.utc.range,De.minute=ze(function(t){return new Ie(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),De.minutes=De.minute.range,De.minutes.utc=De.minute.utc.range,De.hour=ze(function(t){var e=t.getTimezoneOffset()/60;return new Ie(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),De.hours=De.hour.range,De.hours.utc=De.hour.utc.range,De.month=ze(function(t){return(t=De.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),De.months=De.month.range,De.months.utc=De.month.utc.range;var Ll=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ol=[[De.second,1],[De.second,5],[De.second,15],[De.second,30],[De.minute,1],[De.minute,5],[De.minute,15],[De.minute,30],[De.hour,1],[De.hour,3],[De.hour,6],[De.hour,12],[De.day,1],[De.day,2],[De.week,1],[De.month,1],[De.month,3],[De.year,1]],Rl=Ml.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Xr]]),Dl={range:function(t,r,n){return e.range(Math.ceil(t/n)*n,+r,n).map(Sl)},floor:O,ceil:O};Ol.year=De.year,De.scale=function(){return Cl(e.scale.linear(),Ol,Rl)};var Il=Ol.map(function(t){return[t[0].utc,t[1]]}),Pl=Tl.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Xr]]);function Fl(t){return JSON.parse(t.responseText)}function zl(t){var e=a.createRange();return e.selectNode(a.body),e.createContextualFragment(t.responseText)}Il.year=De.year.utc,De.scale.utc=function(){return Cl(e.scale.linear(),Il,Pl)},e.text=me(function(t){return t.responseText}),e.json=function(t,e){return ye(t,"application/json",Fl,e)},e.html=function(t,e){return ye(t,"text/html",zl,e)},e.xml=me(function(t){return t.responseXML}),t.exports?t.exports=e:this.d3=e}(),t=t.exports;var e=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},n={},a=Math.PI;n.deg2rad=function(t){return t/180*a},n.rad2deg=function(t){return t/a*180},n.wrap360=function(t){var e=t%360;return e<0?e+360:e},n.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var i=r.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,l={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,a=t.round,i=t.min,o=t.max,s=t.random;function u(l,s){if(l=l||"",s=s||{},l instanceof u)return l;if(!(this instanceof u))return new u(l,s);var c=function(n){var a={r:0,g:0,b:0},l=1,s=null,u=null,c=null,f=!1,h=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,a=!1;if(E[t])t=E[t],a=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=j.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=j.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=j.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=j.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=j.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=j.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=j.hex8.exec(t))return{r:R(n[1]),g:R(n[2]),b:R(n[3]),a:F(n[4]),format:a?"name":"hex8"};if(n=j.hex6.exec(t))return{r:R(n[1]),g:R(n[2]),b:R(n[3]),format:a?"name":"hex"};if(n=j.hex4.exec(t))return{r:R(n[1]+""+n[1]),g:R(n[2]+""+n[2]),b:R(n[3]+""+n[3]),a:F(n[4]+""+n[4]),format:a?"name":"hex8"};if(n=j.hex3.exec(t))return{r:R(n[1]+""+n[1]),g:R(n[2]+""+n[2]),b:R(n[3]+""+n[3]),format:a?"name":"hex"};return!1}(n));"object"==typeof n&&(U(n.r)&&U(n.g)&&U(n.b)?(d=n.r,p=n.g,g=n.b,a={r:255*L(d,255),g:255*L(p,255),b:255*L(g,255)},f=!0,h="%"===String(n.r).substr(-1)?"prgb":"rgb"):U(n.h)&&U(n.s)&&U(n.v)?(s=I(n.s),u=I(n.v),a=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var a=t.floor(e),i=e-a,o=n*(1-r),l=n*(1-i*r),s=n*(1-(1-i)*r),u=a%6;return{r:255*[n,l,o,o,s,n][u],g:255*[s,n,n,l,o,o][u],b:255*[o,o,s,n,n,l][u]}}(n.h,s,u),f=!0,h="hsv"):U(n.h)&&U(n.s)&&U(n.l)&&(s=I(n.s),c=I(n.l),a=function(t,e,r){var n,a,i;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=a=i=r;else{var l=r<.5?r*(1+e):r+e-r*e,s=2*r-l;n=o(s,l,t+1/3),a=o(s,l,t),i=o(s,l,t-1/3)}return{r:255*n,g:255*a,b:255*i}}(n.h,s,c),f=!0,h="hsl"),n.hasOwnProperty("a")&&(l=n.a));var d,p,g;return l=S(l),{ok:f,format:n.format||h,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=a(100*this._a)/100,this._format=s.format||c.format,this._gradientType=s.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=c.ok,this._tc_id=n++}function c(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,a,l=o(t,e,r),s=i(t,e,r),u=(l+s)/2;if(l==s)n=a=0;else{var c=l-s;switch(a=u>.5?c/(2-l-s):c/(l+s),l){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+a)%360,i.push(u(n));return i}function k(t,e){e=e||6;for(var r=u(t).toHsv(),n=r.h,a=r.s,i=r.v,o=[],l=1/e;e--;)o.push(u({h:n,s:a,v:i})),i=(i+l)%1;return o}u.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,a=this.toRgb();return e=a.r/255,r=a.g/255,n=a.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=S(t),this._roundA=a(100*this._a)/100,this},toHsv:function(){var t=f(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=f(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=c(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=c(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return h(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,i){var o=[D(a(t).toString(16)),D(a(e).toString(16)),D(a(r).toString(16)),D(P(n))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*L(this._r,255))+"%",g:a(100*L(this._g,255))+"%",b:a(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*L(this._r,255))+"%, "+a(100*L(this._g,255))+"%, "+a(100*L(this._b,255))+"%)":"rgba("+a(100*L(this._r,255))+"%, "+a(100*L(this._g,255))+"%, "+a(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[h(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+d(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var a=u(t);r="#"+d(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return u(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(A,arguments)}},u.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:I(t[n]));t=r}return u(t,e)},u.equals=function(t,e){return!(!t||!e)&&u(t).toRgbString()==u(e).toRgbString()},u.random=function(){return u.fromRatio({r:s(),g:s(),b:s()})},u.mix=function(t,e,r){r=0===r?0:r||50;var n=u(t).toRgb(),a=u(e).toRgb(),i=r/100;return u({r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a})},u.readability=function(e,r){var n=u(e),a=u(r);return(t.max(n.getLuminance(),a.getLuminance())+.05)/(t.min(n.getLuminance(),a.getLuminance())+.05)},u.isReadable=function(t,e,r){var n,a,i=u.readability(t,e);switch(a=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},u.mostReadable=function(t,e,r){var n,a,i,o,l=null,s=0;a=(r=r||{}).includeFallbackColors,i=r.level,o=r.size;for(var c=0;cs&&(s=n,l=u(e[c]));return u.isReadable(t,l,{level:i,size:o})||!a?l:(r.includeFallbackColors=!1,u.mostReadable(t,["#fff","#000"],r))};var E=u.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"},C=u.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(E);function S(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=i(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function O(t){return i(1,o(0,t))}function R(t){return parseInt(t,16)}function D(t){return 1==t.length?"0"+t:""+t}function I(t){return t<=1&&(t=100*t+"%"),t}function P(e){return t.round(255*parseFloat(e)).toString(16)}function F(t){return R(t)/255}var z,N,B,j=(N="[\\s|\\(]+("+(z="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+z+")[,|\\s]+("+z+")\\s*\\)?",B="[\\s|\\(]+("+z+")[,|\\s]+("+z+")[,|\\s]+("+z+")[,|\\s]+("+z+")\\s*\\)?",{CSS_UNIT:new RegExp(z),rgb:new RegExp("rgb"+N),rgba:new RegExp("rgba"+B),hsl:new RegExp("hsl"+N),hsla:new RegExp("hsla"+B),hsv:new RegExp("hsv"+N),hsva:new RegExp("hsva"+B),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})$/});function U(t){return!!j.CSS_UNIT.exec(t)}l.exports?l.exports=u:window.tinycolor=u}(Math),l=l.exports;var s={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=s.RdBu,c=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],a=t[e][1],o=!1,G(n))for(r=n.length-1;r>=0;r--)Z(n[r],Q(a,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(i=Object.keys(n),o=!1,r=i.length-1;r>=0;r--)Z(n[i[r]],Q(a,i[r]))?delete n[i[r]]:o=!0;if(o)return}}(s)):o[e[i]]=n}}function Q(t,r){var n=r;return e(r)?n="["+r+"]":t&&(n="."+r),t+n}function $(t,e,r,n){var a,i=G(r),o=!0,l=r,s=n.replace("-1",0),u=!i&&Z(r,s),c=e[0];for(a=0;aa.max?r.set(n):r.set(+t)}},integer:{coerceFunction:function(t,r,n,a){t%1||!e(t)||void 0!==a.min&&ta.max?r.set(n):r.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var a="number"==typeof t;!0!==n.strict&&a?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){l(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return l(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(f(t,r))}},angle:{coerceFunction:function(t,r,n){"auto"===t?r.set("auto"):e(t)?r.set(at(+t)):r.set(n)}},subplotid:{coerceFunction:function(t,e,r){"string"==typeof t&&rt(r).test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!rt(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var a=t.split("+"),i=0;i=ot&&t<=lt?t:ct;if("string"!=typeof t&&"number"!=typeof t)return ct;t=String(t);var r=bt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var a=r&&"chinese"===e.substr(0,7),i=t.match(a?yt:mt);if(!i)return ct;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),u=Number(i[7]||0),c=Number(i[9]||0),f=Number(i[11]||0);if(r){if(2===o.length)return ct;var h;o=Number(o);try{var d=R.getComponentMethod("calendars","getCal")(e);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),h=d.newDate(o,d.toMonthIndex(o,l,p),s)}else h=d.newDate(o,Number(l),s)}catch(t){return ct}return h?(h.toJD()-gt)*ft+u*ht+c*dt+f*pt:ct}o=2===o.length?(Number(o)+2e3-xt)%100+xt:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,u,c));return g.setUTCFullYear(o),g.getUTCMonth()!==l?ct:g.getUTCDate()!==s?ct:g.getTime()+f*pt},ot=ut.MIN_MS=ut.dateTime2ms("-9999"),lt=ut.MAX_MS=ut.dateTime2ms("9999-12-31 23:59:59.9999"),ut.isDateTime=function(t,e){return ut.dateTime2ms(t,e)!==ct};var wt=90*ft,At=3*ht,Mt=5*dt;function Tt(t,e,r,n,a){if((e||r||n||a)&&(t+=" "+_t(e,2)+":"+_t(r,2),(n||a)&&(t+=":"+_t(n,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;t+="."+_t(a,i)}return t}ut.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ot&&t<=lt))return ct;e||(e=0);var n,a,i,o,l,s,u=Math.floor(10*st(t+.05,1)),c=Math.round(t-u/10);if(bt(r)){var f=Math.floor(c/ft)+gt,h=Math.floor(st(t,ft));try{n=R.getComponentMethod("calendars","getCal")(r).fromJD(f).formatDate("yyyy-mm-dd")}catch(t){n=vt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;a=e=ot+ft&&e<=lt-ft))return ct;var r=Math.floor(10*st(e+.05,1)),n=new Date(Math.round(e-r/10));return Tt(t.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ut.cleanDate=function(t,e,r){if(ut.isJSDate(t)||"number"==typeof t){if(bt(r))return _.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ut.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ut.isDateTime(t,r))return _.error("unrecognized date",t),e;return t};var kt=/%\d?f/g;function Et(t,e,r,n){t=t.replace(kt,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(e+.05));if(bt(n))try{t=R.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(a)}var Ct=[59,59.9,59.99,59.999,59.9999];ut.formatDate=function(t,r,n,a,i,o){if(i=bt(i)&&i,!r)if("y"===n)r=o.year;else if("m"===n)r=o.month;else{if("d"!==n)return function(t,r){var n=st(t+.05,ft),a=_t(Math.floor(n/ht),2)+":"+_t(st(Math.floor(n/dt),60),2);if("M"!==r){e(r)||(r=0);var i=(100+Math.min(st(t/pt,60),Ct[r])).toFixed(r).substr(1);r>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),a+=":"+i}return a}(t,n)+"\n"+Et(o.dayMonthYear,t,a,i);r=o.dayMonth+"\n"+o.year}return Et(r,t,a,i)};var St=3*ft;ut.incrementMonth=function(t,e,r){r=bt(r)&&r;var n=st(t,ft);if(t=Math.round(t-n),r)try{var a=Math.round(t/ft)+gt,i=R.getComponentMethod("calendars","getCal")(r),o=i.fromJD(a);return e%12?i.add(o,e,"m"):i.add(o,e/12,"y"),(o.toJD()-gt)*ft+n}catch(e){_.error("invalid ms "+t+" in calendar "+r)}var l=new Date(t+St);return l.setUTCMonth(l.getUTCMonth()+e)+n-St},ut.findExactDates=function(t,r){for(var n,a,i=0,o=0,l=0,s=0,u=bt(r)&&R.getComponentMethod("calendars","getCal")(r),c=0;c1||g<0||g>1?null:{x:t+s*g,y:e+f*g}}function zt(t,e,r,n,a){var i=n*t+a*e;if(i<0)return n*n+a*a;if(i>r){var o=n-t,l=a-e;return o*o+l*l}var s=n*e-a*t;return s*s/r}Pt.segmentsIntersect=Ft,Pt.segmentDistance=function(t,e,r,n,a,i,o,l){if(Ft(t,e,r,n,a,i,o,l))return 0;var s=r-t,u=n-e,c=o-a,f=l-i,h=s*s+u*u,d=c*c+f*f,p=Math.min(zt(s,u,h,a-t,i-e),zt(s,u,h,o-t,l-e),zt(c,f,d,t-a,e-i),zt(c,f,d,r-a,n-i));return Math.sqrt(p)},Pt.getTextLocation=function(t,e,r,n){if(t===Dt&&n===It||(Rt={},Dt=t,It=n),Rt[r])return Rt[r];var a=t.getPointAtLength(st(r-n/2,e)),i=t.getPointAtLength(st(r+n/2,e)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=t.getPointAtLength(st(r,e)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return Rt[r]=s,s},Pt.clearLocationCache=function(){Dt=null},Pt.getVisibleSegment=function(t,e,r){var n,a,i=e.left,o=e.right,l=e.top,s=e.bottom,u=0,c=t.getTotalLength(),f=c;function h(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(a=r);var u=r.xo?r.x-o:0,f=r.ys?r.y-s:0;return Math.sqrt(u*u+f*f)}for(var d=h(u);d;){if((u+=d+r)>f)return;d=h(u)}for(d=h(f);d;){if(u>(f-=d+r))return;d=h(f)}return{min:u,max:f,len:f-u,total:c,isClosed:0===u&&f===c&&Math.abs(n.x-a.x)<.1&&Math.abs(n.y-a.y)<.1}},Pt.findPointOnPath=function(t,e,r,n){for(var a,i,o,l=(n=n||{}).pathLength||t.getTotalLength(),s=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(l)[r]?-1:1,f=0,h=0,d=l;f0?d=a:h=a,f++}return i};var Nt=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},Bt=function(t){return t},jt=/^\w*$/,Ut={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Jt(t,e){return t>=e}Xt.findBin=function(t,r,n){if(e(r.start))return n?Math.ceil((t-r.start)/r.size-1e-9)-1:Math.floor((t-r.start)/r.size+1e-9);var a,i,o=0,l=r.length,s=0,u=l>1?(r[l-1]-r[0])/(l-1):1;for(i=u>=0?n?Wt:Yt:n?Jt:Zt,t+=1e-9*u*(n?-1:1)*(u>=0?1:-1);o90&&_.log("Long binary search..."),o-1},Xt.sorterAsc=function(t,e){return t-e},Xt.sorterDes=function(t,e){return e-t},Xt.distinctVals=function(t){var e=t.slice();e.sort(Xt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,a=n/(r||1)/1e4,i=[e[0]],o=0;oe[o]+a&&(n=Math.min(n,e[o+1]-e[o]),i.push(e[o+1]));return{vals:i,minDiff:n}},Xt.roundUp=function(t,e,r){for(var n,a=0,i=e.length-1,o=0,l=r?0:1,s=r?1:0,u=r?Math.ceil:Math.floor;an.length)&&(a=n.length),e(r)||(r=!1),$t(n[0])){for(o=new Array(a),i=0;it.length-1)return t[t.length-1];var n=r%1;return n*t[Math.ceil(r)]+(1-n)*t[Math.floor(r)]};var Kt={},te={};function ee(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}Kt.throttle=function(t,e,r){var n=te[t],a=Date.now();if(!n){for(var i in te)te[i].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},Kt.done=function(t){var e=te[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},Kt.clear=function(t){if(t)ee(te[t]),delete te[t];else for(var e in te)Kt.clear(e)};var re=function(t,r){if(t>0)return Math.log(t)/Math.LN10;var n=Math.log(Math.min(r[0],r[1]))/Math.LN10;return e(n)||(n=Math.log(Math.max(r[0],r[1]))/Math.LN10-6),n},ne={},ae=r.FP_SAFE,ie=r.BADNUM,oe=ne={};oe.nestedProperty=X,oe.keyedContainer=function(t,e,r,n){var a,i;r=r||"name",n=n||"value";var o={};i=e&&e.length?X(t,e).get():t,e=e||"",i=i||[];var l={};for(a=0;a2)return o[e]=2|o[e],u.set(t,null);if(s){for(a=e;a/g),l=0;lae?ie:e(t)?Number(t):ie:ie},oe.noop=M,oe.identity=Bt,oe.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},oe.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},oe.simpleMap=function(t,e,r,n){for(var a=t.length,i=new Array(a),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):l},oe.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},oe.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,a,i,o=t.length,l=2*o,s=2*e-1,u=new Array(s),c=new Array(o);for(r=0;r=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=t[a]*u[n];c[r]=i}return c},oe.syncOrAsync=function(t,e,r){var n;function a(){return oe.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(a).then(void 0,oe.promiseError);return r&&r(e)},oe.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},oe.noneOrAll=function(t,e,r){if(t){var n,a,i=!1,o=!0;for(n=0;n=0&&i%1==0){var p=a?a[d]:d,g=n?n[p]:p;f(g)&&(t[g].selected=1)}}},oe.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=oe.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},oe.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,i,o=Object.keys(t);for(n=0;n1?a+o[1]:"";if(i&&(o.length>1||l.length>4||r))for(;n.test(l);)l=l.replace(n,"$1"+i+"$2");return l+s};var ue=/%{([^\s%{}]*)}/g,ce=/^\w*$/;oe.templateString=function(t,e){var r={};return t.replace(ue,function(t,n){return ce.test(n)?e[n]||"":(r[n]=r[n]||oe.nestedProperty(e,n).get,r[n]()||"")})};oe.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,a=0,i=0;i=48&&o<=57,u=l>=48&&l<=57;if(s&&(n=10*n+o-48),u&&(a=10*a+l-48),!s||!u){if(n!==a)return n-a;if(o!==l)return o-l}}return a-n};var fe=2e9;oe.seedPseudoRandom=function(){fe=2e9},oe.pseudoRandom=function(){var t=fe;return fe=(69069*fe+1)%4294967296,Math.abs(fe-t)<429496729?oe.pseudoRandom():fe/4294967296};var he=ne.extendFlat,de=ne.isPlainObject,pe={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},ge={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},ve=pe.flags.slice().concat(["clearCalc","fullReplot"]),me=ge.flags.slice().concat("layoutReplot"),ye={traces:pe,layout:ge,traceFlags:function(){return xe(ve)},layoutFlags:function(){return xe(me)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),a=0;an?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},Le={dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},Oe=Le.dash,Re=m.extendFlat,De={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:S.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks+margins"},titlefont:k({editType:"ticks+margins"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"plot+margins",impliedEdits:{"^autorange":!1}}],editType:"plot+margins",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[Ce.idRegex.x.toString(),Ce.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks+margins",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks+margins"},tick0:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks+margins"},ticktext:{valType:"data_array",editType:"ticks+margins"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks+margins"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:S.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks+margins"},automargin:{valType:"boolean",dflt:!1,editType:"ticks+margins"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:Re({},Oe,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:k({editType:"ticks+margins"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks+margins"},tickprefix:{valType:"string",dflt:"",editType:"ticks+margins"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},ticksuffix:{valType:"string",dflt:"",editType:"ticks+margins"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks+margins"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks+margins"},tickformat:{valType:"string",dflt:"",editType:"ticks+margins"},tickformatstops:{_isLinkedToArray:"tickformatstop",dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks+margins"},{valType:"any",editType:"ticks+margins"}],editType:"ticks+margins"},value:{valType:"string",dflt:"",editType:"ticks+margins"},editType:"ticks+margins"},hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:S.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:S.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:S.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",Ce.idRegex.x.toString(),Ce.idRegex.y.toString()],editType:"plot+margins"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot+margins"},overlaying:{valType:"enumerated",values:["free",Ce.idRegex.x.toString(),Ce.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot+margins"},{valType:"number",min:0,max:1,editType:"plot+margins"}],dflt:[0,1],editType:"plot+margins"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot+margins"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks+margins"}}},Ie={},Pe=Ie={};Pe.defaults=S.defaults;var Fe=Pe.defaultLine=S.defaultLine;Pe.lightLine=S.lightLine;var ze=Pe.background=S.background;function Ne(t){if(e(t)||"string"!=typeof t)return t;var r=t.trim();if("rgb"!==r.substr(0,3))return t;var n=r.match(/^rgba?\s*\(([^()]*)\)$/);if(!n)return t;var a=n[1].trim().split(/\s*[\s,]\s*/),i="a"===r.charAt(3)&&4===a.length;if(!i&&3!==a.length)return t;for(var o=0;o=0))return t;if(3===o)a[o]>1&&(a[o]=1);else if(a[o]>=1)return t}var l=Math.round(255*a[0])+", "+Math.round(255*a[1])+", "+Math.round(255*a[2]);return i?"rgba("+l+", "+a[3]+")":"rgb("+l+")"}Pe.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},Pe.rgb=function(t){return Pe.tinyRGB(l(t))},Pe.opacity=function(t){return t?l(t).getAlpha():0},Pe.addOpacity=function(t,e){var r=l(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},Pe.combine=function(t,e){var r=l(t).toRgb();if(1===r.a)return l(t).toRgbString();var n=l(e||ze).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},i={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return l(i).toRgbString()},Pe.contrast=function(t,e,r){var n=l(t);return 1!==n.getAlpha()&&(n=l(Pe.combine(t,ze))),(n.isDark()?e?n.lighten(e):ze:r?n.darken(r):Fe).toString()},Pe.stroke=function(t,e){var r=l(e);t.style({stroke:Pe.tinyRGB(r),"stroke-opacity":r.getAlpha()})},Pe.fill=function(t,e){var r=l(e);t.style({fill:Pe.tinyRGB(r),"fill-opacity":r.getAlpha()})},Pe.clean=function(t){if(t&&"object"==typeof t){var e,r,n,a,i=Object.keys(t);for(e=0;e0)return Math.log(t)/Math.LN10;if(t<=0&&e&&r.range&&2===r.range.length){var n=r.range[0],a=r.range[1];return.5*(n+a-3*i*Math.abs(n-a))}return We}function l(t,n,a){var i=qe(t,a||r.calendar);if(i===We){if(!e(t))return We;i=qe(new Date(+t))}return i}function s(t,e,n){return He(t,e,n||r.calendar)}function u(t){return r._categories[Math.round(t)]}function c(t){if(r._categoriesMap){var n=r._categoriesMap[t];if(void 0!==n)return n}if(e(t))return+t}function f(n){return e(n)?t.round(r._b+r._m*n,2):We}function h(t){return(t-r._b)/r._m}r.c2l="log"===r.type?o:Ge,r.l2c="log"===r.type?Ye:Ge,r.l2p=f,r.p2l=h,r.c2p="log"===r.type?function(t,e){return f(o(t,e))}:f,r.p2c="log"===r.type?function(t){return Ye(h(t))}:h,-1!==["linear","-"].indexOf(r.type)?(r.d2r=r.r2d=r.d2c=r.r2c=r.d2l=r.r2l=Ve,r.c2d=r.c2r=r.l2d=r.l2r=Ge,r.d2p=r.r2p=function(t){return r.l2p(Ve(t))},r.p2d=r.p2r=h,r.cleanPos=Ge):"log"===r.type?(r.d2r=r.d2l=function(t,e){return o(Ve(t),e)},r.r2d=r.r2c=function(t){return Ye(Ve(t))},r.d2c=r.r2l=Ve,r.c2d=r.l2r=Ge,r.c2r=o,r.l2d=Ye,r.d2p=function(t,e){return r.l2p(r.d2r(t,e))},r.p2d=function(t){return Ye(h(t))},r.r2p=function(t){return r.l2p(Ve(t))},r.p2r=h,r.cleanPos=Ge):"date"===r.type?(r.d2r=r.r2d=ne.identity,r.d2c=r.r2c=r.d2l=r.r2l=l,r.c2d=r.c2r=r.l2d=r.l2r=s,r.d2p=r.r2p=function(t,e,n){return r.l2p(l(t,0,n))},r.p2d=r.p2r=function(t,e,r){return s(h(t),e,r)},r.cleanPos=function(t){return ne.cleanDate(t,We,r.calendar)}):"category"===r.type&&(r.d2c=r.d2l=function(t){if(null!==t&&void 0!==t){if(void 0===r._categoriesMap&&(r._categoriesMap={}),void 0!==r._categoriesMap[t])return r._categoriesMap[t];r._categories.push(t);var e=r._categories.length-1;return r._categoriesMap[t]=e,e}return We},r.r2d=r.c2d=r.l2d=u,r.d2r=r.d2l_noadd=c,r.r2c=function(t){var e=c(t);return void 0!==e?e:r.fraction2r(.5)},r.l2r=r.c2r=Ge,r.r2l=c,r.d2p=function(t){return r.l2p(r.r2c(t))},r.p2d=function(t){return u(h(t))},r.r2p=r.d2p,r.p2r=h,r.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Ge(t)}),r.fraction2r=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return r.l2r(e+t*(n-e))},r.r2fraction=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return(r.r2l(t)-e)/(n-e)},r.cleanRange=function(t,n){n||(n={}),t||(t="range");var i,o,l=ne.nestedProperty(r,t).get();if(o=(o="date"===r.type?ne.dfltRange(r.calendar):"y"===a?Ce.DFLTRANGEY:n.dfltRange||Ce.DFLTRANGEX).slice(),l&&2===l.length)for("date"===r.type&&(l[0]=ne.cleanDate(l[0],We,r.calendar),l[1]=ne.cleanDate(l[1],We,r.calendar)),i=0;i<2;i++)if("date"===r.type){if(!ne.isDateTime(l[i],r.calendar)){r[t]=o;break}if(r.r2l(l[0])===r.r2l(l[1])){var s=ne.constrain(r.r2l(l[0]),ne.MIN_MS+1e3,ne.MAX_MS-1e3);l[0]=r.l2r(s-1e3),l[1]=r.l2r(s+1e3);break}}else{if(!e(l[i])){if(!e(l[1-i])){r[t]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Xe?l[i]=-Xe:l[i]>Xe&&(l[i]=Xe),l[0]===l[1]){var u=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=u,l[1]+=u}}else ne.nestedProperty(r,t).set(o)},r.setScale=function(t){var e=n._size;if(r._categories||(r._categories=[]),r._categoriesMap||(r._categoriesMap={}),r.overlaying){var i=Se.getFromId({_fullLayout:n},r.overlaying);r.domain=i.domain}var o=t&&r._r?"_r":"range",l=r.calendar;r.cleanRange(o);var s=r.r2l(r[o][0],l),u=r.r2l(r[o][1],l);if("y"===a?(r._offset=e.t+(1-r.domain[1])*e.h,r._length=e.h*(r.domain[1]-r.domain[0]),r._m=r._length/(s-u),r._b=-r._m*u):(r._offset=e.l+r.domain[0]*e.w,r._length=e.w*(r.domain[1]-r.domain[0]),r._m=r._length/(u-s),r._b=-r._m*s),!isFinite(r._m)||!isFinite(r._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},r.makeCalcdata=function(t,e){var n,a,i,o,l=r.type,s="date"===l&&t[e+"calendar"];if(e in t){if(n=t[e],o=t._length||n.length,ne.isTypedArray(n)&&("linear"===l||"log"===l)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(a=new Array(o),i=0;i=r.r2l(r.range[0])&&n<=r.r2l(r.range[1])},r.clearCalc=function(){r._min=[],r._max=[],r._categories=(r._initialCategories||[]).slice(),r._categoriesMap={};for(var t=0;t0?Number(s):l;else if("string"!=typeof s)r.dtick=l;else{var u=s.charAt(0),c=s.substr(1);((c=e(c)?Number(c):0)<=0||!("date"===a&&"M"===u&&c===Math.round(c)||"log"===a&&"L"===u||"log"===a&&"D"===u&&(1===c||2===c)))&&(r.dtick=l)}var f="date"===a?ne.dateTick0(r.calendar):0,h=n("tick0",f);"date"===a?r.tick0=ne.cleanDate(h,f):e(h)&&"D1"!==s&&"D2"!==s?r.tick0=Number(h):r.tick0=f}else{void 0===n("tickvals")?r.tickmode="auto":n("ticktext")}},tr=function(e,r,n,a,i){var o=a.letter,l=a.font||{},s=n("visible",!a.cheateronly),u=r.type;"date"===u&&R.getComponentMethod("calendars","handleDefaults")(e,r,"calendar",a.calendar);Ze(r,i);var c=n("autorange",!r.isValidRange(e.range));if(r._rangesliderAutorange=!1,c&&n("rangemode"),n("range"),r.cleanRange(),function(t,e,r){if("category"===e.type){var n,a=t.categoryarray,i=Array.isArray(a)&&a.length>0;i&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),i||"array"!==o||(e.categoryorder="trace")}}(e,r,n),r._initialCategories="category"===u?function(e,r,n,a){switch(r){case"array":return Array.isArray(n)?n.slice():[];case"category ascending":return Ue(e,t.ascending,a);case"category descending":return Ue(e,t.descending,a);case"trace":default:return[]}}(o,r.categoryorder,r.categoryarray,a.data):[],"category"===u||a.noHover||n("hoverformat"),!s)return r;var f=n("color"),h=f===e.color?f:l.color;return n("title",i._dfltTitle[o]),ne.coerceFont(n,"titlefont",{family:l.family,size:Math.round(1.2*l.size),color:h}),Ke(e,r,n,u),Je(e,r,n,u,a),Qe(e,r,n,a),function(t,e,r,n){var a=(n=n||{}).dfltColor;function i(r,a){return ne.coerce2(t,e,n.attributes,r,a)}var o=i("linecolor",a),l=i("linewidth");r("showline",n.showLine||!!o||!!l)||(delete e.linecolor,delete e.linewidth);var s=i("gridcolor",Be(a,n.bgColor,n.blend||je).toRgbString()),u=i("gridwidth");if(r("showgrid",n.showGrid||!!s||!!u)||(delete e.gridcolor,delete e.gridwidth),!n.noZeroLine){var c=i("zerolinecolor",a),f=i("zerolinewidth");r("zeroline",n.showGrid||!!c||!!f)||(delete e.zerolinecolor,delete e.zerolinewidth)}}(e,r,n,{dfltColor:f,bgColor:a.bgColor,showGrid:a.showGrid,attributes:De}),(r.showline||r.ticks)&&n("mirror"),a.automargin&&n("automargin"),r},er=Se.id2name,rr=function(t,e,r,n,a){var i=a._axisConstraintGroups,o=e._id,l=o.charAt(0);if(!e.fixedrange&&(r("constrain"),ne.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===l?["left","center","right"]:["bottom","middle","top"],dflt:"x"===l?"center":"middle"}},"constraintoward"),t.scaleanchor)){var s=function(t,e,r,n){var a,i,o,l,s=n[er(e)].type,u=[];for(i=0;ip[1]-.01&&(r.domain=o),ne.noneOrAll(t.domain,r.domain,o)}return n("layer"),r},ar=r.BADNUM,ir=function(t,r){return function(t,r){for(var n,a=0,i=0,o=Math.max(1,(t.length-1)/1e3),l=0;l2*i}(t,r)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,a=0,i=0;i2*n}(t)?"category":function(t){if(!t)return!1;for(var r=0;r=0;a--,i++)e=t[a],n[i]=[1-e[0],e[1]];return n},hr=function(t,e,r,n){var a,i;r?(a=ne.nestedProperty(t,r).get(),i=ne.nestedProperty(t._input,r).get()):(a=t,i=t._input);var o=n+"auto",l=n+"min",u=n+"max",c=a[o],f=a[l],h=a[u],d=a.colorscale;!1===c&&void 0!==f||(f=ne.aggNums(Math.min,null,e)),!1===c&&void 0!==h||(h=ne.aggNums(Math.max,null,e)),f===h&&(f-=.5,h+=.5),a[l]=f,a[u]=h,i[l]=f,i[u]=h,i[o]=!1!==c||void 0===f&&void 0===h,a.autocolorscale&&(d=f*h<0?s.RdBu:f>=0?s.Reds:s.Blues,i.colorscale=d,a.reversescale&&(d=fr(d)),a.colorscale=d)},dr=m.extendFlat,pr=(0,ye.overrideAll)({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:.5,min:-2,max:3},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle"},ypad:{valType:"number",min:0,dflt:10},outlinecolor:De.linecolor,outlinewidth:De.linewidth,bordercolor:De.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},tickmode:De.tickmode,nticks:De.nticks,tick0:De.tick0,dtick:De.dtick,tickvals:De.tickvals,ticktext:De.ticktext,ticks:dr({},De.ticks,{dflt:""}),ticklen:De.ticklen,tickwidth:De.tickwidth,tickcolor:De.tickcolor,showticklabels:De.showticklabels,tickfont:k({}),tickangle:De.tickangle,tickformat:De.tickformat,tickformatstops:De.tickformatstops,tickprefix:De.tickprefix,showtickprefix:De.showtickprefix,ticksuffix:De.ticksuffix,showticksuffix:De.showticksuffix,separatethousands:De.separatethousands,exponentformat:De.exponentformat,showexponent:De.showexponent,title:{valType:"string"},titlefont:k({}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}},"colorbars","from-root"),gr=function(t){return void 0!==s[t]||c(t)},vr=function(t,r,n,a,i){var o,l=i.prefix,s=i.cLetter,u=l.slice(0,l.length-1),c=l?ne.nestedProperty(t,u).get()||{}:t,f=l?ne.nestedProperty(r,u).get()||{}:r,h=c[s+"min"],d=c[s+"max"],p=c.colorscale;a(l+s+"auto",!(e(h)&&e(d)&&h","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},Ar={},Mr=_r.LINE_SPACING;function Tr(t,e){return t.node().getBoundingClientRect()[e]}var kr=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;Ar.convertToTspans=function(e,r,n){var a=e.text(),i=!e.attr("data-notex")&&"undefined"!=typeof MathJax&&a.match(kr),o=t.select(e.node().parentNode);if(!o.empty()){var l=e.attr("class")?e.attr("class").split(" ")[0]:"text";return l+="-math",o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove(),e.style("display",null).attr({"data-unformatted":a,"data-math":"N"}),i?(r&&r._promises||[]).push(new Promise(function(r){e.style("display","none");var u=parseInt(e.node().style.fontSize,10),c={fontSize:u};!function(e,r,n){var a="math-output-"+ne.randstr([],64),i=t.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=e,o.replace(Er,"\\lt ").replace(Cr,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var r=t.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())ne.log("There was an error in the tex syntax.",e),n();else{var a=i.select("svg").node().getBoundingClientRect();n(i.select(".MathJax_SVG"),r,a)}i.remove()})}(i[2],c,function(t,i,c){o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove();var f=t&&t.select("svg");if(!f||!f.node())return s(),void r();var h=o.append("g").classed(l+"-group",!0).attr({"pointer-events":"none","data-unformatted":a,"data-math":"Y"});h.node().appendChild(f.node()),i&&i.node()&&f.node().insertBefore(i.node().cloneNode(!0),f.node().firstChild),f.attr({class:l,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var d=e.node().style.fill||"black";f.select("g").attr({fill:d,stroke:d});var p=Tr(f,"width"),g=Tr(f,"height"),v=+e.attr("x")-p*{start:0,middle:.5,end:1}[e.attr("text-anchor")||"start"],m=-(u||Tr(e,"height"))/4;"y"===l[0]?(h.attr({transform:"rotate("+[-90,+e.attr("x"),+e.attr("y")]+") translate("+[-p/2,m-g/2]+")"}),f.attr({x:+e.attr("x"),y:+e.attr("y")})):"l"===l[0]?f.attr({x:e.attr("x"),y:m-g/2}):"a"===l[0]?f.attr({x:0,y:m}):f.attr({x:v,y:+e.attr("y")+m-g/2}),n&&n.call(e,h),r(h)})})):s(),e}function s(){o.empty()||(l=e.attr("class")+"-math",o.select("svg."+l).remove()),e.text("").style("white-space","pre"),function(e,r){r=(n=r,function(t,e){if(!t)return"";for(var r=0;r1)for(var i=1;i doesnt match end tag <"+t+">. Pretending it did match.",r),a=o[o.length-1].node}else ne.log("Ignoring unexpected end tag .",r)}Br.test(r)?s():(a=e,o=[{node:e}]);for(var h=r.split(zr),d=0;d|>|>)/g;var Sr={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"},Lr={sub:"0.3em",sup:"-0.6em"},Or={sub:"-0.21em",sup:"0.42em"},Rr="\u200b",Dr=["http:","https:","mailto:","",void 0,":"],Ir=new RegExp("]*)?/?>","g"),Pr=Object.keys(wr.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:wr.entityToUnicode[t]}}),Fr=/(\r\n?|\n)/g,zr=/(<[^<>]*>)/,Nr=/<(\/?)([^ >]*)(\s+(.*))?>/i,Br=//i,jr=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Ur=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Vr=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Hr=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function qr(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var Gr=/(^|;)\s*color:/;function Xr(t,e,r){var n,a,i,o=r.horizontalAlign,l=r.verticalAlign||"top",s=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-n.height}:"middle"===l?function(){return s.top+(s.height-n.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-n.width}:"center"===o?function(){return s.left+(s.width-n.width)/2}:function(){return s.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:a()-u.top+"px",left:i()-u.left+"px","z-index":1e3}),this}}Ar.plainText=function(t){return(t||"").replace(Ir," ")},Ar.lineCount=function(t){return t.selectAll("tspan.line").size()||1},Ar.positionText=function(e,r,n){return e.each(function(){var e=t.select(this);function a(t,r){return void 0===r?null===(r=e.attr(t))&&(e.attr(t,0),r=0):e.attr(t,r),r}var i=a("x",r),o=a("y",n);"text"===this.nodeName&&e.selectAll("tspan.line").attr({x:i,y:o})})},Ar.makeEditable=function(e,r){var n=r.gd,a=r.delegate,i=t.dispatch("edit","input","cancel"),o=a||e;if(e.style({"pointer-events":a?"none":"all"}),1!==e.size())throw new Error("boo");function l(){var a,l,u,c;a=t.select(n).select(".svg-container"),l=a.append("div"),u=e.node().style,c=parseFloat(u.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:r.fill||u.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||e.attr("data-unformatted")).call(Xr(e,a,r)).on("blur",function(){n._editing=!1,e.text(this.textContent).style({opacity:1});var r,a=t.select(this).attr("class");(r=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(r).style({opacity:0});var o=this.textContent;t.select(this).transition().duration(0).remove(),t.select(document).on("mouseup",null),i.edit.call(e,o)}).on("focus",function(){var e=this;n._editing=!0,t.select(document).on("mouseup",function(){if(t.event.target===e)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===t.event.which?(n._editing=!1,e.style({opacity:1}),t.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(e,this.textContent)):(i.input.call(e,this.textContent),t.select(this).call(Xr(e,a,r)))}).on("keydown",function(){13===t.event.which&&this.blur()}).call(s),e.style({opacity:0});var f,h=o.attr("class");(f=h?"."+h.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(f).style({opacity:0})}function s(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return r.immediate?l():o.on("click",l),t.rebind(e,i,"on")};var Wr=function(t){var r=t.marker,n=r.sizeref||1,a=r.sizemin||0,i="area"===r.sizemode?function(t){return Math.sqrt(t/n)}:function(t){return t/n};return function(t){var r=i(t/2);return e(r)&&r>0?Math.max(r,a):0}},Yr={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("markers")},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return ne.isPlainObject(t.marker)&&ne.isArrayOrTypedArray(t.marker.size)}},Zr={},Jr=_r.LINE_SPACING,Qr=h.DESELECTDIM,$r=Zr={};$r.font=function(t,e,r,n){ne.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Ie.fill,n)},$r.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},$r.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},$r.setRect=function(t,e,r,n,a){t.call($r.setPosition,e,r).call($r.setSize,n,a)},$r.translatePoint=function(t,r,n,a){var i=n.c2p(t.x),o=a.c2p(t.y);return!!(e(i)&&e(o)&&r.node())&&("text"===r.node().nodeName?r.attr("x",i).attr("y",o):r.attr("transform","translate("+i+","+o+")"),!0)},$r.translatePoints=function(e,r,n){e.each(function(e){var a=t.select(this);$r.translatePoint(e,a,r,n)})},$r.hideOutsideRangePoint=function(t,e,r,n,a,i){e.attr("display",r.isPtWithinRange(t,a)&&n.isPtWithinRange(t,i)?null:"none")},$r.hideOutsideRangePoints=function(e,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var a=r.xaxis,i=r.yaxis;e.each(function(r){var o=r[0].trace,l=o.xcalendar,s=o.ycalendar;e.selectAll(n).each(function(e){$r.hideOutsideRangePoint(e,t.select(this),a,i,l,s)})})}},$r.crispRound=function(t,r,n){return r&&e(r)?t._context.staticPlot?r:r<1?1:Math.round(r):n||0},$r.singleLineStyle=function(t,e,r,n,a){e.style("fill","none");var i=(((t||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";Ie.stroke(e,n||i.color),$r.dashLine(e,l,o)},$r.lineGroupStyle=function(e,r,n,a){e.style("fill","none").each(function(e){var i=(((e||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";t.select(this).call(Ie.stroke,n||i.color).call($r.dashLine,l,o)})},$r.dashLine=function(t,e,r){r=+r||0,e=$r.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},$r.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},$r.singleFillStyle=function(e){var r=(((t.select(e.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&e.call(Ie.fill,r)},$r.fillGroupStyle=function(e){e.style("stroke-width",0).each(function(r){var n=t.select(this);try{n.call(Ie.fill,r[0].trace.fillcolor)}catch(t){ne.error(t,e),n.remove()}})},$r.symbolNames=[],$r.symbolFuncs=[],$r.symbolNeedLines={},$r.symbolNoDot={},$r.symbolNoFill={},$r.symbolList=[],Object.keys(br).forEach(function(t){var e=br[t];$r.symbolList=$r.symbolList.concat([e.n,t,e.n+100,t+"-open"]),$r.symbolNames[e.n]=t,$r.symbolFuncs[e.n]=e.f,e.needLine&&($r.symbolNeedLines[e.n]=!0),e.noDot?$r.symbolNoDot[e.n]=!0:$r.symbolList=$r.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&($r.symbolNoFill[e.n]=!0)});var Kr=$r.symbolNames.length,tn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function en(t,e){var r=t%100;return $r.symbolFuncs[r](e)+(t>=200?tn:"")}$r.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=$r.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=Kr||t>=400?0:Math.floor(Math.max(t,0))};var rn={x1:1,x2:0,y1:0,y2:0},nn={x1:0,x2:0,y1:1,y2:0};$r.gradient=function(e,r,n,a,i,o){var s=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([a+i+o],ne.identity);s.exit().remove(),s.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var e=t.select(this);"horizontal"===a?e.attr(rn):"vertical"===a&&e.attr(nn),e.attr("id",n);var r=l(i),s=l(o);e.append("stop").attr({offset:"0%","stop-color":Ie.tinyRGB(s),"stop-opacity":s.getAlpha()}),e.append("stop").attr({offset:"100%","stop-color":Ie.tinyRGB(r),"stop-opacity":r.getAlpha()})}),e.style({fill:"url(#"+n+")","fill-opacity":null})},$r.initGradients=function(t){var e=t._fullLayout._defs.selectAll(".gradients").data([0]);e.enter().append("g").classed("gradients",!0),e.selectAll("linearGradient,radialGradient").remove()},$r.singlePointStyle=function(t,e,r,n,a,i){var o=r.marker;!function(t,e,r,n,a,i,o,l){if(R.traceIs(r,"symbols")){var s=Wr(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===i.size?3:Yr.isBubble(r)?s(t.ms):(i.size||6)/2,t.mrc=e;var n=$r.symbolNumber(t.mx||i.symbol)||0;return t.om=n%200>=100,en(n,e)})}e.style("opacity",function(t){return(t.mo+1||i.opacity+1)-1});var u,c,f,h=!1;if(t.so?(f=o.outlierwidth,c=o.outliercolor,u=i.outliercolor):(f=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=a(t.mlc):ne.isArrayOrTypedArray(o.color)?Ie.defaultLine:o.color,ne.isArrayOrTypedArray(i.color)&&(u=Ie.defaultLine,h=!0),u="mc"in t?t.mcc=n(t.mc):i.color||"rgba(0,0,0,0)"),t.om)e.call(Ie.stroke,u).style({"stroke-width":(f||1)+"px",fill:"none"});else{e.style("stroke-width",f+"px");var d=i.gradient,p=t.mgt;if(p?h=!0:p=d&&d.type,p&&"none"!==p){var g=t.mgc;g?h=!0:g=d.color;var v="g"+l._fullLayout._uid+"-"+r.uid;h&&(v+="-"+t.i),e.call($r.gradient,l,v,p,u,g)}else e.call(Ie.fill,u);f&&e.call(Ie.stroke,c)}}(t,e,r,n,a,o,o.line,i)},$r.pointStyle=function(e,r,n){if(e.size()){var a=r.marker,i=$r.tryColorscale(a,""),o=$r.tryColorscale(a,"line");e.each(function(e){$r.singlePointStyle(e,t.select(this),r,i,o,n)})}},$r.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},a=t.marker||{},i=r.marker||{},o=n.marker||{},l=a.opacity,s=i.opacity,u=o.opacity,c=void 0!==s,f=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||f){if(!t.selected)return f?u:Qr*(r?e:l);if(c)return s}};var h=i.color,d=o.color;(h||d)&&(e.colorFn=function(t){if(t.selected){if(h)return h}else if(d)return d});var p=i.size,g=o.size,v=void 0!==p,m=void 0!==g;return(v||m)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?v?p/2:e:m?g/2:e}),e},$r.selectedPointStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=$r.makeSelectedPointStyleFns(r),a=r.marker||{};e.each(function(e){var r=t.select(this),a=n.opacityFn(e);void 0!==a&&r.style("opacity",a)}),n.colorFn&&e.each(function(e){var r=t.select(this),a=n.colorFn(e);a&&Ie.fill(r,a)}),R.traceIs(r,"symbols")&&n.sizeFn&&e.each(function(e){var r=t.select(this),i=e.mx||a.symbol||0,o=n.sizeFn(e);r.attr("d",en($r.symbolNumber(i),o)),e.mrc2=o})}},$r.tryColorscale=function(t,e){var r=e?ne.nestedProperty(t,e).get():t,n=r.colorscale,a=r.color;return n&&ne.isArrayOrTypedArray(a)?xr.makeColorScaleFunc(xr.extractScale(n,r.cmin,r.cmax)):ne.identity};var an={start:1,end:-1,middle:0,bottom:1,top:-1};function on(e,r,n,a){var i=t.select(e.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",l=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",s=a?a/.8+1:0,u=(Ar.lineCount(e)-1)*Jr+1,c=an[l]*s,f=.75*n+an[o]*s+(an[o]-1)*u*n/2;e.attr("text-anchor",l),i.attr("transform","translate("+c+","+f+")")}function ln(t,r){var n=t.ts||r.textfont.size;return e(n)&&n>0?n:0}$r.textPointStyle=function(e,r,n){e.each(function(e){var a=t.select(this),i=ne.extractOption(e,r,"tx","text");if(i){var o=e.tp||r.textposition,l=ln(e,r);a.call($r.font,e.tf||r.textfont.family,l,e.tc||r.textfont.color).text(i).call(Ar.convertToTspans,n).call(on,o,l,e.mrc)}else a.remove()})},$r.selectedTextStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=r.selected||{},a=r.unselected||{};e.each(function(e){var i,o=t.select(this),l=e.tc||r.textfont.color,s=e.tp||r.textposition,u=ln(e,r),c=(n.textfont||{}).color,f=(a.textfont||{}).color;e.selected?c&&(i=c):f?i=f:c||(i=Ie.addOpacity(l,Qr)),i&&Ie.fill(o,i),on(o,s,u,e.mrc2||e.mrc)})}};var sn=.5;function un(e,r,n,a){var i=e[0]-r[0],o=e[1]-r[1],l=n[0]-r[0],s=n[1]-r[1],u=Math.pow(i*i+o*o,sn/2),c=Math.pow(l*l+s*s,sn/2),f=(c*c*i-u*u*l)*a,h=(c*c*o-u*u*s)*a,d=3*c*(u+c),p=3*u*(u+c);return[[t.round(r[0]+(d&&f/d),2),t.round(r[1]+(d&&h/d),2)],[t.round(r[0]-(p&&f/p),2),t.round(r[1]-(p&&h/p),2)]]}$r.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],a=[];for(r=1;r=1e4&&($r.savedBBoxes={},hn=0),n&&($r.savedBBoxes[n]=p),hn++,ne.extendFlat({},p)},$r.setClipUrl=function(e,r){if(r){var n="#"+r,a=t.select("base");a.size()&&a.attr("href")&&(n=window.location.href.split("#")[0]+n),e.attr("clip-path","url("+n+")")}else e.attr("clip-path",null)},$r.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},$r.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||0,r=r||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+e+", "+r+")").trim(),t[a]("transform",i),i},$r.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},$r.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||1,r=r||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+e+", "+r+")").trim(),t[a]("transform",i),i},$r.setPointGroupScale=function(t,e,r){var n,a,i;return e=e||1,r=r||1,a=1===e&&1===r?"":" scale("+e+","+r+")",i=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(i,""),n=(n+=a).trim(),this.setAttribute("transform",n)}),a};var pn=/translate\([^)]*\)\s*$/;$r.setTextPointsScale=function(e,r,n){e.each(function(){var e,a=t.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(pn);e=1===r&&1===n?[]:["translate("+o+","+l+")","scale("+r+","+n+")","translate("+-o+","+-l+")"],s&&e.push(s),a.attr("transform",e.join(" "))}})};var gn={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500},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"]}}},vn={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}},mn=m.extendFlat,yn=function(t,e,r){return{color:{valType:"color",arrayOk:!0,editType:e||"style"},colorscale:mn({},cr.colorscale,{}),cauto:mn({},cr.zauto,{impliedEdits:{cmin:void 0,cmax:void 0}}),cmax:mn({},cr.zmax,{editType:e||cr.zmax.editType,impliedEdits:{cauto:!1}}),cmin:mn({},cr.zmin,{editType:e||cr.zmin.editType,impliedEdits:{cauto:!1}}),autocolorscale:mn({},cr.autocolorscale,{dflt:!1===r?r:cr.autocolorscale.dflt}),reversescale:mn({},cr.reversescale,{})}},xn={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20},bn=Le.dash,_n=m.extendFlat,wn={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:_n({},bn,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:_n({symbol:{valType:"enumerated",values:Zr.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},showscale:{valType:"boolean",dflt:!1,editType:"calc"},colorbar:pr,line:_n({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},yn()),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},yn()),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:k({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}},An=wn.marker,Mn={r:wn.r,t:wn.t,marker:{color:An.color,size:An.size,symbol:An.symbol,opacity:An.opacity,editType:"calc"}},Tn=m.extendFlat,kn=ye.overrideAll,En=Tn({},De.domain,{});function Cn(t,e){return Tn({},e,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}var Sn=kn({radialaxis:Cn(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:En,orientation:{valType:"number"}}),angularaxis:Cn(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:En}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested"),Ln={},On=ne.extendFlat,Rn=ne.extendDeepAll,Dn="_isSubplotObj",In="_isLinkedToArray",Pn=[Dn,In,"_arrayAttrRegexps","_deprecated"];function Fn(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(zn(e[r]))r++;else if(r=i.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!zn(o))return!1;t=i[a][o]}else t=i[a]}else t=i}}return t}function zn(t){return t===Math.round(t)&&t>=0}function Nn(t){return function(t){Ln.crawl(t,function(t,e,r){Ln.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):ne.isPlainObject(t)&&(t.role="object")})}(t),function(t){Ln.crawl(t,function(t,e,r){if(!t)return;var n=t[In];if(!n)return;delete t[In],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),t}function Bn(t,e,r){var n=ne.nestedProperty(t,r),a=Rn({},e.layoutAttributes);a[Dn]=!0,n.set(a)}function jn(t,e,r){var n=ne.nestedProperty(t,r);n.set(Rn(n.get()||{},e))}Ln.IS_SUBPLOT_OBJ=Dn,Ln.IS_LINKED_TO_ARRAY=In,Ln.DEPRECATED="_deprecated",Ln.UNDERSCORE_ATTRS=Pn,Ln.get=function(){var t={};R.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:Mn},r={}):(e=R.modules[t]._module,r=e.basePlotModule);var n={type:null};Rn(n,C),Rn(n,e.attributes),r.attributes&&Rn(n,r.attributes);n.type=t;var a={meta:e.meta||{},attributes:Nn(n)};if(e.layoutAttributes){var i={};Rn(i,e.layoutAttributes),a.layoutAttributes=Nn(i)}return a}(e)});var e,r={};return Object.keys(R.transformsRegistry).forEach(function(t){r[t]=function(t){var e=R.transformsRegistry[t],r=Rn({},e.attributes);return Object.keys(R.componentsRegistry).forEach(function(e){var n=R.componentsRegistry[e];n.schema&&n.schema.transforms&&n.schema.transforms[t]&&Object.keys(n.schema.transforms[t]).forEach(function(e){jn(r,n.schema.transforms[t][e],e)})}),{attributes:Nn(r)}}(t)}),{defs:{valObjects:ne.valObjectMeta,metaKeys:Pn.concat(["description","role","editType","impliedEdits"]),editType:{traces:ye.traces,layout:ye.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in Rn(r,O),R.subplotsRegistry)if((e=R.subplotsRegistry[t]).layoutAttributes)if("cartesian"===e.name)Bn(r,e,"xaxis"),Bn(r,e,"yaxis");else{var n="subplot"===e.attr?e.name:e.attr;Bn(r,e,n)}for(t in r=function(t){return On(t,{radialaxis:Sn.radialaxis,angularaxis:Sn.angularaxis}),On(t,Sn.layout),t}(r),R.componentsRegistry){var a=(e=R.componentsRegistry[t]).schema;if(a&&(a.subplots||a.layout)){var i=a.subplots;if(i&&i.xaxis&&!i.yaxis)for(var o in i.xaxis)delete r.yaxis[o]}else e.layoutAttributes&&jn(r,e.layoutAttributes,e.name)}return{layoutAttributes:Nn(r)}}(),transforms:r,frames:(e={frames:ne.extendDeepAll({},vn)},Nn(e),e.frames),animation:Nn(gn)}},Ln.crawl=function(t,e,r,n){var a=r||0;n=n||"",Object.keys(t).forEach(function(r){var i=t[r];if(-1===Pn.indexOf(r)){var o=(n?n+".":"")+r;e(i,r,t,a,o),Ln.isValObject(i)||ne.isPlainObject(i)&&"impliedEdits"!==r&&Ln.crawl(i,e,a+1,o)}})},Ln.isValObject=function(t){return t&&void 0!==t.valType},Ln.findArrayAttributes=function(t){var e=[],r=[];function n(n,a,i,o){if(r=r.slice(0,o).concat([a]),n&&("data_array"===n.valType||!0===n.arrayOk)&&!("colorbar"===r[o-1]&&("ticktext"===a||"tickvals"===a))){var l=function(t){return t.join(".")}(r),s=ne.nestedProperty(t,l).get();ne.isArrayOrTypedArray(s)&&e.push(l)}}if(Ln.crawl(C,n),t._module&&t._module.attributes&&Ln.crawl(t._module.attributes,n),t.transforms)for(var a=t.transforms,i=0;i=t.transforms.length)return!1;n=(r=(R.transformsRegistry[t.transforms[o].type]||{}).attributes)&&r[e[2]],i=3}else if("area"===t.type)n=Mn[a];else{var l=t._module;if(l||(l=(R.modules[t.type||C.type.dflt]||{})._module),!l)return!1;if(!(n=(r=l.attributes)&&r[a])){var s=l.basePlotModule;s&&s.attributes&&(n=s.attributes[a])}n||(n=C[a])}return Fn(n,e,i)},Ln.getLayoutValObject=function(t,e){return Fn(function(t,e){var r,n,a,i,o=t._basePlotModules;if(o){var l;for(r=0;r0?".":"")+a;ne.isPlainObject(i)?Gn(i,e,o,n+1):e(o,a,i)}})}Un.manageCommandObserver=function(t,e,r,n){var a={},i=!0;e&&e._commandObserver&&(a=e._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Un.hasSimpleAPICommandBindings(t,r,a.lookupTable);if(e&&e._commandObserver){if(o)return a;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,a}if(o){Vn(t,o,a.cache),a.check=function(){if(i){var e=Vn(t,o,a.cache);return e.changed&&n&&void 0!==a.lookupTable[e.value]&&(a.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[e.value]})).then(a.enable,a.enable)),e.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=r.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=r._paper.attr("width")-7),n.attr(i);var o=n.select(".js-link-to-tool"),l=n.select(".js-link-spacer"),s=n.select(".js-sourcelinks");e._context.showSources&&e._context.showSources(e),e._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){Zn.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),a=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+a})}}(e,o),l.text(o.text()&&s.text()?" - ":"")}},Zn.sendDataToCloud=function(e){e.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=t.select(e).append("div").attr("id","hiddenform").style("display","none"),a=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=Zn.graphJson(e,!1,"keepdata"),a.node().submit(),n.remove(),e.emit("plotly_afterexport"),!1};var $n,Kn=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],ta=["year","month","dayMonth","dayMonthYear"];function ea(t,e){var r,n,a=t.trace,i=a._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},Zn.cleanPlot=function(t,e,r,n){var a,i,o=n._basePlotModules||[];for(a=0;a0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,f=u.bottom+u.top,h=1-2*l,d=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};a=Math.round(h*(d.width-c)),i=Math.round(h*(d.height-f))}else{var p=s?window.getComputedStyle(t):{};a=parseFloat(p.width)||n.width,i=parseFloat(p.height)||n.height}var g=Zn.layoutAttributes.width.min,v=Zn.layoutAttributes.height.min;a1,y=!r.height&&Math.abs(n.height-i)>1;(y||m)&&(m&&(n.width=a),y&&(n.height=i)),t._initialAutoSize||(t._initialAutoSize={width:a,height:i}),Zn.sanitizeMargins(n)},Zn.supplyLayoutModuleDefaults=function(t,e,r,n){var a,i,o,l=R.componentsRegistry,s=e._basePlotModules,u=R.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in s.length||s.push(u),e._has("cartesian")&&(R.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(ne.subplotSort);for(i=0;i.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+a},r:{val:r.x,size:r.r+a},b:{val:r.y,size:r.b+a},t:{val:r.y,size:r.t+a}}}else delete n._pushmargin[e];n._replotting||Zn.doAutoMargin(t)}},Zn.doAutoMargin=function(t){var r=t._fullLayout;r._size||(r._size={}),r._pushmargin||(r._pushmargin={});var n=r._size,a=JSON.stringify(n),i=Math.max(r.margin.l||0,0),o=Math.max(r.margin.r||0,0),l=Math.max(r.margin.t||0,0),s=Math.max(r.margin.b||0,0),u=r._pushmargin;if(!1!==r.margin.autoexpand)for(var c in u.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},u){var f=u[c].l||{},h=u[c].b||{},d=f.val,p=f.size,g=h.val,v=h.size;for(var m in u){if(e(p)&&u[m].r){var y=u[m].r.val,x=u[m].r.size;if(y>d){var b=(p*y+(x-r.width)*d)/(y-d),_=(x*(1-d)+(p-r.width)*(1-y))/(y-d);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(e(v)&&u[m].t){var w=u[m].t.val,A=u[m].t.size;if(w>g){var M=(v*w+(A-r.height)*g)/(w-g),T=(A*(1-g)+(v-r.height)*(1-w))/(w-g);M>=0&&T>=0&&M+T>s+l&&(s=M,l=T)}}}}if(n.l=Math.round(i),n.r=Math.round(o),n.t=Math.round(l),n.b=Math.round(s),n.p=Math.round(r.margin.pad),n.w=Math.round(r.width)-n.l-n.r,n.h=Math.round(r.height)-n.t-n.b,!r._replotting&&"{}"!==a&&a!==JSON.stringify(r._size))return R.call("plot",t)},Zn.graphJson=function(t,e,r,n,a){(a&&e&&!t._fullData||a&&!e&&!t._fullLayout)&&Zn.supplyDefaults(t);var i=a?t._fullData:t.data,o=a?t._fullLayout:t.layout,l=(t._transitionData||{})._frames;function s(t){if("function"==typeof t)return null;if(ne.isPlainObject(t)){var e,n,a={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!ne.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;a[e]=s(t[e])}return a}return Array.isArray(t)?t.map(s):ne.isJSDate(t)?ne.ms2DateTimeLocal(+t):t}var u={data:(i||[]).map(function(t){var r=s(t);return e&&delete r.fit,r})};return e||(u.layout=s(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),l&&(u.frames=s(l)),"object"===n?u:JSON.stringify(u)},Zn.modifyFrames=function(t,e){var r,n,a,i=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&t._transitionData._interruptCallbacks.push(function(){return R.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,l=0,s=0;function u(){return l++,function(){var r;f||++s!==l||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return R.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var h=t._fullLayout._basePlotModules,d=!1;if(r)for(o=0;o=0;i--)if(g[i].enabled){r._indexToPoints=g[i]._indexToPoints;break}n&&n.calc&&(p=n.calc(t,r))}Array.isArray(p)&&p[0]||(p=[{x:Yn,y:Yn}]),p[0].t||(p[0].t={}),p[0].trace=r,u[a]=p}R.getComponentMethod("fx","calc")(t)},Zn.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},Zn.generalUpdatePerTraceModule=function(t,e,r,n){var a,i=e.traceHash,o={};for(a=0;a0||f<0){var p={left:[-a,0],right:[a,0],top:[0,-a],bottom:[0,a]}[c.side];n.attr("transform","translate("+p+")")}}}T.call(k),A&&(w?T.on(".opacity",null):(b=0,_=!0,T.text(s).on("mouseover.opacity",function(){t.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){t.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(Ar.makeEditable,{gd:r}).on("edit",function(t){void 0!==u?R.call("restyle",r,l,t,u):R.call("relayout",r,l,t)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(k)}).on("input",function(t){this.text(t||" ").call(Ar.positionText,f.x,f.y)}));return T.classed("js-placeholder",_),p}},oa=/ [XY][0-9]* /;var la=r.FP_SAFE,sa=ha,ua=da,ca=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=ha(t),t._r=t.range.slice(),t._rl=ne.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?ha(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=ne.extendFlat({},n)}},fa=function(t,r,n){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!r)return;t._min||(t._min=[]);t._max||(t._max=[]);n||(n={});t._m||t.setScale();var a,i,o,l,s,u,c,f,h,d,p,g,v=r.length,m=n.padded||!1,y=n.tozero&&("linear"===t.type||"-"===t.type),x="log"===t.type,b=!1;function _(t){if(Array.isArray(t))return b=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=_((t._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),A=_((t._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),M=_(n.vpadplus||n.vpad),T=_(n.vpadminus||n.vpad);if(!b){if(p=1/0,g=-1/0,x)for(a=0;a0&&(p=l),l>g&&l-la&&(p=l),l>g&&l=b&&(l.extrapad||!m)){d=!1;break}_(a,l.val)&&l.pad<=b&&(m||!l.extrapad)&&(v.splice(i,1),i--)}if(d){var k=y&&0===a;v.push({val:a,pad:k?0:b,extrapad:!k&&m})}}}}var E=Math.min(6,v);for(a=0;a=E;a--)k(a)};function ha(t){var e,r,n,a,i,o,l,s,u=[],c=t._min[0].val,f=t._max[0].val,h=0,d=!1,p=da(t);for(e=1;e0&&l>0&&s/l>h&&(i=n,o=a,h=s/l);if(c===f){var v=c-1,m=c+1;u="tozero"===t.rangemode?c<0?[v,0]:[0,m]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,m)]:[v,m]}else h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(i.val-h*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),h=(o.val-i.val)/(t._length-p(i)-p(o))),u=[i.val-h*p(i),o.val+h*p(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),d&&u.reverse(),ne.simpleMap(u,t.l2r||Number)}function da(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function pa(t){return e(t)&&Math.abs(t)=e}var ma={},ya=r.ONEAVGYEAR,xa=r.ONEAVGMONTH,ba=r.ONEDAY,_a=r.ONEHOUR,wa=r.ONEMIN,Aa=r.ONESEC,Ma=r.MINUS_SIGN,Ta=r.BADNUM,ka=_r.MID_SHIFT,Ea=_r.LINE_SPACING,Ca=ma={};Ca.setConvert=Ze,Ca.id2name=Se.id2name,Ca.name2id=Se.name2id,Ca.cleanId=Se.cleanId,Ca.list=Se.list,Ca.listIds=Se.listIds,Ca.getFromId=Se.getFromId,Ca.getFromTrace=Se.getFromTrace,Ca.expand=fa,Ca.getAutoRange=sa,Ca.coerceRef=function(t,e,r,n,a,i){var o=n.charAt(n.length-1),l=r._fullLayout._subplots[o+"axis"],s=n+"ref",u={};return a||(a=l[0]||i),i||(i=a),u[s]={valType:"enumerated",values:l.concat(i?[i]:[]),dflt:a},ne.coerce(t,e,u,s)},Ca.coercePosition=function(t,e,r,n,a,i){var o,l;if("paper"===n||"pixel"===n)o=ne.ensureNumber,l=r(a,i);else{var s=Ca.getFromId(e,n);l=r(a,i=s.fraction2r(i)),o=s.cleanPos}t[a]=o(l)},Ca.cleanPosition=function(t,e,r){return("paper"===r||"pixel"===r?ne.ensureNumber:Ca.getFromId(e,r).cleanPos)(t)};var Sa=Ca.getDataConversions=function(t,e,r,n){var a,i="x"===r||"y"===r||"z"===r?r:n;if(Array.isArray(i)){if(a={type:ir(n),_categories:[]},Ca.setConvert(a),"category"===a.type)for(var o=0;o2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},Ca.saveRangeInitial=function(t,e){for(var r=Ca.list(t,"",!0),n=!1,a=0;a.3*h||c(a)||c(i))){var d=n.dtick/2;t+=t+d.8){var o=Number(r.substr(1));i.exactYears>.8&&o%12==0?t=Ca.tickIncrement(t,"M6","reverse")+1.5*ba:i.exactMonths>.8?t=Ca.tickIncrement(t,"M1","reverse")+15.5*ba:t-=ba/2;var l=Ca.tickIncrement(t,r);if(l<=n)return l}return t}(p,t,l.dtick,s,i)),d=p,0;d<=u;)d=Ca.tickIncrement(d,l.dtick,!1,i),0;return{start:r.c2r(p,0,i),end:r.c2r(d,0,i),size:l.dtick,_dataSpan:u-s}},Ca.prepTicks=function(t){var e=ne.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=ne.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),Ca.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),ja(t)},Ca.calcTicks=function(t){Ca.prepTicks(t);var e=ne.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,a=t.ticktext,i=new Array(n.length),o=ne.simpleMap(t.range,t.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],u=Math.min(l,s),c=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var h="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:s<=n)&&!(i.length>l||s===o);s=Ca.tickIncrement(s,t.dtick,a,t.calendar))o=s,i.push(s);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&i.pop(),t._tmax=i[i.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(i.length),c=0;c10||"01-01"!==a.substr(5)?t._tickround="d":t._tickround=+r.substr(1)%12==0?"y":"m";else if(r>=ba&&i<=10||r>=15*ba)t._tickround="d";else if(r>=wa&&i<=16||r>=_a)t._tickround="M";else if(r>=Aa&&i<=19||r>=wa)t._tickround="S";else{var o=t.l2r(n+r).replace(/^-/,"").length;t._tickround=Math.max(i,o)-20}}else if(e(r)||"L"===r.charAt(0)){var l=t.range.map(t.r2d||Number);e(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),u=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(u)>3&&(Ha(t.exponentformat)&&!qa(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function Ua(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}Ca.autoTicks=function(t,r){var n;function a(t){return Math.pow(t,Math.floor(Math.log(r)/Math.LN10))}if("date"===t.type){t.tick0=ne.dateTick0(t.calendar);var i=2*r;i>ya?(r/=ya,n=a(10),t.dtick="M"+12*Ba(r,n,Ra)):i>xa?(r/=xa,t.dtick="M"+Ba(r,1,Da)):i>ba?(t.dtick=Ba(r,ba,Pa),t.tick0=ne.dateTick0(t.calendar,!0)):i>_a?t.dtick=Ba(r,_a,Da):i>wa?t.dtick=Ba(r,wa,Ia):i>Aa?t.dtick=Ba(r,Aa,Ia):(n=a(10),t.dtick=Ba(r,n,Ra))}else if("log"===t.type){t.tick0=0;var o=ne.simpleMap(t.range,t.r2l);if(r>.7)t.dtick=Math.ceil(r);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/r);r=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,n=a(10),t.dtick="L"+Ba(r,n,Ra)}else t.dtick=r>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(r,1))):"angular"===t._id?(t.tick0=0,n=1,t.dtick=Ba(r,n,Na)):(t.tick0=0,n=a(10),t.dtick=Ba(r,n,Ra));if(0===t.dtick&&(t.dtick=1),!e(t.dtick)&&"string"!=typeof t.dtick){var s=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(s)}},Ca.tickIncrement=function(r,n,a,i){var o=a?-1:1;if(e(n))return r+o*n;var l=n.charAt(0),s=o*Number(n.substr(1));if("M"===l)return ne.incrementMonth(r,s,i);if("L"===l)return Math.log(Math.pow(10,r)+s)/Math.LN10;if("D"===l){var u="D2"===n?za:Fa,c=r+.01*o,f=ne.roundUp(ne.mod(c,1),u,a);return Math.floor(c)+Math.log(t.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(n)},Ca.tickFirst=function(r){var n=r.r2l||Number,a=ne.simpleMap(r.range,n),i=a[1]"+l,t._prevDateHead=l));r.text=s}(t,o,n,s):"log"===t.type?function(t,r,n,a,i){var o=t.dtick,l=r.x,s=t.tickformat;"never"===i&&(i="");!a||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))r.text=Ga(Math.pow(10,l),t,i,a);else if(e(o)||"D"===o.charAt(0)&&ne.mod(l+.01,1)<.1){var u=Math.round(l);-1!==["e","E","power"].indexOf(t.exponentformat)||Ha(t.exponentformat)&&qa(u)?(r.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+Ma+-u+"",r.fontSize*=1.25):(r.text=Ga(Math.pow(10,l),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(r.dy-=r.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);r.text=String(Math.round(Math.pow(10,ne.mod(l,1)))),r.fontSize*=.75}if("D1"===t.dtick){var c=String(r.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?r.dx-=r.fontSize/4:(r.dy+=r.fontSize/2,r.dx+=(t.range[1]>t.range[0]?1:-1)*r.fontSize*(l<0?.5:.25)))}}(t,o,0,s,a):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,a){if("radians"!==t.thetaunit||r)e.text=Ga(e.x,t,a,n);else{var i=e.x/180;if(0===i)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,a=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/a),Math.round(r/a)]}(i);if(o[1]>=100)e.text=Ga(ne.deg2rad(e.x),t,a,n);else{var l=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(e.text=Ma+e.text)}}}}(t,o,n,s,a):function(t,e,r,n,a){"never"===a?a="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(a="hide");e.text=Ga(e.x,t,a,n)}(t,o,0,s,a),t.tickprefix&&!h(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!h(t.showticksuffix)&&(o.text+=t.ticksuffix),o},Ca.hoverLabelText=function(t,e,r){if(r!==Ta&&r!==e)return Ca.hoverLabelText(t,e)+" - "+Ca.hoverLabelText(t,r);var n="log"===t.type&&e<=0,a=Ca.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":Ma+a:a};var Va=["f","p","n","\u03bc","m","","k","M","G","T"];function Ha(t){return"SI"===t||"B"===t}function qa(t){return t>14||t<-15}function Ga(t,r,n,a){var i=t<0,o=r._tickround,l=n||r.exponentformat||"B",s=r._tickexponent,u=Ca.getTickFormat(r),c=r.separatethousands;if(a){var f={exponentformat:l,dtick:"none"===r.showexponent?r.dtick:e(t)&&Math.abs(t)||1,range:"none"===r.showexponent?r.range.map(r.r2d):[0,t||1]};ja(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,r.hoverformat&&(u=r.hoverformat)}if(u)return r._numFormat(u)(t).replace(/-/g,Ma);var h,d=Math.pow(10,-o)/2;if("none"===l&&(s=0),(t=Math.abs(t))"+h+"":"B"===l&&9===s?t+="B":Ha(l)&&(t+=Va[s/3+5]));return i?Ma+t:t}function Xa(t,e){for(var r=0;r=0,i=u(t,e[1])<=0;return(r||a)&&(n||i)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=i(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n rect").call(Zr.setTranslate,0,0).call(Zr.setScale,1,1),t.plot.call(Zr.setTranslate,e._offset,r._offset).call(Zr.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(Zr.setPointGroupScale,1,1),n.selectAll(".textpoint").call(Zr.setTextPointsScale,1,1),n.call(Zr.hideOutsideRangePoints,t)}function g(t,r){var n,a,o,l=f[t.xaxis._id],s=f[t.yaxis._id],u=[];if(l){a=(n=e._fullLayout[l.axisName])._r,o=l.to,u[0]=(a[0]*(1-r)+r*o[0]-a[0])/(a[1]-a[0])*t.xaxis._length;var c=a[1]-a[0],h=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],u[2]=t.xaxis._length*(1-r+r*h/c)}else u[0]=0,u[2]=t.xaxis._length;if(s){a=(n=e._fullLayout[s.axisName])._r,o=s.to,u[1]=(a[1]*(1-r)+r*o[1]-a[1])/(a[0]-a[1])*t.yaxis._length;var d=a[1]-a[0],p=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],u[3]=t.yaxis._length*(1-r+r*p/d)}else u[1]=0,u[3]=t.yaxis._length;!function(t,r){var n,a=[];for(a=[t._id,r._id],n=0;n rect").call(Zr.setTranslate,_,w).call(Zr.setScale,1/x,1/b),t.plot.call(Zr.setTranslate,T,k).call(Zr.setScale,x,b).selectAll(".points").selectAll(".point").call(Zr.setPointGroupScale,1/x,1/b),t.plot.selectAll(".points").selectAll(".textpoint").call(Zr.setTextPointsScale,1/x,1/b)}a&&(l=a());var v=t.ease(n.easing);return e._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(c),c=null,function(){for(var t={},r=0;rn.duration?(function(){for(var t={},r=0;r0,s=[],u=[],c=0,f=0;for(n=0;n0&&s.push("var "+u.join(",")),n=i-1;n>=0;--n)c=t[n],s.push(["for(i",n,"=0;i",n,"0&&s.push(["index[",f,"]-=s",f].join("")),s.push(["++index[",c,"]"].join(""))),s.push("}")}return s.join("\n")}function li(t,e,r){for(var n=t.body,a=[],i=[],o=0;o0&&g.push("shape=SS.slice(0)"),t.indexArgs.length>0){var v=new Array(r);for(i=0;i0&&p.push("var "+g.join(",")),i=0;i3&&p.push(li(t.pre,t,a));var b=li(t.body,t,a),_=function(t){for(var e=0,r=t[0].length;e0,s=[],u=0;u0;){"].join("")),s.push(["if(j",u,"<",o,"){"].join("")),s.push(["s",e[u],"=j",u].join("")),s.push(["j",u,"=0"].join("")),s.push(["}else{s",e[u],"=",o].join("")),s.push(["j",u,"-=",o,"}"].join("")),l&&s.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&p.push(li(t.post,t,a)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+p.join("\n")+"\n----------");var w=[t.funcName||"unnamed","_cwise_loop_",n[0].join("s"),"m",_,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(a)].join("");return new Function(["function ",w,"(",d.join(","),"){",p.join("\n"),"} return ",w].join(""))()};var ui=function(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],i=[],o=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],s=[],u=0;u0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+c+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),s.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+c+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u0)throw new Error("cwise: pre() block may not reference array args");if(n0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===a)e.scalarArgs.push(n),e.shimArgs.push("scalar"+n);else if("index"===a){if(e.indexArgs.push(n),n0)throw new Error("cwise: pre() block may not reference array index");if(n0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===a){if(e.shapeArgs.push(n),nr.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,ui(e)},fi={},hi={body:"",args:[],thisVars:[],localVars:[]};function di(t){if(!t)return hi;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in gi){var e=gi[t];fi[t]=pi({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),fi[t+"eq"]=pi({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),fi[t+"s"]=pi({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),fi[t+"seq"]=pi({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var vi={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in vi){var e=vi[t];fi[t]=pi({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),fi[t+"eq"]=pi({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var mi={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in mi){var e=mi[t];fi[t]=pi({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),fi[t+"s"]=pi({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),fi[t+"eq"]=pi({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),fi[t+"seq"]=pi({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var yi=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_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"}),fi.norm1=ci({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,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"}),fi.sup=ci({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:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),fi.inf=ci({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:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),fi.random=pi({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),fi.assign=pi({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),fi.assigns=pi({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),fi.equals=ci({args:["array","array"],pre:hi,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"});var _i=function(t){for(var e=new Array(t),r=0;rMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+o.join(",")+",v){"),n?a.push("return this.data.set("+l+",v)}"):a.push("return this.data["+l+"]=v}"),a.push("proto.get=function "+r+"_get("+o.join(",")+"){"),n?a.push("return this.data.get("+l+")}"):a.push("return this.data["+l+"]}"),a.push("proto.index=function "+r+"_index(",o.join(),"){return "+l+"}"),a.push("proto.hi=function "+r+"_hi("+o.join(",")+"){return new "+r+"(this.data,"+i.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+i.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var c=i.map(function(t){return"a"+t+"=this.shape["+t+"]"}),f=i.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+o.join(",")+"){var b=this.offset,d=0,"+c.join(",")+","+f.join(","));for(var h=0;h=0){d=i"+h+"|0;b+=c"+h+"*d;a"+h+"-=d}");a.push("return new "+r+"(this.data,"+i.map(function(t){return"a"+t}).join(",")+","+i.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+o.join(",")+"){var "+i.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+i.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(h=0;h=0){c=(c+this.stride["+h+"]*i"+h+")|0}else{a.push(this.shape["+h+"]);b.push(this.stride["+h+"])}");return a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+i.map(function(t){return"shape["+t+"]"}).join(",")+","+i.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",a.join("\n"))(Ci[t],ki)}var Ci={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};var Si=function(t,e,r,n){if(void 0===t)return(0,Ci.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var a=e.length;if(void 0===r){r=new Array(a);for(var i=a-1,o=1;i>=0;--i)r[i]=o,o*=e[i]}if(void 0===n)for(n=0,i=0;i0)-(t<0)},Li.abs=function(t){var e=t>>31;return(t^e)-e},Li.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Li.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Li.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Li.countTrailingZeros=Oi,Li.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Li.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Li.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var Ri=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,a=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--a;t[e]=n<>>8&255]<<16|Ri[t>>>16&255]<<8|Ri[t>>>24&255]},Li.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Li.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Li.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Li.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Li.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Oi(t)+1};for(var Di={byteLength:function(t){return 3*t.length/4-ji(t)},toByteArray:function(t){var e,r,n,a,i,o=t.length;a=ji(t),i=new Fi(3*o/4-a),r=a>0?o-4:o;var l=0;for(e=0;e>16&255,i[l++]=n>>8&255,i[l++]=255&n;2===a?(n=Pi[t.charCodeAt(e)]<<2|Pi[t.charCodeAt(e+1)]>>4,i[l++]=255&n):1===a&&(n=Pi[t.charCodeAt(e)]<<10|Pi[t.charCodeAt(e+1)]<<4|Pi[t.charCodeAt(e+2)]>>2,i[l++]=n>>8&255,i[l++]=255&n);return i},fromByteArray:function(t){for(var e,r=t.length,n=r%3,a="",i=[],o=0,l=r-n;ol?l:o+16383));1===n?(e=t[r-1],a+=Ii[e>>2],a+=Ii[e<<4&63],a+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],a+=Ii[e>>10],a+=Ii[e>>4&63],a+=Ii[e<<2&63],a+="=");return i.push(a),i.join("")}},Ii=[],Pi=[],Fi="undefined"!=typeof Uint8Array?Uint8Array:Array,zi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ni=0,Bi=zi.length;Ni0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function Ui(t,e,r){for(var n,a,i=[],o=e;o>18&63]+Ii[a>>12&63]+Ii[a>>6&63]+Ii[63&a]);return i.join("")}Pi["-".charCodeAt(0)]=62,Pi["_".charCodeAt(0)]=63;var Vi={read:function(t,e,r,n,a){var i,o,l=8*a-n-1,s=(1<>1,c=-7,f=r?a-1:0,h=r?-1:1,d=t[e+f];for(f+=h,i=d&(1<<-c)-1,d>>=-c,c+=l;c>0;i=256*i+t[e+f],f+=h,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=h,c-=8);if(0===i)i=1-u;else{if(i===s)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),i-=u}return(d?-1:1)*o*Math.pow(2,i-n)},write:function(t,e,r,n,a,i){var o,l,s,u=8*i-a-1,c=(1<>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,p=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(s=Math.pow(2,-o))<1&&(o--,s*=2),(e+=o+f>=1?h/s:h*Math.pow(2,1-f))*s>=2&&(o++,s/=2),o+f>=c?(l=0,o=c):o+f>=1?(l=(e*s-1)*Math.pow(2,a),o+=f):(l=e*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;t[r+d]=255&l,d+=p,l/=256,a-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*g}},Hi={};Hi.Buffer=Xi,Hi.SlowBuffer=function(t){+t!=t&&(t=0);return Xi.alloc(+t)},Hi.INSPECT_MAX_BYTES=50;var qi=2147483647;function Gi(t){if(t>qi)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=Xi.prototype,e}function Xi(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return Zi(t)}return Wi(t,e,r)}function Wi(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return ko(t)||t&&ko(t.buffer)?function(t,e,r){if(e<0||t.byteLength=qi)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+qi.toString(16)+" bytes");return 0|t}function $i(t,e){if(Xi.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||ko(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Ao(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Mo(t).length;default:if(n)return Ao(t).length;e=(""+e).toLowerCase(),n=!0}}function Ki(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function to(t,e,r,n,a){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Eo(r=+r)&&(r=a?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(a)return-1;r=t.length-1}else if(r<0){if(!a)return-1;r=0}if("string"==typeof e&&(e=Xi.from(e,n)),Xi.isBuffer(e))return 0===e.length?-1:eo(t,e,r,n,a);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):eo(t,[e],r,n,a);throw new TypeError("val must be string, number or Buffer")}function eo(t,e,r,n,a){var i,o=1,l=t.length,s=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,l/=2,s/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(a){var c=-1;for(i=r;il&&(r=l-s),i=r;i>=0;i--){for(var f=!0,h=0;ha&&(n=a):n=a;var i=e.length;n>i/2&&(n=i/2);for(var o=0;o>8,a=r%256,i.push(a),i.push(n);return i}(e,t.length-r),t,r,n)}function so(t,e,r){return 0===e&&r===t.length?Di.fromByteArray(t):Di.fromByteArray(t.slice(e,r))}function uo(t,e,r){r=Math.min(t.length,r);for(var n=[],a=e;a239?4:u>223?3:u>191?2:1;if(a+f<=r)switch(f){case 1:u<128&&(c=u);break;case 2:128==(192&(i=t[a+1]))&&(s=(31&u)<<6|63&i)>127&&(c=s);break;case 3:i=t[a+1],o=t[a+2],128==(192&i)&&128==(192&o)&&(s=(15&u)<<12|(63&i)<<6|63&o)>2047&&(s<55296||s>57343)&&(c=s);break;case 4:i=t[a+1],o=t[a+2],l=t[a+3],128==(192&i)&&128==(192&o)&&128==(192&l)&&(s=(15&u)<<18|(63&i)<<12|(63&o)<<6|63&l)>65535&&s<1114112&&(c=s)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),a+=f}return function(t){var e=t.length;if(e<=co)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return po(this,e,r);case"utf8":case"utf-8":return uo(this,e,r);case"ascii":return fo(this,e,r);case"latin1":case"binary":return ho(this,e,r);case"base64":return so(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return go(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},Xi.prototype.toLocaleString=Xi.prototype.toString,Xi.prototype.equals=function(t){if(!Xi.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Xi.compare(this,t)},Xi.prototype.inspect=function(){var t="",e=Hi.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},Xi.prototype.compare=function(t,e,r,n,a){if(!Xi.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===a&&(a=this.length),e<0||r>t.length||n<0||a>this.length)throw new RangeError("out of range index");if(n>=a&&e>=r)return 0;if(n>=a)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,a>>>=0,this===t)return 0;for(var i=a-n,o=r-e,l=Math.min(i,o),s=this.slice(n,a),u=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var a=this.length-e;if((void 0===r||r>a)&&(r=a),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return ro(this,t,e,r);case"utf8":case"utf-8":return no(this,t,e,r);case"ascii":return ao(this,t,e,r);case"latin1":case"binary":return io(this,t,e,r);case"base64":return oo(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return lo(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Xi.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var co=4096;function fo(t,e,r){var n="";r=Math.min(t.length,r);for(var a=e;an)&&(r=n);for(var a="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function mo(t,e,r,n,a,i){if(!Xi.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>a||et.length)throw new RangeError("Index out of range")}function yo(t,e,r,n,a,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function xo(t,e,r,n,a){return e=+e,r>>>=0,a||yo(t,0,r,4),Vi.write(t,e,r,n,23,4),r+4}function bo(t,e,r,n,a){return e=+e,r>>>=0,a||yo(t,0,r,8),Vi.write(t,e,r,n,52,8),r+8}Xi.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||vo(t,e,this.length);for(var n=this[t],a=1,i=0;++i>>=0,e>>>=0,r||vo(t,e,this.length);for(var n=this[t+--e],a=1;e>0&&(a*=256);)n+=this[t+--e]*a;return n},Xi.prototype.readUInt8=function(t,e){return t>>>=0,e||vo(t,1,this.length),this[t]},Xi.prototype.readUInt16LE=function(t,e){return t>>>=0,e||vo(t,2,this.length),this[t]|this[t+1]<<8},Xi.prototype.readUInt16BE=function(t,e){return t>>>=0,e||vo(t,2,this.length),this[t]<<8|this[t+1]},Xi.prototype.readUInt32LE=function(t,e){return t>>>=0,e||vo(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Xi.prototype.readUInt32BE=function(t,e){return t>>>=0,e||vo(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Xi.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||vo(t,e,this.length);for(var n=this[t],a=1,i=0;++i=(a*=128)&&(n-=Math.pow(2,8*e)),n},Xi.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||vo(t,e,this.length);for(var n=e,a=1,i=this[t+--n];n>0&&(a*=256);)i+=this[t+--n]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*e)),i},Xi.prototype.readInt8=function(t,e){return t>>>=0,e||vo(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Xi.prototype.readInt16LE=function(t,e){t>>>=0,e||vo(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Xi.prototype.readInt16BE=function(t,e){t>>>=0,e||vo(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Xi.prototype.readInt32LE=function(t,e){return t>>>=0,e||vo(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Xi.prototype.readInt32BE=function(t,e){return t>>>=0,e||vo(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Xi.prototype.readFloatLE=function(t,e){return t>>>=0,e||vo(t,4,this.length),Vi.read(this,t,!0,23,4)},Xi.prototype.readFloatBE=function(t,e){return t>>>=0,e||vo(t,4,this.length),Vi.read(this,t,!1,23,4)},Xi.prototype.readDoubleLE=function(t,e){return t>>>=0,e||vo(t,8,this.length),Vi.read(this,t,!0,52,8)},Xi.prototype.readDoubleBE=function(t,e){return t>>>=0,e||vo(t,8,this.length),Vi.read(this,t,!1,52,8)},Xi.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||mo(this,t,e,r,Math.pow(2,8*r)-1,0);var a=1,i=0;for(this[e]=255&t;++i>>=0,r>>>=0,n)||mo(this,t,e,r,Math.pow(2,8*r)-1,0);var a=r-1,i=1;for(this[e+a]=255&t;--a>=0&&(i*=256);)this[e+a]=t/i&255;return e+r},Xi.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,1,255,0),this[e]=255&t,e+1},Xi.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},Xi.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},Xi.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},Xi.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Xi.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var a=Math.pow(2,8*r-1);mo(this,t,e,r,a-1,-a)}var i=0,o=1,l=0;for(this[e]=255&t;++i>0)-l&255;return e+r},Xi.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var a=Math.pow(2,8*r-1);mo(this,t,e,r,a-1,-a)}var i=r-1,o=1,l=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===l&&0!==this[e+i+1]&&(l=1),this[e+i]=(t/o>>0)-l&255;return e+r},Xi.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},Xi.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},Xi.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},Xi.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},Xi.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||mo(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Xi.prototype.writeFloatLE=function(t,e,r){return xo(this,t,e,!0,r)},Xi.prototype.writeFloatBE=function(t,e,r){return xo(this,t,e,!1,r)},Xi.prototype.writeDoubleLE=function(t,e,r){return bo(this,t,e,!0,r)},Xi.prototype.writeDoubleBE=function(t,e,r){return bo(this,t,e,!1,r)},Xi.prototype.copy=function(t,e,r,n){if(!Xi.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return a},Xi.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Xi.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var a=t.charCodeAt(0);("utf8"===n&&a<128||"latin1"===n)&&(t=a)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!a){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&i.push(239,191,189);continue}a=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),a=r;continue}r=65536+(a-55296<<10|r-56320)}else a&&(e-=3)>-1&&i.push(239,191,189);if(a=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function Mo(t){return Di.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(_o,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function To(t,e,r,n){for(var a=0;a=e.length||a>=t.length);++a)e[a+r]=t[a];return a}function ko(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function Eo(t){return t!=t}var Co=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n0?r.pop():new ArrayBuffer(t)}function s(t){return new Uint8Array(l(t),0,t)}function u(t){return new Uint16Array(l(2*t),0,t)}function c(t){return new Uint32Array(l(4*t),0,t)}function f(t){return new Int8Array(l(t),0,t)}function h(t){return new Int16Array(l(2*t),0,t)}function d(t){return new Int32Array(l(4*t),0,t)}function p(t){return new Float32Array(l(4*t),0,t)}function g(t){return new Float64Array(l(8*t),0,t)}function v(t){return r?new Uint8ClampedArray(l(t),0,t):s(t)}function m(t){return new DataView(l(t),0,t)}function y(t){t=Li.nextPow2(t);var r=Li.log2(t),n=i[r];return n.length>0?n.pop():new e(t)}So.free=function(t){if(e.isBuffer(t))i[Li.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var r=t.length||t.byteLength,n=0|Li.log2(r);a[n].push(t)}},So.freeUint8=So.freeUint16=So.freeUint32=So.freeInt8=So.freeInt16=So.freeInt32=So.freeFloat32=So.freeFloat=So.freeFloat64=So.freeDouble=So.freeUint8Clamped=So.freeDataView=function(t){o(t.buffer)},So.freeArrayBuffer=o,So.freeBuffer=function(t){i[Li.log2(t.length)].push(t)},So.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return l(t);switch(e){case"uint8":return s(t);case"uint16":return u(t);case"uint32":return c(t);case"int8":return f(t);case"int16":return h(t);case"int32":return d(t);case"float":case"float32":return p(t);case"double":case"float64":return g(t);case"uint8_clamped":return v(t);case"buffer":return y(t);case"data":case"dataview":return m(t);default:return null}return null},So.mallocArrayBuffer=l,So.mallocUint8=s,So.mallocUint16=u,So.mallocUint32=c,So.mallocInt8=f,So.mallocInt16=h,So.mallocInt32=d,So.mallocFloat32=So.mallocFloat=p,So.mallocFloat64=So.mallocDouble=g,So.mallocUint8Clamped=v,So.mallocDataView=m,So.mallocBuffer=y,So.clearCache=function(){for(var t=0;t<32;++t)n.UINT8[t].length=0,n.UINT16[t].length=0,n.UINT32[t].length=0,n.INT8[t].length=0,n.INT16[t].length=0,n.INT32[t].length=0,n.FLOAT[t].length=0,n.DOUBLE[t].length=0,n.UINT8C[t].length=0,a[t].length=0,i[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Hi.Buffer);var Lo=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function Oo(t,e,r,n,a){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=a}var Ro=Oo.prototype;function Do(t,e,r,n,a,i){var o=a.length*a.BYTES_PER_ELEMENT;if(i<0)return t.bufferData(e,a,n),o;if(o+i>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,i,a),r}function Io(t,e){for(var r=So.malloc(t.length,e),n=t.length,a=0;a=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=Do(this.gl,this.type,this.length,this.usage,t.data,e):this.length=Do(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var n=So.malloc(t.size,r),a=Si(n,t.shape);fi.assign(a,t),this.length=Do(this.gl,this.type,this.length,this.usage,e<0?n:n.subarray(0,t.size),e),So.free(n)}}else if(Array.isArray(t)){var i;i=this.type===this.gl.ELEMENT_ARRAY_BUFFER?Io(t,"uint16"):Io(t,"float32"),this.length=Do(this.gl,this.type,this.length,this.usage,e<0?i:i.subarray(0,t.length),e),So.free(i)}else if("object"==typeof t&&"number"==typeof t.length)this.length=Do(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}};var Po=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=new Oo(t,r,t.createBuffer(),0,n);return a.update(e),a},Fo=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;n=0){var f=u.charCodeAt(u.length-1)-48;if(f<2||f>4)throw new jo("","Invalid data type for attribute "+s+": "+u);qo(t,e,c[0],n,f,a,s)}else{if(!(u.indexOf("mat")>=0))throw new jo("","Unknown data type for attribute "+s+": "+u);var f=u.charCodeAt(u.length-1)-48;if(f<2||f>4)throw new jo("","Invalid data type for attribute "+s+": "+u);Go(t,e,c,n,f,a,s)}}}return a};function Vo(t,e,r,n,a,i){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=a,this._constFunc=i}var Ho=Vo.prototype;function qo(t,e,r,n,a,i,o){for(var l=["gl","v"],s=[],u=0;u1){s[0]in o||(o[s[0]]=[]),o=o[s[0]];for(var u=1;u4)throw new jo("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+a+"fv(locations["+e+"],false,obj"+t+")"}throw new jo("","Unknown uniform data type for "+name+": "+r)}var a=r.charCodeAt(r.length-1)-48;if(a<2||a>4)throw new jo("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+a+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+a+"fv(locations["+e+"],obj"+t+")";default:throw new jo("","Unrecognized data type for vector "+name+": "+r)}}}function i(e){for(var i=["return function updateProperty(obj){"],o=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var a in r){var i=r[a],o=e;parseInt(a)+""===a?o+="["+a+"]":o+="."+a,"object"==typeof i?n.push.apply(n,t(o,i)):n.push([o,i])}return n}("",e),l=0;l4)throw new jo("","Invalid data type");return"b"===t.charAt(0)?Zo(r,!1):Zo(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new jo("","Invalid uniform dimension type for matrix "+name+": "+t);return Zo(r*r,0)}throw new jo("","Unknown uniform data type for "+name+": "+t)}}(r[s].type);var c}function l(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1)for(var l=0;l=r)return el.substr(0,r);for(;r>el.length&&e>1;)1&e&&(el+=t),e>>=1,t+=t;return el=(el+=t).substr(0,r)};var nl=function(t,e,r){return rl(r=void 0!==r?r+"":" ",e)+t},al=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),a=String(n.length+e-1).length;return n.map(function(t,n){var i=n+e,o=String(i).length,l=nl(i,a-o);return l+r+t}).join("\n")};var il={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},ol=function(t){return il[t]},ll=function(t){return atob(t)},sl=["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"],ul=(sl=sl.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)})).concat(["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","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"]),cl=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","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","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"],fl=cl.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),hl=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],dl=function(t){var e,r,n,a=0,i=0,o=pl,l=[],s=[],u=1,c=0,f=0,h=!1,d=!1,p="",g=sl,v=cl;"300 es"===(t=t||{}).version&&(g=ul,v=fl);return function(t){return s=[],null!==t?function(t){var r;a=0,n=(p+=t).length;for(;e=p[a],a0)continue;r=t.slice(0,1).join("")}return m(r),f+=r.length,(l=l.slice(r.length)).length}}function M(){return/[^a-fA-F0-9]/.test(e)?(m(l.join("")),o=pl,a):(l.push(e),r=e,a+1)}function T(){return"."===e?(l.push(e),o=wl,r=e,a+1):/[eE]/.test(e)?(l.push(e),o=wl,r=e,a+1):"x"===e&&1===l.length&&"0"===l[0]?(o=Cl,l.push(e),r=e,a+1):/[^\d]/.test(e)?(m(l.join("")),o=pl,a):(l.push(e),r=e,a+1)}function k(){return"f"===e&&(l.push(e),r=e,a+=1),/[eE]/.test(e)?(l.push(e),r=e,a+1):"-"===e&&/[eE]/.test(r)?(l.push(e),r=e,a+1):/[^\d]/.test(e)?(m(l.join("")),o=pl,a):(l.push(e),r=e,a+1)}function E(){if(/[^\d\w_]/.test(e)){var t=l.join("");return o=v.indexOf(t)>-1?Tl:g.indexOf(t)>-1?Ml:Al,m(l.join("")),o=pl,a}return l.push(e),r=e,a+1}},pl=999,vl=9999,ml=0,yl=1,xl=2,bl=3,_l=4,wl=5,Al=6,Ml=7,Tl=8,kl=9,El=10,Cl=11,Sl=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];var Ll=function(t,e){var r=dl(e),n=[];return n=(n=n.concat(r(t))).concat(r(null))};var Ol=function(t){for(var e=Array.isArray(t)?t:Ll(t),r=0;r=0),l[8]){case"b":a=parseInt(a,10).toString(2);break;case"c":a=String.fromCharCode(parseInt(a,10));break;case"d":case"i":a=parseInt(a,10);break;case"j":a=JSON.stringify(a,null,l[6]?parseInt(l[6]):0);break;case"e":a=l[7]?parseFloat(a).toExponential(l[7]):parseFloat(a).toExponential();break;case"f":a=l[7]?parseFloat(a).toFixed(l[7]):parseFloat(a);break;case"g":a=l[7]?String(Number(a.toPrecision(l[7]))):parseFloat(a);break;case"o":a=(parseInt(a,10)>>>0).toString(8);break;case"s":a=String(a),a=l[7]?a.substring(0,l[7]):a;break;case"t":a=String(!!a),a=l[7]?a.substring(0,l[7]):a;break;case"T":a=Object.prototype.toString.call(a).slice(8,-1).toLowerCase(),a=l[7]?a.substring(0,l[7]):a;break;case"u":a=parseInt(a,10)>>>0;break;case"v":a=a.valueOf(),a=l[7]?a.substring(0,l[7]):a;break;case"x":a=(parseInt(a,10)>>>0).toString(16);break;case"X":a=(parseInt(a,10)>>>0).toString(16).toUpperCase()}t.json.test(l[8])?g+=a:(!t.number.test(l[8])||f&&!l[3]?h="":(h=f?"+":"-",a=a.toString().replace(t.sign,"")),u=l[4]?"0"===l[4]?"0":l[4].charAt(1):" ",c=l[6]-(h+a).length,s=l[6]&&c>0?u.repeat(c):"",g+=l[5]?h+a+s:"0"===u?h+s+a:s+h+a)}return g}(function(e){if(n[e])return n[e];var r,a=e,i=[],o=0;for(;a;){if(null!==(r=t.text.exec(a)))i.push(r[0]);else if(null!==(r=t.modulo.exec(a)))i.push("%");else{if(null===(r=t.placeholder.exec(a)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var l=[],s=r[2],u=[];if(null===(u=t.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(l.push(u[1]);""!==(s=s.substring(u[0].length));)if(null!==(u=t.key_access.exec(s)))l.push(u[1]);else{if(null===(u=t.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");l.push(u[1])}r[2]=l}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");i.push(r)}a=a.substring(r[0].length)}return n[e]=i}(r),arguments)}function r(t,r){return e.apply(null,[t].concat(r||[]))}var n=Object.create(null);void 0!==Rl&&(Rl.sprintf=e,Rl.vsprintf=r),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=r)}();var Dl=Rl.sprintf,Il=function(t,e,r){"use strict";var n=Ol(e)||"of unknown name (see npm glsl-shader-name)",a="unknown type";void 0!==r&&(a=r===ol.FRAGMENT_SHADER?"fragment":"vertex");for(var i=Dl("Error compiling %s shader %s:\n",a,n),o=Dl("%s%s",i,t),l=t.split("\n"),s={},u=0;ur)for(t=r;te)for(t=e;t=0){for(var v=0|g.type.charAt(g.type.length-1),m=new Array(v),y=0;y=0;)x+=1;p[f]=x}var b=new Array(r.length);function _(){i.program=zl.program(o,i._vref,i._fref,d,p);for(var t=0;t>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function ts(t,e,r,n){return new Function([Kl("A","x"+t+"y",e,["y"],n),Kl("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}$l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},$l.drawBox=(Jl=[0,0],Ql=[0,0],function(t,e,r,n,a){var i=this.plot,o=this.shader,l=i.gl;Jl[0]=t,Jl[1]=e,Ql[0]=r,Ql[1]=n,o.uniforms.lo=Jl,o.uniforms.hi=Ql,o.uniforms.color=a,l.drawArrays(l.TRIANGLE_STRIP,0,4)}),$l.dispose=function(){this.vbo.dispose(),this.shader.dispose()};var es={ge:ts(">=",!1,"GE"),gt:ts(">",!1,"GT"),lt:ts("<",!0,"LT"),le:ts("<=",!0,"LE"),eq:ts("-",!0,"EQ",!0)};function rs(t,e,r,n,a){var i=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function ns(t,e,r,n){return new Function([rs("A","x"+t+"y",e,["y"],n),rs("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var as={ge:ns(">=",!1,"GE"),gt:ns(">",!1,"GT"),lt:ns("<",!0,"LT"),le:ns("<=",!0,"LE"),eq:ns("-",!0,"EQ",!0)},is=function(t){var e=t.gl,r=Po(e),n=Wl(e,No.gridVert,No.gridFrag),a=Wl(e,No.tickVert,No.gridFrag);return new os(t,r,n,a)};function os(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function ls(t,e){return t-e}var ss,us,cs,fs,hs,ds=os.prototype;ds.draw=(ss=[0,0],us=[0,0],cs=[0,0],function(){for(var t=this.plot,e=this.vbo,r=this.shader,n=this.ticks,a=t.gl,i=t._tickBounds,o=t.dataBox,l=t.viewBox,s=t.gridLineWidth,u=t.gridLineColor,c=t.gridLineEnable,f=t.pixelRatio,h=0;h<2;++h){var d=i[h],p=i[h+2]-d,g=.5*(o[h+2]+o[h]),v=o[h+2]-o[h];us[h]=2*p/v,ss[h]=2*(d-g)/v}r.bind(),e.bind(),r.attributes.dataCoord.pointer(),r.uniforms.dataShift=ss,r.uniforms.dataScale=us;var m=0;for(h=0;h<2;++h){cs[0]=cs[1]=0,cs[h]=1,r.uniforms.dataAxis=cs,r.uniforms.lineWidth=s[h]/(l[h+2]-l[h])*f,r.uniforms.color=u[h];var y=6*n[h].length;c[h]&&y&&a.drawArrays(a.TRIANGLES,m,y),m+=y}}),ds.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],i=[0,0];return function(){for(var o=this.plot,l=this.vbo,s=this.tickShader,u=this.ticks,c=o.gl,f=o._tickBounds,h=o.dataBox,d=o.viewBox,p=o.pixelRatio,g=o.screenBox,v=g[2]-g[0],m=g[3]-g[1],y=d[2]-d[0],x=d[3]-d[1],b=0;b<2;++b){var _=f[b],w=f[b+2]-_,A=.5*(h[b+2]+h[b]),M=h[b+2]-h[b];e[b]=2*w/M,t[b]=2*(_-A)/M}e[0]*=y/v,t[0]*=y/v,e[1]*=x/m,t[1]*=x/m,s.bind(),l.bind(),s.attributes.dataCoord.pointer();var T=s.uniforms;T.dataShift=t,T.dataScale=e;var k=o.tickMarkLength,E=o.tickMarkWidth,C=o.tickMarkColor,S=6*u[0].length,L=Math.min(as.ge(u[0],(h[0]-f[0])/(f[2]-f[0]),ls),u[0].length),O=Math.min(as.gt(u[0],(h[2]-f[0])/(f[2]-f[0]),ls),u[0].length),R=0+6*L,D=6*Math.max(0,O-L),I=Math.min(as.ge(u[1],(h[1]-f[1])/(f[3]-f[1]),ls),u[1].length),P=Math.min(as.gt(u[1],(h[3]-f[1])/(f[3]-f[1]),ls),u[1].length),F=S+6*I,z=6*Math.max(0,P-I);a[0]=2*(d[0]-k[1])/v-1,a[1]=(d[3]+d[1])/m-1,i[0]=k[1]*p/v,i[1]=E[1]*p/m,z&&(T.color=C[1],T.tickScale=i,T.dataAxis=n,T.screenOffset=a,c.drawArrays(c.TRIANGLES,F,z)),a[0]=(d[2]+d[0])/v-1,a[1]=2*(d[1]-k[0])/m-1,i[0]=E[0]*p/v,i[1]=k[0]*p/m,D&&(T.color=C[0],T.tickScale=i,T.dataAxis=r,T.screenOffset=a,c.drawArrays(c.TRIANGLES,R,D)),a[0]=2*(d[2]+k[3])/v-1,a[1]=(d[3]+d[1])/m-1,i[0]=k[3]*p/v,i[1]=E[3]*p/m,z&&(T.color=C[3],T.tickScale=i,T.dataAxis=n,T.screenOffset=a,c.drawArrays(c.TRIANGLES,F,z)),a[0]=(d[2]+d[0])/v-1,a[1]=2*(d[3]+k[2])/m-1,i[0]=E[2]*p/v,i[1]=k[2]*p/m,D&&(T.color=C[2],T.tickScale=i,T.dataAxis=r,T.screenOffset=a,c.drawArrays(c.TRIANGLES,R,D))}}(),ds.update=(fs=[1,1,-1,-1,1,-1],hs=[1,-1,1,1,-1,-1],function(t){for(var e=t.ticks,r=t.bounds,n=new Float32Array(18*(e[0].length+e[1].length)),a=(this.plot.zeroLineEnable,0),i=[[],[]],o=0;o<2;++o)for(var l=i[o],s=e[o],u=r[o],c=r[o+2],f=0;f1)for(var r=1;r=n?(a=f,(s+=1)=n?(a=f,(s+=1)>1;return["sum(",Hs(t.slice(0,e)),",",Hs(t.slice(e)),")"].join("")}function qs(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return qs(e,t)}function Gs(t){if(2===t.length)return[["diff(",qs(t[0][0],t[1][1]),",",qs(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0;){for(var s=r.pop(),i=r.pop(),u=-1,c=-1,o=a[i],h=1;h=0||(e.flip(i,s),Qs(t,e,r,u,i,c),Qs(t,e,r,i,c,u),Qs(t,e,r,c,s,u),Qs(t,e,r,s,u,c)))}};function Qs(t,e,r,n,a,i){var o=e.opposite(n,a);if(!(o<0)){if(a0||o.length>0;){for(;i.length>0;){var f=i.pop();if(l[f]!==-a){l[f]=a;s[f];for(var h=0;h<3;++h){var d=c[3*f+h];d>=0&&0===l[d]&&(u[3*f+h]?o.push(d):(i.push(d),l[d]=a))}}}var p=o;o=i,i=p,o.length=0,a=-a}var g=function(t,e,r){for(var n=0,a=0;a>1;return["sum(",iu(t.slice(0,e)),",",iu(t.slice(e)),")"].join("")}function ou(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(i<=0)return o;n=a+i}else{if(!(a<0))return o;if(i>=0)return o;n=-(a+i)}var l=3.3306690738754716e-16*n;return o>=l||o<=-l?o:su(t,e,r)},function(t,e,r,n){var a=t[0]-n[0],i=e[0]-n[0],o=r[0]-n[0],l=t[1]-n[1],s=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],d=i*u,p=o*s,g=o*l,v=a*u,m=a*s,y=i*l,x=c*(d-p)+f*(g-v)+h*(m-y),b=7.771561172376103e-16*((Math.abs(d)+Math.abs(p))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(f)+(Math.abs(m)+Math.abs(y))*Math.abs(h));return x>b||-x>b?x:uu(t,e,r,n)}];!function(){for(;cu.length<=nu;)cu.push(lu(cu.length));for(var t=[],e=["slow"],r=0;r<=nu;++r)t.push("a"+r),e.push("o"+r);var n=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(r=2;r<=nu;++r)n.push("case ",r,":return o",r,"(",t.slice(0,r).join(),");");n.push("}var s=new Array(arguments.length);for(var i=0;is[0]&&a.push(new mu(s,l,pu,i),new mu(l,s,du,i))}a.sort(yu);for(var u=a[0].a[0]-(1+Math.abs(a[0].a[0]))*Math.pow(2,-52),c=[new vu([u,1],[u,0],-1,[],[],[],[])],f=[],i=0,h=a.length;i1&&fu(r[u[c-2]],r[u[c-1]],n)>0;)t.push([u[c-1],u[c-2],a]),c-=1;u.length=c,u.push(a);var f=s.upperIds;for(c=f.length;c>1&&fu(r[f[c-2]],r[f[c-1]],n)<0;)t.push([f[c-2],f[c-1],a]),c-=1;f.length=c,f.push(a)}}function _u(t,e){var r;return(r=t.a[0]=0}}(),ku.removeTriangle=function(t,e,r){var n=this.stars;Eu(n[t],e,r),Eu(n[e],r,t),Eu(n[r],t,e)},ku.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},ku.opposite=function(t,e){for(var r=this.stars[e],n=1,a=r.length;n=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function l(t,e,r,n){for(var a=0,i=Math.min(t.length,r),o=e;o=49?l-49+10:l>=17?l-17+10:l}return a}a.isBN=function(t){return t instanceof a||null!==t&&"object"==typeof t&&t.constructor.wordSize===a.wordSize&&Array.isArray(t.words)},a.max=function(t,e){return t.cmp(e)>0?t:e},a.min=function(t,e){return t.cmp(e)<0?t:e},a.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var a=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&a++,16===e?this._parseHex(t,a):this._parseBase(t,e,a),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},a.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},a.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var a=0;a=0;a-=3)o=t[a]|t[a-1]<<8|t[a-2]<<16,this.words[i]|=o<>>26-l&67108863,(l+=24)>=26&&(l-=26,i++);else if("le"===n)for(a=0,i=0;a>>26-l&67108863,(l+=24)>=26&&(l-=26,i++);return this.strip()},a.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)a=o(t,r,r+6),this.words[n]|=a<>>26-i&4194303,(i+=24)>=26&&(i-=26,n++);r+6!==e&&(a=o(t,e,r+6),this.words[n]|=a<>>26-i&4194303),this.strip()},a.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,a=1;a<=67108863;a*=e)n++;n--,a=a/e|0;for(var i=t.length-r,o=i%n,s=Math.min(i,i-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},a.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var s=["","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"],u=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var a=0|t.words[0],i=0|e.words[0],o=a*i,l=67108863&o,s=o/67108864|0;r.words[0]=l;for(var u=1;u>>26,f=67108863&s,h=Math.min(u,e.length-1),d=Math.max(0,u-t.length+1);d<=h;d++){var p=u-d|0;c+=(o=(a=0|t.words[p])*(i=0|e.words[d])+f)/67108864|0,f=67108863&o}r.words[u]=0|f,s=0|c}return 0!==s?r.words[u]=0|s:r.length--,r.strip()}a.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var a=0,i=0,o=0;o>>24-a&16777215)||o!==this.length-1?s[6-f.length]+f+n:f+n,(a+=2)>=26&&(a-=26,o--)}for(0!==i&&(n=i.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var h=u[t],d=c[t];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(d).toString(t);n=(p=p.idivn(d)).isZero()?g+n:s[h-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(t,e){return r(void 0!==i),this.toArrayLike(i,t,e)},a.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},a.prototype.toArrayLike=function(t,e,n){var a=this.byteLength(),i=n||Math.max(1,a);r(a<=i,"byte array longer than desired length"),r(i>0,"Requested array length <= 0"),this.strip();var o,l,s="le"===e,u=new t(i),c=this.clone();if(s){for(l=0;!c.isZero();l++)o=c.andln(255),c.iushrn(8),u[l]=o;for(;l=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},a.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},a.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},a.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},a.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},a.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},a.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},a.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},a.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var a=0;a0&&(this.words[a]=~this.words[a]&67108863>>26-n),this.strip()},a.prototype.notn=function(t){return this.clone().inotn(t)},a.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,a=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var a=0,i=0;i>>26;for(;0!==a&&i>>26;if(this.length=r.length,0!==a)this.words[this.length]=a,this.length++;else if(r!==this)for(;it.length?this.clone().iadd(t):t.clone().iadd(this)},a.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,a=this.cmp(t);if(0===a)return this.negative=0,this.length=1,this.words[0]=0,this;a>0?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==i&&o>26,this.words[o]=67108863&e;if(0===i&&o>>13,d=0|o[1],p=8191&d,g=d>>>13,v=0|o[2],m=8191&v,y=v>>>13,x=0|o[3],b=8191&x,_=x>>>13,w=0|o[4],A=8191&w,M=w>>>13,T=0|o[5],k=8191&T,E=T>>>13,C=0|o[6],S=8191&C,L=C>>>13,O=0|o[7],R=8191&O,D=O>>>13,I=0|o[8],P=8191&I,F=I>>>13,z=0|o[9],N=8191&z,B=z>>>13,j=0|l[0],U=8191&j,V=j>>>13,H=0|l[1],q=8191&H,G=H>>>13,X=0|l[2],W=8191&X,Y=X>>>13,Z=0|l[3],J=8191&Z,Q=Z>>>13,$=0|l[4],K=8191&$,tt=$>>>13,et=0|l[5],rt=8191&et,nt=et>>>13,at=0|l[6],it=8191&at,ot=at>>>13,lt=0|l[7],st=8191<,ut=lt>>>13,ct=0|l[8],ft=8191&ct,ht=ct>>>13,dt=0|l[9],pt=8191&dt,gt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(u+(n=Math.imul(f,U))|0)+((8191&(a=(a=Math.imul(f,V))+Math.imul(h,U)|0))<<13)|0;u=((i=Math.imul(h,V))+(a>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(p,U),a=(a=Math.imul(p,V))+Math.imul(g,U)|0,i=Math.imul(g,V);var mt=(u+(n=n+Math.imul(f,q)|0)|0)+((8191&(a=(a=a+Math.imul(f,G)|0)+Math.imul(h,q)|0))<<13)|0;u=((i=i+Math.imul(h,G)|0)+(a>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,U),a=(a=Math.imul(m,V))+Math.imul(y,U)|0,i=Math.imul(y,V),n=n+Math.imul(p,q)|0,a=(a=a+Math.imul(p,G)|0)+Math.imul(g,q)|0,i=i+Math.imul(g,G)|0;var yt=(u+(n=n+Math.imul(f,W)|0)|0)+((8191&(a=(a=a+Math.imul(f,Y)|0)+Math.imul(h,W)|0))<<13)|0;u=((i=i+Math.imul(h,Y)|0)+(a>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(b,U),a=(a=Math.imul(b,V))+Math.imul(_,U)|0,i=Math.imul(_,V),n=n+Math.imul(m,q)|0,a=(a=a+Math.imul(m,G)|0)+Math.imul(y,q)|0,i=i+Math.imul(y,G)|0,n=n+Math.imul(p,W)|0,a=(a=a+Math.imul(p,Y)|0)+Math.imul(g,W)|0,i=i+Math.imul(g,Y)|0;var xt=(u+(n=n+Math.imul(f,J)|0)|0)+((8191&(a=(a=a+Math.imul(f,Q)|0)+Math.imul(h,J)|0))<<13)|0;u=((i=i+Math.imul(h,Q)|0)+(a>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(A,U),a=(a=Math.imul(A,V))+Math.imul(M,U)|0,i=Math.imul(M,V),n=n+Math.imul(b,q)|0,a=(a=a+Math.imul(b,G)|0)+Math.imul(_,q)|0,i=i+Math.imul(_,G)|0,n=n+Math.imul(m,W)|0,a=(a=a+Math.imul(m,Y)|0)+Math.imul(y,W)|0,i=i+Math.imul(y,Y)|0,n=n+Math.imul(p,J)|0,a=(a=a+Math.imul(p,Q)|0)+Math.imul(g,J)|0,i=i+Math.imul(g,Q)|0;var bt=(u+(n=n+Math.imul(f,K)|0)|0)+((8191&(a=(a=a+Math.imul(f,tt)|0)+Math.imul(h,K)|0))<<13)|0;u=((i=i+Math.imul(h,tt)|0)+(a>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(k,U),a=(a=Math.imul(k,V))+Math.imul(E,U)|0,i=Math.imul(E,V),n=n+Math.imul(A,q)|0,a=(a=a+Math.imul(A,G)|0)+Math.imul(M,q)|0,i=i+Math.imul(M,G)|0,n=n+Math.imul(b,W)|0,a=(a=a+Math.imul(b,Y)|0)+Math.imul(_,W)|0,i=i+Math.imul(_,Y)|0,n=n+Math.imul(m,J)|0,a=(a=a+Math.imul(m,Q)|0)+Math.imul(y,J)|0,i=i+Math.imul(y,Q)|0,n=n+Math.imul(p,K)|0,a=(a=a+Math.imul(p,tt)|0)+Math.imul(g,K)|0,i=i+Math.imul(g,tt)|0;var _t=(u+(n=n+Math.imul(f,rt)|0)|0)+((8191&(a=(a=a+Math.imul(f,nt)|0)+Math.imul(h,rt)|0))<<13)|0;u=((i=i+Math.imul(h,nt)|0)+(a>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(S,U),a=(a=Math.imul(S,V))+Math.imul(L,U)|0,i=Math.imul(L,V),n=n+Math.imul(k,q)|0,a=(a=a+Math.imul(k,G)|0)+Math.imul(E,q)|0,i=i+Math.imul(E,G)|0,n=n+Math.imul(A,W)|0,a=(a=a+Math.imul(A,Y)|0)+Math.imul(M,W)|0,i=i+Math.imul(M,Y)|0,n=n+Math.imul(b,J)|0,a=(a=a+Math.imul(b,Q)|0)+Math.imul(_,J)|0,i=i+Math.imul(_,Q)|0,n=n+Math.imul(m,K)|0,a=(a=a+Math.imul(m,tt)|0)+Math.imul(y,K)|0,i=i+Math.imul(y,tt)|0,n=n+Math.imul(p,rt)|0,a=(a=a+Math.imul(p,nt)|0)+Math.imul(g,rt)|0,i=i+Math.imul(g,nt)|0;var wt=(u+(n=n+Math.imul(f,it)|0)|0)+((8191&(a=(a=a+Math.imul(f,ot)|0)+Math.imul(h,it)|0))<<13)|0;u=((i=i+Math.imul(h,ot)|0)+(a>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(R,U),a=(a=Math.imul(R,V))+Math.imul(D,U)|0,i=Math.imul(D,V),n=n+Math.imul(S,q)|0,a=(a=a+Math.imul(S,G)|0)+Math.imul(L,q)|0,i=i+Math.imul(L,G)|0,n=n+Math.imul(k,W)|0,a=(a=a+Math.imul(k,Y)|0)+Math.imul(E,W)|0,i=i+Math.imul(E,Y)|0,n=n+Math.imul(A,J)|0,a=(a=a+Math.imul(A,Q)|0)+Math.imul(M,J)|0,i=i+Math.imul(M,Q)|0,n=n+Math.imul(b,K)|0,a=(a=a+Math.imul(b,tt)|0)+Math.imul(_,K)|0,i=i+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,a=(a=a+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,i=i+Math.imul(y,nt)|0,n=n+Math.imul(p,it)|0,a=(a=a+Math.imul(p,ot)|0)+Math.imul(g,it)|0,i=i+Math.imul(g,ot)|0;var At=(u+(n=n+Math.imul(f,st)|0)|0)+((8191&(a=(a=a+Math.imul(f,ut)|0)+Math.imul(h,st)|0))<<13)|0;u=((i=i+Math.imul(h,ut)|0)+(a>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(P,U),a=(a=Math.imul(P,V))+Math.imul(F,U)|0,i=Math.imul(F,V),n=n+Math.imul(R,q)|0,a=(a=a+Math.imul(R,G)|0)+Math.imul(D,q)|0,i=i+Math.imul(D,G)|0,n=n+Math.imul(S,W)|0,a=(a=a+Math.imul(S,Y)|0)+Math.imul(L,W)|0,i=i+Math.imul(L,Y)|0,n=n+Math.imul(k,J)|0,a=(a=a+Math.imul(k,Q)|0)+Math.imul(E,J)|0,i=i+Math.imul(E,Q)|0,n=n+Math.imul(A,K)|0,a=(a=a+Math.imul(A,tt)|0)+Math.imul(M,K)|0,i=i+Math.imul(M,tt)|0,n=n+Math.imul(b,rt)|0,a=(a=a+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,i=i+Math.imul(_,nt)|0,n=n+Math.imul(m,it)|0,a=(a=a+Math.imul(m,ot)|0)+Math.imul(y,it)|0,i=i+Math.imul(y,ot)|0,n=n+Math.imul(p,st)|0,a=(a=a+Math.imul(p,ut)|0)+Math.imul(g,st)|0,i=i+Math.imul(g,ut)|0;var Mt=(u+(n=n+Math.imul(f,ft)|0)|0)+((8191&(a=(a=a+Math.imul(f,ht)|0)+Math.imul(h,ft)|0))<<13)|0;u=((i=i+Math.imul(h,ht)|0)+(a>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(N,U),a=(a=Math.imul(N,V))+Math.imul(B,U)|0,i=Math.imul(B,V),n=n+Math.imul(P,q)|0,a=(a=a+Math.imul(P,G)|0)+Math.imul(F,q)|0,i=i+Math.imul(F,G)|0,n=n+Math.imul(R,W)|0,a=(a=a+Math.imul(R,Y)|0)+Math.imul(D,W)|0,i=i+Math.imul(D,Y)|0,n=n+Math.imul(S,J)|0,a=(a=a+Math.imul(S,Q)|0)+Math.imul(L,J)|0,i=i+Math.imul(L,Q)|0,n=n+Math.imul(k,K)|0,a=(a=a+Math.imul(k,tt)|0)+Math.imul(E,K)|0,i=i+Math.imul(E,tt)|0,n=n+Math.imul(A,rt)|0,a=(a=a+Math.imul(A,nt)|0)+Math.imul(M,rt)|0,i=i+Math.imul(M,nt)|0,n=n+Math.imul(b,it)|0,a=(a=a+Math.imul(b,ot)|0)+Math.imul(_,it)|0,i=i+Math.imul(_,ot)|0,n=n+Math.imul(m,st)|0,a=(a=a+Math.imul(m,ut)|0)+Math.imul(y,st)|0,i=i+Math.imul(y,ut)|0,n=n+Math.imul(p,ft)|0,a=(a=a+Math.imul(p,ht)|0)+Math.imul(g,ft)|0,i=i+Math.imul(g,ht)|0;var Tt=(u+(n=n+Math.imul(f,pt)|0)|0)+((8191&(a=(a=a+Math.imul(f,gt)|0)+Math.imul(h,pt)|0))<<13)|0;u=((i=i+Math.imul(h,gt)|0)+(a>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(N,q),a=(a=Math.imul(N,G))+Math.imul(B,q)|0,i=Math.imul(B,G),n=n+Math.imul(P,W)|0,a=(a=a+Math.imul(P,Y)|0)+Math.imul(F,W)|0,i=i+Math.imul(F,Y)|0,n=n+Math.imul(R,J)|0,a=(a=a+Math.imul(R,Q)|0)+Math.imul(D,J)|0,i=i+Math.imul(D,Q)|0,n=n+Math.imul(S,K)|0,a=(a=a+Math.imul(S,tt)|0)+Math.imul(L,K)|0,i=i+Math.imul(L,tt)|0,n=n+Math.imul(k,rt)|0,a=(a=a+Math.imul(k,nt)|0)+Math.imul(E,rt)|0,i=i+Math.imul(E,nt)|0,n=n+Math.imul(A,it)|0,a=(a=a+Math.imul(A,ot)|0)+Math.imul(M,it)|0,i=i+Math.imul(M,ot)|0,n=n+Math.imul(b,st)|0,a=(a=a+Math.imul(b,ut)|0)+Math.imul(_,st)|0,i=i+Math.imul(_,ut)|0,n=n+Math.imul(m,ft)|0,a=(a=a+Math.imul(m,ht)|0)+Math.imul(y,ft)|0,i=i+Math.imul(y,ht)|0;var kt=(u+(n=n+Math.imul(p,pt)|0)|0)+((8191&(a=(a=a+Math.imul(p,gt)|0)+Math.imul(g,pt)|0))<<13)|0;u=((i=i+Math.imul(g,gt)|0)+(a>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(N,W),a=(a=Math.imul(N,Y))+Math.imul(B,W)|0,i=Math.imul(B,Y),n=n+Math.imul(P,J)|0,a=(a=a+Math.imul(P,Q)|0)+Math.imul(F,J)|0,i=i+Math.imul(F,Q)|0,n=n+Math.imul(R,K)|0,a=(a=a+Math.imul(R,tt)|0)+Math.imul(D,K)|0,i=i+Math.imul(D,tt)|0,n=n+Math.imul(S,rt)|0,a=(a=a+Math.imul(S,nt)|0)+Math.imul(L,rt)|0,i=i+Math.imul(L,nt)|0,n=n+Math.imul(k,it)|0,a=(a=a+Math.imul(k,ot)|0)+Math.imul(E,it)|0,i=i+Math.imul(E,ot)|0,n=n+Math.imul(A,st)|0,a=(a=a+Math.imul(A,ut)|0)+Math.imul(M,st)|0,i=i+Math.imul(M,ut)|0,n=n+Math.imul(b,ft)|0,a=(a=a+Math.imul(b,ht)|0)+Math.imul(_,ft)|0,i=i+Math.imul(_,ht)|0;var Et=(u+(n=n+Math.imul(m,pt)|0)|0)+((8191&(a=(a=a+Math.imul(m,gt)|0)+Math.imul(y,pt)|0))<<13)|0;u=((i=i+Math.imul(y,gt)|0)+(a>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(N,J),a=(a=Math.imul(N,Q))+Math.imul(B,J)|0,i=Math.imul(B,Q),n=n+Math.imul(P,K)|0,a=(a=a+Math.imul(P,tt)|0)+Math.imul(F,K)|0,i=i+Math.imul(F,tt)|0,n=n+Math.imul(R,rt)|0,a=(a=a+Math.imul(R,nt)|0)+Math.imul(D,rt)|0,i=i+Math.imul(D,nt)|0,n=n+Math.imul(S,it)|0,a=(a=a+Math.imul(S,ot)|0)+Math.imul(L,it)|0,i=i+Math.imul(L,ot)|0,n=n+Math.imul(k,st)|0,a=(a=a+Math.imul(k,ut)|0)+Math.imul(E,st)|0,i=i+Math.imul(E,ut)|0,n=n+Math.imul(A,ft)|0,a=(a=a+Math.imul(A,ht)|0)+Math.imul(M,ft)|0,i=i+Math.imul(M,ht)|0;var Ct=(u+(n=n+Math.imul(b,pt)|0)|0)+((8191&(a=(a=a+Math.imul(b,gt)|0)+Math.imul(_,pt)|0))<<13)|0;u=((i=i+Math.imul(_,gt)|0)+(a>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(N,K),a=(a=Math.imul(N,tt))+Math.imul(B,K)|0,i=Math.imul(B,tt),n=n+Math.imul(P,rt)|0,a=(a=a+Math.imul(P,nt)|0)+Math.imul(F,rt)|0,i=i+Math.imul(F,nt)|0,n=n+Math.imul(R,it)|0,a=(a=a+Math.imul(R,ot)|0)+Math.imul(D,it)|0,i=i+Math.imul(D,ot)|0,n=n+Math.imul(S,st)|0,a=(a=a+Math.imul(S,ut)|0)+Math.imul(L,st)|0,i=i+Math.imul(L,ut)|0,n=n+Math.imul(k,ft)|0,a=(a=a+Math.imul(k,ht)|0)+Math.imul(E,ft)|0,i=i+Math.imul(E,ht)|0;var St=(u+(n=n+Math.imul(A,pt)|0)|0)+((8191&(a=(a=a+Math.imul(A,gt)|0)+Math.imul(M,pt)|0))<<13)|0;u=((i=i+Math.imul(M,gt)|0)+(a>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(N,rt),a=(a=Math.imul(N,nt))+Math.imul(B,rt)|0,i=Math.imul(B,nt),n=n+Math.imul(P,it)|0,a=(a=a+Math.imul(P,ot)|0)+Math.imul(F,it)|0,i=i+Math.imul(F,ot)|0,n=n+Math.imul(R,st)|0,a=(a=a+Math.imul(R,ut)|0)+Math.imul(D,st)|0,i=i+Math.imul(D,ut)|0,n=n+Math.imul(S,ft)|0,a=(a=a+Math.imul(S,ht)|0)+Math.imul(L,ft)|0,i=i+Math.imul(L,ht)|0;var Lt=(u+(n=n+Math.imul(k,pt)|0)|0)+((8191&(a=(a=a+Math.imul(k,gt)|0)+Math.imul(E,pt)|0))<<13)|0;u=((i=i+Math.imul(E,gt)|0)+(a>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(N,it),a=(a=Math.imul(N,ot))+Math.imul(B,it)|0,i=Math.imul(B,ot),n=n+Math.imul(P,st)|0,a=(a=a+Math.imul(P,ut)|0)+Math.imul(F,st)|0,i=i+Math.imul(F,ut)|0,n=n+Math.imul(R,ft)|0,a=(a=a+Math.imul(R,ht)|0)+Math.imul(D,ft)|0,i=i+Math.imul(D,ht)|0;var Ot=(u+(n=n+Math.imul(S,pt)|0)|0)+((8191&(a=(a=a+Math.imul(S,gt)|0)+Math.imul(L,pt)|0))<<13)|0;u=((i=i+Math.imul(L,gt)|0)+(a>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(N,st),a=(a=Math.imul(N,ut))+Math.imul(B,st)|0,i=Math.imul(B,ut),n=n+Math.imul(P,ft)|0,a=(a=a+Math.imul(P,ht)|0)+Math.imul(F,ft)|0,i=i+Math.imul(F,ht)|0;var Rt=(u+(n=n+Math.imul(R,pt)|0)|0)+((8191&(a=(a=a+Math.imul(R,gt)|0)+Math.imul(D,pt)|0))<<13)|0;u=((i=i+Math.imul(D,gt)|0)+(a>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(N,ft),a=(a=Math.imul(N,ht))+Math.imul(B,ft)|0,i=Math.imul(B,ht);var Dt=(u+(n=n+Math.imul(P,pt)|0)|0)+((8191&(a=(a=a+Math.imul(P,gt)|0)+Math.imul(F,pt)|0))<<13)|0;u=((i=i+Math.imul(F,gt)|0)+(a>>>13)|0)+(Dt>>>26)|0,Dt&=67108863;var It=(u+(n=Math.imul(N,pt))|0)+((8191&(a=(a=Math.imul(N,gt))+Math.imul(B,pt)|0))<<13)|0;return u=((i=Math.imul(B,gt))+(a>>>13)|0)+(It>>>26)|0,It&=67108863,s[0]=vt,s[1]=mt,s[2]=yt,s[3]=xt,s[4]=bt,s[5]=_t,s[6]=wt,s[7]=At,s[8]=Mt,s[9]=Tt,s[10]=kt,s[11]=Et,s[12]=Ct,s[13]=St,s[14]=Lt,s[15]=Ot,s[16]=Rt,s[17]=Dt,s[18]=It,0!==u&&(s[19]=u,r.length++),r};function d(t,e,r){return(new p).mulp(t,e,r)}function p(t,e){this.x=t,this.y=e}Math.imul||(h=f),a.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?h(this,t,e):r<63?f(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,a=0,i=0;i>>26)|0)>>>26,o&=67108863}r.words[i]=l,n=o,o=a}return 0!==n?r.words[i]=n:r.length--,r.strip()}(this,t,e):d(this,t,e)},p.prototype.makeRBT=function(t){for(var e=new Array(t),r=a.prototype._countBits(t)-1,n=0;n>=1;return n},p.prototype.permute=function(t,e,r,n,a,i){for(var o=0;o>>=1)a++;return 1<>>=13,n[2*o+1]=8191&i,i>>>=13;for(o=2*e;o>=26,e+=a/67108864|0,e+=i>>>26,this.words[n]=67108863&i}return 0!==e&&(this.words[n]=e,this.length++),this},a.prototype.muln=function(t){return this.clone().imuln(t)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>a}return e}(t);if(0===e.length)return new a(1);for(var r=this,n=0;n=0);var e,n=t%26,a=(t-n)/26,i=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(e=0;e>>26-n}o&&(this.words[e]=o,this.length++)}if(0!==a){for(e=this.length-1;e>=0;e--)this.words[e+a]=this.words[e];for(e=0;e=0),a=e?(e-e%26)/26:0;var i=t%26,o=Math.min((t-i)/26,this.length),l=67108863^67108863>>>i<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=a);u--){var f=0|this.words[u];this.words[u]=c<<26-i|f>>>i,c=f&l}return s&&0!==c&&(s.words[s.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},a.prototype.shln=function(t){return this.clone().ishln(t)},a.prototype.ushln=function(t){return this.clone().iushln(t)},a.prototype.shrn=function(t){return this.clone().ishrn(t)},a.prototype.ushrn=function(t){return this.clone().iushrn(t)},a.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,a=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var a=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},a.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(s/67108864|0),this.words[a+n]=67108863&i}for(;a>26,this.words[a+n]=67108863&i;if(0===l)return this.strip();for(r(-1===l),l=0,a=0;a>26,this.words[a]=67108863&i;return this.negative=1,this.strip()},a.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!==(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var l,s=n.length-i.length;if("mod"!==e){(l=new a(null)).length=s+1,l.words=new Array(l.length);for(var u=0;u=0;f--){var h=67108864*(0|n.words[i.length+f])+(0|n.words[i.length+f-1]);for(h=Math.min(h/o|0,67108863),n._ishlnsubmul(i,h,f);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(i,1,f),n.isZero()||(n.negative^=1);l&&(l.words[f]=h)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:l||null,mod:n}},a.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new a(0),mod:new a(0)}:0!==this.negative&&0===t.negative?(l=this.neg().divmod(t,e),"mod"!==e&&(i=l.div.neg()),"div"!==e&&(o=l.mod.neg(),n&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(l=this.divmod(t.neg(),e),"mod"!==e&&(i=l.div.neg()),{div:i,mod:l.mod}):0!=(this.negative&t.negative)?(l=this.neg().divmod(t.neg(),e),"div"!==e&&(o=l.mod.neg(),n&&0!==o.negative&&o.isub(t)),{div:l.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new a(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new a(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new a(this.modn(t.words[0]))}:this._wordDiv(t,e);var i,o,l},a.prototype.div=function(t){return this.divmod(t,"div",!1).div},a.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},a.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},a.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),a=t.andln(1),i=r.cmp(n);return i<0||1===a&&0===i?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},a.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,a=this.length-1;a>=0;a--)n=(e*n+(0|this.words[a]))%t;return n},a.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var a=(0|this.words[n])+67108864*e;this.words[n]=a/t|0,e=a%t}return this.strip()},a.prototype.divn=function(t){return this.clone().idivn(t)},a.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new a(1),o=new a(0),l=new a(0),s=new a(1),u=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++u;for(var c=n.clone(),f=e.clone();!e.isZero();){for(var h=0,d=1;0==(e.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(e.iushrn(h);h-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(c),o.isub(f)),i.iushrn(1),o.iushrn(1);for(var p=0,g=1;0==(n.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(l.isOdd()||s.isOdd())&&(l.iadd(c),s.isub(f)),l.iushrn(1),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),i.isub(l),o.isub(s)):(n.isub(e),l.isub(i),s.isub(o))}return{a:l,b:s,gcd:n.iushln(u)}},a.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new a(1),l=new a(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(s),o.iushrn(1);for(var f=0,h=1;0==(n.words[0]&h)&&f<26;++f,h<<=1);if(f>0)for(n.iushrn(f);f-- >0;)l.isOdd()&&l.iadd(s),l.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(l)):(n.isub(e),l.isub(o))}return(i=0===e.cmpn(1)?o:l).cmpn(0)<0&&i.iadd(t),i},a.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var a=e.cmp(r);if(a<0){var i=e;e=r,r=i}else if(0===a||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},a.prototype.invm=function(t){return this.egcd(t).a.umod(t)},a.prototype.isEven=function(){return 0==(1&this.words[0])},a.prototype.isOdd=function(){return 1==(1&this.words[0])},a.prototype.andln=function(t){return this.words[0]&t},a.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,a=1<>>26,l&=67108863,this.words[o]=l}return 0!==i&&(this.words[o]=i,this.length++),this},a.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},a.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var a=0|this.words[0];e=a===t?0:at.length)return 1;if(this.length=0;r--){var n=0|this.words[r],a=0|t.words[r];if(n!==a){na&&(e=1);break}}return e},a.prototype.gtn=function(t){return 1===this.cmpn(t)},a.prototype.gt=function(t){return 1===this.cmp(t)},a.prototype.gten=function(t){return this.cmpn(t)>=0},a.prototype.gte=function(t){return this.cmp(t)>=0},a.prototype.ltn=function(t){return-1===this.cmpn(t)},a.prototype.lt=function(t){return-1===this.cmp(t)},a.prototype.lten=function(t){return this.cmpn(t)<=0},a.prototype.lte=function(t){return this.cmp(t)<=0},a.prototype.eqn=function(t){return 0===this.cmpn(t)},a.prototype.eq=function(t){return 0===this.cmp(t)},a.red=function(t){return new _(t)},a.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},a.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(t){return this.red=t,this},a.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},a.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},a.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},a.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},a.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},a.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},a.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},a.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},a.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function x(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function b(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=a._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function w(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(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)}v.prototype._tmp=function(){var t=new a(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,a=i}a>>>=22,t.words[n-10]=a,0===a&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=a,e=n}return 0!==e&&(t.words[t.length++]=e),t},a._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new y;else if("p192"===t)e=new x;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new b}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new a(1)).iushrn(2);return this.pow(t,n)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);r(!i.isZero());var l=new a(1).toRed(this),s=l.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new a(2*c*c).toRed(this);0!==this.pow(c,u).cmp(s);)c.redIAdd(s);for(var f=this.pow(c,i),h=this.pow(t,i.addn(1).iushrn(1)),d=this.pow(t,i),p=o;0!==d.cmp(l);){for(var g=d,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(v=0;n--){for(var u=e.words[n],c=s-1;c>=0;c--){var f=u>>c&1;i!==r[0]&&(i=this.sqr(i)),0!==f||0!==o?(o<<=1,o|=f,(4===++l||0===n&&0===c)&&(i=this.mul(i,r[o]),l=0,o=0)):l=0}s=26}return i},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},a.mont=function(t){return new w(t)},n(w,_),w.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},w.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},w.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).iushrn(this.shift),i=a;return a.cmp(this.m)>=0?i=a.isub(this.m):a.cmpn(0)<0&&(i=a.iadd(this.m)),i._forceRed(this)},w.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new a(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},w.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(Iu,this),Iu=Iu.exports;var Pu=function(t){return t.cmp(new Iu(0))};var Fu={};(function(t){var e=!1;if("undefined"!=typeof Float64Array){var r=new Float64Array(1),n=new Uint32Array(r.buffer);if(r[0]=1,e=!0,1072693248===n[1]){(Fu=function(t){return r[0]=t,[n[0],n[1]]}).pack=function(t,e){return n[0]=t,n[1]=e,r[0]},Fu.lo=function(t){return r[0]=t,n[0]},Fu.hi=function(t){return r[0]=t,n[1]}}else if(1072693248===n[0]){(Fu=function(t){return r[0]=t,[n[1],n[0]]}).pack=function(t,e){return n[1]=t,n[0]=e,r[0]},Fu.lo=function(t){return r[0]=t,n[1]},Fu.hi=function(t){return r[0]=t,n[0]}}else e=!1}if(!e){var a=new t(8);(Fu=function(t){return a.writeDoubleLE(t,0,!0),[a.readUInt32LE(0,!0),a.readUInt32LE(4,!0)]}).pack=function(t,e){return a.writeUInt32LE(t,0,!0),a.writeUInt32LE(e,4,!0),a.readDoubleLE(0,!0)},Fu.lo=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(0,!0)},Fu.hi=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(4,!0)}}Fu.sign=function(t){return Fu.hi(t)>>>31},Fu.exponent=function(t){return(Fu.hi(t)<<1>>>21)-1023},Fu.fraction=function(t){var e=Fu.lo(t),r=Fu.hi(t),n=1048575&r;return 2146435072&r&&(n+=1<<20),[e,n]},Fu.denormalized=function(t){return!(2146435072&Fu.hi(t))}}).call(this,Hi.Buffer);var zu=function(t){var e=Fu.exponent(t);return e<52?new Iu(t):new Iu(t*Math.pow(2,52-e)).ushln(e-52)};var Nu=function(t,e){var r=Pu(t),n=Pu(e);if(0===r)return[zu(0),zu(1)];if(0===n)return[zu(0),zu(0)];n<0&&(t=t.neg(),e=e.neg());var a=t.gcd(e);if(a.cmpn(1))return[t.div(a),e.div(a)];return[t,e]};var Bu=function(t,e){return Nu(t[0].mul(e[1]),t[1].mul(e[0]))};var ju=function(t){return t&&"object"==typeof t&&Boolean(t.words)};var Uu=function(t){return Array.isArray(t)&&2===t.length&&ju(t[0])&&ju(t[1])};var Vu=function(t){return new Iu(t)};var Hu=function t(e,r){if(Uu(e))return r?Bu(e,t(r)):[e[0].clone(),e[1].clone()];var n=0;var a,i;if(ju(e))a=e.clone();else if("string"==typeof e)a=Vu(e);else{if(0===e)return[zu(0),zu(1)];if(e===Math.floor(e))a=zu(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),n-=256;a=zu(e)}}if(Uu(r))a.mul(r[1]),i=r[0].clone();else if(ju(r))i=r.clone();else if("string"==typeof r)i=Vu(r);else if(r)if(r===Math.floor(r))i=zu(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),n+=256;i=zu(r)}else i=zu(1);n>0?a=a.ushln(n):n<0&&(i=i.ushln(-n));return Nu(a,i)};var qu=function(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var a=0;a20)return 52;return r+32};var Wu=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.abs().divmod(r.abs()),a=n.div,i=qu(a),o=n.mod,l=e.negative!==r.negative?-1:1;if(0===o.cmpn(0))return l*i;if(i){var s=Xu(i)+4,u=qu(o.ushln(s).divRound(r));return l*(i+u*Math.pow(2,-s))}var c=r.bitLength()-o.bitLength()+53,u=qu(o.ushln(c).divRound(r));return c<1023?l*u*Math.pow(2,-c):(u*=Math.pow(2,-1023),l*u*Math.pow(2,1023-c))};var Yu={},Zu="d",Ju="ax",Qu="vv",$u="fp",Ku="es",tc="rs",ec="re",rc="rb",nc="ri",ac="rp",ic="bs",oc="be",lc="bb",sc="bi",uc="bp",cc="rv",fc="Q",hc=[Zu,Ju,Qu,tc,ec,rc,nc,ic,oc,lc,sc];function dc(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],n=hc.slice();t||n.splice(3,0,$u);var a=["function "+e+"("+n.join()+"){"];function i(e,n){var i=function(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),a=["function ",n,"(",hc.join(),"){","var ",Ku,"=2*",Zu,";"],i="for(var i="+tc+","+ac+"="+Ku+"*"+tc+";i<"+ec+";++i,"+ac+"+="+Ku+"){var x0="+rc+"["+Ju+"+"+ac+"],x1="+rc+"["+Ju+"+"+ac+"+"+Zu+"],xi="+nc+"[i];",o="for(var j="+ic+","+uc+"="+Ku+"*"+ic+";j<"+oc+";++j,"+uc+"+="+Ku+"){var y0="+lc+"["+Ju+"+"+uc+"],"+(r?"y1="+lc+"["+Ju+"+"+uc+"+"+Zu+"],":"")+"yi="+sc+"[j];";return t?a.push(i,fc,":",o):a.push(o,fc,":",i),r?a.push("if(y1"+oc+"-"+ic+"){"),t?(i(!0,!1),a.push("}else{"),i(!1,!1)):(a.push("if("+$u+"){"),i(!0,!0),a.push("}else{"),i(!0,!1),a.push("}}else{if("+$u+"){"),i(!1,!0),a.push("}else{"),i(!1,!1),a.push("}")),a.push("}}return "+e);var o=r.join("")+a.join("");return new Function(o)()}Yu.partial=dc(!1),Yu.full=dc(!0);var pc=function(t,e){var r="abcdef".split("").concat(e),n=[];t.indexOf("lo")>=0&&n.push("lo=e[k+n]");t.indexOf("hi")>=0&&n.push("hi=e[k+o]");return r.push(gc.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)},gc="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m";var vc=function(t,e,r,n,a,i){if(n<=r+1)return r;var o=r,l=n,s=n+r>>>1,u=2*t,c=s,f=a[u*s+e];for(;o=v?(c=g,f=v):p>=y?(c=d,f=p):(c=m,f=y):v>=y?(c=g,f=v):y>=p?(c=d,f=p):(c=m,f=y);for(var x=u*(l-1),b=u*c,_=0;_r&&a[f+e]>u;--c,f-=o){for(var h=f,d=f+o,p=0;p>1,s=l-a,u=l+a,c=i,f=s,h=l,d=u,p=o,g=e+1,v=r-1,m=0;Ec(c,f,n)&&(m=c,c=f,f=m);Ec(d,p,n)&&(m=d,d=p,p=m);Ec(c,h,n)&&(m=c,c=h,h=m);Ec(f,h,n)&&(m=f,f=h,h=m);Ec(c,d,n)&&(m=c,c=d,d=m);Ec(h,d,n)&&(m=h,h=d,d=m);Ec(f,p,n)&&(m=f,f=p,p=m);Ec(f,h,n)&&(m=f,f=h,h=m);Ec(d,p,n)&&(m=d,d=p,p=m);var y=n[2*f];var x=n[2*f+1];var b=n[2*d];var _=n[2*d+1];var w=2*c;var A=2*h;var M=2*p;var T=2*i;var k=2*l;var E=2*o;for(var C=0;C<2;++C){var S=n[w+C],L=n[A+C],O=n[M+C];n[T+C]=S,n[k+C]=L,n[E+C]=O}Mc(s,e,n);Mc(u,r,n);for(var R=g;R<=v;++R)if(Cc(R,y,x,n))R!==g&&Ac(R,g,n),++g;else if(!Cc(R,b,_,n))for(;;){if(Cc(v,b,_,n)){Cc(v,y,x,n)?(Tc(R,g,v,n),++g,--v):(Ac(R,v,n),--v);break}if(--vt;){var u=r[s-2],c=r[s-1];if(ur[e+1])}function Cc(t,e,r,n){var a=n[t*=2];return a>>1;bc(zc,y);for(var x=0,b=0,p=0;p=Lc)Nc(Dc,Ic,b--,_=_-Lc|0);else if(_>=0)Nc(Oc,Rc,x--,_);else if(_<=-Lc){_=-_-Lc|0;for(var w=0;w>>1;bc(zc,y);for(var x=0,b=0,_=0,p=0;p>1==zc[2*p+3]>>1&&(A=2,p+=1),w<0){for(var M=-(w>>1)-1,T=0;T<_;++T){var k=e(Pc[T],M);if(void 0!==k)return k}if(0!==A)for(var T=0;T>1)-1;0===A?Nc(Oc,Rc,x--,M):1===A?Nc(Dc,Ic,b--,M):2===A&&Nc(Pc,Fc,_--,M)}}},scanBipartite:function(t,e,r,n,a,i,o,l,s,u,c,f){var h=0,d=2*t,p=e,g=e+t,v=1,m=1;n?m=Lc:v=Lc;for(var y=a;y>>1;bc(zc,w);for(var A=0,y=0;y=Lc?(T=!n,x-=Lc):(T=!!n,x-=1),T)Bc(Oc,Rc,A++,x);else{var k=f[x],E=d*x,C=c[E+e+1],S=c[E+e+1+t];t:for(var L=0;L>>1;bc(zc,x);for(var b=0,g=0;g=Lc)Oc[b++]=v-Lc;else{var w=c[v-=1],A=h*v,M=u[A+e+1],T=u[A+e+1+t];t:for(var k=0;k=0;--k)if(Oc[k]===v){for(var L=k+1;L0;){var h=(c-=1)*$c,d=tf[h],p=tf[h+1],g=tf[h+2],v=tf[h+3],m=tf[h+4],y=tf[h+5],x=c*Kc,b=ef[x],_=ef[x+1],w=1&y,A=!!(16&y),M=a,T=i,k=l,E=s;if(w&&(M=l,T=s,k=a,E=i),!(2&y&&(g=Yc(t,d,p,g,M,T,_),p>=g)||4&y&&(p=Zc(t,d,p,g,M,T,b))>=g)){var C=g-p,S=m-v;if(A){if(t*C*(C+S)=p0)&&!(p1>=hi)",["p0","p1"]),Wc=pc("lo===p0",["p0"]),Yc=pc("lo>>1;if(!(o<=0)){var l,s=So.mallocDouble(2*o*a),u=So.mallocInt32(a);if((a=uf(t,o,s,u))>0){if(1===o&&n)Sc.init(a),l=Sc.sweepComplete(o,r,0,a,s,u,0,a,s,u);else{var c=So.mallocDouble(2*o*i),f=So.mallocInt32(i);(i=uf(e,o,c,f))>0&&(Sc.init(a+i),l=1===o?Sc.sweepBipartite(o,r,0,a,s,u,0,i,c,f):jc(o,r,n,a,s,u,i,c,f),So.free(c),So.free(f))}So.free(s),So.free(u)}return l}}}function ff(t,e){of.push([t,e])}var hf=function(t,e){return Nu(t[0].mul(e[0]),t[1].mul(e[1]))};var df=function(t){return Pu(t[0])*Pu(t[1])};var pf=function(t,e){return Nu(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))};var gf=function(t,e){return Nu(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))};var vf=function(t,e){for(var r=t.length,n=new Array(r),a=0;a>>0,Af=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-_f:_f;var r=Fu.hi(t),n=Fu.lo(t);e>t==t>0?n===wf?(r+=1,n=0):n+=1:0===n?(n=wf,r-=1):n-=1;return Fu.pack(n,r)};var Mf=function(t){for(var e=new Array(t.length),r=0;r0&&i>0||a<0&&i<0)return!1;var o=kf(r,t,e),l=kf(n,t,e);if(o>0&&l>0||o<0&&l<0)return!1;if(0===a&&0===i&&0===o&&0===l)return function(t,e,r,n){for(var a=0;a<2;++a){var i=t[a],o=e[a],l=Math.min(i,o),s=Math.max(i,o),u=r[a],c=n[a],f=Math.min(u,c),h=Math.max(u,c);if(he[2]?1:0)}function Ff(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--i){var p=e[o=(w=n[i])[0]],g=p[0],v=p[1],m=t[g],y=t[v];if((m[0]-y[0]||m[1]-y[1])<0){var x=g;g=v,v=x}p[0]=g;var b,_=p[1]=w[1];for(a&&(b=p[2]);i>0&&n[i-1][0]===o;){var w,A=(w=n[--i])[1];a?e.push([_,A,b]):e.push([_,A]),_=A}a?e.push([_,v,b]):e.push([_,v])}return l}(t,e,a,o,r));return Ff(e,l,r),!!l||(a.length>0||o.length>0)}var Nf=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;n0?1:0},Uf=function(t,e,r,n){var a=ru(e,r,n);if(0===a){var i=jf(ru(t,e,r)),o=jf(ru(t,e,n));if(i===o){if(0===i){var l=Vf(t,e,r),s=Vf(t,e,n);return l===s?0:l?1:-1}return 0}return 0===o?i>0?-1:Vf(t,e,n)?-1:1:0===i?o>0?1:Vf(t,e,r)?1:-1:jf(o-i)}var u=ru(t,e,r);if(u>0)return a>0&&ru(t,e,n)>0?1:-1;if(u<0)return a>0||ru(t,e,n)>0?1:-1;var c=ru(t,e,n);return c>0?1:Vf(t,e,r)?1:-1};function Vf(t,e,r){var n=Fs(t[0],-e[0]),a=Fs(t[1],-e[1]),i=Fs(r[0],-e[0]),o=Fs(r[1],-e[1]),l=Bs(Bf(n,i),Bf(a,o));return l[l.length-1]>=0}var Hf=function(t,e){for(var r=0|e.length,n=t.length,a=[new Array(r),new Array(r)],i=0;i0){i=a[u][r][0],l=u;break}o=i[1^l];for(var c=0;c<2;++c)for(var f=a[c][r],h=0;h0&&(i=d,o=p,l=c)}return n?o:(i&&s(i,l),o)}function c(t,r){var n=a[r][t][0],i=[t];s(n,r);for(var o=n[1^r];;){for(;o!==t;)i.push(o),o=u(i[i.length-2],o,!1);if(a[0][t].length+a[1][t].length===0)break;var l=i[i.length-1],c=t,f=i[1],h=u(l,c,!0);if(Uf(e[l],e[c],e[f],e[h])<0)break;i.push(t),o=u(l,c)}return i}function f(t,e){return e[1]===e[e.length-1]}for(var i=0;i0;){a[0][i].length;var p=c(i,h);f(d,p)?d.push.apply(d,p):(d.length>0&&l.push(d),d=p)}d.length>0&&l.push(d)}return l};var qf=function(t,e){for(var r=Nf(t,e.length),n=new Array(e.length),a=new Array(e.length),i=[],o=0;o0;){var s=i.pop();n[s]=!1;for(var u=r[s],o=0;o>>1,x=a",a?".get(m)":"[m]"];return i?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),i?o.push("return -1};"):o.push("return i};"),o.join("")}function Xf(t,e,r,n){return new Function([Gf("A","x"+t+"y",e,["y"],!1,n),Gf("B","x"+t+"y",e,["y"],!0,n),Gf("P","c(x,y)"+t+"0",e,["y","c"],!1,n),Gf("Q","c(x,y)"+t+"0",e,["y","c"],!0,n),"function dispatchBsearch",r,"(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",r].join(""))()}var Wf={ge:Xf(">=",!1,"GE"),gt:Xf(">",!1,"GT"),lt:Xf("<",!0,"LT"),le:Xf("<=",!0,"LE"),eq:Xf("-",!0,"EQ",!0)},Yf=0,Zf=1,Jf=function(t){if(!t||0===t.length)return new ch(null);return new ch(uh(t))};function Qf(t,e,r,n,a){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=a,this.count=(e?e.count:0)+(r?r.count:0)+n.length}var $f=Qf.prototype;function Kf(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function th(t,e){var r=uh(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function eh(t,e){var r=t.intervals([]);r.push(e),th(t,r)}function rh(t,e){var r=t.intervals([]),n=r.indexOf(e);return n<0?Yf:(r.splice(n,1),th(t,r),Zf)}function nh(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var a=r(t[n]);if(a)return a}}function ih(t,e){for(var r=0;r>1],a=[],i=[],o=[];for(r=0;r3*(e+1)?eh(this,t):this.left.insert(t):this.left=uh([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?eh(this,t):this.right.insert(t):this.right=uh([t]);else{var r=Wf.ge(this.leftPoints,t,lh),n=Wf.ge(this.rightPoints,t,sh);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},$f.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?rh(this,t):2===(i=this.left.remove(t))?(this.left=null,this.count-=1,Zf):(i===Zf&&(this.count-=1),i):Yf}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:Yf;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,n=this.left;n.right;)r=n,n=n.right;if(r===this)n.right=this.right;else{var a=this.left;i=this.right;r.count-=n.count,r.right=n.left,n.left=a,n.right=i}Kf(this,n),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?Kf(this,this.left):Kf(this,this.right);return Zf}for(a=Wf.ge(this.leftPoints,t,lh);a3*(e-1)?rh(this,t):2===(i=this.right.remove(t))?(this.right=null,this.count-=1,Zf):(i===Zf&&(this.count-=1),i):Yf;var i}},$f.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return ah(this.rightPoints,t,e)}return ih(this.leftPoints,e)},$f.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?ah(this.rightPoints,t,r):ih(this.leftPoints,r)};var fh=ch.prototype;fh.insert=function(t){this.root?this.root.insert(t):this.root=new Qf(t[0],null,null,[t],[t])},fh.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==Yf}return!1},fh.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},fh.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(fh,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(fh,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}});var hh=function(t){return new xh(t||Mh,null)},dh=0,ph=1;function gh(t,e,r,n,a,i){this._color=t,this.key=e,this.value=r,this.left=n,this.right=a,this._count=i}function vh(t){return new gh(t._color,t.key,t.value,t.left,t.right,t._count)}function mh(t,e){return new gh(t,e.key,e.value,e.left,e.right,e._count)}function yh(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function xh(t,e){this._compare=t,this.root=e}var bh=xh.prototype;function _h(t,e){this.tree=t,this._stack=e}Object.defineProperty(bh,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(bh,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(bh,"length",{get:function(){return this.root?this.root._count:0}}),bh.insert=function(t,e){for(var r=this._compare,n=this.root,a=[],i=[];n;){var o=r(t,n.key);a.push(n),i.push(o),n=o<=0?n.left:n.right}a.push(new gh(dh,t,e,null,null,1));for(var l=a.length-2;l>=0;--l){n=a[l];i[l]<=0?a[l]=new gh(n._color,n.key,n.value,a[l+1],n.right,n._count+1):a[l]=new gh(n._color,n.key,n.value,n.left,a[l+1],n._count+1)}for(l=a.length-1;l>1;--l){var s=a[l-1];n=a[l];if(s._color===ph||n._color===ph)break;var u=a[l-2];if(u.left===s)if(s.left===n){if(!(c=u.right)||c._color!==dh){if(u._color=dh,u.left=s.right,s._color=ph,s.right=u,a[l-2]=s,a[l-1]=n,yh(u),yh(s),l>=3)(f=a[l-3]).left===u?f.left=s:f.right=s;break}s._color=ph,u.right=mh(ph,c),u._color=dh,l-=1}else{if(!(c=u.right)||c._color!==dh){if(s.right=n.left,u._color=dh,u.left=n.right,n._color=ph,n.left=s,n.right=u,a[l-2]=n,a[l-1]=s,yh(u),yh(s),yh(n),l>=3)(f=a[l-3]).left===u?f.left=n:f.right=n;break}s._color=ph,u.right=mh(ph,c),u._color=dh,l-=1}else if(s.right===n){if(!(c=u.left)||c._color!==dh){if(u._color=dh,u.right=s.left,s._color=ph,s.left=u,a[l-2]=s,a[l-1]=n,yh(u),yh(s),l>=3)(f=a[l-3]).right===u?f.right=s:f.left=s;break}s._color=ph,u.left=mh(ph,c),u._color=dh,l-=1}else{var c;if(!(c=u.left)||c._color!==dh){var f;if(s.left=n.right,u._color=dh,u.right=n.left,n._color=ph,n.right=s,n.left=u,a[l-2]=n,a[l-1]=s,yh(u),yh(s),yh(n),l>=3)(f=a[l-3]).right===u?f.right=n:f.left=n;break}s._color=ph,u.left=mh(ph,c),u._color=dh,l-=1}}return a[0]._color=ph,new xh(r,a[0])},bh.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,a){if(r(e,a.key)<=0){var i;if(a.left&&(i=t(e,r,n,a.left)))return i;if(i=n(a.key,a.value))return i}if(a.right)return t(e,r,n,a.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,a,i){var o,l=n(e,i.key),s=n(r,i.key);if(l<=0){if(i.left&&(o=t(e,r,n,a,i.left)))return o;if(s>0&&(o=a(i.key,i.value)))return o}if(s>0&&i.right)return t(e,r,n,a,i.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(bh,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new _h(this,t)}}),Object.defineProperty(bh,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new _h(this,t)}}),bh.at=function(t){if(t<0)return new _h(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new _h(this,[])},bh.ge=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i<=0&&(a=n.length),r=i<=0?r.left:r.right}return n.length=a,new _h(this,n)},bh.gt=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i<0&&(a=n.length),r=i<0?r.left:r.right}return n.length=a,new _h(this,n)},bh.lt=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i>0&&(a=n.length),r=i<=0?r.left:r.right}return n.length=a,new _h(this,n)},bh.le=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i>=0&&(a=n.length),r=i<0?r.left:r.right}return n.length=a,new _h(this,n)},bh.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var a=e(t,r.key);if(n.push(r),0===a)return new _h(this,n);r=a<=0?r.left:r.right}return new _h(this,[])},bh.remove=function(t){var e=this.find(t);return e?e.remove():this},bh.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var wh=_h.prototype;function Ah(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function Mh(t,e){return te?1:0}Object.defineProperty(wh,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(wh,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),wh.clone=function(){return new _h(this.tree,this._stack.slice())},wh.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new gh(r._color,r.key,r.value,r.left,r.right,r._count);for(var n=t.length-2;n>=0;--n){(r=t[n]).left===t[n+1]?e[n]=new gh(r._color,r.key,r.value,e[n+1],r.right,r._count):e[n]=new gh(r._color,r.key,r.value,r.left,e[n+1],r._count)}if((r=e[e.length-1]).left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var i=e[a-1];e.push(new gh(r._color,i.key,i.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(n=e.length-2;n>=a;--n)r=e[n],e[n]=new gh(r._color,r.key,r.value,r.left,e[n+1],r._count);e[a-1].left=e[a]}if((r=e[e.length-1])._color===dh){var o=e[e.length-2];o.left===r?o.left=null:o.right===r&&(o.right=null),e.pop();for(n=0;n=0;--i){if(e=t[i],0===i)return void(e._color=ph);if((r=t[i-1]).left===e){if((n=r.right).right&&n.right._color===dh)return a=(n=r.right=vh(n)).right=vh(n.right),r.right=n.left,n.left=r,n.right=a,n._color=r._color,e._color=ph,r._color=ph,a._color=ph,yh(r),yh(n),i>1&&((o=t[i-2]).left===r?o.left=n:o.right=n),void(t[i-1]=n);if(n.left&&n.left._color===dh)return a=(n=r.right=vh(n)).left=vh(n.left),r.right=a.left,n.left=a.right,a.left=r,a.right=n,a._color=r._color,r._color=ph,n._color=ph,e._color=ph,yh(r),yh(n),yh(a),i>1&&((o=t[i-2]).left===r?o.left=a:o.right=a),void(t[i-1]=a);if(n._color===ph){if(r._color===dh)return r._color=ph,void(r.right=mh(dh,n));r.right=mh(dh,n);continue}n=vh(n),r.right=n.left,n.left=r,n._color=r._color,r._color=dh,yh(r),yh(n),i>1&&((o=t[i-2]).left===r?o.left=n:o.right=n),t[i-1]=n,t[i]=r,i+11&&((o=t[i-2]).right===r?o.right=n:o.left=n),void(t[i-1]=n);if(n.right&&n.right._color===dh)return a=(n=r.left=vh(n)).right=vh(n.right),r.left=a.right,n.right=a.left,a.right=r,a.left=n,a._color=r._color,r._color=ph,n._color=ph,e._color=ph,yh(r),yh(n),yh(a),i>1&&((o=t[i-2]).right===r?o.right=a:o.left=a),void(t[i-1]=a);if(n._color===ph){if(r._color===dh)return r._color=ph,void(r.left=mh(dh,n));r.left=mh(dh,n);continue}var o;n=vh(n),r.left=n.right,n.right=r,n._color=r._color,r._color=dh,yh(r),yh(n),i>1&&((o=t[i-2]).right===r?o.right=n:o.left=n),t[i-1]=n,t[i]=r,i+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(wh,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(wh,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),wh.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(wh,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),wh.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new gh(n._color,n.key,t,n.left,n.right,n._count);for(var a=e.length-2;a>=0;--a)(n=e[a]).left===e[a+1]?r[a]=new gh(n._color,n.key,n.value,r[a+1],n.right,n._count):r[a]=new gh(n._color,n.key,n.value,n.left,r[a+1],n._count);return new xh(this.tree._compare,r[0])},wh.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(wh,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}});var Th=function(t,e){var r,n,a,i;if(e[0][0]e[1][0]))return kh(e,t);r=e[1],n=e[0]}if(t[0][0]t[1][0]))return-kh(t,e);a=t[1],i=t[0]}var o=ru(r,n,i),l=ru(r,n,a);if(o<0){if(l<=0)return o}else if(o>0){if(l>=0)return o}else if(l)return l;if(o=ru(i,a,n),l=ru(i,a,r),o<0){if(l<=0)return o}else if(o>0){if(l>=0)return o}else if(l)return l;return n[0]-i[0]};function kh(t,e){var r,n,a,i;if(e[0][0]e[1][0])){var o=Math.min(t[0][1],t[1][1]),l=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return lu?o-u:l-u}r=e[1],n=e[0]}t[0][1]0)if(e[0]!==i[1][0])r=t,t=t.right;else{if(l=Lh(t.right,e))return l;t=t.left}else{if(e[0]!==i[1][0])return t;var l;if(l=Lh(t.right,e))return l;t=t.left}}return r}function Oh(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function Rh(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}Ch.prototype.castUp=function(t){var e=Wf.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=Lh(this.slabs[e],t),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var a=null;if(r&&(a=r.key),e>0){var i=Lh(this.slabs[e-1],t);i&&(a?Th(i.key,a)>0&&(a=i.key,n=i.value):(n=i.value,a=i.key))}var o=this.horizontal[e];if(o.length>0){var l=Wf.ge(o,t[1],Sh);if(l=o.length)return n;s=o[l]}}if(s.start)if(a){var u=ru(a[0],a[1],[t[0],s.y]);a[0][0]>a[1][0]&&(u=-u),u>0&&(n=s.index)}else n=s.index;else s.y!==t[1]&&(n=s.index)}}}return n};var Dh=function(t){for(var e=t.length,r=[],n=[],a=0;a0&&e[n]===r[0]))return 1;a=t[n-1]}for(var i=1;a;){var o=a.key,l=Ih(r,o[0],o[1]);if(o[0][0]0))return 0;i=-1,a=a.right}else if(l>0)a=a.left;else{if(!(l<0))return 0;i=1,a=a.right}}return i}}(h.slabs,h.coordinates);return 0===n.length?d:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(Fh(n),d)},Ih=ru[3];function Ph(){return!0}function Fh(t){for(var e={},r=0;r0})).length,s=new Array(l),u=new Array(l),i=0;i0;){var O=S.pop(),R=_[O];ii(R,function(t,e){return t-e});var D,I=R.length,P=L[O];if(0===P){var g=o[O];D=[g]}for(var i=0;i=0)&&(L[F]=1^P,S.push(F),0===P)){var g=o[F];C(g)||(g.reverse(),D.push(g))}}0===P&&r.push(D)}return r};function Bh(t,e){for(var r=new Array(t),n=0;n0)-(t<0)},jh.abs=function(t){var e=t>>31;return(t^e)-e},jh.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},jh.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},jh.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},jh.countTrailingZeros=Uh,jh.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},jh.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},jh.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var Vh=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,a=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--a;t[e]=n<>>8&255]<<16|Vh[t>>>16&255]<<8|Vh[t>>>24&255]},jh.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},jh.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},jh.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},jh.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},jh.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Uh(t)+1};var Hh=qh;function qh(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e>1,o=Xh(t[i],e);o<=0?(0===o&&(a=i),r=i+1):o>0&&(n=i-1)}return a}function Qh(t,e){for(var r=new Array(t.length),n=0,a=r.length;n=t.length||0!==Xh(t[d],i)););}return r}function $h(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&s.push(a[u]);e.push(s)}return Yh(e)},Gh.skeleton=$h,Gh.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function m(t){for(var e=g(t);;){var r=e,n=2*t+1,a=2*(t+1),i=t;if(n0;){var r=v(t);if(r>=0){var n=g(r);if(e0){var t=w[0];return p(0,T-1),T-=1,m(0),t}return-1}function b(t,e){var r=w[t];return l[r]===e?t:(l[r]=-1/0,y(t),x(),l[r]=e,y((T+=1)-1))}function _(t){if(!s[t]){s[t]=!0;var e=i[t],r=o[t];i[r]>=0&&(i[r]=e),o[e]>=0&&(o[e]=r),A[e]>=0&&b(A[e],d(e)),A[r]>=0&&b(A[r],d(r))}}for(var w=[],A=new Array(n),u=0;u>1;u>=0;--u)m(u);for(;;){var k=x();if(k<0||l[k]>r)break;_(k)}for(var E=[],u=0;u=0&&r>=0&&e!==r){var n=A[e],a=A[r];n!==a&&S.push([n,a])}}),Gh.unique(Gh.normalize(S)),{positions:E,edges:S}};var td=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;n<1&&e("Must have at least one array argument");var a=t.scalarArguments||0;a<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var i=t.getters||[],o=new Array(n),l=0;l=0?o[l]=!0:o[l]=!1;return function(t,e,r,n,a,i){var o=i.length,l=a.length;if(l<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var s="extractContour"+a.join("_"),u=[],c=[],f=[],h=0;h0&&v.push(id(h,a[d-1])+"*"+ad(a[d-1])),c.push(fd(h,a[d])+"=("+v.join("-")+")|0")}for(var h=0;h=0;--h)m.push(ad(a[h]));c.push(xd+"=("+m.join("*")+")|0",md+"=mallocUint32("+xd+")",vd+"=mallocUint32("+xd+")",bd+"=0"),c.push(hd(0)+"=0");for(var d=1;d<1<0;v=v-1&d)g.push(vd+"["+bd+"+"+pd(v)+"]");g.push(gd(0));for(var v=0;v=0;--e)w(e,0);for(var r=[],e=0;e0){",cd(a[e]),"=1;");t(e-1,r|1<0;--r)e+=kd[r]/(t+r);var n=t+Td+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}(Ad=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(Ed(e));e-=1;for(var r=Md[0],n=1;n<9;n++)r+=Md[n]/(e+n);var a=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(a,e+.5)*Math.exp(-a)*r}).log=Ed;var Cd=function(t){var e=t.length;if(e0;--a)n=o[a],r=i[a],i[a]=i[n],i[n]=r,o[a]=o[r],o[r]=n,l=(l+r)*a;return So.freeUint32(o),So.freeUint32(i),l},Od.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,a,i,o=1;for((r=r||new Array(t))[0]=0,i=1;i0;--i)e=e-(n=e/o|0)*o|0,o=o/i|0,a=0|r[i],r[i]=0|r[n],r[n]=0|a;return r};var Rd=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(Ad(t+1)),r=[],n=0;n= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"}),Id=function(t,e){var r=[];return e=+e||0,Dd(t.hi(t.shape[0]-1),r,e),r};var Pd=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=Id(t,e),n=r.length,a=new Array(n),i=new Array(n),o=0;o c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var i=[],o=[],l=0;l>>7){");for(var l=0;l<1<<(1<128&&l%128==0){u.length>0&&c.push("}}");var f="vExtra"+u.length;n.push("case ",l>>>7,":",f,"(m&0x7f,",o.join(),");break;"),c=["function ",f,"(m,",o.join(),"){switch(m){"],u.push(c)}c.push("case ",127&l,":");for(var h=new Array(r),d=new Array(r),p=new Array(r),g=new Array(r),v=0,m=0;mm)&&!(l&1<0&&(A="+"+p[y]+"*c");var M=h[y].length/v*.5,T=.5+g[y]/v*.5;w.push("d"+y+"-"+T+"-"+M+"*("+h[y].join("+")+A+")/("+d[y].join("+")+")")}c.push("a.push([",w.join(),"]);","break;")}n.push("}},"),u.length>0&&c.push("}}");for(var k=[],l=0;l<1<8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var i=3*n;t.height0&&(c+=.02);for(var h=new Float32Array(u),d=0,p=-.5*c,f=0;fl[A]&&(i.uniforms.dataAxis=t,i.uniforms.screenOffset=e,i.uniforms.color=g[n],i.uniforms.angle=v[n],s.drawArrays(s.TRIANGLES,l[A],l[M]-l[A]))),m[n]&&w&&(e[1^n]-=T*h*y[n],i.uniforms.dataAxis=r,i.uniforms.screenOffset=e,i.uniforms.color=x[n],i.uniforms.angle=b[n],s.drawArrays(s.TRIANGLES,_,w)),e[1^n]=T*u[2+(1^n)]-1,d[n+2]&&(e[1^n]+=T*h*p[n+2],Al[A]&&(i.uniforms.dataAxis=t,i.uniforms.screenOffset=e,i.uniforms.color=g[n+2],i.uniforms.angle=v[n+2],s.drawArrays(s.TRIANGLES,l[A],l[M]-l[A]))),m[n+2]&&w&&(e[1^n]+=T*h*y[n+2],i.uniforms.dataAxis=r,i.uniforms.screenOffset=e,i.uniforms.color=x[n+2],i.uniforms.angle=b[n+2],s.drawArrays(s.TRIANGLES,_,w))}}(),Xd.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,a=r.gl,i=r.screenBox,o=r.titleCenter,l=r.titleAngle,s=r.titleColor,u=r.pixelRatio;if(this.titleCount){for(var c=0;c<2;++c)e[c]=2*(o[c]*u-i[c])/(i[2+c]-i[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=l,n.uniforms.color=s,a.drawArrays(a.TRIANGLES,this.titleOffset,this.titleCount)}}}(),Xd.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,a=this.shader,i=n._tickBounds,o=n.dataBox,l=n.screenBox,s=n.viewBox;a.bind();for(var u=0;u<2;++u){var c=i[u],f=i[u+2]-c,h=.5*(o[u+2]+o[u]),d=o[u+2]-o[u],p=s[u],g=s[u+2]-p,v=l[u],m=l[u+2]-v;e[u]=2*f/d*g/m,t[u]=2*(c-h)/d*g/m}r[1]=2*n.pixelRatio/(l[3]-l[1]),r[0]=r[1]*(l[3]-l[1])/(l[2]-l[0]),a.uniforms.dataScale=e,a.uniforms.dataShift=t,a.uniforms.textScale=r,this.vbo.bind(),a.attributes.textCoordinate.pointer()}}(),Xd.update=function(t){var e,r,n,a,i,o=[],l=t.ticks,s=t.bounds;for(i=0;i<2;++i){var u=[Math.floor(o.length/3)],c=[-1/0],f=l[i];for(e=0;ea||n[1]<0||n[1]>a)throw new Error("gl-texture2d: Invalid texture size");var i=np(n,e.stride.slice()),o=0;"float32"===r?o=t.FLOAT:"float64"===r?(o=t.FLOAT,i=!1,r="float32"):"uint8"===r?o=t.UNSIGNED_BYTE:(o=t.UNSIGNED_BYTE,i=!1,r="uint8");var l,s,u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=Si(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}o!==t.FLOAT||t.getExtension("OES_texture_float")||(o=t.UNSIGNED_BYTE,i=!1);var c=e.size;if(i)l=0===e.offset&&e.data.length===c?e.data:e.data.subarray(e.offset,e.offset+c);else{var f=[n[2],n[2]*n[0],1];s=So.malloc(c,r);var h=Si(s,n,f,0);"float32"!==r&&"float64"!==r||o!==t.UNSIGNED_BYTE?fi.assign(h,e):Kd(h,e),l=s.subarray(0,c)}var d=ap(t);t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,o,l),i||So.free(s);return new ep(t,d,n[0],n[1],u,o)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")},Zd=null,Jd=null,Qd=null;function $d(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var Kd=function(t,e){fi.muls(t,e,255)};function tp(t,e,r){var n=t.gl,a=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function ep(t,e,r,n,a,i){this.gl=t,this.handle=e,this.format=a,this.type=i,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,l=[this._wrapS,this._wrapT];Object.defineProperties(l,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=l;var s=[this._shape[0],this._shape[1]];Object.defineProperties(s,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=s}var rp=ep.prototype;function np(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function ap(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function ip(t,e,r,n,a){var i=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture shape");if(a===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=ap(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,a,null),new ep(t,o,e,r,n,a)}Object.defineProperties(rp,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Zd.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),Jd.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Zd.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),Jd.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),Qd.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),Qd.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(Qd.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return tp(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return tp(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,tp(this,this._shape[0],t),t}}}),rp.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},rp.dispose=function(){this.gl.deleteTexture(this.handle)},rp.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},rp.setPixels=function(t,e,r,n){var a=this.gl;this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0;var i=$d(t)?t:t.raw;if(i){this._mipLevels.indexOf(n)<0?(a.texImage2D(a.TEXTURE_2D,0,this.format,this.format,this.type,i),this._mipLevels.push(n)):a.texSubImage2D(a.TEXTURE_2D,n,e,r,this.format,this.type,i)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,n,a,i,o,l){var s=l.dtype,u=l.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var c=0,f=0,h=np(u,l.stride.slice());"float32"===s?c=t.FLOAT:"float64"===s?(c=t.FLOAT,h=!1,s="float32"):"uint8"===s?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,h=!1,s="uint8");if(2===u.length)f=t.LUMINANCE,u=[u[0],u[1],1],l=Si(l.data,u,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])f=t.ALPHA;else if(2===u[2])f=t.LUMINANCE_ALPHA;else if(3===u[2])f=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");f=t.RGBA}u[2]}f!==t.LUMINANCE&&f!==t.ALPHA||a!==t.LUMINANCE&&a!==t.ALPHA||(f=a);if(f!==a)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=l.size,p=o.indexOf(n)<0;p&&o.push(n);if(c===i&&h)0===l.offset&&l.data.length===d?p?t.texImage2D(t.TEXTURE_2D,n,a,u[0],u[1],0,a,i,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],a,i,l.data):p?t.texImage2D(t.TEXTURE_2D,n,a,u[0],u[1],0,a,i,l.data.subarray(l.offset,l.offset+d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],a,i,l.data.subarray(l.offset,l.offset+d));else{var g;g=i===t.FLOAT?So.mallocFloat32(d):So.mallocUint8(d);var v=Si(g,u,[u[2],u[2]*u[0],1]);c===t.FLOAT&&i===t.UNSIGNED_BYTE?Kd(v,l):fi.assign(v,l),p?t.texImage2D(t.TEXTURE_2D,n,a,u[0],u[1],0,a,i,g.subarray(0,d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],a,i,g.subarray(0,d)),i===t.FLOAT?So.freeFloat32(g):So.freeUint8(g)}}(a,e,r,n,this.format,this.type,this._mipLevels,t)}};var op,lp,sp,up,cp=function(t,e,r,n){op||(op=t.FRAMEBUFFER_UNSUPPORTED,lp=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,sp=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,up=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var a=t.getExtension("WEBGL_draw_buffers");!fp&&a&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);fp=new Array(r+1);for(var n=0;n<=r;++n){for(var a=new Array(r),i=0;ii||r<0||r>i)throw new Error("gl-fbo: Parameters are too large for FBO");var o=1;if("color"in(n=n||{})){if((o=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(o>1){if(!a)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(o>t.getParameter(a.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+o+" draw buffers")}}var l=t.UNSIGNED_BYTE,s=t.getExtension("OES_texture_float");if(n.float&&o>0){if(!s)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&o>0&&s&&(l=t.FLOAT);var u=!0;"depth"in n&&(u=!!n.depth);var c=!1;"stencil"in n&&(c=!!n.stencil);return new mp(t,e,r,l,o,u,c,a)},fp=null;function hp(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function dp(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function pp(t){switch(t){case op:throw new Error("gl-fbo: Framebuffer unsupported");case lp:throw new Error("gl-fbo: Framebuffer incomplete attachment");case sp:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case up:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function gp(t,e,r,n,a,i){if(!n)return null;var o=Yd(t,e,r,a,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,i,t.TEXTURE_2D,o.handle,0),o}function vp(t,e,r,n,a){var i=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,i),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),i}function mp(t,e,r,n,a,i,o,l){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=l,this.color=new Array(a);for(var s=0;s1&&l.drawBuffersWEBGL(fp[o]);var h=r.getExtension("WEBGL_depth_texture");h?s?t.depth=gp(r,a,i,h.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u&&(t.depth=gp(r,a,i,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):u&&s?t._depth_rb=vp(r,a,i,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u?t._depth_rb=vp(r,a,i,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):s&&(t._depth_rb=vp(r,a,i,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var d=r.checkFramebufferStatus(r.FRAMEBUFFER);if(d!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),f=0;fa||r<0||r>a)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var i=hp(n),o=0;othis.buffer.length){So.free(this.buffer);for(var n=this.buffer=So.mallocUint8(_p(r*e*4)),a=0;a=0){var g=e[p]-n[p]*(e[p+2]-e[p])/(n[p+2]-n[p]);0===p?o.drawLine(g,e[1],g,e[3],d[p],h[p]):o.drawLine(e[0],g,e[2],g,d[p],h[p])}}for(p=0;p=0;--t)this.objects[t].dispose();this.objects.length=0;for(t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},Ep.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},Ep.removeObject=function(t){for(var e=this.objects,r=0;r0){var m=r*c;o.drawBox(f-m,h-m,d+m,h+m,i),o.drawBox(f-m,p-m,d+m,p+m,i),o.drawBox(f-m,h-m,f+m,p+m,i),o.drawBox(d-m,h-m,d+m,p+m,i)}}}},Dp.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},Dp.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)};var Ip=function(t,e){var r=new Pp(t);return r.update(e),t.addOverlay(r),r};function Pp(t){this.plot=t,this.enable=[!0,!0,!1,!1],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=[1/0,1/0]}var Fp=Pp.prototype;Fp.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},Fp.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,a=this.plot,i=a.line,o=a.dataBox,l=a.viewBox;if(i.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var s=l[0]+(n[0]-o[0])/(o[2]-o[0])*(l[2]-l[0]),u=l[1]+(n[1]-o[1])/(o[3]-o[1])*(l[3]-l[1]);t[0]&&i.drawLine(s,u,l[0],u,e[0],r[0]),t[1]&&i.drawLine(s,u,s,l[1],e[1],r[1]),t[2]&&i.drawLine(s,u,l[2],u,e[2],r[2]),t[3]&&i.drawLine(s,u,s,l[3],e[3],r[3])}},Fp.dispose=function(){this.plot.removeOverlay(this)};var zp=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,a=e;try{var i=[t];0===t.indexOf("webgl")&&i.push("experimental-"+t);for(var o=0;o0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},qp.prototype.on=qp.prototype.addListener,qp.prototype.once=function(t,e){if(!Xp(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},qp.prototype.removeListener=function(t,e){var r,n,a,i;if(!Xp(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(a=(r=this._events[t]).length,n=-1,r===e||Xp(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Wp(r)){for(i=a;i-- >0;)if(r[i]===e||r[i].listener&&r[i].listener===e){n=i;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},qp.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(Xp(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},qp.prototype.listeners=function(t){return this._events&&this._events[t]?Xp(this._events[t])?[this._events[t]]:this._events[t].slice():[]},qp.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(Xp(e))return 1;if(e)return e.length}return 0},qp.listenerCount=function(t,e){return t.listenerCount(e)};var Zp,Jp=Gp.EventEmitter,Qp={init:function(t){if(t._ev instanceof Jp)return t;var e=new Jp,r=new Jp;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,a){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,a),e.emit(n,a),r.emit(n,a)},t},triggerHandler:function(t,e,r){var n,a;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var i=t._ev;if(!i)return n;var o=i._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},tg.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:ne.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:ne.constrain(Math.floor(3*e),0,2),Hp[e][t]},tg.unhover=Zp.wrapped,tg.unhoverRaw=Zp.raw,tg.init=function(t){var e,r,n,a,i,o,l,s,u=t.gd,c=1,f=h.DBLCLICKDELAY,d=t.element;u._mouseDownTime||(u._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,jp?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=t.clampFn||function(t,e,r){return Math.abs(t)f&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!s){var r;try{r=new MouseEvent("click",e)}catch(t){var n=rg(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}l.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&R.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},tg.coverSlip=eg;function ng(t,e,r,n){n=n||ne.identity,Array.isArray(t)&&(e[0][r]=n(t))}var ag={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},flat:function(t,e){for(var r=new Array(t.length),n=0;n=0&&r.index-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==e.extraText&&(s+=e.extraText),void 0!==e.zLabel?(void 0!==e.xLabel&&(s+="x: "+e.xLabel+"
"),void 0!==e.yLabel&&(s+="y: "+e.yLabel+"
"),s+=(s?"z: ":"")+e.zLabel):w&&e[a+"Label"]===v?s=e[("x"===a?"y":"x")+"Label"]||"":void 0===e.xLabel?void 0!==e.yLabel&&(s=e.yLabel):s=void 0===e.yLabel?e.xLabel:"("+e.xLabel+", "+e.yLabel+")",e.text&&!Array.isArray(e.text)&&(s+=(s?"
":"")+e.text),""===s&&(""===l&&r.remove(),s=l);var g=r.select("text.nums").call(Zr.font,e.fontFamily||c,e.fontSize||f,e.fontColor||d).text(s).attr("data-notex",1).call(Ar.positionText,0,0).call(Ar.convertToTspans,n),m=r.select("text.name"),y=0;l&&l!==s?(m.call(Zr.font,e.fontFamily||c,e.fontSize||f,h).text(l).attr("data-notex",1).call(Ar.positionText,0,0).call(Ar.convertToTspans,n),y=m.node().getBoundingClientRect().width+2*yg):(m.remove(),r.select("rect").remove()),r.select("path").style({fill:h,stroke:d});var A,M,T=g.node().getBoundingClientRect(),k=e.xa._offset+(e.x0+e.x1)/2,E=e.ya._offset+(e.y0+e.y1)/2,C=Math.abs(e.x1-e.x0),S=Math.abs(e.y1-e.y0),L=T.width+mg+yg+y;e.ty0=x-T.top,e.bx=T.width+2*yg,e.by=T.height+2*yg,e.anchor="start",e.txwidth=T.width,e.tx2width=y,e.offset=0,i?(e.pos=k,A=E+S/2+L<=_,M=E-S/2-L>=0,"top"!==e.idealAlign&&A||!M?A?(E+=S/2,e.anchor="start"):e.anchor="middle":(E-=S/2,e.anchor="end")):(e.pos=E,A=k+C/2+L<=b,M=k-C/2-L>=0,"left"!==e.idealAlign&&A||!M?A?(k+=C/2,e.anchor="start"):e.anchor="middle":(k-=C/2,e.anchor="end")),g.attr("text-anchor",e.anchor),y&&m.attr("text-anchor",e.anchor),r.attr("transform","translate("+k+","+E+")"+(i?"rotate("+hg+")":""))}),C}function bg(e,r){e.each(function(e){var n=t.select(this);if(e.del)n.remove();else{var a="end"===e.anchor?-1:1,i=n.select("text.nums"),o={start:1,end:-1,middle:0}[e.anchor],l=o*(mg+yg),s=l+o*(e.txwidth+yg),u=0,c=e.offset;"middle"===e.anchor&&(l-=e.tx2width/2,s+=e.txwidth/2+yg),r&&(c*=-vg,u=e.offset*gg),n.select("path").attr("d","middle"===e.anchor?"M-"+(e.bx/2+e.tx2width/2)+","+(c-e.by/2)+"h"+e.bx+"v"+e.by+"h-"+e.bx+"Z":"M0,0L"+(a*mg+u)+","+(mg+c)+"v"+(e.by/2-mg)+"h"+a*e.bx+"v-"+e.by+"H"+(a*mg+u)+"V"+(c-mg)+"Z"),i.call(Ar.positionText,l+u,c+e.ty0-e.by/2+yg),e.tx2width&&(n.select("text.name").call(Ar.positionText,s+o*yg+u,c+e.ty0-e.by/2+yg),n.select("rect").call(Zr.setRect,s+(o-1)*e.tx2width/2+u,c-e.by/2-1,e.tx2width,e.by+2))}})}function _g(t,e){var r=t.index,n=t.trace||{},a=t.cd[0],i=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return ne.castOption(a,r,t)||ne.extractOption({},n,"",e)}:function(t,e){return ne.extractOption(i,n,t,e)};function l(e,r,n){var a=o(r,n);a&&(t[e]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=ne.constrain(t.x0,0,t.xa._length),t.x1=ne.constrain(t.x1,0,t.xa._length),t.y0=ne.constrain(t.y0,0,t.ya._length),t.y1=ne.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:ma.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:ma.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var s=ma.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+s+" / -"+ma.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+s,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=ma.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+ma.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function wg(t,e){var r,n,a=e.container,i=e.fullLayout,o=e.event,s=!!t.hLinePoint,u=!!t.vLinePoint;if(a.selectAll(".spikeline").remove(),u||s){var c=Ie.combine(i.plot_bgcolor,i.paper_bgcolor);if(s){var f,h,d=t.hLinePoint;r=d&&d.xa,"cursor"===(n=d&&d.ya).spikesnap?(f=o.pointerX,h=o.pointerY):(f=r._offset+d.x,h=n._offset+d.y);var p,g,v=l.readability(d.color,c)<1.5?Ie.contrast(c):d.color,m=n.spikemode,y=n.spikethickness,x=n.spikecolor||v,b=n._boundingBox,_=(b.left+b.right)/2H.width||U<0||U>H.height)return Kp.unhoverRaw(r,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(_="xval"in n?ag.flat(o,n.xval):ag.p2c(d,j),w="yval"in n?ag.flat(o,n.yval):ag.p2c(p,U),!e(_[0])||!e(w[0]))return ne.warn("Fx.hover failed",n,r),Kp.unhoverRaw(r,n)}var q=1/0;for(M=0;MI&&(z.splice(0,I),q=z[0].distance),c&&0!==F&&0===z.length){D.distance=F,D.index=!1;var Z=k._module.hoverPoints(D,L,O,"closest",l._hoverlayer);if(Z&&(Z=Z.filter(function(t){return t.spikeDistance<=F})),Z&&Z.length){var J,Q=Z.filter(function(t){return t.xa.showspikes});if(Q.length){var $=Q[0];e($.x0)&&e($.y0)&&(J=rt($),(!B.vLinePoint||B.vLinePoint.spikeDistance>J.spikeDistance)&&(B.vLinePoint=J))}var K=Z.filter(function(t){return t.ya.showspikes});if(K.length){var tt=K[0];e(tt.x0)&&e(tt.y0)&&(J=rt(tt),(!B.hLinePoint||B.hLinePoint.spikeDistance>J.spikeDistance)&&(B.hLinePoint=J))}}}}function et(t,e){for(var r,n=null,a=1/0,i=0;i1,gt=Ie.combine(l.plot_bgcolor||Ie.background,l.paper_bgcolor),vt={hovermode:b,rotateLabels:pt,bgColor:gt,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},mt=xg(z,vt,r);if(function(t,e,r){var n,a,i,o,l,s,u,c=0,f=t.map(function(t,n){var a=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===a._id.charAt(0)?pg:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function h(t){var e=t[0],r=t[t.length-1];if(a=e.pmin-e.pos-e.dp+e.size,i=r.pos+r.dp+r.size-e.pmax,a>.01){for(l=t.length-1;l>=0;l--)t[l].dp+=a;n=!1}if(!(i<.01)){if(a<-.01){for(l=t.length-1;l>=0;l--)t[l].dp-=i;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(s=t[o]).pos>e.pmax-1&&(s.del=!0,u--);for(o=0;o=0;l--)t[l].dp-=i;for(o=t.length-1;o>=0&&!(u<=0);o--)(s=t[o]).pos+s.dp+s.size>e.pmax&&(s.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(d.push.apply(d,p),f.splice(o+1,1),u=0,l=d.length-1;l>=0;l--)u+=d[l].dp;for(i=u/d.length,l=d.length-1;l>=0;l--)d[l].dp-=i;n=!1}else o++}f.forEach(h)}for(o=f.length-1;o>=0;o--){var m=f[o];for(l=m.length-1;l>=0;l--){var y=m[l],x=t[y.i];x.offset=y.dp,x.del=y.del}}}(z,pt?"xa":"ya",l),bg(mt,pt),n.target&&n.target.tagName){var yt=R.getComponentMethod("annotations","hasClickToShow")(r,ht);cg(t.select(n.target),yt?"pointer":"")}if(!n.target||i||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var a=r[n],i=t._hoverdata[n];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(r,0,ft))return;ft&&r.emit("plotly_unhover",{event:n,points:ft});r.emit("plotly_hover",{event:n,points:r._hoverdata,xaxes:d,yaxes:p,xvals:_,yvals:w})}(r,n,a,i)})},fg.loneHover=function(e,r){var n={color:e.color||Ie.defaultLine,x0:e.x0||e.x||0,x1:e.x1||e.x||0,y0:e.y0||e.y||0,y1:e.y1||e.y||0,xLabel:e.xLabel,yLabel:e.yLabel,zLabel:e.zLabel,text:e.text,name:e.name,idealAlign:e.idealAlign,borderColor:e.borderColor,fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=t.select(r.container),i=r.outerContainer?t.select(r.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||Ie.background,container:a,outerContainer:i},l=xg([n],o,r.gd);return bg(l,o.rotateLabels),l.node()};var Mg=fg.hover,Tg=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),ne.coerceFont(r,"hoverlabel.font",n.font)};var kg={moduleType:"component",name:"fx",constants:we,schema:{layout:Me},attributes:E,layoutAttributes:Me,supplyLayoutGlobalDefaults:function(t,e){Tg(0,0,function(r,n){return ne.coerce(t,e,Me,r,n)})},supplyDefaults:function(t,e,r,n){Tg(0,0,function(r,n){return ne.coerce(t,e,E,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return ne.coerce(t,e,Me,r,n)}var a;n("dragmode"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))},Lg=function(){},Og=_r.FROM_BL,Rg=function(t,e,r){void 0===r&&(r=Og[t.constraintoward||"center"]);var n=[t.r2l(t.range[0]),t.r2l(t.range[1])],a=n[0]+(n[1]-n[0])*r;t.range=t._input.range=[t.l2r(a+(n[0]-a)*e),t.l2r(a+(n[1]-a)*e)]},Dg={},Ig=Se.id2name,Pg=ua,Fg=r.ALMOST_EQUAL,zg=_r.FROM_BL;function Ng(t,e){var r=t._inputDomain,n=zg[t.constraintoward],a=r[0]+(r[1]-r[0])*n;t.domain=t._input.domain=[a+(r[0]-a)/e,a+(r[1]-a)/e]}Dg.enforce=function(t){var e,r,n,a,i,o,l,s=t._fullLayout,u=s._axisConstraintGroups||[];for(e=0;eFg*d)||m)for(r=0;rE&&LT&&(T=L);l/=(T-M)/(2*k),M=a.l2r(M),T=a.l2r(T),a.range=a._input.range=_0)return 1<=0)return 1<Math.abs(s)?(n.boxEnd[1]=n.boxStart[1]+Math.abs(l)*b*(s>=0?1:-1),n.boxEnd[1]u[3]&&(n.boxEnd[1]=u[3],n.boxEnd[0]=n.boxStart[0]+(u[3]-n.boxStart[1])/Math.abs(b))):(n.boxEnd[0]=n.boxStart[0]+Math.abs(s)/b*(l>=0?1:-1),n.boxEnd[0]u[2]&&(n.boxEnd[0]=u[2],n.boxEnd[1]=n.boxStart[1]+(u[2]-n.boxStart[0])*Math.abs(b)))}}else n.boxEnabled?(l=n.boxStart[0]!==n.boxEnd[0],s=n.boxStart[1]!==n.boxEnd[1],l||s?(l&&(g(0,n.boxStart[0],n.boxEnd[0]),t.xaxis.autorange=!1),s&&(g(1,n.boxStart[1],n.boxEnd[1]),t.yaxis.autorange=!1),t.relayoutCallback()):t.glplot.setDirty(),n.boxEnabled=!1,n.boxInited=!1):n.boxInited&&(n.boxInited=!1);break;case"pan":n.boxEnabled=!1,n.boxInited=!1,e?(n.panning||(n.dragStart[0]=i,n.dragStart[1]=o),Math.abs(n.dragStart[0]-i)r?r:t:te?e:t};var Jg={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]},Qg=function(){for(var t=0;t10&&/[0-9](?:\s|\/)/.test(r)&&(i=r.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),a=r.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof r)a="rgb",i=[r>>>16,(65280&r)>>>8,255&r];else if(Kg(r)){var f=Qg(r.r,r.red,r.R,null);null!==f?(a="rgb",i=[f,Qg(r.g,r.green,r.G),Qg(r.b,r.blue,r.B)]):(a="hsl",i=[Qg(r.h,r.hue,r.H),Qg(r.s,r.saturation,r.S),Qg(r.l,r.lightness,r.L,r.b,r.brightness)]),o=Qg(r.a,r.alpha,r.opacity,1),null!=r.opacity&&(o/=100)}else(Array.isArray(r)||t.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(r))&&(i=[r[0],r[1],r[2]],a="rgb",o=4===r.length?r[3]:1);return{space:a,values:i,alpha:o}};var e={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var ev=function(t){var e,r,n,a,i,o=t[0]/360,l=t[1]/100,s=t[2]/100;if(0===l)return[i=255*s,i,i];e=2*s-(r=s<.5?s*(1+l):s+l-s*l),a=[0,0,0];for(var u=0;u<3;u++)(n=o+1/3*-(u-1))<0?n++:n>1&&n--,i=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,a[u]=255*i;return a},rv=function(t){switch(t){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}},nv=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=rv(e),n=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(n.set(t),n);var a="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:255,a&&(n[0]/=255,n[1]/=255,n[2]/=255,n[3]/=255),n):(t.length&&"string"!=typeof t||((t=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=tv(t);return r.space?((e=Array(3))[0]=Zg(r.values[0],0,255),e[1]=Zg(r.values[1],0,255),e[2]=Zg(r.values[2],0,255),"h"===r.space[0]&&(e=ev(e)),e.push(Zg(r.alpha,0,1)),e):[]}(t))[0]/=255,t[1]/=255,t[2]/=255),a?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:1):(n[0]=Zg(Math.round(255*t[0]),0,255),n[1]=Zg(Math.round(255*t[1]),0,255),n[2]=Zg(Math.round(255*t[2]),0,255),n[3]=null==t[3]?255:Zg(Math.floor(255*t[3]),0,255)),n)};var av=function(t){return t?nv(t):[0,0,0,1]};function iv(t){this.scene=t,this.gl=t.gl,this.pixelRatio=t.pixelRatio,this.screenBox=[0,0,1,1],this.viewBox=[0,0,1,1],this.dataBox=[-1,-1,1,1],this.borderLineEnable=[!1,!1,!1,!1],this.borderLineWidth=[1,1,1,1],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.ticks=[[],[]],this.tickEnable=[!0,!0,!1,!1],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labels=["x","y"],this.labelEnable=[!0,!0,!1,!1],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelPad=[15,15,15,15],this.labelSize=[12,12],this.labelFont=["sans-serif","sans-serif"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.title="",this.titleEnable=!0,this.titleCenter=[0,0,0,0],this.titleAngle=0,this.titleColor=[0,0,0,1],this.titleFont="sans-serif",this.titleSize=18,this.gridLineEnable=[!0,!0],this.gridLineColor=[[0,0,0,.5],[0,0,0,.5]],this.gridLineWidth=[1,1],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[1,1],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderColor=!1,this.backgroundColor=[0,0,0,0],this.static=this.scene.staticPlot}var ov=iv.prototype,lv=["xaxis","yaxis"];ov.merge=function(t){var e,r,n,a,i,o,l,s,u,c,f;for(this.titleEnable=!1,this.backgroundColor=av(t.plot_bgcolor),c=0;c<2;++c){var h=(e=lv[c]).charAt(0);for(n=(r=t[this.scene[e]._name]).title===this.scene.fullLayout._dfltTitle[h]?"":r.title,f=0;f<=2;f+=2)this.labelEnable[c+f]=!1,this.labels[c+f]=Sg(n),this.labelColor[c+f]=av(r.titlefont.color),this.labelFont[c+f]=r.titlefont.family,this.labelSize[c+f]=r.titlefont.size,this.labelPad[c+f]=this.getLabelPad(e,r),this.tickEnable[c+f]=!1,this.tickColor[c+f]=av((r.tickfont||{}).color),this.tickAngle[c+f]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[c+f]=this.getTickPad(r),this.tickMarkLength[c+f]=0,this.tickMarkWidth[c+f]=r.tickwidth||0,this.tickMarkColor[c+f]=av(r.tickcolor),this.borderLineEnable[c+f]=!1,this.borderLineColor[c+f]=av(r.linecolor),this.borderLineWidth[c+f]=r.linewidth||0;l=this.hasSharedAxis(r),i=this.hasAxisInDfltPos(e,r)&&!l,o=this.hasAxisInAltrPos(e,r)&&!l,a=r.mirror||!1,s=l?-1!==String(a).indexOf("all"):!!a,u=l?"allticks"===a:-1!==String(a).indexOf("ticks"),i?this.labelEnable[c]=!0:o&&(this.labelEnable[c+2]=!0),i?this.tickEnable[c]=r.showticklabels:o&&(this.tickEnable[c+2]=r.showticklabels),(i||s)&&(this.borderLineEnable[c]=r.showline),(o||s)&&(this.borderLineEnable[c+2]=r.showline),(i||u)&&(this.tickMarkLength[c]=this.getTickMarkLength(r)),(o||u)&&(this.tickMarkLength[c+2]=this.getTickMarkLength(r)),this.gridLineEnable[c]=r.showgrid,this.gridLineColor[c]=av(r.gridcolor),this.gridLineWidth[c]=r.gridwidth,this.zeroLineEnable[c]=r.zeroline,this.zeroLineColor[c]=av(r.zerolinecolor),this.zeroLineWidth[c]=r.zerolinewidth}},ov.hasSharedAxis=function(t){var e=this.scene,r=e.fullLayout._subplots.gl2d;return 0!==ma.findSubplotsWithAxis(r,t).indexOf(e.id)},ov.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},ov.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},ov.getLabelPad=function(t,e){var r=e.titlefont.size,n=e.showticklabels;return"xaxis"===t?"top"===e.side?r*(1.5+(n?1:0))-10:r*(1.5+(n?.5:0))-10:"yaxis"===t?"right"===e.side?10+r*(1.5+(n?1:.5)):10+r*(1.5+(n?.5:0)):void 0},ov.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},ov.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e};var sv,uv,cv=function(t){return new iv(t)},fv=Dg.enforce,hv=Dg.clean,dv=ca,pv=["xaxis","yaxis"],gv=Ce.SUBPLOT_PATTERN;function vv(t,e){this.container=t.container,this.graphDiv=t.graphDiv,this.pixelRatio=t.plotGlPixelRatio||window.devicePixelRatio,this.id=t.id,this.staticPlot=!!t.staticPlot,this.scrollZoom=this.graphDiv._context.scrollZoom,this.fullData=null,this.updateRefs(e),this.makeFramework(),this.glplotOptions=cv(this),this.glplotOptions.merge(e),this.glplot=Tp(this.glplotOptions),this.camera=Yg(this),this.traces={},this.spikes=Ip(this.glplot),this.selectBox=Op(this.glplot,{innerFill:!1,outerFill:!0}),this.lastButtonState=0,this.pickResult=null,this.isMouseOver=!0,this.stopped=!1,this.redraw=this.draw.bind(this),this.redraw()}var mv=vv,yv=vv.prototype;yv.makeFramework=function(){if(this.staticPlot){if(!(uv||(sv=document.createElement("canvas"),uv=Np({canvas:sv,preserveDrawingBuffer:!1,premultipliedAlpha:!0,antialias:!0}))))throw new Error("Error creating static canvas/context for image server");this.canvas=sv,this.gl=uv}else{var t=this.container.querySelector(".gl-canvas-focus"),e=Np({canvas:t,preserveDrawingBuffer:!0,premultipliedAlpha:!0});e||function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=Lg);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=Ie.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")}}(this),this.canvas=t,this.gl=e}var r=this.canvas;r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style["pointer-events"]="none",this.updateSize(r),r.className+=" user-select-none";var n=this.svgContainer=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.top=n.style.left="0px",n.style.width=n.style.height="100%",n.style["z-index"]=20,n.style["pointer-events"]="none";var a=this.mouseContainer=document.createElement("div");a.style.position="absolute",a.style["pointer-events"]="auto",this.pickCanvas=this.container.querySelector(".gl-canvas-pick");var i=this.container;i.appendChild(n),i.appendChild(a);var o=this;a.addEventListener("mouseout",function(){o.isMouseOver=!1,o.unhover()}),a.addEventListener("mouseover",function(){o.isMouseOver=!0})},yv.toImage=function(t){t||(t="png"),this.stopped=!0,this.staticPlot&&this.container.appendChild(sv),this.updateSize(this.canvas);var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.clearColor(1,1,1,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),this.glplot.setDirty(),this.glplot.draw(),e.bindFramebuffer(e.FRAMEBUFFER,null);var a=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,a);for(var i=0,o=n-1;i=",">","<="],Av=["[]","()","[)","(]","][",")(","](",")["],Mv={"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["},Tv=m.extendFlat,kv=Tv({},{z:{valType:"data_array",editType:"calc"},x:Tv({},wn.x,{impliedEdits:{xtype:"array"}}),x0:Tv({},wn.x0,{impliedEdits:{xtype:"scaled"}}),dx:Tv({},wn.dx,{impliedEdits:{xtype:"scaled"}}),y:Tv({},wn.y,{impliedEdits:{ytype:"array"}}),y0:Tv({},wn.y0,{impliedEdits:{ytype:"scaled"}}),dy:Tv({},wn.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,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",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,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"}},cr,{autocolorscale:Tv({},cr.autocolorscale,{dflt:!1})},{colorbar:pr}),Ev=Le.dash,Cv=m.extendFlat,Sv=wv,Lv=Av,Ov=wn.line,Rv=Cv({z:kv.z,x:kv.x,x0:kv.x0,dx:kv.dx,y:kv.y,y0:kv.y0,dy:kv.dy,text:kv.text,transpose:kv.transpose,xtype:kv.xtype,ytype:kv.ytype,zhoverformat:kv.zhoverformat,connectgaps:kv.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},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":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:k({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(Sv).concat(Lv),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:Cv({},Ov.color,{editType:"style+colorbars"}),width:Cv({},Ov.width,{editType:"style+colorbars"}),dash:Ev,smoothing:Cv({},Ov.smoothing,{}),editType:"plot"}},cr,{autocolorscale:Cv({},cr.autocolorscale,{dflt:!1}),zmin:Cv({},cr.zmin,{editType:"calc"}),zmax:Cv({},cr.zmax,{editType:"calc"})},{colorbar:pr}),Dv=ne.extendFlat;function Iv(t,e,r){var n={type:"linear",range:[t,e]};return ma.autoTicks(n,(e-t)/(r||15)),n}var Pv=r.BADNUM,Fv=function(t){for(var e=0,r=0;rp&&(v=Math.max(v,Math.abs(t[a][i]-d)/(g-p))))}return v}var Vv=ne.isArrayOrTypedArray,Hv=function(t,e,r,n,a,i){var o,l,s,u=[],c=R.traceIs(t,"contour"),f=R.traceIs(t,"histogram"),h=R.traceIs(t,"gl2d");if(Vv(e)&&e.length>1&&!f&&"category"!==i.type){var d=e.length;if(!(d<=a))return c?e.slice(0,a):e.slice(0,a+1);if(c||h)u=e.slice(0,a);else if(1===a)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],s=1;si){var o=i-n[t];return n[t]=i,o}}return 0},max:function(t,r,n,a){var i=a[r];if(e(i)){if(i=Number(i),!e(n[t]))return n[t]=i,i;if(n[t]d&&dYv){var p=i===Xv?1:6,g=i===Xv?"M12":"M1";return function(e,r){var i=n.c2d(e,Xv,a),l=i.indexOf("-",p);l>0&&(i=i.substr(0,l));var s=n.d2c(i,0,a);if(sQv?t>Yv?t>1.1*Xv?Xv:t>1.1*Wv?Wv:Yv:t>Zv?Zv:t>Jv?Jv:Qv:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function rm(t,e,r,n,a,i){if(n&&t>Yv){var o=nm(e,a,i),l=nm(r,a,i),s=t===Xv?0:1;return o[s]!==l[s]}return Math.floor(r/t)-Math.floor(e/t)>.1}function nm(t,e,r){var n=e.c2d(t,Xv,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}var am=ne.cleanDate,im=r.ONEDAY,om=r.BADNUM,lm=function(t,r,n){var a=r.type,i=n+"bins",o=t[i];o||(o=t[i]={});var l="date"===a?function(t){return t||0===t?am(t,om,o.calendar):null}:function(t){return e(t)?Number(t):null};o.start=l(o.start),o.end=l(o.end);var s="date"===a?im:1,u=o.size;if(e(u))o.size=u>0?Number(u):s;else if("string"!=typeof u)o.size=s;else{var c=u.charAt(0),f=u.substr(1);((f=e(f)?Number(f):0)<=0||"date"!==a||"M"!==c||f!==Math.round(f))&&(o.size=s)}var h="autobin"+n;"boolean"!=typeof t[h]&&(t[h]=t._fullInput[h]=t._input[h]=!((o.start||0===o.start)&&(o.end||0===o.end))),t[h]||(delete t["nbins"+n],delete t._fullInput["nbins"+n])},sm={percent:function(t,e){for(var r=t.length,n=100/e,a=0;av&&l.splice(v,l.length-v),u.length>v&&u.splice(v,u.length-v),um(e,"x",l,o,h,p,c),um(e,"y",u,s,d,g,f);var m=[],y=[],x=[],b="string"==typeof e.xbins.size,_="string"==typeof e.ybins.size,w=[],A=[],M=b?w:e.xbins,T=_?A:e.ybins,k=0,E=[],C=[],S=e.histnorm,L=e.histfunc,O=-1!==S.indexOf("density"),R="max"===L||"min"===L?null:0,D=Gv.count,I=sm[S],P=!1,F=[],z=[],N="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";N&&"count"!==L&&(P="avg"===L,D=Gv[L]);var B=e.xbins,j=h(B.start),U=h(B.end)+(j-ma.tickIncrement(j,B.size,!1,c))/1e6;for(r=j;r=0&&a=0&&i=0;i--)(o=((c[[(r=(a=f[i])[0])-1,n=a[1]]]||p)[2]+(c[[r+1,n]]||p)[2]+(c[[r,n-1]]||p)[2]+(c[[r,n+1]]||p)[2])/20)&&(l[a]=[r,n,o],f.splice(i,1),s=!0);if(!s)throw"findEmpties iterated with no new neighbors";for(a in l)c[a]=l[a],u.push(l[a])}return u.sort(function(t,e){return e[2]-t[2]})}(u),r._interpz=function(t,e,r){var n,a,i=1;if(Array.isArray(r))for(n=0;n.01;n++)i=Uv(t,e,jv(i));return i>.01&&ne.log("interp2d didn't converge quickly",i),t}(u,r._emptypoints,r._interpz))),"fast"===m)if("log"===h.type||"log"===d.type)y("log axis found");else if(!g){if(n.length){var x=(n[n.length-1]-n[0])/(n.length-1),b=Math.abs(x/100);for(c=0;cb){y("x scale is not linear");break}}if(o.length&&"fast"===m){var _=(o[o.length-1]-o[0])/(o.length-1),w=Math.abs(_/100);for(c=0;cw){y("y scale is not linear");break}}}var A=Fv(u),M="scaled"===r.xtype?"":n,T=Hv(r,M,a,i,A,h),k="scaled"===r.ytype?"":o,E=Hv(r,k,l,s,u.length,d);v||(ma.expand(h,T),ma.expand(d,E));var C={x:T,y:E,z:u,text:r.text};if(M&&M.length===T.length-1&&(C.xCenter=M),k&&k.length===E.length-1&&(C.yCenter=k),g&&(C.xRanges=f.xRanges,C.yRanges=f.yRanges,C.pts=f.pts),p&&"constraint"===r.contours.type||hr(r,u,"","z"),p&&r.contours&&"heatmap"===r.contours.coloring){var S={type:"contour"===r.type?"heatmap":"histogram2d",xcalendar:r.xcalendar,ycalendar:r.ycalendar};C.xfill=Hv(S,M,a,i,A,h),C.yfill=Hv(S,k,l,s,u.length,d)}return[C]},pm=m.extendFlat,gm=_r.LINE_SPACING,vm={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},mm=function(e,r){var n={};function a(){var o=e._fullLayout,s=o._size;if("function"==typeof n.fillcolor||"function"==typeof n.line.color){var u,c,f=t.extent(("function"==typeof n.fillcolor?n.fillcolor:n.line.color).domain()),h=[],d=[],p="function"==typeof n.line.color?n.line.color:function(){return n.line.color},g="function"==typeof n.fillcolor?n.fillcolor:function(){return n.fillcolor},v=n.levels.end+n.levels.size/100,m=n.levels.size,y=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(c=0;c<1e5&&(u=n.levels.start+c*m,!(m>0?u>=v:u<=v));c++)u>y&&u0?u>=v:u<=v));c++)u>f[0]&&u1){var V=Math.pow(10,Math.floor(Math.log(U)/Math.LN10));B*=V*ne.roundUp(U/V,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(z.tick0=0)}z.dtick=B}z.domain=[D+S,D+k-S],z.setScale();var H=o._infolayer.selectAll("g."+r).data([0]);H.enter().append("g").classed(r,!0).classed(vm.colorbar,!0).each(function(){var e=t.select(this);e.append("rect").classed(vm.cbbg,!0),e.append("g").classed(vm.cbfills,!0),e.append("g").classed(vm.cblines,!0),e.append("g").classed(vm.cbaxis,!0).classed(vm.crisp,!0),e.append("g").classed(vm.cbtitleunshift,!0).append("g").classed(vm.cbtitle,!0),e.append("rect").classed(vm.cboutline,!0),e.select(".cbtitle").datum(0)}),H.attr("transform","translate("+Math.round(s.l)+","+Math.round(s.t)+")");var q=H.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(s.l)+",-"+Math.round(s.t)+")");z._axislayer=H.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var X,W=s.l+(n.x+E)*s.w,Y=z.titlefont.size;X="top"===n.titleside?(1-(D+k-S))*s.h+s.t+3+.75*Y:(1-(D+S))*s.h+s.t-3-.25*Y,tt(z._id+"title",{attributes:{x:W,y:X,"text-anchor":"start"}})}var Z,J,Q,$=ne.syncOrAsync([Xn.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=H.select(".cbtitle"),a=r.select("text"),i=[-n.outlinewidth/2,n.outlinewidth/2],u=r.select(".h"+z._id+"title-math-group").node(),c=15.6;if(a.node()&&(c=parseInt(a.node().style.fontSize,10)*gm),u?(G=Zr.bBox(u).height)>c&&(i[1]-=(G-c)/2):a.node()&&!a.classed(vm.jsPlaceholder)&&(G=Zr.bBox(a.node()).height),G){if(G+=5,"top"===n.titleside)z.domain[1]-=G/s.h,i[1]*=-1;else{z.domain[0]+=G/s.h;var v=Ar.lineCount(a);i[1]+=(1-v)*c}r.attr("transform","translate("+i+")"),z.setScale()}}H.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(s.h*(1-z.domain[1]))+")"),z._axislayer.attr("transform","translate(0,"+Math.round(-s.t)+")");var m=H.select(".cbfills").selectAll("rect.cbfill").data(d);m.enter().append("rect").classed(vm.cbfill,!0).style("stroke","none"),m.exit().remove(),m.each(function(e,r){var n=[0===r?f[0]:(d[r]+d[r-1])/2,r===d.length-1?f[1]:(d[r]+d[r+1])/2].map(z.c2p).map(Math.round);r!==d.length-1&&(n[1]+=n[1]>n[0]?1:-1);var a=g(e).replace("e-",""),i=l(a).toHexString();t.select(this).attr({x:L,width:Math.max(A,2),y:t.min(n),height:Math.max(t.max(n)-t.min(n),2),fill:i})});var y=H.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?h:[]);return y.enter().append("path").classed(vm.cbline,!0),y.exit().remove(),y.each(function(e){t.select(this).attr("d","M"+L+","+(Math.round(z.c2p(e))+n.line.width/2%1)+"h"+A).call(Zr.lineGroupStyle,n.line.width,p(e),n.line.dash)}),z._axislayer.selectAll("g."+z._id+"tick,path").remove(),z._pos=L+A+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),z.side="right",ne.syncOrAsync([function(){return ma.doTicks(e,z,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=z.titlefont.size,a=z._offset+z._length/2,i=s.l+(z.position||0)*s.w+("right"===z.side?10+r*(z.showticklabels?1:.5):-10-r*(z.showticklabels?.5:0));tt("h"+z._id+"title",{avoid:{selection:t.select(e).selectAll("g."+z._id+"tick"),side:n.titleside,offsetLeft:s.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Xn.previousPromises,function(){var t=A+n.outlinewidth/2+Zr.bBox(z._axislayer.node()).width;if((b=q.select("text")).node()&&!b.classed(vm.jsPlaceholder)){var a,i=q.select(".h"+z._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(n.titleside)?Zr.bBox(i).width:Zr.bBox(q.node()).right-L-s.l,t=Math.max(t,a)}var o=2*n.xpad+t+n.borderwidth+n.outlinewidth/2,l=I-P;H.select(".cbbg").attr({x:L-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:P-C,width:Math.max(o,2),height:Math.max(l+2*C,2)}).call(Ie.fill,n.bgcolor).call(Ie.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),H.selectAll(".cboutline").attr({x:L,y:P+n.ypad+("top"===n.titleside?G:0),width:Math.max(A,2),height:Math.max(l-2*n.ypad-G,2)}).call(Ie.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var u=({center:.5,right:1}[n.xanchor]||0)*o;H.attr("transform","translate("+(s.l-u)+","+s.t+")"),Xn.autoMargin(e,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:l*({bottom:1,middle:.5}[n.yanchor]||0),b:l*({top:1,middle:.5}[n.yanchor]||0)})}],e);if($&&$.then&&(e._promises||[]).push($),e._context.edits.colorbarPosition)Kp.init({element:H.node(),gd:e,prepFn:function(){Z=H.attr("transform"),sg(H)},moveFn:function(t,e){H.attr("transform",Z+" translate("+t+","+e+")"),J=Kp.align(O+t/s.w,M,0,1,n.xanchor),Q=Kp.align(D-e/s.h,k,0,1,n.yanchor);var r=Kp.getCursor(J,Q,n.xanchor,n.yanchor);sg(H,r)},doneFn:function(){sg(H),void 0!==J&&void 0!==Q&&R.call("restyle",e,{"colorbar.x":J,"colorbar.y":Q},i().index)}});return $}function K(t,e){return ne.coerce(F,z,De,t,e)}function tt(t,r){var n,a=i();n=R.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:z,propName:n,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:H.select(".cbtitle")},s="h"===t.charAt(0)?t.substr(1):"h"+t;H.selectAll("."+s+",."+s+"-math-group").remove(),ia.draw(e,t,pm(l,r||{}))}o._infolayer.selectAll("g."+r).remove()}function i(){var t,n,a=r.substr(2);for(t=0;t2?r.value=r.value.slice(2):0===r.length?r.value=[0,1]:r.length<2?(n=parseFloat(r.value[0]),r.value=[n,n+1]):r.value=[parseFloat(r.value[0]),parseFloat(r.value[1])]:e(r.value)&&(n=parseFloat(r.value),r.value=[n,n+1])):(t("contours.value",0),e(r.value)||(Array.isArray(r.value)?r.value=parseFloat(r.value[0]):r.value=0))}(n,c),"="===f?l=c.showlines=!0:(l=n("contours.showlines"),u=n("fillcolor",_m((t.line||{}).color||i,.5))),l)&&(s=n("line.color",u&&wm(u)?_m(r.fillcolor,1):i),n("line.width",2),n("line.dash"));n("line.smoothing"),bm(n,a,s,o)};var km=ne.isArrayOrTypedArray,Em=function(t,r,n,a,i,o){var l,s,u=n("z");if(i=i||"x",o=o||"y",void 0===u||!u.length)return 0;if(Nv(t)){if(l=n(i),s=n(o),!l||!s)return 0}else{if(l=Cm(i,n),s=Cm(o,n),!function(t){for(var r,n=!0,a=!1,i=!1,o=0;o0&&(a=!0);for(var l=0;l>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function Om(t,e,r,n){return new Function([Lm("A","x"+t+"y",e,["y"],n),Lm("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var Rm={ge:Om(">=",!1,"GE"),gt:Om(">",!1,"GT"),lt:Om("<",!0,"LT"),le:Om("<=",!0,"LE"),eq:Om("-",!0,"EQ",!0)},Dm=function(t,e){var r=t.gl,n=Wl(r,Sm.vertex,Sm.fragment),a=Wl(r,Sm.fillVertex,Sm.fragment),i=Po(r),o=Po(r),l=Po(r),s=Po(r),u=Po(r),c=new Im(t,n,a,i,o,l,s,u);return c.update(e),t.addObject(c),c};function Im(t,e,r,n,a,i,o,l){this.plot=t,this.shader=e,this.fillShader=r,this.positionBuffer=n,this.colorBuffer=a,this.idBuffer=i,this.fillPositionBuffer=o,this.fillColorBuffer=l,this.fillVerts=0,this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.numVertices=0,this.lineWidth=1}var Pm,Fm,zm=Im.prototype,Nm=[1,0,0,0,0,1,1,0,1,1,0,1];function Bm(t,e){var r=Math.floor(e);if(r<0)return t[0];if(r>=t.length-1)return t[t.length-1];var n=e-r;return(1-n)*t[r]+n*t[r+1]}zm.draw=(Pm=[1,0,0,0,1,0,0,0,1],Fm=[0,0],function(){var t,e,r=this.plot,n=this.shader,a=this.fillShader,i=this.bounds,o=this.numVertices,l=this.fillVerts,s=r.gl,u=r.viewBox,c=r.dataBox,f=i[2]-i[0],h=i[3]-i[1],d=c[2]-c[0],p=c[3]-c[1];if(Pm[0]=2*f/d,Pm[4]=2*h/p,Pm[6]=2*(i[0]-c[0])/d-1,Pm[7]=2*(i[1]-c[1])/p-1,Fm[0]=u[2]-u[0],Fm[1]=u[3]-u[1],l>0&&(a.bind(),(t=a.uniforms).viewTransform=Pm,t.screenShape=Fm,e=n.attributes,this.fillPositionBuffer.bind(),e.position.pointer(),this.fillColorBuffer.bind(),e.color.pointer(s.UNSIGNED_BYTE,!0),s.drawArrays(s.TRIANGLES,0,l)),o>0){n.bind();var g=this.lineWidth*r.pixelRatio;(t=n.uniforms).viewTransform=Pm,t.screenShape=Fm,t.lineWidth=g,t.pointSize=1e3,e=n.attributes,this.positionBuffer.bind(),e.position.pointer(s.FLOAT,!1,16,0),e.tangent.pointer(s.FLOAT,!1,16,8),this.colorBuffer.bind(),e.color.pointer(s.UNSIGNED_BYTE,!0),s.drawArrays(s.TRIANGLES,0,o),t.lineWidth=0,t.pointSize=g,this.positionBuffer.bind(),e.position.pointer(s.FLOAT,!1,48,0),e.tangent.pointer(s.FLOAT,!1,48,8),this.colorBuffer.bind(),e.color.pointer(s.UNSIGNED_BYTE,!0,12,0),s.drawArrays(s.POINTS,0,o/3)}}),zm.drawPick=function(t){return t},zm.pick=function(t,e,r){return null},zm.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||_i(e[0]),n=t.y||_i(e[1]),a=t.z||new Float32Array(e[0]*e[1]),i=t.levels||[],o=t.levelColors||[],l=this.bounds,s=l[0]=r[0],u=l[1]=n[0],c=l[2]=r[r.length-1],f=l[3]=n[n.length-1];s===c&&(l[2]+=1,c+=1),u===f&&(l[3]+=1,f+=1);var h=1/(c-s),d=1/(f-u);this.lineWidth=t.lineWidth||1;var p=Si(a,e),g=[],v=[],m=[],y=[],x=[[0,0],[e[0]-1,0],[0,e[1]-1],[e[0]-1,e[1]-1]];function b(t,e,r,n){var a=n-r;return Math.abs(a)<1e-6?e:Math.floor(e)+Math.max(.001,Math.min(.999,(t-r)/a))}for(var _=0;_0&&w===i[_-1])){for(var A=Pd(p,w),M=255*o[4*_]|0,T=255*o[4*_+1]|0,k=255*o[4*_+2]|0,E=255*o[4*_+3]|0,C=A.cells,S=A.positions,L=Array(S.length),O=0;O1)){var P,F=I[0],z=I[1],N=p.get(Math.floor(F),Math.floor(z)),B=p.get(Math.floor(F),Math.ceil(z)),j=p.get(Math.ceil(F),Math.floor(z)),U=p.get(Math.ceil(F),Math.ceil(z));0===Math.floor(I[0])&&N<=w!=B>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function Vm(t,e,r,n){return new Function([Um("A","x"+t+"y",e,["y"],n),Um("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var Hm={ge:Vm(">=",!1,"GE"),gt:Vm(">",!1,"GT"),lt:Vm("<",!0,"LT"),le:Vm("<=",!0,"LE"),eq:Vm("-",!0,"EQ",!0)},qm=function(t,e){var r=t.gl,n=Wl(r,jm.vertex,jm.fragment),a=Wl(r,jm.pickVertex,jm.pickFragment),i=Po(r),o=Po(r),l=Po(r),s=Po(r),u=new Gm(t,n,a,i,o,l,s);return u.update(e),t.addObject(u),u};function Gm(t,e,r,n,a,i,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.weightBuffer=a,this.colorBuffer=i,this.idBuffer=o,this.xData=[],this.yData=[],this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.pickOffset=0}var Xm=Gm.prototype,Wm=[0,0,1,0,0,1,1,0,1,1,0,1];function Ym(t,e){this.scene=t,this.uid=e,this.type="contourgl",this.name="",this.hoverinfo="all",this.xData=[],this.yData=[],this.zData=[],this.textLabels=[],this.idToIndex=[],this.bounds=[0,0,0,0],this.contourOptions={z:new Float32Array(0),x:[],y:[],shape:[0,0],levels:[0],levelColors:[0,0,0,1],lineWidth:1},this.contour=Dm(t.glplot,this.contourOptions),this.contour._trace=this,this.heatmapOptions={z:new Float32Array(0),x:[],y:[],shape:[0,0],colorLevels:[0],colorValues:[0,0,0,0]},this.heatmap=qm(t.glplot,this.heatmapOptions),this.heatmap._trace=this}Xm.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.bounds,a=this.numVertices;if(!(a<=0)){var i=e.gl,o=e.dataBox,l=n[2]-n[0],s=n[3]-n[1],u=o[2]-o[0],c=o[3]-o[1];t[0]=2*l/u,t[4]=2*s/c,t[6]=2*(n[0]-o[0])/u-1,t[7]=2*(n[1]-o[1])/c-1,r.bind();var f=r.uniforms;f.viewTransform=t,f.shape=this.shape;var h=r.attributes;this.positionBuffer.bind(),h.position.pointer(),this.weightBuffer.bind(),h.weight.pointer(i.UNSIGNED_BYTE,!1),this.colorBuffer.bind(),h.color.pointer(i.UNSIGNED_BYTE,!0),i.drawArrays(i.TRIANGLES,0,a)}}}(),Xm.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,a=this.pickShader,i=this.bounds,o=this.numVertices;if(!(o<=0)){var l=n.gl,s=n.dataBox,u=i[2]-i[0],c=i[3]-i[1],f=s[2]-s[0],h=s[3]-s[1];t[0]=2*u/f,t[4]=2*c/h,t[6]=2*(i[0]-s[0])/f-1,t[7]=2*(i[1]-s[1])/h-1;for(var d=0;d<4;++d)e[d]=r>>8*d&255;this.pickOffset=r,a.bind();var p=a.uniforms;p.viewTransform=t,p.pickOffset=e,p.shape=this.shape;var g=a.attributes;return this.positionBuffer.bind(),g.position.pointer(),this.weightBuffer.bind(),g.weight.pointer(l.UNSIGNED_BYTE,!1),this.idBuffer.bind(),g.pickId.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,o),r+this.shape[0]*this.shape[1]}}}(),Xm.pick=function(t,e,r){var n=this.pickOffset,a=this.shape[0]*this.shape[1];if(r=n+a)return null;var i=r-n,o=this.xData,l=this.yData;return{object:this,pointId:i,dataCoord:[o[i%this.shape[0]],l[i/this.shape[0]|0]]}},Xm.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||_i(e[0]),n=t.y||_i(e[1]),a=t.z||new Float32Array(e[0]*e[1]);this.xData=r,this.yData=n;var i=t.colorLevels||[0],o=t.colorValues||[0,0,0,1],l=i.length,s=this.bounds,u=s[0]=r[0],c=s[1]=n[0],f=1/((s[2]=r[r.length-1])-u),h=1/((s[3]=n[n.length-1])-c),d=e[0],p=e[1];this.shape=[d,p];var g=(d-1)*(p-1)*(Wm.length>>>1);this.numVertices=g;for(var v=So.mallocUint8(4*g),m=So.mallocFloat32(2*g),y=So.mallocUint8(2*g),x=So.mallocUint32(g),b=0,_=0;_e.end&&(e.start=e.end=(e.start+e.end)/2),t._input.contours||(t._input.contours={}),Dv(t._input.contours,{start:e.start,end:e.end,size:e.size}),t._input.autocontour=!0}else if("constraint"!==e.type){var n,a=e.start,i=e.end,o=t._input.contours;a>i&&(e.start=o.start=i,i=e.end=o.end=a,a=e.start),e.size>0||(n=a===i?1:Iv(a,i,t.ncontours).dtick,o.size=e.size=n)}}(e),r},Km.plot=Qm,Km.moduleType="trace",Km.name="contourgl",Km.basePlotModule=xv,Km.categories=["gl","gl2d","2dMap"],Km.meta={};var ty=Km,ey={"X,X div":"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 .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"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":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","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 .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 ry in ey){var ny=ry.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");ne.addStyleRule(ny,ey[ry])}var ay={undo:{width:857.1,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",ascent:850,descent:-150},home:{width:928.6,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",ascent:850,descent:-150},"camera-retro":{width:1e3,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",ascent:850,descent:-150},zoombox:{width:1e3,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",ascent:850,descent:-150},pan:{width:1e3,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",ascent:850,descent:-150},zoom_plus:{width:1e3,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",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,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",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,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",ascent:850,descent:-150},plotlylogo:{width:1542,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",ascent:850,descent:-150},"z-axis":{width:1e3,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",ascent:850,descent:-150},"3d_rotate":{width:1e3,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",ascent:850,descent:-150},camera:{width:1e3,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",ascent:850,descent:-150},movie:{width:1e3,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",ascent:850,descent:-150},question:{width:857.1,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",ascent:850,descent:-150},disk:{width:857.1,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",ascent:850,descent:-150},lasso:{width:1031,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",ascent:850,descent:-150},selectbox:{width:1e3,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",ascent:850,descent:-150},spikeline:{width:1e3,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",ascent:850,descent:-150}},iy={exports:{}};(function(t,e){!function(t,e){"object"==typeof iy.exports?iy.exports=e():t.ES6Promise=e()}(this,function(){"use strict";function r(t){return"function"==typeof t}var n=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},a=0,i=void 0,o=void 0,l=function(t,e){p[a]=t,p[a+1]=e,2===(a+=2)&&(o?o(g):b())};var s="undefined"!=typeof window?window:void 0,u=s||{},c=u.MutationObserver||u.WebKitMutationObserver,f="undefined"==typeof self&&void 0!==t&&"[object process]"==={}.toString.call(t),h="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function d(){var t=setTimeout;return function(){return t(g,1)}}var p=new Array(1e3);function g(){for(var t=0;t=0,p=r.indexOf("end")>=0,g=u.backoff*f+n.standoff,v=c.backoff*h+n.startstandoff;if("line"===s.nodeName){a={x:+e.attr("x1"),y:+e.attr("y1")},i={x:+e.attr("x2"),y:+e.attr("y2")};var m=a.x-i.x,y=a.y-i.y;if(l=(o=Math.atan2(y,m))+Math.PI,g&&v&&g+v>Math.sqrt(m*m+y*y))return void S();if(g){if(g*g>m*m+y*y)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,e.attr({x2:i.x,y2:i.y})}if(v){if(v*v>m*m+y*y)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,e.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var A=s.getTotalLength(),M="";if(A2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}r._w=C,r._h=S;for(var I=!1,P=["x","y"],F=0;F1)&&(q===H?((K=G.r2fraction(r["a"+V]))<0||K>1)&&(I=!0):I=!0,I))continue;z=G._offset+G.r2p(r[V]),j=.5}else"x"===V?(B=r[V],z=c.l+c.w*B):(B=1-r[V],z=c.t+c.h*B),j=r.showarrow?.5:B;if(r.showarrow){$.head=z;var tt=r["a"+V];U=W*D(.5,r.xanchor)-Y*D(.5,r.yanchor),q===H?($.tail=G._offset+G.r2p(tt),N=U):($.tail=z+tt,N=U+tt),$.text=$.tail+U;var et=u["x"===V?"width":"height"];if("paper"===H&&($.head=ne.constrain($.head,1,et-1)),"pixel"===q){var rt=-Math.max($.tail-3,$.text),nt=Math.min($.tail+3,$.text)-et;rt>0?($.tail+=rt,$.text+=rt):nt>0&&($.tail-=nt,$.text-=nt)}$.tail+=Q,$.head+=Q}else N=U=Z*D(j,J),$.text=z+U;$.text+=Q,U+=Q,N+=Q,r["_"+V+"padplus"]=Z/2+N,r["_"+V+"padminus"]=Z/2-N,r["_"+V+"size"]=Z,r["_"+V+"shift"]=U}if(I)x.remove();else{var at=0,it=0;if("left"!==r.align&&(at=(C-_)*("center"===r.align?.5:1)),"top"!==r.valign&&(it=(S-k)*("middle"===r.valign?.5:1)),l)n.select("svg").attr({x:w+at-1,y:w+it}).call(Zr.setClipUrl,M?h:null);else{var ot=w+it-y.top,lt=w+at-y.left;E.call(Ar.positionText,lt,ot).call(Zr.setClipUrl,M?h:null)}T.select("rect").call(Zr.setRect,w,w,C,S),A.call(Zr.setRect,b/2,b/2,L-b,O-b),x.call(Zr.setTranslate,Math.round(d.x.text-L/2),Math.round(d.y.text-O/2)),v.attr({transform:"rotate("+p+","+d.x.text+","+d.y.text+")"});var st,ut,ct=function(t,n){g.selectAll(".annotation-arrow-g").remove();var l=d.x.head,u=d.y.head,h=d.x.tail+t,m=d.y.tail+n,y=d.x.text+t,b=d.y.text+n,_=ne.rotationXYMatrix(p,y,b),w=ne.apply2DTransform(_),M=ne.apply2DTransform2(_),T=+A.attr("width"),k=+A.attr("height"),E=y-.5*T,C=E+T,S=b-.5*k,L=S+k,O=[[E,S,E,L],[E,L,C,L],[C,L,C,S],[C,S,E,S]].map(M);if(!O.reduce(function(t,e){return t^!!ne.segmentsIntersect(l,u,l+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){O.forEach(function(t){var e=ne.segmentsIntersect(h,m,l,u,t[0],t[1],t[2],t[3]);e&&(h=e.x,m=e.y)});var D=r.arrowwidth,I=r.arrowcolor,P=r.arrowside,F=g.append("g").style({opacity:Ie.opacity(I)}).classed("annotation-arrow-g",!0),z=F.append("path").attr("d","M"+h+","+m+"L"+l+","+u).style("stroke-width",D+"px").call(Ie.stroke,Ie.rgb(I));if(sy(z,P,r),f.annotationPosition&&z.node().parentNode&&!a){var N=l,B=u;if(r.standoff){var j=Math.sqrt(Math.pow(l-h,2)+Math.pow(u-m,2));N+=r.standoff*(h-l)/j,B+=r.standoff*(m-u)/j}var U,V,H,q=F.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(h-N)+","+(m-B),transform:"translate("+N+","+B+")"}).style("stroke-width",D+6+"px").call(Ie.stroke,"rgba(0,0,0,0)").call(Ie.fill,"rgba(0,0,0,0)");Kp.init({element:q.node(),gd:e,prepFn:function(){var t=Zr.getTranslate(x);V=t.x,H=t.y,U={},i&&i.autorange&&(U[i._name+".autorange"]=!0),o&&o.autorange&&(U[o._name+".autorange"]=!0)},moveFn:function(t,e){var n=w(V,H),a=n[0]+t,l=n[1]+e;x.call(Zr.setTranslate,a,l),U[s+".x"]=i?i.p2r(i.r2p(r.x)+t):r.x+t/c.w,U[s+".y"]=o?o.p2r(o.r2p(r.y)+e):r.y-e/c.h,r.axref===r.xref&&(U[s+".ax"]=i.p2r(i.r2p(r.ax)+t)),r.ayref===r.yref&&(U[s+".ay"]=o.p2r(o.r2p(r.ay)+e)),F.attr("transform","translate("+t+","+e+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){R.call("relayout",e,U);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}};if(r.showarrow&&ct(0,0),m)Kp.init({element:x.node(),gd:e,prepFn:function(){ut=v.attr("transform"),st={}},moveFn:function(t,e){var n="pointer";if(r.showarrow)r.axref===r.xref?st[s+".ax"]=i.p2r(i.r2p(r.ax)+t):st[s+".ax"]=r.ax+t,r.ayref===r.yref?st[s+".ay"]=o.p2r(o.r2p(r.ay)+e):st[s+".ay"]=r.ay+e,ct(t,e);else{if(a)return;if(i)st[s+".x"]=i.p2r(i.r2p(r.x)+t);else{var l=r._xsize/c.w,u=r.x+(r._xshift-r.xshift)/c.w-l/2;st[s+".x"]=Kp.align(u+t/c.w,l,0,1,r.xanchor)}if(o)st[s+".y"]=o.p2r(o.r2p(r.y)+e);else{var f=r._ysize/c.h,h=r.y-(r._yshift+r.yshift)/c.h-f/2;st[s+".y"]=Kp.align(h-e/c.h,f,0,1,r.yanchor)}i&&o||(n=Kp.getCursor(i?.5:st[s+".x"],o?.5:st[s+".y"],r.xanchor,r.yanchor))}v.attr({transform:"translate("+t+","+e+")"+ut}),sg(x,n)},doneFn:function(){sg(x),R.call("relayout",e,st);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}}var hy=uy.draw;function dy(t){var e=t._fullLayout;ne.filterVisible(e.annotations).forEach(function(e){var r,n,a,i,o=ma.getFromId(t,e.xref),l=ma.getFromId(t,e.yref),s=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=s+e.xshift,n=s-e.xshift,a=u+e.xshift,i=u-e.xshift,e.axref===e.xref?(ma.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),ma.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,a),ppadminus:Math.max(e._xpadminus,i)})):(a=e.ax?a+e.ax:a,i=e.ax?i-e.ax:i,ma.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,a),ppadminus:Math.max(e._xpadminus,n,i)}))),l&&l.autorange&&(r=s-e.yshift,n=s+e.yshift,a=u-e.yshift,i=u+e.yshift,e.ayref===e.yref?(ma.expand(l,[l.r2c(e.y)],{ppadplus:r,ppadminus:n}),ma.expand(l,[l.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,a),ppadminus:Math.max(e._ypadminus,i)})):(a=e.ay?a+e.ay:a,i=e.ay?i-e.ay:i,ma.expand(l,[l.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,a),ppadminus:Math.max(e._ypadminus,n,i)})))})}var py={hasClickToShow:function(t,e){var r=gy(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=gy(t,e),a=n.on,i=n.off.concat(n.explicitOff),o={};if(!a.length&&!i.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+a+'"]').remove():(i._pdata=ky(t.glplot.cameraParams,[e.xaxis.r2l(i.x)*r[0],e.yaxis.r2l(i.y)*r[1],e.zaxis.r2l(i.z)*r[2]]),Ey(t.graphDiv,i,a,t.id,i._xa,i._ya))}}};var Ly={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},Oy=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var a=t.arrayminus||[];return function(t,e){var r=+n[e],i=+a[e];return isNaN(r)&&isNaN(i)?[NaN,NaN]:[i||0,r||0]}}var i=Ry(e,t.value),o=Ry(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=i(t);return[e,e]}:function(t){return[o(t),i(t)]}};function Ry(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var Dy=function(t){for(var e=t.calcdata,r=0;r0;r.each(function(r){var s,u=r[0].trace,c=u.error_x||{},f=u.error_y||{};u.ids&&(s=function(t){return t.id});var h=Yr.hasMarkers(u)&&u.marker.maxdisplayed>0;f.visible||c.visible||(r=[]);var d=t.select(this).selectAll("g.errorbar").data(r,s);if(d.exit().remove(),r.length){c.visible||d.selectAll("path.xerror").remove(),f.visible||d.selectAll("path.yerror").remove(),d.style("opacity",1);var p=d.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(a.duration).style("opacity",1),Zr.setClipUrl(d,n.layerClipId),d.each(function(r){var n=t.select(this),s=function(t,r,n){var a={x:r.c2p(t.x),y:n.c2p(t.y)};return void 0!==t.yh&&(a.yh=n.c2p(t.yh),a.ys=n.c2p(t.ys),e(a.ys)||(a.noYS=!0,a.ys=n.c2p(t.ys,!0))),void 0!==t.xh&&(a.xh=r.c2p(t.xh),a.xs=r.c2p(t.xs),e(a.xs)||(a.noXS=!0,a.xs=r.c2p(t.xs,!0))),a}(r,i,o);if(!h||r.vis){var u,d=n.select("path.yerror");if(f.visible&&e(s.x)&&e(s.yh)&&e(s.ys)){var p=f.width;u="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(u+="m-"+p+",0h"+2*p),d.size()?l&&(d=d.transition().duration(a.duration).ease(a.easing)):d=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),d.attr("d",u)}else d.remove();var g=n.select("path.xerror");if(c.visible&&e(s.y)&&e(s.xh)&&e(s.xs)){var v=(c.copy_ystyle?f:c).width;u="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(u+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(a.duration).ease(a.easing)):g=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",u)}else g.remove()}})}})},style:function(e){e.each(function(e){var r=e[0].trace,n=r.error_y||{},a=r.error_x||{},i=t.select(this);i.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(Ie.stroke,n.color),a.copy_ystyle&&(a=n),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(Ie.stroke,a.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var By={},jy=m.extendFlat;By.attributes=function(t,e){t=t||{},e=e||{};var r={valType:"info_array",editType:t.editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},n=(t.name&&t.name,t.trace,e.description&&e.description,{x:jy({},r,{}),y:jy({},r,{}),editType:t.editType});return t.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:t.editType},n.column={valType:"integer",min:0,dflt:0,editType:t.editType}),n},By.defaults=function(t,e,r,n){var a=n&&n.x||[0,1],i=n&&n.y||[0,1],o=e.grid;if(o){var l=r("domain.column");void 0!==l&&(l1){i||o||l||"independent"===h("pattern")&&(i=!0),s._hasSubplotGrid=i;var f="top to bottom"===h("roworder");s._domains={x:Gy("x",h,i?.2:.1,c),y:Gy("y",h,i?.3:.1,u,f)}}}function h(t,e){return ne.coerce(r,s,qy,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,a,i,o,l,s,u,c=t.grid,f=e._subplots,h=r._hasSubplotGrid,d=r.rows,p=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(h){var m=c.subplots||[];s=r.subplots=new Array(d);var y=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},tx={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},ex=!0,rx=function(t,e,r){if(!e._dragged&&!e._editing){var n,a,i,o,l,s=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,f=u.trace,h=f.legendgroup,d={},p=[],g=[],v=[];if(1===r&&ex&&e.data&&e._context.showTips?(ne.notifier(ne._(e,"Double-click on legend to isolate one trace"),"long"),ex=!1):ex=!1,R.traceIs(f,"pie")){var m=u.label,y=s.indexOf(m);1===r?-1===y?s.push(m):s.splice(y,1):2===r&&(s=[],e.calcdata[0].forEach(function(t){m!==t.label&&s.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===s.length&&-1===y&&(s=[])),R.call("relayout",e,"hiddenlabels",s)}else{var x,b=h&&h.length,_=[];if(b)for(n=0;nr[1])return r[1]}return a}function f(t){return t[0]}if(l||s||u){var h={},d={};l&&(h.mc=c("marker.color",f),h.mo=c("marker.opacity",ne.mean,[.2,1]),h.ms=c("marker.size",ne.mean,[2,16]),h.mlc=c("marker.line.color",f),h.mlw=c("marker.line.width",ne.mean,[0,5]),d.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(d.line={width:c("line.width",f,[0,10])}),s&&(h.tx="Aa",h.tp=c("textposition",f),h.ts=10,h.tc=c("textfont.color",f),h.tf=c("textfont.family",f)),n=[ne.minExtend(i,h)],a=ne.minExtend(o,d)}var p=t.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?n:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Zr.pointStyle,a,r),l&&(n[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?n:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Zr.textPointStyle,a,r)})},lx=_r.LINE_SPACING,sx=_r.FROM_TL,ux=_r.FROM_BR,cx=h.DBLCLICKDELAY;function fx(t,e){var r=t.data()[0][0],n=e._fullLayout,a=r.trace,i=R.traceIs(a,"pie"),o=a.index,l=i?r.label:a.name,s=t.selectAll("text.legendtext").data([0]);function u(r){Ar.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,a,i=t.select("g[class*=math-group]"),o=i.node(),l=e._fullLayout.legend.font.size*lx;if(o){var s=Zr.bBox(o);n=s.height,a=s.width,Zr.setTranslate(i,0,n/4)}else{var u=t.select(".legendtext"),c=Ar.lineCount(u),f=u.node();n=l*c,a=f?Zr.bBox(f).width:0;var h=l*(.3+(1-c)/2);Ar.positionText(u,40,h)}n=Math.max(n,16)+3,r.height=n,r.width=a}(t,e)})}s.enter().append("text").classed("legendtext",!0),s.attr("text-anchor","start").classed("user-select-none",!0).call(Zr.font,n.legend.font).text(l),e._context.edits.legendText&&!i?s.call(Ar.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n,a=t;this.text()||(t=" ");var i=r.trace._fullInput||{},l={};if(-1!==["ohlc","candlestick"].indexOf(i.type))l[(n=r.trace.transforms)[n.length-1].direction+".name"]=t;else if(R.hasTransform(i,"groupby")){var s=R.getTransformIndices(i,"groupby"),c=s[s.length-1],f=ne.keyedContainer(i,"transforms["+c+"].styles","target","value.name");""===a?f.remove(r.trace._group):f.set(r.trace._group,t),l=f.constructUpdate()}else l.name=t;return R.call("restyle",e,l,o)}):u(s)}function hx(t,e){var r,n=1,a=t.selectAll("rect").data([0]);a.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(Ie.fill,"rgba(0,0,0,0)"),a.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimecx&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){rx(t,e,n)},cx):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,rx(t,e,n))}})}function dx(e,r,n){var a=e._fullLayout,i=a.legend,o=i.borderwidth,l=$y.isGrouped(i),s=0;if(i._width=0,i._height=0,$y.isVertical(i))l&&r.each(function(t,e){Zr.setTranslate(this,0,e*i.tracegroupgap)}),n.each(function(t){var e=t[0],r=e.height,n=e.width;Zr.setTranslate(this,o,5+o+i._height+r/2),i._height+=r,i._width=Math.max(i._width,n)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var u=[i._width],c=r.data(),f=0,h=c.length;fo+b-_,n.each(function(t){var e=t[0],r=g?40+t[0].width:y;o+x+_+r>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=m,i._height=i._height+m,m=0),Zr.setTranslate(this,o+x,5+o+e.height/2+v),i._width+=_+r,i._height=Math.max(i._height,e.height),x+=_+r,m=Math.max(e.height,m)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),n.each(function(r){var n=r[0],a=t.select(this).select(".legendtoggle");Zr.setRect(a,0,-n.height/2,(e._context.edits.legendText?0:i._width)+s,n.height)})}function px(t){var e=t._fullLayout.legend,r="left";Ky.isRightAnchor(e)?r="right":Ky.isCenterAnchor(e)&&(r="center");var n="top";Ky.isBottomAnchor(e)?n="bottom":Ky.isMiddleAnchor(e)&&(n="middle"),Xn.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*sx[r],r:e._width*ux[r],b:e._height*ux[n],t:e._height*sx[n]})}var gx={moduleType:"component",name:"legend",layoutAttributes:Qy,supplyLayoutDefaults:function(t,e,r){for(var n,a,i,o,l=t.legend||{},s={},u=0,c="normal",f=0;f1)){if(e.legend=s,d("bgcolor",e.paper_bgcolor),d("bordercolor"),d("borderwidth"),ne.coerceFont(d,"font",e.font),d("orientation"),"h"===s.orientation){var p=t.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(n=0,i="left",a=1.1,o="bottom"):(n=0,i="left",a=-.1,o="top")}d("traceorder",c),$y.isGrouped(e.legend)&&d("tracegroupgap"),d("x",n),d("xanchor",i),d("y",a),d("yanchor",o),ne.noneOrAll(l,s,["x","y"])}},draw:function(e){var r=e._fullLayout,n="legend"+r._uid;if(r._infolayer&&e.calcdata){e._legendMouseDownTime||(e._legendMouseDownTime=0);var a=r.legend,i=r.showlegend&&function(t,e){var r,n,a={},i=[],o=!1,l={},s=0;function u(t,r){if(""!==t&&$y.isGrouped(e))-1===i.indexOf(t)?(i.push(t),o=!0,a[t]=[[r]]):a[t].push([r]);else{var n="~~i"+s;i.push(n),a[n]=[[r]],s++}}for(r=0;rg?function(t){var e=t._fullLayout.legend,r="left";Ky.isRightAnchor(e)?r="right":Ky.isCenterAnchor(e)&&(r="center"),Xn.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*sx[r],r:e._width*ux[r],b:0,t:0})}(e):px(e);var v=r._size,m=v.l+v.w*a.x,y=v.t+v.h*(1-a.y);Ky.isRightAnchor(a)?m-=a._width:Ky.isCenterAnchor(a)&&(m-=a._width/2),Ky.isBottomAnchor(a)?y-=a._height:Ky.isMiddleAnchor(a)&&(y-=a._height/2);var x=a._width,b=v.w;x>b?(m=v.l,x=b):(m+x>p&&(m=p-x),m<0&&(m=0),x=Math.min(p-m,a._width));var _,w,A,M,T=a._height,k=v.h;if(T>k?(y=v.t,T=k):(y+T>g&&(y=g-T),y<0&&(y=0),T=Math.min(g-y,a._height)),Zr.setTranslate(l,m,y),f.on(".drag",null),l.on("wheel",null),a._height<=T||e._context.staticPlot)u.attr({width:x-a.borderwidth,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Zr.setTranslate(c,0,0),s.select("rect").attr({width:x-2*a.borderwidth,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Zr.setClipUrl(c,n),Zr.setRect(f,0,0,0,0),delete a._scrollY;else{var E,C,S=Math.max(tx.scrollBarMinHeight,T*T/a._height),L=T-S-2*tx.scrollBarMargin,O=a._height-T,D=L/O,I=Math.min(a._scrollY||0,O);u.attr({width:x-2*a.borderwidth+tx.scrollBarWidth+tx.scrollBarMargin,height:T-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),s.select("rect").attr({width:x-2*a.borderwidth+tx.scrollBarWidth+tx.scrollBarMargin,height:T-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+I}),Zr.setClipUrl(c,n),F(I,S,D),l.on("wheel",function(){F(I=ne.constrain(a._scrollY+t.event.deltaY/L*O,0,O),S,D),0!==I&&I!==O&&t.event.preventDefault()});var P=t.behavior.drag().on("dragstart",function(){E=t.event.sourceEvent.clientY,C=I}).on("drag",function(){var e=t.event.sourceEvent;2===e.buttons||e.ctrlKey||F(I=ne.constrain((e.clientY-E)/D+C,0,O),S,D)});f.call(P)}e._context.edits.legendPosition&&(l.classed("cursor-move",!0),Kp.init({element:l.node(),gd:e,prepFn:function(){var t=Zr.getTranslate(l);A=t.x,M=t.y},moveFn:function(t,e){var r=A+t,n=M+e;Zr.setTranslate(l,r,n),_=Kp.align(r,0,v.l,v.l+v.w,a.xanchor),w=Kp.align(n,0,v.t+v.h,v.t,a.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&R.call("relayout",e,{"legend.x":_,"legend.y":w})},clickFn:function(t,n){var a=r._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});a.size()>0&&(1===t?l._clickTimeout=setTimeout(function(){rx(a,e,t)},cx):2===t&&(l._clickTimeout&&clearTimeout(l._clickTimeout),rx(a,e,t)))}}))}function F(t,r,n){a._scrollY=e._fullLayout.legend._scrollY=t,Zr.setTranslate(c,0,-t),Zr.setRect(f,x,tx.scrollBarMargin+t*n,tx.scrollBarWidth,r),s.select("rect").attr({y:a.borderwidth+t})}},style:ox},vx={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},mx=m.extendFlat,yx={visible:{valType:"boolean",editType:"plot"},buttons:vx=mx(vx,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:k({editType:"plot"}),bgcolor:{valType:"color",dflt:S.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:S.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},xx={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var bx=function(e,r){var n=e._name,a={};if("all"===r.step)a[n+".autorange"]=!0;else{var i=function(e,r){var n,a=e.range,i=new Date(e.r2l(a[1])),o=r.step,l=r.count;switch(r.stepmode){case"backward":n=e.l2r(+t.time[o].utc.offset(i,-l));break;case"todate":var s=t.time[o].utc.offset(i,-l);n=e.l2r(+t.time[o].utc.ceil(s))}var u=a[1];return[n,u]}(e,r);a[n+".range[0]"]=i[0],a[n+".range[1]"]=i[1]}return a};var _x=_r.LINE_SPACING,wx=_r.FROM_TL,Ax=_r.FROM_BR;function Mx(t){return t._id}function Tx(t,e,r){var n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("selector-rect",!0),n.attr("shape-rendering","crispEdges"),n.attr({rx:xx.rx,ry:xx.ry}),n.call(Ie.stroke,e.bordercolor).call(Ie.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function kx(t,e,r,n){var a,i=t.selectAll("text").data([0]);i.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),i.attr("text-anchor","middle"),i.call(Zr.font,e.font).text((a=r,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(t){Ar.convertToTspans(t,n)})}var Ex={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:yx}}},layoutAttributes:yx,handleDefaults:function(t,e,r,n,a){var i=t.rangeselector||{},o=e.rangeselector={};function l(t,e){return ne.coerce(i,o,yx,t,e)}if(l("visible",function(t,e,r){var n,a,i=t.buttons||[],o=e.buttons=[];function l(t,e){return ne.coerce(n,a,vx,t,e)}for(var s=0;s0)){var s=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),a=0,i=0;if&&(f=u)));return f>=c?[c,f]:void 0}}var Wx=function(t,e,r,n,a){function i(r,n){return ne.coerce(t,e,Hx,r,n)}if(n=n||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return e;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",t.path?"path":"rect"),l=["x","y"],s=0;s<2;s++){var u=l[s],c={_fullLayout:r},f=ma.coerceRef(t,e,c,u,"","paper");if("path"!==o){var h,d,p;"paper"!==f?(h=ma.getFromId(c,f),p=Gx.rangeToShapePosition(h),d=Gx.shapePositionToRange(h)):d=p=ne.identity;var g=u+"0",v=u+"1",m=t[g],y=t[v];t[g]=d(t[g],!0),t[v]=d(t[v],!0),ma.coercePosition(e,c,i,f,g,.25),ma.coercePosition(e,c,i,f,v,.75),e[g]=p(e[g]),e[v]=p(e[v]),t[g]=m,t[v]=y}}return"path"===o?i("path"):ne.noneOrAll(t,e,["x0","x1","y0","y1"]),e},Yx={draw:function(t){var e=t._fullLayout;e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._shapeSubplotLayers.selectAll("path").remove();for(var r=0;rP&&n>F&&!t.shiftKey?Kp.getCursor(a/r,1-i/n):"move";sg(e,o),I=o.split("-")[0]}function j(n,d){if("path"===r.type){var p=function(t){return O(S(t)+n)};E&&"date"===E.type&&(p=Gx.encodeDate(p));var g=function(t){return D(L(t)+d)};C&&"date"===C.type&&(g=Gx.encodeDate(g)),r.path=Qx(T,p,g),a[k]=r.path}else a[u]=r.x0=O(i+n),a[c]=r.y0=D(o+d),a[f]=r.x1=O(l+n),a[h]=r.y1=D(s+d);e.attr("d",Jx(t,r))}function U(n,i){if("path"===r.type){var o=function(t){return O(S(t)+n)};E&&"date"===E.type&&(o=Gx.encodeDate(o));var l=function(t){return D(L(t)+i)};C&&"date"===C.type&&(l=Gx.encodeDate(l)),r.path=Qx(T,o,l),a[k]=r.path}else{var s=~I.indexOf("n")?d+i:d,u=~I.indexOf("s")?p+i:p,c=~I.indexOf("w")?g+n:g,f=~I.indexOf("e")?v+n:v;u-s>F&&(a[m]=r[_]=D(s),a[y]=r[w]=D(u)),f-c>P&&(a[x]=r[A]=O(c),a[b]=r[M]=O(f))}e.attr("d",Jx(t,r))}Kp.init(z),e.node().onmousemove=B}(t,o,n,e)}}function Jx(t,e){var r,n,a,i,o=e.type,l=ma.getFromId(t,e.xref),s=ma.getFromId(t,e.yref),u=t._fullLayout._size;if(l?(r=Gx.shapePositionToRange(l),n=function(t){return l._offset+l.r2p(r(t,!0))}):n=function(t){return u.l+u.w*t},s?(a=Gx.shapePositionToRange(s),i=function(t){return s._offset+s.r2p(a(t,!0))}):i=function(t){return u.t+u.h*(1-t)},"path"===o)return l&&"date"===l.type&&(n=Gx.decodeDate(n)),s&&"date"===s.type&&(i=Gx.decodeDate(i)),function(t,e,r){return t.replace(qx.segmentRE,function(t){var n=0,a=t.charAt(0),i=qx.paramIsX[a],o=qx.paramIsY[a],l=qx.numParams[a],s=t.substr(1).replace(qx.paramRE,function(t){return i[n]?t=e(t):o[n]&&(t=r(t)),++n>l&&(t="X"),t});return n>l&&(s=s.replace(/[\s,]*X.*/,""),ne.log("Ignoring extra params in segment "+t)),a+s})}(e.path,n,i);var c=n(e.x0),f=n(e.x1),h=i(e.y0),d=i(e.y1);if("line"===o)return"M"+c+","+h+"L"+f+","+d;if("rect"===o)return"M"+c+","+h+"H"+f+"V"+d+"H"+c+"Z";var p=(c+f)/2,g=(h+d)/2,v=Math.abs(p-c),m=Math.abs(g-h),y="A"+v+","+m,x=p+v+","+g;return"M"+x+y+" 0 1,1 "+(p+","+(g-m))+y+" 0 0,1 "+x+"Z"}function Qx(t,e,r){return t.replace(qx.segmentRE,function(t){var n=0,a=t.charAt(0),i=qx.paramIsX[a],o=qx.paramIsY[a],l=qx.numParams[a];return a+t.substr(1).replace(qx.paramRE,function(t){return n>=l?t:(i[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var $x={moduleType:"component",name:"shapes",layoutAttributes:Hx,supplyLayoutDefaults:function(t,e){xy(t,e,{name:"shapes",handleItemDefaults:Wx})},includeBasePlot:by("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=ne.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),ne.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),ne.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),ne.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var ob=_r.LINE_SPACING,lb=_r.FROM_TL,sb=_r.FROM_BR;function ub(t){return t._index}function cb(e,r){var n=Zr.tester.selectAll("g."+Kx.labelGroupClass).data(r.steps);n.enter().append("g").classed(Kx.labelGroupClass,!0);var a=0,i=0;n.each(function(e){var n=db(t.select(this),{step:e},r).node();if(n){var o=Zr.bBox(n);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(Kx.railWidth,Kx.gripHeight);var l=e._fullLayout._size;o.lx=l.l+l.w*r.x,o.ly=l.t+l.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(l.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var s=(o.inputAreaLength-2*Kx.stepInset)/(r.steps.length-1),u=a+Kx.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var c=Zr.tester.append("g");n.each(function(t){var e=fb(c,r,t.label),n=e.node()&&Zr.bBox(e.node())||{width:0,height:0},a=Ar.lineCount(e);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+Kx.tickOffset+r.ticklen+Kx.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var f="left";Ky.isRightAnchor(r)&&(o.lx-=o.outerLength,f="right"),Ky.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,f="center");var h="top";Ky.isBottomAnchor(r)&&(o.ly-=o.height,h="bottom"),Ky.isMiddleAnchor(r)&&(o.ly-=o.height/2,h="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Xn.autoMargin(e,Kx.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*lb[f],r:o.outerLength*sb[f],b:o.height*sb[h],t:o.height*lb[h]})}function fb(t,e,r){if(e.currentvalue.visible){var n,a,i=t.selectAll("text").data([0]),o=e._dims;switch(e.currentvalue.xanchor){case"right":n=o.inputAreaLength-Kx.currentValueInset-o.currentValueMaxWidth,a="left";break;case"center":n=.5*o.inputAreaLength,a="middle";break;default:n=Kx.currentValueInset,a="left"}i.enter().append("text").classed(Kx.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1});var l=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)l+=r;else l+=e.steps[e.active].label;e.currentvalue.suffix&&(l+=e.currentvalue.suffix),i.call(Zr.font,e.currentvalue.font).text(l).call(Ar.convertToTspans,e._gd);var s=Ar.lineCount(i),u=(o.currentValueMaxLines+1-s)*e.currentvalue.font.size*ob;return Ar.positionText(i,n,u),i}}function hb(t,e,r){var n=t.selectAll("rect."+Kx.gripRectClass).data([0]);n.enter().append("rect").classed(Kx.gripRectClass,!0).call(mb,e,t,r).style("pointer-events","all"),n.attr({width:Kx.gripWidth,height:Kx.gripHeight,rx:Kx.gripRadius,ry:Kx.gripRadius}).call(Ie.stroke,r.bordercolor).call(Ie.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function db(t,e,r){var n=t.selectAll("text").data([0]);return n.enter().append("text").classed(Kx.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(Zr.font,r.font).text(e.step.label).call(Ar.convertToTspans,r._gd),n}function pb(e,r){var n=e.selectAll("g."+Kx.labelsClass).data([0]),a=r._dims;n.enter().append("g").classed(Kx.labelsClass,!0);var i=n.selectAll("g."+Kx.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(Kx.labelGroupClass,!0),i.exit().remove(),i.each(function(e){var n=t.select(this);n.call(db,e,r),Zr.setTranslate(n,bb(r,e.fraction),Kx.tickOffset+r.ticklen+r.font.size*ob+Kx.labelOffset+a.currentValueTotalHeight)})}function gb(t,e,r,n,a){var i=Math.round(n*(r.steps.length-1));i!==r.active&&vb(t,e,r,i,!0,a)}function vb(t,e,r,n,a,i){var o=r.active;r._input.active=r.active=n;var l=r.steps[r.active];e.call(xb,r,r.active/(r.steps.length-1),i),e.call(fb,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:a,previousActive:o}),l&&l.method&&a&&(e._nextMethod?(e._nextMethod.step=l,e._nextMethod.doCallback=a,e._nextMethod.doTransition=i):(e._nextMethod={step:l,doCallback:a,doTransition:i},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&Xn.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function mb(e,r,n){var a=n.node(),i=t.select(r);function o(){return n.data()[0]}e.on("mousedown",function(){var e=o();r.emit("plotly_sliderstart",{slider:e});var l=n.select("."+Kx.gripRectClass);t.event.stopPropagation(),t.event.preventDefault(),l.call(Ie.fill,e.activebgcolor);var s=_b(e,t.mouse(a)[0]);gb(r,n,e,s,!0),e._dragging=!0,i.on("mousemove",function(){var e=o(),i=_b(e,t.mouse(a)[0]);gb(r,n,e,i,!1)}),i.on("mouseup",function(){var t=o();t._dragging=!1,l.call(Ie.fill,t.bgcolor),i.on("mouseup",null),i.on("mousemove",null),r.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function yb(e,r){var n=e.selectAll("rect."+Kx.tickRectClass).data(r.steps),a=r._dims;n.enter().append("rect").classed(Kx.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(e,n){var i=n%a.labelStride==0,o=t.select(this);o.attr({height:i?r.ticklen:r.minorticklen}).call(Ie.fill,r.tickcolor),Zr.setTranslate(o,bb(r,n/(r.steps.length-1))-.5*r.tickwidth,(i?Kx.tickOffset:Kx.minorTickOffset)+a.currentValueTotalHeight)})}function xb(t,e,r,n){var a=t.select("rect."+Kx.gripRectClass),i=bb(e,r);if(!e._invokingCommand){var o=a;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(i-.5*Kx.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function bb(t,e){var r=t._dims;return r.inputAreaStart+Kx.stepInset+(r.inputAreaLength-2*Kx.stepInset)*Math.min(1,Math.max(0,e))}function _b(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-Kx.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*Kx.stepInset-2*r.inputAreaStart)))}function wb(t,e,r){var n=t.selectAll("rect."+Kx.railTouchRectClass).data([0]),a=r._dims;n.enter().append("rect").classed(Kx.railTouchRectClass,!0).call(mb,e,t,r).style("pointer-events","all"),n.attr({width:a.inputAreaLength,height:Math.max(a.inputAreaWidth,Kx.tickOffset+r.ticklen+a.labelHeight)}).call(Ie.fill,r.bgcolor).attr("opacity",0),Zr.setTranslate(n,0,a.currentValueTotalHeight)}function Ab(t,e){var r=t.selectAll("rect."+Kx.railRectClass).data([0]),n=e._dims;r.enter().append("rect").classed(Kx.railRectClass,!0);var a=n.inputAreaLength-2*Kx.railInset;r.attr({width:a,height:Kx.railWidth,rx:Kx.railRadius,ry:Kx.railRadius,"shape-rendering":"crispEdges"}).call(Ie.stroke,e.bordercolor).call(Ie.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),Zr.setTranslate(r,Kx.railInset,.5*(n.inputAreaWidth-Kx.railWidth)+n.currentValueTotalHeight)}var Mb={moduleType:"component",name:Kx.name,layoutAttributes:rb,supplyLayoutDefaults:function(t,e){xy(t,e,{name:nb,handleItemDefaults:ib})},draw:function(e){var r=e._fullLayout,n=function(t,e){for(var r=t[Kx.name],n=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(Kx.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(fb,r).call(Ab,r).call(pb,r).call(yb,r).call(wb,t,r).call(hb,t,r);var n=r._dims;Zr.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(xb,r,r.active/(r.steps.length-1),!1),e.call(fb,r)}(e,t.select(this),r)}})}}},Tb=m.extendFlat,kb=(0,ye.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Tb({},tb,{}),font:k({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:S.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Eb={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Cb=Eb.name,Sb=kb.buttons;function Lb(t,e,r){function n(r,n){return ne.coerce(t,e,kb,r,n)}n("visible",function(t,e){var r,n,a=t.buttons||[],i=e.buttons=[];function o(t,e){return ne.coerce(r,n,Sb,t,e)}for(var l=0;l0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),ne.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),ne.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var Ob=Rb;function Rb(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Rb.barWidth=2,Rb.barLength=20,Rb.barRadius=2,Rb.barPad=1,Rb.barColor="#808BA4",Rb.prototype.enable=function(e,r,n){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=e;var l,s,u,c,f=this.position.l,h=this.position.w,d=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,m="left"===g,y="up"===g,x=h,b=p;v||m||"right"===g||y||(this.position.direction="down",v=!0),v||y?(s=(l=f)+x,v?(u=d,b=(c=Math.min(u+b,o))-u):b=(c=d+b)-(u=Math.max(c-b,0))):(c=(u=d)+b,m?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:u,w:x,h:b};var _=h>x,w=Rb.barLength+2*Rb.barPad,A=Rb.barWidth+2*Rb.barPad,M=f,T=d+p;T+A>o&&(T=o-A);var k=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);k.exit().on(".drag",null).remove(),k.enter().append("rect").classed("scrollbar-horizontal",!0).call(Ie.fill,Rb.barColor),_?(this.hbar=k.attr({rx:Rb.barRadius,ry:Rb.barRadius,x:M,y:T,width:w,height:A}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var E=p>b,C=Rb.barWidth+2*Rb.barPad,S=Rb.barLength+2*Rb.barPad,L=f+h,O=d;L+C>i&&(L=i-C);var R=this.container.selectAll("rect.scrollbar-vertical").data(E?[0]:[]);R.exit().on(".drag",null).remove(),R.enter().append("rect").classed("scrollbar-vertical",!0).call(Ie.fill,Rb.barColor),E?(this.vbar=R.attr({rx:Rb.barRadius,ry:Rb.barRadius,x:L,y:O,width:C,height:S}),this._vbarYMin=O+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,I=l-.5,P=E?s+C+.5:s+.5,F=u-.5,z=_?c+A+.5:c+.5,N=a._topdefs.selectAll("#"+D).data(_||E?[0]:[]);if(N.exit().remove(),N.enter().append("clipPath").attr("id",D).append("rect"),_||E?(this._clipRect=N.select("rect").attr({x:Math.floor(I),y:Math.floor(F),width:Math.ceil(P)-Math.floor(I),height:Math.ceil(z)-Math.floor(F)}),this.container.call(Zr.setClipUrl,D),this.bg.attr({x:f,y:d,width:h,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Zr.setClipUrl,null),delete this._clipRect),_||E){var B=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(B);var j=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault(),t.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),E&&this.vbar.on(".drag",null).call(j)}this.setTranslate(r,n)},Rb.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Zr.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Rb.prototype._onBoxDrag=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e-=t.event.dx),this.vbar&&(r-=t.event.dy),this.setTranslate(e,r)},Rb.prototype._onBoxWheel=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e+=t.event.deltaY),this.vbar&&(r+=t.event.deltaY),this.setTranslate(e,r)},Rb.prototype._onBarDrag=function(){var e=this.translateX,r=this.translateY;if(this.hbar){var n=e+this._hbarXMin,a=n+this._hbarTranslateMax;e=(ne.constrain(t.event.x,n,a)-n)/(a-n)*(this.position.w-this._box.w)}if(this.vbar){var i=r+this._vbarYMin,o=i+this._vbarTranslateMax;r=(ne.constrain(t.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(e,r)},Rb.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=ne.constrain(t||0,0,r),e=ne.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(Zr.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var a=t/r;this.hbar.call(Zr.setTranslate,t+a*this._hbarTranslateMax,e)}if(this.vbar){var i=e/n;this.vbar.call(Zr.setTranslate,t,e+i*this._vbarTranslateMax)}};var Db=_r.LINE_SPACING;function Ib(t){return t._index}function Pb(t,e){return+t.attr(Eb.menuIndexAttrName)===e._index}function Fb(t,e,r,n,a,i,o,l){e._input.active=e.active=o,"buttons"===e.type?Nb(t,n,null,null,e):"dropdown"===e.type&&(a.attr(Eb.menuIndexAttrName,"-1"),zb(t,n,a,i,e),l||Nb(t,n,a,i,e))}function zb(t,e,r,n,a){var i=e.selectAll("g."+Eb.headerClassName).data([0]),o=a._dims;i.enter().append("g").classed(Eb.headerClassName,!0).style("pointer-events","all");var l=a.active,s=a.buttons[l]||Eb.blankHeaderOpts,u={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};i.call(Bb,a,s,t).call(Xb,a,u,c);var f=e.selectAll("text."+Eb.headerArrowClassName).data([0]);f.enter().append("text").classed(Eb.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(Zr.font,a.font).text(Eb.arrowSymbol[a.direction]),f.attr({x:o.headerWidth-Eb.arrowOffsetX+a.pad.l,y:o.headerHeight/2+Eb.textOffsetY+a.pad.t}),i.on("click",function(){r.call(Wb),r.attr(Eb.menuIndexAttrName,Pb(r,a)?-1:String(a._index)),Nb(t,e,r,n,a)}),i.on("mouseover",function(){i.call(Hb)}),i.on("mouseout",function(){i.call(qb,a)}),Zr.setTranslate(e,o.lx,o.ly)}function Nb(e,r,n,a,i){n||(n=r).attr("pointer-events","all");var o=function(t){return-1==+t.attr(Eb.menuIndexAttrName)}(n)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?Eb.dropdownButtonClassName:Eb.buttonClassName,s=n.selectAll("g."+l).data(o),u=s.enter().append("g").classed(l,!0),c=s.exit();"dropdown"===i.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var f=0,h=0,d=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?h=d.headerHeight+Eb.gapButtonHeader:f=d.headerWidth+Eb.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(h=-Eb.gapButtonHeader+Eb.gapButton-d.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-Eb.gapButtonHeader+Eb.gapButton-d.openWidth);var g={x:d.lx+f+i.pad.l,y:d.ly+h+i.pad.t,yPad:Eb.gapButton,xPad:Eb.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var u=t.select(this);u.call(Bb,i,o,e).call(Xb,i,g),u.on("click",function(){t.event.defaultPrevented||(Fb(e,i,0,r,n,a,l),o.execute&&Xn.executeAPICommand(e,o.method,o.args),e.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),u.on("mouseover",function(){u.call(Hb)}),u.on("mouseout",function(){u.call(qb,i),s.call(Vb,i)})}),s.call(Vb,i),p?(v.w=Math.max(d.openWidth,d.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(d.openHeight,d.headerHeight)),v.direction=i.direction,a&&(s.size()?function(t,e,r,n,a,i){var o,l,s,u=a.direction,c="up"===u||"down"===u,f=a._dims,h=a.active;if(c)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(Eb.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nb.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&ne.log("Clearing previous rejected promises from queue."),t._promises=[]},Kb.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(Xn.subplotsRegistry.cartesian||{}).attrRegex,a=(Xn.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(t);for(e=0;e3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Ie.clean(t),t},Kb.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),a=0;a0)return t.substr(0,e)}Kb.hasParent=function(t,e){for(var r=o_(e);r;){if(r in t)return!0;r=o_(r)}return!1};var l_=["x","y","z"];Kb.clearAxisTypes=function(t,e,r){for(var n=0;n1&&_.warn("Full array edits are incompatible with other edits",a);var f=r[""][""];if(f_(f))e.set(null);else{if(!Array.isArray(f))return _.warn("Unrecognized full array edit value",a,f),!0;e.set(f)}return!s&&(i(u,c),o(t),!0)}var h,d,p,g,v,m,y,x=Object.keys(r).map(Number).sort(u_),b=e.get(),w=b||[],A=X(c,a).get(),T=[],k=-1,E=w.length;for(h=0;hw.length-(y?0:1))_.warn("index out of range",a,p);else if(void 0!==m)v.length>1&&_.warn("Insertion & removal are incompatible with edits to the same index.",a,p),f_(m)?T.push(p):y?("add"===m&&(m={}),w.splice(p,0,m),A&&A.splice(p,0,{})):_.warn("Unrecognized full object edit value",a,p,m),-1===k&&(k=p);else for(d=0;d=0;h--)w.splice(T[h],1),A&&A.splice(T[h],1);if(w.length?b||e.set(w):e.set(null),s)return!1;if(i(u,c),l!==M){var C;if(-1===k)C=x;else{for(E=Math.max(w.length,E),C=[],h=0;h=k);h++)C.push(p);for(h=k;h1?(m=["toggleHover"],y=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],m=["hoverClosestGeo"],y=["resetGeo"]):o?(m=["hoverClosest3d"],y=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(m=["toggleHover"],y=["resetViewMapbox"]):m=u?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(m=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!u||d||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==y[0]&&(y=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||u)&&!d||c?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:h&&(x=["zoom2d"]),function(t){for(var e=!1,r=0;r0})}function u(t,n){var a=t.seg,i=n.seg,o=a.start,s=a.end,u=i.start,c=i.end;r&&r.checkIntersection(a,i);var f=e.linesIntersect(o,s,u,c);if(!1===f){if(!e.pointsCollinear(o,s,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(s,u))return!1;var h=e.pointsSame(o,u),d=e.pointsSame(s,c);if(h&&d)return n;var p=!h&&e.pointBetween(o,u,c),g=!d&&e.pointBetween(s,u,c);if(h)return g?l(n,s):l(t,c),n;p&&(d||(g?l(n,s):l(t,c)),l(n,o))}else 0===f.alongA&&(-1===f.alongB?l(t,u):0===f.alongB?l(t,f.pt):1===f.alongB&&l(t,c)),0===f.alongB&&(-1===f.alongA?l(n,o):0===f.alongA?l(n,f.pt):1===f.alongA&&l(n,s));return!1}for(var c=[];!a.isEmpty();){var f=a.getHead();if(r&&r.vert(f.pt[0]),f.isStart){r&&r.segmentNew(f.seg,f.primary);var h=s(f),d=h.before?h.before.ev:null,p=h.after?h.after.ev:null;function g(){if(d){var t=u(f,d);if(t)return t}return!!p&&u(f,p)}r&&r.tempStatus(f.seg,!!d&&d.seg,!!p&&p.seg);var v,m,y=g();if(y)t?(m=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(y.seg.myFill.above=!y.seg.myFill.above):y.seg.otherFill=f.seg.myFill,r&&r.segmentUpdate(y.seg),f.other.remove(),f.remove();if(a.getHead()!==f){r&&r.rewind(f.seg);continue}t?(m=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:n,f.seg.myFill.above=m?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:n,f.seg.otherFill={above:v,below:v}),r&&r.status(f.seg,!!d&&d.seg,!!p&&p.seg),f.other.status=h.insert(C_.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&u(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}c.push(f.seg)}a.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,a,i,l=t[t.length-1],s=0;s=-t},pointBetween:function(e,r,n){var a=e[1]-r[1],i=n[0]-r[0],o=e[0]-r[0],l=n[1]-r[1],s=o*i+a*l;return!(s-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-a>t&&(i-u)*(a-c)/(o-c)+u-n>t&&(l=!l),i=u,o=c}return l}};return e}();function F_(t,e,r){var n=R_.segments(t),a=R_.segments(e),i=r(R_.combine(n,a));return R_.polygon(i)}R_={buildLog:function(t){return!0===t?I_=k_():!1===t&&(I_=!1),!1!==I_&&I_.list},epsilon:function(t){return P_.epsilon(t)},segments:function(t){var e=S_(!0,P_,I_);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:S_(!1,P_,I_).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:D_.union(t.combined,I_),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:D_.intersect(t.combined,I_),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:D_.difference(t.combined,I_),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:D_.differenceRev(t.combined,I_),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:D_.xor(t.combined,I_),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:L_(t.segments,P_,I_),inverted:t.inverted}},polygonFromGeoJSON:function(t){return E_.toPolygon(R_,t)},polygonToGeoJSON:function(t){return E_.fromPolygon(R_,P_,t)},union:function(t,e){return F_(t,e,R_.selectUnion)},intersect:function(t,e){return F_(t,e,R_.selectIntersect)},difference:function(t,e){return F_(t,e,R_.selectDifference)},differenceRev:function(t,e){return F_(t,e,R_.selectDifferenceRev)},xor:function(t,e){return F_(t,e,R_.selectXor)}},"object"==typeof window&&(window.PolyBool=R_);var z_,N_=R_,B_=Ut.dot,j_=r.BADNUM,U_=z_={};U_.tester=function(t){if(Array.isArray(t[0][0]))return U_.multitester(t);var e,r=t.slice(),n=r[0][0],a=n,i=r[0][1],o=i;for(r.push(r[0]),e=1;ea||s===j_||so||e&&l(t))}:function(t,e){var l=t[0],s=t[1];if(l===j_||la||s===j_||so)return!1;var u,c,f,h,d,p=r.length,g=r[0][0],v=r[0][1],m=0;for(u=1;uMath.max(c,g)||s>Math.max(f,v)))if(su||Math.abs(B_(i,f))>n)return!0;return!1};U_.filter=function(t,e){var r=[t[0]],n=0,a=0;function i(i){t.push(i);var o=r.length,l=n;r.splice(a+1);for(var s=l+1;s1&&i(t.pop());return{addPt:i,raw:t,filtered:r}};var H_=ag.makeEventData,q_=z_.filter,G_=z_.tester,X_=z_.multitester,W_=Ce.MINSELECT;function Y_(t){return t._id}var Z_=function(t,e,r,n,a){var i,o,l,s,u=n.gd,c=u._fullLayout,f=c._zoomlayer,h=n.element.getBoundingClientRect(),d=n.plotinfo,p=d.xaxis._offset,g=d.yaxis._offset,v=e-h.left,m=r-h.top,y=v,x=m,b="M"+v+","+m,_=n.xaxes[0]._length,w=n.yaxes[0]._length,A=n.xaxes.map(Y_),M=n.yaxes.map(Y_),T=n.xaxes.concat(n.yaxes),k=t.altKey;(t.shiftKey||t.altKey)&&d.selection&&d.selection.polygons&&!n.polygons?(n.polygons=d.selection.polygons,n.mergedPolygons=d.selection.mergedPolygons):(!t.shiftKey&&!t.altKey||(t.shiftKey||t.altKey)&&!d.selection)&&(d.selection={},d.selection.polygons=n.polygons=[],d.selection.mergedPolygons=n.mergedPolygons=[]),"lasso"===a&&(i=q_([[v,m]],Ce.BENDPX));var E=f.selectAll("path.select-outline-"+d.id).data([1,2]);E.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+d.id}).attr("transform","translate("+p+", "+g+")").attr("d",b+"Z");var C,S,L,O,R,D,I=f.append("path").attr("class","zoombox-corners").style({fill:Ie.background,stroke:Ie.defaultLine,"stroke-width":1}).attr("transform","translate("+p+", "+g+")").attr("d","M0,0Z"),P=[],F=c._uid+Ce.SELECTID,z=[];for(C=0;C=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function cw(t,e,r,n,a){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",a+"Z")}function fw(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Ie.background,stroke:Ie.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function hw(t){t.selectAll(".select-outline").remove()}function dw(t,e,r,n,a,i){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),pw(t,e,a,i)}function pw(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function gw(e){t.select(e).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function vw(t){nw&&t.data&&t._context.showTips&&(ne.notifier(ne._(t,"Double-click to zoom back out"),"long"),nw=!1)}function mw(t){return"lasso"===t||"select"===t}function yw(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,rw)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function xw(t,e){if(jp){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}var bw=function(e,r,n,a,i,o,s,u){var c,f,h,d,p,g,v,m,y,x,b,_,w,A=e._fullLayout,M=e._fullLayout._zoomlayer,T=s+u==="nsew",k=1===(s+u).length;function E(){f=[r.xaxis],h=[r.yaxis];var t=f[0],n=h[0];g=t._length,v=n._length;var a,i,o=A._axisConstraintGroups,l=[t._id],M=[n._id];c=[r].concat(s&&u?r.overlays:[]);for(var T=1;Trw||o>rw?(z="xy",i/g>o/v?(o=i*v/g,O>a?D.t=O-o:D.b=O+o):(i=o*g/v,L>n?D.l=L-i:D.r=L+i),B.attr("d",yw(D))):l():!y||o rect").call(Zr.setTranslate,a,i).call(Zr.setScale,r,n);var R=x.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");x.plot.call(Zr.setTranslate,L,O).call(Zr.setScale,1/r,1/n),R.selectAll(".point").call(Zr.setPointGroupScale,r,n),R.selectAll(".textpoint").call(Zr.setTextPointsScale,r,n),R.call(Zr.hideOutsideRangePoints,x),x.plot.selectAll(".barlayer .trace").call(Zr.hideOutsideRangePoints,x,".bartext")}}}return s.length*u.length!=1&&xw(C,function(t){if(e._context.scrollZoom||A._enablescrollzoom){if(null===G&&hw(M),e._transitioningWithDuration)return t.preventDefault(),void t.stopPropagation();var r=e.querySelector(".plotly");if(E(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(G);var n=-t.deltaY;if(isFinite(n)||(n=t.wheelDelta/10),isFinite(n)){var a,i=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=W.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(t.clientX-o.left)/o.width,c=(o.bottom-t.clientY)/o.height;if(u||b){for(u||(l=.5),a=0;a=t[1]||a[1]<=t[0])&&i[0]e[0])return!0}return!1}(r,a,d)?(h.push(t),d.push([r,a])):i=[0];var o=e.plotgroup.selectAll(".bg").data(i);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){e.bg=o;var t=e.plotgroup.node();t.insertBefore(this,t.childNodes[0])})});var p=n._bgLayer.selectAll(".bg").data(h);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(e){n._plots[e].bg=t.select(this)}),f.each(function(t){var e=n._plots[t],a=e.xaxis,u=e.yaxis;e.bg&&l&&e.bg.call(Zr.setRect,a._offset-i,u._offset-i,a._length+2*i,u._length+2*i).call(Ie.fill,n.plot_bgcolor).style("stroke-width",0),e.clipId="clip"+n._uid+t+"plot";var c,f,h=n._clips.selectAll("#"+e.clipId).data([0]);for(h.enter().append("clipPath").attr({class:"plotclip",id:e.clipId}).append("rect"),h.selectAll("rect").attr({width:a._length,height:u._length}),Zr.setTranslate(e.plot,a._offset,u._offset),e._hasClipOnAxisFalse?(c=null,f=e.clipId):(c=e.clipId,f=null),Zr.setClipUrl(e.plot,c),r=0;r=0?u.angularAxis.domain:t.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var T=A.slice();w&&b&&(T[1]+=M);var k=u.angularAxis.ticksCount||4;k>8&&(k=k/(k/8)+k%8),u.angularAxis.ticksStep&&(k=(T[1]-T[0])/k);var E=u.angularAxis.ticksStep||(T[1]-T[0])/(k*(u.minorTicks+1));y&&(E=Math.max(Math.round(E),1)),T[2]||(T[2]=E);var C=t.range.apply(this,T);if(C=C.map(function(t,e){return parseFloat(t.toPrecision(12))}),a=t.scale.linear().domain(T.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(e=t.select(this).select("svg.chart-root"))||e.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),L=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));e=t.select(L)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var O,R=e.select(".chart-group"),D={fill:"none",stroke:u.tickColor},I={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){O=e.select(".legend-group").attr({transform:"translate("+[g,u.margin.top]+")"}).style({display:"block"});var P=c.map(function(t,e){var r=Sw.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});Sw.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:Ew({},Sw.Legend.defaultConfig().legendConfig,{container:O,elements:P,reverseOrder:u.legend.reverseOrder})})();var F=O.node().getBBox();g=Math.min(u.width-F.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,g=Math.max(10,g),m=[u.margin.left+g,u.margin.top+g],n.range([0,g]),l.layout.radialAxis.domain=n.domain(),O.attr("transform","translate("+[m[0]+g,m[1]-g]+")")}else O=e.select(".legend-group").style({display:"none"});e.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),R.attr("transform","translate("+m+")").style({cursor:"crosshair"});var z=[(u.width-(u.margin.left+u.margin.right+2*g+(F?F.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*g))/2];if(z[0]=Math.max(0,z[0]),z[1]=Math.max(0,z[1]),e.select(".outer-group").attr("transform","translate("+z+")"),u.title){var N=e.select("g.title-group text").style(I).text(u.title),B=N.node().getBBox();N.attr({x:m[0]-B.width/2,y:m[1]-g-20})}var j=e.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var U=j.selectAll("circle.grid-circle").data(n.ticks(5));U.enter().append("circle").attr({class:"grid-circle"}).style(D),U.attr("r",n),U.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(D);var V=e.select("circle.background-circle").attr({r:g}).style({fill:u.backgroundColor,stroke:u.stroke});function H(t,e){return a(t)%360+u.orientation}if(u.radialAxis.visible){var q=t.svg.axis().scale(n).ticks(5).tickSize(5);j.call(q).attr({transform:"rotate("+u.radialAxis.orientation+")"}),j.selectAll(".domain").style(D),j.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(I).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,I["font-size"]]+")":"translate("+[0,I["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=e.select(".angular.axis-group").selectAll("g.angular-tick").data(C),X=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(t,e){return"rotate("+H(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),G.exit().remove(),X.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(D),X.selectAll(".minor").style({stroke:u.minorTickColor}),G.select("line.grid-line").attr({x1:u.tickLength?g-u.tickLength:0,x2:g}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),X.append("text").classed("axis-text",!0).style(I);var W=G.select("text.axis-text").attr({x:g+u.labelOffset,dy:Cw+"em",transform:function(t,e){var r=H(t),n=g+u.labelOffset,a=u.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-r+" "+n+" 0)":"radial"==a?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":y?y[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(I);u.angularAxis.rewriteTicks&&W.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var Y=t.max(R.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));O.attr({transform:"translate("+[g+Y,u.margin.top]+")"});var Z=e.select("g.geometry-group").selectAll("g").size()>0,J=e.select("g.geometry-group").selectAll("g.geometry").data(c);if(J.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),J.exit().remove(),c[0]||Z){var Q=[];c.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=a,r.container=J.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=u.orientation,r.direction=u.direction,r.index=e,Q.push({data:t,geometryConfig:r})});var $=[];t.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(Q).forEach(function(t,e){"unstacked"===t.key?$=$.concat(t.values.map(function(t,e){return[t]})):$.push(t.values)}),$.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return Ew(Sw[r].defaultConfig(),t)});Sw[r]().config(n)()})}var K,tt,et=e.select(".guides-group"),rt=e.select(".tooltips-group"),nt=Sw.tooltipPanel().config({container:rt,fontSize:8})(),at=Sw.tooltipPanel().config({container:rt,fontSize:8})(),it=Sw.tooltipPanel().config({container:rt,hasTick:!0})();if(!b){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});R.on("mousemove.angular-guide",function(t,e){var r=Sw.util.getMousePos(V).angle;ot.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;K=a.invert(n);var i=Sw.util.convertToCartesian(g+12,r+180);nt.text(Sw.util.round(K)).move([i[0]+m[0],i[1]+m[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var lt=et.select("circle").style({stroke:"grey",fill:"none"});R.on("mousemove.radial-guide",function(t,e){var r=Sw.util.getMousePos(V).radius;lt.attr({r:r}).style({opacity:.5}),tt=n.invert(Sw.util.getMousePos(V).radius);var a=Sw.util.convertToCartesian(r,u.radialAxis.orientation);at.text(Sw.util.round(tt)).move([a[0]+m[0],a[1]+m[1]])}).on("mouseout.radial-guide",function(t,e){lt.style({opacity:0}),it.hide(),nt.hide(),at.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var a=t.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=t.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:Sw.util.round(r[0]),r:Sw.util.round(r[1])};b&&(s.t=y[r[0]]);var u="t: "+s.t+", r: "+s.r,c=this.getBoundingClientRect(),f=e.node().getBoundingClientRect(),h=[c.left+c.width/2-z[0]-f.left,c.top+c.height/2-z[1]-f.top];it.config({color:o}).text(u),it.move(h)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=t.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(e,r){if(0!=t.event.which)return!1;t.select(this).attr("data-fill")&&it.show()}).on("mouseout.tooltip",function(e,r){it.hide();var n=t.select(this),a=n.attr("data-fill");a?n.style({fill:a,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return i;var e=Sw.util.cloneJson(t);return e.data.forEach(function(t,e){i.data[e]||(i.data[e]={}),Ew(i.data[e],Sw.Axis.defaultConfig().data[0]),Ew(i.data[e],t)}),Ew(i.layout,Sw.Axis.defaultConfig().layout),Ew(i.layout,e.layout),this},u.getLiveConfig=function(){return l},u.getinputConfig=function(){return o},u.radialScale=function(t){return n},u.angularScale=function(t){return a},u.svg=function(){return e},t.rebind(u,s,"on"),u},Sw.Axis.defaultConfig=function(e,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:t.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Sw.util={},Sw.DATAEXTENT="dataExtent",Sw.AREA="AreaChart",Sw.LINE="LinePlot",Sw.DOT="DotPlot",Sw.BAR="BarChart",Sw.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},Sw.util._extend=function(t,e){for(var r in t)e[r]=t[r]},Sw.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Sw.util.dataFromEquation2=function(e,r){var n=r||6;return t.range(0,360+n,n).map(function(t,r){var n=t*Math.PI/180;return[t,e(n)]})},Sw.util.dataFromEquation=function(e,r,n){var a=r||6,i=[],o=[];t.range(0,360+a,a).forEach(function(t,r){var n=t*Math.PI/180,a=e(n);i.push(t),o.push(a)});var l={t:i,r:o};return n&&(l.name=n),l},Sw.util.ensureArray=function(e,r){if(void 0===e)return null;var n=[].concat(e);return t.range(r).map(function(t,e){return n[e]||n[0]})},Sw.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=Sw.util.ensureArray(t[e],r)}),t},Sw.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},Sw.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},Sw.util.sumArrays=function(e,r){return t.zip(e,r).map(function(e,r){return t.sum(e)})},Sw.util.arrayLast=function(t){return t[t.length-1]},Sw.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},Sw.util.flattenArray=function(t){for(var e=[];!Sw.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},Sw.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},Sw.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},Sw.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},Sw.util.getMousePos=function(e){var r=t.mouse(e.node()),n=r[0],a=r[1],i={};return i.x=n,i.y=a,i.pos=r,i.angle=180*(Math.atan2(a,n)+Math.PI)/Math.PI,i.radius=Math.sqrt(n*n+a*a),i},Sw.util.duplicatesCount=function(t){for(var e,r={},n={},a=0,i=t.length;a0)){var s=t.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:c(l),transform:function(t,e){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return p.fill(n,a,i)},"fill-opacity":0,stroke:function(t,e){return p.stroke(n,a,i)},"stroke-width":function(t,e){return p["stroke-width"](n,a,i)},"stroke-dasharray":function(t,e){return p["stroke-dasharray"](n,a,i)},opacity:function(t,e){return p.opacity(n,a,i)},display:function(t,e){return p.display(n,a,i)}})}};var f=r.angularScale.range(),h=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,d=t.svg.arc().startAngle(function(t){return-h/2}).endAngle(function(t){return h/2}).innerRadius(function(t){return r.radialScale(s+(t[2]||0))}).outerRadius(function(t){return r.radialScale(s+(t[2]||0))+r.radialScale(t[1])});u.arc=function(e,n,a){t.select(this).attr({class:"mark arc",d:d,transform:function(t,e){return"rotate("+(r.orientation+l(t[0])+90)+")"}})};var p={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,a){return n[e[a].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return void 0===e[n].data.visible||e[n].data.visible?"block":"none"}},g=t.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(p).each(u[r.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(t){return arguments.length?(t.forEach(function(t,r){e[r]||(e[r]={}),Ew(e[r],Sw.PolyChart.defaultConfig()),Ew(e[r],t)}),this):e},a.getColorScale=function(){},t.rebind(a,r,"on"),a},Sw.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:t.scale.category20()}}},Sw.BarChart=function(){return Sw.PolyChart()},Sw.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Sw.AreaChart=function(){return Sw.PolyChart()},Sw.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Sw.DotPlot=function(){return Sw.PolyChart()},Sw.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Sw.LinePlot=function(){return Sw.PolyChart()},Sw.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Sw.Legend=function(){var e=Sw.Legend.defaultConfig(),r=t.dispatch("hover");function n(){var r=e.legendConfig,a=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var a=Ew({},r.elements[e]);return a.name=t,a.color=[].concat(r.elements[e].color)[n],a})}),i=t.merge(a);i=i.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||void 0===r.elements[e].visibleInLegend)}),r.reverseOrder&&(i=i.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=t.select(o));var l=i.map(function(t,e){return t.color}),s=r.fontSize,u=null==r.isContinuous?"number"==typeof i[0]:r.isContinuous,c=u?r.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),h=f.enter().append("svg").attr({width:300,height:c+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});h.append("g").classed("legend-axis",!0),h.append("g").classed("legend-marks",!0);var d=t.range(i.length),p=t.scale[u?"linear":"ordinal"]().domain(d).range(l),g=t.scale[u?"linear":"ordinal"]().domain(d)[u?"range":"rangePoints"]([0,c]);if(u){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),f.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var m=f.select(".legend-marks").selectAll("path.legend-mark").data(i);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[s/2,g(e)+s/2]+")"},d:function(e,r){var n,a,i,o=e.symbol;return i=3*(a=s),"line"===(n=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=t.svg.symbolTypes.indexOf(n)?t.svg.symbol().type(n).size(i)():t.svg.symbol().type("square").size(i)()},fill:function(t,e){return p(e)}}),m.exit().remove()}var y=t.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:s,s/2]+")"}).call(y);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),x.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return i[e].name}),n}return n.config=function(t){return arguments.length?(Ew(e,t),this):e},t.rebind(n,r,"on"),n},Sw.Legend.defaultConfig=function(t,e){return{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:!1}}},Sw.tooltipPanel=function(){var e,r,n,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+Sw.tooltipPanel.uid++,o=10,l=function(){var t=(e=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return n=t.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=t.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=t.hsl(a.color).l,u=s>=.5?"#aaa":"white",c=s>=.5?"black":"white",f=i||"";r.style({fill:c,"font-size":a.fontSize+"px"}).text(f);var h=a.padding,d=r.node().getBBox(),p={fill:a.color,stroke:u,"stroke-width":"2px"},g=d.width+2*h+o,v=d.height+2*h;return n.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),e.attr({transform:"translate("+[o,-v/2+2*h]+")"}),e.style({display:"block"}),l},l.move=function(t){if(e)return e.attr({transform:"translate("+[t[0],t[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(e)return e.style({display:"none"}),l},l.show=function(){if(e)return e.style({display:"block"}),l},l.config=function(t){return Ew(a,t),l},l},Sw.tooltipPanel.uid=1,Sw.adapter={},Sw.adapter.plotly=function(){var e={convert:function(e,r){var n={};if(e.data&&(n.data=e.data.map(function(t,e){var n=Ew({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,e){Sw.util.translator.apply(null,t.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&e.layout&&"stack"===e.layout.barmode)){var a=Sw.util.duplicates(n.data.map(function(t,e){return t.geometry}));n.data.forEach(function(t,e){var r=a.indexOf(t.geometry);-1!=r&&(n.data[e].groupId=r)})}if(e.layout){var i=Ew({},e.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,e){Sw.util.translator.apply(null,t.concat(r))}),r?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};t.entries(i.margin).forEach(function(t,e){s[l[o.indexOf(t.key)]]=t.value}),i.margin=s}r&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),n.layout=i}return n}};return e};var Lw,Ow=ne.extendDeepAll,Rw=Lw={};Rw.framework=function(e){var r,n,a,i,o,l=new function(){var t,e=[],r=-1,n=!1;function a(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(a(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(a(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?Ow(r,n):n,a||(a=kw.Axis()),i=kw.adapter.plotly().convert(r),a.config(i).render(o),e.data=r.data,e.layout=r.layout,Rw.fillLayout(e),r}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return r},s.getLiveConfig=function(){return kw.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var t,e,a=this,i=kw.util.cloneJson(r);t=i,e=n,l.add({undo:function(){e&&a(e)},redo:function(){a(t)}}),n=kw.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},Rw.fillLayout=function(e){var r=t.select(e).selectAll(".plot-container"),n=r.selectAll(".svg-container"),a=e.framework&&e.framework.svg&&e.framework.svg(),i={width:800,height:600,paper_bgcolor:Ie.background,_container:r,_paperdiv:n,_paper:a};e._fullLayout=Ow(i,e.layout)};var Dw={};(Dw=kw).manager=Lw;var Iw={},Pw=Dg.enforce,Fw=Dg.clean,zw=ca,Nw=0;function Bw(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){ne.error(t)}}function jw(t,e){Bw(t,Ie.combine(e,"white"))}function Uw(t,e){t._context||(t._context=ne.extendDeep({},b));var r,n,a,i=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||a<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(a,n+1)>-1||a>=0&&e.indexOf(-t.data.length+a)>-1||a<0&&e.indexOf(t.data.length+a)>-1)throw new Error("each index in "+r+" must be unique.")}}function qw(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),Hw(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&Hw(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function Gw(t,r,n,a,i){!function(t,e,r,n){var a=ne.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!ne.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var i in Hw(t,r,"indices"),e){if(!Array.isArray(e[i])||e[i].length!==r.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in n)||!Array.isArray(n[i])||n[i].length!==e[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,r,n,a);for(var o=function(t,r,n,a){var i,o,l,s,u,c=ne.isPlainObject(a),f=[];for(var h in Array.isArray(n)||(n=[n]),n=Vw(n,t.data.length-1),r)for(var d=0;d0&&"string"!=typeof _.parts[A-1];)M--;var T=_.parts[M],k=_.parts[M-1]+"."+T,E=_.parts.slice(0,M).join("."),C=ne.nestedProperty(t.layout,E).get(),S=ne.nestedProperty(o,E).get(),L=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===T?w:Ww(L);var O=Ln.getLayoutValObject(o,_.parts);if(O&&O.impliedEdits&&null!==w)for(var D in O.impliedEdits)v(ne.relativeAttr(b,D),O.impliedEdits[D]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=t._initialAutoSize[b];else if(k.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(k),ne.nestedProperty(o,E+"._inputRange").set(null);else if(k.match(/^[xyz]axis[0-9]*\.autorange$/)){x(k),ne.nestedProperty(o,E+"._inputRange").set(null);var I=ne.nestedProperty(o,E).get();I._inputDomain&&(I._input.domain=I._inputDomain.slice())}else k.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&ne.nestedProperty(o,E+"._inputDomain").set(null);if("type"===T){var P=C,F="linear"===S.type&&"log"===w,z="log"===S.type&&"linear"===w;if(F||z){if(P&&P.range)if(S.autorange)F&&(P.range=P.range[1]>P.range[0]?[1,2]:[2,1]);else{var N=P.range[0],B=P.range[1];F?(N<=0&&B<=0&&v(E+".autorange",!0),N<=0?N=B/1e6:B<=0&&(B=N/1e6),v(E+".range[0]",Math.log(N)/Math.LN10),v(E+".range[1]",Math.log(B)/Math.LN10)):(v(E+".range[0]",Math.pow(10,N)),v(E+".range[1]",Math.pow(10,B)))}else v(E+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],R.getComponentMethod("annotations","convertCoords")(t,S,w,v),R.getComponentMethod("images","convertCoords")(t,S,w,v)}else v(E+".autorange",!0),v(E+".range",null);ne.nestedProperty(o,E+"._inputRange").set(null)}else if(T.match(Ce.AX_NAME_PATTERN)){var j=ne.nestedProperty(o,b).get(),U=(w||{}).type;U&&"-"!==U||(U="linear"),R.getComponentMethod("annotations","convertCoords")(t,j,U,v),R.getComponentMethod("images","convertCoords")(t,j,U,v)}var V=s_.containerArrayMatch(b);if(V){r=V.array,n=V.index;var H=V.property,q=(ne.nestedProperty(i,r)||[])[n]||{},G=q,X=O||{editType:"calc"},W=-1!==X.editType.indexOf("calcIfAutorange");""===n?(W?d.calc=!0:ye.update(d,X),W=!1):""===H&&(G=w,s_.isAddVal(w)?g[b]=null:s_.isRemoveVal(w)?(g[b]=q,G=q):ne.warn("unrecognized full object value",e)),W&&(Qw(t,G,"x")||Qw(t,G,"y"))?d.calc=!0:ye.update(d,X),u[r]||(u[r]={});var Y=u[r][n];Y||(Y=u[r][n]={}),Y[H]=w,delete e[b]}else"reverse"===T?(C.range?C.range.reverse():(v(E+".autorange",!0),C.range=[1,0]),S.autorange?d.calc=!0:d.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==L&&"select"!==L?d.plot=!0:O?ye.update(d,O):d.calc=!0,_.set(w))}}for(r in u){s_.applyContainerArrayChanges(t,ne.nestedProperty(i,r),u[r],d)||(d.plot=!0)}var Z=o._axisConstraintGroups||[];for(m in y)for(n=0;n=0&&r=0&&r=a.length?a[0]:a[t]:a}function l(t){return Array.isArray(i)?t>=i.length?i[0]:i[t]:i}function s(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(i,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,Xn.transition(t,e.frame.data,e.frame.layout,Kb.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function f(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var h,d,p=0;function g(t){return Array.isArray(a)?p>=a.length?t.transitionOpts=a[p]:t.transitionOpts=a[0]:t.transitionOpts=a,p++,t}var v=[],m=void 0===e||null===e,y=Array.isArray(e);if(!m&&!y&&ne.isPlainObject(e))v.push({type:"object",data:g(ne.extendFlat({},e))});else if(m||-1!==["string","number"].indexOf(typeof e))for(h=0;h0&&__)&&w.push(d);v=w}}v.length>0?function(e){if(0!==e.length){for(var a=0;a=0;n--)if(ne.isPlainObject(e[n])){var h=e[n].name,d=(s[h]||f[h]||{}).name,p=e[n].name,g=s[d]||f[d];d&&p&&"number"==typeof p&&g&&Nw<5&&(Nw++,ne.warn('addFrames: overwriting frame "'+(s[d]||f[d]).name+'" with a frame whose name of type "number" also equates to "'+d+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===Nw&&ne.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[h]={name:h},c.push({frame:Xn.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(a=c[n].frame).name&&ne.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+t._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;r--)n=e[r],i.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:a[n]});var l=Xn.modifyFrames,s=Xn.modifyFrames,u=[t,o],c=[t,i];return Qb&&Qb.add(t,l,u,s,c),Xn.modifyFrames(t,i)},Iw.purge=function(t){var e=(t=ne.getGraphDiv(t))._fullLayout||{},r=t._fullData||[];return Xn.cleanPlot([],{},r,e),Xn.purge(t),Qp.purge(t),e._container&&e._container.remove(),delete t._context,t};var tA={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},eA=Gp.EventEmitter;var rA=function(t){var e=t.emitter||new eA,r=new Promise(function(n,a){var i=window.Image,o=t.svg,l=t.format||"png";if(ne.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),t.promise?r:e.emit("error",s)}var u=t.canvas,c=t.scale||1,f=c*(t.width||300),h=c*(t.height||150),d=u.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);u.width=f,u.height=h,p.onload=function(){var r;switch("svg"!==l&&d.drawImage(p,0,0,f,h),l){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!t.promise)return e.emit("error",i)}n(r),t.promise||e.emit("success",r)},p.onerror=function(r){if(a(r),!t.promise)return e.emit("error",r)},p.src=g});return t.promise?r:e},nA=/"/g,aA=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var iA=function(e,r,n){var a,i=e._fullLayout,o=i._paper,l=i._toppaper,s=i.width,u=i.height;o.insert("rect",":first-child").call(Zr.setRect,0,0,s,u).call(Ie.fill,i.paper_bgcolor);var c=i._basePlotModules||[];for(a=0;a")?"":r.html(t).text()});return r.remove(),n}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(aA,"'"),ne.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},oA={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},lA=/^data:image\/\w+;base64,/;var sA=function(t,e){var r,n,a;function i(t){return!(t in e)||ne.validate(e[t],oA[t])}if(e=e||{},ne.isPlainObject(t)?(r=t.data||[],n=t.layout||{},a=t.config||{}):(t=ne.getGraphDiv(t),r=ne.extendDeep([],t.data),n=ne.extendDeep({},t.layout),a=t._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(t,r){return ne.coerce(e,o,oA,t,r)}var s=l("format"),u=l("width"),c=l("height"),f=l("scale"),h=l("setBackground"),d=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=ne.extendFlat({},n);u&&(g.width=u),c&&(g.height=c);var v=ne.extendFlat({},a,{staticPlot:!0,setBackground:h}),m=tA.getRedrawFunc(p);function y(){return new Promise(function(t){setTimeout(t,tA.getDelay(p._fullLayout))})}function x(){return new Promise(function(t,e){var r=iA(p,s,f),n=p._fullLayout.width,a=p._fullLayout.height;if(Iw.purge(p),document.body.removeChild(p),"svg"===s)return t(d?r:"data:image/svg+xml,"+encodeURIComponent(r));var i=document.createElement("canvas");i.id=ne.randstr(),rA({format:s,width:n,height:a,scale:f,canvas:i,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){Iw.plot(p,r,g,v).then(m).then(y).then(x).then(function(e){t(function(t){return d?t.replace(lA,""):t}(e))}).catch(function(t){e(t)})})},uA=ne.isPlainObject,cA=Array.isArray,fA=ne.isArrayOrTypedArray;function hA(t,e,r,n,a,i){i=i||[];for(var o=Object.keys(t),l=0;lf.length&&n.push(gA("unused",a,u.concat(f.length)));var v,m,y,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===h.dimensions)for(m=0;m<_;m++)if(cA(c[m])){c[m].length>f[m].length&&n.push(gA("unused",a,u.concat(m,f[m].length)));var A=f[m].length;for(v=0;v<(w?Math.min(A,g[m].length):A);v++)y=w?g[m][v]:g,x=c[m][v],b=f[m][v],ne.validate(x,y)?b!==x&&b!==+x&&n.push(gA("dynamic",a,u.concat(m,v),x,b)):n.push(gA("value",a,u.concat(m,v),x))}else n.push(gA("array",a,u.concat(m),c[m]));else for(m=0;m<_;m++)y=w?g[m]:g,x=c[m],b=f[m],ne.validate(x,y)?b!==x&&b!==+x&&n.push(gA("dynamic",a,u.concat(m),x,b)):n.push(gA("value",a,u.concat(m),x))}else if(h.items&&!d&&cA(c)){var M,T,k=g[Object.keys(g)[0]],E=[];for(M=0;M1&&i.push(gA("object","layout"))),Xn.supplyDefaults(o);for(var l=o._fullData,s=r.length,u=0;u-1&&(l[u[r]].title="");for(r=0;r=0;a--){var i=t[a];if("scatter"===i.type&&i.xaxis===r.xaxis&&i.yaxis===r.yaxis){i.opacity=void 0;break}}}}},UA=function(t,r){var n=r[0].trace,a=n.marker,i="cb"+n.uid;if(t._fullLayout._infolayer.selectAll("."+i).remove(),void 0!==a&&a.showscale){var o=a.color,l=a.cmin,s=a.cmax;e(l)||(l=ne.aggNums(Math.min,null,o)),e(s)||(s=ne.aggNums(Math.max,null,o));var u=r[0].t.cb=mm(t,i),c=xr.makeColorScaleFunc(xr.extractScale(a.colorscale,l,s),{noNumericCheck:!0});u.fillcolor(c).filllevels({start:l,end:s,size:(s-l)/254}).options(a.colorbar)()}else Xn.autoMargin(t,i)},VA=ne.isArrayOrTypedArray,HA=function(t,e,r,n){var a=!1;if(e.marker){var i=e.marker.color,o=(e.marker.line||{}).color;i&&!VA(i)?a=i:o&&!VA(o)&&(a=o)}n("fillcolor",Ie.addOpacity((e.line||{}).color||a||r,.5))},qA=ne.isArrayOrTypedArray,GA=function(t,e,r,n,a,i){var o=(t.marker||{}).color;(a("line.color",r),mr(t,"line"))?vr(t,e,n,a,{prefix:"line.",cLetter:"c"}):a("line.color",!qA(o)&&o||r);a("line.width"),(i||{}).noDash||a("line.dash")},XA=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")},WA=function(t,e,r,n,a,i){var o=Yr.isBubble(t),l=(t.line||{}).color;(i=i||{},l&&(r=l),a("marker.symbol"),a("marker.opacity",o?.7:1),a("marker.size"),a("marker.color",r),mr(t,"marker")&&vr(t,e,n,a,{prefix:"marker.",cLetter:"c"}),i.noSelect||(a("selected.marker.color"),a("unselected.marker.color"),a("selected.marker.size"),a("unselected.marker.size")),i.noLine||(a("marker.line.color",l&&!Array.isArray(l)&&e.marker.color!==l?l:o?Ie.background:Ie.defaultLine),mr(t,"marker.line")&&vr(t,e,n,a,{prefix:"marker.line.",cLetter:"c"}),a("marker.line.width",o?1:0)),o&&(a("marker.sizeref"),a("marker.sizemin"),a("marker.sizemode")),i.gradient)&&("none"!==a("marker.gradient.type")&&a("marker.gradient.color"))},YA=function(t,e,r,n){var a,i=n("x"),o=n("y");if(R.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),i)o?a=Math.min(i.length,o.length):(a=i.length,n("y0"),n("dy"));else{if(!o)return 0;a=e.y.length,n("x0"),n("dx")}return e._length=a,a},ZA=function(t,e,r){var n=Array.isArray(r)?function(t){r.push(t)}:function(t){r.text=t},a=ne.extractOption(t,e,"htx","hovertext");if(JA(a))return n(a);var i=ne.extractOption(t,e,"tx","text");return JA(i)?n(i):void 0};function JA(t){return t||0===t}var QA=function(t,e){var r,n;if("lines"===t.mode)return(r=t.line.color)&&Ie.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var a=e.mcc||(t.marker||{}).color,i=e.mlcc||((t.marker||{}).line||{}).color;return(n=a&&Ie.opacity(a)?a:i&&Ie.opacity(i)&&(e.mlw||((t.marker||{}).line||{}).width)?i:"")?Ie.opacity(n)<.3?Ie.addOpacity(n,.3):n:(r=(t.line||{}).color)&&Ie.opacity(r)&&Yr.hasLines(t)&&t.line.width?r:t.fillcolor},$A=r.BADNUM,KA=ne.segmentsIntersect,tM=ne.constrain,eM=function(t,e){var r,n,a,i,o,l,s,u,c,f,h,d,p,g,v,m,y=e.xaxis,x=e.yaxis,b=e.simplify,_=e.connectGaps,w=e.baseTolerance,A=e.shape,M="linear"===A,T=[],k=xn.minTolerance,E=new Array(t.length),C=0;function S(e){var r=t[e],n=y.c2p(r.x),a=x.c2p(r.y);return n===$A||a===$A?r.intoCenter||!1:[n,a]}function L(t){var e=t[0]/y._length,r=t[1]/x._length;return(1+xn.toleranceGrowth*Math.max(0,-e,e-1,-r,r-1))*w}function O(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}b||(w=k=-1);var R,D,I,P,F,z,N,B=xn.maxScreensAway,j=-y._length*B,U=y._length*(1+B),V=-x._length*B,H=x._length*(1+B),q=[[j,V,U,V],[U,V,U,H],[U,H,j,H],[j,H,j,V]];function G(t){if(t[0]U||t[1]H)return[tM(t[0],j,U),tM(t[1],V,H)]}function X(t,e){return t[0]===e[0]&&(t[0]===j||t[0]===U)||(t[1]===e[1]&&(t[1]===V||t[1]===H)||void 0)}function W(t,e,r){return function(n,a){var i=G(n),o=G(a),l=[];if(i&&o&&X(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*ne.constrain((n[t]+a[t])/2,e,r)-((i||n)[t]+(o||a)[t]);s&&((i&&o?s>0==i[t]>o[t]?i:o:i||o)[t]+=s);return l}}function Y(t){var e=t[0],r=t[1],n=e===E[C-1][0],a=r===E[C-1][1];if(!n||!a)if(C>1){var i=e===E[C-2][0],o=r===E[C-2][1];n&&(e===j||e===U)&&i?o?C--:E[C-1]=t:a&&(r===V||r===H)&&o?i?C--:E[C-1]=t:E[C++]=t}else E[C++]=t}function Z(t){E[C-1][0]!==t[0]&&E[C-1][1]!==t[1]&&Y([I,P]),Y(t),F=null,I=P=0}function J(t){if(R=t[0]U?U:0,D=t[1]H?H:0,R||D){if(C)if(F){var e=N(F,t);e.length>1&&(Z(e[0]),E[C++]=e[1])}else z=N(E[C-1],t)[0],E[C++]=z;else E[C++]=[R||t[0],D||t[1]];var r=E[C-1];R&&D&&(r[0]!==R||r[1]!==D)?(F&&(I!==R&&P!==D?Y(I&&P?(n=F,i=(a=t)[0]-n[0],o=(a[1]-n[1])/i,(n[1]*a[0]-a[1]*n[0])/i>0?[o>0?j:U,H]:[o>0?U:j,V]):[I||R,P||D]):I&&P&&Y([I,P])),Y([R,D])):I-R&&P-D&&Y([R||I,D||P]),F=t,I=R,P=D}else F&&Z(N(F,t)[0]),E[C++]=t;var n,a,i,o}for("linear"===A||"spline"===A?N=function(t,e){for(var r=[],n=0,a=0;a<4;a++){var i=q[a],o=KA(t[0],t[1],e[0],e[1],i[0],i[1],i[2],i[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&O(o,t)L(l))break;a=l,(p=c[0]*u[0]+c[1]*u[1])>h?(h=p,i=l,s=!1):p=t.length||!l)break;J(l),n=l}}else J(i)}F&&Y([I||F[0],P||F[1]]),T.push(E.slice(0,C))}return T},rM=function(t,e,r){var n,a,i=null;for(a=0;a=s[0]&&t.x<=s[1]&&t.y>=u[0]&&t.y<=u[1]}),d=Math.ceil(h.length/f),p=0;i.forEach(function(t,e){var n=t[0].trace;Yr.hasMarkers(n)&&n.marker.maxdisplayed>0&&e0;function f(t){return c?t.transition():t}var h=n.xaxis,d=n.yaxis,p=a[0].trace,g=p.line,v=t.select(o);if(R.getComponentMethod("errorbars","plot")(v,n,l),!0===p.visible){var m,y;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),a[0].node3=v;var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",y=w._nextFill,_=w._polygons);var A,M,T,k,E,C,S,L,O,D="",I="",P=[],F=ne.noop;if(m=p._ownFill,Yr.hasLines(p)||"none"!==p.fill){for(y&&y.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=Zr.steps(g.shape),k=Zr.steps(g.shape.split("").reverse().join(""))):T=k="spline"===g.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?Zr.smoothclosed(t.slice(1),g.smoothing):Zr.smoothopen(t,g.smoothing)}:function(t){return"M"+t.join("L")},E=function(t){return k(t.reverse())},P=eM(a,{xaxis:h,yaxis:d,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),O=p._polygons=new Array(P.length),u=0;u1){var n=t.select(this);if(n.datum(a),e)f(n.style("opacity",0).attr("d",A).call(Zr.lineGroupStyle)).style("opacity",1);else{var i=f(n);i.attr("d",A),Zr.singleLineStyle(a,i)}}}}}var z=v.selectAll(".js-line").data(P);f(z.exit()).style("opacity",0).remove(),z.each(F(!1)),z.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Zr.lineGroupStyle).each(F(!0)),Zr.setClipUrl(z,n.layerClipId),P.length?(m?C&&L&&(x?("y"===x?C[1]=L[1]=d.c2p(0,!0):"x"===x&&(C[0]=L[0]=h.c2p(0,!0)),f(m).attr("d","M"+L+"L"+C+"L"+D.substr(1)).call(Zr.singleFillStyle)):f(m).attr("d",D+"Z").call(Zr.singleFillStyle)):y&&("tonext"===p.fill.substr(0,6)&&D&&b?("tonext"===p.fill?f(y).attr("d",D+"Z"+b+"Z").call(Zr.singleFillStyle):f(y).attr("d",D+"L"+b.substr(1)+"Z").call(Zr.singleFillStyle),p._polygons=p._polygons.concat(_)):(B(y),p._polygons=null)),p._prevRevpath=I,p._prevPolygons=O):(m?B(m):y&&B(y),p._polygons=p._prevRevpath=p._prevPolygons=null);var N=v.selectAll(".points");s=N.data([a]),N.each(q),s.enter().append("g").classed("points",!0).each(q),s.exit().remove(),s.each(function(e){var r=!1===e[0].trace.cliponaxis;Zr.setClipUrl(t.select(this),r?null:n.layerClipId)})}function B(t){f(t).attr("d","M0,0Z")}function j(t){return t.filter(function(t){return t.vis})}function U(t){return t.id}function V(t){if(t.ids)return U}function H(){return!1}function q(r){var a,i=r[0].trace,o=t.select(this),l=Yr.hasMarkers(i),s=Yr.hasText(i),u=V(i),p=H,g=H;l&&(p=i.marker.maxdisplayed||i._needsCull?j:ne.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?j:ne.identity);var v=(a=o.selectAll("path.point").data(p,u)).enter().append("path").classed("point",!0);c&&v.call(Zr.pointStyle,i,e).call(Zr.translatePoints,h,d).style("opacity",0).transition().style("opacity",1);var m=l&&Zr.tryColorscale(i.marker,""),y=l&&Zr.tryColorscale(i.marker,"line");a.order(),a.each(function(r){var a=t.select(this),o=f(a);Zr.translatePoint(r,o,h,d)?(Zr.singlePointStyle(r,o,i,m,y,e),n.layerClipId&&Zr.hideOutsideRangePoint(r,o,h,d,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),c?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,u)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(e){var r=t.select(this),a=f(r.select("text"));Zr.translatePoint(e,a,h,d)?n.layerClipId&&Zr.hideOutsideRangePoint(e,r,h,d,i.xcalendar,i.ycalendar):r.remove()}),a.selectAll("text").call(Zr.textPointStyle,i,e).each(function(e){var r=h.c2p(e.x),n=d.c2p(e.y);t.select(this).selectAll("tspan.line").each(function(){f(t.select(this)).attr({x:r,y:n})})}),a.exit().remove()}}function iM(t,e,r){var n=t.selectAll("path.point"),a=t.selectAll("text");Zr.pointStyle(n,e,r),Zr.textPointStyle(a,e,r),Zr.selectedPointStyle(n,e),Zr.selectedTextStyle(a,e)}var oM=function(e,r){var n=r?r[0].node3:t.select(e).selectAll("g.trace.scatter");n.style("opacity",function(t){return t[0].trace.opacity}),n.selectAll("g.points").each(function(r){iM(t.select(this),r.trace||r[0].trace,e)}),n.selectAll("g.trace path.js-line").call(Zr.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(Zr.fillGroupStyle),R.getComponentMethod("errorbars","style")(n)},lM={};lM.hasLines=Yr.hasLines,lM.hasMarkers=Yr.hasMarkers,lM.hasText=Yr.hasText,lM.isBubble=Yr.isBubble,lM.attributes=wn,lM.supplyDefaults=function(t,e,r,n){function a(r,n){return ne.coerce(t,e,wn,r,n)}var i=YA(t,e,n,a),o=i0;for((s=c.selectAll("g.trace").data(n,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),rM(e,r,n),function(e,r,n){var a;r.selectAll("g.trace").each(function(e){var r=t.select(this);if((a=e[0].trace)._nexttrace){if(a._nextFill=r.select(".js-fill.js-tonext"),!a._nextFill.size()){var i=":first-child";r.select(".js-fill.js-tozero").size()&&(i+=" + *"),a._nextFill=r.insert("path",i).attr("class","js-fill js-tonext")}}else r.selectAll(".js-fill.js-tonext").remove(),a._nextFill=null;a.fill&&("tozero"===a.fill.substr(0,6)||"toself"===a.fill||"to"===a.fill.substr(0,2)&&!a._prevtrace)?(a._ownFill=r.select(".js-fill.js-tozero"),a._ownFill.size()||(a._ownFill=r.insert("path",":first-child").attr("class","js-fill js-tozero"))):(r.selectAll(".js-fill.js-tozero").remove(),a._ownFill=null),r.selectAll(".js-fill").call(Zr.setClipUrl,n.layerClipId)})}(0,c,r),o=0,l={};ol[e[0].trace.uid]?1:-1}),h?(i&&(u=i()),t.transition().duration(a.duration).ease(a.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(t,i){aM(e,i,r,t,n,this,a)})})):c.selectAll("g.trace").each(function(t,i){aM(e,i,r,t,n,this,a)});f&&s.exit().remove(),c.selectAll("path:not([d])").remove()},lM.colorbar=UA,lM.style=oM,lM.hoverPoints=function(t,e,r,n){var a=t.cd,i=a[0].trace,o=t.xa,l=t.ya,s=o.c2p(e),u=l.c2p(r),c=[s,u],f=i.hoveron||"",h=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var d=function(t){var e=Math.max(h,t.mrc||0),r=o.c2p(t.x)-s,n=l.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-h/e)},p=kg.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-s);return nF!=(E=w[b][1])>=F&&(M=w[b-1][0],T=w[b][0],E-k&&(A=M+(T-M)*(F-k)/(E-k),O=Math.min(O,A),D=Math.max(D,A)));O=Math.max(O,0),D=Math.min(D,o._length);var z=Ie.defaultLine;return Ie.opacity(i.fillcolor)?z=i.fillcolor:Ie.opacity((i.line||{}).color)&&(z=i.line.color),ne.extendFlat(t,{distance:t.maxHoverDistance,x0:O,x1:D,y0:F,y1:F,color:z}),delete t.index,i.text&&!Array.isArray(i.text)?t.text=String(i.text):t.text=i.name,[t]}}},lM.selectPoints=function(t,e){var r,n,a,i,o=t.cd,l=t.xaxis,s=t.yaxis,u=[],c=o[0].trace;if(!Yr.hasMarkers(c)&&!Yr.hasText(c))return[];if(!1===e)for(r=0;r>>=e))<<3,(e|=r=(15<(t>>>=r))<<2)|(r=(3<(t>>>=r))<<1)|t>>>r>>1}function s(t){t:{for(var e=16;268435456>=e;e*=16)if(t<=e){t=e;break t}t=0}return 0<(e=W[l(t)>>2]).length?e.pop():new ArrayBuffer(t)}function u(t){W[l(t.byteLength)>>2].push(t)}function c(t,e,r,n,a,i){for(var o=0;o(a=s)&&(a=n.buffer.byteLength,5123===f?a>>=1:5125===f&&(a>>=2)),n.vertCount=a,a=l,0>l&&(a=4,1===(l=n.buffer.dimension)&&(a=0),2===l&&(a=1),3===l&&(a=4)),n.primType=a}function l(t){n.elementsCount--,delete s[t.id],t.buffer.destroy(),t.buffer=null}var s={},u=0,c={uint8:5121,uint16:5123};e.oes_element_index_uint&&(c.uint32=5125),a.prototype.bind=function(){this.buffer.bind()};var f=[];return{create:function(t,e){function s(t){if(t)if("number"==typeof t)u(t),f.primType=4,f.vertCount=0|t,f.type=5121;else{var e=null,r=35044,n=-1,a=-1,l=0,h=0;Array.isArray(t)||G(t)||i(t)?e=t:("data"in t&&(e=t.data),"usage"in t&&(r=$[t.usage]),"primitive"in t&&(n=rt[t.primitive]),"count"in t&&(a=0|t.count),"type"in t&&(h=c[t.type]),"length"in t?l=0|t.length:(l=a,5123===h||5122===h?l*=2:5125!==h&&5124!==h||(l*=4))),o(f,e,r,n,a,l,h)}else u(),f.primType=4,f.vertCount=0,f.type=5121;return s}var u=r.create(null,34963,!0),f=new a(u._buffer);return n.elementsCount++,s(t),s._reglType="elements",s._elements=f,s.subdata=function(t,e){return u.subdata(t,e),s},s.destroy=function(){l(f)},s},createStream:function(t){var e=f.pop();return e||(e=new a(r.create(null,34963,!0,!1)._buffer)),o(e,t,35040,-1,-1,0,0),e},destroyStream:function(t){f.push(t)},getElements:function(t){return"function"==typeof t&&t._elements instanceof a?t._elements:null},clear:function(){X(s).forEach(l)}}}function v(t){for(var e=Y.allocType(5123,t.length),r=0;r>>31<<15,a=(i<<1>>>24)-127,i=i>>13&1023;e[r]=-24>a?n:-14>a?n+(i+1024>>-14-a):15>=a,r.height>>=a,d(r,n[a]),t.mipmask|=1<e;++e)t.images[e]=null;return t}function S(t){for(var e=t.images,r=0;re){for(var r=0;r=--this.refCount&&F(this)}}),l.profile&&(o.getTotalTextureSize=function(){var t=0;return Object.keys(ft).forEach(function(e){t+=ft[e].stats.size}),t}),{create2D:function(e,r){function n(t,e){var r=a.texInfo;L.call(r);var i=C();return"number"==typeof t?T(i,0|t,"number"==typeof e?0|e:0|t):t?(O(r,t),k(i,t)):T(i,1,1),r.genMipmaps&&(i.mipmask=(i.width<<1)-1),a.mipmask=i.mipmask,u(a,i),a.internalformat=i.internalformat,n.width=i.width,n.height=i.height,I(a),E(i,3553),R(r,3553),P(),S(i),l.profile&&(a.stats.size=A(a.internalformat,a.type,i.width,i.height,r.genMipmaps,!1)),n.format=K[a.internalformat],n.type=tt[a.type],n.mag=et[r.magFilter],n.min=rt[r.minFilter],n.wrapS=nt[r.wrapS],n.wrapT=nt[r.wrapT],n}var a=new D(3553);return ft[a.id]=a,o.textureCount++,n(e,r),n.subimage=function(t,e,r,i){e|=0,r|=0,i|=0;var o=g();return u(o,a),o.width=0,o.height=0,d(o,t),o.width=o.width||(a.width>>i)-e,o.height=o.height||(a.height>>i)-r,I(a),p(o,3553,e,r,i),P(),M(o),n},n.resize=function(e,r){var i=0|e,o=0|r||i;if(i===a.width&&o===a.height)return n;n.width=a.width=i,n.height=a.height=o,I(a);for(var s=0;a.mipmask>>s;++s)t.texImage2D(3553,s,a.format,i>>s,o>>s,0,a.format,a.type,null);return P(),l.profile&&(a.stats.size=A(a.internalformat,a.type,i,o,!1,!1)),n},n._reglType="texture2d",n._texture=a,l.profile&&(n.stats=a.stats),n.destroy=function(){a.decRef()},n},createCube:function(e,r,n,a,i,s){function f(t,e,r,n,a,i){var o,s=h.texInfo;for(L.call(s),o=0;6>o;++o)v[o]=C();if("number"!=typeof t&&t){if("object"==typeof t)if(e)k(v[0],t),k(v[1],e),k(v[2],r),k(v[3],n),k(v[4],a),k(v[5],i);else if(O(s,t),c(h,t),"faces"in t)for(t=t.faces,o=0;6>o;++o)u(v[o],h),k(v[o],t[o]);else for(o=0;6>o;++o)k(v[o],t)}else for(t=0|t||1,o=0;6>o;++o)T(v[o],t,t);for(u(h,v[0]),h.mipmask=s.genMipmaps?(v[0].width<<1)-1:v[0].mipmask,h.internalformat=v[0].internalformat,f.width=v[0].width,f.height=v[0].height,I(h),o=0;6>o;++o)E(v[o],34069+o);for(R(s,34067),P(),l.profile&&(h.stats.size=A(h.internalformat,h.type,f.width,f.height,s.genMipmaps,!0)),f.format=K[h.internalformat],f.type=tt[h.type],f.mag=et[s.magFilter],f.min=rt[s.minFilter],f.wrapS=nt[s.wrapS],f.wrapT=nt[s.wrapT],o=0;6>o;++o)S(v[o]);return f}var h=new D(34067);ft[h.id]=h,o.cubeCount++;var v=Array(6);return f(e,r,n,a,i,s),f.subimage=function(t,e,r,n,a){r|=0,n|=0,a|=0;var i=g();return u(i,h),i.width=0,i.height=0,d(i,e),i.width=i.width||(h.width>>a)-r,i.height=i.height||(h.height>>a)-n,I(h),p(i,34069+t,r,n,a),P(),M(i),f},f.resize=function(e){if((e|=0)!==h.width){f.width=h.width=e,f.height=h.height=e,I(h);for(var r=0;6>r;++r)for(var n=0;h.mipmask>>n;++n)t.texImage2D(34069+r,n,h.format,e>>n,e>>n,0,h.format,h.type,null);return P(),l.profile&&(h.stats.size=A(h.internalformat,h.type,f.width,f.height,!1,!0)),f}},f._reglType="textureCube",f._texture=h,l.profile&&(f.stats=h.stats),f.destroy=function(){h.decRef()},f},clear:function(){for(var e=0;er;++r)if(0!=(e.mipmask&1<>r,e.height>>r,0,e.internalformat,e.type,null);else for(var n=0;6>n;++n)t.texImage2D(34069+n,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);R(e.texInfo,e.target)})}}}function T(t,e,r,n,a,i){function o(t,e,r){this.target=t,this.texture=e,this.renderbuffer=r;var n=t=0;e?(t=e.width,n=e.height):r&&(t=r.width,n=r.height),this.width=t,this.height=n}function l(t){t&&(t.texture&&t.texture._texture.decRef(),t.renderbuffer&&t.renderbuffer._renderbuffer.decRef())}function s(t,e,r){t&&(t.texture?t.texture._texture.refCount+=1:t.renderbuffer._renderbuffer.refCount+=1)}function u(e,r){r&&(r.texture?t.framebufferTexture2D(36160,e,r.target,r.texture._texture.texture,0):t.framebufferRenderbuffer(36160,e,36161,r.renderbuffer._renderbuffer.renderbuffer))}function c(t){var e=3553,r=null,n=null,a=t;return"object"==typeof t&&(a=t.data,"target"in t&&(e=0|t.target)),"texture2d"===(t=a._reglType)?r=a:"textureCube"===t?r=a:"renderbuffer"===t&&(n=a,e=36161),new o(e,r,n)}function f(t,e,r,i,l){return r?((t=n.create2D({width:t,height:e,format:i,type:l}))._texture.refCount=0,new o(3553,t,null)):((t=a.create({width:t,height:e,format:i}))._renderbuffer.refCount=0,new o(36161,null,t))}function h(t){return t&&(t.texture||t.renderbuffer)}function d(t,e,r){t&&(t.texture?t.texture.resize(e,r):t.renderbuffer&&t.renderbuffer.resize(e,r))}function p(){this.id=A++,M[this.id]=this,this.framebuffer=t.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function g(t){t.colorAttachments.forEach(l),l(t.depthAttachment),l(t.stencilAttachment),l(t.depthStencilAttachment)}function v(e){t.deleteFramebuffer(e.framebuffer),e.framebuffer=null,i.framebufferCount--,delete M[e.id]}function m(e){var n;t.bindFramebuffer(36160,e.framebuffer);var a=e.colorAttachments;for(n=0;na;++a){for(u=0;ut;++t)r[t].resize(n);return e.width=e.height=n,e},_reglType:"framebufferCube",destroy:function(){r.forEach(function(t){t.destroy()})}})},clear:function(){X(M).forEach(v)},restore:function(){X(M).forEach(function(e){e.framebuffer=t.createFramebuffer(),m(e)})}})}function k(){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 E(t,e,r,n){function a(t,e,r,n){this.name=t,this.id=e,this.location=r,this.info=n}function i(t,e){for(var r=0;rt&&(t=e.stats.uniformsCount)}),t},r.getMaxAttributesCount=function(){var t=0;return h.forEach(function(e){e.stats.attributesCount>t&&(t=e.stats.attributesCount)}),t}),{clear:function(){var e=t.deleteShader.bind(t);X(u).forEach(e),u={},X(c).forEach(e),c={},h.forEach(function(e){t.deleteProgram(e.program)}),h.length=0,f={},r.shaderCount=0},program:function(t,e,n){var a=f[e];a||(a=f[e]={});var i=a[t];return i||(i=new l(e,t),r.shaderCount++,s(i),a[t]=i,h.push(i)),i},restore:function(){u={},c={};for(var t=0;t="+e+"?"+a+".constant["+e+"]:0;"}).join(""),"}}else{","if(",o,"(",a,".buffer)){",c,"=",l,".createStream(",34962,",",a,".buffer);","}else{",c,"=",l,".getBuffer(",a,".buffer);","}",f,'="type" in ',a,"?",i.glTypes,"[",a,".type]:",c,".dtype;",s.normalized,"=!!",a,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",s.isStream,"){",l,".destroyStream(",c,");","}"),s})}),o}function T(t,e,r,n,a){var i=_(t),l=function(t,e,r){function n(t){if(t in a){var r=a[t];t=!0;var n,o,l=0|r.x,s=0|r.y;return"width"in r?n=0|r.width:t=!1,"height"in r?o=0|r.height:t=!1,new I(!t&&e&&e.thisDep,!t&&e&&e.contextDep,!t&&e&&e.propDep,function(t,e){var a=t.shared.context,i=n;"width"in r||(i=e.def(a,".","framebufferWidth","-",l));var u=o;return"height"in r||(u=e.def(a,".","framebufferHeight","-",s)),[l,s,i,u]})}if(t in i){var u=i[t];return t=z(u,function(t,e){var r=t.invoke(e,u),n=t.shared.context,a=e.def(r,".x|0"),i=e.def(r,".y|0");return[a,i,e.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",a,")"),r=e.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",i,")")]}),e&&(t.thisDep=t.thisDep||e.thisDep,t.contextDep=t.contextDep||e.contextDep,t.propDep=t.propDep||e.propDep),t}return e?new I(e.thisDep,e.contextDep,e.propDep,function(t,e){var r=t.shared.context;return[0,0,e.def(r,".","framebufferWidth"),e.def(r,".","framebufferHeight")]}):null}var a=t.static,i=t.dynamic;if(t=n("viewport")){var o=t;t=new I(t.thisDep,t.contextDep,t.propDep,function(t,e){var r=o.append(t,e),n=t.shared.context;return e.set(n,".viewportWidth",r[2]),e.set(n,".viewportHeight",r[3]),r})}return{viewport:t,scissor_box:n("scissor.box")}}(t,i),s=A(t),u=function(t,e){var r=t.static,n=t.dynamic,a={};return nt.forEach(function(t){function e(e,o){if(t in r){var l=e(r[t]);a[i]=F(function(){return l})}else if(t in n){var s=n[t];a[i]=z(s,function(t,e){return o(t,e,t.invoke(e,s))})}}var i=v(t);switch(t){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return e(function(t){return t},function(t,e,r){return r});case"depth.func":return e(function(t){return yt[t]},function(t,e,r){return e.def(t.constants.compareFuncs,"[",r,"]")});case"depth.range":return e(function(t){return t},function(t,e,r){return[e.def("+",r,"[0]"),e=e.def("+",r,"[1]")]});case"blend.func":return e(function(t){return[mt["srcRGB"in t?t.srcRGB:t.src],mt["dstRGB"in t?t.dstRGB:t.dst],mt["srcAlpha"in t?t.srcAlpha:t.src],mt["dstAlpha"in t?t.dstAlpha:t.dst]]},function(t,e,r){function n(t,n){return e.def('"',t,n,'" in ',r,"?",r,".",t,n,":",r,".",t)}t=t.constants.blendFuncs;var a=n("src","RGB"),i=n("dst","RGB"),o=(a=e.def(t,"[",a,"]"),e.def(t,"[",n("src","Alpha"),"]"));return[a,i=e.def(t,"[",i,"]"),o,t=e.def(t,"[",n("dst","Alpha"),"]")]});case"blend.equation":return e(function(t){return"string"==typeof t?[J[t],J[t]]:"object"==typeof t?[J[t.rgb],J[t.alpha]]:void 0},function(t,e,r){var n=t.constants.blendEquations,a=e.def(),i=e.def();return(t=t.cond("typeof ",r,'==="string"')).then(a,"=",i,"=",n,"[",r,"];"),t.else(a,"=",n,"[",r,".rgb];",i,"=",n,"[",r,".alpha];"),e(t),[a,i]});case"blend.color":return e(function(t){return o(4,function(e){return+t[e]})},function(t,e,r){return o(4,function(t){return e.def("+",r,"[",t,"]")})});case"stencil.mask":return e(function(t){return 0|t},function(t,e,r){return e.def(r,"|0")});case"stencil.func":return e(function(t){return[yt[t.cmp||"keep"],t.ref||0,"mask"in t?t.mask:-1]},function(t,e,r){return[t=e.def('"cmp" in ',r,"?",t.constants.compareFuncs,"[",r,".cmp]",":",7680),e.def(r,".ref|0"),e=e.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return e(function(e){return["stencil.opBack"===t?1029:1028,xt[e.fail||"keep"],xt[e.zfail||"keep"],xt[e.zpass||"keep"]]},function(e,r,n){function a(t){return r.def('"',t,'" in ',n,"?",i,"[",n,".",t,"]:",7680)}var i=e.constants.stencilOps;return["stencil.opBack"===t?1029:1028,a("fail"),a("zfail"),a("zpass")]});case"polygonOffset.offset":return e(function(t){return[0|t.factor,0|t.units]},function(t,e,r){return[e.def(r,".factor|0"),e=e.def(r,".units|0")]});case"cull.face":return e(function(t){var e=0;return"front"===t?e=1028:"back"===t&&(e=1029),e},function(t,e,r){return e.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return e(function(t){return t},function(t,e,r){return r});case"frontFace":return e(function(t){return bt[t]},function(t,e,r){return e.def(r+'==="cw"?2304:2305')});case"colorMask":return e(function(t){return t.map(function(t){return!!t})},function(t,e,r){return o(4,function(t){return"!!"+r+"["+t+"]"})});case"sample.coverage":return e(function(t){return["value"in t?t.value:1,!!t.invert]},function(t,e,r){return[e.def('"value" in ',r,"?+",r,".value:1"),e=e.def("!!",r,".invert")]})}}),a}(t),c=w(t),f=l.viewport;return f&&(u.viewport=f),(l=l[f=v("scissor.box")])&&(u[f]=l),(i={framebuffer:i,draw:s,shader:c,state:u,dirty:l=0>1)",l],");")}function e(){r(s,".drawArraysInstancedANGLE(",[p,g,v,l],");")}d?y?t():(r("if(",d,"){"),t(),r("}else{"),e(),r("}")):e()}function o(){function t(){r(c+".drawElements("+[p,v,m,g+"<<(("+m+"-5121)>>1)"]+");")}function e(){r(c+".drawArrays("+[p,g,v]+");")}d?y?t():(r("if(",d,"){"),t(),r("}else{"),e(),r("}")):e()}var l,s,u=t.shared,c=u.gl,f=u.draw,h=n.draw,d=function(){var a=h.elements,i=e;return a?((a.contextDep&&n.contextDynamic||a.propDep)&&(i=r),a=a.append(t,i)):a=i.def(f,".","elements"),a&&i("if("+a+")"+c+".bindBuffer(34963,"+a+".buffer.buffer);"),a}(),p=a("primitive"),g=a("offset"),v=function(){var a=h.count,i=e;return a?((a.contextDep&&n.contextDynamic||a.propDep)&&(i=r),a=a.append(t,i)):a=i.def(f,".","count"),a}();if("number"==typeof v){if(0===v)return}else r("if(",v,"){"),r.exit("}");$&&(l=a("instances"),s=t.instancing);var m=d+".type",y=h.elements&&P(h.elements);$&&("number"!=typeof l||0<=l)?"string"==typeof l?(r("if(",l,">0){"),i(),r("}else if(",l,"<0){"),o(),r("}")):i():o()}function H(t,e,r,n,a){return a=(e=b()).proc("body",a),$&&(e.instancing=a.def(e.shared.extensions,".angle_instanced_arrays")),t(e,a,r,n),e.compile().body}function q(t,e,r,n){L(t,e),B(t,e,r,n.attributes,function(){return!0}),j(t,e,r,n.uniforms,function(){return!0}),U(t,e,e,r)}function G(t,e,r,n){function a(){return!0}t.batchId="a1",L(t,e),B(t,e,r,n.attributes,a),j(t,e,r,n.uniforms,a),U(t,e,e,r)}function X(t,e,r,n){function a(t){return t.contextDep&&o||t.propDep}function i(t){return!a(t)}L(t,e);var o=r.contextDep,l=e.def(),s=e.def();t.shared.props=s,t.batchId=l;var u=t.scope(),c=t.scope();e(u.entry,"for(",l,"=0;",l,"<","a1",";++",l,"){",s,"=","a0","[",l,"];",c,"}",u.exit),r.needsContext&&k(t,c,r.context),r.needsFramebuffer&&E(t,c,r.framebuffer),S(t,c,r.state,a),r.profile&&a(r.profile)&&N(t,c,r,!1,!0),n?(B(t,u,r,n.attributes,i),B(t,c,r,n.attributes,a),j(t,u,r,n.uniforms,i),j(t,c,r,n.uniforms,a),U(t,u,c,r)):(e=t.global.def("{}"),n=r.shader.progVar.append(t,c),s=c.def(n,".id"),u=c.def(e,"[",s,"]"),c(t.shared.gl,".useProgram(",n,".program);","if(!",u,"){",u,"=",e,"[",s,"]=",t.link(function(e){return H(G,t,r,e,2)}),"(",n,");}",u,".call(this,a0[",l,"],",l,");"))}function W(t,r){function n(e){var n=r.shader[e];n&&a.set(i.shader,"."+e,n.append(t,a))}var a=t.proc("scope",3);t.batchId="a2";var i=t.shared,o=i.current;k(t,a,r.context),r.framebuffer&&r.framebuffer.append(t,a),D(Object.keys(r.state)).forEach(function(e){var n=r.state[e].append(t,a);m(n)?n.forEach(function(r,n){a.set(t.next[e],"["+n+"]",r)}):a.set(i.next,"."+e,n)}),N(t,a,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(e){var n=r.draw[e];n&&a.set(i.draw,"."+e,""+n.append(t,a))}),Object.keys(r.uniforms).forEach(function(n){a.set(i.uniforms,"["+e.id(n)+"]",r.uniforms[n].append(t,a))}),Object.keys(r.attributes).forEach(function(e){var n=r.attributes[e].append(t,a),i=t.scopeAttrib(e);Object.keys(new Z).forEach(function(t){a.set(i,"."+t,n[t])})}),n("vert"),n("frag"),0=--this.refCount&&o(this)},a.profile&&(n.getTotalRenderbufferSize=function(){var t=0;return Object.keys(c).forEach(function(e){t+=c[e].stats.size}),t}),{create:function(e,r){function o(e,r){var n=0,i=0,c=32854;if("object"==typeof e&&e?("shape"in e?(n=0|(i=e.shape)[0],i=0|i[1]):("radius"in e&&(n=i=0|e.radius),"width"in e&&(n=0|e.width),"height"in e&&(i=0|e.height)),"format"in e&&(c=l[e.format])):"number"==typeof e?(n=0|e,i="number"==typeof r?0|r:n):e||(n=i=1),n!==u.width||i!==u.height||c!==u.format)return o.width=u.width=n,o.height=u.height=i,u.format=c,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,c,n,i),a.profile&&(u.stats.size=ft[u.format]*u.width*u.height),o.format=s[u.format],o}var u=new i(t.createRenderbuffer());return c[u.id]=u,n.renderbufferCount++,o(e,r),o.resize=function(e,r){var n=0|e,i=0|r||n;return n===u.width&&i===u.height?o:(o.width=u.width=n,o.height=u.height=i,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,u.format,n,i),a.profile&&(u.stats.size=ft[u.format]*u.width*u.height),o)},o._reglType="renderbuffer",o._renderbuffer=u,a.profile&&(o.stats=u.stats),o.destroy=function(){u.decRef()},o},clear:function(){X(c).forEach(o)},restore:function(){X(c).forEach(function(e){e.renderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,e.renderbuffer),t.renderbufferStorage(36161,e.format,e.width,e.height)}),t.bindRenderbuffer(36161,null)}}},dt=[];dt[6408]=4;var pt=[];pt[5121]=1,pt[5126]=4,pt[36193]=2;var gt=["x","y","z","w"],vt="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),mt={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},yt={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},xt={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},bt={cw:2304,ccw:2305},_t=new I(!1,!1,!1,function(){});return function(t){function e(){if(0===Y.length)w&&w.update(),$=null;else{$=H.next(e),f();for(var t=Y.length-1;0<=t;--t){var r=Y[t];r&&r(O,null,0)}v.flush(),w&&w.update()}}function r(){!$&&0=Y.length&&n()}}}}function c(){var t=X.viewport,e=X.scissor_box;t[0]=t[1]=e[0]=e[1]=0,O.viewportWidth=O.framebufferWidth=O.drawingBufferWidth=t[2]=e[2]=v.drawingBufferWidth,O.viewportHeight=O.framebufferHeight=O.drawingBufferHeight=t[3]=e[3]=v.drawingBufferHeight}function f(){O.tick+=1,O.time=d(),c(),G.procs.poll()}function h(){c(),G.procs.refresh(),w&&w.update()}function d(){return(q()-A)/1e3}if(!(t=a(t)))return null;var v=t.gl,m=v.getContextAttributes();v.isContextLost();var y=function(t,e){function r(e){var r;e=e.toLowerCase();try{r=n[e]=t.getExtension(e)}catch(t){}return!!r}for(var n={},a=0;ae;++e)K(j({framebuffer:t.framebuffer.faces[e]},t),s);else K(t,s);else s(0,t)},prop:V.define.bind(null,1),context:V.define.bind(null,2),this:V.define.bind(null,3),draw:l({}),buffer:function(t){return D.create(t,34962,!1,!1)},elements:function(t){return I.create(t,!1)},texture:F.create2D,cube:F.createCube,renderbuffer:z.create,framebuffer:U.create,framebufferCube:U.createCube,attributes:m,frame:u,on:function(t,e){var r;switch(t){case"frame":return u(e);case"lost":r=Z;break;case"restore":r=J;break;case"destroy":r=Q}return r.push(e),{cancel:function(){for(var t=0;t>>8*e)%256/255}function KM(t,e){var r={};return[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].map(function(r){return function(t,e,r){var n,a,i,o=[];for(a=0;a=qM-4?$M(o,qM-2-l):.5);return i}(m,v,g,x),M=KM(m,A),T=e.regl,k=T.texture({shape:[256,1],format:"rgba",type:"uint8",mag:"nearest",min:"nearest",data:function(t,e,r){for(var n=[],a=0;a<256;a++){var i=t(a/255);n.push((e?WM:i).concat(r))}return n}(f,h,Math.round(255*(h?b:1)))}),E=T({profile:!1,blend:{enable:y,func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:1,dstAlpha:1},equation:{rgb:"add",alpha:"add"},color:[0,0,0,0]},depth:{enable:!y,mask:!0,func:"less",range:[0,1]},cull:{enable:!0,face:"back"},scissor:{enable:!0,box:{x:T.prop("scissorX"),y:T.prop("scissorY"),width:T.prop("scissorWidth"),height:T.prop("scissorHeight")}},viewport:{x:T.prop("viewportX"),y:T.prop("viewportY"),width:T.prop("viewportWidth"),height:T.prop("viewportHeight")},dither:!1,vert:d?UM:jM,frag:VM,primitive:"lines",lineWidth:1,attributes:M,uniforms:{resolution:T.prop("resolution"),viewBoxPosition:T.prop("viewBoxPosition"),viewBoxSize:T.prop("viewBoxSize"),dim1A:T.prop("dim1A"),dim2A:T.prop("dim2A"),dim1B:T.prop("dim1B"),dim2B:T.prop("dim2B"),dim1C:T.prop("dim1C"),dim2C:T.prop("dim2C"),dim1D:T.prop("dim1D"),dim2D:T.prop("dim2D"),loA:T.prop("loA"),hiA:T.prop("hiA"),loB:T.prop("loB"),hiB:T.prop("hiB"),loC:T.prop("loC"),hiC:T.prop("hiC"),loD:T.prop("loD"),hiD:T.prop("hiD"),palette:k,colorClamp:T.prop("colorClamp"),scatter:T.prop("scatter")},offset:T.prop("offset"),count:T.prop("count")}),C=[0,1];var S=[];function L(t,e,r,a,o,u,c,f,d,p,v){var m,y,x,b,A=[t,e],M=BM.verticalPadding/u,T=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})}),k=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(m=0;m<2;m++)for(b=A[m],y=0;y<4;y++)for(x=0;x<16;x++){var E=x+16*y;T[m][y][x]=x+16*y===b?1:0,k[m][y][x]=(!h&&tT(x,16*y,w)?g[0===E?0:1+(E-1)%(g.length-1)].filter[m]:m)+(2*m-1)*M}return{key:c,resolution:[l,s],viewBoxPosition:[r+_,a],viewBoxSize:[o,u],i:t,ii:e,dim1A:T[0][0],dim1B:T[0][1],dim1C:T[0][2],dim1D:T[0][3],dim2A:T[1][0],dim2B:T[1][1],dim2C:T[1][2],dim2D:T[1][3],loA:k[0][0],loB:k[0][1],loC:k[0][2],loD:k[0][3],hiA:k[1][0],hiB:k[1][1],hiC:k[1][2],hiD:k[1][3],colorClamp:C,scatter:f||0,scissorX:(d===p?0:r+_)+(n.pad.l-_)+n.layoutWidth*i.x[0],scissorWidth:(d===v?l-r+_:o+.5)+(d===p?r+_:0),scissorY:a+n.pad.b+n.layoutHeight*i.y[0],scissorHeight:u,viewportX:n.pad.l-_+n.layoutWidth*i.x[0],viewportY:n.pad.b+n.layoutHeight*i.y[0],viewportWidth:l,viewportHeight:s}}return{setColorDomain:function(t){C[0]=t[0],C[1]=t[1]},render:function(t,e,n){var a,i,u,c=1/0,f=-1/0;for(a=0;af&&(f=t[a].dim2.canvasX,u=a),t[a].dim1.canvasXa)return i;a=o,i=n[r]}return n[n.length-1]}function sT(e){return t.scale.linear().domain(oT(e))}function uT(e,r,n){var a=aT(r),i=a.trace,o=a.lineColor,l=a.cscale,s=i.line,u=i.domain,c=i.dimensions,f=e.width,h=i.labelfont,d=i.tickfont,p=i.rangefont,g=ne.extendDeep({},s,{color:o.map(sT({values:o,range:[s.cmin,s.cmax],_length:i._commonLength})),blockLineCount:BM.blockLineCount,canvasOverdrag:BM.overdrag*BM.canvasPixelRatio}),v=Math.floor(f*(u.x[1]-u.x[0])),m=Math.floor(e.height*(u.y[1]-u.y[0])),y=e.margin||{l:80,r:80,t:100,b:80},x=v,b=m;return{key:n,colCount:c.filter(iT).length,dimensions:c,tickDistance:BM.tickDistance,unitToColor:function(e){var r=e.map(function(t){return t[0]}),n=e.map(function(t){return t[1]}).map(function(e){return t.rgb(e)}),a="rgb".split("").map(function(e){return t.scale.linear().clamp(!0).domain(r).range(n.map((a=e,function(t){return t[a]})));var a});return function(t){return a.map(function(e){return e(t)})}}(l),lines:g,labelFont:h,tickFont:d,rangeFont:p,layoutWidth:f,layoutHeight:e.height,domain:u,translateX:u.x[0]*f,translateY:e.height-u.y[1]*e.height,pad:y,canvasWidth:x*BM.canvasPixelRatio+2*g.canvasOverdrag,canvasHeight:b*BM.canvasPixelRatio,width:x,height:b,canvasPixelRatio:BM.canvasPixelRatio}}function cT(e){var r=e.width,n=e.height,a=e.dimensions,i=e.canvasPixelRatio,o=function(t){return r*t/Math.max(1,e.colCount-1)},l=BM.verticalPadding/(n*i),s=1-2*l,u=function(t){return l+s*t},c={key:e.key,xScale:o,model:e},f={};return c.dimensions=a.filter(iT).map(function(r,a){var l=sT(r),s=f[r.label];f[r.label]=(s||0)+1;var h=r.label+(s?"__"+s:""),d=r.values;return d.length>r._length&&(d=d.slice(0,r._length)),{key:h,label:r.label,tickFormat:r.tickformat,tickvals:r.tickvals,ticktext:r.ticktext,ordinal:!!r.tickvals,scatter:BM.scatter||r.scatter,xIndex:a,crossfilterDimensionIndex:a,visibleIndex:r._index,height:n,values:d,paddedUnitValues:d.map(l).map(u),xScale:o,x:o(a),canvasX:o(a)*i,unitScale:function(e,r){return t.scale.linear().range([e-r,r])}(n,BM.verticalPadding),domainScale:function(e,r,n){var a=oT(n),i=n.ticktext;return n.tickvals?t.scale.ordinal().domain(n.tickvals.map(function(t,e){return function(r,n){if(e){var a=e[n];return null===a||void 0===a?t(r):a}return t(r)}}(t.format(n.tickformat),i))).range(n.tickvals.map(function(t){return(t-a[0])/(a[1]-a[0])}).map(function(t){return e-r+t*(r-(e-r))})):t.scale.linear().domain(a).range([e-r,r])}(n,BM.verticalPadding,r),ordinalScale:function(e){var r=oT(e);return e.tickvals&&t.scale.ordinal().domain(e.tickvals).range(e.tickvals.map(function(t){return(t-r[0])/(r[1]-r[0])}))}(r),domainToUnitScale:l,filter:r.constraintrange?r.constraintrange.map(l):[0,1],parent:c,model:e}}),c}function fT(t){t.classed(BM.cn.axisExtentText,!0).attr("text-anchor","middle").style("cursor","default").style("user-select","none")}var hT={};(function(e){"use strict";hT=function(r,n){var a=r._fullLayout,i=a._toppaper,o=(a._paperdiv,a._glcontainer);a._glcanvas.each(function(t){t.regl||(t.regl=DM({canvas:this,attributes:{antialias:!t.pick,preserveDrawingBuffer:!0},pixelRatio:r._context.plotGlPixelRatio||e.devicePixelRatio}))});var l={},s={},u=a._size;n.forEach(function(t,e){l[e]=r.data[e].dimensions,s[e]=r.data[e].dimensions.slice()});!function(e,r,n,a,i,o){var l=!1,s=!0;var u=a.filter(function(t){return aT(t).trace.visible}).map(uT.bind(0,i)).map(cT);n.each(function(t,e){return ne.extendFlat(t,u[e])});var c=n.selectAll(".gl-canvas").each(function(t){t.viewModel=u[0],t.model=t.viewModel?t.viewModel.model:null}),f={renderers:[],dimensions:[]},h=null;c.filter(function(t){return t.pick}).style("pointer-events","auto").on("mousemove",function(e){if(s&&e.lineLayer&&o&&o.hover){var r=t.event,n=this.width,a=this.height,i=t.mouse(this),l=i[0],u=i[1];if(l<0||u<0||l>=n||u>=a)return;var c=e.lineLayer.readPixel(l,a-1-u),f=0!==c[3],d=f?c[2]+256*(c[1]+256*c[0]):null,p={x:l,y:u,clientX:r.clientX,clientY:r.clientY,dataIndex:e.model.key,curveNumber:d};d!==h&&(f?o.hover(p):o.unhover&&o.unhover(p),h=d)}}),c.style("opacity",function(t){return t.pick?.01:1}),r.style("background","rgba(255, 255, 255, 0)");var d=r.selectAll("."+BM.cn.parcoords).data(u,rT);d.exit().remove(),d.enter().append("g").classed(BM.cn.parcoords,!0).attr("overflow","visible").style("box-sizing","content-box").style("position","absolute").style("left",0).style("overflow","visible").style("shape-rendering","crispEdges").style("pointer-events","none").call(function(t){var e=t.selectAll("defs").data(nT,rT);e.enter().append("defs");var r=e.selectAll("#"+BM.id.filterBarPattern).data(nT,rT);r.enter().append("pattern").attr("id",BM.id.filterBarPattern).attr("patternUnits","userSpaceOnUse"),r.attr("x",-BM.bar.width).attr("width",BM.bar.capturewidth).attr("height",function(t){return t.model.height});var n=r.selectAll("rect").data(nT,rT);n.enter().append("rect").attr("shape-rendering","crispEdges"),n.attr("height",function(t){return t.model.height}).attr("width",BM.bar.width).attr("x",BM.bar.width/2).attr("fill",BM.bar.fillcolor).attr("fill-opacity",BM.bar.fillopacity).attr("stroke",BM.bar.strokecolor).attr("stroke-opacity",BM.bar.strokeopacity).attr("stroke-width",BM.bar.strokewidth)}),d.attr("width",function(t){return t.model.width+t.model.pad.l+t.model.pad.r}).attr("height",function(t){return t.model.height+t.model.pad.t+t.model.pad.b}).attr("transform",function(t){return"translate("+t.model.translateX+","+t.model.translateY+")"});var p=d.selectAll("."+BM.cn.parcoordsControlView).data(nT,rT);p.enter().append("g").classed(BM.cn.parcoordsControlView,!0).style("box-sizing","content-box"),p.attr("transform",function(t){return"translate("+t.model.pad.l+","+t.model.pad.t+")"});var g=p.selectAll("."+BM.cn.yAxis).data(function(t){return t.dimensions},rT);function v(t){return t.dimensions.some(function(t){return 0!==t.filter[0]||1!==t.filter[1]})}function m(t,e){return(BM.scatter?function(t,e){for(var r=e.panels||(e.panels=[]),n=t.each(function(t){return t})[e.key].map(function(t){return t.__data__}),a=n.length-1,i=a,o=0;oline").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.25).attr("stroke-width","1px"),x.selectAll("text").style("text-shadow","1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff").style("cursor","default").style("user-select","none");var b=y.selectAll("."+BM.cn.axisHeading).data(nT,rT);b.enter().append("g").classed(BM.cn.axisHeading,!0);var _=b.selectAll("."+BM.cn.axisTitle).data(nT,rT);_.enter().append("text").classed(BM.cn.axisTitle,!0).attr("text-anchor","middle").style("cursor","ew-resize").style("user-select","none").style("pointer-events","auto"),_.attr("transform","translate(0,"+-BM.axisTitleOffset+")").text(function(t){return t.label}).each(function(t){Zr.font(_,t.model.labelFont)});var w=y.selectAll("."+BM.cn.axisExtent).data(nT,rT);w.enter().append("g").classed(BM.cn.axisExtent,!0);var A=w.selectAll("."+BM.cn.axisExtentTop).data(nT,rT);A.enter().append("g").classed(BM.cn.axisExtentTop,!0),A.attr("transform","translate(0,"+-BM.axisExtentOffset+")");var M=A.selectAll("."+BM.cn.axisExtentTopText).data(nT,rT);function T(e){return e.ordinal?function(){return""}:t.format(e.tickFormat)}M.enter().append("text").classed(BM.cn.axisExtentTopText,!0).call(fT),M.text(function(t){return T(t)(t.domainScale.domain().slice(-1)[0])}).each(function(t){Zr.font(M,t.model.rangeFont)});var k=w.selectAll("."+BM.cn.axisExtentBottom).data(nT,rT);k.enter().append("g").classed(BM.cn.axisExtentBottom,!0),k.attr("transform",function(t){return"translate(0,"+(t.model.height+BM.axisExtentOffset)+")"});var E=k.selectAll("."+BM.cn.axisExtentBottomText).data(nT,rT);E.enter().append("text").classed(BM.cn.axisExtentBottomText,!0).attr("dy","0.75em").call(fT),E.text(function(t){return T(t)(t.domainScale.domain()[0])}).each(function(t){Zr.font(E,t.model.rangeFont)});var C=y.selectAll("."+BM.cn.axisBrush).data(nT,rT),S=C.enter().append("g").classed(BM.cn.axisBrush,!0);C.each(function(e){e.brush||(e.brush=t.svg.brush().y(e.unitScale).on("brushstart",R).on("brush",D).on("brushend",I),0===e.filter[0]&&1===e.filter[1]||e.brush.extent(e.filter),t.select(this).call(e.brush))}),S.selectAll("rect").attr("x",-BM.bar.capturewidth/2).attr("width",BM.bar.capturewidth),S.selectAll("rect.extent").attr("fill","url(#"+BM.id.filterBarPattern+")").style("cursor","ns-resize").filter(function(t){return 0===t.filter[0]&&1===t.filter[1]}).attr("y",-100),S.selectAll(".resize rect").attr("height",BM.bar.handleheight).attr("opacity",0).style("visibility","visible"),S.selectAll(".resize.n rect").style("cursor","n-resize").attr("y",BM.bar.handleoverlap-BM.bar.handleheight),S.selectAll(".resize.s rect").style("cursor","s-resize").attr("y",BM.bar.handleoverlap);var L=!1,O=!1;function R(){L=!0,l=!0}function D(e){s=!1;var r=e.parent,n=e.brush.extent(),a=r.dimensions,i=a[e.xIndex].filter,o=L&&n[0]===n[1];o&&(e.brush.clear(),t.select(this).select("rect.extent").attr("y",-100));var l=o?[0,1]:n.slice();if(l[0]!==i[0]||l[1]!==i[1]){a[e.xIndex].filter=l,r.focusLayer&&r.focusLayer.render(r.panels,!0);var u=v(r);!O&&u?(r.contextLayer&&r.contextLayer.render(r.panels,!0),O=!0):O&&!u&&(r.contextLayer&&r.contextLayer.render(r.panels,!0,!0),O=!1)}L=!1}function I(e){var r=e.parent,n=e.brush.extent(),a=n[0]===n[1],i=r.dimensions[e.xIndex].filter;if(!a&&e.ordinal&&(i[0]=lT(e.ordinalScale,i[0]),i[1]=lT(e.ordinalScale,i[1]),i[0]===i[1]&&(i[0]=Math.max(0,i[0]-.05),i[1]=Math.min(1,i[1]+.05)),t.select(this).transition().duration(150).call(e.brush.extent(i)),r.focusLayer.render(r.panels,!0)),r.pickLayer&&r.pickLayer.render(r.panels,!0),s=!0,l="ending",o&&o.filterChanged){var u=e.domainToUnitScale.invert,c=i.map(u);o.filterChanged(r.key,e.visibleIndex,c)}}}(0,i,o,n,{width:u.w,height:u.h,margin:{t:u.t,r:u.r,b:u.b,l:u.l}},{filterChanged:function(t,e,n){var a=s[t][e],i=a.constraintrange;i&&2===i.length||(i=a.constraintrange=[]),i[0]=n[0],i[1]=n[1],r.emit("plotly_restyle")},hover:function(t){r.emit("plotly_hover",t)},unhover:function(t){r.emit("plotly_unhover",t)},axesMoved:function(t,e){function n(t){return!("visible"in t)||t.visible}function a(t,e,r){var n=e.indexOf(r),a=t.indexOf(n);return-1===a&&(a+=e.length),a}var i=function(t){return function(r,n){return a(e,t,r)-a(e,t,n)}}(s[t].filter(n));l[t].sort(i),s[t].filter(function(t){return!n(t)}).sort(function(e){return s[t].indexOf(e)}).forEach(function(e){l[t].splice(l[t].indexOf(e),1),l[t].splice(s[t].indexOf(e),0,e)}),r.emit("plotly_restyle")}})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var dT={},pT=Ja.getModuleCalcData;dT.name="parcoords",dT.plot=function(t){var e=pT(t.calcdata,"parcoords");e.length&&hT(t,e)},dT.clean=function(t,e,r,n){var a=n._has&&n._has("parcoords"),i=e._has&&e._has("parcoords");a&&!i&&(n._paperdiv.selectAll(".parcoords").remove(),n._glimages.selectAll("*").remove())},dT.toSVG=function(e){var r=e._fullLayout._glimages,n=t.select(e).selectAll(".svg-container");n.filter(function(t,e){return e===n.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");r.append("svg:image").attr({xmlns:Te.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})}),window.setTimeout(function(){t.selectAll("#filterBarPattern").attr("id","filterBarPattern")},60)};var gT=zM;var vT=BM.maxDimensionCount,mT=By.defaults;var yT={};yT.attributes=RM,yT.supplyDefaults=function(t,e,r,n){function a(r,n){return ne.coerce(t,e,RM,r,n)}var i=function(t,e){var r,n,a,i=t.dimensions||[],o=e.dimensions=[],l=1/0;function s(t,e){return ne.coerce(r,n,RM.dimensions,t,e)}for(i.length>vT&&(ne.log("parcoords traces support up to "+vT+" dimensions at the moment"),i.splice(vT)),a=0;a 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]),_T.pickVertex=Fo(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]),_T.pickFragment=Fo(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]);var wT=function(t,e){var r=t.gl,n=Po(r),a=Po(r),i=Wl(r,_T.pointVertex,_T.pointFragment),o=Wl(r,_T.pickVertex,_T.pickFragment),l=new AT(t,n,a,i,o);return l.update(e),t.addObject(l),l};function AT(t,e,r,n,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.shader=n,this.pickShader=a,this.sizeMin=.5,this.sizeMinCap=2,this.sizeMax=20,this.areaRatio=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.blend=!1,this.pickOffset=0,this.points=null}var MT=AT.prototype;MT.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.plot.removeObject(this)},MT.update=function(t){var e;function r(e,r){return e in t?t[e]:r}t=t||{},this.sizeMin=r("sizeMin",.5),this.sizeMax=r("sizeMax",20),this.color=r("color",[1,0,0,1]).slice(),this.areaRatio=r("areaRatio",1),this.borderColor=r("borderColor",[0,0,0,1]).slice(),this.blend=r("blend",!1);var n=t.positions.length>>>1,a=t.positions instanceof Float32Array,i=t.idToIndex instanceof Int32Array&&t.idToIndex.length>=n,o=t.positions,l=a?o:So.mallocFloat32(o.length),s=i?t.idToIndex:So.mallocInt32(n);if(a||l.set(o),!i)for(l.set(o),e=0;e>>1;for(r=0;r=e[0]&&i<=e[2]&&o>=e[1]&&o<=e[3]&&n++}return n}(this.points,o),c=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(u,.33333)));t[0]=2/l,t[4]=2/s,t[6]=-2*o[0]/l-1,t[7]=-2*o[1]/s-1,this.offsetBuffer.bind(),a.bind(),a.attributes.position.pointer(),a.uniforms.matrix=t,a.uniforms.color=this.color,a.uniforms.borderColor=this.borderColor,a.uniforms.pointCloud=c<5,a.uniforms.pointSize=c,a.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio))),n&&(e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,this.pickBuffer.bind(),a.attributes.pickId.pointer(i.UNSIGNED_BYTE),a.uniforms.pickOffset=e,this.pickOffset=r);var f=i.getParameter(i.BLEND),h=i.getParameter(i.DITHER);return f&&!this.blend&&i.disable(i.BLEND),h&&i.disable(i.DITHER),i.drawArrays(i.POINTS,0,this.pointCount),f&&!this.blend&&i.enable(i.BLEND),h&&i.enable(i.DITHER),r+this.pointCount}}(),MT.draw=MT.unifiedDraw,MT.drawPick=MT.unifiedDraw,MT.pick=function(t,e,r){var n=this.pickOffset,a=this.pointCount;if(r=n+a)return null;var i=r-n,o=this.points;return{object:this,pointId:i,dataCoord:[o[2*i],o[2*i+1]]}};var TT=fa;function kT(t,e){this.scene=t,this.uid=e,this.type="pointcloud",this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=new Int32Array(0),this.bounds=[0,0,0,0],this.pointcloudOptions={positions:new Float32Array(0),idToIndex:this.idToIndex,sizemin:.5,sizemax:12,color:[0,0,0,1],areaRatio:1,borderColor:[0,0,0,1]},this.pointcloud=wT(t.glplot,this.pointcloudOptions),this.pointcloud._trace=this}var ET=kT.prototype;ET.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:this.pickXYData?[this.pickXYData[2*e],this.pickXYData[2*e+1]]:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:this.color,name:this.name,pointIndex:e,hoverinfo:this.hoverinfo}},ET.update=function(t){this.index=t.index,this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-1/0,-1/0],this.updateFast(t),this.color=QA(t,{})},ET.updateFast=function(t){var e,r,n,a,i,o,l=this.xData=this.pickXData=t.x,s=this.yData=this.pickYData=t.y,u=this.pickXYData=t.xy,c=t.xbounds&&t.ybounds,f=t.indices,h=this.bounds;if(u){if(n=u,e=u.length>>>1,c)h[0]=t.xbounds[0],h[2]=t.xbounds[1],h[1]=t.ybounds[0],h[3]=t.ybounds[1];else for(o=0;oh[2]&&(h[2]=a),ih[3]&&(h[3]=i);if(f)r=f;else for(r=new Int32Array(e),o=0;oh[2]&&(h[2]=a),ih[3]&&(h[3]=i);this.idToIndex=r,this.pointcloudOptions.idToIndex=r,this.pointcloudOptions.positions=n;var d=av(t.marker.color),p=av(t.marker.border.color),g=t.opacity*t.marker.opacity;d[3]*=g,this.pointcloudOptions.color=d;var v=t.marker.blend;if(null===v){v=l.length<100||s.length<100}this.pointcloudOptions.blend=v,p[3]*=g,this.pointcloudOptions.borderColor=p;var m=t.marker.sizemin,y=Math.max(t.marker.sizemax,t.marker.sizemin);this.pointcloudOptions.sizeMin=m,this.pointcloudOptions.sizeMax=y,this.pointcloudOptions.areaRatio=t.marker.border.arearatio,this.pointcloud.update(this.pointcloudOptions),this.expandAxesFast(h,y/2)},ET.expandAxesFast=function(t,e){var r=e||.5;TT(this.scene.xaxis,[t[0],t[2]],{ppad:r}),TT(this.scene.yaxis,[t[1],t[3]],{ppad:r})},ET.dispose=function(){this.pointcloud.dispose()};var CT=function(t,e){var r=new kT(t,e.uid);return r.update(e),r},ST={};ST.attributes=bT,ST.supplyDefaults=function(t,e,r){function n(r,n){return ne.coerce(t,e,bT,r,n)}n("x"),n("y"),n("xbounds"),n("ybounds"),t.xy&&t.xy instanceof Float32Array&&(e.xy=t.xy),t.indices&&t.indices instanceof Int32Array&&(e.indices=t.indices),n("text"),n("marker.color",r),n("marker.opacity"),n("marker.blend"),n("marker.sizemin"),n("marker.sizemax"),n("marker.border.color",r),n("marker.border.arearatio")},ST.calc=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return LA(r,e),RA(e),r},ST.plot=CT,ST.moduleType="trace",ST.name="pointcloud",ST.basePlotModule=xv,ST.categories=["gl","gl2d","showLegend"],ST.meta={};var LT=ST,OT=function(t,e){var r="number"==typeof t,n="number"==typeof e;r&&!n?(e=t,t=0):r||n||(t=0,e=0);var a=(e|=0)-(t|=0);if(a<0)throw new Error("array length must be positive");for(var i=new Array(a),o=0,l=t;oa;){if(i-a>600){var l=i-a+1,s=n-a+1,u=Math.log(l),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(l-c)/l)*(s-l/2<0?-1:1),h=Math.max(a,Math.floor(n-s*c/l+f)),d=Math.min(i,Math.floor(n+(l-s)*c/l+f));t(e,r,n,h,d,o)}var p=r[2*n+o],g=a,v=i;for(PT(e,r,a,n),r[2*i+o]>p&&PT(e,r,a,i);gp;)v--}r[2*a+o]===p?PT(e,r,a,v):PT(e,r,++v,i),v<=n&&(a=v+1),n<=v&&(i=v-1)}}(e,r,l,a,i,o%2);t(e,r,n,a,l-1,o+1);t(e,r,n,l+1,i,o+1)}(this.ids,this.coords,this.nodeSize,0,this.ids.length-1,0)}function IT(t,e,r,n){var a=t-r,i=e-n;return a*a+i*i}function PT(t,e,r,n){FT(t,r,n),FT(e,2*r,2*n),FT(e,2*r+1,2*n+1)}function FT(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}DT.prototype.range=function(t,e,r,n){for(var a,i,o=this.ids,l=this.coords,s=this.nodeSize,u=[0,o.length-1,0],c=[];u.length;){var f=u.pop(),h=u.pop(),d=u.pop();if(h-d<=s)for(var p=d;p<=h;p++)a=l[2*p],i=l[2*p+1],a>=t&&a<=r&&i>=e&&i<=n&&c.push(o[p]);else{var g=Math.floor((d+h)/2);a=l[2*g],i=l[2*g+1],a>=t&&a<=r&&i>=e&&i<=n&&c.push(o[g]);var v=(f+1)%2;(0===f?t<=a:e<=i)&&(u.push(d),u.push(g-1),u.push(v)),(0===f?r>=a:n>=i)&&(u.push(g+1),u.push(h),u.push(v))}}return c},DT.prototype.within=function(t,e,r){for(var n=this.ids,a=this.coords,i=this.nodeSize,o=[0,n.length-1,0],l=[],s=r*r;o.length;){var u=o.pop(),c=o.pop(),f=o.pop();if(c-f<=i)for(var h=f;h<=c;h++)IT(a[2*h],a[2*h+1],t,e)<=s&&l.push(n[h]);else{var d=Math.floor((f+c)/2),p=a[2*d],g=a[2*d+1];IT(p,g,t,e)<=s&&l.push(n[d]);var v=(u+1)%2;(0===u?t-r<=p:e-r<=g)&&(o.push(f),o.push(d-1),o.push(v)),(0===u?t+r>=p:e+r>=g)&&(o.push(d+1),o.push(c),o.push(v))}}return l};var zT=function(t,e){if(!t||null==t.length)throw Error("Argument should be an array");e=null==e?1:Math.floor(e);for(var r=Array(2*e),n=0;na&&(a=t[o]),t[o]1&&(t.scaleRatio=[t.scale[0]*t.viewport.width,t.scale[1]*t.viewport.height],r(t),t.after&&t.after(t))}function p(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0,r=0;if(c=t.map(function(t,n){var a=c[n];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=HT(t,{color:"color colors fill",capSize:"capSize cap capsize cap-size",lineWidth:"lineWidth line-width width line thickness",opacity:"opacity alpha",range:"range dataBox",viewport:"viewport viewBox",errors:"errors error",positions:"positions position data points"}),a||(c[n]=a={id:n,scale:null,translate:null,scaleFract:null,translateFract:null,draw:!0},t=VT({},u,t)),YT(a,t,[{lineWidth:function(t){return.5*+t},capSize:function(t){return.5*+t},opacity:parseFloat,errors:function(t){return t=NT(t),r+=t.length,t},positions:function(t,r){return t=NT(t,"float64"),r.count=Math.floor(t.length/2),r.bounds=zT(t,2),r.offset=e,e+=r.count,t}},{color:function(t,e){var r=e.count;if(t||(t="transparent"),!Array.isArray(t)||"number"==typeof t[0]){var n=t;t=Array(r);for(var a=0;a80*r){n=i=t[0],a=o=t[1];for(var p=r;pi&&(i=l),s>o&&(o=s);u=0!==(u=Math.max(i-n,o-a))?1/u:0}return ak(h,d,r,n,a,u),d}function rk(t,e,r,n,a){var i,o;if(a===Ak(t,e,r,n)>0)for(i=e;i=e;i-=n)o=bk(i,t[i],t[i+1],o);return o&&vk(o,o.next)&&(_k(o),o=o.next),o}function nk(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!vk(n,n.next)&&0!==gk(n.prev,n,n.next))n=n.next;else{if(_k(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function ak(t,e,r,n,a,i,o){if(t){!o&&i&&function(t,e,r,n){var a=t;do{null===a.z&&(a.z=fk(a.x,a.y,e,r,n)),a.prevZ=a.prev,a.nextZ=a.next,a=a.next}while(a!==t);a.prevZ.nextZ=null,a.prevZ=null,function(t){var e,r,n,a,i,o,l,s,u=1;do{for(r=t,t=null,i=null,o=0;r;){for(o++,n=r,l=0,e=0;e0||s>0&&n;)0!==l&&(0===s||!n||r.z<=n.z)?(a=r,r=r.nextZ,l--):(a=n,n=n.nextZ,s--),i?i.nextZ=a:t=a,a.prevZ=i,i=a;r=n}i.nextZ=null,u*=2}while(o>1)}(a)}(t,n,a,i);for(var l,s,u=t;t.prev!==t.next;)if(l=t.prev,s=t.next,i?ok(t,n,a,i):ik(t))e.push(l.i/r),e.push(t.i/r),e.push(s.i/r),_k(t),t=s.next,u=s.next;else if((t=s)===u){o?1===o?ak(t=lk(t,e,r),e,r,n,a,i,2):2===o&&sk(t,e,r,n,a,i):ak(nk(t),e,r,n,a,i,1);break}}}function ik(t){var e=t.prev,r=t,n=t.next;if(gk(e,r,n)>=0)return!1;for(var a=t.next.next;a!==t.prev;){if(dk(e.x,e.y,r.x,r.y,n.x,n.y,a.x,a.y)&&gk(a.prev,a,a.next)>=0)return!1;a=a.next}return!0}function ok(t,e,r,n){var a=t.prev,i=t,o=t.next;if(gk(a,i,o)>=0)return!1;for(var l=a.xi.x?a.x>o.x?a.x:o.x:i.x>o.x?i.x:o.x,c=a.y>i.y?a.y>o.y?a.y:o.y:i.y>o.y?i.y:o.y,f=fk(l,s,e,r,n),h=fk(u,c,e,r,n),d=t.prevZ,p=t.nextZ;d&&d.z>=f&&p&&p.z<=h;){if(d!==t.prev&&d!==t.next&&dk(a.x,a.y,i.x,i.y,o.x,o.y,d.x,d.y)&&gk(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==t.prev&&p!==t.next&&dk(a.x,a.y,i.x,i.y,o.x,o.y,p.x,p.y)&&gk(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=f;){if(d!==t.prev&&d!==t.next&&dk(a.x,a.y,i.x,i.y,o.x,o.y,d.x,d.y)&&gk(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=h;){if(p!==t.prev&&p!==t.next&&dk(a.x,a.y,i.x,i.y,o.x,o.y,p.x,p.y)&&gk(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function lk(t,e,r){var n=t;do{var a=n.prev,i=n.next.next;!vk(a,i)&&mk(a,n,n.next,i)&&yk(a,i)&&yk(i,a)&&(e.push(a.i/r),e.push(n.i/r),e.push(i.i/r),_k(n),_k(n.next),n=t=i),n=n.next}while(n!==t);return n}function sk(t,e,r,n,a,i){var o=t;do{for(var l=o.next.next;l!==o.prev;){if(o.i!==l.i&&pk(o,l)){var s=xk(o,l);return o=nk(o,o.next),s=nk(s,s.next),ak(o,e,r,n,a,i),void ak(s,e,r,n,a,i)}l=l.next}o=o.next}while(o!==t)}function uk(t,e){return t.x-e.x}function ck(t,e){if(e=function(t,e){var r,n=e,a=t.x,i=t.y,o=-1/0;do{if(i<=n.y&&i>=n.next.y&&n.next.y!==n.y){var l=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(l<=a&&l>o){if(o=l,l===a){if(i===n.y)return n;if(i===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&a!==n.x&&dk(ir.x)&&yk(n,t)&&(r=n,h=s),n=n.next;return r}(t,e)){var r=xk(e,t);nk(r,r.next)}}function fk(t,e,r,n,a){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*a)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*a)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function hk(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-l)-(r-o)*(e-l)>=0&&(r-o)*(i-l)-(a-o)*(n-l)>=0}function pk(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&mk(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&yk(t,e)&&yk(e,t)&&function(t,e){var r=t,n=!1,a=(t.x+e.x)/2,i=(t.y+e.y)/2;do{r.y>i!=r.next.y>i&&r.next.y!==r.y&&a<(r.next.x-r.x)*(i-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function gk(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function vk(t,e){return t.x===e.x&&t.y===e.y}function mk(t,e,r,n){return!!(vk(t,e)&&vk(r,n)||vk(t,n)&&vk(r,e))||gk(t,e,r)>0!=gk(t,e,n)>0&&gk(r,n,t)>0!=gk(r,n,e)>0}function yk(t,e){return gk(t.prev,t,t.next)<0?gk(t,e,t.next)>=0&&gk(t,t.prev,e)>=0:gk(t,e,t.prev)<0||gk(t,t.next,e)<0}function xk(t,e){var r=new wk(t.i,t.x,t.y),n=new wk(e.i,e.x,e.y),a=t.next,i=e.prev;return t.next=e,e.prev=t,r.next=a,a.prev=r,n.next=r,r.prev=n,i.next=n,n.prev=i,n}function bk(t,e,r,n){var a=new wk(t,e,r);return n?(a.next=n.next,a.prev=n,n.next.prev=a,n.next=a):(a.prev=a,a.next=a),a}function _k(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function wk(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function Ak(t,e,r,n){for(var a=0,i=e,o=r-n;i0&&(n+=t[a-1].length,r.holes.push(n))}return r};var Mk=function(t,e){"function"==typeof t?(e||(e={}),e.regl=t):e=t;e.length&&(e.positions=e);if(!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");var r,n,a,i,o,l,s,u,c=t._gl,f={positions:[],dashes:null,join:null,miterLimit:1,thickness:10,cap:"square",color:"black",opacity:1,overlay:!1,viewport:null,range:null,close:null,fill:null},h=[],d=2,p=3e6,g=1e4;i=t.buffer({usage:"dynamic",type:"uint8",data:null}),o=t.buffer({usage:"static",type:"float",data:[0,1,0,0,1,1,1,0]}),l=t.buffer({usage:"dynamic",type:"float",data:null}),s=t.buffer({usage:"dynamic",type:"float",data:null}),u=t.texture({channels:1,data:new Uint8Array(524288),width:256,height:2048,mag:"linear",min:"linear"}),b(e);var v={primitive:"triangle strip",instances:t.prop("count"),count:4,offset:0,uniforms:{miterMode:function(t,e){return"round"===e.join?2:1},miterLimit:t.prop("miterLimit"),scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),thickness:t.prop("thickness"),dashPattern:u,dashLength:t.prop("dashLength"),dashShape:[256,2048],opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),scaleRatio:t.prop("scaleRatio"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:function(t,e){return!e.overlay}},scissor:{enable:!0,box:t.prop("viewport")},stencil:!1,viewport:t.prop("viewport")};function m(t){t?b(t):null===t&&_(),y()}function y(t){if("number"==typeof t)return x(t);t&&!Array.isArray(t)&&(t=[t]),h.forEach(function(t,e){x(e)})}function x(e){"number"==typeof e&&(e=h[e]),e&&e.count&&e.opacity&&e.positions&&e.positions.length>2&&(t._refresh(),e.fill&&e.triangles&&e.triangles.length>2&&a(e),e.thickness&&e.color&&(e.scaleRatio=[e.scale[0]*e.viewport.width,e.scale[1]*e.viewport.height],e.scaleRatio[0]>p||e.scaleRatio[1]>p?n(e):"rect"===e.join||!e.join&&(e.thickness<=2||e.positions.length>=g)?n(e):r(e),e.after&&e.after(e)))}function b(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0;if(m.lines=h=t.map(function(t,r){var n=h[r];return void 0===t?n:(null===t?t={positions:null}:"function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),null===(t=HT(t,{positions:"positions points data coords",thickness:"thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",join:"lineJoin linejoin join type mode",miterLimit:"miterlimit miterLimit",dashes:"dash dashes dasharray dash-array dashArray",color:"color stroke colors stroke-color strokeColor",fill:"fill fill-color fillColor",opacity:"alpha opacity",overlay:"overlay crease overlap intersect",close:"closed close closed-path closePath",range:"range dataBox",viewport:"viewport viewBox",hole:"holes hole hollow",after:"after callback done pass"})).positions&&(t.positions=[]),n||(h[r]=n={id:r,scale:null,scaleFract:null,translate:null,translateFract:null,count:0,offset:0,dashLength:0,hole:!0},t=VT({},f,t)),YT(n,t,[{thickness:parseFloat,opacity:parseFloat,miterLimit:parseFloat,overlay:Boolean,join:function(t){return t},after:function(t){return t},hole:function(t){return t||[]},positions:function(t,r,n){t=NT(t,"float64");var a=Math.floor(t.length/2),i=zT(t,2);return r.range||n.range||(n.range=i),r.count=a,r.bounds=i,e+=a,t},fill:function(t){return t?nv(t,"uint8"):null},dashes:function(t,e,r){var n,a=e.dashLength;if(!t||t.length<2)a=1,n=new Uint8Array([255,255,255,255,255,255,255,255]);else{a=0;for(var i=0;i=4&&e.positions[0]===e.positions[e.positions.length-2]&&e.positions[1]===e.positions[e.positions.length-1]},positions:function(t,e,r){if(e.fill&&t.length){for(var n=[],a={},i=0,o=0,l=0,s=e.count;o 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),frag:Fo(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:o,divisor:0,stride:8,offset:0},lineTop:{buffer:o,divisor:0,stride:8,offset:4},aColor:{buffer:i,stride:4,offset:function(t,e){return 4*e.offset},divisor:1},bColor:{buffer:i,stride:4,offset:function(t,e){return 4*e.offset+4},divisor:1},prevCoord:{buffer:l,stride:8,offset:function(t,e){return 8*e.offset},divisor:1},aCoord:{buffer:l,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoord:{buffer:l,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},nextCoord:{buffer:l,stride:8,offset:function(t,e){return 24+8*e.offset},divisor:1}}},v)),n=t(VT({vert:Fo(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\t// vec2 scaleRatio = scale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scaleRatio);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:Fo(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:o,divisor:0,stride:8,offset:0},lineTop:{buffer:o,divisor:0,stride:8,offset:4},aCoord:{buffer:l,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoord:{buffer:l,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},aCoordFract:{buffer:s,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoordFract:{buffer:s,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},color:{buffer:i,stride:4,offset:function(t,e){return 4*e.offset},divisor:1}}},v)),a=t({primitive:"triangle",elements:function(t,e){return e.triangles},offset:0,vert:Fo(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:Fo(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= opacity;\n}\n"]),uniforms:{scale:t.prop("scale"),color:t.prop("fill"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{position:{buffer:l,stride:8,offset:function(t,e){return 8+8*e.offset}},positionFract:{buffer:s,stride:8,offset:function(t,e){return 8+8*e.offset}}},blend:v.blend,depth:{enable:!1},scissor:v.scissor,stencil:v.stencil,viewport:v.viewport}),VT(m,{update:b,draw:y,destroy:_,regl:t,gl:c,canvas:c.canvas,lines:h}),m};function Tk(t){var e=new Float32Array(t.length);e.set(t);for(var r=0,n=e.length;r>>24,n=(16711680&t)>>>16,a=(65280&t)>>>8,i=255&t;return!1===e?[r,n,a,i]:[r/255,n/255,a/255,i/255]};var Ck="undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)),Sk=function(t){var e;arguments.length>1&&(t=arguments);"string"==typeof t&&(t=t.split(/\s/).map(parseFloat));t.length&&"number"==typeof t[0]?e=2===t.length?{width:t[0],height:t[1],x:0,y:0}:{x:t[0],y:t[1],width:t[2]-t[0]||0,height:t[3]-t[1]||0}:t&&(t=HT(t,{left:"x l left Left",top:"y t top Top",width:"w width",height:"h height",bottom:"b bottom",right:"r right"}),e={x:t.left||0,y:t.top||0},null==t.width?t.right?e.width=t.right-e.x:e.width=0:e.width=t.width,null==t.height?t.bottom?e.height=t.bottom-e.y:e.height=0:e.height=t.height);return e};function Lk(t,e,r,n,a){var i=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function Ok(t,e,r,n){return new Function([Lk("A","x"+t+"y",e,["y"],n),Lk("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var Rk={ge:Ok(">=",!1,"GE"),gt:Ok(">",!1,"GT"),lt:Ok("<",!0,"LT"),le:Ok("<=",!0,"LE"),eq:Ok("-",!0,"EQ",!0)},Dk=function(t,e,r,n,a){a<=4*Ik?Pk(0,a-1,t,e,r,n):function t(e,r,n,a,i,o){var l=(r-e+1)/6|0,s=e+l,u=r-l,c=e+r>>1,f=c-l,h=c+l,d=s,p=f,g=c,v=h,m=u,y=e+1,x=r-1,b=0;jk(d,p,n,a,i)&&(b=d,d=p,p=b);jk(v,m,n,a,i)&&(b=v,v=m,m=b);jk(d,g,n,a,i)&&(b=d,d=g,g=b);jk(p,g,n,a,i)&&(b=p,p=g,g=b);jk(d,v,n,a,i)&&(b=d,d=v,v=b);jk(g,v,n,a,i)&&(b=g,g=v,v=b);jk(p,m,n,a,i)&&(b=p,p=m,m=b);jk(p,g,n,a,i)&&(b=p,p=g,g=b);jk(v,m,n,a,i)&&(b=v,v=m,m=b);var _=n[p];var w=a[2*p];var A=a[2*p+1];var M=i[p];var T=o[p];var k=n[v];var E=a[2*v];var C=a[2*v+1];var S=i[v];var L=o[v];var O=d;var R=g;var D=m;var I=s;var P=c;var F=u;var z=n[O];var N=n[R];var B=n[D];n[I]=z;n[P]=N;n[F]=B;for(var j=0;j<2;++j){var U=a[2*O+j],V=a[2*R+j],H=a[2*D+j];a[2*I+j]=U,a[2*P+j]=V,a[2*F+j]=H}var q=i[O];var G=i[R];var X=i[D];i[I]=q;i[P]=G;i[F]=X;var W=o[O];var Y=o[R];var Z=o[D];o[I]=W;o[P]=Y;o[F]=Z;zk(f,e,n,a,i,o);zk(h,r,n,a,i,o);for(var J=y;J<=x;++J)if(Uk(J,_,w,A,M,n,a,i))J!==y&&Fk(J,y,n,a,i,o),++y;else if(!Uk(J,k,E,C,S,n,a,i))for(;;){if(Uk(x,k,E,C,S,n,a,i)){Uk(x,_,w,A,M,n,a,i)?(Nk(J,y,x,n,a,i,o),++y,--x):(Fk(J,x,n,a,i,o),--x);break}if(--xt;){var d=r[h-1],p=n[2*(h-1)];if((d-l||s-p)>=0)break;r[h]=d,n[2*h]=p,n[2*h+1]=n[2*h-1],a[h]=a[h-1],i[h]=i[h-1],h-=1}r[h]=l,n[2*h]=s,n[2*h+1]=u,a[h]=c,i[h]=f}}function Fk(t,e,r,n,a,i){var o=r[t],l=n[2*t],s=n[2*t+1],u=a[t],c=i[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],a[t]=a[e],i[t]=i[e],r[e]=o,n[2*e]=l,n[2*e+1]=s,a[e]=u,i[e]=c}function zk(t,e,r,n,a,i){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],a[t]=a[e],i[t]=i[e]}function Nk(t,e,r,n,a,i,o){var l=n[t],s=a[2*t],u=a[2*t+1],c=i[t],f=o[t];n[t]=n[e],a[2*t]=a[2*e],a[2*t+1]=a[2*e+1],i[t]=i[e],o[t]=o[e],n[e]=n[r],a[2*e]=a[2*r],a[2*e+1]=a[2*r+1],i[e]=i[r],o[e]=o[r],n[r]=l,a[2*r]=s,a[2*r+1]=u,i[r]=c,o[r]=f}function Bk(t,e,r,n,a,i,o,l,s,u,c){l[t]=l[e],s[2*t]=s[2*e],s[2*t+1]=s[2*e+1],u[t]=u[e],c[t]=c[e],l[e]=r,s[2*e]=n,s[2*e+1]=a,u[e]=i,c[e]=o}function jk(t,e,r,n,a){return(r[t]-r[e]||n[2*e]-n[2*t]||a[t]-a[e])<0}function Uk(t,e,r,n,a,i,o,l){return(e-i[t]||o[2*t]-r||a-l[t])<0}var Vk=function(t,e,r,n){var a=t.length>>>1;if(a<1)return[];e||(e=Array(a));r||(r=Array(a));n||(n=[]);for(var i=0;i=n[2]||n[1]>=n[3]){var o=zT(t,2);o[0]===o[2]&&(o[2]+=1),o[1]===o[3]&&(o[3]+=1),n[0]=o[0],n[1]=o[1],n[2]=o[2],n[3]=o[3]}var l=n[0],s=n[1],u=n[2],c=n[3],f=1/(u-l),h=1/(c-s),d=Math.max(u-l,c-s),p=new Int32Array(a),g=0;(function n(a,i,o,l,s,u){var c=.5*o;var f=l+1;var h=s-l;r[g]=h;p[g++]=u;for(var d=0;d<2;++d)for(var v=0;v<2;++v){var m=a+d*c,y=i+v*c,x=Hk(t,e,f,s,m,y,m+c,y+c);if(x!==f){if(x-f>=Math.max(.9*h,32)){var b=s+l>>>1;n(m,y,c,f,b,u+1),f=b}n(m,y,c,f,x,u+1),f=x}}})(l,s,d,0,a,0),Dk(p,t,e,r,a);for(var v=[],m=0,y=a,g=a-1;g>=0;--g){t[2*g]=(t[2*g]-l)*f,t[2*g+1]=(t[2*g+1]-s)*h;var x=p[g];x!==m&&(v.push(new qk(d*Math.pow(.5,x),g+1,y-(g+1))),y=g+1,m=x)}return v.push(new qk(d*Math.pow(.5,x+1),0,y)),v};function Hk(t,e,r,n,a,i,o,l){for(var s=r,u=r;u 1.0) {\n discard;\n }\n\n float centerFraction = fragBorderSize == 0. ? 2. : fragSize / (fragSize + fragBorderSize + 1.25);\n\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, 1.);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"]),vert:Fo(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nvoid main() {\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n fragBorderSize = borderSize;\n fragSize = size;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragWidth = 1. / gl_PointSize;\n}\n"]),uniforms:{color:function(t,e){var r=e.color.length?e.color[0]:e.color;return c.slice(4*r,4*r+4).map(function(t){return t/255})},borderColor:function(t,e){var r=e.borderColor.length?e.borderColor[0]:e.borderColor;return c.slice(4*r,4*r+4).map(function(t){return t/255})},pixelRatio:t.context("pixelRatio"),palette:s,paletteSize:function(t,e){return[v,s.height]},scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translate:t.prop("translate"),translateFract:t.prop("translateFract"),opacity:t.prop("opacity"),marker:t.prop("marker")},attributes:{position:i,positionFract:o,size:y.attributes.size,borderSize:y.attributes.borderSize}}));else{var x=VT({},y);x.frag=Fo(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n //max-distance alpha\n if (dist < 0.003) discard;\n\n //null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]),x.vert=Fo(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n\t\tfragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]),r=t(x);var b=VT({},y);b.frag=Fo(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif(radius > 1.0 + delta) {\n\t\tdiscard;\n\t\treturn;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]),b.vert=Fo(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]),n=t(b)}function _(t){t?T(t):null===t&&L(),w()}function w(t){if("number"==typeof t)return A(t);Array.isArray(t)?t.forEach(function(t,e){if(null!=t)return t.length?A(t,e):A(t)}):d.forEach(function(t,e){t&&A(e)})}function A(e,a){var i;if("number"==typeof e&&(e=d[e]),Array.isArray(e)&&(i=e,e=d[a]),e&&e.count&&e.opacity){var o;if(i){o=Array(e.count);for(var l=0;l1)){var d=h.offset,g=h.count+d,v=Rk.ge(s,n[0],d,g-1),m=Rk.lt(s,n[2],v,g-1)+1;if(!(m<=v))if(r){var y=x(t.data.subarray(v,m),r);o.push(VT({},e,{elements:y,marker:p[u],offset:0,count:y.length}))}else o.push(VT({},e,{elements:t.elements,marker:p[u],offset:v,count:m-v}))}}function x(t,e){for(var r=[],n=0,i=t.length;na)){s.snap=!0;var f=s.x=Array(u),h=s.w=Array(u),d=void 0;if(n.length>1){d=Array(2*u);for(var p=0;p=0)return n;if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)r=e;else{r=new Uint8Array(e.length);for(var a=0,i=e.length;a1)for(var r=.25*(t=t.slice()).length%v;r7&&(r.push(d.splice(0,7)),d.unshift("C"));break;case"S":var g=u,v=c;"C"!=e&&"S"!=e||(g+=g-n,v+=v-a),d=["C",g,v,d[1],d[2],d[3],d[4]];break;case"T":"Q"==e||"T"==e?(l=2*u-l,s=2*c-s):(l=u,s=c),d=nE(u,c,l,s,d[1],d[2]);break;case"Q":l=d[1],s=d[2],d=nE(u,c,d[1],d[2],d[3],d[4]);break;case"L":d=rE(u,c,d[1],d[2]);break;case"H":d=rE(u,c,d[1],c);break;case"V":d=rE(u,c,u,d[1]);break;case"Z":d=rE(u,c,i,o)}e=p,u=d[d.length-2],c=d[d.length-1],d.length>4?(n=d[d.length-4],a=d[d.length-3]):(n=u,a=c),r.push(d)}return r};function rE(t,e,r,n){return["C",t,e,r,n,r,n]}function nE(t,e,r,n,a,i){return["C",t/3+2/3*r,e/3+2/3*n,a/3+2/3*r,i/3+2/3*n,a,i]}function aE(t,e,r,n,a,i,o,l,s,u){if(u)x=u[0],b=u[1],m=u[2],y=u[3];else{var c=iE(t,e,-a);t=c.x,e=c.y;var f=(t-(l=(c=iE(l,s,-a)).x))/2,h=(e-(s=c.y))/2,d=f*f/(r*r)+h*h/(n*n);d>1&&(r*=d=Math.sqrt(d),n*=d);var p=r*r,g=n*n,v=(i==o?-1:1)*Math.sqrt(Math.abs((p*g-p*h*h-g*f*f)/(p*h*h+g*f*f)));v==1/0&&(v=1);var m=v*r*h/n+(t+l)/2,y=v*-n*f/r+(e+s)/2,x=Math.asin(((e-y)/n).toFixed(9)),b=Math.asin(((s-y)/n).toFixed(9));x=tb&&(x-=2*Kk),!o&&b>x&&(b-=2*Kk)}if(Math.abs(b-x)>tE){var _=b,w=l,A=s;b=x+tE*(o&&b>x?1:-1);var M=aE(l=m+r*Math.cos(b),s=y+n*Math.sin(b),r,n,a,0,o,w,A,[b,_,m,y])}var T=Math.tan((b-x)/4),k=4/3*r*T,E=4/3*n*T,C=[2*t-(t+k*Math.sin(x)),2*e-(e-E*Math.cos(x)),l+k*Math.sin(b),s-E*Math.cos(b),l,s];if(u)return C;M&&(C=C.concat(M));for(var S=0;S4))},cE=function(t){var e=[];return t.replace(hE,function(t,r,n){var a=r.toLowerCase();for(n=function(t){var e=t.match(dE);return e?e.map(Number):[]}(n),"m"==a&&n.length>2&&(e.push([r].concat(n.splice(0,2))),a="l",r="m"==r?"l":"L");;){if(n.length==fE[a])return n.unshift(r),e.push(n);if(n.length=o)return t;switch(t){case"%s":return String(a[n++]);case"%d":return Number(a[n++]);case"%j":try{return JSON.stringify(a[n++])}catch(t){return"[Circular]"}default:return t}}),s=a[n];n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),h(e)?r.showHidden=e:e&&vE._extend(r,e),v(r.showHidden)&&(r.showHidden=!1),v(r.depth)&&(r.depth=2),v(r.colors)&&(r.colors=!1),v(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),s(r,t,r.depth)}function o(t,e){var r=i.styles[e];return r?"\x1b["+i.colors[r][0]+"m"+t+"\x1b["+i.colors[r][1]+"m":t}function l(t,e){return t}function s(t,e,r){if(t.customInspect&&e&&_(e.inspect)&&e.inspect!==vE.inspect&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return g(n)||(n=s(t,n,r)),n}var a=function(t,e){if(v(e))return t.stylize("undefined","undefined");if(g(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(p(e))return t.stylize(""+e,"number");if(h(e))return t.stylize(""+e,"boolean");if(d(e))return t.stylize("null","null")}(t,e);if(a)return a;var i=Object.keys(e),o=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(i);if(t.showHidden&&(i=Object.getOwnPropertyNames(e)),b(e)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return u(e);if(0===i.length){if(_(e)){var l=e.name?": "+e.name:"";return t.stylize("[Function"+l+"]","special")}if(m(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(x(e))return t.stylize(Date.prototype.toString.call(e),"date");if(b(e))return u(e)}var y,w="",A=!1,M=["{","}"];(f(e)&&(A=!0,M=["[","]"]),_(e))&&(w=" [Function"+(e.name?": "+e.name:"")+"]");return m(e)&&(w=" "+RegExp.prototype.toString.call(e)),x(e)&&(w=" "+Date.prototype.toUTCString.call(e)),b(e)&&(w=" "+u(e)),0!==i.length||A&&0!=e.length?r<0?m(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),y=A?function(t,e,r,n,a){for(var i=[],o=0,l=e.length;o=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(y,w,M)):M[0]+w+M[1]}function u(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,e,r,n,a,i){var o,l,u;if((u=Object.getOwnPropertyDescriptor(e,a)||{value:e[a]}).get?l=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(l=t.stylize("[Setter]","special")),T(n,a)||(o="["+a+"]"),l||(t.seen.indexOf(u.value)<0?(l=d(r)?s(t,u.value,null):s(t,u.value,r-1)).indexOf("\n")>-1&&(l=i?l.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+l.split("\n").map(function(t){return" "+t}).join("\n")):l=t.stylize("[Circular]","special")),v(o)){if(i&&a.match(/^\d+$/))return l;(o=JSON.stringify(""+a)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+l}function f(t){return Array.isArray(t)}function h(t){return"boolean"==typeof t}function d(t){return null===t}function p(t){return"number"==typeof t}function g(t){return"string"==typeof t}function v(t){return void 0===t}function m(t){return y(t)&&"[object RegExp]"===w(t)}function y(t){return"object"==typeof t&&null!==t}function x(t){return y(t)&&"[object Date]"===w(t)}function b(t){return y(t)&&("[object Error]"===w(t)||t instanceof Error)}function _(t){return"function"==typeof t}function w(t){return Object.prototype.toString.call(t)}function A(t){return t<10?"0"+t.toString(10):t.toString(10)}vE.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var r=t.pid;a[e]=function(){var t=vE.format.apply(vE,arguments);console.error("%s %d: %s",e,r,t)}}else a[e]=function(){};return a[e]},vE.inspect=i,i.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]},i.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},vE.isArray=f,vE.isBoolean=h,vE.isNull=d,vE.isNullOrUndefined=function(t){return null==t},vE.isNumber=p,vE.isString=g,vE.isSymbol=function(t){return"symbol"==typeof t},vE.isUndefined=v,vE.isRegExp=m,vE.isObject=y,vE.isDate=x,vE.isError=b,vE.isFunction=_,vE.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},vE.isBuffer=gE;var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function T(t,e){return Object.prototype.hasOwnProperty.call(t,e)}vE.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[A(t.getHours()),A(t.getMinutes()),A(t.getSeconds())].join(":"),[t.getDate(),M[t.getMonth()],e].join(" ")),vE.format.apply(vE,arguments))},vE.inherits=pE,vE._extend=function(t,e){if(!e||!y(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,xs,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var mE={};(function(t){"use strict";function e(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,a=0,i=Math.min(r,n);a=0;s--)if(u[s]!==c[s])return!1;for(s=u.length-1;s>=0;s--)if(l=u[s],!g(t[l],e[l],r,n))return!1;return!0}(t,n,i,s))}return i?t===n:t==n}function v(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function m(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function y(t,e,r,n){var a;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),a=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!a&&d(a,r,"Missing expected exception"+n);var i="string"==typeof n,o=!t&&vE.isError(a),l=!t&&a&&!r;if((o&&i&&m(a,r)||l)&&d(a,r,"Got unwanted exception"+n),t&&a&&r&&!m(a,r)||!t&&a)throw a}s.AssertionError=function(t){var e;this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=f(h((e=this).actual),128)+" "+e.operator+" "+f(h(e.expected),128),this.generatedMessage=!0);var r=t.stackStartFunction||d;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var a=n.stack,i=c(r),o=a.indexOf("\n"+i);if(o>=0){var l=a.indexOf("\n",o+1);a=a.substring(l+1)}this.stack=a}}},vE.inherits(s.AssertionError,Error),s.fail=d,s.ok=p,s.equal=function(t,e,r){t!=e&&d(t,e,r,"==",s.equal)},s.notEqual=function(t,e,r){t==e&&d(t,e,r,"!=",s.notEqual)},s.deepEqual=function(t,e,r){g(t,e,!1)||d(t,e,r,"deepEqual",s.deepEqual)},s.deepStrictEqual=function(t,e,r){g(t,e,!0)||d(t,e,r,"deepStrictEqual",s.deepStrictEqual)},s.notDeepEqual=function(t,e,r){g(t,e,!1)&&d(t,e,r,"notDeepEqual",s.notDeepEqual)},s.notDeepStrictEqual=function t(e,r,n){g(e,r,!0)&&d(e,r,n,"notDeepStrictEqual",t)},s.strictEqual=function(t,e,r){t!==e&&d(t,e,r,"===",s.strictEqual)},s.notStrictEqual=function(t,e,r){t===e&&d(t,e,r,"!==",s.notStrictEqual)},s.throws=function(t,e,r){y(!0,t,e,r)},s.doesNotThrow=function(t,e,r){y(!1,t,e,r)},s.ifError=function(t){if(t)throw t};var x=Object.keys||function(t){var e=[];for(var r in t)n.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var yE={};Object.defineProperty(yE,"__esModule",{value:!0});var xE=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var r=[],n=!0,a=!1,i=void 0;try{for(var o,l=t[Symbol.iterator]();!(n=(o=l.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){a=!0,i=t}finally{try{!n&&l.return&&l.return()}finally{if(a)throw i}}return r}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),bE=2*Math.PI,_E=function(t,e,r,n,a,i,o){var l=t.x,s=t.y;return{x:n*(l*=e)-a*(s*=r)+i,y:a*l+n*s+o}},wE=function(t,e){var r=4/3*Math.tan(e/4),n=Math.cos(t),a=Math.sin(t),i=Math.cos(t+e),o=Math.sin(t+e);return[{x:n-a*r,y:a+n*r},{x:i+o*r,y:o-i*r},{x:i,y:o}]},AE=function(t,e,r,n){var a=t*n-e*r<0?-1:1,i=(t*r+e*n)/(Math.sqrt(t*t+e*e)*Math.sqrt(t*t+e*e));return i>1&&(i=1),i<-1&&(i=-1),a*Math.acos(i)};yE.default=function(t){var e=t.px,r=t.py,n=t.cx,a=t.cy,i=t.rx,o=t.ry,l=t.xAxisRotation,s=void 0===l?0:l,u=t.largeArcFlag,c=void 0===u?0:u,f=t.sweepFlag,h=void 0===f?0:f,d=[];if(0===i||0===o)return[];var p=Math.sin(s*bE/360),g=Math.cos(s*bE/360),v=g*(e-n)/2+p*(r-a)/2,m=-p*(e-n)/2+g*(r-a)/2;if(0===v&&0===m)return[];i=Math.abs(i),o=Math.abs(o);var y=Math.pow(v,2)/Math.pow(i,2)+Math.pow(m,2)/Math.pow(o,2);y>1&&(i*=Math.sqrt(y),o*=Math.sqrt(y));var x=function(t,e,r,n,a,i,o,l,s,u,c,f){var h=Math.pow(a,2),d=Math.pow(i,2),p=Math.pow(c,2),g=Math.pow(f,2),v=h*d-h*g-d*p;v<0&&(v=0),v/=h*g+d*p;var m=(v=Math.sqrt(v)*(o===l?-1:1))*a/i*f,y=v*-i/a*c,x=u*m-s*y+(t+r)/2,b=s*m+u*y+(e+n)/2,_=(c-m)/a,w=(f-y)/i,A=(-c-m)/a,M=(-f-y)/i,T=AE(1,0,_,w),k=AE(_,w,A,M);return 0===l&&k>0&&(k-=bE),1===l&&k<0&&(k+=bE),[x,b,T,k]}(e,r,n,a,i,o,c,h,p,g,v,m),b=xE(x,4),_=b[0],w=b[1],A=b[2],M=b[3],T=Math.max(Math.ceil(Math.abs(M)/(bE/4)),1);M/=T;for(var k=0;k4?(n=d[d.length-4],a=d[d.length-3]):(n=u,a=c),r.push(d)}return r};function TE(t,e,r,n){return["C",t,e,r,n,r,n]}function kE(t,e,r,n,a,i){return["C",t/3+2/3*r,e/3+2/3*n,a/3+2/3*r,i/3+2/3*n,a,i]}var EE=function(t){Array.isArray(t)&&1===t.length&&"string"==typeof t[0]&&(t=t[0]);"string"==typeof t&&(mE(uE(t),"String is not an SVG path."),t=cE(t));if(mE(Array.isArray(t),"Argument should be a string or an array of path segments."),t=$k(t),!(t=ME(t)).length)return[0,0,0,0];for(var e=[1/0,1/0,-1/0,-1/0],r=0,n=t.length;re[2]&&(e[2]=a[i+0]),a[i+1]>e[3]&&(e[3]=a[i+1]);return e};var CE={};(function(t){"use strict";var e=document.createElement("canvas"),r=e.getContext("2d");CE=function(n,a){if(!uE(n))throw Error("Argument should be valid svg path string");a||(a={});var i,o;a.shape?(i=a.shape[0],o=a.shape[1]):(i=e.width=a.w||a.width||200,o=e.height=a.h||a.height||200);var l=Math.min(i,o),s=a.stroke||0,u=a.viewbox||a.viewBox||EE(n),c=[i/(u[2]-u[0]),o/(u[3]-u[1])],f=Math.min(c[0]||0,c[1]||0)/2;r.fillStyle="black",r.fillRect(0,0,i,o),r.fillStyle="white",s&&("number"!=typeof s&&(s=1),r.strokeStyle=s>0?"white":"black",r.lineWidth=Math.abs(s));if(r.translate(.5*i,.5*o),r.scale(f,f),t.Path2D){var h=new Path2D(n);r.fill(h),s&&r.stroke(h)}else{var d=cE(n);sE(r,d),r.fill(),s&&r.stroke()}return r.setTransform(1,0,0,1,0,0),Yk(r,{cutoff:null!=a.cutoff?a.cutoff:.5,radius:null!=a.radius?a.radius:.5*l})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var SE={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]},LE=S.defaultLine,OE=nv(LE),RE=1;function DE(t,e){var r=t;return r[3]*=e,r}function IE(t){if(e(t))return OE;var r=nv(t);return r.length?r:OE}function PE(t){return e(t)?t:RE}var FE=function(t,e,r){var n,a,i,o,l,s=t.color,u=Array.isArray(s),c=Array.isArray(e),f=[];if(n=void 0!==t.colorscale?xr.makeColorScaleFunc(xr.extractScale(t.colorscale,t.cmin,t.cmax)):IE,a=u?function(t,e){return void 0===t[e]?OE:nv(n(t[e]))}:IE,i=c?function(t,e){return void 0===t[e]?RE:PE(t[e])}:PE,u||c)for(var h=0;h1,o=r.error_x&&!0===r.error_x.visible,l=r.error_y&&!0===r.error_y.visible,s=Yr.hasMarkers(r),u=!!r.fill&&"none"!==r.fill),o||l){var M=R.getComponentMethod("errorbars","calcFromTrace")(r,_);o&&(v=S("x",r.error_x,M)),l&&(m=S("y",r.error_y,M))}if(i){(f={}).thickness=r.line.width,f.color=r.line.color,f.opacity=r.opacity,f.overlay=!0;var T=(SE[r.line.dash]||[1]).slice();for(a=0;ac?"rect":s?"rect":"round",k&&r.connectgaps){var E=b[0],C=b[1];for(a=0;ae?1:t>=e?0:NaN}function d(t){return null===t?NaN:+t}function p(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n>>1;t(e[i],r)<0?n=i+1:a=i}return n},right:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n>>1;t(e[i],r)>0?a=i:n=i+1}return n}}}t.ascending=h,t.descending=function(t,e){return et?1:e>=t?0:NaN},t.min=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++an&&(r=n)}else{for(;++a=n){r=n;break}for(;++an&&(r=n)}return r},t.max=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a=n){r=n;break}for(;++ar&&(r=n)}else{for(;++a=n){r=n;break}for(;++ar&&(r=n)}return r},t.extent=function(t,e){var r,n,a,i=-1,o=t.length;if(1===arguments.length){for(;++i=n){r=a=n;break}for(;++in&&(r=n),a=n){r=a=n;break}for(;++in&&(r=n),a1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(h);function m(t){return t.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(t){return g(1===t.length?function(e,r){return h(t(e),r)}:t)},t.shuffle=function(t,e,r){(i=arguments.length)<3&&(r=t.length,i<2&&(e=0));for(var n,a,i=r-e;i;)a=Math.random()*i--|0,n=t[i+e],t[i+e]=t[a+e],t[a+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],a=new Array(r<0?0:r);e=0;)for(e=(n=t[a]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,a=[],i=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=i,e*=i,(r*=i)<0)for(;(n=t+r*++o)>e;)a.push(n/i);else for(;(n=t+r*++o)=a.length)return r?r.call(n,i):e?i.sort(e):i;for(var s,u,c,f,h=-1,d=i.length,p=a[l++],g=new b;++h=a.length)return e;var n=[],o=i[r++];return e.forEach(function(e,a){n.push({key:e,values:t(a,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return a.push(t),n},n.sortKeys=function(t){return i[a.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(U,"\\$&")};var U=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,V={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function H(t){return V(t,Y),t}var q=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},X=function(t,e){var r=t.matches||t[R(t,"matchesSelector")];return(X=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(q=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,X=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var Y=t.selection.prototype=[];function W(t){return"function"==typeof t?t:function(){return q(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}Y.select=function(t){var e,r,n,a,i=[];t=W(t);for(var o=-1,l=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),Q.hasOwnProperty(r)?{space:Q[r],local:t}:t}},Y.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each($(r,e[r]));return this}return this.each($(e,r))},Y.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,a=-1;if(e=r.classList){for(;++a=0;)(r=n[a])&&(i&&i!==r.nextSibling&&i.parentNode.insertBefore(r,i),i=r);return this},Y.sort=function(t){t=function(t){arguments.length||(t=h);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(e=e.slice(0,o));var s=pt.get(e);function u(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=vt),o?n?function(){var t=l(n,r(arguments));u.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=n}:u:n?I:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(r=a.match(n)){var i=this[a];this.removeEventListener(r[1],i,i.$),delete this[a]}}}t.selection.enter=ft,t.selection.enter.prototype=ht,ht.append=Y.append,ht.empty=Y.empty,ht.node=Y.node,ht.call=Y.call,ht.size=Y.size,ht.select=function(t){for(var e,r,n,a,i,o=[],l=-1,s=this.length;++l=n&&(n=e+1);!(o=l[n])&&++n0?1:t<0?-1:0}function Dt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function Rt(t){return t>1?0:t<-1?Tt:Math.acos(t)}function Pt(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function It(t){return((t=Math.exp(t))+1/t)/2}function Bt(t){return(t=Math.sin(t/2))*t}var Ft=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,a=t[0],i=t[1],o=t[2],l=e[0],s=e[1],u=e[2],c=l-a,f=s-i,h=c*c+f*f;if(h0&&(e=e.transition().duration(g)),e.call(w.event)}function E(){u&&u.domain(s.range().map(function(t){return(t-h.x)/h.k}).map(s.invert)),f&&f.domain(c.range().map(function(t){return(t-h.y)/h.k}).map(c.invert))}function C(t){v++||t({type:"zoomstart"})}function S(t){E(),t({type:"zoom",scale:h.k,translate:[h.x,h.y]})}function L(t){--v||(t({type:"zoomend"}),r=null)}function O(){var e=this,r=_.of(e,arguments),n=0,a=t.select(o(e)).on(y,function(){n=1,T(t.mouse(e),i),S(r)}).on(x,function(){a.on(y,null).on(x,null),l(n),L(r)}),i=A(t.mouse(e)),l=xt(e);ll.call(e),C(r)}function D(){var e,r=this,n=_.of(r,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,u="touchend"+o,c=[],f=t.select(r),d=xt(r);function p(){var n=t.touches(r);return e=h.k,n.forEach(function(t){t.identifier in a&&(a[t.identifier]=A(t))}),n}function g(){var e=t.event.target;t.select(e).on(s,v).on(u,y),c.push(e);for(var n=t.event.changedTouches,o=0,f=n.length;o1){m=d[0];var x=d[1],b=m[0]-x[0],_=m[1]-x[1];i=b*b+_*_}}function v(){var o,s,u,c,f=t.touches(r);ll.call(r);for(var h=0,d=f.length;h360?t-=360:t<0&&(t+=360),t<60?n+(a-n)*t/60:t<180?a:t<240?n+(a-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(a=r<=.5?r*(1+e):r+e-r*e),new ie(i(t+120),i(t),i(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Wt?e.l:(e=he((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}Ht.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,this.l/t)},Ht.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,t*this.l)},Ht.rgb=function(){return qt(this.h,this.s,this.l)},t.hcl=Gt;var Xt=Gt.prototype=new Ut;function Yt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Wt(r,Math.cos(t*=St)*e,Math.sin(t)*e)}function Wt(t,e,r){return this instanceof Wt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Wt?new Wt(t.l,t.a,t.b):t instanceof Gt?Yt(t.h,t.c,t.l):he((t=ie(t)).r,t.g,t.b):new Wt(t,e,r)}Xt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Xt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Xt.rgb=function(){return Yt(this.h,this.c,this.l).rgb()},t.lab=Wt;var Zt=18,Jt=.95047,Qt=1,$t=1.08883,Kt=Wt.prototype=new Ut;function te(t,e,r){var n=(t+16)/116,a=n+e/500,i=n-r/200;return new ie(ae(3.2404542*(a=re(a)*Jt)-1.5371385*(n=re(n)*Qt)-.4985314*(i=re(i)*$t)),ae(-.969266*a+1.8760108*n+.041556*i),ae(.0556434*a-.2040259*n+1.0572252*i))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ae(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ie(t,e,r){return this instanceof ie?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ie?new ie(t.r,t.g,t.b):ce(""+t,ie,qt):new ie(t,e,r)}function oe(t){return new ie(t>>16,t>>8&255,255&t)}function le(t){return oe(t)+""}Kt.brighter=function(t){return new Wt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},Kt.darker=function(t){return new Wt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},Kt.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ie;var se=ie.prototype=new Ut;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,a,i,o=0,l=0,s=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(a=n[2].split(","),n[1]){case"hsl":return r(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return e(pe(a[0]),pe(a[1]),pe(a[2]))}return(i=ge.get(t))?e(i.r,i.g,i.b):(null==t||"#"!==t.charAt(0)||isNaN(i=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===t.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),e(o,l,s))}function fe(t,e,r){var n,a,i=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),n=t==o?(e-r)/l+(e0&&s<1?0:n),new Vt(n,a,s)}function he(t,e,r){var n=ne((.4124564*(t=de(t))+.3575761*(e=de(e))+.1804375*(r=de(r)))/Jt),a=ne((.2126729*t+.7151522*e+.072175*r)/Qt);return Wt(116*a-16,500*(n-a),200*(a-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function de(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function pe(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}se.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,a=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=a.call(o,u)}catch(t){return void l.error.call(o,t)}l.load.call(o,t)}else l.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(e)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=f:u.onreadystatechange=function(){u.readyState>3&&f()},u.onprogress=function(e){var r=t.event;t.event=e;try{l.progress.call(o,u)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(n=null==t?null:t+"",o):n},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return a=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(r(arguments)))}}),o.send=function(t,r,a){if(2===arguments.length&&"function"==typeof r&&(a=r,r=null),u.open(t,e,!0),null==n||"accept"in s||(s.accept=n+",*/*"),u.setRequestHeader)for(var i in s)u.setRequestHeader(i,s[i]);return null!=n&&u.overrideMimeType&&u.overrideMimeType(n),null!=c&&(u.responseType=c),null!=a&&o.on("error",a).on("load",function(t){a(null,t)}),l.beforesend.call(o,u),u.send(null==r?null:r),o},o.abort=function(){return u.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(i))}ge.forEach(function(t,e){ge.set(t,oe(e))}),t.functor=ve,t.xhr=me(O),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function a(t,r,n){arguments.length<3&&(n=r,r=null);var a=ye(t,e,null==r?i:o(r),n);return a.row=function(t){return arguments.length?a.response(null==(r=t)?i:o(t)):r},a}function i(t){return a.parse(t.responseText)}function o(t){return function(e){return a.parse(e.responseText,t)}}function l(e){return e.map(s).join(t)}function s(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return a.parse=function(t,e){var r;return a.parseRows(t,function(t,n){if(r)return r(t,n-1);var a=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(a(t),r)}:a})},a.parseRows=function(t,e){var r,a,i={},o={},l=[],s=t.length,u=0,c=0;function f(){if(u>=s)return o;if(a)return a=!1,i;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),_e=0):(_e=1,Ae(Te))}function ke(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Ee(){for(var t,e=xe,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ce(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Se[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Oe=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Ce(e,r))).toFixed(Math.max(0,Math.min(20,Ce(e*(1+1e-15),r))))}});function De(t){return t+""}var Re=t.time={},Pe=Date;function Ie(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Ie.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(){Be.setUTCDate.apply(this._,arguments)},setDay:function(){Be.setUTCDay.apply(this._,arguments)},setFullYear:function(){Be.setUTCFullYear.apply(this._,arguments)},setHours:function(){Be.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Be.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Be.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Be.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Be.setUTCSeconds.apply(this._,arguments)},setTime:function(){Be.setTime.apply(this._,arguments)}};var Be=Date.prototype;function Fe(t,e,r){function n(e){var r=t(e),n=i(r,1);return e-r1)for(;o68?1900:2e3),r+a[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ar(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,a=y(e)%60;return r+Ve(n,"0",2)+Ve(a,"0",2)}function ir(t,e,r){Ue.lastIndex=0;var n=Ue.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&l>0&&(s+l+1>e&&(l=Math.max(1,e-s)),i.push(t.substring(r-=l,r+l)),!((s+=l+1)>e));)l=a[o=(o+1)%a.length];return i.reverse().join(n)}:O;return function(e){var n=Le.exec(e),a=n[1]||" ",l=n[2]||">",s=n[3]||"-",u=n[4]||"",c=n[5],f=+n[6],h=n[7],d=n[8],p=n[9],g=1,v="",m="",y=!1,x=!0;switch(d&&(d=+d.substring(1)),(c||"0"===a&&"="===l)&&(c=a="0",l="="),p){case"n":h=!0,p="g";break;case"%":g=100,m="%",p="f";break;case"p":g=100,m="%",p="r";break;case"b":case"o":case"x":case"X":"#"===u&&(v="0"+p.toLowerCase());case"c":x=!1;case"d":y=!0,d=0;break;case"s":g=-1,p="r"}"$"===u&&(v=i[0],m=i[1]),"r"!=p||d||(p="g"),null!=d&&("g"==p?d=Math.max(1,Math.min(21,d)):"e"!=p&&"f"!=p||(d=Math.max(0,Math.min(20,d)))),p=Oe.get(p)||De;var b=c&&h;return function(e){var n=m;if(y&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var u=t.formatPrefix(e,d);e=u.scale(e),n=u.symbol+m}else e*=g;var _,w,A=(e=p(e,d)).lastIndexOf(".");if(A<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,A),w=r+e.substring(A+1);!c&&h&&(_=o(_,1/0));var T=v.length+_.length+w.length+(b?0:i.length),k=T"===l?k+i+e:"^"===l?k.substring(0,T>>=1)+i+e+k.substring(T):i+(b?e:k+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,u=e.shortMonths;function c(t){var e=t.length;function r(r){for(var n,a,i,o=[],l=-1,s=0;++l=u)return-1;if(37===(a=e.charCodeAt(l++))){if(o=e.charAt(l++),!(i=w[o in Ne?e.charAt(l++):o])||(n=i(t,r,n))<0)return-1}else if(a!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(Pe=Ie);return r._=t,e(r)}finally{Pe=Date}}return r.parse=function(t){try{Pe=Ie;var r=e.parse(t);return r&&r._}finally{Pe=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var h=t.map(),d=He(o),p=qe(o),g=He(l),v=qe(l),m=He(s),y=qe(s),x=He(u),b=qe(u);i.forEach(function(t,e){h.set(t.toLowerCase(),e)});var _={a:function(t){return l[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:c(r),d:function(t,e){return Ve(t.getDate(),e,2)},e:function(t,e){return Ve(t.getDate(),e,2)},H:function(t,e){return Ve(t.getHours(),e,2)},I:function(t,e){return Ve(t.getHours()%12||12,e,2)},j:function(t,e){return Ve(1+Re.dayOfYear(t),e,3)},L:function(t,e){return Ve(t.getMilliseconds(),e,3)},m:function(t,e){return Ve(t.getMonth()+1,e,2)},M:function(t,e){return Ve(t.getMinutes(),e,2)},p:function(t){return i[+(t.getHours()>=12)]},S:function(t,e){return Ve(t.getSeconds(),e,2)},U:function(t,e){return Ve(Re.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ve(Re.mondayOfYear(t),e,2)},x:c(n),X:c(a),y:function(t,e){return Ve(t.getFullYear()%100,e,2)},Y:function(t,e){return Ve(t.getFullYear()%1e4,e,4)},Z:ar,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){d.lastIndex=0;var n=d.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return f(t,_.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Ke,L:nr,m:Qe,M:er,p:function(t,e,r){var n=h.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Xe,w:Ge,W:Ye,x:function(t,e,r){return f(t,_.x.toString(),e,r)},X:function(t,e,r){return f(t,_.X.toString(),e,r)},y:Ze,Y:We,Z:Je,"%":ir};return c}(e)}};var lr=t.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"]});function sr(){}t.format=lr.numberFormat,t.geo={},sr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new sr;function cr(t,e,r){var n=r.s=t+e,a=n-t,i=n-a;r.t=t-i+(e-a)}function fr(t,e){t&&dr.hasOwnProperty(t.type)&&dr[t.type](t,e)}t.geo.stream=function(t,e){t&&hr.hasOwnProperty(t.type)?hr[t.type](t,e):fr(t,e)};var hr={Feature:function(t,e){fr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,a=r.length;++n=0?1:-1,l=o*i,s=Math.cos(e),u=Math.sin(e),c=a*u,f=n*s+c*Math.cos(l),h=c*o*Math.sin(l);Cr.add(Math.atan2(h,f)),r=t,n=s,a=u}Sr.point=function(o,l){Sr.point=i,r=(t=o)*St,n=Math.cos(l=(e=l)*St/2+Tt/4),a=Math.sin(l)},Sr.lineEnd=function(){i(t,e)}}function Or(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Dr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Rr(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Pr(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Ir(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Br(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Fr(t){return[Math.atan2(t[1],t[0]),Pt(t[2])]}function zr(t,e){return y(t[0]-e[0])At?a=90:u<-At&&(r=-90),f[0]=e,f[1]=n}};function d(t,i){c.push(f=[e=t,n=t]),ia&&(a=i)}function p(t,o){var l=Or([t*St,o*St]);if(s){var u=Rr(s,l),c=Rr([u[1],-u[0],0],u);Br(c),c=Fr(c);var f=t-i,h=f>0?1:-1,p=c[0]*Lt*h,g=y(f)>180;if(g^(h*ia&&(a=v);else if(g^(h*i<(p=(p+360)%360-180)&&pa&&(a=o);g?t_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(tn&&(n=t)):t>i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else d(t,o);s=l,i=t}function g(){h.point=p}function v(){f[0]=e,f[1]=n,h.point=d,s=null}function m(t,e){if(s){var r=t-i;u+=y(r)>180?r+(r>0?360:-360):r}else o=t,l=e;Sr.point(t,e),p(t,e)}function x(){Sr.lineStart()}function b(){m(o,l),Sr.lineEnd(),y(u)>At&&(e=-(n=180)),f[0]=e,f[1]=n,s=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function A(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(g[0],g[1])&&(g[1]=d[1]),_(d[0],g[1])>_(g[0],g[1])&&(g[0]=d[0])):l.push(g=d);for(var s,u,d,p=-1/0,g=(o=0,l[u=l.length-1]);o<=u;g=d,++o)d=l[o],(s=_(g[1],d[0]))>p&&(p=s,e=d[0],n=g[1])}return c=f=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,a]]}}(),t.geo.centroid=function(e){mr=yr=xr=br=_r=wr=Ar=Mr=Tr=kr=Er=0,t.geo.stream(e,Nr);var r=Tr,n=kr,a=Er,i=r*r+n*n+a*a;return i=0;--l)a.point((f=c[l])[0],f[1]);else n(d.x,d.p.x,-1,a);d=d.p}c=(d=d.o).z,p=!p}while(!d.v);a.lineEnd()}}}function Wr(t){if(e=t.length){for(var e,r,n=0,a=t[0];++n=0?1:-1,A=w*_,M=A>Tt,T=p*x;if(Cr.add(Math.atan2(T*w*Math.sin(A),g*b+T*Math.cos(A))),i+=M?_+w*kt:_,M^h>=r^m>=r){var k=Rr(Or(f),Or(t));Br(k);var E=Rr(a,k);Br(E);var C=(M^_>=0?-1:1)*Pt(E[2]);(n>C||n===C&&(k[0]||k[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;h=m,p=x,g=b,f=t}}return(i<-At||i0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i1&&2&e&&r.push(r.pop().concat(r.shift())),l.push(r.filter(Qr))}return c}}function Qr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:I,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Kr(t,e){return((t=t.x)[0]<0?t[1]-Ct-At:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-At:Ct-e[1])}var tn=Jr(Xr,function(t){var e,r=NaN,n=NaN,a=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(i,o){var l=i>0?Tt:-Tt,s=y(i-r);y(s-Tt)0?Ct:-Ct),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),t.point(i,n),e=0):a!==l&&s>=Tt&&(y(r-a)At?Math.atan((Math.sin(e)*(i=Math.cos(n))*Math.sin(r)-Math.sin(n)*(a=Math.cos(e))*Math.sin(t))/(a*i*o)):(e+n)/2}(r,n,i,o),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),e=0),t.point(r=i,n=o),a=l},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var a;if(null==t)a=r*Ct,n.point(-Tt,a),n.point(0,a),n.point(Tt,a),n.point(Tt,0),n.point(Tt,-a),n.point(0,-a),n.point(-Tt,-a),n.point(-Tt,0),n.point(-Tt,a);else if(y(t[0]-e[0])>At){var i=t[0]0)){if(i/=h,h<0){if(i0){if(i>f)return;i>c&&(c=i)}if(i=r-s,h||!(i<0)){if(i/=h,h<0){if(i>f)return;i>c&&(c=i)}else if(h>0){if(i0)){if(i/=d,d<0){if(i0){if(i>f)return;i>c&&(c=i)}if(i=n-u,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>c&&(c=i)}else if(d>0){if(i0&&(a.a={x:s+c*h,y:u+c*d}),f<1&&(a.b={x:s+f*h,y:u+f*d}),a}}}}}}var rn=1e9;function nn(e,r,n,a){return function(s){var u,c,f,h,d,p,g,v,m,y,x,b=s,_=$r(),w=en(e,r,n,a),A={point:k,lineStart:function(){A.point=E,c&&c.push(f=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){u&&(E(h,d),p&&m&&_.rejoin(),u.push(_.buffer()));A.point=k,m&&s.lineEnd()},polygonStart:function(){s=_,u=[],c=[],x=!0},polygonEnd:function(){s=b,u=t.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],a=0;an&&Dt(u,i,t)>0&&++e:i[1]<=n&&Dt(u,i,t)<0&&--e,u=i;return 0!==e}([e,a]),n=x&&r,i=u.length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Yr(u,o,r,M,s),s.polygonEnd()),u=c=f=null}};function M(t,o,s,u){var c=0,f=0;if(null==t||(c=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{u.point(0===c||3===c?e:n,c>1?a:r)}while((c=(c+s+4)%4)!==f);else u.point(o[0],o[1])}function T(t,i){return e<=t&&t<=n&&r<=i&&i<=a}function k(t,e){T(t,e)&&s.point(t,e)}function E(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&f.push([t,e]),y)h=t,d=e,p=r,y=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&m)s.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),x=!1):r&&(s.lineStart(),s.point(t,e),x=!1)}g=t,v=e,m=r}return A};function i(t,a){return y(t[0]-e)0?0:3:y(t[0]-n)0?2:1:y(t[1]-r)0?1:0:a>0?3:2}function o(t,e){return l(t.x,e.x)}function l(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=En(t),a=n(e,r);return a.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},a}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,a=1+r*(2*n-r),i=Math.sqrt(a)/n;function o(t,e){var r=Math.sqrt(a-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),i-r*Math.cos(t)]}return o.invert=function(t,e){var r=i-e;return[Math.atan2(t,r)/n,Pt((a-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,a,i,o={stream:function(t){return a&&(a.valid=!1),(a=i(t)).valid=!0,a},extent:function(l){return arguments.length?(i=nn(t=+l[0][0],e=+l[0][1],r=+l[1][0],n=+l[1][1]),a&&(a.valid=!1,a=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,r){e=[t,r]}};function u(t){var i=t[0],o=t[1];return e=null,r(i,o),e||(n(i,o),e)||a(i,o),e}return u.invert=function(t){var e=i.scale(),r=i.translate(),n=(t[0]-r[0])/e,a=(t[1]-r[1])/e;return(a>=.12&&a<.234&&n>=-.425&&n<-.214?o:a>=.166&&a<.234&&n>=-.214&&n<-.115?l:i).invert(t)},u.stream=function(t){var e=i.stream(t),r=o.stream(t),n=l.stream(t);return{point:function(t,a){e.point(t,a),r.point(t,a),n.point(t,a)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),l.precision(t),u):i.precision()},u.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),l.scale(t),u.translate(i.translate())):i.scale()},u.translate=function(t){if(!arguments.length)return i.translate();var e=i.scale(),c=+t[0],f=+t[1];return r=i.translate(t).clipExtent([[c-.455*e,f-.238*e],[c+.455*e,f+.238*e]]).stream(s).point,n=o.translate([c-.307*e,f+.201*e]).clipExtent([[c-.425*e+At,f+.12*e+At],[c-.214*e-At,f+.234*e-At]]).stream(s).point,a=l.translate([c-.205*e,f+.212*e]).clipExtent([[c-.214*e+At,f+.166*e+At],[c-.115*e-At,f+.234*e-At]]).stream(s).point,u},u.scale(1070)};var ln,sn,un,cn,fn,hn,dn={point:I,lineStart:I,lineEnd:I,polygonStart:function(){sn=0,dn.lineStart=pn},polygonEnd:function(){dn.lineStart=dn.lineEnd=dn.point=I,ln+=y(sn/2)}};function pn(){var t,e,r,n;function a(t,e){sn+=n*t-r*e,r=t,n=e}dn.point=function(i,o){dn.point=a,t=r=i,e=n=o},dn.lineEnd=function(){a(t,e)}}var gn={point:function(t,e){tfn&&(fn=t);ehn&&(hn=e)},lineStart:I,lineEnd:I,polygonStart:I,polygonEnd:I};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,yn={point:xn,lineStart:bn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=xn,yn.lineStart=bn,yn.lineEnd=_n}};function xn(t,e){xr+=t,br+=e,++_r}function bn(){var t,e;function r(r,n){var a=r-t,i=n-e,o=Math.sqrt(a*a+i*i);wr+=o*(t+r)/2,Ar+=o*(e+n)/2,Mr+=o,xn(t=r,e=n)}yn.point=function(n,a){yn.point=r,xn(t=n,e=a)}}function _n(){yn.point=xn}function wn(){var t,e,r,n;function a(t,e){var a=t-r,i=e-n,o=Math.sqrt(a*a+i*i);wr+=o*(r+t)/2,Ar+=o*(n+e)/2,Mr+=o,Tr+=(o=n*t-r*e)*(r+t),kr+=o*(n+e),Er+=3*o,xn(r=t,n=e)}yn.point=function(i,o){yn.point=a,xn(t=r=i,e=n=o)},yn.lineEnd=function(){a(t,e)}}function An(t){var e=.5,r=Math.cos(30*St),n=16;function a(e){return(n?function(e){var r,a,o,l,s,u,c,f,h,d,p,g,v={point:m,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){f=NaN,v.point=x,e.lineStart()}function x(r,a){var o=Or([r,a]),l=t(r,a);i(f,h,c,d,p,g,f=l[0],h=l[1],c=r,d=o[0],p=o[1],g=o[2],n,e),e.point(f,h)}function b(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=A}function w(t,e){x(r=t,e),a=f,o=h,l=d,s=p,u=g,v.point=x}function A(){i(f,h,c,d,p,g,a,o,r,l,s,u,n,e),v.lineEnd=b,b()}return v}:function(e){return Tn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function i(n,a,o,l,s,u,c,f,h,d,p,g,v,m){var x=c-n,b=f-a,_=x*x+b*b;if(_>4*e&&v--){var w=l+d,A=s+p,M=u+g,T=Math.sqrt(w*w+A*A+M*M),k=Math.asin(M/=T),E=y(y(M)-1)e||y((x*O+b*D)/_-.5)>.3||l*d+s*p+u*g0&&16,a):Math.sqrt(e)},a}function Mn(t){this.stream=t}function Tn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function kn(t){return En(function(){return t})()}function En(e){var r,n,a,i,o,l,s=An(function(t,e){return[(t=r(t,e))[0]*u+i,o-t[1]*u]}),u=150,c=480,f=250,h=0,d=0,p=0,g=0,v=0,m=tn,x=O,b=null,_=null;function w(t){return[(t=a(t[0]*St,t[1]*St))[0]*u+i,o-t[1]*u]}function A(t){return(t=a.invert((t[0]-i)/u,(o-t[1])/u))&&[t[0]*Lt,t[1]*Lt]}function M(){a=Gr(n=On(p,g,v),r);var t=r(h,d);return i=c-t[0]*u,o=f+t[1]*u,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(t){return l&&(l.valid=!1),(l=Cn(m(n,s(x(t))))).valid=!0,l},w.clipAngle=function(t){return arguments.length?(m=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>At;return Jr(a,function(t){var e,l,s,u,c;return{lineStart:function(){u=s=!1,c=1},point:function(f,h){var d,p=[f,h],g=a(f,h),v=r?g?0:o(f,h):g?o(f+(f<0?Tt:-Tt),h):0;if(!e&&(u=s=g)&&t.lineStart(),g!==s&&(d=i(e,p),(zr(e,d)||zr(p,d))&&(p[0]+=At,p[1]+=At,g=a(p[0],p[1]))),g!==s)c=0,g?(t.lineStart(),d=i(p,e),t.point(d[0],d[1])):(d=i(e,p),t.point(d[0],d[1]),t.lineEnd()),e=d;else if(n&&e&&r^g){var m;v&l||!(m=i(p,e,!0))||(c=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&zr(e,p)||t.point(p[0],p[1]),e=p,s=g,l=v},lineEnd:function(){s&&t.lineEnd(),e=null},clean:function(){return c|(u&&s)<<1}}},In(t,6*St),r?[0,-t]:[-Tt,t-Tt]);function a(t,r){return Math.cos(t)*Math.cos(r)>e}function i(t,r,n){var a=[1,0,0],i=Rr(Or(t),Or(r)),o=Dr(i,i),l=i[0],s=o-l*l;if(!s)return!n&&t;var u=e*o/s,c=-e*l/s,f=Rr(a,i),h=Ir(a,u);Pr(h,Ir(i,c));var d=f,p=Dr(h,d),g=Dr(d,d),v=p*p-g*(Dr(h,h)-1);if(!(v<0)){var m=Math.sqrt(v),x=Ir(d,(-p-m)/g);if(Pr(x,h),x=Fr(x),!n)return x;var b,_=t[0],w=r[0],A=t[1],M=r[1];w<_&&(b=_,_=w,w=b);var T=w-_,k=y(T-Tt)0^x[1]<(y(x[0]-_)Tt^(_<=x[0]&&x[0]<=w)){var E=Ir(d,(-p+m)/g);return Pr(E,h),[x,Fr(E)]}}}function o(e,n){var a=r?t:Tt-t,i=0;return e<-a?i|=1:e>a&&(i|=2),n<-a?i|=4:n>a&&(i|=8),i}}((b=+t)*St),T()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):O,T()):_},w.scale=function(t){return arguments.length?(u=+t,M()):u},w.translate=function(t){return arguments.length?(c=+t[0],f=+t[1],M()):[c,f]},w.center=function(t){return arguments.length?(h=t[0]%360*St,d=t[1]%360*St,M()):[h*Lt,d*Lt]},w.rotate=function(t){return arguments.length?(p=t[0]%360*St,g=t[1]%360*St,v=t.length>2?t[2]%360*St:0,M()):[p*Lt,g*Lt,v*Lt]},t.rebind(w,s,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&A,M()}}function Cn(t){return Tn(t,function(e,r){t.point(e*St,r*St)})}function Sn(t,e){return[t,e]}function Ln(t,e){return[t>Tt?t-kt:t<-Tt?t+kt:t,e]}function On(t,e,r){return t?e||r?Gr(Rn(t),Pn(e,r)):Rn(t):e||r?Pn(e,r):Ln}function Dn(t){return function(e,r){return[(e+=t)>Tt?e-kt:e<-Tt?e+kt:e,r]}}function Rn(t){var e=Dn(t);return e.invert=Dn(-t),e}function Pn(t,e){var r=Math.cos(t),n=Math.sin(t),a=Math.cos(e),i=Math.sin(e);function o(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,u=Math.sin(e),c=u*r+l*n;return[Math.atan2(s*a-c*i,l*r-u*n),Pt(c*a+s*i)]}return o.invert=function(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,u=Math.sin(e),c=u*a-s*i;return[Math.atan2(s*a+u*i,l*r+c*n),Pt(c*r-l*n)]},o}function In(t,e){var r=Math.cos(t),n=Math.sin(t);return function(a,i,o,l){var s=o*e;null!=a?(a=Bn(r,a),i=Bn(r,i),(o>0?ai)&&(a+=o*kt)):(a=t+o*kt,i=t-.5*s);for(var u,c=a;o>0?c>i:c2?t[2]*St:0),e.invert=function(e){return(e=t.invert(e[0]*St,e[1]*St))[0]*=Lt,e[1]*=Lt,e},e},Ln.invert=Sn,t.geo.circle=function(){var t,e,r=[0,0],n=6;function a(){var t="function"==typeof r?r.apply(this,arguments):r,n=On(-t[0]*St,-t[1]*St,0).invert,a=[];return e(null,null,1,{point:function(t,e){a.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(t){return arguments.length?(r=t,a):r},a.angle=function(r){return arguments.length?(e=In((t=+r)*St,n*St),a):t},a.precision=function(r){return arguments.length?(e=In(t*St,(n=+r)*St),a):n},a.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*St,a=t[1]*St,i=e[1]*St,o=Math.sin(n),l=Math.cos(n),s=Math.sin(a),u=Math.cos(a),c=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((r=f*o)*r+(r=u*c-s*f*l)*r),s*c+u*f*l)},t.geo.graticule=function(){var e,r,n,a,i,o,l,s,u,c,f,h,d=10,p=d,g=90,v=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,n,g).map(f).concat(t.range(Math.ceil(s/v)*v,l,v).map(h)).concat(t.range(Math.ceil(r/d)*d,e,d).filter(function(t){return y(t%g)>At}).map(u)).concat(t.range(Math.ceil(o/p)*p,i,p).filter(function(t){return y(t%v)>At}).map(c))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(h(l).slice(1),f(n).reverse().slice(1),h(s).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(a=+t[0][0],n=+t[1][0],s=+t[0][1],l=+t[1][1],a>n&&(t=a,a=n,n=t),s>l&&(t=s,s=l,l=t),x.precision(m)):[[a,s],[n,l]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],r>e&&(t=r,r=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(m)):[[r,o],[e,i]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],x):[g,v]},x.minorStep=function(t){return arguments.length?(d=+t[0],p=+t[1],x):[d,p]},x.precision=function(t){return arguments.length?(m=+t,u=Fn(o,i,90),c=zn(r,e,m),f=Fn(s,l,90),h=zn(a,n,m),x):m},x.majorExtent([[-180,-90+At],[180,90-At]]).minorExtent([[-180,-80-At],[180,80+At]])},t.geo.greatArc=function(){var e,r,n=Nn,a=jn;function i(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||a.apply(this,arguments))},i.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,i):n},i.target=function(t){return arguments.length?(a=t,r="function"==typeof t?null:t,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(t,e){return r=t[0]*St,n=t[1]*St,a=e[0]*St,i=e[1]*St,o=Math.cos(n),l=Math.sin(n),s=Math.cos(i),u=Math.sin(i),c=o*Math.cos(r),f=o*Math.sin(r),h=s*Math.cos(a),d=s*Math.sin(a),p=2*Math.asin(Math.sqrt(Bt(i-n)+o*s*Bt(a-r))),g=1/Math.sin(p),(v=p?function(t){var e=Math.sin(t*=p)*g,r=Math.sin(p-t)*g,n=r*c+e*h,a=r*f+e*d,i=r*l+e*u;return[Math.atan2(a,n)*Lt,Math.atan2(i,Math.sqrt(n*n+a*a))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=p,v;var r,n,a,i,o,l,s,u,c,f,h,d,p,g,v},t.geo.length=function(e){return mn=0,t.geo.stream(e,Un),mn};var Un={sphere:I,point:I,lineStart:function(){var t,e,r;function n(n,a){var i=Math.sin(a*=St),o=Math.cos(a),l=y((n*=St)-t),s=Math.cos(l);mn+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=r*i-e*o*s)*l),e*i+r*o*s),t=n,e=i,r=o}Un.point=function(a,i){t=a*St,e=Math.sin(i*=St),r=Math.cos(i),Un.point=n},Un.lineEnd=function(){Un.point=Un.lineEnd=I}},lineEnd:I,polygonStart:I,polygonEnd:I};function Vn(t,e){function r(e,r){var n=Math.cos(e),a=Math.cos(r),i=t(n*a);return[i*a*Math.sin(e),i*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),a=e(n),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(t*i,n*o),Math.asin(n&&r*i/n)]},r}var Hn=Vn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return kn(Hn)}).raw=Hn;var qn=Vn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},O);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},a=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),i=r*Math.pow(n(t),a)/a;if(!a)return Wn;function o(t,e){i>0?e<-Ct+At&&(e=-Ct+At):e>Ct-At&&(e=Ct-At);var r=i/Math.pow(n(e),a);return[r*Math.sin(a*t),i-r*Math.cos(a*t)]}return o.invert=function(t,e){var r=i-e,n=Ot(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(i/n,1/a))-Ct]},o}function Xn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),a=r/n+t;if(y(n)1&&Dt(t[r[n-2]],t[r[n-1]],t[a])<=0;)--n;r[n++]=a}return r.slice(0,n)}function ra(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return kn(Qn)}).raw=Qn,$n.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(t.geo.transverseMercator=function(){var t=Zn($n),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=$n,t.geom={},t.geom.hull=function(t){var e=Kn,r=ta;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,a=ve(e),i=ve(r),o=t.length,l=[],s=[];for(n=0;n=0;--n)d.push(t[l[u[n]][2]]);for(n=+f;nAt)l=l.L;else{if(!((a=i-xa(l,o))>At)){n>-At?(e=l.P,r=l):a>-At?(e=l,r=l.N):e=r=l;break}if(!l.R){e=l;break}l=l.R}var s=pa(t);if(ua.insert(e,s),e||r){if(e===r)return Aa(e),r=pa(e.site),ua.insert(s,r),s.edge=r.edge=ka(e.site,s.site),wa(e),void wa(r);if(r){Aa(e),Aa(r);var u=e.site,c=u.x,f=u.y,h=t.x-c,d=t.y-f,p=r.site,g=p.x-c,v=p.y-f,m=2*(h*v-d*g),y=h*h+d*d,x=g*g+v*v,b={x:(v*y-d*x)/m+c,y:(h*x-g*y)/m+f};Ea(r.edge,u,p,b),s.edge=ka(u,t,null,b),r.edge=ka(t,p,null,b),wa(e),wa(r)}else s.edge=ka(e.site,s.site)}}function ya(t,e){var r=t.site,n=r.x,a=r.y,i=a-e;if(!i)return n;var o=t.P;if(!o)return-1/0;var l=(r=o.site).x,s=r.y,u=s-e;if(!u)return l;var c=l-n,f=1/i-1/u,h=c/u;return f?(-h+Math.sqrt(h*h-2*f*(c*c/(-2*u)-s+u/2+a-i/2)))/f+n:(n+l)/2}function xa(t,e){var r=t.N;if(r)return ya(r,e);var n=t.site;return n.y===e?n.x:1/0}function ba(t){this.site=t,this.edges=[]}function _a(t,e){return e.angle-t.angle}function wa(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,a=t.site,i=r.site;if(n!==i){var o=a.x,l=a.y,s=n.x-o,u=n.y-l,c=i.x-o,f=2*(s*(v=i.y-l)-u*c);if(!(f>=-Mt)){var h=s*s+u*u,d=c*c+v*v,p=(v*h-u*d)/f,g=(s*d-c*h)/f,v=g+l,m=da.pop()||new function(){La(this),this.x=this.y=this.arc=this.site=this.cy=null};m.arc=t,m.site=a,m.x=p+o,m.y=v+Math.sqrt(p*p+g*g),m.cy=v,t.circle=m;for(var y=null,x=fa._;x;)if(m.y=l)return;if(h>p){if(i){if(i.y>=u)return}else i={x:v,y:s};r={x:v,y:u}}else{if(i){if(i.y1)if(h>p){if(i){if(i.y>=u)return}else i={x:(s-a)/n,y:s};r={x:(u-a)/n,y:u}}else{if(i){if(i.y=l)return}else i={x:o,y:n*o+a};r={x:l,y:n*l+a}}else{if(i){if(i.xAt||y(a-r)>At)&&(l.splice(o,0,new Ca((m=i.site,x=c,b=y(n-f)At?{x:f,y:y(e-f)At?{x:y(r-p)At?{x:h,y:y(e-h)At?{x:y(r-d)=r&&u.x<=a&&u.y>=n&&u.y<=o?[[r,o],[a,o],[a,n],[r,n]]:[]).point=t[l]}),e}function l(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/At)*At,y:Math.round(a(t,e)/At)*At,i:e}})}return o.links=function(t){return Pa(l(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Pa(l(t)).cells.forEach(function(r,n){for(var a,i,o,l,s=r.site,u=r.edges.sort(_a),c=-1,f=u.length,h=u[f-1].edge,d=h.l===s?h.r:h.l;++ci&&(a=e.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(r=r[0])===(n=n[0])?l[o]?l[o]+=n:l[++o]=n:(l[++o]=null,s.push({i:o,x:Ua(r,n)})),i=qa.lastIndex;return ig&&(g=s.x),s.y>v&&(v=s.y),u.push(s.x),c.push(s.y);else for(f=0;fg&&(g=b),_>v&&(v=_),u.push(b),c.push(_)}var w=g-d,A=v-p;function M(t,e,r,n,a,i,o,l){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var s=t.x,u=t.y;if(null!=s)if(y(s-r)+y(u-n)<.01)T(t,e,r,n,a,i,o,l);else{var c=t.point;t.x=t.y=t.point=null,T(t,c,s,u,a,i,o,l),T(t,e,r,n,a,i,o,l)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,a,i,o,l)}function T(t,e,r,n,a,i,o,l){var s=.5*(a+o),u=.5*(i+l),c=r>=s,f=n>=u,h=f<<1|c;t.leaf=!1,t=t.nodes[h]||(t.nodes[h]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(k,t,+m(t,++f),+x(t,f),d,p,g,v)}}),c?a=s:o=s,f?i=u:l=u,M(t,e,r,n,a,i,o,l)}w>A?v=p+w:g=d+A;var k={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(k,t,+m(t,++f),+x(t,f),d,p,g,v)}};if(k.visit=function(t){!function t(e,r,n,a,i,o){if(!e(r,n,a,i,o)){var l=.5*(n+i),s=.5*(a+o),u=r.nodes;u[0]&&t(e,u[0],n,a,l,s),u[1]&&t(e,u[1],l,a,i,s),u[2]&&t(e,u[2],n,s,l,o),u[3]&&t(e,u[3],l,s,i,o)}}(t,k,d,p,g,v)},k.find=function(t){return function(t,e,r,n,a,i,o){var l,s=1/0;return function t(u,c,f,h,d){if(!(c>i||f>o||h=_)<<1|e>=b,A=w+4;w=0&&!(n=t.interpolators[a](e,r)););return n}function Xa(t,e){var r,n=[],a=[],i=t.length,o=e.length,l=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ei(t){return 1-Math.cos(t*Ct)}function ri(t){return Math.pow(2,10*(t-1))}function ni(t){return 1-Math.sqrt(1-t*t)}function ai(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}function ii(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oi(t){var e,r,n,a=[t.a,t.b],i=[t.c,t.d],o=si(a),l=li(a,i),s=si(((e=i)[0]+=(n=-l)*(r=a)[0],e[1]+=n*r[1],e))||0;a[0]*i[1]=0?t.slice(0,n):t,i=n>=0?t.slice(n+1):"in";return a=Wa.get(a)||Ya,i=Za.get(i)||O,r=i(a.apply(null,e.call(arguments,1))),function(t){return t<=0?0:t>=1?1:r(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,a=e.c,i=e.l,o=r.h-n,l=r.c-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.c:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Yt(n+o*t,a+l*t,i+s*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,a=e.s,i=e.l,o=r.h-n,l=r.s-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.s:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return qt(n+o*t,a+l*t,i+s*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,a=e.a,i=e.b,o=r.l-n,l=r.a-a,s=r.b-i;return function(t){return te(n+o*t,a+l*t,i+s*t)+""}},t.interpolateRound=ii,t.transform=function(e){var r=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oi(e?e.matrix:ui)})(e)},oi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ui={a:1,b:0,c:0,d:1,e:0,f:0};function ci(t){return t.length?t.pop()+",":""}function fi(e,r){var n=[],a=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push("translate(",null,",",null,")");n.push({i:a-4,x:Ua(t[0],e[0])},{i:a-2,x:Ua(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,a),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ci(r)+"rotate(",null,")")-2,x:Ua(t,e)})):e&&r.push(ci(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,a),function(t,e,r,n){t!==e?n.push({i:r.push(ci(r)+"skewX(",null,")")-2,x:Ua(t,e)}):e&&r.push(ci(r)+"skewX("+e+")")}(e.skew,r.skew,n,a),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push(ci(r)+"scale(",null,",",null,")");n.push({i:a-4,x:Ua(t[0],e[0])},{i:a-2,x:Ua(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ci(r)+"scale("+e+")")}(e.scale,r.scale,n,a),e=r=null,function(t){for(var e,r=-1,i=a.length;++r0?n=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:n=0})):t>0&&(s.start({type:"start",alpha:n=t}),e=Me(l.tick)),l):n},l.start=function(){var t,e,r,n=m.length,s=y.length,c=u[0],p=u[1];for(t=0;t=0;)r.push(a[n])}function Ti(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(i=t.children)&&(a=i.length))for(var a,i,o=-1;++o=0;)o.push(c=u[s]),c.parent=i,c.depth=i.depth+1;r&&(i.value=0),i.children=u}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Ti(a,function(e){var n,a;t&&(n=e.children)&&n.sort(t),r&&(a=e.parent)&&(a.value+=e.value)}),l}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Mi(t,function(t){t.children&&(t.value=0)}),Ti(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var a=e.call(this,t,n);return function t(e,r,n,a){var i=e.children;if(e.x=r,e.y=e.depth*a,e.dx=n,e.dy=a,i&&(o=i.length)){var o,l,s,u=-1;for(n=e.value?n/e.value:0;++ul&&(l=n),o.push(n)}for(r=0;ra&&(n=r,a=e);return n}function Ni(t){return t.reduce(ji,0)}function ji(t,e){return t+e[1]}function Ui(t,e){return Vi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Vi(t,e){for(var r=-1,n=+t[0],a=(t[1]-n)/e,i=[];++r<=e;)i[r]=a*r+n;return i}function Hi(e){return[t.min(e),t.max(e)]}function qi(t,e){return t.value-e.value}function Gi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Xi(t,e){t._pack_next=e,e._pack_prev=t}function Yi(t,e){var r=e.x-t.x,n=e.y-t.y,a=t.r+e.r;return.999*a*a>r*r+n*n}function Wi(t){if((e=t.children)&&(s=e.length)){var e,r,n,a,i,o,l,s,u=1/0,c=-1/0,f=1/0,h=-1/0;if(e.forEach(Zi),(r=e[0]).x=-r.r,r.y=0,x(r),s>1&&((n=e[1]).x=n.r,n.y=0,x(n),s>2))for(Qi(r,n,a=e[2]),x(a),Gi(r,a),r._pack_prev=a,Gi(a,n),n=r._pack_next,i=3;i0)for(o=-1;++o=f[0]&&s<=f[1]&&((l=u[t.bisect(h,s,1,p)-1]).y+=g,l.push(i[o]));return u}return i.value=function(t){return arguments.length?(r=t,i):r},i.range=function(t){return arguments.length?(n=ve(t),i):n},i.bins=function(t){return arguments.length?(a="number"==typeof t?function(e){return Vi(e,t)}:ve(t),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(qi),n=0,a=[1,1];function i(t,i){var o=r.call(this,t,i),l=o[0],s=a[0],u=a[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Ti(l,function(t){t.r=+c(t.value)}),Ti(l,Wi),n){var f=n*(e?1:Math.max(2*l.r/s,2*l.r/u))/2;Ti(l,function(t){t.r+=f}),Ti(l,Wi),Ti(l,function(t){t.r-=f})}return function t(e,r,n,a){var i=e.children;e.x=r+=a*e.x;e.y=n+=a*e.y;e.r*=a;if(i)for(var o=-1,l=i.length;++od.x&&(d=t),t.depth>p.depth&&(p=t)});var g=r(h,d)/2-h.x,v=n[0]/(d.x+r(d,h)/2+g),m=n[1]/(p.depth||1);Mi(c,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return u}function o(t){var e=t.children,n=t.parent.children,a=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,a=t.children,i=a.length;for(;--i>=0;)(e=a[i]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var i=(e[0].z+e[e.length-1].z)/2;a?(t.z=a.z+r(t._,a._),t.m=t.z-i):t.z=i}else a&&(t.z=a.z+r(t._,a._));t.parent.A=function(t,e,n){if(e){for(var a,i=t,o=t,l=e,s=i.parent.children[0],u=i.m,c=o.m,f=l.m,h=s.m;l=to(l),i=Ki(i),l&&i;)s=Ki(s),(o=to(o)).a=t,(a=l.z+f-i.z-u+r(l._,i._))>0&&(eo(ro(l,t,n),t,a),u+=a,c+=a),f+=l.m,u+=i.m,h+=s.m,c+=o.m;l&&!to(o)&&(o.t=l,o.m+=f-c),i&&!Ki(s)&&(s.t=i,s.m+=u-h,n=t)}return n}(t,a,t.parent.A||n[0])}function l(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function s(t){t.x*=n[0],t.y=t.depth*n[1]}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t)?s:null,i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null==(n=t)?null:s,i):a?n:null},Ai(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=$i,n=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),u=s[0],c=0;Ti(u,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=l?c+=r(e,l):0,e.y=0,l=e)});var f=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),h=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),d=f.x-r(f,h)/2,p=h.x+r(h,f)/2;return Ti(u,a?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-d)/(p-d)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),s}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t),i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null!=(n=t),i):a?n:null},Ai(i,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,a=[1,1],i=null,o=no,l=!1,s="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,a=-1,i=t.length;++a0;)l.push(r=u[a-1]),l.area+=r.area,"squarify"!==s||(n=d(l,g))<=h?(u.pop(),h=n):(l.area-=l.pop().area,p(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,h=1/0);l.length&&(p(l,g,i,!0),l.length=l.area=0),e.forEach(f)}}function h(t){var e=t.children;if(e&&e.length){var r,n=o(t),a=e.slice(),i=[];for(c(a,n.dx*n.dy/t.value),i.area=0;r=a.pop();)i.push(r),i.area+=r.area,null!=r.z&&(p(i,r.z?n.dx:n.dy,n,!a.length),i.length=i.area=0);e.forEach(h)}}function d(t,e){for(var r,n=t.area,a=0,i=1/0,o=-1,l=t.length;++oa&&(a=r));return e*=e,(n*=n)?Math.max(e*a*u/n,n/(e*i*u)):1/0}function p(t,e,r,a){var i,o=-1,l=t.length,s=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((a||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?fo:lo,l=a?di:hi;return i=t(e,r,l,n),o=t(r,e,l,Ga),s}function s(t){return i(t)}s.invert=function(t){return o(t)};s.domain=function(t){return arguments.length?(e=t.map(Number),l()):e};s.range=function(t){return arguments.length?(r=t,l()):r};s.rangeRound=function(t){return s.range(t).interpolate(ii)};s.clamp=function(t){return arguments.length?(a=t,l()):a};s.interpolate=function(t){return arguments.length?(n=t,l()):n};s.ticks=function(t){return vo(e,t)};s.tickFormat=function(t,r){return mo(e,t,r)};s.nice=function(t){return po(e,t),l()};s.copy=function(){return t(e,r,n,a)};return l()}([0,1],[0,1],Ga,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function xo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,a,i){function o(t){return(a?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function l(t){return a?Math.pow(n,t):-Math.pow(n,-t)}function s(t){return r(o(t))}s.invert=function(t){return l(r.invert(t))};s.domain=function(t){return arguments.length?(a=t[0]>=0,r.domain((i=t.map(Number)).map(o)),s):i};s.base=function(t){return arguments.length?(n=+t,r.domain(i.map(o)),s):n};s.nice=function(){var t=so(i.map(o),a?Math:_o);return r.domain(t),i=t.map(l),s};s.ticks=function(){var t=io(i),e=[],r=t[0],s=t[1],u=Math.floor(o(r)),c=Math.ceil(o(s)),f=n%1?2:n;if(isFinite(c-u)){if(a){for(;u0;h--)e.push(l(u)*h);for(u=0;e[u]s;c--);e=e.slice(u,c)}return e};s.tickFormat=function(e,r){if(!arguments.length)return bo;arguments.length<2?r=bo:"function"!=typeof r&&(r=t.format(r));var a=Math.max(1,n*e/s.ticks().length);return function(t){var e=t/l(Math.round(o(t)));return e*n0?a[t-1]:r[0],tf?0:1;if(u=Et)return s(u,d)+(l?s(l,1-d):"")+"Z";var p,g,v,m,y,x,b,_,w,A,M,T,k=0,E=0,C=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Co?Math.sqrt(l*l+u*u):+n.apply(this,arguments),d||(E*=-1),u&&(E=Pt(v/u*Math.sin(m))),l&&(k=Pt(v/l*Math.sin(m)))),u){y=u*Math.cos(c+E),x=u*Math.sin(c+E),b=u*Math.cos(f-E),_=u*Math.sin(f-E);var S=Math.abs(f-c-2*E)<=Tt?0:1;if(E&&Po(y,x,b,_)===d^S){var L=(c+f)/2;y=u*Math.cos(L),x=u*Math.sin(L),b=_=null}}else y=x=0;if(l){w=l*Math.cos(f-k),A=l*Math.sin(f-k),M=l*Math.cos(c+k),T=l*Math.sin(c+k);var O=Math.abs(c-f+2*k)<=Tt?0:1;if(k&&Po(w,A,M,T)===1-d^O){var D=(c+f)/2;w=l*Math.cos(D),A=l*Math.sin(D),M=T=null}}else w=A=0;if(h>At&&(p=Math.min(Math.abs(u-l)/2,+r.apply(this,arguments)))>.001){g=l0?0:1}function Io(t,e,r,n,a){var i=t[0]-e[0],o=t[1]-e[1],l=(a?n:-n)/Math.sqrt(i*i+o*o),s=l*o,u=-l*i,c=t[0]+s,f=t[1]+u,h=e[0]+s,d=e[1]+u,p=(c+h)/2,g=(f+d)/2,v=h-c,m=d-f,y=v*v+m*m,x=r-n,b=c*d-h*f,_=(m<0?-1:1)*Math.sqrt(Math.max(0,x*x*y-b*b)),w=(b*m-v*_)/y,A=(-b*v-m*_)/y,M=(b*m+v*_)/y,T=(-b*v+m*_)/y,k=w-p,E=A-g,C=M-p,S=T-g;return k*k+E*E>C*C+S*S&&(w=M,A=T),[[w-s,A-u],[w*r/x,A*r/x]]}function Bo(t){var e=Kn,r=ta,n=Xr,a=zo,i=a.key,o=.7;function l(i){var l,s=[],u=[],c=-1,f=i.length,h=ve(e),d=ve(r);function p(){s.push("M",a(t(u),o))}for(;++c1&&a.push("H",n[0]);return a.join("")},"step-before":jo,"step-after":Uo,basis:qo,"basis-open":function(t){if(t.length<4)return zo(t);var e,r=[],n=-1,a=t.length,i=[0],o=[0];for(;++n<3;)e=t[n],i.push(e[0]),o.push(e[1]);r.push(Go(Wo,i)+","+Go(Wo,o)),--n;for(;++n9&&(a=3*e/Math.sqrt(a),o[l]=a*r,o[l+1]=a*n));l=-1;for(;++l<=s;)a=(t[Math.min(s,l+1)][0]-t[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(t))}});function zo(t){return t.length>1?t.join("L"):t+"Z"}function No(t){return t.join("L")+"Z"}function jo(t){for(var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];++e1){l=e[1],i=t[s],s++,n+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var u=2;uTt)+",1 "+e}function s(t,e,r,n){return"Q 0,0 "+n}return i.radius=function(t){return arguments.length?(r=ve(t),i):r},i.source=function(e){return arguments.length?(t=ve(e),i):t},i.target=function(t){return arguments.length?(e=ve(t),i):e},i.startAngle=function(t){return arguments.length?(n=ve(t),i):n},i.endAngle=function(t){return arguments.length?(a=ve(t),i):a},i},t.svg.diagonal=function(){var t=Nn,e=jn,r=tl;function n(n,a){var i=t.call(this,n,a),o=e.call(this,n,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(r))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=tl,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=rl,e=el;function r(r,n){return(al.get(t.call(this,r,n))||nl)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var al=t.map({circle:nl,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*ol)),r=e*ol;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/il),r=e*il/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/il),r=e*il/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=al.keys();var il=Math.sqrt(3),ol=Math.tan(30*St);Y.transition=function(t){for(var e,r,n=cl||++dl,a=vl(t),i=[],o=fl||{time:Date.now(),ease:ti,delay:0,duration:250},l=-1,s=this.length;++l0;)u[--h].call(t,o);if(i>=1)return f.event&&f.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}f||(i=a.time,o=Me(function(t){var e=f.delay;if(o.t=e+i,e<=t)return h(t-e);o.c=h},0,i),f=c[n]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:e},a=null,++c.count)}hl.call=Y.call,hl.empty=Y.empty,hl.node=Y.node,hl.size=Y.size,t.transition=function(e,r){return e&&e.transition?cl?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=hl,hl.select=function(t){var e,r,n,a=this.id,i=this.namespace,o=[];t=W(t);for(var l=-1,s=this.length;++lrect,.s>rect").attr("width",l[1]-l[0])}function g(t){t.select(".extent").attr("y",s[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function v(){var f,v,m=this,y=t.select(t.event.target),x=n.of(m,arguments),b=t.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&a,A=!/^(e|w)$/.test(_)&&i,M=y.classed("extent"),T=xt(m),k=t.mouse(m),E=t.select(o(m)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,k[0]-=l[1],k[1]-=s[1],M=2),z())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(k[0]+=l[1],k[1]+=s[1],M=0,z())});if(t.event.changedTouches?E.on("touchmove.brush",L).on("touchend.brush",D):E.on("mousemove.brush",L).on("mouseup.brush",D),b.interrupt().selectAll("*").interrupt(),M)k[0]=l[0]-k[0],k[1]=s[0]-k[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);v=[l[1-C]-k[0],s[1-S]-k[1]],k[0]=l[C],k[1]=s[S]}else t.event.altKey&&(f=k.slice());function L(){var e=t.mouse(m),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),k[0]=l[+(e[0]1?{floor:function(e){for(;l(e=t.floor(e));)e=Sl(e-1);return e},ceil:function(e){for(;l(e=t.ceil(e));)e=Sl(+e+1);return e}}:t))},a.ticks=function(t,e){var r=io(a.domain()),n=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Sl(+r[1]+1),e<1?1:e)},a.tickFormat=function(){return n},a.copy=function(){return Cl(e.copy(),r,n)},ho(a,e)}function Sl(t){return new Date(t)}Ml.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?El:kl,El.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},El.toString=kl.toString,Re.second=Fe(function(t){return new Pe(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Re.seconds=Re.second.range,Re.seconds.utc=Re.second.utc.range,Re.minute=Fe(function(t){return new Pe(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Re.minutes=Re.minute.range,Re.minutes.utc=Re.minute.utc.range,Re.hour=Fe(function(t){var e=t.getTimezoneOffset()/60;return new Pe(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Re.hours=Re.hour.range,Re.hours.utc=Re.hour.utc.range,Re.month=Fe(function(t){return(t=Re.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Re.months=Re.month.range,Re.months.utc=Re.month.utc.range;var Ll=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ol=[[Re.second,1],[Re.second,5],[Re.second,15],[Re.second,30],[Re.minute,1],[Re.minute,5],[Re.minute,15],[Re.minute,30],[Re.hour,1],[Re.hour,3],[Re.hour,6],[Re.hour,12],[Re.day,1],[Re.day,2],[Re.week,1],[Re.month,1],[Re.month,3],[Re.year,1]],Dl=Ml.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Xr]]),Rl={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Sl)},floor:O,ceil:O};Ol.year=Re.year,Re.scale=function(){return Cl(t.scale.linear(),Ol,Dl)};var Pl=Ol.map(function(t){return[t[0].utc,t[1]]}),Il=Tl.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Xr]]);function Bl(t){return JSON.parse(t.responseText)}function Fl(t){var e=a.createRange();return e.selectNode(a.body),e.createContextualFragment(t.responseText)}Pl.year=Re.year.utc,Re.scale.utc=function(){return Cl(t.scale.linear(),Pl,Il)},t.text=me(function(t){return t.responseText}),t.json=function(t,e){return ye(t,"application/json",Bl,e)},t.html=function(t,e){return ye(t,"text/html",Fl,e)},t.xml=me(function(t){return t.responseXML}),"function"==typeof CC&&CC.amd?(this.d3=t,CC(t)):n.exports?n.exports=t:this.d3=t}(),n=n.exports;var a=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},i={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},o={},l=Math.PI;o.deg2rad=function(t){return t/180*l},o.rad2deg=function(t){return t/l*180},o.wrap360=function(t){var e=t%360;return e<0?e+360:e},o.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var s=i.BADNUM,u=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,c={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,a=t.round,i=t.min,o=t.max,l=t.random;function s(l,u){if(l=l||"",u=u||{},l instanceof s)return l;if(!(this instanceof s))return new s(l,u);var c=function(n){var a={r:0,g:0,b:0},l=1,s=null,u=null,c=null,f=!1,h=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,a=!1;if(E[t])t=E[t],a=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=j.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=j.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=j.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=j.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=j.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=j.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=j.hex8.exec(t))return{r:D(n[1]),g:D(n[2]),b:D(n[3]),a:B(n[4]),format:a?"name":"hex8"};if(n=j.hex6.exec(t))return{r:D(n[1]),g:D(n[2]),b:D(n[3]),format:a?"name":"hex"};if(n=j.hex4.exec(t))return{r:D(n[1]+""+n[1]),g:D(n[2]+""+n[2]),b:D(n[3]+""+n[3]),a:B(n[4]+""+n[4]),format:a?"name":"hex8"};if(n=j.hex3.exec(t))return{r:D(n[1]+""+n[1]),g:D(n[2]+""+n[2]),b:D(n[3]+""+n[3]),format:a?"name":"hex"};return!1}(n));"object"==typeof n&&(U(n.r)&&U(n.g)&&U(n.b)?(d=n.r,p=n.g,g=n.b,a={r:255*L(d,255),g:255*L(p,255),b:255*L(g,255)},f=!0,h="%"===String(n.r).substr(-1)?"prgb":"rgb"):U(n.h)&&U(n.s)&&U(n.v)?(s=P(n.s),u=P(n.v),a=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var a=t.floor(e),i=e-a,o=n*(1-r),l=n*(1-i*r),s=n*(1-(1-i)*r),u=a%6;return{r:255*[n,l,o,o,s,n][u],g:255*[s,n,n,l,o,o][u],b:255*[o,o,s,n,n,l][u]}}(n.h,s,u),f=!0,h="hsv"):U(n.h)&&U(n.s)&&U(n.l)&&(s=P(n.s),c=P(n.l),a=function(t,e,r){var n,a,i;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=a=i=r;else{var l=r<.5?r*(1+e):r+e-r*e,s=2*r-l;n=o(s,l,t+1/3),a=o(s,l,t),i=o(s,l,t-1/3)}return{r:255*n,g:255*a,b:255*i}}(n.h,s,c),f=!0,h="hsl"),n.hasOwnProperty("a")&&(l=n.a));var d,p,g;return l=S(l),{ok:f,format:n.format||h,r:i(255,o(a.r,0)),g:i(255,o(a.g,0)),b:i(255,o(a.b,0)),a:l}}(l);this._originalInput=l,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=a(100*this._a)/100,this._format=u.format||c.format,this._gradientType=u.gradientType,this._r<1&&(this._r=a(this._r)),this._g<1&&(this._g=a(this._g)),this._b<1&&(this._b=a(this._b)),this._ok=c.ok,this._tc_id=n++}function u(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,a,l=o(t,e,r),s=i(t,e,r),u=(l+s)/2;if(l==s)n=a=0;else{var c=l-s;switch(a=u>.5?c/(2-l-s):c/(l+s),l){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+a)%360,i.push(s(n));return i}function k(t,e){e=e||6;for(var r=s(t).toHsv(),n=r.h,a=r.s,i=r.v,o=[],l=1/e;e--;)o.push(s({h:n,s:a,v:i})),i=(i+l)%1;return o}s.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,a=this.toRgb();return e=a.r/255,r=a.g/255,n=a.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=S(t),this._roundA=a(100*this._a)/100,this},toHsv:function(){var t=f(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=f(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=u(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=u(this._r,this._g,this._b),e=a(360*t.h),r=a(100*t.s),n=a(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return h(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,i){var o=[R(a(t).toString(16)),R(a(e).toString(16)),R(a(r).toString(16)),R(I(n))];if(i&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:a(this._r),g:a(this._g),b:a(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+a(this._r)+", "+a(this._g)+", "+a(this._b)+")":"rgba("+a(this._r)+", "+a(this._g)+", "+a(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:a(100*L(this._r,255))+"%",g:a(100*L(this._g,255))+"%",b:a(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+a(100*L(this._r,255))+"%, "+a(100*L(this._g,255))+"%, "+a(100*L(this._b,255))+"%)":"rgba("+a(100*L(this._r,255))+"%, "+a(100*L(this._g,255))+"%, "+a(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[h(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+d(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var a=s(t);r="#"+d(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return s(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(A,arguments)}},s.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:P(t[n]));t=r}return s(t,e)},s.equals=function(t,e){return!(!t||!e)&&s(t).toRgbString()==s(e).toRgbString()},s.random=function(){return s.fromRatio({r:l(),g:l(),b:l()})},s.mix=function(t,e,r){r=0===r?0:r||50;var n=s(t).toRgb(),a=s(e).toRgb(),i=r/100;return s({r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a})},s.readability=function(e,r){var n=s(e),a=s(r);return(t.max(n.getLuminance(),a.getLuminance())+.05)/(t.min(n.getLuminance(),a.getLuminance())+.05)},s.isReadable=function(t,e,r){var n,a,i=s.readability(t,e);switch(a=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},s.mostReadable=function(t,e,r){var n,a,i,o,l=null,u=0;a=(r=r||{}).includeFallbackColors,i=r.level,o=r.size;for(var c=0;cu&&(u=n,l=s(e[c]));return s.isReadable(t,l,{level:i,size:o})||!a?l:(r.includeFallbackColors=!1,s.mostReadable(t,["#fff","#000"],r))};var E=s.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"},C=s.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(E);function S(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=i(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function O(t){return i(1,o(0,t))}function D(t){return parseInt(t,16)}function R(t){return 1==t.length?"0"+t:""+t}function P(t){return t<=1&&(t=100*t+"%"),t}function I(e){return t.round(255*parseFloat(e)).toString(16)}function B(t){return D(t)/255}var F,z,N,j=(z="[\\s|\\(]+("+(F="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+F+")[,|\\s]+("+F+")\\s*\\)?",N="[\\s|\\(]+("+F+")[,|\\s]+("+F+")[,|\\s]+("+F+")[,|\\s]+("+F+")\\s*\\)?",{CSS_UNIT:new RegExp(F),rgb:new RegExp("rgb"+z),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+z),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+z),hsva:new RegExp("hsva"+N),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})$/});function U(t){return!!j.CSS_UNIT.exec(t)}c.exports?c.exports=s:"function"==typeof CC&&CC.amd?CC(function(){return s}):window.tinycolor=s}(Math),c=c.exports;var f={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},h=f.RdBu,d=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],a=t[e][1],o=!1,W(n))for(r=n.length-1;r>=0;r--)$(n[r],tt(a,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(i=Object.keys(n),o=!1,r=i.length-1;r>=0;r--)$(n[i[r]],tt(a,i[r]))?delete n[i[r]]:o=!0;if(o)return}}(s)):o[e[i]]=n}}function tt(t,e){var r=e;return a(e)?r="["+e+"]":t&&(r="."+e),t+r}function et(t,e,r,n){var a,i=W(r),o=!0,l=r,s=n.replace("-1",0),u=!i&&$(r,s),c=e[0];for(a=0;an.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,n){t%1||!a(t)||void 0!==n.min&&tn.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var a="number"==typeof t;!0!==n.strict&&a?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){c(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return c(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(p(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):a(t)?e.set(lt(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r,n){var a=n.regex||it(r);"string"==typeof t&&a.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!it(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var a=t.split("+"),i=0;i=ut&&t<=ct?t:dt;if("string"!=typeof t&&"number"!=typeof t)return dt;t=String(t);var r=At(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var a=r&&"chinese"===e.substr(0,7),i=t.match(a?_t:bt);if(!i)return dt;var o=i[1],l=i[3]||"1",s=Number(i[5]||1),u=Number(i[7]||0),c=Number(i[9]||0),f=Number(i[11]||0);if(r){if(2===o.length)return dt;var h;o=Number(o);try{var d=I.getComponentMethod("calendars","getCal")(e);if(a){var p="i"===l.charAt(l.length-1);l=parseInt(l,10),h=d.newDate(o,d.toMonthIndex(o,l,p),s)}else h=d.newDate(o,Number(l),s)}catch(t){return dt}return h?(h.toJD()-yt)*pt+u*gt+c*vt+f*mt:dt}o=2===o.length?(Number(o)+2e3-wt)%100+wt:Number(o),l-=1;var g=new Date(Date.UTC(2e3,l,s,u,c));return g.setUTCFullYear(o),g.getUTCMonth()!==l?dt:g.getUTCDate()!==s?dt:g.getTime()+f*mt},ut=ht.MIN_MS=ht.dateTime2ms("-9999"),ct=ht.MAX_MS=ht.dateTime2ms("9999-12-31 23:59:59.9999"),ht.isDateTime=function(t,e){return ht.dateTime2ms(t,e)!==dt};var Tt=90*pt,kt=3*gt,Et=5*vt;function Ct(t,e,r,n,a){if((e||r||n||a)&&(t+=" "+Mt(e,2)+":"+Mt(r,2),(n||a)&&(t+=":"+Mt(n,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;t+="."+Mt(a,i)}return t}ht.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ut&&t<=ct))return dt;e||(e=0);var n,a,i,o,l,s,u=Math.floor(10*ft(t+.05,1)),c=Math.round(t-u/10);if(At(r)){var f=Math.floor(c/pt)+yt,h=Math.floor(ft(t,pt));try{n=I.getComponentMethod("calendars","getCal")(r).fromJD(f).formatDate("yyyy-mm-dd")}catch(t){n=xt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;a=e=ut+pt&&t<=ct-pt))return dt;var e=Math.floor(10*ft(t+.05,1)),r=new Date(Math.round(t-e/10));return Ct(n.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+e)},ht.cleanDate=function(t,e,r){if(ht.isJSDate(t)||"number"==typeof t){if(At(r))return M.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ht.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ht.isDateTime(t,r))return M.error("unrecognized date",t),e;return t};var St=/%\d?f/g;function Lt(t,e,r,n){t=t.replace(St,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(e+.05));if(At(n))try{t=I.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(a)}var Ot=[59,59.9,59.99,59.999,59.9999];ht.formatDate=function(t,e,r,n,i,o){if(i=At(i)&&i,!e)if("y"===r)e=o.year;else if("m"===r)e=o.month;else{if("d"!==r)return function(t,e){var r=ft(t+.05,pt),n=Mt(Math.floor(r/gt),2)+":"+Mt(ft(Math.floor(r/vt),60),2);if("M"!==e){a(e)||(e=0);var i=(100+Math.min(ft(t/mt,60),Ot[e])).toFixed(e).substr(1);e>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),n+=":"+i}return n}(t,r)+"\n"+Lt(o.dayMonthYear,t,n,i);e=o.dayMonth+"\n"+o.year}return Lt(e,t,n,i)};var Dt=3*pt;ht.incrementMonth=function(t,e,r){r=At(r)&&r;var n=ft(t,pt);if(t=Math.round(t-n),r)try{var a=Math.round(t/pt)+yt,i=I.getComponentMethod("calendars","getCal")(r),o=i.fromJD(a);return e%12?i.add(o,e,"m"):i.add(o,e/12,"y"),(o.toJD()-yt)*pt+n}catch(e){M.error("invalid ms "+t+" in calendar "+r)}var l=new Date(t+Dt);return l.setUTCMonth(l.getUTCMonth()+e)+n-Dt},ht.findExactDates=function(t,e){for(var r,n,i=0,o=0,l=0,s=0,u=At(e)&&I.getComponentMethod("calendars","getCal")(e),c=0;c1||g<0||g>1?null:{x:t+s*g,y:e+f*g}}function jt(t,e,r,n,a){var i=n*t+a*e;if(i<0)return n*n+a*a;if(i>r){var o=n-t,l=a-e;return o*o+l*l}var s=n*e-a*t;return s*s/r}zt.segmentsIntersect=Nt,zt.segmentDistance=function(t,e,r,n,a,i,o,l){if(Nt(t,e,r,n,a,i,o,l))return 0;var s=r-t,u=n-e,c=o-a,f=l-i,h=s*s+u*u,d=c*c+f*f,p=Math.min(jt(s,u,h,a-t,i-e),jt(s,u,h,o-t,l-e),jt(c,f,d,t-a,e-i),jt(c,f,d,r-a,n-i));return Math.sqrt(p)},zt.getTextLocation=function(t,e,r,n){if(t===Bt&&n===Ft||(It={},Bt=t,Ft=n),It[r])return It[r];var a=t.getPointAtLength(ft(r-n/2,e)),i=t.getPointAtLength(ft(r+n/2,e)),o=Math.atan((i.y-a.y)/(i.x-a.x)),l=t.getPointAtLength(ft(r,e)),s={x:(4*l.x+a.x+i.x)/6,y:(4*l.y+a.y+i.y)/6,theta:o};return It[r]=s,s},zt.clearLocationCache=function(){Bt=null},zt.getVisibleSegment=function(t,e,r){var n,a,i=e.left,o=e.right,l=e.top,s=e.bottom,u=0,c=t.getTotalLength(),f=c;function h(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(a=r);var u=r.xo?r.x-o:0,f=r.ys?r.y-s:0;return Math.sqrt(u*u+f*f)}for(var d=h(u);d;){if((u+=d+r)>f)return;d=h(u)}for(d=h(f);d;){if(u>(f-=d+r))return;d=h(f)}return{min:u,max:f,len:f-u,total:c,isClosed:0===u&&f===c&&Math.abs(n.x-a.x)<.1&&Math.abs(n.y-a.y)<.1}},zt.findPointOnPath=function(t,e,r,n){for(var a,i,o,l=(n=n||{}).pathLength||t.getTotalLength(),s=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(l)[r]?-1:1,f=0,h=0,d=l;f0?d=a:h=a,f++}return i};var Ut=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},Vt=function(t){return t},Ht=/^\w*$/,qt={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Kt(t,e){return t>=e}Zt.findBin=function(t,e,r){if(a(e.start))return r?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var n,i,o=0,l=e.length,s=0,u=l>1?(e[l-1]-e[0])/(l-1):1;for(i=u>=0?r?Jt:Qt:r?Kt:$t,t+=1e-9*u*(r?-1:1)*(u>=0?1:-1);o90&&M.log("Long binary search..."),o-1},Zt.sorterAsc=function(t,e){return t-e},Zt.sorterDes=function(t,e){return e-t},Zt.distinctVals=function(t){var e=t.slice();e.sort(Zt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,a=n/(r||1)/1e4,i=[e[0]],o=0;oe[o]+a&&(n=Math.min(n,e[o+1]-e[o]),i.push(e[o+1]));return{vals:i,minDiff:n}},Zt.roundUp=function(t,e,r){for(var n,a=0,i=e.length-1,o=0,l=r?0:1,s=r?1:0,u=r?Math.ceil:Math.floor;ar.length)&&(n=r.length),a(e)||(e=!1),ee(r[0])){for(o=new Array(n),i=0;it.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]};var re={},ne={};function ae(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}re.throttle=function(t,e,r){var n=ne[t],a=Date.now();if(!n){for(var i in ne)ne[i].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},re.done=function(t){var e=ne[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},re.clear=function(t){if(t)ae(ne[t]),delete ne[t];else for(var e in ne)re.clear(e)};var ie=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var r=Math.log(Math.min(e[0],e[1]))/Math.LN10;return a(r)||(r=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),r},oe={},le=i.FP_SAFE,se=i.BADNUM,ue=oe={};ue.nestedProperty=Z,ue.keyedContainer=function(t,e,r,n){var a,i;r=r||"name",n=n||"value";var o={};i=e&&e.length?Z(t,e).get():t,e=e||"",i=i||[];var l={};for(a=0;a2)return o[e]=2|o[e],u.set(t,null);if(s){for(a=e;a/g),l=0;lle?se:a(t)?Number(t):se:se},ue.noop=E,ue.identity=Vt,ue.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},ue.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},ue.simpleMap=function(t,e,r,n){for(var a=t.length,i=new Array(a),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):l},ue.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},ue.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,a,i,o=t.length,l=2*o,s=2*e-1,u=new Array(s),c=new Array(o);for(r=0;r=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=t[a]*u[n];c[r]=i}return c},ue.syncOrAsync=function(t,e,r){var n;function a(){return ue.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(a).then(void 0,ue.promiseError);return r&&r(e)},ue.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},ue.noneOrAll=function(t,e,r){if(t){var n,a,i=!1,o=!0;for(n=0;n=0&&i%1==0){var p=n?n[d]:d,g=r?r[p]:p;f(g)&&(t[g].selected=1)}}},ue.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=ue.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ue.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,i,o=Object.keys(t);for(n=0;n1?a+o[1]:"";if(i&&(o.length>1||l.length>4||r))for(;n.test(l);)l=l.replace(n,"$1"+i+"$2");return l+s};var he=/%{([^\s%{}]*)}/g,de=/^\w*$/;ue.templateString=function(t,e){var r={};return t.replace(he,function(t,n){return de.test(n)?e[n]||"":(r[n]=r[n]||ue.nestedProperty(e,n).get,r[n]()||"")})};ue.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,a=0,i=0;i=48&&o<=57,u=l>=48&&l<=57;if(s&&(n=10*n+o-48),u&&(a=10*a+l-48),!s||!u){if(n!==a)return n-a;if(o!==l)return o-l}}return a-n};var pe=2e9;ue.seedPseudoRandom=function(){pe=2e9},ue.pseudoRandom=function(){var t=pe;return pe=(69069*pe+1)%4294967296,Math.abs(pe-t)<429496729?ue.pseudoRandom():pe/4294967296};var ge=oe.extendFlat,ve=oe.isPlainObject,me={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},ye={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},xe=me.flags.slice().concat(["clearCalc","fullReplot"]),be=ye.flags.slice().concat("layoutReplot"),_e={traces:me,layout:ye,traceFlags:function(){return we(xe)},layoutFlags:function(){return we(be)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),a=0;an?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},Re={};(function(t){"use strict";var e;e="function"!=typeof t.matchMedia||!t.matchMedia("(hover: none)").matches,Re=e}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Pe=function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){t=!1}return t}(),Ie={left:0,top:0},Be=function(t,e,r){e=e||t.currentTarget||t.srcElement,Array.isArray(r)||(r=[0,0]);var n=t.clientX||0,a=t.clientY||0,i=(o=e,o===window||o===document||o===document.body?Ie:o.getBoundingClientRect());var o;return r[0]=n-i.left,r[1]=a-i.top,r};var Fe=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];function ze(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var Ne=ze;function je(t){return"function"==typeof t}function Ue(t){return"object"==typeof t&&null!==t}function Ve(t){return void 0===t}ze.EventEmitter=ze,ze.prototype._events=void 0,ze.prototype._maxListeners=void 0,ze.defaultMaxListeners=10,ze.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},ze.prototype.emit=function(t){var e,r,n,a,i,o;if(this._events||(this._events={}),"error"===t&&(!this._events.error||Ue(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var l=new Error('Uncaught, unspecified "error" event. ('+e+")");throw l.context=e,l}if(Ve(r=this._events[t]))return!1;if(je(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(Ue(r))for(a=Array.prototype.slice.call(arguments,1),n=(o=r.slice()).length,i=0;i0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},ze.prototype.on=ze.prototype.addListener,ze.prototype.once=function(t,e){if(!je(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},ze.prototype.removeListener=function(t,e){var r,n,a,i;if(!je(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(a=(r=this._events[t]).length,n=-1,r===e||je(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Ue(r)){for(i=a;i-- >0;)if(r[i]===e||r[i].listener&&r[i].listener===e){n=i;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},ze.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(je(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},ze.prototype.listeners=function(t){return this._events&&this._events[t]?je(this._events[t])?[this._events[t]]:this._events[t].slice():[]},ze.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(je(e))return 1;if(e)return e.length}return 0},ze.listenerCount=function(t,e){return t.listenerCount(e)};var He,qe=Ne.EventEmitter,Ge={init:function(t){if(t._ev instanceof qe)return t;var e=new qe,r=new qe;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,a){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,a),e.emit(n,a),r.emit(n,a)},t},triggerHandler:function(t,e,r){var n,a;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var i=t._ev;if(!i)return n;var o=i._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var l=o.pop(),s=0;s4/3-l?o:l},We.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:oe.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:oe.constrain(Math.floor(3*e),0,2),Fe[e][t]},We.unhover=He.wrapped,We.unhoverRaw=He.raw,We.init=function(t){var e,r,n,a,i,o,l,s,u=t.gd,c=1,f=g.DBLCLICKDELAY,h=t.element;u._mouseDownTime||(u._mouseDownTime=0),h.style.pointerEvents="all",h.onmousedown=p,Pe?(h._ontouchstart&&h.removeEventListener("touchstart",h._ontouchstart),h._ontouchstart=p,h.addEventListener("touchstart",p,{passive:!1})):h.ontouchstart=p;var d=t.clampFn||function(t,e,r){return Math.abs(t)f&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!s){var r;try{r=new MouseEvent("click",e)}catch(t){var n=Je(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}l.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&I.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},We.coverSlip=Ze;function Qe(t,e,r,n){n=n||oe.identity,Array.isArray(t)&&(e[0][r]=n(t))}var $e={},Ke=$e={};Ke.defaults=D.defaults;var tr=Ke.defaultLine=D.defaultLine;Ke.lightLine=D.lightLine;var er=Ke.background=D.background;function rr(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var l=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+l+", "+n[3]+")":"rgb("+l+")"}Ke.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},Ke.rgb=function(t){return Ke.tinyRGB(c(t))},Ke.opacity=function(t){return t?c(t).getAlpha():0},Ke.addOpacity=function(t,e){var r=c(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},Ke.combine=function(t,e){var r=c(t).toRgb();if(1===r.a)return c(t).toRgbString();var n=c(e||er).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},i={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return c(i).toRgbString()},Ke.contrast=function(t,e,r){var n=c(t);return 1!==n.getAlpha()&&(n=c(Ke.combine(t,er))),(n.isDark()?e?n.lighten(e):er:r?n.darken(r):tr).toString()},Ke.stroke=function(t,e){var r=c(e);t.style({stroke:Ke.tinyRGB(r),"stroke-opacity":r.getAlpha()})},Ke.fill=function(t,e){var r=c(e);t.style({fill:Ke.tinyRGB(r),"fill-opacity":r.getAlpha()})},Ke.clean=function(t){if(t&&"object"==typeof t){var e,r,n,a,i=Object.keys(t);for(e=0;e=0;a--,i++)e=t[a],n[i]=[1-e[0],e[1]];return n},ir=function(t,e,r,n){var a,i;r?(a=oe.nestedProperty(t,r).get(),i=oe.nestedProperty(t._input,r).get()):(a=t,i=t._input);var o=n+"auto",l=n+"min",s=n+"max",u=a[o],c=a[l],h=a[s],d=a.colorscale;!1===u&&void 0!==c||(c=oe.aggNums(Math.min,null,e)),!1===u&&void 0!==h||(h=oe.aggNums(Math.max,null,e)),c===h&&(c-=.5,h+=.5),a[l]=c,a[s]=h,i[l]=c,i[s]=h,i[o]=!1!==u||void 0===c&&void 0===h,a.autocolorscale&&(d=c*h<0?f.RdBu:c>=0?f.Reds:f.Blues,i.colorscale=d,a.reversescale&&(d=ar(d)),a.colorscale=d)},or={dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},lr=or.dash,sr=b.extendFlat,ur={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:D.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks+margins"},titlefont:S({editType:"ticks+margins"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"axrange+margins",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"axrange+margins",impliedEdits:{"^autorange":!1}}],editType:"axrange+margins",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[Oe.idRegex.x.toString(),Oe.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks+margins",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks+margins"},tick0:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks+margins",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks+margins"},ticktext:{valType:"data_array",editType:"ticks+margins"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks+margins"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:D.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks+margins"},automargin:{valType:"boolean",dflt:!1,editType:"ticks+margins"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:sr({},lr,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:S({editType:"ticks+margins"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks+margins"},tickprefix:{valType:"string",dflt:"",editType:"ticks+margins"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},ticksuffix:{valType:"string",dflt:"",editType:"ticks+margins"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks+margins"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks+margins"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks+margins"},tickformat:{valType:"string",dflt:"",editType:"ticks+margins"},tickformatstops:{_isLinkedToArray:"tickformatstop",dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks+margins"},{valType:"any",editType:"ticks+margins"}],editType:"ticks+margins"},value:{valType:"string",dflt:"",editType:"ticks+margins"},editType:"ticks+margins"},hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:D.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:D.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:D.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",Oe.idRegex.x.toString(),Oe.idRegex.y.toString()],editType:"plot+margins"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot+margins"},overlaying:{valType:"enumerated",values:["free",Oe.idRegex.x.toString(),Oe.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot+margins"},{valType:"number",min:0,max:1,editType:"plot+margins"}],dflt:[0,1],editType:"plot+margins"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot+margins"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks+margins"}}},cr=b.extendFlat,fr=(0,_e.overrideAll)({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:.5,min:-2,max:3},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle"},ypad:{valType:"number",min:0,dflt:10},outlinecolor:ur.linecolor,outlinewidth:ur.linewidth,bordercolor:ur.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},tickmode:ur.tickmode,nticks:ur.nticks,tick0:ur.tick0,dtick:ur.dtick,tickvals:ur.tickvals,ticktext:ur.ticktext,ticks:cr({},ur.ticks,{dflt:""}),ticklen:ur.ticklen,tickwidth:ur.tickwidth,tickcolor:ur.tickcolor,showticklabels:ur.showticklabels,tickfont:S({}),tickangle:ur.tickangle,tickformat:ur.tickformat,tickformatstops:ur.tickformatstops,tickprefix:ur.tickprefix,showtickprefix:ur.showtickprefix,ticksuffix:ur.ticksuffix,showticksuffix:ur.showticksuffix,separatethousands:ur.separatethousands,exponentformat:ur.exponentformat,showexponent:ur.showexponent,title:{valType:"string"},titlefont:S({}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}},"colorbars","from-root"),hr=function(t,e,r,n,a){var i=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",i),r("ticksuffix",a.tickSuffixDflt)&&r("showticksuffix",i),r("showticklabels")){var o=a.font||{},l=e.color===t.color?e.color:o.color;if(oe.coerceFont(r,"tickfont",{family:o.family,size:o.size,color:l}),r("tickangle"),"category"!==n){var s=r("tickformat");!function(t,e){var r,n,a=t.tickformatstops,i=e.tickformatstops=[];if(!Array.isArray(a))return;function o(t,e){return oe.coerce(r,n,ur.tickformatstops,t,e)}for(var l=0;l0?Number(s):l;else if("string"!=typeof s)e.dtick=l;else{var u=s.charAt(0),c=s.substr(1);((c=a(c)?Number(c):0)<=0||!("date"===n&&"M"===u&&c===Math.round(c)||"log"===n&&"L"===u||"log"===n&&"D"===u&&(1===c||2===c)))&&(e.dtick=l)}var f="date"===n?oe.dateTick0(e.calendar):0,h=r("tick0",f);"date"===n?e.tick0=oe.cleanDate(h,f):a(h)&&"D1"!==s&&"D2"!==s?e.tick0=Number(h):e.tick0=f}else{void 0===r("tickvals")?e.tickmode="auto":r("ticktext")}},vr=function(t){return void 0!==f[t]||d(t)},mr=function(t,e,r,n,i){var o,l=i.prefix,s=i.cLetter,u=l.slice(0,l.length-1),c=l?oe.nestedProperty(t,u).get()||{}:t,f=l?oe.nestedProperty(e,u).get()||{}:e,h=c[s+"min"],d=c[s+"max"],p=c.colorscale;n(l+s+"auto",!(a(h)&&a(d)&&h","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},Mr={},Tr=wr.LINE_SPACING;function kr(t,e){return t.node().getBoundingClientRect()[e]}var Er=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;Mr.convertToTspans=function(t,e,r){var a=t.text(),i=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&a.match(Er),o=n.select(t.node().parentNode);if(!o.empty()){var l=t.attr("class")?t.attr("class").split(" ")[0]:"text";return l+="-math",o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove(),t.style("display",null).attr({"data-unformatted":a,"data-math":"N"}),i?(e&&e._promises||[]).push(new Promise(function(e){t.style("display","none");var u=parseInt(t.node().style.fontSize,10),c={fontSize:u};!function(t,e,r){var a="math-output-"+oe.randstr([],64),i=n.select("body").append("div").attr({id:a}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text((o=t,o.replace(Cr,"\\lt ").replace(Sr,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,i.node()],function(){var e=n.select("body").select("#MathJax_SVG_glyphs");if(i.select(".MathJax_SVG").empty()||!i.select("svg").node())oe.log("There was an error in the tex syntax.",t),r();else{var a=i.select("svg").node().getBoundingClientRect();r(i.select(".MathJax_SVG"),e,a)}i.remove()})}(i[2],c,function(n,i,c){o.selectAll("svg."+l).remove(),o.selectAll("g."+l+"-group").remove();var f=n&&n.select("svg");if(!f||!f.node())return s(),void e();var h=o.append("g").classed(l+"-group",!0).attr({"pointer-events":"none","data-unformatted":a,"data-math":"Y"});h.node().appendChild(f.node()),i&&i.node()&&f.node().insertBefore(i.node().cloneNode(!0),f.node().firstChild),f.attr({class:l,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var d=t.node().style.fill||"black";f.select("g").attr({fill:d,stroke:d});var p=kr(f,"width"),g=kr(f,"height"),v=+t.attr("x")-p*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],m=-(u||kr(t,"height"))/4;"y"===l[0]?(h.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-p/2,m-g/2]+")"}),f.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===l[0]?f.attr({x:t.attr("x"),y:m-g/2}):"a"===l[0]?f.attr({x:0,y:m}):f.attr({x:v,y:+t.attr("y")+m-g/2}),r&&r.call(t,h),e(h)})})):s(),t}function s(){o.empty()||(l=t.attr("class")+"-math",o.select("svg."+l).remove()),t.text("").style("white-space","pre"),function(t,e){e=(r=e,function(t,e){if(!t)return"";for(var r=0;r1)for(var i=1;i doesnt match end tag <"+t+">. Pretending it did match.",e),a=o[o.length-1].node}else oe.log("Ignoring unexpected end tag .",e)}jr.test(e)?s():(a=t,o=[{node:t}]);for(var h=e.split(zr),d=0;d|>|>)/g;var Lr={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"},Or={sub:"0.3em",sup:"-0.6em"},Dr={sub:"-0.21em",sup:"0.42em"},Rr="\u200b",Pr=["http:","https:","mailto:","",void 0,":"],Ir=new RegExp("]*)?/?>","g"),Br=Object.keys(Ar.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:Ar.entityToUnicode[t]}}),Fr=/(\r\n?|\n)/g,zr=/(<[^<>]*>)/,Nr=/<(\/?)([^ >]*)(\s+(.*))?>/i,jr=//i,Ur=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,Vr=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,Hr=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,qr=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function Gr(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var Xr=/(^|;)\s*color:/;function Yr(t,e,r){var n,a,i,o=r.horizontalAlign,l=r.verticalAlign||"top",s=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-n.height}:"middle"===l?function(){return s.top+(s.height-n.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-n.width}:"center"===o?function(){return s.left+(s.width-n.width)/2}:function(){return s.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:a()-u.top+"px",left:i()-u.left+"px","z-index":1e3}),this}}Mr.plainText=function(t){return(t||"").replace(Ir," ")},Mr.lineCount=function(t){return t.selectAll("tspan.line").size()||1},Mr.positionText=function(t,e,r){return t.each(function(){var t=n.select(this);function a(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var i=a("x",e),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},Mr.makeEditable=function(t,e){var r=e.gd,a=e.delegate,i=n.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){var a,l,u,c;a=n.select(r).select(".svg-container"),l=a.append("div"),u=t.node().style,c=parseFloat(u.fontSize||12),l.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:e.fill||u.fill||"black",opacity:1,"background-color":e.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(e.text||t.attr("data-unformatted")).call(Yr(t,a,e)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var e,a=n.select(this).attr("class");(e=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(e).style({opacity:0});var o=this.textContent;n.select(this).transition().duration(0).remove(),n.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,n.select(document).on("mouseup",function(){if(n.event.target===t)return!1;document.activeElement===l.node()&&l.node().blur()})}).on("keyup",function(){27===n.event.which?(r._editing=!1,t.style({opacity:1}),n.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),n.select(this).call(Yr(t,a,e)))}).on("keydown",function(){13===n.event.which&&this.blur()}).call(s),t.style({opacity:0});var f,h=o.attr("class");(f=h?"."+h.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(f).style({opacity:0})}function s(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return e.immediate?l():o.on("click",l),n.rebind(t,i,"on")};var Wr=function(t){var e=t.marker,r=e.sizeref||1,n=e.sizemin||0,i="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=i(t/2);return a(e)&&e>0?Math.max(e,n):0}},Zr={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return oe.isPlainObject(t.marker)&&oe.isArrayOrTypedArray(t.marker.size)}},Jr={},Qr=wr.LINE_SPACING,$r=g.DESELECTDIM,Kr=Jr={};Kr.font=function(t,e,r,n){oe.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call($e.fill,n)},Kr.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},Kr.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},Kr.setRect=function(t,e,r,n,a){t.call(Kr.setPosition,e,r).call(Kr.setSize,n,a)},Kr.translatePoint=function(t,e,r,n){var i=r.c2p(t.x),o=n.c2p(t.y);return!!(a(i)&&a(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",i).attr("y",o):e.attr("transform","translate("+i+","+o+")"),!0)},Kr.translatePoints=function(t,e,r){t.each(function(t){var a=n.select(this);Kr.translatePoint(t,a,e,r)})},Kr.hideOutsideRangePoint=function(t,e,r,n,a,i){e.attr("display",r.isPtWithinRange(t,a)&&n.isPtWithinRange(t,i)?null:"none")},Kr.hideOutsideRangePoints=function(t,e,r){if(e._hasClipOnAxisFalse){r=r||".point,.textpoint";var a=e.xaxis,i=e.yaxis;t.each(function(e){var o=e[0].trace,l=o.xcalendar,s=o.ycalendar;t.selectAll(r).each(function(t){Kr.hideOutsideRangePoint(t,n.select(this),a,i,l,s)})})}},Kr.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:e<1?1:Math.round(e):r||0},Kr.singleLineStyle=function(t,e,r,n,a){e.style("fill","none");var i=(((t||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,l=a||i.dash||"";$e.stroke(e,n||i.color),Kr.dashLine(e,l,o)},Kr.lineGroupStyle=function(t,e,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=e||i.width||0,l=a||i.dash||"";n.select(this).call($e.stroke,r||i.color).call(Kr.dashLine,l,o)})},Kr.dashLine=function(t,e,r){r=+r||0,e=Kr.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},Kr.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},Kr.singleFillStyle=function(t){var e=(((n.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;e&&t.call($e.fill,e)},Kr.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=n.select(this);try{r.call($e.fill,e[0].trace.fillcolor)}catch(e){oe.error(e,t),r.remove()}})},Kr.symbolNames=[],Kr.symbolFuncs=[],Kr.symbolNeedLines={},Kr.symbolNoDot={},Kr.symbolNoFill={},Kr.symbolList=[],Object.keys(_r).forEach(function(t){var e=_r[t];Kr.symbolList=Kr.symbolList.concat([e.n,t,e.n+100,t+"-open"]),Kr.symbolNames[e.n]=t,Kr.symbolFuncs[e.n]=e.f,e.needLine&&(Kr.symbolNeedLines[e.n]=!0),e.noDot?Kr.symbolNoDot[e.n]=!0:Kr.symbolList=Kr.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(Kr.symbolNoFill[e.n]=!0)});var tn=Kr.symbolNames.length,en="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function rn(t,e){var r=t%100;return Kr.symbolFuncs[r](e)+(t>=200?en:"")}Kr.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=Kr.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=tn||t>=400?0:Math.floor(Math.max(t,0))};var nn={x1:1,x2:0,y1:0,y2:0},an={x1:0,x2:0,y1:1,y2:0};Kr.gradient=function(t,e,r,a,i,o){var l=e._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+i+o],oe.identity);l.exit().remove(),l.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=n.select(this);"horizontal"===a?t.attr(nn):"vertical"===a&&t.attr(an),t.attr("id",r);var e=c(i),l=c(o);t.append("stop").attr({offset:"0%","stop-color":$e.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":$e.tinyRGB(e),"stop-opacity":e.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Kr.initGradients=function(t){oe.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},Kr.singlePointStyle=function(t,e,r,n,a,i){var o=r.marker;!function(t,e,r,n,a,i,o,l){if(I.traceIs(r,"symbols")){var s=Wr(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===i.size?3:Zr.isBubble(r)?s(t.ms):(i.size||6)/2,t.mrc=e;var n=Kr.symbolNumber(t.mx||i.symbol)||0;return t.om=n%200>=100,rn(n,e)})}e.style("opacity",function(t){return(t.mo+1||i.opacity+1)-1});var u,c,f,h=!1;if(t.so?(f=o.outlierwidth,c=o.outliercolor,u=i.outliercolor):(f=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=a(t.mlc):oe.isArrayOrTypedArray(o.color)?$e.defaultLine:o.color,oe.isArrayOrTypedArray(i.color)&&(u=$e.defaultLine,h=!0),u="mc"in t?t.mcc=n(t.mc):i.color||"rgba(0,0,0,0)"),t.om)e.call($e.stroke,u).style({"stroke-width":(f||1)+"px",fill:"none"});else{e.style("stroke-width",f+"px");var d=i.gradient,p=t.mgt;if(p?h=!0:p=d&&d.type,p&&"none"!==p){var g=t.mgc;g?h=!0:g=d.color;var v="g"+l._fullLayout._uid+"-"+r.uid;h&&(v+="-"+t.i),e.call(Kr.gradient,l,v,p,u,g)}else e.call($e.fill,u);f&&e.call($e.stroke,c)}}(t,e,r,n,a,o,o.line,i)},Kr.pointStyle=function(t,e,r){if(t.size()){var a=e.marker,i=Kr.tryColorscale(a,""),o=Kr.tryColorscale(a,"line");t.each(function(t){Kr.singlePointStyle(t,n.select(this),e,i,o,r)})}},Kr.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},a=t.marker||{},i=r.marker||{},o=n.marker||{},l=a.opacity,s=i.opacity,u=o.opacity,c=void 0!==s,f=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||f){if(!t.selected)return f?u:$r*(r?e:l);if(c)return s}};var h=i.color,d=o.color;(h||d)&&(e.colorFn=function(t){if(t.selected){if(h)return h}else if(d)return d});var p=i.size,g=o.size,v=void 0!==p,m=void 0!==g;return(v||m)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?v?p/2:e:m?g/2:e}),e},Kr.selectedPointStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=Kr.makeSelectedPointStyleFns(e),a=e.marker||{};t.each(function(t){var e=n.select(this),a=r.opacityFn(t);void 0!==a&&e.style("opacity",a)}),r.colorFn&&t.each(function(t){var e=n.select(this),a=r.colorFn(t);a&&$e.fill(e,a)}),I.traceIs(e,"symbols")&&r.sizeFn&&t.each(function(t){var e=n.select(this),i=t.mx||a.symbol||0,o=r.sizeFn(t);e.attr("d",rn(Kr.symbolNumber(i),o)),t.mrc2=o})}},Kr.tryColorscale=function(t,e){var r=e?oe.nestedProperty(t,e).get():t,n=r.colorscale,a=r.color;return n&&oe.isArrayOrTypedArray(a)?br.makeColorScaleFunc(br.extractScale(n,r.cmin,r.cmax)):oe.identity};var on={start:1,end:-1,middle:0,bottom:1,top:-1};function ln(t,e,r,a){var i=n.select(t.node().parentNode),o=-1!==e.indexOf("top")?"top":-1!==e.indexOf("bottom")?"bottom":"middle",l=-1!==e.indexOf("left")?"end":-1!==e.indexOf("right")?"start":"middle",s=a?a/.8+1:0,u=(Mr.lineCount(t)-1)*Qr+1,c=on[l]*s,f=.75*r+on[o]*s+(on[o]-1)*u*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+c+","+f+")")}function sn(t,e){var r=t.ts||e.textfont.size;return a(r)&&r>0?r:0}Kr.textPointStyle=function(t,e,r){t.each(function(t){var a=n.select(this),i=oe.extractOption(t,e,"tx","text");if(i){var o=t.tp||e.textposition,l=sn(t,e);a.call(Kr.font,t.tf||e.textfont.family,l,t.tc||e.textfont.color).text(i).call(Mr.convertToTspans,r).call(ln,o,l,t.mrc)}else a.remove()})},Kr.selectedTextStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=e.selected||{},a=e.unselected||{};t.each(function(t){var i,o=n.select(this),l=t.tc||e.textfont.color,s=t.tp||e.textposition,u=sn(t,e),c=(r.textfont||{}).color,f=(a.textfont||{}).color;t.selected?c&&(i=c):f?i=f:c||(i=$e.addOpacity(l,$r)),i&&$e.fill(o,i),ln(o,s,u,t.mrc2||t.mrc)})}};var un=.5;function cn(t,e,r,a){var i=t[0]-e[0],o=t[1]-e[1],l=r[0]-e[0],s=r[1]-e[1],u=Math.pow(i*i+o*o,un/2),c=Math.pow(l*l+s*s,un/2),f=(c*c*i-u*u*l)*a,h=(c*c*o-u*u*s)*a,d=3*c*(u+c),p=3*u*(u+c);return[[n.round(e[0]+(d&&f/d),2),n.round(e[1]+(d&&h/d),2)],[n.round(e[0]-(p&&f/p),2),n.round(e[1]-(p&&h/p),2)]]}Kr.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],a=[];for(r=1;r=1e4&&(Kr.savedBBoxes={},dn=0),r&&(Kr.savedBBoxes[r]=p),dn++,oe.extendFlat({},p)},Kr.setClipUrl=function(t,e){if(e){if(void 0===Kr.baseUrl){var r=n.select("base");r.size()&&r.attr("href")?Kr.baseUrl=window.location.href.split("#")[0]:Kr.baseUrl=""}t.attr("clip-path","url("+Kr.baseUrl+"#"+e+")")}else t.attr("clip-path",null)},Kr.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},Kr.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||0,r=r||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+e+", "+r+")").trim(),t[a]("transform",i),i},Kr.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},Kr.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||1,r=r||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+e+", "+r+")").trim(),t[a]("transform",i),i},Kr.setPointGroupScale=function(t,e,r){var n,a,i;return e=e||1,r=r||1,a=1===e&&1===r?"":" scale("+e+","+r+")",i=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(i,""),n=(n+=a).trim(),this.setAttribute("transform",n)}),a};var gn=/translate\([^)]*\)\s*$/;Kr.setTextPointsScale=function(t,e,r){t.each(function(){var t,a=n.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(gn);t=1===e&&1===r?[]:["translate("+o+","+l+")","scale("+e+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})};var vn={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},isTraceInSubplots:function(t,e){if("splom"===t.type){for(var r=t.xaxes||[],n=t.yaxes||[],a=0;a=0&&r.index=i.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!Xn(o))return!1;t=i[a][o]}else t=i[a]}else t=i}}return t}function Xn(t){return t===Math.round(t)&&t>=0}function Yn(t){return function(t){zn.crawl(t,function(t,e,r){zn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):Un(t)&&(t.role="object")})}(t),function(t){zn.crawl(t,function(t,e,r){if(!t)return;var n=t[Hn];if(!n)return;delete t[Hn],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(Un(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n=o.length)return!1;n=(r=(I.transformsRegistry[o[l].type]||{}).attributes)&&r[e[2]],i=3}else if("area"===t.type)n=Dn[a];else{var s=t._module;if(s||(s=(I.modules[t.type||O.type.dflt]||{})._module),!s)return!1;if(!(n=(r=s.attributes)&&r[a])){var u=s.basePlotModule;u&&u.attributes&&(n=u.attributes[a])}n||(n=O[a])}return Gn(n,e,i)},zn.getLayoutValObject=function(t,e){return Gn(function(t,e){var r,n,a,i,o=t._basePlotModules;if(o){var l;for(r=0;r0?".":"")+a;oe.isPlainObject(i)?ta(i,e,o,n+1):e(o,a,i)}})}function ea(t,e){return"splom"===t?-1:"splom"===e?1:0}Jn.manageCommandObserver=function(t,e,r,n){var a={},i=!0;e&&e._commandObserver&&(a=e._commandObserver),a.cache||(a.cache={}),a.lookupTable={};var o=Jn.hasSimpleAPICommandBindings(t,r,a.lookupTable);if(e&&e._commandObserver){if(o)return a;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,a}if(o){Qn(t,o,a.cache),a.check=function(){if(i){var e=Qn(t,o,a.cache);return e.changed&&n&&void 0!==a.lookupTable[e.value]&&(a.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:a.lookupTable[e.value]})).then(a.enable,a.enable)),e.changed}};for(var l=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],s=0;s=e.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=e._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),s=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){sa.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),a=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+a})}}(t,o),l.text(o.text()&&s.text()?" - ":"")}},sa.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=n.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=sa.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var ca,fa=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],ha=["year","month","dayMonth","dayMonthYear"];function da(t,e){var r,n,a=t.trace,i=a._arrayAttrs,o={};for(r=0;r1&&_.length>1){for(I.getComponentMethod("grid","sizeDefaults")(i,a),r=0;r15&&_.length>15&&0===a.shapes.length&&0===a.images.length,a._hasCartesian=a._has("cartesian"),a._hasGeo=a._has("geo"),a._hasGL3D=a._has("gl3d"),a._hasGL2D=a._has("gl2d"),a._hasTernary=a._has("ternary"),a._hasPie=a._has("pie"),sa.cleanPlot(l,a,o,e,u),sa.linkSubplots(l,a,o,e),oa(a,e),sa.doAutoMargin(t);var T=De.list(t);for(r=0;r0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,f=u.bottom+u.top,h=1-2*l,d=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};n=Math.round(h*(d.width-c)),i=Math.round(h*(d.height-f))}else{var p=s?window.getComputedStyle(t):{};n=parseFloat(p.width)||r.width,i=parseFloat(p.height)||r.height}var g=sa.layoutAttributes.width.min,v=sa.layoutAttributes.height.min;n1,y=!e.height&&Math.abs(r.height-i)>1;(y||m)&&(m&&(r.width=n),y&&(r.height=i)),t._initialAutoSize||(t._initialAutoSize={width:n,height:i}),sa.sanitizeMargins(r)},sa.supplyLayoutModuleDefaults=function(t,e,r,n){var a,i,o,l=I.componentsRegistry,s=e._basePlotModules,u=I.subplotsRegistry.cartesian;for(a in l)(o=l[a]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in s.length||s.push(u),e._has("cartesian")&&(I.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(oe.subplotSort);for(i=0;i.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+a},r:{val:r.x,size:r.r+a},b:{val:r.y,size:r.b+a},t:{val:r.y,size:r.t+a}}}else delete n._pushmargin[e];n._replotting||sa.doAutoMargin(t)}},sa.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),o=Math.max(e.margin.r||0,0),l=Math.max(e.margin.t||0,0),s=Math.max(e.margin.b||0,0),u=e._pushmargin;if(!1!==e.margin.autoexpand)for(var c in u.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:l},b:{val:0,size:s}},u){var f=u[c].l||{},h=u[c].b||{},d=f.val,p=f.size,g=h.val,v=h.size;for(var m in u){if(a(p)&&u[m].r){var y=u[m].r.val,x=u[m].r.size;if(y>d){var b=(p*y+(x-e.width)*d)/(y-d),_=(x*(1-d)+(p-e.width)*(1-y))/(y-d);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(a(v)&&u[m].t){var w=u[m].t.val,A=u[m].t.size;if(w>g){var M=(v*w+(A-e.height)*g)/(w-g),T=(A*(1-g)+(v-e.height)*(1-w))/(w-g);M>=0&&T>=0&&M+T>s+l&&(s=M,l=T)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(l),r.b=Math.round(s),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,!e._replotting&&"{}"!==n&&n!==JSON.stringify(e._size))return I.call("plot",t)},sa.graphJson=function(t,e,r,n,a){(a&&e&&!t._fullData||a&&!e&&!t._fullLayout)&&sa.supplyDefaults(t);var i=a?t._fullData:t.data,o=a?t._fullLayout:t.layout,l=(t._transitionData||{})._frames;function s(t){if("function"==typeof t)return null;if(oe.isPlainObject(t)){var e,n,a={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!oe.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;a[e]=s(t[e])}return a}return Array.isArray(t)?t.map(s):oe.isJSDate(t)?oe.ms2DateTimeLocal(+t):t}var u={data:(i||[]).map(function(t){var r=s(t);return e&&delete r.fit,r})};return e||(u.layout=s(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),l&&(u.frames=s(l)),"object"===n?u:JSON.stringify(u)},sa.modifyFrames=function(t,e){var r,n,a,i=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){f=!0}),a.redraw&&t._transitionData._interruptCallbacks.push(function(){return I.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,l=0,s=0;function u(){return l++,function(){var r;f||++s!==l||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return I.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var h=t._fullLayout._basePlotModules,d=!1;if(r)for(o=0;o=0;i--)if(s[i].enabled){r._indexToPoints=s[i]._indexToPoints;break}n&&n.calc&&(o=n.calc(t,r))}Array.isArray(o)&&o[0]||(o=[{x:aa,y:aa}]),o[0].t||(o[0].t={}),o[0].trace=r,u[e]=o}}for(h&&va(o),a=0;a0||f<0){var g={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[c.side];e.attr("transform","translate("+g+")")}}}T.call(k),A&&(w?T.on(".opacity",null):(b=0,_=!0,T.text(s).on("mouseover.opacity",function(){n.select(this).transition().duration(g.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(g.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(Mr.makeEditable,{gd:t}).on("edit",function(e){void 0!==u?I.call("restyle",t,l,e,u):I.call("relayout",t,l,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(k)}).on("input",function(t){this.text(t||" ").call(Mr.positionText,f.x,f.y)}));return T.classed("js-placeholder",_),d}},ya=/ [XY][0-9]* /;var xa=i.FP_SAFE,ba=Ma,_a=Ta,wa=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=Ma(t),t._r=t.range.slice(),t._rl=oe.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?Ma(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=oe.extendFlat({},n)}},Aa=function(t,e,r){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!e)return;t._min||(t._min=[]);t._max||(t._max=[]);r||(r={});t._m||t.setScale();var n,i,o,l,s,u,c,f,h,d,p,g,v=e.length,m=r.padded||!1,y=r.tozero&&("linear"===t.type||"-"===t.type),x="log"===t.type,b=!1;function _(t){if(Array.isArray(t))return b=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=_((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),A=_((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),T=_(r.vpadminus||r.vpad);if(!b){if(p=1/0,g=-1/0,x)for(n=0;n0&&(p=l),l>g&&l-xa&&(p=l),l>g&&l=b&&(l.extrapad||!m)){d=!1;break}_(n,l.val)&&l.pad<=b&&(m||!l.extrapad)&&(v.splice(i,1),i--)}if(d){var k=y&&0===n;v.push({val:n,pad:k?0:b,extrapad:!k&&m})}}}}var E=Math.min(6,v);for(n=0;n=E;n--)k(n)};function Ma(t){var e,r,n,a,i,o,l,s,u=[],c=t._min[0].val,f=t._max[0].val,h=0,d=!1,p=Ta(t);for(e=1;e0&&l>0&&s/l>h&&(i=n,o=a,h=s/l);if(c===f){var v=c-1,m=c+1;u="tozero"===t.rangemode?c<0?[v,0]:[0,m]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,m)]:[v,m]}else h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(i.val>=0&&(i={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(i.val-h*p(i)<0&&(i={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),h=(o.val-i.val)/(t._length-p(i)-p(o))),u=[i.val-h*p(i),o.val+h*p(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),d&&u.reverse(),oe.simpleMap(u,t.l2r||Number)}function Ta(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function ka(t){return a(t)&&Math.abs(t)=e}var Sa=i.BADNUM,La=function(t,e){return function(t,e){for(var r,n=0,i=0,o=Math.max(1,(t.length-1)/1e3),l=0;l2*i}(t,e)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,a=0,i=0;i2*n}(t)?"category":function(t){if(!t)return!1;for(var e=0;e0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],a=t.range[1];return.5*(n+a-3*i*Math.abs(n-a))}return Ba}function l(e,r,n){var i=Ra(e,n||t.calendar);if(i===Ba){if(!a(e))return Ba;i=Ra(new Date(+e))}return i}function s(e,r,n){return Da(e,r,n||t.calendar)}function u(e){return t._categories[Math.round(e)]}function c(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(a(e))return+e}function f(e){return a(e)?n.round(t._b+t._m*e,2):Ba}function h(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:Pa,t.l2c="log"===t.type?Fa:Pa,t.l2p=f,t.p2l=h,t.c2p="log"===t.type?function(t,e){return f(o(t,e))}:f,t.p2c="log"===t.type?function(t){return Fa(h(t))}:h,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Oa,t.c2d=t.c2r=t.l2d=t.l2r=Pa,t.d2p=t.r2p=function(e){return t.l2p(Oa(e))},t.p2d=t.p2r=h,t.cleanPos=Pa):"log"===t.type?(t.d2r=t.d2l=function(t,e){return o(Oa(t),e)},t.r2d=t.r2c=function(t){return Fa(Oa(t))},t.d2c=t.r2l=Oa,t.c2d=t.l2r=Pa,t.c2r=o,t.l2d=Fa,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return Fa(h(t))},t.r2p=function(e){return t.l2p(Oa(e))},t.p2r=h,t.cleanPos=Pa):"date"===t.type?(t.d2r=t.r2d=oe.identity,t.d2c=t.r2c=t.d2l=t.r2l=l,t.c2d=t.c2r=t.l2d=t.l2r=s,t.d2p=t.r2p=function(e,r,n){return t.l2p(l(e,0,n))},t.p2d=t.p2r=function(t,e,r){return s(h(t),e,r)},t.cleanPos=function(e){return oe.cleanDate(e,Ba,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return Ba},t.r2d=t.c2d=t.l2d=u,t.d2r=t.d2l_noadd=c,t.r2c=function(e){var r=c(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=Pa,t.r2l=c,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return u(h(t))},t.r2p=t.d2p,t.p2r=h,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Pa(t)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var i,o,l=oe.nestedProperty(t,e).get();if(o=(o="date"===t.type?oe.dfltRange(t.calendar):"y"===r?Oe.DFLTRANGEY:n.dfltRange||Oe.DFLTRANGEX).slice(),l&&2===l.length)for("date"===t.type&&(l[0]=oe.cleanDate(l[0],Ba,t.calendar),l[1]=oe.cleanDate(l[1],Ba,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!oe.isDateTime(l[i],t.calendar)){t[e]=o;break}if(t.r2l(l[0])===t.r2l(l[1])){var s=oe.constrain(t.r2l(l[0]),oe.MIN_MS+1e3,oe.MAX_MS-1e3);l[0]=t.l2r(s-1e3),l[1]=t.l2r(s+1e3);break}}else{if(!a(l[i])){if(!a(l[1-i])){t[e]=o;break}l[i]=l[1-i]*(i?10:.1)}if(l[i]<-Ia?l[i]=-Ia:l[i]>Ia&&(l[i]=Ia),l[0]===l[1]){var u=Math.max(1,Math.abs(1e-6*l[0]));l[0]-=u,l[1]+=u}}else oe.nestedProperty(t,e).set(o)},t.setScale=function(n){var a=e._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=De.getFromId({_fullLayout:e},t.overlaying);t.domain=i.domain}var o=n&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),u=t.r2l(t[o][1],l);if("y"===r?(t._offset=a.t+(1-t.domain[1])*a.h,t._length=a.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-u),t._b=-t._m*u):(t._offset=a.l+t.domain[0]*a.w,t._length=a.w*(t.domain[1]-t.domain[0]),t._m=t._length/(u-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw e._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,a,i,o,l=t.type,s="date"===l&&e[r+"calendar"];if(r in e){if(n=e[r],o=e._length||n.length,oe.isTypedArray(n)&&("linear"===l||"log"===l)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(a=new Array(o),i=0;i2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},Ja.saveRangeInitial=function(t,e){for(var r=Ja.list(t,"",!0),n=!1,a=0;a.3*h||c(n)||c(i))){var d=r.dtick/2;t+=t+d.8){var o=Number(r.substr(1));i.exactYears>.8&&o%12==0?t=Ja.tickIncrement(t,"M6","reverse")+1.5*Va:i.exactMonths>.8?t=Ja.tickIncrement(t,"M1","reverse")+15.5*Va:t-=Va/2;var l=Ja.tickIncrement(t,r);if(l<=n)return l}return t}(p,t,l.dtick,s,i)),d=p,0;d<=u;)d=Ja.tickIncrement(d,l.dtick,!1,i),0;return{start:e.c2r(p,0,i),end:e.c2r(d,0,i),size:l.dtick,_dataSpan:u-s}},Ja.prepTicks=function(t){var e=oe.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=oe.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),Ja.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),si(t)},Ja.calcTicks=function(t){Ja.prepTicks(t);var e=oe.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,a=t.ticktext,i=new Array(n.length),o=oe.simpleMap(t.range,t.r2l),l=1.0001*o[0]-1e-4*o[1],s=1.0001*o[1]-1e-4*o[0],u=Math.min(l,s),c=Math.max(l,s),f=0;Array.isArray(a)||(a=[]);var h="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:s<=n)&&!(i.length>l||s===o);s=Ja.tickIncrement(s,t.dtick,a,t.calendar))o=s,i.push(s);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&i.pop(),t._tmax=i[i.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(i.length),c=0;c10||"01-01"!==n.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=Va&&i<=10||e>=15*Va)t._tickround="d";else if(e>=qa&&i<=16||e>=Ha)t._tickround="M";else if(e>=Ga&&i<=19||e>=qa)t._tickround="S";else{var o=t.l2r(r+e).replace(/^-/,"").length;t._tickround=Math.max(i,o)-20}}else if(a(e)||"L"===e.charAt(0)){var l=t.range.map(t.r2d||Number);a(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),u=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(u)>3&&(fi(t.exponentformat)&&!hi(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function ui(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}Ja.autoTicks=function(t,e){var r;function n(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=oe.dateTick0(t.calendar);var i=2*e;i>ja?(e/=ja,r=n(10),t.dtick="M"+12*li(e,r,ti)):i>Ua?(e/=Ua,t.dtick="M"+li(e,1,ei)):i>Va?(t.dtick=li(e,Va,ni),t.tick0=oe.dateTick0(t.calendar,!0)):i>Ha?t.dtick=li(e,Ha,ei):i>qa?t.dtick=li(e,qa,ri):i>Ga?t.dtick=li(e,Ga,ri):(r=n(10),t.dtick=li(e,r,ti))}else if("log"===t.type){t.tick0=0;var o=oe.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(o[1]-o[0])<1){var l=1.5*Math.abs((o[1]-o[0])/e);e=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/l,r=n(10),t.dtick="L"+li(e,r,ti)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):"angular"===t._id?(t.tick0=0,r=1,t.dtick=li(e,r,oi)):(t.tick0=0,r=n(10),t.dtick=li(e,r,ti));if(0===t.dtick&&(t.dtick=1),!a(t.dtick)&&"string"!=typeof t.dtick){var s=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(s)}},Ja.tickIncrement=function(t,e,r,i){var o=r?-1:1;if(a(e))return t+o*e;var l=e.charAt(0),s=o*Number(e.substr(1));if("M"===l)return oe.incrementMonth(t,s,i);if("L"===l)return Math.log(Math.pow(10,t)+s)/Math.LN10;if("D"===l){var u="D2"===e?ii:ai,c=t+.01*o,f=oe.roundUp(oe.mod(c,1),u,r);return Math.floor(c)+Math.log(n.round(Math.pow(10,f),1))/Math.LN10}throw"unrecognized dtick "+String(e)},Ja.tickFirst=function(t){var e=t.r2l||Number,r=oe.simpleMap(t.range,e),i=r[1]"+l,t._prevDateHead=l));e.text=s}(t,o,r,s):"log"===t.type?function(t,e,r,n,i){var o=t.dtick,l=e.x,s=t.tickformat;"never"===i&&(i="");!n||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(s||"string"==typeof o&&"L"===o.charAt(0))e.text=di(Math.pow(10,l),t,i,n);else if(a(o)||"D"===o.charAt(0)&&oe.mod(l+.01,1)<.1){var u=Math.round(l);-1!==["e","E","power"].indexOf(t.exponentformat)||fi(t.exponentformat)&&hi(u)?(e.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+Xa+-u+"",e.fontSize*=1.25):(e.text=di(Math.pow(10,l),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);e.text=String(Math.round(Math.pow(10,oe.mod(l,1)))),e.fontSize*=.75}if("D1"===t.dtick){var c=String(e.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(l<0?.5:.25)))}}(t,o,0,s,n):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,a){if("radians"!==t.thetaunit||r)e.text=di(e.x,t,a,n);else{var i=e.x/180;if(0===i)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,a=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/a),Math.round(r/a)]}(i);if(o[1]>=100)e.text=di(oe.deg2rad(e.x),t,a,n);else{var l=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),l&&(e.text=Xa+e.text)}}}}(t,o,r,s,n):function(t,e,r,n,a){"never"===a?a="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(a="hide");e.text=di(e.x,t,a,n)}(t,o,0,s,n),t.tickprefix&&!h(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!h(t.showticksuffix)&&(o.text+=t.ticksuffix),o},Ja.hoverLabelText=function(t,e,r){if(r!==Ya&&r!==e)return Ja.hoverLabelText(t,e)+" - "+Ja.hoverLabelText(t,r);var n="log"===t.type&&e<=0,a=Ja.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":Xa+a:a};var ci=["f","p","n","\u03bc","m","","k","M","G","T"];function fi(t){return"SI"===t||"B"===t}function hi(t){return t>14||t<-15}function di(t,e,r,n){var i=t<0,o=e._tickround,l=r||e.exponentformat||"B",s=e._tickexponent,u=Ja.getTickFormat(e),c=e.separatethousands;if(n){var f={exponentformat:l,dtick:"none"===e.showexponent?e.dtick:a(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};si(f),o=(Number(f._tickround)||0)+4,s=f._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,Xa);var h,d=Math.pow(10,-o)/2;if("none"===l&&(s=0),(t=Math.abs(t))"+h+"":"B"===l&&9===s?t+="B":fi(l)&&(t+=ci[s/3+5]));return i?Xa+t:t}function pi(t,e){for(var r=0;r=0,i=u(t,e[1])<=0;return(r||a)&&(n||i)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=i(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n-1&&l.length>p&&(l=p>3?l.substr(0,p-3)+"...":l.substr(0,p))}void 0!==t.zLabel?(void 0!==t.xLabel&&(s+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(s+="y: "+t.yLabel+"
"),s+=(s?"z: ":"")+t.zLabel):w&&t[a+"Label"]===v?s=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(s=t.yLabel):s=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(s+=(s?"
":"")+t.text),void 0!==t.extraText&&(s+=(s?"
":"")+t.extraText),""===s&&(""===l&&e.remove(),s=l);var g=e.select("text.nums").call(Jr.font,t.fontFamily||c,t.fontSize||f,t.fontColor||d).text(s).attr("data-notex",1).call(Mr.positionText,0,0).call(Mr.convertToTspans,r),m=e.select("text.name"),y=0;l&&l!==s?(m.call(Jr.font,t.fontFamily||c,t.fontSize||f,h).text(l).attr("data-notex",1).call(Mr.positionText,0,0).call(Mr.convertToTspans,r),y=m.node().getBoundingClientRect().width+2*Mi):(m.remove(),e.select("rect").remove()),e.select("path").style({fill:h,stroke:d});var A,M,T=g.node().getBoundingClientRect(),k=t.xa._offset+(t.x0+t.x1)/2,E=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),S=Math.abs(t.y1-t.y0),L=T.width+Ai+Mi+y;t.ty0=x-T.top,t.bx=T.width+2*Mi,t.by=T.height+2*Mi,t.anchor="start",t.txwidth=T.width,t.tx2width=y,t.offset=0,i?(t.pos=k,A=E+S/2+L<=_,M=E-S/2-L>=0,"top"!==t.idealAlign&&A||!M?A?(E+=S/2,t.anchor="start"):t.anchor="middle":(E-=S/2,t.anchor="end")):(t.pos=E,A=k+C/2+L<=b,M=k-C/2-L>=0,"left"!==t.idealAlign&&A||!M?A?(k+=C/2,t.anchor="start"):t.anchor="middle":(k-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),y&&m.attr("text-anchor",t.anchor),e.attr("transform","translate("+k+","+E+")"+(i?"rotate("+yi+")":""))}),C}function ki(t,e){t.each(function(t){var r=n.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(Ai+Mi),s=l+o*(t.txwidth+Mi),u=0,c=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,s+=t.txwidth/2+Mi),e&&(c*=-wi,u=t.offset*_i),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(c-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*Ai+u)+","+(Ai+c)+"v"+(t.by/2-Ai)+"h"+a*t.bx+"v-"+t.by+"H"+(a*Ai+u)+"V"+(c-Ai)+"Z"),i.call(Mr.positionText,l+u,c+t.ty0-t.by/2+Mi),t.tx2width&&(r.select("text.name").call(Mr.positionText,s+o*Mi+u,c+t.ty0-t.by/2+Mi),r.select("rect").call(Jr.setRect,s+(o-1)*t.tx2width/2+u,c-t.by/2-1,t.tx2width,t.by+2))}})}function Ei(t,e){var r=t.index,n=t.trace||{},a=t.cd[0],i=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return oe.castOption(a,r,t)||oe.extractOption({},n,"",e)}:function(t,e){return oe.extractOption(i,n,t,e)};function l(e,r,n){var a=o(r,n);a&&(t[e]=a)}if(l("hoverinfo","hi","hoverinfo"),l("color","hbg","hoverlabel.bgcolor"),l("borderColor","hbc","hoverlabel.bordercolor"),l("fontFamily","htf","hoverlabel.font.family"),l("fontSize","hts","hoverlabel.font.size"),l("fontColor","htc","hoverlabel.font.color"),l("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=oe.constrain(t.x0,0,t.xa._length),t.x1=oe.constrain(t.x1,0,t.xa._length),t.y0=oe.constrain(t.y0,0,t.ya._length),t.y1=oe.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:Na.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:Na.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var s=Na.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+s+" / -"+Na.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+s,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=Na.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+Na.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function Ci(t,e){var r,n,a=e.container,i=e.fullLayout,o=e.event,l=!!t.hLinePoint,s=!!t.vLinePoint;if(a.selectAll(".spikeline").remove(),s||l){var u=$e.combine(i.plot_bgcolor,i.paper_bgcolor);if(l){var f,h,d=t.hLinePoint;r=d&&d.xa,"cursor"===(n=d&&d.ya).spikesnap?(f=o.pointerX,h=o.pointerY):(f=r._offset+d.x,h=n._offset+d.y);var p,g,v=c.readability(d.color,u)<1.5?$e.contrast(u):d.color,m=n.spikemode,y=n.spikethickness,x=n.spikecolor||v,b=n._boundingBox,_=(b.left+b.right)/2H.width||U<0||U>H.height)return Ye.unhoverRaw(t,e);e.pointerX=e.offsetX,e.pointerY=e.offsetY}if(_="xval"in e?vn.flat(o,e.xval):vn.p2c(d,j),w="yval"in e?vn.flat(o,e.yval):vn.p2c(p,U),!a(_[0])||!a(w[0]))return oe.warn("Fx.hover failed",e,t),Ye.unhoverRaw(t,e)}var q=1/0;for(M=0;MR&&(F.splice(0,R),q=F[0].distance),c&&0!==B&&0===F.length){D.distance=B,D.index=!1;var Z=k._module.hoverPoints(D,L,O,"closest",l._hoverlayer);if(Z&&(Z=Z.filter(function(t){return t.spikeDistance<=B})),Z&&Z.length){var J,Q=Z.filter(function(t){return t.xa.showspikes});if(Q.length){var $=Q[0];a($.x0)&&a($.y0)&&(J=rt($),(!N.vLinePoint||N.vLinePoint.spikeDistance>J.spikeDistance)&&(N.vLinePoint=J))}var K=Z.filter(function(t){return t.ya.showspikes});if(K.length){var tt=K[0];a(tt.x0)&&a(tt.y0)&&(J=rt(tt),(!N.hLinePoint||N.hLinePoint.spikeDistance>J.spikeDistance)&&(N.hLinePoint=J))}}}}function et(t,e){for(var r,n=null,a=1/0,i=0;i1,gt=$e.combine(l.plot_bgcolor||$e.background,l.paper_bgcolor),vt={hovermode:b,rotateLabels:pt,bgColor:gt,container:l._hoverlayer,outerContainer:l._paperdiv,commonLabelOpts:l.hoverlabel,hoverdistance:l.hoverdistance},mt=Ti(F,vt,t);if(function(t,e,r){var n,a,i,o,l,s,u,c=0,f=t.map(function(t,n){var a=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===a._id.charAt(0)?bi:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function h(t){var e=t[0],r=t[t.length-1];if(a=e.pmin-e.pos-e.dp+e.size,i=r.pos+r.dp+r.size-e.pmax,a>.01){for(l=t.length-1;l>=0;l--)t[l].dp+=a;n=!1}if(!(i<.01)){if(a<-.01){for(l=t.length-1;l>=0;l--)t[l].dp-=i;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(s=t[o]).pos>e.pmax-1&&(s.del=!0,u--);for(o=0;o=0;l--)t[l].dp-=i;for(o=t.length-1;o>=0&&!(u<=0);o--)(s=t[o]).pos+s.dp+s.size>e.pmax&&(s.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(l=p.length-1;l>=0;l--)p[l].dp+=a;for(d.push.apply(d,p),f.splice(o+1,1),u=0,l=d.length-1;l>=0;l--)u+=d[l].dp;for(i=u/d.length,l=d.length-1;l>=0;l--)d[l].dp-=i;n=!1}else o++}f.forEach(h)}for(o=f.length-1;o>=0;o--){var m=f[o];for(l=m.length-1;l>=0;l--){var y=m[l],x=t[y.i];x.offset=y.dp,x.del=y.del}}}(F,pt?"xa":"ya",l),ki(mt,pt),e.target&&e.target.tagName){var yt=I.getComponentMethod("annotations","hasClickToShow")(t,ht);wn(n.select(e.target),yt?"pointer":"")}if(!e.target||i||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var a=r[n],i=t._hoverdata[n];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,ft))return;ft&&t.emit("plotly_unhover",{event:e,points:ft});t.emit("plotly_hover",{event:e,points:t._hoverdata,xaxes:d,yaxes:p,xvals:_,yvals:w})}(t,e,r,i)})},mi.loneHover=function(t,e){var r={color:t.color||$e.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=n.select(e.container),i=e.outerContainer?n.select(e.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||$e.background,container:a,outerContainer:i},l=Ti([r],o,e.gd);return ki(l,o.rotateLabels),l.node()};var Li=mi.hover,Oi=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),oe.coerceFont(r,"hoverlabel.font",n.font)};var Di={moduleType:"component",name:"fx",constants:Te,schema:{layout:Ee},attributes:L,layoutAttributes:Ee,supplyLayoutGlobalDefaults:function(t,e){Oi(0,0,function(r,n){return oe.coerce(t,e,Ee,r,n)})},supplyDefaults:function(t,e,r,n){Oi(0,0,function(r,n){return oe.coerce(t,e,L,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return oe.coerce(t,e,Ee,r,n)}var a;"select"===n("dragmode")&&n("selectdirection"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r0})}function u(t,n){var a=t.seg,i=n.seg,o=a.start,s=a.end,u=i.start,c=i.end;r&&r.checkIntersection(a,i);var f=e.linesIntersect(o,s,u,c);if(!1===f){if(!e.pointsCollinear(o,s,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(s,u))return!1;var h=e.pointsSame(o,u),d=e.pointsSame(s,c);if(h&&d)return n;var p=!h&&e.pointBetween(o,u,c),g=!d&&e.pointBetween(s,u,c);if(h)return g?l(n,s):l(t,c),n;p&&(d||(g?l(n,s):l(t,c)),l(n,o))}else 0===f.alongA&&(-1===f.alongB?l(t,u):0===f.alongB?l(t,f.pt):1===f.alongB&&l(t,c)),0===f.alongB&&(-1===f.alongA?l(n,o):0===f.alongA?l(n,f.pt):1===f.alongA&&l(n,s));return!1}for(var c=[];!a.isEmpty();){var f=a.getHead();if(r&&r.vert(f.pt[0]),f.isStart){r&&r.segmentNew(f.seg,f.primary);var h=s(f),d=h.before?h.before.ev:null,p=h.after?h.after.ev:null;function g(){if(d){var t=u(f,d);if(t)return t}return!!p&&u(f,p)}r&&r.tempStatus(f.seg,!!d&&d.seg,!!p&&p.seg);var v,m,y=g();if(y)t?(m=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below)&&(y.seg.myFill.above=!y.seg.myFill.above):y.seg.otherFill=f.seg.myFill,r&&r.segmentUpdate(y.seg),f.other.remove(),f.remove();if(a.getHead()!==f){r&&r.rewind(f.seg);continue}t?(m=null===f.seg.myFill.below||f.seg.myFill.above!==f.seg.myFill.below,f.seg.myFill.below=p?p.seg.myFill.above:n,f.seg.myFill.above=m?!f.seg.myFill.below:f.seg.myFill.below):null===f.seg.otherFill&&(v=p?f.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:f.primary?i:n,f.seg.otherFill={above:v,below:v}),r&&r.status(f.seg,!!d&&d.seg,!!p&&p.seg),f.other.status=h.insert(zi.node({ev:f}))}else{var x=f.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&u(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!f.primary){var b=f.seg.myFill;f.seg.myFill=f.seg.otherFill,f.seg.otherFill=b}c.push(f.seg)}a.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,a,i,l=t[t.length-1],s=0;s=-t},pointBetween:function(e,r,n){var a=e[1]-r[1],i=n[0]-r[0],o=e[0]-r[0],l=n[1]-r[1],s=o*i+a*l;return!(s-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-a>t&&(i-u)*(a-c)/(o-c)+u-n>t&&(l=!l),i=u,o=c}return l}};return e}();function Xi(t,e,r){var n=Vi.segments(t),a=Vi.segments(e),i=r(Vi.combine(n,a));return Vi.polygon(i)}Vi={buildLog:function(t){return!0===t?qi=Bi():!1===t&&(qi=!1),!1!==qi&&qi.list},epsilon:function(t){return Gi.epsilon(t)},segments:function(t){var e=Ni(!0,Gi,qi);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:Ni(!1,Gi,qi).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:Hi.union(t.combined,qi),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:Hi.intersect(t.combined,qi),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:Hi.difference(t.combined,qi),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:Hi.differenceRev(t.combined,qi),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:Hi.xor(t.combined,qi),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:ji(t.segments,Gi,qi),inverted:t.inverted}},polygonFromGeoJSON:function(t){return Fi.toPolygon(Vi,t)},polygonToGeoJSON:function(t){return Fi.fromPolygon(Vi,Gi,t)},union:function(t,e){return Xi(t,e,Vi.selectUnion)},intersect:function(t,e){return Xi(t,e,Vi.selectIntersect)},difference:function(t,e){return Xi(t,e,Vi.selectDifference)},differenceRev:function(t,e){return Xi(t,e,Vi.selectDifferenceRev)},xor:function(t,e){return Xi(t,e,Vi.selectXor)}},"object"==typeof window&&(window.PolyBool=Vi);var Yi,Wi=Vi,Zi=qt.dot,Ji=i.BADNUM,Qi=Yi={};Qi.tester=function(t){if(Array.isArray(t[0][0]))return Qi.multitester(t);var e,r=t.slice(),n=r[0][0],a=n,i=r[0][1],o=i;for(r.push(r[0]),e=1;ea||s===Ji||so||e&&l(t))}:function(t,e){var l=t[0],s=t[1];if(l===Ji||la||s===Ji||so)return!1;var u,c,f,h,d,p=r.length,g=r[0][0],v=r[0][1],m=0;for(u=1;uMath.max(c,g)||s>Math.max(f,v)))if(su||Math.abs(Zi(i,f))>n)return!0;return!1};Qi.filter=function(t,e){var r=[t[0]],n=0,a=0;function i(i){t.push(i);var o=r.length,l=n;r.splice(a+1);for(var s=l+1;s1&&i(t.pop());return{addPt:i,raw:t,filtered:r}};var Ki=vn.makeEventData,to=De.getFromId,eo=ra,ro=Oe.MINSELECT,no=Yi.filter,ao=Yi.tester,io=Yi.multitester;function oo(t){return t._id}function lo(t,e,r){var n,a,i,o;if(r){var l=r.points||[];for(n=0;n=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function Eo(t,e,r,n,a){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",a+"Z")}function Co(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:$e.background,stroke:$e.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function So(t,e,r,n,a,i){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),Lo(t,e,a,i)}function Lo(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function Oo(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Do(t){bo&&t.data&&t._context.showTips&&(oe.notifier(oe._(t,"Double-click to zoom back out"),"long"),bo=!1)}function Ro(t){return"lasso"===t||"select"===t}function Po(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,xo)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function Io(t,e){if(Pe){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function Bo(t){var e=[];for(var r in t)e.push(t[r]);return e}var Fo={},zo=function(t,e,r,a,i,o,l,s){var u,f,h,d,p,g,v,m,y,x,b,_,w,A,M,T,k,E=t._fullLayout._zoomlayer,C=l+s==="nsew",S=1===(l+s).length;function L(){if(u=e.xaxis,f=e.yaxis,y=u._length,x=f._length,v=u._offset,m=f._offset,(h={})[u._id]=u,(d={})[f._id]=f,l&&s)for(var r=e.overlays,n=0;nxo||o>xo?(j="xy",i/y>o/x?(o=i*x/y,P>a?B.t=P-o:B.b=P+o):(i=o*y/x,R>n?B.l=R-i:B.r=R+i),V.attr("d",Po(B))):l():!w||o10||r.scrollWidth-r.clientWidth>10)){clearTimeout(W);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var a,i=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=J.draglayer.select(".nsewdrag").node().getBoundingClientRect(),u=(e.clientX-o.left)/o.width,c=(o.bottom-e.clientY)/o.height;if(T){for(s||(u=.5),a=0;a0;o&&(a="array");var l,s=r("categoryorder",a);"array"===s&&(l=r("categoryarray")),o||"array"!==s||(s=e.categoryorder="trace"),"trace"===s?e._initialCategories=[]:"array"===s?e._initialCategories=l.slice():(l=function(t,e){var r,n,a,i=e.dataAttr||t._id.charAt(0),o={};if(e.axData)r=e.axData;else for(r=[],n=0;np[1]-.01&&(e.domain=o),oe.noneOrAll(t.domain,e.domain,o)}return r("layer"),e},Yo=De.name2id,Wo=function(t,e,r,n,a){a&&(e._name=a,e._id=Yo(a)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var a=function(t,e,r){for(var n=0;n0&&a["_"+r+"axes"][e])return a;if((a[r+"axis"]||r)===e){if(Jo(a,r))return a;if((a[r]||[]).length||a[r+"0"])return a}}}(e,r,n);if(!a)return;if("histogram"===a.type&&n==={v:"y",h:"x"}[a.orientation||"v"])return void(t.type="linear");var i,o=n+"calendar",l=a[o];if(Jo(a,n)){var s=Zo(a),u=[];for(i=0;i rect").call(Jr.setTranslate,0,0).call(Jr.setScale,1,1),t.plot.call(Jr.setTranslate,e._offset,r._offset).call(Jr.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(Jr.setPointGroupScale,1,1),n.selectAll(".textpoint").call(Jr.setTextPointsScale,1,1),n.call(Jr.hideOutsideRangePoints,t)}function g(e,r){var n,a,o,l=f[e.xaxis._id],s=f[e.yaxis._id],u=[];if(l){a=(n=t._fullLayout[l.axisName])._r,o=l.to,u[0]=(a[0]*(1-r)+r*o[0]-a[0])/(a[1]-a[0])*e.xaxis._length;var c=a[1]-a[0],h=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],u[2]=e.xaxis._length*(1-r+r*h/c)}else u[0]=0,u[2]=e.xaxis._length;if(s){a=(n=t._fullLayout[s.axisName])._r,o=s.to,u[1]=(a[1]*(1-r)+r*o[1]-a[1])/(a[0]-a[1])*e.yaxis._length;var d=a[1]-a[0],p=o[1]-o[0];n.range[0]=a[0]*(1-r)+r*o[0],n.range[1]=a[1]*(1-r)+r*o[1],u[3]=e.yaxis._length*(1-r+r*p/d)}else u[1]=0,u[3]=e.yaxis._length;!function(e,r){var n,a=[];for(a=[e._id,r._id],n=0;nr.duration?(function(){for(var e={},r=0;r0,s=[],u=[],c=0,f=0;for(n=0;n0&&s.push("var "+u.join(",")),n=i-1;n>=0;--n)c=t[n],s.push(["for(i",n,"=0;i",n,"0&&s.push(["index[",f,"]-=s",f].join("")),s.push(["++index[",c,"]"].join(""))),s.push("}")}return s.join("\n")}function cl(t,e,r){for(var n=t.body,a=[],i=[],o=0;o0&&g.push("shape=SS.slice(0)"),t.indexArgs.length>0){var v=new Array(r);for(i=0;i0&&p.push("var "+g.join(",")),i=0;i3&&p.push(cl(t.pre,t,a));var b=cl(t.body,t,a),_=function(t){for(var e=0,r=t[0].length;e0,s=[],u=0;u0;){"].join("")),s.push(["if(j",u,"<",o,"){"].join("")),s.push(["s",e[u],"=j",u].join("")),s.push(["j",u,"=0"].join("")),s.push(["}else{s",e[u],"=",o].join("")),s.push(["j",u,"-=",o,"}"].join("")),l&&s.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&p.push(cl(t.post,t,a)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+p.join("\n")+"\n----------");var w=[t.funcName||"unnamed","_cwise_loop_",n[0].join("s"),"m",_,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(a)].join("");return new Function(["function ",w,"(",d.join(","),"){",p.join("\n"),"} return ",w].join(""))()};var hl=function(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],i=[],o=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],s=[],u=0;u0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+c+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),s.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+c+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u0)throw new Error("cwise: pre() block may not reference array args");if(n0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===a)e.scalarArgs.push(n),e.shimArgs.push("scalar"+n);else if("index"===a){if(e.indexArgs.push(n),n0)throw new Error("cwise: pre() block may not reference array index");if(n0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===a){if(e.shapeArgs.push(n),nr.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,hl(e)},pl={},vl={body:"",args:[],thisVars:[],localVars:[]};function ml(t){if(!t)return vl;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in xl){var e=xl[t];pl[t]=yl({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),pl[t+"eq"]=yl({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),pl[t+"s"]=yl({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),pl[t+"seq"]=yl({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var bl={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in bl){var e=bl[t];pl[t]=yl({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),pl[t+"eq"]=yl({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var _l={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in _l){var e=_l[t];pl[t]=yl({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),pl[t+"s"]=yl({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),pl[t+"eq"]=yl({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),pl[t+"seq"]=yl({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var wl=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_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"}),pl.norm1=dl({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,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"}),pl.sup=dl({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:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),pl.inf=dl({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:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),pl.random=yl({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),pl.assign=yl({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),pl.assigns=yl({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),pl.equals=dl({args:["array","array"],pre:vl,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"});var Tl=function(t){for(var e=new Array(t),r=0;rMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+o.join(",")+",v){"),n?a.push("return this.data.set("+l+",v)}"):a.push("return this.data["+l+"]=v}"),a.push("proto.get=function "+r+"_get("+o.join(",")+"){"),n?a.push("return this.data.get("+l+")}"):a.push("return this.data["+l+"]}"),a.push("proto.index=function "+r+"_index(",o.join(),"){return "+l+"}"),a.push("proto.hi=function "+r+"_hi("+o.join(",")+"){return new "+r+"(this.data,"+i.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+i.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var c=i.map(function(t){return"a"+t+"=this.shape["+t+"]"}),f=i.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+o.join(",")+"){var b=this.offset,d=0,"+c.join(",")+","+f.join(","));for(var h=0;h=0){d=i"+h+"|0;b+=c"+h+"*d;a"+h+"-=d}");a.push("return new "+r+"(this.data,"+i.map(function(t){return"a"+t}).join(",")+","+i.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+o.join(",")+"){var "+i.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+i.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(h=0;h=0){c=(c+this.stride["+h+"]*i"+h+")|0}else{a.push(this.shape["+h+"]);b.push(this.stride["+h+"])}");return a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+i.map(function(t){return"shape["+t+"]"}).join(",")+","+i.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",a.join("\n"))(Dl[t],Ll)}var Dl={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};var Rl=function(t,e,r,n){if(void 0===t)return(0,Dl.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var a=e.length;if(void 0===r){r=new Array(a);for(var i=a-1,o=1;i>=0;--i)r[i]=o,o*=e[i]}if(void 0===n)for(n=0,i=0;i0)-(t<0)},Pl.abs=function(t){var e=t>>31;return(t^e)-e},Pl.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Pl.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Pl.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Pl.countTrailingZeros=Il,Pl.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Pl.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Pl.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var Bl=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,a=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--a;t[e]=n<>>8&255]<<16|Bl[t>>>16&255]<<8|Bl[t>>>24&255]},Pl.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Pl.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Pl.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Pl.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Pl.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Il(t)+1};for(var Fl={byteLength:function(t){return 3*t.length/4-ql(t)},toByteArray:function(t){var e,r,n,a,i,o=t.length;a=ql(t),i=new jl(3*o/4-a),r=a>0?o-4:o;var l=0;for(e=0;e>16&255,i[l++]=n>>8&255,i[l++]=255&n;2===a?(n=Nl[t.charCodeAt(e)]<<2|Nl[t.charCodeAt(e+1)]>>4,i[l++]=255&n):1===a&&(n=Nl[t.charCodeAt(e)]<<10|Nl[t.charCodeAt(e+1)]<<4|Nl[t.charCodeAt(e+2)]>>2,i[l++]=n>>8&255,i[l++]=255&n);return i},fromByteArray:function(t){for(var e,r=t.length,n=r%3,a="",i=[],o=0,l=r-n;ol?l:o+16383));1===n?(e=t[r-1],a+=zl[e>>2],a+=zl[e<<4&63],a+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],a+=zl[e>>10],a+=zl[e>>4&63],a+=zl[e<<2&63],a+="=");return i.push(a),i.join("")}},zl=[],Nl=[],jl="undefined"!=typeof Uint8Array?Uint8Array:Array,Ul="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Vl=0,Hl=Ul.length;Vl0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function Gl(t,e,r){for(var n,a,i=[],o=e;o>18&63]+zl[a>>12&63]+zl[a>>6&63]+zl[63&a]);return i.join("")}Nl["-".charCodeAt(0)]=62,Nl["_".charCodeAt(0)]=63;var Xl={read:function(t,e,r,n,a){var i,o,l=8*a-n-1,s=(1<>1,c=-7,f=r?a-1:0,h=r?-1:1,d=t[e+f];for(f+=h,i=d&(1<<-c)-1,d>>=-c,c+=l;c>0;i=256*i+t[e+f],f+=h,c-=8);for(o=i&(1<<-c)-1,i>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=h,c-=8);if(0===i)i=1-u;else{if(i===s)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),i-=u}return(d?-1:1)*o*Math.pow(2,i-n)},write:function(t,e,r,n,a,i){var o,l,s,u=8*i-a-1,c=(1<>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:i-1,p=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(s=Math.pow(2,-o))<1&&(o--,s*=2),(e+=o+f>=1?h/s:h*Math.pow(2,1-f))*s>=2&&(o++,s/=2),o+f>=c?(l=0,o=c):o+f>=1?(l=(e*s-1)*Math.pow(2,a),o+=f):(l=e*Math.pow(2,f-1)*Math.pow(2,a),o=0));a>=8;t[r+d]=255&l,d+=p,l/=256,a-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*g}},Yl={};Yl.Buffer=Jl,Yl.SlowBuffer=function(t){+t!=t&&(t=0);return Jl.alloc(+t)},Yl.INSPECT_MAX_BYTES=50;var Wl=2147483647;function Zl(t){if(t>Wl)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=Jl.prototype,e}function Jl(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return Kl(t)}return Ql(t,e,r)}function Ql(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return Ss(t)||t&&Ss(t.buffer)?function(t,e,r){if(e<0||t.byteLength=Wl)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Wl.toString(16)+" bytes");return 0|t}function rs(t,e){if(Jl.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Ss(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ks(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Es(t).length;default:if(n)return ks(t).length;e=(""+e).toLowerCase(),n=!0}}function ns(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function as(t,e,r,n,a){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Ls(r=+r)&&(r=a?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(a)return-1;r=t.length-1}else if(r<0){if(!a)return-1;r=0}if("string"==typeof e&&(e=Jl.from(e,n)),Jl.isBuffer(e))return 0===e.length?-1:is(t,e,r,n,a);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):is(t,[e],r,n,a);throw new TypeError("val must be string, number or Buffer")}function is(t,e,r,n,a){var i,o=1,l=t.length,s=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,l/=2,s/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(a){var c=-1;for(i=r;il&&(r=l-s),i=r;i>=0;i--){for(var f=!0,h=0;ha&&(n=a):n=a;var i=e.length;n>i/2&&(n=i/2);for(var o=0;o>8,a=r%256,i.push(a),i.push(n);return i}(e,t.length-r),t,r,n)}function hs(t,e,r){return 0===e&&r===t.length?Fl.fromByteArray(t):Fl.fromByteArray(t.slice(e,r))}function ds(t,e,r){r=Math.min(t.length,r);for(var n=[],a=e;a239?4:u>223?3:u>191?2:1;if(a+f<=r)switch(f){case 1:u<128&&(c=u);break;case 2:128==(192&(i=t[a+1]))&&(s=(31&u)<<6|63&i)>127&&(c=s);break;case 3:i=t[a+1],o=t[a+2],128==(192&i)&&128==(192&o)&&(s=(15&u)<<12|(63&i)<<6|63&o)>2047&&(s<55296||s>57343)&&(c=s);break;case 4:i=t[a+1],o=t[a+2],l=t[a+3],128==(192&i)&&128==(192&o)&&128==(192&l)&&(s=(15&u)<<18|(63&i)<<12|(63&o)<<6|63&l)>65535&&s<1114112&&(c=s)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),a+=f}return function(t){var e=t.length;if(e<=ps)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return ms(this,e,r);case"utf8":case"utf-8":return ds(this,e,r);case"ascii":return gs(this,e,r);case"latin1":case"binary":return vs(this,e,r);case"base64":return hs(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ys(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},Jl.prototype.toLocaleString=Jl.prototype.toString,Jl.prototype.equals=function(t){if(!Jl.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Jl.compare(this,t)},Jl.prototype.inspect=function(){var t="",e=Yl.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},Jl.prototype.compare=function(t,e,r,n,a){if(!Jl.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===a&&(a=this.length),e<0||r>t.length||n<0||a>this.length)throw new RangeError("out of range index");if(n>=a&&e>=r)return 0;if(n>=a)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,a>>>=0,this===t)return 0;for(var i=a-n,o=r-e,l=Math.min(i,o),s=this.slice(n,a),u=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var a=this.length-e;if((void 0===r||r>a)&&(r=a),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return os(this,t,e,r);case"utf8":case"utf-8":return ls(this,t,e,r);case"ascii":return ss(this,t,e,r);case"latin1":case"binary":return us(this,t,e,r);case"base64":return cs(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return fs(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Jl.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ps=4096;function gs(t,e,r){var n="";r=Math.min(t.length,r);for(var a=e;an)&&(r=n);for(var a="",i=e;ir)throw new RangeError("Trying to access beyond buffer length")}function bs(t,e,r,n,a,i){if(!Jl.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>a||et.length)throw new RangeError("Index out of range")}function _s(t,e,r,n,a,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function ws(t,e,r,n,a){return e=+e,r>>>=0,a||_s(t,0,r,4),Xl.write(t,e,r,n,23,4),r+4}function As(t,e,r,n,a){return e=+e,r>>>=0,a||_s(t,0,r,8),Xl.write(t,e,r,n,52,8),r+8}Jl.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||xs(t,e,this.length);for(var n=this[t],a=1,i=0;++i>>=0,e>>>=0,r||xs(t,e,this.length);for(var n=this[t+--e],a=1;e>0&&(a*=256);)n+=this[t+--e]*a;return n},Jl.prototype.readUInt8=function(t,e){return t>>>=0,e||xs(t,1,this.length),this[t]},Jl.prototype.readUInt16LE=function(t,e){return t>>>=0,e||xs(t,2,this.length),this[t]|this[t+1]<<8},Jl.prototype.readUInt16BE=function(t,e){return t>>>=0,e||xs(t,2,this.length),this[t]<<8|this[t+1]},Jl.prototype.readUInt32LE=function(t,e){return t>>>=0,e||xs(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Jl.prototype.readUInt32BE=function(t,e){return t>>>=0,e||xs(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Jl.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||xs(t,e,this.length);for(var n=this[t],a=1,i=0;++i=(a*=128)&&(n-=Math.pow(2,8*e)),n},Jl.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||xs(t,e,this.length);for(var n=e,a=1,i=this[t+--n];n>0&&(a*=256);)i+=this[t+--n]*a;return i>=(a*=128)&&(i-=Math.pow(2,8*e)),i},Jl.prototype.readInt8=function(t,e){return t>>>=0,e||xs(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Jl.prototype.readInt16LE=function(t,e){t>>>=0,e||xs(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Jl.prototype.readInt16BE=function(t,e){t>>>=0,e||xs(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Jl.prototype.readInt32LE=function(t,e){return t>>>=0,e||xs(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Jl.prototype.readInt32BE=function(t,e){return t>>>=0,e||xs(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Jl.prototype.readFloatLE=function(t,e){return t>>>=0,e||xs(t,4,this.length),Xl.read(this,t,!0,23,4)},Jl.prototype.readFloatBE=function(t,e){return t>>>=0,e||xs(t,4,this.length),Xl.read(this,t,!1,23,4)},Jl.prototype.readDoubleLE=function(t,e){return t>>>=0,e||xs(t,8,this.length),Xl.read(this,t,!0,52,8)},Jl.prototype.readDoubleBE=function(t,e){return t>>>=0,e||xs(t,8,this.length),Xl.read(this,t,!1,52,8)},Jl.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||bs(this,t,e,r,Math.pow(2,8*r)-1,0);var a=1,i=0;for(this[e]=255&t;++i>>=0,r>>>=0,n)||bs(this,t,e,r,Math.pow(2,8*r)-1,0);var a=r-1,i=1;for(this[e+a]=255&t;--a>=0&&(i*=256);)this[e+a]=t/i&255;return e+r},Jl.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,1,255,0),this[e]=255&t,e+1},Jl.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},Jl.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},Jl.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},Jl.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Jl.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var a=Math.pow(2,8*r-1);bs(this,t,e,r,a-1,-a)}var i=0,o=1,l=0;for(this[e]=255&t;++i>0)-l&255;return e+r},Jl.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var a=Math.pow(2,8*r-1);bs(this,t,e,r,a-1,-a)}var i=r-1,o=1,l=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===l&&0!==this[e+i+1]&&(l=1),this[e+i]=(t/o>>0)-l&255;return e+r},Jl.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},Jl.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},Jl.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},Jl.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},Jl.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||bs(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Jl.prototype.writeFloatLE=function(t,e,r){return ws(this,t,e,!0,r)},Jl.prototype.writeFloatBE=function(t,e,r){return ws(this,t,e,!1,r)},Jl.prototype.writeDoubleLE=function(t,e,r){return As(this,t,e,!0,r)},Jl.prototype.writeDoubleBE=function(t,e,r){return As(this,t,e,!1,r)},Jl.prototype.copy=function(t,e,r,n){if(!Jl.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return a},Jl.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Jl.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var a=t.charCodeAt(0);("utf8"===n&&a<128||"latin1"===n)&&(t=a)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i55295&&r<57344){if(!a){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&i.push(239,191,189);continue}a=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),a=r;continue}r=65536+(a-55296<<10|r-56320)}else a&&(e-=3)>-1&&i.push(239,191,189);if(a=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function Es(t){return Fl.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(Ms,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Cs(t,e,r,n){for(var a=0;a=e.length||a>=t.length);++a)e[a+r]=t[a];return a}function Ss(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function Ls(t){return t!=t}var Os=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n0?r.pop():new ArrayBuffer(t)}function s(t){return new Uint8Array(l(t),0,t)}function u(t){return new Uint16Array(l(2*t),0,t)}function c(t){return new Uint32Array(l(4*t),0,t)}function f(t){return new Int8Array(l(t),0,t)}function h(t){return new Int16Array(l(2*t),0,t)}function d(t){return new Int32Array(l(4*t),0,t)}function p(t){return new Float32Array(l(4*t),0,t)}function g(t){return new Float64Array(l(8*t),0,t)}function v(t){return r?new Uint8ClampedArray(l(t),0,t):s(t)}function m(t){return new DataView(l(t),0,t)}function y(t){t=Pl.nextPow2(t);var r=Pl.log2(t),n=i[r];return n.length>0?n.pop():new e(t)}Ds.free=function(t){if(e.isBuffer(t))i[Pl.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var r=t.length||t.byteLength,n=0|Pl.log2(r);a[n].push(t)}},Ds.freeUint8=Ds.freeUint16=Ds.freeUint32=Ds.freeInt8=Ds.freeInt16=Ds.freeInt32=Ds.freeFloat32=Ds.freeFloat=Ds.freeFloat64=Ds.freeDouble=Ds.freeUint8Clamped=Ds.freeDataView=function(t){o(t.buffer)},Ds.freeArrayBuffer=o,Ds.freeBuffer=function(t){i[Pl.log2(t.length)].push(t)},Ds.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return l(t);switch(e){case"uint8":return s(t);case"uint16":return u(t);case"uint32":return c(t);case"int8":return f(t);case"int16":return h(t);case"int32":return d(t);case"float":case"float32":return p(t);case"double":case"float64":return g(t);case"uint8_clamped":return v(t);case"buffer":return y(t);case"data":case"dataview":return m(t);default:return null}return null},Ds.mallocArrayBuffer=l,Ds.mallocUint8=s,Ds.mallocUint16=u,Ds.mallocUint32=c,Ds.mallocInt8=f,Ds.mallocInt16=h,Ds.mallocInt32=d,Ds.mallocFloat32=Ds.mallocFloat=p,Ds.mallocFloat64=Ds.mallocDouble=g,Ds.mallocUint8Clamped=v,Ds.mallocDataView=m,Ds.mallocBuffer=y,Ds.clearCache=function(){for(var t=0;t<32;++t)n.UINT8[t].length=0,n.UINT16[t].length=0,n.UINT32[t].length=0,n.INT8[t].length=0,n.INT16[t].length=0,n.INT32[t].length=0,n.FLOAT[t].length=0,n.DOUBLE[t].length=0,n.UINT8C[t].length=0,a[t].length=0,i[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Yl.Buffer);var Rs=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function Ps(t,e,r,n,a){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=a}var Is=Ps.prototype;function Bs(t,e,r,n,a,i){var o=a.length*a.BYTES_PER_ELEMENT;if(i<0)return t.bufferData(e,a,n),o;if(o+i>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,i,a),r}function Fs(t,e){for(var r=Ds.malloc(t.length,e),n=t.length,a=0;a=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=Bs(this.gl,this.type,this.length,this.usage,t.data,e):this.length=Bs(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var n=Ds.malloc(t.size,r),a=Rl(n,t.shape);pl.assign(a,t),this.length=Bs(this.gl,this.type,this.length,this.usage,e<0?n:n.subarray(0,t.size),e),Ds.free(n)}}else if(Array.isArray(t)){var i;i=this.type===this.gl.ELEMENT_ARRAY_BUFFER?Fs(t,"uint16"):Fs(t,"float32"),this.length=Bs(this.gl,this.type,this.length,this.usage,e<0?i:i.subarray(0,t.length),e),Ds.free(i)}else if("object"==typeof t&&"number"==typeof t.length)this.length=Bs(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}};var zs=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=new Ps(t,r,t.createBuffer(),0,n);return a.update(e),a},Ns=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;n=0){var f=u.charCodeAt(u.length-1)-48;if(f<2||f>4)throw new Hs("","Invalid data type for attribute "+s+": "+u);Ys(t,e,c[0],n,f,a,s)}else{if(!(u.indexOf("mat")>=0))throw new Hs("","Unknown data type for attribute "+s+": "+u);var f=u.charCodeAt(u.length-1)-48;if(f<2||f>4)throw new Hs("","Invalid data type for attribute "+s+": "+u);Ws(t,e,c,n,f,a,s)}}}return a};function Gs(t,e,r,n,a,i){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=a,this._constFunc=i}var Xs=Gs.prototype;function Ys(t,e,r,n,a,i,o){for(var l=["gl","v"],s=[],u=0;u1){s[0]in o||(o[s[0]]=[]),o=o[s[0]];for(var u=1;u4)throw new Hs("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+a+"fv(locations["+e+"],false,obj"+t+")"}throw new Hs("","Unknown uniform data type for "+name+": "+r)}var a=r.charCodeAt(r.length-1)-48;if(a<2||a>4)throw new Hs("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+a+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+a+"fv(locations["+e+"],obj"+t+")";default:throw new Hs("","Unrecognized data type for vector "+name+": "+r)}}}function i(e){for(var i=["return function updateProperty(obj){"],o=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var a in r){var i=r[a],o=e;parseInt(a)+""===a?o+="["+a+"]":o+="."+a,"object"==typeof i?n.push.apply(n,t(o,i)):n.push([o,i])}return n}("",e),l=0;l4)throw new Hs("","Invalid data type");return"b"===t.charAt(0)?$s(r,!1):$s(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new Hs("","Invalid uniform dimension type for matrix "+name+": "+t);return $s(r*r,0)}throw new Hs("","Unknown uniform data type for "+name+": "+t)}}(r[s].type);var c}function l(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1)for(var l=0;l=r)return au.substr(0,r);for(;r>au.length&&e>1;)1&e&&(au+=t),e>>=1,t+=t;return au=(au+=t).substr(0,r)};var ou=function(t,e,r){return iu(r=void 0!==r?r+"":" ",e)+t},lu=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),a=String(n.length+e-1).length;return n.map(function(t,n){var i=n+e,o=String(i).length,l=ou(i,a-o);return l+r+t}).join("\n")};var su={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},uu=function(t){return su[t]},cu=function(t){return atob(t)},fu=["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"],hu=(fu=fu.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)})).concat(["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","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"]),du=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","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","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"],pu=du.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),gu=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],vu=function(t){var e,r,n,a=0,i=0,o=mu,l=[],s=[],u=1,c=0,f=0,h=!1,d=!1,p="",g=fu,v=du;"300 es"===(t=t||{}).version&&(g=hu,v=pu);return function(t){return s=[],null!==t?function(t){var r;a=0,n=(p+=t).length;for(;e=p[a],a0)continue;r=t.slice(0,1).join("")}return m(r),f+=r.length,(l=l.slice(r.length)).length}}function M(){return/[^a-fA-F0-9]/.test(e)?(m(l.join("")),o=mu,a):(l.push(e),r=e,a+1)}function T(){return"."===e?(l.push(e),o=Mu,r=e,a+1):/[eE]/.test(e)?(l.push(e),o=Mu,r=e,a+1):"x"===e&&1===l.length&&"0"===l[0]?(o=Lu,l.push(e),r=e,a+1):/[^\d]/.test(e)?(m(l.join("")),o=mu,a):(l.push(e),r=e,a+1)}function k(){return"f"===e&&(l.push(e),r=e,a+=1),/[eE]/.test(e)?(l.push(e),r=e,a+1):"-"===e&&/[eE]/.test(r)?(l.push(e),r=e,a+1):/[^\d]/.test(e)?(m(l.join("")),o=mu,a):(l.push(e),r=e,a+1)}function E(){if(/[^\d\w_]/.test(e)){var t=l.join("");return o=v.indexOf(t)>-1?Eu:g.indexOf(t)>-1?ku:Tu,m(l.join("")),o=mu,a}return l.push(e),r=e,a+1}},mu=999,yu=9999,xu=0,bu=1,_u=2,wu=3,Au=4,Mu=5,Tu=6,ku=7,Eu=8,Cu=9,Su=10,Lu=11,Ou=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];var Du=function(t,e){var r=vu(e),n=[];return n=(n=n.concat(r(t))).concat(r(null))};var Ru=function(t){for(var e=Array.isArray(t)?t:Du(t),r=0;r=0),l[8]){case"b":a=parseInt(a,10).toString(2);break;case"c":a=String.fromCharCode(parseInt(a,10));break;case"d":case"i":a=parseInt(a,10);break;case"j":a=JSON.stringify(a,null,l[6]?parseInt(l[6]):0);break;case"e":a=l[7]?parseFloat(a).toExponential(l[7]):parseFloat(a).toExponential();break;case"f":a=l[7]?parseFloat(a).toFixed(l[7]):parseFloat(a);break;case"g":a=l[7]?String(Number(a.toPrecision(l[7]))):parseFloat(a);break;case"o":a=(parseInt(a,10)>>>0).toString(8);break;case"s":a=String(a),a=l[7]?a.substring(0,l[7]):a;break;case"t":a=String(!!a),a=l[7]?a.substring(0,l[7]):a;break;case"T":a=Object.prototype.toString.call(a).slice(8,-1).toLowerCase(),a=l[7]?a.substring(0,l[7]):a;break;case"u":a=parseInt(a,10)>>>0;break;case"v":a=a.valueOf(),a=l[7]?a.substring(0,l[7]):a;break;case"x":a=(parseInt(a,10)>>>0).toString(16);break;case"X":a=(parseInt(a,10)>>>0).toString(16).toUpperCase()}t.json.test(l[8])?g+=a:(!t.number.test(l[8])||f&&!l[3]?h="":(h=f?"+":"-",a=a.toString().replace(t.sign,"")),u=l[4]?"0"===l[4]?"0":l[4].charAt(1):" ",c=l[6]-(h+a).length,s=l[6]&&c>0?u.repeat(c):"",g+=l[5]?h+a+s:"0"===u?h+s+a:s+h+a)}return g}(function(e){if(n[e])return n[e];var r,a=e,i=[],o=0;for(;a;){if(null!==(r=t.text.exec(a)))i.push(r[0]);else if(null!==(r=t.modulo.exec(a)))i.push("%");else{if(null===(r=t.placeholder.exec(a)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var l=[],s=r[2],u=[];if(null===(u=t.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(l.push(u[1]);""!==(s=s.substring(u[0].length));)if(null!==(u=t.key_access.exec(s)))l.push(u[1]);else{if(null===(u=t.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");l.push(u[1])}r[2]=l}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");i.push(r)}a=a.substring(r[0].length)}return n[e]=i}(r),arguments)}function r(t,r){return e.apply(null,[t].concat(r||[]))}var n=Object.create(null);void 0!==Pu&&(Pu.sprintf=e,Pu.vsprintf=r),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=r,"function"==typeof CC&&CC.amd&&CC(function(){return{sprintf:e,vsprintf:r}}))}();var Iu=Pu.sprintf,Bu=function(t,e,r){"use strict";var n=Ru(e)||"of unknown name (see npm glsl-shader-name)",a="unknown type";void 0!==r&&(a=r===uu.FRAGMENT_SHADER?"fragment":"vertex");for(var i=Iu("Error compiling %s shader %s:\n",a,n),o=Iu("%s%s",i,t),l=t.split("\n"),s={},u=0;ur)for(t=r;te)for(t=e;t=0){for(var v=0|g.type.charAt(g.type.length-1),m=new Array(v),y=0;y=0;)x+=1;p[f]=x}var b=new Array(r.length);function _(){i.program=Nu.program(o,i._vref,i._fref,d,p);for(var t=0;t>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function rc(t,e,r,n){return new Function([ec("A","x"+t+"y",e,["y"],n),ec("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}tc.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},tc.drawBox=($u=[0,0],Ku=[0,0],function(t,e,r,n,a){var i=this.plot,o=this.shader,l=i.gl;$u[0]=t,$u[1]=e,Ku[0]=r,Ku[1]=n,o.uniforms.lo=$u,o.uniforms.hi=Ku,o.uniforms.color=a,l.drawArrays(l.TRIANGLE_STRIP,0,4)}),tc.dispose=function(){this.vbo.dispose(),this.shader.dispose()};var nc={ge:rc(">=",!1,"GE"),gt:rc(">",!1,"GT"),lt:rc("<",!0,"LT"),le:rc("<=",!0,"LE"),eq:rc("-",!0,"EQ",!0)};function ac(t,e,r,n,a){var i=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function ic(t,e,r,n){return new Function([ac("A","x"+t+"y",e,["y"],n),ac("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var oc={ge:ic(">=",!1,"GE"),gt:ic(">",!1,"GT"),lt:ic("<",!0,"LT"),le:ic("<=",!0,"LE"),eq:ic("-",!0,"EQ",!0)},lc=function(t){var e=t.gl,r=zs(e),n=Zu(e,Us.gridVert,Us.gridFrag),a=Zu(e,Us.tickVert,Us.gridFrag);return new sc(t,r,n,a)};function sc(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function uc(t,e){return t-e}var cc,fc,hc,dc,pc,gc=sc.prototype;gc.draw=(cc=[0,0],fc=[0,0],hc=[0,0],function(){for(var t=this.plot,e=this.vbo,r=this.shader,n=this.ticks,a=t.gl,i=t._tickBounds,o=t.dataBox,l=t.viewBox,s=t.gridLineWidth,u=t.gridLineColor,c=t.gridLineEnable,f=t.pixelRatio,h=0;h<2;++h){var d=i[h],p=i[h+2]-d,g=.5*(o[h+2]+o[h]),v=o[h+2]-o[h];fc[h]=2*p/v,cc[h]=2*(d-g)/v}r.bind(),e.bind(),r.attributes.dataCoord.pointer(),r.uniforms.dataShift=cc,r.uniforms.dataScale=fc;var m=0;for(h=0;h<2;++h){hc[0]=hc[1]=0,hc[h]=1,r.uniforms.dataAxis=hc,r.uniforms.lineWidth=s[h]/(l[h+2]-l[h])*f,r.uniforms.color=u[h];var y=6*n[h].length;c[h]&&y&&a.drawArrays(a.TRIANGLES,m,y),m+=y}}),gc.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],i=[0,0];return function(){for(var o=this.plot,l=this.vbo,s=this.tickShader,u=this.ticks,c=o.gl,f=o._tickBounds,h=o.dataBox,d=o.viewBox,p=o.pixelRatio,g=o.screenBox,v=g[2]-g[0],m=g[3]-g[1],y=d[2]-d[0],x=d[3]-d[1],b=0;b<2;++b){var _=f[b],w=f[b+2]-_,A=.5*(h[b+2]+h[b]),M=h[b+2]-h[b];e[b]=2*w/M,t[b]=2*(_-A)/M}e[0]*=y/v,t[0]*=y/v,e[1]*=x/m,t[1]*=x/m,s.bind(),l.bind(),s.attributes.dataCoord.pointer();var T=s.uniforms;T.dataShift=t,T.dataScale=e;var k=o.tickMarkLength,E=o.tickMarkWidth,C=o.tickMarkColor,S=6*u[0].length,L=Math.min(oc.ge(u[0],(h[0]-f[0])/(f[2]-f[0]),uc),u[0].length),O=Math.min(oc.gt(u[0],(h[2]-f[0])/(f[2]-f[0]),uc),u[0].length),D=0+6*L,R=6*Math.max(0,O-L),P=Math.min(oc.ge(u[1],(h[1]-f[1])/(f[3]-f[1]),uc),u[1].length),I=Math.min(oc.gt(u[1],(h[3]-f[1])/(f[3]-f[1]),uc),u[1].length),B=S+6*P,F=6*Math.max(0,I-P);a[0]=2*(d[0]-k[1])/v-1,a[1]=(d[3]+d[1])/m-1,i[0]=k[1]*p/v,i[1]=E[1]*p/m,F&&(T.color=C[1],T.tickScale=i,T.dataAxis=n,T.screenOffset=a,c.drawArrays(c.TRIANGLES,B,F)),a[0]=(d[2]+d[0])/v-1,a[1]=2*(d[1]-k[0])/m-1,i[0]=E[0]*p/v,i[1]=k[0]*p/m,R&&(T.color=C[0],T.tickScale=i,T.dataAxis=r,T.screenOffset=a,c.drawArrays(c.TRIANGLES,D,R)),a[0]=2*(d[2]+k[3])/v-1,a[1]=(d[3]+d[1])/m-1,i[0]=k[3]*p/v,i[1]=E[3]*p/m,F&&(T.color=C[3],T.tickScale=i,T.dataAxis=n,T.screenOffset=a,c.drawArrays(c.TRIANGLES,B,F)),a[0]=(d[2]+d[0])/v-1,a[1]=2*(d[3]+k[2])/m-1,i[0]=E[2]*p/v,i[1]=k[2]*p/m,R&&(T.color=C[2],T.tickScale=i,T.dataAxis=r,T.screenOffset=a,c.drawArrays(c.TRIANGLES,D,R))}}(),gc.update=(dc=[1,1,-1,-1,1,-1],pc=[1,-1,1,1,-1,-1],function(t){for(var e=t.ticks,r=t.bounds,n=new Float32Array(18*(e[0].length+e[1].length)),a=(this.plot.zeroLineEnable,0),i=[[],[]],o=0;o<2;++o)for(var l=i[o],s=e[o],u=r[o],c=r[o+2],f=0;f1)for(var r=1;r=n?(a=f,(s+=1)=n?(a=f,(s+=1)>1;return["sum(",Gc(t.slice(0,e)),",",Gc(t.slice(e)),")"].join("")}function Xc(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return Xc(e,t)}function Yc(t){if(2===t.length)return[["diff(",Xc(t[0][0],t[1][1]),",",Xc(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0;){for(var s=r.pop(),i=r.pop(),u=-1,c=-1,o=a[i],h=1;h=0||(e.flip(i,s),Kc(t,e,r,u,i,c),Kc(t,e,r,i,c,u),Kc(t,e,r,c,s,u),Kc(t,e,r,s,u,c)))}};function Kc(t,e,r,n,a,i){var o=e.opposite(n,a);if(!(o<0)){if(a0||o.length>0;){for(;i.length>0;){var f=i.pop();if(l[f]!==-a){l[f]=a;s[f];for(var h=0;h<3;++h){var d=c[3*f+h];d>=0&&0===l[d]&&(u[3*f+h]?o.push(d):(i.push(d),l[d]=a))}}}var p=o;o=i,i=p,o.length=0,a=-a}var g=function(t,e,r){for(var n=0,a=0;a>1;return["sum(",sf(t.slice(0,e)),",",sf(t.slice(e)),")"].join("")}function uf(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(i<=0)return o;n=a+i}else{if(!(a<0))return o;if(i>=0)return o;n=-(a+i)}var l=3.3306690738754716e-16*n;return o>=l||o<=-l?o:ff(t,e,r)},function(t,e,r,n){var a=t[0]-n[0],i=e[0]-n[0],o=r[0]-n[0],l=t[1]-n[1],s=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],d=i*u,p=o*s,g=o*l,v=a*u,m=a*s,y=i*l,x=c*(d-p)+f*(g-v)+h*(m-y),b=7.771561172376103e-16*((Math.abs(d)+Math.abs(p))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(f)+(Math.abs(m)+Math.abs(y))*Math.abs(h));return x>b||-x>b?x:hf(t,e,r,n)}];!function(){for(;df.length<=of;)df.push(cf(df.length));for(var t=[],e=["slow"],r=0;r<=of;++r)t.push("a"+r),e.push("o"+r);var n=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(r=2;r<=of;++r)n.push("case ",r,":return o",r,"(",t.slice(0,r).join(),");");n.push("}var s=new Array(arguments.length);for(var i=0;is[0]&&a.push(new bf(s,l,mf,i),new bf(l,s,vf,i))}a.sort(_f);for(var u=a[0].a[0]-(1+Math.abs(a[0].a[0]))*Math.pow(2,-52),c=[new xf([u,1],[u,0],-1,[],[],[],[])],f=[],i=0,h=a.length;i1&&pf(r[u[c-2]],r[u[c-1]],n)>0;)t.push([u[c-1],u[c-2],a]),c-=1;u.length=c,u.push(a);var f=s.upperIds;for(c=f.length;c>1&&pf(r[f[c-2]],r[f[c-1]],n)<0;)t.push([f[c-2],f[c-1],a]),c-=1;f.length=c,f.push(a)}}function Mf(t,e){var r;return(r=t.a[0]=0}}(),Sf.removeTriangle=function(t,e,r){var n=this.stars;Lf(n[t],e,r),Lf(n[e],r,t),Lf(n[r],t,e)},Sf.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},Sf.opposite=function(t,e){for(var r=this.stars[e],n=1,a=r.length;n=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function l(t,e,r,n){for(var a=0,i=Math.min(t.length,r),o=e;o=49?l-49+10:l>=17?l-17+10:l}return a}a.isBN=function(t){return t instanceof a||null!==t&&"object"==typeof t&&t.constructor.wordSize===a.wordSize&&Array.isArray(t.words)},a.max=function(t,e){return t.cmp(e)>0?t:e},a.min=function(t,e){return t.cmp(e)<0?t:e},a.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var a=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&a++,16===e?this._parseHex(t,a):this._parseBase(t,e,a),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},a.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},a.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var a=0;a=0;a-=3)o=t[a]|t[a-1]<<8|t[a-2]<<16,this.words[i]|=o<>>26-l&67108863,(l+=24)>=26&&(l-=26,i++);else if("le"===n)for(a=0,i=0;a>>26-l&67108863,(l+=24)>=26&&(l-=26,i++);return this.strip()},a.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)a=o(t,r,r+6),this.words[n]|=a<>>26-i&4194303,(i+=24)>=26&&(i-=26,n++);r+6!==e&&(a=o(t,e,r+6),this.words[n]|=a<>>26-i&4194303),this.strip()},a.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,a=1;a<=67108863;a*=e)n++;n--,a=a/e|0;for(var i=t.length-r,o=i%n,s=Math.min(i,i-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},a.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},a.prototype.inspect=function(){return(this.red?""};var s=["","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"],u=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var a=0|t.words[0],i=0|e.words[0],o=a*i,l=67108863&o,s=o/67108864|0;r.words[0]=l;for(var u=1;u>>26,f=67108863&s,h=Math.min(u,e.length-1),d=Math.max(0,u-t.length+1);d<=h;d++){var p=u-d|0;c+=(o=(a=0|t.words[p])*(i=0|e.words[d])+f)/67108864|0,f=67108863&o}r.words[u]=0|f,s=0|c}return 0!==s?r.words[u]=0|s:r.length--,r.strip()}a.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var a=0,i=0,o=0;o>>24-a&16777215)||o!==this.length-1?s[6-f.length]+f+n:f+n,(a+=2)>=26&&(a-=26,o--)}for(0!==i&&(n=i.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var h=u[t],d=c[t];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(d).toString(t);n=(p=p.idivn(d)).isZero()?g+n:s[h-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},a.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},a.prototype.toJSON=function(){return this.toString(16)},a.prototype.toBuffer=function(t,e){return r(void 0!==i),this.toArrayLike(i,t,e)},a.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},a.prototype.toArrayLike=function(t,e,n){var a=this.byteLength(),i=n||Math.max(1,a);r(a<=i,"byte array longer than desired length"),r(i>0,"Requested array length <= 0"),this.strip();var o,l,s="le"===e,u=new t(i),c=this.clone();if(s){for(l=0;!c.isZero();l++)o=c.andln(255),c.iushrn(8),u[l]=o;for(;l=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},a.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},a.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},a.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},a.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},a.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},a.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},a.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},a.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},a.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var a=0;a0&&(this.words[a]=~this.words[a]&67108863>>26-n),this.strip()},a.prototype.notn=function(t){return this.clone().inotn(t)},a.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,a=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var a=0,i=0;i>>26;for(;0!==a&&i>>26;if(this.length=r.length,0!==a)this.words[this.length]=a,this.length++;else if(r!==this)for(;it.length?this.clone().iadd(t):t.clone().iadd(this)},a.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,a=this.cmp(t);if(0===a)return this.negative=0,this.length=1,this.words[0]=0,this;a>0?(r=this,n=t):(r=t,n=this);for(var i=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==i&&o>26,this.words[o]=67108863&e;if(0===i&&o>>13,d=0|o[1],p=8191&d,g=d>>>13,v=0|o[2],m=8191&v,y=v>>>13,x=0|o[3],b=8191&x,_=x>>>13,w=0|o[4],A=8191&w,M=w>>>13,T=0|o[5],k=8191&T,E=T>>>13,C=0|o[6],S=8191&C,L=C>>>13,O=0|o[7],D=8191&O,R=O>>>13,P=0|o[8],I=8191&P,B=P>>>13,F=0|o[9],z=8191&F,N=F>>>13,j=0|l[0],U=8191&j,V=j>>>13,H=0|l[1],q=8191&H,G=H>>>13,X=0|l[2],Y=8191&X,W=X>>>13,Z=0|l[3],J=8191&Z,Q=Z>>>13,$=0|l[4],K=8191&$,tt=$>>>13,et=0|l[5],rt=8191&et,nt=et>>>13,at=0|l[6],it=8191&at,ot=at>>>13,lt=0|l[7],st=8191<,ut=lt>>>13,ct=0|l[8],ft=8191&ct,ht=ct>>>13,dt=0|l[9],pt=8191&dt,gt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(u+(n=Math.imul(f,U))|0)+((8191&(a=(a=Math.imul(f,V))+Math.imul(h,U)|0))<<13)|0;u=((i=Math.imul(h,V))+(a>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(p,U),a=(a=Math.imul(p,V))+Math.imul(g,U)|0,i=Math.imul(g,V);var mt=(u+(n=n+Math.imul(f,q)|0)|0)+((8191&(a=(a=a+Math.imul(f,G)|0)+Math.imul(h,q)|0))<<13)|0;u=((i=i+Math.imul(h,G)|0)+(a>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,U),a=(a=Math.imul(m,V))+Math.imul(y,U)|0,i=Math.imul(y,V),n=n+Math.imul(p,q)|0,a=(a=a+Math.imul(p,G)|0)+Math.imul(g,q)|0,i=i+Math.imul(g,G)|0;var yt=(u+(n=n+Math.imul(f,Y)|0)|0)+((8191&(a=(a=a+Math.imul(f,W)|0)+Math.imul(h,Y)|0))<<13)|0;u=((i=i+Math.imul(h,W)|0)+(a>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(b,U),a=(a=Math.imul(b,V))+Math.imul(_,U)|0,i=Math.imul(_,V),n=n+Math.imul(m,q)|0,a=(a=a+Math.imul(m,G)|0)+Math.imul(y,q)|0,i=i+Math.imul(y,G)|0,n=n+Math.imul(p,Y)|0,a=(a=a+Math.imul(p,W)|0)+Math.imul(g,Y)|0,i=i+Math.imul(g,W)|0;var xt=(u+(n=n+Math.imul(f,J)|0)|0)+((8191&(a=(a=a+Math.imul(f,Q)|0)+Math.imul(h,J)|0))<<13)|0;u=((i=i+Math.imul(h,Q)|0)+(a>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(A,U),a=(a=Math.imul(A,V))+Math.imul(M,U)|0,i=Math.imul(M,V),n=n+Math.imul(b,q)|0,a=(a=a+Math.imul(b,G)|0)+Math.imul(_,q)|0,i=i+Math.imul(_,G)|0,n=n+Math.imul(m,Y)|0,a=(a=a+Math.imul(m,W)|0)+Math.imul(y,Y)|0,i=i+Math.imul(y,W)|0,n=n+Math.imul(p,J)|0,a=(a=a+Math.imul(p,Q)|0)+Math.imul(g,J)|0,i=i+Math.imul(g,Q)|0;var bt=(u+(n=n+Math.imul(f,K)|0)|0)+((8191&(a=(a=a+Math.imul(f,tt)|0)+Math.imul(h,K)|0))<<13)|0;u=((i=i+Math.imul(h,tt)|0)+(a>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(k,U),a=(a=Math.imul(k,V))+Math.imul(E,U)|0,i=Math.imul(E,V),n=n+Math.imul(A,q)|0,a=(a=a+Math.imul(A,G)|0)+Math.imul(M,q)|0,i=i+Math.imul(M,G)|0,n=n+Math.imul(b,Y)|0,a=(a=a+Math.imul(b,W)|0)+Math.imul(_,Y)|0,i=i+Math.imul(_,W)|0,n=n+Math.imul(m,J)|0,a=(a=a+Math.imul(m,Q)|0)+Math.imul(y,J)|0,i=i+Math.imul(y,Q)|0,n=n+Math.imul(p,K)|0,a=(a=a+Math.imul(p,tt)|0)+Math.imul(g,K)|0,i=i+Math.imul(g,tt)|0;var _t=(u+(n=n+Math.imul(f,rt)|0)|0)+((8191&(a=(a=a+Math.imul(f,nt)|0)+Math.imul(h,rt)|0))<<13)|0;u=((i=i+Math.imul(h,nt)|0)+(a>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(S,U),a=(a=Math.imul(S,V))+Math.imul(L,U)|0,i=Math.imul(L,V),n=n+Math.imul(k,q)|0,a=(a=a+Math.imul(k,G)|0)+Math.imul(E,q)|0,i=i+Math.imul(E,G)|0,n=n+Math.imul(A,Y)|0,a=(a=a+Math.imul(A,W)|0)+Math.imul(M,Y)|0,i=i+Math.imul(M,W)|0,n=n+Math.imul(b,J)|0,a=(a=a+Math.imul(b,Q)|0)+Math.imul(_,J)|0,i=i+Math.imul(_,Q)|0,n=n+Math.imul(m,K)|0,a=(a=a+Math.imul(m,tt)|0)+Math.imul(y,K)|0,i=i+Math.imul(y,tt)|0,n=n+Math.imul(p,rt)|0,a=(a=a+Math.imul(p,nt)|0)+Math.imul(g,rt)|0,i=i+Math.imul(g,nt)|0;var wt=(u+(n=n+Math.imul(f,it)|0)|0)+((8191&(a=(a=a+Math.imul(f,ot)|0)+Math.imul(h,it)|0))<<13)|0;u=((i=i+Math.imul(h,ot)|0)+(a>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(D,U),a=(a=Math.imul(D,V))+Math.imul(R,U)|0,i=Math.imul(R,V),n=n+Math.imul(S,q)|0,a=(a=a+Math.imul(S,G)|0)+Math.imul(L,q)|0,i=i+Math.imul(L,G)|0,n=n+Math.imul(k,Y)|0,a=(a=a+Math.imul(k,W)|0)+Math.imul(E,Y)|0,i=i+Math.imul(E,W)|0,n=n+Math.imul(A,J)|0,a=(a=a+Math.imul(A,Q)|0)+Math.imul(M,J)|0,i=i+Math.imul(M,Q)|0,n=n+Math.imul(b,K)|0,a=(a=a+Math.imul(b,tt)|0)+Math.imul(_,K)|0,i=i+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,a=(a=a+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,i=i+Math.imul(y,nt)|0,n=n+Math.imul(p,it)|0,a=(a=a+Math.imul(p,ot)|0)+Math.imul(g,it)|0,i=i+Math.imul(g,ot)|0;var At=(u+(n=n+Math.imul(f,st)|0)|0)+((8191&(a=(a=a+Math.imul(f,ut)|0)+Math.imul(h,st)|0))<<13)|0;u=((i=i+Math.imul(h,ut)|0)+(a>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(I,U),a=(a=Math.imul(I,V))+Math.imul(B,U)|0,i=Math.imul(B,V),n=n+Math.imul(D,q)|0,a=(a=a+Math.imul(D,G)|0)+Math.imul(R,q)|0,i=i+Math.imul(R,G)|0,n=n+Math.imul(S,Y)|0,a=(a=a+Math.imul(S,W)|0)+Math.imul(L,Y)|0,i=i+Math.imul(L,W)|0,n=n+Math.imul(k,J)|0,a=(a=a+Math.imul(k,Q)|0)+Math.imul(E,J)|0,i=i+Math.imul(E,Q)|0,n=n+Math.imul(A,K)|0,a=(a=a+Math.imul(A,tt)|0)+Math.imul(M,K)|0,i=i+Math.imul(M,tt)|0,n=n+Math.imul(b,rt)|0,a=(a=a+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,i=i+Math.imul(_,nt)|0,n=n+Math.imul(m,it)|0,a=(a=a+Math.imul(m,ot)|0)+Math.imul(y,it)|0,i=i+Math.imul(y,ot)|0,n=n+Math.imul(p,st)|0,a=(a=a+Math.imul(p,ut)|0)+Math.imul(g,st)|0,i=i+Math.imul(g,ut)|0;var Mt=(u+(n=n+Math.imul(f,ft)|0)|0)+((8191&(a=(a=a+Math.imul(f,ht)|0)+Math.imul(h,ft)|0))<<13)|0;u=((i=i+Math.imul(h,ht)|0)+(a>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(z,U),a=(a=Math.imul(z,V))+Math.imul(N,U)|0,i=Math.imul(N,V),n=n+Math.imul(I,q)|0,a=(a=a+Math.imul(I,G)|0)+Math.imul(B,q)|0,i=i+Math.imul(B,G)|0,n=n+Math.imul(D,Y)|0,a=(a=a+Math.imul(D,W)|0)+Math.imul(R,Y)|0,i=i+Math.imul(R,W)|0,n=n+Math.imul(S,J)|0,a=(a=a+Math.imul(S,Q)|0)+Math.imul(L,J)|0,i=i+Math.imul(L,Q)|0,n=n+Math.imul(k,K)|0,a=(a=a+Math.imul(k,tt)|0)+Math.imul(E,K)|0,i=i+Math.imul(E,tt)|0,n=n+Math.imul(A,rt)|0,a=(a=a+Math.imul(A,nt)|0)+Math.imul(M,rt)|0,i=i+Math.imul(M,nt)|0,n=n+Math.imul(b,it)|0,a=(a=a+Math.imul(b,ot)|0)+Math.imul(_,it)|0,i=i+Math.imul(_,ot)|0,n=n+Math.imul(m,st)|0,a=(a=a+Math.imul(m,ut)|0)+Math.imul(y,st)|0,i=i+Math.imul(y,ut)|0,n=n+Math.imul(p,ft)|0,a=(a=a+Math.imul(p,ht)|0)+Math.imul(g,ft)|0,i=i+Math.imul(g,ht)|0;var Tt=(u+(n=n+Math.imul(f,pt)|0)|0)+((8191&(a=(a=a+Math.imul(f,gt)|0)+Math.imul(h,pt)|0))<<13)|0;u=((i=i+Math.imul(h,gt)|0)+(a>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(z,q),a=(a=Math.imul(z,G))+Math.imul(N,q)|0,i=Math.imul(N,G),n=n+Math.imul(I,Y)|0,a=(a=a+Math.imul(I,W)|0)+Math.imul(B,Y)|0,i=i+Math.imul(B,W)|0,n=n+Math.imul(D,J)|0,a=(a=a+Math.imul(D,Q)|0)+Math.imul(R,J)|0,i=i+Math.imul(R,Q)|0,n=n+Math.imul(S,K)|0,a=(a=a+Math.imul(S,tt)|0)+Math.imul(L,K)|0,i=i+Math.imul(L,tt)|0,n=n+Math.imul(k,rt)|0,a=(a=a+Math.imul(k,nt)|0)+Math.imul(E,rt)|0,i=i+Math.imul(E,nt)|0,n=n+Math.imul(A,it)|0,a=(a=a+Math.imul(A,ot)|0)+Math.imul(M,it)|0,i=i+Math.imul(M,ot)|0,n=n+Math.imul(b,st)|0,a=(a=a+Math.imul(b,ut)|0)+Math.imul(_,st)|0,i=i+Math.imul(_,ut)|0,n=n+Math.imul(m,ft)|0,a=(a=a+Math.imul(m,ht)|0)+Math.imul(y,ft)|0,i=i+Math.imul(y,ht)|0;var kt=(u+(n=n+Math.imul(p,pt)|0)|0)+((8191&(a=(a=a+Math.imul(p,gt)|0)+Math.imul(g,pt)|0))<<13)|0;u=((i=i+Math.imul(g,gt)|0)+(a>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(z,Y),a=(a=Math.imul(z,W))+Math.imul(N,Y)|0,i=Math.imul(N,W),n=n+Math.imul(I,J)|0,a=(a=a+Math.imul(I,Q)|0)+Math.imul(B,J)|0,i=i+Math.imul(B,Q)|0,n=n+Math.imul(D,K)|0,a=(a=a+Math.imul(D,tt)|0)+Math.imul(R,K)|0,i=i+Math.imul(R,tt)|0,n=n+Math.imul(S,rt)|0,a=(a=a+Math.imul(S,nt)|0)+Math.imul(L,rt)|0,i=i+Math.imul(L,nt)|0,n=n+Math.imul(k,it)|0,a=(a=a+Math.imul(k,ot)|0)+Math.imul(E,it)|0,i=i+Math.imul(E,ot)|0,n=n+Math.imul(A,st)|0,a=(a=a+Math.imul(A,ut)|0)+Math.imul(M,st)|0,i=i+Math.imul(M,ut)|0,n=n+Math.imul(b,ft)|0,a=(a=a+Math.imul(b,ht)|0)+Math.imul(_,ft)|0,i=i+Math.imul(_,ht)|0;var Et=(u+(n=n+Math.imul(m,pt)|0)|0)+((8191&(a=(a=a+Math.imul(m,gt)|0)+Math.imul(y,pt)|0))<<13)|0;u=((i=i+Math.imul(y,gt)|0)+(a>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(z,J),a=(a=Math.imul(z,Q))+Math.imul(N,J)|0,i=Math.imul(N,Q),n=n+Math.imul(I,K)|0,a=(a=a+Math.imul(I,tt)|0)+Math.imul(B,K)|0,i=i+Math.imul(B,tt)|0,n=n+Math.imul(D,rt)|0,a=(a=a+Math.imul(D,nt)|0)+Math.imul(R,rt)|0,i=i+Math.imul(R,nt)|0,n=n+Math.imul(S,it)|0,a=(a=a+Math.imul(S,ot)|0)+Math.imul(L,it)|0,i=i+Math.imul(L,ot)|0,n=n+Math.imul(k,st)|0,a=(a=a+Math.imul(k,ut)|0)+Math.imul(E,st)|0,i=i+Math.imul(E,ut)|0,n=n+Math.imul(A,ft)|0,a=(a=a+Math.imul(A,ht)|0)+Math.imul(M,ft)|0,i=i+Math.imul(M,ht)|0;var Ct=(u+(n=n+Math.imul(b,pt)|0)|0)+((8191&(a=(a=a+Math.imul(b,gt)|0)+Math.imul(_,pt)|0))<<13)|0;u=((i=i+Math.imul(_,gt)|0)+(a>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(z,K),a=(a=Math.imul(z,tt))+Math.imul(N,K)|0,i=Math.imul(N,tt),n=n+Math.imul(I,rt)|0,a=(a=a+Math.imul(I,nt)|0)+Math.imul(B,rt)|0,i=i+Math.imul(B,nt)|0,n=n+Math.imul(D,it)|0,a=(a=a+Math.imul(D,ot)|0)+Math.imul(R,it)|0,i=i+Math.imul(R,ot)|0,n=n+Math.imul(S,st)|0,a=(a=a+Math.imul(S,ut)|0)+Math.imul(L,st)|0,i=i+Math.imul(L,ut)|0,n=n+Math.imul(k,ft)|0,a=(a=a+Math.imul(k,ht)|0)+Math.imul(E,ft)|0,i=i+Math.imul(E,ht)|0;var St=(u+(n=n+Math.imul(A,pt)|0)|0)+((8191&(a=(a=a+Math.imul(A,gt)|0)+Math.imul(M,pt)|0))<<13)|0;u=((i=i+Math.imul(M,gt)|0)+(a>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(z,rt),a=(a=Math.imul(z,nt))+Math.imul(N,rt)|0,i=Math.imul(N,nt),n=n+Math.imul(I,it)|0,a=(a=a+Math.imul(I,ot)|0)+Math.imul(B,it)|0,i=i+Math.imul(B,ot)|0,n=n+Math.imul(D,st)|0,a=(a=a+Math.imul(D,ut)|0)+Math.imul(R,st)|0,i=i+Math.imul(R,ut)|0,n=n+Math.imul(S,ft)|0,a=(a=a+Math.imul(S,ht)|0)+Math.imul(L,ft)|0,i=i+Math.imul(L,ht)|0;var Lt=(u+(n=n+Math.imul(k,pt)|0)|0)+((8191&(a=(a=a+Math.imul(k,gt)|0)+Math.imul(E,pt)|0))<<13)|0;u=((i=i+Math.imul(E,gt)|0)+(a>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(z,it),a=(a=Math.imul(z,ot))+Math.imul(N,it)|0,i=Math.imul(N,ot),n=n+Math.imul(I,st)|0,a=(a=a+Math.imul(I,ut)|0)+Math.imul(B,st)|0,i=i+Math.imul(B,ut)|0,n=n+Math.imul(D,ft)|0,a=(a=a+Math.imul(D,ht)|0)+Math.imul(R,ft)|0,i=i+Math.imul(R,ht)|0;var Ot=(u+(n=n+Math.imul(S,pt)|0)|0)+((8191&(a=(a=a+Math.imul(S,gt)|0)+Math.imul(L,pt)|0))<<13)|0;u=((i=i+Math.imul(L,gt)|0)+(a>>>13)|0)+(Ot>>>26)|0,Ot&=67108863,n=Math.imul(z,st),a=(a=Math.imul(z,ut))+Math.imul(N,st)|0,i=Math.imul(N,ut),n=n+Math.imul(I,ft)|0,a=(a=a+Math.imul(I,ht)|0)+Math.imul(B,ft)|0,i=i+Math.imul(B,ht)|0;var Dt=(u+(n=n+Math.imul(D,pt)|0)|0)+((8191&(a=(a=a+Math.imul(D,gt)|0)+Math.imul(R,pt)|0))<<13)|0;u=((i=i+Math.imul(R,gt)|0)+(a>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,n=Math.imul(z,ft),a=(a=Math.imul(z,ht))+Math.imul(N,ft)|0,i=Math.imul(N,ht);var Rt=(u+(n=n+Math.imul(I,pt)|0)|0)+((8191&(a=(a=a+Math.imul(I,gt)|0)+Math.imul(B,pt)|0))<<13)|0;u=((i=i+Math.imul(B,gt)|0)+(a>>>13)|0)+(Rt>>>26)|0,Rt&=67108863;var Pt=(u+(n=Math.imul(z,pt))|0)+((8191&(a=(a=Math.imul(z,gt))+Math.imul(N,pt)|0))<<13)|0;return u=((i=Math.imul(N,gt))+(a>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,s[0]=vt,s[1]=mt,s[2]=yt,s[3]=xt,s[4]=bt,s[5]=_t,s[6]=wt,s[7]=At,s[8]=Mt,s[9]=Tt,s[10]=kt,s[11]=Et,s[12]=Ct,s[13]=St,s[14]=Lt,s[15]=Ot,s[16]=Dt,s[17]=Rt,s[18]=Pt,0!==u&&(s[19]=u,r.length++),r};function d(t,e,r){return(new p).mulp(t,e,r)}function p(t,e){this.x=t,this.y=e}Math.imul||(h=f),a.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?h(this,t,e):r<63?f(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,a=0,i=0;i>>26)|0)>>>26,o&=67108863}r.words[i]=l,n=o,o=a}return 0!==n?r.words[i]=n:r.length--,r.strip()}(this,t,e):d(this,t,e)},p.prototype.makeRBT=function(t){for(var e=new Array(t),r=a.prototype._countBits(t)-1,n=0;n>=1;return n},p.prototype.permute=function(t,e,r,n,a,i){for(var o=0;o>>=1)a++;return 1<>>=13,n[2*o+1]=8191&i,i>>>=13;for(o=2*e;o>=26,e+=a/67108864|0,e+=i>>>26,this.words[n]=67108863&i}return 0!==e&&(this.words[n]=e,this.length++),this},a.prototype.muln=function(t){return this.clone().imuln(t)},a.prototype.sqr=function(){return this.mul(this)},a.prototype.isqr=function(){return this.imul(this.clone())},a.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>a}return e}(t);if(0===e.length)return new a(1);for(var r=this,n=0;n=0);var e,n=t%26,a=(t-n)/26,i=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(e=0;e>>26-n}o&&(this.words[e]=o,this.length++)}if(0!==a){for(e=this.length-1;e>=0;e--)this.words[e+a]=this.words[e];for(e=0;e=0),a=e?(e-e%26)/26:0;var i=t%26,o=Math.min((t-i)/26,this.length),l=67108863^67108863>>>i<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=a);u--){var f=0|this.words[u];this.words[u]=c<<26-i|f>>>i,c=f&l}return s&&0!==c&&(s.words[s.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},a.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},a.prototype.shln=function(t){return this.clone().ishln(t)},a.prototype.ushln=function(t){return this.clone().iushln(t)},a.prototype.shrn=function(t){return this.clone().ishrn(t)},a.prototype.ushrn=function(t){return this.clone().iushrn(t)},a.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,a=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var a=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},a.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(s/67108864|0),this.words[a+n]=67108863&i}for(;a>26,this.words[a+n]=67108863&i;if(0===l)return this.strip();for(r(-1===l),l=0,a=0;a>26,this.words[a]=67108863&i;return this.negative=1,this.strip()},a.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),i=t,o=0|i.words[i.length-1];0!==(r=26-this._countBits(o))&&(i=i.ushln(r),n.iushln(r),o=0|i.words[i.length-1]);var l,s=n.length-i.length;if("mod"!==e){(l=new a(null)).length=s+1,l.words=new Array(l.length);for(var u=0;u=0;f--){var h=67108864*(0|n.words[i.length+f])+(0|n.words[i.length+f-1]);for(h=Math.min(h/o|0,67108863),n._ishlnsubmul(i,h,f);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(i,1,f),n.isZero()||(n.negative^=1);l&&(l.words[f]=h)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:l||null,mod:n}},a.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new a(0),mod:new a(0)}:0!==this.negative&&0===t.negative?(l=this.neg().divmod(t,e),"mod"!==e&&(i=l.div.neg()),"div"!==e&&(o=l.mod.neg(),n&&0!==o.negative&&o.iadd(t)),{div:i,mod:o}):0===this.negative&&0!==t.negative?(l=this.divmod(t.neg(),e),"mod"!==e&&(i=l.div.neg()),{div:i,mod:l.mod}):0!=(this.negative&t.negative)?(l=this.neg().divmod(t.neg(),e),"div"!==e&&(o=l.mod.neg(),n&&0!==o.negative&&o.isub(t)),{div:l.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new a(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new a(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new a(this.modn(t.words[0]))}:this._wordDiv(t,e);var i,o,l},a.prototype.div=function(t){return this.divmod(t,"div",!1).div},a.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},a.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},a.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),a=t.andln(1),i=r.cmp(n);return i<0||1===a&&0===i?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},a.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,a=this.length-1;a>=0;a--)n=(e*n+(0|this.words[a]))%t;return n},a.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var a=(0|this.words[n])+67108864*e;this.words[n]=a/t|0,e=a%t}return this.strip()},a.prototype.divn=function(t){return this.clone().idivn(t)},a.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i=new a(1),o=new a(0),l=new a(0),s=new a(1),u=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++u;for(var c=n.clone(),f=e.clone();!e.isZero();){for(var h=0,d=1;0==(e.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(e.iushrn(h);h-- >0;)(i.isOdd()||o.isOdd())&&(i.iadd(c),o.isub(f)),i.iushrn(1),o.iushrn(1);for(var p=0,g=1;0==(n.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(l.isOdd()||s.isOdd())&&(l.iadd(c),s.isub(f)),l.iushrn(1),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),i.isub(l),o.isub(s)):(n.isub(e),l.isub(i),s.isub(o))}return{a:l,b:s,gcd:n.iushln(u)}},a.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var i,o=new a(1),l=new a(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(s),o.iushrn(1);for(var f=0,h=1;0==(n.words[0]&h)&&f<26;++f,h<<=1);if(f>0)for(n.iushrn(f);f-- >0;)l.isOdd()&&l.iadd(s),l.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(l)):(n.isub(e),l.isub(o))}return(i=0===e.cmpn(1)?o:l).cmpn(0)<0&&i.iadd(t),i},a.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var a=e.cmp(r);if(a<0){var i=e;e=r,r=i}else if(0===a||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},a.prototype.invm=function(t){return this.egcd(t).a.umod(t)},a.prototype.isEven=function(){return 0==(1&this.words[0])},a.prototype.isOdd=function(){return 1==(1&this.words[0])},a.prototype.andln=function(t){return this.words[0]&t},a.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,a=1<>>26,l&=67108863,this.words[o]=l}return 0!==i&&(this.words[o]=i,this.length++),this},a.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},a.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var a=0|this.words[0];e=a===t?0:at.length)return 1;if(this.length=0;r--){var n=0|this.words[r],a=0|t.words[r];if(n!==a){na&&(e=1);break}}return e},a.prototype.gtn=function(t){return 1===this.cmpn(t)},a.prototype.gt=function(t){return 1===this.cmp(t)},a.prototype.gten=function(t){return this.cmpn(t)>=0},a.prototype.gte=function(t){return this.cmp(t)>=0},a.prototype.ltn=function(t){return-1===this.cmpn(t)},a.prototype.lt=function(t){return-1===this.cmp(t)},a.prototype.lten=function(t){return this.cmpn(t)<=0},a.prototype.lte=function(t){return this.cmp(t)<=0},a.prototype.eqn=function(t){return 0===this.cmpn(t)},a.prototype.eq=function(t){return 0===this.cmp(t)},a.red=function(t){return new _(t)},a.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},a.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},a.prototype._forceRed=function(t){return this.red=t,this},a.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},a.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},a.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},a.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},a.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},a.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},a.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},a.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},a.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},a.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},a.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},a.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},a.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},a.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new a(e,16),this.n=this.p.bitLength(),this.k=new a(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function x(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function b(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=a._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function w(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new a(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)}v.prototype._tmp=function(){var t=new a(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,a=i}a>>>=22,t.words[n-10]=a,0===a&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=a,e=n}return 0!==e&&(t.words[t.length++]=e),t},a._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new y;else if("p192"===t)e=new x;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new b}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new a(1)).iushrn(2);return this.pow(t,n)}for(var i=this.m.subn(1),o=0;!i.isZero()&&0===i.andln(1);)o++,i.iushrn(1);r(!i.isZero());var l=new a(1).toRed(this),s=l.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new a(2*c*c).toRed(this);0!==this.pow(c,u).cmp(s);)c.redIAdd(s);for(var f=this.pow(c,i),h=this.pow(t,i.addn(1).iushrn(1)),d=this.pow(t,i),p=o;0!==d.cmp(l);){for(var g=d,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(v=0;n--){for(var u=e.words[n],c=s-1;c>=0;c--){var f=u>>c&1;i!==r[0]&&(i=this.sqr(i)),0!==f||0!==o?(o<<=1,o|=f,(4===++l||0===n&&0===c)&&(i=this.mul(i,r[o]),l=0,o=0)):l=0}s=26}return i},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},a.mont=function(t){return new w(t)},n(w,_),w.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},w.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},w.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).iushrn(this.shift),i=a;return a.cmp(this.m)>=0?i=a.isub(this.m):a.cmpn(0)<0&&(i=a.iadd(this.m)),i._forceRed(this)},w.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new a(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},w.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(Ff,this),Ff=Ff.exports;var zf=function(t){return t.cmp(new Ff(0))};var Nf={};(function(t){var e=!1;if("undefined"!=typeof Float64Array){var r=new Float64Array(1),n=new Uint32Array(r.buffer);if(r[0]=1,e=!0,1072693248===n[1]){(Nf=function(t){return r[0]=t,[n[0],n[1]]}).pack=function(t,e){return n[0]=t,n[1]=e,r[0]},Nf.lo=function(t){return r[0]=t,n[0]},Nf.hi=function(t){return r[0]=t,n[1]}}else if(1072693248===n[0]){(Nf=function(t){return r[0]=t,[n[1],n[0]]}).pack=function(t,e){return n[1]=t,n[0]=e,r[0]},Nf.lo=function(t){return r[0]=t,n[1]},Nf.hi=function(t){return r[0]=t,n[0]}}else e=!1}if(!e){var a=new t(8);(Nf=function(t){return a.writeDoubleLE(t,0,!0),[a.readUInt32LE(0,!0),a.readUInt32LE(4,!0)]}).pack=function(t,e){return a.writeUInt32LE(t,0,!0),a.writeUInt32LE(e,4,!0),a.readDoubleLE(0,!0)},Nf.lo=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(0,!0)},Nf.hi=function(t){return a.writeDoubleLE(t,0,!0),a.readUInt32LE(4,!0)}}Nf.sign=function(t){return Nf.hi(t)>>>31},Nf.exponent=function(t){return(Nf.hi(t)<<1>>>21)-1023},Nf.fraction=function(t){var e=Nf.lo(t),r=Nf.hi(t),n=1048575&r;return 2146435072&r&&(n+=1<<20),[e,n]},Nf.denormalized=function(t){return!(2146435072&Nf.hi(t))}}).call(this,Yl.Buffer);var jf=function(t){var e=Nf.exponent(t);return e<52?new Ff(t):new Ff(t*Math.pow(2,52-e)).ushln(e-52)};var Uf=function(t,e){var r=zf(t),n=zf(e);if(0===r)return[jf(0),jf(1)];if(0===n)return[jf(0),jf(0)];n<0&&(t=t.neg(),e=e.neg());var a=t.gcd(e);if(a.cmpn(1))return[t.div(a),e.div(a)];return[t,e]};var Vf=function(t,e){return Uf(t[0].mul(e[1]),t[1].mul(e[0]))};var Hf=function(t){return t&&"object"==typeof t&&Boolean(t.words)};var qf=function(t){return Array.isArray(t)&&2===t.length&&Hf(t[0])&&Hf(t[1])};var Gf=function(t){return new Ff(t)};var Xf=function t(e,r){if(qf(e))return r?Vf(e,t(r)):[e[0].clone(),e[1].clone()];var n=0;var a,i;if(Hf(e))a=e.clone();else if("string"==typeof e)a=Gf(e);else{if(0===e)return[jf(0),jf(1)];if(e===Math.floor(e))a=jf(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),n-=256;a=jf(e)}}if(qf(r))a.mul(r[1]),i=r[0].clone();else if(Hf(r))i=r.clone();else if("string"==typeof r)i=Gf(r);else if(r)if(r===Math.floor(r))i=jf(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),n+=256;i=jf(r)}else i=jf(1);n>0?a=a.ushln(n):n<0&&(i=i.ushln(-n));return Uf(a,i)};var Yf=function(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var a=0;a20)return 52;return r+32};var Jf=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.abs().divmod(r.abs()),a=n.div,i=Yf(a),o=n.mod,l=e.negative!==r.negative?-1:1;if(0===o.cmpn(0))return l*i;if(i){var s=Zf(i)+4,u=Yf(o.ushln(s).divRound(r));return l*(i+u*Math.pow(2,-s))}var c=r.bitLength()-o.bitLength()+53,u=Yf(o.ushln(c).divRound(r));return c<1023?l*u*Math.pow(2,-c):(u*=Math.pow(2,-1023),l*u*Math.pow(2,1023-c))};var Qf={},$f="d",Kf="ax",th="vv",eh="fp",rh="es",nh="rs",ah="re",ih="rb",oh="ri",lh="rp",sh="bs",uh="be",ch="bb",fh="bi",hh="bp",dh="rv",ph="Q",gh=[$f,Kf,th,nh,ah,ih,oh,sh,uh,ch,fh];function vh(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],n=gh.slice();t||n.splice(3,0,eh);var a=["function "+e+"("+n.join()+"){"];function i(e,n){var i=function(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),a=["function ",n,"(",gh.join(),"){","var ",rh,"=2*",$f,";"],i="for(var i="+nh+","+lh+"="+rh+"*"+nh+";i<"+ah+";++i,"+lh+"+="+rh+"){var x0="+ih+"["+Kf+"+"+lh+"],x1="+ih+"["+Kf+"+"+lh+"+"+$f+"],xi="+oh+"[i];",o="for(var j="+sh+","+hh+"="+rh+"*"+sh+";j<"+uh+";++j,"+hh+"+="+rh+"){var y0="+ch+"["+Kf+"+"+hh+"],"+(r?"y1="+ch+"["+Kf+"+"+hh+"+"+$f+"],":"")+"yi="+fh+"[j];";return t?a.push(i,ph,":",o):a.push(o,ph,":",i),r?a.push("if(y1"+uh+"-"+sh+"){"),t?(i(!0,!1),a.push("}else{"),i(!1,!1)):(a.push("if("+eh+"){"),i(!0,!0),a.push("}else{"),i(!0,!1),a.push("}}else{if("+eh+"){"),i(!1,!0),a.push("}else{"),i(!1,!1),a.push("}")),a.push("}}return "+e);var o=r.join("")+a.join("");return new Function(o)()}Qf.partial=vh(!1),Qf.full=vh(!0);var mh=function(t,e){var r="abcdef".split("").concat(e),n=[];t.indexOf("lo")>=0&&n.push("lo=e[k+n]");t.indexOf("hi")>=0&&n.push("hi=e[k+o]");return r.push(yh.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)},yh="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m";var xh=function(t,e,r,n,a,i){if(n<=r+1)return r;var o=r,l=n,s=n+r>>>1,u=2*t,c=s,f=a[u*s+e];for(;o=v?(c=g,f=v):p>=y?(c=d,f=p):(c=m,f=y):v>=y?(c=g,f=v):y>=p?(c=d,f=p):(c=m,f=y);for(var x=u*(l-1),b=u*c,_=0;_r&&a[f+e]>u;--c,f-=o){for(var h=f,d=f+o,p=0;p>1,s=l-a,u=l+a,c=i,f=s,h=l,d=u,p=o,g=e+1,v=r-1,m=0;Lh(c,f,n)&&(m=c,c=f,f=m);Lh(d,p,n)&&(m=d,d=p,p=m);Lh(c,h,n)&&(m=c,c=h,h=m);Lh(f,h,n)&&(m=f,f=h,h=m);Lh(c,d,n)&&(m=c,c=d,d=m);Lh(h,d,n)&&(m=h,h=d,d=m);Lh(f,p,n)&&(m=f,f=p,p=m);Lh(f,h,n)&&(m=f,f=h,h=m);Lh(d,p,n)&&(m=d,d=p,p=m);var y=n[2*f];var x=n[2*f+1];var b=n[2*d];var _=n[2*d+1];var w=2*c;var A=2*h;var M=2*p;var T=2*i;var k=2*l;var E=2*o;for(var C=0;C<2;++C){var S=n[w+C],L=n[A+C],O=n[M+C];n[T+C]=S,n[k+C]=L,n[E+C]=O}Eh(s,e,n);Eh(u,r,n);for(var D=g;D<=v;++D)if(Oh(D,y,x,n))D!==g&&kh(D,g,n),++g;else if(!Oh(D,b,_,n))for(;;){if(Oh(v,b,_,n)){Oh(v,y,x,n)?(Ch(D,g,v,n),++g,--v):(kh(D,v,n),--v);break}if(--vt;){var u=r[s-2],c=r[s-1];if(ur[e+1])}function Oh(t,e,r,n){var a=n[t*=2];return a>>1;Ah(jh,y);for(var x=0,b=0,p=0;p=Rh)Uh(Bh,Fh,b--,_=_-Rh|0);else if(_>=0)Uh(Ph,Ih,x--,_);else if(_<=-Rh){_=-_-Rh|0;for(var w=0;w>>1;Ah(jh,y);for(var x=0,b=0,_=0,p=0;p>1==jh[2*p+3]>>1&&(A=2,p+=1),w<0){for(var M=-(w>>1)-1,T=0;T<_;++T){var k=e(zh[T],M);if(void 0!==k)return k}if(0!==A)for(var T=0;T>1)-1;0===A?Uh(Ph,Ih,x--,M):1===A?Uh(Bh,Fh,b--,M):2===A&&Uh(zh,Nh,_--,M)}}},scanBipartite:function(t,e,r,n,a,i,o,l,s,u,c,f){var h=0,d=2*t,p=e,g=e+t,v=1,m=1;n?m=Rh:v=Rh;for(var y=a;y>>1;Ah(jh,w);for(var A=0,y=0;y=Rh?(T=!n,x-=Rh):(T=!!n,x-=1),T)Vh(Ph,Ih,A++,x);else{var k=f[x],E=d*x,C=c[E+e+1],S=c[E+e+1+t];t:for(var L=0;L>>1;Ah(jh,x);for(var b=0,g=0;g=Rh)Ph[b++]=v-Rh;else{var w=c[v-=1],A=h*v,M=u[A+e+1],T=u[A+e+1+t];t:for(var k=0;k=0;--k)if(Ph[k]===v){for(var L=k+1;L0;){var h=(c-=1)*ed,d=nd[h],p=nd[h+1],g=nd[h+2],v=nd[h+3],m=nd[h+4],y=nd[h+5],x=c*rd,b=ad[x],_=ad[x+1],w=1&y,A=!!(16&y),M=a,T=i,k=l,E=s;if(w&&(M=l,T=s,k=a,E=i),!(2&y&&(g=Qh(t,d,p,g,M,T,_),p>=g)||4&y&&(p=$h(t,d,p,g,M,T,b))>=g)){var C=g-p,S=m-v;if(A){if(t*C*(C+S)=p0)&&!(p1>=hi)",["p0","p1"]),Jh=mh("lo===p0",["p0"]),Qh=mh("lo>>1;if(!(o<=0)){var l,s=Ds.mallocDouble(2*o*a),u=Ds.mallocInt32(a);if((a=fd(t,o,s,u))>0){if(1===o&&n)Dh.init(a),l=Dh.sweepComplete(o,r,0,a,s,u,0,a,s,u);else{var c=Ds.mallocDouble(2*o*i),f=Ds.mallocInt32(i);(i=fd(e,o,c,f))>0&&(Dh.init(a+i),l=1===o?Dh.sweepBipartite(o,r,0,a,s,u,0,i,c,f):Hh(o,r,n,a,s,u,i,c,f),Ds.free(c),Ds.free(f))}Ds.free(s),Ds.free(u)}return l}}}function dd(t,e){sd.push([t,e])}var pd=function(t,e){return Uf(t[0].mul(e[0]),t[1].mul(e[1]))};var gd=function(t){return zf(t[0])*zf(t[1])};var vd=function(t,e){return Uf(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))};var md=function(t,e){return Uf(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))};var yd=function(t,e){for(var r=t.length,n=new Array(r),a=0;a>>0,Td=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-Ad:Ad;var r=Nf.hi(t),n=Nf.lo(t);e>t==t>0?n===Md?(r+=1,n=0):n+=1:0===n?(n=Md,r-=1):n-=1;return Nf.pack(n,r)};var kd=function(t){for(var e=new Array(t.length),r=0;r0&&i>0||a<0&&i<0)return!1;var o=Cd(r,t,e),l=Cd(n,t,e);if(o>0&&l>0||o<0&&l<0)return!1;if(0===a&&0===i&&0===o&&0===l)return function(t,e,r,n){for(var a=0;a<2;++a){var i=t[a],o=e[a],l=Math.min(i,o),s=Math.max(i,o),u=r[a],c=n[a],f=Math.min(u,c),h=Math.max(u,c);if(he[2]?1:0)}function zd(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--i){var p=e[o=(w=n[i])[0]],g=p[0],v=p[1],m=t[g],y=t[v];if((m[0]-y[0]||m[1]-y[1])<0){var x=g;g=v,v=x}p[0]=g;var b,_=p[1]=w[1];for(a&&(b=p[2]);i>0&&n[i-1][0]===o;){var w,A=(w=n[--i])[1];a?e.push([_,A,b]):e.push([_,A]),_=A}a?e.push([_,v,b]):e.push([_,v])}return l}(t,e,a,o,r));return zd(e,l,r),!!l||(a.length>0||o.length>0)}var jd=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;n0?1:0},Hd=function(t,e,r,n){var a=af(e,r,n);if(0===a){var i=Vd(af(t,e,r)),o=Vd(af(t,e,n));if(i===o){if(0===i){var l=qd(t,e,r),s=qd(t,e,n);return l===s?0:l?1:-1}return 0}return 0===o?i>0?-1:qd(t,e,n)?-1:1:0===i?o>0?1:qd(t,e,r)?1:-1:Vd(o-i)}var u=af(t,e,r);if(u>0)return a>0&&af(t,e,n)>0?1:-1;if(u<0)return a>0||af(t,e,n)>0?1:-1;var c=af(t,e,n);return c>0?1:qd(t,e,r)?1:-1};function qd(t,e,r){var n=zc(t[0],-e[0]),a=zc(t[1],-e[1]),i=zc(r[0],-e[0]),o=zc(r[1],-e[1]),l=Uc(Ud(n,i),Ud(a,o));return l[l.length-1]>=0}var Gd=function(t,e){for(var r=0|e.length,n=t.length,a=[new Array(r),new Array(r)],i=0;i0){i=a[u][r][0],l=u;break}o=i[1^l];for(var c=0;c<2;++c)for(var f=a[c][r],h=0;h0&&(i=d,o=p,l=c)}return n?o:(i&&s(i,l),o)}function c(t,r){var n=a[r][t][0],i=[t];s(n,r);for(var o=n[1^r];;){for(;o!==t;)i.push(o),o=u(i[i.length-2],o,!1);if(a[0][t].length+a[1][t].length===0)break;var l=i[i.length-1],c=t,f=i[1],h=u(l,c,!0);if(Hd(e[l],e[c],e[f],e[h])<0)break;i.push(t),o=u(l,c)}return i}function f(t,e){return e[1]===e[e.length-1]}for(var i=0;i0;){a[0][i].length;var p=c(i,h);f(d,p)?d.push.apply(d,p):(d.length>0&&l.push(d),d=p)}d.length>0&&l.push(d)}return l};var Xd=function(t,e){for(var r=jd(t,e.length),n=new Array(e.length),a=new Array(e.length),i=[],o=0;o0;){var s=i.pop();n[s]=!1;for(var u=r[s],o=0;o>>1,x=a",a?".get(m)":"[m]"];return i?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),i?o.push("return -1};"):o.push("return i};"),o.join("")}function Wd(t,e,r,n){return new Function([Yd("A","x"+t+"y",e,["y"],!1,n),Yd("B","x"+t+"y",e,["y"],!0,n),Yd("P","c(x,y)"+t+"0",e,["y","c"],!1,n),Yd("Q","c(x,y)"+t+"0",e,["y","c"],!0,n),"function dispatchBsearch",r,"(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",r].join(""))()}var Zd={ge:Wd(">=",!1,"GE"),gt:Wd(">",!1,"GT"),lt:Wd("<",!0,"LT"),le:Wd("<=",!0,"LE"),eq:Wd("-",!0,"EQ",!0)},Jd=0,Qd=1,$d=function(t){if(!t||0===t.length)return new hp(null);return new hp(fp(t))};function Kd(t,e,r,n,a){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=a,this.count=(e?e.count:0)+(r?r.count:0)+n.length}var tp=Kd.prototype;function ep(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function rp(t,e){var r=fp(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function np(t,e){var r=t.intervals([]);r.push(e),rp(t,r)}function ap(t,e){var r=t.intervals([]),n=r.indexOf(e);return n<0?Jd:(r.splice(n,1),rp(t,r),Qd)}function ip(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var a=r(t[n]);if(a)return a}}function lp(t,e){for(var r=0;r>1],a=[],i=[],o=[];for(r=0;r3*(e+1)?np(this,t):this.left.insert(t):this.left=fp([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?np(this,t):this.right.insert(t):this.right=fp([t]);else{var r=Zd.ge(this.leftPoints,t,up),n=Zd.ge(this.rightPoints,t,cp);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},tp.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?ap(this,t):2===(i=this.left.remove(t))?(this.left=null,this.count-=1,Qd):(i===Qd&&(this.count-=1),i):Jd}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:Jd;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,n=this.left;n.right;)r=n,n=n.right;if(r===this)n.right=this.right;else{var a=this.left;i=this.right;r.count-=n.count,r.right=n.left,n.left=a,n.right=i}ep(this,n),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?ep(this,this.left):ep(this,this.right);return Qd}for(a=Zd.ge(this.leftPoints,t,up);a3*(e-1)?ap(this,t):2===(i=this.right.remove(t))?(this.right=null,this.count-=1,Qd):(i===Qd&&(this.count-=1),i):Jd;var i}},tp.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return op(this.rightPoints,t,e)}return lp(this.leftPoints,e)},tp.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?op(this.rightPoints,t,r):lp(this.leftPoints,r)};var dp=hp.prototype;dp.insert=function(t){this.root?this.root.insert(t):this.root=new Kd(t[0],null,null,[t],[t])},dp.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==Jd}return!1},dp.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},dp.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(dp,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(dp,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}});var pp=function(t){return new _p(t||kp,null)},gp=0,vp=1;function mp(t,e,r,n,a,i){this._color=t,this.key=e,this.value=r,this.left=n,this.right=a,this._count=i}function yp(t){return new mp(t._color,t.key,t.value,t.left,t.right,t._count)}function xp(t,e){return new mp(t,e.key,e.value,e.left,e.right,e._count)}function bp(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function _p(t,e){this._compare=t,this.root=e}var wp=_p.prototype;function Ap(t,e){this.tree=t,this._stack=e}Object.defineProperty(wp,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(wp,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(wp,"length",{get:function(){return this.root?this.root._count:0}}),wp.insert=function(t,e){for(var r=this._compare,n=this.root,a=[],i=[];n;){var o=r(t,n.key);a.push(n),i.push(o),n=o<=0?n.left:n.right}a.push(new mp(gp,t,e,null,null,1));for(var l=a.length-2;l>=0;--l){n=a[l];i[l]<=0?a[l]=new mp(n._color,n.key,n.value,a[l+1],n.right,n._count+1):a[l]=new mp(n._color,n.key,n.value,n.left,a[l+1],n._count+1)}for(l=a.length-1;l>1;--l){var s=a[l-1];n=a[l];if(s._color===vp||n._color===vp)break;var u=a[l-2];if(u.left===s)if(s.left===n){if(!(c=u.right)||c._color!==gp){if(u._color=gp,u.left=s.right,s._color=vp,s.right=u,a[l-2]=s,a[l-1]=n,bp(u),bp(s),l>=3)(f=a[l-3]).left===u?f.left=s:f.right=s;break}s._color=vp,u.right=xp(vp,c),u._color=gp,l-=1}else{if(!(c=u.right)||c._color!==gp){if(s.right=n.left,u._color=gp,u.left=n.right,n._color=vp,n.left=s,n.right=u,a[l-2]=n,a[l-1]=s,bp(u),bp(s),bp(n),l>=3)(f=a[l-3]).left===u?f.left=n:f.right=n;break}s._color=vp,u.right=xp(vp,c),u._color=gp,l-=1}else if(s.right===n){if(!(c=u.left)||c._color!==gp){if(u._color=gp,u.right=s.left,s._color=vp,s.left=u,a[l-2]=s,a[l-1]=n,bp(u),bp(s),l>=3)(f=a[l-3]).right===u?f.right=s:f.left=s;break}s._color=vp,u.left=xp(vp,c),u._color=gp,l-=1}else{var c;if(!(c=u.left)||c._color!==gp){var f;if(s.left=n.right,u._color=gp,u.right=n.left,n._color=vp,n.right=s,n.left=u,a[l-2]=n,a[l-1]=s,bp(u),bp(s),bp(n),l>=3)(f=a[l-3]).right===u?f.right=n:f.left=n;break}s._color=vp,u.left=xp(vp,c),u._color=gp,l-=1}}return a[0]._color=vp,new _p(r,a[0])},wp.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,a){if(r(e,a.key)<=0){var i;if(a.left&&(i=t(e,r,n,a.left)))return i;if(i=n(a.key,a.value))return i}if(a.right)return t(e,r,n,a.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,a,i){var o,l=n(e,i.key),s=n(r,i.key);if(l<=0){if(i.left&&(o=t(e,r,n,a,i.left)))return o;if(s>0&&(o=a(i.key,i.value)))return o}if(s>0&&i.right)return t(e,r,n,a,i.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(wp,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new Ap(this,t)}}),Object.defineProperty(wp,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new Ap(this,t)}}),wp.at=function(t){if(t<0)return new Ap(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new Ap(this,[])},wp.ge=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i<=0&&(a=n.length),r=i<=0?r.left:r.right}return n.length=a,new Ap(this,n)},wp.gt=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i<0&&(a=n.length),r=i<0?r.left:r.right}return n.length=a,new Ap(this,n)},wp.lt=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i>0&&(a=n.length),r=i<=0?r.left:r.right}return n.length=a,new Ap(this,n)},wp.le=function(t){for(var e=this._compare,r=this.root,n=[],a=0;r;){var i=e(t,r.key);n.push(r),i>=0&&(a=n.length),r=i<0?r.left:r.right}return n.length=a,new Ap(this,n)},wp.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var a=e(t,r.key);if(n.push(r),0===a)return new Ap(this,n);r=a<=0?r.left:r.right}return new Ap(this,[])},wp.remove=function(t){var e=this.find(t);return e?e.remove():this},wp.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var Mp=Ap.prototype;function Tp(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function kp(t,e){return te?1:0}Object.defineProperty(Mp,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(Mp,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),Mp.clone=function(){return new Ap(this.tree,this._stack.slice())},Mp.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new mp(r._color,r.key,r.value,r.left,r.right,r._count);for(var n=t.length-2;n>=0;--n){(r=t[n]).left===t[n+1]?e[n]=new mp(r._color,r.key,r.value,e[n+1],r.right,r._count):e[n]=new mp(r._color,r.key,r.value,r.left,e[n+1],r._count)}if((r=e[e.length-1]).left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var i=e[a-1];e.push(new mp(r._color,i.key,i.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(n=e.length-2;n>=a;--n)r=e[n],e[n]=new mp(r._color,r.key,r.value,r.left,e[n+1],r._count);e[a-1].left=e[a]}if((r=e[e.length-1])._color===gp){var o=e[e.length-2];o.left===r?o.left=null:o.right===r&&(o.right=null),e.pop();for(n=0;n=0;--i){if(e=t[i],0===i)return void(e._color=vp);if((r=t[i-1]).left===e){if((n=r.right).right&&n.right._color===gp)return a=(n=r.right=yp(n)).right=yp(n.right),r.right=n.left,n.left=r,n.right=a,n._color=r._color,e._color=vp,r._color=vp,a._color=vp,bp(r),bp(n),i>1&&((o=t[i-2]).left===r?o.left=n:o.right=n),void(t[i-1]=n);if(n.left&&n.left._color===gp)return a=(n=r.right=yp(n)).left=yp(n.left),r.right=a.left,n.left=a.right,a.left=r,a.right=n,a._color=r._color,r._color=vp,n._color=vp,e._color=vp,bp(r),bp(n),bp(a),i>1&&((o=t[i-2]).left===r?o.left=a:o.right=a),void(t[i-1]=a);if(n._color===vp){if(r._color===gp)return r._color=vp,void(r.right=xp(gp,n));r.right=xp(gp,n);continue}n=yp(n),r.right=n.left,n.left=r,n._color=r._color,r._color=gp,bp(r),bp(n),i>1&&((o=t[i-2]).left===r?o.left=n:o.right=n),t[i-1]=n,t[i]=r,i+11&&((o=t[i-2]).right===r?o.right=n:o.left=n),void(t[i-1]=n);if(n.right&&n.right._color===gp)return a=(n=r.left=yp(n)).right=yp(n.right),r.left=a.right,n.right=a.left,a.right=r,a.left=n,a._color=r._color,r._color=vp,n._color=vp,e._color=vp,bp(r),bp(n),bp(a),i>1&&((o=t[i-2]).right===r?o.right=a:o.left=a),void(t[i-1]=a);if(n._color===vp){if(r._color===gp)return r._color=vp,void(r.left=xp(gp,n));r.left=xp(gp,n);continue}var o;n=yp(n),r.left=n.right,n.right=r,n._color=r._color,r._color=gp,bp(r),bp(n),i>1&&((o=t[i-2]).right===r?o.right=n:o.left=n),t[i-1]=n,t[i]=r,i+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(Mp,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(Mp,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),Mp.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(Mp,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),Mp.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new mp(n._color,n.key,t,n.left,n.right,n._count);for(var a=e.length-2;a>=0;--a)(n=e[a]).left===e[a+1]?r[a]=new mp(n._color,n.key,n.value,r[a+1],n.right,n._count):r[a]=new mp(n._color,n.key,n.value,n.left,r[a+1],n._count);return new _p(this.tree._compare,r[0])},Mp.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(Mp,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}});var Ep=function(t,e){var r,n,a,i;if(e[0][0]e[1][0]))return Cp(e,t);r=e[1],n=e[0]}if(t[0][0]t[1][0]))return-Cp(t,e);a=t[1],i=t[0]}var o=af(r,n,i),l=af(r,n,a);if(o<0){if(l<=0)return o}else if(o>0){if(l>=0)return o}else if(l)return l;if(o=af(i,a,n),l=af(i,a,r),o<0){if(l<=0)return o}else if(o>0){if(l>=0)return o}else if(l)return l;return n[0]-i[0]};function Cp(t,e){var r,n,a,i;if(e[0][0]e[1][0])){var o=Math.min(t[0][1],t[1][1]),l=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return lu?o-u:l-u}r=e[1],n=e[0]}t[0][1]0)if(e[0]!==i[1][0])r=t,t=t.right;else{if(l=Dp(t.right,e))return l;t=t.left}else{if(e[0]!==i[1][0])return t;var l;if(l=Dp(t.right,e))return l;t=t.left}}return r}function Rp(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function Pp(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}Lp.prototype.castUp=function(t){var e=Zd.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=Dp(this.slabs[e],t),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var a=null;if(r&&(a=r.key),e>0){var i=Dp(this.slabs[e-1],t);i&&(a?Ep(i.key,a)>0&&(a=i.key,n=i.value):(n=i.value,a=i.key))}var o=this.horizontal[e];if(o.length>0){var l=Zd.ge(o,t[1],Op);if(l=o.length)return n;s=o[l]}}if(s.start)if(a){var u=af(a[0],a[1],[t[0],s.y]);a[0][0]>a[1][0]&&(u=-u),u>0&&(n=s.index)}else n=s.index;else s.y!==t[1]&&(n=s.index)}}}return n};var Ip=function(t){for(var e=t.length,r=[],n=[],a=0;a0&&e[n]===r[0]))return 1;a=t[n-1]}for(var i=1;a;){var o=a.key,l=Bp(r,o[0],o[1]);if(o[0][0]0))return 0;i=-1,a=a.right}else if(l>0)a=a.left;else{if(!(l<0))return 0;i=1,a=a.right}}return i}}(h.slabs,h.coordinates);return 0===n.length?d:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(zp(n),d)},Bp=af[3];function Fp(){return!0}function zp(t){for(var e={},r=0;r0})).length,s=new Array(l),u=new Array(l),i=0;i0;){var O=S.pop(),D=_[O];sl(D,function(t,e){return t-e});var R,P=D.length,I=L[O];if(0===I){var g=o[O];R=[g]}for(var i=0;i=0)&&(L[B]=1^I,S.push(B),0===I)){var g=o[B];C(g)||(g.reverse(),R.push(g))}}0===I&&r.push(R)}return r};function Up(t,e){for(var r=new Array(t),n=0;n0)-(t<0)},Vp.abs=function(t){var e=t>>31;return(t^e)-e},Vp.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Vp.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Vp.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Vp.countTrailingZeros=Hp,Vp.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Vp.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Vp.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var qp=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,a=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--a;t[e]=n<>>8&255]<<16|qp[t>>>16&255]<<8|qp[t>>>24&255]},Vp.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Vp.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Vp.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Vp.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Vp.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Hp(t)+1};var Gp=Xp;function Xp(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e>1,o=Wp(t[i],e);o<=0?(0===o&&(a=i),r=i+1):o>0&&(n=i-1)}return a}function Kp(t,e){for(var r=new Array(t.length),n=0,a=r.length;n=t.length||0!==Wp(t[d],i)););}return r}function tg(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&s.push(a[u]);e.push(s)}return Jp(e)},Yp.skeleton=tg,Yp.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function m(t){for(var e=g(t);;){var r=e,n=2*t+1,a=2*(t+1),i=t;if(n0;){var r=v(t);if(r>=0){var n=g(r);if(e0){var t=w[0];return p(0,T-1),T-=1,m(0),t}return-1}function b(t,e){var r=w[t];return l[r]===e?t:(l[r]=-1/0,y(t),x(),l[r]=e,y((T+=1)-1))}function _(t){if(!s[t]){s[t]=!0;var e=i[t],r=o[t];i[r]>=0&&(i[r]=e),o[e]>=0&&(o[e]=r),A[e]>=0&&b(A[e],d(e)),A[r]>=0&&b(A[r],d(r))}}for(var w=[],A=new Array(n),u=0;u>1;u>=0;--u)m(u);for(;;){var k=x();if(k<0||l[k]>r)break;_(k)}for(var E=[],u=0;u=0&&r>=0&&e!==r){var n=A[e],a=A[r];n!==a&&S.push([n,a])}}),Yp.unique(Yp.normalize(S)),{positions:E,edges:S}};var rg=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;n<1&&e("Must have at least one array argument");var a=t.scalarArguments||0;a<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var i=t.getters||[],o=new Array(n),l=0;l=0?o[l]=!0:o[l]=!1;return function(t,e,r,n,a,i){var o=i.length,l=a.length;if(l<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var s="extractContour"+a.join("_"),u=[],c=[],f=[],h=0;h0&&v.push(lg(h,a[d-1])+"*"+og(a[d-1])),c.push(dg(h,a[d])+"=("+v.join("-")+")|0")}for(var h=0;h=0;--h)m.push(og(a[h]));c.push(_g+"=("+m.join("*")+")|0",xg+"=mallocUint32("+_g+")",yg+"=mallocUint32("+_g+")",wg+"=0"),c.push(pg(0)+"=0");for(var d=1;d<1<0;v=v-1&d)g.push(yg+"["+wg+"+"+vg(v)+"]");g.push(mg(0));for(var v=0;v=0;--e)w(e,0);for(var r=[],e=0;e0){",hg(a[e]),"=1;");t(e-1,r|1<0;--r)e+=Cg[r]/(t+r);var n=t+Eg+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}(Tg=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(Sg(e));e-=1;for(var r=kg[0],n=1;n<9;n++)r+=kg[n]/(e+n);var a=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(a,e+.5)*Math.exp(-a)*r}).log=Sg;var Lg=function(t){var e=t.length;if(e0;--a)n=o[a],r=i[a],i[a]=i[n],i[n]=r,o[a]=o[r],o[r]=n,l=(l+r)*a;return Ds.freeUint32(o),Ds.freeUint32(i),l},Rg.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,a,i,o=1;for((r=r||new Array(t))[0]=0,i=1;i0;--i)e=e-(n=e/o|0)*o|0,o=o/i|0,a=0|r[i],r[i]=0|r[n],r[n]=0|a;return r};var Pg=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(Tg(t+1)),r=[],n=0;n= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"}),Bg=function(t,e){var r=[];return e=+e||0,Ig(t.hi(t.shape[0]-1),r,e),r};var Fg=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=Bg(t,e),n=r.length,a=new Array(n),i=new Array(n),o=0;o c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var i=[],o=[],l=0;l>>7){");for(var l=0;l<1<<(1<128&&l%128==0){u.length>0&&c.push("}}");var f="vExtra"+u.length;n.push("case ",l>>>7,":",f,"(m&0x7f,",o.join(),");break;"),c=["function ",f,"(m,",o.join(),"){switch(m){"],u.push(c)}c.push("case ",127&l,":");for(var h=new Array(r),d=new Array(r),p=new Array(r),g=new Array(r),v=0,m=0;mm)&&!(l&1<0&&(A="+"+p[y]+"*c");var M=h[y].length/v*.5,T=.5+g[y]/v*.5;w.push("d"+y+"-"+T+"-"+M+"*("+h[y].join("+")+A+")/("+d[y].join("+")+")")}c.push("a.push([",w.join(),"]);","break;")}n.push("}},"),u.length>0&&c.push("}}");for(var k=[],l=0;l<1<8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var i=3*n;t.height0&&(c+=.02);for(var h=new Float32Array(u),d=0,p=-.5*c,f=0;fl[A]&&(i.uniforms.dataAxis=t,i.uniforms.screenOffset=e,i.uniforms.color=g[n],i.uniforms.angle=v[n],s.drawArrays(s.TRIANGLES,l[A],l[M]-l[A]))),m[n]&&w&&(e[1^n]-=T*h*y[n],i.uniforms.dataAxis=r,i.uniforms.screenOffset=e,i.uniforms.color=x[n],i.uniforms.angle=b[n],s.drawArrays(s.TRIANGLES,_,w)),e[1^n]=T*u[2+(1^n)]-1,d[n+2]&&(e[1^n]+=T*h*p[n+2],Al[A]&&(i.uniforms.dataAxis=t,i.uniforms.screenOffset=e,i.uniforms.color=g[n+2],i.uniforms.angle=v[n+2],s.drawArrays(s.TRIANGLES,l[A],l[M]-l[A]))),m[n+2]&&w&&(e[1^n]+=T*h*y[n+2],i.uniforms.dataAxis=r,i.uniforms.screenOffset=e,i.uniforms.color=x[n+2],i.uniforms.angle=b[n+2],s.drawArrays(s.TRIANGLES,_,w))}}(),Wg.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,a=r.gl,i=r.screenBox,o=r.titleCenter,l=r.titleAngle,s=r.titleColor,u=r.pixelRatio;if(this.titleCount){for(var c=0;c<2;++c)e[c]=2*(o[c]*u-i[c])/(i[2+c]-i[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=l,n.uniforms.color=s,a.drawArrays(a.TRIANGLES,this.titleOffset,this.titleCount)}}}(),Wg.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,a=this.shader,i=n._tickBounds,o=n.dataBox,l=n.screenBox,s=n.viewBox;a.bind();for(var u=0;u<2;++u){var c=i[u],f=i[u+2]-c,h=.5*(o[u+2]+o[u]),d=o[u+2]-o[u],p=s[u],g=s[u+2]-p,v=l[u],m=l[u+2]-v;e[u]=2*f/d*g/m,t[u]=2*(c-h)/d*g/m}r[1]=2*n.pixelRatio/(l[3]-l[1]),r[0]=r[1]*(l[3]-l[1])/(l[2]-l[0]),a.uniforms.dataScale=e,a.uniforms.dataShift=t,a.uniforms.textScale=r,this.vbo.bind(),a.attributes.textCoordinate.pointer()}}(),Wg.update=function(t){var e,r,n,a,i,o=[],l=t.ticks,s=t.bounds;for(i=0;i<2;++i){var u=[Math.floor(o.length/3)],c=[-1/0],f=l[i];for(e=0;ea||n[1]<0||n[1]>a)throw new Error("gl-texture2d: Invalid texture size");var i=iv(n,e.stride.slice()),o=0;"float32"===r?o=t.FLOAT:"float64"===r?(o=t.FLOAT,i=!1,r="float32"):"uint8"===r?o=t.UNSIGNED_BYTE:(o=t.UNSIGNED_BYTE,i=!1,r="uint8");var l,s,u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=Rl(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}o!==t.FLOAT||t.getExtension("OES_texture_float")||(o=t.UNSIGNED_BYTE,i=!1);var c=e.size;if(i)l=0===e.offset&&e.data.length===c?e.data:e.data.subarray(e.offset,e.offset+c);else{var f=[n[2],n[2]*n[0],1];s=Ds.malloc(c,r);var h=Rl(s,n,f,0);"float32"!==r&&"float64"!==r||o!==t.UNSIGNED_BYTE?pl.assign(h,e):ev(h,e),l=s.subarray(0,c)}var d=ov(t);t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,o,l),i||Ds.free(s);return new nv(t,d,n[0],n[1],u,o)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")},Qg=null,$g=null,Kg=null;function tv(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var ev=function(t,e){pl.muls(t,e,255)};function rv(t,e,r){var n=t.gl,a=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function nv(t,e,r,n,a,i){this.gl=t,this.handle=e,this.format=a,this.type=i,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,l=[this._wrapS,this._wrapT];Object.defineProperties(l,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=l;var s=[this._shape[0],this._shape[1]];Object.defineProperties(s,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=s}var av=nv.prototype;function iv(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function ov(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function lv(t,e,r,n,a){var i=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture shape");if(a===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=ov(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,a,null),new nv(t,o,e,r,n,a)}Object.defineProperties(av,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Qg.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),$g.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&Qg.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),$g.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),Kg.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),Kg.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(Kg.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return rv(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return rv(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,rv(this,this._shape[0],t),t}}}),av.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},av.dispose=function(){this.gl.deleteTexture(this.handle)},av.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},av.setPixels=function(t,e,r,n){var a=this.gl;this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0;var i=tv(t)?t:t.raw;if(i){this._mipLevels.indexOf(n)<0?(a.texImage2D(a.TEXTURE_2D,0,this.format,this.format,this.type,i),this._mipLevels.push(n)):a.texSubImage2D(a.TEXTURE_2D,n,e,r,this.format,this.type,i)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,n,a,i,o,l){var s=l.dtype,u=l.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var c=0,f=0,h=iv(u,l.stride.slice());"float32"===s?c=t.FLOAT:"float64"===s?(c=t.FLOAT,h=!1,s="float32"):"uint8"===s?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,h=!1,s="uint8");if(2===u.length)f=t.LUMINANCE,u=[u[0],u[1],1],l=Rl(l.data,u,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])f=t.ALPHA;else if(2===u[2])f=t.LUMINANCE_ALPHA;else if(3===u[2])f=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");f=t.RGBA}u[2]}f!==t.LUMINANCE&&f!==t.ALPHA||a!==t.LUMINANCE&&a!==t.ALPHA||(f=a);if(f!==a)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=l.size,p=o.indexOf(n)<0;p&&o.push(n);if(c===i&&h)0===l.offset&&l.data.length===d?p?t.texImage2D(t.TEXTURE_2D,n,a,u[0],u[1],0,a,i,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],a,i,l.data):p?t.texImage2D(t.TEXTURE_2D,n,a,u[0],u[1],0,a,i,l.data.subarray(l.offset,l.offset+d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],a,i,l.data.subarray(l.offset,l.offset+d));else{var g;g=i===t.FLOAT?Ds.mallocFloat32(d):Ds.mallocUint8(d);var v=Rl(g,u,[u[2],u[2]*u[0],1]);c===t.FLOAT&&i===t.UNSIGNED_BYTE?ev(v,l):pl.assign(v,l),p?t.texImage2D(t.TEXTURE_2D,n,a,u[0],u[1],0,a,i,g.subarray(0,d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],a,i,g.subarray(0,d)),i===t.FLOAT?Ds.freeFloat32(g):Ds.freeUint8(g)}}(a,e,r,n,this.format,this.type,this._mipLevels,t)}};var sv,uv,cv,fv,hv=function(t,e,r,n){sv||(sv=t.FRAMEBUFFER_UNSUPPORTED,uv=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,cv=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,fv=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var a=t.getExtension("WEBGL_draw_buffers");!dv&&a&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);dv=new Array(r+1);for(var n=0;n<=r;++n){for(var a=new Array(r),i=0;ii||r<0||r>i)throw new Error("gl-fbo: Parameters are too large for FBO");var o=1;if("color"in(n=n||{})){if((o=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(o>1){if(!a)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(o>t.getParameter(a.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+o+" draw buffers")}}var l=t.UNSIGNED_BYTE,s=t.getExtension("OES_texture_float");if(n.float&&o>0){if(!s)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&o>0&&s&&(l=t.FLOAT);var u=!0;"depth"in n&&(u=!!n.depth);var c=!1;"stencil"in n&&(c=!!n.stencil);return new xv(t,e,r,l,o,u,c,a)},dv=null;function pv(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function gv(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function vv(t){switch(t){case sv:throw new Error("gl-fbo: Framebuffer unsupported");case uv:throw new Error("gl-fbo: Framebuffer incomplete attachment");case cv:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case fv:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function mv(t,e,r,n,a,i){if(!n)return null;var o=Jg(t,e,r,a,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,i,t.TEXTURE_2D,o.handle,0),o}function yv(t,e,r,n,a){var i=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,i),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),i}function xv(t,e,r,n,a,i,o,l){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=l,this.color=new Array(a);for(var s=0;s1&&l.drawBuffersWEBGL(dv[o]);var h=r.getExtension("WEBGL_depth_texture");h?s?t.depth=mv(r,a,i,h.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u&&(t.depth=mv(r,a,i,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):u&&s?t._depth_rb=yv(r,a,i,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u?t._depth_rb=yv(r,a,i,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):s&&(t._depth_rb=yv(r,a,i,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var d=r.checkFramebufferStatus(r.FRAMEBUFFER);if(d!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),f=0;fa||r<0||r>a)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var i=pv(n),o=0;othis.buffer.length){Ds.free(this.buffer);for(var n=this.buffer=Ds.mallocUint8(Av(r*e*4)),a=0;a=0){var g=e[p]-n[p]*(e[p+2]-e[p])/(n[p+2]-n[p]);0===p?o.drawLine(g,e[1],g,e[3],d[p],h[p]):o.drawLine(e[0],g,e[2],g,d[p],h[p])}}for(p=0;p=0;--t)this.objects[t].dispose();this.objects.length=0;for(t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},Sv.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},Sv.removeObject=function(t){for(var e=this.objects,r=0;r0){var m=r*c;o.drawBox(f-m,h-m,d+m,h+m,i),o.drawBox(f-m,p-m,d+m,p+m,i),o.drawBox(f-m,h-m,f+m,p+m,i),o.drawBox(d-m,h-m,d+m,p+m,i)}}}},Iv.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},Iv.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)};var Bv=function(t,e){var r=new Fv(t);return r.update(e),t.addOverlay(r),r};function Fv(t){this.plot=t,this.enable=[!0,!0,!1,!1],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=[1/0,1/0]}var zv=Fv.prototype;zv.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},zv.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,a=this.plot,i=a.line,o=a.dataBox,l=a.viewBox;if(i.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var s=l[0]+(n[0]-o[0])/(o[2]-o[0])*(l[2]-l[0]),u=l[1]+(n[1]-o[1])/(o[3]-o[1])*(l[3]-l[1]);t[0]&&i.drawLine(s,u,l[0],u,e[0],r[0]),t[1]&&i.drawLine(s,u,s,l[1],e[1],r[1]),t[2]&&i.drawLine(s,u,l[2],u,e[2],r[2]),t[3]&&i.drawLine(s,u,s,l[3],e[3],r[3])}},zv.dispose=function(){this.plot.removeOverlay(this)};var Nv=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,a=e;try{var i=[t];0===t.indexOf("webgl")&&i.push("experimental-"+t);for(var o=0;o=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))},qv=function(){},Gv={},Xv=De.id2name,Yv=_a,Wv=i.ALMOST_EQUAL,Zv=wr.FROM_BL;function Jv(t,e){var r=t._inputDomain,n=Zv[t.constraintoward],a=r[0]+(r[1]-r[0])*n;t.domain=t._input.domain=[a+(r[0]-a)/e,a+(r[1]-a)/e]}Gv.enforce=function(t){var e,r,n,a,i,o,l,s=t._fullLayout,u=s._axisConstraintGroups||[];for(e=0;eWv*d)||m)for(r=0;rE&&LT&&(T=L);l/=(T-M)/(2*k),M=a.l2r(M),T=a.l2r(T),a.range=a._input.range=_0)return 1<=0)return 1<Math.abs(s)?(n.boxEnd[1]=n.boxStart[1]+Math.abs(l)*b*(s>=0?1:-1),n.boxEnd[1]u[3]&&(n.boxEnd[1]=u[3],n.boxEnd[0]=n.boxStart[0]+(u[3]-n.boxStart[1])/Math.abs(b))):(n.boxEnd[0]=n.boxStart[0]+Math.abs(s)/b*(l>=0?1:-1),n.boxEnd[0]u[2]&&(n.boxEnd[0]=u[2],n.boxEnd[1]=n.boxStart[1]+(u[2]-n.boxStart[0])*Math.abs(b)))}}else n.boxEnabled?(l=n.boxStart[0]!==n.boxEnd[0],s=n.boxStart[1]!==n.boxEnd[1],l||s?(l&&(g(0,n.boxStart[0],n.boxEnd[0]),t.xaxis.autorange=!1),s&&(g(1,n.boxStart[1],n.boxEnd[1]),t.yaxis.autorange=!1),t.relayoutCallback()):t.glplot.setDirty(),n.boxEnabled=!1,n.boxInited=!1):n.boxInited&&(n.boxInited=!1);break;case"pan":n.boxEnabled=!1,n.boxInited=!1,e?(n.panning||(n.dragStart[0]=i,n.dragStart[1]=o),Math.abs(n.dragStart[0]-i)r?r:t:te?e:t};var sm={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]},um=function(){for(var t=0;t10&&/[0-9](?:\s|\/)/.test(r)&&(i=r.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),a=r.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof r)a="rgb",i=[r>>>16,(65280&r)>>>8,255&r];else if(fm(r)){var f=um(r.r,r.red,r.R,null);null!==f?(a="rgb",i=[f,um(r.g,r.green,r.G),um(r.b,r.blue,r.B)]):(a="hsl",i=[um(r.h,r.hue,r.H),um(r.s,r.saturation,r.S),um(r.l,r.lightness,r.L,r.b,r.brightness)]),o=um(r.a,r.alpha,r.opacity,1),null!=r.opacity&&(o/=100)}else(Array.isArray(r)||t.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(r))&&(i=[r[0],r[1],r[2]],a="rgb",o=4===r.length?r[3]:1);return{space:a,values:i,alpha:o}};var e={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var dm=function(t){var e,r,n,a,i,o=t[0]/360,l=t[1]/100,s=t[2]/100;if(0===l)return[i=255*s,i,i];e=2*s-(r=s<.5?s*(1+l):s+l-s*l),a=[0,0,0];for(var u=0;u<3;u++)(n=o+1/3*-(u-1))<0?n++:n>1&&n--,i=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,a[u]=255*i;return a},pm=function(t){switch(t){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}},gm=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=pm(e),n=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(n.set(t),n);var a="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:255,a&&(n[0]/=255,n[1]/=255,n[2]/=255,n[3]/=255),n):(t.length&&"string"!=typeof t||((t=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=hm(t);return r.space?((e=Array(3))[0]=lm(r.values[0],0,255),e[1]=lm(r.values[1],0,255),e[2]=lm(r.values[2],0,255),"h"===r.space[0]&&(e=dm(e)),e.push(lm(r.alpha,0,1)),e):[]}(t))[0]/=255,t[1]/=255,t[2]/=255),a?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:1):(n[0]=lm(Math.round(255*t[0]),0,255),n[1]=lm(Math.round(255*t[1]),0,255),n[2]=lm(Math.round(255*t[2]),0,255),n[3]=null==t[3]?255:lm(Math.floor(255*t[3]),0,255)),n)};var vm=function(t){return t?gm(t):[0,0,0,1]};function mm(t){this.scene=t,this.gl=t.gl,this.pixelRatio=t.pixelRatio,this.screenBox=[0,0,1,1],this.viewBox=[0,0,1,1],this.dataBox=[-1,-1,1,1],this.borderLineEnable=[!1,!1,!1,!1],this.borderLineWidth=[1,1,1,1],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.ticks=[[],[]],this.tickEnable=[!0,!0,!1,!1],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labels=["x","y"],this.labelEnable=[!0,!0,!1,!1],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelPad=[15,15,15,15],this.labelSize=[12,12],this.labelFont=["sans-serif","sans-serif"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.title="",this.titleEnable=!0,this.titleCenter=[0,0,0,0],this.titleAngle=0,this.titleColor=[0,0,0,1],this.titleFont="sans-serif",this.titleSize=18,this.gridLineEnable=[!0,!0],this.gridLineColor=[[0,0,0,.5],[0,0,0,.5]],this.gridLineWidth=[1,1],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[1,1],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderColor=!1,this.backgroundColor=[0,0,0,0],this.static=this.scene.staticPlot}var ym=mm.prototype,xm=["xaxis","yaxis"];ym.merge=function(t){var e,r,n,a,i,o,l,s,u,c,f;for(this.titleEnable=!1,this.backgroundColor=vm(t.plot_bgcolor),c=0;c<2;++c){var h=(e=xm[c]).charAt(0);for(n=(r=t[this.scene[e]._name]).title===this.scene.fullLayout._dfltTitle[h]?"":r.title,f=0;f<=2;f+=2)this.labelEnable[c+f]=!1,this.labels[c+f]=Hv(n),this.labelColor[c+f]=vm(r.titlefont.color),this.labelFont[c+f]=r.titlefont.family,this.labelSize[c+f]=r.titlefont.size,this.labelPad[c+f]=this.getLabelPad(e,r),this.tickEnable[c+f]=!1,this.tickColor[c+f]=vm((r.tickfont||{}).color),this.tickAngle[c+f]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[c+f]=this.getTickPad(r),this.tickMarkLength[c+f]=0,this.tickMarkWidth[c+f]=r.tickwidth||0,this.tickMarkColor[c+f]=vm(r.tickcolor),this.borderLineEnable[c+f]=!1,this.borderLineColor[c+f]=vm(r.linecolor),this.borderLineWidth[c+f]=r.linewidth||0;l=this.hasSharedAxis(r),i=this.hasAxisInDfltPos(e,r)&&!l,o=this.hasAxisInAltrPos(e,r)&&!l,a=r.mirror||!1,s=l?-1!==String(a).indexOf("all"):!!a,u=l?"allticks"===a:-1!==String(a).indexOf("ticks"),i?this.labelEnable[c]=!0:o&&(this.labelEnable[c+2]=!0),i?this.tickEnable[c]=r.showticklabels:o&&(this.tickEnable[c+2]=r.showticklabels),(i||s)&&(this.borderLineEnable[c]=r.showline),(o||s)&&(this.borderLineEnable[c+2]=r.showline),(i||u)&&(this.tickMarkLength[c]=this.getTickMarkLength(r)),(o||u)&&(this.tickMarkLength[c+2]=this.getTickMarkLength(r)),this.gridLineEnable[c]=r.showgrid,this.gridLineColor[c]=vm(r.gridcolor),this.gridLineWidth[c]=r.gridwidth,this.zeroLineEnable[c]=r.zeroline,this.zeroLineColor[c]=vm(r.zerolinecolor),this.zeroLineWidth[c]=r.zerolinewidth}},ym.hasSharedAxis=function(t){var e=this.scene,r=e.fullLayout._subplots.gl2d;return 0!==Na.findSubplotsWithAxis(r,t).indexOf(e.id)},ym.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},ym.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},ym.getLabelPad=function(t,e){var r=e.titlefont.size,n=e.showticklabels;return"xaxis"===t?"top"===e.side?r*(1.5+(n?1:0))-10:r*(1.5+(n?.5:0))-10:"yaxis"===t?"right"===e.side?10+r*(1.5+(n?1:.5)):10+r*(1.5+(n?.5:0)):void 0},ym.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},ym.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e};var bm,_m,wm=function(t){return new mm(t)},Am=Gv.enforce,Mm=Gv.clean,Tm=wa,km=["xaxis","yaxis"],Em=Oe.SUBPLOT_PATTERN;function Cm(t,e){this.container=t.container,this.graphDiv=t.graphDiv,this.pixelRatio=t.plotGlPixelRatio||window.devicePixelRatio,this.id=t.id,this.staticPlot=!!t.staticPlot,this.scrollZoom=this.graphDiv._context.scrollZoom,this.fullData=null,this.updateRefs(e),this.makeFramework(),this.glplotOptions=wm(this),this.glplotOptions.merge(e),this.glplot=Ev(this.glplotOptions),this.camera=om(this),this.traces={},this.spikes=Bv(this.glplot),this.selectBox=Rv(this.glplot,{innerFill:!1,outerFill:!0}),this.lastButtonState=0,this.pickResult=null,this.isMouseOver=!0,this.stopped=!1,this.redraw=this.draw.bind(this),this.redraw()}var Sm=Cm,Lm=Cm.prototype;Lm.makeFramework=function(){if(this.staticPlot){if(!(_m||(bm=document.createElement("canvas"),_m=jv({canvas:bm,preserveDrawingBuffer:!1,premultipliedAlpha:!0,antialias:!0}))))throw new Error("Error creating static canvas/context for image server");this.canvas=bm,this.gl=_m}else{var t=this.container.querySelector(".gl-canvas-focus"),e=jv({canvas:t,preserveDrawingBuffer:!0,premultipliedAlpha:!0});e||function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=qv);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=$e.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")}}(this),this.canvas=t,this.gl=e}var r=this.canvas;r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style["pointer-events"]="none",this.updateSize(r),r.className+=" user-select-none";var n=this.svgContainer=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.top=n.style.left="0px",n.style.width=n.style.height="100%",n.style["z-index"]=20,n.style["pointer-events"]="none";var a=this.mouseContainer=document.createElement("div");a.style.position="absolute",a.style["pointer-events"]="auto",this.pickCanvas=this.container.querySelector(".gl-canvas-pick");var i=this.container;i.appendChild(n),i.appendChild(a);var o=this;a.addEventListener("mouseout",function(){o.isMouseOver=!1,o.unhover()}),a.addEventListener("mouseover",function(){o.isMouseOver=!0})},Lm.toImage=function(t){t||(t="png"),this.stopped=!0,this.staticPlot&&this.container.appendChild(bm),this.updateSize(this.canvas);var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.clearColor(1,1,1,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),this.glplot.setDirty(),this.glplot.draw(),e.bindFramebuffer(e.FRAMEBUFFER,null);var a=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,a);for(var i=0,o=n-1;i=",">","<="],Im=["[]","()","[)","(]","][",")(","](",")["],Bm={"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["},Fm=b.extendFlat,zm=Fm({},{z:{valType:"data_array",editType:"calc"},x:Fm({},Ln.x,{impliedEdits:{xtype:"array"}}),x0:Fm({},Ln.x0,{impliedEdits:{xtype:"scaled"}}),dx:Fm({},Ln.dx,{impliedEdits:{xtype:"scaled"}}),y:Fm({},Ln.y,{impliedEdits:{ytype:"array"}}),y0:Fm({},Ln.y0,{impliedEdits:{ytype:"scaled"}}),dy:Fm({},Ln.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,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",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,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"}},nr,{autocolorscale:Fm({},nr.autocolorscale,{dflt:!1})},{colorbar:fr}),Nm=or.dash,jm=b.extendFlat,Um=Pm,Vm=Im,Hm=Ln.line,qm=jm({z:zm.z,x:zm.x,x0:zm.x0,dx:zm.dx,y:zm.y,y0:zm.y0,dy:zm.dy,text:zm.text,transpose:zm.transpose,xtype:zm.xtype,ytype:zm.ytype,zhoverformat:zm.zhoverformat,connectgaps:zm.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},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":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:S({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(Um).concat(Vm),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:jm({},Hm.color,{editType:"style+colorbars"}),width:jm({},Hm.width,{editType:"style+colorbars"}),dash:Nm,smoothing:jm({},Hm.smoothing,{}),editType:"plot"}},nr,{autocolorscale:jm({},nr.autocolorscale,{dflt:!1}),zmin:jm({},nr.zmin,{editType:"calc"}),zmax:jm({},nr.zmax,{editType:"calc"})},{colorbar:fr}),Gm=oe.extendFlat;function Xm(t,e,r){var n={type:"linear",range:[t,e]};return Na.autoTicks(n,(e-t)/(r||15)),n}var Ym=i.BADNUM,Wm=function(t){for(var e=0,r=0;rp&&(v=Math.max(v,Math.abs(t[a][i]-d)/(g-p))))}return v}var ty=oe.isArrayOrTypedArray,ey=function(t,e,r,n,a,i){var o,l,s,u=[],c=I.traceIs(t,"contour"),f=I.traceIs(t,"histogram"),h=I.traceIs(t,"gl2d");if(ty(e)&&e.length>1&&!f&&"category"!==i.type){var d=e.length;if(!(d<=a))return c?e.slice(0,a):e.slice(0,a+1);if(c||h)u=e.slice(0,a);else if(1===a)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],s=1;si){var o=i-r[t];return r[t]=i,o}}return 0},max:function(t,e,r,n){var i=n[e];if(a(i)){if(i=Number(i),!a(r[t]))return r[t]=i,i;if(r[t]d&&doy){var p=i===ay?1:6,g=i===ay?"M12":"M1";return function(e,r){var i=n.c2d(e,ay,a),l=i.indexOf("-",p);l>0&&(i=i.substr(0,l));var s=n.d2c(i,0,a);if(suy?t>oy?t>1.1*ay?ay:t>1.1*iy?iy:oy:t>ly?ly:t>sy?sy:uy:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function py(t,e,r,n,a,i){if(n&&t>oy){var o=gy(e,a,i),l=gy(r,a,i),s=t===ay?0:1;return o[s]!==l[s]}return Math.floor(r/t)-Math.floor(e/t)>.1}function gy(t,e,r){var n=e.c2d(t,ay,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}var vy=oe.cleanDate,my=i.ONEDAY,yy=i.BADNUM,xy=function(t,e,r){var n=e.type,i=r+"bins",o=t[i];o||(o=t[i]={});var l="date"===n?function(t){return t||0===t?vy(t,yy,o.calendar):null}:function(t){return a(t)?Number(t):null};o.start=l(o.start),o.end=l(o.end);var s="date"===n?my:1,u=o.size;if(a(u))o.size=u>0?Number(u):s;else if("string"!=typeof u)o.size=s;else{var c=u.charAt(0),f=u.substr(1);((f=a(f)?Number(f):0)<=0||"date"!==n||"M"!==c||f!==Math.round(f))&&(o.size=s)}var h="autobin"+r;"boolean"!=typeof t[h]&&(t[h]=t._fullInput[h]=t._input[h]=!((o.start||0===o.start)&&(o.end||0===o.end))),t[h]||(delete t["nbins"+r],delete t._fullInput["nbins"+r])},by={percent:function(t,e){for(var r=t.length,n=100/e,a=0;av&&l.splice(v,l.length-v),u.length>v&&u.splice(v,u.length-v),_y(e,"x",l,o,h,p,c),_y(e,"y",u,s,d,g,f);var m=[],y=[],x=[],b="string"==typeof e.xbins.size,_="string"==typeof e.ybins.size,w=[],A=[],M=b?w:e.xbins,T=_?A:e.ybins,k=0,E=[],C=[],S=e.histnorm,L=e.histfunc,O=-1!==S.indexOf("density"),D="max"===L||"min"===L?null:0,R=ny.count,P=by[S],I=!1,B=[],F=[],z="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";z&&"count"!==L&&(I="avg"===L,R=ny[L]);var N=e.xbins,j=h(N.start),U=h(N.end)+(j-Na.tickIncrement(j,N.size,!1,c))/1e6;for(r=j;r=0&&a=0&&i=0;i--)(o=((c[[(r=(a=f[i])[0])-1,n=a[1]]]||p)[2]+(c[[r+1,n]]||p)[2]+(c[[r,n-1]]||p)[2]+(c[[r,n+1]]||p)[2])/20)&&(l[a]=[r,n,o],f.splice(i,1),s=!0);if(!s)throw"findEmpties iterated with no new neighbors";for(a in l)c[a]=l[a],u.push(l[a])}return u.sort(function(t,e){return e[2]-t[2]})}(u),e._interpz=function(t,e,r){var n,a,i=1;if(Array.isArray(r))for(n=0;n.01;n++)i=Km(t,e,$m(i));return i>.01&&oe.log("interp2d didn't converge quickly",i),t}(u,e._emptypoints,e._interpz))}function x(t){m=e._input.zsmooth=e.zsmooth=!1,oe.warn('cannot use zsmooth: "fast": '+t)}if("fast"===m)if("log"===h.type||"log"===d.type)x("log axis found");else if(!g){if(r.length){var b=(r[r.length-1]-r[0])/(r.length-1),_=Math.abs(b/100);for(c=0;c_){x("x scale is not linear");break}}if(o.length&&"fast"===m){var w=(o[o.length-1]-o[0])/(o.length-1),A=Math.abs(w/100);for(c=0;cA){x("y scale is not linear");break}}}var M=Wm(u),T="scaled"===e.xtype?"":r,k=ey(e,T,n,i,M,h),E="scaled"===e.ytype?"":o,C=ey(e,E,l,s,u.length,d);v||(Na.expand(h,k),Na.expand(d,C));var S={x:k,y:C,z:u,text:e._text||e.text};if(T&&T.length===k.length-1&&(S.xCenter=T),E&&E.length===C.length-1&&(S.yCenter=E),g&&(S.xRanges=f.xRanges,S.yRanges=f.yRanges,S.pts=f.pts),p&&"constraint"===e.contours.type||ir(e,u,"","z"),p&&e.contours&&"heatmap"===e.contours.coloring){var L={type:"contour"===e.type?"heatmap":"histogram2d",xcalendar:e.xcalendar,ycalendar:e.ycalendar};S.xfill=ey(L,T,n,i,M,h),S.yfill=ey(L,E,l,s,u.length,d)}return[S]},ky=b.extendFlat,Ey=wr.LINE_SPACING,Cy={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},Sy=function(t,e){var r={};function a(){var o=t._fullLayout,l=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var s,u,f=n.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),h=[],d=[],p="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,m=r.levels.size,y=1.001*f[0]-.001*f[1],x=1.001*f[1]-.001*f[0];for(u=0;u<1e5&&(s=r.levels.start+u*m,!(m>0?s>=v:s<=v));u++)s>y&&s0?s>=v:s<=v));u++)s>f[0]&&s1){var V=Math.pow(10,Math.floor(Math.log(U)/Math.LN10));N*=V*oe.roundUp(U/V,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(F.tick0=0)}F.dtick=N}F.domain=[D+S,D+k-S],F.setScale();var H=oe.ensureSingle(o._infolayer,"g",e,function(t){t.classed(Cy.colorbar,!0).each(function(){var t=n.select(this);t.append("rect").classed(Cy.cbbg,!0),t.append("g").classed(Cy.cbfills,!0),t.append("g").classed(Cy.cblines,!0),t.append("g").classed(Cy.cbaxis,!0).classed(Cy.crisp,!0),t.append("g").classed(Cy.cbtitleunshift,!0).append("g").classed(Cy.cbtitle,!0),t.append("rect").classed(Cy.cboutline,!0),t.select(".cbtitle").datum(0)})});H.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var q=H.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");F._axislayer=H.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var X,Y=l.l+(r.x+E)*l.w,W=F.titlefont.size;X="top"===r.titleside?(1-(D+k-S))*l.h+l.t+3+.75*W:(1-(D+S))*l.h+l.t-3-.25*W,tt(F._id+"title",{attributes:{x:Y,y:X,"text-anchor":"start"}})}var Z,J,Q,$=oe.syncOrAsync([na.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var e=H.select(".cbtitle"),a=e.select("text"),i=[-r.outlinewidth/2,r.outlinewidth/2],s=e.select(".h"+F._id+"title-math-group").node(),u=15.6;if(a.node()&&(u=parseInt(a.node().style.fontSize,10)*Ey),s?(G=Jr.bBox(s).height)>u&&(i[1]-=(G-u)/2):a.node()&&!a.classed(Cy.jsPlaceholder)&&(G=Jr.bBox(a.node()).height),G){if(G+=5,"top"===r.titleside)F.domain[1]-=G/l.h,i[1]*=-1;else{F.domain[0]+=G/l.h;var v=Mr.lineCount(a);i[1]+=(1-v)*u}e.attr("transform","translate("+i+")"),F.setScale()}}H.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-F.domain[1]))+")"),F._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var m=H.select(".cbfills").selectAll("rect.cbfill").data(d);m.enter().append("rect").classed(Cy.cbfill,!0).style("stroke","none"),m.exit().remove(),m.each(function(t,e){var r=[0===e?f[0]:(d[e]+d[e-1])/2,e===d.length-1?f[1]:(d[e]+d[e+1])/2].map(F.c2p).map(Math.round);e!==d.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=g(t).replace("e-",""),i=c(a).toHexString();n.select(this).attr({x:L,width:Math.max(A,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:i})});var y=H.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?h:[]);return y.enter().append("path").classed(Cy.cbline,!0),y.exit().remove(),y.each(function(t){n.select(this).attr("d","M"+L+","+(Math.round(F.c2p(t))+r.line.width/2%1)+"h"+A).call(Jr.lineGroupStyle,r.line.width,p(t),r.line.dash)}),F._axislayer.selectAll("g."+F._id+"tick,path").remove(),F._pos=L+A+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),F.side="right",oe.syncOrAsync([function(){return Na.doTicks(t,F,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var e=F.titlefont.size,a=F._offset+F._length/2,i=l.l+(F.position||0)*l.w+("right"===F.side?10+e*(F.showticklabels?1:.5):-10-e*(F.showticklabels?.5:0));tt("h"+F._id+"title",{avoid:{selection:n.select(t).selectAll("g."+F._id+"tick"),side:r.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},na.previousPromises,function(){var n=A+r.outlinewidth/2+Jr.bBox(F._axislayer.node()).width;if((b=q.select("text")).node()&&!b.classed(Cy.jsPlaceholder)){var a,i=q.select(".h"+F._id+"title-math-group").node();a=i&&-1!==["top","bottom"].indexOf(r.titleside)?Jr.bBox(i).width:Jr.bBox(q.node()).right-L-l.l,n=Math.max(n,a)}var o=2*r.xpad+n+r.borderwidth+r.outlinewidth/2,s=R-P;H.select(".cbbg").attr({x:L-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:P-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call($e.fill,r.bgcolor).call($e.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),H.selectAll(".cboutline").attr({x:L,y:P+r.ypad+("top"===r.titleside?G:0),width:Math.max(A,2),height:Math.max(s-2*r.ypad-G,2)}).call($e.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var u=({center:.5,right:1}[r.xanchor]||0)*o;H.attr("transform","translate("+(l.l-u)+","+l.t+")"),na.autoMargin(t,e,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:s*({bottom:1,middle:.5}[r.yanchor]||0),b:s*({top:1,middle:.5}[r.yanchor]||0)})}],t);if($&&$.then&&(t._promises||[]).push($),t._context.edits.colorbarPosition)Ye.init({element:H.node(),gd:t,prepFn:function(){Z=H.attr("transform"),bn(H)},moveFn:function(t,e){H.attr("transform",Z+" translate("+t+","+e+")"),J=Ye.align(O+t/l.w,M,0,1,r.xanchor),Q=Ye.align(D-e/l.h,k,0,1,r.yanchor);var n=Ye.getCursor(J,Q,r.xanchor,r.yanchor);bn(H,n)},doneFn:function(){bn(H),void 0!==J&&void 0!==Q&&I.call("restyle",t,{"colorbar.x":J,"colorbar.y":Q},i().index)}});return $}function K(t,e){return oe.coerce(B,F,ur,t,e)}function tt(e,r){var n,a=i();n=I.traceIs(a,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var l={propContainer:F,propName:n,traceIndex:a.index,placeholder:o._dfltTitle.colorbar,containerGroup:H.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;H.selectAll("."+s+",."+s+"-math-group").remove(),ma.draw(t,e,ky(l,r||{}))}o._infolayer.selectAll("g."+e).remove()}function i(){var r,n,a=e.substr(2);for(r=0;r2?e.value=e.value.slice(2):0===e.length?e.value=[0,1]:e.length<2?(r=parseFloat(e.value[0]),e.value=[r,r+1]):e.value=[parseFloat(e.value[0]),parseFloat(e.value[1])]:a(e.value)&&(r=parseFloat(e.value),e.value=[r,r+1])):(t("contours.value",0),a(e.value)||(Array.isArray(e.value)?e.value=parseFloat(e.value[0]):e.value=0))}(r,c),"="===f?l=c.showlines=!0:(l=r("contours.showlines"),u=r("fillcolor",Ry((t.line||{}).color||i,.5))),l)&&(s=r("line.color",u&&Py(u)?Ry(e.fillcolor,1):i),r("line.width",2),r("line.dash"));r("line.smoothing"),Dy(r,n,s,o)};var zy=oe.isArrayOrTypedArray,Ny=function(t,e,r,n,i,o){var l,s,u=r("z");if(i=i||"x",o=o||"y",void 0===u||!u.length)return 0;if(Jm(t)){if(l=r(i),s=r(o),!l||!s)return 0}else{if(l=jy(i,r),s=jy(o,r),!function(t){for(var e,r=!0,n=!1,i=!1,o=0;o0&&(n=!0);for(var l=0;l>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function Hy(t,e,r,n){return new Function([Vy("A","x"+t+"y",e,["y"],n),Vy("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var qy={ge:Hy(">=",!1,"GE"),gt:Hy(">",!1,"GT"),lt:Hy("<",!0,"LT"),le:Hy("<=",!0,"LE"),eq:Hy("-",!0,"EQ",!0)},Gy=function(t,e){var r=t.gl,n=Zu(r,Uy.vertex,Uy.fragment),a=Zu(r,Uy.fillVertex,Uy.fragment),i=zs(r),o=zs(r),l=zs(r),s=zs(r),u=zs(r),c=new Xy(t,n,a,i,o,l,s,u);return c.update(e),t.addObject(c),c};function Xy(t,e,r,n,a,i,o,l){this.plot=t,this.shader=e,this.fillShader=r,this.positionBuffer=n,this.colorBuffer=a,this.idBuffer=i,this.fillPositionBuffer=o,this.fillColorBuffer=l,this.fillVerts=0,this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.numVertices=0,this.lineWidth=1}var Yy,Wy,Zy=Xy.prototype,Jy=[1,0,0,0,0,1,1,0,1,1,0,1];function Qy(t,e){var r=Math.floor(e);if(r<0)return t[0];if(r>=t.length-1)return t[t.length-1];var n=e-r;return(1-n)*t[r]+n*t[r+1]}Zy.draw=(Yy=[1,0,0,0,1,0,0,0,1],Wy=[0,0],function(){var t,e,r=this.plot,n=this.shader,a=this.fillShader,i=this.bounds,o=this.numVertices,l=this.fillVerts,s=r.gl,u=r.viewBox,c=r.dataBox,f=i[2]-i[0],h=i[3]-i[1],d=c[2]-c[0],p=c[3]-c[1];if(Yy[0]=2*f/d,Yy[4]=2*h/p,Yy[6]=2*(i[0]-c[0])/d-1,Yy[7]=2*(i[1]-c[1])/p-1,Wy[0]=u[2]-u[0],Wy[1]=u[3]-u[1],l>0&&(a.bind(),(t=a.uniforms).viewTransform=Yy,t.screenShape=Wy,e=n.attributes,this.fillPositionBuffer.bind(),e.position.pointer(),this.fillColorBuffer.bind(),e.color.pointer(s.UNSIGNED_BYTE,!0),s.drawArrays(s.TRIANGLES,0,l)),o>0){n.bind();var g=this.lineWidth*r.pixelRatio;(t=n.uniforms).viewTransform=Yy,t.screenShape=Wy,t.lineWidth=g,t.pointSize=1e3,e=n.attributes,this.positionBuffer.bind(),e.position.pointer(s.FLOAT,!1,16,0),e.tangent.pointer(s.FLOAT,!1,16,8),this.colorBuffer.bind(),e.color.pointer(s.UNSIGNED_BYTE,!0),s.drawArrays(s.TRIANGLES,0,o),t.lineWidth=0,t.pointSize=g,this.positionBuffer.bind(),e.position.pointer(s.FLOAT,!1,48,0),e.tangent.pointer(s.FLOAT,!1,48,8),this.colorBuffer.bind(),e.color.pointer(s.UNSIGNED_BYTE,!0,12,0),s.drawArrays(s.POINTS,0,o/3)}}),Zy.drawPick=function(t){return t},Zy.pick=function(t,e,r){return null},Zy.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||Tl(e[0]),n=t.y||Tl(e[1]),a=t.z||new Float32Array(e[0]*e[1]),i=t.levels||[],o=t.levelColors||[],l=this.bounds,s=l[0]=r[0],u=l[1]=n[0],c=l[2]=r[r.length-1],f=l[3]=n[n.length-1];s===c&&(l[2]+=1,c+=1),u===f&&(l[3]+=1,f+=1);var h=1/(c-s),d=1/(f-u);this.lineWidth=t.lineWidth||1;var p=Rl(a,e),g=[],v=[],m=[],y=[],x=[[0,0],[e[0]-1,0],[0,e[1]-1],[e[0]-1,e[1]-1]];function b(t,e,r,n){var a=n-r;return Math.abs(a)<1e-6?e:Math.floor(e)+Math.max(.001,Math.min(.999,(t-r)/a))}for(var _=0;_0&&w===i[_-1])){for(var A=Fg(p,w),M=255*o[4*_]|0,T=255*o[4*_+1]|0,k=255*o[4*_+2]|0,E=255*o[4*_+3]|0,C=A.cells,S=A.positions,L=Array(S.length),O=0;O1)){var I,B=P[0],F=P[1],z=p.get(Math.floor(B),Math.floor(F)),N=p.get(Math.floor(B),Math.ceil(F)),j=p.get(Math.ceil(B),Math.floor(F)),U=p.get(Math.ceil(B),Math.ceil(F));0===Math.floor(P[0])&&z<=w!=N>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function tx(t,e,r,n){return new Function([Ky("A","x"+t+"y",e,["y"],n),Ky("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var ex={ge:tx(">=",!1,"GE"),gt:tx(">",!1,"GT"),lt:tx("<",!0,"LT"),le:tx("<=",!0,"LE"),eq:tx("-",!0,"EQ",!0)},rx=function(t,e){var r=t.gl,n=Zu(r,$y.vertex,$y.fragment),a=Zu(r,$y.pickVertex,$y.pickFragment),i=zs(r),o=zs(r),l=zs(r),s=zs(r),u=new nx(t,n,a,i,o,l,s);return u.update(e),t.addObject(u),u};function nx(t,e,r,n,a,i,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.weightBuffer=a,this.colorBuffer=i,this.idBuffer=o,this.xData=[],this.yData=[],this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.pickOffset=0}var ax=nx.prototype,ix=[0,0,1,0,0,1,1,0,1,1,0,1];function ox(t,e){this.scene=t,this.uid=e,this.type="contourgl",this.name="",this.hoverinfo="all",this.xData=[],this.yData=[],this.zData=[],this.textLabels=[],this.idToIndex=[],this.bounds=[0,0,0,0],this.contourOptions={z:new Float32Array(0),x:[],y:[],shape:[0,0],levels:[0],levelColors:[0,0,0,1],lineWidth:1},this.contour=Gy(t.glplot,this.contourOptions),this.contour._trace=this,this.heatmapOptions={z:new Float32Array(0),x:[],y:[],shape:[0,0],colorLevels:[0],colorValues:[0,0,0,0]},this.heatmap=rx(t.glplot,this.heatmapOptions),this.heatmap._trace=this}ax.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.bounds,a=this.numVertices;if(!(a<=0)){var i=e.gl,o=e.dataBox,l=n[2]-n[0],s=n[3]-n[1],u=o[2]-o[0],c=o[3]-o[1];t[0]=2*l/u,t[4]=2*s/c,t[6]=2*(n[0]-o[0])/u-1,t[7]=2*(n[1]-o[1])/c-1,r.bind();var f=r.uniforms;f.viewTransform=t,f.shape=this.shape;var h=r.attributes;this.positionBuffer.bind(),h.position.pointer(),this.weightBuffer.bind(),h.weight.pointer(i.UNSIGNED_BYTE,!1),this.colorBuffer.bind(),h.color.pointer(i.UNSIGNED_BYTE,!0),i.drawArrays(i.TRIANGLES,0,a)}}}(),ax.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,a=this.pickShader,i=this.bounds,o=this.numVertices;if(!(o<=0)){var l=n.gl,s=n.dataBox,u=i[2]-i[0],c=i[3]-i[1],f=s[2]-s[0],h=s[3]-s[1];t[0]=2*u/f,t[4]=2*c/h,t[6]=2*(i[0]-s[0])/f-1,t[7]=2*(i[1]-s[1])/h-1;for(var d=0;d<4;++d)e[d]=r>>8*d&255;this.pickOffset=r,a.bind();var p=a.uniforms;p.viewTransform=t,p.pickOffset=e,p.shape=this.shape;var g=a.attributes;return this.positionBuffer.bind(),g.position.pointer(),this.weightBuffer.bind(),g.weight.pointer(l.UNSIGNED_BYTE,!1),this.idBuffer.bind(),g.pickId.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,o),r+this.shape[0]*this.shape[1]}}}(),ax.pick=function(t,e,r){var n=this.pickOffset,a=this.shape[0]*this.shape[1];if(r=n+a)return null;var i=r-n,o=this.xData,l=this.yData;return{object:this,pointId:i,dataCoord:[o[i%this.shape[0]],l[i/this.shape[0]|0]]}},ax.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||Tl(e[0]),n=t.y||Tl(e[1]),a=t.z||new Float32Array(e[0]*e[1]);this.xData=r,this.yData=n;var i=t.colorLevels||[0],o=t.colorValues||[0,0,0,1],l=i.length,s=this.bounds,u=s[0]=r[0],c=s[1]=n[0],f=1/((s[2]=r[r.length-1])-u),h=1/((s[3]=n[n.length-1])-c),d=e[0],p=e[1];this.shape=[d,p];var g=(d-1)*(p-1)*(ix.length>>>1);this.numVertices=g;for(var v=Ds.mallocUint8(4*g),m=Ds.mallocFloat32(2*g),y=Ds.mallocUint8(2*g),x=Ds.mallocUint32(g),b=0,_=0;_e.end&&(e.start=e.end=(e.start+e.end)/2),t._input.contours||(t._input.contours={}),Gm(t._input.contours,{start:e.start,end:e.end,size:e.size}),t._input.autocontour=!0}else if("constraint"!==e.type){var n,a=e.start,i=e.end,o=t._input.contours;a>i&&(e.start=o.start=i,i=e.end=o.end=a,a=e.start),e.size>0||(n=a===i?1:Xm(a,i,t.ncontours).dtick,o.size=e.size=n)}}(e),r},fx.plot=ux,fx.moduleType="trace",fx.name="contourgl",fx.basePlotModule=Om,fx.categories=["gl","gl2d","2dMap"],fx.meta={};var hx=fx,dx={"X,X div":"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 .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"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":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","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 .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 px in dx){var gx=px.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");oe.addStyleRule(gx,dx[px])}var vx={undo:{width:857.1,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",ascent:850,descent:-150},home:{width:928.6,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",ascent:850,descent:-150},"camera-retro":{width:1e3,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",ascent:850,descent:-150},zoombox:{width:1e3,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",ascent:850,descent:-150},pan:{width:1e3,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",ascent:850,descent:-150},zoom_plus:{width:1e3,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",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,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",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,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",ascent:850,descent:-150},plotlylogo:{width:1542,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",ascent:850,descent:-150},"z-axis":{width:1e3,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",ascent:850,descent:-150},"3d_rotate":{width:1e3,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",ascent:850,descent:-150},camera:{width:1e3,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",ascent:850,descent:-150},movie:{width:1e3,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",ascent:850,descent:-150},question:{width:857.1,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",ascent:850,descent:-150},disk:{width:857.1,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",ascent:850,descent:-150},lasso:{width:1031,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",ascent:850,descent:-150},selectbox:{width:1e3,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",ascent:850,descent:-150},spikeline:{width:1e3,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",ascent:850,descent:-150}},mx={exports:{}};(function(t,e){!function(t,e){"object"==typeof mx.exports?mx.exports=e():"function"==typeof CC&&CC.amd?CC(e):t.ES6Promise=e()}(this,function(){"use strict";function r(t){return"function"==typeof t}var n=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},a=0,i=void 0,o=void 0,l=function(t,e){p[a]=t,p[a+1]=e,2===(a+=2)&&(o?o(g):b())};var s="undefined"!=typeof window?window:void 0,u=s||{},c=u.MutationObserver||u.WebKitMutationObserver,f="undefined"==typeof self&&void 0!==t&&"[object process]"==={}.toString.call(t),h="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function d(){var t=setTimeout;return function(){return t(g,1)}}var p=new Array(1e3);function g(){for(var t=0;t=0,p=e.indexOf("end")>=0,g=u.backoff*f+r.standoff,v=c.backoff*h+r.startstandoff;if("line"===s.nodeName){a={x:+t.attr("x1"),y:+t.attr("y1")},i={x:+t.attr("x2"),y:+t.attr("y2")};var m=a.x-i.x,y=a.y-i.y;if(l=(o=Math.atan2(y,m))+Math.PI,g&&v&&g+v>Math.sqrt(m*m+y*y))return void S();if(g){if(g*g>m*m+y*y)return void S();var x=g*Math.cos(o),b=g*Math.sin(o);i.x+=x,i.y+=b,t.attr({x2:i.x,y2:i.y})}if(v){if(v*v>m*m+y*y)return void S();var _=v*Math.cos(o),w=v*Math.sin(o);a.x-=_,a.y-=w,t.attr({x1:a.x,y1:a.y})}}else if("path"===s.nodeName){var A=s.getTotalLength(),M="";if(A2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}e._w=C,e._h=S;for(var R=!1,P=["x","y"],B=0;B1)&&(q===H?((K=G.r2fraction(e["a"+V]))<0||K>1)&&(R=!0):R=!0,R))continue;F=G._offset+G.r2p(e[V]),j=.5}else"x"===V?(N=e[V],F=c.l+c.w*N):(N=1-e[V],F=c.t+c.h*N),j=e.showarrow?.5:N;if(e.showarrow){$.head=F;var tt=e["a"+V];U=Y*D(.5,e.xanchor)-W*D(.5,e.yanchor),q===H?($.tail=G._offset+G.r2p(tt),z=U):($.tail=F+tt,z=U+tt),$.text=$.tail+U;var et=u["x"===V?"width":"height"];if("paper"===H&&($.head=oe.constrain($.head,1,et-1)),"pixel"===q){var rt=-Math.max($.tail-3,$.text),nt=Math.min($.tail+3,$.text)-et;rt>0?($.tail+=rt,$.text+=rt):nt>0&&($.tail-=nt,$.text-=nt)}$.tail+=Q,$.head+=Q}else z=U=Z*D(j,J),$.text=F+U;$.text+=Q,U+=Q,z+=Q,e["_"+V+"padplus"]=Z/2+z,e["_"+V+"padminus"]=Z/2-z,e["_"+V+"size"]=Z,e["_"+V+"shift"]=U}if(R)x.remove();else{var at=0,it=0;if("left"!==e.align&&(at=(C-_)*("center"===e.align?.5:1)),"top"!==e.valign&&(it=(S-k)*("middle"===e.valign?.5:1)),l)n.select("svg").attr({x:w+at-1,y:w+it}).call(Jr.setClipUrl,M?h:null);else{var ot=w+it-y.top,lt=w+at-y.left;E.call(Mr.positionText,lt,ot).call(Jr.setClipUrl,M?h:null)}T.select("rect").call(Jr.setRect,w,w,C,S),A.call(Jr.setRect,b/2,b/2,L-b,O-b),x.call(Jr.setTranslate,Math.round(d.x.text-L/2),Math.round(d.y.text-O/2)),v.attr({transform:"rotate("+p+","+d.x.text+","+d.y.text+")"});var st,ut,ct=function(r,n){g.selectAll(".annotation-arrow-g").remove();var l=d.x.head,u=d.y.head,h=d.x.tail+r,m=d.y.tail+n,y=d.x.text+r,b=d.y.text+n,_=oe.rotationXYMatrix(p,y,b),w=oe.apply2DTransform(_),M=oe.apply2DTransform2(_),T=+A.attr("width"),k=+A.attr("height"),E=y-.5*T,C=E+T,S=b-.5*k,L=S+k,O=[[E,S,E,L],[E,L,C,L],[C,L,C,S],[C,S,E,S]].map(M);if(!O.reduce(function(t,e){return t^!!oe.segmentsIntersect(l,u,l+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){O.forEach(function(t){var e=oe.segmentsIntersect(h,m,l,u,t[0],t[1],t[2],t[3]);e&&(h=e.x,m=e.y)});var D=e.arrowwidth,R=e.arrowcolor,P=e.arrowside,B=g.append("g").style({opacity:$e.opacity(R)}).classed("annotation-arrow-g",!0),F=B.append("path").attr("d","M"+h+","+m+"L"+l+","+u).style("stroke-width",D+"px").call($e.stroke,$e.rgb(R));if(bx(F,P,e),f.annotationPosition&&F.node().parentNode&&!a){var z=l,N=u;if(e.standoff){var j=Math.sqrt(Math.pow(l-h,2)+Math.pow(u-m,2));z+=e.standoff*(h-l)/j,N+=e.standoff*(m-u)/j}var U,V,H,q=B.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(h-z)+","+(m-N),transform:"translate("+z+","+N+")"}).style("stroke-width",D+6+"px").call($e.stroke,"rgba(0,0,0,0)").call($e.fill,"rgba(0,0,0,0)");Ye.init({element:q.node(),gd:t,prepFn:function(){var t=Jr.getTranslate(x);V=t.x,H=t.y,U={},i&&i.autorange&&(U[i._name+".autorange"]=!0),o&&o.autorange&&(U[o._name+".autorange"]=!0)},moveFn:function(t,r){var n=w(V,H),a=n[0]+t,l=n[1]+r;x.call(Jr.setTranslate,a,l),U[s+".x"]=i?i.p2r(i.r2p(e.x)+t):e.x+t/c.w,U[s+".y"]=o?o.p2r(o.r2p(e.y)+r):e.y-r/c.h,e.axref===e.xref&&(U[s+".ax"]=i.p2r(i.r2p(e.ax)+t)),e.ayref===e.yref&&(U[s+".ay"]=o.p2r(o.r2p(e.ay)+r)),B.attr("transform","translate("+t+","+r+")"),v.attr({transform:"rotate("+p+","+a+","+l+")"})},doneFn:function(){I.call("relayout",t,U);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(e.showarrow&&ct(0,0),m)Ye.init({element:x.node(),gd:t,prepFn:function(){ut=v.attr("transform"),st={}},moveFn:function(t,r){var n="pointer";if(e.showarrow)e.axref===e.xref?st[s+".ax"]=i.p2r(i.r2p(e.ax)+t):st[s+".ax"]=e.ax+t,e.ayref===e.yref?st[s+".ay"]=o.p2r(o.r2p(e.ay)+r):st[s+".ay"]=e.ay+r,ct(t,r);else{if(a)return;if(i)st[s+".x"]=i.p2r(i.r2p(e.x)+t);else{var l=e._xsize/c.w,u=e.x+(e._xshift-e.xshift)/c.w-l/2;st[s+".x"]=Ye.align(u+t/c.w,l,0,1,e.xanchor)}if(o)st[s+".y"]=o.p2r(o.r2p(e.y)+r);else{var f=e._ysize/c.h,h=e.y-(e._yshift+e.yshift)/c.h-f/2;st[s+".y"]=Ye.align(h-r/c.h,f,0,1,e.yanchor)}i&&o||(n=Ye.getCursor(i?.5:st[s+".x"],o?.5:st[s+".y"],e.xanchor,e.yanchor))}v.attr({transform:"translate("+t+","+r+")"+ut}),bn(x,n)},doneFn:function(){bn(x),I.call("relayout",t,st);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var Mx=_x.draw;function Tx(t){var e=t._fullLayout;oe.filterVisible(e.annotations).forEach(function(e){var r,n,a,i,o=Na.getFromId(t,e.xref),l=Na.getFromId(t,e.yref),s=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=s+e.xshift,n=s-e.xshift,a=u+e.xshift,i=u-e.xshift,e.axref===e.xref?(Na.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),Na.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,a),ppadminus:Math.max(e._xpadminus,i)})):(a=e.ax?a+e.ax:a,i=e.ax?i-e.ax:i,Na.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,a),ppadminus:Math.max(e._xpadminus,n,i)}))),l&&l.autorange&&(r=s-e.yshift,n=s+e.yshift,a=u-e.yshift,i=u+e.yshift,e.ayref===e.yref?(Na.expand(l,[l.r2c(e.y)],{ppadplus:r,ppadminus:n}),Na.expand(l,[l.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,a),ppadminus:Math.max(e._ypadminus,i)})):(a=e.ay?a+e.ay:a,i=e.ay?i-e.ay:i,Na.expand(l,[l.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,a),ppadminus:Math.max(e._ypadminus,n,i)})))})}var kx={hasClickToShow:function(t,e){var r=Ex(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=Ex(t,e),a=n.on,i=n.off.concat(n.explicitOff),o={};if(!a.length&&!i.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+a+'"]').remove():(i._pdata=zx(t.glplot.cameraParams,[e.xaxis.r2l(i.x)*r[0],e.yaxis.r2l(i.y)*r[1],e.zaxis.r2l(i.z)*r[2]]),Nx(t.graphDiv,i,a,t.id,i._xa,i._ya))}}};var Vx={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},Hx=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var a=t.arrayminus||[];return function(t,e){var r=+n[e],i=+a[e];return isNaN(r)&&isNaN(i)?[NaN,NaN]:[i||0,r||0]}}var i=qx(e,t.value),o=qx(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=i(t);return[e,e]}:function(t){return[o(t),i(t)]}};function qx(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var Gx=function(t){for(var e=t.calcdata,r=0;r0;t.each(function(t){var s,u=t[0].trace,c=u.error_x||{},f=u.error_y||{};u.ids&&(s=function(t){return t.id});var h=Zr.hasMarkers(u)&&u.marker.maxdisplayed>0;f.visible||c.visible||(t=[]);var d=n.select(this).selectAll("g.errorbar").data(t,s);if(d.exit().remove(),t.length){c.visible||d.selectAll("path.xerror").remove(),f.visible||d.selectAll("path.yerror").remove(),d.style("opacity",1);var p=d.enter().append("g").classed("errorbar",!0);l&&p.style("opacity",0).transition().duration(r.duration).style("opacity",1),Jr.setClipUrl(d,e.layerClipId),d.each(function(t){var e=n.select(this),s=function(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}(t,i,o);if(!h||t.vis){var u,d=e.select("path.yerror");if(f.visible&&a(s.x)&&a(s.yh)&&a(s.ys)){var p=f.width;u="M"+(s.x-p)+","+s.yh+"h"+2*p+"m-"+p+",0V"+s.ys,s.noYS||(u+="m-"+p+",0h"+2*p),d.size()?l&&(d=d.transition().duration(r.duration).ease(r.easing)):d=e.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),d.attr("d",u)}else d.remove();var g=e.select("path.xerror");if(c.visible&&a(s.y)&&a(s.xh)&&a(s.xs)){var v=(c.copy_ystyle?f:c).width;u="M"+s.xh+","+(s.y-v)+"v"+2*v+"m0,-"+v+"H"+s.xs,s.noXS||(u+="m0,-"+v+"v"+2*v),g.size()?l&&(g=g.transition().duration(r.duration).ease(r.easing)):g=e.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",u)}else g.remove()}})}})},style:function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},i=n.select(this);i.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call($e.stroke,r.color),a.copy_ystyle&&(a=r),i.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call($e.stroke,a.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var Qx={},$x=b.extendFlat;Qx.attributes=function(t,e){t=t||{},e=e||{};var r={valType:"info_array",editType:t.editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},n=(t.name&&t.name,t.trace,e.description&&e.description,{x:$x({},r,{}),y:$x({},r,{}),editType:t.editType});return t.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:t.editType},n.column={valType:"integer",min:0,dflt:0,editType:t.editType}),n},Qx.defaults=function(t,e,r,n){var a=n&&n.x||[0,1],i=n&&n.y||[0,1],o=e.grid;if(o){var l=r("domain.column");void 0!==l&&(l1){l||s||u||"independent"===x("pattern")&&(l=!0),f._hasSubplotGrid=l;var p,g,v="top to bottom"===x("roworder"),m=l?.2:.1,y=l?.3:.1;c&&(p="bottom",g="left"),f._domains={x:ab("x",x,m,p,d),y:ab("y",x,y,g,h,v)}}}function x(t,e){return oe.coerce(r,f,rb,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,a,i,o,l,s,u,c=t.grid||{},f=e._subplots,h=r._hasSubplotGrid,d=r.rows,p=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(h){var m=c.subplots||[];s=r.subplots=new Array(d);var y=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},db={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},pb=!0,gb=function(t,e,r){if(!e._dragged&&!e._editing){var n,a,i,o,l,s=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,f=u.trace,h=f.legendgroup,d={},p=[],g=[],v=[];if(1===r&&pb&&e.data&&e._context.showTips?(oe.notifier(oe._(e,"Double-click on legend to isolate one trace"),"long"),pb=!1):pb=!1,I.traceIs(f,"pie")){var m=u.label,y=s.indexOf(m);1===r?-1===y?s.push(m):s.splice(y,1):2===r&&(s=[],e.calcdata[0].forEach(function(t){m!==t.label&&s.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===s.length&&-1===y&&(s=[])),I.call("relayout",e,"hiddenlabels",s)}else{var x,b=h&&h.length,_=[];if(b)for(n=0;nr[1])return r[1]}return a}function f(t){return t[0]}if(l||s||u){var h={},d={};l&&(h.mc=c("marker.color",f),h.mo=c("marker.opacity",oe.mean,[.2,1]),h.ms=c("marker.size",oe.mean,[2,16]),h.mlc=c("marker.line.color",f),h.mlw=c("marker.line.width",oe.mean,[0,5]),d.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(d.line={width:c("line.width",f,[0,10])}),s&&(h.tx="Aa",h.tp=c("textposition",f),h.ts=10,h.tc=c("textfont.color",f),h.tf=c("textfont.family",f)),r=[oe.minExtend(i,h)],a=oe.minExtend(o,d)}var p=n.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(l?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Jr.pointStyle,a,e),l&&(r[0].mrc=3);var v=p.selectAll("g.pointtext").data(s?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Jr.textPointStyle,a,e)}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=e[r?"increasing":"decreasing"],i=a.line.width,o=n.select(this);o.style("stroke-width",i+"px").call($e.fill,a.fillcolor),i&&$e.stroke(o,a.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=e[r?"increasing":"decreasing"],i=a.line.width,o=n.select(this);o.style("fill","none").call(Jr.dashLine,a.line.dash,i),i&&$e.stroke(o,a.line.color)})})},bb=wr.LINE_SPACING,_b=wr.FROM_TL,wb=wr.FROM_BR,Ab=g.DBLCLICKDELAY;function Mb(t,e){var r=t.data()[0][0],n=e._fullLayout,a=r.trace,i=I.traceIs(a,"pie"),o=a.index,l=i?r.label:a.name,s=oe.ensureSingle(t,"text","legendtext");function u(r){Mr.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,a,i=t.select("g[class*=math-group]"),o=i.node(),l=e._fullLayout.legend.font.size*bb;if(o){var s=Jr.bBox(o);n=s.height,a=s.width,Jr.setTranslate(i,0,n/4)}else{var u=t.select(".legendtext"),c=Mr.lineCount(u),f=u.node();n=l*c,a=f?Jr.bBox(f).width:0;var h=l*(.3+(1-c)/2);Mr.positionText(u,40,h)}n=Math.max(n,16)+3,r.height=n,r.width=a}(t,e)})}s.attr("text-anchor","start").classed("user-select-none",!0).call(Jr.font,n.legend.font).text(l),e._context.edits.legendText&&!i?s.call(Mr.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n=t;this.text()||(t=" ");var a=r.trace._fullInput||{},i={};if(I.hasTransform(a,"groupby")){var l=I.getTransformIndices(a,"groupby"),s=l[l.length-1],c=oe.keyedContainer(a,"transforms["+s+"].styles","target","value.name");""===n?c.remove(r.trace._group):c.set(r.trace._group,t),i=c.constructUpdate()}else i.name=t;return I.call("restyle",e,i,o)}):u(s)}function Tb(t,e){var r,n=1,a=oe.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call($e.fill,"rgba(0,0,0,0)")});a.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimeAb&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){gb(t,e,n)},Ab):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,gb(t,e,n))}})}function kb(t,e,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=fb.isGrouped(i),s=0;if(i._width=0,i._height=0,fb.isVertical(i))l&&e.each(function(t,e){Jr.setTranslate(this,0,e*i.tracegroupgap)}),r.each(function(t){var e=t[0],r=e.height,n=e.width;Jr.setTranslate(this,o,5+o+i._height+r/2),i._height+=r,i._width=Math.max(i._width,n)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var u=[i._width],c=e.data(),f=0,h=c.length;fo+b-_,r.each(function(t){var e=t[0],r=g?40+t[0].width:y;o+x+_+r>a.width-(a.margin.r+a.margin.l)&&(x=0,v+=m,i._height=i._height+m,m=0),Jr.setTranslate(this,o+x,5+o+e.height/2+v),i._width+=_+r,i._height=Math.max(i._height,e.height),x+=_+r,m=Math.max(e.height,m)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(e){var r=e[0],a=n.select(this).select(".legendtoggle");Jr.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function Eb(t){var e=t._fullLayout.legend,r="left";hb.isRightAnchor(e)?r="right":hb.isCenterAnchor(e)&&(r="center");var n="top";hb.isBottomAnchor(e)?n="bottom":hb.isMiddleAnchor(e)&&(n="middle"),na.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*_b[r],r:e._width*wb[r],b:e._height*wb[n],t:e._height*_b[n]})}var Cb={moduleType:"component",name:"legend",layoutAttributes:cb,supplyLayoutDefaults:function(t,e,r){for(var n,a,i,o,l=t.legend||{},s={},u=0,c="normal",f=0;f1)){if(e.legend=s,d("bgcolor",e.paper_bgcolor),d("bordercolor"),d("borderwidth"),oe.coerceFont(d,"font",e.font),d("orientation"),"h"===s.orientation){var p=t.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(n=0,i="left",a=1.1,o="bottom"):(n=0,i="left",a=-.1,o="top")}d("traceorder",c),fb.isGrouped(e.legend)&&d("tracegroupgap"),d("x",n),d("xanchor",i),d("y",a),d("yanchor",o),oe.noneOrAll(l,s,["x","y"])}},draw:function(t){var e=t._fullLayout,r="legend"+e._uid;if(e._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var a=e.legend,i=e.showlegend&&function(t,e){var r,n,a={},i=[],o=!1,l={},s=0;function u(t,r){if(""!==t&&fb.isGrouped(e))-1===i.indexOf(t)?(i.push(t),o=!0,a[t]=[[r]]):a[t].push([r]);else{var n="~~i"+s;i.push(n),a[n]=[[r]],s++}}for(r=0;rv?function(t){var e=t._fullLayout.legend,r="left";hb.isRightAnchor(e)?r="right":hb.isCenterAnchor(e)&&(r="center"),na.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*_b[r],r:e._width*wb[r],b:0,t:0})}(t):Eb(t);var m=e._size,y=m.l+m.w*a.x,x=m.t+m.h*(1-a.y);hb.isRightAnchor(a)?y-=a._width:hb.isCenterAnchor(a)&&(y-=a._width/2),hb.isBottomAnchor(a)?x-=a._height:hb.isMiddleAnchor(a)&&(x-=a._height/2);var b=a._width,_=m.w;b>_?(y=m.l,b=_):(y+b>g&&(y=g-b),y<0&&(y=0),b=Math.min(g-y,a._width));var w,A,M,T,k=a._height,E=m.h;if(k>E?(x=m.t,k=E):(x+k>v&&(x=v-k),x<0&&(x=0),k=Math.min(v-x,a._height)),Jr.setTranslate(s,y,x),h.on(".drag",null),s.on("wheel",null),a._height<=k||t._context.staticPlot)c.attr({width:b-a.borderwidth,height:k-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),Jr.setTranslate(f,0,0),u.select("rect").attr({width:b-2*a.borderwidth,height:k-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth}),Jr.setClipUrl(f,r),Jr.setRect(h,0,0,0,0),delete a._scrollY;else{var C,S,L=Math.max(db.scrollBarMinHeight,k*k/a._height),O=k-L-2*db.scrollBarMargin,D=a._height-k,R=O/D,P=Math.min(a._scrollY||0,D);c.attr({width:b-2*a.borderwidth+db.scrollBarWidth+db.scrollBarMargin,height:k-a.borderwidth,x:a.borderwidth/2,y:a.borderwidth/2}),u.select("rect").attr({width:b-2*a.borderwidth+db.scrollBarWidth+db.scrollBarMargin,height:k-2*a.borderwidth,x:a.borderwidth,y:a.borderwidth+P}),Jr.setClipUrl(f,r),F(P,L,R),s.on("wheel",function(){F(P=oe.constrain(a._scrollY+n.event.deltaY/O*D,0,D),L,R),0!==P&&P!==D&&n.event.preventDefault()});var B=n.behavior.drag().on("dragstart",function(){C=n.event.sourceEvent.clientY,S=P}).on("drag",function(){var t=n.event.sourceEvent;2===t.buttons||t.ctrlKey||F(P=oe.constrain((t.clientY-C)/R+S,0,D),L,R)});h.call(B)}t._context.edits.legendPosition&&(s.classed("cursor-move",!0),Ye.init({element:s.node(),gd:t,prepFn:function(){var t=Jr.getTranslate(s);M=t.x,T=t.y},moveFn:function(t,e){var r=M+t,n=T+e;Jr.setTranslate(s,r,n),w=Ye.align(r,0,m.l,m.l+m.w,a.xanchor),A=Ye.align(n,0,m.t+m.h,m.t,a.yanchor)},doneFn:function(){void 0!==w&&void 0!==A&&I.call("relayout",t,{"legend.x":w,"legend.y":A})},clickFn:function(r,n){var a=e._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});a.size()>0&&(1===r?s._clickTimeout=setTimeout(function(){gb(a,t,r)},Ab):2===r&&(s._clickTimeout&&clearTimeout(s._clickTimeout),gb(a,t,r)))}}))}function F(e,r,n){a._scrollY=t._fullLayout.legend._scrollY=e,Jr.setTranslate(f,0,-e),Jr.setRect(h,b,db.scrollBarMargin+e*n,db.scrollBarWidth,r),u.select("rect").attr({y:a.borderwidth+e})}},style:xb},Sb={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},Lb=b.extendFlat,Ob={visible:{valType:"boolean",editType:"plot"},buttons:Sb=Lb(Sb,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:S({editType:"plot"}),bgcolor:{valType:"color",dflt:D.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:D.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},Db={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var Rb=function(t,e){var r=t._name,a={};if("all"===e.step)a[r+".autorange"]=!0;else{var i=function(t,e){var r,a=t.range,i=new Date(t.r2l(a[1])),o=e.step,l=e.count;switch(e.stepmode){case"backward":r=t.l2r(+n.time[o].utc.offset(i,-l));break;case"todate":var s=n.time[o].utc.offset(i,-l);r=t.l2r(+n.time[o].utc.ceil(s))}var u=a[1];return[r,u]}(t,e);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a};var Pb=wr.LINE_SPACING,Ib=wr.FROM_TL,Bb=wr.FROM_BR;function Fb(t){return t._id}function zb(t,e,r){var n=oe.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:Db.rx,ry:Db.ry}),n.call($e.stroke,e.bordercolor).call($e.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function Nb(t,e,r,n){var a;oe.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(Jr.font,e.font).text((a=r,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(t){Mr.convertToTspans(t,n)})}var jb={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:Ob}}},layoutAttributes:Ob,handleDefaults:function(t,e,r,n,a){var i=t.rangeselector||{},o=e.rangeselector={};function l(t,e){return oe.coerce(i,o,Ob,t,e)}if(l("visible",function(t,e,r){var n,a,i=t.buttons||[],o=e.buttons=[];function l(t,e){return oe.coerce(n,a,Sb,t,e)}for(var s=0;s0)){var s=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),a=0,i=0;i0?u+o:o;return{ppad:o,ppadplus:l?f:h,ppadminus:l?h:f}}return{ppad:o}}function s_(t,e,r,n,a){var i="category"===t.type?t.r2c:t.d2c;if(void 0!==e)return[i(e),i(r)];if(n){var o,l,s,u,c=1/0,f=-1/0,h=n.match(n_.segmentRE);for("date"===t.type&&(i=a_.decodeDate(i)),o=0;of&&(f=u)));return f>=c?[c,f]:void 0}}var u_=function(t,e,r,n,a){function i(r,n){return oe.coerce(t,e,r_,r,n)}if(n=n||{},!i("visible",!(a=a||{}).itemIsNotPlainObject))return e;i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var o=i("type",t.path?"path":"rect"),l=i("xsizemode"),s=i("ysizemode"),u=["x","y"],c=0;c<2;c++){var f,h,d,p=u[c],g=p+"anchor",v="x"===p?l:s,m={_fullLayout:r},y=Na.coerceRef(t,e,m,p,"","paper");if("paper"!==y?(f=Na.getFromId(m,y),d=a_.rangeToShapePosition(f),h=a_.shapePositionToRange(f)):h=d=oe.identity,"path"!==o){var x=p+"0",b=p+"1",_=t[x],w=t[b];t[x]=h(t[x],!0),t[b]=h(t[b],!0),"pixel"===v?(i(x,0),i(b,10)):(Na.coercePosition(e,m,i,y,x,.25),Na.coercePosition(e,m,i,y,b,.75)),e[x]=d(e[x]),e[b]=d(e[b]),t[x]=_,t[b]=w}if("pixel"===v){var A=t[g];t[g]=h(t[g],!0),Na.coercePosition(e,m,i,y,g,.25),e[g]=d(e[g]),t[g]=A}}return"path"===o?i("path"):oe.noneOrAll(t,e,["x0","x1","y0","y1"]),e},c_={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var a=0;as?(m=o,_=I+".y0",T="y0",y=s,w=I+".y1",k="y1"):(m=s,_=I+".y1",T="y1",y=o,w=I+".y0",k="y0");a={},q(e),H.moveFn="move"===z?G:X},doneFn:function(){bn(e),I.call("relayout",t,a)}};function q(t){var r=H.element.getBoundingClientRect(),n=r.right-r.left,a=r.bottom-r.top,i=t.clientX-r.left,o=t.clientY-r.top,l=n>N&&a>j&&!t.shiftKey?Ye.getCursor(i/n,1-o/a):"move";bn(e,l),z=l.split("-")[0]}function G(n,m){if("path"===r.type){var y=function(t){return t},x=y,b=y;U?a[g]=r.xanchor=B(u+n):(x=function(t){return B(R(t)+n)},O&&"date"===O.type&&(x=a_.encodeDate(x))),V?a[v]=r.yanchor=F(c+m):(b=function(t){return F(P(t)+m)},D&&"date"===D.type&&(b=a_.encodeDate(b))),r.path=d_(S,x,b),a[L]=r.path}else U?a[g]=r.xanchor=B(u+n):(a[f]=r.x0=B(i+n),a[d]=r.x1=B(l+n)),V?a[v]=r.yanchor=F(c+m):(a[h]=r.y0=F(o+m),a[p]=r.y1=F(s+m));e.attr("d",h_(t,r))}function X(n,i){if("path"===r.type){var o=function(t){return t},l=o,s=o;U?a[g]=r.xanchor=B(u+n):(l=function(t){return B(R(t)+n)},O&&"date"===O.type&&(l=a_.encodeDate(l))),V?a[v]=r.yanchor=F(c+i):(s=function(t){return F(P(t)+i)},D&&"date"===D.type&&(s=a_.encodeDate(s))),r.path=d_(S,l,s),a[L]=r.path}else{var f=~z.indexOf("n")?m+i:m,h=~z.indexOf("s")?y+i:y,d=~z.indexOf("w")?x+n:x,p=~z.indexOf("e")?b+n:b;~z.indexOf("n")&&V&&(f=m-i),~z.indexOf("s")&&V&&(h=y-i),(!V&&h-f>j||V&&f-h>j)&&(a[_]=r[T]=V?f:F(f),a[w]=r[k]=V?h:F(h)),p-d>N&&(a[A]=r[E]=U?d:B(d),a[M]=r[C]=U?p:B(p))}e.attr("d",h_(t,r))}Ye.init(H),e.node().onmousemove=q}(t,o,n,e)}}function h_(t,e){var r,n,a,i,o,l,s,u,c=e.type,f=Na.getFromId(t,e.xref),h=Na.getFromId(t,e.yref),d=t._fullLayout._size;if(f?(r=a_.shapePositionToRange(f),n=function(t){return f._offset+f.r2p(r(t,!0))}):n=function(t){return d.l+d.w*t},h?(a=a_.shapePositionToRange(h),i=function(t){return h._offset+h.r2p(a(t,!0))}):i=function(t){return d.t+d.h*(1-t)},"path"===c)return f&&"date"===f.type&&(n=a_.decodeDate(n)),h&&"date"===h.type&&(i=a_.decodeDate(i)),function(t,e,r){var n=t.path,a=t.xsizemode,i=t.ysizemode,o=t.xanchor,l=t.yanchor;return n.replace(n_.segmentRE,function(t){var n=0,s=t.charAt(0),u=n_.paramIsX[s],c=n_.paramIsY[s],f=n_.numParams[s],h=t.substr(1).replace(n_.paramRE,function(t){return u[n]?t="pixel"===a?e(o)+Number(t):e(t):c[n]&&(t="pixel"===i?r(l)-Number(t):r(t)),++n>f&&(t="X"),t});return n>f&&(h=h.replace(/[\s,]*X.*/,""),oe.log("Ignoring extra params in segment "+t)),s+h})}(e,n,i);if("pixel"===e.xsizemode){var p=n(e.xanchor);o=p+e.x0,l=p+e.x1}else o=n(e.x0),l=n(e.x1);if("pixel"===e.ysizemode){var g=i(e.yanchor);s=g-e.y0,u=g-e.y1}else s=i(e.y0),u=i(e.y1);if("line"===c)return"M"+o+","+s+"L"+l+","+u;if("rect"===c)return"M"+o+","+s+"H"+l+"V"+u+"H"+o+"Z";var v=(o+l)/2,m=(s+u)/2,y=Math.abs(v-o),x=Math.abs(m-s),b="A"+y+","+x,_=v+y+","+m;return"M"+_+b+" 0 1,1 "+(v+","+(m-x))+b+" 0 0,1 "+_+"Z"}function d_(t,e,r){return t.replace(n_.segmentRE,function(t){var n=0,a=t.charAt(0),i=n_.paramIsX[a],o=n_.paramIsY[a],l=n_.numParams[a];return a+t.substr(1).replace(n_.paramRE,function(t){return n>=l?t:(i[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var p_={moduleType:"component",name:"shapes",layoutAttributes:r_,supplyLayoutDefaults:function(t,e){Ox(t,e,{name:"shapes",handleItemDefaults:u_})},includeBasePlot:Dx("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=oe.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),oe.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),oe.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),oe.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var w_=wr.LINE_SPACING,A_=wr.FROM_TL,M_=wr.FROM_BR;function T_(t){return t._index}function k_(t,e){var r=Jr.tester.selectAll("g."+g_.labelGroupClass).data(e.steps);r.enter().append("g").classed(g_.labelGroupClass,!0);var a=0,i=0;r.each(function(t){var r=S_(n.select(this),{step:t},e).node();if(r){var o=Jr.bBox(r);i=Math.max(i,o.height),a=Math.max(a,o.width)}}),r.remove();var o=e._dims={};o.inputAreaWidth=Math.max(g_.railWidth,g_.gripHeight);var l=t._fullLayout._size;o.lx=l.l+l.w*e.x,o.ly=l.t+l.h*(1-e.y),"fraction"===e.lenmode?o.outerLength=Math.round(l.w*e.len):o.outerLength=e.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-e.pad.l-e.pad.r);var s=(o.inputAreaLength-2*g_.stepInset)/(e.steps.length-1),u=a+g_.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/s)),o.labelHeight=i,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,e.currentvalue.visible){var c=Jr.tester.append("g");r.each(function(t){var r=E_(c,e,t.label),n=r.node()&&Jr.bBox(r.node())||{width:0,height:0},a=Mr.lineCount(r);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,a)}),o.currentValueTotalHeight=o.currentValueHeight+e.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+g_.tickOffset+e.ticklen+g_.labelOffset+o.labelHeight+e.pad.t+e.pad.b;var f="left";hb.isRightAnchor(e)&&(o.lx-=o.outerLength,f="right"),hb.isCenterAnchor(e)&&(o.lx-=o.outerLength/2,f="center");var h="top";hb.isBottomAnchor(e)&&(o.ly-=o.height,h="bottom"),hb.isMiddleAnchor(e)&&(o.ly-=o.height/2,h="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),na.autoMargin(t,g_.autoMarginIdRoot+e._index,{x:e.x,y:e.y,l:o.outerLength*A_[f],r:o.outerLength*M_[f],b:o.height*M_[h],t:o.height*A_[h]})}function E_(t,e,r){if(e.currentvalue.visible){var n,a,i=e._dims;switch(e.currentvalue.xanchor){case"right":n=i.inputAreaLength-g_.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":n=.5*i.inputAreaLength,a="middle";break;default:n=g_.currentValueInset,a="left"}var o=oe.ensureSingle(t,"text",g_.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),l=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)l+=r;else l+=e.steps[e.active].label;e.currentvalue.suffix&&(l+=e.currentvalue.suffix),o.call(Jr.font,e.currentvalue.font).text(l).call(Mr.convertToTspans,e._gd);var s=Mr.lineCount(o),u=(i.currentValueMaxLines+1-s)*e.currentvalue.font.size*w_;return Mr.positionText(o,n,u),o}}function C_(t,e,r){oe.ensureSingle(t,"rect",g_.gripRectClass,function(n){n.call(R_,e,t,r).style("pointer-events","all")}).attr({width:g_.gripWidth,height:g_.gripHeight,rx:g_.gripRadius,ry:g_.gripRadius}).call($e.stroke,r.bordercolor).call($e.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function S_(t,e,r){var n=oe.ensureSingle(t,"text",g_.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return n.call(Jr.font,r.font).text(e.step.label).call(Mr.convertToTspans,r._gd),n}function L_(t,e){var r=oe.ensureSingle(t,"g",g_.labelsClass),a=e._dims,i=r.selectAll("g."+g_.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(g_.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=n.select(this);r.call(S_,t,e),Jr.setTranslate(r,B_(e,t.fraction),g_.tickOffset+e.ticklen+e.font.size*w_+g_.labelOffset+a.currentValueTotalHeight)})}function O_(t,e,r,n,a){var i=Math.round(n*(r.steps.length-1));i!==r.active&&D_(t,e,r,i,!0,a)}function D_(t,e,r,n,a,i){var o=r.active;r._input.active=r.active=n;var l=r.steps[r.active];e.call(I_,r,r.active/(r.steps.length-1),i),e.call(E_,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:a,previousActive:o}),l&&l.method&&a&&(e._nextMethod?(e._nextMethod.step=l,e._nextMethod.doCallback=a,e._nextMethod.doTransition=i):(e._nextMethod={step:l,doCallback:a,doTransition:i},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&na.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function R_(t,e,r){var a=r.node(),i=n.select(e);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();e.emit("plotly_sliderstart",{slider:t});var l=r.select("."+g_.gripRectClass);n.event.stopPropagation(),n.event.preventDefault(),l.call($e.fill,t.activebgcolor);var s=F_(t,n.mouse(a)[0]);O_(e,r,t,s,!0),t._dragging=!0,i.on("mousemove",function(){var t=o(),i=F_(t,n.mouse(a)[0]);O_(e,r,t,i,!1)}),i.on("mouseup",function(){var t=o();t._dragging=!1,l.call($e.fill,t.bgcolor),i.on("mouseup",null),i.on("mousemove",null),e.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function P_(t,e){var r=t.selectAll("rect."+g_.tickRectClass).data(e.steps),a=e._dims;r.enter().append("rect").classed(g_.tickRectClass,!0),r.exit().remove(),r.attr({width:e.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var i=r%a.labelStride==0,o=n.select(this);o.attr({height:i?e.ticklen:e.minorticklen}).call($e.fill,e.tickcolor),Jr.setTranslate(o,B_(e,r/(e.steps.length-1))-.5*e.tickwidth,(i?g_.tickOffset:g_.minorTickOffset)+a.currentValueTotalHeight)})}function I_(t,e,r,n){var a=t.select("rect."+g_.gripRectClass),i=B_(e,r);if(!e._invokingCommand){var o=a;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(i-.5*g_.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function B_(t,e){var r=t._dims;return r.inputAreaStart+g_.stepInset+(r.inputAreaLength-2*g_.stepInset)*Math.min(1,Math.max(0,e))}function F_(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-g_.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*g_.stepInset-2*r.inputAreaStart)))}function z_(t,e,r){var n=r._dims,a=oe.ensureSingle(t,"rect",g_.railTouchRectClass,function(n){n.call(R_,e,t,r).style("pointer-events","all")});a.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,g_.tickOffset+r.ticklen+n.labelHeight)}).call($e.fill,r.bgcolor).attr("opacity",0),Jr.setTranslate(a,0,n.currentValueTotalHeight)}function N_(t,e){var r=e._dims,n=r.inputAreaLength-2*g_.railInset,a=oe.ensureSingle(t,"rect",g_.railRectClass);a.attr({width:n,height:g_.railWidth,rx:g_.railRadius,ry:g_.railRadius,"shape-rendering":"crispEdges"}).call($e.stroke,e.bordercolor).call($e.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),Jr.setTranslate(a,g_.railInset,.5*(r.inputAreaWidth-g_.railWidth)+r.currentValueTotalHeight)}var j_={moduleType:"component",name:g_.name,layoutAttributes:y_,supplyLayoutDefaults:function(t,e){Ox(t,e,{name:x_,handleItemDefaults:__})},draw:function(t){var e=t._fullLayout,r=function(t,e){for(var r=t[g_.name],n=[],a=0;a0?[0]:[]);if(a.enter().append("g").classed(g_.containerClassName,!0).style("cursor","ew-resize"),a.exit().remove(),a.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(E_,r).call(N_,r).call(L_,r).call(P_,r).call(z_,t,r).call(C_,t,r);var n=r._dims;Jr.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(I_,r,r.active/(r.steps.length-1),!1),e.call(E_,r)}(t,n.select(this),e)}})}}},U_=b.extendFlat,V_=(0,_e.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:U_({},v_,{}),font:S({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:D.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),H_={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},q_=H_.name,G_=V_.buttons;function X_(t,e,r){function n(r,n){return oe.coerce(t,e,V_,r,n)}n("visible",function(t,e){var r,n,a=t.buttons||[],i=e.buttons=[];function o(t,e){return oe.coerce(r,n,G_,t,e)}for(var l=0;l0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),oe.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),oe.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var Y_=W_;function W_(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}W_.barWidth=2,W_.barLength=20,W_.barRadius=2,W_.barPad=1,W_.barColor="#808BA4",W_.prototype.enable=function(t,e,r){var a=this.gd._fullLayout,i=a.width,o=a.height;this.position=t;var l,s,u,c,f=this.position.l,h=this.position.w,d=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,m="left"===g,y="up"===g,x=h,b=p;v||m||"right"===g||y||(this.position.direction="down",v=!0),v||y?(s=(l=f)+x,v?(u=d,b=(c=Math.min(u+b,o))-u):b=(c=d+b)-(u=Math.max(c-b,0))):(c=(u=d)+b,m?x=(s=f+x)-(l=Math.max(s-x,0)):(l=f,x=(s=Math.min(l+x,i))-l)),this._box={l:l,t:u,w:x,h:b};var _=h>x,w=W_.barLength+2*W_.barPad,A=W_.barWidth+2*W_.barPad,M=f,T=d+p;T+A>o&&(T=o-A);var k=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);k.exit().on(".drag",null).remove(),k.enter().append("rect").classed("scrollbar-horizontal",!0).call($e.fill,W_.barColor),_?(this.hbar=k.attr({rx:W_.barRadius,ry:W_.barRadius,x:M,y:T,width:w,height:A}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var E=p>b,C=W_.barWidth+2*W_.barPad,S=W_.barLength+2*W_.barPad,L=f+h,O=d;L+C>i&&(L=i-C);var D=this.container.selectAll("rect.scrollbar-vertical").data(E?[0]:[]);D.exit().on(".drag",null).remove(),D.enter().append("rect").classed("scrollbar-vertical",!0).call($e.fill,W_.barColor),E?(this.vbar=D.attr({rx:W_.barRadius,ry:W_.barRadius,x:L,y:O,width:C,height:S}),this._vbarYMin=O+S/2,this._vbarTranslateMax=b-S):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var R=this.id,P=l-.5,I=E?s+C+.5:s+.5,B=u-.5,F=_?c+A+.5:c+.5,z=a._topdefs.selectAll("#"+R).data(_||E?[0]:[]);if(z.exit().remove(),z.enter().append("clipPath").attr("id",R).append("rect"),_||E?(this._clipRect=z.select("rect").attr({x:Math.floor(P),y:Math.floor(B),width:Math.ceil(I)-Math.floor(P),height:Math.ceil(F)-Math.floor(B)}),this.container.call(Jr.setClipUrl,R),this.bg.attr({x:f,y:d,width:h,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Jr.setClipUrl,null),delete this._clipRect),_||E){var N=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(N);var j=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault(),n.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),E&&this.vbar.on(".drag",null).call(j)}this.setTranslate(e,r)},W_.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Jr.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},W_.prototype._onBoxDrag=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t-=n.event.dx),this.vbar&&(e-=n.event.dy),this.setTranslate(t,e)},W_.prototype._onBoxWheel=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t+=n.event.deltaY),this.vbar&&(e+=n.event.deltaY),this.setTranslate(t,e)},W_.prototype._onBarDrag=function(){var t=this.translateX,e=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(oe.constrain(n.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=e+this._vbarYMin,o=i+this._vbarTranslateMax;e=(oe.constrain(n.event.y,i,o)-i)/(o-i)*(this.position.h-this._box.h)}this.setTranslate(t,e)},W_.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=oe.constrain(t||0,0,r),e=oe.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(Jr.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var a=t/r;this.hbar.call(Jr.setTranslate,t+a*this._hbarTranslateMax,e)}if(this.vbar){var i=e/n;this.vbar.call(Jr.setTranslate,t,e+i*this._vbarTranslateMax)}};var Z_=wr.LINE_SPACING;function J_(t){return t._index}function Q_(t,e){return+t.attr(H_.menuIndexAttrName)===e._index}function $_(t,e,r,n,a,i,o,l){e._input.active=e.active=o,"buttons"===e.type?tw(t,n,null,null,e):"dropdown"===e.type&&(a.attr(H_.menuIndexAttrName,"-1"),K_(t,n,a,i,e),l||tw(t,n,a,i,e))}function K_(t,e,r,n,a){var i=oe.ensureSingle(e,"g",H_.headerClassName,function(t){t.style("pointer-events","all")}),o=a._dims,l=a.active,s=a.buttons[l]||H_.blankHeaderOpts,u={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};i.call(ew,a,s,t).call(sw,a,u,c),oe.ensureSingle(e,"text",H_.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(Jr.font,a.font).text(H_.arrowSymbol[a.direction])}).attr({x:o.headerWidth-H_.arrowOffsetX+a.pad.l,y:o.headerHeight/2+H_.textOffsetY+a.pad.t}),i.on("click",function(){r.call(uw),r.attr(H_.menuIndexAttrName,Q_(r,a)?-1:String(a._index)),tw(t,e,r,n,a)}),i.on("mouseover",function(){i.call(iw)}),i.on("mouseout",function(){i.call(ow,a)}),Jr.setTranslate(e,o.lx,o.ly)}function tw(t,e,r,a,i){r||(r=e).attr("pointer-events","all");var o=function(t){return-1==+t.attr(H_.menuIndexAttrName)}(r)&&"buttons"!==i.type?[]:i.buttons,l="dropdown"===i.type?H_.dropdownButtonClassName:H_.buttonClassName,s=r.selectAll("g."+l).data(o),u=s.enter().append("g").classed(l,!0),c=s.exit();"dropdown"===i.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var f=0,h=0,d=i._dims,p=-1!==["up","down"].indexOf(i.direction);"dropdown"===i.type&&(p?h=d.headerHeight+H_.gapButtonHeader:f=d.headerWidth+H_.gapButtonHeader),"dropdown"===i.type&&"up"===i.direction&&(h=-H_.gapButtonHeader+H_.gapButton-d.openHeight),"dropdown"===i.type&&"left"===i.direction&&(f=-H_.gapButtonHeader+H_.gapButton-d.openWidth);var g={x:d.lx+f+i.pad.l,y:d.ly+h+i.pad.t,yPad:H_.gapButton,xPad:H_.gapButton,index:0},v={l:g.x+i.borderwidth,t:g.y+i.borderwidth};s.each(function(o,l){var u=n.select(this);u.call(ew,i,o,t).call(sw,i,g),u.on("click",function(){n.event.defaultPrevented||($_(t,i,0,e,r,a,l),o.execute&&na.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:i,button:o,active:i.active}))}),u.on("mouseover",function(){u.call(iw)}),u.on("mouseout",function(){u.call(ow,i),s.call(aw,i)})}),s.call(aw,i),p?(v.w=Math.max(d.openWidth,d.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(d.openHeight,d.headerHeight)),v.direction=i.direction,a&&(s.size()?function(t,e,r,n,a,i){var o,l,s,u=a.direction,c="up"===u||"down"===u,f=a._dims,h=a.active;if(c)for(l=0,s=0;s0?[0]:[]);if(a.enter().append("g").classed(H_.containerClassName,!0).style("cursor","pointer"),a.exit().remove(),a.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nA.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&oe.log("Clearing previous rejected promises from queue."),t._promises=[]},gw.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(na.subplotsRegistry.cartesian||{}).attrRegex,a=(na.subplotsRegistry.gl3d||{}).attrRegex,i=Object.keys(t);for(e=0;e3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),$e.clean(t),t},gw.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),a=0;a0)return t.substr(0,e)}gw.hasParent=function(t,e){for(var r=Mw(e);r;){if(r in t)return!0;r=Mw(r)}return!1};var Tw=["x","y","z"];gw.clearAxisTypes=function(t,e,r){for(var n=0;n1&&M.warn("Full array edits are incompatible with other edits",a);var f=r[""][""];if(Sw(f))e.set(null);else{if(!Array.isArray(f))return M.warn("Unrecognized full array edit value",a,f),!0;e.set(f)}return!s&&(i(u,c),o(t),!0)}var h,d,p,g,v,m,y,x=Object.keys(r).map(Number).sort(Ew),b=e.get(),_=b||[],w=Z(c,a).get(),A=[],T=-1,k=_.length;for(h=0;h_.length-(y?0:1))M.warn("index out of range",a,p);else if(void 0!==m)v.length>1&&M.warn("Insertion & removal are incompatible with edits to the same index.",a,p),Sw(m)?A.push(p):y?("add"===m&&(m={}),_.splice(p,0,m),w&&w.splice(p,0,{})):M.warn("Unrecognized full object edit value",a,p,m),-1===T&&(T=p);else for(d=0;d=0;h--)_.splice(A[h],1),w&&w.splice(A[h],1);if(_.length?b||e.set(_):e.set(null),s)return!1;if(i(u,c),l!==E){var C;if(-1===T)C=x;else{for(k=Math.max(_.length,k),C=[],h=0;h=T);h++)C.push(p);for(h=T;h1?(m=["toggleHover"],y=["resetViews"]):l?(v=["zoomInGeo","zoomOutGeo"],m=["hoverClosestGeo"],y=["resetGeo"]):o?(m=["hoverClosest3d"],y=["resetCameraDefault3d","resetCameraLastSave3d"]):f?(m=["toggleHover"],y=["resetViewMapbox"]):m=u?["hoverClosestGl2d"]:s?["hoverClosestPie"]:["toggleHover"],i&&(m=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!i&&!u||d||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==y[0]&&(y=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(i||u)&&!d||c?x=["zoom2d","pan2d"]:f||l?x=["pan2d"]:h&&(x=["zoom2d"]),function(t){for(var e=!1,r=0;r=t[1]||a[1]<=t[0])&&i[0]e[0])return!0}return!1}(n,a,d)){var o=i.node(),l=e.bg=oe.ensureSingle(i,"rect","bg");o.insertBefore(l.node(),o.childNodes[0])}else i.select("rect.bg").remove(),h.push(t),d.push([n,a])});var p=r._bgLayer.selectAll(".bg").data(h);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(t){r._plots[t].bg=n.select(this)}),f.each(function(t){var n=r._plots[t],a=n.xaxis,u=n.yaxis;n.bg&&l&&n.bg.call(Jr.setRect,a._offset-i,u._offset-i,a._length+2*i,u._length+2*i).call($e.fill,r.plot_bgcolor).style("stroke-width",0);var c,f,h=n.clipId="clip"+r._uid+t+"plot",d=oe.ensureSingleById(r._clips,"clipPath",h,function(t){t.classed("plotclip",!0).append("rect")});for(n.clipRect=d.select("rect").attr({width:a._length,height:u._length}),Jr.setTranslate(n.plot,a._offset,u._offset),n._hasClipOnAxisFalse?(c=null,f=h):(c=h,f=null),Jr.setClipUrl(n.plot,c),e=0;e=0?u.angularAxis.domain:n.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var T=A.slice();w&&b&&(T[1]+=M);var k=u.angularAxis.ticksCount||4;k>8&&(k=k/(k/8)+k%8),u.angularAxis.ticksStep&&(k=(T[1]-T[0])/k);var E=u.angularAxis.ticksStep||(T[1]-T[0])/(k*(u.minorTicks+1));y&&(E=Math.max(Math.round(E),1)),T[2]||(T[2]=E);var C=n.range.apply(this,T);if(C=C.map(function(t,e){return parseFloat(t.toPrecision(12))}),a=n.scale.linear().domain(T.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),l.layout.angularAxis.domain=a.domain(),l.layout.angularAxis.endPadding=w?M:0,void 0===(t=n.select(this).select("svg.chart-root"))||t.empty()){var S=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),L=this.appendChild(this.ownerDocument.importNode(S.documentElement,!0));t=n.select(L)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var O,D=t.select(".chart-group"),R={fill:"none",stroke:u.tickColor},P={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){O=t.select(".legend-group").attr({transform:"translate("+[g,u.margin.top]+")"}).style({display:"block"});var I=c.map(function(t,e){var r=tA.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});tA.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:$w({},tA.Legend.defaultConfig().legendConfig,{container:O,elements:I,reverseOrder:u.legend.reverseOrder})})();var B=O.node().getBBox();g=Math.min(u.width-B.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,g=Math.max(10,g),m=[u.margin.left+g,u.margin.top+g],r.range([0,g]),l.layout.radialAxis.domain=r.domain(),O.attr("transform","translate("+[m[0]+g,m[1]-g]+")")}else O=t.select(".legend-group").style({display:"none"});t.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),D.attr("transform","translate("+m+")").style({cursor:"crosshair"});var F=[(u.width-(u.margin.left+u.margin.right+2*g+(B?B.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*g))/2];if(F[0]=Math.max(0,F[0]),F[1]=Math.max(0,F[1]),t.select(".outer-group").attr("transform","translate("+F+")"),u.title){var z=t.select("g.title-group text").style(P).text(u.title),N=z.node().getBBox();z.attr({x:m[0]-N.width/2,y:m[1]-g-20})}var j=t.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var U=j.selectAll("circle.grid-circle").data(r.ticks(5));U.enter().append("circle").attr({class:"grid-circle"}).style(R),U.attr("r",r),U.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(R);var V=t.select("circle.background-circle").attr({r:g}).style({fill:u.backgroundColor,stroke:u.stroke});function H(t,e){return a(t)%360+u.orientation}if(u.radialAxis.visible){var q=n.svg.axis().scale(r).ticks(5).tickSize(5);j.call(q).attr({transform:"rotate("+u.radialAxis.orientation+")"}),j.selectAll(".domain").style(R),j.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(P).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,P["font-size"]]+")":"translate("+[0,P["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),X=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(t,e){return"rotate("+H(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),G.exit().remove(),X.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(R),X.selectAll(".minor").style({stroke:u.minorTickColor}),G.select("line.grid-line").attr({x1:u.tickLength?g-u.tickLength:0,x2:g}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),X.append("text").classed("axis-text",!0).style(P);var Y=G.select("text.axis-text").attr({x:g+u.labelOffset,dy:Kw+"em",transform:function(t,e){var r=H(t),n=g+u.labelOffset,a=u.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-r+" "+n+" 0)":"radial"==a?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":y?y[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(P);u.angularAxis.rewriteTicks&&Y.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var W=n.max(D.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));O.attr({transform:"translate("+[g+W,u.margin.top]+")"});var Z=t.select("g.geometry-group").selectAll("g").size()>0,J=t.select("g.geometry-group").selectAll("g.geometry").data(c);if(J.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),J.exit().remove(),c[0]||Z){var Q=[];c.forEach(function(t,e){var n={};n.radialScale=r,n.angularScale=a,n.container=J.filter(function(t,r){return r==e}),n.geometry=t.geometry,n.orientation=u.orientation,n.direction=u.direction,n.index=e,Q.push({data:t,geometryConfig:n})});var $=[];n.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(Q).forEach(function(t,e){"unstacked"===t.key?$=$.concat(t.values.map(function(t,e){return[t]})):$.push(t.values)}),$.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return $w(tA[r].defaultConfig(),t)});tA[r]().config(n)()})}var K,tt,et=t.select(".guides-group"),rt=t.select(".tooltips-group"),nt=tA.tooltipPanel().config({container:rt,fontSize:8})(),at=tA.tooltipPanel().config({container:rt,fontSize:8})(),it=tA.tooltipPanel().config({container:rt,hasTick:!0})();if(!b){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});D.on("mousemove.angular-guide",function(t,e){var r=tA.util.getMousePos(V).angle;ot.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;K=a.invert(n);var i=tA.util.convertToCartesian(g+12,r+180);nt.text(tA.util.round(K)).move([i[0]+m[0],i[1]+m[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var lt=et.select("circle").style({stroke:"grey",fill:"none"});D.on("mousemove.radial-guide",function(t,e){var n=tA.util.getMousePos(V).radius;lt.attr({r:n}).style({opacity:.5}),tt=r.invert(tA.util.getMousePos(V).radius);var a=tA.util.convertToCartesian(n,u.radialAxis.orientation);at.text(tA.util.round(tt)).move([a[0]+m[0],a[1]+m[1]])}).on("mouseout.radial-guide",function(t,e){lt.style({opacity:0}),it.hide(),nt.hide(),at.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(e,r){var a=n.select(this),i=this.style.fill,o="black",l=this.style.opacity||1;if(a.attr({"data-opacity":l}),i&&"none"!==i){a.attr({"data-fill":i}),o=n.hsl(i).darker().toString(),a.style({fill:o,opacity:1});var s={t:tA.util.round(e[0]),r:tA.util.round(e[1])};b&&(s.t=y[e[0]]);var u="t: "+s.t+", r: "+s.r,c=this.getBoundingClientRect(),f=t.node().getBoundingClientRect(),h=[c.left+c.width/2-F[0]-f.left,c.top+c.height/2-F[1]-f.top];it.config({color:o}).text(u),it.move(h)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),o=n.hsl(i).darker().toString(),a.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,e){if(0!=n.event.which)return!1;n.select(this).attr("data-fill")&&it.show()}).on("mouseout.tooltip",function(t,e){it.hide();var r=n.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return i;var e=tA.util.cloneJson(t);return e.data.forEach(function(t,e){i.data[e]||(i.data[e]={}),$w(i.data[e],tA.Axis.defaultConfig().data[0]),$w(i.data[e],t)}),$w(i.layout,tA.Axis.defaultConfig().layout),$w(i.layout,e.layout),this},u.getLiveConfig=function(){return l},u.getinputConfig=function(){return o},u.radialScale=function(t){return r},u.angularScale=function(t){return a},u.svg=function(){return t},n.rebind(u,s,"on"),u},tA.Axis.defaultConfig=function(t,e){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:n.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},tA.util={},tA.DATAEXTENT="dataExtent",tA.AREA="AreaChart",tA.LINE="LinePlot",tA.DOT="DotPlot",tA.BAR="BarChart",tA.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},tA.util._extend=function(t,e){for(var r in t)e[r]=t[r]},tA.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},tA.util.dataFromEquation2=function(t,e){var r=e||6;return n.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},tA.util.dataFromEquation=function(t,e,r){var a=e||6,i=[],o=[];n.range(0,360+a,a).forEach(function(e,r){var n=e*Math.PI/180,a=t(n);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},tA.util.ensureArray=function(t,e){if(void 0===t)return null;var r=[].concat(t);return n.range(e).map(function(t,e){return r[e]||r[0]})},tA.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=tA.util.ensureArray(t[e],r)}),t},tA.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},tA.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},tA.util.sumArrays=function(t,e){return n.zip(t,e).map(function(t,e){return n.sum(t)})},tA.util.arrayLast=function(t){return t[t.length-1]},tA.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},tA.util.flattenArray=function(t){for(var e=[];!tA.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},tA.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},tA.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},tA.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},tA.util.getMousePos=function(t){var e=n.mouse(t.node()),r=e[0],a=e[1],i={};return i.x=r,i.y=a,i.pos=e,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},tA.util.duplicatesCount=function(t){for(var e,r={},n={},a=0,i=t.length;a0)){var s=n.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:c(l),transform:function(t,r){return"rotate("+(e.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return p.fill(r,a,i)},"fill-opacity":0,stroke:function(t,e){return p.stroke(r,a,i)},"stroke-width":function(t,e){return p["stroke-width"](r,a,i)},"stroke-dasharray":function(t,e){return p["stroke-dasharray"](r,a,i)},opacity:function(t,e){return p.opacity(r,a,i)},display:function(t,e){return p.display(r,a,i)}})}};var f=e.angularScale.range(),h=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,d=n.svg.arc().startAngle(function(t){return-h/2}).endAngle(function(t){return h/2}).innerRadius(function(t){return e.radialScale(s+(t[2]||0))}).outerRadius(function(t){return e.radialScale(s+(t[2]||0))+e.radialScale(t[1])});u.arc=function(t,r,a){n.select(this).attr({class:"mark arc",d:d,transform:function(t,r){return"rotate("+(e.orientation+l(t[0])+90)+")"}})};var p={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return void 0===t[n].data.visible||t[n].data.visible?"block":"none"}},g=n.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(p).each(u[e.geometryType]),v.exit().remove(),g.exit().remove()})}return a.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),$w(t[r],tA.PolyChart.defaultConfig()),$w(t[r],e)}),this):t},a.getColorScale=function(){},n.rebind(a,e,"on"),a},tA.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:n.scale.category20()}}},tA.BarChart=function(){return tA.PolyChart()},tA.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},tA.AreaChart=function(){return tA.PolyChart()},tA.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},tA.DotPlot=function(){return tA.PolyChart()},tA.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},tA.LinePlot=function(){return tA.PolyChart()},tA.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},tA.Legend=function(){var t=tA.Legend.defaultConfig(),e=n.dispatch("hover");function r(){var e=t.legendConfig,a=t.data.map(function(t,r){return[].concat(t).map(function(t,n){var a=$w({},e.elements[r]);return a.name=t,a.color=[].concat(e.elements[r].color)[n],a})}),i=n.merge(a);i=i.filter(function(t,r){return e.elements[r]&&(e.elements[r].visibleInLegend||void 0===e.elements[r].visibleInLegend)}),e.reverseOrder&&(i=i.reverse());var o=e.container;("string"==typeof o||o.nodeName)&&(o=n.select(o));var l=i.map(function(t,e){return t.color}),s=e.fontSize,u=null==e.isContinuous?"number"==typeof i[0]:e.isContinuous,c=u?e.height:s*i.length,f=o.classed("legend-group",!0).selectAll("svg").data([0]),h=f.enter().append("svg").attr({width:300,height:c+s,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});h.append("g").classed("legend-axis",!0),h.append("g").classed("legend-marks",!0);var d=n.range(i.length),p=n.scale[u?"linear":"ordinal"]().domain(d).range(l),g=n.scale[u?"linear":"ordinal"]().domain(d)[u?"range":"rangePoints"]([0,c]);if(u){var v=f.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),f.append("rect").classed("legend-mark",!0).attr({height:e.height,width:e.colorBandWidth,fill:"url(#grad1)"})}else{var m=f.select(".legend-marks").selectAll("path.legend-mark").data(i);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[s/2,g(e)+s/2]+")"},d:function(t,e){var r,a,i,o=t.symbol;return i=3*(a=s),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=n.svg.symbolTypes.indexOf(r)?n.svg.symbol().type(r).size(i)():n.svg.symbol().type("square").size(i)()},fill:function(t,e){return p(e)}}),m.exit().remove()}var y=n.svg.axis().scale(g).orient("right"),x=f.select("g.legend-axis").attr({transform:"translate("+[u?e.colorBandWidth:s,s/2]+")"}).call(y);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:u?e.textColor:"none"}),x.selectAll("text").style({fill:e.textColor,"font-size":e.fontSize}).text(function(t,e){return i[e].name}),r}return r.config=function(e){return arguments.length?($w(t,e),this):t},n.rebind(r,e,"on"),r},tA.Legend.defaultConfig=function(t,e){return{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:!1}}},tA.tooltipPanel=function(){var t,e,r,a={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},i="tooltip-"+tA.tooltipPanel.uid++,o=10,l=function(){var n=(t=a.container.selectAll("g."+i).data([0])).enter().append("g").classed(i,!0).style({"pointer-events":"none",display:"none"});return r=n.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=n.append("text").attr({dx:a.padding+o,dy:.3*+a.fontSize}),l};return l.text=function(i){var s=n.hsl(a.color).l,u=s>=.5?"#aaa":"white",c=s>=.5?"black":"white",f=i||"";e.style({fill:c,"font-size":a.fontSize+"px"}).text(f);var h=a.padding,d=e.node().getBBox(),p={fill:a.color,stroke:u,"stroke-width":"2px"},g=d.width+2*h+o,v=d.height+2*h;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[a.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[o,-v/2+2*h]+")"}),t.style({display:"block"}),l},l.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),l},l.hide=function(){if(t)return t.style({display:"none"}),l},l.show=function(){if(t)return t.style({display:"block"}),l},l.config=function(t){return $w(a,t),l},l},tA.tooltipPanel.uid=1,tA.adapter={},tA.adapter.plotly=function(){var t={convert:function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=$w({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,r){tA.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var a=tA.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var n=a.indexOf(t.geometry);-1!=n&&(r.data[e].groupId=n)})}if(t.layout){var i=$w({},t.layout);if([[i,["plot_bgcolor"],["backgroundColor"]],[i,["showlegend"],["showLegend"]],[i,["radialaxis"],["radialAxis"]],[i,["angularaxis"],["angularAxis"]],[i.angularaxis,["showline"],["gridLinesVisible"]],[i.angularaxis,["showticklabels"],["labelsVisible"]],[i.angularaxis,["nticks"],["ticksCount"]],[i.angularaxis,["tickorientation"],["tickOrientation"]],[i.angularaxis,["ticksuffix"],["ticksSuffix"]],[i.angularaxis,["range"],["domain"]],[i.angularaxis,["endpadding"],["endPadding"]],[i.radialaxis,["showline"],["gridLinesVisible"]],[i.radialaxis,["tickorientation"],["tickOrientation"]],[i.radialaxis,["ticksuffix"],["ticksSuffix"]],[i.radialaxis,["range"],["domain"]],[i.angularAxis,["showline"],["gridLinesVisible"]],[i.angularAxis,["showticklabels"],["labelsVisible"]],[i.angularAxis,["nticks"],["ticksCount"]],[i.angularAxis,["tickorientation"],["tickOrientation"]],[i.angularAxis,["ticksuffix"],["ticksSuffix"]],[i.angularAxis,["range"],["domain"]],[i.angularAxis,["endpadding"],["endPadding"]],[i.radialAxis,["showline"],["gridLinesVisible"]],[i.radialAxis,["tickorientation"],["tickOrientation"]],[i.radialAxis,["ticksuffix"],["ticksSuffix"]],[i.radialAxis,["range"],["domain"]],[i.font,["outlinecolor"],["outlineColor"]],[i.legend,["traceorder"],["reverseOrder"]],[i,["labeloffset"],["labelOffset"]],[i,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,r){tA.util.translator.apply(null,t.concat(e))}),e?(void 0!==i.tickLength&&(i.angularaxis.ticklen=i.tickLength,delete i.tickLength),i.tickColor&&(i.angularaxis.tickcolor=i.tickColor,delete i.tickColor)):(i.angularAxis&&void 0!==i.angularAxis.ticklen&&(i.tickLength=i.angularAxis.ticklen),i.angularAxis&&void 0!==i.angularAxis.tickcolor&&(i.tickColor=i.angularAxis.tickcolor)),i.legend&&"boolean"!=typeof i.legend.reverseOrder&&(i.legend.reverseOrder="normal"!=i.legend.reverseOrder),i.legend&&"boolean"==typeof i.legend.traceorder&&(i.legend.traceorder=i.legend.traceorder?"reversed":"normal",delete i.legend.reverseOrder),i.margin&&void 0!==i.margin.t){var o=["t","r","b","l","pad"],l=["top","right","bottom","left","pad"],s={};n.entries(i.margin).forEach(function(t,e){s[l[o.indexOf(t.key)]]=t.value}),i.margin=s}e&&(delete i.needsEndSpacing,delete i.minorTickColor,delete i.minorTicks,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksCount,delete i.angularaxis.ticksStep,delete i.angularaxis.rewriteTicks,delete i.angularaxis.nticks,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksCount,delete i.radialaxis.ticksStep,delete i.radialaxis.rewriteTicks,delete i.radialaxis.nticks),r.layout=i}return r}};return t};var eA,rA=oe.extendDeepAll,nA=eA={};nA.framework=function(t){var e,r,a,i,o,l=new function(){var t,e=[],r=-1,n=!1;function a(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(a(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(a(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),e=e?rA(e,r):r,a||(a=Qw.Axis()),i=Qw.adapter.plotly().convert(e),a.config(i).render(o),t.data=e.data,t.layout=e.layout,nA.fillLayout(t),e}return s.isPolar=!0,s.svg=function(){return a.svg()},s.getConfig=function(){return e},s.getLiveConfig=function(){return Qw.adapter.plotly().convert(a.getLiveConfig(),!0)},s.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},s.setUndoPoint=function(){var t,n,a=this,i=Qw.util.cloneJson(e);t=i,n=r,l.add({undo:function(){n&&a(n)},redo:function(){a(t)}}),r=Qw.util.cloneJson(i)},s.undo=function(){l.undo()},s.redo=function(){l.redo()},s},nA.fillLayout=function(t){var e=n.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),i={width:800,height:600,paper_bgcolor:$e.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=rA(i,t.layout)};var aA={};(aA=Qw).manager=eA;var iA={},oA=Fo.initInteractions,lA=Oe.AX_NAME_PATTERN,sA=0;function uA(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){oe.error(t)}}function cA(t,e){uA(t,$e.combine(e,"white"))}function fA(t,e){t._context||(t._context=oe.extendDeep({},A));var r,n,a,i=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||a<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(a,n+1)>-1||a>=0&&e.indexOf(-t.data.length+a)>-1||a<0&&e.indexOf(t.data.length+a)>-1)throw new Error("each index in "+r+" must be unique.")}}function pA(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),dA(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&dA(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function gA(t,e,r,n,i){!function(t,e,r,n){var a=oe.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!oe.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var i in dA(t,r,"indices"),e){if(!Array.isArray(e[i])||e[i].length!==r.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in n)||!Array.isArray(n[i])||n[i].length!==e[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,r,n);for(var o=function(t,e,r,n){var i,o,l,s,u,c=oe.isPlainObject(n),f=[];for(var h in Array.isArray(r)||(r=[r]),r=hA(r,t.data.length-1),e)for(var d=0;d0&&"string"!=typeof _.parts[A-1];)M--;var T=_.parts[M],k=_.parts[M-1]+"."+T,E=_.parts.slice(0,M).join("."),C=oe.nestedProperty(t.layout,E).get(),S=oe.nestedProperty(o,E).get(),L=_.get();if(void 0!==w){p[b]=w,g[b]="reverse"===T?w:mA(L);var O=zn.getLayoutValObject(o,_.parts);if(O&&O.impliedEdits&&null!==w)for(var D in O.impliedEdits)v(oe.relativeAttr(b,D),O.impliedEdits[D]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=t._initialAutoSize[b];else if(k.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(k),oe.nestedProperty(o,E+"._inputRange").set(null);else if(k.match(/^[xyz]axis[0-9]*\.autorange$/)){x(k),oe.nestedProperty(o,E+"._inputRange").set(null);var R=oe.nestedProperty(o,E).get();R._inputDomain&&(R._input.domain=R._inputDomain.slice())}else k.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&oe.nestedProperty(o,E+"._inputDomain").set(null);if("type"===T){var P=C,B="linear"===S.type&&"log"===w,F="log"===S.type&&"linear"===w;if(B||F){if(P&&P.range)if(S.autorange)B&&(P.range=P.range[1]>P.range[0]?[1,2]:[2,1]);else{var z=P.range[0],N=P.range[1];B?(z<=0&&N<=0&&v(E+".autorange",!0),z<=0?z=N/1e6:N<=0&&(N=z/1e6),v(E+".range[0]",Math.log(z)/Math.LN10),v(E+".range[1]",Math.log(N)/Math.LN10)):(v(E+".range[0]",Math.pow(10,z)),v(E+".range[1]",Math.pow(10,N)))}else v(E+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],I.getComponentMethod("annotations","convertCoords")(t,S,w,v),I.getComponentMethod("images","convertCoords")(t,S,w,v)}else v(E+".autorange",!0),v(E+".range",null);oe.nestedProperty(o,E+"._inputRange").set(null)}else if(T.match(lA)){var j=oe.nestedProperty(o,b).get(),U=(w||{}).type;U&&"-"!==U||(U="linear"),I.getComponentMethod("annotations","convertCoords")(t,j,U,v),I.getComponentMethod("images","convertCoords")(t,j,U,v)}var V=kw.containerArrayMatch(b);if(V){r=V.array,n=V.index;var H=V.property,q=(oe.nestedProperty(i,r)||[])[n]||{},G=q,X=O||{editType:"calc"},Y=-1!==X.editType.indexOf("calcIfAutorange");""===n?(Y?d.calc=!0:_e.update(d,X),Y=!1):""===H&&(G=w,kw.isAddVal(w)?g[b]=null:kw.isRemoveVal(w)?(g[b]=q,G=q):oe.warn("unrecognized full object value",e)),Y&&(_A(t,G,"x")||_A(t,G,"y"))?d.calc=!0:_e.update(d,X),u[r]||(u[r]={});var W=u[r][n];W||(W=u[r][n]={}),W[H]=w,delete e[b]}else"reverse"===T?(C.range?C.range.reverse():(v(E+".autorange",!0),C.range=[1,0]),S.autorange?d.calc=!0:d.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==L&&"select"!==L?d.plot=!0:O?_e.update(d,O):d.calc=!0,_.set(w))}}for(r in u){kw.applyContainerArrayChanges(t,oe.nestedProperty(i,r),u[r],d)||(d.plot=!0)}var Z=o._axisConstraintGroups||[];for(m in y)for(n=0;n=0&&r=0&&r=a.length?a[0]:a[t]:a}function l(t){return Array.isArray(i)?t>=i.length?i[0]:i[t]:i}function s(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(i,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,na.transition(t,e.frame.data,e.frame.layout,gw.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function f(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var h,d,p=0;function g(t){return Array.isArray(a)?p>=a.length?t.transitionOpts=a[p]:t.transitionOpts=a[0]:t.transitionOpts=a,p++,t}var v=[],m=void 0===e||null===e,y=Array.isArray(e);if(!m&&!y&&oe.isPlainObject(e))v.push({type:"object",data:g(oe.extendFlat({},e))});else if(m||-1!==["string","number"].indexOf(typeof e))for(h=0;h0&&__)&&w.push(d);v=w}}v.length>0?function(e){if(0!==e.length){for(var a=0;a=0;n--)if(oe.isPlainObject(e[n])){var h=e[n].name,d=(s[h]||f[h]||{}).name,p=e[n].name,g=s[d]||f[d];d&&p&&"number"==typeof p&&g&&sA<5&&(sA++,oe.warn('addFrames: overwriting frame "'+(s[d]||f[d]).name+'" with a frame whose name of type "number" also equates to "'+d+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===sA&&oe.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),f[h]={name:h},c.push({frame:na.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(a=c[n].frame).name&&oe.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;s[a.name="frame "+t._transitionData._counter++];);if(s[a.name]){for(i=0;i=0;r--)n=e[r],i.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:a[n]});var l=na.modifyFrames,s=na.modifyFrames,u=[t,o],c=[t,i];return dw&&dw.add(t,l,u,s,c),na.modifyFrames(t,i)},iA.purge=function(t){var e=(t=oe.getGraphDiv(t))._fullLayout||{},r=t._fullData||[],n=t.calcdata||[];return na.cleanPlot([],{},r,e,n),na.purge(t),Ge.purge(t),e._container&&e._container.remove(),delete t._context,t};var MA={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},TA=Ne.EventEmitter;var kA=function(t){var e=t.emitter||new TA,r=new Promise(function(n,a){var i=window.Image,o=t.svg,l=t.format||"png";if(oe.isIE()&&"svg"!==l){var s=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return a(s),t.promise?r:e.emit("error",s)}var u=t.canvas,c=t.scale||1,f=c*(t.width||300),h=c*(t.height||150),d=u.getContext("2d"),p=new i,g="data:image/svg+xml,"+encodeURIComponent(o);u.width=f,u.height=h,p.onload=function(){var r;switch("svg"!==l&&d.drawImage(p,0,0,f,h),l){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=g;break;default:var i="Image format is not jpeg, png, svg or webp.";if(a(new Error(i)),!t.promise)return e.emit("error",i)}n(r),t.promise||e.emit("success",r)},p.onerror=function(r){if(a(r),!t.promise)return e.emit("error",r)},p.src=g});return t.promise?r:e},EA=/"/g,CA=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var SA=function(t,e,r){var a,i=t._fullLayout,o=i._paper,l=i._toppaper,s=i.width,u=i.height;o.insert("rect",":first-child").call(Jr.setRect,0,0,s,u).call($e.fill,i.paper_bgcolor);var c=i._basePlotModules||[];for(a=0;a")?"":e.html(t).text()});return e.remove(),r}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(CA,"'"),oe.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},LA={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},OA=/^data:image\/\w+;base64,/;var DA=function(t,e){var r,n,a;function i(t){return!(t in e)||oe.validate(e[t],LA[t])}if(e=e||{},oe.isPlainObject(t)?(r=t.data||[],n=t.layout||{},a=t.config||{}):(t=oe.getGraphDiv(t),r=oe.extendDeep([],t.data),n=oe.extendDeep({},t.layout),a=t._context),!i("width")||!i("height"))throw new Error("Height and width should be pixel values.");if(!i("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function l(t,r){return oe.coerce(e,o,LA,t,r)}var s=l("format"),u=l("width"),c=l("height"),f=l("scale"),h=l("setBackground"),d=l("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=oe.extendFlat({},n);u&&(g.width=u),c&&(g.height=c);var v=oe.extendFlat({},a,{staticPlot:!0,setBackground:h}),m=MA.getRedrawFunc(p);function y(){return new Promise(function(t){setTimeout(t,MA.getDelay(p._fullLayout))})}function x(){return new Promise(function(t,e){var r=SA(p,s,f),n=p._fullLayout.width,a=p._fullLayout.height;if(iA.purge(p),document.body.removeChild(p),"svg"===s)return t(d?r:"data:image/svg+xml,"+encodeURIComponent(r));var i=document.createElement("canvas");i.id=oe.randstr(),kA({format:s,width:n,height:a,scale:f,canvas:i,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){iA.plot(p,r,g,v).then(m).then(y).then(x).then(function(e){t(function(t){return d?t.replace(OA,""):t}(e))}).catch(function(t){e(t)})})},RA=oe.isPlainObject,PA=Array.isArray,IA=oe.isArrayOrTypedArray;function BA(t,e,r,n,a,i){i=i||[];for(var o=Object.keys(t),l=0;lf.length&&n.push(NA("unused",a,u.concat(f.length)));var v,m,y,x,b,_=f.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===h.dimensions)for(m=0;m<_;m++)if(PA(c[m])){c[m].length>f[m].length&&n.push(NA("unused",a,u.concat(m,f[m].length)));var A=f[m].length;for(v=0;v<(w?Math.min(A,g[m].length):A);v++)y=w?g[m][v]:g,x=c[m][v],b=f[m][v],oe.validate(x,y)?b!==x&&b!==+x&&n.push(NA("dynamic",a,u.concat(m,v),x,b)):n.push(NA("value",a,u.concat(m,v),x))}else n.push(NA("array",a,u.concat(m),c[m]));else for(m=0;m<_;m++)y=w?g[m]:g,x=c[m],b=f[m],oe.validate(x,y)?b!==x&&b!==+x&&n.push(NA("dynamic",a,u.concat(m),x,b)):n.push(NA("value",a,u.concat(m),x))}else if(h.items&&!d&&PA(c)){var M,T,k=g[Object.keys(g)[0]],E=[];for(M=0;M1&&i.push(NA("object","layout"))),na.supplyDefaults(o);for(var l=o._fullData,s=r.length,u=0;u-1&&(l[u[r]].title="");for(r=0;r=0;a--){var i=t[a];if("scatter"===i.type&&i.xaxis===r.xaxis&&i.yaxis===r.yaxis){i.opacity=void 0;break}}}}},fM=function(t,e){var r=e[0].trace,n=r.marker,i="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+i).remove(),void 0!==n&&n.showscale){var o=n.color,l=n.cmin,s=n.cmax;a(l)||(l=oe.aggNums(Math.min,null,o)),a(s)||(s=oe.aggNums(Math.max,null,o));var u=e[0].t.cb=Sy(t,i),c=br.makeColorScaleFunc(br.extractScale(n.colorscale,l,s),{noNumericCheck:!0});u.fillcolor(c).filllevels({start:l,end:s,size:(s-l)/254}).options(n.colorbar)()}else na.autoMargin(t,i)},hM=oe.isArrayOrTypedArray,dM=function(t,e,r,n){var a=!1;if(e.marker){var i=e.marker.color,o=(e.marker.line||{}).color;i&&!hM(i)?a=i:o&&!hM(o)&&(a=o)}n("fillcolor",$e.addOpacity((e.line||{}).color||a||r,.5))},pM=oe.isArrayOrTypedArray,gM=function(t,e,r,n,a,i){var o=(t.marker||{}).color;(a("line.color",r),yr(t,"line"))?mr(t,e,n,a,{prefix:"line.",cLetter:"c"}):a("line.color",!pM(o)&&o||r);a("line.width"),(i||{}).noDash||a("line.dash")},vM=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")},mM=function(t,e,r,n,a,i){var o=Zr.isBubble(t),l=(t.line||{}).color;(i=i||{},l&&(r=l),a("marker.symbol"),a("marker.opacity",o?.7:1),a("marker.size"),a("marker.color",r),yr(t,"marker")&&mr(t,e,n,a,{prefix:"marker.",cLetter:"c"}),i.noSelect||(a("selected.marker.color"),a("unselected.marker.color"),a("selected.marker.size"),a("unselected.marker.size")),i.noLine||(a("marker.line.color",l&&!Array.isArray(l)&&e.marker.color!==l?l:o?$e.background:$e.defaultLine),yr(t,"marker.line")&&mr(t,e,n,a,{prefix:"marker.line.",cLetter:"c"}),a("marker.line.width",o?1:0)),o&&(a("marker.sizeref"),a("marker.sizemin"),a("marker.sizemode")),i.gradient)&&("none"!==a("marker.gradient.type")&&a("marker.gradient.color"))},yM=function(t,e,r,n){var a,i=n("x"),o=n("y");if(I.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),i)o?a=Math.min(i.length,o.length):(a=i.length,n("y0"),n("dy"));else{if(!o)return 0;a=e.y.length,n("x0"),n("dx")}return e._length=a,a},xM=function(t,e,r){var n=Array.isArray(r)?function(t){r.push(t)}:function(t){r.text=t},a=oe.extractOption(t,e,"htx","hovertext");if(bM(a))return n(a);var i=oe.extractOption(t,e,"tx","text");return bM(i)?n(i):void 0};function bM(t){return t||0===t}var _M=function(t,e){var r,n;if("lines"===t.mode)return(r=t.line.color)&&$e.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var a=e.mcc||(t.marker||{}).color,i=e.mlcc||((t.marker||{}).line||{}).color;return(n=a&&$e.opacity(a)?a:i&&$e.opacity(i)&&(e.mlw||((t.marker||{}).line||{}).width)?i:"")?$e.opacity(n)<.3?$e.addOpacity(n,.3):n:(r=(t.line||{}).color)&&$e.opacity(r)&&Zr.hasLines(t)&&t.line.width?r:t.fillcolor},wM=i.BADNUM,AM=oe.segmentsIntersect,MM=oe.constrain,TM=function(t,e){var r,n,a,i,o,l,s,u,c,f,h,d,p,g,v,m,y=e.xaxis,x=e.yaxis,b=e.simplify,_=e.connectGaps,w=e.baseTolerance,A=e.shape,M="linear"===A,T=[],k=En.minTolerance,E=new Array(t.length),C=0;function S(e){var r=t[e],n=y.c2p(r.x),a=x.c2p(r.y);return n===wM||a===wM?r.intoCenter||!1:[n,a]}function L(t){var e=t[0]/y._length,r=t[1]/x._length;return(1+En.toleranceGrowth*Math.max(0,-e,e-1,-r,r-1))*w}function O(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}b||(w=k=-1);var D,R,P,I,B,F,z,N=En.maxScreensAway,j=-y._length*N,U=y._length*(1+N),V=-x._length*N,H=x._length*(1+N),q=[[j,V,U,V],[U,V,U,H],[U,H,j,H],[j,H,j,V]];function G(t){if(t[0]U||t[1]H)return[MM(t[0],j,U),MM(t[1],V,H)]}function X(t,e){return t[0]===e[0]&&(t[0]===j||t[0]===U)||(t[1]===e[1]&&(t[1]===V||t[1]===H)||void 0)}function Y(t,e,r){return function(n,a){var i=G(n),o=G(a),l=[];if(i&&o&&X(i,o))return l;i&&l.push(i),o&&l.push(o);var s=2*oe.constrain((n[t]+a[t])/2,e,r)-((i||n)[t]+(o||a)[t]);s&&((i&&o?s>0==i[t]>o[t]?i:o:i||o)[t]+=s);return l}}function W(t){var e=t[0],r=t[1],n=e===E[C-1][0],a=r===E[C-1][1];if(!n||!a)if(C>1){var i=e===E[C-2][0],o=r===E[C-2][1];n&&(e===j||e===U)&&i?o?C--:E[C-1]=t:a&&(r===V||r===H)&&o?i?C--:E[C-1]=t:E[C++]=t}else E[C++]=t}function Z(t){E[C-1][0]!==t[0]&&E[C-1][1]!==t[1]&&W([P,I]),W(t),B=null,P=I=0}function J(t){if(D=t[0]U?U:0,R=t[1]H?H:0,D||R){if(C)if(B){var e=z(B,t);e.length>1&&(Z(e[0]),E[C++]=e[1])}else F=z(E[C-1],t)[0],E[C++]=F;else E[C++]=[D||t[0],R||t[1]];var r=E[C-1];D&&R&&(r[0]!==D||r[1]!==R)?(B&&(P!==D&&I!==R?W(P&&I?(n=B,i=(a=t)[0]-n[0],o=(a[1]-n[1])/i,(n[1]*a[0]-a[1]*n[0])/i>0?[o>0?j:U,H]:[o>0?U:j,V]):[P||D,I||R]):P&&I&&W([P,I])),W([D,R])):P-D&&I-R&&W([D||P,R||I]),B=t,P=D,I=R}else B&&Z(z(B,t)[0]),E[C++]=t;var n,a,i,o}for("linear"===A||"spline"===A?z=function(t,e){for(var r=[],n=0,a=0;a<4;a++){var i=q[a],o=AM(t[0],t[1],e[0],e[1],i[0],i[1],i[2],i[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&O(o,t)L(l))break;a=l,(p=c[0]*u[0]+c[1]*u[1])>h?(h=p,i=l,s=!1):p=t.length||!l)break;J(l),n=l}}else J(i)}B&&W([P||B[0],I||B[1]]),T.push(E.slice(0,C))}return T},kM=function(t,e,r){var n,a,i=null;for(a=0;a=s[0]&&t.x<=s[1]&&t.y>=u[0]&&t.y<=u[1]}),d=Math.ceil(h.length/f),p=0;i.forEach(function(t,r){var n=t[0].trace;Zr.hasMarkers(n)&&n.marker.maxdisplayed>0&&r0;function f(t){return c?t.transition():t}var h=r.xaxis,d=r.yaxis,p=a[0].trace,g=p.line,v=n.select(o);if(I.getComponentMethod("errorbars","plot")(v,r,l),!0===p.visible){var m,y;f(v).style("opacity",p.opacity);var x=p.fill.charAt(p.fill.length-1);"x"!==x&&"y"!==x&&(x=""),r.isRangePlot||(a[0].node3=v);var b="",_=[],w=p._prevtrace;w&&(b=w._prevRevpath||"",y=w._nextFill,_=w._polygons);var A,M,T,k,E,C,S,L,O,D="",R="",P=[],B=oe.noop;if(m=p._ownFill,Zr.hasLines(p)||"none"!==p.fill){for(y&&y.datum(a),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=Jr.steps(g.shape),k=Jr.steps(g.shape.split("").reverse().join(""))):T=k="spline"===g.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?Jr.smoothclosed(t.slice(1),g.smoothing):Jr.smoothopen(t,g.smoothing)}:function(t){return"M"+t.join("L")},E=function(t){return k(t.reverse())},P=TM(a,{xaxis:h,yaxis:d,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),O=p._polygons=new Array(P.length),u=0;u1){var r=n.select(this);if(r.datum(a),t)f(r.style("opacity",0).attr("d",A).call(Jr.lineGroupStyle)).style("opacity",1);else{var i=f(r);i.attr("d",A),Jr.singleLineStyle(a,i)}}}}}var F=v.selectAll(".js-line").data(P);f(F.exit()).style("opacity",0).remove(),F.each(B(!1)),F.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Jr.lineGroupStyle).each(B(!0)),Jr.setClipUrl(F,r.layerClipId),P.length?(m?C&&L&&(x?("y"===x?C[1]=L[1]=d.c2p(0,!0):"x"===x&&(C[0]=L[0]=h.c2p(0,!0)),f(m).attr("d","M"+L+"L"+C+"L"+D.substr(1)).call(Jr.singleFillStyle)):f(m).attr("d",D+"Z").call(Jr.singleFillStyle)):y&&("tonext"===p.fill.substr(0,6)&&D&&b?("tonext"===p.fill?f(y).attr("d",D+"Z"+b+"Z").call(Jr.singleFillStyle):f(y).attr("d",D+"L"+b.substr(1)+"Z").call(Jr.singleFillStyle),p._polygons=p._polygons.concat(_)):(N(y),p._polygons=null)),p._prevRevpath=R,p._prevPolygons=O):(m?N(m):y&&N(y),p._polygons=p._prevRevpath=p._prevPolygons=null);var z=v.selectAll(".points");s=z.data([a]),z.each(q),s.enter().append("g").classed("points",!0).each(q),s.exit().remove(),s.each(function(t){var e=!1===t[0].trace.cliponaxis;Jr.setClipUrl(n.select(this),e?null:r.layerClipId)})}function N(t){f(t).attr("d","M0,0Z")}function j(t){return t.filter(function(t){return t.vis})}function U(t){return t.id}function V(t){if(t.ids)return U}function H(){return!1}function q(e){var a,i=e[0].trace,o=n.select(this),l=Zr.hasMarkers(i),s=Zr.hasText(i),u=V(i),p=H,g=H;l&&(p=i.marker.maxdisplayed||i._needsCull?j:oe.identity),s&&(g=i.marker.maxdisplayed||i._needsCull?j:oe.identity);var v=(a=o.selectAll("path.point").data(p,u)).enter().append("path").classed("point",!0);c&&v.call(Jr.pointStyle,i,t).call(Jr.translatePoints,h,d).style("opacity",0).transition().style("opacity",1);var m=l&&Jr.tryColorscale(i.marker,""),y=l&&Jr.tryColorscale(i.marker,"line");a.order(),a.each(function(e){var a=n.select(this),o=f(a);Jr.translatePoint(e,o,h,d)?(Jr.singlePointStyle(e,o,i,m,y,t),r.layerClipId&&Jr.hideOutsideRangePoint(e,o,h,d,i.xcalendar,i.ycalendar),i.customdata&&a.classed("plotly-customdata",null!==e.data&&void 0!==e.data)):o.remove()}),c?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=o.selectAll("g").data(g,u)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var e=n.select(this),a=f(e.select("text"));Jr.translatePoint(t,a,h,d)?r.layerClipId&&Jr.hideOutsideRangePoint(t,e,h,d,i.xcalendar,i.ycalendar):e.remove()}),a.selectAll("text").call(Jr.textPointStyle,i,t).each(function(t){var e=h.c2p(t.x),r=d.c2p(t.y);n.select(this).selectAll("tspan.line").each(function(){f(n.select(this)).attr({x:e,y:r})})}),a.exit().remove()}}function SM(t,e,r){var n=t.selectAll("path.point"),a=t.selectAll("text");Jr.pointStyle(n,e,r),Jr.textPointStyle(a,e,r),Jr.selectedPointStyle(n,e),Jr.selectedTextStyle(a,e)}var LM=function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.scatter");r.style("opacity",function(t){return t[0].trace.opacity}),r.selectAll("g.points").each(function(e){SM(n.select(this),e.trace||e[0].trace,t)}),r.selectAll("g.trace path.js-line").call(Jr.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(Jr.fillGroupStyle),I.getComponentMethod("errorbars","style")(r)},OM={};OM.hasLines=Zr.hasLines,OM.hasMarkers=Zr.hasMarkers,OM.hasText=Zr.hasText,OM.isBubble=Zr.isBubble,OM.attributes=Ln,OM.supplyDefaults=function(t,e,r,n){function a(r,n){return oe.coerce(t,e,Ln,r,n)}var i=yM(t,e,n,a),o=i0;for((s=c.selectAll("g.trace").data(r,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),kM(t,e,r),function(t,e,r){var a;e.selectAll("g.trace").each(function(t){var e=n.select(this);if((a=t[0].trace)._nexttrace){if(a._nextFill=e.select(".js-fill.js-tonext"),!a._nextFill.size()){var i=":first-child";e.select(".js-fill.js-tozero").size()&&(i+=" + *"),a._nextFill=e.insert("path",i).attr("class","js-fill js-tonext")}}else e.selectAll(".js-fill.js-tonext").remove(),a._nextFill=null;a.fill&&("tozero"===a.fill.substr(0,6)||"toself"===a.fill||"to"===a.fill.substr(0,2)&&!a._prevtrace)?(a._ownFill=e.select(".js-fill.js-tozero"),a._ownFill.size()||(a._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),a._ownFill=null),e.selectAll(".js-fill").call(Jr.setClipUrl,r.layerClipId)})}(0,c,e),o=0,l={};ol[e[0].trace.uid]?1:-1}),h?(i&&(u=i()),n.transition().duration(a.duration).ease(a.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(n,i){CM(t,i,e,n,r,this,a)})})):c.selectAll("g.trace").each(function(n,i){CM(t,i,e,n,r,this,a)});f&&s.exit().remove(),c.selectAll("path:not([d])").remove()},OM.colorbar=fM,OM.style=LM,OM.hoverPoints=function(t,e,r,n){var a=t.cd,i=a[0].trace,o=t.xa,l=t.ya,s=o.c2p(e),u=l.c2p(r),c=[s,u],f=i.hoveron||"",h=-1!==i.mode.indexOf("markers")?3:.5;if(-1!==f.indexOf("points")){var d=function(t){var e=Math.max(h,t.mrc||0),r=o.c2p(t.x)-s,n=l.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-h/e)},p=Di.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-s);return nB!=(E=w[b][1])>=B&&(M=w[b-1][0],T=w[b][0],E-k&&(A=M+(T-M)*(B-k)/(E-k),O=Math.min(O,A),D=Math.max(D,A)));O=Math.max(O,0),D=Math.min(D,o._length);var F=$e.defaultLine;return $e.opacity(i.fillcolor)?F=i.fillcolor:$e.opacity((i.line||{}).color)&&(F=i.line.color),oe.extendFlat(t,{distance:t.maxHoverDistance,x0:O,x1:D,y0:B,y1:B,color:F}),delete t.index,i.text&&!Array.isArray(i.text)?t.text=String(i.text):t.text=i.name,[t]}}},OM.selectPoints=function(t,e){var r,n,a,i,o=t.cd,l=t.xaxis,s=t.yaxis,u=[],c=o[0].trace;if(!Zr.hasMarkers(c)&&!Zr.hasText(c))return[];if(!1===e)for(r=0;r>>=e))<<3,(e|=r=(15<(t>>>=r))<<2)|(r=(3<(t>>>=r))<<1)|t>>>r>>1}function s(t){t:{for(var e=16;268435456>=e;e*=16)if(t<=e){t=e;break t}t=0}return 0<(e=Y[l(t)>>2]).length?e.pop():new ArrayBuffer(t)}function u(t){Y[l(t.byteLength)>>2].push(t)}function c(t,e,r,n,a,i){for(var o=0;o(a=s)&&(a=n.buffer.byteLength,5123===f?a>>=1:5125===f&&(a>>=2)),n.vertCount=a,a=l,0>l&&(a=4,1===(l=n.buffer.dimension)&&(a=0),2===l&&(a=1),3===l&&(a=4)),n.primType=a}function l(t){n.elementsCount--,delete s[t.id],t.buffer.destroy(),t.buffer=null}var s={},u=0,c={uint8:5121,uint16:5123};e.oes_element_index_uint&&(c.uint32=5125),a.prototype.bind=function(){this.buffer.bind()};var f=[];return{create:function(t,e){function s(t){if(t)if("number"==typeof t)u(t),f.primType=4,f.vertCount=0|t,f.type=5121;else{var e=null,r=35044,n=-1,a=-1,l=0,h=0;Array.isArray(t)||G(t)||i(t)?e=t:("data"in t&&(e=t.data),"usage"in t&&(r=$[t.usage]),"primitive"in t&&(n=rt[t.primitive]),"count"in t&&(a=0|t.count),"type"in t&&(h=c[t.type]),"length"in t?l=0|t.length:(l=a,5123===h||5122===h?l*=2:5125!==h&&5124!==h||(l*=4))),o(f,e,r,n,a,l,h)}else u(),f.primType=4,f.vertCount=0,f.type=5121;return s}var u=r.create(null,34963,!0),f=new a(u._buffer);return n.elementsCount++,s(t),s._reglType="elements",s._elements=f,s.subdata=function(t,e){return u.subdata(t,e),s},s.destroy=function(){l(f)},s},createStream:function(t){var e=f.pop();return e||(e=new a(r.create(null,34963,!0,!1)._buffer)),o(e,t,35040,-1,-1,0,0),e},destroyStream:function(t){f.push(t)},getElements:function(t){return"function"==typeof t&&t._elements instanceof a?t._elements:null},clear:function(){X(s).forEach(l)}}}function v(t){for(var e=W.allocType(5123,t.length),r=0;r>>31<<15,a=(i<<1>>>24)-127,i=i>>13&1023;e[r]=-24>a?n:-14>a?n+(i+1024>>-14-a):15>=a,r.height>>=a,d(r,n[a]),t.mipmask|=1<e;++e)t.images[e]=null;return t}function S(t){for(var e=t.images,r=0;re){for(var r=0;r=--this.refCount&&B(this)}}),l.profile&&(o.getTotalTextureSize=function(){var t=0;return Object.keys(ft).forEach(function(e){t+=ft[e].stats.size}),t}),{create2D:function(e,r){function n(t,e){var r=a.texInfo;L.call(r);var i=C();return"number"==typeof t?T(i,0|t,"number"==typeof e?0|e:0|t):t?(O(r,t),k(i,t)):T(i,1,1),r.genMipmaps&&(i.mipmask=(i.width<<1)-1),a.mipmask=i.mipmask,u(a,i),a.internalformat=i.internalformat,n.width=i.width,n.height=i.height,P(a),E(i,3553),D(r,3553),I(),S(i),l.profile&&(a.stats.size=A(a.internalformat,a.type,i.width,i.height,r.genMipmaps,!1)),n.format=K[a.internalformat],n.type=tt[a.type],n.mag=et[r.magFilter],n.min=rt[r.minFilter],n.wrapS=nt[r.wrapS],n.wrapT=nt[r.wrapT],n}var a=new R(3553);return ft[a.id]=a,o.textureCount++,n(e,r),n.subimage=function(t,e,r,i){e|=0,r|=0,i|=0;var o=g();return u(o,a),o.width=0,o.height=0,d(o,t),o.width=o.width||(a.width>>i)-e,o.height=o.height||(a.height>>i)-r,P(a),p(o,3553,e,r,i),I(),M(o),n},n.resize=function(e,r){var i=0|e,o=0|r||i;if(i===a.width&&o===a.height)return n;n.width=a.width=i,n.height=a.height=o,P(a);for(var s=0;a.mipmask>>s;++s)t.texImage2D(3553,s,a.format,i>>s,o>>s,0,a.format,a.type,null);return I(),l.profile&&(a.stats.size=A(a.internalformat,a.type,i,o,!1,!1)),n},n._reglType="texture2d",n._texture=a,l.profile&&(n.stats=a.stats),n.destroy=function(){a.decRef()},n},createCube:function(e,r,n,a,i,s){function f(t,e,r,n,a,i){var o,s=h.texInfo;for(L.call(s),o=0;6>o;++o)v[o]=C();if("number"!=typeof t&&t){if("object"==typeof t)if(e)k(v[0],t),k(v[1],e),k(v[2],r),k(v[3],n),k(v[4],a),k(v[5],i);else if(O(s,t),c(h,t),"faces"in t)for(t=t.faces,o=0;6>o;++o)u(v[o],h),k(v[o],t[o]);else for(o=0;6>o;++o)k(v[o],t)}else for(t=0|t||1,o=0;6>o;++o)T(v[o],t,t);for(u(h,v[0]),h.mipmask=s.genMipmaps?(v[0].width<<1)-1:v[0].mipmask,h.internalformat=v[0].internalformat,f.width=v[0].width,f.height=v[0].height,P(h),o=0;6>o;++o)E(v[o],34069+o);for(D(s,34067),I(),l.profile&&(h.stats.size=A(h.internalformat,h.type,f.width,f.height,s.genMipmaps,!0)),f.format=K[h.internalformat],f.type=tt[h.type],f.mag=et[s.magFilter],f.min=rt[s.minFilter],f.wrapS=nt[s.wrapS],f.wrapT=nt[s.wrapT],o=0;6>o;++o)S(v[o]);return f}var h=new R(34067);ft[h.id]=h,o.cubeCount++;var v=Array(6);return f(e,r,n,a,i,s),f.subimage=function(t,e,r,n,a){r|=0,n|=0,a|=0;var i=g();return u(i,h),i.width=0,i.height=0,d(i,e),i.width=i.width||(h.width>>a)-r,i.height=i.height||(h.height>>a)-n,P(h),p(i,34069+t,r,n,a),I(),M(i),f},f.resize=function(e){if((e|=0)!==h.width){f.width=h.width=e,f.height=h.height=e,P(h);for(var r=0;6>r;++r)for(var n=0;h.mipmask>>n;++n)t.texImage2D(34069+r,n,h.format,e>>n,e>>n,0,h.format,h.type,null);return I(),l.profile&&(h.stats.size=A(h.internalformat,h.type,f.width,f.height,!1,!0)),f}},f._reglType="textureCube",f._texture=h,l.profile&&(f.stats=h.stats),f.destroy=function(){h.decRef()},f},clear:function(){for(var e=0;er;++r)if(0!=(e.mipmask&1<>r,e.height>>r,0,e.internalformat,e.type,null);else for(var n=0;6>n;++n)t.texImage2D(34069+n,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);D(e.texInfo,e.target)})}}}function T(t,e,r,n,a,i){function o(t,e,r){this.target=t,this.texture=e,this.renderbuffer=r;var n=t=0;e?(t=e.width,n=e.height):r&&(t=r.width,n=r.height),this.width=t,this.height=n}function l(t){t&&(t.texture&&t.texture._texture.decRef(),t.renderbuffer&&t.renderbuffer._renderbuffer.decRef())}function s(t,e,r){t&&(t.texture?t.texture._texture.refCount+=1:t.renderbuffer._renderbuffer.refCount+=1)}function u(e,r){r&&(r.texture?t.framebufferTexture2D(36160,e,r.target,r.texture._texture.texture,0):t.framebufferRenderbuffer(36160,e,36161,r.renderbuffer._renderbuffer.renderbuffer))}function c(t){var e=3553,r=null,n=null,a=t;return"object"==typeof t&&(a=t.data,"target"in t&&(e=0|t.target)),"texture2d"===(t=a._reglType)?r=a:"textureCube"===t?r=a:"renderbuffer"===t&&(n=a,e=36161),new o(e,r,n)}function f(t,e,r,i,l){return r?((t=n.create2D({width:t,height:e,format:i,type:l}))._texture.refCount=0,new o(3553,t,null)):((t=a.create({width:t,height:e,format:i}))._renderbuffer.refCount=0,new o(36161,null,t))}function h(t){return t&&(t.texture||t.renderbuffer)}function d(t,e,r){t&&(t.texture?t.texture.resize(e,r):t.renderbuffer&&t.renderbuffer.resize(e,r))}function p(){this.id=A++,M[this.id]=this,this.framebuffer=t.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function g(t){t.colorAttachments.forEach(l),l(t.depthAttachment),l(t.stencilAttachment),l(t.depthStencilAttachment)}function v(e){t.deleteFramebuffer(e.framebuffer),e.framebuffer=null,i.framebufferCount--,delete M[e.id]}function m(e){var n;t.bindFramebuffer(36160,e.framebuffer);var a=e.colorAttachments;for(n=0;na;++a){for(u=0;ut;++t)r[t].resize(n);return e.width=e.height=n,e},_reglType:"framebufferCube",destroy:function(){r.forEach(function(t){t.destroy()})}})},clear:function(){X(M).forEach(v)},restore:function(){X(M).forEach(function(e){e.framebuffer=t.createFramebuffer(),m(e)})}})}function k(){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 E(t,e,r,n){function a(t,e,r,n){this.name=t,this.id=e,this.location=r,this.info=n}function i(t,e){for(var r=0;rt&&(t=e.stats.uniformsCount)}),t},r.getMaxAttributesCount=function(){var t=0;return h.forEach(function(e){e.stats.attributesCount>t&&(t=e.stats.attributesCount)}),t}),{clear:function(){var e=t.deleteShader.bind(t);X(u).forEach(e),u={},X(c).forEach(e),c={},h.forEach(function(e){t.deleteProgram(e.program)}),h.length=0,f={},r.shaderCount=0},program:function(t,e,n){var a=f[e];a||(a=f[e]={});var i=a[t];return i||(i=new l(e,t),r.shaderCount++,s(i),a[t]=i,h.push(i)),i},restore:function(){u={},c={};for(var t=0;t="+e+"?"+a+".constant["+e+"]:0;"}).join(""),"}}else{","if(",o,"(",a,".buffer)){",c,"=",l,".createStream(",34962,",",a,".buffer);","}else{",c,"=",l,".getBuffer(",a,".buffer);","}",f,'="type" in ',a,"?",i.glTypes,"[",a,".type]:",c,".dtype;",s.normalized,"=!!",a,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",s.isStream,"){",l,".destroyStream(",c,");","}"),s})}),o}function T(t,e,r,n,a){var i=_(t),l=function(t,e,r){function n(t){if(t in a){var r=a[t];t=!0;var n,o,l=0|r.x,s=0|r.y;return"width"in r?n=0|r.width:t=!1,"height"in r?o=0|r.height:t=!1,new P(!t&&e&&e.thisDep,!t&&e&&e.contextDep,!t&&e&&e.propDep,function(t,e){var a=t.shared.context,i=n;"width"in r||(i=e.def(a,".","framebufferWidth","-",l));var u=o;return"height"in r||(u=e.def(a,".","framebufferHeight","-",s)),[l,s,i,u]})}if(t in i){var u=i[t];return t=F(u,function(t,e){var r=t.invoke(e,u),n=t.shared.context,a=e.def(r,".x|0"),i=e.def(r,".y|0");return[a,i,e.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",a,")"),r=e.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",i,")")]}),e&&(t.thisDep=t.thisDep||e.thisDep,t.contextDep=t.contextDep||e.contextDep,t.propDep=t.propDep||e.propDep),t}return e?new P(e.thisDep,e.contextDep,e.propDep,function(t,e){var r=t.shared.context;return[0,0,e.def(r,".","framebufferWidth"),e.def(r,".","framebufferHeight")]}):null}var a=t.static,i=t.dynamic;if(t=n("viewport")){var o=t;t=new P(t.thisDep,t.contextDep,t.propDep,function(t,e){var r=o.append(t,e),n=t.shared.context;return e.set(n,".viewportWidth",r[2]),e.set(n,".viewportHeight",r[3]),r})}return{viewport:t,scissor_box:n("scissor.box")}}(t,i),s=A(t),u=function(t,e){var r=t.static,n=t.dynamic,a={};return nt.forEach(function(t){function e(e,o){if(t in r){var l=e(r[t]);a[i]=B(function(){return l})}else if(t in n){var s=n[t];a[i]=F(s,function(t,e){return o(t,e,t.invoke(e,s))})}}var i=v(t);switch(t){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return e(function(t){return t},function(t,e,r){return r});case"depth.func":return e(function(t){return yt[t]},function(t,e,r){return e.def(t.constants.compareFuncs,"[",r,"]")});case"depth.range":return e(function(t){return t},function(t,e,r){return[e.def("+",r,"[0]"),e=e.def("+",r,"[1]")]});case"blend.func":return e(function(t){return[mt["srcRGB"in t?t.srcRGB:t.src],mt["dstRGB"in t?t.dstRGB:t.dst],mt["srcAlpha"in t?t.srcAlpha:t.src],mt["dstAlpha"in t?t.dstAlpha:t.dst]]},function(t,e,r){function n(t,n){return e.def('"',t,n,'" in ',r,"?",r,".",t,n,":",r,".",t)}t=t.constants.blendFuncs;var a=n("src","RGB"),i=n("dst","RGB"),o=(a=e.def(t,"[",a,"]"),e.def(t,"[",n("src","Alpha"),"]"));return[a,i=e.def(t,"[",i,"]"),o,t=e.def(t,"[",n("dst","Alpha"),"]")]});case"blend.equation":return e(function(t){return"string"==typeof t?[J[t],J[t]]:"object"==typeof t?[J[t.rgb],J[t.alpha]]:void 0},function(t,e,r){var n=t.constants.blendEquations,a=e.def(),i=e.def();return(t=t.cond("typeof ",r,'==="string"')).then(a,"=",i,"=",n,"[",r,"];"),t.else(a,"=",n,"[",r,".rgb];",i,"=",n,"[",r,".alpha];"),e(t),[a,i]});case"blend.color":return e(function(t){return o(4,function(e){return+t[e]})},function(t,e,r){return o(4,function(t){return e.def("+",r,"[",t,"]")})});case"stencil.mask":return e(function(t){return 0|t},function(t,e,r){return e.def(r,"|0")});case"stencil.func":return e(function(t){return[yt[t.cmp||"keep"],t.ref||0,"mask"in t?t.mask:-1]},function(t,e,r){return[t=e.def('"cmp" in ',r,"?",t.constants.compareFuncs,"[",r,".cmp]",":",7680),e.def(r,".ref|0"),e=e.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return e(function(e){return["stencil.opBack"===t?1029:1028,xt[e.fail||"keep"],xt[e.zfail||"keep"],xt[e.zpass||"keep"]]},function(e,r,n){function a(t){return r.def('"',t,'" in ',n,"?",i,"[",n,".",t,"]:",7680)}var i=e.constants.stencilOps;return["stencil.opBack"===t?1029:1028,a("fail"),a("zfail"),a("zpass")]});case"polygonOffset.offset":return e(function(t){return[0|t.factor,0|t.units]},function(t,e,r){return[e.def(r,".factor|0"),e=e.def(r,".units|0")]});case"cull.face":return e(function(t){var e=0;return"front"===t?e=1028:"back"===t&&(e=1029),e},function(t,e,r){return e.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return e(function(t){return t},function(t,e,r){return r});case"frontFace":return e(function(t){return bt[t]},function(t,e,r){return e.def(r+'==="cw"?2304:2305')});case"colorMask":return e(function(t){return t.map(function(t){return!!t})},function(t,e,r){return o(4,function(t){return"!!"+r+"["+t+"]"})});case"sample.coverage":return e(function(t){return["value"in t?t.value:1,!!t.invert]},function(t,e,r){return[e.def('"value" in ',r,"?+",r,".value:1"),e=e.def("!!",r,".invert")]})}}),a}(t),c=w(t),f=l.viewport;return f&&(u.viewport=f),(l=l[f=v("scissor.box")])&&(u[f]=l),(i={framebuffer:i,draw:s,shader:c,state:u,dirty:l=0>1)",l],");")}function e(){r(s,".drawArraysInstancedANGLE(",[p,g,v,l],");")}d?y?t():(r("if(",d,"){"),t(),r("}else{"),e(),r("}")):e()}function o(){function t(){r(c+".drawElements("+[p,v,m,g+"<<(("+m+"-5121)>>1)"]+");")}function e(){r(c+".drawArrays("+[p,g,v]+");")}d?y?t():(r("if(",d,"){"),t(),r("}else{"),e(),r("}")):e()}var l,s,u=t.shared,c=u.gl,f=u.draw,h=n.draw,d=function(){var a=h.elements,i=e;return a?((a.contextDep&&n.contextDynamic||a.propDep)&&(i=r),a=a.append(t,i)):a=i.def(f,".","elements"),a&&i("if("+a+")"+c+".bindBuffer(34963,"+a+".buffer.buffer);"),a}(),p=a("primitive"),g=a("offset"),v=function(){var a=h.count,i=e;return a?((a.contextDep&&n.contextDynamic||a.propDep)&&(i=r),a=a.append(t,i)):a=i.def(f,".","count"),a}();if("number"==typeof v){if(0===v)return}else r("if(",v,"){"),r.exit("}");$&&(l=a("instances"),s=t.instancing);var m=d+".type",y=h.elements&&I(h.elements);$&&("number"!=typeof l||0<=l)?"string"==typeof l?(r("if(",l,">0){"),i(),r("}else if(",l,"<0){"),o(),r("}")):i():o()}function H(t,e,r,n,a){return a=(e=b()).proc("body",a),$&&(e.instancing=a.def(e.shared.extensions,".angle_instanced_arrays")),t(e,a,r,n),e.compile().body}function q(t,e,r,n){L(t,e),N(t,e,r,n.attributes,function(){return!0}),j(t,e,r,n.uniforms,function(){return!0}),U(t,e,e,r)}function G(t,e,r,n){function a(){return!0}t.batchId="a1",L(t,e),N(t,e,r,n.attributes,a),j(t,e,r,n.uniforms,a),U(t,e,e,r)}function X(t,e,r,n){function a(t){return t.contextDep&&o||t.propDep}function i(t){return!a(t)}L(t,e);var o=r.contextDep,l=e.def(),s=e.def();t.shared.props=s,t.batchId=l;var u=t.scope(),c=t.scope();e(u.entry,"for(",l,"=0;",l,"<","a1",";++",l,"){",s,"=","a0","[",l,"];",c,"}",u.exit),r.needsContext&&k(t,c,r.context),r.needsFramebuffer&&E(t,c,r.framebuffer),S(t,c,r.state,a),r.profile&&a(r.profile)&&z(t,c,r,!1,!0),n?(N(t,u,r,n.attributes,i),N(t,c,r,n.attributes,a),j(t,u,r,n.uniforms,i),j(t,c,r,n.uniforms,a),U(t,u,c,r)):(e=t.global.def("{}"),n=r.shader.progVar.append(t,c),s=c.def(n,".id"),u=c.def(e,"[",s,"]"),c(t.shared.gl,".useProgram(",n,".program);","if(!",u,"){",u,"=",e,"[",s,"]=",t.link(function(e){return H(G,t,r,e,2)}),"(",n,");}",u,".call(this,a0[",l,"],",l,");"))}function Y(t,r){function n(e){var n=r.shader[e];n&&a.set(i.shader,"."+e,n.append(t,a))}var a=t.proc("scope",3);t.batchId="a2";var i=t.shared,o=i.current;k(t,a,r.context),r.framebuffer&&r.framebuffer.append(t,a),R(Object.keys(r.state)).forEach(function(e){var n=r.state[e].append(t,a);m(n)?n.forEach(function(r,n){a.set(t.next[e],"["+n+"]",r)}):a.set(i.next,"."+e,n)}),z(t,a,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(e){var n=r.draw[e];n&&a.set(i.draw,"."+e,""+n.append(t,a))}),Object.keys(r.uniforms).forEach(function(n){a.set(i.uniforms,"["+e.id(n)+"]",r.uniforms[n].append(t,a))}),Object.keys(r.attributes).forEach(function(e){var n=r.attributes[e].append(t,a),i=t.scopeAttrib(e);Object.keys(new Z).forEach(function(t){a.set(i,"."+t,n[t])})}),n("vert"),n("frag"),0=--this.refCount&&o(this)},a.profile&&(n.getTotalRenderbufferSize=function(){var t=0;return Object.keys(c).forEach(function(e){t+=c[e].stats.size}),t}),{create:function(e,r){function o(e,r){var n=0,i=0,c=32854;if("object"==typeof e&&e?("shape"in e?(n=0|(i=e.shape)[0],i=0|i[1]):("radius"in e&&(n=i=0|e.radius),"width"in e&&(n=0|e.width),"height"in e&&(i=0|e.height)),"format"in e&&(c=l[e.format])):"number"==typeof e?(n=0|e,i="number"==typeof r?0|r:n):e||(n=i=1),n!==u.width||i!==u.height||c!==u.format)return o.width=u.width=n,o.height=u.height=i,u.format=c,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,c,n,i),a.profile&&(u.stats.size=ft[u.format]*u.width*u.height),o.format=s[u.format],o}var u=new i(t.createRenderbuffer());return c[u.id]=u,n.renderbufferCount++,o(e,r),o.resize=function(e,r){var n=0|e,i=0|r||n;return n===u.width&&i===u.height?o:(o.width=u.width=n,o.height=u.height=i,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,u.format,n,i),a.profile&&(u.stats.size=ft[u.format]*u.width*u.height),o)},o._reglType="renderbuffer",o._renderbuffer=u,a.profile&&(o.stats=u.stats),o.destroy=function(){u.decRef()},o},clear:function(){X(c).forEach(o)},restore:function(){X(c).forEach(function(e){e.renderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,e.renderbuffer),t.renderbufferStorage(36161,e.format,e.width,e.height)}),t.bindRenderbuffer(36161,null)}}},dt=[];dt[6408]=4;var pt=[];pt[5121]=1,pt[5126]=4,pt[36193]=2;var gt=["x","y","z","w"],vt="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),mt={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},yt={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},xt={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},bt={cw:2304,ccw:2305},_t=new P(!1,!1,!1,function(){});return function(t){function e(){if(0===W.length)w&&w.update(),$=null;else{$=H.next(e),f();for(var t=W.length-1;0<=t;--t){var r=W[t];r&&r(O,null,0)}v.flush(),w&&w.update()}}function r(){!$&&0=W.length&&n()}}}}function c(){var t=X.viewport,e=X.scissor_box;t[0]=t[1]=e[0]=e[1]=0,O.viewportWidth=O.framebufferWidth=O.drawingBufferWidth=t[2]=e[2]=v.drawingBufferWidth,O.viewportHeight=O.framebufferHeight=O.drawingBufferHeight=t[3]=e[3]=v.drawingBufferHeight}function f(){O.tick+=1,O.time=d(),c(),G.procs.poll()}function h(){c(),G.procs.refresh(),w&&w.update()}function d(){return(q()-A)/1e3}if(!(t=a(t)))return null;var v=t.gl,m=v.getContextAttributes();v.isContextLost();var y=function(t,e){function r(e){var r;e=e.toLowerCase();try{r=n[e]=t.getExtension(e)}catch(t){}return!!r}for(var n={},a=0;ae;++e)K(j({framebuffer:t.framebuffer.faces[e]},t),s);else K(t,s);else s(0,t)},prop:V.define.bind(null,1),context:V.define.bind(null,2),this:V.define.bind(null,3),draw:l({}),buffer:function(t){return R.create(t,34962,!1,!1)},elements:function(t){return P.create(t,!1)},texture:B.create2D,cube:B.createCube,renderbuffer:F.create,framebuffer:U.create,framebufferCube:U.createCube,attributes:m,frame:u,on:function(t,e){var r;switch(t){case"frame":return u(e);case"lost":r=Z;break;case"restore":r=J;break;case"destroy":r=Q}return r.push(e),{cancel:function(){for(var t=0;t=0;i--){var o=t[i];if(e>mT(n,o))return gT(n,a);if(e>o||i===t.length-1)return gT(o,n);a=n,n=o}}function bT(t,e){for(var r=0;r=e[r][0]&&t<=e[r][1])return!0;return!1}function _T(t){t.attr("x",-cT.bar.captureWidth/2).attr("width",cT.bar.captureWidth)}function wT(t){t.attr("visibility","visible").style("visibility","visible").attr("fill","yellow").attr("opacity",0)}function AT(t){if(!t.brush.filterSpecified)return"0,"+t.height;for(var e,r,n,a=MT(t.brush.filter.getConsolidated(),t.height),i=[0],o=a.length?a[0][0]:null,l=0;le){f=r;break}}if(a=u,isNaN(a)&&(a=isNaN(c)||isNaN(f)?isNaN(c)?f:c:e-s[c][1]t[1]+r||e=.9*t[1]+.1*t[0]?"n":e<=.9*t[0]+.1*t[1]?"s":"ns"}(d,e);p&&(i.interval=l[a],i.intervalPix=d,i.region=p)}}if(t.ordinal&&!i.region){var g=t.unitTickvals,v=t.unitToPaddedPx.invert(e);for(r=0;r=m[0]&&v<=m[1]){i.clickableOrdinalRange=m;break}}}return i}function ST(t){t.on("mousemove",function(t){if(n.event.preventDefault(),!t.parent.inBrushDrag){var e=CT(t,t.height-n.mouse(this)[1]-2*cT.verticalPadding),r="crosshair";e.clickableOrdinalRange?r="pointer":e.region&&(r=e.region+"-resize"),n.select(document.body).style("cursor",r)}}).on("mouseleave",function(t){t.parent.inBrushDrag||TT()}).call(n.behavior.drag().on("dragstart",function(t){n.event.sourceEvent.stopPropagation();var e=t.height-n.mouse(this)[1]-2*cT.verticalPadding,r=t.unitToPaddedPx.invert(e),a=t.brush,i=CT(t,e),o=i.interval,l=a.svgBrush;if(l.wasDragged=!1,l.grabbingBar="ns"===i.region,l.grabbingBar){var s=o.map(t.unitToPaddedPx);l.grabPoint=e-s[0]-cT.verticalPadding,l.barLength=s[1]-s[0]}l.clickableOrdinalRange=i.clickableOrdinalRange,l.stayingIntervals=t.multiselect&&a.filterSpecified?a.filter.getConsolidated():[],o&&(l.stayingIntervals=l.stayingIntervals.filter(function(t){return t[0]!==o[0]&&t[1]!==o[1]})),l.startExtent=i.region?o["s"===i.region?1:0]:r,t.parent.inBrushDrag=!0,l.brushStartCallback()}).on("drag",function(t){n.event.sourceEvent.stopPropagation();var e=t.height-n.mouse(this)[1]-2*cT.verticalPadding,r=t.brush.svgBrush;r.wasDragged=!0,r.grabbingBar?r.newExtent=[e-r.grabPoint,e+r.barLength-r.grabPoint].map(t.unitToPaddedPx.invert):r.newExtent=[r.startExtent,t.unitToPaddedPx.invert(e)].sort(dT);var a=Math.max(0,-r.newExtent[0]),i=Math.max(0,r.newExtent[1]-1);r.newExtent[0]+=a,r.newExtent[1]-=i,r.grabbingBar&&(r.newExtent[1]+=a,r.newExtent[0]-=i),t.brush.filterSpecified=!0,r.extent=r.stayingIntervals.concat([r.newExtent]),r.brushCallback(t),ET(this.parentNode)}).on("dragend",function(t){n.event.sourceEvent.stopPropagation();var e=t.brush,r=e.filter,a=e.svgBrush,i=a.grabbingBar;if(a.grabbingBar=!1,a.grabLocation=void 0,t.parent.inBrushDrag=!1,TT(),!a.wasDragged)return a.wasDragged=void 0,a.clickableOrdinalRange?e.filterSpecified&&t.multiselect?a.extent.push(a.clickableOrdinalRange):(a.extent=[a.clickableOrdinalRange],e.filterSpecified=!0):i?(a.extent=a.stayingIntervals,0===a.extent.length&&OT(e)):OT(e),a.brushCallback(t),ET(this.parentNode),void a.brushEndCallback(e.filterSpecified?r.getConsolidated():[]);var o=function(){r.set(r.getConsolidated())};if(t.ordinal){var l=t.unitTickvals;l[l.length-1]a.newExtent[0];a.extent=a.stayingIntervals.concat(s?[a.newExtent]:[]),a.extent.length||OT(e),a.brushCallback(t),s?ET(this.parentNode,o):(o(),ET(this.parentNode))}else o();a.brushEndCallback(e.filterSpecified?r.getConsolidated():[])}))}function LT(t,e){return t[0]-e[0]}function OT(t){t.filterSpecified=!1,t.svgBrush.extent=[[0,1]]}function DT(t){for(var e,r=t.slice(),n=[],a=r.shift();a;){for(e=a.slice();(a=r.shift())&&a[0]<=e[1];)e[1]=Math.max(e[1],a[1]);n.push(e)}return n}var RT={makeBrush:function(t,e,r,n,a,i){var o,l=function(){var t,e,r=[];return{set:function(n){r=n.map(function(t){return t.slice().sort(dT)}).sort(LT),t=DT(r),e=r.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0])},get:function(){return r.slice()},getConsolidated:function(){return t},getBounds:function(){return e}}}();return l.set(r),{filter:l,filterSpecified:e,svgBrush:{extent:[],brushStartCallback:n,brushCallback:(o=a,function(t){var e=t.brush,r=function(t){return t.svgBrush.extent.map(function(t){return t.slice()})}(e).slice();e.filter.set(r),o()}),brushEndCallback:i}}},ensureAxisBrush:function(t){var e=t.selectAll("."+cT.cn.axisBrush).data(hT,fT);e.enter().append("g").classed(cT.cn.axisBrush,!0),function(t){var e=t.selectAll(".background").data(hT);e.enter().append("rect").classed("background",!0).call(_T).call(wT).style("pointer-events","auto").attr("transform","translate(0 "+cT.verticalPadding+")"),e.call(ST).attr("height",function(t){return t.height-cT.verticalPadding});var r=t.selectAll(".highlight-shadow").data(hT);r.enter().append("line").classed("highlight-shadow",!0).attr("x",-cT.bar.width/2).attr("stroke-width",cT.bar.width+cT.bar.strokeWidth).attr("stroke",cT.bar.strokeColor).attr("opacity",cT.bar.strokeOpacity).attr("stroke-linecap","butt"),r.attr("y1",function(t){return t.height}).call(kT);var n=t.selectAll(".highlight").data(hT);n.enter().append("line").classed("highlight",!0).attr("x",-cT.bar.width/2).attr("stroke-width",cT.bar.width-cT.bar.strokeWidth).attr("stroke",cT.bar.fillColor).attr("opacity",cT.bar.fillOpacity).attr("stroke-linecap","butt"),n.attr("y1",function(t){return t.height}).call(kT)}(e)},cleanRanges:function(t,e){if(Array.isArray(t[0])?(t=t.map(function(t){return t.sort(dT)}),t=e.multiselect?DT(t.sort(LT)):[t[0]]):t=[t.sort(dT)],e.tickvals){var r=e.tickvals.slice().sort(dT);if(!(t=t.map(function(t){var e=[yT(r,t[0],[]),xT(r,t[1],[])];if(e[1]>e[0])return e}).filter(function(t){return t})).length)return}return t.length>1?t:t[0]}},PT=Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),IT=Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depth,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),BT=Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n fragColor = vec4(pf.rgb, 1.0);\n}\n"]),FT=Ns(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]),zT=1e-6,NT=1e-7,jT=2048,UT=64,VT=2,HT=4,qT=8,GT=UT/qT,XT=[119,119,119],YT=new Uint8Array(4),WT=new Uint8Array(4),ZT={shape:[256,1],format:"rgba",type:"uint8",mag:"nearest",min:"nearest"};function JT(t,e,r,n,a){var i=t._gl;i.enable(i.SCISSOR_TEST),i.scissor(e,r,n,a),t.clear({color:[0,0,0,0],depth:1})}function QT(t,e,r,n,a,i){var o=i.key;r.drawCompleted||(!function(t){t.read({x:0,y:0,width:1,height:1,data:YT})}(t),r.drawCompleted=!0),function l(s){var u;u=Math.min(n,a-s*n),i.offset=VT*s*n,i.count=VT*u,0===s&&(window.cancelAnimationFrame(r.currentRafs[o]),delete r.currentRafs[o],JT(t,i.scissorX,i.scissorY,i.scissorWidth,i.viewBoxSize[1])),r.clearOnly||(e(i),s*n+u>>8*e)%256/255}function KT(t,e,r){var n,a,i,o=[];for(a=0;a=UT-4?$T(o,UT-2-l):.5);return i}(i,a,o);!function(t,e,r){for(var n=0;n<16;n++)t["p"+n.toString(16)](KT(e,r,n))}(f,i,d),h=u.texture(oe.extendFlat({data:function(t,e,r){for(var n=[],a=0;a<256;a++){var i=t(a/255);n.push((e?XT:i).concat(r))}return n}(r.unitToColor,l,Math.round(255*(l?c:1)))},ZT))}var g=[0,1];var v=[];function m(t,e,n,a,i,o,l,s,u,c,f){var h,d,p,v,m=[t,e],y=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(h=0;h<2;h++)for(v=m[h],d=0;d<4;d++)for(p=0;p<16;p++)y[h][d][p]=p+16*d===v?1:0;var x=r.lines.canvasOverdrag,b=r.domain,_=r.canvasWidth,w=r.canvasHeight;return oe.extendFlat({key:l,resolution:[_,w],viewBoxPosition:[n+x,a],viewBoxSize:[i,o],i:t,ii:e,dim1A:y[0][0],dim1B:y[0][1],dim1C:y[0][2],dim1D:y[0][3],dim2A:y[1][0],dim2B:y[1][1],dim2C:y[1][2],dim2D:y[1][3],colorClamp:g,scissorX:(s===u?0:n+x)+(r.pad.l-x)+r.layoutWidth*b.x[0],scissorWidth:(s===c?_-n+x:i+.5)+(s===u?n+x:0),scissorY:a+r.pad.b+r.layoutHeight*b.y[0],scissorHeight:o,viewportX:r.pad.l-x+r.layoutWidth*b.x[0],viewportY:r.pad.b+r.layoutHeight*b.y[0],viewportWidth:_,viewportHeight:w},f)}return{setColorDomain:function(t){g[0]=t[0],g[1]=t[1]},render:function(t,e,n){var s,f,h,p=t.length,g=1/0,y=-1/0;for(s=0;sy&&(y=t[s].dim2.canvasX,h=s),t[s].dim1.canvasXa._length&&(x=x.slice(0,a._length));var b,_=a.tickvals;function w(t,e){return{val:t,text:b[e]}}function A(t,e){return t.val-e.val}if(Array.isArray(_)&&_.length){b=a.ticktext,Array.isArray(b)&&b.length?b.length>_.length?b=b.slice(0,_.length):_.length>b.length&&(_=_.slice(0,b.length)):b=_.map(n.format(a.tickformat));for(var M=1;M<_.length;M++)if(_[M]<_[M-1]){for(var T=_.map(w).sort(A),k=0;k<_.length;k++)_[k]=T[k].val,b[k]=T[k].text;break}}else _=void 0;return{key:g,label:a.label,tickFormat:a.tickformat,tickvals:_,ticktext:b,ordinal:!!_,multiselect:a.multiselect,xIndex:o,crossfilterDimensionIndex:o,visibleIndex:a._index,height:i,values:x,paddedUnitValues:x.map(d),unitTickvals:_&&_.map(d),xScale:s,x:s(o),canvasX:s(o)*l,unitToPaddedPx:c,domainScale:function(t,e,r,a,i){var o,l,s=ik(r);return a?n.scale.ordinal().domain(a.map((o=n.format(r.tickformat),l=i,l?function(t,e){var r=l[e];return null===r||void 0===r?o(t):r}:o))).range(a.map(function(r){var n=(r-s[0])/(s[1]-s[0]);return t-e+n*(2*e-t)})):n.scale.linear().domain(s).range([t-e,e])}(i,cT.verticalPadding,a,_,b),ordinalScale:function(t){if(t.tickvals){var e=ik(t);return n.scale.ordinal().domain(t.tickvals).range(t.tickvals.map(function(t){return(t-e[0])/(e[1]-e[0])}))}}(a),parent:f,model:r,brush:RT.makeBrush(t,m,y,function(){t.linePickActive(!1)},function(){var e=f;e.focusLayer&&e.focusLayer.render(e.panels,!0);var r=ok(e);!t.contextShown()&&r?(e.contextLayer&&e.contextLayer.render(e.panels,!0),t.contextShown(!0)):t.contextShown()&&!r&&(e.contextLayer&&e.contextLayer.render(e.panels,!0,!0),t.contextShown(!1))},function(r){var n=f;if(n.focusLayer.render(n.panels,!0),n.pickLayer&&n.pickLayer.render(n.panels,!0),t.linePickActive(!0),e&&e.filterChanged){var i=d.invert,o=r.map(function(t){return t.map(i).sort(oe.sorterAsc)}).sort(function(t,e){return t[0]-e[0]});e.filterChanged(n.key,a._index,o)}})}}),f}function uk(t){t.classed(cT.cn.axisExtentText,!0).attr("text-anchor","middle").style("cursor","default").style("user-select","none")}var ck=function(t,e){var r=t._fullLayout,a=r._toppaper,i=(r._paperdiv,r._glcontainer);aT(t);var o={},l={},s=r._size;e.forEach(function(e,r){o[r]=t.data[r].dimensions,l[r]=t.data[r].dimensions.slice()});!function(t,e,r,a,i,o){var l,s,u=(l=!0,s=!1,{linePickActive:function(t){return arguments.length?l=!!t:l},contextShown:function(t){return arguments.length?s=!!t:s}}),c=a.filter(function(t){return nk(t).trace.visible}).map(lk.bind(0,i)).map(sk.bind(0,u,o));r.each(function(t,e){return oe.extendFlat(t,c[e])});var f=r.selectAll(".gl-canvas").each(function(t){t.viewModel=c[0],t.model=t.viewModel?t.viewModel.model:null}),h=null;f.filter(function(t){return t.pick}).style("pointer-events","auto").on("mousemove",function(t){if(u.linePickActive()&&t.lineLayer&&o&&o.hover){var e=n.event,r=this.width,a=this.height,i=n.mouse(this),l=i[0],s=i[1];if(l<0||s<0||l>=r||s>=a)return;var c=t.lineLayer.readPixel(l,a-1-s),f=0!==c[3],d=f?c[2]+256*(c[1]+256*c[0]):null,p={x:l,y:s,clientX:e.clientX,clientY:e.clientY,dataIndex:t.model.key,curveNumber:d};d!==h&&(f?o.hover(p):o.unhover&&o.unhover(p),h=d)}}),f.style("opacity",function(t){return t.pick?.01:1}),e.style("background","rgba(255, 255, 255, 0)");var d=e.selectAll("."+cT.cn.parcoords).data(c,ek);d.exit().remove(),d.enter().append("g").classed(cT.cn.parcoords,!0).style("shape-rendering","crispEdges").style("pointer-events","none"),d.attr("transform",function(t){return"translate("+t.model.translateX+","+t.model.translateY+")"});var p=d.selectAll("."+cT.cn.parcoordsControlView).data(rk,ek);p.enter().append("g").classed(cT.cn.parcoordsControlView,!0),p.attr("transform",function(t){return"translate("+t.model.pad.l+","+t.model.pad.t+")"});var g=p.selectAll("."+cT.cn.yAxis).data(function(t){return t.dimensions},ek);function v(t,e){for(var r=e.panels||(e.panels=[]),n=t.data(),a=n.length-1,i=0;iline").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.25).attr("stroke-width","1px"),y.selectAll("text").style("text-shadow","1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff").style("cursor","default").style("user-select","none");var x=m.selectAll("."+cT.cn.axisHeading).data(rk,ek);x.enter().append("g").classed(cT.cn.axisHeading,!0);var b=x.selectAll("."+cT.cn.axisTitle).data(rk,ek);b.enter().append("text").classed(cT.cn.axisTitle,!0).attr("text-anchor","middle").style("cursor","ew-resize").style("user-select","none").style("pointer-events","auto"),b.attr("transform","translate(0,"+-cT.axisTitleOffset+")").text(function(t){return t.label}).each(function(t){Jr.font(n.select(this),t.model.labelFont)});var _=m.selectAll("."+cT.cn.axisExtent).data(rk,ek);_.enter().append("g").classed(cT.cn.axisExtent,!0);var w=_.selectAll("."+cT.cn.axisExtentTop).data(rk,ek);w.enter().append("g").classed(cT.cn.axisExtentTop,!0),w.attr("transform","translate(0,"+-cT.axisExtentOffset+")");var A=w.selectAll("."+cT.cn.axisExtentTopText).data(rk,ek);function M(t,e){if(t.ordinal)return"";var r=t.domainScale.domain();return n.format(t.tickFormat)(r[e?r.length-1:0])}A.enter().append("text").classed(cT.cn.axisExtentTopText,!0).call(uk),A.text(function(t){return M(t,!0)}).each(function(t){Jr.font(n.select(this),t.model.rangeFont)});var T=_.selectAll("."+cT.cn.axisExtentBottom).data(rk,ek);T.enter().append("g").classed(cT.cn.axisExtentBottom,!0),T.attr("transform",function(t){return"translate(0,"+(t.model.height+cT.axisExtentOffset)+")"});var k=T.selectAll("."+cT.cn.axisExtentBottomText).data(rk,ek);k.enter().append("text").classed(cT.cn.axisExtentBottomText,!0).attr("dy","0.75em").call(uk),k.text(function(t){return M(t)}).each(function(t){Jr.font(n.select(this),t.model.rangeFont)}),RT.ensureAxisBrush(m)}(0,a,i,e,{width:s.w,height:s.h,margin:{t:s.t,r:s.r,b:s.b,l:s.l}},{filterChanged:function(e,r,n){var a=l[e][r],i=n.map(function(t){return t.slice()});i.length?(1===i.length&&(i=i[0]),a.constraintrange=i,i=[i]):(delete a.constraintrange,i=null);var o={};o["dimensions["+r+"].constraintrange"]=i,t.emit("plotly_restyle",[o,[e]])},hover:function(e){t.emit("plotly_hover",e)},unhover:function(e){t.emit("plotly_unhover",e)},axesMoved:function(e,r){function n(t){return!("visible"in t)||t.visible}function a(t,e,r){var n=e.indexOf(r),a=t.indexOf(n);return-1===a&&(a+=e.length),a}var i=function(t){return function(e,n){return a(r,t,e)-a(r,t,n)}}(l[e].filter(n));o[e].sort(i),l[e].filter(function(t){return!n(t)}).sort(function(t){return l[e].indexOf(t)}).forEach(function(t){o[e].splice(o[e].indexOf(t),1),o[e].splice(l[e].indexOf(t),0,t)}),t.emit("plotly_restyle")}})},fk={},hk=$o.getModuleCalcData;fk.name="parcoords",fk.plot=function(t){var e=hk(t.calcdata,"parcoords")[0];e.length&&ck(t,e)},fk.clean=function(t,e,r,n){var a=n._has&&n._has("parcoords"),i=e._has&&e._has("parcoords");a&&!i&&(n._paperdiv.selectAll(".parcoords").remove(),n._glimages.selectAll("*").remove())},fk.toSVG=function(t){var e=t._fullLayout._glimages,r=n.select(t).selectAll(".svg-container");r.filter(function(t,e){return e===r.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");e.append("svg:image").attr({xmlns:Ce.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})}),window.setTimeout(function(){n.selectAll("#filterBarPattern").attr("id","filterBarPattern")},60)};var dk=sT;var pk=cT.maxDimensionCount,gk=Qx.defaults;var vk={};vk.attributes=rT,vk.supplyDefaults=function(t,e,r,n){function a(r,n){return oe.coerce(t,e,rT,r,n)}var i=function(t,e){var r,n,a,i=t.dimensions||[],o=e.dimensions=[],l=1/0;function s(t,e){return oe.coerce(r,n,rT.dimensions,t,e)}for(i.length>pk&&(oe.log("parcoords traces support up to "+pk+" dimensions at the moment"),i.splice(pk)),a=0;a 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]),xk.pickVertex=Ns(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]),xk.pickFragment=Ns(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]);var bk=function(t,e){var r=t.gl,n=zs(r),a=zs(r),i=Zu(r,xk.pointVertex,xk.pointFragment),o=Zu(r,xk.pickVertex,xk.pickFragment),l=new _k(t,n,a,i,o);return l.update(e),t.addObject(l),l};function _k(t,e,r,n,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.shader=n,this.pickShader=a,this.sizeMin=.5,this.sizeMinCap=2,this.sizeMax=20,this.areaRatio=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.blend=!1,this.pickOffset=0,this.points=null}var wk=_k.prototype;wk.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.plot.removeObject(this)},wk.update=function(t){var e;function r(e,r){return e in t?t[e]:r}t=t||{},this.sizeMin=r("sizeMin",.5),this.sizeMax=r("sizeMax",20),this.color=r("color",[1,0,0,1]).slice(),this.areaRatio=r("areaRatio",1),this.borderColor=r("borderColor",[0,0,0,1]).slice(),this.blend=r("blend",!1);var n=t.positions.length>>>1,a=t.positions instanceof Float32Array,i=t.idToIndex instanceof Int32Array&&t.idToIndex.length>=n,o=t.positions,l=a?o:Ds.mallocFloat32(o.length),s=i?t.idToIndex:Ds.mallocInt32(n);if(a||l.set(o),!i)for(l.set(o),e=0;e>>1;for(r=0;r=e[0]&&i<=e[2]&&o>=e[1]&&o<=e[3]&&n++}return n}(this.points,o),c=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(u,.33333)));t[0]=2/l,t[4]=2/s,t[6]=-2*o[0]/l-1,t[7]=-2*o[1]/s-1,this.offsetBuffer.bind(),a.bind(),a.attributes.position.pointer(),a.uniforms.matrix=t,a.uniforms.color=this.color,a.uniforms.borderColor=this.borderColor,a.uniforms.pointCloud=c<5,a.uniforms.pointSize=c,a.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio))),n&&(e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,this.pickBuffer.bind(),a.attributes.pickId.pointer(i.UNSIGNED_BYTE),a.uniforms.pickOffset=e,this.pickOffset=r);var f=i.getParameter(i.BLEND),h=i.getParameter(i.DITHER);return f&&!this.blend&&i.disable(i.BLEND),h&&i.disable(i.DITHER),i.drawArrays(i.POINTS,0,this.pointCount),f&&!this.blend&&i.enable(i.BLEND),h&&i.enable(i.DITHER),r+this.pointCount}}(),wk.draw=wk.unifiedDraw,wk.drawPick=wk.unifiedDraw,wk.pick=function(t,e,r){var n=this.pickOffset,a=this.pointCount;if(r=n+a)return null;var i=r-n,o=this.points;return{object:this,pointId:i,dataCoord:[o[2*i],o[2*i+1]]}};var Ak=Aa;function Mk(t,e){this.scene=t,this.uid=e,this.type="pointcloud",this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=new Int32Array(0),this.bounds=[0,0,0,0],this.pointcloudOptions={positions:new Float32Array(0),idToIndex:this.idToIndex,sizemin:.5,sizemax:12,color:[0,0,0,1],areaRatio:1,borderColor:[0,0,0,1]},this.pointcloud=bk(t.glplot,this.pointcloudOptions),this.pointcloud._trace=this}var Tk=Mk.prototype;Tk.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:this.pickXYData?[this.pickXYData[2*e],this.pickXYData[2*e+1]]:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:this.color,name:this.name,pointIndex:e,hoverinfo:this.hoverinfo}},Tk.update=function(t){this.index=t.index,this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-1/0,-1/0],this.updateFast(t),this.color=_M(t,{})},Tk.updateFast=function(t){var e,r,n,a,i,o,l=this.xData=this.pickXData=t.x,s=this.yData=this.pickYData=t.y,u=this.pickXYData=t.xy,c=t.xbounds&&t.ybounds,f=t.indices,h=this.bounds;if(u){if(n=u,e=u.length>>>1,c)h[0]=t.xbounds[0],h[2]=t.xbounds[1],h[1]=t.ybounds[0],h[3]=t.ybounds[1];else for(o=0;oh[2]&&(h[2]=a),ih[3]&&(h[3]=i);if(f)r=f;else for(r=new Int32Array(e),o=0;oh[2]&&(h[2]=a),ih[3]&&(h[3]=i);this.idToIndex=r,this.pointcloudOptions.idToIndex=r,this.pointcloudOptions.positions=n;var d=vm(t.marker.color),p=vm(t.marker.border.color),g=t.opacity*t.marker.opacity;d[3]*=g,this.pointcloudOptions.color=d;var v=t.marker.blend;if(null===v){v=l.length<100||s.length<100}this.pointcloudOptions.blend=v,p[3]*=g,this.pointcloudOptions.borderColor=p;var m=t.marker.sizemin,y=Math.max(t.marker.sizemax,t.marker.sizemin);this.pointcloudOptions.sizeMin=m,this.pointcloudOptions.sizeMax=y,this.pointcloudOptions.areaRatio=t.marker.border.arearatio,this.pointcloud.update(this.pointcloudOptions),this.expandAxesFast(h,y/2)},Tk.expandAxesFast=function(t,e){var r=e||.5;Ak(this.scene.xaxis,[t[0],t[2]],{ppad:r}),Ak(this.scene.yaxis,[t[1],t[3]],{ppad:r})},Tk.dispose=function(){this.pointcloud.dispose()};var kk=function(t,e){var r=new Mk(t,e.uid);return r.update(e),r},Ek={};Ek.attributes=yk,Ek.supplyDefaults=function(t,e,r){function n(r,n){return oe.coerce(t,e,yk,r,n)}n("x"),n("y"),n("xbounds"),n("ybounds"),t.xy&&t.xy instanceof Float32Array&&(e.xy=t.xy),t.indices&&t.indices instanceof Int32Array&&(e.indices=t.indices),n("text"),n("marker.color",r),n("marker.opacity"),n("marker.blend"),n("marker.sizemin"),n("marker.sizemax"),n("marker.border.color",r),n("marker.border.arearatio")},Ek.calc=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return tM(r,e),rM(e),r},Ek.plot=kk,Ek.moduleType="trace",Ek.name="pointcloud",Ek.basePlotModule=Om,Ek.categories=["gl","gl2d","showLegend"],Ek.meta={};var Ck=Ek,Sk=function(t,e){var r="number"==typeof t,n="number"==typeof e;r&&!n?(e=t,t=0):r||n||(t=0,e=0);var a=(e|=0)-(t|=0);if(a<0)throw new Error("array length must be positive");for(var i=new Array(a),o=0,l=t;oa&&(a=t[o]),t[o]1&&(t=arguments);"string"==typeof t?t=t.split(/\s/).map(parseFloat):"number"==typeof t&&(t=[t]);t.length&&"number"==typeof t[0]?e=1===t.length?{width:t[0],height:t[0],x:0,y:0}:2===t.length?{width:t[0],height:t[1],x:0,y:0}:{x:t[0],y:t[1],width:t[2]-t[0]||0,height:t[3]-t[1]||0}:t&&(t=Pk(t,{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"}),e={x:t.left||0,y:t.top||0},null==t.width?t.right?e.width=t.right-e.x:e.width=0:e.width=t.width,null==t.height?t.bottom?e.height=t.bottom-e.y:e.height=0:e.height=t.height);return e};function zk(t,e,r,n,a){var i=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return a?e.indexOf("c")<0?i.push(";if(x===y){return m}else if(x<=y){"):i.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):i.push(";if(",e,"){i=m;"),r?i.push("l=m+1}else{h=m-1}"):i.push("h=m-1}else{l=m+1}"),i.push("}"),a?i.push("return -1};"):i.push("return i};"),i.join("")}function Nk(t,e,r,n){return new Function([zk("A","x"+t+"y",e,["y"],n),zk("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var jk={ge:Nk(">=",!1,"GE"),gt:Nk(">",!1,"GT"),lt:Nk("<",!0,"LT"),le:Nk("<=",!0,"LE"),eq:Nk("-",!0,"EQ",!0)};function Uk(t,e){for(var r=e[0],n=e[1],a=1/(e[2]-r),i=1/(e[3]-n),o=new Array(t.length),l=0,s=t.length/2;l>>1;e.dtype||(e.dtype="array"),"string"==typeof e.dtype?a=new(pm(e.dtype))(o):e.dtype&&(a=e.dtype,Array.isArray(a)&&(a.length=o));for(var l=0;lr){for(var v=0;vc||b>f||_=A||o===l)){var h=s[i];void 0===l&&(l=h.length);for(var m=o;m=d&&T<=g&&k>=p&&k<=v&&M.push(y)}var E=u[i],C=E[4*o+0],S=E[4*o+1],L=E[4*o+2],O=E[4*o+3],D=function(t,e){for(var r=null,n=0;null===r;)if(r=t[4*e+n],++n>t.length)return null;return r}(E,o+1),R=.5*a,P=i+1;e(r,n,R,P,C,S||L||O||D),e(r,n+R,R,P,S,L||O||D),e(r+R,n,R,P,L,O||D),e(r+R,n+R,R,P,O,D)}}}(0,0,1,0,0,1),M},a;function y(t,e,r){for(var n=1,a=.5,i=.5,o=.5,l=0;l1&&(t.scaleRatio=[t.scale[0]*t.viewport.width,t.scale[1]*t.viewport.height],r(t),t.after&&t.after(t))}function p(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0,r=0;if(c=t.map(function(t,n){var a=c[n];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=Pk(t,{color:"color colors fill",capSize:"capSize cap capsize cap-size",lineWidth:"lineWidth line-width width line thickness",opacity:"opacity alpha",range:"range dataBox",viewport:"viewport viewBox",errors:"errors error",positions:"positions position data points"}),a||(c[n]=a={id:n,scale:null,translate:null,scaleFract:null,translateFract:null,draw:!0},t=Xk({},u,t)),Zk(a,t,[{lineWidth:function(t){return.5*+t},capSize:function(t){return.5*+t},opacity:parseFloat,errors:function(t){return t=Ok(t),r+=t.length,t},positions:function(t,r){return t=Ok(t,"float64"),r.count=Math.floor(t.length/2),r.bounds=Lk(t,2),r.offset=e,e+=r.count,t}},{color:function(t,e){var r=e.count;if(t||(t="transparent"),!Array.isArray(t)||"number"==typeof t[0]){var n=t;t=Array(r);for(var a=0;a80*r){n=i=t[0],a=o=t[1];for(var p=r;pi&&(i=l),s>o&&(o=s);u=0!==(u=Math.max(i-n,o-a))?1/u:0}return iE(h,d,r,n,a,u),d}function nE(t,e,r,n,a){var i,o;if(a===ME(t,e,r,n)>0)for(i=e;i=e;i-=n)o=_E(i,t[i],t[i+1],o);return o&&mE(o,o.next)&&(wE(o),o=o.next),o}function aE(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!mE(n,n.next)&&0!==vE(n.prev,n,n.next))n=n.next;else{if(wE(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function iE(t,e,r,n,a,i,o){if(t){!o&&i&&function(t,e,r,n){var a=t;do{null===a.z&&(a.z=hE(a.x,a.y,e,r,n)),a.prevZ=a.prev,a.nextZ=a.next,a=a.next}while(a!==t);a.prevZ.nextZ=null,a.prevZ=null,function(t){var e,r,n,a,i,o,l,s,u=1;do{for(r=t,t=null,i=null,o=0;r;){for(o++,n=r,l=0,e=0;e0||s>0&&n;)0!==l&&(0===s||!n||r.z<=n.z)?(a=r,r=r.nextZ,l--):(a=n,n=n.nextZ,s--),i?i.nextZ=a:t=a,a.prevZ=i,i=a;r=n}i.nextZ=null,u*=2}while(o>1)}(a)}(t,n,a,i);for(var l,s,u=t;t.prev!==t.next;)if(l=t.prev,s=t.next,i?lE(t,n,a,i):oE(t))e.push(l.i/r),e.push(t.i/r),e.push(s.i/r),wE(t),t=s.next,u=s.next;else if((t=s)===u){o?1===o?iE(t=sE(t,e,r),e,r,n,a,i,2):2===o&&uE(t,e,r,n,a,i):iE(aE(t),e,r,n,a,i,1);break}}}function oE(t){var e=t.prev,r=t,n=t.next;if(vE(e,r,n)>=0)return!1;for(var a=t.next.next;a!==t.prev;){if(pE(e.x,e.y,r.x,r.y,n.x,n.y,a.x,a.y)&&vE(a.prev,a,a.next)>=0)return!1;a=a.next}return!0}function lE(t,e,r,n){var a=t.prev,i=t,o=t.next;if(vE(a,i,o)>=0)return!1;for(var l=a.xi.x?a.x>o.x?a.x:o.x:i.x>o.x?i.x:o.x,c=a.y>i.y?a.y>o.y?a.y:o.y:i.y>o.y?i.y:o.y,f=hE(l,s,e,r,n),h=hE(u,c,e,r,n),d=t.prevZ,p=t.nextZ;d&&d.z>=f&&p&&p.z<=h;){if(d!==t.prev&&d!==t.next&&pE(a.x,a.y,i.x,i.y,o.x,o.y,d.x,d.y)&&vE(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==t.prev&&p!==t.next&&pE(a.x,a.y,i.x,i.y,o.x,o.y,p.x,p.y)&&vE(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=f;){if(d!==t.prev&&d!==t.next&&pE(a.x,a.y,i.x,i.y,o.x,o.y,d.x,d.y)&&vE(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=h;){if(p!==t.prev&&p!==t.next&&pE(a.x,a.y,i.x,i.y,o.x,o.y,p.x,p.y)&&vE(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function sE(t,e,r){var n=t;do{var a=n.prev,i=n.next.next;!mE(a,i)&&yE(a,n,n.next,i)&&xE(a,i)&&xE(i,a)&&(e.push(a.i/r),e.push(n.i/r),e.push(i.i/r),wE(n),wE(n.next),n=t=i),n=n.next}while(n!==t);return n}function uE(t,e,r,n,a,i){var o=t;do{for(var l=o.next.next;l!==o.prev;){if(o.i!==l.i&&gE(o,l)){var s=bE(o,l);return o=aE(o,o.next),s=aE(s,s.next),iE(o,e,r,n,a,i),void iE(s,e,r,n,a,i)}l=l.next}o=o.next}while(o!==t)}function cE(t,e){return t.x-e.x}function fE(t,e){if(e=function(t,e){var r,n=e,a=t.x,i=t.y,o=-1/0;do{if(i<=n.y&&i>=n.next.y&&n.next.y!==n.y){var l=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(l<=a&&l>o){if(o=l,l===a){if(i===n.y)return n;if(i===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&a!==n.x&&pE(ir.x)&&xE(n,t)&&(r=n,h=s),n=n.next;return r}(t,e)){var r=bE(e,t);aE(r,r.next)}}function hE(t,e,r,n,a){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*a)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*a)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function dE(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-l)-(r-o)*(e-l)>=0&&(r-o)*(i-l)-(a-o)*(n-l)>=0}function gE(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&yE(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&xE(t,e)&&xE(e,t)&&function(t,e){var r=t,n=!1,a=(t.x+e.x)/2,i=(t.y+e.y)/2;do{r.y>i!=r.next.y>i&&r.next.y!==r.y&&a<(r.next.x-r.x)*(i-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function vE(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function mE(t,e){return t.x===e.x&&t.y===e.y}function yE(t,e,r,n){return!!(mE(t,e)&&mE(r,n)||mE(t,n)&&mE(r,e))||vE(t,e,r)>0!=vE(t,e,n)>0&&vE(r,n,t)>0!=vE(r,n,e)>0}function xE(t,e){return vE(t.prev,t,t.next)<0?vE(t,e,t.next)>=0&&vE(t,t.prev,e)>=0:vE(t,e,t.prev)<0||vE(t,t.next,e)<0}function bE(t,e){var r=new AE(t.i,t.x,t.y),n=new AE(e.i,e.x,e.y),a=t.next,i=e.prev;return t.next=e,e.prev=t,r.next=a,a.prev=r,n.next=r,r.prev=n,i.next=n,n.prev=i,n}function _E(t,e,r,n){var a=new AE(t,e,r);return n?(a.next=n.next,a.prev=n,n.next.prev=a,n.next=a):(a.prev=a,a.next=a),a}function wE(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function AE(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function ME(t,e,r,n){for(var a=0,i=e,o=r-n;i0&&(n+=t[a-1].length,r.holes.push(n))}return r};var TE,kE,EE,CE=function(){},SE=function(t){return void 0!==t&&null!==t},LE=Object.keys,OE=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}()?Object.keys:function(t){return LE(SE(t)?Object(t):t)},DE=function(t){if(!SE(t))throw new TypeError("Cannot use null or undefined");return t},RE=Math.max,PE="function"==typeof(kE=Object.assign)&&(kE(TE={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),TE.foo+TE.bar+TE.trzy==="razdwatrzy")?Object.assign:function(t,e){var r,n,a,i=RE(arguments.length,2);for(t=Object(DE(t)),a=function(n){try{t[n]=e[n]}catch(t){r||(r=t)}},n=1;n-1};(EE=function(t,e){var r,n,a,i,o;return arguments.length<2||"string"!=typeof t?(i=e,e=t,t=null):i=arguments[2],null==t?(r=a=!0,n=!1):(r=UE.call(t,"c"),n=UE.call(t,"e"),a=UE.call(t,"w")),o={value:e,configurable:r,enumerable:n,writable:a},i?PE(zE(i),o):o}).gs=function(t,e,r){var n,a,i,o;return"string"!=typeof t?(i=r,r=e,e=t,t=null):i=arguments[3],null==e?e=void 0:IE(e)?null==r?r=void 0:IE(r)||(i=r,r=void 0):(i=e,e=r=void 0),null==t?(n=!0,a=!1):(n=UE.call(t,"c"),a=UE.call(t,"e")),o={get:e,set:r,configurable:n,enumerable:a},i?PE(zE(i),o):o};var VE,HE,qE,GE,XE=Object.create,YE=Object.getPrototypeOf,WE={},ZE=function(){var t=Object.setPrototypeOf,e=arguments[0]||XE;return"function"==typeof t&&YE(t(e(null),WE))===WE},JE={function:!0,object:!0},QE=function(t){return SE(t)&&JE[typeof t]||!1},$E=ZE()?Object.setPrototypeOf:e({}),KE=function(t){if(!QE(t))throw new TypeError(t+" is not an Object");return t},tC=Object.create(null),eC=Math.random,rC=Object.prototype.toString,nC=rC.call(function(){return arguments}()),aC=function(t){return rC.call(t)===nC},iC=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t},oC=Object.prototype.toString,lC=oC.call(""),sC=function(t){return"string"==typeof t||t&&"object"==typeof t&&(t instanceof String||oC.call(t)===lC)||!1},uC=Object.prototype.toString,cC=uC.call(CE),fC=function(){var t=Math.sign;return"function"==typeof t&&1===t(10)&&-1===t(-20)}()?Math.sign:function(t){return t=Number(t),isNaN(t)||0===t?t:t>0?1:-1},hC=Math.abs,dC=Math.floor,pC=Math.max,gC=function(t){return pC(0,function(t){return isNaN(t)?0:0!==(t=Number(t))&&isFinite(t)?fC(t)*dC(hC(t)):t}(t))},vC={object:!0,symbol:!0},mC=function(t){if(!(e=t)||!("symbol"==typeof e||e.constructor&&"Symbol"===e.constructor.name&&"Symbol"===e[e.constructor.toStringTag]))throw new TypeError(t+" is not a symbol");var e;return t},yC=Object.create,xC=Object.defineProperties,bC=Object.defineProperty,_C=Object.prototype,wC=yC(null);if("function"==typeof Symbol){VE=Symbol;try{String(VE()),GE=!0}catch(t){}}var AC,MC=(AC=yC(null),function(t){for(var e,r,n=0;AC[t+(n||"")];)++n;return AC[t+=n||""]=!0,bC(_C,e="@@"+t,EE.gs(null,function(t){r||(r=!0,bC(this,e,EE(t)),r=!1)})),e});qE=function(t){if(this instanceof qE)throw new TypeError("Symbol is not a constructor");return HE(t)};var TC=HE=function t(e){var r;if(this instanceof t)throw new TypeError("Symbol is not a constructor");return GE?VE(e):(r=yC(qE.prototype),e=void 0===e?"":String(e),xC(r,{__description__:EE("",e),__name__:EE("",MC(e))}))};xC(HE,{for:EE(function(t){return wC[t]?wC[t]:wC[t]=HE(String(t))}),keyFor:EE(function(t){var e;for(e in mC(t),wC)if(wC[e]===t)return e}),hasInstance:EE("",VE&&VE.hasInstance||HE("hasInstance")),isConcatSpreadable:EE("",VE&&VE.isConcatSpreadable||HE("isConcatSpreadable")),iterator:EE("",VE&&VE.iterator||HE("iterator")),match:EE("",VE&&VE.match||HE("match")),replace:EE("",VE&&VE.replace||HE("replace")),search:EE("",VE&&VE.search||HE("search")),species:EE("",VE&&VE.species||HE("species")),split:EE("",VE&&VE.split||HE("split")),toPrimitive:EE("",VE&&VE.toPrimitive||HE("toPrimitive")),toStringTag:EE("",VE&&VE.toStringTag||HE("toStringTag")),unscopables:EE("",VE&&VE.unscopables||HE("unscopables"))}),xC(qE.prototype,{constructor:EE(HE),toString:EE("",function(){return this.__name__})}),xC(HE.prototype,{toString:EE(function(){return"Symbol ("+mC(this).__description__+")"}),valueOf:EE(function(){return mC(this)})}),bC(HE.prototype,HE.toPrimitive,EE("",function(){var t=mC(this);return"symbol"==typeof t?t:t.toString()})),bC(HE.prototype,HE.toStringTag,EE("c","Symbol")),bC(qE.prototype,HE.toStringTag,EE("c",HE.prototype[HE.toStringTag])),bC(qE.prototype,HE.toPrimitive,EE("c",HE.prototype[HE.toPrimitive]));var kC,EC,CC,SC=function(){var t;if("function"!=typeof Symbol)return!1;t=Symbol("test symbol");try{String(t)}catch(t){return!1}return!!vC[typeof Symbol.iterator]&&!!vC[typeof Symbol.toPrimitive]&&!!vC[typeof Symbol.toStringTag]}()?Symbol:TC,LC=SC.iterator,OC=Array.isArray,DC=Function.prototype.call,RC={configurable:!0,enumerable:!0,writable:!0,value:null},PC=Object.defineProperty,IC=function(){var t,e,r=Array.from;return"function"==typeof r&&(e=r(t=["raz","dwa"]),Boolean(e&&e!==t&&"dwa"===e[1]))}()?Array.from:function(t){var e,r,n,a,i,o,l,s,u,c,f=arguments[1],h=arguments[2];if(t=Object(DE(t)),SE(f)&&iC(f),this&&this!==Array&&function(t){return"function"==typeof t&&uC.call(t)===cC}(this))e=this;else{if(!f){if(aC(t))return 1!==(i=t.length)?Array.apply(null,t):((a=new Array(1))[0]=t[0],a);if(OC(t)){for(a=new Array(i=t.length),r=0;r=55296&&o<=56319&&(c+=t[++r]),c=f?DC.call(f,h,c,n):c,e?(RC.value=c,PC(a,n,RC)):a[n]=c,++n;i=n}if(void 0===i)for(i=gC(t.length),e&&(a=new e(i)),r=0;r=this.__nextIndex__||(++this.__nextIndex__,this.__redo__?(this.__redo__.forEach(function(e,r){e>=t&&(this.__redo__[r]=++e)},this),this.__redo__.push(t)):XC(this,"__redo__",EE("c",[t])))}),_onDelete:EE(function(t){var e;t>=this.__nextIndex__||(--this.__nextIndex__,this.__redo__&&(-1!==(e=this.__redo__.indexOf(t))&&this.__redo__.splice(e,1),this.__redo__.forEach(function(e,r){e>t&&(this.__redo__[r]=--e)},this)))}),_onClear:EE(function(){this.__redo__&&function(){return DE(this).length=0,this}.call(this.__redo__),this.__nextIndex__=0})}))),XC(GC.prototype,SC.iterator,EE(function(){return this}));var ZC,JC,QC=Object.defineProperty;JC=ZC=function(t,e){if(!(this instanceof JC))throw new TypeError("Constructor requires 'new'");WC.call(this,t),e=e?UE.call(e,"key+value")?"key+value":UE.call(e,"key")?"key":"value":"value",QC(this,"__kind__",EE("",e))},$E&&$E(JC,WC),delete JC.prototype.constructor,JC.prototype=Object.create(WC.prototype,{_resolve:EE(function(t){return"value"===this.__kind__?this.__list__[t]:"key+value"===this.__kind__?[t,this.__list__[t]]:t})}),QC(JC.prototype,SC.toStringTag,EE("c","Array Iterator"));var $C,KC,tS=Object.defineProperty;KC=$C=function(t){if(!(this instanceof KC))throw new TypeError("Constructor requires 'new'");t=String(t),WC.call(this,t),tS(this,"__length__",EE("",t.length))},$E&&$E(KC,WC),delete KC.prototype.constructor,KC.prototype=Object.create(WC.prototype,{_next:EE(function(){if(this.__list__)return this.__nextIndex__=55296&&e<=56319?r+this.__list__[this.__nextIndex__++]:r})}),tS(KC.prototype,SC.toStringTag,EE("c","String Iterator"));var eS,rS=SC.iterator,nS=Array.isArray,aS=function(t){if(!function(t){return!(!SE(t)||!nS(t)&&!sC(t)&&!aC(t)&&"function"!=typeof t[rS])}(t))throw new TypeError(t+" is not iterable");return t},iS=SC.iterator,oS=function(t){return"function"==typeof aS(t)[iS]?t[iS]():aC(t)?new ZC(t):sC(t)?new $C(t):new ZC(t)},lS=Array.isArray,sS=Function.prototype.call,uS=Array.prototype.some,cS="function"==typeof WeakMap&&"[object WeakMap]"===Object.prototype.toString.call(new WeakMap),fS=SC.toStringTag,hS=Array.isArray,dS=Object.defineProperty,pS=Object.prototype.hasOwnProperty,gS=Object.getPrototypeOf,vS=eS=function(){var t,e=arguments[0];if(!(this instanceof eS))throw new TypeError("Constructor requires 'new'");return t=cS&&$E&&WeakMap!==eS?$E(new WeakMap,gS(this)):this,null!=e&&(hS(e)||(e=oS(e))),dS(t,"__weakMapData__",EE("c","$weakMap$"+function(){var t;do{t=eC().toString(36).slice(2)}while(tC[t]);return t}())),e?(function(t,e){var r,n,a,i,o,l,s,u,c=arguments[2];if(lS(t)||aC(t)?r="array":sC(t)?r="string":t=oS(t),iC(e),a=function(){i=!0},"array"!==r)if("string"!==r)for(n=t.next();!n.done;){if(sS.call(e,c,n.value,a),i)return;n=t.next()}else for(l=t.length,o=0;o=55296&&u<=56319&&(s+=t[++o]),sS.call(e,c,s,a),!i);++o);else uS.call(t,function(t){return sS.call(e,c,t,a),i})}(e,function(e){DE(e),t.set(e[0],e[1])}),t):t};cS&&($E&&$E(eS,WeakMap),eS.prototype=Object.create(WeakMap.prototype,{constructor:EE(eS)})),Object.defineProperties(eS.prototype,{delete:EE(function(t){return!!pS.call(KE(t),this.__weakMapData__)&&(delete t[this.__weakMapData__],!0)}),get:EE(function(t){if(pS.call(KE(t),this.__weakMapData__))return t[this.__weakMapData__]}),has:EE(function(t){return pS.call(KE(t),this.__weakMapData__)}),set:EE(function(t,e){return dS(KE(t),this.__weakMapData__,EE("c",e)),this}),toString:EE(function(){return"[object WeakMap]"})}),dS(eS.prototype,fS,EE("c","WeakMap"));var mS=function(){var t,e;if("function"!=typeof WeakMap)return!1;try{t=new WeakMap([[e={},"one"],[{},"two"],[{},"three"]])}catch(t){return!1}return"[object WeakMap]"===String(t)&&"function"==typeof t.set&&t.set({},1)===t&&"function"==typeof t.delete&&"function"==typeof t.has&&"one"===t.get(e)}()?WeakMap:vS,yS=Yk.float32,xS=Yk.fract32,bS=_S;function _S(t,e){if(!(this instanceof _S))return new _S(t,e);if("function"==typeof t?(e||(e={}),e.regl=t):e=t,e.length&&(e.positions=e),!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");this.gl=t._gl,this.regl=t,this.passes=[],this.shaders=_S.shaders.has(t)?_S.shaders.get(t):_S.shaders.set(t,_S.createShaders(t)).get(t),this.update(e)}_S.dashMult=2,_S.maxPatternLength=256,_S.precisionThreshold=3e6,_S.maxPoints=1e4,_S.shaders=new mS,_S.createShaders=function(t){var e,r=t.buffer({usage:"static",type:"float",data:[0,1,0,0,1,1,1,0]}),n={primitive:"triangle strip",instances:t.prop("count"),count:4,offset:0,uniforms:{miterMode:function(t,e){return"round"===e.join?2:1},miterLimit:t.prop("miterLimit"),scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),thickness:t.prop("thickness"),dashPattern:t.prop("dashTexture"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),dashSize:t.prop("dashLength"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:function(t,e){return!e.overlay}},stencil:{enable:!1},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport")},a=t(Xk({vert:Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:Ns(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:r,divisor:0,stride:8,offset:0},lineTop:{buffer:r,divisor:0,stride:8,offset:4},aCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:8,divisor:1},bCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:16,divisor:1},aCoordFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:8,divisor:1},bCoordFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:16,divisor:1},color:{buffer:t.prop("colorBuffer"),stride:4,offset:0,divisor:1}}},n));try{e=t(Xk({cull:{enable:!0,face:"back"},vert:Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n\t// adjust scale for horizontal bars\n\tvec2 scale = max(scale, MIN_DIFF);\n\tvec2 scaleRatio = scale * viewport.zw;\n\n\tvec2 normalWidth = thickness / (scale * viewport.zw);\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),frag:Ns(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:r,divisor:0,stride:8,offset:0},lineTop:{buffer:r,divisor:0,stride:8,offset:4},aColor:{buffer:t.prop("colorBuffer"),stride:4,offset:0,divisor:1},bColor:{buffer:t.prop("colorBuffer"),stride:4,offset:4,divisor:1},prevCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:0,divisor:1},aCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:8,divisor:1},bCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:16,divisor:1},nextCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:24,divisor:1}}},n))}catch(t){e=a}return{fill:t({primitive:"triangle",elements:function(t,e){return e.triangles},offset:0,vert:Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]),frag:Ns(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]),uniforms:{scale:t.prop("scale"),color:t.prop("fill"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{position:{buffer:t.prop("positionBuffer"),stride:8,offset:8},positionFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:8}},blend:n.blend,depth:{enable:!1},scissor:n.scissor,stencil:n.stencil,viewport:n.viewport}),rect:a,miter:e}},_S.defaults={dashes:null,join:"miter",miterLimit:1,thickness:10,cap:"square",color:"black",opacity:1,overlay:!1,viewport:null,range:null,close:!1,fill:null},_S.prototype.render=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];e.length&&(t=this).update.apply(t,e),this.draw()},_S.prototype.draw=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return(e.length?e:this.passes).forEach(function(e,r){if(e&&Array.isArray(e))return(n=t).draw.apply(n,e);var n;("number"==typeof e&&(e=t.passes[e]),e&&e.count>1&&e.opacity)&&(t.regl._refresh(),e.fill&&e.triangles&&e.triangles.length>2&&t.shaders.fill(e),e.thickness&&(e.scale[0]*e.viewport.width>_S.precisionThreshold||e.scale[1]*e.viewport.height>_S.precisionThreshold?t.shaders.rect(e):"rect"===e.join||!e.join&&(e.thickness<=2||e.count>=_S.maxPoints)?t.shaders.rect(e):t.shaders.miter(e)))}),this},_S.prototype.update=function(t){var e=this;if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var r=this.regl,n=this.gl;if(t.forEach(function(t,a){var i=e.passes[a];if(void 0!==t)if(null!==t){if("number"==typeof t[0]&&(t={positions:t}),t=Pk(t,{positions:"positions points data coords",thickness:"thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",join:"lineJoin linejoin join type mode",miterLimit:"miterlimit miterLimit",dashes:"dash dashes dasharray dash-array dashArray",color:"color colour stroke colors colours stroke-color strokeColor",fill:"fill fill-color fillColor",opacity:"alpha opacity",overlay:"overlay crease overlap intersect",close:"closed close closed-path closePath",range:"range dataBox",viewport:"viewport viewBox",hole:"holes hole hollow"}),i||(e.passes[a]=i={id:a,scale:null,scaleFract:null,translate:null,translateFract:null,count:0,hole:[],dashLength:1,dashTexture:r.texture({channels:1,data:new Uint8Array([255]),width:1,height:1,mag:"linear",min:"linear"}),colorBuffer:r.buffer({usage:"dynamic",type:"uint8",data:null}),positionBuffer:r.buffer({usage:"dynamic",type:"float",data:null}),positionFractBuffer:r.buffer({usage:"dynamic",type:"float",data:null})},t=Xk({},_S.defaults,t)),null!=t.thickness&&(i.thickness=parseFloat(t.thickness)),null!=t.opacity&&(i.opacity=parseFloat(t.opacity)),null!=t.miterLimit&&(i.miterLimit=parseFloat(t.miterLimit)),null!=t.overlay&&(i.overlay=!!t.overlay),null!=t.join&&(i.join=t.join),null!=t.hole&&(i.hole=t.hole),null!=t.fill&&(i.fill=t.fill?gm(t.fill,"uint8"):null),null!=t.viewport&&(i.viewport=Fk(t.viewport)),i.viewport||(i.viewport=Fk([n.drawingBufferWidth,n.drawingBufferHeight])),null!=t.close&&(i.close=t.close),null===t.positions&&(t.positions=[]),t.positions){var o,l;if(t.positions.x&&t.positions.y){var s=t.positions.x,u=t.positions.y;l=i.count=Math.max(s.length,u.length),o=new Float64Array(2*l);for(var c=0;c>>24,n=(16711680&t)>>>16,a=(65280&t)>>>8,i=255&t;return!1===e?[r,n,a,i]:[r/255,n/255,a/255,i/255]};var MS="undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)),TS=Yk.float32,kS=Yk.fract32,ES=CS;function CS(t,e){var r=this;if(!(this instanceof CS))return new CS(t,e);"function"==typeof t?(e||(e={}),e.regl=t):(e=t,t=null),e&&e.length&&(e.positions=e);var n,a=(t=e.regl)._gl,i=[];this.tooManyColors=MS,n=t.texture({data:new Uint8Array(1020),width:255,height:1,type:"uint8",format:"rgba",wrapS:"clamp",wrapT:"clamp",mag:"nearest",min:"nearest"}),Xk(this,{regl:t,gl:a,groups:[],markerCache:[null],markerTextures:[null],palette:i,paletteIds:{},paletteTexture:n,maxColors:255,maxSize:100,canvas:a.canvas}),this.update(e);var o={uniforms:{pixelRatio:t.context("pixelRatio"),palette:n,paletteSize:function(t,e){return[r.tooManyColors?0:255,n.height]},scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translate:t.prop("translate"),translateFract:t.prop("translateFract"),opacity:t.prop("opacity"),marker:t.prop("markerTexture")},attributes:{x:function(t,e){return e.xAttr||{buffer:e.positionBuffer,stride:8,offset:0}},y:function(t,e){return e.yAttr||{buffer:e.positionBuffer,stride:8,offset:4}},xFract:function(t,e){return e.xAttr?{constant:[0,0]}:{buffer:e.positionFractBuffer,stride:8,offset:0}},yFract:function(t,e){return e.yAttr?{constant:[0,0]}:{buffer:e.positionFractBuffer,stride:8,offset:4}},size:function(t,e){return e.size.length?{buffer:e.sizeBuffer,stride:2,offset:0}:{constant:[Math.round(255*e.size/r.maxSize)]}},borderSize:function(t,e){return e.borderSize.length?{buffer:e.sizeBuffer,stride:2,offset:1}:{constant:[Math.round(255*e.borderSize/r.maxSize)]}},colorId:function(t,e){return e.color.length?{buffer:e.colorBuffer,stride:r.tooManyColors?8:4,offset:0}:{constant:r.tooManyColors?i.slice(4*e.color,4*e.color+4):[e.color]}},borderColorId:function(t,e){return e.borderColor.length?{buffer:e.colorBuffer,stride:r.tooManyColors?8:4,offset:r.tooManyColors?4:2}:{constant:r.tooManyColors?i.slice(4*e.borderColor,4*e.borderColor+4):[e.borderColor]}},isActive:function(t,e){return!0===e.activation?{constant:[1]}:e.activation?e.activation:{constant:[0]}}},blend:{enable:!0,color:[0,0,0,1],func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport"),stencil:{enable:!1},depth:{enable:!1},elements:t.prop("elements"),count:t.prop("count"),offset:t.prop("offset"),primitive:"points"},l=Xk({},o);l.frag=Ns(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]),l.vert=Ns(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n fragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]);try{this.drawMarker=t(l)}catch(t){}var s=Xk({},o);s.frag=Ns(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]),s.vert=Ns(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]),MS&&(s.frag=s.frag.replace("smoothstep","smoothStep")),this.drawCircle=t(s)}CS.defaults={color:"black",borderColor:"transparent",borderSize:0,size:12,opacity:1,marker:void 0,viewport:null,range:null,pixelSize:null,count:0,offset:0,bounds:null,positions:[],snap:1e4},CS.prototype.render=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.length&&(t=this).update.apply(t,e),this.draw(),this},CS.prototype.draw=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];var n=this.groups;if(1===e.length&&Array.isArray(e[0])&&(null===e[0][0]||Array.isArray(e[0][0]))&&(e=e[0]),e.length)for(var a=0;an)?e.tree=Vk(t,{bounds:u}):n&&n.length&&(e.tree=n),e.tree){var c={primitive:"points",usage:"static",data:e.tree,type:"uint32"};e.elements?e.elements(c):e.elements=i.elements(c)}return a({data:TS(t),usage:"dynamic"}),o({data:kS(t),usage:"dynamic"}),l({data:new Uint8Array(s),type:"uint8",usage:"stream"}),t}},{marker:function(e,r,n){var a=r.activation;if(a.forEach(function(t){return t&&t.destroy&&t.destroy()}),a.length=0,e&&"number"!=typeof e[0]){for(var o=[],l=0,s=Math.min(e.length,r.count);l=0)return i;if(t instanceof Uint8Array||t instanceof Uint8ClampedArray)e=t;else{e=new Uint8Array(t.length);for(var o=0,l=t.length;on*n*4&&(this.tooManyColors=!0),this.updatePalette(r),1===a.length?a[0]:a},CS.prototype.updatePalette=function(t){if(!this.tooManyColors){var e=this.maxColors,r=this.paletteTexture,n=Math.ceil(.25*t.length/e);if(n>1)for(var a=.25*(t=t.slice()).length%e;a7&&(r.push(d.splice(0,7)),d.unshift("C"));break;case"S":var g=u,v=c;"C"!=e&&"S"!=e||(g+=g-n,v+=v-a),d=["C",g,v,d[1],d[2],d[3],d[4]];break;case"T":"Q"==e||"T"==e?(l=2*u-l,s=2*c-s):(l=u,s=c),d=WS(u,c,l,s,d[1],d[2]);break;case"Q":l=d[1],s=d[2],d=WS(u,c,d[1],d[2],d[3],d[4]);break;case"L":d=YS(u,c,d[1],d[2]);break;case"H":d=YS(u,c,d[1],c);break;case"V":d=YS(u,c,u,d[1]);break;case"Z":d=YS(u,c,i,o)}e=p,u=d[d.length-2],c=d[d.length-1],d.length>4?(n=d[d.length-4],a=d[d.length-3]):(n=u,a=c),r.push(d)}return r};function YS(t,e,r,n){return["C",t,e,r,n,r,n]}function WS(t,e,r,n,a,i){return["C",t/3+2/3*r,e/3+2/3*n,a/3+2/3*r,i/3+2/3*n,a,i]}function ZS(t,e,r,n,a,i,o,l,s,u){if(u)x=u[0],b=u[1],m=u[2],y=u[3];else{var c=JS(t,e,-a);t=c.x,e=c.y;var f=(t-(l=(c=JS(l,s,-a)).x))/2,h=(e-(s=c.y))/2,d=f*f/(r*r)+h*h/(n*n);d>1&&(r*=d=Math.sqrt(d),n*=d);var p=r*r,g=n*n,v=(i==o?-1:1)*Math.sqrt(Math.abs((p*g-p*h*h-g*f*f)/(p*h*h+g*f*f)));v==1/0&&(v=1);var m=v*r*h/n+(t+l)/2,y=v*-n*f/r+(e+s)/2,x=Math.asin(((e-y)/n).toFixed(9)),b=Math.asin(((s-y)/n).toFixed(9));x=tb&&(x-=2*qS),!o&&b>x&&(b-=2*qS)}if(Math.abs(b-x)>GS){var _=b,w=l,A=s;b=x+GS*(o&&b>x?1:-1);var M=ZS(l=m+r*Math.cos(b),s=y+n*Math.sin(b),r,n,a,0,o,w,A,[b,_,m,y])}var T=Math.tan((b-x)/4),k=4/3*r*T,E=4/3*n*T,C=[2*t-(t+k*Math.sin(x)),2*e-(e-E*Math.cos(x)),l+k*Math.sin(b),s-E*Math.cos(b),l,s];if(u)return C;M&&(C=C.concat(M));for(var S=0;S4))},eL=function(t){var e=[];return t.replace(nL,function(t,r,n){var a=r.toLowerCase();for(n=function(t){var e=t.match(aL);return e?e.map(Number):[]}(n),"m"==a&&n.length>2&&(e.push([r].concat(n.splice(0,2))),a="l",r="m"==r?"l":"L");;){if(n.length==rL[a])return n.unshift(r),e.push(n);if(n.length=o)return t;switch(t){case"%s":return String(a[n++]);case"%d":return Number(a[n++]);case"%j":try{return JSON.stringify(a[n++])}catch(t){return"[Circular]"}default:return t}}),s=a[n];n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),h(e)?r.showHidden=e:e&&lL._extend(r,e),v(r.showHidden)&&(r.showHidden=!1),v(r.depth)&&(r.depth=2),v(r.colors)&&(r.colors=!1),v(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),s(r,t,r.depth)}function o(t,e){var r=i.styles[e];return r?"\x1b["+i.colors[r][0]+"m"+t+"\x1b["+i.colors[r][1]+"m":t}function l(t,e){return t}function s(t,e,r){if(t.customInspect&&e&&_(e.inspect)&&e.inspect!==lL.inspect&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return g(n)||(n=s(t,n,r)),n}var a=function(t,e){if(v(e))return t.stylize("undefined","undefined");if(g(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(p(e))return t.stylize(""+e,"number");if(h(e))return t.stylize(""+e,"boolean");if(d(e))return t.stylize("null","null")}(t,e);if(a)return a;var i=Object.keys(e),o=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(i);if(t.showHidden&&(i=Object.getOwnPropertyNames(e)),b(e)&&(i.indexOf("message")>=0||i.indexOf("description")>=0))return u(e);if(0===i.length){if(_(e)){var l=e.name?": "+e.name:"";return t.stylize("[Function"+l+"]","special")}if(m(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(x(e))return t.stylize(Date.prototype.toString.call(e),"date");if(b(e))return u(e)}var y,w="",A=!1,M=["{","}"];(f(e)&&(A=!0,M=["[","]"]),_(e))&&(w=" [Function"+(e.name?": "+e.name:"")+"]");return m(e)&&(w=" "+RegExp.prototype.toString.call(e)),x(e)&&(w=" "+Date.prototype.toUTCString.call(e)),b(e)&&(w=" "+u(e)),0!==i.length||A&&0!=e.length?r<0?m(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),y=A?function(t,e,r,n,a){for(var i=[],o=0,l=e.length;o=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(y,w,M)):M[0]+w+M[1]}function u(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,e,r,n,a,i){var o,l,u;if((u=Object.getOwnPropertyDescriptor(e,a)||{value:e[a]}).get?l=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(l=t.stylize("[Setter]","special")),T(n,a)||(o="["+a+"]"),l||(t.seen.indexOf(u.value)<0?(l=d(r)?s(t,u.value,null):s(t,u.value,r-1)).indexOf("\n")>-1&&(l=i?l.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+l.split("\n").map(function(t){return" "+t}).join("\n")):l=t.stylize("[Circular]","special")),v(o)){if(i&&a.match(/^\d+$/))return l;(o=JSON.stringify(""+a)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+l}function f(t){return Array.isArray(t)}function h(t){return"boolean"==typeof t}function d(t){return null===t}function p(t){return"number"==typeof t}function g(t){return"string"==typeof t}function v(t){return void 0===t}function m(t){return y(t)&&"[object RegExp]"===w(t)}function y(t){return"object"==typeof t&&null!==t}function x(t){return y(t)&&"[object Date]"===w(t)}function b(t){return y(t)&&("[object Error]"===w(t)||t instanceof Error)}function _(t){return"function"==typeof t}function w(t){return Object.prototype.toString.call(t)}function A(t){return t<10?"0"+t.toString(10):t.toString(10)}lL.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var r=t.pid;a[e]=function(){var t=lL.format.apply(lL,arguments);console.error("%s %d: %s",e,r,t)}}else a[e]=function(){};return a[e]},lL.inspect=i,i.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]},i.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},lL.isArray=f,lL.isBoolean=h,lL.isNull=d,lL.isNullOrUndefined=function(t){return null==t},lL.isNumber=p,lL.isString=g,lL.isSymbol=function(t){return"symbol"==typeof t},lL.isUndefined=v,lL.isRegExp=m,lL.isObject=y,lL.isDate=x,lL.isError=b,lL.isFunction=_,lL.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},lL.isBuffer=oL;var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function T(t,e){return Object.prototype.hasOwnProperty.call(t,e)}lL.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[A(t.getHours()),A(t.getMinutes()),A(t.getSeconds())].join(":"),[t.getDate(),M[t.getMonth()],e].join(" ")),lL.format.apply(lL,arguments))},lL.inherits=iL,lL._extend=function(t,e){if(!e||!y(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,_c,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var sL={};(function(t){"use strict";function e(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,a=0,i=Math.min(r,n);a=0;s--)if(u[s]!==c[s])return!1;for(s=u.length-1;s>=0;s--)if(l=u[s],!g(t[l],e[l],r,n))return!1;return!0}(t,n,i,s))}return i?t===n:t==n}function v(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function m(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function y(t,e,r,n){var a;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),a=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!a&&d(a,r,"Missing expected exception"+n);var i="string"==typeof n,o=!t&&lL.isError(a),l=!t&&a&&!r;if((o&&i&&m(a,r)||l)&&d(a,r,"Got unwanted exception"+n),t&&a&&r&&!m(a,r)||!t&&a)throw a}s.AssertionError=function(t){var e;this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=f(h((e=this).actual),128)+" "+e.operator+" "+f(h(e.expected),128),this.generatedMessage=!0);var r=t.stackStartFunction||d;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var a=n.stack,i=c(r),o=a.indexOf("\n"+i);if(o>=0){var l=a.indexOf("\n",o+1);a=a.substring(l+1)}this.stack=a}}},lL.inherits(s.AssertionError,Error),s.fail=d,s.ok=p,s.equal=function(t,e,r){t!=e&&d(t,e,r,"==",s.equal)},s.notEqual=function(t,e,r){t==e&&d(t,e,r,"!=",s.notEqual)},s.deepEqual=function(t,e,r){g(t,e,!1)||d(t,e,r,"deepEqual",s.deepEqual)},s.deepStrictEqual=function(t,e,r){g(t,e,!0)||d(t,e,r,"deepStrictEqual",s.deepStrictEqual)},s.notDeepEqual=function(t,e,r){g(t,e,!1)&&d(t,e,r,"notDeepEqual",s.notDeepEqual)},s.notDeepStrictEqual=function t(e,r,n){g(e,r,!0)&&d(e,r,n,"notDeepStrictEqual",t)},s.strictEqual=function(t,e,r){t!==e&&d(t,e,r,"===",s.strictEqual)},s.notStrictEqual=function(t,e,r){t===e&&d(t,e,r,"!==",s.notStrictEqual)},s.throws=function(t,e,r){y(!0,t,e,r)},s.doesNotThrow=function(t,e,r){y(!1,t,e,r)},s.ifError=function(t){if(t)throw t};var x=Object.keys||function(t){var e=[];for(var r in t)n.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var uL={};Object.defineProperty(uL,"__esModule",{value:!0});var cL=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var r=[],n=!0,a=!1,i=void 0;try{for(var o,l=t[Symbol.iterator]();!(n=(o=l.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){a=!0,i=t}finally{try{!n&&l.return&&l.return()}finally{if(a)throw i}}return r}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),fL=2*Math.PI,hL=function(t,e,r,n,a,i,o){var l=t.x,s=t.y;return{x:n*(l*=e)-a*(s*=r)+i,y:a*l+n*s+o}},dL=function(t,e){var r=4/3*Math.tan(e/4),n=Math.cos(t),a=Math.sin(t),i=Math.cos(t+e),o=Math.sin(t+e);return[{x:n-a*r,y:a+n*r},{x:i+o*r,y:o-i*r},{x:i,y:o}]},pL=function(t,e,r,n){var a=t*n-e*r<0?-1:1,i=(t*r+e*n)/(Math.sqrt(t*t+e*e)*Math.sqrt(t*t+e*e));return i>1&&(i=1),i<-1&&(i=-1),a*Math.acos(i)};uL.default=function(t){var e=t.px,r=t.py,n=t.cx,a=t.cy,i=t.rx,o=t.ry,l=t.xAxisRotation,s=void 0===l?0:l,u=t.largeArcFlag,c=void 0===u?0:u,f=t.sweepFlag,h=void 0===f?0:f,d=[];if(0===i||0===o)return[];var p=Math.sin(s*fL/360),g=Math.cos(s*fL/360),v=g*(e-n)/2+p*(r-a)/2,m=-p*(e-n)/2+g*(r-a)/2;if(0===v&&0===m)return[];i=Math.abs(i),o=Math.abs(o);var y=Math.pow(v,2)/Math.pow(i,2)+Math.pow(m,2)/Math.pow(o,2);y>1&&(i*=Math.sqrt(y),o*=Math.sqrt(y));var x=function(t,e,r,n,a,i,o,l,s,u,c,f){var h=Math.pow(a,2),d=Math.pow(i,2),p=Math.pow(c,2),g=Math.pow(f,2),v=h*d-h*g-d*p;v<0&&(v=0),v/=h*g+d*p;var m=(v=Math.sqrt(v)*(o===l?-1:1))*a/i*f,y=v*-i/a*c,x=u*m-s*y+(t+r)/2,b=s*m+u*y+(e+n)/2,_=(c-m)/a,w=(f-y)/i,A=(-c-m)/a,M=(-f-y)/i,T=pL(1,0,_,w),k=pL(_,w,A,M);return 0===l&&k>0&&(k-=fL),1===l&&k<0&&(k+=fL),[x,b,T,k]}(e,r,n,a,i,o,c,h,p,g,v,m),b=cL(x,4),_=b[0],w=b[1],A=b[2],M=b[3],T=Math.max(Math.ceil(Math.abs(M)/(fL/4)),1);M/=T;for(var k=0;k4?(n=d[d.length-4],a=d[d.length-3]):(n=u,a=c),r.push(d)}return r};function vL(t,e,r,n){return["C",t,e,r,n,r,n]}function mL(t,e,r,n,a,i){return["C",t/3+2/3*r,e/3+2/3*n,a/3+2/3*r,i/3+2/3*n,a,i]}var yL=function(t){Array.isArray(t)&&1===t.length&&"string"==typeof t[0]&&(t=t[0]);"string"==typeof t&&(sL(tL(t),"String is not an SVG path."),t=eL(t));if(sL(Array.isArray(t),"Argument should be a string or an array of path segments."),t=HS(t),!(t=gL(t)).length)return[0,0,0,0];for(var e=[1/0,1/0,-1/0,-1/0],r=0,n=t.length;re[2]&&(e[2]=a[i+0]),a[i+1]>e[3]&&(e[3]=a[i+1]);return e};var xL={};(function(t){"use strict";var e=document.createElement("canvas"),r=e.getContext("2d");xL=function(n,a){if(!tL(n))throw Error("Argument should be valid svg path string");a||(a={});var i,o;a.shape?(i=a.shape[0],o=a.shape[1]):(i=e.width=a.w||a.width||200,o=e.height=a.h||a.height||200);var l=Math.min(i,o),s=a.stroke||0,u=a.viewbox||a.viewBox||yL(n),c=[i/(u[2]-u[0]),o/(u[3]-u[1])],f=Math.min(c[0]||0,c[1]||0)/2;r.fillStyle="black",r.fillRect(0,0,i,o),r.fillStyle="white",s&&("number"!=typeof s&&(s=1),r.strokeStyle=s>0?"white":"black",r.lineWidth=Math.abs(s));if(r.translate(.5*i,.5*o),r.scale(f,f),t.Path2D){var h=new Path2D(n);r.fill(h),s&&r.stroke(h)}else{var d=eL(n);KS(r,d),r.fill(),s&&r.stroke()}return r.setTransform(1,0,0,1,0,0),NS(r,{cutoff:null!=a.cutoff?a.cutoff:.5,radius:null!=a.radius?a.radius:.5*l})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var bL=D.defaultLine,_L=gm(bL),wL=1;function AL(t,e){var r=t;return r[3]*=e,r}function ML(t){if(a(t))return _L;var e=gm(t);return e.length?e:_L}function TL(t){return a(t)?t:wL}var kL=function(t,e,r){var n,a,i,o,l,s=t.color,u=Array.isArray(s),c=Array.isArray(e),f=[];if(n=void 0!==t.colorscale?br.makeColorScaleFunc(br.extractScale(t.colorscale,t.cmin,t.cmax)):ML,a=u?function(t,e){return void 0===t[e]?_L:gm(n(t[e]))}:ML,i=c?function(t,e){return void 0===t[e]?wL:TL(t[e])}:TL,u||c)for(var h=0;hLS.TOO_MANY_POINTS?"rect":Zr.hasMarkers(e)?"rect":"round";if(o&&e.connectgaps){var s=n[0],u=n[1];for(a=0;a1&&oe.extendFlat(a.line,VL(t,r,n)),a.errorX||a.errorY){var i=HL(t,r,n);a.errorX&&oe.extendFlat(a.errorX,i.x),a.errorY&&oe.extendFlat(a.errorY,i.y)}return a}function YL(t,e){var r=e._scene,n=t._fullLayout,a={count:0,dirty:!0,lineOptions:[],fillOptions:[],markerOptions:[],selectedOptions:[],unselectedOptions:[],errorXOptions:[],errorYOptions:[]};return e._scene||((r=e._scene=oe.extendFlat({},a,{selectBatch:null,unselectBatch:null,fill2d:!1,scatter2d:!1,error2d:!1,line2d:!1,select2d:null})).update=function(t){for(var e=new Array(r.count),n=0;n=GL&&(m.marker.cluster=f.tree),y.lineOptions.push(m.line),y.errorXOptions.push(m.errorX),y.errorYOptions.push(m.errorY),y.fillOptions.push(m.fill),y.markerOptions.push(m.marker),y.selectedOptions.push(m.selected),y.unselectedOptions.push(m.unselected),y.count++,f._scene=y,f.index=y.count-1,f.x=h,f.y=d,f.positions=p,f.count=u,t.firstscatter=!1,[{x:!1,y:!1,t:f,trace:e}]},plot:function(t,e,r){if(r.length){var n=t._fullLayout,a=r[0][0].t._scene,i=n.dragmode;if(a){var o=n._size,l=n.width,s=n.height;aT(t,["ANGLE_instanced_arrays","OES_element_index_uint"]);var u=n._glcanvas.data()[0].regl;if(kM(t,e,r),a.dirty){if(!0===a.error2d&&(a.error2d=$k(u)),!0===a.line2d&&(a.line2d=bS(u)),!0===a.scatter2d&&(a.scatter2d=SS(u)),!0===a.fill2d&&(a.fill2d=bS(u)),a.line2d&&a.line2d.update(a.lineOptions),a.error2d){var c=(a.errorXOptions||[]).concat(a.errorYOptions||[]);a.error2d.update(c)}a.scatter2d&&a.scatter2d.update(a.markerOptions),a.fill2d&&(a.fillOptions=a.fillOptions.map(function(t,e){var n=r[e];if(!(t&&n&&n[0]&&n[0].trace))return null;var i,o,l=n[0],s=l.trace,u=l.t,c=a.lineOptions[e],f=[],h=c&&c.positions||u.positions;if("tozeroy"===s.fill)(f=(f=[h[0],0]).concat(h)).push(h[h.length-2]),f.push(0);else if("tozerox"===s.fill)(f=(f=[0,h[1]]).concat(h)).push(0),f.push(h[h.length-1]);else if("toself"===s.fill||"tonext"===s.fill){for(f=[],i=0,o=0;o2?(l[0],l[2],n=l[1],a=l[3]):l.length?(n=l[0],a=l[1]):(l.x,n=l.y,l.x+l.width,a=l.y+l.height),s.length>2?(i=s[0],o=s[2],s[1],s[3]):s.length?(i=s[0],o=s[1]):(i=s.x,s.y,o=s.x+s.width,s.y+s.height),[i,n,o,a]}function nO(t){if("number"==typeof t)return[t,t,t,t];if(2===t.length)return[t[0],t[1],t[0],t[1]];var e=Fk(t);return[e.x,e.y,e.x+e.width,e.y+e.height]}tO.prototype.render=function(){for(var t,e=this,r=[],n=arguments.length;n--;)r[n]=arguments[n];return r.length&&(t=this).update.apply(t,r),this.regl.attributes.preserveDrawingBuffer?this.draw():(this.dirty?null==this.planned&&(this.planned=$L(function(){e.draw(),e.dirty=!0,e.planned=null})):(this.draw(),this.dirty=!0,$L(function(){e.dirty=!1})),this)},tO.prototype.update=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(t.length){for(var r=0;rm))&&(i.lower||!(v1&&ri&&s?r._splomSubplots[g]=1:aAO;for(r=0,n=0;r 1) { + if(_$plot_config_457.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11589,7 +11589,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_456.logging > 0) { + if(_$plot_config_457.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11601,7 +11601,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_456.logging > 0) { + if(_$plot_config_457.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11640,7 +11640,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_431 = function noop() {}; +var _$noop_432 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11665,7 +11665,7 @@ var _$noop_431 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_435 = function pushUnique(array, item) { +var _$pushUnique_436 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11802,7 +11802,7 @@ var _$attributes_333 = { /* removed: var _$attributes_333 = require('../components/fx/attributes'); */; -var _$attributes_463 = { +var _$attributes_464 = { type: { valType: 'enumerated', @@ -12108,7 +12108,7 @@ var _$layout_attributes_508 = { } }; -var _$registry_518 = {}; +var _$registry_519 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12119,29 +12119,29 @@ var _$registry_518 = {}; 'use strict'; -/* removed: var _$loggers_427 = require('./lib/loggers'); */; -/* removed: var _$noop_431 = require('./lib/noop'); */; -/* removed: var _$pushUnique_435 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_424 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_414 = require('./lib/extend'); */; +/* removed: var _$loggers_428 = require('./lib/loggers'); */; +/* removed: var _$noop_432 = require('./lib/noop'); */; +/* removed: var _$pushUnique_436 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_425 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_415 = require('./lib/extend'); */; -/* removed: var _$attributes_463 = require('./plots/attributes'); */; +/* removed: var _$attributes_464 = require('./plots/attributes'); */; /* removed: var _$layout_attributes_508 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_414.extendFlat; -var extendDeepAll = _$extend_414.extendDeepAll; - -_$registry_518.modules = {}; -_$registry_518.allCategories = {}; -_$registry_518.allTypes = []; -_$registry_518.subplotsRegistry = {}; -_$registry_518.transformsRegistry = {}; -_$registry_518.componentsRegistry = {}; -_$registry_518.layoutArrayContainers = []; -_$registry_518.layoutArrayRegexes = []; -_$registry_518.traceLayoutAttributes = {}; -_$registry_518.localeRegistry = {}; -_$registry_518.apiMethodRegistry = {}; +var extendFlat = _$extend_415.extendFlat; +var extendDeepAll = _$extend_415.extendDeepAll; + +_$registry_519.modules = {}; +_$registry_519.allCategories = {}; +_$registry_519.allTypes = []; +_$registry_519.subplotsRegistry = {}; +_$registry_519.transformsRegistry = {}; +_$registry_519.componentsRegistry = {}; +_$registry_519.layoutArrayContainers = []; +_$registry_519.layoutArrayRegexes = []; +_$registry_519.traceLayoutAttributes = {}; +_$registry_519.localeRegistry = {}; +_$registry_519.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12182,7 +12182,7 @@ _$registry_518.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_518.register = function register(_modules) { +_$registry_519.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12211,7 +12211,7 @@ _$registry_518.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_518.apiMethodRegistry[name] = newModule.fn; + _$registry_519.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12227,8 +12227,8 @@ _$registry_518.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_518.getModule = function(trace) { - var _module = _$registry_518.modules[getTraceType(trace)]; +_$registry_519.getModule = function(trace) { + var _module = _$registry_519.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12242,20 +12242,20 @@ _$registry_518.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_518.traceIs = function(traceType, category) { +_$registry_519.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_518.modules[traceType]; + var _module = _$registry_519.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_427.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_428.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_518.modules[_$attributes_463.type.dflt]; + _module = _$registry_519.modules[_$attributes_464.type.dflt]; } return !!_module.categories[category]; @@ -12272,7 +12272,7 @@ _$registry_518.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_518.getTransformIndices = function(data, type) { +_$registry_519.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12292,7 +12292,7 @@ _$registry_518.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_518.hasTransform = function(data, type) { +_$registry_519.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12312,11 +12312,11 @@ _$registry_518.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_518.getComponentMethod = function(name, method) { - var _module = _$registry_518.componentsRegistry[name]; +_$registry_519.getComponentMethod = function(name, method) { + var _module = _$registry_519.componentsRegistry[name]; - if(!_module) return _$noop_431; - return _module[method] || _$noop_431; + if(!_module) return _$noop_432; + return _module[method] || _$noop_432; }; /** @@ -12326,10 +12326,10 @@ _$registry_518.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_518.call = function() { +_$registry_519.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_518.apiMethodRegistry[name].apply(null, args); + return _$registry_519.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12337,33 +12337,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_518.modules[thisType]) { - _$loggers_427.log('Type ' + thisType + ' already registered'); + if(_$registry_519.modules[thisType]) { + _$loggers_428.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_518.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_519.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_518.allCategories[categoriesIn[i]] = true; + _$registry_519.allCategories[categoriesIn[i]] = true; } - _$registry_518.modules[thisType] = { + _$registry_519.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_518.modules[thisType].meta = meta; + _$registry_519.modules[thisType].meta = meta; } - _$registry_518.allTypes.push(thisType); + _$registry_519.allTypes.push(thisType); - for(var componentName in _$registry_518.componentsRegistry) { + for(var componentName in _$registry_519.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12373,15 +12373,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_518.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_519.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_518.subplotsRegistry[plotType]) { - _$loggers_427.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_519.subplotsRegistry[plotType]) { + _$loggers_428.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12391,9 +12391,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_518.subplotsRegistry[plotType] = _module; + _$registry_519.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_518.componentsRegistry) { + for(var componentName in _$registry_519.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12404,24 +12404,24 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_518.componentsRegistry[name] = _module; + _$registry_519.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_435(_$registry_518.layoutArrayContainers, name); + _$pushUnique_436(_$registry_519.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_518.modules) { + for(var traceType in _$registry_519.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_518.subplotsRegistry) { + for(var subplotName in _$registry_519.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_518.transformsRegistry) { + for(var transformType in _$registry_519.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } @@ -12443,22 +12443,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_427.log([ + _$loggers_428.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_424(_module.attributes)) { - _$loggers_427.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_425(_module.attributes)) { + _$loggers_428.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_427.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_428.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_518.transformsRegistry[_module.name] = _module; + _$registry_519.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_518.componentsRegistry) { + for(var componentName in _$registry_519.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12472,7 +12472,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_518.localeRegistry; + var locales = _$registry_519.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12504,37 +12504,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_435(_$registry_518.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_436(_$registry_519.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_518.componentsRegistry[componentName].schema; + var componentSchema = _$registry_519.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_518.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_519.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_518.componentsRegistry[componentName].schema; + var componentSchema = _$registry_519.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_518.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_519.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_518.componentsRegistry[componentName].schema; + var componentSchema = _$registry_519.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_518.subplotsRegistry[subplotName]; + var subplotModule = _$registry_519.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12561,7 +12561,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_518 = require('../registry'); */; +/* removed: var _$registry_519 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12576,9 +12576,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_450 = function containerArrayMatch(astr) { - var rootContainers = _$registry_518.layoutArrayContainers, - regexpContainers = _$registry_518.layoutArrayRegexes, +var _$containerArrayMatch_451 = function containerArrayMatch(astr) { + var rootContainers = _$registry_519.layoutArrayContainers, + regexpContainers = _$registry_519.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12619,9 +12619,9 @@ var _$containerArrayMatch_450 = function containerArrayMatch(astr) { 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_423.isArrayOrTypedArray; -/* removed: var _$isPlainObject_424 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_450 = require('../plot_api/container_array_match'); */; +var isArrayOrTypedArray = _$is_array_424.isArrayOrTypedArray; +/* removed: var _$isPlainObject_425 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_451 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12637,7 +12637,7 @@ var isArrayOrTypedArray = _$is_array_423.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_430 = function nestedProperty(container, propStr) { +var _$nestedProperty_431 = function nestedProperty(container, propStr) { if(_$fastIsnumeric_89(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { @@ -12748,7 +12748,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_424(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_425(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12757,7 +12757,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_450(propStr); + var match = _$containerArrayMatch_451(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12910,7 +12910,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_437 = {}; +var _$regex_438 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12930,7 +12930,7 @@ var _$regex_437 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_437.counter = function(head, tail, openEnded) { +_$regex_438.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12938,7 +12938,7 @@ _$regex_437.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_410 = {}; +var _$coerce_411 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12953,16 +12953,16 @@ var _$coerce_410 = {}; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_264 = require('tinycolor2'); */; -/* removed: var _$attributes_463 = require('../plots/attributes'); */; +/* removed: var _$attributes_464 = require('../plots/attributes'); */; /* removed: var _$getScale_312 = require('../components/colorscale/get_scale'); */; var colorscaleNames = Object.keys(_$scales_318); -/* removed: var _$nestedProperty_430 = require('./nested_property'); */; -var counterRegex = _$regex_437.counter; +/* removed: var _$nestedProperty_431 = require('./nested_property'); */; +var counterRegex = _$regex_438.counter; var DESELECTDIM = _$interactions_402.DESELECTDIM; var wrap180 = _$angles_408.wrap180; -var __isArrayOrTypedArray_410 = _$is_array_423.isArrayOrTypedArray; +var __isArrayOrTypedArray_411 = _$is_array_424.isArrayOrTypedArray; -_$coerce_410.valObjectMeta = { +_$coerce_411.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12970,7 +12970,7 @@ _$coerce_410.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_410(v)) propOut.set(v); + if(__isArrayOrTypedArray_411(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13093,8 +13093,9 @@ _$coerce_410.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13148,9 +13149,11 @@ _$coerce_410.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13161,12 +13164,12 @@ _$coerce_410.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_410.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_411.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13176,19 +13179,28 @@ _$coerce_410.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13219,12 +13231,12 @@ _$coerce_410.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_410.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_411.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_410.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_411.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13244,10 +13256,10 @@ _$coerce_410.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_410.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_430(attributes, attribute).get(), - propIn = _$nestedProperty_430(containerIn, attribute), - propOut = _$nestedProperty_430(containerOut, attribute), +_$coerce_411.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_431(attributes, attribute).get(), + propIn = _$nestedProperty_431(containerIn, attribute), + propOut = _$nestedProperty_431(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13258,12 +13270,12 @@ _$coerce_410.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_410(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_411(v)) { propOut.set(v); return v; } - _$coerce_410.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_411.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13275,9 +13287,9 @@ _$coerce_410.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_410.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_430(containerIn, attribute), - propOut = _$coerce_410.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_411.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_431(containerIn, attribute), + propOut = _$coerce_411.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13288,7 +13300,7 @@ _$coerce_410.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_410.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_411.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13308,11 +13320,9 @@ _$coerce_410.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_410.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_411.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_463; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_464; var valObj = attrs.hoverinfo; var dflt; @@ -13326,7 +13336,7 @@ _$coerce_410.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_410.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_411.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13340,7 +13350,7 @@ _$coerce_410.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_410.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_411.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13355,7 +13365,7 @@ _$coerce_410.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_410(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_411(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13364,10 +13374,10 @@ _$coerce_410.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_410.validate = function(value, opts) { - var valObjectDef = _$coerce_410.valObjectMeta[opts.valType]; +_$coerce_411.validate = function(value, opts) { + var valObjectDef = _$coerce_411.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_410(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_411(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13397,12 +13407,12 @@ _$coerce_410.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_429 = function mod(v, d) { +var _$mod_430 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_411 = {}; +var _$dates_412 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13417,18 +13427,18 @@ var _$dates_411 = {}; /* removed: var _$d3_79 = require('d3'); */; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$loggers_427 = require('./loggers'); */; -/* removed: var _$mod_429 = require('./mod'); */; +/* removed: var _$loggers_428 = require('./loggers'); */; +/* removed: var _$mod_430 = require('./mod'); */; /* removed: var _$numerical_403 = require('../constants/numerical'); */; -var __BADNUM_411 = _$numerical_403.BADNUM; +var __BADNUM_412 = _$numerical_403.BADNUM; var ONEDAY = _$numerical_403.ONEDAY; var ONEHOUR = _$numerical_403.ONEHOUR; var ONEMIN = _$numerical_403.ONEMIN; var ONESEC = _$numerical_403.ONESEC; var EPOCHJD = _$numerical_403.EPOCHJD; -/* removed: var _$registry_518 = require('../registry'); */; +/* removed: var _$registry_519 = require('../registry'); */; var utcFormat = _$d3_79.time.format.utc; @@ -13442,7 +13452,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_518.componentsRegistry.calendars && + _$registry_519.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13452,11 +13462,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_411.dateTick0 = function(calendar, sunday) { +_$dates_412.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_518.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_518.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_519.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_519.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13466,9 +13476,9 @@ _$dates_411.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_411.dfltRange = function(calendar) { +_$dates_412.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_518.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_519.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13476,7 +13486,7 @@ _$dates_411.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_411.isJSDate = function(v) { +_$dates_412.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13538,17 +13548,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_411.dateTime2ms = function(s, calendar) { +_$dates_412.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_411.isJSDate(s)) { + if(_$dates_412.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_411; + return __BADNUM_412; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_411; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_412; s = String(s); @@ -13565,7 +13575,7 @@ _$dates_411.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_411; + if(!match) return __BADNUM_412; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13575,12 +13585,12 @@ _$dates_411.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_411; + if(y.length === 2) return __BADNUM_412; y = Number(y); var cDate; try { - var calInstance = _$registry_518.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_519.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13590,9 +13600,9 @@ _$dates_411.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_411; } // Invalid ... date + catch(e) { return __BADNUM_412; } // Invalid ... date - if(!cDate) return __BADNUM_411; + if(!cDate) return __BADNUM_412; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13613,18 +13623,18 @@ _$dates_411.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_411; - if(date.getUTCDate() !== d) return __BADNUM_411; + if(date.getUTCMonth() !== m) return __BADNUM_412; + if(date.getUTCDate() !== d) return __BADNUM_412; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_411.MIN_MS = _$dates_411.dateTime2ms('-9999'); -MAX_MS = _$dates_411.MAX_MS = _$dates_411.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_412.MIN_MS = _$dates_412.dateTime2ms('-9999'); +MAX_MS = _$dates_412.MAX_MS = _$dates_412.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_411.isDateTime = function(s, calendar) { - return (_$dates_411.dateTime2ms(s, calendar) !== __BADNUM_411); +_$dates_412.isDateTime = function(s, calendar) { + return (_$dates_412.dateTime2ms(s, calendar) !== __BADNUM_412); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13643,20 +13653,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_411.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_411; +_$dates_412.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_412; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_429(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_430(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_429(ms, ONEDAY)); + timeMs = Math.floor(_$mod_430(ms, ONEDAY)); try { - dateStr = _$registry_518.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_519.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13704,10 +13714,10 @@ _$dates_411.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_411.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_411; +_$dates_412.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_412; - var msecTenths = Math.floor(_$mod_429(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_430(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), dateStr = _$d3_79.time.format('%Y-%m-%d')(d), h = d.getHours(), @@ -13740,23 +13750,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_411.cleanDate = function(v, dflt, calendar) { - if(_$dates_411.isJSDate(v) || typeof v === 'number') { +_$dates_412.cleanDate = function(v, dflt, calendar) { + if(_$dates_412.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_427.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_428.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 = _$dates_411.ms2DateTimeLocal(+v); + v = _$dates_412.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_411.isDateTime(v, calendar)) { - _$loggers_427.error('unrecognized date', v); + else if(!_$dates_412.isDateTime(v, calendar)) { + _$loggers_428.error('unrecognized date', v); return dflt; } return v; @@ -13786,7 +13796,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_518.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_519.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13803,10 +13813,10 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_429(x + 0.05, ONEDAY); + var timePart = _$mod_430(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_429(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_430(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { if(!_$fastIsnumeric_89(tr)) tr = 0; // should only be 'S' @@ -13826,7 +13836,7 @@ function formatTime(x, tr) { * 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_429(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_430(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13855,7 +13865,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_411.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_412.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13899,19 +13909,19 @@ _$dates_411.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_411.incrementMonth = function(ms, dMonth, calendar) { +_$dates_412.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_429(ms, ONEDAY); + var timeMs = _$mod_430(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_518.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_519.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13920,7 +13930,7 @@ _$dates_411.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_427.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_428.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13935,7 +13945,7 @@ _$dates_411.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_411.findExactDates = function(data, calendar) { +_$dates_412.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13945,7 +13955,7 @@ _$dates_411.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_518.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_519.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { @@ -14012,7 +14022,7 @@ _$dates_411.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_412 = function ensureArray(out, n) { +var _$ensureArray_413 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14055,7 +14065,7 @@ var _$ensureArray_412 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_415 = function filterUnique(array) { +var _$filterUnique_416 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14089,7 +14099,7 @@ var _$filterUnique_415 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_416 = function filterVisible(container) { +var _$filterVisible_417 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14118,7 +14128,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_417 = {}; +var _$geometry2d_418 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14129,13 +14139,13 @@ var _$geometry2d_417 = {}; 'use strict'; -/* removed: var _$mod_429 = require('./mod'); */; +/* removed: var _$mod_430 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_417.segmentsIntersect = segmentsIntersect; +_$geometry2d_418.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14158,7 +14168,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_417.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_418.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 @@ -14211,7 +14221,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_417.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_418.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14223,13 +14233,13 @@ _$geometry2d_417.getTextLocation = function getTextLocation(path, totalPathLen, // 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_429(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_429(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_430(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_430(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_429(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_430(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14238,7 +14248,7 @@ _$geometry2d_417.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_417.clearLocationCache = function() { +_$geometry2d_418.clearLocationCache = function() { workingPath = null; }; @@ -14266,7 +14276,7 @@ _$geometry2d_417.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_417.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_418.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14327,7 +14337,7 @@ _$geometry2d_417.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_417.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_418.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14382,7 +14392,7 @@ _$geometry2d_417.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_418 = function(gd) { +var _$get_graph_div_419 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14414,7 +14424,7 @@ var _$get_graph_div_418 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_421 = function identity(d) { return d; }; +var _$identity_422 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14426,7 +14436,7 @@ var _$identity_421 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_430 = require('./nested_property'); */; +/* removed: var _$nestedProperty_431 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14448,13 +14458,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_426 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_430(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_431(baseObj, path).get(); } else { arr = baseObj; } @@ -14480,7 +14490,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_430(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_431(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14490,7 +14500,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_430(newValue, valueName).set(value); + _$nestedProperty_431(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14511,7 +14521,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_430(arr[idx], valueName).get(); + return _$nestedProperty_431(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14552,7 +14562,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value } 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_430(object, valueName).set(null); + _$nestedProperty_431(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, @@ -14579,7 +14589,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_430(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_431(arr[idx], valueName).get(); } } } else { @@ -14605,7 +14615,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_518 = require('../registry'); */; +/* removed: var _$registry_519 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14616,7 +14626,7 @@ var _$keyedContainer_425 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_426 = function localize(gd, s) { +var _$localize_427 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14638,7 +14648,7 @@ var _$localize_426 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_518.localeRegistry; + locales = _$registry_519.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14649,7 +14659,7 @@ var _$localize_426 = function localize(gd, s) { return s; }; -var _$matrix_428 = {}; +var _$matrix_429 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14662,7 +14672,7 @@ var _$matrix_428 = {}; 'use strict'; -_$matrix_428.init2dArray = function(rowLength, colLength) { +_$matrix_429.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14673,7 +14683,7 @@ _$matrix_428.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_428.transposeRagged = function(z) { +_$matrix_429.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14691,7 +14701,7 @@ _$matrix_428.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_428.dot = function(x, y) { +_$matrix_429.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14701,13 +14711,13 @@ _$matrix_428.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_428.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_429.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_428.transposeRagged(y); + var yTranspose = _$matrix_429.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_428.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_429.dot(x, yTranspose[i]); } else { // vec-vec @@ -14719,12 +14729,12 @@ _$matrix_428.dot = function(x, y) { }; // translate by (x,y) -_$matrix_428.translationMatrix = function(x, y) { +_$matrix_429.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_428.rotationMatrix = function(alpha) { +_$matrix_429.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14732,28 +14742,28 @@ _$matrix_428.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_428.rotationXYMatrix = function(a, x, y) { - return _$matrix_428.dot( - _$matrix_428.dot(_$matrix_428.translationMatrix(x, y), - _$matrix_428.rotationMatrix(a)), - _$matrix_428.translationMatrix(-x, -y)); +_$matrix_429.rotationXYMatrix = function(a, x, y) { + return _$matrix_429.dot( + _$matrix_429.dot(_$matrix_429.translationMatrix(x, y), + _$matrix_429.rotationMatrix(a)), + _$matrix_429.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_428.apply2DTransform = function(transform) { +_$matrix_429.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_428.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_429.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_428.apply2DTransform2 = function(transform) { - var at = _$matrix_428.apply2DTransform(transform); +_$matrix_429.apply2DTransform2 = function(transform) { + var at = _$matrix_429.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14782,7 +14792,7 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_432 = function(text, displayLength) { +var _$notifier_433 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); @@ -14874,7 +14884,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_438 = function(baseAttr, relativeAttr) { +var _$relative_attr_439 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14903,8 +14913,8 @@ var _$relative_attr_438 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_439 = _$is_array_423.isArrayOrTypedArray; -/* removed: var _$isPlainObject_424 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_440 = _$is_array_424.isArrayOrTypedArray; +/* removed: var _$isPlainObject_425 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14913,7 +14923,7 @@ var __isArrayOrTypedArray_439 = _$is_array_423.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_439 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_440 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14929,7 +14939,7 @@ var _$relinkPrivateKeys_439 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_439(fromVal) && __isArrayOrTypedArray_439(toVal) && _$isPlainObject_424(fromVal[0])) { + else if(__isArrayOrTypedArray_440(fromVal) && __isArrayOrTypedArray_440(toVal) && _$isPlainObject_425(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14939,12 +14949,12 @@ var _$relinkPrivateKeys_439 = function relinkPrivateKeys(toContainer, fromContai // 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_424(fromVal[j]) && _$isPlainObject_424(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_425(fromVal[j]) && _$isPlainObject_425(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_424(fromVal) && _$isPlainObject_424(toVal)) { + else if(_$isPlainObject_425(fromVal) && _$isPlainObject_425(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14954,7 +14964,7 @@ var _$relinkPrivateKeys_439 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_440 = {}; +var _$search_441 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14967,7 +14977,7 @@ var _$search_440 = {}; 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$loggers_427 = require('./loggers'); */; +/* removed: var _$loggers_428 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -14985,7 +14995,7 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_440.findBin = function(val, bins, linelow) { +_$search_441.findBin = function(val, bins, linelow) { if(_$fastIsnumeric_89(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : @@ -15009,7 +15019,7 @@ _$search_440.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_427.log('Long binary search...'); + if(c > 90) _$loggers_428.log('Long binary search...'); return n1 - 1; } }; @@ -15019,17 +15029,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_440.sorterAsc = function(a, b) { return a - b; }; -_$search_440.sorterDes = function(a, b) { return b - a; }; +_$search_441.sorterAsc = function(a, b) { return a - b; }; +_$search_441.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_440.distinctVals = function(valsIn) { +_$search_441.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_440.sorterAsc); + vals.sort(_$search_441.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15054,7 +15064,7 @@ _$search_440.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_440.roundUp = function(val, arrayIn, reverse) { +_$search_441.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15071,7 +15081,7 @@ _$search_440.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_443 = {}; +var _$stats_444 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15084,7 +15094,7 @@ var _$stats_443 = {}; 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_443 = _$is_array_423.isArrayOrTypedArray; +var __isArrayOrTypedArray_444 = _$is_array_424.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15099,14 +15109,14 @@ var __isArrayOrTypedArray_443 = _$is_array_423.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_443.aggNums = function(f, v, a, len) { +_$stats_444.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; if(!_$fastIsnumeric_89(v)) v = false; - if(__isArrayOrTypedArray_443(a[0])) { + if(__isArrayOrTypedArray_444(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_443.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_444.aggNums(f, v, a[i]); a = b; } @@ -15121,26 +15131,26 @@ _$stats_443.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_443.len = function(data) { - return _$stats_443.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_444.len = function(data) { + return _$stats_444.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_443.mean = function(data, len) { - if(!len) len = _$stats_443.len(data); - return _$stats_443.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_444.mean = function(data, len) { + if(!len) len = _$stats_444.len(data); + return _$stats_444.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_443.variance = function(data, len, mean) { - if(!len) len = _$stats_443.len(data); - if(!_$fastIsnumeric_89(mean)) mean = _$stats_443.mean(data, len); +_$stats_444.variance = function(data, len, mean) { + if(!len) len = _$stats_444.len(data); + if(!_$fastIsnumeric_89(mean)) mean = _$stats_444.mean(data, len); - return _$stats_443.aggNums(function(a, b) { + return _$stats_444.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_443.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_443.variance(data, len, mean)); +_$stats_444.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_444.variance(data, len, mean)); }; /** @@ -15158,7 +15168,7 @@ _$stats_443.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_443.interp = function(arr, n) { +_$stats_444.interp = function(arr, n) { if(!_$fastIsnumeric_89(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; @@ -15167,7 +15177,7 @@ _$stats_443.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_446 = {}; +var _$throttle_447 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15194,7 +15204,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_446.throttle = function throttle(id, minInterval, callback) { +_$throttle_447.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15234,7 +15244,7 @@ _$throttle_446.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_446.done = function(id) { +_$throttle_447.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15254,13 +15264,13 @@ _$throttle_446.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_446.clear = function(id) { +_$throttle_447.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_446.clear(idi); + for(var idi in timerCache) _$throttle_447.clear(idi); } }; @@ -15287,7 +15297,7 @@ function _clearTimeout(cache) { * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_447 = function toLogRange(val, range) { +var _$toLogRange_448 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the @@ -15298,7 +15308,7 @@ var _$toLogRange_447 = function toLogRange(val, range) { return newVal; }; -var _$lib_422 = {}; +var _$lib_423 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15315,71 +15325,71 @@ var _$lib_422 = {}; /* removed: var _$numerical_403 = require('../constants/numerical'); */; var FP_SAFE = _$numerical_403.FP_SAFE; -var __BADNUM_422 = _$numerical_403.BADNUM; - -var lib = _$lib_422 = {}; - -lib.nestedProperty = _$nestedProperty_430; -lib.keyedContainer = _$keyedContainer_425; -lib.relativeAttr = _$relative_attr_438; -lib.isPlainObject = _$isPlainObject_424; -lib.mod = _$mod_429; -lib.toLogRange = _$toLogRange_447; -lib.relinkPrivateKeys = _$relinkPrivateKeys_439; -lib.ensureArray = _$ensureArray_412; - -/* removed: var _$is_array_423 = require('./is_array'); */; -lib.isTypedArray = _$is_array_423.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_423.isArrayOrTypedArray; - -/* removed: var _$coerce_410 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_410.valObjectMeta; -lib.coerce = _$coerce_410.coerce; -lib.coerce2 = _$coerce_410.coerce2; -lib.coerceFont = _$coerce_410.coerceFont; -lib.coerceHoverinfo = _$coerce_410.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_410.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_410.validate; - -/* removed: var _$dates_411 = require('./dates'); */; -lib.dateTime2ms = _$dates_411.dateTime2ms; -lib.isDateTime = _$dates_411.isDateTime; -lib.ms2DateTime = _$dates_411.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_411.ms2DateTimeLocal; -lib.cleanDate = _$dates_411.cleanDate; -lib.isJSDate = _$dates_411.isJSDate; -lib.formatDate = _$dates_411.formatDate; -lib.incrementMonth = _$dates_411.incrementMonth; -lib.dateTick0 = _$dates_411.dateTick0; -lib.dfltRange = _$dates_411.dfltRange; -lib.findExactDates = _$dates_411.findExactDates; -lib.MIN_MS = _$dates_411.MIN_MS; -lib.MAX_MS = _$dates_411.MAX_MS; - -/* removed: var _$search_440 = require('./search'); */; -lib.findBin = _$search_440.findBin; -lib.sorterAsc = _$search_440.sorterAsc; -lib.sorterDes = _$search_440.sorterDes; -lib.distinctVals = _$search_440.distinctVals; -lib.roundUp = _$search_440.roundUp; - -/* removed: var _$stats_443 = require('./stats'); */; -lib.aggNums = _$stats_443.aggNums; -lib.len = _$stats_443.len; -lib.mean = _$stats_443.mean; -lib.variance = _$stats_443.variance; -lib.stdev = _$stats_443.stdev; -lib.interp = _$stats_443.interp; - -/* removed: var _$matrix_428 = require('./matrix'); */; -lib.init2dArray = _$matrix_428.init2dArray; -lib.transposeRagged = _$matrix_428.transposeRagged; -lib.dot = _$matrix_428.dot; -lib.translationMatrix = _$matrix_428.translationMatrix; -lib.rotationMatrix = _$matrix_428.rotationMatrix; -lib.rotationXYMatrix = _$matrix_428.rotationXYMatrix; -lib.apply2DTransform = _$matrix_428.apply2DTransform; -lib.apply2DTransform2 = _$matrix_428.apply2DTransform2; +var __BADNUM_423 = _$numerical_403.BADNUM; + +var lib = _$lib_423 = {}; + +lib.nestedProperty = _$nestedProperty_431; +lib.keyedContainer = _$keyedContainer_426; +lib.relativeAttr = _$relative_attr_439; +lib.isPlainObject = _$isPlainObject_425; +lib.mod = _$mod_430; +lib.toLogRange = _$toLogRange_448; +lib.relinkPrivateKeys = _$relinkPrivateKeys_440; +lib.ensureArray = _$ensureArray_413; + +/* removed: var _$is_array_424 = require('./is_array'); */; +lib.isTypedArray = _$is_array_424.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_424.isArrayOrTypedArray; + +/* removed: var _$coerce_411 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_411.valObjectMeta; +lib.coerce = _$coerce_411.coerce; +lib.coerce2 = _$coerce_411.coerce2; +lib.coerceFont = _$coerce_411.coerceFont; +lib.coerceHoverinfo = _$coerce_411.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_411.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_411.validate; + +/* removed: var _$dates_412 = require('./dates'); */; +lib.dateTime2ms = _$dates_412.dateTime2ms; +lib.isDateTime = _$dates_412.isDateTime; +lib.ms2DateTime = _$dates_412.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_412.ms2DateTimeLocal; +lib.cleanDate = _$dates_412.cleanDate; +lib.isJSDate = _$dates_412.isJSDate; +lib.formatDate = _$dates_412.formatDate; +lib.incrementMonth = _$dates_412.incrementMonth; +lib.dateTick0 = _$dates_412.dateTick0; +lib.dfltRange = _$dates_412.dfltRange; +lib.findExactDates = _$dates_412.findExactDates; +lib.MIN_MS = _$dates_412.MIN_MS; +lib.MAX_MS = _$dates_412.MAX_MS; + +/* removed: var _$search_441 = require('./search'); */; +lib.findBin = _$search_441.findBin; +lib.sorterAsc = _$search_441.sorterAsc; +lib.sorterDes = _$search_441.sorterDes; +lib.distinctVals = _$search_441.distinctVals; +lib.roundUp = _$search_441.roundUp; + +/* removed: var _$stats_444 = require('./stats'); */; +lib.aggNums = _$stats_444.aggNums; +lib.len = _$stats_444.len; +lib.mean = _$stats_444.mean; +lib.variance = _$stats_444.variance; +lib.stdev = _$stats_444.stdev; +lib.interp = _$stats_444.interp; + +/* removed: var _$matrix_429 = require('./matrix'); */; +lib.init2dArray = _$matrix_429.init2dArray; +lib.transposeRagged = _$matrix_429.transposeRagged; +lib.dot = _$matrix_429.dot; +lib.translationMatrix = _$matrix_429.translationMatrix; +lib.rotationMatrix = _$matrix_429.rotationMatrix; +lib.rotationXYMatrix = _$matrix_429.rotationXYMatrix; +lib.apply2DTransform = _$matrix_429.apply2DTransform; +lib.apply2DTransform2 = _$matrix_429.apply2DTransform2; /* removed: var _$angles_408 = require('./angles'); */; lib.deg2rad = _$angles_408.deg2rad; @@ -15387,54 +15397,54 @@ lib.rad2deg = _$angles_408.rad2deg; lib.wrap360 = _$angles_408.wrap360; lib.wrap180 = _$angles_408.wrap180; -/* removed: var _$geometry2d_417 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_417.segmentsIntersect; -lib.segmentDistance = _$geometry2d_417.segmentDistance; -lib.getTextLocation = _$geometry2d_417.getTextLocation; -lib.clearLocationCache = _$geometry2d_417.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_417.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_417.findPointOnPath; +/* removed: var _$geometry2d_418 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_418.segmentsIntersect; +lib.segmentDistance = _$geometry2d_418.segmentDistance; +lib.getTextLocation = _$geometry2d_418.getTextLocation; +lib.clearLocationCache = _$geometry2d_418.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_418.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_418.findPointOnPath; -/* removed: var _$extend_414 = require('./extend'); */; -lib.extendFlat = _$extend_414.extendFlat; -lib.extendDeep = _$extend_414.extendDeep; -lib.extendDeepAll = _$extend_414.extendDeepAll; -lib.extendDeepNoArrays = _$extend_414.extendDeepNoArrays; +/* removed: var _$extend_415 = require('./extend'); */; +lib.extendFlat = _$extend_415.extendFlat; +lib.extendDeep = _$extend_415.extendDeep; +lib.extendDeepAll = _$extend_415.extendDeepAll; +lib.extendDeepNoArrays = _$extend_415.extendDeepNoArrays; -/* removed: var _$loggers_427 = require('./loggers'); */; -lib.log = _$loggers_427.log; -lib.warn = _$loggers_427.warn; -lib.error = _$loggers_427.error; +/* removed: var _$loggers_428 = require('./loggers'); */; +lib.log = _$loggers_428.log; +lib.warn = _$loggers_428.warn; +lib.error = _$loggers_428.error; -/* removed: var _$regex_437 = require('./regex'); */; -lib.counterRegex = _$regex_437.counter; +/* removed: var _$regex_438 = require('./regex'); */; +lib.counterRegex = _$regex_438.counter; -/* removed: var _$throttle_446 = require('./throttle'); */; -lib.throttle = _$throttle_446.throttle; -lib.throttleDone = _$throttle_446.done; -lib.clearThrottle = _$throttle_446.clear; +/* removed: var _$throttle_447 = require('./throttle'); */; +lib.throttle = _$throttle_447.throttle; +lib.throttleDone = _$throttle_447.done; +lib.clearThrottle = _$throttle_447.clear; -lib.getGraphDiv = _$get_graph_div_418; +lib.getGraphDiv = _$get_graph_div_419; -lib._ = _$localize_426; +lib._ = _$localize_427; -lib.notifier = _$notifier_432; +lib.notifier = _$notifier_433; -lib.filterUnique = _$filterUnique_415; -lib.filterVisible = _$filterVisible_416; -lib.pushUnique = _$pushUnique_435; +lib.filterUnique = _$filterUnique_416; +lib.filterVisible = _$filterVisible_417; +lib.pushUnique = _$pushUnique_436; lib.cleanNumber = _$cleanNumber_409; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_89(v)) return __BADNUM_422; + if(!_$fastIsnumeric_89(v)) return __BADNUM_423; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_422; - return _$fastIsnumeric_89(v) ? Number(v) : __BADNUM_422; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_423; + return _$fastIsnumeric_89(v) ? Number(v) : __BADNUM_423; }; -lib.noop = _$noop_431; -lib.identity = _$identity_421; +lib.noop = _$noop_432; +lib.identity = _$identity_422; /** * swap x and y of the same attribute in container cont @@ -15933,6 +15943,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16126,7 +16193,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_422 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_423 = /^\w*$/; /* * Substitute values from an object into a string @@ -16147,7 +16214,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_422.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_423.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16200,7 +16267,7 @@ lib.pseudoRandom = function() { var _$plotcss_1 = {}; 'use strict'; -/* removed: var _$lib_422 = require('../src/lib'); */; +/* removed: var _$lib_423 = require('../src/lib'); */; var rules = { "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;", "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;", @@ -16259,7 +16326,7 @@ for(var selector in rules) { var fullSelector = selector.replace(/^,/,' ,') .replace(/X/g, '.js-plotly-plot .plotly') .replace(/Y/g, '.plotly-notifier'); - _$lib_422.addStyleRule(fullSelector, rules[selector]); + _$lib_423.addStyleRule(fullSelector, rules[selector]); } 'use strict'; @@ -17810,21 +17877,21 @@ var _$arrow_paths_283 = [ */ 'use strict'; -var __counterRegex_471 = _$regex_437.counter; +var __counterRegex_472 = _$regex_438.counter; -var _$constants_471 = { +var _$constants_472 = { idRegex: { - x: __counterRegex_471('x'), - y: __counterRegex_471('y') + x: __counterRegex_472('x'), + y: __counterRegex_472('y') }, - attrRegex: __counterRegex_471('[xy]axis'), + attrRegex: __counterRegex_472('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_471('xaxis'), - yAxisMatch: __counterRegex_471('yaxis'), + xAxisMatch: __counterRegex_472('xaxis'), + yAxisMatch: __counterRegex_472('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -17871,6 +17938,7 @@ var _$constants_471 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -17892,7 +17960,7 @@ var _$constants_471 = { /* removed: var _$arrow_paths_283 = require('./arrow_paths'); */; /* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_471 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_472 = require('../../plots/cartesian/constants'); */; var _$attributes_284 = { @@ -18092,7 +18160,7 @@ var _$attributes_284 = { dflt: 'pixel', values: [ 'pixel', - _$constants_471.idRegex.x.toString() + _$constants_472.idRegex.x.toString() ], editType: 'calc', @@ -18103,7 +18171,7 @@ var _$attributes_284 = { dflt: 'pixel', values: [ 'pixel', - _$constants_471.idRegex.y.toString() + _$constants_472.idRegex.y.toString() ], editType: 'calc', @@ -18114,7 +18182,7 @@ var _$attributes_284 = { valType: 'enumerated', values: [ 'paper', - _$constants_471.idRegex.x.toString() + _$constants_472.idRegex.x.toString() ], editType: 'calc', @@ -18145,7 +18213,7 @@ var _$attributes_284 = { valType: 'enumerated', values: [ 'paper', - _$constants_471.idRegex.y.toString() + _$constants_472.idRegex.y.toString() ], editType: 'calc', @@ -18671,7 +18739,7 @@ var _$align_319 = function align(v, dv, v0, v1, anchor) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; // set cursors pointing toward the closest corner/side, @@ -18687,12 +18755,12 @@ var _$getCursor_320 = 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_422.constrain(Math.floor(x * 3), 0, 2); + else x = _$lib_423.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_422.constrain(Math.floor(y * 3), 0, 2); + else y = _$lib_423.constrain(Math.floor(y * 3), 0, 2); return cursorset[y][x]; }; @@ -19044,7 +19112,7 @@ function isUndefined(arg) { /* global jQuery:false */ -var __EventEmitter_413 = _$EventEmitter_87.EventEmitter; +var __EventEmitter_414 = _$EventEmitter_87.EventEmitter; var Events = { @@ -19054,10 +19122,10 @@ var Events = { * If we have already instantiated an emitter for this plot * return early. */ - if(plotObj._ev instanceof __EventEmitter_413) return plotObj; + if(plotObj._ev instanceof __EventEmitter_414) return plotObj; - var ev = new __EventEmitter_413(); - var internalEv = new __EventEmitter_413(); + var ev = new __EventEmitter_414(); + var internalEv = new __EventEmitter_414(); /* * Assign to plot._ev while we still live in a land @@ -19194,7 +19262,7 @@ var Events = { }; -var _$Events_413 = Events; +var _$Events_414 = Events; var _$unhover_322 = {}; /** @@ -19209,9 +19277,9 @@ var _$unhover_322 = {}; 'use strict'; -/* removed: var _$Events_413 = require('../../lib/events'); */; -/* removed: var _$throttle_446 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_418 = require('../../lib/get_graph_div'); */; +/* removed: var _$Events_414 = require('../../lib/events'); */; +/* removed: var _$throttle_447 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_419 = require('../../lib/get_graph_div'); */; /* removed: var _$constants_336 = require('../fx/constants'); */; @@ -19219,11 +19287,11 @@ var unhover = _$unhover_322 = {}; unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_418(gd); + gd = _$get_graph_div_419(gd); // Important, clear any queued hovers if(gd._fullLayout) { - _$throttle_446.clear(gd._fullLayout._uid + _$constants_336.HOVERID); + _$throttle_447.clear(gd._fullLayout._uid + _$constants_336.HOVERID); } unhover.raw(gd, evt, subplot); @@ -19237,7 +19305,7 @@ unhover.raw = function unhoverRaw(gd, evt) { if(!evt) evt = {}; if(evt.target && - _$Events_413.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + _$Events_414.triggerHandler(gd, 'plotly_beforehover', evt) === false) { return; } @@ -19270,10 +19338,10 @@ var _$dragelement_321 = {}; /* removed: var _$hasHover_173 = require('has-hover'); */; /* removed: var _$hasPassiveEvents_174 = require('has-passive-events'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -/* removed: var _$constants_471 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_472 = require('../../plots/cartesian/constants'); */; /* removed: var _$interactions_402 = require('../../constants/interactions'); */; var dragElement = _$dragelement_321 = {}; @@ -19430,7 +19498,7 @@ dragElement.init = function init(options) { e.preventDefault(); var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_471.MINDRAG; + var minDrag = options.minDrag || _$constants_472.MINDRAG; var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); var dx = dxdy[0]; var dy = dxdy[1]; @@ -19454,7 +19522,7 @@ dragElement.init = function init(options) { e.preventDefault(); if(_$hasHover_173) { - _$lib_422.removeElement(dragCover); + _$lib_423.removeElement(dragCover); } else if(cursor) { dragCover.documentElement.style.cursor = cursor; @@ -19535,7 +19603,7 @@ dragElement.coverSlip = coverSlip; function finishDrag(gd) { gd._dragging = false; - if(gd._replotPending) _$registry_518.call('plot', gd); + if(gd._replotPending) _$registry_519.call('plot', gd); } function pointerOffset(e) { @@ -19646,7 +19714,7 @@ var _$flipScale_311 = function flipScale(scl) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$scales_318 = require('./scales'); */; /* removed: var _$flipScale_311 = require('./flip_scale'); */; @@ -19656,8 +19724,8 @@ var _$calc_306 = function calc(trace, vals, containerStr, cLetter) { var container, inputContainer; if(containerStr) { - container = _$lib_422.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_422.nestedProperty(trace._input, containerStr).get(); + container = _$lib_423.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_423.nestedProperty(trace._input, containerStr).get(); } else { container = trace; @@ -19673,11 +19741,11 @@ var _$calc_306 = function calc(trace, vals, containerStr, cLetter) { scl = container.colorscale; if(auto !== false || min === undefined) { - min = _$lib_422.aggNums(Math.min, null, vals); + min = _$lib_423.aggNums(Math.min, null, vals); } if(auto !== false || max === undefined) { - max = _$lib_422.aggNums(Math.max, null, vals); + max = _$lib_423.aggNums(Math.max, null, vals); } if(min === max) { @@ -19723,9 +19791,9 @@ var _$calc_306 = function calc(trace, vals, containerStr, cLetter) { 'use strict'; -/* removed: var _$lib_422 = require('../lib'); */; -var __extendFlat_451 = _$lib_422.extendFlat; -var __isPlainObject_451 = _$lib_422.isPlainObject; +/* removed: var _$lib_423 = require('../lib'); */; +var __extendFlat_452 = _$lib_423.extendFlat; +var __isPlainObject_452 = _$lib_423.isPlainObject; var traceOpts = { valType: 'flaglist', @@ -19738,7 +19806,7 @@ var layoutOpts = { valType: 'flaglist', extras: ['none'], flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', 'layoutstyle', 'modebar', 'camera', 'arraydraw' ], @@ -19753,7 +19821,7 @@ var traceEditTypeFlags = traceOpts.flags.slice() var layoutEditTypeFlags = layoutOpts.flags.slice() .concat('layoutReplot'); -var _$edit_types_451 = { +var _$edit_types_452 = { traces: traceOpts, layout: layoutOpts, /* @@ -19806,10 +19874,10 @@ function falseObj(keys) { * @return {object} a new attributes object with `editType` modified as directed */ function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_451({}, attrs); + var out = __extendFlat_452({}, attrs); for(var key in out) { var attr = out[key]; - if(__isPlainObject_451(attr)) { + if(__isPlainObject_452(attr)) { out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } @@ -19820,7 +19888,7 @@ function overrideAll(attrs, editTypeOverride, overrideContainers) { function overrideOne(attr, editTypeOverride, overrideContainers, key) { if(attr.valType) { - var out = __extendFlat_451({}, attr); + var out = __extendFlat_452({}, attr); out.editType = editTypeOverride; if(Array.isArray(attr.items)) { @@ -19876,12 +19944,12 @@ _$attributes_323.dash = { /* removed: var _$font_attributes_493 = require('../font_attributes'); */; /* removed: var _$attributes_298 = require('../../components/color/attributes'); */; var dash = _$attributes_323.dash; -var __extendFlat_478 = _$extend_414.extendFlat; +var __extendFlat_479 = _$extend_415.extendFlat; -/* removed: var _$constants_471 = require('./constants'); */; +/* removed: var _$constants_472 = require('./constants'); */; -var _$layout_attributes_478 = { +var _$layout_attributes_479 = { visible: { valType: 'boolean', @@ -19937,10 +20005,10 @@ var _$layout_attributes_478 = { valType: 'info_array', items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} ], - editType: 'plot+margins', + editType: 'axrange+margins', impliedEdits: {'autorange': false}, }, @@ -19956,8 +20024,8 @@ var _$layout_attributes_478 = { scaleanchor: { valType: 'enumerated', values: [ - _$constants_471.idRegex.x.toString(), - _$constants_471.idRegex.y.toString() + _$constants_472.idRegex.x.toString(), + _$constants_472.idRegex.y.toString() ], editType: 'plot', @@ -20101,7 +20169,7 @@ var _$layout_attributes_478 = { editType: 'none', }, - spikedash: __extendFlat_478({}, dash, {dflt: 'dash', editType: 'none'}), + spikedash: __extendFlat_479({}, dash, {dflt: 'dash', editType: 'none'}), spikemode: { valType: 'flaglist', flags: ['toaxis', 'across', 'marker'], @@ -20289,8 +20357,8 @@ var _$layout_attributes_478 = { valType: 'enumerated', values: [ 'free', - _$constants_471.idRegex.x.toString(), - _$constants_471.idRegex.y.toString() + _$constants_472.idRegex.x.toString(), + _$constants_472.idRegex.y.toString() ], editType: 'plot+margins', @@ -20312,8 +20380,8 @@ var _$layout_attributes_478 = { valType: 'enumerated', values: [ 'free', - _$constants_471.idRegex.x.toString(), - _$constants_471.idRegex.y.toString() + _$constants_472.idRegex.x.toString(), + _$constants_472.idRegex.y.toString() ], editType: 'plot', @@ -20386,10 +20454,10 @@ var _$layout_attributes_478 = { 'use strict'; -/* removed: var _$layout_attributes_478 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$layout_attributes_479 = require('../../plots/cartesian/layout_attributes'); */; /* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; -var __extendFlat_300 = _$extend_414.extendFlat; -var __overrideAll_300 = _$edit_types_451.overrideAll; +var __extendFlat_300 = _$extend_415.extendFlat; +var __overrideAll_300 = _$edit_types_452.overrideAll; var _$attributes_300 = __overrideAll_300({ @@ -20474,11 +20542,11 @@ var _$attributes_300 = __overrideAll_300({ }, // a possible line around the bar itself - outlinecolor: _$layout_attributes_478.linecolor, - outlinewidth: _$layout_attributes_478.linewidth, + outlinecolor: _$layout_attributes_479.linecolor, + outlinewidth: _$layout_attributes_479.linewidth, // Should outlinewidth have {dflt: 0} ? // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_478.linecolor, + bordercolor: _$layout_attributes_479.linecolor, borderwidth: { valType: 'number', @@ -20493,30 +20561,30 @@ var _$attributes_300 = __overrideAll_300({ }, // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_478.tickmode, - nticks: _$layout_attributes_478.nticks, - tick0: _$layout_attributes_478.tick0, - dtick: _$layout_attributes_478.dtick, - tickvals: _$layout_attributes_478.tickvals, - ticktext: _$layout_attributes_478.ticktext, - ticks: __extendFlat_300({}, _$layout_attributes_478.ticks, {dflt: ''}), - ticklen: _$layout_attributes_478.ticklen, - tickwidth: _$layout_attributes_478.tickwidth, - tickcolor: _$layout_attributes_478.tickcolor, - showticklabels: _$layout_attributes_478.showticklabels, + tickmode: _$layout_attributes_479.tickmode, + nticks: _$layout_attributes_479.nticks, + tick0: _$layout_attributes_479.tick0, + dtick: _$layout_attributes_479.dtick, + tickvals: _$layout_attributes_479.tickvals, + ticktext: _$layout_attributes_479.ticktext, + ticks: __extendFlat_300({}, _$layout_attributes_479.ticks, {dflt: ''}), + ticklen: _$layout_attributes_479.ticklen, + tickwidth: _$layout_attributes_479.tickwidth, + tickcolor: _$layout_attributes_479.tickcolor, + showticklabels: _$layout_attributes_479.showticklabels, tickfont: _$font_attributes_493({ }), - tickangle: _$layout_attributes_478.tickangle, - tickformat: _$layout_attributes_478.tickformat, - tickformatstops: _$layout_attributes_478.tickformatstops, - tickprefix: _$layout_attributes_478.tickprefix, - showtickprefix: _$layout_attributes_478.showtickprefix, - ticksuffix: _$layout_attributes_478.ticksuffix, - showticksuffix: _$layout_attributes_478.showticksuffix, - separatethousands: _$layout_attributes_478.separatethousands, - exponentformat: _$layout_attributes_478.exponentformat, - showexponent: _$layout_attributes_478.showexponent, + tickangle: _$layout_attributes_479.tickangle, + tickformat: _$layout_attributes_479.tickformat, + tickformatstops: _$layout_attributes_479.tickformatstops, + tickprefix: _$layout_attributes_479.tickprefix, + showtickprefix: _$layout_attributes_479.showtickprefix, + ticksuffix: _$layout_attributes_479.ticksuffix, + showticksuffix: _$layout_attributes_479.showticksuffix, + separatethousands: _$layout_attributes_479.separatethousands, + exponentformat: _$layout_attributes_479.exponentformat, + showexponent: _$layout_attributes_479.showexponent, title: { valType: 'string', @@ -20545,8 +20613,8 @@ var _$attributes_300 = __overrideAll_300({ 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$layout_attributes_478 = require('./layout_attributes'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$layout_attributes_479 = require('./layout_attributes'); */; var _$handleTickLabelDefaults_486 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); @@ -20564,7 +20632,7 @@ var _$handleTickLabelDefaults_486 = function handleTickLabelDefaults(containerIn // explicitly provided var dfltFontColor = (containerOut.color === containerIn.color) ? containerOut.color : font.color; - _$lib_422.coerceFont(coerce, 'tickfont', { + _$lib_423.coerceFont(coerce, 'tickfont', { family: font.family, size: font.size, color: dfltFontColor @@ -20622,7 +20690,7 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_422.coerce(valueIn, valueOut, _$layout_attributes_478.tickformatstops, attr, dflt); + return _$lib_423.coerce(valueIn, valueOut, _$layout_attributes_479.tickformatstops, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -20647,18 +20715,18 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -/* removed: var _$layout_attributes_478 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_479 = require('./layout_attributes'); */; /** * options: inherits outerTicks from axes.handleAxisDefaults */ var _$handleTickDefaults_487 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_422.coerce2(containerIn, containerOut, _$layout_attributes_478, 'ticklen'), - tickWidth = _$lib_422.coerce2(containerIn, containerOut, _$layout_attributes_478, 'tickwidth'), - tickColor = _$lib_422.coerce2(containerIn, containerOut, _$layout_attributes_478, 'tickcolor', containerOut.color), + var tickLen = _$lib_423.coerce2(containerIn, containerOut, _$layout_attributes_479, 'ticklen'), + tickWidth = _$lib_423.coerce2(containerIn, containerOut, _$layout_attributes_479, 'tickwidth'), + tickColor = _$lib_423.coerce2(containerIn, containerOut, _$layout_attributes_479, 'tickcolor', containerOut.color), showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); if(!showTicks) { @@ -20680,7 +20748,7 @@ var _$handleTickDefaults_487 = function handleTickDefaults(containerIn, containe 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; var __ONEDAY_488 = _$numerical_403.ONEDAY; @@ -20731,10 +20799,10 @@ var _$handleTickValueDefaults_488 = function handleTickValueDefaults(containerIn // tick0 can have different valType for different axis types, so // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_422.dateTick0(containerOut.calendar) : 0; + var tick0Dflt = (axType === 'date') ? _$lib_423.dateTick0(containerOut.calendar) : 0; var tick0 = coerce('tick0', tick0Dflt); if(axType === 'date') { - containerOut.tick0 = _$lib_422.cleanDate(tick0, tick0Dflt); + containerOut.tick0 = _$lib_423.cleanDate(tick0, tick0Dflt); } // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely else if(_$fastIsnumeric_89(tick0) && dtick !== 'D1' && dtick !== 'D2') { @@ -20762,7 +20830,7 @@ var _$handleTickValueDefaults_488 = function handleTickValueDefaults(containerIn 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$handleTickValueDefaults_488 = require('../../plots/cartesian/tick_value_defaults'); */; /* removed: var _$handleTickDefaults_487 = require('../../plots/cartesian/tick_mark_defaults'); */; /* removed: var _$handleTickLabelDefaults_486 = require('../../plots/cartesian/tick_label_defaults'); */; @@ -20775,7 +20843,7 @@ var _$colorbarDefaults_302 = function colorbarDefaults(containerIn, containerOut colorbarIn = containerIn.colorbar || {}; function coerce(attr, dflt) { - return _$lib_422.coerce(colorbarIn, colorbarOut, _$attributes_300, attr, dflt); + return _$lib_423.coerce(colorbarIn, colorbarOut, _$attributes_300, attr, dflt); } var thicknessmode = coerce('thicknessmode'); @@ -20796,7 +20864,7 @@ var _$colorbarDefaults_302 = function colorbarDefaults(containerIn, containerOut coerce('y'); coerce('yanchor'); coerce('ypad'); - _$lib_422.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + _$lib_423.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); coerce('outlinecolor'); coerce('outlinewidth'); @@ -20811,7 +20879,7 @@ var _$colorbarDefaults_302 = function colorbarDefaults(containerIn, containerOut _$handleTickDefaults_487(colorbarIn, colorbarOut, coerce, 'linear', opts); coerce('title', layout._dfltTitle.colorbar); - _$lib_422.coerceFont(coerce, 'titlefont', layout.font); + _$lib_423.coerceFont(coerce, 'titlefont', layout.font); coerce('titleside'); }; @@ -20826,11 +20894,11 @@ var _$colorbarDefaults_302 = function colorbarDefaults(containerIn, containerOut 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; var _$hasColorbar_304 = function hasColorbar(container) { - return _$lib_422.isPlainObject(container.colorbar); + return _$lib_423.isPlainObject(container.colorbar); }; /** @@ -20866,7 +20934,7 @@ var _$isValidScale_315 = function isValidScale(scl) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$hasColorbar_304 = require('../colorbar/has_colorbar'); */; /* removed: var _$colorbarDefaults_302 = require('../colorbar/defaults'); */; @@ -20879,10 +20947,10 @@ var _$colorScaleDefaults_309 = function colorScaleDefaults(traceIn, traceOut, la cLetter = opts.cLetter, containerStr = prefix.slice(0, prefix.length - 1), containerIn = prefix ? - _$lib_422.nestedProperty(traceIn, containerStr).get() || {} : + _$lib_423.nestedProperty(traceIn, containerStr).get() || {} : traceIn, containerOut = prefix ? - _$lib_422.nestedProperty(traceOut, containerStr).get() || {} : + _$lib_423.nestedProperty(traceOut, containerStr).get() || {} : traceOut, minIn = containerIn[cLetter + 'min'], maxIn = containerIn[cLetter + 'max'], @@ -20963,17 +21031,17 @@ var _$extractScale_310 = function extractScale(scl, cmin, cmax) { 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$isValidScale_315 = require('./is_valid_scale'); */; var _$hasColorscale_313 = function hasColorscale(trace, containerStr) { var container = containerStr ? - _$lib_422.nestedProperty(trace, containerStr).get() || {} : + _$lib_423.nestedProperty(trace, containerStr).get() || {} : trace; var color = container.color; var isArrayWithOneNumber = false; - if(_$lib_422.isArrayOrTypedArray(color)) { + if(_$lib_423.isArrayOrTypedArray(color)) { for(var i = 0; i < color.length; i++) { if(_$fastIsnumeric_89(color[i])) { isArrayWithOneNumber = true; @@ -20983,12 +21051,12 @@ var _$hasColorscale_313 = function hasColorscale(trace, containerStr) { } return ( - _$lib_422.isPlainObject(container) && ( + _$lib_423.isPlainObject(container) && ( isArrayWithOneNumber || container.showscale === true || (_$fastIsnumeric_89(container.cmin) && _$fastIsnumeric_89(container.cmax)) || _$isValidScale_315(container.colorscale) || - _$lib_422.isPlainObject(container.colorbar) + _$lib_423.isPlainObject(container.colorbar) ) ); }; @@ -21734,7 +21802,7 @@ var _$string_mappings_404 = { } }; -var _$svg_text_utils_445 = {}; +var _$svg_text_utils_446 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21750,7 +21818,7 @@ var _$svg_text_utils_445 = {}; /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$lib_423 = require('../lib'); */; /* removed: var _$xmlns_namespaces_405 = require('../constants/xmlns_namespaces'); */; /* removed: var _$string_mappings_404 = require('../constants/string_mappings'); */; var LINE_SPACING = _$alignment_399.LINE_SPACING; @@ -21763,7 +21831,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_445.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_446.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) @@ -21806,7 +21874,7 @@ _$svg_text_utils_445.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_445.positionText(_context); + _$svg_text_utils_446.positionText(_context); if(_callback) _callback.call(_context); } @@ -21901,7 +21969,7 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_422.randstr([], 64); + var randomID = 'math-output-' + _$lib_423.randstr([], 64); var tmpDiv = _$d3_79.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) @@ -21912,7 +21980,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = _$d3_79.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_422.log('There was an error in the tex syntax.', _texString); + _$lib_423.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -22007,7 +22075,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_445.plainText = function(_str) { +_$svg_text_utils_446.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -22140,14 +22208,14 @@ function buildSVGText(containerNode, str) { // 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_422.log('Ignoring unexpected end tag .', str); + _$lib_423.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_422.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_423.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -22206,7 +22274,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -22221,11 +22292,11 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_445.lineCount = function lineCount(s) { +_$svg_text_utils_446.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_445.positionText = function positionText(s, x, y) { +_$svg_text_utils_446.positionText = function positionText(s, x, y) { return s.each(function() { var text = _$d3_79.select(this); @@ -22301,7 +22372,7 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_445.makeEditable = function(context, options) { +_$svg_text_utils_446.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; var dispatch = _$d3_79.dispatch('edit', 'input', 'cancel'); @@ -22424,7 +22495,7 @@ _$svg_text_utils_445.makeEditable = function(context, options) { // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_553 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_554 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -22460,17 +22531,20 @@ var _$makeBubbleSizeFn_553 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -var _$subtypes_558 = { +var _$subtypes_559 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -22479,8 +22553,8 @@ var _$subtypes_558 = { }, isBubble: function(trace) { - return _$lib_422.isPlainObject(trace.marker) && - _$lib_422.isArrayOrTypedArray(trace.marker.size); + return _$lib_423.isPlainObject(trace.marker) && + _$lib_423.isArrayOrTypedArray(trace.marker.size); } }; @@ -22500,19 +22574,19 @@ var _$drawing_324 = {}; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_264 = require('tinycolor2'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; /* removed: var _$color_299 = require('../color'); */; /* removed: var _$colorscale_314 = require('../colorscale'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; /* removed: var _$xmlns_namespaces_405 = require('../../constants/xmlns_namespaces'); */; /* removed: var _$alignment_399 = require('../../constants/alignment'); */; var __LINE_SPACING_324 = _$alignment_399.LINE_SPACING; var __DESELECTDIM_324 = _$interactions_402.DESELECTDIM; -/* removed: var _$subtypes_558 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_553 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_559 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_554 = require('../../traces/scatter/make_bubble_size_func'); */; var drawing = _$drawing_324 = {}; @@ -22522,7 +22596,7 @@ var drawing = _$drawing_324 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_422.isPlainObject(family)) { + if(_$lib_423.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; @@ -22690,7 +22764,7 @@ drawing.fillGroupStyle = function(s) { shape.call(_$color_299.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_422.error(e, s); + _$lib_423.error(e, s); shape.remove(); } }); @@ -22753,8 +22827,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_518.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_553(trace); + if(_$registry_519.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_554(trace); sel.attr('d', function(d) { var r; @@ -22763,7 +22837,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_558.isBubble(trace) ? + r = _$subtypes_559.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -22803,10 +22877,10 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_422.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_299.defaultLine; + else if(_$lib_423.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_299.defaultLine; else lineColor = markerLine.color; - if(_$lib_422.isArrayOrTypedArray(marker.color)) { + if(_$lib_423.isArrayOrTypedArray(marker.color)) { fillColor = _$color_299.defaultLine; perPointGradient = true; } @@ -22859,7 +22933,7 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_422.identity); + .data([type + color1 + color2], _$lib_423.identity); gradient.exit().remove(); @@ -22902,9 +22976,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_423.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -23010,7 +23082,7 @@ drawing.selectedPointStyle = function(s, trace) { }); } - if(_$registry_518.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_519.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { var pt = _$d3_79.select(this); var mx = d.mx || marker.symbol || 0; @@ -23025,16 +23097,16 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_422.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_423.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_422.isArrayOrTypedArray(colorArray)) { + if(scl && _$lib_423.isArrayOrTypedArray(colorArray)) { return _$colorscale_314.makeColorScaleFunc( _$colorscale_314.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_422.identity; + else return _$lib_423.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; @@ -23054,7 +23126,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_445.lineCount(s) - 1) * __LINE_SPACING_324 + 1; + var numLines = (_$svg_text_utils_446.lineCount(s) - 1) * __LINE_SPACING_324 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -23073,7 +23145,7 @@ function extracTextFontSize(d, trace) { drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { var p = _$d3_79.select(this); - var text = _$lib_422.extractOption(d, trace, 'tx', 'text'); + var text = _$lib_423.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -23088,7 +23160,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_445.convertToTspans, gd) + .call(_$svg_text_utils_446.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -23216,33 +23288,28 @@ drawing.steps = function(shape) { // 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 = _$d3_79.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_405.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_423.ensureSingleById(_$d3_79.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_405.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_423.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; @@ -23287,7 +23354,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_422.extendFlat({}, out); + if(out) return _$lib_423.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -23331,7 +23398,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_422.extendFlat({}, out); + if(out) return _$lib_423.extendFlat({}, out); } } var testNode, tester; @@ -23349,7 +23416,7 @@ drawing.bBox = function(node, inTester, hash) { // standardize its position (and newline tspans if any) _$d3_79.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_445.positionText, 0, 0); + .call(_$svg_text_utils_446.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -23379,7 +23446,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_422.extendFlat({}, bb); + return _$lib_423.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -23404,15 +23471,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_79.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_79.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -23560,8 +23633,8 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; var _$calc_334 = function calc(gd) { var calcdata = gd.calcdata; @@ -23569,7 +23642,7 @@ var _$calc_334 = function calc(gd) { function makeCoerceHoverInfo(trace) { return function(val) { - return _$lib_422.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + return _$lib_423.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); }; } @@ -23580,9 +23653,9 @@ var _$calc_334 = function calc(gd) { // 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_518.traceIs(trace, 'pie')) continue; + if(_$registry_519.traceIs(trace, 'pie')) continue; - var fillFn = _$registry_518.traceIs(trace, '2dMap') ? paste : _$lib_422.fillArray; + var fillFn = _$registry_519.traceIs(trace, '2dMap') ? paste : _$lib_423.fillArray; fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); @@ -23598,7 +23671,7 @@ var _$calc_334 = function calc(gd) { }; function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_422.identity; + fn = fn || _$lib_423.identity; if(Array.isArray(traceAttr)) { cd[0][cdAttr] = fn(traceAttr); @@ -23616,13 +23689,33 @@ var _$helpers_338 = {}; 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; // look for either subplot or xaxis and yaxis attributes +// does not handle splom case _$helpers_338.getSubplot = function getSubplot(trace) { return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; }; +// is trace in given list of subplots? +// does handle splom case +_$helpers_338.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_338.getSubplot(trace)) !== -1; +}; + // convenience functions for mapping all relevant axes _$helpers_338.flat = function flat(subplots, v) { var out = new Array(subplots.length); @@ -23765,7 +23858,7 @@ _$helpers_338.appendArrayPointValue = function(pointData, trace, pointNumber) { var key = getPointKey(astr); if(pointData[key] === undefined) { - var val = _$lib_422.nestedProperty(trace, astr).get(); + var val = _$lib_423.nestedProperty(trace, astr).get(); var pointVal = getPointData(val, pointNumber); if(pointVal !== undefined) pointData[key] = pointVal; @@ -23795,7 +23888,7 @@ _$helpers_338.appendArrayMultiPointValues = function(pointData, trace, pointNumb var key = getPointKey(astr); if(pointData[key] === undefined) { - var val = _$lib_422.nestedProperty(trace, astr).get(); + var val = _$lib_423.nestedProperty(trace, astr).get(); var keyVal = new Array(pointNumbers.length); for(var j = 0; j < pointNumbers.length; j++) { @@ -23842,7 +23935,7 @@ function getPointData(val, pointNumber) { // works with our CSS cursor classes (see css/_cursor.scss) // to apply cursors to d3 single-element selections. // omit cursor to revert to the default. -var _$setCursor_441 = function setCursor(el3, csr) { +var _$setCursor_442 = function setCursor(el3, csr) { (el3.attr('class') || '').split(' ').forEach(function(cls) { if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); }); @@ -23861,7 +23954,7 @@ var _$setCursor_441 = function setCursor(el3, csr) { 'use strict'; -/* removed: var _$setCursor_441 = require('./setcursor'); */; +/* removed: var _$setCursor_442 = require('./setcursor'); */; var STASHATTR = 'data-savedcursor'; var NO_CURSOR = '!!'; @@ -23872,7 +23965,7 @@ var NO_CURSOR = '!!'; * by moving the name of the original cursor to the data-savedcursor attr. * omit cursor to revert to the previously set value. */ -var _$overrideCursor_433 = function overrideCursor(el3, csr) { +var _$overrideCursor_434 = function overrideCursor(el3, csr) { var savedCursor = el3.attr(STASHATTR); if(csr) { if(!savedCursor) { @@ -23888,13 +23981,13 @@ var _$overrideCursor_433 = function overrideCursor(el3, csr) { el3.attr(STASHATTR, NO_CURSOR); } } - _$setCursor_441(el3, csr); + _$setCursor_442(el3, csr); } else if(savedCursor) { el3.attr(STASHATTR, null); - if(savedCursor === NO_CURSOR) _$setCursor_441(el3); - else _$setCursor_441(el3, savedCursor); + if(savedCursor === NO_CURSOR) _$setCursor_442(el3); + else _$setCursor_442(el3, savedCursor); } }; @@ -23908,7 +24001,7 @@ var _$overrideCursor_433 = function overrideCursor(el3, csr) { 'use strict'; -var _$animation_attributes_461 = { +var _$animation_attributes_462 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -24055,7 +24148,7 @@ var _$frame_attributes_494 = { 'use strict'; /* removed: var _$attributes_305 = require('./attributes'); */; -var __extendFlat_307 = _$extend_414.extendFlat; +var __extendFlat_307 = _$extend_415.extendFlat; /* removed: var _$scales_318 = require('./scales.js'); */; /* @@ -24121,7 +24214,7 @@ var _$makeColorScaleAttributes_307 = function makeColorScaleAttributes(context, 'use strict'; -var _$constants_542 = { +var _$constants_543 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -24149,13 +24242,13 @@ var _$constants_542 = { /* removed: var _$makeColorScaleAttributes_307 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_300 = require('../../components/colorbar/attributes'); */; /* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; -var __dash_536 = _$attributes_323.dash; +var __dash_537 = _$attributes_323.dash; /* removed: var _$drawing_324 = require('../../components/drawing'); */; -/* removed: var _$constants_542 = require('./constants'); */; -var __extendFlat_536 = _$extend_414.extendFlat; +/* removed: var _$constants_543 = require('./constants'); */; +var __extendFlat_537 = _$extend_415.extendFlat; -var _$attributes_536 = { +var _$attributes_537 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -24257,7 +24350,7 @@ var _$attributes_536 = { editType: 'plot', }, - dash: __extendFlat_536({}, __dash_536, {editType: 'style'}), + dash: __extendFlat_537({}, __dash_537, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -24297,7 +24390,7 @@ var _$attributes_536 = { editType: 'style', }, - marker: __extendFlat_536({ + marker: __extendFlat_537({ symbol: { valType: 'enumerated', values: _$drawing_324.symbolList, @@ -24366,7 +24459,7 @@ var _$attributes_536 = { }, colorbar: _$attributes_300, - line: __extendFlat_536({ + line: __extendFlat_537({ width: { valType: 'number', min: 0, @@ -24517,12 +24610,12 @@ var _$attributes_536 = { 'use strict'; -/* removed: var _$attributes_536 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_536.marker; +/* removed: var _$attributes_537 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_537.marker; var _$area_attributes_511 = { - r: _$attributes_536.r, - t: _$attributes_536.t, + r: _$attributes_537.r, + t: _$attributes_537.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -24543,11 +24636,11 @@ var _$area_attributes_511 = { 'use strict'; -/* removed: var _$layout_attributes_478 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_512 = _$extend_414.extendFlat; -var __overrideAll_512 = _$edit_types_451.overrideAll; +/* removed: var _$layout_attributes_479 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_512 = _$extend_415.extendFlat; +var __overrideAll_512 = _$edit_types_452.overrideAll; -var domainAttr = __extendFlat_512({}, _$layout_attributes_478.domain, { +var domainAttr = __extendFlat_512({}, _$layout_attributes_479.domain, { }); @@ -24647,7 +24740,7 @@ var _$axis_attributes_512 = __overrideAll_512({ } }, 'plot', 'nested'); -var _$plot_schema_457 = {}; +var _$plot_schema_458 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -24659,22 +24752,23 @@ var _$plot_schema_457 = {}; 'use strict'; -/* removed: var _$registry_518 = require('../registry'); */; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$registry_519 = require('../registry'); */; +/* removed: var _$lib_423 = require('../lib'); */; -/* removed: var _$attributes_463 = require('../plots/attributes'); */; +/* removed: var _$attributes_464 = require('../plots/attributes'); */; /* removed: var _$layout_attributes_508 = require('../plots/layout_attributes'); */; /* removed: var _$frame_attributes_494 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_461 = require('../plots/animation_attributes'); */; +/* removed: var _$animation_attributes_462 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet /* removed: var _$area_attributes_511 = require('../plots/polar/legacy/area_attributes'); */; /* removed: var _$axis_attributes_512 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_451 = require('./edit_types'); */; +/* removed: var _$edit_types_452 = require('./edit_types'); */; -var __extendFlat_457 = _$lib_422.extendFlat; -var __extendDeepAll_457 = _$lib_422.extendDeepAll; +var __extendFlat_458 = _$lib_423.extendFlat; +var __extendDeepAll_458 = _$lib_423.extendDeepAll; +var __isPlainObject_458 = _$lib_423.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -24682,10 +24776,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_457.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_457.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_457.DEPRECATED = DEPRECATED; -_$plot_schema_457.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_458.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_458.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_458.DEPRECATED = DEPRECATED; +_$plot_schema_458.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -24698,26 +24792,26 @@ _$plot_schema_457.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_457.get = function() { +_$plot_schema_458.get = function() { var traces = {}; - _$registry_518.allTypes.concat('area').forEach(function(type) { + _$registry_519.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_518.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_519.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_422.valObjectMeta, + valObjects: _$lib_423.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_451.traces, - layout: _$edit_types_451.layout + traces: _$edit_types_452.traces, + layout: _$edit_types_452.layout }, impliedEdits: { @@ -24730,7 +24824,7 @@ _$plot_schema_457.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_461) + animation: formatAttributes(_$animation_attributes_462) }; }; @@ -24761,7 +24855,7 @@ _$plot_schema_457.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_457.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_458.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -24773,10 +24867,10 @@ _$plot_schema_457.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_457.isValObject(attr)) return; + if(_$plot_schema_458.isValObject(attr)) return; - if(_$lib_422.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_457.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_458(attr) && attrName !== 'impliedEdits') { + _$plot_schema_458.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -24788,7 +24882,7 @@ _$plot_schema_457.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_457.isValObject = function(obj) { +_$plot_schema_458.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -24802,7 +24896,7 @@ _$plot_schema_457.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_457.findArrayAttributes = function(trace) { +_$plot_schema_458.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -24825,8 +24919,8 @@ _$plot_schema_457.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_422.nestedProperty(trace, astr).get(); - if(!_$lib_422.isArrayOrTypedArray(val)) return; + var val = _$lib_423.nestedProperty(trace, astr).get(); + if(!_$lib_423.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -24835,9 +24929,9 @@ _$plot_schema_457.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_457.crawl(_$attributes_463, callback); + _$plot_schema_458.crawl(_$attributes_464, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_457.crawl(trace._module.attributes, callback); + _$plot_schema_458.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -24850,7 +24944,7 @@ _$plot_schema_457.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_457.crawl(module.attributes, callback, 1); + _$plot_schema_458.crawl(module.attributes, callback, 1); } } } @@ -24862,8 +24956,8 @@ _$plot_schema_457.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_457.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_422.filterUnique(arrayAttributes); + _$plot_schema_458.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_423.filterUnique(arrayAttributes); } return arrayAttributes; @@ -24884,18 +24978,19 @@ _$plot_schema_457.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_457.getTraceValObject = function(trace, parts) { +_$plot_schema_458.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_518.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_519.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } @@ -24906,7 +25001,7 @@ _$plot_schema_457.getTraceValObject = function(trace, parts) { // 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_518.modules[trace.type || _$attributes_463.type.dflt] || {})._module; + if(!_module) _module = (_$registry_519.modules[trace.type || _$attributes_464.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -24921,7 +25016,7 @@ _$plot_schema_457.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_463[head]; + if(!valObject) valObject = _$attributes_464[head]; } return recurseIntoValObject(valObject, parts, i); @@ -24940,7 +25035,7 @@ _$plot_schema_457.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_457.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_458.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -24991,8 +25086,8 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_518.componentsRegistry) { - _module = _$registry_518.componentsRegistry[key]; + for(key in _$registry_519.componentsRegistry) { + _module = _$registry_519.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } @@ -25022,7 +25117,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_422.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_458(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -25069,7 +25164,7 @@ function getTraceAttributes(type) { basePlotModule = {}; } else { - _module = _$registry_518.modules[type]._module, + _module = _$registry_519.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -25079,14 +25174,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_457(attributes, _$attributes_463); + __extendDeepAll_458(attributes, _$attributes_464); // module attributes - __extendDeepAll_457(attributes, _module.attributes); + __extendDeepAll_458(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_457(attributes, basePlotModule.attributes); + __extendDeepAll_458(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -25101,7 +25196,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_457(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_458(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -25113,21 +25208,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_457(layoutAttributes, _$layout_attributes_508); + __extendDeepAll_458(layoutAttributes, _$layout_attributes_508); // add base plot module layout attributes - for(key in _$registry_518.subplotsRegistry) { - _module = _$registry_518.subplotsRegistry[key]; + for(key in _$registry_519.subplotsRegistry) { + _module = _$registry_519.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -25136,8 +25230,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_518.componentsRegistry) { - _module = _$registry_518.componentsRegistry[key]; + for(key in _$registry_519.componentsRegistry) { + _module = _$registry_519.componentsRegistry[key]; var schema = _module.schema; /* @@ -25168,12 +25262,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_518.transformsRegistry[type]; - var attributes = __extendDeepAll_457({}, _module.attributes); + var _module = _$registry_519.transformsRegistry[type]; + var attributes = __extendDeepAll_458({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_518.componentsRegistry).forEach(function(k) { - var _module = _$registry_518.componentsRegistry[k]; + Object.keys(_$registry_519.componentsRegistry).forEach(function(k) { + var _module = _$registry_519.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -25189,7 +25283,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_422.extendDeepAll({}, _$frame_attributes_494) + frames: _$lib_423.extendDeepAll({}, _$frame_attributes_494) }; formatAttributes(attrs); @@ -25200,6 +25294,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -25216,7 +25311,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_457.isValObject(attr)) { + if(_$plot_schema_458.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -25228,13 +25323,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_422.isPlainObject(attr)) { + else if(__isPlainObject_458(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_457.crawl(attrs, callback); + _$plot_schema_458.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -25253,35 +25348,58 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_457.crawl(attrs, callback); + _$plot_schema_458.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_458(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_457(layoutAttributes, { + __extendFlat_458(layoutAttributes, { radialaxis: _$axis_attributes_512.radialaxis, angularaxis: _$axis_attributes_512.angularaxis }); - __extendFlat_457(layoutAttributes, _$axis_attributes_512.layout); + __extendFlat_458(layoutAttributes, _$axis_attributes_512.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_422.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_457({}, _module.layoutAttributes); + var np = _$lib_423.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_458({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_422.nestedProperty(baseAttrs, astr); + var np = _$lib_423.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_457(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_458(np.get() || {}, newAttrs)); } -var _$axis_ids_469 = {}; +var _$axis_ids_470 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -25292,30 +25410,30 @@ var _$axis_ids_469 = {}; 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; -/* removed: var _$constants_471 = require('./constants'); */; +/* removed: var _$constants_472 = require('./constants'); */; // 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. -_$axis_ids_469.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_471.AX_ID_PATTERN)) return; +_$axis_ids_470.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_472.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_469.name2id = function name2id(name) { - if(!name.match(_$constants_471.AX_NAME_PATTERN)) return; +_$axis_ids_470.name2id = function name2id(name) { + if(!name.match(_$constants_472.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_469.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_471.AX_ID_PATTERN)) return; +_$axis_ids_470.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_472.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -25324,11 +25442,11 @@ _$axis_ids_469.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_469.list = function(gd, axLetter, only2d) { +_$axis_ids_470.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_469.listIds(gd, axLetter); + var idList = _$axis_ids_470.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -25353,7 +25471,7 @@ _$axis_ids_469.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_469.listIds = function(gd, axLetter) { +_$axis_ids_470.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -25364,35 +25482,35 @@ _$axis_ids_469.listIds = function(gd, axLetter) { // 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 -_$axis_ids_469.getFromId = function(gd, id, type) { +_$axis_ids_470.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[_$axis_ids_469.id2name(id)]; + return fullLayout[_$axis_ids_470.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_469.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_470.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_518.traceIs(fullTrace, 'gl3d')) { + if(_$registry_519.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_469.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_470.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_469.idSort = function(id1, id2) { +_$axis_ids_470.idSort = function(id1, id2) { var letter1 = id1.charAt(0); var letter2 = id2.charAt(0); if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1; @@ -25410,8 +25528,8 @@ var _$command_491 = {}; 'use strict'; -/* removed: var _$registry_518 = require('../registry'); */; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$registry_519 = require('../registry'); */; +/* removed: var _$lib_423 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -25515,7 +25633,7 @@ _$command_491.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_422.log('Unable to automatically bind plot updates to API command'); + _$lib_423.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -25633,7 +25751,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_422.nestedProperty(container, binding.prop).get(); + value = _$lib_423.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -25665,7 +25783,7 @@ function bindingValueHasChanged(gd, binding, cache) { _$command_491.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_518.apiMethodRegistry[method]; + var _method = _$registry_519.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -25674,7 +25792,7 @@ _$command_491.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_422.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_423.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; @@ -25724,7 +25842,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_422.isPlainObject(astr)) { + } else if(_$lib_423.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -25748,7 +25866,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_422.isPlainObject(astr)) { + } else if(_$lib_423.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -25814,7 +25932,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_422.isPlainObject(attr)) { + if(_$lib_423.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -25823,6 +25941,32 @@ function crawl(attrs, callback, path, depth) { }); } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_517 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + var _$plots_510 = {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -25838,25 +25982,27 @@ var _$plots_510 = {}; /* removed: var _$d3_79 = require('d3'); */; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$registry_518 = require('../registry'); */; -/* removed: var _$plot_schema_457 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_469 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_422 = require('../lib'); */; -var _ = _$lib_422._; +/* removed: var _$registry_519 = require('../registry'); */; +/* removed: var _$plot_schema_458 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_423 = require('../lib'); */; /* removed: var _$color_299 = require('../components/color'); */; var __BADNUM_510 = _$numerical_403.BADNUM; -var plots = _$plots_510 = {}; +/* removed: var _$axis_ids_470 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_510 = _$sort_modules_517.sortBasePlotModules; -/* removed: var _$animation_attributes_461 = require('./animation_attributes'); */; +/* removed: var _$animation_attributes_462 = require('./animation_attributes'); */; /* removed: var _$frame_attributes_494 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_422.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_423.relinkPrivateKeys; +var _ = _$lib_423._; + +var plots = _$plots_510 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_422.extendFlat(plots, _$registry_518); +_$lib_423.extendFlat(plots, _$registry_519); -plots.attributes = _$attributes_463; +plots.attributes = _$attributes_464; plots.attributes.type.values = plots.allTypes; plots.fontAttrs = _$font_attributes_493; plots.layoutAttributes = _$layout_attributes_508; @@ -25876,15 +26022,15 @@ plots.hasSimpleAPICommandBindings = _$command_491.hasSimpleAPICommandBindings; // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_422.getGraphDiv(gd); + gd = _$lib_423.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_518.getComponentMethod('annotations', 'draw')(gd); - _$registry_518.getComponentMethod('legend', 'draw')(gd); + _$registry_519.getComponentMethod('annotations', 'draw')(gd); + _$registry_519.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -25897,7 +26043,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_422.getGraphDiv(gd); + gd = _$lib_423.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -25928,7 +26074,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_518.call('relayout', gd, {autosize: true}).then(function() { + _$registry_519.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -25958,12 +26104,8 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_423.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', 'fill': _$color_299.defaultLine, @@ -25975,12 +26117,11 @@ plots.addLinks = function(gd) { links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -26118,6 +26259,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -26152,7 +26295,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -26195,12 +26337,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_519.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_423.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_423.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_423.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -26211,7 +26379,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -26220,6 +26388,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -26230,7 +26409,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -26242,17 +26421,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_469.list(gd); + var axList = _$axis_ids_470.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -26262,6 +26441,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_510); }; /** @@ -26280,7 +26462,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_518.subplotsRegistry; + var subplotsRegistry = _$registry_519.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -26293,7 +26475,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_422.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_423.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -26314,14 +26496,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_422.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_423.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_422.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_423.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -26366,7 +26548,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_518.localeRegistry; + locales = _$registry_519.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -26375,7 +26557,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_518.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_519.localeRegistry.en.format); return formatObj; } @@ -26427,30 +26609,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_519.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -26458,7 +26638,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -26530,8 +26710,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_469.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_469.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_470.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_470.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -26576,13 +26756,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_469.list(mockGd, null, true); + var axList = _$axis_ids_470.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_469.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_470.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -26604,7 +26784,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_469.getFromId(mockGd, ax.anchor); + _$axis_ids_470.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -26633,7 +26813,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_469.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_470.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -26674,17 +26854,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_457.crawl( + _$plot_schema_458.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_422.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_423.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_422.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_423.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -26706,8 +26886,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_422.pushUnique(modules, _module); - _$lib_422.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_423.pushUnique(modules, _module); + _$lib_423.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -26767,11 +26947,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_518.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_519.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_518.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_519.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -26800,7 +26980,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(opts || {}, optsOut, _$animation_attributes_461, attr, dflt); + return _$lib_423.coerce(opts || {}, optsOut, _$animation_attributes_462, attr, dflt); } coerce('mode'); @@ -26832,7 +27012,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(opts || {}, optsOut, _$animation_attributes_461.frame, attr, dflt); + return _$lib_423.coerce(opts || {}, optsOut, _$animation_attributes_462.frame, attr, dflt); } coerce('duration'); @@ -26845,7 +27025,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(opts || {}, optsOut, _$animation_attributes_461.transition, attr, dflt); + return _$lib_423.coerce(opts || {}, optsOut, _$animation_attributes_462.transition, attr, dflt); } coerce('duration'); @@ -26858,7 +27038,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(frameIn, frameOut, _$frame_attributes_494, attr, dflt); + return _$lib_423.coerce(frameIn, frameOut, _$frame_attributes_494, attr, dflt); } coerce('group'); @@ -26879,7 +27059,7 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) var i; function coerce(attr, dflt) { - return _$lib_422.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_423.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -26895,9 +27075,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -26907,18 +27087,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_422.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_423.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_422.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_423.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_422.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_423.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_422.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_423.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -26928,12 +27108,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_518.traceIs(traceOut, 'showLegend')) { + if(_$registry_519.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_518.getComponentMethod( + _$registry_519.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -26942,12 +27122,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_422.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_423.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_518.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_519.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_518.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_519.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -26991,17 +27171,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_422.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_423.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_422.pushUnique(transformModules, _module); + _$lib_423.pushUnique(transformModules, _module); } else { - transformOut = _$lib_422.extendFlat({}, transformIn); + transformOut = _$lib_423.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -27033,14 +27213,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_422.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_423.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_422.coerceFont(coerce, 'font'); + var globalFont = _$lib_423.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_422.coerceFont(coerce, 'titlefont', { + _$lib_423.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -27068,7 +27248,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_518.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_519.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -27079,12 +27259,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_518.getComponentMethod( + _$registry_519.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_518.getComponentMethod( + _$registry_519.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -27096,7 +27276,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_422.isPlotDiv(gd); + var isPlotDiv = _$lib_423.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -27184,11 +27364,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_518.componentsRegistry; + var componentsRegistry = _$registry_519.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_518.subplotsRegistry.cartesian; + var Cartesian = _$registry_519.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -27207,13 +27387,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_518.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_519.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_422.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_423.subplotSort); } // base plot module layout defaults @@ -27285,7 +27465,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_422.clearThrottle(); + _$lib_423.clearThrottle(); // data and layout delete gd.data; @@ -27341,7 +27521,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_422.pushUnique(styleModules, _module.style); + _$lib_423.pushUnique(styleModules, _module.style); } } @@ -27496,7 +27676,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_518.call('plot', gd); + return _$registry_519.call('plot', gd); } }; @@ -27537,7 +27717,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_422.isPlainObject(d)) { + if(_$lib_423.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -27560,7 +27740,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_422.isPlainObject(d.stream)) { + if(!_$lib_423.isPlainObject(d.stream)) { continue; } } @@ -27586,7 +27766,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_422.isJSDate(d)) return _$lib_422.ms2DateTimeLocal(+d); + if(_$lib_423.isJSDate(d)) return _$lib_423.ms2DateTimeLocal(+d); return d; } @@ -27783,8 +27963,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_422.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_422.expandObjectPaths(copy); + var copy = _$lib_423.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_423.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -27792,29 +27972,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_422.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_423.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_422.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_423.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_422.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_423.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_422.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_423.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_422.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_423.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_422.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_423.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -27839,7 +28019,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_518.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_519.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -27913,7 +28093,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_422.expandObjectPaths(_$lib_422.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_423.expandObjectPaths(_$lib_423.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -27940,7 +28120,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_518.getComponentMethod('errorbars', 'calc')(gd); + _$registry_519.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -27988,7 +28168,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_518.call('redraw', gd); + return _$registry_519.call('redraw', gd); }); } @@ -28020,7 +28200,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_422.expandObjectPaths(layout); + var newLayout = _$lib_423.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -28030,7 +28210,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_422.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_423.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -28060,7 +28240,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_518.call('redraw', gd); + return _$registry_519.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -28095,7 +28275,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_422.syncOrAsync(seq, gd); + var transitionStarting = _$lib_423.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -28107,7 +28287,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_469.list(gd), + var axList = _$axis_ids_470.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -28151,7 +28331,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_457.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_458.findArrayAttributes(trace); } // add polar axes to axis list @@ -28195,14 +28375,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -28237,7 +28418,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_518.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_519.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -28288,7 +28474,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_422.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_423.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -28310,11 +28496,11 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$drawing_324 = require('../drawing'); */; /* removed: var _$color_299 = require('../color'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; /* removed: var _$interactions_402 = require('../../constants/interactions'); */; var _$titles_392 = { @@ -28395,10 +28581,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_423.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -28416,7 +28599,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_422.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_423.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -28444,7 +28627,7 @@ function draw(gd, titleClass, options) { 'font-weight': _$plots_510.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_445.convertToTspans, gd); + .call(_$svg_text_utils_446.convertToTspans, gd); return _$plots_510.previousPromises(gd); } @@ -28494,7 +28677,7 @@ function draw(gd, titleClass, options) { avoid.selection.each(function() { var avoidbb = _$drawing_324.bBox(this); - if(_$lib_422.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_423.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -28534,12 +28717,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_445.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_446.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_518.call('restyle', gd, prop, text, traceIndex); + _$registry_519.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_518.call('relayout', gd, prop, text); + _$registry_519.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -28548,7 +28731,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_445.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_446.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -28569,10 +28752,10 @@ function draw(gd, titleClass, options) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -var __FP_SAFE_465 = _$numerical_403.FP_SAFE; +/* removed: var _$lib_423 = require('../../lib'); */; +var __FP_SAFE_466 = _$numerical_403.FP_SAFE; -var _$autorange_465 = { +var _$autorange_466 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -28617,7 +28800,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_422.simpleMap(ax.range, ax.r2l); + var rng = _$lib_423.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -28710,7 +28893,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_422.simpleMap(newRange, ax.l2r || Number); + return _$lib_423.simpleMap(newRange, ax.l2r || Number); } /* @@ -28742,7 +28925,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_422.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_423.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -28764,7 +28947,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_422.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_423.extendFlat({}, axeRangeOpts); } } @@ -28777,6 +28960,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -28837,14 +29022,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_465) vmax = v; + if(v > vmax && v < __FP_SAFE_466) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_465) vmin = v; - if(v > vmax && v < __FP_SAFE_465) vmax = v; + if(v < vmin && v > -__FP_SAFE_466) vmin = v; + if(v > vmax && v < __FP_SAFE_466) vmax = v; } } @@ -28878,7 +29063,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_465 : __lessOrEqual_465; + var atLeastAsExtreme = k ? __greaterOrEqual_466 : __lessOrEqual_466; includeThis = true; /* @@ -28929,11 +29114,11 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_89(v) && Math.abs(v) < __FP_SAFE_465; + return _$fastIsnumeric_89(v) && Math.abs(v) < __FP_SAFE_466; } -function __lessOrEqual_465(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_465(v0, v1) { return v0 >= v1; } +function __lessOrEqual_466(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_466(v0, v1) { return v0 >= v1; } /** * Copyright 2012-2018, Plotly, Inc. @@ -28948,10 +29133,10 @@ function __greaterOrEqual_465(v0, v1) { return v0 >= v1; } /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -var __BADNUM_467 = _$numerical_403.BADNUM; +/* removed: var _$lib_423 = require('../../lib'); */; +var __BADNUM_468 = _$numerical_403.BADNUM; -var _$autoType_467 = function autoType(array, calendar) { +var _$autoType_468 = function autoType(array, calendar) { if(moreDates(array, calendar)) return 'date'; if(category(array)) return 'category'; if(linearOK(array)) return 'linear'; @@ -28984,7 +29169,7 @@ function moreDates(a, calendar) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_422.isDateTime(ai, calendar)) dcnt += 1; + if(_$lib_423.isDateTime(ai, calendar)) dcnt += 1; if(_$fastIsnumeric_89(ai)) ncnt += 1; } @@ -29002,7 +29187,7 @@ function category(a) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_422.cleanNumber(ai) !== __BADNUM_467) curvenums++; + if(_$lib_423.cleanNumber(ai) !== __BADNUM_468) curvenums++; else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; } @@ -29023,18 +29208,18 @@ function category(a) { /* removed: var _$d3_79 = require('d3'); */; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -var cleanNumber = _$lib_422.cleanNumber; -var ms2DateTime = _$lib_422.ms2DateTime; -var dateTime2ms = _$lib_422.dateTime2ms; -var ensureNumber = _$lib_422.ensureNumber; +/* removed: var _$lib_423 = require('../../lib'); */; +var cleanNumber = _$lib_423.cleanNumber; +var ms2DateTime = _$lib_423.ms2DateTime; +var dateTime2ms = _$lib_423.dateTime2ms; +var ensureNumber = _$lib_423.ensureNumber; /* removed: var _$numerical_403 = require('../../constants/numerical'); */; var __FP_SAFE_485 = _$numerical_403.FP_SAFE; var __BADNUM_485 = _$numerical_403.BADNUM; -/* removed: var _$constants_471 = require('./constants'); */; -/* removed: var _$axis_ids_469 = require('./axis_ids'); */; +/* removed: var _$constants_472 = require('./constants'); */; +/* removed: var _$axis_ids_470 = require('./axis_ids'); */; function fromLog(v) { return Math.pow(10, v); @@ -29226,7 +29411,7 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { * 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_422.identity; + ax.d2r = ax.r2d = _$lib_423.identity; ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; @@ -29234,7 +29419,7 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { 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_422.cleanDate(v, __BADNUM_485, ax.calendar); }; + ax.cleanPos = function(v) { return _$lib_423.cleanDate(v, __BADNUM_485, ax.calendar); }; } else if(ax.type === 'category') { // d is categories (string) @@ -29291,39 +29476,39 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { if(!opts) opts = {}; if(!rangeAttr) rangeAttr = 'range'; - var range = _$lib_422.nestedProperty(ax, rangeAttr).get(); + var range = _$lib_423.nestedProperty(ax, rangeAttr).get(); var i, dflt; - if(ax.type === 'date') dflt = _$lib_422.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_471.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_471.DFLTRANGEX; + if(ax.type === 'date') dflt = _$lib_423.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_472.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_472.DFLTRANGEX; // make sure we don't later mutate the defaults dflt = dflt.slice(); if(!range || range.length !== 2) { - _$lib_422.nestedProperty(ax, rangeAttr).set(dflt); + _$lib_423.nestedProperty(ax, rangeAttr).set(dflt); return; } if(ax.type === 'date') { // check if milliseconds or js date objects are provided for range // and convert to date strings - range[0] = _$lib_422.cleanDate(range[0], __BADNUM_485, ax.calendar); - range[1] = _$lib_422.cleanDate(range[1], __BADNUM_485, ax.calendar); + range[0] = _$lib_423.cleanDate(range[0], __BADNUM_485, ax.calendar); + range[1] = _$lib_423.cleanDate(range[1], __BADNUM_485, ax.calendar); } for(i = 0; i < 2; i++) { if(ax.type === 'date') { - if(!_$lib_422.isDateTime(range[i], ax.calendar)) { + if(!_$lib_423.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_422.constrain(ax.r2l(range[0]), - _$lib_422.MIN_MS + 1000, _$lib_422.MAX_MS - 1000); + var linCenter = _$lib_423.constrain(ax.r2l(range[0]), + _$lib_423.MIN_MS + 1000, _$lib_423.MAX_MS - 1000); range[0] = ax.l2r(linCenter - 1000); range[1] = ax.l2r(linCenter + 1000); break; @@ -29365,7 +29550,7 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { // make sure we have a domain (pull it in from the axis // this one is overlaying if necessary) if(ax.overlaying) { - var ax2 = _$axis_ids_469.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + var ax2 = _$axis_ids_470.getFromId({ _fullLayout: fullLayout }, ax.overlaying); ax.domain = ax2.domain; } @@ -29418,7 +29603,7 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { arrayIn = trace[axLetter]; len = trace._length || arrayIn.length; - if(_$lib_422.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(_$lib_423.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { if(len === arrayIn.length) { return arrayIn; } else if(arrayIn.subarray) { @@ -29459,11 +29644,15 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { 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]); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } }; ax.clearCalc = function() { @@ -29507,7 +29696,7 @@ var _$setConvert_485 = function setConvert(ax, fullLayout) { delete ax._forceTick0; }; -var _$axes_466 = {}; +var _$axes_467 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29523,9 +29712,9 @@ var _$axes_466 = {}; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; /* removed: var _$titles_392 = require('../../components/titles'); */; /* removed: var _$color_299 = require('../../components/color'); */; /* removed: var _$drawing_324 = require('../../components/drawing'); */; @@ -29533,33 +29722,33 @@ var _$axes_466 = {}; /* removed: var _$numerical_403 = require('../../constants/numerical'); */; var ONEAVGYEAR = _$numerical_403.ONEAVGYEAR; var ONEAVGMONTH = _$numerical_403.ONEAVGMONTH; -var __ONEDAY_466 = _$numerical_403.ONEDAY; -var __ONEHOUR_466 = _$numerical_403.ONEHOUR; -var __ONEMIN_466 = _$numerical_403.ONEMIN; -var __ONESEC_466 = _$numerical_403.ONESEC; +var __ONEDAY_467 = _$numerical_403.ONEDAY; +var __ONEHOUR_467 = _$numerical_403.ONEHOUR; +var __ONEMIN_467 = _$numerical_403.ONEMIN; +var __ONESEC_467 = _$numerical_403.ONESEC; var MINUS_SIGN = _$numerical_403.MINUS_SIGN; -var __BADNUM_466 = _$numerical_403.BADNUM; +var __BADNUM_467 = _$numerical_403.BADNUM; var MID_SHIFT = _$alignment_399.MID_SHIFT; -var __LINE_SPACING_466 = _$alignment_399.LINE_SPACING; +var __LINE_SPACING_467 = _$alignment_399.LINE_SPACING; -var axes = _$axes_466 = {}; +var axes = _$axes_467 = {}; axes.setConvert = _$setConvert_485; -/* removed: var _$autoType_467 = require('./axis_autotype'); */; +/* removed: var _$autoType_468 = require('./axis_autotype'); */; -/* removed: var _$axis_ids_469 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_469.id2name; -axes.name2id = _$axis_ids_469.name2id; -axes.cleanId = _$axis_ids_469.cleanId; -axes.list = _$axis_ids_469.list; -axes.listIds = _$axis_ids_469.listIds; -axes.getFromId = _$axis_ids_469.getFromId; -axes.getFromTrace = _$axis_ids_469.getFromTrace; +/* removed: var _$axis_ids_470 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_470.id2name; +axes.name2id = _$axis_ids_470.name2id; +axes.cleanId = _$axis_ids_470.cleanId; +axes.list = _$axis_ids_470.list; +axes.listIds = _$axis_ids_470.listIds; +axes.getFromId = _$axis_ids_470.getFromId; +axes.getFromTrace = _$axis_ids_470.getFromTrace; -/* removed: var _$autorange_465 = require('./autorange'); */; -axes.expand = _$autorange_465.expand; -axes.getAutoRange = _$autorange_465.getAutoRange; +/* removed: var _$autorange_466 = require('./autorange'); */; +axes.expand = _$autorange_466.expand; +axes.getAutoRange = _$autorange_466.getAutoRange; /* * find the list of possible axes to reference with an xref or yref attribute @@ -29590,7 +29779,7 @@ axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption }; // xref, yref - return _$lib_422.coerce(containerIn, containerOut, attrDef, refAttr); + return _$lib_423.coerce(containerIn, containerOut, attrDef, refAttr); }; /* @@ -29619,7 +29808,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { var cleanPos, pos; if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_422.ensureNumber; + cleanPos = _$lib_423.ensureNumber; pos = coerce(attr, dflt); } else { var ax = axes.getFromId(gd, axRef); @@ -29633,7 +29822,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { axes.cleanPosition = function(pos, gd, axRef) { var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_422.ensureNumber : + _$lib_423.ensureNumber : axes.getFromId(gd, axRef).cleanPos; return cleanPos(pos); @@ -29653,7 +29842,7 @@ var getDataConversions = axes.getDataConversions = function(gd, trace, target, t // setup the data-to-calc method. if(Array.isArray(d2cTarget)) { ax = { - type: _$autoType_467(targetArray), + type: _$autoType_468(targetArray), _categories: [] }; axes.setConvert(ax); @@ -29789,8 +29978,8 @@ axes.saveShowSpikeInitial = function(gd, overwrite) { }; axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_422.aggNums(Math.min, null, data), - dataMax = _$lib_422.aggNums(Math.max, null, data); + var dataMin = _$lib_423.aggNums(Math.min, null, data), + dataMax = _$lib_423.aggNums(Math.max, null, data); if(!calendar) calendar = ax.calendar; @@ -29810,12 +29999,12 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { // 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_422.distinctVals(data), + var distinctData = _$lib_423.distinctVals(data), msexp = Math.pow(10, Math.floor( Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_422.roundUp( + minSize = msexp * _$lib_423.roundUp( distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_422.stdev(data) / + size0 = Math.max(minSize, 2 * _$lib_423.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4)); // fallback if ax.d2c output BADNUMs @@ -29835,7 +30024,7 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { else { dummyAx = { type: ax.type, - range: _$lib_422.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + range: _$lib_423.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), calendar: calendar }; } @@ -29934,7 +30123,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_422.findExactDates(data, calendar); + var stats = _$lib_423.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; @@ -29946,21 +30135,21 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // 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_466 * 1.5; + binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + __ONEDAY_467 * 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_466 * 15.5; + binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + __ONEDAY_467 * 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_466 / 2; + binStart -= __ONEDAY_467 / 2; } var nextBinStart = axes.tickIncrement(binStart, dtick); @@ -29975,7 +30164,7 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // ensure we have tick0, dtick, and tick rounding calculated axes.prepTicks = function(ax) { - var rng = _$lib_422.simpleMap(ax.range, ax.r2l); + var rng = _$lib_423.simpleMap(ax.range, ax.r2l); // calculate max number of (auto) ticks to display based on plot size if(ax.tickmode === 'auto' || !ax.dtick) { @@ -29988,7 +30177,7 @@ axes.prepTicks = function(ax) { } else { minPx = ax._id.charAt(0) === 'y' ? 40 : 80; - nt = _$lib_422.constrain(ax._length / minPx, 4, 9) + 1; + nt = _$lib_423.constrain(ax._length / minPx, 4, 9) + 1; } // radial axes span half their domain, @@ -30023,7 +30212,7 @@ axes.prepTicks = function(ax) { // or codes to this effect for log and date scales axes.calcTicks = function calcTicks(ax) { axes.prepTicks(ax); - var rng = _$lib_422.simpleMap(ax.range, ax.r2l); + var rng = _$lib_423.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 @@ -30091,7 +30280,7 @@ function arrayTicks(ax) { var vals = ax.tickvals, text = ax.ticktext, ticksOut = new Array(vals.length), - rng = _$lib_422.simpleMap(ax.range, ax.r2l), + rng = _$lib_423.simpleMap(ax.range, ax.r2l), r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, tickMin = Math.min(r0expanded, r1expanded), @@ -30140,7 +30329,7 @@ var roundBase10 = [2, 5, 10], roundAngles = [15, 30, 45, 90, 180]; function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_422.roundUp(roughDTick / base, roundingSet); + return base * _$lib_423.roundUp(roughDTick / base, roundingSet); } // autoTicks: calculate best guess at pleasant ticks for this axis @@ -30167,7 +30356,7 @@ axes.autoTicks = function(ax, roughDTick) { } if(ax.type === 'date') { - ax.tick0 = _$lib_422.dateTick0(ax.calendar); + ax.tick0 = _$lib_423.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; @@ -30181,21 +30370,21 @@ axes.autoTicks = function(ax, roughDTick) { roughDTick /= ONEAVGMONTH; ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); } - else if(roughX2 > __ONEDAY_466) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_466, roundDays); + else if(roughX2 > __ONEDAY_467) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_467, 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_422.dateTick0(ax.calendar, true); + ax.tick0 = _$lib_423.dateTick0(ax.calendar, true); } - else if(roughX2 > __ONEHOUR_466) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_466, roundBase24); + else if(roughX2 > __ONEHOUR_467) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_467, roundBase24); } - else if(roughX2 > __ONEMIN_466) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_466, roundBase60); + else if(roughX2 > __ONEMIN_467) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_467, roundBase60); } - else if(roughX2 > __ONESEC_466) { - ax.dtick = roundDTick(roughDTick, __ONESEC_466, roundBase60); + else if(roughX2 > __ONESEC_467) { + ax.dtick = roundDTick(roughDTick, __ONESEC_467, roundBase60); } else { // milliseconds @@ -30205,7 +30394,7 @@ axes.autoTicks = function(ax, roughDTick) { } else if(ax.type === 'log') { ax.tick0 = 0; - var rng = _$lib_422.simpleMap(ax.range, ax.r2l); + var rng = _$lib_423.simpleMap(ax.range, ax.r2l); if(roughDTick > 0.7) { // only show powers of 10 @@ -30286,9 +30475,9 @@ function autoTickRound(ax) { // 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_466 && tick0len <= 10) || (dtick >= __ONEDAY_466 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_466 && tick0len <= 16) || (dtick >= __ONEHOUR_466)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_466 && tick0len <= 19) || (dtick >= __ONEMIN_466)) ax._tickround = 'S'; + else if((dtick >= __ONEDAY_467 && tick0len <= 10) || (dtick >= __ONEDAY_467 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_467 && tick0len <= 16) || (dtick >= __ONEHOUR_467)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_467 && tick0len <= 19) || (dtick >= __ONEMIN_467)) 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 @@ -30335,7 +30524,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { dtSigned = axSign * Number(dtick.substr(1)); // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_422.incrementMonth(x, dtSigned, calendar); + if(tType === 'M') return _$lib_423.incrementMonth(x, dtSigned, calendar); // Log scales: Linear, Digits else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; @@ -30345,7 +30534,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, x2 = x + axSign * 0.01, - frac = _$lib_422.roundUp(_$lib_422.mod(x2, 1), tickset, axrev); + frac = _$lib_423.roundUp(_$lib_423.mod(x2, 1), tickset, axrev); return Math.floor(x2) + Math.log(_$d3_79.round(Math.pow(10, frac), 1)) / Math.LN10; @@ -30356,7 +30545,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { // calculate the first tick on an axis axes.tickFirst = function(ax) { var r2l = ax.r2l || Number, - rng = _$lib_422.simpleMap(ax.range, r2l), + rng = _$lib_423.simpleMap(ax.range, r2l), axrev = rng[1] < rng[0], sRound = axrev ? Math.floor : Math.ceil, // add a tiny extra bit to make sure we get ticks @@ -30370,7 +30559,7 @@ axes.tickFirst = function(ax) { // make sure no ticks outside the category list if(ax.type === 'category') { - tmin = _$lib_422.constrain(tmin, 0, ax._categories.length - 1); + tmin = _$lib_423.constrain(tmin, 0, ax._categories.length - 1); } return tmin; } @@ -30400,7 +30589,7 @@ axes.tickFirst = function(ax) { t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); cnt++; } - _$lib_422.error('tickFirst did not converge', ax); + _$lib_423.error('tickFirst did not converge', ax); return t0; } @@ -30411,7 +30600,7 @@ axes.tickFirst = function(ax) { } else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_422.roundUp(_$lib_422.mod(r0, 1), tickset, axrev); + frac = _$lib_423.roundUp(_$lib_423.mod(r0, 1), tickset, axrev); return Math.floor(r0) + Math.log(_$d3_79.round(Math.pow(10, frac), 1)) / Math.LN10; @@ -30434,7 +30623,7 @@ axes.tickText = function(ax, x, hover) { tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_422.simpleMap(ax.range, ax.r2l), + var rng = _$lib_423.simpleMap(ax.range, ax.r2l), 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; @@ -30491,7 +30680,7 @@ axes.tickText = function(ax, x, hover) { * it's different from `val`. */ axes.hoverLabelText = function(ax, val, val2) { - if(val2 !== __BADNUM_466 && val2 !== val) { + if(val2 !== __BADNUM_467 && val2 !== val) { return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } @@ -30534,7 +30723,7 @@ function formatDate(ax, out, hover, extraPrecision) { else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; } - var dateStr = _$lib_422.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + var dateStr = _$lib_423.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), headStr; var splitIndex = dateStr.indexOf('\n'); @@ -30599,7 +30788,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); } - else if(_$fastIsnumeric_89(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_422.mod(x + 0.01, 1) < 0.1))) { + else if(_$fastIsnumeric_89(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_423.mod(x + 0.01, 1) < 0.1))) { var p = Math.round(x); if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || (isSIFormat(ax.exponentformat) && beyondSI(p))) { @@ -30618,7 +30807,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { } } else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_422.mod(x, 1)))); + out.text = String(Math.round(Math.pow(10, _$lib_423.mod(x, 1)))); out.fontSize *= 0.75; } else throw 'unrecognized dtick ' + String(dtick); @@ -30673,7 +30862,7 @@ function formatAngle(ax, out, hover, extraPrecision, hideexp) { var frac = num2frac(num); if(frac[1] >= 100) { - out.text = numFormat(_$lib_422.deg2rad(out.x), ax, hideexp, extraPrecision); + out.text = numFormat(_$lib_423.deg2rad(out.x), ax, hideexp, extraPrecision); } else { var isNeg = out.x < 0; @@ -30821,7 +31010,7 @@ function numFormat(v, ax, fmtoverride, hover) { if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); } // insert appropriate decimal point and thousands separator - v = _$lib_422.numSeparate(v, ax._separators, separatethousands); + v = _$lib_423.numSeparate(v, ax._separators, separatethousands); } // add exponent @@ -31012,9 +31201,9 @@ axes.makeClipPaths = function(gd) { // ax._rl (stored linearized range for use by zoom/pan) // or can pass in an axis object directly axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + var fullLayout = gd._fullLayout; + var ax; + var independent = false; // allow passing an independent axis object instead of id if(typeof axid === 'object') { @@ -31027,32 +31216,26 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'redraw') { fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); }); } if(!axid || axid === 'redraw') { - return _$lib_422.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return _$lib_423.syncOrAsync(axes.list(gd, '', true).map(function(ax) { return function() { if(!ax._id) return; var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_422.simpleMap(ax._r, ax.r2l); - } + ax._r = ax.range.slice(); + ax._rl = _$lib_423.simpleMap(ax._r, ax.r2l); return axDone; }; })); @@ -31062,21 +31245,22 @@ axes.doTicks = function(gd, axid, skipTitle) { // set scaling to pixels ax.setScale(); - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_324.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_324.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_324.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + var axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_324.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_324.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_324.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; if(ax._counterangle && ax.ticks === 'outside') { var caRad = ax._counterangle * Math.PI / 180; @@ -31123,13 +31307,14 @@ axes.doTicks = function(gd, axid, skipTitle) { }; } else { - _$lib_422.warn('Unrecognized doTicks axis:', axid); + _$lib_423.warn('Unrecognized doTicks axis:', axid); return; } - var axside = ax.side || sides[0], + + var axside = ax.side || sides[0]; // which direction do the side[0], side[1], and free ticks go? // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; if((ax.ticks !== 'inside') === (axLetter === 'x')) { ticksign = ticksign.map(function(v) { return -v; }); } @@ -31157,6 +31342,7 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawTicks(container, tickpath) { var ticks = container.selectAll('path.' + tcls) .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); + if(tickpath && ax.ticks) { ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) .classed('crisp', 1) @@ -31172,7 +31358,7 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawLabels(container, position) { // tick labels - for now just the main labels. // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); if(!_$fastIsnumeric_89(position)) { tickLabels.remove(); @@ -31240,10 +31426,10 @@ axes.doTicks = function(gd, axid, skipTitle) { var thisLabel = _$d3_79.select(this), newPromise = gd._promises.length; thisLabel - .call(_$svg_text_utils_445.positionText, labelx(d), labely(d)) + .call(_$svg_text_utils_446.positionText, labelx(d), labely(d)) .call(_$drawing_324.font, d.font, d.fontSize, d.fontColor) .text(d.text) - .call(_$svg_text_utils_445.convertToTspans, gd); + .call(_$svg_text_utils_446.convertToTspans, gd); newPromise = gd._promises[newPromise]; if(newPromise) { // if we have an async label, we'll deal with that @@ -31268,7 +31454,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'angular') { tickLabels.each(function(d) { _$d3_79.select(this).select('text') - .call(_$svg_text_utils_445.positionText, labelx(d), labely(d)); + .call(_$svg_text_utils_446.positionText, labelx(d), labely(d)); }); } @@ -31303,8 +31489,8 @@ axes.doTicks = function(gd, axid, skipTitle) { (labely(d) - d.fontSize / 2) + ')') : ''); var anchorHeight = getAnchorHeight( - _$svg_text_utils_445.lineCount(thisLabel), - __LINE_SPACING_466 * d.fontSize, + _$svg_text_utils_446.lineCount(thisLabel), + __LINE_SPACING_467 * d.fontSize, _$fastIsnumeric_89(angle) ? +angle : 0); if(anchorHeight) { transform += ' translate(0, ' + anchorHeight + ')'; @@ -31365,7 +31551,7 @@ axes.doTicks = function(gd, axid, skipTitle) { }); }); for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_422.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + if(_$lib_423.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { // any overlap at all - set 30 degrees autoangle = 30; break; @@ -31507,7 +31693,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } } - var done = _$lib_422.syncOrAsync([ + var done = _$lib_423.syncOrAsync([ allLabelsReady, fixLabelOverlaps, calcBoundingBox, @@ -31523,14 +31709,12 @@ axes.doTicks = function(gd, axid, skipTitle) { // now this only applies to regular cartesian axes; colorbars and // others ALWAYS call doTicks with skipTitle=true so they can // configure their own titles. - var ax = _$axis_ids_469.getFromId(gd, axid); // rangeslider takes over a bottom title so drop it here if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - var avoidSelection = _$d3_79.select(gd).selectAll('g.' + axid + 'tick'); var avoid = { - selection: avoidSelection, + selection: tickLabels, side: ax.side }; var axLetter = axid.charAt(0); @@ -31540,8 +31724,8 @@ axes.doTicks = function(gd, axid, skipTitle) { var transform, counterAxis, x, y; - if(avoidSelection.size()) { - var translation = _$drawing_324.getTranslate(avoidSelection.node().parentNode); + if(tickLabels.size()) { + var translation = _$drawing_324.getTranslate(tickLabels.node().parentNode); avoid.offsetLeft = translation.x; avoid.offsetTop = translation.y; } @@ -31552,7 +31736,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axLetter === 'x') { counterAxis = (ax.anchor === 'free') ? {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_469.getFromId(gd, ax.anchor); + _$axis_ids_470.getFromId(gd, ax.anchor); x = ax._offset + ax._length / 2; @@ -31570,7 +31754,7 @@ axes.doTicks = function(gd, axid, skipTitle) { else { counterAxis = (ax.anchor === 'free') ? {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_469.getFromId(gd, ax.anchor); + _$axis_ids_470.getFromId(gd, ax.anchor); y = ax._offset + ax._length / 2; if(ax.side === 'right') { @@ -31598,11 +31782,13 @@ axes.doTicks = function(gd, axid, skipTitle) { function traceHasBarsOrFill(trace, subplot) { if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_518.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + if(_$registry_519.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; } function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); var zlcontainer = plotinfo.zerolinelayer; var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; @@ -31636,7 +31822,7 @@ axes.doTicks = function(gd, axid, skipTitle) { break; } } - var rng = _$lib_422.simpleMap(ax.range, ax.r2l), + var rng = _$lib_423.simpleMap(ax.range, ax.r2l), showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && (ax.type === 'linear' || ax.type === '-') && gridvals.length && (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); @@ -31650,7 +31836,7 @@ axes.doTicks = function(gd, axid, skipTitle) { // If several zerolines enter at the same time we will sort once per, // but generally this should be a minimal overhead. zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_469.idSort(da.id, db.id); + return _$axis_ids_470.idSort(da.id, db.id); }); }); zl.attr('transform', transfn) @@ -31701,7 +31887,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - tickSubplots = Object.keys(ax._linepositions); + tickSubplots = Object.keys(ax._linepositions || {}); } tickSubplots.map(function(subplot) { @@ -31840,7 +32026,7 @@ function swapAxisGroup(gd, xIds, yIds) { var ann = gd._fullLayout.annotations[i]; if(xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { - _$lib_422.swapAttrs(layout.annotations[i], ['?']); + _$lib_423.swapAttrs(layout.annotations[i], ['?']); } } } @@ -31849,7 +32035,7 @@ 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_422.nestedProperty, + var np = _$lib_423.nestedProperty, xVal = np(layout[xFullAxes[0]._name], key).get(), yVal = np(layout[yFullAxes[0]._name], key).get(), i; @@ -31886,15 +32072,15 @@ var _$hover_339 = {}; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_264 = require('tinycolor2'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$Events_413 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_433 = require('../../lib/override_cursor'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$Events_414 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_434 = require('../../lib/override_cursor'); */; /* removed: var _$drawing_324 = require('../drawing'); */; /* removed: var _$color_299 = require('../color'); */; /* removed: var _$dragelement_321 = require('../dragelement'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_519 = require('../../registry'); */; /* removed: var _$helpers_338 = require('./helpers'); */; /* removed: var _$constants_336 = require('./constants'); */; @@ -31941,9 +32127,9 @@ var HOVERTEXTPAD = _$constants_336.HOVERTEXTPAD; // We wrap the hovers in a timer, to limit their frequency. // The actual rendering is done by private function _hover. _$hover_339.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_422.getGraphDiv(gd); + gd = _$lib_423.getGraphDiv(gd); - _$lib_422.throttle( + _$lib_423.throttle( gd._fullLayout._uid + _$constants_336.HOVERID, _$constants_336.HOVERMINTIME, function() { _hover(gd, evt, subplot, noHoverEvent); } @@ -32066,8 +32252,8 @@ function _hover(gd, evt, subplot, noHoverEvent) { // get updated properly so that we don't have // to use Axes.getFromId in general. - xaArray[i] = _$axes_466.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_466.getFromId(gd, plotObj.yaxis._id); + xaArray[i] = _$axes_467.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_467.getFromId(gd, plotObj.yaxis._id); continue; } @@ -32089,7 +32275,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - // hoverData: the set of candidate points we've found to highlight + // hoverData: the set of candidate points we've found to highlight var hoverData = [], // searchData: the data to search in. Mostly this is just a copy of @@ -32139,7 +32325,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { cd = gd.calcdata[curvenum]; trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_338.getSubplot(trace)) !== -1) { + if(trace.hoverinfo !== 'skip' && _$helpers_338.isTraceInSubplots(trace, subplots)) { searchData.push(cd); } } @@ -32163,7 +32349,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { // fire the beforehover event and quit if it returns false // note that we're only calling this on real mouse events, so // manual calls to fx.hover will always run. - if(_$Events_413.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + if(_$Events_414.triggerHandler(gd, 'plotly_beforehover', evt) === false) { return; } @@ -32188,7 +32374,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { else yvalArray = _$helpers_338.p2c(yaArray, ypx); if(!_$fastIsnumeric_89(xvalArray[0]) || !_$fastIsnumeric_89(yvalArray[0])) { - _$lib_422.warn('Fx.hover failed', evt, gd); + _$lib_423.warn('Fx.hover failed', evt, gd); return _$dragelement_321.unhoverRaw(gd, evt); } } @@ -32212,8 +32398,15 @@ function _hover(gd, evt, subplot, noHoverEvent) { // the rest of this function from running and failing if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotId = _$helpers_338.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_338.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } // within one trace mode can sometimes be overridden mode = hovermode; @@ -32307,7 +32500,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { } } else { - _$lib_422.log('Unrecognized trace type in hover:', trace); + _$lib_423.log('Unrecognized trace type in hover:', trace); } } @@ -32484,8 +32677,8 @@ function _hover(gd, evt, subplot, noHoverEvent) { // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true // we should improve the "fx" API so other plots can use it without these hack. if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_518.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_433(_$d3_79.select(evt.target), hasClickToShow ? 'pointer' : ''); + var hasClickToShow = _$registry_519.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_434(_$d3_79.select(evt.target), hasClickToShow ? 'pointer' : ''); } // don't emit events if called manually @@ -32570,38 +32763,36 @@ function createHoverText(hoverData, opts, gd) { commonLabel.exit().remove(); commonLabel.each(function() { - var label = _$d3_79.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); - - lpath.enter().append('path') - .style({'stroke-width': '1px'}); + var label = _$d3_79.select(this); + var lpath = _$lib_423.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_423.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); lpath.style({ fill: commonLabelOpts.bgcolor || _$color_299.defaultLine, stroke: commonLabelOpts.bordercolor || _$color_299.background, }); - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); - ltext.text(t0) .call(_$drawing_324.font, commonLabelOpts.font.family || fontFamily, commonLabelOpts.font.size || fontSize, commonLabelOpts.font.color || _$color_299.background ) - .call(_$svg_text_utils_445.positionText, 0, 0) - .call(_$svg_text_utils_445.convertToTspans, gd); + .call(_$svg_text_utils_446.positionText, 0, 0) + .call(_$svg_text_utils_446.convertToTspans, gd); label.attr('transform', ''); var tbb = ltext.node().getBoundingClientRect(); if(hovermode === 'x') { ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_445.positionText, 0, (xa.side === 'top' ? + .call(_$svg_text_utils_446.positionText, 0, (xa.side === 'top' ? (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); @@ -32619,7 +32810,7 @@ function createHoverText(hoverData, opts, gd) { } else { ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_445.positionText, + .call(_$svg_text_utils_446.positionText, (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), outerTop - tbb.top - tbb.height / 2); @@ -32685,7 +32876,7 @@ function createHoverText(hoverData, opts, gd) { if(d.name) { // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_445.plainText(d.name || ''); + name = _$svg_text_utils_446.plainText(d.name || ''); var nameLength = Math.round(d.nameLength); @@ -32695,13 +32886,6 @@ function createHoverText(hoverData, opts, gd) { } } - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; - if(d.zLabel !== undefined) { if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; @@ -32720,6 +32904,13 @@ function createHoverText(hoverData, opts, gd) { text += (text ? '
' : '') + d.text; } + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; + // if 'text' is empty at this point, // put 'name' in main label and don't show secondary label if(text === '') { @@ -32736,8 +32927,8 @@ function createHoverText(hoverData, opts, gd) { d.fontColor || contrastColor) .text(text) .attr('data-notex', 1) - .call(_$svg_text_utils_445.positionText, 0, 0) - .call(_$svg_text_utils_445.convertToTspans, gd); + .call(_$svg_text_utils_446.positionText, 0, 0) + .call(_$svg_text_utils_446.convertToTspans, gd); var tx2 = g.select('text.name'), tx2width = 0; @@ -32750,8 +32941,8 @@ function createHoverText(hoverData, opts, gd) { traceColor) .text(name) .attr('data-notex', 1) - .call(_$svg_text_utils_445.positionText, 0, 0) - .call(_$svg_text_utils_445.convertToTspans, gd); + .call(_$svg_text_utils_446.positionText, 0, 0) + .call(_$svg_text_utils_446.convertToTspans, gd); tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; } else { @@ -33020,12 +33211,12 @@ function alignHoverText(hoverLabels, rotateLabels) { 'V' + (offsetY - HOVERARROWSIZE) + 'Z')); - tx.call(_$svg_text_utils_445.positionText, + tx.call(_$svg_text_utils_446.positionText, txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); if(d.tx2width) { g.select('text.name') - .call(_$svg_text_utils_445.positionText, + .call(_$svg_text_utils_446.positionText, tx2x + alignShift * HOVERTEXTPAD + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); g.select('rect') @@ -33045,11 +33236,11 @@ function cleanPoint(d, hovermode) { var getVal = Array.isArray(index) ? function(calcKey, traceKey) { - return _$lib_422.castOption(cd0, index, calcKey) || - _$lib_422.extractOption({}, trace, '', traceKey); + return _$lib_423.castOption(cd0, index, calcKey) || + _$lib_423.extractOption({}, trace, '', traceKey); } : function(calcKey, traceKey) { - return _$lib_422.extractOption(cd, trace, calcKey, traceKey); + return _$lib_423.extractOption(cd, trace, calcKey, traceKey); }; function fill(key, calcKey, traceKey) { @@ -33070,18 +33261,18 @@ function cleanPoint(d, hovermode) { (d.ya._offset + (d.y0 + d.y1) / 2); // then constrain all the positions to be on the plot - d.x0 = _$lib_422.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_422.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_422.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_422.constrain(d.y1, 0, d.ya._length); + d.x0 = _$lib_423.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_423.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_423.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_423.constrain(d.y1, 0, d.ya._length); // and convert the x and y label values into formatted text if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_466.hoverLabelText(d.xa, d.xLabelVal); + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_467.hoverLabelText(d.xa, d.xLabelVal); d.xVal = d.xa.c2d(d.xLabelVal); } if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_466.hoverLabelText(d.ya, d.yLabelVal); + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_467.hoverLabelText(d.ya, d.yLabelVal); d.yVal = d.ya.c2d(d.yLabelVal); } @@ -33092,10 +33283,10 @@ function cleanPoint(d, hovermode) { // for box means and error bars, add the range to the label if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_466.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + var xeText = _$axes_467.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; if(d.xerrneg !== undefined) { d.xLabel += ' +' + xeText + ' / -' + - _$axes_466.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + _$axes_467.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; } else d.xLabel += ' ± ' + xeText; @@ -33105,10 +33296,10 @@ function cleanPoint(d, hovermode) { if(hovermode === 'x') d.distance += 1; } if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_466.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + var yeText = _$axes_467.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; if(d.yerrneg !== undefined) { d.yLabel += ' +' + yeText + ' / -' + - _$axes_466.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + _$axes_467.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; } else d.yLabel += ' ± ' + yeText; @@ -33334,11 +33525,11 @@ function spikesChanged(gd, oldspikepoints) { 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; var hover = _$hover_339.hover; var _$click_335 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_518.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); + var annotationsDone = _$registry_519.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. @@ -33371,7 +33562,7 @@ var _$click_335 = function click(gd, evt, subplot) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; var _$handleHoverLabelDefaults_340 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { opts = opts || {}; @@ -33379,7 +33570,7 @@ var _$handleHoverLabelDefaults_340 = function handleHoverLabelDefaults(contIn, c coerce('hoverlabel.bgcolor', opts.bgcolor); coerce('hoverlabel.bordercolor', opts.bordercolor); coerce('hoverlabel.namelength', opts.namelength); - _$lib_422.coerceFont(coerce, 'hoverlabel.font', opts.font); + _$lib_423.coerceFont(coerce, 'hoverlabel.font', opts.font); }; /** @@ -33392,13 +33583,13 @@ var _$handleHoverLabelDefaults_340 = function handleHoverLabelDefaults(contIn, c 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$attributes_333 = require('./attributes'); */; /* removed: var _$handleHoverLabelDefaults_340 = require('./hoverlabel_defaults'); */; var _$supplyDefaults_337 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_422.coerce(traceIn, traceOut, _$attributes_333, attr, dflt); + return _$lib_423.coerce(traceIn, traceOut, _$attributes_333, attr, dflt); } _$handleHoverLabelDefaults_340(traceIn, traceOut, coerce, layout.hoverlabel); @@ -33477,6 +33668,14 @@ var _$layout_attributes_342 = { editType: 'none', }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + editType: 'none' } }; @@ -33491,15 +33690,16 @@ var _$layout_attributes_342 = { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$layout_attributes_342 = require('./layout_attributes'); */; var _$supplyLayoutDefaults_343 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_422.coerce(layoutIn, layoutOut, _$layout_attributes_342, attr, dflt); + return _$lib_423.coerce(layoutIn, layoutOut, _$layout_attributes_342, attr, dflt); } - coerce('dragmode'); + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); var hovermodeDflt; if(layoutOut._has('cartesian')) { @@ -33556,13 +33756,13 @@ function isHoriz(fullData) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$handleHoverLabelDefaults_340 = require('./hoverlabel_defaults'); */; /* removed: var _$layout_attributes_342 = require('./layout_attributes'); */; var _$supplyLayoutGlobalDefaults_344 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_422.coerce(layoutIn, layoutOut, _$layout_attributes_342, attr, dflt); + return _$lib_423.coerce(layoutIn, layoutOut, _$layout_attributes_342, attr, dflt); } _$handleHoverLabelDefaults_340(layoutIn, layoutOut, coerce); @@ -33579,7 +33779,7 @@ var _$supplyLayoutGlobalDefaults_344 = function supplyLayoutGlobalDefaults(layou 'use strict'; /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$dragelement_321 = require('../dragelement'); */; /* removed: var _$helpers_338 = require('./helpers'); */; /* removed: var _$layout_attributes_342 = require('./layout_attributes'); */; @@ -33623,7 +33823,7 @@ var _$fx_341 = { function loneUnhover(containerOrSelection) { // duck type whether the arg is a d3 selection because ie9 doesn't // handle instanceof like modern browsers do. - var selection = _$lib_422.isD3Selection(containerOrSelection) ? + var selection = _$lib_423.isD3Selection(containerOrSelection) ? containerOrSelection : _$d3_79.select(containerOrSelection); @@ -33634,15 +33834,15 @@ function loneUnhover(containerOrSelection) { // helpers for traces that use Fx.loneHover function castHoverOption(trace, ptNumber, attr) { - return _$lib_422.castOption(trace, ptNumber, 'hoverlabel.' + attr); + return _$lib_423.castOption(trace, ptNumber, 'hoverlabel.' + attr); } function castHoverinfo(trace, fullLayout, ptNumber) { function _coerce(val) { - return _$lib_422.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + return _$lib_423.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } - return _$lib_422.castOption(trace, ptNumber, 'hoverinfo', _coerce); + return _$lib_423.castOption(trace, ptNumber, 'hoverinfo', _coerce); } /** @@ -33657,15 +33857,15 @@ function castHoverinfo(trace, fullLayout, ptNumber) { /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; /* removed: var _$color_299 = require('../color'); */; /* removed: var _$drawing_324 = require('../drawing'); */; /* removed: var _$fx_341 = require('../fx'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_441 = require('../../lib/setcursor'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_442 = require('../../lib/setcursor'); */; /* removed: var _$dragelement_321 = require('../dragelement'); */; /* removed: var _$drawArrowHead_291 = require('./draw_arrow_head'); */; @@ -33709,8 +33909,8 @@ function __draw_290(gd) { function drawOne(gd, index) { var fullLayout = gd._fullLayout; var options = fullLayout.annotations[index] || {}; - var xa = _$axes_466.getFromId(gd, options.xref); - var ya = _$axes_466.getFromId(gd, options.yref); + var xa = _$axes_467.getFromId(gd, options.xref); + var ya = _$axes_467.getFromId(gd, options.yref); drawRaw(gd, options, index, false, xa, ya); } @@ -33779,7 +33979,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextGroupInner = annTextGroup.append('g') .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_441, 'default') + .call(_$setCursor_442, 'default') .on('click', function() { gd._dragging = false; @@ -33863,7 +34063,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }[options.align] || 'middle' }); - _$svg_text_utils_445.convertToTspans(s, gd, drawGraphicalElements); + _$svg_text_utils_446.convertToTspans(s, gd, drawGraphicalElements); return s; } @@ -34004,7 +34204,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // partially visible var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height']; if(axRef === 'paper') { - posPx.head = _$lib_422.constrain(posPx.head, 1, maxPx - 1); + posPx.head = _$lib_423.constrain(posPx.head, 1, maxPx - 1); } if(tailRef === 'pixel') { var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), @@ -34069,7 +34269,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var texty = borderfull + yShift - anntextBB.top; var textx = borderfull + xShift - anntextBB.left; - annText.call(_$svg_text_utils_445.positionText, textx, texty) + annText.call(_$svg_text_utils_446.positionText, textx, texty) .call(_$drawing_324.setClipUrl, isSizeConstrained ? annClipID : null); } @@ -34112,9 +34312,9 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // find the edge of the text box, where we'll start the arrow: // create transform matrix to rotate the text box corners - transform = _$lib_422.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_422.apply2DTransform(transform), - applyTransform2 = _$lib_422.apply2DTransform2(transform), + transform = _$lib_423.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_423.apply2DTransform(transform), + applyTransform2 = _$lib_423.apply2DTransform2(transform), // calculate and transform bounding box width = +annTextBG.attr('width'), @@ -34136,7 +34336,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // to get the parity of the number of intersections. if(edges.reduce(function(a, x) { return a ^ - !!_$lib_422.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, + !!_$lib_423.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, x[0], x[1], x[2], x[3]); }, false)) { // no line or arrow - so quit drawArrow now @@ -34144,7 +34344,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } edges.forEach(function(x) { - var p = _$lib_422.segmentsIntersect(tailX, tailY, headX, headY, + var p = _$lib_423.segmentsIntersect(tailX, tailY, headX, headY, x[0], x[1], x[2], x[3]); if(p) { tailX = p.x; @@ -34238,7 +34438,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }, doneFn: function() { - _$registry_518.call('relayout', gd, update); + _$registry_519.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -34316,11 +34516,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform }); - _$setCursor_441(annTextGroupInner, csr); + _$setCursor_442(annTextGroupInner, csr); }, doneFn: function() { - _$setCursor_441(annTextGroupInner); - _$registry_518.call('relayout', gd, update); + _$setCursor_442(annTextGroupInner); + _$registry_519.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -34329,7 +34529,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } if(edits.annotationText) { - annText.call(_$svg_text_utils_445.makeEditable, {delegate: annTextGroupInner, gd: gd}) + annText.call(_$svg_text_utils_446.makeEditable, {delegate: annTextGroupInner, gd: gd}) .call(textLayout) .on('edit', function(_text) { options.text = _text; @@ -34345,7 +34545,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { update[ya._name + '.autorange'] = true; } - _$registry_518.call('relayout', gd, update); + _$registry_519.call('relayout', gd, update); }); } else annText.call(textLayout); @@ -34362,15 +34562,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; var __draw_285 = _$draw_290.draw; var _$calcAutorange_285 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - annotationList = _$lib_422.filterVisible(fullLayout.annotations); + annotationList = _$lib_423.filterVisible(fullLayout.annotations); if(!annotationList.length || !gd._fullData.length) return; @@ -34381,9 +34581,9 @@ var _$calcAutorange_285 = function calcAutorange(gd) { }); for(var axId in annotationAxes) { - var ax = _$axes_466.getFromId(gd, axId); + var ax = _$axes_467.getFromId(gd, axId); if(ax && ax.autorange) { - return _$lib_422.syncOrAsync([ + return _$lib_423.syncOrAsync([ __draw_285, annAutorange ], gd); @@ -34398,9 +34598,9 @@ function annAutorange(gd) { // relative to their anchor points // use the arrow and the text bg rectangle, // as the whole anno may include hidden text in its bbox - _$lib_422.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_466.getFromId(gd, ann.xref), - ya = _$axes_466.getFromId(gd, ann.yref), + _$lib_423.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_467.getFromId(gd, ann.xref), + ya = _$axes_467.getFromId(gd, ann.yref), headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; @@ -34414,12 +34614,12 @@ function annAutorange(gd) { if(ann.axref === ann.xref) { // expand for the arrowhead (padded by arrowhead) - _$axes_466.expand(xa, [xa.r2c(ann.x)], { + _$axes_467.expand(xa, [xa.r2c(ann.x)], { ppadplus: headPlus, ppadminus: headMinus }); // again for the textbox (padded by textbox) - _$axes_466.expand(xa, [xa.r2c(ann.ax)], { + _$axes_467.expand(xa, [xa.r2c(ann.ax)], { ppadplus: Math.max(ann._xpadplus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, startHeadMinus) }); @@ -34427,7 +34627,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_466.expand(xa, [xa.r2c(ann.x)], { + _$axes_467.expand(xa, [xa.r2c(ann.x)], { ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) }); @@ -34441,11 +34641,11 @@ function annAutorange(gd) { startHeadMinus = startHeadSize + ann.yshift; if(ann.ayref === ann.yref) { - _$axes_466.expand(ya, [ya.r2c(ann.y)], { + _$axes_467.expand(ya, [ya.r2c(ann.y)], { ppadplus: headPlus, ppadminus: headMinus }); - _$axes_466.expand(ya, [ya.r2c(ann.ay)], { + _$axes_467.expand(ya, [ya.r2c(ann.ay)], { ppadplus: Math.max(ann._ypadplus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, startHeadMinus) }); @@ -34453,7 +34653,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_466.expand(ya, [ya.r2c(ann.y)], { + _$axes_467.expand(ya, [ya.r2c(ann.y)], { ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) }); @@ -34472,7 +34672,7 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; var _$click_286 = { hasClickToShow: hasClickToShow, @@ -34521,7 +34721,7 @@ function onClick(gd, hoverData) { update['annotations[' + offSet[i] + '].visible'] = false; } - return _$registry_518.call('update', gd, {}, update); + return _$registry_519.call('update', gd, {}, update); } /* @@ -34605,7 +34805,7 @@ function clickData2r(d, ax) { 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_447 = require('../../lib/to_log_range'); */; +/* removed: var _$toLogRange_448 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -34637,7 +34837,7 @@ var _$convertCoords_288 = function convertCoords(gd, ax, newType, doExtra) { var currentVal = ann[attr], newVal = null; - if(toLog) newVal = _$toLogRange_447(currentVal, ax.range); + if(toLog) newVal = _$toLogRange_448(currentVal, ax.range); else newVal = Math.pow(10, currentVal); // if conversion failed, delete the value so it gets a default value @@ -34665,7 +34865,7 @@ var _$convertCoords_288 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$color_299 = require('../color'); */; // defaults common to 'annotations' and 'annotations3d' @@ -34683,7 +34883,7 @@ var _$handleAnnotationCommonDefaults_287 = function handleAnnotationCommonDefaul coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); coerce('textangle'); - _$lib_422.coerceFont(coerce, 'font', fullLayout.font); + _$lib_423.coerceFont(coerce, 'font', fullLayout.font); coerce('width'); coerce('align'); @@ -34724,7 +34924,7 @@ var _$handleAnnotationCommonDefaults_287 = function handleAnnotationCommonDefaul _$color_299.contrast(hoverBG) ); - _$lib_422.coerceFont(coerce, 'hoverlabel.font', { + _$lib_423.coerceFont(coerce, 'hoverlabel.font', { family: globalHoverLabel.font.family, size: globalHoverLabel.font.size, color: globalHoverLabel.font.color || hoverBorder @@ -34745,8 +34945,8 @@ var _$handleAnnotationCommonDefaults_287 = function handleAnnotationCommonDefaul 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; /* removed: var _$handleAnnotationCommonDefaults_287 = require('./common_defaults'); */; /* removed: var _$attributes_284 = require('./attributes'); */; @@ -34756,7 +34956,7 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_422.coerce(annIn, annOut, _$attributes_284, attr, dflt); + return _$lib_423.coerce(annIn, annOut, _$attributes_284, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -34776,15 +34976,15 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an var axLetter = axLetters[i]; // xref, yref - var axRef = _$axes_466.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_467.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); // x, y - _$axes_466.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + _$axes_467.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); if(showArrow) { var arrowPosAttr = 'a' + axLetter, // axref, ayref - aaxRef = _$axes_466.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + aaxRef = _$axes_467.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); // for now the arrow can only be on the same axis or specified as pixels // TODO: sometime it might be interesting to allow it to be on *any* axis @@ -34795,7 +34995,7 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an // ax, ay var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_466.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + _$axes_467.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } // xanchor, yanchor @@ -34806,11 +35006,11 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an } // if you have one coordinate you should have both - _$lib_422.noneOrAll(annIn, annOut, ['x', 'y']); + _$lib_423.noneOrAll(annIn, annOut, ['x', 'y']); // if you have one part of arrow length you should have both if(showArrow) { - _$lib_422.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_423.noneOrAll(annIn, annOut, ['ax', 'ay']); } if(clickToShow) { @@ -34821,10 +35021,10 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an // so we don't have to do this little bit of logic on every hover event annOut._xclick = (xClick === undefined) ? annOut.x : - _$axes_466.cleanPosition(xClick, gdMock, annOut.xref); + _$axes_467.cleanPosition(xClick, gdMock, annOut.xref); annOut._yclick = (yClick === undefined) ? annOut.y : - _$axes_466.cleanPosition(yClick, gdMock, annOut.yref); + _$axes_467.cleanPosition(yClick, gdMock, annOut.yref); } return annOut; @@ -34840,7 +35040,7 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an 'use strict'; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$lib_423 = require('../lib'); */; /** Convenience wrapper for making array container logic DRY and consistent * @@ -34872,12 +35072,12 @@ var _$handleAnnotationDefaults_282 = function handleAnnotationDefaults(annIn, an * links to supplementary data (e.g. fullData for layout components) * */ -var _$handleArrayContainerDefaults_462 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { +var _$handleArrayContainerDefaults_463 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { var name = opts.name; var previousContOut = parentObjOut[name]; - var contIn = _$lib_422.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + var contIn = _$lib_423.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], contOut = parentObjOut[name] = [], i; @@ -34886,7 +35086,7 @@ var _$handleArrayContainerDefaults_462 = function handleArrayContainerDefaults(p itemOut = {}, itemOpts = {}; - if(!_$lib_422.isPlainObject(itemIn)) { + if(!_$lib_423.isPlainObject(itemIn)) { itemOpts.itemIsNotPlainObject = true; itemIn = {}; } @@ -34901,10 +35101,10 @@ var _$handleArrayContainerDefaults_462 = function handleArrayContainerDefaults(p // in case this array gets its defaults rebuilt independent of the whole layout, // relink the private keys just for this array. - if(_$lib_422.isArrayOrTypedArray(previousContOut)) { + if(_$lib_423.isArrayOrTypedArray(previousContOut)) { var len = Math.min(previousContOut.length, contOut.length); for(i = 0; i < len; i++) { - _$lib_422.relinkPrivateKeys(contOut[i], previousContOut[i]); + _$lib_423.relinkPrivateKeys(contOut[i], previousContOut[i]); } } }; @@ -34920,7 +35120,7 @@ var _$handleArrayContainerDefaults_462 = function handleArrayContainerDefaults(p 'use strict'; -/* removed: var _$handleArrayContainerDefaults_462 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_463 = require('../../plots/array_container_defaults'); */; /* removed: var _$handleAnnotationDefaults_282 = require('./annotation_defaults'); */; @@ -34930,7 +35130,7 @@ var _$supplyLayoutDefaults_289 = function supplyLayoutDefaults(layoutIn, layoutO handleItemDefaults: _$handleAnnotationDefaults_282 }; - _$handleArrayContainerDefaults_462(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_463(layoutIn, layoutOut, opts); }; /** @@ -34944,8 +35144,8 @@ var _$supplyLayoutDefaults_289 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /** * Factory function for checking component arrays for subplot references. @@ -34958,12 +35158,12 @@ var _$supplyLayoutDefaults_289 = function supplyLayoutDefaults(layoutIn, layoutO * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout) * as expected of a component includeBasePlot method */ -var _$makeIncludeComponents_476 = function makeIncludeComponents(containerArrayName) { +var _$makeIncludeComponents_477 = function makeIncludeComponents(containerArrayName) { return function includeComponents(layoutIn, layoutOut) { var array = layoutIn[containerArrayName]; if(!Array.isArray(array)) return; - var Cartesian = _$registry_518.subplotsRegistry.cartesian; + var Cartesian = _$registry_519.subplotsRegistry.cartesian; var idRegex = Cartesian.idRegex; var subplots = layoutOut._subplots; var xaList = subplots.xaxis; @@ -34973,7 +35173,7 @@ var _$makeIncludeComponents_476 = function makeIncludeComponents(containerArrayN for(var i = 0; i < array.length; i++) { var itemi = array[i]; - if(!_$lib_422.isPlainObject(itemi)) continue; + if(!_$lib_423.isPlainObject(itemi)) continue; var xref = itemi.xref; var yref = itemi.yref; @@ -34981,7 +35181,7 @@ var _$makeIncludeComponents_476 = function makeIncludeComponents(containerArrayN var hasXref = idRegex.x.test(xref); var hasYref = idRegex.y.test(yref); if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_422.pushUnique(layoutOut._basePlotModules, Cartesian); + if(!hasCartesianOrGL2D) _$lib_423.pushUnique(layoutOut._basePlotModules, Cartesian); var newAxis = false; if(hasXref && xaList.indexOf(xref) === -1) { @@ -35027,7 +35227,7 @@ var _$annotations_292 = { layoutAttributes: _$attributes_284, supplyLayoutDefaults: _$supplyLayoutDefaults_289, - includeBasePlot: _$makeIncludeComponents_476('annotations'), + includeBasePlot: _$makeIncludeComponents_477('annotations'), calcAutorange: _$calcAutorange_285, draw: _$draw_290.draw, @@ -35052,7 +35252,7 @@ var _$annotations_292 = { 'use strict'; /* removed: var _$attributes_284 = require('../annotations/attributes'); */; -var __overrideAll_293 = _$edit_types_451.overrideAll; +var __overrideAll_293 = _$edit_types_452.overrideAll; var _$attributes_293 = __overrideAll_293({ _isLinkedToArray: 'annotation', @@ -35138,8 +35338,8 @@ var _$attributes_293 = __overrideAll_293({ 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; var _$convert_294 = function convert(scene) { var fullSceneLayout = scene.fullSceneLayout; @@ -35176,16 +35376,16 @@ function mockAnnAxes(ann, scene) { }; ann._xa = {}; - _$lib_422.extendFlat(ann._xa, base); - _$axes_466.setConvert(ann._xa); + _$lib_423.extendFlat(ann._xa, base); + _$axes_467.setConvert(ann._xa); ann._xa._offset = size.l + domain.x[0] * size.w; ann._xa.l2p = function() { return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); }; ann._ya = {}; - _$lib_422.extendFlat(ann._ya, base); - _$axes_466.setConvert(ann._ya); + _$lib_423.extendFlat(ann._ya, base); + _$axes_467.setConvert(ann._ya); ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; ann._ya.l2p = function() { return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); @@ -35202,14 +35402,14 @@ function mockAnnAxes(ann, scene) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_462 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_463 = require('../../plots/array_container_defaults'); */; /* removed: var _$handleAnnotationCommonDefaults_287 = require('../annotations/common_defaults'); */; /* removed: var _$attributes_293 = require('./attributes'); */; var _$handleDefaults_295 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_462(sceneLayoutIn, sceneLayoutOut, { + _$handleArrayContainerDefaults_463(sceneLayoutIn, sceneLayoutOut, { name: 'annotations', handleItemDefaults: __handleAnnotationDefaults_295, fullLayout: opts.fullLayout @@ -35218,7 +35418,7 @@ var _$handleDefaults_295 = function handleDefaults(sceneLayoutIn, sceneLayoutOut function __handleAnnotationDefaults_295(annIn, annOut, sceneLayout, opts, itemOpts) { function coerce(attr, dflt) { - return _$lib_422.coerce(annIn, annOut, _$attributes_293, attr, dflt); + return _$lib_423.coerce(annIn, annOut, _$attributes_293, attr, dflt); } function coercePosition(axLetter) { @@ -35228,7 +35428,7 @@ function __handleAnnotationDefaults_295(annIn, annOut, sceneLayout, opts, itemOp var gdMock = { _fullLayout: {} }; gdMock._fullLayout[axName] = sceneLayout[axName]; - return _$axes_466.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + return _$axes_467.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } @@ -35242,7 +35442,7 @@ function __handleAnnotationDefaults_295(annIn, annOut, sceneLayout, opts, itemOp coercePosition('z'); // if you have one coordinate you should all three - _$lib_422.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + _$lib_423.noneOrAll(annIn, annOut, ['x', 'y', 'z']); // hard-set here for completeness annOut.xref = 'x'; @@ -35263,7 +35463,7 @@ function __handleAnnotationDefaults_295(annIn, annOut, sceneLayout, opts, itemOp coerce('ay', -30); // if you have one part of arrow length you should have both - _$lib_422.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_423.noneOrAll(annIn, annOut, ['ax', 'ay']); } return annOut; @@ -35363,8 +35563,8 @@ var _$draw_296 = function draw(scene) { 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; var _$annotations3d_297 = { moduleType: 'component', @@ -35385,7 +35585,7 @@ var _$annotations3d_297 = { }; function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_518.subplotsRegistry.gl3d; + var GL3D = _$registry_519.subplotsRegistry.gl3d; if(!GL3D) return; var attrRegex = GL3D.attrRegex; @@ -35394,8 +35594,8 @@ function includeGL3D(layoutIn, layoutOut) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_422.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_422.pushUnique(layoutOut._subplots.gl3d, k); + _$lib_423.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_423.pushUnique(layoutOut._subplots.gl3d, k); } } } @@ -35630,8 +35830,8 @@ function makeComputeErrorValue(type, value) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; /* removed: var _$makeComputeError_328 = require('./compute_error'); */; @@ -35643,10 +35843,10 @@ var _$calc_327 = function calc(gd) { var calcTrace = calcdata[i], trace = calcTrace[0].trace; - if(!_$registry_518.traceIs(trace, 'errorBarsOK')) continue; + if(!_$registry_519.traceIs(trace, 'errorBarsOK')) continue; - var xa = _$axes_466.getFromId(gd, trace.xaxis), - ya = _$axes_466.getFromId(gd, trace.yaxis); + var xa = _$axes_467.getFromId(gd, trace.xaxis), + ya = _$axes_467.getFromId(gd, trace.yaxis); calcOneAxis(calcTrace, trace, xa, 'x'); calcOneAxis(calcTrace, trace, ya, 'y'); @@ -35676,7 +35876,7 @@ function calcOneAxis(calcTrace, trace, axis, coord) { } } - _$axes_466.expand(axis, vals, {padded: true}); + _$axes_467.expand(axis, vals, {padded: true}); } /** @@ -35691,8 +35891,8 @@ function calcOneAxis(calcTrace, trace, axis, coord) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$attributes_326 = require('./attributes'); */; @@ -35703,7 +35903,7 @@ var _$defaults_329 = function(traceIn, traceOut, defaultColor, opts) { containerIn = traceIn[objName] || {}; function coerce(attr, dflt) { - return _$lib_422.coerce(containerIn, containerOut, _$attributes_326, attr, dflt); + return _$lib_423.coerce(containerIn, containerOut, _$attributes_326, attr, dflt); } var hasErrorBars = ( @@ -35749,7 +35949,7 @@ var _$defaults_329 = function(traceIn, traceOut, defaultColor, opts) { if(!opts.inherit || !containerOut[copyAttr]) { coerce('color', defaultColor); coerce('thickness'); - coerce('width', _$registry_518.traceIs(traceOut, 'gl3d') ? 0 : 4); + coerce('width', _$registry_519.traceIs(traceOut, 'gl3d') ? 0 : 4); } }; @@ -35768,7 +35968,7 @@ var _$defaults_329 = function(traceIn, traceOut, defaultColor, opts) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$drawing_324 = require('../drawing'); */; -/* removed: var _$subtypes_558 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$subtypes_559 = require('../../traces/scatter/subtypes'); */; var _$plot_331 = function plot(traces, plotinfo, transitionOpts) { var isNew; @@ -35794,7 +35994,7 @@ var _$plot_331 = function plot(traces, plotinfo, transitionOpts) { } var sparse = ( - _$subtypes_558.hasMarkers(trace) && + _$subtypes_559.hasMarkers(trace) && trace.marker.maxdisplayed > 0 ); @@ -35972,24 +36172,24 @@ var _$style_332 = function style(traces) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -var __overrideAll_330 = _$edit_types_451.overrideAll; +/* removed: var _$lib_423 = require('../../lib'); */; +var __overrideAll_330 = _$edit_types_452.overrideAll; /* removed: var _$attributes_326 = require('./attributes'); */; /* removed: var _$calc_327 = require('./calc'); */; var xyAttrs = { - error_x: _$lib_422.extendFlat({}, _$attributes_326), - error_y: _$lib_422.extendFlat({}, _$attributes_326) + error_x: _$lib_423.extendFlat({}, _$attributes_326), + error_y: _$lib_423.extendFlat({}, _$attributes_326) }; delete xyAttrs.error_x.copy_zstyle; delete xyAttrs.error_y.copy_zstyle; delete xyAttrs.error_y.copy_ystyle; var xyzAttrs = { - error_x: _$lib_422.extendFlat({}, _$attributes_326), - error_y: _$lib_422.extendFlat({}, _$attributes_326), - error_z: _$lib_422.extendFlat({}, _$attributes_326) + error_x: _$lib_423.extendFlat({}, _$attributes_326), + error_y: _$lib_423.extendFlat({}, _$attributes_326), + error_z: _$lib_423.extendFlat({}, _$attributes_326) }; delete xyzAttrs.error_x.copy_ystyle; delete xyzAttrs.error_y.copy_ystyle; @@ -36066,7 +36266,7 @@ var _$domain_492 = {}; 'use strict'; -var __extendFlat_492 = _$extend_414.extendFlat; +var __extendFlat_492 = _$extend_415.extendFlat; /** * Make a xy domain attribute group @@ -36173,10 +36373,10 @@ _$domain_492.defaults = function(containerOut, layout, coerce, dfltDomains) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -var __counterRegex_345 = _$regex_437.counter; +/* removed: var _$lib_423 = require('../../lib'); */; +var __counterRegex_345 = _$regex_438.counter; var domainAttrs = _$domain_492.attributes; -var cartesianIdRegex = _$constants_471.idRegex; +var cartesianIdRegex = _$constants_472.idRegex; var gridAttrs = { rows: { @@ -36258,7 +36458,7 @@ var gridAttrs = { values: ['bottom', 'bottom plot', 'top plot', 'top'], dflt: 'bottom plot', - editType: 'ticks', + editType: 'plot', }, yside: { @@ -36266,21 +36466,36 @@ var gridAttrs = { values: ['left', 'left plot', 'right plot', 'right'], dflt: 'left plot', - editType: 'ticks', + 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; - if(!gridIn) return; + 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(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + var hasXaxes = Array.isArray(xAxes); + var hasYaxes = Array.isArray(yAxes); + var isSplomGenerated = ( + hasXaxes && xAxes !== gridIn.xaxes && + hasYaxes && yAxes !== gridIn.yaxes + ); var dfltRows, dfltColumns; @@ -36289,14 +36504,14 @@ function sizeDefaults(layoutIn, layoutOut) { dfltColumns = gridIn.subplots[0].length; } else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } var gridOut = layoutOut.grid = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + return _$lib_423.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } var rows = coerce('rows', dfltRows); @@ -36313,17 +36528,26 @@ function sizeDefaults(layoutIn, layoutOut) { 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) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } + gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) + 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, len, reversed) { +function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) { var dirGap = coerce(axLetter + 'gap', dfltGap); var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + coerce(axLetter + 'side', dfltSide); var out = new Array(len); var start = domain[0]; @@ -36343,7 +36567,7 @@ function contentDefaults(layoutIn, layoutOut) { // make sure we got to the end of handleGridSizing if(!gridOut || !gridOut._domains) return; - var gridIn = layoutIn.grid; + var gridIn = layoutIn.grid || {}; var subplots = layoutOut._subplots; var hasSubplotGrid = gridOut._hasSubplotGrid; var rows = gridOut.rows; @@ -36389,8 +36613,10 @@ function contentDefaults(layoutIn, layoutOut) { } } else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); + 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 = {}; @@ -36527,7 +36753,7 @@ var _$grid_345 = { 'use strict'; -/* removed: var _$constants_471 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_472 = require('../../plots/cartesian/constants'); */; var _$attributes_346 = { @@ -36630,7 +36856,7 @@ var _$attributes_346 = { valType: 'enumerated', values: [ 'paper', - _$constants_471.idRegex.x.toString() + _$constants_472.idRegex.x.toString() ], dflt: 'paper', @@ -36642,7 +36868,7 @@ var _$attributes_346 = { valType: 'enumerated', values: [ 'paper', - _$constants_471.idRegex.y.toString() + _$constants_472.idRegex.y.toString() ], dflt: 'paper', @@ -36664,7 +36890,7 @@ var _$attributes_346 = { 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_447 = require('../../lib/to_log_range'); */; +/* removed: var _$toLogRange_448 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -36708,7 +36934,7 @@ var _$convertCoords_347 = function convertCoords(gd, ax, newType, doExtra) { newSize = null; if(toLog) { - newPos = _$toLogRange_447(currentPos, ax.range); + newPos = _$toLogRange_448(currentPos, ax.range); // this is the inverse of the conversion we do in fromLog below // so that the conversion is reversible (notice the fromLog conversion @@ -36744,9 +36970,9 @@ var _$convertCoords_347 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_462 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_463 = require('../../plots/array_container_defaults'); */; /* removed: var _$attributes_346 = require('./attributes'); */; var name = 'images'; @@ -36757,14 +36983,14 @@ var _$supplyLayoutDefaults_348 = function supplyLayoutDefaults(layoutIn, layoutO handleItemDefaults: imageDefaults }; - _$handleArrayContainerDefaults_462(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_463(layoutIn, layoutOut, opts); }; function imageDefaults(imageIn, imageOut, fullLayout) { function coerce(attr, dflt) { - return _$lib_422.coerce(imageIn, imageOut, _$attributes_346, attr, dflt); + return _$lib_423.coerce(imageIn, imageOut, _$attributes_346, attr, dflt); } var source = coerce('source'); @@ -36786,9 +37012,9 @@ function imageDefaults(imageIn, imageOut, fullLayout) { for(var i = 0; i < 2; i++) { // 'paper' is the fallback axref var axLetter = axLetters[i], - axRef = _$axes_466.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + axRef = _$axes_467.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - _$axes_466.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + _$axes_467.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); } return imageOut; @@ -36806,7 +37032,7 @@ function imageDefaults(imageIn, imageOut, fullLayout) { /* removed: var _$d3_79 = require('d3'); */; /* removed: var _$drawing_324 = require('../drawing'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; /* removed: var _$xmlns_namespaces_405 = require('../../constants/xmlns_namespaces'); */; var _$draw_349 = function draw(gd) { @@ -36920,8 +37146,8 @@ var _$draw_349 = function draw(gd) { var thisImage = _$d3_79.select(this); // Axes if specified - var xa = _$axes_466.getFromId(gd, d.xref), - ya = _$axes_466.getFromId(gd, d.yref); + var xa = _$axes_467.getFromId(gd, d.xref), + ya = _$axes_467.getFromId(gd, d.yref); var size = fullLayout._size, width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, @@ -37030,7 +37256,7 @@ var _$images_350 = { layoutAttributes: _$attributes_346, supplyLayoutDefaults: _$supplyLayoutDefaults_348, - includeBasePlot: _$makeIncludeComponents_476('images'), + includeBasePlot: _$makeIncludeComponents_477('images'), draw: _$draw_349, @@ -37183,8 +37409,8 @@ _$helpers_358.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$attributes_352 = require('./attributes'); */; /* removed: var _$layout_attributes_508 = require('../../plots/layout_attributes'); */; @@ -37206,10 +37432,10 @@ var _$legendDefaults_354 = function legendDefaults(layoutIn, layoutOut, fullData if(_$helpers_358.legendGetsTrace(trace)) { visibleTraces++; // always show the legend by default if there's a pie - if(_$registry_518.traceIs(trace, 'pie')) visibleTraces++; + if(_$registry_519.traceIs(trace, 'pie')) visibleTraces++; } - if((_$registry_518.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + if((_$registry_519.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { defaultOrder = _$helpers_358.isGrouped({traceorder: defaultOrder}) ? 'grouped+reversed' : 'reversed'; @@ -37222,10 +37448,10 @@ var _$legendDefaults_354 = function legendDefaults(layoutIn, layoutOut, fullData } function coerce(attr, dflt) { - return _$lib_422.coerce(containerIn, containerOut, _$attributes_352, attr, dflt); + return _$lib_423.coerce(containerIn, containerOut, _$attributes_352, attr, dflt); } - var showLegend = _$lib_422.coerce(layoutIn, layoutOut, + var showLegend = _$lib_423.coerce(layoutIn, layoutOut, _$layout_attributes_508, 'showlegend', visibleTraces > 1); if(showLegend === false) return; @@ -37235,7 +37461,7 @@ var _$legendDefaults_354 = function legendDefaults(layoutIn, layoutOut, fullData coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - _$lib_422.coerceFont(coerce, 'font', layoutOut.font); + _$lib_423.coerceFont(coerce, 'font', layoutOut.font); coerce('orientation'); if(containerOut.orientation === 'h') { @@ -37261,7 +37487,7 @@ var _$legendDefaults_354 = function legendDefaults(layoutIn, layoutOut, fullData coerce('xanchor', defaultXAnchor); coerce('y', defaultY); coerce('yanchor', defaultYAnchor); - _$lib_422.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_423.noneOrAll(containerIn, containerOut, ['x', 'y']); }; var _$anchor_utils_351 = {}; @@ -37341,7 +37567,7 @@ var _$constants_353 = { 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; /* removed: var _$helpers_358 = require('./helpers'); */; @@ -37380,7 +37606,7 @@ var _$getLegendData_356 = function getLegendData(calcdata, opts) { if(!_$helpers_358.legendGetsTrace(trace) || !trace.showlegend) continue; - if(_$registry_518.traceIs(trace, 'pie')) { + if(_$registry_519.traceIs(trace, 'pie')) { if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; for(j = 0; j < cd.length; j++) { @@ -37444,8 +37670,8 @@ var _$getLegendData_356 = function getLegendData(calcdata, opts) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; var SHOWISOLATETIP = true; @@ -37486,12 +37712,12 @@ var _$handleClick_357 = function handleClick(g, gd, numClicks) { function setVisibility(fullTrace, visibility) { var fullInput = fullTrace._fullInput; - if(_$registry_518.hasTransform(fullInput, 'groupby')) { + if(_$registry_519.hasTransform(fullInput, 'groupby')) { var kcont = carrs[fullInput.index]; if(!kcont) { - var groupbyIndices = _$registry_518.getTransformIndices(fullInput, 'groupby'); + var groupbyIndices = _$registry_519.getTransformIndices(fullInput, 'groupby'); var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_422.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + kcont = _$lib_423.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); carrs[fullInput.index] = kcont; } @@ -37522,13 +37748,13 @@ var _$handleClick_357 = function handleClick(g, gd, numClicks) { } if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_422.notifier(_$lib_422._(gd, 'Double-click on legend to isolate one trace'), 'long'); + _$lib_423.notifier(_$lib_423._(gd, 'Double-click on legend to isolate one trace'), 'long'); SHOWISOLATETIP = false; } else { SHOWISOLATETIP = false; } - if(_$registry_518.traceIs(fullTrace, 'pie')) { + if(_$registry_519.traceIs(fullTrace, 'pie')) { var thisLabel = legendItem.label, thisLabelIndex = hiddenSlices.indexOf(thisLabel); @@ -37547,7 +37773,7 @@ var _$handleClick_357 = function handleClick(g, gd, numClicks) { } } - _$registry_518.call('relayout', gd, 'hiddenlabels', hiddenSlices); + _$registry_519.call('relayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; @@ -37597,7 +37823,7 @@ var _$handleClick_357 = function handleClick(g, gd, numClicks) { isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - if(!isInGroup && fullData[i].visible === true && !_$registry_518.traceIs(fullData[i], 'notLegendIsolatable')) { + if(!isInGroup && fullData[i].visible === true && !_$registry_519.traceIs(fullData[i], 'notLegendIsolatable')) { isIsolated = false; break; } @@ -37607,7 +37833,7 @@ var _$handleClick_357 = function handleClick(g, gd, numClicks) { // False is sticky; we don't change it. if(fullData[i].visible === false) continue; - if(_$registry_518.traceIs(fullData[i], 'notLegendIsolatable')) { + if(_$registry_519.traceIs(fullData[i], 'notLegendIsolatable')) { continue; } @@ -37653,11 +37879,11 @@ var _$handleClick_357 = function handleClick(g, gd, numClicks) { } } - _$registry_518.call('restyle', gd, attrUpdate, attrIndices); + _$registry_519.call('restyle', gd, attrUpdate, attrIndices); } }; -var _$helpers_533 = {}; +var _$helpers_534 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -37668,25 +37894,25 @@ var _$helpers_533 = {}; 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -_$helpers_533.formatPiePercent = function formatPiePercent(v, separators) { +_$helpers_534.formatPiePercent = function formatPiePercent(v, separators) { var vRounded = (v * 100).toPrecision(3); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_422.numSeparate(vRounded, separators) + '%'; + return _$lib_423.numSeparate(vRounded, separators) + '%'; }; -_$helpers_533.formatPieValue = function formatPieValue(v, separators) { +_$helpers_534.formatPieValue = function formatPieValue(v, separators) { var vRounded = v.toPrecision(10); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_422.numSeparate(vRounded, separators); + return _$lib_423.numSeparate(vRounded, separators); }; -_$helpers_533.getFirstFilled = function getFirstFilled(array, indices) { +_$helpers_534.getFirstFilled = function getFirstFilled(array, indices) { if(!Array.isArray(array)) return; for(var i = 0; i < indices.length; i++) { var v = array[indices[i]]; @@ -37694,8 +37920,8 @@ _$helpers_533.getFirstFilled = function getFirstFilled(array, indices) { } }; -_$helpers_533.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_533.getFirstFilled(item, indices); +_$helpers_534.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_534.getFirstFilled(item, indices); else if(item) return item; }; @@ -37710,9 +37936,9 @@ _$helpers_533.castOption = function castOption(item, indices) { 'use strict'; /* removed: var _$color_299 = require('../../components/color'); */; -var castOption = _$helpers_533.castOption; +var castOption = _$helpers_534.castOption; -var _$styleOne_534 = function styleOne(s, pt, trace) { +var _$styleOne_535 = function styleOne(s, pt, trace) { var line = trace.marker.line; var lineColor = castOption(line.color, pt.pts) || _$color_299.defaultLine; var lineWidth = castOption(line.width, pt.pts) || 0; @@ -37730,28 +37956,23 @@ var _$styleOne_534 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$drawing_324 = require('../drawing'); */; /* removed: var _$color_299 = require('../color'); */; -/* removed: var _$subtypes_558 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_534 = require('../../traces/pie/style_one'); */; - +/* removed: var _$subtypes_559 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_535 = require('../../traces/pie/style_one'); */; var _$style_360 = function style(s, gd) { s.each(function(d) { var traceGroup = _$d3_79.select(this); - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); + var layers = _$lib_423.ensureSingle(traceGroup, 'g', 'layers'); layers.style('opacity', d[0].trace.opacity); var fill = layers @@ -37781,12 +38002,14 @@ var _$style_360 = function style(s, gd) { .each(styleBoxes) .each(stylePies) .each(styleLines) - .each(stylePoints); + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); function styleLines(d) { var trace = d[0].trace; var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_558.hasLines(trace); + var showLine = _$subtypes_559.hasLines(trace); var contours = trace.contours; if(contours && contours.type === 'constraint') { @@ -37812,9 +38035,9 @@ var _$style_360 = function style(s, gd) { function stylePoints(d) { var d0 = d[0], trace = d0.trace, - showMarkers = _$subtypes_558.hasMarkers(trace), - showText = _$subtypes_558.hasText(trace), - showLines = _$subtypes_558.hasLines(trace); + showMarkers = _$subtypes_559.hasMarkers(trace), + showText = _$subtypes_559.hasText(trace), + showLines = _$subtypes_559.hasLines(trace); var dMod, tMod; @@ -37822,7 +38045,7 @@ var _$style_360 = function style(s, gd) { // use d0.trace to infer arrayOk attributes function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_422.nestedProperty(trace, attrIn).get(), + var valIn = _$lib_423.nestedProperty(trace, attrIn).get(), valToBound = (Array.isArray(valIn) && arrayToValFn) ? arrayToValFn(valIn) : valIn; @@ -37842,10 +38065,10 @@ var _$style_360 = function style(s, gd) { if(showMarkers) { dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_422.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_422.mean, [2, 16]); + dEdit.mo = boundVal('marker.opacity', _$lib_423.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_423.mean, [2, 16]); dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_422.mean, [0, 5]); + dEdit.mlw = boundVal('marker.line.width', _$lib_423.mean, [0, 5]); tEdit.marker = { sizeref: 1, sizemin: 1, @@ -37867,8 +38090,8 @@ var _$style_360 = function style(s, gd) { dEdit.tf = boundVal('textfont.family', pickFirst); } - dMod = [_$lib_422.minExtend(d0, dEdit)]; - tMod = _$lib_422.minExtend(trace, tEdit); + dMod = [_$lib_423.minExtend(d0, dEdit)]; + tMod = _$lib_423.minExtend(trace, tEdit); } var ptgroup = _$d3_79.select(this).select('g.legendpoints'); @@ -37899,7 +38122,7 @@ var _$style_360 = function style(s, gd) { markerLine = marker.line || {}, barpath = _$d3_79.select(this).select('g.legendpoints') .selectAll('path.legendbar') - .data(_$registry_518.traceIs(trace, 'bar') ? [d] : []); + .data(_$registry_519.traceIs(trace, 'bar') ? [d] : []); barpath.enter().append('path').classed('legendbar', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); @@ -37922,7 +38145,7 @@ var _$style_360 = function style(s, gd) { var trace = d[0].trace, pts = _$d3_79.select(this).select('g.legendpoints') .selectAll('path.legendbox') - .data(_$registry_518.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + .data(_$registry_519.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendbox', true) // if we want the median bar, prepend M6,0H-6 .attr('d', 'M6,6H-6V-6H6Z') @@ -37936,7 +38159,61 @@ var _$style_360 = function style(s, gd) { .call(_$color_299.fill, trace.fillcolor); if(w) { - p.call(_$color_299.stroke, trace.line.color); + _$color_299.stroke(p, trace.line.color); + } + }); + } + + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_79.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_79.select(this); + + p.style('stroke-width', w + 'px') + .call(_$color_299.fill, container.fillcolor); + + if(w) { + _$color_299.stroke(p, container.line.color); + } + }); + } + + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_79.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_79.select(this); + + p.style('fill', 'none') + .call(_$drawing_324.dashLine, container.line.dash, w); + + if(w) { + _$color_299.stroke(p, container.line.color); } }); } @@ -37945,13 +38222,13 @@ var _$style_360 = function style(s, gd) { var trace = d[0].trace, pts = _$d3_79.select(this).select('g.legendpoints') .selectAll('path.legendpie') - .data(_$registry_518.traceIs(trace, 'pie') && trace.visible ? [d] : []); + .data(_$registry_519.traceIs(trace, 'pie') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendpie', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); pts.exit().remove(); - if(pts.size()) pts.call(_$styleOne_534, d[0], trace); + if(pts.size()) pts.call(_$styleOne_535, d[0], trace); } }; @@ -37967,13 +38244,13 @@ var _$style_360 = function style(s, gd) { /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; /* removed: var _$dragelement_321 = require('../dragelement'); */; /* removed: var _$drawing_324 = require('../drawing'); */; /* removed: var _$color_299 = require('../color'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; /* removed: var _$handleClick_357 = require('./handle_click'); */; /* removed: var _$constants_353 = require('./constants'); */; @@ -38010,52 +38287,35 @@ var _$draw_355 = function draw(gd) { return; } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); - - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); - - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var firstRender = false; + var legend = _$lib_423.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - var bg = legend.selectAll('rect.bg') - .data([0]); + var clipPath = _$lib_423.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' + var bg = _$lib_423.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); }); bg.call(_$color_299.stroke, opts.bordercolor) .call(_$color_299.fill, opts.bgcolor) .style('stroke-width', opts.borderwidth + 'px'); - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); - - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); + var scrollBox = _$lib_423.ensureSingle(legend, 'g', 'scrollbox'); - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); - - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', + var scrollBar = _$lib_423.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ rx: 20, ry: 3, width: 0, height: 0 }) .call(_$color_299.fill, '#808BA4'); + }); var groups = scrollBox.selectAll('g.groups') .data(legendData); @@ -38066,7 +38326,7 @@ var _$draw_355 = function draw(gd) { groups.exit().remove(); var traces = groups.selectAll('g.traces') - .data(_$lib_422.identity); + .data(_$lib_423.identity); traces.enter().append('g').attr('class', 'traces'); traces.exit().remove(); @@ -38074,7 +38334,7 @@ var _$draw_355 = function draw(gd) { traces.call(_$style_360, gd) .style('opacity', function(d) { var trace = d[0].trace; - if(_$registry_518.traceIs(trace, 'pie')) { + if(_$registry_519.traceIs(trace, 'pie')) { return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; } else { return trace.visible === 'legendonly' ? 0.5 : 1; @@ -38086,7 +38346,6 @@ var _$draw_355 = function draw(gd) { .call(setupTraceToggle, gd); }); - var firstRender = legend.enter().size() !== 0; if(firstRender) { computeLegendDimensions(gd, groups, traces); expandMargin(gd); @@ -38228,7 +38487,7 @@ var _$draw_355 = function draw(gd) { scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); legend.on('wheel', function() { - scrollBoxY = _$lib_422.constrain( + scrollBoxY = _$lib_423.constrain( opts._scrollY + _$d3_79.event.deltaY / scrollBarYMax * scrollBoxYMax, 0, scrollBoxYMax); @@ -38249,7 +38508,7 @@ var _$draw_355 = function draw(gd) { var e = _$d3_79.event.sourceEvent; if(e.buttons === 2 || e.ctrlKey) return; - scrollBoxY = _$lib_422.constrain( + scrollBoxY = _$lib_423.constrain( (e.clientY - eventY0) / scrollRatio + scrollBoxY0, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); @@ -38300,7 +38559,7 @@ var _$draw_355 = function draw(gd) { }, doneFn: function() { if(xf !== undefined && yf !== undefined) { - _$registry_518.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + _$registry_519.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); } }, clickFn: function(numClicks, e) { @@ -38331,14 +38590,11 @@ function drawTexts(g, gd) { var legendItem = g.data()[0][0], fullLayout = gd._fullLayout, trace = legendItem.trace, - isPie = _$registry_518.traceIs(trace, 'pie'), + isPie = _$registry_519.traceIs(trace, 'pie'), traceIndex = trace.index, name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); + var text = _$lib_423.ensureSingle(g, 'text', 'legendtext'); text.attr('text-anchor', 'start') .classed('user-select-none', true) @@ -38346,13 +38602,13 @@ function drawTexts(g, gd) { .text(name); function textLayout(s) { - _$svg_text_utils_445.convertToTspans(s, gd, function() { + _$svg_text_utils_446.convertToTspans(s, gd, function() { computeTextDimensions(g, gd); }); } if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_445.makeEditable, {gd: gd}) + text.call(_$svg_text_utils_446.makeEditable, {gd: gd}) .call(textLayout) .on('edit', function(text) { this.text(text) @@ -38362,24 +38618,14 @@ function drawTexts(g, gd) { if(!this.text()) text = ' \u0020\u0020 '; - var transforms, direction; var fullInput = legendItem.trace._fullInput || {}; var update = {}; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_518.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_518.getTransformIndices(fullInput, 'groupby'); + if(_$registry_519.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_519.getTransformIndices(fullInput, 'groupby'); var index = groupbyIndices[groupbyIndices.length - 1]; - var kcont = _$lib_422.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + var kcont = _$lib_423.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); if(origText === '') { kcont.remove(legendItem.trace._group); @@ -38392,7 +38638,7 @@ function drawTexts(g, gd) { update.name = text; } - return _$registry_518.call('restyle', gd, update, traceIndex); + return _$registry_519.call('restyle', gd, update, traceIndex); }); } else { textLayout(text); @@ -38403,15 +38649,11 @@ function setupTraceToggle(g, gd) { var newMouseDownTime, numClicks = 1; - var traceToggle = g.selectAll('rect') - .data([0]); - - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_299.fill, 'rgba(0,0,0,0)'); - + var traceToggle = _$lib_423.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_299.fill, 'rgba(0,0,0,0)'); + }); traceToggle.on('mousedown', function() { newMouseDownTime = (new Date()).getTime(); @@ -38469,7 +38711,7 @@ function computeTextDimensions(g, gd) { } else { var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_445.lineCount(text); + var textLines = _$svg_text_utils_446.lineCount(text); var textNode = text.node(); height = lineHeight * textLines; @@ -38480,7 +38722,7 @@ function computeTextDimensions(g, gd) { var textY = lineHeight * (0.3 + (1 - textLines) / 2); // TODO: this 40 should go in a constants file (along with other // values related to the legend symbol size) - _$svg_text_utils_445.positionText(text, 40, textY); + _$svg_text_utils_446.positionText(text, 40, textY); } height = Math.max(height, 16) + 3; @@ -38768,7 +39010,7 @@ var _$button_attributes_366 = { /* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; /* removed: var _$attributes_298 = require('../color/attributes'); */; -var __extendFlat_365 = _$extend_414.extendFlat; +var __extendFlat_365 = _$extend_415.extendFlat; /* removed: var _$button_attributes_366 = require('./button_attributes'); */; _$button_attributes_366 = __extendFlat_365(_$button_attributes_366, { @@ -38894,7 +39136,7 @@ var _$constants_367 = { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$color_299 = require('../color'); */; /* removed: var _$attributes_365 = require('./attributes'); */; @@ -38907,7 +39149,7 @@ var _$handleDefaults_368 = function handleDefaults(containerIn, containerOut, la selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(selectorIn, selectorOut, _$attributes_365, attr, dflt); + return _$lib_423.coerce(selectorIn, selectorOut, _$attributes_365, attr, dflt); } var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); @@ -38918,12 +39160,12 @@ var _$handleDefaults_368 = function handleDefaults(containerIn, containerOut, la var posDflt = getPosDflt(containerOut, layout, counterAxes); coerce('x', posDflt[0]); coerce('y', posDflt[1]); - _$lib_422.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_423.noneOrAll(containerIn, containerOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); - _$lib_422.coerceFont(coerce, 'font', layout.font); + _$lib_423.coerceFont(coerce, 'font', layout.font); var bgColor = coerce('bgcolor'); coerce('activecolor', _$color_299.contrast(bgColor, _$constants_367.lightAmount, _$constants_367.darkAmount)); @@ -38938,14 +39180,14 @@ function buttonsDefaults(containerIn, containerOut, calendar) { var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_422.coerce(buttonIn, buttonOut, _$button_attributes_366, attr, dflt); + return _$lib_423.coerce(buttonIn, buttonOut, _$button_attributes_366, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { buttonIn = buttonsIn[i]; buttonOut = {}; - if(!_$lib_422.isPlainObject(buttonIn)) continue; + if(!_$lib_423.isPlainObject(buttonIn)) continue; var step = coerce('step'); if(step !== 'all') { @@ -39050,12 +39292,13 @@ function getXRange(axisLayout, buttonLayout) { /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; /* removed: var _$color_299 = require('../color'); */; /* removed: var _$drawing_324 = require('../drawing'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_469 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_470 = require('../../plots/cartesian/axis_ids'); */; /* removed: var _$anchor_utils_351 = require('../legend/anchor_utils'); */; /* removed: var _$alignment_399 = require('../../constants/alignment'); */; @@ -39108,7 +39351,7 @@ var _$draw_369 = function draw(gd) { button.on('click', function() { if(gd._dragged) return; - _$registry_518.call('relayout', gd, update); + _$registry_519.call('relayout', gd, update); }); button.on('mouseover', function() { @@ -39128,7 +39371,7 @@ var _$draw_369 = function draw(gd) { }; function makeSelectorData(gd) { - var axes = _$axis_ids_469.list(gd, 'x', true); + var axes = _$axis_ids_470.list(gd, 'x', true); var data = []; for(var i = 0; i < axes.length; i++) { @@ -39161,13 +39404,9 @@ function isActive(axisLayout, opts, update) { } function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - - rect.attr('shape-rendering', 'crispEdges'); + var rect = _$lib_423.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); rect.attr({ 'rx': _$constants_367.rx, @@ -39187,17 +39426,13 @@ function getFillColor(selectorLayout, d) { function drawButtonText(button, selectorLayout, d, gd) { function textLayout(s) { - _$svg_text_utils_445.convertToTspans(s, gd); + _$svg_text_utils_446.convertToTspans(s, gd); } - var text = button.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - - text.attr('text-anchor', 'middle'); + var text = _$lib_423.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); text.call(_$drawing_324.font, selectorLayout.font) .text(getLabel(d)) @@ -39223,7 +39458,7 @@ function reposition(gd, buttons, opts, axName, selector) { var text = button.select('.selector-text'); var tHeight = opts.font.size * __LINE_SPACING_369; - var hEff = Math.max(tHeight * _$svg_text_utils_445.lineCount(text), 16) + 3; + var hEff = Math.max(tHeight * _$svg_text_utils_446.lineCount(text), 16) + 3; height = Math.max(height, hEff); }); @@ -39235,7 +39470,7 @@ function reposition(gd, buttons, opts, axName, selector) { var tWidth = text.node() && _$drawing_324.bBox(text.node()).width; var tHeight = opts.font.size * __LINE_SPACING_369; - var tLines = _$svg_text_utils_445.lineCount(text); + var tLines = _$svg_text_utils_446.lineCount(text); var wEff = Math.max(tWidth + 10, _$constants_367.minButtonWidth); @@ -39254,7 +39489,7 @@ function reposition(gd, buttons, opts, axName, selector) { height: height }); - _$svg_text_utils_445.positionText(text, wEff / 2, + _$svg_text_utils_446.positionText(text, wEff / 2, height / 2 - ((tLines - 1) * tHeight / 2) + 3); width += wEff + 5; @@ -39465,8 +39700,8 @@ var _$constants_374 = { 'use strict'; -var listAxes = _$axis_ids_469.list; -var __getAutoRange_373 = _$autorange_465.getAutoRange; +var listAxes = _$axis_ids_470.list; +var __getAutoRange_373 = _$autorange_466.getAutoRange; /* removed: var _$constants_374 = require('./constants'); */; var _$calcAutorange_373 = function calcAutorange(gd) { @@ -39538,29 +39773,31 @@ var _$oppaxis_attributes_378 = { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$attributes_372 = require('./attributes'); */; /* removed: var _$oppaxis_attributes_378 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_469 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$axis_ids_470 = require('../../plots/cartesian/axis_ids'); */; var _$handleDefaults_375 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; + 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_422.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; + if(!_$lib_423.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; } - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(containerIn, containerOut, _$attributes_372, attr, dflt); + return _$lib_423.coerce(containerIn, containerOut, _$attributes_372, attr, dflt); } function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_422.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_378, attr, dflt); + return _$lib_423.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_378, attr, dflt); } var visible = coerce('visible'); @@ -39578,12 +39815,12 @@ var _$handleDefaults_375 = function handleDefaults(layoutIn, layoutOut, axName) if(subplots) { var yIds = subplots.cartesian .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_469.name2id(axName); + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_470.name2id(axName); }) .map(function(subplotId) { return subplotId.substr(subplotId.indexOf('y'), subplotId.length); }); - var yNames = _$lib_422.simpleMap(yIds, _$axis_ids_469.id2name); + var yNames = _$lib_423.simpleMap(yIds, _$axis_ids_470.id2name); for(var i = 0; i < yNames.length; i++) { var yName = yNames[i]; @@ -39620,7 +39857,7 @@ var _$handleDefaults_375 = function handleDefaults(layoutIn, layoutOut, axName) 'use strict'; -var _$attributes_464 = { +var _$attributes_465 = { xaxis: { valType: 'subplotid', @@ -39647,90 +39884,20 @@ var _$attributes_464 = { 'use strict'; - -var _$handleCategoryOrderDefaults_470 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; - - var arrayIn = containerIn.categoryarray, - orderDefault; - - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); - - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; - - var order = coerce('categoryorder', orderDefault); - - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); - - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var colorMix = _$tinycolor_264.mix; -var lightFraction = _$attributes_298.lightFraction; -/* removed: var _$lib_422 = require('../../lib'); */; - /** - * @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 + * 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 */ -var _$handleLineGridDefaults_480 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; - - var dfltColor = opts.dfltColor; - - function coerce2(attr, dflt) { - return _$lib_422.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); +var _$clearGlCanvases_410 = function clearGlCanvases(gd) { + var fullLayout = gd._fullLayout; - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); + }); } }; @@ -39745,1196 +39912,1930 @@ var _$handleLineGridDefaults_480 = function handleLineGridDefaults(containerIn, 'use strict'; -/* removed: var _$d3_79 = require('d3'); */; - -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { - - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. - - var categoryArray = []; - - var traceLines = data.map(function(d) {return d[axisLetter];}); - - var i, j, tracePoints, category, insertionIndex; - - var bisector = _$d3_79.bisector(sortFunction).left; - - for(i = 0; i < traceLines.length; i++) { +var FROM_BL = _$alignment_399.FROM_BL; - tracePoints = traceLines[i]; +var _$scaleZoom_483 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } - for(j = 0; j < tracePoints.length; j++) { + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - category = tracePoints[j]; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - insertionIndex = bisector(categoryArray, category); +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } - } + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - return categoryArray; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; } +var _$BuildLog_221 = BuildLog; -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ - -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_481 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_79.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_79.descending, data); - case 'trace': return []; - default: return []; - } -}; +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; -'use strict'; + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; -/* removed: var _$layout_attributes_478 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_488 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_487 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_486 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_470 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_480 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_485 = require('./set_convert'); */; -/* removed: var _$orderedCategories_481 = require('./ordered_categories'); */; + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; -/** - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_468 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - var visible = coerce('visible', !options.cheateronly); + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - var axType = containerOut.type; + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; - if(axType === 'date') { - var handleCalendarDefaults = _$registry_518.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; - _$setConvert_485(containerOut, layoutOut); + // categorize where intersection point is along A and B - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if(autoRange) coerce('rangemode'); + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; - coerce('range'); - containerOut.cleanRange(); + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside - _$handleCategoryOrderDefaults_470(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_481(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} +var _$Epsilon_222 = Epsilon; - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if(!visible) return containerOut; +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_422.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - _$handleTickValueDefaults_488(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_486(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_487(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_480(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_478 - }); + // 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] }); + } - if(containerOut.showline || containerOut.ticks) coerce('mirror'); + // the first LineString is considered the outside + var out = LineString(coords[0]); - if(options.automargin) coerce('automargin'); + // 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 containerOut; -}; + return out; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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)); -'use strict'; + // 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); + } -/* removed: var _$lib_422 = require('../../lib'); */; -var id2name = _$axis_ids_469.id2name; + // 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 _$handleConstraintDefaults_472 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); + var roots = newNode(null); - if(containerOut.fixedrange) return; + 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; + } + } - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_422.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); + // 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--; + } + } - if(!containerIn.scaleanchor) return; + // now we can add ourselves + root.children.push(node); + } - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + // 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); + } - var scaleanchor = _$lib_422.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); + // 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 - 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; + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_422.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.'); - } -}; + 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; + } -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. + var geopolys = []; - var thisType = layoutOut[id2name(thisID)].type; + 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])); + } - var i, j, idj, axj; + 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); + } - var linkableAxes = []; - for(j = 0; j < allAxisIds.length; j++) { - idj = allAxisIds[j]; - if(idj === thisID) continue; + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - axj = layoutOut[id2name(idj)]; - if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); - } + // lastly, construct the approrpriate GeoJSON object - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[i]; + 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 + }; + } +}; - var linkableAxesNoLoops = []; - for(j = 0; j < linkableAxes.length; j++) { - idj = linkableAxes[j]; - if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); - } - return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; - } - } +var _$GeoJSON_223 = GeoJSON; - return {linkableAxes: linkableAxes, thisGroup: null}; -} +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// -/* - * 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; +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } +}; - if(thisGroup === null) { - thisGroup = {}; - thisGroup[thisID] = 1; - thisGroupIndex = constraintGroups.length; - constraintGroups.push(thisGroup); - } - else { - thisGroupIndex = constraintGroups.indexOf(thisGroup); - } +var _$LinkedList_225 = LinkedList; - var thisGroupKeys = Object.keys(thisGroup); +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // 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; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 is the core work-horse +// +/* removed: var _$LinkedList_225 = require('./linked-list'); */; -'use strict'; +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm -/* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; + // + // segment creation + // -/* removed: var _$lib_422 = require('../../lib'); */; + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } -var _$handlePositionDefaults_482 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; + // + // event logic + // - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; + var event_root = _$LinkedList_225.create(); - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } - } + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_89(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - var anchor = _$lib_422.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start - if(anchor === 'free') coerce('position', dfltPosition); + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } - _$lib_422.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_422.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); - } + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_225.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_422.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); - } + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_225.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } - coerce('layer'); + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } - return containerOut; -}; + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (buildLog) + buildLog.segmentChop(ev.seg, end); + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } -'use strict'; + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$autoType_467 = require('./axis_autotype'); */; -var name2id = _$axis_ids_469.name2id; + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored - */ -var _$handleTypeDefaults_490 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } + // + // status logic + // - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); + var status_root = _$LinkedList_225.create(); - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; - } - } -}; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } - var id = ax._id, - axLetter = id.charAt(0); + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } + if (buildLog) + buildLog.checkIntersection(seg1, seg2); - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; + var i = eps.linesIntersect(a1, a2, b1, b2); - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; + if (i === false){ + // segments are parallel or coincident - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_518.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection - if(trace[calAttr] !== calendar) calendar = undefined; - } + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); - ax.type = _$autoType_467(boxPositions, calendar); - } - else { - ax.type = _$autoType_467(d0[axLetter] || [d0[axLetter + '0']], calendar); - } -} + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; + var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; - } - } - } -} + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_518.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_518.traceIs(trace._fullInput || {}, 'candlestick'); + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); -'use strict'; + if (buildLog) + buildLog.vert(ev.pt[0]); -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$color_299 = require('../../components/color'); */; -/* removed: var _$layout_attributes_508 = require('../layout_attributes'); */; + if (ev.isStart){ -/* removed: var _$layout_attributes_478 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_490 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_468 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_472 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_482 = require('./position_defaults'); */; -/* removed: var _$axis_ids_469 = require('./axis_ids'); */; + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; -var _$supplyLayoutDefaults_479 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } - if(!_$registry_518.traceIs(trace, 'cartesian') && !_$registry_518.traceIs(trace, 'gl2d')) { - continue; - } + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev - var xaName = _$axis_ids_469.id2name(trace.xaxis); - var yaName = _$axis_ids_469.id2name(trace.yaxis); + // merge ev.seg's fill information into eve.seg - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_518.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - // 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) xaCheater[xaName] = 1; - } + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } - // check for default formatting tweaks - if(_$registry_518.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } + if (buildLog) + buildLog.segmentUpdate(eve.seg); - if(_$registry_518.traceIs(trace, 'oriented')) { - var positionAxis = trace.orientation === 'h' ? yaName : xaName; - noGrids[positionAxis] = true; - } - } + ev.other.remove(); + ev.remove(); + } - var subplots = layoutOut._subplots; - var xIds = subplots.xaxis; - var yIds = subplots.yaxis; - var xNames = _$lib_422.simpleMap(xIds, _$axis_ids_469.id2name); - var yNames = _$lib_422.simpleMap(yIds, _$axis_ids_469.id2name); - var axNames = xNames.concat(yNames); + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } - // plot_bgcolor only makes sense if there's a (2D) plot! - // TODO: bgcolor for each subplot, to inherit from the main one - var plot_bgcolor = _$color_299.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_422.coerce(layoutIn, layoutOut, _$layout_attributes_508, 'plot_bgcolor'); - } + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle - var bgColor = _$color_299.combine(plot_bgcolor, layoutOut.paper_bgcolor); - - var axName, axLetter, axLayoutIn, axLayoutOut; + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } - function coerce(attr, dflt) { - return _$lib_422.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_478, attr, dflt); - } + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point - function coerce2(attr, dflt) { - return _$lib_422.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_478, attr, dflt); - } + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; - } + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_225.node({ ev: ev })); + } + else{ + var st = ev.status; - function getOverlayableAxes(axLetter, axName) { - var list = (axLetter === 'x') ? xNames : yNames; - var out = []; + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } - for(var j = 0; j < list.length; j++) { - var axName2 = list[j]; + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); - if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { - out.push(_$axis_ids_469.name2id(axName2)); - } - } + if (buildLog) + buildLog.statusRemove(st.ev.seg); - return out; - } + // remove the status + st.remove(); - // first pass creates the containers, determines types, and handles most of the settings - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } - if(!_$lib_422.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } + // remove the event and continue + event_root.getHead().remove(); + } - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; + if (buildLog) + buildLog.done(); - _$handleTypeDefaults_490(axLayoutIn, axLayoutOut, coerce, fullData, axName); + return segments; + } - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; - _$handleAxisDefaults_468(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} - if(!showSpikes) { - delete axLayoutOut.spikecolor; - delete axLayoutOut.spikethickness; - delete axLayoutOut.spikedash; - delete axLayoutOut.spikemode; - delete axLayoutOut.spikesnap; - } +var _$Intersecter_224 = Intersecter; - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - _$handlePositionDefaults_482(axLayoutIn, axLayoutOut, coerce, positioningOptions); +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// - axLayoutOut._input = axLayoutIn; - } +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_518.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_518.getComponentMethod('rangeselector', 'handleDefaults'); + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } - for(i = 0; i < xNames.length; i++) { - axName = xNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + if (buildLog) + buildLog.chainStart(seg); - rangeSliderDefaults(layoutIn, layoutOut, axName); + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } - if(axLayoutOut.type === 'date') { - rangeSelectorDefaults( - axLayoutIn, - axLayoutOut, - layoutOut, - yNames, - axLayoutOut.calendar - ); - } + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } - coerce('fixedrange'); - } + if (next_match === second_match){ + // we matched a single chain - for(i = 0; i < yNames.length; i++) { - axName = yNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + if (buildLog) + buildLog.chainMatch(first_match.index); - var anchoredAxis = layoutOut[_$axis_ids_469.id2name(axLayoutOut.anchor)]; + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head - coerce('fixedrange', fixedRangeDflt); - } + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - // Finally, handle scale constraints. 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). + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } - // sets of axes linked by `scaleanchor` along with the scaleratios compounded - // together, populated in handleConstraintDefaults - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + if (buildLog) + buildLog.chainClose(first_match.index); - _$handleConstraintDefaults_472(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } -}; + // we have a closed chain! + regions.push(chain); + return; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } -'use strict'; + // otherwise, we matched two chains, so we need to combine those chains together -/* removed: var _$d3_79 = require('d3'); */; + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$drawing_324 = require('../../components/drawing'); */; -/* removed: var _$axes_466 = require('./axes'); */; -var axisRegex = _$constants_471.attrRegex; + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; -var _$transitionAxes_489 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); - } - } - if(!update.to) continue; + var F = first_match.index; + var S = second_match.index; - update.axisName = axisName; - update.length = axis._length; + if (buildLog) + buildLog.chainConnect(F, S); - axes.push(axisLetter); + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); - updates[axisLetter] = update; - } - } + return regions; +} - return updates; - } +var _$SegmentChainer_226 = SegmentChainer; - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; - - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; +// +// filter a list of segments based on boolean operations +// - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + if (buildLog) + buildLog.selected(result); - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; - } + return result; +} - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); - } - } +var _$SegmentSelector_227 = SegmentSelector; - return affectedSubplots; - } +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); +/* removed: var _$BuildLog_221 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_222 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_224 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_226 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_227 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_223 = require('./lib/geojson'); */; - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); +var buildLog = false; +var epsilon = _$Epsilon_222(); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_221(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v){ + return epsilon.epsilon(v); + }, - redrawObjs(fullLayout.annotations || [], _$registry_518.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_518.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_518.getComponentMethod('images', 'draw'), true); - } + // core API + segments: function(poly){ + var i = _$Intersecter_224(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_224(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_227.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_227.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_227.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_227.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_227.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_226(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; - } + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_223.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_223.fromPolygon(PolyBool, epsilon, poly); + }, - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; + // 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); + } +}; - activeAxIds = [xa._id, ya._id]; +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); +} - for(i = 0; i < activeAxIds.length; i++) { - _$axes_466.doTicks(gd, activeAxIds[i], true); - } +if (typeof window === 'object') + window.PolyBool = PolyBool; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +var _$PolyBool_220 = PolyBool; - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - } +var _$polygon_435 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - redrawObjs(fullLayout.annotations || [], _$registry_518.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_518.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_518.getComponentMethod('images', 'draw'), true); - } +'use strict'; - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; +var dot = _$matrix_429.dot; +var __BADNUM_435 = _$numerical_403.BADNUM; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_324.setTranslate, 0, 0) - .call(_$drawing_324.setScale, 1, 1); +var polygon = _$polygon_435 = {}; - subplot.plot - .call(_$drawing_324.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_324.setScale, 1, 1); +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; - // 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_324.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_324.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_324.hideOutsideRangePoints, subplot); + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); } - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed - var viewBox = []; + var isRect = false, + rectFirstEdgeTest; - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; + } + } + } - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; + if(x === __BADNUM_435 || x < xmin || x > xmax || y === __BADNUM_435 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + return true; + } - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; + if(x === __BADNUM_435 || x < xmin || x > xmax || y === __BADNUM_435 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; } - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); - var editX = !!xUpdate; - var editY = !!yUpdate; + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; - - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; - - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_324.setTranslate, clipDx, clipDy) - .call(_$drawing_324.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - - subplot.plot - .call(_$drawing_324.setTranslate, plotDx, plotDy) - .call(_$drawing_324.setScale, xScaleFactor, yScaleFactor) - - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_324.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_324.setTextPointsScale, 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 < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; - - axi.range = to.slice(); - } - - // Signal that this transition has completed: - onComplete && onComplete(); - - return _$registry_518.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + if(y <= ycross && x !== xmini) crossings++; } - }); - } - - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; - - axi.range = axi._r.slice(); } - return _$registry_518.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; } - var t1, t2, raf; - var easeFn = _$d3_79.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 < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } - - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; } } - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); - - return Promise.resolve(); + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; }; -var _$get_data_495 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_518 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_471.SUBPLOT_PATTERN; - /** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces + * Test multiple polygons */ -_$get_data_495.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_518.subplotsRegistry[type]; - if(!basePlotModule) return []; +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; - var attr = basePlotModule.attr; - var subplotCalcData = []; + for(var i = 0; i < list.length; i++) { + 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); + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + return yes; } - return subplotCalcData; + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; }; -_$get_data_495.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_518.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; } - - return moduleCalcData; + return false; }; /** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. + * Make a filtering polygon, to minimize the number of segments * - * @return {array} list of trace objects. + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs */ -_$get_data_495.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_518.subplotsRegistry[type]) return []; - - var attr = _$registry_518.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; - - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; - } +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; - for(var i = 0; i < data.length; i++) { - trace = data[i]; + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); - if(type === 'gl2d' && _$registry_518.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; } } - else { - if(trace[attr] === subplotId) subplotData.push(trace); - } } - return subplotData; + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } + + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; }; -var _$cartesian_477 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40946,542 +41847,467 @@ var _$cartesian_477 = {}; 'use strict'; -/* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$plots_510 = require('../plots'); */; -var getModuleCalcData = _$get_data_495.getModuleCalcData; - -/* removed: var _$axis_ids_469 = require('./axis_ids'); */; -/* removed: var _$constants_471 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_405 = require('../../constants/xmlns_namespaces'); */; - -_$cartesian_477.name = 'cartesian'; - -_$cartesian_477.attr = ['xaxis', 'yaxis']; - -_$cartesian_477.idRoot = ['x', 'y']; - -_$cartesian_477.idRegex = _$constants_471.idRegex; - -_$cartesian_477.attrRegex = _$constants_471.attrRegex; +/* removed: var _$PolyBool_220 = require('polybooljs'); */; -_$cartesian_477.attributes = _$attributes_464; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$color_299 = require('../../components/color'); */; +/* removed: var _$fx_341 = require('../../components/fx'); */; -_$cartesian_477.layoutAttributes = _$layout_attributes_478; +/* removed: var _$polygon_435 = require('../../lib/polygon'); */; +/* removed: var _$throttle_447 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_338.makeEventData; +var getFromId = _$axis_ids_470.getFromId; +var __sortModules_484 = _$sort_modules_517.sortModules; -_$cartesian_477.supplyLayoutDefaults = _$supplyLayoutDefaults_479; +/* removed: var _$constants_472 = require('./constants'); */; +var MINSELECT = _$constants_472.MINSELECT; -_$cartesian_477.transitionAxes = _$transitionAxes_489; +var filteredPolygon = _$polygon_435.filter; +var polygonTester = _$polygon_435.tester; +var multipolygonTester = _$polygon_435.multitester; -_$cartesian_477.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; +function getAxId(ax) { return ax._id; } - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_469.id2name(xi)] || {}).anchor; - if(!_$constants_471.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); - if(!allY[yi]) { - allY[yi] = 1; - _$lib_422.pushUnique(yList, yi); - } - } + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; } - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_469.id2name(yi)] || {}).anchor; - if(!_$constants_471.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); - - if(!allX[xi]) { - allX[xi] = 1; - _$lib_422.pushUnique(xList, xi); - } - } + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; } - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_471.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_469.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_469.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_472.BENDPX); } -}; - -_$cartesian_477.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; - - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); - } + 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'); - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + var corners = zoomLayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_299.background, + stroke: _$color_299.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_472.SELECTID; + var selection = []; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + for(i = 0; i < gd.calcdata.length; i++) { + cd = gd.calcdata[i]; + trace = cd[0].trace; - cdSubplot.push(cd); - } + if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; + if(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); + } } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(v[index]); }; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; - - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + function ascending(a, b) { return a - b; } - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); - } -} + // allow subplots to override fillRangeItems routine + var fillRangeItems; -_$cartesian_477.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + if(plotinfo.fillRangeItems) { + fillRangeItems = plotinfo.fillRangeItems; + } else { + if(mode === 'select') { + fillRangeItems = function(eventData, poly) { + var ranges = eventData.range = {}; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + var axLetter = ax._id.charAt(0); + ranges[ax._id] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(poly[axLetter + 'max']) + ].sort(ascending); + } + }; + } else { + fillRangeItems = function(eventData, poly, filterPoly) { + var dataPts = eventData.lassoPoints = {}; - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); + } + }; + } } - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + dragOptions.moveFn = function(dx0, dy0) { + x1 = Math.max(0, Math.min(pw, dx0 + x0)); + y1 = Math.max(0, Math.min(ph, dy0 + y0)); - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + var dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(mode === 'select') { + var direction = fullLayout.selectdirection; - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + 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; } - } - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); - } - - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); - - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + 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'); - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); } - } - } - - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); - - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + 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'); } - } - } - - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); + 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'); } } - } -}; - -_$cartesian_477.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); - - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_422.identity); - - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); - - subplotLayers.order(); - - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); - - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; - - // keep ref to plot group - plotinfo.plotgroup = _$d3_79.select(this); + else if(mode === 'lasso') { + filterPoly.addPt([x1, y1]); + currentPolygon = filterPoly.filtered; + } - // initialize list of overlay subplots - plotinfo.overlays = []; + // create outline & tester + if(dragOptions.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + _$throttle_447.throttle( + throttleID, + _$constants_472.SELECTDELAY, + function() { + selection = []; -_$cartesian_477.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_510.style(gd); -}; + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + traceSelections.push(traceSelection); - var subplotData = [], - overlays = []; + thisSelection = fillSelectionItem(traceSelection, searchInfo); - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + if(selection.length) { + for(var j = 0; j < thisSelection.length; j++) { + selection.push(thisSelection[j]); + } + } + else selection = thisSelection; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + eventData = {points: selection}; + updateSelectedState(gd, searchTraces, eventData); + fillRangeItems(eventData, currentPolygon, filterPoly); + dragOptions.gd.emit('plotly_selecting', eventData); + } + ); + }; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); - } - else { - subplotData.push(subplot); - } - } + dragOptions.clickFn = function(numClicks, evt) { + corners.remove(); - // main subplots before overlays - subplotData = subplotData.concat(overlays); + _$throttle_447.done(throttleID).then(function() { + _$throttle_447.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); + } - return subplotData; -} + updateSelectedState(gd, searchTraces); + gd.emit('plotly_deselect', null); + } + else { + // 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. + gd.emit('plotly_selected', undefined); + } -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_471.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_471.layerValue2layerClass[plotinfo.yaxis.layer]; + _$fx_341.click(gd, evt); + }); + }; - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); + dragOptions.doneFn = function() { + corners.remove(); - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); + _$throttle_447.done(throttleID).then(function() { + _$throttle_447.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + if(eventData) { + var pts = eventData.points || []; - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.selectedpoints = []; + } - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + for(i = 0; i < pts.length; i++) { + var pt = pts[i]; + var data = pt.data; + var fullData = pt.fullData; - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + if(pt.pointIndices) { + [].push.apply(data.selectedpoints, pt.pointIndices); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + fullData.selectedpoints.push(pt.pointIndex); + } + } } else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); - - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); - - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); - - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + delete trace.selectedpoints; + delete trace._input.selectedpoints; + } } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_469.idSort); + // group searchInfo traces by trace modules + var lookup = {}; - // common attributes for all subplots, overlays or not + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - for(var i = 0; i < _$constants_471.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_471.traceLayerClasses[i]); + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; + } } - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + var keys = Object.keys(lookup).sort(__sortModules_484); - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_519.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } + } + } } -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; - - var overlayIdsToRemove = {}; - - layers.each(function(subplotId) { - var plotgroup = _$d3_79.select(this); +function mergePolygons(list, poly, subtract) { + var res; - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + if(subtract) { + res = _$PolyBool_220.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); - overlayIdsToRemove[subplotId] = true; + return res.regions; + } - // do not remove individual axis s here - // as other subplots may need them + res = _$PolyBool_220.union({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false }); - // must remove overlaid subplot trace layers 'manually' - - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); - - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + return res.regions; +} - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; +function fillSelectionItem(selection, searchInfo) { + if(Array.isArray(selection)) { + var cd = searchInfo.cd; + var trace = searchInfo.cd[0].trace; - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); - } + for(var i = 0; i < selection.length; i++) { + selection[i] = makeEventData(selection[i], trace, cd); } } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); + return selection; } -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); - - layer.enter().append(nodeType) - .classed(className, true); - - return layer; +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); } -_$cartesian_477.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_79.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); - - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); - - image.attr({ - xmlns: _$xmlns_namespaces_405.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); - } - - canvases.each(canvasToImage); +var _$select_484 = { + prepSelect: prepSelect, + clearSelect: clearSelect }; /** @@ -41492,681 +42318,1156 @@ _$cartesian_477.toSVG = function(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; /* removed: var _$d3_79 = require('d3'); */; +/* removed: var _$tinycolor_264 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_174 = require('has-passive-events'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$plots_510 = require('../../plots/plots'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_410 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_299 = require('../../components/color'); */; +/* removed: var _$drawing_324 = require('../../components/drawing'); */; +/* removed: var _$fx_341 = require('../../components/fx'); */; +/* removed: var _$setCursor_442 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_321 = require('../../components/dragelement'); */; +var __FROM_TL_475 = _$alignment_399.FROM_TL; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$drawing_324 = require('../drawing'); */; -/* removed: var _$color_299 = require('../color'); */; -/* removed: var _$titles_392 = require('../titles'); */; +/* removed: var _$plots_510 = require('../plots'); */; -/* removed: var _$cartesian_477 = require('../../plots/cartesian'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +var doTicks = _$axes_467.doTicks; +var __getFromId_475 = _$axis_ids_470.getFromId; +var __prepSelect_475 = _$select_484.prepSelect; +var __clearSelect_475 = _$select_484.clearSelect; +/* removed: var _$scaleZoom_483 = require('./scale_zoom'); */; -/* removed: var _$dragelement_321 = require('../dragelement'); */; -/* removed: var _$setCursor_441 = require('../../lib/setcursor'); */; +/* removed: var _$constants_472 = require('./constants'); */; +var MINDRAG = _$constants_472.MINDRAG; +var MINZOOM = _$constants_472.MINZOOM; -/* removed: var _$constants_374 = require('./constants'); */; -var _$draw_376 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; - function keyFunction(axisOpts) { - return axisOpts._name; - } + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_374.containerClassName) - .data(rangeSliderData, keyFunction); + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; - rangeSliders.enter().append('g') - .classed(_$constants_374.containerClassName, true) - .attr('pointer-events', 'all'); + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_79.select(this), - opts = axisOpts[_$constants_374.name]; + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; + } - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; + recomputeAxisLists(); - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_79.select(this), - opts = axisOpts[_$constants_374.name], - oppAxisOpts = fullLayout[_$axes_466.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_466.id2name(axisOpts.anchor)]; + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; + } - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; - axisOpts.cleanRange('rangeslider.range'); + recomputeAxisLists(); + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } - // update range slider dimensions + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_475(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_475(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; - var oppBottom = Infinity; - var subplotData = _$axes_466.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_466.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); - } + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; - opts._id = _$constants_374.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_475(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); + if(numClicks === 2 && !singleEnd) doubleClick(); - var x = Math.round(margin.l + (graphSize.w * domain[0])); + if(isMainDrag) { + _$fx_341.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_374.extraPad - ); + if(ax.fixedrange) return; - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; - // update data <--> pixel coordinate conversion methods + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_79.select(dragger) + .call(_$svg_text_utils_446.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_519.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; + _$dragelement_321.init(dragOptions); - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; - }; + // collected changes to be made to the plot by relayout at the end + var updates = {}; - opts._rl = [range0, range1]; + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_264(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; - } + corners = makeCorners(zoomlayer, xs, ys); - // update inner nodes + __clearSelect_475(zoomlayer); + } - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_392.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' - } - }); + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); } - // update margins - _$plots_510.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_374.extraPad + opts._offsetShift * 2 - }); - }); -}; + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; -function makeRangeSliderData(fullLayout) { - var axes = _$axes_466.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_374.name, - out = []; + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; + } - if(fullLayout._has('gl2d')) return out; + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } - if(ax[name] && ax[name].visible) out.push(ax); + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); } - return out; -} - -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_374.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_374.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_374.grabAreaMaxClassName).node(); + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_472.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - rangeSlider.on('mousedown', function() { - var event = _$d3_79.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } - var dragCover = _$dragelement_321.coverSlip(); + if(redrawTimer === null) { + __clearSelect_475(zoomlayer); + } - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; + var pc = gd.querySelector('.plotly'); - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; + recomputeAxisLists(); - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; + clearTimeout(redrawTimer); - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_423.log('Did not find wheel motion attributes: ', e); + return; + } - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; - _$setCursor_441(_$d3_79.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); + var axRange = _$lib_423.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); } - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_422.removeElement(dragCover); + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; + + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } + + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); } - }); -} + if(editY) { + if(!ns) yfrac = 0.5; -function setDataRange(rangeSlider, gd, axisOpts, opts) { + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } - function clamp(v) { - return axisOpts.l2r(_$lib_422.constrain(v, opts._rl[0], opts._rl[1])); - } + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); - window.requestAnimationFrame(function() { - _$registry_518.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_374.handleWidth / 2; + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); - function clamp(v) { - return _$lib_422.constrain(v, 0, opts._width); - } + dragTail(zoomMode); + }, REDRAWDELAY); - function clampOppAxis(v) { - return _$lib_422.constrain(v, 0, opts._height); + e.preventDefault(); + return; } - function clampHandle(v) { - return _$lib_422.constrain(v, -hw2, opts._width + hw2); + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); } - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - rangeSlider.select('rect.' + _$constants_374.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - rangeSlider.select('rect.' + _$constants_374.maskMinClassName) - .attr('width', pixelMin); + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); - rangeSlider.select('rect.' + _$constants_374.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - rangeSlider.select('rect.' + _$constants_374.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - rangeSlider.select('rect.' + _$constants_374.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - rangeSlider.select('rect.' + _$constants_374.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); - } + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_483(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_483(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } - rangeSlider.select('g.' + _$constants_374.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; - rangeSlider.select('g.' + _$constants_374.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_374.bgClassName) - .data([0]); + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } - bg.enter().append('rect') - .classed(_$constants_374.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_475(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - var offsetShift = -opts._offsetShift; - var lw = _$drawing_324.crispRound(gd, opts.borderwidth); + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } + } - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} + // annotations and shapes 'draw' method is slow, + // use the finer-grained 'drawOne' method instead -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; + redrawObjs(gd._fullLayout.annotations || [], _$registry_519.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_519.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_519.getComponentMethod('images', 'draw'), true); + } - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); + function doubleClick() { + if(gd._transitioningWithDuration) return; - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); -} + var ax, i, rangeInitial; -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_466.getSubplots(gd, axisOpts), - calcData = gd.calcdata; + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { - var rangePlots = rangeSlider.selectAll('g.' + _$constants_374.rangePlotClassName) - .data(subplotData, _$lib_422.identity); + doubleClickConfig = 'autosize'; - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_374.rangePlotClassName + ' ' + id; }) - .call(_$drawing_324.setClipUrl, opts._clipId); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } - rangePlots.order(); + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); - rangePlots.exit().remove(); + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } - var mainplotinfo; + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - rangePlots.each(function(id, i) { - var plotgroup = _$d3_79.select(this), - isMainPlot = (i === 0); + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } - var oppAxisOpts = _$axes_466.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; + gd.emit('plotly_doubleclick', null); + _$registry_519.call('relayout', gd, attrs); + } - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_423.syncOrAsync([ + _$plots_510.previousPromises, + function() { _$registry_519.call('relayout', gd, updates); } + ], gd); + } - _$plots_510.supplyDefaults(mockFigure); + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya - }; + var i, sp, xa, ya; - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_410(gd); } - _$cartesian_477.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); -} + if(hasSplom) { + _$registry_519.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; + } -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_423.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_423.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; + + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; + + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } + + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } + + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } + + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_324.setTranslate, clipDx, clipDy) + .call(_$drawing_324.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_324.setTranslate, plotDx, plotDy) + .call(_$drawing_324.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_324.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_324.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_324.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_324.hideOutsideRangePoints, sp, '.bartext'); + } + } } } - return out; + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; + + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } + + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_483(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } + + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * __FROM_TL_475[ax.constraintoward || 'middle']; + } + + return dragger; } -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_374.maskMinClassName) - .data([0]); +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_423.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); + }); - maskMin.enter().append('rect') - .classed(_$constants_374.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + dragger3.call(_$setCursor_442, cursor); - maskMin - .attr('height', opts._height) - .call(_$color_299.fill, _$constants_374.maskColor); + return dragger3.node(); +} - var maskMax = rangeSlider.selectAll('rect.' + _$constants_374.maskMaxClassName) - .data([0]); +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_79.select(dragger).call(_$drawing_324.setRect, x, y, w, h); + return dragger; +} - maskMax.enter().append('rect') - .classed(_$constants_374.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} - maskMax - .attr('height', opts._height) - .call(_$color_299.fill, _$constants_374.maskColor); +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_374.maskMinOppAxisClassName) - .data([0]); + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_79.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_79.format('.' + String(dig) + 'g')(initialVal); + } +} + +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; - maskMinOppAxis.enter().append('rect') - .classed(_$constants_374.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_299.fill, _$constants_374.maskOppAxisColor); + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_374.maskMaxOppAxisClassName) - .data([0]); + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_374.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_374.maskOppBorder) - .call(_$color_299.fill, _$constants_374.maskOppAxisColor); +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } } } -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} - var slideBox = rangeSlider.selectAll('rect.' + _$constants_374.slideBoxClassName) - .data([0]); +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} - slideBox.enter().append('rect') - .classed(_$constants_374.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_374.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} - slideBox.attr({ - height: opts._height, - fill: _$constants_374.slideBoxFill - }); +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_299.background, + stroke: _$color_299.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); } -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} - // +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); + } +} - var grabberMin = rangeSlider.selectAll('g.' + _$constants_374.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_374.grabberMinClassName, true); +function removeZoombox(gd) { + _$d3_79.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} - var grabberMax = rangeSlider.selectAll('g.' + _$constants_374.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_374.grabberMaxClassName, true); +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_423.notifier(_$lib_423._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} - // +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} - var handleFixAttrs = { - x: 0, - width: _$constants_374.handleWidth, - rx: _$constants_374.handleRadius, - fill: _$color_299.background, - stroke: _$color_299.defaultLine, - 'stroke-width': _$constants_374.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} - var handleMin = grabberMin.selectAll('rect.' + _$constants_374.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_374.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - var handleMax = grabberMax.selectAll('rect.' + _$constants_374.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_374.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; - // + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } - if(gd._context.staticPlot) return; + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } + } + } - var grabAreaFixAttrs = { - width: _$constants_374.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_374.grabAreaFill, - cursor: _$constants_374.grabAreaCursor - }; + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } + } + } - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_374.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_374.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_423.extendFlat(xLinks, yLinks); + yLinks = {}; + } - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_374.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_374.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); -} + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_475(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; + } -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_475(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; + } - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} - if(k.indexOf(_$constants_374.name) !== -1) { - _$plots_510.autoMargin(gd, k); +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_174) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; + } + else { + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; + + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); } } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; +} -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$attributes_372 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_378 = require('./oppaxis_attributes'); */; +var _$dragbox_475 = { + makeDragBox: makeDragBox, -var _$rangeslider_377 = { - moduleType: 'component', - name: 'rangeslider', + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_422.extendFlat({}, _$attributes_372, { - yaxis: _$oppaxis_attributes_378 - }) - } - } - }, + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, - layoutAttributes: _$attributes_372, - handleDefaults: _$handleDefaults_375, - calcAutorange: _$calcAutorange_373, - draw: _$draw_376 + attachWheelEventHandler: attachWheelEventHandler }; +var _$graph_interact_476 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -42175,170 +43476,164 @@ var _$rangeslider_377 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; -/* removed: var _$attributes_284 = require('../annotations/attributes'); */; -var scatterLineAttrs = _$attributes_536.line; -var __dash_379 = _$attributes_323.dash; -var __extendFlat_379 = _$extend_414.extendFlat; +'use strict'; -var _$attributes_379 = { - _isLinkedToArray: 'shape', +/* removed: var _$d3_79 = require('d3'); */; - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, +/* removed: var _$fx_341 = require('../../components/fx'); */; +/* removed: var _$dragelement_321 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_442 = require('../../lib/setcursor'); */; - type: { - valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], - - editType: 'calcIfAutorange+arraydraw', - - }, +var __makeDragBox_476 = _$dragbox_475.makeDragBox; +var DRAGGERSIZE = _$constants_472.DRAGGERSIZE; - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, +_$graph_interact_476.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; - xref: __extendFlat_379({}, _$attributes_284.xref, { - - }), - x0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - x1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_79.select(gd).selectAll('.drag').remove(); + return; + } - yref: __extendFlat_379({}, _$attributes_284.yref, { - - }), - y0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - y1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - path: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, + 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'), + 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; + }); - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - line: { - color: __extendFlat_379({}, scatterLineAttrs.color, {editType: 'arraydraw'}), - width: __extendFlat_379({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_379({}, __dash_379, {editType: 'arraydraw'}), - - editType: 'calcIfAutorange+arraydraw' - }, - fillcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // 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_476(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) { + _$fx_341.hover(gd, evt, subplot); + } + }; -'use strict'; + _$fx_341.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; + }; -var _$constants_381 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, + /* + * 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; - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, + // 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; - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} - }, + _$dragelement_321.unhover(gd, evt); + }; - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 - } + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_476(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_476(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_476(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_476(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_476(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_476(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_476(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_476(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_476(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_476(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_341.hover(gd, evt, fullLayout._hoversubplot); + }; + + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_341.click(gd, evt); + }; + + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; + + _$graph_interact_476.updateFx(fullLayout); +}; + +// 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. +_$graph_interact_476.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_442(fullLayout._draggers, cursor); }; -var _$helpers_384 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -42347,76 +43642,89 @@ var _$helpers_384 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; -_$helpers_384.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } -_$helpers_384.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } + } -_$helpers_384.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; + return Object.keys(lookup); +} -_$helpers_384.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_471 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; -_$helpers_384.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); - if(axis) { - var d2r = _$helpers_384.shapePositionToRange(axis); + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; + var order = coerce('categoryorder', orderDefault); + var array; - if(axis.type === 'date') dataToPixel = _$helpers_384.decodeDate(dataToPixel); - } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; - } - else { - dataToPixel = function(v) { return gs.l + gs.w * v; }; + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); } - return dataToPixel; -}; - -_$helpers_384.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; - - if(axis) { - var r2d = _$helpers_384.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; - } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; - } - else { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; } - return pixelToData; + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } + } }; /** @@ -42427,73 +43735,61 @@ _$helpers_384.getPixelToData = function(gd, axis, isVertical) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$constants_381 = require('./constants'); */; -/* removed: var _$helpers_384 = require('./helpers'); */; - - -var _$calcAutorange_380 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_422.filterVisible(fullLayout.shapes); - - if(!shapeList.length || !gd._fullData.length) return; - - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; +var colorMix = _$tinycolor_264.mix; +var lightFraction = _$attributes_298.lightFraction; +/* removed: var _$lib_423 = require('../../lib'); */; - var ax, bounds; +/** + * @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 + */ +var _$handleLineGridDefaults_481 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; - if(shape.xref !== 'paper') { - ax = _$axes_466.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_381.paramIsX); - if(bounds) _$axes_466.expand(ax, bounds, {ppad: ppad}); - } + var dfltColor = opts.dfltColor; - if(shape.yref !== 'paper') { - ax = _$axes_466.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_381.paramIsY); - if(bounds) _$axes_466.expand(ax, bounds, {ppad: ppad}); - } + function coerce2(attr, dflt) { + return _$lib_423.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } -}; - -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; + var lineColor = coerce2('linecolor', dfltColor); + var lineWidth = coerce2('linewidth'); + var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_381.segmentRE), - i, - segment, - drawnParam, - params, - val; + if(!showLine) { + delete containerOut.linecolor; + delete containerOut.linewidth; + } - if(ax.type === 'date') convertVal = _$helpers_384.decodeDate(convertVal); + 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); - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; + if(!showGridLines) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; + } - params = segments[i].substr(1).match(_$constants_381.paramRE); - if(!params || params.length < drawnParam) continue; + if(!opts.noZeroLine) { + var zeroLineColor = coerce2('zerolinecolor', dfltColor); + var zeroLineWidth = coerce2('zerolinewidth'); + var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; + if(!showZeroLine) { + delete containerOut.zerolinecolor; + delete containerOut.zerolinewidth; + } } - if(max >= min) return [min, max]; -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -42503,94 +43799,95 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -/* removed: var _$attributes_379 = require('./attributes'); */; -/* removed: var _$helpers_384 = require('./helpers'); */; +/* removed: var _$layout_attributes_479 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_488 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_487 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_486 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_471 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_481 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_485 = require('./set_convert'); */; + +/** + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors + */ +var _$handleAxisDefaults_469 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; + var visible = coerce('visible', !options.cheateronly); -var _$handleShapeDefaults_386 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + var axType = containerOut.type; - function coerce(attr, dflt) { - return _$lib_422.coerce(shapeIn, shapeOut, _$attributes_379, attr, dflt); + if(axType === 'date') { + var handleCalendarDefaults = _$registry_519.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + _$setConvert_485(containerOut, layoutOut); - if(!visible) return shapeOut; + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + if(autoRange) coerce('rangemode'); - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + coerce('range'); + containerOut.cleanRange(); - // xref, yref - var axRef = _$axes_466.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + _$handleCategoryOrderDefaults_471(containerIn, containerOut, coerce, options); - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); - if(axRef !== 'paper') { - ax = _$axes_466.getFromId(gdMock, axRef); - r2pos = _$helpers_384.rangeToShapePosition(ax); - pos2r = _$helpers_384.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_422.identity; - } + if(!visible) return containerOut; - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; - // x0, x1 (and y0, y1) - _$axes_466.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_466.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + coerce('title', dfltTitle); + _$lib_423.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; - } - } + _$handleTickValueDefaults_488(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_486(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_487(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_481(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_479 + }); - if(shapeType === 'path') { - coerce('path'); - } - else { - _$lib_422.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); - } + if(containerOut.showline || containerOut.ticks) coerce('mirror'); - return shapeOut; + if(options.automargin) coerce('automargin'); + + return containerOut; }; /** @@ -42604,391 +43901,373 @@ var _$handleShapeDefaults_386 = function handleShapeDefaults(shapeIn, shapeOut, 'use strict'; -/* removed: var _$handleArrayContainerDefaults_462 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_386 = require('./shape_defaults'); */; - - -var _$supplyLayoutDefaults_382 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_386 - }; - - _$handleArrayContainerDefaults_462(layoutIn, layoutOut, opts); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +/* removed: var _$lib_423 = require('../../lib'); */; +var id2name = _$axis_ids_470.id2name; -'use strict'; +var _$handleConstraintDefaults_473 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_299 = require('../color'); */; -/* removed: var _$drawing_324 = require('../drawing'); */; + if(containerOut.fixedrange) return; -/* removed: var _$dragelement_321 = require('../dragelement'); */; -/* removed: var _$setCursor_441 = require('../../lib/setcursor'); */; + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_423.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' + } + }, 'constraintoward'); -/* removed: var _$constants_381 = require('./constants'); */; -/* removed: var _$helpers_384 = require('./helpers'); */; + if(!containerIn.scaleanchor) return; + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one + var scaleanchor = _$lib_423.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes + } + }, 'scaleanchor'); -var _$draw_383 = { - draw: __draw_383, - drawOne: __drawOne_383 + 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, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_423.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.'); + } }; -function __draw_383(gd) { - var fullLayout = gd._fullLayout; +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + var thisType = layoutOut[id2name(thisID)].type; - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_383(gd, i); + 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 && !axj.fixedrange) linkableAxes.push(idj); + } + + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; + + var linkableAxesNoLoops = []; + for(j = 0; j < linkableAxes.length; j++) { + idj = linkableAxes[j]; + if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); + } + return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; } } - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); + return {linkableAxes: linkableAxes, thisGroup: null}; } -function __drawOne_383(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); - - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; - // this shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; +/* + * 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(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); + if(thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); } else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } + thisGroupIndex = constraintGroups.indexOf(thisGroup); } - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; - - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_299.stroke, lineColor) - .call(_$color_299.fill, options.fillcolor) - .call(_$drawing_324.dashLine, options.line.dash, options.line.width); - - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); + var thisGroupKeys = Object.keys(thisGroup); - path.call(_$drawing_324.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); + // 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; + } + } - if(gd._context.edits.shapePosition) __setupDragElement_383(gd, path, options, index); + // 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; } -function __setupDragElement_383(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; - var xa, ya, x2p, y2p, p2x, p2y; +'use strict'; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag - }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; +/* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; - _$dragelement_321.init(dragOptions); +/* removed: var _$lib_423 = require('../../lib'); */; - shapePath.node().onmousemove = updateDragMode; - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_321.getCursor(x / w, 1 - y / h) : - 'move'; +var _$handlePositionDefaults_482 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; - _$setCursor_441(shapePath, cursor); + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; + } } - function startDrag(evt) { - // setup conversion functions - xa = _$axes_466.getFromId(gd, shapeOptions.xref); - ya = _$axes_466.getFromId(gd, shapeOptions.yref); - - x2p = _$helpers_384.getDataToPixel(gd, xa); - y2p = _$helpers_384.getDataToPixel(gd, ya, true); - p2x = _$helpers_384.getPixelToData(gd, xa); - p2y = _$helpers_384.getPixelToData(gd, ya, true); + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_89(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; + var anchor = _$lib_423.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + }, 'anchor'); - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } + if(anchor === 'free') coerce('position', dfltPosition); - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; - } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + _$lib_423.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide } + }, 'side'); - update = {}; - - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_423.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); } - function endDrag() { - _$setCursor_441(shapePath); - _$registry_518.call('relayout', gd, update); + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_423.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_384.encodeDate(moveX); + coerce('layer'); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_384.encodeDate(moveY); + return containerOut; +}; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - shapePath.attr('d', getPathString(gd, shapeOptions)); - } - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_384.encodeDate(moveX); +'use strict'; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_384.encodeDate(moveY); +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$autoType_468 = require('./axis_autotype'); */; +var name2id = _$axis_ids_470.name2id; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_490 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); + } - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); - } + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; } - - shapePath.attr('d', getPathString(gd, shapeOptions)); } -} - -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_466.getFromId(gd, options.xref), - ya = _$axes_466.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; +}; - if(xa) { - x2r = _$helpers_384.shapePositionToRange(xa); - x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; - } - else { - x2p = function(v) { return gs.l + gs.w * v; }; - } +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - if(ya) { - y2r = _$helpers_384.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + var id = ax._id; + var axLetter = id.charAt(0); - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_384.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_384.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); - } + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), - y1 = y2p(options.y1); + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; -} + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_381.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_381.paramIsX[segmentType], - yParams = _$constants_381.paramIsY[segmentType], - nParams = _$constants_381.numParams[segmentType]; + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - var paramString = segment.substr(1).replace(_$constants_381.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_519.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; - if(paramNumber > nParams) param = 'X'; - return param; - }); + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_422.log('Ignoring extra params in segment ' + segment); + if(trace[calAttr] !== calendar) calendar = undefined; } - return segmentType + paramString; - }); + ax.type = _$autoType_468(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_468(dim.values, calendar); + break; + } + } + } + else { + ax.type = _$autoType_468(d0[axLetter] || [d0[axLetter + '0']], calendar); + } } -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_381.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_381.paramIsX[segmentType], - yParams = _$constants_381.paramIsY[segmentType], - nParams = _$constants_381.numParams[segmentType]; +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; - var paramString = segment.substr(1).replace(_$constants_381.paramRE, function(param) { - if(paramNumber >= nParams) return param; + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } + } + } +} - paramNumber++; +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} - return param; - }); +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_519.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_519.traceIs(trace._fullInput || {}, 'candlestick'); - return segmentType + paramString; - }); + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); } /** @@ -43002,397 +44281,227 @@ function movePath(pathIn, moveX, moveY) { 'use strict'; -/* removed: var _$draw_383 = require('./draw'); */; - -var _$shapes_385 = { - moduleType: 'component', - name: 'shapes', +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$color_299 = require('../../components/color'); */; +/* removed: var _$layout_attributes_508 = require('../layout_attributes'); */; - layoutAttributes: _$attributes_379, - supplyLayoutDefaults: _$supplyLayoutDefaults_382, - includeBasePlot: _$makeIncludeComponents_476('shapes'), +/* removed: var _$layout_attributes_479 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_490 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_469 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_473 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_482 = require('./position_defaults'); */; +/* removed: var _$axis_ids_470 = require('./axis_ids'); */; - calcAutorange: _$calcAutorange_380, - draw: _$draw_383.draw, - drawOne: _$draw_383.drawOne -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$supplyLayoutDefaults_480 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -'use strict'; + if(!_$registry_519.traceIs(trace, 'cartesian') && !_$registry_519.traceIs(trace, 'gl2d')) { + continue; + } + var xaName = _$axis_ids_470.id2name(trace.xaxis); + var yaName = _$axis_ids_470.id2name(trace.yaxis); -var _$constants_388 = { + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_519.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - // layout attribute name - name: 'sliders', + // 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) xaCheater[xaName] = 1; + } - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', + // check for default formatting tweaks + if(_$registry_519.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } - railHeight: 5, + if(_$registry_519.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; + } + } - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_423.simpleMap(xIds, _$axis_ids_470.id2name); + var yNames = _$lib_423.simpleMap(yIds, _$axis_ids_470.id2name); + var axNames = xNames.concat(yNames); - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', + // plot_bgcolor only makes sense if there's a (2D) plot! + // TODO: bgcolor for each subplot, to inherit from the main one + var plot_bgcolor = _$color_299.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_423.coerce(layoutIn, layoutOut, _$layout_attributes_508, 'plot_bgcolor'); + } - // min item width / height - minWidth: 30, - minHeight: 30, + var bgColor = _$color_299.combine(plot_bgcolor, layoutOut.paper_bgcolor); - // padding around item text - textPadX: 40, + var axName, axLetter, axLayoutIn, axLayoutOut; - // arrow offset off right edge - arrowOffsetX: 4, + function coerce(attr, dflt) { + return _$lib_423.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_479, attr, dflt); + } - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', + function coerce2(attr, dflt) { + return _$lib_423.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_479, attr, dflt); + } - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; - labelPadding: 8, - labelOffset: 0, + for(var j = 0; j < list.length; j++) { + var axName2 = list[j]; - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, + if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { + out.push(_$axis_ids_470.name2id(axName2)); + } + } - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, + return out; + } - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; + // first pass creates the containers, determines types, and handles most of the settings + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!_$lib_423.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } -'use strict'; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_509 = { - t: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - r: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - b: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - l: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; + _$handleTypeDefaults_490(axLayoutIn, axLayoutOut, coerce, fullData, axName); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); -'use strict'; + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; -/* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_509 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_387 = _$extend_414.extendDeepAll; -var __overrideAll_387 = _$edit_types_451.overrideAll; -/* removed: var _$animation_attributes_461 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_388 = require('./constants'); */; + _$handleAxisDefaults_469(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); -var stepsAttrs = { - _isLinkedToArray: 'step', + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], - - }, - label: { - valType: 'string', - - - }, - value: { - valType: 'string', - - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; + if(!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; + } -var _$attributes_387 = __overrideAll_387({ - _isLinkedToArray: 'slider', + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; - visible: { - valType: 'boolean', - - dflt: true, - - }, + _$handlePositionDefaults_482(axLayoutIn, axLayoutOut, coerce, positioningOptions); - active: { - valType: 'number', - - min: 0, - dflt: 0, - - }, + axLayoutOut._input = axLayoutIn; + } - steps: stepsAttrs, + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_519.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_519.getComponentMethod('rangeselector', 'handleDefaults'); - lenmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], - - dflt: 'fraction', - - }, - len: { - valType: 'number', - min: 0, - dflt: 1, - - - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, - - - }, - pad: __extendDeepAll_387({}, _$pad_attributes_509, { - - }, {t: {dflt: 20}}), - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, - - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_461.transition.easing.values, - - dflt: 'cubic-in-out', - + rangeSliderDefaults(layoutIn, layoutOut, axName); + + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); } - }, - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, + coerce('fixedrange'); + } - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - offset: { - valType: 'number', - dflt: 10, - - - }, + var anchoredAxis = layoutOut[_$axis_ids_470.id2name(axLayoutOut.anchor)]; - prefix: { - valType: 'string', - - - }, + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - suffix: { - valType: 'string', - - - }, + coerce('fixedrange', fixedRangeDflt); + } - font: _$font_attributes_493({ - - }) - }, + // Finally, handle scale constraints. 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). - font: _$font_attributes_493({ - - }), + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); - activebgcolor: { - valType: 'color', - - dflt: _$constants_388.gripBgActiveColor, - - }, - bgcolor: { - valType: 'color', - - dflt: _$constants_388.railBgColor, - - }, - bordercolor: { - valType: 'color', - dflt: _$constants_388.railBorderColor, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: _$constants_388.railBorderWidth, - - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_388.tickLength, - - - }, - tickcolor: { - valType: 'color', - dflt: _$constants_388.tickColor, - - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - - }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_388.minorTickLength, - - + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + + _$handleConstraintDefaults_473(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); } -}, 'arraydraw', 'from-root'); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -43404,997 +44513,1009 @@ var _$attributes_387 = __overrideAll_387({ 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_462 = require('../../plots/array_container_defaults'); */; - -/* removed: var _$attributes_387 = require('./attributes'); */; -/* removed: var _$constants_388 = require('./constants'); */; +/* removed: var _$d3_79 = require('d3'); */; -var __name_389 = _$constants_388.name; -var stepAttrs = _$attributes_387.steps; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$drawing_324 = require('../../components/drawing'); */; +/* removed: var _$axes_467 = require('./axes'); */; +var axisRegex = _$constants_472.attrRegex; +var _$transitionAxes_489 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var axes = []; -var _$slidersDefaults_389 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_389, - handleItemDefaults: sliderDefaults - }; + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - _$handleArrayContainerDefaults_462(layoutIn, layoutOut, opts); -}; + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; -function sliderDefaults(sliderIn, sliderOut, layoutOut) { + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; - function coerce(attr, dflt) { - return _$lib_422.coerce(sliderIn, sliderOut, _$attributes_387, attr, dflt); - } + update.axisName = axisName; + update.length = axis._length; - var steps = stepsDefaults(sliderIn, sliderOut); + axes.push(axisLetter); - var visible = coerce('visible', steps.length > 0); - if(!visible) return; + updates[axisLetter] = update; + } + } - coerce('active'); + return updates; + } - coerce('x'); - coerce('y'); - _$lib_422.noneOrAll(sliderIn, sliderOut, ['x', 'y']); + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - coerce('xanchor'); - coerce('yanchor'); + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - coerce('len'); - coerce('lenmode'); + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; - _$lib_422.coerceFont(coerce, 'font', layoutOut.font); + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); - var currentValueIsVisible = coerce('currentvalue.visible'); + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; + } - if(currentValueIsVisible) { - coerce('currentvalue.xanchor'); - coerce('currentvalue.prefix'); - coerce('currentvalue.suffix'); - coerce('currentvalue.offset'); + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } + } - _$lib_422.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + return affectedSubplots; } - coerce('transition.duration'); - coerce('transition.easing'); + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - coerce('bgcolor'); - coerce('activebgcolor'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('ticklen'); - coerce('tickwidth'); - coerce('tickcolor'); - coerce('minorticklen'); -} + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); -function stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } - var valueIn, valueOut; + redrawObjs(fullLayout.annotations || [], _$registry_519.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_519.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_519.getComponentMethod('images', 'draw'), true); + } - function coerce(attr, dflt) { - return _$lib_422.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; } - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; - coerce('method'); + activeAxIds = [xa._id, ya._id]; - if(!_$lib_422.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; + for(i = 0; i < activeAxIds.length; i++) { + _$axes_467.doTicks(gd, activeAxIds[i], true); } - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - valuesOut.push(valueOut); - } + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } - return valuesOut; -} + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + redrawObjs(fullLayout.annotations || [], _$registry_519.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_519.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_519.getComponentMethod('images', 'draw'), true); + } + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; -'use strict'; + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_324.setTranslate, 0, 0) + .call(_$drawing_324.setScale, 1, 1); -/* removed: var _$d3_79 = require('d3'); */; + subplot.plot + .call(_$drawing_324.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_324.setScale, 1, 1); -/* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$color_299 = require('../color'); */; -/* removed: var _$drawing_324 = require('../drawing'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_351 = require('../legend/anchor_utils'); */; + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); -/* removed: var _$constants_388 = require('./constants'); */; -/* removed: var _$alignment_399 = require('../../constants/alignment'); */; -var __LINE_SPACING_390 = _$alignment_399.LINE_SPACING; -var __FROM_TL_390 = _$alignment_399.FROM_TL; -var __FROM_BR_390 = _$alignment_399.FROM_BR; + // 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_324.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_324.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_324.hideOutsideRangePoints, subplot); + } + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; -var _$draw_390 = function draw(gd) { - var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); + var viewBox = []; - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_388.containerClassName) - .data(sliderData.length > 0 ? [0] : []); + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - sliders.enter().append('g') - .classed(_$constants_388.containerClassName, true) - .style('cursor', 'ew-resize'); + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - sliders.exit().remove(); + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; + } - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_390(gd); + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // Return early if no menus visible: - if(sliderData.length === 0) return; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - var sliderGroups = sliders.selectAll('g.' + _$constants_388.groupClassName) - .data(sliderData, keyFunction); + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; + } - sliderGroups.enter().append('g') - .classed(_$constants_388.groupClassName, true); + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - sliderGroups.exit().each(function(sliderOpts) { - _$d3_79.select(this).remove(); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; + var editX = !!xUpdate; + var editY = !!yUpdate; - _$plots_510.autoMargin(gd, _$constants_388.autoMarginIdRoot + sliderOpts._index); - }); + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); - } + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - var gSlider = _$d3_79.select(this); + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - computeLabelSteps(sliderOpts); + subplot.clipRect + .call(_$drawing_324.setTranslate, clipDx, clipDy) + .call(_$drawing_324.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - _$plots_510.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; + subplot.plot + .call(_$drawing_324.setTranslate, plotDx, plotDy) + .call(_$drawing_324.setScale, xScaleFactor, yScaleFactor) - if(opts.active === data.index) return; - if(opts._dragging) return; + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_324.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - setActive(gd, gSlider, opts, data.index, false, true); - }); + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_324.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + } - drawSlider(gd, _$d3_79.select(this), sliderOpts); - }); -}; + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_388.name], - sliderData = []; + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); - } + axi.range = to.slice(); + } - return sliderData; -} + // Signal that this transition has completed: + onComplete && onComplete(); -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; -} + return _$registry_519.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_324.tester.selectAll('g.' + _$constants_388.labelGroupClass) - .data(sliderOpts.steps); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; - sliderLabels.enter().append('g') - .classed(_$constants_388.labelGroupClass, true); + axi.range = axi._r.slice(); + } - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_79.select(this); + return _$registry_519.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + var t1, t2, raf; + var easeFn = _$d3_79.ease(transitionOpts.easing); - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_324.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); - } + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); }); - sliderLabels.remove(); - - var dims = sliderOpts._dims = {}; + function doFrame() { + t2 = Date.now(); - dims.inputAreaWidth = Math.max( - _$constants_388.railWidth, - _$constants_388.gripHeight - ); + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); + } } - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - - var textableInputLength = dims.inputAreaLength - 2 * _$constants_388.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_388.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; + return Promise.resolve(); +}; - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_324.tester.append('g'); +var _$get_data_495 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_324.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_445.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); +'use strict'; - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; +/* removed: var _$registry_519 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_472.SUBPLOT_PATTERN; - dummyGroup.remove(); - } +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_495.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_519.subplotsRegistry[type]; + if(!basePlotModule) return []; - dims.height = dims.currentValueTotalHeight + _$constants_388.tickOffset + sliderOpts.ticklen + _$constants_388.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + var attr = basePlotModule.attr; + var subplotCalcData = []; - var xanchor = 'left'; - if(_$anchor_utils_351.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_351.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; - var yanchor = 'top'; - if(_$anchor_utils_351.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_351.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); } - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + return subplotCalcData; +}; +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_495.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_519.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; - _$plots_510.autoMargin(gd, _$constants_388.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_390[xanchor], - r: dims.outerLength * __FROM_BR_390[xanchor], - b: dims.height * __FROM_BR_390[yanchor], - t: dims.height * __FROM_TL_390[yanchor] - }); -} + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } } - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); - - var dims = sliderOpts._dims; - - // Position the rectangle: - _$drawing_324.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + return [moduleCalcData, remainingCalcData]; +}; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); +/** + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_495.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_519.subplotsRegistry[type]) return []; -} + var attr = _$registry_519.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; + for(var i = 0; i < data.length; i++) { + trace = data[i]; - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_388.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; - break; - default: - x0 = _$constants_388.currentValueInset; - textAnchor = 'left'; + if(type === 'gl2d' && _$registry_519.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); + } + } + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } } - text.enter().append('text') - .classed(_$constants_388.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); - - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; + return subplotData; +}; - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } +var _$cartesian_478 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; - } - text.call(_$drawing_324.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_445.convertToTspans, sliderOpts._gd); +'use strict'; - var lines = _$svg_text_utils_445.lineCount(text); +/* removed: var _$d3_79 = require('d3'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$plots_510 = require('../plots'); */; +var getModuleCalcData = _$get_data_495.getModuleCalcData; - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_390; +/* removed: var _$axis_ids_470 = require('./axis_ids'); */; +/* removed: var _$constants_472 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_405 = require('../../constants/xmlns_namespaces'); */; - _$svg_text_utils_445.positionText(text, x0, y0); +var ensureSingle = _$lib_423.ensureSingle; - return text; +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_423.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); } -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_388.gripRectClass) - .data([0]); +_$cartesian_478.name = 'cartesian'; - grip.enter().append('rect') - .classed(_$constants_388.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); +_$cartesian_478.attr = ['xaxis', 'yaxis']; - grip.attr({ - width: _$constants_388.gripWidth, - height: _$constants_388.gripHeight, - rx: _$constants_388.gripRadius, - ry: _$constants_388.gripRadius, - }) - .call(_$color_299.stroke, sliderOpts.bordercolor) - .call(_$color_299.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); -} +_$cartesian_478.idRoot = ['x', 'y']; -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); +_$cartesian_478.idRegex = _$constants_472.idRegex; - text.enter().append('text') - .classed(_$constants_388.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); +_$cartesian_478.attrRegex = _$constants_472.attrRegex; - text.call(_$drawing_324.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_445.convertToTspans, sliderOpts._gd); +_$cartesian_478.attributes = _$attributes_465; - return text; -} +_$cartesian_478.layoutAttributes = _$layout_attributes_479; -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_388.labelsClass) - .data([0]); - var dims = sliderOpts._dims; +_$cartesian_478.supplyLayoutDefaults = _$supplyLayoutDefaults_480; - labels.enter().append('g') - .classed(_$constants_388.labelsClass, true); +_$cartesian_478.transitionAxes = _$transitionAxes_489; - var labelItems = labels.selectAll('g.' + _$constants_388.labelGroupClass) - .data(dims.labelSteps); +_$cartesian_478.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - labelItems.enter().append('g') - .classed(_$constants_388.labelGroupClass, true); + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; + } - labelItems.exit().remove(); + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_470.id2name(xi)] || {}).anchor; + if(!_$constants_472.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - labelItems.each(function(d) { - var item = _$d3_79.select(this); + if(!allY[yi]) { + allY[yi] = 1; + _$lib_423.pushUnique(yList, yi); + } + } + } - item.call(drawLabel, d, sliderOpts); + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_470.id2name(yi)] || {}).anchor; + if(!_$constants_472.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - _$drawing_324.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_388.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_390 + - _$constants_388.labelOffset + - dims.currentValueTotalHeight - ); - }); + if(!allX[xi]) { + allX[xi] = 1; + _$lib_423.pushUnique(xList, xi); + } + } + } -} + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_472.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } + } + xi = xi ? _$axis_ids_470.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_470.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); +_$cartesian_478.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); - } -} + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; + for(i = 0; i < calcdata.length; i++) { + traces.push(i); + } + } - var step = sliderOpts.steps[sliderOpts.active]; + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive - }); + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - if(_step.execute) { - _$plots_510.executeAPICommand(gd, _step.method, _step.args); + cdSubplot.push(cd); } - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } } - } -} - -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_79.select(gd); - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); } +}; - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); - - var grip = sliderGroup.select('.' + _$constants_388.gripRectClass); +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; - _$d3_79.event.stopPropagation(); - _$d3_79.event.preventDefault(); - grip.call(_$color_299.fill, sliderOpts.activebgcolor); + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); + } - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_79.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_79.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_299.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + } } -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_388.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; +_$cartesian_478.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; - tick.enter().append('rect') - .classed(_$constants_388.tickRectClass, true); + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; - tick.exit().remove(); + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); + } + } - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' - }); + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_79.select(this); + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_299.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); - _$drawing_324.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_388.tickOffset : _$constants_388.minorTickOffset) + dims.currentValueTotalHeight - ); - }); + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } -} + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } } -} -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_388.gripRectClass); + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - var x = normalizedValueToPosition(sliderOpts, position); + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + } + } + } - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } } +}; - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_388.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); -} +_$cartesian_478.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_388.stepInset + - (dims.inputAreaLength - 2 * _$constants_388.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_423.identity); -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_388.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_388.stepInset - 2 * dims.inputAreaStart))); -} + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_388.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; + subplotLayers.order(); - rect.enter().append('rect') - .classed(_$constants_388.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_388.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_299.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; - _$drawing_324.setTranslate(rect, 0, dims.currentValueTotalHeight); -} + // keep ref to plot group + plotinfo.plotgroup = _$d3_79.select(this); -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_388.railRectClass) - .data([0]); - var dims = sliderOpts._dims; + // initialize list of overlay subplots + plotinfo.overlays = []; - rect.enter().append('rect') - .classed(_$constants_388.railRectClass, true); + makeSubplotLayer(gd, plotinfo); - var computedLength = dims.inputAreaLength - _$constants_388.railInset * 2; + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); + } - rect.attr({ - width: computedLength, - height: _$constants_388.railWidth, - rx: _$constants_388.railRadius, - ry: _$constants_388.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_299.stroke, sliderOpts.bordercolor) - .call(_$color_299.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; - _$drawing_324.setTranslate(rect, - _$constants_388.railInset, - (dims.inputAreaWidth - _$constants_388.railWidth) * 0.5 + dims.currentValueTotalHeight - ); -} +_$cartesian_478.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_510.style(gd); +}; -function __clearPushMargins_390(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; - if(k.indexOf(_$constants_388.autoMarginIdRoot) !== -1) { - _$plots_510.autoMargin(gd, k); + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; } } + + // main subplots before overlays + subplotData = subplotData.concat(overlays); + + return subplotData; } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_472.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_472.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; -'use strict'; + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); -/* removed: var _$constants_388 = require('./constants'); */; + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); -var _$sliders_391 = { - moduleType: 'component', - name: _$constants_388.name, + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - layoutAttributes: _$attributes_387, - supplyLayoutDefaults: _$slidersDefaults_389, + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - draw: _$draw_390 -}; + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); -'use strict'; + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); -/* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_298 = require('../color/attributes'); */; -var __extendFlat_393 = _$extend_414.extendFlat; -var __overrideAll_393 = _$edit_types_451.overrideAll; -/* removed: var _$pad_attributes_509 = require('../../plots/pad_attributes'); */; - -var buttonsAttrs = { - _isLinkedToArray: 'button', - - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} - ], - - }, - label: { - valType: 'string', - - dflt: '', - - }, - execute: { - valType: 'boolean', - - dflt: true, - + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } -}; - -var _$attributes_393 = __overrideAll_393({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - - visible: { - valType: 'boolean', - - - }, - - type: { - valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', - - - }, - - direction: { - valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', - - - }, - - active: { - valType: 'integer', - - min: -1, - dflt: 0, - - }, + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - showactive: { - valType: 'boolean', - - dflt: true, - - }, + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. - buttons: buttonsAttrs, + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - x: { - valType: 'number', - min: -2, - max: 3, - dflt: -0.05, - - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'right', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, - - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - pad: __extendFlat_393({}, _$pad_attributes_509, { - - }), + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - font: _$font_attributes_493({ - - }), + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - bgcolor: { - valType: 'color', - - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_298.borderLine, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'arraydraw', - + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); } -}, 'arraydraw', 'from-root'); - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // common attributes for all subplots, overlays or not -'use strict'; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_470.idSort); + for(var i = 0; i < _$constants_472.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_472.traceLayerClasses[i]); + } + } -var _$constants_394 = { + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - // layout attribute name - name: 'updatemenus', + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - // 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', +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'updatemenu-active-index', + var overlayIdsToRemove = {}; - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'updatemenu-', + layers.each(function(subplotId) { + var plotgroup = _$d3_79.select(this); - // options when 'active: -1' - blankHeaderOpts: { label: ' ' }, + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - // min item width / height - minWidth: 30, - minHeight: 30, + overlayIdsToRemove[subplotId] = true; - // padding around item text - textPadX: 24, - arrowPadX: 16, + // do not remove individual axis s here + // as other subplots may need them + }); - // item rect radii - rx: 2, - ry: 2, + // must remove overlaid subplot trace layers 'manually' - // item text x offset off left edge - textOffsetX: 12, + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); - // item text y offset (w.r.t. middle) - textOffsetY: 3, + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - // arrow offset off right edge - arrowOffsetX: 4, + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; - // gap between header and buttons - gapButtonHeader: 5, + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } + } + } +} - // gap between between buttons - gapButton: 2, +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); +} - // color given to active buttons - activeColor: '#F4FAFF', +_$cartesian_478.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_79.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - // color given to hovered buttons - hoverColor: '#F4FAFF', + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); - // symbol for menu open arrow - arrowSymbol: { - left: '◄', - right: '►', - up: '▲', - down: '▼' + image.attr({ + xmlns: _$xmlns_namespaces_405.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); } + + canvases.each(canvasToImage); }; +_$cartesian_478.updateFx = _$graph_interact_476.updateFx; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44405,1248 +45526,1177 @@ var _$constants_394 = { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_462 = require('../../plots/array_container_defaults'); */; +/* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$attributes_393 = require('./attributes'); */; -/* removed: var _$constants_394 = require('./constants'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$plots_510 = require('../../plots/plots'); */; -var __name_395 = _$constants_394.name; -var __buttonAttrs_395 = _$attributes_393.buttons; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$drawing_324 = require('../drawing'); */; +/* removed: var _$color_299 = require('../color'); */; +/* removed: var _$titles_392 = require('../titles'); */; +/* removed: var _$cartesian_478 = require('../../plots/cartesian'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; -var _$updateMenusDefaults_395 = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_395, - handleItemDefaults: menuDefaults - }; +/* removed: var _$dragelement_321 = require('../dragelement'); */; +/* removed: var _$setCursor_442 = require('../../lib/setcursor'); */; - _$handleArrayContainerDefaults_462(layoutIn, layoutOut, opts); -}; +/* removed: var _$constants_374 = require('./constants'); */; -function menuDefaults(menuIn, menuOut, layoutOut) { +var _$draw_376 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); - function coerce(attr, dflt) { - return _$lib_422.coerce(menuIn, menuOut, _$attributes_393, attr, dflt); + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ + + function keyFunction(axisOpts) { + return axisOpts._name; } - var buttons = __buttonsDefaults_395(menuIn, menuOut); + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_374.containerClassName) + .data(rangeSliderData, keyFunction); - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; + rangeSliders.enter().append('g') + .classed(_$constants_374.containerClassName, true) + .attr('pointer-events', 'all'); - coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_79.select(this), + opts = axisOpts[_$constants_374.name]; - coerce('x'); - coerce('y'); - _$lib_422.noneOrAll(menuIn, menuOut, ['x', 'y']); + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); + }); - coerce('xanchor'); - coerce('yanchor'); + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; - _$lib_422.coerceFont(coerce, 'font', layoutOut.font); + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_79.select(this), + opts = axisOpts[_$constants_374.name], + oppAxisOpts = fullLayout[_$axes_467.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_467.id2name(axisOpts.anchor)]; - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); -} + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; -function __buttonsDefaults_395(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); + } - var buttonIn, buttonOut; + axisOpts.cleanRange('rangeslider.range'); - function coerce(attr, dflt) { - return _$lib_422.coerce(buttonIn, buttonOut, __buttonAttrs_395, attr, dflt); - } - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + // update range slider dimensions - coerce('method'); + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; - if(!_$lib_422.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { - continue; + var oppBottom = Infinity; + var subplotData = _$axes_467.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_467.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - coerce('args'); - coerce('label'); - coerce('execute'); - - buttonOut._index = i; - buttonsOut.push(buttonOut); - } + opts._id = _$constants_374.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; - return buttonsOut; -} + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 x = Math.round(margin.l + (graphSize.w * domain[0])); -'use strict'; + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_374.extraPad + ); -var _$ScrollBox_398 = ScrollBox; + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); -/* removed: var _$d3_79 = require('d3'); */; + // update data <--> pixel coordinate conversion methods -/* removed: var _$color_299 = require('../color'); */; -/* removed: var _$drawing_324 = require('../drawing'); */; + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; -/* removed: var _$lib_422 = require('../../lib'); */; + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection + opts._rl = [range0, range1]; - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; + } - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} + // update inner nodes -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); - // compute position of scrollbox - this.position = position; + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; - - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; - } - - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; - - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } - } - else { - boxT = t; - boxB = boxT + boxH; - - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_392.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); } - } - - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; - - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); - - hbar.exit() - .on('.drag', null) - .remove(); - - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_299.fill, ScrollBox.barColor); - - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH + // update margins + _$plots_510.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_374.extraPad + opts._offsetShift * 2 }); + }); +}; - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } - - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; - - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; +function makeRangeSliderData(fullLayout) { + var axes = _$axes_467.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_374.name, + out = []; - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); + if(fullLayout._has('gl2d')) return out; - vbar.exit() - .on('.drag', null) - .remove(); + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_299.fill, ScrollBox.barColor); + if(ax[name] && ax[name].visible) out.push(ax); + } - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH - }); + return out; +} - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_374.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_374.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_374.grabAreaMaxClassName).node(); - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + rangeSlider.on('mousedown', function() { + var event = _$d3_79.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + var dragCover = _$dragelement_321.coverSlip(); - clipPath.exit().remove(); + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; - this.container.call(_$drawing_324.setClipUrl, clipId); + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } - else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_324.setClipUrl, null); - delete this._clipRect; - } + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_79.behavior.drag() - .on('dragstart', function() { - _$d3_79.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - var onBarDrag = _$d3_79.behavior.drag() - .on('dragstart', function() { - _$d3_79.event.sourceEvent.preventDefault(); - _$d3_79.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); + _$setCursor_442(_$d3_79.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); } - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_423.removeElement(dragCover); } - } - - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + }); +} -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_324.setClipUrl, null); - delete this._clipRect; - } +function setDataRange(rangeSlider, gd, axisOpts, opts) { - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; + function clamp(v) { + return axisOpts.l2r(_$lib_423.constrain(v, opts._rl[0], opts._rl[1])); } - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } -}; + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); -/** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + window.requestAnimationFrame(function() { + _$registry_519.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); +} - if(this.hbar) { - translateX -= _$d3_79.event.dx; - } +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_374.handleWidth / 2; - if(this.vbar) { - translateY -= _$d3_79.event.dy; + function clamp(v) { + return _$lib_423.constrain(v, 0, opts._width); } - this.setTranslate(translateX, translateY); -}; - -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; - - if(this.hbar) { - translateX += _$d3_79.event.deltaY; + function clampOppAxis(v) { + return _$lib_423.constrain(v, 0, opts._height); } - if(this.vbar) { - translateY += _$d3_79.event.deltaY; + function clampHandle(v) { + return _$lib_423.constrain(v, -hw2, opts._width + hw2); } - this.setTranslate(translateX, translateY); -}; + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); -/** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + rangeSlider.select('rect.' + _$constants_374.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_422.constrain(_$d3_79.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); + rangeSlider.select('rect.' + _$constants_374.maskMinClassName) + .attr('width', pixelMin); - var translateXMax = this.position.w - this._box.w; + rangeSlider.select('rect.' + _$constants_374.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - translateX = xf * translateXMax; - } + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_422.constrain(_$d3_79.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); + rangeSlider.select('rect.' + _$constants_374.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - var translateYMax = this.position.h - this._box.h; + rangeSlider.select('rect.' + _$constants_374.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - translateY = yf * translateYMax; + rangeSlider.select('rect.' + _$constants_374.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); } - this.setTranslate(translateX, translateY); -}; - -/** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; - translateX = _$lib_422.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_422.constrain(translateY || 0, 0, translateYMax); + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - this.translateX = translateX; - this.translateY = translateY; + rangeSlider.select('g.' + _$constants_374.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); - this.container.call(_$drawing_324.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); + rangeSlider.select('g.' + _$constants_374.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); +} - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_423.ensureSingle(rangeSlider, 'rect', _$constants_374.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' }); - } + }); - if(this.hbar) { - var xf = translateX / translateXMax; + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - this.hbar.call(_$drawing_324.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); - } + var offsetShift = -opts._offsetShift; + var lw = _$drawing_324.crispRound(gd, opts.borderwidth); - if(this.vbar) { - var yf = translateY / translateYMax; + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw + }); +} - this.vbar.call(_$drawing_324.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); - } -}; +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 clipPath = _$lib_423.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); +} -'use strict'; +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_467.getSubplots(gd, axisOpts), + calcData = gd.calcdata; -/* removed: var _$d3_79 = require('d3'); */; + var rangePlots = rangeSlider.selectAll('g.' + _$constants_374.rangePlotClassName) + .data(subplotData, _$lib_423.identity); -/* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$color_299 = require('../color'); */; -/* removed: var _$drawing_324 = require('../drawing'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_351 = require('../legend/anchor_utils'); */; + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_374.rangePlotClassName + ' ' + id; }) + .call(_$drawing_324.setClipUrl, opts._clipId); -var __LINE_SPACING_396 = _$alignment_399.LINE_SPACING; + rangePlots.order(); -/* removed: var _$constants_394 = require('./constants'); */; -/* removed: var _$ScrollBox_398 = require('./scrollbox'); */; + rangePlots.exit().remove(); -var _$draw_396 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); + var mainplotinfo; - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ - - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_394.containerClassName) - .data(menuData.length > 0 ? [0] : []); - - menus.enter().append('g') - .classed(_$constants_394.containerClassName, true) - .style('cursor', 'pointer'); + rangePlots.each(function(id, i) { + var plotgroup = _$d3_79.select(this), + isMainPlot = (i === 0); - menus.exit().remove(); + var oppAxisOpts = _$axes_467.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; - // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_396(gd); + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; - // return early if no update menus are visible - if(menuData.length === 0) return; + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_394.headerGroupClassName) - .data(menuData, __keyFunction_396); + _$plots_510.supplyDefaults(mockFigure); - headerGroups.enter().append('g') - .classed(_$constants_394.headerGroupClassName, true); + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_394.dropdownButtonGroupClassName) - .data([0]); + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; - gButton.enter().append('g') - .classed(_$constants_394.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + if(isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; + } - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_396(gd, menuOpts); - } + _$cartesian_478.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + }); +} - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_398(gd, gButton, scrollBoxId); +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; - gButton - .call(removeAllButtons) - .attr(_$constants_394.menuIndexAttrName, '-1'); + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } } - headerGroups.exit().each(function(menuOpts) { - _$d3_79.select(this).remove(); - - gButton - .call(removeAllButtons) - .attr(_$constants_394.menuIndexAttrName, '-1'); + return out; +} - _$plots_510.autoMargin(gd, _$constants_394.autoMarginIdRoot + menuOpts._index); +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_423.ensureSingle(rangeSlider, 'rect', _$constants_374.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); }); - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_79.select(this); + maskMin + .attr('height', opts._height) + .call(_$color_299.fill, _$constants_374.maskColor); - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_510.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_396(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + var maskMax = _$lib_423.ensureSingle(rangeSlider, 'rect', _$constants_374.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' }); - - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - - // if this menu is active, update the dropdown container - if(__isActive_396(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); - } - }); -}; - -/** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_394.name]; - var menuData = []; - - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - - if(item.visible) menuData.push(item); - } - - return menuData; -} - -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_396(menuOpts) { - return menuOpts._index; -} - -function isFolded(gButton) { - return +gButton.attr(_$constants_394.menuIndexAttrName) === -1; -} -function __isActive_396(gButton, menuOpts) { - return +gButton.attr(_$constants_394.menuIndexAttrName) === menuOpts._index; -} + maskMax + .attr('height', opts._height) + .call(_$color_299.fill, _$constants_374.maskColor); -function __setActive_396(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_423.ensureSingle(rangeSlider, 'rect', _$constants_374.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_394.menuIndexAttrName, '-1'); + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_299.fill, _$constants_374.maskOppAxisColor); - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + var maskMaxOppAxis = _$lib_423.ensureSingle(rangeSlider, 'rect', _$constants_374.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_374.maskOppBorder) + .call(_$color_299.fill, _$constants_374.maskOppAxisColor); } } -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_394.headerClassName) - .data([0]); - var dims = menuOpts._dims; - - header.enter().append('g') - .classed(_$constants_394.headerClassName, true) - .style('pointer-events', 'all'); - - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_394.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); + var slideBox = _$lib_423.ensureSingle(rangeSlider, 'rect', _$constants_374.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_374.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_394.headerArrowClassName) - .data([0]); + slideBox.attr({ + height: opts._height, + fill: _$constants_374.slideBoxFill + }); +} - arrow.enter().append('text') - .classed(_$constants_394.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_324.font, menuOpts.font) - .text(_$constants_394.arrowSymbol[menuOpts.direction]); +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_423.ensureSingle(rangeSlider, 'g', _$constants_374.grabberMinClassName); + var grabberMax = _$lib_423.ensureSingle(rangeSlider, 'g', _$constants_374.grabberMaxClassName); - arrow.attr({ - x: dims.headerWidth - _$constants_394.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_394.textOffsetY + menuOpts.pad.t + // + var handleFixAttrs = { + x: 0, + width: _$constants_374.handleWidth, + rx: _$constants_374.handleRadius, + fill: _$color_299.background, + stroke: _$color_299.defaultLine, + 'stroke-width': _$constants_374.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_423.ensureSingle(grabberMin, 'rect', _$constants_374.handleMinClassName, function(s) { + s.attr(handleFixAttrs); }); + handleMin.attr(handleDynamicAttrs); - header.on('click', function() { - gButton.call(removeAllButtons); + var handleMax = _$lib_423.ensureSingle(grabberMax, 'rect', _$constants_374.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); + // + if(gd._context.staticPlot) return; - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_394.menuIndexAttrName, - __isActive_396(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); + var grabAreaFixAttrs = { + width: _$constants_374.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_374.grabAreaFill, + cursor: _$constants_374.grabAreaCursor + }; - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + var grabAreaMin = _$lib_423.ensureSingle(grabberMin, 'rect', _$constants_374.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); }); + grabAreaMin.attr('height', opts._height); - header.on('mouseover', function() { - header.call(styleOnMouseOver); + var grabAreaMax = _$lib_423.ensureSingle(grabberMax, 'rect', _$constants_374.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); }); + grabAreaMax.attr('height', opts._height); +} - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); +function clearPushMargins(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); - // translate header group - _$drawing_324.setTranslate(gHeader, dims.lx, dims.ly); -} + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); + if(k.indexOf(_$constants_374.name) !== -1) { + _$plots_510.autoMargin(gd, k); + } } +} - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 klass = menuOpts.type === 'dropdown' ? _$constants_394.dropdownButtonClassName : _$constants_394.buttonClassName; +'use strict'; - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$attributes_372 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_378 = require('./oppaxis_attributes'); */; - var enter = buttons.enter().append('g') - .classed(klass, true); +var _$rangeslider_377 = { + moduleType: 'component', + name: 'rangeslider', - var exit = buttons.exit(); + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_423.extendFlat({}, _$attributes_372, { + yaxis: _$oppaxis_attributes_378 + }) + } + } + }, - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + layoutAttributes: _$attributes_372, + handleDefaults: _$handleDefaults_375, + calcAutorange: _$calcAutorange_373, + draw: _$draw_376 +}; - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; +'use strict'; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +/* removed: var _$attributes_284 = require('../annotations/attributes'); */; +var scatterLineAttrs = _$attributes_537.line; +var __dash_379 = _$attributes_323.dash; +var __extendFlat_379 = _$extend_415.extendFlat; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_394.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_394.gapButtonHeader; - } - } +var _$attributes_379 = { + _isLinkedToArray: 'shape', - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_394.gapButtonHeader + _$constants_394.gapButton - dims.openHeight; - } + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calcIfAutorange+arraydraw', + + }, - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_394.gapButtonHeader + _$constants_394.gapButton - dims.openWidth; - } + type: { + valType: 'enumerated', + values: ['circle', 'rect', 'path', 'line'], + + editType: 'calcIfAutorange+arraydraw', + + }, - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_394.gapButton, - xPad: _$constants_394.gapButton, - index: 0, - }; + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; + xref: __extendFlat_379({}, _$attributes_284.xref, { + + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_79.select(this); + yref: __extendFlat_379({}, _$attributes_284.yref, { + + }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); + path: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, - button.on('click', function() { - // skip `dragend` events - if(_$d3_79.event.defaultPrevented) return; + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + + }, + line: { + color: __extendFlat_379({}, scatterLineAttrs.color, {editType: 'arraydraw'}), + width: __extendFlat_379({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_379({}, __dash_379, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; - __setActive_396(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(buttonOpts.execute) { - _$plots_510.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); - } - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); - }); +'use strict'; - button.on('mouseover', function() { - button.call(styleOnMouseOver); - }); - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); - }); +var _$constants_381 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, - buttons.call(styleButtons, menuOpts); + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, + + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 } +}; - scrollBoxPosition.direction = menuOpts.direction; +var _$helpers_384 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); - } - } -} -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; +'use strict'; - var active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_394.gapButton; - } +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. + +_$helpers_384.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; +}; + +_$helpers_384.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; +}; + +_$helpers_384.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); + }; +}; + +_$helpers_384.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; +}; + +_$helpers_384.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; + + if(axis) { + var d2r = _$helpers_384.shapePositionToRange(axis); + + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; + + if(axis.type === 'date') dataToPixel = _$helpers_384.decodeDate(dataToPixel); + } + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; } else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_394.gapButton; - } + dataToPixel = function(v) { return gs.l + gs.w * v; }; } - scrollBox.enable(position, translateX, translateY); + return dataToPixel; +}; - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } +_$helpers_384.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); + if(axis) { + var r2d = _$helpers_384.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + } + else { + pixelToData = function(p) { return (p - gs.l) / gs.w; }; } -} -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; + return pixelToData; +}; - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); - } -} -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); -} +'use strict'; -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; - rect.enter().append('rect') - .classed(_$constants_394.itemRectClassName, true) - .attr({ - rx: _$constants_394.rx, - ry: _$constants_394.ry, - 'shape-rendering': 'crispEdges' - }); +/* removed: var _$constants_381 = require('./constants'); */; +/* removed: var _$helpers_384 = require('./helpers'); */; - rect.call(_$color_299.stroke, menuOpts.bordercolor) - .call(_$color_299.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); -} -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); +var _$calcAutorange_380 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + shapeList = _$lib_423.filterVisible(fullLayout.shapes); - text.enter().append('text') - .classed(_$constants_394.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + if(!shapeList.length || !gd._fullData.length) return; - text.call(_$drawing_324.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_445.convertToTspans, gd); -} + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; + var ax, bounds; - buttons.each(function(buttonOpts, i) { - var button = _$d3_79.select(this); + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_467.getFromId(gd, shape.xref); - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_394.itemRectClassName) - .call(_$color_299.fill, _$constants_394.activeColor); + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_381.paramIsX); + + if(bounds) _$axes_467.expand(ax, bounds, calcXPaddingOptions(shape)); } - }); -} -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_394.itemRectClassName) - .call(_$color_299.fill, _$constants_394.hoverColor); + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_467.getFromId(gd, shape.yref); + + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_381.paramIsY); + if(bounds) _$axes_467.expand(ax, bounds, calcYPaddingOptions(shape)); + } + } +}; + +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); } -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_394.itemRectClassName) - .call(_$color_299.fill, menuOpts.bgcolor); +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); } -// find item dimensions (this mutates menuOpts) -function __findDimensions_396(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - var fakeButtons = _$drawing_324.tester.selectAll('g.' + _$constants_394.dropdownButtonClassName) - .data(menuOpts.buttons); + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_381.paramIsY : _$constants_381.paramIsX) : + [v0, v1]; + var maxValue = _$lib_423.aggNums(Math.max, null, coords), + minValue = _$lib_423.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - fakeButtons.enter().append('g') - .classed(_$constants_394.dropdownButtonClassName, true); + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_79.select(this); + var segments = path.match(_$constants_381.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - button.call(drawItem, menuOpts, buttonOpts, gd); + var params = segment.substr(1).match(_$constants_381.paramRE); + if(!params || params.length < relevantParamIdx) return; - var text = button.select('.' + _$constants_394.itemTextClassName); + extractedCoordinates.push(params[relevantParamIdx]); + }); - // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_324.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_394.textPadX, _$constants_394.minWidth); + return extractedCoordinates; +} - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_396; - var tLines = _$svg_text_utils_445.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_394.minHeight) + _$constants_394.textOffsetY; +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_381.segmentRE), + i, + segment, + drawnParam, + params, + val; - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); + if(ax.type === 'date') convertVal = _$helpers_384.decodeDate(convertVal); - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_394.gapButton; - dims.openHeight += hEff + _$constants_394.gapButton; - } else { - dims.totalWidth += wEff + _$constants_394.gapButton; - dims.openWidth += wEff + _$constants_394.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; - } - }); + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - if(isVertical) { - dims.totalHeight -= _$constants_394.gapButton; - } else { - dims.totalWidth -= _$constants_394.gapButton; + params = segments[i].substr(1).match(_$constants_381.paramRE); + if(!params || params.length < drawnParam) continue; + + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; } + if(max >= min) return [min, max]; +} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - dims.headerWidth = dims.width1 + _$constants_394.arrowPadX; - dims.headerHeight = dims.height1; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_394.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_394.arrowPadX; - } +'use strict'; - fakeButtons.remove(); +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; +/* removed: var _$attributes_379 = require('./attributes'); */; +/* removed: var _$helpers_384 = require('./helpers'); */; - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - var xanchor = 'left'; - if(_$anchor_utils_351.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = 'right'; - } - if(_$anchor_utils_351.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = 'center'; - } +var _$handleShapeDefaults_386 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; - var yanchor = 'top'; - if(_$anchor_utils_351.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = 'bottom'; - } - if(_$anchor_utils_351.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = 'middle'; + function coerce(attr, dflt) { + return _$lib_423.coerce(shapeIn, shapeOut, _$attributes_379, attr, dflt); } - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - _$plots_510.autoMargin(gd, _$constants_394.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); -} + if(!visible) return shapeOut; -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_394.itemRectClassName); - var text = item.select('.' + _$constants_394.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - _$drawing_324.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight - }); + // xref, yref + var axRef = _$axes_467.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - var tHeight = menuOpts.font.size * __LINE_SPACING_396; - var tLines = _$svg_text_utils_445.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); + if(axRef !== 'paper') { + ax = _$axes_467.getFromId(gdMock, axRef); + r2pos = _$helpers_384.rangeToShapePosition(ax); + pos2r = _$helpers_384.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_423.identity; + } - _$svg_text_utils_445.positionText(text, _$constants_394.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_394.textOffsetY); + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; - } + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); - posOpts.index++; -} + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_467.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_467.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_394.dropdownButtonClassName).remove(); -} + // hack part 2 + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } -function __clearPushMargins_396(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + _$axes_467.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); - if(k.indexOf(_$constants_394.autoMarginIdRoot) !== -1) { - _$plots_510.autoMargin(gd, k); + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; } } -} + + if(shapeType === 'path') { + coerce('path'); + } + else { + _$lib_423.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + } + + return shapeOut; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45656,21 +46706,22 @@ function __clearPushMargins_396(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$constants_394 = require('./constants'); */; +/* removed: var _$handleArrayContainerDefaults_463 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_386 = require('./shape_defaults'); */; -var _$updatemenus_397 = { - moduleType: 'component', - name: _$constants_394.name, - layoutAttributes: _$attributes_393, - supplyLayoutDefaults: _$updateMenusDefaults_395, +var _$supplyLayoutDefaults_382 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_386 + }; - draw: _$draw_396 + _$handleArrayContainerDefaults_463(layoutIn, layoutOut, opts); }; -var _$mathjax_config_407 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45679,239 +46730,459 @@ var _$mathjax_config_407 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* global MathJax:false */ +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_299 = require('../color'); */; +/* removed: var _$drawing_324 = require('../drawing'); */; -/** - * Check and configure MathJax - */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_407.MathJax = true; +/* removed: var _$dragelement_321 = require('../dragelement'); */; +/* removed: var _$setCursor_442 = require('../../lib/setcursor'); */; - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] - } - }); +/* removed: var _$constants_381 = require('./constants'); */; +/* removed: var _$helpers_384 = require('./helpers'); */; - MathJax.Hub.Configured(); -} else { - _$mathjax_config_407.MathJax = false; -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one + +var _$draw_383 = { + draw: __draw_383, + drawOne: __drawOne_383 +}; +function __draw_383(gd) { + var fullLayout = gd._fullLayout; -'use strict'; + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); -/* removed: var _$lib_422 = require('../lib'); */; -/* removed: var _$plot_config_456 = require('../plot_api/plot_config'); */; + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); + } + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_383(gd, i); + } + } -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); +} - for(var i = 0; i < args.length; i++) { - arg = args[i]; +function __drawOne_383(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_422.extendDeep([], arg) : - _$lib_422.extendDeepAll({}, arg); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; + + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; + + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); } - else copy[i] = arg; } - return copy; + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; + + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_299.stroke, lineColor) + .call(_$color_299.fill, options.fillcolor) + .call(_$drawing_324.dashLine, options.line.dash, options.line.width); + + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); + + path.call(_$drawing_324.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null + ); + + if(gd._context.edits.shapePosition) __setupDragElement_383(gd, path, options, index); + } } +function __setupDragElement_383(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; + + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; + var xa, ya, x2p, y2p, p2x, p2y; -var __queue_436 = {}; + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; -// TODO: disable/enable undo and redo buttons appropriately + _$dragelement_321.init(dragOptions); -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_436.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + shapePath.node().onmousemove = updateDragMode; - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + function updateDragMode(evt) { + // element might not be on screen at time of setup, + // so obtain bounding box here + var dragBBox = dragOptions.element.getBoundingClientRect(); - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } + // choose 'move' or 'resize' + // based on initial position of cursor within the drag element + var w = dragBBox.right - dragBBox.left, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_321.getCursor(x / w, 1 - y / h) : + 'move'; - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; + _$setCursor_442(shapePath, cursor); + + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; } - gd.undoQueue.beginSequence = false; - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); + function startDrag(evt) { + // setup conversion functions + xa = _$axes_467.getFromId(gd, shapeOptions.xref); + ya = _$axes_467.getFromId(gd, shapeOptions.yref); + + x2p = _$helpers_384.getDataToPixel(gd, xa); + y2p = _$helpers_384.getDataToPixel(gd, ya, true); + p2x = _$helpers_384.getPixelToData(gd, xa); + p2y = _$helpers_384.getPixelToData(gd, ya, true); + + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; + + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } + + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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); + + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; + } + + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + } + + update = {}; + + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; } - if(gd.undoQueue.queue.length > _$plot_config_456.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; + function endDrag() { + _$setCursor_442(shapePath); + _$registry_519.call('relayout', gd, update); } -}; -/** - * Begin a sequence of undoQueue changes - * - * @param gd - */ -__queue_436.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; -/** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended - * - * @param gd - */ -__queue_436.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; -}; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_384.encodeDate(moveX); + } -/** - * Move one step back in the undo queue, and undo the object there. - * - * @param gd - */ -__queue_436.undo = function undo(gd) { - var queueObj, i; + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_384.encodeDate(moveY); + } - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_384.encodeDate(moveX); + } - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_436.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_384.encodeDate(moveY); + } + + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; +} -/** - * Redo the current object in the undo, then move forward in the queue. - * - * @param gd - */ -__queue_436.redo = function redo(gd) { - var queueObj, i; +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_467.getFromId(gd, options.xref), + ya = _$axes_467.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; + if(xa) { + x2r = _$helpers_384.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; + else { + x2p = function(v) { return gs.l + gs.w * v; }; } - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + if(ya) { + y2r = _$helpers_384.shapePositionToRange(ya); + y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; + } + else { + y2p = function(v) { return gs.t + gs.h * (1 - v); }; + } - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_436.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_384.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_384.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; -}; + 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); + } -/** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. - * - * @param gd - * @param func - * @param args - */ -__queue_436.plotDo = function(gd, func, args) { - gd.autoplay = true; + 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); + } - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; +} - // call the supplied function - func.apply(null, args); -}; -var _$queue_436 = __queue_436; +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; + + + return pathIn.replace(_$constants_381.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_381.paramIsX[segmentType], + yParams = _$constants_381.paramIsY[segmentType], + nParams = _$constants_381.numParams[segmentType]; + + var paramString = segment.substr(1).replace(_$constants_381.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_423.log('Ignoring extra params in segment ' + segment); + } + + return segmentType + paramString; + }); +} + +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_381.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_381.paramIsX[segmentType], + yParams = _$constants_381.paramIsY[segmentType], + nParams = _$constants_381.numParams[segmentType]; + + var paramString = segment.substr(1).replace(_$constants_381.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; + }); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -45921,17 +47192,22 @@ var _$queue_436 = __queue_436; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$localeEnUs_448 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' - }, - format: { - date: '%m/%d/%Y' - } +/* removed: var _$draw_383 = require('./draw'); */; + +var _$shapes_385 = { + moduleType: 'component', + name: 'shapes', + + layoutAttributes: _$attributes_379, + supplyLayoutDefaults: _$supplyLayoutDefaults_382, + includeBasePlot: _$makeIncludeComponents_477('shapes'), + + calcAutorange: _$calcAutorange_380, + draw: _$draw_383.draw, + drawOne: _$draw_383.drawOne }; /** @@ -45942,88 +47218,91 @@ var _$localeEnUs_448 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$localeEn_449 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' - } -}; -var _$fromQuat_116 = fromQuat; +var _$constants_388 = { -/** - * 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, + // layout attribute name + name: 'sliders', - 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; + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; + railHeight: 5, - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + // min item width / height + minWidth: 30, + minHeight: 30, - return out; + // padding around item text + textPadX: 40, + + // arrow offset off right edge + arrowOffsetX: 4, + + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', + + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, + + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, + + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', + + labelPadding: 8, + labelOffset: 0, + + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, + + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, + + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, }; -var _$helpers_452 = {}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46032,1390 +47311,1004 @@ var _$helpers_452 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_116 = require('gl-mat4/fromQuat'); */; - -/* removed: var _$registry_518 = require('../registry'); */; -/* removed: var _$lib_422 = require('../lib'); */; -/* removed: var _$plots_510 = require('../plots/plots'); */; -/* removed: var _$axis_ids_469 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_469.cleanId; -var getFromTrace = _$axis_ids_469.getFromTrace; -/* removed: var _$color_299 = require('../components/color'); */; - +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_509 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; -// clear the promise queue if one of them got rejected -_$helpers_452.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_422.log('Clearing previous rejected promises from queue.'); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - gd._promises = []; -}; +'use strict'; -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_452.cleanLayout = function(layout) { - var i, j; +/* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_509 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_387 = _$extend_415.extendDeepAll; +var __overrideAll_387 = _$edit_types_452.overrideAll; +/* removed: var _$animation_attributes_462 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_388 = require('./constants'); */; - if(!layout) layout = {}; +var stepsAttrs = { + _isLinkedToArray: 'step', - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; - } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } + ], + + }, + label: { + valType: 'string', + + + }, + value: { + valType: 'string', + + + }, + execute: { + valType: 'boolean', + + dflt: true, + } +}; - var axisAttrRegex = (_$plots_510.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_510.subplotsRegistry.gl3d || {}).attrRegex; +var _$attributes_387 = __overrideAll_387({ + _isLinkedToArray: 'slider', - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; + visible: { + valType: 'boolean', + + dflt: true, + + }, - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + active: { + valType: 'number', + + min: 0, + dflt: 0, + + }, - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories + steps: stepsAttrs, - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], + + dflt: 'fraction', + + }, + len: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + pad: __extendDeepAll_387({}, _$pad_attributes_509, { + + }, {t: {dflt: 20}}), + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; - } + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_462.transition.easing.values, + + dflt: 'cubic-in-out', + } + }, - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; - - // clean old Camera coords - var cameraposition = scene.cameraposition; - - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_116([], rotation), - eye = []; + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; + offset: { + valType: 'number', + dflt: 10, + + + }, - delete scene.cameraposition; - } - } - } + prefix: { + valType: 'string', + + + }, - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; + suffix: { + valType: 'string', + + + }, - if(!_$lib_422.isPlainObject(ann)) continue; + font: _$font_attributes_493({ + + }) + }, - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } + font: _$font_attributes_493({ + + }), - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); + activebgcolor: { + valType: 'color', + + dflt: _$constants_388.gripBgActiveColor, + + }, + bgcolor: { + valType: 'color', + + dflt: _$constants_388.railBgColor, + + }, + bordercolor: { + valType: 'color', + dflt: _$constants_388.railBorderColor, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_388.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_388.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_388.tickColor, + + + }, + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_388.minorTickLength, + + } +}, 'arraydraw', 'from-root'); - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!_$lib_422.isPlainObject(shape)) continue; +'use strict'; - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); - } +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_463 = require('../../plots/array_container_defaults'); */; - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } +/* removed: var _$attributes_387 = require('./attributes'); */; +/* removed: var _$constants_388 = require('./constants'); */; - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; - } - } +var __name_389 = _$constants_388.name; +var stepAttrs = _$attributes_387.steps; - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_299.clean(layout); +var _$slidersDefaults_389 = function slidersDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_389, + handleItemDefaults: sliderDefaults + }; - return layout; + _$handleArrayContainerDefaults_463(layoutIn, layoutOut, opts); }; -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); +function sliderDefaults(sliderIn, sliderOut, layoutOut) { + + function coerce(attr, dflt) { + return _$lib_423.coerce(sliderIn, sliderOut, _$attributes_387, attr, dflt); } -} -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_452.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); + var steps = stepsDefaults(sliderIn, sliderOut); - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; + var visible = coerce('visible', steps.length > 0); + if(!visible) return; - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; + coerce('active'); - for(i = 0; i < 100; i++) { - newUid = _$lib_422.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_422.randstr(uids); - uids.push(trace.uid); - } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); + coerce('x'); + coerce('y'); + _$lib_423.noneOrAll(sliderIn, sliderOut, ['x', 'y']); - // BACKWARD COMPATIBILITY FIXES + coerce('xanchor'); + coerce('yanchor'); - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } + coerce('len'); + coerce('lenmode'); - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_299.defaults, - yeColor = trace.error_y.color || - (_$registry_518.traceIs(trace, 'bar') ? _$color_299.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_299.addOpacity( - _$color_299.rgb(yeColor), - _$color_299.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_518.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_452.swapXYData(trace); - } - delete trace.bardir; - } + _$lib_423.coerceFont(coerce, 'font', layoutOut.font); - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_452.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; - } + var currentValueIsVisible = coerce('currentvalue.visible'); - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } + if(currentValueIsVisible) { + coerce('currentvalue.xanchor'); + coerce('currentvalue.prefix'); + coerce('currentvalue.suffix'); + coerce('currentvalue.offset'); - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + _$lib_423.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + } - // scene ids scene1 -> scene - if(_$registry_518.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_510.subplotsRegistry.gl3d.cleanId(trace.scene); - } + coerce('transition.duration'); + coerce('transition.easing'); - if(!_$registry_518.traceIs(trace, 'pie') && !_$registry_518.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } + coerce('bgcolor'); + coerce('activebgcolor'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('ticklen'); + coerce('tickwidth'); + coerce('tickcolor'); + coerce('minorticklen'); +} - // fix typo in colorscale definition - if(_$registry_518.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_518.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } +function stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_422.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + var valueIn, valueOut; - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; + function coerce(attr, dflt) { + return _$lib_423.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + } - if(!_$lib_422.isPlainObject(opts)) continue; + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } + coerce('method'); - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } + if(!_$lib_423.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + continue; } - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; + coerce('args'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); + coerce('execute'); - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + valuesOut.push(valueOut); + } - if(!_$lib_422.isPlainObject(transform)) continue; + return valuesOut; +} - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; +'use strict'; - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; +/* removed: var _$d3_79 = require('d3'); */; - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); +/* removed: var _$plots_510 = require('../../plots/plots'); */; +/* removed: var _$color_299 = require('../color'); */; +/* removed: var _$drawing_324 = require('../drawing'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_351 = require('../legend/anchor_utils'); */; - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } - } +/* removed: var _$constants_388 = require('./constants'); */; +/* removed: var _$alignment_399 = require('../../constants/alignment'); */; +var __LINE_SPACING_390 = _$alignment_399.LINE_SPACING; +var __FROM_TL_390 = _$alignment_399.FROM_TL; +var __FROM_BR_390 = _$alignment_399.FROM_BR; - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; - } +var _$draw_390 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_299.clean(trace); - } -}; + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_388.containerClassName) + .data(sliderData.length > 0 ? [0] : []); -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; + sliders.enter().append('g') + .classed(_$constants_388.containerClassName, true) + .style('cursor', 'ew-resize'); - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + sliders.exit().remove(); - return posY + ' ' + posX; -} + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_390(gd); -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); -} + // Return early if no menus visible: + if(sliderData.length === 0) return; + var sliderGroups = sliders.selectAll('g.' + _$constants_388.groupClassName) + .data(sliderData, keyFunction); -// swap all the data and data attributes associated with x and y -_$helpers_452.swapXYData = function(trace) { - var i; - _$lib_422.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_422.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_422.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); - } - } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; - } - trace.hoverinfo = hoverInfoParts.join('+'); - } -}; + sliderGroups.enter().append('g') + .classed(_$constants_388.groupClassName, true); -// coerce traceIndices input to array of trace indices -_$helpers_452.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_89(traceIndices)) { - return [traceIndices]; - } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); + sliderGroups.exit().each(function(sliderOpts) { + _$d3_79.select(this).remove(); + + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; + + _$plots_510.autoMargin(gd, _$constants_388.autoMarginIdRoot + sliderOpts._index); + }); + + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); } - return traceIndices; -}; + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; -/** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_452.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; + var gSlider = _$d3_79.select(this); - var pLastIsNumber = _$fastIsnumeric_89(pLast); + computeLabelSteps(sliderOpts); - // delete item - if(pLastIsNumber && newVal === null) { + _$plots_510.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_422.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); + if(opts.active === data.index) return; + if(opts._dragging) return; - // Note that nested property clears null / undefined at end of - // array container, but not within them. - } - // create item - else if(pLastIsNumber && np.get() === undefined) { + setActive(gd, gSlider, opts, data.index, false, true); + }); - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; + drawSlider(gd, _$d3_79.select(this), sliderOpts); + }); +}; - np.set(newVal); - } - // update item - else { +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_388.name], + sliderData = []; - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); } -}; -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + return sliderData; +} -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); +// This is set in the defaults step: +function keyFunction(opts) { + return opts._index; } -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_452.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; -}; +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_324.tester.selectAll('g.' + _$constants_388.labelGroupClass) + .data(sliderOpts.steps); -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_452 = ['x', 'y', 'z']; -_$helpers_452.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_452[j]); + sliderLabels.enter().append('g') + .classed(_$constants_388.labelGroupClass, true); - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_79.select(this); - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_422.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } -}; + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); -_$helpers_452.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_324.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); } + }); + + sliderLabels.remove(); + + var dims = sliderOpts._dims = {}; + + dims.inputAreaWidth = Math.max( + _$constants_388.railWidth, + _$constants_388.gripHeight + ); + + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; } -}; -var _$manage_arrays_454 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + var textableInputLength = dims.inputAreaLength - 2 * _$constants_388.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_388.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; -'use strict'; + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; -/* removed: var _$nestedProperty_430 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_424 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_431 = require('../lib/noop'); */; -/* removed: var _$loggers_427 = require('../lib/loggers'); */; -var sorterAsc = _$search_440.sorterAsc; -/* removed: var _$registry_518 = require('../registry'); */; + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_324.tester.append('g'); + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_324.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_446.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); -_$manage_arrays_454.containerArrayMatch = _$containerArrayMatch_450; + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; -var isAddVal = _$manage_arrays_454.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_424(val); -}; + dummyGroup.remove(); + } -var isRemoveVal = _$manage_arrays_454.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; + dims.height = dims.currentValueTotalHeight + _$constants_388.tickOffset + sliderOpts.ticklen + _$constants_388.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_454.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_518.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_518.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_518.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_431) || - (draw === _$noop_431), - layout = gd.layout, - fullLayout = gd._fullLayout; - - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_427.warn('Full array edits are incompatible with other edits', - componentType); - } + var xanchor = 'left'; + if(_$anchor_utils_351.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; + } + if(_$anchor_utils_351.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; + } - var fullVal = edits['']['']; + var yanchor = 'top'; + if(_$anchor_utils_351.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_351.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; + } - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); - else { - _$loggers_427.warn('Unrecognized full array edit value', componentType, fullVal); - return true; - } + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - if(replotLater) return false; + _$plots_510.autoMargin(gd, _$constants_388.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_390[xanchor], + r: dims.outerLength * __FROM_BR_390[xanchor], + b: dims.height * __FROM_BR_390[yanchor], + t: dims.height * __FROM_TL_390[yanchor] + }); +} - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; } - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_430(fullLayout, componentType).get(); + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; + var dims = sliderOpts._dims; - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + // Position the rectangle: + _$drawing_324.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_427.warn('index out of range', componentType, componentNum); - continue; - } + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_427.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } +} - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_427.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_430(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } - } + var dims = sliderOpts._dims; + var x0, textAnchor; - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_388.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_388.currentValueInset; + textAnchor = 'left'; } - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); + var text = _$lib_423.ensureSingle(sliderGroup, 'text', _$constants_388.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); - if(replotLater) return false; + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; - supplyComponentDefaults(layout, fullLayout); + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; + } - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_431) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); - } + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; } - else draw(gd); - return true; -}; + text.call(_$drawing_324.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_446.convertToTspans, sliderOpts._gd); -var _$buttons_361 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 lines = _$svg_text_utils_446.lineCount(text); + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_390; -'use strict'; + _$svg_text_utils_446.positionText(text, x0, y0); -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_469 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; + return text; +} -var ____361 = _$lib_422._; +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_423.ensureSingle(sliderGroup, 'rect', _$constants_388.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); -var modeBarButtons = _$buttons_361 = {}; + grip.attr({ + width: _$constants_388.gripWidth, + height: _$constants_388.gripHeight, + rx: _$constants_388.gripRadius, + ry: _$constants_388.gripRadius, + }) + .call(_$color_299.stroke, sliderOpts.bordercolor) + .call(_$color_299.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); +} -/** - * 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? - */ +function drawLabel(item, data, sliderOpts) { + var text = _$lib_423.ensureSingle(item, 'text', _$constants_388.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); -modeBarButtons.toImage = { - name: 'toImage', - title: function(gd) { return ____361(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; + text.call(_$drawing_324.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_446.convertToTspans, sliderOpts._gd); - _$lib_422.notifier(____361(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + return text; +} - if(_$lib_422.isIE()) { - _$lib_422.notifier(____361(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; - } +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_423.ensureSingle(sliderGroup, 'g', _$constants_388.labelsClass); + var dims = sliderOpts._dims; - _$registry_518.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_422.notifier(____361(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_422.notifier(____361(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); - } -}; + var labelItems = labels.selectAll('g.' + _$constants_388.labelGroupClass) + .data(dims.labelSteps); -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____361(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_510.sendDataToCloud(gd); - } -}; + labelItems.enter().append('g') + .classed(_$constants_388.labelGroupClass, true); -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____361(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian -}; + labelItems.exit().remove(); -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____361(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian -}; + labelItems.each(function(d) { + var item = _$d3_79.select(this); -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____361(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; + item.call(drawLabel, d, sliderOpts); -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____361(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian -}; + _$drawing_324.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_388.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_390 + + _$constants_388.labelOffset + + dims.currentValueTotalHeight + ); + }); -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____361(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian -}; +} -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____361(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian -}; +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____361(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian -}; + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); + } +} -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____361(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian -}; +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____361(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian -}; + var step = sliderOpts.steps[sliderOpts.active]; -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____361(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; - }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian -}; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); -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 = _$axis_ids_469.list(gd, null, true); - var allSpikesEnabled = 'on'; + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); - var ax, i; + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; + if(_step.execute) { + _$plots_510.executeAPICommand(gd, _step.method, _step.args); + } - var axName; + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } + } +} - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_79.select(gd); - 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]; - } - 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]), - ]; + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; + } - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); - aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); - aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); - } - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - - aobj[astr] = val; - } - - _$registry_518.call('relayout', gd, aobj); -} - -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____361(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d -}; - -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____361(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d -}; - -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____361(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d -}; - -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____361(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['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_518.call('relayout', gd, layoutUpdate); -} - -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____361(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; + var grip = sliderGroup.select('.' + _$constants_388.gripRectClass); -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____361(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d -}; + _$d3_79.event.stopPropagation(); + _$d3_79.event.preventDefault(); + grip.call(_$color_299.fill, sliderOpts.activebgcolor); -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 = {}; + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_79.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_79.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); + }); - if(attr === 'resetDefault') { - aobj[key] = null; - } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_422.extendDeep({}, scene.cameraInitial); - } - } + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_299.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); - _$registry_518.call('relayout', gd, aobj); + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); + }); } -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; - -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; - - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; - - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_388.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; - if(val) { - layoutUpdate = _$lib_422.extendDeep(layout, val); - button._previousVal = null; - } - else { - layoutUpdate = { - 'allaxes.showspikes': false - }; + tick.enter().append('rect') + .classed(_$constants_388.tickRectClass, true); - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + tick.exit().remove(); - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_79.select(this); - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; - } - } - } + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_299.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - button._previousVal = _$lib_422.extendDeep({}, currentSpikes); - } + _$drawing_324.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_388.tickOffset : _$constants_388.minorTickOffset) + dims.currentValueTotalHeight + ); + }); - _$registry_518.call('relayout', gd, layoutUpdate); } -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____361(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; - -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____361(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; - -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____361(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo -}; - -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.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; +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; - _$registry_518.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); - } + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); } } -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_388.gripRectClass); -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + var x = normalizedValueToPosition(sliderOpts, position); -function toggleHover(gd) { - var fullLayout = gd._fullLayout; + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); } - else onHoverVal = 'closest'; - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - - _$registry_518.call('relayout', gd, 'hovermode', newHover); + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_388.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); } -// buttons when more then one plot types are present - -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); - - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); - } -}; - -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____361(gd, 'Reset views'); }, - icon: _$ploticon_2.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 ____361(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_388.stepInset + + (dims.inputAreaLength - 2 * _$constants_388.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_388.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_388.stepInset - 2 * dims.inputAreaStart))); +} - var aobj = setSpikelineVisibility(gd); +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_423.ensureSingle(sliderGroup, 'rect', _$constants_388.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - _$registry_518.call('relayout', gd, aobj); - } -}; + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_388.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_299.fill, sliderOpts.bgcolor) + .attr('opacity', 0); -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_469.list(gd, null, true); - var aobj = {}; + _$drawing_324.setTranslate(rect, 0, dims.currentValueTotalHeight); +} - var ax, axName; +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_388.railInset * 2; + var rect = _$lib_423.ensureSingle(sliderGroup, 'rect', _$constants_388.railRectClass); - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; - } + rect.attr({ + width: computedLength, + height: _$constants_388.railWidth, + rx: _$constants_388.railRadius, + ry: _$constants_388.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_299.stroke, sliderOpts.bordercolor) + .call(_$color_299.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - return aobj; + _$drawing_324.setTranslate(rect, + _$constants_388.railInset, + (dims.inputAreaWidth - _$constants_388.railWidth) * 0.5 + dims.currentValueTotalHeight + ); } -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____361(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); - } -}; - -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; +function __clearPushMargins_390(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); - 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 i = 0; i < keys.length; i++) { + var k = keys[i]; - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; + if(k.indexOf(_$constants_388.autoMarginIdRoot) !== -1) { + _$plots_510.autoMargin(gd, k); } } - - _$registry_518.call('relayout', gd, aObj); } /** @@ -47426,294 +48319,349 @@ function resetView(gd, subplotType) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_79 = require('d3'); */; - -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - - -/** - * 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'); +/* removed: var _$constants_388 = require('./constants'); */; - this.update(opts.graphInfo, opts.buttons); +var _$sliders_391 = { + moduleType: 'component', + name: _$constants_388.name, - this.container.appendChild(this.element); -} + layoutAttributes: _$attributes_387, + supplyLayoutDefaults: _$slidersDefaults_389, -var proto = ModeBar.prototype; + draw: _$draw_390 +}; /** - * 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; - - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; - } - else this.element.className = 'modebar'; - - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); - - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); - - this.updateButtons(buttons); +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; - } - } +'use strict'; - this.updateActiveButton(); -}; +/* removed: var _$font_attributes_493 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_298 = require('../color/attributes'); */; +var __extendFlat_393 = _$extend_415.extendFlat; +var __overrideAll_393 = _$edit_types_452.overrideAll; +/* removed: var _$pad_attributes_509 = require('../../plots/pad_attributes'); */; -proto.updateButtons = function(buttons) { - var _this = this; +var buttonsAttrs = { + _isLinkedToArray: 'button', - this.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); +var _$attributes_393 = __overrideAll_393({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - 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); + visible: { + valType: 'boolean', + + + }, - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, - _this.element.appendChild(group); - }); -}; + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, -/** - * Empty div for containing a group of buttons - * @Return {HTMLelement} - */ -proto.createGroup = function() { - var group = document.createElement('div'); - group.className = 'modebar-group'; + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, - return group; -}; + showactive: { + valType: 'boolean', + + dflt: true, + + }, + + buttons: buttonsAttrs, + + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, + + pad: __extendFlat_393({}, _$pad_attributes_509, { + + }), + + font: _$font_attributes_493({ + + }), + + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_298.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + + } +}, 'arraydraw', 'from-root'); /** - * 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, - button = document.createElement('a'); +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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); +'use strict'; - if(title || title === 0) button.setAttribute('data-title', title); - if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); +var _$constants_394 = { - var val = config.val; - if(val !== undefined) { - if(typeof val === 'function') val = val(this.graphInfo); - button.setAttribute('data-val', val); - } + // layout attribute name + name: 'updatemenus', - 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); + // 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', - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); - } + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'updatemenu-active-index', - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_79.select(button).classed('active', true); + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'updatemenu-', - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - button.setAttribute('data-gravity', config.gravity || 'n'); + // options when 'active: -1' + blankHeaderOpts: { label: ' ' }, - return button; -}; + // min item width / height + minWidth: 30, + minHeight: 30, -/** - * Add an icon to a button - * @Param {object} thisIcon - * @Param {number} thisIcon.width - * @Param {string} thisIcon.path - * @Return {HTMLelement} - */ -proto.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); + // padding around item text + textPadX: 24, + arrowPadX: 16, - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); + // item rect radii + rx: 2, + ry: 2, - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; + // item text x offset off left edge + textOffsetX: 12, - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); + // item text y offset (w.r.t. middle) + textOffsetY: 3, - return icon; -}; + // arrow offset off right edge + arrowOffsetX: 4, -/** - * 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, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; + // gap between header and buttons + gapButtonHeader: 5, - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_79.select(button); + // gap between between buttons + gapButton: 2, - // 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_422.nestedProperty(fullLayout, dataAttr).get(); + // color given to active buttons + activeColor: '#F4FAFF', - button3.classed('active', val === thisval); - } + // color given to hovered buttons + hoverColor: '#F4FAFF', - }); + // symbol for menu open arrow + arrowSymbol: { + left: '◄', + right: '►', + up: '▲', + down: '▼' + } }; /** - * 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; +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!currentButtons) return false; +'use strict'; - if(buttons.length !== currentButtons.length) return false; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_463 = require('../../plots/array_container_defaults'); */; - 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; - } - } +/* removed: var _$attributes_393 = require('./attributes'); */; +/* removed: var _$constants_394 = require('./constants'); */; - return true; +var __name_395 = _$constants_394.name; +var __buttonAttrs_395 = _$attributes_393.buttons; + + +var _$updateMenusDefaults_395 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_395, + handleItemDefaults: menuDefaults + }; + + _$handleArrayContainerDefaults_463(layoutIn, layoutOut, opts); }; -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -proto.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); +function menuDefaults(menuIn, menuOut, layoutOut) { - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_422._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; + function coerce(attr, dflt) { + return _$lib_423.coerce(menuIn, menuOut, _$attributes_393, attr, dflt); + } - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); + var buttons = __buttonsDefaults_395(menuIn, menuOut); - group.appendChild(a); - return group; -}; + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; -proto.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); + + coerce('x'); + coerce('y'); + _$lib_423.noneOrAll(menuIn, menuOut, ['x', 'y']); + + coerce('xanchor'); + coerce('yanchor'); + + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); + + _$lib_423.coerceFont(coerce, 'font', layoutOut.font); + + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} + +function __buttonsDefaults_395(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; + + var buttonIn, buttonOut; + + function coerce(attr, dflt) { + return _$lib_423.coerce(buttonIn, buttonOut, __buttonAttrs_395, attr, dflt); } - this.hasLogo = false; -}; + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; -proto.destroy = function() { - _$lib_422.removeElement(this.container.querySelector('.modebar')); -}; + coerce('method'); -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; + if(!_$lib_423.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); + coerce('args'); + coerce('label'); + coerce('execute'); - if(fullLayout._privateplot) { - _$d3_79.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); + buttonOut._index = i; + buttonsOut.push(buttonOut); } - return modeBar; + return buttonsOut; } -var _$createModeBar_364 = createModeBar; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -47722,265 +48670,467 @@ var _$createModeBar_364 = createModeBar; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$axis_ids_469 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_558 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +var _$ScrollBox_398 = ScrollBox; -/* removed: var _$createModeBar_364 = require('./modebar'); */; -/* removed: var _$buttons_361 = require('./buttons'); */; +/* removed: var _$d3_79 = require('d3'); */; + +/* removed: var _$color_299 = require('../color'); */; +/* removed: var _$drawing_324 = require('../drawing'); */; + +/* removed: var _$lib_423 = require('../../lib'); */; /** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object + * Helper class to setup a scroll box * + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box */ -var _$manageModeBar_363 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); - var customButtons = context.modeBarButtons; - var buttonGroups; + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_364(gd, buttonGroups); -}; +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; +/** + * If needed, setup a clip path and scrollbars + * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); + // compute position of scrollbox + this.position = position; - var groups = []; + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; - function addGroup(newGroup) { - if(!newGroup.length) return; + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; + } - var out = []; + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_361[button]); + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; } + } + else { + boxT = t; + boxB = boxT + boxH; - groups.push(out); + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; + } + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; + } } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); + + hbar.exit() + .on('.drag', null) + .remove(); + + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_299.fill, ScrollBox.barColor); + + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); + + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; + else { + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; + + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; + + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); + + vbar.exit() + .on('.drag', null) + .remove(); + + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_299.fill, ScrollBox.barColor); + + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); + + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; + + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + + clipPath.exit().remove(); + + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); + + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); + + this.container.call(_$drawing_324.setClipUrl, clipId); + + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_324.setClipUrl, null); + delete this._clipRect; } - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; - } + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_79.behavior.drag() + .on('dragstart', function() { + _$d3_79.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); + + var onBarDrag = _$d3_79.behavior.drag() + .on('dragstart', function() { + _$d3_79.event.sourceEvent.preventDefault(); + _$d3_79.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); + + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } + + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; + + // set scrollbox translation + this.setTranslate(translateX, translateY); +}; + +/** + * If present, remove clip-path and scrollbars + * + * @method + */ +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_324.setClipUrl, null); + delete this._clipRect; } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; + + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; + + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); +}; + +/** + * Handles scroll box drag events + * + * @method + */ +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX -= _$d3_79.event.dx; } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); + if(this.vbar) { + translateY -= _$d3_79.event.dy; + } - return appendButtonsToGroups(groups, buttonsToAdd); -} + this.setTranslate(translateX, translateY); +}; -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_469.list({_fullLayout: fullLayout}, null, true); +/** + * Handles scroll box wheel events + * + * @method + */ +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } + if(this.hbar) { + translateX += _$d3_79.event.deltaY; } - return true; -} + if(this.vbar) { + translateY += _$d3_79.event.deltaY; + } -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; + this.setTranslate(translateX, translateY); +}; - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; +/** + * Handles scroll bar drag events + * + * @method + */ +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; - var trace = fullData[i]; + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_423.constrain(_$d3_79.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); - if(!trace._module || !trace._module.selectPoints) continue; + var translateXMax = this.position.w - this._box.w; - if(_$registry_518.traceIs(trace, 'scatter-like')) { - if(_$subtypes_558.hasMarkers(trace) || _$subtypes_558.hasText(trace)) { - selectable = true; - } - } else if(_$registry_518.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; + translateX = xf * translateXMax; } - return selectable; -} + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_423.constrain(_$d3_79.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } - } - else groups.push(buttons); + var translateYMax = this.position.h - this._box.h; + + translateY = yf * translateYMax; } - return groups; -} + this.setTranslate(translateX, translateY); +}; -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; +/** + * Set clip path and scroll bar translate transform + * + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + translateX = _$lib_423.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_423.constrain(translateY || 0, 0, translateYMax); - if(typeof button === 'string') { - if(_$buttons_361[button] !== undefined) { - customButtons[i][j] = _$buttons_361[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } - } + this.translateX = translateX; + this.translateY = translateY; - return customButtons; -} + this.container.call(_$drawing_324.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); -var _$modebar_362 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } + if(this.hbar) { + var xf = translateX / translateXMax; -'use strict'; + this.hbar.call(_$drawing_324.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); + } -_$modebar_362.manage = _$manageModeBar_363; + if(this.vbar) { + var yf = translateY / translateYMax; + + this.vbar.call(_$drawing_324.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -47993,1632 +49143,1677 @@ _$modebar_362.manage = _$manageModeBar_363; 'use strict'; -var FROM_BL = _$alignment_399.FROM_BL; +/* removed: var _$d3_79 = require('d3'); */; -var _$scaleZoom_483 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } +/* removed: var _$plots_510 = require('../../plots/plots'); */; +/* removed: var _$color_299 = require('../color'); */; +/* removed: var _$drawing_324 = require('../drawing'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_351 = require('../legend/anchor_utils'); */; - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; +var __LINE_SPACING_396 = _$alignment_399.LINE_SPACING; - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; +/* removed: var _$constants_394 = require('./constants'); */; +/* removed: var _$ScrollBox_398 = require('./scrollbox'); */; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs - -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// +var _$draw_396 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_394.containerClassName) + .data(menuData.length > 0 ? [0] : []); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + menus.enter().append('g') + .classed(_$constants_394.containerClassName, true) + .style('cursor', 'pointer'); -var _$BuildLog_221 = BuildLog; + menus.exit().remove(); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_396(gd); -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + // return early if no update menus are visible + if(menuData.length === 0) return; -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_394.headerGroupClassName) + .data(menuData, __keyFunction_396); - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + headerGroups.enter().append('g') + .classed(_$constants_394.headerGroupClassName, true); - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + // draw dropdown button container + var gButton = _$lib_423.ensureSingle(menus, 'g', _$constants_394.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_396(gd, menuOpts); + } - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_398(gd, gButton, scrollBoxId); - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; + gButton + .call(removeAllButtons) + .attr(_$constants_394.menuIndexAttrName, '-1'); + } - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; + headerGroups.exit().each(function(menuOpts) { + _$d3_79.select(this).remove(); - // categorize where intersection point is along A and B + gButton + .call(removeAllButtons) + .attr(_$constants_394.menuIndexAttrName, '-1'); - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + _$plots_510.autoMargin(gd, _$constants_394.autoMarginIdRoot + menuOpts._index); + }); - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_79.select(this); - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_510.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_396(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; -} + // if this menu is active, update the dropdown container + if(__isActive_396(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); + } -var _$Epsilon_222 = Epsilon; + }); +}; -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** + * get only visible menus for display + */ +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_394.name]; + var menuData = []; -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + if(item.visible) menuData.push(item); + } - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + return menuData; +} - // 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] }); - } +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_396(menuOpts) { + return menuOpts._index; +} - // the first LineString is considered the outside - var out = LineString(coords[0]); +function isFolded(gButton) { + return +gButton.attr(_$constants_394.menuIndexAttrName) === -1; +} - // 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]))); +function __isActive_396(gButton, menuOpts) { + return +gButton.attr(_$constants_394.menuIndexAttrName) === menuOpts._index; +} - return out; - } +function __setActive_396(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; - 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'); - }, + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); + } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_394.menuIndexAttrName, '-1'); - // 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)); + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - // 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); - } + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } +} - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_423.ensureSingle(gHeader, 'g', _$constants_394.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); - function newNode(region){ - return { - region: region, - children: [] - }; - } + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_394.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; - var roots = newNode(null); + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); - 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; - } - } + // draw drop arrow at the right edge + var arrow = _$lib_423.ensureSingle(gHeader, 'text', _$constants_394.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_324.font, menuOpts.font) + .text(_$constants_394.arrowSymbol[menuOpts.direction]); + }); - // 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--; - } - } + arrow.attr({ + x: dims.headerWidth - _$constants_394.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_394.textOffsetY + menuOpts.pad.t + }); - // now we can add ourselves - root.children.push(node); - } + header.on('click', function() { + gButton.call(removeAllButtons); - // 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 + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_394.menuIndexAttrName, + __isActive_396(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); - 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; - } + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); - var geopolys = []; + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); - 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])); - } + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); - 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); - } + // translate header group + _$drawing_324.setTranslate(gHeader, dims.lx, dims.ly); +} - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } - // lastly, construct the approrpriate GeoJSON object + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; - 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 - }; - } -}; + var klass = menuOpts.type === 'dropdown' ? _$constants_394.dropdownButtonClassName : _$constants_394.buttonClassName; -var _$GeoJSON_223 = GeoJSON; + var buttons = gButton.selectAll('g.' + klass) + .data(buttonData); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + var enter = buttons.enter().append('g') + .classed(klass, true); -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + var exit = buttons.exit(); -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); -var _$LinkedList_225 = LinkedList; + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; -// -// this is the core work-horse -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; -/* removed: var _$LinkedList_225 = require('./linked-list'); */; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_394.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_394.gapButtonHeader; + } + } -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_394.gapButtonHeader + _$constants_394.gapButton - dims.openHeight; + } - // - // segment creation - // + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_394.gapButtonHeader + _$constants_394.gapButton - dims.openWidth; + } - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_394.gapButton, + xPad: _$constants_394.gapButton, + index: 0, + }; - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; - // - // event logic - // + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_79.select(this); - var event_root = _$LinkedList_225.create(); + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same + button.on('click', function() { + // skip `dragend` events + if(_$d3_79.event.defaultPrevented) return; - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + __setActive_396(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + if(buttonOpts.execute) { + _$plots_510.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_225.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_225.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + buttons.call(styleButtons, menuOpts); - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + } - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) + scrollBoxPosition.direction = menuOpts.direction; - if (buildLog) - buildLog.segmentChop(ev.seg, end); + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } +} - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_394.gapButton; + } + } + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_394.gapButton; + } + } - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used + scrollBox.enable(position, translateX, translateY); - // - // status logic - // + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } - var status_root = _$LinkedList_225.create(); + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } +} - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); + } +} - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); +} - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; +function drawItemRect(item, menuOpts) { + var rect = _$lib_423.ensureSingle(item, 'rect', _$constants_394.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_394.rx, + ry: _$constants_394.ry, + 'shape-rendering': 'crispEdges' + }); + }); - if (buildLog) - buildLog.checkIntersection(seg1, seg2); + rect.call(_$color_299.stroke, menuOpts.bordercolor) + .call(_$color_299.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} - var i = eps.linesIntersect(a1, a2, b1, b2); +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_423.ensureSingle(item, 'text', _$constants_394.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); - if (i === false){ - // segments are parallel or coincident + text.call(_$drawing_324.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_446.convertToTspans, gd); +} - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection + buttons.each(function(buttonOpts, i) { + var button = _$d3_79.select(this); - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_394.itemRectClassName) + .call(_$color_299.fill, _$constants_394.activeColor); + } + }); +} - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_394.itemRectClassName) + .call(_$color_299.fill, _$constants_394.hoverColor); +} - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_394.itemRectClassName) + .call(_$color_299.fill, menuOpts.bgcolor); +} - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); - - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } +// find item dimensions (this mutates menuOpts) +function __findDimensions_396(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + var fakeButtons = _$drawing_324.tester.selectAll('g.' + _$constants_394.dropdownButtonClassName) + .data(menuOpts.buttons); - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + fakeButtons.enter().append('g') + .classed(_$constants_394.dropdownButtonClassName, true); - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_79.select(this); - if (buildLog) - buildLog.vert(ev.pt[0]); + button.call(drawItem, menuOpts, buttonOpts, gd); - if (ev.isStart){ + var text = button.select('.' + _$constants_394.itemTextClassName); - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_324.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_394.textPadX, _$constants_394.minWidth); - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_396; + var tLines = _$svg_text_utils_446.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_394.minHeight) + _$constants_394.textOffsetY; - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); - // merge ev.seg's fill information into eve.seg + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_394.gapButton; + dims.openHeight += hEff + _$constants_394.gapButton; + } else { + dims.totalWidth += wEff + _$constants_394.gapButton; + dims.openWidth += wEff + _$constants_394.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + if(isVertical) { + dims.totalHeight -= _$constants_394.gapButton; + } else { + dims.totalWidth -= _$constants_394.gapButton; + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } - if (buildLog) - buildLog.segmentUpdate(eve.seg); + dims.headerWidth = dims.width1 + _$constants_394.arrowPadX; + dims.headerHeight = dims.height1; - ev.other.remove(); - ev.remove(); - } + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_394.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_394.arrowPadX; + } - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } + fakeButtons.remove(); - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var xanchor = 'left'; + if(_$anchor_utils_351.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_351.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + var yanchor = 'top'; + if(_$anchor_utils_351.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_351.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; + } - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_225.node({ ev: ev })); - } - else{ - var st = ev.status; + _$plots_510.autoMargin(gd, _$constants_394.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); +} - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_394.itemRectClassName); + var text = item.select('.' + _$constants_394.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); + _$drawing_324.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); - if (buildLog) - buildLog.statusRemove(st.ev.seg); + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); - // remove the status - st.remove(); + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } + var tHeight = menuOpts.font.size * __LINE_SPACING_396; + var tLines = _$svg_text_utils_446.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); - // remove the event and continue - event_root.getHead().remove(); - } + _$svg_text_utils_446.positionText(text, _$constants_394.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_394.textOffsetY); - if (buildLog) - buildLog.done(); + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; + } - return segments; - } + posOpts.index++; +} - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_394.dropdownButtonClassName).remove(); +} - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; +function __clearPushMargins_396(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; + if(k.indexOf(_$constants_394.autoMarginIdRoot) !== -1) { + _$plots_510.autoMargin(gd, k); + } + } } -var _$Intersecter_224 = Intersecter; - -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// +'use strict'; -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; +/* removed: var _$constants_394 = require('./constants'); */; - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } +var _$updatemenus_397 = { + moduleType: 'component', + name: _$constants_394.name, - if (buildLog) - buildLog.chainStart(seg); + layoutAttributes: _$attributes_393, + supplyLayoutDefaults: _$updateMenusDefaults_395, - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + draw: _$draw_396 +}; - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } +var _$mathjax_config_407 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (next_match === second_match){ - // we matched a single chain +'use strict'; - if (buildLog) - buildLog.chainMatch(first_match.index); +/* global MathJax:false */ - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop - - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_407.MathJax = true; - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + MathJax.Hub.Configured(); +} else { + _$mathjax_config_407.MathJax = false; +} - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } - if (buildLog) - buildLog.chainClose(first_match.index); +'use strict'; - // we have a closed chain! - regions.push(chain); - return; - } +/* removed: var _$lib_423 = require('../lib'); */; +/* removed: var _$plot_config_457 = require('../plot_api/plot_config'); */; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } - // otherwise, we matched two chains, so we need to combine those chains together +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + for(var i = 0; i < args.length; i++) { + arg = args[i]; - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_423.extendDeep([], arg) : + _$lib_423.extendDeepAll({}, arg); + } + else copy[i] = arg; + } - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + return copy; +} - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- - var F = first_match.index; - var S = second_match.index; - if (buildLog) - buildLog.chainConnect(F, S); +var __queue_437 = {}; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); +// TODO: disable/enable undo and redo buttons appropriately - return regions; -} +/** + * Add an item to the undoQueue for a graphDiv + * + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with + */ +__queue_437.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; -var _$SegmentChainer_226 = SegmentChainer; + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } -// -// filter a list of segments based on boolean operations -// + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } - if (buildLog) - buildLog.selected(result); + if(gd.undoQueue.queue.length > _$plot_config_457.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; - return result; -} +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_437.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_437.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; }; -var _$SegmentSelector_227 = SegmentSelector; +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_437.undo = function undo(gd) { + var queueObj, i; -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } + + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; + + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_437.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; + +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd */ +__queue_437.redo = function redo(gd) { + var queueObj, i; -/* removed: var _$BuildLog_221 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_222 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_224 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_226 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_227 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_223 = require('./lib/geojson'); */; + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } -var buildLog = false; -var epsilon = _$Epsilon_222(); + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_221(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_437.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; - // core API - segments: function(poly){ - var i = _$Intersecter_224(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_224(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_227.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_227.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_227.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_227.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_227.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_226(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; +}; - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_223.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_223.fromPolygon(PolyBool, epsilon, poly); - }, +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_437.plotDo = function(gd, func, args) { + gd.autoplay = true; - // 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); - } + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); + + // call the supplied function + func.apply(null, args); +}; + +var _$queue_437 = __queue_437; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$localeEnUs_449 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$localeEn_450 = { + 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' + } +}; + +var _$fromQuat_116 = 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; +}; +var _$helpers_453 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_116 = require('gl-mat4/fromQuat'); */; + +/* removed: var _$registry_519 = require('../registry'); */; +/* removed: var _$lib_423 = require('../lib'); */; +/* removed: var _$plots_510 = require('../plots/plots'); */; +/* removed: var _$axis_ids_470 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_470.cleanId; +var getFromTrace = _$axis_ids_470.getFromTrace; +/* removed: var _$color_299 = require('../components/color'); */; + + +// clear the promise queue if one of them got rejected +_$helpers_453.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_423.log('Clearing previous rejected promises from queue.'); + } + + gd._promises = []; +}; + +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_453.cleanLayout = function(layout) { + var i, j; + + if(!layout) layout = {}; + + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } + + var axisAttrRegex = (_$plots_510.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_510.subplotsRegistry.gl3d || {}).attrRegex; + + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[i]; + + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories + + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; + + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; + } + delete ax.autotick; + } + } + + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; + + // clean old Camera coords + var cameraposition = scene.cameraposition; + + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_116([], rotation), + eye = []; + + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } + + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; + + delete scene.cameraposition; + } + } + } + + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; + + if(!_$lib_423.isPlainObject(ann)) continue; + + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; + } + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; + } + + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); + } + + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; + + if(!_$lib_423.isPlainObject(shape)) continue; + + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); + } + + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } + + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } + + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_299.clean(layout); + + return layout; +}; + +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); + } +} + +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_453.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); + + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; + + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; + + for(i = 0; i < 100; i++) { + newUid = _$lib_423.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_423.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); + + // BACKWARD COMPATIBILITY FIXES + + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } + + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_299.defaults, + yeColor = trace.error_y.color || + (_$registry_519.traceIs(trace, 'bar') ? _$color_299.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_299.addOpacity( + _$color_299.rgb(yeColor), + _$color_299.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; + } + + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_519.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_453.swapXYData(trace); + } + delete trace.bardir; + } + + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_453.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } + + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } + + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + + // scene ids scene1 -> scene + if(_$registry_519.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_510.subplotsRegistry.gl3d.cleanId(trace.scene); + } + + if(!_$registry_519.traceIs(trace, 'pie') && !_$registry_519.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } + + // fix typo in colorscale definition + if(_$registry_519.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_519.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } + + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_423.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; + + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; + + if(!_$lib_423.isPlainObject(opts)) continue; + + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } + + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } + } + + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); + + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names + + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } + + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; + + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; + + if(!_$lib_423.isPlainObject(transform)) continue; + + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } + + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; + + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; + + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); + + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } + } + + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } + + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_299.clean(trace); + } }; -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); -} +function cleanFinanceDir(dirContainer) { + if(!_$lib_423.isPlainObject(dirContainer)) return false; + + var dirName = dirContainer.name; + + delete dirContainer.name; + delete dirContainer.showlegend; + + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); +} + +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; + + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; + + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } + + var out = name1.substr(0, i); + return out.trim(); +} + +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; + + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; + + return posY + ' ' + posX; +} + +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} + + +// swap all the data and data attributes associated with x and y +_$helpers_453.swapXYData = function(trace) { + var i; + _$lib_423.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_423.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_423.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); + } +}; + +// coerce traceIndices input to array of trace indices +_$helpers_453.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_89(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); + } + + return traceIndices; +}; + +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * + */ +_$helpers_453.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; + + var pLastIsNumber = _$fastIsnumeric_89(pLast); + + // delete item + if(pLastIsNumber && newVal === null) { + + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_423.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); + + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { + + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; + + np.set(newVal); + } + // update item + else { + + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); + } +}; + +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); +} + +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_453.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; +}; + +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_453 = ['x', 'y', 'z']; +_$helpers_453.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_453[j]); + + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; + } + var typeAttr = axAttr + '.type'; -if (typeof window === 'object') - window.PolyBool = PolyBool; + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_423.nestedProperty(gd.layout, typeAttr).set(null); + } + } + } + } +}; -var _$PolyBool_220 = PolyBool; +_$helpers_453.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; + } + } +}; -var _$polygon_434 = {}; +var _$manage_arrays_455 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49630,293 +50825,209 @@ var _$polygon_434 = {}; 'use strict'; -var dot = _$matrix_428.dot; -var __BADNUM_434 = _$numerical_403.BADNUM; - -var polygon = _$polygon_434 = {}; +/* removed: var _$nestedProperty_431 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_425 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_432 = require('../lib/noop'); */; +/* removed: var _$loggers_428 = require('../lib/loggers'); */; +var sorterAsc = _$search_441.sorterAsc; +/* removed: var _$registry_519 = require('../registry'); */; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; +_$manage_arrays_455.containerArrayMatch = _$containerArrayMatch_451; - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } +var isAddVal = _$manage_arrays_455.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_425(val); +}; - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed +var isRemoveVal = _$manage_arrays_455.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; - var isRect = false, - rectFirstEdgeTest; +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. + * + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items + * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. + */ +_$manage_arrays_455.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_519.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_519.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_519.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_432) || + (draw === _$noop_432), + layout = gd.layout, + fullLayout = gd._fullLayout; - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_428.warn('Full array edits are incompatible with other edits', + componentType); } - } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var fullVal = edits['']['']; - if(x === __BADNUM_434 || x < xmin || x > xmax || y === __BADNUM_434 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_428.warn('Unrecognized full array edit value', componentType, fullVal); + return true; } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + if(replotLater) return false; + + supplyComponentDefaults(layout, fullLayout); + draw(gd); return true; } - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_431(fullLayout, componentType).get(); - if(x === __BADNUM_434 || x < xmin || x > xmax || y === __BADNUM_434 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_428.warn('index out of range', componentType, componentNum); + continue; + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_428.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; + + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } - // inside the bounding box, check the actual line intercept else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } - - if(y <= ycross && x !== xmini) crossings++; + _$loggers_428.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); } - } - - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; + if(firstIndexChange === -1) firstIndexChange = componentNum; } - } - - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; - -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; - - for(var i = 0; i < list.length; i++) { - 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); - } - - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_431(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } - - return yes; } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; - -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; - - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); - - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - return false; -}; -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); + if(replotLater) return false; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; + supplyComponentDefaults(layout, fullLayout); + + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_432) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); } } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); + } } + else draw(gd); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); - } - - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; + return true; }; +var _$buttons_361 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49928,1483 +51039,1166 @@ polygon.filter = function filter(pts, tolerance) { 'use strict'; -/* removed: var _$PolyBool_220 = require('polybooljs'); */; -/* removed: var _$polygon_434 = require('../../lib/polygon'); */; -/* removed: var _$throttle_446 = require('../../lib/throttle'); */; -/* removed: var _$color_299 = require('../../components/color'); */; -var makeEventData = _$helpers_338.makeEventData; -/* removed: var _$fx_341 = require('../../components/fx'); */; - -/* removed: var _$axes_466 = require('./axes'); */; -/* removed: var _$constants_471 = require('./constants'); */; - -var filteredPolygon = _$polygon_434.filter; -var polygonTester = _$polygon_434.tester; -var multipolygonTester = _$polygon_434.multitester; -var MINSELECT = _$constants_471.MINSELECT; - -function getAxId(ax) { return ax._id; } - -var _$prepSelect_484 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } - - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_471.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_299.background, - stroke: _$color_299.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$plots_510 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_470 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; +var ____361 = _$lib_423._; - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_471.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; +var modeBarButtons = _$buttons_361 = {}; - 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; +/** + * 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? + */ - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____361(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_466.getFromId(gd, trace.xaxis), - yaxis: _$axes_466.getFromId(gd, trace.yaxis) - }); + _$lib_423.notifier(____361(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + + if(_$lib_423.isIE()) { + _$lib_423.notifier(____361(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; } - } - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + _$registry_519.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_423.notifier(____361(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_423.notifier(____361(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); } +}; - function ascending(a, b) { return a - b; } +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____361(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_510.sendDataToCloud(gd); + } +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____361(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____361(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____361(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian +}; - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____361(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } - } +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____361(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian +}; - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____361(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian +}; - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____361(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____361(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____361(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____361(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +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 = _$axis_ids_470.list(gd, null, true); + var allSpikesEnabled = 'on'; - _$throttle_446.throttle( - throttleID, - _$constants_471.SELECTDELAY, - function() { - selection = []; + var ax, i; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); + var axName; - thisSelection = fillSelectionItem(traceSelection, searchInfo); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); + 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]; + } + if(ax._showSpikeInitial !== undefined) { + aobj[axName + '.showspikes'] = ax._showSpikeInitial; + if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) { + allSpikesEnabled = 'off'; } } - else selection = thisSelection; } + else { + var rangeNow = [ + ax.r2l(ax.range[0]), + ax.r2l(ax.range[1]), + ]; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; - - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - _$throttle_446.done(throttleID).then(function() { - _$throttle_446.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); } - - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); } - else { - // 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. - gd.emit('plotly_selected', undefined); + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } - _$fx_341.click(gd, evt); - }); - }; - - dragOptions.doneFn = function() { - corners.remove(); + aobj[astr] = val; + } - _$throttle_446.done(throttleID).then(function() { - _$throttle_446.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); + _$registry_519.call('relayout', gd, aobj); +} - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____361(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d +}; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____361(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____361(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - if(eventData) { - var pts = eventData.points || []; +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____361(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['z-axis'], + click: handleDrag3d +}; - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +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 = {}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; + var parts = attr.split('.'); - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); - } - } + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - else { - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; + + _$registry_519.call('relayout', gd, layoutUpdate); +} + +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____361(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; + +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____361(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.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], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; + + if(attr === 'resetDefault') { + aobj[key] = null; + } + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_423.extendDeep({}, scene.cameraInitial); } } - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } + _$registry_519.call('relayout', gd, aobj); } -function mergePolygons(list, poly, subtract) { - var res; +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - if(subtract) { - res = _$PolyBool_220.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - return res.regions; + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; + + if(val) { + layoutUpdate = _$lib_423.extendDeep(layout, val); + button._previousVal = null; } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - res = _$PolyBool_220.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; - return res.regions; -} + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; -function fillSelectionItem(selection, searchInfo) { - if(Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - for(var i = 0; i < selection.length; i++) { - selection[i] = makeEventData(selection[i], trace, cd); + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + } + } } + + button._previousVal = _$lib_423.extendDeep({}, currentSpikes); } - return selection; + _$registry_519.call('relayout', gd, layoutUpdate); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____361(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____361(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; -'use strict'; +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____361(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; -/* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$tinycolor_264 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_174 = require('has-passive-events'); */; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_299 = require('../../components/color'); */; -/* removed: var _$drawing_324 = require('../../components/drawing'); */; -/* removed: var _$fx_341 = require('../../components/fx'); */; -/* removed: var _$setCursor_441 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_321 = require('../../components/dragelement'); */; -var __FROM_TL_474 = _$alignment_399.FROM_TL; +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; -/* removed: var _$plots_510 = require('../plots'); */; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; -var doTicks = _$axes_466.doTicks; -var getFromId = _$axis_ids_469.getFromId; -/* removed: var _$prepSelect_484 = require('./select'); */; -/* removed: var _$scaleZoom_483 = require('./scale_zoom'); */; + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; -/* removed: var _$constants_471 = require('./constants'); */; -var MINDRAG = _$constants_471.MINDRAG; -var MINZOOM = _$constants_471.MINZOOM; + _$registry_519.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); + } + } +} +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px +function toggleHover(gd) { var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + } + else onHoverVal = 'closest'; - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$registry_519.call('relayout', gd, 'hovermode', newHover); +} - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); +// buttons when more then one plot types are present - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____361(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____361(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); } +}; - recomputeAxisLists(); +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____361(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - var allFixedRanges = !yActive && !xActive; + var aobj = setSpikelineVisibility(gd); - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; + _$registry_519.call('relayout', gd, aobj); } +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_484(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_470.list(gd, null, true); + var aobj = {}; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + var ax, axName; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - if(numClicks === 2 && !singleEnd) doubleClick(); + return aobj; +} - if(isMainDrag) { - _$fx_341.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____361(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if(ax.fixedrange) return; +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; + 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); - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_79.select(dragger) - .call(_$svg_text_utils_445.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_518.call('relayout', gd, attrStr, v); - } - }); - } - } + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; } - }; - - _$dragelement_321.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + } - // collected changes to be made to the plot by relayout at the end - var updates = {}; + _$registry_519.call('relayout', gd, aObj); +} - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_264(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); +'use strict'; - clearSelect(zoomlayer); - } +/* removed: var _$d3_79 = require('d3'); */; - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +/** + * 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'); - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } + this.update(opts.graphInfo, opts.buttons); - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; + this.container.appendChild(this.element); +} - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } +var proto = ModeBar.prototype; - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } +/** + * 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; - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); + var context = this.graphInfo._context; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; } + else this.element.className = 'modebar'; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_471.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - var pc = gd.querySelector('.plotly'); + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - recomputeAxisLists(); + this.updateButtons(buttons); - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - clearTimeout(redrawTimer); + this.updateActiveButton(); +}; - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_422.log('Did not find wheel motion attributes: ', e); - return; - } +proto.updateButtons = function(buttons) { + var _this = this; - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - var axRange = _$lib_422.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + 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); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +proto.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * 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, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_79.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +proto.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_483(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_483(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * 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, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_79.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_423.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * 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((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_518.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_518.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_518.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +proto.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_423._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +proto.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +proto.destroy = function() { + _$lib_423.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_518.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_79.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_422.syncOrAsync([ - _$plots_510.previousPromises, - function() { _$registry_518.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_364 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_470 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_559 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_519 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_483(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_364 = require('./modebar'); */; +/* removed: var _$buttons_361 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_474[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_363 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_422.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_422.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_364(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_324.setTranslate, clipDx, clipDy) - .call(_$drawing_324.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_324.setTranslate, plotDx, plotDy) - .call(_$drawing_324.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_324.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_324.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_324.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_324.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_361[button]); } - } - - return dragger; -} - -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - dragger3.call(_$setCursor_441, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_79.select(dragger).call(_$drawing_324.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_79.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_79.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_470.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_299.background, - stroke: _$color_299.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_519.traceIs(trace, 'scatter-like')) { + if(_$subtypes_559.hasMarkers(trace) || _$subtypes_559.hasText(trace)) { + selectable = true; + } + } else if(_$registry_519.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_79.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_422.notifier(_$lib_422._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_361[button] !== undefined) { + customButtons[i][j] = _$buttons_361[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_422.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_174) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_474 = { - makeDragBox: makeDragBox, +var _$modebar_362 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_362.manage = _$manageModeBar_363; +var _$constraints_474 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51416,152 +52210,202 @@ var _$dragbox_474 = { 'use strict'; -/* removed: var _$d3_79 = require('d3'); */; +var __id2name_474 = _$axis_ids_470.id2name; +/* removed: var _$scaleZoom_483 = require('./scale_zoom'); */; +var __makePadFn_474 = _$autorange_466.makePadFn; -/* removed: var _$fx_341 = require('../../components/fx'); */; -/* removed: var _$dragelement_321 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_403.ALMOST_EQUAL; -/* removed: var _$constants_471 = require('./constants'); */; -var __makeDragBox_475 = _$dragbox_474.makeDragBox; +var __FROM_BL_474 = _$alignment_399.FROM_BL; -var _$initInteractions_475 = function initInteractions(gd) { + +_$constraints_474.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_79.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - 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'), - 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)); + 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_474(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_471.DRAGGERSIZE; + if(mode === 'range') { + _$scaleZoom_483(ax, factor); + } + else { + // mode === 'domain' - // 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_475(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + 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])); - 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) { - _$fx_341.hover(gd, evt, subplot); + 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_483(ax, factor); + continue; } - }; - _$fx_341.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_474(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_321.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_475(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_475(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_475(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_475(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_475(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_475(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_475(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_475(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_475(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_475(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_474.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_341.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_341.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_474[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_458 = {}; +var _$subroutines_459 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51573,21 +52417,27 @@ var _$subroutines_458 = {}; 'use strict'; /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$registry_518 = require('../registry'); */; +/* removed: var _$registry_519 = require('../registry'); */; /* removed: var _$plots_510 = require('../plots/plots'); */; -/* removed: var _$lib_422 = require('../lib'); */; + +/* removed: var _$lib_423 = require('../lib'); */; +/* removed: var _$clearGlCanvases_410 = require('../lib/clear_gl_canvases'); */; /* removed: var _$color_299 = require('../components/color'); */; /* removed: var _$drawing_324 = require('../components/drawing'); */; /* removed: var _$titles_392 = require('../components/titles'); */; /* removed: var _$modebar_362 = require('../components/modebar'); */; -/* removed: var _$axes_466 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_475 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_471 = require('../plots/cartesian/constants'); */; + +/* removed: var _$axes_467 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_472 = require('../plots/cartesian/constants'); */; /* removed: var _$alignment_399 = require('../constants/alignment'); */; +/* removed: var _$constraints_474 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_474.enforce; +var cleanAxisConstraints = _$constraints_474.clean; +var __doAutoRange_459 = _$autorange_466.doAutoRange; -_$subroutines_458.layoutStyles = function(gd) { - return _$lib_422.syncOrAsync([_$plots_510.doAutoMargin, _$subroutines_458.lsInner], gd); +_$subroutines_459.layoutStyles = function(gd) { + return _$lib_423.syncOrAsync([_$plots_510.doAutoMargin, _$subroutines_459.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -51605,11 +52455,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_458.lsInner = function(gd) { +_$subroutines_459.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_466.list(gd); + var axList = _$axes_467.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -51688,31 +52538,17 @@ _$subroutines_458.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_423.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -51744,23 +52580,17 @@ _$subroutines_458.lsInner = function(gd) { } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_423.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); _$drawing_324.setTranslate(plotinfo.plot, xa._offset, ya._offset); @@ -51769,16 +52599,16 @@ _$subroutines_458.lsInner = function(gd) { if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } _$drawing_324.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_471.traceLayerClasses.length; i++) { - var layer = _$constants_471.traceLayerClasses[i]; + for(i = 0; i < _$constants_472.traceLayerClasses.length; i++) { + var layer = _$constants_472.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { plotinfo.plot.selectAll('g.' + layer).call(_$drawing_324.setClipUrl, layerClipId); } @@ -51902,8 +52732,8 @@ _$subroutines_458.lsInner = function(gd) { plotinfo.ylines.attr('d', yPath); }); - _$axes_466.makeClipPaths(gd); - _$subroutines_458.drawMainTitle(gd); + _$axes_467.makeClipPaths(gd); + _$subroutines_459.drawMainTitle(gd); _$modebar_362.manage(gd); return gd._promises.length && Promise.all(gd._promises); @@ -51960,7 +52790,7 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_458.drawMainTitle = function(gd) { +_$subroutines_459.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; _$titles_392.draw(gd, 'gtitle', { @@ -51979,7 +52809,7 @@ _$subroutines_458.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_458.doTraceStyle = function(gd) { +_$subroutines_459.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -51989,12 +52819,12 @@ _$subroutines_458.doTraceStyle = function(gd) { } _$plots_510.style(gd); - _$registry_518.getComponentMethod('legend', 'draw')(gd); + _$registry_519.getComponentMethod('legend', 'draw')(gd); return _$plots_510.previousPromises(gd); }; -_$subroutines_458.doColorBars = function(gd) { +_$subroutines_459.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -52002,7 +52832,7 @@ _$subroutines_458.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_518.traceIs(trace, 'contour')) { + if(_$registry_519.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -52011,7 +52841,7 @@ _$subroutines_458.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_518.traceIs(trace, 'markerColorscale')) { + if(_$registry_519.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); @@ -52022,28 +52852,33 @@ _$subroutines_458.doColorBars = function(gd) { }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_458.layoutReplot = function(gd) { +_$subroutines_459.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_518.call('plot', gd, '', layout); + return _$registry_519.call('plot', gd, '', layout); }; -_$subroutines_458.doLegend = function(gd) { - _$registry_518.getComponentMethod('legend', 'draw')(gd); +_$subroutines_459.doLegend = function(gd) { + _$registry_519.getComponentMethod('legend', 'draw')(gd); return _$plots_510.previousPromises(gd); }; -_$subroutines_458.doTicksRelayout = function(gd) { - _$axes_466.doTicks(gd, 'redraw'); - _$subroutines_458.drawMainTitle(gd); +_$subroutines_459.doTicksRelayout = function(gd) { + _$axes_467.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_410(gd); + _$registry_519.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_459.drawMainTitle(gd); return _$plots_510.previousPromises(gd); }; -_$subroutines_458.doModeBar = function(gd) { +_$subroutines_459.doModeBar = function(gd) { var fullLayout = gd._fullLayout; _$modebar_362.manage(gd); - _$initInteractions_475(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; @@ -52053,7 +52888,7 @@ _$subroutines_458.doModeBar = function(gd) { return _$plots_510.previousPromises(gd); }; -_$subroutines_458.doCamera = function(gd) { +_$subroutines_459.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -52065,212 +52900,86 @@ _$subroutines_458.doCamera = function(gd) { } }; -var _$constraints_473 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_473 = _$axis_ids_469.id2name; -/* removed: var _$scaleZoom_483 = require('./scale_zoom'); */; -var __makePadFn_473 = _$autorange_465.makePadFn; - -var ALMOST_EQUAL = _$numerical_403.ALMOST_EQUAL; - -var __FROM_BL_473 = _$alignment_399.FROM_BL; - - -_$constraints_473.enforce = function enforceAxisConstraints(gd) { +_$subroutines_459.drawData = function(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_473(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_519.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_483(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(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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_483(ax, factor); - continue; - } + _$clearGlCanvases_410(gd); - 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 && ax._min.length && ax._max.length) { - /* - * 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_473(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_510.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_519.getComponentMethod('shapes', 'draw')(gd); + _$registry_519.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_510.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_459.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_467.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_459(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_473.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_473[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_459.finalDraw = function(gd) { + _$registry_519.getComponentMethod('shapes', 'draw')(gd); + _$registry_519.getComponentMethod('images', 'draw')(gd); + _$registry_519.getComponentMethod('annotations', 'draw')(gd); + _$registry_519.getComponentMethod('legend', 'draw')(gd); + _$registry_519.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_519.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_519.getComponentMethod('sliders', 'draw')(gd); + _$registry_519.getComponentMethod('updatemenus', 'draw')(gd); +}; var _$micropolar_514 = {}; /** @@ -52282,8 +52991,8 @@ var _$micropolar_514 = {}; */ /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../../../lib'); */; -var __extendDeepAll_514 = _$lib_422.extendDeepAll; +/* removed: var _$lib_423 = require('../../../lib'); */; +var __extendDeepAll_514 = _$lib_423.extendDeepAll; var __MID_SHIFT_514 = _$alignment_399.MID_SHIFT; var µ = _$micropolar_514 = { version: '0.2.2' }; @@ -53771,12 +54480,12 @@ var _$micropolar_manager_515 = {}; 'use strict'; /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../../../lib'); */; +/* removed: var _$lib_423 = require('../../../lib'); */; /* removed: var _$color_299 = require('../../../components/color'); */; /* removed: var _$micropolar_514 = require('./micropolar'); */; /* removed: var _$UndoManager_516 = require('./undo_manager'); */; -var __extendDeepAll_515 = _$lib_422.extendDeepAll; +var __extendDeepAll_515 = _$lib_423.extendDeepAll; var manager = _$micropolar_manager_515 = {}; @@ -53858,7 +54567,7 @@ var Polar = _$legacy_513 = _$micropolar_514; Polar.manager = _$micropolar_manager_515; -var _$plot_api_455 = {}; +var _$plot_api_456 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53875,33 +54584,29 @@ var _$plot_api_455 = {}; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; /* removed: var _$hasHover_173 = require('has-hover'); */; -/* removed: var _$lib_422 = require('../lib'); */; -/* removed: var _$Events_413 = require('../lib/events'); */; -/* removed: var _$queue_436 = require('../lib/queue'); */; +/* removed: var _$lib_423 = require('../lib'); */; +/* removed: var _$Events_414 = require('../lib/events'); */; +/* removed: var _$queue_437 = require('../lib/queue'); */; -/* removed: var _$registry_518 = require('../registry'); */; -/* removed: var _$plot_schema_457 = require('./plot_schema'); */; +/* removed: var _$registry_519 = require('../registry'); */; +/* removed: var _$plot_schema_458 = require('./plot_schema'); */; /* removed: var _$plots_510 = require('../plots/plots'); */; /* removed: var _$legacy_513 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_475 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$axes_466 = require('../plots/cartesian/axes'); */; +/* removed: var _$axes_467 = require('../plots/cartesian/axes'); */; /* removed: var _$drawing_324 = require('../components/drawing'); */; /* removed: var _$color_299 = require('../components/color'); */; +var initInteractions = _$graph_interact_476.initInteractions; /* removed: var _$xmlns_namespaces_405 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_445 = require('../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_446 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_456 = require('./plot_config'); */; -/* removed: var _$manage_arrays_454 = require('./manage_arrays'); */; -/* removed: var _$helpers_452 = require('./helpers'); */; -/* removed: var _$subroutines_458 = require('./subroutines'); */; -/* removed: var _$edit_types_451 = require('./edit_types'); */; +/* removed: var _$plot_config_457 = require('./plot_config'); */; +/* removed: var _$manage_arrays_455 = require('./manage_arrays'); */; +/* removed: var _$helpers_453 = require('./helpers'); */; +/* removed: var _$subroutines_459 = require('./subroutines'); */; +/* removed: var _$edit_types_452 = require('./edit_types'); */; -/* removed: var _$constants_471 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_473 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_473.enforce; -var cleanAxisConstraints = _$constraints_473.clean; -var __doAutoRange_455 = _$autorange_465.doAutoRange; +var AX_NAME_PATTERN = _$constants_472.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -53927,15 +54632,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_455.plot = function(gd, data, layout, config) { +_$plot_api_456.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_422.getGraphDiv(gd); + gd = _$lib_423.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_413.init(gd); + _$Events_414.init(gd); - if(_$lib_422.isPlainObject(data)) { + if(_$lib_423.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -53943,19 +54648,19 @@ _$plot_api_455.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_413.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_414.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_422.isPlotDiv(gd)) { - _$lib_422.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_423.isPlotDiv(gd)) { + _$lib_423.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_455.addFrames(gd, frames); + return _$plot_api_456.addFrames(gd, frames); } } @@ -53974,6 +54679,9 @@ _$plot_api_455.plot = function(gd, data, layout, config) { // so we can share cached text across tabs _$drawing_324.makeTester(); + // clear stashed base url + delete _$drawing_324.baseUrl; + // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all @@ -53985,7 +54693,7 @@ _$plot_api_455.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_452.cleanData(data, gd.data); + _$helpers_453.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -53996,7 +54704,7 @@ _$plot_api_455.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_452.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_453.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -54018,7 +54726,7 @@ _$plot_api_455.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_422.log('Legacy polar charts are deprecated!'); + _$lib_423.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -54039,7 +54747,7 @@ _$plot_api_455.plot = function(gd, data, layout, config) { _$drawing_324.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_466.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_467.saveShowSpikeInitial(gd); // prepare the data and find the autorange @@ -54106,9 +54814,7 @@ _$plot_api_455.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_422.syncOrAsync([ - _$subroutines_458.layoutStyles - ], gd); + return _$plots_510.previousPromises(gd); } // draw anything that can affect margins. @@ -54116,10 +54822,10 @@ _$plot_api_455.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_518.getComponentMethod('legend', 'draw')(gd); - _$registry_518.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_518.getComponentMethod('sliders', 'draw')(gd); - _$registry_518.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_519.getComponentMethod('legend', 'draw')(gd); + _$registry_519.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_519.getComponentMethod('sliders', 'draw')(gd); + _$registry_519.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; @@ -54138,9 +54844,9 @@ _$plot_api_455.plot = function(gd, data, layout, config) { function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_422.syncOrAsync([ + return _$lib_423.syncOrAsync([ marginPushers, - _$subroutines_458.layoutStyles + _$subroutines_459.layoutStyles ], gd); } @@ -54161,7 +54867,7 @@ _$plot_api_455.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_422.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_423.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -54175,113 +54881,31 @@ _$plot_api_455.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_518.getComponentMethod('errorbars', 'calc')(gd); + _$registry_519.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_422.syncOrAsync([ - _$registry_518.getComponentMethod('shapes', 'calcAutorange'), - _$registry_518.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_423.syncOrAsync([ + _$registry_519.getComponentMethod('shapes', 'calcAutorange'), + _$registry_519.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_518.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_519.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_466.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_455(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_459.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_466.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_467.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_466.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_518.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_510.style(gd); - - // show annotations and shapes - _$registry_518.getComponentMethod('shapes', 'draw')(gd); - _$registry_518.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_510.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_510.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_518.getComponentMethod('shapes', 'draw')(gd); - _$registry_518.getComponentMethod('images', 'draw')(gd); - _$registry_518.getComponentMethod('annotations', 'draw')(gd); - _$registry_518.getComponentMethod('legend', 'draw')(gd); - _$registry_518.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_518.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_518.getComponentMethod('sliders', 'draw')(gd); - _$registry_518.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_467.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ @@ -54292,19 +54916,20 @@ _$plot_api_455.plot = function(gd, data, layout, config) { marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_458.layoutStyles); + seq.push(_$subroutines_459.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_475, + _$subroutines_459.drawData, + _$subroutines_459.finalDraw, + initInteractions, + _$plots_510.addLinks, _$plots_510.rehover, _$plots_510.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_422.syncOrAsync(seq, gd); + var plotDone = _$lib_423.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -54313,15 +54938,15 @@ _$plot_api_455.plot = function(gd, data, layout, config) { }); }; -_$plot_api_455.setPlotConfig = function setPlotConfig(obj) { - return _$lib_422.extendFlat(_$plot_config_456, obj); +_$plot_api_456.setPlotConfig = function setPlotConfig(obj) { + return _$lib_423.extendFlat(_$plot_config_457, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_422.error(e); + _$lib_423.error(e); } } @@ -54331,7 +54956,7 @@ function opaqueSetBackground(gd, bgColor) { } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_422.extendDeep({}, _$plot_config_456); + if(!gd._context) gd._context = _$lib_423.extendDeep({}, _$plot_config_457); var context = gd._context; var i, keys, key; @@ -54447,7 +55072,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_445.convertToTspans, gd); + this.call(_$svg_text_utils_446.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -54456,7 +55081,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_422._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_423._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -54475,7 +55100,7 @@ function plotPolar(gd, data, layout) { } var setContenteditable = function() { - this.call(_$svg_text_utils_445.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_446.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -54497,18 +55122,18 @@ function plotPolar(gd, data, layout) { } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_455.redraw = function(gd) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.redraw = function(gd) { + gd = _$lib_423.getGraphDiv(gd); - if(!_$lib_422.isPlotDiv(gd)) { + if(!_$lib_423.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_452.cleanData(gd.data, gd.data); - _$helpers_452.cleanLayout(gd.layout); + _$helpers_453.cleanData(gd.data, gd.data); + _$helpers_453.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_455.plot(gd).then(function() { + return _$plot_api_456.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -54522,14 +55147,14 @@ _$plot_api_455.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_455.newPlot = function(gd, data, layout, config) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.newPlot = function(gd, data, layout, config) { + gd = _$lib_423.getGraphDiv(gd); // remove gl contexts - _$plots_510.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_510.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); _$plots_510.purge(gd); - return _$plot_api_455.plot(gd, data, layout, config); + return _$plot_api_456.plot(gd, data, layout, config); }; /** @@ -54682,12 +55307,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_422.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_423.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_422.isPlainObject(update)) { + if(!_$lib_423.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -54730,7 +55355,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_422.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_423.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -54750,7 +55375,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_422.nestedProperty(trace, key); + prop = _$lib_423.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -54759,10 +55384,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_422.isArrayOrTypedArray(insert)) { + if(!_$lib_423.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_422.isArrayOrTypedArray(target)) { + if(!_$lib_423.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -54857,13 +55482,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_455.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_423.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_422.isTypedArray(target)) { + if(_$lib_423.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -54908,20 +55533,20 @@ _$plot_api_455.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_455.redraw(gd); + var promise = _$plot_api_456.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_436.add(gd, _$plot_api_455.prependTraces, undoArgs, extendTraces, arguments); + _$queue_437.add(gd, _$plot_api_456.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_455.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_423.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_422.isTypedArray(target)) { + if(_$lib_423.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -54965,9 +55590,9 @@ _$plot_api_455.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_455.redraw(gd); + var promise = _$plot_api_456.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_436.add(gd, _$plot_api_455.extendTraces, undoArgs, prependTraces, arguments); + _$queue_437.add(gd, _$plot_api_456.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -54981,11 +55606,11 @@ _$plot_api_455.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_455.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_423.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_455.deleteTraces, + undoFunc = _$plot_api_456.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -55002,10 +55627,10 @@ _$plot_api_455.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_422.extendFlat({}, trace); + return _$lib_423.extendFlat({}, trace); }); - _$helpers_452.cleanData(traces, gd.data); + _$helpers_453.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -55020,8 +55645,8 @@ _$plot_api_455.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_455.redraw(gd); - _$queue_436.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_456.redraw(gd); + _$queue_437.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -55044,10 +55669,10 @@ _$plot_api_455.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_436.startSequence(gd); - _$queue_436.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_455.moveTraces(gd, currentIndices, newIndices); - _$queue_436.stopSequence(gd); + _$queue_437.startSequence(gd); + _$queue_437.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_456.moveTraces(gd, currentIndices, newIndices); + _$queue_437.stopSequence(gd); return promise; }; @@ -55058,11 +55683,11 @@ _$plot_api_455.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_455.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_423.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_455.addTraces, + undoFunc = _$plot_api_456.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -55081,14 +55706,14 @@ _$plot_api_455.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_422.sorterDes); + indices.sort(_$lib_423.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_455.redraw(gd); - _$queue_436.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_456.redraw(gd); + _$queue_437.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -55124,8 +55749,8 @@ _$plot_api_455.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_455.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_423.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -55185,8 +55810,8 @@ _$plot_api_455.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_455.redraw(gd); - _$queue_436.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_456.redraw(gd); + _$queue_437.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -55221,55 +55846,55 @@ _$plot_api_455.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_455.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_422.getGraphDiv(gd); - _$helpers_452.clearPromiseQueue(gd); +_$plot_api_456.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_423.getGraphDiv(gd); + _$helpers_453.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_422.isPlainObject(astr)) { + else if(_$lib_423.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_422.extendFlat({}, astr); + aobj = _$lib_423.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_422.warn('Restyle fail.', astr, val, _traces); + _$lib_423.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_452.coerceTraceIndices(gd, _traces); + var traces = _$helpers_453.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_452.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_453.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_455.plot); + seq.push(_$plot_api_456.plot); } else { seq.push(_$plots_510.previousPromises); _$plots_510.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_458.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_458.doColorBars); + if(flags.style) seq.push(_$subroutines_459.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_459.doColorBars); } seq.push(_$plots_510.rehover); - _$queue_436.add(gd, + _$queue_437.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_422.syncOrAsync(seq, gd); + var plotDone = _$lib_423.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -55292,7 +55917,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_451.traceFlags(); + var flags = _$edit_types_452.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -55305,7 +55930,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_466.id2name(axid); + var axName = _$axes_467.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -55324,13 +55949,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_452.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_453.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_422.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_423.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_422.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_423.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -55347,7 +55972,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_452.hasParent(aobj, ai)) { + if(_$helpers_453.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -55362,7 +55987,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_422.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_423.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -55378,17 +56003,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_422.nestedProperty(cont, ai); + param = _$lib_423.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_457.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_458.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_422.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_423.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -55428,19 +56053,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_422.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_422.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_422.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_423.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_423.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_423.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_422.nestedProperty(cont, 'marker.color') - .set(_$lib_422.nestedProperty(cont, 'marker.colors').get()); + _$lib_423.nestedProperty(cont, 'marker.color') + .set(_$lib_423.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_518.traceIs(cont, 'cartesian')) { - _$lib_422.nestedProperty(cont, 'marker.colors') - .set(_$lib_422.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_519.traceIs(cont, 'cartesian')) { + _$lib_423.nestedProperty(cont, 'marker.colors') + .set(_$lib_423.nestedProperty(cont, 'marker.color').get()); } } @@ -55469,23 +56094,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_452.swapXYData(cont); + _$helpers_453.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(_$plots_510.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_452.manageArrayContainers(param, newVal, undoit); + _$helpers_453.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_422.isArrayOrTypedArray(newVal) || _$lib_422.isArrayOrTypedArray(oldVal)) + _$lib_423.isArrayOrTypedArray(newVal) || _$lib_423.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_451.update(flags, valObject); + else _$edit_types_452.update(flags, valObject); } else { /* @@ -55504,12 +56129,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_466.swap(gd, traces); + _$axes_467.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_422.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_423.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -55524,7 +56149,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_518.traceIs(trace, 'cartesian')) { + if(_$registry_519.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -55541,7 +56166,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_466.list(gd); + var axList = _$axes_467.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -55562,7 +56187,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_422.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_423.extendDeepNoArrays([], [redoit, traces]) }; } @@ -55586,9 +56211,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_455.relayout = function relayout(gd, astr, val) { - gd = _$lib_422.getGraphDiv(gd); - _$helpers_452.clearPromiseQueue(gd); +_$plot_api_456.relayout = function relayout(gd, astr, val) { + gd = _$lib_423.getGraphDiv(gd); + _$helpers_453.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -55597,21 +56222,21 @@ _$plot_api_455.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_422.isPlainObject(astr)) { - aobj = _$lib_422.extendFlat({}, astr); + } else if(_$lib_423.isPlainObject(astr)) { + aobj = _$lib_423.extendFlat({}, astr); } else { - _$lib_422.warn('Relayout fail.', astr, val); + _$lib_423.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_452.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_453.clearAxisAutomargins(gd); // fill in redraw sequence @@ -55621,26 +56246,50 @@ _$plot_api_455.relayout = function relayout(gd, astr, val) { var seq = [_$plots_510.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_458.layoutReplot); + seq.push(_$subroutines_459.layoutReplot); } else if(Object.keys(aobj).length) { _$plots_510.supplyDefaults(gd); - if(flags.legend) seq.push(_$subroutines_458.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_458.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_458.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_458.doModeBar); - if(flags.camera) seq.push(_$subroutines_458.doCamera); + if(flags.legend) seq.push(_$subroutines_459.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_459.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_459.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_459.doTicksRelayout, + _$subroutines_459.drawData, + _$subroutines_459.finalDraw + ); + } + + if(flags.ticks) seq.push(_$subroutines_459.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_459.doModeBar); + if(flags.camera) seq.push(_$subroutines_459.doCamera); } seq.push(_$plots_510.rehover); - _$queue_436.add(gd, + _$queue_437.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_422.syncOrAsync(seq, gd); + var plotDone = _$lib_423.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -55653,7 +56302,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_466.list(gd), + axes = _$axes_467.list(gd), arrayEdits = {}, arrayStr, i, @@ -55676,7 +56325,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_451.layoutFlags(); + var flags = _$edit_types_452.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -55695,9 +56344,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_452.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_453.hasParent(aobj, attr)) return; - var p = _$lib_422.nestedProperty(layout, attr); + var p = _$lib_423.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -55711,18 +56360,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_466.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_467.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_452.hasParent(aobj, ai)) { + if(_$helpers_453.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_422.nestedProperty(layout, ai); + var p = _$lib_423.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -55734,8 +56383,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_422.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_422.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_423.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_423.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -55746,11 +56395,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_457.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_458.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_422.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_423.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -55764,12 +56413,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_422.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_423.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_422.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_422.nestedProperty(fullLayout, ptrunk).get(); + _$lib_423.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_423.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -55777,7 +56426,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_422.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_423.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -55837,8 +56486,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_518.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_518.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_519.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_519.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -55846,18 +56495,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_422.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_423.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_471.AX_NAME_PATTERN)) { - var fullProp = _$lib_422.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_423.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_518.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_518.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_519.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_519.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -55866,12 +56515,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_454.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_455.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_422.nestedProperty(layout, arrayStr); + var componentArray = _$lib_423.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -55881,28 +56530,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_451.update(flags, updateValObject); + else _$edit_types_452.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_454.isAddVal(vi)) { + if(_$manage_arrays_455.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_454.isRemoveVal(vi)) { + else if(_$manage_arrays_455.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_422.warn('unrecognized full object value', aobj); + else _$lib_423.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_451.update(flags, updateValObject); - + else { + _$edit_types_452.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -55931,7 +56581,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_451.update(flags, valObject); + else if(valObject) _$edit_types_452.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -55940,8 +56590,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_454.applyContainerArrayChanges(gd, - _$lib_422.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_455.applyContainerArrayChanges(gd, + _$lib_423.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -55959,7 +56609,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_466.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_467.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -55983,7 +56633,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_422.extendDeep({}, redoit) + eventData: _$lib_423.extendDeep({}, redoit) }; } @@ -56005,9 +56655,9 @@ function updateAutosize(gd) { // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_422.isPlainObject(obj)) return false; + if(!_$lib_423.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_466.getFromId(gd, axRef); + ax = _$axes_467.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -56017,7 +56667,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_466.getFromId(gd, axLetter); + ax = _$axes_467.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -56037,32 +56687,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_455.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_422.getGraphDiv(gd); - _$helpers_452.clearPromiseQueue(gd); +_$plot_api_456.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_423.getGraphDiv(gd); + _$helpers_453.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_422.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_422.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_423.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_423.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_452.coerceTraceIndices(gd, _traces); + var traces = _$helpers_453.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_422.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_423.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_422.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_423.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_452.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_452.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_453.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_453.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -56076,35 +56726,43 @@ _$plot_api_455.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_455.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_456.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_455.plot); + seq.push(_$plot_api_456.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_458.layoutReplot); + seq.push(_$subroutines_459.layoutReplot); } else { seq.push(_$plots_510.previousPromises); _$plots_510.supplyDefaults(gd); - if(restyleFlags.style) seq.push(_$subroutines_458.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_458.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_458.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_458.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_458.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_458.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_458.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_459.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_459.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_459.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_459.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_459.doAutoRangeAndConstraints, + _$subroutines_459.doTicksRelayout, + _$subroutines_459.drawData, + _$subroutines_459.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_459.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_459.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_459.doCamera); } seq.push(_$plots_510.rehover); - _$queue_436.add(gd, + _$queue_437.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_422.syncOrAsync(seq, gd); + var plotDone = _$lib_423.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -56140,23 +56798,23 @@ _$plot_api_455.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_455.react = function(gd, data, layout, config) { +_$plot_api_456.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_455.addFrames(gd, frames); } + function addFrames() { return _$plot_api_456.addFrames(gd, frames); } - gd = _$lib_422.getGraphDiv(gd); + gd = _$lib_423.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_422.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_455.newPlot(gd, data, layout, config); + if(!_$lib_423.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_456.newPlot(gd, data, layout, config); } else { - if(_$lib_422.isPlainObject(data)) { + if(_$lib_423.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -56168,16 +56826,16 @@ _$plot_api_455.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_422.extendDeep({}, gd._context); + var oldConfig = _$lib_423.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_452.cleanData(gd.data, []); + _$helpers_453.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_452.cleanLayout(gd.layout); + _$helpers_453.cleanLayout(gd.layout); _$plots_510.supplyDefaults(gd); @@ -56201,7 +56859,7 @@ _$plot_api_455.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_452.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_453.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -56217,21 +56875,21 @@ _$plot_api_455.react = function(gd, data, layout, config) { if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_455.plot); + seq.push(_$plot_api_456.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_518.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_422.noop) { + var drawOne = _$registry_519.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_423.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_518.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_422.noop) { + var draw = _$registry_519.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_423.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -56240,18 +56898,26 @@ _$plot_api_455.react = function(gd, data, layout, config) { } seq.push(_$plots_510.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_458.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_458.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_458.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_458.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_458.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_458.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_458.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_459.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_459.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_459.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_459.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_459.doAutoRangeAndConstraints, + _$subroutines_459.doTicksRelayout, + _$subroutines_459.drawData, + _$subroutines_459.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_459.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_459.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_459.doCamera); } seq.push(_$plots_510.rehover); - plotDone = _$lib_422.syncOrAsync(seq, gd); + plotDone = _$lib_423.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -56274,12 +56940,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_451.traceFlags(); + var flags = _$edit_types_452.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_457.getTraceValObject(trace, parts); + return _$plot_schema_458.getTraceValObject(trace, parts); } var diffOpts = { @@ -56289,11 +56955,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_466.getFromId(gd, trace.xaxis).autorange || - _$axes_466.getFromId(gd, trace.yaxis).autorange + _$axes_467.getFromId(gd, trace.xaxis).autorange || + _$axes_467.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -56306,11 +56978,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_451.layoutFlags(); + var flags = _$edit_types_452.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_457.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_458.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -56349,10 +57021,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_422.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_423.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_451.update(flags, valObject); + _$edit_types_452.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -56432,7 +57104,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_422.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_423.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -56444,7 +57116,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_422.isPlainObject(oldVal)) { + else if(!valType && _$lib_423.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -56498,7 +57170,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_422.isPlainObject(oldVal) && _$lib_422.isPlainObject(newVal)) { + if(_$lib_423.isPlainObject(oldVal) && _$lib_423.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -56509,7 +57181,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_422.isPlainObject(oldVal[i]) && _$lib_422.isPlainObject(newVal[i])) { + if(_$lib_423.isPlainObject(oldVal[i]) && _$lib_423.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -56554,10 +57226,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_455.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_423.getGraphDiv(gd); - if(!_$lib_422.isPlotDiv(gd)) { + if(!_$lib_423.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -56731,7 +57403,7 @@ _$plot_api_455.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts _$plots_510.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_452.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_453.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -56801,13 +57473,13 @@ _$plot_api_455.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_422.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_423.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_422.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_423.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -56836,10 +57508,10 @@ _$plot_api_455.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_422.isPlainObject(frameOrName)) { + } else if(_$lib_423.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_422.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_423.extendFlat({}, frameOrName)) }); } } @@ -56849,7 +57521,7 @@ _$plot_api_455.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_422.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_423.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -56918,14 +57590,14 @@ _$plot_api_455.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_455.addFrames = function(gd, frameList, indices) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.addFrames = function(gd, frameList, indices) { + gd = _$lib_423.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_422.isPlotDiv(gd)) { + if(!_$lib_423.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -56952,7 +57624,7 @@ _$plot_api_455.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_422.isPlainObject(frameList[i])) continue; + if(!_$lib_423.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -56964,14 +57636,14 @@ _$plot_api_455.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_422.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_423.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_422.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_423.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -57000,7 +57672,7 @@ _$plot_api_455.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_422.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_423.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -57033,7 +57705,7 @@ _$plot_api_455.addFrames = function(gd, frameList, indices) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_436) _$queue_436.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_437) _$queue_437.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_510.modifyFrames(gd, ops); }; @@ -57047,10 +57719,10 @@ _$plot_api_455.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_455.deleteFrames = function(gd, frameList) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.deleteFrames = function(gd, frameList) { + gd = _$lib_423.getGraphDiv(gd); - if(!_$lib_422.isPlotDiv(gd)) { + if(!_$lib_423.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -57080,7 +57752,7 @@ _$plot_api_455.deleteFrames = function(gd, frameList) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_436) _$queue_436.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_437) _$queue_437.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_510.modifyFrames(gd, ops); }; @@ -57091,20 +57763,21 @@ _$plot_api_455.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_455.purge = function purge(gd) { - gd = _$lib_422.getGraphDiv(gd); +_$plot_api_456.purge = function purge(gd) { + gd = _$lib_423.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_510.cleanPlot([], {}, fullData, fullLayout); + _$plots_510.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties _$plots_510.purge(gd); // purge event emitter methods - _$Events_413.purge(gd); + _$Events_414.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -57162,7 +57835,7 @@ function makePlotFramework(gd) { _$d3_79.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_422.randstr(otherUids); + fullLayout._uid = _$lib_423.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') @@ -57238,7 +57911,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_522 = {}; +var _$helpers_523 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -57250,7 +57923,7 @@ var _$helpers_522 = {}; 'use strict'; -_$helpers_522.getDelay = function(fullLayout) { +_$helpers_523.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -57260,7 +57933,7 @@ _$helpers_522.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_522.getRedrawFunc = function(gd) { +_$helpers_523.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -57285,11 +57958,11 @@ _$helpers_522.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_422 = require('../lib'); */; -var __EventEmitter_524 = _$EventEmitter_87.EventEmitter; +/* removed: var _$lib_423 = require('../lib'); */; +var __EventEmitter_525 = _$EventEmitter_87.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_524(); + var ev = opts.emitter || new __EventEmitter_525(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -57297,7 +57970,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_422.isIE() && format !== 'svg') { + if(_$lib_423.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -57388,7 +58061,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_524 = svgToImg; +var _$svgToImg_525 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -57403,7 +58076,7 @@ var _$svgToImg_524 = svgToImg; /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$lib_423 = require('../lib'); */; /* removed: var _$drawing_324 = require('../components/drawing'); */; /* removed: var _$color_299 = require('../components/color'); */; @@ -57428,7 +58101,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_526 = function toSVG(gd, format, scale) { +var _$toSVG_527 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -57551,7 +58224,7 @@ var _$toSVG_526 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_422.isIE()) { + if(_$lib_423.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -57576,14 +58249,14 @@ var _$toSVG_526 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_455 = require('./plot_api'); */; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$plot_api_456 = require('./plot_api'); */; +/* removed: var _$lib_423 = require('../lib'); */; -/* removed: var _$helpers_522 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_526 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_524 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_523 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_527 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_525 = require('../snapshot/svgtoimg'); */; -var __attrs_459 = { +var __attrs_460 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -57636,19 +58309,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_422.isPlainObject(gd)) { + if(_$lib_423.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_422.getGraphDiv(gd); - data = _$lib_422.extendDeep([], gd.data); - layout = _$lib_422.extendDeep({}, gd.layout); + gd = _$lib_423.getGraphDiv(gd); + data = _$lib_423.extendDeep([], gd.data); + layout = _$lib_423.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_422.validate(opts[attr], __attrs_459[attr]); + return !(attr in opts) || _$lib_423.validate(opts[attr], __attrs_460[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -57662,7 +58335,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_422.coerce(opts, fullOpts, __attrs_459, attr, dflt); + return _$lib_423.coerce(opts, fullOpts, __attrs_460, attr, dflt); } var format = coerce('format'); @@ -57679,31 +58352,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_422.extendFlat({}, layout); + var layoutImage = _$lib_423.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_422.extendFlat({}, config, { + var configImage = _$lib_423.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_522.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_523.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_522.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_523.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_526(clonedGd, format, scale); + var svg = _$toSVG_527(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_455.purge(clonedGd); + _$plot_api_456.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -57715,9 +58388,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_422.randstr(); + canvas.id = _$lib_423.randstr(); - _$svgToImg_524({ + _$svgToImg_525({ format: format, width: width, height: height, @@ -57744,7 +58417,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_455.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_456.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -57753,7 +58426,7 @@ function toImage(gd, opts) { }); } -var _$toImage_459 = toImage; +var _$toImage_460 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -57765,14 +58438,14 @@ var _$toImage_459 = toImage; 'use strict'; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$lib_423 = require('../lib'); */; /* removed: var _$plots_510 = require('../plots/plots'); */; -/* removed: var _$plot_schema_457 = require('./plot_schema'); */; -/* removed: var _$plot_config_456 = require('./plot_config'); */; +/* removed: var _$plot_schema_458 = require('./plot_schema'); */; +/* removed: var _$plot_config_457 = require('./plot_config'); */; -var __isPlainObject_460 = _$lib_422.isPlainObject; -var __isArray_460 = Array.isArray; -var __isArrayOrTypedArray_460 = _$lib_422.isArrayOrTypedArray; +var __isPlainObject_461 = _$lib_423.isPlainObject; +var __isArray_461 = Array.isArray; +var __isArrayOrTypedArray_461 = _$lib_423.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -57795,15 +58468,15 @@ var __isArrayOrTypedArray_460 = _$lib_422.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_460 = function valiate(data, layout) { - var schema = _$plot_schema_457.get(); +var _$valiate_461 = function valiate(data, layout) { + var schema = _$plot_schema_458.get(); var errorList = []; - var gd = {_context: _$lib_422.extendFlat({}, _$plot_config_456)}; + var gd = {_context: _$lib_423.extendFlat({}, _$plot_config_457)}; var dataIn, layoutIn; - if(__isArray_460(data)) { - gd.data = _$lib_422.extendDeep([], data); + if(__isArray_461(data)) { + gd.data = _$lib_423.extendDeep([], data); dataIn = data; } else { @@ -57812,8 +58485,8 @@ var _$valiate_460 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_460(layout)) { - gd.layout = _$lib_422.extendDeep({}, layout); + if(__isPlainObject_461(layout)) { + gd.layout = _$lib_423.extendDeep({}, layout); layoutIn = layout; } else { @@ -57837,7 +58510,7 @@ var _$valiate_460 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_460(traceIn)) { + if(!__isPlainObject_461(traceIn)) { errorList.push(format('object', base)); continue; } @@ -57857,13 +58530,13 @@ var _$valiate_460 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_460(traceIn, traceOut, traceSchema, errorList, base); + __crawl_461(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_460(transformsIn)) { + if(!__isArray_461(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -57873,7 +58546,7 @@ var _$valiate_460 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_460(transformsIn[j])) { + if(!__isPlainObject_461(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -57888,7 +58561,7 @@ var _$valiate_460 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_460(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_461(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -57896,13 +58569,13 @@ var _$valiate_460 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_460(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_461(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_460(objIn, objOut, schema, list, base, path) { +function __crawl_461(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -57927,10 +58600,10 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_460(valIn) && __isPlainObject_460(valOut)) { - __crawl_460(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_461(valIn) && __isPlainObject_461(valOut)) { + __crawl_461(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_460(valIn)) { + else if(isInfoArray && __isArray_461(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -57940,7 +58613,7 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_460(valIn[n])) { + if(__isArray_461(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -57949,7 +58622,7 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_422.validate(valInPart, item)) { + if(!_$lib_423.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -57967,7 +58640,7 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_422.validate(valInPart, item)) { + if(!_$lib_423.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -57976,7 +58649,7 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_460(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_461(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -57990,9 +58663,9 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_460(valIn[_index]) && __isPlainObject_460(valOut[j])) { + if(__isPlainObject_461(valIn[_index]) && __isPlainObject_461(valOut[j])) { indexList.push(_index); - __crawl_460(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_461(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -58001,7 +58674,7 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_460(valIn[j])) { + if(!__isPlainObject_461(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -58009,16 +58682,16 @@ function __crawl_460(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_460(valIn) && __isPlainObject_460(valOut)) { + else if(!__isPlainObject_461(valIn) && __isPlainObject_461(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_460(valIn) && __isArrayOrTypedArray_460(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_461(valIn) && __isArrayOrTypedArray_461(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_422.validate(valIn, nestedSchema)) { + else if(!_$lib_423.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -58038,7 +58711,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_422.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_423.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -58070,7 +58743,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_460(valIn) ? 'container' : 'key'; + var target = __isPlainObject_461(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -58096,7 +58769,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_460(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_461(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -58109,7 +58782,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_460(base)) { + if(__isArray_461(base)) { container = base[0]; trace = base[1]; } @@ -58122,7 +58795,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_422.log(msg); + _$lib_423.log(msg); return { code: code, @@ -58152,7 +58825,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_422.counterRegex('([a-z]+)'); +var idRegex = _$lib_423.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -58164,7 +58837,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_460(path)) return String(path); + if(!__isArray_461(path)) return String(path); var astr = ''; @@ -58253,7 +58926,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_521 = fileSaver; +var _$fileSaver_522 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -58266,9 +58939,9 @@ var _$fileSaver_521 = fileSaver; 'use strict'; -/* removed: var _$toImage_459 = require('../plot_api/to_image'); */; -/* removed: var _$lib_422 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_521 = require('./filesaver'); */; +/* removed: var _$toImage_460 = require('../plot_api/to_image'); */; +/* removed: var _$lib_423 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_522 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -58296,19 +58969,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_422.isIE() && opts.format !== 'svg') { + if(_$lib_423.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_459(gd, opts); + var promise = _$toImage_460(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_521(result, filename); + return _$fileSaver_522(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -58318,9 +58991,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_520 = downloadImage; +var _$downloadImage_521 = downloadImage; -var _$plot_api_453 = {}; +var _$plot_api_454 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -58331,29 +59004,29 @@ var _$plot_api_453 = {}; 'use strict'; -/* removed: var _$plot_api_455 = require('./plot_api'); */; - -_$plot_api_453.plot = _$plot_api_455.plot; -_$plot_api_453.newPlot = _$plot_api_455.newPlot; -_$plot_api_453.restyle = _$plot_api_455.restyle; -_$plot_api_453.relayout = _$plot_api_455.relayout; -_$plot_api_453.redraw = _$plot_api_455.redraw; -_$plot_api_453.update = _$plot_api_455.update; -_$plot_api_453.react = _$plot_api_455.react; -_$plot_api_453.extendTraces = _$plot_api_455.extendTraces; -_$plot_api_453.prependTraces = _$plot_api_455.prependTraces; -_$plot_api_453.addTraces = _$plot_api_455.addTraces; -_$plot_api_453.deleteTraces = _$plot_api_455.deleteTraces; -_$plot_api_453.moveTraces = _$plot_api_455.moveTraces; -_$plot_api_453.purge = _$plot_api_455.purge; -_$plot_api_453.addFrames = _$plot_api_455.addFrames; -_$plot_api_453.deleteFrames = _$plot_api_455.deleteFrames; -_$plot_api_453.animate = _$plot_api_455.animate; -_$plot_api_453.setPlotConfig = _$plot_api_455.setPlotConfig; - -_$plot_api_453.toImage = _$toImage_459; -_$plot_api_453.validate = _$valiate_460; -_$plot_api_453.downloadImage = _$downloadImage_520; +/* removed: var _$plot_api_456 = require('./plot_api'); */; + +_$plot_api_454.plot = _$plot_api_456.plot; +_$plot_api_454.newPlot = _$plot_api_456.newPlot; +_$plot_api_454.restyle = _$plot_api_456.restyle; +_$plot_api_454.relayout = _$plot_api_456.relayout; +_$plot_api_454.redraw = _$plot_api_456.redraw; +_$plot_api_454.update = _$plot_api_456.update; +_$plot_api_454.react = _$plot_api_456.react; +_$plot_api_454.extendTraces = _$plot_api_456.extendTraces; +_$plot_api_454.prependTraces = _$plot_api_456.prependTraces; +_$plot_api_454.addTraces = _$plot_api_456.addTraces; +_$plot_api_454.deleteTraces = _$plot_api_456.deleteTraces; +_$plot_api_454.moveTraces = _$plot_api_456.moveTraces; +_$plot_api_454.purge = _$plot_api_456.purge; +_$plot_api_454.addFrames = _$plot_api_456.addFrames; +_$plot_api_454.deleteFrames = _$plot_api_456.deleteFrames; +_$plot_api_454.animate = _$plot_api_456.animate; +_$plot_api_454.setPlotConfig = _$plot_api_456.setPlotConfig; + +_$plot_api_454.toImage = _$toImage_460; +_$plot_api_454.validate = _$valiate_461; +_$plot_api_454.downloadImage = _$downloadImage_521; /** * Copyright 2012-2018, Plotly, Inc. @@ -58366,10 +59039,10 @@ _$plot_api_453.downloadImage = _$downloadImage_520; 'use strict'; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$lib_423 = require('../lib'); */; -var __extendFlat_519 = _$lib_422.extendFlat; -var extendDeep = _$lib_422.extendDeep; +var __extendFlat_520 = _$lib_423.extendFlat; +var extendDeep = _$lib_423.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -58414,7 +59087,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_519 = function clonePlot(graphObj, options) { +var _$clonePlot_520 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -58487,9 +59160,9 @@ var _$clonePlot_519 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_519(scene.xaxis, axesImageOverride); - __extendFlat_519(scene.yaxis, axesImageOverride); - __extendFlat_519(scene.zaxis, axesImageOverride); + __extendFlat_520(scene.xaxis, axesImageOverride); + __extendFlat_520(scene.yaxis, axesImageOverride); + __extendFlat_520(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -58538,27 +59211,27 @@ var _$clonePlot_519 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_525 = _$EventEmitter_87.EventEmitter; +var __EventEmitter_526 = _$EventEmitter_87.EventEmitter; -/* removed: var _$registry_518 = require('../registry'); */; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$registry_519 = require('../registry'); */; +/* removed: var _$lib_423 = require('../lib'); */; -/* removed: var _$helpers_522 = require('./helpers'); */; -/* removed: var _$clonePlot_519 = require('./cloneplot'); */; -/* removed: var _$toSVG_526 = require('./tosvg'); */; -/* removed: var _$svgToImg_524 = require('./svgtoimg'); */; +/* removed: var _$helpers_523 = require('./helpers'); */; +/* removed: var _$clonePlot_520 = require('./cloneplot'); */; +/* removed: var _$toSVG_527 = require('./tosvg'); */; +/* removed: var _$svgToImg_525 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_525(gd, opts) { +function __toImage_526(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_525(); + var ev = new __EventEmitter_526(); - var clone = _$clonePlot_519(gd, {format: 'png'}); + var clone = _$clonePlot_520(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -58567,15 +59240,15 @@ function __toImage_525(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_522.getDelay(clonedGd._fullLayout); + var delay = _$helpers_523.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_526(clonedGd); + var svg = _$toSVG_527(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_422.randstr(); + canvas.id = _$lib_423.randstr(); - ev = _$svgToImg_524({ + ev = _$svgToImg_525({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -58591,9 +59264,9 @@ function __toImage_525(gd, opts) { }, delay); } - var redrawFunc = _$helpers_522.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_523.getRedrawFunc(clonedGd); - _$registry_518.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_519.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -58604,7 +59277,7 @@ function __toImage_525(gd, opts) { return ev; } -var _$toImage_525 = __toImage_525; +var _$toImage_526 = __toImage_526; /** * Copyright 2012-2018, Plotly, Inc. @@ -58617,19 +59290,19 @@ var _$toImage_525 = __toImage_525; 'use strict'; -/* removed: var _$helpers_522 = require('./helpers'); */; +/* removed: var _$helpers_523 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_522.getDelay, - getRedrawFunc: _$helpers_522.getRedrawFunc, - clone: _$clonePlot_519, - toSVG: _$toSVG_526, - svgToImg: _$svgToImg_524, - toImage: _$toImage_525, - downloadImage: _$downloadImage_520 + getDelay: _$helpers_523.getDelay, + getRedrawFunc: _$helpers_523.getRedrawFunc, + clone: _$clonePlot_520, + toSVG: _$toSVG_527, + svgToImg: _$svgToImg_525, + toImage: _$toImage_526, + downloadImage: _$downloadImage_521 }; -var _$Snapshot_523 = Snapshot; +var _$Snapshot_524 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -58642,42 +59315,42 @@ var _$Snapshot_523 = Snapshot; 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_535 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_536 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_422.mergeArray(trace.text, cd, 'tx'); - _$lib_422.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_422.mergeArray(trace.customdata, cd, 'data'); - _$lib_422.mergeArray(trace.textposition, cd, 'tp'); + _$lib_423.mergeArray(trace.text, cd, 'tx'); + _$lib_423.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_423.mergeArray(trace.customdata, cd, 'data'); + _$lib_423.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_422.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_422.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_422.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_423.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_423.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_423.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_422.mergeArray(marker.size, cd, 'ms'); - _$lib_422.mergeArray(marker.opacity, cd, 'mo'); - _$lib_422.mergeArray(marker.symbol, cd, 'mx'); - _$lib_422.mergeArray(marker.color, cd, 'mc'); + _$lib_423.mergeArray(marker.size, cd, 'ms'); + _$lib_423.mergeArray(marker.opacity, cd, 'mo'); + _$lib_423.mergeArray(marker.symbol, cd, 'mx'); + _$lib_423.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_422.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_422.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_423.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_423.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_422.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_422.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_423.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_423.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -58692,11 +59365,11 @@ var _$arraysToCalcdata_535 = function arraysToCalcdata(cd, trace) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -var _$calcSelection_538 = function calcSelection(cd, trace) { - if(_$lib_422.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_422.tagSelected(cd, trace); +var _$calcSelection_539 = function calcSelection(cd, trace) { + if(_$lib_423.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_423.tagSelected(cd, trace); } }; @@ -58714,15 +59387,15 @@ var _$calcSelection_538 = function calcSelection(cd, trace) { /* removed: var _$hasColorscale_313 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$calc_306 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_558 = require('./subtypes'); */; +/* removed: var _$subtypes_559 = require('./subtypes'); */; -var _$calcMarkerColorscale_541 = function calcMarkerColorscale(trace) { - if(_$subtypes_558.hasLines(trace) && _$hasColorscale_313(trace, 'line')) { +var _$calcMarkerColorscale_542 = function calcMarkerColorscale(trace) { + if(_$subtypes_559.hasLines(trace) && _$hasColorscale_313(trace, 'line')) { _$calc_306(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_558.hasMarkers(trace)) { + if(_$subtypes_559.hasMarkers(trace)) { if(_$hasColorscale_313(trace, 'marker')) { _$calc_306(trace, trace.marker.color, 'marker', 'c'); } @@ -58743,19 +59416,19 @@ var _$calcMarkerColorscale_541 = function calcMarkerColorscale(trace) { 'use strict'; /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_537 = _$lib_422.isArrayOrTypedArray; +var __isArrayOrTypedArray_538 = _$lib_423.isArrayOrTypedArray; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; -var __BADNUM_537 = _$numerical_403.BADNUM; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; +var __BADNUM_538 = _$numerical_403.BADNUM; -/* removed: var _$subtypes_558 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_541 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_535 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_538 = require('./calc_selection'); */; +/* removed: var _$subtypes_559 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_542 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_536 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_539 = require('./calc_selection'); */; -function __calc_537(gd, trace) { - var xa = _$axes_466.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_466.getFromId(gd, trace.yaxis || 'y'); +function __calc_538(gd, trace) { + var xa = _$axes_467.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_467.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -58767,16 +59440,16 @@ function __calc_537(gd, trace) { for(var i = 0; i < serieslen; i++) { cd[i] = (_$fastIsnumeric_89(x[i]) && _$fastIsnumeric_89(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_537, y: __BADNUM_537}; + {x: __BADNUM_538, y: __BADNUM_538}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_535(cd, trace); - _$calcMarkerColorscale_541(trace); - _$calcSelection_538(cd, trace); + _$arraysToCalcdata_536(cd, trace); + _$calcMarkerColorscale_542(trace); + _$calcSelection_539(cd, trace); gd.firstscatter = false; return cd; @@ -58809,9 +59482,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_558.hasMarkers(trace) && !_$subtypes_558.hasText(trace)) + (!_$subtypes_559.hasMarkers(trace) && !_$subtypes_559.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -58830,12 +59503,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_466.expand(xa, x, xOptions); - _$axes_466.expand(ya, y, yOptions); + _$axes_467.expand(xa, x, xOptions); + _$axes_467.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_558.hasMarkers(trace)) return; + if(!_$subtypes_559.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -58853,10 +59526,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_537(marker.size)) { + if(__isArrayOrTypedArray_538(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_466.setConvert(ax); + _$axes_467.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -58871,8 +59544,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_537 = { - calc: __calc_537, +var _$calc_538 = { + calc: __calc_538, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -58890,7 +59563,7 @@ var _$calc_537 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_539 = function cleanData(fullData) { +var _$cleanData_540 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -58957,21 +59630,21 @@ var _$constants_301 = { /* removed: var _$tinycolor_264 = require('tinycolor2'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; /* removed: var _$dragelement_321 = require('../dragelement'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -var __extendFlat_303 = _$extend_414.extendFlat; -/* removed: var _$setCursor_441 = require('../../lib/setcursor'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +var __extendFlat_303 = _$extend_415.extendFlat; +/* removed: var _$setCursor_442 = require('../../lib/setcursor'); */; /* removed: var _$drawing_324 = require('../drawing'); */; /* removed: var _$color_299 = require('../color'); */; /* removed: var _$titles_392 = require('../titles'); */; -/* removed: var _$svg_text_utils_445 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_446 = require('../../lib/svg_text_utils'); */; var __LINE_SPACING_303 = _$alignment_399.LINE_SPACING; -/* removed: var _$handleAxisDefaults_468 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handleAxisDefaults_469 = require('../../plots/cartesian/axis_defaults'); */; /* removed: var _$handlePositionDefaults_482 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_478 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$layout_attributes_479 = require('../../plots/cartesian/layout_attributes'); */; /* removed: var _$attributes_300 = require('./attributes'); */; var cn = _$constants_301.cn; @@ -59135,11 +59808,11 @@ var _$draw_303 = function draw(gd, id) { // Coerce w.r.t. Axes layoutAttributes: // re-use axes.js logic without updating _fullData function coerce(attr, dflt) { - return _$lib_422.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_478, attr, dflt); + return _$lib_423.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_479, attr, dflt); } // Prepare the Plotly axis object - _$handleAxisDefaults_468(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handleAxisDefaults_469(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); _$handlePositionDefaults_482(cbAxisIn, cbAxisOut, coerce, axisOptions); // position can't go in through supplyDefaults @@ -59161,14 +59834,14 @@ var _$draw_303 = function draw(gd, id) { cbAxisOut.tick0 = opts.levels.start; var dtick = opts.levels.size; // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_422.constrain( + var autoNtick = _$lib_423.constrain( (yBottomPx - yTopPx) / 50, 4, 15) + 1, dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick); if(dtFactor > 1) { var dtexp = Math.pow(10, Math.floor( Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_422.roundUp(dtFactor / dtexp, [2, 5, 10]); + dtick *= dtexp * _$lib_423.roundUp(dtFactor / dtexp, [2, 5, 10]); // if the contours are at round multiples, reset tick0 // so they're still at round multiples. Otherwise, // keep the first label on the first contour level @@ -59189,20 +59862,21 @@ var _$draw_303 = function draw(gd, id) { cbAxisOut.setScale(); // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_79.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); + var container = _$lib_423.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_79.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); + container.attr('transform', 'translate(' + Math.round(gs.l) + ',' + Math.round(gs.t) + ')'); // TODO: this opposite transform is a hack until we make it @@ -59273,7 +59947,7 @@ var _$draw_303 = function draw(gd, id) { } else { cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_445.lineCount(titleText); + var nlines = _$svg_text_utils_446.lineCount(titleText); titleTrans[1] += (1 - nlines) * lineSize; } @@ -59359,9 +60033,9 @@ var _$draw_303 = function draw(gd, id) { // so we don't need such complicated logic in Titles.draw // if title is on the top or bottom, we've already drawn it // this title call only handles side=right - return _$lib_422.syncOrAsync([ + return _$lib_423.syncOrAsync([ function() { - return _$axes_466.doTicks(gd, cbAxisOut, true); + return _$axes_467.doTicks(gd, cbAxisOut, true); }, function() { if(['top', 'bottom'].indexOf(opts.titleside) === -1) { @@ -59392,7 +60066,7 @@ var _$draw_303 = function draw(gd, id) { function drawTitle(titleClass, titleOpts) { var trace = getTrace(), propName; - if(_$registry_518.traceIs(trace, 'markerColorscale')) { + if(_$registry_519.traceIs(trace, 'markerColorscale')) { propName = 'marker.colorbar.title'; } else propName = 'colorbar.title'; @@ -59492,7 +60166,7 @@ var _$draw_303 = function draw(gd, id) { }); } - var cbDone = _$lib_422.syncOrAsync([ + var cbDone = _$lib_423.syncOrAsync([ _$plots_510.previousPromises, drawAxis, _$plots_510.previousPromises, @@ -59512,7 +60186,7 @@ var _$draw_303 = function draw(gd, id) { gd: gd, prepFn: function() { t0 = container.attr('transform'); - _$setCursor_441(container); + _$setCursor_442(container); }, moveFn: function(dx, dy) { container.attr('transform', @@ -59525,13 +60199,13 @@ var _$draw_303 = function draw(gd, id) { var csr = _$dragelement_321.getCursor(xf, yf, opts.xanchor, opts.yanchor); - _$setCursor_441(container, csr); + _$setCursor_442(container, csr); }, doneFn: function() { - _$setCursor_441(container); + _$setCursor_442(container); if(xf !== undefined && yf !== undefined) { - _$registry_518.call('restyle', + _$registry_519.call('restyle', gd, {'colorbar.x': xf, 'colorbar.y': yf}, getTrace().index @@ -59561,8 +60235,8 @@ var _$draw_303 = function draw(gd, id) { // setter - for multi-part properties, // set only the parts that are provided - opts[name] = _$lib_422.isPlainObject(opts[name]) ? - _$lib_422.extendFlat(opts[name], v) : + opts[name] = _$lib_423.isPlainObject(opts[name]) ? + _$lib_423.extendFlat(opts[name], v) : v; return component; @@ -59599,13 +60273,13 @@ var _$draw_303 = function draw(gd, id) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; /* removed: var _$colorscale_314 = require('../../components/colorscale'); */; /* removed: var _$draw_303 = require('../../components/colorbar/draw'); */; -var _$colorbar_540 = function colorbar(gd, cd) { +var _$colorbar_541 = function colorbar(gd, cd) { var trace = cd[0].trace, marker = trace.marker, cbId = 'cb' + trace.uid; @@ -59623,8 +60297,8 @@ var _$colorbar_540 = function colorbar(gd, cd) { cmin = marker.cmin, cmax = marker.cmax; - if(!_$fastIsnumeric_89(cmin)) cmin = _$lib_422.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_89(cmax)) cmax = _$lib_422.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_89(cmin)) cmin = _$lib_423.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_89(cmax)) cmax = _$lib_423.aggNums(Math.max, null, vals); var cb = cd[0].t.cb = _$draw_303(gd, cbId); var sclFunc = _$colorscale_314.makeColorScaleFunc( @@ -59653,9 +60327,9 @@ var _$colorbar_540 = function colorbar(gd, cd) { 'use strict'; /* removed: var _$color_299 = require('../../components/color'); */; -var __isArrayOrTypedArray_545 = _$lib_422.isArrayOrTypedArray; +var __isArrayOrTypedArray_546 = _$lib_423.isArrayOrTypedArray; -var _$fillColorDefaults_545 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_546 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -59663,10 +60337,10 @@ var _$fillColorDefaults_545 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_545(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_546(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_545(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_546(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } @@ -59688,11 +60362,11 @@ var _$fillColorDefaults_545 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_549 = _$lib_422.isArrayOrTypedArray; +var __isArrayOrTypedArray_550 = _$lib_423.isArrayOrTypedArray; /* removed: var _$hasColorscale_313 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_309 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_549 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_550 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); @@ -59701,7 +60375,7 @@ var _$lineDefaults_549 = function lineDefaults(traceIn, traceOut, defaultColor, _$colorScaleDefaults_309(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_549(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_550(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -59722,7 +60396,7 @@ var _$lineDefaults_549 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_551 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_552 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -59742,7 +60416,7 @@ var _$handleLineShapeDefaults_551 = function handleLineShapeDefaults(traceIn, tr /* removed: var _$hasColorscale_313 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_309 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_558 = require('./subtypes'); */; +/* removed: var _$subtypes_559 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -59750,8 +60424,8 @@ var _$handleLineShapeDefaults_551 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_554 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_558.isBubble(traceIn), +var _$markerDefaults_555 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_559.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -59820,17 +60494,17 @@ var _$markerDefaults_554 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_559 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_560 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_422.coerceFont(coerce, 'textfont', layout.font); + _$lib_423.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -59849,15 +60523,15 @@ var _$text_defaults_559 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; -var _$handleXYDefaults_560 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { +var _$handleXYDefaults_561 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { var len, x = coerce('x'), y = coerce('y'); - var handleCalendarDefaults = _$registry_518.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_519.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); if(x) { @@ -59893,27 +60567,27 @@ var _$handleXYDefaults_560 = function handleXYDefaults(traceIn, traceOut, layout 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; -/* removed: var _$attributes_536 = require('./attributes'); */; -/* removed: var _$constants_542 = require('./constants'); */; -/* removed: var _$subtypes_558 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_560 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_554 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_549 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_551 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_559 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_545 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_537 = require('./attributes'); */; +/* removed: var _$constants_543 = require('./constants'); */; +/* removed: var _$subtypes_559 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_561 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_555 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_550 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_552 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_560 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_546 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_543 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_544 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_422.coerce(traceIn, traceOut, _$attributes_536, attr, dflt); + return _$lib_423.coerce(traceIn, traceOut, _$attributes_537, attr, dflt); } - var len = _$handleXYDefaults_560(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_561(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_542.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_543.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -59923,24 +60597,24 @@ var _$supplyDefaults_543 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_558.hasLines(traceOut)) { - _$lineDefaults_549(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_551(traceIn, traceOut, coerce); + if(_$subtypes_559.hasLines(traceOut)) { + _$lineDefaults_550(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_552(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_558.hasMarkers(traceOut)) { - _$markerDefaults_554(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_559.hasMarkers(traceOut)) { + _$markerDefaults_555(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_558.hasText(traceOut)) { - _$text_defaults_559(traceIn, traceOut, layout, coerce); + if(_$subtypes_559.hasText(traceOut)) { + _$text_defaults_560(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_558.hasMarkers(traceOut) || _$subtypes_558.hasText(traceOut)) { + if(_$subtypes_559.hasMarkers(traceOut) || _$subtypes_559.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -59948,8 +60622,8 @@ var _$supplyDefaults_543 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_545(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_558.hasLines(traceOut)) _$handleLineShapeDefaults_551(traceIn, traceOut, coerce); + _$fillColorDefaults_546(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_559.hasLines(traceOut)) _$handleLineShapeDefaults_552(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -59957,11 +60631,11 @@ var _$supplyDefaults_543 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_518.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_519.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_422.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_423.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -59974,7 +60648,7 @@ var _$supplyDefaults_543 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /** Fill hover 'pointData' container with 'correct' hover text value * @@ -59989,15 +60663,15 @@ var _$supplyDefaults_543 = function supplyDefaults(traceIn, traceOut, defaultCol * @param {object} trace * @param {object || array} contOut (mutated here) */ -var _$fillHoverText_544 = function fillHoverText(calcPt, trace, contOut) { +var _$fillHoverText_545 = function fillHoverText(calcPt, trace, contOut) { var fill = Array.isArray(contOut) ? function(v) { contOut.push(v); } : function(v) { contOut.text = v; }; - var htx = _$lib_422.extractOption(calcPt, trace, 'htx', 'hovertext'); + var htx = _$lib_423.extractOption(calcPt, trace, 'htx', 'hovertext'); if(isValid(htx)) return fill(htx); - var tx = _$lib_422.extractOption(calcPt, trace, 'tx', 'text'); + var tx = _$lib_423.extractOption(calcPt, trace, 'tx', 'text'); if(isValid(tx)) return fill(tx); }; @@ -60018,10 +60692,10 @@ function isValid(v) { 'use strict'; /* removed: var _$color_299 = require('../../components/color'); */; -/* removed: var _$subtypes_558 = require('./subtypes'); */; +/* removed: var _$subtypes_559 = require('./subtypes'); */; -var _$getTraceColor_546 = function getTraceColor(trace, di) { +var _$getTraceColor_547 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes @@ -60052,7 +60726,7 @@ var _$getTraceColor_546 = function getTraceColor(trace, di) { else { lc = (trace.line || {}).color; return (lc && _$color_299.opacity(lc) && - _$subtypes_558.hasLines(trace) && trace.line.width) ? + _$subtypes_559.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -60068,14 +60742,14 @@ var _$getTraceColor_546 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$fx_341 = require('../../components/fx'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$getTraceColor_546 = require('./get_trace_color'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$getTraceColor_547 = require('./get_trace_color'); */; /* removed: var _$color_299 = require('../../components/color'); */; -/* removed: var _$fillHoverText_544 = require('./fill_hover_text'); */; +/* removed: var _$fillHoverText_545 = require('./fill_hover_text'); */; -var _$hoverPoints_547 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_548 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -60128,8 +60802,8 @@ var _$hoverPoints_547 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_422.extendFlat(pointData, { - color: _$getTraceColor_546(trace, di), + _$lib_423.extendFlat(pointData, { + color: _$getTraceColor_547(trace, di), x0: xc - rad, x1: xc + rad, @@ -60142,8 +60816,8 @@ var _$hoverPoints_547 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_544(di, trace, pointData); - _$registry_518.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_545(di, trace, pointData); + _$registry_519.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -60215,7 +60889,7 @@ var _$hoverPoints_547 = function hoverPoints(pointData, xval, yval, hovermode) { color = trace.line.color; } - _$lib_422.extendFlat(pointData, { + _$lib_423.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -60249,14 +60923,14 @@ var _$hoverPoints_547 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_550 = _$numerical_403.BADNUM; -/* removed: var _$lib_422 = require('../../lib'); */; -var __segmentsIntersect_550 = _$lib_422.segmentsIntersect; -var constrain = _$lib_422.constrain; -/* removed: var _$constants_542 = require('./constants'); */; +var __BADNUM_551 = _$numerical_403.BADNUM; +/* removed: var _$lib_423 = require('../../lib'); */; +var __segmentsIntersect_551 = _$lib_423.segmentsIntersect; +var constrain = _$lib_423.constrain; +/* removed: var _$constants_543 = require('./constants'); */; -var _$linePoints_550 = function linePoints(d, opts) { +var _$linePoints_551 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -60265,7 +60939,7 @@ var _$linePoints_550 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_542.minTolerance; + var minTolerance = _$constants_543.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -60303,7 +60977,7 @@ var _$linePoints_550 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_550 || y === __BADNUM_550) return di.intoCenter || false; + if(x === __BADNUM_551 || y === __BADNUM_551) return di.intoCenter || false; return [x, y]; } @@ -60311,7 +60985,7 @@ var _$linePoints_550 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_542.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_543.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -60323,7 +60997,7 @@ var _$linePoints_550 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_542.maxScreensAway; + var maxScreensAway = _$constants_543.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -60352,7 +61026,7 @@ var _$linePoints_550 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_550(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_551(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -60406,7 +61080,7 @@ var _$linePoints_550 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_422.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_423.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -60659,7 +61333,7 @@ var _$linePoints_550 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_552 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_553 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -60701,17 +61375,17 @@ var _$linkTraces_552 = function linkTraces(gd, plotinfo, cdscatter) { /* removed: var _$d3_79 = require('d3'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$drawing_324 = require('../../components/drawing'); */; -/* removed: var _$subtypes_558 = require('./subtypes'); */; -/* removed: var _$linePoints_550 = require('./line_points'); */; -/* removed: var _$linkTraces_552 = require('./link_traces'); */; -var __polygonTester_555 = _$polygon_434.tester; +/* removed: var _$subtypes_559 = require('./subtypes'); */; +/* removed: var _$linePoints_551 = require('./line_points'); */; +/* removed: var _$linkTraces_553 = require('./link_traces'); */; +var __polygonTester_556 = _$polygon_435.tester; -var _$plot_555 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_556 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -60720,9 +61394,8 @@ var _$plot_555 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -60734,7 +61407,7 @@ var _$plot_555 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_552(gd, plotinfo, cdscatter); + _$linkTraces_553(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -60773,12 +61446,12 @@ var _$plot_555 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_555(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_556(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_555(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_556(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -60833,7 +61506,7 @@ function createFills(gd, scatterlayer, plotinfo) { }); } -function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_556(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -60855,7 +61528,7 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran tr = _$d3_79.select(element); // error bars are at the bottom - _$registry_518.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_519.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -60867,7 +61540,7 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -60893,11 +61566,11 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_422.noop; + makeUpdate = _$lib_423.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_558.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_559.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -60934,7 +61607,7 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_550(cdscatter, { + segments = _$linePoints_551(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -60949,7 +61622,7 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_555(segments[i]); + trace._polygons[i] = __polygonTester_556(segments[i]); } if(segments.length) { @@ -60975,7 +61648,7 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_558.hasLines(trace) && pts.length > 1) { + if(_$subtypes_559.hasLines(trace) && pts.length > 1) { var el = _$d3_79.select(this); // This makes the coloring work correctly: @@ -61102,19 +61775,19 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = d[0].trace, s = _$d3_79.select(this), - showMarkers = _$subtypes_558.hasMarkers(trace), - showText = _$subtypes_558.hasText(trace); + showMarkers = _$subtypes_559.hasMarkers(trace), + showText = _$subtypes_559.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_422.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_423.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_422.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_423.identity; } // marker points @@ -61235,11 +61908,11 @@ function __plotOne_555(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_79.extent(_$lib_422.simpleMap(xa.range, xa.r2c)), - yr = _$d3_79.extent(_$lib_422.simpleMap(ya.range, ya.r2c)); + xr = _$d3_79.extent(_$lib_423.simpleMap(xa.range, xa.r2c)), + yr = _$d3_79.extent(_$lib_423.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_558.hasMarkers(trace)) return; + if(!_$subtypes_559.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -61254,7 +61927,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_558.hasMarkers(tracei) && + if(_$subtypes_559.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -61285,9 +61958,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_558 = require('./subtypes'); */; +/* removed: var _$subtypes_559 = require('./subtypes'); */; -var _$selectPoints_556 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_557 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -61298,7 +61971,7 @@ var _$selectPoints_556 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_558.hasMarkers(trace) && !_$subtypes_558.hasText(trace)); + var hasOnlyLines = (!_$subtypes_559.hasMarkers(trace) && !_$subtypes_559.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -61341,9 +62014,9 @@ var _$selectPoints_556 = function selectPoints(searchInfo, polygon) { /* removed: var _$d3_79 = require('d3'); */; /* removed: var _$drawing_324 = require('../../components/drawing'); */; -/* removed: var _$registry_518 = require('../../registry'); */; +/* removed: var _$registry_519 = require('../../registry'); */; -function __style_557(gd, cd) { +function __style_558(gd, cd) { var s = cd ? cd[0].node3 : _$d3_79.select(gd).selectAll('g.trace.scatter'); s.style('opacity', function(d) { @@ -61362,7 +62035,7 @@ function __style_557(gd, cd) { s.selectAll('g.trace path.js-fill') .call(_$drawing_324.fillGroupStyle); - _$registry_518.getComponentMethod('errorbars', 'style')(s); + _$registry_519.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { @@ -61375,8 +62048,8 @@ function stylePoints(sel, trace, gd) { _$drawing_324.selectedTextStyle(txs, trace); } -var _$style_557 = { - style: __style_557, +var _$style_558 = { + style: __style_558, stylePoints: stylePoints }; @@ -61393,35 +62066,35 @@ var _$style_557 = { var Scatter = {}; -/* removed: var _$subtypes_558 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_558.hasLines; -Scatter.hasMarkers = _$subtypes_558.hasMarkers; -Scatter.hasText = _$subtypes_558.hasText; -Scatter.isBubble = _$subtypes_558.isBubble; +/* removed: var _$subtypes_559 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_559.hasLines; +Scatter.hasMarkers = _$subtypes_559.hasMarkers; +Scatter.hasText = _$subtypes_559.hasText; +Scatter.isBubble = _$subtypes_559.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_536; -Scatter.supplyDefaults = _$supplyDefaults_543; -Scatter.cleanData = _$cleanData_539; -Scatter.calc = _$calc_537.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_535; -Scatter.plot = _$plot_555; -Scatter.colorbar = _$colorbar_540; -Scatter.style = _$style_557.style; -Scatter.hoverPoints = _$hoverPoints_547; -Scatter.selectPoints = _$selectPoints_556; +Scatter.attributes = _$attributes_537; +Scatter.supplyDefaults = _$supplyDefaults_544; +Scatter.cleanData = _$cleanData_540; +Scatter.calc = _$calc_538.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_536; +Scatter.plot = _$plot_556; +Scatter.colorbar = _$colorbar_541; +Scatter.style = _$style_558.style; +Scatter.hoverPoints = _$hoverPoints_548; +Scatter.selectPoints = _$selectPoints_557; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_477; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_478; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_548 = Scatter; +var _$Scatter_549 = Scatter; var _$core_406 = {}; /** @@ -61435,7 +62108,7 @@ var _$core_406 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_406.version = '1.35.2'; +_$core_406.version = '1.36.0'; // inject promise polyfill _$es6Promise_86.polyfill(); @@ -61447,24 +62120,24 @@ _$plotcss_1; _$mathjax_config_407; // include registry module and expose register method -/* removed: var _$registry_518 = require('./registry'); */; -var register = _$core_406.register = _$registry_518.register; +/* removed: var _$registry_519 = require('./registry'); */; +var register = _$core_406.register = _$registry_519.register; // expose plot api methods -/* removed: var _$plot_api_453 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_453); +/* removed: var _$plot_api_454 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_454); for(var i = 0; i < methodNames.length; i++) { var __name_406 = methodNames[i]; - _$core_406[__name_406] = _$plot_api_453[__name_406]; + _$core_406[__name_406] = _$plot_api_454[__name_406]; register({ moduleType: 'apiMethod', name: __name_406, - fn: _$plot_api_453[__name_406] + fn: _$plot_api_454[__name_406] }); } // scatter is the only trace included by default -register(_$Scatter_548); +register(_$Scatter_549); // register all registrable components modules register([ @@ -61484,8 +62157,8 @@ register([ // locales en and en-US are required for default behavior register([ - _$localeEn_449, - _$localeEnUs_448 + _$localeEn_450, + _$localeEnUs_449 ]); // plot icons @@ -61494,9 +62167,9 @@ _$core_406.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk _$core_406.Plots = _$plots_510; _$core_406.Fx = _$fx_341; -_$core_406.Snapshot = _$Snapshot_523; -_$core_406.PlotSchema = _$plot_schema_457; -_$core_406.Queue = _$queue_436; +_$core_406.Snapshot = _$Snapshot_524; +_$core_406.PlotSchema = _$plot_schema_458; +_$core_406.Queue = _$queue_437; // export d3 used in the bundle _$core_406.d3 = _$d3_79; @@ -61545,13 +62218,13 @@ var _$attributes_498 = { 'use strict'; /* removed: var _$color_299 = require('../../../components/color'); */; -/* removed: var _$layout_attributes_478 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_499 = _$extend_414.extendFlat; -var __overrideAll_499 = _$edit_types_451.overrideAll; +/* removed: var _$layout_attributes_479 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_499 = _$extend_415.extendFlat; +var __overrideAll_499 = _$edit_types_452.overrideAll; var _$axis_attributes_499 = __overrideAll_499({ - visible: _$layout_attributes_478.visible, + visible: _$layout_attributes_479.visible, showspikes: { valType: 'boolean', @@ -61595,51 +62268,51 @@ var _$axis_attributes_499 = __overrideAll_499({ dflt: true, }, - color: _$layout_attributes_478.color, - categoryorder: _$layout_attributes_478.categoryorder, - categoryarray: _$layout_attributes_478.categoryarray, - title: _$layout_attributes_478.title, - titlefont: _$layout_attributes_478.titlefont, - type: _$layout_attributes_478.type, - autorange: _$layout_attributes_478.autorange, - rangemode: _$layout_attributes_478.rangemode, - range: _$layout_attributes_478.range, + color: _$layout_attributes_479.color, + categoryorder: _$layout_attributes_479.categoryorder, + categoryarray: _$layout_attributes_479.categoryarray, + title: _$layout_attributes_479.title, + titlefont: _$layout_attributes_479.titlefont, + type: _$layout_attributes_479.type, + autorange: _$layout_attributes_479.autorange, + rangemode: _$layout_attributes_479.rangemode, + range: _$layout_attributes_479.range, // ticks - tickmode: _$layout_attributes_478.tickmode, - nticks: _$layout_attributes_478.nticks, - tick0: _$layout_attributes_478.tick0, - dtick: _$layout_attributes_478.dtick, - tickvals: _$layout_attributes_478.tickvals, - ticktext: _$layout_attributes_478.ticktext, - ticks: _$layout_attributes_478.ticks, - mirror: _$layout_attributes_478.mirror, - ticklen: _$layout_attributes_478.ticklen, - tickwidth: _$layout_attributes_478.tickwidth, - tickcolor: _$layout_attributes_478.tickcolor, - showticklabels: _$layout_attributes_478.showticklabels, - tickfont: _$layout_attributes_478.tickfont, - tickangle: _$layout_attributes_478.tickangle, - tickprefix: _$layout_attributes_478.tickprefix, - showtickprefix: _$layout_attributes_478.showtickprefix, - ticksuffix: _$layout_attributes_478.ticksuffix, - showticksuffix: _$layout_attributes_478.showticksuffix, - showexponent: _$layout_attributes_478.showexponent, - exponentformat: _$layout_attributes_478.exponentformat, - separatethousands: _$layout_attributes_478.separatethousands, - tickformat: _$layout_attributes_478.tickformat, - tickformatstops: _$layout_attributes_478.tickformatstops, - hoverformat: _$layout_attributes_478.hoverformat, + tickmode: _$layout_attributes_479.tickmode, + nticks: _$layout_attributes_479.nticks, + tick0: _$layout_attributes_479.tick0, + dtick: _$layout_attributes_479.dtick, + tickvals: _$layout_attributes_479.tickvals, + ticktext: _$layout_attributes_479.ticktext, + ticks: _$layout_attributes_479.ticks, + mirror: _$layout_attributes_479.mirror, + ticklen: _$layout_attributes_479.ticklen, + tickwidth: _$layout_attributes_479.tickwidth, + tickcolor: _$layout_attributes_479.tickcolor, + showticklabels: _$layout_attributes_479.showticklabels, + tickfont: _$layout_attributes_479.tickfont, + tickangle: _$layout_attributes_479.tickangle, + tickprefix: _$layout_attributes_479.tickprefix, + showtickprefix: _$layout_attributes_479.showtickprefix, + ticksuffix: _$layout_attributes_479.ticksuffix, + showticksuffix: _$layout_attributes_479.showticksuffix, + showexponent: _$layout_attributes_479.showexponent, + exponentformat: _$layout_attributes_479.exponentformat, + separatethousands: _$layout_attributes_479.separatethousands, + tickformat: _$layout_attributes_479.tickformat, + tickformatstops: _$layout_attributes_479.tickformatstops, + hoverformat: _$layout_attributes_479.hoverformat, // lines and grids - showline: _$layout_attributes_478.showline, - linecolor: _$layout_attributes_478.linecolor, - linewidth: _$layout_attributes_478.linewidth, - showgrid: _$layout_attributes_478.showgrid, - gridcolor: __extendFlat_499({}, _$layout_attributes_478.gridcolor, // shouldn't this be on-par with 2D? + showline: _$layout_attributes_479.showline, + linecolor: _$layout_attributes_479.linecolor, + linewidth: _$layout_attributes_479.linewidth, + showgrid: _$layout_attributes_479.showgrid, + gridcolor: __extendFlat_499({}, _$layout_attributes_479.gridcolor, // shouldn't this be on-par with 2D? {dflt: 'rgb(204, 204, 204)'}), - gridwidth: _$layout_attributes_478.gridwidth, - zeroline: _$layout_attributes_478.zeroline, - zerolinecolor: _$layout_attributes_478.zerolinecolor, - zerolinewidth: _$layout_attributes_478.zerolinewidth + gridwidth: _$layout_attributes_479.gridwidth, + zeroline: _$layout_attributes_479.zeroline, + zerolinecolor: _$layout_attributes_479.zerolinecolor, + zerolinewidth: _$layout_attributes_479.zerolinewidth }, 'plot', 'from-root'); /** @@ -61655,11 +62328,11 @@ var _$axis_attributes_499 = __overrideAll_499({ var __colorMix_500 = _$tinycolor_264.mix; -/* removed: var _$lib_422 = require('../../../lib'); */; +/* removed: var _$lib_423 = require('../../../lib'); */; /* removed: var _$axis_attributes_499 = require('./axis_attributes'); */; /* removed: var _$handleTypeDefaults_490 = require('../../cartesian/type_defaults'); */; -/* removed: var _$handleAxisDefaults_468 = require('../../cartesian/axis_defaults'); */; +/* removed: var _$handleAxisDefaults_469 = require('../../cartesian/axis_defaults'); */; var axesNames = ['xaxis', 'yaxis', 'zaxis']; @@ -61671,7 +62344,7 @@ var _$supplyLayoutDefaults_500 = function supplyLayoutDefaults(layoutIn, layoutO var containerIn, containerOut; function coerce(attr, dflt) { - return _$lib_422.coerce(containerIn, containerOut, _$axis_attributes_499, attr, dflt); + return _$lib_423.coerce(containerIn, containerOut, _$axis_attributes_499, attr, dflt); } for(var j = 0; j < axesNames.length; j++) { @@ -61685,7 +62358,7 @@ var _$supplyLayoutDefaults_500 = function supplyLayoutDefaults(layoutIn, layoutO _$handleTypeDefaults_490(containerIn, containerOut, coerce, options.data); - _$handleAxisDefaults_468( + _$handleAxisDefaults_469( containerIn, containerOut, coerce, @@ -61702,7 +62375,7 @@ var _$supplyLayoutDefaults_500 = function supplyLayoutDefaults(layoutIn, layoutO coerce('gridcolor', __colorMix_500(containerOut.color, options.bgColor, gridLightness).toRgbString()); coerce('title', axName[0]); // shouldn't this be on-par with 2D? - containerOut.setScale = _$lib_422.noop; + containerOut.setScale = _$lib_423.noop; if(coerce('showspikes')) { coerce('spikesides'); @@ -61728,8 +62401,8 @@ var _$supplyLayoutDefaults_500 = function supplyLayoutDefaults(layoutIn, layoutO /* removed: var _$axis_attributes_499 = require('./axis_attributes'); */; var __domainAttrs_503 = _$domain_492.attributes; -var __extendFlat_503 = _$extend_414.extendFlat; -var __counterRegex_503 = _$lib_422.counterRegex; +var __extendFlat_503 = _$extend_415.extendFlat; +var __counterRegex_503 = _$lib_423.counterRegex; function makeCameraVector(x, y, z) { return { @@ -61860,7 +62533,7 @@ var _$layout_attributes_503 = { 'use strict'; -/* removed: var _$lib_422 = require('../lib'); */; +/* removed: var _$lib_423 = require('../lib'); */; var handleDomainDefaults = _$domain_492.defaults; @@ -61891,7 +62564,7 @@ var handleDomainDefaults = _$domain_492.defaults; * additional items needed by this function here as well * } */ -var _$handleSubplotDefaults_517 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { +var _$handleSubplotDefaults_518 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { var subplotType = opts.type; var subplotAttributes = opts.attributes; var handleDefaults = opts.handleDefaults; @@ -61903,7 +62576,7 @@ var _$handleSubplotDefaults_517 = function handleSubplotDefaults(layoutIn, layou var subplotLayoutIn, subplotLayoutOut; function coerce(attr, dflt) { - return _$lib_422.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); + return _$lib_423.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); } for(var i = 0; i < idsLength; i++) { @@ -61935,11 +62608,11 @@ var _$handleSubplotDefaults_517 = function handleSubplotDefaults(layoutIn, layou 'use strict'; -/* removed: var _$lib_422 = require('../../../lib'); */; +/* removed: var _$lib_423 = require('../../../lib'); */; /* removed: var _$color_299 = require('../../../components/color'); */; -/* removed: var _$registry_518 = require('../../../registry'); */; +/* removed: var _$registry_519 = require('../../../registry'); */; -/* removed: var _$handleSubplotDefaults_517 = require('../../subplot_defaults'); */; +/* removed: var _$handleSubplotDefaults_518 = require('../../subplot_defaults'); */; /* removed: var _$supplyLayoutDefaults_500 = require('./axis_defaults'); */; /* removed: var _$layout_attributes_503 = require('./layout_attributes'); */; @@ -61952,11 +62625,11 @@ var _$supplyLayoutDefaults_502 = function supplyLayoutDefaults(layoutIn, layoutO function getDfltFromLayout(attr) { if(hasNon3D) return; - var isValid = _$lib_422.validate(layoutIn[attr], _$layout_attributes_503[attr]); + var isValid = _$lib_423.validate(layoutIn[attr], _$layout_attributes_503[attr]); if(isValid) return layoutIn[attr]; } - _$handleSubplotDefaults_517(layoutIn, layoutOut, fullData, { + _$handleSubplotDefaults_518(layoutIn, layoutOut, fullData, { type: 'gl3d', attributes: _$layout_attributes_503, handleDefaults: handleGl3dDefaults, @@ -62032,7 +62705,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { fullLayout: opts.fullLayout }); - _$registry_518.getComponentMethod('annotations3d', 'handleDefaults')( + _$registry_519.getComponentMethod('annotations3d', 'handleDefaults')( sceneLayoutIn, sceneLayoutOut, opts ); @@ -89361,7 +90034,7 @@ var _$getWebGLContext_279 = function getWebGLContext (opt) { /* removed: var _$color_299 = require('../components/color'); */; -var __noop_442 = function() {}; +var __noop_443 = function() {}; /** @@ -89371,9 +90044,9 @@ var __noop_442 = function() {}; * Expects 'scene' to have property 'container' * */ -var _$showWebGlMsg_442 = function showWebGlMsg(scene) { +var _$showWebGlMsg_443 = function showWebGlMsg(scene) { for(var prop in scene) { - if(typeof scene[prop] === 'function') scene[prop] = __noop_442; + if(typeof scene[prop] === 'function') scene[prop] = __noop_443; } scene.destroy = function() { @@ -90015,7 +90688,7 @@ function str2RgbaArray(color) { return _$normalize_60(color); } -var _$str2RgbaArray_444 = str2RgbaArray; +var _$str2RgbaArray_445 = str2RgbaArray; /** * Copyright 2012-2018, Plotly, Inc. @@ -90410,7 +91083,7 @@ function convertHTMLToUnicode(html) { html)))); } -var _$convertHTMLToUnicode_420 = convertHTMLToUnicode; +var _$convertHTMLToUnicode_421 = convertHTMLToUnicode; /** * Copyright 2012-2018, Plotly, Inc. @@ -90423,8 +91096,8 @@ var _$convertHTMLToUnicode_420 = convertHTMLToUnicode; 'use strict'; -/* removed: var _$convertHTMLToUnicode_420 = require('../../../lib/html2unicode'); */; -/* removed: var _$str2RgbaArray_444 = require('../../../lib/str2rgbarray'); */; +/* removed: var _$convertHTMLToUnicode_421 = require('../../../lib/html2unicode'); */; +/* removed: var _$str2RgbaArray_445 = require('../../../lib/str2rgbarray'); */; var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis']; @@ -90499,27 +91172,27 @@ __proto_501.merge = function(sceneLayout) { } // Axes labels - opts.labels[i] = _$convertHTMLToUnicode_420(axes.title); + opts.labels[i] = _$convertHTMLToUnicode_421(axes.title); if('titlefont' in axes) { - if(axes.titlefont.color) opts.labelColor[i] = _$str2RgbaArray_444(axes.titlefont.color); + if(axes.titlefont.color) opts.labelColor[i] = _$str2RgbaArray_445(axes.titlefont.color); if(axes.titlefont.family) opts.labelFont[i] = axes.titlefont.family; if(axes.titlefont.size) opts.labelSize[i] = axes.titlefont.size; } // Lines if('showline' in axes) opts.lineEnable[i] = axes.showline; - if('linecolor' in axes) opts.lineColor[i] = _$str2RgbaArray_444(axes.linecolor); + if('linecolor' in axes) opts.lineColor[i] = _$str2RgbaArray_445(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_444(axes.gridcolor); + if('gridcolor' in axes) opts.gridColor[i] = _$str2RgbaArray_445(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_444(axes.zerolinecolor); + if('zerolinecolor' in axes) opts.zeroLineColor[i] = _$str2RgbaArray_445(axes.zerolinecolor); if('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth; // tick lines @@ -90529,7 +91202,7 @@ __proto_501.merge = function(sceneLayout) { if('ticklen' in axes) { opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen; } - if('tickcolor' in axes) opts.lineTickColor[i] = _$str2RgbaArray_444(axes.tickcolor); + if('tickcolor' in axes) opts.lineTickColor[i] = _$str2RgbaArray_445(axes.tickcolor); if('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth; if('tickangle' in axes) { opts.tickAngle[i] = (axes.tickangle === 'auto') ? @@ -90539,7 +91212,7 @@ __proto_501.merge = function(sceneLayout) { // tick labels if('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels; if('tickfont' in axes) { - if(axes.tickfont.color) opts.tickColor[i] = _$str2RgbaArray_444(axes.tickfont.color); + if(axes.tickfont.color) opts.tickColor[i] = _$str2RgbaArray_445(axes.tickfont.color); if(axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family; if(axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size; } @@ -90560,7 +91233,7 @@ __proto_501.merge = function(sceneLayout) { // grid background if('showbackground' in axes && axes.showbackground !== false) { opts.backgroundEnable[i] = true; - opts.backgroundColor[i] = _$str2RgbaArray_444(axes.backgroundcolor); + opts.backgroundColor[i] = _$str2RgbaArray_445(axes.backgroundcolor); } else opts.backgroundEnable[i] = false; } }; @@ -90585,7 +91258,7 @@ var _$createAxesOptions_501 = createAxesOptions; 'use strict'; -/* removed: var _$str2RgbaArray_444 = require('../../../lib/str2rgbarray'); */; +/* removed: var _$str2RgbaArray_445 = require('../../../lib/str2rgbarray'); */; var __AXES_NAMES_504 = ['xaxis', 'yaxis', 'zaxis']; @@ -90611,7 +91284,7 @@ __proto_504.merge = function(sceneLayout) { } this.enabled[i] = axes.showspikes; - this.colors[i] = _$str2RgbaArray_444(axes.spikecolor); + this.colors[i] = _$str2RgbaArray_445(axes.spikecolor); this.drawSides[i] = axes.spikesides; this.lineWidth[i] = axes.spikethickness; } @@ -90640,9 +91313,9 @@ var _$createSpikeOptions_504 = createSpikeOptions; var _$computeTickMarks_505 = computeTickMarks; -/* removed: var _$axes_466 = require('../../cartesian/axes'); */; -/* removed: var _$lib_422 = require('../../../lib'); */; -/* removed: var _$convertHTMLToUnicode_420 = require('../../../lib/html2unicode'); */; +/* removed: var _$axes_467 = require('../../cartesian/axes'); */; +/* removed: var _$lib_423 = require('../../../lib'); */; +/* removed: var _$convertHTMLToUnicode_421 = require('../../../lib/html2unicode'); */; var __AXES_NAMES_505 = ['xaxis', 'yaxis', 'zaxis']; @@ -90693,13 +91366,13 @@ function computeTickMarks(scene) { var tickModeCached = axes.tickmode; if(axes.tickmode === 'auto') { axes.tickmode = 'linear'; - var nticks = axes.nticks || _$lib_422.constrain((axes._length / 40), 4, 9); - _$axes_466.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks); + var nticks = axes.nticks || _$lib_423.constrain((axes._length / 40), 4, 9); + _$axes_467.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks); } - var dataTicks = _$axes_466.calcTicks(axes); + var dataTicks = _$axes_467.calcTicks(axes); for(var j = 0; j < dataTicks.length; ++j) { dataTicks[j].x = dataTicks[j].x * scene.dataScale[i]; - dataTicks[j].text = _$convertHTMLToUnicode_420(dataTicks[j].text); + dataTicks[j].text = _$convertHTMLToUnicode_421(dataTicks[j].text); } ticks[i] = dataTicks; @@ -90736,14 +91409,14 @@ function computeTickMarks(scene) { /* removed: var _$getWebGLContext_279 = require('webgl-context'); */; /* removed: var _$hasPassiveEvents_174 = require('has-passive-events'); */; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -/* removed: var _$axes_466 = require('../../plots/cartesian/axes'); */; +/* removed: var _$axes_467 = require('../../plots/cartesian/axes'); */; /* removed: var _$fx_341 = require('../../components/fx'); */; -/* removed: var _$str2RgbaArray_444 = require('../../lib/str2rgbarray'); */; -/* removed: var _$showWebGlMsg_442 = require('../../lib/show_no_webgl_msg'); */; +/* removed: var _$str2RgbaArray_445 = require('../../lib/str2rgbarray'); */; +/* removed: var _$showWebGlMsg_443 = require('../../lib/show_no_webgl_msg'); */; /* removed: var _$createCamera_496 = require('./camera'); */; /* removed: var _$project_506 = require('./project'); */; @@ -90784,7 +91457,7 @@ function render(scene) { function formatter(axisName, val) { var axis = scene.fullSceneLayout[axisName]; - return _$axes_466.tickText(axis, axis.d2l(val), 'hover').text; + return _$axes_467.tickText(axis, axis.d2l(val), 'hover').text; } var oldEventData; @@ -90902,7 +91575,7 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { * The destroy method - which will remove the container from the DOM * is overridden with a function that removes the container only. */ - _$showWebGlMsg_442(scene); + _$showWebGlMsg_443(scene); } var relayoutCallback = function(scene) { @@ -90919,7 +91592,7 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { if(!scene.staticMode) { scene.glplot.canvas.addEventListener('webglcontextlost', function(ev) { - _$lib_422.warn('Lost WebGL context.'); + _$lib_423.warn('Lost WebGL context.'); ev.preventDefault(); }); } @@ -90999,8 +91672,8 @@ function Scene(options, fullLayout) { this.contourLevels = [ [], [], [] ]; - this.convertAnnotations = _$registry_518.getComponentMethod('annotations3d', 'convert'); - this.drawAnnotations = _$registry_518.getComponentMethod('annotations3d', 'draw'); + this.convertAnnotations = _$registry_519.getComponentMethod('annotations3d', 'convert'); + this.drawAnnotations = _$registry_519.getComponentMethod('annotations3d', 'draw'); if(!initializeGLPlot(this, fullLayout)) return; // todo check the necessity for this line } @@ -91019,7 +91692,7 @@ __proto_507.recoverContext = function() { return; } if(!initializeGLPlot(scene, scene.fullLayout, canvas, gl)) { - _$lib_422.error('Catastrophic and unrecoverable WebGL error. Context lost.'); + _$lib_423.error('Catastrophic and unrecoverable WebGL error. Context lost.'); return; } scene.plot.apply(scene, scene.plotArgs); @@ -91031,14 +91704,14 @@ var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ]; function coordinateBound(axis, coord, len, d, bounds, calendar) { var x; - if(!_$lib_422.isArrayOrTypedArray(coord)) { + if(!_$lib_423.isArrayOrTypedArray(coord)) { bounds[0][d] = Math.min(bounds[0][d], 0); bounds[1][d] = Math.max(bounds[1][d], len - 1); return; } for(var i = 0; i < (len || coord.length); ++i) { - if(_$lib_422.isArrayOrTypedArray(coord[i])) { + if(_$lib_423.isArrayOrTypedArray(coord[i])) { for(var j = 0; j < coord[i].length; ++j) { x = axis.d2l(coord[i][j], 0, calendar); if(!isNaN(x) && isFinite(x)) { @@ -91076,7 +91749,7 @@ __proto_507.plot = function(sceneData, fullLayout, layout) { var fullSceneLayout = fullLayout[this.id]; var sceneLayout = layout[this.id]; - if(fullSceneLayout.bgcolor) this.glplot.clearColor = _$str2RgbaArray_444(fullSceneLayout.bgcolor); + if(fullSceneLayout.bgcolor) this.glplot.clearColor = _$str2RgbaArray_445(fullSceneLayout.bgcolor); else this.glplot.clearColor = [0, 0, 0, 0]; this.glplot.snapToData = true; @@ -91368,7 +92041,7 @@ __proto_507.setCamera = function setCamera(cameraData) { // save camera to user layout (i.e. gd.layout) __proto_507.saveCamera = function saveCamera(layout) { var cameraData = this.getCamera(), - cameraNestedProp = _$lib_422.nestedProperty(layout, this.id + '.camera'), + cameraNestedProp = _$lib_423.nestedProperty(layout, this.id + '.camera'), cameraDataLastSave = cameraNestedProp.get(), hasChanged = false; @@ -91478,8 +92151,8 @@ __proto_507.toImage = function(format) { __proto_507.setConvert = function() { for(var i = 0; i < 3; i++) { var ax = this.fullSceneLayout[axisProperties[i]]; - _$axes_466.setConvert(ax, this.fullLayout); - ax.setScale = _$lib_422.noop; + _$axes_467.setConvert(ax, this.fullLayout); + ax.setScale = _$lib_423.noop; } }; @@ -91497,12 +92170,12 @@ var _$gl3d_497 = {}; 'use strict'; -var __overrideAll_497 = _$edit_types_451.overrideAll; +var __overrideAll_497 = _$edit_types_452.overrideAll; /* removed: var _$layout_attributes_342 = require('../../components/fx/layout_attributes'); */; /* removed: var _$Scene_507 = require('./scene'); */; var getSubplotData = _$get_data_495.getSubplotData; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$xmlns_namespaces_405 = require('../../constants/xmlns_namespaces'); */; var GL3D = 'gl3d'; @@ -91515,7 +92188,7 @@ _$gl3d_497.attr = SCENE; _$gl3d_497.idRoot = SCENE; -_$gl3d_497.idRegex = _$gl3d_497.attrRegex = _$lib_422.counterRegex('scene'); +_$gl3d_497.idRegex = _$gl3d_497.attrRegex = _$lib_423.counterRegex('scene'); _$gl3d_497.attributes = _$attributes_498; @@ -91555,7 +92228,7 @@ _$gl3d_497.plot = function plotGl3d(gd) { // save 'initial' camera settings for modebar button if(!scene.cameraInitial) { - scene.cameraInitial = _$lib_422.extendDeep({}, sceneLayout.camera); + scene.cameraInitial = _$lib_423.extendDeep({}, sceneLayout.camera); } scene.plot(fullSceneData, fullLayout, gd.layout); @@ -91626,7 +92299,7 @@ _$gl3d_497.updateFx = function(fullLayout) { } }; -var _$attributes_567 = {}; +var _$attributes_568 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -91640,10 +92313,10 @@ var _$attributes_567 = {}; /* removed: var _$color_299 = require('../../components/color'); */; /* removed: var _$attributes_305 = require('../../components/colorscale/attributes'); */; /* removed: var _$attributes_300 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_463 = require('../../plots/attributes'); */; +/* removed: var _$attributes_464 = require('../../plots/attributes'); */; -var __extendFlat_567 = _$extend_414.extendFlat; -var __overrideAll_567 = _$edit_types_451.overrideAll; +var __extendFlat_568 = _$extend_415.extendFlat; +var __overrideAll_568 = _$edit_types_452.overrideAll; function makeContourProjAttr(axLetter) { return { @@ -91710,7 +92383,7 @@ function makeContourAttr(axLetter) { }; } -var __attrs_567 = _$attributes_567 = __overrideAll_567({ +var __attrs_568 = _$attributes_568 = __overrideAll_568({ z: { valType: 'data_array', @@ -91741,7 +92414,7 @@ var __attrs_567 = _$attributes_567 = __overrideAll_567({ cmin: _$attributes_305.zmin, cmax: _$attributes_305.zmax, colorscale: _$attributes_305.colorscale, - autocolorscale: __extendFlat_567({}, _$attributes_305.autocolorscale, + autocolorscale: __extendFlat_568({}, _$attributes_305.autocolorscale, {dflt: false}), reversescale: _$attributes_305.reversescale, showscale: _$attributes_305.showscale, @@ -91839,21 +92512,21 @@ var __attrs_567 = _$attributes_567 = __overrideAll_567({ }, _deprecated: { - zauto: __extendFlat_567({}, _$attributes_305.zauto, { + zauto: __extendFlat_568({}, _$attributes_305.zauto, { }), - zmin: __extendFlat_567({}, _$attributes_305.zmin, { + zmin: __extendFlat_568({}, _$attributes_305.zmin, { }), - zmax: __extendFlat_567({}, _$attributes_305.zmax, { + zmax: __extendFlat_568({}, _$attributes_305.zmax, { }) }, - hoverinfo: __extendFlat_567({}, _$attributes_463.hoverinfo) + hoverinfo: __extendFlat_568({}, _$attributes_464.hoverinfo) }, 'calc', 'nested'); -__attrs_567.x.editType = __attrs_567.y.editType = __attrs_567.z.editType = 'calc+clearAxisTypes'; +__attrs_568.x.editType = __attrs_568.y.editType = __attrs_568.z.editType = 'calc+clearAxisTypes'; /** * Copyright 2012-2018, Plotly, Inc. @@ -91868,12 +92541,12 @@ __attrs_567.x.editType = __attrs_567.y.editType = __attrs_567.z.editType = 'calc /* removed: var _$makeColorScaleAttributes_307 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_305 = require('../../components/colorscale/attributes'); */; /* removed: var _$attributes_300 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_567 = require('../surface/attributes'); */; -/* removed: var _$attributes_463 = require('../../plots/attributes'); */; +/* removed: var _$attributes_568 = require('../surface/attributes'); */; +/* removed: var _$attributes_464 = require('../../plots/attributes'); */; -var __extendFlat_527 = _$extend_414.extendFlat; +var __extendFlat_528 = _$extend_415.extendFlat; -var _$attributes_527 = __extendFlat_527(_$makeColorScaleAttributes_307('', 'calc', false), { +var _$attributes_528 = __extendFlat_528(_$makeColorScaleAttributes_307('', 'calc', false), { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -91961,7 +92634,7 @@ var _$attributes_527 = __extendFlat_527(_$makeColorScaleAttributes_307('', 'calc }, // Opacity - opacity: _$attributes_567.opacity, + opacity: _$attributes_568.opacity, // Flat shaded mode flatshading: { @@ -91973,11 +92646,11 @@ var _$attributes_527 = __extendFlat_527(_$makeColorScaleAttributes_307('', 'calc }, contour: { - show: __extendFlat_527({}, _$attributes_567.contours.x.show, { + show: __extendFlat_528({}, _$attributes_568.contours.x.show, { }), - color: _$attributes_567.contours.x.color, - width: _$attributes_567.contours.x.width, + color: _$attributes_568.contours.x.color, + width: _$attributes_568.contours.x.width, editType: 'calc' }, @@ -91985,12 +92658,12 @@ var _$attributes_527 = __extendFlat_527(_$makeColorScaleAttributes_307('', 'calc colorbar: _$attributes_300, lightposition: { - x: __extendFlat_527({}, _$attributes_567.lightposition.x, {dflt: 1e5}), - y: __extendFlat_527({}, _$attributes_567.lightposition.y, {dflt: 1e5}), - z: __extendFlat_527({}, _$attributes_567.lightposition.z, {dflt: 0}), + x: __extendFlat_528({}, _$attributes_568.lightposition.x, {dflt: 1e5}), + y: __extendFlat_528({}, _$attributes_568.lightposition.y, {dflt: 1e5}), + z: __extendFlat_528({}, _$attributes_568.lightposition.z, {dflt: 0}), editType: 'calc' }, - lighting: __extendFlat_527({ + lighting: __extendFlat_528({ vertexnormalsepsilon: { valType: 'number', @@ -92010,9 +92683,9 @@ var _$attributes_527 = __extendFlat_527(_$makeColorScaleAttributes_307('', 'calc }, editType: 'calc' - }, _$attributes_567.lighting), + }, _$attributes_568.lighting), - hoverinfo: __extendFlat_527({}, _$attributes_463.hoverinfo, {editType: 'calc'}) + hoverinfo: __extendFlat_528({}, _$attributes_464.hoverinfo, {editType: 'calc'}) }); /** @@ -92027,7 +92700,7 @@ var _$attributes_527 = __extendFlat_527(_$makeColorScaleAttributes_307('', 'calc /* removed: var _$calc_306 = require('../../components/colorscale/calc'); */; -var _$calc_528 = function calc(gd, trace) { +var _$calc_529 = function calc(gd, trace) { if(trace.intensity) { _$calc_306(trace, trace.intensity, '', 'c'); } @@ -92045,20 +92718,20 @@ var _$calc_528 = function calc(gd, trace) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; /* removed: var _$colorscale_314 = require('../../components/colorscale'); */; /* removed: var _$draw_303 = require('../../components/colorbar/draw'); */; -var _$colorbar_529 = function colorbar(gd, cd) { +var _$colorbar_530 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, cmin = trace.cmin, cmax = trace.cmax, vals = trace.intensity || []; - if(!_$fastIsnumeric_89(cmin)) cmin = _$lib_422.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_89(cmax)) cmax = _$lib_422.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_89(cmin)) cmin = _$lib_423.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_89(cmax)) cmax = _$lib_423.aggNums(Math.max, null, vals); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); @@ -94016,8 +94689,8 @@ function closestPointToPickLocation(simplex, pixelCoord, model, view, projection var _$shaders_132 = {}; /* removed: var _$browser_172 = require('glslify') */; -var triVertSrc = _$browser_172(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\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\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}"]) -var triFragSrc = _$browser_172(["precision mediump 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\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\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 = cookTorranceSpecular(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}"]) +var triVertSrc = _$browser_172(["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;\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\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}\n"]) +var triFragSrc = _$browser_172(["#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\nvec3 normals(vec3 pos) {\n vec3 fdx = dFdx(pos);\n vec3 fdy = dFdy(pos);\n return normalize(cross(fdx, fdy));\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\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(any(lessThan(f_data, clipBounds[0])) ||\n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n vec3 normal = normals(f_data);\n\n if (\n dot(N, normal) < 0.0\n ) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}\n"]) var edgeVertSrc = _$browser_172(["precision mediump 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 = _$browser_172(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]) var pointVertSrc = _$browser_172(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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}"]) @@ -95309,6 +95982,7 @@ var identityMatrix = [ 0,0,1,0, 0,0,0,1] + function SimplicialMesh(gl , texture , triShader @@ -96162,6 +96836,11 @@ function createSimplicialMesh(gl, params) { gl = params.gl; } + //enable derivatives for face normals + var ext = gl.getExtension('OES_standard_derivatives') || gl.getExtension('MOZ_OES_standard_derivatives') || gl.getExtension('WEBKIT_OES_standard_derivatives') + if (!ext) + throw new Error('derivatives not supported') + var triShader = createMeshShader(gl) var lineShader = createWireShader(gl) var pointShader = createPointShader(gl) @@ -96316,7 +96995,7 @@ var _$createSimplicialMesh_133 = createSimplicialMesh /* removed: var _$alphaShape_14 = require('alpha-shape'); */; /* removed: var _$convexHull_70 = require('convex-hull'); */; -/* removed: var _$str2RgbaArray_444 = require('../../lib/str2rgbarray'); */; +/* removed: var _$str2RgbaArray_445 = require('../../lib/str2rgbarray'); */; function Mesh3DTrace(scene, mesh, uid) { @@ -96329,9 +97008,9 @@ function Mesh3DTrace(scene, mesh, uid) { this.showContour = false; } -var __proto_530 = Mesh3DTrace.prototype; +var __proto_531 = Mesh3DTrace.prototype; -__proto_530.handlePick = function(selection) { +__proto_531.handlePick = function(selection) { if(selection.object === this.mesh) { var selectIndex = selection.index = selection.data.index; @@ -96365,7 +97044,7 @@ function parseColorScale(colorscale) { } function parseColorArray(colors) { - return colors.map(_$str2RgbaArray_444); + return colors.map(_$str2RgbaArray_445); } function zip3(x, y, z) { @@ -96376,7 +97055,7 @@ function zip3(x, y, z) { return result; } -__proto_530.update = function(data) { +__proto_531.update = function(data) { var scene = this.scene, layout = scene.fullSceneLayout; @@ -96424,7 +97103,7 @@ __proto_530.update = function(data) { faceNormalsEpsilon: data.lighting.facenormalsepsilon, opacity: data.opacity, contourEnable: data.contour.show, - contourColor: _$str2RgbaArray_444(data.contour.color).slice(0, 3), + contourColor: _$str2RgbaArray_445(data.contour.color).slice(0, 3), contourWidth: data.contour.width, useFacetNormals: data.flatshading }; @@ -96445,14 +97124,14 @@ __proto_530.update = function(data) { } else { this.color = data.color; - config.meshColor = _$str2RgbaArray_444(data.color); + config.meshColor = _$str2RgbaArray_445(data.color); } // Update mesh this.mesh.update(config); }; -__proto_530.dispose = function() { +__proto_531.dispose = function() { this.scene.glplot.remove(this.mesh); this.mesh.dispose(); }; @@ -96467,7 +97146,7 @@ function createMesh3DTrace(scene, data) { return result; } -var _$createMesh3DTrace_530 = createMesh3DTrace; +var _$createMesh3DTrace_531 = createMesh3DTrace; /** * Copyright 2012-2018, Plotly, Inc. @@ -96480,14 +97159,14 @@ var _$createMesh3DTrace_530 = createMesh3DTrace; 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$colorScaleDefaults_309 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_527 = require('./attributes'); */; +/* removed: var _$attributes_528 = require('./attributes'); */; -var _$supplyDefaults_531 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_532 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_422.coerce(traceIn, traceOut, _$attributes_527, attr, dflt); + return _$lib_423.coerce(traceIn, traceOut, _$attributes_528, attr, dflt); } // read in face/vertex properties @@ -96495,7 +97174,7 @@ var _$supplyDefaults_531 = function supplyDefaults(traceIn, traceOut, defaultCol var ret = array.map(function(attr) { var result = coerce(attr); - if(result && _$lib_422.isArrayOrTypedArray(result)) return result; + if(result && _$lib_423.isArrayOrTypedArray(result)) return result; return null; }); @@ -96519,7 +97198,7 @@ var _$supplyDefaults_531 = function supplyDefaults(traceIn, traceOut, defaultCol }); } - var handleCalendarDefaults = _$registry_518.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_519.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); // Coerce remaining properties @@ -96572,11 +97251,11 @@ var _$supplyDefaults_531 = function supplyDefaults(traceIn, traceOut, defaultCol var Mesh3D = {}; -Mesh3D.attributes = _$attributes_527; -Mesh3D.supplyDefaults = _$supplyDefaults_531; -Mesh3D.calc = _$calc_528; -Mesh3D.colorbar = _$colorbar_529; -Mesh3D.plot = _$createMesh3DTrace_530; +Mesh3D.attributes = _$attributes_528; +Mesh3D.supplyDefaults = _$supplyDefaults_532; +Mesh3D.calc = _$calc_529; +Mesh3D.colorbar = _$colorbar_530; +Mesh3D.plot = _$createMesh3DTrace_531; Mesh3D.moduleType = 'trace'; Mesh3D.name = 'mesh3d', @@ -96586,7 +97265,7 @@ Mesh3D.meta = { }; -var _$Mesh3D_532 = Mesh3D; +var _$Mesh3D_533 = Mesh3D; /** * Copyright 2012-2018, Plotly, Inc. @@ -96598,7 +97277,7 @@ var _$Mesh3D_532 = Mesh3D; 'use strict'; -var _$mesh3d_5 = _$Mesh3D_532; +var _$mesh3d_5 = _$Mesh3D_533; /** * Copyright 2012-2018, Plotly, Inc. @@ -96642,7 +97321,7 @@ var _$gl3d_dashes_400 = { longdashdot: [[0.5, 0.7, 0.8, 1], 10] }; -var _$attributes_561 = {}; +var _$attributes_562 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -96653,18 +97332,18 @@ var _$attributes_561 = {}; 'use strict'; -/* removed: var _$attributes_536 = require('../scatter/attributes'); */; +/* removed: var _$attributes_537 = require('../scatter/attributes'); */; /* removed: var _$makeColorScaleAttributes_307 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_463 = require('../../plots/attributes'); */; +/* removed: var _$attributes_464 = require('../../plots/attributes'); */; /* removed: var _$gl3d_dashes_400 = require('../../constants/gl3d_dashes'); */; /* removed: var _$gl3d_markers_401 = require('../../constants/gl3d_markers'); */; -var __extendFlat_561 = _$extend_414.extendFlat; -var __overrideAll_561 = _$edit_types_451.overrideAll; +var __extendFlat_562 = _$extend_415.extendFlat; +var __overrideAll_562 = _$edit_types_452.overrideAll; -var __scatterLineAttrs_561 = _$attributes_536.line; -var __scatterMarkerAttrs_561 = _$attributes_536.marker; -var scatterMarkerLineAttrs = __scatterMarkerAttrs_561.line; +var __scatterLineAttrs_562 = _$attributes_537.line; +var __scatterMarkerAttrs_562 = _$attributes_537.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_562.line; function makeProjectionAttr(axLetter) { return { @@ -96693,22 +97372,22 @@ function makeProjectionAttr(axLetter) { }; } -var __attrs_561 = _$attributes_561 = __overrideAll_561({ - x: _$attributes_536.x, - y: _$attributes_536.y, +var __attrs_562 = _$attributes_562 = __overrideAll_562({ + x: _$attributes_537.x, + y: _$attributes_537.y, z: { valType: 'data_array', }, - text: __extendFlat_561({}, _$attributes_536.text, { + text: __extendFlat_562({}, _$attributes_537.text, { }), - hovertext: __extendFlat_561({}, _$attributes_536.hovertext, { + hovertext: __extendFlat_562({}, _$attributes_537.hovertext, { }), - mode: __extendFlat_561({}, _$attributes_536.mode, // shouldn't this be on-par with 2D? + mode: __extendFlat_562({}, _$attributes_537.mode, // shouldn't this be on-par with 2D? {dflt: 'lines+markers'}), surfaceaxis: { valType: 'enumerated', @@ -96727,9 +97406,9 @@ var __attrs_561 = _$attributes_561 = __overrideAll_561({ y: makeProjectionAttr('y'), z: makeProjectionAttr('z') }, - connectgaps: _$attributes_536.connectgaps, - line: __extendFlat_561({ - width: __scatterLineAttrs_561.width, + connectgaps: _$attributes_537.connectgaps, + line: __extendFlat_562({ + width: __scatterLineAttrs_562.width, dash: { valType: 'enumerated', values: Object.keys(_$gl3d_dashes_400), @@ -96746,7 +97425,7 @@ var __attrs_561 = _$attributes_561 = __overrideAll_561({ }, _$makeColorScaleAttributes_307('line') ), - marker: __extendFlat_561({ // Parity with scatter.js? + marker: __extendFlat_562({ // Parity with scatter.js? symbol: { valType: 'enumerated', values: Object.keys(_$gl3d_markers_401), @@ -96755,19 +97434,19 @@ var __attrs_561 = _$attributes_561 = __overrideAll_561({ arrayOk: true, }, - size: __extendFlat_561({}, __scatterMarkerAttrs_561.size, {dflt: 8}), - sizeref: __scatterMarkerAttrs_561.sizeref, - sizemin: __scatterMarkerAttrs_561.sizemin, - sizemode: __scatterMarkerAttrs_561.sizemode, - opacity: __extendFlat_561({}, __scatterMarkerAttrs_561.opacity, { + size: __extendFlat_562({}, __scatterMarkerAttrs_562.size, {dflt: 8}), + sizeref: __scatterMarkerAttrs_562.sizeref, + sizemin: __scatterMarkerAttrs_562.sizemin, + sizemode: __scatterMarkerAttrs_562.sizemode, + opacity: __extendFlat_562({}, __scatterMarkerAttrs_562.opacity, { arrayOk: false, }), - showscale: __scatterMarkerAttrs_561.showscale, - colorbar: __scatterMarkerAttrs_561.colorbar, + showscale: __scatterMarkerAttrs_562.showscale, + colorbar: __scatterMarkerAttrs_562.colorbar, - line: __extendFlat_561({ - width: __extendFlat_561({}, scatterMarkerLineAttrs.width, {arrayOk: false}) + line: __extendFlat_562({ + width: __extendFlat_562({}, scatterMarkerLineAttrs.width, {arrayOk: false}) }, _$makeColorScaleAttributes_307('marker.line') ) @@ -96775,13 +97454,13 @@ var __attrs_561 = _$attributes_561 = __overrideAll_561({ _$makeColorScaleAttributes_307('marker') ), - textposition: __extendFlat_561({}, _$attributes_536.textposition, {dflt: 'top center'}), - textfont: _$attributes_536.textfont, + textposition: __extendFlat_562({}, _$attributes_537.textposition, {dflt: 'top center'}), + textfont: _$attributes_537.textfont, - hoverinfo: __extendFlat_561({}, _$attributes_463.hoverinfo) + hoverinfo: __extendFlat_562({}, _$attributes_464.hoverinfo) }, 'calc', 'nested'); -__attrs_561.x.editType = __attrs_561.y.editType = __attrs_561.z.editType = 'calc+clearAxisTypes'; +__attrs_562.x.editType = __attrs_562.y.editType = __attrs_562.z.editType = 'calc+clearAxisTypes'; /** * Copyright 2012-2018, Plotly, Inc. @@ -96793,8 +97472,8 @@ __attrs_561.x.editType = __attrs_561.y.editType = __attrs_561.z.editType = 'calc 'use strict'; -/* removed: var _$arraysToCalcdata_535 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcMarkerColorscale_541 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_536 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcMarkerColorscale_542 = require('../scatter/colorscale_calc'); */; /** @@ -96802,11 +97481,11 @@ __attrs_561.x.editType = __attrs_561.y.editType = __attrs_561.z.editType = 'calc * calcdata the way Scatter.plot does, so that legends and * popovers know what to do with them. */ -var _$calc_562 = function calc(gd, trace) { +var _$calc_563 = function calc(gd, trace) { var cd = [{x: false, y: false, trace: trace, t: {}}]; - _$arraysToCalcdata_535(cd, trace); - _$calcMarkerColorscale_541(trace); + _$arraysToCalcdata_536(cd, trace); + _$calcMarkerColorscale_542(trace); return cd; }; @@ -98439,7 +99118,7 @@ function formatColor(containerIn, opacityIn, len) { return colorOut; } -var _$formatColor_419 = formatColor; +var _$formatColor_420 = formatColor; /** * Copyright 2012-2018, Plotly, Inc. @@ -98508,7 +99187,7 @@ function calculateErrors(data, scaleFactor) { return errorBounds; } -var _$calculateErrors_563 = calculateErrors; +var _$calculateErrors_564 = calculateErrors; /** * Copyright 2012-2018, Plotly, Inc. @@ -98527,14 +99206,14 @@ var _$calculateErrors_563 = calculateErrors; /* removed: var _$createSimplicialMesh_133 = require('gl-mesh3d'); */; /* removed: var _$triangulate_81 = require('delaunay-triangulate'); */; -/* removed: var _$lib_422 = require('../../lib'); */; -/* removed: var _$str2RgbaArray_444 = require('../../lib/str2rgbarray'); */; -/* removed: var _$formatColor_419 = require('../../lib/gl_format_color'); */; -/* removed: var _$makeBubbleSizeFn_553 = require('../scatter/make_bubble_size_func'); */; +/* removed: var _$lib_423 = require('../../lib'); */; +/* removed: var _$str2RgbaArray_445 = require('../../lib/str2rgbarray'); */; +/* removed: var _$formatColor_420 = require('../../lib/gl_format_color'); */; +/* removed: var _$makeBubbleSizeFn_554 = require('../scatter/make_bubble_size_func'); */; /* removed: var _$gl3d_dashes_400 = require('../../constants/gl3d_dashes'); */; /* removed: var _$gl3d_markers_401 = require('../../constants/gl3d_markers'); */; -/* removed: var _$calculateErrors_563 = require('./calc_errors'); */; +/* removed: var _$calculateErrors_564 = require('./calc_errors'); */; function LineWithMarkers(scene, uid) { this.scene = scene; @@ -98555,9 +99234,9 @@ function LineWithMarkers(scene, uid) { this.data = null; } -var __proto_564 = LineWithMarkers.prototype; +var __proto_565 = LineWithMarkers.prototype; -__proto_564.handlePick = function(selection) { +__proto_565.handlePick = function(selection) { if(selection.object && (selection.object === this.linePlot || selection.object === this.delaunayMesh || @@ -98632,7 +99311,7 @@ function calculateErrorParams(errors) { if(!e) continue; capSize[i] = e.width / 2; // ballpark rescaling - color[i] = _$str2RgbaArray_444(e.color); + color[i] = _$str2RgbaArray_445(e.color); lineWidth = e.thickness; } @@ -98664,7 +99343,7 @@ function calculateSymbol(symbolIn) { function formatParam(paramIn, len, calculate, dflt, extraFn) { var paramOut = null; - if(_$lib_422.isArrayOrTypedArray(paramIn)) { + if(_$lib_423.isArrayOrTypedArray(paramIn)) { paramOut = []; for(var i = 0; i < len; i++) { @@ -98673,7 +99352,7 @@ function formatParam(paramIn, len, calculate, dflt, extraFn) { } } - else paramOut = calculate(paramIn, _$lib_422.identity); + else paramOut = calculate(paramIn, _$lib_423.identity); return paramOut; } @@ -98723,26 +99402,26 @@ function convertPlotlyOptions(scene, data) { }; if('line' in data) { - params.lineColor = _$formatColor_419(line, 1, len); + params.lineColor = _$formatColor_420(line, 1, len); params.lineWidth = line.width; params.lineDashes = line.dash; } if('marker' in data) { - var sizeFn = _$makeBubbleSizeFn_553(data); + var sizeFn = _$makeBubbleSizeFn_554(data); - params.scatterColor = _$formatColor_419(marker, 1, len); + params.scatterColor = _$formatColor_420(marker, 1, len); params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn); params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, '●'); params.scatterLineWidth = marker.line.width; // arrayOk === false - params.scatterLineColor = _$formatColor_419(marker.line, 1, len); + params.scatterLineColor = _$formatColor_420(marker.line, 1, len); params.scatterAngle = 0; } if('textposition' in data) { params.textOffset = calculateTextOffset(data.textposition); // arrayOk === false - params.textColor = _$formatColor_419(data.textfont, 1, len); - params.textSize = formatParam(data.textfont.size, len, _$lib_422.identity, 12); + params.textColor = _$formatColor_420(data.textfont, 1, len); + params.textSize = formatParam(data.textfont.size, len, _$lib_423.identity, 12); params.textFont = data.textfont.family; // arrayOk === false params.textAngle = 0; } @@ -98759,7 +99438,7 @@ function convertPlotlyOptions(scene, data) { } } - params.errorBounds = _$calculateErrors_563(data, scaleFactor); + params.errorBounds = _$calculateErrors_564(data, scaleFactor); var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]); params.errorColor = errorParams.color; @@ -98767,7 +99446,7 @@ function convertPlotlyOptions(scene, data) { params.errorCapSize = errorParams.capSize; params.delaunayAxis = data.surfaceaxis; - params.delaunayColor = _$str2RgbaArray_444(data.surfacecolor); + params.delaunayColor = _$str2RgbaArray_445(data.surfacecolor); return params; } @@ -98786,7 +99465,7 @@ function arrayToColor(color) { return null; } -__proto_564.update = function(data) { +__proto_565.update = function(data) { var gl = this.scene.glplot.gl, lineOptions, scatterOptions, @@ -98949,7 +99628,7 @@ __proto_564.update = function(data) { } }; -__proto_564.dispose = function() { +__proto_565.dispose = function() { if(this.linePlot) { this.scene.glplot.remove(this.linePlot); this.linePlot.dispose(); @@ -98978,7 +99657,7 @@ function createLineWithMarkers(scene, data) { return plot; } -var _$createLineWithMarkers_564 = createLineWithMarkers; +var _$createLineWithMarkers_565 = createLineWithMarkers; /** * Copyright 2012-2018, Plotly, Inc. @@ -98991,20 +99670,20 @@ var _$createLineWithMarkers_564 = createLineWithMarkers; 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; -/* removed: var _$subtypes_558 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_554 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_549 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_559 = require('../scatter/text_defaults'); */; +/* removed: var _$subtypes_559 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_555 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_550 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_560 = require('../scatter/text_defaults'); */; -/* removed: var _$attributes_561 = require('./attributes'); */; +/* removed: var _$attributes_562 = require('./attributes'); */; -var _$supplyDefaults_565 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_566 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_422.coerce(traceIn, traceOut, _$attributes_561, attr, dflt); + return _$lib_423.coerce(traceIn, traceOut, _$attributes_562, attr, dflt); } var len = handleXYZDefaults(traceIn, traceOut, coerce, layout); @@ -99017,17 +99696,17 @@ var _$supplyDefaults_565 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_558.hasLines(traceOut)) { + if(_$subtypes_559.hasLines(traceOut)) { coerce('connectgaps'); - _$lineDefaults_549(traceIn, traceOut, defaultColor, layout, coerce); + _$lineDefaults_550(traceIn, traceOut, defaultColor, layout, coerce); } - if(_$subtypes_558.hasMarkers(traceOut)) { - _$markerDefaults_554(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true}); + if(_$subtypes_559.hasMarkers(traceOut)) { + _$markerDefaults_555(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true}); } - if(_$subtypes_558.hasText(traceOut)) { - _$text_defaults_559(traceIn, traceOut, layout, coerce, {noSelect: true}); + if(_$subtypes_559.hasText(traceOut)) { + _$text_defaults_560(traceIn, traceOut, layout, coerce, {noSelect: true}); } var lineColor = (traceOut.line || {}).color, @@ -99043,7 +99722,7 @@ var _$supplyDefaults_565 = function supplyDefaults(traceIn, traceOut, defaultCol } } - var errorBarsSupplyDefaults = _$registry_518.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_519.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'z'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y', inherit: 'z'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'z'}); @@ -99055,7 +99734,7 @@ function handleXYZDefaults(traceIn, traceOut, coerce, layout) { y = coerce('y'), z = coerce('z'); - var handleCalendarDefaults = _$registry_518.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_519.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); if(x && y && z) { @@ -99079,12 +99758,12 @@ function handleXYZDefaults(traceIn, traceOut, coerce, layout) { var Scatter3D = {}; -Scatter3D.plot = _$createLineWithMarkers_564; -Scatter3D.attributes = _$attributes_561; +Scatter3D.plot = _$createLineWithMarkers_565; +Scatter3D.attributes = _$attributes_562; Scatter3D.markerSymbols = _$gl3d_markers_401; -Scatter3D.supplyDefaults = _$supplyDefaults_565; -Scatter3D.colorbar = _$colorbar_540; -Scatter3D.calc = _$calc_562; +Scatter3D.supplyDefaults = _$supplyDefaults_566; +Scatter3D.colorbar = _$colorbar_541; +Scatter3D.calc = _$calc_563; Scatter3D.moduleType = 'trace'; Scatter3D.name = 'scatter3d'; @@ -99095,7 +99774,7 @@ Scatter3D.meta = { }; -var _$Scatter3D_566 = Scatter3D; +var _$Scatter3D_567 = Scatter3D; /** * Copyright 2012-2018, Plotly, Inc. @@ -99107,7 +99786,7 @@ var _$Scatter3D_566 = Scatter3D; 'use strict'; -var _$scatter3d_6 = _$Scatter3D_566; +var _$scatter3d_6 = _$Scatter3D_567; /** * Copyright 2012-2018, Plotly, Inc. @@ -99124,7 +99803,7 @@ var _$scatter3d_6 = _$Scatter3D_566; // Compute auto-z and autocolorscale if applicable -var _$calc_568 = function calc(gd, trace) { +var _$calc_569 = function calc(gd, trace) { if(trace.surfacecolor) { _$calc_306(trace, trace.surfacecolor, '', 'c'); } else { @@ -99145,21 +99824,21 @@ var _$calc_568 = function calc(gd, trace) { /* removed: var _$fastIsnumeric_89 = require('fast-isnumeric'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$plots_510 = require('../../plots/plots'); */; /* removed: var _$colorscale_314 = require('../../components/colorscale'); */; /* removed: var _$draw_303 = require('../../components/colorbar/draw'); */; -var _$colorbar_569 = function colorbar(gd, cd) { +var _$colorbar_570 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, cmin = trace.cmin, cmax = trace.cmax, vals = trace.surfacecolor || trace.z; - if(!_$fastIsnumeric_89(cmin)) cmin = _$lib_422.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_89(cmax)) cmax = _$lib_422.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_89(cmin)) cmin = _$lib_423.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_89(cmax)) cmax = _$lib_423.aggNums(Math.max, null, vals); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); @@ -101175,8 +101854,8 @@ function applyHomography(dest, src, Xi) { /* removed: var _$ndarrayOps_201 = require('ndarray-ops'); */; /* removed: var _$tinycolor_264 = require('tinycolor2'); */; -var __isArrayOrTypedArray_570 = _$lib_422.isArrayOrTypedArray; -/* removed: var _$str2RgbaArray_444 = require('../../lib/str2rgbarray'); */; +var __isArrayOrTypedArray_571 = _$lib_423.isArrayOrTypedArray; +/* removed: var _$str2RgbaArray_445 = require('../../lib/str2rgbarray'); */; var MIN_RESOLUTION = 128; @@ -101189,9 +101868,9 @@ function SurfaceTrace(scene, surface, uid) { this.dataScale = 1.0; } -var __proto_570 = SurfaceTrace.prototype; +var __proto_571 = SurfaceTrace.prototype; -__proto_570.handlePick = function(selection) { +__proto_571.handlePick = function(selection) { if(selection.object === this.surface) { var selectIndex = selection.index = [ Math.min( @@ -101205,17 +101884,17 @@ __proto_570.handlePick = function(selection) { ]; var traceCoordinate = [0, 0, 0]; - if(!__isArrayOrTypedArray_570(this.data.x)) { + if(!__isArrayOrTypedArray_571(this.data.x)) { traceCoordinate[0] = selectIndex[0]; - } else if(__isArrayOrTypedArray_570(this.data.x[0])) { + } else if(__isArrayOrTypedArray_571(this.data.x[0])) { traceCoordinate[0] = this.data.x[selectIndex[1]][selectIndex[0]]; } else { traceCoordinate[0] = this.data.x[selectIndex[0]]; } - if(!__isArrayOrTypedArray_570(this.data.y)) { + if(!__isArrayOrTypedArray_571(this.data.y)) { traceCoordinate[1] = selectIndex[1]; - } else if(__isArrayOrTypedArray_570(this.data.y[0])) { + } else if(__isArrayOrTypedArray_571(this.data.y[0])) { traceCoordinate[1] = this.data.y[selectIndex[1]][selectIndex[0]]; } else { traceCoordinate[1] = this.data.y[selectIndex[1]]; @@ -101251,7 +101930,7 @@ __proto_570.handlePick = function(selection) { } }; -function __parseColorScale_570(colorscale, alpha) { +function __parseColorScale_571(colorscale, alpha) { if(alpha === undefined) alpha = 1; return colorscale.map(function(elem) { @@ -101278,7 +101957,7 @@ function isColormapCircular(colormap) { } // Pad coords by +1 -function __padField_570(field) { +function __padField_571(field) { var shape = field.shape; var nshape = [shape[0] + 2, shape[1] + 2]; var nfield = _$wrappedNDArrayCtor_207(new Float32Array(nshape[0] * nshape[1]), nshape); @@ -101316,7 +101995,7 @@ function refine(coords) { var nsize = nshape[0] * nshape[1]; for(var i = 0; i < coords.length; ++i) { - var padImg = __padField_570(coords[i]); + var padImg = __padField_571(coords[i]); var scaledImg = _$wrappedNDArrayCtor_207(new Float32Array(nsize), nshape); _$applyHomography_199(scaledImg, padImg, [scaleF, 0, 0, 0, scaleF, 0, @@ -101330,7 +102009,7 @@ function refine(coords) { return 1.0; } -__proto_570.setContourLevels = function() { +__proto_571.setContourLevels = function() { var nlevels = [[], [], []]; var needsUpdate = false; @@ -101346,13 +102025,13 @@ __proto_570.setContourLevels = function() { } }; -__proto_570.update = function(data) { +__proto_571.update = function(data) { var i, scene = this.scene, sceneLayout = scene.fullSceneLayout, surface = this.surface, alpha = data.opacity, - colormap = __parseColorScale_570(data.colorscale, alpha), + colormap = __parseColorScale_571(data.colorscale, alpha), z = data.z, x = data.x, y = data.y, @@ -101391,11 +102070,11 @@ __proto_570.update = function(data) { }); // coords x - if(!__isArrayOrTypedArray_570(x)) { + if(!__isArrayOrTypedArray_571(x)) { _$ndarrayFill_197(xc, function(row) { return xaxis.d2l(row, 0, xcalendar) * scaleFactor[0]; }); - } else if(__isArrayOrTypedArray_570(x[0])) { + } else if(__isArrayOrTypedArray_571(x[0])) { _$ndarrayFill_197(xc, function(row, col) { return xaxis.d2l(x[col][row], 0, xcalendar) * scaleFactor[0]; }); @@ -101407,11 +102086,11 @@ __proto_570.update = function(data) { } // coords y - if(!__isArrayOrTypedArray_570(x)) { + if(!__isArrayOrTypedArray_571(x)) { _$ndarrayFill_197(yc, function(row, col) { return yaxis.d2l(col, 0, xcalendar) * scaleFactor[1]; }); - } else if(__isArrayOrTypedArray_570(y[0])) { + } else if(__isArrayOrTypedArray_571(y[0])) { _$ndarrayFill_197(yc, function(row, col) { return yaxis.d2l(y[col][row], 0, ycalendar) * scaleFactor[1]; }); @@ -101485,7 +102164,7 @@ __proto_570.update = function(data) { if(contourParams.show) { this.showContour[i] = true; params.levels[i] = contourLevels[i]; - surface.highlightColor[i] = params.contourColor[i] = _$str2RgbaArray_444(contourParams.color); + surface.highlightColor[i] = params.contourColor[i] = _$str2RgbaArray_445(contourParams.color); if(contourParams.usecolormap) { surface.highlightTint[i] = params.contourTint[i] = 0; @@ -101499,7 +102178,7 @@ __proto_570.update = function(data) { } if(contourParams.highlight) { - params.dynamicColor[i] = _$str2RgbaArray_444(contourParams.highlightcolor); + params.dynamicColor[i] = _$str2RgbaArray_445(contourParams.highlightcolor); params.dynamicWidth[i] = contourParams.highlightwidth; } } @@ -101535,7 +102214,7 @@ __proto_570.update = function(data) { } }; -__proto_570.dispose = function() { +__proto_571.dispose = function() { this.scene.glplot.remove(this.surface); this.surface.dispose(); }; @@ -101550,7 +102229,7 @@ function createSurfaceTrace(scene, data) { return result; } -var _$createSurfaceTrace_570 = createSurfaceTrace; +var _$createSurfaceTrace_571 = createSurfaceTrace; /** * Copyright 2012-2018, Plotly, Inc. @@ -101563,18 +102242,18 @@ var _$createSurfaceTrace_570 = createSurfaceTrace; 'use strict'; -/* removed: var _$registry_518 = require('../../registry'); */; -/* removed: var _$lib_422 = require('../../lib'); */; +/* removed: var _$registry_519 = require('../../registry'); */; +/* removed: var _$lib_423 = require('../../lib'); */; /* removed: var _$colorScaleDefaults_309 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_567 = require('./attributes'); */; +/* removed: var _$attributes_568 = require('./attributes'); */; -var _$supplyDefaults_571 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_572 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { var i, j; function coerce(attr, dflt) { - return _$lib_422.coerce(traceIn, traceOut, _$attributes_567, attr, dflt); + return _$lib_423.coerce(traceIn, traceOut, _$attributes_568, attr, dflt); } var z = coerce('z'); @@ -101586,10 +102265,10 @@ var _$supplyDefaults_571 = function supplyDefaults(traceIn, traceOut, defaultCol var x = coerce('x'); coerce('y'); - traceOut._xlength = (Array.isArray(x) && _$lib_422.isArrayOrTypedArray(x[0])) ? z.length : z[0].length; + traceOut._xlength = (Array.isArray(x) && _$lib_423.isArrayOrTypedArray(x[0])) ? z.length : z[0].length; traceOut._ylength = z.length; - var handleCalendarDefaults = _$registry_518.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_519.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); coerce('text'); @@ -101671,11 +102350,11 @@ function mapLegacy(traceIn, oldAttr, newAttr) { var Surface = {}; -Surface.attributes = _$attributes_567; -Surface.supplyDefaults = _$supplyDefaults_571; -Surface.colorbar = _$colorbar_569; -Surface.calc = _$calc_568; -Surface.plot = _$createSurfaceTrace_570; +Surface.attributes = _$attributes_568; +Surface.supplyDefaults = _$supplyDefaults_572; +Surface.colorbar = _$colorbar_570; +Surface.calc = _$calc_569; +Surface.plot = _$createSurfaceTrace_571; Surface.moduleType = 'trace'; Surface.name = 'surface'; @@ -101685,7 +102364,7 @@ Surface.meta = { }; -var _$Surface_572 = Surface; +var _$Surface_573 = Surface; /** * Copyright 2012-2018, Plotly, Inc. @@ -101697,7 +102376,7 @@ var _$Surface_572 = Surface; 'use strict'; -var _$surface_7 = _$Surface_572; +var _$surface_7 = _$Surface_573; /** * Copyright 2012-2018, Plotly, Inc. diff --git a/dist/plotly-gl3d.min.js b/dist/plotly-gl3d.min.js index 3f98152f970..21afcbebfe3 100644 --- a/dist/plotly-gl3d.min.js +++ b/dist/plotly-gl3d.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (gl3d - minified) v1.35.2 +* plotly.js (gl3d - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){var t={exports:{}};!function(){var e={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},i=this.document;function a(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(i)try{n(i.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),i)try{i.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var s=this.Element.prototype,l=s.setAttribute,u=s.setAttributeNS,c=this.CSSStyleDeclaration.prototype,h=c.setProperty;s.setAttribute=function(t,e){l.call(this,t,e+"")},s.setAttributeNS=function(t,e,r){u.call(this,t,e,r+"")},c.setProperty=function(t,e,r){h.call(this,t,e+"",r)}}function f(t,e){return te?1:t>=e?0:NaN}function d(t){return null===t?NaN:+t}function p(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}e.ascending=f,e.descending=function(t,e){return et?1:e>=t?0:NaN},e.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},e.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},e.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),i=n){r=i=n;break}for(;++an&&(r=n),i1)return o/(l-1)},e.deviation=function(){var t=e.variance.apply(this,arguments);return t?Math.sqrt(t):t};var v=g(f);function m(t){return t.length}e.bisectLeft=v.left,e.bisect=e.bisectRight=v.right,e.bisector=function(t){return g(1===t.length?function(e,r){return f(t(e),r)}:t)},e.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},e.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},e.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function b(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function x(){this._=Object.create(null)}e.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=i.length)return r?r.call(n,a):t?a.sort(t):a;for(var l,u,c,h,f=-1,d=a.length,p=i[s++],g=new x;++f=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(e.map,t,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(e){return t=e,n},n.rollup=function(t){return r=t,n},n},e.set=function(t){var e=new S;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},e.event=null,e.requote=function(t){return t.replace(U,"\\$&")};var U=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,V={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function H(t){return V(t,W),t}var q=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},X=function(t,e){var r=t.matches||t[O(t,"matchesSelector")];return(X=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(q=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,X=Sizzle.matchesSelector),e.selection=function(){return e.select(i.documentElement)};var W=e.selection.prototype=[];function Y(t){return"function"==typeof t?t:function(){return q(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}W.select=function(t){var e,r,n,i,a=[];t=Y(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},W.attr=function(t,r){if(arguments.length<2){if("string"==typeof t){var n=this.node();return(t=e.ns.qualify(t)).local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(r in t)this.each($(r,t[r]));return this}return this.each($(t,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=f);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(t=t.slice(0,o));var l=pt.get(t);function u(){var e=this[a];e&&(this.removeEventListener(t,e,e.$),delete this[a])}return l&&(t=l,s=vt),o?r?function(){var e=s(r,n(arguments));u.call(this),this.addEventListener(t,this[a]=e,e.$=i),e._=r}:u:r?N:function(){var r,n=new RegExp("^__on([^.]+)"+e.requote(t)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}e.selection.enter=ht,e.selection.enter.prototype=ft,ft.append=W.append,ft.empty=W.empty,ft.node=W.node,ft.call=W.call,ft.size=W.size,ft.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s=n&&(n=e+1);!(o=s[n])&&++n0?1:t<0?-1:0}function Rt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function Ot(t){return t>1?0:t<-1?Tt:Math.acos(t)}function It(t){return t>1?Lt:t<-1?-Lt:Math.asin(t)}function Nt(t){return((t=Math.exp(t))+1/t)/2}function Dt(t){return(t=Math.sin(t/2))*t}var zt=Math.SQRT2;e.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,h=l-a,f=c*c+h*h;if(f0&&(t=t.transition().duration(g)),t.call(w.event)}function E(){u&&u.domain(l.range().map(function(t){return(t-f.x)/f.k}).map(l.invert)),h&&h.domain(c.range().map(function(t){return(t-f.y)/f.k}).map(c.invert))}function L(t){v++||t({type:"zoomstart"})}function C(t){E(),t({type:"zoom",scale:f.k,translate:[f.x,f.y]})}function S(t){--v||(t({type:"zoomend"}),r=null)}function P(){var t=this,r=_.of(t,arguments),n=0,i=e.select(o(t)).on(y,function(){n=1,T(e.mouse(t),a),C(r)}).on(b,function(){i.on(y,null).on(b,null),s(n),S(r)}),a=M(e.mouse(t)),s=bt(t);ss.call(t),L(r)}function R(){var t,r=this,n=_.of(r,arguments),i={},a=0,o=".zoom-"+e.event.changedTouches[0].identifier,l="touchmove"+o,u="touchend"+o,c=[],h=e.select(r),d=bt(r);function p(){var n=e.touches(r);return t=f.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=M(t))}),n}function g(){var t=e.event.target;e.select(t).on(l,v).on(u,y),c.push(t);for(var n=e.event.changedTouches,o=0,h=n.length;o1){m=d[0];var b=d[1],x=m[0]-b[0],_=m[1]-b[1];a=x*x+_*_}}function v(){var o,l,u,c,h=e.touches(r);ss.call(r);for(var f=0,d=h.length;f360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Gt(t,r,n){return this instanceof Gt?(this.h=+t,this.c=+r,void(this.l=+n)):arguments.length<2?t instanceof Gt?new Gt(t.h,t.c,t.l):ee(t instanceof Yt?t.l:(t=fe((t=e.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new Gt(t,r,n)}Ht.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,this.l/t)},Ht.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,t*this.l)},Ht.rgb=function(){return qt(this.h,this.s,this.l)},e.hcl=Gt;var Xt=Gt.prototype=new Ut;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Yt(r,Math.cos(t*=Ct)*e,Math.sin(t)*e)}function Yt(t,e,r){return this instanceof Yt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Yt?new Yt(t.l,t.a,t.b):t instanceof Gt?Wt(t.h,t.c,t.l):fe((t=ae(t)).r,t.g,t.b):new Yt(t,e,r)}Xt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Xt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Xt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},e.lab=Yt;var Zt=18,Qt=.95047,Kt=1,$t=1.08883,Jt=Yt.prototype=new Ut;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*Qt)-1.5371385*(n=re(n)*Kt)-.4985314*(a=re(a)*$t)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*St,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ce(""+t,ae,qt):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}Jt.brighter=function(t){return new Yt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},Jt.darker=function(t){return new Yt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},Jt.rgb=function(){return te(this.l,this.a,this.b)},e.rgb=ae;var le=ae.prototype=new Ut;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(pe(i[0]),pe(i[1]),pe(i[2]))}return(a=ge.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function he(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e0&&l<1?0:n),new Vt(n,i,l)}function fe(t,e,r){var n=ne((.4124564*(t=de(t))+.3575761*(e=de(e))+.1804375*(r=de(r)))/Qt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Yt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function de(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function pe(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(o,u)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(t)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=h:u.onreadystatechange=function(){u.readyState>3&&h()},u.onprogress=function(t){var r=e.event;e.event=t;try{s.progress.call(o,u)}finally{e.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(e,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),u.open(e,t,!0),null==r||"accept"in l||(l.accept=r+",*/*"),u.setRequestHeader)for(var a in l)u.setRequestHeader(a,l[a]);return null!=r&&u.overrideMimeType&&u.overrideMimeType(r),null!=c&&(u.responseType=c),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,u),u.send(null==n?null:n),o},o.abort=function(){return u.abort(),o},e.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}ge.forEach(function(t,e){ge.set(t,oe(e))}),e.functor=ve,e.xhr=me(P),e.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ye(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,u=0,c=0;function h(){if(u>=l)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),_e=0):(_e=1,Me(Te))}function ke(){for(var t=Date.now(),e=be;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Ee(){for(var t,e=be,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});e.formatPrefix=function(t,r){var n=0;return(t=+t)&&(t<0&&(t*=-1),r&&(t=e.round(t,Le(t,r))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Ce[8+n/3]};var Se=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pe=e.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,r){return(t=e.round(t,Le(t,r))).toFixed(Math.max(0,Math.min(20,Le(t*(1+1e-15),r))))}});function Re(t){return t+""}var Oe=e.time={},Ie=Date;function Ne(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Ne.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(){De.setUTCDate.apply(this._,arguments)},setDay:function(){De.setUTCDay.apply(this._,arguments)},setFullYear:function(){De.setUTCFullYear.apply(this._,arguments)},setHours:function(){De.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){De.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){De.setUTCMinutes.apply(this._,arguments)},setMonth:function(){De.setUTCMonth.apply(this._,arguments)},setSeconds:function(){De.setUTCSeconds.apply(this._,arguments)},setTime:function(){De.setTime.apply(this._,arguments)}};var De=Date.prototype;function ze(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r1)for(;o68?1900:2e3),r+i[0].length):-1}function Qe(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Je(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,i=y(e)%60;return r+Ve(n,"0",2)+Ve(i,"0",2)}function ar(t,e,r){Ue.lastIndex=0;var n=Ue.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:P;return function(t){var n=Se.exec(t),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",u=n[4]||"",c=n[5],h=+n[6],f=n[7],d=n[8],p=n[9],g=1,v="",m="",y=!1,b=!0;switch(d&&(d=+d.substring(1)),(c||"0"===i&&"="===s)&&(c=i="0",s="="),p){case"n":f=!0,p="g";break;case"%":g=100,m="%",p="f";break;case"p":g=100,m="%",p="r";break;case"b":case"o":case"x":case"X":"#"===u&&(v="0"+p.toLowerCase());case"c":b=!1;case"d":y=!0,d=0;break;case"s":g=-1,p="r"}"$"===u&&(v=a[0],m=a[1]),"r"!=p||d||(p="g"),null!=d&&("g"==p?d=Math.max(1,Math.min(21,d)):"e"!=p&&"f"!=p||(d=Math.max(0,Math.min(20,d)))),p=Pe.get(p)||Re;var x=c&&f;return function(t){var n=m;if(y&&t%1)return"";var a=t<0||0===t&&1/t<0?(t=-t,"-"):"-"===l?"":l;if(g<0){var u=e.formatPrefix(t,d);t=u.scale(t),n=u.symbol+m}else t*=g;var _,w,M=(t=p(t,d)).lastIndexOf(".");if(M<0){var A=b?t.lastIndexOf("e"):-1;A<0?(_=t,w=""):(_=t.substring(0,A),w=t.substring(A))}else _=t.substring(0,M),w=r+t.substring(M+1);!c&&f&&(_=o(_,1/0));var T=v.length+_.length+w.length+(x?0:a.length),k=T"===s?k+a+t:"^"===s?k.substring(0,T>>=1)+a+t+k.substring(T):a+(x?t:k+t))+n}}}(t),timeFormat:function(t){var r=t.dateTime,n=t.date,i=t.time,a=t.periods,o=t.days,s=t.shortDays,l=t.months,u=t.shortMonths;function c(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s=u)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in je?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(Ie=Ne);return r._=t,e(r)}finally{Ie=Date}}return r.parse=function(t){try{Ie=Ne;var r=e.parse(t);return r&&r._}finally{Ie=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var f=e.map(),d=He(o),p=qe(o),g=He(s),v=qe(s),m=He(l),y=qe(l),b=He(u),x=qe(u);a.forEach(function(t,e){f.set(t.toLowerCase(),e)});var _={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:c(r),d:function(t,e){return Ve(t.getDate(),e,2)},e:function(t,e){return Ve(t.getDate(),e,2)},H:function(t,e){return Ve(t.getHours(),e,2)},I:function(t,e){return Ve(t.getHours()%12||12,e,2)},j:function(t,e){return Ve(1+Oe.dayOfYear(t),e,3)},L:function(t,e){return Ve(t.getMilliseconds(),e,3)},m:function(t,e){return Ve(t.getMonth()+1,e,2)},M:function(t,e){return Ve(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return Ve(t.getSeconds(),e,2)},U:function(t,e){return Ve(Oe.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ve(Oe.mondayOfYear(t),e,2)},x:c(n),X:c(i),y:function(t,e){return Ve(t.getFullYear()%100,e,2)},Y:function(t,e){return Ve(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){d.lastIndex=0;var n=d.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){b.lastIndex=0;var n=b.exec(e.slice(r));return n?(t.m=x.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return h(t,_.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Je,L:nr,m:Ke,M:er,p:function(t,e,r){var n=f.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Xe,w:Ge,W:We,x:function(t,e,r){return h(t,_.x.toString(),e,r)},X:function(t,e,r){return h(t,_.X.toString(),e,r)},y:Ze,Y:Ye,Z:Qe,"%":ar};return c}(t)}};var sr=e.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"]});function lr(){}e.format=sr.numberFormat,e.geo={},lr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new lr;function cr(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function hr(t,e){t&&dr.hasOwnProperty(t.type)&&dr[t.type](t,e)}e.geo.stream=function(t,e){t&&fr.hasOwnProperty(t.type)?fr[t.type](t,e):hr(t,e)};var fr={Feature:function(t,e){hr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=o*a,l=Math.cos(e),u=Math.sin(e),c=i*u,h=n*l+c*Math.cos(s),f=c*o*Math.sin(s);Lr.add(Math.atan2(f,h)),r=t,n=l,i=u}Cr.point=function(o,s){Cr.point=a,r=(t=o)*Ct,n=Math.cos(s=(e=s)*Ct/2+Tt/4),i=Math.sin(s)},Cr.lineEnd=function(){a(t,e)}}function Pr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Rr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Or(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Ir(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Nr(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Dr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function zr(t){return[Math.atan2(t[1],t[0]),It(t[2])]}function Fr(t,e){return y(t[0]-e[0])Mt?i=90:u<-Mt&&(r=-90),h[0]=t,h[1]=n}};function d(e,a){c.push(h=[t=e,n=e]),ai&&(i=a)}function p(e,o){var s=Pr([e*Ct,o*Ct]);if(l){var u=Or(l,s),c=Or([u[1],-u[0],0],u);Dr(c),c=zr(c);var h=e-a,f=h>0?1:-1,p=c[0]*St*f,g=y(h)>180;if(g^(f*ai&&(i=v);else if(g^(f*a<(p=(p+360)%360-180)&&pi&&(i=o);g?e_(t,n)&&(n=e):_(e,n)>_(t,n)&&(t=e):n>=t?(en&&(n=e)):e>a?_(t,e)>_(t,n)&&(n=e):_(e,n)>_(t,n)&&(t=e)}else d(e,o);l=s,a=e}function g(){f.point=p}function v(){h[0]=t,h[1]=n,f.point=d,l=null}function m(t,e){if(l){var r=t-a;u+=y(r)>180?r+(r>0?360:-360):r}else o=t,s=e;Cr.point(t,e),p(t,e)}function b(){Cr.lineStart()}function x(){m(o,s),Cr.lineEnd(),y(u)>Mt&&(t=-(n=180)),h[0]=t,h[1]=n,l=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function M(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(g[0],g[1])&&(g[1]=d[1]),_(d[0],g[1])>_(g[0],g[1])&&(g[0]=d[0])):s.push(g=d);for(var l,u,d,p=-1/0,g=(o=0,s[u=s.length-1]);o<=u;g=d,++o)d=s[o],(l=_(g[1],d[0]))>p&&(p=l,t=d[0],n=g[1])}return c=h=null,t===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[t,r],[n,i]]}}(),e.geo.centroid=function(t){mr=yr=br=xr=_r=wr=Mr=Ar=Tr=kr=Er=0,e.geo.stream(t,jr);var r=Tr,n=kr,i=Er,a=r*r+n*n+i*i;return a=0;--s)i.point((h=c[s])[0],h[1]);else n(d.x,d.p.x,-1,i);d=d.p}c=(d=d.o).z,p=!p}while(!d.v);i.lineEnd()}}}function Yr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,M=w*_,A=M>Tt,T=p*b;if(Lr.add(Math.atan2(T*w*Math.sin(M),g*x+T*Math.cos(M))),a+=A?_+w*kt:_,A^f>=r^m>=r){var k=Or(Pr(h),Pr(t));Dr(k);var E=Or(i,k);Dr(E);var L=(A^_>=0?-1:1)*It(E[2]);(n>L||n===L&&(k[0]||k[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;f=m,p=b,g=x,h=t}}return(a<-Mt||a0){for(b||(o.polygonStart(),b=!0),o.lineStart();++a1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return c}}function Kr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:N,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Jr(t,e){return((t=t.x)[0]<0?t[1]-Lt-Mt:Lt-t[1])-((e=e.x)[0]<0?e[1]-Lt-Mt:Lt-e[1])}var tn=Qr(Xr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Tt:-Tt,l=y(a-r);y(l-Tt)0?Lt:-Lt),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Tt&&(y(r-i)Mt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Lt,n.point(-Tt,i),n.point(0,i),n.point(Tt,i),n.point(Tt,0),n.point(Tt,-i),n.point(0,-i),n.point(-Tt,-i),n.point(-Tt,0),n.point(-Tt,i);else if(y(t[0]-e[0])>Mt){var a=t[0]0)){if(a/=f,f<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=r-l,f||!(a<0)){if(a/=f,f<0){if(a>h)return;a>c&&(c=a)}else if(f>0){if(a0)){if(a/=d,d<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=n-u,d||!(a<0)){if(a/=d,d<0){if(a>h)return;a>c&&(c=a)}else if(d>0){if(a0&&(i.a={x:l+c*f,y:u+c*d}),h<1&&(i.b={x:l+h*f,y:u+h*d}),i}}}}}}var rn=1e9;function nn(t,r,n,i){return function(l){var u,c,h,f,d,p,g,v,m,y,b,x=l,_=$r(),w=en(t,r,n,i),M={point:k,lineStart:function(){M.point=E,c&&c.push(h=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){u&&(E(f,d),p&&m&&_.rejoin(),u.push(_.buffer()));M.point=k,m&&l.lineEnd()},polygonStart:function(){l=_,u=[],c=[],b=!0},polygonEnd:function(){l=x,u=e.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],i=0;in&&Rt(u,a,t)>0&&++e:a[1]<=n&&Rt(u,a,t)<0&&--e,u=a;return 0!==e}([t,i]),n=b&&r,a=u.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),A(null,null,1,l),l.lineEnd()),a&&Wr(u,o,r,A,l),l.polygonEnd()),u=c=h=null}};function A(e,o,l,u){var c=0,h=0;if(null==e||(c=a(e,l))!==(h=a(o,l))||s(e,o)<0^l>0)do{u.point(0===c||3===c?t:n,c>1?i:r)}while((c=(c+l+4)%4)!==h);else u.point(o[0],o[1])}function T(e,a){return t<=e&&e<=n&&r<=a&&a<=i}function k(t,e){T(t,e)&&l.point(t,e)}function E(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&h.push([t,e]),y)f=t,d=e,p=r,y=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&m)l.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),b=!1):r&&(l.lineStart(),l.point(t,e),b=!1)}g=t,v=e,m=r}return M};function a(e,i){return y(e[0]-t)0?0:3:y(e[0]-n)0?2:1:y(e[1]-r)0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=En(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,It((i-(t*t+r*r)*n*n)/(2*n))]},o}e.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(e.geo.conicEqualArea=function(){return an(on)}).raw=on,e.geo.albers=function(){return e.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},e.geo.albersUsa=function(){var t,r,n,i,a=e.geo.albers(),o=e.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=e.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,r){t=[e,r]}};function u(e){var a=e[0],o=e[1];return t=null,r(a,o),t||(n(a,o),t)||i(a,o),t}return u.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},u.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),u):a.precision()},u.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),u.translate(a.translate())):a.scale()},u.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),c=+t[0],h=+t[1];return r=a.translate(t).clipExtent([[c-.455*e,h-.238*e],[c+.455*e,h+.238*e]]).stream(l).point,n=o.translate([c-.307*e,h+.201*e]).clipExtent([[c-.425*e+Mt,h+.12*e+Mt],[c-.214*e-Mt,h+.234*e-Mt]]).stream(l).point,i=s.translate([c-.205*e,h+.212*e]).clipExtent([[c-.214*e+Mt,h+.166*e+Mt],[c-.115*e-Mt,h+.234*e-Mt]]).stream(l).point,u},u.scale(1070)};var sn,ln,un,cn,hn,fn,dn={point:N,lineStart:N,lineEnd:N,polygonStart:function(){ln=0,dn.lineStart=pn},polygonEnd:function(){dn.lineStart=dn.lineEnd=dn.point=N,sn+=y(ln/2)}};function pn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}dn.point=function(a,o){dn.point=i,t=r=a,e=n=o},dn.lineEnd=function(){i(t,e)}}var gn={point:function(t,e){thn&&(hn=t);efn&&(fn=e)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,yn={point:bn,lineStart:xn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=bn,yn.lineStart=xn,yn.lineEnd=_n}};function bn(t,e){br+=t,xr+=e,++_r}function xn(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,Mr+=o*(e+n)/2,Ar+=o,bn(t=r,e=n)}yn.point=function(n,i){yn.point=r,bn(t=n,e=i)}}function _n(){yn.point=bn}function wn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,Mr+=o*(n+e)/2,Ar+=o,Tr+=(o=n*t-r*e)*(r+t),kr+=o*(n+e),Er+=3*o,bn(r=t,n=e)}yn.point=function(a,o){yn.point=i,bn(t=r=a,e=n=o)},yn.lineEnd=function(){i(t,e)}}function Mn(t){var e=.5,r=Math.cos(30*Ct),n=16;function i(e){return(n?function(e){var r,i,o,s,l,u,c,h,f,d,p,g,v={point:m,lineStart:y,lineEnd:x,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){h=NaN,v.point=b,e.lineStart()}function b(r,i){var o=Pr([r,i]),s=t(r,i);a(h,f,c,d,p,g,h=s[0],f=s[1],c=r,d=o[0],p=o[1],g=o[2],n,e),e.point(h,f)}function x(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=M}function w(t,e){b(r=t,e),i=h,o=f,s=d,l=p,u=g,v.point=b}function M(){a(h,f,c,d,p,g,i,o,r,s,l,u,n,e),v.lineEnd=x,x()}return v}:function(e){return Tn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,u,c,h,f,d,p,g,v,m){var b=c-n,x=h-i,_=b*b+x*x;if(_>4*e&&v--){var w=s+d,M=l+p,A=u+g,T=Math.sqrt(w*w+M*M+A*A),k=Math.asin(A/=T),E=y(y(A)-1)e||y((b*P+x*R)/_-.5)>.3||s*d+l*p+u*g0&&16,i):Math.sqrt(e)},i}function An(t){this.stream=t}function Tn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function kn(t){return En(function(){return t})()}function En(t){var r,n,i,a,o,s,l=Mn(function(t,e){return[(t=r(t,e))[0]*u+a,o-t[1]*u]}),u=150,c=480,h=250,f=0,d=0,p=0,g=0,v=0,m=tn,b=P,x=null,_=null;function w(t){return[(t=i(t[0]*Ct,t[1]*Ct))[0]*u+a,o-t[1]*u]}function M(t){return(t=i.invert((t[0]-a)/u,(o-t[1])/u))&&[t[0]*St,t[1]*St]}function A(){i=Gr(n=Pn(p,g,v),r);var t=r(f,d);return a=c-t[0]*u,o=h+t[1]*u,T()}function T(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Ln(m(n,l(b(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(m=null==t?(x=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>Mt;return Qr(i,function(t){var e,s,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(h,f){var d,p=[h,f],g=i(h,f),v=r?g?0:o(h,f):g?o(h+(h<0?Tt:-Tt),f):0;if(!e&&(u=l=g)&&t.lineStart(),g!==l&&(d=a(e,p),(Fr(e,d)||Fr(p,d))&&(p[0]+=Mt,p[1]+=Mt,g=i(p[0],p[1]))),g!==l)c=0,g?(t.lineStart(),d=a(p,e),t.point(d[0],d[1])):(d=a(e,p),t.point(d[0],d[1]),t.lineEnd()),e=d;else if(n&&e&&r^g){var m;v&s||!(m=a(p,e,!0))||(c=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&Fr(e,p)||t.point(p[0],p[1]),e=p,l=g,s=v},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return c|(u&&l)<<1}}},Nn(t,6*Ct),r?[0,-t]:[-Tt,t-Tt]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Or(Pr(t),Pr(r)),o=Rr(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var u=e*o/l,c=-e*s/l,h=Or(i,a),f=Nr(i,u);Ir(f,Nr(a,c));var d=h,p=Rr(f,d),g=Rr(d,d),v=p*p-g*(Rr(f,f)-1);if(!(v<0)){var m=Math.sqrt(v),b=Nr(d,(-p-m)/g);if(Ir(b,f),b=zr(b),!n)return b;var x,_=t[0],w=r[0],M=t[1],A=r[1];w<_&&(x=_,_=w,w=x);var T=w-_,k=y(T-Tt)0^b[1]<(y(b[0]-_)Tt^(_<=b[0]&&b[0]<=w)){var E=Nr(d,(-p+m)/g);return Ir(E,f),[b,zr(E)]}}}function o(e,n){var i=r?t:Tt-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((x=+t)*Ct),T()):x},w.clipExtent=function(t){return arguments.length?(_=t,b=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):P,T()):_},w.scale=function(t){return arguments.length?(u=+t,A()):u},w.translate=function(t){return arguments.length?(c=+t[0],h=+t[1],A()):[c,h]},w.center=function(t){return arguments.length?(f=t[0]%360*Ct,d=t[1]%360*Ct,A()):[f*St,d*St]},w.rotate=function(t){return arguments.length?(p=t[0]%360*Ct,g=t[1]%360*Ct,v=t.length>2?t[2]%360*Ct:0,A()):[p*St,g*St,v*St]},e.rebind(w,l,"precision"),function(){return r=t.apply(this,arguments),w.invert=r.invert&&M,A()}}function Ln(t){return Tn(t,function(e,r){t.point(e*Ct,r*Ct)})}function Cn(t,e){return[t,e]}function Sn(t,e){return[t>Tt?t-kt:t<-Tt?t+kt:t,e]}function Pn(t,e,r){return t?e||r?Gr(On(t),In(e,r)):On(t):e||r?In(e,r):Sn}function Rn(t){return function(e,r){return[(e+=t)>Tt?e-kt:e<-Tt?e+kt:e,r]}}function On(t){var e=Rn(t);return e.invert=Rn(-t),e}function In(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*r+s*n;return[Math.atan2(l*i-c*a,s*r-u*n),It(c*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*i-l*a;return[Math.atan2(l*i+u*a,s*r+c*n),It(c*r-s*n)]},o}function Nn(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Dn(r,i),a=Dn(r,a),(o>0?ia)&&(i+=o*kt)):(i=t+o*kt,a=t-.5*l);for(var u,c=i;o>0?c>a:c2?t[2]*Ct:0),e.invert=function(e){return(e=t.invert(e[0]*Ct,e[1]*Ct))[0]*=St,e[1]*=St,e},e},Sn.invert=Cn,e.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=Pn(-t[0]*Ct,-t[1]*Ct,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=St,t[1]*=St}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=Nn((t=+r)*Ct,n*Ct),i):t},i.precision=function(r){return arguments.length?(e=Nn(t*Ct,(n=+r)*Ct),i):n},i.angle(90)},e.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ct,i=t[1]*Ct,a=e[1]*Ct,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((r=h*o)*r+(r=u*c-l*h*s)*r),l*c+u*h*s)},e.geo.graticule=function(){var t,r,n,i,a,o,s,l,u,c,h,f,d=10,p=d,g=90,v=360,m=2.5;function b(){return{type:"MultiLineString",coordinates:x()}}function x(){return e.range(Math.ceil(i/g)*g,n,g).map(h).concat(e.range(Math.ceil(l/v)*v,s,v).map(f)).concat(e.range(Math.ceil(r/d)*d,t,d).filter(function(t){return y(t%g)>Mt}).map(u)).concat(e.range(Math.ceil(o/p)*p,a,p).filter(function(t){return y(t%v)>Mt}).map(c))}return b.lines=function(){return x().map(function(t){return{type:"LineString",coordinates:t}})},b.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(f(s).slice(1),h(n).reverse().slice(1),f(l).reverse().slice(1))]}},b.extent=function(t){return arguments.length?b.majorExtent(t).minorExtent(t):b.minorExtent()},b.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),b.precision(m)):[[i,l],[n,s]]},b.minorExtent=function(e){return arguments.length?(r=+e[0][0],t=+e[1][0],o=+e[0][1],a=+e[1][1],r>t&&(e=r,r=t,t=e),o>a&&(e=o,o=a,a=e),b.precision(m)):[[r,o],[t,a]]},b.step=function(t){return arguments.length?b.majorStep(t).minorStep(t):b.minorStep()},b.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],b):[g,v]},b.minorStep=function(t){return arguments.length?(d=+t[0],p=+t[1],b):[d,p]},b.precision=function(e){return arguments.length?(m=+e,u=zn(o,a,90),c=Fn(r,t,m),h=zn(l,s,90),f=Fn(i,n,m),b):m},b.majorExtent([[-180,-90+Mt],[180,90-Mt]]).minorExtent([[-180,-80-Mt],[180,80+Mt]])},e.geo.greatArc=function(){var t,r,n=jn,i=Bn;function a(){return{type:"LineString",coordinates:[t||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return e.geo.distance(t||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(e){return arguments.length?(n=e,t="function"==typeof e?null:e,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},e.geo.interpolate=function(t,e){return r=t[0]*Ct,n=t[1]*Ct,i=e[0]*Ct,a=e[1]*Ct,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),u=Math.sin(a),c=o*Math.cos(r),h=o*Math.sin(r),f=l*Math.cos(i),d=l*Math.sin(i),p=2*Math.asin(Math.sqrt(Dt(a-n)+o*l*Dt(i-r))),g=1/Math.sin(p),(v=p?function(t){var e=Math.sin(t*=p)*g,r=Math.sin(p-t)*g,n=r*c+e*f,i=r*h+e*d,a=r*s+e*u;return[Math.atan2(i,n)*St,Math.atan2(a,Math.sqrt(n*n+i*i))*St]}:function(){return[r*St,n*St]}).distance=p,v;var r,n,i,a,o,s,l,u,c,h,f,d,p,g,v},e.geo.length=function(t){return mn=0,e.geo.stream(t,Un),mn};var Un={sphere:N,point:N,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=Ct),o=Math.cos(i),s=y((n*=Ct)-t),l=Math.cos(s);mn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}Un.point=function(i,a){t=i*Ct,e=Math.sin(a*=Ct),r=Math.cos(a),Un.point=n},Un.lineEnd=function(){Un.point=Un.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function Vn(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var Hn=Vn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(e.geo.azimuthalEqualArea=function(){return kn(Hn)}).raw=Hn;var qn=Vn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},P);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return Yn;function o(t,e){a>0?e<-Lt+Mt&&(e=-Lt+Mt):e>Lt-Mt&&(e=Lt-Mt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=Pt(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-Lt]},o}function Xn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(y(n)1&&Rt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(e.geo.stereographic=function(){return kn(Kn)}).raw=Kn,$n.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Lt]},(e.geo.transverseMercator=function(){var t=Zn($n),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=$n,e.geom={},e.geom.hull=function(t){var e=Jn,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=ve(e),a=ve(r),o=t.length,s=[],l=[];for(n=0;n=0;--n)d.push(t[s[u[n]][2]]);for(n=+h;nMt)s=s.L;else{if(!((i=a-bi(s,o))>Mt)){n>-Mt?(e=s.P,r=s):i>-Mt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=pi(t);if(ui.insert(e,l),e||r){if(e===r)return Mi(e),r=pi(e.site),ui.insert(l,r),l.edge=r.edge=ki(e.site,l.site),wi(e),void wi(r);if(r){Mi(e),Mi(r);var u=e.site,c=u.x,h=u.y,f=t.x-c,d=t.y-h,p=r.site,g=p.x-c,v=p.y-h,m=2*(f*v-d*g),y=f*f+d*d,b=g*g+v*v,x={x:(v*y-d*b)/m+c,y:(f*b-g*y)/m+h};Ei(r.edge,u,p,x),l.edge=ki(u,t,null,x),r.edge=ki(t,p,null,x),wi(e),wi(r)}else l.edge=ki(e.site,l.site)}}function yi(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,u=l-e;if(!u)return s;var c=s-n,h=1/a-1/u,f=c/u;return h?(-f+Math.sqrt(f*f-2*h*(c*c/(-2*u)-l+u/2+i-a/2)))/h+n:(n+s)/2}function bi(t,e){var r=t.N;if(r)return yi(r,e);var n=t.site;return n.y===e?n.x:1/0}function xi(t){this.site=t,this.edges=[]}function _i(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,u=n.y-s,c=a.x-o,h=2*(l*(v=a.y-s)-u*c);if(!(h>=-At)){var f=l*l+u*u,d=c*c+v*v,p=(v*f-u*d)/h,g=(l*d-c*f)/h,v=g+s,m=di.pop()||new function(){Si(this),this.x=this.y=this.arc=this.site=this.cy=null};m.arc=t,m.site=i,m.x=p+o,m.y=v+Math.sqrt(p*p+g*g),m.cy=v,t.circle=m;for(var y=null,b=hi._;b;)if(m.y=s)return;if(f>p){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.y1)if(f>p){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.y=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xMt||y(i-r)>Mt)&&(s.splice(o,0,new Li((m=a.site,b=c,x=y(n-h)Mt?{x:h,y:y(e-h)Mt?{x:y(r-p)Mt?{x:f,y:y(e-f)Mt?{x:y(r-d)=r&&u.x<=i&&u.y>=n&&u.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/Mt)*Mt,y:Math.round(i(t,e)/Mt)*Mt,i:e}})}return o.links=function(t){return Ii(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Ii(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,u=r.edges.sort(_i),c=-1,h=u.length,f=u[h-1].edge,d=f.l===l?f.r:f.l;++ca&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Ui(r,n)})),a=qi.lastIndex;return ag&&(g=l.x),l.y>v&&(v=l.y),u.push(l.x),c.push(l.y);else for(h=0;hg&&(g=x),_>v&&(v=_),u.push(x),c.push(_)}var w=g-d,M=v-p;function A(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,u=t.y;if(null!=l)if(y(l-r)+y(u-n)<.01)T(t,e,r,n,i,a,o,s);else{var c=t.point;t.x=t.y=t.point=null,T(t,c,l,u,i,a,o,s),T(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,i,a,o,s)}function T(t,e,r,n,i,a,o,s){var l=.5*(i+o),u=.5*(a+s),c=r>=l,h=n>=u,f=h<<1|c;t.leaf=!1,t=t.nodes[f]||(t.nodes[f]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(k,t,+m(t,++h),+b(t,h),d,p,g,v)}}),c?i=l:o=l,h?a=u:s=u,A(t,e,r,n,i,a,o,s)}w>M?v=p+w:g=d+M;var k={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(k,t,+m(t,++h),+b(t,h),d,p,g,v)}};if(k.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),u=r.nodes;u[0]&&t(e,u[0],n,i,s,l),u[1]&&t(e,u[1],s,i,a,l),u[2]&&t(e,u[2],n,l,s,o),u[3]&&t(e,u[3],s,l,a,o)}}(t,k,d,p,g,v)},k.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(u,c,h,f,d){if(!(c>a||h>o||f=_)<<1|e>=x,M=w+4;w=0&&!(n=e.interpolators[i](t,r)););return n}function Xi(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ea(t){return 1-Math.cos(t*Lt)}function ra(t){return Math.pow(2,10*(t-1))}function na(t){return 1-Math.sqrt(1-t*t)}function ia(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}function aa(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oa(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=la(i),s=sa(i,a),l=la(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Yi.get(i)||Wi,a=Zi.get(a)||P,e=a(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},e.interpolateHcl=function(t,r){t=e.hcl(t),r=e.hcl(r);var n=t.h,i=t.c,a=t.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Wt(n+o*t,i+s*t,a+l*t)+""}},e.interpolateHsl=function(t,r){t=e.hsl(t),r=e.hsl(r);var n=t.h,i=t.s,a=t.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return qt(n+o*t,i+s*t,a+l*t)+""}},e.interpolateLab=function(t,r){t=e.lab(t),r=e.lab(r);var n=t.l,i=t.a,a=t.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},e.interpolateRound=aa,e.transform=function(t){var r=i.createElementNS(e.ns.prefix.svg,"g");return(e.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oa(e?e.matrix:ua)})(t)},oa.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ua={a:1,b:0,c:0,d:1,e:0,f:0};function ca(t){return t.length?t.pop()+",":""}function ha(t,r){var n=[],i=[];return t=e.transform(t),r=e.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Ui(t[0],e[0])},{i:i-2,x:Ui(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(t.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ca(r)+"rotate(",null,")")-2,x:Ui(t,e)})):e&&r.push(ca(r)+"rotate("+e+")")}(t.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(ca(r)+"skewX(",null,")")-2,x:Ui(t,e)}):e&&r.push(ca(r)+"skewX("+e+")")}(t.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(ca(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Ui(t[0],e[0])},{i:i-2,x:Ui(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ca(r)+"scale("+e+")")}(t.scale,r.scale,n,i),t=r=null,function(t){for(var e,r=-1,a=i.length;++r0?n=e:(t.c=null,t.t=NaN,t=null,l.end({type:"end",alpha:n=0})):e>0&&(l.start({type:"start",alpha:n=e}),t=Ae(s.tick)),s):n},s.start=function(){var t,e,r,n=m.length,l=y.length,c=u[0],p=u[1];for(t=0;t=0;)r.push(i[n])}function Ta(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;r&&(a.value=0),a.children=u}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return Ta(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Aa(t,function(t){t.children&&(t.value=0)}),Ta(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},e.layout.partition=function(){var t=e.layout.hierarchy(),r=[1,1];function n(e,n){var i=t.call(this,e,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++us&&(s=n),o.push(n)}for(r=0;ri&&(n=r,i=e);return n}function ja(t){return t.reduce(Ba,0)}function Ba(t,e){return t+e[1]}function Ua(t,e){return Va(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Va(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function Ha(t){return[e.min(t),e.max(t)]}function qa(t,e){return t.value-e.value}function Ga(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Xa(t,e){t._pack_next=e,e._pack_prev=t}function Wa(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Ya(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,u=1/0,c=-1/0,h=1/0,f=-1/0;if(e.forEach(Za),(r=e[0]).x=-r.r,r.y=0,b(r),l>1&&((n=e[1]).x=n.r,n.y=0,b(n),l>2))for(Ka(r,n,i=e[2]),b(i),Ga(r,i),r._pack_prev=i,Ga(i,n),n=r._pack_next,a=3;a0)for(o=-1;++o=h[0]&&l<=h[1]&&((s=u[e.bisect(f,l,1,p)-1]).y+=g,s.push(a[o]));return u}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=ve(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Va(e,t)}:ve(t),a):i},a.frequency=function(e){return arguments.length?(t=!!e,a):t},a},e.layout.pack=function(){var t,r=e.layout.hierarchy().sort(qa),n=0,i=[1,1];function a(e,a){var o=r.call(this,e,a),s=o[0],l=i[0],u=i[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(s.x=s.y=0,Ta(s,function(t){t.r=+c(t.value)}),Ta(s,Ya),n){var h=n*(t?1:Math.max(2*s.r/l,2*s.r/u))/2;Ta(s,function(t){t.r+=h}),Ta(s,Ya),Ta(s,function(t){t.r-=h})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++od.x&&(d=t),t.depth>p.depth&&(p=t)});var g=r(f,d)/2-f.x,v=n[0]/(d.x+r(d,f)/2+g),m=n[1]/(p.depth||1);Aa(c,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return u}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],u=a.m,c=o.m,h=s.m,f=l.m;s=to(s),a=Ja(a),s&&a;)l=Ja(l),(o=to(o)).a=t,(i=s.z+h-a.z-u+r(s._,a._))>0&&(eo(ro(s,t,n),t,i),u+=i,c+=i),h+=s.m,u+=a.m,f+=l.m,c+=o.m;s&&!to(o)&&(o.t=s,o.m+=h-c),a&&!Ja(l)&&(l.t=a,l.m+=u-f,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},Ma(a,t)},e.layout.cluster=function(){var t=e.layout.hierarchy().sort(null).value(null),r=$a,n=[1,1],i=!1;function a(a,o){var s,l=t.call(this,a,o),u=l[0],c=0;Ta(u,function(t){var n=t.children;n&&n.length?(t.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),t.y=function(t){return 1+e.max(t,function(t){return t.y})}(n)):(t.x=s?c+=r(t,s):0,t.y=0,s=t)});var h=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),f=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),d=h.x-r(h,f)/2,p=f.x+r(f,h)/2;return Ta(u,i?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-d)/(p-d)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},Ma(a,t)},e.layout.treemap=function(){var t,r=e.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=no,s=!1,l="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,i=-1,a=t.length;++i0;)s.push(r=u[i-1]),s.area+=r.area,"squarify"!==l||(n=d(s,g))<=f?(u.pop(),f=n):(s.area-=s.pop().area,p(s,g,a,!1),g=Math.min(a.dx,a.dy),s.length=s.area=0,f=1/0);s.length&&(p(s,g,a,!0),s.length=s.area=0),e.forEach(h)}}function f(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(c(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(p(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(f)}}function d(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++oi&&(i=r));return e*=e,(n*=n)?Math.max(e*i*u/n,n/(e*a*u)):1/0}function p(t,e,r,i){var a,o=-1,s=t.length,l=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((i||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=e.random.normal.apply(e,arguments);return function(){return Math.exp(t())}},bates:function(t){var r=e.random.irwinHall(t);return function(){return r()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?ho:so,s=i?da:fa;return a=t(e,r,s,n),o=t(r,e,s,Gi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(aa)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return vo(e,t)};l.tickFormat=function(t,r){return mo(e,t,r)};l.nice=function(t){return po(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Gi,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function bo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}e.scale.log=function(){return function t(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=lo(a.map(o),i?Math:_o);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=ao(a),e=[],r=t[0],l=t[1],u=Math.floor(o(r)),c=Math.ceil(o(l)),h=n%1?2:n;if(isFinite(c-u)){if(i){for(;u0;f--)e.push(s(u)*f);for(u=0;e[u]l;c--);e=e.slice(u,c)}return e};l.tickFormat=function(t,r){if(!arguments.length)return xo;arguments.length<2?r=xo:"function"!=typeof r&&(r=e.format(r));var i=Math.max(1,n*t/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n0?i[t-1]:r[0],th?0:1;if(u=Et)return l(u,d)+(s?l(s,1-d):"")+"Z";var p,g,v,m,y,b,x,_,w,M,A,T,k=0,E=0,L=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Lo?Math.sqrt(s*s+u*u):+n.apply(this,arguments),d||(E*=-1),u&&(E=It(v/u*Math.sin(m))),s&&(k=It(v/s*Math.sin(m)))),u){y=u*Math.cos(c+E),b=u*Math.sin(c+E),x=u*Math.cos(h-E),_=u*Math.sin(h-E);var C=Math.abs(h-c-2*E)<=Tt?0:1;if(E&&Io(y,b,x,_)===d^C){var S=(c+h)/2;y=u*Math.cos(S),b=u*Math.sin(S),x=_=null}}else y=b=0;if(s){w=s*Math.cos(h-k),M=s*Math.sin(h-k),A=s*Math.cos(c+k),T=s*Math.sin(c+k);var P=Math.abs(c-h+2*k)<=Tt?0:1;if(k&&Io(w,M,A,T)===1-d^P){var R=(c+h)/2;w=s*Math.cos(R),M=s*Math.sin(R),A=T=null}}else w=M=0;if(f>Mt&&(p=Math.min(Math.abs(u-s)/2,+r.apply(this,arguments)))>.001){g=s0?0:1}function No(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,h=t[1]+u,f=e[0]+l,d=e[1]+u,p=(c+f)/2,g=(h+d)/2,v=f-c,m=d-h,y=v*v+m*m,b=r-n,x=c*d-f*h,_=(m<0?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,M=(-x*v-m*_)/y,A=(x*m+v*_)/y,T=(-x*v+m*_)/y,k=w-p,E=M-g,L=A-p,C=T-g;return k*k+E*E>L*L+C*C&&(w=A,M=T),[[w-l,M-u],[w*r/b,M*r/b]]}function Do(t){var e=Jn,r=ti,n=Xr,i=Fo,a=i.key,o=.7;function s(a){var s,l=[],u=[],c=-1,h=a.length,f=ve(e),d=ve(r);function p(){l.push("M",i(t(u),o))}for(;++c1&&i.push("H",n[0]);return i.join("")},"step-before":Bo,"step-after":Uo,basis:qo,"basis-open":function(t){if(t.length<4)return Fo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Go(Yo,a)+","+Go(Yo,o)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Fo(t){return t.length>1?t.join("L"):t+"Z"}function jo(t){return t.join("L")+"Z"}function Bo(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;uTt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=ve(t),a):r},a.source=function(e){return arguments.length?(t=ve(e),a):t},a.target=function(t){return arguments.length?(e=ve(t),a):e},a.startAngle=function(t){return arguments.length?(n=ve(t),a):n},a.endAngle=function(t){return arguments.length?(i=ve(t),a):i},a},e.svg.diagonal=function(){var t=jn,e=Bn,r=ts;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},e.svg.diagonal.radial=function(){var t=e.svg.diagonal(),r=ts,n=t.projection;return t.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Lt;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},t},e.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var is=e.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*os)),r=e*os;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});e.svg.symbolTypes=is.keys();var as=Math.sqrt(3),os=Math.tan(30*Ct);W.transition=function(t){for(var e,r,n=cs||++ds,i=vs(t),a=[],o=hs||{time:Date.now(),ease:ta,delay:0,duration:250},s=-1,l=this.length;++s0;)u[--f].call(t,o);if(a>=1)return h.event&&h.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}h||(a=i.time,o=Ae(function(t){var e=h.delay;if(o.t=e+a,e<=t)return f(t-e);o.c=f},0,a),h=c[n]={tween:new x,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++c.count)}fs.call=W.call,fs.empty=W.empty,fs.node=W.node,fs.size=W.size,e.transition=function(t,r){return t&&t.transition?cs?t.transition(r):t:e.selection().transition(t)},e.transition.prototype=fs,fs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=Y(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function g(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function v(){var h,v,m=this,y=e.select(e.event.target),b=n.of(m,arguments),x=e.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&i,M=!/^(e|w)$/.test(_)&&a,A=y.classed("extent"),T=bt(m),k=e.mouse(m),E=e.select(o(m)).on("keydown.brush",function(){32==e.event.keyCode&&(A||(h=null,k[0]-=s[1],k[1]-=l[1],A=2),F())}).on("keyup.brush",function(){32==e.event.keyCode&&2==A&&(k[0]+=s[1],k[1]+=l[1],A=0,F())});if(e.event.changedTouches?E.on("touchmove.brush",S).on("touchend.brush",R):E.on("mousemove.brush",S).on("mouseup.brush",R),x.interrupt().selectAll("*").interrupt(),A)k[0]=s[0]-k[0],k[1]=l[0]-k[1];else if(_){var L=+/w$/.test(_),C=+/^n/.test(_);v=[s[1-L]-k[0],l[1-C]-k[1]],k[0]=s[L],k[1]=l[C]}else e.event.altKey&&(h=k.slice());function S(){var t=e.mouse(m),r=!1;v&&(t[0]+=v[0],t[1]+=v[1]),A||(e.event.altKey?(h||(h=[(s[0]+s[1])/2,(l[0]+l[1])/2]),k[0]=s[+(t[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=Cs(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=Cs(+e+1);return e}}:t))},i.ticks=function(t,e){var r=ao(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Cs(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Ls(t.copy(),r,n)},fo(i,t)}function Cs(t){return new Date(t)}As.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Es:ks,Es.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Es.toString=ks.toString,Oe.second=ze(function(t){return new Ie(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Oe.seconds=Oe.second.range,Oe.seconds.utc=Oe.second.utc.range,Oe.minute=ze(function(t){return new Ie(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Oe.minutes=Oe.minute.range,Oe.minutes.utc=Oe.minute.utc.range,Oe.hour=ze(function(t){var e=t.getTimezoneOffset()/60;return new Ie(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Oe.hours=Oe.hour.range,Oe.hours.utc=Oe.hour.utc.range,Oe.month=ze(function(t){return(t=Oe.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Oe.months=Oe.month.range,Oe.months.utc=Oe.month.utc.range;var Ss=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ps=[[Oe.second,1],[Oe.second,5],[Oe.second,15],[Oe.second,30],[Oe.minute,1],[Oe.minute,5],[Oe.minute,15],[Oe.minute,30],[Oe.hour,1],[Oe.hour,3],[Oe.hour,6],[Oe.hour,12],[Oe.day,1],[Oe.day,2],[Oe.week,1],[Oe.month,1],[Oe.month,3],[Oe.year,1]],Rs=As.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Xr]]),Os={range:function(t,r,n){return e.range(Math.ceil(t/n)*n,+r,n).map(Cs)},floor:P,ceil:P};Ps.year=Oe.year,Oe.scale=function(){return Ls(e.scale.linear(),Ps,Rs)};var Is=Ps.map(function(t){return[t[0].utc,t[1]]}),Ns=Ts.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Xr]]);function Ds(t){return JSON.parse(t.responseText)}function zs(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Is.year=Oe.year.utc,Oe.scale.utc=function(){return Ls(e.scale.linear(),Is,Ns)},e.text=me(function(t){return t.responseText}),e.json=function(t,e){return ye(t,"application/json",Ds,e)},e.html=function(t,e){return ye(t,"text/html",zs,e)},e.xml=me(function(t){return t.responseXML}),t.exports?t.exports=e:this.d3=e}(),t=t.exports;var e=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},n={},i=Math.PI;n.deg2rad=function(t){return t/180*i},n.rad2deg=function(t){return t/i*180},n.wrap360=function(t){var e=t%360;return e<0?e+360:e},n.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var a=r.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,i=t.round,a=t.min,o=t.max,l=t.random;function u(s,l){if(s=s||"",l=l||{},s instanceof u)return s;if(!(this instanceof u))return new u(s,l);var c=function(n){var i={r:0,g:0,b:0},s=1,l=null,u=null,c=null,h=!1,f=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,i=!1;if(E[t])t=E[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=B.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=B.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=B.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=B.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=B.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=B.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=B.hex8.exec(t))return{r:R(n[1]),g:R(n[2]),b:R(n[3]),a:D(n[4]),format:i?"name":"hex8"};if(n=B.hex6.exec(t))return{r:R(n[1]),g:R(n[2]),b:R(n[3]),format:i?"name":"hex"};if(n=B.hex4.exec(t))return{r:R(n[1]+""+n[1]),g:R(n[2]+""+n[2]),b:R(n[3]+""+n[3]),a:D(n[4]+""+n[4]),format:i?"name":"hex8"};if(n=B.hex3.exec(t))return{r:R(n[1]+""+n[1]),g:R(n[2]+""+n[2]),b:R(n[3]+""+n[3]),format:i?"name":"hex"};return!1}(n));"object"==typeof n&&(U(n.r)&&U(n.g)&&U(n.b)?(d=n.r,p=n.g,g=n.b,i={r:255*S(d,255),g:255*S(p,255),b:255*S(g,255)},h=!0,f="%"===String(n.r).substr(-1)?"prgb":"rgb"):U(n.h)&&U(n.s)&&U(n.v)?(l=I(n.s),u=I(n.v),i=function(e,r,n){e=6*S(e,360),r=S(r,100),n=S(n,100);var i=t.floor(e),a=e-i,o=n*(1-r),s=n*(1-a*r),l=n*(1-(1-a)*r),u=i%6;return{r:255*[n,s,o,o,l,n][u],g:255*[l,n,n,s,o,o][u],b:255*[o,o,l,n,n,s][u]}}(n.h,l,u),h=!0,f="hsv"):U(n.h)&&U(n.s)&&U(n.l)&&(l=I(n.s),c=I(n.l),i=function(t,e,r){var n,i,a;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=S(t,360),e=S(e,100),r=S(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(n.h,l,c),h=!0,f="hsl"),n.hasOwnProperty("a")&&(s=n.a));var d,p,g;return s=C(s),{ok:h,format:n.format||f,r:a(255,o(i.r,0)),g:a(255,o(i.g,0)),b:a(255,o(i.b,0)),a:s}}(s);this._originalInput=s,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=i(100*this._a)/100,this._format=l.format||c.format,this._gradientType=l.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=c.ok,this._tc_id=n++}function c(t,e,r){t=S(t,255),e=S(e,255),r=S(r,255);var n,i,s=o(t,e,r),l=a(t,e,r),u=(s+l)/2;if(s==l)n=i=0;else{var c=s-l;switch(i=u>.5?c/(2-s-l):c/(s+l),s){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(u(n));return a}function k(t,e){e=e||6;for(var r=u(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(u({h:n,s:i,v:a})),a=(a+s)%1;return o}u.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=C(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=h(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=h(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=c(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=c(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return f(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[O(i(t).toString(16)),O(i(e).toString(16)),O(i(r).toString(16)),O(N(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*S(this._r,255))+"%",g:i(100*S(this._g,255))+"%",b:i(100*S(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*S(this._r,255))+"%, "+i(100*S(this._g,255))+"%, "+i(100*S(this._b,255))+"%)":"rgba("+i(100*S(this._r,255))+"%, "+i(100*S(this._g,255))+"%, "+i(100*S(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(L[f(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+d(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=u(t);r="#"+d(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return u(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(b,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(x,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(A,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(M,arguments)}},u.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:I(t[n]));t=r}return u(t,e)},u.equals=function(t,e){return!(!t||!e)&&u(t).toRgbString()==u(e).toRgbString()},u.random=function(){return u.fromRatio({r:l(),g:l(),b:l()})},u.mix=function(t,e,r){r=0===r?0:r||50;var n=u(t).toRgb(),i=u(e).toRgb(),a=r/100;return u({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},u.readability=function(e,r){var n=u(e),i=u(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},u.isReadable=function(t,e,r){var n,i,a=u.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},u.mostReadable=function(t,e,r){var n,i,a,o,s=null,l=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var c=0;cl&&(l=n,s=u(e[c]));return u.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,u.mostReadable(t,["#fff","#000"],r))};var E=u.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"},L=u.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(E);function C(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function S(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=a(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function P(t){return a(1,o(0,t))}function R(t){return parseInt(t,16)}function O(t){return 1==t.length?"0"+t:""+t}function I(t){return t<=1&&(t=100*t+"%"),t}function N(e){return t.round(255*parseFloat(e)).toString(16)}function D(t){return R(t)/255}var z,F,j,B=(F="[\\s|\\(]+("+(z="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+z+")[,|\\s]+("+z+")\\s*\\)?",j="[\\s|\\(]+("+z+")[,|\\s]+("+z+")[,|\\s]+("+z+")[,|\\s]+("+z+")\\s*\\)?",{CSS_UNIT:new RegExp(z),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function U(t){return!!B.CSS_UNIT.exec(t)}s.exports?s.exports=u:window.tinycolor=u}(Math),s=s.exports;var l={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=l.RdBu,c=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],i=t[e][1],o=!1,G(n))for(r=n.length-1;r>=0;r--)Z(n[r],K(i,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)Z(n[a[r]],K(i,a[r]))?delete n[a[r]]:o=!0;if(o)return}}(l)):o[e[a]]=n}}function K(t,r){var n=r;return e(r)?n="["+r+"]":t&&(n="."+r),t+n}function $(t,e,r,n){var i,a=G(r),o=!0,s=r,l=n.replace("-1",0),u=!a&&Z(r,l),c=e[0];for(i=0;ii.max?r.set(n):r.set(+t)}},integer:{coerceFunction:function(t,r,n,i){t%1||!e(t)||void 0!==i.min&&ti.max?r.set(n):r.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){s(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return s(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(h(t,r))}},angle:{coerceFunction:function(t,r,n){"auto"===t?r.set("auto"):e(t)?r.set(it(+t)):r.set(n)}},subplotid:{coerceFunction:function(t,e,r){"string"==typeof t&&rt(r).test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!rt(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a=ot&&t<=st?t:ct;if("string"!=typeof t&&"number"!=typeof t)return ct;t=String(t);var r=xt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var i=r&&"chinese"===e.substr(0,7),a=t.match(i?yt:mt);if(!a)return ct;var o=a[1],s=a[3]||"1",l=Number(a[5]||1),u=Number(a[7]||0),c=Number(a[9]||0),h=Number(a[11]||0);if(r){if(2===o.length)return ct;var f;o=Number(o);try{var d=R.getComponentMethod("calendars","getCal")(e);if(i){var p="i"===s.charAt(s.length-1);s=parseInt(s,10),f=d.newDate(o,d.toMonthIndex(o,s,p),l)}else f=d.newDate(o,Number(s),l)}catch(t){return ct}return f?(f.toJD()-gt)*ht+u*ft+c*dt+h*pt:ct}o=2===o.length?(Number(o)+2e3-bt)%100+bt:Number(o),s-=1;var g=new Date(Date.UTC(2e3,s,l,u,c));return g.setUTCFullYear(o),g.getUTCMonth()!==s?ct:g.getUTCDate()!==l?ct:g.getTime()+h*pt},ot=ut.MIN_MS=ut.dateTime2ms("-9999"),st=ut.MAX_MS=ut.dateTime2ms("9999-12-31 23:59:59.9999"),ut.isDateTime=function(t,e){return ut.dateTime2ms(t,e)!==ct};var wt=90*ht,Mt=3*ft,At=5*dt;function Tt(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+_t(e,2)+":"+_t(r,2),(n||i)&&(t+=":"+_t(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+_t(i,a)}return t}ut.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ot&&t<=st))return ct;e||(e=0);var n,i,a,o,s,l,u=Math.floor(10*lt(t+.05,1)),c=Math.round(t-u/10);if(xt(r)){var h=Math.floor(c/ht)+gt,f=Math.floor(lt(t,ht));try{n=R.getComponentMethod("calendars","getCal")(r).fromJD(h).formatDate("yyyy-mm-dd")}catch(t){n=vt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;i=e=ot+ht&&e<=st-ht))return ct;var r=Math.floor(10*lt(e+.05,1)),n=new Date(Math.round(e-r/10));return Tt(t.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ut.cleanDate=function(t,e,r){if(ut.isJSDate(t)||"number"==typeof t){if(xt(r))return _.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ut.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ut.isDateTime(t,r))return _.error("unrecognized date",t),e;return t};var kt=/%\d?f/g;function Et(t,e,r,n){t=t.replace(kt,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(xt(n))try{t=R.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var Lt=[59,59.9,59.99,59.999,59.9999];ut.formatDate=function(t,r,n,i,a,o){if(a=xt(a)&&a,!r)if("y"===n)r=o.year;else if("m"===n)r=o.month;else{if("d"!==n)return function(t,r){var n=lt(t+.05,ht),i=_t(Math.floor(n/ft),2)+":"+_t(lt(Math.floor(n/dt),60),2);if("M"!==r){e(r)||(r=0);var a=(100+Math.min(lt(t/pt,60),Lt[r])).toFixed(r).substr(1);r>0&&(a=a.replace(/0+$/,"").replace(/[\.]$/,"")),i+=":"+a}return i}(t,n)+"\n"+Et(o.dayMonthYear,t,i,a);r=o.dayMonth+"\n"+o.year}return Et(r,t,i,a)};var Ct=3*ht;ut.incrementMonth=function(t,e,r){r=xt(r)&&r;var n=lt(t,ht);if(t=Math.round(t-n),r)try{var i=Math.round(t/ht)+gt,a=R.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-gt)*ht+n}catch(e){_.error("invalid ms "+t+" in calendar "+r)}var s=new Date(t+Ct);return s.setUTCMonth(s.getUTCMonth()+e)+n-Ct},ut.findExactDates=function(t,r){for(var n,i,a=0,o=0,s=0,l=0,u=xt(r)&&R.getComponentMethod("calendars","getCal")(r),c=0;c1||g<0||g>1?null:{x:t+l*g,y:e+h*g}}function zt(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}Nt.segmentsIntersect=Dt,Nt.segmentDistance=function(t,e,r,n,i,a,o,s){if(Dt(t,e,r,n,i,a,o,s))return 0;var l=r-t,u=n-e,c=o-i,h=s-a,f=l*l+u*u,d=c*c+h*h,p=Math.min(zt(l,u,f,i-t,a-e),zt(l,u,f,o-t,s-e),zt(c,h,d,t-i,e-a),zt(c,h,d,r-i,n-a));return Math.sqrt(p)},Nt.getTextLocation=function(t,e,r,n){if(t===Ot&&n===It||(Rt={},Ot=t,It=n),Rt[r])return Rt[r];var i=t.getPointAtLength(lt(r-n/2,e)),a=t.getPointAtLength(lt(r+n/2,e)),o=Math.atan((a.y-i.y)/(a.x-i.x)),s=t.getPointAtLength(lt(r,e)),l={x:(4*s.x+i.x+a.x)/6,y:(4*s.y+i.y+a.y)/6,theta:o};return Rt[r]=l,l},Nt.clearLocationCache=function(){Ot=null},Nt.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,u=0,c=t.getTotalLength(),h=c;function f(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(i=r);var u=r.xo?r.x-o:0,h=r.yl?r.y-l:0;return Math.sqrt(u*u+h*h)}for(var d=f(u);d;){if((u+=d+r)>h)return;d=f(u)}for(d=f(h);d;){if(u>(h-=d+r))return;d=f(h)}return{min:u,max:h,len:h-u,total:c,isClosed:0===u&&h===c&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},Nt.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,h=0,f=0,d=s;h0?d=i:f=i,h++}return a};var Ft=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},jt=/^\w*$/,Bt={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Zt(t,e){return t>=e}Gt.findBin=function(t,r,n){if(e(r.start))return n?Math.ceil((t-r.start)/r.size-1e-9)-1:Math.floor((t-r.start)/r.size+1e-9);var i,a,o=0,s=r.length,l=0,u=s>1?(r[s-1]-r[0])/(s-1):1;for(a=u>=0?n?Xt:Wt:n?Zt:Yt,t+=1e-9*u*(n?-1:1)*(u>=0?1:-1);o90&&_.log("Long binary search..."),o-1},Gt.sorterAsc=function(t,e){return t-e},Gt.sorterDes=function(t,e){return e-t},Gt.distinctVals=function(t){var e=t.slice();e.sort(Gt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,i=n/(r||1)/1e4,a=[e[0]],o=0;oe[o]+i&&(n=Math.min(n,e[o+1]-e[o]),a.push(e[o+1]));return{vals:a,minDiff:n}},Gt.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;in.length)&&(i=n.length),e(r)||(r=!1),Kt(n[0])){for(o=new Array(i),a=0;at.length-1)return t[t.length-1];var n=r%1;return n*t[Math.ceil(r)]+(1-n)*t[Math.floor(r)]};var $t={},Jt={};function te(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}$t.throttle=function(t,e,r){var n=Jt[t],i=Date.now();if(!n){for(var a in Jt)Jt[a].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},$t.done=function(t){var e=Jt[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},$t.clear=function(t){if(t)te(Jt[t]),delete Jt[t];else for(var e in Jt)$t.clear(e)};var ee=function(t,r){if(t>0)return Math.log(t)/Math.LN10;var n=Math.log(Math.min(r[0],r[1]))/Math.LN10;return e(n)||(n=Math.log(Math.max(r[0],r[1]))/Math.LN10-6),n},re={},ne=r.FP_SAFE,ie=r.BADNUM,ae=re={};ae.nestedProperty=X,ae.keyedContainer=function(t,e,r,n){var i,a;r=r||"name",n=n||"value";var o={};a=e&&e.length?X(t,e).get():t,e=e||"",a=a||[];var s={};for(i=0;i2)return o[e]=2|o[e],u.set(t,null);if(l){for(i=e;i/g),s=0;sne?ie:e(t)?Number(t):ie:ie},ae.noop=A,ae.identity=function(t){return t},ae.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},ae.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},ae.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):s},ae.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},ae.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},ae.syncOrAsync=function(t,e,r){var n;function i(){return ae.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,ae.promiseError);return r&&r(e)},ae.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},ae.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n=0&&a%1==0){var p=i?i[d]:d,g=n?n[p]:p;h(g)&&(t[g].selected=1)}}},ae.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=ae.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ae.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l};var le=/%{([^\s%{}]*)}/g,ue=/^\w*$/;ae.templateString=function(t,e){var r={};return t.replace(le,function(t,n){return ue.test(n)?e[n]||"":(r[n]=r[n]||ae.nestedProperty(e,n).get,r[n]()||"")})};ae.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a=48&&o<=57,u=s>=48&&s<=57;if(l&&(n=10*n+o-48),u&&(i=10*i+s-48),!l||!u){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n};var ce=2e9;ae.seedPseudoRandom=function(){ce=2e9},ae.pseudoRandom=function(){var t=ce;return ce=(69069*ce+1)%4294967296,Math.abs(ce-t)<429496729?ae.pseudoRandom():ce/4294967296};var he={"X,X div":"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 .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"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":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","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 .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 fe in he){var de=fe.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");re.addStyleRule(de,he[fe])}var pe,ge,ve,me={undo:{width:857.1,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",ascent:850,descent:-150},home:{width:928.6,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",ascent:850,descent:-150},"camera-retro":{width:1e3,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",ascent:850,descent:-150},zoombox:{width:1e3,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",ascent:850,descent:-150},pan:{width:1e3,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",ascent:850,descent:-150},zoom_plus:{width:1e3,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",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,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",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,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",ascent:850,descent:-150},plotlylogo:{width:1542,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",ascent:850,descent:-150},"z-axis":{width:1e3,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",ascent:850,descent:-150},"3d_rotate":{width:1e3,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",ascent:850,descent:-150},camera:{width:1e3,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",ascent:850,descent:-150},movie:{width:1e3,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",ascent:850,descent:-150},question:{width:857.1,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",ascent:850,descent:-150},disk:{width:857.1,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",ascent:850,descent:-150},lasso:{width:1031,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",ascent:850,descent:-150},selectbox:{width:1e3,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",ascent:850,descent:-150},spikeline:{width:1e3,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",ascent:850,descent:-150}},ye=pe={};function be(){throw new Error("setTimeout has not been defined")}function xe(){throw new Error("clearTimeout has not been defined")}function _e(t){if(ge===setTimeout)return setTimeout(t,0);if((ge===be||!ge)&&setTimeout)return ge=setTimeout,setTimeout(t,0);try{return ge(t,0)}catch(e){try{return ge.call(null,t,0)}catch(e){return ge.call(this,t,0)}}}!function(){try{ge="function"==typeof setTimeout?setTimeout:be}catch(t){ge=be}try{ve="function"==typeof clearTimeout?clearTimeout:xe}catch(t){ve=xe}}();var we,Me=[],Ae=!1,Te=-1;function ke(){Ae&&we&&(Ae=!1,we.length?Me=we.concat(Me):Te=-1,Me.length&&Ee())}function Ee(){if(!Ae){var t=_e(ke);Ae=!0;for(var e=Me.length;e;){for(we=Me,Me=[];++Te1)for(var r=1;r=0))return t;if(3===o)i[o]>1&&(i[o]=1);else if(i[o]>=1)return t}var s=Math.round(255*i[0])+", "+Math.round(255*i[1])+", "+Math.round(255*i[2]);return a?"rgba("+s+", "+i[3]+")":"rgb("+s+")"}De.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},De.rgb=function(t){return De.tinyRGB(s(t))},De.opacity=function(t){return t?s(t).getAlpha():0},De.addOpacity=function(t,e){var r=s(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},De.combine=function(t,e){var r=s(t).toRgb();if(1===r.a)return s(t).toRgbString();var n=s(e||Fe).toRgb(),i=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},a={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return s(a).toRgbString()},De.contrast=function(t,e,r){var n=s(t);return 1!==n.getAlpha()&&(n=s(De.combine(t,Fe))),(n.isDark()?e?n.lighten(e):Fe:r?n.darken(r):ze).toString()},De.stroke=function(t,e){var r=s(e);t.style({stroke:De.tinyRGB(r),"stroke-opacity":r.getAlpha()})},De.fill=function(t,e){var r=s(e);t.style({fill:De.tinyRGB(r),"fill-opacity":r.getAlpha()})},De.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,a=Object.keys(t);for(e=0;e=0,p=r.indexOf("end")>=0,g=u.backoff*h+n.standoff,v=c.backoff*f+n.startstandoff;if("line"===l.nodeName){i={x:+e.attr("x1"),y:+e.attr("y1")},a={x:+e.attr("x2"),y:+e.attr("y2")};var m=i.x-a.x,y=i.y-a.y;if(s=(o=Math.atan2(y,m))+Math.PI,g&&v&&g+v>Math.sqrt(m*m+y*y))return void C();if(g){if(g*g>m*m+y*y)return void C();var b=g*Math.cos(o),x=g*Math.sin(o);a.x+=b,a.y+=x,e.attr({x2:a.x,y2:a.y})}if(v){if(v*v>m*m+y*y)return void C();var _=v*Math.cos(o),w=v*Math.sin(o);i.x-=_,i.y-=w,e.attr({x1:i.x,y1:i.y})}}else if("path"===l.nodeName){var M=l.getTotalLength(),A="";if(M0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},We.prototype.on=We.prototype.addListener,We.prototype.once=function(t,e){if(!Ze(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},We.prototype.removeListener=function(t,e){var r,n,i,a;if(!Ze(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=(r=this._events[t]).length,n=-1,r===e||Ze(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Qe(r)){for(a=i;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},We.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(Ze(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},We.prototype.listeners=function(t){return this._events&&this._events[t]?Ze(this._events[t])?[this._events[t]]:this._events[t].slice():[]},We.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(Ze(e))return 1;if(e)return e.length}return 0},We.listenerCount=function(t,e){return t.listenerCount(e)};var $e,Je=Ye.EventEmitter,tr={init:function(t){if(t._ev instanceof Je)return t;var e=new Je,r=new Je;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;l4/3-s?o:s},nr.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:re.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:re.constrain(Math.floor(3*e),0,2),Ge[e][t]},nr.unhover=$e.wrapped,nr.unhoverRaw=$e.raw,nr.init=function(t){var e,r,n,i,a,o,s,l,u=t.gd,c=1,h=f.DBLCLICKDELAY,d=t.element;u._mouseDownTime||(u._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,Ve?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=t.clampFn||function(t,e,r){return Math.abs(t)h&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!l){var r;try{r=new MouseEvent("click",e)}catch(t){var n=ar(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}s.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&R.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},nr.coverSlip=ir;var or={zauto:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{zmin:void 0,zmax:void 0}},zmin:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},zmax:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},colorscale:{valType:"colorscale",editType:"calc",impliedEdits:{autocolorscale:!1}},autocolorscale:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{colorscale:void 0}},reversescale:{valType:"boolean",dflt:!1,editType:"calc"},showscale:{valType:"boolean",dflt:!0,editType:"calc"}},sr=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n},lr=function(t,e,r,n){var i,a;r?(i=re.nestedProperty(t,r).get(),a=re.nestedProperty(t._input,r).get()):(i=t,a=t._input);var o=n+"auto",s=n+"min",u=n+"max",c=i[o],h=i[s],f=i[u],d=i.colorscale;!1===c&&void 0!==h||(h=re.aggNums(Math.min,null,e)),!1===c&&void 0!==f||(f=re.aggNums(Math.max,null,e)),h===f&&(h-=.5,f+=.5),i[s]=h,i[u]=f,a[s]=h,a[u]=f,a[o]=!1!==c||void 0===h&&void 0===f,i.autocolorscale&&(d=h*f<0?l.RdBu:h>=0?l.Reds:l.Blues,a.colorscale=d,i.reversescale&&(d=sr(d)),i.colorscale=d)},ur=re.extendFlat,cr=re.isPlainObject,hr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},fr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},dr=hr.flags.slice().concat(["clearCalc","fullReplot"]),pr=fr.flags.slice().concat("layoutReplot"),gr={traces:hr,layout:fr,traceFlags:function(){return vr(dr)},layoutFlags:function(){return vr(pr)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i0?Number(l):s;else if("string"!=typeof l)r.dtick=s;else{var u=l.charAt(0),c=l.substr(1);((c=e(c)?Number(c):0)<=0||!("date"===i&&"M"===u&&c===Math.round(c)||"log"===i&&"L"===u||"log"===i&&"D"===u&&(1===c||2===c)))&&(r.dtick=s)}var h="date"===i?re.dateTick0(r.calendar):0,f=n("tick0",h);"date"===i?r.tick0=re.cleanDate(f,h):e(f)&&"D1"!==l&&"D2"!==l?r.tick0=Number(f):r.tick0=h}else{void 0===n("tickvals")?r.tickmode="auto":n("ticktext")}},Cr=function(t){return void 0!==l[t]||c(t)},Sr=function(t,r,n,i,a){var o,s=a.prefix,l=a.cLetter,u=s.slice(0,s.length-1),c=s?re.nestedProperty(t,u).get()||{}:t,h=s?re.nestedProperty(r,u).get()||{}:r,f=c[l+"min"],d=c[l+"max"],p=c.colorscale;i(s+l+"auto",!(e(f)&&e(d)&&f","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},Fr={},jr=Nr.LINE_SPACING;function Br(t,e){return t.node().getBoundingClientRect()[e]}var Ur=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;Fr.convertToTspans=function(e,r,n){var i=e.text(),a=!e.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(Ur),o=t.select(e.node().parentNode);if(!o.empty()){var s=e.attr("class")?e.attr("class").split(" ")[0]:"text";return s+="-math",o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove(),e.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),a?(r&&r._promises||[]).push(new Promise(function(r){e.style("display","none");var u=parseInt(e.node().style.fontSize,10),c={fontSize:u};!function(e,r,n){var i="math-output-"+re.randstr([],64),a=t.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=e,o.replace(Vr,"\\lt ").replace(Hr,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var r=t.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())re.log("There was an error in the tex syntax.",e),n();else{var i=a.select("svg").node().getBoundingClientRect();n(a.select(".MathJax_SVG"),r,i)}a.remove()})}(a[2],c,function(t,a,c){o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove();var h=t&&t.select("svg");if(!h||!h.node())return l(),void r();var f=o.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});f.node().appendChild(h.node()),a&&a.node()&&h.node().insertBefore(a.node().cloneNode(!0),h.node().firstChild),h.attr({class:s,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var d=e.node().style.fill||"black";h.select("g").attr({fill:d,stroke:d});var p=Br(h,"width"),g=Br(h,"height"),v=+e.attr("x")-p*{start:0,middle:.5,end:1}[e.attr("text-anchor")||"start"],m=-(u||Br(e,"height"))/4;"y"===s[0]?(f.attr({transform:"rotate("+[-90,+e.attr("x"),+e.attr("y")]+") translate("+[-p/2,m-g/2]+")"}),h.attr({x:+e.attr("x"),y:+e.attr("y")})):"l"===s[0]?h.attr({x:e.attr("x"),y:m-g/2}):"a"===s[0]?h.attr({x:0,y:m}):h.attr({x:v,y:+e.attr("y")+m-g/2}),n&&n.call(e,f),r(f)})})):l(),e}function l(){o.empty()||(s=e.attr("class")+"-math",o.select("svg."+s).remove()),e.text("").style("white-space","pre"),function(e,r){r=(n=r,function(t,e){if(!t)return"";for(var r=0;r1)for(var a=1;a doesnt match end tag <"+t+">. Pretending it did match.",r),i=o[o.length-1].node}else re.log("Ignoring unexpected end tag .",r)}tn.test(r)?l():(i=e,o=[{node:e}]);for(var f=r.split($r),d=0;d|>|>)/g;var qr={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"},Gr={sub:"0.3em",sup:"-0.6em"},Xr={sub:"-0.21em",sup:"0.42em"},Wr="\u200b",Yr=["http:","https:","mailto:","",void 0,":"],Zr=new RegExp("]*)?/?>","g"),Qr=Object.keys(zr.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:zr.entityToUnicode[t]}}),Kr=/(\r\n?|\n)/g,$r=/(<[^<>]*>)/,Jr=/<(\/?)([^ >]*)(\s+(.*))?>/i,tn=//i,en=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,rn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,nn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,an=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function on(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var sn=/(^|;)\s*color:/;function ln(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}Fr.plainText=function(t){return(t||"").replace(Zr," ")},Fr.lineCount=function(t){return t.selectAll("tspan.line").size()||1},Fr.positionText=function(e,r,n){return e.each(function(){var e=t.select(this);function i(t,r){return void 0===r?null===(r=e.attr(t))&&(e.attr(t,0),r=0):e.attr(t,r),r}var a=i("x",r),o=i("y",n);"text"===this.nodeName&&e.selectAll("tspan.line").attr({x:a,y:o})})},Fr.makeEditable=function(e,r){var n=r.gd,i=r.delegate,a=t.dispatch("edit","input","cancel"),o=i||e;if(e.style({"pointer-events":i?"none":"all"}),1!==e.size())throw new Error("boo");function s(){var i,s,u,c;i=t.select(n).select(".svg-container"),s=i.append("div"),u=e.node().style,c=parseFloat(u.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:r.fill||u.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||e.attr("data-unformatted")).call(ln(e,i,r)).on("blur",function(){n._editing=!1,e.text(this.textContent).style({opacity:1});var r,i=t.select(this).attr("class");(r=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(r).style({opacity:0});var o=this.textContent;t.select(this).transition().duration(0).remove(),t.select(document).on("mouseup",null),a.edit.call(e,o)}).on("focus",function(){var e=this;n._editing=!0,t.select(document).on("mouseup",function(){if(t.event.target===e)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===t.event.which?(n._editing=!1,e.style({opacity:1}),t.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(e,this.textContent)):(a.input.call(e,this.textContent),t.select(this).call(ln(e,i,r)))}).on("keydown",function(){13===t.event.which&&this.blur()}).call(l),e.style({opacity:0});var h,f=o.attr("class");(h=f?"."+f.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(h).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return r.immediate?s():o.on("click",s),t.rebind(e,a,"on")};var un=function(t){var r=t.marker,n=r.sizeref||1,i=r.sizemin||0,a="area"===r.sizemode?function(t){return Math.sqrt(t/n)}:function(t){return t/n};return function(t){var r=a(t/2);return e(r)&&r>0?Math.max(r,i):0}},cn={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("markers")},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return re.isPlainObject(t.marker)&&re.isArrayOrTypedArray(t.marker.size)}},hn={},fn=Nr.LINE_SPACING,dn=f.DESELECTDIM,pn=hn={};pn.font=function(t,e,r,n){re.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Ne.fill,n)},pn.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},pn.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},pn.setRect=function(t,e,r,n,i){t.call(pn.setPosition,e,r).call(pn.setSize,n,i)},pn.translatePoint=function(t,r,n,i){var a=n.c2p(t.x),o=i.c2p(t.y);return!!(e(a)&&e(o)&&r.node())&&("text"===r.node().nodeName?r.attr("x",a).attr("y",o):r.attr("transform","translate("+a+","+o+")"),!0)},pn.translatePoints=function(e,r,n){e.each(function(e){var i=t.select(this);pn.translatePoint(e,i,r,n)})},pn.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},pn.hideOutsideRangePoints=function(e,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var i=r.xaxis,a=r.yaxis;e.each(function(r){var o=r[0].trace,s=o.xcalendar,l=o.ycalendar;e.selectAll(n).each(function(e){pn.hideOutsideRangePoint(e,t.select(this),i,a,s,l)})})}},pn.crispRound=function(t,r,n){return r&&e(r)?t._context.staticPlot?r:r<1?1:Math.round(r):n||0},pn.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";Ne.stroke(e,n||a.color),pn.dashLine(e,s,o)},pn.lineGroupStyle=function(e,r,n,i){e.style("fill","none").each(function(e){var a=(((e||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";t.select(this).call(Ne.stroke,n||a.color).call(pn.dashLine,s,o)})},pn.dashLine=function(t,e,r){r=+r||0,e=pn.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},pn.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},pn.singleFillStyle=function(e){var r=(((t.select(e.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&e.call(Ne.fill,r)},pn.fillGroupStyle=function(e){e.style("stroke-width",0).each(function(r){var n=t.select(this);try{n.call(Ne.fill,r[0].trace.fillcolor)}catch(t){re.error(t,e),n.remove()}})},pn.symbolNames=[],pn.symbolFuncs=[],pn.symbolNeedLines={},pn.symbolNoDot={},pn.symbolNoFill={},pn.symbolList=[],Object.keys(Ir).forEach(function(t){var e=Ir[t];pn.symbolList=pn.symbolList.concat([e.n,t,e.n+100,t+"-open"]),pn.symbolNames[e.n]=t,pn.symbolFuncs[e.n]=e.f,e.needLine&&(pn.symbolNeedLines[e.n]=!0),e.noDot?pn.symbolNoDot[e.n]=!0:pn.symbolList=pn.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(pn.symbolNoFill[e.n]=!0)});var gn=pn.symbolNames.length,vn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function mn(t,e){var r=t%100;return pn.symbolFuncs[r](e)+(t>=200?vn:"")}pn.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=pn.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=gn||t>=400?0:Math.floor(Math.max(t,0))};var yn={x1:1,x2:0,y1:0,y2:0},bn={x1:0,x2:0,y1:1,y2:0};pn.gradient=function(e,r,n,i,a,o){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([i+a+o],re.identity);l.exit().remove(),l.enter().append("radial"===i?"radialGradient":"linearGradient").each(function(){var e=t.select(this);"horizontal"===i?e.attr(yn):"vertical"===i&&e.attr(bn),e.attr("id",n);var r=s(a),l=s(o);e.append("stop").attr({offset:"0%","stop-color":Ne.tinyRGB(l),"stop-opacity":l.getAlpha()}),e.append("stop").attr({offset:"100%","stop-color":Ne.tinyRGB(r),"stop-opacity":r.getAlpha()})}),e.style({fill:"url(#"+n+")","fill-opacity":null})},pn.initGradients=function(t){var e=t._fullLayout._defs.selectAll(".gradients").data([0]);e.enter().append("g").classed("gradients",!0),e.selectAll("linearGradient,radialGradient").remove()},pn.singlePointStyle=function(t,e,r,n,i,a){var o=r.marker;!function(t,e,r,n,i,a,o,s){if(R.traceIs(r,"symbols")){var l=un(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===a.size?3:cn.isBubble(r)?l(t.ms):(a.size||6)/2,t.mrc=e;var n=pn.symbolNumber(t.mx||a.symbol)||0;return t.om=n%200>=100,mn(n,e)})}e.style("opacity",function(t){return(t.mo+1||a.opacity+1)-1});var u,c,h,f=!1;if(t.so?(h=o.outlierwidth,c=o.outliercolor,u=a.outliercolor):(h=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=i(t.mlc):re.isArrayOrTypedArray(o.color)?Ne.defaultLine:o.color,re.isArrayOrTypedArray(a.color)&&(u=Ne.defaultLine,f=!0),u="mc"in t?t.mcc=n(t.mc):a.color||"rgba(0,0,0,0)"),t.om)e.call(Ne.stroke,u).style({"stroke-width":(h||1)+"px",fill:"none"});else{e.style("stroke-width",h+"px");var d=a.gradient,p=t.mgt;if(p?f=!0:p=d&&d.type,p&&"none"!==p){var g=t.mgc;g?f=!0:g=d.color;var v="g"+s._fullLayout._uid+"-"+r.uid;f&&(v+="-"+t.i),e.call(pn.gradient,s,v,p,u,g)}else e.call(Ne.fill,u);h&&e.call(Ne.stroke,c)}}(t,e,r,n,i,o,o.line,a)},pn.pointStyle=function(e,r,n){if(e.size()){var i=r.marker,a=pn.tryColorscale(i,""),o=pn.tryColorscale(i,"line");e.each(function(e){pn.singlePointStyle(e,t.select(this),r,a,o,n)})}},pn.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},a=r.marker||{},o=n.marker||{},s=i.opacity,l=a.opacity,u=o.opacity,c=void 0!==l,h=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||h){if(!t.selected)return h?u:dn*(r?e:s);if(c)return l}};var f=a.color,d=o.color;(f||d)&&(e.colorFn=function(t){if(t.selected){if(f)return f}else if(d)return d});var p=a.size,g=o.size,v=void 0!==p,m=void 0!==g;return(v||m)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?v?p/2:e:m?g/2:e}),e},pn.selectedPointStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=pn.makeSelectedPointStyleFns(r),i=r.marker||{};e.each(function(e){var r=t.select(this),i=n.opacityFn(e);void 0!==i&&r.style("opacity",i)}),n.colorFn&&e.each(function(e){var r=t.select(this),i=n.colorFn(e);i&&Ne.fill(r,i)}),R.traceIs(r,"symbols")&&n.sizeFn&&e.each(function(e){var r=t.select(this),a=e.mx||i.symbol||0,o=n.sizeFn(e);r.attr("d",mn(pn.symbolNumber(a),o)),e.mrc2=o})}},pn.tryColorscale=function(t,e){var r=e?re.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&re.isArrayOrTypedArray(i)?Or.makeColorScaleFunc(Or.extractScale(n,r.cmin,r.cmax)):re.identity};var xn={start:1,end:-1,middle:0,bottom:1,top:-1};function _n(e,r,n,i){var a=t.select(e.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",s=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",l=i?i/.8+1:0,u=(Fr.lineCount(e)-1)*fn+1,c=xn[s]*l,h=.75*n+xn[o]*l+(xn[o]-1)*u*n/2;e.attr("text-anchor",s),a.attr("transform","translate("+c+","+h+")")}function wn(t,r){var n=t.ts||r.textfont.size;return e(n)&&n>0?n:0}pn.textPointStyle=function(e,r,n){e.each(function(e){var i=t.select(this),a=re.extractOption(e,r,"tx","text");if(a){var o=e.tp||r.textposition,s=wn(e,r);i.call(pn.font,e.tf||r.textfont.family,s,e.tc||r.textfont.color).text(a).call(Fr.convertToTspans,n).call(_n,o,s,e.mrc)}else i.remove()})},pn.selectedTextStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=r.selected||{},i=r.unselected||{};e.each(function(e){var a,o=t.select(this),s=e.tc||r.textfont.color,l=e.tp||r.textposition,u=wn(e,r),c=(n.textfont||{}).color,h=(i.textfont||{}).color;e.selected?c&&(a=c):h?a=h:c||(a=Ne.addOpacity(s,dn)),a&&Ne.fill(o,a),_n(o,l,u,e.mrc2||e.mrc)})}};var Mn=.5;function An(e,r,n,i){var a=e[0]-r[0],o=e[1]-r[1],s=n[0]-r[0],l=n[1]-r[1],u=Math.pow(a*a+o*o,Mn/2),c=Math.pow(s*s+l*l,Mn/2),h=(c*c*a-u*u*s)*i,f=(c*c*o-u*u*l)*i,d=3*c*(u+c),p=3*u*(u+c);return[[t.round(r[0]+(d&&h/d),2),t.round(r[1]+(d&&f/d),2)],[t.round(r[0]-(p&&h/p),2),t.round(r[1]-(p&&f/p),2)]]}pn.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(pn.savedBBoxes={},En=0),n&&(pn.savedBBoxes[n]=p),En++,re.extendFlat({},p)},pn.setClipUrl=function(e,r){if(r){var n="#"+r,i=t.select("base");i.size()&&i.attr("href")&&(n=window.location.href.split("#")[0]+n),e.attr("clip-path","url("+n+")")}else e.attr("clip-path",null)},pn.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},pn.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},pn.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},pn.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a},pn.setPointGroupScale=function(t,e,r){var n,i,a;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",a=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(a,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var Cn=/translate\([^)]*\)\s*$/;pn.setTextPointsScale=function(e,r,n){e.each(function(){var e,i=t.select(this),a=i.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(i.attr("transform")||"").match(Cn);e=1===r&&1===n?[]:["translate("+o+","+s+")","scale("+r+","+n+")","translate("+-o+","+-s+")"],l&&e.push(l),i.attr("transform",e.join(" "))}})};function Sn(t,e,r,n){n=n||re.identity,Array.isArray(t)&&(e[0][r]=n(t))}var Pn={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},flat:function(t,e){for(var r=new Array(t.length),n=0;n=0&&r.index=a.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!oi(o))return!1;t=a[i][o]}else t=a[i]}else t=a}}return t}function oi(t){return t===Math.round(t)&&t>=0}function si(t){return function(t){Jn.crawl(t,function(t,e,r){Jn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):re.isPlainObject(t)&&(t.role="object")})}(t),function(t){Jn.crawl(t,function(t,e,r){if(!t)return;var n=t[ni];if(!n)return;delete t[ni],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),t}function li(t,e,r){var n=re.nestedProperty(t,r),i=ei({},e.layoutAttributes);i[ri]=!0,n.set(i)}function ui(t,e,r){var n=re.nestedProperty(t,r);n.set(ei(n.get()||{},e))}Jn.IS_SUBPLOT_OBJ=ri,Jn.IS_LINKED_TO_ARRAY=ni,Jn.DEPRECATED="_deprecated",Jn.UNDERSCORE_ATTRS=ii,Jn.get=function(){var t={};R.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:Wn},r={}):(e=R.modules[t]._module,r=e.basePlotModule);var n={type:null};ei(n,L),ei(n,e.attributes),r.attributes&&ei(n,r.attributes);n.type=t;var i={meta:e.meta||{},attributes:si(n)};if(e.layoutAttributes){var a={};ei(a,e.layoutAttributes),i.layoutAttributes=si(a)}return i}(e)});var e,r={};return Object.keys(R.transformsRegistry).forEach(function(t){r[t]=function(t){var e=R.transformsRegistry[t],r=ei({},e.attributes);return Object.keys(R.componentsRegistry).forEach(function(e){var n=R.componentsRegistry[e];n.schema&&n.schema.transforms&&n.schema.transforms[t]&&Object.keys(n.schema.transforms[t]).forEach(function(e){ui(r,n.schema.transforms[t][e],e)})}),{attributes:si(r)}}(t)}),{defs:{valObjects:re.valObjectMeta,metaKeys:ii.concat(["description","role","editType","impliedEdits"]),editType:{traces:gr.traces,layout:gr.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in ei(r,P),R.subplotsRegistry)if((e=R.subplotsRegistry[t]).layoutAttributes)if("cartesian"===e.name)li(r,e,"xaxis"),li(r,e,"yaxis");else{var n="subplot"===e.attr?e.name:e.attr;li(r,e,n)}for(t in r=function(t){return ti(t,{radialaxis:$n.radialaxis,angularaxis:$n.angularaxis}),ti(t,$n.layout),t}(r),R.componentsRegistry){var i=(e=R.componentsRegistry[t]).schema;if(i&&(i.subplots||i.layout)){var a=i.subplots;if(a&&a.xaxis&&!a.yaxis)for(var o in a.xaxis)delete r.yaxis[o]}else e.layoutAttributes&&ui(r,e.layoutAttributes,e.name)}return{layoutAttributes:si(r)}}(),transforms:r,frames:(e={frames:re.extendDeepAll({},jn)},si(e),e.frames),animation:si(Fn)}},Jn.crawl=function(t,e,r,n){var i=r||0;n=n||"",Object.keys(t).forEach(function(r){var a=t[r];if(-1===ii.indexOf(r)){var o=(n?n+".":"")+r;e(a,r,t,i,o),Jn.isValObject(a)||re.isPlainObject(a)&&"impliedEdits"!==r&&Jn.crawl(a,e,i+1,o)}})},Jn.isValObject=function(t){return t&&void 0!==t.valType},Jn.findArrayAttributes=function(t){var e=[],r=[];function n(n,i,a,o){if(r=r.slice(0,o).concat([i]),n&&("data_array"===n.valType||!0===n.arrayOk)&&!("colorbar"===r[o-1]&&("ticktext"===i||"tickvals"===i))){var s=function(t){return t.join(".")}(r),l=re.nestedProperty(t,s).get();re.isArrayOrTypedArray(l)&&e.push(s)}}if(Jn.crawl(L,n),t._module&&t._module.attributes&&Jn.crawl(t._module.attributes,n),t.transforms)for(var i=t.transforms,a=0;a=t.transforms.length)return!1;n=(r=(R.transformsRegistry[t.transforms[o].type]||{}).attributes)&&r[e[2]],a=3}else if("area"===t.type)n=Wn[i];else{var s=t._module;if(s||(s=(R.modules[t.type||L.type.dflt]||{})._module),!s)return!1;if(!(n=(r=s.attributes)&&r[i])){var l=s.basePlotModule;l&&l.attributes&&(n=l.attributes[i])}n||(n=L[i])}return ai(n,e,a)},Jn.getLayoutValObject=function(t,e){return ai(function(t,e){var r,n,i,a,o=t._basePlotModules;if(o){var s;for(r=0;rn?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},hi={};function fi(t,e,r){var n,i,a,o=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=re.nestedProperty(n,e.prop).get(),(a=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&a[e.prop]!==i&&(o=!0),a[e.prop]=i,{changed:o,value:i}}function di(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!re.isPlainObject(n))return r;i=n}return gi(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function pi(t,e){var r,n,i,a,o=[];if(n=e[0],i=e[1],r=e[2],a={},"string"==typeof n)a[n]=i;else{if(!re.isPlainObject(n))return o;a=n,void 0===r&&(r=i)}return void 0===r&&(r=null),gi(a,function(e,n,i){var a;if(Array.isArray(i)){var s=Math.min(i.length,t.data.length);r&&(s=Math.min(s,r.length)),a=[];for(var l=0;l0?".":"")+i;re.isPlainObject(a)?gi(a,e,o,n+1):e(o,i,a)}})}hi.manageCommandObserver=function(t,e,r,n){var i={},a=!0;e&&e._commandObserver&&(i=e._commandObserver),i.cache||(i.cache={}),i.lookupTable={};var o=hi.hasSimpleAPICommandBindings(t,r,i.lookupTable);if(e&&e._commandObserver){if(o)return i;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,i}if(o){fi(t,o,i.cache),i.check=function(){if(a){var e=fi(t,o,i.cache);return e.changed&&n&&void 0!==i.lookupTable[e.value]&&(i.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:i.lookupTable[e.value]})).then(i.enable,i.enable)),e.changed}};for(var s=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],l=0;l=r.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=r._paper.attr("width")-7),n.attr(a);var o=n.select(".js-link-to-tool"),s=n.select(".js-link-spacer"),l=n.select(".js-sourcelinks");e._context.showSources&&e._context.showSources(e),e._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){bi.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(e,o),s.text(o.text()&&l.text()?" - ":"")}},bi.sendDataToCloud=function(e){e.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=t.select(e).append("div").attr("id","hiddenform").style("display","none"),i=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=bi.graphJson(e,!1,"keepdata"),i.node().submit(),n.remove(),e.emit("plotly_afterexport"),!1};var wi,Mi=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Ai=["year","month","dayMonth","dayMonthYear"];function Ti(t,e){var r,n,i=t.trace,a=i._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},bi.cleanPlot=function(t,e,r,n){var i,a,o=n._basePlotModules||[];for(i=0;i0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,h=u.bottom+u.top,f=1-2*s,d=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};i=Math.round(f*(d.width-c)),a=Math.round(f*(d.height-h))}else{var p=l?window.getComputedStyle(t):{};i=parseFloat(p.width)||n.width,a=parseFloat(p.height)||n.height}var g=bi.layoutAttributes.width.min,v=bi.layoutAttributes.height.min;i1,y=!r.height&&Math.abs(n.height-a)>1;(y||m)&&(m&&(n.width=i),y&&(n.height=a)),t._initialAutoSize||(t._initialAutoSize={width:i,height:a}),bi.sanitizeMargins(n)},bi.supplyLayoutModuleDefaults=function(t,e,r,n){var i,a,o,s=R.componentsRegistry,l=e._basePlotModules,u=R.subplotsRegistry.cartesian;for(i in s)(o=s[i]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in l.length||l.push(u),e._has("cartesian")&&(R.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(re.subplotSort);for(a=0;a.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||bi.doAutoMargin(t)}},bi.doAutoMargin=function(t){var r=t._fullLayout;r._size||(r._size={}),r._pushmargin||(r._pushmargin={});var n=r._size,i=JSON.stringify(n),a=Math.max(r.margin.l||0,0),o=Math.max(r.margin.r||0,0),s=Math.max(r.margin.t||0,0),l=Math.max(r.margin.b||0,0),u=r._pushmargin;if(!1!==r.margin.autoexpand)for(var c in u.base={l:{val:0,size:a},r:{val:1,size:o},t:{val:1,size:s},b:{val:0,size:l}},u){var h=u[c].l||{},f=u[c].b||{},d=h.val,p=h.size,g=f.val,v=f.size;for(var m in u){if(e(p)&&u[m].r){var y=u[m].r.val,b=u[m].r.size;if(y>d){var x=(p*y+(b-r.width)*d)/(y-d),_=(b*(1-d)+(p-r.width)*(1-y))/(y-d);x>=0&&_>=0&&x+_>a+o&&(a=x,o=_)}}if(e(v)&&u[m].t){var w=u[m].t.val,M=u[m].t.size;if(w>g){var A=(v*w+(M-r.height)*g)/(w-g),T=(M*(1-g)+(v-r.height)*(1-w))/(w-g);A>=0&&T>=0&&A+T>l+s&&(l=A,s=T)}}}}if(n.l=Math.round(a),n.r=Math.round(o),n.t=Math.round(s),n.b=Math.round(l),n.p=Math.round(r.margin.pad),n.w=Math.round(r.width)-n.l-n.r,n.h=Math.round(r.height)-n.t-n.b,!r._replotting&&"{}"!==i&&i!==JSON.stringify(r._size))return R.call("plot",t)},bi.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&bi.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(re.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!re.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):re.isJSDate(t)?re.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},bi.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){h=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return R.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,s=0,l=0;function u(){return s++,function(){var r;h||++l!==s||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return R.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var f=t._fullLayout._basePlotModules,d=!1;if(r)for(o=0;o=0;a--)if(g[a].enabled){r._indexToPoints=g[a]._indexToPoints;break}n&&n.calc&&(p=n.calc(t,r))}Array.isArray(p)&&p[0]||(p=[{x:yi,y:yi}]),p[0].t||(p[0].t={}),p[0].trace=r,u[i]=p}R.getComponentMethod("fx","calc")(t)},bi.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},bi.generalUpdatePerTraceModule=function(t,e,r,n){var i,a=e.traceHash,o={};for(i=0;i0||h<0){var p={left:[-i,0],right:[i,0],top:[0,-i],bottom:[0,i]}[c.side];n.attr("transform","translate("+p+")")}}}T.call(k),M&&(w?T.on(".opacity",null):(x=0,_=!0,T.text(l).on("mouseover.opacity",function(){t.select(this).transition().duration(f.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){t.select(this).transition().duration(f.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(Fr.makeEditable,{gd:r}).on("edit",function(t){void 0!==u?R.call("restyle",r,s,t,u):R.call("relayout",r,s,t)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(k)}).on("input",function(t){this.text(t||" ").call(Fr.positionText,h.x,h.y)}));return T.classed("js-placeholder",_),p}},Si=/ [XY][0-9]* /;var Pi=r.FP_SAFE,Ri=Di,Oi=zi,Ii=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=Di(t),t._r=t.range.slice(),t._rl=re.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?Di(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=re.extendFlat({},n)}},Ni=function(t,r,n){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!r)return;t._min||(t._min=[]);t._max||(t._max=[]);n||(n={});t._m||t.setScale();var i,a,o,s,l,u,c,h,f,d,p,g,v=r.length,m=n.padded||!1,y=n.tozero&&("linear"===t.type||"-"===t.type),b="log"===t.type,x=!1;function _(t){if(Array.isArray(t))return x=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=_((t._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),M=_((t._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),A=_(n.vpadplus||n.vpad),T=_(n.vpadminus||n.vpad);if(!x){if(p=1/0,g=-1/0,b)for(i=0;i0&&(p=s),s>g&&s-Pi&&(p=s),s>g&&s=x&&(s.extrapad||!m)){d=!1;break}_(i,s.val)&&s.pad<=x&&(m||!s.extrapad)&&(v.splice(a,1),a--)}if(d){var k=y&&0===i;v.push({val:i,pad:k?0:x,extrapad:!k&&m})}}}}var E=Math.min(6,v);for(i=0;i=E;i--)k(i)};function Di(t){var e,r,n,i,a,o,s,l,u=[],c=t._min[0].val,h=t._max[0].val,f=0,d=!1,p=zi(t);for(e=1;e0&&s>0&&l/s>f&&(a=n,o=i,f=l/s);if(c===h){var v=c-1,m=c+1;u="tozero"===t.rangemode?c<0?[v,0]:[0,m]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,m)]:[v,m]}else f&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(a.val>=0&&(a={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(a.val-f*p(a)<0&&(a={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),f=(o.val-a.val)/(t._length-p(a)-p(o))),u=[a.val-f*p(a),o.val+f*p(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),d&&u.reverse(),re.simpleMap(u,t.l2r||Number)}function zi(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function Fi(t){return e(t)&&Math.abs(t)=e}var Ui=r.BADNUM,Vi=function(t,r){return function(t,r){for(var n,i=0,a=0,o=Math.max(1,(t.length-1)/1e3),s=0;s2*a}(t,r)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}(t)?"category":function(t){if(!t)return!1;for(var r=0;r0)return Math.log(t)/Math.LN10;if(t<=0&&e&&r.range&&2===r.range.length){var n=r.range[0],i=r.range[1];return.5*(n+i-3*a*Math.abs(n-i))}return Yi}function s(t,n,i){var a=Gi(t,i||r.calendar);if(a===Yi){if(!e(t))return Yi;a=Gi(new Date(+t))}return a}function l(t,e,n){return qi(t,e,n||r.calendar)}function u(t){return r._categories[Math.round(t)]}function c(t){if(r._categoriesMap){var n=r._categoriesMap[t];if(void 0!==n)return n}if(e(t))return+t}function h(n){return e(n)?t.round(r._b+r._m*n,2):Yi}function f(t){return(t-r._b)/r._m}r.c2l="log"===r.type?o:Xi,r.l2c="log"===r.type?Zi:Xi,r.l2p=h,r.p2l=f,r.c2p="log"===r.type?function(t,e){return h(o(t,e))}:h,r.p2c="log"===r.type?function(t){return Zi(f(t))}:f,-1!==["linear","-"].indexOf(r.type)?(r.d2r=r.r2d=r.d2c=r.r2c=r.d2l=r.r2l=Hi,r.c2d=r.c2r=r.l2d=r.l2r=Xi,r.d2p=r.r2p=function(t){return r.l2p(Hi(t))},r.p2d=r.p2r=f,r.cleanPos=Xi):"log"===r.type?(r.d2r=r.d2l=function(t,e){return o(Hi(t),e)},r.r2d=r.r2c=function(t){return Zi(Hi(t))},r.d2c=r.r2l=Hi,r.c2d=r.l2r=Xi,r.c2r=o,r.l2d=Zi,r.d2p=function(t,e){return r.l2p(r.d2r(t,e))},r.p2d=function(t){return Zi(f(t))},r.r2p=function(t){return r.l2p(Hi(t))},r.p2r=f,r.cleanPos=Xi):"date"===r.type?(r.d2r=r.r2d=re.identity,r.d2c=r.r2c=r.d2l=r.r2l=s,r.c2d=r.c2r=r.l2d=r.l2r=l,r.d2p=r.r2p=function(t,e,n){return r.l2p(s(t,0,n))},r.p2d=r.p2r=function(t,e,r){return l(f(t),e,r)},r.cleanPos=function(t){return re.cleanDate(t,Yi,r.calendar)}):"category"===r.type&&(r.d2c=r.d2l=function(t){if(null!==t&&void 0!==t){if(void 0===r._categoriesMap&&(r._categoriesMap={}),void 0!==r._categoriesMap[t])return r._categoriesMap[t];r._categories.push(t);var e=r._categories.length-1;return r._categoriesMap[t]=e,e}return Yi},r.r2d=r.c2d=r.l2d=u,r.d2r=r.d2l_noadd=c,r.r2c=function(t){var e=c(t);return void 0!==e?e:r.fraction2r(.5)},r.l2r=r.c2r=Xi,r.r2l=c,r.d2p=function(t){return r.l2p(r.r2c(t))},r.p2d=function(t){return u(f(t))},r.r2p=r.d2p,r.p2r=f,r.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Xi(t)}),r.fraction2r=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return r.l2r(e+t*(n-e))},r.r2fraction=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return(r.r2l(t)-e)/(n-e)},r.cleanRange=function(t,n){n||(n={}),t||(t="range");var a,o,s=re.nestedProperty(r,t).get();if(o=(o="date"===r.type?re.dfltRange(r.calendar):"y"===i?Oe.DFLTRANGEY:n.dfltRange||Oe.DFLTRANGEX).slice(),s&&2===s.length)for("date"===r.type&&(s[0]=re.cleanDate(s[0],Yi,r.calendar),s[1]=re.cleanDate(s[1],Yi,r.calendar)),a=0;a<2;a++)if("date"===r.type){if(!re.isDateTime(s[a],r.calendar)){r[t]=o;break}if(r.r2l(s[0])===r.r2l(s[1])){var l=re.constrain(r.r2l(s[0]),re.MIN_MS+1e3,re.MAX_MS-1e3);s[0]=r.l2r(l-1e3),s[1]=r.l2r(l+1e3);break}}else{if(!e(s[a])){if(!e(s[1-a])){r[t]=o;break}s[a]=s[1-a]*(a?10:.1)}if(s[a]<-Wi?s[a]=-Wi:s[a]>Wi&&(s[a]=Wi),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else re.nestedProperty(r,t).set(o)},r.setScale=function(t){var e=n._size;if(r._categories||(r._categories=[]),r._categoriesMap||(r._categoriesMap={}),r.overlaying){var a=ci.getFromId({_fullLayout:n},r.overlaying);r.domain=a.domain}var o=t&&r._r?"_r":"range",s=r.calendar;r.cleanRange(o);var l=r.r2l(r[o][0],s),u=r.r2l(r[o][1],s);if("y"===i?(r._offset=e.t+(1-r.domain[1])*e.h,r._length=e.h*(r.domain[1]-r.domain[0]),r._m=r._length/(l-u),r._b=-r._m*u):(r._offset=e.l+r.domain[0]*e.w,r._length=e.w*(r.domain[1]-r.domain[0]),r._m=r._length/(u-l),r._b=-r._m*l),!isFinite(r._m)||!isFinite(r._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},r.makeCalcdata=function(t,e){var n,i,a,o,s=r.type,l="date"===s&&t[e+"calendar"];if(e in t){if(n=t[e],o=t._length||n.length,re.isTypedArray(n)&&("linear"===s||"log"===s)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(i=new Array(o),a=0;a=r.r2l(r.range[0])&&n<=r.r2l(r.range[1])},r.clearCalc=function(){r._min=[],r._max=[],r._categories=(r._initialCategories||[]).slice(),r._categoriesMap={};for(var t=0;t2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},la.saveRangeInitial=function(t,e){for(var r=la.list(t,"",!0),n=!1,i=0;i.3*f||c(i)||c(a))){var d=n.dtick/2;t+=t+d.8){var o=Number(r.substr(1));a.exactYears>.8&&o%12==0?t=la.tickIncrement(t,"M6","reverse")+1.5*ta:a.exactMonths>.8?t=la.tickIncrement(t,"M1","reverse")+15.5*ta:t-=ta/2;var s=la.tickIncrement(t,r);if(s<=n)return s}return t}(p,t,s.dtick,l,a)),d=p,0;d<=u;)d=la.tickIncrement(d,s.dtick,!1,a),0;return{start:r.c2r(p,0,a),end:r.c2r(d,0,a),size:s.dtick,_dataSpan:u-l}},la.prepTicks=function(t){var e=re.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=re.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),la.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),xa(t)},la.calcTicks=function(t){la.prepTicks(t);var e=re.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),o=re.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],l=1.0001*o[1]-1e-4*o[0],u=Math.min(s,l),c=Math.max(s,l),h=0;Array.isArray(i)||(i=[]);var f="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:l<=n)&&!(a.length>s||l===o);l=la.tickIncrement(l,t.dtick,i,t.calendar))o=l,a.push(l);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(a.length),c=0;c10||"01-01"!==i.substr(5)?t._tickround="d":t._tickround=+r.substr(1)%12==0?"y":"m";else if(r>=ta&&a<=10||r>=15*ta)t._tickround="d";else if(r>=ra&&a<=16||r>=ea)t._tickround="M";else if(r>=na&&a<=19||r>=ra)t._tickround="S";else{var o=t.l2r(n+r).replace(/^-/,"").length;t._tickround=Math.max(a,o)-20}}else if(e(r)||"L"===r.charAt(0)){var s=t.range.map(t.r2d||Number);e(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),u=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(u)>3&&(Ma(t.exponentformat)&&!Aa(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function _a(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}la.autoTicks=function(t,r){var n;function i(t){return Math.pow(t,Math.floor(Math.log(r)/Math.LN10))}if("date"===t.type){t.tick0=re.dateTick0(t.calendar);var a=2*r;a>$i?(r/=$i,n=i(10),t.dtick="M"+12*ba(r,n,fa)):a>Ji?(r/=Ji,t.dtick="M"+ba(r,1,da)):a>ta?(t.dtick=ba(r,ta,ga),t.tick0=re.dateTick0(t.calendar,!0)):a>ea?t.dtick=ba(r,ea,da):a>ra?t.dtick=ba(r,ra,pa):a>na?t.dtick=ba(r,na,pa):(n=i(10),t.dtick=ba(r,n,fa))}else if("log"===t.type){t.tick0=0;var o=re.simpleMap(t.range,t.r2l);if(r>.7)t.dtick=Math.ceil(r);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/r);r=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,n=i(10),t.dtick="L"+ba(r,n,fa)}else t.dtick=r>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(r,1))):"angular"===t._id?(t.tick0=0,n=1,t.dtick=ba(r,n,ya)):(t.tick0=0,n=i(10),t.dtick=ba(r,n,fa));if(0===t.dtick&&(t.dtick=1),!e(t.dtick)&&"string"!=typeof t.dtick){var l=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(l)}},la.tickIncrement=function(r,n,i,a){var o=i?-1:1;if(e(n))return r+o*n;var s=n.charAt(0),l=o*Number(n.substr(1));if("M"===s)return re.incrementMonth(r,l,a);if("L"===s)return Math.log(Math.pow(10,r)+l)/Math.LN10;if("D"===s){var u="D2"===n?ma:va,c=r+.01*o,h=re.roundUp(re.mod(c,1),u,i);return Math.floor(c)+Math.log(t.round(Math.pow(10,h),1))/Math.LN10}throw"unrecognized dtick "+String(n)},la.tickFirst=function(r){var n=r.r2l||Number,i=re.simpleMap(r.range,n),a=i[1]"+s,t._prevDateHead=s));r.text=l}(t,o,n,l):"log"===t.type?function(t,r,n,i,a){var o=t.dtick,s=r.x,l=t.tickformat;"never"===a&&(a="");!i||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(l||"string"==typeof o&&"L"===o.charAt(0))r.text=Ta(Math.pow(10,s),t,a,i);else if(e(o)||"D"===o.charAt(0)&&re.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||Ma(t.exponentformat)&&Aa(u)?(r.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+ia+-u+"",r.fontSize*=1.25):(r.text=Ta(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(r.dy-=r.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);r.text=String(Math.round(Math.pow(10,re.mod(s,1)))),r.fontSize*=.75}if("D1"===t.dtick){var c=String(r.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?r.dx-=r.fontSize/4:(r.dy+=r.fontSize/2,r.dx+=(t.range[1]>t.range[0]?1:-1)*r.fontSize*(s<0?.5:.25)))}}(t,o,0,l,i):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=Ta(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(o[1]>=100)e.text=Ta(re.deg2rad(e.x),t,i,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),s&&(e.text=ia+e.text)}}}}(t,o,n,l,i):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=Ta(e.x,t,i,n)}(t,o,0,l,i),t.tickprefix&&!f(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!f(t.showticksuffix)&&(o.text+=t.ticksuffix),o},la.hoverLabelText=function(t,e,r){if(r!==aa&&r!==e)return la.hoverLabelText(t,e)+" - "+la.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=la.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":ia+i:i};var wa=["f","p","n","\u03bc","m","","k","M","G","T"];function Ma(t){return"SI"===t||"B"===t}function Aa(t){return t>14||t<-15}function Ta(t,r,n,i){var a=t<0,o=r._tickround,s=n||r.exponentformat||"B",l=r._tickexponent,u=la.getTickFormat(r),c=r.separatethousands;if(i){var h={exponentformat:s,dtick:"none"===r.showexponent?r.dtick:e(t)&&Math.abs(t)||1,range:"none"===r.showexponent?r.range.map(r.r2d):[0,t||1]};xa(h),o=(Number(h._tickround)||0)+4,l=h._tickexponent,r.hoverformat&&(u=r.hoverformat)}if(u)return r._numFormat(u)(t).replace(/-/g,ia);var f,d=Math.pow(10,-o)/2;if("none"===s&&(l=0),(t=Math.abs(t))"+f+"":"B"===s&&9===l?t+="B":Ma(s)&&(t+=wa[l/3+5]));return a?ia+t:t}function ka(t,e){for(var r=0;r=0,a=u(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=a(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n-1&&s.length>p&&(s=p>3?s.substr(0,p-3)+"...":s.substr(0,p))}void 0!==e.extraText&&(l+=e.extraText),void 0!==e.zLabel?(void 0!==e.xLabel&&(l+="x: "+e.xLabel+"
"),void 0!==e.yLabel&&(l+="y: "+e.yLabel+"
"),l+=(l?"z: ":"")+e.zLabel):w&&e[i+"Label"]===v?l=e[("x"===i?"y":"x")+"Label"]||"":void 0===e.xLabel?void 0!==e.yLabel&&(l=e.yLabel):l=void 0===e.yLabel?e.xLabel:"("+e.xLabel+", "+e.yLabel+")",e.text&&!Array.isArray(e.text)&&(l+=(l?"
":"")+e.text),""===l&&(""===s&&r.remove(),l=s);var g=r.select("text.nums").call(hn.font,e.fontFamily||c,e.fontSize||h,e.fontColor||d).text(l).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),m=r.select("text.name"),y=0;s&&s!==l?(m.call(hn.font,e.fontFamily||c,e.fontSize||h,f).text(s).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),y=m.node().getBoundingClientRect().width+2*Da):(m.remove(),r.select("rect").remove()),r.select("path").style({fill:f,stroke:d});var M,A,T=g.node().getBoundingClientRect(),k=e.xa._offset+(e.x0+e.x1)/2,E=e.ya._offset+(e.y0+e.y1)/2,L=Math.abs(e.x1-e.x0),C=Math.abs(e.y1-e.y0),S=T.width+Na+Da+y;e.ty0=b-T.top,e.bx=T.width+2*Da,e.by=T.height+2*Da,e.anchor="start",e.txwidth=T.width,e.tx2width=y,e.offset=0,a?(e.pos=k,M=E+C/2+S<=_,A=E-C/2-S>=0,"top"!==e.idealAlign&&M||!A?M?(E+=C/2,e.anchor="start"):e.anchor="middle":(E-=C/2,e.anchor="end")):(e.pos=E,M=k+L/2+S<=x,A=k-L/2-S>=0,"left"!==e.idealAlign&&M||!A?M?(k+=L/2,e.anchor="start"):e.anchor="middle":(k-=L/2,e.anchor="end")),g.attr("text-anchor",e.anchor),y&&m.attr("text-anchor",e.anchor),r.attr("transform","translate("+k+","+E+")"+(a?"rotate("+Sa+")":""))}),L}function Fa(e,r){e.each(function(e){var n=t.select(this);if(e.del)n.remove();else{var i="end"===e.anchor?-1:1,a=n.select("text.nums"),o={start:1,end:-1,middle:0}[e.anchor],s=o*(Na+Da),l=s+o*(e.txwidth+Da),u=0,c=e.offset;"middle"===e.anchor&&(s-=e.tx2width/2,l+=e.txwidth/2+Da),r&&(c*=-Ia,u=e.offset*Oa),n.select("path").attr("d","middle"===e.anchor?"M-"+(e.bx/2+e.tx2width/2)+","+(c-e.by/2)+"h"+e.bx+"v"+e.by+"h-"+e.bx+"Z":"M0,0L"+(i*Na+u)+","+(Na+c)+"v"+(e.by/2-Na)+"h"+i*e.bx+"v-"+e.by+"H"+(i*Na+u)+"V"+(c-Na)+"Z"),a.call(Fr.positionText,s+u,c+e.ty0-e.by/2+Da),e.tx2width&&(n.select("text.name").call(Fr.positionText,l+o*Da+u,c+e.ty0-e.by/2+Da),n.select("rect").call(hn.setRect,l+(o-1)*e.tx2width/2+u,c-e.by/2-1,e.tx2width,e.by+2))}})}function ja(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return re.castOption(i,r,t)||re.extractOption({},n,"",e)}:function(t,e){return re.extractOption(a,n,t,e)};function s(e,r,n){var i=o(r,n);i&&(t[e]=i)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=re.constrain(t.x0,0,t.xa._length),t.x1=re.constrain(t.x1,0,t.xa._length),t.y0=re.constrain(t.y0,0,t.ya._length),t.y1=re.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:Ki.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:Ki.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var l=Ki.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+l+" / -"+Ki.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+l,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=Ki.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+Ki.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function Ba(t,e){var r,n,i=e.container,a=e.fullLayout,o=e.event,l=!!t.hLinePoint,u=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),u||l){var c=Ne.combine(a.plot_bgcolor,a.paper_bgcolor);if(l){var h,f,d=t.hLinePoint;r=d&&d.xa,"cursor"===(n=d&&d.ya).spikesnap?(h=o.pointerX,f=o.pointerY):(h=r._offset+d.x,f=n._offset+d.y);var p,g,v=s.readability(d.color,c)<1.5?Ne.contrast(c):d.color,m=n.spikemode,y=n.spikethickness,b=n.spikecolor||v,x=n._boundingBox,_=(x.left+x.right)/2H.width||U<0||U>H.height)return rr.unhoverRaw(r,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(_="xval"in n?Pn.flat(o,n.xval):Pn.p2c(d,B),w="yval"in n?Pn.flat(o,n.yval):Pn.p2c(p,U),!e(_[0])||!e(w[0]))return re.warn("Fx.hover failed",n,r),rr.unhoverRaw(r,n)}var q=1/0;for(A=0;AI&&(z.splice(0,I),q=z[0].distance),c&&0!==D&&0===z.length){O.distance=D,O.index=!1;var Z=k._module.hoverPoints(O,S,P,"closest",s._hoverlayer);if(Z&&(Z=Z.filter(function(t){return t.spikeDistance<=D})),Z&&Z.length){var Q,K=Z.filter(function(t){return t.xa.showspikes});if(K.length){var $=K[0];e($.x0)&&e($.y0)&&(Q=rt($),(!j.vLinePoint||j.vLinePoint.spikeDistance>Q.spikeDistance)&&(j.vLinePoint=Q))}var J=Z.filter(function(t){return t.ya.showspikes});if(J.length){var tt=J[0];e(tt.x0)&&e(tt.y0)&&(Q=rt(tt),(!j.hLinePoint||j.hLinePoint.spikeDistance>Q.spikeDistance)&&(j.hLinePoint=Q))}}}}function et(t,e){for(var r,n=null,i=1/0,a=0;a1,gt=Ne.combine(s.plot_bgcolor||Ne.background,s.paper_bgcolor),vt={hovermode:x,rotateLabels:pt,bgColor:gt,container:s._hoverlayer,outerContainer:s._paperdiv,commonLabelOpts:s.hoverlabel,hoverdistance:s.hoverdistance},mt=za(z,vt,r);if(function(t,e,r){var n,i,a,o,s,l,u,c=0,h=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?Ra:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function f(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(s=p.length-1;s>=0;s--)p[s].dp+=i;for(d.push.apply(d,p),h.splice(o+1,1),u=0,s=d.length-1;s>=0;s--)u+=d[s].dp;for(a=u/d.length,s=d.length-1;s>=0;s--)d[s].dp-=a;n=!1}else o++}h.forEach(f)}for(o=h.length-1;o>=0;o--){var m=h[o];for(s=m.length-1;s>=0;s--){var y=m[s],b=t[y.i];b.offset=y.dp,b.del=y.del}}}(z,pt?"xa":"ya",s),Fa(mt,pt),n.target&&n.target.tagName){var yt=R.getComponentMethod("annotations","hasClickToShow")(r,ft);zn(t.select(n.target),yt?"pointer":"")}if(!n.target||a||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}(r,0,ht))return;ht&&r.emit("plotly_unhover",{event:n,points:ht});r.emit("plotly_hover",{event:n,points:r._hoverdata,xaxes:d,yaxes:p,xvals:_,yvals:w})}(r,n,i,a)})},Ca.loneHover=function(e,r){var n={color:e.color||Ne.defaultLine,x0:e.x0||e.x||0,x1:e.x1||e.x||0,y0:e.y0||e.y||0,y1:e.y1||e.y||0,xLabel:e.xLabel,yLabel:e.yLabel,zLabel:e.zLabel,text:e.text,name:e.name,idealAlign:e.idealAlign,borderColor:e.borderColor,fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},i=t.select(r.container),a=r.outerContainer?t.select(r.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||Ne.background,container:i,outerContainer:a},s=za([n],o,r.gd);return Fa(s,o.rotateLabels),s.node()};var Va=Ca.hover,Ha=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),re.coerceFont(r,"hoverlabel.font",n.font)},qa=k({editType:"none"});qa.family.dflt=Xe.HOVERFONT,qa.size.dflt=Xe.HOVERFONTSIZE;var Ga={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:qa,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var Xa={moduleType:"component",name:"fx",constants:Xe,schema:{layout:Ga},attributes:E,layoutAttributes:Ga,supplyLayoutGlobalDefaults:function(t,e){Ha(0,0,function(r,n){return re.coerce(t,e,Ga,r,n)})},supplyDefaults:function(t,e,r,n){Ha(0,0,function(r,n){return re.coerce(t,e,E,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return re.coerce(t,e,Ga,r,n)}var i;n("dragmode"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}r._w=L,r._h=C;for(var I=!1,N=["x","y"],D=0;D1)&&(q===H?((J=G.r2fraction(r["a"+V]))<0||J>1)&&(I=!0):I=!0,I))continue;z=G._offset+G.r2p(r[V]),B=.5}else"x"===V?(j=r[V],z=c.l+c.w*j):(j=1-r[V],z=c.t+c.h*j),B=r.showarrow?.5:j;if(r.showarrow){$.head=z;var tt=r["a"+V];U=W*O(.5,r.xanchor)-Y*O(.5,r.yanchor),q===H?($.tail=G._offset+G.r2p(tt),F=U):($.tail=z+tt,F=U+tt),$.text=$.tail+U;var et=u["x"===V?"width":"height"];if("paper"===H&&($.head=re.constrain($.head,1,et-1)),"pixel"===q){var rt=-Math.max($.tail-3,$.text),nt=Math.min($.tail+3,$.text)-et;rt>0?($.tail+=rt,$.text+=rt):nt>0&&($.tail-=nt,$.text-=nt)}$.tail+=K,$.head+=K}else F=U=Z*O(B,Q),$.text=z+U;$.text+=K,U+=K,F+=K,r["_"+V+"padplus"]=Z/2+F,r["_"+V+"padminus"]=Z/2-F,r["_"+V+"size"]=Z,r["_"+V+"shift"]=U}if(I)b.remove();else{var it=0,at=0;if("left"!==r.align&&(it=(L-_)*("center"===r.align?.5:1)),"top"!==r.valign&&(at=(C-k)*("middle"===r.valign?.5:1)),s)n.select("svg").attr({x:w+it-1,y:w+at}).call(hn.setClipUrl,A?f:null);else{var ot=w+at-y.top,st=w+it-y.left;E.call(Fr.positionText,st,ot).call(hn.setClipUrl,A?f:null)}T.select("rect").call(hn.setRect,w,w,L,C),M.call(hn.setRect,x/2,x/2,S-x,P-x),b.call(hn.setTranslate,Math.round(d.x.text-S/2),Math.round(d.y.text-P/2)),v.attr({transform:"rotate("+p+","+d.x.text+","+d.y.text+")"});var lt,ut,ct=function(t,n){g.selectAll(".annotation-arrow-g").remove();var s=d.x.head,u=d.y.head,f=d.x.tail+t,m=d.y.tail+n,y=d.x.text+t,x=d.y.text+n,_=re.rotationXYMatrix(p,y,x),w=re.apply2DTransform(_),A=re.apply2DTransform2(_),T=+M.attr("width"),k=+M.attr("height"),E=y-.5*T,L=E+T,C=x-.5*k,S=C+k,P=[[E,C,E,S],[E,S,L,S],[L,S,L,C],[L,C,E,C]].map(A);if(!P.reduce(function(t,e){return t^!!re.segmentsIntersect(s,u,s+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){P.forEach(function(t){var e=re.segmentsIntersect(f,m,s,u,t[0],t[1],t[2],t[3]);e&&(f=e.x,m=e.y)});var O=r.arrowwidth,I=r.arrowcolor,N=r.arrowside,D=g.append("g").style({opacity:Ne.opacity(I)}).classed("annotation-arrow-g",!0),z=D.append("path").attr("d","M"+f+","+m+"L"+s+","+u).style("stroke-width",O+"px").call(Ne.stroke,Ne.rgb(I));if(Be(z,N,r),h.annotationPosition&&z.node().parentNode&&!i){var F=s,j=u;if(r.standoff){var B=Math.sqrt(Math.pow(s-f,2)+Math.pow(u-m,2));F+=r.standoff*(f-s)/B,j+=r.standoff*(m-u)/B}var U,V,H,q=D.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(f-F)+","+(m-j),transform:"translate("+F+","+j+")"}).style("stroke-width",O+6+"px").call(Ne.stroke,"rgba(0,0,0,0)").call(Ne.fill,"rgba(0,0,0,0)");rr.init({element:q.node(),gd:e,prepFn:function(){var t=hn.getTranslate(b);V=t.x,H=t.y,U={},a&&a.autorange&&(U[a._name+".autorange"]=!0),o&&o.autorange&&(U[o._name+".autorange"]=!0)},moveFn:function(t,e){var n=w(V,H),i=n[0]+t,s=n[1]+e;b.call(hn.setTranslate,i,s),U[l+".x"]=a?a.p2r(a.r2p(r.x)+t):r.x+t/c.w,U[l+".y"]=o?o.p2r(o.r2p(r.y)+e):r.y-e/c.h,r.axref===r.xref&&(U[l+".ax"]=a.p2r(a.r2p(r.ax)+t)),r.ayref===r.yref&&(U[l+".ay"]=o.p2r(o.r2p(r.ay)+e)),D.attr("transform","translate("+t+","+e+")"),v.attr({transform:"rotate("+p+","+i+","+s+")"})},doneFn:function(){R.call("relayout",e,U);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}};if(r.showarrow&&ct(0,0),m)rr.init({element:b.node(),gd:e,prepFn:function(){ut=v.attr("transform"),lt={}},moveFn:function(t,e){var n="pointer";if(r.showarrow)r.axref===r.xref?lt[l+".ax"]=a.p2r(a.r2p(r.ax)+t):lt[l+".ax"]=r.ax+t,r.ayref===r.yref?lt[l+".ay"]=o.p2r(o.r2p(r.ay)+e):lt[l+".ay"]=r.ay+e,ct(t,e);else{if(i)return;if(a)lt[l+".x"]=a.p2r(a.r2p(r.x)+t);else{var s=r._xsize/c.w,u=r.x+(r._xshift-r.xshift)/c.w-s/2;lt[l+".x"]=rr.align(u+t/c.w,s,0,1,r.xanchor)}if(o)lt[l+".y"]=o.p2r(o.r2p(r.y)+e);else{var h=r._ysize/c.h,f=r.y-(r._yshift+r.yshift)/c.h-h/2;lt[l+".y"]=rr.align(f-e/c.h,h,0,1,r.yanchor)}a&&o||(n=rr.getCursor(a?.5:lt[l+".x"],o?.5:lt[l+".y"],r.xanchor,r.yanchor))}v.attr({transform:"translate("+t+","+e+")"+ut}),Nn(b,n)},doneFn:function(){Nn(b),R.call("relayout",e,lt);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}}var Qa=Wa.draw;function Ka(t){var e=t._fullLayout;re.filterVisible(e.annotations).forEach(function(e){var r,n,i,a,o=Ki.getFromId(t,e.xref),s=Ki.getFromId(t,e.yref),l=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=l+e.xshift,n=l-e.xshift,i=u+e.xshift,a=u-e.xshift,e.axref===e.xref?(Ki.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),Ki.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,a)})):(i=e.ax?i+e.ax:i,a=e.ax?a-e.ax:a,Ki.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,a)}))),s&&s.autorange&&(r=l-e.yshift,n=l+e.yshift,i=u-e.yshift,a=u+e.yshift,e.ayref===e.yref?(Ki.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),Ki.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,a)})):(i=e.ay?i+e.ay:i,a=e.ay?a-e.ay:a,Ki.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,a)})))})}var $a={hasClickToShow:function(t,e){var r=Ja(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=Ja(t,e),i=n.on,a=n.off.concat(n.explicitOff),o={};if(!i.length&&!a.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+i+'"]').remove():(a._pdata=co(t.glplot.cameraParams,[e.xaxis.r2l(a.x)*r[0],e.yaxis.r2l(a.y)*r[1],e.zaxis.r2l(a.z)*r[2]]),ho(t.graphDiv,a,i,t.id,a._xa,a._ya))}}};var go={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},vo=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+n[e],a=+i[e];return isNaN(r)&&isNaN(a)?[NaN,NaN]:[a||0,r||0]}}var a=mo(e,t.value),o=mo(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=a(t);return[e,e]}:function(t){return[o(t),a(t)]}};function mo(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var yo=function(t){for(var e=t.calcdata,r=0;r0;r.each(function(r){var l,u=r[0].trace,c=u.error_x||{},h=u.error_y||{};u.ids&&(l=function(t){return t.id});var f=cn.hasMarkers(u)&&u.marker.maxdisplayed>0;h.visible||c.visible||(r=[]);var d=t.select(this).selectAll("g.errorbar").data(r,l);if(d.exit().remove(),r.length){c.visible||d.selectAll("path.xerror").remove(),h.visible||d.selectAll("path.yerror").remove(),d.style("opacity",1);var p=d.enter().append("g").classed("errorbar",!0);s&&p.style("opacity",0).transition().duration(i.duration).style("opacity",1),hn.setClipUrl(d,n.layerClipId),d.each(function(r){var n=t.select(this),l=function(t,r,n){var i={x:r.c2p(t.x),y:n.c2p(t.y)};return void 0!==t.yh&&(i.yh=n.c2p(t.yh),i.ys=n.c2p(t.ys),e(i.ys)||(i.noYS=!0,i.ys=n.c2p(t.ys,!0))),void 0!==t.xh&&(i.xh=r.c2p(t.xh),i.xs=r.c2p(t.xs),e(i.xs)||(i.noXS=!0,i.xs=r.c2p(t.xs,!0))),i}(r,a,o);if(!f||r.vis){var u,d=n.select("path.yerror");if(h.visible&&e(l.x)&&e(l.yh)&&e(l.ys)){var p=h.width;u="M"+(l.x-p)+","+l.yh+"h"+2*p+"m-"+p+",0V"+l.ys,l.noYS||(u+="m-"+p+",0h"+2*p),d.size()?s&&(d=d.transition().duration(i.duration).ease(i.easing)):d=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),d.attr("d",u)}else d.remove();var g=n.select("path.xerror");if(c.visible&&e(l.y)&&e(l.xh)&&e(l.xs)){var v=(c.copy_ystyle?h:c).width;u="M"+l.xh+","+(l.y-v)+"v"+2*v+"m0,-"+v+"H"+l.xs,l.noXS||(u+="m0,-"+v+"v"+2*v),g.size()?s&&(g=g.transition().duration(i.duration).ease(i.easing)):g=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",u)}else g.remove()}})}})},style:function(e){e.each(function(e){var r=e[0].trace,n=r.error_y||{},i=r.error_x||{},a=t.select(this);a.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(Ne.stroke,n.color),i.copy_ystyle&&(i=n),a.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(Ne.stroke,i.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var Ao={},To=m.extendFlat;Ao.attributes=function(t,e){t=t||{},e=e||{};var r={valType:"info_array",editType:t.editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},n=(t.name&&t.name,t.trace,e.description&&e.description,{x:To({},r,{}),y:To({},r,{}),editType:t.editType});return t.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:t.editType},n.column={valType:"integer",min:0,dflt:0,editType:t.editType}),n},Ao.defaults=function(t,e,r,n){var i=n&&n.x||[0,1],a=n&&n.y||[0,1],o=e.grid;if(o){var s=r("domain.column");void 0!==s&&(s1){a||o||s||"independent"===f("pattern")&&(a=!0),l._hasSubplotGrid=a;var h="top to bottom"===f("roworder");l._domains={x:So("x",f,a?.2:.1,c),y:So("y",f,a?.3:.1,u,h)}}}function f(t,e){return re.coerce(r,l,Co,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,a,o,s,l,u,c=t.grid,h=e._subplots,f=r._hasSubplotGrid,d=r.rows,p=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(f){var m=c.subplots||[];l=r.subplots=new Array(d);var y=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},Bo={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Uo=!0,Vo=function(t,e,r){if(!e._dragged&&!e._editing){var n,i,a,o,s,l=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,h=u.trace,f=h.legendgroup,d={},p=[],g=[],v=[];if(1===r&&Uo&&e.data&&e._context.showTips?(re.notifier(re._(e,"Double-click on legend to isolate one trace"),"long"),Uo=!1):Uo=!1,R.traceIs(h,"pie")){var m=u.label,y=l.indexOf(m);1===r?-1===y?l.push(m):l.splice(y,1):2===r&&(l=[],e.calcdata[0].forEach(function(t){m!==t.label&&l.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===l.length&&-1===y&&(l=[])),R.call("relayout",e,"hiddenlabels",l)}else{var b,x=f&&f.length,_=[];if(x)for(n=0;nr[1])return r[1]}return i}function h(t){return t[0]}if(s||l||u){var f={},d={};s&&(f.mc=c("marker.color",h),f.mo=c("marker.opacity",re.mean,[.2,1]),f.ms=c("marker.size",re.mean,[2,16]),f.mlc=c("marker.line.color",h),f.mlw=c("marker.line.width",re.mean,[0,5]),d.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(d.line={width:c("line.width",h,[0,10])}),l&&(f.tx="Aa",f.tp=c("textposition",h),f.ts=10,f.tc=c("textfont.color",h),f.tf=c("textfont.family",h)),n=[re.minExtend(a,f)],i=re.minExtend(o,d)}var p=t.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(s?n:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(hn.pointStyle,i,r),s&&(n[0].mrc=3);var v=p.selectAll("g.pointtext").data(l?n:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(hn.textPointStyle,i,r)})},Wo=Nr.LINE_SPACING,Yo=Nr.FROM_TL,Zo=Nr.FROM_BR,Qo=f.DBLCLICKDELAY;function Ko(t,e){var r=t.data()[0][0],n=e._fullLayout,i=r.trace,a=R.traceIs(i,"pie"),o=i.index,s=a?r.label:i.name,l=t.selectAll("text.legendtext").data([0]);function u(r){Fr.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*Wo;if(o){var l=hn.bBox(o);n=l.height,i=l.width,hn.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),c=Fr.lineCount(u),h=u.node();n=s*c,i=h?hn.bBox(h).width:0;var f=s*(.3+(1-c)/2);Fr.positionText(u,40,f)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}l.enter().append("text").classed("legendtext",!0),l.attr("text-anchor","start").classed("user-select-none",!0).call(hn.font,n.legend.font).text(s),e._context.edits.legendText&&!a?l.call(Fr.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n,i=t;this.text()||(t=" ");var a=r.trace._fullInput||{},s={};if(-1!==["ohlc","candlestick"].indexOf(a.type))s[(n=r.trace.transforms)[n.length-1].direction+".name"]=t;else if(R.hasTransform(a,"groupby")){var l=R.getTransformIndices(a,"groupby"),c=l[l.length-1],h=re.keyedContainer(a,"transforms["+c+"].styles","target","value.name");""===i?h.remove(r.trace._group):h.set(r.trace._group,t),s=h.constructUpdate()}else s.name=t;return R.call("restyle",e,s,o)}):u(l)}function $o(t,e){var r,n=1,i=t.selectAll("rect").data([0]);i.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(Ne.fill,"rgba(0,0,0,0)"),i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimeQo&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Vo(t,e,n)},Qo):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,Vo(t,e,n))}})}function Jo(e,r,n){var i=e._fullLayout,a=i.legend,o=a.borderwidth,s=Fo.isGrouped(a),l=0;if(a._width=0,a._height=0,Fo.isVertical(a))s&&r.each(function(t,e){hn.setTranslate(this,0,e*a.tracegroupgap)}),n.each(function(t){var e=t[0],r=e.height,n=e.width;hn.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],c=r.data(),h=0,f=c.length;ho+x-_,n.each(function(t){var e=t[0],r=g?40+t[0].width:y;o+b+_+r>i.width-(i.margin.r+i.margin.l)&&(b=0,v+=m,a._height=a._height+m,m=0),hn.setTranslate(this,o+b,5+o+e.height/2+v),a._width+=_+r,a._height=Math.max(a._height,e.height),b+=_+r,m=Math.max(e.height,m)}),a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height),n.each(function(r){var n=r[0],i=t.select(this).select(".legendtoggle");hn.setRect(i,0,-n.height/2,(e._context.edits.legendText?0:a._width)+l,n.height)})}function ts(t){var e=t._fullLayout.legend,r="left";jo.isRightAnchor(e)?r="right":jo.isCenterAnchor(e)&&(r="center");var n="top";jo.isBottomAnchor(e)?n="bottom":jo.isMiddleAnchor(e)&&(n="middle"),vi.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*Yo[r],r:e._width*Zo[r],b:e._height*Zo[n],t:e._height*Yo[n]})}var es={moduleType:"component",name:"legend",layoutAttributes:zo,supplyLayoutDefaults:function(t,e,r){for(var n,i,a,o,s=t.legend||{},l={},u=0,c="normal",h=0;h1)){if(e.legend=l,d("bgcolor",e.paper_bgcolor),d("bordercolor"),d("borderwidth"),re.coerceFont(d,"font",e.font),d("orientation"),"h"===l.orientation){var p=t.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(n=0,a="left",i=1.1,o="bottom"):(n=0,a="left",i=-.1,o="top")}d("traceorder",c),Fo.isGrouped(e.legend)&&d("tracegroupgap"),d("x",n),d("xanchor",a),d("y",i),d("yanchor",o),re.noneOrAll(s,l,["x","y"])}},draw:function(e){var r=e._fullLayout,n="legend"+r._uid;if(r._infolayer&&e.calcdata){e._legendMouseDownTime||(e._legendMouseDownTime=0);var i=r.legend,a=r.showlegend&&function(t,e){var r,n,i={},a=[],o=!1,s={},l=0;function u(t,r){if(""!==t&&Fo.isGrouped(e))-1===a.indexOf(t)?(a.push(t),o=!0,i[t]=[[r]]):i[t].push([r]);else{var n="~~i"+l;a.push(n),i[n]=[[r]],l++}}for(r=0;rg?function(t){var e=t._fullLayout.legend,r="left";jo.isRightAnchor(e)?r="right":jo.isCenterAnchor(e)&&(r="center"),vi.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*Yo[r],r:e._width*Zo[r],b:0,t:0})}(e):ts(e);var v=r._size,m=v.l+v.w*i.x,y=v.t+v.h*(1-i.y);jo.isRightAnchor(i)?m-=i._width:jo.isCenterAnchor(i)&&(m-=i._width/2),jo.isBottomAnchor(i)?y-=i._height:jo.isMiddleAnchor(i)&&(y-=i._height/2);var b=i._width,x=v.w;b>x?(m=v.l,b=x):(m+b>p&&(m=p-b),m<0&&(m=0),b=Math.min(p-m,i._width));var _,w,M,A,T=i._height,k=v.h;if(T>k?(y=v.t,T=k):(y+T>g&&(y=g-T),y<0&&(y=0),T=Math.min(g-y,i._height)),hn.setTranslate(s,m,y),h.on(".drag",null),s.on("wheel",null),i._height<=T||e._context.staticPlot)u.attr({width:b-i.borderwidth,height:T-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),hn.setTranslate(c,0,0),l.select("rect").attr({width:b-2*i.borderwidth,height:T-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth}),hn.setClipUrl(c,n),hn.setRect(h,0,0,0,0),delete i._scrollY;else{var E,L,C=Math.max(Bo.scrollBarMinHeight,T*T/i._height),S=T-C-2*Bo.scrollBarMargin,P=i._height-T,O=S/P,I=Math.min(i._scrollY||0,P);u.attr({width:b-2*i.borderwidth+Bo.scrollBarWidth+Bo.scrollBarMargin,height:T-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),l.select("rect").attr({width:b-2*i.borderwidth+Bo.scrollBarWidth+Bo.scrollBarMargin,height:T-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth+I}),hn.setClipUrl(c,n),D(I,C,O),s.on("wheel",function(){D(I=re.constrain(i._scrollY+t.event.deltaY/S*P,0,P),C,O),0!==I&&I!==P&&t.event.preventDefault()});var N=t.behavior.drag().on("dragstart",function(){E=t.event.sourceEvent.clientY,L=I}).on("drag",function(){var e=t.event.sourceEvent;2===e.buttons||e.ctrlKey||D(I=re.constrain((e.clientY-E)/O+L,0,P),C,O)});h.call(N)}e._context.edits.legendPosition&&(s.classed("cursor-move",!0),rr.init({element:s.node(),gd:e,prepFn:function(){var t=hn.getTranslate(s);M=t.x,A=t.y},moveFn:function(t,e){var r=M+t,n=A+e;hn.setTranslate(s,r,n),_=rr.align(r,0,v.l,v.l+v.w,i.xanchor),w=rr.align(n,0,v.t+v.h,v.t,i.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&R.call("relayout",e,{"legend.x":_,"legend.y":w})},clickFn:function(t,n){var i=r._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===t?s._clickTimeout=setTimeout(function(){Vo(i,e,t)},Qo):2===t&&(s._clickTimeout&&clearTimeout(s._clickTimeout),Vo(i,e,t)))}}))}function D(t,r,n){i._scrollY=e._fullLayout.legend._scrollY=t,hn.setTranslate(c,0,-t),hn.setRect(h,b,Bo.scrollBarMargin+t*n,Bo.scrollBarWidth,r),l.select("rect").attr({y:i.borderwidth+t})}},style:Xo},rs={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},ns=m.extendFlat,is={visible:{valType:"boolean",editType:"plot"},buttons:rs=ns(rs,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:k({editType:"plot"}),bgcolor:{valType:"color",dflt:C.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:C.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},as={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var os=function(e,r){var n=e._name,i={};if("all"===r.step)i[n+".autorange"]=!0;else{var a=function(e,r){var n,i=e.range,a=new Date(e.r2l(i[1])),o=r.step,s=r.count;switch(r.stepmode){case"backward":n=e.l2r(+t.time[o].utc.offset(a,-s));break;case"todate":var l=t.time[o].utc.offset(a,-s);n=e.l2r(+t.time[o].utc.ceil(l))}var u=i[1];return[n,u]}(e,r);i[n+".range[0]"]=a[0],i[n+".range[1]"]=a[1]}return i};var ss=Nr.LINE_SPACING,ls=Nr.FROM_TL,us=Nr.FROM_BR;function cs(t){return t._id}function hs(t,e,r){var n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("selector-rect",!0),n.attr("shape-rendering","crispEdges"),n.attr({rx:as.rx,ry:as.ry}),n.call(Ne.stroke,e.bordercolor).call(Ne.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function fs(t,e,r,n){var i,a=t.selectAll("text").data([0]);a.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),a.attr("text-anchor","middle"),a.call(hn.font,e.font).text((i=r,i.label?i.label:"all"===i.step?"all":i.count+i.step.charAt(0))).call(function(t){Fr.convertToTspans(t,n)})}var ds={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:is}}},layoutAttributes:is,handleDefaults:function(t,e,r,n,i){var a=t.rangeselector||{},o=e.rangeselector={};function s(t,e){return re.coerce(a,o,is,t,e)}if(s("visible",function(t,e,r){var n,i,a=t.buttons||[],o=e.buttons=[];function s(t,e){return re.coerce(n,i,rs,t,e)}for(var l=0;l0)){var l=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;a0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}(e,r,n),r._initialCategories="category"===u?function(e,r,n,i){switch(r){case"array":return Array.isArray(n)?n.slice():[];case"category ascending":return _s(e,t.ascending,i);case"category descending":return _s(e,t.descending,i);case"trace":default:return[]}}(o,r.categoryorder,r.categoryarray,i.data):[],"category"===u||i.noHover||n("hoverformat"),!l)return r;var h=n("color"),f=h===e.color?h:s.color;return n("title",a._dfltTitle[o]),re.coerceFont(n,"titlefont",{family:s.family,size:Math.round(1.2*s.size),color:f}),Lr(e,r,n,u),Tr(e,r,n,u,i),kr(e,r,n,i),function(t,e,r,n){var i=(n=n||{}).dfltColor;function a(r,i){return re.coerce2(t,e,n.attributes,r,i)}var o=a("linecolor",i),s=a("linewidth");r("showline",n.showLine||!!o||!!s)||(delete e.linecolor,delete e.linewidth);var l=a("gridcolor",bs(i,n.bgColor,n.blend||xs).toRgbString()),u=a("gridwidth");if(r("showgrid",n.showGrid||!!l||!!u)||(delete e.gridcolor,delete e.gridwidth),!n.noZeroLine){var c=a("zerolinecolor",i),h=a("zerolinewidth");r("zeroline",n.showGrid||!!c||!!h)||(delete e.zerolinecolor,delete e.zerolinewidth)}}(e,r,n,{dfltColor:h,bgColor:i.bgColor,showGrid:i.showGrid,attributes:wr}),(r.showline||r.ticks)&&n("mirror"),i.automargin&&n("automargin"),r},Ms=ci.id2name,As=function(t,e,r,n,i){var a=i._axisConstraintGroups,o=e._id,s=o.charAt(0);if(!e.fixedrange&&(r("constrain"),re.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===s?["left","center","right"]:["bottom","middle","top"],dflt:"x"===s?"center":"middle"}},"constraintoward"),t.scaleanchor)){var l=function(t,e,r,n){var i,a,o,s,l=n[Ms(e)].type,u=[];for(a=0;ap[1]-.01&&(r.domain=o),re.noneOrAll(t.domain,r.domain,o)}return n("layer"),r},ks=ci.name2id,Es=function(t,e,r,n,i){i&&(e._name=i,e._id=ks(i)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var i=function(t,e,r){for(var n=0;n rect").call(hn.setTranslate,0,0).call(hn.setScale,1,1),t.plot.call(hn.setTranslate,e._offset,r._offset).call(hn.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(hn.setPointGroupScale,1,1),n.selectAll(".textpoint").call(hn.setTextPointsScale,1,1),n.call(hn.hideOutsideRangePoints,t)}function g(t,r){var n,i,o,s=h[t.xaxis._id],l=h[t.yaxis._id],u=[];if(s){i=(n=e._fullLayout[s.axisName])._r,o=s.to,u[0]=(i[0]*(1-r)+r*o[0]-i[0])/(i[1]-i[0])*t.xaxis._length;var c=i[1]-i[0],f=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[2]=t.xaxis._length*(1-r+r*f/c)}else u[0]=0,u[2]=t.xaxis._length;if(l){i=(n=e._fullLayout[l.axisName])._r,o=l.to,u[1]=(i[1]*(1-r)+r*o[1]-i[1])/(i[0]-i[1])*t.yaxis._length;var d=i[1]-i[0],p=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[3]=t.yaxis._length*(1-r+r*p/d)}else u[1]=0,u[3]=t.yaxis._length;!function(t,r){var n,i=[];for(i=[t._id,r._id],n=0;n rect").call(hn.setTranslate,_,w).call(hn.setScale,1/b,1/x),t.plot.call(hn.setTranslate,T,k).call(hn.setScale,b,x).selectAll(".points").selectAll(".point").call(hn.setPointGroupScale,1/b,1/x),t.plot.selectAll(".points").selectAll(".textpoint").call(hn.setTextPointsScale,1/b,1/x)}i&&(s=i());var v=t.ease(n.easing);return e._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(c),c=null,function(){for(var t={},r=0;rn.duration?(function(){for(var t={},r=0;rh&&(h=u)));return h>=c?[c,h]:void 0}}var tl=function(t,e,r,n,i){function a(r,n){return re.coerce(t,e,Qs,r,n)}if(n=n||{},!a("visible",!(i=i||{}).itemIsNotPlainObject))return e;a("layer"),a("opacity"),a("fillcolor"),a("line.color"),a("line.width"),a("line.dash");for(var o=a("type",t.path?"path":"rect"),s=["x","y"],l=0;l<2;l++){var u=s[l],c={_fullLayout:r},h=Ki.coerceRef(t,e,c,u,"","paper");if("path"!==o){var f,d,p;"paper"!==h?(f=Ki.getFromId(c,h),p=$s.rangeToShapePosition(f),d=$s.shapePositionToRange(f)):d=p=re.identity;var g=u+"0",v=u+"1",m=t[g],y=t[v];t[g]=d(t[g],!0),t[v]=d(t[v],!0),Ki.coercePosition(e,c,a,h,g,.25),Ki.coercePosition(e,c,a,h,v,.75),e[g]=p(e[g]),e[v]=p(e[v]),t[g]=m,t[v]=y}}return"path"===o?a("path"):re.noneOrAll(t,e,["x0","x1","y0","y1"]),e},el={draw:function(t){var e=t._fullLayout;e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._shapeSubplotLayers.selectAll("path").remove();for(var r=0;rN&&n>D&&!t.shiftKey?rr.getCursor(i/r,1-a/n):"move";Nn(e,o),I=o.split("-")[0]}function B(n,d){if("path"===r.type){var p=function(t){return P(C(t)+n)};E&&"date"===E.type&&(p=$s.encodeDate(p));var g=function(t){return O(S(t)+d)};L&&"date"===L.type&&(g=$s.encodeDate(g)),r.path=il(T,p,g),i[k]=r.path}else i[u]=r.x0=P(a+n),i[c]=r.y0=O(o+d),i[h]=r.x1=P(s+n),i[f]=r.y1=O(l+d);e.attr("d",nl(t,r))}function U(n,a){if("path"===r.type){var o=function(t){return P(C(t)+n)};E&&"date"===E.type&&(o=$s.encodeDate(o));var s=function(t){return O(S(t)+a)};L&&"date"===L.type&&(s=$s.encodeDate(s)),r.path=il(T,o,s),i[k]=r.path}else{var l=~I.indexOf("n")?d+a:d,u=~I.indexOf("s")?p+a:p,c=~I.indexOf("w")?g+n:g,h=~I.indexOf("e")?v+n:v;u-l>D&&(i[m]=r[_]=O(l),i[y]=r[w]=O(u)),h-c>N&&(i[b]=r[M]=P(c),i[x]=r[A]=P(h))}e.attr("d",nl(t,r))}rr.init(z),e.node().onmousemove=j}(t,o,n,e)}}function nl(t,e){var r,n,i,a,o=e.type,s=Ki.getFromId(t,e.xref),l=Ki.getFromId(t,e.yref),u=t._fullLayout._size;if(s?(r=$s.shapePositionToRange(s),n=function(t){return s._offset+s.r2p(r(t,!0))}):n=function(t){return u.l+u.w*t},l?(i=$s.shapePositionToRange(l),a=function(t){return l._offset+l.r2p(i(t,!0))}):a=function(t){return u.t+u.h*(1-t)},"path"===o)return s&&"date"===s.type&&(n=$s.decodeDate(n)),l&&"date"===l.type&&(a=$s.decodeDate(a)),function(t,e,r){return t.replace(Ks.segmentRE,function(t){var n=0,i=t.charAt(0),a=Ks.paramIsX[i],o=Ks.paramIsY[i],s=Ks.numParams[i],l=t.substr(1).replace(Ks.paramRE,function(t){return a[n]?t=e(t):o[n]&&(t=r(t)),++n>s&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),re.log("Ignoring extra params in segment "+t)),i+l})}(e.path,n,a);var c=n(e.x0),h=n(e.x1),f=a(e.y0),d=a(e.y1);if("line"===o)return"M"+c+","+f+"L"+h+","+d;if("rect"===o)return"M"+c+","+f+"H"+h+"V"+d+"H"+c+"Z";var p=(c+h)/2,g=(f+d)/2,v=Math.abs(p-c),m=Math.abs(g-f),y="A"+v+","+m,b=p+v+","+g;return"M"+b+y+" 0 1,1 "+(p+","+(g-m))+y+" 0 0,1 "+b+"Z"}function il(t,e,r){return t.replace(Ks.segmentRE,function(t){var n=0,i=t.charAt(0),a=Ks.paramIsX[i],o=Ks.paramIsY[i],s=Ks.numParams[i];return i+t.substr(1).replace(Ks.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var al={moduleType:"component",name:"shapes",layoutAttributes:Qs,supplyLayoutDefaults:function(t,e){no(t,e,{name:"shapes",handleItemDefaults:tl})},includeBasePlot:io("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=re.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),re.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var dl=Nr.LINE_SPACING,pl=Nr.FROM_TL,vl=Nr.FROM_BR;function ml(t){return t._index}function yl(e,r){var n=hn.tester.selectAll("g."+ol.labelGroupClass).data(r.steps);n.enter().append("g").classed(ol.labelGroupClass,!0);var i=0,a=0;n.each(function(e){var n=_l(t.select(this),{step:e},r).node();if(n){var o=hn.bBox(n);a=Math.max(a,o.height),i=Math.max(i,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(ol.railWidth,ol.gripHeight);var s=e._fullLayout._size;o.lx=s.l+s.w*r.x,o.ly=s.t+s.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(s.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var l=(o.inputAreaLength-2*ol.stepInset)/(r.steps.length-1),u=i+ol.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/l)),o.labelHeight=a,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var c=hn.tester.append("g");n.each(function(t){var e=bl(c,r,t.label),n=e.node()&&hn.bBox(e.node())||{width:0,height:0},i=Fr.lineCount(e);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,i)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+ol.tickOffset+r.ticklen+ol.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var h="left";jo.isRightAnchor(r)&&(o.lx-=o.outerLength,h="right"),jo.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,h="center");var f="top";jo.isBottomAnchor(r)&&(o.ly-=o.height,f="bottom"),jo.isMiddleAnchor(r)&&(o.ly-=o.height/2,f="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),vi.autoMargin(e,ol.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*pl[h],r:o.outerLength*vl[h],b:o.height*vl[f],t:o.height*pl[f]})}function bl(t,e,r){if(e.currentvalue.visible){var n,i,a=t.selectAll("text").data([0]),o=e._dims;switch(e.currentvalue.xanchor){case"right":n=o.inputAreaLength-ol.currentValueInset-o.currentValueMaxWidth,i="left";break;case"center":n=.5*o.inputAreaLength,i="middle";break;default:n=ol.currentValueInset,i="left"}a.enter().append("text").classed(ol.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1});var s=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)s+=r;else s+=e.steps[e.active].label;e.currentvalue.suffix&&(s+=e.currentvalue.suffix),a.call(hn.font,e.currentvalue.font).text(s).call(Fr.convertToTspans,e._gd);var l=Fr.lineCount(a),u=(o.currentValueMaxLines+1-l)*e.currentvalue.font.size*dl;return Fr.positionText(a,n,u),a}}function xl(t,e,r){var n=t.selectAll("rect."+ol.gripRectClass).data([0]);n.enter().append("rect").classed(ol.gripRectClass,!0).call(Tl,e,t,r).style("pointer-events","all"),n.attr({width:ol.gripWidth,height:ol.gripHeight,rx:ol.gripRadius,ry:ol.gripRadius}).call(Ne.stroke,r.bordercolor).call(Ne.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function _l(t,e,r){var n=t.selectAll("text").data([0]);return n.enter().append("text").classed(ol.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(hn.font,r.font).text(e.step.label).call(Fr.convertToTspans,r._gd),n}function wl(e,r){var n=e.selectAll("g."+ol.labelsClass).data([0]),i=r._dims;n.enter().append("g").classed(ol.labelsClass,!0);var a=n.selectAll("g."+ol.labelGroupClass).data(i.labelSteps);a.enter().append("g").classed(ol.labelGroupClass,!0),a.exit().remove(),a.each(function(e){var n=t.select(this);n.call(_l,e,r),hn.setTranslate(n,Ll(r,e.fraction),ol.tickOffset+r.ticklen+r.font.size*dl+ol.labelOffset+i.currentValueTotalHeight)})}function Ml(t,e,r,n,i){var a=Math.round(n*(r.steps.length-1));a!==r.active&&Al(t,e,r,a,!0,i)}function Al(t,e,r,n,i,a){var o=r.active;r._input.active=r.active=n;var s=r.steps[r.active];e.call(El,r,r.active/(r.steps.length-1),a),e.call(bl,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:o}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=a):(e._nextMethod={step:s,doCallback:i,doTransition:a},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&vi.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function Tl(e,r,n){var i=n.node(),a=t.select(r);function o(){return n.data()[0]}e.on("mousedown",function(){var e=o();r.emit("plotly_sliderstart",{slider:e});var s=n.select("."+ol.gripRectClass);t.event.stopPropagation(),t.event.preventDefault(),s.call(Ne.fill,e.activebgcolor);var l=Cl(e,t.mouse(i)[0]);Ml(r,n,e,l,!0),e._dragging=!0,a.on("mousemove",function(){var e=o(),a=Cl(e,t.mouse(i)[0]);Ml(r,n,e,a,!1)}),a.on("mouseup",function(){var t=o();t._dragging=!1,s.call(Ne.fill,t.bgcolor),a.on("mouseup",null),a.on("mousemove",null),r.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function kl(e,r){var n=e.selectAll("rect."+ol.tickRectClass).data(r.steps),i=r._dims;n.enter().append("rect").classed(ol.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(e,n){var a=n%i.labelStride==0,o=t.select(this);o.attr({height:a?r.ticklen:r.minorticklen}).call(Ne.fill,r.tickcolor),hn.setTranslate(o,Ll(r,n/(r.steps.length-1))-.5*r.tickwidth,(a?ol.tickOffset:ol.minorTickOffset)+i.currentValueTotalHeight)})}function El(t,e,r,n){var i=t.select("rect."+ol.gripRectClass),a=Ll(e,r);if(!e._invokingCommand){var o=i;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(a-.5*ol.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function Ll(t,e){var r=t._dims;return r.inputAreaStart+ol.stepInset+(r.inputAreaLength-2*ol.stepInset)*Math.min(1,Math.max(0,e))}function Cl(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-ol.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*ol.stepInset-2*r.inputAreaStart)))}function Sl(t,e,r){var n=t.selectAll("rect."+ol.railTouchRectClass).data([0]),i=r._dims;n.enter().append("rect").classed(ol.railTouchRectClass,!0).call(Tl,e,t,r).style("pointer-events","all"),n.attr({width:i.inputAreaLength,height:Math.max(i.inputAreaWidth,ol.tickOffset+r.ticklen+i.labelHeight)}).call(Ne.fill,r.bgcolor).attr("opacity",0),hn.setTranslate(n,0,i.currentValueTotalHeight)}function Pl(t,e){var r=t.selectAll("rect."+ol.railRectClass).data([0]),n=e._dims;r.enter().append("rect").classed(ol.railRectClass,!0);var i=n.inputAreaLength-2*ol.railInset;r.attr({width:i,height:ol.railWidth,rx:ol.railRadius,ry:ol.railRadius,"shape-rendering":"crispEdges"}).call(Ne.stroke,e.bordercolor).call(Ne.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),hn.setTranslate(r,ol.railInset,.5*(n.inputAreaWidth-ol.railWidth)+n.currentValueTotalHeight)}var Rl={moduleType:"component",name:ol.name,layoutAttributes:ul,supplyLayoutDefaults:function(t,e){no(t,e,{name:cl,handleItemDefaults:fl})},draw:function(e){var r=e._fullLayout,n=function(t,e){for(var r=t[ol.name],n=[],i=0;i0?[0]:[]);if(i.enter().append("g").classed(ol.containerClassName,!0).style("cursor","ew-resize"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(bl,r).call(Pl,r).call(wl,r).call(kl,r).call(Sl,t,r).call(xl,t,r);var n=r._dims;hn.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(El,r,r.active/(r.steps.length-1),!1),e.call(bl,r)}(e,t.select(this),r)}})}}},Ol=m.extendFlat,Il=(0,gr.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Ol({},sl,{}),font:k({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:C.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Nl={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Dl=Nl.name,zl=Il.buttons;function Fl(t,e,r){function n(r,n){return re.coerce(t,e,Il,r,n)}n("visible",function(t,e){var r,n,i=t.buttons||[],a=e.buttons=[];function o(t,e){return re.coerce(r,n,zl,t,e)}for(var s=0;s0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var jl=Bl;function Bl(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Bl.barWidth=2,Bl.barLength=20,Bl.barRadius=2,Bl.barPad=1,Bl.barColor="#808BA4",Bl.prototype.enable=function(e,r,n){var i=this.gd._fullLayout,a=i.width,o=i.height;this.position=e;var s,l,u,c,h=this.position.l,f=this.position.w,d=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,m="left"===g,y="up"===g,b=f,x=p;v||m||"right"===g||y||(this.position.direction="down",v=!0),v||y?(l=(s=h)+b,v?(u=d,x=(c=Math.min(u+x,o))-u):x=(c=d+x)-(u=Math.max(c-x,0))):(c=(u=d)+x,m?b=(l=h+b)-(s=Math.max(l-b,0)):(s=h,b=(l=Math.min(s+b,a))-s)),this._box={l:s,t:u,w:b,h:x};var _=f>b,w=Bl.barLength+2*Bl.barPad,M=Bl.barWidth+2*Bl.barPad,A=h,T=d+p;T+M>o&&(T=o-M);var k=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);k.exit().on(".drag",null).remove(),k.enter().append("rect").classed("scrollbar-horizontal",!0).call(Ne.fill,Bl.barColor),_?(this.hbar=k.attr({rx:Bl.barRadius,ry:Bl.barRadius,x:A,y:T,width:w,height:M}),this._hbarXMin=A+w/2,this._hbarTranslateMax=b-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var E=p>x,L=Bl.barWidth+2*Bl.barPad,C=Bl.barLength+2*Bl.barPad,S=h+f,P=d;S+L>a&&(S=a-L);var R=this.container.selectAll("rect.scrollbar-vertical").data(E?[0]:[]);R.exit().on(".drag",null).remove(),R.enter().append("rect").classed("scrollbar-vertical",!0).call(Ne.fill,Bl.barColor),E?(this.vbar=R.attr({rx:Bl.barRadius,ry:Bl.barRadius,x:S,y:P,width:L,height:C}),this._vbarYMin=P+C/2,this._vbarTranslateMax=x-C):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var O=this.id,I=s-.5,N=E?l+L+.5:l+.5,D=u-.5,z=_?c+M+.5:c+.5,F=i._topdefs.selectAll("#"+O).data(_||E?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",O).append("rect"),_||E?(this._clipRect=F.select("rect").attr({x:Math.floor(I),y:Math.floor(D),width:Math.ceil(N)-Math.floor(I),height:Math.ceil(z)-Math.floor(D)}),this.container.call(hn.setClipUrl,O),this.bg.attr({x:h,y:d,width:f,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(hn.setClipUrl,null),delete this._clipRect),_||E){var j=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault(),t.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),E&&this.vbar.on(".drag",null).call(B)}this.setTranslate(r,n)},Bl.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(hn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Bl.prototype._onBoxDrag=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e-=t.event.dx),this.vbar&&(r-=t.event.dy),this.setTranslate(e,r)},Bl.prototype._onBoxWheel=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e+=t.event.deltaY),this.vbar&&(r+=t.event.deltaY),this.setTranslate(e,r)},Bl.prototype._onBarDrag=function(){var e=this.translateX,r=this.translateY;if(this.hbar){var n=e+this._hbarXMin,i=n+this._hbarTranslateMax;e=(re.constrain(t.event.x,n,i)-n)/(i-n)*(this.position.w-this._box.w)}if(this.vbar){var a=r+this._vbarYMin,o=a+this._vbarTranslateMax;r=(re.constrain(t.event.y,a,o)-a)/(o-a)*(this.position.h-this._box.h)}this.setTranslate(e,r)},Bl.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=re.constrain(t||0,0,r),e=re.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(hn.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(hn.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var a=e/n;this.vbar.call(hn.setTranslate,t,e+a*this._vbarTranslateMax)}};var Ul=Nr.LINE_SPACING;function Vl(t){return t._index}function Hl(t,e){return+t.attr(Nl.menuIndexAttrName)===e._index}function ql(t,e,r,n,i,a,o,s){e._input.active=e.active=o,"buttons"===e.type?Xl(t,n,null,null,e):"dropdown"===e.type&&(i.attr(Nl.menuIndexAttrName,"-1"),Gl(t,n,i,a,e),s||Xl(t,n,i,a,e))}function Gl(t,e,r,n,i){var a=e.selectAll("g."+Nl.headerClassName).data([0]),o=i._dims;a.enter().append("g").classed(Nl.headerClassName,!0).style("pointer-events","all");var s=i.active,l=i.buttons[s]||Nl.blankHeaderOpts,u={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};a.call(Wl,i,l,t).call(tu,i,u,c);var h=e.selectAll("text."+Nl.headerArrowClassName).data([0]);h.enter().append("text").classed(Nl.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(hn.font,i.font).text(Nl.arrowSymbol[i.direction]),h.attr({x:o.headerWidth-Nl.arrowOffsetX+i.pad.l,y:o.headerHeight/2+Nl.textOffsetY+i.pad.t}),a.on("click",function(){r.call(eu),r.attr(Nl.menuIndexAttrName,Hl(r,i)?-1:String(i._index)),Xl(t,e,r,n,i)}),a.on("mouseover",function(){a.call(Kl)}),a.on("mouseout",function(){a.call($l,i)}),hn.setTranslate(e,o.lx,o.ly)}function Xl(e,r,n,i,a){n||(n=r).attr("pointer-events","all");var o=function(t){return-1==+t.attr(Nl.menuIndexAttrName)}(n)&&"buttons"!==a.type?[]:a.buttons,s="dropdown"===a.type?Nl.dropdownButtonClassName:Nl.buttonClassName,l=n.selectAll("g."+s).data(o),u=l.enter().append("g").classed(s,!0),c=l.exit();"dropdown"===a.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var h=0,f=0,d=a._dims,p=-1!==["up","down"].indexOf(a.direction);"dropdown"===a.type&&(p?f=d.headerHeight+Nl.gapButtonHeader:h=d.headerWidth+Nl.gapButtonHeader),"dropdown"===a.type&&"up"===a.direction&&(f=-Nl.gapButtonHeader+Nl.gapButton-d.openHeight),"dropdown"===a.type&&"left"===a.direction&&(h=-Nl.gapButtonHeader+Nl.gapButton-d.openWidth);var g={x:d.lx+h+a.pad.l,y:d.ly+f+a.pad.t,yPad:Nl.gapButton,xPad:Nl.gapButton,index:0},v={l:g.x+a.borderwidth,t:g.y+a.borderwidth};l.each(function(o,s){var u=t.select(this);u.call(Wl,a,o,e).call(tu,a,g),u.on("click",function(){t.event.defaultPrevented||(ql(e,a,0,r,n,i,s),o.execute&&vi.executeAPICommand(e,o.method,o.args),e.emit("plotly_buttonclicked",{menu:a,button:o,active:a.active}))}),u.on("mouseover",function(){u.call(Kl)}),u.on("mouseout",function(){u.call($l,a),l.call(Ql,a)})}),l.call(Ql,a),p?(v.w=Math.max(d.openWidth,d.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(d.openHeight,d.headerHeight)),v.direction=a.direction,i&&(l.size()?function(t,e,r,n,i,a){var o,s,l,u=i.direction,c="up"===u||"down"===u,h=i._dims,f=i.active;if(c)for(s=0,l=0;l0?[0]:[]);if(i.enter().append("g").classed(Nl.containerClassName,!0).style("cursor","pointer"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nx.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&re.log("Clearing previous rejected promises from queue."),t._promises=[]},su.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(vi.subplotsRegistry.cartesian||{}).attrRegex,i=(vi.subplotsRegistry.gl3d||{}).attrRegex,a=Object.keys(t);for(e=0;e3?(b.x=1.02,b.xanchor="left"):b.x<-2&&(b.x=-.02,b.xanchor="right"),b.y>3?(b.y=1.02,b.yanchor="bottom"):b.y<-2&&(b.y=-.02,b.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Ne.clean(t),t},su.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),i=0;i0)return t.substr(0,e)}su.hasParent=function(t,e){for(var r=pu(e);r;){if(r in t)return!0;r=pu(r)}return!1};var gu=["x","y","z"];su.clearAxisTypes=function(t,e,r){for(var n=0;n1&&_.warn("Full array edits are incompatible with other edits",i);var h=r[""][""];if(bu(h))e.set(null);else{if(!Array.isArray(h))return _.warn("Unrecognized full array edit value",i,h),!0;e.set(h)}return!l&&(a(u,c),o(t),!0)}var f,d,p,g,v,m,y,b=Object.keys(r).map(Number).sort(mu),x=e.get(),w=x||[],M=X(c,i).get(),T=[],k=-1,E=w.length;for(f=0;fw.length-(y?0:1))_.warn("index out of range",i,p);else if(void 0!==m)v.length>1&&_.warn("Insertion & removal are incompatible with edits to the same index.",i,p),bu(m)?T.push(p):y?("add"===m&&(m={}),w.splice(p,0,m),M&&M.splice(p,0,{})):_.warn("Unrecognized full object edit value",i,p,m),-1===k&&(k=p);else for(d=0;d=0;f--)w.splice(T[f],1),M&&M.splice(T[f],1);if(w.length?x||e.set(w):e.set(null),l)return!1;if(a(u,c),s!==A){var L;if(-1===k)L=b;else{for(E=Math.max(w.length,E),L=[],f=0;f=k);f++)L.push(p);for(f=k;f1?(m=["toggleHover"],y=["resetViews"]):s?(v=["zoomInGeo","zoomOutGeo"],m=["hoverClosestGeo"],y=["resetGeo"]):o?(m=["hoverClosest3d"],y=["resetCameraDefault3d","resetCameraLastSave3d"]):h?(m=["toggleHover"],y=["resetViewMapbox"]):m=u?["hoverClosestGl2d"]:l?["hoverClosestPie"]:["toggleHover"],a&&(m=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!a&&!u||d||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==y[0]&&(y=["resetScale2d"])),o?b=["zoom3d","pan3d","orbitRotation","tableRotation"]:(a||u)&&!d||c?b=["zoom2d","pan2d"]:h||s?b=["pan2d"]:f&&(b=["zoom2d"]),function(t){for(var e=!1,r=0;r0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,l=i.end,u=a.start,c=a.end;r&&r.checkIntersection(i,a);var h=e.linesIntersect(o,l,u,c);if(!1===h){if(!e.pointsCollinear(o,l,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(l,u))return!1;var f=e.pointsSame(o,u),d=e.pointsSame(l,c);if(f&&d)return n;var p=!f&&e.pointBetween(o,u,c),g=!d&&e.pointBetween(l,u,c);if(f)return g?s(n,l):s(t,c),n;p&&(d||(g?s(n,l):s(t,c)),s(n,o))}else 0===h.alongA&&(-1===h.alongB?s(t,u):0===h.alongB?s(t,h.pt):1===h.alongB&&s(t,c)),0===h.alongB&&(-1===h.alongA?s(n,o):0===h.alongA?s(n,h.pt):1===h.alongA&&s(n,l));return!1}for(var c=[];!i.isEmpty();){var h=i.getHead();if(r&&r.vert(h.pt[0]),h.isStart){r&&r.segmentNew(h.seg,h.primary);var f=l(h),d=f.before?f.before.ev:null,p=f.after?f.after.ev:null;function g(){if(d){var t=u(h,d);if(t)return t}return!!p&&u(h,p)}r&&r.tempStatus(h.seg,!!d&&d.seg,!!p&&p.seg);var v,m,y=g();if(y)t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below)&&(y.seg.myFill.above=!y.seg.myFill.above):y.seg.otherFill=h.seg.myFill,r&&r.segmentUpdate(y.seg),h.other.remove(),h.remove();if(i.getHead()!==h){r&&r.rewind(h.seg);continue}t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below,h.seg.myFill.below=p?p.seg.myFill.above:n,h.seg.myFill.above=m?!h.seg.myFill.below:h.seg.myFill.below):null===h.seg.otherFill&&(v=p?h.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:h.primary?a:n,h.seg.otherFill={above:v,below:v}),r&&r.status(h.seg,!!d&&d.seg,!!p&&p.seg),h.other.status=f.insert(Fu.node({ev:h}))}else{var b=h.status;if(null===b)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(b.prev)&&o.exists(b.next)&&u(b.prev.ev,b.next.ev),r&&r.statusRemove(b.ev.seg),b.remove(),!h.primary){var x=h.seg.myFill;h.seg.myFill=h.seg.otherFill,h.seg.otherFill=x}c.push(h.seg)}i.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,i,a,s=t[t.length-1],l=0;l=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-i>t&&(a-u)*(i-c)/(o-c)+u-n>t&&(s=!s),a=u,o=c}return s}};return e}();function Xu(t,e,r){var n=Vu.segments(t),i=Vu.segments(e),a=r(Vu.combine(n,i));return Vu.polygon(a)}Vu={buildLog:function(t){return!0===t?qu=Du():!1===t&&(qu=!1),!1!==qu&&qu.list},epsilon:function(t){return Gu.epsilon(t)},segments:function(t){var e=ju(!0,Gu,qu);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:ju(!1,Gu,qu).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:Hu.union(t.combined,qu),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:Hu.intersect(t.combined,qu),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:Hu.difference(t.combined,qu),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:Hu.differenceRev(t.combined,qu),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:Hu.xor(t.combined,qu),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:Bu(t.segments,Gu,qu),inverted:t.inverted}},polygonFromGeoJSON:function(t){return zu.toPolygon(Vu,t)},polygonToGeoJSON:function(t){return zu.fromPolygon(Vu,Gu,t)},union:function(t,e){return Xu(t,e,Vu.selectUnion)},intersect:function(t,e){return Xu(t,e,Vu.selectIntersect)},difference:function(t,e){return Xu(t,e,Vu.selectDifference)},differenceRev:function(t,e){return Xu(t,e,Vu.selectDifferenceRev)},xor:function(t,e){return Xu(t,e,Vu.selectXor)}},"object"==typeof window&&(window.PolyBool=Vu);var Wu,Yu=Vu,Zu=Bt.dot,Qu=r.BADNUM,Ku=Wu={};Ku.tester=function(t){if(Array.isArray(t[0][0]))return Ku.multitester(t);var e,r=t.slice(),n=r[0][0],i=n,a=r[0][1],o=a;for(r.push(r[0]),e=1;ei||l===Qu||lo||e&&s(t))}:function(t,e){var s=t[0],l=t[1];if(s===Qu||si||l===Qu||lo)return!1;var u,c,h,f,d,p=r.length,g=r[0][0],v=r[0][1],m=0;for(u=1;uMath.max(c,g)||l>Math.max(h,v)))if(lu||Math.abs(Zu(a,h))>n)return!0;return!1};Ku.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var o=r.length,s=n;r.splice(i+1);for(var l=s+1;l1&&a(t.pop());return{addPt:a,raw:t,filtered:r}};var Ju=Pn.makeEventData,tc=Wu.filter,ec=Wu.tester,rc=Wu.multitester,nc=Oe.MINSELECT;function ic(t){return t._id}var ac=function(t,e,r,n,i){var a,o,s,l,u=n.gd,c=u._fullLayout,h=c._zoomlayer,f=n.element.getBoundingClientRect(),d=n.plotinfo,p=d.xaxis._offset,g=d.yaxis._offset,v=e-f.left,m=r-f.top,y=v,b=m,x="M"+v+","+m,_=n.xaxes[0]._length,w=n.yaxes[0]._length,M=n.xaxes.map(ic),A=n.yaxes.map(ic),T=n.xaxes.concat(n.yaxes),k=t.altKey;(t.shiftKey||t.altKey)&&d.selection&&d.selection.polygons&&!n.polygons?(n.polygons=d.selection.polygons,n.mergedPolygons=d.selection.mergedPolygons):(!t.shiftKey&&!t.altKey||(t.shiftKey||t.altKey)&&!d.selection)&&(d.selection={},d.selection.polygons=n.polygons=[],d.selection.mergedPolygons=n.mergedPolygons=[]),"lasso"===i&&(a=tc([[v,m]],Oe.BENDPX));var E=h.selectAll("path.select-outline-"+d.id).data([1,2]);E.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+d.id}).attr("transform","translate("+p+", "+g+")").attr("d",x+"Z");var L,C,S,P,R,O,I=h.append("path").attr("class","zoombox-corners").style({fill:Ne.background,stroke:Ne.defaultLine,"stroke-width":1}).attr("transform","translate("+p+", "+g+")").attr("d","M0,0Z"),N=[],D=c._uid+Oe.SELECTID,z=[];for(L=0;L=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function xc(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function _c(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Ne.background,stroke:Ne.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function wc(t){t.selectAll(".select-outline").remove()}function Mc(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),Ac(t,e,i,a)}function Ac(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function Tc(e){t.select(e).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function kc(t){dc&&t.data&&t._context.showTips&&(re.notifier(re._(t,"Double-click to zoom back out"),"long"),dc=!1)}function Ec(t){return"lasso"===t||"select"===t}function Lc(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,fc)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function Cc(t,e){if(Ve){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}var Sc=function(e,r,n,i,a,o,l,u){var c,h,f,d,p,g,v,m,y,b,x,_,w,M=e._fullLayout,A=e._fullLayout._zoomlayer,T=l+u==="nsew",k=1===(l+u).length;function E(){h=[r.xaxis],f=[r.yaxis];var t=h[0],n=f[0];g=t._length,v=n._length;var i,a,o=M._axisConstraintGroups,s=[t._id],A=[n._id];c=[r].concat(l&&u?r.overlays:[]);for(var T=1;Tfc||o>fc?(z="xy",a/g>o/v?(o=a*v/g,P>i?O.t=P-o:O.b=P+o):(a=o*g/v,S>n?O.l=S-a:O.r=S+a),j.attr("d",Lc(O))):s():!y||o rect").call(hn.setTranslate,i,a).call(hn.setScale,r,n);var R=b.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");b.plot.call(hn.setTranslate,S,P).call(hn.setScale,1/r,1/n),R.selectAll(".point").call(hn.setPointGroupScale,r,n),R.selectAll(".textpoint").call(hn.setTextPointsScale,r,n),R.call(hn.hideOutsideRangePoints,b),b.plot.selectAll(".barlayer .trace").call(hn.hideOutsideRangePoints,b,".bartext")}}}return l.length*u.length!=1&&Cc(L,function(t){if(e._context.scrollZoom||M._enablescrollzoom){if(null===G&&wc(A),e._transitioningWithDuration)return t.preventDefault(),void t.stopPropagation();var r=e.querySelector(".plotly");if(E(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(G);var n=-t.deltaY;if(isFinite(n)||(n=t.wheelDelta/10),isFinite(n)){var i,a=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=W.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(t.clientX-o.left)/o.width,c=(o.bottom-t.clientY)/o.height;if(u||x){for(u||(s=.5),i=0;i=t[1]||i[1]<=t[0])&&a[0]e[0])return!0}return!1}(r,i,d)?(f.push(t),d.push([r,i])):a=[0];var o=e.plotgroup.selectAll(".bg").data(a);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){e.bg=o;var t=e.plotgroup.node();t.insertBefore(this,t.childNodes[0])})});var p=n._bgLayer.selectAll(".bg").data(f);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(e){n._plots[e].bg=t.select(this)}),h.each(function(t){var e=n._plots[t],i=e.xaxis,u=e.yaxis;e.bg&&s&&e.bg.call(hn.setRect,i._offset-a,u._offset-a,i._length+2*a,u._length+2*a).call(Ne.fill,n.plot_bgcolor).style("stroke-width",0),e.clipId="clip"+n._uid+t+"plot";var c,h,f=n._clips.selectAll("#"+e.clipId).data([0]);for(f.enter().append("clipPath").attr({class:"plotclip",id:e.clipId}).append("rect"),f.selectAll("rect").attr({width:i._length,height:u._length}),hn.setTranslate(e.plot,i._offset,u._offset),e._hasClipOnAxisFalse?(c=null,h=e.clipId):(c=e.clipId,h=null),hn.setClipUrl(e.plot,c),r=0;rjc*d)||m)for(r=0;rE&&ST&&(T=S);s/=(T-A)/(2*k),A=i.l2r(A),T=i.l2r(T),i.range=i._input.range=_=0?u.angularAxis.domain:t.extent(b),A=Math.abs(b[1]-b[0]);_&&!x&&(A=0);var T=M.slice();w&&x&&(T[1]+=A);var k=u.angularAxis.ticksCount||4;k>8&&(k=k/(k/8)+k%8),u.angularAxis.ticksStep&&(k=(T[1]-T[0])/k);var E=u.angularAxis.ticksStep||(T[1]-T[0])/(k*(u.minorTicks+1));y&&(E=Math.max(Math.round(E),1)),T[2]||(T[2]=E);var L=t.range.apply(this,T);if(L=L.map(function(t,e){return parseFloat(t.toPrecision(12))}),i=t.scale.linear().domain(T.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),s.layout.angularAxis.domain=i.domain(),s.layout.angularAxis.endPadding=w?A:0,void 0===(e=t.select(this).select("svg.chart-root"))||e.empty()){var C=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),S=this.appendChild(this.ownerDocument.importNode(C.documentElement,!0));e=t.select(S)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var P,R=e.select(".chart-group"),O={fill:"none",stroke:u.tickColor},I={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){P=e.select(".legend-group").attr({transform:"translate("+[g,u.margin.top]+")"}).style({display:"block"});var N=c.map(function(t,e){var r=Gc.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});Gc.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:Hc({},Gc.Legend.defaultConfig().legendConfig,{container:P,elements:N,reverseOrder:u.legend.reverseOrder})})();var D=P.node().getBBox();g=Math.min(u.width-D.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,g=Math.max(10,g),m=[u.margin.left+g,u.margin.top+g],n.range([0,g]),s.layout.radialAxis.domain=n.domain(),P.attr("transform","translate("+[m[0]+g,m[1]-g]+")")}else P=e.select(".legend-group").style({display:"none"});e.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),R.attr("transform","translate("+m+")").style({cursor:"crosshair"});var z=[(u.width-(u.margin.left+u.margin.right+2*g+(D?D.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*g))/2];if(z[0]=Math.max(0,z[0]),z[1]=Math.max(0,z[1]),e.select(".outer-group").attr("transform","translate("+z+")"),u.title){var F=e.select("g.title-group text").style(I).text(u.title),j=F.node().getBBox();F.attr({x:m[0]-j.width/2,y:m[1]-g-20})}var B=e.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var U=B.selectAll("circle.grid-circle").data(n.ticks(5));U.enter().append("circle").attr({class:"grid-circle"}).style(O),U.attr("r",n),U.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(O);var V=e.select("circle.background-circle").attr({r:g}).style({fill:u.backgroundColor,stroke:u.stroke});function H(t,e){return i(t)%360+u.orientation}if(u.radialAxis.visible){var q=t.svg.axis().scale(n).ticks(5).tickSize(5);B.call(q).attr({transform:"rotate("+u.radialAxis.orientation+")"}),B.selectAll(".domain").style(O),B.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(I).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,I["font-size"]]+")":"translate("+[0,I["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=e.select(".angular.axis-group").selectAll("g.angular-tick").data(L),X=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(t,e){return"rotate("+H(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),G.exit().remove(),X.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(O),X.selectAll(".minor").style({stroke:u.minorTickColor}),G.select("line.grid-line").attr({x1:u.tickLength?g-u.tickLength:0,x2:g}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),X.append("text").classed("axis-text",!0).style(I);var W=G.select("text.axis-text").attr({x:g+u.labelOffset,dy:qc+"em",transform:function(t,e){var r=H(t),n=g+u.labelOffset,i=u.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":y?y[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(I);u.angularAxis.rewriteTicks&&W.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var Y=t.max(R.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));P.attr({transform:"translate("+[g+Y,u.margin.top]+")"});var Z=e.select("g.geometry-group").selectAll("g").size()>0,Q=e.select("g.geometry-group").selectAll("g.geometry").data(c);if(Q.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),Q.exit().remove(),c[0]||Z){var K=[];c.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=i,r.container=Q.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=u.orientation,r.direction=u.direction,r.index=e,K.push({data:t,geometryConfig:r})});var $=[];t.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(K).forEach(function(t,e){"unstacked"===t.key?$=$.concat(t.values.map(function(t,e){return[t]})):$.push(t.values)}),$.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return Hc(Gc[r].defaultConfig(),t)});Gc[r]().config(n)()})}var J,tt,et=e.select(".guides-group"),rt=e.select(".tooltips-group"),nt=Gc.tooltipPanel().config({container:rt,fontSize:8})(),it=Gc.tooltipPanel().config({container:rt,fontSize:8})(),at=Gc.tooltipPanel().config({container:rt,hasTick:!0})();if(!x){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});R.on("mousemove.angular-guide",function(t,e){var r=Gc.util.getMousePos(V).angle;ot.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;J=i.invert(n);var a=Gc.util.convertToCartesian(g+12,r+180);nt.text(Gc.util.round(J)).move([a[0]+m[0],a[1]+m[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var st=et.select("circle").style({stroke:"grey",fill:"none"});R.on("mousemove.radial-guide",function(t,e){var r=Gc.util.getMousePos(V).radius;st.attr({r:r}).style({opacity:.5}),tt=n.invert(Gc.util.getMousePos(V).radius);var i=Gc.util.convertToCartesian(r,u.radialAxis.orientation);it.text(Gc.util.round(tt)).move([i[0]+m[0],i[1]+m[1]])}).on("mouseout.radial-guide",function(t,e){st.style({opacity:0}),at.hide(),nt.hide(),it.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var i=t.select(this),a=this.style.fill,o="black",s=this.style.opacity||1;if(i.attr({"data-opacity":s}),a&&"none"!==a){i.attr({"data-fill":a}),o=t.hsl(a).darker().toString(),i.style({fill:o,opacity:1});var l={t:Gc.util.round(r[0]),r:Gc.util.round(r[1])};x&&(l.t=y[r[0]]);var u="t: "+l.t+", r: "+l.r,c=this.getBoundingClientRect(),h=e.node().getBoundingClientRect(),f=[c.left+c.width/2-z[0]-h.left,c.top+c.height/2-z[1]-h.top];at.config({color:o}).text(u),at.move(f)}else a=this.style.stroke||"black",i.attr({"data-stroke":a}),o=t.hsl(a).darker().toString(),i.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(e,r){if(0!=t.event.which)return!1;t.select(this).attr("data-fill")&&at.show()}).on("mouseout.tooltip",function(e,r){at.hide();var n=t.select(this),i=n.attr("data-fill");i?n.style({fill:i,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return a;var e=Gc.util.cloneJson(t);return e.data.forEach(function(t,e){a.data[e]||(a.data[e]={}),Hc(a.data[e],Gc.Axis.defaultConfig().data[0]),Hc(a.data[e],t)}),Hc(a.layout,Gc.Axis.defaultConfig().layout),Hc(a.layout,e.layout),this},u.getLiveConfig=function(){return s},u.getinputConfig=function(){return o},u.radialScale=function(t){return n},u.angularScale=function(t){return i},u.svg=function(){return e},t.rebind(u,l,"on"),u},Gc.Axis.defaultConfig=function(e,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:t.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Gc.util={},Gc.DATAEXTENT="dataExtent",Gc.AREA="AreaChart",Gc.LINE="LinePlot",Gc.DOT="DotPlot",Gc.BAR="BarChart",Gc.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},Gc.util._extend=function(t,e){for(var r in t)e[r]=t[r]},Gc.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Gc.util.dataFromEquation2=function(e,r){var n=r||6;return t.range(0,360+n,n).map(function(t,r){var n=t*Math.PI/180;return[t,e(n)]})},Gc.util.dataFromEquation=function(e,r,n){var i=r||6,a=[],o=[];t.range(0,360+i,i).forEach(function(t,r){var n=t*Math.PI/180,i=e(n);a.push(t),o.push(i)});var s={t:a,r:o};return n&&(s.name=n),s},Gc.util.ensureArray=function(e,r){if(void 0===e)return null;var n=[].concat(e);return t.range(r).map(function(t,e){return n[e]||n[0]})},Gc.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=Gc.util.ensureArray(t[e],r)}),t},Gc.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},Gc.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},Gc.util.sumArrays=function(e,r){return t.zip(e,r).map(function(e,r){return t.sum(e)})},Gc.util.arrayLast=function(t){return t[t.length-1]},Gc.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},Gc.util.flattenArray=function(t){for(var e=[];!Gc.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},Gc.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},Gc.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},Gc.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},Gc.util.getMousePos=function(e){var r=t.mouse(e.node()),n=r[0],i=r[1],a={};return a.x=n,a.y=i,a.pos=r,a.angle=180*(Math.atan2(i,n)+Math.PI)/Math.PI,a.radius=Math.sqrt(n*n+i*i),a},Gc.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i0)){var l=t.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:c(s),transform:function(t,e){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return p.fill(n,i,a)},"fill-opacity":0,stroke:function(t,e){return p.stroke(n,i,a)},"stroke-width":function(t,e){return p["stroke-width"](n,i,a)},"stroke-dasharray":function(t,e){return p["stroke-dasharray"](n,i,a)},opacity:function(t,e){return p.opacity(n,i,a)},display:function(t,e){return p.display(n,i,a)}})}};var h=r.angularScale.range(),f=Math.abs(h[1]-h[0])/o[0].length*Math.PI/180,d=t.svg.arc().startAngle(function(t){return-f/2}).endAngle(function(t){return f/2}).innerRadius(function(t){return r.radialScale(l+(t[2]||0))}).outerRadius(function(t){return r.radialScale(l+(t[2]||0))+r.radialScale(t[1])});u.arc=function(e,n,i){t.select(this).attr({class:"mark arc",d:d,transform:function(t,e){return"rotate("+(r.orientation+s(t[0])+90)+")"}})};var p={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,i){return n[e[i].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return void 0===e[n].data.visible||e[n].data.visible?"block":"none"}},g=t.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(p).each(u[r.geometryType]),v.exit().remove(),g.exit().remove()})}return i.config=function(t){return arguments.length?(t.forEach(function(t,r){e[r]||(e[r]={}),Hc(e[r],Gc.PolyChart.defaultConfig()),Hc(e[r],t)}),this):e},i.getColorScale=function(){},t.rebind(i,r,"on"),i},Gc.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:t.scale.category20()}}},Gc.BarChart=function(){return Gc.PolyChart()},Gc.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Gc.AreaChart=function(){return Gc.PolyChart()},Gc.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Gc.DotPlot=function(){return Gc.PolyChart()},Gc.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Gc.LinePlot=function(){return Gc.PolyChart()},Gc.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Gc.Legend=function(){var e=Gc.Legend.defaultConfig(),r=t.dispatch("hover");function n(){var r=e.legendConfig,i=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=Hc({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=t.merge(i);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||void 0===r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=t.select(o));var s=a.map(function(t,e){return t.color}),l=r.fontSize,u=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,c=u?r.height:l*a.length,h=o.classed("legend-group",!0).selectAll("svg").data([0]),f=h.enter().append("svg").attr({width:300,height:c+l,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});f.append("g").classed("legend-axis",!0),f.append("g").classed("legend-marks",!0);var d=t.range(a.length),p=t.scale[u?"linear":"ordinal"]().domain(d).range(s),g=t.scale[u?"linear":"ordinal"]().domain(d)[u?"range":"rangePoints"]([0,c]);if(u){var v=h.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),h.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var m=h.select(".legend-marks").selectAll("path.legend-mark").data(a);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[l/2,g(e)+l/2]+")"},d:function(e,r){var n,i,a,o=e.symbol;return a=3*(i=l),"line"===(n=o)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=t.svg.symbolTypes.indexOf(n)?t.svg.symbol().type(n).size(a)():t.svg.symbol().type("square").size(a)()},fill:function(t,e){return p(e)}}),m.exit().remove()}var y=t.svg.axis().scale(g).orient("right"),b=h.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:l,l/2]+")"}).call(y);return b.selectAll(".domain").style({fill:"none",stroke:"none"}),b.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),b.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),n}return n.config=function(t){return arguments.length?(Hc(e,t),this):e},t.rebind(n,r,"on"),n},Gc.Legend.defaultConfig=function(t,e){return{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:!1}}},Gc.tooltipPanel=function(){var e,r,n,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},a="tooltip-"+Gc.tooltipPanel.uid++,o=10,s=function(){var t=(e=i.container.selectAll("g."+a).data([0])).enter().append("g").classed(a,!0).style({"pointer-events":"none",display:"none"});return n=t.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=t.append("text").attr({dx:i.padding+o,dy:.3*+i.fontSize}),s};return s.text=function(a){var l=t.hsl(i.color).l,u=l>=.5?"#aaa":"white",c=l>=.5?"black":"white",h=a||"";r.style({fill:c,"font-size":i.fontSize+"px"}).text(h);var f=i.padding,d=r.node().getBBox(),p={fill:i.color,stroke:u,"stroke-width":"2px"},g=d.width+2*f+o,v=d.height+2*f;return n.attr({d:"M"+[[o,-v/2],[o,-v/4],[i.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),e.attr({transform:"translate("+[o,-v/2+2*f]+")"}),e.style({display:"block"}),s},s.move=function(t){if(e)return e.attr({transform:"translate("+[t[0],t[1]]+")"}).style({display:"block"}),s},s.hide=function(){if(e)return e.style({display:"none"}),s},s.show=function(){if(e)return e.style({display:"block"}),s},s.config=function(t){return Hc(i,t),s},s},Gc.tooltipPanel.uid=1,Gc.adapter={},Gc.adapter.plotly=function(){var e={convert:function(e,r){var n={};if(e.data&&(n.data=e.data.map(function(t,e){var n=Hc({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,e){Gc.util.translator.apply(null,t.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&e.layout&&"stack"===e.layout.barmode)){var i=Gc.util.duplicates(n.data.map(function(t,e){return t.geometry}));n.data.forEach(function(t,e){var r=i.indexOf(t.geometry);-1!=r&&(n.data[e].groupId=r)})}if(e.layout){var a=Hc({},e.layout);if([[a,["plot_bgcolor"],["backgroundColor"]],[a,["showlegend"],["showLegend"]],[a,["radialaxis"],["radialAxis"]],[a,["angularaxis"],["angularAxis"]],[a.angularaxis,["showline"],["gridLinesVisible"]],[a.angularaxis,["showticklabels"],["labelsVisible"]],[a.angularaxis,["nticks"],["ticksCount"]],[a.angularaxis,["tickorientation"],["tickOrientation"]],[a.angularaxis,["ticksuffix"],["ticksSuffix"]],[a.angularaxis,["range"],["domain"]],[a.angularaxis,["endpadding"],["endPadding"]],[a.radialaxis,["showline"],["gridLinesVisible"]],[a.radialaxis,["tickorientation"],["tickOrientation"]],[a.radialaxis,["ticksuffix"],["ticksSuffix"]],[a.radialaxis,["range"],["domain"]],[a.angularAxis,["showline"],["gridLinesVisible"]],[a.angularAxis,["showticklabels"],["labelsVisible"]],[a.angularAxis,["nticks"],["ticksCount"]],[a.angularAxis,["tickorientation"],["tickOrientation"]],[a.angularAxis,["ticksuffix"],["ticksSuffix"]],[a.angularAxis,["range"],["domain"]],[a.angularAxis,["endpadding"],["endPadding"]],[a.radialAxis,["showline"],["gridLinesVisible"]],[a.radialAxis,["tickorientation"],["tickOrientation"]],[a.radialAxis,["ticksuffix"],["ticksSuffix"]],[a.radialAxis,["range"],["domain"]],[a.font,["outlinecolor"],["outlineColor"]],[a.legend,["traceorder"],["reverseOrder"]],[a,["labeloffset"],["labelOffset"]],[a,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,e){Gc.util.translator.apply(null,t.concat(r))}),r?(void 0!==a.tickLength&&(a.angularaxis.ticklen=a.tickLength,delete a.tickLength),a.tickColor&&(a.angularaxis.tickcolor=a.tickColor,delete a.tickColor)):(a.angularAxis&&void 0!==a.angularAxis.ticklen&&(a.tickLength=a.angularAxis.ticklen),a.angularAxis&&void 0!==a.angularAxis.tickcolor&&(a.tickColor=a.angularAxis.tickcolor)),a.legend&&"boolean"!=typeof a.legend.reverseOrder&&(a.legend.reverseOrder="normal"!=a.legend.reverseOrder),a.legend&&"boolean"==typeof a.legend.traceorder&&(a.legend.traceorder=a.legend.traceorder?"reversed":"normal",delete a.legend.reverseOrder),a.margin&&void 0!==a.margin.t){var o=["t","r","b","l","pad"],s=["top","right","bottom","left","pad"],l={};t.entries(a.margin).forEach(function(t,e){l[s[o.indexOf(t.key)]]=t.value}),a.margin=l}r&&(delete a.needsEndSpacing,delete a.minorTickColor,delete a.minorTicks,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksStep,delete a.angularaxis.rewriteTicks,delete a.angularaxis.nticks,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksStep,delete a.radialaxis.rewriteTicks,delete a.radialaxis.nticks),n.layout=a}return n}};return e};var Xc,Wc=re.extendDeepAll,Yc=Xc={};Yc.framework=function(e){var r,n,i,a,o,s=new function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?Wc(r,n):n,i||(i=Vc.Axis()),a=Vc.adapter.plotly().convert(r),i.config(a).render(o),e.data=r.data,e.layout=r.layout,Yc.fillLayout(e),r}return l.isPolar=!0,l.svg=function(){return i.svg()},l.getConfig=function(){return r},l.getLiveConfig=function(){return Vc.adapter.plotly().convert(i.getLiveConfig(),!0)},l.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},l.setUndoPoint=function(){var t,e,i=this,a=Vc.util.cloneJson(r);t=a,e=n,s.add({undo:function(){e&&i(e)},redo:function(){i(t)}}),n=Vc.util.cloneJson(a)},l.undo=function(){s.undo()},l.redo=function(){s.redo()},l},Yc.fillLayout=function(e){var r=t.select(e).selectAll(".plot-container"),n=r.selectAll(".svg-container"),i=e.framework&&e.framework.svg&&e.framework.svg(),a={width:800,height:600,paper_bgcolor:Ne.background,_container:r,_paperdiv:n,_paper:i};e._fullLayout=Wc(a,e.layout)};var Zc={};(Zc=Vc).manager=Xc;var Qc={},Kc=Dc.enforce,$c=Dc.clean,Jc=Ii,th=0;function eh(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){re.error(t)}}function rh(t,e){eh(t,Ne.combine(e,"white"))}function nh(t,e){t._context||(t._context=re.extendDeep({},x));var r,n,i,a=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function oh(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),ah(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&ah(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function sh(t,r,n,i,a){!function(t,e,r,n){var i=re.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!re.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var a in ah(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,r,n,i);for(var o=function(t,r,n,i){var a,o,s,l,u,c=re.isPlainObject(i),h=[];for(var f in Array.isArray(n)||(n=[n]),n=ih(n,t.data.length-1),r)for(var d=0;d0&&"string"!=typeof _.parts[M-1];)A--;var T=_.parts[A],k=_.parts[A-1]+"."+T,E=_.parts.slice(0,A).join("."),L=re.nestedProperty(t.layout,E).get(),C=re.nestedProperty(o,E).get(),S=_.get();if(void 0!==w){p[x]=w,g[x]="reverse"===T?w:uh(S);var P=Jn.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var O in P.impliedEdits)v(re.relativeAttr(x,O),P.impliedEdits[O]);if(-1!==["width","height"].indexOf(x)&&null===w)o[x]=t._initialAutoSize[x];else if(k.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))b(k),re.nestedProperty(o,E+"._inputRange").set(null);else if(k.match(/^[xyz]axis[0-9]*\.autorange$/)){b(k),re.nestedProperty(o,E+"._inputRange").set(null);var I=re.nestedProperty(o,E).get();I._inputDomain&&(I._input.domain=I._inputDomain.slice())}else k.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&re.nestedProperty(o,E+"._inputDomain").set(null);if("type"===T){var N=L,D="linear"===C.type&&"log"===w,z="log"===C.type&&"linear"===w;if(D||z){if(N&&N.range)if(C.autorange)D&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],j=N.range[1];D?(F<=0&&j<=0&&v(E+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(E+".range[0]",Math.log(F)/Math.LN10),v(E+".range[1]",Math.log(j)/Math.LN10)):(v(E+".range[0]",Math.pow(10,F)),v(E+".range[1]",Math.pow(10,j)))}else v(E+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],R.getComponentMethod("annotations","convertCoords")(t,C,w,v),R.getComponentMethod("images","convertCoords")(t,C,w,v)}else v(E+".autorange",!0),v(E+".range",null);re.nestedProperty(o,E+"._inputRange").set(null)}else if(T.match(Oe.AX_NAME_PATTERN)){var B=re.nestedProperty(o,x).get(),U=(w||{}).type;U&&"-"!==U||(U="linear"),R.getComponentMethod("annotations","convertCoords")(t,B,U,v),R.getComponentMethod("images","convertCoords")(t,B,U,v)}var V=vu.containerArrayMatch(x);if(V){r=V.array,n=V.index;var H=V.property,q=(re.nestedProperty(a,r)||[])[n]||{},G=q,X=P||{editType:"calc"},W=-1!==X.editType.indexOf("calcIfAutorange");""===n?(W?d.calc=!0:gr.update(d,X),W=!1):""===H&&(G=w,vu.isAddVal(w)?g[x]=null:vu.isRemoveVal(w)?(g[x]=q,G=q):re.warn("unrecognized full object value",e)),W&&(dh(t,G,"x")||dh(t,G,"y"))?d.calc=!0:gr.update(d,X),u[r]||(u[r]={});var Y=u[r][n];Y||(Y=u[r][n]={}),Y[H]=w,delete e[x]}else"reverse"===T?(L.range?L.range.reverse():(v(E+".autorange",!0),L.range=[1,0]),C.autorange?d.calc=!0:d.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===x&&("lasso"===w||"select"===w)&&"lasso"!==S&&"select"!==S?d.plot=!0:P?gr.update(d,P):d.calc=!0,_.set(w))}}for(r in u){vu.applyContainerArrayChanges(t,re.nestedProperty(a,r),u[r],d)||(d.plot=!0)}var Z=o._axisConstraintGroups||[];for(m in y)for(n=0;n=0&&r=0&&r=i.length?i[0]:i[t]:i}function s(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function l(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,vi.transition(t,e.frame.data,e.frame.layout,su.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function h(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var f,d,p=0;function g(t){return Array.isArray(i)?p>=i.length?t.transitionOpts=i[p]:t.transitionOpts=i[0]:t.transitionOpts=i,p++,t}var v=[],m=void 0===e||null===e,y=Array.isArray(e);if(!m&&!y&&re.isPlainObject(e))v.push({type:"object",data:g(re.extendFlat({},e))});else if(m||-1!==["string","number"].indexOf(typeof e))for(f=0;f0&&__)&&w.push(d);v=w}}v.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(re.isPlainObject(e[n])){var f=e[n].name,d=(l[f]||h[f]||{}).name,p=e[n].name,g=l[d]||h[d];d&&p&&"number"==typeof p&&g&&th<5&&(th++,re.warn('addFrames: overwriting frame "'+(l[d]||h[d]).name+'" with a frame whose name of type "number" also equates to "'+d+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===th&&re.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),h[f]={name:f},c.push({frame:vi.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=c[n].frame).name&&re.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;l[i.name="frame "+t._transitionData._counter++];);if(l[i.name]){for(a=0;a=0;r--)n=e[r],a.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:i[n]});var s=vi.modifyFrames,l=vi.modifyFrames,u=[t,o],c=[t,a];return au&&au.add(t,s,u,l,c),vi.modifyFrames(t,a)},Qc.purge=function(t){var e=(t=re.getGraphDiv(t))._fullLayout||{},r=t._fullData||[];return vi.cleanPlot([],{},r,e),vi.purge(t),tr.purge(t),e._container&&e._container.remove(),delete t._context,t};var vh={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},mh=Ye.EventEmitter;var yh=function(t){var e=t.emitter||new mh,r=new Promise(function(n,i){var a=window.Image,o=t.svg,s=t.format||"png";if(re.isIE()&&"svg"!==s){var l=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(l),t.promise?r:e.emit("error",l)}var u=t.canvas,c=t.scale||1,h=c*(t.width||300),f=c*(t.height||150),d=u.getContext("2d"),p=new a,g="data:image/svg+xml,"+encodeURIComponent(o);u.width=h,u.height=f,p.onload=function(){var r;switch("svg"!==s&&d.drawImage(p,0,0,h,f),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=g;break;default:var a="Image format is not jpeg, png, svg or webp.";if(i(new Error(a)),!t.promise)return e.emit("error",a)}n(r),t.promise||e.emit("success",r)},p.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},p.src=g});return t.promise?r:e},bh=/"/g,xh=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var _h=function(e,r,n){var i,a=e._fullLayout,o=a._paper,s=a._toppaper,l=a.width,u=a.height;o.insert("rect",":first-child").call(hn.setRect,0,0,l,u).call(Ne.fill,a.paper_bgcolor);var c=a._basePlotModules||[];for(i=0;i")?"":r.html(t).text()});return r.remove(),n}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(xh,"'"),re.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},wh={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},Mh=/^data:image\/\w+;base64,/;var Ah=function(t,e){var r,n,i;function a(t){return!(t in e)||re.validate(e[t],wh[t])}if(e=e||{},re.isPlainObject(t)?(r=t.data||[],n=t.layout||{},i=t.config||{}):(t=re.getGraphDiv(t),r=re.extendDeep([],t.data),n=re.extendDeep({},t.layout),i=t._context),!a("width")||!a("height"))throw new Error("Height and width should be pixel values.");if(!a("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function s(t,r){return re.coerce(e,o,wh,t,r)}var l=s("format"),u=s("width"),c=s("height"),h=s("scale"),f=s("setBackground"),d=s("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=re.extendFlat({},n);u&&(g.width=u),c&&(g.height=c);var v=re.extendFlat({},i,{staticPlot:!0,setBackground:f}),m=vh.getRedrawFunc(p);function y(){return new Promise(function(t){setTimeout(t,vh.getDelay(p._fullLayout))})}function b(){return new Promise(function(t,e){var r=_h(p,l,h),n=p._fullLayout.width,i=p._fullLayout.height;if(Qc.purge(p),document.body.removeChild(p),"svg"===l)return t(d?r:"data:image/svg+xml,"+encodeURIComponent(r));var a=document.createElement("canvas");a.id=re.randstr(),yh({format:l,width:n,height:i,scale:h,canvas:a,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){Qc.plot(p,r,g,v).then(m).then(y).then(b).then(function(e){t(function(t){return d?t.replace(Mh,""):t}(e))}).catch(function(t){e(t)})})},Th=re.isPlainObject,kh=Array.isArray,Eh=re.isArrayOrTypedArray;function Lh(t,e,r,n,i,a){a=a||[];for(var o=Object.keys(t),s=0;sh.length&&n.push(Ph("unused",i,u.concat(h.length)));var v,m,y,b,x,_=h.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===f.dimensions)for(m=0;m<_;m++)if(kh(c[m])){c[m].length>h[m].length&&n.push(Ph("unused",i,u.concat(m,h[m].length)));var M=h[m].length;for(v=0;v<(w?Math.min(M,g[m].length):M);v++)y=w?g[m][v]:g,b=c[m][v],x=h[m][v],re.validate(b,y)?x!==b&&x!==+b&&n.push(Ph("dynamic",i,u.concat(m,v),b,x)):n.push(Ph("value",i,u.concat(m,v),b))}else n.push(Ph("array",i,u.concat(m),c[m]));else for(m=0;m<_;m++)y=w?g[m]:g,b=c[m],x=h[m],re.validate(b,y)?x!==b&&x!==+b&&n.push(Ph("dynamic",i,u.concat(m),b,x)):n.push(Ph("value",i,u.concat(m),b))}else if(f.items&&!d&&kh(c)){var A,T,k=g[Object.keys(g)[0]],E=[];for(A=0;A1&&a.push(Ph("object","layout"))),vi.supplyDefaults(o);for(var s=o._fullData,l=r.length,u=0;u-1&&(s[u[r]].title="");for(r=0;r0?u>=v:u<=v));c++)u>y&&u0?u>=v:u<=v));c++)u>h[0]&&u1){var V=Math.pow(10,Math.floor(Math.log(U)/Math.LN10));j*=V*re.roundUp(U/V,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(z.tick0=0)}z.dtick=j}z.domain=[O+C,O+k-C],z.setScale();var H=o._infolayer.selectAll("g."+r).data([0]);H.enter().append("g").classed(r,!0).classed(rf.colorbar,!0).each(function(){var e=t.select(this);e.append("rect").classed(rf.cbbg,!0),e.append("g").classed(rf.cbfills,!0),e.append("g").classed(rf.cblines,!0),e.append("g").classed(rf.cbaxis,!0).classed(rf.crisp,!0),e.append("g").classed(rf.cbtitleunshift,!0).append("g").classed(rf.cbtitle,!0),e.append("rect").classed(rf.cboutline,!0),e.select(".cbtitle").datum(0)}),H.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var q=H.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");z._axislayer=H.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var X,W=l.l+(n.x+E)*l.w,Y=z.titlefont.size;X="top"===n.titleside?(1-(O+k-C))*l.h+l.t+3+.75*Y:(1-(O+C))*l.h+l.t-3-.25*Y,tt(z._id+"title",{attributes:{x:W,y:X,"text-anchor":"start"}})}var Z,Q,K,$=re.syncOrAsync([vi.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=H.select(".cbtitle"),i=r.select("text"),a=[-n.outlinewidth/2,n.outlinewidth/2],u=r.select(".h"+z._id+"title-math-group").node(),c=15.6;if(i.node()&&(c=parseInt(i.node().style.fontSize,10)*ef),u?(G=hn.bBox(u).height)>c&&(a[1]-=(G-c)/2):i.node()&&!i.classed(rf.jsPlaceholder)&&(G=hn.bBox(i.node()).height),G){if(G+=5,"top"===n.titleside)z.domain[1]-=G/l.h,a[1]*=-1;else{z.domain[0]+=G/l.h;var v=Fr.lineCount(i);a[1]+=(1-v)*c}r.attr("transform","translate("+a+")"),z.setScale()}}H.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-z.domain[1]))+")"),z._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var m=H.select(".cbfills").selectAll("rect.cbfill").data(d);m.enter().append("rect").classed(rf.cbfill,!0).style("stroke","none"),m.exit().remove(),m.each(function(e,r){var n=[0===r?h[0]:(d[r]+d[r-1])/2,r===d.length-1?h[1]:(d[r]+d[r+1])/2].map(z.c2p).map(Math.round);r!==d.length-1&&(n[1]+=n[1]>n[0]?1:-1);var i=g(e).replace("e-",""),a=s(i).toHexString();t.select(this).attr({x:S,width:Math.max(M,2),y:t.min(n),height:Math.max(t.max(n)-t.min(n),2),fill:a})});var y=H.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?f:[]);return y.enter().append("path").classed(rf.cbline,!0),y.exit().remove(),y.each(function(e){t.select(this).attr("d","M"+S+","+(Math.round(z.c2p(e))+n.line.width/2%1)+"h"+M).call(hn.lineGroupStyle,n.line.width,p(e),n.line.dash)}),z._axislayer.selectAll("g."+z._id+"tick,path").remove(),z._pos=S+M+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),z.side="right",re.syncOrAsync([function(){return Ki.doTicks(e,z,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=z.titlefont.size,i=z._offset+z._length/2,a=l.l+(z.position||0)*l.w+("right"===z.side?10+r*(z.showticklabels?1:.5):-10-r*(z.showticklabels?.5:0));tt("h"+z._id+"title",{avoid:{selection:t.select(e).selectAll("g."+z._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:a,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},vi.previousPromises,function(){var t=M+n.outlinewidth/2+hn.bBox(z._axislayer.node()).width;if((x=q.select("text")).node()&&!x.classed(rf.jsPlaceholder)){var i,a=q.select(".h"+z._id+"title-math-group").node();i=a&&-1!==["top","bottom"].indexOf(n.titleside)?hn.bBox(a).width:hn.bBox(q.node()).right-S-l.l,t=Math.max(t,i)}var o=2*n.xpad+t+n.borderwidth+n.outlinewidth/2,s=I-N;H.select(".cbbg").attr({x:S-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:N-L,width:Math.max(o,2),height:Math.max(s+2*L,2)}).call(Ne.fill,n.bgcolor).call(Ne.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),H.selectAll(".cboutline").attr({x:S,y:N+n.ypad+("top"===n.titleside?G:0),width:Math.max(M,2),height:Math.max(s-2*n.ypad-G,2)}).call(Ne.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var u=({center:.5,right:1}[n.xanchor]||0)*o;H.attr("transform","translate("+(l.l-u)+","+l.t+")"),vi.autoMargin(e,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],e);if($&&$.then&&(e._promises||[]).push($),e._context.edits.colorbarPosition)rr.init({element:H.node(),gd:e,prepFn:function(){Z=H.attr("transform"),Nn(H)},moveFn:function(t,e){H.attr("transform",Z+" translate("+t+","+e+")"),Q=rr.align(P+t/l.w,A,0,1,n.xanchor),K=rr.align(O-e/l.h,k,0,1,n.yanchor);var r=rr.getCursor(Q,K,n.xanchor,n.yanchor);Nn(H,r)},doneFn:function(){Nn(H),void 0!==Q&&void 0!==K&&R.call("restyle",e,{"colorbar.x":Q,"colorbar.y":K},a().index)}});return $}function J(t,e){return re.coerce(D,z,wr,t,e)}function tt(t,r){var n,i=a();n=R.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var s={propContainer:z,propName:n,traceIndex:i.index,placeholder:o._dfltTitle.colorbar,containerGroup:H.select(".cbtitle")},l="h"===t.charAt(0)?t.substr(1):"h"+t;H.selectAll("."+l+",."+l+"-math-group").remove(),Ci.draw(e,t,tf(s,r||{}))}o._infolayer.selectAll("g."+r).remove()}function a(){var t,n,i=r.substr(2);for(t=0;tU||t[1]H)return[gf(t[0],B,U),gf(t[1],V,H)]}function X(t,e){return t[0]===e[0]&&(t[0]===B||t[0]===U)||(t[1]===e[1]&&(t[1]===V||t[1]===H)||void 0)}function W(t,e,r){return function(n,i){var a=G(n),o=G(i),s=[];if(a&&o&&X(a,o))return s;a&&s.push(a),o&&s.push(o);var l=2*re.constrain((n[t]+i[t])/2,e,r)-((a||n)[t]+(o||i)[t]);l&&((a&&o?l>0==a[t]>o[t]?a:o:a||o)[t]+=l);return s}}function Y(t){var e=t[0],r=t[1],n=e===E[L-1][0],i=r===E[L-1][1];if(!n||!i)if(L>1){var a=e===E[L-2][0],o=r===E[L-2][1];n&&(e===B||e===U)&&a?o?L--:E[L-1]=t:i&&(r===V||r===H)&&o?a?L--:E[L-1]=t:E[L++]=t}else E[L++]=t}function Z(t){E[L-1][0]!==t[0]&&E[L-1][1]!==t[1]&&Y([I,N]),Y(t),D=null,I=N=0}function Q(t){if(R=t[0]U?U:0,O=t[1]H?H:0,R||O){if(L)if(D){var e=F(D,t);e.length>1&&(Z(e[0]),E[L++]=e[1])}else z=F(E[L-1],t)[0],E[L++]=z;else E[L++]=[R||t[0],O||t[1]];var r=E[L-1];R&&O&&(r[0]!==R||r[1]!==O)?(D&&(I!==R&&N!==O?Y(I&&N?(n=D,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?B:U,H]:[o>0?U:B,V]):[I||R,N||O]):I&&N&&Y([I,N])),Y([R,O])):I-R&&N-O&&Y([R||I,O||N]),D=t,I=R,N=O}else D&&Z(F(D,t)[0]),E[L++]=t;var n,i,a,o}for("linear"===M||"spline"===M?F=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var a=q[i],o=pf(t[0],t[1],e[0],e[1],a[0],a[1],a[2],a[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&P(o,t)S(s))break;i=s,(p=c[0]*u[0]+c[1]*u[1])>f?(f=p,a=s,l=!1):p=t.length||!s)break;Q(s),n=s}}else Q(a)}D&&Y([I||D[0],N||D[1]]),T.push(E.slice(0,L))}return T},mf=Wu.tester;function yf(e,r,n,i,a,o,s){var l,u;!function(e,r,n,i,a){var o=n.xaxis,s=n.yaxis,l=t.extent(re.simpleMap(o.range,o.r2c)),u=t.extent(re.simpleMap(s.range,s.r2c)),c=i[0].trace;if(!cn.hasMarkers(c))return;var h=c.marker.maxdisplayed;if(0===h)return;var f=i.filter(function(t){return t.x>=l[0]&&t.x<=l[1]&&t.y>=u[0]&&t.y<=u[1]}),d=Math.ceil(f.length/h),p=0;a.forEach(function(t,e){var n=t[0].trace;cn.hasMarkers(n)&&n.marker.maxdisplayed>0&&e0;function h(t){return c?t.transition():t}var f=n.xaxis,d=n.yaxis,p=i[0].trace,g=p.line,v=t.select(o);if(R.getComponentMethod("errorbars","plot")(v,n,s),!0===p.visible){var m,y;h(v).style("opacity",p.opacity);var b=p.fill.charAt(p.fill.length-1);"x"!==b&&"y"!==b&&(b=""),i[0].node3=v;var x="",_=[],w=p._prevtrace;w&&(x=w._prevRevpath||"",y=w._nextFill,_=w._polygons);var M,A,T,k,E,L,C,S,P,O="",I="",N=[],D=re.noop;if(m=p._ownFill,cn.hasLines(p)||"none"!==p.fill){for(y&&y.datum(i),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=hn.steps(g.shape),k=hn.steps(g.shape.split("").reverse().join(""))):T=k="spline"===g.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?hn.smoothclosed(t.slice(1),g.smoothing):hn.smoothopen(t,g.smoothing)}:function(t){return"M"+t.join("L")},E=function(t){return k(t.reverse())},N=vf(i,{xaxis:f,yaxis:d,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=p._polygons=new Array(N.length),u=0;u1){var n=t.select(this);if(n.datum(i),e)h(n.style("opacity",0).attr("d",M).call(hn.lineGroupStyle)).style("opacity",1);else{var a=h(n);a.attr("d",M),hn.singleLineStyle(i,a)}}}}}var z=v.selectAll(".js-line").data(N);h(z.exit()).style("opacity",0).remove(),z.each(D(!1)),z.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(hn.lineGroupStyle).each(D(!0)),hn.setClipUrl(z,n.layerClipId),N.length?(m?L&&S&&(b?("y"===b?L[1]=S[1]=d.c2p(0,!0):"x"===b&&(L[0]=S[0]=f.c2p(0,!0)),h(m).attr("d","M"+S+"L"+L+"L"+O.substr(1)).call(hn.singleFillStyle)):h(m).attr("d",O+"Z").call(hn.singleFillStyle)):y&&("tonext"===p.fill.substr(0,6)&&O&&x?("tonext"===p.fill?h(y).attr("d",O+"Z"+x+"Z").call(hn.singleFillStyle):h(y).attr("d",O+"L"+x.substr(1)+"Z").call(hn.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(y),p._polygons=null)),p._prevRevpath=I,p._prevPolygons=P):(m?j(m):y&&j(y),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");l=F.data([i]),F.each(q),l.enter().append("g").classed("points",!0).each(q),l.exit().remove(),l.each(function(e){var r=!1===e[0].trace.cliponaxis;hn.setClipUrl(t.select(this),r?null:n.layerClipId)})}function j(t){h(t).attr("d","M0,0Z")}function B(t){return t.filter(function(t){return t.vis})}function U(t){return t.id}function V(t){if(t.ids)return U}function H(){return!1}function q(r){var i,a=r[0].trace,o=t.select(this),s=cn.hasMarkers(a),l=cn.hasText(a),u=V(a),p=H,g=H;s&&(p=a.marker.maxdisplayed||a._needsCull?B:re.identity),l&&(g=a.marker.maxdisplayed||a._needsCull?B:re.identity);var v=(i=o.selectAll("path.point").data(p,u)).enter().append("path").classed("point",!0);c&&v.call(hn.pointStyle,a,e).call(hn.translatePoints,f,d).style("opacity",0).transition().style("opacity",1);var m=s&&hn.tryColorscale(a.marker,""),y=s&&hn.tryColorscale(a.marker,"line");i.order(),i.each(function(r){var i=t.select(this),o=h(i);hn.translatePoint(r,o,f,d)?(hn.singlePointStyle(r,o,a,m,y,e),n.layerClipId&&hn.hideOutsideRangePoint(r,o,f,d,a.xcalendar,a.ycalendar),a.customdata&&i.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),c?i.exit().transition().style("opacity",0).remove():i.exit().remove(),(i=o.selectAll("g").data(g,u)).enter().append("g").classed("textpoint",!0).append("text"),i.order(),i.each(function(e){var r=t.select(this),i=h(r.select("text"));hn.translatePoint(e,i,f,d)?n.layerClipId&&hn.hideOutsideRangePoint(e,r,f,d,a.xcalendar,a.ycalendar):r.remove()}),i.selectAll("text").call(hn.textPointStyle,a,e).each(function(e){var r=f.c2p(e.x),n=d.c2p(e.y);t.select(this).selectAll("tspan.line").each(function(){h(t.select(this)).attr({x:r,y:n})})}),i.exit().remove()}}function bf(t,e,r){var n=t.selectAll("path.point"),i=t.selectAll("text");hn.pointStyle(n,e,r),hn.textPointStyle(i,e,r),hn.selectedPointStyle(n,e),hn.selectedTextStyle(i,e)}var xf=function(e,r){var n=r?r[0].node3:t.select(e).selectAll("g.trace.scatter");n.style("opacity",function(t){return t[0].trace.opacity}),n.selectAll("g.points").each(function(r){bf(t.select(this),r.trace||r[0].trace,e)}),n.selectAll("g.trace path.js-line").call(hn.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(hn.fillGroupStyle),R.getComponentMethod("errorbars","style")(n)},_f={};_f.hasLines=cn.hasLines,_f.hasMarkers=cn.hasMarkers,_f.hasText=cn.hasText,_f.isBubble=cn.isBubble,_f.attributes=Gn,_f.supplyDefaults=function(t,e,r,n){function i(r,n){return re.coerce(t,e,Gn,r,n)}var a=function(t,e,r,n){var i,a=n("x"),o=n("y");if(R.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),a)o?i=Math.min(a.length,o.length):(i=a.length,n("y0"),n("dy"));else{if(!o)return 0;i=e.y.length,n("x0"),n("dx")}return e._length=i,i}(t,e,n,i),o=a=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}},_f.calc=Jh,_f.arraysToCalcdata=Xh,_f.plot=function(e,r,n,i,a){var o,s,l,u,c=r.plot.select("g.scatterlayer"),h=!i,f=!!i&&i.duration>0;for((l=c.selectAll("g.trace").data(n,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),function(t,e,r){var n,i,a=null;for(i=0;is[e[0].trace.uid]?1:-1}),f?(a&&(u=a()),t.transition().duration(i.duration).ease(i.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(t,a){yf(e,a,r,t,n,this,i)})})):c.selectAll("g.trace").each(function(t,a){yf(e,a,r,t,n,this,i)});h&&l.exit().remove(),c.selectAll("path:not([d])").remove()},_f.colorbar=af,_f.style=xf,_f.hoverPoints=function(t,e,r,n){var i=t.cd,a=i[0].trace,o=t.xa,s=t.ya,l=o.c2p(e),u=s.c2p(r),c=[l,u],h=a.hoveron||"",f=-1!==a.mode.indexOf("markers")?3:.5;if(-1!==h.indexOf("points")){var d=function(t){var e=Math.max(f,t.mrc||0),r=o.c2p(t.x)-l,n=s.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-f/e)},p=Xa.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-l);return nD!=(E=w[x][1])>=D&&(A=w[x-1][0],T=w[x][0],E-k&&(M=A+(T-A)*(D-k)/(E-k),P=Math.min(P,M),O=Math.max(O,M)));P=Math.max(P,0),O=Math.min(O,o._length);var z=Ne.defaultLine;return Ne.opacity(a.fillcolor)?z=a.fillcolor:Ne.opacity((a.line||{}).color)&&(z=a.line.color),re.extendFlat(t,{distance:t.maxHoverDistance,x0:P,x1:O,y0:D,y1:D,color:z}),delete t.index,a.text&&!Array.isArray(a.text)?t.text=String(a.text):t.text=a.name,[t]}}},_f.selectPoints=function(t,e){var r,n,i,a,o=t.cd,s=t.xaxis,l=t.yaxis,u=[],c=o[0].trace;if(!cn.hasMarkers(c)&&!cn.hasText(c))return[];if(!1===e)for(r=0;r>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function Uf(t,e,r,n){return new Function([Bf("A","x"+t+"y",e,["y"],!1,n),Bf("B","x"+t+"y",e,["y"],!0,n),Bf("P","c(x,y)"+t+"0",e,["y","c"],!1,n),Bf("Q","c(x,y)"+t+"0",e,["y","c"],!0,n),"function dispatchBsearch",r,"(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",r].join(""))()}var Vf={ge:Uf(">=",!1,"GE"),gt:Uf(">",!1,"GT"),lt:Uf("<",!0,"LT"),le:Uf("<=",!0,"LE"),eq:Uf("-",!0,"EQ",!0)},Hf=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],u=e[7],c=e[8],h=e[9],f=e[10],d=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*u-a*o,_=n*l-i*s,w=n*u-a*s,M=i*u-a*l,A=c*g-h*p,T=c*v-f*p,k=c*m-d*p,E=h*v-f*g,L=h*m-d*g,C=f*m-d*v,S=y*C-b*L+x*E+_*k-w*T+M*A;if(!S)return null;return S=1/S,t[0]=(s*C-l*L+u*E)*S,t[1]=(i*L-n*C-a*E)*S,t[2]=(g*M-v*w+m*_)*S,t[3]=(f*w-h*M-d*_)*S,t[4]=(l*k-o*C-u*T)*S,t[5]=(r*C-i*k+a*T)*S,t[6]=(v*x-p*M-m*b)*S,t[7]=(c*M-f*x+d*b)*S,t[8]=(o*L-s*k+u*A)*S,t[9]=(n*k-r*L-a*A)*S,t[10]=(p*w-g*x+m*y)*S,t[11]=(h*x-c*w-d*y)*S,t[12]=(s*T-o*E-l*A)*S,t[13]=(r*E-n*T+i*A)*S,t[14]=(g*b-p*_-v*y)*S,t[15]=(c*_-h*b+f*y)*S,t};var qf=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t};var Gf=function(t,e,r,n){var i,a,o,s,l,u,c,h,f,d,p=e[0],g=e[1],v=e[2],m=n[0],y=n[1],b=n[2],x=r[0],_=r[1],w=r[2];if(Math.abs(p-x)<1e-6&&Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6)return qf(t);c=p-x,h=g-_,f=v-w,d=1/Math.sqrt(c*c+h*h+f*f),i=y*(f*=d)-b*(h*=d),a=b*(c*=d)-m*f,o=m*h-y*c,(d=Math.sqrt(i*i+a*a+o*o))?(i*=d=1/d,a*=d,o*=d):(i=0,a=0,o=0);s=h*o-f*a,l=f*i-c*o,u=c*a-h*i,(d=Math.sqrt(s*s+l*l+u*u))?(s*=d=1/d,l*=d,u*=d):(s=0,l=0,u=0);return t[0]=i,t[1]=s,t[2]=c,t[3]=0,t[4]=a,t[5]=l,t[6]=h,t[7]=0,t[8]=o,t[9]=u,t[10]=f,t[11]=0,t[12]=-(i*p+a*g+o*v),t[13]=-(s*p+l*g+u*v),t[14]=-(c*p+h*g+f*v),t[15]=1,t};var Xf=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],u=e[8],c=e[9],h=e[10],f=e[11];e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[4]=a*i+u*n,t[5]=o*i+c*n,t[6]=s*i+h*n,t[7]=l*i+f*n,t[8]=u*i-a*n,t[9]=c*i-o*n,t[10]=h*i-s*n,t[11]=f*i-l*n,t};var Wf=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[8],c=e[9],h=e[10],f=e[11];e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[0]=a*i-u*n,t[1]=o*i-c*n,t[2]=s*i-h*n,t[3]=l*i-f*n,t[8]=a*n+u*i,t[9]=o*n+c*i,t[10]=s*n+h*i,t[11]=l*n+f*i,t};var Yf=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[4],c=e[5],h=e[6],f=e[7];e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[0]=a*i+u*n,t[1]=o*i+c*n,t[2]=s*i+h*n,t[3]=l*i+f*n,t[4]=u*i-a*n,t[5]=c*i-o*n,t[6]=h*i-s*n,t[7]=f*i-l*n,t};var Zf=function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t};var Qf=function(t,e,r){var n,i,a,o,s,l,u,c,h,f,d,p,g=r[0],v=r[1],m=r[2];e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],d=e[10],p=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=f,t[10]=d,t[11]=p,t[12]=n*g+s*v+h*m+e[12],t[13]=i*g+l*v+f*m+e[13],t[14]=a*g+u*v+d*m+e[14],t[15]=o*g+c*v+p*m+e[15]);return t};var Kf=function(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a);return t};var $f=function(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],h=t[10],f=t[11],d=t[12],p=t[13],g=t[14],v=t[15];return(e*o-r*a)*(h*v-f*g)-(e*s-n*a)*(c*v-f*p)+(e*l-i*a)*(c*g-h*p)+(r*s-n*o)*(u*v-f*d)-(r*l-i*o)*(u*g-h*d)+(n*l-i*s)*(u*p-c*d)};var Jf=function(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t};var td=function(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e};var ed=function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t};var rd=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t};var nd=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t};var id=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]};var ad={length:function(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)},normalize:Kf,dot:id,cross:nd},od=ed(),sd=ed(),ld=[0,0,0,0],ud=[[0,0,0],[0,0,0],[0,0,0]],cd=[0,0,0],hd=function(t,e,r,n,i,a){if(e||(e=[0,0,0]),r||(r=[0,0,0]),n||(n=[0,0,0]),i||(i=[0,0,0,1]),a||(a=[0,0,0,1]),!function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;i<16;i++)t[i]=e[i]*n;return!0}(od,t))return!1;if(td(sd,od),sd[3]=0,sd[7]=0,sd[11]=0,sd[15]=1,Math.abs($f(sd)<1e-8))return!1;var o,s,l,u,c,h,f,d=od[3],p=od[7],g=od[11],v=od[12],m=od[13],y=od[14],b=od[15];if(0!==d||0!==p||0!==g){if(ld[0]=d,ld[1]=p,ld[2]=g,ld[3]=b,!Hf(sd,sd))return!1;rd(sd,sd),o=i,l=sd,u=(s=ld)[0],c=s[1],h=s[2],f=s[3],o[0]=l[0]*u+l[4]*c+l[8]*h+l[12]*f,o[1]=l[1]*u+l[5]*c+l[9]*h+l[13]*f,o[2]=l[2]*u+l[6]*c+l[10]*h+l[14]*f,o[3]=l[3]*u+l[7]*c+l[11]*h+l[15]*f}else i[0]=i[1]=i[2]=0,i[3]=1;if(e[0]=v,e[1]=m,e[2]=y,function(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}(ud,od),r[0]=ad.length(ud[0]),ad.normalize(ud[0],ud[0]),n[0]=ad.dot(ud[0],ud[1]),fd(ud[1],ud[1],ud[0],1,-n[0]),r[1]=ad.length(ud[1]),ad.normalize(ud[1],ud[1]),n[0]/=r[1],n[1]=ad.dot(ud[0],ud[2]),fd(ud[2],ud[2],ud[0],1,-n[1]),n[2]=ad.dot(ud[1],ud[2]),fd(ud[2],ud[2],ud[1],1,-n[2]),r[2]=ad.length(ud[2]),ad.normalize(ud[2],ud[2]),n[1]/=r[2],n[2]/=r[2],ad.cross(cd,ud[1],ud[2]),ad.dot(ud[0],cd)<0)for(var x=0;x<3;x++)r[x]*=-1,ud[x][0]*=-1,ud[x][1]*=-1,ud[x][2]*=-1;return a[0]=.5*Math.sqrt(Math.max(1+ud[0][0]-ud[1][1]-ud[2][2],0)),a[1]=.5*Math.sqrt(Math.max(1-ud[0][0]+ud[1][1]-ud[2][2],0)),a[2]=.5*Math.sqrt(Math.max(1-ud[0][0]-ud[1][1]+ud[2][2],0)),a[3]=.5*Math.sqrt(Math.max(1+ud[0][0]+ud[1][1]+ud[2][2],0)),ud[2][1]>ud[1][2]&&(a[0]=-a[0]),ud[0][2]>ud[2][0]&&(a[1]=-a[1]),ud[1][0]>ud[0][1]&&(a[2]=-a[2]),!0};function fd(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var dd=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],d=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*h+w*g,t[1]=b*i+x*l+_*f+w*v,t[2]=b*a+x*u+_*d+w*m,t[3]=b*o+x*c+_*p+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*h+w*g,t[5]=b*i+x*l+_*f+w*v,t[6]=b*a+x*u+_*d+w*m,t[7]=b*o+x*c+_*p+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*h+w*g,t[9]=b*i+x*l+_*f+w*v,t[10]=b*a+x*u+_*d+w*m,t[11]=b*o+x*c+_*p+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*h+w*g,t[13]=b*i+x*l+_*f+w*v,t[14]=b*a+x*u+_*d+w*m,t[15]=b*o+x*c+_*p+w*y,t};var pd={identity:qf,translate:Qf,multiply:dd,create:ed,scale:Zf,fromRotationTranslation:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,h=n*l,f=n*u,d=i*l,p=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(d+g),t[1]=h+y,t[2]=f-m,t[3]=0,t[4]=h-y,t[5]=1-(c+g),t[6]=p+v,t[7]=0,t[8]=f+m,t[9]=p-v,t[10]=1-(c+d),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}},gd=(pd.create(),pd.create()),vd=function(t,e,r,n,i,a){return pd.identity(t),pd.fromRotationTranslation(t,a,e),t[3]=i[0],t[7]=i[1],t[11]=i[2],t[15]=i[3],pd.identity(gd),0!==n[2]&&(gd[9]=n[2],pd.multiply(t,t,gd)),0!==n[1]&&(gd[9]=0,gd[8]=n[1],pd.multiply(t,t,gd)),0!==n[0]&&(gd[8]=0,gd[4]=n[0],pd.multiply(t,t,gd)),pd.scale(t,t,r),t};var md=function(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],h=e[2],f=e[3],d=r[0],p=r[1],g=r[2],v=r[3];(a=u*d+c*p+h*g+f*v)<0&&(a=-a,d=-d,p=-p,g=-g,v=-v);1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n);return t[0]=s*u+l*d,t[1]=s*c+l*p,t[2]=s*h+l*g,t[3]=s*f+l*v,t},yd=wd(),bd=wd(),xd=wd(),_d=function(t,e,r,n){if(0===$f(e)||0===$f(r))return!1;var i=hd(e,yd.translate,yd.scale,yd.skew,yd.perspective,yd.quaternion),a=hd(r,bd.translate,bd.scale,bd.skew,bd.perspective,bd.quaternion);return!(!i||!a||(Jf(xd.translate,yd.translate,bd.translate,n),Jf(xd.skew,yd.skew,bd.skew,n),Jf(xd.scale,yd.scale,bd.scale,n),Jf(xd.perspective,yd.perspective,bd.perspective,n),md(xd.quaternion,yd.quaternion,bd.quaternion,n),vd(t,xd.translate,xd.scale,xd.skew,xd.perspective,xd.quaternion),0))};function wd(){return{translate:Md(),scale:Md(1),skew:Md(),perspective:[0,0,0,1],quaternion:[0,0,0,1]}}function Md(t){return[t||0,t||0,t||0]}var Ad=[0,0,0],Td=function(t){return new kd((t=t||{}).matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])};function kd(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-1/0,1/0]}var Ed=kd.prototype;Ed.recalcMatrix=function(t){var e=this._time,r=Vf.le(e,t),n=this.computedMatrix;if(!(r<0)){var i=this._components;if(r===e.length-1)for(var a=16*r,o=0;o<16;++o)n[o]=i[a++];else{var s=e[r+1]-e[r],l=(a=16*r,this.prevMatrix),u=!0;for(o=0;o<16;++o)l[o]=i[a++];var c=this.nextMatrix;for(o=0;o<16;++o)c[o]=i[a++],u=u&&l[o]===c[o];if(s<1e-6||u)for(o=0;o<16;++o)n[o]=l[o];else _d(n,l,c,(t-e[r])/s)}var h=this.computedUp;h[0]=n[1],h[1]=n[5],h[2]=n[9],Kf(h,h);var f=this.computedInverse;Hf(f,n);var d=this.computedEye,p=f[15];d[0]=f[12]/p,d[1]=f[13]/p,d[2]=f[14]/p;var g=this.computedCenter,v=Math.exp(this.computedRadius[0]);for(o=0;o<3;++o)g[o]=d[o]-n[2+4*o]*v}},Ed.idle=function(t){if(!(t=0;--d)a[d]=u*t[d]+c*e[d]+h*r[d]+f*n[d];return a}return u*t+c*e+h*r+f*n}).derivative=function(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n};var Sd=function(t,e,r){switch(arguments.length){case 0:return new Rd([0],[0],0);case 1:if("number"==typeof t){var n=Id(t);return new Rd(n,n,0)}return new Rd(t,Id(t.length),0);case 2:if("number"==typeof e){var n=Id(t.length);return new Rd(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new Rd(t,e,r)}};function Pd(t,e,r){return Math.min(e,Math.max(t,r))}function Rd(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n=r-1){u=a.length-1;var h=t-e[r-1];for(c=0;c=r-1)for(var l=a.length-1,u=(e[r-1],0);u=0;--r)if(t[--e])return!1;return!0},Od.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(t0;--c)n.push(Pd(s[c-1],l[c-1],arguments[c])),i.push(0)}},Od.push=function(t){var e=this.lastT(),r=this.dimension;if(!(t1e-6?1/o:0;this._time.push(t);for(var h=r;h>0;--h){var f=Pd(l[h-1],u[h-1],arguments[h]);n.push(f),i.push((f-n[a++])*c)}}},Od.set=function(t){var e=this.dimension;if(!(t0;--s)r.push(Pd(a[s-1],o[s-1],arguments[s])),n.push(0)}},Od.move=function(t){var e=this.lastT(),r=this.dimension;if(!(t<=e||arguments.length!==r+1)){var n=this._state,i=this._velocity,a=n.length-this.dimension,o=this.bounds,s=o[0],l=o[1],u=t-e,c=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var f=arguments[h];n.push(Pd(s[h-1],l[h-1],n[a++]+f)),i.push(f*c)}}},Od.idle=function(t){var e=this.lastT();if(!(t=0;--c)n.push(Pd(s[c],l[c],n[a]+u*i[a])),i.push(0),a+=1}};var Nd=function(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(h>0){var h=Math.sqrt(c+1);t[0]=.5*(o-l)/h,t[1]=.5*(s-n)/h,t[2]=.5*(r-a)/h,t[3]=.5*h}else{var f=Math.max(e,a,u),h=Math.sqrt(2*f-c+1);e>=f?(t[0]=.5*h,t[1]=.5*(i+r)/h,t[2]=.5*(s+n)/h,t[3]=.5*(o-l)/h):a>=f?(t[0]=.5*(r+i)/h,t[1]=.5*h,t[2]=.5*(l+o)/h,t[3]=.5*(s-n)/h):(t[0]=.5*(n+s)/h,t[1]=.5*(o+l)/h,t[2]=.5*h,t[3]=.5*(r-i)/h)}return t};var Dd=function(t){var e=(t=t||{}).center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),jd(r=[].slice.call(r,0,4),r);var i=new Bd(r,e,Math.log(n));i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up);return i};function zd(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function Fd(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function jd(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=Fd(r,n,i,a);o>1e-6?(t[0]=r/o,t[1]=n/o,t[2]=i/o,t[3]=a/o):(t[0]=t[1]=t[2]=0,t[3]=1)}function Bd(t,e,r){this.radius=Sd([r]),this.center=Sd(e),this.rotation=Sd(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}var Ud=Bd.prototype;Ud.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},Ud.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;jd(e,e);var r=this.computedMatrix;ou(r,e);var n=this.computedCenter,i=this.computedEye,a=this.computedUp,o=Math.exp(this.computedRadius[0]);i[0]=n[0]+o*r[2],i[1]=n[1]+o*r[6],i[2]=n[2]+o*r[10],a[0]=r[1],a[1]=r[5],a[2]=r[9];for(var s=0;s<3;++s){for(var l=0,u=0;u<3;++u)l+=r[s+4*u]*i[u];r[12+s]=-l}},Ud.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r},Ud.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},Ud.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},Ud.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=i[1],o=i[5],s=i[9],l=zd(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,d=zd(u-=a*f,c-=o*f,h-=s*f);u/=d,c/=d,h/=d;var p=i[2],g=i[6],v=i[10],m=p*a+g*o+v*s,y=p*u+g*c+v*h,b=zd(p-=m*a+y*u,g-=m*o+y*c,v-=m*s+y*h);p/=b,g/=b,v/=b;var x=u*e+a*r,_=c*e+o*r,w=h*e+s*r;this.center.move(t,x,_,w);var M=Math.exp(this.computedRadius[0]);M=Math.max(1e-4,M+n),this.radius.set(t,Math.log(M))},Ud.rotate=function(t,e,r,n){this.recalcMatrix(t),e=e||0,r=r||0;var i=this.computedMatrix,a=i[0],o=i[4],s=i[8],l=i[1],u=i[5],c=i[9],h=i[2],f=i[6],d=i[10],p=e*a+r*l,g=e*o+r*u,v=e*s+r*c,m=-(f*v-d*g),y=-(d*p-h*v),b=-(h*g-f*p),x=Math.sqrt(Math.max(0,1-Math.pow(m,2)-Math.pow(y,2)-Math.pow(b,2))),_=Fd(m,y,b,x);_>1e-6?(m/=_,y/=_,b/=_,x/=_):(m=y=b=0,x=1);var w=this.computedRotation,M=w[0],A=w[1],T=w[2],k=w[3],E=M*x+k*m+A*b-T*y,L=A*x+k*y+T*m-M*b,C=T*x+k*b+M*y-A*m,S=k*x-M*m-A*y-T*b;if(n){m=h,y=f,b=d;var P=Math.sin(n)/zd(m,y,b);m*=P,y*=P,b*=P,S=S*(x=Math.cos(e))-(E=E*x+S*m+L*b-C*y)*m-(L=L*x+S*y+C*m-E*b)*y-(C=C*x+S*b+E*y-L*m)*b}var R=Fd(E,L,C,S);R>1e-6?(E/=R,L/=R,C/=R,S/=R):(E=L=C=0,S=1),this.rotation.set(t,E,L,C,S)},Ud.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;Gf(i,e,r,n);var a=this.computedRotation;Nd(a,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),jd(a,a),this.rotation.set(t,a[0],a[1],a[2],a[3]);for(var o=0,s=0;s<3;++s)o+=Math.pow(r[s]-e[s],2);this.radius.set(t,.5*Math.log(Math.max(o,1e-6))),this.center.set(t,r[0],r[1],r[2])},Ud.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},Ud.setMatrix=function(t,e){var r=this.computedRotation;Nd(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),jd(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;Hf(n,e);var i=n[15];if(Math.abs(i)>1e-6){var a=n[12]/i,o=n[13]/i,s=n[14]/i;this.recalcMatrix(t);var l=Math.exp(this.computedRadius[0]);this.center.set(t,a-n[2]*l,o-n[6]*l,s-n[10]*l),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},Ud.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},Ud.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},Ud.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},Ud.toJSON=function(){return this.recalcMatrix(this.lastT()),{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]}},Ud.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)};var Vd=function(t,e,r,n){var i,a,o,s,l,u,c,h,f,d,p,g,v,m,y,b,x,_,w,M,A,T,k,E,L=n[0],C=n[1],S=n[2],P=Math.sqrt(L*L+C*C+S*S);if(Math.abs(P)<1e-6)return null;L*=P=1/P,C*=P,S*=P,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],h=e[4],f=e[5],d=e[6],p=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=C*L*o+S*i,_=S*L*o-C*i,w=L*C*o-S*i,M=C*C*o+a,A=S*C*o+L*i,T=L*S*o+C*i,k=C*S*o-L*i,E=S*S*o+a,t[0]=s*b+h*x+g*_,t[1]=l*b+f*x+v*_,t[2]=u*b+d*x+m*_,t[3]=c*b+p*x+y*_,t[4]=s*w+h*M+g*A,t[5]=l*w+f*M+v*A,t[6]=u*w+d*M+m*A,t[7]=c*w+p*M+y*A,t[8]=s*T+h*k+g*E,t[9]=l*T+f*k+v*E,t[10]=u*T+d*k+m*E,t[11]=c*T+p*k+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t};var Hd=function(t){var e=(t=t||{}).center||[0,0,0],r=t.up||[0,1,0],n=t.right||Xd(r),i=t.radius||1,a=t.theta||0,o=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),Kf(r,r),n=[].slice.call(n,0,3),Kf(n,n),"eye"in t){var s=t.eye,l=[s[0]-e[0],s[1]-e[1],s[2]-e[2]];nd(n,l,r),qd(n[0],n[1],n[2])<1e-6?n=Xd(r):Kf(n,n),i=qd(l[0],l[1],l[2]);var u=id(r,l)/i,c=id(n,l)/i;o=Math.acos(u),a=Math.acos(c)}return i=Math.log(i),new Wd(t.zoomMin,t.zoomMax,e,r,n,i,a,o)};function qd(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function Gd(t){return Math.min(1,Math.max(-1,t))}function Xd(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;s<3;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(s=0;s<3;++s)i[s]-=o/a*t[s];return Kf(i,i),i}function Wd(t,e,r,n,i,a,o,s){this.center=Sd(r),this.up=Sd(n),this.right=Sd(i),this.radius=Sd([a]),this.angle=Sd([o,s]),this.angle.bounds=[[-1/0,-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var l=0;l<16;++l)this.computedMatrix[l]=.5;this.recalcMatrix(0)}var Yd=Wd.prototype;Yd.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},Yd.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},Yd.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,n=0,i=0,a=0;a<3;++a)i+=e[a]*r[a],n+=e[a]*e[a];var o=Math.sqrt(n),s=0;for(a=0;a<3;++a)r[a]-=e[a]*i/n,s+=r[a]*r[a],e[a]/=o;var l=Math.sqrt(s);for(a=0;a<3;++a)r[a]/=l;var u=this.computedToward;nd(u,e,r),Kf(u,u);var c=Math.exp(this.computedRadius[0]),h=this.computedAngle[0],f=this.computedAngle[1],d=Math.cos(h),p=Math.sin(h),g=Math.cos(f),v=Math.sin(f),m=this.computedCenter,y=d*g,b=p*g,x=v,_=-d*v,w=-p*v,M=g,A=this.computedEye,T=this.computedMatrix;for(a=0;a<3;++a){var k=y*r[a]+b*u[a]+x*e[a];T[4*a+1]=_*r[a]+w*u[a]+M*e[a],T[4*a+2]=k,T[4*a+3]=0}var E=T[1],L=T[5],C=T[9],S=T[2],P=T[6],R=T[10],O=L*R-C*P,I=C*S-E*R,N=E*P-L*S,D=qd(O,I,N);O/=D,I/=D,N/=D,T[0]=O,T[4]=I,T[8]=N;for(a=0;a<3;++a)A[a]=m[a]+T[2+4*a]*c;for(a=0;a<3;++a){s=0;for(var z=0;z<3;++z)s+=T[a+4*z]*A[z];T[12+a]=-s}T[15]=1},Yd.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r};var Zd=[0,0,0];Yd.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;Zd[0]=i[2],Zd[1]=i[6],Zd[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;l<3;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];Vd(i,i,n,Zd);for(l=0;l<3;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},Yd.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=(Math.exp(this.computedRadius[0]),i[1]),o=i[5],s=i[9],l=qd(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,d=qd(u-=a*f,c-=o*f,h-=s*f),p=(u/=d)*e+a*r,g=(c/=d)*e+o*r,v=(h/=d)*e+s*r;this.center.move(t,p,g,v);var m=Math.exp(this.computedRadius[0]);m=Math.max(1e-4,m+n),this.radius.set(t,Math.log(m))},Yd.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},Yd.setMatrix=function(t,e,r,n){var i=1;"number"==typeof r&&(i=0|r),(i<0||i>3)&&(i=1);var a=(i+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var o=e[i],s=e[i+4],l=e[i+8];if(n){var u=Math.abs(o),c=Math.abs(s),h=Math.abs(l),f=Math.max(u,c,h);u===f?(o=o<0?-1:1,s=l=0):h===f?(l=l<0?-1:1,o=s=0):(s=s<0?-1:1,o=l=0)}else{var d=qd(o,s,l);o/=d,s/=d,l/=d}var p,g,v=e[a],m=e[a+4],y=e[a+8],b=v*o+m*s+y*l,x=qd(v-=o*b,m-=s*b,y-=l*b),_=s*(y/=x)-l*(m/=x),w=l*(v/=x)-o*y,M=o*m-s*v,A=qd(_,w,M);if(_/=A,w/=A,M/=A,this.center.jump(t,U,V,H),this.radius.idle(t),this.up.jump(t,o,s,l),this.right.jump(t,v,m,y),2===i){var T=e[1],k=e[5],E=e[9],L=T*v+k*m+E*y,C=T*_+k*w+E*M;p=O<0?-Math.PI/2:Math.PI/2,g=Math.atan2(C,L)}else{var S=e[2],P=e[6],R=e[10],O=S*o+P*s+R*l,I=S*v+P*m+R*y,N=S*_+P*w+R*M;p=Math.asin(Gd(O)),g=Math.atan2(N,I)}this.angle.jump(t,g,p),this.recalcMatrix(t);var D=e[2],z=e[6],F=e[10],j=this.computedMatrix;Hf(j,e);var B=j[15],U=j[12]/B,V=j[13]/B,H=j[14]/B,q=Math.exp(this.computedRadius[0]);this.center.jump(t,U-D*q,V-z*q,H-F*q)},Yd.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},Yd.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},Yd.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},Yd.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},Yd.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter;var i=(n=n||this.computedUp)[0],a=n[1],o=n[2],s=qd(i,a,o);if(!(s<1e-6)){i/=s,a/=s,o/=s;var l=e[0]-r[0],u=e[1]-r[1],c=e[2]-r[2],h=qd(l,u,c);if(!(h<1e-6)){l/=h,u/=h,c/=h;var f=this.computedRight,d=f[0],p=f[1],g=f[2],v=i*d+a*p+o*g,m=qd(d-=v*i,p-=v*a,g-=v*o);if(!(m<.01&&(m=qd(d=a*c-o*u,p=o*l-i*c,g=i*u-a*l))<1e-6)){d/=m,p/=m,g/=m,this.up.set(t,i,a,o),this.right.set(t,d,p,g),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(h));var y=a*g-o*p,b=o*d-i*g,x=i*p-a*d,_=qd(y,b,x),w=i*l+a*u+o*c,M=d*l+p*u+g*c,A=(y/=_)*l+(b/=_)*u+(x/=_)*c,T=Math.asin(Gd(w)),k=Math.atan2(A,M),E=this.angle._state,L=E[E.length-1],C=E[E.length-2];L%=2*Math.PI;var S=Math.abs(L+2*Math.PI-k),P=Math.abs(L-k),R=Math.abs(L-2*Math.PI-k);S0)return 1<=0)return 1<Math.abs(e))n.rotate(s,0,0,-t*i*Math.PI*l.rotateSpeed/window.innerWidth);else{var u=l.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,a*(Math.exp(u)-1))}},!0),l};var cp=function(t,e,r){return 0===t.length?t:e?(r||t.sort(e),function(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;o0,l=[],u=[],c=0,h=0;for(n=0;n0&&l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"0&&l.push(["index[",h,"]-=s",h].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function fp(t,e,r){for(var n=t.body,i=[],a=[],o=0;o0&&g.push("shape=SS.slice(0)"),t.indexArgs.length>0){var v=new Array(r);for(a=0;a0&&p.push("var "+g.join(",")),a=0;a3&&p.push(fp(t.pre,t,i));var x=fp(t.body,t,i),_=function(t){for(var e=0,r=t[0].length;e0,l=[],u=0;u0;){"].join("")),l.push(["if(j",u,"<",o,"){"].join("")),l.push(["s",e[u],"=j",u].join("")),l.push(["j",u,"=0"].join("")),l.push(["}else{s",e[u],"=",o].join("")),l.push(["j",u,"-=",o,"}"].join("")),s&&l.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&p.push(fp(t.post,t,i)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+p.join("\n")+"\n----------");var w=[t.funcName||"unnamed","_cwise_loop_",n[0].join("s"),"m",_,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(i)].join("");return new Function(["function ",w,"(",d.join(","),"){",p.join("\n"),"} return ",w].join(""))()};var pp=function(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var i=[],a=[],o=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],s=[],l=[],u=0;u0&&(s.push("array"+t.arrayArgs[0]+".shape.length===array"+c+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),l.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+c+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u0)throw new Error("cwise: pre() block may not reference array args");if(n0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===i)e.scalarArgs.push(n),e.shimArgs.push("scalar"+n);else if("index"===i){if(e.indexArgs.push(n),n0)throw new Error("cwise: pre() block may not reference array index");if(n0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===i){if(e.shapeArgs.push(n),nr.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,pp(e)},vp={},mp={body:"",args:[],thisVars:[],localVars:[]};function yp(t){if(!t)return mp;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in xp){var e=xp[t];vp[t]=bp({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),vp[t+"eq"]=bp({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),vp[t+"s"]=bp({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),vp[t+"seq"]=bp({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var _p={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in _p){var e=_p[t];vp[t]=bp({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),vp[t+"eq"]=bp({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var wp={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in wp){var e=wp[t];vp[t]=bp({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),vp[t+"s"]=bp({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),vp[t+"eq"]=bp({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),vp[t+"seq"]=bp({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var Mp=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_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"}),vp.norm1=gp({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,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"}),vp.sup=gp({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:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),vp.inf=gp({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:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),vp.random=bp({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),vp.assign=bp({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),vp.assigns=bp({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),vp.equals=gp({args:["array","array"],pre:mp,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"});var kp=function(t){for(var e=new Array(t),r=0;rMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&i.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):i.push("ORDER})")),i.push("proto.set=function "+r+"_set("+o.join(",")+",v){"),n?i.push("return this.data.set("+s+",v)}"):i.push("return this.data["+s+"]=v}"),i.push("proto.get=function "+r+"_get("+o.join(",")+"){"),n?i.push("return this.data.get("+s+")}"):i.push("return this.data["+s+"]}"),i.push("proto.index=function "+r+"_index(",o.join(),"){return "+s+"}"),i.push("proto.hi=function "+r+"_hi("+o.join(",")+"){return new "+r+"(this.data,"+a.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+a.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var c=a.map(function(t){return"a"+t+"=this.shape["+t+"]"}),h=a.map(function(t){return"c"+t+"=this.stride["+t+"]"});i.push("proto.lo=function "+r+"_lo("+o.join(",")+"){var b=this.offset,d=0,"+c.join(",")+","+h.join(","));for(var f=0;f=0){d=i"+f+"|0;b+=c"+f+"*d;a"+f+"-=d}");i.push("return new "+r+"(this.data,"+a.map(function(t){return"a"+t}).join(",")+","+a.map(function(t){return"c"+t}).join(",")+",b)}"),i.push("proto.step=function "+r+"_step("+o.join(",")+"){var "+a.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+a.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(f=0;f=0){c=(c+this.stride["+f+"]*i"+f+")|0}else{a.push(this.shape["+f+"]);b.push(this.stride["+f+"])}");return i.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),i.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+a.map(function(t){return"shape["+t+"]"}).join(",")+","+a.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",i.join("\n"))(Op[t],Pp)}var Op={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};var Ip=function(t,e,r,n){if(void 0===t)return(0,Op.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var i=e.length;if(void 0===r){r=new Array(i);for(var a=i-1,o=1;a>=0;--a)r[a]=o,o*=e[a]}if(void 0===n)for(n=0,a=0;a0)-(t<0)},Np.abs=function(t){var e=t>>31;return(t^e)-e},Np.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Np.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Np.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Np.countTrailingZeros=Dp,Np.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Np.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Np.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var zp=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|zp[t>>>16&255]<<8|zp[t>>>24&255]},Np.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Np.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Np.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Np.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Np.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Dp(t)+1};for(var Fp={byteLength:function(t){return 3*t.length/4-Gp(t)},toByteArray:function(t){var e,r,n,i,a,o=t.length;i=Gp(t),a=new Up(3*o/4-i),r=i>0?o-4:o;var s=0;for(e=0;e>16&255,a[s++]=n>>8&255,a[s++]=255&n;2===i?(n=Bp[t.charCodeAt(e)]<<2|Bp[t.charCodeAt(e+1)]>>4,a[s++]=255&n):1===i&&(n=Bp[t.charCodeAt(e)]<<10|Bp[t.charCodeAt(e+1)]<<4|Bp[t.charCodeAt(e+2)]>>2,a[s++]=n>>8&255,a[s++]=255&n);return a},fromByteArray:function(t){for(var e,r=t.length,n=r%3,i="",a=[],o=0,s=r-n;os?s:o+16383));1===n?(e=t[r-1],i+=jp[e>>2],i+=jp[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=jp[e>>10],i+=jp[e>>4&63],i+=jp[e<<2&63],i+="=");return a.push(i),a.join("")}},jp=[],Bp=[],Up="undefined"!=typeof Uint8Array?Uint8Array:Array,Vp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Hp=0,qp=Vp.length;Hp0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function Xp(t,e,r){for(var n,i,a=[],o=e;o>18&63]+jp[i>>12&63]+jp[i>>6&63]+jp[63&i]);return a.join("")}Bp["-".charCodeAt(0)]=62,Bp["_".charCodeAt(0)]=63;var Wp={read:function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,f=r?-1:1,d=t[e+h];for(h+=f,a=d&(1<<-c)-1,d>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),a-=u}return(d?-1:1)*o*Math.pow(2,a-n)},write:function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:a-1,p=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&s,d+=p,s/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*g}},Yp={};Yp.Buffer=Kp,Yp.SlowBuffer=function(t){+t!=t&&(t=0);return Kp.alloc(+t)},Yp.INSPECT_MAX_BYTES=50;var Zp=2147483647;function Qp(t){if(t>Zp)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=Kp.prototype,e}function Kp(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return tg(t)}return $p(t,e,r)}function $p(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return Sg(t)||t&&Sg(t.buffer)?function(t,e,r){if(e<0||t.byteLength=Zp)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Zp.toString(16)+" bytes");return 0|t}function ng(t,e){if(Kp.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Sg(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Eg(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Lg(t).length;default:if(n)return Eg(t).length;e=(""+e).toLowerCase(),n=!0}}function ig(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function ag(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Pg(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=Kp.from(e,n)),Kp.isBuffer(e))return 0===e.length?-1:og(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):og(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function og(t,e,r,n,i){var a,o=1,s=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,s/=2,l/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var c=-1;for(a=r;as&&(r=s-l),a=r;a>=0;a--){for(var h=!0,f=0;fi&&(n=i):n=i;var a=e.length;n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(e,t.length-r),t,r,n)}function dg(t,e,r){return 0===e&&r===t.length?Fp.fromByteArray(t):Fp.fromByteArray(t.slice(e,r))}function pg(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(c=u);break;case 2:128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)>127&&(c=l);break;case 3:a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&(l=(15&u)<<12|(63&a)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(c=l)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=h}return function(t){var e=t.length;if(e<=gg)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return yg(this,e,r);case"utf8":case"utf-8":return pg(this,e,r);case"ascii":return vg(this,e,r);case"latin1":case"binary":return mg(this,e,r);case"base64":return dg(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return bg(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},Kp.prototype.toLocaleString=Kp.prototype.toString,Kp.prototype.equals=function(t){if(!Kp.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Kp.compare(this,t)},Kp.prototype.inspect=function(){var t="",e=Yp.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},Kp.prototype.compare=function(t,e,r,n,i){if(!Kp.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,o=r-e,s=Math.min(a,o),l=this.slice(n,i),u=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return sg(this,t,e,r);case"utf8":case"utf-8":return lg(this,t,e,r);case"ascii":return ug(this,t,e,r);case"latin1":case"binary":return cg(this,t,e,r);case"base64":return hg(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return fg(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Kp.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var gg=4096;function vg(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",a=e;ar)throw new RangeError("Trying to access beyond buffer length")}function _g(t,e,r,n,i,a){if(!Kp.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function wg(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Mg(t,e,r,n,i){return e=+e,r>>>=0,i||wg(t,0,r,4),Wp.write(t,e,r,n,23,4),r+4}function Ag(t,e,r,n,i){return e=+e,r>>>=0,i||wg(t,0,r,8),Wp.write(t,e,r,n,52,8),r+8}Kp.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||xg(t,e,this.length);for(var n=this[t],i=1,a=0;++a>>=0,e>>>=0,r||xg(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},Kp.prototype.readUInt8=function(t,e){return t>>>=0,e||xg(t,1,this.length),this[t]},Kp.prototype.readUInt16LE=function(t,e){return t>>>=0,e||xg(t,2,this.length),this[t]|this[t+1]<<8},Kp.prototype.readUInt16BE=function(t,e){return t>>>=0,e||xg(t,2,this.length),this[t]<<8|this[t+1]},Kp.prototype.readUInt32LE=function(t,e){return t>>>=0,e||xg(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Kp.prototype.readUInt32BE=function(t,e){return t>>>=0,e||xg(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Kp.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||xg(t,e,this.length);for(var n=this[t],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*e)),n},Kp.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||xg(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*e)),a},Kp.prototype.readInt8=function(t,e){return t>>>=0,e||xg(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Kp.prototype.readInt16LE=function(t,e){t>>>=0,e||xg(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Kp.prototype.readInt16BE=function(t,e){t>>>=0,e||xg(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Kp.prototype.readInt32LE=function(t,e){return t>>>=0,e||xg(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Kp.prototype.readInt32BE=function(t,e){return t>>>=0,e||xg(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Kp.prototype.readFloatLE=function(t,e){return t>>>=0,e||xg(t,4,this.length),Wp.read(this,t,!0,23,4)},Kp.prototype.readFloatBE=function(t,e){return t>>>=0,e||xg(t,4,this.length),Wp.read(this,t,!1,23,4)},Kp.prototype.readDoubleLE=function(t,e){return t>>>=0,e||xg(t,8,this.length),Wp.read(this,t,!0,52,8)},Kp.prototype.readDoubleBE=function(t,e){return t>>>=0,e||xg(t,8,this.length),Wp.read(this,t,!1,52,8)},Kp.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||_g(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,n)||_g(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},Kp.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,1,255,0),this[e]=255&t,e+1},Kp.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},Kp.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},Kp.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},Kp.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Kp.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);_g(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},Kp.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);_g(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},Kp.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},Kp.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},Kp.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},Kp.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},Kp.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||_g(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Kp.prototype.writeFloatLE=function(t,e,r){return Mg(this,t,e,!0,r)},Kp.prototype.writeFloatBE=function(t,e,r){return Mg(this,t,e,!1,r)},Kp.prototype.writeDoubleLE=function(t,e,r){return Ag(this,t,e,!0,r)},Kp.prototype.writeDoubleBE=function(t,e,r){return Ag(this,t,e,!1,r)},Kp.prototype.copy=function(t,e,r,n){if(!Kp.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},Kp.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Kp.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function Lg(t){return Fp.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(Tg,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Cg(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Sg(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function Pg(t){return t!=t}var Rg=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n0?r.pop():new ArrayBuffer(t)}function l(t){return new Uint8Array(s(t),0,t)}function u(t){return new Uint16Array(s(2*t),0,t)}function c(t){return new Uint32Array(s(4*t),0,t)}function h(t){return new Int8Array(s(t),0,t)}function f(t){return new Int16Array(s(2*t),0,t)}function d(t){return new Int32Array(s(4*t),0,t)}function p(t){return new Float32Array(s(4*t),0,t)}function g(t){return new Float64Array(s(8*t),0,t)}function v(t){return r?new Uint8ClampedArray(s(t),0,t):l(t)}function m(t){return new DataView(s(t),0,t)}function y(t){t=Np.nextPow2(t);var r=Np.log2(t),n=a[r];return n.length>0?n.pop():new e(t)}Og.free=function(t){if(e.isBuffer(t))a[Np.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var r=t.length||t.byteLength,n=0|Np.log2(r);i[n].push(t)}},Og.freeUint8=Og.freeUint16=Og.freeUint32=Og.freeInt8=Og.freeInt16=Og.freeInt32=Og.freeFloat32=Og.freeFloat=Og.freeFloat64=Og.freeDouble=Og.freeUint8Clamped=Og.freeDataView=function(t){o(t.buffer)},Og.freeArrayBuffer=o,Og.freeBuffer=function(t){a[Np.log2(t.length)].push(t)},Og.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return s(t);switch(e){case"uint8":return l(t);case"uint16":return u(t);case"uint32":return c(t);case"int8":return h(t);case"int16":return f(t);case"int32":return d(t);case"float":case"float32":return p(t);case"double":case"float64":return g(t);case"uint8_clamped":return v(t);case"buffer":return y(t);case"data":case"dataview":return m(t);default:return null}return null},Og.mallocArrayBuffer=s,Og.mallocUint8=l,Og.mallocUint16=u,Og.mallocUint32=c,Og.mallocInt8=h,Og.mallocInt16=f,Og.mallocInt32=d,Og.mallocFloat32=Og.mallocFloat=p,Og.mallocFloat64=Og.mallocDouble=g,Og.mallocUint8Clamped=v,Og.mallocDataView=m,Og.mallocBuffer=y,Og.clearCache=function(){for(var t=0;t<32;++t)n.UINT8[t].length=0,n.UINT16[t].length=0,n.UINT32[t].length=0,n.INT8[t].length=0,n.INT16[t].length=0,n.INT32[t].length=0,n.FLOAT[t].length=0,n.DOUBLE[t].length=0,n.UINT8C[t].length=0,i[t].length=0,a[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Yp.Buffer);var Ig=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function Ng(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}var Dg=Ng.prototype;function zg(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(a<0)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function Fg(t,e){for(var r=Og.malloc(t.length,e),n=t.length,i=0;i=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=zg(this.gl,this.type,this.length,this.usage,t.data,e):this.length=zg(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var n=Og.malloc(t.size,r),i=Ip(n,t.shape);vp.assign(i,t),this.length=zg(this.gl,this.type,this.length,this.usage,e<0?n:n.subarray(0,t.size),e),Og.free(n)}}else if(Array.isArray(t)){var a;a=this.type===this.gl.ELEMENT_ARRAY_BUFFER?Fg(t,"uint16"):Fg(t,"float32"),this.length=zg(this.gl,this.type,this.length,this.usage,e<0?a:a.subarray(0,t.length),e),Og.free(a)}else if("object"==typeof t&&"number"==typeof t.length)this.length=zg(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}};var jg=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var i=new Ng(t,r,t.createBuffer(),0,n);return i.update(e),i};var Bg=function(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i=0?e[a]:i})},has___:{value:y(function(e){var n=m(e);return n?r in n:t.indexOf(e)>=0})},set___:{value:y(function(n,i){var a,o=m(n);return o?o[r]=i:(a=t.indexOf(n))>=0?e[a]=i:(a=t.length,e[a]=i,t[a]=n),this})},delete___:{value:y(function(n){var i,a,o=m(n);return o?r in o&&delete o[r]:!((i=t.indexOf(n))<0||(a=t.length-1,t[i]=void 0,e[i]=e[a],t[i]=t[a],t.length=a,e.length=a,0))})}})};p.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},delete:{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof e?function(){function r(){this instanceof p||b();var r,n=new e,i=void 0,a=!1;return r=t?function(t,e){return n.set(t,e),n.has(t)||(i||(i=new p),i.set(t,e)),this}:function(t,e){if(a)try{n.set(t,e)}catch(r){i||(i=new p),i.set___(t,e)}else n.set(t,e);return this},Object.create(p.prototype,{get___:{value:y(function(t,e){return i?n.has(t)?n.get(t):i.get___(t,e):n.get(t,e)})},has___:{value:y(function(t){return n.has(t)||!!i&&i.has___(t)})},set___:{value:y(r)},delete___:{value:y(function(t){var e=!!n.delete(t);return i&&i.delete___(t)||e})},permitHostObjects___:{value:y(function(t){if(t!==g)throw new Error("bogus call to permitHostObjects___");a=!0})}})}t&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=p.prototype,Wg=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),Wg=p)}function g(t){t.permitHostObjects___&&t.permitHostObjects___(g)}function v(t){return!(t.substr(0,s.length)==s&&"___"===t.substr(t.length-3))}function m(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[l];if(e&&e.key===t)return e;if(o(t)){e={key:t};try{return a(t,l,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(t){return}}}function y(t){return t.prototype=null,Object.freeze(t)}function b(){f||"undefined"==typeof console||(f=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}}();var Yg=new("undefined"==typeof WeakMap?Wg:WeakMap);var Zg=function(t){var e=Yg.get(t),r=e&&(e._triangleBuffer.handle||e._triangleBuffer.buffer);if(!r||!t.isBuffer(r)){var n=jg(t,new Float32Array([-1,-1,-1,4,4,-1]));(e=Xg(t,[{buffer:n,type:t.FLOAT,size:2}]))._triangleBuffer=n,Yg.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()};function Qg(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}Qg.prototype=new Error,Qg.prototype.name="GLError",Qg.prototype.constructor=Qg;var Kg=Qg,$g=function(t,e,r,n){for(var i={},a=0,o=r.length;a=0){var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new Kg("","Invalid data type for attribute "+l+": "+u);ev(t,e,c[0],n,h,i,l)}else{if(!(u.indexOf("mat")>=0))throw new Kg("","Unknown data type for attribute "+l+": "+u);var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new Kg("","Invalid data type for attribute "+l+": "+u);rv(t,e,c,n,h,i,l)}}}return i};function Jg(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}var tv=Jg.prototype;function ev(t,e,r,n,i,a,o){for(var s=["gl","v"],l=[],u=0;u1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;u4)throw new Kg("","Invalid uniform dimension type for matrix "+Io+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new Kg("","Unknown uniform data type for "+Io+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(i<2||i>4)throw new Kg("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new Kg("","Unrecognized data type for vector "+Io+": "+r)}}}function a(e){for(var a=["return function updateProperty(obj){"],o=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var i in r){var a=r[i],o=e;parseInt(i)+""===i?o+="["+i+"]":o+="."+i,"object"==typeof a?n.push.apply(n,t(o,a)):n.push([o,a])}return n}("",e),s=0;s4)throw new Kg("","Invalid data type");return"b"===t.charAt(0)?ov(r,!1):ov(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new Kg("","Invalid uniform dimension type for matrix "+Io+": "+t);return ov(r*r,0)}throw new Kg("","Unknown uniform data type for "+Io+": "+t)}}(r[l].type);var c}function s(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1)for(var s=0;s=r)return fv.substr(0,r);for(;r>fv.length&&e>1;)1&e&&(fv+=t),e>>=1,t+=t;return fv=(fv+=t).substr(0,r)};var pv=function(t,e,r){return dv(r=void 0!==r?r+"":" ",e)+t},gv=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),i=String(n.length+e-1).length;return n.map(function(t,n){var a=n+e,o=String(a).length,s=pv(a,i-o);return s+r+t}).join("\n")};var vv={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},mv=function(t){return vv[t]},yv=function(t){return atob(t)},bv=["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"],xv=(bv=bv.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)})).concat(["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","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"]),_v=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","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","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"],wv=_v.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),Mv=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],Av=function(t){var e,r,n,i=0,a=0,o=Tv,s=[],l=[],u=1,c=0,h=0,f=!1,d=!1,p="",g=bv,v=_v;"300 es"===(t=t||{}).version&&(g=xv,v=wv);return function(t){return l=[],null!==t?function(t){var r;i=0,n=(p+=t).length;for(;e=p[i],i0)continue;r=t.slice(0,1).join("")}return m(r),h+=r.length,(s=s.slice(r.length)).length}}function A(){return/[^a-fA-F0-9]/.test(e)?(m(s.join("")),o=Tv,i):(s.push(e),r=e,i+1)}function T(){return"."===e?(s.push(e),o=Rv,r=e,i+1):/[eE]/.test(e)?(s.push(e),o=Rv,r=e,i+1):"x"===e&&1===s.length&&"0"===s[0]?(o=Fv,s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=Tv,i):(s.push(e),r=e,i+1)}function k(){return"f"===e&&(s.push(e),r=e,i+=1),/[eE]/.test(e)?(s.push(e),r=e,i+1):"-"===e&&/[eE]/.test(r)?(s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=Tv,i):(s.push(e),r=e,i+1)}function E(){if(/[^\d\w_]/.test(e)){var t=s.join("");return o=v.indexOf(t)>-1?Nv:g.indexOf(t)>-1?Iv:Ov,m(s.join("")),o=Tv,i}return s.push(e),r=e,i+1}},Tv=999,kv=9999,Ev=0,Lv=1,Cv=2,Sv=3,Pv=4,Rv=5,Ov=6,Iv=7,Nv=8,Dv=9,zv=10,Fv=11,jv=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];var Bv=function(t,e){var r=Av(e),n=[];return n=(n=n.concat(r(t))).concat(r(null))};var Uv=function(t){for(var e=Array.isArray(t)?t:Bv(t),r=0;r=0),s[8]){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,s[6]?parseInt(s[6]):0);break;case"e":i=s[7]?parseFloat(i).toExponential(s[7]):parseFloat(i).toExponential();break;case"f":i=s[7]?parseFloat(i).toFixed(s[7]):parseFloat(i);break;case"g":i=s[7]?String(Number(i.toPrecision(s[7]))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=s[7]?i.substring(0,s[7]):i;break;case"t":i=String(!!i),i=s[7]?i.substring(0,s[7]):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=s[7]?i.substring(0,s[7]):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=s[7]?i.substring(0,s[7]):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(s[8])?g+=i:(!t.number.test(s[8])||h&&!s[3]?f="":(f=h?"+":"-",i=i.toString().replace(t.sign,"")),u=s[4]?"0"===s[4]?"0":s[4].charAt(1):" ",c=s[6]-(f+i).length,l=s[6]&&c>0?u.repeat(c):"",g+=s[5]?f+i+l:"0"===u?f+l+i:l+f+i)}return g}(function(e){if(n[e])return n[e];var r,i=e,a=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))a.push(r[0]);else if(null!==(r=t.modulo.exec(i)))a.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var s=[],l=r[2],u=[];if(null===(u=t.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(l=l.substring(u[0].length));)if(null!==(u=t.key_access.exec(l)))s.push(u[1]);else{if(null===(u=t.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}r[2]=s}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a.push(r)}i=i.substring(r[0].length)}return n[e]=a}(r),arguments)}function r(t,r){return e.apply(null,[t].concat(r||[]))}var n=Object.create(null);void 0!==Vv&&(Vv.sprintf=e,Vv.vsprintf=r),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=r)}();var Hv=Vv.sprintf,qv=function(t,e,r){"use strict";var n=Uv(e)||"of unknown name (see npm glsl-shader-name)",i="unknown type";void 0!==r&&(i=r===mv.FRAGMENT_SHADER?"fragment":"vertex");for(var a=Hv("Error compiling %s shader %s:\n",i,n),o=Hv("%s%s",a,t),s=t.split("\n"),l={},u=0;ur)for(t=r;te)for(t=e;t=0){for(var v=0|g.type.charAt(g.type.length-1),m=new Array(v),y=0;y=0;)b+=1;p[h]=b}var x=new Array(r.length);function _(){a.program=Wv.program(o,a._vref,a._fref,d,p);for(var t=0;t 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]),hm=im(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]);am.bg=function(t){return nm(t,cm,hm,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])};var fm=function(t){for(var e=[],r=[],n=0,i=0;i<3;++i)for(var a=(i+1)%3,o=(i+2)%3,s=[0,0,0],l=[0,0,0],u=-1;u<=1;u+=2){r.push(n,n+2,n+1,n+1,n+2,n+3),s[i]=u,l[i]=u;for(var c=-1;c<=1;c+=2){s[a]=c;for(var h=-1;h<=1;h+=2)s[o]=h,e.push(s[0],s[1],s[2],l[0],l[1],l[2]),n+=1}var f=a;a=o,o=f}var d=jg(t,new Float32Array(e)),p=jg(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),g=Xg(t,[{buffer:d,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:d,type:t.FLOAT,size:3,offset:12,stride:24}],p),v=dm(t);return v.attributes.position.location=0,v.attributes.normal.location=1,new pm(t,d,g,v)},dm=am.bg;function pm(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}var gm=pm.prototype;gm.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;s<3;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),this.vao.unbind(),l.disable(l.POLYGON_OFFSET_FILL)}},gm.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()};var vm=function(t,e,r){var n=t*e,i=mm*t,a=i-(i-t),o=t-a,s=mm*e,l=s-(s-e),u=e-l,c=o*u-(n-a*l-o*l-a*u);if(r)return r[0]=c,r[1]=n,r;return[c,n]},mm=+(Math.pow(2,27)+1);var ym=function(t,e,r){var n=t+e,i=n-t,a=e-i,o=t-(n-i);if(r)return r[0]=o+a,r[1]=n,r;return[o+a,n]};var bm=function(t,e){var r=t.length;if(1===r){var n=vm(t[0],e);return n[0]?n:[n[1]]}var i=new Array(2*r),a=[.1,.1],o=[.1,.1],s=0;vm(t[0],e,a),a[0]&&(i[s++]=a[0]);for(var l=1;l=n?(i=h,(l+=1)=n?(i=h,(l+=1)>1;return["sum(",Tm(t.slice(0,e)),",",Tm(t.slice(e)),")"].join("")}function km(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(a<=0)return o;n=i+a}else{if(!(i<0))return o;if(a>=0)return o;n=-(i+a)}var s=3.3306690738754716e-16*n;return o>=s||o<=-s?o:Lm(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],h=e[2]-n[2],f=r[2]-n[2],d=a*u,p=o*l,g=o*s,v=i*u,m=i*l,y=a*s,b=c*(d-p)+h*(g-v)+f*(m-y),x=7.771561172376103e-16*((Math.abs(d)+Math.abs(p))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(h)+(Math.abs(m)+Math.abs(y))*Math.abs(f));return b>x||-b>x?b:Cm(t,e,r,n)}];!function(){for(;Sm.length<=Mm;)Sm.push(Em(Sm.length));for(var t=[],e=["slow"],r=0;r<=Mm;++r)t.push("a"+r),e.push("o"+r);var n=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(r=2;r<=Mm;++r)n.push("case ",r,":return o",r,"(",t.slice(0,r).join(),");");n.push("}var s=new Array(arguments.length);for(var i=0;i1&&(i=1);for(var a=1-i,o=t.length,s=new Array(o),l=0;l0||i>0&&l<0){var u=Im(a,l,o,i);r.push(u),n.push(u.slice())}l<0?n.push(o.slice()):l>0?r.push(o.slice()):(r.push(o.slice()),n.push(o.slice())),i=l}return{positive:r,negative:n}}).positive=function(t,e){for(var r=[],n=Om(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(Im(i,s,a,n)),s>=0&&r.push(a.slice()),n=s}return r},Rm.negative=function(t,e){for(var r=[],n=Om(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(Im(i,s,a,n)),s<=0&&r.push(a.slice()),n=s}return r};var Nm=function(t,e,r,n){dd(Dm,e,t),dd(Dm,r,Dm);for(var i=0,a=0;a<2;++a){jm[2]=n[a][2];for(var o=0;o<2;++o){jm[1]=n[o][1];for(var s=0;s<2;++s)jm[0]=n[s][0],Um(zm[i],jm,Dm),i+=1}}for(var l=-1,a=0;a<8;++a){for(var u=zm[a][3],c=0;c<3;++c)Fm[a][c]=zm[a][c]/u;u<0&&(l<0?l=a:Fm[a][2]p&&(l|=1<p&&(l|=1<Fm[a][1]&&(w=a));for(var M=-1,a=0;a<3;++a){var A=w^1<Fm[T][0]&&(T=A)}}var k=qm;k[0]=k[1]=k[2]=0,k[Np.log2(M^w)]=w&M,k[Np.log2(w^T)]=w&T;var E=7^T;E===l||E===_?(E=7^M,k[Np.log2(T^E)]=E&T):k[Np.log2(M^E)]=E&M;for(var L=Gm,C=l,h=0;h<3;++h)L[h]=C&1<>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function ay(t,e,r,n){return new Function([iy("A","x"+t+"y",e,["y"],n),iy("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}ny.bind=function(t,e,r){this.shader.bind(),this.shader.uniforms.model=t,this.shader.uniforms.view=e,this.shader.uniforms.projection=r,Jm[0]=this.gl.drawingBufferWidth,Jm[1]=this.gl.drawingBufferHeight,this.shader.uniforms.screenShape=Jm,this.vao.bind()},ny.unbind=function(){this.vao.unbind()},ny.drawAxisLine=function(t,e,r,n,i){var a=ty(Qm);this.shader.uniforms.majorAxis=Qm,a[t]=e[1][t]-e[0][t],this.shader.uniforms.minorAxis=a;var o,s=ey($m,r);s[t]+=e[0][t],this.shader.uniforms.offset=s,this.shader.uniforms.lineWidth=i,this.shader.uniforms.color=n,(o=ty(Km))[(t+2)%3]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,6),(o=ty(Km))[(t+1)%3]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,6)},ny.drawAxisTicks=function(t,e,r,n,i){if(this.tickCount[t]){var a=ty(Zm);a[t]=1,this.shader.uniforms.majorAxis=a,this.shader.uniforms.offset=e,this.shader.uniforms.minorAxis=r,this.shader.uniforms.color=n,this.shader.uniforms.lineWidth=i;var o=ty(Km);o[t]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,this.tickCount[t],this.tickOffset[t])}},ny.drawGrid=function(t,e,r,n,i,a){if(this.gridCount[t]){var o=ty(Qm);o[e]=r[1][e]-r[0][e],this.shader.uniforms.minorAxis=o;var s=ey($m,n);s[e]+=r[0][e],this.shader.uniforms.offset=s;var l=ty(Zm);l[t]=1,this.shader.uniforms.majorAxis=l;var u=ty(Km);u[t]=1,this.shader.uniforms.screenAxis=u,this.shader.uniforms.lineWidth=a,this.shader.uniforms.color=i,this.vao.draw(this.gl.TRIANGLES,this.gridCount[t],this.gridOffset[t])}},ny.drawZero=function(t,e,r,n,i,a){var o=ty(Qm);this.shader.uniforms.majorAxis=o,o[t]=r[1][t]-r[0][t],this.shader.uniforms.minorAxis=o;var s=ey($m,n);s[t]+=r[0][t],this.shader.uniforms.offset=s;var l=ty(Km);l[e]=1,this.shader.uniforms.screenAxis=l,this.shader.uniforms.lineWidth=a,this.shader.uniforms.color=i,this.vao.draw(this.gl.TRIANGLES,6)},ny.dispose=function(){this.vao.dispose(),this.vertBuffer.dispose(),this.shader.dispose()};var oy={ge:ay(">=",!1,"GE"),gt:ay(">",!1,"GT"),lt:ay("<",!0,"LT"),le:ay("<=",!0,"LE"),eq:ay("-",!0,"EQ",!0)},sy={},ly=6;function uy(t,e){for(var r=new Array(t.length-1),n=1;n>1;return["sum(",cy(t.slice(0,e)),",",cy(t.slice(e)),")"].join("")}function hy(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return hy(e,t)}function fy(t){if(2===t.length)return[["diff(",hy(t[0][0],t[1][1]),",",hy(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0;){for(var l=r.pop(),a=r.pop(),u=-1,c=-1,o=i[a],f=1;f=0||(e.flip(a,l),yy(t,e,r,u,a,c),yy(t,e,r,a,c,u),yy(t,e,r,c,l,u),yy(t,e,r,l,u,c)))}};function yy(t,e,r,n,i,a){var o=e.opposite(n,i);if(!(o<0)){if(i0||o.length>0;){for(;a.length>0;){var h=a.pop();if(s[h]!==-i){s[h]=i;l[h];for(var f=0;f<3;++f){var d=c[3*h+f];d>=0&&0===s[d]&&(u[3*h+f]?o.push(d):(a.push(d),s[d]=i))}}}var p=o;o=a,a=p,o.length=0,i=-i}var g=function(t,e,r){for(var n=0,i=0;il[0]&&i.push(new Cy(l,s,ky,a),new Cy(s,l,Ty,a))}i.sort(Sy);for(var u=i[0].a[0]-(1+Math.abs(i[0].a[0]))*Math.pow(2,-52),c=[new Ly([u,1],[u,0],-1,[],[],[],[])],h=[],a=0,f=i.length;a1&&My(r[u[c-2]],r[u[c-1]],n)>0;)t.push([u[c-1],u[c-2],i]),c-=1;u.length=c,u.push(i);var h=l.upperIds;for(c=h.length;c>1&&My(r[h[c-2]],r[h[c-1]],n)<0;)t.push([h[c-2],h[c-1],i]),c-=1;h.length=c,h.push(i)}}function Oy(t,e){var r;return(r=t.a[0]=0}}(),Fy.removeTriangle=function(t,e,r){var n=this.stars;jy(n[t],e,r),jy(n[e],r,t),jy(n[r],t,e)},Fy.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},Fy.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;n=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function s(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;o=49?s-49+10:s>=17?s-17+10:s}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[a]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);else if("le"===n)for(i=0,a=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)i=o(t,r,r+6),this.words[n]|=i<>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==e&&(i=o(t,e,r+6),this.words[n]|=i<>>26-a&4194303),this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,o=a%n,l=Math.min(a,a-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var l=["","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"],u=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],a=0|e.words[0],o=i*a,s=67108863&o,l=o/67108864|0;r.words[0]=s;for(var u=1;u>>26,h=67108863&l,f=Math.min(u,e.length-1),d=Math.max(0,u-t.length+1);d<=f;d++){var p=u-d|0;c+=(o=(i=0|t.words[p])*(a=0|e.words[d])+h)/67108864|0,h=67108863&o}r.words[u]=0|h,l=0|c}return 0!==l?r.words[u]=0|l:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var i=0,a=0,o=0;o>>24-i&16777215)||o!==this.length-1?l[6-h.length]+h+n:h+n,(i+=2)>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var f=u[t],d=c[t];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(d).toString(t);n=(p=p.idivn(d)).isZero()?g+n:l[f-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==a),this.toArrayLike(a,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),a=n||Math.max(1,i);r(i<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var o,s,l="le"===e,u=new t(a),c=this.clone();if(l){for(s=0;!c.isZero();s++)o=c.andln(255),c.iushrn(8),u[s]=o;for(;s=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26;for(;0!==i&&a>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==a&&o>26,this.words[o]=67108863&e;if(0===a&&o>>13,d=0|o[1],p=8191&d,g=d>>>13,v=0|o[2],m=8191&v,y=v>>>13,b=0|o[3],x=8191&b,_=b>>>13,w=0|o[4],M=8191&w,A=w>>>13,T=0|o[5],k=8191&T,E=T>>>13,L=0|o[6],C=8191&L,S=L>>>13,P=0|o[7],R=8191&P,O=P>>>13,I=0|o[8],N=8191&I,D=I>>>13,z=0|o[9],F=8191&z,j=z>>>13,B=0|s[0],U=8191&B,V=B>>>13,H=0|s[1],q=8191&H,G=H>>>13,X=0|s[2],W=8191&X,Y=X>>>13,Z=0|s[3],Q=8191&Z,K=Z>>>13,$=0|s[4],J=8191&$,tt=$>>>13,et=0|s[5],rt=8191&et,nt=et>>>13,it=0|s[6],at=8191&it,ot=it>>>13,st=0|s[7],lt=8191&st,ut=st>>>13,ct=0|s[8],ht=8191&ct,ft=ct>>>13,dt=0|s[9],pt=8191&dt,gt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(u+(n=Math.imul(h,U))|0)+((8191&(i=(i=Math.imul(h,V))+Math.imul(f,U)|0))<<13)|0;u=((a=Math.imul(f,V))+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,V))+Math.imul(g,U)|0,a=Math.imul(g,V);var mt=(u+(n=n+Math.imul(h,q)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(f,q)|0))<<13)|0;u=((a=a+Math.imul(f,G)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,U),i=(i=Math.imul(m,V))+Math.imul(y,U)|0,a=Math.imul(y,V),n=n+Math.imul(p,q)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(g,q)|0,a=a+Math.imul(g,G)|0;var yt=(u+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(f,W)|0))<<13)|0;u=((a=a+Math.imul(f,Y)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,V))+Math.imul(_,U)|0,a=Math.imul(_,V),n=n+Math.imul(m,q)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,q)|0,a=a+Math.imul(y,G)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(g,W)|0,a=a+Math.imul(g,Y)|0;var bt=(u+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(f,Q)|0))<<13)|0;u=((a=a+Math.imul(f,K)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(M,U),i=(i=Math.imul(M,V))+Math.imul(A,U)|0,a=Math.imul(A,V),n=n+Math.imul(x,q)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(_,q)|0,a=a+Math.imul(_,G)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(y,W)|0,a=a+Math.imul(y,Y)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,K)|0)+Math.imul(g,Q)|0,a=a+Math.imul(g,K)|0;var xt=(u+(n=n+Math.imul(h,J)|0)|0)+((8191&(i=(i=i+Math.imul(h,tt)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,tt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(k,U),i=(i=Math.imul(k,V))+Math.imul(E,U)|0,a=Math.imul(E,V),n=n+Math.imul(M,q)|0,i=(i=i+Math.imul(M,G)|0)+Math.imul(A,q)|0,a=a+Math.imul(A,G)|0,n=n+Math.imul(x,W)|0,i=(i=i+Math.imul(x,Y)|0)+Math.imul(_,W)|0,a=a+Math.imul(_,Y)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,K)|0)+Math.imul(y,Q)|0,a=a+Math.imul(y,K)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,tt)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,tt)|0;var _t=(u+(n=n+Math.imul(h,rt)|0)|0)+((8191&(i=(i=i+Math.imul(h,nt)|0)+Math.imul(f,rt)|0))<<13)|0;u=((a=a+Math.imul(f,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(C,U),i=(i=Math.imul(C,V))+Math.imul(S,U)|0,a=Math.imul(S,V),n=n+Math.imul(k,q)|0,i=(i=i+Math.imul(k,G)|0)+Math.imul(E,q)|0,a=a+Math.imul(E,G)|0,n=n+Math.imul(M,W)|0,i=(i=i+Math.imul(M,Y)|0)+Math.imul(A,W)|0,a=a+Math.imul(A,Y)|0,n=n+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,K)|0)+Math.imul(_,Q)|0,a=a+Math.imul(_,K)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,tt)|0,n=n+Math.imul(p,rt)|0,i=(i=i+Math.imul(p,nt)|0)+Math.imul(g,rt)|0,a=a+Math.imul(g,nt)|0;var wt=(u+(n=n+Math.imul(h,at)|0)|0)+((8191&(i=(i=i+Math.imul(h,ot)|0)+Math.imul(f,at)|0))<<13)|0;u=((a=a+Math.imul(f,ot)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(R,U),i=(i=Math.imul(R,V))+Math.imul(O,U)|0,a=Math.imul(O,V),n=n+Math.imul(C,q)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(S,q)|0,a=a+Math.imul(S,G)|0,n=n+Math.imul(k,W)|0,i=(i=i+Math.imul(k,Y)|0)+Math.imul(E,W)|0,a=a+Math.imul(E,Y)|0,n=n+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,K)|0)+Math.imul(A,Q)|0,a=a+Math.imul(A,K)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,tt)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,a=a+Math.imul(y,nt)|0,n=n+Math.imul(p,at)|0,i=(i=i+Math.imul(p,ot)|0)+Math.imul(g,at)|0,a=a+Math.imul(g,ot)|0;var Mt=(u+(n=n+Math.imul(h,lt)|0)|0)+((8191&(i=(i=i+Math.imul(h,ut)|0)+Math.imul(f,lt)|0))<<13)|0;u=((a=a+Math.imul(f,ut)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(N,U),i=(i=Math.imul(N,V))+Math.imul(D,U)|0,a=Math.imul(D,V),n=n+Math.imul(R,q)|0,i=(i=i+Math.imul(R,G)|0)+Math.imul(O,q)|0,a=a+Math.imul(O,G)|0,n=n+Math.imul(C,W)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(S,W)|0,a=a+Math.imul(S,Y)|0,n=n+Math.imul(k,Q)|0,i=(i=i+Math.imul(k,K)|0)+Math.imul(E,Q)|0,a=a+Math.imul(E,K)|0,n=n+Math.imul(M,J)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(A,J)|0,a=a+Math.imul(A,tt)|0,n=n+Math.imul(x,rt)|0,i=(i=i+Math.imul(x,nt)|0)+Math.imul(_,rt)|0,a=a+Math.imul(_,nt)|0,n=n+Math.imul(m,at)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(y,at)|0,a=a+Math.imul(y,ot)|0,n=n+Math.imul(p,lt)|0,i=(i=i+Math.imul(p,ut)|0)+Math.imul(g,lt)|0,a=a+Math.imul(g,ut)|0;var At=(u+(n=n+Math.imul(h,ht)|0)|0)+((8191&(i=(i=i+Math.imul(h,ft)|0)+Math.imul(f,ht)|0))<<13)|0;u=((a=a+Math.imul(f,ft)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(F,U),i=(i=Math.imul(F,V))+Math.imul(j,U)|0,a=Math.imul(j,V),n=n+Math.imul(N,q)|0,i=(i=i+Math.imul(N,G)|0)+Math.imul(D,q)|0,a=a+Math.imul(D,G)|0,n=n+Math.imul(R,W)|0,i=(i=i+Math.imul(R,Y)|0)+Math.imul(O,W)|0,a=a+Math.imul(O,Y)|0,n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,K)|0)+Math.imul(S,Q)|0,a=a+Math.imul(S,K)|0,n=n+Math.imul(k,J)|0,i=(i=i+Math.imul(k,tt)|0)+Math.imul(E,J)|0,a=a+Math.imul(E,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(A,rt)|0,a=a+Math.imul(A,nt)|0,n=n+Math.imul(x,at)|0,i=(i=i+Math.imul(x,ot)|0)+Math.imul(_,at)|0,a=a+Math.imul(_,ot)|0,n=n+Math.imul(m,lt)|0,i=(i=i+Math.imul(m,ut)|0)+Math.imul(y,lt)|0,a=a+Math.imul(y,ut)|0,n=n+Math.imul(p,ht)|0,i=(i=i+Math.imul(p,ft)|0)+Math.imul(g,ht)|0,a=a+Math.imul(g,ft)|0;var Tt=(u+(n=n+Math.imul(h,pt)|0)|0)+((8191&(i=(i=i+Math.imul(h,gt)|0)+Math.imul(f,pt)|0))<<13)|0;u=((a=a+Math.imul(f,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(F,q),i=(i=Math.imul(F,G))+Math.imul(j,q)|0,a=Math.imul(j,G),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(D,W)|0,a=a+Math.imul(D,Y)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,K)|0)+Math.imul(O,Q)|0,a=a+Math.imul(O,K)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,tt)|0,n=n+Math.imul(k,rt)|0,i=(i=i+Math.imul(k,nt)|0)+Math.imul(E,rt)|0,a=a+Math.imul(E,nt)|0,n=n+Math.imul(M,at)|0,i=(i=i+Math.imul(M,ot)|0)+Math.imul(A,at)|0,a=a+Math.imul(A,ot)|0,n=n+Math.imul(x,lt)|0,i=(i=i+Math.imul(x,ut)|0)+Math.imul(_,lt)|0,a=a+Math.imul(_,ut)|0,n=n+Math.imul(m,ht)|0,i=(i=i+Math.imul(m,ft)|0)+Math.imul(y,ht)|0,a=a+Math.imul(y,ft)|0;var kt=(u+(n=n+Math.imul(p,pt)|0)|0)+((8191&(i=(i=i+Math.imul(p,gt)|0)+Math.imul(g,pt)|0))<<13)|0;u=((a=a+Math.imul(g,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(F,W),i=(i=Math.imul(F,Y))+Math.imul(j,W)|0,a=Math.imul(j,Y),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,K)|0)+Math.imul(D,Q)|0,a=a+Math.imul(D,K)|0,n=n+Math.imul(R,J)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(O,J)|0,a=a+Math.imul(O,tt)|0,n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(S,rt)|0,a=a+Math.imul(S,nt)|0,n=n+Math.imul(k,at)|0,i=(i=i+Math.imul(k,ot)|0)+Math.imul(E,at)|0,a=a+Math.imul(E,ot)|0,n=n+Math.imul(M,lt)|0,i=(i=i+Math.imul(M,ut)|0)+Math.imul(A,lt)|0,a=a+Math.imul(A,ut)|0,n=n+Math.imul(x,ht)|0,i=(i=i+Math.imul(x,ft)|0)+Math.imul(_,ht)|0,a=a+Math.imul(_,ft)|0;var Et=(u+(n=n+Math.imul(m,pt)|0)|0)+((8191&(i=(i=i+Math.imul(m,gt)|0)+Math.imul(y,pt)|0))<<13)|0;u=((a=a+Math.imul(y,gt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(F,Q),i=(i=Math.imul(F,K))+Math.imul(j,Q)|0,a=Math.imul(j,K),n=n+Math.imul(N,J)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(D,J)|0,a=a+Math.imul(D,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(O,rt)|0,a=a+Math.imul(O,nt)|0,n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ot)|0)+Math.imul(S,at)|0,a=a+Math.imul(S,ot)|0,n=n+Math.imul(k,lt)|0,i=(i=i+Math.imul(k,ut)|0)+Math.imul(E,lt)|0,a=a+Math.imul(E,ut)|0,n=n+Math.imul(M,ht)|0,i=(i=i+Math.imul(M,ft)|0)+Math.imul(A,ht)|0,a=a+Math.imul(A,ft)|0;var Lt=(u+(n=n+Math.imul(x,pt)|0)|0)+((8191&(i=(i=i+Math.imul(x,gt)|0)+Math.imul(_,pt)|0))<<13)|0;u=((a=a+Math.imul(_,gt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(F,J),i=(i=Math.imul(F,tt))+Math.imul(j,J)|0,a=Math.imul(j,tt),n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(D,rt)|0,a=a+Math.imul(D,nt)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ot)|0)+Math.imul(O,at)|0,a=a+Math.imul(O,ot)|0,n=n+Math.imul(C,lt)|0,i=(i=i+Math.imul(C,ut)|0)+Math.imul(S,lt)|0,a=a+Math.imul(S,ut)|0,n=n+Math.imul(k,ht)|0,i=(i=i+Math.imul(k,ft)|0)+Math.imul(E,ht)|0,a=a+Math.imul(E,ft)|0;var Ct=(u+(n=n+Math.imul(M,pt)|0)|0)+((8191&(i=(i=i+Math.imul(M,gt)|0)+Math.imul(A,pt)|0))<<13)|0;u=((a=a+Math.imul(A,gt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(F,rt),i=(i=Math.imul(F,nt))+Math.imul(j,rt)|0,a=Math.imul(j,nt),n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ot)|0)+Math.imul(D,at)|0,a=a+Math.imul(D,ot)|0,n=n+Math.imul(R,lt)|0,i=(i=i+Math.imul(R,ut)|0)+Math.imul(O,lt)|0,a=a+Math.imul(O,ut)|0,n=n+Math.imul(C,ht)|0,i=(i=i+Math.imul(C,ft)|0)+Math.imul(S,ht)|0,a=a+Math.imul(S,ft)|0;var St=(u+(n=n+Math.imul(k,pt)|0)|0)+((8191&(i=(i=i+Math.imul(k,gt)|0)+Math.imul(E,pt)|0))<<13)|0;u=((a=a+Math.imul(E,gt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(F,at),i=(i=Math.imul(F,ot))+Math.imul(j,at)|0,a=Math.imul(j,ot),n=n+Math.imul(N,lt)|0,i=(i=i+Math.imul(N,ut)|0)+Math.imul(D,lt)|0,a=a+Math.imul(D,ut)|0,n=n+Math.imul(R,ht)|0,i=(i=i+Math.imul(R,ft)|0)+Math.imul(O,ht)|0,a=a+Math.imul(O,ft)|0;var Pt=(u+(n=n+Math.imul(C,pt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(S,pt)|0))<<13)|0;u=((a=a+Math.imul(S,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(F,lt),i=(i=Math.imul(F,ut))+Math.imul(j,lt)|0,a=Math.imul(j,ut),n=n+Math.imul(N,ht)|0,i=(i=i+Math.imul(N,ft)|0)+Math.imul(D,ht)|0,a=a+Math.imul(D,ft)|0;var Rt=(u+(n=n+Math.imul(R,pt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(O,pt)|0))<<13)|0;u=((a=a+Math.imul(O,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(F,ht),i=(i=Math.imul(F,ft))+Math.imul(j,ht)|0,a=Math.imul(j,ft);var Ot=(u+(n=n+Math.imul(N,pt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(D,pt)|0))<<13)|0;u=((a=a+Math.imul(D,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863;var It=(u+(n=Math.imul(F,pt))|0)+((8191&(i=(i=Math.imul(F,gt))+Math.imul(j,pt)|0))<<13)|0;return u=((a=Math.imul(j,gt))+(i>>>13)|0)+(It>>>26)|0,It&=67108863,l[0]=vt,l[1]=mt,l[2]=yt,l[3]=bt,l[4]=xt,l[5]=_t,l[6]=wt,l[7]=Mt,l[8]=At,l[9]=Tt,l[10]=kt,l[11]=Et,l[12]=Lt,l[13]=Ct,l[14]=St,l[15]=Pt,l[16]=Rt,l[17]=Ot,l[18]=It,0!==u&&(l[19]=u,r.length++),r};function d(t,e,r){return(new p).mulp(t,e,r)}function p(t,e){this.x=t,this.y=e}Math.imul||(f=h),i.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?f(this,t,e):r<63?h(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,a=0;a>>26)|0)>>>26,o&=67108863}r.words[a]=s,n=o,o=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,t,e):d(this,t,e)},p.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},p.prototype.permute=function(t,e,r,n,i,a){for(var o=0;o>>=1)i++;return 1<>>=13,n[2*o+1]=8191&a,a>>>=13;for(o=2*e;o>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,a=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(e=0;e>>26-n}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=i);u--){var h=0|this.words[u];this.words[u]=c<<26-a|h>>>a,c=h&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(l/67108864|0),this.words[i+n]=67108863&a}for(;i>26,this.words[i+n]=67108863&a;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),a=t,o=0|a.words[a.length-1];0!==(r=26-this._countBits(o))&&(a=a.ushln(r),n.iushln(r),o=0|a.words[a.length-1]);var s,l=n.length-a.length;if("mod"!==e){(s=new i(null)).length=l+1,s.words=new Array(s.length);for(var u=0;u=0;h--){var f=67108864*(0|n.words[a.length+h])+(0|n.words[a.length+h-1]);for(f=Math.min(f/o|0,67108863),n._ishlnsubmul(a,f,h);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(a,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(a=s.div.neg()),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.iadd(t)),{div:a,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(a=s.div.neg()),{div:a,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var a,o,s},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++u;for(var c=n.clone(),h=e.clone();!e.isZero();){for(var f=0,d=1;0==(e.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(e.iushrn(f);f-- >0;)(a.isOdd()||o.isOdd())&&(a.iadd(c),o.isub(h)),a.iushrn(1),o.iushrn(1);for(var p=0,g=1;0==(n.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(s.isOdd()||l.isOdd())&&(s.iadd(c),l.isub(h)),s.iushrn(1),l.iushrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.iushln(u)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a,o=new i(1),s=new i(0),l=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);for(var h=0,f=1;0==(n.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(n.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(s)):(n.isub(e),s.isub(o))}return(a=0===e.cmpn(1)?o:s).cmpn(0)<0&&a.iadd(t),a},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,s&=67108863,this.words[o]=s}return 0!==a&&(this.words[o]=a,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function x(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function w(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,i=a}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new y;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new x}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var a=this.m.subn(1),o=0;!a.isZero()&&0===a.andln(1);)o++,a.iushrn(1);r(!a.isZero());var s=new i(1).toRed(this),l=s.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,u).cmp(l);)c.redIAdd(l);for(var h=this.pow(c,a),f=this.pow(t,a.addn(1).iushrn(1)),d=this.pow(t,a),p=o;0!==d.cmp(s);){for(var g=d,v=0;0!==g.cmp(s);v++)g=g.redSqr();r(v=0;n--){for(var u=e.words[n],c=l-1;c>=0;c--){var h=u>>c&1;a!==r[0]&&(a=this.sqr(a)),0!==h||0!==o?(o<<=1,o|=h,(4===++s||0===n&&0===c)&&(a=this.mul(a,r[o]),s=0,o=0)):s=0}l=26}return a},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new w(t)},n(w,_),w.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},w.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},w.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},w.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).iushrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},w.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(Xy,this),Xy=Xy.exports;var Wy=function(t){return t.cmp(new Xy(0))};var Yy={};(function(t){var e=!1;if("undefined"!=typeof Float64Array){var r=new Float64Array(1),n=new Uint32Array(r.buffer);if(r[0]=1,e=!0,1072693248===n[1]){(Yy=function(t){return r[0]=t,[n[0],n[1]]}).pack=function(t,e){return n[0]=t,n[1]=e,r[0]},Yy.lo=function(t){return r[0]=t,n[0]},Yy.hi=function(t){return r[0]=t,n[1]}}else if(1072693248===n[0]){(Yy=function(t){return r[0]=t,[n[1],n[0]]}).pack=function(t,e){return n[1]=t,n[0]=e,r[0]},Yy.lo=function(t){return r[0]=t,n[1]},Yy.hi=function(t){return r[0]=t,n[0]}}else e=!1}if(!e){var i=new t(8);(Yy=function(t){return i.writeDoubleLE(t,0,!0),[i.readUInt32LE(0,!0),i.readUInt32LE(4,!0)]}).pack=function(t,e){return i.writeUInt32LE(t,0,!0),i.writeUInt32LE(e,4,!0),i.readDoubleLE(0,!0)},Yy.lo=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(0,!0)},Yy.hi=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(4,!0)}}Yy.sign=function(t){return Yy.hi(t)>>>31},Yy.exponent=function(t){return(Yy.hi(t)<<1>>>21)-1023},Yy.fraction=function(t){var e=Yy.lo(t),r=Yy.hi(t),n=1048575&r;return 2146435072&r&&(n+=1<<20),[e,n]},Yy.denormalized=function(t){return!(2146435072&Yy.hi(t))}}).call(this,Yp.Buffer);var Zy=function(t){var e=Yy.exponent(t);return e<52?new Xy(t):new Xy(t*Math.pow(2,52-e)).ushln(e-52)};var Qy=function(t,e){var r=Wy(t),n=Wy(e);if(0===r)return[Zy(0),Zy(1)];if(0===n)return[Zy(0),Zy(0)];n<0&&(t=t.neg(),e=e.neg());var i=t.gcd(e);if(i.cmpn(1))return[t.div(i),e.div(i)];return[t,e]};var Ky=function(t,e){return Qy(t[0].mul(e[1]),t[1].mul(e[0]))};var $y=function(t){return t&&"object"==typeof t&&Boolean(t.words)};var Jy=function(t){return Array.isArray(t)&&2===t.length&&$y(t[0])&&$y(t[1])};var tb=function(t){return new Xy(t)};var eb=function t(e,r){if(Jy(e))return r?Ky(e,t(r)):[e[0].clone(),e[1].clone()];var n=0;var i,a;if($y(e))i=e.clone();else if("string"==typeof e)i=tb(e);else{if(0===e)return[Zy(0),Zy(1)];if(e===Math.floor(e))i=Zy(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),n-=256;i=Zy(e)}}if(Jy(r))i.mul(r[1]),a=r[0].clone();else if($y(r))a=r.clone();else if("string"==typeof r)a=tb(r);else if(r)if(r===Math.floor(r))a=Zy(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),n+=256;a=Zy(r)}else a=Zy(1);n>0?i=i.ushln(n):n<0&&(a=a.ushln(-n));return Qy(i,a)};var rb=function(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var i=0;i20)return 52;return r+32};var ab=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.abs().divmod(r.abs()),i=n.div,a=rb(i),o=n.mod,s=e.negative!==r.negative?-1:1;if(0===o.cmpn(0))return s*a;if(a){var l=ib(a)+4,u=rb(o.ushln(l).divRound(r));return s*(a+u*Math.pow(2,-l))}var c=r.bitLength()-o.bitLength()+53,u=rb(o.ushln(c).divRound(r));return c<1023?s*u*Math.pow(2,-c):(u*=Math.pow(2,-1023),s*u*Math.pow(2,1023-c))};var ob={},sb="d",lb="ax",ub="vv",cb="fp",hb="es",fb="rs",db="re",pb="rb",gb="ri",vb="rp",mb="bs",yb="be",bb="bb",xb="bi",_b="bp",wb="rv",Mb="Q",Ab=[sb,lb,ub,fb,db,pb,gb,mb,yb,bb,xb];function Tb(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],n=Ab.slice();t||n.splice(3,0,cb);var i=["function "+e+"("+n.join()+"){"];function a(e,n){var a=function(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",Ab.join(),"){","var ",hb,"=2*",sb,";"],a="for(var i="+fb+","+vb+"="+hb+"*"+fb+";i<"+db+";++i,"+vb+"+="+hb+"){var x0="+pb+"["+lb+"+"+vb+"],x1="+pb+"["+lb+"+"+vb+"+"+sb+"],xi="+gb+"[i];",o="for(var j="+mb+","+_b+"="+hb+"*"+mb+";j<"+yb+";++j,"+_b+"+="+hb+"){var y0="+bb+"["+lb+"+"+_b+"],"+(r?"y1="+bb+"["+lb+"+"+_b+"+"+sb+"],":"")+"yi="+xb+"[j];";return t?i.push(a,Mb,":",o):i.push(o,Mb,":",a),r?i.push("if(y1"+yb+"-"+mb+"){"),t?(a(!0,!1),i.push("}else{"),a(!1,!1)):(i.push("if("+cb+"){"),a(!0,!0),i.push("}else{"),a(!0,!1),i.push("}}else{if("+cb+"){"),a(!1,!0),i.push("}else{"),a(!1,!1),i.push("}")),i.push("}}return "+e);var o=r.join("")+i.join("");return new Function(o)()}ob.partial=Tb(!1),ob.full=Tb(!0);var kb=function(t,e){var r="abcdef".split("").concat(e),n=[];t.indexOf("lo")>=0&&n.push("lo=e[k+n]");t.indexOf("hi")>=0&&n.push("hi=e[k+o]");return r.push(Eb.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)},Eb="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m";var Lb=function(t,e,r,n,i,a){if(n<=r+1)return r;var o=r,s=n,l=n+r>>>1,u=2*t,c=l,h=i[u*l+e];for(;o=v?(c=g,h=v):p>=y?(c=d,h=p):(c=m,h=y):v>=y?(c=g,h=v):y>=p?(c=d,h=p):(c=m,h=y);for(var b=u*(s-1),x=u*c,_=0;_r&&i[h+e]>u;--c,h-=o){for(var f=h,d=h+o,p=0;p>1,l=s-i,u=s+i,c=a,h=l,f=s,d=u,p=o,g=e+1,v=r-1,m=0;jb(c,h,n)&&(m=c,c=h,h=m);jb(d,p,n)&&(m=d,d=p,p=m);jb(c,f,n)&&(m=c,c=f,f=m);jb(h,f,n)&&(m=h,h=f,f=m);jb(c,d,n)&&(m=c,c=d,d=m);jb(f,d,n)&&(m=f,f=d,d=m);jb(h,p,n)&&(m=h,h=p,p=m);jb(h,f,n)&&(m=h,h=f,f=m);jb(d,p,n)&&(m=d,d=p,p=m);var y=n[2*h];var b=n[2*h+1];var x=n[2*d];var _=n[2*d+1];var w=2*c;var M=2*f;var A=2*p;var T=2*a;var k=2*s;var E=2*o;for(var L=0;L<2;++L){var C=n[w+L],S=n[M+L],P=n[A+L];n[T+L]=C,n[k+L]=S,n[E+L]=P}Db(l,e,n);Db(u,r,n);for(var R=g;R<=v;++R)if(Bb(R,y,b,n))R!==g&&Nb(R,g,n),++g;else if(!Bb(R,x,_,n))for(;;){if(Bb(v,x,_,n)){Bb(v,y,b,n)?(zb(R,g,v,n),++g,--v):(Nb(R,v,n),--v);break}if(--vt;){var u=r[l-2],c=r[l-1];if(ur[e+1])}function Bb(t,e,r,n){var i=n[t*=2];return i>>1;Rb(Zb,y);for(var b=0,x=0,p=0;p=Vb)Qb(Gb,Xb,x--,_=_-Vb|0);else if(_>=0)Qb(Hb,qb,b--,_);else if(_<=-Vb){_=-_-Vb|0;for(var w=0;w>>1;Rb(Zb,y);for(var b=0,x=0,_=0,p=0;p>1==Zb[2*p+3]>>1&&(M=2,p+=1),w<0){for(var A=-(w>>1)-1,T=0;T<_;++T){var k=e(Wb[T],A);if(void 0!==k)return k}if(0!==M)for(var T=0;T>1)-1;0===M?Qb(Hb,qb,b--,A):1===M?Qb(Gb,Xb,x--,A):2===M&&Qb(Wb,Yb,_--,A)}}},scanBipartite:function(t,e,r,n,i,a,o,s,l,u,c,h){var f=0,d=2*t,p=e,g=e+t,v=1,m=1;n?m=Vb:v=Vb;for(var y=i;y>>1;Rb(Zb,w);for(var M=0,y=0;y=Vb?(T=!n,b-=Vb):(T=!!n,b-=1),T)Kb(Hb,qb,M++,b);else{var k=h[b],E=d*b,L=c[E+e+1],C=c[E+e+1+t];t:for(var S=0;S>>1;Rb(Zb,b);for(var x=0,g=0;g=Vb)Hb[x++]=v-Vb;else{var w=c[v-=1],M=f*v,A=u[M+e+1],T=u[M+e+1+t];t:for(var k=0;k=0;--k)if(Hb[k]===v){for(var S=k+1;S0;){var f=(c-=1)*cx,d=fx[f],p=fx[f+1],g=fx[f+2],v=fx[f+3],m=fx[f+4],y=fx[f+5],b=c*hx,x=dx[b],_=dx[b+1],w=1&y,M=!!(16&y),A=i,T=a,k=s,E=l;if(w&&(A=s,T=l,k=i,E=a),!(2&y&&(g=ox(t,d,p,g,A,T,_),p>=g)||4&y&&(p=sx(t,d,p,g,A,T,x))>=g)){var L=g-p,C=m-v;if(M){if(t*L*(L+C)=p0)&&!(p1>=hi)",["p0","p1"]),ax=kb("lo===p0",["p0"]),ox=kb("lo>>1;if(!(o<=0)){var s,l=Og.mallocDouble(2*o*i),u=Og.mallocInt32(i);if((i=xx(t,o,l,u))>0){if(1===o&&n)Ub.init(i),s=Ub.sweepComplete(o,r,0,i,l,u,0,i,l,u);else{var c=Og.mallocDouble(2*o*a),h=Og.mallocInt32(a);(a=xx(e,o,c,h))>0&&(Ub.init(i+a),s=1===o?Ub.sweepBipartite(o,r,0,i,l,u,0,a,c,h):$b(o,r,n,i,l,u,a,c,h),Og.free(c),Og.free(h))}Og.free(l),Og.free(u)}return s}}}function wx(t,e){mx.push([t,e])}var Mx=function(t,e){return Qy(t[0].mul(e[0]),t[1].mul(e[1]))};var Ax=function(t){return Wy(t[0])*Wy(t[1])};var Tx=function(t,e){return Qy(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))};var kx=function(t,e){return Qy(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))};var Ex=function(t,e){for(var r=t.length,n=new Array(r),i=0;i>>0,Ix=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-Rx:Rx;var r=Yy.hi(t),n=Yy.lo(t);e>t==t>0?n===Ox?(r+=1,n=0):n+=1:0===n?(n=Ox,r-=1):n-=1;return Yy.pack(n,r)};var Nx=function(t){for(var e=new Array(t.length),r=0;r0&&a>0||i<0&&a<0)return!1;var o=zx(r,t,e),s=zx(n,t,e);if(o>0&&s>0||o<0&&s<0)return!1;if(0===i&&0===a&&0===o&&0===s)return function(t,e,r,n){for(var i=0;i<2;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],h=Math.min(u,c),f=Math.max(u,c);if(fe[2]?1:0)}function Wx(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--a){var p=e[o=(w=n[a])[0]],g=p[0],v=p[1],m=t[g],y=t[v];if((m[0]-y[0]||m[1]-y[1])<0){var b=g;g=v,v=b}p[0]=g;var x,_=p[1]=w[1];for(i&&(x=p[2]);a>0&&n[a-1][0]===o;){var w,M=(w=n[--a])[1];i?e.push([_,M,x]):e.push([_,M]),_=M}i?e.push([_,v,x]):e.push([_,v])}return s}(t,e,i,o,r));return Wx(e,s,r),!!s||(i.length>0||o.length>0)}var Zx=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;n0?1:0},$x=function(t,e,r,n){var i=wm(e,r,n);if(0===i){var a=Kx(wm(t,e,r)),o=Kx(wm(t,e,n));if(a===o){if(0===a){var s=Jx(t,e,r),l=Jx(t,e,n);return s===l?0:s?1:-1}return 0}return 0===o?a>0?-1:Jx(t,e,n)?-1:1:0===a?o>0?1:Jx(t,e,r)?1:-1:Kx(o-a)}var u=wm(t,e,r);if(u>0)return i>0&&wm(t,e,n)>0?1:-1;if(u<0)return i>0||wm(t,e,n)>0?1:-1;var c=wm(t,e,n);return c>0?1:Jx(t,e,r)?1:-1};function Jx(t,e,r){var n=ym(t[0],-e[0]),i=ym(t[1],-e[1]),a=ym(r[0],-e[0]),o=ym(r[1],-e[1]),s=_m(Qx(n,a),Qx(i,o));return s[s.length-1]>=0}var t_=function(t,e){for(var r=0|e.length,n=t.length,i=[new Array(r),new Array(r)],a=0;a0){a=i[u][r][0],s=u;break}o=a[1^s];for(var c=0;c<2;++c)for(var h=i[c][r],f=0;f0&&(a=d,o=p,s=c)}return n?o:(a&&l(a,s),o)}function c(t,r){var n=i[r][t][0],a=[t];l(n,r);for(var o=n[1^r];;){for(;o!==t;)a.push(o),o=u(a[a.length-2],o,!1);if(i[0][t].length+i[1][t].length===0)break;var s=a[a.length-1],c=t,h=a[1],f=u(s,c,!0);if($x(e[s],e[c],e[h],e[f])<0)break;a.push(t),o=u(s,c)}return a}function h(t,e){return e[1]===e[e.length-1]}for(var a=0;a0;){i[0][a].length;var p=c(a,f);h(d,p)?d.push.apply(d,p):(d.length>0&&s.push(d),d=p)}d.length>0&&s.push(d)}return s};var e_=function(t,e){for(var r=Zx(t,e.length),n=new Array(e.length),i=new Array(e.length),a=[],o=0;o0;){var l=a.pop();n[l]=!1;for(var u=r[l],o=0;o=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function d_(t,e){for(var r=0;r>1],i=[],a=[],o=[];for(r=0;r3*(e+1)?u_(this,t):this.left.insert(t):this.left=m_([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?u_(this,t):this.right.insert(t):this.right=m_([t]);else{var r=Vf.ge(this.leftPoints,t,g_),n=Vf.ge(this.rightPoints,t,v_);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},o_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?c_(this,t):2===(a=this.left.remove(t))?(this.left=null,this.count-=1,n_):(a===n_&&(this.count-=1),a):r_}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:r_;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,n=this.left;n.right;)r=n,n=n.right;if(r===this)n.right=this.right;else{var i=this.left;a=this.right;r.count-=n.count,r.right=n.left,n.left=i,n.right=a}s_(this,n),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?s_(this,this.left):s_(this,this.right);return n_}for(i=Vf.ge(this.leftPoints,t,g_);i3*(e-1)?c_(this,t):2===(a=this.right.remove(t))?(this.right=null,this.count-=1,n_):(a===n_&&(this.count-=1),a):r_;var a}},o_.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return f_(this.rightPoints,t,e)}return d_(this.leftPoints,e)},o_.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?f_(this.rightPoints,t,r):d_(this.leftPoints,r)};var b_=y_.prototype;b_.insert=function(t){this.root?this.root.insert(t):this.root=new a_(t[0],null,null,[t],[t])},b_.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==r_}return!1},b_.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},b_.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(b_,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(b_,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}});var x_=function(t){return new E_(t||R_,null)},__=0,w_=1;function M_(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function A_(t){return new M_(t._color,t.key,t.value,t.left,t.right,t._count)}function T_(t,e){return new M_(t,e.key,e.value,e.left,e.right,e._count)}function k_(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function E_(t,e){this._compare=t,this.root=e}var L_=E_.prototype;function C_(t,e){this.tree=t,this._stack=e}Object.defineProperty(L_,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(L_,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(L_,"length",{get:function(){return this.root?this.root._count:0}}),L_.insert=function(t,e){for(var r=this._compare,n=this.root,i=[],a=[];n;){var o=r(t,n.key);i.push(n),a.push(o),n=o<=0?n.left:n.right}i.push(new M_(__,t,e,null,null,1));for(var s=i.length-2;s>=0;--s){n=i[s];a[s]<=0?i[s]=new M_(n._color,n.key,n.value,i[s+1],n.right,n._count+1):i[s]=new M_(n._color,n.key,n.value,n.left,i[s+1],n._count+1)}for(s=i.length-1;s>1;--s){var l=i[s-1];n=i[s];if(l._color===w_||n._color===w_)break;var u=i[s-2];if(u.left===l)if(l.left===n){if(!(c=u.right)||c._color!==__){if(u._color=__,u.left=l.right,l._color=w_,l.right=u,i[s-2]=l,i[s-1]=n,k_(u),k_(l),s>=3)(h=i[s-3]).left===u?h.left=l:h.right=l;break}l._color=w_,u.right=T_(w_,c),u._color=__,s-=1}else{if(!(c=u.right)||c._color!==__){if(l.right=n.left,u._color=__,u.left=n.right,n._color=w_,n.left=l,n.right=u,i[s-2]=n,i[s-1]=l,k_(u),k_(l),k_(n),s>=3)(h=i[s-3]).left===u?h.left=n:h.right=n;break}l._color=w_,u.right=T_(w_,c),u._color=__,s-=1}else if(l.right===n){if(!(c=u.left)||c._color!==__){if(u._color=__,u.right=l.left,l._color=w_,l.left=u,i[s-2]=l,i[s-1]=n,k_(u),k_(l),s>=3)(h=i[s-3]).right===u?h.right=l:h.left=l;break}l._color=w_,u.left=T_(w_,c),u._color=__,s-=1}else{var c;if(!(c=u.left)||c._color!==__){var h;if(l.left=n.right,u._color=__,u.right=n.left,n._color=w_,n.right=l,n.left=u,i[s-2]=n,i[s-1]=l,k_(u),k_(l),k_(n),s>=3)(h=i[s-3]).right===u?h.right=n:h.left=n;break}l._color=w_,u.left=T_(w_,c),u._color=__,s-=1}}return i[0]._color=w_,new E_(r,i[0])},L_.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,i){if(r(e,i.key)<=0){var a;if(i.left&&(a=t(e,r,n,i.left)))return a;if(a=n(i.key,i.value))return a}if(i.right)return t(e,r,n,i.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,i,a){var o,s=n(e,a.key),l=n(r,a.key);if(s<=0){if(a.left&&(o=t(e,r,n,i,a.left)))return o;if(l>0&&(o=i(a.key,a.value)))return o}if(l>0&&a.right)return t(e,r,n,i,a.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(L_,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new C_(this,t)}}),Object.defineProperty(L_,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new C_(this,t)}}),L_.at=function(t){if(t<0)return new C_(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new C_(this,[])},L_.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<=0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new C_(this,n)},L_.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new C_(this,n)},L_.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new C_(this,n)},L_.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new C_(this,n)},L_.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new C_(this,n);r=i<=0?r.left:r.right}return new C_(this,[])},L_.remove=function(t){var e=this.find(t);return e?e.remove():this},L_.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var S_=C_.prototype;function P_(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function R_(t,e){return te?1:0}Object.defineProperty(S_,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(S_,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),S_.clone=function(){return new C_(this.tree,this._stack.slice())},S_.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new M_(r._color,r.key,r.value,r.left,r.right,r._count);for(var n=t.length-2;n>=0;--n){(r=t[n]).left===t[n+1]?e[n]=new M_(r._color,r.key,r.value,e[n+1],r.right,r._count):e[n]=new M_(r._color,r.key,r.value,r.left,e[n+1],r._count)}if((r=e[e.length-1]).left&&r.right){var i=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var a=e[i-1];e.push(new M_(r._color,a.key,a.value,r.left,r.right,r._count)),e[i-1].key=r.key,e[i-1].value=r.value;for(n=e.length-2;n>=i;--n)r=e[n],e[n]=new M_(r._color,r.key,r.value,r.left,e[n+1],r._count);e[i-1].left=e[i]}if((r=e[e.length-1])._color===__){var o=e[e.length-2];o.left===r?o.left=null:o.right===r&&(o.right=null),e.pop();for(n=0;n=0;--a){if(e=t[a],0===a)return void(e._color=w_);if((r=t[a-1]).left===e){if((n=r.right).right&&n.right._color===__)return i=(n=r.right=A_(n)).right=A_(n.right),r.right=n.left,n.left=r,n.right=i,n._color=r._color,e._color=w_,r._color=w_,i._color=w_,k_(r),k_(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),void(t[a-1]=n);if(n.left&&n.left._color===__)return i=(n=r.right=A_(n)).left=A_(n.left),r.right=i.left,n.left=i.right,i.left=r,i.right=n,i._color=r._color,r._color=w_,n._color=w_,e._color=w_,k_(r),k_(n),k_(i),a>1&&((o=t[a-2]).left===r?o.left=i:o.right=i),void(t[a-1]=i);if(n._color===w_){if(r._color===__)return r._color=w_,void(r.right=T_(__,n));r.right=T_(__,n);continue}n=A_(n),r.right=n.left,n.left=r,n._color=r._color,r._color=__,k_(r),k_(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),t[a-1]=n,t[a]=r,a+11&&((o=t[a-2]).right===r?o.right=n:o.left=n),void(t[a-1]=n);if(n.right&&n.right._color===__)return i=(n=r.left=A_(n)).right=A_(n.right),r.left=i.right,n.right=i.left,i.right=r,i.left=n,i._color=r._color,r._color=w_,n._color=w_,e._color=w_,k_(r),k_(n),k_(i),a>1&&((o=t[a-2]).right===r?o.right=i:o.left=i),void(t[a-1]=i);if(n._color===w_){if(r._color===__)return r._color=w_,void(r.left=T_(__,n));r.left=T_(__,n);continue}var o;n=A_(n),r.left=n.right,n.right=r,n._color=r._color,r._color=__,k_(r),k_(n),a>1&&((o=t[a-2]).right===r?o.right=n:o.left=n),t[a-1]=n,t[a]=r,a+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(S_,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(S_,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),S_.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(S_,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),S_.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new M_(n._color,n.key,t,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i)(n=e[i]).left===e[i+1]?r[i]=new M_(n._color,n.key,n.value,r[i+1],n.right,n._count):r[i]=new M_(n._color,n.key,n.value,n.left,r[i+1],n._count);return new E_(this.tree._compare,r[0])},S_.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(S_,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}});var O_=function(t,e){var r,n,i,a;if(e[0][0]e[1][0]))return I_(e,t);r=e[1],n=e[0]}if(t[0][0]t[1][0]))return-I_(t,e);i=t[1],a=t[0]}var o=wm(r,n,a),s=wm(r,n,i);if(o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;if(o=wm(a,i,n),s=wm(a,i,r),o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;return n[0]-a[0]};function I_(t,e){var r,n,i,a;if(e[0][0]e[1][0])){var o=Math.min(t[0][1],t[1][1]),s=Math.max(t[0][1],t[1][1]),l=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return su?o-u:s-u}r=e[1],n=e[0]}t[0][1]0)if(e[0]!==a[1][0])r=t,t=t.right;else{if(s=F_(t.right,e))return s;t=t.left}else{if(e[0]!==a[1][0])return t;var s;if(s=F_(t.right,e))return s;t=t.left}}return r}function j_(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function B_(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}D_.prototype.castUp=function(t){var e=Vf.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=F_(this.slabs[e],t),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var i=null;if(r&&(i=r.key),e>0){var a=F_(this.slabs[e-1],t);a&&(i?O_(a.key,i)>0&&(i=a.key,n=a.value):(n=a.value,i=a.key))}var o=this.horizontal[e];if(o.length>0){var s=Vf.ge(o,t[1],z_);if(s=o.length)return n;l=o[s]}}if(l.start)if(i){var u=wm(i[0],i[1],[t[0],l.y]);i[0][0]>i[1][0]&&(u=-u),u>0&&(n=l.index)}else n=l.index;else l.y!==t[1]&&(n=l.index)}}}return n};var U_=function(t){for(var e=t.length,r=[],n=[],i=0;i0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=V_(r,o[0],o[1]);if(o[0][0]0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(s<0))return 0;a=1,i=i.right}}return a}}(f.slabs,f.coordinates);return 0===n.length?d:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(q_(n),d)},V_=wm[3];function H_(){return!0}function q_(t){for(var e={},r=0;r0})).length,l=new Array(s),u=new Array(s),a=0;a0;){var P=C.pop(),R=_[P];cp(R,function(t,e){return t-e});var O,I=R.length,N=S[P];if(0===N){var g=o[P];O=[g]}for(var a=0;a=0)&&(S[D]=1^N,C.push(D),0===N)){var g=o[D];L(g)||(g.reverse(),O.push(g))}}0===N&&r.push(O)}return r};function W_(t,e){for(var r=new Array(t),n=0;n>1,o=Z_(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function tw(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==Z_(t[d],a)););}return r}function ew(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return K_(e)},Y_.skeleton=ew,Y_.boundary=function(t){for(var e=[],r=0,n=t.length;r0)-(t<0)},rw.abs=function(t){var e=t>>31;return(t^e)-e},rw.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},rw.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},rw.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},rw.countTrailingZeros=nw,rw.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},rw.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},rw.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var iw=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|iw[t>>>16&255]<<8|iw[t>>>24&255]},rw.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},rw.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},rw.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},rw.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},rw.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>nw(t)+1};var aw=ow;function ow(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e>1,o=lw(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function dw(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==lw(t[d],a)););}return r}function pw(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return cw(e)},sw.skeleton=pw,sw.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function m(t){for(var e=g(t);;){var r=e,n=2*t+1,i=2*(t+1),a=t;if(n0;){var r=v(t);if(r>=0){var n=g(r);if(e0){var t=w[0];return p(0,T-1),T-=1,m(0),t}return-1}function x(t,e){var r=w[t];return s[r]===e?t:(s[r]=-1/0,y(t),b(),s[r]=e,y((T+=1)-1))}function _(t){if(!l[t]){l[t]=!0;var e=a[t],r=o[t];a[r]>=0&&(a[r]=e),o[e]>=0&&(o[e]=r),M[e]>=0&&x(M[e],d(e)),M[r]>=0&&x(M[r],d(r))}}for(var w=[],M=new Array(n),u=0;u>1;u>=0;--u)m(u);for(;;){var k=b();if(k<0||s[k]>r)break;_(k)}for(var E=[],u=0;u=0&&r>=0&&e!==r){var n=M[e],i=M[r];n!==i&&C.push([n,i])}}),sw.unique(sw.normalize(C)),{positions:E,edges:C}};var vw=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;n<1&&e("Must have at least one array argument");var i=t.scalarArguments||0;i<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;s=0?o[s]=!0:o[s]=!1;return function(t,e,r,n,i,a){var o=a.length,s=i.length;if(s<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var l="extractContour"+i.join("_"),u=[],c=[],h=[],f=0;f0&&v.push(_w(f,i[d-1])+"*"+xw(i[d-1])),c.push(Ew(f,i[d])+"=("+v.join("-")+")|0")}for(var f=0;f=0;--f)m.push(xw(i[f]));c.push(Nw+"=("+m.join("*")+")|0",Ow+"=mallocUint32("+Nw+")",Rw+"=mallocUint32("+Nw+")",Dw+"=0"),c.push(Lw(0)+"=0");for(var d=1;d<1<0;v=v-1&d)g.push(Rw+"["+Dw+"+"+Sw(v)+"]");g.push(Pw(0));for(var v=0;v=0;--e)w(e,0);for(var r=[],e=0;e0){",kw(i[e]),"=1;");t(e-1,r|1<0;--r)e+=Vw[r]/(t+r);var n=t+Uw+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}(jw=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(Hw(e));e-=1;for(var r=Bw[0],n=1;n<9;n++)r+=Bw[n]/(e+n);var i=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(i,e+.5)*Math.exp(-i)*r}).log=Hw;var qw=function(t){var e=t.length;if(e0;--i)n=o[i],r=a[i],a[i]=a[n],a[n]=r,o[i]=o[r],o[r]=n,s=(s+r)*i;return Og.freeUint32(o),Og.freeUint32(a),s},Ww.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,i,a,o=1;for((r=r||new Array(t))[0]=0,a=1;a0;--a)e=e-(n=e/o|0)*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r};var Yw=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(jw(t+1)),r=[],n=0;n= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"}),Qw=function(t,e){var r=[];return e=+e||0,Zw(t.hi(t.shape[0]-1),r,e),r};var Kw=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=Qw(t,e),n=r.length,i=new Array(n),a=new Array(n),o=0;o c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],o=[],s=0;s>>7){");for(var s=0;s<1<<(1<128&&s%128==0){u.length>0&&c.push("}}");var h="vExtra"+u.length;n.push("case ",s>>>7,":",h,"(m&0x7f,",o.join(),");break;"),c=["function ",h,"(m,",o.join(),"){switch(m){"],u.push(c)}c.push("case ",127&s,":");for(var f=new Array(r),d=new Array(r),p=new Array(r),g=new Array(r),v=0,m=0;mm)&&!(s&1<0&&(M="+"+p[y]+"*c");var A=f[y].length/v*.5,T=.5+g[y]/v*.5;w.push("d"+y+"-"+T+"-"+A+"*("+f[y].join("+")+M+")/("+d[y].join("+")+")")}c.push("a.push([",w.join(),"]);","break;")}n.push("}},"),u.length>0&&c.push("}}");for(var k=[],s=0;s<1<8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height=0;--p){var g=u[d[p]];o.push(l*g[0],-l*g[1],t)}}for(var l=[0,0,0],u=[0,0,0],c=[0,0,0],h=[0,0,0],f=0;f<3;++f){c[f]=o.length/3|0,s(.5*(t[0][f]+t[1][f]),e[f],r),h[f]=(o.length/3|0)-c[f],l[f]=o.length/3|0;for(var d=0;d=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;o<0?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u|=0);var c=""+l;if(o<0&&(c="-"+c),i){for(var h=""+u;h.length=t[0][n];--a)i.push({x:a*e[n],text:sM(e[n],a)});r.push(i)}return r},oM.equal=function(t,e){for(var r=0;r<3;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n0?(d[c]=-1,p[c]=0):(d[c]=0,p[c]=1)}}var vM=[0,0,0],mM={model:uM,view:uM,projection:uM};fM.isOpaque=function(){return!0},fM.isTransparent=function(){return!1},fM.drawTransparent=function(t){};var yM=[0,0,0],bM=[0,0,0],xM=[0,0,0];fM.draw=function(t){t=t||mM;for(var e=this.gl,r=t.model||uM,n=t.view||uM,i=t.projection||uM,a=this.bounds,o=Nm(r,n,i,a),s=o.cubeEdges,l=o.axis,u=n[12],c=n[13],h=n[14],f=n[15],d=this.pixelRatio*(i[3]*u+i[7]*c+i[11]*h+i[15]*f)/e.drawingBufferHeight,p=0;p<3;++p)this.lastCubeProps.cubeEdges[p]=s[p],this.lastCubeProps.axis[p]=l[p];var g=pM;for(p=0;p<3;++p)gM(pM[p],p,this.bounds,s,l);e=this.gl;var v=vM;for(p=0;p<3;++p)this.backgroundEnable[p]?v[p]=l[p]:v[p]=0;this._background.draw(r,n,i,a,v,this.backgroundColor),this._lines.bind(r,n,i,this);for(p=0;p<3;++p){var m=[0,0,0];l[p]>0?m[p]=a[1][p]:m[p]=a[0][p];for(var y=0;y<2;++y){var b=(p+1+y)%3,x=(p+1+(1^y))%3;this.gridEnable[b]&&this._lines.drawGrid(b,x,this.bounds,m,this.gridColor[b],this.gridWidth[b]*this.pixelRatio)}for(y=0;y<2;++y){b=(p+1+y)%3,x=(p+1+(1^y))%3;this.zeroEnable[x]&&a[0][x]<=0&&a[1][x]>=0&&this._lines.drawZero(b,x,this.bounds,m,this.zeroLineColor[x],this.zeroLineWidth[x]*this.pixelRatio)}}for(p=0;p<3;++p){this.lineEnable[p]&&this._lines.drawAxisLine(p,this.bounds,g[p].primalOffset,this.lineColor[p],this.lineWidth[p]*this.pixelRatio),this.lineMirror[p]&&this._lines.drawAxisLine(p,this.bounds,g[p].mirrorOffset,this.lineColor[p],this.lineWidth[p]*this.pixelRatio);var _=cM(yM,g[p].primalMinor),w=cM(bM,g[p].mirrorMinor),M=this.lineTickLength;for(y=0;y<3;++y){var A=d/r[5*y];_[y]*=M[y]*A,w[y]*=M[y]*A}this.lineTickEnable[p]&&this._lines.drawAxisTicks(p,g[p].primalOffset,_,this.lineTickColor[p],this.lineTickWidth[p]*this.pixelRatio),this.lineTickMirror[p]&&this._lines.drawAxisTicks(p,g[p].mirrorOffset,w,this.lineTickColor[p],this.lineTickWidth[p]*this.pixelRatio)}this._lines.unbind(),this._text.bind(r,n,i,this.pixelRatio);for(p=0;p<3;++p){var T=g[p].primalMinor,k=cM(xM,g[p].primalOffset);for(y=0;y<3;++y)this.lineTickEnable[p]&&(k[y]+=d*T[y]*Math.max(this.lineTickLength[y],0)/r[5*y]);if(this.tickEnable[p]){for(y=0;y<3;++y)k[y]+=d*T[y]*this.tickPad[y]/r[5*y];this._text.drawTicks(p,this.tickSize[p],this.tickAngle[p],k,this.tickColor[p])}if(this.labelEnable[p]){for(y=0;y<3;++y)k[y]+=d*T[y]*this.labelPad[y]/r[5*y];k[p]+=.5*(a[0][p]+a[1][p]),this._text.drawLabel(p,this.labelSize[p],this.labelAngle[p],k,this.labelColor[p])}}this._text.unbind()},fM.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null};var _M=function(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]};var wM=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t};var MM=function(t,e,r,n,i){var a=e.model||AM,o=e.view||AM,s=e.projection||AM,l=t.bounds,u=(i=i||Nm(a,o,s,l)).axis;i.edges;dd(TM,o,a),dd(TM,s,TM);for(var c=SM,h=0;h<3;++h)c[h].lo=1/0,c[h].hi=-1/0,c[h].pixelsPerDataUnit=1/0;var f=_M(rd(TM,TM));rd(TM,TM);for(var d=0;d<3;++d){var p=(d+1)%3,g=(d+2)%3,v=PM;t:for(var h=0;h<2;++h){var m=[];if(u[d]<0!=!!h){v[d]=l[h][d];for(var y=0;y<2;++y){v[p]=l[y^h][p];for(var b=0;b<2;++b)v[g]=l[b^y^h][g],m.push(v.slice())}for(var y=0;yi||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var a=UM(n,e.stride.slice()),o=0;"float32"===r?o=t.FLOAT:"float64"===r?(o=t.FLOAT,a=!1,r="float32"):"uint8"===r?o=t.UNSIGNED_BYTE:(o=t.UNSIGNED_BYTE,a=!1,r="uint8");var s,l,u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=Ip(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}o!==t.FLOAT||t.getExtension("OES_texture_float")||(o=t.UNSIGNED_BYTE,a=!1);var c=e.size;if(a)s=0===e.offset&&e.data.length===c?e.data:e.data.subarray(e.offset,e.offset+c);else{var h=[n[2],n[2]*n[0],1];l=Og.malloc(c,r);var f=Ip(l,n,h,0);"float32"!==r&&"float64"!==r||o!==t.UNSIGNED_BYTE?vp.assign(f,e):zM(f,e),s=l.subarray(0,c)}var d=VM(t);t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,o,s),a||Og.free(l);return new jM(t,d,n[0],n[1],u,o)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")},OM=null,IM=null,NM=null;function DM(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var zM=function(t,e){vp.muls(t,e,255)};function FM(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function jM(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}var BM=jM.prototype;function UM(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function VM(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function HM(t,e,r,n,i){var a=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=VM(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new jM(t,o,e,r,n,i)}Object.defineProperties(BM,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&OM.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),IM.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&OM.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),IM.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),NM.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),NM.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(NM.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return FM(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return FM(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,FM(this,this._shape[0],t),t}}}),BM.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},BM.dispose=function(){this.gl.deleteTexture(this.handle)},BM.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},BM.setPixels=function(t,e,r,n){var i=this.gl;this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0;var a=DM(t)?t:t.raw;if(a){this._mipLevels.indexOf(n)<0?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,a),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,a)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,n,i,a,o,s){var l=s.dtype,u=s.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var c=0,h=0,f=UM(u,s.stride.slice());"float32"===l?c=t.FLOAT:"float64"===l?(c=t.FLOAT,f=!1,l="float32"):"uint8"===l?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,f=!1,l="uint8");if(2===u.length)h=t.LUMINANCE,u=[u[0],u[1],1],s=Ip(s.data,u,[s.stride[0],s.stride[1],1],s.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])h=t.ALPHA;else if(2===u[2])h=t.LUMINANCE_ALPHA;else if(3===u[2])h=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}u[2]}h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i);if(h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=s.size,p=o.indexOf(n)<0;p&&o.push(n);if(c===a&&f)0===s.offset&&s.data.length===d?p?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data):p?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data.subarray(s.offset,s.offset+d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data.subarray(s.offset,s.offset+d));else{var g;g=a===t.FLOAT?Og.mallocFloat32(d):Og.mallocUint8(d);var v=Ip(g,u,[u[2],u[2]*u[0],1]);c===t.FLOAT&&a===t.UNSIGNED_BYTE?zM(v,s):vp.assign(v,s),p?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,g.subarray(0,d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,g.subarray(0,d)),a===t.FLOAT?Og.freeFloat32(g):Og.freeUint8(g)}}(i,e,r,n,this.format,this.type,this._mipLevels,t)}};var qM,GM,XM,WM,YM=function(t,e,r,n){qM||(qM=t.FRAMEBUFFER_UNSUPPORTED,GM=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,XM=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,WM=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var i=t.getExtension("WEBGL_draw_buffers");!ZM&&i&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);ZM=new Array(r+1);for(var n=0;n<=r;++n){for(var i=new Array(r),a=0;aa||r<0||r>a)throw new Error("gl-fbo: Parameters are too large for FBO");var o=1;if("color"in(n=n||{})){if((o=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(o>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(o>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+o+" draw buffers")}}var s=t.UNSIGNED_BYTE,l=t.getExtension("OES_texture_float");if(n.float&&o>0){if(!l)throw new Error("gl-fbo: Context does not support floating point textures");s=t.FLOAT}else n.preferFloat&&o>0&&l&&(s=t.FLOAT);var u=!0;"depth"in n&&(u=!!n.depth);var c=!1;"stencil"in n&&(c=!!n.stencil);return new eA(t,e,r,s,o,u,c,i)},ZM=null;function QM(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function KM(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function $M(t){switch(t){case qM:throw new Error("gl-fbo: Framebuffer unsupported");case GM:throw new Error("gl-fbo: Framebuffer incomplete attachment");case XM:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case WM:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function JM(t,e,r,n,i,a){if(!n)return null;var o=RM(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function tA(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function eA(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var l=0;l1&&s.drawBuffersWEBGL(ZM[o]);var f=r.getExtension("WEBGL_depth_texture");f?l?t.depth=JM(r,i,a,f.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u&&(t.depth=JM(r,i,a,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):u&&l?t._depth_rb=tA(r,i,a,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u?t._depth_rb=tA(r,i,a,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):l&&(t._depth_rb=tA(r,i,a,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var d=r.checkFramebufferStatus(r.FRAMEBUFFER);if(d!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),h=0;hi||r<0||r>i)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var a=QM(n),o=0;othis.buffer.length){Og.free(this.buffer);for(var n=this.buffer=Og.mallocUint8(cA(r*e*4)),i=0;i0&&0===v[e-1];)v.pop(),m.pop().dispose()}window.addEventListener("resize",k),A.update=function(t){e||(t=t||{},y=!0,b=!0)},A.add=function(t){e||(t.axes=h,p.push(t),g.push(-1),y=!0,b=!0,E())},A.remove=function(t){if(!e){var r=p.indexOf(t);r<0||(p.splice(r,1),g.pop(),y=!0,b=!0,E())}},A.dispose=function(){if(!e&&(e=!0,window.removeEventListener("resize",k),r.removeEventListener("webglcontextlost",S),A.mouseListener.enabled=!1,!A.contextLost)){h.dispose(),d.dispose();for(var t=0;to.distance)continue;for(var h=0;h0){r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function EA(t){return"boolean"!=typeof t||t}var LA=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,i=e;try{var a=[t];0===t.indexOf("webgl")&&a.push("experimental-"+t);for(var o=0;or?r:t:te?e:t};var OA={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]},IA=function(){for(var t=0;t10&&/[0-9](?:\s|\/)/.test(r)&&(a=r.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),i=r.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof r)i="rgb",a=[r>>>16,(65280&r)>>>8,255&r];else if(DA(r)){var h=IA(r.r,r.red,r.R,null);null!==h?(i="rgb",a=[h,IA(r.g,r.green,r.G),IA(r.b,r.blue,r.B)]):(i="hsl",a=[IA(r.h,r.hue,r.H),IA(r.s,r.saturation,r.S),IA(r.l,r.lightness,r.L,r.b,r.brightness)]),o=IA(r.a,r.alpha,r.opacity,1),null!=r.opacity&&(o/=100)}else(Array.isArray(r)||t.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(r))&&(a=[r[0],r[1],r[2]],i="rgb",o=4===r.length?r[3]:1);return{space:i,values:a,alpha:o}};var e={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var FA=function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[a=255*l,a,a];e=2*l-(r=l<.5?l*(1+s):l+s-l*s),i=[0,0,0];for(var u=0;u<3;u++)(n=o+1/3*-(u-1))<0?n++:n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[u]=255*a;return i},jA=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=function(t){switch(t){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}}(e),n=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(n.set(t),n);var i="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:255,i&&(n[0]/=255,n[1]/=255,n[2]/=255,n[3]/=255),n):(t.length&&"string"!=typeof t||((t=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=zA(t);return r.space?((e=Array(3))[0]=RA(r.values[0],0,255),e[1]=RA(r.values[1],0,255),e[2]=RA(r.values[2],0,255),"h"===r.space[0]&&(e=FA(e)),e.push(RA(r.alpha,0,1)),e):[]}(t))[0]/=255,t[1]/=255,t[2]/=255),i?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:1):(n[0]=RA(Math.round(255*t[0]),0,255),n[1]=RA(Math.round(255*t[1]),0,255),n[2]=RA(Math.round(255*t[2]),0,255),n[3]=null==t[3]?255:RA(Math.floor(255*t[3]),0,255)),n)};var BA=function(t){return t?jA(t):[0,0,0,1]},UA=function(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]);"zoomMin"in e&&(r[0]=e.zoomMin);"zoomMax"in e&&(r[1]=e.zoomMax);var n=Qd({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0,o=t.clientWidth,s=t.clientHeight,l={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=lp(),r=this.delay,l=e-2*r;n.idle(e-r),n.recalcMatrix(l),n.flush(e-(100+2*r));for(var u=!0,c=n.computedMatrix,h=0;h<16;++h)u=u&&i[h]===c[h],i[h]=c[h];var f=t.clientWidth===o&&t.clientHeight===s;return o=t.clientWidth,s=t.clientHeight,u?!f:(a=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(l,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),i=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var a=lp();n._active.lookAt(a,r,i,e),n._active.lookAt(a+500,r,i,[0,0,1]),n._active.flush(a)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return a},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var u=0,c=0,h={shift:!1,control:!1,alt:!1,meta:!1};function f(e,r,i,o){var s=l.keyBindingMode;if(!1!==s){var f="rotate"===s,d="pan"===s,p="zoom"===s,g=!!o.control,v=!!o.alt,m=!!o.shift,y=!!(1&e),b=!!(2&e),x=!!(4&e),_=1/t.clientHeight,w=_*(r-u),M=_*(i-c),A=l.flipX?1:-1,T=l.flipY?1:-1,k=lp(),E=Math.PI*l.rotateSpeed;if((f&&y&&!g&&!v&&!m||y&&!g&&!v&&m)&&n.rotate(k,A*E*w,-T*E*M,0),(d&&y&&!g&&!v&&!m||b||y&&g&&!v&&!m)&&n.pan(k,-l.translateSpeed*w*a,l.translateSpeed*M*a,0),p&&y&&!g&&!v&&!m||x||y&&!g&&v&&!m){var L=-l.zoomSpeed*M/window.innerHeight*(k-n.lastT())*100;n.pan(k,0,0,a*(Math.exp(L)-1))}return u=r,c=i,h=o,!0}}return l.mouseListener=ep(t,f),t.addEventListener("touchstart",function(e){var r=qe(e.changedTouches[0],t);f(0,r[0],r[1],h),f(1,r[0],r[1],h),e.preventDefault()},!!Ve&&{passive:!1}),t.addEventListener("touchmove",function(e){var r=qe(e.changedTouches[0],t);f(1,r[0],r[1],h),e.preventDefault()},!!Ve&&{passive:!1}),t.addEventListener("touchend",function(t){f(0,u,c,h),t.preventDefault()},!!Ve&&{passive:!1}),l.wheelListener=sp(t,function(t,e){if(!1!==l.keyBindingMode){var r=l.flipX?1:-1,i=l.flipY?1:-1,o=lp();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*l.rotateSpeed/window.innerWidth);else{var s=-l.zoomSpeed*i*e/window.innerHeight*(o-n.lastT())/20;n.pan(o,0,0,a*(Math.exp(s)-1))}}},!0),l};var VA=function(t){return t.split("").map(function(t){return t in HA?HA[t]:""}).join("")},HA={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"};var qA=function(t){return""+function(t){for(var e=zr.entityToUnicode,r=0;(r=t.indexOf("&",r))>=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))},GA=["xaxis","yaxis","zaxis"];function XA(){this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.tickEnable=[!0,!0,!0],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=[!0,!0,!0],this.labelFont=["Open Sans","Open Sans","Open Sans"],this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[30,30,30],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],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=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!0,!0,!0],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._defaultTickPad=this.tickPad.slice(),this._defaultLabelPad=this.labelPad.slice(),this._defaultLineTickLength=this.lineTickLength.slice()}XA.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[GA[e]];r.visible?(this.labels[e]=qA(r.title),"titlefont"in r&&(r.titlefont.color&&(this.labelColor[e]=BA(r.titlefont.color)),r.titlefont.family&&(this.labelFont[e]=r.titlefont.family),r.titlefont.size&&(this.labelSize[e]=r.titlefont.size)),"showline"in r&&(this.lineEnable[e]=r.showline),"linecolor"in r&&(this.lineColor[e]=BA(r.linecolor)),"linewidth"in r&&(this.lineWidth[e]=r.linewidth),"showgrid"in r&&(this.gridEnable[e]=r.showgrid),"gridcolor"in r&&(this.gridColor[e]=BA(r.gridcolor)),"gridwidth"in r&&(this.gridWidth[e]=r.gridwidth),"log"===r.type?this.zeroEnable[e]=!1:"zeroline"in r&&(this.zeroEnable[e]=r.zeroline),"zerolinecolor"in r&&(this.zeroLineColor[e]=BA(r.zerolinecolor)),"zerolinewidth"in r&&(this.zeroLineWidth[e]=r.zerolinewidth),"ticks"in r&&r.ticks?this.lineTickEnable[e]=!0:this.lineTickEnable[e]=!1,"ticklen"in r&&(this.lineTickLength[e]=this._defaultLineTickLength[e]=r.ticklen),"tickcolor"in r&&(this.lineTickColor[e]=BA(r.tickcolor)),"tickwidth"in r&&(this.lineTickWidth[e]=r.tickwidth),"tickangle"in r&&(this.tickAngle[e]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180),"showticklabels"in r&&(this.tickEnable[e]=r.showticklabels),"tickfont"in r&&(r.tickfont.color&&(this.tickColor[e]=BA(r.tickfont.color)),r.tickfont.family&&(this.tickFont[e]=r.tickfont.family),r.tickfont.size&&(this.tickSize[e]=r.tickfont.size)),"mirror"in r?-1!==["ticks","all","allticks"].indexOf(r.mirror)?(this.lineTickMirror[e]=!0,this.lineMirror[e]=!0):!0===r.mirror?(this.lineTickMirror[e]=!1,this.lineMirror[e]=!0):(this.lineTickMirror[e]=!1,this.lineMirror[e]=!1):this.lineMirror[e]=!1,"showbackground"in r&&!1!==r.showbackground?(this.backgroundEnable[e]=!0,this.backgroundColor[e]=BA(r.backgroundcolor)):this.backgroundEnable[e]=!1):(this.tickEnable[e]=!1,this.labelEnable[e]=!1,this.lineEnable[e]=!1,this.lineTickEnable[e]=!1,this.gridEnable[e]=!1,this.zeroEnable[e]=!1,this.backgroundEnable[e]=!1)}};var WA=function(t){var e=new XA;return e.merge(t),e},YA=["xaxis","yaxis","zaxis"];function ZA(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}ZA.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[YA[e]];r.visible?(this.enabled[e]=r.showspikes,this.colors[e]=BA(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness):(this.enabled[e]=!1,this.drawSides[e]=!1)}};var QA,KA,$A=function(t){var e=new ZA;return e.merge(t),e},JA=function(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,n=t.fullSceneLayout,i=[[],[],[]],a=0;a<3;++a){var o=n[tT[a]];if(o._length=(r[a].hi-r[a].lo)*r[a].pixelsPerDataUnit/t.dataScale[a],Math.abs(o._length)===1/0)i[a]=[];else{o._input_range=o.range.slice(),o.range[0]=r[a].lo/t.dataScale[a],o.range[1]=r[a].hi/t.dataScale[a],o._m=1/(t.dataScale[a]*r[a].pixelsPerDataUnit),o.range[0]===o.range[1]&&(o.range[0]-=1,o.range[1]+=1);var s=o.tickmode;if("auto"===o.tickmode){o.tickmode="linear";var l=o.nticks||re.constrain(o._length/40,4,9);Ki.autoTicks(o,Math.abs(o.range[1]-o.range[0])/l)}for(var u=Ki.calcTicks(o),c=0;ch[1][o]?f[o]=1:h[1][o]===h[0][o]?f[o]=1:f[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=f,this.convertAnnotations(this),a=0;ap[1][a])p[0][a]=-1,p[1][a]=1;else{var M=p[1][a]-p[0][a];p[0][a]-=M/32,p[1][a]+=M/32}}else{var A=s.range;p[0][a]=s.r2l(A[0]),p[1][a]=s.r2l(A[1])}p[0][a]===p[1][a]&&(p[0][a]-=1,p[1][a]+=1),g[a]=p[1][a]-p[0][a],this.glplot.bounds[0][a]=p[0][a]*f[a],this.glplot.bounds[1][a]=p[1][a]*f[a]}var T=[1,1,1];for(a=0;a<3;++a){var k=v[l=(s=u[aT[a]]).type];T[a]=Math.pow(k.acc,1/k.count)/f[a]}var E;if("auto"===u.aspectmode)E=Math.max.apply(null,T)/Math.min.apply(null,T)<=4?T:[1,1,1];else if("cube"===u.aspectmode)E=[1,1,1];else if("data"===u.aspectmode)E=T;else{if("manual"!==u.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var L=u.aspectratio;E=[L.x,L.y,L.z]}u.aspectratio.x=c.aspectratio.x=E[0],u.aspectratio.y=c.aspectratio.y=E[1],u.aspectratio.z=c.aspectratio.z=E[2],this.glplot.aspect=E;var C=u.domain||null,S=e._size||null;if(C&&S){var P=this.container.style;P.position="absolute",P.left=S.l+C.x[0]*S.w+"px",P.top=S.t+(1-C.y[1])*S.h+"px",P.width=S.w*(C.x[1]-C.x[0])+"px",P.height=S.h*(C.y[1]-C.y[0])+"px"}this.glplot.redraw()}},iT.destroy=function(){this.glplot&&(this.camera.mouseListener.enabled=!1,this.container.removeEventListener("wheel",this.camera.wheelListener),this.camera=this.glplot.camera=null,this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null)},iT.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),lT(this.glplot.camera)},iT.setCamera=function(t){var e;this.glplot.camera.lookAt.apply(this,[[(e=t).eye.x,e.eye.y,e.eye.z],[e.center.x,e.center.y,e.center.z],[e.up.x,e.up.y,e.up.z]])},iT.saveCamera=function(t){var e=this.getCamera(),r=re.nestedProperty(t,this.id+".camera"),n=r.get(),i=!1;function a(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}if(void 0===n)i=!0;else for(var o=0;o<3;o++)for(var s=0;s<3;s++)if(!a(e,n,o,s)){i=!0;break}return i&&r.set(e),i},iT.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},iT.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(QA),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;a1;!function(t,e,r,n){var i,a,o=n.type,s=n.attributes,l=n.handleDefaults,u=n.partition||"x",c=e._subplots[o],h=c.length;function f(t,e){return re.coerce(i,a,s,t,e)}for(var d=0;d=0;--i){var a=r,o=t[i],s=(r=a+o)-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;i>1;return["sum(",t(e.slice(0,r)),",",t(e.slice(r)),")"].join("")}(e);var n}function TT(t){return new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",AT(function(t){for(var e=new Array(t),r=0;r0&&r.push(","),r.push("[");for(var a=0;a0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(t<6?_T[t]:_T)}var ST=[function(){return[0]},function(t,e){return[[e[0]],[t[0][0]]]}];function PT(t,e){for(var r=0,n=t.length,i=0;i0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=wm[t+1];return i||(i=wm),n(i)}(t)),this.orient=i}var HT=VT.prototype;HT.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){(t=o.pop()).vertices;for(var s=t.adjacent,l=0;l<=r;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,h=0;h<=r;++h){var f=c[h];i[h]=f<0?e:a[f]}var d=this.orient();if(d>0)return u;u.lastVisited=-n,0===d&&o.push(u)}}}return null},HT.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;c<=n;++c)a[c]=i[l[c]];s.lastVisited=r;for(c=0;c<=n;++c){var h=u[c];if(!(h.lastVisited>=r)){var f=a[c];a[c]=t;var d=this.orient();if(a[c]=f,d<0){s=h;continue t}h.boundary?h.lastVisited=-r:h.lastVisited=r}}return}return s},HT.addPeaks=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=this.interior,s=this.simplices,l=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,o.push(e);for(var u=[];l.length>0;){var c=(e=l.pop()).vertices,h=e.adjacent,f=c.indexOf(r);if(!(f<0))for(var d=0;d<=n;++d)if(d!==f){var p=h[d];if(p.boundary&&!(p.lastVisited>=r)){var g=p.vertices;if(p.lastVisited!==-r){for(var v=0,m=0;m<=n;++m)g[m]<0?(v=m,a[m]=t):a[m]=i[g[m]];if(this.orient()>0){g[v]=r,p.boundary=!1,o.push(p),l.push(p),p.lastVisited=r;continue}p.lastVisited=-r}var y=p.adjacent,b=c.slice(),x=h.slice(),_=new FT(b,x,!0);s.push(_);var w=y.indexOf(e);if(!(w<0)){y[w]=_,x[f]=p,b[d]=-1,x[d]=e,h[d]=_,_.flip();for(m=0;m<=n;++m){var M=b[m];if(!(M<0||M===r)){for(var A=new Array(n-1),T=0,k=0;k<=n;++k){var E=b[k];E<0||k===m||(A[T++]=E)}u.push(new jT(A,_,m))}}}}}}u.sort(BT);for(d=0;d+1=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var h=o[0];o[0]=o[1],o[1]=h}e.push(o)}}return e};var qT=function(t,e){var r=t.length;if(0===r)return[];var n=t[0].length;if(n<1)return[];if(1===n)return function(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;a=2)return!1;t[r]=i}return!0}):m.filter(function(t){for(var e=0;e<=n;++e){var r=d[t[e]];if(r<0)return!1;t[e]=r}return!0});if(1&n)for(var o=0;o0){var o=t[r-1];if(0===QT(i,o)&&ZT(o)!==a){r-=1;continue}}t[r++]=i}}return t.length=r,t};var ek=function(t){return tk(YT(t))};var rk=function(t,e){return ek(WT(t,e))};var nk=function(t){for(var e=0,r=0,n=1;nt[r][0]&&(r=n);return er?[[r],[e]]:[[e]]};var ik=function(t){var e=t.length;if(e<3){for(var r=new Array(e),n=0;n1&&ak(t[a[u-2]],t[a[u-1]],l)<=0;)u-=1,a.pop();for(a.push(s),u=o.length;u>1&&ak(t[o[u-2]],t[o[u-1]],l)>=0;)u-=1,o.pop();o.push(s)}for(var r=new Array(o.length+a.length-2),c=0,n=0,h=a.length;n0;--f)r[c++]=o[f];return r},ak=wm[3];var ok=function(t){var e=ik(t),r=e.length;if(r<=2)return[];for(var n=new Array(r),i=e[r-1],a=0;a=e[l]&&(s+=1);a[o]=s}}return t}(i,r)}};var ck=function(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;if(0===r)return[];if(1===r)return nk(t);if(2===r)return ok(t);return uk(t,r)};var hk={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:1,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13,rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]};var fk=function(t,e,r){return t*(1-r)+e*r},dk=function(t){var e,r,n,i,a,o,s,l,u,c;t||(t={});l=(t.nshades||72)-1,s=t.format||"hex",(o=t.colormap)||(o="jet");if("string"==typeof o){if(o=o.toLowerCase(),!hk[o])throw Error(o+" not a supported colorscale");a=hk[o]}else{if(!Array.isArray(o))throw Error("unsupported colormap option",o);a=o.slice()}if(a.length>l)throw new Error(o+" map requires nshades to be at least size "+a.length);u=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:t.alpha.slice():"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1];e=a.map(function(t){return Math.round(t.index*l)}),u[0]=Math.min(Math.max(u[0],0),1),u[1]=Math.min(Math.max(u[1],0),1);var h=a.map(function(t,e){var r=a[e].index,n=a[e].rgb.slice();return 4===n.length&&n[3]>=0&&n[3]<=1?n:(n[3]=u[0]+(u[1]-u[0])*r,n)}),f=[];for(c=0;c=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h):(_=0,c>=0?(w=0,g=h):-c>=l?(w=1,g=l+2*c+h):g=c*(w=-c/l)+h);else if(w<0)w=0,u>=0?(_=0,g=h):-u>=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h;else{var M=1/x;g=(_*=M)*(o*_+s*(w*=M)+2*u)+w*(s*_+l*w+2*c)+h}else _<0?(m=l+c)>(v=s+u)?(y=m-v)>=(b=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/b)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h:(_=0,m<=0?(w=1,g=l+2*c+h):c>=0?(w=0,g=h):g=c*(w=-c/l)+h):w<0?(m=o+u)>(v=s+c)?(y=m-v)>=(b=o-2*s+l)?(w=1,_=0,g=l+2*c+h):g=(_=1-(w=y/b))*(o*_+s*w+2*u)+w*(s*_+l*w+2*c)+h:(w=0,m<=0?(_=1,g=o+2*u+h):u>=0?(_=0,g=h):g=u*(_=-u/o)+h):(y=l+c-s-u)<=0?(_=0,w=1,g=l+2*c+h):y>=(b=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/b)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h;var A=1-_-w;for(a=0;a1.0001)return null;d+=f[s]}if(Math.abs(d-1)>.001)return null;return[l,function(t,e){for(var r=[0,0,0],n=0;n 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),Ok=im(["precision mediump 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}"]),Ik=im(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]),Nk=im(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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}"]),Dk=im(["precision mediump 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}"]),zk=im(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]);kk.meshShader={vertex:Ek,fragment:Lk,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},kk.wireShader={vertex:Ck,fragment:Sk,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},kk.pointShader={vertex:Pk,fragment:Rk,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},kk.pickShader={vertex:Ok,fragment:Ik,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},kk.pointPickShader={vertex:Nk,fragment:Ik,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},kk.contourShader={vertex:Dk,fragment:zk,attributes:[{name:"position",type:"vec3"}]};var Fk={};Fk.vertexNormals=function(t,e,r){for(var n=e.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa){var x=i[u],_=1/Math.sqrt(v*y);for(b=0;b<3;++b){var w=(b+1)%3,M=(b+2)%3;x[b]+=_*(m[w]*g[M]-m[M]*g[w])}}}for(o=0;oa)for(_=1/Math.sqrt(A),b=0;b<3;++b)x[b]*=_;else for(b=0;b<3;++b)x[b]=0}return i},Fk.faceNormals=function(t,e,r){for(var n=t.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa?1/Math.sqrt(d):0;for(u=0;u<3;++u)f[u]*=d;i[o]=f}return i};var jk=32;function Bk(t){switch(t){case"uint8":return[Og.mallocUint8,Og.freeUint8];case"uint16":return[Og.mallocUint16,Og.freeUint16];case"uint32":return[Og.mallocUint32,Og.freeUint32];case"int8":return[Og.mallocInt8,Og.freeInt8];case"int16":return[Og.mallocInt16,Og.freeInt16];case"int32":return[Og.mallocInt32,Og.freeInt32];case"float32":return[Og.mallocFloat,Og.freeFloat];case"float64":return[Og.mallocDouble,Og.freeDouble];default:return null}}function Uk(t){for(var e=[],r=0;r0?i.push(["d",h,"=s",h,"-d",l,"*n",l].join("")):i.push(["d",h,"=s",h].join("")),l=h),0!=(c=t.length-1-a)&&(u>0?i.push(["e",c,"=s",c,"-e",u,"*n",u,",f",c,"=",o[c],"-f",u,"*n",u].join("")):i.push(["e",c,"=s",c,",f",c,"=",o[c]].join("")),u=c)}r.push("var "+i.join(","));var f=["0","n0-1","data","offset"].concat(Uk(t.length));r.push(["if(n0<=",jk,"){","insertionSort(",f.join(","),")}else{","quickSort(",f.join(","),")}"].join("")),r.push("}return "+n);var d=new Function("insertionSort","quickSort",r.join("\n")),p=function(t,e){var r=["'use strict'"],n=["ndarrayInsertionSort",t.join("d"),e].join(""),i=["left","right","data","offset"].concat(Uk(t.length)),a=Bk(e),o=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var s=[],l=1;l1){for(r.push("dptr=0;sptr=ptr"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"b){break __l}"].join("")),l=t.length-1;l>=1;--l)r.push("sptr+=e"+l,"dptr+=f"+l,"}");for(r.push("dptr=cptr;sptr=cptr-s0"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"scratch)){",c("cptr",u("cptr-s0")),"cptr-=s0","}",c("cptr","scratch"));return r.push("}"),t.length>1&&a&&r.push("free(scratch)"),r.push("} return "+n),a?new Function("malloc","free",r.join("\n"))(a[0],a[1]):new Function(r.join("\n"))()}(t,e);return d(p,function(t,e,r){var n=["'use strict'"],i=["ndarrayQuickSort",t.join("d"),e].join(""),a=["left","right","data","offset"].concat(Uk(t.length)),o=Bk(e),s=0;n.push(["function ",i,"(",a.join(","),"){"].join(""));var l=["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","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var u=[],c=1;c=0;--a)0!==(o=t[a])&&n.push(["for(i",o,"=0;i",o,"1)for(a=0;a1?n.push("ptr_shift+=d"+o):n.push("ptr0+=d"+o),n.push("}"))}}function g(e,r,i,a){if(1===r.length)n.push("ptr0="+h(r[0]));else{for(var o=0;o1)for(o=0;o=1;--o)i&&n.push("pivot_ptr+=f"+o),r.length>1?n.push("ptr_shift+=e"+o):n.push("ptr0+=e"+o),n.push("}")}function v(){t.length>1&&o&&n.push("free(pivot1)","free(pivot2)")}function m(e,r){var i="el"+e,a="el"+r;if(t.length>1){var o="__l"+ ++s;g(o,[i,a],!1,["comp=",f("ptr0"),"-",f("ptr1"),"\n","if(comp>0){tmp0=",i,";",i,"=",a,";",a,"=tmp0;break ",o,"}\n","if(comp<0){break ",o,"}"].join(""))}else n.push(["if(",f(h(i)),">",f(h(a)),"){tmp0=",i,";",i,"=",a,";",a,"=tmp0}"].join(""))}function y(e,r){t.length>1?p([e,r],!1,d("ptr0",f("ptr1"))):n.push(d(h(e),f(h(r))))}function b(e,r,i){if(t.length>1){var a="__l"+ ++s;g(a,[r],!0,[e,"=",f("ptr0"),"-pivot",i,"[pivot_ptr]\n","if(",e,"!==0){break ",a,"}"].join(""))}else n.push([e,"=",f(h(r)),"-pivot",i].join(""))}function x(e,r){t.length>1?p([e,r],!1,["tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1","tmp")].join("")):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1","tmp")].join(""))}function _(e,r,i){t.length>1?(p([e,r,i],!1,["tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1",f("ptr2")),"\n",d("ptr2","tmp")].join("")),n.push("++"+r,"--"+i)):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","ptr2=",h(i),"\n","++",r,"\n","--",i,"\n","tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1",f("ptr2")),"\n",d("ptr2","tmp")].join(""))}function w(t,e){x(t,e),n.push("--"+e)}function M(e,r,i){t.length>1?p([e,r],!0,[d("ptr0",f("ptr1")),"\n",d("ptr1",["pivot",i,"[pivot_ptr]"].join(""))].join("")):n.push(d(h(e),f(h(r))),d(h(r),"pivot"+i))}function A(e,r){n.push(["if((",r,"-",e,")<=",jk,"){\n","insertionSort(",e,",",r,",data,offset,",Uk(t.length).join(","),")\n","}else{\n",i,"(",e,",",r,",data,offset,",Uk(t.length).join(","),")\n","}"].join(""))}function T(e,r,i){t.length>1?(n.push(["__l",++s,":while(true){"].join("")),p([e],!0,["if(",f("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",s,"}"].join("")),n.push(i,"}")):n.push(["while(",f(h(e)),"===pivot",r,"){",i,"}"].join(""))}return n.push("var "+l.join(",")),m(1,2),m(4,5),m(1,3),m(2,3),m(1,4),m(3,4),m(2,5),m(2,3),m(4,5),t.length>1?p(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",f("ptr1"),"\n","pivot2[pivot_ptr]=",f("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",f("ptr0"),"\n","y=",f("ptr2"),"\n","z=",f("ptr4"),"\n",d("ptr5","x"),"\n",d("ptr6","y"),"\n",d("ptr7","z")].join("")):n.push(["pivot1=",f(h("el2")),"\n","pivot2=",f(h("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",f(h("el1")),"\n","y=",f(h("el3")),"\n","z=",f(h("el5")),"\n",d(h("index1"),"x"),"\n",d(h("index3"),"y"),"\n",d(h("index5"),"z")].join("")),y("index2","left"),y("index4","right"),n.push("if(pivots_are_equal){"),n.push("for(k=less;k<=great;++k){"),b("comp","k",1),n.push("if(comp===0){continue}"),n.push("if(comp<0){"),n.push("if(k!==less){"),x("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),n.push("while(true){"),b("comp","great",1),n.push("if(comp>0){"),n.push("great--"),n.push("}else if(comp<0){"),_("k","less","great"),n.push("break"),n.push("}else{"),w("k","great"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}else{"),n.push("for(k=less;k<=great;++k){"),b("comp_pivot1","k",1),n.push("if(comp_pivot1<0){"),n.push("if(k!==less){"),x("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),b("comp_pivot2","k",2),n.push("if(comp_pivot2>0){"),n.push("while(true){"),b("comp","great",2),n.push("if(comp>0){"),n.push("if(--greatindex5){"),T("less",1,"++less"),T("great",2,"--great"),n.push("for(k=less;k<=great;++k){"),b("comp_pivot1","k",1),n.push("if(comp_pivot1===0){"),n.push("if(k!==less){"),x("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),b("comp_pivot2","k",2),n.push("if(comp_pivot2===0){"),n.push("while(true){"),b("comp","great",2),n.push("if(comp===0){"),n.push("if(--great1&&o?new Function("insertionSort","malloc","free",n.join("\n"))(r,o[0],o[1]):new Function("insertionSort",n.join("\n"))(r)}(t,e,p))},Hk={};var qk=function(t){var e=t.order,r=t.dtype,n=[e,r].join(":"),i=Hk[n];return i||(Hk[n]=i=Vk(e,r)),i(t),t},Gk=function(t){for(var e=1<>1,v=E[2*m+1];","if(v===b){return m}","if(b0&&o.push(","),o.push("[");for(var n=0;n0&&o.push(","),o.push("B(C,E,c[",i[0],"],c[",i[1],"])")}o.push("]")}o.push(");")}}for(var n=t+1;n>1;--n){n=1},aE.isTransparent=function(){return this.opacity<1},aE.pickSlots=1,aE.setPickBase=function(t){this.pickId=t},aE.highlight=function(t){if(t&&this.contourEnable){for(var e=Qk(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=Og.mallocFloat32(6*a),s=0,l=0;l0&&((u=this.triShader).bind(),u.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind());this.edgeCount>0&&this.lineWidth>0&&((u=this.lineShader).bind(),u.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind());this.pointCount>0&&((u=this.pointShader).bind(),u.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind());this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0&&((u=this.contourShader).bind(),u.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind())},aE.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||nE,n=t.view||nE,i=t.projection||nE,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s,l={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255};((s=this.pickShader).bind(),s.uniforms=l,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0)&&((s=this.pointPickShader).bind(),s.uniforms=l,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind())},aE.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;a0)i=rk(t.alphahull,a);else{var o=["x","y","z"].indexOf(t.delaunayaxis);i=qT(a.map(function(t){return[t[(o+1)%3],t[(o+2)%3]]}))}var l={positions:a,cells:i,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:BA(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",l.vertexIntensity=t.intensity,l.vertexIntensityBounds=[t.cmin,t.cmax],l.colormap=t.colorscale.map(function(t){var e=t[0],r=s(t[1]).toRgb();return{index:e,rgb:[r.r,r.g,r.b,1]}})):t.vertexcolor?(this.color=t.vertexcolor[0],l.vertexColors=dE(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],l.cellColors=dE(t.facecolor)):(this.color=t.color,l.meshColor=BA(t.color)),this.mesh.update(l)},fE.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()};var gE=function(t,e){var r=t.glplot.gl,n=cE({gl:r}),i=new hE(t,n,e.uid);return n._trace=i,i.update(e),t.glplot.add(n),i},vE={};vE.attributes=bT,vE.supplyDefaults=function(t,e,r,n){function i(r,n){return re.coerce(t,e,bT,r,n)}function a(t){var e=t.map(function(t){var e=i(t);return e&&re.isArrayOrTypedArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var o=a(["x","y","z"]),s=a(["i","j","k"]);o?(s&&s.forEach(function(t){for(var e=0;e=1},OE.isTransparent=function(){return this.opacity<1},OE.drawTransparent=OE.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||PE,i=r.projection=t.projection||PE;r.model=t.model||PE,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var c=0;c<3;++c)e.lineWidth(this.lineWidth[c]),r.capSize=this.capSize[c]*u,this.lineCount[c]&&e.drawArrays(e.LINES,this.lineOffset[c],this.lineCount[c]);this.vao.unbind()};var NE=function(){for(var t=new Array(3),e=0;e<3;++e){for(var r=[],n=1;n<=2;++n)for(var i=-1;i<=1;i+=2){var a=[0,0,0];a[(n+e)%3]=i,r.push(a)}t[e]=r}return t}();function DE(t,e,r,n){for(var i=NE[n],a=0;a0)(d=u.slice())[s]+=h[1][s],i.push(u[0],u[1],u[2],f[0],f[1],f[2],f[3],0,0,0,d[0],d[1],d[2],f[0],f[1],f[2],f[3],0,0,0),IE(this.bounds,d),o+=2+DE(i,d,f,s)}}this.lineCount[s]=o-this.lineOffset[s]}this.buffer.update(i)}},OE.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()};var zE={},FE=im(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]),jE=im(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]),BE=im(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]),UE=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];zE.createShader=function(t){return nm(t,FE,jE,null,UE)},zE.createPickShader=function(t){return nm(t,FE,BE,null,UE)};var VE=function(t,e,r,n){return HE[0]=n,HE[1]=r,HE[2]=e,HE[3]=t,qE[0]},HE=new Uint8Array(4),qE=new Float32Array(HE.buffer);var GE=function(t){var e=t.gl||t.scene&&t.scene.gl,r=XE(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=WE(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=jg(e),a=Xg(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),o=Ip(new Array(1024),[256,1,4]),s=0;s<1024;++s)o.data[s]=255;var l=RM(e,o);l.wrap=e.REPEAT;var u=new $E(e,r,n,i,a,l);return u.update(t),u},XE=zE.createShader,WE=zE.createPickShader,YE=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function ZE(t,e){for(var r=0,n=0;n<3;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function QE(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;r<3;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function KE(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function $E(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}var JE=$E.prototype;JE.isTransparent=function(){return this.opacity<1},JE.isOpaque=function(){return this.opacity>=1},JE.pickSlots=1,JE.setPickBase=function(t){this.pickId=t},JE.drawTransparent=JE.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||YE,view:t.view||YE,projection:t.projection||YE,clipBounds:QE(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},JE.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||YE,view:t.view||YE,projection:t.projection||YE,pickId:this.pickId,clipBounds:QE(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},JE.update=function(t){var e,r;this.dirty=!0;var n=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var i=t.position||t.positions;if(i){var a=t.color||t.colors||[0,0,0,1],o=t.lineWidth||1,s=[],l=[],u=[],c=0,h=0,f=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],d=!1;t:for(e=1;e0){for(var b=0;b<24;++b)s.push(s[s.length-12]);h+=2,d=!0}continue t}f[0][r]=Math.min(f[0][r],m[r],y[r]),f[1][r]=Math.max(f[1][r],m[r],y[r])}Array.isArray(a[0])?(p=a[e-1],g=a[e]):p=g=a,3===p.length&&(p=[p[0],p[1],p[2],1]),3===g.length&&(g=[g[0],g[1],g[2],1]),v=Array.isArray(o)?o[e-1]:o;var x=c;if(c+=ZE(m,y),d){for(r=0;r<2;++r)s.push(m[0],m[1],m[2],y[0],y[1],y[2],x,v,p[0],p[1],p[2],p[3]);h+=2,d=!1}s.push(m[0],m[1],m[2],y[0],y[1],y[2],x,v,p[0],p[1],p[2],p[3],m[0],m[1],m[2],y[0],y[1],y[2],x,-v,p[0],p[1],p[2],p[3],y[0],y[1],y[2],m[0],m[1],m[2],c,-v,g[0],g[1],g[2],g[3],y[0],y[1],y[2],m[0],m[1],m[2],c,v,g[0],g[1],g[2],g[3]),h+=4}if(this.buffer.update(s),l.push(c),u.push(i[i.length-1].slice()),this.bounds=f,this.vertexCount=h,this.points=u,this.arcLength=l,"dashes"in t){var _=t.dashes.slice();for(_.unshift(0),e=1;e<_.length;++e)_[e]=_[e-1]+_[e];var w=Ip(new Array(1024),[256,1,4]);for(e=0;e<256;++e){for(r=0;r<4;++r)w.set(e,0,r,0);1&Vf.le(_,_[_.length-1]*e/255)?w.set(e,0,0,0):w.set(e,0,0,255)}this.texture.setPixels(w)}}},JE.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},JE.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=VE(t.value[0],t.value[1],t.value[2],0),r=Vf.le(this.arcLength,e);if(r<0)return null;if(r===this.arcLength.length-1)return new KE(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],a=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),o=1-a,s=[0,0,0],l=0;l<3;++l)s[l]=o*n[l]+a*i[l];var u=Math.min(a<.5?r:r+1,this.points.length-1);return new KE(e,s,u,this.points[u])};var tL=function(t,e){var r=eL[e];r||(r=eL[e]={});if(t in r)return r[t];for(var n=rM(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),i=rM(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),a=[[1/0,1/0],[-1/0,-1/0]],o=0;o=1)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var wL=[0,0],ML=[0,0,0],AL=[0,0,0],TL=[0,0,0,1],kL=[0,0,0,1],EL=vL.slice(),LL=[0,0,0],CL=[[0,0,0],[0,0,0]];function SL(t){return t[0]=t[1]=t[2]=0,t}function PL(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function RL(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function OL(t,e,r,n,i){var a,o=e.axesProject,s=e.gl,l=t.uniforms,u=r.model||vL,c=r.view||vL,h=r.projection||vL,f=e.axesBounds,d=function(t){for(var e=CL,r=0;r<2;++r)for(var n=0;n<3;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}(e.clipBounds);a=e.axes&&e.axes.lastCubeProps?e.axes.lastCubeProps.axis:[1,1,1],wL[0]=2/s.drawingBufferWidth,wL[1]=2/s.drawingBufferHeight,t.bind(),l.view=c,l.projection=h,l.screenSize=wL,l.highlightId=e.highlightId,l.highlightScale=e.highlightScale,l.clipBounds=d,l.pickGroup=e.pickId/255,l.pixelRatio=e.pixelRatio;for(var p=0;p<3;++p)if(o[p]&&e.projectOpacity[p]<1===n){l.scale=e.projectScale[p],l.opacity=e.projectOpacity[p];for(var g=EL,v=0;v<16;++v)g[v]=0;for(v=0;v<4;++v)g[5*v]=1;g[5*p]=0,a[p]<0?g[12+p]=f[0][p]:g[12+p]=f[1][p],dd(g,u,g),l.model=g;var m=(p+1)%3,y=(p+2)%3,b=SL(ML),x=SL(AL);b[m]=1,x[y]=1;var _=bL(0,0,0,PL(TL,b)),w=bL(0,0,0,PL(kL,x));if(Math.abs(_[1])>Math.abs(w[1])){var M=_;_=w,w=M,M=b,b=x,x=M;var A=m;m=y,y=A}_[0]<0&&(b[m]=-1),w[1]>0&&(x[y]=-1);var T=0,k=0;for(v=0;v<4;++v)T+=Math.pow(u[4*m+v],2),k+=Math.pow(u[4*y+v],2);b[m]/=Math.sqrt(T),x[y]/=Math.sqrt(k),l.axes[0]=b,l.axes[1]=x,l.fragClipBounds[0]=RL(LL,d[0],p,-1e8),l.fragClipBounds[1]=RL(LL,d[1],p,1e8),e.vao.draw(s.TRIANGLES,e.vertexCount),e.lineWidth>0&&(s.lineWidth(e.lineWidth),e.vao.draw(s.LINES,e.lineVertexCount,e.vertexCount))}}var IL=[[-1e8,-1e8,-1e8],[1e8,1e8,1e8]];function NL(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||vL,s.view=n.view||vL,s.projection=n.projection||vL,wL[0]=2/o.drawingBufferWidth,wL[1]=2/o.drawingBufferHeight,s.screenSize=wL,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=IL,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}OL(e,r,n,i),r.vao.unbind()}_L.draw=function(t){NL(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!1,!1)},_L.drawTransparent=function(t){NL(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!0,!1)},_L.drawPick=function(t){NL(this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader,this.pickProjectShader,this,t,!1,!0)},_L.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||e<0)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;i<3;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},_L.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},_L.update=function(t){if("perspective"in(t=t||{})&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0],l=t.glyph,u=t.color,c=t.size,h=t.angle,f=t.lineColor,d=0,p=0,g=0,v=n.length;t:for(var m=0;m0&&(L[0]=-a[0]*(1+w[0][0]));var U=x.cells,V=x.positions;for(b=0;b=0&&(u[1]+=1),l.indexOf("top")>=0&&(u[1]-=1),l.indexOf("left")>=0&&(u[0]-=1),l.indexOf("right")>=0&&(u[0]+=1),u)),r.textColor=VL(e.textfont,1,_),r.textSize=ZL(e.textfont.size,_,re.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var k=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;n<3;++n){var E=e.projection[k[n]];(r.project[n]=E.show)&&(r.projectOpacity[n]=E.opacity,r.projectScale[n]=E.scale)}r.errorBounds=qL(e,f);var L=function(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[0,0,0],i=0;i<3;i++){var a=t[i];a&&!1!==a.copy_zstyle&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=BA(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}([e.error_x,e.error_y,e.error_z]);return r.errorColor=L.color,r.errorLineWidth=L.lineWidth,r.errorCapSize=L.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=BA(e.surfacecolor),r}function KL(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}XL.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels?void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel=this.textLabels:t.textLabel="";var e=t.index=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},XL.update=function(t){var e,r,n,i,a=this.scene.glplot.gl,o=bE.solid;this.data=t;var s=QL(this.scene,t);"mode"in s&&(this.mode=s.mode),"lineDashes"in s&&s.lineDashes in bE&&(o=bE[s.lineDashes]),this.color=KL(s.scatterColor)||KL(s.lineColor),this.dataPoints=s.position,e={gl:a,position:s.position,color:s.lineColor,lineWidth:s.lineWidth||1,dashes:o[0],dashScale:o[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=GE(e),this.linePlot._trace=this,this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var l=t.opacity;if(t.marker&&t.marker.opacity&&(l*=t.marker.opacity),r={gl:a,position:s.position,color:s.scatterColor,size:s.scatterSize,glyph:s.scatterMarker,opacity:l,orthographic:!0,lineWidth:s.scatterLineWidth,lineColor:s.scatterLineColor,project:s.project,projectScale:s.projectScale,projectOpacity:s.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=mL(r),this.scatterPlot._trace=this,this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),i={gl:a,position:s.position,glyph:s.text,color:s.textColor,size:s.textSize,angle:s.textAngle,alignment:s.textOffset,font:s.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=t.hovertext||t.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(i):(this.textMarkers=mL(i),this.textMarkers._trace=this,this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:a,position:s.position,color:s.errorColor,error:s.errorBounds,lineWidth:s.errorLineWidth,capSize:s.errorCapSize,opacity:t.opacity},this.errorBars?s.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):s.errorBounds&&(this.errorBars=SE(n),this.errorBars._trace=this,this.scene.glplot.add(this.errorBars)),s.delaunayAxis>=0){var u=function(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;n=0&&i("surfacecolor",a||o);for(var s=["x","y","z"],l=0;l<3;++l){var u="projection."+s[l];i(u+".show")&&(i(u+".opacity"),i(u+".scale"))}var c=R.getComponentMethod("errorbars","supplyDefaults");c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}else e.visible=!1},JL.colorbar=af,JL.calc=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return Xh(r,e),Yh(e),r},JL.moduleType="trace",JL.name="scatter3d",JL.basePlotModule=cT,JL.categories=["gl3d","symbols","markerColorscale","showLegend"],JL.meta={};var tC=JL,eC={},rC=im(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\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 worldCoordinate = vec3(uv.zw, f.x);\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"]),nC=im(["precision mediump 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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 \u2014 in vertex or in fragment\n vec4 surfaceColor = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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"]),iC=im(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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"]),aC=im(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]);eC.createShader=function(t){var e=nm(t,rC,nC,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},eC.createPickShader=function(t){var e=nm(t,rC,aC,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},eC.createContourShader=function(t){var e=nm(t,iC,nC,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},eC.createPickContourShader=function(t){var e=nm(t,iC,aC,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e};var oC=function(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r=Rg(e.dimension,"string"==typeof r?r:"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;n=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),a.push("1"),o.push("s["+l+"]-2"));var u=".lo("+a.join()+").hi("+o.join()+")";if(0===a.length&&(u=""),i>0){n.push("if(1");for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push("&&s[",l,"]>2");n.push("){grad",i,"(src.pick(",s.join(),")",u);for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push(",dst.pick(",s.join(),",",l,")",u);n.push(");")}for(var l=0;l1){dst.set(",s.join(),",",c,",0.5*(src.get(",f.join(),")-src.get(",d.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>1){diff(",h,",src.pick(",f.join(),")",u,",src.pick(",d.join(),")",u,");}else{zero(",h,");};");break;case"mirror":0===i?n.push("dst.set(",s.join(),",",c,",0);"):n.push("zero(",h,");");break;case"wrap":var p=s.slice(),g=s.slice();e[l]<0?(p[c]="s["+c+"]-2",g[c]="0"):(p[c]="s["+c+"]-1",g[c]="1"),0===i?n.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",p.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>2){diff(",h,",src.pick(",p.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",h,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}i>0&&n.push("};")}for(var a=0;a<1<=1)return!0;for(var t=0;t<3;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},kC.pickSlots=1,kC.setPickBase=function(t){this.pickId=t};var EC=[0,0,0],LC={showSurface:!1,showContour:!1,projections:[_C.slice(),_C.slice(),_C.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]};function CC(t,e){var r,n,i,a=e.axes&&e.axes.lastCubeProps.axis||EC,o=e.showSurface,s=e.showContour;for(r=0;r<3;++r)for(o=o||e.surfaceProject[r],n=0;n<3;++n)s=s||e.contourProject[r][n];for(r=0;r<3;++r){var l=LC.projections[r];for(n=0;n<16;++n)l[n]=0;for(n=0;n<4;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],dd(l,t.model,l);var u=LC.clipBounds[r];for(i=0;i<2;++i)for(n=0;n<3;++n)u[i][n]=t.clipBounds[i][n];u[0][r]=-1e8,u[1][r]=1e8}return LC.showSurface=o,LC.showContour=s,LC}var SC={model:_C,view:_C,projection:_C,inverseModel:_C.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1,vertexColor:0},PC=_C.slice(),RC=[1,0,0,0,1,0,0,0,1];function OC(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=SC;n.model=t.model||_C,n.view=t.view||_C,n.projection=t.projection||_C,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=Hf(n.inverseModel,n.model);for(var i=0;i<2;++i)for(var a=n.clipBounds[i],o=0;o<3;++o)a[o]=Math.min(Math.max(this.clipBounds[i][o],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=RC,n.vertexColor=this.vertexColor;var s=PC;for(dd(s,n.view,n.model),dd(s,n.projection,s),Hf(s,s),i=0;i<3;++i)n.eyePosition[i]=s[12+i]/s[15];var l=s[15];for(i=0;i<3;++i)l+=this.lightPosition[i]*s[4*i+3];for(i=0;i<3;++i){var u=s[12+i];for(o=0;o<3;++o)u+=s[4*o+i]*this.lightPosition[o];n.lightPosition[i]=u/l}var c=CC(n,this);if(c.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;i<3;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=c.projections[i],this._shader.uniforms.clipBounds=c.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(c.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var f=this._contourVAO;for(f.bind(),i=0;i<3;++i)for(h.uniforms.permutation=MC[i],r.lineWidth(this.contourWidth[i]),o=0;o>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;c<2;++c)for(var h=c?a:1-a,f=0;f<2;++f)for(var d=i+c,p=s+f,g=h*(f?l:1-l),v=0;v<3;++v)u[v]+=this._field[v].get(d,p)*g;for(var m=this._pickResult.level,y=0;y<3;++y)if(m[y]=Vf.le(this.contourLevels[y],u[y]),m[y]<0)this.contourLevels[y].length>0&&(m[y]=0);else if(m[y]Math.abs(x-u[y])&&(m[y]+=1)}for(r.index[0]=a<.5?i:i+1,r.index[1]=l<.5?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],v=0;v<3;++v)r.dataCoordinate[v]=this._field[v].get(r.index[0],r.index[1]);return r},kC.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=DC(t.contourWidth,Number)),"showContour"in t&&(this.showContour=DC(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=DC(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=FC(t.contourColor)),"contourProject"in t&&(this.contourProject=DC(t.contourProject,function(t){return DC(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=FC(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=DC(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=DC(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds),"vertexColor"in t&&(this.vertexColor=t.vertexColor?1:0);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(Og.freeFloat(this._field[2].data),this._field[2].data=Og.mallocFloat(Np.nextPow2(n))),this._field[2]=Ip(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),NC(this._field[2],e),this.shape=e.shape.slice();for(var i=this.shape,a=0;a<2;++a)this._field[2].size>this._field[a].data.length&&(Og.freeFloat(this._field[a].data),this._field[a].data=Og.mallocFloat(this._field[2].size)),this._field[a]=Ip(this._field[a].data,[i[0]+2,i[1]+2]);if(t.coords){var o=t.coords;if(!Array.isArray(o)||3!==o.length)throw new Error("gl-surface: invalid coordinates for x/y");for(a=0;a<2;++a){var s=o[a];for(f=0;f<2;++f)if(s.shape[f]!==i[f])throw new Error("gl-surface: coords have incorrect shape");NC(this._field[a],s)}}else if(t.ticks){var l=t.ticks;if(!Array.isArray(l)||2!==l.length)throw new Error("gl-surface: invalid ticks");for(a=0;a<2;++a){var u=l[a];if((Array.isArray(u)||u.length)&&(u=Ip(u)),u.shape[0]!==i[a])throw new Error("gl-surface: invalid tick length");var c=Ip(u.data,i);c.stride[a]=u.stride[0],c.stride[1^a]=0,NC(this._field[a],c)}}else{for(a=0;a<2;++a){var h=[0,0];h[a]=1,this._field[a]=Ip(this._field[a].data,[i[0]+2,i[1]+2],h,0)}this._field[0].set(0,0,0);for(var f=0;f0){for(var ct=0;ct<5;++ct)q.pop();O-=1}continue t}q.push(Y[0],Y[1],K[0],K[1],Y[2]),O+=1}}W.push(O)}this._contourOffsets[G]=X,this._contourCounts[G]=W}var ht=Og.mallocFloat(q.length);for(a=0;ae?1:t>=e?0:NaN}function d(t){return null===t?NaN:+t}function p(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}e.ascending=f,e.descending=function(t,e){return et?1:e>=t?0:NaN},e.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},e.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},e.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),i=n){r=i=n;break}for(;++an&&(r=n),i1)return o/(l-1)},e.deviation=function(){var t=e.variance.apply(this,arguments);return t?Math.sqrt(t):t};var v=g(f);function m(t){return t.length}e.bisectLeft=v.left,e.bisect=e.bisectRight=v.right,e.bisector=function(t){return g(1===t.length?function(e,r){return f(t(e),r)}:t)},e.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},e.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},e.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function b(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function x(){this._=Object.create(null)}e.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=i.length)return r?r.call(n,a):t?a.sort(t):a;for(var l,u,c,h,f=-1,d=a.length,p=i[s++],g=new x;++f=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(e.map,t,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(e){return t=e,n},n.rollup=function(t){return r=t,n},n},e.set=function(t){var e=new S;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},e.event=null,e.requote=function(t){return t.replace(U,"\\$&")};var U=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,V={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function H(t){return V(t,W),t}var q=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},X=function(t,e){var r=t.matches||t[O(t,"matchesSelector")];return(X=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(q=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,X=Sizzle.matchesSelector),e.selection=function(){return e.select(i.documentElement)};var W=e.selection.prototype=[];function Y(t){return"function"==typeof t?t:function(){return q(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}W.select=function(t){var e,r,n,i,a=[];t=Y(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},W.attr=function(t,r){if(arguments.length<2){if("string"==typeof t){var n=this.node();return(t=e.ns.qualify(t)).local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(r in t)this.each($(r,t[r]));return this}return this.each($(t,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=f);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(t=t.slice(0,o));var l=pt.get(t);function u(){var e=this[a];e&&(this.removeEventListener(t,e,e.$),delete this[a])}return l&&(t=l,s=vt),o?r?function(){var e=s(r,n(arguments));u.call(this),this.addEventListener(t,this[a]=e,e.$=i),e._=r}:u:r?N:function(){var r,n=new RegExp("^__on([^.]+)"+e.requote(t)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}e.selection.enter=ht,e.selection.enter.prototype=ft,ft.append=W.append,ft.empty=W.empty,ft.node=W.node,ft.call=W.call,ft.size=W.size,ft.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s=n&&(n=e+1);!(o=s[n])&&++n0?1:t<0?-1:0}function Rt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function Ot(t){return t>1?0:t<-1?Tt:Math.acos(t)}function It(t){return t>1?Lt:t<-1?-Lt:Math.asin(t)}function Nt(t){return((t=Math.exp(t))+1/t)/2}function Dt(t){return(t=Math.sin(t/2))*t}var zt=Math.SQRT2;e.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,h=l-a,f=c*c+h*h;if(f0&&(t=t.transition().duration(g)),t.call(w.event)}function E(){u&&u.domain(l.range().map(function(t){return(t-f.x)/f.k}).map(l.invert)),h&&h.domain(c.range().map(function(t){return(t-f.y)/f.k}).map(c.invert))}function L(t){v++||t({type:"zoomstart"})}function C(t){E(),t({type:"zoom",scale:f.k,translate:[f.x,f.y]})}function S(t){--v||(t({type:"zoomend"}),r=null)}function P(){var t=this,r=_.of(t,arguments),n=0,i=e.select(o(t)).on(y,function(){n=1,T(e.mouse(t),a),C(r)}).on(b,function(){i.on(y,null).on(b,null),s(n),S(r)}),a=M(e.mouse(t)),s=bt(t);ss.call(t),L(r)}function R(){var t,r=this,n=_.of(r,arguments),i={},a=0,o=".zoom-"+e.event.changedTouches[0].identifier,l="touchmove"+o,u="touchend"+o,c=[],h=e.select(r),d=bt(r);function p(){var n=e.touches(r);return t=f.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=M(t))}),n}function g(){var t=e.event.target;e.select(t).on(l,v).on(u,y),c.push(t);for(var n=e.event.changedTouches,o=0,h=n.length;o1){m=d[0];var b=d[1],x=m[0]-b[0],_=m[1]-b[1];a=x*x+_*_}}function v(){var o,l,u,c,h=e.touches(r);ss.call(r);for(var f=0,d=h.length;f360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Gt(t,r,n){return this instanceof Gt?(this.h=+t,this.c=+r,void(this.l=+n)):arguments.length<2?t instanceof Gt?new Gt(t.h,t.c,t.l):ee(t instanceof Yt?t.l:(t=fe((t=e.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new Gt(t,r,n)}Ht.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,this.l/t)},Ht.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Vt(this.h,this.s,t*this.l)},Ht.rgb=function(){return qt(this.h,this.s,this.l)},e.hcl=Gt;var Xt=Gt.prototype=new Ut;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Yt(r,Math.cos(t*=Ct)*e,Math.sin(t)*e)}function Yt(t,e,r){return this instanceof Yt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Yt?new Yt(t.l,t.a,t.b):t instanceof Gt?Wt(t.h,t.c,t.l):fe((t=ae(t)).r,t.g,t.b):new Yt(t,e,r)}Xt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Xt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Xt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},e.lab=Yt;var Zt=18,Qt=.95047,Kt=1,$t=1.08883,Jt=Yt.prototype=new Ut;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*Qt)-1.5371385*(n=re(n)*Kt)-.4985314*(a=re(a)*$t)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*St,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ce(""+t,ae,qt):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}Jt.brighter=function(t){return new Yt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},Jt.darker=function(t){return new Yt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},Jt.rgb=function(){return te(this.l,this.a,this.b)},e.rgb=ae;var le=ae.prototype=new Ut;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(pe(i[0]),pe(i[1]),pe(i[2]))}return(a=ge.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function he(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e0&&l<1?0:n),new Vt(n,i,l)}function fe(t,e,r){var n=ne((.4124564*(t=de(t))+.3575761*(e=de(e))+.1804375*(r=de(r)))/Qt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Yt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function de(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function pe(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(o,u)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(t)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=h:u.onreadystatechange=function(){u.readyState>3&&h()},u.onprogress=function(t){var r=e.event;e.event=t;try{s.progress.call(o,u)}finally{e.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(e,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),u.open(e,t,!0),null==r||"accept"in l||(l.accept=r+",*/*"),u.setRequestHeader)for(var a in l)u.setRequestHeader(a,l[a]);return null!=r&&u.overrideMimeType&&u.overrideMimeType(r),null!=c&&(u.responseType=c),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,u),u.send(null==n?null:n),o},o.abort=function(){return u.abort(),o},e.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}ge.forEach(function(t,e){ge.set(t,oe(e))}),e.functor=ve,e.xhr=me(P),e.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ye(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,u=0,c=0;function h(){if(u>=l)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),_e=0):(_e=1,Me(Te))}function ke(){for(var t=Date.now(),e=be;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Ee(){for(var t,e=be,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});e.formatPrefix=function(t,r){var n=0;return(t=+t)&&(t<0&&(t*=-1),r&&(t=e.round(t,Le(t,r))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Ce[8+n/3]};var Se=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pe=e.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,r){return(t=e.round(t,Le(t,r))).toFixed(Math.max(0,Math.min(20,Le(t*(1+1e-15),r))))}});function Re(t){return t+""}var Oe=e.time={},Ie=Date;function Ne(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Ne.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(){De.setUTCDate.apply(this._,arguments)},setDay:function(){De.setUTCDay.apply(this._,arguments)},setFullYear:function(){De.setUTCFullYear.apply(this._,arguments)},setHours:function(){De.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){De.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){De.setUTCMinutes.apply(this._,arguments)},setMonth:function(){De.setUTCMonth.apply(this._,arguments)},setSeconds:function(){De.setUTCSeconds.apply(this._,arguments)},setTime:function(){De.setTime.apply(this._,arguments)}};var De=Date.prototype;function ze(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r1)for(;o68?1900:2e3),r+i[0].length):-1}function Qe(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Je(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,i=y(e)%60;return r+Ve(n,"0",2)+Ve(i,"0",2)}function ar(t,e,r){Ue.lastIndex=0;var n=Ue.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:P;return function(t){var n=Se.exec(t),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",u=n[4]||"",c=n[5],h=+n[6],f=n[7],d=n[8],p=n[9],g=1,v="",m="",y=!1,b=!0;switch(d&&(d=+d.substring(1)),(c||"0"===i&&"="===s)&&(c=i="0",s="="),p){case"n":f=!0,p="g";break;case"%":g=100,m="%",p="f";break;case"p":g=100,m="%",p="r";break;case"b":case"o":case"x":case"X":"#"===u&&(v="0"+p.toLowerCase());case"c":b=!1;case"d":y=!0,d=0;break;case"s":g=-1,p="r"}"$"===u&&(v=a[0],m=a[1]),"r"!=p||d||(p="g"),null!=d&&("g"==p?d=Math.max(1,Math.min(21,d)):"e"!=p&&"f"!=p||(d=Math.max(0,Math.min(20,d)))),p=Pe.get(p)||Re;var x=c&&f;return function(t){var n=m;if(y&&t%1)return"";var a=t<0||0===t&&1/t<0?(t=-t,"-"):"-"===l?"":l;if(g<0){var u=e.formatPrefix(t,d);t=u.scale(t),n=u.symbol+m}else t*=g;var _,w,M=(t=p(t,d)).lastIndexOf(".");if(M<0){var A=b?t.lastIndexOf("e"):-1;A<0?(_=t,w=""):(_=t.substring(0,A),w=t.substring(A))}else _=t.substring(0,M),w=r+t.substring(M+1);!c&&f&&(_=o(_,1/0));var T=v.length+_.length+w.length+(x?0:a.length),k=T"===s?k+a+t:"^"===s?k.substring(0,T>>=1)+a+t+k.substring(T):a+(x?t:k+t))+n}}}(t),timeFormat:function(t){var r=t.dateTime,n=t.date,i=t.time,a=t.periods,o=t.days,s=t.shortDays,l=t.months,u=t.shortMonths;function c(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s=u)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in je?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(Ie=Ne);return r._=t,e(r)}finally{Ie=Date}}return r.parse=function(t){try{Ie=Ne;var r=e.parse(t);return r&&r._}finally{Ie=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var f=e.map(),d=He(o),p=qe(o),g=He(s),v=qe(s),m=He(l),y=qe(l),b=He(u),x=qe(u);a.forEach(function(t,e){f.set(t.toLowerCase(),e)});var _={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:c(r),d:function(t,e){return Ve(t.getDate(),e,2)},e:function(t,e){return Ve(t.getDate(),e,2)},H:function(t,e){return Ve(t.getHours(),e,2)},I:function(t,e){return Ve(t.getHours()%12||12,e,2)},j:function(t,e){return Ve(1+Oe.dayOfYear(t),e,3)},L:function(t,e){return Ve(t.getMilliseconds(),e,3)},m:function(t,e){return Ve(t.getMonth()+1,e,2)},M:function(t,e){return Ve(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return Ve(t.getSeconds(),e,2)},U:function(t,e){return Ve(Oe.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ve(Oe.mondayOfYear(t),e,2)},x:c(n),X:c(i),y:function(t,e){return Ve(t.getFullYear()%100,e,2)},Y:function(t,e){return Ve(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){d.lastIndex=0;var n=d.exec(e.slice(r));return n?(t.w=p.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){b.lastIndex=0;var n=b.exec(e.slice(r));return n?(t.m=x.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return h(t,_.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Je,L:nr,m:Ke,M:er,p:function(t,e,r){var n=f.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Xe,w:Ge,W:We,x:function(t,e,r){return h(t,_.x.toString(),e,r)},X:function(t,e,r){return h(t,_.X.toString(),e,r)},y:Ze,Y:Ye,Z:Qe,"%":ar};return c}(t)}};var sr=e.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"]});function lr(){}e.format=sr.numberFormat,e.geo={},lr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new lr;function cr(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function hr(t,e){t&&dr.hasOwnProperty(t.type)&&dr[t.type](t,e)}e.geo.stream=function(t,e){t&&fr.hasOwnProperty(t.type)?fr[t.type](t,e):hr(t,e)};var fr={Feature:function(t,e){hr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=o*a,l=Math.cos(e),u=Math.sin(e),c=i*u,h=n*l+c*Math.cos(s),f=c*o*Math.sin(s);Lr.add(Math.atan2(f,h)),r=t,n=l,i=u}Cr.point=function(o,s){Cr.point=a,r=(t=o)*Ct,n=Math.cos(s=(e=s)*Ct/2+Tt/4),i=Math.sin(s)},Cr.lineEnd=function(){a(t,e)}}function Pr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Rr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Or(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Ir(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Nr(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Dr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function zr(t){return[Math.atan2(t[1],t[0]),It(t[2])]}function Fr(t,e){return y(t[0]-e[0])Mt?i=90:u<-Mt&&(r=-90),h[0]=t,h[1]=n}};function d(e,a){c.push(h=[t=e,n=e]),ai&&(i=a)}function p(e,o){var s=Pr([e*Ct,o*Ct]);if(l){var u=Or(l,s),c=Or([u[1],-u[0],0],u);Dr(c),c=zr(c);var h=e-a,f=h>0?1:-1,p=c[0]*St*f,g=y(h)>180;if(g^(f*ai&&(i=v);else if(g^(f*a<(p=(p+360)%360-180)&&pi&&(i=o);g?e_(t,n)&&(n=e):_(e,n)>_(t,n)&&(t=e):n>=t?(en&&(n=e)):e>a?_(t,e)>_(t,n)&&(n=e):_(e,n)>_(t,n)&&(t=e)}else d(e,o);l=s,a=e}function g(){f.point=p}function v(){h[0]=t,h[1]=n,f.point=d,l=null}function m(t,e){if(l){var r=t-a;u+=y(r)>180?r+(r>0?360:-360):r}else o=t,s=e;Cr.point(t,e),p(t,e)}function b(){Cr.lineStart()}function x(){m(o,s),Cr.lineEnd(),y(u)>Mt&&(t=-(n=180)),h[0]=t,h[1]=n,l=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function M(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(g[0],g[1])&&(g[1]=d[1]),_(d[0],g[1])>_(g[0],g[1])&&(g[0]=d[0])):s.push(g=d);for(var l,u,d,p=-1/0,g=(o=0,s[u=s.length-1]);o<=u;g=d,++o)d=s[o],(l=_(g[1],d[0]))>p&&(p=l,t=d[0],n=g[1])}return c=h=null,t===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[t,r],[n,i]]}}(),e.geo.centroid=function(t){mr=yr=br=xr=_r=wr=Mr=Ar=Tr=kr=Er=0,e.geo.stream(t,jr);var r=Tr,n=kr,i=Er,a=r*r+n*n+i*i;return a=0;--s)i.point((h=c[s])[0],h[1]);else n(d.x,d.p.x,-1,i);d=d.p}c=(d=d.o).z,p=!p}while(!d.v);i.lineEnd()}}}function Yr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,M=w*_,A=M>Tt,T=p*b;if(Lr.add(Math.atan2(T*w*Math.sin(M),g*x+T*Math.cos(M))),a+=A?_+w*kt:_,A^f>=r^m>=r){var k=Or(Pr(h),Pr(t));Dr(k);var E=Or(i,k);Dr(E);var L=(A^_>=0?-1:1)*It(E[2]);(n>L||n===L&&(k[0]||k[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;f=m,p=b,g=x,h=t}}return(a<-Mt||a0){for(b||(o.polygonStart(),b=!0),o.lineStart();++a1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return c}}function Kr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:N,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Jr(t,e){return((t=t.x)[0]<0?t[1]-Lt-Mt:Lt-t[1])-((e=e.x)[0]<0?e[1]-Lt-Mt:Lt-e[1])}var tn=Qr(Xr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Tt:-Tt,l=y(a-r);y(l-Tt)0?Lt:-Lt),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Tt&&(y(r-i)Mt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Lt,n.point(-Tt,i),n.point(0,i),n.point(Tt,i),n.point(Tt,0),n.point(Tt,-i),n.point(0,-i),n.point(-Tt,-i),n.point(-Tt,0),n.point(-Tt,i);else if(y(t[0]-e[0])>Mt){var a=t[0]0)){if(a/=f,f<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=r-l,f||!(a<0)){if(a/=f,f<0){if(a>h)return;a>c&&(c=a)}else if(f>0){if(a0)){if(a/=d,d<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=n-u,d||!(a<0)){if(a/=d,d<0){if(a>h)return;a>c&&(c=a)}else if(d>0){if(a0&&(i.a={x:l+c*f,y:u+c*d}),h<1&&(i.b={x:l+h*f,y:u+h*d}),i}}}}}}var rn=1e9;function nn(t,r,n,i){return function(l){var u,c,h,f,d,p,g,v,m,y,b,x=l,_=$r(),w=en(t,r,n,i),M={point:k,lineStart:function(){M.point=E,c&&c.push(h=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){u&&(E(f,d),p&&m&&_.rejoin(),u.push(_.buffer()));M.point=k,m&&l.lineEnd()},polygonStart:function(){l=_,u=[],c=[],b=!0},polygonEnd:function(){l=x,u=e.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],i=0;in&&Rt(u,a,t)>0&&++e:a[1]<=n&&Rt(u,a,t)<0&&--e,u=a;return 0!==e}([t,i]),n=b&&r,a=u.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),A(null,null,1,l),l.lineEnd()),a&&Wr(u,o,r,A,l),l.polygonEnd()),u=c=h=null}};function A(e,o,l,u){var c=0,h=0;if(null==e||(c=a(e,l))!==(h=a(o,l))||s(e,o)<0^l>0)do{u.point(0===c||3===c?t:n,c>1?i:r)}while((c=(c+l+4)%4)!==h);else u.point(o[0],o[1])}function T(e,a){return t<=e&&e<=n&&r<=a&&a<=i}function k(t,e){T(t,e)&&l.point(t,e)}function E(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&h.push([t,e]),y)f=t,d=e,p=r,y=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&m)l.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),b=!1):r&&(l.lineStart(),l.point(t,e),b=!1)}g=t,v=e,m=r}return M};function a(e,i){return y(e[0]-t)0?0:3:y(e[0]-n)0?2:1:y(e[1]-r)0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=En(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,It((i-(t*t+r*r)*n*n)/(2*n))]},o}e.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(e.geo.conicEqualArea=function(){return an(on)}).raw=on,e.geo.albers=function(){return e.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},e.geo.albersUsa=function(){var t,r,n,i,a=e.geo.albers(),o=e.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=e.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,r){t=[e,r]}};function u(e){var a=e[0],o=e[1];return t=null,r(a,o),t||(n(a,o),t)||i(a,o),t}return u.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},u.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),u):a.precision()},u.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),u.translate(a.translate())):a.scale()},u.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),c=+t[0],h=+t[1];return r=a.translate(t).clipExtent([[c-.455*e,h-.238*e],[c+.455*e,h+.238*e]]).stream(l).point,n=o.translate([c-.307*e,h+.201*e]).clipExtent([[c-.425*e+Mt,h+.12*e+Mt],[c-.214*e-Mt,h+.234*e-Mt]]).stream(l).point,i=s.translate([c-.205*e,h+.212*e]).clipExtent([[c-.214*e+Mt,h+.166*e+Mt],[c-.115*e-Mt,h+.234*e-Mt]]).stream(l).point,u},u.scale(1070)};var sn,ln,un,cn,hn,fn,dn={point:N,lineStart:N,lineEnd:N,polygonStart:function(){ln=0,dn.lineStart=pn},polygonEnd:function(){dn.lineStart=dn.lineEnd=dn.point=N,sn+=y(ln/2)}};function pn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}dn.point=function(a,o){dn.point=i,t=r=a,e=n=o},dn.lineEnd=function(){i(t,e)}}var gn={point:function(t,e){thn&&(hn=t);efn&&(fn=e)},lineStart:N,lineEnd:N,polygonStart:N,polygonEnd:N};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,yn={point:bn,lineStart:xn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=bn,yn.lineStart=xn,yn.lineEnd=_n}};function bn(t,e){br+=t,xr+=e,++_r}function xn(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,Mr+=o*(e+n)/2,Ar+=o,bn(t=r,e=n)}yn.point=function(n,i){yn.point=r,bn(t=n,e=i)}}function _n(){yn.point=bn}function wn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,Mr+=o*(n+e)/2,Ar+=o,Tr+=(o=n*t-r*e)*(r+t),kr+=o*(n+e),Er+=3*o,bn(r=t,n=e)}yn.point=function(a,o){yn.point=i,bn(t=r=a,e=n=o)},yn.lineEnd=function(){i(t,e)}}function Mn(t){var e=.5,r=Math.cos(30*Ct),n=16;function i(e){return(n?function(e){var r,i,o,s,l,u,c,h,f,d,p,g,v={point:m,lineStart:y,lineEnd:x,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){h=NaN,v.point=b,e.lineStart()}function b(r,i){var o=Pr([r,i]),s=t(r,i);a(h,f,c,d,p,g,h=s[0],f=s[1],c=r,d=o[0],p=o[1],g=o[2],n,e),e.point(h,f)}function x(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=M}function w(t,e){b(r=t,e),i=h,o=f,s=d,l=p,u=g,v.point=b}function M(){a(h,f,c,d,p,g,i,o,r,s,l,u,n,e),v.lineEnd=x,x()}return v}:function(e){return Tn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,u,c,h,f,d,p,g,v,m){var b=c-n,x=h-i,_=b*b+x*x;if(_>4*e&&v--){var w=s+d,M=l+p,A=u+g,T=Math.sqrt(w*w+M*M+A*A),k=Math.asin(A/=T),E=y(y(A)-1)e||y((b*P+x*R)/_-.5)>.3||s*d+l*p+u*g0&&16,i):Math.sqrt(e)},i}function An(t){this.stream=t}function Tn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function kn(t){return En(function(){return t})()}function En(t){var r,n,i,a,o,s,l=Mn(function(t,e){return[(t=r(t,e))[0]*u+a,o-t[1]*u]}),u=150,c=480,h=250,f=0,d=0,p=0,g=0,v=0,m=tn,b=P,x=null,_=null;function w(t){return[(t=i(t[0]*Ct,t[1]*Ct))[0]*u+a,o-t[1]*u]}function M(t){return(t=i.invert((t[0]-a)/u,(o-t[1])/u))&&[t[0]*St,t[1]*St]}function A(){i=Gr(n=Pn(p,g,v),r);var t=r(f,d);return a=c-t[0]*u,o=h+t[1]*u,T()}function T(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Ln(m(n,l(b(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(m=null==t?(x=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>Mt;return Qr(i,function(t){var e,s,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(h,f){var d,p=[h,f],g=i(h,f),v=r?g?0:o(h,f):g?o(h+(h<0?Tt:-Tt),f):0;if(!e&&(u=l=g)&&t.lineStart(),g!==l&&(d=a(e,p),(Fr(e,d)||Fr(p,d))&&(p[0]+=Mt,p[1]+=Mt,g=i(p[0],p[1]))),g!==l)c=0,g?(t.lineStart(),d=a(p,e),t.point(d[0],d[1])):(d=a(e,p),t.point(d[0],d[1]),t.lineEnd()),e=d;else if(n&&e&&r^g){var m;v&s||!(m=a(p,e,!0))||(c=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&Fr(e,p)||t.point(p[0],p[1]),e=p,l=g,s=v},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return c|(u&&l)<<1}}},Nn(t,6*Ct),r?[0,-t]:[-Tt,t-Tt]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Or(Pr(t),Pr(r)),o=Rr(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var u=e*o/l,c=-e*s/l,h=Or(i,a),f=Nr(i,u);Ir(f,Nr(a,c));var d=h,p=Rr(f,d),g=Rr(d,d),v=p*p-g*(Rr(f,f)-1);if(!(v<0)){var m=Math.sqrt(v),b=Nr(d,(-p-m)/g);if(Ir(b,f),b=zr(b),!n)return b;var x,_=t[0],w=r[0],M=t[1],A=r[1];w<_&&(x=_,_=w,w=x);var T=w-_,k=y(T-Tt)0^b[1]<(y(b[0]-_)Tt^(_<=b[0]&&b[0]<=w)){var E=Nr(d,(-p+m)/g);return Ir(E,f),[b,zr(E)]}}}function o(e,n){var i=r?t:Tt-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((x=+t)*Ct),T()):x},w.clipExtent=function(t){return arguments.length?(_=t,b=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):P,T()):_},w.scale=function(t){return arguments.length?(u=+t,A()):u},w.translate=function(t){return arguments.length?(c=+t[0],h=+t[1],A()):[c,h]},w.center=function(t){return arguments.length?(f=t[0]%360*Ct,d=t[1]%360*Ct,A()):[f*St,d*St]},w.rotate=function(t){return arguments.length?(p=t[0]%360*Ct,g=t[1]%360*Ct,v=t.length>2?t[2]%360*Ct:0,A()):[p*St,g*St,v*St]},e.rebind(w,l,"precision"),function(){return r=t.apply(this,arguments),w.invert=r.invert&&M,A()}}function Ln(t){return Tn(t,function(e,r){t.point(e*Ct,r*Ct)})}function Cn(t,e){return[t,e]}function Sn(t,e){return[t>Tt?t-kt:t<-Tt?t+kt:t,e]}function Pn(t,e,r){return t?e||r?Gr(On(t),In(e,r)):On(t):e||r?In(e,r):Sn}function Rn(t){return function(e,r){return[(e+=t)>Tt?e-kt:e<-Tt?e+kt:e,r]}}function On(t){var e=Rn(t);return e.invert=Rn(-t),e}function In(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*r+s*n;return[Math.atan2(l*i-c*a,s*r-u*n),It(c*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*i-l*a;return[Math.atan2(l*i+u*a,s*r+c*n),It(c*r-s*n)]},o}function Nn(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Dn(r,i),a=Dn(r,a),(o>0?ia)&&(i+=o*kt)):(i=t+o*kt,a=t-.5*l);for(var u,c=i;o>0?c>a:c2?t[2]*Ct:0),e.invert=function(e){return(e=t.invert(e[0]*Ct,e[1]*Ct))[0]*=St,e[1]*=St,e},e},Sn.invert=Cn,e.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=Pn(-t[0]*Ct,-t[1]*Ct,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=St,t[1]*=St}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=Nn((t=+r)*Ct,n*Ct),i):t},i.precision=function(r){return arguments.length?(e=Nn(t*Ct,(n=+r)*Ct),i):n},i.angle(90)},e.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ct,i=t[1]*Ct,a=e[1]*Ct,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((r=h*o)*r+(r=u*c-l*h*s)*r),l*c+u*h*s)},e.geo.graticule=function(){var t,r,n,i,a,o,s,l,u,c,h,f,d=10,p=d,g=90,v=360,m=2.5;function b(){return{type:"MultiLineString",coordinates:x()}}function x(){return e.range(Math.ceil(i/g)*g,n,g).map(h).concat(e.range(Math.ceil(l/v)*v,s,v).map(f)).concat(e.range(Math.ceil(r/d)*d,t,d).filter(function(t){return y(t%g)>Mt}).map(u)).concat(e.range(Math.ceil(o/p)*p,a,p).filter(function(t){return y(t%v)>Mt}).map(c))}return b.lines=function(){return x().map(function(t){return{type:"LineString",coordinates:t}})},b.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(f(s).slice(1),h(n).reverse().slice(1),f(l).reverse().slice(1))]}},b.extent=function(t){return arguments.length?b.majorExtent(t).minorExtent(t):b.minorExtent()},b.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),b.precision(m)):[[i,l],[n,s]]},b.minorExtent=function(e){return arguments.length?(r=+e[0][0],t=+e[1][0],o=+e[0][1],a=+e[1][1],r>t&&(e=r,r=t,t=e),o>a&&(e=o,o=a,a=e),b.precision(m)):[[r,o],[t,a]]},b.step=function(t){return arguments.length?b.majorStep(t).minorStep(t):b.minorStep()},b.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],b):[g,v]},b.minorStep=function(t){return arguments.length?(d=+t[0],p=+t[1],b):[d,p]},b.precision=function(e){return arguments.length?(m=+e,u=zn(o,a,90),c=Fn(r,t,m),h=zn(l,s,90),f=Fn(i,n,m),b):m},b.majorExtent([[-180,-90+Mt],[180,90-Mt]]).minorExtent([[-180,-80-Mt],[180,80+Mt]])},e.geo.greatArc=function(){var t,r,n=jn,i=Bn;function a(){return{type:"LineString",coordinates:[t||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return e.geo.distance(t||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(e){return arguments.length?(n=e,t="function"==typeof e?null:e,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},e.geo.interpolate=function(t,e){return r=t[0]*Ct,n=t[1]*Ct,i=e[0]*Ct,a=e[1]*Ct,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),u=Math.sin(a),c=o*Math.cos(r),h=o*Math.sin(r),f=l*Math.cos(i),d=l*Math.sin(i),p=2*Math.asin(Math.sqrt(Dt(a-n)+o*l*Dt(i-r))),g=1/Math.sin(p),(v=p?function(t){var e=Math.sin(t*=p)*g,r=Math.sin(p-t)*g,n=r*c+e*f,i=r*h+e*d,a=r*s+e*u;return[Math.atan2(i,n)*St,Math.atan2(a,Math.sqrt(n*n+i*i))*St]}:function(){return[r*St,n*St]}).distance=p,v;var r,n,i,a,o,s,l,u,c,h,f,d,p,g,v},e.geo.length=function(t){return mn=0,e.geo.stream(t,Un),mn};var Un={sphere:N,point:N,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=Ct),o=Math.cos(i),s=y((n*=Ct)-t),l=Math.cos(s);mn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}Un.point=function(i,a){t=i*Ct,e=Math.sin(a*=Ct),r=Math.cos(a),Un.point=n},Un.lineEnd=function(){Un.point=Un.lineEnd=N}},lineEnd:N,polygonStart:N,polygonEnd:N};function Vn(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var Hn=Vn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(e.geo.azimuthalEqualArea=function(){return kn(Hn)}).raw=Hn;var qn=Vn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},P);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return Yn;function o(t,e){a>0?e<-Lt+Mt&&(e=-Lt+Mt):e>Lt-Mt&&(e=Lt-Mt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=Pt(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-Lt]},o}function Xn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(y(n)1&&Rt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(e.geo.stereographic=function(){return kn(Kn)}).raw=Kn,$n.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Lt]},(e.geo.transverseMercator=function(){var t=Zn($n),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=$n,e.geom={},e.geom.hull=function(t){var e=Jn,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=ve(e),a=ve(r),o=t.length,s=[],l=[];for(n=0;n=0;--n)d.push(t[s[u[n]][2]]);for(n=+h;nMt)s=s.L;else{if(!((i=a-bi(s,o))>Mt)){n>-Mt?(e=s.P,r=s):i>-Mt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=pi(t);if(ui.insert(e,l),e||r){if(e===r)return Mi(e),r=pi(e.site),ui.insert(l,r),l.edge=r.edge=ki(e.site,l.site),wi(e),void wi(r);if(r){Mi(e),Mi(r);var u=e.site,c=u.x,h=u.y,f=t.x-c,d=t.y-h,p=r.site,g=p.x-c,v=p.y-h,m=2*(f*v-d*g),y=f*f+d*d,b=g*g+v*v,x={x:(v*y-d*b)/m+c,y:(f*b-g*y)/m+h};Ei(r.edge,u,p,x),l.edge=ki(u,t,null,x),r.edge=ki(t,p,null,x),wi(e),wi(r)}else l.edge=ki(e.site,l.site)}}function yi(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,u=l-e;if(!u)return s;var c=s-n,h=1/a-1/u,f=c/u;return h?(-f+Math.sqrt(f*f-2*h*(c*c/(-2*u)-l+u/2+i-a/2)))/h+n:(n+s)/2}function bi(t,e){var r=t.N;if(r)return yi(r,e);var n=t.site;return n.y===e?n.x:1/0}function xi(t){this.site=t,this.edges=[]}function _i(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,u=n.y-s,c=a.x-o,h=2*(l*(v=a.y-s)-u*c);if(!(h>=-At)){var f=l*l+u*u,d=c*c+v*v,p=(v*f-u*d)/h,g=(l*d-c*f)/h,v=g+s,m=di.pop()||new function(){Si(this),this.x=this.y=this.arc=this.site=this.cy=null};m.arc=t,m.site=i,m.x=p+o,m.y=v+Math.sqrt(p*p+g*g),m.cy=v,t.circle=m;for(var y=null,b=hi._;b;)if(m.y=s)return;if(f>p){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.y1)if(f>p){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.y=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xMt||y(i-r)>Mt)&&(s.splice(o,0,new Li((m=a.site,b=c,x=y(n-h)Mt?{x:h,y:y(e-h)Mt?{x:y(r-p)Mt?{x:f,y:y(e-f)Mt?{x:y(r-d)=r&&u.x<=i&&u.y>=n&&u.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/Mt)*Mt,y:Math.round(i(t,e)/Mt)*Mt,i:e}})}return o.links=function(t){return Ii(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Ii(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,u=r.edges.sort(_i),c=-1,h=u.length,f=u[h-1].edge,d=f.l===l?f.r:f.l;++ca&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Ui(r,n)})),a=qi.lastIndex;return ag&&(g=l.x),l.y>v&&(v=l.y),u.push(l.x),c.push(l.y);else for(h=0;hg&&(g=x),_>v&&(v=_),u.push(x),c.push(_)}var w=g-d,M=v-p;function A(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,u=t.y;if(null!=l)if(y(l-r)+y(u-n)<.01)T(t,e,r,n,i,a,o,s);else{var c=t.point;t.x=t.y=t.point=null,T(t,c,l,u,i,a,o,s),T(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,i,a,o,s)}function T(t,e,r,n,i,a,o,s){var l=.5*(i+o),u=.5*(a+s),c=r>=l,h=n>=u,f=h<<1|c;t.leaf=!1,t=t.nodes[f]||(t.nodes[f]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(k,t,+m(t,++h),+b(t,h),d,p,g,v)}}),c?i=l:o=l,h?a=u:s=u,A(t,e,r,n,i,a,o,s)}w>M?v=p+w:g=d+M;var k={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(k,t,+m(t,++h),+b(t,h),d,p,g,v)}};if(k.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),u=r.nodes;u[0]&&t(e,u[0],n,i,s,l),u[1]&&t(e,u[1],s,i,a,l),u[2]&&t(e,u[2],n,l,s,o),u[3]&&t(e,u[3],s,l,a,o)}}(t,k,d,p,g,v)},k.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(u,c,h,f,d){if(!(c>a||h>o||f=_)<<1|e>=x,M=w+4;w=0&&!(n=e.interpolators[i](t,r)););return n}function Xi(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ea(t){return 1-Math.cos(t*Lt)}function ra(t){return Math.pow(2,10*(t-1))}function na(t){return 1-Math.sqrt(1-t*t)}function ia(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}function aa(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oa(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=la(i),s=sa(i,a),l=la(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Yi.get(i)||Wi,a=Zi.get(a)||P,e=a(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},e.interpolateHcl=function(t,r){t=e.hcl(t),r=e.hcl(r);var n=t.h,i=t.c,a=t.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Wt(n+o*t,i+s*t,a+l*t)+""}},e.interpolateHsl=function(t,r){t=e.hsl(t),r=e.hsl(r);var n=t.h,i=t.s,a=t.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return qt(n+o*t,i+s*t,a+l*t)+""}},e.interpolateLab=function(t,r){t=e.lab(t),r=e.lab(r);var n=t.l,i=t.a,a=t.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},e.interpolateRound=aa,e.transform=function(t){var r=i.createElementNS(e.ns.prefix.svg,"g");return(e.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oa(e?e.matrix:ua)})(t)},oa.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ua={a:1,b:0,c:0,d:1,e:0,f:0};function ca(t){return t.length?t.pop()+",":""}function ha(t,r){var n=[],i=[];return t=e.transform(t),r=e.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Ui(t[0],e[0])},{i:i-2,x:Ui(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(t.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ca(r)+"rotate(",null,")")-2,x:Ui(t,e)})):e&&r.push(ca(r)+"rotate("+e+")")}(t.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(ca(r)+"skewX(",null,")")-2,x:Ui(t,e)}):e&&r.push(ca(r)+"skewX("+e+")")}(t.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(ca(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Ui(t[0],e[0])},{i:i-2,x:Ui(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ca(r)+"scale("+e+")")}(t.scale,r.scale,n,i),t=r=null,function(t){for(var e,r=-1,a=i.length;++r0?n=e:(t.c=null,t.t=NaN,t=null,l.end({type:"end",alpha:n=0})):e>0&&(l.start({type:"start",alpha:n=e}),t=Ae(s.tick)),s):n},s.start=function(){var t,e,r,n=m.length,l=y.length,c=u[0],p=u[1];for(t=0;t=0;)r.push(i[n])}function Ta(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;r&&(a.value=0),a.children=u}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return Ta(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Aa(t,function(t){t.children&&(t.value=0)}),Ta(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},e.layout.partition=function(){var t=e.layout.hierarchy(),r=[1,1];function n(e,n){var i=t.call(this,e,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++us&&(s=n),o.push(n)}for(r=0;ri&&(n=r,i=e);return n}function ja(t){return t.reduce(Ba,0)}function Ba(t,e){return t+e[1]}function Ua(t,e){return Va(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Va(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function Ha(t){return[e.min(t),e.max(t)]}function qa(t,e){return t.value-e.value}function Ga(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Xa(t,e){t._pack_next=e,e._pack_prev=t}function Wa(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Ya(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,u=1/0,c=-1/0,h=1/0,f=-1/0;if(e.forEach(Za),(r=e[0]).x=-r.r,r.y=0,b(r),l>1&&((n=e[1]).x=n.r,n.y=0,b(n),l>2))for(Ka(r,n,i=e[2]),b(i),Ga(r,i),r._pack_prev=i,Ga(i,n),n=r._pack_next,a=3;a0)for(o=-1;++o=h[0]&&l<=h[1]&&((s=u[e.bisect(f,l,1,p)-1]).y+=g,s.push(a[o]));return u}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=ve(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Va(e,t)}:ve(t),a):i},a.frequency=function(e){return arguments.length?(t=!!e,a):t},a},e.layout.pack=function(){var t,r=e.layout.hierarchy().sort(qa),n=0,i=[1,1];function a(e,a){var o=r.call(this,e,a),s=o[0],l=i[0],u=i[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(s.x=s.y=0,Ta(s,function(t){t.r=+c(t.value)}),Ta(s,Ya),n){var h=n*(t?1:Math.max(2*s.r/l,2*s.r/u))/2;Ta(s,function(t){t.r+=h}),Ta(s,Ya),Ta(s,function(t){t.r-=h})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++od.x&&(d=t),t.depth>p.depth&&(p=t)});var g=r(f,d)/2-f.x,v=n[0]/(d.x+r(d,f)/2+g),m=n[1]/(p.depth||1);Aa(c,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return u}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],u=a.m,c=o.m,h=s.m,f=l.m;s=to(s),a=Ja(a),s&&a;)l=Ja(l),(o=to(o)).a=t,(i=s.z+h-a.z-u+r(s._,a._))>0&&(eo(ro(s,t,n),t,i),u+=i,c+=i),h+=s.m,u+=a.m,f+=l.m,c+=o.m;s&&!to(o)&&(o.t=s,o.m+=h-c),a&&!Ja(l)&&(l.t=a,l.m+=u-f,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},Ma(a,t)},e.layout.cluster=function(){var t=e.layout.hierarchy().sort(null).value(null),r=$a,n=[1,1],i=!1;function a(a,o){var s,l=t.call(this,a,o),u=l[0],c=0;Ta(u,function(t){var n=t.children;n&&n.length?(t.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),t.y=function(t){return 1+e.max(t,function(t){return t.y})}(n)):(t.x=s?c+=r(t,s):0,t.y=0,s=t)});var h=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),f=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),d=h.x-r(h,f)/2,p=f.x+r(f,h)/2;return Ta(u,i?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-d)/(p-d)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},Ma(a,t)},e.layout.treemap=function(){var t,r=e.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=no,s=!1,l="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,i=-1,a=t.length;++i0;)s.push(r=u[i-1]),s.area+=r.area,"squarify"!==l||(n=d(s,g))<=f?(u.pop(),f=n):(s.area-=s.pop().area,p(s,g,a,!1),g=Math.min(a.dx,a.dy),s.length=s.area=0,f=1/0);s.length&&(p(s,g,a,!0),s.length=s.area=0),e.forEach(h)}}function f(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(c(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(p(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(f)}}function d(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++oi&&(i=r));return e*=e,(n*=n)?Math.max(e*i*u/n,n/(e*a*u)):1/0}function p(t,e,r,i){var a,o=-1,s=t.length,l=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((i||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=e.random.normal.apply(e,arguments);return function(){return Math.exp(t())}},bates:function(t){var r=e.random.irwinHall(t);return function(){return r()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?ho:so,s=i?da:fa;return a=t(e,r,s,n),o=t(r,e,s,Gi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(aa)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return vo(e,t)};l.tickFormat=function(t,r){return mo(e,t,r)};l.nice=function(t){return po(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Gi,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function bo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}e.scale.log=function(){return function t(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=lo(a.map(o),i?Math:_o);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=ao(a),e=[],r=t[0],l=t[1],u=Math.floor(o(r)),c=Math.ceil(o(l)),h=n%1?2:n;if(isFinite(c-u)){if(i){for(;u0;f--)e.push(s(u)*f);for(u=0;e[u]l;c--);e=e.slice(u,c)}return e};l.tickFormat=function(t,r){if(!arguments.length)return xo;arguments.length<2?r=xo:"function"!=typeof r&&(r=e.format(r));var i=Math.max(1,n*t/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n0?i[t-1]:r[0],th?0:1;if(u=Et)return l(u,d)+(s?l(s,1-d):"")+"Z";var p,g,v,m,y,b,x,_,w,M,A,T,k=0,E=0,L=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Lo?Math.sqrt(s*s+u*u):+n.apply(this,arguments),d||(E*=-1),u&&(E=It(v/u*Math.sin(m))),s&&(k=It(v/s*Math.sin(m)))),u){y=u*Math.cos(c+E),b=u*Math.sin(c+E),x=u*Math.cos(h-E),_=u*Math.sin(h-E);var C=Math.abs(h-c-2*E)<=Tt?0:1;if(E&&Io(y,b,x,_)===d^C){var S=(c+h)/2;y=u*Math.cos(S),b=u*Math.sin(S),x=_=null}}else y=b=0;if(s){w=s*Math.cos(h-k),M=s*Math.sin(h-k),A=s*Math.cos(c+k),T=s*Math.sin(c+k);var P=Math.abs(c-h+2*k)<=Tt?0:1;if(k&&Io(w,M,A,T)===1-d^P){var R=(c+h)/2;w=s*Math.cos(R),M=s*Math.sin(R),A=T=null}}else w=M=0;if(f>Mt&&(p=Math.min(Math.abs(u-s)/2,+r.apply(this,arguments)))>.001){g=s0?0:1}function No(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,h=t[1]+u,f=e[0]+l,d=e[1]+u,p=(c+f)/2,g=(h+d)/2,v=f-c,m=d-h,y=v*v+m*m,b=r-n,x=c*d-f*h,_=(m<0?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,M=(-x*v-m*_)/y,A=(x*m+v*_)/y,T=(-x*v+m*_)/y,k=w-p,E=M-g,L=A-p,C=T-g;return k*k+E*E>L*L+C*C&&(w=A,M=T),[[w-l,M-u],[w*r/b,M*r/b]]}function Do(t){var e=Jn,r=ti,n=Xr,i=Fo,a=i.key,o=.7;function s(a){var s,l=[],u=[],c=-1,h=a.length,f=ve(e),d=ve(r);function p(){l.push("M",i(t(u),o))}for(;++c1&&i.push("H",n[0]);return i.join("")},"step-before":Bo,"step-after":Uo,basis:qo,"basis-open":function(t){if(t.length<4)return Fo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Go(Yo,a)+","+Go(Yo,o)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Fo(t){return t.length>1?t.join("L"):t+"Z"}function jo(t){return t.join("L")+"Z"}function Bo(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;uTt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=ve(t),a):r},a.source=function(e){return arguments.length?(t=ve(e),a):t},a.target=function(t){return arguments.length?(e=ve(t),a):e},a.startAngle=function(t){return arguments.length?(n=ve(t),a):n},a.endAngle=function(t){return arguments.length?(i=ve(t),a):i},a},e.svg.diagonal=function(){var t=jn,e=Bn,r=ts;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},e.svg.diagonal.radial=function(){var t=e.svg.diagonal(),r=ts,n=t.projection;return t.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Lt;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},t},e.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var is=e.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*os)),r=e*os;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});e.svg.symbolTypes=is.keys();var as=Math.sqrt(3),os=Math.tan(30*Ct);W.transition=function(t){for(var e,r,n=cs||++ds,i=vs(t),a=[],o=hs||{time:Date.now(),ease:ta,delay:0,duration:250},s=-1,l=this.length;++s0;)u[--f].call(t,o);if(a>=1)return h.event&&h.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}h||(a=i.time,o=Ae(function(t){var e=h.delay;if(o.t=e+a,e<=t)return f(t-e);o.c=f},0,a),h=c[n]={tween:new x,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++c.count)}fs.call=W.call,fs.empty=W.empty,fs.node=W.node,fs.size=W.size,e.transition=function(t,r){return t&&t.transition?cs?t.transition(r):t:e.selection().transition(t)},e.transition.prototype=fs,fs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=Y(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function g(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function v(){var h,v,m=this,y=e.select(e.event.target),b=n.of(m,arguments),x=e.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&i,M=!/^(e|w)$/.test(_)&&a,A=y.classed("extent"),T=bt(m),k=e.mouse(m),E=e.select(o(m)).on("keydown.brush",function(){32==e.event.keyCode&&(A||(h=null,k[0]-=s[1],k[1]-=l[1],A=2),F())}).on("keyup.brush",function(){32==e.event.keyCode&&2==A&&(k[0]+=s[1],k[1]+=l[1],A=0,F())});if(e.event.changedTouches?E.on("touchmove.brush",S).on("touchend.brush",R):E.on("mousemove.brush",S).on("mouseup.brush",R),x.interrupt().selectAll("*").interrupt(),A)k[0]=s[0]-k[0],k[1]=l[0]-k[1];else if(_){var L=+/w$/.test(_),C=+/^n/.test(_);v=[s[1-L]-k[0],l[1-C]-k[1]],k[0]=s[L],k[1]=l[C]}else e.event.altKey&&(h=k.slice());function S(){var t=e.mouse(m),r=!1;v&&(t[0]+=v[0],t[1]+=v[1]),A||(e.event.altKey?(h||(h=[(s[0]+s[1])/2,(l[0]+l[1])/2]),k[0]=s[+(t[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=Cs(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=Cs(+e+1);return e}}:t))},i.ticks=function(t,e){var r=ao(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Cs(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Ls(t.copy(),r,n)},fo(i,t)}function Cs(t){return new Date(t)}As.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Es:ks,Es.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Es.toString=ks.toString,Oe.second=ze(function(t){return new Ie(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Oe.seconds=Oe.second.range,Oe.seconds.utc=Oe.second.utc.range,Oe.minute=ze(function(t){return new Ie(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Oe.minutes=Oe.minute.range,Oe.minutes.utc=Oe.minute.utc.range,Oe.hour=ze(function(t){var e=t.getTimezoneOffset()/60;return new Ie(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Oe.hours=Oe.hour.range,Oe.hours.utc=Oe.hour.utc.range,Oe.month=ze(function(t){return(t=Oe.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Oe.months=Oe.month.range,Oe.months.utc=Oe.month.utc.range;var Ss=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ps=[[Oe.second,1],[Oe.second,5],[Oe.second,15],[Oe.second,30],[Oe.minute,1],[Oe.minute,5],[Oe.minute,15],[Oe.minute,30],[Oe.hour,1],[Oe.hour,3],[Oe.hour,6],[Oe.hour,12],[Oe.day,1],[Oe.day,2],[Oe.week,1],[Oe.month,1],[Oe.month,3],[Oe.year,1]],Rs=As.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Xr]]),Os={range:function(t,r,n){return e.range(Math.ceil(t/n)*n,+r,n).map(Cs)},floor:P,ceil:P};Ps.year=Oe.year,Oe.scale=function(){return Ls(e.scale.linear(),Ps,Rs)};var Is=Ps.map(function(t){return[t[0].utc,t[1]]}),Ns=Ts.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Xr]]);function Ds(t){return JSON.parse(t.responseText)}function zs(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Is.year=Oe.year.utc,Oe.scale.utc=function(){return Ls(e.scale.linear(),Is,Ns)},e.text=me(function(t){return t.responseText}),e.json=function(t,e){return ye(t,"application/json",Ds,e)},e.html=function(t,e){return ye(t,"text/html",zs,e)},e.xml=me(function(t){return t.responseXML}),t.exports?t.exports=e:this.d3=e}(),t=t.exports;var e=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},n={},i=Math.PI;n.deg2rad=function(t){return t/180*i},n.rad2deg=function(t){return t/i*180},n.wrap360=function(t){var e=t%360;return e<0?e+360:e},n.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var a=r.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,i=t.round,a=t.min,o=t.max,l=t.random;function u(s,l){if(s=s||"",l=l||{},s instanceof u)return s;if(!(this instanceof u))return new u(s,l);var c=function(n){var i={r:0,g:0,b:0},s=1,l=null,u=null,c=null,h=!1,f=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,i=!1;if(E[t])t=E[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=B.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=B.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=B.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=B.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=B.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=B.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=B.hex8.exec(t))return{r:R(n[1]),g:R(n[2]),b:R(n[3]),a:D(n[4]),format:i?"name":"hex8"};if(n=B.hex6.exec(t))return{r:R(n[1]),g:R(n[2]),b:R(n[3]),format:i?"name":"hex"};if(n=B.hex4.exec(t))return{r:R(n[1]+""+n[1]),g:R(n[2]+""+n[2]),b:R(n[3]+""+n[3]),a:D(n[4]+""+n[4]),format:i?"name":"hex8"};if(n=B.hex3.exec(t))return{r:R(n[1]+""+n[1]),g:R(n[2]+""+n[2]),b:R(n[3]+""+n[3]),format:i?"name":"hex"};return!1}(n));"object"==typeof n&&(U(n.r)&&U(n.g)&&U(n.b)?(d=n.r,p=n.g,g=n.b,i={r:255*S(d,255),g:255*S(p,255),b:255*S(g,255)},h=!0,f="%"===String(n.r).substr(-1)?"prgb":"rgb"):U(n.h)&&U(n.s)&&U(n.v)?(l=I(n.s),u=I(n.v),i=function(e,r,n){e=6*S(e,360),r=S(r,100),n=S(n,100);var i=t.floor(e),a=e-i,o=n*(1-r),s=n*(1-a*r),l=n*(1-(1-a)*r),u=i%6;return{r:255*[n,s,o,o,l,n][u],g:255*[l,n,n,s,o,o][u],b:255*[o,o,l,n,n,s][u]}}(n.h,l,u),h=!0,f="hsv"):U(n.h)&&U(n.s)&&U(n.l)&&(l=I(n.s),c=I(n.l),i=function(t,e,r){var n,i,a;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=S(t,360),e=S(e,100),r=S(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(n.h,l,c),h=!0,f="hsl"),n.hasOwnProperty("a")&&(s=n.a));var d,p,g;return s=C(s),{ok:h,format:n.format||f,r:a(255,o(i.r,0)),g:a(255,o(i.g,0)),b:a(255,o(i.b,0)),a:s}}(s);this._originalInput=s,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=i(100*this._a)/100,this._format=l.format||c.format,this._gradientType=l.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=c.ok,this._tc_id=n++}function c(t,e,r){t=S(t,255),e=S(e,255),r=S(r,255);var n,i,s=o(t,e,r),l=a(t,e,r),u=(s+l)/2;if(s==l)n=i=0;else{var c=s-l;switch(i=u>.5?c/(2-s-l):c/(s+l),s){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(u(n));return a}function k(t,e){e=e||6;for(var r=u(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(u({h:n,s:i,v:a})),a=(a+s)%1;return o}u.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=C(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=h(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=h(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=c(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=c(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return f(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[O(i(t).toString(16)),O(i(e).toString(16)),O(i(r).toString(16)),O(N(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*S(this._r,255))+"%",g:i(100*S(this._g,255))+"%",b:i(100*S(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*S(this._r,255))+"%, "+i(100*S(this._g,255))+"%, "+i(100*S(this._b,255))+"%)":"rgba("+i(100*S(this._r,255))+"%, "+i(100*S(this._g,255))+"%, "+i(100*S(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(L[f(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+d(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=u(t);r="#"+d(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return u(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(b,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(x,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(A,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(M,arguments)}},u.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:I(t[n]));t=r}return u(t,e)},u.equals=function(t,e){return!(!t||!e)&&u(t).toRgbString()==u(e).toRgbString()},u.random=function(){return u.fromRatio({r:l(),g:l(),b:l()})},u.mix=function(t,e,r){r=0===r?0:r||50;var n=u(t).toRgb(),i=u(e).toRgb(),a=r/100;return u({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},u.readability=function(e,r){var n=u(e),i=u(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},u.isReadable=function(t,e,r){var n,i,a=u.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},u.mostReadable=function(t,e,r){var n,i,a,o,s=null,l=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var c=0;cl&&(l=n,s=u(e[c]));return u.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,u.mostReadable(t,["#fff","#000"],r))};var E=u.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"},L=u.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(E);function C(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function S(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=a(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function P(t){return a(1,o(0,t))}function R(t){return parseInt(t,16)}function O(t){return 1==t.length?"0"+t:""+t}function I(t){return t<=1&&(t=100*t+"%"),t}function N(e){return t.round(255*parseFloat(e)).toString(16)}function D(t){return R(t)/255}var z,F,j,B=(F="[\\s|\\(]+("+(z="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+z+")[,|\\s]+("+z+")\\s*\\)?",j="[\\s|\\(]+("+z+")[,|\\s]+("+z+")[,|\\s]+("+z+")[,|\\s]+("+z+")\\s*\\)?",{CSS_UNIT:new RegExp(z),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),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})$/});function U(t){return!!B.CSS_UNIT.exec(t)}s.exports?s.exports=u:window.tinycolor=u}(Math),s=s.exports;var l={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=l.RdBu,c=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],i=t[e][1],o=!1,G(n))for(r=n.length-1;r>=0;r--)Z(n[r],K(i,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)Z(n[a[r]],K(i,a[r]))?delete n[a[r]]:o=!0;if(o)return}}(l)):o[e[a]]=n}}function K(t,r){var n=r;return e(r)?n="["+r+"]":t&&(n="."+r),t+n}function $(t,e,r,n){var i,a=G(r),o=!0,s=r,l=n.replace("-1",0),u=!a&&Z(r,l),c=e[0];for(i=0;ii.max?r.set(n):r.set(+t)}},integer:{coerceFunction:function(t,r,n,i){t%1||!e(t)||void 0!==i.min&&ti.max?r.set(n):r.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){s(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return s(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(h(t,r))}},angle:{coerceFunction:function(t,r,n){"auto"===t?r.set("auto"):e(t)?r.set(it(+t)):r.set(n)}},subplotid:{coerceFunction:function(t,e,r,n){var i=n.regex||rt(r);"string"==typeof t&&i.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!rt(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a=ot&&t<=st?t:ct;if("string"!=typeof t&&"number"!=typeof t)return ct;t=String(t);var r=xt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var i=r&&"chinese"===e.substr(0,7),a=t.match(i?yt:mt);if(!a)return ct;var o=a[1],s=a[3]||"1",l=Number(a[5]||1),u=Number(a[7]||0),c=Number(a[9]||0),h=Number(a[11]||0);if(r){if(2===o.length)return ct;var f;o=Number(o);try{var d=R.getComponentMethod("calendars","getCal")(e);if(i){var p="i"===s.charAt(s.length-1);s=parseInt(s,10),f=d.newDate(o,d.toMonthIndex(o,s,p),l)}else f=d.newDate(o,Number(s),l)}catch(t){return ct}return f?(f.toJD()-gt)*ht+u*ft+c*dt+h*pt:ct}o=2===o.length?(Number(o)+2e3-bt)%100+bt:Number(o),s-=1;var g=new Date(Date.UTC(2e3,s,l,u,c));return g.setUTCFullYear(o),g.getUTCMonth()!==s?ct:g.getUTCDate()!==l?ct:g.getTime()+h*pt},ot=ut.MIN_MS=ut.dateTime2ms("-9999"),st=ut.MAX_MS=ut.dateTime2ms("9999-12-31 23:59:59.9999"),ut.isDateTime=function(t,e){return ut.dateTime2ms(t,e)!==ct};var wt=90*ht,Mt=3*ft,At=5*dt;function Tt(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+_t(e,2)+":"+_t(r,2),(n||i)&&(t+=":"+_t(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+_t(i,a)}return t}ut.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ot&&t<=st))return ct;e||(e=0);var n,i,a,o,s,l,u=Math.floor(10*lt(t+.05,1)),c=Math.round(t-u/10);if(xt(r)){var h=Math.floor(c/ht)+gt,f=Math.floor(lt(t,ht));try{n=R.getComponentMethod("calendars","getCal")(r).fromJD(h).formatDate("yyyy-mm-dd")}catch(t){n=vt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;i=e=ot+ht&&e<=st-ht))return ct;var r=Math.floor(10*lt(e+.05,1)),n=new Date(Math.round(e-r/10));return Tt(t.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ut.cleanDate=function(t,e,r){if(ut.isJSDate(t)||"number"==typeof t){if(xt(r))return _.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ut.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ut.isDateTime(t,r))return _.error("unrecognized date",t),e;return t};var kt=/%\d?f/g;function Et(t,e,r,n){t=t.replace(kt,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(xt(n))try{t=R.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var Lt=[59,59.9,59.99,59.999,59.9999];ut.formatDate=function(t,r,n,i,a,o){if(a=xt(a)&&a,!r)if("y"===n)r=o.year;else if("m"===n)r=o.month;else{if("d"!==n)return function(t,r){var n=lt(t+.05,ht),i=_t(Math.floor(n/ft),2)+":"+_t(lt(Math.floor(n/dt),60),2);if("M"!==r){e(r)||(r=0);var a=(100+Math.min(lt(t/pt,60),Lt[r])).toFixed(r).substr(1);r>0&&(a=a.replace(/0+$/,"").replace(/[\.]$/,"")),i+=":"+a}return i}(t,n)+"\n"+Et(o.dayMonthYear,t,i,a);r=o.dayMonth+"\n"+o.year}return Et(r,t,i,a)};var Ct=3*ht;ut.incrementMonth=function(t,e,r){r=xt(r)&&r;var n=lt(t,ht);if(t=Math.round(t-n),r)try{var i=Math.round(t/ht)+gt,a=R.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-gt)*ht+n}catch(e){_.error("invalid ms "+t+" in calendar "+r)}var s=new Date(t+Ct);return s.setUTCMonth(s.getUTCMonth()+e)+n-Ct},ut.findExactDates=function(t,r){for(var n,i,a=0,o=0,s=0,l=0,u=xt(r)&&R.getComponentMethod("calendars","getCal")(r),c=0;c1||g<0||g>1?null:{x:t+l*g,y:e+h*g}}function zt(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}Nt.segmentsIntersect=Dt,Nt.segmentDistance=function(t,e,r,n,i,a,o,s){if(Dt(t,e,r,n,i,a,o,s))return 0;var l=r-t,u=n-e,c=o-i,h=s-a,f=l*l+u*u,d=c*c+h*h,p=Math.min(zt(l,u,f,i-t,a-e),zt(l,u,f,o-t,s-e),zt(c,h,d,t-i,e-a),zt(c,h,d,r-i,n-a));return Math.sqrt(p)},Nt.getTextLocation=function(t,e,r,n){if(t===Ot&&n===It||(Rt={},Ot=t,It=n),Rt[r])return Rt[r];var i=t.getPointAtLength(lt(r-n/2,e)),a=t.getPointAtLength(lt(r+n/2,e)),o=Math.atan((a.y-i.y)/(a.x-i.x)),s=t.getPointAtLength(lt(r,e)),l={x:(4*s.x+i.x+a.x)/6,y:(4*s.y+i.y+a.y)/6,theta:o};return Rt[r]=l,l},Nt.clearLocationCache=function(){Ot=null},Nt.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,u=0,c=t.getTotalLength(),h=c;function f(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(i=r);var u=r.xo?r.x-o:0,h=r.yl?r.y-l:0;return Math.sqrt(u*u+h*h)}for(var d=f(u);d;){if((u+=d+r)>h)return;d=f(u)}for(d=f(h);d;){if(u>(h-=d+r))return;d=f(h)}return{min:u,max:h,len:h-u,total:c,isClosed:0===u&&h===c&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},Nt.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,h=0,f=0,d=s;h0?d=i:f=i,h++}return a};var Ft=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},jt=/^\w*$/,Bt={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Zt(t,e){return t>=e}Gt.findBin=function(t,r,n){if(e(r.start))return n?Math.ceil((t-r.start)/r.size-1e-9)-1:Math.floor((t-r.start)/r.size+1e-9);var i,a,o=0,s=r.length,l=0,u=s>1?(r[s-1]-r[0])/(s-1):1;for(a=u>=0?n?Xt:Wt:n?Zt:Yt,t+=1e-9*u*(n?-1:1)*(u>=0?1:-1);o90&&_.log("Long binary search..."),o-1},Gt.sorterAsc=function(t,e){return t-e},Gt.sorterDes=function(t,e){return e-t},Gt.distinctVals=function(t){var e=t.slice();e.sort(Gt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,i=n/(r||1)/1e4,a=[e[0]],o=0;oe[o]+i&&(n=Math.min(n,e[o+1]-e[o]),a.push(e[o+1]));return{vals:a,minDiff:n}},Gt.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;in.length)&&(i=n.length),e(r)||(r=!1),Kt(n[0])){for(o=new Array(i),a=0;at.length-1)return t[t.length-1];var n=r%1;return n*t[Math.ceil(r)]+(1-n)*t[Math.floor(r)]};var $t={},Jt={};function te(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}$t.throttle=function(t,e,r){var n=Jt[t],i=Date.now();if(!n){for(var a in Jt)Jt[a].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},$t.done=function(t){var e=Jt[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},$t.clear=function(t){if(t)te(Jt[t]),delete Jt[t];else for(var e in Jt)$t.clear(e)};var ee=function(t,r){if(t>0)return Math.log(t)/Math.LN10;var n=Math.log(Math.min(r[0],r[1]))/Math.LN10;return e(n)||(n=Math.log(Math.max(r[0],r[1]))/Math.LN10-6),n},re={},ne=r.FP_SAFE,ie=r.BADNUM,ae=re={};ae.nestedProperty=X,ae.keyedContainer=function(t,e,r,n){var i,a;r=r||"name",n=n||"value";var o={};a=e&&e.length?X(t,e).get():t,e=e||"",a=a||[];var s={};for(i=0;i2)return o[e]=2|o[e],u.set(t,null);if(l){for(i=e;i/g),s=0;sne?ie:e(t)?Number(t):ie:ie},ae.noop=A,ae.identity=function(t){return t},ae.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},ae.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},ae.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):s},ae.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},ae.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},ae.syncOrAsync=function(t,e,r){var n;function i(){return ae.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,ae.promiseError);return r&&r(e)},ae.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},ae.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n=0&&a%1==0){var p=i?i[d]:d,g=n?n[p]:p;h(g)&&(t[g].selected=1)}}},ae.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=ae.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ae.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l};var le=/%{([^\s%{}]*)}/g,ue=/^\w*$/;ae.templateString=function(t,e){var r={};return t.replace(le,function(t,n){return ue.test(n)?e[n]||"":(r[n]=r[n]||ae.nestedProperty(e,n).get,r[n]()||"")})};ae.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a=48&&o<=57,u=s>=48&&s<=57;if(l&&(n=10*n+o-48),u&&(i=10*i+s-48),!l||!u){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n};var ce=2e9;ae.seedPseudoRandom=function(){ce=2e9},ae.pseudoRandom=function(){var t=ce;return ce=(69069*ce+1)%4294967296,Math.abs(ce-t)<429496729?ae.pseudoRandom():ce/4294967296};var he={"X,X div":"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 .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"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":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","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 .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 fe in he){var de=fe.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");re.addStyleRule(de,he[fe])}var pe,ge,ve,me={undo:{width:857.1,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",ascent:850,descent:-150},home:{width:928.6,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",ascent:850,descent:-150},"camera-retro":{width:1e3,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",ascent:850,descent:-150},zoombox:{width:1e3,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",ascent:850,descent:-150},pan:{width:1e3,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",ascent:850,descent:-150},zoom_plus:{width:1e3,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",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,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",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,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",ascent:850,descent:-150},plotlylogo:{width:1542,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",ascent:850,descent:-150},"z-axis":{width:1e3,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",ascent:850,descent:-150},"3d_rotate":{width:1e3,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",ascent:850,descent:-150},camera:{width:1e3,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",ascent:850,descent:-150},movie:{width:1e3,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",ascent:850,descent:-150},question:{width:857.1,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",ascent:850,descent:-150},disk:{width:857.1,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",ascent:850,descent:-150},lasso:{width:1031,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",ascent:850,descent:-150},selectbox:{width:1e3,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",ascent:850,descent:-150},spikeline:{width:1e3,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",ascent:850,descent:-150}},ye=pe={};function be(){throw new Error("setTimeout has not been defined")}function xe(){throw new Error("clearTimeout has not been defined")}function _e(t){if(ge===setTimeout)return setTimeout(t,0);if((ge===be||!ge)&&setTimeout)return ge=setTimeout,setTimeout(t,0);try{return ge(t,0)}catch(e){try{return ge.call(null,t,0)}catch(e){return ge.call(this,t,0)}}}!function(){try{ge="function"==typeof setTimeout?setTimeout:be}catch(t){ge=be}try{ve="function"==typeof clearTimeout?clearTimeout:xe}catch(t){ve=xe}}();var we,Me=[],Ae=!1,Te=-1;function ke(){Ae&&we&&(Ae=!1,we.length?Me=we.concat(Me):Te=-1,Me.length&&Ee())}function Ee(){if(!Ae){var t=_e(ke);Ae=!0;for(var e=Me.length;e;){for(we=Me,Me=[];++Te1)for(var r=1;r=0))return t;if(3===o)i[o]>1&&(i[o]=1);else if(i[o]>=1)return t}var s=Math.round(255*i[0])+", "+Math.round(255*i[1])+", "+Math.round(255*i[2]);return a?"rgba("+s+", "+i[3]+")":"rgb("+s+")"}De.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},De.rgb=function(t){return De.tinyRGB(s(t))},De.opacity=function(t){return t?s(t).getAlpha():0},De.addOpacity=function(t,e){var r=s(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},De.combine=function(t,e){var r=s(t).toRgb();if(1===r.a)return s(t).toRgbString();var n=s(e||Fe).toRgb(),i=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},a={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return s(a).toRgbString()},De.contrast=function(t,e,r){var n=s(t);return 1!==n.getAlpha()&&(n=s(De.combine(t,Fe))),(n.isDark()?e?n.lighten(e):Fe:r?n.darken(r):ze).toString()},De.stroke=function(t,e){var r=s(e);t.style({stroke:De.tinyRGB(r),"stroke-opacity":r.getAlpha()})},De.fill=function(t,e){var r=s(e);t.style({fill:De.tinyRGB(r),"fill-opacity":r.getAlpha()})},De.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,a=Object.keys(t);for(e=0;e=0,p=r.indexOf("end")>=0,g=u.backoff*h+n.standoff,v=c.backoff*f+n.startstandoff;if("line"===l.nodeName){i={x:+e.attr("x1"),y:+e.attr("y1")},a={x:+e.attr("x2"),y:+e.attr("y2")};var m=i.x-a.x,y=i.y-a.y;if(s=(o=Math.atan2(y,m))+Math.PI,g&&v&&g+v>Math.sqrt(m*m+y*y))return void C();if(g){if(g*g>m*m+y*y)return void C();var b=g*Math.cos(o),x=g*Math.sin(o);a.x+=b,a.y+=x,e.attr({x2:a.x,y2:a.y})}if(v){if(v*v>m*m+y*y)return void C();var _=v*Math.cos(o),w=v*Math.sin(o);i.x-=_,i.y-=w,e.attr({x1:i.x,y1:i.y})}}else if("path"===l.nodeName){var M=l.getTotalLength(),A="";if(M0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},We.prototype.on=We.prototype.addListener,We.prototype.once=function(t,e){if(!Ze(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},We.prototype.removeListener=function(t,e){var r,n,i,a;if(!Ze(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=(r=this._events[t]).length,n=-1,r===e||Ze(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Qe(r)){for(a=i;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},We.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(Ze(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},We.prototype.listeners=function(t){return this._events&&this._events[t]?Ze(this._events[t])?[this._events[t]]:this._events[t].slice():[]},We.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(Ze(e))return 1;if(e)return e.length}return 0},We.listenerCount=function(t,e){return t.listenerCount(e)};var $e,Je=Ye.EventEmitter,tr={init:function(t){if(t._ev instanceof Je)return t;var e=new Je,r=new Je;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;l4/3-s?o:s},nr.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:re.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:re.constrain(Math.floor(3*e),0,2),Ge[e][t]},nr.unhover=$e.wrapped,nr.unhoverRaw=$e.raw,nr.init=function(t){var e,r,n,i,a,o,s,l,u=t.gd,c=1,h=f.DBLCLICKDELAY,d=t.element;u._mouseDownTime||(u._mouseDownTime=0),d.style.pointerEvents="all",d.onmousedown=g,Ve?(d._ontouchstart&&d.removeEventListener("touchstart",d._ontouchstart),d._ontouchstart=g,d.addEventListener("touchstart",g,{passive:!1})):d.ontouchstart=g;var p=t.clampFn||function(t,e,r){return Math.abs(t)h&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!l){var r;try{r=new MouseEvent("click",e)}catch(t){var n=ar(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}s.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&R.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},nr.coverSlip=ir;var or={zauto:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{zmin:void 0,zmax:void 0}},zmin:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},zmax:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},colorscale:{valType:"colorscale",editType:"calc",impliedEdits:{autocolorscale:!1}},autocolorscale:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{colorscale:void 0}},reversescale:{valType:"boolean",dflt:!1,editType:"calc"},showscale:{valType:"boolean",dflt:!0,editType:"calc"}},sr=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n},lr=function(t,e,r,n){var i,a;r?(i=re.nestedProperty(t,r).get(),a=re.nestedProperty(t._input,r).get()):(i=t,a=t._input);var o=n+"auto",s=n+"min",u=n+"max",c=i[o],h=i[s],f=i[u],d=i.colorscale;!1===c&&void 0!==h||(h=re.aggNums(Math.min,null,e)),!1===c&&void 0!==f||(f=re.aggNums(Math.max,null,e)),h===f&&(h-=.5,f+=.5),i[s]=h,i[u]=f,a[s]=h,a[u]=f,a[o]=!1!==c||void 0===h&&void 0===f,i.autocolorscale&&(d=h*f<0?l.RdBu:h>=0?l.Reds:l.Blues,a.colorscale=d,i.reversescale&&(d=sr(d)),i.colorscale=d)},ur=re.extendFlat,cr=re.isPlainObject,hr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},fr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},dr=hr.flags.slice().concat(["clearCalc","fullReplot"]),pr=fr.flags.slice().concat("layoutReplot"),gr={traces:hr,layout:fr,traceFlags:function(){return vr(dr)},layoutFlags:function(){return vr(pr)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i0?Number(l):s;else if("string"!=typeof l)r.dtick=s;else{var u=l.charAt(0),c=l.substr(1);((c=e(c)?Number(c):0)<=0||!("date"===i&&"M"===u&&c===Math.round(c)||"log"===i&&"L"===u||"log"===i&&"D"===u&&(1===c||2===c)))&&(r.dtick=s)}var h="date"===i?re.dateTick0(r.calendar):0,f=n("tick0",h);"date"===i?r.tick0=re.cleanDate(f,h):e(f)&&"D1"!==l&&"D2"!==l?r.tick0=Number(f):r.tick0=h}else{void 0===n("tickvals")?r.tickmode="auto":n("ticktext")}},Cr=function(t){return void 0!==l[t]||c(t)},Sr=function(t,r,n,i,a){var o,s=a.prefix,l=a.cLetter,u=s.slice(0,s.length-1),c=s?re.nestedProperty(t,u).get()||{}:t,h=s?re.nestedProperty(r,u).get()||{}:r,f=c[l+"min"],d=c[l+"max"],p=c.colorscale;i(s+l+"auto",!(e(f)&&e(d)&&f","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},Fr={},jr=Nr.LINE_SPACING;function Br(t,e){return t.node().getBoundingClientRect()[e]}var Ur=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;Fr.convertToTspans=function(e,r,n){var i=e.text(),a=!e.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(Ur),o=t.select(e.node().parentNode);if(!o.empty()){var s=e.attr("class")?e.attr("class").split(" ")[0]:"text";return s+="-math",o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove(),e.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),a?(r&&r._promises||[]).push(new Promise(function(r){e.style("display","none");var u=parseInt(e.node().style.fontSize,10),c={fontSize:u};!function(e,r,n){var i="math-output-"+re.randstr([],64),a=t.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=e,o.replace(Vr,"\\lt ").replace(Hr,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var r=t.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())re.log("There was an error in the tex syntax.",e),n();else{var i=a.select("svg").node().getBoundingClientRect();n(a.select(".MathJax_SVG"),r,i)}a.remove()})}(a[2],c,function(t,a,c){o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove();var h=t&&t.select("svg");if(!h||!h.node())return l(),void r();var f=o.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});f.node().appendChild(h.node()),a&&a.node()&&h.node().insertBefore(a.node().cloneNode(!0),h.node().firstChild),h.attr({class:s,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var d=e.node().style.fill||"black";h.select("g").attr({fill:d,stroke:d});var p=Br(h,"width"),g=Br(h,"height"),v=+e.attr("x")-p*{start:0,middle:.5,end:1}[e.attr("text-anchor")||"start"],m=-(u||Br(e,"height"))/4;"y"===s[0]?(f.attr({transform:"rotate("+[-90,+e.attr("x"),+e.attr("y")]+") translate("+[-p/2,m-g/2]+")"}),h.attr({x:+e.attr("x"),y:+e.attr("y")})):"l"===s[0]?h.attr({x:e.attr("x"),y:m-g/2}):"a"===s[0]?h.attr({x:0,y:m}):h.attr({x:v,y:+e.attr("y")+m-g/2}),n&&n.call(e,f),r(f)})})):l(),e}function l(){o.empty()||(s=e.attr("class")+"-math",o.select("svg."+s).remove()),e.text("").style("white-space","pre"),function(e,r){r=(n=r,function(t,e){if(!t)return"";for(var r=0;r1)for(var a=1;a doesnt match end tag <"+t+">. Pretending it did match.",r),i=o[o.length-1].node}else re.log("Ignoring unexpected end tag .",r)}tn.test(r)?l():(i=e,o=[{node:e}]);for(var f=r.split($r),d=0;d|>|>)/g;var qr={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"},Gr={sub:"0.3em",sup:"-0.6em"},Xr={sub:"-0.21em",sup:"0.42em"},Wr="\u200b",Yr=["http:","https:","mailto:","",void 0,":"],Zr=new RegExp("]*)?/?>","g"),Qr=Object.keys(zr.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:zr.entityToUnicode[t]}}),Kr=/(\r\n?|\n)/g,$r=/(<[^<>]*>)/,Jr=/<(\/?)([^ >]*)(\s+(.*))?>/i,tn=//i,en=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,rn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,nn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,an=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function on(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var sn=/(^|;)\s*color:/;function ln(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}Fr.plainText=function(t){return(t||"").replace(Zr," ")},Fr.lineCount=function(t){return t.selectAll("tspan.line").size()||1},Fr.positionText=function(e,r,n){return e.each(function(){var e=t.select(this);function i(t,r){return void 0===r?null===(r=e.attr(t))&&(e.attr(t,0),r=0):e.attr(t,r),r}var a=i("x",r),o=i("y",n);"text"===this.nodeName&&e.selectAll("tspan.line").attr({x:a,y:o})})},Fr.makeEditable=function(e,r){var n=r.gd,i=r.delegate,a=t.dispatch("edit","input","cancel"),o=i||e;if(e.style({"pointer-events":i?"none":"all"}),1!==e.size())throw new Error("boo");function s(){var i,s,u,c;i=t.select(n).select(".svg-container"),s=i.append("div"),u=e.node().style,c=parseFloat(u.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:r.fill||u.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||e.attr("data-unformatted")).call(ln(e,i,r)).on("blur",function(){n._editing=!1,e.text(this.textContent).style({opacity:1});var r,i=t.select(this).attr("class");(r=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(r).style({opacity:0});var o=this.textContent;t.select(this).transition().duration(0).remove(),t.select(document).on("mouseup",null),a.edit.call(e,o)}).on("focus",function(){var e=this;n._editing=!0,t.select(document).on("mouseup",function(){if(t.event.target===e)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===t.event.which?(n._editing=!1,e.style({opacity:1}),t.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(e,this.textContent)):(a.input.call(e,this.textContent),t.select(this).call(ln(e,i,r)))}).on("keydown",function(){13===t.event.which&&this.blur()}).call(l),e.style({opacity:0});var h,f=o.attr("class");(h=f?"."+f.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(h).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return r.immediate?s():o.on("click",s),t.rebind(e,a,"on")};var un=function(t){var r=t.marker,n=r.sizeref||1,i=r.sizemin||0,a="area"===r.sizemode?function(t){return Math.sqrt(t/n)}:function(t){return t/n};return function(t){var r=a(t/2);return e(r)&&r>0?Math.max(r,i):0}},cn={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return re.isPlainObject(t.marker)&&re.isArrayOrTypedArray(t.marker.size)}},hn={},fn=Nr.LINE_SPACING,dn=f.DESELECTDIM,pn=hn={};pn.font=function(t,e,r,n){re.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Ne.fill,n)},pn.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},pn.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},pn.setRect=function(t,e,r,n,i){t.call(pn.setPosition,e,r).call(pn.setSize,n,i)},pn.translatePoint=function(t,r,n,i){var a=n.c2p(t.x),o=i.c2p(t.y);return!!(e(a)&&e(o)&&r.node())&&("text"===r.node().nodeName?r.attr("x",a).attr("y",o):r.attr("transform","translate("+a+","+o+")"),!0)},pn.translatePoints=function(e,r,n){e.each(function(e){var i=t.select(this);pn.translatePoint(e,i,r,n)})},pn.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},pn.hideOutsideRangePoints=function(e,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var i=r.xaxis,a=r.yaxis;e.each(function(r){var o=r[0].trace,s=o.xcalendar,l=o.ycalendar;e.selectAll(n).each(function(e){pn.hideOutsideRangePoint(e,t.select(this),i,a,s,l)})})}},pn.crispRound=function(t,r,n){return r&&e(r)?t._context.staticPlot?r:r<1?1:Math.round(r):n||0},pn.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";Ne.stroke(e,n||a.color),pn.dashLine(e,s,o)},pn.lineGroupStyle=function(e,r,n,i){e.style("fill","none").each(function(e){var a=(((e||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";t.select(this).call(Ne.stroke,n||a.color).call(pn.dashLine,s,o)})},pn.dashLine=function(t,e,r){r=+r||0,e=pn.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},pn.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},pn.singleFillStyle=function(e){var r=(((t.select(e.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&e.call(Ne.fill,r)},pn.fillGroupStyle=function(e){e.style("stroke-width",0).each(function(r){var n=t.select(this);try{n.call(Ne.fill,r[0].trace.fillcolor)}catch(t){re.error(t,e),n.remove()}})},pn.symbolNames=[],pn.symbolFuncs=[],pn.symbolNeedLines={},pn.symbolNoDot={},pn.symbolNoFill={},pn.symbolList=[],Object.keys(Ir).forEach(function(t){var e=Ir[t];pn.symbolList=pn.symbolList.concat([e.n,t,e.n+100,t+"-open"]),pn.symbolNames[e.n]=t,pn.symbolFuncs[e.n]=e.f,e.needLine&&(pn.symbolNeedLines[e.n]=!0),e.noDot?pn.symbolNoDot[e.n]=!0:pn.symbolList=pn.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(pn.symbolNoFill[e.n]=!0)});var gn=pn.symbolNames.length,vn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function mn(t,e){var r=t%100;return pn.symbolFuncs[r](e)+(t>=200?vn:"")}pn.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=pn.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=gn||t>=400?0:Math.floor(Math.max(t,0))};var yn={x1:1,x2:0,y1:0,y2:0},bn={x1:0,x2:0,y1:1,y2:0};pn.gradient=function(e,r,n,i,a,o){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([i+a+o],re.identity);l.exit().remove(),l.enter().append("radial"===i?"radialGradient":"linearGradient").each(function(){var e=t.select(this);"horizontal"===i?e.attr(yn):"vertical"===i&&e.attr(bn),e.attr("id",n);var r=s(a),l=s(o);e.append("stop").attr({offset:"0%","stop-color":Ne.tinyRGB(l),"stop-opacity":l.getAlpha()}),e.append("stop").attr({offset:"100%","stop-color":Ne.tinyRGB(r),"stop-opacity":r.getAlpha()})}),e.style({fill:"url(#"+n+")","fill-opacity":null})},pn.initGradients=function(t){re.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},pn.singlePointStyle=function(t,e,r,n,i,a){var o=r.marker;!function(t,e,r,n,i,a,o,s){if(R.traceIs(r,"symbols")){var l=un(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===a.size?3:cn.isBubble(r)?l(t.ms):(a.size||6)/2,t.mrc=e;var n=pn.symbolNumber(t.mx||a.symbol)||0;return t.om=n%200>=100,mn(n,e)})}e.style("opacity",function(t){return(t.mo+1||a.opacity+1)-1});var u,c,h,f=!1;if(t.so?(h=o.outlierwidth,c=o.outliercolor,u=a.outliercolor):(h=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=i(t.mlc):re.isArrayOrTypedArray(o.color)?Ne.defaultLine:o.color,re.isArrayOrTypedArray(a.color)&&(u=Ne.defaultLine,f=!0),u="mc"in t?t.mcc=n(t.mc):a.color||"rgba(0,0,0,0)"),t.om)e.call(Ne.stroke,u).style({"stroke-width":(h||1)+"px",fill:"none"});else{e.style("stroke-width",h+"px");var d=a.gradient,p=t.mgt;if(p?f=!0:p=d&&d.type,p&&"none"!==p){var g=t.mgc;g?f=!0:g=d.color;var v="g"+s._fullLayout._uid+"-"+r.uid;f&&(v+="-"+t.i),e.call(pn.gradient,s,v,p,u,g)}else e.call(Ne.fill,u);h&&e.call(Ne.stroke,c)}}(t,e,r,n,i,o,o.line,a)},pn.pointStyle=function(e,r,n){if(e.size()){var i=r.marker,a=pn.tryColorscale(i,""),o=pn.tryColorscale(i,"line");e.each(function(e){pn.singlePointStyle(e,t.select(this),r,a,o,n)})}},pn.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},a=r.marker||{},o=n.marker||{},s=i.opacity,l=a.opacity,u=o.opacity,c=void 0!==l,h=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||h){if(!t.selected)return h?u:dn*(r?e:s);if(c)return l}};var f=a.color,d=o.color;(f||d)&&(e.colorFn=function(t){if(t.selected){if(f)return f}else if(d)return d});var p=a.size,g=o.size,v=void 0!==p,m=void 0!==g;return(v||m)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?v?p/2:e:m?g/2:e}),e},pn.selectedPointStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=pn.makeSelectedPointStyleFns(r),i=r.marker||{};e.each(function(e){var r=t.select(this),i=n.opacityFn(e);void 0!==i&&r.style("opacity",i)}),n.colorFn&&e.each(function(e){var r=t.select(this),i=n.colorFn(e);i&&Ne.fill(r,i)}),R.traceIs(r,"symbols")&&n.sizeFn&&e.each(function(e){var r=t.select(this),a=e.mx||i.symbol||0,o=n.sizeFn(e);r.attr("d",mn(pn.symbolNumber(a),o)),e.mrc2=o})}},pn.tryColorscale=function(t,e){var r=e?re.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&re.isArrayOrTypedArray(i)?Or.makeColorScaleFunc(Or.extractScale(n,r.cmin,r.cmax)):re.identity};var xn={start:1,end:-1,middle:0,bottom:1,top:-1};function _n(e,r,n,i){var a=t.select(e.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",s=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",l=i?i/.8+1:0,u=(Fr.lineCount(e)-1)*fn+1,c=xn[s]*l,h=.75*n+xn[o]*l+(xn[o]-1)*u*n/2;e.attr("text-anchor",s),a.attr("transform","translate("+c+","+h+")")}function wn(t,r){var n=t.ts||r.textfont.size;return e(n)&&n>0?n:0}pn.textPointStyle=function(e,r,n){e.each(function(e){var i=t.select(this),a=re.extractOption(e,r,"tx","text");if(a){var o=e.tp||r.textposition,s=wn(e,r);i.call(pn.font,e.tf||r.textfont.family,s,e.tc||r.textfont.color).text(a).call(Fr.convertToTspans,n).call(_n,o,s,e.mrc)}else i.remove()})},pn.selectedTextStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=r.selected||{},i=r.unselected||{};e.each(function(e){var a,o=t.select(this),s=e.tc||r.textfont.color,l=e.tp||r.textposition,u=wn(e,r),c=(n.textfont||{}).color,h=(i.textfont||{}).color;e.selected?c&&(a=c):h?a=h:c||(a=Ne.addOpacity(s,dn)),a&&Ne.fill(o,a),_n(o,l,u,e.mrc2||e.mrc)})}};var Mn=.5;function An(e,r,n,i){var a=e[0]-r[0],o=e[1]-r[1],s=n[0]-r[0],l=n[1]-r[1],u=Math.pow(a*a+o*o,Mn/2),c=Math.pow(s*s+l*l,Mn/2),h=(c*c*a-u*u*s)*i,f=(c*c*o-u*u*l)*i,d=3*c*(u+c),p=3*u*(u+c);return[[t.round(r[0]+(d&&h/d),2),t.round(r[1]+(d&&f/d),2)],[t.round(r[0]-(p&&h/p),2),t.round(r[1]-(p&&f/p),2)]]}pn.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(pn.savedBBoxes={},En=0),n&&(pn.savedBBoxes[n]=p),En++,re.extendFlat({},p)},pn.setClipUrl=function(e,r){if(r){if(void 0===pn.baseUrl){var n=t.select("base");n.size()&&n.attr("href")?pn.baseUrl=window.location.href.split("#")[0]:pn.baseUrl=""}e.attr("clip-path","url("+pn.baseUrl+"#"+r+")")}else e.attr("clip-path",null)},pn.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},pn.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},pn.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},pn.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a},pn.setPointGroupScale=function(t,e,r){var n,i,a;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",a=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(a,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var Cn=/translate\([^)]*\)\s*$/;pn.setTextPointsScale=function(e,r,n){e.each(function(){var e,i=t.select(this),a=i.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(i.attr("transform")||"").match(Cn);e=1===r&&1===n?[]:["translate("+o+","+s+")","scale("+r+","+n+")","translate("+-o+","+-s+")"],l&&e.push(l),i.attr("transform",e.join(" "))}})};function Sn(t,e,r,n){n=n||re.identity,Array.isArray(t)&&(e[0][r]=n(t))}var Pn={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},isTraceInSubplots:function(t,e){if("splom"===t.type){for(var r=t.xaxes||[],n=t.yaxes||[],i=0;i=0&&r.index=a.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!si(o))return!1;t=a[i][o]}else t=a[i]}else t=a}}return t}function si(t){return t===Math.round(t)&&t>=0}function li(t){return function(t){Jn.crawl(t,function(t,e,r){Jn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):ri(t)&&(t.role="object")})}(t),function(t){Jn.crawl(t,function(t,e,r){if(!t)return;var n=t[ii];if(!n)return;delete t[ii],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(ri(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n=o.length)return!1;n=(r=(R.transformsRegistry[o[s].type]||{}).attributes)&&r[e[2]],a=3}else if("area"===t.type)n=Wn[i];else{var l=t._module;if(l||(l=(R.modules[t.type||L.type.dflt]||{})._module),!l)return!1;if(!(n=(r=l.attributes)&&r[i])){var u=l.basePlotModule;u&&u.attributes&&(n=u.attributes[i])}n||(n=L[i])}return oi(n,e,a)},Jn.getLayoutValObject=function(t,e){return oi(function(t,e){var r,n,i,a,o=t._basePlotModules;if(o){var s;for(r=0;rn?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},fi={};function di(t,e,r){var n,i,a,o=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=re.nestedProperty(n,e.prop).get(),(a=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&a[e.prop]!==i&&(o=!0),a[e.prop]=i,{changed:o,value:i}}function pi(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!re.isPlainObject(n))return r;i=n}return vi(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function gi(t,e){var r,n,i,a,o=[];if(n=e[0],i=e[1],r=e[2],a={},"string"==typeof n)a[n]=i;else{if(!re.isPlainObject(n))return o;a=n,void 0===r&&(r=i)}return void 0===r&&(r=null),vi(a,function(e,n,i){var a;if(Array.isArray(i)){var s=Math.min(i.length,t.data.length);r&&(s=Math.min(s,r.length)),a=[];for(var l=0;l0?".":"")+i;re.isPlainObject(a)?vi(a,e,o,n+1):e(o,i,a)}})}function mi(t,e){return"splom"===t?-1:"splom"===e?1:0}fi.manageCommandObserver=function(t,e,r,n){var i={},a=!0;e&&e._commandObserver&&(i=e._commandObserver),i.cache||(i.cache={}),i.lookupTable={};var o=fi.hasSimpleAPICommandBindings(t,r,i.lookupTable);if(e&&e._commandObserver){if(o)return i;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,i}if(o){di(t,o,i.cache),i.check=function(){if(a){var e=di(t,o,i.cache);return e.changed&&n&&void 0!==i.lookupTable[e.value]&&(i.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:i.lookupTable[e.value]})).then(i.enable,i.enable)),e.changed}};for(var s=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],l=0;l=r.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=r._paper.attr("width")-7),n.attr(a);var o=n.select(".js-link-to-tool"),s=n.select(".js-link-spacer"),l=n.select(".js-sourcelinks");e._context.showSources&&e._context.showSources(e),e._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){Ai.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(e,o),s.text(o.text()&&l.text()?" - ":"")}},Ai.sendDataToCloud=function(e){e.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=t.select(e).append("div").attr("id","hiddenform").style("display","none"),i=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=Ai.graphJson(e,!1,"keepdata"),i.node().submit(),n.remove(),e.emit("plotly_afterexport"),!1};var ki,Ei=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Li=["year","month","dayMonth","dayMonthYear"];function Ci(t,e){var r,n,i=t.trace,a=i._arrayAttrs,o={};for(r=0;r1&&_.length>1){for(R.getComponentMethod("grid","sizeDefaults")(a,i),n=0;n15&&_.length>15&&0===i.shapes.length&&0===i.images.length,i._hasCartesian=i._has("cartesian"),i._hasGeo=i._has("geo"),i._hasGL3D=i._has("gl3d"),i._hasGL2D=i._has("gl2d"),i._hasTernary=i._has("ternary"),i._hasPie=i._has("pie"),Ai.cleanPlot(s,i,o,r,u),Ai.linkSubplots(s,i,o,r),wi(i,r),Ai.doAutoMargin(e);var T=hi.list(e);for(n=0;n0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,h=u.bottom+u.top,f=1-2*s,d=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};i=Math.round(f*(d.width-c)),a=Math.round(f*(d.height-h))}else{var p=l?window.getComputedStyle(t):{};i=parseFloat(p.width)||n.width,a=parseFloat(p.height)||n.height}var g=Ai.layoutAttributes.width.min,v=Ai.layoutAttributes.height.min;i1,y=!r.height&&Math.abs(n.height-a)>1;(y||m)&&(m&&(n.width=i),y&&(n.height=a)),t._initialAutoSize||(t._initialAutoSize={width:i,height:a}),Ai.sanitizeMargins(n)},Ai.supplyLayoutModuleDefaults=function(t,e,r,n){var i,a,o,s=R.componentsRegistry,l=e._basePlotModules,u=R.subplotsRegistry.cartesian;for(i in s)(o=s[i]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in l.length||l.push(u),e._has("cartesian")&&(R.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(re.subplotSort);for(a=0;a.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||Ai.doAutoMargin(t)}},Ai.doAutoMargin=function(t){var r=t._fullLayout;r._size||(r._size={}),r._pushmargin||(r._pushmargin={});var n=r._size,i=JSON.stringify(n),a=Math.max(r.margin.l||0,0),o=Math.max(r.margin.r||0,0),s=Math.max(r.margin.t||0,0),l=Math.max(r.margin.b||0,0),u=r._pushmargin;if(!1!==r.margin.autoexpand)for(var c in u.base={l:{val:0,size:a},r:{val:1,size:o},t:{val:1,size:s},b:{val:0,size:l}},u){var h=u[c].l||{},f=u[c].b||{},d=h.val,p=h.size,g=f.val,v=f.size;for(var m in u){if(e(p)&&u[m].r){var y=u[m].r.val,b=u[m].r.size;if(y>d){var x=(p*y+(b-r.width)*d)/(y-d),_=(b*(1-d)+(p-r.width)*(1-y))/(y-d);x>=0&&_>=0&&x+_>a+o&&(a=x,o=_)}}if(e(v)&&u[m].t){var w=u[m].t.val,M=u[m].t.size;if(w>g){var A=(v*w+(M-r.height)*g)/(w-g),T=(M*(1-g)+(v-r.height)*(1-w))/(w-g);A>=0&&T>=0&&A+T>l+s&&(l=A,s=T)}}}}if(n.l=Math.round(a),n.r=Math.round(o),n.t=Math.round(s),n.b=Math.round(l),n.p=Math.round(r.margin.pad),n.w=Math.round(r.width)-n.l-n.r,n.h=Math.round(r.height)-n.t-n.b,!r._replotting&&"{}"!==i&&i!==JSON.stringify(r._size))return R.call("plot",t)},Ai.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&Ai.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(re.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!re.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):re.isJSDate(t)?re.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},Ai.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){h=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return R.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,s=0,l=0;function u(){return s++,function(){var r;h||++l!==s||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return R.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var f=t._fullLayout._basePlotModules,d=!1;if(r)for(o=0;o=0;a--)if(l[a].enabled){r._indexToPoints=l[a]._indexToPoints;break}n&&n.calc&&(o=n.calc(t,r))}Array.isArray(o)&&o[0]||(o=[{x:xi,y:xi}]),o[0].t||(o[0].t={}),o[0].trace=r,u[e]=o}}for(f&&Ri(o),i=0;i0||h<0){var p={left:[-i,0],right:[i,0],top:[0,-i],bottom:[0,i]}[c.side];n.attr("transform","translate("+p+")")}}}T.call(k),M&&(w?T.on(".opacity",null):(x=0,_=!0,T.text(l).on("mouseover.opacity",function(){t.select(this).transition().duration(f.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){t.select(this).transition().duration(f.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(Fr.makeEditable,{gd:r}).on("edit",function(t){void 0!==u?R.call("restyle",r,s,t,u):R.call("relayout",r,s,t)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(k)}).on("input",function(t){this.text(t||" ").call(Fr.positionText,h.x,h.y)}));return T.classed("js-placeholder",_),p}},Ii=/ [XY][0-9]* /;var Ni=r.FP_SAFE,Di=Bi,zi=Ui,Fi=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=Bi(t),t._r=t.range.slice(),t._rl=re.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?Bi(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=re.extendFlat({},n)}},ji=function(t,r,n){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!r)return;t._min||(t._min=[]);t._max||(t._max=[]);n||(n={});t._m||t.setScale();var i,a,o,s,l,u,c,h,f,d,p,g,v=r.length,m=n.padded||!1,y=n.tozero&&("linear"===t.type||"-"===t.type),b="log"===t.type,x=!1;function _(t){if(Array.isArray(t))return x=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=_((t._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),M=_((t._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),A=_(n.vpadplus||n.vpad),T=_(n.vpadminus||n.vpad);if(!x){if(p=1/0,g=-1/0,b)for(i=0;i0&&(p=s),s>g&&s-Ni&&(p=s),s>g&&s=x&&(s.extrapad||!m)){d=!1;break}_(i,s.val)&&s.pad<=x&&(m||!s.extrapad)&&(v.splice(a,1),a--)}if(d){var k=y&&0===i;v.push({val:i,pad:k?0:x,extrapad:!k&&m})}}}}var E=Math.min(6,v);for(i=0;i=E;i--)k(i)};function Bi(t){var e,r,n,i,a,o,s,l,u=[],c=t._min[0].val,h=t._max[0].val,f=0,d=!1,p=Ui(t);for(e=1;e0&&s>0&&l/s>f&&(a=n,o=i,f=l/s);if(c===h){var v=c-1,m=c+1;u="tozero"===t.rangemode?c<0?[v,0]:[0,m]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,m)]:[v,m]}else f&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(a.val>=0&&(a={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(a.val-f*p(a)<0&&(a={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),f=(o.val-a.val)/(t._length-p(a)-p(o))),u=[a.val-f*p(a),o.val+f*p(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),d&&u.reverse(),re.simpleMap(u,t.l2r||Number)}function Ui(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function Vi(t){return e(t)&&Math.abs(t)=e}var Gi=r.BADNUM,Xi=function(t,r){return function(t,r){for(var n,i=0,a=0,o=Math.max(1,(t.length-1)/1e3),s=0;s2*a}(t,r)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}(t)?"category":function(t){if(!t)return!1;for(var r=0;r0)return Math.log(t)/Math.LN10;if(t<=0&&e&&r.range&&2===r.range.length){var n=r.range[0],i=r.range[1];return.5*(n+i-3*a*Math.abs(n-i))}return $i}function s(t,n,i){var a=Zi(t,i||r.calendar);if(a===$i){if(!e(t))return $i;a=Zi(new Date(+t))}return a}function l(t,e,n){return Yi(t,e,n||r.calendar)}function u(t){return r._categories[Math.round(t)]}function c(t){if(r._categoriesMap){var n=r._categoriesMap[t];if(void 0!==n)return n}if(e(t))return+t}function h(n){return e(n)?t.round(r._b+r._m*n,2):$i}function f(t){return(t-r._b)/r._m}r.c2l="log"===r.type?o:Qi,r.l2c="log"===r.type?Ji:Qi,r.l2p=h,r.p2l=f,r.c2p="log"===r.type?function(t,e){return h(o(t,e))}:h,r.p2c="log"===r.type?function(t){return Ji(f(t))}:f,-1!==["linear","-"].indexOf(r.type)?(r.d2r=r.r2d=r.d2c=r.r2c=r.d2l=r.r2l=Wi,r.c2d=r.c2r=r.l2d=r.l2r=Qi,r.d2p=r.r2p=function(t){return r.l2p(Wi(t))},r.p2d=r.p2r=f,r.cleanPos=Qi):"log"===r.type?(r.d2r=r.d2l=function(t,e){return o(Wi(t),e)},r.r2d=r.r2c=function(t){return Ji(Wi(t))},r.d2c=r.r2l=Wi,r.c2d=r.l2r=Qi,r.c2r=o,r.l2d=Ji,r.d2p=function(t,e){return r.l2p(r.d2r(t,e))},r.p2d=function(t){return Ji(f(t))},r.r2p=function(t){return r.l2p(Wi(t))},r.p2r=f,r.cleanPos=Qi):"date"===r.type?(r.d2r=r.r2d=re.identity,r.d2c=r.r2c=r.d2l=r.r2l=s,r.c2d=r.c2r=r.l2d=r.l2r=l,r.d2p=r.r2p=function(t,e,n){return r.l2p(s(t,0,n))},r.p2d=r.p2r=function(t,e,r){return l(f(t),e,r)},r.cleanPos=function(t){return re.cleanDate(t,$i,r.calendar)}):"category"===r.type&&(r.d2c=r.d2l=function(t){if(null!==t&&void 0!==t){if(void 0===r._categoriesMap&&(r._categoriesMap={}),void 0!==r._categoriesMap[t])return r._categoriesMap[t];r._categories.push(t);var e=r._categories.length-1;return r._categoriesMap[t]=e,e}return $i},r.r2d=r.c2d=r.l2d=u,r.d2r=r.d2l_noadd=c,r.r2c=function(t){var e=c(t);return void 0!==e?e:r.fraction2r(.5)},r.l2r=r.c2r=Qi,r.r2l=c,r.d2p=function(t){return r.l2p(r.r2c(t))},r.p2d=function(t){return u(f(t))},r.r2p=r.d2p,r.p2r=f,r.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Qi(t)}),r.fraction2r=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return r.l2r(e+t*(n-e))},r.r2fraction=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return(r.r2l(t)-e)/(n-e)},r.cleanRange=function(t,n){n||(n={}),t||(t="range");var a,o,s=re.nestedProperty(r,t).get();if(o=(o="date"===r.type?re.dfltRange(r.calendar):"y"===i?Oe.DFLTRANGEY:n.dfltRange||Oe.DFLTRANGEX).slice(),s&&2===s.length)for("date"===r.type&&(s[0]=re.cleanDate(s[0],$i,r.calendar),s[1]=re.cleanDate(s[1],$i,r.calendar)),a=0;a<2;a++)if("date"===r.type){if(!re.isDateTime(s[a],r.calendar)){r[t]=o;break}if(r.r2l(s[0])===r.r2l(s[1])){var l=re.constrain(r.r2l(s[0]),re.MIN_MS+1e3,re.MAX_MS-1e3);s[0]=r.l2r(l-1e3),s[1]=r.l2r(l+1e3);break}}else{if(!e(s[a])){if(!e(s[1-a])){r[t]=o;break}s[a]=s[1-a]*(a?10:.1)}if(s[a]<-Ki?s[a]=-Ki:s[a]>Ki&&(s[a]=Ki),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else re.nestedProperty(r,t).set(o)},r.setScale=function(t){var e=n._size;if(r._categories||(r._categories=[]),r._categoriesMap||(r._categoriesMap={}),r.overlaying){var a=hi.getFromId({_fullLayout:n},r.overlaying);r.domain=a.domain}var o=t&&r._r?"_r":"range",s=r.calendar;r.cleanRange(o);var l=r.r2l(r[o][0],s),u=r.r2l(r[o][1],s);if("y"===i?(r._offset=e.t+(1-r.domain[1])*e.h,r._length=e.h*(r.domain[1]-r.domain[0]),r._m=r._length/(l-u),r._b=-r._m*u):(r._offset=e.l+r.domain[0]*e.w,r._length=e.w*(r.domain[1]-r.domain[0]),r._m=r._length/(u-l),r._b=-r._m*l),!isFinite(r._m)||!isFinite(r._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},r.makeCalcdata=function(t,e){var n,i,a,o,s=r.type,l="date"===s&&t[e+"calendar"];if(e in t){if(n=t[e],o=t._length||n.length,re.isTypedArray(n)&&("linear"===s||"log"===s)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(i=new Array(o),a=0;a2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},fa.saveRangeInitial=function(t,e){for(var r=fa.list(t,"",!0),n=!1,i=0;i.3*f||c(i)||c(a))){var d=n.dtick/2;t+=t+d.8){var o=Number(r.substr(1));a.exactYears>.8&&o%12==0?t=fa.tickIncrement(t,"M6","reverse")+1.5*ia:a.exactMonths>.8?t=fa.tickIncrement(t,"M1","reverse")+15.5*ia:t-=ia/2;var s=fa.tickIncrement(t,r);if(s<=n)return s}return t}(p,t,s.dtick,l,a)),d=p,0;d<=u;)d=fa.tickIncrement(d,s.dtick,!1,a),0;return{start:r.c2r(p,0,a),end:r.c2r(d,0,a),size:s.dtick,_dataSpan:u-l}},fa.prepTicks=function(t){var e=re.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=re.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),fa.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),Aa(t)},fa.calcTicks=function(t){fa.prepTicks(t);var e=re.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),o=re.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],l=1.0001*o[1]-1e-4*o[0],u=Math.min(s,l),c=Math.max(s,l),h=0;Array.isArray(i)||(i=[]);var f="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:l<=n)&&!(a.length>s||l===o);l=fa.tickIncrement(l,t.dtick,i,t.calendar))o=l,a.push(l);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(a.length),c=0;c10||"01-01"!==i.substr(5)?t._tickround="d":t._tickround=+r.substr(1)%12==0?"y":"m";else if(r>=ia&&a<=10||r>=15*ia)t._tickround="d";else if(r>=oa&&a<=16||r>=aa)t._tickround="M";else if(r>=sa&&a<=19||r>=oa)t._tickround="S";else{var o=t.l2r(n+r).replace(/^-/,"").length;t._tickround=Math.max(a,o)-20}}else if(e(r)||"L"===r.charAt(0)){var s=t.range.map(t.r2d||Number);e(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),u=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(u)>3&&(Ea(t.exponentformat)&&!La(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function Ta(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}fa.autoTicks=function(t,r){var n;function i(t){return Math.pow(t,Math.floor(Math.log(r)/Math.LN10))}if("date"===t.type){t.tick0=re.dateTick0(t.calendar);var a=2*r;a>ra?(r/=ra,n=i(10),t.dtick="M"+12*Ma(r,n,va)):a>na?(r/=na,t.dtick="M"+Ma(r,1,ma)):a>ia?(t.dtick=Ma(r,ia,ba),t.tick0=re.dateTick0(t.calendar,!0)):a>aa?t.dtick=Ma(r,aa,ma):a>oa?t.dtick=Ma(r,oa,ya):a>sa?t.dtick=Ma(r,sa,ya):(n=i(10),t.dtick=Ma(r,n,va))}else if("log"===t.type){t.tick0=0;var o=re.simpleMap(t.range,t.r2l);if(r>.7)t.dtick=Math.ceil(r);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/r);r=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,n=i(10),t.dtick="L"+Ma(r,n,va)}else t.dtick=r>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(r,1))):"angular"===t._id?(t.tick0=0,n=1,t.dtick=Ma(r,n,wa)):(t.tick0=0,n=i(10),t.dtick=Ma(r,n,va));if(0===t.dtick&&(t.dtick=1),!e(t.dtick)&&"string"!=typeof t.dtick){var l=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(l)}},fa.tickIncrement=function(r,n,i,a){var o=i?-1:1;if(e(n))return r+o*n;var s=n.charAt(0),l=o*Number(n.substr(1));if("M"===s)return re.incrementMonth(r,l,a);if("L"===s)return Math.log(Math.pow(10,r)+l)/Math.LN10;if("D"===s){var u="D2"===n?_a:xa,c=r+.01*o,h=re.roundUp(re.mod(c,1),u,i);return Math.floor(c)+Math.log(t.round(Math.pow(10,h),1))/Math.LN10}throw"unrecognized dtick "+String(n)},fa.tickFirst=function(r){var n=r.r2l||Number,i=re.simpleMap(r.range,n),a=i[1]"+s,t._prevDateHead=s));r.text=l}(t,o,n,l):"log"===t.type?function(t,r,n,i,a){var o=t.dtick,s=r.x,l=t.tickformat;"never"===a&&(a="");!i||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(l||"string"==typeof o&&"L"===o.charAt(0))r.text=Ca(Math.pow(10,s),t,a,i);else if(e(o)||"D"===o.charAt(0)&&re.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||Ea(t.exponentformat)&&La(u)?(r.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+la+-u+"",r.fontSize*=1.25):(r.text=Ca(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(r.dy-=r.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);r.text=String(Math.round(Math.pow(10,re.mod(s,1)))),r.fontSize*=.75}if("D1"===t.dtick){var c=String(r.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?r.dx-=r.fontSize/4:(r.dy+=r.fontSize/2,r.dx+=(t.range[1]>t.range[0]?1:-1)*r.fontSize*(s<0?.5:.25)))}}(t,o,0,l,i):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=Ca(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(o[1]>=100)e.text=Ca(re.deg2rad(e.x),t,i,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),s&&(e.text=la+e.text)}}}}(t,o,n,l,i):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=Ca(e.x,t,i,n)}(t,o,0,l,i),t.tickprefix&&!f(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!f(t.showticksuffix)&&(o.text+=t.ticksuffix),o},fa.hoverLabelText=function(t,e,r){if(r!==ua&&r!==e)return fa.hoverLabelText(t,e)+" - "+fa.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=fa.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":la+i:i};var ka=["f","p","n","\u03bc","m","","k","M","G","T"];function Ea(t){return"SI"===t||"B"===t}function La(t){return t>14||t<-15}function Ca(t,r,n,i){var a=t<0,o=r._tickround,s=n||r.exponentformat||"B",l=r._tickexponent,u=fa.getTickFormat(r),c=r.separatethousands;if(i){var h={exponentformat:s,dtick:"none"===r.showexponent?r.dtick:e(t)&&Math.abs(t)||1,range:"none"===r.showexponent?r.range.map(r.r2d):[0,t||1]};Aa(h),o=(Number(h._tickround)||0)+4,l=h._tickexponent,r.hoverformat&&(u=r.hoverformat)}if(u)return r._numFormat(u)(t).replace(/-/g,la);var f,d=Math.pow(10,-o)/2;if("none"===s&&(l=0),(t=Math.abs(t))"+f+"":"B"===s&&9===l?t+="B":Ea(s)&&(t+=ka[l/3+5]));return a?la+t:t}function Sa(t,e){for(var r=0;r=0,a=u(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=a(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n-1&&s.length>p&&(s=p>3?s.substr(0,p-3)+"...":s.substr(0,p))}void 0!==e.zLabel?(void 0!==e.xLabel&&(l+="x: "+e.xLabel+"
"),void 0!==e.yLabel&&(l+="y: "+e.yLabel+"
"),l+=(l?"z: ":"")+e.zLabel):w&&e[i+"Label"]===v?l=e[("x"===i?"y":"x")+"Label"]||"":void 0===e.xLabel?void 0!==e.yLabel&&(l=e.yLabel):l=void 0===e.yLabel?e.xLabel:"("+e.xLabel+", "+e.yLabel+")",e.text&&!Array.isArray(e.text)&&(l+=(l?"
":"")+e.text),void 0!==e.extraText&&(l+=(l?"
":"")+e.extraText),""===l&&(""===s&&r.remove(),l=s);var g=r.select("text.nums").call(hn.font,e.fontFamily||c,e.fontSize||h,e.fontColor||d).text(l).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),m=r.select("text.name"),y=0;s&&s!==l?(m.call(hn.font,e.fontFamily||c,e.fontSize||h,f).text(s).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),y=m.node().getBoundingClientRect().width+2*Ba):(m.remove(),r.select("rect").remove()),r.select("path").style({fill:f,stroke:d});var M,A,T=g.node().getBoundingClientRect(),k=e.xa._offset+(e.x0+e.x1)/2,E=e.ya._offset+(e.y0+e.y1)/2,L=Math.abs(e.x1-e.x0),C=Math.abs(e.y1-e.y0),S=T.width+ja+Ba+y;e.ty0=b-T.top,e.bx=T.width+2*Ba,e.by=T.height+2*Ba,e.anchor="start",e.txwidth=T.width,e.tx2width=y,e.offset=0,a?(e.pos=k,M=E+C/2+S<=_,A=E-C/2-S>=0,"top"!==e.idealAlign&&M||!A?M?(E+=C/2,e.anchor="start"):e.anchor="middle":(E-=C/2,e.anchor="end")):(e.pos=E,M=k+L/2+S<=x,A=k-L/2-S>=0,"left"!==e.idealAlign&&M||!A?M?(k+=L/2,e.anchor="start"):e.anchor="middle":(k-=L/2,e.anchor="end")),g.attr("text-anchor",e.anchor),y&&m.attr("text-anchor",e.anchor),r.attr("transform","translate("+k+","+E+")"+(a?"rotate("+Ia+")":""))}),L}function Va(e,r){e.each(function(e){var n=t.select(this);if(e.del)n.remove();else{var i="end"===e.anchor?-1:1,a=n.select("text.nums"),o={start:1,end:-1,middle:0}[e.anchor],s=o*(ja+Ba),l=s+o*(e.txwidth+Ba),u=0,c=e.offset;"middle"===e.anchor&&(s-=e.tx2width/2,l+=e.txwidth/2+Ba),r&&(c*=-Fa,u=e.offset*za),n.select("path").attr("d","middle"===e.anchor?"M-"+(e.bx/2+e.tx2width/2)+","+(c-e.by/2)+"h"+e.bx+"v"+e.by+"h-"+e.bx+"Z":"M0,0L"+(i*ja+u)+","+(ja+c)+"v"+(e.by/2-ja)+"h"+i*e.bx+"v-"+e.by+"H"+(i*ja+u)+"V"+(c-ja)+"Z"),a.call(Fr.positionText,s+u,c+e.ty0-e.by/2+Ba),e.tx2width&&(n.select("text.name").call(Fr.positionText,l+o*Ba+u,c+e.ty0-e.by/2+Ba),n.select("rect").call(hn.setRect,l+(o-1)*e.tx2width/2+u,c-e.by/2-1,e.tx2width,e.by+2))}})}function Ha(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return re.castOption(i,r,t)||re.extractOption({},n,"",e)}:function(t,e){return re.extractOption(a,n,t,e)};function s(e,r,n){var i=o(r,n);i&&(t[e]=i)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=re.constrain(t.x0,0,t.xa._length),t.x1=re.constrain(t.x1,0,t.xa._length),t.y0=re.constrain(t.y0,0,t.ya._length),t.y1=re.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:ea.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:ea.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var l=ea.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+l+" / -"+ea.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+l,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=ea.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+ea.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function qa(t,e){var r,n,i=e.container,a=e.fullLayout,o=e.event,l=!!t.hLinePoint,u=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),u||l){var c=Ne.combine(a.plot_bgcolor,a.paper_bgcolor);if(l){var h,f,d=t.hLinePoint;r=d&&d.xa,"cursor"===(n=d&&d.ya).spikesnap?(h=o.pointerX,f=o.pointerY):(h=r._offset+d.x,f=n._offset+d.y);var p,g,v=s.readability(d.color,c)<1.5?Ne.contrast(c):d.color,m=n.spikemode,y=n.spikethickness,b=n.spikecolor||v,x=n._boundingBox,_=(x.left+x.right)/2H.width||U<0||U>H.height)return rr.unhoverRaw(r,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(_="xval"in n?Pn.flat(o,n.xval):Pn.p2c(d,B),w="yval"in n?Pn.flat(o,n.yval):Pn.p2c(p,U),!e(_[0])||!e(w[0]))return re.warn("Fx.hover failed",n,r),rr.unhoverRaw(r,n)}var q=1/0;for(A=0;AI&&(z.splice(0,I),q=z[0].distance),c&&0!==D&&0===z.length){O.distance=D,O.index=!1;var Z=k._module.hoverPoints(O,S,P,"closest",s._hoverlayer);if(Z&&(Z=Z.filter(function(t){return t.spikeDistance<=D})),Z&&Z.length){var Q,K=Z.filter(function(t){return t.xa.showspikes});if(K.length){var $=K[0];e($.x0)&&e($.y0)&&(Q=rt($),(!j.vLinePoint||j.vLinePoint.spikeDistance>Q.spikeDistance)&&(j.vLinePoint=Q))}var J=Z.filter(function(t){return t.ya.showspikes});if(J.length){var tt=J[0];e(tt.x0)&&e(tt.y0)&&(Q=rt(tt),(!j.hLinePoint||j.hLinePoint.spikeDistance>Q.spikeDistance)&&(j.hLinePoint=Q))}}}}function et(t,e){for(var r,n=null,i=1/0,a=0;a1,gt=Ne.combine(s.plot_bgcolor||Ne.background,s.paper_bgcolor),vt={hovermode:x,rotateLabels:pt,bgColor:gt,container:s._hoverlayer,outerContainer:s._paperdiv,commonLabelOpts:s.hoverlabel,hoverdistance:s.hoverdistance},mt=Ua(z,vt,r);if(function(t,e,r){var n,i,a,o,s,l,u,c=0,h=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?Da:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function f(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(s=p.length-1;s>=0;s--)p[s].dp+=i;for(d.push.apply(d,p),h.splice(o+1,1),u=0,s=d.length-1;s>=0;s--)u+=d[s].dp;for(a=u/d.length,s=d.length-1;s>=0;s--)d[s].dp-=a;n=!1}else o++}h.forEach(f)}for(o=h.length-1;o>=0;o--){var m=h[o];for(s=m.length-1;s>=0;s--){var y=m[s],b=t[y.i];b.offset=y.dp,b.del=y.del}}}(z,pt?"xa":"ya",s),Va(mt,pt),n.target&&n.target.tagName){var yt=R.getComponentMethod("annotations","hasClickToShow")(r,ft);zn(t.select(n.target),yt?"pointer":"")}if(!n.target||a||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}(r,0,ht))return;ht&&r.emit("plotly_unhover",{event:n,points:ht});r.emit("plotly_hover",{event:n,points:r._hoverdata,xaxes:d,yaxes:p,xvals:_,yvals:w})}(r,n,i,a)})},Oa.loneHover=function(e,r){var n={color:e.color||Ne.defaultLine,x0:e.x0||e.x||0,x1:e.x1||e.x||0,y0:e.y0||e.y||0,y1:e.y1||e.y||0,xLabel:e.xLabel,yLabel:e.yLabel,zLabel:e.zLabel,text:e.text,name:e.name,idealAlign:e.idealAlign,borderColor:e.borderColor,fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},i=t.select(r.container),a=r.outerContainer?t.select(r.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||Ne.background,container:i,outerContainer:a},s=Ua([n],o,r.gd);return Va(s,o.rotateLabels),s.node()};var Xa=Oa.hover,Wa=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),re.coerceFont(r,"hoverlabel.font",n.font)},Ya=k({editType:"none"});Ya.family.dflt=Xe.HOVERFONT,Ya.size.dflt=Xe.HOVERFONTSIZE;var Za={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Ya,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var Qa={moduleType:"component",name:"fx",constants:Xe,schema:{layout:Za},attributes:E,layoutAttributes:Za,supplyLayoutGlobalDefaults:function(t,e){Wa(0,0,function(r,n){return re.coerce(t,e,Za,r,n)})},supplyDefaults:function(t,e,r,n){Wa(0,0,function(r,n){return re.coerce(t,e,E,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return re.coerce(t,e,Za,r,n)}var i;"select"===n("dragmode")&&n("selectdirection"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}r._w=L,r._h=C;for(var I=!1,N=["x","y"],D=0;D1)&&(q===H?((J=G.r2fraction(r["a"+V]))<0||J>1)&&(I=!0):I=!0,I))continue;z=G._offset+G.r2p(r[V]),B=.5}else"x"===V?(j=r[V],z=c.l+c.w*j):(j=1-r[V],z=c.t+c.h*j),B=r.showarrow?.5:j;if(r.showarrow){$.head=z;var tt=r["a"+V];U=W*O(.5,r.xanchor)-Y*O(.5,r.yanchor),q===H?($.tail=G._offset+G.r2p(tt),F=U):($.tail=z+tt,F=U+tt),$.text=$.tail+U;var et=u["x"===V?"width":"height"];if("paper"===H&&($.head=re.constrain($.head,1,et-1)),"pixel"===q){var rt=-Math.max($.tail-3,$.text),nt=Math.min($.tail+3,$.text)-et;rt>0?($.tail+=rt,$.text+=rt):nt>0&&($.tail-=nt,$.text-=nt)}$.tail+=K,$.head+=K}else F=U=Z*O(B,Q),$.text=z+U;$.text+=K,U+=K,F+=K,r["_"+V+"padplus"]=Z/2+F,r["_"+V+"padminus"]=Z/2-F,r["_"+V+"size"]=Z,r["_"+V+"shift"]=U}if(I)b.remove();else{var it=0,at=0;if("left"!==r.align&&(it=(L-_)*("center"===r.align?.5:1)),"top"!==r.valign&&(at=(C-k)*("middle"===r.valign?.5:1)),s)n.select("svg").attr({x:w+it-1,y:w+at}).call(hn.setClipUrl,A?f:null);else{var ot=w+at-y.top,st=w+it-y.left;E.call(Fr.positionText,st,ot).call(hn.setClipUrl,A?f:null)}T.select("rect").call(hn.setRect,w,w,L,C),M.call(hn.setRect,x/2,x/2,S-x,P-x),b.call(hn.setTranslate,Math.round(d.x.text-S/2),Math.round(d.y.text-P/2)),v.attr({transform:"rotate("+p+","+d.x.text+","+d.y.text+")"});var lt,ut,ct=function(t,n){g.selectAll(".annotation-arrow-g").remove();var s=d.x.head,u=d.y.head,f=d.x.tail+t,m=d.y.tail+n,y=d.x.text+t,x=d.y.text+n,_=re.rotationXYMatrix(p,y,x),w=re.apply2DTransform(_),A=re.apply2DTransform2(_),T=+M.attr("width"),k=+M.attr("height"),E=y-.5*T,L=E+T,C=x-.5*k,S=C+k,P=[[E,C,E,S],[E,S,L,S],[L,S,L,C],[L,C,E,C]].map(A);if(!P.reduce(function(t,e){return t^!!re.segmentsIntersect(s,u,s+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){P.forEach(function(t){var e=re.segmentsIntersect(f,m,s,u,t[0],t[1],t[2],t[3]);e&&(f=e.x,m=e.y)});var O=r.arrowwidth,I=r.arrowcolor,N=r.arrowside,D=g.append("g").style({opacity:Ne.opacity(I)}).classed("annotation-arrow-g",!0),z=D.append("path").attr("d","M"+f+","+m+"L"+s+","+u).style("stroke-width",O+"px").call(Ne.stroke,Ne.rgb(I));if(Be(z,N,r),h.annotationPosition&&z.node().parentNode&&!i){var F=s,j=u;if(r.standoff){var B=Math.sqrt(Math.pow(s-f,2)+Math.pow(u-m,2));F+=r.standoff*(f-s)/B,j+=r.standoff*(m-u)/B}var U,V,H,q=D.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(f-F)+","+(m-j),transform:"translate("+F+","+j+")"}).style("stroke-width",O+6+"px").call(Ne.stroke,"rgba(0,0,0,0)").call(Ne.fill,"rgba(0,0,0,0)");rr.init({element:q.node(),gd:e,prepFn:function(){var t=hn.getTranslate(b);V=t.x,H=t.y,U={},a&&a.autorange&&(U[a._name+".autorange"]=!0),o&&o.autorange&&(U[o._name+".autorange"]=!0)},moveFn:function(t,e){var n=w(V,H),i=n[0]+t,s=n[1]+e;b.call(hn.setTranslate,i,s),U[l+".x"]=a?a.p2r(a.r2p(r.x)+t):r.x+t/c.w,U[l+".y"]=o?o.p2r(o.r2p(r.y)+e):r.y-e/c.h,r.axref===r.xref&&(U[l+".ax"]=a.p2r(a.r2p(r.ax)+t)),r.ayref===r.yref&&(U[l+".ay"]=o.p2r(o.r2p(r.ay)+e)),D.attr("transform","translate("+t+","+e+")"),v.attr({transform:"rotate("+p+","+i+","+s+")"})},doneFn:function(){R.call("relayout",e,U);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}};if(r.showarrow&&ct(0,0),m)rr.init({element:b.node(),gd:e,prepFn:function(){ut=v.attr("transform"),lt={}},moveFn:function(t,e){var n="pointer";if(r.showarrow)r.axref===r.xref?lt[l+".ax"]=a.p2r(a.r2p(r.ax)+t):lt[l+".ax"]=r.ax+t,r.ayref===r.yref?lt[l+".ay"]=o.p2r(o.r2p(r.ay)+e):lt[l+".ay"]=r.ay+e,ct(t,e);else{if(i)return;if(a)lt[l+".x"]=a.p2r(a.r2p(r.x)+t);else{var s=r._xsize/c.w,u=r.x+(r._xshift-r.xshift)/c.w-s/2;lt[l+".x"]=rr.align(u+t/c.w,s,0,1,r.xanchor)}if(o)lt[l+".y"]=o.p2r(o.r2p(r.y)+e);else{var h=r._ysize/c.h,f=r.y-(r._yshift+r.yshift)/c.h-h/2;lt[l+".y"]=rr.align(f-e/c.h,h,0,1,r.yanchor)}a&&o||(n=rr.getCursor(a?.5:lt[l+".x"],o?.5:lt[l+".y"],r.xanchor,r.yanchor))}v.attr({transform:"translate("+t+","+e+")"+ut}),Nn(b,n)},doneFn:function(){Nn(b),R.call("relayout",e,lt);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}}var to=Ka.draw;function eo(t){var e=t._fullLayout;re.filterVisible(e.annotations).forEach(function(e){var r,n,i,a,o=ea.getFromId(t,e.xref),s=ea.getFromId(t,e.yref),l=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=l+e.xshift,n=l-e.xshift,i=u+e.xshift,a=u-e.xshift,e.axref===e.xref?(ea.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),ea.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,a)})):(i=e.ax?i+e.ax:i,a=e.ax?a-e.ax:a,ea.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,a)}))),s&&s.autorange&&(r=l-e.yshift,n=l+e.yshift,i=u-e.yshift,a=u+e.yshift,e.ayref===e.yref?(ea.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),ea.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,a)})):(i=e.ay?i+e.ay:i,a=e.ay?a-e.ay:a,ea.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,a)})))})}var ro={hasClickToShow:function(t,e){var r=no(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=no(t,e),i=n.on,a=n.off.concat(n.explicitOff),o={};if(!i.length&&!a.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+i+'"]').remove():(a._pdata=go(t.glplot.cameraParams,[e.xaxis.r2l(a.x)*r[0],e.yaxis.r2l(a.y)*r[1],e.zaxis.r2l(a.z)*r[2]]),vo(t.graphDiv,a,i,t.id,a._xa,a._ya))}}};var bo={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},xo=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+n[e],a=+i[e];return isNaN(r)&&isNaN(a)?[NaN,NaN]:[a||0,r||0]}}var a=_o(e,t.value),o=_o(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=a(t);return[e,e]}:function(t){return[o(t),a(t)]}};function _o(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var wo=function(t){for(var e=t.calcdata,r=0;r0;r.each(function(r){var l,u=r[0].trace,c=u.error_x||{},h=u.error_y||{};u.ids&&(l=function(t){return t.id});var f=cn.hasMarkers(u)&&u.marker.maxdisplayed>0;h.visible||c.visible||(r=[]);var d=t.select(this).selectAll("g.errorbar").data(r,l);if(d.exit().remove(),r.length){c.visible||d.selectAll("path.xerror").remove(),h.visible||d.selectAll("path.yerror").remove(),d.style("opacity",1);var p=d.enter().append("g").classed("errorbar",!0);s&&p.style("opacity",0).transition().duration(i.duration).style("opacity",1),hn.setClipUrl(d,n.layerClipId),d.each(function(r){var n=t.select(this),l=function(t,r,n){var i={x:r.c2p(t.x),y:n.c2p(t.y)};return void 0!==t.yh&&(i.yh=n.c2p(t.yh),i.ys=n.c2p(t.ys),e(i.ys)||(i.noYS=!0,i.ys=n.c2p(t.ys,!0))),void 0!==t.xh&&(i.xh=r.c2p(t.xh),i.xs=r.c2p(t.xs),e(i.xs)||(i.noXS=!0,i.xs=r.c2p(t.xs,!0))),i}(r,a,o);if(!f||r.vis){var u,d=n.select("path.yerror");if(h.visible&&e(l.x)&&e(l.yh)&&e(l.ys)){var p=h.width;u="M"+(l.x-p)+","+l.yh+"h"+2*p+"m-"+p+",0V"+l.ys,l.noYS||(u+="m-"+p+",0h"+2*p),d.size()?s&&(d=d.transition().duration(i.duration).ease(i.easing)):d=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),d.attr("d",u)}else d.remove();var g=n.select("path.xerror");if(c.visible&&e(l.y)&&e(l.xh)&&e(l.xs)){var v=(c.copy_ystyle?h:c).width;u="M"+l.xh+","+(l.y-v)+"v"+2*v+"m0,-"+v+"H"+l.xs,l.noXS||(u+="m0,-"+v+"v"+2*v),g.size()?s&&(g=g.transition().duration(i.duration).ease(i.easing)):g=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",u)}else g.remove()}})}})},style:function(e){e.each(function(e){var r=e[0].trace,n=r.error_y||{},i=r.error_x||{},a=t.select(this);a.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(Ne.stroke,n.color),i.copy_ystyle&&(i=n),a.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(Ne.stroke,i.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var Lo={},Co=m.extendFlat;Lo.attributes=function(t,e){t=t||{},e=e||{};var r={valType:"info_array",editType:t.editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},n=(t.name&&t.name,t.trace,e.description&&e.description,{x:Co({},r,{}),y:Co({},r,{}),editType:t.editType});return t.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:t.editType},n.column={valType:"integer",min:0,dflt:0,editType:t.editType}),n},Lo.defaults=function(t,e,r,n){var i=n&&n.x||[0,1],a=n&&n.y||[0,1],o=e.grid;if(o){var s=r("domain.column");void 0!==s&&(s1){s||l||u||"independent"===b("pattern")&&(s=!0),h._hasSubplotGrid=s;var p,g,v="top to bottom"===b("roworder"),m=s?.2:.1,y=s?.3:.1;c&&(p="bottom",g="left"),h._domains={x:No("x",b,m,p,d),y:No("y",b,y,g,f,v)}}}function b(t,e){return re.coerce(r,h,Oo,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,a,o,s,l,u,c=t.grid||{},h=e._subplots,f=r._hasSubplotGrid,d=r.rows,p=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(f){var m=c.subplots||[];l=r.subplots=new Array(d);var y=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},Go={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Xo=!0,Wo=function(t,e,r){if(!e._dragged&&!e._editing){var n,i,a,o,s,l=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,h=u.trace,f=h.legendgroup,d={},p=[],g=[],v=[];if(1===r&&Xo&&e.data&&e._context.showTips?(re.notifier(re._(e,"Double-click on legend to isolate one trace"),"long"),Xo=!1):Xo=!1,R.traceIs(h,"pie")){var m=u.label,y=l.indexOf(m);1===r?-1===y?l.push(m):l.splice(y,1):2===r&&(l=[],e.calcdata[0].forEach(function(t){m!==t.label&&l.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===l.length&&-1===y&&(l=[])),R.call("relayout",e,"hiddenlabels",l)}else{var b,x=f&&f.length,_=[];if(x)for(n=0;nr[1])return r[1]}return i}function h(t){return t[0]}if(s||l||u){var f={},d={};s&&(f.mc=c("marker.color",h),f.mo=c("marker.opacity",re.mean,[.2,1]),f.ms=c("marker.size",re.mean,[2,16]),f.mlc=c("marker.line.color",h),f.mlw=c("marker.line.width",re.mean,[0,5]),d.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(d.line={width:c("line.width",h,[0,10])}),l&&(f.tx="Aa",f.tp=c("textposition",h),f.ts=10,f.tc=c("textfont.color",h),f.tf=c("textfont.family",h)),n=[re.minExtend(a,f)],i=re.minExtend(o,d)}var p=t.select(this).select("g.legendpoints"),g=p.selectAll("path.scatterpts").data(s?n:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(hn.pointStyle,i,r),s&&(n[0].mrc=3);var v=p.selectAll("g.pointtext").data(l?n:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(hn.textPointStyle,i,r)}).each(function(e){var r=e[0].trace,n=t.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===r.type&&r.visible?[e,e]:[]);n.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),n.exit().remove(),n.each(function(e,n){var i=r[n?"increasing":"decreasing"],a=i.line.width,o=t.select(this);o.style("stroke-width",a+"px").call(Ne.fill,i.fillcolor),a&&Ne.stroke(o,i.line.color)})}).each(function(e){var r=e[0].trace,n=t.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===r.type&&r.visible?[e,e]:[]);n.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),n.exit().remove(),n.each(function(e,n){var i=r[n?"increasing":"decreasing"],a=i.line.width,o=t.select(this);o.style("fill","none").call(hn.dashLine,i.line.dash,a),a&&Ne.stroke(o,i.line.color)})})},$o=Nr.LINE_SPACING,Jo=Nr.FROM_TL,ts=Nr.FROM_BR,es=f.DBLCLICKDELAY;function rs(t,e){var r=t.data()[0][0],n=e._fullLayout,i=r.trace,a=R.traceIs(i,"pie"),o=i.index,s=a?r.label:i.name,l=re.ensureSingle(t,"text","legendtext");function u(r){Fr.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*$o;if(o){var l=hn.bBox(o);n=l.height,i=l.width,hn.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),c=Fr.lineCount(u),h=u.node();n=s*c,i=h?hn.bBox(h).width:0;var f=s*(.3+(1-c)/2);Fr.positionText(u,40,f)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}l.attr("text-anchor","start").classed("user-select-none",!0).call(hn.font,n.legend.font).text(s),e._context.edits.legendText&&!a?l.call(Fr.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n=t;this.text()||(t=" ");var i=r.trace._fullInput||{},a={};if(R.hasTransform(i,"groupby")){var s=R.getTransformIndices(i,"groupby"),l=s[s.length-1],c=re.keyedContainer(i,"transforms["+l+"].styles","target","value.name");""===n?c.remove(r.trace._group):c.set(r.trace._group,t),a=c.constructUpdate()}else a.name=t;return R.call("restyle",e,a,o)}):u(l)}function ns(t,e){var r,n=1,i=re.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call(Ne.fill,"rgba(0,0,0,0)")});i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimees&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Wo(t,e,n)},es):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,Wo(t,e,n))}})}function is(e,r,n){var i=e._fullLayout,a=i.legend,o=a.borderwidth,s=Ho.isGrouped(a),l=0;if(a._width=0,a._height=0,Ho.isVertical(a))s&&r.each(function(t,e){hn.setTranslate(this,0,e*a.tracegroupgap)}),n.each(function(t){var e=t[0],r=e.height,n=e.width;hn.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],c=r.data(),h=0,f=c.length;ho+x-_,n.each(function(t){var e=t[0],r=g?40+t[0].width:y;o+b+_+r>i.width-(i.margin.r+i.margin.l)&&(b=0,v+=m,a._height=a._height+m,m=0),hn.setTranslate(this,o+b,5+o+e.height/2+v),a._width+=_+r,a._height=Math.max(a._height,e.height),b+=_+r,m=Math.max(e.height,m)}),a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height),n.each(function(r){var n=r[0],i=t.select(this).select(".legendtoggle");hn.setRect(i,0,-n.height/2,(e._context.edits.legendText?0:a._width)+l,n.height)})}function as(t){var e=t._fullLayout.legend,r="left";qo.isRightAnchor(e)?r="right":qo.isCenterAnchor(e)&&(r="center");var n="top";qo.isBottomAnchor(e)?n="bottom":qo.isMiddleAnchor(e)&&(n="middle"),bi.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*Jo[r],r:e._width*ts[r],b:e._height*ts[n],t:e._height*Jo[n]})}var os={moduleType:"component",name:"legend",layoutAttributes:Vo,supplyLayoutDefaults:function(t,e,r){for(var n,i,a,o,s=t.legend||{},l={},u=0,c="normal",h=0;h1)){if(e.legend=l,d("bgcolor",e.paper_bgcolor),d("bordercolor"),d("borderwidth"),re.coerceFont(d,"font",e.font),d("orientation"),"h"===l.orientation){var p=t.xaxis;p&&p.rangeslider&&p.rangeslider.visible?(n=0,a="left",i=1.1,o="bottom"):(n=0,a="left",i=-.1,o="top")}d("traceorder",c),Ho.isGrouped(e.legend)&&d("tracegroupgap"),d("x",n),d("xanchor",a),d("y",i),d("yanchor",o),re.noneOrAll(s,l,["x","y"])}},draw:function(e){var r=e._fullLayout,n="legend"+r._uid;if(r._infolayer&&e.calcdata){e._legendMouseDownTime||(e._legendMouseDownTime=0);var i=r.legend,a=r.showlegend&&function(t,e){var r,n,i={},a=[],o=!1,s={},l=0;function u(t,r){if(""!==t&&Ho.isGrouped(e))-1===a.indexOf(t)?(a.push(t),o=!0,i[t]=[[r]]):i[t].push([r]);else{var n="~~i"+l;a.push(n),i[n]=[[r]],l++}}for(r=0;rv?function(t){var e=t._fullLayout.legend,r="left";qo.isRightAnchor(e)?r="right":qo.isCenterAnchor(e)&&(r="center"),bi.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*Jo[r],r:e._width*ts[r],b:0,t:0})}(e):as(e);var m=r._size,y=m.l+m.w*i.x,b=m.t+m.h*(1-i.y);qo.isRightAnchor(i)?y-=i._width:qo.isCenterAnchor(i)&&(y-=i._width/2),qo.isBottomAnchor(i)?b-=i._height:qo.isMiddleAnchor(i)&&(b-=i._height/2);var x=i._width,_=m.w;x>_?(y=m.l,x=_):(y+x>g&&(y=g-x),y<0&&(y=0),x=Math.min(g-y,i._width));var w,M,A,T,k=i._height,E=m.h;if(k>E?(b=m.t,k=E):(b+k>v&&(b=v-k),b<0&&(b=0),k=Math.min(v-b,i._height)),hn.setTranslate(l,y,b),f.on(".drag",null),l.on("wheel",null),i._height<=k||e._context.staticPlot)c.attr({width:x-i.borderwidth,height:k-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),hn.setTranslate(h,0,0),u.select("rect").attr({width:x-2*i.borderwidth,height:k-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth}),hn.setClipUrl(h,n),hn.setRect(f,0,0,0,0),delete i._scrollY;else{var L,C,S=Math.max(Go.scrollBarMinHeight,k*k/i._height),P=k-S-2*Go.scrollBarMargin,O=i._height-k,I=P/O,N=Math.min(i._scrollY||0,O);c.attr({width:x-2*i.borderwidth+Go.scrollBarWidth+Go.scrollBarMargin,height:k-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),u.select("rect").attr({width:x-2*i.borderwidth+Go.scrollBarWidth+Go.scrollBarMargin,height:k-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth+N}),hn.setClipUrl(h,n),z(N,S,I),l.on("wheel",function(){z(N=re.constrain(i._scrollY+t.event.deltaY/P*O,0,O),S,I),0!==N&&N!==O&&t.event.preventDefault()});var D=t.behavior.drag().on("dragstart",function(){L=t.event.sourceEvent.clientY,C=N}).on("drag",function(){var e=t.event.sourceEvent;2===e.buttons||e.ctrlKey||z(N=re.constrain((e.clientY-L)/I+C,0,O),S,I)});f.call(D)}e._context.edits.legendPosition&&(l.classed("cursor-move",!0),rr.init({element:l.node(),gd:e,prepFn:function(){var t=hn.getTranslate(l);A=t.x,T=t.y},moveFn:function(t,e){var r=A+t,n=T+e;hn.setTranslate(l,r,n),w=rr.align(r,0,m.l,m.l+m.w,i.xanchor),M=rr.align(n,0,m.t+m.h,m.t,i.yanchor)},doneFn:function(){void 0!==w&&void 0!==M&&R.call("relayout",e,{"legend.x":w,"legend.y":M})},clickFn:function(t,n){var i=r._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===t?l._clickTimeout=setTimeout(function(){Wo(i,e,t)},es):2===t&&(l._clickTimeout&&clearTimeout(l._clickTimeout),Wo(i,e,t)))}}))}function z(t,r,n){i._scrollY=e._fullLayout.legend._scrollY=t,hn.setTranslate(h,0,-t),hn.setRect(f,x,Go.scrollBarMargin+t*n,Go.scrollBarWidth,r),u.select("rect").attr({y:i.borderwidth+t})}},style:Ko},ss={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},ls=m.extendFlat,us={visible:{valType:"boolean",editType:"plot"},buttons:ss=ls(ss,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:k({editType:"plot"}),bgcolor:{valType:"color",dflt:C.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:C.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},cs={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var hs=function(e,r){var n=e._name,i={};if("all"===r.step)i[n+".autorange"]=!0;else{var a=function(e,r){var n,i=e.range,a=new Date(e.r2l(i[1])),o=r.step,s=r.count;switch(r.stepmode){case"backward":n=e.l2r(+t.time[o].utc.offset(a,-s));break;case"todate":var l=t.time[o].utc.offset(a,-s);n=e.l2r(+t.time[o].utc.ceil(l))}var u=i[1];return[n,u]}(e,r);i[n+".range[0]"]=a[0],i[n+".range[1]"]=a[1]}return i};var fs=Nr.LINE_SPACING,ds=Nr.FROM_TL,ps=Nr.FROM_BR;function gs(t){return t._id}function vs(t,e,r){var n=re.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:cs.rx,ry:cs.ry}),n.call(Ne.stroke,e.bordercolor).call(Ne.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function ms(t,e,r,n){var i;re.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(hn.font,e.font).text((i=r,i.label?i.label:"all"===i.step?"all":i.count+i.step.charAt(0))).call(function(t){Fr.convertToTspans(t,n)})}var ys={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:us}}},layoutAttributes:us,handleDefaults:function(t,e,r,n,i){var a=t.rangeselector||{},o=e.rangeselector={};function s(t,e){return re.coerce(a,o,us,t,e)}if(s("visible",function(t,e,r){var n,i,a=t.buttons||[],o=e.buttons=[];function s(t,e){return re.coerce(n,i,ss,t,e)}for(var l=0;l0)){var l=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;a0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,l=i.end,u=a.start,c=a.end;r&&r.checkIntersection(i,a);var h=e.linesIntersect(o,l,u,c);if(!1===h){if(!e.pointsCollinear(o,l,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(l,u))return!1;var f=e.pointsSame(o,u),d=e.pointsSame(l,c);if(f&&d)return n;var p=!f&&e.pointBetween(o,u,c),g=!d&&e.pointBetween(l,u,c);if(f)return g?s(n,l):s(t,c),n;p&&(d||(g?s(n,l):s(t,c)),s(n,o))}else 0===h.alongA&&(-1===h.alongB?s(t,u):0===h.alongB?s(t,h.pt):1===h.alongB&&s(t,c)),0===h.alongB&&(-1===h.alongA?s(n,o):0===h.alongA?s(n,h.pt):1===h.alongA&&s(n,l));return!1}for(var c=[];!i.isEmpty();){var h=i.getHead();if(r&&r.vert(h.pt[0]),h.isStart){r&&r.segmentNew(h.seg,h.primary);var f=l(h),d=f.before?f.before.ev:null,p=f.after?f.after.ev:null;function g(){if(d){var t=u(h,d);if(t)return t}return!!p&&u(h,p)}r&&r.tempStatus(h.seg,!!d&&d.seg,!!p&&p.seg);var v,m,y=g();if(y)t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below)&&(y.seg.myFill.above=!y.seg.myFill.above):y.seg.otherFill=h.seg.myFill,r&&r.segmentUpdate(y.seg),h.other.remove(),h.remove();if(i.getHead()!==h){r&&r.rewind(h.seg);continue}t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below,h.seg.myFill.below=p?p.seg.myFill.above:n,h.seg.myFill.above=m?!h.seg.myFill.below:h.seg.myFill.below):null===h.seg.otherFill&&(v=p?h.primary===p.primary?p.seg.otherFill.above:p.seg.myFill.above:h.primary?a:n,h.seg.otherFill={above:v,below:v}),r&&r.status(h.seg,!!d&&d.seg,!!p&&p.seg),h.other.status=f.insert(Cs.node({ev:h}))}else{var b=h.status;if(null===b)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(b.prev)&&o.exists(b.next)&&u(b.prev.ev,b.next.ev),r&&r.statusRemove(b.ev.seg),b.remove(),!h.primary){var x=h.seg.myFill;h.seg.myFill=h.seg.otherFill,h.seg.otherFill=x}c.push(h.seg)}i.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,i,a,s=t[t.length-1],l=0;l=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-i>t&&(a-u)*(i-c)/(o-c)+u-n>t&&(s=!s),a=u,o=c}return s}};return e}();function zs(t,e,r){var n=Os.segments(t),i=Os.segments(e),a=r(Os.combine(n,i));return Os.polygon(a)}Os={buildLog:function(t){return!0===t?Ns=Es():!1===t&&(Ns=!1),!1!==Ns&&Ns.list},epsilon:function(t){return Ds.epsilon(t)},segments:function(t){var e=Ss(!0,Ds,Ns);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:Ss(!1,Ds,Ns).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:Is.union(t.combined,Ns),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:Is.intersect(t.combined,Ns),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:Is.difference(t.combined,Ns),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:Is.differenceRev(t.combined,Ns),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:Is.xor(t.combined,Ns),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:Ps(t.segments,Ds,Ns),inverted:t.inverted}},polygonFromGeoJSON:function(t){return Ls.toPolygon(Os,t)},polygonToGeoJSON:function(t){return Ls.fromPolygon(Os,Ds,t)},union:function(t,e){return zs(t,e,Os.selectUnion)},intersect:function(t,e){return zs(t,e,Os.selectIntersect)},difference:function(t,e){return zs(t,e,Os.selectDifference)},differenceRev:function(t,e){return zs(t,e,Os.selectDifferenceRev)},xor:function(t,e){return zs(t,e,Os.selectXor)}},"object"==typeof window&&(window.PolyBool=Os);var Fs,js=Os,Bs=Bt.dot,Us=r.BADNUM,Vs=Fs={};Vs.tester=function(t){if(Array.isArray(t[0][0]))return Vs.multitester(t);var e,r=t.slice(),n=r[0][0],i=n,a=r[0][1],o=a;for(r.push(r[0]),e=1;ei||l===Us||lo||e&&s(t))}:function(t,e){var s=t[0],l=t[1];if(s===Us||si||l===Us||lo)return!1;var u,c,h,f,d,p=r.length,g=r[0][0],v=r[0][1],m=0;for(u=1;uMath.max(c,g)||l>Math.max(h,v)))if(lu||Math.abs(Bs(a,h))>n)return!0;return!1};Vs.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var o=r.length,s=n;r.splice(i+1);for(var l=s+1;l1&&a(t.pop());return{addPt:a,raw:t,filtered:r}};var qs=Pn.makeEventData,Gs=hi.getFromId,Xs=yi,Ws=Oe.MINSELECT,Ys=Fs.filter,Zs=Fs.tester,Qs=Fs.multitester;function Ks(t){return t._id}function $s(t,e,r){var n,i,a,o;if(r){var s=r.points||[];for(n=0;n=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function yl(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function bl(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Ne.background,stroke:Ne.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function xl(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),_l(t,e,i,a)}function _l(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function wl(e){t.select(e).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Ml(t){cl&&t.data&&t._context.showTips&&(re.notifier(re._(t,"Double-click to zoom back out"),"long"),cl=!1)}function Al(t){return"lasso"===t||"select"===t}function Tl(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,ul)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function kl(t,e){if(Ve){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function El(t){var e=[];for(var r in t)e.push(t[r]);return e}var Ll={},Cl=function(e,r,n,i,a,o,l,u){var c,h,f,d,p,g,v,m,y,b,x,_,w,M,A,T,k,E=e._fullLayout._zoomlayer,L=l+u==="nsew",C=1===(l+u).length;function S(){if(c=r.xaxis,h=r.yaxis,y=c._length,b=h._length,v=c._offset,m=h._offset,(f={})[c._id]=c,(d={})[h._id]=h,l&&u)for(var t=r.overlays,n=0;nul||o>ul?(B="xy",a/y>o/b?(o=a*b/y,N>i?D.t=N-o:D.b=N+o):(a=o*y/b,I>n?D.l=I-a:D.r=I+a),V.attr("d",Tl(D))):s():!w||o10||r.scrollWidth-r.clientWidth>10)){clearTimeout(Y);var n=-t.deltaY;if(isFinite(n)||(n=t.wheelDelta/10),isFinite(n)){var i,a=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=Q.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(t.clientX-o.left)/o.width,c=(o.bottom-t.clientY)/o.height;if(T){for(u||(s=.5),i=0;i0;o&&(i="array");var s,l=r("categoryorder",i);"array"===l&&(s=r("categoryarray")),o||"array"!==l||(l=e.categoryorder="trace"),"trace"===l?e._initialCategories=[]:"array"===l?e._initialCategories=s.slice():(s=function(t,e){var r,n,i,a=e.dataAttr||t._id.charAt(0),o={};if(e.axData)r=e.axData;else for(r=[],n=0;np[1]-.01&&(r.domain=o),re.noneOrAll(t.domain,r.domain,o)}return n("layer"),r},Fl=hi.name2id,jl=function(t,e,r,n,i){i&&(e._name=i,e._id=Fl(i)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var i=function(t,e,r){for(var n=0;n0&&i["_"+r+"axes"][e])return i;if((i[r+"axis"]||r)===e){if(Ul(i,r))return i;if((i[r]||[]).length||i[r+"0"])return i}}}(e,r,n);if(!i)return;if("histogram"===i.type&&n==={v:"y",h:"x"}[i.orientation||"v"])return void(t.type="linear");var a,o=n+"calendar",s=i[o];if(Ul(i,n)){var l=Bl(i),u=[];for(a=0;a rect").call(hn.setTranslate,0,0).call(hn.setScale,1,1),t.plot.call(hn.setTranslate,e._offset,r._offset).call(hn.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(hn.setPointGroupScale,1,1),n.selectAll(".textpoint").call(hn.setTextPointsScale,1,1),n.call(hn.hideOutsideRangePoints,t)}function g(t,r){var n,i,o,s=h[t.xaxis._id],l=h[t.yaxis._id],u=[];if(s){i=(n=e._fullLayout[s.axisName])._r,o=s.to,u[0]=(i[0]*(1-r)+r*o[0]-i[0])/(i[1]-i[0])*t.xaxis._length;var c=i[1]-i[0],f=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[2]=t.xaxis._length*(1-r+r*f/c)}else u[0]=0,u[2]=t.xaxis._length;if(l){i=(n=e._fullLayout[l.axisName])._r,o=l.to,u[1]=(i[1]*(1-r)+r*o[1]-i[1])/(i[0]-i[1])*t.yaxis._length;var d=i[1]-i[0],p=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[3]=t.yaxis._length*(1-r+r*p/d)}else u[1]=0,u[3]=t.yaxis._length;!function(t,r){var n,i=[];for(i=[t._id,r._id],n=0;nn.duration?(function(){for(var t={},r=0;r0?u+o:o;return{ppad:o,ppadplus:s?h:f,ppadminus:s?f:h}}return{ppad:o}}function gu(t,e,r,n,i){var a="category"===t.type?t.r2c:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var o,s,l,u,c=1/0,h=-1/0,f=n.match(cu.segmentRE);for("date"===t.type&&(a=hu.decodeDate(a)),o=0;oh&&(h=u)));return h>=c?[c,h]:void 0}}var vu=function(t,e,r,n,i){function a(r,n){return re.coerce(t,e,uu,r,n)}if(n=n||{},!a("visible",!(i=i||{}).itemIsNotPlainObject))return e;a("layer"),a("opacity"),a("fillcolor"),a("line.color"),a("line.width"),a("line.dash");for(var o=a("type",t.path?"path":"rect"),s=a("xsizemode"),l=a("ysizemode"),u=["x","y"],c=0;c<2;c++){var h,f,d,p=u[c],g=p+"anchor",v="x"===p?s:l,m={_fullLayout:r},y=ea.coerceRef(t,e,m,p,"","paper");if("paper"!==y?(h=ea.getFromId(m,y),d=hu.rangeToShapePosition(h),f=hu.shapePositionToRange(h)):f=d=re.identity,"path"!==o){var b=p+"0",x=p+"1",_=t[b],w=t[x];t[b]=f(t[b],!0),t[x]=f(t[x],!0),"pixel"===v?(a(b,0),a(x,10)):(ea.coercePosition(e,m,a,y,b,.25),ea.coercePosition(e,m,a,y,x,.75)),e[b]=d(e[b]),e[x]=d(e[x]),t[b]=_,t[x]=w}if("pixel"===v){var M=t[g];t[g]=f(t[g],!0),ea.coercePosition(e,m,a,y,g,.25),e[g]=d(e[g]),t[g]=M}}return"path"===o?a("path"):re.noneOrAll(t,e,["x0","x1","y0","y1"]),e},mu={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var i=0;il?(m=o,_=R+".y0",T="y0",y=l,w=R+".y1",k="y1"):(m=l,_=R+".y1",T="y1",y=o,w=R+".y0",k="y0");i={},q(e),H.moveFn="move"===F?G:X},doneFn:function(){Nn(e),R.call("relayout",t,i)}};function q(t){var r=H.element.getBoundingClientRect(),n=r.right-r.left,i=r.bottom-r.top,a=t.clientX-r.left,o=t.clientY-r.top,s=n>j&&i>B&&!t.shiftKey?rr.getCursor(a/n,1-o/i):"move";Nn(e,s),F=s.split("-")[0]}function G(n,m){if("path"===r.type){var y=function(t){return t},b=y,x=y;U?i[g]=r.xanchor=D(u+n):(b=function(t){return D(I(t)+n)},P&&"date"===P.type&&(b=hu.encodeDate(b))),V?i[v]=r.yanchor=z(c+m):(x=function(t){return z(N(t)+m)},O&&"date"===O.type&&(x=hu.encodeDate(x))),r.path=xu(C,b,x),i[S]=r.path}else U?i[g]=r.xanchor=D(u+n):(i[h]=r.x0=D(a+n),i[d]=r.x1=D(s+n)),V?i[v]=r.yanchor=z(c+m):(i[f]=r.y0=z(o+m),i[p]=r.y1=z(l+m));e.attr("d",bu(t,r))}function X(n,a){if("path"===r.type){var o=function(t){return t},s=o,l=o;U?i[g]=r.xanchor=D(u+n):(s=function(t){return D(I(t)+n)},P&&"date"===P.type&&(s=hu.encodeDate(s))),V?i[v]=r.yanchor=z(c+a):(l=function(t){return z(N(t)+a)},O&&"date"===O.type&&(l=hu.encodeDate(l))),r.path=xu(C,s,l),i[S]=r.path}else{var h=~F.indexOf("n")?m+a:m,f=~F.indexOf("s")?y+a:y,d=~F.indexOf("w")?b+n:b,p=~F.indexOf("e")?x+n:x;~F.indexOf("n")&&V&&(h=m-a),~F.indexOf("s")&&V&&(f=y-a),(!V&&f-h>B||V&&h-f>B)&&(i[_]=r[T]=V?h:z(h),i[w]=r[k]=V?f:z(f)),p-d>j&&(i[M]=r[E]=U?d:D(d),i[A]=r[L]=U?p:D(p))}e.attr("d",bu(t,r))}rr.init(H),e.node().onmousemove=q}(t,o,n,e)}}function bu(t,e){var r,n,i,a,o,s,l,u,c=e.type,h=ea.getFromId(t,e.xref),f=ea.getFromId(t,e.yref),d=t._fullLayout._size;if(h?(r=hu.shapePositionToRange(h),n=function(t){return h._offset+h.r2p(r(t,!0))}):n=function(t){return d.l+d.w*t},f?(i=hu.shapePositionToRange(f),a=function(t){return f._offset+f.r2p(i(t,!0))}):a=function(t){return d.t+d.h*(1-t)},"path"===c)return h&&"date"===h.type&&(n=hu.decodeDate(n)),f&&"date"===f.type&&(a=hu.decodeDate(a)),function(t,e,r){var n=t.path,i=t.xsizemode,a=t.ysizemode,o=t.xanchor,s=t.yanchor;return n.replace(cu.segmentRE,function(t){var n=0,l=t.charAt(0),u=cu.paramIsX[l],c=cu.paramIsY[l],h=cu.numParams[l],f=t.substr(1).replace(cu.paramRE,function(t){return u[n]?t="pixel"===i?e(o)+Number(t):e(t):c[n]&&(t="pixel"===a?r(s)-Number(t):r(t)),++n>h&&(t="X"),t});return n>h&&(f=f.replace(/[\s,]*X.*/,""),re.log("Ignoring extra params in segment "+t)),l+f})}(e,n,a);if("pixel"===e.xsizemode){var p=n(e.xanchor);o=p+e.x0,s=p+e.x1}else o=n(e.x0),s=n(e.x1);if("pixel"===e.ysizemode){var g=a(e.yanchor);l=g-e.y0,u=g-e.y1}else l=a(e.y0),u=a(e.y1);if("line"===c)return"M"+o+","+l+"L"+s+","+u;if("rect"===c)return"M"+o+","+l+"H"+s+"V"+u+"H"+o+"Z";var v=(o+s)/2,m=(l+u)/2,y=Math.abs(v-o),b=Math.abs(m-l),x="A"+y+","+b,_=v+y+","+m;return"M"+_+x+" 0 1,1 "+(v+","+(m-b))+x+" 0 0,1 "+_+"Z"}function xu(t,e,r){return t.replace(cu.segmentRE,function(t){var n=0,i=t.charAt(0),a=cu.paramIsX[i],o=cu.paramIsY[i],s=cu.numParams[i];return i+t.substr(1).replace(cu.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var _u={moduleType:"component",name:"shapes",layoutAttributes:uu,supplyLayoutDefaults:function(t,e){so(t,e,{name:"shapes",handleItemDefaults:vu})},includeBasePlot:lo("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=re.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),re.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var Cu=Nr.LINE_SPACING,Su=Nr.FROM_TL,Pu=Nr.FROM_BR;function Ru(t){return t._index}function Ou(e,r){var n=hn.tester.selectAll("g."+wu.labelGroupClass).data(r.steps);n.enter().append("g").classed(wu.labelGroupClass,!0);var i=0,a=0;n.each(function(e){var n=Du(t.select(this),{step:e},r).node();if(n){var o=hn.bBox(n);a=Math.max(a,o.height),i=Math.max(i,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(wu.railWidth,wu.gripHeight);var s=e._fullLayout._size;o.lx=s.l+s.w*r.x,o.ly=s.t+s.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(s.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var l=(o.inputAreaLength-2*wu.stepInset)/(r.steps.length-1),u=i+wu.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/l)),o.labelHeight=a,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var c=hn.tester.append("g");n.each(function(t){var e=Iu(c,r,t.label),n=e.node()&&hn.bBox(e.node())||{width:0,height:0},i=Fr.lineCount(e);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,i)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+wu.tickOffset+r.ticklen+wu.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var h="left";qo.isRightAnchor(r)&&(o.lx-=o.outerLength,h="right"),qo.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,h="center");var f="top";qo.isBottomAnchor(r)&&(o.ly-=o.height,f="bottom"),qo.isMiddleAnchor(r)&&(o.ly-=o.height/2,f="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),bi.autoMargin(e,wu.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*Su[h],r:o.outerLength*Pu[h],b:o.height*Pu[f],t:o.height*Su[f]})}function Iu(t,e,r){if(e.currentvalue.visible){var n,i,a=e._dims;switch(e.currentvalue.xanchor){case"right":n=a.inputAreaLength-wu.currentValueInset-a.currentValueMaxWidth,i="left";break;case"center":n=.5*a.inputAreaLength,i="middle";break;default:n=wu.currentValueInset,i="left"}var o=re.ensureSingle(t,"text",wu.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1})}),s=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)s+=r;else s+=e.steps[e.active].label;e.currentvalue.suffix&&(s+=e.currentvalue.suffix),o.call(hn.font,e.currentvalue.font).text(s).call(Fr.convertToTspans,e._gd);var l=Fr.lineCount(o),u=(a.currentValueMaxLines+1-l)*e.currentvalue.font.size*Cu;return Fr.positionText(o,n,u),o}}function Nu(t,e,r){re.ensureSingle(t,"rect",wu.gripRectClass,function(n){n.call(Bu,e,t,r).style("pointer-events","all")}).attr({width:wu.gripWidth,height:wu.gripHeight,rx:wu.gripRadius,ry:wu.gripRadius}).call(Ne.stroke,r.bordercolor).call(Ne.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function Du(t,e,r){var n=re.ensureSingle(t,"text",wu.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return n.call(hn.font,r.font).text(e.step.label).call(Fr.convertToTspans,r._gd),n}function zu(e,r){var n=re.ensureSingle(e,"g",wu.labelsClass),i=r._dims,a=n.selectAll("g."+wu.labelGroupClass).data(i.labelSteps);a.enter().append("g").classed(wu.labelGroupClass,!0),a.exit().remove(),a.each(function(e){var n=t.select(this);n.call(Du,e,r),hn.setTranslate(n,Hu(r,e.fraction),wu.tickOffset+r.ticklen+r.font.size*Cu+wu.labelOffset+i.currentValueTotalHeight)})}function Fu(t,e,r,n,i){var a=Math.round(n*(r.steps.length-1));a!==r.active&&ju(t,e,r,a,!0,i)}function ju(t,e,r,n,i,a){var o=r.active;r._input.active=r.active=n;var s=r.steps[r.active];e.call(Vu,r,r.active/(r.steps.length-1),a),e.call(Iu,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:o}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=a):(e._nextMethod={step:s,doCallback:i,doTransition:a},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&bi.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function Bu(e,r,n){var i=n.node(),a=t.select(r);function o(){return n.data()[0]}e.on("mousedown",function(){var e=o();r.emit("plotly_sliderstart",{slider:e});var s=n.select("."+wu.gripRectClass);t.event.stopPropagation(),t.event.preventDefault(),s.call(Ne.fill,e.activebgcolor);var l=qu(e,t.mouse(i)[0]);Fu(r,n,e,l,!0),e._dragging=!0,a.on("mousemove",function(){var e=o(),a=qu(e,t.mouse(i)[0]);Fu(r,n,e,a,!1)}),a.on("mouseup",function(){var t=o();t._dragging=!1,s.call(Ne.fill,t.bgcolor),a.on("mouseup",null),a.on("mousemove",null),r.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function Uu(e,r){var n=e.selectAll("rect."+wu.tickRectClass).data(r.steps),i=r._dims;n.enter().append("rect").classed(wu.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(e,n){var a=n%i.labelStride==0,o=t.select(this);o.attr({height:a?r.ticklen:r.minorticklen}).call(Ne.fill,r.tickcolor),hn.setTranslate(o,Hu(r,n/(r.steps.length-1))-.5*r.tickwidth,(a?wu.tickOffset:wu.minorTickOffset)+i.currentValueTotalHeight)})}function Vu(t,e,r,n){var i=t.select("rect."+wu.gripRectClass),a=Hu(e,r);if(!e._invokingCommand){var o=i;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(a-.5*wu.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function Hu(t,e){var r=t._dims;return r.inputAreaStart+wu.stepInset+(r.inputAreaLength-2*wu.stepInset)*Math.min(1,Math.max(0,e))}function qu(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-wu.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*wu.stepInset-2*r.inputAreaStart)))}function Gu(t,e,r){var n=r._dims,i=re.ensureSingle(t,"rect",wu.railTouchRectClass,function(n){n.call(Bu,e,t,r).style("pointer-events","all")});i.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,wu.tickOffset+r.ticklen+n.labelHeight)}).call(Ne.fill,r.bgcolor).attr("opacity",0),hn.setTranslate(i,0,n.currentValueTotalHeight)}function Xu(t,e){var r=e._dims,n=r.inputAreaLength-2*wu.railInset,i=re.ensureSingle(t,"rect",wu.railRectClass);i.attr({width:n,height:wu.railWidth,rx:wu.railRadius,ry:wu.railRadius,"shape-rendering":"crispEdges"}).call(Ne.stroke,e.bordercolor).call(Ne.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),hn.setTranslate(i,wu.railInset,.5*(r.inputAreaWidth-wu.railWidth)+r.currentValueTotalHeight)}var Wu={moduleType:"component",name:wu.name,layoutAttributes:Tu,supplyLayoutDefaults:function(t,e){so(t,e,{name:ku,handleItemDefaults:Lu})},draw:function(e){var r=e._fullLayout,n=function(t,e){for(var r=t[wu.name],n=[],i=0;i0?[0]:[]);if(i.enter().append("g").classed(wu.containerClassName,!0).style("cursor","ew-resize"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(Iu,r).call(Xu,r).call(zu,r).call(Uu,r).call(Gu,t,r).call(Nu,t,r);var n=r._dims;hn.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(Vu,r,r.active/(r.steps.length-1),!1),e.call(Iu,r)}(e,t.select(this),r)}})}}},Yu=m.extendFlat,Zu=(0,gr.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Yu({},Mu,{}),font:k({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:C.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Qu={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Ku=Qu.name,$u=Zu.buttons;function Ju(t,e,r){function n(r,n){return re.coerce(t,e,Zu,r,n)}n("visible",function(t,e){var r,n,i=t.buttons||[],a=e.buttons=[];function o(t,e){return re.coerce(r,n,$u,t,e)}for(var s=0;s0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var tc=ec;function ec(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}ec.barWidth=2,ec.barLength=20,ec.barRadius=2,ec.barPad=1,ec.barColor="#808BA4",ec.prototype.enable=function(e,r,n){var i=this.gd._fullLayout,a=i.width,o=i.height;this.position=e;var s,l,u,c,h=this.position.l,f=this.position.w,d=this.position.t,p=this.position.h,g=this.position.direction,v="down"===g,m="left"===g,y="up"===g,b=f,x=p;v||m||"right"===g||y||(this.position.direction="down",v=!0),v||y?(l=(s=h)+b,v?(u=d,x=(c=Math.min(u+x,o))-u):x=(c=d+x)-(u=Math.max(c-x,0))):(c=(u=d)+x,m?b=(l=h+b)-(s=Math.max(l-b,0)):(s=h,b=(l=Math.min(s+b,a))-s)),this._box={l:s,t:u,w:b,h:x};var _=f>b,w=ec.barLength+2*ec.barPad,M=ec.barWidth+2*ec.barPad,A=h,T=d+p;T+M>o&&(T=o-M);var k=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);k.exit().on(".drag",null).remove(),k.enter().append("rect").classed("scrollbar-horizontal",!0).call(Ne.fill,ec.barColor),_?(this.hbar=k.attr({rx:ec.barRadius,ry:ec.barRadius,x:A,y:T,width:w,height:M}),this._hbarXMin=A+w/2,this._hbarTranslateMax=b-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var E=p>x,L=ec.barWidth+2*ec.barPad,C=ec.barLength+2*ec.barPad,S=h+f,P=d;S+L>a&&(S=a-L);var R=this.container.selectAll("rect.scrollbar-vertical").data(E?[0]:[]);R.exit().on(".drag",null).remove(),R.enter().append("rect").classed("scrollbar-vertical",!0).call(Ne.fill,ec.barColor),E?(this.vbar=R.attr({rx:ec.barRadius,ry:ec.barRadius,x:S,y:P,width:L,height:C}),this._vbarYMin=P+C/2,this._vbarTranslateMax=x-C):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var O=this.id,I=s-.5,N=E?l+L+.5:l+.5,D=u-.5,z=_?c+M+.5:c+.5,F=i._topdefs.selectAll("#"+O).data(_||E?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",O).append("rect"),_||E?(this._clipRect=F.select("rect").attr({x:Math.floor(I),y:Math.floor(D),width:Math.ceil(N)-Math.floor(I),height:Math.ceil(z)-Math.floor(D)}),this.container.call(hn.setClipUrl,O),this.bg.attr({x:h,y:d,width:f,height:p})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(hn.setClipUrl,null),delete this._clipRect),_||E){var j=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(j);var B=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault(),t.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(B),E&&this.vbar.on(".drag",null).call(B)}this.setTranslate(r,n)},ec.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(hn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},ec.prototype._onBoxDrag=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e-=t.event.dx),this.vbar&&(r-=t.event.dy),this.setTranslate(e,r)},ec.prototype._onBoxWheel=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e+=t.event.deltaY),this.vbar&&(r+=t.event.deltaY),this.setTranslate(e,r)},ec.prototype._onBarDrag=function(){var e=this.translateX,r=this.translateY;if(this.hbar){var n=e+this._hbarXMin,i=n+this._hbarTranslateMax;e=(re.constrain(t.event.x,n,i)-n)/(i-n)*(this.position.w-this._box.w)}if(this.vbar){var a=r+this._vbarYMin,o=a+this._vbarTranslateMax;r=(re.constrain(t.event.y,a,o)-a)/(o-a)*(this.position.h-this._box.h)}this.setTranslate(e,r)},ec.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=re.constrain(t||0,0,r),e=re.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(hn.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(hn.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var a=e/n;this.vbar.call(hn.setTranslate,t,e+a*this._vbarTranslateMax)}};var rc=Nr.LINE_SPACING;function nc(t){return t._index}function ic(t,e){return+t.attr(Qu.menuIndexAttrName)===e._index}function ac(t,e,r,n,i,a,o,s){e._input.active=e.active=o,"buttons"===e.type?sc(t,n,null,null,e):"dropdown"===e.type&&(i.attr(Qu.menuIndexAttrName,"-1"),oc(t,n,i,a,e),s||sc(t,n,i,a,e))}function oc(t,e,r,n,i){var a=re.ensureSingle(e,"g",Qu.headerClassName,function(t){t.style("pointer-events","all")}),o=i._dims,s=i.active,l=i.buttons[s]||Qu.blankHeaderOpts,u={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};a.call(lc,i,l,t).call(gc,i,u,c),re.ensureSingle(e,"text",Qu.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(hn.font,i.font).text(Qu.arrowSymbol[i.direction])}).attr({x:o.headerWidth-Qu.arrowOffsetX+i.pad.l,y:o.headerHeight/2+Qu.textOffsetY+i.pad.t}),a.on("click",function(){r.call(vc),r.attr(Qu.menuIndexAttrName,ic(r,i)?-1:String(i._index)),sc(t,e,r,n,i)}),a.on("mouseover",function(){a.call(fc)}),a.on("mouseout",function(){a.call(dc,i)}),hn.setTranslate(e,o.lx,o.ly)}function sc(e,r,n,i,a){n||(n=r).attr("pointer-events","all");var o=function(t){return-1==+t.attr(Qu.menuIndexAttrName)}(n)&&"buttons"!==a.type?[]:a.buttons,s="dropdown"===a.type?Qu.dropdownButtonClassName:Qu.buttonClassName,l=n.selectAll("g."+s).data(o),u=l.enter().append("g").classed(s,!0),c=l.exit();"dropdown"===a.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var h=0,f=0,d=a._dims,p=-1!==["up","down"].indexOf(a.direction);"dropdown"===a.type&&(p?f=d.headerHeight+Qu.gapButtonHeader:h=d.headerWidth+Qu.gapButtonHeader),"dropdown"===a.type&&"up"===a.direction&&(f=-Qu.gapButtonHeader+Qu.gapButton-d.openHeight),"dropdown"===a.type&&"left"===a.direction&&(h=-Qu.gapButtonHeader+Qu.gapButton-d.openWidth);var g={x:d.lx+h+a.pad.l,y:d.ly+f+a.pad.t,yPad:Qu.gapButton,xPad:Qu.gapButton,index:0},v={l:g.x+a.borderwidth,t:g.y+a.borderwidth};l.each(function(o,s){var u=t.select(this);u.call(lc,a,o,e).call(gc,a,g),u.on("click",function(){t.event.defaultPrevented||(ac(e,a,0,r,n,i,s),o.execute&&bi.executeAPICommand(e,o.method,o.args),e.emit("plotly_buttonclicked",{menu:a,button:o,active:a.active}))}),u.on("mouseover",function(){u.call(fc)}),u.on("mouseout",function(){u.call(dc,a),l.call(hc,a)})}),l.call(hc,a),p?(v.w=Math.max(d.openWidth,d.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(d.openHeight,d.headerHeight)),v.direction=a.direction,i&&(l.size()?function(t,e,r,n,i,a){var o,s,l,u=i.direction,c="up"===u||"down"===u,h=i._dims,f=i.active;if(c)for(s=0,l=0;l0?[0]:[]);if(i.enter().append("g").classed(Qu.containerClassName,!0).style("cursor","pointer"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nx.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&re.log("Clearing previous rejected promises from queue."),t._promises=[]},wc.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(bi.subplotsRegistry.cartesian||{}).attrRegex,i=(bi.subplotsRegistry.gl3d||{}).attrRegex,a=Object.keys(t);for(e=0;e3?(b.x=1.02,b.xanchor="left"):b.x<-2&&(b.x=-.02,b.xanchor="right"),b.y>3?(b.y=1.02,b.yanchor="bottom"):b.y<-2&&(b.y=-.02,b.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Ne.clean(t),t},wc.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),i=0;i0)return t.substr(0,e)}wc.hasParent=function(t,e){for(var r=Pc(e);r;){if(r in t)return!0;r=Pc(r)}return!1};var Rc=["x","y","z"];wc.clearAxisTypes=function(t,e,r){for(var n=0;n1&&_.warn("Full array edits are incompatible with other edits",i);var h=r[""][""];if(Dc(h))e.set(null);else{if(!Array.isArray(h))return _.warn("Unrecognized full array edit value",i,h),!0;e.set(h)}return!l&&(a(u,c),o(t),!0)}var f,d,p,g,v,m,y,b=Object.keys(r).map(Number).sort(Ic),x=e.get(),w=x||[],M=X(c,i).get(),T=[],k=-1,E=w.length;for(f=0;fw.length-(y?0:1))_.warn("index out of range",i,p);else if(void 0!==m)v.length>1&&_.warn("Insertion & removal are incompatible with edits to the same index.",i,p),Dc(m)?T.push(p):y?("add"===m&&(m={}),w.splice(p,0,m),M&&M.splice(p,0,{})):_.warn("Unrecognized full object edit value",i,p,m),-1===k&&(k=p);else for(d=0;d=0;f--)w.splice(T[f],1),M&&M.splice(T[f],1);if(w.length?x||e.set(w):e.set(null),l)return!1;if(a(u,c),s!==A){var L;if(-1===k)L=b;else{for(E=Math.max(w.length,E),L=[],f=0;f=k);f++)L.push(p);for(f=k;f1?(m=["toggleHover"],y=["resetViews"]):s?(v=["zoomInGeo","zoomOutGeo"],m=["hoverClosestGeo"],y=["resetGeo"]):o?(m=["hoverClosest3d"],y=["resetCameraDefault3d","resetCameraLastSave3d"]):h?(m=["toggleHover"],y=["resetViewMapbox"]):m=u?["hoverClosestGl2d"]:l?["hoverClosestPie"]:["toggleHover"],a&&(m=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!a&&!u||d||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==y[0]&&(y=["resetScale2d"])),o?b=["zoom3d","pan3d","orbitRotation","tableRotation"]:(a||u)&&!d||c?b=["zoom2d","pan2d"]:h||s?b=["pan2d"]:f&&(b=["zoom2d"]),function(t){for(var e=!1,r=0;rth*d)||m)for(r=0;rE&&ST&&(T=S);s/=(T-A)/(2*k),A=i.l2r(A),T=i.l2r(T),i.range=i._input.range=_=t[1]||i[1]<=t[0])&&a[0]e[0])return!0}return!1}(r,i,d)){var o=a.node(),s=e.bg=re.ensureSingle(a,"rect","bg");o.insertBefore(s.node(),o.childNodes[0])}else a.select("rect.bg").remove(),f.push(t),d.push([r,i])});var p=n._bgLayer.selectAll(".bg").data(f);return p.enter().append("rect").classed("bg",!0),p.exit().remove(),p.each(function(e){n._plots[e].bg=t.select(this)}),h.each(function(t){var e=n._plots[t],i=e.xaxis,u=e.yaxis;e.bg&&s&&e.bg.call(hn.setRect,i._offset-a,u._offset-a,i._length+2*a,u._length+2*a).call(Ne.fill,n.plot_bgcolor).style("stroke-width",0);var c,h,f=e.clipId="clip"+n._uid+t+"plot",d=re.ensureSingleById(n._clips,"clipPath",f,function(t){t.classed("plotclip",!0).append("rect")});for(e.clipRect=d.select("rect").attr({width:i._length,height:u._length}),hn.setTranslate(e.plot,i._offset,u._offset),e._hasClipOnAxisFalse?(c=null,h=f):(c=f,h=null),hn.setClipUrl(e.plot,c),r=0;r=0?u.angularAxis.domain:t.extent(b),A=Math.abs(b[1]-b[0]);_&&!x&&(A=0);var T=M.slice();w&&x&&(T[1]+=A);var k=u.angularAxis.ticksCount||4;k>8&&(k=k/(k/8)+k%8),u.angularAxis.ticksStep&&(k=(T[1]-T[0])/k);var E=u.angularAxis.ticksStep||(T[1]-T[0])/(k*(u.minorTicks+1));y&&(E=Math.max(Math.round(E),1)),T[2]||(T[2]=E);var L=t.range.apply(this,T);if(L=L.map(function(t,e){return parseFloat(t.toPrecision(12))}),i=t.scale.linear().domain(T.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),s.layout.angularAxis.domain=i.domain(),s.layout.angularAxis.endPadding=w?A:0,void 0===(e=t.select(this).select("svg.chart-root"))||e.empty()){var C=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),S=this.appendChild(this.ownerDocument.importNode(C.documentElement,!0));e=t.select(S)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var P,R=e.select(".chart-group"),O={fill:"none",stroke:u.tickColor},I={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){P=e.select(".legend-group").attr({transform:"translate("+[g,u.margin.top]+")"}).style({display:"block"});var N=c.map(function(t,e){var r=dh.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});dh.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:hh({},dh.Legend.defaultConfig().legendConfig,{container:P,elements:N,reverseOrder:u.legend.reverseOrder})})();var D=P.node().getBBox();g=Math.min(u.width-D.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,g=Math.max(10,g),m=[u.margin.left+g,u.margin.top+g],n.range([0,g]),s.layout.radialAxis.domain=n.domain(),P.attr("transform","translate("+[m[0]+g,m[1]-g]+")")}else P=e.select(".legend-group").style({display:"none"});e.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),R.attr("transform","translate("+m+")").style({cursor:"crosshair"});var z=[(u.width-(u.margin.left+u.margin.right+2*g+(D?D.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*g))/2];if(z[0]=Math.max(0,z[0]),z[1]=Math.max(0,z[1]),e.select(".outer-group").attr("transform","translate("+z+")"),u.title){var F=e.select("g.title-group text").style(I).text(u.title),j=F.node().getBBox();F.attr({x:m[0]-j.width/2,y:m[1]-g-20})}var B=e.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var U=B.selectAll("circle.grid-circle").data(n.ticks(5));U.enter().append("circle").attr({class:"grid-circle"}).style(O),U.attr("r",n),U.exit().remove()}B.select("circle.outside-circle").attr({r:g}).style(O);var V=e.select("circle.background-circle").attr({r:g}).style({fill:u.backgroundColor,stroke:u.stroke});function H(t,e){return i(t)%360+u.orientation}if(u.radialAxis.visible){var q=t.svg.axis().scale(n).ticks(5).tickSize(5);B.call(q).attr({transform:"rotate("+u.radialAxis.orientation+")"}),B.selectAll(".domain").style(O),B.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(I).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,I["font-size"]]+")":"translate("+[0,I["font-size"]]+")"}}),B.selectAll("g>line").style({stroke:"black"})}var G=e.select(".angular.axis-group").selectAll("g.angular-tick").data(L),X=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(t,e){return"rotate("+H(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),G.exit().remove(),X.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(O),X.selectAll(".minor").style({stroke:u.minorTickColor}),G.select("line.grid-line").attr({x1:u.tickLength?g-u.tickLength:0,x2:g}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),X.append("text").classed("axis-text",!0).style(I);var W=G.select("text.axis-text").attr({x:g+u.labelOffset,dy:fh+"em",transform:function(t,e){var r=H(t),n=g+u.labelOffset,i=u.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":y?y[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(I);u.angularAxis.rewriteTicks&&W.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var Y=t.max(R.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));P.attr({transform:"translate("+[g+Y,u.margin.top]+")"});var Z=e.select("g.geometry-group").selectAll("g").size()>0,Q=e.select("g.geometry-group").selectAll("g.geometry").data(c);if(Q.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),Q.exit().remove(),c[0]||Z){var K=[];c.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=i,r.container=Q.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=u.orientation,r.direction=u.direction,r.index=e,K.push({data:t,geometryConfig:r})});var $=[];t.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(K).forEach(function(t,e){"unstacked"===t.key?$=$.concat(t.values.map(function(t,e){return[t]})):$.push(t.values)}),$.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return hh(dh[r].defaultConfig(),t)});dh[r]().config(n)()})}var J,tt,et=e.select(".guides-group"),rt=e.select(".tooltips-group"),nt=dh.tooltipPanel().config({container:rt,fontSize:8})(),it=dh.tooltipPanel().config({container:rt,fontSize:8})(),at=dh.tooltipPanel().config({container:rt,hasTick:!0})();if(!x){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});R.on("mousemove.angular-guide",function(t,e){var r=dh.util.getMousePos(V).angle;ot.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;J=i.invert(n);var a=dh.util.convertToCartesian(g+12,r+180);nt.text(dh.util.round(J)).move([a[0]+m[0],a[1]+m[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var st=et.select("circle").style({stroke:"grey",fill:"none"});R.on("mousemove.radial-guide",function(t,e){var r=dh.util.getMousePos(V).radius;st.attr({r:r}).style({opacity:.5}),tt=n.invert(dh.util.getMousePos(V).radius);var i=dh.util.convertToCartesian(r,u.radialAxis.orientation);it.text(dh.util.round(tt)).move([i[0]+m[0],i[1]+m[1]])}).on("mouseout.radial-guide",function(t,e){st.style({opacity:0}),at.hide(),nt.hide(),it.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var i=t.select(this),a=this.style.fill,o="black",s=this.style.opacity||1;if(i.attr({"data-opacity":s}),a&&"none"!==a){i.attr({"data-fill":a}),o=t.hsl(a).darker().toString(),i.style({fill:o,opacity:1});var l={t:dh.util.round(r[0]),r:dh.util.round(r[1])};x&&(l.t=y[r[0]]);var u="t: "+l.t+", r: "+l.r,c=this.getBoundingClientRect(),h=e.node().getBoundingClientRect(),f=[c.left+c.width/2-z[0]-h.left,c.top+c.height/2-z[1]-h.top];at.config({color:o}).text(u),at.move(f)}else a=this.style.stroke||"black",i.attr({"data-stroke":a}),o=t.hsl(a).darker().toString(),i.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(e,r){if(0!=t.event.which)return!1;t.select(this).attr("data-fill")&&at.show()}).on("mouseout.tooltip",function(e,r){at.hide();var n=t.select(this),i=n.attr("data-fill");i?n.style({fill:i,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return a;var e=dh.util.cloneJson(t);return e.data.forEach(function(t,e){a.data[e]||(a.data[e]={}),hh(a.data[e],dh.Axis.defaultConfig().data[0]),hh(a.data[e],t)}),hh(a.layout,dh.Axis.defaultConfig().layout),hh(a.layout,e.layout),this},u.getLiveConfig=function(){return s},u.getinputConfig=function(){return o},u.radialScale=function(t){return n},u.angularScale=function(t){return i},u.svg=function(){return e},t.rebind(u,l,"on"),u},dh.Axis.defaultConfig=function(e,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:t.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},dh.util={},dh.DATAEXTENT="dataExtent",dh.AREA="AreaChart",dh.LINE="LinePlot",dh.DOT="DotPlot",dh.BAR="BarChart",dh.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},dh.util._extend=function(t,e){for(var r in t)e[r]=t[r]},dh.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},dh.util.dataFromEquation2=function(e,r){var n=r||6;return t.range(0,360+n,n).map(function(t,r){var n=t*Math.PI/180;return[t,e(n)]})},dh.util.dataFromEquation=function(e,r,n){var i=r||6,a=[],o=[];t.range(0,360+i,i).forEach(function(t,r){var n=t*Math.PI/180,i=e(n);a.push(t),o.push(i)});var s={t:a,r:o};return n&&(s.name=n),s},dh.util.ensureArray=function(e,r){if(void 0===e)return null;var n=[].concat(e);return t.range(r).map(function(t,e){return n[e]||n[0]})},dh.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=dh.util.ensureArray(t[e],r)}),t},dh.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},dh.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},dh.util.sumArrays=function(e,r){return t.zip(e,r).map(function(e,r){return t.sum(e)})},dh.util.arrayLast=function(t){return t[t.length-1]},dh.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},dh.util.flattenArray=function(t){for(var e=[];!dh.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},dh.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},dh.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},dh.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},dh.util.getMousePos=function(e){var r=t.mouse(e.node()),n=r[0],i=r[1],a={};return a.x=n,a.y=i,a.pos=r,a.angle=180*(Math.atan2(i,n)+Math.PI)/Math.PI,a.radius=Math.sqrt(n*n+i*i),a},dh.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i0)){var l=t.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:c(s),transform:function(t,e){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return p.fill(n,i,a)},"fill-opacity":0,stroke:function(t,e){return p.stroke(n,i,a)},"stroke-width":function(t,e){return p["stroke-width"](n,i,a)},"stroke-dasharray":function(t,e){return p["stroke-dasharray"](n,i,a)},opacity:function(t,e){return p.opacity(n,i,a)},display:function(t,e){return p.display(n,i,a)}})}};var h=r.angularScale.range(),f=Math.abs(h[1]-h[0])/o[0].length*Math.PI/180,d=t.svg.arc().startAngle(function(t){return-f/2}).endAngle(function(t){return f/2}).innerRadius(function(t){return r.radialScale(l+(t[2]||0))}).outerRadius(function(t){return r.radialScale(l+(t[2]||0))+r.radialScale(t[1])});u.arc=function(e,n,i){t.select(this).attr({class:"mark arc",d:d,transform:function(t,e){return"rotate("+(r.orientation+s(t[0])+90)+")"}})};var p={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,i){return n[e[i].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return void 0===e[n].data.visible||e[n].data.visible?"block":"none"}},g=t.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(p).each(u[r.geometryType]),v.exit().remove(),g.exit().remove()})}return i.config=function(t){return arguments.length?(t.forEach(function(t,r){e[r]||(e[r]={}),hh(e[r],dh.PolyChart.defaultConfig()),hh(e[r],t)}),this):e},i.getColorScale=function(){},t.rebind(i,r,"on"),i},dh.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:t.scale.category20()}}},dh.BarChart=function(){return dh.PolyChart()},dh.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},dh.AreaChart=function(){return dh.PolyChart()},dh.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},dh.DotPlot=function(){return dh.PolyChart()},dh.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},dh.LinePlot=function(){return dh.PolyChart()},dh.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},dh.Legend=function(){var e=dh.Legend.defaultConfig(),r=t.dispatch("hover");function n(){var r=e.legendConfig,i=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=hh({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=t.merge(i);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||void 0===r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=t.select(o));var s=a.map(function(t,e){return t.color}),l=r.fontSize,u=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,c=u?r.height:l*a.length,h=o.classed("legend-group",!0).selectAll("svg").data([0]),f=h.enter().append("svg").attr({width:300,height:c+l,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});f.append("g").classed("legend-axis",!0),f.append("g").classed("legend-marks",!0);var d=t.range(a.length),p=t.scale[u?"linear":"ordinal"]().domain(d).range(s),g=t.scale[u?"linear":"ordinal"]().domain(d)[u?"range":"rangePoints"]([0,c]);if(u){var v=h.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),h.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var m=h.select(".legend-marks").selectAll("path.legend-mark").data(a);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[l/2,g(e)+l/2]+")"},d:function(e,r){var n,i,a,o=e.symbol;return a=3*(i=l),"line"===(n=o)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=t.svg.symbolTypes.indexOf(n)?t.svg.symbol().type(n).size(a)():t.svg.symbol().type("square").size(a)()},fill:function(t,e){return p(e)}}),m.exit().remove()}var y=t.svg.axis().scale(g).orient("right"),b=h.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:l,l/2]+")"}).call(y);return b.selectAll(".domain").style({fill:"none",stroke:"none"}),b.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),b.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),n}return n.config=function(t){return arguments.length?(hh(e,t),this):e},t.rebind(n,r,"on"),n},dh.Legend.defaultConfig=function(t,e){return{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:!1}}},dh.tooltipPanel=function(){var e,r,n,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},a="tooltip-"+dh.tooltipPanel.uid++,o=10,s=function(){var t=(e=i.container.selectAll("g."+a).data([0])).enter().append("g").classed(a,!0).style({"pointer-events":"none",display:"none"});return n=t.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=t.append("text").attr({dx:i.padding+o,dy:.3*+i.fontSize}),s};return s.text=function(a){var l=t.hsl(i.color).l,u=l>=.5?"#aaa":"white",c=l>=.5?"black":"white",h=a||"";r.style({fill:c,"font-size":i.fontSize+"px"}).text(h);var f=i.padding,d=r.node().getBBox(),p={fill:i.color,stroke:u,"stroke-width":"2px"},g=d.width+2*f+o,v=d.height+2*f;return n.attr({d:"M"+[[o,-v/2],[o,-v/4],[i.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),e.attr({transform:"translate("+[o,-v/2+2*f]+")"}),e.style({display:"block"}),s},s.move=function(t){if(e)return e.attr({transform:"translate("+[t[0],t[1]]+")"}).style({display:"block"}),s},s.hide=function(){if(e)return e.style({display:"none"}),s},s.show=function(){if(e)return e.style({display:"block"}),s},s.config=function(t){return hh(i,t),s},s},dh.tooltipPanel.uid=1,dh.adapter={},dh.adapter.plotly=function(){var e={convert:function(e,r){var n={};if(e.data&&(n.data=e.data.map(function(t,e){var n=hh({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,e){dh.util.translator.apply(null,t.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&e.layout&&"stack"===e.layout.barmode)){var i=dh.util.duplicates(n.data.map(function(t,e){return t.geometry}));n.data.forEach(function(t,e){var r=i.indexOf(t.geometry);-1!=r&&(n.data[e].groupId=r)})}if(e.layout){var a=hh({},e.layout);if([[a,["plot_bgcolor"],["backgroundColor"]],[a,["showlegend"],["showLegend"]],[a,["radialaxis"],["radialAxis"]],[a,["angularaxis"],["angularAxis"]],[a.angularaxis,["showline"],["gridLinesVisible"]],[a.angularaxis,["showticklabels"],["labelsVisible"]],[a.angularaxis,["nticks"],["ticksCount"]],[a.angularaxis,["tickorientation"],["tickOrientation"]],[a.angularaxis,["ticksuffix"],["ticksSuffix"]],[a.angularaxis,["range"],["domain"]],[a.angularaxis,["endpadding"],["endPadding"]],[a.radialaxis,["showline"],["gridLinesVisible"]],[a.radialaxis,["tickorientation"],["tickOrientation"]],[a.radialaxis,["ticksuffix"],["ticksSuffix"]],[a.radialaxis,["range"],["domain"]],[a.angularAxis,["showline"],["gridLinesVisible"]],[a.angularAxis,["showticklabels"],["labelsVisible"]],[a.angularAxis,["nticks"],["ticksCount"]],[a.angularAxis,["tickorientation"],["tickOrientation"]],[a.angularAxis,["ticksuffix"],["ticksSuffix"]],[a.angularAxis,["range"],["domain"]],[a.angularAxis,["endpadding"],["endPadding"]],[a.radialAxis,["showline"],["gridLinesVisible"]],[a.radialAxis,["tickorientation"],["tickOrientation"]],[a.radialAxis,["ticksuffix"],["ticksSuffix"]],[a.radialAxis,["range"],["domain"]],[a.font,["outlinecolor"],["outlineColor"]],[a.legend,["traceorder"],["reverseOrder"]],[a,["labeloffset"],["labelOffset"]],[a,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,e){dh.util.translator.apply(null,t.concat(r))}),r?(void 0!==a.tickLength&&(a.angularaxis.ticklen=a.tickLength,delete a.tickLength),a.tickColor&&(a.angularaxis.tickcolor=a.tickColor,delete a.tickColor)):(a.angularAxis&&void 0!==a.angularAxis.ticklen&&(a.tickLength=a.angularAxis.ticklen),a.angularAxis&&void 0!==a.angularAxis.tickcolor&&(a.tickColor=a.angularAxis.tickcolor)),a.legend&&"boolean"!=typeof a.legend.reverseOrder&&(a.legend.reverseOrder="normal"!=a.legend.reverseOrder),a.legend&&"boolean"==typeof a.legend.traceorder&&(a.legend.traceorder=a.legend.traceorder?"reversed":"normal",delete a.legend.reverseOrder),a.margin&&void 0!==a.margin.t){var o=["t","r","b","l","pad"],s=["top","right","bottom","left","pad"],l={};t.entries(a.margin).forEach(function(t,e){l[s[o.indexOf(t.key)]]=t.value}),a.margin=l}r&&(delete a.needsEndSpacing,delete a.minorTickColor,delete a.minorTicks,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksStep,delete a.angularaxis.rewriteTicks,delete a.angularaxis.nticks,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksStep,delete a.radialaxis.rewriteTicks,delete a.radialaxis.nticks),n.layout=a}return n}};return e};var ph,gh=re.extendDeepAll,vh=ph={};vh.framework=function(e){var r,n,i,a,o,s=new function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?gh(r,n):n,i||(i=ch.Axis()),a=ch.adapter.plotly().convert(r),i.config(a).render(o),e.data=r.data,e.layout=r.layout,vh.fillLayout(e),r}return l.isPolar=!0,l.svg=function(){return i.svg()},l.getConfig=function(){return r},l.getLiveConfig=function(){return ch.adapter.plotly().convert(i.getLiveConfig(),!0)},l.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},l.setUndoPoint=function(){var t,e,i=this,a=ch.util.cloneJson(r);t=a,e=n,s.add({undo:function(){e&&i(e)},redo:function(){i(t)}}),n=ch.util.cloneJson(a)},l.undo=function(){s.undo()},l.redo=function(){s.redo()},l},vh.fillLayout=function(e){var r=t.select(e).selectAll(".plot-container"),n=r.selectAll(".svg-container"),i=e.framework&&e.framework.svg&&e.framework.svg(),a={width:800,height:600,paper_bgcolor:Ne.background,_container:r,_paperdiv:n,_paper:i};e._fullLayout=gh(a,e.layout)};var mh={};(mh=ch).manager=ph;var yh={},bh=Ll.initInteractions,xh=Oe.AX_NAME_PATTERN,_h=0;function wh(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){re.error(t)}}function Mh(t,e){wh(t,Ne.combine(e,"white"))}function Ah(t,e){t._context||(t._context=re.extendDeep({},x));var r,n,i,a=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function Eh(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),kh(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&kh(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function Lh(t,r,n,i,a){!function(t,e,r,n){var i=re.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!re.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var a in kh(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,r,n,i);for(var o=function(t,r,n,i){var a,o,s,l,u,c=re.isPlainObject(i),h=[];for(var f in Array.isArray(n)||(n=[n]),n=Th(n,t.data.length-1),r)for(var d=0;d0&&"string"!=typeof _.parts[M-1];)A--;var T=_.parts[A],k=_.parts[A-1]+"."+T,E=_.parts.slice(0,A).join("."),L=re.nestedProperty(t.layout,E).get(),C=re.nestedProperty(o,E).get(),S=_.get();if(void 0!==w){p[x]=w,g[x]="reverse"===T?w:Sh(S);var P=Jn.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var O in P.impliedEdits)v(re.relativeAttr(x,O),P.impliedEdits[O]);if(-1!==["width","height"].indexOf(x)&&null===w)o[x]=t._initialAutoSize[x];else if(k.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))b(k),re.nestedProperty(o,E+"._inputRange").set(null);else if(k.match(/^[xyz]axis[0-9]*\.autorange$/)){b(k),re.nestedProperty(o,E+"._inputRange").set(null);var I=re.nestedProperty(o,E).get();I._inputDomain&&(I._input.domain=I._inputDomain.slice())}else k.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&re.nestedProperty(o,E+"._inputDomain").set(null);if("type"===T){var N=L,D="linear"===C.type&&"log"===w,z="log"===C.type&&"linear"===w;if(D||z){if(N&&N.range)if(C.autorange)D&&(N.range=N.range[1]>N.range[0]?[1,2]:[2,1]);else{var F=N.range[0],j=N.range[1];D?(F<=0&&j<=0&&v(E+".autorange",!0),F<=0?F=j/1e6:j<=0&&(j=F/1e6),v(E+".range[0]",Math.log(F)/Math.LN10),v(E+".range[1]",Math.log(j)/Math.LN10)):(v(E+".range[0]",Math.pow(10,F)),v(E+".range[1]",Math.pow(10,j)))}else v(E+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],R.getComponentMethod("annotations","convertCoords")(t,C,w,v),R.getComponentMethod("images","convertCoords")(t,C,w,v)}else v(E+".autorange",!0),v(E+".range",null);re.nestedProperty(o,E+"._inputRange").set(null)}else if(T.match(xh)){var B=re.nestedProperty(o,x).get(),U=(w||{}).type;U&&"-"!==U||(U="linear"),R.getComponentMethod("annotations","convertCoords")(t,B,U,v),R.getComponentMethod("images","convertCoords")(t,B,U,v)}var V=Oc.containerArrayMatch(x);if(V){r=V.array,n=V.index;var H=V.property,q=(re.nestedProperty(a,r)||[])[n]||{},G=q,X=P||{editType:"calc"},W=-1!==X.editType.indexOf("calcIfAutorange");""===n?(W?d.calc=!0:gr.update(d,X),W=!1):""===H&&(G=w,Oc.isAddVal(w)?g[x]=null:Oc.isRemoveVal(w)?(g[x]=q,G=q):re.warn("unrecognized full object value",e)),W&&(Ih(t,G,"x")||Ih(t,G,"y"))?d.calc=!0:gr.update(d,X),u[r]||(u[r]={});var Y=u[r][n];Y||(Y=u[r][n]={}),Y[H]=w,delete e[x]}else"reverse"===T?(L.range?L.range.reverse():(v(E+".autorange",!0),L.range=[1,0]),C.autorange?d.calc=!0:d.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===x&&("lasso"===w||"select"===w)&&"lasso"!==S&&"select"!==S?d.plot=!0:P?gr.update(d,P):d.calc=!0,_.set(w))}}for(r in u){Oc.applyContainerArrayChanges(t,re.nestedProperty(a,r),u[r],d)||(d.plot=!0)}var Z=o._axisConstraintGroups||[];for(m in y)for(n=0;n=0&&r=0&&r=i.length?i[0]:i[t]:i}function s(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function l(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,bi.transition(t,e.frame.data,e.frame.layout,wc.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function h(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var f,d,p=0;function g(t){return Array.isArray(i)?p>=i.length?t.transitionOpts=i[p]:t.transitionOpts=i[0]:t.transitionOpts=i,p++,t}var v=[],m=void 0===e||null===e,y=Array.isArray(e);if(!m&&!y&&re.isPlainObject(e))v.push({type:"object",data:g(re.extendFlat({},e))});else if(m||-1!==["string","number"].indexOf(typeof e))for(f=0;f0&&__)&&w.push(d);v=w}}v.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(re.isPlainObject(e[n])){var f=e[n].name,d=(l[f]||h[f]||{}).name,p=e[n].name,g=l[d]||h[d];d&&p&&"number"==typeof p&&g&&_h<5&&(_h++,re.warn('addFrames: overwriting frame "'+(l[d]||h[d]).name+'" with a frame whose name of type "number" also equates to "'+d+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===_h&&re.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),h[f]={name:f},c.push({frame:bi.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=c[n].frame).name&&re.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;l[i.name="frame "+t._transitionData._counter++];);if(l[i.name]){for(a=0;a=0;r--)n=e[r],a.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:i[n]});var s=bi.modifyFrames,l=bi.modifyFrames,u=[t,o],c=[t,a];return xc&&xc.add(t,s,u,l,c),bi.modifyFrames(t,a)},yh.purge=function(t){var e=(t=re.getGraphDiv(t))._fullLayout||{},r=t._fullData||[],n=t.calcdata||[];return bi.cleanPlot([],{},r,e,n),bi.purge(t),tr.purge(t),e._container&&e._container.remove(),delete t._context,t};var zh={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},Fh=Ye.EventEmitter;var jh=function(t){var e=t.emitter||new Fh,r=new Promise(function(n,i){var a=window.Image,o=t.svg,s=t.format||"png";if(re.isIE()&&"svg"!==s){var l=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(l),t.promise?r:e.emit("error",l)}var u=t.canvas,c=t.scale||1,h=c*(t.width||300),f=c*(t.height||150),d=u.getContext("2d"),p=new a,g="data:image/svg+xml,"+encodeURIComponent(o);u.width=h,u.height=f,p.onload=function(){var r;switch("svg"!==s&&d.drawImage(p,0,0,h,f),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=g;break;default:var a="Image format is not jpeg, png, svg or webp.";if(i(new Error(a)),!t.promise)return e.emit("error",a)}n(r),t.promise||e.emit("success",r)},p.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},p.src=g});return t.promise?r:e},Bh=/"/g,Uh=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var Vh=function(e,r,n){var i,a=e._fullLayout,o=a._paper,s=a._toppaper,l=a.width,u=a.height;o.insert("rect",":first-child").call(hn.setRect,0,0,l,u).call(Ne.fill,a.paper_bgcolor);var c=a._basePlotModules||[];for(i=0;i")?"":r.html(t).text()});return r.remove(),n}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(Uh,"'"),re.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},Hh={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},qh=/^data:image\/\w+;base64,/;var Gh=function(t,e){var r,n,i;function a(t){return!(t in e)||re.validate(e[t],Hh[t])}if(e=e||{},re.isPlainObject(t)?(r=t.data||[],n=t.layout||{},i=t.config||{}):(t=re.getGraphDiv(t),r=re.extendDeep([],t.data),n=re.extendDeep({},t.layout),i=t._context),!a("width")||!a("height"))throw new Error("Height and width should be pixel values.");if(!a("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function s(t,r){return re.coerce(e,o,Hh,t,r)}var l=s("format"),u=s("width"),c=s("height"),h=s("scale"),f=s("setBackground"),d=s("imageDataOnly"),p=document.createElement("div");p.style.position="absolute",p.style.left="-5000px",document.body.appendChild(p);var g=re.extendFlat({},n);u&&(g.width=u),c&&(g.height=c);var v=re.extendFlat({},i,{staticPlot:!0,setBackground:f}),m=zh.getRedrawFunc(p);function y(){return new Promise(function(t){setTimeout(t,zh.getDelay(p._fullLayout))})}function b(){return new Promise(function(t,e){var r=Vh(p,l,h),n=p._fullLayout.width,i=p._fullLayout.height;if(yh.purge(p),document.body.removeChild(p),"svg"===l)return t(d?r:"data:image/svg+xml,"+encodeURIComponent(r));var a=document.createElement("canvas");a.id=re.randstr(),jh({format:l,width:n,height:i,scale:h,canvas:a,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){yh.plot(p,r,g,v).then(m).then(y).then(b).then(function(e){t(function(t){return d?t.replace(qh,""):t}(e))}).catch(function(t){e(t)})})},Xh=re.isPlainObject,Wh=Array.isArray,Yh=re.isArrayOrTypedArray;function Zh(t,e,r,n,i,a){a=a||[];for(var o=Object.keys(t),s=0;sh.length&&n.push($h("unused",i,u.concat(h.length)));var v,m,y,b,x,_=h.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===f.dimensions)for(m=0;m<_;m++)if(Wh(c[m])){c[m].length>h[m].length&&n.push($h("unused",i,u.concat(m,h[m].length)));var M=h[m].length;for(v=0;v<(w?Math.min(M,g[m].length):M);v++)y=w?g[m][v]:g,b=c[m][v],x=h[m][v],re.validate(b,y)?x!==b&&x!==+b&&n.push($h("dynamic",i,u.concat(m,v),b,x)):n.push($h("value",i,u.concat(m,v),b))}else n.push($h("array",i,u.concat(m),c[m]));else for(m=0;m<_;m++)y=w?g[m]:g,b=c[m],x=h[m],re.validate(b,y)?x!==b&&x!==+b&&n.push($h("dynamic",i,u.concat(m),b,x)):n.push($h("value",i,u.concat(m),b))}else if(f.items&&!d&&Wh(c)){var A,T,k=g[Object.keys(g)[0]],E=[];for(A=0;A1&&a.push($h("object","layout"))),bi.supplyDefaults(o);for(var s=o._fullData,l=r.length,u=0;u-1&&(s[u[r]].title="");for(r=0;r0?u>=v:u<=v));c++)u>y&&u0?u>=v:u<=v));c++)u>h[0]&&u1){var V=Math.pow(10,Math.floor(Math.log(U)/Math.LN10));j*=V*re.roundUp(U/V,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(z.tick0=0)}z.dtick=j}z.domain=[O+C,O+k-C],z.setScale();var H=re.ensureSingle(o._infolayer,"g",r,function(e){e.classed(Af.colorbar,!0).each(function(){var e=t.select(this);e.append("rect").classed(Af.cbbg,!0),e.append("g").classed(Af.cbfills,!0),e.append("g").classed(Af.cblines,!0),e.append("g").classed(Af.cbaxis,!0).classed(Af.crisp,!0),e.append("g").classed(Af.cbtitleunshift,!0).append("g").classed(Af.cbtitle,!0),e.append("rect").classed(Af.cboutline,!0),e.select(".cbtitle").datum(0)})});H.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var q=H.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");z._axislayer=H.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var X,W=l.l+(n.x+E)*l.w,Y=z.titlefont.size;X="top"===n.titleside?(1-(O+k-C))*l.h+l.t+3+.75*Y:(1-(O+C))*l.h+l.t-3-.25*Y,tt(z._id+"title",{attributes:{x:W,y:X,"text-anchor":"start"}})}var Z,Q,K,$=re.syncOrAsync([bi.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=H.select(".cbtitle"),i=r.select("text"),a=[-n.outlinewidth/2,n.outlinewidth/2],u=r.select(".h"+z._id+"title-math-group").node(),c=15.6;if(i.node()&&(c=parseInt(i.node().style.fontSize,10)*Mf),u?(G=hn.bBox(u).height)>c&&(a[1]-=(G-c)/2):i.node()&&!i.classed(Af.jsPlaceholder)&&(G=hn.bBox(i.node()).height),G){if(G+=5,"top"===n.titleside)z.domain[1]-=G/l.h,a[1]*=-1;else{z.domain[0]+=G/l.h;var v=Fr.lineCount(i);a[1]+=(1-v)*c}r.attr("transform","translate("+a+")"),z.setScale()}}H.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-z.domain[1]))+")"),z._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var m=H.select(".cbfills").selectAll("rect.cbfill").data(d);m.enter().append("rect").classed(Af.cbfill,!0).style("stroke","none"),m.exit().remove(),m.each(function(e,r){var n=[0===r?h[0]:(d[r]+d[r-1])/2,r===d.length-1?h[1]:(d[r]+d[r+1])/2].map(z.c2p).map(Math.round);r!==d.length-1&&(n[1]+=n[1]>n[0]?1:-1);var i=g(e).replace("e-",""),a=s(i).toHexString();t.select(this).attr({x:S,width:Math.max(M,2),y:t.min(n),height:Math.max(t.max(n)-t.min(n),2),fill:a})});var y=H.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?f:[]);return y.enter().append("path").classed(Af.cbline,!0),y.exit().remove(),y.each(function(e){t.select(this).attr("d","M"+S+","+(Math.round(z.c2p(e))+n.line.width/2%1)+"h"+M).call(hn.lineGroupStyle,n.line.width,p(e),n.line.dash)}),z._axislayer.selectAll("g."+z._id+"tick,path").remove(),z._pos=S+M+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),z.side="right",re.syncOrAsync([function(){return ea.doTicks(e,z,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=z.titlefont.size,i=z._offset+z._length/2,a=l.l+(z.position||0)*l.w+("right"===z.side?10+r*(z.showticklabels?1:.5):-10-r*(z.showticklabels?.5:0));tt("h"+z._id+"title",{avoid:{selection:t.select(e).selectAll("g."+z._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:a,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},bi.previousPromises,function(){var t=M+n.outlinewidth/2+hn.bBox(z._axislayer.node()).width;if((x=q.select("text")).node()&&!x.classed(Af.jsPlaceholder)){var i,a=q.select(".h"+z._id+"title-math-group").node();i=a&&-1!==["top","bottom"].indexOf(n.titleside)?hn.bBox(a).width:hn.bBox(q.node()).right-S-l.l,t=Math.max(t,i)}var o=2*n.xpad+t+n.borderwidth+n.outlinewidth/2,s=I-N;H.select(".cbbg").attr({x:S-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:N-L,width:Math.max(o,2),height:Math.max(s+2*L,2)}).call(Ne.fill,n.bgcolor).call(Ne.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),H.selectAll(".cboutline").attr({x:S,y:N+n.ypad+("top"===n.titleside?G:0),width:Math.max(M,2),height:Math.max(s-2*n.ypad-G,2)}).call(Ne.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var u=({center:.5,right:1}[n.xanchor]||0)*o;H.attr("transform","translate("+(l.l-u)+","+l.t+")"),bi.autoMargin(e,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],e);if($&&$.then&&(e._promises||[]).push($),e._context.edits.colorbarPosition)rr.init({element:H.node(),gd:e,prepFn:function(){Z=H.attr("transform"),Nn(H)},moveFn:function(t,e){H.attr("transform",Z+" translate("+t+","+e+")"),Q=rr.align(P+t/l.w,A,0,1,n.xanchor),K=rr.align(O-e/l.h,k,0,1,n.yanchor);var r=rr.getCursor(Q,K,n.xanchor,n.yanchor);Nn(H,r)},doneFn:function(){Nn(H),void 0!==Q&&void 0!==K&&R.call("restyle",e,{"colorbar.x":Q,"colorbar.y":K},a().index)}});return $}function J(t,e){return re.coerce(D,z,wr,t,e)}function tt(t,r){var n,i=a();n=R.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var s={propContainer:z,propName:n,traceIndex:i.index,placeholder:o._dfltTitle.colorbar,containerGroup:H.select(".cbtitle")},l="h"===t.charAt(0)?t.substr(1):"h"+t;H.selectAll("."+l+",."+l+"-math-group").remove(),Oi.draw(e,t,wf(s,r||{}))}o._infolayer.selectAll("g."+r).remove()}function a(){var t,n,i=r.substr(2);for(t=0;tU||t[1]H)return[Df(t[0],B,U),Df(t[1],V,H)]}function X(t,e){return t[0]===e[0]&&(t[0]===B||t[0]===U)||(t[1]===e[1]&&(t[1]===V||t[1]===H)||void 0)}function W(t,e,r){return function(n,i){var a=G(n),o=G(i),s=[];if(a&&o&&X(a,o))return s;a&&s.push(a),o&&s.push(o);var l=2*re.constrain((n[t]+i[t])/2,e,r)-((a||n)[t]+(o||i)[t]);l&&((a&&o?l>0==a[t]>o[t]?a:o:a||o)[t]+=l);return s}}function Y(t){var e=t[0],r=t[1],n=e===E[L-1][0],i=r===E[L-1][1];if(!n||!i)if(L>1){var a=e===E[L-2][0],o=r===E[L-2][1];n&&(e===B||e===U)&&a?o?L--:E[L-1]=t:i&&(r===V||r===H)&&o?a?L--:E[L-1]=t:E[L++]=t}else E[L++]=t}function Z(t){E[L-1][0]!==t[0]&&E[L-1][1]!==t[1]&&Y([I,N]),Y(t),D=null,I=N=0}function Q(t){if(R=t[0]U?U:0,O=t[1]H?H:0,R||O){if(L)if(D){var e=F(D,t);e.length>1&&(Z(e[0]),E[L++]=e[1])}else z=F(E[L-1],t)[0],E[L++]=z;else E[L++]=[R||t[0],O||t[1]];var r=E[L-1];R&&O&&(r[0]!==R||r[1]!==O)?(D&&(I!==R&&N!==O?Y(I&&N?(n=D,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?B:U,H]:[o>0?U:B,V]):[I||R,N||O]):I&&N&&Y([I,N])),Y([R,O])):I-R&&N-O&&Y([R||I,O||N]),D=t,I=R,N=O}else D&&Z(F(D,t)[0]),E[L++]=t;var n,i,a,o}for("linear"===M||"spline"===M?F=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var a=q[i],o=Nf(t[0],t[1],e[0],e[1],a[0],a[1],a[2],a[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&P(o,t)S(s))break;i=s,(p=c[0]*u[0]+c[1]*u[1])>f?(f=p,a=s,l=!1):p=t.length||!s)break;Q(s),n=s}}else Q(a)}D&&Y([I||D[0],N||D[1]]),T.push(E.slice(0,L))}return T},Ff=Fs.tester;function jf(e,r,n,i,a,o,s){var l,u;!function(e,r,n,i,a){var o=n.xaxis,s=n.yaxis,l=t.extent(re.simpleMap(o.range,o.r2c)),u=t.extent(re.simpleMap(s.range,s.r2c)),c=i[0].trace;if(!cn.hasMarkers(c))return;var h=c.marker.maxdisplayed;if(0===h)return;var f=i.filter(function(t){return t.x>=l[0]&&t.x<=l[1]&&t.y>=u[0]&&t.y<=u[1]}),d=Math.ceil(f.length/h),p=0;a.forEach(function(t,e){var n=t[0].trace;cn.hasMarkers(n)&&n.marker.maxdisplayed>0&&e0;function h(t){return c?t.transition():t}var f=n.xaxis,d=n.yaxis,p=i[0].trace,g=p.line,v=t.select(o);if(R.getComponentMethod("errorbars","plot")(v,n,s),!0===p.visible){var m,y;h(v).style("opacity",p.opacity);var b=p.fill.charAt(p.fill.length-1);"x"!==b&&"y"!==b&&(b=""),n.isRangePlot||(i[0].node3=v);var x="",_=[],w=p._prevtrace;w&&(x=w._prevRevpath||"",y=w._nextFill,_=w._polygons);var M,A,T,k,E,L,C,S,P,O="",I="",N=[],D=re.noop;if(m=p._ownFill,cn.hasLines(p)||"none"!==p.fill){for(y&&y.datum(i),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(T=hn.steps(g.shape),k=hn.steps(g.shape.split("").reverse().join(""))):T=k="spline"===g.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?hn.smoothclosed(t.slice(1),g.smoothing):hn.smoothopen(t,g.smoothing)}:function(t){return"M"+t.join("L")},E=function(t){return k(t.reverse())},N=zf(i,{xaxis:f,yaxis:d,connectGaps:p.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=p._polygons=new Array(N.length),u=0;u1){var n=t.select(this);if(n.datum(i),e)h(n.style("opacity",0).attr("d",M).call(hn.lineGroupStyle)).style("opacity",1);else{var a=h(n);a.attr("d",M),hn.singleLineStyle(i,a)}}}}}var z=v.selectAll(".js-line").data(N);h(z.exit()).style("opacity",0).remove(),z.each(D(!1)),z.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(hn.lineGroupStyle).each(D(!0)),hn.setClipUrl(z,n.layerClipId),N.length?(m?L&&S&&(b?("y"===b?L[1]=S[1]=d.c2p(0,!0):"x"===b&&(L[0]=S[0]=f.c2p(0,!0)),h(m).attr("d","M"+S+"L"+L+"L"+O.substr(1)).call(hn.singleFillStyle)):h(m).attr("d",O+"Z").call(hn.singleFillStyle)):y&&("tonext"===p.fill.substr(0,6)&&O&&x?("tonext"===p.fill?h(y).attr("d",O+"Z"+x+"Z").call(hn.singleFillStyle):h(y).attr("d",O+"L"+x.substr(1)+"Z").call(hn.singleFillStyle),p._polygons=p._polygons.concat(_)):(j(y),p._polygons=null)),p._prevRevpath=I,p._prevPolygons=P):(m?j(m):y&&j(y),p._polygons=p._prevRevpath=p._prevPolygons=null);var F=v.selectAll(".points");l=F.data([i]),F.each(q),l.enter().append("g").classed("points",!0).each(q),l.exit().remove(),l.each(function(e){var r=!1===e[0].trace.cliponaxis;hn.setClipUrl(t.select(this),r?null:n.layerClipId)})}function j(t){h(t).attr("d","M0,0Z")}function B(t){return t.filter(function(t){return t.vis})}function U(t){return t.id}function V(t){if(t.ids)return U}function H(){return!1}function q(r){var i,a=r[0].trace,o=t.select(this),s=cn.hasMarkers(a),l=cn.hasText(a),u=V(a),p=H,g=H;s&&(p=a.marker.maxdisplayed||a._needsCull?B:re.identity),l&&(g=a.marker.maxdisplayed||a._needsCull?B:re.identity);var v=(i=o.selectAll("path.point").data(p,u)).enter().append("path").classed("point",!0);c&&v.call(hn.pointStyle,a,e).call(hn.translatePoints,f,d).style("opacity",0).transition().style("opacity",1);var m=s&&hn.tryColorscale(a.marker,""),y=s&&hn.tryColorscale(a.marker,"line");i.order(),i.each(function(r){var i=t.select(this),o=h(i);hn.translatePoint(r,o,f,d)?(hn.singlePointStyle(r,o,a,m,y,e),n.layerClipId&&hn.hideOutsideRangePoint(r,o,f,d,a.xcalendar,a.ycalendar),a.customdata&&i.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),c?i.exit().transition().style("opacity",0).remove():i.exit().remove(),(i=o.selectAll("g").data(g,u)).enter().append("g").classed("textpoint",!0).append("text"),i.order(),i.each(function(e){var r=t.select(this),i=h(r.select("text"));hn.translatePoint(e,i,f,d)?n.layerClipId&&hn.hideOutsideRangePoint(e,r,f,d,a.xcalendar,a.ycalendar):r.remove()}),i.selectAll("text").call(hn.textPointStyle,a,e).each(function(e){var r=f.c2p(e.x),n=d.c2p(e.y);t.select(this).selectAll("tspan.line").each(function(){h(t.select(this)).attr({x:r,y:n})})}),i.exit().remove()}}function Bf(t,e,r){var n=t.selectAll("path.point"),i=t.selectAll("text");hn.pointStyle(n,e,r),hn.textPointStyle(i,e,r),hn.selectedPointStyle(n,e),hn.selectedTextStyle(i,e)}var Uf=function(e,r){var n=r?r[0].node3:t.select(e).selectAll("g.trace.scatter");n.style("opacity",function(t){return t[0].trace.opacity}),n.selectAll("g.points").each(function(r){Bf(t.select(this),r.trace||r[0].trace,e)}),n.selectAll("g.trace path.js-line").call(hn.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(hn.fillGroupStyle),R.getComponentMethod("errorbars","style")(n)},Vf={};Vf.hasLines=cn.hasLines,Vf.hasMarkers=cn.hasMarkers,Vf.hasText=cn.hasText,Vf.isBubble=cn.isBubble,Vf.attributes=Gn,Vf.supplyDefaults=function(t,e,r,n){function i(r,n){return re.coerce(t,e,Gn,r,n)}var a=function(t,e,r,n){var i,a=n("x"),o=n("y");if(R.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),a)o?i=Math.min(a.length,o.length):(i=a.length,n("y0"),n("dy"));else{if(!o)return 0;i=e.y.length,n("x0"),n("dx")}return e._length=i,i}(t,e,n,i),o=a=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}},Vf.calc=_f,Vf.arraysToCalcdata=pf,Vf.plot=function(e,r,n,i,a){var o,s,l,u,c=r.plot.select("g.scatterlayer"),h=!i,f=!!i&&i.duration>0;for((l=c.selectAll("g.trace").data(n,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),function(t,e,r){var n,i,a=null;for(i=0;is[e[0].trace.uid]?1:-1}),f?(a&&(u=a()),t.transition().duration(i.duration).ease(i.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(t,a){jf(e,a,r,t,n,this,i)})})):c.selectAll("g.trace").each(function(t,a){jf(e,a,r,t,n,this,i)});h&&l.exit().remove(),c.selectAll("path:not([d])").remove()},Vf.colorbar=kf,Vf.style=Uf,Vf.hoverPoints=function(t,e,r,n){var i=t.cd,a=i[0].trace,o=t.xa,s=t.ya,l=o.c2p(e),u=s.c2p(r),c=[l,u],h=a.hoveron||"",f=-1!==a.mode.indexOf("markers")?3:.5;if(-1!==h.indexOf("points")){var d=function(t){var e=Math.max(f,t.mrc||0),r=o.c2p(t.x)-l,n=s.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-f/e)},p=Qa.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-l);return nD!=(E=w[x][1])>=D&&(A=w[x-1][0],T=w[x][0],E-k&&(M=A+(T-A)*(D-k)/(E-k),P=Math.min(P,M),O=Math.max(O,M)));P=Math.max(P,0),O=Math.min(O,o._length);var z=Ne.defaultLine;return Ne.opacity(a.fillcolor)?z=a.fillcolor:Ne.opacity((a.line||{}).color)&&(z=a.line.color),re.extendFlat(t,{distance:t.maxHoverDistance,x0:P,x1:O,y0:D,y1:D,color:z}),delete t.index,a.text&&!Array.isArray(a.text)?t.text=String(a.text):t.text=a.name,[t]}}},Vf.selectPoints=function(t,e){var r,n,i,a,o=t.cd,s=t.xaxis,l=t.yaxis,u=[],c=o[0].trace;if(!cn.hasMarkers(c)&&!cn.hasText(c))return[];if(!1===e)for(r=0;r>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function ld(t,e,r,n){return new Function([sd("A","x"+t+"y",e,["y"],!1,n),sd("B","x"+t+"y",e,["y"],!0,n),sd("P","c(x,y)"+t+"0",e,["y","c"],!1,n),sd("Q","c(x,y)"+t+"0",e,["y","c"],!0,n),"function dispatchBsearch",r,"(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",r].join(""))()}var ud={ge:ld(">=",!1,"GE"),gt:ld(">",!1,"GT"),lt:ld("<",!0,"LT"),le:ld("<=",!0,"LE"),eq:ld("-",!0,"EQ",!0)},cd=function(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],u=e[7],c=e[8],h=e[9],f=e[10],d=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*u-a*o,_=n*l-i*s,w=n*u-a*s,M=i*u-a*l,A=c*g-h*p,T=c*v-f*p,k=c*m-d*p,E=h*v-f*g,L=h*m-d*g,C=f*m-d*v,S=y*C-b*L+x*E+_*k-w*T+M*A;if(!S)return null;return S=1/S,t[0]=(s*C-l*L+u*E)*S,t[1]=(i*L-n*C-a*E)*S,t[2]=(g*M-v*w+m*_)*S,t[3]=(f*w-h*M-d*_)*S,t[4]=(l*k-o*C-u*T)*S,t[5]=(r*C-i*k+a*T)*S,t[6]=(v*x-p*M-m*b)*S,t[7]=(c*M-f*x+d*b)*S,t[8]=(o*L-s*k+u*A)*S,t[9]=(n*k-r*L-a*A)*S,t[10]=(p*w-g*x+m*y)*S,t[11]=(h*x-c*w-d*y)*S,t[12]=(s*T-o*E-l*A)*S,t[13]=(r*E-n*T+i*A)*S,t[14]=(g*b-p*_-v*y)*S,t[15]=(c*_-h*b+f*y)*S,t};var hd=function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t};var fd=function(t,e,r,n){var i,a,o,s,l,u,c,h,f,d,p=e[0],g=e[1],v=e[2],m=n[0],y=n[1],b=n[2],x=r[0],_=r[1],w=r[2];if(Math.abs(p-x)<1e-6&&Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6)return hd(t);c=p-x,h=g-_,f=v-w,d=1/Math.sqrt(c*c+h*h+f*f),i=y*(f*=d)-b*(h*=d),a=b*(c*=d)-m*f,o=m*h-y*c,(d=Math.sqrt(i*i+a*a+o*o))?(i*=d=1/d,a*=d,o*=d):(i=0,a=0,o=0);s=h*o-f*a,l=f*i-c*o,u=c*a-h*i,(d=Math.sqrt(s*s+l*l+u*u))?(s*=d=1/d,l*=d,u*=d):(s=0,l=0,u=0);return t[0]=i,t[1]=s,t[2]=c,t[3]=0,t[4]=a,t[5]=l,t[6]=h,t[7]=0,t[8]=o,t[9]=u,t[10]=f,t[11]=0,t[12]=-(i*p+a*g+o*v),t[13]=-(s*p+l*g+u*v),t[14]=-(c*p+h*g+f*v),t[15]=1,t};var dd=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],u=e[8],c=e[9],h=e[10],f=e[11];e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[4]=a*i+u*n,t[5]=o*i+c*n,t[6]=s*i+h*n,t[7]=l*i+f*n,t[8]=u*i-a*n,t[9]=c*i-o*n,t[10]=h*i-s*n,t[11]=f*i-l*n,t};var pd=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[8],c=e[9],h=e[10],f=e[11];e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[0]=a*i-u*n,t[1]=o*i-c*n,t[2]=s*i-h*n,t[3]=l*i-f*n,t[8]=a*n+u*i,t[9]=o*n+c*i,t[10]=s*n+h*i,t[11]=l*n+f*i,t};var gd=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[4],c=e[5],h=e[6],f=e[7];e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t[0]=a*i+u*n,t[1]=o*i+c*n,t[2]=s*i+h*n,t[3]=l*i+f*n,t[4]=u*i-a*n,t[5]=c*i-o*n,t[6]=h*i-s*n,t[7]=f*i-l*n,t};var vd=function(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t};var md=function(t,e,r){var n,i,a,o,s,l,u,c,h,f,d,p,g=r[0],v=r[1],m=r[2];e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],d=e[10],p=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=f,t[10]=d,t[11]=p,t[12]=n*g+s*v+h*m+e[12],t[13]=i*g+l*v+f*m+e[13],t[14]=a*g+u*v+d*m+e[14],t[15]=o*g+c*v+p*m+e[15]);return t};var yd=function(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a);return t};var bd=function(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],h=t[10],f=t[11],d=t[12],p=t[13],g=t[14],v=t[15];return(e*o-r*a)*(h*v-f*g)-(e*s-n*a)*(c*v-f*p)+(e*l-i*a)*(c*g-h*p)+(r*s-n*o)*(u*v-f*d)-(r*l-i*o)*(u*g-h*d)+(n*l-i*s)*(u*p-c*d)};var xd=function(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t};var _d=function(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e};var wd=function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t};var Md=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t};var Ad=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t};var Td=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]};var kd={length:function(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)},normalize:yd,dot:Td,cross:Ad},Ed=wd(),Ld=wd(),Cd=[0,0,0,0],Sd=[[0,0,0],[0,0,0],[0,0,0]],Pd=[0,0,0],Rd=function(t,e,r,n,i,a){if(e||(e=[0,0,0]),r||(r=[0,0,0]),n||(n=[0,0,0]),i||(i=[0,0,0,1]),a||(a=[0,0,0,1]),!function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;i<16;i++)t[i]=e[i]*n;return!0}(Ed,t))return!1;if(_d(Ld,Ed),Ld[3]=0,Ld[7]=0,Ld[11]=0,Ld[15]=1,Math.abs(bd(Ld)<1e-8))return!1;var o,s,l,u,c,h,f,d=Ed[3],p=Ed[7],g=Ed[11],v=Ed[12],m=Ed[13],y=Ed[14],b=Ed[15];if(0!==d||0!==p||0!==g){if(Cd[0]=d,Cd[1]=p,Cd[2]=g,Cd[3]=b,!cd(Ld,Ld))return!1;Md(Ld,Ld),o=i,l=Ld,u=(s=Cd)[0],c=s[1],h=s[2],f=s[3],o[0]=l[0]*u+l[4]*c+l[8]*h+l[12]*f,o[1]=l[1]*u+l[5]*c+l[9]*h+l[13]*f,o[2]=l[2]*u+l[6]*c+l[10]*h+l[14]*f,o[3]=l[3]*u+l[7]*c+l[11]*h+l[15]*f}else i[0]=i[1]=i[2]=0,i[3]=1;if(e[0]=v,e[1]=m,e[2]=y,function(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}(Sd,Ed),r[0]=kd.length(Sd[0]),kd.normalize(Sd[0],Sd[0]),n[0]=kd.dot(Sd[0],Sd[1]),Od(Sd[1],Sd[1],Sd[0],1,-n[0]),r[1]=kd.length(Sd[1]),kd.normalize(Sd[1],Sd[1]),n[0]/=r[1],n[1]=kd.dot(Sd[0],Sd[2]),Od(Sd[2],Sd[2],Sd[0],1,-n[1]),n[2]=kd.dot(Sd[1],Sd[2]),Od(Sd[2],Sd[2],Sd[1],1,-n[2]),r[2]=kd.length(Sd[2]),kd.normalize(Sd[2],Sd[2]),n[1]/=r[2],n[2]/=r[2],kd.cross(Pd,Sd[1],Sd[2]),kd.dot(Sd[0],Pd)<0)for(var x=0;x<3;x++)r[x]*=-1,Sd[x][0]*=-1,Sd[x][1]*=-1,Sd[x][2]*=-1;return a[0]=.5*Math.sqrt(Math.max(1+Sd[0][0]-Sd[1][1]-Sd[2][2],0)),a[1]=.5*Math.sqrt(Math.max(1-Sd[0][0]+Sd[1][1]-Sd[2][2],0)),a[2]=.5*Math.sqrt(Math.max(1-Sd[0][0]-Sd[1][1]+Sd[2][2],0)),a[3]=.5*Math.sqrt(Math.max(1+Sd[0][0]+Sd[1][1]+Sd[2][2],0)),Sd[2][1]>Sd[1][2]&&(a[0]=-a[0]),Sd[0][2]>Sd[2][0]&&(a[1]=-a[1]),Sd[1][0]>Sd[0][1]&&(a[2]=-a[2]),!0};function Od(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var Id=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],d=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*h+w*g,t[1]=b*i+x*l+_*f+w*v,t[2]=b*a+x*u+_*d+w*m,t[3]=b*o+x*c+_*p+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*h+w*g,t[5]=b*i+x*l+_*f+w*v,t[6]=b*a+x*u+_*d+w*m,t[7]=b*o+x*c+_*p+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*h+w*g,t[9]=b*i+x*l+_*f+w*v,t[10]=b*a+x*u+_*d+w*m,t[11]=b*o+x*c+_*p+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*h+w*g,t[13]=b*i+x*l+_*f+w*v,t[14]=b*a+x*u+_*d+w*m,t[15]=b*o+x*c+_*p+w*y,t};var Nd={identity:hd,translate:md,multiply:Id,create:wd,scale:vd,fromRotationTranslation:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,h=n*l,f=n*u,d=i*l,p=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(d+g),t[1]=h+y,t[2]=f-m,t[3]=0,t[4]=h-y,t[5]=1-(c+g),t[6]=p+v,t[7]=0,t[8]=f+m,t[9]=p-v,t[10]=1-(c+d),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}},Dd=(Nd.create(),Nd.create()),zd=function(t,e,r,n,i,a){return Nd.identity(t),Nd.fromRotationTranslation(t,a,e),t[3]=i[0],t[7]=i[1],t[11]=i[2],t[15]=i[3],Nd.identity(Dd),0!==n[2]&&(Dd[9]=n[2],Nd.multiply(t,t,Dd)),0!==n[1]&&(Dd[9]=0,Dd[8]=n[1],Nd.multiply(t,t,Dd)),0!==n[0]&&(Dd[8]=0,Dd[4]=n[0],Nd.multiply(t,t,Dd)),Nd.scale(t,t,r),t};var Fd=function(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],h=e[2],f=e[3],d=r[0],p=r[1],g=r[2],v=r[3];(a=u*d+c*p+h*g+f*v)<0&&(a=-a,d=-d,p=-p,g=-g,v=-v);1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n);return t[0]=s*u+l*d,t[1]=s*c+l*p,t[2]=s*h+l*g,t[3]=s*f+l*v,t},jd=Hd(),Bd=Hd(),Ud=Hd(),Vd=function(t,e,r,n){if(0===bd(e)||0===bd(r))return!1;var i=Rd(e,jd.translate,jd.scale,jd.skew,jd.perspective,jd.quaternion),a=Rd(r,Bd.translate,Bd.scale,Bd.skew,Bd.perspective,Bd.quaternion);return!(!i||!a||(xd(Ud.translate,jd.translate,Bd.translate,n),xd(Ud.skew,jd.skew,Bd.skew,n),xd(Ud.scale,jd.scale,Bd.scale,n),xd(Ud.perspective,jd.perspective,Bd.perspective,n),Fd(Ud.quaternion,jd.quaternion,Bd.quaternion,n),zd(t,Ud.translate,Ud.scale,Ud.skew,Ud.perspective,Ud.quaternion),0))};function Hd(){return{translate:qd(),scale:qd(1),skew:qd(),perspective:[0,0,0,1],quaternion:[0,0,0,1]}}function qd(t){return[t||0,t||0,t||0]}var Gd=[0,0,0],Xd=function(t){return new Wd((t=t||{}).matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])};function Wd(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-1/0,1/0]}var Yd=Wd.prototype;Yd.recalcMatrix=function(t){var e=this._time,r=ud.le(e,t),n=this.computedMatrix;if(!(r<0)){var i=this._components;if(r===e.length-1)for(var a=16*r,o=0;o<16;++o)n[o]=i[a++];else{var s=e[r+1]-e[r],l=(a=16*r,this.prevMatrix),u=!0;for(o=0;o<16;++o)l[o]=i[a++];var c=this.nextMatrix;for(o=0;o<16;++o)c[o]=i[a++],u=u&&l[o]===c[o];if(s<1e-6||u)for(o=0;o<16;++o)n[o]=l[o];else Vd(n,l,c,(t-e[r])/s)}var h=this.computedUp;h[0]=n[1],h[1]=n[5],h[2]=n[9],yd(h,h);var f=this.computedInverse;cd(f,n);var d=this.computedEye,p=f[15];d[0]=f[12]/p,d[1]=f[13]/p,d[2]=f[14]/p;var g=this.computedCenter,v=Math.exp(this.computedRadius[0]);for(o=0;o<3;++o)g[o]=d[o]-n[2+4*o]*v}},Yd.idle=function(t){if(!(t=0;--d)a[d]=u*t[d]+c*e[d]+h*r[d]+f*n[d];return a}return u*t+c*e+h*r+f*n}).derivative=function(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n};var Kd=function(t,e,r){switch(arguments.length){case 0:return new Jd([0],[0],0);case 1:if("number"==typeof t){var n=ep(t);return new Jd(n,n,0)}return new Jd(t,ep(t.length),0);case 2:if("number"==typeof e){var n=ep(t.length);return new Jd(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new Jd(t,e,r)}};function $d(t,e,r){return Math.min(e,Math.max(t,r))}function Jd(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n=r-1){u=a.length-1;var h=t-e[r-1];for(c=0;c=r-1)for(var l=a.length-1,u=(e[r-1],0);u=0;--r)if(t[--e])return!1;return!0},tp.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(t0;--c)n.push($d(s[c-1],l[c-1],arguments[c])),i.push(0)}},tp.push=function(t){var e=this.lastT(),r=this.dimension;if(!(t1e-6?1/o:0;this._time.push(t);for(var h=r;h>0;--h){var f=$d(l[h-1],u[h-1],arguments[h]);n.push(f),i.push((f-n[a++])*c)}}},tp.set=function(t){var e=this.dimension;if(!(t0;--s)r.push($d(a[s-1],o[s-1],arguments[s])),n.push(0)}},tp.move=function(t){var e=this.lastT(),r=this.dimension;if(!(t<=e||arguments.length!==r+1)){var n=this._state,i=this._velocity,a=n.length-this.dimension,o=this.bounds,s=o[0],l=o[1],u=t-e,c=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var f=arguments[h];n.push($d(s[h-1],l[h-1],n[a++]+f)),i.push(f*c)}}},tp.idle=function(t){var e=this.lastT();if(!(t=0;--c)n.push($d(s[c],l[c],n[a]+u*i[a])),i.push(0),a+=1}};var rp=function(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(h>0){var h=Math.sqrt(c+1);t[0]=.5*(o-l)/h,t[1]=.5*(s-n)/h,t[2]=.5*(r-a)/h,t[3]=.5*h}else{var f=Math.max(e,a,u),h=Math.sqrt(2*f-c+1);e>=f?(t[0]=.5*h,t[1]=.5*(i+r)/h,t[2]=.5*(s+n)/h,t[3]=.5*(o-l)/h):a>=f?(t[0]=.5*(r+i)/h,t[1]=.5*h,t[2]=.5*(l+o)/h,t[3]=.5*(s-n)/h):(t[0]=.5*(n+s)/h,t[1]=.5*(o+l)/h,t[2]=.5*h,t[3]=.5*(r-i)/h)}return t};var np=function(t){var e=(t=t||{}).center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),op(r=[].slice.call(r,0,4),r);var i=new sp(r,e,Math.log(n));i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up);return i};function ip(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function ap(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function op(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=ap(r,n,i,a);o>1e-6?(t[0]=r/o,t[1]=n/o,t[2]=i/o,t[3]=a/o):(t[0]=t[1]=t[2]=0,t[3]=1)}function sp(t,e,r){this.radius=Kd([r]),this.center=Kd(e),this.rotation=Kd(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}var lp=sp.prototype;lp.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},lp.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;op(e,e);var r=this.computedMatrix;_c(r,e);var n=this.computedCenter,i=this.computedEye,a=this.computedUp,o=Math.exp(this.computedRadius[0]);i[0]=n[0]+o*r[2],i[1]=n[1]+o*r[6],i[2]=n[2]+o*r[10],a[0]=r[1],a[1]=r[5],a[2]=r[9];for(var s=0;s<3;++s){for(var l=0,u=0;u<3;++u)l+=r[s+4*u]*i[u];r[12+s]=-l}},lp.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r},lp.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},lp.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},lp.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=i[1],o=i[5],s=i[9],l=ip(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,d=ip(u-=a*f,c-=o*f,h-=s*f);u/=d,c/=d,h/=d;var p=i[2],g=i[6],v=i[10],m=p*a+g*o+v*s,y=p*u+g*c+v*h,b=ip(p-=m*a+y*u,g-=m*o+y*c,v-=m*s+y*h);p/=b,g/=b,v/=b;var x=u*e+a*r,_=c*e+o*r,w=h*e+s*r;this.center.move(t,x,_,w);var M=Math.exp(this.computedRadius[0]);M=Math.max(1e-4,M+n),this.radius.set(t,Math.log(M))},lp.rotate=function(t,e,r,n){this.recalcMatrix(t),e=e||0,r=r||0;var i=this.computedMatrix,a=i[0],o=i[4],s=i[8],l=i[1],u=i[5],c=i[9],h=i[2],f=i[6],d=i[10],p=e*a+r*l,g=e*o+r*u,v=e*s+r*c,m=-(f*v-d*g),y=-(d*p-h*v),b=-(h*g-f*p),x=Math.sqrt(Math.max(0,1-Math.pow(m,2)-Math.pow(y,2)-Math.pow(b,2))),_=ap(m,y,b,x);_>1e-6?(m/=_,y/=_,b/=_,x/=_):(m=y=b=0,x=1);var w=this.computedRotation,M=w[0],A=w[1],T=w[2],k=w[3],E=M*x+k*m+A*b-T*y,L=A*x+k*y+T*m-M*b,C=T*x+k*b+M*y-A*m,S=k*x-M*m-A*y-T*b;if(n){m=h,y=f,b=d;var P=Math.sin(n)/ip(m,y,b);m*=P,y*=P,b*=P,S=S*(x=Math.cos(e))-(E=E*x+S*m+L*b-C*y)*m-(L=L*x+S*y+C*m-E*b)*y-(C=C*x+S*b+E*y-L*m)*b}var R=ap(E,L,C,S);R>1e-6?(E/=R,L/=R,C/=R,S/=R):(E=L=C=0,S=1),this.rotation.set(t,E,L,C,S)},lp.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;fd(i,e,r,n);var a=this.computedRotation;rp(a,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),op(a,a),this.rotation.set(t,a[0],a[1],a[2],a[3]);for(var o=0,s=0;s<3;++s)o+=Math.pow(r[s]-e[s],2);this.radius.set(t,.5*Math.log(Math.max(o,1e-6))),this.center.set(t,r[0],r[1],r[2])},lp.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},lp.setMatrix=function(t,e){var r=this.computedRotation;rp(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),op(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;cd(n,e);var i=n[15];if(Math.abs(i)>1e-6){var a=n[12]/i,o=n[13]/i,s=n[14]/i;this.recalcMatrix(t);var l=Math.exp(this.computedRadius[0]);this.center.set(t,a-n[2]*l,o-n[6]*l,s-n[10]*l),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},lp.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},lp.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},lp.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},lp.toJSON=function(){return this.recalcMatrix(this.lastT()),{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]}},lp.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)};var up=function(t,e,r,n){var i,a,o,s,l,u,c,h,f,d,p,g,v,m,y,b,x,_,w,M,A,T,k,E,L=n[0],C=n[1],S=n[2],P=Math.sqrt(L*L+C*C+S*S);if(Math.abs(P)<1e-6)return null;L*=P=1/P,C*=P,S*=P,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],h=e[4],f=e[5],d=e[6],p=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=C*L*o+S*i,_=S*L*o-C*i,w=L*C*o-S*i,M=C*C*o+a,A=S*C*o+L*i,T=L*S*o+C*i,k=C*S*o-L*i,E=S*S*o+a,t[0]=s*b+h*x+g*_,t[1]=l*b+f*x+v*_,t[2]=u*b+d*x+m*_,t[3]=c*b+p*x+y*_,t[4]=s*w+h*M+g*A,t[5]=l*w+f*M+v*A,t[6]=u*w+d*M+m*A,t[7]=c*w+p*M+y*A,t[8]=s*T+h*k+g*E,t[9]=l*T+f*k+v*E,t[10]=u*T+d*k+m*E,t[11]=c*T+p*k+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t};var cp=function(t){var e=(t=t||{}).center||[0,0,0],r=t.up||[0,1,0],n=t.right||dp(r),i=t.radius||1,a=t.theta||0,o=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),yd(r,r),n=[].slice.call(n,0,3),yd(n,n),"eye"in t){var s=t.eye,l=[s[0]-e[0],s[1]-e[1],s[2]-e[2]];Ad(n,l,r),hp(n[0],n[1],n[2])<1e-6?n=dp(r):yd(n,n),i=hp(l[0],l[1],l[2]);var u=Td(r,l)/i,c=Td(n,l)/i;o=Math.acos(u),a=Math.acos(c)}return i=Math.log(i),new pp(t.zoomMin,t.zoomMax,e,r,n,i,a,o)};function hp(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function fp(t){return Math.min(1,Math.max(-1,t))}function dp(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;s<3;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(s=0;s<3;++s)i[s]-=o/a*t[s];return yd(i,i),i}function pp(t,e,r,n,i,a,o,s){this.center=Kd(r),this.up=Kd(n),this.right=Kd(i),this.radius=Kd([a]),this.angle=Kd([o,s]),this.angle.bounds=[[-1/0,-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var l=0;l<16;++l)this.computedMatrix[l]=.5;this.recalcMatrix(0)}var gp=pp.prototype;gp.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},gp.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},gp.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,n=0,i=0,a=0;a<3;++a)i+=e[a]*r[a],n+=e[a]*e[a];var o=Math.sqrt(n),s=0;for(a=0;a<3;++a)r[a]-=e[a]*i/n,s+=r[a]*r[a],e[a]/=o;var l=Math.sqrt(s);for(a=0;a<3;++a)r[a]/=l;var u=this.computedToward;Ad(u,e,r),yd(u,u);var c=Math.exp(this.computedRadius[0]),h=this.computedAngle[0],f=this.computedAngle[1],d=Math.cos(h),p=Math.sin(h),g=Math.cos(f),v=Math.sin(f),m=this.computedCenter,y=d*g,b=p*g,x=v,_=-d*v,w=-p*v,M=g,A=this.computedEye,T=this.computedMatrix;for(a=0;a<3;++a){var k=y*r[a]+b*u[a]+x*e[a];T[4*a+1]=_*r[a]+w*u[a]+M*e[a],T[4*a+2]=k,T[4*a+3]=0}var E=T[1],L=T[5],C=T[9],S=T[2],P=T[6],R=T[10],O=L*R-C*P,I=C*S-E*R,N=E*P-L*S,D=hp(O,I,N);O/=D,I/=D,N/=D,T[0]=O,T[4]=I,T[8]=N;for(a=0;a<3;++a)A[a]=m[a]+T[2+4*a]*c;for(a=0;a<3;++a){s=0;for(var z=0;z<3;++z)s+=T[a+4*z]*A[z];T[12+a]=-s}T[15]=1},gp.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r};var vp=[0,0,0];gp.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;vp[0]=i[2],vp[1]=i[6],vp[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;l<3;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];up(i,i,n,vp);for(l=0;l<3;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},gp.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=(Math.exp(this.computedRadius[0]),i[1]),o=i[5],s=i[9],l=hp(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,d=hp(u-=a*f,c-=o*f,h-=s*f),p=(u/=d)*e+a*r,g=(c/=d)*e+o*r,v=(h/=d)*e+s*r;this.center.move(t,p,g,v);var m=Math.exp(this.computedRadius[0]);m=Math.max(1e-4,m+n),this.radius.set(t,Math.log(m))},gp.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},gp.setMatrix=function(t,e,r,n){var i=1;"number"==typeof r&&(i=0|r),(i<0||i>3)&&(i=1);var a=(i+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var o=e[i],s=e[i+4],l=e[i+8];if(n){var u=Math.abs(o),c=Math.abs(s),h=Math.abs(l),f=Math.max(u,c,h);u===f?(o=o<0?-1:1,s=l=0):h===f?(l=l<0?-1:1,o=s=0):(s=s<0?-1:1,o=l=0)}else{var d=hp(o,s,l);o/=d,s/=d,l/=d}var p,g,v=e[a],m=e[a+4],y=e[a+8],b=v*o+m*s+y*l,x=hp(v-=o*b,m-=s*b,y-=l*b),_=s*(y/=x)-l*(m/=x),w=l*(v/=x)-o*y,M=o*m-s*v,A=hp(_,w,M);if(_/=A,w/=A,M/=A,this.center.jump(t,U,V,H),this.radius.idle(t),this.up.jump(t,o,s,l),this.right.jump(t,v,m,y),2===i){var T=e[1],k=e[5],E=e[9],L=T*v+k*m+E*y,C=T*_+k*w+E*M;p=O<0?-Math.PI/2:Math.PI/2,g=Math.atan2(C,L)}else{var S=e[2],P=e[6],R=e[10],O=S*o+P*s+R*l,I=S*v+P*m+R*y,N=S*_+P*w+R*M;p=Math.asin(fp(O)),g=Math.atan2(N,I)}this.angle.jump(t,g,p),this.recalcMatrix(t);var D=e[2],z=e[6],F=e[10],j=this.computedMatrix;cd(j,e);var B=j[15],U=j[12]/B,V=j[13]/B,H=j[14]/B,q=Math.exp(this.computedRadius[0]);this.center.jump(t,U-D*q,V-z*q,H-F*q)},gp.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},gp.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},gp.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},gp.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},gp.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter;var i=(n=n||this.computedUp)[0],a=n[1],o=n[2],s=hp(i,a,o);if(!(s<1e-6)){i/=s,a/=s,o/=s;var l=e[0]-r[0],u=e[1]-r[1],c=e[2]-r[2],h=hp(l,u,c);if(!(h<1e-6)){l/=h,u/=h,c/=h;var f=this.computedRight,d=f[0],p=f[1],g=f[2],v=i*d+a*p+o*g,m=hp(d-=v*i,p-=v*a,g-=v*o);if(!(m<.01&&(m=hp(d=a*c-o*u,p=o*l-i*c,g=i*u-a*l))<1e-6)){d/=m,p/=m,g/=m,this.up.set(t,i,a,o),this.right.set(t,d,p,g),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(h));var y=a*g-o*p,b=o*d-i*g,x=i*p-a*d,_=hp(y,b,x),w=i*l+a*u+o*c,M=d*l+p*u+g*c,A=(y/=_)*l+(b/=_)*u+(x/=_)*c,T=Math.asin(fp(w)),k=Math.atan2(A,M),E=this.angle._state,L=E[E.length-1],C=E[E.length-2];L%=2*Math.PI;var S=Math.abs(L+2*Math.PI-k),P=Math.abs(L-k),R=Math.abs(L-2*Math.PI-k);S0)return 1<=0)return 1<Math.abs(e))n.rotate(s,0,0,-t*i*Math.PI*l.rotateSpeed/window.innerWidth);else{var u=l.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,a*(Math.exp(u)-1))}},!0),l};var Pp=function(t,e,r){return 0===t.length?t:e?(r||t.sort(e),function(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;o0,l=[],u=[],c=0,h=0;for(n=0;n0&&l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"0&&l.push(["index[",h,"]-=s",h].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function Op(t,e,r){for(var n=t.body,i=[],a=[],o=0;o0&&g.push("shape=SS.slice(0)"),t.indexArgs.length>0){var v=new Array(r);for(a=0;a0&&p.push("var "+g.join(",")),a=0;a3&&p.push(Op(t.pre,t,i));var x=Op(t.body,t,i),_=function(t){for(var e=0,r=t[0].length;e0,l=[],u=0;u0;){"].join("")),l.push(["if(j",u,"<",o,"){"].join("")),l.push(["s",e[u],"=j",u].join("")),l.push(["j",u,"=0"].join("")),l.push(["}else{s",e[u],"=",o].join("")),l.push(["j",u,"-=",o,"}"].join("")),s&&l.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&p.push(Op(t.post,t,i)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+p.join("\n")+"\n----------");var w=[t.funcName||"unnamed","_cwise_loop_",n[0].join("s"),"m",_,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(i)].join("");return new Function(["function ",w,"(",d.join(","),"){",p.join("\n"),"} return ",w].join(""))()};var Np=function(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var i=[],a=[],o=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],s=[],l=[],u=0;u0&&(s.push("array"+t.arrayArgs[0]+".shape.length===array"+c+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),l.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+c+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u0)throw new Error("cwise: pre() block may not reference array args");if(n0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===i)e.scalarArgs.push(n),e.shimArgs.push("scalar"+n);else if("index"===i){if(e.indexArgs.push(n),n0)throw new Error("cwise: pre() block may not reference array index");if(n0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===i){if(e.shapeArgs.push(n),nr.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,Np(e)},zp={},Fp={body:"",args:[],thisVars:[],localVars:[]};function jp(t){if(!t)return Fp;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in Up){var e=Up[t];zp[t]=Bp({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),zp[t+"eq"]=Bp({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),zp[t+"s"]=Bp({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),zp[t+"seq"]=Bp({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var Vp={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in Vp){var e=Vp[t];zp[t]=Bp({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),zp[t+"eq"]=Bp({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var Hp={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in Hp){var e=Hp[t];zp[t]=Bp({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),zp[t+"s"]=Bp({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),zp[t+"eq"]=Bp({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),zp[t+"seq"]=Bp({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var qp=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_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"}),zp.norm1=Dp({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,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"}),zp.sup=Dp({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:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),zp.inf=Dp({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:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),zp.random=Bp({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),zp.assign=Bp({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),zp.assigns=Bp({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),zp.equals=Dp({args:["array","array"],pre:Fp,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"});var Wp=function(t){for(var e=new Array(t),r=0;rMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&i.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):i.push("ORDER})")),i.push("proto.set=function "+r+"_set("+o.join(",")+",v){"),n?i.push("return this.data.set("+s+",v)}"):i.push("return this.data["+s+"]=v}"),i.push("proto.get=function "+r+"_get("+o.join(",")+"){"),n?i.push("return this.data.get("+s+")}"):i.push("return this.data["+s+"]}"),i.push("proto.index=function "+r+"_index(",o.join(),"){return "+s+"}"),i.push("proto.hi=function "+r+"_hi("+o.join(",")+"){return new "+r+"(this.data,"+a.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+a.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var c=a.map(function(t){return"a"+t+"=this.shape["+t+"]"}),h=a.map(function(t){return"c"+t+"=this.stride["+t+"]"});i.push("proto.lo=function "+r+"_lo("+o.join(",")+"){var b=this.offset,d=0,"+c.join(",")+","+h.join(","));for(var f=0;f=0){d=i"+f+"|0;b+=c"+f+"*d;a"+f+"-=d}");i.push("return new "+r+"(this.data,"+a.map(function(t){return"a"+t}).join(",")+","+a.map(function(t){return"c"+t}).join(",")+",b)}"),i.push("proto.step=function "+r+"_step("+o.join(",")+"){var "+a.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+a.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(f=0;f=0){c=(c+this.stride["+f+"]*i"+f+")|0}else{a.push(this.shape["+f+"]);b.push(this.stride["+f+"])}");return i.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),i.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+a.map(function(t){return"shape["+t+"]"}).join(",")+","+a.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",i.join("\n"))(tg[t],$p)}var tg={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};var eg=function(t,e,r,n){if(void 0===t)return(0,tg.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var i=e.length;if(void 0===r){r=new Array(i);for(var a=i-1,o=1;a>=0;--a)r[a]=o,o*=e[a]}if(void 0===n)for(n=0,a=0;a0)-(t<0)},rg.abs=function(t){var e=t>>31;return(t^e)-e},rg.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},rg.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},rg.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},rg.countTrailingZeros=ng,rg.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},rg.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},rg.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var ig=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|ig[t>>>16&255]<<8|ig[t>>>24&255]},rg.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},rg.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},rg.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},rg.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},rg.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>ng(t)+1};for(var ag={byteLength:function(t){return 3*t.length/4-fg(t)},toByteArray:function(t){var e,r,n,i,a,o=t.length;i=fg(t),a=new lg(3*o/4-i),r=i>0?o-4:o;var s=0;for(e=0;e>16&255,a[s++]=n>>8&255,a[s++]=255&n;2===i?(n=sg[t.charCodeAt(e)]<<2|sg[t.charCodeAt(e+1)]>>4,a[s++]=255&n):1===i&&(n=sg[t.charCodeAt(e)]<<10|sg[t.charCodeAt(e+1)]<<4|sg[t.charCodeAt(e+2)]>>2,a[s++]=n>>8&255,a[s++]=255&n);return a},fromByteArray:function(t){for(var e,r=t.length,n=r%3,i="",a=[],o=0,s=r-n;os?s:o+16383));1===n?(e=t[r-1],i+=og[e>>2],i+=og[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=og[e>>10],i+=og[e>>4&63],i+=og[e<<2&63],i+="=");return a.push(i),a.join("")}},og=[],sg=[],lg="undefined"!=typeof Uint8Array?Uint8Array:Array,ug="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",cg=0,hg=ug.length;cg0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function dg(t,e,r){for(var n,i,a=[],o=e;o>18&63]+og[i>>12&63]+og[i>>6&63]+og[63&i]);return a.join("")}sg["-".charCodeAt(0)]=62,sg["_".charCodeAt(0)]=63;var pg={read:function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,f=r?-1:1,d=t[e+h];for(h+=f,a=d&(1<<-c)-1,d>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,n),a-=u}return(d?-1:1)*o*Math.pow(2,a-n)},write:function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:a-1,p=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&s,d+=p,s/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*g}},gg={};gg.Buffer=yg,gg.SlowBuffer=function(t){+t!=t&&(t=0);return yg.alloc(+t)},gg.INSPECT_MAX_BYTES=50;var vg=2147483647;function mg(t){if(t>vg)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=yg.prototype,e}function yg(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return _g(t)}return bg(t,e,r)}function bg(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return Kg(t)||t&&Kg(t.buffer)?function(t,e,r){if(e<0||t.byteLength=vg)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+vg.toString(16)+" bytes");return 0|t}function Ag(t,e){if(yg.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Kg(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Yg(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Zg(t).length;default:if(n)return Yg(t).length;e=(""+e).toLowerCase(),n=!0}}function Tg(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function kg(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),$g(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=yg.from(e,n)),yg.isBuffer(e))return 0===e.length?-1:Eg(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Eg(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Eg(t,e,r,n,i){var a,o=1,s=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,s/=2,l/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var c=-1;for(a=r;as&&(r=s-l),a=r;a>=0;a--){for(var h=!0,f=0;fi&&(n=i):n=i;var a=e.length;n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(e,t.length-r),t,r,n)}function Ig(t,e,r){return 0===e&&r===t.length?ag.fromByteArray(t):ag.fromByteArray(t.slice(e,r))}function Ng(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(c=u);break;case 2:128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)>127&&(c=l);break;case 3:a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&(l=(15&u)<<12|(63&a)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(c=l)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=h}return function(t){var e=t.length;if(e<=Dg)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return jg(this,e,r);case"utf8":case"utf-8":return Ng(this,e,r);case"ascii":return zg(this,e,r);case"latin1":case"binary":return Fg(this,e,r);case"base64":return Ig(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Bg(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},yg.prototype.toLocaleString=yg.prototype.toString,yg.prototype.equals=function(t){if(!yg.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===yg.compare(this,t)},yg.prototype.inspect=function(){var t="",e=gg.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},yg.prototype.compare=function(t,e,r,n,i){if(!yg.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,o=r-e,s=Math.min(a,o),l=this.slice(n,i),u=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return Lg(this,t,e,r);case"utf8":case"utf-8":return Cg(this,t,e,r);case"ascii":return Sg(this,t,e,r);case"latin1":case"binary":return Pg(this,t,e,r);case"base64":return Rg(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Og(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},yg.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Dg=4096;function zg(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",a=e;ar)throw new RangeError("Trying to access beyond buffer length")}function Vg(t,e,r,n,i,a){if(!yg.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function Hg(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function qg(t,e,r,n,i){return e=+e,r>>>=0,i||Hg(t,0,r,4),pg.write(t,e,r,n,23,4),r+4}function Gg(t,e,r,n,i){return e=+e,r>>>=0,i||Hg(t,0,r,8),pg.write(t,e,r,n,52,8),r+8}yg.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||Ug(t,e,this.length);for(var n=this[t],i=1,a=0;++a>>=0,e>>>=0,r||Ug(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},yg.prototype.readUInt8=function(t,e){return t>>>=0,e||Ug(t,1,this.length),this[t]},yg.prototype.readUInt16LE=function(t,e){return t>>>=0,e||Ug(t,2,this.length),this[t]|this[t+1]<<8},yg.prototype.readUInt16BE=function(t,e){return t>>>=0,e||Ug(t,2,this.length),this[t]<<8|this[t+1]},yg.prototype.readUInt32LE=function(t,e){return t>>>=0,e||Ug(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},yg.prototype.readUInt32BE=function(t,e){return t>>>=0,e||Ug(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},yg.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||Ug(t,e,this.length);for(var n=this[t],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*e)),n},yg.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||Ug(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*e)),a},yg.prototype.readInt8=function(t,e){return t>>>=0,e||Ug(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},yg.prototype.readInt16LE=function(t,e){t>>>=0,e||Ug(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},yg.prototype.readInt16BE=function(t,e){t>>>=0,e||Ug(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},yg.prototype.readInt32LE=function(t,e){return t>>>=0,e||Ug(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},yg.prototype.readInt32BE=function(t,e){return t>>>=0,e||Ug(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},yg.prototype.readFloatLE=function(t,e){return t>>>=0,e||Ug(t,4,this.length),pg.read(this,t,!0,23,4)},yg.prototype.readFloatBE=function(t,e){return t>>>=0,e||Ug(t,4,this.length),pg.read(this,t,!1,23,4)},yg.prototype.readDoubleLE=function(t,e){return t>>>=0,e||Ug(t,8,this.length),pg.read(this,t,!0,52,8)},yg.prototype.readDoubleBE=function(t,e){return t>>>=0,e||Ug(t,8,this.length),pg.read(this,t,!1,52,8)},yg.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||Vg(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,n)||Vg(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},yg.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,1,255,0),this[e]=255&t,e+1},yg.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},yg.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},yg.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},yg.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},yg.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);Vg(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},yg.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);Vg(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},yg.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},yg.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},yg.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},yg.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},yg.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||Vg(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},yg.prototype.writeFloatLE=function(t,e,r){return qg(this,t,e,!0,r)},yg.prototype.writeFloatBE=function(t,e,r){return qg(this,t,e,!1,r)},yg.prototype.writeDoubleLE=function(t,e,r){return Gg(this,t,e,!0,r)},yg.prototype.writeDoubleBE=function(t,e,r){return Gg(this,t,e,!1,r)},yg.prototype.copy=function(t,e,r,n){if(!yg.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},yg.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!yg.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function Zg(t){return ag.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(Xg,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Qg(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Kg(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function $g(t){return t!=t}var Jg=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n0?r.pop():new ArrayBuffer(t)}function l(t){return new Uint8Array(s(t),0,t)}function u(t){return new Uint16Array(s(2*t),0,t)}function c(t){return new Uint32Array(s(4*t),0,t)}function h(t){return new Int8Array(s(t),0,t)}function f(t){return new Int16Array(s(2*t),0,t)}function d(t){return new Int32Array(s(4*t),0,t)}function p(t){return new Float32Array(s(4*t),0,t)}function g(t){return new Float64Array(s(8*t),0,t)}function v(t){return r?new Uint8ClampedArray(s(t),0,t):l(t)}function m(t){return new DataView(s(t),0,t)}function y(t){t=rg.nextPow2(t);var r=rg.log2(t),n=a[r];return n.length>0?n.pop():new e(t)}tv.free=function(t){if(e.isBuffer(t))a[rg.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var r=t.length||t.byteLength,n=0|rg.log2(r);i[n].push(t)}},tv.freeUint8=tv.freeUint16=tv.freeUint32=tv.freeInt8=tv.freeInt16=tv.freeInt32=tv.freeFloat32=tv.freeFloat=tv.freeFloat64=tv.freeDouble=tv.freeUint8Clamped=tv.freeDataView=function(t){o(t.buffer)},tv.freeArrayBuffer=o,tv.freeBuffer=function(t){a[rg.log2(t.length)].push(t)},tv.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return s(t);switch(e){case"uint8":return l(t);case"uint16":return u(t);case"uint32":return c(t);case"int8":return h(t);case"int16":return f(t);case"int32":return d(t);case"float":case"float32":return p(t);case"double":case"float64":return g(t);case"uint8_clamped":return v(t);case"buffer":return y(t);case"data":case"dataview":return m(t);default:return null}return null},tv.mallocArrayBuffer=s,tv.mallocUint8=l,tv.mallocUint16=u,tv.mallocUint32=c,tv.mallocInt8=h,tv.mallocInt16=f,tv.mallocInt32=d,tv.mallocFloat32=tv.mallocFloat=p,tv.mallocFloat64=tv.mallocDouble=g,tv.mallocUint8Clamped=v,tv.mallocDataView=m,tv.mallocBuffer=y,tv.clearCache=function(){for(var t=0;t<32;++t)n.UINT8[t].length=0,n.UINT16[t].length=0,n.UINT32[t].length=0,n.INT8[t].length=0,n.INT16[t].length=0,n.INT32[t].length=0,n.FLOAT[t].length=0,n.DOUBLE[t].length=0,n.UINT8C[t].length=0,i[t].length=0,a[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},gg.Buffer);var ev=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function rv(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}var nv=rv.prototype;function iv(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(a<0)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function av(t,e){for(var r=tv.malloc(t.length,e),n=t.length,i=0;i=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=iv(this.gl,this.type,this.length,this.usage,t.data,e):this.length=iv(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var n=tv.malloc(t.size,r),i=eg(n,t.shape);zp.assign(i,t),this.length=iv(this.gl,this.type,this.length,this.usage,e<0?n:n.subarray(0,t.size),e),tv.free(n)}}else if(Array.isArray(t)){var a;a=this.type===this.gl.ELEMENT_ARRAY_BUFFER?av(t,"uint16"):av(t,"float32"),this.length=iv(this.gl,this.type,this.length,this.usage,e<0?a:a.subarray(0,t.length),e),tv.free(a)}else if("object"==typeof t&&"number"==typeof t.length)this.length=iv(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}};var ov=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var i=new rv(t,r,t.createBuffer(),0,n);return i.update(e),i};var sv=function(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i=0?e[a]:i})},has___:{value:y(function(e){var n=m(e);return n?r in n:t.indexOf(e)>=0})},set___:{value:y(function(n,i){var a,o=m(n);return o?o[r]=i:(a=t.indexOf(n))>=0?e[a]=i:(a=t.length,e[a]=i,t[a]=n),this})},delete___:{value:y(function(n){var i,a,o=m(n);return o?r in o&&delete o[r]:!((i=t.indexOf(n))<0||(a=t.length-1,t[i]=void 0,e[i]=e[a],t[i]=t[a],t.length=a,e.length=a,0))})}})};p.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},delete:{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof e?function(){function r(){this instanceof p||b();var r,n=new e,i=void 0,a=!1;return r=t?function(t,e){return n.set(t,e),n.has(t)||(i||(i=new p),i.set(t,e)),this}:function(t,e){if(a)try{n.set(t,e)}catch(r){i||(i=new p),i.set___(t,e)}else n.set(t,e);return this},Object.create(p.prototype,{get___:{value:y(function(t,e){return i?n.has(t)?n.get(t):i.get___(t,e):n.get(t,e)})},has___:{value:y(function(t){return n.has(t)||!!i&&i.has___(t)})},set___:{value:y(r)},delete___:{value:y(function(t){var e=!!n.delete(t);return i&&i.delete___(t)||e})},permitHostObjects___:{value:y(function(t){if(t!==g)throw new Error("bogus call to permitHostObjects___");a=!0})}})}t&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=p.prototype,pv=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),pv=p)}function g(t){t.permitHostObjects___&&t.permitHostObjects___(g)}function v(t){return!(t.substr(0,s.length)==s&&"___"===t.substr(t.length-3))}function m(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[l];if(e&&e.key===t)return e;if(o(t)){e={key:t};try{return a(t,l,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(t){return}}}function y(t){return t.prototype=null,Object.freeze(t)}function b(){f||"undefined"==typeof console||(f=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}}();var gv=new("undefined"==typeof WeakMap?pv:WeakMap);var vv=function(t){var e=gv.get(t),r=e&&(e._triangleBuffer.handle||e._triangleBuffer.buffer);if(!r||!t.isBuffer(r)){var n=ov(t,new Float32Array([-1,-1,-1,4,4,-1]));(e=dv(t,[{buffer:n,type:t.FLOAT,size:2}]))._triangleBuffer=n,gv.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()};function mv(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}mv.prototype=new Error,mv.prototype.name="GLError",mv.prototype.constructor=mv;var yv=mv,bv=function(t,e,r,n){for(var i={},a=0,o=r.length;a=0){var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new yv("","Invalid data type for attribute "+l+": "+u);wv(t,e,c[0],n,h,i,l)}else{if(!(u.indexOf("mat")>=0))throw new yv("","Unknown data type for attribute "+l+": "+u);var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new yv("","Invalid data type for attribute "+l+": "+u);Mv(t,e,c,n,h,i,l)}}}return i};function xv(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}var _v=xv.prototype;function wv(t,e,r,n,i,a,o){for(var s=["gl","v"],l=[],u=0;u1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;u4)throw new yv("","Invalid uniform dimension type for matrix "+jo+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new yv("","Unknown uniform data type for "+jo+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(i<2||i>4)throw new yv("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new yv("","Unrecognized data type for vector "+jo+": "+r)}}}function a(e){for(var a=["return function updateProperty(obj){"],o=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var i in r){var a=r[i],o=e;parseInt(i)+""===i?o+="["+i+"]":o+="."+i,"object"==typeof a?n.push.apply(n,t(o,a)):n.push([o,a])}return n}("",e),s=0;s4)throw new yv("","Invalid data type");return"b"===t.charAt(0)?Ev(r,!1):Ev(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new yv("","Invalid uniform dimension type for matrix "+jo+": "+t);return Ev(r*r,0)}throw new yv("","Unknown uniform data type for "+jo+": "+t)}}(r[l].type);var c}function s(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1)for(var s=0;s=r)return Ov.substr(0,r);for(;r>Ov.length&&e>1;)1&e&&(Ov+=t),e>>=1,t+=t;return Ov=(Ov+=t).substr(0,r)};var Nv=function(t,e,r){return Iv(r=void 0!==r?r+"":" ",e)+t},Dv=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),i=String(n.length+e-1).length;return n.map(function(t,n){var a=n+e,o=String(a).length,s=Nv(a,i-o);return s+r+t}).join("\n")};var zv={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},Fv=function(t){return zv[t]},jv=function(t){return atob(t)},Bv=["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"],Uv=(Bv=Bv.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)})).concat(["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","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"]),Vv=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","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","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"],Hv=Vv.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),qv=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],Gv=function(t){var e,r,n,i=0,a=0,o=Xv,s=[],l=[],u=1,c=0,h=0,f=!1,d=!1,p="",g=Bv,v=Vv;"300 es"===(t=t||{}).version&&(g=Uv,v=Hv);return function(t){return l=[],null!==t?function(t){var r;i=0,n=(p+=t).length;for(;e=p[i],i0)continue;r=t.slice(0,1).join("")}return m(r),h+=r.length,(s=s.slice(r.length)).length}}function A(){return/[^a-fA-F0-9]/.test(e)?(m(s.join("")),o=Xv,i):(s.push(e),r=e,i+1)}function T(){return"."===e?(s.push(e),o=Jv,r=e,i+1):/[eE]/.test(e)?(s.push(e),o=Jv,r=e,i+1):"x"===e&&1===s.length&&"0"===s[0]?(o=am,s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=Xv,i):(s.push(e),r=e,i+1)}function k(){return"f"===e&&(s.push(e),r=e,i+=1),/[eE]/.test(e)?(s.push(e),r=e,i+1):"-"===e&&/[eE]/.test(r)?(s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=Xv,i):(s.push(e),r=e,i+1)}function E(){if(/[^\d\w_]/.test(e)){var t=s.join("");return o=v.indexOf(t)>-1?rm:g.indexOf(t)>-1?em:tm,m(s.join("")),o=Xv,i}return s.push(e),r=e,i+1}},Xv=999,Wv=9999,Yv=0,Zv=1,Qv=2,Kv=3,$v=4,Jv=5,tm=6,em=7,rm=8,nm=9,im=10,am=11,om=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];var sm=function(t,e){var r=Gv(e),n=[];return n=(n=n.concat(r(t))).concat(r(null))};var lm=function(t){for(var e=Array.isArray(t)?t:sm(t),r=0;r=0),s[8]){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,s[6]?parseInt(s[6]):0);break;case"e":i=s[7]?parseFloat(i).toExponential(s[7]):parseFloat(i).toExponential();break;case"f":i=s[7]?parseFloat(i).toFixed(s[7]):parseFloat(i);break;case"g":i=s[7]?String(Number(i.toPrecision(s[7]))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=s[7]?i.substring(0,s[7]):i;break;case"t":i=String(!!i),i=s[7]?i.substring(0,s[7]):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=s[7]?i.substring(0,s[7]):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=s[7]?i.substring(0,s[7]):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(s[8])?g+=i:(!t.number.test(s[8])||h&&!s[3]?f="":(f=h?"+":"-",i=i.toString().replace(t.sign,"")),u=s[4]?"0"===s[4]?"0":s[4].charAt(1):" ",c=s[6]-(f+i).length,l=s[6]&&c>0?u.repeat(c):"",g+=s[5]?f+i+l:"0"===u?f+l+i:l+f+i)}return g}(function(e){if(n[e])return n[e];var r,i=e,a=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))a.push(r[0]);else if(null!==(r=t.modulo.exec(i)))a.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var s=[],l=r[2],u=[];if(null===(u=t.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(l=l.substring(u[0].length));)if(null!==(u=t.key_access.exec(l)))s.push(u[1]);else{if(null===(u=t.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}r[2]=s}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a.push(r)}i=i.substring(r[0].length)}return n[e]=a}(r),arguments)}function r(t,r){return e.apply(null,[t].concat(r||[]))}var n=Object.create(null);void 0!==um&&(um.sprintf=e,um.vsprintf=r),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=r)}();var cm=um.sprintf,hm=function(t,e,r){"use strict";var n=lm(e)||"of unknown name (see npm glsl-shader-name)",i="unknown type";void 0!==r&&(i=r===Fv.FRAGMENT_SHADER?"fragment":"vertex");for(var a=cm("Error compiling %s shader %s:\n",i,n),o=cm("%s%s",a,t),s=t.split("\n"),l={},u=0;ur)for(t=r;te)for(t=e;t=0){for(var v=0|g.type.charAt(g.type.length-1),m=new Array(v),y=0;y=0;)b+=1;p[h]=b}var x=new Array(r.length);function _(){a.program=pm.program(o,a._vref,a._fref,d,p);for(var t=0;t 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]),Rm=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]);km.bg=function(t){return Am(t,Pm,Rm,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])};var Om=function(t){for(var e=[],r=[],n=0,i=0;i<3;++i)for(var a=(i+1)%3,o=(i+2)%3,s=[0,0,0],l=[0,0,0],u=-1;u<=1;u+=2){r.push(n,n+2,n+1,n+1,n+2,n+3),s[i]=u,l[i]=u;for(var c=-1;c<=1;c+=2){s[a]=c;for(var h=-1;h<=1;h+=2)s[o]=h,e.push(s[0],s[1],s[2],l[0],l[1],l[2]),n+=1}var f=a;a=o,o=f}var d=ov(t,new Float32Array(e)),p=ov(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),g=dv(t,[{buffer:d,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:d,type:t.FLOAT,size:3,offset:12,stride:24}],p),v=Im(t);return v.attributes.position.location=0,v.attributes.normal.location=1,new Nm(t,d,g,v)},Im=km.bg;function Nm(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}var Dm=Nm.prototype;Dm.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;s<3;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),this.vao.unbind(),l.disable(l.POLYGON_OFFSET_FILL)}},Dm.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()};var zm=function(t,e,r){var n=t*e,i=Fm*t,a=i-(i-t),o=t-a,s=Fm*e,l=s-(s-e),u=e-l,c=o*u-(n-a*l-o*l-a*u);if(r)return r[0]=c,r[1]=n,r;return[c,n]},Fm=+(Math.pow(2,27)+1);var jm=function(t,e,r){var n=t+e,i=n-t,a=e-i,o=t-(n-i);if(r)return r[0]=o+a,r[1]=n,r;return[o+a,n]};var Bm=function(t,e){var r=t.length;if(1===r){var n=zm(t[0],e);return n[0]?n:[n[1]]}var i=new Array(2*r),a=[.1,.1],o=[.1,.1],s=0;zm(t[0],e,a),a[0]&&(i[s++]=a[0]);for(var l=1;l=n?(i=h,(l+=1)=n?(i=h,(l+=1)>1;return["sum(",Xm(t.slice(0,e)),",",Xm(t.slice(e)),")"].join("")}function Wm(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(a<=0)return o;n=i+a}else{if(!(i<0))return o;if(a>=0)return o;n=-(i+a)}var s=3.3306690738754716e-16*n;return o>=s||o<=-s?o:Zm(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],h=e[2]-n[2],f=r[2]-n[2],d=a*u,p=o*l,g=o*s,v=i*u,m=i*l,y=a*s,b=c*(d-p)+h*(g-v)+f*(m-y),x=7.771561172376103e-16*((Math.abs(d)+Math.abs(p))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(h)+(Math.abs(m)+Math.abs(y))*Math.abs(f));return b>x||-b>x?b:Qm(t,e,r,n)}];!function(){for(;Km.length<=qm;)Km.push(Ym(Km.length));for(var t=[],e=["slow"],r=0;r<=qm;++r)t.push("a"+r),e.push("o"+r);var n=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(r=2;r<=qm;++r)n.push("case ",r,":return o",r,"(",t.slice(0,r).join(),");");n.push("}var s=new Array(arguments.length);for(var i=0;i1&&(i=1);for(var a=1-i,o=t.length,s=new Array(o),l=0;l0||i>0&&l<0){var u=ey(a,l,o,i);r.push(u),n.push(u.slice())}l<0?n.push(o.slice()):l>0?r.push(o.slice()):(r.push(o.slice()),n.push(o.slice())),i=l}return{positive:r,negative:n}}).positive=function(t,e){for(var r=[],n=ty(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(ey(i,s,a,n)),s>=0&&r.push(a.slice()),n=s}return r},Jm.negative=function(t,e){for(var r=[],n=ty(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(ey(i,s,a,n)),s<=0&&r.push(a.slice()),n=s}return r};var ry=function(t,e,r,n){Id(ny,e,t),Id(ny,r,ny);for(var i=0,a=0;a<2;++a){oy[2]=n[a][2];for(var o=0;o<2;++o){oy[1]=n[o][1];for(var s=0;s<2;++s)oy[0]=n[s][0],ly(iy[i],oy,ny),i+=1}}for(var l=-1,a=0;a<8;++a){for(var u=iy[a][3],c=0;c<3;++c)ay[a][c]=iy[a][c]/u;u<0&&(l<0?l=a:ay[a][2]p&&(l|=1<p&&(l|=1<ay[a][1]&&(w=a));for(var M=-1,a=0;a<3;++a){var A=w^1<ay[T][0]&&(T=A)}}var k=hy;k[0]=k[1]=k[2]=0,k[rg.log2(M^w)]=w&M,k[rg.log2(w^T)]=w&T;var E=7^T;E===l||E===_?(E=7^M,k[rg.log2(T^E)]=E&T):k[rg.log2(M^E)]=E&M;for(var L=fy,C=l,h=0;h<3;++h)L[h]=C&1<>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function ky(t,e,r,n){return new Function([Ty("A","x"+t+"y",e,["y"],n),Ty("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}Ay.bind=function(t,e,r){this.shader.bind(),this.shader.uniforms.model=t,this.shader.uniforms.view=e,this.shader.uniforms.projection=r,xy[0]=this.gl.drawingBufferWidth,xy[1]=this.gl.drawingBufferHeight,this.shader.uniforms.screenShape=xy,this.vao.bind()},Ay.unbind=function(){this.vao.unbind()},Ay.drawAxisLine=function(t,e,r,n,i){var a=_y(my);this.shader.uniforms.majorAxis=my,a[t]=e[1][t]-e[0][t],this.shader.uniforms.minorAxis=a;var o,s=wy(by,r);s[t]+=e[0][t],this.shader.uniforms.offset=s,this.shader.uniforms.lineWidth=i,this.shader.uniforms.color=n,(o=_y(yy))[(t+2)%3]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,6),(o=_y(yy))[(t+1)%3]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,6)},Ay.drawAxisTicks=function(t,e,r,n,i){if(this.tickCount[t]){var a=_y(vy);a[t]=1,this.shader.uniforms.majorAxis=a,this.shader.uniforms.offset=e,this.shader.uniforms.minorAxis=r,this.shader.uniforms.color=n,this.shader.uniforms.lineWidth=i;var o=_y(yy);o[t]=1,this.shader.uniforms.screenAxis=o,this.vao.draw(this.gl.TRIANGLES,this.tickCount[t],this.tickOffset[t])}},Ay.drawGrid=function(t,e,r,n,i,a){if(this.gridCount[t]){var o=_y(my);o[e]=r[1][e]-r[0][e],this.shader.uniforms.minorAxis=o;var s=wy(by,n);s[e]+=r[0][e],this.shader.uniforms.offset=s;var l=_y(vy);l[t]=1,this.shader.uniforms.majorAxis=l;var u=_y(yy);u[t]=1,this.shader.uniforms.screenAxis=u,this.shader.uniforms.lineWidth=a,this.shader.uniforms.color=i,this.vao.draw(this.gl.TRIANGLES,this.gridCount[t],this.gridOffset[t])}},Ay.drawZero=function(t,e,r,n,i,a){var o=_y(my);this.shader.uniforms.majorAxis=o,o[t]=r[1][t]-r[0][t],this.shader.uniforms.minorAxis=o;var s=wy(by,n);s[t]+=r[0][t],this.shader.uniforms.offset=s;var l=_y(yy);l[e]=1,this.shader.uniforms.screenAxis=l,this.shader.uniforms.lineWidth=a,this.shader.uniforms.color=i,this.vao.draw(this.gl.TRIANGLES,6)},Ay.dispose=function(){this.vao.dispose(),this.vertBuffer.dispose(),this.shader.dispose()};var Ey={ge:ky(">=",!1,"GE"),gt:ky(">",!1,"GT"),lt:ky("<",!0,"LT"),le:ky("<=",!0,"LE"),eq:ky("-",!0,"EQ",!0)},Ly={},Cy=6;function Sy(t,e){for(var r=new Array(t.length-1),n=1;n>1;return["sum(",Py(t.slice(0,e)),",",Py(t.slice(e)),")"].join("")}function Ry(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return Ry(e,t)}function Oy(t){if(2===t.length)return[["diff(",Ry(t[0][0],t[1][1]),",",Ry(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0;){for(var l=r.pop(),a=r.pop(),u=-1,c=-1,o=i[a],f=1;f=0||(e.flip(a,l),jy(t,e,r,u,a,c),jy(t,e,r,a,c,u),jy(t,e,r,c,l,u),jy(t,e,r,l,u,c)))}};function jy(t,e,r,n,i,a){var o=e.opposite(n,i);if(!(o<0)){if(i0||o.length>0;){for(;a.length>0;){var h=a.pop();if(s[h]!==-i){s[h]=i;l[h];for(var f=0;f<3;++f){var d=c[3*h+f];d>=0&&0===s[d]&&(u[3*h+f]?o.push(d):(a.push(d),s[d]=i))}}}var p=o;o=a,a=p,o.length=0,i=-i}var g=function(t,e,r){for(var n=0,i=0;il[0]&&i.push(new Qy(l,s,Wy,a),new Qy(s,l,Xy,a))}i.sort(Ky);for(var u=i[0].a[0]-(1+Math.abs(i[0].a[0]))*Math.pow(2,-52),c=[new Zy([u,1],[u,0],-1,[],[],[],[])],h=[],a=0,f=i.length;a1&&qy(r[u[c-2]],r[u[c-1]],n)>0;)t.push([u[c-1],u[c-2],i]),c-=1;u.length=c,u.push(i);var h=l.upperIds;for(c=h.length;c>1&&qy(r[h[c-2]],r[h[c-1]],n)<0;)t.push([h[c-2],h[c-1],i]),c-=1;h.length=c,h.push(i)}}function tb(t,e){var r;return(r=t.a[0]=0}}(),ab.removeTriangle=function(t,e,r){var n=this.stars;ob(n[t],e,r),ob(n[e],r,t),ob(n[r],t,e)},ab.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},ab.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;n=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function s(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;o=49?s-49+10:s>=17?s-17+10:s}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[a]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);else if("le"===n)for(i=0,a=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)i=o(t,r,r+6),this.words[n]|=i<>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==e&&(i=o(t,e,r+6),this.words[n]|=i<>>26-a&4194303),this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,o=a%n,l=Math.min(a,a-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var l=["","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"],u=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],a=0|e.words[0],o=i*a,s=67108863&o,l=o/67108864|0;r.words[0]=s;for(var u=1;u>>26,h=67108863&l,f=Math.min(u,e.length-1),d=Math.max(0,u-t.length+1);d<=f;d++){var p=u-d|0;c+=(o=(i=0|t.words[p])*(a=0|e.words[d])+h)/67108864|0,h=67108863&o}r.words[u]=0|h,l=0|c}return 0!==l?r.words[u]=0|l:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var i=0,a=0,o=0;o>>24-i&16777215)||o!==this.length-1?l[6-h.length]+h+n:h+n,(i+=2)>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var f=u[t],d=c[t];n="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(d).toString(t);n=(p=p.idivn(d)).isZero()?g+n:l[f-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==a),this.toArrayLike(a,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),a=n||Math.max(1,i);r(i<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var o,s,l="le"===e,u=new t(a),c=this.clone();if(l){for(s=0;!c.isZero();s++)o=c.andln(255),c.iushrn(8),u[s]=o;for(;s=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26;for(;0!==i&&a>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==a&&o>26,this.words[o]=67108863&e;if(0===a&&o>>13,d=0|o[1],p=8191&d,g=d>>>13,v=0|o[2],m=8191&v,y=v>>>13,b=0|o[3],x=8191&b,_=b>>>13,w=0|o[4],M=8191&w,A=w>>>13,T=0|o[5],k=8191&T,E=T>>>13,L=0|o[6],C=8191&L,S=L>>>13,P=0|o[7],R=8191&P,O=P>>>13,I=0|o[8],N=8191&I,D=I>>>13,z=0|o[9],F=8191&z,j=z>>>13,B=0|s[0],U=8191&B,V=B>>>13,H=0|s[1],q=8191&H,G=H>>>13,X=0|s[2],W=8191&X,Y=X>>>13,Z=0|s[3],Q=8191&Z,K=Z>>>13,$=0|s[4],J=8191&$,tt=$>>>13,et=0|s[5],rt=8191&et,nt=et>>>13,it=0|s[6],at=8191&it,ot=it>>>13,st=0|s[7],lt=8191&st,ut=st>>>13,ct=0|s[8],ht=8191&ct,ft=ct>>>13,dt=0|s[9],pt=8191&dt,gt=dt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(u+(n=Math.imul(h,U))|0)+((8191&(i=(i=Math.imul(h,V))+Math.imul(f,U)|0))<<13)|0;u=((a=Math.imul(f,V))+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(p,U),i=(i=Math.imul(p,V))+Math.imul(g,U)|0,a=Math.imul(g,V);var mt=(u+(n=n+Math.imul(h,q)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(f,q)|0))<<13)|0;u=((a=a+Math.imul(f,G)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,U),i=(i=Math.imul(m,V))+Math.imul(y,U)|0,a=Math.imul(y,V),n=n+Math.imul(p,q)|0,i=(i=i+Math.imul(p,G)|0)+Math.imul(g,q)|0,a=a+Math.imul(g,G)|0;var yt=(u+(n=n+Math.imul(h,W)|0)|0)+((8191&(i=(i=i+Math.imul(h,Y)|0)+Math.imul(f,W)|0))<<13)|0;u=((a=a+Math.imul(f,Y)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(x,U),i=(i=Math.imul(x,V))+Math.imul(_,U)|0,a=Math.imul(_,V),n=n+Math.imul(m,q)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,q)|0,a=a+Math.imul(y,G)|0,n=n+Math.imul(p,W)|0,i=(i=i+Math.imul(p,Y)|0)+Math.imul(g,W)|0,a=a+Math.imul(g,Y)|0;var bt=(u+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(f,Q)|0))<<13)|0;u=((a=a+Math.imul(f,K)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(M,U),i=(i=Math.imul(M,V))+Math.imul(A,U)|0,a=Math.imul(A,V),n=n+Math.imul(x,q)|0,i=(i=i+Math.imul(x,G)|0)+Math.imul(_,q)|0,a=a+Math.imul(_,G)|0,n=n+Math.imul(m,W)|0,i=(i=i+Math.imul(m,Y)|0)+Math.imul(y,W)|0,a=a+Math.imul(y,Y)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,K)|0)+Math.imul(g,Q)|0,a=a+Math.imul(g,K)|0;var xt=(u+(n=n+Math.imul(h,J)|0)|0)+((8191&(i=(i=i+Math.imul(h,tt)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,tt)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(k,U),i=(i=Math.imul(k,V))+Math.imul(E,U)|0,a=Math.imul(E,V),n=n+Math.imul(M,q)|0,i=(i=i+Math.imul(M,G)|0)+Math.imul(A,q)|0,a=a+Math.imul(A,G)|0,n=n+Math.imul(x,W)|0,i=(i=i+Math.imul(x,Y)|0)+Math.imul(_,W)|0,a=a+Math.imul(_,Y)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,K)|0)+Math.imul(y,Q)|0,a=a+Math.imul(y,K)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,tt)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,tt)|0;var _t=(u+(n=n+Math.imul(h,rt)|0)|0)+((8191&(i=(i=i+Math.imul(h,nt)|0)+Math.imul(f,rt)|0))<<13)|0;u=((a=a+Math.imul(f,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(C,U),i=(i=Math.imul(C,V))+Math.imul(S,U)|0,a=Math.imul(S,V),n=n+Math.imul(k,q)|0,i=(i=i+Math.imul(k,G)|0)+Math.imul(E,q)|0,a=a+Math.imul(E,G)|0,n=n+Math.imul(M,W)|0,i=(i=i+Math.imul(M,Y)|0)+Math.imul(A,W)|0,a=a+Math.imul(A,Y)|0,n=n+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,K)|0)+Math.imul(_,Q)|0,a=a+Math.imul(_,K)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,tt)|0,n=n+Math.imul(p,rt)|0,i=(i=i+Math.imul(p,nt)|0)+Math.imul(g,rt)|0,a=a+Math.imul(g,nt)|0;var wt=(u+(n=n+Math.imul(h,at)|0)|0)+((8191&(i=(i=i+Math.imul(h,ot)|0)+Math.imul(f,at)|0))<<13)|0;u=((a=a+Math.imul(f,ot)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(R,U),i=(i=Math.imul(R,V))+Math.imul(O,U)|0,a=Math.imul(O,V),n=n+Math.imul(C,q)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(S,q)|0,a=a+Math.imul(S,G)|0,n=n+Math.imul(k,W)|0,i=(i=i+Math.imul(k,Y)|0)+Math.imul(E,W)|0,a=a+Math.imul(E,Y)|0,n=n+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,K)|0)+Math.imul(A,Q)|0,a=a+Math.imul(A,K)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,tt)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,a=a+Math.imul(y,nt)|0,n=n+Math.imul(p,at)|0,i=(i=i+Math.imul(p,ot)|0)+Math.imul(g,at)|0,a=a+Math.imul(g,ot)|0;var Mt=(u+(n=n+Math.imul(h,lt)|0)|0)+((8191&(i=(i=i+Math.imul(h,ut)|0)+Math.imul(f,lt)|0))<<13)|0;u=((a=a+Math.imul(f,ut)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(N,U),i=(i=Math.imul(N,V))+Math.imul(D,U)|0,a=Math.imul(D,V),n=n+Math.imul(R,q)|0,i=(i=i+Math.imul(R,G)|0)+Math.imul(O,q)|0,a=a+Math.imul(O,G)|0,n=n+Math.imul(C,W)|0,i=(i=i+Math.imul(C,Y)|0)+Math.imul(S,W)|0,a=a+Math.imul(S,Y)|0,n=n+Math.imul(k,Q)|0,i=(i=i+Math.imul(k,K)|0)+Math.imul(E,Q)|0,a=a+Math.imul(E,K)|0,n=n+Math.imul(M,J)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(A,J)|0,a=a+Math.imul(A,tt)|0,n=n+Math.imul(x,rt)|0,i=(i=i+Math.imul(x,nt)|0)+Math.imul(_,rt)|0,a=a+Math.imul(_,nt)|0,n=n+Math.imul(m,at)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(y,at)|0,a=a+Math.imul(y,ot)|0,n=n+Math.imul(p,lt)|0,i=(i=i+Math.imul(p,ut)|0)+Math.imul(g,lt)|0,a=a+Math.imul(g,ut)|0;var At=(u+(n=n+Math.imul(h,ht)|0)|0)+((8191&(i=(i=i+Math.imul(h,ft)|0)+Math.imul(f,ht)|0))<<13)|0;u=((a=a+Math.imul(f,ft)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(F,U),i=(i=Math.imul(F,V))+Math.imul(j,U)|0,a=Math.imul(j,V),n=n+Math.imul(N,q)|0,i=(i=i+Math.imul(N,G)|0)+Math.imul(D,q)|0,a=a+Math.imul(D,G)|0,n=n+Math.imul(R,W)|0,i=(i=i+Math.imul(R,Y)|0)+Math.imul(O,W)|0,a=a+Math.imul(O,Y)|0,n=n+Math.imul(C,Q)|0,i=(i=i+Math.imul(C,K)|0)+Math.imul(S,Q)|0,a=a+Math.imul(S,K)|0,n=n+Math.imul(k,J)|0,i=(i=i+Math.imul(k,tt)|0)+Math.imul(E,J)|0,a=a+Math.imul(E,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(A,rt)|0,a=a+Math.imul(A,nt)|0,n=n+Math.imul(x,at)|0,i=(i=i+Math.imul(x,ot)|0)+Math.imul(_,at)|0,a=a+Math.imul(_,ot)|0,n=n+Math.imul(m,lt)|0,i=(i=i+Math.imul(m,ut)|0)+Math.imul(y,lt)|0,a=a+Math.imul(y,ut)|0,n=n+Math.imul(p,ht)|0,i=(i=i+Math.imul(p,ft)|0)+Math.imul(g,ht)|0,a=a+Math.imul(g,ft)|0;var Tt=(u+(n=n+Math.imul(h,pt)|0)|0)+((8191&(i=(i=i+Math.imul(h,gt)|0)+Math.imul(f,pt)|0))<<13)|0;u=((a=a+Math.imul(f,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(F,q),i=(i=Math.imul(F,G))+Math.imul(j,q)|0,a=Math.imul(j,G),n=n+Math.imul(N,W)|0,i=(i=i+Math.imul(N,Y)|0)+Math.imul(D,W)|0,a=a+Math.imul(D,Y)|0,n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,K)|0)+Math.imul(O,Q)|0,a=a+Math.imul(O,K)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,tt)|0,n=n+Math.imul(k,rt)|0,i=(i=i+Math.imul(k,nt)|0)+Math.imul(E,rt)|0,a=a+Math.imul(E,nt)|0,n=n+Math.imul(M,at)|0,i=(i=i+Math.imul(M,ot)|0)+Math.imul(A,at)|0,a=a+Math.imul(A,ot)|0,n=n+Math.imul(x,lt)|0,i=(i=i+Math.imul(x,ut)|0)+Math.imul(_,lt)|0,a=a+Math.imul(_,ut)|0,n=n+Math.imul(m,ht)|0,i=(i=i+Math.imul(m,ft)|0)+Math.imul(y,ht)|0,a=a+Math.imul(y,ft)|0;var kt=(u+(n=n+Math.imul(p,pt)|0)|0)+((8191&(i=(i=i+Math.imul(p,gt)|0)+Math.imul(g,pt)|0))<<13)|0;u=((a=a+Math.imul(g,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(F,W),i=(i=Math.imul(F,Y))+Math.imul(j,W)|0,a=Math.imul(j,Y),n=n+Math.imul(N,Q)|0,i=(i=i+Math.imul(N,K)|0)+Math.imul(D,Q)|0,a=a+Math.imul(D,K)|0,n=n+Math.imul(R,J)|0,i=(i=i+Math.imul(R,tt)|0)+Math.imul(O,J)|0,a=a+Math.imul(O,tt)|0,n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(S,rt)|0,a=a+Math.imul(S,nt)|0,n=n+Math.imul(k,at)|0,i=(i=i+Math.imul(k,ot)|0)+Math.imul(E,at)|0,a=a+Math.imul(E,ot)|0,n=n+Math.imul(M,lt)|0,i=(i=i+Math.imul(M,ut)|0)+Math.imul(A,lt)|0,a=a+Math.imul(A,ut)|0,n=n+Math.imul(x,ht)|0,i=(i=i+Math.imul(x,ft)|0)+Math.imul(_,ht)|0,a=a+Math.imul(_,ft)|0;var Et=(u+(n=n+Math.imul(m,pt)|0)|0)+((8191&(i=(i=i+Math.imul(m,gt)|0)+Math.imul(y,pt)|0))<<13)|0;u=((a=a+Math.imul(y,gt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(F,Q),i=(i=Math.imul(F,K))+Math.imul(j,Q)|0,a=Math.imul(j,K),n=n+Math.imul(N,J)|0,i=(i=i+Math.imul(N,tt)|0)+Math.imul(D,J)|0,a=a+Math.imul(D,tt)|0,n=n+Math.imul(R,rt)|0,i=(i=i+Math.imul(R,nt)|0)+Math.imul(O,rt)|0,a=a+Math.imul(O,nt)|0,n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ot)|0)+Math.imul(S,at)|0,a=a+Math.imul(S,ot)|0,n=n+Math.imul(k,lt)|0,i=(i=i+Math.imul(k,ut)|0)+Math.imul(E,lt)|0,a=a+Math.imul(E,ut)|0,n=n+Math.imul(M,ht)|0,i=(i=i+Math.imul(M,ft)|0)+Math.imul(A,ht)|0,a=a+Math.imul(A,ft)|0;var Lt=(u+(n=n+Math.imul(x,pt)|0)|0)+((8191&(i=(i=i+Math.imul(x,gt)|0)+Math.imul(_,pt)|0))<<13)|0;u=((a=a+Math.imul(_,gt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(F,J),i=(i=Math.imul(F,tt))+Math.imul(j,J)|0,a=Math.imul(j,tt),n=n+Math.imul(N,rt)|0,i=(i=i+Math.imul(N,nt)|0)+Math.imul(D,rt)|0,a=a+Math.imul(D,nt)|0,n=n+Math.imul(R,at)|0,i=(i=i+Math.imul(R,ot)|0)+Math.imul(O,at)|0,a=a+Math.imul(O,ot)|0,n=n+Math.imul(C,lt)|0,i=(i=i+Math.imul(C,ut)|0)+Math.imul(S,lt)|0,a=a+Math.imul(S,ut)|0,n=n+Math.imul(k,ht)|0,i=(i=i+Math.imul(k,ft)|0)+Math.imul(E,ht)|0,a=a+Math.imul(E,ft)|0;var Ct=(u+(n=n+Math.imul(M,pt)|0)|0)+((8191&(i=(i=i+Math.imul(M,gt)|0)+Math.imul(A,pt)|0))<<13)|0;u=((a=a+Math.imul(A,gt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(F,rt),i=(i=Math.imul(F,nt))+Math.imul(j,rt)|0,a=Math.imul(j,nt),n=n+Math.imul(N,at)|0,i=(i=i+Math.imul(N,ot)|0)+Math.imul(D,at)|0,a=a+Math.imul(D,ot)|0,n=n+Math.imul(R,lt)|0,i=(i=i+Math.imul(R,ut)|0)+Math.imul(O,lt)|0,a=a+Math.imul(O,ut)|0,n=n+Math.imul(C,ht)|0,i=(i=i+Math.imul(C,ft)|0)+Math.imul(S,ht)|0,a=a+Math.imul(S,ft)|0;var St=(u+(n=n+Math.imul(k,pt)|0)|0)+((8191&(i=(i=i+Math.imul(k,gt)|0)+Math.imul(E,pt)|0))<<13)|0;u=((a=a+Math.imul(E,gt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(F,at),i=(i=Math.imul(F,ot))+Math.imul(j,at)|0,a=Math.imul(j,ot),n=n+Math.imul(N,lt)|0,i=(i=i+Math.imul(N,ut)|0)+Math.imul(D,lt)|0,a=a+Math.imul(D,ut)|0,n=n+Math.imul(R,ht)|0,i=(i=i+Math.imul(R,ft)|0)+Math.imul(O,ht)|0,a=a+Math.imul(O,ft)|0;var Pt=(u+(n=n+Math.imul(C,pt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(S,pt)|0))<<13)|0;u=((a=a+Math.imul(S,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(F,lt),i=(i=Math.imul(F,ut))+Math.imul(j,lt)|0,a=Math.imul(j,ut),n=n+Math.imul(N,ht)|0,i=(i=i+Math.imul(N,ft)|0)+Math.imul(D,ht)|0,a=a+Math.imul(D,ft)|0;var Rt=(u+(n=n+Math.imul(R,pt)|0)|0)+((8191&(i=(i=i+Math.imul(R,gt)|0)+Math.imul(O,pt)|0))<<13)|0;u=((a=a+Math.imul(O,gt)|0)+(i>>>13)|0)+(Rt>>>26)|0,Rt&=67108863,n=Math.imul(F,ht),i=(i=Math.imul(F,ft))+Math.imul(j,ht)|0,a=Math.imul(j,ft);var Ot=(u+(n=n+Math.imul(N,pt)|0)|0)+((8191&(i=(i=i+Math.imul(N,gt)|0)+Math.imul(D,pt)|0))<<13)|0;u=((a=a+Math.imul(D,gt)|0)+(i>>>13)|0)+(Ot>>>26)|0,Ot&=67108863;var It=(u+(n=Math.imul(F,pt))|0)+((8191&(i=(i=Math.imul(F,gt))+Math.imul(j,pt)|0))<<13)|0;return u=((a=Math.imul(j,gt))+(i>>>13)|0)+(It>>>26)|0,It&=67108863,l[0]=vt,l[1]=mt,l[2]=yt,l[3]=bt,l[4]=xt,l[5]=_t,l[6]=wt,l[7]=Mt,l[8]=At,l[9]=Tt,l[10]=kt,l[11]=Et,l[12]=Lt,l[13]=Ct,l[14]=St,l[15]=Pt,l[16]=Rt,l[17]=Ot,l[18]=It,0!==u&&(l[19]=u,r.length++),r};function d(t,e,r){return(new p).mulp(t,e,r)}function p(t,e){this.x=t,this.y=e}Math.imul||(f=h),i.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?f(this,t,e):r<63?h(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,a=0;a>>26)|0)>>>26,o&=67108863}r.words[a]=s,n=o,o=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,t,e):d(this,t,e)},p.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},p.prototype.permute=function(t,e,r,n,i,a){for(var o=0;o>>=1)i++;return 1<>>=13,n[2*o+1]=8191&a,a>>>=13;for(o=2*e;o>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,a=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(e=0;e>>26-n}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=i);u--){var h=0|this.words[u];this.words[u]=c<<26-a|h>>>a,c=h&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(l/67108864|0),this.words[i+n]=67108863&a}for(;i>26,this.words[i+n]=67108863&a;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),a=t,o=0|a.words[a.length-1];0!==(r=26-this._countBits(o))&&(a=a.ushln(r),n.iushln(r),o=0|a.words[a.length-1]);var s,l=n.length-a.length;if("mod"!==e){(s=new i(null)).length=l+1,s.words=new Array(s.length);for(var u=0;u=0;h--){var f=67108864*(0|n.words[a.length+h])+(0|n.words[a.length+h-1]);for(f=Math.min(f/o|0,67108863),n._ishlnsubmul(a,f,h);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(a,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(a=s.div.neg()),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.iadd(t)),{div:a,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(a=s.div.neg()),{div:a,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var a,o,s},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++u;for(var c=n.clone(),h=e.clone();!e.isZero();){for(var f=0,d=1;0==(e.words[0]&d)&&f<26;++f,d<<=1);if(f>0)for(e.iushrn(f);f-- >0;)(a.isOdd()||o.isOdd())&&(a.iadd(c),o.isub(h)),a.iushrn(1),o.iushrn(1);for(var p=0,g=1;0==(n.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(n.iushrn(p);p-- >0;)(s.isOdd()||l.isOdd())&&(s.iadd(c),l.isub(h)),s.iushrn(1),l.iushrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.iushln(u)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a,o=new i(1),s=new i(0),l=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);for(var h=0,f=1;0==(n.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(n.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(s)):(n.isub(e),s.isub(o))}return(a=0===e.cmpn(1)?o:s).cmpn(0)<0&&a.iadd(t),a},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,s&=67108863,this.words[o]=s}return 0!==a&&(this.words[o]=a,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function b(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function x(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function w(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,i=a}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new y;else if("p192"===t)e=new b;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new x}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var a=this.m.subn(1),o=0;!a.isZero()&&0===a.andln(1);)o++,a.iushrn(1);r(!a.isZero());var s=new i(1).toRed(this),l=s.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,u).cmp(l);)c.redIAdd(l);for(var h=this.pow(c,a),f=this.pow(t,a.addn(1).iushrn(1)),d=this.pow(t,a),p=o;0!==d.cmp(s);){for(var g=d,v=0;0!==g.cmp(s);v++)g=g.redSqr();r(v=0;n--){for(var u=e.words[n],c=l-1;c>=0;c--){var h=u>>c&1;a!==r[0]&&(a=this.sqr(a)),0!==h||0!==o?(o<<=1,o|=h,(4===++s||0===n&&0===c)&&(a=this.mul(a,r[o]),s=0,o=0)):s=0}l=26}return a},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new w(t)},n(w,_),w.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},w.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},w.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},w.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).iushrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},w.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(db,this),db=db.exports;var pb=function(t){return t.cmp(new db(0))};var gb={};(function(t){var e=!1;if("undefined"!=typeof Float64Array){var r=new Float64Array(1),n=new Uint32Array(r.buffer);if(r[0]=1,e=!0,1072693248===n[1]){(gb=function(t){return r[0]=t,[n[0],n[1]]}).pack=function(t,e){return n[0]=t,n[1]=e,r[0]},gb.lo=function(t){return r[0]=t,n[0]},gb.hi=function(t){return r[0]=t,n[1]}}else if(1072693248===n[0]){(gb=function(t){return r[0]=t,[n[1],n[0]]}).pack=function(t,e){return n[1]=t,n[0]=e,r[0]},gb.lo=function(t){return r[0]=t,n[1]},gb.hi=function(t){return r[0]=t,n[0]}}else e=!1}if(!e){var i=new t(8);(gb=function(t){return i.writeDoubleLE(t,0,!0),[i.readUInt32LE(0,!0),i.readUInt32LE(4,!0)]}).pack=function(t,e){return i.writeUInt32LE(t,0,!0),i.writeUInt32LE(e,4,!0),i.readDoubleLE(0,!0)},gb.lo=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(0,!0)},gb.hi=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(4,!0)}}gb.sign=function(t){return gb.hi(t)>>>31},gb.exponent=function(t){return(gb.hi(t)<<1>>>21)-1023},gb.fraction=function(t){var e=gb.lo(t),r=gb.hi(t),n=1048575&r;return 2146435072&r&&(n+=1<<20),[e,n]},gb.denormalized=function(t){return!(2146435072&gb.hi(t))}}).call(this,gg.Buffer);var vb=function(t){var e=gb.exponent(t);return e<52?new db(t):new db(t*Math.pow(2,52-e)).ushln(e-52)};var mb=function(t,e){var r=pb(t),n=pb(e);if(0===r)return[vb(0),vb(1)];if(0===n)return[vb(0),vb(0)];n<0&&(t=t.neg(),e=e.neg());var i=t.gcd(e);if(i.cmpn(1))return[t.div(i),e.div(i)];return[t,e]};var yb=function(t,e){return mb(t[0].mul(e[1]),t[1].mul(e[0]))};var bb=function(t){return t&&"object"==typeof t&&Boolean(t.words)};var xb=function(t){return Array.isArray(t)&&2===t.length&&bb(t[0])&&bb(t[1])};var _b=function(t){return new db(t)};var wb=function t(e,r){if(xb(e))return r?yb(e,t(r)):[e[0].clone(),e[1].clone()];var n=0;var i,a;if(bb(e))i=e.clone();else if("string"==typeof e)i=_b(e);else{if(0===e)return[vb(0),vb(1)];if(e===Math.floor(e))i=vb(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),n-=256;i=vb(e)}}if(xb(r))i.mul(r[1]),a=r[0].clone();else if(bb(r))a=r.clone();else if("string"==typeof r)a=_b(r);else if(r)if(r===Math.floor(r))a=vb(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),n+=256;a=vb(r)}else a=vb(1);n>0?i=i.ushln(n):n<0&&(a=a.ushln(-n));return mb(i,a)};var Mb=function(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var i=0;i20)return 52;return r+32};var kb=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.abs().divmod(r.abs()),i=n.div,a=Mb(i),o=n.mod,s=e.negative!==r.negative?-1:1;if(0===o.cmpn(0))return s*a;if(a){var l=Tb(a)+4,u=Mb(o.ushln(l).divRound(r));return s*(a+u*Math.pow(2,-l))}var c=r.bitLength()-o.bitLength()+53,u=Mb(o.ushln(c).divRound(r));return c<1023?s*u*Math.pow(2,-c):(u*=Math.pow(2,-1023),s*u*Math.pow(2,1023-c))};var Eb={},Lb="d",Cb="ax",Sb="vv",Pb="fp",Rb="es",Ob="rs",Ib="re",Nb="rb",Db="ri",zb="rp",Fb="bs",jb="be",Bb="bb",Ub="bi",Vb="bp",Hb="rv",qb="Q",Gb=[Lb,Cb,Sb,Ob,Ib,Nb,Db,Fb,jb,Bb,Ub];function Xb(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],n=Gb.slice();t||n.splice(3,0,Pb);var i=["function "+e+"("+n.join()+"){"];function a(e,n){var a=function(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",Gb.join(),"){","var ",Rb,"=2*",Lb,";"],a="for(var i="+Ob+","+zb+"="+Rb+"*"+Ob+";i<"+Ib+";++i,"+zb+"+="+Rb+"){var x0="+Nb+"["+Cb+"+"+zb+"],x1="+Nb+"["+Cb+"+"+zb+"+"+Lb+"],xi="+Db+"[i];",o="for(var j="+Fb+","+Vb+"="+Rb+"*"+Fb+";j<"+jb+";++j,"+Vb+"+="+Rb+"){var y0="+Bb+"["+Cb+"+"+Vb+"],"+(r?"y1="+Bb+"["+Cb+"+"+Vb+"+"+Lb+"],":"")+"yi="+Ub+"[j];";return t?i.push(a,qb,":",o):i.push(o,qb,":",a),r?i.push("if(y1"+jb+"-"+Fb+"){"),t?(a(!0,!1),i.push("}else{"),a(!1,!1)):(i.push("if("+Pb+"){"),a(!0,!0),i.push("}else{"),a(!0,!1),i.push("}}else{if("+Pb+"){"),a(!1,!0),i.push("}else{"),a(!1,!1),i.push("}")),i.push("}}return "+e);var o=r.join("")+i.join("");return new Function(o)()}Eb.partial=Xb(!1),Eb.full=Xb(!0);var Wb=function(t,e){var r="abcdef".split("").concat(e),n=[];t.indexOf("lo")>=0&&n.push("lo=e[k+n]");t.indexOf("hi")>=0&&n.push("hi=e[k+o]");return r.push(Yb.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)},Yb="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m";var Zb=function(t,e,r,n,i,a){if(n<=r+1)return r;var o=r,s=n,l=n+r>>>1,u=2*t,c=l,h=i[u*l+e];for(;o=v?(c=g,h=v):p>=y?(c=d,h=p):(c=m,h=y):v>=y?(c=g,h=v):y>=p?(c=d,h=p):(c=m,h=y);for(var b=u*(s-1),x=u*c,_=0;_r&&i[h+e]>u;--c,h-=o){for(var f=h,d=h+o,p=0;p>1,l=s-i,u=s+i,c=a,h=l,f=s,d=u,p=o,g=e+1,v=r-1,m=0;ox(c,h,n)&&(m=c,c=h,h=m);ox(d,p,n)&&(m=d,d=p,p=m);ox(c,f,n)&&(m=c,c=f,f=m);ox(h,f,n)&&(m=h,h=f,f=m);ox(c,d,n)&&(m=c,c=d,d=m);ox(f,d,n)&&(m=f,f=d,d=m);ox(h,p,n)&&(m=h,h=p,p=m);ox(h,f,n)&&(m=h,h=f,f=m);ox(d,p,n)&&(m=d,d=p,p=m);var y=n[2*h];var b=n[2*h+1];var x=n[2*d];var _=n[2*d+1];var w=2*c;var M=2*f;var A=2*p;var T=2*a;var k=2*s;var E=2*o;for(var L=0;L<2;++L){var C=n[w+L],S=n[M+L],P=n[A+L];n[T+L]=C,n[k+L]=S,n[E+L]=P}nx(l,e,n);nx(u,r,n);for(var R=g;R<=v;++R)if(sx(R,y,b,n))R!==g&&rx(R,g,n),++g;else if(!sx(R,x,_,n))for(;;){if(sx(v,x,_,n)){sx(v,y,b,n)?(ix(R,g,v,n),++g,--v):(rx(R,v,n),--v);break}if(--vt;){var u=r[l-2],c=r[l-1];if(ur[e+1])}function sx(t,e,r,n){var i=n[t*=2];return i>>1;Jb(vx,y);for(var b=0,x=0,p=0;p=ux)mx(fx,dx,x--,_=_-ux|0);else if(_>=0)mx(cx,hx,b--,_);else if(_<=-ux){_=-_-ux|0;for(var w=0;w>>1;Jb(vx,y);for(var b=0,x=0,_=0,p=0;p>1==vx[2*p+3]>>1&&(M=2,p+=1),w<0){for(var A=-(w>>1)-1,T=0;T<_;++T){var k=e(px[T],A);if(void 0!==k)return k}if(0!==M)for(var T=0;T>1)-1;0===M?mx(cx,hx,b--,A):1===M?mx(fx,dx,x--,A):2===M&&mx(px,gx,_--,A)}}},scanBipartite:function(t,e,r,n,i,a,o,s,l,u,c,h){var f=0,d=2*t,p=e,g=e+t,v=1,m=1;n?m=ux:v=ux;for(var y=i;y>>1;Jb(vx,w);for(var M=0,y=0;y=ux?(T=!n,b-=ux):(T=!!n,b-=1),T)yx(cx,hx,M++,b);else{var k=h[b],E=d*b,L=c[E+e+1],C=c[E+e+1+t];t:for(var S=0;S>>1;Jb(vx,b);for(var x=0,g=0;g=ux)cx[x++]=v-ux;else{var w=c[v-=1],M=f*v,A=u[M+e+1],T=u[M+e+1+t];t:for(var k=0;k=0;--k)if(cx[k]===v){for(var S=k+1;S0;){var f=(c-=1)*Px,d=Ox[f],p=Ox[f+1],g=Ox[f+2],v=Ox[f+3],m=Ox[f+4],y=Ox[f+5],b=c*Rx,x=Ix[b],_=Ix[b+1],w=1&y,M=!!(16&y),A=i,T=a,k=s,E=l;if(w&&(A=s,T=l,k=i,E=a),!(2&y&&(g=Ex(t,d,p,g,A,T,_),p>=g)||4&y&&(p=Lx(t,d,p,g,A,T,x))>=g)){var L=g-p,C=m-v;if(M){if(t*L*(L+C)=p0)&&!(p1>=hi)",["p0","p1"]),kx=Wb("lo===p0",["p0"]),Ex=Wb("lo>>1;if(!(o<=0)){var s,l=tv.mallocDouble(2*o*i),u=tv.mallocInt32(i);if((i=Ux(t,o,l,u))>0){if(1===o&&n)lx.init(i),s=lx.sweepComplete(o,r,0,i,l,u,0,i,l,u);else{var c=tv.mallocDouble(2*o*a),h=tv.mallocInt32(a);(a=Ux(e,o,c,h))>0&&(lx.init(i+a),s=1===o?lx.sweepBipartite(o,r,0,i,l,u,0,a,c,h):bx(o,r,n,i,l,u,a,c,h),tv.free(c),tv.free(h))}tv.free(l),tv.free(u)}return s}}}function Hx(t,e){Fx.push([t,e])}var qx=function(t,e){return mb(t[0].mul(e[0]),t[1].mul(e[1]))};var Gx=function(t){return pb(t[0])*pb(t[1])};var Xx=function(t,e){return mb(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))};var Wx=function(t,e){return mb(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))};var Yx=function(t,e){for(var r=t.length,n=new Array(r),i=0;i>>0,e_=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-Jx:Jx;var r=gb.hi(t),n=gb.lo(t);e>t==t>0?n===t_?(r+=1,n=0):n+=1:0===n?(n=t_,r-=1):n-=1;return gb.pack(n,r)};var r_=function(t){for(var e=new Array(t.length),r=0;r0&&a>0||i<0&&a<0)return!1;var o=i_(r,t,e),s=i_(n,t,e);if(o>0&&s>0||o<0&&s<0)return!1;if(0===i&&0===a&&0===o&&0===s)return function(t,e,r,n){for(var i=0;i<2;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],h=Math.min(u,c),f=Math.max(u,c);if(fe[2]?1:0)}function p_(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--a){var p=e[o=(w=n[a])[0]],g=p[0],v=p[1],m=t[g],y=t[v];if((m[0]-y[0]||m[1]-y[1])<0){var b=g;g=v,v=b}p[0]=g;var x,_=p[1]=w[1];for(i&&(x=p[2]);a>0&&n[a-1][0]===o;){var w,M=(w=n[--a])[1];i?e.push([_,M,x]):e.push([_,M]),_=M}i?e.push([_,v,x]):e.push([_,v])}return s}(t,e,i,o,r));return p_(e,s,r),!!s||(i.length>0||o.length>0)}var v_=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;n0?1:0},b_=function(t,e,r,n){var i=Hm(e,r,n);if(0===i){var a=y_(Hm(t,e,r)),o=y_(Hm(t,e,n));if(a===o){if(0===a){var s=x_(t,e,r),l=x_(t,e,n);return s===l?0:s?1:-1}return 0}return 0===o?a>0?-1:x_(t,e,n)?-1:1:0===a?o>0?1:x_(t,e,r)?1:-1:y_(o-a)}var u=Hm(t,e,r);if(u>0)return i>0&&Hm(t,e,n)>0?1:-1;if(u<0)return i>0||Hm(t,e,n)>0?1:-1;var c=Hm(t,e,n);return c>0?1:x_(t,e,r)?1:-1};function x_(t,e,r){var n=jm(t[0],-e[0]),i=jm(t[1],-e[1]),a=jm(r[0],-e[0]),o=jm(r[1],-e[1]),s=Vm(m_(n,a),m_(i,o));return s[s.length-1]>=0}var __=function(t,e){for(var r=0|e.length,n=t.length,i=[new Array(r),new Array(r)],a=0;a0){a=i[u][r][0],s=u;break}o=a[1^s];for(var c=0;c<2;++c)for(var h=i[c][r],f=0;f0&&(a=d,o=p,s=c)}return n?o:(a&&l(a,s),o)}function c(t,r){var n=i[r][t][0],a=[t];l(n,r);for(var o=n[1^r];;){for(;o!==t;)a.push(o),o=u(a[a.length-2],o,!1);if(i[0][t].length+i[1][t].length===0)break;var s=a[a.length-1],c=t,h=a[1],f=u(s,c,!0);if(b_(e[s],e[c],e[h],e[f])<0)break;a.push(t),o=u(s,c)}return a}function h(t,e){return e[1]===e[e.length-1]}for(var a=0;a0;){i[0][a].length;var p=c(a,f);h(d,p)?d.push.apply(d,p):(d.length>0&&s.push(d),d=p)}d.length>0&&s.push(d)}return s};var w_=function(t,e){for(var r=v_(t,e.length),n=new Array(e.length),i=new Array(e.length),a=[],o=0;o0;){var l=a.pop();n[l]=!1;for(var u=r[l],o=0;o=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function I_(t,e){for(var r=0;r>1],i=[],a=[],o=[];for(r=0;r3*(e+1)?S_(this,t):this.left.insert(t):this.left=F_([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?S_(this,t):this.right.insert(t):this.right=F_([t]);else{var r=ud.ge(this.leftPoints,t,D_),n=ud.ge(this.rightPoints,t,z_);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},E_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?P_(this,t):2===(a=this.left.remove(t))?(this.left=null,this.count-=1,A_):(a===A_&&(this.count-=1),a):M_}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:M_;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,n=this.left;n.right;)r=n,n=n.right;if(r===this)n.right=this.right;else{var i=this.left;a=this.right;r.count-=n.count,r.right=n.left,n.left=i,n.right=a}L_(this,n),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?L_(this,this.left):L_(this,this.right);return A_}for(i=ud.ge(this.leftPoints,t,D_);i3*(e-1)?P_(this,t):2===(a=this.right.remove(t))?(this.right=null,this.count-=1,A_):(a===A_&&(this.count-=1),a):M_;var a}},E_.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return O_(this.rightPoints,t,e)}return I_(this.leftPoints,e)},E_.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?O_(this.rightPoints,t,r):I_(this.leftPoints,r)};var B_=j_.prototype;B_.insert=function(t){this.root?this.root.insert(t):this.root=new k_(t[0],null,null,[t],[t])},B_.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==M_}return!1},B_.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},B_.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(B_,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(B_,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}});var U_=function(t){return new Y_(t||J_,null)},V_=0,H_=1;function q_(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function G_(t){return new q_(t._color,t.key,t.value,t.left,t.right,t._count)}function X_(t,e){return new q_(t,e.key,e.value,e.left,e.right,e._count)}function W_(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function Y_(t,e){this._compare=t,this.root=e}var Z_=Y_.prototype;function Q_(t,e){this.tree=t,this._stack=e}Object.defineProperty(Z_,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(Z_,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(Z_,"length",{get:function(){return this.root?this.root._count:0}}),Z_.insert=function(t,e){for(var r=this._compare,n=this.root,i=[],a=[];n;){var o=r(t,n.key);i.push(n),a.push(o),n=o<=0?n.left:n.right}i.push(new q_(V_,t,e,null,null,1));for(var s=i.length-2;s>=0;--s){n=i[s];a[s]<=0?i[s]=new q_(n._color,n.key,n.value,i[s+1],n.right,n._count+1):i[s]=new q_(n._color,n.key,n.value,n.left,i[s+1],n._count+1)}for(s=i.length-1;s>1;--s){var l=i[s-1];n=i[s];if(l._color===H_||n._color===H_)break;var u=i[s-2];if(u.left===l)if(l.left===n){if(!(c=u.right)||c._color!==V_){if(u._color=V_,u.left=l.right,l._color=H_,l.right=u,i[s-2]=l,i[s-1]=n,W_(u),W_(l),s>=3)(h=i[s-3]).left===u?h.left=l:h.right=l;break}l._color=H_,u.right=X_(H_,c),u._color=V_,s-=1}else{if(!(c=u.right)||c._color!==V_){if(l.right=n.left,u._color=V_,u.left=n.right,n._color=H_,n.left=l,n.right=u,i[s-2]=n,i[s-1]=l,W_(u),W_(l),W_(n),s>=3)(h=i[s-3]).left===u?h.left=n:h.right=n;break}l._color=H_,u.right=X_(H_,c),u._color=V_,s-=1}else if(l.right===n){if(!(c=u.left)||c._color!==V_){if(u._color=V_,u.right=l.left,l._color=H_,l.left=u,i[s-2]=l,i[s-1]=n,W_(u),W_(l),s>=3)(h=i[s-3]).right===u?h.right=l:h.left=l;break}l._color=H_,u.left=X_(H_,c),u._color=V_,s-=1}else{var c;if(!(c=u.left)||c._color!==V_){var h;if(l.left=n.right,u._color=V_,u.right=n.left,n._color=H_,n.right=l,n.left=u,i[s-2]=n,i[s-1]=l,W_(u),W_(l),W_(n),s>=3)(h=i[s-3]).right===u?h.right=n:h.left=n;break}l._color=H_,u.left=X_(H_,c),u._color=V_,s-=1}}return i[0]._color=H_,new Y_(r,i[0])},Z_.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,i){if(r(e,i.key)<=0){var a;if(i.left&&(a=t(e,r,n,i.left)))return a;if(a=n(i.key,i.value))return a}if(i.right)return t(e,r,n,i.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,i,a){var o,s=n(e,a.key),l=n(r,a.key);if(s<=0){if(a.left&&(o=t(e,r,n,i,a.left)))return o;if(l>0&&(o=i(a.key,a.value)))return o}if(l>0&&a.right)return t(e,r,n,i,a.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(Z_,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new Q_(this,t)}}),Object.defineProperty(Z_,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new Q_(this,t)}}),Z_.at=function(t){if(t<0)return new Q_(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new Q_(this,[])},Z_.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<=0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new Q_(this,n)},Z_.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new Q_(this,n)},Z_.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new Q_(this,n)},Z_.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new Q_(this,n)},Z_.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new Q_(this,n);r=i<=0?r.left:r.right}return new Q_(this,[])},Z_.remove=function(t){var e=this.find(t);return e?e.remove():this},Z_.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var K_=Q_.prototype;function $_(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function J_(t,e){return te?1:0}Object.defineProperty(K_,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(K_,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),K_.clone=function(){return new Q_(this.tree,this._stack.slice())},K_.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new q_(r._color,r.key,r.value,r.left,r.right,r._count);for(var n=t.length-2;n>=0;--n){(r=t[n]).left===t[n+1]?e[n]=new q_(r._color,r.key,r.value,e[n+1],r.right,r._count):e[n]=new q_(r._color,r.key,r.value,r.left,e[n+1],r._count)}if((r=e[e.length-1]).left&&r.right){var i=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var a=e[i-1];e.push(new q_(r._color,a.key,a.value,r.left,r.right,r._count)),e[i-1].key=r.key,e[i-1].value=r.value;for(n=e.length-2;n>=i;--n)r=e[n],e[n]=new q_(r._color,r.key,r.value,r.left,e[n+1],r._count);e[i-1].left=e[i]}if((r=e[e.length-1])._color===V_){var o=e[e.length-2];o.left===r?o.left=null:o.right===r&&(o.right=null),e.pop();for(n=0;n=0;--a){if(e=t[a],0===a)return void(e._color=H_);if((r=t[a-1]).left===e){if((n=r.right).right&&n.right._color===V_)return i=(n=r.right=G_(n)).right=G_(n.right),r.right=n.left,n.left=r,n.right=i,n._color=r._color,e._color=H_,r._color=H_,i._color=H_,W_(r),W_(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),void(t[a-1]=n);if(n.left&&n.left._color===V_)return i=(n=r.right=G_(n)).left=G_(n.left),r.right=i.left,n.left=i.right,i.left=r,i.right=n,i._color=r._color,r._color=H_,n._color=H_,e._color=H_,W_(r),W_(n),W_(i),a>1&&((o=t[a-2]).left===r?o.left=i:o.right=i),void(t[a-1]=i);if(n._color===H_){if(r._color===V_)return r._color=H_,void(r.right=X_(V_,n));r.right=X_(V_,n);continue}n=G_(n),r.right=n.left,n.left=r,n._color=r._color,r._color=V_,W_(r),W_(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),t[a-1]=n,t[a]=r,a+11&&((o=t[a-2]).right===r?o.right=n:o.left=n),void(t[a-1]=n);if(n.right&&n.right._color===V_)return i=(n=r.left=G_(n)).right=G_(n.right),r.left=i.right,n.right=i.left,i.right=r,i.left=n,i._color=r._color,r._color=H_,n._color=H_,e._color=H_,W_(r),W_(n),W_(i),a>1&&((o=t[a-2]).right===r?o.right=i:o.left=i),void(t[a-1]=i);if(n._color===H_){if(r._color===V_)return r._color=H_,void(r.left=X_(V_,n));r.left=X_(V_,n);continue}var o;n=G_(n),r.left=n.right,n.right=r,n._color=r._color,r._color=V_,W_(r),W_(n),a>1&&((o=t[a-2]).right===r?o.right=n:o.left=n),t[a-1]=n,t[a]=r,a+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(K_,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(K_,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),K_.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(K_,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),K_.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new q_(n._color,n.key,t,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i)(n=e[i]).left===e[i+1]?r[i]=new q_(n._color,n.key,n.value,r[i+1],n.right,n._count):r[i]=new q_(n._color,n.key,n.value,n.left,r[i+1],n._count);return new Y_(this.tree._compare,r[0])},K_.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(K_,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}});var tw=function(t,e){var r,n,i,a;if(e[0][0]e[1][0]))return ew(e,t);r=e[1],n=e[0]}if(t[0][0]t[1][0]))return-ew(t,e);i=t[1],a=t[0]}var o=Hm(r,n,a),s=Hm(r,n,i);if(o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;if(o=Hm(a,i,n),s=Hm(a,i,r),o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;return n[0]-a[0]};function ew(t,e){var r,n,i,a;if(e[0][0]e[1][0])){var o=Math.min(t[0][1],t[1][1]),s=Math.max(t[0][1],t[1][1]),l=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return su?o-u:s-u}r=e[1],n=e[0]}t[0][1]0)if(e[0]!==a[1][0])r=t,t=t.right;else{if(s=aw(t.right,e))return s;t=t.left}else{if(e[0]!==a[1][0])return t;var s;if(s=aw(t.right,e))return s;t=t.left}}return r}function ow(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function sw(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}nw.prototype.castUp=function(t){var e=ud.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=aw(this.slabs[e],t),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var i=null;if(r&&(i=r.key),e>0){var a=aw(this.slabs[e-1],t);a&&(i?tw(a.key,i)>0&&(i=a.key,n=a.value):(n=a.value,i=a.key))}var o=this.horizontal[e];if(o.length>0){var s=ud.ge(o,t[1],iw);if(s=o.length)return n;l=o[s]}}if(l.start)if(i){var u=Hm(i[0],i[1],[t[0],l.y]);i[0][0]>i[1][0]&&(u=-u),u>0&&(n=l.index)}else n=l.index;else l.y!==t[1]&&(n=l.index)}}}return n};var lw=function(t){for(var e=t.length,r=[],n=[],i=0;i0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=uw(r,o[0],o[1]);if(o[0][0]0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(s<0))return 0;a=1,i=i.right}}return a}}(f.slabs,f.coordinates);return 0===n.length?d:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(hw(n),d)},uw=Hm[3];function cw(){return!0}function hw(t){for(var e={},r=0;r0})).length,l=new Array(s),u=new Array(s),a=0;a0;){var P=C.pop(),R=_[P];Pp(R,function(t,e){return t-e});var O,I=R.length,N=S[P];if(0===N){var g=o[P];O=[g]}for(var a=0;a=0)&&(S[D]=1^N,C.push(D),0===N)){var g=o[D];L(g)||(g.reverse(),O.push(g))}}0===N&&r.push(O)}return r};function pw(t,e){for(var r=new Array(t),n=0;n>1,o=vw(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function _w(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==vw(t[d],a)););}return r}function ww(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return yw(e)},gw.skeleton=ww,gw.boundary=function(t){for(var e=[],r=0,n=t.length;r0)-(t<0)},Mw.abs=function(t){var e=t>>31;return(t^e)-e},Mw.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Mw.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Mw.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Mw.countTrailingZeros=Aw,Mw.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Mw.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Mw.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var Tw=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|Tw[t>>>16&255]<<8|Tw[t>>>24&255]},Mw.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Mw.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Mw.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Mw.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Mw.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Aw(t)+1};var kw=Ew;function Ew(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e>1,o=Cw(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function Iw(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==Cw(t[d],a)););}return r}function Nw(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return Pw(e)},Lw.skeleton=Nw,Lw.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function m(t){for(var e=g(t);;){var r=e,n=2*t+1,i=2*(t+1),a=t;if(n0;){var r=v(t);if(r>=0){var n=g(r);if(e0){var t=w[0];return p(0,T-1),T-=1,m(0),t}return-1}function x(t,e){var r=w[t];return s[r]===e?t:(s[r]=-1/0,y(t),b(),s[r]=e,y((T+=1)-1))}function _(t){if(!l[t]){l[t]=!0;var e=a[t],r=o[t];a[r]>=0&&(a[r]=e),o[e]>=0&&(o[e]=r),M[e]>=0&&x(M[e],d(e)),M[r]>=0&&x(M[r],d(r))}}for(var w=[],M=new Array(n),u=0;u>1;u>=0;--u)m(u);for(;;){var k=b();if(k<0||s[k]>r)break;_(k)}for(var E=[],u=0;u=0&&r>=0&&e!==r){var n=M[e],i=M[r];n!==i&&C.push([n,i])}}),Lw.unique(Lw.normalize(C)),{positions:E,edges:C}};var zw=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;n<1&&e("Must have at least one array argument");var i=t.scalarArguments||0;i<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;s=0?o[s]=!0:o[s]=!1;return function(t,e,r,n,i,a){var o=a.length,s=i.length;if(s<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var l="extractContour"+i.join("_"),u=[],c=[],h=[],f=0;f0&&v.push(Vw(f,i[d-1])+"*"+Uw(i[d-1])),c.push(Yw(f,i[d])+"=("+v.join("-")+")|0")}for(var f=0;f=0;--f)m.push(Uw(i[f]));c.push(rM+"=("+m.join("*")+")|0",tM+"=mallocUint32("+rM+")",Jw+"=mallocUint32("+rM+")",nM+"=0"),c.push(Zw(0)+"=0");for(var d=1;d<1<0;v=v-1&d)g.push(Jw+"["+nM+"+"+Kw(v)+"]");g.push($w(0));for(var v=0;v=0;--e)w(e,0);for(var r=[],e=0;e0){",Ww(i[e]),"=1;");t(e-1,r|1<0;--r)e+=uM[r]/(t+r);var n=t+lM+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}(oM=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(cM(e));e-=1;for(var r=sM[0],n=1;n<9;n++)r+=sM[n]/(e+n);var i=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(i,e+.5)*Math.exp(-i)*r}).log=cM;var hM=function(t){var e=t.length;if(e0;--i)n=o[i],r=a[i],a[i]=a[n],a[n]=r,o[i]=o[r],o[r]=n,s=(s+r)*i;return tv.freeUint32(o),tv.freeUint32(a),s},pM.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,i,a,o=1;for((r=r||new Array(t))[0]=0,a=1;a0;--a)e=e-(n=e/o|0)*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r};var gM=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(oM(t+1)),r=[],n=0;n= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"}),mM=function(t,e){var r=[];return e=+e||0,vM(t.hi(t.shape[0]-1),r,e),r};var yM=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=mM(t,e),n=r.length,i=new Array(n),a=new Array(n),o=0;o c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],o=[],s=0;s>>7){");for(var s=0;s<1<<(1<128&&s%128==0){u.length>0&&c.push("}}");var h="vExtra"+u.length;n.push("case ",s>>>7,":",h,"(m&0x7f,",o.join(),");break;"),c=["function ",h,"(m,",o.join(),"){switch(m){"],u.push(c)}c.push("case ",127&s,":");for(var f=new Array(r),d=new Array(r),p=new Array(r),g=new Array(r),v=0,m=0;mm)&&!(s&1<0&&(M="+"+p[y]+"*c");var A=f[y].length/v*.5,T=.5+g[y]/v*.5;w.push("d"+y+"-"+T+"-"+A+"*("+f[y].join("+")+M+")/("+d[y].join("+")+")")}c.push("a.push([",w.join(),"]);","break;")}n.push("}},"),u.length>0&&c.push("}}");for(var k=[],s=0;s<1<8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height=0;--p){var g=u[d[p]];o.push(l*g[0],-l*g[1],t)}}for(var l=[0,0,0],u=[0,0,0],c=[0,0,0],h=[0,0,0],f=0;f<3;++f){c[f]=o.length/3|0,s(.5*(t[0][f]+t[1][f]),e[f],r),h[f]=(o.length/3|0)-c[f],l[f]=o.length/3|0;for(var d=0;d=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;o<0?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u|=0);var c=""+l;if(o<0&&(c="-"+c),i){for(var h=""+u;h.length=t[0][n];--a)i.push({x:a*e[n],text:LM(e[n],a)});r.push(i)}return r},EM.equal=function(t,e){for(var r=0;r<3;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n0?(d[c]=-1,p[c]=0):(d[c]=0,p[c]=1)}}var zM=[0,0,0],FM={model:SM,view:SM,projection:SM};OM.isOpaque=function(){return!0},OM.isTransparent=function(){return!1},OM.drawTransparent=function(t){};var jM=[0,0,0],BM=[0,0,0],UM=[0,0,0];OM.draw=function(t){t=t||FM;for(var e=this.gl,r=t.model||SM,n=t.view||SM,i=t.projection||SM,a=this.bounds,o=ry(r,n,i,a),s=o.cubeEdges,l=o.axis,u=n[12],c=n[13],h=n[14],f=n[15],d=this.pixelRatio*(i[3]*u+i[7]*c+i[11]*h+i[15]*f)/e.drawingBufferHeight,p=0;p<3;++p)this.lastCubeProps.cubeEdges[p]=s[p],this.lastCubeProps.axis[p]=l[p];var g=NM;for(p=0;p<3;++p)DM(NM[p],p,this.bounds,s,l);e=this.gl;var v=zM;for(p=0;p<3;++p)this.backgroundEnable[p]?v[p]=l[p]:v[p]=0;this._background.draw(r,n,i,a,v,this.backgroundColor),this._lines.bind(r,n,i,this);for(p=0;p<3;++p){var m=[0,0,0];l[p]>0?m[p]=a[1][p]:m[p]=a[0][p];for(var y=0;y<2;++y){var b=(p+1+y)%3,x=(p+1+(1^y))%3;this.gridEnable[b]&&this._lines.drawGrid(b,x,this.bounds,m,this.gridColor[b],this.gridWidth[b]*this.pixelRatio)}for(y=0;y<2;++y){b=(p+1+y)%3,x=(p+1+(1^y))%3;this.zeroEnable[x]&&a[0][x]<=0&&a[1][x]>=0&&this._lines.drawZero(b,x,this.bounds,m,this.zeroLineColor[x],this.zeroLineWidth[x]*this.pixelRatio)}}for(p=0;p<3;++p){this.lineEnable[p]&&this._lines.drawAxisLine(p,this.bounds,g[p].primalOffset,this.lineColor[p],this.lineWidth[p]*this.pixelRatio),this.lineMirror[p]&&this._lines.drawAxisLine(p,this.bounds,g[p].mirrorOffset,this.lineColor[p],this.lineWidth[p]*this.pixelRatio);var _=PM(jM,g[p].primalMinor),w=PM(BM,g[p].mirrorMinor),M=this.lineTickLength;for(y=0;y<3;++y){var A=d/r[5*y];_[y]*=M[y]*A,w[y]*=M[y]*A}this.lineTickEnable[p]&&this._lines.drawAxisTicks(p,g[p].primalOffset,_,this.lineTickColor[p],this.lineTickWidth[p]*this.pixelRatio),this.lineTickMirror[p]&&this._lines.drawAxisTicks(p,g[p].mirrorOffset,w,this.lineTickColor[p],this.lineTickWidth[p]*this.pixelRatio)}this._lines.unbind(),this._text.bind(r,n,i,this.pixelRatio);for(p=0;p<3;++p){var T=g[p].primalMinor,k=PM(UM,g[p].primalOffset);for(y=0;y<3;++y)this.lineTickEnable[p]&&(k[y]+=d*T[y]*Math.max(this.lineTickLength[y],0)/r[5*y]);if(this.tickEnable[p]){for(y=0;y<3;++y)k[y]+=d*T[y]*this.tickPad[y]/r[5*y];this._text.drawTicks(p,this.tickSize[p],this.tickAngle[p],k,this.tickColor[p])}if(this.labelEnable[p]){for(y=0;y<3;++y)k[y]+=d*T[y]*this.labelPad[y]/r[5*y];k[p]+=.5*(a[0][p]+a[1][p]),this._text.drawLabel(p,this.labelSize[p],this.labelAngle[p],k,this.labelColor[p])}}this._text.unbind()},OM.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null};var VM=function(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]};var HM=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t};var qM=function(t,e,r,n,i){var a=e.model||GM,o=e.view||GM,s=e.projection||GM,l=t.bounds,u=(i=i||ry(a,o,s,l)).axis;i.edges;Id(XM,o,a),Id(XM,s,XM);for(var c=KM,h=0;h<3;++h)c[h].lo=1/0,c[h].hi=-1/0,c[h].pixelsPerDataUnit=1/0;var f=VM(Md(XM,XM));Md(XM,XM);for(var d=0;d<3;++d){var p=(d+1)%3,g=(d+2)%3,v=$M;t:for(var h=0;h<2;++h){var m=[];if(u[d]<0!=!!h){v[d]=l[h][d];for(var y=0;y<2;++y){v[p]=l[y^h][p];for(var b=0;b<2;++b)v[g]=l[b^y^h][g],m.push(v.slice())}for(var y=0;yi||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var a=lA(n,e.stride.slice()),o=0;"float32"===r?o=t.FLOAT:"float64"===r?(o=t.FLOAT,a=!1,r="float32"):"uint8"===r?o=t.UNSIGNED_BYTE:(o=t.UNSIGNED_BYTE,a=!1,r="uint8");var s,l,u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=eg(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}o!==t.FLOAT||t.getExtension("OES_texture_float")||(o=t.UNSIGNED_BYTE,a=!1);var c=e.size;if(a)s=0===e.offset&&e.data.length===c?e.data:e.data.subarray(e.offset,e.offset+c);else{var h=[n[2],n[2]*n[0],1];l=tv.malloc(c,r);var f=eg(l,n,h,0);"float32"!==r&&"float64"!==r||o!==t.UNSIGNED_BYTE?zp.assign(f,e):iA(f,e),s=l.subarray(0,c)}var d=uA(t);t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,o,s),a||tv.free(l);return new oA(t,d,n[0],n[1],u,o)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")},tA=null,eA=null,rA=null;function nA(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var iA=function(t,e){zp.muls(t,e,255)};function aA(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function oA(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}var sA=oA.prototype;function lA(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function uA(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function cA(t,e,r,n,i){var a=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=uA(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new oA(t,o,e,r,n,i)}Object.defineProperties(sA,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&tA.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),eA.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&tA.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),eA.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),rA.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),rA.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(rA.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return aA(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return aA(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,aA(this,this._shape[0],t),t}}}),sA.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},sA.dispose=function(){this.gl.deleteTexture(this.handle)},sA.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},sA.setPixels=function(t,e,r,n){var i=this.gl;this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0;var a=nA(t)?t:t.raw;if(a){this._mipLevels.indexOf(n)<0?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,a),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,a)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,n,i,a,o,s){var l=s.dtype,u=s.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var c=0,h=0,f=lA(u,s.stride.slice());"float32"===l?c=t.FLOAT:"float64"===l?(c=t.FLOAT,f=!1,l="float32"):"uint8"===l?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,f=!1,l="uint8");if(2===u.length)h=t.LUMINANCE,u=[u[0],u[1],1],s=eg(s.data,u,[s.stride[0],s.stride[1],1],s.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])h=t.ALPHA;else if(2===u[2])h=t.LUMINANCE_ALPHA;else if(3===u[2])h=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}u[2]}h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i);if(h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var d=s.size,p=o.indexOf(n)<0;p&&o.push(n);if(c===a&&f)0===s.offset&&s.data.length===d?p?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data):p?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data.subarray(s.offset,s.offset+d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data.subarray(s.offset,s.offset+d));else{var g;g=a===t.FLOAT?tv.mallocFloat32(d):tv.mallocUint8(d);var v=eg(g,u,[u[2],u[2]*u[0],1]);c===t.FLOAT&&a===t.UNSIGNED_BYTE?iA(v,s):zp.assign(v,s),p?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,g.subarray(0,d)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,g.subarray(0,d)),a===t.FLOAT?tv.freeFloat32(g):tv.freeUint8(g)}}(i,e,r,n,this.format,this.type,this._mipLevels,t)}};var hA,fA,dA,pA,gA=function(t,e,r,n){hA||(hA=t.FRAMEBUFFER_UNSUPPORTED,fA=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,dA=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,pA=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var i=t.getExtension("WEBGL_draw_buffers");!vA&&i&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);vA=new Array(r+1);for(var n=0;n<=r;++n){for(var i=new Array(r),a=0;aa||r<0||r>a)throw new Error("gl-fbo: Parameters are too large for FBO");var o=1;if("color"in(n=n||{})){if((o=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(o>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(o>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+o+" draw buffers")}}var s=t.UNSIGNED_BYTE,l=t.getExtension("OES_texture_float");if(n.float&&o>0){if(!l)throw new Error("gl-fbo: Context does not support floating point textures");s=t.FLOAT}else n.preferFloat&&o>0&&l&&(s=t.FLOAT);var u=!0;"depth"in n&&(u=!!n.depth);var c=!1;"stencil"in n&&(c=!!n.stencil);return new wA(t,e,r,s,o,u,c,i)},vA=null;function mA(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function yA(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function bA(t){switch(t){case hA:throw new Error("gl-fbo: Framebuffer unsupported");case fA:throw new Error("gl-fbo: Framebuffer incomplete attachment");case dA:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case pA:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function xA(t,e,r,n,i,a){if(!n)return null;var o=JM(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function _A(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function wA(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var l=0;l1&&s.drawBuffersWEBGL(vA[o]);var f=r.getExtension("WEBGL_depth_texture");f?l?t.depth=xA(r,i,a,f.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u&&(t.depth=xA(r,i,a,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):u&&l?t._depth_rb=_A(r,i,a,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u?t._depth_rb=_A(r,i,a,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):l&&(t._depth_rb=_A(r,i,a,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var d=r.checkFramebufferStatus(r.FRAMEBUFFER);if(d!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),h=0;hi||r<0||r>i)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var a=mA(n),o=0;othis.buffer.length){tv.free(this.buffer);for(var n=this.buffer=tv.mallocUint8(PA(r*e*4)),i=0;i0&&0===v[e-1];)v.pop(),m.pop().dispose()}window.addEventListener("resize",k),A.update=function(t){e||(t=t||{},y=!0,b=!0)},A.add=function(t){e||(t.axes=h,p.push(t),g.push(-1),y=!0,b=!0,E())},A.remove=function(t){if(!e){var r=p.indexOf(t);r<0||(p.splice(r,1),g.pop(),y=!0,b=!0,E())}},A.dispose=function(){if(!e&&(e=!0,window.removeEventListener("resize",k),r.removeEventListener("webglcontextlost",S),A.mouseListener.enabled=!1,!A.contextLost)){h.dispose(),d.dispose();for(var t=0;to.distance)continue;for(var h=0;h0){r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function YA(t){return"boolean"!=typeof t||t}var ZA=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,i=e;try{var a=[t];0===t.indexOf("webgl")&&a.push("experimental-"+t);for(var o=0;or?r:t:te?e:t};var tT={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]},eT=function(){for(var t=0;t10&&/[0-9](?:\s|\/)/.test(r)&&(a=r.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),i=r.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof r)i="rgb",a=[r>>>16,(65280&r)>>>8,255&r];else if(nT(r)){var h=eT(r.r,r.red,r.R,null);null!==h?(i="rgb",a=[h,eT(r.g,r.green,r.G),eT(r.b,r.blue,r.B)]):(i="hsl",a=[eT(r.h,r.hue,r.H),eT(r.s,r.saturation,r.S),eT(r.l,r.lightness,r.L,r.b,r.brightness)]),o=eT(r.a,r.alpha,r.opacity,1),null!=r.opacity&&(o/=100)}else(Array.isArray(r)||t.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(r))&&(a=[r[0],r[1],r[2]],i="rgb",o=4===r.length?r[3]:1);return{space:i,values:a,alpha:o}};var e={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var aT=function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[a=255*l,a,a];e=2*l-(r=l<.5?l*(1+s):l+s-l*s),i=[0,0,0];for(var u=0;u<3;u++)(n=o+1/3*-(u-1))<0?n++:n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[u]=255*a;return i},oT=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=function(t){switch(t){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}}(e),n=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(n.set(t),n);var i="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:255,i&&(n[0]/=255,n[1]/=255,n[2]/=255,n[3]/=255),n):(t.length&&"string"!=typeof t||((t=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=iT(t);return r.space?((e=Array(3))[0]=JA(r.values[0],0,255),e[1]=JA(r.values[1],0,255),e[2]=JA(r.values[2],0,255),"h"===r.space[0]&&(e=aT(e)),e.push(JA(r.alpha,0,1)),e):[]}(t))[0]/=255,t[1]/=255,t[2]/=255),i?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:1):(n[0]=JA(Math.round(255*t[0]),0,255),n[1]=JA(Math.round(255*t[1]),0,255),n[2]=JA(Math.round(255*t[2]),0,255),n[3]=null==t[3]?255:JA(Math.floor(255*t[3]),0,255)),n)};var sT=function(t){return t?oT(t):[0,0,0,1]},lT=function(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]);"zoomMin"in e&&(r[0]=e.zoomMin);"zoomMax"in e&&(r[1]=e.zoomMax);var n=mp({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0,o=t.clientWidth,s=t.clientHeight,l={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=Cp(),r=this.delay,l=e-2*r;n.idle(e-r),n.recalcMatrix(l),n.flush(e-(100+2*r));for(var u=!0,c=n.computedMatrix,h=0;h<16;++h)u=u&&i[h]===c[h],i[h]=c[h];var f=t.clientWidth===o&&t.clientHeight===s;return o=t.clientWidth,s=t.clientHeight,u?!f:(a=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(l,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),i=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var a=Cp();n._active.lookAt(a,r,i,e),n._active.lookAt(a+500,r,i,[0,0,1]),n._active.flush(a)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return a},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var u=0,c=0,h={shift:!1,control:!1,alt:!1,meta:!1};function f(e,r,i,o){var s=l.keyBindingMode;if(!1!==s){var f="rotate"===s,d="pan"===s,p="zoom"===s,g=!!o.control,v=!!o.alt,m=!!o.shift,y=!!(1&e),b=!!(2&e),x=!!(4&e),_=1/t.clientHeight,w=_*(r-u),M=_*(i-c),A=l.flipX?1:-1,T=l.flipY?1:-1,k=Cp(),E=Math.PI*l.rotateSpeed;if((f&&y&&!g&&!v&&!m||y&&!g&&!v&&m)&&n.rotate(k,A*E*w,-T*E*M,0),(d&&y&&!g&&!v&&!m||b||y&&g&&!v&&!m)&&n.pan(k,-l.translateSpeed*w*a,l.translateSpeed*M*a,0),p&&y&&!g&&!v&&!m||x||y&&!g&&v&&!m){var L=-l.zoomSpeed*M/window.innerHeight*(k-n.lastT())*100;n.pan(k,0,0,a*(Math.exp(L)-1))}return u=r,c=i,h=o,!0}}return l.mouseListener=wp(t,f),t.addEventListener("touchstart",function(e){var r=qe(e.changedTouches[0],t);f(0,r[0],r[1],h),f(1,r[0],r[1],h),e.preventDefault()},!!Ve&&{passive:!1}),t.addEventListener("touchmove",function(e){var r=qe(e.changedTouches[0],t);f(1,r[0],r[1],h),e.preventDefault()},!!Ve&&{passive:!1}),t.addEventListener("touchend",function(t){f(0,u,c,h),t.preventDefault()},!!Ve&&{passive:!1}),l.wheelListener=Lp(t,function(t,e){if(!1!==l.keyBindingMode){var r=l.flipX?1:-1,i=l.flipY?1:-1,o=Cp();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*l.rotateSpeed/window.innerWidth);else{var s=-l.zoomSpeed*i*e/window.innerHeight*(o-n.lastT())/20;n.pan(o,0,0,a*(Math.exp(s)-1))}}},!0),l};var uT=function(t){return t.split("").map(function(t){return t in cT?cT[t]:""}).join("")},cT={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"};var hT=function(t){return""+function(t){for(var e=zr.entityToUnicode,r=0;(r=t.indexOf("&",r))>=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))},fT=["xaxis","yaxis","zaxis"];function dT(){this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.tickEnable=[!0,!0,!0],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=[!0,!0,!0],this.labelFont=["Open Sans","Open Sans","Open Sans"],this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[30,30,30],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],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=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!0,!0,!0],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._defaultTickPad=this.tickPad.slice(),this._defaultLabelPad=this.labelPad.slice(),this._defaultLineTickLength=this.lineTickLength.slice()}dT.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[fT[e]];r.visible?(this.labels[e]=hT(r.title),"titlefont"in r&&(r.titlefont.color&&(this.labelColor[e]=sT(r.titlefont.color)),r.titlefont.family&&(this.labelFont[e]=r.titlefont.family),r.titlefont.size&&(this.labelSize[e]=r.titlefont.size)),"showline"in r&&(this.lineEnable[e]=r.showline),"linecolor"in r&&(this.lineColor[e]=sT(r.linecolor)),"linewidth"in r&&(this.lineWidth[e]=r.linewidth),"showgrid"in r&&(this.gridEnable[e]=r.showgrid),"gridcolor"in r&&(this.gridColor[e]=sT(r.gridcolor)),"gridwidth"in r&&(this.gridWidth[e]=r.gridwidth),"log"===r.type?this.zeroEnable[e]=!1:"zeroline"in r&&(this.zeroEnable[e]=r.zeroline),"zerolinecolor"in r&&(this.zeroLineColor[e]=sT(r.zerolinecolor)),"zerolinewidth"in r&&(this.zeroLineWidth[e]=r.zerolinewidth),"ticks"in r&&r.ticks?this.lineTickEnable[e]=!0:this.lineTickEnable[e]=!1,"ticklen"in r&&(this.lineTickLength[e]=this._defaultLineTickLength[e]=r.ticklen),"tickcolor"in r&&(this.lineTickColor[e]=sT(r.tickcolor)),"tickwidth"in r&&(this.lineTickWidth[e]=r.tickwidth),"tickangle"in r&&(this.tickAngle[e]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180),"showticklabels"in r&&(this.tickEnable[e]=r.showticklabels),"tickfont"in r&&(r.tickfont.color&&(this.tickColor[e]=sT(r.tickfont.color)),r.tickfont.family&&(this.tickFont[e]=r.tickfont.family),r.tickfont.size&&(this.tickSize[e]=r.tickfont.size)),"mirror"in r?-1!==["ticks","all","allticks"].indexOf(r.mirror)?(this.lineTickMirror[e]=!0,this.lineMirror[e]=!0):!0===r.mirror?(this.lineTickMirror[e]=!1,this.lineMirror[e]=!0):(this.lineTickMirror[e]=!1,this.lineMirror[e]=!1):this.lineMirror[e]=!1,"showbackground"in r&&!1!==r.showbackground?(this.backgroundEnable[e]=!0,this.backgroundColor[e]=sT(r.backgroundcolor)):this.backgroundEnable[e]=!1):(this.tickEnable[e]=!1,this.labelEnable[e]=!1,this.lineEnable[e]=!1,this.lineTickEnable[e]=!1,this.gridEnable[e]=!1,this.zeroEnable[e]=!1,this.backgroundEnable[e]=!1)}};var pT=function(t){var e=new dT;return e.merge(t),e},gT=["xaxis","yaxis","zaxis"];function vT(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}vT.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[gT[e]];r.visible?(this.enabled[e]=r.showspikes,this.colors[e]=sT(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness):(this.enabled[e]=!1,this.drawSides[e]=!1)}};var mT,yT,bT=function(t){var e=new vT;return e.merge(t),e},xT=function(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,n=t.fullSceneLayout,i=[[],[],[]],a=0;a<3;++a){var o=n[_T[a]];if(o._length=(r[a].hi-r[a].lo)*r[a].pixelsPerDataUnit/t.dataScale[a],Math.abs(o._length)===1/0)i[a]=[];else{o._input_range=o.range.slice(),o.range[0]=r[a].lo/t.dataScale[a],o.range[1]=r[a].hi/t.dataScale[a],o._m=1/(t.dataScale[a]*r[a].pixelsPerDataUnit),o.range[0]===o.range[1]&&(o.range[0]-=1,o.range[1]+=1);var s=o.tickmode;if("auto"===o.tickmode){o.tickmode="linear";var l=o.nticks||re.constrain(o._length/40,4,9);ea.autoTicks(o,Math.abs(o.range[1]-o.range[0])/l)}for(var u=ea.calcTicks(o),c=0;ch[1][o]?f[o]=1:h[1][o]===h[0][o]?f[o]=1:f[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=f,this.convertAnnotations(this),a=0;ap[1][a])p[0][a]=-1,p[1][a]=1;else{var M=p[1][a]-p[0][a];p[0][a]-=M/32,p[1][a]+=M/32}}else{var A=s.range;p[0][a]=s.r2l(A[0]),p[1][a]=s.r2l(A[1])}p[0][a]===p[1][a]&&(p[0][a]-=1,p[1][a]+=1),g[a]=p[1][a]-p[0][a],this.glplot.bounds[0][a]=p[0][a]*f[a],this.glplot.bounds[1][a]=p[1][a]*f[a]}var T=[1,1,1];for(a=0;a<3;++a){var k=v[l=(s=u[kT[a]]).type];T[a]=Math.pow(k.acc,1/k.count)/f[a]}var E;if("auto"===u.aspectmode)E=Math.max.apply(null,T)/Math.min.apply(null,T)<=4?T:[1,1,1];else if("cube"===u.aspectmode)E=[1,1,1];else if("data"===u.aspectmode)E=T;else{if("manual"!==u.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var L=u.aspectratio;E=[L.x,L.y,L.z]}u.aspectratio.x=c.aspectratio.x=E[0],u.aspectratio.y=c.aspectratio.y=E[1],u.aspectratio.z=c.aspectratio.z=E[2],this.glplot.aspect=E;var C=u.domain||null,S=e._size||null;if(C&&S){var P=this.container.style;P.position="absolute",P.left=S.l+C.x[0]*S.w+"px",P.top=S.t+(1-C.y[1])*S.h+"px",P.width=S.w*(C.x[1]-C.x[0])+"px",P.height=S.h*(C.y[1]-C.y[0])+"px"}this.glplot.redraw()}},TT.destroy=function(){this.glplot&&(this.camera.mouseListener.enabled=!1,this.container.removeEventListener("wheel",this.camera.wheelListener),this.camera=this.glplot.camera=null,this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null)},TT.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),CT(this.glplot.camera)},TT.setCamera=function(t){var e;this.glplot.camera.lookAt.apply(this,[[(e=t).eye.x,e.eye.y,e.eye.z],[e.center.x,e.center.y,e.center.z],[e.up.x,e.up.y,e.up.z]])},TT.saveCamera=function(t){var e=this.getCamera(),r=re.nestedProperty(t,this.id+".camera"),n=r.get(),i=!1;function a(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}if(void 0===n)i=!0;else for(var o=0;o<3;o++)for(var s=0;s<3;s++)if(!a(e,n,o,s)){i=!0;break}return i&&r.set(e),i},TT.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},TT.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(mT),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;a1;!function(t,e,r,n){var i,a,o=n.type,s=n.attributes,l=n.handleDefaults,u=n.partition||"x",c=e._subplots[o],h=c.length;function f(t,e){return re.coerce(i,a,s,t,e)}for(var d=0;d=0;--i){var a=r,o=t[i],s=(r=a+o)-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;i>1;return["sum(",t(e.slice(0,r)),",",t(e.slice(r)),")"].join("")}(e);var n}function XT(t){return new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",GT(function(t){for(var e=new Array(t),r=0;r0&&r.push(","),r.push("[");for(var a=0;a0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(t<6?VT[t]:VT)}var KT=[function(){return[0]},function(t,e){return[[e[0]],[t[0][0]]]}];function $T(t,e){for(var r=0,n=t.length,i=0;i0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=Hm[t+1];return i||(i=Hm),n(i)}(t)),this.orient=i}var ck=uk.prototype;ck.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){(t=o.pop()).vertices;for(var s=t.adjacent,l=0;l<=r;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,h=0;h<=r;++h){var f=c[h];i[h]=f<0?e:a[f]}var d=this.orient();if(d>0)return u;u.lastVisited=-n,0===d&&o.push(u)}}}return null},ck.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;c<=n;++c)a[c]=i[l[c]];s.lastVisited=r;for(c=0;c<=n;++c){var h=u[c];if(!(h.lastVisited>=r)){var f=a[c];a[c]=t;var d=this.orient();if(a[c]=f,d<0){s=h;continue t}h.boundary?h.lastVisited=-r:h.lastVisited=r}}return}return s},ck.addPeaks=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=this.interior,s=this.simplices,l=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,o.push(e);for(var u=[];l.length>0;){var c=(e=l.pop()).vertices,h=e.adjacent,f=c.indexOf(r);if(!(f<0))for(var d=0;d<=n;++d)if(d!==f){var p=h[d];if(p.boundary&&!(p.lastVisited>=r)){var g=p.vertices;if(p.lastVisited!==-r){for(var v=0,m=0;m<=n;++m)g[m]<0?(v=m,a[m]=t):a[m]=i[g[m]];if(this.orient()>0){g[v]=r,p.boundary=!1,o.push(p),l.push(p),p.lastVisited=r;continue}p.lastVisited=-r}var y=p.adjacent,b=c.slice(),x=h.slice(),_=new ak(b,x,!0);s.push(_);var w=y.indexOf(e);if(!(w<0)){y[w]=_,x[f]=p,b[d]=-1,x[d]=e,h[d]=_,_.flip();for(m=0;m<=n;++m){var M=b[m];if(!(M<0||M===r)){for(var A=new Array(n-1),T=0,k=0;k<=n;++k){var E=b[k];E<0||k===m||(A[T++]=E)}u.push(new ok(A,_,m))}}}}}}u.sort(sk);for(d=0;d+1=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var h=o[0];o[0]=o[1],o[1]=h}e.push(o)}}return e};var hk=function(t,e){var r=t.length;if(0===r)return[];var n=t[0].length;if(n<1)return[];if(1===n)return function(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;a=2)return!1;t[r]=i}return!0}):m.filter(function(t){for(var e=0;e<=n;++e){var r=d[t[e]];if(r<0)return!1;t[e]=r}return!0});if(1&n)for(var o=0;o0){var o=t[r-1];if(0===mk(i,o)&&vk(o)!==a){r-=1;continue}}t[r++]=i}}return t.length=r,t};var wk=function(t){return _k(gk(t))};var Mk=function(t,e){return wk(pk(t,e))};var Ak=function(t){for(var e=0,r=0,n=1;nt[r][0]&&(r=n);return er?[[r],[e]]:[[e]]};var Tk=function(t){var e=t.length;if(e<3){for(var r=new Array(e),n=0;n1&&kk(t[a[u-2]],t[a[u-1]],l)<=0;)u-=1,a.pop();for(a.push(s),u=o.length;u>1&&kk(t[o[u-2]],t[o[u-1]],l)>=0;)u-=1,o.pop();o.push(s)}for(var r=new Array(o.length+a.length-2),c=0,n=0,h=a.length;n0;--f)r[c++]=o[f];return r},kk=Hm[3];var Ek=function(t){var e=Tk(t),r=e.length;if(r<=2)return[];for(var n=new Array(r),i=e[r-1],a=0;a=e[l]&&(s+=1);a[o]=s}}return t}(i,r)}};var Pk=function(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;if(0===r)return[];if(1===r)return Ak(t);if(2===r)return Ek(t);return Sk(t,r)};var Rk={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:1,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13,rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]};var Ok=function(t,e,r){return t*(1-r)+e*r},Ik=function(t){var e,r,n,i,a,o,s,l,u,c;t||(t={});l=(t.nshades||72)-1,s=t.format||"hex",(o=t.colormap)||(o="jet");if("string"==typeof o){if(o=o.toLowerCase(),!Rk[o])throw Error(o+" not a supported colorscale");a=Rk[o]}else{if(!Array.isArray(o))throw Error("unsupported colormap option",o);a=o.slice()}if(a.length>l)throw new Error(o+" map requires nshades to be at least size "+a.length);u=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:t.alpha.slice():"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1];e=a.map(function(t){return Math.round(t.index*l)}),u[0]=Math.min(Math.max(u[0],0),1),u[1]=Math.min(Math.max(u[1],0),1);var h=a.map(function(t,e){var r=a[e].index,n=a[e].rgb.slice();return 4===n.length&&n[3]>=0&&n[3]<=1?n:(n[3]=u[0]+(u[1]-u[0])*r,n)}),f=[];for(c=0;c=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h):(_=0,c>=0?(w=0,g=h):-c>=l?(w=1,g=l+2*c+h):g=c*(w=-c/l)+h);else if(w<0)w=0,u>=0?(_=0,g=h):-u>=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h;else{var M=1/x;g=(_*=M)*(o*_+s*(w*=M)+2*u)+w*(s*_+l*w+2*c)+h}else _<0?(m=l+c)>(v=s+u)?(y=m-v)>=(b=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/b)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h:(_=0,m<=0?(w=1,g=l+2*c+h):c>=0?(w=0,g=h):g=c*(w=-c/l)+h):w<0?(m=o+u)>(v=s+c)?(y=m-v)>=(b=o-2*s+l)?(w=1,_=0,g=l+2*c+h):g=(_=1-(w=y/b))*(o*_+s*w+2*u)+w*(s*_+l*w+2*c)+h:(w=0,m<=0?(_=1,g=o+2*u+h):u>=0?(_=0,g=h):g=u*(_=-u/o)+h):(y=l+c-s-u)<=0?(_=0,w=1,g=l+2*c+h):y>=(b=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/b)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h;var A=1-_-w;for(a=0;a1.0001)return null;d+=f[s]}if(Math.abs(d-1)>.001)return null;return[l,function(t,e){for(var r=[0,0,0],n=0;n 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),tE=Tm(["precision mediump 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}"]),eE=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]),rE=Tm(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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}"]),nE=Tm(["precision mediump 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}"]),iE=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]);Wk.meshShader={vertex:Yk,fragment:Zk,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},Wk.wireShader={vertex:Qk,fragment:Kk,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},Wk.pointShader={vertex:$k,fragment:Jk,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},Wk.pickShader={vertex:tE,fragment:eE,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},Wk.pointPickShader={vertex:rE,fragment:eE,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},Wk.contourShader={vertex:nE,fragment:iE,attributes:[{name:"position",type:"vec3"}]};var aE={};aE.vertexNormals=function(t,e,r){for(var n=e.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa){var x=i[u],_=1/Math.sqrt(v*y);for(b=0;b<3;++b){var w=(b+1)%3,M=(b+2)%3;x[b]+=_*(m[w]*g[M]-m[M]*g[w])}}}for(o=0;oa)for(_=1/Math.sqrt(A),b=0;b<3;++b)x[b]*=_;else for(b=0;b<3;++b)x[b]=0}return i},aE.faceNormals=function(t,e,r){for(var n=t.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa?1/Math.sqrt(d):0;for(u=0;u<3;++u)f[u]*=d;i[o]=f}return i};var oE=32;function sE(t){switch(t){case"uint8":return[tv.mallocUint8,tv.freeUint8];case"uint16":return[tv.mallocUint16,tv.freeUint16];case"uint32":return[tv.mallocUint32,tv.freeUint32];case"int8":return[tv.mallocInt8,tv.freeInt8];case"int16":return[tv.mallocInt16,tv.freeInt16];case"int32":return[tv.mallocInt32,tv.freeInt32];case"float32":return[tv.mallocFloat,tv.freeFloat];case"float64":return[tv.mallocDouble,tv.freeDouble];default:return null}}function lE(t){for(var e=[],r=0;r0?i.push(["d",h,"=s",h,"-d",l,"*n",l].join("")):i.push(["d",h,"=s",h].join("")),l=h),0!=(c=t.length-1-a)&&(u>0?i.push(["e",c,"=s",c,"-e",u,"*n",u,",f",c,"=",o[c],"-f",u,"*n",u].join("")):i.push(["e",c,"=s",c,",f",c,"=",o[c]].join("")),u=c)}r.push("var "+i.join(","));var f=["0","n0-1","data","offset"].concat(lE(t.length));r.push(["if(n0<=",oE,"){","insertionSort(",f.join(","),")}else{","quickSort(",f.join(","),")}"].join("")),r.push("}return "+n);var d=new Function("insertionSort","quickSort",r.join("\n")),p=function(t,e){var r=["'use strict'"],n=["ndarrayInsertionSort",t.join("d"),e].join(""),i=["left","right","data","offset"].concat(lE(t.length)),a=sE(e),o=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var s=[],l=1;l1){for(r.push("dptr=0;sptr=ptr"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"b){break __l}"].join("")),l=t.length-1;l>=1;--l)r.push("sptr+=e"+l,"dptr+=f"+l,"}");for(r.push("dptr=cptr;sptr=cptr-s0"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"scratch)){",c("cptr",u("cptr-s0")),"cptr-=s0","}",c("cptr","scratch"));return r.push("}"),t.length>1&&a&&r.push("free(scratch)"),r.push("} return "+n),a?new Function("malloc","free",r.join("\n"))(a[0],a[1]):new Function(r.join("\n"))()}(t,e);return d(p,function(t,e,r){var n=["'use strict'"],i=["ndarrayQuickSort",t.join("d"),e].join(""),a=["left","right","data","offset"].concat(lE(t.length)),o=sE(e),s=0;n.push(["function ",i,"(",a.join(","),"){"].join(""));var l=["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","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var u=[],c=1;c=0;--a)0!==(o=t[a])&&n.push(["for(i",o,"=0;i",o,"1)for(a=0;a1?n.push("ptr_shift+=d"+o):n.push("ptr0+=d"+o),n.push("}"))}}function g(e,r,i,a){if(1===r.length)n.push("ptr0="+h(r[0]));else{for(var o=0;o1)for(o=0;o=1;--o)i&&n.push("pivot_ptr+=f"+o),r.length>1?n.push("ptr_shift+=e"+o):n.push("ptr0+=e"+o),n.push("}")}function v(){t.length>1&&o&&n.push("free(pivot1)","free(pivot2)")}function m(e,r){var i="el"+e,a="el"+r;if(t.length>1){var o="__l"+ ++s;g(o,[i,a],!1,["comp=",f("ptr0"),"-",f("ptr1"),"\n","if(comp>0){tmp0=",i,";",i,"=",a,";",a,"=tmp0;break ",o,"}\n","if(comp<0){break ",o,"}"].join(""))}else n.push(["if(",f(h(i)),">",f(h(a)),"){tmp0=",i,";",i,"=",a,";",a,"=tmp0}"].join(""))}function y(e,r){t.length>1?p([e,r],!1,d("ptr0",f("ptr1"))):n.push(d(h(e),f(h(r))))}function b(e,r,i){if(t.length>1){var a="__l"+ ++s;g(a,[r],!0,[e,"=",f("ptr0"),"-pivot",i,"[pivot_ptr]\n","if(",e,"!==0){break ",a,"}"].join(""))}else n.push([e,"=",f(h(r)),"-pivot",i].join(""))}function x(e,r){t.length>1?p([e,r],!1,["tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1","tmp")].join("")):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1","tmp")].join(""))}function _(e,r,i){t.length>1?(p([e,r,i],!1,["tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1",f("ptr2")),"\n",d("ptr2","tmp")].join("")),n.push("++"+r,"--"+i)):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","ptr2=",h(i),"\n","++",r,"\n","--",i,"\n","tmp=",f("ptr0"),"\n",d("ptr0",f("ptr1")),"\n",d("ptr1",f("ptr2")),"\n",d("ptr2","tmp")].join(""))}function w(t,e){x(t,e),n.push("--"+e)}function M(e,r,i){t.length>1?p([e,r],!0,[d("ptr0",f("ptr1")),"\n",d("ptr1",["pivot",i,"[pivot_ptr]"].join(""))].join("")):n.push(d(h(e),f(h(r))),d(h(r),"pivot"+i))}function A(e,r){n.push(["if((",r,"-",e,")<=",oE,"){\n","insertionSort(",e,",",r,",data,offset,",lE(t.length).join(","),")\n","}else{\n",i,"(",e,",",r,",data,offset,",lE(t.length).join(","),")\n","}"].join(""))}function T(e,r,i){t.length>1?(n.push(["__l",++s,":while(true){"].join("")),p([e],!0,["if(",f("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",s,"}"].join("")),n.push(i,"}")):n.push(["while(",f(h(e)),"===pivot",r,"){",i,"}"].join(""))}return n.push("var "+l.join(",")),m(1,2),m(4,5),m(1,3),m(2,3),m(1,4),m(3,4),m(2,5),m(2,3),m(4,5),t.length>1?p(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",f("ptr1"),"\n","pivot2[pivot_ptr]=",f("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",f("ptr0"),"\n","y=",f("ptr2"),"\n","z=",f("ptr4"),"\n",d("ptr5","x"),"\n",d("ptr6","y"),"\n",d("ptr7","z")].join("")):n.push(["pivot1=",f(h("el2")),"\n","pivot2=",f(h("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",f(h("el1")),"\n","y=",f(h("el3")),"\n","z=",f(h("el5")),"\n",d(h("index1"),"x"),"\n",d(h("index3"),"y"),"\n",d(h("index5"),"z")].join("")),y("index2","left"),y("index4","right"),n.push("if(pivots_are_equal){"),n.push("for(k=less;k<=great;++k){"),b("comp","k",1),n.push("if(comp===0){continue}"),n.push("if(comp<0){"),n.push("if(k!==less){"),x("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),n.push("while(true){"),b("comp","great",1),n.push("if(comp>0){"),n.push("great--"),n.push("}else if(comp<0){"),_("k","less","great"),n.push("break"),n.push("}else{"),w("k","great"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}else{"),n.push("for(k=less;k<=great;++k){"),b("comp_pivot1","k",1),n.push("if(comp_pivot1<0){"),n.push("if(k!==less){"),x("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),b("comp_pivot2","k",2),n.push("if(comp_pivot2>0){"),n.push("while(true){"),b("comp","great",2),n.push("if(comp>0){"),n.push("if(--greatindex5){"),T("less",1,"++less"),T("great",2,"--great"),n.push("for(k=less;k<=great;++k){"),b("comp_pivot1","k",1),n.push("if(comp_pivot1===0){"),n.push("if(k!==less){"),x("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),b("comp_pivot2","k",2),n.push("if(comp_pivot2===0){"),n.push("while(true){"),b("comp","great",2),n.push("if(comp===0){"),n.push("if(--great1&&o?new Function("insertionSort","malloc","free",n.join("\n"))(r,o[0],o[1]):new Function("insertionSort",n.join("\n"))(r)}(t,e,p))},cE={};var hE=function(t){var e=t.order,r=t.dtype,n=[e,r].join(":"),i=cE[n];return i||(cE[n]=i=uE(e,r)),i(t),t},fE=function(t){for(var e=1<>1,v=E[2*m+1];","if(v===b){return m}","if(b0&&o.push(","),o.push("[");for(var n=0;n0&&o.push(","),o.push("B(C,E,c[",i[0],"],c[",i[1],"])")}o.push("]")}o.push(");")}}for(var n=t+1;n>1;--n){n=1},kE.isTransparent=function(){return this.opacity<1},kE.pickSlots=1,kE.setPickBase=function(t){this.pickId=t},kE.highlight=function(t){if(t&&this.contourEnable){for(var e=mE(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=tv.mallocFloat32(6*a),s=0,l=0;l0&&((u=this.triShader).bind(),u.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind());this.edgeCount>0&&this.lineWidth>0&&((u=this.lineShader).bind(),u.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind());this.pointCount>0&&((u=this.pointShader).bind(),u.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind());this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0&&((u=this.contourShader).bind(),u.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind())},kE.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||AE,n=t.view||AE,i=t.projection||AE,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s,l={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255};((s=this.pickShader).bind(),s.uniforms=l,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0)&&((s=this.pointPickShader).bind(),s.uniforms=l,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind())},kE.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;a0)i=Mk(t.alphahull,a);else{var o=["x","y","z"].indexOf(t.delaunayaxis);i=hk(a.map(function(t){return[t[(o+1)%3],t[(o+2)%3]]}))}var l={positions:a,cells:i,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:sT(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",l.vertexIntensity=t.intensity,l.vertexIntensityBounds=[t.cmin,t.cmax],l.colormap=t.colorscale.map(function(t){var e=t[0],r=s(t[1]).toRgb();return{index:e,rgb:[r.r,r.g,r.b,1]}})):t.vertexcolor?(this.color=t.vertexcolor[0],l.vertexColors=IE(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],l.cellColors=IE(t.facecolor)):(this.color=t.color,l.meshColor=sT(t.color)),this.mesh.update(l)},OE.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()};var DE=function(t,e){var r=t.glplot.gl,n=PE({gl:r}),i=new RE(t,n,e.uid);return n._trace=i,i.update(e),t.glplot.add(n),i},zE={};zE.attributes=BT,zE.supplyDefaults=function(t,e,r,n){function i(r,n){return re.coerce(t,e,BT,r,n)}function a(t){var e=t.map(function(t){var e=i(t);return e&&re.isArrayOrTypedArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var o=a(["x","y","z"]),s=a(["i","j","k"]);o?(s&&s.forEach(function(t){for(var e=0;e=1},tL.isTransparent=function(){return this.opacity<1},tL.drawTransparent=tL.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||$E,i=r.projection=t.projection||$E;r.model=t.model||$E,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var c=0;c<3;++c)e.lineWidth(this.lineWidth[c]),r.capSize=this.capSize[c]*u,this.lineCount[c]&&e.drawArrays(e.LINES,this.lineOffset[c],this.lineCount[c]);this.vao.unbind()};var rL=function(){for(var t=new Array(3),e=0;e<3;++e){for(var r=[],n=1;n<=2;++n)for(var i=-1;i<=1;i+=2){var a=[0,0,0];a[(n+e)%3]=i,r.push(a)}t[e]=r}return t}();function nL(t,e,r,n){for(var i=rL[n],a=0;a0)(d=u.slice())[s]+=h[1][s],i.push(u[0],u[1],u[2],f[0],f[1],f[2],f[3],0,0,0,d[0],d[1],d[2],f[0],f[1],f[2],f[3],0,0,0),eL(this.bounds,d),o+=2+nL(i,d,f,s)}}this.lineCount[s]=o-this.lineOffset[s]}this.buffer.update(i)}},tL.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()};var iL={},aL=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]),oL=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]),sL=Tm(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]),lL=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];iL.createShader=function(t){return Am(t,aL,oL,null,lL)},iL.createPickShader=function(t){return Am(t,aL,sL,null,lL)};var uL=function(t,e,r,n){return cL[0]=n,cL[1]=r,cL[2]=e,cL[3]=t,hL[0]},cL=new Uint8Array(4),hL=new Float32Array(cL.buffer);var fL=function(t){var e=t.gl||t.scene&&t.scene.gl,r=dL(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=pL(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=ov(e),a=dv(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),o=eg(new Array(1024),[256,1,4]),s=0;s<1024;++s)o.data[s]=255;var l=JM(e,o);l.wrap=e.REPEAT;var u=new bL(e,r,n,i,a,l);return u.update(t),u},dL=iL.createShader,pL=iL.createPickShader,gL=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function vL(t,e){for(var r=0,n=0;n<3;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function mL(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;r<3;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function yL(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function bL(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}var xL=bL.prototype;xL.isTransparent=function(){return this.opacity<1},xL.isOpaque=function(){return this.opacity>=1},xL.pickSlots=1,xL.setPickBase=function(t){this.pickId=t},xL.drawTransparent=xL.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||gL,view:t.view||gL,projection:t.projection||gL,clipBounds:mL(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},xL.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||gL,view:t.view||gL,projection:t.projection||gL,pickId:this.pickId,clipBounds:mL(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},xL.update=function(t){var e,r;this.dirty=!0;var n=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var i=t.position||t.positions;if(i){var a=t.color||t.colors||[0,0,0,1],o=t.lineWidth||1,s=[],l=[],u=[],c=0,h=0,f=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],d=!1;t:for(e=1;e0){for(var b=0;b<24;++b)s.push(s[s.length-12]);h+=2,d=!0}continue t}f[0][r]=Math.min(f[0][r],m[r],y[r]),f[1][r]=Math.max(f[1][r],m[r],y[r])}Array.isArray(a[0])?(p=a[e-1],g=a[e]):p=g=a,3===p.length&&(p=[p[0],p[1],p[2],1]),3===g.length&&(g=[g[0],g[1],g[2],1]),v=Array.isArray(o)?o[e-1]:o;var x=c;if(c+=vL(m,y),d){for(r=0;r<2;++r)s.push(m[0],m[1],m[2],y[0],y[1],y[2],x,v,p[0],p[1],p[2],p[3]);h+=2,d=!1}s.push(m[0],m[1],m[2],y[0],y[1],y[2],x,v,p[0],p[1],p[2],p[3],m[0],m[1],m[2],y[0],y[1],y[2],x,-v,p[0],p[1],p[2],p[3],y[0],y[1],y[2],m[0],m[1],m[2],c,-v,g[0],g[1],g[2],g[3],y[0],y[1],y[2],m[0],m[1],m[2],c,v,g[0],g[1],g[2],g[3]),h+=4}if(this.buffer.update(s),l.push(c),u.push(i[i.length-1].slice()),this.bounds=f,this.vertexCount=h,this.points=u,this.arcLength=l,"dashes"in t){var _=t.dashes.slice();for(_.unshift(0),e=1;e<_.length;++e)_[e]=_[e-1]+_[e];var w=eg(new Array(1024),[256,1,4]);for(e=0;e<256;++e){for(r=0;r<4;++r)w.set(e,0,r,0);1&ud.le(_,_[_.length-1]*e/255)?w.set(e,0,0,0):w.set(e,0,0,255)}this.texture.setPixels(w)}}},xL.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},xL.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=uL(t.value[0],t.value[1],t.value[2],0),r=ud.le(this.arcLength,e);if(r<0)return null;if(r===this.arcLength.length-1)return new yL(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],a=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),o=1-a,s=[0,0,0],l=0;l<3;++l)s[l]=o*n[l]+a*i[l];var u=Math.min(a<.5?r:r+1,this.points.length-1);return new yL(e,s,u,this.points[u])};var _L=function(t,e){var r=wL[e];r||(r=wL[e]={});if(t in r)return r[t];for(var n=MM(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),i=MM(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),a=[[1/0,1/0],[-1/0,-1/0]],o=0;o=1)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var HL=[0,0],qL=[0,0,0],GL=[0,0,0],XL=[0,0,0,1],WL=[0,0,0,1],YL=zL.slice(),ZL=[0,0,0],QL=[[0,0,0],[0,0,0]];function KL(t){return t[0]=t[1]=t[2]=0,t}function $L(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function JL(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function tC(t,e,r,n,i){var a,o=e.axesProject,s=e.gl,l=t.uniforms,u=r.model||zL,c=r.view||zL,h=r.projection||zL,f=e.axesBounds,d=function(t){for(var e=QL,r=0;r<2;++r)for(var n=0;n<3;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}(e.clipBounds);a=e.axes&&e.axes.lastCubeProps?e.axes.lastCubeProps.axis:[1,1,1],HL[0]=2/s.drawingBufferWidth,HL[1]=2/s.drawingBufferHeight,t.bind(),l.view=c,l.projection=h,l.screenSize=HL,l.highlightId=e.highlightId,l.highlightScale=e.highlightScale,l.clipBounds=d,l.pickGroup=e.pickId/255,l.pixelRatio=e.pixelRatio;for(var p=0;p<3;++p)if(o[p]&&e.projectOpacity[p]<1===n){l.scale=e.projectScale[p],l.opacity=e.projectOpacity[p];for(var g=YL,v=0;v<16;++v)g[v]=0;for(v=0;v<4;++v)g[5*v]=1;g[5*p]=0,a[p]<0?g[12+p]=f[0][p]:g[12+p]=f[1][p],Id(g,u,g),l.model=g;var m=(p+1)%3,y=(p+2)%3,b=KL(qL),x=KL(GL);b[m]=1,x[y]=1;var _=BL(0,0,0,$L(XL,b)),w=BL(0,0,0,$L(WL,x));if(Math.abs(_[1])>Math.abs(w[1])){var M=_;_=w,w=M,M=b,b=x,x=M;var A=m;m=y,y=A}_[0]<0&&(b[m]=-1),w[1]>0&&(x[y]=-1);var T=0,k=0;for(v=0;v<4;++v)T+=Math.pow(u[4*m+v],2),k+=Math.pow(u[4*y+v],2);b[m]/=Math.sqrt(T),x[y]/=Math.sqrt(k),l.axes[0]=b,l.axes[1]=x,l.fragClipBounds[0]=JL(ZL,d[0],p,-1e8),l.fragClipBounds[1]=JL(ZL,d[1],p,1e8),e.vao.draw(s.TRIANGLES,e.vertexCount),e.lineWidth>0&&(s.lineWidth(e.lineWidth),e.vao.draw(s.LINES,e.lineVertexCount,e.vertexCount))}}var eC=[[-1e8,-1e8,-1e8],[1e8,1e8,1e8]];function rC(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||zL,s.view=n.view||zL,s.projection=n.projection||zL,HL[0]=2/o.drawingBufferWidth,HL[1]=2/o.drawingBufferHeight,s.screenSize=HL,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=eC,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}tC(e,r,n,i),r.vao.unbind()}VL.draw=function(t){rC(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!1,!1)},VL.drawTransparent=function(t){rC(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!0,!1)},VL.drawPick=function(t){rC(this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader,this.pickProjectShader,this,t,!1,!0)},VL.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||e<0)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;i<3;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},VL.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},VL.update=function(t){if("perspective"in(t=t||{})&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0],l=t.glyph,u=t.color,c=t.size,h=t.angle,f=t.lineColor,d=0,p=0,g=0,v=n.length;t:for(var m=0;m0&&(L[0]=-a[0]*(1+w[0][0]));var U=x.cells,V=x.positions;for(b=0;b=0&&(u[1]+=1),l.indexOf("top")>=0&&(u[1]-=1),l.indexOf("left")>=0&&(u[0]-=1),l.indexOf("right")>=0&&(u[0]+=1),u)),r.textColor=uC(e.textfont,1,_),r.textSize=vC(e.textfont.size,_,re.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var k=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;n<3;++n){var E=e.projection[k[n]];(r.project[n]=E.show)&&(r.projectOpacity[n]=E.opacity,r.projectScale[n]=E.scale)}r.errorBounds=hC(e,f);var L=function(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[0,0,0],i=0;i<3;i++){var a=t[i];a&&!1!==a.copy_zstyle&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=sT(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}([e.error_x,e.error_y,e.error_z]);return r.errorColor=L.color,r.errorLineWidth=L.lineWidth,r.errorCapSize=L.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=sT(e.surfacecolor),r}function yC(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}dC.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels?void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel=this.textLabels:t.textLabel="";var e=t.index=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},dC.update=function(t){var e,r,n,i,a=this.scene.glplot.gl,o=BE.solid;this.data=t;var s=mC(this.scene,t);"mode"in s&&(this.mode=s.mode),"lineDashes"in s&&s.lineDashes in BE&&(o=BE[s.lineDashes]),this.color=yC(s.scatterColor)||yC(s.lineColor),this.dataPoints=s.position,e={gl:a,position:s.position,color:s.lineColor,lineWidth:s.lineWidth||1,dashes:o[0],dashScale:o[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=fL(e),this.linePlot._trace=this,this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var l=t.opacity;if(t.marker&&t.marker.opacity&&(l*=t.marker.opacity),r={gl:a,position:s.position,color:s.scatterColor,size:s.scatterSize,glyph:s.scatterMarker,opacity:l,orthographic:!0,lineWidth:s.scatterLineWidth,lineColor:s.scatterLineColor,project:s.project,projectScale:s.projectScale,projectOpacity:s.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=FL(r),this.scatterPlot._trace=this,this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),i={gl:a,position:s.position,glyph:s.text,color:s.textColor,size:s.textSize,angle:s.textAngle,alignment:s.textOffset,font:s.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=t.hovertext||t.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(i):(this.textMarkers=FL(i),this.textMarkers._trace=this,this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:a,position:s.position,color:s.errorColor,error:s.errorBounds,lineWidth:s.errorLineWidth,capSize:s.errorCapSize,opacity:t.opacity},this.errorBars?s.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):s.errorBounds&&(this.errorBars=KE(n),this.errorBars._trace=this,this.scene.glplot.add(this.errorBars)),s.delaunayAxis>=0){var u=function(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;n=0&&i("surfacecolor",a||o);for(var s=["x","y","z"],l=0;l<3;++l){var u="projection."+s[l];i(u+".show")&&(i(u+".opacity"),i(u+".scale"))}var c=R.getComponentMethod("errorbars","supplyDefaults");c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}else e.visible=!1},xC.colorbar=kf,xC.calc=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return pf(r,e),vf(e),r},xC.moduleType="trace",xC.name="scatter3d",xC.basePlotModule=PT,xC.categories=["gl3d","symbols","markerColorscale","showLegend"],xC.meta={};var _C=xC,wC={},MC=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\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 worldCoordinate = vec3(uv.zw, f.x);\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"]),AC=Tm(["precision mediump 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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 \u2014 in vertex or in fragment\n vec4 surfaceColor = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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"]),TC=Tm(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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"]),kC=Tm(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]);wC.createShader=function(t){var e=Am(t,MC,AC,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},wC.createPickShader=function(t){var e=Am(t,MC,kC,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},wC.createContourShader=function(t){var e=Am(t,TC,AC,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},wC.createPickContourShader=function(t){var e=Am(t,TC,kC,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e};var EC=function(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r=Jg(e.dimension,"string"==typeof r?r:"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;n=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),a.push("1"),o.push("s["+l+"]-2"));var u=".lo("+a.join()+").hi("+o.join()+")";if(0===a.length&&(u=""),i>0){n.push("if(1");for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push("&&s[",l,"]>2");n.push("){grad",i,"(src.pick(",s.join(),")",u);for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push(",dst.pick(",s.join(),",",l,")",u);n.push(");")}for(var l=0;l1){dst.set(",s.join(),",",c,",0.5*(src.get(",f.join(),")-src.get(",d.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>1){diff(",h,",src.pick(",f.join(),")",u,",src.pick(",d.join(),")",u,");}else{zero(",h,");};");break;case"mirror":0===i?n.push("dst.set(",s.join(),",",c,",0);"):n.push("zero(",h,");");break;case"wrap":var p=s.slice(),g=s.slice();e[l]<0?(p[c]="s["+c+"]-2",g[c]="0"):(p[c]="s["+c+"]-1",g[c]="1"),0===i?n.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",p.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>2){diff(",h,",src.pick(",p.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",h,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}i>0&&n.push("};")}for(var a=0;a<1<=1)return!0;for(var t=0;t<3;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},WC.pickSlots=1,WC.setPickBase=function(t){this.pickId=t};var YC=[0,0,0],ZC={showSurface:!1,showContour:!1,projections:[VC.slice(),VC.slice(),VC.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]};function QC(t,e){var r,n,i,a=e.axes&&e.axes.lastCubeProps.axis||YC,o=e.showSurface,s=e.showContour;for(r=0;r<3;++r)for(o=o||e.surfaceProject[r],n=0;n<3;++n)s=s||e.contourProject[r][n];for(r=0;r<3;++r){var l=ZC.projections[r];for(n=0;n<16;++n)l[n]=0;for(n=0;n<4;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],Id(l,t.model,l);var u=ZC.clipBounds[r];for(i=0;i<2;++i)for(n=0;n<3;++n)u[i][n]=t.clipBounds[i][n];u[0][r]=-1e8,u[1][r]=1e8}return ZC.showSurface=o,ZC.showContour=s,ZC}var KC={model:VC,view:VC,projection:VC,inverseModel:VC.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1,vertexColor:0},$C=VC.slice(),JC=[1,0,0,0,1,0,0,0,1];function tS(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=KC;n.model=t.model||VC,n.view=t.view||VC,n.projection=t.projection||VC,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=cd(n.inverseModel,n.model);for(var i=0;i<2;++i)for(var a=n.clipBounds[i],o=0;o<3;++o)a[o]=Math.min(Math.max(this.clipBounds[i][o],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=JC,n.vertexColor=this.vertexColor;var s=$C;for(Id(s,n.view,n.model),Id(s,n.projection,s),cd(s,s),i=0;i<3;++i)n.eyePosition[i]=s[12+i]/s[15];var l=s[15];for(i=0;i<3;++i)l+=this.lightPosition[i]*s[4*i+3];for(i=0;i<3;++i){var u=s[12+i];for(o=0;o<3;++o)u+=s[4*o+i]*this.lightPosition[o];n.lightPosition[i]=u/l}var c=QC(n,this);if(c.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;i<3;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=c.projections[i],this._shader.uniforms.clipBounds=c.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(c.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var f=this._contourVAO;for(f.bind(),i=0;i<3;++i)for(h.uniforms.permutation=qC[i],r.lineWidth(this.contourWidth[i]),o=0;o>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;c<2;++c)for(var h=c?a:1-a,f=0;f<2;++f)for(var d=i+c,p=s+f,g=h*(f?l:1-l),v=0;v<3;++v)u[v]+=this._field[v].get(d,p)*g;for(var m=this._pickResult.level,y=0;y<3;++y)if(m[y]=ud.le(this.contourLevels[y],u[y]),m[y]<0)this.contourLevels[y].length>0&&(m[y]=0);else if(m[y]Math.abs(x-u[y])&&(m[y]+=1)}for(r.index[0]=a<.5?i:i+1,r.index[1]=l<.5?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],v=0;v<3;++v)r.dataCoordinate[v]=this._field[v].get(r.index[0],r.index[1]);return r},WC.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=nS(t.contourWidth,Number)),"showContour"in t&&(this.showContour=nS(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=nS(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=aS(t.contourColor)),"contourProject"in t&&(this.contourProject=nS(t.contourProject,function(t){return nS(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=aS(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=nS(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=nS(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds),"vertexColor"in t&&(this.vertexColor=t.vertexColor?1:0);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(tv.freeFloat(this._field[2].data),this._field[2].data=tv.mallocFloat(rg.nextPow2(n))),this._field[2]=eg(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),rS(this._field[2],e),this.shape=e.shape.slice();for(var i=this.shape,a=0;a<2;++a)this._field[2].size>this._field[a].data.length&&(tv.freeFloat(this._field[a].data),this._field[a].data=tv.mallocFloat(this._field[2].size)),this._field[a]=eg(this._field[a].data,[i[0]+2,i[1]+2]);if(t.coords){var o=t.coords;if(!Array.isArray(o)||3!==o.length)throw new Error("gl-surface: invalid coordinates for x/y");for(a=0;a<2;++a){var s=o[a];for(f=0;f<2;++f)if(s.shape[f]!==i[f])throw new Error("gl-surface: coords have incorrect shape");rS(this._field[a],s)}}else if(t.ticks){var l=t.ticks;if(!Array.isArray(l)||2!==l.length)throw new Error("gl-surface: invalid ticks");for(a=0;a<2;++a){var u=l[a];if((Array.isArray(u)||u.length)&&(u=eg(u)),u.shape[0]!==i[a])throw new Error("gl-surface: invalid tick length");var c=eg(u.data,i);c.stride[a]=u.stride[0],c.stride[1^a]=0,rS(this._field[a],c)}}else{for(a=0;a<2;++a){var h=[0,0];h[a]=1,this._field[a]=eg(this._field[a].data,[i[0]+2,i[1]+2],h,0)}this._field[0].set(0,0,0);for(var f=0;f0){for(var ct=0;ct<5;++ct)q.pop();O-=1}continue t}q.push(Y[0],Y[1],K[0],K[1],Y[2]),O+=1}}W.push(O)}this._contourOffsets[G]=X,this._contourCounts[G]=W}var ht=tv.mallocFloat(q.length);for(a=0;a 1) { + if(_$plot_config_196.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11589,7 +11589,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_195.logging > 0) { + if(_$plot_config_196.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11601,7 +11601,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_195.logging > 0) { + if(_$plot_config_196.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11640,7 +11640,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_172 = function noop() {}; +var _$noop_173 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11665,7 +11665,7 @@ var _$noop_172 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_176 = function pushUnique(array, item) { +var _$pushUnique_177 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11802,7 +11802,7 @@ var _$attributes_77 = { /* removed: var _$attributes_77 = require('../components/fx/attributes'); */; -var _$attributes_202 = { +var _$attributes_203 = { type: { valType: 'enumerated', @@ -12108,7 +12108,7 @@ var _$layout_attributes_236 = { } }; -var _$registry_253 = {}; +var _$registry_254 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12119,29 +12119,29 @@ var _$registry_253 = {}; 'use strict'; -/* removed: var _$loggers_168 = require('./lib/loggers'); */; -/* removed: var _$noop_172 = require('./lib/noop'); */; -/* removed: var _$pushUnique_176 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_165 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_156 = require('./lib/extend'); */; +/* removed: var _$loggers_169 = require('./lib/loggers'); */; +/* removed: var _$noop_173 = require('./lib/noop'); */; +/* removed: var _$pushUnique_177 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_166 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_157 = require('./lib/extend'); */; -/* removed: var _$attributes_202 = require('./plots/attributes'); */; +/* removed: var _$attributes_203 = require('./plots/attributes'); */; /* removed: var _$layout_attributes_236 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_156.extendFlat; -var extendDeepAll = _$extend_156.extendDeepAll; - -_$registry_253.modules = {}; -_$registry_253.allCategories = {}; -_$registry_253.allTypes = []; -_$registry_253.subplotsRegistry = {}; -_$registry_253.transformsRegistry = {}; -_$registry_253.componentsRegistry = {}; -_$registry_253.layoutArrayContainers = []; -_$registry_253.layoutArrayRegexes = []; -_$registry_253.traceLayoutAttributes = {}; -_$registry_253.localeRegistry = {}; -_$registry_253.apiMethodRegistry = {}; +var extendFlat = _$extend_157.extendFlat; +var extendDeepAll = _$extend_157.extendDeepAll; + +_$registry_254.modules = {}; +_$registry_254.allCategories = {}; +_$registry_254.allTypes = []; +_$registry_254.subplotsRegistry = {}; +_$registry_254.transformsRegistry = {}; +_$registry_254.componentsRegistry = {}; +_$registry_254.layoutArrayContainers = []; +_$registry_254.layoutArrayRegexes = []; +_$registry_254.traceLayoutAttributes = {}; +_$registry_254.localeRegistry = {}; +_$registry_254.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12182,7 +12182,7 @@ _$registry_253.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_253.register = function register(_modules) { +_$registry_254.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12211,7 +12211,7 @@ _$registry_253.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_253.apiMethodRegistry[name] = newModule.fn; + _$registry_254.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12227,8 +12227,8 @@ _$registry_253.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_253.getModule = function(trace) { - var _module = _$registry_253.modules[getTraceType(trace)]; +_$registry_254.getModule = function(trace) { + var _module = _$registry_254.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12242,20 +12242,20 @@ _$registry_253.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_253.traceIs = function(traceType, category) { +_$registry_254.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_253.modules[traceType]; + var _module = _$registry_254.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_168.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_169.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_253.modules[_$attributes_202.type.dflt]; + _module = _$registry_254.modules[_$attributes_203.type.dflt]; } return !!_module.categories[category]; @@ -12272,7 +12272,7 @@ _$registry_253.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_253.getTransformIndices = function(data, type) { +_$registry_254.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12292,7 +12292,7 @@ _$registry_253.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_253.hasTransform = function(data, type) { +_$registry_254.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12312,11 +12312,11 @@ _$registry_253.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_253.getComponentMethod = function(name, method) { - var _module = _$registry_253.componentsRegistry[name]; +_$registry_254.getComponentMethod = function(name, method) { + var _module = _$registry_254.componentsRegistry[name]; - if(!_module) return _$noop_172; - return _module[method] || _$noop_172; + if(!_module) return _$noop_173; + return _module[method] || _$noop_173; }; /** @@ -12326,10 +12326,10 @@ _$registry_253.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_253.call = function() { +_$registry_254.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_253.apiMethodRegistry[name].apply(null, args); + return _$registry_254.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12337,33 +12337,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_253.modules[thisType]) { - _$loggers_168.log('Type ' + thisType + ' already registered'); + if(_$registry_254.modules[thisType]) { + _$loggers_169.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_253.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_254.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_253.allCategories[categoriesIn[i]] = true; + _$registry_254.allCategories[categoriesIn[i]] = true; } - _$registry_253.modules[thisType] = { + _$registry_254.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_253.modules[thisType].meta = meta; + _$registry_254.modules[thisType].meta = meta; } - _$registry_253.allTypes.push(thisType); + _$registry_254.allTypes.push(thisType); - for(var componentName in _$registry_253.componentsRegistry) { + for(var componentName in _$registry_254.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12373,15 +12373,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_253.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_254.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_253.subplotsRegistry[plotType]) { - _$loggers_168.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_254.subplotsRegistry[plotType]) { + _$loggers_169.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12391,9 +12391,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_253.subplotsRegistry[plotType] = _module; + _$registry_254.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_253.componentsRegistry) { + for(var componentName in _$registry_254.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12404,24 +12404,24 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_253.componentsRegistry[name] = _module; + _$registry_254.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_176(_$registry_253.layoutArrayContainers, name); + _$pushUnique_177(_$registry_254.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_253.modules) { + for(var traceType in _$registry_254.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_253.subplotsRegistry) { + for(var subplotName in _$registry_254.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_253.transformsRegistry) { + for(var transformType in _$registry_254.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } @@ -12443,22 +12443,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_168.log([ + _$loggers_169.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_165(_module.attributes)) { - _$loggers_168.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_166(_module.attributes)) { + _$loggers_169.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_168.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_169.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_253.transformsRegistry[_module.name] = _module; + _$registry_254.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_253.componentsRegistry) { + for(var componentName in _$registry_254.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12472,7 +12472,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_253.localeRegistry; + var locales = _$registry_254.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12504,37 +12504,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_176(_$registry_253.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_177(_$registry_254.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_253.componentsRegistry[componentName].schema; + var componentSchema = _$registry_254.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_253.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_254.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_253.componentsRegistry[componentName].schema; + var componentSchema = _$registry_254.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_253.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_254.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_253.componentsRegistry[componentName].schema; + var componentSchema = _$registry_254.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_253.subplotsRegistry[subplotName]; + var subplotModule = _$registry_254.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12561,7 +12561,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_253 = require('../registry'); */; +/* removed: var _$registry_254 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12576,9 +12576,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_189 = function containerArrayMatch(astr) { - var rootContainers = _$registry_253.layoutArrayContainers, - regexpContainers = _$registry_253.layoutArrayRegexes, +var _$containerArrayMatch_190 = function containerArrayMatch(astr) { + var rootContainers = _$registry_254.layoutArrayContainers, + regexpContainers = _$registry_254.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12619,9 +12619,9 @@ var _$containerArrayMatch_189 = function containerArrayMatch(astr) { 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_164.isArrayOrTypedArray; -/* removed: var _$isPlainObject_165 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_189 = require('../plot_api/container_array_match'); */; +var isArrayOrTypedArray = _$is_array_165.isArrayOrTypedArray; +/* removed: var _$isPlainObject_166 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_190 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12637,7 +12637,7 @@ var isArrayOrTypedArray = _$is_array_164.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_171 = function nestedProperty(container, propStr) { +var _$nestedProperty_172 = function nestedProperty(container, propStr) { if(_$fastIsnumeric_9(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { @@ -12748,7 +12748,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_165(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_166(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12757,7 +12757,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_189(propStr); + var match = _$containerArrayMatch_190(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12910,7 +12910,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_178 = {}; +var _$regex_179 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12930,7 +12930,7 @@ var _$regex_178 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_178.counter = function(head, tail, openEnded) { +_$regex_179.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12938,7 +12938,7 @@ _$regex_178.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_152 = {}; +var _$coerce_153 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12953,16 +12953,16 @@ var _$coerce_152 = {}; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$attributes_202 = require('../plots/attributes'); */; +/* removed: var _$attributes_203 = require('../plots/attributes'); */; /* removed: var _$getScale_56 = require('../components/colorscale/get_scale'); */; var colorscaleNames = Object.keys(_$scales_62); -/* removed: var _$nestedProperty_171 = require('./nested_property'); */; -var counterRegex = _$regex_178.counter; +/* removed: var _$nestedProperty_172 = require('./nested_property'); */; +var counterRegex = _$regex_179.counter; var DESELECTDIM = _$interactions_144.DESELECTDIM; var wrap180 = _$angles_150.wrap180; -var __isArrayOrTypedArray_152 = _$is_array_164.isArrayOrTypedArray; +var __isArrayOrTypedArray_153 = _$is_array_165.isArrayOrTypedArray; -_$coerce_152.valObjectMeta = { +_$coerce_153.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12970,7 +12970,7 @@ _$coerce_152.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_152(v)) propOut.set(v); + if(__isArrayOrTypedArray_153(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13093,8 +13093,9 @@ _$coerce_152.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13148,9 +13149,11 @@ _$coerce_152.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13161,12 +13164,12 @@ _$coerce_152.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_152.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_153.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13176,19 +13179,28 @@ _$coerce_152.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13219,12 +13231,12 @@ _$coerce_152.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_152.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_153.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_152.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_153.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13244,10 +13256,10 @@ _$coerce_152.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_152.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_171(attributes, attribute).get(), - propIn = _$nestedProperty_171(containerIn, attribute), - propOut = _$nestedProperty_171(containerOut, attribute), +_$coerce_153.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_172(attributes, attribute).get(), + propIn = _$nestedProperty_172(containerIn, attribute), + propOut = _$nestedProperty_172(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13258,12 +13270,12 @@ _$coerce_152.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_152(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_153(v)) { propOut.set(v); return v; } - _$coerce_152.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_153.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13275,9 +13287,9 @@ _$coerce_152.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_152.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_171(containerIn, attribute), - propOut = _$coerce_152.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_153.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_172(containerIn, attribute), + propOut = _$coerce_153.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13288,7 +13300,7 @@ _$coerce_152.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_152.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_153.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13308,11 +13320,9 @@ _$coerce_152.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_152.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_153.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_202; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_203; var valObj = attrs.hoverinfo; var dflt; @@ -13326,7 +13336,7 @@ _$coerce_152.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_152.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_153.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13340,7 +13350,7 @@ _$coerce_152.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_152.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_153.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13355,7 +13365,7 @@ _$coerce_152.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_152(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_153(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13364,10 +13374,10 @@ _$coerce_152.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_152.validate = function(value, opts) { - var valObjectDef = _$coerce_152.valObjectMeta[opts.valType]; +_$coerce_153.validate = function(value, opts) { + var valObjectDef = _$coerce_153.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_152(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_153(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13397,12 +13407,12 @@ _$coerce_152.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_170 = function mod(v, d) { +var _$mod_171 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_153 = {}; +var _$dates_154 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13417,18 +13427,18 @@ var _$dates_153 = {}; /* removed: var _$d3_6 = require('d3'); */; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$loggers_168 = require('./loggers'); */; -/* removed: var _$mod_170 = require('./mod'); */; +/* removed: var _$loggers_169 = require('./loggers'); */; +/* removed: var _$mod_171 = require('./mod'); */; /* removed: var _$numerical_145 = require('../constants/numerical'); */; -var __BADNUM_153 = _$numerical_145.BADNUM; +var __BADNUM_154 = _$numerical_145.BADNUM; var ONEDAY = _$numerical_145.ONEDAY; var ONEHOUR = _$numerical_145.ONEHOUR; var ONEMIN = _$numerical_145.ONEMIN; var ONESEC = _$numerical_145.ONESEC; var EPOCHJD = _$numerical_145.EPOCHJD; -/* removed: var _$registry_253 = require('../registry'); */; +/* removed: var _$registry_254 = require('../registry'); */; var utcFormat = _$d3_6.time.format.utc; @@ -13442,7 +13452,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_253.componentsRegistry.calendars && + _$registry_254.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13452,11 +13462,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_153.dateTick0 = function(calendar, sunday) { +_$dates_154.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_253.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_253.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_254.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_254.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13466,9 +13476,9 @@ _$dates_153.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_153.dfltRange = function(calendar) { +_$dates_154.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_253.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_254.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13476,7 +13486,7 @@ _$dates_153.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_153.isJSDate = function(v) { +_$dates_154.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13538,17 +13548,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_153.dateTime2ms = function(s, calendar) { +_$dates_154.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_153.isJSDate(s)) { + if(_$dates_154.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_153; + return __BADNUM_154; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_153; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_154; s = String(s); @@ -13565,7 +13575,7 @@ _$dates_153.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_153; + if(!match) return __BADNUM_154; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13575,12 +13585,12 @@ _$dates_153.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_153; + if(y.length === 2) return __BADNUM_154; y = Number(y); var cDate; try { - var calInstance = _$registry_253.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_254.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13590,9 +13600,9 @@ _$dates_153.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_153; } // Invalid ... date + catch(e) { return __BADNUM_154; } // Invalid ... date - if(!cDate) return __BADNUM_153; + if(!cDate) return __BADNUM_154; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13613,18 +13623,18 @@ _$dates_153.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_153; - if(date.getUTCDate() !== d) return __BADNUM_153; + if(date.getUTCMonth() !== m) return __BADNUM_154; + if(date.getUTCDate() !== d) return __BADNUM_154; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_153.MIN_MS = _$dates_153.dateTime2ms('-9999'); -MAX_MS = _$dates_153.MAX_MS = _$dates_153.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_154.MIN_MS = _$dates_154.dateTime2ms('-9999'); +MAX_MS = _$dates_154.MAX_MS = _$dates_154.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_153.isDateTime = function(s, calendar) { - return (_$dates_153.dateTime2ms(s, calendar) !== __BADNUM_153); +_$dates_154.isDateTime = function(s, calendar) { + return (_$dates_154.dateTime2ms(s, calendar) !== __BADNUM_154); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13643,20 +13653,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_153.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_153; +_$dates_154.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_154; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_170(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_171(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_170(ms, ONEDAY)); + timeMs = Math.floor(_$mod_171(ms, ONEDAY)); try { - dateStr = _$registry_253.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_254.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13704,10 +13714,10 @@ _$dates_153.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_153.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_153; +_$dates_154.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_154; - var msecTenths = Math.floor(_$mod_170(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_171(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), dateStr = _$d3_6.time.format('%Y-%m-%d')(d), h = d.getHours(), @@ -13740,23 +13750,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_153.cleanDate = function(v, dflt, calendar) { - if(_$dates_153.isJSDate(v) || typeof v === 'number') { +_$dates_154.cleanDate = function(v, dflt, calendar) { + if(_$dates_154.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_168.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_169.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 = _$dates_153.ms2DateTimeLocal(+v); + v = _$dates_154.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_153.isDateTime(v, calendar)) { - _$loggers_168.error('unrecognized date', v); + else if(!_$dates_154.isDateTime(v, calendar)) { + _$loggers_169.error('unrecognized date', v); return dflt; } return v; @@ -13786,7 +13796,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_253.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_254.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13803,10 +13813,10 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_170(x + 0.05, ONEDAY); + var timePart = _$mod_171(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_170(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_171(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { if(!_$fastIsnumeric_9(tr)) tr = 0; // should only be 'S' @@ -13826,7 +13836,7 @@ function formatTime(x, tr) { * 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_170(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_171(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13855,7 +13865,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_153.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_154.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13899,19 +13909,19 @@ _$dates_153.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_153.incrementMonth = function(ms, dMonth, calendar) { +_$dates_154.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_170(ms, ONEDAY); + var timeMs = _$mod_171(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_253.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_254.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13920,7 +13930,7 @@ _$dates_153.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_168.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_169.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13935,7 +13945,7 @@ _$dates_153.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_153.findExactDates = function(data, calendar) { +_$dates_154.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13945,7 +13955,7 @@ _$dates_153.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_253.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_254.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { @@ -14012,7 +14022,7 @@ _$dates_153.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_154 = function ensureArray(out, n) { +var _$ensureArray_155 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14055,7 +14065,7 @@ var _$ensureArray_154 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_157 = function filterUnique(array) { +var _$filterUnique_158 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14089,7 +14099,7 @@ var _$filterUnique_157 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_158 = function filterVisible(container) { +var _$filterVisible_159 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14118,7 +14128,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_160 = {}; +var _$geometry2d_161 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14129,13 +14139,13 @@ var _$geometry2d_160 = {}; 'use strict'; -/* removed: var _$mod_170 = require('./mod'); */; +/* removed: var _$mod_171 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_160.segmentsIntersect = segmentsIntersect; +_$geometry2d_161.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14158,7 +14168,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_160.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_161.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 @@ -14211,7 +14221,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_160.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_161.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14223,13 +14233,13 @@ _$geometry2d_160.getTextLocation = function getTextLocation(path, totalPathLen, // 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_170(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_170(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_171(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_171(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_170(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_171(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14238,7 +14248,7 @@ _$geometry2d_160.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_160.clearLocationCache = function() { +_$geometry2d_161.clearLocationCache = function() { workingPath = null; }; @@ -14266,7 +14276,7 @@ _$geometry2d_160.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_160.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_161.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14327,7 +14337,7 @@ _$geometry2d_160.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_160.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_161.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14382,7 +14392,7 @@ _$geometry2d_160.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_161 = function(gd) { +var _$get_graph_div_162 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14414,7 +14424,7 @@ var _$get_graph_div_161 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_162 = function identity(d) { return d; }; +var _$identity_163 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14426,7 +14436,7 @@ var _$identity_162 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_171 = require('./nested_property'); */; +/* removed: var _$nestedProperty_172 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14448,13 +14458,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_167 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_171(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_172(baseObj, path).get(); } else { arr = baseObj; } @@ -14480,7 +14490,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_171(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_172(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14490,7 +14500,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_171(newValue, valueName).set(value); + _$nestedProperty_172(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14511,7 +14521,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_171(arr[idx], valueName).get(); + return _$nestedProperty_172(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14552,7 +14562,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value } 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_171(object, valueName).set(null); + _$nestedProperty_172(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, @@ -14579,7 +14589,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_171(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_172(arr[idx], valueName).get(); } } } else { @@ -14605,7 +14615,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_253 = require('../registry'); */; +/* removed: var _$registry_254 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14616,7 +14626,7 @@ var _$keyedContainer_166 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_167 = function localize(gd, s) { +var _$localize_168 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14638,7 +14648,7 @@ var _$localize_167 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_253.localeRegistry; + locales = _$registry_254.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14649,7 +14659,7 @@ var _$localize_167 = function localize(gd, s) { return s; }; -var _$matrix_169 = {}; +var _$matrix_170 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14662,7 +14672,7 @@ var _$matrix_169 = {}; 'use strict'; -_$matrix_169.init2dArray = function(rowLength, colLength) { +_$matrix_170.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14673,7 +14683,7 @@ _$matrix_169.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_169.transposeRagged = function(z) { +_$matrix_170.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14691,7 +14701,7 @@ _$matrix_169.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_169.dot = function(x, y) { +_$matrix_170.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14701,13 +14711,13 @@ _$matrix_169.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_169.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_170.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_169.transposeRagged(y); + var yTranspose = _$matrix_170.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_169.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_170.dot(x, yTranspose[i]); } else { // vec-vec @@ -14719,12 +14729,12 @@ _$matrix_169.dot = function(x, y) { }; // translate by (x,y) -_$matrix_169.translationMatrix = function(x, y) { +_$matrix_170.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_169.rotationMatrix = function(alpha) { +_$matrix_170.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14732,28 +14742,28 @@ _$matrix_169.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_169.rotationXYMatrix = function(a, x, y) { - return _$matrix_169.dot( - _$matrix_169.dot(_$matrix_169.translationMatrix(x, y), - _$matrix_169.rotationMatrix(a)), - _$matrix_169.translationMatrix(-x, -y)); +_$matrix_170.rotationXYMatrix = function(a, x, y) { + return _$matrix_170.dot( + _$matrix_170.dot(_$matrix_170.translationMatrix(x, y), + _$matrix_170.rotationMatrix(a)), + _$matrix_170.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_169.apply2DTransform = function(transform) { +_$matrix_170.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_169.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_170.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_169.apply2DTransform2 = function(transform) { - var at = _$matrix_169.apply2DTransform(transform); +_$matrix_170.apply2DTransform2 = function(transform) { + var at = _$matrix_170.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14782,7 +14792,7 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_173 = function(text, displayLength) { +var _$notifier_174 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); @@ -14874,7 +14884,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_179 = function(baseAttr, relativeAttr) { +var _$relative_attr_180 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14903,8 +14913,8 @@ var _$relative_attr_179 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_180 = _$is_array_164.isArrayOrTypedArray; -/* removed: var _$isPlainObject_165 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_181 = _$is_array_165.isArrayOrTypedArray; +/* removed: var _$isPlainObject_166 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14913,7 +14923,7 @@ var __isArrayOrTypedArray_180 = _$is_array_164.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_180 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_181 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14929,7 +14939,7 @@ var _$relinkPrivateKeys_180 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_180(fromVal) && __isArrayOrTypedArray_180(toVal) && _$isPlainObject_165(fromVal[0])) { + else if(__isArrayOrTypedArray_181(fromVal) && __isArrayOrTypedArray_181(toVal) && _$isPlainObject_166(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14939,12 +14949,12 @@ var _$relinkPrivateKeys_180 = function relinkPrivateKeys(toContainer, fromContai // 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_165(fromVal[j]) && _$isPlainObject_165(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_166(fromVal[j]) && _$isPlainObject_166(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_165(fromVal) && _$isPlainObject_165(toVal)) { + else if(_$isPlainObject_166(fromVal) && _$isPlainObject_166(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14954,7 +14964,7 @@ var _$relinkPrivateKeys_180 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_181 = {}; +var _$search_182 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14967,7 +14977,7 @@ var _$search_181 = {}; 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$loggers_168 = require('./loggers'); */; +/* removed: var _$loggers_169 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -14985,7 +14995,7 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_181.findBin = function(val, bins, linelow) { +_$search_182.findBin = function(val, bins, linelow) { if(_$fastIsnumeric_9(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : @@ -15009,7 +15019,7 @@ _$search_181.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_168.log('Long binary search...'); + if(c > 90) _$loggers_169.log('Long binary search...'); return n1 - 1; } }; @@ -15019,17 +15029,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_181.sorterAsc = function(a, b) { return a - b; }; -_$search_181.sorterDes = function(a, b) { return b - a; }; +_$search_182.sorterAsc = function(a, b) { return a - b; }; +_$search_182.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_181.distinctVals = function(valsIn) { +_$search_182.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_181.sorterAsc); + vals.sort(_$search_182.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15054,7 +15064,7 @@ _$search_181.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_181.roundUp = function(val, arrayIn, reverse) { +_$search_182.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15071,7 +15081,7 @@ _$search_181.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_183 = {}; +var _$stats_184 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15084,7 +15094,7 @@ var _$stats_183 = {}; 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_183 = _$is_array_164.isArrayOrTypedArray; +var __isArrayOrTypedArray_184 = _$is_array_165.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15099,14 +15109,14 @@ var __isArrayOrTypedArray_183 = _$is_array_164.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_183.aggNums = function(f, v, a, len) { +_$stats_184.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; if(!_$fastIsnumeric_9(v)) v = false; - if(__isArrayOrTypedArray_183(a[0])) { + if(__isArrayOrTypedArray_184(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_183.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_184.aggNums(f, v, a[i]); a = b; } @@ -15121,26 +15131,26 @@ _$stats_183.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_183.len = function(data) { - return _$stats_183.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_184.len = function(data) { + return _$stats_184.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_183.mean = function(data, len) { - if(!len) len = _$stats_183.len(data); - return _$stats_183.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_184.mean = function(data, len) { + if(!len) len = _$stats_184.len(data); + return _$stats_184.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_183.variance = function(data, len, mean) { - if(!len) len = _$stats_183.len(data); - if(!_$fastIsnumeric_9(mean)) mean = _$stats_183.mean(data, len); +_$stats_184.variance = function(data, len, mean) { + if(!len) len = _$stats_184.len(data); + if(!_$fastIsnumeric_9(mean)) mean = _$stats_184.mean(data, len); - return _$stats_183.aggNums(function(a, b) { + return _$stats_184.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_183.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_183.variance(data, len, mean)); +_$stats_184.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_184.variance(data, len, mean)); }; /** @@ -15158,7 +15168,7 @@ _$stats_183.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_183.interp = function(arr, n) { +_$stats_184.interp = function(arr, n) { if(!_$fastIsnumeric_9(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; @@ -15167,7 +15177,7 @@ _$stats_183.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_185 = {}; +var _$throttle_186 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15194,7 +15204,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_185.throttle = function throttle(id, minInterval, callback) { +_$throttle_186.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15234,7 +15244,7 @@ _$throttle_185.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_185.done = function(id) { +_$throttle_186.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15254,13 +15264,13 @@ _$throttle_185.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_185.clear = function(id) { +_$throttle_186.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_185.clear(idi); + for(var idi in timerCache) _$throttle_186.clear(idi); } }; @@ -15287,7 +15297,7 @@ function _clearTimeout(cache) { * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_186 = function toLogRange(val, range) { +var _$toLogRange_187 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the @@ -15298,7 +15308,7 @@ var _$toLogRange_186 = function toLogRange(val, range) { return newVal; }; -var _$lib_163 = {}; +var _$lib_164 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15315,71 +15325,71 @@ var _$lib_163 = {}; /* removed: var _$numerical_145 = require('../constants/numerical'); */; var FP_SAFE = _$numerical_145.FP_SAFE; -var __BADNUM_163 = _$numerical_145.BADNUM; - -var lib = _$lib_163 = {}; - -lib.nestedProperty = _$nestedProperty_171; -lib.keyedContainer = _$keyedContainer_166; -lib.relativeAttr = _$relative_attr_179; -lib.isPlainObject = _$isPlainObject_165; -lib.mod = _$mod_170; -lib.toLogRange = _$toLogRange_186; -lib.relinkPrivateKeys = _$relinkPrivateKeys_180; -lib.ensureArray = _$ensureArray_154; - -/* removed: var _$is_array_164 = require('./is_array'); */; -lib.isTypedArray = _$is_array_164.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_164.isArrayOrTypedArray; - -/* removed: var _$coerce_152 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_152.valObjectMeta; -lib.coerce = _$coerce_152.coerce; -lib.coerce2 = _$coerce_152.coerce2; -lib.coerceFont = _$coerce_152.coerceFont; -lib.coerceHoverinfo = _$coerce_152.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_152.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_152.validate; - -/* removed: var _$dates_153 = require('./dates'); */; -lib.dateTime2ms = _$dates_153.dateTime2ms; -lib.isDateTime = _$dates_153.isDateTime; -lib.ms2DateTime = _$dates_153.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_153.ms2DateTimeLocal; -lib.cleanDate = _$dates_153.cleanDate; -lib.isJSDate = _$dates_153.isJSDate; -lib.formatDate = _$dates_153.formatDate; -lib.incrementMonth = _$dates_153.incrementMonth; -lib.dateTick0 = _$dates_153.dateTick0; -lib.dfltRange = _$dates_153.dfltRange; -lib.findExactDates = _$dates_153.findExactDates; -lib.MIN_MS = _$dates_153.MIN_MS; -lib.MAX_MS = _$dates_153.MAX_MS; - -/* removed: var _$search_181 = require('./search'); */; -lib.findBin = _$search_181.findBin; -lib.sorterAsc = _$search_181.sorterAsc; -lib.sorterDes = _$search_181.sorterDes; -lib.distinctVals = _$search_181.distinctVals; -lib.roundUp = _$search_181.roundUp; - -/* removed: var _$stats_183 = require('./stats'); */; -lib.aggNums = _$stats_183.aggNums; -lib.len = _$stats_183.len; -lib.mean = _$stats_183.mean; -lib.variance = _$stats_183.variance; -lib.stdev = _$stats_183.stdev; -lib.interp = _$stats_183.interp; - -/* removed: var _$matrix_169 = require('./matrix'); */; -lib.init2dArray = _$matrix_169.init2dArray; -lib.transposeRagged = _$matrix_169.transposeRagged; -lib.dot = _$matrix_169.dot; -lib.translationMatrix = _$matrix_169.translationMatrix; -lib.rotationMatrix = _$matrix_169.rotationMatrix; -lib.rotationXYMatrix = _$matrix_169.rotationXYMatrix; -lib.apply2DTransform = _$matrix_169.apply2DTransform; -lib.apply2DTransform2 = _$matrix_169.apply2DTransform2; +var __BADNUM_164 = _$numerical_145.BADNUM; + +var lib = _$lib_164 = {}; + +lib.nestedProperty = _$nestedProperty_172; +lib.keyedContainer = _$keyedContainer_167; +lib.relativeAttr = _$relative_attr_180; +lib.isPlainObject = _$isPlainObject_166; +lib.mod = _$mod_171; +lib.toLogRange = _$toLogRange_187; +lib.relinkPrivateKeys = _$relinkPrivateKeys_181; +lib.ensureArray = _$ensureArray_155; + +/* removed: var _$is_array_165 = require('./is_array'); */; +lib.isTypedArray = _$is_array_165.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_165.isArrayOrTypedArray; + +/* removed: var _$coerce_153 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_153.valObjectMeta; +lib.coerce = _$coerce_153.coerce; +lib.coerce2 = _$coerce_153.coerce2; +lib.coerceFont = _$coerce_153.coerceFont; +lib.coerceHoverinfo = _$coerce_153.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_153.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_153.validate; + +/* removed: var _$dates_154 = require('./dates'); */; +lib.dateTime2ms = _$dates_154.dateTime2ms; +lib.isDateTime = _$dates_154.isDateTime; +lib.ms2DateTime = _$dates_154.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_154.ms2DateTimeLocal; +lib.cleanDate = _$dates_154.cleanDate; +lib.isJSDate = _$dates_154.isJSDate; +lib.formatDate = _$dates_154.formatDate; +lib.incrementMonth = _$dates_154.incrementMonth; +lib.dateTick0 = _$dates_154.dateTick0; +lib.dfltRange = _$dates_154.dfltRange; +lib.findExactDates = _$dates_154.findExactDates; +lib.MIN_MS = _$dates_154.MIN_MS; +lib.MAX_MS = _$dates_154.MAX_MS; + +/* removed: var _$search_182 = require('./search'); */; +lib.findBin = _$search_182.findBin; +lib.sorterAsc = _$search_182.sorterAsc; +lib.sorterDes = _$search_182.sorterDes; +lib.distinctVals = _$search_182.distinctVals; +lib.roundUp = _$search_182.roundUp; + +/* removed: var _$stats_184 = require('./stats'); */; +lib.aggNums = _$stats_184.aggNums; +lib.len = _$stats_184.len; +lib.mean = _$stats_184.mean; +lib.variance = _$stats_184.variance; +lib.stdev = _$stats_184.stdev; +lib.interp = _$stats_184.interp; + +/* removed: var _$matrix_170 = require('./matrix'); */; +lib.init2dArray = _$matrix_170.init2dArray; +lib.transposeRagged = _$matrix_170.transposeRagged; +lib.dot = _$matrix_170.dot; +lib.translationMatrix = _$matrix_170.translationMatrix; +lib.rotationMatrix = _$matrix_170.rotationMatrix; +lib.rotationXYMatrix = _$matrix_170.rotationXYMatrix; +lib.apply2DTransform = _$matrix_170.apply2DTransform; +lib.apply2DTransform2 = _$matrix_170.apply2DTransform2; /* removed: var _$angles_150 = require('./angles'); */; lib.deg2rad = _$angles_150.deg2rad; @@ -15387,54 +15397,54 @@ lib.rad2deg = _$angles_150.rad2deg; lib.wrap360 = _$angles_150.wrap360; lib.wrap180 = _$angles_150.wrap180; -/* removed: var _$geometry2d_160 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_160.segmentsIntersect; -lib.segmentDistance = _$geometry2d_160.segmentDistance; -lib.getTextLocation = _$geometry2d_160.getTextLocation; -lib.clearLocationCache = _$geometry2d_160.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_160.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_160.findPointOnPath; +/* removed: var _$geometry2d_161 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_161.segmentsIntersect; +lib.segmentDistance = _$geometry2d_161.segmentDistance; +lib.getTextLocation = _$geometry2d_161.getTextLocation; +lib.clearLocationCache = _$geometry2d_161.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_161.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_161.findPointOnPath; -/* removed: var _$extend_156 = require('./extend'); */; -lib.extendFlat = _$extend_156.extendFlat; -lib.extendDeep = _$extend_156.extendDeep; -lib.extendDeepAll = _$extend_156.extendDeepAll; -lib.extendDeepNoArrays = _$extend_156.extendDeepNoArrays; +/* removed: var _$extend_157 = require('./extend'); */; +lib.extendFlat = _$extend_157.extendFlat; +lib.extendDeep = _$extend_157.extendDeep; +lib.extendDeepAll = _$extend_157.extendDeepAll; +lib.extendDeepNoArrays = _$extend_157.extendDeepNoArrays; -/* removed: var _$loggers_168 = require('./loggers'); */; -lib.log = _$loggers_168.log; -lib.warn = _$loggers_168.warn; -lib.error = _$loggers_168.error; +/* removed: var _$loggers_169 = require('./loggers'); */; +lib.log = _$loggers_169.log; +lib.warn = _$loggers_169.warn; +lib.error = _$loggers_169.error; -/* removed: var _$regex_178 = require('./regex'); */; -lib.counterRegex = _$regex_178.counter; +/* removed: var _$regex_179 = require('./regex'); */; +lib.counterRegex = _$regex_179.counter; -/* removed: var _$throttle_185 = require('./throttle'); */; -lib.throttle = _$throttle_185.throttle; -lib.throttleDone = _$throttle_185.done; -lib.clearThrottle = _$throttle_185.clear; +/* removed: var _$throttle_186 = require('./throttle'); */; +lib.throttle = _$throttle_186.throttle; +lib.throttleDone = _$throttle_186.done; +lib.clearThrottle = _$throttle_186.clear; -lib.getGraphDiv = _$get_graph_div_161; +lib.getGraphDiv = _$get_graph_div_162; -lib._ = _$localize_167; +lib._ = _$localize_168; -lib.notifier = _$notifier_173; +lib.notifier = _$notifier_174; -lib.filterUnique = _$filterUnique_157; -lib.filterVisible = _$filterVisible_158; -lib.pushUnique = _$pushUnique_176; +lib.filterUnique = _$filterUnique_158; +lib.filterVisible = _$filterVisible_159; +lib.pushUnique = _$pushUnique_177; lib.cleanNumber = _$cleanNumber_151; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_9(v)) return __BADNUM_163; + if(!_$fastIsnumeric_9(v)) return __BADNUM_164; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_163; - return _$fastIsnumeric_9(v) ? Number(v) : __BADNUM_163; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_164; + return _$fastIsnumeric_9(v) ? Number(v) : __BADNUM_164; }; -lib.noop = _$noop_172; -lib.identity = _$identity_162; +lib.noop = _$noop_173; +lib.identity = _$identity_163; /** * swap x and y of the same attribute in container cont @@ -15933,6 +15943,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16126,7 +16193,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_163 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_164 = /^\w*$/; /* * Substitute values from an object into a string @@ -16147,7 +16214,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_163.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_164.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16200,7 +16267,7 @@ lib.pseudoRandom = function() { var _$plotcss_1 = {}; 'use strict'; -/* removed: var _$lib_163 = require('../src/lib'); */; +/* removed: var _$lib_164 = require('../src/lib'); */; var rules = { "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;", "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;", @@ -16259,7 +16326,7 @@ for(var selector in rules) { var fullSelector = selector.replace(/^,/,' ,') .replace(/X/g, '.js-plotly-plot .plotly') .replace(/Y/g, '.plotly-notifier'); - _$lib_163.addStyleRule(fullSelector, rules[selector]); + _$lib_164.addStyleRule(fullSelector, rules[selector]); } 'use strict'; @@ -17810,21 +17877,21 @@ var _$arrow_paths_27 = [ */ 'use strict'; -var __counterRegex_210 = _$regex_178.counter; +var __counterRegex_211 = _$regex_179.counter; -var _$constants_210 = { +var _$constants_211 = { idRegex: { - x: __counterRegex_210('x'), - y: __counterRegex_210('y') + x: __counterRegex_211('x'), + y: __counterRegex_211('y') }, - attrRegex: __counterRegex_210('[xy]axis'), + attrRegex: __counterRegex_211('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_210('xaxis'), - yAxisMatch: __counterRegex_210('yaxis'), + xAxisMatch: __counterRegex_211('xaxis'), + yAxisMatch: __counterRegex_211('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -17871,6 +17938,7 @@ var _$constants_210 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -17892,7 +17960,7 @@ var _$constants_210 = { /* removed: var _$arrow_paths_27 = require('./arrow_paths'); */; /* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_210 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_211 = require('../../plots/cartesian/constants'); */; var _$attributes_28 = { @@ -18092,7 +18160,7 @@ var _$attributes_28 = { dflt: 'pixel', values: [ 'pixel', - _$constants_210.idRegex.x.toString() + _$constants_211.idRegex.x.toString() ], editType: 'calc', @@ -18103,7 +18171,7 @@ var _$attributes_28 = { dflt: 'pixel', values: [ 'pixel', - _$constants_210.idRegex.y.toString() + _$constants_211.idRegex.y.toString() ], editType: 'calc', @@ -18114,7 +18182,7 @@ var _$attributes_28 = { valType: 'enumerated', values: [ 'paper', - _$constants_210.idRegex.x.toString() + _$constants_211.idRegex.x.toString() ], editType: 'calc', @@ -18145,7 +18213,7 @@ var _$attributes_28 = { valType: 'enumerated', values: [ 'paper', - _$constants_210.idRegex.y.toString() + _$constants_211.idRegex.y.toString() ], editType: 'calc', @@ -18671,7 +18739,7 @@ var _$align_63 = function align(v, dv, v0, v1, anchor) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; // set cursors pointing toward the closest corner/side, @@ -18687,12 +18755,12 @@ var _$getCursor_64 = 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_163.constrain(Math.floor(x * 3), 0, 2); + else x = _$lib_164.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_163.constrain(Math.floor(y * 3), 0, 2); + else y = _$lib_164.constrain(Math.floor(y * 3), 0, 2); return cursorset[y][x]; }; @@ -19044,7 +19112,7 @@ function isUndefined(arg) { /* global jQuery:false */ -var __EventEmitter_155 = _$EventEmitter_8.EventEmitter; +var __EventEmitter_156 = _$EventEmitter_8.EventEmitter; var Events = { @@ -19054,10 +19122,10 @@ var Events = { * If we have already instantiated an emitter for this plot * return early. */ - if(plotObj._ev instanceof __EventEmitter_155) return plotObj; + if(plotObj._ev instanceof __EventEmitter_156) return plotObj; - var ev = new __EventEmitter_155(); - var internalEv = new __EventEmitter_155(); + var ev = new __EventEmitter_156(); + var internalEv = new __EventEmitter_156(); /* * Assign to plot._ev while we still live in a land @@ -19194,7 +19262,7 @@ var Events = { }; -var _$Events_155 = Events; +var _$Events_156 = Events; var _$unhover_66 = {}; /** @@ -19209,9 +19277,9 @@ var _$unhover_66 = {}; 'use strict'; -/* removed: var _$Events_155 = require('../../lib/events'); */; -/* removed: var _$throttle_185 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_161 = require('../../lib/get_graph_div'); */; +/* removed: var _$Events_156 = require('../../lib/events'); */; +/* removed: var _$throttle_186 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_162 = require('../../lib/get_graph_div'); */; /* removed: var _$constants_80 = require('../fx/constants'); */; @@ -19219,11 +19287,11 @@ var unhover = _$unhover_66 = {}; unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_161(gd); + gd = _$get_graph_div_162(gd); // Important, clear any queued hovers if(gd._fullLayout) { - _$throttle_185.clear(gd._fullLayout._uid + _$constants_80.HOVERID); + _$throttle_186.clear(gd._fullLayout._uid + _$constants_80.HOVERID); } unhover.raw(gd, evt, subplot); @@ -19237,7 +19305,7 @@ unhover.raw = function unhoverRaw(gd, evt) { if(!evt) evt = {}; if(evt.target && - _$Events_155.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + _$Events_156.triggerHandler(gd, 'plotly_beforehover', evt) === false) { return; } @@ -19270,10 +19338,10 @@ var _$dragelement_65 = {}; /* removed: var _$hasHover_11 = require('has-hover'); */; /* removed: var _$hasPassiveEvents_12 = require('has-passive-events'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -/* removed: var _$constants_210 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_211 = require('../../plots/cartesian/constants'); */; /* removed: var _$interactions_144 = require('../../constants/interactions'); */; var dragElement = _$dragelement_65 = {}; @@ -19430,7 +19498,7 @@ dragElement.init = function init(options) { e.preventDefault(); var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_210.MINDRAG; + var minDrag = options.minDrag || _$constants_211.MINDRAG; var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); var dx = dxdy[0]; var dy = dxdy[1]; @@ -19454,7 +19522,7 @@ dragElement.init = function init(options) { e.preventDefault(); if(_$hasHover_11) { - _$lib_163.removeElement(dragCover); + _$lib_164.removeElement(dragCover); } else if(cursor) { dragCover.documentElement.style.cursor = cursor; @@ -19535,7 +19603,7 @@ dragElement.coverSlip = coverSlip; function finishDrag(gd) { gd._dragging = false; - if(gd._replotPending) _$registry_253.call('plot', gd); + if(gd._replotPending) _$registry_254.call('plot', gd); } function pointerOffset(e) { @@ -19646,7 +19714,7 @@ var _$flipScale_55 = function flipScale(scl) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$scales_62 = require('./scales'); */; /* removed: var _$flipScale_55 = require('./flip_scale'); */; @@ -19656,8 +19724,8 @@ var _$calc_50 = function calc(trace, vals, containerStr, cLetter) { var container, inputContainer; if(containerStr) { - container = _$lib_163.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_163.nestedProperty(trace._input, containerStr).get(); + container = _$lib_164.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_164.nestedProperty(trace._input, containerStr).get(); } else { container = trace; @@ -19673,11 +19741,11 @@ var _$calc_50 = function calc(trace, vals, containerStr, cLetter) { scl = container.colorscale; if(auto !== false || min === undefined) { - min = _$lib_163.aggNums(Math.min, null, vals); + min = _$lib_164.aggNums(Math.min, null, vals); } if(auto !== false || max === undefined) { - max = _$lib_163.aggNums(Math.max, null, vals); + max = _$lib_164.aggNums(Math.max, null, vals); } if(min === max) { @@ -19723,9 +19791,9 @@ var _$calc_50 = function calc(trace, vals, containerStr, cLetter) { 'use strict'; -/* removed: var _$lib_163 = require('../lib'); */; -var __extendFlat_190 = _$lib_163.extendFlat; -var __isPlainObject_190 = _$lib_163.isPlainObject; +/* removed: var _$lib_164 = require('../lib'); */; +var __extendFlat_191 = _$lib_164.extendFlat; +var __isPlainObject_191 = _$lib_164.isPlainObject; var traceOpts = { valType: 'flaglist', @@ -19738,7 +19806,7 @@ var layoutOpts = { valType: 'flaglist', extras: ['none'], flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', 'layoutstyle', 'modebar', 'camera', 'arraydraw' ], @@ -19753,7 +19821,7 @@ var traceEditTypeFlags = traceOpts.flags.slice() var layoutEditTypeFlags = layoutOpts.flags.slice() .concat('layoutReplot'); -var _$edit_types_190 = { +var _$edit_types_191 = { traces: traceOpts, layout: layoutOpts, /* @@ -19806,10 +19874,10 @@ function falseObj(keys) { * @return {object} a new attributes object with `editType` modified as directed */ function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_190({}, attrs); + var out = __extendFlat_191({}, attrs); for(var key in out) { var attr = out[key]; - if(__isPlainObject_190(attr)) { + if(__isPlainObject_191(attr)) { out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } @@ -19820,7 +19888,7 @@ function overrideAll(attrs, editTypeOverride, overrideContainers) { function overrideOne(attr, editTypeOverride, overrideContainers, key) { if(attr.valType) { - var out = __extendFlat_190({}, attr); + var out = __extendFlat_191({}, attr); out.editType = editTypeOverride; if(Array.isArray(attr.items)) { @@ -19876,12 +19944,12 @@ _$attributes_67.dash = { /* removed: var _$font_attributes_232 = require('../font_attributes'); */; /* removed: var _$attributes_42 = require('../../components/color/attributes'); */; var dash = _$attributes_67.dash; -var __extendFlat_217 = _$extend_156.extendFlat; +var __extendFlat_218 = _$extend_157.extendFlat; -/* removed: var _$constants_210 = require('./constants'); */; +/* removed: var _$constants_211 = require('./constants'); */; -var _$layout_attributes_217 = { +var _$layout_attributes_218 = { visible: { valType: 'boolean', @@ -19937,10 +20005,10 @@ var _$layout_attributes_217 = { valType: 'info_array', items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} ], - editType: 'plot+margins', + editType: 'axrange+margins', impliedEdits: {'autorange': false}, }, @@ -19956,8 +20024,8 @@ var _$layout_attributes_217 = { scaleanchor: { valType: 'enumerated', values: [ - _$constants_210.idRegex.x.toString(), - _$constants_210.idRegex.y.toString() + _$constants_211.idRegex.x.toString(), + _$constants_211.idRegex.y.toString() ], editType: 'plot', @@ -20101,7 +20169,7 @@ var _$layout_attributes_217 = { editType: 'none', }, - spikedash: __extendFlat_217({}, dash, {dflt: 'dash', editType: 'none'}), + spikedash: __extendFlat_218({}, dash, {dflt: 'dash', editType: 'none'}), spikemode: { valType: 'flaglist', flags: ['toaxis', 'across', 'marker'], @@ -20289,8 +20357,8 @@ var _$layout_attributes_217 = { valType: 'enumerated', values: [ 'free', - _$constants_210.idRegex.x.toString(), - _$constants_210.idRegex.y.toString() + _$constants_211.idRegex.x.toString(), + _$constants_211.idRegex.y.toString() ], editType: 'plot+margins', @@ -20312,8 +20380,8 @@ var _$layout_attributes_217 = { valType: 'enumerated', values: [ 'free', - _$constants_210.idRegex.x.toString(), - _$constants_210.idRegex.y.toString() + _$constants_211.idRegex.x.toString(), + _$constants_211.idRegex.y.toString() ], editType: 'plot', @@ -20386,10 +20454,10 @@ var _$layout_attributes_217 = { 'use strict'; -/* removed: var _$layout_attributes_217 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$layout_attributes_218 = require('../../plots/cartesian/layout_attributes'); */; /* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; -var __extendFlat_44 = _$extend_156.extendFlat; -var __overrideAll_44 = _$edit_types_190.overrideAll; +var __extendFlat_44 = _$extend_157.extendFlat; +var __overrideAll_44 = _$edit_types_191.overrideAll; var _$attributes_44 = __overrideAll_44({ @@ -20474,11 +20542,11 @@ var _$attributes_44 = __overrideAll_44({ }, // a possible line around the bar itself - outlinecolor: _$layout_attributes_217.linecolor, - outlinewidth: _$layout_attributes_217.linewidth, + outlinecolor: _$layout_attributes_218.linecolor, + outlinewidth: _$layout_attributes_218.linewidth, // Should outlinewidth have {dflt: 0} ? // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_217.linecolor, + bordercolor: _$layout_attributes_218.linecolor, borderwidth: { valType: 'number', @@ -20493,30 +20561,30 @@ var _$attributes_44 = __overrideAll_44({ }, // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_217.tickmode, - nticks: _$layout_attributes_217.nticks, - tick0: _$layout_attributes_217.tick0, - dtick: _$layout_attributes_217.dtick, - tickvals: _$layout_attributes_217.tickvals, - ticktext: _$layout_attributes_217.ticktext, - ticks: __extendFlat_44({}, _$layout_attributes_217.ticks, {dflt: ''}), - ticklen: _$layout_attributes_217.ticklen, - tickwidth: _$layout_attributes_217.tickwidth, - tickcolor: _$layout_attributes_217.tickcolor, - showticklabels: _$layout_attributes_217.showticklabels, + tickmode: _$layout_attributes_218.tickmode, + nticks: _$layout_attributes_218.nticks, + tick0: _$layout_attributes_218.tick0, + dtick: _$layout_attributes_218.dtick, + tickvals: _$layout_attributes_218.tickvals, + ticktext: _$layout_attributes_218.ticktext, + ticks: __extendFlat_44({}, _$layout_attributes_218.ticks, {dflt: ''}), + ticklen: _$layout_attributes_218.ticklen, + tickwidth: _$layout_attributes_218.tickwidth, + tickcolor: _$layout_attributes_218.tickcolor, + showticklabels: _$layout_attributes_218.showticklabels, tickfont: _$font_attributes_232({ }), - tickangle: _$layout_attributes_217.tickangle, - tickformat: _$layout_attributes_217.tickformat, - tickformatstops: _$layout_attributes_217.tickformatstops, - tickprefix: _$layout_attributes_217.tickprefix, - showtickprefix: _$layout_attributes_217.showtickprefix, - ticksuffix: _$layout_attributes_217.ticksuffix, - showticksuffix: _$layout_attributes_217.showticksuffix, - separatethousands: _$layout_attributes_217.separatethousands, - exponentformat: _$layout_attributes_217.exponentformat, - showexponent: _$layout_attributes_217.showexponent, + tickangle: _$layout_attributes_218.tickangle, + tickformat: _$layout_attributes_218.tickformat, + tickformatstops: _$layout_attributes_218.tickformatstops, + tickprefix: _$layout_attributes_218.tickprefix, + showtickprefix: _$layout_attributes_218.showtickprefix, + ticksuffix: _$layout_attributes_218.ticksuffix, + showticksuffix: _$layout_attributes_218.showticksuffix, + separatethousands: _$layout_attributes_218.separatethousands, + exponentformat: _$layout_attributes_218.exponentformat, + showexponent: _$layout_attributes_218.showexponent, title: { valType: 'string', @@ -20545,8 +20613,8 @@ var _$attributes_44 = __overrideAll_44({ 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$layout_attributes_218 = require('./layout_attributes'); */; var _$handleTickLabelDefaults_225 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); @@ -20564,7 +20632,7 @@ var _$handleTickLabelDefaults_225 = function handleTickLabelDefaults(containerIn // explicitly provided var dfltFontColor = (containerOut.color === containerIn.color) ? containerOut.color : font.color; - _$lib_163.coerceFont(coerce, 'tickfont', { + _$lib_164.coerceFont(coerce, 'tickfont', { family: font.family, size: font.size, color: dfltFontColor @@ -20622,7 +20690,7 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_163.coerce(valueIn, valueOut, _$layout_attributes_217.tickformatstops, attr, dflt); + return _$lib_164.coerce(valueIn, valueOut, _$layout_attributes_218.tickformatstops, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -20647,18 +20715,18 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_218 = require('./layout_attributes'); */; /** * options: inherits outerTicks from axes.handleAxisDefaults */ var _$handleTickDefaults_226 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_163.coerce2(containerIn, containerOut, _$layout_attributes_217, 'ticklen'), - tickWidth = _$lib_163.coerce2(containerIn, containerOut, _$layout_attributes_217, 'tickwidth'), - tickColor = _$lib_163.coerce2(containerIn, containerOut, _$layout_attributes_217, 'tickcolor', containerOut.color), + var tickLen = _$lib_164.coerce2(containerIn, containerOut, _$layout_attributes_218, 'ticklen'), + tickWidth = _$lib_164.coerce2(containerIn, containerOut, _$layout_attributes_218, 'tickwidth'), + tickColor = _$lib_164.coerce2(containerIn, containerOut, _$layout_attributes_218, 'tickcolor', containerOut.color), showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); if(!showTicks) { @@ -20680,7 +20748,7 @@ var _$handleTickDefaults_226 = function handleTickDefaults(containerIn, containe 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; var __ONEDAY_227 = _$numerical_145.ONEDAY; @@ -20731,10 +20799,10 @@ var _$handleTickValueDefaults_227 = function handleTickValueDefaults(containerIn // tick0 can have different valType for different axis types, so // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_163.dateTick0(containerOut.calendar) : 0; + var tick0Dflt = (axType === 'date') ? _$lib_164.dateTick0(containerOut.calendar) : 0; var tick0 = coerce('tick0', tick0Dflt); if(axType === 'date') { - containerOut.tick0 = _$lib_163.cleanDate(tick0, tick0Dflt); + containerOut.tick0 = _$lib_164.cleanDate(tick0, tick0Dflt); } // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely else if(_$fastIsnumeric_9(tick0) && dtick !== 'D1' && dtick !== 'D2') { @@ -20762,7 +20830,7 @@ var _$handleTickValueDefaults_227 = function handleTickValueDefaults(containerIn 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$handleTickValueDefaults_227 = require('../../plots/cartesian/tick_value_defaults'); */; /* removed: var _$handleTickDefaults_226 = require('../../plots/cartesian/tick_mark_defaults'); */; /* removed: var _$handleTickLabelDefaults_225 = require('../../plots/cartesian/tick_label_defaults'); */; @@ -20775,7 +20843,7 @@ var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, colorbarIn = containerIn.colorbar || {}; function coerce(attr, dflt) { - return _$lib_163.coerce(colorbarIn, colorbarOut, _$attributes_44, attr, dflt); + return _$lib_164.coerce(colorbarIn, colorbarOut, _$attributes_44, attr, dflt); } var thicknessmode = coerce('thicknessmode'); @@ -20796,7 +20864,7 @@ var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, coerce('y'); coerce('yanchor'); coerce('ypad'); - _$lib_163.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + _$lib_164.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); coerce('outlinecolor'); coerce('outlinewidth'); @@ -20811,7 +20879,7 @@ var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, _$handleTickDefaults_226(colorbarIn, colorbarOut, coerce, 'linear', opts); coerce('title', layout._dfltTitle.colorbar); - _$lib_163.coerceFont(coerce, 'titlefont', layout.font); + _$lib_164.coerceFont(coerce, 'titlefont', layout.font); coerce('titleside'); }; @@ -20826,11 +20894,11 @@ var _$colorbarDefaults_46 = function colorbarDefaults(containerIn, containerOut, 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; var _$hasColorbar_48 = function hasColorbar(container) { - return _$lib_163.isPlainObject(container.colorbar); + return _$lib_164.isPlainObject(container.colorbar); }; /** @@ -20866,7 +20934,7 @@ var _$isValidScale_59 = function isValidScale(scl) { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$hasColorbar_48 = require('../colorbar/has_colorbar'); */; /* removed: var _$colorbarDefaults_46 = require('../colorbar/defaults'); */; @@ -20879,10 +20947,10 @@ var _$colorScaleDefaults_53 = function colorScaleDefaults(traceIn, traceOut, lay cLetter = opts.cLetter, containerStr = prefix.slice(0, prefix.length - 1), containerIn = prefix ? - _$lib_163.nestedProperty(traceIn, containerStr).get() || {} : + _$lib_164.nestedProperty(traceIn, containerStr).get() || {} : traceIn, containerOut = prefix ? - _$lib_163.nestedProperty(traceOut, containerStr).get() || {} : + _$lib_164.nestedProperty(traceOut, containerStr).get() || {} : traceOut, minIn = containerIn[cLetter + 'min'], maxIn = containerIn[cLetter + 'max'], @@ -20963,17 +21031,17 @@ var _$extractScale_54 = function extractScale(scl, cmin, cmax) { 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$isValidScale_59 = require('./is_valid_scale'); */; var _$hasColorscale_57 = function hasColorscale(trace, containerStr) { var container = containerStr ? - _$lib_163.nestedProperty(trace, containerStr).get() || {} : + _$lib_164.nestedProperty(trace, containerStr).get() || {} : trace; var color = container.color; var isArrayWithOneNumber = false; - if(_$lib_163.isArrayOrTypedArray(color)) { + if(_$lib_164.isArrayOrTypedArray(color)) { for(var i = 0; i < color.length; i++) { if(_$fastIsnumeric_9(color[i])) { isArrayWithOneNumber = true; @@ -20983,12 +21051,12 @@ var _$hasColorscale_57 = function hasColorscale(trace, containerStr) { } return ( - _$lib_163.isPlainObject(container) && ( + _$lib_164.isPlainObject(container) && ( isArrayWithOneNumber || container.showscale === true || (_$fastIsnumeric_9(container.cmin) && _$fastIsnumeric_9(container.cmax)) || _$isValidScale_59(container.colorscale) || - _$lib_163.isPlainObject(container.colorbar) + _$lib_164.isPlainObject(container.colorbar) ) ); }; @@ -21734,7 +21802,7 @@ var _$string_mappings_146 = { } }; -var _$svg_text_utils_184 = {}; +var _$svg_text_utils_185 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21750,7 +21818,7 @@ var _$svg_text_utils_184 = {}; /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$lib_164 = require('../lib'); */; /* removed: var _$xmlns_namespaces_147 = require('../constants/xmlns_namespaces'); */; /* removed: var _$string_mappings_146 = require('../constants/string_mappings'); */; var LINE_SPACING = _$alignment_143.LINE_SPACING; @@ -21763,7 +21831,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_184.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_185.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) @@ -21806,7 +21874,7 @@ _$svg_text_utils_184.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_184.positionText(_context); + _$svg_text_utils_185.positionText(_context); if(_callback) _callback.call(_context); } @@ -21901,7 +21969,7 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_163.randstr([], 64); + var randomID = 'math-output-' + _$lib_164.randstr([], 64); var tmpDiv = _$d3_6.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) @@ -21912,7 +21980,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = _$d3_6.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_163.log('There was an error in the tex syntax.', _texString); + _$lib_164.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -22007,7 +22075,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_184.plainText = function(_str) { +_$svg_text_utils_185.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -22140,14 +22208,14 @@ function buildSVGText(containerNode, str) { // 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_163.log('Ignoring unexpected end tag .', str); + _$lib_164.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_163.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_164.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -22206,7 +22274,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -22221,11 +22292,11 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_184.lineCount = function lineCount(s) { +_$svg_text_utils_185.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_184.positionText = function positionText(s, x, y) { +_$svg_text_utils_185.positionText = function positionText(s, x, y) { return s.each(function() { var text = _$d3_6.select(this); @@ -22301,7 +22372,7 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_184.makeEditable = function(context, options) { +_$svg_text_utils_185.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; var dispatch = _$d3_6.dispatch('edit', 'input', 'cancel'); @@ -22424,7 +22495,7 @@ _$svg_text_utils_184.makeEditable = function(context, options) { // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_282 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_283 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -22460,17 +22531,20 @@ var _$makeBubbleSizeFn_282 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -var _$subtypes_287 = { +var _$subtypes_288 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -22479,8 +22553,8 @@ var _$subtypes_287 = { }, isBubble: function(trace) { - return _$lib_163.isPlainObject(trace.marker) && - _$lib_163.isArrayOrTypedArray(trace.marker.size); + return _$lib_164.isPlainObject(trace.marker) && + _$lib_164.isArrayOrTypedArray(trace.marker.size); } }; @@ -22500,19 +22574,19 @@ var _$drawing_68 = {}; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$colorscale_58 = require('../colorscale'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; /* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; /* removed: var _$alignment_143 = require('../../constants/alignment'); */; var __LINE_SPACING_68 = _$alignment_143.LINE_SPACING; var __DESELECTDIM_68 = _$interactions_144.DESELECTDIM; -/* removed: var _$subtypes_287 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_282 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_288 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_283 = require('../../traces/scatter/make_bubble_size_func'); */; var drawing = _$drawing_68 = {}; @@ -22522,7 +22596,7 @@ var drawing = _$drawing_68 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_163.isPlainObject(family)) { + if(_$lib_164.isPlainObject(family)) { color = family.color; size = family.size; family = family.family; @@ -22690,7 +22764,7 @@ drawing.fillGroupStyle = function(s) { shape.call(_$color_43.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_163.error(e, s); + _$lib_164.error(e, s); shape.remove(); } }); @@ -22753,8 +22827,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_253.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_282(trace); + if(_$registry_254.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_283(trace); sel.attr('d', function(d) { var r; @@ -22763,7 +22837,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_287.isBubble(trace) ? + r = _$subtypes_288.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -22803,10 +22877,10 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_163.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_43.defaultLine; + else if(_$lib_164.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_43.defaultLine; else lineColor = markerLine.color; - if(_$lib_163.isArrayOrTypedArray(marker.color)) { + if(_$lib_164.isArrayOrTypedArray(marker.color)) { fillColor = _$color_43.defaultLine; perPointGradient = true; } @@ -22859,7 +22933,7 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_163.identity); + .data([type + color1 + color2], _$lib_164.identity); gradient.exit().remove(); @@ -22902,9 +22976,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_164.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -23010,7 +23082,7 @@ drawing.selectedPointStyle = function(s, trace) { }); } - if(_$registry_253.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_254.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { var pt = _$d3_6.select(this); var mx = d.mx || marker.symbol || 0; @@ -23025,16 +23097,16 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_163.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_164.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_163.isArrayOrTypedArray(colorArray)) { + if(scl && _$lib_164.isArrayOrTypedArray(colorArray)) { return _$colorscale_58.makeColorScaleFunc( _$colorscale_58.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_163.identity; + else return _$lib_164.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; @@ -23054,7 +23126,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_184.lineCount(s) - 1) * __LINE_SPACING_68 + 1; + var numLines = (_$svg_text_utils_185.lineCount(s) - 1) * __LINE_SPACING_68 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -23073,7 +23145,7 @@ function extracTextFontSize(d, trace) { drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { var p = _$d3_6.select(this); - var text = _$lib_163.extractOption(d, trace, 'tx', 'text'); + var text = _$lib_164.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -23088,7 +23160,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_184.convertToTspans, gd) + .call(_$svg_text_utils_185.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -23216,33 +23288,28 @@ drawing.steps = function(shape) { // 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 = _$d3_6.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_147.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_164.ensureSingleById(_$d3_6.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_147.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_164.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; @@ -23287,7 +23354,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_163.extendFlat({}, out); + if(out) return _$lib_164.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -23331,7 +23398,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_163.extendFlat({}, out); + if(out) return _$lib_164.extendFlat({}, out); } } var testNode, tester; @@ -23349,7 +23416,7 @@ drawing.bBox = function(node, inTester, hash) { // standardize its position (and newline tspans if any) _$d3_6.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_184.positionText, 0, 0); + .call(_$svg_text_utils_185.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -23379,7 +23446,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_163.extendFlat({}, bb); + return _$lib_164.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -23404,15 +23471,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_6.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_6.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -23560,8 +23633,8 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; var _$calc_78 = function calc(gd) { var calcdata = gd.calcdata; @@ -23569,7 +23642,7 @@ var _$calc_78 = function calc(gd) { function makeCoerceHoverInfo(trace) { return function(val) { - return _$lib_163.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + return _$lib_164.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); }; } @@ -23580,9 +23653,9 @@ var _$calc_78 = function calc(gd) { // 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_253.traceIs(trace, 'pie')) continue; + if(_$registry_254.traceIs(trace, 'pie')) continue; - var fillFn = _$registry_253.traceIs(trace, '2dMap') ? paste : _$lib_163.fillArray; + var fillFn = _$registry_254.traceIs(trace, '2dMap') ? paste : _$lib_164.fillArray; fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); @@ -23598,7 +23671,7 @@ var _$calc_78 = function calc(gd) { }; function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_163.identity; + fn = fn || _$lib_164.identity; if(Array.isArray(traceAttr)) { cd[0][cdAttr] = fn(traceAttr); @@ -23616,13 +23689,33 @@ var _$helpers_82 = {}; 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; // look for either subplot or xaxis and yaxis attributes +// does not handle splom case _$helpers_82.getSubplot = function getSubplot(trace) { return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; }; +// is trace in given list of subplots? +// does handle splom case +_$helpers_82.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + + return subplots.indexOf(_$helpers_82.getSubplot(trace)) !== -1; +}; + // convenience functions for mapping all relevant axes _$helpers_82.flat = function flat(subplots, v) { var out = new Array(subplots.length); @@ -23765,7 +23858,7 @@ _$helpers_82.appendArrayPointValue = function(pointData, trace, pointNumber) { var key = getPointKey(astr); if(pointData[key] === undefined) { - var val = _$lib_163.nestedProperty(trace, astr).get(); + var val = _$lib_164.nestedProperty(trace, astr).get(); var pointVal = getPointData(val, pointNumber); if(pointVal !== undefined) pointData[key] = pointVal; @@ -23795,7 +23888,7 @@ _$helpers_82.appendArrayMultiPointValues = function(pointData, trace, pointNumbe var key = getPointKey(astr); if(pointData[key] === undefined) { - var val = _$lib_163.nestedProperty(trace, astr).get(); + var val = _$lib_164.nestedProperty(trace, astr).get(); var keyVal = new Array(pointNumbers.length); for(var j = 0; j < pointNumbers.length; j++) { @@ -23842,7 +23935,7 @@ function getPointData(val, pointNumber) { // works with our CSS cursor classes (see css/_cursor.scss) // to apply cursors to d3 single-element selections. // omit cursor to revert to the default. -var _$setCursor_182 = function setCursor(el3, csr) { +var _$setCursor_183 = function setCursor(el3, csr) { (el3.attr('class') || '').split(' ').forEach(function(cls) { if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); }); @@ -23861,7 +23954,7 @@ var _$setCursor_182 = function setCursor(el3, csr) { 'use strict'; -/* removed: var _$setCursor_182 = require('./setcursor'); */; +/* removed: var _$setCursor_183 = require('./setcursor'); */; var STASHATTR = 'data-savedcursor'; var NO_CURSOR = '!!'; @@ -23872,7 +23965,7 @@ var NO_CURSOR = '!!'; * by moving the name of the original cursor to the data-savedcursor attr. * omit cursor to revert to the previously set value. */ -var _$overrideCursor_174 = function overrideCursor(el3, csr) { +var _$overrideCursor_175 = function overrideCursor(el3, csr) { var savedCursor = el3.attr(STASHATTR); if(csr) { if(!savedCursor) { @@ -23888,13 +23981,13 @@ var _$overrideCursor_174 = function overrideCursor(el3, csr) { el3.attr(STASHATTR, NO_CURSOR); } } - _$setCursor_182(el3, csr); + _$setCursor_183(el3, csr); } else if(savedCursor) { el3.attr(STASHATTR, null); - if(savedCursor === NO_CURSOR) _$setCursor_182(el3); - else _$setCursor_182(el3, savedCursor); + if(savedCursor === NO_CURSOR) _$setCursor_183(el3); + else _$setCursor_183(el3, savedCursor); } }; @@ -23908,7 +24001,7 @@ var _$overrideCursor_174 = function overrideCursor(el3, csr) { 'use strict'; -var _$animation_attributes_200 = { +var _$animation_attributes_201 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -24055,7 +24148,7 @@ var _$frame_attributes_233 = { 'use strict'; /* removed: var _$attributes_49 = require('./attributes'); */; -var __extendFlat_51 = _$extend_156.extendFlat; +var __extendFlat_51 = _$extend_157.extendFlat; /* removed: var _$scales_62 = require('./scales.js'); */; /* @@ -24121,7 +24214,7 @@ var _$makeColorScaleAttributes_51 = function makeColorScaleAttributes(context, e 'use strict'; -var _$constants_271 = { +var _$constants_272 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -24149,13 +24242,13 @@ var _$constants_271 = { /* removed: var _$makeColorScaleAttributes_51 = require('../../components/colorscale/color_attributes'); */; /* removed: var _$attributes_44 = require('../../components/colorbar/attributes'); */; /* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; -var __dash_265 = _$attributes_67.dash; +var __dash_266 = _$attributes_67.dash; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$constants_271 = require('./constants'); */; -var __extendFlat_265 = _$extend_156.extendFlat; +/* removed: var _$constants_272 = require('./constants'); */; +var __extendFlat_266 = _$extend_157.extendFlat; -var _$attributes_265 = { +var _$attributes_266 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -24257,7 +24350,7 @@ var _$attributes_265 = { editType: 'plot', }, - dash: __extendFlat_265({}, __dash_265, {editType: 'style'}), + dash: __extendFlat_266({}, __dash_266, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -24297,7 +24390,7 @@ var _$attributes_265 = { editType: 'style', }, - marker: __extendFlat_265({ + marker: __extendFlat_266({ symbol: { valType: 'enumerated', values: _$drawing_68.symbolList, @@ -24366,7 +24459,7 @@ var _$attributes_265 = { }, colorbar: _$attributes_44, - line: __extendFlat_265({ + line: __extendFlat_266({ width: { valType: 'number', min: 0, @@ -24517,12 +24610,12 @@ var _$attributes_265 = { 'use strict'; -/* removed: var _$attributes_265 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_265.marker; +/* removed: var _$attributes_266 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_266.marker; var _$area_attributes_246 = { - r: _$attributes_265.r, - t: _$attributes_265.t, + r: _$attributes_266.r, + t: _$attributes_266.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -24543,11 +24636,11 @@ var _$area_attributes_246 = { 'use strict'; -/* removed: var _$layout_attributes_217 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_247 = _$extend_156.extendFlat; -var __overrideAll_247 = _$edit_types_190.overrideAll; +/* removed: var _$layout_attributes_218 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_247 = _$extend_157.extendFlat; +var __overrideAll_247 = _$edit_types_191.overrideAll; -var domainAttr = __extendFlat_247({}, _$layout_attributes_217.domain, { +var domainAttr = __extendFlat_247({}, _$layout_attributes_218.domain, { }); @@ -24647,7 +24740,7 @@ var _$axis_attributes_247 = __overrideAll_247({ } }, 'plot', 'nested'); -var _$plot_schema_196 = {}; +var _$plot_schema_197 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -24659,22 +24752,23 @@ var _$plot_schema_196 = {}; 'use strict'; -/* removed: var _$registry_253 = require('../registry'); */; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$registry_254 = require('../registry'); */; +/* removed: var _$lib_164 = require('../lib'); */; -/* removed: var _$attributes_202 = require('../plots/attributes'); */; +/* removed: var _$attributes_203 = require('../plots/attributes'); */; /* removed: var _$layout_attributes_236 = require('../plots/layout_attributes'); */; /* removed: var _$frame_attributes_233 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_200 = require('../plots/animation_attributes'); */; +/* removed: var _$animation_attributes_201 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet /* removed: var _$area_attributes_246 = require('../plots/polar/legacy/area_attributes'); */; /* removed: var _$axis_attributes_247 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_190 = require('./edit_types'); */; +/* removed: var _$edit_types_191 = require('./edit_types'); */; -var __extendFlat_196 = _$lib_163.extendFlat; -var __extendDeepAll_196 = _$lib_163.extendDeepAll; +var __extendFlat_197 = _$lib_164.extendFlat; +var __extendDeepAll_197 = _$lib_164.extendDeepAll; +var __isPlainObject_197 = _$lib_164.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -24682,10 +24776,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_196.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_196.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_196.DEPRECATED = DEPRECATED; -_$plot_schema_196.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_197.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_197.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_197.DEPRECATED = DEPRECATED; +_$plot_schema_197.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -24698,26 +24792,26 @@ _$plot_schema_196.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_196.get = function() { +_$plot_schema_197.get = function() { var traces = {}; - _$registry_253.allTypes.concat('area').forEach(function(type) { + _$registry_254.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_253.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_254.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_163.valObjectMeta, + valObjects: _$lib_164.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_190.traces, - layout: _$edit_types_190.layout + traces: _$edit_types_191.traces, + layout: _$edit_types_191.layout }, impliedEdits: { @@ -24730,7 +24824,7 @@ _$plot_schema_196.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_200) + animation: formatAttributes(_$animation_attributes_201) }; }; @@ -24761,7 +24855,7 @@ _$plot_schema_196.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_196.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_197.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -24773,10 +24867,10 @@ _$plot_schema_196.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_196.isValObject(attr)) return; + if(_$plot_schema_197.isValObject(attr)) return; - if(_$lib_163.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_196.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_197(attr) && attrName !== 'impliedEdits') { + _$plot_schema_197.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -24788,7 +24882,7 @@ _$plot_schema_196.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_196.isValObject = function(obj) { +_$plot_schema_197.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -24802,7 +24896,7 @@ _$plot_schema_196.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_196.findArrayAttributes = function(trace) { +_$plot_schema_197.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -24825,8 +24919,8 @@ _$plot_schema_196.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_163.nestedProperty(trace, astr).get(); - if(!_$lib_163.isArrayOrTypedArray(val)) return; + var val = _$lib_164.nestedProperty(trace, astr).get(); + if(!_$lib_164.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -24835,9 +24929,9 @@ _$plot_schema_196.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_196.crawl(_$attributes_202, callback); + _$plot_schema_197.crawl(_$attributes_203, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_196.crawl(trace._module.attributes, callback); + _$plot_schema_197.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -24850,7 +24944,7 @@ _$plot_schema_196.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_196.crawl(module.attributes, callback, 1); + _$plot_schema_197.crawl(module.attributes, callback, 1); } } } @@ -24862,8 +24956,8 @@ _$plot_schema_196.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_196.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_163.filterUnique(arrayAttributes); + _$plot_schema_197.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_164.filterUnique(arrayAttributes); } return arrayAttributes; @@ -24884,18 +24978,19 @@ _$plot_schema_196.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_196.getTraceValObject = function(trace, parts) { +_$plot_schema_197.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_253.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_254.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } @@ -24906,7 +25001,7 @@ _$plot_schema_196.getTraceValObject = function(trace, parts) { // 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_253.modules[trace.type || _$attributes_202.type.dflt] || {})._module; + if(!_module) _module = (_$registry_254.modules[trace.type || _$attributes_203.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -24921,7 +25016,7 @@ _$plot_schema_196.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_202[head]; + if(!valObject) valObject = _$attributes_203[head]; } return recurseIntoValObject(valObject, parts, i); @@ -24940,7 +25035,7 @@ _$plot_schema_196.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_196.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_197.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -24991,8 +25086,8 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_253.componentsRegistry) { - _module = _$registry_253.componentsRegistry[key]; + for(key in _$registry_254.componentsRegistry) { + _module = _$registry_254.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } @@ -25022,7 +25117,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_163.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_197(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -25069,7 +25164,7 @@ function getTraceAttributes(type) { basePlotModule = {}; } else { - _module = _$registry_253.modules[type]._module, + _module = _$registry_254.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -25079,14 +25174,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_196(attributes, _$attributes_202); + __extendDeepAll_197(attributes, _$attributes_203); // module attributes - __extendDeepAll_196(attributes, _module.attributes); + __extendDeepAll_197(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_196(attributes, basePlotModule.attributes); + __extendDeepAll_197(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -25101,7 +25196,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_196(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_197(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -25113,21 +25208,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_196(layoutAttributes, _$layout_attributes_236); + __extendDeepAll_197(layoutAttributes, _$layout_attributes_236); // add base plot module layout attributes - for(key in _$registry_253.subplotsRegistry) { - _module = _$registry_253.subplotsRegistry[key]; + for(key in _$registry_254.subplotsRegistry) { + _module = _$registry_254.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -25136,8 +25230,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_253.componentsRegistry) { - _module = _$registry_253.componentsRegistry[key]; + for(key in _$registry_254.componentsRegistry) { + _module = _$registry_254.componentsRegistry[key]; var schema = _module.schema; /* @@ -25168,12 +25262,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_253.transformsRegistry[type]; - var attributes = __extendDeepAll_196({}, _module.attributes); + var _module = _$registry_254.transformsRegistry[type]; + var attributes = __extendDeepAll_197({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_253.componentsRegistry).forEach(function(k) { - var _module = _$registry_253.componentsRegistry[k]; + Object.keys(_$registry_254.componentsRegistry).forEach(function(k) { + var _module = _$registry_254.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -25189,7 +25283,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_163.extendDeepAll({}, _$frame_attributes_233) + frames: _$lib_164.extendDeepAll({}, _$frame_attributes_233) }; formatAttributes(attrs); @@ -25200,6 +25294,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -25216,7 +25311,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_196.isValObject(attr)) { + if(_$plot_schema_197.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -25228,13 +25323,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_163.isPlainObject(attr)) { + else if(__isPlainObject_197(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_196.crawl(attrs, callback); + _$plot_schema_197.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -25253,35 +25348,58 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_196.crawl(attrs, callback); + _$plot_schema_197.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_197(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_196(layoutAttributes, { + __extendFlat_197(layoutAttributes, { radialaxis: _$axis_attributes_247.radialaxis, angularaxis: _$axis_attributes_247.angularaxis }); - __extendFlat_196(layoutAttributes, _$axis_attributes_247.layout); + __extendFlat_197(layoutAttributes, _$axis_attributes_247.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_163.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_196({}, _module.layoutAttributes); + var np = _$lib_164.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_197({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_163.nestedProperty(baseAttrs, astr); + var np = _$lib_164.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_196(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_197(np.get() || {}, newAttrs)); } -var _$axis_ids_208 = {}; +var _$axis_ids_209 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -25292,30 +25410,30 @@ var _$axis_ids_208 = {}; 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; -/* removed: var _$constants_210 = require('./constants'); */; +/* removed: var _$constants_211 = require('./constants'); */; // 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. -_$axis_ids_208.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_210.AX_ID_PATTERN)) return; +_$axis_ids_209.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_211.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_208.name2id = function name2id(name) { - if(!name.match(_$constants_210.AX_NAME_PATTERN)) return; +_$axis_ids_209.name2id = function name2id(name) { + if(!name.match(_$constants_211.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_208.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_210.AX_ID_PATTERN)) return; +_$axis_ids_209.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_211.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -25324,11 +25442,11 @@ _$axis_ids_208.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_208.list = function(gd, axLetter, only2d) { +_$axis_ids_209.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_208.listIds(gd, axLetter); + var idList = _$axis_ids_209.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -25353,7 +25471,7 @@ _$axis_ids_208.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_208.listIds = function(gd, axLetter) { +_$axis_ids_209.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -25364,35 +25482,35 @@ _$axis_ids_208.listIds = function(gd, axLetter) { // 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 -_$axis_ids_208.getFromId = function(gd, id, type) { +_$axis_ids_209.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[_$axis_ids_208.id2name(id)]; + return fullLayout[_$axis_ids_209.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_208.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_209.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_253.traceIs(fullTrace, 'gl3d')) { + if(_$registry_254.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_208.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_209.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_208.idSort = function(id1, id2) { +_$axis_ids_209.idSort = function(id1, id2) { var letter1 = id1.charAt(0); var letter2 = id2.charAt(0); if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1; @@ -25410,8 +25528,8 @@ var _$command_230 = {}; 'use strict'; -/* removed: var _$registry_253 = require('../registry'); */; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$registry_254 = require('../registry'); */; +/* removed: var _$lib_164 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -25515,7 +25633,7 @@ _$command_230.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_163.log('Unable to automatically bind plot updates to API command'); + _$lib_164.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -25633,7 +25751,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_163.nestedProperty(container, binding.prop).get(); + value = _$lib_164.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -25665,7 +25783,7 @@ function bindingValueHasChanged(gd, binding, cache) { _$command_230.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_253.apiMethodRegistry[method]; + var _method = _$registry_254.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -25674,7 +25792,7 @@ _$command_230.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_163.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_164.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; @@ -25724,7 +25842,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_163.isPlainObject(astr)) { + } else if(_$lib_164.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -25748,7 +25866,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_163.isPlainObject(astr)) { + } else if(_$lib_164.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -25814,7 +25932,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_163.isPlainObject(attr)) { + if(_$lib_164.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -25823,6 +25941,32 @@ function crawl(attrs, callback, path, depth) { }); } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_252 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + var _$plots_245 = {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -25838,25 +25982,27 @@ var _$plots_245 = {}; /* removed: var _$d3_6 = require('d3'); */; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$registry_253 = require('../registry'); */; -/* removed: var _$plot_schema_196 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_208 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_163 = require('../lib'); */; -var _ = _$lib_163._; +/* removed: var _$registry_254 = require('../registry'); */; +/* removed: var _$plot_schema_197 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_164 = require('../lib'); */; /* removed: var _$color_43 = require('../components/color'); */; var __BADNUM_245 = _$numerical_145.BADNUM; -var plots = _$plots_245 = {}; +/* removed: var _$axis_ids_209 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_245 = _$sort_modules_252.sortBasePlotModules; -/* removed: var _$animation_attributes_200 = require('./animation_attributes'); */; +/* removed: var _$animation_attributes_201 = require('./animation_attributes'); */; /* removed: var _$frame_attributes_233 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_163.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_164.relinkPrivateKeys; +var _ = _$lib_164._; + +var plots = _$plots_245 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_163.extendFlat(plots, _$registry_253); +_$lib_164.extendFlat(plots, _$registry_254); -plots.attributes = _$attributes_202; +plots.attributes = _$attributes_203; plots.attributes.type.values = plots.allTypes; plots.fontAttrs = _$font_attributes_232; plots.layoutAttributes = _$layout_attributes_236; @@ -25876,15 +26022,15 @@ plots.hasSimpleAPICommandBindings = _$command_230.hasSimpleAPICommandBindings; // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_163.getGraphDiv(gd); + gd = _$lib_164.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_253.getComponentMethod('annotations', 'draw')(gd); - _$registry_253.getComponentMethod('legend', 'draw')(gd); + _$registry_254.getComponentMethod('annotations', 'draw')(gd); + _$registry_254.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -25897,7 +26043,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_163.getGraphDiv(gd); + gd = _$lib_164.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -25928,7 +26074,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_253.call('relayout', gd, {autosize: true}).then(function() { + _$registry_254.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -25958,12 +26104,8 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_164.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', 'fill': _$color_43.defaultLine, @@ -25975,12 +26117,11 @@ plots.addLinks = function(gd) { links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -26118,6 +26259,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -26152,7 +26295,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -26195,12 +26337,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_254.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_164.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_164.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_164.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -26211,7 +26379,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -26220,6 +26388,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -26230,7 +26409,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -26242,17 +26421,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_208.list(gd); + var axList = _$axis_ids_209.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -26262,6 +26441,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_245); }; /** @@ -26280,7 +26462,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_253.subplotsRegistry; + var subplotsRegistry = _$registry_254.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -26293,7 +26475,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_163.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_164.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -26314,14 +26496,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_163.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_164.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_163.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_164.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -26366,7 +26548,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_253.localeRegistry; + locales = _$registry_254.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -26375,7 +26557,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_253.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_254.localeRegistry.en.format); return formatObj; } @@ -26427,30 +26609,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_254.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -26458,7 +26638,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -26530,8 +26710,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_208.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_208.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_209.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_209.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -26576,13 +26756,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_208.list(mockGd, null, true); + var axList = _$axis_ids_209.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_208.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_209.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -26604,7 +26784,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_208.getFromId(mockGd, ax.anchor); + _$axis_ids_209.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -26633,7 +26813,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_208.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_209.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -26674,17 +26854,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_196.crawl( + _$plot_schema_197.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_163.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_164.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_163.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_164.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -26706,8 +26886,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_163.pushUnique(modules, _module); - _$lib_163.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_164.pushUnique(modules, _module); + _$lib_164.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -26767,11 +26947,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_253.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_254.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_253.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_254.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -26800,7 +26980,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(opts || {}, optsOut, _$animation_attributes_200, attr, dflt); + return _$lib_164.coerce(opts || {}, optsOut, _$animation_attributes_201, attr, dflt); } coerce('mode'); @@ -26832,7 +27012,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(opts || {}, optsOut, _$animation_attributes_200.frame, attr, dflt); + return _$lib_164.coerce(opts || {}, optsOut, _$animation_attributes_201.frame, attr, dflt); } coerce('duration'); @@ -26845,7 +27025,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(opts || {}, optsOut, _$animation_attributes_200.transition, attr, dflt); + return _$lib_164.coerce(opts || {}, optsOut, _$animation_attributes_201.transition, attr, dflt); } coerce('duration'); @@ -26858,7 +27038,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(frameIn, frameOut, _$frame_attributes_233, attr, dflt); + return _$lib_164.coerce(frameIn, frameOut, _$frame_attributes_233, attr, dflt); } coerce('group'); @@ -26879,7 +27059,7 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) var i; function coerce(attr, dflt) { - return _$lib_163.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_164.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -26895,9 +27075,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -26907,18 +27087,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_163.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_164.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_163.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_164.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_163.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_164.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_163.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_164.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -26928,12 +27108,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_253.traceIs(traceOut, 'showLegend')) { + if(_$registry_254.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_253.getComponentMethod( + _$registry_254.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -26942,12 +27122,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_163.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_164.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_253.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_254.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_253.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_254.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -26991,17 +27171,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_163.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_164.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_163.pushUnique(transformModules, _module); + _$lib_164.pushUnique(transformModules, _module); } else { - transformOut = _$lib_163.extendFlat({}, transformIn); + transformOut = _$lib_164.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -27033,14 +27213,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_163.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_164.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_163.coerceFont(coerce, 'font'); + var globalFont = _$lib_164.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_163.coerceFont(coerce, 'titlefont', { + _$lib_164.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -27068,7 +27248,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_253.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_254.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -27079,12 +27259,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_253.getComponentMethod( + _$registry_254.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_253.getComponentMethod( + _$registry_254.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -27096,7 +27276,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_163.isPlotDiv(gd); + var isPlotDiv = _$lib_164.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -27184,11 +27364,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_253.componentsRegistry; + var componentsRegistry = _$registry_254.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_253.subplotsRegistry.cartesian; + var Cartesian = _$registry_254.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -27207,13 +27387,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_253.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_254.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_163.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_164.subplotSort); } // base plot module layout defaults @@ -27285,7 +27465,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_163.clearThrottle(); + _$lib_164.clearThrottle(); // data and layout delete gd.data; @@ -27341,7 +27521,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_163.pushUnique(styleModules, _module.style); + _$lib_164.pushUnique(styleModules, _module.style); } } @@ -27496,7 +27676,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_253.call('plot', gd); + return _$registry_254.call('plot', gd); } }; @@ -27537,7 +27717,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_163.isPlainObject(d)) { + if(_$lib_164.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -27560,7 +27740,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_163.isPlainObject(d.stream)) { + if(!_$lib_164.isPlainObject(d.stream)) { continue; } } @@ -27586,7 +27766,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_163.isJSDate(d)) return _$lib_163.ms2DateTimeLocal(+d); + if(_$lib_164.isJSDate(d)) return _$lib_164.ms2DateTimeLocal(+d); return d; } @@ -27783,8 +27963,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_163.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_163.expandObjectPaths(copy); + var copy = _$lib_164.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_164.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -27792,29 +27972,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_163.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_164.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_163.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_164.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_163.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_164.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_163.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_164.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_163.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_164.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_163.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_164.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -27839,7 +28019,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_253.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_254.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -27913,7 +28093,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_163.expandObjectPaths(_$lib_163.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_164.expandObjectPaths(_$lib_164.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -27940,7 +28120,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_253.getComponentMethod('errorbars', 'calc')(gd); + _$registry_254.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -27988,7 +28168,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_253.call('redraw', gd); + return _$registry_254.call('redraw', gd); }); } @@ -28020,7 +28200,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_163.expandObjectPaths(layout); + var newLayout = _$lib_164.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -28030,7 +28210,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_163.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_164.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -28060,7 +28240,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_253.call('redraw', gd); + return _$registry_254.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -28095,7 +28275,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_163.syncOrAsync(seq, gd); + var transitionStarting = _$lib_164.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -28107,7 +28287,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_208.list(gd), + var axList = _$axis_ids_209.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -28151,7 +28331,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_196.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_197.findArrayAttributes(trace); } // add polar axes to axis list @@ -28195,14 +28375,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -28237,7 +28418,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_253.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_254.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -28288,7 +28474,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_163.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_164.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -28310,11 +28496,11 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$color_43 = require('../color'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; /* removed: var _$interactions_144 = require('../../constants/interactions'); */; var _$titles_136 = { @@ -28395,10 +28581,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_164.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -28416,7 +28599,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_163.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_164.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -28444,7 +28627,7 @@ function draw(gd, titleClass, options) { 'font-weight': _$plots_245.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_184.convertToTspans, gd); + .call(_$svg_text_utils_185.convertToTspans, gd); return _$plots_245.previousPromises(gd); } @@ -28494,7 +28677,7 @@ function draw(gd, titleClass, options) { avoid.selection.each(function() { var avoidbb = _$drawing_68.bBox(this); - if(_$lib_163.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_164.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -28534,12 +28717,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_184.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_185.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_253.call('restyle', gd, prop, text, traceIndex); + _$registry_254.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_253.call('relayout', gd, prop, text); + _$registry_254.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -28548,7 +28731,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_184.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_185.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -28569,10 +28752,10 @@ function draw(gd, titleClass, options) { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -var __FP_SAFE_204 = _$numerical_145.FP_SAFE; +/* removed: var _$lib_164 = require('../../lib'); */; +var __FP_SAFE_205 = _$numerical_145.FP_SAFE; -var _$autorange_204 = { +var _$autorange_205 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -28617,7 +28800,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_163.simpleMap(ax.range, ax.r2l); + var rng = _$lib_164.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -28710,7 +28893,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_163.simpleMap(newRange, ax.l2r || Number); + return _$lib_164.simpleMap(newRange, ax.l2r || Number); } /* @@ -28742,7 +28925,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_163.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_164.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -28764,7 +28947,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_163.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_164.extendFlat({}, axeRangeOpts); } } @@ -28777,6 +28960,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -28837,14 +29022,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_204) vmax = v; + if(v > vmax && v < __FP_SAFE_205) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_204) vmin = v; - if(v > vmax && v < __FP_SAFE_204) vmax = v; + if(v < vmin && v > -__FP_SAFE_205) vmin = v; + if(v > vmax && v < __FP_SAFE_205) vmax = v; } } @@ -28878,7 +29063,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_204 : __lessOrEqual_204; + var atLeastAsExtreme = k ? __greaterOrEqual_205 : __lessOrEqual_205; includeThis = true; /* @@ -28929,11 +29114,11 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_9(v) && Math.abs(v) < __FP_SAFE_204; + return _$fastIsnumeric_9(v) && Math.abs(v) < __FP_SAFE_205; } -function __lessOrEqual_204(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_204(v0, v1) { return v0 >= v1; } +function __lessOrEqual_205(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_205(v0, v1) { return v0 >= v1; } /** * Copyright 2012-2018, Plotly, Inc. @@ -28948,10 +29133,10 @@ function __greaterOrEqual_204(v0, v1) { return v0 >= v1; } /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -var __BADNUM_206 = _$numerical_145.BADNUM; +/* removed: var _$lib_164 = require('../../lib'); */; +var __BADNUM_207 = _$numerical_145.BADNUM; -var _$autoType_206 = function autoType(array, calendar) { +var _$autoType_207 = function autoType(array, calendar) { if(moreDates(array, calendar)) return 'date'; if(category(array)) return 'category'; if(linearOK(array)) return 'linear'; @@ -28984,7 +29169,7 @@ function moreDates(a, calendar) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_163.isDateTime(ai, calendar)) dcnt += 1; + if(_$lib_164.isDateTime(ai, calendar)) dcnt += 1; if(_$fastIsnumeric_9(ai)) ncnt += 1; } @@ -29002,7 +29187,7 @@ function category(a) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_163.cleanNumber(ai) !== __BADNUM_206) curvenums++; + if(_$lib_164.cleanNumber(ai) !== __BADNUM_207) curvenums++; else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; } @@ -29023,18 +29208,18 @@ function category(a) { /* removed: var _$d3_6 = require('d3'); */; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -var cleanNumber = _$lib_163.cleanNumber; -var ms2DateTime = _$lib_163.ms2DateTime; -var dateTime2ms = _$lib_163.dateTime2ms; -var ensureNumber = _$lib_163.ensureNumber; +/* removed: var _$lib_164 = require('../../lib'); */; +var cleanNumber = _$lib_164.cleanNumber; +var ms2DateTime = _$lib_164.ms2DateTime; +var dateTime2ms = _$lib_164.dateTime2ms; +var ensureNumber = _$lib_164.ensureNumber; /* removed: var _$numerical_145 = require('../../constants/numerical'); */; var __FP_SAFE_224 = _$numerical_145.FP_SAFE; var __BADNUM_224 = _$numerical_145.BADNUM; -/* removed: var _$constants_210 = require('./constants'); */; -/* removed: var _$axis_ids_208 = require('./axis_ids'); */; +/* removed: var _$constants_211 = require('./constants'); */; +/* removed: var _$axis_ids_209 = require('./axis_ids'); */; function fromLog(v) { return Math.pow(10, v); @@ -29226,7 +29411,7 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { * 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_163.identity; + ax.d2r = ax.r2d = _$lib_164.identity; ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; @@ -29234,7 +29419,7 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { 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_163.cleanDate(v, __BADNUM_224, ax.calendar); }; + ax.cleanPos = function(v) { return _$lib_164.cleanDate(v, __BADNUM_224, ax.calendar); }; } else if(ax.type === 'category') { // d is categories (string) @@ -29291,39 +29476,39 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { if(!opts) opts = {}; if(!rangeAttr) rangeAttr = 'range'; - var range = _$lib_163.nestedProperty(ax, rangeAttr).get(); + var range = _$lib_164.nestedProperty(ax, rangeAttr).get(); var i, dflt; - if(ax.type === 'date') dflt = _$lib_163.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_210.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_210.DFLTRANGEX; + if(ax.type === 'date') dflt = _$lib_164.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_211.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_211.DFLTRANGEX; // make sure we don't later mutate the defaults dflt = dflt.slice(); if(!range || range.length !== 2) { - _$lib_163.nestedProperty(ax, rangeAttr).set(dflt); + _$lib_164.nestedProperty(ax, rangeAttr).set(dflt); return; } if(ax.type === 'date') { // check if milliseconds or js date objects are provided for range // and convert to date strings - range[0] = _$lib_163.cleanDate(range[0], __BADNUM_224, ax.calendar); - range[1] = _$lib_163.cleanDate(range[1], __BADNUM_224, ax.calendar); + range[0] = _$lib_164.cleanDate(range[0], __BADNUM_224, ax.calendar); + range[1] = _$lib_164.cleanDate(range[1], __BADNUM_224, ax.calendar); } for(i = 0; i < 2; i++) { if(ax.type === 'date') { - if(!_$lib_163.isDateTime(range[i], ax.calendar)) { + if(!_$lib_164.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_163.constrain(ax.r2l(range[0]), - _$lib_163.MIN_MS + 1000, _$lib_163.MAX_MS - 1000); + var linCenter = _$lib_164.constrain(ax.r2l(range[0]), + _$lib_164.MIN_MS + 1000, _$lib_164.MAX_MS - 1000); range[0] = ax.l2r(linCenter - 1000); range[1] = ax.l2r(linCenter + 1000); break; @@ -29365,7 +29550,7 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { // make sure we have a domain (pull it in from the axis // this one is overlaying if necessary) if(ax.overlaying) { - var ax2 = _$axis_ids_208.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + var ax2 = _$axis_ids_209.getFromId({ _fullLayout: fullLayout }, ax.overlaying); ax.domain = ax2.domain; } @@ -29418,7 +29603,7 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { arrayIn = trace[axLetter]; len = trace._length || arrayIn.length; - if(_$lib_163.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(_$lib_164.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { if(len === arrayIn.length) { return arrayIn; } else if(arrayIn.subarray) { @@ -29459,11 +29644,15 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { 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]); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } }; ax.clearCalc = function() { @@ -29507,7 +29696,7 @@ var _$setConvert_224 = function setConvert(ax, fullLayout) { delete ax._forceTick0; }; -var _$axes_205 = {}; +var _$axes_206 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29523,9 +29712,9 @@ var _$axes_205 = {}; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; /* removed: var _$titles_136 = require('../../components/titles'); */; /* removed: var _$color_43 = require('../../components/color'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; @@ -29533,33 +29722,33 @@ var _$axes_205 = {}; /* removed: var _$numerical_145 = require('../../constants/numerical'); */; var ONEAVGYEAR = _$numerical_145.ONEAVGYEAR; var ONEAVGMONTH = _$numerical_145.ONEAVGMONTH; -var __ONEDAY_205 = _$numerical_145.ONEDAY; -var __ONEHOUR_205 = _$numerical_145.ONEHOUR; -var __ONEMIN_205 = _$numerical_145.ONEMIN; -var __ONESEC_205 = _$numerical_145.ONESEC; +var __ONEDAY_206 = _$numerical_145.ONEDAY; +var __ONEHOUR_206 = _$numerical_145.ONEHOUR; +var __ONEMIN_206 = _$numerical_145.ONEMIN; +var __ONESEC_206 = _$numerical_145.ONESEC; var MINUS_SIGN = _$numerical_145.MINUS_SIGN; -var __BADNUM_205 = _$numerical_145.BADNUM; +var __BADNUM_206 = _$numerical_145.BADNUM; var MID_SHIFT = _$alignment_143.MID_SHIFT; -var __LINE_SPACING_205 = _$alignment_143.LINE_SPACING; +var __LINE_SPACING_206 = _$alignment_143.LINE_SPACING; -var axes = _$axes_205 = {}; +var axes = _$axes_206 = {}; axes.setConvert = _$setConvert_224; -/* removed: var _$autoType_206 = require('./axis_autotype'); */; +/* removed: var _$autoType_207 = require('./axis_autotype'); */; -/* removed: var _$axis_ids_208 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_208.id2name; -axes.name2id = _$axis_ids_208.name2id; -axes.cleanId = _$axis_ids_208.cleanId; -axes.list = _$axis_ids_208.list; -axes.listIds = _$axis_ids_208.listIds; -axes.getFromId = _$axis_ids_208.getFromId; -axes.getFromTrace = _$axis_ids_208.getFromTrace; +/* removed: var _$axis_ids_209 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_209.id2name; +axes.name2id = _$axis_ids_209.name2id; +axes.cleanId = _$axis_ids_209.cleanId; +axes.list = _$axis_ids_209.list; +axes.listIds = _$axis_ids_209.listIds; +axes.getFromId = _$axis_ids_209.getFromId; +axes.getFromTrace = _$axis_ids_209.getFromTrace; -/* removed: var _$autorange_204 = require('./autorange'); */; -axes.expand = _$autorange_204.expand; -axes.getAutoRange = _$autorange_204.getAutoRange; +/* removed: var _$autorange_205 = require('./autorange'); */; +axes.expand = _$autorange_205.expand; +axes.getAutoRange = _$autorange_205.getAutoRange; /* * find the list of possible axes to reference with an xref or yref attribute @@ -29590,7 +29779,7 @@ axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption }; // xref, yref - return _$lib_163.coerce(containerIn, containerOut, attrDef, refAttr); + return _$lib_164.coerce(containerIn, containerOut, attrDef, refAttr); }; /* @@ -29619,7 +29808,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { var cleanPos, pos; if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_163.ensureNumber; + cleanPos = _$lib_164.ensureNumber; pos = coerce(attr, dflt); } else { var ax = axes.getFromId(gd, axRef); @@ -29633,7 +29822,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { axes.cleanPosition = function(pos, gd, axRef) { var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_163.ensureNumber : + _$lib_164.ensureNumber : axes.getFromId(gd, axRef).cleanPos; return cleanPos(pos); @@ -29653,7 +29842,7 @@ var getDataConversions = axes.getDataConversions = function(gd, trace, target, t // setup the data-to-calc method. if(Array.isArray(d2cTarget)) { ax = { - type: _$autoType_206(targetArray), + type: _$autoType_207(targetArray), _categories: [] }; axes.setConvert(ax); @@ -29789,8 +29978,8 @@ axes.saveShowSpikeInitial = function(gd, overwrite) { }; axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_163.aggNums(Math.min, null, data), - dataMax = _$lib_163.aggNums(Math.max, null, data); + var dataMin = _$lib_164.aggNums(Math.min, null, data), + dataMax = _$lib_164.aggNums(Math.max, null, data); if(!calendar) calendar = ax.calendar; @@ -29810,12 +29999,12 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { // 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_163.distinctVals(data), + var distinctData = _$lib_164.distinctVals(data), msexp = Math.pow(10, Math.floor( Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_163.roundUp( + minSize = msexp * _$lib_164.roundUp( distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_163.stdev(data) / + size0 = Math.max(minSize, 2 * _$lib_164.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4)); // fallback if ax.d2c output BADNUMs @@ -29835,7 +30024,7 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { else { dummyAx = { type: ax.type, - range: _$lib_163.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + range: _$lib_164.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), calendar: calendar }; } @@ -29934,7 +30123,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_163.findExactDates(data, calendar); + var stats = _$lib_164.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; @@ -29946,21 +30135,21 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // 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_205 * 1.5; + binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + __ONEDAY_206 * 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_205 * 15.5; + binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + __ONEDAY_206 * 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_205 / 2; + binStart -= __ONEDAY_206 / 2; } var nextBinStart = axes.tickIncrement(binStart, dtick); @@ -29975,7 +30164,7 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // ensure we have tick0, dtick, and tick rounding calculated axes.prepTicks = function(ax) { - var rng = _$lib_163.simpleMap(ax.range, ax.r2l); + var rng = _$lib_164.simpleMap(ax.range, ax.r2l); // calculate max number of (auto) ticks to display based on plot size if(ax.tickmode === 'auto' || !ax.dtick) { @@ -29988,7 +30177,7 @@ axes.prepTicks = function(ax) { } else { minPx = ax._id.charAt(0) === 'y' ? 40 : 80; - nt = _$lib_163.constrain(ax._length / minPx, 4, 9) + 1; + nt = _$lib_164.constrain(ax._length / minPx, 4, 9) + 1; } // radial axes span half their domain, @@ -30023,7 +30212,7 @@ axes.prepTicks = function(ax) { // or codes to this effect for log and date scales axes.calcTicks = function calcTicks(ax) { axes.prepTicks(ax); - var rng = _$lib_163.simpleMap(ax.range, ax.r2l); + var rng = _$lib_164.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 @@ -30091,7 +30280,7 @@ function arrayTicks(ax) { var vals = ax.tickvals, text = ax.ticktext, ticksOut = new Array(vals.length), - rng = _$lib_163.simpleMap(ax.range, ax.r2l), + rng = _$lib_164.simpleMap(ax.range, ax.r2l), r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, tickMin = Math.min(r0expanded, r1expanded), @@ -30140,7 +30329,7 @@ var roundBase10 = [2, 5, 10], roundAngles = [15, 30, 45, 90, 180]; function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_163.roundUp(roughDTick / base, roundingSet); + return base * _$lib_164.roundUp(roughDTick / base, roundingSet); } // autoTicks: calculate best guess at pleasant ticks for this axis @@ -30167,7 +30356,7 @@ axes.autoTicks = function(ax, roughDTick) { } if(ax.type === 'date') { - ax.tick0 = _$lib_163.dateTick0(ax.calendar); + ax.tick0 = _$lib_164.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; @@ -30181,21 +30370,21 @@ axes.autoTicks = function(ax, roughDTick) { roughDTick /= ONEAVGMONTH; ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); } - else if(roughX2 > __ONEDAY_205) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_205, roundDays); + else if(roughX2 > __ONEDAY_206) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_206, 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_163.dateTick0(ax.calendar, true); + ax.tick0 = _$lib_164.dateTick0(ax.calendar, true); } - else if(roughX2 > __ONEHOUR_205) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_205, roundBase24); + else if(roughX2 > __ONEHOUR_206) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_206, roundBase24); } - else if(roughX2 > __ONEMIN_205) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_205, roundBase60); + else if(roughX2 > __ONEMIN_206) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_206, roundBase60); } - else if(roughX2 > __ONESEC_205) { - ax.dtick = roundDTick(roughDTick, __ONESEC_205, roundBase60); + else if(roughX2 > __ONESEC_206) { + ax.dtick = roundDTick(roughDTick, __ONESEC_206, roundBase60); } else { // milliseconds @@ -30205,7 +30394,7 @@ axes.autoTicks = function(ax, roughDTick) { } else if(ax.type === 'log') { ax.tick0 = 0; - var rng = _$lib_163.simpleMap(ax.range, ax.r2l); + var rng = _$lib_164.simpleMap(ax.range, ax.r2l); if(roughDTick > 0.7) { // only show powers of 10 @@ -30286,9 +30475,9 @@ function autoTickRound(ax) { // 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_205 && tick0len <= 10) || (dtick >= __ONEDAY_205 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_205 && tick0len <= 16) || (dtick >= __ONEHOUR_205)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_205 && tick0len <= 19) || (dtick >= __ONEMIN_205)) ax._tickround = 'S'; + else if((dtick >= __ONEDAY_206 && tick0len <= 10) || (dtick >= __ONEDAY_206 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_206 && tick0len <= 16) || (dtick >= __ONEHOUR_206)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_206 && tick0len <= 19) || (dtick >= __ONEMIN_206)) 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 @@ -30335,7 +30524,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { dtSigned = axSign * Number(dtick.substr(1)); // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_163.incrementMonth(x, dtSigned, calendar); + if(tType === 'M') return _$lib_164.incrementMonth(x, dtSigned, calendar); // Log scales: Linear, Digits else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; @@ -30345,7 +30534,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, x2 = x + axSign * 0.01, - frac = _$lib_163.roundUp(_$lib_163.mod(x2, 1), tickset, axrev); + frac = _$lib_164.roundUp(_$lib_164.mod(x2, 1), tickset, axrev); return Math.floor(x2) + Math.log(_$d3_6.round(Math.pow(10, frac), 1)) / Math.LN10; @@ -30356,7 +30545,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { // calculate the first tick on an axis axes.tickFirst = function(ax) { var r2l = ax.r2l || Number, - rng = _$lib_163.simpleMap(ax.range, r2l), + rng = _$lib_164.simpleMap(ax.range, r2l), axrev = rng[1] < rng[0], sRound = axrev ? Math.floor : Math.ceil, // add a tiny extra bit to make sure we get ticks @@ -30370,7 +30559,7 @@ axes.tickFirst = function(ax) { // make sure no ticks outside the category list if(ax.type === 'category') { - tmin = _$lib_163.constrain(tmin, 0, ax._categories.length - 1); + tmin = _$lib_164.constrain(tmin, 0, ax._categories.length - 1); } return tmin; } @@ -30400,7 +30589,7 @@ axes.tickFirst = function(ax) { t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); cnt++; } - _$lib_163.error('tickFirst did not converge', ax); + _$lib_164.error('tickFirst did not converge', ax); return t0; } @@ -30411,7 +30600,7 @@ axes.tickFirst = function(ax) { } else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_163.roundUp(_$lib_163.mod(r0, 1), tickset, axrev); + frac = _$lib_164.roundUp(_$lib_164.mod(r0, 1), tickset, axrev); return Math.floor(r0) + Math.log(_$d3_6.round(Math.pow(10, frac), 1)) / Math.LN10; @@ -30434,7 +30623,7 @@ axes.tickText = function(ax, x, hover) { tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_163.simpleMap(ax.range, ax.r2l), + var rng = _$lib_164.simpleMap(ax.range, ax.r2l), 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; @@ -30491,7 +30680,7 @@ axes.tickText = function(ax, x, hover) { * it's different from `val`. */ axes.hoverLabelText = function(ax, val, val2) { - if(val2 !== __BADNUM_205 && val2 !== val) { + if(val2 !== __BADNUM_206 && val2 !== val) { return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } @@ -30534,7 +30723,7 @@ function formatDate(ax, out, hover, extraPrecision) { else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; } - var dateStr = _$lib_163.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + var dateStr = _$lib_164.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), headStr; var splitIndex = dateStr.indexOf('\n'); @@ -30599,7 +30788,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); } - else if(_$fastIsnumeric_9(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_163.mod(x + 0.01, 1) < 0.1))) { + else if(_$fastIsnumeric_9(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_164.mod(x + 0.01, 1) < 0.1))) { var p = Math.round(x); if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || (isSIFormat(ax.exponentformat) && beyondSI(p))) { @@ -30618,7 +30807,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { } } else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_163.mod(x, 1)))); + out.text = String(Math.round(Math.pow(10, _$lib_164.mod(x, 1)))); out.fontSize *= 0.75; } else throw 'unrecognized dtick ' + String(dtick); @@ -30673,7 +30862,7 @@ function formatAngle(ax, out, hover, extraPrecision, hideexp) { var frac = num2frac(num); if(frac[1] >= 100) { - out.text = numFormat(_$lib_163.deg2rad(out.x), ax, hideexp, extraPrecision); + out.text = numFormat(_$lib_164.deg2rad(out.x), ax, hideexp, extraPrecision); } else { var isNeg = out.x < 0; @@ -30821,7 +31010,7 @@ function numFormat(v, ax, fmtoverride, hover) { if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); } // insert appropriate decimal point and thousands separator - v = _$lib_163.numSeparate(v, ax._separators, separatethousands); + v = _$lib_164.numSeparate(v, ax._separators, separatethousands); } // add exponent @@ -31012,9 +31201,9 @@ axes.makeClipPaths = function(gd) { // ax._rl (stored linearized range for use by zoom/pan) // or can pass in an axis object directly axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + var fullLayout = gd._fullLayout; + var ax; + var independent = false; // allow passing an independent axis object instead of id if(typeof axid === 'object') { @@ -31027,32 +31216,26 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'redraw') { fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); }); } if(!axid || axid === 'redraw') { - return _$lib_163.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return _$lib_164.syncOrAsync(axes.list(gd, '', true).map(function(ax) { return function() { if(!ax._id) return; var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_163.simpleMap(ax._r, ax.r2l); - } + ax._r = ax.range.slice(); + ax._rl = _$lib_164.simpleMap(ax._r, ax.r2l); return axDone; }; })); @@ -31062,21 +31245,22 @@ axes.doTicks = function(gd, axid, skipTitle) { // set scaling to pixels ax.setScale(); - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_68.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_68.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_68.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + var axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_68.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_68.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_68.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; if(ax._counterangle && ax.ticks === 'outside') { var caRad = ax._counterangle * Math.PI / 180; @@ -31123,13 +31307,14 @@ axes.doTicks = function(gd, axid, skipTitle) { }; } else { - _$lib_163.warn('Unrecognized doTicks axis:', axid); + _$lib_164.warn('Unrecognized doTicks axis:', axid); return; } - var axside = ax.side || sides[0], + + var axside = ax.side || sides[0]; // which direction do the side[0], side[1], and free ticks go? // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; if((ax.ticks !== 'inside') === (axLetter === 'x')) { ticksign = ticksign.map(function(v) { return -v; }); } @@ -31157,6 +31342,7 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawTicks(container, tickpath) { var ticks = container.selectAll('path.' + tcls) .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); + if(tickpath && ax.ticks) { ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) .classed('crisp', 1) @@ -31172,7 +31358,7 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawLabels(container, position) { // tick labels - for now just the main labels. // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); if(!_$fastIsnumeric_9(position)) { tickLabels.remove(); @@ -31240,10 +31426,10 @@ axes.doTicks = function(gd, axid, skipTitle) { var thisLabel = _$d3_6.select(this), newPromise = gd._promises.length; thisLabel - .call(_$svg_text_utils_184.positionText, labelx(d), labely(d)) + .call(_$svg_text_utils_185.positionText, labelx(d), labely(d)) .call(_$drawing_68.font, d.font, d.fontSize, d.fontColor) .text(d.text) - .call(_$svg_text_utils_184.convertToTspans, gd); + .call(_$svg_text_utils_185.convertToTspans, gd); newPromise = gd._promises[newPromise]; if(newPromise) { // if we have an async label, we'll deal with that @@ -31268,7 +31454,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'angular') { tickLabels.each(function(d) { _$d3_6.select(this).select('text') - .call(_$svg_text_utils_184.positionText, labelx(d), labely(d)); + .call(_$svg_text_utils_185.positionText, labelx(d), labely(d)); }); } @@ -31303,8 +31489,8 @@ axes.doTicks = function(gd, axid, skipTitle) { (labely(d) - d.fontSize / 2) + ')') : ''); var anchorHeight = getAnchorHeight( - _$svg_text_utils_184.lineCount(thisLabel), - __LINE_SPACING_205 * d.fontSize, + _$svg_text_utils_185.lineCount(thisLabel), + __LINE_SPACING_206 * d.fontSize, _$fastIsnumeric_9(angle) ? +angle : 0); if(anchorHeight) { transform += ' translate(0, ' + anchorHeight + ')'; @@ -31365,7 +31551,7 @@ axes.doTicks = function(gd, axid, skipTitle) { }); }); for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_163.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + if(_$lib_164.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { // any overlap at all - set 30 degrees autoangle = 30; break; @@ -31507,7 +31693,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } } - var done = _$lib_163.syncOrAsync([ + var done = _$lib_164.syncOrAsync([ allLabelsReady, fixLabelOverlaps, calcBoundingBox, @@ -31523,14 +31709,12 @@ axes.doTicks = function(gd, axid, skipTitle) { // now this only applies to regular cartesian axes; colorbars and // others ALWAYS call doTicks with skipTitle=true so they can // configure their own titles. - var ax = _$axis_ids_208.getFromId(gd, axid); // rangeslider takes over a bottom title so drop it here if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - var avoidSelection = _$d3_6.select(gd).selectAll('g.' + axid + 'tick'); var avoid = { - selection: avoidSelection, + selection: tickLabels, side: ax.side }; var axLetter = axid.charAt(0); @@ -31540,8 +31724,8 @@ axes.doTicks = function(gd, axid, skipTitle) { var transform, counterAxis, x, y; - if(avoidSelection.size()) { - var translation = _$drawing_68.getTranslate(avoidSelection.node().parentNode); + if(tickLabels.size()) { + var translation = _$drawing_68.getTranslate(tickLabels.node().parentNode); avoid.offsetLeft = translation.x; avoid.offsetTop = translation.y; } @@ -31552,7 +31736,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axLetter === 'x') { counterAxis = (ax.anchor === 'free') ? {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_208.getFromId(gd, ax.anchor); + _$axis_ids_209.getFromId(gd, ax.anchor); x = ax._offset + ax._length / 2; @@ -31570,7 +31754,7 @@ axes.doTicks = function(gd, axid, skipTitle) { else { counterAxis = (ax.anchor === 'free') ? {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_208.getFromId(gd, ax.anchor); + _$axis_ids_209.getFromId(gd, ax.anchor); y = ax._offset + ax._length / 2; if(ax.side === 'right') { @@ -31598,11 +31782,13 @@ axes.doTicks = function(gd, axid, skipTitle) { function traceHasBarsOrFill(trace, subplot) { if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_253.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + if(_$registry_254.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; } function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); var zlcontainer = plotinfo.zerolinelayer; var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; @@ -31636,7 +31822,7 @@ axes.doTicks = function(gd, axid, skipTitle) { break; } } - var rng = _$lib_163.simpleMap(ax.range, ax.r2l), + var rng = _$lib_164.simpleMap(ax.range, ax.r2l), showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && (ax.type === 'linear' || ax.type === '-') && gridvals.length && (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); @@ -31650,7 +31836,7 @@ axes.doTicks = function(gd, axid, skipTitle) { // If several zerolines enter at the same time we will sort once per, // but generally this should be a minimal overhead. zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_208.idSort(da.id, db.id); + return _$axis_ids_209.idSort(da.id, db.id); }); }); zl.attr('transform', transfn) @@ -31701,7 +31887,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - tickSubplots = Object.keys(ax._linepositions); + tickSubplots = Object.keys(ax._linepositions || {}); } tickSubplots.map(function(subplot) { @@ -31840,7 +32026,7 @@ function swapAxisGroup(gd, xIds, yIds) { var ann = gd._fullLayout.annotations[i]; if(xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { - _$lib_163.swapAttrs(layout.annotations[i], ['?']); + _$lib_164.swapAttrs(layout.annotations[i], ['?']); } } } @@ -31849,7 +32035,7 @@ 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_163.nestedProperty, + var np = _$lib_164.nestedProperty, xVal = np(layout[xFullAxes[0]._name], key).get(), yVal = np(layout[yFullAxes[0]._name], key).get(), i; @@ -31886,15 +32072,15 @@ var _$hover_83 = {}; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$Events_155 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_174 = require('../../lib/override_cursor'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$Events_156 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_175 = require('../../lib/override_cursor'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_254 = require('../../registry'); */; /* removed: var _$helpers_82 = require('./helpers'); */; /* removed: var _$constants_80 = require('./constants'); */; @@ -31941,9 +32127,9 @@ var HOVERTEXTPAD = _$constants_80.HOVERTEXTPAD; // We wrap the hovers in a timer, to limit their frequency. // The actual rendering is done by private function _hover. _$hover_83.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_163.getGraphDiv(gd); + gd = _$lib_164.getGraphDiv(gd); - _$lib_163.throttle( + _$lib_164.throttle( gd._fullLayout._uid + _$constants_80.HOVERID, _$constants_80.HOVERMINTIME, function() { _hover(gd, evt, subplot, noHoverEvent); } @@ -32066,8 +32252,8 @@ function _hover(gd, evt, subplot, noHoverEvent) { // get updated properly so that we don't have // to use Axes.getFromId in general. - xaArray[i] = _$axes_205.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_205.getFromId(gd, plotObj.yaxis._id); + xaArray[i] = _$axes_206.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_206.getFromId(gd, plotObj.yaxis._id); continue; } @@ -32089,7 +32275,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - // hoverData: the set of candidate points we've found to highlight + // hoverData: the set of candidate points we've found to highlight var hoverData = [], // searchData: the data to search in. Mostly this is just a copy of @@ -32139,7 +32325,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { cd = gd.calcdata[curvenum]; trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_82.getSubplot(trace)) !== -1) { + if(trace.hoverinfo !== 'skip' && _$helpers_82.isTraceInSubplots(trace, subplots)) { searchData.push(cd); } } @@ -32163,7 +32349,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { // fire the beforehover event and quit if it returns false // note that we're only calling this on real mouse events, so // manual calls to fx.hover will always run. - if(_$Events_155.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + if(_$Events_156.triggerHandler(gd, 'plotly_beforehover', evt) === false) { return; } @@ -32188,7 +32374,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { else yvalArray = _$helpers_82.p2c(yaArray, ypx); if(!_$fastIsnumeric_9(xvalArray[0]) || !_$fastIsnumeric_9(yvalArray[0])) { - _$lib_163.warn('Fx.hover failed', evt, gd); + _$lib_164.warn('Fx.hover failed', evt, gd); return _$dragelement_65.unhoverRaw(gd, evt); } } @@ -32212,8 +32398,15 @@ function _hover(gd, evt, subplot, noHoverEvent) { // the rest of this function from running and failing if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotId = _$helpers_82.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_82.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } // within one trace mode can sometimes be overridden mode = hovermode; @@ -32307,7 +32500,7 @@ function _hover(gd, evt, subplot, noHoverEvent) { } } else { - _$lib_163.log('Unrecognized trace type in hover:', trace); + _$lib_164.log('Unrecognized trace type in hover:', trace); } } @@ -32484,8 +32677,8 @@ function _hover(gd, evt, subplot, noHoverEvent) { // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true // we should improve the "fx" API so other plots can use it without these hack. if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_253.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_174(_$d3_6.select(evt.target), hasClickToShow ? 'pointer' : ''); + var hasClickToShow = _$registry_254.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_175(_$d3_6.select(evt.target), hasClickToShow ? 'pointer' : ''); } // don't emit events if called manually @@ -32570,38 +32763,36 @@ function createHoverText(hoverData, opts, gd) { commonLabel.exit().remove(); commonLabel.each(function() { - var label = _$d3_6.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); - - lpath.enter().append('path') - .style({'stroke-width': '1px'}); + var label = _$d3_6.select(this); + var lpath = _$lib_164.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_164.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); lpath.style({ fill: commonLabelOpts.bgcolor || _$color_43.defaultLine, stroke: commonLabelOpts.bordercolor || _$color_43.background, }); - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); - ltext.text(t0) .call(_$drawing_68.font, commonLabelOpts.font.family || fontFamily, commonLabelOpts.font.size || fontSize, commonLabelOpts.font.color || _$color_43.background ) - .call(_$svg_text_utils_184.positionText, 0, 0) - .call(_$svg_text_utils_184.convertToTspans, gd); + .call(_$svg_text_utils_185.positionText, 0, 0) + .call(_$svg_text_utils_185.convertToTspans, gd); label.attr('transform', ''); var tbb = ltext.node().getBoundingClientRect(); if(hovermode === 'x') { ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_184.positionText, 0, (xa.side === 'top' ? + .call(_$svg_text_utils_185.positionText, 0, (xa.side === 'top' ? (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); @@ -32619,7 +32810,7 @@ function createHoverText(hoverData, opts, gd) { } else { ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_184.positionText, + .call(_$svg_text_utils_185.positionText, (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), outerTop - tbb.top - tbb.height / 2); @@ -32685,7 +32876,7 @@ function createHoverText(hoverData, opts, gd) { if(d.name) { // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_184.plainText(d.name || ''); + name = _$svg_text_utils_185.plainText(d.name || ''); var nameLength = Math.round(d.nameLength); @@ -32695,13 +32886,6 @@ function createHoverText(hoverData, opts, gd) { } } - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; - if(d.zLabel !== undefined) { if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; @@ -32720,6 +32904,13 @@ function createHoverText(hoverData, opts, gd) { text += (text ? '
' : '') + d.text; } + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; + // if 'text' is empty at this point, // put 'name' in main label and don't show secondary label if(text === '') { @@ -32736,8 +32927,8 @@ function createHoverText(hoverData, opts, gd) { d.fontColor || contrastColor) .text(text) .attr('data-notex', 1) - .call(_$svg_text_utils_184.positionText, 0, 0) - .call(_$svg_text_utils_184.convertToTspans, gd); + .call(_$svg_text_utils_185.positionText, 0, 0) + .call(_$svg_text_utils_185.convertToTspans, gd); var tx2 = g.select('text.name'), tx2width = 0; @@ -32750,8 +32941,8 @@ function createHoverText(hoverData, opts, gd) { traceColor) .text(name) .attr('data-notex', 1) - .call(_$svg_text_utils_184.positionText, 0, 0) - .call(_$svg_text_utils_184.convertToTspans, gd); + .call(_$svg_text_utils_185.positionText, 0, 0) + .call(_$svg_text_utils_185.convertToTspans, gd); tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; } else { @@ -33020,12 +33211,12 @@ function alignHoverText(hoverLabels, rotateLabels) { 'V' + (offsetY - HOVERARROWSIZE) + 'Z')); - tx.call(_$svg_text_utils_184.positionText, + tx.call(_$svg_text_utils_185.positionText, txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); if(d.tx2width) { g.select('text.name') - .call(_$svg_text_utils_184.positionText, + .call(_$svg_text_utils_185.positionText, tx2x + alignShift * HOVERTEXTPAD + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); g.select('rect') @@ -33045,11 +33236,11 @@ function cleanPoint(d, hovermode) { var getVal = Array.isArray(index) ? function(calcKey, traceKey) { - return _$lib_163.castOption(cd0, index, calcKey) || - _$lib_163.extractOption({}, trace, '', traceKey); + return _$lib_164.castOption(cd0, index, calcKey) || + _$lib_164.extractOption({}, trace, '', traceKey); } : function(calcKey, traceKey) { - return _$lib_163.extractOption(cd, trace, calcKey, traceKey); + return _$lib_164.extractOption(cd, trace, calcKey, traceKey); }; function fill(key, calcKey, traceKey) { @@ -33070,18 +33261,18 @@ function cleanPoint(d, hovermode) { (d.ya._offset + (d.y0 + d.y1) / 2); // then constrain all the positions to be on the plot - d.x0 = _$lib_163.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_163.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_163.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_163.constrain(d.y1, 0, d.ya._length); + d.x0 = _$lib_164.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_164.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_164.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_164.constrain(d.y1, 0, d.ya._length); // and convert the x and y label values into formatted text if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_205.hoverLabelText(d.xa, d.xLabelVal); + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_206.hoverLabelText(d.xa, d.xLabelVal); d.xVal = d.xa.c2d(d.xLabelVal); } if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_205.hoverLabelText(d.ya, d.yLabelVal); + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_206.hoverLabelText(d.ya, d.yLabelVal); d.yVal = d.ya.c2d(d.yLabelVal); } @@ -33092,10 +33283,10 @@ function cleanPoint(d, hovermode) { // for box means and error bars, add the range to the label if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_205.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + var xeText = _$axes_206.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; if(d.xerrneg !== undefined) { d.xLabel += ' +' + xeText + ' / -' + - _$axes_205.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + _$axes_206.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; } else d.xLabel += ' ± ' + xeText; @@ -33105,10 +33296,10 @@ function cleanPoint(d, hovermode) { if(hovermode === 'x') d.distance += 1; } if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_205.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + var yeText = _$axes_206.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; if(d.yerrneg !== undefined) { d.yLabel += ' +' + yeText + ' / -' + - _$axes_205.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; + _$axes_206.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; } else d.yLabel += ' ± ' + yeText; @@ -33334,11 +33525,11 @@ function spikesChanged(gd, oldspikepoints) { 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; var hover = _$hover_83.hover; var _$click_79 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_253.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); + var annotationsDone = _$registry_254.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. @@ -33371,7 +33562,7 @@ var _$click_79 = function click(gd, evt, subplot) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; var _$handleHoverLabelDefaults_84 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { opts = opts || {}; @@ -33379,7 +33570,7 @@ var _$handleHoverLabelDefaults_84 = function handleHoverLabelDefaults(contIn, co coerce('hoverlabel.bgcolor', opts.bgcolor); coerce('hoverlabel.bordercolor', opts.bordercolor); coerce('hoverlabel.namelength', opts.namelength); - _$lib_163.coerceFont(coerce, 'hoverlabel.font', opts.font); + _$lib_164.coerceFont(coerce, 'hoverlabel.font', opts.font); }; /** @@ -33392,13 +33583,13 @@ var _$handleHoverLabelDefaults_84 = function handleHoverLabelDefaults(contIn, co 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$attributes_77 = require('./attributes'); */; /* removed: var _$handleHoverLabelDefaults_84 = require('./hoverlabel_defaults'); */; var _$supplyDefaults_81 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_163.coerce(traceIn, traceOut, _$attributes_77, attr, dflt); + return _$lib_164.coerce(traceIn, traceOut, _$attributes_77, attr, dflt); } _$handleHoverLabelDefaults_84(traceIn, traceOut, coerce, layout.hoverlabel); @@ -33477,6 +33668,14 @@ var _$layout_attributes_86 = { editType: 'none', }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + editType: 'none' } }; @@ -33491,15 +33690,16 @@ var _$layout_attributes_86 = { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; var _$supplyLayoutDefaults_87 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); + return _$lib_164.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); } - coerce('dragmode'); + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); var hovermodeDflt; if(layoutOut._has('cartesian')) { @@ -33556,13 +33756,13 @@ function isHoriz(fullData) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$handleHoverLabelDefaults_84 = require('./hoverlabel_defaults'); */; /* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; var _$supplyLayoutGlobalDefaults_88 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); + return _$lib_164.coerce(layoutIn, layoutOut, _$layout_attributes_86, attr, dflt); } _$handleHoverLabelDefaults_84(layoutIn, layoutOut, coerce); @@ -33579,7 +33779,7 @@ var _$supplyLayoutGlobalDefaults_88 = function supplyLayoutGlobalDefaults(layout 'use strict'; /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$dragelement_65 = require('../dragelement'); */; /* removed: var _$helpers_82 = require('./helpers'); */; /* removed: var _$layout_attributes_86 = require('./layout_attributes'); */; @@ -33623,7 +33823,7 @@ var _$fx_85 = { function loneUnhover(containerOrSelection) { // duck type whether the arg is a d3 selection because ie9 doesn't // handle instanceof like modern browsers do. - var selection = _$lib_163.isD3Selection(containerOrSelection) ? + var selection = _$lib_164.isD3Selection(containerOrSelection) ? containerOrSelection : _$d3_6.select(containerOrSelection); @@ -33634,15 +33834,15 @@ function loneUnhover(containerOrSelection) { // helpers for traces that use Fx.loneHover function castHoverOption(trace, ptNumber, attr) { - return _$lib_163.castOption(trace, ptNumber, 'hoverlabel.' + attr); + return _$lib_164.castOption(trace, ptNumber, 'hoverlabel.' + attr); } function castHoverinfo(trace, fullLayout, ptNumber) { function _coerce(val) { - return _$lib_163.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + return _$lib_164.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } - return _$lib_163.castOption(trace, ptNumber, 'hoverinfo', _coerce); + return _$lib_164.castOption(trace, ptNumber, 'hoverinfo', _coerce); } /** @@ -33657,15 +33857,15 @@ function castHoverinfo(trace, fullLayout, ptNumber) { /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$fx_85 = require('../fx'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_183 = require('../../lib/setcursor'); */; /* removed: var _$dragelement_65 = require('../dragelement'); */; /* removed: var _$drawArrowHead_35 = require('./draw_arrow_head'); */; @@ -33709,8 +33909,8 @@ function __draw_34(gd) { function drawOne(gd, index) { var fullLayout = gd._fullLayout; var options = fullLayout.annotations[index] || {}; - var xa = _$axes_205.getFromId(gd, options.xref); - var ya = _$axes_205.getFromId(gd, options.yref); + var xa = _$axes_206.getFromId(gd, options.xref); + var ya = _$axes_206.getFromId(gd, options.yref); drawRaw(gd, options, index, false, xa, ya); } @@ -33779,7 +33979,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextGroupInner = annTextGroup.append('g') .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_182, 'default') + .call(_$setCursor_183, 'default') .on('click', function() { gd._dragging = false; @@ -33863,7 +34063,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }[options.align] || 'middle' }); - _$svg_text_utils_184.convertToTspans(s, gd, drawGraphicalElements); + _$svg_text_utils_185.convertToTspans(s, gd, drawGraphicalElements); return s; } @@ -34004,7 +34204,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // partially visible var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height']; if(axRef === 'paper') { - posPx.head = _$lib_163.constrain(posPx.head, 1, maxPx - 1); + posPx.head = _$lib_164.constrain(posPx.head, 1, maxPx - 1); } if(tailRef === 'pixel') { var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), @@ -34069,7 +34269,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var texty = borderfull + yShift - anntextBB.top; var textx = borderfull + xShift - anntextBB.left; - annText.call(_$svg_text_utils_184.positionText, textx, texty) + annText.call(_$svg_text_utils_185.positionText, textx, texty) .call(_$drawing_68.setClipUrl, isSizeConstrained ? annClipID : null); } @@ -34112,9 +34312,9 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // find the edge of the text box, where we'll start the arrow: // create transform matrix to rotate the text box corners - transform = _$lib_163.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_163.apply2DTransform(transform), - applyTransform2 = _$lib_163.apply2DTransform2(transform), + transform = _$lib_164.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_164.apply2DTransform(transform), + applyTransform2 = _$lib_164.apply2DTransform2(transform), // calculate and transform bounding box width = +annTextBG.attr('width'), @@ -34136,7 +34336,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // to get the parity of the number of intersections. if(edges.reduce(function(a, x) { return a ^ - !!_$lib_163.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, + !!_$lib_164.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, x[0], x[1], x[2], x[3]); }, false)) { // no line or arrow - so quit drawArrow now @@ -34144,7 +34344,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } edges.forEach(function(x) { - var p = _$lib_163.segmentsIntersect(tailX, tailY, headX, headY, + var p = _$lib_164.segmentsIntersect(tailX, tailY, headX, headY, x[0], x[1], x[2], x[3]); if(p) { tailX = p.x; @@ -34238,7 +34438,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }, doneFn: function() { - _$registry_253.call('relayout', gd, update); + _$registry_254.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -34316,11 +34516,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform }); - _$setCursor_182(annTextGroupInner, csr); + _$setCursor_183(annTextGroupInner, csr); }, doneFn: function() { - _$setCursor_182(annTextGroupInner); - _$registry_253.call('relayout', gd, update); + _$setCursor_183(annTextGroupInner); + _$registry_254.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -34329,7 +34529,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } if(edits.annotationText) { - annText.call(_$svg_text_utils_184.makeEditable, {delegate: annTextGroupInner, gd: gd}) + annText.call(_$svg_text_utils_185.makeEditable, {delegate: annTextGroupInner, gd: gd}) .call(textLayout) .on('edit', function(_text) { options.text = _text; @@ -34345,7 +34545,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { update[ya._name + '.autorange'] = true; } - _$registry_253.call('relayout', gd, update); + _$registry_254.call('relayout', gd, update); }); } else annText.call(textLayout); @@ -34362,15 +34562,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; var __draw_29 = _$draw_34.draw; var _$calcAutorange_29 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - annotationList = _$lib_163.filterVisible(fullLayout.annotations); + annotationList = _$lib_164.filterVisible(fullLayout.annotations); if(!annotationList.length || !gd._fullData.length) return; @@ -34381,9 +34581,9 @@ var _$calcAutorange_29 = function calcAutorange(gd) { }); for(var axId in annotationAxes) { - var ax = _$axes_205.getFromId(gd, axId); + var ax = _$axes_206.getFromId(gd, axId); if(ax && ax.autorange) { - return _$lib_163.syncOrAsync([ + return _$lib_164.syncOrAsync([ __draw_29, annAutorange ], gd); @@ -34398,9 +34598,9 @@ function annAutorange(gd) { // relative to their anchor points // use the arrow and the text bg rectangle, // as the whole anno may include hidden text in its bbox - _$lib_163.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_205.getFromId(gd, ann.xref), - ya = _$axes_205.getFromId(gd, ann.yref), + _$lib_164.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_206.getFromId(gd, ann.xref), + ya = _$axes_206.getFromId(gd, ann.yref), headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; @@ -34414,12 +34614,12 @@ function annAutorange(gd) { if(ann.axref === ann.xref) { // expand for the arrowhead (padded by arrowhead) - _$axes_205.expand(xa, [xa.r2c(ann.x)], { + _$axes_206.expand(xa, [xa.r2c(ann.x)], { ppadplus: headPlus, ppadminus: headMinus }); // again for the textbox (padded by textbox) - _$axes_205.expand(xa, [xa.r2c(ann.ax)], { + _$axes_206.expand(xa, [xa.r2c(ann.ax)], { ppadplus: Math.max(ann._xpadplus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, startHeadMinus) }); @@ -34427,7 +34627,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_205.expand(xa, [xa.r2c(ann.x)], { + _$axes_206.expand(xa, [xa.r2c(ann.x)], { ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) }); @@ -34441,11 +34641,11 @@ function annAutorange(gd) { startHeadMinus = startHeadSize + ann.yshift; if(ann.ayref === ann.yref) { - _$axes_205.expand(ya, [ya.r2c(ann.y)], { + _$axes_206.expand(ya, [ya.r2c(ann.y)], { ppadplus: headPlus, ppadminus: headMinus }); - _$axes_205.expand(ya, [ya.r2c(ann.ay)], { + _$axes_206.expand(ya, [ya.r2c(ann.ay)], { ppadplus: Math.max(ann._ypadplus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, startHeadMinus) }); @@ -34453,7 +34653,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_205.expand(ya, [ya.r2c(ann.y)], { + _$axes_206.expand(ya, [ya.r2c(ann.y)], { ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) }); @@ -34472,7 +34672,7 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; var _$click_30 = { hasClickToShow: hasClickToShow, @@ -34521,7 +34721,7 @@ function onClick(gd, hoverData) { update['annotations[' + offSet[i] + '].visible'] = false; } - return _$registry_253.call('update', gd, {}, update); + return _$registry_254.call('update', gd, {}, update); } /* @@ -34605,7 +34805,7 @@ function clickData2r(d, ax) { 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_186 = require('../../lib/to_log_range'); */; +/* removed: var _$toLogRange_187 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -34637,7 +34837,7 @@ var _$convertCoords_32 = function convertCoords(gd, ax, newType, doExtra) { var currentVal = ann[attr], newVal = null; - if(toLog) newVal = _$toLogRange_186(currentVal, ax.range); + if(toLog) newVal = _$toLogRange_187(currentVal, ax.range); else newVal = Math.pow(10, currentVal); // if conversion failed, delete the value so it gets a default value @@ -34665,7 +34865,7 @@ var _$convertCoords_32 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$color_43 = require('../color'); */; // defaults common to 'annotations' and 'annotations3d' @@ -34683,7 +34883,7 @@ var _$handleAnnotationCommonDefaults_31 = function handleAnnotationCommonDefault coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); coerce('textangle'); - _$lib_163.coerceFont(coerce, 'font', fullLayout.font); + _$lib_164.coerceFont(coerce, 'font', fullLayout.font); coerce('width'); coerce('align'); @@ -34724,7 +34924,7 @@ var _$handleAnnotationCommonDefaults_31 = function handleAnnotationCommonDefault _$color_43.contrast(hoverBG) ); - _$lib_163.coerceFont(coerce, 'hoverlabel.font', { + _$lib_164.coerceFont(coerce, 'hoverlabel.font', { family: globalHoverLabel.font.family, size: globalHoverLabel.font.size, color: globalHoverLabel.font.color || hoverBorder @@ -34745,8 +34945,8 @@ var _$handleAnnotationCommonDefaults_31 = function handleAnnotationCommonDefault 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; /* removed: var _$handleAnnotationCommonDefaults_31 = require('./common_defaults'); */; /* removed: var _$attributes_28 = require('./attributes'); */; @@ -34756,7 +34956,7 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_163.coerce(annIn, annOut, _$attributes_28, attr, dflt); + return _$lib_164.coerce(annIn, annOut, _$attributes_28, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -34776,15 +34976,15 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann var axLetter = axLetters[i]; // xref, yref - var axRef = _$axes_205.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_206.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); // x, y - _$axes_205.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + _$axes_206.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); if(showArrow) { var arrowPosAttr = 'a' + axLetter, // axref, ayref - aaxRef = _$axes_205.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + aaxRef = _$axes_206.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); // for now the arrow can only be on the same axis or specified as pixels // TODO: sometime it might be interesting to allow it to be on *any* axis @@ -34795,7 +34995,7 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann // ax, ay var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_205.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + _$axes_206.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } // xanchor, yanchor @@ -34806,11 +35006,11 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann } // if you have one coordinate you should have both - _$lib_163.noneOrAll(annIn, annOut, ['x', 'y']); + _$lib_164.noneOrAll(annIn, annOut, ['x', 'y']); // if you have one part of arrow length you should have both if(showArrow) { - _$lib_163.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_164.noneOrAll(annIn, annOut, ['ax', 'ay']); } if(clickToShow) { @@ -34821,10 +35021,10 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann // so we don't have to do this little bit of logic on every hover event annOut._xclick = (xClick === undefined) ? annOut.x : - _$axes_205.cleanPosition(xClick, gdMock, annOut.xref); + _$axes_206.cleanPosition(xClick, gdMock, annOut.xref); annOut._yclick = (yClick === undefined) ? annOut.y : - _$axes_205.cleanPosition(yClick, gdMock, annOut.yref); + _$axes_206.cleanPosition(yClick, gdMock, annOut.yref); } return annOut; @@ -34840,7 +35040,7 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann 'use strict'; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$lib_164 = require('../lib'); */; /** Convenience wrapper for making array container logic DRY and consistent * @@ -34872,12 +35072,12 @@ var _$handleAnnotationDefaults_26 = function handleAnnotationDefaults(annIn, ann * links to supplementary data (e.g. fullData for layout components) * */ -var _$handleArrayContainerDefaults_201 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { +var _$handleArrayContainerDefaults_202 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { var name = opts.name; var previousContOut = parentObjOut[name]; - var contIn = _$lib_163.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + var contIn = _$lib_164.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], contOut = parentObjOut[name] = [], i; @@ -34886,7 +35086,7 @@ var _$handleArrayContainerDefaults_201 = function handleArrayContainerDefaults(p itemOut = {}, itemOpts = {}; - if(!_$lib_163.isPlainObject(itemIn)) { + if(!_$lib_164.isPlainObject(itemIn)) { itemOpts.itemIsNotPlainObject = true; itemIn = {}; } @@ -34901,10 +35101,10 @@ var _$handleArrayContainerDefaults_201 = function handleArrayContainerDefaults(p // in case this array gets its defaults rebuilt independent of the whole layout, // relink the private keys just for this array. - if(_$lib_163.isArrayOrTypedArray(previousContOut)) { + if(_$lib_164.isArrayOrTypedArray(previousContOut)) { var len = Math.min(previousContOut.length, contOut.length); for(i = 0; i < len; i++) { - _$lib_163.relinkPrivateKeys(contOut[i], previousContOut[i]); + _$lib_164.relinkPrivateKeys(contOut[i], previousContOut[i]); } } }; @@ -34920,7 +35120,7 @@ var _$handleArrayContainerDefaults_201 = function handleArrayContainerDefaults(p 'use strict'; -/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_202 = require('../../plots/array_container_defaults'); */; /* removed: var _$handleAnnotationDefaults_26 = require('./annotation_defaults'); */; @@ -34930,7 +35130,7 @@ var _$supplyLayoutDefaults_33 = function supplyLayoutDefaults(layoutIn, layoutOu handleItemDefaults: _$handleAnnotationDefaults_26 }; - _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_202(layoutIn, layoutOut, opts); }; /** @@ -34944,8 +35144,8 @@ var _$supplyLayoutDefaults_33 = function supplyLayoutDefaults(layoutIn, layoutOu 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /** * Factory function for checking component arrays for subplot references. @@ -34958,12 +35158,12 @@ var _$supplyLayoutDefaults_33 = function supplyLayoutDefaults(layoutIn, layoutOu * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout) * as expected of a component includeBasePlot method */ -var _$makeIncludeComponents_215 = function makeIncludeComponents(containerArrayName) { +var _$makeIncludeComponents_216 = function makeIncludeComponents(containerArrayName) { return function includeComponents(layoutIn, layoutOut) { var array = layoutIn[containerArrayName]; if(!Array.isArray(array)) return; - var Cartesian = _$registry_253.subplotsRegistry.cartesian; + var Cartesian = _$registry_254.subplotsRegistry.cartesian; var idRegex = Cartesian.idRegex; var subplots = layoutOut._subplots; var xaList = subplots.xaxis; @@ -34973,7 +35173,7 @@ var _$makeIncludeComponents_215 = function makeIncludeComponents(containerArrayN for(var i = 0; i < array.length; i++) { var itemi = array[i]; - if(!_$lib_163.isPlainObject(itemi)) continue; + if(!_$lib_164.isPlainObject(itemi)) continue; var xref = itemi.xref; var yref = itemi.yref; @@ -34981,7 +35181,7 @@ var _$makeIncludeComponents_215 = function makeIncludeComponents(containerArrayN var hasXref = idRegex.x.test(xref); var hasYref = idRegex.y.test(yref); if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_163.pushUnique(layoutOut._basePlotModules, Cartesian); + if(!hasCartesianOrGL2D) _$lib_164.pushUnique(layoutOut._basePlotModules, Cartesian); var newAxis = false; if(hasXref && xaList.indexOf(xref) === -1) { @@ -35027,7 +35227,7 @@ var _$annotations_36 = { layoutAttributes: _$attributes_28, supplyLayoutDefaults: _$supplyLayoutDefaults_33, - includeBasePlot: _$makeIncludeComponents_215('annotations'), + includeBasePlot: _$makeIncludeComponents_216('annotations'), calcAutorange: _$calcAutorange_29, draw: _$draw_34.draw, @@ -35052,7 +35252,7 @@ var _$annotations_36 = { 'use strict'; /* removed: var _$attributes_28 = require('../annotations/attributes'); */; -var __overrideAll_37 = _$edit_types_190.overrideAll; +var __overrideAll_37 = _$edit_types_191.overrideAll; var _$attributes_37 = __overrideAll_37({ _isLinkedToArray: 'annotation', @@ -35138,8 +35338,8 @@ var _$attributes_37 = __overrideAll_37({ 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; var _$convert_38 = function convert(scene) { var fullSceneLayout = scene.fullSceneLayout; @@ -35176,16 +35376,16 @@ function mockAnnAxes(ann, scene) { }; ann._xa = {}; - _$lib_163.extendFlat(ann._xa, base); - _$axes_205.setConvert(ann._xa); + _$lib_164.extendFlat(ann._xa, base); + _$axes_206.setConvert(ann._xa); ann._xa._offset = size.l + domain.x[0] * size.w; ann._xa.l2p = function() { return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); }; ann._ya = {}; - _$lib_163.extendFlat(ann._ya, base); - _$axes_205.setConvert(ann._ya); + _$lib_164.extendFlat(ann._ya, base); + _$axes_206.setConvert(ann._ya); ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; ann._ya.l2p = function() { return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); @@ -35202,14 +35402,14 @@ function mockAnnAxes(ann, scene) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_202 = require('../../plots/array_container_defaults'); */; /* removed: var _$handleAnnotationCommonDefaults_31 = require('../annotations/common_defaults'); */; /* removed: var _$attributes_37 = require('./attributes'); */; var _$handleDefaults_39 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_201(sceneLayoutIn, sceneLayoutOut, { + _$handleArrayContainerDefaults_202(sceneLayoutIn, sceneLayoutOut, { name: 'annotations', handleItemDefaults: __handleAnnotationDefaults_39, fullLayout: opts.fullLayout @@ -35218,7 +35418,7 @@ var _$handleDefaults_39 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, function __handleAnnotationDefaults_39(annIn, annOut, sceneLayout, opts, itemOpts) { function coerce(attr, dflt) { - return _$lib_163.coerce(annIn, annOut, _$attributes_37, attr, dflt); + return _$lib_164.coerce(annIn, annOut, _$attributes_37, attr, dflt); } function coercePosition(axLetter) { @@ -35228,7 +35428,7 @@ function __handleAnnotationDefaults_39(annIn, annOut, sceneLayout, opts, itemOpt var gdMock = { _fullLayout: {} }; gdMock._fullLayout[axName] = sceneLayout[axName]; - return _$axes_205.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + return _$axes_206.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } @@ -35242,7 +35442,7 @@ function __handleAnnotationDefaults_39(annIn, annOut, sceneLayout, opts, itemOpt coercePosition('z'); // if you have one coordinate you should all three - _$lib_163.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + _$lib_164.noneOrAll(annIn, annOut, ['x', 'y', 'z']); // hard-set here for completeness annOut.xref = 'x'; @@ -35263,7 +35463,7 @@ function __handleAnnotationDefaults_39(annIn, annOut, sceneLayout, opts, itemOpt coerce('ay', -30); // if you have one part of arrow length you should have both - _$lib_163.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_164.noneOrAll(annIn, annOut, ['ax', 'ay']); } return annOut; @@ -35363,8 +35563,8 @@ var _$draw_40 = function draw(scene) { 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; var _$annotations3d_41 = { moduleType: 'component', @@ -35385,7 +35585,7 @@ var _$annotations3d_41 = { }; function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_253.subplotsRegistry.gl3d; + var GL3D = _$registry_254.subplotsRegistry.gl3d; if(!GL3D) return; var attrRegex = GL3D.attrRegex; @@ -35394,8 +35594,8 @@ function includeGL3D(layoutIn, layoutOut) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_163.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_163.pushUnique(layoutOut._subplots.gl3d, k); + _$lib_164.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_164.pushUnique(layoutOut._subplots.gl3d, k); } } } @@ -35630,8 +35830,8 @@ function makeComputeErrorValue(type, value) { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; /* removed: var _$makeComputeError_72 = require('./compute_error'); */; @@ -35643,10 +35843,10 @@ var _$calc_71 = function calc(gd) { var calcTrace = calcdata[i], trace = calcTrace[0].trace; - if(!_$registry_253.traceIs(trace, 'errorBarsOK')) continue; + if(!_$registry_254.traceIs(trace, 'errorBarsOK')) continue; - var xa = _$axes_205.getFromId(gd, trace.xaxis), - ya = _$axes_205.getFromId(gd, trace.yaxis); + var xa = _$axes_206.getFromId(gd, trace.xaxis), + ya = _$axes_206.getFromId(gd, trace.yaxis); calcOneAxis(calcTrace, trace, xa, 'x'); calcOneAxis(calcTrace, trace, ya, 'y'); @@ -35676,7 +35876,7 @@ function calcOneAxis(calcTrace, trace, axis, coord) { } } - _$axes_205.expand(axis, vals, {padded: true}); + _$axes_206.expand(axis, vals, {padded: true}); } /** @@ -35691,8 +35891,8 @@ function calcOneAxis(calcTrace, trace, axis, coord) { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$attributes_70 = require('./attributes'); */; @@ -35703,7 +35903,7 @@ var _$defaults_73 = function(traceIn, traceOut, defaultColor, opts) { containerIn = traceIn[objName] || {}; function coerce(attr, dflt) { - return _$lib_163.coerce(containerIn, containerOut, _$attributes_70, attr, dflt); + return _$lib_164.coerce(containerIn, containerOut, _$attributes_70, attr, dflt); } var hasErrorBars = ( @@ -35749,7 +35949,7 @@ var _$defaults_73 = function(traceIn, traceOut, defaultColor, opts) { if(!opts.inherit || !containerOut[copyAttr]) { coerce('color', defaultColor); coerce('thickness'); - coerce('width', _$registry_253.traceIs(traceOut, 'gl3d') ? 0 : 4); + coerce('width', _$registry_254.traceIs(traceOut, 'gl3d') ? 0 : 4); } }; @@ -35768,7 +35968,7 @@ var _$defaults_73 = function(traceIn, traceOut, defaultColor, opts) { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$subtypes_287 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$subtypes_288 = require('../../traces/scatter/subtypes'); */; var _$plot_75 = function plot(traces, plotinfo, transitionOpts) { var isNew; @@ -35794,7 +35994,7 @@ var _$plot_75 = function plot(traces, plotinfo, transitionOpts) { } var sparse = ( - _$subtypes_287.hasMarkers(trace) && + _$subtypes_288.hasMarkers(trace) && trace.marker.maxdisplayed > 0 ); @@ -35972,24 +36172,24 @@ var _$style_76 = function style(traces) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -var __overrideAll_74 = _$edit_types_190.overrideAll; +/* removed: var _$lib_164 = require('../../lib'); */; +var __overrideAll_74 = _$edit_types_191.overrideAll; /* removed: var _$attributes_70 = require('./attributes'); */; /* removed: var _$calc_71 = require('./calc'); */; var xyAttrs = { - error_x: _$lib_163.extendFlat({}, _$attributes_70), - error_y: _$lib_163.extendFlat({}, _$attributes_70) + error_x: _$lib_164.extendFlat({}, _$attributes_70), + error_y: _$lib_164.extendFlat({}, _$attributes_70) }; delete xyAttrs.error_x.copy_zstyle; delete xyAttrs.error_y.copy_zstyle; delete xyAttrs.error_y.copy_ystyle; var xyzAttrs = { - error_x: _$lib_163.extendFlat({}, _$attributes_70), - error_y: _$lib_163.extendFlat({}, _$attributes_70), - error_z: _$lib_163.extendFlat({}, _$attributes_70) + error_x: _$lib_164.extendFlat({}, _$attributes_70), + error_y: _$lib_164.extendFlat({}, _$attributes_70), + error_z: _$lib_164.extendFlat({}, _$attributes_70) }; delete xyzAttrs.error_x.copy_ystyle; delete xyzAttrs.error_y.copy_ystyle; @@ -36066,7 +36266,7 @@ var _$domain_231 = {}; 'use strict'; -var __extendFlat_231 = _$extend_156.extendFlat; +var __extendFlat_231 = _$extend_157.extendFlat; /** * Make a xy domain attribute group @@ -36173,10 +36373,10 @@ _$domain_231.defaults = function(containerOut, layout, coerce, dfltDomains) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -var __counterRegex_89 = _$regex_178.counter; +/* removed: var _$lib_164 = require('../../lib'); */; +var __counterRegex_89 = _$regex_179.counter; var domainAttrs = _$domain_231.attributes; -var cartesianIdRegex = _$constants_210.idRegex; +var cartesianIdRegex = _$constants_211.idRegex; var gridAttrs = { rows: { @@ -36258,7 +36458,7 @@ var gridAttrs = { values: ['bottom', 'bottom plot', 'top plot', 'top'], dflt: 'bottom plot', - editType: 'ticks', + editType: 'plot', }, yside: { @@ -36266,21 +36466,36 @@ var gridAttrs = { values: ['left', 'left plot', 'right plot', 'right'], dflt: 'left plot', - editType: 'ticks', + 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; - if(!gridIn) return; + 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(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + var hasXaxes = Array.isArray(xAxes); + var hasYaxes = Array.isArray(yAxes); + var isSplomGenerated = ( + hasXaxes && xAxes !== gridIn.xaxes && + hasYaxes && yAxes !== gridIn.yaxes + ); var dfltRows, dfltColumns; @@ -36289,14 +36504,14 @@ function sizeDefaults(layoutIn, layoutOut) { dfltColumns = gridIn.subplots[0].length; } else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } var gridOut = layoutOut.grid = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + return _$lib_164.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } var rows = coerce('rows', dfltRows); @@ -36313,17 +36528,26 @@ function sizeDefaults(layoutIn, layoutOut) { 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) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } + gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) + 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, len, reversed) { +function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) { var dirGap = coerce(axLetter + 'gap', dfltGap); var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + coerce(axLetter + 'side', dfltSide); var out = new Array(len); var start = domain[0]; @@ -36343,7 +36567,7 @@ function contentDefaults(layoutIn, layoutOut) { // make sure we got to the end of handleGridSizing if(!gridOut || !gridOut._domains) return; - var gridIn = layoutIn.grid; + var gridIn = layoutIn.grid || {}; var subplots = layoutOut._subplots; var hasSubplotGrid = gridOut._hasSubplotGrid; var rows = gridOut.rows; @@ -36389,8 +36613,10 @@ function contentDefaults(layoutIn, layoutOut) { } } else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); + 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 = {}; @@ -36527,7 +36753,7 @@ var _$grid_89 = { 'use strict'; -/* removed: var _$constants_210 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_211 = require('../../plots/cartesian/constants'); */; var _$attributes_90 = { @@ -36630,7 +36856,7 @@ var _$attributes_90 = { valType: 'enumerated', values: [ 'paper', - _$constants_210.idRegex.x.toString() + _$constants_211.idRegex.x.toString() ], dflt: 'paper', @@ -36642,7 +36868,7 @@ var _$attributes_90 = { valType: 'enumerated', values: [ 'paper', - _$constants_210.idRegex.y.toString() + _$constants_211.idRegex.y.toString() ], dflt: 'paper', @@ -36664,7 +36890,7 @@ var _$attributes_90 = { 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_186 = require('../../lib/to_log_range'); */; +/* removed: var _$toLogRange_187 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -36708,7 +36934,7 @@ var _$convertCoords_91 = function convertCoords(gd, ax, newType, doExtra) { newSize = null; if(toLog) { - newPos = _$toLogRange_186(currentPos, ax.range); + newPos = _$toLogRange_187(currentPos, ax.range); // this is the inverse of the conversion we do in fromLog below // so that the conversion is reversible (notice the fromLog conversion @@ -36744,9 +36970,9 @@ var _$convertCoords_91 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_202 = require('../../plots/array_container_defaults'); */; /* removed: var _$attributes_90 = require('./attributes'); */; var name = 'images'; @@ -36757,14 +36983,14 @@ var _$supplyLayoutDefaults_92 = function supplyLayoutDefaults(layoutIn, layoutOu handleItemDefaults: imageDefaults }; - _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_202(layoutIn, layoutOut, opts); }; function imageDefaults(imageIn, imageOut, fullLayout) { function coerce(attr, dflt) { - return _$lib_163.coerce(imageIn, imageOut, _$attributes_90, attr, dflt); + return _$lib_164.coerce(imageIn, imageOut, _$attributes_90, attr, dflt); } var source = coerce('source'); @@ -36786,9 +37012,9 @@ function imageDefaults(imageIn, imageOut, fullLayout) { for(var i = 0; i < 2; i++) { // 'paper' is the fallback axref var axLetter = axLetters[i], - axRef = _$axes_205.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + axRef = _$axes_206.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - _$axes_205.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + _$axes_206.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); } return imageOut; @@ -36806,7 +37032,7 @@ function imageDefaults(imageIn, imageOut, fullLayout) { /* removed: var _$d3_6 = require('d3'); */; /* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; /* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; var _$draw_93 = function draw(gd) { @@ -36920,8 +37146,8 @@ var _$draw_93 = function draw(gd) { var thisImage = _$d3_6.select(this); // Axes if specified - var xa = _$axes_205.getFromId(gd, d.xref), - ya = _$axes_205.getFromId(gd, d.yref); + var xa = _$axes_206.getFromId(gd, d.xref), + ya = _$axes_206.getFromId(gd, d.yref); var size = fullLayout._size, width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, @@ -37030,7 +37256,7 @@ var _$images_94 = { layoutAttributes: _$attributes_90, supplyLayoutDefaults: _$supplyLayoutDefaults_92, - includeBasePlot: _$makeIncludeComponents_215('images'), + includeBasePlot: _$makeIncludeComponents_216('images'), draw: _$draw_93, @@ -37183,8 +37409,8 @@ _$helpers_102.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$attributes_96 = require('./attributes'); */; /* removed: var _$layout_attributes_236 = require('../../plots/layout_attributes'); */; @@ -37206,10 +37432,10 @@ var _$legendDefaults_98 = function legendDefaults(layoutIn, layoutOut, fullData) if(_$helpers_102.legendGetsTrace(trace)) { visibleTraces++; // always show the legend by default if there's a pie - if(_$registry_253.traceIs(trace, 'pie')) visibleTraces++; + if(_$registry_254.traceIs(trace, 'pie')) visibleTraces++; } - if((_$registry_253.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + if((_$registry_254.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { defaultOrder = _$helpers_102.isGrouped({traceorder: defaultOrder}) ? 'grouped+reversed' : 'reversed'; @@ -37222,10 +37448,10 @@ var _$legendDefaults_98 = function legendDefaults(layoutIn, layoutOut, fullData) } function coerce(attr, dflt) { - return _$lib_163.coerce(containerIn, containerOut, _$attributes_96, attr, dflt); + return _$lib_164.coerce(containerIn, containerOut, _$attributes_96, attr, dflt); } - var showLegend = _$lib_163.coerce(layoutIn, layoutOut, + var showLegend = _$lib_164.coerce(layoutIn, layoutOut, _$layout_attributes_236, 'showlegend', visibleTraces > 1); if(showLegend === false) return; @@ -37235,7 +37461,7 @@ var _$legendDefaults_98 = function legendDefaults(layoutIn, layoutOut, fullData) coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - _$lib_163.coerceFont(coerce, 'font', layoutOut.font); + _$lib_164.coerceFont(coerce, 'font', layoutOut.font); coerce('orientation'); if(containerOut.orientation === 'h') { @@ -37261,7 +37487,7 @@ var _$legendDefaults_98 = function legendDefaults(layoutIn, layoutOut, fullData) coerce('xanchor', defaultXAnchor); coerce('y', defaultY); coerce('yanchor', defaultYAnchor); - _$lib_163.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_164.noneOrAll(containerIn, containerOut, ['x', 'y']); }; var _$anchor_utils_95 = {}; @@ -37341,7 +37567,7 @@ var _$constants_97 = { 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; /* removed: var _$helpers_102 = require('./helpers'); */; @@ -37380,7 +37606,7 @@ var _$getLegendData_100 = function getLegendData(calcdata, opts) { if(!_$helpers_102.legendGetsTrace(trace) || !trace.showlegend) continue; - if(_$registry_253.traceIs(trace, 'pie')) { + if(_$registry_254.traceIs(trace, 'pie')) { if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; for(j = 0; j < cd.length; j++) { @@ -37444,8 +37670,8 @@ var _$getLegendData_100 = function getLegendData(calcdata, opts) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; var SHOWISOLATETIP = true; @@ -37486,12 +37712,12 @@ var _$handleClick_101 = function handleClick(g, gd, numClicks) { function setVisibility(fullTrace, visibility) { var fullInput = fullTrace._fullInput; - if(_$registry_253.hasTransform(fullInput, 'groupby')) { + if(_$registry_254.hasTransform(fullInput, 'groupby')) { var kcont = carrs[fullInput.index]; if(!kcont) { - var groupbyIndices = _$registry_253.getTransformIndices(fullInput, 'groupby'); + var groupbyIndices = _$registry_254.getTransformIndices(fullInput, 'groupby'); var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_163.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + kcont = _$lib_164.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); carrs[fullInput.index] = kcont; } @@ -37522,13 +37748,13 @@ var _$handleClick_101 = function handleClick(g, gd, numClicks) { } if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_163.notifier(_$lib_163._(gd, 'Double-click on legend to isolate one trace'), 'long'); + _$lib_164.notifier(_$lib_164._(gd, 'Double-click on legend to isolate one trace'), 'long'); SHOWISOLATETIP = false; } else { SHOWISOLATETIP = false; } - if(_$registry_253.traceIs(fullTrace, 'pie')) { + if(_$registry_254.traceIs(fullTrace, 'pie')) { var thisLabel = legendItem.label, thisLabelIndex = hiddenSlices.indexOf(thisLabel); @@ -37547,7 +37773,7 @@ var _$handleClick_101 = function handleClick(g, gd, numClicks) { } } - _$registry_253.call('relayout', gd, 'hiddenlabels', hiddenSlices); + _$registry_254.call('relayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; @@ -37597,7 +37823,7 @@ var _$handleClick_101 = function handleClick(g, gd, numClicks) { isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - if(!isInGroup && fullData[i].visible === true && !_$registry_253.traceIs(fullData[i], 'notLegendIsolatable')) { + if(!isInGroup && fullData[i].visible === true && !_$registry_254.traceIs(fullData[i], 'notLegendIsolatable')) { isIsolated = false; break; } @@ -37607,7 +37833,7 @@ var _$handleClick_101 = function handleClick(g, gd, numClicks) { // False is sticky; we don't change it. if(fullData[i].visible === false) continue; - if(_$registry_253.traceIs(fullData[i], 'notLegendIsolatable')) { + if(_$registry_254.traceIs(fullData[i], 'notLegendIsolatable')) { continue; } @@ -37653,11 +37879,11 @@ var _$handleClick_101 = function handleClick(g, gd, numClicks) { } } - _$registry_253.call('restyle', gd, attrUpdate, attrIndices); + _$registry_254.call('restyle', gd, attrUpdate, attrIndices); } }; -var _$helpers_262 = {}; +var _$helpers_263 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -37668,25 +37894,25 @@ var _$helpers_262 = {}; 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -_$helpers_262.formatPiePercent = function formatPiePercent(v, separators) { +_$helpers_263.formatPiePercent = function formatPiePercent(v, separators) { var vRounded = (v * 100).toPrecision(3); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_163.numSeparate(vRounded, separators) + '%'; + return _$lib_164.numSeparate(vRounded, separators) + '%'; }; -_$helpers_262.formatPieValue = function formatPieValue(v, separators) { +_$helpers_263.formatPieValue = function formatPieValue(v, separators) { var vRounded = v.toPrecision(10); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_163.numSeparate(vRounded, separators); + return _$lib_164.numSeparate(vRounded, separators); }; -_$helpers_262.getFirstFilled = function getFirstFilled(array, indices) { +_$helpers_263.getFirstFilled = function getFirstFilled(array, indices) { if(!Array.isArray(array)) return; for(var i = 0; i < indices.length; i++) { var v = array[indices[i]]; @@ -37694,8 +37920,8 @@ _$helpers_262.getFirstFilled = function getFirstFilled(array, indices) { } }; -_$helpers_262.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_262.getFirstFilled(item, indices); +_$helpers_263.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_263.getFirstFilled(item, indices); else if(item) return item; }; @@ -37710,9 +37936,9 @@ _$helpers_262.castOption = function castOption(item, indices) { 'use strict'; /* removed: var _$color_43 = require('../../components/color'); */; -var castOption = _$helpers_262.castOption; +var castOption = _$helpers_263.castOption; -var _$styleOne_263 = function styleOne(s, pt, trace) { +var _$styleOne_264 = function styleOne(s, pt, trace) { var line = trace.marker.line; var lineColor = castOption(line.color, pt.pts) || _$color_43.defaultLine; var lineWidth = castOption(line.width, pt.pts) || 0; @@ -37730,28 +37956,23 @@ var _$styleOne_263 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$color_43 = require('../color'); */; -/* removed: var _$subtypes_287 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_263 = require('../../traces/pie/style_one'); */; - +/* removed: var _$subtypes_288 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_264 = require('../../traces/pie/style_one'); */; var _$style_104 = function style(s, gd) { s.each(function(d) { var traceGroup = _$d3_6.select(this); - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); + var layers = _$lib_164.ensureSingle(traceGroup, 'g', 'layers'); layers.style('opacity', d[0].trace.opacity); var fill = layers @@ -37781,12 +38002,14 @@ var _$style_104 = function style(s, gd) { .each(styleBoxes) .each(stylePies) .each(styleLines) - .each(stylePoints); + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); function styleLines(d) { var trace = d[0].trace; var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_287.hasLines(trace); + var showLine = _$subtypes_288.hasLines(trace); var contours = trace.contours; if(contours && contours.type === 'constraint') { @@ -37812,9 +38035,9 @@ var _$style_104 = function style(s, gd) { function stylePoints(d) { var d0 = d[0], trace = d0.trace, - showMarkers = _$subtypes_287.hasMarkers(trace), - showText = _$subtypes_287.hasText(trace), - showLines = _$subtypes_287.hasLines(trace); + showMarkers = _$subtypes_288.hasMarkers(trace), + showText = _$subtypes_288.hasText(trace), + showLines = _$subtypes_288.hasLines(trace); var dMod, tMod; @@ -37822,7 +38045,7 @@ var _$style_104 = function style(s, gd) { // use d0.trace to infer arrayOk attributes function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_163.nestedProperty(trace, attrIn).get(), + var valIn = _$lib_164.nestedProperty(trace, attrIn).get(), valToBound = (Array.isArray(valIn) && arrayToValFn) ? arrayToValFn(valIn) : valIn; @@ -37842,10 +38065,10 @@ var _$style_104 = function style(s, gd) { if(showMarkers) { dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_163.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_163.mean, [2, 16]); + dEdit.mo = boundVal('marker.opacity', _$lib_164.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_164.mean, [2, 16]); dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_163.mean, [0, 5]); + dEdit.mlw = boundVal('marker.line.width', _$lib_164.mean, [0, 5]); tEdit.marker = { sizeref: 1, sizemin: 1, @@ -37867,8 +38090,8 @@ var _$style_104 = function style(s, gd) { dEdit.tf = boundVal('textfont.family', pickFirst); } - dMod = [_$lib_163.minExtend(d0, dEdit)]; - tMod = _$lib_163.minExtend(trace, tEdit); + dMod = [_$lib_164.minExtend(d0, dEdit)]; + tMod = _$lib_164.minExtend(trace, tEdit); } var ptgroup = _$d3_6.select(this).select('g.legendpoints'); @@ -37899,7 +38122,7 @@ var _$style_104 = function style(s, gd) { markerLine = marker.line || {}, barpath = _$d3_6.select(this).select('g.legendpoints') .selectAll('path.legendbar') - .data(_$registry_253.traceIs(trace, 'bar') ? [d] : []); + .data(_$registry_254.traceIs(trace, 'bar') ? [d] : []); barpath.enter().append('path').classed('legendbar', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); @@ -37922,7 +38145,7 @@ var _$style_104 = function style(s, gd) { var trace = d[0].trace, pts = _$d3_6.select(this).select('g.legendpoints') .selectAll('path.legendbox') - .data(_$registry_253.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + .data(_$registry_254.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendbox', true) // if we want the median bar, prepend M6,0H-6 .attr('d', 'M6,6H-6V-6H6Z') @@ -37936,7 +38159,61 @@ var _$style_104 = function style(s, gd) { .call(_$color_43.fill, trace.fillcolor); if(w) { - p.call(_$color_43.stroke, trace.line.color); + _$color_43.stroke(p, trace.line.color); + } + }); + } + + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_6.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_6.select(this); + + p.style('stroke-width', w + 'px') + .call(_$color_43.fill, container.fillcolor); + + if(w) { + _$color_43.stroke(p, container.line.color); + } + }); + } + + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_6.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_6.select(this); + + p.style('fill', 'none') + .call(_$drawing_68.dashLine, container.line.dash, w); + + if(w) { + _$color_43.stroke(p, container.line.color); } }); } @@ -37945,13 +38222,13 @@ var _$style_104 = function style(s, gd) { var trace = d[0].trace, pts = _$d3_6.select(this).select('g.legendpoints') .selectAll('path.legendpie') - .data(_$registry_253.traceIs(trace, 'pie') && trace.visible ? [d] : []); + .data(_$registry_254.traceIs(trace, 'pie') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendpie', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); pts.exit().remove(); - if(pts.size()) pts.call(_$styleOne_263, d[0], trace); + if(pts.size()) pts.call(_$styleOne_264, d[0], trace); } }; @@ -37967,13 +38244,13 @@ var _$style_104 = function style(s, gd) { /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; /* removed: var _$dragelement_65 = require('../dragelement'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$color_43 = require('../color'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; /* removed: var _$handleClick_101 = require('./handle_click'); */; /* removed: var _$constants_97 = require('./constants'); */; @@ -38010,52 +38287,35 @@ var _$draw_99 = function draw(gd) { return; } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); - - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); - - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var firstRender = false; + var legend = _$lib_164.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - var bg = legend.selectAll('rect.bg') - .data([0]); + var clipPath = _$lib_164.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' + var bg = _$lib_164.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); }); bg.call(_$color_43.stroke, opts.bordercolor) .call(_$color_43.fill, opts.bgcolor) .style('stroke-width', opts.borderwidth + 'px'); - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); - - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); - - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); + var scrollBox = _$lib_164.ensureSingle(legend, 'g', 'scrollbox'); - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', + var scrollBar = _$lib_164.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ rx: 20, ry: 3, width: 0, height: 0 }) .call(_$color_43.fill, '#808BA4'); + }); var groups = scrollBox.selectAll('g.groups') .data(legendData); @@ -38066,7 +38326,7 @@ var _$draw_99 = function draw(gd) { groups.exit().remove(); var traces = groups.selectAll('g.traces') - .data(_$lib_163.identity); + .data(_$lib_164.identity); traces.enter().append('g').attr('class', 'traces'); traces.exit().remove(); @@ -38074,7 +38334,7 @@ var _$draw_99 = function draw(gd) { traces.call(_$style_104, gd) .style('opacity', function(d) { var trace = d[0].trace; - if(_$registry_253.traceIs(trace, 'pie')) { + if(_$registry_254.traceIs(trace, 'pie')) { return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; } else { return trace.visible === 'legendonly' ? 0.5 : 1; @@ -38086,7 +38346,6 @@ var _$draw_99 = function draw(gd) { .call(setupTraceToggle, gd); }); - var firstRender = legend.enter().size() !== 0; if(firstRender) { computeLegendDimensions(gd, groups, traces); expandMargin(gd); @@ -38228,7 +38487,7 @@ var _$draw_99 = function draw(gd) { scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); legend.on('wheel', function() { - scrollBoxY = _$lib_163.constrain( + scrollBoxY = _$lib_164.constrain( opts._scrollY + _$d3_6.event.deltaY / scrollBarYMax * scrollBoxYMax, 0, scrollBoxYMax); @@ -38249,7 +38508,7 @@ var _$draw_99 = function draw(gd) { var e = _$d3_6.event.sourceEvent; if(e.buttons === 2 || e.ctrlKey) return; - scrollBoxY = _$lib_163.constrain( + scrollBoxY = _$lib_164.constrain( (e.clientY - eventY0) / scrollRatio + scrollBoxY0, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); @@ -38300,7 +38559,7 @@ var _$draw_99 = function draw(gd) { }, doneFn: function() { if(xf !== undefined && yf !== undefined) { - _$registry_253.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + _$registry_254.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); } }, clickFn: function(numClicks, e) { @@ -38331,14 +38590,11 @@ function drawTexts(g, gd) { var legendItem = g.data()[0][0], fullLayout = gd._fullLayout, trace = legendItem.trace, - isPie = _$registry_253.traceIs(trace, 'pie'), + isPie = _$registry_254.traceIs(trace, 'pie'), traceIndex = trace.index, name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); + var text = _$lib_164.ensureSingle(g, 'text', 'legendtext'); text.attr('text-anchor', 'start') .classed('user-select-none', true) @@ -38346,13 +38602,13 @@ function drawTexts(g, gd) { .text(name); function textLayout(s) { - _$svg_text_utils_184.convertToTspans(s, gd, function() { + _$svg_text_utils_185.convertToTspans(s, gd, function() { computeTextDimensions(g, gd); }); } if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_184.makeEditable, {gd: gd}) + text.call(_$svg_text_utils_185.makeEditable, {gd: gd}) .call(textLayout) .on('edit', function(text) { this.text(text) @@ -38362,24 +38618,14 @@ function drawTexts(g, gd) { if(!this.text()) text = ' \u0020\u0020 '; - var transforms, direction; var fullInput = legendItem.trace._fullInput || {}; var update = {}; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_253.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_253.getTransformIndices(fullInput, 'groupby'); + if(_$registry_254.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_254.getTransformIndices(fullInput, 'groupby'); var index = groupbyIndices[groupbyIndices.length - 1]; - var kcont = _$lib_163.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + var kcont = _$lib_164.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); if(origText === '') { kcont.remove(legendItem.trace._group); @@ -38392,7 +38638,7 @@ function drawTexts(g, gd) { update.name = text; } - return _$registry_253.call('restyle', gd, update, traceIndex); + return _$registry_254.call('restyle', gd, update, traceIndex); }); } else { textLayout(text); @@ -38403,15 +38649,11 @@ function setupTraceToggle(g, gd) { var newMouseDownTime, numClicks = 1; - var traceToggle = g.selectAll('rect') - .data([0]); - - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_43.fill, 'rgba(0,0,0,0)'); - + var traceToggle = _$lib_164.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_43.fill, 'rgba(0,0,0,0)'); + }); traceToggle.on('mousedown', function() { newMouseDownTime = (new Date()).getTime(); @@ -38469,7 +38711,7 @@ function computeTextDimensions(g, gd) { } else { var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_184.lineCount(text); + var textLines = _$svg_text_utils_185.lineCount(text); var textNode = text.node(); height = lineHeight * textLines; @@ -38480,7 +38722,7 @@ function computeTextDimensions(g, gd) { var textY = lineHeight * (0.3 + (1 - textLines) / 2); // TODO: this 40 should go in a constants file (along with other // values related to the legend symbol size) - _$svg_text_utils_184.positionText(text, 40, textY); + _$svg_text_utils_185.positionText(text, 40, textY); } height = Math.max(height, 16) + 3; @@ -38768,7 +39010,7 @@ var _$button_attributes_110 = { /* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; /* removed: var _$attributes_42 = require('../color/attributes'); */; -var __extendFlat_109 = _$extend_156.extendFlat; +var __extendFlat_109 = _$extend_157.extendFlat; /* removed: var _$button_attributes_110 = require('./button_attributes'); */; _$button_attributes_110 = __extendFlat_109(_$button_attributes_110, { @@ -38894,7 +39136,7 @@ var _$constants_111 = { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$attributes_109 = require('./attributes'); */; @@ -38907,7 +39149,7 @@ var _$handleDefaults_112 = function handleDefaults(containerIn, containerOut, la selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(selectorIn, selectorOut, _$attributes_109, attr, dflt); + return _$lib_164.coerce(selectorIn, selectorOut, _$attributes_109, attr, dflt); } var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); @@ -38918,12 +39160,12 @@ var _$handleDefaults_112 = function handleDefaults(containerIn, containerOut, la var posDflt = getPosDflt(containerOut, layout, counterAxes); coerce('x', posDflt[0]); coerce('y', posDflt[1]); - _$lib_163.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_164.noneOrAll(containerIn, containerOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); - _$lib_163.coerceFont(coerce, 'font', layout.font); + _$lib_164.coerceFont(coerce, 'font', layout.font); var bgColor = coerce('bgcolor'); coerce('activecolor', _$color_43.contrast(bgColor, _$constants_111.lightAmount, _$constants_111.darkAmount)); @@ -38938,14 +39180,14 @@ function buttonsDefaults(containerIn, containerOut, calendar) { var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_163.coerce(buttonIn, buttonOut, _$button_attributes_110, attr, dflt); + return _$lib_164.coerce(buttonIn, buttonOut, _$button_attributes_110, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { buttonIn = buttonsIn[i]; buttonOut = {}; - if(!_$lib_163.isPlainObject(buttonIn)) continue; + if(!_$lib_164.isPlainObject(buttonIn)) continue; var step = coerce('step'); if(step !== 'all') { @@ -39050,12 +39292,13 @@ function getXRange(axisLayout, buttonLayout) { /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_209 = require('../../plots/cartesian/axis_ids'); */; /* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; /* removed: var _$alignment_143 = require('../../constants/alignment'); */; @@ -39108,7 +39351,7 @@ var _$draw_113 = function draw(gd) { button.on('click', function() { if(gd._dragged) return; - _$registry_253.call('relayout', gd, update); + _$registry_254.call('relayout', gd, update); }); button.on('mouseover', function() { @@ -39128,7 +39371,7 @@ var _$draw_113 = function draw(gd) { }; function makeSelectorData(gd) { - var axes = _$axis_ids_208.list(gd, 'x', true); + var axes = _$axis_ids_209.list(gd, 'x', true); var data = []; for(var i = 0; i < axes.length; i++) { @@ -39161,13 +39404,9 @@ function isActive(axisLayout, opts, update) { } function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - - rect.attr('shape-rendering', 'crispEdges'); + var rect = _$lib_164.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); rect.attr({ 'rx': _$constants_111.rx, @@ -39187,17 +39426,13 @@ function getFillColor(selectorLayout, d) { function drawButtonText(button, selectorLayout, d, gd) { function textLayout(s) { - _$svg_text_utils_184.convertToTspans(s, gd); + _$svg_text_utils_185.convertToTspans(s, gd); } - var text = button.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - - text.attr('text-anchor', 'middle'); + var text = _$lib_164.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); text.call(_$drawing_68.font, selectorLayout.font) .text(getLabel(d)) @@ -39223,7 +39458,7 @@ function reposition(gd, buttons, opts, axName, selector) { var text = button.select('.selector-text'); var tHeight = opts.font.size * __LINE_SPACING_113; - var hEff = Math.max(tHeight * _$svg_text_utils_184.lineCount(text), 16) + 3; + var hEff = Math.max(tHeight * _$svg_text_utils_185.lineCount(text), 16) + 3; height = Math.max(height, hEff); }); @@ -39235,7 +39470,7 @@ function reposition(gd, buttons, opts, axName, selector) { var tWidth = text.node() && _$drawing_68.bBox(text.node()).width; var tHeight = opts.font.size * __LINE_SPACING_113; - var tLines = _$svg_text_utils_184.lineCount(text); + var tLines = _$svg_text_utils_185.lineCount(text); var wEff = Math.max(tWidth + 10, _$constants_111.minButtonWidth); @@ -39254,7 +39489,7 @@ function reposition(gd, buttons, opts, axName, selector) { height: height }); - _$svg_text_utils_184.positionText(text, wEff / 2, + _$svg_text_utils_185.positionText(text, wEff / 2, height / 2 - ((tLines - 1) * tHeight / 2) + 3); width += wEff + 5; @@ -39465,8 +39700,8 @@ var _$constants_118 = { 'use strict'; -var listAxes = _$axis_ids_208.list; -var __getAutoRange_117 = _$autorange_204.getAutoRange; +var listAxes = _$axis_ids_209.list; +var __getAutoRange_117 = _$autorange_205.getAutoRange; /* removed: var _$constants_118 = require('./constants'); */; var _$calcAutorange_117 = function calcAutorange(gd) { @@ -39538,29 +39773,31 @@ var _$oppaxis_attributes_122 = { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$attributes_116 = require('./attributes'); */; /* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$axis_ids_209 = require('../../plots/cartesian/axis_ids'); */; var _$handleDefaults_119 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; + 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_163.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; + if(!_$lib_164.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; } - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(containerIn, containerOut, _$attributes_116, attr, dflt); + return _$lib_164.coerce(containerIn, containerOut, _$attributes_116, attr, dflt); } function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_163.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_122, attr, dflt); + return _$lib_164.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_122, attr, dflt); } var visible = coerce('visible'); @@ -39578,12 +39815,12 @@ var _$handleDefaults_119 = function handleDefaults(layoutIn, layoutOut, axName) if(subplots) { var yIds = subplots.cartesian .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_208.name2id(axName); + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_209.name2id(axName); }) .map(function(subplotId) { return subplotId.substr(subplotId.indexOf('y'), subplotId.length); }); - var yNames = _$lib_163.simpleMap(yIds, _$axis_ids_208.id2name); + var yNames = _$lib_164.simpleMap(yIds, _$axis_ids_209.id2name); for(var i = 0; i < yNames.length; i++) { var yName = yNames[i]; @@ -39620,7 +39857,7 @@ var _$handleDefaults_119 = function handleDefaults(layoutIn, layoutOut, axName) 'use strict'; -var _$attributes_203 = { +var _$attributes_204 = { xaxis: { valType: 'subplotid', @@ -39647,90 +39884,20 @@ var _$attributes_203 = { 'use strict'; - -var _$handleCategoryOrderDefaults_209 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; - - var arrayIn = containerIn.categoryarray, - orderDefault; - - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); - - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; - - var order = coerce('categoryorder', orderDefault); - - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); - - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var colorMix = _$tinycolor_25.mix; -var lightFraction = _$attributes_42.lightFraction; -/* removed: var _$lib_163 = require('../../lib'); */; - /** - * @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 + * 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 */ -var _$handleLineGridDefaults_219 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; - - var dfltColor = opts.dfltColor; - - function coerce2(attr, dflt) { - return _$lib_163.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); +var _$clearGlCanvases_152 = function clearGlCanvases(gd) { + var fullLayout = gd._fullLayout; - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); + }); } }; @@ -39745,1196 +39912,1930 @@ var _$handleLineGridDefaults_219 = function handleLineGridDefaults(containerIn, 'use strict'; -/* removed: var _$d3_6 = require('d3'); */; - -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { - - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. - - var categoryArray = []; - - var traceLines = data.map(function(d) {return d[axisLetter];}); - - var i, j, tracePoints, category, insertionIndex; - - var bisector = _$d3_6.bisector(sortFunction).left; - - for(i = 0; i < traceLines.length; i++) { +var FROM_BL = _$alignment_143.FROM_BL; - tracePoints = traceLines[i]; +var _$scaleZoom_222 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } - for(j = 0; j < tracePoints.length; j++) { + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - category = tracePoints[j]; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - insertionIndex = bisector(categoryArray, category); +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } - } + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - return categoryArray; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; } +var _$BuildLog_17 = BuildLog; -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ - -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_220 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_6.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_6.descending, data); - case 'trace': return []; - default: return []; - } -}; +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; -'use strict'; + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; -/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_227 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_226 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_225 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_209 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_219 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_224 = require('./set_convert'); */; -/* removed: var _$orderedCategories_220 = require('./ordered_categories'); */; + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; -/** - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_207 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - var visible = coerce('visible', !options.cheateronly); + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - var axType = containerOut.type; + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; - if(axType === 'date') { - var handleCalendarDefaults = _$registry_253.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; - _$setConvert_224(containerOut, layoutOut); + // categorize where intersection point is along A and B - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if(autoRange) coerce('rangemode'); + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; - coerce('range'); - containerOut.cleanRange(); + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside - _$handleCategoryOrderDefaults_209(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_220(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} +var _$Epsilon_18 = Epsilon; - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if(!visible) return containerOut; +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_163.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - _$handleTickValueDefaults_227(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_225(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_226(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_219(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_217 - }); + // 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] }); + } - if(containerOut.showline || containerOut.ticks) coerce('mirror'); + // the first LineString is considered the outside + var out = LineString(coords[0]); - if(options.automargin) coerce('automargin'); + // 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 containerOut; -}; + return out; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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)); -'use strict'; + // 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); + } -/* removed: var _$lib_163 = require('../../lib'); */; -var id2name = _$axis_ids_208.id2name; + // 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 _$handleConstraintDefaults_211 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); + var roots = newNode(null); - if(containerOut.fixedrange) return; + 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; + } + } - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_163.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); + // 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--; + } + } - if(!containerIn.scaleanchor) return; + // now we can add ourselves + root.children.push(node); + } - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + // 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); + } - var scaleanchor = _$lib_163.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); + // 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 - 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; + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_163.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.'); - } -}; + 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; + } -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. + var geopolys = []; - var thisType = layoutOut[id2name(thisID)].type; + 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])); + } - var i, j, idj, axj; + 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); + } - var linkableAxes = []; - for(j = 0; j < allAxisIds.length; j++) { - idj = allAxisIds[j]; - if(idj === thisID) continue; + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - axj = layoutOut[id2name(idj)]; - if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); - } + // lastly, construct the approrpriate GeoJSON object - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[i]; + 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 + }; + } +}; - var linkableAxesNoLoops = []; - for(j = 0; j < linkableAxes.length; j++) { - idj = linkableAxes[j]; - if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); - } - return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; - } - } +var _$GeoJSON_19 = GeoJSON; - return {linkableAxes: linkableAxes, thisGroup: null}; -} +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// -/* - * 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; +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } +}; - if(thisGroup === null) { - thisGroup = {}; - thisGroup[thisID] = 1; - thisGroupIndex = constraintGroups.length; - constraintGroups.push(thisGroup); - } - else { - thisGroupIndex = constraintGroups.indexOf(thisGroup); - } +var _$LinkedList_21 = LinkedList; - 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; -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs +// +// this is the core work-horse +// -'use strict'; +/* removed: var _$LinkedList_21 = require('./linked-list'); */; -/* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm -/* removed: var _$lib_163 = require('../../lib'); */; + // + // segment creation + // + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } -var _$handlePositionDefaults_221 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; + // + // event logic + // - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } - } + var event_root = _$LinkedList_21.create(); - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_9(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same - var anchor = _$lib_163.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - if(anchor === 'free') coerce('position', dfltPosition); + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start - _$lib_163.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_163.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); - } + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_163.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); - } + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_21.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } - coerce('layer'); + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_21.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } - return containerOut; -}; + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) + if (buildLog) + buildLog.segmentChop(ev.seg, end); -'use strict'; + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$autoType_206 = require('./axis_autotype'); */; -var name2id = _$axis_ids_208.name2id; + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored - */ -var _$handleTypeDefaults_229 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); + // + // status logic + // - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; - } - } -}; + var status_root = _$LinkedList_21.create(); -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; - var id = ax._id, - axLetter = id.charAt(0); + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; + if (buildLog) + buildLog.checkIntersection(seg1, seg2); - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; + var i = eps.linesIntersect(a1, a2, b1, b2); - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_253.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; + if (i === false){ + // segments are parallel or coincident - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) - if(trace[calAttr] !== calendar) calendar = undefined; - } + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection - ax.type = _$autoType_206(boxPositions, calendar); - } - else { - ax.type = _$autoType_206(d0[axLetter] || [d0[axLetter + '0']], calendar); - } -} + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; - } - } - } -} + var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_253.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_253.traceIs(trace._fullInput || {}, 'candlestick'); + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } -'use strict'; + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$layout_attributes_236 = require('../layout_attributes'); */; + if (buildLog) + buildLog.vert(ev.pt[0]); -/* removed: var _$layout_attributes_217 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_229 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_207 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_211 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_221 = require('./position_defaults'); */; -/* removed: var _$axis_ids_208 = require('./axis_ids'); */; + if (ev.isStart){ + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); -var _$supplyLayoutDefaults_218 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - if(!_$registry_253.traceIs(trace, 'cartesian') && !_$registry_253.traceIs(trace, 'gl2d')) { - continue; - } + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } - var xaName = _$axis_ids_208.id2name(trace.xaxis); - var yaName = _$axis_ids_208.id2name(trace.yaxis); + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_253.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; - } + // merge ev.seg's fill information into eve.seg - // 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) xaCheater[xaName] = 1; - } + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - // check for default formatting tweaks - if(_$registry_253.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } - if(_$registry_253.traceIs(trace, 'oriented')) { - var positionAxis = trace.orientation === 'h' ? yaName : xaName; - noGrids[positionAxis] = true; - } - } + if (buildLog) + buildLog.segmentUpdate(eve.seg); - var subplots = layoutOut._subplots; - var xIds = subplots.xaxis; - var yIds = subplots.yaxis; - var xNames = _$lib_163.simpleMap(xIds, _$axis_ids_208.id2name); - var yNames = _$lib_163.simpleMap(yIds, _$axis_ids_208.id2name); - var axNames = xNames.concat(yNames); + ev.other.remove(); + ev.remove(); + } - // plot_bgcolor only makes sense if there's a (2D) plot! - // TODO: bgcolor for each subplot, to inherit from the main one - var plot_bgcolor = _$color_43.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_163.coerce(layoutIn, layoutOut, _$layout_attributes_236, 'plot_bgcolor'); - } + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } - var bgColor = _$color_43.combine(plot_bgcolor, layoutOut.paper_bgcolor); + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle - var axName, axLetter, axLayoutIn, axLayoutOut; - - function coerce(attr, dflt) { - return _$lib_163.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_217, attr, dflt); - } + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } - function coerce2(attr, dflt) { - return _$lib_163.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_217, attr, dflt); - } + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; - } + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } - function getOverlayableAxes(axLetter, axName) { - var list = (axLetter === 'x') ? xNames : yNames; - var out = []; + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_21.node({ ev: ev })); + } + else{ + var st = ev.status; - for(var j = 0; j < list.length; j++) { - var axName2 = list[j]; + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } - if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { - out.push(_$axis_ids_208.name2id(axName2)); - } - } + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); - return out; - } + if (buildLog) + buildLog.statusRemove(st.ev.seg); - // first pass creates the containers, determines types, and handles most of the settings - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; + // remove the status + st.remove(); - if(!_$lib_163.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; + // remove the event and continue + event_root.getHead().remove(); + } - _$handleTypeDefaults_229(axLayoutIn, axLayoutOut, coerce, fullData, axName); + if (buildLog) + buildLog.done(); - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); + return segments; + } - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } - _$handleAxisDefaults_207(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it - if(!showSpikes) { - delete axLayoutOut.spikecolor; - delete axLayoutOut.spikethickness; - delete axLayoutOut.spikedash; - delete axLayoutOut.spikemode; - delete axLayoutOut.spikesnap; - } + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; +var _$Intersecter_20 = Intersecter; - _$handlePositionDefaults_221(axLayoutIn, axLayoutOut, coerce, positioningOptions); +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - axLayoutOut._input = axLayoutIn; - } +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_253.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_253.getComponentMethod('rangeselector', 'handleDefaults'); +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; - for(i = 0; i < xNames.length; i++) { - axName = xNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } - rangeSliderDefaults(layoutIn, layoutOut, axName); + if (buildLog) + buildLog.chainStart(seg); - if(axLayoutOut.type === 'date') { - rangeSelectorDefaults( - axLayoutIn, - axLayoutOut, - layoutOut, - yNames, - axLayoutOut.calendar - ); - } + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } - coerce('fixedrange'); - } + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } - for(i = 0; i < yNames.length; i++) { - axName = yNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + if (next_match === second_match){ + // we matched a single chain - var anchoredAxis = layoutOut[_$axis_ids_208.id2name(axLayoutOut.anchor)]; + if (buildLog) + buildLog.chainMatch(first_match.index); - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop - coerce('fixedrange', fixedRangeDflt); - } + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head - // Finally, handle scale constraints. 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). + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - // sets of axes linked by `scaleanchor` along with the scaleratios compounded - // together, populated in handleConstraintDefaults - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } - _$handleConstraintDefaults_211(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } -}; + if (buildLog) + buildLog.chainClose(first_match.index); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // we have a closed chain! + regions.push(chain); + return; + } -'use strict'; + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } -/* removed: var _$d3_6 = require('d3'); */; + // otherwise, we matched two chains, so we need to combine those chains together -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$axes_205 = require('./axes'); */; -var axisRegex = _$constants_210.attrRegex; + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } -var _$transitionAxes_228 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var axes = []; + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); - } - } - if(!update.to) continue; + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } - update.axisName = axisName; - update.length = axis._length; + var F = first_match.index; + var S = second_match.index; - axes.push(axisLetter); + if (buildLog) + buildLog.chainConnect(F, S); - updates[axisLetter] = update; - } - } + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); - return updates; - } + return regions; +} - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; +var _$SegmentChainer_22 = SegmentChainer; - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; +// +// filter a list of segments based on boolean operations +// - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); + if (buildLog) + buildLog.selected(result); - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; - } + return result; +} - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); - } - } +var _$SegmentSelector_23 = SegmentSelector; - return affectedSubplots; - } +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); +/* removed: var _$BuildLog_17 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_18 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_20 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_22 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_23 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_19 = require('./lib/geojson'); */; - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); +var buildLog = false; +var epsilon = _$Epsilon_18(); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_17(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v){ + return epsilon.epsilon(v); + }, - redrawObjs(fullLayout.annotations || [], _$registry_253.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_253.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_253.getComponentMethod('images', 'draw'), true); - } + // core API + segments: function(poly){ + var i = _$Intersecter_20(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_20(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_23.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_23.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_23.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_23.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_23.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_22(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; - } + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_19.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_19.fromPolygon(PolyBool, epsilon, poly); + }, - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; + // 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); + } +}; - activeAxIds = [xa._id, ya._id]; +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); +} - for(i = 0; i < activeAxIds.length; i++) { - _$axes_205.doTicks(gd, activeAxIds[i], true); - } +if (typeof window === 'object') + window.PolyBool = PolyBool; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +var _$PolyBool_16 = PolyBool; - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - } +var _$polygon_176 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - redrawObjs(fullLayout.annotations || [], _$registry_253.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_253.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_253.getComponentMethod('images', 'draw'), true); - } +'use strict'; - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; +var dot = _$matrix_170.dot; +var __BADNUM_176 = _$numerical_145.BADNUM; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_68.setTranslate, 0, 0) - .call(_$drawing_68.setScale, 1, 1); +var polygon = _$polygon_176 = {}; - subplot.plot - .call(_$drawing_68.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_68.setScale, 1, 1); +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; - // 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_68.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_68.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_68.hideOutsideRangePoints, subplot); + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); } - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed - var viewBox = []; + var isRect = false, + rectFirstEdgeTest; - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; + } + } + } - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; + if(x === __BADNUM_176 || x < xmin || x > xmax || y === __BADNUM_176 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + return true; + } - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); - } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; + if(x === __BADNUM_176 || x < xmin || x > xmax || y === __BADNUM_176 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; } - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; - var editX = !!xUpdate; - var editY = !!yUpdate; + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; - - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_68.setTranslate, clipDx, clipDy) - .call(_$drawing_68.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - - subplot.plot - .call(_$drawing_68.setTranslate, plotDx, plotDy) - .call(_$drawing_68.setScale, xScaleFactor, yScaleFactor) - - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_68.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_68.setTextPointsScale, 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 < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; - - axi.range = to.slice(); - } - - // Signal that this transition has completed: - onComplete && onComplete(); - - return _$registry_253.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + if(y <= ycross && x !== xmini) crossings++; } - }); - } - - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; - - axi.range = axi._r.slice(); } - return _$registry_253.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; } - var t1, t2, raf; - var easeFn = _$d3_6.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 < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } - - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; } } - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); - - return Promise.resolve(); + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; }; -var _$get_data_234 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$registry_253 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_210.SUBPLOT_PATTERN; - /** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces + * Test multiple polygons */ -_$get_data_234.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_253.subplotsRegistry[type]; - if(!basePlotModule) return []; +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; - var attr = basePlotModule.attr; - var subplotCalcData = []; + for(var i = 0; i < list.length; i++) { + 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); + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); + return yes; } - return subplotCalcData; + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; }; -_$get_data_234.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_253.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; } - - return moduleCalcData; + return false; }; /** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. + * Make a filtering polygon, to minimize the number of segments * - * @return {array} list of trace objects. + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs */ -_$get_data_234.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_253.subplotsRegistry[type]) return []; - - var attr = _$registry_253.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; - - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; - } +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; - for(var i = 0; i < data.length; i++) { - trace = data[i]; + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); - if(type === 'gl2d' && _$registry_253.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; } } - else { - if(trace[attr] === subplotId) subplotData.push(trace); - } } - return subplotData; + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } + + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; }; -var _$cartesian_216 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -40946,542 +41847,467 @@ var _$cartesian_216 = {}; 'use strict'; -/* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$plots_245 = require('../plots'); */; -var getModuleCalcData = _$get_data_234.getModuleCalcData; - -/* removed: var _$axis_ids_208 = require('./axis_ids'); */; -/* removed: var _$constants_210 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; - -_$cartesian_216.name = 'cartesian'; - -_$cartesian_216.attr = ['xaxis', 'yaxis']; - -_$cartesian_216.idRoot = ['x', 'y']; - -_$cartesian_216.idRegex = _$constants_210.idRegex; - -_$cartesian_216.attrRegex = _$constants_210.attrRegex; +/* removed: var _$PolyBool_16 = require('polybooljs'); */; -_$cartesian_216.attributes = _$attributes_203; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$fx_85 = require('../../components/fx'); */; -_$cartesian_216.layoutAttributes = _$layout_attributes_217; +/* removed: var _$polygon_176 = require('../../lib/polygon'); */; +/* removed: var _$throttle_186 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_82.makeEventData; +var getFromId = _$axis_ids_209.getFromId; +var __sortModules_223 = _$sort_modules_252.sortModules; -_$cartesian_216.supplyLayoutDefaults = _$supplyLayoutDefaults_218; +/* removed: var _$constants_211 = require('./constants'); */; +var MINSELECT = _$constants_211.MINSELECT; -_$cartesian_216.transitionAxes = _$transitionAxes_228; +var filteredPolygon = _$polygon_176.filter; +var polygonTester = _$polygon_176.tester; +var multipolygonTester = _$polygon_176.multitester; -_$cartesian_216.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; +function getAxId(ax) { return ax._id; } - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_208.id2name(xi)] || {}).anchor; - if(!_$constants_210.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); - if(!allY[yi]) { - allY[yi] = 1; - _$lib_163.pushUnique(yList, yi); - } - } + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; } - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_208.id2name(yi)] || {}).anchor; - if(!_$constants_210.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); - - if(!allX[xi]) { - allX[xi] = 1; - _$lib_163.pushUnique(xList, xi); - } - } + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; } - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_210.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_208.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_208.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_211.BENDPX); } -}; - -_$cartesian_216.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; - - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); - } + 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'); - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + var corners = zoomLayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_43.background, + stroke: _$color_43.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_211.SELECTID; + var selection = []; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + for(i = 0; i < gd.calcdata.length; i++) { + cd = gd.calcdata[i]; + trace = cd[0].trace; - cdSubplot.push(cd); - } + if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; + if(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); + } } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(v[index]); }; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; - - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + function ascending(a, b) { return a - b; } - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); - } -} + // allow subplots to override fillRangeItems routine + var fillRangeItems; -_$cartesian_216.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + if(plotinfo.fillRangeItems) { + fillRangeItems = plotinfo.fillRangeItems; + } else { + if(mode === 'select') { + fillRangeItems = function(eventData, poly) { + var ranges = eventData.range = {}; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + var axLetter = ax._id.charAt(0); + ranges[ax._id] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(poly[axLetter + 'max']) + ].sort(ascending); + } + }; + } else { + fillRangeItems = function(eventData, poly, filterPoly) { + var dataPts = eventData.lassoPoints = {}; - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; + for(i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); + } + }; + } } - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + dragOptions.moveFn = function(dx0, dy0) { + x1 = Math.max(0, Math.min(pw, dx0 + x0)); + y1 = Math.max(0, Math.min(ph, dy0 + y0)); - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + var dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(mode === 'select') { + var direction = fullLayout.selectdirection; - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + 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; } - } - - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); - } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); - - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + 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'); - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); } - } - } - - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); - - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + 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'); } - } - } - - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); + 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'); } } - } -}; - -_$cartesian_216.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); - - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_163.identity); - - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); - - subplotLayers.order(); - - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); - - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; - - // keep ref to plot group - plotinfo.plotgroup = _$d3_6.select(this); + else if(mode === 'lasso') { + filterPoly.addPt([x1, y1]); + currentPolygon = filterPoly.filtered; + } - // initialize list of overlay subplots - plotinfo.overlays = []; + // create outline & tester + if(dragOptions.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + _$throttle_186.throttle( + throttleID, + _$constants_211.SELECTDELAY, + function() { + selection = []; -_$cartesian_216.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_245.style(gd); -}; + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + traceSelections.push(traceSelection); - var subplotData = [], - overlays = []; + thisSelection = fillSelectionItem(traceSelection, searchInfo); - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + if(selection.length) { + for(var j = 0; j < thisSelection.length; j++) { + selection.push(thisSelection[j]); + } + } + else selection = thisSelection; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + eventData = {points: selection}; + updateSelectedState(gd, searchTraces, eventData); + fillRangeItems(eventData, currentPolygon, filterPoly); + dragOptions.gd.emit('plotly_selecting', eventData); + } + ); + }; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); - } - else { - subplotData.push(subplot); - } - } + dragOptions.clickFn = function(numClicks, evt) { + corners.remove(); - // main subplots before overlays - subplotData = subplotData.concat(overlays); + _$throttle_186.done(throttleID).then(function() { + _$throttle_186.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); + } - return subplotData; -} + updateSelectedState(gd, searchTraces); + gd.emit('plotly_deselect', null); + } + else { + // 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. + gd.emit('plotly_selected', undefined); + } -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_210.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_210.layerValue2layerClass[plotinfo.yaxis.layer]; + _$fx_85.click(gd, evt); + }); + }; - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); + dragOptions.doneFn = function() { + corners.remove(); - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); + _$throttle_186.done(throttleID).then(function() { + _$throttle_186.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + if(eventData) { + var pts = eventData.points || []; - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.selectedpoints = []; + } - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + for(i = 0; i < pts.length; i++) { + var pt = pts[i]; + var data = pt.data; + var fullData = pt.fullData; - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + if(pt.pointIndices) { + [].push.apply(data.selectedpoints, pt.pointIndices); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + fullData.selectedpoints.push(pt.pointIndex); + } + } } else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); - - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); - - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); - - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + delete trace.selectedpoints; + delete trace._input.selectedpoints; + } } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_208.idSort); + // group searchInfo traces by trace modules + var lookup = {}; - // common attributes for all subplots, overlays or not + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; - for(var i = 0; i < _$constants_210.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_210.traceLayerClasses[i]); + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; + } } - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + var keys = Object.keys(lookup).sort(__sortModules_223); - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_254.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } + } + } } -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; - - var overlayIdsToRemove = {}; - - layers.each(function(subplotId) { - var plotgroup = _$d3_6.select(this); +function mergePolygons(list, poly, subtract) { + var res; - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + if(subtract) { + res = _$PolyBool_16.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); - overlayIdsToRemove[subplotId] = true; + return res.regions; + } - // do not remove individual axis s here - // as other subplots may need them + res = _$PolyBool_16.union({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false }); - // must remove overlaid subplot trace layers 'manually' - - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); - - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + return res.regions; +} - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; +function fillSelectionItem(selection, searchInfo) { + if(Array.isArray(selection)) { + var cd = searchInfo.cd; + var trace = searchInfo.cd[0].trace; - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); - } + for(var i = 0; i < selection.length; i++) { + selection[i] = makeEventData(selection[i], trace, cd); } } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); + return selection; } -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); - - layer.enter().append(nodeType) - .classed(className, true); - - return layer; +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); } -_$cartesian_216.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_6.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); - - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); - - image.attr({ - xmlns: _$xmlns_namespaces_147.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height - }); - } - - canvases.each(canvasToImage); +var _$select_223 = { + prepSelect: prepSelect, + clearSelect: clearSelect }; /** @@ -41492,681 +42318,1156 @@ _$cartesian_216.toSVG = function(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; /* removed: var _$d3_6 = require('d3'); */; +/* removed: var _$tinycolor_25 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_12 = require('has-passive-events'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$plots_245 = require('../../plots/plots'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_152 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$drawing_68 = require('../../components/drawing'); */; +/* removed: var _$fx_85 = require('../../components/fx'); */; +/* removed: var _$setCursor_183 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; +var __FROM_TL_214 = _$alignment_143.FROM_TL; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$titles_136 = require('../titles'); */; +/* removed: var _$plots_245 = require('../plots'); */; -/* removed: var _$cartesian_216 = require('../../plots/cartesian'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +var doTicks = _$axes_206.doTicks; +var __getFromId_214 = _$axis_ids_209.getFromId; +var __prepSelect_214 = _$select_223.prepSelect; +var __clearSelect_214 = _$select_223.clearSelect; +/* removed: var _$scaleZoom_222 = require('./scale_zoom'); */; -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; +/* removed: var _$constants_211 = require('./constants'); */; +var MINDRAG = _$constants_211.MINDRAG; +var MINZOOM = _$constants_211.MINZOOM; -/* removed: var _$constants_118 = require('./constants'); */; -var _$draw_120 = function(gd) { - var fullLayout = gd._fullLayout, - rangeSliderData = makeRangeSliderData(fullLayout); +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; - /* - * - * - * < .... range plot /> - * - * - * - * - * - * - * - * - * - * - * ... - */ +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; - function keyFunction(axisOpts) { - return axisOpts._name; - } + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; - var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_118.containerClassName) - .data(rangeSliderData, keyFunction); + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; - rangeSliders.enter().append('g') - .classed(_$constants_118.containerClassName, true) - .attr('pointer-events', 'all'); + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; - // remove exiting sliders and their corresponding clip paths - rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_6.select(this), - opts = axisOpts[_$constants_118.name]; + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } - rangeSlider.remove(); - fullLayout._topdefs.select('#' + opts._clipId).remove(); - }); + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; - // remove push margin object(s) - if(rangeSliders.exit().size()) clearPushMargins(gd); + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; + } - // return early if no range slider is visible - if(rangeSliderData.length === 0) return; + recomputeAxisLists(); - // for all present range sliders - rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_6.select(this), - opts = axisOpts[_$constants_118.name], - oppAxisOpts = fullLayout[_$axes_205.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_205.id2name(axisOpts.anchor)]; + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - // update range - // Expand slider range to the axis range - // TODO: what if the ranges are reversed? - if(opts.range) { - var outRange = opts.range; - var axRange = axisOpts.range; + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; + } - outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); - outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); - opts._input.range = outRange.slice(); - } + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; - axisOpts.cleanRange('rangeslider.range'); + recomputeAxisLists(); + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } - // update range slider dimensions + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; - var margin = fullLayout.margin; - var graphSize = fullLayout._size; - var domain = axisOpts.domain; - var tickHeight = (axisOpts._boundingBox || {}).height || 0; + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_214(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_214(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; - var oppBottom = Infinity; - var subplotData = _$axes_205.getSubplots(gd, axisOpts); - for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_205.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); - oppBottom = Math.min(oppBottom, oppAxis.domain[0]); - } + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; - opts._id = _$constants_118.name + axisOpts._id; - opts._clipId = opts._id + '-' + fullLayout._uid; + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_214(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); - opts._width = graphSize.w * (domain[1] - domain[0]); - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); + if(numClicks === 2 && !singleEnd) doubleClick(); - var x = Math.round(margin.l + (graphSize.w * domain[0])); + if(isMainDrag) { + _$fx_85.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; - var y = Math.round( - graphSize.t + graphSize.h * (1 - oppBottom) + - tickHeight + - opts._offsetShift + _$constants_118.extraPad - ); + if(ax.fixedrange) return; - rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; - // update data <--> pixel coordinate conversion methods + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_6.select(dragger) + .call(_$svg_text_utils_185.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_254.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; - var range0 = axisOpts.r2l(opts.range[0]), - range1 = axisOpts.r2l(opts.range[1]), - dist = range1 - range0; + _$dragelement_65.init(dragOptions); - opts.p2d = function(v) { - return (v / opts._width) * dist + range0; - }; + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; - opts.d2p = function(v) { - return (v - range0) / dist * opts._width; - }; + // collected changes to be made to the plot by relayout at the end + var updates = {}; - opts._rl = [range0, range1]; + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_25(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; - if(oppAxisRangeOpts.rangemode !== 'match') { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), - range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), - distOppAxis = range1OppAxis - range0OppAxis; + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - opts.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts._height; - }; - } + corners = makeCorners(zoomlayer, xs, ys); - // update inner nodes + __clearSelect_214(zoomlayer); + } - rangeSlider - .call(drawBg, gd, axisOpts, opts) - .call(addClipPath, gd, axisOpts, opts) - .call(drawRangePlot, gd, axisOpts, opts) - .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) - .call(drawSlideBox, gd, axisOpts, opts) - .call(drawGrabbers, gd, axisOpts, opts); + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } - // setup drag element - setupDragElement(rangeSlider, gd, axisOpts, opts); + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); - // update current range - setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); - // title goes next to range slider instead of tick labels, so - // just take it over and draw it from here - if(axisOpts.side === 'bottom') { - _$titles_136.draw(gd, axisOpts._id + 'title', { - propContainer: axisOpts, - propName: axisOpts._name + '.title', - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, - 'text-anchor': 'middle' - } - }); + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); } - // update margins - _$plots_245.autoMargin(gd, opts._id, { - x: domain[0], - y: oppBottom, - l: 0, - r: 0, - t: 0, - b: opts._height + margin.b + tickHeight, - pad: _$constants_118.extraPad + opts._offsetShift * 2 - }); - }); -}; + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; -function makeRangeSliderData(fullLayout) { - var axes = _$axes_205.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_118.name, - out = []; + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; + } - if(fullLayout._has('gl2d')) return out; + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } - for(var i = 0; i < axes.length; i++) { - var ax = axes[i]; + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } - if(ax[name] && ax[name].visible) out.push(ax); + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); } - return out; -} - -function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_118.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_118.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_118.grabAreaMaxClassName).node(); + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_211.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - rangeSlider.on('mousedown', function() { - var event = _$d3_6.event, - target = event.target, - startX = event.clientX, - offsetX = startX - rangeSlider.node().getBoundingClientRect().left, - minVal = opts.d2p(axisOpts._rl[0]), - maxVal = opts.d2p(axisOpts._rl[1]); + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } - var dragCover = _$dragelement_65.coverSlip(); + if(redrawTimer === null) { + __clearSelect_214(zoomlayer); + } - dragCover.addEventListener('mousemove', mouseMove); - dragCover.addEventListener('mouseup', mouseUp); + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } - function mouseMove(e) { - var delta = +e.clientX - startX; - var pixelMin, pixelMax, cursor; + var pc = gd.querySelector('.plotly'); - switch(target) { - case slideBox: - cursor = 'ew-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal + delta; - break; + recomputeAxisLists(); - case grabAreaMin: - cursor = 'col-resize'; - pixelMin = minVal + delta; - pixelMax = maxVal; - break; + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } - case grabAreaMax: - cursor = 'col-resize'; - pixelMin = minVal; - pixelMax = maxVal + delta; - break; + clearTimeout(redrawTimer); - default: - cursor = 'ew-resize'; - pixelMin = offsetX; - pixelMax = offsetX + delta; - break; - } + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_164.log('Did not find wheel motion attributes: ', e); + return; + } - if(pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; - _$setCursor_182(_$d3_6.select(dragCover), cursor); - setDataRange(rangeSlider, gd, axisOpts, opts); + var axRange = _$lib_164.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); } - function mouseUp() { - dragCover.removeEventListener('mousemove', mouseMove); - dragCover.removeEventListener('mouseup', mouseUp); - _$lib_163.removeElement(dragCover); + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; + + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } + + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); } - }); -} + if(editY) { + if(!ns) yfrac = 0.5; -function setDataRange(rangeSlider, gd, axisOpts, opts) { + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } - function clamp(v) { - return axisOpts.l2r(_$lib_163.constrain(v, opts._rl[0], opts._rl[1])); - } + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } - var dataMin = clamp(opts.p2d(opts._pixelMin)), - dataMax = clamp(opts.p2d(opts._pixelMax)); + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); - window.requestAnimationFrame(function() { - _$registry_253.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); - }); -} + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; -function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_118.handleWidth / 2; + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); - function clamp(v) { - return _$lib_163.constrain(v, 0, opts._width); - } + dragTail(zoomMode); + }, REDRAWDELAY); - function clampOppAxis(v) { - return _$lib_163.constrain(v, 0, opts._height); + e.preventDefault(); + return; } - function clampHandle(v) { - return _$lib_163.constrain(v, -hw2, opts._width + hw2); + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); } - var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), - pixelMax = clamp(opts.d2p(axisOpts._rl[1])); + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } - rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) - .attr('x', pixelMin) - .attr('width', pixelMax - pixelMin); + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } - rangeSlider.select('rect.' + _$constants_118.maskMinClassName) - .attr('width', pixelMin); + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); - rangeSlider.select('rect.' + _$constants_118.maskMaxClassName) - .attr('x', pixelMax) - .attr('width', opts._width - pixelMax); + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } - if(oppAxisRangeOpts.rangemode !== 'match') { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), - pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } - rangeSlider.select('rect.' + _$constants_118.maskMinOppAxisClassName) - .attr('x', pixelMin) - .attr('height', pixelMinOppAxis) - .attr('width', pixelMax - pixelMin); + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; - rangeSlider.select('rect.' + _$constants_118.maskMaxOppAxisClassName) - .attr('x', pixelMin) - .attr('y', pixelMaxOppAxis) - .attr('height', opts._height - pixelMaxOppAxis) - .attr('width', pixelMax - pixelMin); + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; - rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) - .attr('y', pixelMinOppAxis) - .attr('height', pixelMaxOppAxis - pixelMinOppAxis); - } + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; - // add offset for crispier corners - // https://github.com/plotly/plotly.js/pull/1409 - var offset = 0.5; + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_222(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_222(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, - xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } - rangeSlider.select('g.' + _$constants_118.grabberMinClassName) - .attr('transform', 'translate(' + xMin + ',' + offset + ')'); + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; - rangeSlider.select('g.' + _$constants_118.grabberMaxClassName) - .attr('transform', 'translate(' + xMax + ',' + offset + ')'); -} + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } -function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_118.bgClassName) - .data([0]); + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } - bg.enter().append('rect') - .classed(_$constants_118.bgClassName, true) - .attr({ - x: 0, - y: 0, - 'shape-rendering': 'crispEdges' - }); + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_214(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } - var borderCorrect = (opts.borderwidth % 2) === 0 ? - opts.borderwidth : - opts.borderwidth - 1; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - var offsetShift = -opts._offsetShift; - var lw = _$drawing_68.crispRound(gd, opts.borderwidth); + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } + } - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: 'translate(' + offsetShift + ',' + offsetShift + ')', - fill: opts.bgcolor, - stroke: opts.bordercolor, - 'stroke-width': lw - }); -} + // annotations and shapes 'draw' method is slow, + // use the finer-grained 'drawOne' method instead -function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; + redrawObjs(gd._fullLayout.annotations || [], _$registry_254.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_254.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_254.getComponentMethod('images', 'draw'), true); + } - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); + function doubleClick() { + if(gd._transitioningWithDuration) return; - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; - clipPath.select('rect').attr({ - width: opts._width, - height: opts._height - }); -} + var ax, i, rangeInitial; -function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_205.getSubplots(gd, axisOpts), - calcData = gd.calcdata; + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { - var rangePlots = rangeSlider.selectAll('g.' + _$constants_118.rangePlotClassName) - .data(subplotData, _$lib_163.identity); + doubleClickConfig = 'autosize'; - rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_118.rangePlotClassName + ' ' + id; }) - .call(_$drawing_68.setClipUrl, opts._clipId); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } - rangePlots.order(); + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); - rangePlots.exit().remove(); + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } - var mainplotinfo; + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - rangePlots.each(function(id, i) { - var plotgroup = _$d3_6.select(this), - isMainPlot = (i === 0); + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } - var oppAxisOpts = _$axes_205.getFromId(gd, id, 'y'), - oppAxisName = oppAxisOpts._name, - oppAxisRangeOpts = opts[oppAxisName]; + gd.emit('plotly_doubleclick', null); + _$registry_254.call('relayout', gd, attrs); + } - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_164.syncOrAsync([ + _$plots_245.previousPromises, + function() { _$registry_254.call('relayout', gd, updates); } + ], gd); + } - _$plots_245.supplyDefaults(mockFigure); + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; - var xa = mockFigure._fullLayout.xaxis, - ya = mockFigure._fullLayout[oppAxisName]; + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); - var plotinfo = { - id: id, - plotgroup: plotgroup, - xaxis: xa, - yaxis: ya - }; + var i, sp, xa, ya; - if(isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = 'xy'; - plotinfo.mainplotinfo = mainplotinfo; + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_152(gd); } - _$cartesian_216.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); -} - -function filterRangePlotCalcData(calcData, subplotId) { - var out = []; + if(hasSplom) { + _$registry_254.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; + } - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i], - trace = calcTrace[0].trace; + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; - if(trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_164.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_164.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } } - } - return out; -} + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; -function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_118.maskMinClassName) - .data([0]); + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; - maskMin.enter().append('rect') - .classed(_$constants_118.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + var editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; - maskMin - .attr('height', opts._height) - .call(_$color_43.fill, _$constants_118.maskColor); + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; - var maskMax = rangeSlider.selectAll('rect.' + _$constants_118.maskMaxClassName) - .data([0]); + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } - maskMax.enter().append('rect') - .classed(_$constants_118.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } - maskMax - .attr('height', opts._height) - .call(_$color_43.fill, _$constants_118.maskColor); + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } - // masks used for oppAxis zoom - if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_118.maskMinOppAxisClassName) - .data([0]); + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; - maskMinOppAxis.enter().append('rect') - .classed(_$constants_118.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; - maskMinOppAxis - .attr('width', opts._width) - .call(_$color_43.fill, _$constants_118.maskOppAxisColor); + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_68.setTranslate, clipDx, clipDy) + .call(_$drawing_68.setScale, xScaleFactor2, yScaleFactor2); - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_118.maskMaxOppAxisClassName) - .data([0]); + sp.plot + .call(_$drawing_68.setTranslate, plotDx, plotDy) + .call(_$drawing_68.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_118.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); - maskMaxOppAxis - .attr('width', opts._width) - .style('border-top', _$constants_118.maskOppBorder) - .call(_$color_43.fill, _$constants_118.maskOppAxisColor); + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_68.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_68.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_68.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_68.hideOutsideRangePoints, sp, '.bartext'); + } + } + } } -} -function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if(gd._context.staticPlot) return; + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; - var slideBox = rangeSlider.selectAll('rect.' + _$constants_118.slideBoxClassName) - .data([0]); + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } + + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_222(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } - slideBox.enter().append('rect') - .classed(_$constants_118.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_118.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * __FROM_TL_214[ax.constraintoward || 'middle']; + } - slideBox.attr({ - height: opts._height, - fill: _$constants_118.slideBoxFill + return dragger; +} + +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_164.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); }); + + dragger3.call(_$setCursor_183, cursor); + + return dragger3.node(); } -function drawGrabbers(rangeSlider, gd, axisOpts, opts) { +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_6.select(dragger).call(_$drawing_68.setRect, x, y, w, h); + return dragger; +} - // +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} - var grabberMin = rangeSlider.selectAll('g.' + _$constants_118.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_118.grabberMinClassName, true); +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; - var grabberMax = rangeSlider.selectAll('g.' + _$constants_118.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_118.grabberMaxClassName, true); + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_6.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_6.format('.' + String(dig) + 'g')(initialVal); + } +} - // +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; - var handleFixAttrs = { - x: 0, - width: _$constants_118.handleWidth, - rx: _$constants_118.handleRadius, - fill: _$color_43.background, - stroke: _$color_43.defaultLine, - 'stroke-width': _$constants_118.handleStrokeWidth, - 'shape-rendering': 'crispEdges' - }; + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2), - }; + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } - var handleMin = grabberMin.selectAll('rect.' + _$constants_118.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_118.handleMinClassName, true) - .attr(handleFixAttrs); - handleMin.attr(handleDynamicAttrs); + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - var handleMax = grabberMax.selectAll('rect.' + _$constants_118.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_118.handleMaxClassName, true) - .attr(handleFixAttrs); - handleMax.attr(handleDynamicAttrs); + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} - // +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} - if(gd._context.staticPlot) return; +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} - var grabAreaFixAttrs = { - width: _$constants_118.grabAreaWidth, - x: 0, - y: 0, - fill: _$constants_118.grabAreaFill, - cursor: _$constants_118.grabAreaCursor - }; +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_118.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_118.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMin.attr('height', opts._height); +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_118.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_118.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); - grabAreaMax.attr('height', opts._height); +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_43.background, + stroke: _$color_43.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); } -function clearPushMargins(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); + } +} - if(k.indexOf(_$constants_118.name) !== -1) { - _$plots_245.autoMargin(gd, k); - } +function removeZoombox(gd) { + _$d3_6.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} + +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_164.notifier(_$lib_164._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; } } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} -'use strict'; +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$attributes_116 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} -var _$rangeslider_121 = { - moduleType: 'component', - name: 'rangeslider', +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} - schema: { - subplots: { - xaxis: { - rangeslider: _$lib_163.extendFlat({}, _$attributes_116, { - yaxis: _$oppaxis_attributes_122 - }) +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; + + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } + + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } } } - }, - layoutAttributes: _$attributes_116, - handleDefaults: _$handleDefaults_119, - calcAutorange: _$calcAutorange_117, - draw: _$draw_120 + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } + } + } + + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_164.extendFlat(xLinks, yLinks); + yLinks = {}; + } + + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_214(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; + } + + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_214(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; + } + + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} + +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_12) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; + } + else { + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; + + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); + } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); + } +} + +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; +} + +var _$dragbox_214 = { + makeDragBox: makeDragBox, + + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, + + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, + + attachWheelEventHandler: attachWheelEventHandler }; +var _$graph_interact_215 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -42175,170 +43476,164 @@ var _$rangeslider_121 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$attributes_28 = require('../annotations/attributes'); */; -var scatterLineAttrs = _$attributes_265.line; -var __dash_123 = _$attributes_67.dash; -var __extendFlat_123 = _$extend_156.extendFlat; +/* removed: var _$d3_6 = require('d3'); */; -var _$attributes_123 = { - _isLinkedToArray: 'shape', +/* removed: var _$fx_85 = require('../../components/fx'); */; +/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_183 = require('../../lib/setcursor'); */; - visible: { - valType: 'boolean', - - dflt: true, - editType: 'calcIfAutorange+arraydraw', - - }, +var __makeDragBox_215 = _$dragbox_214.makeDragBox; +var DRAGGERSIZE = _$constants_211.DRAGGERSIZE; - type: { - valType: 'enumerated', - values: ['circle', 'rect', 'path', 'line'], - - editType: 'calcIfAutorange+arraydraw', - - }, +_$graph_interact_215.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; - layer: { - valType: 'enumerated', - values: ['below', 'above'], - dflt: 'above', - - editType: 'arraydraw', - - }, + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_6.select(gd).selectAll('.drag').remove(); + return; + } - xref: __extendFlat_123({}, _$attributes_28.xref, { - - }), - x0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - x1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - yref: __extendFlat_123({}, _$attributes_28.yref, { - - }), - y0: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, - y1: { - valType: 'any', - - editType: 'calcIfAutorange+arraydraw', - - }, + 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'), + 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; + }); - path: { - valType: 'string', - - editType: 'calcIfAutorange+arraydraw', - - }, + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - opacity: { - valType: 'number', - min: 0, - max: 1, - dflt: 1, - - editType: 'arraydraw', - - }, - line: { - color: __extendFlat_123({}, scatterLineAttrs.color, {editType: 'arraydraw'}), - width: __extendFlat_123({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_123({}, __dash_123, {editType: 'arraydraw'}), - - editType: 'calcIfAutorange+arraydraw' - }, - fillcolor: { - valType: 'color', - dflt: 'rgba(0,0,0,0)', - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; + // 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_215(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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) { + _$fx_85.hover(gd, evt, subplot); + } + }; + _$fx_85.hover(gd, evt, subplot); -'use strict'; + // 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; -var _$constants_125 = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, + // 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; - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: {0: true, drawn: 0}, - L: {0: true, drawn: 0}, - H: {0: true, drawn: 0}, - V: {}, - Q: {0: true, 2: true, drawn: 2}, - C: {0: true, 2: true, 4: true, drawn: 4}, - T: {0: true, drawn: 0}, - S: {0: true, 2: true, drawn: 2}, - // A: {0: true, 5: true}, - Z: {} - }, + _$dragelement_65.unhover(gd, evt); + }; - paramIsY: { - M: {1: true, drawn: 1}, - L: {1: true, drawn: 1}, - H: {}, - V: {0: true, drawn: 0}, - Q: {1: true, 3: true, drawn: 3}, - C: {1: true, 3: true, 5: true, drawn: 5}, - T: {1: true, drawn: 1}, - S: {1: true, 3: true, drawn: 5}, - // A: {1: true, 6: true}, - Z: {} - }, + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_215(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_215(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_215(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_215(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_215(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_215(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_215(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_215(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_215(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_215(gd, plotinfo, x0, ya._offset, + DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } + } + }); - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 - } + // 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_85.hover(gd, evt, fullLayout._hoversubplot); + }; + + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_85.click(gd, evt); + }; + + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; + + _$graph_interact_215.updateFx(fullLayout); +}; + +// 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. +_$graph_interact_215.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_183(fullLayout._draggers, cursor); }; -var _$helpers_128 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -42347,76 +43642,89 @@ var _$helpers_128 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -// special position conversion functions... category axis positions can't be -// specified by their data values, because they don't make a continuous mapping. -// so these have to be specified in terms of the category serial numbers, -// but can take fractional values. Other axis types we specify position based on -// the actual data values. -// TODO: in V2.0 (when log axis ranges are in data units) range and shape position -// will be identical, so rangeToShapePosition and shapePositionToRange can be -// removed entirely. +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; -_$helpers_128.rangeToShapePosition = function(ax) { - return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; -}; + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } -_$helpers_128.shapePositionToRange = function(ax) { - return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; -}; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } + } -_$helpers_128.decodeDate = function(convertToPx) { - return function(v) { - if(v.replace) v = v.replace('_', ' '); - return convertToPx(v); - }; -}; + return Object.keys(lookup); +} -_$helpers_128.encodeDate = function(convertToDate) { - return function(v) { return convertToDate(v).replace(' ', '_'); }; -}; +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_210 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; -_$helpers_128.getDataToPixel = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - dataToPixel; + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); - if(axis) { - var d2r = _$helpers_128.shapePositionToRange(axis); + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; - dataToPixel = function(v) { - return axis._offset + axis.r2p(d2r(v, true)); - }; + var order = coerce('categoryorder', orderDefault); + var array; - if(axis.type === 'date') dataToPixel = _$helpers_128.decodeDate(dataToPixel); - } - else if(isVertical) { - dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; - } - else { - dataToPixel = function(v) { return gs.l + gs.w * v; }; + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); } - return dataToPixel; -}; - -_$helpers_128.getPixelToData = function(gd, axis, isVertical) { - var gs = gd._fullLayout._size, - pixelToData; - - if(axis) { - var r2d = _$helpers_128.rangeToShapePosition(axis); - pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; - } - else if(isVertical) { - pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; - } - else { - pixelToData = function(p) { return (p - gs.l) / gs.w; }; + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; } - return pixelToData; + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } + } }; /** @@ -42427,73 +43735,61 @@ _$helpers_128.getPixelToData = function(gd, axis, isVertical) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; - -/* removed: var _$constants_125 = require('./constants'); */; -/* removed: var _$helpers_128 = require('./helpers'); */; - - -var _$calcAutorange_124 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout, - shapeList = _$lib_163.filterVisible(fullLayout.shapes); - - if(!shapeList.length || !gd._fullData.length) return; - - for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; +var colorMix = _$tinycolor_25.mix; +var lightFraction = _$attributes_42.lightFraction; +/* removed: var _$lib_164 = require('../../lib'); */; - var ax, bounds; +/** + * @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 + */ +var _$handleLineGridDefaults_220 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; - if(shape.xref !== 'paper') { - ax = _$axes_205.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_125.paramIsX); - if(bounds) _$axes_205.expand(ax, bounds, {ppad: ppad}); - } + var dfltColor = opts.dfltColor; - if(shape.yref !== 'paper') { - ax = _$axes_205.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_125.paramIsY); - if(bounds) _$axes_205.expand(ax, bounds, {ppad: ppad}); - } + function coerce2(attr, dflt) { + return _$lib_164.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } -}; -function shapeBounds(ax, v0, v1, path, paramsToUse) { - var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - - if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; - if(!path) return; + var lineColor = coerce2('linecolor', dfltColor); + var lineWidth = coerce2('linewidth'); + var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); - var min = Infinity, - max = -Infinity, - segments = path.match(_$constants_125.segmentRE), - i, - segment, - drawnParam, - params, - val; + if(!showLine) { + delete containerOut.linecolor; + delete containerOut.linewidth; + } - if(ax.type === 'date') convertVal = _$helpers_128.decodeDate(convertVal); + 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); - for(i = 0; i < segments.length; i++) { - segment = segments[i]; - drawnParam = paramsToUse[segment.charAt(0)].drawn; - if(drawnParam === undefined) continue; + if(!showGridLines) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; + } - params = segments[i].substr(1).match(_$constants_125.paramRE); - if(!params || params.length < drawnParam) continue; + if(!opts.noZeroLine) { + var zeroLineColor = coerce2('zerolinecolor', dfltColor); + var zeroLineWidth = coerce2('zerolinewidth'); + var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); - val = convertVal(params[drawnParam]); - if(val < min) min = val; - if(val > max) max = val; + if(!showZeroLine) { + delete containerOut.zerolinecolor; + delete containerOut.zerolinewidth; + } } - if(max >= min) return [min, max]; -} +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -42503,94 +43799,95 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -/* removed: var _$attributes_123 = require('./attributes'); */; -/* removed: var _$helpers_128 = require('./helpers'); */; +/* removed: var _$layout_attributes_218 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_227 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_226 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_225 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_210 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_220 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_224 = require('./set_convert'); */; + +/** + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors + */ +var _$handleAxisDefaults_208 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; + var visible = coerce('visible', !options.cheateronly); -var _$handleShapeDefaults_130 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { - opts = opts || {}; - itemOpts = itemOpts || {}; + var axType = containerOut.type; - function coerce(attr, dflt) { - return _$lib_163.coerce(shapeIn, shapeOut, _$attributes_123, attr, dflt); + if(axType === 'date') { + var handleCalendarDefaults = _$registry_254.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } - var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); + _$setConvert_224(containerOut, layoutOut); - if(!visible) return shapeOut; + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - coerce('layer'); - coerce('opacity'); - coerce('fillcolor'); - coerce('line.color'); - coerce('line.width'); - coerce('line.dash'); + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; - var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + if(autoRange) coerce('rangemode'); - // positioning - var axLetters = ['x', 'y']; - for(var i = 0; i < 2; i++) { - var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + coerce('range'); + containerOut.cleanRange(); - // xref, yref - var axRef = _$axes_205.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + _$handleCategoryOrderDefaults_210(containerIn, containerOut, coerce, options); - if(shapeType !== 'path') { - var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); - if(axRef !== 'paper') { - ax = _$axes_205.getFromId(gdMock, axRef); - r2pos = _$helpers_128.rangeToShapePosition(ax); - pos2r = _$helpers_128.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_163.identity; - } + if(!visible) return containerOut; - // 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', - attr1 = axLetter + '1', - in0 = shapeIn[attr0], - in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; - // x0, x1 (and y0, y1) - _$axes_205.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_205.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + coerce('title', dfltTitle); + _$lib_164.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); - // hack part 2 - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; - } - } + _$handleTickValueDefaults_227(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_225(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_226(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_220(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_218 + }); - if(shapeType === 'path') { - coerce('path'); - } - else { - _$lib_163.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); - } + if(containerOut.showline || containerOut.ticks) coerce('mirror'); - return shapeOut; + if(options.automargin) coerce('automargin'); + + return containerOut; }; /** @@ -42604,391 +43901,373 @@ var _$handleShapeDefaults_130 = function handleShapeDefaults(shapeIn, shapeOut, 'use strict'; -/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_130 = require('./shape_defaults'); */; - - -var _$supplyLayoutDefaults_126 = function supplyLayoutDefaults(layoutIn, layoutOut) { - var opts = { - name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_130 - }; - - _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); -}; +/* removed: var _$lib_164 = require('../../lib'); */; +var id2name = _$axis_ids_209.id2name; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$handleConstraintDefaults_212 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); -'use strict'; + if(containerOut.fixedrange) return; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_164.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' + } + }, 'constraintoward'); -/* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; + if(!containerIn.scaleanchor) return; -/* removed: var _$constants_125 = require('./constants'); */; -/* removed: var _$helpers_128 = require('./helpers'); */; + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + var scaleanchor = _$lib_164.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes + } + }, 'scaleanchor'); -// Shapes are stored in gd.layout.shapes, an array of objects -// index can point to one item in this array, -// or non-numeric to simply add a new one -// or -1 to modify all existing -// opt can be the full options object, or one key (to be set to value) -// or undefined to simply redraw -// if opt is blank, val can be 'add' or a full options object to add a new -// annotation at that point in the array, or 'remove' to delete this one + 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; -var _$draw_127 = { - draw: __draw_127, - drawOne: __drawOne_127 + updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_164.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.'); + } }; -function __draw_127(gd) { - var fullLayout = gd._fullLayout; +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. - // Remove previous shapes before drawing new in shapes in fullLayout.shapes - fullLayout._shapeUpperLayer.selectAll('path').remove(); - fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + var thisType = layoutOut[id2name(thisID)].type; - for(var i = 0; i < fullLayout.shapes.length; i++) { - if(fullLayout.shapes[i].visible) { - __drawOne_127(gd, i); + 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 && !axj.fixedrange) linkableAxes.push(idj); + } + + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; + + var linkableAxesNoLoops = []; + for(j = 0; j < linkableAxes.length; j++) { + idj = linkableAxes[j]; + if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); + } + return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; } } - // may need to resurrect this if we put text (LaTeX) in shapes - // return Plots.previousPromises(gd); + return {linkableAxes: linkableAxes, thisGroup: null}; } -function __drawOne_127(gd, index) { - // remove the existing shape if there is one. - // because indices can change, we need to look in all shape layers - gd._fullLayout._paperdiv - .selectAll('.shapelayer [data-index="' + index + '"]') - .remove(); - - var optionsIn = (gd.layout.shapes || [])[index], - options = gd._fullLayout.shapes[index]; - // this shape is gone - quit now after deleting it - // TODO: use d3 idioms instead of deleting and redrawing every time - if(!optionsIn || options.visible === false) return; +/* + * 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(options.layer !== 'below') { - drawShape(gd._fullLayout._shapeUpperLayer); - } - else if(options.xref === 'paper' || options.yref === 'paper') { - drawShape(gd._fullLayout._shapeLowerLayer); + if(thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); } else { - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - if(plotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } - else { - // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. - // This can happen if you reference the shape to an x / y axis combination - // that doesn't have any data on it (and layer is below) - drawShape(gd._fullLayout._shapeLowerLayer); - } + thisGroupIndex = constraintGroups.indexOf(thisGroup); } - function drawShape(shapeLayer) { - var attrs = { - 'data-index': index, - 'fill-rule': 'evenodd', - d: getPathString(gd, options) - }, - lineColor = options.line.width ? - options.line.color : 'rgba(0,0,0,0)'; - - var path = shapeLayer.append('path') - .attr(attrs) - .style('opacity', options.opacity) - .call(_$color_43.stroke, lineColor) - .call(_$color_43.fill, options.fillcolor) - .call(_$drawing_68.dashLine, options.line.dash, options.line.width); - - // note that for layer="below" the clipAxes can be different from the - // subplot we're drawing this in. This could cause problems if the shape - // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 - var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); + var thisGroupKeys = Object.keys(thisGroup); - path.call(_$drawing_68.setClipUrl, clipAxes ? - ('clip' + gd._fullLayout._uid + clipAxes) : - null - ); + // 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; + } + } - if(gd._context.edits.shapePosition) __setupDragElement_127(gd, path, options, index); + // 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; } -function __setupDragElement_127(gd, shapePath, shapeOptions, index) { - var MINWIDTH = 10, - MINHEIGHT = 10; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; - var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; - var pathIn, astrPath; - var xa, ya, x2p, y2p, p2x, p2y; +'use strict'; - var dragOptions = { - element: shapePath.node(), - gd: gd, - prepFn: startDrag, - doneFn: endDrag - }, - dragBBox = dragOptions.element.getBoundingClientRect(), - dragMode; +/* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; - _$dragelement_65.init(dragOptions); +/* removed: var _$lib_164 = require('../../lib'); */; - shapePath.node().onmousemove = updateDragMode; - function updateDragMode(evt) { - // choose 'move' or 'resize' - // based on initial position of cursor within the drag element - var w = dragBBox.right - dragBBox.left, - h = dragBBox.bottom - dragBBox.top, - x = evt.clientX - dragBBox.left, - y = evt.clientY - dragBBox.top, - cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_65.getCursor(x / w, 1 - y / h) : - 'move'; +var _$handlePositionDefaults_221 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; - _$setCursor_182(shapePath, cursor); + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; - // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' - dragMode = cursor.split('-')[0]; + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; + } } - function startDrag(evt) { - // setup conversion functions - xa = _$axes_205.getFromId(gd, shapeOptions.xref); - ya = _$axes_205.getFromId(gd, shapeOptions.yref); - - x2p = _$helpers_128.getDataToPixel(gd, xa); - y2p = _$helpers_128.getDataToPixel(gd, ya, true); - p2x = _$helpers_128.getPixelToData(gd, xa); - p2y = _$helpers_128.getPixelToData(gd, ya, true); + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_9(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; - // setup update strings and initial values - var astr = 'shapes[' + index + ']'; - if(shapeOptions.type === 'path') { - pathIn = shapeOptions.path; - astrPath = astr + '.path'; + var anchor = _$lib_164.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor } - else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + }, 'anchor'); - astrX0 = astr + '.x0'; - astrY0 = astr + '.y0'; - astrX1 = astr + '.x1'; - astrY1 = astr + '.y1'; - } + if(anchor === 'free') coerce('position', dfltPosition); - if(x0 < x1) { - w0 = x0; astrW = astr + '.x0'; optW = 'x0'; - e0 = x1; astrE = astr + '.x1'; optE = 'x1'; - } - else { - w0 = x1; astrW = astr + '.x1'; optW = 'x1'; - e0 = x0; astrE = astr + '.x0'; optE = 'x0'; - } - if(y0 < y1) { - n0 = y0; astrN = astr + '.y0'; optN = 'y0'; - s0 = y1; astrS = astr + '.y1'; optS = 'y1'; - } - else { - n0 = y1; astrN = astr + '.y1'; optN = 'y1'; - s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + _$lib_164.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide } + }, 'side'); - update = {}; - - // setup dragMode and the corresponding handler - updateDragMode(evt); - dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_164.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); } - function endDrag() { - _$setCursor_182(shapePath); - _$registry_253.call('relayout', gd, update); + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_164.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } - function moveShape(dx, dy) { - if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); + coerce('layer'); - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + return containerOut; +}; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - shapePath.attr('d', getPathString(gd, shapeOptions)); - } - function resizeShape(dx, dy) { - if(shapeOptions.type === 'path') { - // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); +'use strict'; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$autoType_207 = require('./axis_autotype'); */; +var name2id = _$axis_ids_209.name2id; - shapeOptions.path = movePath(pathIn, moveX, moveY); - update[astrPath] = shapeOptions.path; - } - else { - var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, - newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, - newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, - newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_229 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); + } - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); - } + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; } - - shapePath.attr('d', getPathString(gd, shapeOptions)); } -} - -function getPathString(gd, options) { - var type = options.type, - xa = _$axes_205.getFromId(gd, options.xref), - ya = _$axes_205.getFromId(gd, options.yref), - gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; +}; - if(xa) { - x2r = _$helpers_128.shapePositionToRange(xa); - x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; - } - else { - x2p = function(v) { return gs.l + gs.w * v; }; - } +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - if(ya) { - y2r = _$helpers_128.shapePositionToRange(ya); - y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; - } - else { - y2p = function(v) { return gs.t + gs.h * (1 - v); }; - } + var id = ax._id; + var axLetter = id.charAt(0); - if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_128.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_128.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); - } + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), - y1 = y2p(options.y1); + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; - 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, - cy = (y0 + y1) / 2, - rx = Math.abs(cx - x0), - ry = Math.abs(cy - y0), - rArc = 'A' + rx + ',' + ry, - rightPt = (cx + rx) + ',' + cy, - topPt = cx + ',' + (cy - ry); - return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + - rArc + ' 0 0,1 ' + rightPt + 'Z'; -} + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_125.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_125.paramIsX[segmentType], - yParams = _$constants_125.paramIsY[segmentType], - nParams = _$constants_125.numParams[segmentType]; + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - var paramString = segment.substr(1).replace(_$constants_125.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); - paramNumber++; + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_254.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; - if(paramNumber > nParams) param = 'X'; - return param; - }); + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); - if(paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_163.log('Ignoring extra params in segment ' + segment); + if(trace[calAttr] !== calendar) calendar = undefined; } - return segmentType + paramString; - }); + ax.type = _$autoType_207(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_207(dim.values, calendar); + break; + } + } + } + else { + ax.type = _$autoType_207(d0[axLetter] || [d0[axLetter + '0']], calendar); + } } -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_125.segmentRE, function(segment) { - var paramNumber = 0, - segmentType = segment.charAt(0), - xParams = _$constants_125.paramIsX[segmentType], - yParams = _$constants_125.paramIsY[segmentType], - nParams = _$constants_125.numParams[segmentType]; +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; - var paramString = segment.substr(1).replace(_$constants_125.paramRE, function(param) { - if(paramNumber >= nParams) return param; + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } - if(xParams[paramNumber]) param = moveX(param); - else if(yParams[paramNumber]) param = moveY(param); + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } + } + } +} - paramNumber++; +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} - return param; - }); +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_254.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_254.traceIs(trace._fullInput || {}, 'candlestick'); - return segmentType + paramString; - }); + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); } /** @@ -43002,397 +44281,227 @@ function movePath(pathIn, moveX, moveY) { 'use strict'; -/* removed: var _$draw_127 = require('./draw'); */; - -var _$shapes_129 = { - moduleType: 'component', - name: 'shapes', +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$color_43 = require('../../components/color'); */; +/* removed: var _$layout_attributes_236 = require('../layout_attributes'); */; - layoutAttributes: _$attributes_123, - supplyLayoutDefaults: _$supplyLayoutDefaults_126, - includeBasePlot: _$makeIncludeComponents_215('shapes'), +/* removed: var _$layout_attributes_218 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_229 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_208 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_212 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_221 = require('./position_defaults'); */; +/* removed: var _$axis_ids_209 = require('./axis_ids'); */; - calcAutorange: _$calcAutorange_124, - draw: _$draw_127.draw, - drawOne: _$draw_127.drawOne -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$supplyLayoutDefaults_219 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -'use strict'; + if(!_$registry_254.traceIs(trace, 'cartesian') && !_$registry_254.traceIs(trace, 'gl2d')) { + continue; + } + var xaName = _$axis_ids_209.id2name(trace.xaxis); + var yaName = _$axis_ids_209.id2name(trace.yaxis); -var _$constants_132 = { + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_254.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - // layout attribute name - name: 'sliders', + // 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) xaCheater[xaName] = 1; + } - // class names - containerClassName: 'slider-container', - groupClassName: 'slider-group', - inputAreaClass: 'slider-input-area', - railRectClass: 'slider-rail-rect', - railTouchRectClass: 'slider-rail-touch-rect', - gripRectClass: 'slider-grip-rect', - tickRectClass: 'slider-tick-rect', - inputProxyClass: 'slider-input-proxy', - labelsClass: 'slider-labels', - labelGroupClass: 'slider-label-group', - labelClass: 'slider-label', - currentValueClass: 'slider-current-value', + // check for default formatting tweaks + if(_$registry_254.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } - railHeight: 5, + if(_$registry_254.traceIs(trace, 'oriented')) { + var positionAxis = trace.orientation === 'h' ? yaName : xaName; + noGrids[positionAxis] = true; + } + } - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'slider-active-index', + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = _$lib_164.simpleMap(xIds, _$axis_ids_209.id2name); + var yNames = _$lib_164.simpleMap(yIds, _$axis_ids_209.id2name); + var axNames = xNames.concat(yNames); - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'slider-', + // plot_bgcolor only makes sense if there's a (2D) plot! + // TODO: bgcolor for each subplot, to inherit from the main one + var plot_bgcolor = _$color_43.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_164.coerce(layoutIn, layoutOut, _$layout_attributes_236, 'plot_bgcolor'); + } - // min item width / height - minWidth: 30, - minHeight: 30, + var bgColor = _$color_43.combine(plot_bgcolor, layoutOut.paper_bgcolor); - // padding around item text - textPadX: 40, + var axName, axLetter, axLayoutIn, axLayoutOut; - // arrow offset off right edge - arrowOffsetX: 4, + function coerce(attr, dflt) { + return _$lib_164.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_218, attr, dflt); + } - railRadius: 2, - railWidth: 5, - railBorder: 4, - railBorderWidth: 1, - railBorderColor: '#bec8d9', - railBgColor: '#f8fafc', + function coerce2(attr, dflt) { + return _$lib_164.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_218, attr, dflt); + } - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBorder: 20, - gripBorderWidth: 1, - gripBorderColor: '#bec8d9', - gripBgColor: '#f6f8fa', - gripBgActiveColor: '#dbdde0', + function getOverlayableAxes(axLetter, axName) { + var list = (axLetter === 'x') ? xNames : yNames; + var out = []; - labelPadding: 8, - labelOffset: 0, + for(var j = 0; j < list.length; j++) { + var axName2 = list[j]; - tickWidth: 1, - tickColor: '#333', - tickOffset: 25, - tickLength: 7, + if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { + out.push(_$axis_ids_209.name2id(axName2)); + } + } - minorTickOffset: 25, - minorTickColor: '#333', - minorTickLength: 4, + return out; + } - // Extra space below the current value label: - currentValuePadding: 8, - currentValueInset: 0, -}; + // first pass creates the containers, determines types, and handles most of the settings + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(!_$lib_164.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } -'use strict'; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; -// This is used exclusively by components inside component arrays, -// hence the 'arraydraw' editType. If this ever gets used elsewhere -// we could generalize it as a function ala font_attributes -var _$pad_attributes_244 = { - t: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - r: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - b: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - l: { - valType: 'number', - dflt: 0, - - editType: 'arraydraw', - - }, - editType: 'arraydraw' -}; + _$handleTypeDefaults_229(axLayoutIn, axLayoutOut, coerce, fullData, axName); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); -'use strict'; + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; -/* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_244 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_131 = _$extend_156.extendDeepAll; -var __overrideAll_131 = _$edit_types_190.overrideAll; -/* removed: var _$animation_attributes_200 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_132 = require('./constants'); */; + _$handleAxisDefaults_208(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); -var stepsAttrs = { - _isLinkedToArray: 'step', + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - { valType: 'any' }, - { valType: 'any' }, - { valType: 'any' } - ], - - }, - label: { - valType: 'string', - - - }, - value: { - valType: 'string', - - - }, - execute: { - valType: 'boolean', - - dflt: true, - - } -}; + if(!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; + } -var _$attributes_131 = __overrideAll_131({ - _isLinkedToArray: 'slider', + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; - visible: { - valType: 'boolean', - - dflt: true, - - }, + _$handlePositionDefaults_221(axLayoutIn, axLayoutOut, coerce, positioningOptions); - active: { - valType: 'number', - - min: 0, - dflt: 0, - - }, + axLayoutOut._input = axLayoutIn; + } - steps: stepsAttrs, + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_254.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_254.getComponentMethod('rangeselector', 'handleDefaults'); - lenmode: { - valType: 'enumerated', - values: ['fraction', 'pixels'], - - dflt: 'fraction', - - }, - len: { - valType: 'number', - min: 0, - dflt: 1, - - - }, - x: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, - - - }, - pad: __extendDeepAll_131({}, _$pad_attributes_244, { - - }, {t: {dflt: 20}}), - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'left', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 0, - - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - transition: { - duration: { - valType: 'number', - - min: 0, - dflt: 150, - - }, - easing: { - valType: 'enumerated', - values: _$animation_attributes_200.transition.easing.values, - - dflt: 'cubic-in-out', - + rangeSliderDefaults(layoutIn, layoutOut, axName); + + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); } - }, - currentvalue: { - visible: { - valType: 'boolean', - - dflt: true, - - }, + coerce('fixedrange'); + } - xanchor: { - valType: 'enumerated', - values: ['left', 'center', 'right'], - dflt: 'left', - - - }, + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - offset: { - valType: 'number', - dflt: 10, - - - }, + var anchoredAxis = layoutOut[_$axis_ids_209.id2name(axLayoutOut.anchor)]; - prefix: { - valType: 'string', - - - }, + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - suffix: { - valType: 'string', - - - }, + coerce('fixedrange', fixedRangeDflt); + } - font: _$font_attributes_232({ - - }) - }, + // Finally, handle scale constraints. 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). - font: _$font_attributes_232({ - - }), + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); - activebgcolor: { - valType: 'color', - - dflt: _$constants_132.gripBgActiveColor, - - }, - bgcolor: { - valType: 'color', - - dflt: _$constants_132.railBgColor, - - }, - bordercolor: { - valType: 'color', - dflt: _$constants_132.railBorderColor, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: _$constants_132.railBorderWidth, - - - }, - ticklen: { - valType: 'number', - min: 0, - dflt: _$constants_132.tickLength, - - - }, - tickcolor: { - valType: 'color', - dflt: _$constants_132.tickColor, - - - }, - tickwidth: { - valType: 'number', - min: 0, - dflt: 1, - - - }, - minorticklen: { - valType: 'number', - min: 0, - dflt: _$constants_132.minorTickLength, - - + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + + _$handleConstraintDefaults_212(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); } -}, 'arraydraw', 'from-root'); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -43404,997 +44513,1009 @@ var _$attributes_131 = __overrideAll_131({ 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; - -/* removed: var _$attributes_131 = require('./attributes'); */; -/* removed: var _$constants_132 = require('./constants'); */; +/* removed: var _$d3_6 = require('d3'); */; -var __name_133 = _$constants_132.name; -var stepAttrs = _$attributes_131.steps; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$drawing_68 = require('../../components/drawing'); */; +/* removed: var _$axes_206 = require('./axes'); */; +var axisRegex = _$constants_211.attrRegex; +var _$transitionAxes_228 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var axes = []; -var _$slidersDefaults_133 = function slidersDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_133, - handleItemDefaults: sliderDefaults - }; + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); -}; + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; -function sliderDefaults(sliderIn, sliderOut, layoutOut) { + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; - function coerce(attr, dflt) { - return _$lib_163.coerce(sliderIn, sliderOut, _$attributes_131, attr, dflt); - } + update.axisName = axisName; + update.length = axis._length; - var steps = stepsDefaults(sliderIn, sliderOut); + axes.push(axisLetter); - var visible = coerce('visible', steps.length > 0); - if(!visible) return; + updates[axisLetter] = update; + } + } - coerce('active'); + return updates; + } - coerce('x'); - coerce('y'); - _$lib_163.noneOrAll(sliderIn, sliderOut, ['x', 'y']); + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - coerce('xanchor'); - coerce('yanchor'); + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - coerce('len'); - coerce('lenmode'); + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; - _$lib_163.coerceFont(coerce, 'font', layoutOut.font); + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); - var currentValueIsVisible = coerce('currentvalue.visible'); + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; + } - if(currentValueIsVisible) { - coerce('currentvalue.xanchor'); - coerce('currentvalue.prefix'); - coerce('currentvalue.suffix'); - coerce('currentvalue.offset'); + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; + + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } + } - _$lib_163.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + return affectedSubplots; } - coerce('transition.duration'); - coerce('transition.easing'); + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - coerce('bgcolor'); - coerce('activebgcolor'); - coerce('bordercolor'); - coerce('borderwidth'); - coerce('ticklen'); - coerce('tickwidth'); - coerce('tickcolor'); - coerce('minorticklen'); -} + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); -function stepsDefaults(sliderIn, sliderOut) { - var valuesIn = sliderIn.steps || [], - valuesOut = sliderOut.steps = []; + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } - var valueIn, valueOut; + redrawObjs(fullLayout.annotations || [], _$registry_254.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_254.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_254.getComponentMethod('images', 'draw'), true); + } - function coerce(attr, dflt) { - return _$lib_163.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; } - for(var i = 0; i < valuesIn.length; i++) { - valueIn = valuesIn[i]; - valueOut = {}; + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; - coerce('method'); + activeAxIds = [xa._id, ya._id]; - if(!_$lib_163.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { - continue; + for(i = 0; i < activeAxIds.length; i++) { + _$axes_206.doTicks(gd, activeAxIds[i], true); } - coerce('args'); - coerce('label', 'step-' + i); - coerce('value', valueOut.label); - coerce('execute'); + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - valuesOut.push(valueOut); - } + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } - return valuesOut; -} + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + redrawObjs(fullLayout.annotations || [], _$registry_254.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_254.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_254.getComponentMethod('images', 'draw'), true); + } + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; -'use strict'; + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_68.setTranslate, 0, 0) + .call(_$drawing_68.setScale, 1, 1); -/* removed: var _$d3_6 = require('d3'); */; + subplot.plot + .call(_$drawing_68.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_68.setScale, 1, 1); -/* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); -/* removed: var _$constants_132 = require('./constants'); */; -/* removed: var _$alignment_143 = require('../../constants/alignment'); */; -var __LINE_SPACING_134 = _$alignment_143.LINE_SPACING; -var __FROM_TL_134 = _$alignment_143.FROM_TL; -var __FROM_BR_134 = _$alignment_143.FROM_BR; + // 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_68.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_68.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_68.hideOutsideRangePoints, subplot); + } + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; -var _$draw_134 = function draw(gd) { - var fullLayout = gd._fullLayout, - sliderData = makeSliderData(fullLayout, gd); + var viewBox = []; - // draw a container for *all* sliders: - var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_132.containerClassName) - .data(sliderData.length > 0 ? [0] : []); + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - sliders.enter().append('g') - .classed(_$constants_132.containerClassName, true) - .style('cursor', 'ew-resize'); + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - sliders.exit().remove(); + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; + } - // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_134(gd); + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // Return early if no menus visible: - if(sliderData.length === 0) return; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - var sliderGroups = sliders.selectAll('g.' + _$constants_132.groupClassName) - .data(sliderData, keyFunction); + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; + } - sliderGroups.enter().append('g') - .classed(_$constants_132.groupClassName, true); + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - sliderGroups.exit().each(function(sliderOpts) { - _$d3_6.select(this).remove(); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - sliderOpts._commandObserver.remove(); - delete sliderOpts._commandObserver; + var editX = !!xUpdate; + var editY = !!yUpdate; - _$plots_245.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index); - }); + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - // Find the dimensions of the sliders: - for(var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); - } + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - sliderGroups.each(function(sliderOpts) { - // If it has fewer than two options, it's not really a slider: - if(sliderOpts.steps.length < 2) return; + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - var gSlider = _$d3_6.select(this); + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - computeLabelSteps(sliderOpts); + subplot.clipRect + .call(_$drawing_68.setTranslate, clipDx, clipDy) + .call(_$drawing_68.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - _$plots_245.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { - // NB: Same as below. This is *not* always the same as sliderOpts since - // if a new set of steps comes in, the reference in this callback would - // be invalid. We need to refetch it from the slider group, which is - // the join data that creates this slider. So if this slider still exists, - // the group should be valid, *to the best of my knowledge.* If not, - // we'd have to look it up by d3 data join index/key. - var opts = gSlider.data()[0]; + subplot.plot + .call(_$drawing_68.setTranslate, plotDx, plotDy) + .call(_$drawing_68.setScale, xScaleFactor, yScaleFactor) - if(opts.active === data.index) return; - if(opts._dragging) return; + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_68.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - setActive(gd, gSlider, opts, data.index, false, true); - }); + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_68.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + } - drawSlider(gd, _$d3_6.select(this), sliderOpts); - }); -}; + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } -// This really only just filters by visibility: -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_132.name], - sliderData = []; + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if(!item.visible || !item.steps.length) continue; - item._gd = gd; - sliderData.push(item); - } + axi.range = to.slice(); + } - return sliderData; -} + // Signal that this transition has completed: + onComplete && onComplete(); -// This is set in the defaults step: -function keyFunction(opts) { - return opts._index; -} + return _$registry_254.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } -// Compute the dimensions (mutates sliderOpts): -function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_68.tester.selectAll('g.' + _$constants_132.labelGroupClass) - .data(sliderOpts.steps); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; - sliderLabels.enter().append('g') - .classed(_$constants_132.labelGroupClass, true); + axi.range = axi._r.slice(); + } - // loop over fake buttons to find width / height - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_6.select(this); + return _$registry_254.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); + } - var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); + var t1, t2, raf; + var easeFn = _$d3_6.ease(transitionOpts.easing); - var textNode = text.node(); - if(textNode) { - var bBox = _$drawing_68.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); - } + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); }); - sliderLabels.remove(); - - var dims = sliderOpts._dims = {}; + function doFrame() { + t2 = Date.now(); - dims.inputAreaWidth = Math.max( - _$constants_132.railWidth, - _$constants_132.gripHeight - ); + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); - // calculate some overall dimensions - some of these are needed for - // calculating the currentValue dimensions - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } - if(sliderOpts.lenmode === 'fraction') { - // fraction: - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - // pixels: - dims.outerLength = sliderOpts.len; + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); + } } - // The length of the rail, *excluding* padding on either end: - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - - var textableInputLength = dims.inputAreaLength - 2 * _$constants_132.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_132.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - // loop over all possible values for currentValue to find the - // area we need for it - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; + return Promise.resolve(); +}; - if(sliderOpts.currentvalue.visible) { - // Get the dimensions of the current value label: - var dummyGroup = _$drawing_68.tester.append('g'); +var _$get_data_234 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_68.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_184.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); +'use strict'; - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; +/* removed: var _$registry_254 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_211.SUBPLOT_PATTERN; - dummyGroup.remove(); - } +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_234.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_254.subplotsRegistry[type]; + if(!basePlotModule) return []; - dims.height = dims.currentValueTotalHeight + _$constants_132.tickOffset + sliderOpts.ticklen + _$constants_132.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + var attr = basePlotModule.attr; + var subplotCalcData = []; - var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = 'right'; - } - if(_$anchor_utils_95.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = 'center'; - } + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; - var yanchor = 'top'; - if(_$anchor_utils_95.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = 'bottom'; - } - if(_$anchor_utils_95.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = 'middle'; + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); } - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + return subplotCalcData; +}; +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_234.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_254.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; - _$plots_245.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index, { - x: sliderOpts.x, - y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_134[xanchor], - r: dims.outerLength * __FROM_BR_134[xanchor], - b: dims.height * __FROM_BR_134[yanchor], - t: dims.height * __FROM_TL_134[yanchor] - }); -} + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; -function drawSlider(gd, sliderGroup, sliderOpts) { - // This is related to the other long notes in this file regarding what happens - // when slider steps disappear. This particular fix handles what happens when - // the *current* slider step is removed. The drawing functions will error out - // when they fail to find it, so the fix for now is that it will just draw the - // slider in the first position but will not execute the command. - if(sliderOpts.active >= sliderOpts.steps.length) { - sliderOpts.active = 0; + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } } - // These are carefully ordered for proper z-ordering: - sliderGroup - .call(drawCurrentValue, sliderOpts) - .call(drawRail, sliderOpts) - .call(drawLabelGroup, sliderOpts) - .call(drawTicks, sliderOpts) - .call(drawTouchRect, gd, sliderOpts) - .call(drawGrip, gd, sliderOpts); - - var dims = sliderOpts._dims; - - // Position the rectangle: - _$drawing_68.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + return [moduleCalcData, remainingCalcData]; +}; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); - sliderGroup.call(drawCurrentValue, sliderOpts); +/** + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_234.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_254.subplotsRegistry[type]) return []; -} + var attr = _$registry_254.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if(!sliderOpts.currentvalue.visible) return; + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); - var dims = sliderOpts._dims; + for(var i = 0; i < data.length; i++) { + trace = data[i]; - switch(sliderOpts.currentvalue.xanchor) { - case 'right': - // This is anchored left and adjusted by the width of the longest label - // so that the prefix doesn't move. The goal of this is to emphasize - // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_132.currentValueInset - dims.currentValueMaxWidth; - textAnchor = 'left'; - break; - case 'center': - x0 = dims.inputAreaLength * 0.5; - textAnchor = 'middle'; - break; - default: - x0 = _$constants_132.currentValueInset; - textAnchor = 'left'; + if(type === 'gl2d' && _$registry_254.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); + } + } + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } } - text.enter().append('text') - .classed(_$constants_132.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); - - var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; + return subplotData; +}; - if(typeof valueOverride === 'string') { - str += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - str += curVal; - } +var _$cartesian_217 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(sliderOpts.currentvalue.suffix) { - str += sliderOpts.currentvalue.suffix; - } - text.call(_$drawing_68.font, sliderOpts.currentvalue.font) - .text(str) - .call(_$svg_text_utils_184.convertToTspans, sliderOpts._gd); +'use strict'; - var lines = _$svg_text_utils_184.lineCount(text); +/* removed: var _$d3_6 = require('d3'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$plots_245 = require('../plots'); */; +var getModuleCalcData = _$get_data_234.getModuleCalcData; - var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_134; +/* removed: var _$axis_ids_209 = require('./axis_ids'); */; +/* removed: var _$constants_211 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; - _$svg_text_utils_184.positionText(text, x0, y0); +var ensureSingle = _$lib_164.ensureSingle; - return text; +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_164.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); } -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_132.gripRectClass) - .data([0]); +_$cartesian_217.name = 'cartesian'; - grip.enter().append('rect') - .classed(_$constants_132.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); +_$cartesian_217.attr = ['xaxis', 'yaxis']; - grip.attr({ - width: _$constants_132.gripWidth, - height: _$constants_132.gripHeight, - rx: _$constants_132.gripRadius, - ry: _$constants_132.gripRadius, - }) - .call(_$color_43.stroke, sliderOpts.bordercolor) - .call(_$color_43.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); -} +_$cartesian_217.idRoot = ['x', 'y']; -function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); +_$cartesian_217.idRegex = _$constants_211.idRegex; - text.enter().append('text') - .classed(_$constants_132.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); +_$cartesian_217.attrRegex = _$constants_211.attrRegex; - text.call(_$drawing_68.font, sliderOpts.font) - .text(data.step.label) - .call(_$svg_text_utils_184.convertToTspans, sliderOpts._gd); +_$cartesian_217.attributes = _$attributes_204; - return text; -} +_$cartesian_217.layoutAttributes = _$layout_attributes_218; -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_132.labelsClass) - .data([0]); - var dims = sliderOpts._dims; +_$cartesian_217.supplyLayoutDefaults = _$supplyLayoutDefaults_219; - labels.enter().append('g') - .classed(_$constants_132.labelsClass, true); +_$cartesian_217.transitionAxes = _$transitionAxes_228; - var labelItems = labels.selectAll('g.' + _$constants_132.labelGroupClass) - .data(dims.labelSteps); +_$cartesian_217.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - labelItems.enter().append('g') - .classed(_$constants_132.labelGroupClass, true); + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; + } - labelItems.exit().remove(); + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_209.id2name(xi)] || {}).anchor; + if(!_$constants_211.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - labelItems.each(function(d) { - var item = _$d3_6.select(this); + if(!allY[yi]) { + allY[yi] = 1; + _$lib_164.pushUnique(yList, yi); + } + } + } - item.call(drawLabel, d, sliderOpts); + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_209.id2name(yi)] || {}).anchor; + if(!_$constants_211.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - _$drawing_68.setTranslate(item, - normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_132.tickOffset + - sliderOpts.ticklen + - // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_134 + - _$constants_132.labelOffset + - dims.currentValueTotalHeight - ); - }); + if(!allX[xi]) { + allX[xi] = 1; + _$lib_164.pushUnique(xList, xi); + } + } + } -} + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_211.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } + } + xi = xi ? _$axis_ids_209.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_209.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); +_$cartesian_217.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; - if(quantizedPosition !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); - } -} + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; -function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts._input.active = sliderOpts.active = index; + for(i = 0; i < calcdata.length; i++) { + traces.push(i); + } + } - var step = sliderOpts.steps[sliderOpts.active]; + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; - sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; - gd.emit('plotly_sliderchange', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive: previousActive - }); + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; - if(step && step.method && doCallback) { - if(sliderGroup._nextMethod) { - // If we've already queued up an update, just overwrite it with the most recent: - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if(!_step.method) return; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - if(_step.execute) { - _$plots_245.executeAPICommand(gd, _step.method, _step.args); + cdSubplot.push(cd); } - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } } - } -} - -function attachGripEvents(item, gd, sliderGroup) { - var node = sliderGroup.node(); - var $gd = _$d3_6.select(gd); - // NB: This is *not* the same as sliderOpts itself! These callbacks - // are in a closure so this array won't actually be correct if the - // steps have changed since this was initialized. The sliderGroup, - // however, has not changed since that *is* the slider, so it must - // be present to receive mouse events. - function getSliderOpts() { - return sliderGroup.data()[0]; + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); } +}; - item.on('mousedown', function() { - var sliderOpts = getSliderOpts(); - gd.emit('plotly_sliderstart', {slider: sliderOpts}); - - var grip = sliderGroup.select('.' + _$constants_132.gripRectClass); +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; - _$d3_6.event.stopPropagation(); - _$d3_6.event.preventDefault(); - grip.call(_$color_43.fill, sliderOpts.activebgcolor); + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); + } - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_6.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; - $gd.on('mousemove', function() { - var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_6.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); - }); + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; - $gd.on('mouseup', function() { - var sliderOpts = getSliderOpts(); - sliderOpts._dragging = false; - grip.call(_$color_43.fill, sliderOpts.bgcolor); - $gd.on('mouseup', null); - $gd.on('mousemove', null); + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; - gd.emit('plotly_sliderend', { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active] - }); - }); - }); + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + } } -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_132.tickRectClass) - .data(sliderOpts.steps); - var dims = sliderOpts._dims; +_$cartesian_217.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; - tick.enter().append('rect') - .classed(_$constants_132.tickRectClass, true); + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; - tick.exit().remove(); + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); + } + } - tick.attr({ - width: sliderOpts.tickwidth + 'px', - 'shape-rendering': 'crispEdges' - }); + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = _$d3_6.select(this); + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } - item - .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_43.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); - _$drawing_68.setTranslate(item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_132.tickOffset : _$constants_132.minorTickOffset) + dims.currentValueTotalHeight - ); - }); + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } -} + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } + } -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var i0 = 0; - var nsteps = sliderOpts.steps.length; + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - for(var i = i0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts.steps[i] - }); + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); + } + } } -} -function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_132.gripRectClass); + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; - var x = normalizedValueToPosition(sliderOpts, position); + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); - // If this is true, then *this component* is already invoking its own command - // and has triggered its own animation. - if(sliderOpts._invokingCommand) return; + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + } + } + } - var el = grip; - if(doTransition && sliderOpts.transition.duration > 0) { - el = el.transition() - .duration(sliderOpts.transition.duration) - .ease(sliderOpts.transition.easing); + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } } +}; - // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. - // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_132.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); -} +_$cartesian_217.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); -// Convert a number from [0-1] to a pixel position relative to the slider group container: -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_132.stepInset + - (dims.inputAreaLength - 2 * _$constants_132.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_164.identity); -// Convert a position relative to the slider group to a nubmer in [0, 1] -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_132.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_132.stepInset - 2 * dims.inputAreaStart))); -} + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_132.railTouchRectClass) - .data([0]); - var dims = sliderOpts._dims; + subplotLayers.order(); - rect.enter().append('rect') - .classed(_$constants_132.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - rect.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_132.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }) - .call(_$color_43.fill, sliderOpts.bgcolor) - .attr('opacity', 0); + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; - _$drawing_68.setTranslate(rect, 0, dims.currentValueTotalHeight); -} + // keep ref to plot group + plotinfo.plotgroup = _$d3_6.select(this); -function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_132.railRectClass) - .data([0]); - var dims = sliderOpts._dims; + // initialize list of overlay subplots + plotinfo.overlays = []; - rect.enter().append('rect') - .classed(_$constants_132.railRectClass, true); + makeSubplotLayer(gd, plotinfo); - var computedLength = dims.inputAreaLength - _$constants_132.railInset * 2; + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); + } - rect.attr({ - width: computedLength, - height: _$constants_132.railWidth, - rx: _$constants_132.railRadius, - ry: _$constants_132.railRadius, - 'shape-rendering': 'crispEdges' - }) - .call(_$color_43.stroke, sliderOpts.bordercolor) - .call(_$color_43.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); + }); +}; - _$drawing_68.setTranslate(rect, - _$constants_132.railInset, - (dims.inputAreaWidth - _$constants_132.railWidth) * 0.5 + dims.currentValueTotalHeight - ); -} +_$cartesian_217.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_245.style(gd); +}; -function __clearPushMargins_134(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}, - keys = Object.keys(pushMargins); +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; - if(k.indexOf(_$constants_132.autoMarginIdRoot) !== -1) { - _$plots_245.autoMargin(gd, k); + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; } } + + // main subplots before overlays + subplotData = subplotData.concat(overlays); + + return subplotData; } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_211.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_211.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; -'use strict'; + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); -/* removed: var _$constants_132 = require('./constants'); */; + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); -var _$sliders_135 = { - moduleType: 'component', - name: _$constants_132.name, + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - layoutAttributes: _$attributes_131, - supplyLayoutDefaults: _$slidersDefaults_133, + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - draw: _$draw_134 -}; + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); -'use strict'; + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); -/* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_42 = require('../color/attributes'); */; -var __extendFlat_137 = _$extend_156.extendFlat; -var __overrideAll_137 = _$edit_types_190.overrideAll; -/* removed: var _$pad_attributes_244 = require('../../plots/pad_attributes'); */; - -var buttonsAttrs = { - _isLinkedToArray: 'button', - - method: { - valType: 'enumerated', - values: ['restyle', 'relayout', 'animate', 'update', 'skip'], - dflt: 'restyle', - - - }, - args: { - valType: 'info_array', - - freeLength: true, - items: [ - {valType: 'any'}, - {valType: 'any'}, - {valType: 'any'} - ], - - }, - label: { - valType: 'string', - - dflt: '', - - }, - execute: { - valType: 'boolean', - - dflt: true, - + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } -}; - -var _$attributes_137 = __overrideAll_137({ - _isLinkedToArray: 'updatemenu', - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - - visible: { - valType: 'boolean', - - - }, - - type: { - valType: 'enumerated', - values: ['dropdown', 'buttons'], - dflt: 'dropdown', - - - }, - - direction: { - valType: 'enumerated', - values: ['left', 'right', 'up', 'down'], - dflt: 'down', - - - }, - - active: { - valType: 'integer', - - min: -1, - dflt: 0, - - }, + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - showactive: { - valType: 'boolean', - - dflt: true, - - }, + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. - buttons: buttonsAttrs, + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - x: { - valType: 'number', - min: -2, - max: 3, - dflt: -0.05, - - - }, - xanchor: { - valType: 'enumerated', - values: ['auto', 'left', 'center', 'right'], - dflt: 'right', - - - }, - y: { - valType: 'number', - min: -2, - max: 3, - dflt: 1, - - - }, - yanchor: { - valType: 'enumerated', - values: ['auto', 'top', 'middle', 'bottom'], - dflt: 'top', - - - }, + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - pad: __extendFlat_137({}, _$pad_attributes_244, { - - }), + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - font: _$font_attributes_232({ - - }), + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - bgcolor: { - valType: 'color', - - - }, - bordercolor: { - valType: 'color', - dflt: _$attributes_42.borderLine, - - - }, - borderwidth: { - valType: 'number', - min: 0, - dflt: 1, - - editType: 'arraydraw', - + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); } -}, 'arraydraw', 'from-root'); - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // common attributes for all subplots, overlays or not -'use strict'; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_209.idSort); + for(var i = 0; i < _$constants_211.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_211.traceLayerClasses[i]); + } + } -var _$constants_138 = { + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - // layout attribute name - name: 'updatemenus', + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - // 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', +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: 'updatemenu-active-index', + var overlayIdsToRemove = {}; - // id root pass to Plots.autoMargin - autoMarginIdRoot: 'updatemenu-', + layers.each(function(subplotId) { + var plotgroup = _$d3_6.select(this); - // options when 'active: -1' - blankHeaderOpts: { label: ' ' }, + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - // min item width / height - minWidth: 30, - minHeight: 30, + overlayIdsToRemove[subplotId] = true; - // padding around item text - textPadX: 24, - arrowPadX: 16, + // do not remove individual axis s here + // as other subplots may need them + }); - // item rect radii - rx: 2, - ry: 2, + // must remove overlaid subplot trace layers 'manually' - // item text x offset off left edge - textOffsetX: 12, + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); - // item text y offset (w.r.t. middle) - textOffsetY: 3, + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - // arrow offset off right edge - arrowOffsetX: 4, + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; - // gap between header and buttons - gapButtonHeader: 5, + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } + } + } +} - // gap between between buttons - gapButton: 2, +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); +} - // color given to active buttons - activeColor: '#F4FAFF', +_$cartesian_217.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_6.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); - // color given to hovered buttons - hoverColor: '#F4FAFF', + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); - // symbol for menu open arrow - arrowSymbol: { - left: '◄', - right: '►', - up: '▲', - down: '▼' + image.attr({ + xmlns: _$xmlns_namespaces_147.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); } + + canvases.each(canvasToImage); }; +_$cartesian_217.updateFx = _$graph_interact_215.updateFx; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44405,1248 +45526,1177 @@ var _$constants_138 = { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_201 = require('../../plots/array_container_defaults'); */; +/* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$attributes_137 = require('./attributes'); */; -/* removed: var _$constants_138 = require('./constants'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$plots_245 = require('../../plots/plots'); */; -var __name_139 = _$constants_138.name; -var __buttonAttrs_139 = _$attributes_137.buttons; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$titles_136 = require('../titles'); */; +/* removed: var _$cartesian_217 = require('../../plots/cartesian'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; -var _$updateMenusDefaults_139 = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: __name_139, - handleItemDefaults: menuDefaults - }; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$setCursor_183 = require('../../lib/setcursor'); */; - _$handleArrayContainerDefaults_201(layoutIn, layoutOut, opts); -}; +/* removed: var _$constants_118 = require('./constants'); */; -function menuDefaults(menuIn, menuOut, layoutOut) { +var _$draw_120 = function(gd) { + var fullLayout = gd._fullLayout, + rangeSliderData = makeRangeSliderData(fullLayout); - function coerce(attr, dflt) { - return _$lib_163.coerce(menuIn, menuOut, _$attributes_137, attr, dflt); + /* + * + * + * < .... range plot /> + * + * + * + * + * + * + * + * + * + * + * ... + */ + + function keyFunction(axisOpts) { + return axisOpts._name; } - var buttons = __buttonsDefaults_139(menuIn, menuOut); + var rangeSliders = fullLayout._infolayer + .selectAll('g.' + _$constants_118.containerClassName) + .data(rangeSliderData, keyFunction); - var visible = coerce('visible', buttons.length > 0); - if(!visible) return; + rangeSliders.enter().append('g') + .classed(_$constants_118.containerClassName, true) + .attr('pointer-events', 'all'); - coerce('active'); - coerce('direction'); - coerce('type'); - coerce('showactive'); + // remove exiting sliders and their corresponding clip paths + rangeSliders.exit().each(function(axisOpts) { + var rangeSlider = _$d3_6.select(this), + opts = axisOpts[_$constants_118.name]; - coerce('x'); - coerce('y'); - _$lib_163.noneOrAll(menuIn, menuOut, ['x', 'y']); + rangeSlider.remove(); + fullLayout._topdefs.select('#' + opts._clipId).remove(); + }); - coerce('xanchor'); - coerce('yanchor'); + // remove push margin object(s) + if(rangeSliders.exit().size()) clearPushMargins(gd); - coerce('pad.t'); - coerce('pad.r'); - coerce('pad.b'); - coerce('pad.l'); + // return early if no range slider is visible + if(rangeSliderData.length === 0) return; - _$lib_163.coerceFont(coerce, 'font', layoutOut.font); + // for all present range sliders + rangeSliders.each(function(axisOpts) { + var rangeSlider = _$d3_6.select(this), + opts = axisOpts[_$constants_118.name], + oppAxisOpts = fullLayout[_$axes_206.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_206.id2name(axisOpts.anchor)]; - coerce('bgcolor', layoutOut.paper_bgcolor); - coerce('bordercolor'); - coerce('borderwidth'); -} + // update range + // Expand slider range to the axis range + // TODO: what if the ranges are reversed? + if(opts.range) { + var outRange = opts.range; + var axRange = axisOpts.range; -function __buttonsDefaults_139(menuIn, menuOut) { - var buttonsIn = menuIn.buttons || [], - buttonsOut = menuOut.buttons = []; + outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0]))); + outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1]))); + opts._input.range = outRange.slice(); + } - var buttonIn, buttonOut; + axisOpts.cleanRange('rangeslider.range'); - function coerce(attr, dflt) { - return _$lib_163.coerce(buttonIn, buttonOut, __buttonAttrs_139, attr, dflt); - } - for(var i = 0; i < buttonsIn.length; i++) { - buttonIn = buttonsIn[i]; - buttonOut = {}; + // update range slider dimensions - coerce('method'); + var margin = fullLayout.margin; + var graphSize = fullLayout._size; + var domain = axisOpts.domain; + var tickHeight = (axisOpts._boundingBox || {}).height || 0; - if(!_$lib_163.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { - continue; + var oppBottom = Infinity; + var subplotData = _$axes_206.getSubplots(gd, axisOpts); + for(var i = 0; i < subplotData.length; i++) { + var oppAxis = _$axes_206.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - coerce('args'); - coerce('label'); - coerce('execute'); - - buttonOut._index = i; - buttonsOut.push(buttonOut); - } + opts._id = _$constants_118.name + axisOpts._id; + opts._clipId = opts._id + '-' + fullLayout._uid; - return buttonsOut; -} + opts._width = graphSize.w * (domain[1] - domain[0]); + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 x = Math.round(margin.l + (graphSize.w * domain[0])); -'use strict'; + var y = Math.round( + graphSize.t + graphSize.h * (1 - oppBottom) + + tickHeight + + opts._offsetShift + _$constants_118.extraPad + ); -var _$ScrollBox_142 = ScrollBox; + rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); -/* removed: var _$d3_6 = require('d3'); */; + // update data <--> pixel coordinate conversion methods -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; + var range0 = axisOpts.r2l(opts.range[0]), + range1 = axisOpts.r2l(opts.range[1]), + dist = range1 - range0; -/* removed: var _$lib_163 = require('../../lib'); */; + opts.p2d = function(v) { + return (v / opts._width) * dist + range0; + }; -/** - * Helper class to setup a scroll box - * - * @class - * @param gd Plotly's graph div - * @param container Container to be scroll-boxed (as a D3 selection) - * @param {string} id Id for the clip path to implement the scroll box - */ -function ScrollBox(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; + opts.d2p = function(v) { + return (v - range0) / dist * opts._width; + }; - // See ScrollBox.prototype.enable for further definition - this.position = null; // scrollbox position - this.translateX = null; // scrollbox horizontal translation - this.translateY = null; // scrollbox vertical translation - this.hbar = null; // horizontal scrollbar D3 selection - this.vbar = null; // vertical scrollbar D3 selection + opts._rl = [range0, range1]; - // element to capture pointer events - this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); + if(oppAxisRangeOpts.rangemode !== 'match') { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]), + range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]), + distOppAxis = range1OppAxis - range0OppAxis; - this.bg.exit() - .on('.drag', null) - .on('wheel', null) - .remove(); + opts.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts._height; + }; + } - this.bg.enter().append('rect') - .classed('scrollbox-bg', true) - .style('pointer-events', 'all') - .attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} + // update inner nodes -// scroll bar dimensions -ScrollBox.barWidth = 2; -ScrollBox.barLength = 20; -ScrollBox.barRadius = 2; -ScrollBox.barPad = 1; -ScrollBox.barColor = '#808BA4'; + rangeSlider + .call(drawBg, gd, axisOpts, opts) + .call(addClipPath, gd, axisOpts, opts) + .call(drawRangePlot, gd, axisOpts, opts) + .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts) + .call(drawSlideBox, gd, axisOpts, opts) + .call(drawGrabbers, gd, axisOpts, opts); -/** - * If needed, setup a clip path and scrollbars - * - * @method - * @param {Object} position - * @param {number} position.l Left side position (in pixels) - * @param {number} position.t Top side (in pixels) - * @param {number} position.w Width (in pixels) - * @param {number} position.h Height (in pixels) - * @param {string} [position.direction='down'] - * Either 'down', 'left', 'right' or 'up' - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout, - fullWidth = fullLayout.width, - fullHeight = fullLayout.height; + // setup drag element + setupDragElement(rangeSlider, gd, axisOpts, opts); - // compute position of scrollbox - this.position = position; + // update current range + setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts); - var l = this.position.l, - w = this.position.w, - t = this.position.t, - h = this.position.h, - direction = this.position.direction, - isDown = (direction === 'down'), - isLeft = (direction === 'left'), - isRight = (direction === 'right'), - isUp = (direction === 'up'), - boxW = w, - boxH = h, - boxL, boxR, - boxT, boxB; - - if(!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = 'down'; - isDown = true; - } - - var isVertical = isDown || isUp; - if(isVertical) { - boxL = l; - boxR = boxL + boxW; - - if(isDown) { - // anchor to top side - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } - else { - // anchor to bottom side - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } - } - else { - boxT = t; - boxB = boxT + boxH; - - if(isLeft) { - // anchor to right side - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } - else { - // anchor to left side - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; + // title goes next to range slider instead of tick labels, so + // just take it over and draw it from here + if(axisOpts.side === 'bottom') { + _$titles_136.draw(gd, axisOpts._id + 'title', { + propContainer: axisOpts, + propName: axisOpts._name + '.title', + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size, + 'text-anchor': 'middle' + } + }); } - } - - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; - // compute position of horizontal scroll bar - var needsHorizontalScrollBar = (w > boxW), - hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, - hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, - // draw horizontal scrollbar on the bottom side - hbarL = l, - hbarT = t + h; - - if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - - var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( - (needsHorizontalScrollBar) ? [0] : []); - - hbar.exit() - .on('.drag', null) - .remove(); - - hbar.enter().append('rect') - .classed('scrollbar-horizontal', true) - .call(_$color_43.fill, ScrollBox.barColor); - - if(needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': hbarL, - 'y': hbarT, - 'width': hbarW, - 'height': hbarH + // update margins + _$plots_245.autoMargin(gd, opts._id, { + x: domain[0], + y: oppBottom, + l: 0, + r: 0, + t: 0, + b: opts._height + margin.b + tickHeight, + pad: _$constants_118.extraPad + opts._offsetShift * 2 }); + }); +}; - // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } - else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } - - // compute position of vertical scroll bar - var needsVerticalScrollBar = (h > boxH), - vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, - vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, - // draw vertical scrollbar on the right side - vbarL = l + w, - vbarT = t; - - if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; +function makeRangeSliderData(fullLayout) { + var axes = _$axes_206.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_118.name, + out = []; - var vbar = this.container.selectAll('rect.scrollbar-vertical').data( - (needsVerticalScrollBar) ? [0] : []); + if(fullLayout._has('gl2d')) return out; - vbar.exit() - .on('.drag', null) - .remove(); + for(var i = 0; i < axes.length; i++) { + var ax = axes[i]; - vbar.enter().append('rect') - .classed('scrollbar-vertical', true) - .call(_$color_43.fill, ScrollBox.barColor); + if(ax[name] && ax[name].visible) out.push(ax); + } - if(needsVerticalScrollBar) { - this.vbar = vbar.attr({ - 'rx': ScrollBox.barRadius, - 'ry': ScrollBox.barRadius, - 'x': vbarL, - 'y': vbarT, - 'width': vbarW, - 'height': vbarH - }); + return out; +} - // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } - else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } +function setupDragElement(rangeSlider, gd, axisOpts, opts) { + var slideBox = rangeSlider.select('rect.' + _$constants_118.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_118.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_118.grabAreaMaxClassName).node(); - // setup a clip path (if scroll bars are needed) - var clipId = this.id, - clipL = boxL - 0.5, - clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, - clipT = boxT - 0.5, - clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + rangeSlider.on('mousedown', function() { + var event = _$d3_6.event, + target = event.target, + startX = event.clientX, + offsetX = startX - rangeSlider.node().getBoundingClientRect().left, + minVal = opts.d2p(axisOpts._rl[0]), + maxVal = opts.d2p(axisOpts._rl[1]); - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + var dragCover = _$dragelement_65.coverSlip(); - clipPath.exit().remove(); + dragCover.addEventListener('mousemove', mouseMove); + dragCover.addEventListener('mouseup', mouseUp); - clipPath.enter() - .append('clipPath').attr('id', clipId) - .append('rect'); + function mouseMove(e) { + var delta = +e.clientX - startX; + var pixelMin, pixelMax, cursor; - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select('rect').attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); + switch(target) { + case slideBox: + cursor = 'ew-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal + delta; + break; - this.container.call(_$drawing_68.setClipUrl, clipId); + case grabAreaMin: + cursor = 'col-resize'; + pixelMin = minVal + delta; + pixelMax = maxVal; + break; - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } - else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_68.setClipUrl, null); - delete this._clipRect; - } + case grabAreaMax: + cursor = 'col-resize'; + pixelMin = minVal; + pixelMax = maxVal + delta; + break; - // set up drag listeners (if scroll bars are needed) - if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_6.behavior.drag() - .on('dragstart', function() { - _$d3_6.event.sourceEvent.preventDefault(); - }) - .on('drag', this._onBoxDrag.bind(this)); + default: + cursor = 'ew-resize'; + pixelMin = offsetX; + pixelMax = offsetX + delta; + break; + } - this.container - .on('wheel', null) - .on('wheel', this._onBoxWheel.bind(this)) - .on('.drag', null) - .call(onBoxDrag); + if(pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } - var onBarDrag = _$d3_6.behavior.drag() - .on('dragstart', function() { - _$d3_6.event.sourceEvent.preventDefault(); - _$d3_6.event.sourceEvent.stopPropagation(); - }) - .on('drag', this._onBarDrag.bind(this)); + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; - if(needsHorizontalScrollBar) { - this.hbar - .on('.drag', null) - .call(onBarDrag); + _$setCursor_183(_$d3_6.select(dragCover), cursor); + setDataRange(rangeSlider, gd, axisOpts, opts); } - if(needsVerticalScrollBar) { - this.vbar - .on('.drag', null) - .call(onBarDrag); + function mouseUp() { + dragCover.removeEventListener('mousemove', mouseMove); + dragCover.removeEventListener('mouseup', mouseUp); + _$lib_164.removeElement(dragCover); } - } - - // set scrollbox translation - this.setTranslate(translateX, translateY); -}; + }); +} -/** - * If present, remove clip-path and scrollbars - * - * @method - */ -ScrollBox.prototype.disable = function disable() { - if(this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container - .on('wheel', null) - .on('.drag', null) - .call(_$drawing_68.setClipUrl, null); - delete this._clipRect; - } +function setDataRange(rangeSlider, gd, axisOpts, opts) { - if(this.hbar) { - this.hbar.on('.drag', null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; + function clamp(v) { + return axisOpts.l2r(_$lib_164.constrain(v, opts._rl[0], opts._rl[1])); } - if(this.vbar) { - this.vbar.on('.drag', null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } -}; + var dataMin = clamp(opts.p2d(opts._pixelMin)), + dataMax = clamp(opts.p2d(opts._pixelMax)); -/** - * Handles scroll box drag events - * - * @method - */ -ScrollBox.prototype._onBoxDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + window.requestAnimationFrame(function() { + _$registry_254.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + }); +} - if(this.hbar) { - translateX -= _$d3_6.event.dx; - } +function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = _$constants_118.handleWidth / 2; - if(this.vbar) { - translateY -= _$d3_6.event.dy; + function clamp(v) { + return _$lib_164.constrain(v, 0, opts._width); } - this.setTranslate(translateX, translateY); -}; - -/** - * Handles scroll box wheel events - * - * @method - */ -ScrollBox.prototype._onBoxWheel = function onBarWheel() { - var translateX = this.translateX, - translateY = this.translateY; - - if(this.hbar) { - translateX += _$d3_6.event.deltaY; + function clampOppAxis(v) { + return _$lib_164.constrain(v, 0, opts._height); } - if(this.vbar) { - translateY += _$d3_6.event.deltaY; + function clampHandle(v) { + return _$lib_164.constrain(v, -hw2, opts._width + hw2); } - this.setTranslate(translateX, translateY); -}; + var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), + pixelMax = clamp(opts.d2p(axisOpts._rl[1])); -/** - * Handles scroll bar drag events - * - * @method - */ -ScrollBox.prototype._onBarDrag = function onBarDrag() { - var translateX = this.translateX, - translateY = this.translateY; + rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) + .attr('x', pixelMin) + .attr('width', pixelMax - pixelMin); - if(this.hbar) { - var xMin = translateX + this._hbarXMin, - xMax = xMin + this._hbarTranslateMax, - x = _$lib_163.constrain(_$d3_6.event.x, xMin, xMax), - xf = (x - xMin) / (xMax - xMin); + rangeSlider.select('rect.' + _$constants_118.maskMinClassName) + .attr('width', pixelMin); - var translateXMax = this.position.w - this._box.w; + rangeSlider.select('rect.' + _$constants_118.maskMaxClassName) + .attr('x', pixelMax) + .attr('width', opts._width - pixelMax); - translateX = xf * translateXMax; - } + if(oppAxisRangeOpts.rangemode !== 'match') { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), + pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - if(this.vbar) { - var yMin = translateY + this._vbarYMin, - yMax = yMin + this._vbarTranslateMax, - y = _$lib_163.constrain(_$d3_6.event.y, yMin, yMax), - yf = (y - yMin) / (yMax - yMin); + rangeSlider.select('rect.' + _$constants_118.maskMinOppAxisClassName) + .attr('x', pixelMin) + .attr('height', pixelMinOppAxis) + .attr('width', pixelMax - pixelMin); - var translateYMax = this.position.h - this._box.h; + rangeSlider.select('rect.' + _$constants_118.maskMaxOppAxisClassName) + .attr('x', pixelMin) + .attr('y', pixelMaxOppAxis) + .attr('height', opts._height - pixelMaxOppAxis) + .attr('width', pixelMax - pixelMin); - translateY = yf * translateYMax; + rangeSlider.select('rect.' + _$constants_118.slideBoxClassName) + .attr('y', pixelMinOppAxis) + .attr('height', pixelMaxOppAxis - pixelMinOppAxis); } - this.setTranslate(translateX, translateY); -}; - -/** - * Set clip path and scroll bar translate transform - * - * @method - * @param {number} [translateX=0] Horizontal offset (in pixels) - * @param {number} [translateY=0] Vertical offset (in pixels) - */ -ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { - // store translateX and translateY (needed by mouse event handlers) - var translateXMax = this.position.w - this._box.w, - translateYMax = this.position.h - this._box.h; + // add offset for crispier corners + // https://github.com/plotly/plotly.js/pull/1409 + var offset = 0.5; - translateX = _$lib_163.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_163.constrain(translateY || 0, 0, translateYMax); + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, + xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - this.translateX = translateX; - this.translateY = translateY; + rangeSlider.select('g.' + _$constants_118.grabberMinClassName) + .attr('transform', 'translate(' + xMin + ',' + offset + ')'); - this.container.call(_$drawing_68.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY); + rangeSlider.select('g.' + _$constants_118.grabberMaxClassName) + .attr('transform', 'translate(' + xMax + ',' + offset + ')'); +} - if(this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) +function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = _$lib_164.ensureSingle(rangeSlider, 'rect', _$constants_118.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' }); - } + }); - if(this.hbar) { - var xf = translateX / translateXMax; + var borderCorrect = (opts.borderwidth % 2) === 0 ? + opts.borderwidth : + opts.borderwidth - 1; - this.hbar.call(_$drawing_68.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY); - } + var offsetShift = -opts._offsetShift; + var lw = _$drawing_68.crispRound(gd, opts.borderwidth); - if(this.vbar) { - var yf = translateY / translateYMax; + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: 'translate(' + offsetShift + ',' + offsetShift + ')', + fill: opts.bgcolor, + stroke: opts.bordercolor, + 'stroke-width': lw + }); +} - this.vbar.call(_$drawing_68.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax); - } -}; +function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 clipPath = _$lib_164.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); + clipPath.select('rect').attr({ + width: opts._width, + height: opts._height + }); +} -'use strict'; +function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var subplotData = _$axes_206.getSubplots(gd, axisOpts), + calcData = gd.calcdata; -/* removed: var _$d3_6 = require('d3'); */; + var rangePlots = rangeSlider.selectAll('g.' + _$constants_118.rangePlotClassName) + .data(subplotData, _$lib_164.identity); -/* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$color_43 = require('../color'); */; -/* removed: var _$drawing_68 = require('../drawing'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; + rangePlots.enter().append('g') + .attr('class', function(id) { return _$constants_118.rangePlotClassName + ' ' + id; }) + .call(_$drawing_68.setClipUrl, opts._clipId); -var __LINE_SPACING_140 = _$alignment_143.LINE_SPACING; + rangePlots.order(); -/* removed: var _$constants_138 = require('./constants'); */; -/* removed: var _$ScrollBox_142 = require('./scrollbox'); */; + rangePlots.exit().remove(); -var _$draw_140 = function draw(gd) { - var fullLayout = gd._fullLayout, - menuData = makeMenuData(fullLayout); + var mainplotinfo; - /* Update menu data is bound to the header-group. - * The items in the header group are always present. - * - * Upon clicking on a header its corresponding button - * data is bound to the button-group. - * - * We draw all headers in one group before all buttons - * so that the buttons *always* appear above the headers. - * - * Note that only one set of buttons are visible at once. - * - * - * - * - * - * - * - * - * - * ... - * - * - * - * - * ... - */ - - // draw update menu container - var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_138.containerClassName) - .data(menuData.length > 0 ? [0] : []); - - menus.enter().append('g') - .classed(_$constants_138.containerClassName, true) - .style('cursor', 'pointer'); + rangePlots.each(function(id, i) { + var plotgroup = _$d3_6.select(this), + isMainPlot = (i === 0); - menus.exit().remove(); + var oppAxisOpts = _$axes_206.getFromId(gd, id, 'y'), + oppAxisName = oppAxisOpts._name, + oppAxisRangeOpts = opts[oppAxisName]; - // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_140(gd); + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; - // return early if no update menus are visible - if(menuData.length === 0) return; + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; - // join header group - var headerGroups = menus.selectAll('g.' + _$constants_138.headerGroupClassName) - .data(menuData, __keyFunction_140); + _$plots_245.supplyDefaults(mockFigure); - headerGroups.enter().append('g') - .classed(_$constants_138.headerGroupClassName, true); + var xa = mockFigure._fullLayout.xaxis, + ya = mockFigure._fullLayout[oppAxisName]; - // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_138.dropdownButtonGroupClassName) - .data([0]); + var plotinfo = { + id: id, + plotgroup: plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; - gButton.enter().append('g') - .classed(_$constants_138.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + if(isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = 'xy'; + plotinfo.mainplotinfo = mainplotinfo; + } - // find dimensions before plotting anything (this mutates menuOpts) - for(var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - __findDimensions_140(gd, menuOpts); - } + _$cartesian_217.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + }); +} - // setup scrollbox - var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_142(gd, gButton, scrollBoxId); +function filterRangePlotCalcData(calcData, subplotId) { + var out = []; - // remove exiting header, remove dropped buttons and reset margins - if(headerGroups.enter().size()) { - // make sure gButton is on top of all headers - gButton.node().parentNode.appendChild(gButton.node()); + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i], + trace = calcTrace[0].trace; - gButton - .call(removeAllButtons) - .attr(_$constants_138.menuIndexAttrName, '-1'); + if(trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } } - headerGroups.exit().each(function(menuOpts) { - _$d3_6.select(this).remove(); - - gButton - .call(removeAllButtons) - .attr(_$constants_138.menuIndexAttrName, '-1'); + return out; +} - _$plots_245.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index); +function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = _$lib_164.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); }); - // draw headers! - headerGroups.each(function(menuOpts) { - var gHeader = _$d3_6.select(this); + maskMin + .attr('height', opts._height) + .call(_$color_43.fill, _$constants_118.maskColor); - var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_245.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_140(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + var maskMax = _$lib_164.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' }); - - if(menuOpts.type === 'dropdown') { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - - // if this menu is active, update the dropdown container - if(__isActive_140(gButton, menuOpts)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts); - } - }); -}; - -/** - * get only visible menus for display - */ -function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_138.name]; - var menuData = []; - - for(var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - - if(item.visible) menuData.push(item); - } - - return menuData; -} - -// Note that '_index' is set at the default step, -// it corresponds to the menu index in the user layout update menu container. -// Because a menu can be set invisible, -// this is a more 'consistent' field than the index in the menuData. -function __keyFunction_140(menuOpts) { - return menuOpts._index; -} - -function isFolded(gButton) { - return +gButton.attr(_$constants_138.menuIndexAttrName) === -1; -} -function __isActive_140(gButton, menuOpts) { - return +gButton.attr(_$constants_138.menuIndexAttrName) === menuOpts._index; -} + maskMax + .attr('height', opts._height) + .call(_$color_43.fill, _$constants_118.maskColor); -function __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - // update 'active' attribute in menuOpts - menuOpts._input.active = menuOpts.active = buttonIndex; + // masks used for oppAxis zoom + if(oppAxisRangeOpts.rangemode !== 'match') { + var maskMinOppAxis = _$lib_164.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(menuOpts.type === 'buttons') { - drawButtons(gd, gHeader, null, null, menuOpts); - } - else if(menuOpts.type === 'dropdown') { - // fold up buttons and redraw header - gButton.attr(_$constants_138.menuIndexAttrName, '-1'); + maskMinOppAxis + .attr('width', opts._width) + .call(_$color_43.fill, _$constants_118.maskOppAxisColor); - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + var maskMaxOppAxis = _$lib_164.ensureSingle(rangeSlider, 'rect', _$constants_118.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); - if(!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } + maskMaxOppAxis + .attr('width', opts._width) + .style('border-top', _$constants_118.maskOppBorder) + .call(_$color_43.fill, _$constants_118.maskOppAxisColor); } } -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_138.headerClassName) - .data([0]); - var dims = menuOpts._dims; - - header.enter().append('g') - .classed(_$constants_138.headerClassName, true) - .style('pointer-events', 'all'); - - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_138.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; +function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if(gd._context.staticPlot) return; - header - .call(drawItem, menuOpts, headerOpts, gd) - .call(setItemPosition, menuOpts, posOpts, positionOverrides); + var slideBox = _$lib_164.ensureSingle(rangeSlider, 'rect', _$constants_118.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_118.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); - // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_138.headerArrowClassName) - .data([0]); + slideBox.attr({ + height: opts._height, + fill: _$constants_118.slideBoxFill + }); +} - arrow.enter().append('text') - .classed(_$constants_138.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_68.font, menuOpts.font) - .text(_$constants_138.arrowSymbol[menuOpts.direction]); +function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + // + var grabberMin = _$lib_164.ensureSingle(rangeSlider, 'g', _$constants_118.grabberMinClassName); + var grabberMax = _$lib_164.ensureSingle(rangeSlider, 'g', _$constants_118.grabberMaxClassName); - arrow.attr({ - x: dims.headerWidth - _$constants_138.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_138.textOffsetY + menuOpts.pad.t + // + var handleFixAttrs = { + x: 0, + width: _$constants_118.handleWidth, + rx: _$constants_118.handleRadius, + fill: _$color_43.background, + stroke: _$color_43.defaultLine, + 'stroke-width': _$constants_118.handleStrokeWidth, + 'shape-rendering': 'crispEdges' + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2), + }; + var handleMin = _$lib_164.ensureSingle(grabberMin, 'rect', _$constants_118.handleMinClassName, function(s) { + s.attr(handleFixAttrs); }); + handleMin.attr(handleDynamicAttrs); - header.on('click', function() { - gButton.call(removeAllButtons); + var handleMax = _$lib_164.ensureSingle(grabberMax, 'rect', _$constants_118.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); + // + if(gd._context.staticPlot) return; - // if this menu is active, fold the dropdown container - // otherwise, make this menu active - gButton.attr( - _$constants_138.menuIndexAttrName, - __isActive_140(gButton, menuOpts) ? - -1 : - String(menuOpts._index) - ); + var grabAreaFixAttrs = { + width: _$constants_118.grabAreaWidth, + x: 0, + y: 0, + fill: _$constants_118.grabAreaFill, + cursor: _$constants_118.grabAreaCursor + }; - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + var grabAreaMin = _$lib_164.ensureSingle(grabberMin, 'rect', _$constants_118.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); }); + grabAreaMin.attr('height', opts._height); - header.on('mouseover', function() { - header.call(styleOnMouseOver); + var grabAreaMax = _$lib_164.ensureSingle(grabberMax, 'rect', _$constants_118.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); }); + grabAreaMax.attr('height', opts._height); +} - header.on('mouseout', function() { - header.call(styleOnMouseOut, menuOpts); - }); +function clearPushMargins(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); - // translate header group - _$drawing_68.setTranslate(gHeader, dims.lx, dims.ly); -} + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - // If this is a set of buttons, set pointer events = all since we play - // some minor games with which container is which in order to simplify - // the drawing of *either* buttons or menus - if(!gButton) { - gButton = gHeader; - gButton.attr('pointer-events', 'all'); + if(k.indexOf(_$constants_118.name) !== -1) { + _$plots_245.autoMargin(gd, k); + } } +} - var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? - menuOpts.buttons : - []; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 klass = menuOpts.type === 'dropdown' ? _$constants_138.dropdownButtonClassName : _$constants_138.buttonClassName; +'use strict'; - var buttons = gButton.selectAll('g.' + klass) - .data(buttonData); +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$attributes_116 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_122 = require('./oppaxis_attributes'); */; - var enter = buttons.enter().append('g') - .classed(klass, true); +var _$rangeslider_121 = { + moduleType: 'component', + name: 'rangeslider', - var exit = buttons.exit(); + schema: { + subplots: { + xaxis: { + rangeslider: _$lib_164.extendFlat({}, _$attributes_116, { + yaxis: _$oppaxis_attributes_122 + }) + } + } + }, - if(menuOpts.type === 'dropdown') { - enter.attr('opacity', '0') - .transition() - .attr('opacity', '1'); + layoutAttributes: _$attributes_116, + handleDefaults: _$handleDefaults_119, + calcAutorange: _$calcAutorange_117, + draw: _$draw_120 +}; - exit.transition() - .attr('opacity', '0') - .remove(); - } else { - exit.remove(); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; +'use strict'; - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +/* removed: var _$attributes_28 = require('../annotations/attributes'); */; +var scatterLineAttrs = _$attributes_266.line; +var __dash_123 = _$attributes_67.dash; +var __extendFlat_123 = _$extend_157.extendFlat; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - y0 = dims.headerHeight + _$constants_138.gapButtonHeader; - } else { - x0 = dims.headerWidth + _$constants_138.gapButtonHeader; - } - } +var _$attributes_123 = { + _isLinkedToArray: 'shape', - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openHeight; - } + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calcIfAutorange+arraydraw', + + }, - if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openWidth; - } + type: { + valType: 'enumerated', + values: ['circle', 'rect', 'path', 'line'], + + editType: 'calcIfAutorange+arraydraw', + + }, - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_138.gapButton, - xPad: _$constants_138.gapButton, - index: 0, - }; + layer: { + valType: 'enumerated', + values: ['below', 'above'], + dflt: 'above', + + editType: 'arraydraw', + + }, - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; + xref: __extendFlat_123({}, _$attributes_28.xref, { + + }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + x1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, - buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_6.select(this); + yref: __extendFlat_123({}, _$attributes_28.yref, { + + }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y0: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, + y1: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, - button - .call(drawItem, menuOpts, buttonOpts, gd) - .call(setItemPosition, menuOpts, posOpts); + path: { + valType: 'string', + + editType: 'calcIfAutorange+arraydraw', + + }, - button.on('click', function() { - // skip `dragend` events - if(_$d3_6.event.defaultPrevented) return; + opacity: { + valType: 'number', + min: 0, + max: 1, + dflt: 1, + + editType: 'arraydraw', + + }, + line: { + color: __extendFlat_123({}, scatterLineAttrs.color, {editType: 'arraydraw'}), + width: __extendFlat_123({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_123({}, __dash_123, {editType: 'arraydraw'}), + + editType: 'calcIfAutorange+arraydraw' + }, + fillcolor: { + valType: 'color', + dflt: 'rgba(0,0,0,0)', + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; - __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(buttonOpts.execute) { - _$plots_245.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); - } - gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); - }); +'use strict'; - button.on('mouseover', function() { - button.call(styleOnMouseOver); - }); - button.on('mouseout', function() { - button.call(styleOnMouseOut, menuOpts); - buttons.call(styleButtons, menuOpts); - }); - }); +var _$constants_125 = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, - buttons.call(styleButtons, menuOpts); + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: {0: true, drawn: 0}, + L: {0: true, drawn: 0}, + H: {0: true, drawn: 0}, + V: {}, + Q: {0: true, 2: true, drawn: 2}, + C: {0: true, 2: true, 4: true, drawn: 4}, + T: {0: true, drawn: 0}, + S: {0: true, 2: true, drawn: 2}, + // A: {0: true, 5: true}, + Z: {} + }, - if(isVertical) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } - else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + paramIsY: { + M: {1: true, drawn: 1}, + L: {1: true, drawn: 1}, + H: {}, + V: {0: true, drawn: 0}, + Q: {1: true, 3: true, drawn: 3}, + C: {1: true, 3: true, 5: true, drawn: 5}, + T: {1: true, drawn: 1}, + S: {1: true, 3: true, drawn: 5}, + // A: {1: true, 6: true}, + Z: {} + }, + + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 } +}; - scrollBoxPosition.direction = menuOpts.direction; +var _$helpers_128 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(scrollBox) { - if(buttons.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } - else { - hideScrollBox(scrollBox); - } - } -} -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - // enable the scrollbox - var direction = menuOpts.direction; - var isVertical = (direction === 'up' || direction === 'down'); - var dims = menuOpts._dims; +'use strict'; - var active = menuOpts.active, - translateX, translateY, - i; - if(isVertical) { - translateY = 0; - for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_138.gapButton; - } +// special position conversion functions... category axis positions can't be +// specified by their data values, because they don't make a continuous mapping. +// so these have to be specified in terms of the category serial numbers, +// but can take fractional values. Other axis types we specify position based on +// the actual data values. +// TODO: in V2.0 (when log axis ranges are in data units) range and shape position +// will be identical, so rangeToShapePosition and shapePositionToRange can be +// removed entirely. + +_$helpers_128.rangeToShapePosition = function(ax) { + return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; +}; + +_$helpers_128.shapePositionToRange = function(ax) { + return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; +}; + +_$helpers_128.decodeDate = function(convertToPx) { + return function(v) { + if(v.replace) v = v.replace('_', ' '); + return convertToPx(v); + }; +}; + +_$helpers_128.encodeDate = function(convertToDate) { + return function(v) { return convertToDate(v).replace(' ', '_'); }; +}; + +_$helpers_128.getDataToPixel = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + dataToPixel; + + if(axis) { + var d2r = _$helpers_128.shapePositionToRange(axis); + + dataToPixel = function(v) { + return axis._offset + axis.r2p(d2r(v, true)); + }; + + if(axis.type === 'date') dataToPixel = _$helpers_128.decodeDate(dataToPixel); + } + else if(isVertical) { + dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; } else { - translateX = 0; - for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_138.gapButton; - } + dataToPixel = function(v) { return gs.l + gs.w * v; }; } - scrollBox.enable(position, translateX, translateY); + return dataToPixel; +}; - if(scrollBox.hbar) { - scrollBox.hbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); - } +_$helpers_128.getPixelToData = function(gd, axis, isVertical) { + var gs = gd._fullLayout._size, + pixelToData; - if(scrollBox.vbar) { - scrollBox.vbar - .attr('opacity', '0') - .transition() - .attr('opacity', '1'); + if(axis) { + var r2d = _$helpers_128.rangeToShapePosition(axis); + pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; + } + else if(isVertical) { + pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; }; + } + else { + pixelToData = function(p) { return (p - gs.l) / gs.w; }; } -} -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar, - hasVBar = !!scrollBox.vbar; + return pixelToData; +}; - if(hasHBar) { - scrollBox.hbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasHBar = false; - if(!hasVBar) scrollBox.disable(); - }); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(hasVBar) { - scrollBox.vbar - .transition() - .attr('opacity', '0') - .each('end', function() { - hasVBar = false; - if(!hasHBar) scrollBox.disable(); - }); - } -} -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts) - .call(drawItemText, menuOpts, itemOpts, gd); -} +'use strict'; -function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; - rect.enter().append('rect') - .classed(_$constants_138.itemRectClassName, true) - .attr({ - rx: _$constants_138.rx, - ry: _$constants_138.ry, - 'shape-rendering': 'crispEdges' - }); +/* removed: var _$constants_125 = require('./constants'); */; +/* removed: var _$helpers_128 = require('./helpers'); */; - rect.call(_$color_43.stroke, menuOpts.bordercolor) - .call(_$color_43.fill, menuOpts.bgcolor) - .style('stroke-width', menuOpts.borderwidth + 'px'); -} -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); +var _$calcAutorange_124 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout, + shapeList = _$lib_164.filterVisible(fullLayout.shapes); - text.enter().append('text') - .classed(_$constants_138.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + if(!shapeList.length || !gd._fullData.length) return; - text.call(_$drawing_68.font, menuOpts.font) - .text(itemOpts.label) - .call(_$svg_text_utils_184.convertToTspans, gd); -} + for(var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; -function styleButtons(buttons, menuOpts) { - var active = menuOpts.active; + var ax, bounds; - buttons.each(function(buttonOpts, i) { - var button = _$d3_6.select(this); + if(shape.xref !== 'paper') { + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_206.getFromId(gd, shape.xref); - if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_138.itemRectClassName) - .call(_$color_43.fill, _$constants_138.activeColor); + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_125.paramIsX); + + if(bounds) _$axes_206.expand(ax, bounds, calcXPaddingOptions(shape)); } - }); -} -function styleOnMouseOver(item) { - item.select('rect.' + _$constants_138.itemRectClassName) - .call(_$color_43.fill, _$constants_138.hoverColor); + if(shape.yref !== 'paper') { + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_206.getFromId(gd, shape.yref); + + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_125.paramIsY); + if(bounds) _$axes_206.expand(ax, bounds, calcYPaddingOptions(shape)); + } + } +}; + +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); } -function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_138.itemRectClassName) - .call(_$color_43.fill, menuOpts.bgcolor); +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); } -// find item dimensions (this mutates menuOpts) -function __findDimensions_140(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; - var fakeButtons = _$drawing_68.tester.selectAll('g.' + _$constants_138.dropdownButtonClassName) - .data(menuOpts.buttons); + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_125.paramIsY : _$constants_125.paramIsX) : + [v0, v1]; + var maxValue = _$lib_164.aggNums(Math.max, null, coords), + minValue = _$lib_164.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; - fakeButtons.enter().append('g') - .classed(_$constants_138.dropdownButtonClassName, true); + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; - // loop over fake buttons to find width / height - fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_6.select(this); + var segments = path.match(_$constants_125.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; - button.call(drawItem, menuOpts, buttonOpts, gd); + var params = segment.substr(1).match(_$constants_125.paramRE); + if(!params || params.length < relevantParamIdx) return; - var text = button.select('.' + _$constants_138.itemTextClassName); + extractedCoordinates.push(params[relevantParamIdx]); + }); - // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_68.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_138.textPadX, _$constants_138.minWidth); + return extractedCoordinates; +} - // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_140; - var tLines = _$svg_text_utils_184.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_138.minHeight) + _$constants_138.textOffsetY; +function shapeBounds(ax, v0, v1, path, paramsToUse) { + var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); + if(v0 !== undefined) return [convertVal(v0), convertVal(v1)]; + if(!path) return; - // Store per-item sizes since a row of horizontal buttons, for example, - // don't all need to be the same width: - dims.widths[i] = wEff; - dims.heights[i] = hEff; + var min = Infinity, + max = -Infinity, + segments = path.match(_$constants_125.segmentRE), + i, + segment, + drawnParam, + params, + val; - // Height and width of individual element: - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); + if(ax.type === 'date') convertVal = _$helpers_128.decodeDate(convertVal); - if(isVertical) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_138.gapButton; - dims.openHeight += hEff + _$constants_138.gapButton; - } else { - dims.totalWidth += wEff + _$constants_138.gapButton; - dims.openWidth += wEff + _$constants_138.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; - } - }); + for(i = 0; i < segments.length; i++) { + segment = segments[i]; + drawnParam = paramsToUse[segment.charAt(0)].drawn; + if(drawnParam === undefined) continue; - if(isVertical) { - dims.totalHeight -= _$constants_138.gapButton; - } else { - dims.totalWidth -= _$constants_138.gapButton; + params = segments[i].substr(1).match(_$constants_125.paramRE); + if(!params || params.length < drawnParam) continue; + + val = convertVal(params[drawnParam]); + if(val < min) min = val; + if(val > max) max = val; } + if(max >= min) return [min, max]; +} +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - dims.headerWidth = dims.width1 + _$constants_138.arrowPadX; - dims.headerHeight = dims.height1; - if(menuOpts.type === 'dropdown') { - if(isVertical) { - dims.width1 += _$constants_138.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += _$constants_138.arrowPadX; - } +'use strict'; - fakeButtons.remove(); +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; +/* removed: var _$attributes_123 = require('./attributes'); */; +/* removed: var _$helpers_128 = require('./helpers'); */; - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - var xanchor = 'left'; - if(_$anchor_utils_95.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = 'right'; - } - if(_$anchor_utils_95.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = 'center'; - } +var _$handleShapeDefaults_130 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { + opts = opts || {}; + itemOpts = itemOpts || {}; - var yanchor = 'top'; - if(_$anchor_utils_95.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = 'bottom'; - } - if(_$anchor_utils_95.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = 'middle'; + function coerce(attr, dflt) { + return _$lib_164.coerce(shapeIn, shapeOut, _$attributes_123, attr, dflt); } - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); + var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); - _$plots_245.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index, { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), - r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), - b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), - t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) - }); -} + if(!visible) return shapeOut; -// set item positions (mutates posOpts) -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_138.itemRectClassName); - var text = item.select('.' + _$constants_138.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index = posOpts.index; - var dims = menuOpts._dims; + coerce('layer'); + coerce('opacity'); + coerce('fillcolor'); + coerce('line.color'); + coerce('line.width'); + coerce('line.dash'); - _$drawing_68.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + var dfltType = shapeIn.path ? 'path' : 'rect', + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); - var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); + // positioning + var axLetters = ['x', 'y']; + for(var i = 0; i < 2; i++) { + var axLetter = axLetters[i], + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; - rect.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), - height: finalHeight - }); + // xref, yref + var axRef = _$axes_206.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); - var tHeight = menuOpts.font.size * __LINE_SPACING_140; - var tLines = _$svg_text_utils_184.lineCount(text); - var spanOffset = ((tLines - 1) * tHeight / 2); + if(axRef !== 'paper') { + ax = _$axes_206.getFromId(gdMock, axRef); + r2pos = _$helpers_128.rangeToShapePosition(ax); + pos2r = _$helpers_128.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_164.identity; + } - _$svg_text_utils_184.positionText(text, _$constants_138.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_138.textOffsetY); + // Coerce x0, x1, y0, y1 + if(shapeType !== 'path') { + var dflt0 = 0.25, + dflt1 = 0.75; - if(isVertical) { - posOpts.y += dims.heights[index] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index] + posOpts.xPad; - } + // 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', + attr1 = axLetter + '1', + in0 = shapeIn[attr0], + in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); - posOpts.index++; -} + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_206.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_206.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } -function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_138.dropdownButtonClassName).remove(); -} + // hack part 2 + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } -function __clearPushMargins_140(gd) { - var pushMargins = gd._fullLayout._pushmargin || {}; - var keys = Object.keys(pushMargins); + // Coerce xanchor and yanchor + if(sizeMode === 'pixel') { + // Hack for log axis described above + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); - for(var i = 0; i < keys.length; i++) { - var k = keys[i]; + _$axes_206.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25); - if(k.indexOf(_$constants_138.autoMarginIdRoot) !== -1) { - _$plots_245.autoMargin(gd, k); + // Hack part 2 + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; } } -} + + if(shapeType === 'path') { + coerce('path'); + } + else { + _$lib_164.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + } + + return shapeOut; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -45656,21 +46706,22 @@ function __clearPushMargins_140(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$constants_138 = require('./constants'); */; +/* removed: var _$handleArrayContainerDefaults_202 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_130 = require('./shape_defaults'); */; -var _$updatemenus_141 = { - moduleType: 'component', - name: _$constants_138.name, - layoutAttributes: _$attributes_137, - supplyLayoutDefaults: _$updateMenusDefaults_139, +var _$supplyLayoutDefaults_126 = function supplyLayoutDefaults(layoutIn, layoutOut) { + var opts = { + name: 'shapes', + handleItemDefaults: _$handleShapeDefaults_130 + }; - draw: _$draw_140 + _$handleArrayContainerDefaults_202(layoutIn, layoutOut, opts); }; -var _$mathjax_config_149 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45679,239 +46730,459 @@ var _$mathjax_config_149 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* global MathJax:false */ +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; -/** - * Check and configure MathJax - */ -if(typeof MathJax !== 'undefined') { - _$mathjax_config_149.MathJax = true; +/* removed: var _$dragelement_65 = require('../dragelement'); */; +/* removed: var _$setCursor_183 = require('../../lib/setcursor'); */; - MathJax.Hub.Config({ - messageStyle: 'none', - skipStartupTypeset: true, - displayAlign: 'left', - tex2jax: { - inlineMath: [['$', '$'], ['\\(', '\\)']] - } - }); +/* removed: var _$constants_125 = require('./constants'); */; +/* removed: var _$helpers_128 = require('./helpers'); */; - MathJax.Hub.Configured(); -} else { - _$mathjax_config_149.MathJax = false; -} -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// Shapes are stored in gd.layout.shapes, an array of objects +// index can point to one item in this array, +// or non-numeric to simply add a new one +// or -1 to modify all existing +// opt can be the full options object, or one key (to be set to value) +// or undefined to simply redraw +// if opt is blank, val can be 'add' or a full options object to add a new +// annotation at that point in the array, or 'remove' to delete this one + +var _$draw_127 = { + draw: __draw_127, + drawOne: __drawOne_127 +}; +function __draw_127(gd) { + var fullLayout = gd._fullLayout; -'use strict'; + // Remove previous shapes before drawing new in shapes in fullLayout.shapes + fullLayout._shapeUpperLayer.selectAll('path').remove(); + fullLayout._shapeLowerLayer.selectAll('path').remove(); -/* removed: var _$lib_163 = require('../lib'); */; -/* removed: var _$plot_config_195 = require('../plot_api/plot_config'); */; + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); + } + for(var i = 0; i < fullLayout.shapes.length; i++) { + if(fullLayout.shapes[i].visible) { + __drawOne_127(gd, i); + } + } -/** - * Copy arg array *without* removing `undefined` values from objects. - * - * @param gd - * @param args - * @returns {Array} - */ -function copyArgArray(gd, args) { - var copy = []; - var arg; + // may need to resurrect this if we put text (LaTeX) in shapes + // return Plots.previousPromises(gd); +} - for(var i = 0; i < args.length; i++) { - arg = args[i]; +function __drawOne_127(gd, index) { + // remove the existing shape if there is one. + // because indices can change, we need to look in all shape layers + gd._fullLayout._paperdiv + .selectAll('.shapelayer [data-index="' + index + '"]') + .remove(); - if(arg === gd) copy[i] = arg; - else if(typeof arg === 'object') { - copy[i] = Array.isArray(arg) ? - _$lib_163.extendDeep([], arg) : - _$lib_163.extendDeepAll({}, arg); + var optionsIn = (gd.layout.shapes || [])[index], + options = gd._fullLayout.shapes[index]; + + // this shape is gone - quit now after deleting it + // TODO: use d3 idioms instead of deleting and redrawing every time + if(!optionsIn || options.visible === false) return; + + if(options.layer !== 'below') { + drawShape(gd._fullLayout._shapeUpperLayer); + } + else if(options.xref === 'paper' || options.yref === 'paper') { + drawShape(gd._fullLayout._shapeLowerLayer); + } + else { + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + if(plotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } + else { + // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist. + // This can happen if you reference the shape to an x / y axis combination + // that doesn't have any data on it (and layer is below) + drawShape(gd._fullLayout._shapeLowerLayer); } - else copy[i] = arg; } - return copy; + function drawShape(shapeLayer) { + var attrs = { + 'data-index': index, + 'fill-rule': 'evenodd', + d: getPathString(gd, options) + }, + lineColor = options.line.width ? + options.line.color : 'rgba(0,0,0,0)'; + + var path = shapeLayer.append('path') + .attr(attrs) + .style('opacity', options.opacity) + .call(_$color_43.stroke, lineColor) + .call(_$color_43.fill, options.fillcolor) + .call(_$drawing_68.dashLine, options.line.dash, options.line.width); + + // note that for layer="below" the clipAxes can be different from the + // subplot we're drawing this in. This could cause problems if the shape + // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 + var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); + + path.call(_$drawing_68.setClipUrl, clipAxes ? + ('clip' + gd._fullLayout._uid + clipAxes) : + null + ); + + if(gd._context.edits.shapePosition) __setupDragElement_127(gd, path, options, index); + } } +function __setupDragElement_127(gd, shapePath, shapeOptions, index) { + var MINWIDTH = 10, + MINHEIGHT = 10; + + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; -// ----------------------------------------------------- -// Undo/Redo queue for plots -// ----------------------------------------------------- + var update; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; + var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; + var pathIn, astrPath; + var xa, ya, x2p, y2p, p2x, p2y; -var __queue_177 = {}; + var dragOptions = { + element: shapePath.node(), + gd: gd, + prepFn: startDrag, + doneFn: endDrag + }, + dragMode; -// TODO: disable/enable undo and redo buttons appropriately + _$dragelement_65.init(dragOptions); -/** - * Add an item to the undoQueue for a graphDiv - * - * @param gd - * @param undoFunc Function undo this operation - * @param undoArgs Args to supply undoFunc with - * @param redoFunc Function to redo this operation - * @param redoArgs Args to supply redoFunc with - */ -__queue_177.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, - queueIndex; + shapePath.node().onmousemove = updateDragMode; - // make sure we have the queue and our position in it - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - queueIndex = gd.undoQueue.index; + function updateDragMode(evt) { + // element might not be on screen at time of setup, + // so obtain bounding box here + var dragBBox = dragOptions.element.getBoundingClientRect(); - // if we're already playing an undo or redo, or if this is an auto operation - // (like pane resize... any others?) then we don't save this to the undo queue - if(gd.autoplay) { - if(!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } + // choose 'move' or 'resize' + // based on initial position of cursor within the drag element + var w = dragBBox.right - dragBBox.left, + h = dragBBox.bottom - dragBBox.top, + x = evt.clientX - dragBBox.left, + y = evt.clientY - dragBBox.top, + cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? + _$dragelement_65.getCursor(x / w, 1 - y / h) : + 'move'; - // if we're not in a sequence or are just starting, we need a new queue item - if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; + _$setCursor_183(shapePath, cursor); + + // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' + dragMode = cursor.split('-')[0]; } - gd.undoQueue.beginSequence = false; - // we unshift to handle calls for undo in a forward for loop later - if(queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); + function startDrag(evt) { + // setup conversion functions + xa = _$axes_206.getFromId(gd, shapeOptions.xref); + ya = _$axes_206.getFromId(gd, shapeOptions.yref); + + x2p = _$helpers_128.getDataToPixel(gd, xa); + y2p = _$helpers_128.getDataToPixel(gd, ya, true); + p2x = _$helpers_128.getPixelToData(gd, xa); + p2y = _$helpers_128.getPixelToData(gd, ya, true); + + // setup update strings and initial values + var astr = 'shapes[' + index + ']'; + + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } + + if(shapeOptions.type === 'path') { + pathIn = shapeOptions.path; + astrPath = astr + '.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); + + astrX0 = astr + '.x0'; + astrY0 = astr + '.y0'; + astrX1 = astr + '.x1'; + astrY1 = astr + '.y1'; + } + + if(x0 < x1) { + w0 = x0; astrW = astr + '.x0'; optW = 'x0'; + e0 = x1; astrE = astr + '.x1'; optE = 'x1'; + } + else { + w0 = x1; astrW = astr + '.x1'; optW = 'x1'; + e0 = x0; astrE = astr + '.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; astrN = astr + '.y0'; optN = 'y0'; + s0 = y1; astrS = astr + '.y1'; optS = 'y1'; + } + else { + n0 = y1; astrN = astr + '.y1'; optN = 'y1'; + s0 = y0; astrS = astr + '.y0'; optS = 'y0'; + } + + update = {}; + + // setup dragMode and the corresponding handler + updateDragMode(evt); + dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape; } - if(gd.undoQueue.queue.length > _$plot_config_195.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; + function endDrag() { + _$setCursor_183(shapePath); + _$registry_254.call('relayout', gd, update); } -}; -/** - * Begin a sequence of undoQueue changes - * - * @param gd - */ -__queue_177.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; + function moveShape(dx, dy) { + if(shapeOptions.type === 'path') { + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; -/** - * Stop a sequence of undoQueue changes - * - * Call this *after* you're sure your undo chain has ended - * - * @param gd - */ -__queue_177.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; -}; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); + } -/** - * Move one step back in the undo queue, and undo the object there. - * - * @param gd - */ -__queue_177.undo = function undo(gd) { - var queueObj, i; + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + } - if(gd.framework && gd.framework.isPolar) { - gd.framework.undo(); - return; - } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index <= 0) { - return; + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - // index is pointing to next *forward* queueObj, point to the one we're undoing - gd.undoQueue.index--; + function resizeShape(dx, dy) { + if(shapeOptions.type === 'path') { + // TODO: implement path resize + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_128.encodeDate(moveX); + } - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_177.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_128.encodeDate(moveY); + } + + shapeOptions.path = movePath(pathIn, moveX, moveY); + update[astrPath] = shapeOptions.path; + } + else { + var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0, + newS = (~dragMode.indexOf('s')) ? s0 + dy : s0, + newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, + 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } + if(newE - newW > MINWIDTH) { + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); + } + } + + shapePath.attr('d', getPathString(gd, shapeOptions)); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; +} -/** - * Redo the current object in the undo, then move forward in the queue. - * - * @param gd - */ -__queue_177.redo = function redo(gd) { - var queueObj, i; +function getPathString(gd, options) { + var type = options.type, + xa = _$axes_206.getFromId(gd, options.xref), + ya = _$axes_206.getFromId(gd, options.yref), + gs = gd._fullLayout._size, + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; - if(gd.framework && gd.framework.isPolar) { - gd.framework.redo(); - return; + if(xa) { + x2r = _$helpers_128.shapePositionToRange(xa); + x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; } - if(gd.undoQueue === undefined || - isNaN(gd.undoQueue.index) || - gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; + else { + x2p = function(v) { return gs.l + gs.w * v; }; } - // get the queueObj for instructions on how to undo - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + if(ya) { + y2r = _$helpers_128.shapePositionToRange(ya); + y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; + } + else { + y2p = function(v) { return gs.t + gs.h * (1 - v); }; + } - // this sequence keeps things from adding to the queue during undo/redo - gd.undoQueue.inSequence = true; - for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_177.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + if(type === 'path') { + if(xa && xa.type === 'date') x2p = _$helpers_128.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_128.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - gd.undoQueue.inSequence = false; - gd.autoplay = false; - // index is pointing to the thing we just redid, move it - gd.undoQueue.index++; -}; + 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); + } -/** - * Called by undo/redo to make the actual changes. - * - * Not meant to be called publically, but included for mocking out in tests. - * - * @param gd - * @param func - * @param args - */ -__queue_177.plotDo = function(gd, func, args) { - gd.autoplay = true; + 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); + } - // this *won't* copy gd and it preserves `undefined` properties! - args = copyArgArray(gd, args); + 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, + cy = (y0 + y1) / 2, + rx = Math.abs(cx - x0), + ry = Math.abs(cy - y0), + rArc = 'A' + rx + ',' + ry, + rightPt = (cx + rx) + ',' + cy, + topPt = cx + ',' + (cy - ry); + return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt + + rArc + ' 0 0,1 ' + rightPt + 'Z'; +} - // call the supplied function - func.apply(null, args); -}; -var _$queue_177 = __queue_177; +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; + + + return pathIn.replace(_$constants_125.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_125.paramIsX[segmentType], + yParams = _$constants_125.paramIsY[segmentType], + nParams = _$constants_125.numParams[segmentType]; + + var paramString = segment.substr(1).replace(_$constants_125.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_164.log('Ignoring extra params in segment ' + segment); + } + + return segmentType + paramString; + }); +} + +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(_$constants_125.segmentRE, function(segment) { + var paramNumber = 0, + segmentType = segment.charAt(0), + xParams = _$constants_125.paramIsX[segmentType], + yParams = _$constants_125.paramIsY[segmentType], + nParams = _$constants_125.numParams[segmentType]; + + var paramString = segment.substr(1).replace(_$constants_125.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; + }); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -45921,17 +47192,22 @@ var _$queue_177 = __queue_177; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$localeEnUs_187 = { - moduleType: 'locale', - name: 'en-US', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colorscale title' - }, - format: { - date: '%m/%d/%Y' - } +/* removed: var _$draw_127 = require('./draw'); */; + +var _$shapes_129 = { + moduleType: 'component', + name: 'shapes', + + layoutAttributes: _$attributes_123, + supplyLayoutDefaults: _$supplyLayoutDefaults_126, + includeBasePlot: _$makeIncludeComponents_216('shapes'), + + calcAutorange: _$calcAutorange_124, + draw: _$draw_127.draw, + drawOne: _$draw_127.drawOne }; /** @@ -45942,88 +47218,91 @@ var _$localeEnUs_187 = { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -var _$localeEn_188 = { - moduleType: 'locale', - name: 'en', - dictionary: { - 'Click to enter Colorscale title': 'Click to enter Colourscale title' - }, - format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - 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' - } -}; -var _$fromQuat_10 = fromQuat; +var _$constants_132 = { -/** - * 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, + // layout attribute name + name: 'sliders', - 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; + // class names + containerClassName: 'slider-container', + groupClassName: 'slider-group', + inputAreaClass: 'slider-input-area', + railRectClass: 'slider-rail-rect', + railTouchRectClass: 'slider-rail-touch-rect', + gripRectClass: 'slider-grip-rect', + tickRectClass: 'slider-tick-rect', + inputProxyClass: 'slider-input-proxy', + labelsClass: 'slider-labels', + labelGroupClass: 'slider-label-group', + labelClass: 'slider-label', + currentValueClass: 'slider-current-value', - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; + railHeight: 5, - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'slider-active-index', - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'slider-', - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + // min item width / height + minWidth: 30, + minHeight: 30, - return out; + // padding around item text + textPadX: 40, + + // arrow offset off right edge + arrowOffsetX: 4, + + railRadius: 2, + railWidth: 5, + railBorder: 4, + railBorderWidth: 1, + railBorderColor: '#bec8d9', + railBgColor: '#f8fafc', + + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, + + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, + + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBorder: 20, + gripBorderWidth: 1, + gripBorderColor: '#bec8d9', + gripBgColor: '#f6f8fa', + gripBgActiveColor: '#dbdde0', + + labelPadding: 8, + labelOffset: 0, + + tickWidth: 1, + tickColor: '#333', + tickOffset: 25, + tickLength: 7, + + minorTickOffset: 25, + minorTickColor: '#333', + minorTickLength: 4, + + // Extra space below the current value label: + currentValuePadding: 8, + currentValueInset: 0, }; -var _$helpers_191 = {}; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -46032,1390 +47311,1004 @@ var _$helpers_191 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_10 = require('gl-mat4/fromQuat'); */; - -/* removed: var _$registry_253 = require('../registry'); */; -/* removed: var _$lib_163 = require('../lib'); */; -/* removed: var _$plots_245 = require('../plots/plots'); */; -/* removed: var _$axis_ids_208 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_208.cleanId; -var getFromTrace = _$axis_ids_208.getFromTrace; -/* removed: var _$color_43 = require('../components/color'); */; - +// This is used exclusively by components inside component arrays, +// hence the 'arraydraw' editType. If this ever gets used elsewhere +// we could generalize it as a function ala font_attributes +var _$pad_attributes_244 = { + t: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + r: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + b: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + l: { + valType: 'number', + dflt: 0, + + editType: 'arraydraw', + + }, + editType: 'arraydraw' +}; -// clear the promise queue if one of them got rejected -_$helpers_191.clearPromiseQueue = function(gd) { - if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_163.log('Clearing previous rejected promises from queue.'); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - gd._promises = []; -}; +'use strict'; -// make a few changes to the layout right away -// before it gets used for anything -// backward compatibility and cleanup of nonstandard options -_$helpers_191.cleanLayout = function(layout) { - var i, j; +/* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_244 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_131 = _$extend_157.extendDeepAll; +var __overrideAll_131 = _$edit_types_191.overrideAll; +/* removed: var _$animation_attributes_201 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_132 = require('./constants'); */; - if(!layout) layout = {}; +var stepsAttrs = { + _isLinkedToArray: 'step', - // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... - if(layout.xaxis1) { - if(!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if(layout.yaxis1) { - if(!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; - } - if(layout.scene1) { - if(!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + { valType: 'any' }, + { valType: 'any' }, + { valType: 'any' } + ], + + }, + label: { + valType: 'string', + + + }, + value: { + valType: 'string', + + + }, + execute: { + valType: 'boolean', + + dflt: true, + } +}; - var axisAttrRegex = (_$plots_245.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_245.subplotsRegistry.gl3d || {}).attrRegex; +var _$attributes_131 = __overrideAll_131({ + _isLinkedToArray: 'slider', - var keys = Object.keys(layout); - for(i = 0; i < keys.length; i++) { - var key = keys[i]; + visible: { + valType: 'boolean', + + dflt: true, + + }, - // modifications to cartesian axes - if(axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if(ax.anchor && ax.anchor !== 'free') { - ax.anchor = cleanId(ax.anchor); - } - if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + active: { + valType: 'number', + + min: 0, + dflt: 0, + + }, - // old method of axis type - isdate and islog (before category existed) - if(!ax.type) { - if(ax.isdate) ax.type = 'date'; - else if(ax.islog) ax.type = 'log'; - else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; - } - if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { - ax.autorange = true; - ax.rangemode = 'tozero'; - } - delete ax.islog; - delete ax.isdate; - delete ax.categories; // replaced by _categories + steps: stepsAttrs, - // prune empty domain arrays made before the new nestedProperty - if(emptyContainer(ax, 'domain')) delete ax.domain; + lenmode: { + valType: 'enumerated', + values: ['fraction', 'pixels'], + + dflt: 'fraction', + + }, + len: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + x: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + pad: __extendDeepAll_131({}, _$pad_attributes_244, { + + }, {t: {dflt: 20}}), + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'left', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 0, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, - // autotick -> tickmode - if(ax.autotick !== undefined) { - if(ax.tickmode === undefined) { - ax.tickmode = ax.autotick ? 'auto' : 'linear'; - } - delete ax.autotick; - } + transition: { + duration: { + valType: 'number', + + min: 0, + dflt: 150, + + }, + easing: { + valType: 'enumerated', + values: _$animation_attributes_201.transition.easing.values, + + dflt: 'cubic-in-out', + } + }, - // modifications for 3D scenes - else if(sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; - - // clean old Camera coords - var cameraposition = scene.cameraposition; - - if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0], - center = cameraposition[1], - radius = cameraposition[2], - mat = _$fromQuat_10([], rotation), - eye = []; + currentvalue: { + visible: { + valType: 'boolean', + + dflt: true, + + }, - for(j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } + xanchor: { + valType: 'enumerated', + values: ['left', 'center', 'right'], + dflt: 'left', + + + }, - scene.camera = { - eye: {x: eye[0], y: eye[1], z: eye[2]}, - center: {x: center[0], y: center[1], z: center[2]}, - up: {x: mat[1], y: mat[5], z: mat[9]} - }; + offset: { + valType: 'number', + dflt: 10, + + + }, - delete scene.cameraposition; - } - } - } + prefix: { + valType: 'string', + + + }, - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for(i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; + suffix: { + valType: 'string', + + + }, - if(!_$lib_163.isPlainObject(ann)) continue; + font: _$font_attributes_232({ + + }) + }, - if(ann.ref) { - if(ann.ref === 'paper') { - ann.xref = 'paper'; - ann.yref = 'paper'; - } - else if(ann.ref === 'data') { - ann.xref = 'x'; - ann.yref = 'y'; - } - delete ann.ref; - } + font: _$font_attributes_232({ + + }), - cleanAxRef(ann, 'xref'); - cleanAxRef(ann, 'yref'); + activebgcolor: { + valType: 'color', + + dflt: _$constants_132.gripBgActiveColor, + + }, + bgcolor: { + valType: 'color', + + dflt: _$constants_132.railBgColor, + + }, + bordercolor: { + valType: 'color', + dflt: _$constants_132.railBorderColor, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: _$constants_132.railBorderWidth, + + + }, + ticklen: { + valType: 'number', + min: 0, + dflt: _$constants_132.tickLength, + + + }, + tickcolor: { + valType: 'color', + dflt: _$constants_132.tickColor, + + + }, + tickwidth: { + valType: 'number', + min: 0, + dflt: 1, + + + }, + minorticklen: { + valType: 'number', + min: 0, + dflt: _$constants_132.minorTickLength, + + } +}, 'arraydraw', 'from-root'); - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for(i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!_$lib_163.isPlainObject(shape)) continue; +'use strict'; - cleanAxRef(shape, 'xref'); - cleanAxRef(shape, 'yref'); - } +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_202 = require('../../plots/array_container_defaults'); */; - var legend = layout.legend; - if(legend) { - // check for old-style legend positioning (x or y is +/- 100) - if(legend.x > 3) { - legend.x = 1.02; - legend.xanchor = 'left'; - } - else if(legend.x < -2) { - legend.x = -0.02; - legend.xanchor = 'right'; - } +/* removed: var _$attributes_131 = require('./attributes'); */; +/* removed: var _$constants_132 = require('./constants'); */; - if(legend.y > 3) { - legend.y = 1.02; - legend.yanchor = 'bottom'; - } - else if(legend.y < -2) { - legend.y = -0.02; - legend.yanchor = 'top'; - } - } +var __name_133 = _$constants_132.name; +var stepAttrs = _$attributes_131.steps; - /* - * Moved from rotate -> orbit for dragmode - */ - if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_43.clean(layout); +var _$slidersDefaults_133 = function slidersDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_133, + handleItemDefaults: sliderDefaults + }; - return layout; + _$handleArrayContainerDefaults_202(layoutIn, layoutOut, opts); }; -function cleanAxRef(container, attr) { - var valIn = container[attr], - axLetter = attr.charAt(0); - if(valIn && valIn !== 'paper') { - container[attr] = cleanId(valIn, axLetter); +function sliderDefaults(sliderIn, sliderOut, layoutOut) { + + function coerce(attr, dflt) { + return _$lib_164.coerce(sliderIn, sliderOut, _$attributes_131, attr, dflt); } -} -/* - * cleanData: Make a few changes to the data right away - * before it gets used for anything - * Mostly for backward compatibility, modifies the data traces users provide. - * - * Important: if you're going to add something here that modifies a data array, - * update it in place so the new array === the old one. - */ -_$helpers_191.cleanData = function(data, existingData) { - // Enforce unique IDs - var suids = [], // seen uids --- so we can weed out incoming repeats - uids = data.concat(Array.isArray(existingData) ? existingData : []) - .filter(function(trace) { return 'uid' in trace; }) - .map(function(trace) { return trace.uid; }); + var steps = stepsDefaults(sliderIn, sliderOut); - for(var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; + var visible = coerce('visible', steps.length > 0); + if(!visible) return; - // assign uids to each trace and detect collisions. - if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { - var newUid; + coerce('active'); - for(i = 0; i < 100; i++) { - newUid = _$lib_163.randstr(uids); - if(suids.indexOf(newUid) === -1) break; - } - trace.uid = _$lib_163.randstr(uids); - uids.push(trace.uid); - } - // keep track of already seen uids, so that if there are - // doubles we force the trace with a repeat uid to - // acquire a new one - suids.push(trace.uid); + coerce('x'); + coerce('y'); + _$lib_164.noneOrAll(sliderIn, sliderOut, ['x', 'y']); - // BACKWARD COMPATIBILITY FIXES + coerce('xanchor'); + coerce('yanchor'); - // use xbins to bin data in x, and ybins to bin data in y - if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } + coerce('len'); + coerce('lenmode'); - // error_y.opacity is obsolete - merge into color - if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_43.defaults, - yeColor = trace.error_y.color || - (_$registry_253.traceIs(trace, 'bar') ? _$color_43.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_43.addOpacity( - _$color_43.rgb(yeColor), - _$color_43.opacity(yeColor) * trace.error_y.opacity); - delete trace.error_y.opacity; - } + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); - // convert bardir to orientation, and put the data into - // the axes it's eventually going to be used with - if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_253.traceIs(trace, 'bar') || - trace.type.substr(0, 9) === 'histogram')) { - trace.orientation = 'h'; - _$helpers_191.swapXYData(trace); - } - delete trace.bardir; - } + _$lib_164.coerceFont(coerce, 'font', layoutOut.font); - // now we have only one 1D histogram type, and whether - // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_191.swapXYData(trace); - if(trace.type === 'histogramx' || trace.type === 'histogramy') { - trace.type = 'histogram'; - } + var currentValueIsVisible = coerce('currentvalue.visible'); - // scl->scale, reversescl->reversescale - if('scl' in trace) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if('reversescl' in trace) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } + if(currentValueIsVisible) { + coerce('currentvalue.xanchor'); + coerce('currentvalue.prefix'); + coerce('currentvalue.suffix'); + coerce('currentvalue.offset'); - // axis ids x1 -> x, y1-> y - if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); - if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + _$lib_164.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + } - // scene ids scene1 -> scene - if(_$registry_253.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_245.subplotsRegistry.gl3d.cleanId(trace.scene); - } + coerce('transition.duration'); + coerce('transition.easing'); - if(!_$registry_253.traceIs(trace, 'pie') && !_$registry_253.traceIs(trace, 'bar')) { - if(Array.isArray(trace.textposition)) { - for(i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } - else if(trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } + coerce('bgcolor'); + coerce('activebgcolor'); + coerce('bordercolor'); + coerce('borderwidth'); + coerce('ticklen'); + coerce('tickwidth'); + coerce('tickcolor'); + coerce('minorticklen'); +} - // fix typo in colorscale definition - if(_$registry_253.traceIs(trace, '2dMap')) { - if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; - if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; - } - if(_$registry_253.traceIs(trace, 'markerColorscale') && trace.marker) { - var cont = trace.marker; - if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; - if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; - } +function stepsDefaults(sliderIn, sliderOut) { + var valuesIn = sliderIn.steps || [], + valuesOut = sliderOut.steps = []; - // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_163.isPlainObject(trace.contours)) { - var dims = ['x', 'y', 'z']; + var valueIn, valueOut; - for(i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; + function coerce(attr, dflt) { + return _$lib_164.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + } - if(!_$lib_163.isPlainObject(opts)) continue; + for(var i = 0; i < valuesIn.length; i++) { + valueIn = valuesIn[i]; + valueOut = {}; - if(opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } + coerce('method'); - if(opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } + if(!_$lib_164.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + continue; } - // transforms backward compatibility fixes - if(Array.isArray(trace.transforms)) { - var transforms = trace.transforms; + coerce('args'); + coerce('label', 'step-' + i); + coerce('value', valueOut.label); + coerce('execute'); - for(i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + valuesOut.push(valueOut); + } - if(!_$lib_163.isPlainObject(transform)) continue; + return valuesOut; +} - switch(transform.type) { - case 'filter': - if(transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(transform.calendar) { - if(!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; +'use strict'; - case 'groupby': - // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: - transform.styles = transform.styles || transform.style; +/* removed: var _$d3_6 = require('d3'); */; - if(transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); +/* removed: var _$plots_245 = require('../../plots/plots'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; - transform.styles = []; - for(var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } - } +/* removed: var _$constants_132 = require('./constants'); */; +/* removed: var _$alignment_143 = require('../../constants/alignment'); */; +var __LINE_SPACING_134 = _$alignment_143.LINE_SPACING; +var __FROM_TL_134 = _$alignment_143.FROM_TL; +var __FROM_BR_134 = _$alignment_143.FROM_BR; - // prune empty containers made before the new nestedProperty - if(emptyContainer(trace, 'line')) delete trace.line; - if('marker' in trace) { - if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; - if(emptyContainer(trace, 'marker')) delete trace.marker; - } +var _$draw_134 = function draw(gd) { + var fullLayout = gd._fullLayout, + sliderData = makeSliderData(fullLayout, gd); - // sanitize rgb(fractions) and rgba(fractions) that old tinycolor - // supported, but new tinycolor does not because they're not valid css - _$color_43.clean(trace); - } -}; + // draw a container for *all* sliders: + var sliders = fullLayout._infolayer + .selectAll('g.' + _$constants_132.containerClassName) + .data(sliderData.length > 0 ? [0] : []); -// textposition - support partial attributes (ie just 'top') -// and incorrect use of middle / center etc. -function cleanTextPosition(textposition) { - var posY = 'middle', - posX = 'center'; - if(textposition.indexOf('top') !== -1) posY = 'top'; - else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; + sliders.enter().append('g') + .classed(_$constants_132.containerClassName, true) + .style('cursor', 'ew-resize'); - if(textposition.indexOf('left') !== -1) posX = 'left'; - else if(textposition.indexOf('right') !== -1) posX = 'right'; + sliders.exit().remove(); - return posY + ' ' + posX; -} + // If no more sliders, clear the margisn: + if(sliders.exit().size()) __clearPushMargins_134(gd); -function emptyContainer(outer, innerStr) { - return (innerStr in outer) && - (typeof outer[innerStr] === 'object') && - (Object.keys(outer[innerStr]).length === 0); -} + // Return early if no menus visible: + if(sliderData.length === 0) return; + var sliderGroups = sliders.selectAll('g.' + _$constants_132.groupClassName) + .data(sliderData, keyFunction); -// swap all the data and data attributes associated with x and y -_$helpers_191.swapXYData = function(trace) { - var i; - _$lib_163.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); - if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if(trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if(trace.error_x && trace.error_y) { - var errorY = trace.error_y, - copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : - !(errorY.color || errorY.thickness || errorY.width); - _$lib_163.swapAttrs(trace, ['error_?.copy_ystyle']); - if(copyYstyle) { - _$lib_163.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); - } - } - if(typeof trace.hoverinfo === 'string') { - var hoverInfoParts = trace.hoverinfo.split('+'); - for(i = 0; i < hoverInfoParts.length; i++) { - if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; - else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; - } - trace.hoverinfo = hoverInfoParts.join('+'); - } -}; + sliderGroups.enter().append('g') + .classed(_$constants_132.groupClassName, true); -// coerce traceIndices input to array of trace indices -_$helpers_191.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_9(traceIndices)) { - return [traceIndices]; - } - else if(!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_, i) { return i; }); + sliderGroups.exit().each(function(sliderOpts) { + _$d3_6.select(this).remove(); + + sliderOpts._commandObserver.remove(); + delete sliderOpts._commandObserver; + + _$plots_245.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index); + }); + + // Find the dimensions of the sliders: + for(var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); } - return traceIndices; -}; + sliderGroups.each(function(sliderOpts) { + // If it has fewer than two options, it's not really a slider: + if(sliderOpts.steps.length < 2) return; -/** - * Manages logic around array container item creation / deletion / update - * that nested property alone can't handle. - * - * @param {Object} np - * nested property of update attribute string about trace or layout object - * @param {*} newVal - * update value passed to restyle / relayout / update - * @param {Object} undoit - * undo hash (N.B. undoit may be mutated here). - * - */ -_$helpers_191.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj, - parts = np.parts, - pLength = parts.length, - pLast = parts[pLength - 1]; + var gSlider = _$d3_6.select(this); - var pLastIsNumber = _$fastIsnumeric_9(pLast); + computeLabelSteps(sliderOpts); - // delete item - if(pLastIsNumber && newVal === null) { + _$plots_245.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + // NB: Same as below. This is *not* always the same as sliderOpts since + // if a new set of steps comes in, the reference in this callback would + // be invalid. We need to refetch it from the slider group, which is + // the join data that creates this slider. So if this slider still exists, + // the group should be valid, *to the best of my knowledge.* If not, + // we'd have to look it up by d3 data join index/key. + var opts = gSlider.data()[0]; - // Clear item in array container when new value is null - var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_163.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); + if(opts.active === data.index) return; + if(opts._dragging) return; - // Note that nested property clears null / undefined at end of - // array container, but not within them. - } - // create item - else if(pLastIsNumber && np.get() === undefined) { + setActive(gd, gSlider, opts, data.index, false, true); + }); - // When adding a new item, make sure undo command will remove it - if(np.get() === undefined) undoit[np.astr] = null; + drawSlider(gd, _$d3_6.select(this), sliderOpts); + }); +}; - np.set(newVal); - } - // update item - else { +// This really only just filters by visibility: +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[_$constants_132.name], + sliderData = []; - // If the last part of attribute string isn't a number, - // np.set is all we need. - np.set(newVal); + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if(!item.visible || !item.steps.length) continue; + item._gd = gd; + sliderData.push(item); } -}; -/* - * Match the part to strip off to turn an attribute into its parent - * really it should be either '.some_characters' or '[number]' - * but we're a little more permissive here and match either - * '.not_brackets_or_dot' or '[not_brackets_or_dot]' - */ -var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + return sliderData; +} -function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if(tail > 0) return attr.substr(0, tail); +// This is set in the defaults step: +function keyFunction(opts) { + return opts._index; } -/* - * hasParent: does an attribute object contain a parent of the given attribute? - * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? - * - * @param {Object} aobj - * update object, whose keys are attribute strings and values are their new settings - * @param {string} attr - * the attribute string to test against - * @returns {Boolean} - * is a parent of attr present in aobj? - */ -_$helpers_191.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while(attrParent) { - if(attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; -}; +// Compute the dimensions (mutates sliderOpts): +function findDimensions(gd, sliderOpts) { + var sliderLabels = _$drawing_68.tester.selectAll('g.' + _$constants_132.labelGroupClass) + .data(sliderOpts.steps); -/** - * Empty out types for all axes containing these traces so we auto-set them again - * - * @param {object} gd - * @param {[integer]} traces: trace indices to search for axes to clear the types of - * @param {object} layoutUpdate: any update being done concurrently to the layout, - * which may supercede clearing the axis types - */ -var __axLetters_191 = ['x', 'y', 'z']; -_$helpers_191.clearAxisTypes = function(gd, traces, layoutUpdate) { - for(var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_191[j]); + sliderLabels.enter().append('g') + .classed(_$constants_132.labelGroupClass, true); - // do not clear log type - that's never an auto result so must have been intentional - if(ax && ax.type !== 'log') { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if(sceneName.substr(0, 5) === 'scene') { - if(layoutUpdate[sceneName] !== undefined) continue; - axAttr = sceneName + '.' + axAttr; - } - var typeAttr = axAttr + '.type'; + // loop over fake buttons to find width / height + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = _$d3_6.select(this); - if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_163.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } -}; + var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); -_$helpers_191.clearAxisAutomargins = function(gd) { - var keys = Object.keys(gd._fullLayout._pushmargin); - for(var i = 0; i < keys.length; i++) { - if(keys[i].indexOf('automargin') !== -1) { - delete gd._fullLayout._pushmargin[keys[i]]; + var textNode = text.node(); + if(textNode) { + var bBox = _$drawing_68.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); } + }); + + sliderLabels.remove(); + + var dims = sliderOpts._dims = {}; + + dims.inputAreaWidth = Math.max( + _$constants_132.railWidth, + _$constants_132.gripHeight + ); + + // calculate some overall dimensions - some of these are needed for + // calculating the currentValue dimensions + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + + if(sliderOpts.lenmode === 'fraction') { + // fraction: + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + // pixels: + dims.outerLength = sliderOpts.len; } -}; -var _$manage_arrays_193 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // The length of the rail, *excluding* padding on either end: + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + var textableInputLength = dims.inputAreaLength - 2 * _$constants_132.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); + var computedSpacePerLabel = maxLabelWidth + _$constants_132.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; -'use strict'; + // loop over all possible values for currentValue to find the + // area we need for it + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; -/* removed: var _$nestedProperty_171 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_165 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_172 = require('../lib/noop'); */; -/* removed: var _$loggers_168 = require('../lib/loggers'); */; -var sorterAsc = _$search_181.sorterAsc; -/* removed: var _$registry_253 = require('../registry'); */; + if(sliderOpts.currentvalue.visible) { + // Get the dimensions of the current value label: + var dummyGroup = _$drawing_68.tester.append('g'); + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = (curValPrefix.node() && _$drawing_68.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_185.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); -_$manage_arrays_193.containerArrayMatch = _$containerArrayMatch_189; + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; -var isAddVal = _$manage_arrays_193.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_165(val); -}; + dummyGroup.remove(); + } -var isRemoveVal = _$manage_arrays_193.isRemoveVal = function isRemoveVal(val) { - return val === null || val === 'remove'; -}; + dims.height = dims.currentValueTotalHeight + _$constants_132.tickOffset + sliderOpts.ticklen + _$constants_132.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; -/* - * applyContainerArrayChanges: for managing arrays of layout components in relayout - * handles them all with a consistent interface. - * - * Here are the supported actions -> relayout calls -> edits we get here - * (as prepared in _relayout): - * - * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} - * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} - * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} - * -> {'annotations[2]': null} -> {2: {'': null}} - * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} - * -> {'annotations': null} -> {'': {'': null}} - * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} - * - * You can combine many edits to different objects. Objects are added and edited - * in ascending order, then removed in descending order. - * For example, starting with [a, b, c], if you want to: - * - replace b with d: - * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) - * - add a new item d between a and b, and edit b: - * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) - * - delete b and edit c: - * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) - * - * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` - * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). - * - * @param {HTMLDivElement} gd - * the DOM element of the graph container div - * @param {Lib.nestedProperty} componentType: the array we are editing - * @param {Object} edits - * the changes to make; keys are indices to edit, values are themselves objects: - * {attr: newValue} of changes to make to that index (with add/remove behavior - * in special values of the empty attr) - * @param {Object} flags - * the flags for which actions we're going to perform to display these (and - * any other) changes. If we're already `recalc`ing, we don't need to redraw - * individual items - * - * @returns {bool} `true` if it managed to complete drawing of the changes - * `false` would mean the parent should replot. - */ -_$manage_arrays_193.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { - var componentType = np.astr, - supplyComponentDefaults = _$registry_253.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_253.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_253.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_172) || - (draw === _$noop_172), - layout = gd.layout, - fullLayout = gd._fullLayout; - - if(edits['']) { - if(Object.keys(edits).length > 1) { - _$loggers_168.warn('Full array edits are incompatible with other edits', - componentType); - } + var xanchor = 'left'; + if(_$anchor_utils_95.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = 'right'; + } + if(_$anchor_utils_95.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = 'center'; + } - var fullVal = edits['']['']; + var yanchor = 'top'; + if(_$anchor_utils_95.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = 'bottom'; + } + if(_$anchor_utils_95.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = 'middle'; + } - if(isRemoveVal(fullVal)) np.set(null); - else if(Array.isArray(fullVal)) np.set(fullVal); - else { - _$loggers_168.warn('Unrecognized full array edit value', componentType, fullVal); - return true; - } + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - if(replotLater) return false; + _$plots_245.autoMargin(gd, _$constants_132.autoMarginIdRoot + sliderOpts._index, { + x: sliderOpts.x, + y: sliderOpts.y, + l: dims.outerLength * __FROM_TL_134[xanchor], + r: dims.outerLength * __FROM_BR_134[xanchor], + b: dims.height * __FROM_BR_134[yanchor], + t: dims.height * __FROM_TL_134[yanchor] + }); +} - supplyComponentDefaults(layout, fullLayout); - draw(gd); - return true; +function drawSlider(gd, sliderGroup, sliderOpts) { + // This is related to the other long notes in this file regarding what happens + // when slider steps disappear. This particular fix handles what happens when + // the *current* slider step is removed. The drawing functions will error out + // when they fail to find it, so the fix for now is that it will just draw the + // slider in the first position but will not execute the command. + if(sliderOpts.active >= sliderOpts.steps.length) { + sliderOpts.active = 0; } - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), - componentArrayIn = np.get(), - componentArray = componentArrayIn || [], - // componentArrayFull is used just to keep splices in line between - // full and input arrays, so private keys can be copied over after - // redoing supplyDefaults - // TODO: this assumes componentArray is in gd.layout - which will not be - // true after we extend this to restyle - componentArrayFull = _$nestedProperty_171(fullLayout, componentType).get(); + // These are carefully ordered for proper z-ordering: + sliderGroup + .call(drawCurrentValue, sliderOpts) + .call(drawRail, sliderOpts) + .call(drawLabelGroup, sliderOpts) + .call(drawTicks, sliderOpts) + .call(drawTouchRect, gd, sliderOpts) + .call(drawGrip, gd, sliderOpts); - var deletes = [], - firstIndexChange = -1, - maxIndex = componentArray.length, - i, - j, - componentNum, - objEdits, - objKeys, - objVal, - adding; + var dims = sliderOpts._dims; - // first make the add and edit changes - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[''], - adding = isAddVal(objVal); + // Position the rectangle: + _$drawing_68.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); - if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_168.warn('index out of range', componentType, componentNum); - continue; - } + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); + sliderGroup.call(drawCurrentValue, sliderOpts); - if(objVal !== undefined) { - if(objKeys.length > 1) { - _$loggers_168.warn( - 'Insertion & removal are incompatible with edits to the same index.', - componentType, componentNum); - } +} - if(isRemoveVal(objVal)) { - deletes.push(componentNum); - } - else if(adding) { - if(objVal === 'add') objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } - else { - _$loggers_168.warn('Unrecognized full object edit value', - componentType, componentNum, objVal); - } +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if(!sliderOpts.currentvalue.visible) return; - if(firstIndexChange === -1) firstIndexChange = componentNum; - } - else { - for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_171(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); - } - } - } + var dims = sliderOpts._dims; + var x0, textAnchor; - // now do deletes - for(i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - // TODO: this drops private keys that had been stored in componentArrayFull - // does this have any ill effects? - if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); + switch(sliderOpts.currentvalue.xanchor) { + case 'right': + // This is anchored left and adjusted by the width of the longest label + // so that the prefix doesn't move. The goal of this is to emphasize + // what's actually changing and make the update less distracting. + x0 = dims.inputAreaLength - _$constants_132.currentValueInset - dims.currentValueMaxWidth; + textAnchor = 'left'; + break; + case 'center': + x0 = dims.inputAreaLength * 0.5; + textAnchor = 'middle'; + break; + default: + x0 = _$constants_132.currentValueInset; + textAnchor = 'left'; } - if(!componentArray.length) np.set(null); - else if(!componentArrayIn) np.set(componentArray); + var text = _$lib_164.ensureSingle(sliderGroup, 'text', _$constants_132.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); - if(replotLater) return false; + var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; - supplyComponentDefaults(layout, fullLayout); + if(typeof valueOverride === 'string') { + str += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + str += curVal; + } - // finally draw all the components we need to - // if we added or removed any, redraw all after it - if(drawOne !== _$noop_172) { - var indicesToDraw; - if(firstIndexChange === -1) { - // there's no re-indexing to do, so only redraw components that changed - indicesToDraw = componentNums; - } - else { - // in case the component array was shortened, we still need do call - // drawOne on the latter items so they get properly removed - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for(i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if(componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for(i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for(i = 0; i < indicesToDraw.length; i++) { - drawOne(gd, indicesToDraw[i]); - } + if(sliderOpts.currentvalue.suffix) { + str += sliderOpts.currentvalue.suffix; } - else draw(gd); - return true; -}; + text.call(_$drawing_68.font, sliderOpts.currentvalue.font) + .text(str) + .call(_$svg_text_utils_185.convertToTspans, sliderOpts._gd); -var _$buttons_105 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 lines = _$svg_text_utils_185.lineCount(text); + var y0 = (dims.currentValueMaxLines + 1 - lines) * + sliderOpts.currentvalue.font.size * __LINE_SPACING_134; -'use strict'; + _$svg_text_utils_185.positionText(text, x0, y0); -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; + return text; +} -var ____105 = _$lib_163._; +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = _$lib_164.ensureSingle(sliderGroup, 'rect', _$constants_132.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); -var modeBarButtons = _$buttons_105 = {}; + grip.attr({ + width: _$constants_132.gripWidth, + height: _$constants_132.gripHeight, + rx: _$constants_132.gripRadius, + ry: _$constants_132.gripRadius, + }) + .call(_$color_43.stroke, sliderOpts.bordercolor) + .call(_$color_43.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); +} -/** - * 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? - */ +function drawLabel(item, data, sliderOpts) { + var text = _$lib_164.ensureSingle(item, 'text', _$constants_132.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); -modeBarButtons.toImage = { - name: 'toImage', - title: function(gd) { return ____105(gd, 'Download plot as a png'); }, - icon: _$ploticon_2.camera, - click: function(gd) { - var format = 'png'; + text.call(_$drawing_68.font, sliderOpts.font) + .text(data.step.label) + .call(_$svg_text_utils_185.convertToTspans, sliderOpts._gd); - _$lib_163.notifier(____105(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + return text; +} - if(_$lib_163.isIE()) { - _$lib_163.notifier(____105(gd, 'IE only supports svg. Changing format to svg.'), 'long'); - format = 'svg'; - } +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = _$lib_164.ensureSingle(sliderGroup, 'g', _$constants_132.labelsClass); + var dims = sliderOpts._dims; - _$registry_253.call('downloadImage', gd, {'format': format}) - .then(function(filename) { - _$lib_163.notifier(____105(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); - }) - .catch(function() { - _$lib_163.notifier(____105(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); - }); - } -}; + var labelItems = labels.selectAll('g.' + _$constants_132.labelGroupClass) + .data(dims.labelSteps); -modeBarButtons.sendDataToCloud = { - name: 'sendDataToCloud', - title: function(gd) { return ____105(gd, 'Edit in Chart Studio'); }, - icon: _$ploticon_2.disk, - click: function(gd) { - _$plots_245.sendDataToCloud(gd); - } -}; + labelItems.enter().append('g') + .classed(_$constants_132.labelGroupClass, true); -modeBarButtons.zoom2d = { - name: 'zoom2d', - title: function(gd) { return ____105(gd, 'Zoom'); }, - attr: 'dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleCartesian -}; + labelItems.exit().remove(); -modeBarButtons.pan2d = { - name: 'pan2d', - title: function(gd) { return ____105(gd, 'Pan'); }, - attr: 'dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleCartesian -}; + labelItems.each(function(d) { + var item = _$d3_6.select(this); -modeBarButtons.select2d = { - name: 'select2d', - title: function(gd) { return ____105(gd, 'Box Select'); }, - attr: 'dragmode', - val: 'select', - icon: _$ploticon_2.selectbox, - click: handleCartesian -}; + item.call(drawLabel, d, sliderOpts); -modeBarButtons.lasso2d = { - name: 'lasso2d', - title: function(gd) { return ____105(gd, 'Lasso Select'); }, - attr: 'dragmode', - val: 'lasso', - icon: _$ploticon_2.lasso, - click: handleCartesian -}; + _$drawing_68.setTranslate(item, + normalizedValueToPosition(sliderOpts, d.fraction), + _$constants_132.tickOffset + + sliderOpts.ticklen + + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * __LINE_SPACING_134 + + _$constants_132.labelOffset + + dims.currentValueTotalHeight + ); + }); -modeBarButtons.zoomIn2d = { - name: 'zoomIn2d', - title: function(gd) { return ____105(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleCartesian -}; +} -modeBarButtons.zoomOut2d = { - name: 'zoomOut2d', - title: function(gd) { return ____105(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleCartesian -}; +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1)); -modeBarButtons.autoScale2d = { - name: 'autoScale2d', - title: function(gd) { return ____105(gd, 'Autoscale'); }, - attr: 'zoom', - val: 'auto', - icon: _$ploticon_2.autoscale, - click: handleCartesian -}; + if(quantizedPosition !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition); + } +} -modeBarButtons.resetScale2d = { - name: 'resetScale2d', - title: function(gd) { return ____105(gd, 'Reset axes'); }, - attr: 'zoom', - val: 'reset', - icon: _$ploticon_2.home, - click: handleCartesian -}; +function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts._input.active = sliderOpts.active = index; -modeBarButtons.hoverClosestCartesian = { - name: 'hoverClosestCartesian', - title: function(gd) { return ____105(gd, 'Show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleCartesian -}; + var step = sliderOpts.steps[sliderOpts.active]; -modeBarButtons.hoverCompareCartesian = { - name: 'hoverCompareCartesian', - title: function(gd) { return ____105(gd, 'Compare data on hover'); }, - attr: 'hovermode', - val: function(gd) { - return gd._fullLayout._isHoriz ? 'y' : 'x'; - }, - icon: _$ploticon_2.tooltip_compare, - gravity: 'ne', - click: handleCartesian -}; + sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); -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 = _$axis_ids_208.list(gd, null, true); - var allSpikesEnabled = 'on'; + gd.emit('plotly_sliderchange', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive: previousActive + }); - var ax, i; + if(step && step.method && doCallback) { + if(sliderGroup._nextMethod) { + // If we've already queued up an update, just overwrite it with the most recent: + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition}; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if(!_step.method) return; - if(astr === 'zoom') { - var mag = (val === 'in') ? 0.5 : 2, - r0 = (1 + mag) / 2, - r1 = (1 - mag) / 2; + if(_step.execute) { + _$plots_245.executeAPICommand(gd, _step.method, _step.args); + } - var axName; + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } + } +} - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function attachGripEvents(item, gd, sliderGroup) { + var node = sliderGroup.node(); + var $gd = _$d3_6.select(gd); - 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]; - } - 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]), - ]; + // NB: This is *not* the same as sliderOpts itself! These callbacks + // are in a closure so this array won't actually be correct if the + // steps have changed since this was initialized. The sliderGroup, + // however, has not changed since that *is* the slider, so it must + // be present to receive mouse events. + function getSliderOpts() { + return sliderGroup.data()[0]; + } - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; + item.on('mousedown', function() { + var sliderOpts = getSliderOpts(); + gd.emit('plotly_sliderstart', {slider: sliderOpts}); - aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); - aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); - } - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - 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); - } else if(astr === 'hovermode' && val === 'closest') { - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(allSpikesEnabled === 'on' && !ax.showspikes) { - allSpikesEnabled = 'off'; - } - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - } - - aobj[astr] = val; - } - - _$registry_253.call('relayout', gd, aobj); -} - -modeBarButtons.zoom3d = { - name: 'zoom3d', - title: function(gd) { return ____105(gd, 'Zoom'); }, - attr: 'scene.dragmode', - val: 'zoom', - icon: _$ploticon_2.zoombox, - click: handleDrag3d -}; - -modeBarButtons.pan3d = { - name: 'pan3d', - title: function(gd) { return ____105(gd, 'Pan'); }, - attr: 'scene.dragmode', - val: 'pan', - icon: _$ploticon_2.pan, - click: handleDrag3d -}; - -modeBarButtons.orbitRotation = { - name: 'orbitRotation', - title: function(gd) { return ____105(gd, 'Orbital rotation'); }, - attr: 'scene.dragmode', - val: 'orbit', - icon: _$ploticon_2['3d_rotate'], - click: handleDrag3d -}; - -modeBarButtons.tableRotation = { - name: 'tableRotation', - title: function(gd) { return ____105(gd, 'Turntable rotation'); }, - attr: 'scene.dragmode', - val: 'turntable', - icon: _$ploticon_2['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_253.call('relayout', gd, layoutUpdate); -} - -modeBarButtons.resetCameraDefault3d = { - name: 'resetCameraDefault3d', - title: function(gd) { return ____105(gd, 'Reset camera to default'); }, - attr: 'resetDefault', - icon: _$ploticon_2.home, - click: handleCamera3d -}; + var grip = sliderGroup.select('.' + _$constants_132.gripRectClass); -modeBarButtons.resetCameraLastSave3d = { - name: 'resetCameraLastSave3d', - title: function(gd) { return ____105(gd, 'Reset camera to last save'); }, - attr: 'resetLastSave', - icon: _$ploticon_2.movie, - click: handleCamera3d -}; + _$d3_6.event.stopPropagation(); + _$d3_6.event.preventDefault(); + grip.call(_$color_43.fill, sliderOpts.activebgcolor); -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 = {}; + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_6.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - key = sceneId + '.camera', - scene = fullLayout[sceneId]._scene; + $gd.on('mousemove', function() { + var sliderOpts = getSliderOpts(); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_6.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); + }); - if(attr === 'resetDefault') { - aobj[key] = null; - } - else if(attr === 'resetLastSave') { - aobj[key] = _$lib_163.extendDeep({}, scene.cameraInitial); - } - } + $gd.on('mouseup', function() { + var sliderOpts = getSliderOpts(); + sliderOpts._dragging = false; + grip.call(_$color_43.fill, sliderOpts.bgcolor); + $gd.on('mouseup', null); + $gd.on('mousemove', null); - _$registry_253.call('relayout', gd, aobj); + gd.emit('plotly_sliderend', { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active] + }); + }); + }); } -modeBarButtons.hoverClosest3d = { - name: 'hoverClosest3d', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: handleHover3d -}; - -function handleHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal || false; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; - - var axes = ['xaxis', 'yaxis', 'zaxis']; - var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; - - // initialize 'current spike' object to be stored in the DOM - var currentSpikes = {}; - var axisSpikes = {}; - var layoutUpdate = {}; +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll('rect.' + _$constants_132.tickRectClass) + .data(sliderOpts.steps); + var dims = sliderOpts._dims; - if(val) { - layoutUpdate = _$lib_163.extendDeep(layout, val); - button._previousVal = null; - } - else { - layoutUpdate = { - 'allaxes.showspikes': false - }; + tick.enter().append('rect') + .classed(_$constants_132.tickRectClass, true); - for(var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i], - sceneLayout = fullLayout[sceneId], - sceneSpikes = currentSpikes[sceneId] = {}; + tick.exit().remove(); - sceneSpikes.hovermode = sceneLayout.hovermode; - layoutUpdate[sceneId + '.hovermode'] = false; + tick.attr({ + width: sliderOpts.tickwidth + 'px', + 'shape-rendering': 'crispEdges' + }); - // copy all the current spike attrs - for(var j = 0; j < 3; j++) { - var axis = axes[j]; - axisSpikes = sceneSpikes[axis] = {}; + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = _$d3_6.select(this); - for(var k = 0; k < spikeAttrs.length; k++) { - var spikeAttr = spikeAttrs[k]; - axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; - } - } - } + item + .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) + .call(_$color_43.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - button._previousVal = _$lib_163.extendDeep({}, currentSpikes); - } + _$drawing_68.setTranslate(item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? _$constants_132.tickOffset : _$constants_132.minorTickOffset) + dims.currentValueTotalHeight + ); + }); - _$registry_253.call('relayout', gd, layoutUpdate); } -modeBarButtons.zoomInGeo = { - name: 'zoomInGeo', - title: function(gd) { return ____105(gd, 'Zoom in'); }, - attr: 'zoom', - val: 'in', - icon: _$ploticon_2.zoom_plus, - click: handleGeo -}; - -modeBarButtons.zoomOutGeo = { - name: 'zoomOutGeo', - title: function(gd) { return ____105(gd, 'Zoom out'); }, - attr: 'zoom', - val: 'out', - icon: _$ploticon_2.zoom_minus, - click: handleGeo -}; - -modeBarButtons.resetGeo = { - name: 'resetGeo', - title: function(gd) { return ____105(gd, 'Reset'); }, - attr: 'reset', - val: null, - icon: _$ploticon_2.autoscale, - click: handleGeo -}; - -modeBarButtons.hoverClosestGeo = { - name: 'hoverClosestGeo', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.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; +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var i0 = 0; + var nsteps = sliderOpts.steps.length; - _$registry_253.call('relayout', gd, id + '.projection.scale', newScale); - } else if(attr === 'reset') { - resetView(gd, 'geo'); - } + for(var i = i0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts.steps[i] + }); } } -modeBarButtons.hoverClosestGl2d = { - name: 'hoverClosestGl2d', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; +function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { + var grip = sliderGroup.select('rect.' + _$constants_132.gripRectClass); -modeBarButtons.hoverClosestPie = { - name: 'hoverClosestPie', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: 'closest', - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: toggleHover -}; + var x = normalizedValueToPosition(sliderOpts, position); -function toggleHover(gd) { - var fullLayout = gd._fullLayout; + // If this is true, then *this component* is already invoking its own command + // and has triggered its own animation. + if(sliderOpts._invokingCommand) return; - var onHoverVal; - if(fullLayout._has('cartesian')) { - onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + var el = grip; + if(doTransition && sliderOpts.transition.duration > 0) { + el = el.transition() + .duration(sliderOpts.transition.duration) + .ease(sliderOpts.transition.easing); } - else onHoverVal = 'closest'; - var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - - _$registry_253.call('relayout', gd, 'hovermode', newHover); + // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. + // It's also not necessary because there are no other transitions to preserve. + el.attr('transform', 'translate(' + (x - _$constants_132.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); } -// buttons when more then one plot types are present - -modeBarButtons.toggleHover = { - name: 'toggleHover', - title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, - attr: 'hovermode', - val: null, - toggle: true, - icon: _$ploticon_2.tooltip_basic, - gravity: 'ne', - click: function(gd, ev) { - toggleHover(gd); - - // the 3d hovermode update must come - // last so that layout.hovermode update does not - // override scene?.hovermode?.layout. - handleHover3d(gd, ev); - } -}; - -modeBarButtons.resetViews = { - name: 'resetViews', - title: function(gd) { return ____105(gd, 'Reset views'); }, - icon: _$ploticon_2.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 ____105(gd, 'Toggle Spike Lines'); }, - icon: _$ploticon_2.spikeline, - attr: '_cartesianSpikesEnabled', - val: 'on', - click: function(gd) { - var fullLayout = gd._fullLayout; +// Convert a number from [0-1] to a pixel position relative to the slider group container: +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + _$constants_132.stepInset + + (dims.inputAreaLength - 2 * _$constants_132.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} - fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; +// Convert a position relative to the slider group to a nubmer in [0, 1] +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - _$constants_132.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_132.stepInset - 2 * dims.inputAreaStart))); +} - var aobj = setSpikelineVisibility(gd); +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect = _$lib_164.ensureSingle(sliderGroup, 'rect', _$constants_132.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); - _$registry_253.call('relayout', gd, aobj); - } -}; + rect.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, _$constants_132.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }) + .call(_$color_43.fill, sliderOpts.bgcolor) + .attr('opacity', 0); -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var axList = _$axis_ids_208.list(gd, null, true); - var aobj = {}; + _$drawing_68.setTranslate(rect, 0, dims.currentValueTotalHeight); +} - var ax, axName; +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - _$constants_132.railInset * 2; + var rect = _$lib_164.ensureSingle(sliderGroup, 'rect', _$constants_132.railRectClass); - for(var i = 0; i < axList.length; i++) { - ax = axList[i]; - axName = ax._name; - aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; - } + rect.attr({ + width: computedLength, + height: _$constants_132.railWidth, + rx: _$constants_132.railRadius, + ry: _$constants_132.railRadius, + 'shape-rendering': 'crispEdges' + }) + .call(_$color_43.stroke, sliderOpts.bordercolor) + .call(_$color_43.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - return aobj; + _$drawing_68.setTranslate(rect, + _$constants_132.railInset, + (dims.inputAreaWidth - _$constants_132.railWidth) * 0.5 + dims.currentValueTotalHeight + ); } -modeBarButtons.resetViewMapbox = { - name: 'resetViewMapbox', - title: function(gd) { return ____105(gd, 'Reset view'); }, - attr: 'reset', - icon: _$ploticon_2.home, - click: function(gd) { - resetView(gd, 'mapbox'); - } -}; - -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType]; - var aObj = {}; +function __clearPushMargins_134(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}, + keys = Object.keys(pushMargins); - 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 i = 0; i < keys.length; i++) { + var k = keys[i]; - for(var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + '.' + key] = viewInitial[key]; + if(k.indexOf(_$constants_132.autoMarginIdRoot) !== -1) { + _$plots_245.autoMargin(gd, k); } } - - _$registry_253.call('relayout', gd, aObj); } /** @@ -47426,294 +48319,349 @@ function resetView(gd, subplotType) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_6 = require('d3'); */; - -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - - -/** - * 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'); +/* removed: var _$constants_132 = require('./constants'); */; - this.update(opts.graphInfo, opts.buttons); +var _$sliders_135 = { + moduleType: 'component', + name: _$constants_132.name, - this.container.appendChild(this.element); -} + layoutAttributes: _$attributes_131, + supplyLayoutDefaults: _$slidersDefaults_133, -var proto = ModeBar.prototype; + draw: _$draw_134 +}; /** - * 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; - - if(context.displayModeBar === 'hover') { - this.element.className = 'modebar modebar--hover'; - } - else this.element.className = 'modebar'; - - // if buttons or logo have changed, redraw modebar interior - var needsNewButtons = !this.hasButtons(buttons), - needsNewLogo = (this.hasLogo !== context.displaylogo); - - if(needsNewButtons || needsNewLogo) { - this.removeAllButtons(); - - this.updateButtons(buttons); +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(context.displaylogo) { - this.element.appendChild(this.getLogo()); - this.hasLogo = true; - } - } +'use strict'; - this.updateActiveButton(); -}; +/* removed: var _$font_attributes_232 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_42 = require('../color/attributes'); */; +var __extendFlat_137 = _$extend_157.extendFlat; +var __overrideAll_137 = _$edit_types_191.overrideAll; +/* removed: var _$pad_attributes_244 = require('../../plots/pad_attributes'); */; -proto.updateButtons = function(buttons) { - var _this = this; +var buttonsAttrs = { + _isLinkedToArray: 'button', - this.buttons = buttons; - this.buttonElements = []; - this.buttonsNames = []; + method: { + valType: 'enumerated', + values: ['restyle', 'relayout', 'animate', 'update', 'skip'], + dflt: 'restyle', + + + }, + args: { + valType: 'info_array', + + freeLength: true, + items: [ + {valType: 'any'}, + {valType: 'any'}, + {valType: 'any'} + ], + + }, + label: { + valType: 'string', + + dflt: '', + + }, + execute: { + valType: 'boolean', + + dflt: true, + + } +}; - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); +var _$attributes_137 = __overrideAll_137({ + _isLinkedToArray: 'updatemenu', + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - 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); + visible: { + valType: 'boolean', + + + }, - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); + type: { + valType: 'enumerated', + values: ['dropdown', 'buttons'], + dflt: 'dropdown', + + + }, - _this.element.appendChild(group); - }); -}; + direction: { + valType: 'enumerated', + values: ['left', 'right', 'up', 'down'], + dflt: 'down', + + + }, -/** - * Empty div for containing a group of buttons - * @Return {HTMLelement} - */ -proto.createGroup = function() { - var group = document.createElement('div'); - group.className = 'modebar-group'; + active: { + valType: 'integer', + + min: -1, + dflt: 0, + + }, - return group; -}; + showactive: { + valType: 'boolean', + + dflt: true, + + }, + + buttons: buttonsAttrs, + + x: { + valType: 'number', + min: -2, + max: 3, + dflt: -0.05, + + + }, + xanchor: { + valType: 'enumerated', + values: ['auto', 'left', 'center', 'right'], + dflt: 'right', + + + }, + y: { + valType: 'number', + min: -2, + max: 3, + dflt: 1, + + + }, + yanchor: { + valType: 'enumerated', + values: ['auto', 'top', 'middle', 'bottom'], + dflt: 'top', + + + }, + + pad: __extendFlat_137({}, _$pad_attributes_244, { + + }), + + font: _$font_attributes_232({ + + }), + + bgcolor: { + valType: 'color', + + + }, + bordercolor: { + valType: 'color', + dflt: _$attributes_42.borderLine, + + + }, + borderwidth: { + valType: 'number', + min: 0, + dflt: 1, + + editType: 'arraydraw', + + } +}, 'arraydraw', 'from-root'); /** - * 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, - button = document.createElement('a'); +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - 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); +'use strict'; - if(title || title === 0) button.setAttribute('data-title', title); - if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); +var _$constants_138 = { - var val = config.val; - if(val !== undefined) { - if(typeof val === 'function') val = val(this.graphInfo); - button.setAttribute('data-val', val); - } + // layout attribute name + name: 'updatemenus', - 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); + // 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', - // only needed for 'hoverClosestGeo' which does not call relayout - _this.updateActiveButton(ev.currentTarget); - }); - } + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: 'updatemenu-active-index', - button.setAttribute('data-toggle', config.toggle || false); - if(config.toggle) _$d3_6.select(button).classed('active', true); + // id root pass to Plots.autoMargin + autoMarginIdRoot: 'updatemenu-', - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - button.setAttribute('data-gravity', config.gravity || 'n'); + // options when 'active: -1' + blankHeaderOpts: { label: ' ' }, - return button; -}; + // min item width / height + minWidth: 30, + minHeight: 30, -/** - * Add an icon to a button - * @Param {object} thisIcon - * @Param {number} thisIcon.width - * @Param {string} thisIcon.path - * @Return {HTMLelement} - */ -proto.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); + // padding around item text + textPadX: 24, + arrowPadX: 16, - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); + // item rect radii + rx: 2, + ry: 2, - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; + // item text x offset off left edge + textOffsetX: 12, - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); + // item text y offset (w.r.t. middle) + textOffsetY: 3, - return icon; -}; + // arrow offset off right edge + arrowOffsetX: 4, -/** - * 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, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; + // gap between header and buttons + gapButtonHeader: 5, - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_6.select(button); + // gap between between buttons + gapButton: 2, - // 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_163.nestedProperty(fullLayout, dataAttr).get(); + // color given to active buttons + activeColor: '#F4FAFF', - button3.classed('active', val === thisval); - } + // color given to hovered buttons + hoverColor: '#F4FAFF', - }); + // symbol for menu open arrow + arrowSymbol: { + left: '◄', + right: '►', + up: '▲', + down: '▼' + } }; /** - * 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; +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!currentButtons) return false; +'use strict'; - if(buttons.length !== currentButtons.length) return false; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_202 = require('../../plots/array_container_defaults'); */; - 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; - } - } +/* removed: var _$attributes_137 = require('./attributes'); */; +/* removed: var _$constants_138 = require('./constants'); */; - return true; +var __name_139 = _$constants_138.name; +var __buttonAttrs_139 = _$attributes_137.buttons; + + +var _$updateMenusDefaults_139 = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: __name_139, + handleItemDefaults: menuDefaults + }; + + _$handleArrayContainerDefaults_202(layoutIn, layoutOut, opts); }; -/** - * @return {HTMLDivElement} The logo image wrapped in a group - */ -proto.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); +function menuDefaults(menuIn, menuOut, layoutOut) { - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_163._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; + function coerce(attr, dflt) { + return _$lib_164.coerce(menuIn, menuOut, _$attributes_137, attr, dflt); + } - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); + var buttons = __buttonsDefaults_139(menuIn, menuOut); - group.appendChild(a); - return group; -}; + var visible = coerce('visible', buttons.length > 0); + if(!visible) return; -proto.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); + coerce('active'); + coerce('direction'); + coerce('type'); + coerce('showactive'); + + coerce('x'); + coerce('y'); + _$lib_164.noneOrAll(menuIn, menuOut, ['x', 'y']); + + coerce('xanchor'); + coerce('yanchor'); + + coerce('pad.t'); + coerce('pad.r'); + coerce('pad.b'); + coerce('pad.l'); + + _$lib_164.coerceFont(coerce, 'font', layoutOut.font); + + coerce('bgcolor', layoutOut.paper_bgcolor); + coerce('bordercolor'); + coerce('borderwidth'); +} + +function __buttonsDefaults_139(menuIn, menuOut) { + var buttonsIn = menuIn.buttons || [], + buttonsOut = menuOut.buttons = []; + + var buttonIn, buttonOut; + + function coerce(attr, dflt) { + return _$lib_164.coerce(buttonIn, buttonOut, __buttonAttrs_139, attr, dflt); } - this.hasLogo = false; -}; + for(var i = 0; i < buttonsIn.length; i++) { + buttonIn = buttonsIn[i]; + buttonOut = {}; -proto.destroy = function() { - _$lib_163.removeElement(this.container.querySelector('.modebar')); -}; + coerce('method'); -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; + if(!_$lib_164.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + continue; + } - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); + coerce('args'); + coerce('label'); + coerce('execute'); - if(fullLayout._privateplot) { - _$d3_6.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); + buttonOut._index = i; + buttonsOut.push(buttonOut); } - return modeBar; + return buttonsOut; } -var _$createModeBar_108 = createModeBar; - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -47722,265 +48670,467 @@ var _$createModeBar_108 = createModeBar; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$axis_ids_208 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_287 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +var _$ScrollBox_142 = ScrollBox; -/* removed: var _$createModeBar_108 = require('./modebar'); */; -/* removed: var _$buttons_105 = require('./buttons'); */; +/* removed: var _$d3_6 = require('d3'); */; + +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; + +/* removed: var _$lib_164 = require('../../lib'); */; /** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object + * Helper class to setup a scroll box * + * @class + * @param gd Plotly's graph div + * @param container Container to be scroll-boxed (as a D3 selection) + * @param {string} id Id for the clip path to implement the scroll box */ -var _$manageModeBar_107 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } +function ScrollBox(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } + // See ScrollBox.prototype.enable for further definition + this.position = null; // scrollbox position + this.translateX = null; // scrollbox horizontal translation + this.translateY = null; // scrollbox vertical translation + this.hbar = null; // horizontal scrollbar D3 selection + this.vbar = null; // vertical scrollbar D3 selection - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } + // element to capture pointer events + this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]); - var customButtons = context.modeBarButtons; - var buttonGroups; + this.bg.exit() + .on('.drag', null) + .on('wheel', null) + .remove(); - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } + this.bg.enter().append('rect') + .classed('scrollbox-bg', true) + .style('pointer-events', 'all') + .attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_108(gd, buttonGroups); -}; +// scroll bar dimensions +ScrollBox.barWidth = 2; +ScrollBox.barLength = 20; +ScrollBox.barRadius = 2; +ScrollBox.barPad = 1; +ScrollBox.barColor = '#808BA4'; -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; +/** + * If needed, setup a clip path and scrollbars + * + * @method + * @param {Object} position + * @param {number} position.l Left side position (in pixels) + * @param {number} position.t Top side (in pixels) + * @param {number} position.w Width (in pixels) + * @param {number} position.h Height (in pixels) + * @param {string} [position.direction='down'] + * Either 'down', 'left', 'right' or 'up' + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout, + fullWidth = fullLayout.width, + fullHeight = fullLayout.height; - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); + // compute position of scrollbox + this.position = position; - var groups = []; + var l = this.position.l, + w = this.position.w, + t = this.position.t, + h = this.position.h, + direction = this.position.direction, + isDown = (direction === 'down'), + isLeft = (direction === 'left'), + isRight = (direction === 'right'), + isUp = (direction === 'up'), + boxW = w, + boxH = h, + boxL, boxR, + boxT, boxB; - function addGroup(newGroup) { - if(!newGroup.length) return; + if(!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = 'down'; + isDown = true; + } - var out = []; + var isVertical = isDown || isUp; + if(isVertical) { + boxL = l; + boxR = boxL + boxW; - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_105[button]); + if(isDown) { + // anchor to top side + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } + else { + // anchor to bottom side + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; } + } + else { + boxT = t; + boxB = boxT + boxH; - groups.push(out); + if(isLeft) { + // anchor to right side + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; + } + else { + // anchor to left side + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; + } } - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; + // compute position of horizontal scroll bar + var needsHorizontalScrollBar = (w > boxW), + hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad, + hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad, + // draw horizontal scrollbar on the bottom side + hbarL = l, + hbarT = t + h; - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; + if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + + var hbar = this.container.selectAll('rect.scrollbar-horizontal').data( + (needsHorizontalScrollBar) ? [0] : []); + + hbar.exit() + .on('.drag', null) + .remove(); + + hbar.enter().append('rect') + .classed('scrollbar-horizontal', true) + .call(_$color_43.fill, ScrollBox.barColor); + + if(needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': hbarL, + 'y': hbarT, + 'width': hbarW, + 'height': hbarH + }); + + // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; + else { + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; + + // compute position of vertical scroll bar + var needsVerticalScrollBar = (h > boxH), + vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad, + vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad, + // draw vertical scrollbar on the right side + vbarL = l + w, + vbarT = t; + + if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + + var vbar = this.container.selectAll('rect.scrollbar-vertical').data( + (needsVerticalScrollBar) ? [0] : []); + + vbar.exit() + .on('.drag', null) + .remove(); + + vbar.enter().append('rect') + .classed('scrollbar-vertical', true) + .call(_$color_43.fill, ScrollBox.barColor); + + if(needsVerticalScrollBar) { + this.vbar = vbar.attr({ + 'rx': ScrollBox.barRadius, + 'ry': ScrollBox.barRadius, + 'x': vbarL, + 'y': vbarT, + 'width': vbarW, + 'height': vbarH + }); + + // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; + else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; + + // setup a clip path (if scroll bars are needed) + var clipId = this.id, + clipL = boxL - 0.5, + clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5, + clipT = boxT - 0.5, + clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5; + + var clipPath = fullLayout._topdefs.selectAll('#' + clipId) + .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []); + + clipPath.exit().remove(); + + clipPath.enter() + .append('clipPath').attr('id', clipId) + .append('rect'); + + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select('rect').attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); + + this.container.call(_$drawing_68.setClipUrl, clipId); + + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; + else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_68.setClipUrl, null); + delete this._clipRect; } - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; - } + // set up drag listeners (if scroll bars are needed) + if(needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = _$d3_6.behavior.drag() + .on('dragstart', function() { + _$d3_6.event.sourceEvent.preventDefault(); + }) + .on('drag', this._onBoxDrag.bind(this)); - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + this.container + .on('wheel', null) + .on('wheel', this._onBoxWheel.bind(this)) + .on('.drag', null) + .call(onBoxDrag); + + var onBarDrag = _$d3_6.behavior.drag() + .on('dragstart', function() { + _$d3_6.event.sourceEvent.preventDefault(); + _$d3_6.event.sourceEvent.stopPropagation(); + }) + .on('drag', this._onBarDrag.bind(this)); + + if(needsHorizontalScrollBar) { + this.hbar + .on('.drag', null) + .call(onBarDrag); + } + + if(needsVerticalScrollBar) { + this.vbar + .on('.drag', null) + .call(onBarDrag); + } } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; + + // set scrollbox translation + this.setTranslate(translateX, translateY); +}; + +/** + * If present, remove clip-path and scrollbars + * + * @method + */ +ScrollBox.prototype.disable = function disable() { + if(this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container + .on('wheel', null) + .on('.drag', null) + .call(_$drawing_68.setClipUrl, null); + delete this._clipRect; } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; + + if(this.hbar) { + this.hbar.on('.drag', null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; + + if(this.vbar) { + this.vbar.on('.drag', null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); +}; + +/** + * Handles scroll box drag events + * + * @method + */ +ScrollBox.prototype._onBoxDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; + + if(this.hbar) { + translateX -= _$d3_6.event.dx; } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); + if(this.vbar) { + translateY -= _$d3_6.event.dy; + } - return appendButtonsToGroups(groups, buttonsToAdd); -} + this.setTranslate(translateX, translateY); +}; -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_208.list({_fullLayout: fullLayout}, null, true); +/** + * Handles scroll box wheel events + * + * @method + */ +ScrollBox.prototype._onBoxWheel = function onBarWheel() { + var translateX = this.translateX, + translateY = this.translateY; - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } + if(this.hbar) { + translateX += _$d3_6.event.deltaY; } - return true; -} + if(this.vbar) { + translateY += _$d3_6.event.deltaY; + } -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; + this.setTranslate(translateX, translateY); +}; - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; +/** + * Handles scroll bar drag events + * + * @method + */ +ScrollBox.prototype._onBarDrag = function onBarDrag() { + var translateX = this.translateX, + translateY = this.translateY; - var trace = fullData[i]; + if(this.hbar) { + var xMin = translateX + this._hbarXMin, + xMax = xMin + this._hbarTranslateMax, + x = _$lib_164.constrain(_$d3_6.event.x, xMin, xMax), + xf = (x - xMin) / (xMax - xMin); - if(!trace._module || !trace._module.selectPoints) continue; + var translateXMax = this.position.w - this._box.w; - if(_$registry_253.traceIs(trace, 'scatter-like')) { - if(_$subtypes_287.hasMarkers(trace) || _$subtypes_287.hasText(trace)) { - selectable = true; - } - } else if(_$registry_253.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; + translateX = xf * translateXMax; } - return selectable; -} + if(this.vbar) { + var yMin = translateY + this._vbarYMin, + yMax = yMin + this._vbarTranslateMax, + y = _$lib_164.constrain(_$d3_6.event.y, yMin, yMax), + yf = (y - yMin) / (yMax - yMin); -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } - } - else groups.push(buttons); + var translateYMax = this.position.h - this._box.h; + + translateY = yf * translateYMax; } - return groups; -} + this.setTranslate(translateX, translateY); +}; -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; +/** + * Set clip path and scroll bar translate transform + * + * @method + * @param {number} [translateX=0] Horizontal offset (in pixels) + * @param {number} [translateY=0] Vertical offset (in pixels) + */ +ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) { + // store translateX and translateY (needed by mouse event handlers) + var translateXMax = this.position.w - this._box.w, + translateYMax = this.position.h - this._box.h; - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; + translateX = _$lib_164.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_164.constrain(translateY || 0, 0, translateYMax); - if(typeof button === 'string') { - if(_$buttons_105[button] !== undefined) { - customButtons[i][j] = _$buttons_105[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } - } + this.translateX = translateX; + this.translateY = translateY; - return customButtons; -} + this.container.call(_$drawing_68.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY); -var _$modebar_106 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } + if(this.hbar) { + var xf = translateX / translateXMax; -'use strict'; + this.hbar.call(_$drawing_68.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY); + } -_$modebar_106.manage = _$manageModeBar_107; + if(this.vbar) { + var yf = translateY / translateYMax; + + this.vbar.call(_$drawing_68.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax); + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -47993,1632 +49143,1677 @@ _$modebar_106.manage = _$manageModeBar_107; 'use strict'; -var FROM_BL = _$alignment_143.FROM_BL; +/* removed: var _$d3_6 = require('d3'); */; -var _$scaleZoom_222 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } +/* removed: var _$plots_245 = require('../../plots/plots'); */; +/* removed: var _$color_43 = require('../color'); */; +/* removed: var _$drawing_68 = require('../drawing'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_95 = require('../legend/anchor_utils'); */; - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; +var __LINE_SPACING_140 = _$alignment_143.LINE_SPACING; - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; +/* removed: var _$constants_138 = require('./constants'); */; +/* removed: var _$ScrollBox_142 = require('./scrollbox'); */; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs - -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// +var _$draw_140 = function draw(gd) { + var fullLayout = gd._fullLayout, + menuData = makeMenuData(fullLayout); -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + /* Update menu data is bound to the header-group. + * The items in the header group are always present. + * + * Upon clicking on a header its corresponding button + * data is bound to the button-group. + * + * We draw all headers in one group before all buttons + * so that the buttons *always* appear above the headers. + * + * Note that only one set of buttons are visible at once. + * + * + * + * + * + * + * + * + * + * ... + * + * + * + * + * ... + */ - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + // draw update menu container + var menus = fullLayout._menulayer + .selectAll('g.' + _$constants_138.containerClassName) + .data(menuData.length > 0 ? [0] : []); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + menus.enter().append('g') + .classed(_$constants_138.containerClassName, true) + .style('cursor', 'pointer'); -var _$BuildLog_17 = BuildLog; + menus.exit().remove(); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // remove push margin object(s) + if(menus.exit().size()) __clearPushMargins_140(gd); -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + // return early if no update menus are visible + if(menuData.length === 0) return; -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // join header group + var headerGroups = menus.selectAll('g.' + _$constants_138.headerGroupClassName) + .data(menuData, __keyFunction_140); - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + headerGroups.enter().append('g') + .classed(_$constants_138.headerGroupClassName, true); - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + // draw dropdown button container + var gButton = _$lib_164.ensureSingle(menus, 'g', _$constants_138.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; + // find dimensions before plotting anything (this mutates menuOpts) + for(var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + __findDimensions_140(gd, menuOpts); + } - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident + // setup scrollbox + var scrollBoxId = 'updatemenus' + fullLayout._uid, + scrollBox = new _$ScrollBox_142(gd, gButton, scrollBoxId); - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; + // remove exiting header, remove dropped buttons and reset margins + if(headerGroups.enter().size()) { + // make sure gButton is on top of all headers + gButton.node().parentNode.appendChild(gButton.node()); - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; + gButton + .call(removeAllButtons) + .attr(_$constants_138.menuIndexAttrName, '-1'); + } - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; + headerGroups.exit().each(function(menuOpts) { + _$d3_6.select(this).remove(); - // categorize where intersection point is along A and B + gButton + .call(removeAllButtons) + .attr(_$constants_138.menuIndexAttrName, '-1'); - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + _$plots_245.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index); + }); - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + // draw headers! + headerGroups.each(function(menuOpts) { + var gHeader = _$d3_6.select(this); - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + var _gButton = menuOpts.type === 'dropdown' ? gButton : null; + _$plots_245.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_140(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + if(menuOpts.type === 'dropdown') { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; -} + // if this menu is active, update the dropdown container + if(__isActive_140(gButton, menuOpts)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts); + } -var _$Epsilon_18 = Epsilon; + }); +}; -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** + * get only visible menus for display + */ +function makeMenuData(fullLayout) { + var contOpts = fullLayout[_$constants_138.name]; + var menuData = []; -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + for(var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + if(item.visible) menuData.push(item); + } - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + return menuData; +} - // 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] }); - } +// Note that '_index' is set at the default step, +// it corresponds to the menu index in the user layout update menu container. +// Because a menu can be set invisible, +// this is a more 'consistent' field than the index in the menuData. +function __keyFunction_140(menuOpts) { + return menuOpts._index; +} - // the first LineString is considered the outside - var out = LineString(coords[0]); +function isFolded(gButton) { + return +gButton.attr(_$constants_138.menuIndexAttrName) === -1; +} - // 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]))); +function __isActive_140(gButton, menuOpts) { + return +gButton.attr(_$constants_138.menuIndexAttrName) === menuOpts._index; +} - return out; - } +function __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + // update 'active' attribute in menuOpts + menuOpts._input.active = menuOpts.active = buttonIndex; - 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'); - }, + if(menuOpts.type === 'buttons') { + drawButtons(gd, gHeader, null, null, menuOpts); + } + else if(menuOpts.type === 'dropdown') { + // fold up buttons and redraw header + gButton.attr(_$constants_138.menuIndexAttrName, '-1'); - // 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)); + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - // 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); - } + if(!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } +} - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = _$lib_164.ensureSingle(gHeader, 'g', _$constants_138.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); - function newNode(region){ - return { - region: region, - children: [] - }; - } + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_138.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; - var roots = newNode(null); + header + .call(drawItem, menuOpts, headerOpts, gd) + .call(setItemPosition, menuOpts, posOpts, positionOverrides); - 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; - } - } + // draw drop arrow at the right edge + var arrow = _$lib_164.ensureSingle(gHeader, 'text', _$constants_138.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_68.font, menuOpts.font) + .text(_$constants_138.arrowSymbol[menuOpts.direction]); + }); - // 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--; - } - } + arrow.attr({ + x: dims.headerWidth - _$constants_138.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_138.textOffsetY + menuOpts.pad.t + }); - // now we can add ourselves - root.children.push(node); - } + header.on('click', function() { + gButton.call(removeAllButtons); - // 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 + // if this menu is active, fold the dropdown container + // otherwise, make this menu active + gButton.attr( + _$constants_138.menuIndexAttrName, + __isActive_140(gButton, menuOpts) ? + -1 : + String(menuOpts._index) + ); - 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; - } + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); - var geopolys = []; + header.on('mouseover', function() { + header.call(styleOnMouseOver); + }); - 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])); - } + header.on('mouseout', function() { + header.call(styleOnMouseOut, menuOpts); + }); - 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); - } + // translate header group + _$drawing_68.setTranslate(gHeader, dims.lx, dims.ly); +} - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + // If this is a set of buttons, set pointer events = all since we play + // some minor games with which container is which in order to simplify + // the drawing of *either* buttons or menus + if(!gButton) { + gButton = gHeader; + gButton.attr('pointer-events', 'all'); + } - // lastly, construct the approrpriate GeoJSON object + var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ? + menuOpts.buttons : + []; - 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 - }; - } -}; + var klass = menuOpts.type === 'dropdown' ? _$constants_138.dropdownButtonClassName : _$constants_138.buttonClassName; -var _$GeoJSON_19 = GeoJSON; + var buttons = gButton.selectAll('g.' + klass) + .data(buttonData); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + var enter = buttons.enter().append('g') + .classed(klass, true); -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + var exit = buttons.exit(); -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; + if(menuOpts.type === 'dropdown') { + enter.attr('opacity', '0') + .transition() + .attr('opacity', '1'); -var _$LinkedList_21 = LinkedList; + exit.transition() + .attr('opacity', '0') + .remove(); + } else { + exit.remove(); + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; -// -// this is the core work-horse -// + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; -/* removed: var _$LinkedList_21 = require('./linked-list'); */; + if(menuOpts.type === 'dropdown') { + if(isVertical) { + y0 = dims.headerHeight + _$constants_138.gapButtonHeader; + } else { + x0 = dims.headerWidth + _$constants_138.gapButtonHeader; + } + } -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { + y0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openHeight; + } - // - // segment creation - // + if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { + x0 = -_$constants_138.gapButtonHeader + _$constants_138.gapButton - dims.openWidth; + } - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: _$constants_138.gapButton, + xPad: _$constants_138.gapButton, + index: 0, + }; - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; - // - // event logic - // + buttons.each(function(buttonOpts, buttonIndex) { + var button = _$d3_6.select(this); - var event_root = _$LinkedList_21.create(); + button + .call(drawItem, menuOpts, buttonOpts, gd) + .call(setItemPosition, menuOpts, posOpts); - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same + button.on('click', function() { + // skip `dragend` events + if(_$d3_6.event.defaultPrevented) return; - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + __setActive_140(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + if(buttonOpts.execute) { + _$plots_245.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); + }); - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + button.on('mouseover', function() { + button.call(styleOnMouseOver); + }); - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_21.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } + button.on('mouseout', function() { + button.call(styleOnMouseOut, menuOpts); + buttons.call(styleButtons, menuOpts); + }); + }); - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_21.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + buttons.call(styleButtons, menuOpts); - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + if(isVertical) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } + else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + } - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) + scrollBoxPosition.direction = menuOpts.direction; - if (buildLog) - buildLog.segmentChop(ev.seg, end); + if(scrollBox) { + if(buttons.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } + else { + hideScrollBox(scrollBox); + } + } +} - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + // enable the scrollbox + var direction = menuOpts.direction; + var isVertical = (direction === 'up' || direction === 'down'); + var dims = menuOpts._dims; - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } + var active = menuOpts.active, + translateX, translateY, + i; + if(isVertical) { + translateY = 0; + for(i = 0; i < active; i++) { + translateY += dims.heights[i] + _$constants_138.gapButton; + } + } + else { + translateX = 0; + for(i = 0; i < active; i++) { + translateX += dims.widths[i] + _$constants_138.gapButton; + } + } - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used + scrollBox.enable(position, translateX, translateY); - // - // status logic - // + if(scrollBox.hbar) { + scrollBox.hbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } - var status_root = _$LinkedList_21.create(); + if(scrollBox.vbar) { + scrollBox.vbar + .attr('opacity', '0') + .transition() + .attr('opacity', '1'); + } +} - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar, + hasVBar = !!scrollBox.vbar; - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } + if(hasHBar) { + scrollBox.hbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasHBar = false; + if(!hasVBar) scrollBox.disable(); + }); + } - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + if(hasVBar) { + scrollBox.vbar + .transition() + .attr('opacity', '0') + .each('end', function() { + hasVBar = false; + if(!hasHBar) scrollBox.disable(); + }); + } +} - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts) + .call(drawItemText, menuOpts, itemOpts, gd); +} - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; +function drawItemRect(item, menuOpts) { + var rect = _$lib_164.ensureSingle(item, 'rect', _$constants_138.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_138.rx, + ry: _$constants_138.ry, + 'shape-rendering': 'crispEdges' + }); + }); - if (buildLog) - buildLog.checkIntersection(seg1, seg2); + rect.call(_$color_43.stroke, menuOpts.bordercolor) + .call(_$color_43.fill, menuOpts.bgcolor) + .style('stroke-width', menuOpts.borderwidth + 'px'); +} - var i = eps.linesIntersect(a1, a2, b1, b2); +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = _$lib_164.ensureSingle(item, 'text', _$constants_138.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); - if (i === false){ - // segments are parallel or coincident + text.call(_$drawing_68.font, menuOpts.font) + .text(itemOpts.label) + .call(_$svg_text_utils_185.convertToTspans, gd); +} - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) +function styleButtons(buttons, menuOpts) { + var active = menuOpts.active; - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection + buttons.each(function(buttonOpts, i) { + var button = _$d3_6.select(this); - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); + if(i === active && menuOpts.showactive) { + button.select('rect.' + _$constants_138.itemRectClassName) + .call(_$color_43.fill, _$constants_138.activeColor); + } + }); +} - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal +function styleOnMouseOver(item) { + item.select('rect.' + _$constants_138.itemRectClassName) + .call(_$color_43.fill, _$constants_138.hoverColor); +} - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); +function styleOnMouseOut(item, menuOpts) { + item.select('rect.' + _$constants_138.itemRectClassName) + .call(_$color_43.fill, menuOpts.bgcolor); +} - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); - - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } +// find item dimensions (this mutates menuOpts) +function __findDimensions_140(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + var fakeButtons = _$drawing_68.tester.selectAll('g.' + _$constants_138.dropdownButtonClassName) + .data(menuOpts.buttons); - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + fakeButtons.enter().append('g') + .classed(_$constants_138.dropdownButtonClassName, true); - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); + // loop over fake buttons to find width / height + fakeButtons.each(function(buttonOpts, i) { + var button = _$d3_6.select(this); - if (buildLog) - buildLog.vert(ev.pt[0]); + button.call(drawItem, menuOpts, buttonOpts, gd); - if (ev.isStart){ + var text = button.select('.' + _$constants_138.itemTextClassName); - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + // width is given by max width of all buttons + var tWidth = text.node() && _$drawing_68.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_138.textPadX, _$constants_138.minWidth); - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + // height is determined by item text + var tHeight = menuOpts.font.size * __LINE_SPACING_140; + var tLines = _$svg_text_utils_185.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_138.minHeight) + _$constants_138.textOffsetY; - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } + // Store per-item sizes since a row of horizontal buttons, for example, + // don't all need to be the same width: + dims.widths[i] = wEff; + dims.heights[i] = hEff; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev + // Height and width of individual element: + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); - // merge ev.seg's fill information into eve.seg + if(isVertical) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + _$constants_138.gapButton; + dims.openHeight += hEff + _$constants_138.gapButton; + } else { + dims.totalWidth += wEff + _$constants_138.gapButton; + dims.openWidth += wEff + _$constants_138.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + if(isVertical) { + dims.totalHeight -= _$constants_138.gapButton; + } else { + dims.totalWidth -= _$constants_138.gapButton; + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } - if (buildLog) - buildLog.segmentUpdate(eve.seg); + dims.headerWidth = dims.width1 + _$constants_138.arrowPadX; + dims.headerHeight = dims.height1; - ev.other.remove(); - ev.remove(); - } + if(menuOpts.type === 'dropdown') { + if(isVertical) { + dims.width1 += _$constants_138.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += _$constants_138.arrowPadX; + } - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } + fakeButtons.remove(); - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var xanchor = 'left'; + if(_$anchor_utils_95.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = 'right'; + } + if(_$anchor_utils_95.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = 'center'; + } - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + var yanchor = 'top'; + if(_$anchor_utils_95.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = 'bottom'; + } + if(_$anchor_utils_95.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = 'middle'; + } - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_21.node({ ev: ev })); - } - else{ - var st = ev.status; + _$plots_245.autoMargin(gd, _$constants_138.autoMarginIdRoot + menuOpts._index, { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), + r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0), + b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0), + t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0) + }); +} - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } +// set item positions (mutates posOpts) +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect = item.select('.' + _$constants_138.itemRectClassName); + var text = item.select('.' + _$constants_138.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index = posOpts.index; + var dims = menuOpts._dims; - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); + _$drawing_68.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); - if (buildLog) - buildLog.statusRemove(st.ev.seg); + var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); - // remove the status - st.remove(); + rect.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]), + height: finalHeight + }); - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } + var tHeight = menuOpts.font.size * __LINE_SPACING_140; + var tLines = _$svg_text_utils_185.lineCount(text); + var spanOffset = ((tLines - 1) * tHeight / 2); - // remove the event and continue - event_root.getHead().remove(); - } + _$svg_text_utils_185.positionText(text, _$constants_138.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_138.textOffsetY); - if (buildLog) - buildLog.done(); + if(isVertical) { + posOpts.y += dims.heights[index] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index] + posOpts.xPad; + } - return segments; - } + posOpts.index++; +} - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } +function removeAllButtons(gButton) { + gButton.selectAll('g.' + _$constants_138.dropdownButtonClassName).remove(); +} - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; +function __clearPushMargins_140(gd) { + var pushMargins = gd._fullLayout._pushmargin || {}; + var keys = Object.keys(pushMargins); - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + for(var i = 0; i < keys.length; i++) { + var k = keys[i]; - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; + if(k.indexOf(_$constants_138.autoMarginIdRoot) !== -1) { + _$plots_245.autoMargin(gd, k); + } + } } -var _$Intersecter_20 = Intersecter; - -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// +'use strict'; -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; +/* removed: var _$constants_138 = require('./constants'); */; - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } +var _$updatemenus_141 = { + moduleType: 'component', + name: _$constants_138.name, - if (buildLog) - buildLog.chainStart(seg); + layoutAttributes: _$attributes_137, + supplyLayoutDefaults: _$updateMenusDefaults_139, - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + draw: _$draw_140 +}; - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } +var _$mathjax_config_149 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (next_match === second_match){ - // we matched a single chain +'use strict'; - if (buildLog) - buildLog.chainMatch(first_match.index); +/* global MathJax:false */ - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop - - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head +/** + * Check and configure MathJax + */ +if(typeof MathJax !== 'undefined') { + _$mathjax_config_149.MathJax = true; - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + MathJax.Hub.Config({ + messageStyle: 'none', + skipStartupTypeset: true, + displayAlign: 'left', + tex2jax: { + inlineMath: [['$', '$'], ['\\(', '\\)']] + } + }); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + MathJax.Hub.Configured(); +} else { + _$mathjax_config_149.MathJax = false; +} - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } - if (buildLog) - buildLog.chainClose(first_match.index); +'use strict'; - // we have a closed chain! - regions.push(chain); - return; - } +/* removed: var _$lib_164 = require('../lib'); */; +/* removed: var _$plot_config_196 = require('../plot_api/plot_config'); */; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } - // otherwise, we matched two chains, so we need to combine those chains together +/** + * Copy arg array *without* removing `undefined` values from objects. + * + * @param gd + * @param args + * @returns {Array} + */ +function copyArgArray(gd, args) { + var copy = []; + var arg; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + for(var i = 0; i < args.length; i++) { + arg = args[i]; - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + if(arg === gd) copy[i] = arg; + else if(typeof arg === 'object') { + copy[i] = Array.isArray(arg) ? + _$lib_164.extendDeep([], arg) : + _$lib_164.extendDeepAll({}, arg); + } + else copy[i] = arg; + } - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + return copy; +} - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } +// ----------------------------------------------------- +// Undo/Redo queue for plots +// ----------------------------------------------------- - var F = first_match.index; - var S = second_match.index; - if (buildLog) - buildLog.chainConnect(F, S); +var __queue_178 = {}; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); +// TODO: disable/enable undo and redo buttons appropriately - return regions; -} +/** + * Add an item to the undoQueue for a graphDiv + * + * @param gd + * @param undoFunc Function undo this operation + * @param undoArgs Args to supply undoFunc with + * @param redoFunc Function to redo this operation + * @param redoArgs Args to supply redoFunc with + */ +__queue_178.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, + queueIndex; -var _$SegmentChainer_22 = SegmentChainer; + // make sure we have the queue and our position in it + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + queueIndex = gd.undoQueue.index; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // if we're already playing an undo or redo, or if this is an auto operation + // (like pane resize... any others?) then we don't save this to the undo queue + if(gd.autoplay) { + if(!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } -// -// filter a list of segments based on boolean operations -// + // if we're not in a sequence or are just starting, we need a new queue item + if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}}; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + // we unshift to handle calls for undo in a forward for loop later + if(queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } - if (buildLog) - buildLog.selected(result); + if(gd.undoQueue.queue.length > _$plot_config_196.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; - return result; -} +/** + * Begin a sequence of undoQueue changes + * + * @param gd + */ +__queue_178.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } +/** + * Stop a sequence of undoQueue changes + * + * Call this *after* you're sure your undo chain has ended + * + * @param gd + */ +__queue_178.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; }; -var _$SegmentSelector_23 = SegmentSelector; +/** + * Move one step back in the undo queue, and undo the object there. + * + * @param gd + */ +__queue_178.undo = function undo(gd) { + var queueObj, i; -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs + if(gd.framework && gd.framework.isPolar) { + gd.framework.undo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index <= 0) { + return; + } + + // index is pointing to next *forward* queueObj, point to the one we're undoing + gd.undoQueue.index--; + + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.undo.calls.length; i++) { + __queue_178.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; + +/** + * Redo the current object in the undo, then move forward in the queue. + * + * @param gd */ +__queue_178.redo = function redo(gd) { + var queueObj, i; -/* removed: var _$BuildLog_17 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_18 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_20 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_22 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_23 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_19 = require('./lib/geojson'); */; + if(gd.framework && gd.framework.isPolar) { + gd.framework.redo(); + return; + } + if(gd.undoQueue === undefined || + isNaN(gd.undoQueue.index) || + gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } -var buildLog = false; -var epsilon = _$Epsilon_18(); + // get the queueObj for instructions on how to undo + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_17(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + // this sequence keeps things from adding to the queue during undo/redo + gd.undoQueue.inSequence = true; + for(i = 0; i < queueObj.redo.calls.length; i++) { + __queue_178.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; - // core API - segments: function(poly){ - var i = _$Intersecter_20(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_20(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_23.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_23.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_23.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_23.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_23.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_22(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, + // index is pointing to the thing we just redid, move it + gd.undoQueue.index++; +}; - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_19.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_19.fromPolygon(PolyBool, epsilon, poly); - }, +/** + * Called by undo/redo to make the actual changes. + * + * Not meant to be called publically, but included for mocking out in tests. + * + * @param gd + * @param func + * @param args + */ +__queue_178.plotDo = function(gd, func, args) { + gd.autoplay = true; - // 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); - } + // this *won't* copy gd and it preserves `undefined` properties! + args = copyArgArray(gd, args); + + // call the supplied function + func.apply(null, args); }; -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); +var _$queue_178 = __queue_178; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$localeEnUs_188 = { + moduleType: 'locale', + name: 'en-US', + dictionary: { + 'Click to enter Colorscale title': 'Click to enter Colorscale title' + }, + format: { + date: '%m/%d/%Y' + } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$localeEn_189 = { + 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' + } +}; + +var _$fromQuat_10 = 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; +}; +var _$helpers_192 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_10 = require('gl-mat4/fromQuat'); */; + +/* removed: var _$registry_254 = require('../registry'); */; +/* removed: var _$lib_164 = require('../lib'); */; +/* removed: var _$plots_245 = require('../plots/plots'); */; +/* removed: var _$axis_ids_209 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_209.cleanId; +var getFromTrace = _$axis_ids_209.getFromTrace; +/* removed: var _$color_43 = require('../components/color'); */; + + +// clear the promise queue if one of them got rejected +_$helpers_192.clearPromiseQueue = function(gd) { + if(Array.isArray(gd._promises) && gd._promises.length > 0) { + _$lib_164.log('Clearing previous rejected promises from queue.'); + } + + gd._promises = []; +}; + +// make a few changes to the layout right away +// before it gets used for anything +// backward compatibility and cleanup of nonstandard options +_$helpers_192.cleanLayout = function(layout) { + var i, j; + + if(!layout) layout = {}; + + // cannot have (x|y)axis1, numbering goes axis, axis2, axis3... + if(layout.xaxis1) { + if(!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if(layout.yaxis1) { + if(!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if(layout.scene1) { + if(!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } + + var axisAttrRegex = (_$plots_245.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_245.subplotsRegistry.gl3d || {}).attrRegex; + + var keys = Object.keys(layout); + for(i = 0; i < keys.length; i++) { + var key = keys[i]; + + // modifications to cartesian axes + if(axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if(ax.anchor && ax.anchor !== 'free') { + ax.anchor = cleanId(ax.anchor); + } + if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + + // old method of axis type - isdate and islog (before category existed) + if(!ax.type) { + if(ax.isdate) ax.type = 'date'; + else if(ax.islog) ax.type = 'log'; + else if(ax.isdate === false && ax.islog === false) ax.type = 'linear'; + } + if(ax.autorange === 'withzero' || ax.autorange === 'tozero') { + ax.autorange = true; + ax.rangemode = 'tozero'; + } + delete ax.islog; + delete ax.isdate; + delete ax.categories; // replaced by _categories + + // prune empty domain arrays made before the new nestedProperty + if(emptyContainer(ax, 'domain')) delete ax.domain; + + // autotick -> tickmode + if(ax.autotick !== undefined) { + if(ax.tickmode === undefined) { + ax.tickmode = ax.autotick ? 'auto' : 'linear'; + } + delete ax.autotick; + } + } + + // modifications for 3D scenes + else if(sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; + + // clean old Camera coords + var cameraposition = scene.cameraposition; + + if(Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0], + center = cameraposition[1], + radius = cameraposition[2], + mat = _$fromQuat_10([], rotation), + eye = []; + + for(j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } + + scene.camera = { + eye: {x: eye[0], y: eye[1], z: eye[2]}, + center: {x: center[0], y: center[1], z: center[2]}, + up: {x: mat[1], y: mat[5], z: mat[9]} + }; + + delete scene.cameraposition; + } + } + } + + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for(i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; + + if(!_$lib_164.isPlainObject(ann)) continue; + + if(ann.ref) { + if(ann.ref === 'paper') { + ann.xref = 'paper'; + ann.yref = 'paper'; + } + else if(ann.ref === 'data') { + ann.xref = 'x'; + ann.yref = 'y'; + } + delete ann.ref; + } + + cleanAxRef(ann, 'xref'); + cleanAxRef(ann, 'yref'); + } + + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for(i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; + + if(!_$lib_164.isPlainObject(shape)) continue; + + cleanAxRef(shape, 'xref'); + cleanAxRef(shape, 'yref'); + } + + var legend = layout.legend; + if(legend) { + // check for old-style legend positioning (x or y is +/- 100) + if(legend.x > 3) { + legend.x = 1.02; + legend.xanchor = 'left'; + } + else if(legend.x < -2) { + legend.x = -0.02; + legend.xanchor = 'right'; + } + + if(legend.y > 3) { + legend.y = 1.02; + legend.yanchor = 'bottom'; + } + else if(legend.y < -2) { + legend.y = -0.02; + legend.yanchor = 'top'; + } + } + + /* + * Moved from rotate -> orbit for dragmode + */ + if(layout.dragmode === 'rotate') layout.dragmode = 'orbit'; + + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_43.clean(layout); + + return layout; +}; + +function cleanAxRef(container, attr) { + var valIn = container[attr], + axLetter = attr.charAt(0); + if(valIn && valIn !== 'paper') { + container[attr] = cleanId(valIn, axLetter); + } } -if (typeof window === 'object') - window.PolyBool = PolyBool; +/* + * cleanData: Make a few changes to the data right away + * before it gets used for anything + * Mostly for backward compatibility, modifies the data traces users provide. + * + * Important: if you're going to add something here that modifies a data array, + * update it in place so the new array === the old one. + */ +_$helpers_192.cleanData = function(data, existingData) { + // Enforce unique IDs + var suids = [], // seen uids --- so we can weed out incoming repeats + uids = data.concat(Array.isArray(existingData) ? existingData : []) + .filter(function(trace) { return 'uid' in trace; }) + .map(function(trace) { return trace.uid; }); + + for(var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; + + // assign uids to each trace and detect collisions. + if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) { + var newUid; + + for(i = 0; i < 100; i++) { + newUid = _$lib_164.randstr(uids); + if(suids.indexOf(newUid) === -1) break; + } + trace.uid = _$lib_164.randstr(uids); + uids.push(trace.uid); + } + // keep track of already seen uids, so that if there are + // doubles we force the trace with a repeat uid to + // acquire a new one + suids.push(trace.uid); + + // BACKWARD COMPATIBILITY FIXES + + // use xbins to bin data in x, and ybins to bin data in y + if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } + + // error_y.opacity is obsolete - merge into color + if(trace.error_y && 'opacity' in trace.error_y) { + var dc = _$color_43.defaults, + yeColor = trace.error_y.color || + (_$registry_254.traceIs(trace, 'bar') ? _$color_43.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_43.addOpacity( + _$color_43.rgb(yeColor), + _$color_43.opacity(yeColor) * trace.error_y.opacity); + delete trace.error_y.opacity; + } + + // convert bardir to orientation, and put the data into + // the axes it's eventually going to be used with + if('bardir' in trace) { + if(trace.bardir === 'h' && (_$registry_254.traceIs(trace, 'bar') || + trace.type.substr(0, 9) === 'histogram')) { + trace.orientation = 'h'; + _$helpers_192.swapXYData(trace); + } + delete trace.bardir; + } + + // now we have only one 1D histogram type, and whether + // it uses x or y data depends on trace.orientation + if(trace.type === 'histogramy') _$helpers_192.swapXYData(trace); + if(trace.type === 'histogramx' || trace.type === 'histogramy') { + trace.type = 'histogram'; + } + + // scl->scale, reversescl->reversescale + if('scl' in trace) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if('reversescl' in trace) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } + + // axis ids x1 -> x, y1-> y + if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x'); + if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); + + // scene ids scene1 -> scene + if(_$registry_254.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_245.subplotsRegistry.gl3d.cleanId(trace.scene); + } + + if(!_$registry_254.traceIs(trace, 'pie') && !_$registry_254.traceIs(trace, 'bar')) { + if(Array.isArray(trace.textposition)) { + for(i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } + else if(trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } + + // fix typo in colorscale definition + if(_$registry_254.traceIs(trace, '2dMap')) { + if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; + if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; + } + if(_$registry_254.traceIs(trace, 'markerColorscale') && trace.marker) { + var cont = trace.marker; + if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; + if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; + } + + // fix typo in surface 'highlight*' definitions + if(trace.type === 'surface' && _$lib_164.isPlainObject(trace.contours)) { + var dims = ['x', 'y', 'z']; + + for(i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; + + if(!_$lib_164.isPlainObject(opts)) continue; + + if(opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } + + if(opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } + } + + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); + + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names + + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } + + // transforms backward compatibility fixes + if(Array.isArray(trace.transforms)) { + var transforms = trace.transforms; + + for(i = 0; i < transforms.length; i++) { + var transform = transforms[i]; + + if(!_$lib_164.isPlainObject(transform)) continue; + + switch(transform.type) { + case 'filter': + if(transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } + + if(transform.calendar) { + if(!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; + + case 'groupby': + // Name has changed from `style` to `styles`, so use `style` but prefer `styles`: + transform.styles = transform.styles || transform.style; + + if(transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); + + transform.styles = []; + for(var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } + } + + // prune empty containers made before the new nestedProperty + if(emptyContainer(trace, 'line')) delete trace.line; + if('marker' in trace) { + if(emptyContainer(trace.marker, 'line')) delete trace.marker.line; + if(emptyContainer(trace, 'marker')) delete trace.marker; + } + + // sanitize rgb(fractions) and rgba(fractions) that old tinycolor + // supported, but new tinycolor does not because they're not valid css + _$color_43.clean(trace); + } +}; + +function cleanFinanceDir(dirContainer) { + if(!_$lib_164.isPlainObject(dirContainer)) return false; + + var dirName = dirContainer.name; + + delete dirContainer.name; + delete dirContainer.showlegend; + + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); +} + +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; + + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; + + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } + + var out = name1.substr(0, i); + return out.trim(); +} + +// textposition - support partial attributes (ie just 'top') +// and incorrect use of middle / center etc. +function cleanTextPosition(textposition) { + var posY = 'middle', + posX = 'center'; + if(textposition.indexOf('top') !== -1) posY = 'top'; + else if(textposition.indexOf('bottom') !== -1) posY = 'bottom'; + + if(textposition.indexOf('left') !== -1) posX = 'left'; + else if(textposition.indexOf('right') !== -1) posX = 'right'; + + return posY + ' ' + posX; +} + +function emptyContainer(outer, innerStr) { + return (innerStr in outer) && + (typeof outer[innerStr] === 'object') && + (Object.keys(outer[innerStr]).length === 0); +} + + +// swap all the data and data attributes associated with x and y +_$helpers_192.swapXYData = function(trace) { + var i; + _$lib_164.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if(trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if(trace.error_x && trace.error_y) { + var errorY = trace.error_y, + copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : + !(errorY.color || errorY.thickness || errorY.width); + _$lib_164.swapAttrs(trace, ['error_?.copy_ystyle']); + if(copyYstyle) { + _$lib_164.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + } + } + if(typeof trace.hoverinfo === 'string') { + var hoverInfoParts = trace.hoverinfo.split('+'); + for(i = 0; i < hoverInfoParts.length; i++) { + if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y'; + else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x'; + } + trace.hoverinfo = hoverInfoParts.join('+'); + } +}; + +// coerce traceIndices input to array of trace indices +_$helpers_192.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_9(traceIndices)) { + return [traceIndices]; + } + else if(!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_, i) { return i; }); + } + + return traceIndices; +}; + +/** + * Manages logic around array container item creation / deletion / update + * that nested property alone can't handle. + * + * @param {Object} np + * nested property of update attribute string about trace or layout object + * @param {*} newVal + * update value passed to restyle / relayout / update + * @param {Object} undoit + * undo hash (N.B. undoit may be mutated here). + * + */ +_$helpers_192.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj, + parts = np.parts, + pLength = parts.length, + pLast = parts[pLength - 1]; + + var pLastIsNumber = _$fastIsnumeric_9(pLast); + + // delete item + if(pLastIsNumber && newVal === null) { + + // Clear item in array container when new value is null + var contPath = parts.slice(0, pLength - 1).join('.'), + cont = _$lib_164.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); + + // Note that nested property clears null / undefined at end of + // array container, but not within them. + } + // create item + else if(pLastIsNumber && np.get() === undefined) { + + // When adding a new item, make sure undo command will remove it + if(np.get() === undefined) undoit[np.astr] = null; + + np.set(newVal); + } + // update item + else { + + // If the last part of attribute string isn't a number, + // np.set is all we need. + np.set(newVal); + } +}; + +/* + * Match the part to strip off to turn an attribute into its parent + * really it should be either '.some_characters' or '[number]' + * but we're a little more permissive here and match either + * '.not_brackets_or_dot' or '[not_brackets_or_dot]' + */ +var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + +function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if(tail > 0) return attr.substr(0, tail); +} + +/* + * hasParent: does an attribute object contain a parent of the given attribute? + * for example, given 'images[2].x' do we also have 'images' or 'images[2]'? + * + * @param {Object} aobj + * update object, whose keys are attribute strings and values are their new settings + * @param {string} attr + * the attribute string to test against + * @returns {Boolean} + * is a parent of attr present in aobj? + */ +_$helpers_192.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while(attrParent) { + if(attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; +}; + +/** + * Empty out types for all axes containing these traces so we auto-set them again + * + * @param {object} gd + * @param {[integer]} traces: trace indices to search for axes to clear the types of + * @param {object} layoutUpdate: any update being done concurrently to the layout, + * which may supercede clearing the axis types + */ +var __axLetters_192 = ['x', 'y', 'z']; +_$helpers_192.clearAxisTypes = function(gd, traces, layoutUpdate) { + for(var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for(var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, __axLetters_192[j]); + + // do not clear log type - that's never an auto result so must have been intentional + if(ax && ax.type !== 'log') { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if(sceneName.substr(0, 5) === 'scene') { + if(layoutUpdate[sceneName] !== undefined) continue; + axAttr = sceneName + '.' + axAttr; + } + var typeAttr = axAttr + '.type'; -var _$PolyBool_16 = PolyBool; + if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { + _$lib_164.nestedProperty(gd.layout, typeAttr).set(null); + } + } + } + } +}; + +_$helpers_192.clearAxisAutomargins = function(gd) { + var keys = Object.keys(gd._fullLayout._pushmargin); + for(var i = 0; i < keys.length; i++) { + if(keys[i].indexOf('automargin') !== -1) { + delete gd._fullLayout._pushmargin[keys[i]]; + } + } +}; -var _$polygon_175 = {}; +var _$manage_arrays_194 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49630,293 +50825,209 @@ var _$polygon_175 = {}; 'use strict'; -var dot = _$matrix_169.dot; -var __BADNUM_175 = _$numerical_145.BADNUM; - -var polygon = _$polygon_175 = {}; +/* removed: var _$nestedProperty_172 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_166 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_173 = require('../lib/noop'); */; +/* removed: var _$loggers_169 = require('../lib/loggers'); */; +var sorterAsc = _$search_182.sorterAsc; +/* removed: var _$registry_254 = require('../registry'); */; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; +_$manage_arrays_194.containerArrayMatch = _$containerArrayMatch_190; - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } +var isAddVal = _$manage_arrays_194.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_166(val); +}; - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed +var isRemoveVal = _$manage_arrays_194.isRemoveVal = function isRemoveVal(val) { + return val === null || val === 'remove'; +}; - var isRect = false, - rectFirstEdgeTest; +/* + * applyContainerArrayChanges: for managing arrays of layout components in relayout + * handles them all with a consistent interface. + * + * Here are the supported actions -> relayout calls -> edits we get here + * (as prepared in _relayout): + * + * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}} + * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}} + * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}} + * -> {'annotations[2]': null} -> {2: {'': null}} + * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}} + * -> {'annotations': null} -> {'': {'': null}} + * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}} + * + * You can combine many edits to different objects. Objects are added and edited + * in ascending order, then removed in descending order. + * For example, starting with [a, b, c], if you want to: + * - replace b with d: + * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d) + * - add a new item d between a and b, and edit b: + * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d) + * - delete b and edit c: + * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed) + * + * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i` + * You CANNOT combine replacing/deleting the whole array with anything else (for the same array). + * + * @param {HTMLDivElement} gd + * the DOM element of the graph container div + * @param {Lib.nestedProperty} componentType: the array we are editing + * @param {Object} edits + * the changes to make; keys are indices to edit, values are themselves objects: + * {attr: newValue} of changes to make to that index (with add/remove behavior + * in special values of the empty attr) + * @param {Object} flags + * the flags for which actions we're going to perform to display these (and + * any other) changes. If we're already `recalc`ing, we don't need to redraw + * individual items + * + * @returns {bool} `true` if it managed to complete drawing of the changes + * `false` would mean the parent should replot. + */ +_$manage_arrays_194.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { + var componentType = np.astr, + supplyComponentDefaults = _$registry_254.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_254.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_254.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_173) || + (draw === _$noop_173), + layout = gd.layout, + fullLayout = gd._fullLayout; - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } + if(edits['']) { + if(Object.keys(edits).length > 1) { + _$loggers_169.warn('Full array edits are incompatible with other edits', + componentType); } - } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var fullVal = edits['']['']; - if(x === __BADNUM_175 || x < xmin || x > xmax || y === __BADNUM_175 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; + if(isRemoveVal(fullVal)) np.set(null); + else if(Array.isArray(fullVal)) np.set(fullVal); + else { + _$loggers_169.warn('Unrecognized full array edit value', componentType, fullVal); + return true; } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + if(replotLater) return false; + + supplyComponentDefaults(layout, fullLayout); + draw(gd); return true; } - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc), + componentArrayIn = np.get(), + componentArray = componentArrayIn || [], + // componentArrayFull is used just to keep splices in line between + // full and input arrays, so private keys can be copied over after + // redoing supplyDefaults + // TODO: this assumes componentArray is in gd.layout - which will not be + // true after we extend this to restyle + componentArrayFull = _$nestedProperty_172(fullLayout, componentType).get(); - if(x === __BADNUM_175 || x < xmin || x > xmax || y === __BADNUM_175 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + var deletes = [], + firstIndexChange = -1, + maxIndex = componentArray.length, + i, + j, + componentNum, + objEdits, + objKeys, + objVal, + adding; - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + // first make the add and edit changes + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[''], + adding = isAddVal(objVal); - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + _$loggers_169.warn('index out of range', componentType, componentNum); + continue; + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; + if(objVal !== undefined) { + if(objKeys.length > 1) { + _$loggers_169.warn( + 'Insertion & removal are incompatible with edits to the same index.', + componentType, componentNum); } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; + + if(isRemoveVal(objVal)) { + deletes.push(componentNum); + } + else if(adding) { + if(objVal === 'add') objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } - // inside the bounding box, check the actual line intercept else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } - - if(y <= ycross && x !== xmini) crossings++; + _$loggers_169.warn('Unrecognized full object edit value', + componentType, componentNum, objVal); } - } - - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; + if(firstIndexChange === -1) firstIndexChange = componentNum; } - } - - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; - -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; - - for(var i = 0; i < list.length; i++) { - 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); - } - - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; + else { + for(j = 0; j < objKeys.length; j++) { + _$nestedProperty_172(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } - - return yes; } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; - -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; - - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); - - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; + // now do deletes + for(i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + // TODO: this drops private keys that had been stored in componentArrayFull + // does this have any ill effects? + if(componentArrayFull) componentArrayFull.splice(deletes[i], 1); } - return false; -}; -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; + if(!componentArray.length) np.set(null); + else if(!componentArrayIn) np.set(componentArray); - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); + if(replotLater) return false; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; + supplyComponentDefaults(layout, fullLayout); + + // finally draw all the components we need to + // if we added or removed any, redraw all after it + if(drawOne !== _$noop_173) { + var indicesToDraw; + if(firstIndexChange === -1) { + // there's no re-indexing to do, so only redraw components that changed + indicesToDraw = componentNums; + } + else { + // in case the component array was shortened, we still need do call + // drawOne on the latter items so they get properly removed + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for(i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if(componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for(i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); } } + for(i = 0; i < indicesToDraw.length; i++) { + drawOne(gd, indicesToDraw[i]); + } } + else draw(gd); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); - } - - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; + return true; }; +var _$buttons_105 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49928,1483 +51039,1166 @@ polygon.filter = function filter(pts, tolerance) { 'use strict'; -/* removed: var _$PolyBool_16 = require('polybooljs'); */; -/* removed: var _$polygon_175 = require('../../lib/polygon'); */; -/* removed: var _$throttle_185 = require('../../lib/throttle'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -var makeEventData = _$helpers_82.makeEventData; -/* removed: var _$fx_85 = require('../../components/fx'); */; - -/* removed: var _$axes_205 = require('./axes'); */; -/* removed: var _$constants_210 = require('./constants'); */; - -var filteredPolygon = _$polygon_175.filter; -var polygonTester = _$polygon_175.tester; -var multipolygonTester = _$polygon_175.multitester; -var MINSELECT = _$constants_210.MINSELECT; - -function getAxId(ax) { return ax._id; } - -var _$prepSelect_223 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } - - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_210.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'); +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$plots_245 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_209 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_43.background, - stroke: _$color_43.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +var ____105 = _$lib_164._; +var modeBarButtons = _$buttons_105 = {}; - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_210.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; +/** + * 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? + */ - 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; +modeBarButtons.toImage = { + name: 'toImage', + title: function(gd) { return ____105(gd, 'Download plot as a png'); }, + icon: _$ploticon_2.camera, + click: function(gd) { + var format = 'png'; - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + _$lib_164.notifier(____105(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_205.getFromId(gd, trace.xaxis), - yaxis: _$axes_205.getFromId(gd, trace.yaxis) - }); + if(_$lib_164.isIE()) { + _$lib_164.notifier(____105(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + format = 'svg'; } - } - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + _$registry_254.call('downloadImage', gd, {'format': format}) + .then(function(filename) { + _$lib_164.notifier(____105(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + }) + .catch(function() { + _$lib_164.notifier(____105(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + }); } +}; - function ascending(a, b) { return a - b; } +modeBarButtons.sendDataToCloud = { + name: 'sendDataToCloud', + title: function(gd) { return ____105(gd, 'Edit in Chart Studio'); }, + icon: _$ploticon_2.disk, + click: function(gd) { + _$plots_245.sendDataToCloud(gd); + } +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +modeBarButtons.zoom2d = { + name: 'zoom2d', + title: function(gd) { return ____105(gd, 'Zoom'); }, + attr: 'dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleCartesian +}; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; +modeBarButtons.pan2d = { + name: 'pan2d', + title: function(gd) { return ____105(gd, 'Pan'); }, + attr: 'dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); +modeBarButtons.select2d = { + name: 'select2d', + title: function(gd) { return ____105(gd, 'Box Select'); }, + attr: 'dragmode', + val: 'select', + icon: _$ploticon_2.selectbox, + click: handleCartesian +}; - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; +modeBarButtons.lasso2d = { + name: 'lasso2d', + title: function(gd) { return ____105(gd, 'Lasso Select'); }, + attr: 'dragmode', + val: 'lasso', + icon: _$ploticon_2.lasso, + click: handleCartesian +}; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } - } +modeBarButtons.zoomIn2d = { + name: 'zoomIn2d', + title: function(gd) { return ____105(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleCartesian +}; - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); +modeBarButtons.zoomOut2d = { + name: 'zoomOut2d', + title: function(gd) { return ____105(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleCartesian +}; - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); +modeBarButtons.autoScale2d = { + name: 'autoScale2d', + title: function(gd) { return ____105(gd, 'Autoscale'); }, + attr: 'zoom', + val: 'auto', + icon: _$ploticon_2.autoscale, + click: handleCartesian +}; - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); +modeBarButtons.resetScale2d = { + name: 'resetScale2d', + title: function(gd) { return ____105(gd, 'Reset axes'); }, + attr: 'zoom', + val: 'reset', + icon: _$ploticon_2.home, + click: handleCartesian +}; - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } +modeBarButtons.hoverClosestCartesian = { + name: 'hoverClosestCartesian', + title: function(gd) { return ____105(gd, 'Show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleCartesian +}; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } +modeBarButtons.hoverCompareCartesian = { + name: 'hoverCompareCartesian', + title: function(gd) { return ____105(gd, 'Compare data on hover'); }, + attr: 'hovermode', + val: function(gd) { + return gd._fullLayout._isHoriz ? 'y' : 'x'; + }, + icon: _$ploticon_2.tooltip_compare, + gravity: 'ne', + click: handleCartesian +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +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 = _$axis_ids_209.list(gd, null, true); + var allSpikesEnabled = 'on'; - _$throttle_185.throttle( - throttleID, - _$constants_210.SELECTDELAY, - function() { - selection = []; + var ax, i; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; + if(astr === 'zoom') { + var mag = (val === 'in') ? 0.5 : 2, + r0 = (1 + mag) / 2, + r1 = (1 - mag) / 2; - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); + var axName; - thisSelection = fillSelectionItem(traceSelection, searchInfo); + for(i = 0; i < axList.length; i++) { + ax = axList[i]; - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); + 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]; + } + if(ax._showSpikeInitial !== undefined) { + aobj[axName + '.showspikes'] = ax._showSpikeInitial; + if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) { + allSpikesEnabled = 'off'; } } - else selection = thisSelection; } + else { + var rangeNow = [ + ax.r2l(ax.range[0]), + ax.r2l(ax.range[1]), + ]; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; - - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; - _$throttle_185.done(throttleID).then(function() { - _$throttle_185.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); + aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]); + aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]); } - - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); } - else { - // 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. - gd.emit('plotly_selected', undefined); + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } + 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); + } else if(astr === 'hovermode' && val === 'closest') { + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(allSpikesEnabled === 'on' && !ax.showspikes) { + allSpikesEnabled = 'off'; + } } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + } - _$fx_85.click(gd, evt); - }); - }; - - dragOptions.doneFn = function() { - corners.remove(); + aobj[astr] = val; + } - _$throttle_185.done(throttleID).then(function() { - _$throttle_185.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); + _$registry_254.call('relayout', gd, aobj); +} - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +modeBarButtons.zoom3d = { + name: 'zoom3d', + title: function(gd) { return ____105(gd, 'Zoom'); }, + attr: 'scene.dragmode', + val: 'zoom', + icon: _$ploticon_2.zoombox, + click: handleDrag3d +}; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +modeBarButtons.pan3d = { + name: 'pan3d', + title: function(gd) { return ____105(gd, 'Pan'); }, + attr: 'scene.dragmode', + val: 'pan', + icon: _$ploticon_2.pan, + click: handleDrag3d }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +modeBarButtons.orbitRotation = { + name: 'orbitRotation', + title: function(gd) { return ____105(gd, 'Orbital rotation'); }, + attr: 'scene.dragmode', + val: 'orbit', + icon: _$ploticon_2['3d_rotate'], + click: handleDrag3d +}; - if(eventData) { - var pts = eventData.points || []; +modeBarButtons.tableRotation = { + name: 'tableRotation', + title: function(gd) { return ____105(gd, 'Turntable rotation'); }, + attr: 'scene.dragmode', + val: 'turntable', + icon: _$ploticon_2['z-axis'], + click: handleDrag3d +}; - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +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 = {}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; + var parts = attr.split('.'); - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - fullData.selectedpoints.push(pt.pointIndex); - } - } + for(var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + '.' + parts[1]] = val; } - else { - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } + // for multi-type subplots + var val2d = (val === 'pan') ? val : 'zoom'; + layoutUpdate.dragmode = val2d; + + _$registry_254.call('relayout', gd, layoutUpdate); +} + +modeBarButtons.resetCameraDefault3d = { + name: 'resetCameraDefault3d', + title: function(gd) { return ____105(gd, 'Reset camera to default'); }, + attr: 'resetDefault', + icon: _$ploticon_2.home, + click: handleCamera3d +}; + +modeBarButtons.resetCameraLastSave3d = { + name: 'resetCameraLastSave3d', + title: function(gd) { return ____105(gd, 'Reset camera to last save'); }, + attr: 'resetLastSave', + icon: _$ploticon_2.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], + key = sceneId + '.camera', + scene = fullLayout[sceneId]._scene; + + if(attr === 'resetDefault') { + aobj[key] = null; + } + else if(attr === 'resetLastSave') { + aobj[key] = _$lib_164.extendDeep({}, scene.cameraInitial); } } - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } + _$registry_254.call('relayout', gd, aobj); } -function mergePolygons(list, poly, subtract) { - var res; +modeBarButtons.hoverClosest3d = { + name: 'hoverClosest3d', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: handleHover3d +}; - if(subtract) { - res = _$PolyBool_16.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +function handleHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal || false; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; - return res.regions; + var axes = ['xaxis', 'yaxis', 'zaxis']; + var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor']; + + // initialize 'current spike' object to be stored in the DOM + var currentSpikes = {}; + var axisSpikes = {}; + var layoutUpdate = {}; + + if(val) { + layoutUpdate = _$lib_164.extendDeep(layout, val); + button._previousVal = null; } + else { + layoutUpdate = { + 'allaxes.showspikes': false + }; - res = _$PolyBool_16.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); + for(var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i], + sceneLayout = fullLayout[sceneId], + sceneSpikes = currentSpikes[sceneId] = {}; - return res.regions; -} + sceneSpikes.hovermode = sceneLayout.hovermode; + layoutUpdate[sceneId + '.hovermode'] = false; -function fillSelectionItem(selection, searchInfo) { - if(Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; + // copy all the current spike attrs + for(var j = 0; j < 3; j++) { + var axis = axes[j]; + axisSpikes = sceneSpikes[axis] = {}; - for(var i = 0; i < selection.length; i++) { - selection[i] = makeEventData(selection[i], trace, cd); + for(var k = 0; k < spikeAttrs.length; k++) { + var spikeAttr = spikeAttrs[k]; + axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr]; + } + } } + + button._previousVal = _$lib_164.extendDeep({}, currentSpikes); } - return selection; + _$registry_254.call('relayout', gd, layoutUpdate); } -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +modeBarButtons.zoomInGeo = { + name: 'zoomInGeo', + title: function(gd) { return ____105(gd, 'Zoom in'); }, + attr: 'zoom', + val: 'in', + icon: _$ploticon_2.zoom_plus, + click: handleGeo +}; +modeBarButtons.zoomOutGeo = { + name: 'zoomOutGeo', + title: function(gd) { return ____105(gd, 'Zoom out'); }, + attr: 'zoom', + val: 'out', + icon: _$ploticon_2.zoom_minus, + click: handleGeo +}; -'use strict'; +modeBarButtons.resetGeo = { + name: 'resetGeo', + title: function(gd) { return ____105(gd, 'Reset'); }, + attr: 'reset', + val: null, + icon: _$ploticon_2.autoscale, + click: handleGeo +}; -/* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$tinycolor_25 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_12 = require('has-passive-events'); */; +modeBarButtons.hoverClosestGeo = { + name: 'hoverClosestGeo', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; -var __FROM_TL_213 = _$alignment_143.FROM_TL; +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; -/* removed: var _$plots_245 = require('../plots'); */; + for(var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; -var doTicks = _$axes_205.doTicks; -var getFromId = _$axis_ids_208.getFromId; -/* removed: var _$prepSelect_223 = require('./select'); */; -/* removed: var _$scaleZoom_222 = require('./scale_zoom'); */; + if(attr === 'zoom') { + var scale = geoLayout.projection.scale; + var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; -/* removed: var _$constants_210 = require('./constants'); */; -var MINDRAG = _$constants_210.MINDRAG; -var MINZOOM = _$constants_210.MINZOOM; + _$registry_254.call('relayout', gd, id + '.projection.scale', newScale); + } else if(attr === 'reset') { + resetView(gd, 'geo'); + } + } +} +modeBarButtons.hoverClosestGl2d = { + name: 'hoverClosestGl2d', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; +modeBarButtons.hoverClosestPie = { + name: 'hoverClosestPie', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: 'closest', + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: toggleHover +}; -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px +function toggleHover(gd) { var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; + var onHoverVal; + if(fullLayout._has('cartesian')) { + onHoverVal = fullLayout._isHoriz ? 'y' : 'x'; + } + else onHoverVal = 'closest'; - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; + var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; + _$registry_254.call('relayout', gd, 'hovermode', newHover); +} - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); +// buttons when more then one plot types are present - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; +modeBarButtons.toggleHover = { + name: 'toggleHover', + title: function(gd) { return ____105(gd, 'Toggle show closest data on hover'); }, + attr: 'hovermode', + val: null, + toggle: true, + icon: _$ploticon_2.tooltip_basic, + gravity: 'ne', + click: function(gd, ev) { + toggleHover(gd); - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } + // the 3d hovermode update must come + // last so that layout.hovermode update does not + // override scene?.hovermode?.layout. + handleHover3d(gd, ev); + } +}; - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } +modeBarButtons.resetViews = { + name: 'resetViews', + title: function(gd) { return ____105(gd, 'Reset views'); }, + icon: _$ploticon_2.home, + click: function(gd, ev) { + var button = ev.currentTarget; - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; + button.setAttribute('data-attr', 'zoom'); + button.setAttribute('data-val', 'reset'); + handleCartesian(gd, ev); - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; + button.setAttribute('data-attr', 'resetLastSave'); + handleCamera3d(gd, ev); - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } + resetView(gd, 'geo'); + resetView(gd, 'mapbox'); } +}; - recomputeAxisLists(); +modeBarButtons.toggleSpikelines = { + name: 'toggleSpikelines', + title: function(gd) { return ____105(gd, 'Toggle Spike Lines'); }, + icon: _$ploticon_2.spikeline, + attr: '_cartesianSpikesEnabled', + val: 'on', + click: function(gd) { + var fullLayout = gd._fullLayout; - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on'; - var allFixedRanges = !yActive && !xActive; + var aobj = setSpikelineVisibility(gd); - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; + _$registry_254.call('relayout', gd, aobj); } +}; - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_223(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var axList = _$axis_ids_209.list(gd, null, true); + var aobj = {}; - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; + var ax, axName; - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); + for(var i = 0; i < axList.length; i++) { + ax = axList[i]; + axName = ax._name; + aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial; + } - if(numClicks === 2 && !singleEnd) doubleClick(); + return aobj; +} - if(isMainDrag) { - _$fx_85.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; +modeBarButtons.resetViewMapbox = { + name: 'resetViewMapbox', + title: function(gd) { return ____105(gd, 'Reset view'); }, + attr: 'reset', + icon: _$ploticon_2.home, + click: function(gd) { + resetView(gd, 'mapbox'); + } +}; - if(ax.fixedrange) return; +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType]; + var aObj = {}; - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; + 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); - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_6.select(dragger) - .call(_$svg_text_utils_184.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_253.call('relayout', gd, attrStr, v); - } - }); - } - } + for(var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + '.' + key] = viewInitial[key]; } - }; - - _$dragelement_65.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; + } - // collected changes to be made to the plot by relayout at the end - var updates = {}; + _$registry_254.call('relayout', gd, aObj); +} - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_25(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); +'use strict'; - clearSelect(zoomlayer); - } +/* removed: var _$d3_6 = require('d3'); */; - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); +/** + * 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'); - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } + this.update(opts.graphInfo, opts.buttons); - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; + this.container.appendChild(this.element); +} - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } +var proto = ModeBar.prototype; - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } +/** + * 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; - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); + var context = this.graphInfo._context; - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); + if(context.displayModeBar === 'hover') { + this.element.className = 'modebar modebar--hover'; } + else this.element.className = 'modebar'; - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_210.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } + // if buttons or logo have changed, redraw modebar interior + var needsNewButtons = !this.hasButtons(buttons), + needsNewLogo = (this.hasLogo !== context.displaylogo); - var pc = gd.querySelector('.plotly'); + if(needsNewButtons || needsNewLogo) { + this.removeAllButtons(); - recomputeAxisLists(); + this.updateButtons(buttons); - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; + if(context.displaylogo) { + this.element.appendChild(this.getLogo()); + this.hasLogo = true; } + } - clearTimeout(redrawTimer); + this.updateActiveButton(); +}; - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_163.log('Did not find wheel motion attributes: ', e); - return; - } +proto.updateButtons = function(buttons) { + var _this = this; - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; + this.buttons = buttons; + this.buttonElements = []; + this.buttonsNames = []; - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); - var axRange = _$lib_163.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + 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); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +proto.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * 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, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_6.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +proto.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_222(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_222(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * 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, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_6.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_164.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * 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((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_253.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_253.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_253.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +proto.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_164._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +proto.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +proto.destroy = function() { + _$lib_164.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_253.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_6.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_163.syncOrAsync([ - _$plots_245.previousPromises, - function() { _$registry_253.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_108 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_209 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_288 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_254 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_222(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_108 = require('./modebar'); */; +/* removed: var _$buttons_105 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_213[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_107 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_163.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_163.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_108(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_68.setTranslate, clipDx, clipDy) - .call(_$drawing_68.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_68.setTranslate, plotDx, plotDy) - .call(_$drawing_68.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_68.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_68.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_68.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_68.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_105[button]); } - } - - return dragger; -} - -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - dragger3.call(_$setCursor_182, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_6.select(dragger).call(_$drawing_68.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_6.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_6.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_209.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_43.background, - stroke: _$color_43.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_254.traceIs(trace, 'scatter-like')) { + if(_$subtypes_288.hasMarkers(trace) || _$subtypes_288.hasText(trace)) { + selectable = true; + } + } else if(_$registry_254.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_6.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_163.notifier(_$lib_163._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_105[button] !== undefined) { + customButtons[i][j] = _$buttons_105[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_163.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_12) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_213 = { - makeDragBox: makeDragBox, +var _$modebar_106 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_106.manage = _$manageModeBar_107; +var _$constraints_213 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51416,152 +52210,202 @@ var _$dragbox_213 = { 'use strict'; -/* removed: var _$d3_6 = require('d3'); */; +var __id2name_213 = _$axis_ids_209.id2name; +/* removed: var _$scaleZoom_222 = require('./scale_zoom'); */; +var __makePadFn_213 = _$autorange_205.makePadFn; -/* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$dragelement_65 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_145.ALMOST_EQUAL; -/* removed: var _$constants_210 = require('./constants'); */; -var __makeDragBox_214 = _$dragbox_213.makeDragBox; +var __FROM_BL_213 = _$alignment_143.FROM_BL; -var _$initInteractions_214 = function initInteractions(gd) { + +_$constraints_213.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_6.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - 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'), - 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)); + 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_213(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_210.DRAGGERSIZE; + // 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; - // 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_214(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + if(mode === 'range') { + _$scaleZoom_222(ax, factor); + } + else { + // mode === 'domain' - 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) { - _$fx_85.hover(gd, evt, subplot); + 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_222(ax, factor); + continue; } - }; - _$fx_85.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_213(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_65.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_214(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_214(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_214(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_214(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_214(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_214(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_214(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_214(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_214(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_214(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_213.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_85.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_85.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_213[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_197 = {}; +var _$subroutines_198 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51573,21 +52417,27 @@ var _$subroutines_197 = {}; 'use strict'; /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$registry_253 = require('../registry'); */; +/* removed: var _$registry_254 = require('../registry'); */; /* removed: var _$plots_245 = require('../plots/plots'); */; -/* removed: var _$lib_163 = require('../lib'); */; + +/* removed: var _$lib_164 = require('../lib'); */; +/* removed: var _$clearGlCanvases_152 = require('../lib/clear_gl_canvases'); */; /* removed: var _$color_43 = require('../components/color'); */; /* removed: var _$drawing_68 = require('../components/drawing'); */; /* removed: var _$titles_136 = require('../components/titles'); */; /* removed: var _$modebar_106 = require('../components/modebar'); */; -/* removed: var _$axes_205 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_214 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_210 = require('../plots/cartesian/constants'); */; + +/* removed: var _$axes_206 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_211 = require('../plots/cartesian/constants'); */; /* removed: var _$alignment_143 = require('../constants/alignment'); */; +/* removed: var _$constraints_213 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_213.enforce; +var cleanAxisConstraints = _$constraints_213.clean; +var __doAutoRange_198 = _$autorange_205.doAutoRange; -_$subroutines_197.layoutStyles = function(gd) { - return _$lib_163.syncOrAsync([_$plots_245.doAutoMargin, _$subroutines_197.lsInner], gd); +_$subroutines_198.layoutStyles = function(gd) { + return _$lib_164.syncOrAsync([_$plots_245.doAutoMargin, _$subroutines_198.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -51605,11 +52455,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_197.lsInner = function(gd) { +_$subroutines_198.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_205.list(gd); + var axList = _$axes_206.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -51688,31 +52538,17 @@ _$subroutines_197.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_164.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -51744,23 +52580,17 @@ _$subroutines_197.lsInner = function(gd) { } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_164.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); _$drawing_68.setTranslate(plotinfo.plot, xa._offset, ya._offset); @@ -51769,16 +52599,16 @@ _$subroutines_197.lsInner = function(gd) { if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } _$drawing_68.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_210.traceLayerClasses.length; i++) { - var layer = _$constants_210.traceLayerClasses[i]; + for(i = 0; i < _$constants_211.traceLayerClasses.length; i++) { + var layer = _$constants_211.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { plotinfo.plot.selectAll('g.' + layer).call(_$drawing_68.setClipUrl, layerClipId); } @@ -51902,8 +52732,8 @@ _$subroutines_197.lsInner = function(gd) { plotinfo.ylines.attr('d', yPath); }); - _$axes_205.makeClipPaths(gd); - _$subroutines_197.drawMainTitle(gd); + _$axes_206.makeClipPaths(gd); + _$subroutines_198.drawMainTitle(gd); _$modebar_106.manage(gd); return gd._promises.length && Promise.all(gd._promises); @@ -51960,7 +52790,7 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_197.drawMainTitle = function(gd) { +_$subroutines_198.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; _$titles_136.draw(gd, 'gtitle', { @@ -51979,7 +52809,7 @@ _$subroutines_197.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_197.doTraceStyle = function(gd) { +_$subroutines_198.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -51989,12 +52819,12 @@ _$subroutines_197.doTraceStyle = function(gd) { } _$plots_245.style(gd); - _$registry_253.getComponentMethod('legend', 'draw')(gd); + _$registry_254.getComponentMethod('legend', 'draw')(gd); return _$plots_245.previousPromises(gd); }; -_$subroutines_197.doColorBars = function(gd) { +_$subroutines_198.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -52002,7 +52832,7 @@ _$subroutines_197.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_253.traceIs(trace, 'contour')) { + if(_$registry_254.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -52011,7 +52841,7 @@ _$subroutines_197.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_253.traceIs(trace, 'markerColorscale')) { + if(_$registry_254.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); @@ -52022,28 +52852,33 @@ _$subroutines_197.doColorBars = function(gd) { }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_197.layoutReplot = function(gd) { +_$subroutines_198.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_253.call('plot', gd, '', layout); + return _$registry_254.call('plot', gd, '', layout); }; -_$subroutines_197.doLegend = function(gd) { - _$registry_253.getComponentMethod('legend', 'draw')(gd); +_$subroutines_198.doLegend = function(gd) { + _$registry_254.getComponentMethod('legend', 'draw')(gd); return _$plots_245.previousPromises(gd); }; -_$subroutines_197.doTicksRelayout = function(gd) { - _$axes_205.doTicks(gd, 'redraw'); - _$subroutines_197.drawMainTitle(gd); +_$subroutines_198.doTicksRelayout = function(gd) { + _$axes_206.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_152(gd); + _$registry_254.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_198.drawMainTitle(gd); return _$plots_245.previousPromises(gd); }; -_$subroutines_197.doModeBar = function(gd) { +_$subroutines_198.doModeBar = function(gd) { var fullLayout = gd._fullLayout; _$modebar_106.manage(gd); - _$initInteractions_214(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; @@ -52053,7 +52888,7 @@ _$subroutines_197.doModeBar = function(gd) { return _$plots_245.previousPromises(gd); }; -_$subroutines_197.doCamera = function(gd) { +_$subroutines_198.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -52065,212 +52900,86 @@ _$subroutines_197.doCamera = function(gd) { } }; -var _$constraints_212 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_212 = _$axis_ids_208.id2name; -/* removed: var _$scaleZoom_222 = require('./scale_zoom'); */; -var __makePadFn_212 = _$autorange_204.makePadFn; - -var ALMOST_EQUAL = _$numerical_145.ALMOST_EQUAL; - -var __FROM_BL_212 = _$alignment_143.FROM_BL; - - -_$constraints_212.enforce = function enforceAxisConstraints(gd) { +_$subroutines_198.drawData = function(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_212(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_254.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_222(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_222(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_152(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_212(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_245.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_254.getComponentMethod('shapes', 'draw')(gd); + _$registry_254.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_245.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_198.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_206.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_198(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_212.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_212[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_198.finalDraw = function(gd) { + _$registry_254.getComponentMethod('shapes', 'draw')(gd); + _$registry_254.getComponentMethod('images', 'draw')(gd); + _$registry_254.getComponentMethod('annotations', 'draw')(gd); + _$registry_254.getComponentMethod('legend', 'draw')(gd); + _$registry_254.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_254.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_254.getComponentMethod('sliders', 'draw')(gd); + _$registry_254.getComponentMethod('updatemenus', 'draw')(gd); +}; var _$micropolar_249 = {}; /** @@ -52282,8 +52991,8 @@ var _$micropolar_249 = {}; */ /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../../../lib'); */; -var __extendDeepAll_249 = _$lib_163.extendDeepAll; +/* removed: var _$lib_164 = require('../../../lib'); */; +var __extendDeepAll_249 = _$lib_164.extendDeepAll; var __MID_SHIFT_249 = _$alignment_143.MID_SHIFT; var µ = _$micropolar_249 = { version: '0.2.2' }; @@ -53771,12 +54480,12 @@ var _$micropolar_manager_250 = {}; 'use strict'; /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../../../lib'); */; +/* removed: var _$lib_164 = require('../../../lib'); */; /* removed: var _$color_43 = require('../../../components/color'); */; /* removed: var _$micropolar_249 = require('./micropolar'); */; /* removed: var _$UndoManager_251 = require('./undo_manager'); */; -var __extendDeepAll_250 = _$lib_163.extendDeepAll; +var __extendDeepAll_250 = _$lib_164.extendDeepAll; var manager = _$micropolar_manager_250 = {}; @@ -53858,7 +54567,7 @@ var Polar = _$legacy_248 = _$micropolar_249; Polar.manager = _$micropolar_manager_250; -var _$plot_api_194 = {}; +var _$plot_api_195 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53875,33 +54584,29 @@ var _$plot_api_194 = {}; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; /* removed: var _$hasHover_11 = require('has-hover'); */; -/* removed: var _$lib_163 = require('../lib'); */; -/* removed: var _$Events_155 = require('../lib/events'); */; -/* removed: var _$queue_177 = require('../lib/queue'); */; +/* removed: var _$lib_164 = require('../lib'); */; +/* removed: var _$Events_156 = require('../lib/events'); */; +/* removed: var _$queue_178 = require('../lib/queue'); */; -/* removed: var _$registry_253 = require('../registry'); */; -/* removed: var _$plot_schema_196 = require('./plot_schema'); */; +/* removed: var _$registry_254 = require('../registry'); */; +/* removed: var _$plot_schema_197 = require('./plot_schema'); */; /* removed: var _$plots_245 = require('../plots/plots'); */; /* removed: var _$legacy_248 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_214 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$axes_205 = require('../plots/cartesian/axes'); */; +/* removed: var _$axes_206 = require('../plots/cartesian/axes'); */; /* removed: var _$drawing_68 = require('../components/drawing'); */; /* removed: var _$color_43 = require('../components/color'); */; +var initInteractions = _$graph_interact_215.initInteractions; /* removed: var _$xmlns_namespaces_147 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_184 = require('../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_185 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_195 = require('./plot_config'); */; -/* removed: var _$manage_arrays_193 = require('./manage_arrays'); */; -/* removed: var _$helpers_191 = require('./helpers'); */; -/* removed: var _$subroutines_197 = require('./subroutines'); */; -/* removed: var _$edit_types_190 = require('./edit_types'); */; +/* removed: var _$plot_config_196 = require('./plot_config'); */; +/* removed: var _$manage_arrays_194 = require('./manage_arrays'); */; +/* removed: var _$helpers_192 = require('./helpers'); */; +/* removed: var _$subroutines_198 = require('./subroutines'); */; +/* removed: var _$edit_types_191 = require('./edit_types'); */; -/* removed: var _$constants_210 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_212 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_212.enforce; -var cleanAxisConstraints = _$constraints_212.clean; -var __doAutoRange_194 = _$autorange_204.doAutoRange; +var AX_NAME_PATTERN = _$constants_211.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -53927,15 +54632,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_194.plot = function(gd, data, layout, config) { +_$plot_api_195.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_163.getGraphDiv(gd); + gd = _$lib_164.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_155.init(gd); + _$Events_156.init(gd); - if(_$lib_163.isPlainObject(data)) { + if(_$lib_164.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -53943,19 +54648,19 @@ _$plot_api_194.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_155.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_156.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_163.isPlotDiv(gd)) { - _$lib_163.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_164.isPlotDiv(gd)) { + _$lib_164.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_194.addFrames(gd, frames); + return _$plot_api_195.addFrames(gd, frames); } } @@ -53974,6 +54679,9 @@ _$plot_api_194.plot = function(gd, data, layout, config) { // so we can share cached text across tabs _$drawing_68.makeTester(); + // clear stashed base url + delete _$drawing_68.baseUrl; + // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then // before we move to the next step, we check that they're all @@ -53985,7 +54693,7 @@ _$plot_api_194.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_191.cleanData(data, gd.data); + _$helpers_192.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -53996,7 +54704,7 @@ _$plot_api_194.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_191.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_192.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -54018,7 +54726,7 @@ _$plot_api_194.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_163.log('Legacy polar charts are deprecated!'); + _$lib_164.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -54039,7 +54747,7 @@ _$plot_api_194.plot = function(gd, data, layout, config) { _$drawing_68.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_205.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_206.saveShowSpikeInitial(gd); // prepare the data and find the autorange @@ -54106,9 +54814,7 @@ _$plot_api_194.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_163.syncOrAsync([ - _$subroutines_197.layoutStyles - ], gd); + return _$plots_245.previousPromises(gd); } // draw anything that can affect margins. @@ -54116,10 +54822,10 @@ _$plot_api_194.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_253.getComponentMethod('legend', 'draw')(gd); - _$registry_253.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_253.getComponentMethod('sliders', 'draw')(gd); - _$registry_253.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_254.getComponentMethod('legend', 'draw')(gd); + _$registry_254.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_254.getComponentMethod('sliders', 'draw')(gd); + _$registry_254.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; @@ -54138,9 +54844,9 @@ _$plot_api_194.plot = function(gd, data, layout, config) { function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_163.syncOrAsync([ + return _$lib_164.syncOrAsync([ marginPushers, - _$subroutines_197.layoutStyles + _$subroutines_198.layoutStyles ], gd); } @@ -54161,7 +54867,7 @@ _$plot_api_194.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_163.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_164.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -54175,113 +54881,31 @@ _$plot_api_194.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_253.getComponentMethod('errorbars', 'calc')(gd); + _$registry_254.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_163.syncOrAsync([ - _$registry_253.getComponentMethod('shapes', 'calcAutorange'), - _$registry_253.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_164.syncOrAsync([ + _$registry_254.getComponentMethod('shapes', 'calcAutorange'), + _$registry_254.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_253.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_254.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_205.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_194(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_198.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_205.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_206.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_205.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_253.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_245.style(gd); - - // show annotations and shapes - _$registry_253.getComponentMethod('shapes', 'draw')(gd); - _$registry_253.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_245.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_245.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_253.getComponentMethod('shapes', 'draw')(gd); - _$registry_253.getComponentMethod('images', 'draw')(gd); - _$registry_253.getComponentMethod('annotations', 'draw')(gd); - _$registry_253.getComponentMethod('legend', 'draw')(gd); - _$registry_253.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_253.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_253.getComponentMethod('sliders', 'draw')(gd); - _$registry_253.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_206.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ @@ -54292,19 +54916,20 @@ _$plot_api_194.plot = function(gd, data, layout, config) { marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_197.layoutStyles); + seq.push(_$subroutines_198.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_214, + _$subroutines_198.drawData, + _$subroutines_198.finalDraw, + initInteractions, + _$plots_245.addLinks, _$plots_245.rehover, _$plots_245.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_163.syncOrAsync(seq, gd); + var plotDone = _$lib_164.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -54313,15 +54938,15 @@ _$plot_api_194.plot = function(gd, data, layout, config) { }); }; -_$plot_api_194.setPlotConfig = function setPlotConfig(obj) { - return _$lib_163.extendFlat(_$plot_config_195, obj); +_$plot_api_195.setPlotConfig = function setPlotConfig(obj) { + return _$lib_164.extendFlat(_$plot_config_196, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_163.error(e); + _$lib_164.error(e); } } @@ -54331,7 +54956,7 @@ function opaqueSetBackground(gd, bgColor) { } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_163.extendDeep({}, _$plot_config_195); + if(!gd._context) gd._context = _$lib_164.extendDeep({}, _$plot_config_196); var context = gd._context; var i, keys, key; @@ -54447,7 +55072,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_184.convertToTspans, gd); + this.call(_$svg_text_utils_185.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -54456,7 +55081,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_163._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_164._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -54475,7 +55100,7 @@ function plotPolar(gd, data, layout) { } var setContenteditable = function() { - this.call(_$svg_text_utils_184.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_185.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -54497,18 +55122,18 @@ function plotPolar(gd, data, layout) { } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_194.redraw = function(gd) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.redraw = function(gd) { + gd = _$lib_164.getGraphDiv(gd); - if(!_$lib_163.isPlotDiv(gd)) { + if(!_$lib_164.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_191.cleanData(gd.data, gd.data); - _$helpers_191.cleanLayout(gd.layout); + _$helpers_192.cleanData(gd.data, gd.data); + _$helpers_192.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_194.plot(gd).then(function() { + return _$plot_api_195.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -54522,14 +55147,14 @@ _$plot_api_194.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_194.newPlot = function(gd, data, layout, config) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.newPlot = function(gd, data, layout, config) { + gd = _$lib_164.getGraphDiv(gd); // remove gl contexts - _$plots_245.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_245.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); _$plots_245.purge(gd); - return _$plot_api_194.plot(gd, data, layout, config); + return _$plot_api_195.plot(gd, data, layout, config); }; /** @@ -54682,12 +55307,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_163.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_164.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_163.isPlainObject(update)) { + if(!_$lib_164.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -54730,7 +55355,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_163.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_164.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -54750,7 +55375,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_163.nestedProperty(trace, key); + prop = _$lib_164.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -54759,10 +55384,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_163.isArrayOrTypedArray(insert)) { + if(!_$lib_164.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_163.isArrayOrTypedArray(target)) { + if(!_$lib_164.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -54857,13 +55482,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_194.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_164.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_163.isTypedArray(target)) { + if(_$lib_164.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -54908,20 +55533,20 @@ _$plot_api_194.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_194.redraw(gd); + var promise = _$plot_api_195.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_177.add(gd, _$plot_api_194.prependTraces, undoArgs, extendTraces, arguments); + _$queue_178.add(gd, _$plot_api_195.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_194.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_164.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_163.isTypedArray(target)) { + if(_$lib_164.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -54965,9 +55590,9 @@ _$plot_api_194.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_194.redraw(gd); + var promise = _$plot_api_195.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_177.add(gd, _$plot_api_194.extendTraces, undoArgs, prependTraces, arguments); + _$queue_178.add(gd, _$plot_api_195.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -54981,11 +55606,11 @@ _$plot_api_194.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_194.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_164.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_194.deleteTraces, + undoFunc = _$plot_api_195.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -55002,10 +55627,10 @@ _$plot_api_194.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_163.extendFlat({}, trace); + return _$lib_164.extendFlat({}, trace); }); - _$helpers_191.cleanData(traces, gd.data); + _$helpers_192.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -55020,8 +55645,8 @@ _$plot_api_194.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_194.redraw(gd); - _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_195.redraw(gd); + _$queue_178.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -55044,10 +55669,10 @@ _$plot_api_194.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_177.startSequence(gd); - _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_194.moveTraces(gd, currentIndices, newIndices); - _$queue_177.stopSequence(gd); + _$queue_178.startSequence(gd); + _$queue_178.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_195.moveTraces(gd, currentIndices, newIndices); + _$queue_178.stopSequence(gd); return promise; }; @@ -55058,11 +55683,11 @@ _$plot_api_194.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_194.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_164.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_194.addTraces, + undoFunc = _$plot_api_195.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -55081,14 +55706,14 @@ _$plot_api_194.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_163.sorterDes); + indices.sort(_$lib_164.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_194.redraw(gd); - _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_195.redraw(gd); + _$queue_178.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -55124,8 +55749,8 @@ _$plot_api_194.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_194.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_164.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -55185,8 +55810,8 @@ _$plot_api_194.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_194.redraw(gd); - _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_195.redraw(gd); + _$queue_178.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -55221,55 +55846,55 @@ _$plot_api_194.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_194.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_163.getGraphDiv(gd); - _$helpers_191.clearPromiseQueue(gd); +_$plot_api_195.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_164.getGraphDiv(gd); + _$helpers_192.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_163.isPlainObject(astr)) { + else if(_$lib_164.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_163.extendFlat({}, astr); + aobj = _$lib_164.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_163.warn('Restyle fail.', astr, val, _traces); + _$lib_164.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_191.coerceTraceIndices(gd, _traces); + var traces = _$helpers_192.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_191.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_192.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_194.plot); + seq.push(_$plot_api_195.plot); } else { seq.push(_$plots_245.previousPromises); _$plots_245.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_197.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_197.doColorBars); + if(flags.style) seq.push(_$subroutines_198.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_198.doColorBars); } seq.push(_$plots_245.rehover); - _$queue_177.add(gd, + _$queue_178.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_163.syncOrAsync(seq, gd); + var plotDone = _$lib_164.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -55292,7 +55917,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_190.traceFlags(); + var flags = _$edit_types_191.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -55305,7 +55930,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_205.id2name(axid); + var axName = _$axes_206.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -55324,13 +55949,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_191.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_192.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_163.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_164.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_163.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_164.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -55347,7 +55972,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_191.hasParent(aobj, ai)) { + if(_$helpers_192.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -55362,7 +55987,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_163.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_164.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -55378,17 +56003,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_163.nestedProperty(cont, ai); + param = _$lib_164.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_196.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_197.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_163.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_164.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -55428,19 +56053,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_163.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_163.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_163.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_164.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_164.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_164.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_163.nestedProperty(cont, 'marker.color') - .set(_$lib_163.nestedProperty(cont, 'marker.colors').get()); + _$lib_164.nestedProperty(cont, 'marker.color') + .set(_$lib_164.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_253.traceIs(cont, 'cartesian')) { - _$lib_163.nestedProperty(cont, 'marker.colors') - .set(_$lib_163.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_254.traceIs(cont, 'cartesian')) { + _$lib_164.nestedProperty(cont, 'marker.colors') + .set(_$lib_164.nestedProperty(cont, 'marker.color').get()); } } @@ -55469,23 +56094,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_191.swapXYData(cont); + _$helpers_192.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } else if(_$plots_245.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_191.manageArrayContainers(param, newVal, undoit); + _$helpers_192.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_163.isArrayOrTypedArray(newVal) || _$lib_163.isArrayOrTypedArray(oldVal)) + _$lib_164.isArrayOrTypedArray(newVal) || _$lib_164.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_190.update(flags, valObject); + else _$edit_types_191.update(flags, valObject); } else { /* @@ -55504,12 +56129,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_205.swap(gd, traces); + _$axes_206.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_163.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_164.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -55524,7 +56149,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_253.traceIs(trace, 'cartesian')) { + if(_$registry_254.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -55541,7 +56166,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_205.list(gd); + var axList = _$axes_206.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -55562,7 +56187,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_163.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_164.extendDeepNoArrays([], [redoit, traces]) }; } @@ -55586,9 +56211,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_194.relayout = function relayout(gd, astr, val) { - gd = _$lib_163.getGraphDiv(gd); - _$helpers_191.clearPromiseQueue(gd); +_$plot_api_195.relayout = function relayout(gd, astr, val) { + gd = _$lib_164.getGraphDiv(gd); + _$helpers_192.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -55597,21 +56222,21 @@ _$plot_api_194.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_163.isPlainObject(astr)) { - aobj = _$lib_163.extendFlat({}, astr); + } else if(_$lib_164.isPlainObject(astr)) { + aobj = _$lib_164.extendFlat({}, astr); } else { - _$lib_163.warn('Relayout fail.', astr, val); + _$lib_164.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_191.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_192.clearAxisAutomargins(gd); // fill in redraw sequence @@ -55621,26 +56246,50 @@ _$plot_api_194.relayout = function relayout(gd, astr, val) { var seq = [_$plots_245.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_197.layoutReplot); + seq.push(_$subroutines_198.layoutReplot); } else if(Object.keys(aobj).length) { _$plots_245.supplyDefaults(gd); - if(flags.legend) seq.push(_$subroutines_197.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_197.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_197.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_197.doModeBar); - if(flags.camera) seq.push(_$subroutines_197.doCamera); + if(flags.legend) seq.push(_$subroutines_198.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_198.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_198.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_198.doTicksRelayout, + _$subroutines_198.drawData, + _$subroutines_198.finalDraw + ); + } + + if(flags.ticks) seq.push(_$subroutines_198.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_198.doModeBar); + if(flags.camera) seq.push(_$subroutines_198.doCamera); } seq.push(_$plots_245.rehover); - _$queue_177.add(gd, + _$queue_178.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_163.syncOrAsync(seq, gd); + var plotDone = _$lib_164.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -55653,7 +56302,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_205.list(gd), + axes = _$axes_206.list(gd), arrayEdits = {}, arrayStr, i, @@ -55676,7 +56325,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_190.layoutFlags(); + var flags = _$edit_types_191.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -55695,9 +56344,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_191.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_192.hasParent(aobj, attr)) return; - var p = _$lib_163.nestedProperty(layout, attr); + var p = _$lib_164.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -55711,18 +56360,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_205.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_206.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_191.hasParent(aobj, ai)) { + if(_$helpers_192.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_163.nestedProperty(layout, ai); + var p = _$lib_164.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -55734,8 +56383,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_163.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_163.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_164.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_164.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -55746,11 +56395,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_196.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_197.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_163.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_164.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -55764,12 +56413,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_164.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_163.nestedProperty(fullLayout, ptrunk).get(); + _$lib_164.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_164.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -55777,7 +56426,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_164.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -55837,8 +56486,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_253.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_253.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_254.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_254.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -55846,18 +56495,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_163.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_164.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_210.AX_NAME_PATTERN)) { - var fullProp = _$lib_163.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_164.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_253.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_253.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_254.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_254.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -55866,12 +56515,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_193.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_194.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_163.nestedProperty(layout, arrayStr); + var componentArray = _$lib_164.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -55881,28 +56530,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_190.update(flags, updateValObject); + else _$edit_types_191.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_193.isAddVal(vi)) { + if(_$manage_arrays_194.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_193.isRemoveVal(vi)) { + else if(_$manage_arrays_194.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_163.warn('unrecognized full object value', aobj); + else _$lib_164.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_190.update(flags, updateValObject); - + else { + _$edit_types_191.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -55931,7 +56581,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_190.update(flags, valObject); + else if(valObject) _$edit_types_191.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -55940,8 +56590,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_193.applyContainerArrayChanges(gd, - _$lib_163.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_194.applyContainerArrayChanges(gd, + _$lib_164.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -55959,7 +56609,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_205.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_206.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -55983,7 +56633,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_163.extendDeep({}, redoit) + eventData: _$lib_164.extendDeep({}, redoit) }; } @@ -56005,9 +56655,9 @@ function updateAutosize(gd) { // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_163.isPlainObject(obj)) return false; + if(!_$lib_164.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_205.getFromId(gd, axRef); + ax = _$axes_206.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -56017,7 +56667,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_205.getFromId(gd, axLetter); + ax = _$axes_206.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -56037,32 +56687,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_194.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_163.getGraphDiv(gd); - _$helpers_191.clearPromiseQueue(gd); +_$plot_api_195.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_164.getGraphDiv(gd); + _$helpers_192.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_163.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_163.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_164.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_164.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_191.coerceTraceIndices(gd, _traces); + var traces = _$helpers_192.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_163.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_164.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_163.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_164.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_191.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_191.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_192.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_192.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -56076,35 +56726,43 @@ _$plot_api_194.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_194.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_195.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_194.plot); + seq.push(_$plot_api_195.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_197.layoutReplot); + seq.push(_$subroutines_198.layoutReplot); } else { seq.push(_$plots_245.previousPromises); _$plots_245.supplyDefaults(gd); - if(restyleFlags.style) seq.push(_$subroutines_197.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_197.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_197.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_197.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_197.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_197.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_197.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_198.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_198.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_198.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_198.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_198.doAutoRangeAndConstraints, + _$subroutines_198.doTicksRelayout, + _$subroutines_198.drawData, + _$subroutines_198.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_198.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_198.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_198.doCamera); } seq.push(_$plots_245.rehover); - _$queue_177.add(gd, + _$queue_178.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_163.syncOrAsync(seq, gd); + var plotDone = _$lib_164.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -56140,23 +56798,23 @@ _$plot_api_194.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_194.react = function(gd, data, layout, config) { +_$plot_api_195.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_194.addFrames(gd, frames); } + function addFrames() { return _$plot_api_195.addFrames(gd, frames); } - gd = _$lib_163.getGraphDiv(gd); + gd = _$lib_164.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_163.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_194.newPlot(gd, data, layout, config); + if(!_$lib_164.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_195.newPlot(gd, data, layout, config); } else { - if(_$lib_163.isPlainObject(data)) { + if(_$lib_164.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -56168,16 +56826,16 @@ _$plot_api_194.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_163.extendDeep({}, gd._context); + var oldConfig = _$lib_164.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_191.cleanData(gd.data, []); + _$helpers_192.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_191.cleanLayout(gd.layout); + _$helpers_192.cleanLayout(gd.layout); _$plots_245.supplyDefaults(gd); @@ -56201,7 +56859,7 @@ _$plot_api_194.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_191.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_192.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -56217,21 +56875,21 @@ _$plot_api_194.react = function(gd, data, layout, config) { if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_194.plot); + seq.push(_$plot_api_195.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_253.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_163.noop) { + var drawOne = _$registry_254.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_164.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_253.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_163.noop) { + var draw = _$registry_254.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_164.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -56240,18 +56898,26 @@ _$plot_api_194.react = function(gd, data, layout, config) { } seq.push(_$plots_245.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_197.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_197.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_197.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_197.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_197.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_197.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_197.doCamera); + if(restyleFlags.style) seq.push(_$subroutines_198.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_198.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_198.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_198.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_198.doAutoRangeAndConstraints, + _$subroutines_198.doTicksRelayout, + _$subroutines_198.drawData, + _$subroutines_198.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_198.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_198.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_198.doCamera); } seq.push(_$plots_245.rehover); - plotDone = _$lib_163.syncOrAsync(seq, gd); + plotDone = _$lib_164.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -56274,12 +56940,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_190.traceFlags(); + var flags = _$edit_types_191.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_196.getTraceValObject(trace, parts); + return _$plot_schema_197.getTraceValObject(trace, parts); } var diffOpts = { @@ -56289,11 +56955,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_205.getFromId(gd, trace.xaxis).autorange || - _$axes_205.getFromId(gd, trace.yaxis).autorange + _$axes_206.getFromId(gd, trace.xaxis).autorange || + _$axes_206.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -56306,11 +56978,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_190.layoutFlags(); + var flags = _$edit_types_191.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_196.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_197.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -56349,10 +57021,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_163.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_164.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_190.update(flags, valObject); + _$edit_types_191.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -56432,7 +57104,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_163.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_164.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -56444,7 +57116,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_163.isPlainObject(oldVal)) { + else if(!valType && _$lib_164.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -56498,7 +57170,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_163.isPlainObject(oldVal) && _$lib_163.isPlainObject(newVal)) { + if(_$lib_164.isPlainObject(oldVal) && _$lib_164.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -56509,7 +57181,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_163.isPlainObject(oldVal[i]) && _$lib_163.isPlainObject(newVal[i])) { + if(_$lib_164.isPlainObject(oldVal[i]) && _$lib_164.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -56554,10 +57226,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_164.getGraphDiv(gd); - if(!_$lib_163.isPlotDiv(gd)) { + if(!_$lib_164.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -56731,7 +57403,7 @@ _$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts _$plots_245.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_191.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_192.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -56801,13 +57473,13 @@ _$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_163.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_164.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_163.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_164.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -56836,10 +57508,10 @@ _$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_163.isPlainObject(frameOrName)) { + } else if(_$lib_164.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_163.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_164.extendFlat({}, frameOrName)) }); } } @@ -56849,7 +57521,7 @@ _$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_163.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_164.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -56918,14 +57590,14 @@ _$plot_api_194.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_194.addFrames = function(gd, frameList, indices) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.addFrames = function(gd, frameList, indices) { + gd = _$lib_164.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_163.isPlotDiv(gd)) { + if(!_$lib_164.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -56952,7 +57624,7 @@ _$plot_api_194.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_163.isPlainObject(frameList[i])) continue; + if(!_$lib_164.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -56964,14 +57636,14 @@ _$plot_api_194.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_163.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_164.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_163.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_164.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -57000,7 +57672,7 @@ _$plot_api_194.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_163.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_164.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -57033,7 +57705,7 @@ _$plot_api_194.addFrames = function(gd, frameList, indices) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_177) _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_178) _$queue_178.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_245.modifyFrames(gd, ops); }; @@ -57047,10 +57719,10 @@ _$plot_api_194.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_194.deleteFrames = function(gd, frameList) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.deleteFrames = function(gd, frameList) { + gd = _$lib_164.getGraphDiv(gd); - if(!_$lib_163.isPlotDiv(gd)) { + if(!_$lib_164.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -57080,7 +57752,7 @@ _$plot_api_194.deleteFrames = function(gd, frameList) { undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_177) _$queue_177.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_178) _$queue_178.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return _$plots_245.modifyFrames(gd, ops); }; @@ -57091,20 +57763,21 @@ _$plot_api_194.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_194.purge = function purge(gd) { - gd = _$lib_163.getGraphDiv(gd); +_$plot_api_195.purge = function purge(gd) { + gd = _$lib_164.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_245.cleanPlot([], {}, fullData, fullLayout); + _$plots_245.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties _$plots_245.purge(gd); // purge event emitter methods - _$Events_155.purge(gd); + _$Events_156.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -57162,7 +57835,7 @@ function makePlotFramework(gd) { _$d3_6.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_163.randstr(otherUids); + fullLayout._uid = _$lib_164.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') @@ -57238,7 +57911,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_257 = {}; +var _$helpers_258 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -57250,7 +57923,7 @@ var _$helpers_257 = {}; 'use strict'; -_$helpers_257.getDelay = function(fullLayout) { +_$helpers_258.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -57260,7 +57933,7 @@ _$helpers_257.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_257.getRedrawFunc = function(gd) { +_$helpers_258.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -57285,11 +57958,11 @@ _$helpers_257.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_163 = require('../lib'); */; -var __EventEmitter_259 = _$EventEmitter_8.EventEmitter; +/* removed: var _$lib_164 = require('../lib'); */; +var __EventEmitter_260 = _$EventEmitter_8.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_259(); + var ev = opts.emitter || new __EventEmitter_260(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -57297,7 +57970,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_163.isIE() && format !== 'svg') { + if(_$lib_164.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -57388,7 +58061,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_259 = svgToImg; +var _$svgToImg_260 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -57403,7 +58076,7 @@ var _$svgToImg_259 = svgToImg; /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$lib_164 = require('../lib'); */; /* removed: var _$drawing_68 = require('../components/drawing'); */; /* removed: var _$color_43 = require('../components/color'); */; @@ -57428,7 +58101,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_261 = function toSVG(gd, format, scale) { +var _$toSVG_262 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -57551,7 +58224,7 @@ var _$toSVG_261 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_163.isIE()) { + if(_$lib_164.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -57576,14 +58249,14 @@ var _$toSVG_261 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_194 = require('./plot_api'); */; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$plot_api_195 = require('./plot_api'); */; +/* removed: var _$lib_164 = require('../lib'); */; -/* removed: var _$helpers_257 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_261 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_259 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_258 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_262 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_260 = require('../snapshot/svgtoimg'); */; -var __attrs_198 = { +var __attrs_199 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -57636,19 +58309,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_163.isPlainObject(gd)) { + if(_$lib_164.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_163.getGraphDiv(gd); - data = _$lib_163.extendDeep([], gd.data); - layout = _$lib_163.extendDeep({}, gd.layout); + gd = _$lib_164.getGraphDiv(gd); + data = _$lib_164.extendDeep([], gd.data); + layout = _$lib_164.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_163.validate(opts[attr], __attrs_198[attr]); + return !(attr in opts) || _$lib_164.validate(opts[attr], __attrs_199[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -57662,7 +58335,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_163.coerce(opts, fullOpts, __attrs_198, attr, dflt); + return _$lib_164.coerce(opts, fullOpts, __attrs_199, attr, dflt); } var format = coerce('format'); @@ -57679,31 +58352,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_163.extendFlat({}, layout); + var layoutImage = _$lib_164.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_163.extendFlat({}, config, { + var configImage = _$lib_164.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_257.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_258.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_257.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_258.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_261(clonedGd, format, scale); + var svg = _$toSVG_262(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_194.purge(clonedGd); + _$plot_api_195.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -57715,9 +58388,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_163.randstr(); + canvas.id = _$lib_164.randstr(); - _$svgToImg_259({ + _$svgToImg_260({ format: format, width: width, height: height, @@ -57744,7 +58417,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_194.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_195.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -57753,7 +58426,7 @@ function toImage(gd, opts) { }); } -var _$toImage_198 = toImage; +var _$toImage_199 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -57765,14 +58438,14 @@ var _$toImage_198 = toImage; 'use strict'; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$lib_164 = require('../lib'); */; /* removed: var _$plots_245 = require('../plots/plots'); */; -/* removed: var _$plot_schema_196 = require('./plot_schema'); */; -/* removed: var _$plot_config_195 = require('./plot_config'); */; +/* removed: var _$plot_schema_197 = require('./plot_schema'); */; +/* removed: var _$plot_config_196 = require('./plot_config'); */; -var __isPlainObject_199 = _$lib_163.isPlainObject; -var __isArray_199 = Array.isArray; -var __isArrayOrTypedArray_199 = _$lib_163.isArrayOrTypedArray; +var __isPlainObject_200 = _$lib_164.isPlainObject; +var __isArray_200 = Array.isArray; +var __isArrayOrTypedArray_200 = _$lib_164.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -57795,15 +58468,15 @@ var __isArrayOrTypedArray_199 = _$lib_163.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_199 = function valiate(data, layout) { - var schema = _$plot_schema_196.get(); +var _$valiate_200 = function valiate(data, layout) { + var schema = _$plot_schema_197.get(); var errorList = []; - var gd = {_context: _$lib_163.extendFlat({}, _$plot_config_195)}; + var gd = {_context: _$lib_164.extendFlat({}, _$plot_config_196)}; var dataIn, layoutIn; - if(__isArray_199(data)) { - gd.data = _$lib_163.extendDeep([], data); + if(__isArray_200(data)) { + gd.data = _$lib_164.extendDeep([], data); dataIn = data; } else { @@ -57812,8 +58485,8 @@ var _$valiate_199 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_199(layout)) { - gd.layout = _$lib_163.extendDeep({}, layout); + if(__isPlainObject_200(layout)) { + gd.layout = _$lib_164.extendDeep({}, layout); layoutIn = layout; } else { @@ -57837,7 +58510,7 @@ var _$valiate_199 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_199(traceIn)) { + if(!__isPlainObject_200(traceIn)) { errorList.push(format('object', base)); continue; } @@ -57857,13 +58530,13 @@ var _$valiate_199 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_199(traceIn, traceOut, traceSchema, errorList, base); + __crawl_200(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_199(transformsIn)) { + if(!__isArray_200(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -57873,7 +58546,7 @@ var _$valiate_199 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_199(transformsIn[j])) { + if(!__isPlainObject_200(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -57888,7 +58561,7 @@ var _$valiate_199 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_199(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_200(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -57896,13 +58569,13 @@ var _$valiate_199 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_199(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_200(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_199(objIn, objOut, schema, list, base, path) { +function __crawl_200(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -57927,10 +58600,10 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_199(valIn) && __isPlainObject_199(valOut)) { - __crawl_199(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_200(valIn) && __isPlainObject_200(valOut)) { + __crawl_200(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_199(valIn)) { + else if(isInfoArray && __isArray_200(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -57940,7 +58613,7 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_199(valIn[n])) { + if(__isArray_200(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -57949,7 +58622,7 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_163.validate(valInPart, item)) { + if(!_$lib_164.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -57967,7 +58640,7 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_163.validate(valInPart, item)) { + if(!_$lib_164.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -57976,7 +58649,7 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_199(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_200(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -57990,9 +58663,9 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_199(valIn[_index]) && __isPlainObject_199(valOut[j])) { + if(__isPlainObject_200(valIn[_index]) && __isPlainObject_200(valOut[j])) { indexList.push(_index); - __crawl_199(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_200(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -58001,7 +58674,7 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_199(valIn[j])) { + if(!__isPlainObject_200(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -58009,16 +58682,16 @@ function __crawl_199(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_199(valIn) && __isPlainObject_199(valOut)) { + else if(!__isPlainObject_200(valIn) && __isPlainObject_200(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_199(valIn) && __isArrayOrTypedArray_199(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_200(valIn) && __isArrayOrTypedArray_200(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_163.validate(valIn, nestedSchema)) { + else if(!_$lib_164.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -58038,7 +58711,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_163.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_164.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -58070,7 +58743,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_199(valIn) ? 'container' : 'key'; + var target = __isPlainObject_200(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -58096,7 +58769,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_199(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_200(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -58109,7 +58782,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_199(base)) { + if(__isArray_200(base)) { container = base[0]; trace = base[1]; } @@ -58122,7 +58795,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_163.log(msg); + _$lib_164.log(msg); return { code: code, @@ -58152,7 +58825,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_163.counterRegex('([a-z]+)'); +var idRegex = _$lib_164.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -58164,7 +58837,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_199(path)) return String(path); + if(!__isArray_200(path)) return String(path); var astr = ''; @@ -58253,7 +58926,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_256 = fileSaver; +var _$fileSaver_257 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -58266,9 +58939,9 @@ var _$fileSaver_256 = fileSaver; 'use strict'; -/* removed: var _$toImage_198 = require('../plot_api/to_image'); */; -/* removed: var _$lib_163 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_256 = require('./filesaver'); */; +/* removed: var _$toImage_199 = require('../plot_api/to_image'); */; +/* removed: var _$lib_164 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_257 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -58296,19 +58969,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_163.isIE() && opts.format !== 'svg') { + if(_$lib_164.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_198(gd, opts); + var promise = _$toImage_199(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_256(result, filename); + return _$fileSaver_257(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -58318,9 +58991,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_255 = downloadImage; +var _$downloadImage_256 = downloadImage; -var _$plot_api_192 = {}; +var _$plot_api_193 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -58331,29 +59004,29 @@ var _$plot_api_192 = {}; 'use strict'; -/* removed: var _$plot_api_194 = require('./plot_api'); */; - -_$plot_api_192.plot = _$plot_api_194.plot; -_$plot_api_192.newPlot = _$plot_api_194.newPlot; -_$plot_api_192.restyle = _$plot_api_194.restyle; -_$plot_api_192.relayout = _$plot_api_194.relayout; -_$plot_api_192.redraw = _$plot_api_194.redraw; -_$plot_api_192.update = _$plot_api_194.update; -_$plot_api_192.react = _$plot_api_194.react; -_$plot_api_192.extendTraces = _$plot_api_194.extendTraces; -_$plot_api_192.prependTraces = _$plot_api_194.prependTraces; -_$plot_api_192.addTraces = _$plot_api_194.addTraces; -_$plot_api_192.deleteTraces = _$plot_api_194.deleteTraces; -_$plot_api_192.moveTraces = _$plot_api_194.moveTraces; -_$plot_api_192.purge = _$plot_api_194.purge; -_$plot_api_192.addFrames = _$plot_api_194.addFrames; -_$plot_api_192.deleteFrames = _$plot_api_194.deleteFrames; -_$plot_api_192.animate = _$plot_api_194.animate; -_$plot_api_192.setPlotConfig = _$plot_api_194.setPlotConfig; - -_$plot_api_192.toImage = _$toImage_198; -_$plot_api_192.validate = _$valiate_199; -_$plot_api_192.downloadImage = _$downloadImage_255; +/* removed: var _$plot_api_195 = require('./plot_api'); */; + +_$plot_api_193.plot = _$plot_api_195.plot; +_$plot_api_193.newPlot = _$plot_api_195.newPlot; +_$plot_api_193.restyle = _$plot_api_195.restyle; +_$plot_api_193.relayout = _$plot_api_195.relayout; +_$plot_api_193.redraw = _$plot_api_195.redraw; +_$plot_api_193.update = _$plot_api_195.update; +_$plot_api_193.react = _$plot_api_195.react; +_$plot_api_193.extendTraces = _$plot_api_195.extendTraces; +_$plot_api_193.prependTraces = _$plot_api_195.prependTraces; +_$plot_api_193.addTraces = _$plot_api_195.addTraces; +_$plot_api_193.deleteTraces = _$plot_api_195.deleteTraces; +_$plot_api_193.moveTraces = _$plot_api_195.moveTraces; +_$plot_api_193.purge = _$plot_api_195.purge; +_$plot_api_193.addFrames = _$plot_api_195.addFrames; +_$plot_api_193.deleteFrames = _$plot_api_195.deleteFrames; +_$plot_api_193.animate = _$plot_api_195.animate; +_$plot_api_193.setPlotConfig = _$plot_api_195.setPlotConfig; + +_$plot_api_193.toImage = _$toImage_199; +_$plot_api_193.validate = _$valiate_200; +_$plot_api_193.downloadImage = _$downloadImage_256; /** * Copyright 2012-2018, Plotly, Inc. @@ -58366,10 +59039,10 @@ _$plot_api_192.downloadImage = _$downloadImage_255; 'use strict'; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$lib_164 = require('../lib'); */; -var __extendFlat_254 = _$lib_163.extendFlat; -var extendDeep = _$lib_163.extendDeep; +var __extendFlat_255 = _$lib_164.extendFlat; +var extendDeep = _$lib_164.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -58414,7 +59087,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_254 = function clonePlot(graphObj, options) { +var _$clonePlot_255 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -58487,9 +59160,9 @@ var _$clonePlot_254 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_254(scene.xaxis, axesImageOverride); - __extendFlat_254(scene.yaxis, axesImageOverride); - __extendFlat_254(scene.zaxis, axesImageOverride); + __extendFlat_255(scene.xaxis, axesImageOverride); + __extendFlat_255(scene.yaxis, axesImageOverride); + __extendFlat_255(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -58538,27 +59211,27 @@ var _$clonePlot_254 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_260 = _$EventEmitter_8.EventEmitter; +var __EventEmitter_261 = _$EventEmitter_8.EventEmitter; -/* removed: var _$registry_253 = require('../registry'); */; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$registry_254 = require('../registry'); */; +/* removed: var _$lib_164 = require('../lib'); */; -/* removed: var _$helpers_257 = require('./helpers'); */; -/* removed: var _$clonePlot_254 = require('./cloneplot'); */; -/* removed: var _$toSVG_261 = require('./tosvg'); */; -/* removed: var _$svgToImg_259 = require('./svgtoimg'); */; +/* removed: var _$helpers_258 = require('./helpers'); */; +/* removed: var _$clonePlot_255 = require('./cloneplot'); */; +/* removed: var _$toSVG_262 = require('./tosvg'); */; +/* removed: var _$svgToImg_260 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_260(gd, opts) { +function __toImage_261(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_260(); + var ev = new __EventEmitter_261(); - var clone = _$clonePlot_254(gd, {format: 'png'}); + var clone = _$clonePlot_255(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -58567,15 +59240,15 @@ function __toImage_260(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_257.getDelay(clonedGd._fullLayout); + var delay = _$helpers_258.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_261(clonedGd); + var svg = _$toSVG_262(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_163.randstr(); + canvas.id = _$lib_164.randstr(); - ev = _$svgToImg_259({ + ev = _$svgToImg_260({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -58591,9 +59264,9 @@ function __toImage_260(gd, opts) { }, delay); } - var redrawFunc = _$helpers_257.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_258.getRedrawFunc(clonedGd); - _$registry_253.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_254.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -58604,7 +59277,7 @@ function __toImage_260(gd, opts) { return ev; } -var _$toImage_260 = __toImage_260; +var _$toImage_261 = __toImage_261; /** * Copyright 2012-2018, Plotly, Inc. @@ -58617,19 +59290,19 @@ var _$toImage_260 = __toImage_260; 'use strict'; -/* removed: var _$helpers_257 = require('./helpers'); */; +/* removed: var _$helpers_258 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_257.getDelay, - getRedrawFunc: _$helpers_257.getRedrawFunc, - clone: _$clonePlot_254, - toSVG: _$toSVG_261, - svgToImg: _$svgToImg_259, - toImage: _$toImage_260, - downloadImage: _$downloadImage_255 + getDelay: _$helpers_258.getDelay, + getRedrawFunc: _$helpers_258.getRedrawFunc, + clone: _$clonePlot_255, + toSVG: _$toSVG_262, + svgToImg: _$svgToImg_260, + toImage: _$toImage_261, + downloadImage: _$downloadImage_256 }; -var _$Snapshot_258 = Snapshot; +var _$Snapshot_259 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -58642,42 +59315,42 @@ var _$Snapshot_258 = Snapshot; 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_264 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_265 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_163.mergeArray(trace.text, cd, 'tx'); - _$lib_163.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_163.mergeArray(trace.customdata, cd, 'data'); - _$lib_163.mergeArray(trace.textposition, cd, 'tp'); + _$lib_164.mergeArray(trace.text, cd, 'tx'); + _$lib_164.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_164.mergeArray(trace.customdata, cd, 'data'); + _$lib_164.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_163.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_163.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_163.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_164.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_164.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_164.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_163.mergeArray(marker.size, cd, 'ms'); - _$lib_163.mergeArray(marker.opacity, cd, 'mo'); - _$lib_163.mergeArray(marker.symbol, cd, 'mx'); - _$lib_163.mergeArray(marker.color, cd, 'mc'); + _$lib_164.mergeArray(marker.size, cd, 'ms'); + _$lib_164.mergeArray(marker.opacity, cd, 'mo'); + _$lib_164.mergeArray(marker.symbol, cd, 'mx'); + _$lib_164.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_163.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_163.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_164.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_164.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_163.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_163.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_164.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_164.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -58692,11 +59365,11 @@ var _$arraysToCalcdata_264 = function arraysToCalcdata(cd, trace) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -var _$calcSelection_267 = function calcSelection(cd, trace) { - if(_$lib_163.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_163.tagSelected(cd, trace); +var _$calcSelection_268 = function calcSelection(cd, trace) { + if(_$lib_164.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_164.tagSelected(cd, trace); } }; @@ -58714,15 +59387,15 @@ var _$calcSelection_267 = function calcSelection(cd, trace) { /* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$calc_50 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_287 = require('./subtypes'); */; +/* removed: var _$subtypes_288 = require('./subtypes'); */; -var _$calcMarkerColorscale_270 = function calcMarkerColorscale(trace) { - if(_$subtypes_287.hasLines(trace) && _$hasColorscale_57(trace, 'line')) { +var _$calcMarkerColorscale_271 = function calcMarkerColorscale(trace) { + if(_$subtypes_288.hasLines(trace) && _$hasColorscale_57(trace, 'line')) { _$calc_50(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_287.hasMarkers(trace)) { + if(_$subtypes_288.hasMarkers(trace)) { if(_$hasColorscale_57(trace, 'marker')) { _$calc_50(trace, trace.marker.color, 'marker', 'c'); } @@ -58743,19 +59416,19 @@ var _$calcMarkerColorscale_270 = function calcMarkerColorscale(trace) { 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_266 = _$lib_163.isArrayOrTypedArray; +var __isArrayOrTypedArray_267 = _$lib_164.isArrayOrTypedArray; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; -var __BADNUM_266 = _$numerical_145.BADNUM; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; +var __BADNUM_267 = _$numerical_145.BADNUM; -/* removed: var _$subtypes_287 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_270 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_264 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_267 = require('./calc_selection'); */; +/* removed: var _$subtypes_288 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_271 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_265 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_268 = require('./calc_selection'); */; -function __calc_266(gd, trace) { - var xa = _$axes_205.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_205.getFromId(gd, trace.yaxis || 'y'); +function __calc_267(gd, trace) { + var xa = _$axes_206.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_206.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -58767,16 +59440,16 @@ function __calc_266(gd, trace) { for(var i = 0; i < serieslen; i++) { cd[i] = (_$fastIsnumeric_9(x[i]) && _$fastIsnumeric_9(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_266, y: __BADNUM_266}; + {x: __BADNUM_267, y: __BADNUM_267}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_264(cd, trace); - _$calcMarkerColorscale_270(trace); - _$calcSelection_267(cd, trace); + _$arraysToCalcdata_265(cd, trace); + _$calcMarkerColorscale_271(trace); + _$calcSelection_268(cd, trace); gd.firstscatter = false; return cd; @@ -58809,9 +59482,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_287.hasMarkers(trace) && !_$subtypes_287.hasText(trace)) + (!_$subtypes_288.hasMarkers(trace) && !_$subtypes_288.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -58830,12 +59503,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_205.expand(xa, x, xOptions); - _$axes_205.expand(ya, y, yOptions); + _$axes_206.expand(xa, x, xOptions); + _$axes_206.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_287.hasMarkers(trace)) return; + if(!_$subtypes_288.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -58853,10 +59526,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_266(marker.size)) { + if(__isArrayOrTypedArray_267(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_205.setConvert(ax); + _$axes_206.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -58871,8 +59544,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_266 = { - calc: __calc_266, +var _$calc_267 = { + calc: __calc_267, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -58890,7 +59563,7 @@ var _$calc_266 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_268 = function cleanData(fullData) { +var _$cleanData_269 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -58957,21 +59630,21 @@ var _$constants_45 = { /* removed: var _$tinycolor_25 = require('tinycolor2'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$axes_205 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$axes_206 = require('../../plots/cartesian/axes'); */; /* removed: var _$dragelement_65 = require('../dragelement'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -var __extendFlat_47 = _$extend_156.extendFlat; -/* removed: var _$setCursor_182 = require('../../lib/setcursor'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +var __extendFlat_47 = _$extend_157.extendFlat; +/* removed: var _$setCursor_183 = require('../../lib/setcursor'); */; /* removed: var _$drawing_68 = require('../drawing'); */; /* removed: var _$color_43 = require('../color'); */; /* removed: var _$titles_136 = require('../titles'); */; -/* removed: var _$svg_text_utils_184 = require('../../lib/svg_text_utils'); */; +/* removed: var _$svg_text_utils_185 = require('../../lib/svg_text_utils'); */; var __LINE_SPACING_47 = _$alignment_143.LINE_SPACING; -/* removed: var _$handleAxisDefaults_207 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handleAxisDefaults_208 = require('../../plots/cartesian/axis_defaults'); */; /* removed: var _$handlePositionDefaults_221 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_217 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$layout_attributes_218 = require('../../plots/cartesian/layout_attributes'); */; /* removed: var _$attributes_44 = require('./attributes'); */; var cn = _$constants_45.cn; @@ -59135,11 +59808,11 @@ var _$draw_47 = function draw(gd, id) { // Coerce w.r.t. Axes layoutAttributes: // re-use axes.js logic without updating _fullData function coerce(attr, dflt) { - return _$lib_163.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_217, attr, dflt); + return _$lib_164.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_218, attr, dflt); } // Prepare the Plotly axis object - _$handleAxisDefaults_207(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handleAxisDefaults_208(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); _$handlePositionDefaults_221(cbAxisIn, cbAxisOut, coerce, axisOptions); // position can't go in through supplyDefaults @@ -59161,14 +59834,14 @@ var _$draw_47 = function draw(gd, id) { cbAxisOut.tick0 = opts.levels.start; var dtick = opts.levels.size; // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_163.constrain( + var autoNtick = _$lib_164.constrain( (yBottomPx - yTopPx) / 50, 4, 15) + 1, dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick); if(dtFactor > 1) { var dtexp = Math.pow(10, Math.floor( Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_163.roundUp(dtFactor / dtexp, [2, 5, 10]); + dtick *= dtexp * _$lib_164.roundUp(dtFactor / dtexp, [2, 5, 10]); // if the contours are at round multiples, reset tick0 // so they're still at round multiples. Otherwise, // keep the first label on the first contour level @@ -59189,20 +59862,21 @@ var _$draw_47 = function draw(gd, id) { cbAxisOut.setScale(); // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_6.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); + var container = _$lib_164.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_6.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); + container.attr('transform', 'translate(' + Math.round(gs.l) + ',' + Math.round(gs.t) + ')'); // TODO: this opposite transform is a hack until we make it @@ -59273,7 +59947,7 @@ var _$draw_47 = function draw(gd, id) { } else { cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_184.lineCount(titleText); + var nlines = _$svg_text_utils_185.lineCount(titleText); titleTrans[1] += (1 - nlines) * lineSize; } @@ -59359,9 +60033,9 @@ var _$draw_47 = function draw(gd, id) { // so we don't need such complicated logic in Titles.draw // if title is on the top or bottom, we've already drawn it // this title call only handles side=right - return _$lib_163.syncOrAsync([ + return _$lib_164.syncOrAsync([ function() { - return _$axes_205.doTicks(gd, cbAxisOut, true); + return _$axes_206.doTicks(gd, cbAxisOut, true); }, function() { if(['top', 'bottom'].indexOf(opts.titleside) === -1) { @@ -59392,7 +60066,7 @@ var _$draw_47 = function draw(gd, id) { function drawTitle(titleClass, titleOpts) { var trace = getTrace(), propName; - if(_$registry_253.traceIs(trace, 'markerColorscale')) { + if(_$registry_254.traceIs(trace, 'markerColorscale')) { propName = 'marker.colorbar.title'; } else propName = 'colorbar.title'; @@ -59492,7 +60166,7 @@ var _$draw_47 = function draw(gd, id) { }); } - var cbDone = _$lib_163.syncOrAsync([ + var cbDone = _$lib_164.syncOrAsync([ _$plots_245.previousPromises, drawAxis, _$plots_245.previousPromises, @@ -59512,7 +60186,7 @@ var _$draw_47 = function draw(gd, id) { gd: gd, prepFn: function() { t0 = container.attr('transform'); - _$setCursor_182(container); + _$setCursor_183(container); }, moveFn: function(dx, dy) { container.attr('transform', @@ -59525,13 +60199,13 @@ var _$draw_47 = function draw(gd, id) { var csr = _$dragelement_65.getCursor(xf, yf, opts.xanchor, opts.yanchor); - _$setCursor_182(container, csr); + _$setCursor_183(container, csr); }, doneFn: function() { - _$setCursor_182(container); + _$setCursor_183(container); if(xf !== undefined && yf !== undefined) { - _$registry_253.call('restyle', + _$registry_254.call('restyle', gd, {'colorbar.x': xf, 'colorbar.y': yf}, getTrace().index @@ -59561,8 +60235,8 @@ var _$draw_47 = function draw(gd, id) { // setter - for multi-part properties, // set only the parts that are provided - opts[name] = _$lib_163.isPlainObject(opts[name]) ? - _$lib_163.extendFlat(opts[name], v) : + opts[name] = _$lib_164.isPlainObject(opts[name]) ? + _$lib_164.extendFlat(opts[name], v) : v; return component; @@ -59599,13 +60273,13 @@ var _$draw_47 = function draw(gd, id) { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$plots_245 = require('../../plots/plots'); */; /* removed: var _$colorscale_58 = require('../../components/colorscale'); */; /* removed: var _$draw_47 = require('../../components/colorbar/draw'); */; -var _$colorbar_269 = function colorbar(gd, cd) { +var _$colorbar_270 = function colorbar(gd, cd) { var trace = cd[0].trace, marker = trace.marker, cbId = 'cb' + trace.uid; @@ -59623,8 +60297,8 @@ var _$colorbar_269 = function colorbar(gd, cd) { cmin = marker.cmin, cmax = marker.cmax; - if(!_$fastIsnumeric_9(cmin)) cmin = _$lib_163.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_9(cmax)) cmax = _$lib_163.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_9(cmin)) cmin = _$lib_164.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_9(cmax)) cmax = _$lib_164.aggNums(Math.max, null, vals); var cb = cd[0].t.cb = _$draw_47(gd, cbId); var sclFunc = _$colorscale_58.makeColorScaleFunc( @@ -59653,9 +60327,9 @@ var _$colorbar_269 = function colorbar(gd, cd) { 'use strict'; /* removed: var _$color_43 = require('../../components/color'); */; -var __isArrayOrTypedArray_274 = _$lib_163.isArrayOrTypedArray; +var __isArrayOrTypedArray_275 = _$lib_164.isArrayOrTypedArray; -var _$fillColorDefaults_274 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_275 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -59663,10 +60337,10 @@ var _$fillColorDefaults_274 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_274(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_275(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_274(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_275(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } @@ -59688,11 +60362,11 @@ var _$fillColorDefaults_274 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_278 = _$lib_163.isArrayOrTypedArray; +var __isArrayOrTypedArray_279 = _$lib_164.isArrayOrTypedArray; /* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_53 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_278 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_279 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); @@ -59701,7 +60375,7 @@ var _$lineDefaults_278 = function lineDefaults(traceIn, traceOut, defaultColor, _$colorScaleDefaults_53(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_278(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_279(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -59722,7 +60396,7 @@ var _$lineDefaults_278 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_280 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_281 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -59742,7 +60416,7 @@ var _$handleLineShapeDefaults_280 = function handleLineShapeDefaults(traceIn, tr /* removed: var _$hasColorscale_57 = require('../../components/colorscale/has_colorscale'); */; /* removed: var _$colorScaleDefaults_53 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_287 = require('./subtypes'); */; +/* removed: var _$subtypes_288 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -59750,8 +60424,8 @@ var _$handleLineShapeDefaults_280 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_283 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_287.isBubble(traceIn), +var _$markerDefaults_284 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_288.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -59820,17 +60494,17 @@ var _$markerDefaults_283 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_288 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_289 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_163.coerceFont(coerce, 'textfont', layout.font); + _$lib_164.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -59849,15 +60523,15 @@ var _$text_defaults_288 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; -var _$handleXYDefaults_289 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { +var _$handleXYDefaults_290 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { var len, x = coerce('x'), y = coerce('y'); - var handleCalendarDefaults = _$registry_253.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_254.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); if(x) { @@ -59893,27 +60567,27 @@ var _$handleXYDefaults_289 = function handleXYDefaults(traceIn, traceOut, layout 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; -/* removed: var _$attributes_265 = require('./attributes'); */; -/* removed: var _$constants_271 = require('./constants'); */; -/* removed: var _$subtypes_287 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_289 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_283 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_278 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_280 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_288 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_274 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_266 = require('./attributes'); */; +/* removed: var _$constants_272 = require('./constants'); */; +/* removed: var _$subtypes_288 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_290 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_284 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_279 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_281 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_289 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_275 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_272 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_273 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_163.coerce(traceIn, traceOut, _$attributes_265, attr, dflt); + return _$lib_164.coerce(traceIn, traceOut, _$attributes_266, attr, dflt); } - var len = _$handleXYDefaults_289(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_290(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_271.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_272.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -59923,24 +60597,24 @@ var _$supplyDefaults_272 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_287.hasLines(traceOut)) { - _$lineDefaults_278(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_280(traceIn, traceOut, coerce); + if(_$subtypes_288.hasLines(traceOut)) { + _$lineDefaults_279(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_281(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_287.hasMarkers(traceOut)) { - _$markerDefaults_283(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_288.hasMarkers(traceOut)) { + _$markerDefaults_284(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_287.hasText(traceOut)) { - _$text_defaults_288(traceIn, traceOut, layout, coerce); + if(_$subtypes_288.hasText(traceOut)) { + _$text_defaults_289(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_287.hasMarkers(traceOut) || _$subtypes_287.hasText(traceOut)) { + if(_$subtypes_288.hasMarkers(traceOut) || _$subtypes_288.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -59948,8 +60622,8 @@ var _$supplyDefaults_272 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_274(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_287.hasLines(traceOut)) _$handleLineShapeDefaults_280(traceIn, traceOut, coerce); + _$fillColorDefaults_275(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_288.hasLines(traceOut)) _$handleLineShapeDefaults_281(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -59957,11 +60631,11 @@ var _$supplyDefaults_272 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_253.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_254.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_163.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_164.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -59974,7 +60648,7 @@ var _$supplyDefaults_272 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /** Fill hover 'pointData' container with 'correct' hover text value * @@ -59989,15 +60663,15 @@ var _$supplyDefaults_272 = function supplyDefaults(traceIn, traceOut, defaultCol * @param {object} trace * @param {object || array} contOut (mutated here) */ -var _$fillHoverText_273 = function fillHoverText(calcPt, trace, contOut) { +var _$fillHoverText_274 = function fillHoverText(calcPt, trace, contOut) { var fill = Array.isArray(contOut) ? function(v) { contOut.push(v); } : function(v) { contOut.text = v; }; - var htx = _$lib_163.extractOption(calcPt, trace, 'htx', 'hovertext'); + var htx = _$lib_164.extractOption(calcPt, trace, 'htx', 'hovertext'); if(isValid(htx)) return fill(htx); - var tx = _$lib_163.extractOption(calcPt, trace, 'tx', 'text'); + var tx = _$lib_164.extractOption(calcPt, trace, 'tx', 'text'); if(isValid(tx)) return fill(tx); }; @@ -60018,10 +60692,10 @@ function isValid(v) { 'use strict'; /* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$subtypes_287 = require('./subtypes'); */; +/* removed: var _$subtypes_288 = require('./subtypes'); */; -var _$getTraceColor_275 = function getTraceColor(trace, di) { +var _$getTraceColor_276 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes @@ -60052,7 +60726,7 @@ var _$getTraceColor_275 = function getTraceColor(trace, di) { else { lc = (trace.line || {}).color; return (lc && _$color_43.opacity(lc) && - _$subtypes_287.hasLines(trace) && trace.line.width) ? + _$subtypes_288.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -60068,14 +60742,14 @@ var _$getTraceColor_275 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$getTraceColor_275 = require('./get_trace_color'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$getTraceColor_276 = require('./get_trace_color'); */; /* removed: var _$color_43 = require('../../components/color'); */; -/* removed: var _$fillHoverText_273 = require('./fill_hover_text'); */; +/* removed: var _$fillHoverText_274 = require('./fill_hover_text'); */; -var _$hoverPoints_276 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_277 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -60128,8 +60802,8 @@ var _$hoverPoints_276 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_163.extendFlat(pointData, { - color: _$getTraceColor_275(trace, di), + _$lib_164.extendFlat(pointData, { + color: _$getTraceColor_276(trace, di), x0: xc - rad, x1: xc + rad, @@ -60142,8 +60816,8 @@ var _$hoverPoints_276 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_273(di, trace, pointData); - _$registry_253.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_274(di, trace, pointData); + _$registry_254.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -60215,7 +60889,7 @@ var _$hoverPoints_276 = function hoverPoints(pointData, xval, yval, hovermode) { color = trace.line.color; } - _$lib_163.extendFlat(pointData, { + _$lib_164.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -60249,14 +60923,14 @@ var _$hoverPoints_276 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_279 = _$numerical_145.BADNUM; -/* removed: var _$lib_163 = require('../../lib'); */; -var __segmentsIntersect_279 = _$lib_163.segmentsIntersect; -var constrain = _$lib_163.constrain; -/* removed: var _$constants_271 = require('./constants'); */; +var __BADNUM_280 = _$numerical_145.BADNUM; +/* removed: var _$lib_164 = require('../../lib'); */; +var __segmentsIntersect_280 = _$lib_164.segmentsIntersect; +var constrain = _$lib_164.constrain; +/* removed: var _$constants_272 = require('./constants'); */; -var _$linePoints_279 = function linePoints(d, opts) { +var _$linePoints_280 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -60265,7 +60939,7 @@ var _$linePoints_279 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_271.minTolerance; + var minTolerance = _$constants_272.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -60303,7 +60977,7 @@ var _$linePoints_279 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_279 || y === __BADNUM_279) return di.intoCenter || false; + if(x === __BADNUM_280 || y === __BADNUM_280) return di.intoCenter || false; return [x, y]; } @@ -60311,7 +60985,7 @@ var _$linePoints_279 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_271.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_272.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -60323,7 +60997,7 @@ var _$linePoints_279 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_271.maxScreensAway; + var maxScreensAway = _$constants_272.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -60352,7 +61026,7 @@ var _$linePoints_279 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_279(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_280(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -60406,7 +61080,7 @@ var _$linePoints_279 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_163.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_164.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -60659,7 +61333,7 @@ var _$linePoints_279 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_281 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_282 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -60701,17 +61375,17 @@ var _$linkTraces_281 = function linkTraces(gd, plotinfo, cdscatter) { /* removed: var _$d3_6 = require('d3'); */; -/* removed: var _$registry_253 = require('../../registry'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$registry_254 = require('../../registry'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$subtypes_287 = require('./subtypes'); */; -/* removed: var _$linePoints_279 = require('./line_points'); */; -/* removed: var _$linkTraces_281 = require('./link_traces'); */; -var __polygonTester_284 = _$polygon_175.tester; +/* removed: var _$subtypes_288 = require('./subtypes'); */; +/* removed: var _$linePoints_280 = require('./line_points'); */; +/* removed: var _$linkTraces_282 = require('./link_traces'); */; +var __polygonTester_285 = _$polygon_176.tester; -var _$plot_284 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_285 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -60720,9 +61394,8 @@ var _$plot_284 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -60734,7 +61407,7 @@ var _$plot_284 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_281(gd, plotinfo, cdscatter); + _$linkTraces_282(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -60773,12 +61446,12 @@ var _$plot_284 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_284(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_285(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_284(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_285(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -60833,7 +61506,7 @@ function createFills(gd, scatterlayer, plotinfo) { }); } -function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_285(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -60855,7 +61528,7 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran tr = _$d3_6.select(element); // error bars are at the bottom - _$registry_253.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_254.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -60867,7 +61540,7 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -60893,11 +61566,11 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_163.noop; + makeUpdate = _$lib_164.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_287.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_288.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -60934,7 +61607,7 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_279(cdscatter, { + segments = _$linePoints_280(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -60949,7 +61622,7 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_284(segments[i]); + trace._polygons[i] = __polygonTester_285(segments[i]); } if(segments.length) { @@ -60975,7 +61648,7 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_287.hasLines(trace) && pts.length > 1) { + if(_$subtypes_288.hasLines(trace) && pts.length > 1) { var el = _$d3_6.select(this); // This makes the coloring work correctly: @@ -61102,19 +61775,19 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = d[0].trace, s = _$d3_6.select(this), - showMarkers = _$subtypes_287.hasMarkers(trace), - showText = _$subtypes_287.hasText(trace); + showMarkers = _$subtypes_288.hasMarkers(trace), + showText = _$subtypes_288.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_163.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_164.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_163.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_164.identity; } // marker points @@ -61235,11 +61908,11 @@ function __plotOne_284(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_6.extent(_$lib_163.simpleMap(xa.range, xa.r2c)), - yr = _$d3_6.extent(_$lib_163.simpleMap(ya.range, ya.r2c)); + xr = _$d3_6.extent(_$lib_164.simpleMap(xa.range, xa.r2c)), + yr = _$d3_6.extent(_$lib_164.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_287.hasMarkers(trace)) return; + if(!_$subtypes_288.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -61254,7 +61927,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_287.hasMarkers(tracei) && + if(_$subtypes_288.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -61285,9 +61958,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_287 = require('./subtypes'); */; +/* removed: var _$subtypes_288 = require('./subtypes'); */; -var _$selectPoints_285 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_286 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -61298,7 +61971,7 @@ var _$selectPoints_285 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_287.hasMarkers(trace) && !_$subtypes_287.hasText(trace)); + var hasOnlyLines = (!_$subtypes_288.hasMarkers(trace) && !_$subtypes_288.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -61341,9 +62014,9 @@ var _$selectPoints_285 = function selectPoints(searchInfo, polygon) { /* removed: var _$d3_6 = require('d3'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$registry_253 = require('../../registry'); */; +/* removed: var _$registry_254 = require('../../registry'); */; -function __style_286(gd, cd) { +function __style_287(gd, cd) { var s = cd ? cd[0].node3 : _$d3_6.select(gd).selectAll('g.trace.scatter'); s.style('opacity', function(d) { @@ -61362,7 +62035,7 @@ function __style_286(gd, cd) { s.selectAll('g.trace path.js-fill') .call(_$drawing_68.fillGroupStyle); - _$registry_253.getComponentMethod('errorbars', 'style')(s); + _$registry_254.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { @@ -61375,8 +62048,8 @@ function stylePoints(sel, trace, gd) { _$drawing_68.selectedTextStyle(txs, trace); } -var _$style_286 = { - style: __style_286, +var _$style_287 = { + style: __style_287, stylePoints: stylePoints }; @@ -61393,35 +62066,35 @@ var _$style_286 = { var Scatter = {}; -/* removed: var _$subtypes_287 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_287.hasLines; -Scatter.hasMarkers = _$subtypes_287.hasMarkers; -Scatter.hasText = _$subtypes_287.hasText; -Scatter.isBubble = _$subtypes_287.isBubble; +/* removed: var _$subtypes_288 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_288.hasLines; +Scatter.hasMarkers = _$subtypes_288.hasMarkers; +Scatter.hasText = _$subtypes_288.hasText; +Scatter.isBubble = _$subtypes_288.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_265; -Scatter.supplyDefaults = _$supplyDefaults_272; -Scatter.cleanData = _$cleanData_268; -Scatter.calc = _$calc_266.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_264; -Scatter.plot = _$plot_284; -Scatter.colorbar = _$colorbar_269; -Scatter.style = _$style_286.style; -Scatter.hoverPoints = _$hoverPoints_276; -Scatter.selectPoints = _$selectPoints_285; +Scatter.attributes = _$attributes_266; +Scatter.supplyDefaults = _$supplyDefaults_273; +Scatter.cleanData = _$cleanData_269; +Scatter.calc = _$calc_267.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_265; +Scatter.plot = _$plot_285; +Scatter.colorbar = _$colorbar_270; +Scatter.style = _$style_287.style; +Scatter.hoverPoints = _$hoverPoints_277; +Scatter.selectPoints = _$selectPoints_286; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_216; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_217; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_277 = Scatter; +var _$Scatter_278 = Scatter; var _$core_148 = {}; /** @@ -61435,7 +62108,7 @@ var _$core_148 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_148.version = '1.35.2'; +_$core_148.version = '1.36.0'; // inject promise polyfill _$es6Promise_7.polyfill(); @@ -61447,24 +62120,24 @@ _$plotcss_1; _$mathjax_config_149; // include registry module and expose register method -/* removed: var _$registry_253 = require('./registry'); */; -var register = _$core_148.register = _$registry_253.register; +/* removed: var _$registry_254 = require('./registry'); */; +var register = _$core_148.register = _$registry_254.register; // expose plot api methods -/* removed: var _$plot_api_192 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_192); +/* removed: var _$plot_api_193 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_193); for(var i = 0; i < methodNames.length; i++) { var __name_148 = methodNames[i]; - _$core_148[__name_148] = _$plot_api_192[__name_148]; + _$core_148[__name_148] = _$plot_api_193[__name_148]; register({ moduleType: 'apiMethod', name: __name_148, - fn: _$plot_api_192[__name_148] + fn: _$plot_api_193[__name_148] }); } // scatter is the only trace included by default -register(_$Scatter_277); +register(_$Scatter_278); // register all registrable components modules register([ @@ -61484,8 +62157,8 @@ register([ // locales en and en-US are required for default behavior register([ - _$localeEn_188, - _$localeEnUs_187 + _$localeEn_189, + _$localeEnUs_188 ]); // plot icons @@ -61494,9 +62167,9 @@ _$core_148.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk _$core_148.Plots = _$plots_245; _$core_148.Fx = _$fx_85; -_$core_148.Snapshot = _$Snapshot_258; -_$core_148.PlotSchema = _$plot_schema_196; -_$core_148.Queue = _$queue_177; +_$core_148.Snapshot = _$Snapshot_259; +_$core_148.PlotSchema = _$plot_schema_197; +_$core_148.Queue = _$queue_178; // export d3 used in the bundle _$core_148.d3 = _$d3_6; @@ -86548,12 +87221,12 @@ var _$constants_237 = { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; var __defaultLine_241 = _$color_43.defaultLine; var __domainAttrs_241 = _$domain_231.attributes; /* removed: var _$font_attributes_232 = require('../font_attributes'); */; -var textposition = _$attributes_265.textposition; -var __overrideAll_241 = _$edit_types_190.overrideAll; +var textposition = _$attributes_266.textposition; +var __overrideAll_241 = _$edit_types_191.overrideAll; var fontAttr = _$font_attributes_232({ @@ -86561,7 +87234,7 @@ var fontAttr = _$font_attributes_232({ fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular'; var _$layout_attributes_241 = __overrideAll_241({ - _arrayAttrRegexps: [_$lib_163.counterRegex('mapbox', '.layers', true)], + _arrayAttrRegexps: [_$lib_164.counterRegex('mapbox', '.layers', true)], domain: __domainAttrs_241({name: 'mapbox'}), @@ -86715,7 +87388,7 @@ var _$layout_attributes_241 = __overrideAll_241({ }, textfont: fontAttr, - textposition: _$lib_163.extendFlat({}, textposition, { arrayOk: false }) + textposition: _$lib_164.extendFlat({}, textposition, { arrayOk: false }) } } }, 'plot', 'from-root'); @@ -86731,7 +87404,7 @@ var _$layout_attributes_241 = __overrideAll_241({ 'use strict'; -/* removed: var _$lib_163 = require('../lib'); */; +/* removed: var _$lib_164 = require('../lib'); */; var handleDomainDefaults = _$domain_231.defaults; @@ -86762,7 +87435,7 @@ var handleDomainDefaults = _$domain_231.defaults; * additional items needed by this function here as well * } */ -var _$handleSubplotDefaults_252 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { +var _$handleSubplotDefaults_253 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { var subplotType = opts.type; var subplotAttributes = opts.attributes; var handleDefaults = opts.handleDefaults; @@ -86774,7 +87447,7 @@ var _$handleSubplotDefaults_252 = function handleSubplotDefaults(layoutIn, layou var subplotLayoutIn, subplotLayoutOut; function coerce(attr, dflt) { - return _$lib_163.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); + return _$lib_164.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); } for(var i = 0; i < idsLength; i++) { @@ -86806,14 +87479,14 @@ var _$handleSubplotDefaults_252 = function handleSubplotDefaults(layoutIn, layou 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -/* removed: var _$handleSubplotDefaults_252 = require('../subplot_defaults'); */; +/* removed: var _$handleSubplotDefaults_253 = require('../subplot_defaults'); */; /* removed: var _$layout_attributes_241 = require('./layout_attributes'); */; var _$supplyLayoutDefaults_242 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_252(layoutIn, layoutOut, fullData, { + _$handleSubplotDefaults_253(layoutIn, layoutOut, fullData, { type: 'mapbox', attributes: _$layout_attributes_241, handleDefaults: handleDefaults, @@ -86844,14 +87517,14 @@ function handleLayerDefaults(containerIn, containerOut) { var layerIn, layerOut; function coerce(attr, dflt) { - return _$lib_163.coerce(layerIn, layerOut, _$layout_attributes_241.layers, attr, dflt); + return _$lib_164.coerce(layerIn, layerOut, _$layout_attributes_241.layers, attr, dflt); } for(var i = 0; i < layersIn.length; i++) { layerIn = layersIn[i]; layerOut = {}; - if(!_$lib_163.isPlainObject(layerIn)) continue; + if(!_$lib_164.isPlainObject(layerIn)) continue; var sourceType = coerce('sourcetype'); coerce('source'); @@ -86882,7 +87555,7 @@ function handleLayerDefaults(containerIn, containerOut) { coerce('symbol.iconsize'); coerce('symbol.text'); - _$lib_163.coerceFont(coerce, 'symbol.textfont'); + _$lib_164.coerceFont(coerce, 'symbol.textfont'); coerce('symbol.textposition'); } @@ -86902,7 +87575,7 @@ function handleLayerDefaults(containerIn, containerOut) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /** * Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset' @@ -86921,7 +87594,7 @@ var _$convertTextOpts_238 = function convertTextOpts(textposition, iconSize) { hPos = parts[1]; // ballpack values - var factor = _$lib_163.isArrayOrTypedArray(iconSize) ? _$lib_163.mean(iconSize) : iconSize, + var factor = _$lib_164.isArrayOrTypedArray(iconSize) ? _$lib_164.mean(iconSize) : iconSize, xInc = 0.5 + (factor / 100), yInc = 1.5 + (factor / 100); @@ -86973,7 +87646,7 @@ var _$convertTextOpts_238 = function convertTextOpts(textposition, iconSize) { 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$convertTextOpts_238 = require('./convert_text_opts'); */; function MapboxLayer(mapbox, index) { @@ -87086,7 +87759,7 @@ function isVisible(opts) { var source = opts.source; return ( - _$lib_163.isPlainObject(source) || + _$lib_164.isPlainObject(source) || (typeof source === 'string' && source.length > 0) ); } @@ -87098,7 +87771,7 @@ function convertOpts(opts) { switch(opts.type) { case 'circle': - _$lib_163.extendFlat(paint, { + _$lib_164.extendFlat(paint, { 'circle-radius': opts.circle.radius, 'circle-color': opts.color, 'circle-opacity': opts.opacity @@ -87106,7 +87779,7 @@ function convertOpts(opts) { break; case 'line': - _$lib_163.extendFlat(paint, { + _$lib_164.extendFlat(paint, { 'line-width': opts.line.width, 'line-color': opts.color, 'line-opacity': opts.opacity @@ -87114,7 +87787,7 @@ function convertOpts(opts) { break; case 'fill': - _$lib_163.extendFlat(paint, { + _$lib_164.extendFlat(paint, { 'fill-color': opts.color, 'fill-outline-color': opts.fill.outlinecolor, 'fill-opacity': opts.opacity @@ -87127,7 +87800,7 @@ function convertOpts(opts) { var symbol = opts.symbol, textOpts = _$convertTextOpts_238(symbol.textposition, symbol.iconsize); - _$lib_163.extendFlat(layout, { + _$lib_164.extendFlat(layout, { 'icon-image': symbol.icon + '-15', 'icon-size': symbol.iconsize / 10, @@ -87140,7 +87813,7 @@ function convertOpts(opts) { // 'text-font': symbol.textfont.family.split(', '), }); - _$lib_163.extendFlat(paint, { + _$lib_164.extendFlat(paint, { 'icon-color': opts.color, 'text-color': symbol.textfont.color, 'text-opacity': opts.opacity @@ -87189,9 +87862,9 @@ var _$createMapboxLayer_240 = function createMapboxLayer(mapbox, index, opts) { /* removed: var _$mapboxGl_14 = require('mapbox-gl'); */; /* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; /* removed: var _$dragelement_65 = require('../../components/dragelement'); */; -/* removed: var _$prepSelect_223 = require('../cartesian/select'); */; +var __prepSelect_243 = _$select_223.prepSelect; /* removed: var _$constants_237 = require('./constants'); */; /* removed: var _$layout_attributes_241 = require('./layout_attributes'); */; /* removed: var _$createMapboxLayer_240 = require('./layers'); */; @@ -87328,7 +88001,7 @@ __proto_243.createMap = function(calcData, fullLayout, resolve, reject) { if(eventData.originalEvent) { var update = {}; - update[self.id] = _$lib_163.extendFlat({}, view); + update[self.id] = _$lib_164.extendFlat({}, view); gd.emit('plotly_relayout', update); } }); @@ -87561,7 +88234,7 @@ __proto_243.updateFx = function(fullLayout) { }; dragOptions.prepFn = function(e, startX, startY) { - _$prepSelect_223(e, startX, startY, dragOptions, dragMode); + __prepSelect_243(e, startX, startY, dragOptions, dragMode); }; _$dragelement_65.init(dragOptions); @@ -87662,7 +88335,7 @@ function getStyleObj(val) { var styleDflt = _$layout_attributes_241.style.dflt; var styleObj = {}; - if(_$lib_163.isPlainObject(val)) { + if(_$lib_164.isPlainObject(val)) { styleObj.id = val.id; styleObj.style = val; } else if(typeof val === 'string') { @@ -87702,7 +88375,7 @@ var _$mapbox_239 = {}; /* removed: var _$mapboxGl_14 = require('mapbox-gl'); */; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; var getSubplotCalcData = _$get_data_234.getSubplotCalcData; /* removed: var _$xmlns_namespaces_147 = require('../../constants/xmlns_namespaces'); */; @@ -87712,7 +88385,7 @@ var getSubplotCalcData = _$get_data_234.getSubplotCalcData; var MAPBOX = 'mapbox'; for(var k in _$constants_237.styleRules) { - _$lib_163.addStyleRule('.mapboxgl-' + k, _$constants_237.styleRules[k]); + _$lib_164.addStyleRule('.mapboxgl-' + k, _$constants_237.styleRules[k]); } _$mapbox_239.name = MAPBOX; @@ -87721,7 +88394,7 @@ _$mapbox_239.attr = 'subplot'; _$mapbox_239.idRoot = MAPBOX; -_$mapbox_239.idRegex = _$mapbox_239.attrRegex = _$lib_163.counterRegex(MAPBOX); +_$mapbox_239.idRegex = _$mapbox_239.attrRegex = _$lib_164.counterRegex(MAPBOX); _$mapbox_239.attributes = { subplot: { @@ -87769,7 +88442,7 @@ _$mapbox_239.plot = function plotMapbox(gd) { if(!mapbox.viewInitial) { mapbox.viewInitial = { - center: _$lib_163.extendFlat({}, opts.center), + center: _$lib_164.extendFlat({}, opts.center), zoom: opts.zoom, bearing: opts.bearing, pitch: opts.pitch @@ -87860,15 +88533,15 @@ _$mapbox_239.updateFx = function(fullLayout) { 'use strict'; /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -var __BADNUM_291 = _$numerical_145.BADNUM; +var __BADNUM_292 = _$numerical_145.BADNUM; -/* removed: var _$calcMarkerColorscale_270 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_264 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_267 = require('../scatter/calc_selection'); */; +/* removed: var _$calcMarkerColorscale_271 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_265 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_268 = require('../scatter/calc_selection'); */; -var ____291 = _$lib_163._; +var ____292 = _$lib_164._; -var _$calc_291 = function calc(gd, trace) { +var _$calc_292 = function calc(gd, trace) { var hasLocationData = Array.isArray(trace.locations); var len = hasLocationData ? trace.locations.length : trace._length; var calcTrace = new Array(len); @@ -87884,19 +88557,19 @@ var _$calc_291 = function calc(gd, trace) { var lat = trace.lat[i]; if(_$fastIsnumeric_9(lon) && _$fastIsnumeric_9(lat)) calcPt.lonlat = [+lon, +lat]; - else calcPt.lonlat = [__BADNUM_291, __BADNUM_291]; + else calcPt.lonlat = [__BADNUM_292, __BADNUM_292]; } } - _$arraysToCalcdata_264(calcTrace, trace); - _$calcMarkerColorscale_270(trace); - _$calcSelection_267(calcTrace, trace); + _$arraysToCalcdata_265(calcTrace, trace); + _$calcMarkerColorscale_271(trace); + _$calcSelection_268(calcTrace, trace); if(len) { calcTrace[0].t = { labels: { - lat: ____291(gd, 'lat:') + ' ', - lon: ____291(gd, 'lon:') + ' ' + lat: ____292(gd, 'lat:') + ' ', + lon: ____292(gd, 'lon:') + ' ' } }; } @@ -87914,19 +88587,19 @@ var _$calc_291 = function calc(gd, trace) { 'use strict'; -/* removed: var _$attributes_265 = require('../scatter/attributes'); */; -/* removed: var _$attributes_202 = require('../../plots/attributes'); */; +/* removed: var _$attributes_266 = require('../scatter/attributes'); */; +/* removed: var _$attributes_203 = require('../../plots/attributes'); */; /* removed: var _$makeColorScaleAttributes_51 = require('../../components/colorscale/color_attributes'); */; -var __dash_290 = _$attributes_67.dash; +var __dash_291 = _$attributes_67.dash; -var __extendFlat_290 = _$extend_156.extendFlat; -var __overrideAll_290 = _$edit_types_190.overrideAll; +var __extendFlat_291 = _$extend_157.extendFlat; +var __overrideAll_291 = _$edit_types_191.overrideAll; -var __scatterMarkerAttrs_290 = _$attributes_265.marker, - __scatterLineAttrs_290 = _$attributes_265.line, - scatterMarkerLineAttrs = __scatterMarkerAttrs_290.line; +var __scatterMarkerAttrs_291 = _$attributes_266.marker, + __scatterLineAttrs_291 = _$attributes_266.line, + scatterMarkerLineAttrs = __scatterMarkerAttrs_291.line; -var _$attributes_290 = __overrideAll_290({ +var _$attributes_291 = __overrideAll_291({ lon: { valType: 'data_array', @@ -87948,40 +88621,40 @@ var _$attributes_290 = __overrideAll_290({ }, - mode: __extendFlat_290({}, _$attributes_265.mode, {dflt: 'markers'}), + mode: __extendFlat_291({}, _$attributes_266.mode, {dflt: 'markers'}), - text: __extendFlat_290({}, _$attributes_265.text, { + text: __extendFlat_291({}, _$attributes_266.text, { }), - hovertext: __extendFlat_290({}, _$attributes_265.hovertext, { + hovertext: __extendFlat_291({}, _$attributes_266.hovertext, { }), - textfont: _$attributes_265.textfont, - textposition: _$attributes_265.textposition, + textfont: _$attributes_266.textfont, + textposition: _$attributes_266.textposition, line: { - color: __scatterLineAttrs_290.color, - width: __scatterLineAttrs_290.width, - dash: __dash_290 - }, - connectgaps: _$attributes_265.connectgaps, - - marker: __extendFlat_290({ - symbol: __scatterMarkerAttrs_290.symbol, - opacity: __scatterMarkerAttrs_290.opacity, - size: __scatterMarkerAttrs_290.size, - sizeref: __scatterMarkerAttrs_290.sizeref, - sizemin: __scatterMarkerAttrs_290.sizemin, - sizemode: __scatterMarkerAttrs_290.sizemode, - showscale: __scatterMarkerAttrs_290.showscale, - colorbar: __scatterMarkerAttrs_290.colorbar, - line: __extendFlat_290({ + color: __scatterLineAttrs_291.color, + width: __scatterLineAttrs_291.width, + dash: __dash_291 + }, + connectgaps: _$attributes_266.connectgaps, + + marker: __extendFlat_291({ + symbol: __scatterMarkerAttrs_291.symbol, + opacity: __scatterMarkerAttrs_291.opacity, + size: __scatterMarkerAttrs_291.size, + sizeref: __scatterMarkerAttrs_291.sizeref, + sizemin: __scatterMarkerAttrs_291.sizemin, + sizemode: __scatterMarkerAttrs_291.sizemode, + showscale: __scatterMarkerAttrs_291.showscale, + colorbar: __scatterMarkerAttrs_291.colorbar, + line: __extendFlat_291({ width: scatterMarkerLineAttrs.width }, _$makeColorScaleAttributes_51('marker.line') ), - gradient: __scatterMarkerAttrs_290.gradient + gradient: __scatterMarkerAttrs_291.gradient }, _$makeColorScaleAttributes_51('marker') ), @@ -87993,12 +88666,12 @@ var _$attributes_290 = __overrideAll_290({ }, - fillcolor: _$attributes_265.fillcolor, + fillcolor: _$attributes_266.fillcolor, - selected: _$attributes_265.selected, - unselected: _$attributes_265.unselected, + selected: _$attributes_266.selected, + unselected: _$attributes_266.unselected, - hoverinfo: __extendFlat_290({}, _$attributes_202.hoverinfo, { + hoverinfo: __extendFlat_291({}, _$attributes_203.hoverinfo, { flags: ['lon', 'lat', 'location', 'text', 'name'] }) }, 'calc', 'nested'); @@ -88013,34 +88686,34 @@ var _$attributes_290 = __overrideAll_290({ 'use strict'; -/* removed: var _$attributes_290 = require('../scattergeo/attributes'); */; -/* removed: var _$attributes_265 = require('../scatter/attributes'); */; +/* removed: var _$attributes_291 = require('../scattergeo/attributes'); */; +/* removed: var _$attributes_266 = require('../scatter/attributes'); */; /* removed: var _$layout_attributes_241 = require('../../plots/mapbox/layout_attributes'); */; -/* removed: var _$attributes_202 = require('../../plots/attributes'); */; +/* removed: var _$attributes_203 = require('../../plots/attributes'); */; /* removed: var _$attributes_44 = require('../../components/colorbar/attributes'); */; -var __extendFlat_292 = _$extend_156.extendFlat; -var __overrideAll_292 = _$edit_types_190.overrideAll; +var __extendFlat_293 = _$extend_157.extendFlat; +var __overrideAll_293 = _$edit_types_191.overrideAll; -var lineAttrs = _$attributes_290.line; -var markerAttrs = _$attributes_290.marker; +var lineAttrs = _$attributes_291.line; +var markerAttrs = _$attributes_291.marker; -var _$attributes_292 = __overrideAll_292({ - lon: _$attributes_290.lon, - lat: _$attributes_290.lat, +var _$attributes_293 = __overrideAll_293({ + lon: _$attributes_291.lon, + lat: _$attributes_291.lat, // locations // locationmode - mode: __extendFlat_292({}, _$attributes_265.mode, { + mode: __extendFlat_293({}, _$attributes_266.mode, { dflt: 'markers', }), - text: __extendFlat_292({}, _$attributes_265.text, { + text: __extendFlat_293({}, _$attributes_266.text, { }), - hovertext: __extendFlat_292({}, _$attributes_265.hovertext, { + hovertext: __extendFlat_293({}, _$attributes_266.hovertext, { }), @@ -88052,7 +88725,7 @@ var _$attributes_292 = __overrideAll_292({ // dash: dash }, - connectgaps: _$attributes_265.connectgaps, + connectgaps: _$attributes_266.connectgaps, marker: { symbol: { @@ -88080,20 +88753,20 @@ var _$attributes_292 = __overrideAll_292({ // line }, - fill: _$attributes_290.fill, - fillcolor: _$attributes_265.fillcolor, + fill: _$attributes_291.fill, + fillcolor: _$attributes_266.fillcolor, textfont: _$layout_attributes_241.layers.symbol.textfont, textposition: _$layout_attributes_241.layers.symbol.textposition, selected: { - marker: _$attributes_265.selected.marker + marker: _$attributes_266.selected.marker }, unselected: { - marker: _$attributes_265.unselected.marker + marker: _$attributes_266.unselected.marker }, - hoverinfo: __extendFlat_292({}, _$attributes_202.hoverinfo, { + hoverinfo: __extendFlat_293({}, _$attributes_203.hoverinfo, { flags: ['lon', 'lat', 'text', 'name'] }) }, 'calc', 'nested'); @@ -88108,18 +88781,18 @@ var _$attributes_292 = __overrideAll_292({ 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; +/* removed: var _$lib_164 = require('../../lib'); */; -/* removed: var _$subtypes_287 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_283 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_278 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_288 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_274 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_292 = require('./attributes'); */; +/* removed: var _$subtypes_288 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_284 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_279 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_289 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_275 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$attributes_293 = require('./attributes'); */; -var _$supplyDefaults_294 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_295 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_163.coerce(traceIn, traceOut, _$attributes_292, attr, dflt); + return _$lib_164.coerce(traceIn, traceOut, _$attributes_293, attr, dflt); } var len = handleLonLatDefaults(traceIn, traceOut, coerce); @@ -88132,13 +88805,13 @@ var _$supplyDefaults_294 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_287.hasLines(traceOut)) { - _$lineDefaults_278(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); + if(_$subtypes_288.hasLines(traceOut)) { + _$lineDefaults_279(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); coerce('connectgaps'); } - if(_$subtypes_287.hasMarkers(traceOut)) { - _$markerDefaults_283(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); + if(_$subtypes_288.hasMarkers(traceOut)) { + _$markerDefaults_284(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); // array marker.size and marker.color are only supported with circles @@ -88147,21 +88820,21 @@ var _$supplyDefaults_294 = function supplyDefaults(traceIn, traceOut, defaultCol marker.line = {width: 0}; if(marker.symbol !== 'circle') { - if(_$lib_163.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0]; - if(_$lib_163.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0]; + if(_$lib_164.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0]; + if(_$lib_164.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0]; } } - if(_$subtypes_287.hasText(traceOut)) { - _$text_defaults_288(traceIn, traceOut, layout, coerce, {noSelect: true}); + if(_$subtypes_288.hasText(traceOut)) { + _$text_defaults_289(traceIn, traceOut, layout, coerce, {noSelect: true}); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_274(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_275(traceIn, traceOut, defaultColor, coerce); } - _$lib_163.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_164.coerceSelectionMarkerOpacity(traceOut, coerce); }; function handleLonLatDefaults(traceIn, traceOut, coerce) { @@ -88185,7 +88858,7 @@ function handleLonLatDefaults(traceIn, traceOut, coerce) { 'use strict'; -var _$eventData_295 = function eventData(out, pt) { +var _$eventData_296 = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; @@ -88204,12 +88877,12 @@ var _$eventData_295 = function eventData(out, pt) { 'use strict'; /* removed: var _$fx_85 = require('../../components/fx'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$getTraceColor_275 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_273 = require('../scatter/fill_hover_text'); */; -var __BADNUM_296 = _$numerical_145.BADNUM; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$getTraceColor_276 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_274 = require('../scatter/fill_hover_text'); */; +var __BADNUM_297 = _$numerical_145.BADNUM; -var _$hoverPoints_296 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_297 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -88227,9 +88900,9 @@ var _$hoverPoints_296 = function hoverPoints(pointData, xval, yval) { function distFn(d) { var lonlat = d.lonlat; - if(lonlat[0] === __BADNUM_296) return Infinity; + if(lonlat[0] === __BADNUM_297) return Infinity; - var lon = _$lib_163.wrap180(lonlat[0]); + var lon = _$lib_164.wrap180(lonlat[0]); var lat = lonlat[1]; var pt = subplot.project([lon, lat]); var dx = pt.x - xa.c2p([xval2, lat]); @@ -88246,7 +88919,7 @@ var _$hoverPoints_296 = function hoverPoints(pointData, xval, yval) { var di = cd[pointData.index]; var lonlat = di.lonlat; - var lonlatShifted = [_$lib_163.wrap180(lonlat[0]) + lonShift, lonlat[1]]; + var lonlatShifted = [_$lib_164.wrap180(lonlat[0]) + lonShift, lonlat[1]]; // shift labels back to original winded globe var xc = xa.c2p(lonlatShifted); @@ -88258,7 +88931,7 @@ var _$hoverPoints_296 = function hoverPoints(pointData, xval, yval) { pointData.y0 = yc - rad; pointData.y1 = yc + rad; - pointData.color = _$getTraceColor_275(trace, di); + pointData.color = _$getTraceColor_276(trace, di); pointData.extraText = getExtraText(trace, di, cd[0].t.labels); return [pointData]; @@ -88288,13 +88961,13 @@ function getExtraText(trace, di, labels) { } if(isAll || parts.indexOf('text') !== -1) { - _$fillHoverText_273(di, trace, text); + _$fillHoverText_274(di, trace, text); } return text.join('
'); } -var _$geojson_utils_159 = {}; +var _$geojson_utils_160 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -88306,7 +88979,7 @@ var _$geojson_utils_159 = {}; 'use strict'; -var __BADNUM_159 = _$numerical_145.BADNUM; +var __BADNUM_160 = _$numerical_145.BADNUM; /** * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays @@ -88319,7 +88992,7 @@ var __BADNUM_159 = _$numerical_145.BADNUM; * return line coords array (or array of arrays) * */ -_$geojson_utils_159.calcTraceToLineCoords = function(calcTrace) { +_$geojson_utils_160.calcTraceToLineCoords = function(calcTrace) { var trace = calcTrace[0].trace; var connectgaps = trace.connectgaps; @@ -88330,7 +89003,7 @@ _$geojson_utils_159.calcTraceToLineCoords = function(calcTrace) { var calcPt = calcTrace[i]; var lonlat = calcPt.lonlat; - if(lonlat[0] !== __BADNUM_159) { + if(lonlat[0] !== __BADNUM_160) { lineString.push(lonlat); } else if(!connectgaps && lineString.length > 0) { coords.push(lineString); @@ -88355,7 +89028,7 @@ _$geojson_utils_159.calcTraceToLineCoords = function(calcTrace) { * GeoJSON object * */ -_$geojson_utils_159.makeLine = function(coords) { +_$geojson_utils_160.makeLine = function(coords) { if(coords.length === 1) { return { type: 'LineString', @@ -88377,7 +89050,7 @@ _$geojson_utils_159.makeLine = function(coords) { * @return {object} out * GeoJSON object */ -_$geojson_utils_159.makePolygon = function(coords) { +_$geojson_utils_160.makePolygon = function(coords) { if(coords.length === 1) { return { type: 'Polygon', @@ -88404,7 +89077,7 @@ _$geojson_utils_159.makePolygon = function(coords) { * Blank GeoJSON object * */ -_$geojson_utils_159.makeBlank = function() { +_$geojson_utils_160.makeBlank = function() { return { type: 'Point', coordinates: [] @@ -88423,24 +89096,24 @@ _$geojson_utils_159.makeBlank = function() { /* removed: var _$fastIsnumeric_9 = require('fast-isnumeric'); */; -/* removed: var _$lib_163 = require('../../lib'); */; -var __BADNUM_293 = _$numerical_145.BADNUM; -/* removed: var _$geojson_utils_159 = require('../../lib/geojson_utils'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +var __BADNUM_294 = _$numerical_145.BADNUM; +/* removed: var _$geojson_utils_160 = require('../../lib/geojson_utils'); */; /* removed: var _$colorscale_58 = require('../../components/colorscale'); */; /* removed: var _$drawing_68 = require('../../components/drawing'); */; -/* removed: var _$makeBubbleSizeFn_282 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$subtypes_287 = require('../scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_283 = require('../scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_288 = require('../scatter/subtypes'); */; /* removed: var _$convertTextOpts_238 = require('../../plots/mapbox/convert_text_opts'); */; -var _$convert_293 = function convert(calcTrace) { +var _$convert_294 = function convert(calcTrace) { var trace = calcTrace[0].trace; var isVisible = (trace.visible === true); var hasFill = (trace.fill !== 'none'); - var hasLines = _$subtypes_287.hasLines(trace); - var hasMarkers = _$subtypes_287.hasMarkers(trace); - var hasText = _$subtypes_287.hasText(trace); + var hasLines = _$subtypes_288.hasLines(trace); + var hasMarkers = _$subtypes_288.hasMarkers(trace); + var hasText = _$subtypes_288.hasText(trace); var hasCircles = (hasMarkers && trace.marker.symbol === 'circle'); var hasSymbols = (hasMarkers && trace.marker.symbol !== 'circle'); @@ -88462,23 +89135,23 @@ var _$convert_293 = function convert(calcTrace) { // fill layer and line layer use the same coords var lineCoords; if(hasFill || hasLines) { - lineCoords = _$geojson_utils_159.calcTraceToLineCoords(calcTrace); + lineCoords = _$geojson_utils_160.calcTraceToLineCoords(calcTrace); } if(hasFill) { - fill.geojson = _$geojson_utils_159.makePolygon(lineCoords); + fill.geojson = _$geojson_utils_160.makePolygon(lineCoords); fill.layout.visibility = 'visible'; - _$lib_163.extendFlat(fill.paint, { + _$lib_164.extendFlat(fill.paint, { 'fill-color': trace.fillcolor }); } if(hasLines) { - line.geojson = _$geojson_utils_159.makeLine(lineCoords); + line.geojson = _$geojson_utils_160.makeLine(lineCoords); line.layout.visibility = 'visible'; - _$lib_163.extendFlat(line.paint, { + _$lib_164.extendFlat(line.paint, { 'line-width': trace.line.width, 'line-color': trace.line.color, 'line-opacity': trace.opacity @@ -88492,7 +89165,7 @@ var _$convert_293 = function convert(calcTrace) { circle.geojson = circleOpts.geojson; circle.layout.visibility = 'visible'; - _$lib_163.extendFlat(circle.paint, { + _$lib_164.extendFlat(circle.paint, { 'circle-color': circleOpts.mcc, 'circle-radius': circleOpts.mrc, 'circle-opacity': circleOpts.mo @@ -88502,18 +89175,18 @@ var _$convert_293 = function convert(calcTrace) { if(hasSymbols || hasText) { symbol.geojson = makeSymbolGeoJSON(calcTrace); - _$lib_163.extendFlat(symbol.layout, { + _$lib_164.extendFlat(symbol.layout, { visibility: 'visible', 'icon-image': '{symbol}-15', 'text-field': '{text}' }); if(hasSymbols) { - _$lib_163.extendFlat(symbol.layout, { + _$lib_164.extendFlat(symbol.layout, { 'icon-size': trace.marker.size / 10 }); - _$lib_163.extendFlat(symbol.paint, { + _$lib_164.extendFlat(symbol.paint, { 'icon-opacity': trace.opacity * trace.marker.opacity, // TODO does not work ?? @@ -88527,7 +89200,7 @@ var _$convert_293 = function convert(calcTrace) { // all data-driven below !! - _$lib_163.extendFlat(symbol.layout, { + _$lib_164.extendFlat(symbol.layout, { 'text-size': trace.textfont.size, 'text-anchor': textOpts.anchor, 'text-offset': textOpts.offset @@ -88536,7 +89209,7 @@ var _$convert_293 = function convert(calcTrace) { // 'text-font': symbol.textfont.family.split(', '), }); - _$lib_163.extendFlat(symbol.paint, { + _$lib_164.extendFlat(symbol.paint, { 'text-color': trace.textfont.color, 'text-opacity': trace.opacity }); @@ -88548,7 +89221,7 @@ var _$convert_293 = function convert(calcTrace) { function initContainer() { return { - geojson: _$geojson_utils_159.makeBlank(), + geojson: _$geojson_utils_160.makeBlank(), layout: { visibility: 'none' }, paint: {} }; @@ -88558,9 +89231,9 @@ function makeCircleOpts(calcTrace) { var trace = calcTrace[0].trace; var marker = trace.marker; var selectedpoints = trace.selectedpoints; - var arrayColor = _$lib_163.isArrayOrTypedArray(marker.color); - var arraySize = _$lib_163.isArrayOrTypedArray(marker.size); - var arrayOpacity = _$lib_163.isArrayOrTypedArray(marker.opacity); + var arrayColor = _$lib_164.isArrayOrTypedArray(marker.color); + var arraySize = _$lib_164.isArrayOrTypedArray(marker.size); + var arrayOpacity = _$lib_164.isArrayOrTypedArray(marker.opacity); var i; function addTraceOpacity(o) { return trace.opacity * o; } @@ -88574,19 +89247,19 @@ function makeCircleOpts(calcTrace) { _$colorscale_58.extractScale(marker.colorscale, marker.cmin, marker.cmax) ); } else { - colorFn = _$lib_163.identity; + colorFn = _$lib_164.identity; } } var sizeFn; if(arraySize) { - sizeFn = _$makeBubbleSizeFn_282(trace); + sizeFn = _$makeBubbleSizeFn_283(trace); } var opacityFn; if(arrayOpacity) { opacityFn = function(mo) { - var mo2 = _$fastIsnumeric_9(mo) ? +_$lib_163.constrain(mo, 0, 1) : 0; + var mo2 = _$fastIsnumeric_9(mo) ? +_$lib_164.constrain(mo, 0, 1) : 0; return addTraceOpacity(mo2); }; } @@ -88661,7 +89334,7 @@ function makeSymbolGeoJSON(calcTrace) { getFillFunc(symbol) : blankFillFunc; - var fillText = _$subtypes_287.hasText(trace) ? + var fillText = _$subtypes_288.hasText(trace) ? getFillFunc(text) : blankFillFunc; @@ -88692,7 +89365,7 @@ function makeSymbolGeoJSON(calcTrace) { } function getFillFunc(attr) { - if(_$lib_163.isArrayOrTypedArray(attr)) { + if(_$lib_164.isArrayOrTypedArray(attr)) { return function(v) { return v; }; } else if(attr) { @@ -88707,7 +89380,7 @@ function blankFillFunc() { return ''; } // only need to check lon (OR lat) function isBADNUM(lonlat) { - return lonlat[0] === __BADNUM_293; + return lonlat[0] === __BADNUM_294; } /** @@ -88720,7 +89393,7 @@ function isBADNUM(lonlat) { 'use strict'; -/* removed: var _$convert_293 = require('./convert'); */; +/* removed: var _$convert_294 = require('./convert'); */; function ScatterMapbox(subplot, uid) { this.subplot = subplot; @@ -88747,22 +89420,22 @@ function ScatterMapbox(subplot, uid) { // for up-to 4 sources per 'scattermapbox' traces becomes a problem. } -var __proto_298 = ScatterMapbox.prototype; +var __proto_299 = ScatterMapbox.prototype; -__proto_298.addSource = function(k, opts) { +__proto_299.addSource = function(k, opts) { this.subplot.map.addSource(this.sourceIds[k], { type: 'geojson', data: opts.geojson }); }; -__proto_298.setSourceData = function(k, opts) { +__proto_299.setSourceData = function(k, opts) { this.subplot.map .getSource(this.sourceIds[k]) .setData(opts.geojson); }; -__proto_298.addLayer = function(k, opts) { +__proto_299.addLayer = function(k, opts) { this.subplot.map.addLayer({ type: k, id: this.layerIds[k], @@ -88772,9 +89445,9 @@ __proto_298.addLayer = function(k, opts) { }); }; -__proto_298.update = function update(calcTrace) { +__proto_299.update = function update(calcTrace) { var subplot = this.subplot; - var optsAll = _$convert_293(calcTrace); + var optsAll = _$convert_294(calcTrace); for(var i = 0; i < this.order.length; i++) { var k = this.order[i]; @@ -88792,7 +89465,7 @@ __proto_298.update = function update(calcTrace) { calcTrace[0].trace._glTrace = this; }; -__proto_298.dispose = function dispose() { +__proto_299.dispose = function dispose() { var map = this.subplot.map; for(var i = 0; i < this.order.length; i++) { @@ -88802,10 +89475,10 @@ __proto_298.dispose = function dispose() { } }; -var _$createScatterMapbox_298 = function createScatterMapbox(subplot, calcTrace) { +var _$createScatterMapbox_299 = function createScatterMapbox(subplot, calcTrace) { var trace = calcTrace[0].trace; var scatterMapbox = new ScatterMapbox(subplot, trace.uid); - var optsAll = _$convert_293(calcTrace); + var optsAll = _$convert_294(calcTrace); for(var i = 0; i < scatterMapbox.order.length; i++) { var k = scatterMapbox.order[i]; @@ -88831,10 +89504,11 @@ var _$createScatterMapbox_298 = function createScatterMapbox(subplot, calcTrace) 'use strict'; -/* removed: var _$lib_163 = require('../../lib'); */; -/* removed: var _$subtypes_287 = require('../scatter/subtypes'); */; +/* removed: var _$lib_164 = require('../../lib'); */; +/* removed: var _$subtypes_288 = require('../scatter/subtypes'); */; +var __BADNUM_300 = _$numerical_145.BADNUM; -var _$selectPoints_299 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_300 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -88842,7 +89516,7 @@ var _$selectPoints_299 = function selectPoints(searchInfo, polygon) { var trace = cd[0].trace; var i; - if(!_$subtypes_287.hasMarkers(trace)) return []; + if(!_$subtypes_288.hasMarkers(trace)) return []; if(polygon === false) { for(i = 0; i < cd.length; i++) { @@ -88852,18 +89526,21 @@ var _$selectPoints_299 = function selectPoints(searchInfo, polygon) { for(i = 0; i < cd.length; i++) { var di = cd[i]; var lonlat = di.lonlat; - var lonlat2 = [_$lib_163.wrap180(lonlat[0]), lonlat[1]]; - var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)]; - if(polygon.contains(xy)) { - selection.push({ - pointNumber: i, - lon: lonlat[0], - lat: lonlat[1] - }); - di.selected = 1; - } else { - di.selected = 0; + if(lonlat[0] !== __BADNUM_300) { + var lonlat2 = [_$lib_164.wrap180(lonlat[0]), lonlat[1]]; + var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)]; + + if(polygon.contains(xy)) { + selection.push({ + pointNumber: i, + lon: lonlat[0], + lat: lonlat[1] + }); + di.selected = 1; + } else { + di.selected = 0; + } } } } @@ -88882,34 +89559,34 @@ var _$selectPoints_299 = function selectPoints(searchInfo, polygon) { 'use strict'; -var __ScatterMapbox_297 = {}; +var __ScatterMapbox_298 = {}; -__ScatterMapbox_297.attributes = _$attributes_292; -__ScatterMapbox_297.supplyDefaults = _$supplyDefaults_294; -__ScatterMapbox_297.colorbar = _$colorbar_269; -__ScatterMapbox_297.calc = _$calc_291; -__ScatterMapbox_297.plot = _$createScatterMapbox_298; -__ScatterMapbox_297.hoverPoints = _$hoverPoints_296; -__ScatterMapbox_297.eventData = _$eventData_295; -__ScatterMapbox_297.selectPoints = _$selectPoints_299; +__ScatterMapbox_298.attributes = _$attributes_293; +__ScatterMapbox_298.supplyDefaults = _$supplyDefaults_295; +__ScatterMapbox_298.colorbar = _$colorbar_270; +__ScatterMapbox_298.calc = _$calc_292; +__ScatterMapbox_298.plot = _$createScatterMapbox_299; +__ScatterMapbox_298.hoverPoints = _$hoverPoints_297; +__ScatterMapbox_298.eventData = _$eventData_296; +__ScatterMapbox_298.selectPoints = _$selectPoints_300; -__ScatterMapbox_297.style = function(_, cd) { +__ScatterMapbox_298.style = function(_, cd) { if(cd) { var trace = cd[0].trace; trace._glTrace.update(cd); } }; -__ScatterMapbox_297.moduleType = 'trace'; -__ScatterMapbox_297.name = 'scattermapbox'; -__ScatterMapbox_297.basePlotModule = _$mapbox_239; -__ScatterMapbox_297.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike']; -__ScatterMapbox_297.meta = { +__ScatterMapbox_298.moduleType = 'trace'; +__ScatterMapbox_298.name = 'scattermapbox'; +__ScatterMapbox_298.basePlotModule = _$mapbox_239; +__ScatterMapbox_298.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike']; +__ScatterMapbox_298.meta = { }; -var _$ScatterMapbox_297 = __ScatterMapbox_297; +var _$ScatterMapbox_298 = __ScatterMapbox_298; /** * Copyright 2012-2018, Plotly, Inc. @@ -88921,7 +89598,7 @@ var _$ScatterMapbox_297 = __ScatterMapbox_297; 'use strict'; -var _$scattermapbox_5 = _$ScatterMapbox_297; +var _$scattermapbox_5 = _$ScatterMapbox_298; /** * Copyright 2012-2018, Plotly, Inc. diff --git a/dist/plotly-mapbox.min.js b/dist/plotly-mapbox.min.js index 349bba44622..1af2fde9df0 100644 --- a/dist/plotly-mapbox.min.js +++ b/dist/plotly-mapbox.min.js @@ -1,7 +1,7 @@ /** -* plotly.js (mapbox - minified) v1.35.2 +* plotly.js (mapbox - minified) v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){var t={exports:{}};!function(){var e={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},i=this.document;function a(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(i)try{n(i.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),i)try{i.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var s=this.Element.prototype,l=s.setAttribute,u=s.setAttributeNS,c=this.CSSStyleDeclaration.prototype,p=c.setProperty;s.setAttribute=function(t,e){l.call(this,t,e+"")},s.setAttributeNS=function(t,e,r){u.call(this,t,e,r+"")},c.setProperty=function(t,e,r){p.call(this,t,e+"",r)}}function h(t,e){return te?1:t>=e?0:NaN}function f(t){return null===t?NaN:+t}function d(t){return!isNaN(t)}function y(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}e.ascending=h,e.descending=function(t,e){return et?1:e>=t?0:NaN},e.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},e.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},e.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),i=n){r=i=n;break}for(;++an&&(r=n),i1)return o/(l-1)},e.deviation=function(){var t=e.variance.apply(this,arguments);return t?Math.sqrt(t):t};var m=y(h);function g(t){return t.length}e.bisectLeft=m.left,e.bisect=e.bisectRight=m.right,e.bisector=function(t){return y(1===t.length?function(e,r){return h(t(e),r)}:t)},e.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},e.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},e.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var v=Math.abs;function _(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function x(){this._=Object.create(null)}e.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(v(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=i.length)return r?r.call(n,a):t?a.sort(t):a;for(var l,u,c,p,h=-1,f=a.length,d=i[s++],y=new x;++h=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(e.map,t,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(e){return t=e,n},n.rollup=function(t){return r=t,n},n},e.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},e.event=null,e.requote=function(t){return t.replace(V,"\\$&")};var V=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function U(t){return q(t,W),t}var Z=function(t,e){return e.querySelector(t)},H=function(t,e){return e.querySelectorAll(t)},G=function(t,e){var r=t.matches||t[I(t,"matchesSelector")];return(G=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(Z=function(t,e){return Sizzle(t,e)[0]||null},H=Sizzle,G=Sizzle.matchesSelector),e.selection=function(){return e.select(i.documentElement)};var W=e.selection.prototype=[];function X(t){return"function"==typeof t?t:function(){return Z(t,this)}}function Y(t){return"function"==typeof t?t:function(){return H(t,this)}}W.select=function(t){var e,r,n,i,a=[];t=X(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},W.attr=function(t,r){if(arguments.length<2){if("string"==typeof t){var n=this.node();return(t=e.ns.qualify(t)).local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(r in t)this.each($(r,t[r]));return this}return this.each($(t,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=h);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(t=t.slice(0,o));var l=dt.get(t);function u(){var e=this[a];e&&(this.removeEventListener(t,e,e.$),delete this[a])}return l&&(t=l,s=mt),o?r?function(){var e=s(r,n(arguments));u.call(this),this.addEventListener(t,this[a]=e,e.$=i),e._=r}:u:r?O:function(){var r,n=new RegExp("^__on([^.]+)"+e.requote(t)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}e.selection.enter=pt,e.selection.enter.prototype=ht,ht.append=W.append,ht.empty=W.empty,ht.node=W.node,ht.call=W.call,ht.size=W.size,ht.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s=n&&(n=e+1);!(o=s[n])&&++n0?1:t<0?-1:0}function Pt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function It(t){return t>1?0:t<-1?Tt:Math.acos(t)}function Dt(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function Ot(t){return((t=Math.exp(t))+1/t)/2}function Rt(t){return(t=Math.sin(t/2))*t}var Bt=Math.SQRT2;e.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,p=l-a,h=c*c+p*p;if(h0&&(t=t.transition().duration(y)),t.call(w.event)}function S(){u&&u.domain(l.range().map(function(t){return(t-h.x)/h.k}).map(l.invert)),p&&p.domain(c.range().map(function(t){return(t-h.y)/h.k}).map(c.invert))}function C(t){m++||t({type:"zoomstart"})}function z(t){S(),t({type:"zoom",scale:h.k,translate:[h.x,h.y]})}function L(t){--m||(t({type:"zoomend"}),r=null)}function E(){var t=this,r=b.of(t,arguments),n=0,i=e.select(o(t)).on(v,function(){n=1,T(e.mouse(t),a),z(r)}).on(_,function(){i.on(v,null).on(_,null),s(n),L(r)}),a=k(e.mouse(t)),s=_t(t);ss.call(t),C(r)}function P(){var t,r=this,n=b.of(r,arguments),i={},a=0,o=".zoom-"+e.event.changedTouches[0].identifier,l="touchmove"+o,u="touchend"+o,c=[],p=e.select(r),f=_t(r);function d(){var n=e.touches(r);return t=h.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=k(t))}),n}function y(){var t=e.event.target;e.select(t).on(l,m).on(u,v),c.push(t);for(var n=e.event.changedTouches,o=0,p=n.length;o1){g=f[0];var _=f[1],x=g[0]-_[0],b=g[1]-_[1];a=x*x+b*b}}function m(){var o,l,u,c,p=e.touches(r);ss.call(r);for(var h=0,f=p.length;h360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Ht(t,r,n){return this instanceof Ht?(this.h=+t,this.c=+r,void(this.l=+n)):arguments.length<2?t instanceof Ht?new Ht(t.h,t.c,t.l):ee(t instanceof Xt?t.l:(t=he((t=e.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new Ht(t,r,n)}Ut.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,this.l/t)},Ut.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,t*this.l)},Ut.rgb=function(){return Zt(this.h,this.s,this.l)},e.hcl=Ht;var Gt=Ht.prototype=new Vt;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Xt(r,Math.cos(t*=zt)*e,Math.sin(t)*e)}function Xt(t,e,r){return this instanceof Xt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Xt?new Xt(t.l,t.a,t.b):t instanceof Ht?Wt(t.h,t.c,t.l):he((t=ae(t)).r,t.g,t.b):new Xt(t,e,r)}Gt.brighter=function(t){return new Ht(this.h,this.c,Math.min(100,this.l+Yt*(arguments.length?t:1)))},Gt.darker=function(t){return new Ht(this.h,this.c,Math.max(0,this.l-Yt*(arguments.length?t:1)))},Gt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},e.lab=Xt;var Yt=18,Jt=.95047,Kt=1,$t=1.08883,Qt=Xt.prototype=new Vt;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*Jt)-1.5371385*(n=re(n)*Kt)-.4985314*(a=re(a)*$t)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Ht(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Ht(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ce(""+t,ae,Zt):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}Qt.brighter=function(t){return new Xt(Math.min(100,this.l+Yt*(arguments.length?t:1)),this.a,this.b)},Qt.darker=function(t){return new Xt(Math.max(0,this.l-Yt*(arguments.length?t:1)),this.a,this.b)},Qt.rgb=function(){return te(this.l,this.a,this.b)},e.rgb=ae;var le=ae.prototype=new Vt;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(de(i[0]),de(i[1]),de(i[2]))}return(a=ye.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function pe(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e0&&l<1?0:n),new qt(n,i,l)}function he(t,e,r){var n=ne((.4124564*(t=fe(t))+.3575761*(e=fe(e))+.1804375*(r=fe(r)))/Jt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Xt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function fe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function de(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(o,u)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(t)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=p:u.onreadystatechange=function(){u.readyState>3&&p()},u.onprogress=function(t){var r=e.event;e.event=t;try{s.progress.call(o,u)}finally{e.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(e,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),u.open(e,t,!0),null==r||"accept"in l||(l.accept=r+",*/*"),u.setRequestHeader)for(var a in l)u.setRequestHeader(a,l[a]);return null!=r&&u.overrideMimeType&&u.overrideMimeType(r),null!=c&&(u.responseType=c),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,u),u.send(null==n?null:n),o},o.abort=function(){return u.abort(),o},e.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}ye.forEach(function(t,e){ye.set(t,oe(e))}),e.functor=me,e.xhr=ge(E),e.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ve(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,u=0,c=0;function p(){if(u>=l)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),be=0):(be=1,ke(Te))}function Me(){for(var t=Date.now(),e=_e;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Se(){for(var t,e=_e,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});e.formatPrefix=function(t,r){var n=0;return(t=+t)&&(t<0&&(t*=-1),r&&(t=e.round(t,Ce(t,r))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),ze[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Ee=e.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,r){return(t=e.round(t,Ce(t,r))).toFixed(Math.max(0,Math.min(20,Ce(t*(1+1e-15),r))))}});function Pe(t){return t+""}var Ie=e.time={},De=Date;function Oe(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Oe.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(){Re.setUTCDate.apply(this._,arguments)},setDay:function(){Re.setUTCDay.apply(this._,arguments)},setFullYear:function(){Re.setUTCFullYear.apply(this._,arguments)},setHours:function(){Re.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Re.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Re.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Re.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Re.setUTCSeconds.apply(this._,arguments)},setTime:function(){Re.setTime.apply(this._,arguments)}};var Re=Date.prototype;function Be(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r1)for(;o68?1900:2e3),r+i[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=v(e)/60|0,i=v(e)%60;return r+qe(n,"0",2)+qe(i,"0",2)}function ar(t,e,r){Ve.lastIndex=0;var n=Ve.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:E;return function(t){var n=Le.exec(t),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",u=n[4]||"",c=n[5],p=+n[6],h=n[7],f=n[8],d=n[9],y=1,m="",g="",v=!1,_=!0;switch(f&&(f=+f.substring(1)),(c||"0"===i&&"="===s)&&(c=i="0",s="="),d){case"n":h=!0,d="g";break;case"%":y=100,g="%",d="f";break;case"p":y=100,g="%",d="r";break;case"b":case"o":case"x":case"X":"#"===u&&(m="0"+d.toLowerCase());case"c":_=!1;case"d":v=!0,f=0;break;case"s":y=-1,d="r"}"$"===u&&(m=a[0],g=a[1]),"r"!=d||f||(d="g"),null!=f&&("g"==d?f=Math.max(1,Math.min(21,f)):"e"!=d&&"f"!=d||(f=Math.max(0,Math.min(20,f)))),d=Ee.get(d)||Pe;var x=c&&h;return function(t){var n=g;if(v&&t%1)return"";var a=t<0||0===t&&1/t<0?(t=-t,"-"):"-"===l?"":l;if(y<0){var u=e.formatPrefix(t,f);t=u.scale(t),n=u.symbol+g}else t*=y;var b,w,k=(t=d(t,f)).lastIndexOf(".");if(k<0){var A=_?t.lastIndexOf("e"):-1;A<0?(b=t,w=""):(b=t.substring(0,A),w=t.substring(A))}else b=t.substring(0,k),w=r+t.substring(k+1);!c&&h&&(b=o(b,1/0));var T=m.length+b.length+w.length+(x?0:a.length),M=T"===s?M+a+t:"^"===s?M.substring(0,T>>=1)+a+t+M.substring(T):a+(x?t:M+t))+n}}}(t),timeFormat:function(t){var r=t.dateTime,n=t.date,i=t.time,a=t.periods,o=t.days,s=t.shortDays,l=t.months,u=t.shortMonths;function c(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s=u)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in Ne?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(De=Oe);return r._=t,e(r)}finally{De=Date}}return r.parse=function(t){try{De=Oe;var r=e.parse(t);return r&&r._}finally{De=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var h=e.map(),f=Ue(o),d=Ze(o),y=Ue(s),m=Ze(s),g=Ue(l),v=Ze(l),_=Ue(u),x=Ze(u);a.forEach(function(t,e){h.set(t.toLowerCase(),e)});var b={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:c(r),d:function(t,e){return qe(t.getDate(),e,2)},e:function(t,e){return qe(t.getDate(),e,2)},H:function(t,e){return qe(t.getHours(),e,2)},I:function(t,e){return qe(t.getHours()%12||12,e,2)},j:function(t,e){return qe(1+Ie.dayOfYear(t),e,3)},L:function(t,e){return qe(t.getMilliseconds(),e,3)},m:function(t,e){return qe(t.getMonth()+1,e,2)},M:function(t,e){return qe(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return qe(t.getSeconds(),e,2)},U:function(t,e){return qe(Ie.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return qe(Ie.mondayOfYear(t),e,2)},x:c(n),X:c(i),y:function(t,e){return qe(t.getFullYear()%100,e,2)},Y:function(t,e){return qe(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){y.lastIndex=0;var n=y.exec(e.slice(r));return n?(t.w=m.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){f.lastIndex=0;var n=f.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){_.lastIndex=0;var n=_.exec(e.slice(r));return n?(t.m=x.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.m=v.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return p(t,b.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Qe,L:nr,m:Ke,M:er,p:function(t,e,r){var n=h.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Ge,w:He,W:We,x:function(t,e,r){return p(t,b.x.toString(),e,r)},X:function(t,e,r){return p(t,b.X.toString(),e,r)},y:Ye,Y:Xe,Z:Je,"%":ar};return c}(t)}};var sr=e.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"]});function lr(){}e.format=sr.numberFormat,e.geo={},lr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new lr;function cr(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function pr(t,e){t&&fr.hasOwnProperty(t.type)&&fr[t.type](t,e)}e.geo.stream=function(t,e){t&&hr.hasOwnProperty(t.type)?hr[t.type](t,e):pr(t,e)};var hr={Feature:function(t,e){pr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=o*a,l=Math.cos(e),u=Math.sin(e),c=i*u,p=n*l+c*Math.cos(s),h=c*o*Math.sin(s);Cr.add(Math.atan2(h,p)),r=t,n=l,i=u}zr.point=function(o,s){zr.point=a,r=(t=o)*zt,n=Math.cos(s=(e=s)*zt/2+Tt/4),i=Math.sin(s)},zr.lineEnd=function(){a(t,e)}}function Er(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Pr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Ir(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Dr(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Or(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Rr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Br(t){return[Math.atan2(t[1],t[0]),Dt(t[2])]}function Fr(t,e){return v(t[0]-e[0])kt?i=90:u<-kt&&(r=-90),p[0]=t,p[1]=n}};function f(e,a){c.push(p=[t=e,n=e]),ai&&(i=a)}function d(e,o){var s=Er([e*zt,o*zt]);if(l){var u=Ir(l,s),c=Ir([u[1],-u[0],0],u);Rr(c),c=Br(c);var p=e-a,h=p>0?1:-1,d=c[0]*Lt*h,y=v(p)>180;if(y^(h*ai&&(i=m);else if(y^(h*a<(d=(d+360)%360-180)&&di&&(i=o);y?eb(t,n)&&(n=e):b(e,n)>b(t,n)&&(t=e):n>=t?(en&&(n=e)):e>a?b(t,e)>b(t,n)&&(n=e):b(e,n)>b(t,n)&&(t=e)}else f(e,o);l=s,a=e}function y(){h.point=d}function m(){p[0]=t,p[1]=n,h.point=f,l=null}function g(t,e){if(l){var r=t-a;u+=v(r)>180?r+(r>0?360:-360):r}else o=t,s=e;zr.point(t,e),d(t,e)}function _(){zr.lineStart()}function x(){g(o,s),zr.lineEnd(),v(u)>kt&&(t=-(n=180)),p[0]=t,p[1]=n,l=null}function b(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function k(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:tb(y[0],y[1])&&(y[1]=f[1]),b(f[0],y[1])>b(y[0],y[1])&&(y[0]=f[0])):s.push(y=f);for(var l,u,f,d=-1/0,y=(o=0,s[u=s.length-1]);o<=u;y=f,++o)f=s[o],(l=b(y[1],f[0]))>d&&(d=l,t=f[0],n=y[1])}return c=p=null,t===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[t,r],[n,i]]}}(),e.geo.centroid=function(t){gr=vr=_r=xr=br=wr=kr=Ar=Tr=Mr=Sr=0,e.geo.stream(t,Nr);var r=Tr,n=Mr,i=Sr,a=r*r+n*n+i*i;return a=0;--s)i.point((p=c[s])[0],p[1]);else n(f.x,f.p.x,-1,i);f=f.p}c=(f=f.o).z,d=!d}while(!f.v);i.lineEnd()}}}function Xr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,k=w*b,A=k>Tt,T=d*_;if(Cr.add(Math.atan2(T*w*Math.sin(k),y*x+T*Math.cos(k))),a+=A?b+w*Mt:b,A^h>=r^g>=r){var M=Ir(Er(p),Er(t));Rr(M);var S=Ir(i,M);Rr(S);var C=(A^b>=0?-1:1)*Dt(S[2]);(n>C||n===C&&(M[0]||M[1]))&&(o+=A^b>=0?1:-1)}if(!m++)break;h=g,d=_,y=x,p=t}}return(a<-kt||a0){for(_||(o.polygonStart(),_=!0),o.lineStart();++a1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return c}}function Kr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:O,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Qr(t,e){return((t=t.x)[0]<0?t[1]-Ct-kt:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-kt:Ct-e[1])}var tn=Jr(Gr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Tt:-Tt,l=v(a-r);v(l-Tt)0?Ct:-Ct),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Tt&&(v(r-i)kt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Ct,n.point(-Tt,i),n.point(0,i),n.point(Tt,i),n.point(Tt,0),n.point(Tt,-i),n.point(0,-i),n.point(-Tt,-i),n.point(-Tt,0),n.point(-Tt,i);else if(v(t[0]-e[0])>kt){var a=t[0]0)){if(a/=h,h<0){if(a0){if(a>p)return;a>c&&(c=a)}if(a=r-l,h||!(a<0)){if(a/=h,h<0){if(a>p)return;a>c&&(c=a)}else if(h>0){if(a0)){if(a/=f,f<0){if(a0){if(a>p)return;a>c&&(c=a)}if(a=n-u,f||!(a<0)){if(a/=f,f<0){if(a>p)return;a>c&&(c=a)}else if(f>0){if(a0&&(i.a={x:l+c*h,y:u+c*f}),p<1&&(i.b={x:l+p*h,y:u+p*f}),i}}}}}}var rn=1e9;function nn(t,r,n,i){return function(l){var u,c,p,h,f,d,y,m,g,v,_,x=l,b=$r(),w=en(t,r,n,i),k={point:M,lineStart:function(){k.point=S,c&&c.push(p=[]);v=!0,g=!1,y=m=NaN},lineEnd:function(){u&&(S(h,f),d&&g&&b.rejoin(),u.push(b.buffer()));k.point=M,g&&l.lineEnd()},polygonStart:function(){l=b,u=[],c=[],_=!0},polygonEnd:function(){l=x,u=e.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],i=0;in&&Pt(u,a,t)>0&&++e:a[1]<=n&&Pt(u,a,t)<0&&--e,u=a;return 0!==e}([t,i]),n=_&&r,a=u.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),A(null,null,1,l),l.lineEnd()),a&&Wr(u,o,r,A,l),l.polygonEnd()),u=c=p=null}};function A(e,o,l,u){var c=0,p=0;if(null==e||(c=a(e,l))!==(p=a(o,l))||s(e,o)<0^l>0)do{u.point(0===c||3===c?t:n,c>1?i:r)}while((c=(c+l+4)%4)!==p);else u.point(o[0],o[1])}function T(e,a){return t<=e&&e<=n&&r<=a&&a<=i}function M(t,e){T(t,e)&&l.point(t,e)}function S(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&p.push([t,e]),v)h=t,f=e,d=r,v=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&g)l.point(t,e);else{var n={a:{x:y,y:m},b:{x:t,y:e}};w(n)?(g||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),_=!1):r&&(l.lineStart(),l.point(t,e),_=!1)}y=t,m=e,g=r}return k};function a(e,i){return v(e[0]-t)0?0:3:v(e[0]-n)0?2:1:v(e[1]-r)0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=Sn(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,Dt((i-(t*t+r*r)*n*n)/(2*n))]},o}e.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(e.geo.conicEqualArea=function(){return an(on)}).raw=on,e.geo.albers=function(){return e.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},e.geo.albersUsa=function(){var t,r,n,i,a=e.geo.albers(),o=e.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=e.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,r){t=[e,r]}};function u(e){var a=e[0],o=e[1];return t=null,r(a,o),t||(n(a,o),t)||i(a,o),t}return u.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},u.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),u):a.precision()},u.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),u.translate(a.translate())):a.scale()},u.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),c=+t[0],p=+t[1];return r=a.translate(t).clipExtent([[c-.455*e,p-.238*e],[c+.455*e,p+.238*e]]).stream(l).point,n=o.translate([c-.307*e,p+.201*e]).clipExtent([[c-.425*e+kt,p+.12*e+kt],[c-.214*e-kt,p+.234*e-kt]]).stream(l).point,i=s.translate([c-.205*e,p+.212*e]).clipExtent([[c-.214*e+kt,p+.166*e+kt],[c-.115*e-kt,p+.234*e-kt]]).stream(l).point,u},u.scale(1070)};var sn,ln,un,cn,pn,hn,fn={point:O,lineStart:O,lineEnd:O,polygonStart:function(){ln=0,fn.lineStart=dn},polygonEnd:function(){fn.lineStart=fn.lineEnd=fn.point=O,sn+=v(ln/2)}};function dn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}fn.point=function(a,o){fn.point=i,t=r=a,e=n=o},fn.lineEnd=function(){i(t,e)}}var yn={point:function(t,e){tpn&&(pn=t);ehn&&(hn=e)},lineStart:O,lineEnd:O,polygonStart:O,polygonEnd:O};function mn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var gn,vn={point:_n,lineStart:xn,lineEnd:bn,polygonStart:function(){vn.lineStart=wn},polygonEnd:function(){vn.point=_n,vn.lineStart=xn,vn.lineEnd=bn}};function _n(t,e){_r+=t,xr+=e,++br}function xn(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,kr+=o*(e+n)/2,Ar+=o,_n(t=r,e=n)}vn.point=function(n,i){vn.point=r,_n(t=n,e=i)}}function bn(){vn.point=_n}function wn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,kr+=o*(n+e)/2,Ar+=o,Tr+=(o=n*t-r*e)*(r+t),Mr+=o*(n+e),Sr+=3*o,_n(r=t,n=e)}vn.point=function(a,o){vn.point=i,_n(t=r=a,e=n=o)},vn.lineEnd=function(){i(t,e)}}function kn(t){var e=.5,r=Math.cos(30*zt),n=16;function i(e){return(n?function(e){var r,i,o,s,l,u,c,p,h,f,d,y,m={point:g,lineStart:v,lineEnd:x,polygonStart:function(){e.polygonStart(),m.lineStart=b},polygonEnd:function(){e.polygonEnd(),m.lineStart=v}};function g(r,n){r=t(r,n),e.point(r[0],r[1])}function v(){p=NaN,m.point=_,e.lineStart()}function _(r,i){var o=Er([r,i]),s=t(r,i);a(p,h,c,f,d,y,p=s[0],h=s[1],c=r,f=o[0],d=o[1],y=o[2],n,e),e.point(p,h)}function x(){m.point=g,e.lineEnd()}function b(){v(),m.point=w,m.lineEnd=k}function w(t,e){_(r=t,e),i=p,o=h,s=f,l=d,u=y,m.point=_}function k(){a(p,h,c,f,d,y,i,o,r,s,l,u,n,e),m.lineEnd=x,x()}return m}:function(e){return Tn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,u,c,p,h,f,d,y,m,g){var _=c-n,x=p-i,b=_*_+x*x;if(b>4*e&&m--){var w=s+f,k=l+d,A=u+y,T=Math.sqrt(w*w+k*k+A*A),M=Math.asin(A/=T),S=v(v(A)-1)e||v((_*E+x*P)/b-.5)>.3||s*f+l*d+u*y0&&16,i):Math.sqrt(e)},i}function An(t){this.stream=t}function Tn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Mn(t){return Sn(function(){return t})()}function Sn(t){var r,n,i,a,o,s,l=kn(function(t,e){return[(t=r(t,e))[0]*u+a,o-t[1]*u]}),u=150,c=480,p=250,h=0,f=0,d=0,y=0,m=0,g=tn,_=E,x=null,b=null;function w(t){return[(t=i(t[0]*zt,t[1]*zt))[0]*u+a,o-t[1]*u]}function k(t){return(t=i.invert((t[0]-a)/u,(o-t[1])/u))&&[t[0]*Lt,t[1]*Lt]}function A(){i=Hr(n=En(d,y,m),r);var t=r(h,f);return a=c-t[0]*u,o=p+t[1]*u,T()}function T(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Cn(g(n,l(_(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(g=null==t?(x=t,tn):function(t){var e=Math.cos(t),r=e>0,n=v(e)>kt;return Jr(i,function(t){var e,s,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(p,h){var f,d=[p,h],y=i(p,h),m=r?y?0:o(p,h):y?o(p+(p<0?Tt:-Tt),h):0;if(!e&&(u=l=y)&&t.lineStart(),y!==l&&(f=a(e,d),(Fr(e,f)||Fr(d,f))&&(d[0]+=kt,d[1]+=kt,y=i(d[0],d[1]))),y!==l)c=0,y?(t.lineStart(),f=a(d,e),t.point(f[0],f[1])):(f=a(e,d),t.point(f[0],f[1]),t.lineEnd()),e=f;else if(n&&e&&r^y){var g;m&s||!(g=a(d,e,!0))||(c=0,r?(t.lineStart(),t.point(g[0][0],g[0][1]),t.point(g[1][0],g[1][1]),t.lineEnd()):(t.point(g[1][0],g[1][1]),t.lineEnd(),t.lineStart(),t.point(g[0][0],g[0][1])))}!y||e&&Fr(e,d)||t.point(d[0],d[1]),e=d,l=y,s=m},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return c|(u&&l)<<1}}},On(t,6*zt),r?[0,-t]:[-Tt,t-Tt]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Ir(Er(t),Er(r)),o=Pr(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var u=e*o/l,c=-e*s/l,p=Ir(i,a),h=Or(i,u);Dr(h,Or(a,c));var f=p,d=Pr(h,f),y=Pr(f,f),m=d*d-y*(Pr(h,h)-1);if(!(m<0)){var g=Math.sqrt(m),_=Or(f,(-d-g)/y);if(Dr(_,h),_=Br(_),!n)return _;var x,b=t[0],w=r[0],k=t[1],A=r[1];w0^_[1]<(v(_[0]-b)Tt^(b<=_[0]&&_[0]<=w)){var S=Or(f,(-d+g)/y);return Dr(S,h),[_,Br(S)]}}}function o(e,n){var i=r?t:Tt-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((x=+t)*zt),T()):x},w.clipExtent=function(t){return arguments.length?(b=t,_=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):E,T()):b},w.scale=function(t){return arguments.length?(u=+t,A()):u},w.translate=function(t){return arguments.length?(c=+t[0],p=+t[1],A()):[c,p]},w.center=function(t){return arguments.length?(h=t[0]%360*zt,f=t[1]%360*zt,A()):[h*Lt,f*Lt]},w.rotate=function(t){return arguments.length?(d=t[0]%360*zt,y=t[1]%360*zt,m=t.length>2?t[2]%360*zt:0,A()):[d*Lt,y*Lt,m*Lt]},e.rebind(w,l,"precision"),function(){return r=t.apply(this,arguments),w.invert=r.invert&&k,A()}}function Cn(t){return Tn(t,function(e,r){t.point(e*zt,r*zt)})}function zn(t,e){return[t,e]}function Ln(t,e){return[t>Tt?t-Mt:t<-Tt?t+Mt:t,e]}function En(t,e,r){return t?e||r?Hr(In(t),Dn(e,r)):In(t):e||r?Dn(e,r):Ln}function Pn(t){return function(e,r){return[(e+=t)>Tt?e-Mt:e<-Tt?e+Mt:e,r]}}function In(t){var e=Pn(t);return e.invert=Pn(-t),e}function Dn(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*r+s*n;return[Math.atan2(l*i-c*a,s*r-u*n),Dt(c*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*i-l*a;return[Math.atan2(l*i+u*a,s*r+c*n),Dt(c*r-s*n)]},o}function On(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Rn(r,i),a=Rn(r,a),(o>0?ia)&&(i+=o*Mt)):(i=t+o*Mt,a=t-.5*l);for(var u,c=i;o>0?c>a:c2?t[2]*zt:0),e.invert=function(e){return(e=t.invert(e[0]*zt,e[1]*zt))[0]*=Lt,e[1]*=Lt,e},e},Ln.invert=zn,e.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=En(-t[0]*zt,-t[1]*zt,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=On((t=+r)*zt,n*zt),i):t},i.precision=function(r){return arguments.length?(e=On(t*zt,(n=+r)*zt),i):n},i.angle(90)},e.geo.distance=function(t,e){var r,n=(e[0]-t[0])*zt,i=t[1]*zt,a=e[1]*zt,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),p=Math.cos(a);return Math.atan2(Math.sqrt((r=p*o)*r+(r=u*c-l*p*s)*r),l*c+u*p*s)},e.geo.graticule=function(){var t,r,n,i,a,o,s,l,u,c,p,h,f=10,d=f,y=90,m=360,g=2.5;function _(){return{type:"MultiLineString",coordinates:x()}}function x(){return e.range(Math.ceil(i/y)*y,n,y).map(p).concat(e.range(Math.ceil(l/m)*m,s,m).map(h)).concat(e.range(Math.ceil(r/f)*f,t,f).filter(function(t){return v(t%y)>kt}).map(u)).concat(e.range(Math.ceil(o/d)*d,a,d).filter(function(t){return v(t%m)>kt}).map(c))}return _.lines=function(){return x().map(function(t){return{type:"LineString",coordinates:t}})},_.outline=function(){return{type:"Polygon",coordinates:[p(i).concat(h(s).slice(1),p(n).reverse().slice(1),h(l).reverse().slice(1))]}},_.extent=function(t){return arguments.length?_.majorExtent(t).minorExtent(t):_.minorExtent()},_.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),_.precision(g)):[[i,l],[n,s]]},_.minorExtent=function(e){return arguments.length?(r=+e[0][0],t=+e[1][0],o=+e[0][1],a=+e[1][1],r>t&&(e=r,r=t,t=e),o>a&&(e=o,o=a,a=e),_.precision(g)):[[r,o],[t,a]]},_.step=function(t){return arguments.length?_.majorStep(t).minorStep(t):_.minorStep()},_.majorStep=function(t){return arguments.length?(y=+t[0],m=+t[1],_):[y,m]},_.minorStep=function(t){return arguments.length?(f=+t[0],d=+t[1],_):[f,d]},_.precision=function(e){return arguments.length?(g=+e,u=Bn(o,a,90),c=Fn(r,t,g),p=Bn(l,s,90),h=Fn(i,n,g),_):g},_.majorExtent([[-180,-90+kt],[180,90-kt]]).minorExtent([[-180,-80-kt],[180,80+kt]])},e.geo.greatArc=function(){var t,r,n=Nn,i=jn;function a(){return{type:"LineString",coordinates:[t||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return e.geo.distance(t||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(e){return arguments.length?(n=e,t="function"==typeof e?null:e,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},e.geo.interpolate=function(t,e){return r=t[0]*zt,n=t[1]*zt,i=e[0]*zt,a=e[1]*zt,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),u=Math.sin(a),c=o*Math.cos(r),p=o*Math.sin(r),h=l*Math.cos(i),f=l*Math.sin(i),d=2*Math.asin(Math.sqrt(Rt(a-n)+o*l*Rt(i-r))),y=1/Math.sin(d),(m=d?function(t){var e=Math.sin(t*=d)*y,r=Math.sin(d-t)*y,n=r*c+e*h,i=r*p+e*f,a=r*s+e*u;return[Math.atan2(i,n)*Lt,Math.atan2(a,Math.sqrt(n*n+i*i))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=d,m;var r,n,i,a,o,s,l,u,c,p,h,f,d,y,m},e.geo.length=function(t){return gn=0,e.geo.stream(t,Vn),gn};var Vn={sphere:O,point:O,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=zt),o=Math.cos(i),s=v((n*=zt)-t),l=Math.cos(s);gn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}Vn.point=function(i,a){t=i*zt,e=Math.sin(a*=zt),r=Math.cos(a),Vn.point=n},Vn.lineEnd=function(){Vn.point=Vn.lineEnd=O}},lineEnd:O,polygonStart:O,polygonEnd:O};function qn(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var Un=qn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(e.geo.azimuthalEqualArea=function(){return Mn(Un)}).raw=Un;var Zn=qn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},E);function Hn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return Xn;function o(t,e){a>0?e<-Ct+kt&&(e=-Ct+kt):e>Ct-kt&&(e=Ct-kt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=Et(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-Ct]},o}function Gn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(v(n)1&&Pt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(e.geo.stereographic=function(){return Mn(Kn)}).raw=Kn,$n.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(e.geo.transverseMercator=function(){var t=Yn($n),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=$n,e.geom={},e.geom.hull=function(t){var e=Qn,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=me(e),a=me(r),o=t.length,s=[],l=[];for(n=0;n=0;--n)f.push(t[s[u[n]][2]]);for(n=+p;nkt)s=s.L;else{if(!((i=a-_i(s,o))>kt)){n>-kt?(e=s.P,r=s):i>-kt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=di(t);if(ui.insert(e,l),e||r){if(e===r)return ki(e),r=di(e.site),ui.insert(l,r),l.edge=r.edge=Mi(e.site,l.site),wi(e),void wi(r);if(r){ki(e),ki(r);var u=e.site,c=u.x,p=u.y,h=t.x-c,f=t.y-p,d=r.site,y=d.x-c,m=d.y-p,g=2*(h*m-f*y),v=h*h+f*f,_=y*y+m*m,x={x:(m*v-f*_)/g+c,y:(h*_-y*v)/g+p};Si(r.edge,u,d,x),l.edge=Mi(u,t,null,x),r.edge=Mi(t,d,null,x),wi(e),wi(r)}else l.edge=Mi(e.site,l.site)}}function vi(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,u=l-e;if(!u)return s;var c=s-n,p=1/a-1/u,h=c/u;return p?(-h+Math.sqrt(h*h-2*p*(c*c/(-2*u)-l+u/2+i-a/2)))/p+n:(n+s)/2}function _i(t,e){var r=t.N;if(r)return vi(r,e);var n=t.site;return n.y===e?n.x:1/0}function xi(t){this.site=t,this.edges=[]}function bi(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,u=n.y-s,c=a.x-o,p=2*(l*(m=a.y-s)-u*c);if(!(p>=-At)){var h=l*l+u*u,f=c*c+m*m,d=(m*h-u*f)/p,y=(l*f-c*h)/p,m=y+s,g=fi.pop()||new function(){Li(this),this.x=this.y=this.arc=this.site=this.cy=null};g.arc=t,g.site=i,g.x=d+o,g.y=m+Math.sqrt(d*d+y*y),g.cy=m,t.circle=g;for(var v=null,_=pi._;_;)if(g.y<_.y||g.y===_.y&&g.x<=_.x){if(!_.L){v=_.P;break}_=_.L}else{if(!_.R){v=_;break}_=_.R}pi.insert(v,g),v||(ci=g)}}}}function ki(t){var e=t.circle;e&&(e.P||(ci=e.N),pi.remove(e),fi.push(e),Li(e),t.circle=null)}function Ai(t,e){var r=t.b;if(r)return!0;var n,i,a=t.a,o=e[0][0],s=e[1][0],l=e[0][1],u=e[1][1],c=t.l,p=t.r,h=c.x,f=c.y,d=p.x,y=p.y,m=(h+d)/2,g=(f+y)/2;if(y===f){if(m=s)return;if(h>d){if(a){if(a.y>=u)return}else a={x:m,y:l};r={x:m,y:u}}else{if(a){if(a.y1)if(h>d){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.y=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xkt||v(i-r)>kt)&&(s.splice(o,0,new Ci((g=a.site,_=c,x=v(n-p)kt?{x:p,y:v(e-p)kt?{x:v(r-d)kt?{x:h,y:v(e-h)kt?{x:v(r-f)=r&&u.x<=i&&u.y>=n&&u.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/kt)*kt,y:Math.round(i(t,e)/kt)*kt,i:e}})}return o.links=function(t){return Di(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Di(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,u=r.edges.sort(bi),c=-1,p=u.length,h=u[p-1].edge,f=h.l===l?h.r:h.l;++ca&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Vi(r,n)})),a=Zi.lastIndex;return ay&&(y=l.x),l.y>m&&(m=l.y),u.push(l.x),c.push(l.y);else for(p=0;py&&(y=x),b>m&&(m=b),u.push(x),c.push(b)}var w=y-f,k=m-d;function A(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,u=t.y;if(null!=l)if(v(l-r)+v(u-n)<.01)T(t,e,r,n,i,a,o,s);else{var c=t.point;t.x=t.y=t.point=null,T(t,c,l,u,i,a,o,s),T(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,i,a,o,s)}function T(t,e,r,n,i,a,o,s){var l=.5*(i+o),u=.5*(a+s),c=r>=l,p=n>=u,h=p<<1|c;t.leaf=!1,t=t.nodes[h]||(t.nodes[h]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(M,t,+g(t,++p),+_(t,p),f,d,y,m)}}),c?i=l:o=l,p?a=u:s=u,A(t,e,r,n,i,a,o,s)}w>k?m=d+w:y=f+k;var M={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(M,t,+g(t,++p),+_(t,p),f,d,y,m)}};if(M.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),u=r.nodes;u[0]&&t(e,u[0],n,i,s,l),u[1]&&t(e,u[1],s,i,a,l),u[2]&&t(e,u[2],n,l,s,o),u[3]&&t(e,u[3],s,l,a,o)}}(t,M,f,d,y,m)},M.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(u,c,p,h,f){if(!(c>a||p>o||h=b)<<1|e>=x,k=w+4;w=0&&!(n=e.interpolators[i](t,r)););return n}function Gi(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ea(t){return 1-Math.cos(t*Ct)}function ra(t){return Math.pow(2,10*(t-1))}function na(t){return 1-Math.sqrt(1-t*t)}function ia(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}function aa(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oa(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=la(i),s=sa(i,a),l=la(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Xi.get(i)||Wi,a=Yi.get(a)||E,e=a(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},e.interpolateHcl=function(t,r){t=e.hcl(t),r=e.hcl(r);var n=t.h,i=t.c,a=t.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Wt(n+o*t,i+s*t,a+l*t)+""}},e.interpolateHsl=function(t,r){t=e.hsl(t),r=e.hsl(r);var n=t.h,i=t.s,a=t.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Zt(n+o*t,i+s*t,a+l*t)+""}},e.interpolateLab=function(t,r){t=e.lab(t),r=e.lab(r);var n=t.l,i=t.a,a=t.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},e.interpolateRound=aa,e.transform=function(t){var r=i.createElementNS(e.ns.prefix.svg,"g");return(e.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oa(e?e.matrix:ua)})(t)},oa.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ua={a:1,b:0,c:0,d:1,e:0,f:0};function ca(t){return t.length?t.pop()+",":""}function pa(t,r){var n=[],i=[];return t=e.transform(t),r=e.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(t.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ca(r)+"rotate(",null,")")-2,x:Vi(t,e)})):e&&r.push(ca(r)+"rotate("+e+")")}(t.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(ca(r)+"skewX(",null,")")-2,x:Vi(t,e)}):e&&r.push(ca(r)+"skewX("+e+")")}(t.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(ca(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ca(r)+"scale("+e+")")}(t.scale,r.scale,n,i),t=r=null,function(t){for(var e,r=-1,a=i.length;++r0?n=e:(t.c=null,t.t=NaN,t=null,l.end({type:"end",alpha:n=0})):e>0&&(l.start({type:"start",alpha:n=e}),t=Ae(s.tick)),s):n},s.start=function(){var t,e,r,n=g.length,l=v.length,c=u[0],d=u[1];for(t=0;t=0;)r.push(i[n])}function Ta(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;r&&(a.value=0),a.children=u}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return Ta(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Aa(t,function(t){t.children&&(t.value=0)}),Ta(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},e.layout.partition=function(){var t=e.layout.hierarchy(),r=[1,1];function n(e,n){var i=t.call(this,e,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++us&&(s=n),o.push(n)}for(r=0;ri&&(n=r,i=e);return n}function Na(t){return t.reduce(ja,0)}function ja(t,e){return t+e[1]}function Va(t,e){return qa(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function qa(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function Ua(t){return[e.min(t),e.max(t)]}function Za(t,e){return t.value-e.value}function Ha(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ga(t,e){t._pack_next=e,e._pack_prev=t}function Wa(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Xa(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,u=1/0,c=-1/0,p=1/0,h=-1/0;if(e.forEach(Ya),(r=e[0]).x=-r.r,r.y=0,_(r),l>1&&((n=e[1]).x=n.r,n.y=0,_(n),l>2))for(Ka(r,n,i=e[2]),_(i),Ha(r,i),r._pack_prev=i,Ha(i,n),n=r._pack_next,a=3;a0)for(o=-1;++o=p[0]&&l<=p[1]&&((s=u[e.bisect(h,l,1,d)-1]).y+=y,s.push(a[o]));return u}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=me(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return qa(e,t)}:me(t),a):i},a.frequency=function(e){return arguments.length?(t=!!e,a):t},a},e.layout.pack=function(){var t,r=e.layout.hierarchy().sort(Za),n=0,i=[1,1];function a(e,a){var o=r.call(this,e,a),s=o[0],l=i[0],u=i[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(s.x=s.y=0,Ta(s,function(t){t.r=+c(t.value)}),Ta(s,Xa),n){var p=n*(t?1:Math.max(2*s.r/l,2*s.r/u))/2;Ta(s,function(t){t.r+=p}),Ta(s,Xa),Ta(s,function(t){t.r-=p})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++of.x&&(f=t),t.depth>d.depth&&(d=t)});var y=r(h,f)/2-h.x,m=n[0]/(f.x+r(f,h)/2+y),g=n[1]/(d.depth||1);Aa(c,function(t){t.x=(t.x+y)*m,t.y=t.depth*g})}return u}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],u=a.m,c=o.m,p=s.m,h=l.m;s=to(s),a=Qa(a),s&&a;)l=Qa(l),(o=to(o)).a=t,(i=s.z+p-a.z-u+r(s._,a._))>0&&(eo(ro(s,t,n),t,i),u+=i,c+=i),p+=s.m,u+=a.m,h+=l.m,c+=o.m;s&&!to(o)&&(o.t=s,o.m+=p-c),a&&!Qa(l)&&(l.t=a,l.m+=u-h,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},ka(a,t)},e.layout.cluster=function(){var t=e.layout.hierarchy().sort(null).value(null),r=$a,n=[1,1],i=!1;function a(a,o){var s,l=t.call(this,a,o),u=l[0],c=0;Ta(u,function(t){var n=t.children;n&&n.length?(t.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),t.y=function(t){return 1+e.max(t,function(t){return t.y})}(n)):(t.x=s?c+=r(t,s):0,t.y=0,s=t)});var p=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),h=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),f=p.x-r(p,h)/2,d=h.x+r(h,p)/2;return Ta(u,i?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-f)/(d-f)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},ka(a,t)},e.layout.treemap=function(){var t,r=e.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=no,s=!1,l="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,i=-1,a=t.length;++i0;)s.push(r=u[i-1]),s.area+=r.area,"squarify"!==l||(n=f(s,y))<=h?(u.pop(),h=n):(s.area-=s.pop().area,d(s,y,a,!1),y=Math.min(a.dx,a.dy),s.length=s.area=0,h=1/0);s.length&&(d(s,y,a,!0),s.length=s.area=0),e.forEach(p)}}function h(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(c(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(d(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(h)}}function f(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++oi&&(i=r));return e*=e,(n*=n)?Math.max(e*i*u/n,n/(e*a*u)):1/0}function d(t,e,r,i){var a,o=-1,s=t.length,l=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((i||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=e.random.normal.apply(e,arguments);return function(){return Math.exp(t())}},bates:function(t){var r=e.random.irwinHall(t);return function(){return r()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?po:so,s=i?fa:ha;return a=t(e,r,s,n),o=t(r,e,s,Hi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(aa)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return mo(e,t)};l.tickFormat=function(t,r){return go(e,t,r)};l.nice=function(t){return fo(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Hi,!1)};var vo={s:1,g:1,p:1,r:1,e:1};function _o(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}e.scale.log=function(){return function t(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=lo(a.map(o),i?Math:bo);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=ao(a),e=[],r=t[0],l=t[1],u=Math.floor(o(r)),c=Math.ceil(o(l)),p=n%1?2:n;if(isFinite(c-u)){if(i){for(;u0;h--)e.push(s(u)*h);for(u=0;e[u]l;c--);e=e.slice(u,c)}return e};l.tickFormat=function(t,r){if(!arguments.length)return xo;arguments.length<2?r=xo:"function"!=typeof r&&(r=e.format(r));var i=Math.max(1,n*t/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n0?i[t-1]:r[0],tp?0:1;if(u=St)return l(u,f)+(s?l(s,1-f):"")+"Z";var d,y,m,g,v,_,x,b,w,k,A,T,M=0,S=0,C=[];if((g=(+o.apply(this,arguments)||0)/2)&&(m=n===Co?Math.sqrt(s*s+u*u):+n.apply(this,arguments),f||(S*=-1),u&&(S=Dt(m/u*Math.sin(g))),s&&(M=Dt(m/s*Math.sin(g)))),u){v=u*Math.cos(c+S),_=u*Math.sin(c+S),x=u*Math.cos(p-S),b=u*Math.sin(p-S);var z=Math.abs(p-c-2*S)<=Tt?0:1;if(S&&Do(v,_,x,b)===f^z){var L=(c+p)/2;v=u*Math.cos(L),_=u*Math.sin(L),x=b=null}}else v=_=0;if(s){w=s*Math.cos(p-M),k=s*Math.sin(p-M),A=s*Math.cos(c+M),T=s*Math.sin(c+M);var E=Math.abs(c-p+2*M)<=Tt?0:1;if(M&&Do(w,k,A,T)===1-f^E){var P=(c+p)/2;w=s*Math.cos(P),k=s*Math.sin(P),A=T=null}}else w=k=0;if(h>kt&&(d=Math.min(Math.abs(u-s)/2,+r.apply(this,arguments)))>.001){y=s0?0:1}function Oo(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,p=t[1]+u,h=e[0]+l,f=e[1]+u,d=(c+h)/2,y=(p+f)/2,m=h-c,g=f-p,v=m*m+g*g,_=r-n,x=c*f-h*p,b=(g<0?-1:1)*Math.sqrt(Math.max(0,_*_*v-x*x)),w=(x*g-m*b)/v,k=(-x*m-g*b)/v,A=(x*g+m*b)/v,T=(-x*m+g*b)/v,M=w-d,S=k-y,C=A-d,z=T-y;return M*M+S*S>C*C+z*z&&(w=A,k=T),[[w-l,k-u],[w*r/_,k*r/_]]}function Ro(t){var e=Qn,r=ti,n=Gr,i=Fo,a=i.key,o=.7;function s(a){var s,l=[],u=[],c=-1,p=a.length,h=me(e),f=me(r);function d(){l.push("M",i(t(u),o))}for(;++c1&&i.push("H",n[0]);return i.join("")},"step-before":jo,"step-after":Vo,basis:Zo,"basis-open":function(t){if(t.length<4)return Fo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Ho(Xo,a)+","+Ho(Xo,o)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Fo(t){return t.length>1?t.join("L"):t+"Z"}function No(t){return t.join("L")+"Z"}function jo(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;uTt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=me(t),a):r},a.source=function(e){return arguments.length?(t=me(e),a):t},a.target=function(t){return arguments.length?(e=me(t),a):e},a.startAngle=function(t){return arguments.length?(n=me(t),a):n},a.endAngle=function(t){return arguments.length?(i=me(t),a):i},a},e.svg.diagonal=function(){var t=Nn,e=jn,r=ts;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=me(e),n):t},n.target=function(t){return arguments.length?(e=me(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},e.svg.diagonal.radial=function(){var t=e.svg.diagonal(),r=ts,n=t.projection;return t.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},t},e.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=me(e),r):t},r.size=function(t){return arguments.length?(e=me(t),r):e},r};var is=e.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*os)),r=e*os;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});e.svg.symbolTypes=is.keys();var as=Math.sqrt(3),os=Math.tan(30*zt);W.transition=function(t){for(var e,r,n=cs||++fs,i=ms(t),a=[],o=ps||{time:Date.now(),ease:ta,delay:0,duration:250},s=-1,l=this.length;++s0;)u[--h].call(t,o);if(a>=1)return p.event&&p.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}p||(a=i.time,o=Ae(function(t){var e=p.delay;if(o.t=e+a,e<=t)return h(t-e);o.c=h},0,a),p=c[n]={tween:new x,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++c.count)}hs.call=W.call,hs.empty=W.empty,hs.node=W.node,hs.size=W.size,e.transition=function(t,r){return t&&t.transition?cs?t.transition(r):t:e.selection().transition(t)},e.transition.prototype=hs,hs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=X(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function y(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function m(){var p,m,g=this,v=e.select(e.event.target),_=n.of(g,arguments),x=e.select(g),b=v.datum(),w=!/^(n|s)$/.test(b)&&i,k=!/^(e|w)$/.test(b)&&a,A=v.classed("extent"),T=_t(g),M=e.mouse(g),S=e.select(o(g)).on("keydown.brush",function(){32==e.event.keyCode&&(A||(p=null,M[0]-=s[1],M[1]-=l[1],A=2),F())}).on("keyup.brush",function(){32==e.event.keyCode&&2==A&&(M[0]+=s[1],M[1]+=l[1],A=0,F())});if(e.event.changedTouches?S.on("touchmove.brush",L).on("touchend.brush",P):S.on("mousemove.brush",L).on("mouseup.brush",P),x.interrupt().selectAll("*").interrupt(),A)M[0]=s[0]-M[0],M[1]=l[0]-M[1];else if(b){var C=+/w$/.test(b),z=+/^n/.test(b);m=[s[1-C]-M[0],l[1-z]-M[1]],M[0]=s[C],M[1]=l[z]}else e.event.altKey&&(p=M.slice());function L(){var t=e.mouse(g),r=!1;m&&(t[0]+=m[0],t[1]+=m[1]),A||(e.event.altKey?(p||(p=[(s[0]+s[1])/2,(l[0]+l[1])/2]),M[0]=s[+(t[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=zs(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=zs(+e+1);return e}}:t))},i.ticks=function(t,e){var r=ao(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],zs(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Cs(t.copy(),r,n)},ho(i,t)}function zs(t){return new Date(t)}As.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ss:Ms,Ss.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Ss.toString=Ms.toString,Ie.second=Be(function(t){return new De(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Ie.seconds=Ie.second.range,Ie.seconds.utc=Ie.second.utc.range,Ie.minute=Be(function(t){return new De(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Ie.minutes=Ie.minute.range,Ie.minutes.utc=Ie.minute.utc.range,Ie.hour=Be(function(t){var e=t.getTimezoneOffset()/60;return new De(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Ie.hours=Ie.hour.range,Ie.hours.utc=Ie.hour.utc.range,Ie.month=Be(function(t){return(t=Ie.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Ie.months=Ie.month.range,Ie.months.utc=Ie.month.utc.range;var Ls=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Es=[[Ie.second,1],[Ie.second,5],[Ie.second,15],[Ie.second,30],[Ie.minute,1],[Ie.minute,5],[Ie.minute,15],[Ie.minute,30],[Ie.hour,1],[Ie.hour,3],[Ie.hour,6],[Ie.hour,12],[Ie.day,1],[Ie.day,2],[Ie.week,1],[Ie.month,1],[Ie.month,3],[Ie.year,1]],Ps=As.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Gr]]),Is={range:function(t,r,n){return e.range(Math.ceil(t/n)*n,+r,n).map(zs)},floor:E,ceil:E};Es.year=Ie.year,Ie.scale=function(){return Cs(e.scale.linear(),Es,Ps)};var Ds=Es.map(function(t){return[t[0].utc,t[1]]}),Os=Ts.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Gr]]);function Rs(t){return JSON.parse(t.responseText)}function Bs(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Ds.year=Ie.year.utc,Ie.scale.utc=function(){return Cs(e.scale.linear(),Ds,Os)},e.text=ge(function(t){return t.responseText}),e.json=function(t,e){return ve(t,"application/json",Rs,e)},e.html=function(t,e){return ve(t,"text/html",Bs,e)},e.xml=ge(function(t){return t.responseXML}),t.exports?t.exports=e:this.d3=e}(),t=t.exports;var e=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},n={},i=Math.PI;n.deg2rad=function(t){return t/180*i},n.rad2deg=function(t){return t/i*180},n.wrap360=function(t){var e=t%360;return e<0?e+360:e},n.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var a=r.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,i=t.round,a=t.min,o=t.max,l=t.random;function u(s,l){if(s=s||"",l=l||{},s instanceof u)return s;if(!(this instanceof u))return new u(s,l);var c=function(n){var i={r:0,g:0,b:0},s=1,l=null,u=null,c=null,p=!1,h=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,i=!1;if(S[t])t=S[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=j.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=j.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=j.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=j.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=j.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=j.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=j.hex8.exec(t))return{r:P(n[1]),g:P(n[2]),b:P(n[3]),a:R(n[4]),format:i?"name":"hex8"};if(n=j.hex6.exec(t))return{r:P(n[1]),g:P(n[2]),b:P(n[3]),format:i?"name":"hex"};if(n=j.hex4.exec(t))return{r:P(n[1]+""+n[1]),g:P(n[2]+""+n[2]),b:P(n[3]+""+n[3]),a:R(n[4]+""+n[4]),format:i?"name":"hex8"};if(n=j.hex3.exec(t))return{r:P(n[1]+""+n[1]),g:P(n[2]+""+n[2]),b:P(n[3]+""+n[3]),format:i?"name":"hex"};return!1}(n));"object"==typeof n&&(V(n.r)&&V(n.g)&&V(n.b)?(f=n.r,d=n.g,y=n.b,i={r:255*L(f,255),g:255*L(d,255),b:255*L(y,255)},p=!0,h="%"===String(n.r).substr(-1)?"prgb":"rgb"):V(n.h)&&V(n.s)&&V(n.v)?(l=D(n.s),u=D(n.v),i=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var i=t.floor(e),a=e-i,o=n*(1-r),s=n*(1-a*r),l=n*(1-(1-a)*r),u=i%6;return{r:255*[n,s,o,o,l,n][u],g:255*[l,n,n,s,o,o][u],b:255*[o,o,l,n,n,s][u]}}(n.h,l,u),p=!0,h="hsv"):V(n.h)&&V(n.s)&&V(n.l)&&(l=D(n.s),c=D(n.l),i=function(t,e,r){var n,i,a;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(n.h,l,c),p=!0,h="hsl"),n.hasOwnProperty("a")&&(s=n.a));var f,d,y;return s=z(s),{ok:p,format:n.format||h,r:a(255,o(i.r,0)),g:a(255,o(i.g,0)),b:a(255,o(i.b,0)),a:s}}(s);this._originalInput=s,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=i(100*this._a)/100,this._format=l.format||c.format,this._gradientType=l.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=c.ok,this._tc_id=n++}function c(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,i,s=o(t,e,r),l=a(t,e,r),u=(s+l)/2;if(s==l)n=i=0;else{var c=s-l;switch(i=u>.5?c/(2-s-l):c/(s+l),s){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(u(n));return a}function M(t,e){e=e||6;for(var r=u(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(u({h:n,s:i,v:a})),a=(a+s)%1;return o}u.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=z(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=p(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=p(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=c(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=c(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return h(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[I(i(t).toString(16)),I(i(e).toString(16)),I(i(r).toString(16)),I(O(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*L(this._r,255))+"%",g:i(100*L(this._g,255))+"%",b:i(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%)":"rgba("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[h(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+f(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=u(t);r="#"+f(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return u(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(g,arguments)},brighten:function(){return this._applyModification(v,arguments)},darken:function(){return this._applyModification(_,arguments)},desaturate:function(){return this._applyModification(d,arguments)},saturate:function(){return this._applyModification(y,arguments)},greyscale:function(){return this._applyModification(m,arguments)},spin:function(){return this._applyModification(x,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(b,arguments)},monochromatic:function(){return this._applyCombination(M,arguments)},splitcomplement:function(){return this._applyCombination(A,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},u.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:D(t[n]));t=r}return u(t,e)},u.equals=function(t,e){return!(!t||!e)&&u(t).toRgbString()==u(e).toRgbString()},u.random=function(){return u.fromRatio({r:l(),g:l(),b:l()})},u.mix=function(t,e,r){r=0===r?0:r||50;var n=u(t).toRgb(),i=u(e).toRgb(),a=r/100;return u({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},u.readability=function(e,r){var n=u(e),i=u(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},u.isReadable=function(t,e,r){var n,i,a=u.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},u.mostReadable=function(t,e,r){var n,i,a,o,s=null,l=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var c=0;cl&&(l=n,s=u(e[c]));return u.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,u.mostReadable(t,["#fff","#000"],r))};var S=u.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"},C=u.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(S);function z(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=a(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function E(t){return a(1,o(0,t))}function P(t){return parseInt(t,16)}function I(t){return 1==t.length?"0"+t:""+t}function D(t){return t<=1&&(t=100*t+"%"),t}function O(e){return t.round(255*parseFloat(e)).toString(16)}function R(t){return P(t)/255}var B,F,N,j=(F="[\\s|\\(]+("+(B="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+B+")[,|\\s]+("+B+")\\s*\\)?",N="[\\s|\\(]+("+B+")[,|\\s]+("+B+")[,|\\s]+("+B+")[,|\\s]+("+B+")\\s*\\)?",{CSS_UNIT:new RegExp(B),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+N),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})$/});function V(t){return!!j.CSS_UNIT.exec(t)}s.exports?s.exports=u:window.tinycolor=u}(Math),s=s.exports;var l={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=l.RdBu,c=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],i=t[e][1],o=!1,H(n))for(r=n.length-1;r>=0;r--)Y(n[r],K(i,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)Y(n[a[r]],K(i,a[r]))?delete n[a[r]]:o=!0;if(o)return}}(l)):o[e[a]]=n}}function K(t,r){var n=r;return e(r)?n="["+r+"]":t&&(n="."+r),t+n}function $(t,e,r,n){var i,a=H(r),o=!0,s=r,l=n.replace("-1",0),u=!a&&Y(r,l),c=e[0];for(i=0;ii.max?r.set(n):r.set(+t)}},integer:{coerceFunction:function(t,r,n,i){t%1||!e(t)||void 0!==i.min&&ti.max?r.set(n):r.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){s(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return s(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(p(t,r))}},angle:{coerceFunction:function(t,r,n){"auto"===t?r.set("auto"):e(t)?r.set(it(+t)):r.set(n)}},subplotid:{coerceFunction:function(t,e,r){"string"==typeof t&&rt(r).test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!rt(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a=ot&&t<=st?t:ct;if("string"!=typeof t&&"number"!=typeof t)return ct;t=String(t);var r=xt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var i=r&&"chinese"===e.substr(0,7),a=t.match(i?vt:gt);if(!a)return ct;var o=a[1],s=a[3]||"1",l=Number(a[5]||1),u=Number(a[7]||0),c=Number(a[9]||0),p=Number(a[11]||0);if(r){if(2===o.length)return ct;var h;o=Number(o);try{var f=P.getComponentMethod("calendars","getCal")(e);if(i){var d="i"===s.charAt(s.length-1);s=parseInt(s,10),h=f.newDate(o,f.toMonthIndex(o,s,d),l)}else h=f.newDate(o,Number(s),l)}catch(t){return ct}return h?(h.toJD()-yt)*pt+u*ht+c*ft+p*dt:ct}o=2===o.length?(Number(o)+2e3-_t)%100+_t:Number(o),s-=1;var y=new Date(Date.UTC(2e3,s,l,u,c));return y.setUTCFullYear(o),y.getUTCMonth()!==s?ct:y.getUTCDate()!==l?ct:y.getTime()+p*dt},ot=ut.MIN_MS=ut.dateTime2ms("-9999"),st=ut.MAX_MS=ut.dateTime2ms("9999-12-31 23:59:59.9999"),ut.isDateTime=function(t,e){return ut.dateTime2ms(t,e)!==ct};var wt=90*pt,kt=3*ht,At=5*ft;function Tt(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+bt(e,2)+":"+bt(r,2),(n||i)&&(t+=":"+bt(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+bt(i,a)}return t}ut.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ot&&t<=st))return ct;e||(e=0);var n,i,a,o,s,l,u=Math.floor(10*lt(t+.05,1)),c=Math.round(t-u/10);if(xt(r)){var p=Math.floor(c/pt)+yt,h=Math.floor(lt(t,pt));try{n=P.getComponentMethod("calendars","getCal")(r).fromJD(p).formatDate("yyyy-mm-dd")}catch(t){n=mt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;i=e=ot+pt&&e<=st-pt))return ct;var r=Math.floor(10*lt(e+.05,1)),n=new Date(Math.round(e-r/10));return Tt(t.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ut.cleanDate=function(t,e,r){if(ut.isJSDate(t)||"number"==typeof t){if(xt(r))return b.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ut.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ut.isDateTime(t,r))return b.error("unrecognized date",t),e;return t};var Mt=/%\d?f/g;function St(t,e,r,n){t=t.replace(Mt,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(xt(n))try{t=P.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var Ct=[59,59.9,59.99,59.999,59.9999];ut.formatDate=function(t,r,n,i,a,o){if(a=xt(a)&&a,!r)if("y"===n)r=o.year;else if("m"===n)r=o.month;else{if("d"!==n)return function(t,r){var n=lt(t+.05,pt),i=bt(Math.floor(n/ht),2)+":"+bt(lt(Math.floor(n/ft),60),2);if("M"!==r){e(r)||(r=0);var a=(100+Math.min(lt(t/dt,60),Ct[r])).toFixed(r).substr(1);r>0&&(a=a.replace(/0+$/,"").replace(/[\.]$/,"")),i+=":"+a}return i}(t,n)+"\n"+St(o.dayMonthYear,t,i,a);r=o.dayMonth+"\n"+o.year}return St(r,t,i,a)};var zt=3*pt;ut.incrementMonth=function(t,e,r){r=xt(r)&&r;var n=lt(t,pt);if(t=Math.round(t-n),r)try{var i=Math.round(t/pt)+yt,a=P.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-yt)*pt+n}catch(e){b.error("invalid ms "+t+" in calendar "+r)}var s=new Date(t+zt);return s.setUTCMonth(s.getUTCMonth()+e)+n-zt},ut.findExactDates=function(t,r){for(var n,i,a=0,o=0,s=0,l=0,u=xt(r)&&P.getComponentMethod("calendars","getCal")(r),c=0;c1||y<0||y>1?null:{x:t+l*y,y:e+p*y}}function Bt(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}Ot.segmentsIntersect=Rt,Ot.segmentDistance=function(t,e,r,n,i,a,o,s){if(Rt(t,e,r,n,i,a,o,s))return 0;var l=r-t,u=n-e,c=o-i,p=s-a,h=l*l+u*u,f=c*c+p*p,d=Math.min(Bt(l,u,h,i-t,a-e),Bt(l,u,h,o-t,s-e),Bt(c,p,f,t-i,e-a),Bt(c,p,f,r-i,n-a));return Math.sqrt(d)},Ot.getTextLocation=function(t,e,r,n){if(t===It&&n===Dt||(Pt={},It=t,Dt=n),Pt[r])return Pt[r];var i=t.getPointAtLength(lt(r-n/2,e)),a=t.getPointAtLength(lt(r+n/2,e)),o=Math.atan((a.y-i.y)/(a.x-i.x)),s=t.getPointAtLength(lt(r,e)),l={x:(4*s.x+i.x+a.x)/6,y:(4*s.y+i.y+a.y)/6,theta:o};return Pt[r]=l,l},Ot.clearLocationCache=function(){It=null},Ot.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,u=0,c=t.getTotalLength(),p=c;function h(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(i=r);var u=r.xo?r.x-o:0,p=r.yl?r.y-l:0;return Math.sqrt(u*u+p*p)}for(var f=h(u);f;){if((u+=f+r)>p)return;f=h(u)}for(f=h(p);f;){if(u>(p-=f+r))return;f=h(p)}return{min:u,max:p,len:p-u,total:c,isClosed:0===u&&p===c&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},Ot.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,p=0,h=0,f=s;p0?f=i:h=i,p++}return a};var Ft=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},Nt=/^\w*$/,jt={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Yt(t,e){return t>=e}Ht.findBin=function(t,r,n){if(e(r.start))return n?Math.ceil((t-r.start)/r.size-1e-9)-1:Math.floor((t-r.start)/r.size+1e-9);var i,a,o=0,s=r.length,l=0,u=s>1?(r[s-1]-r[0])/(s-1):1;for(a=u>=0?n?Gt:Wt:n?Yt:Xt,t+=1e-9*u*(n?-1:1)*(u>=0?1:-1);o90&&b.log("Long binary search..."),o-1},Ht.sorterAsc=function(t,e){return t-e},Ht.sorterDes=function(t,e){return e-t},Ht.distinctVals=function(t){var e=t.slice();e.sort(Ht.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,i=n/(r||1)/1e4,a=[e[0]],o=0;oe[o]+i&&(n=Math.min(n,e[o+1]-e[o]),a.push(e[o+1]));return{vals:a,minDiff:n}},Ht.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;in.length)&&(i=n.length),e(r)||(r=!1),Kt(n[0])){for(o=new Array(i),a=0;at.length-1)return t[t.length-1];var n=r%1;return n*t[Math.ceil(r)]+(1-n)*t[Math.floor(r)]};var $t={},Qt={};function te(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}$t.throttle=function(t,e,r){var n=Qt[t],i=Date.now();if(!n){for(var a in Qt)Qt[a].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},$t.done=function(t){var e=Qt[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},$t.clear=function(t){if(t)te(Qt[t]),delete Qt[t];else for(var e in Qt)$t.clear(e)};var ee=function(t,r){if(t>0)return Math.log(t)/Math.LN10;var n=Math.log(Math.min(r[0],r[1]))/Math.LN10;return e(n)||(n=Math.log(Math.max(r[0],r[1]))/Math.LN10-6),n},re={},ne=r.FP_SAFE,ie=r.BADNUM,ae=re={};ae.nestedProperty=G,ae.keyedContainer=function(t,e,r,n){var i,a;r=r||"name",n=n||"value";var o={};a=e&&e.length?G(t,e).get():t,e=e||"",a=a||[];var s={};for(i=0;i2)return o[e]=2|o[e],u.set(t,null);if(l){for(i=e;i/g),s=0;sne?ie:e(t)?Number(t):ie:ie},ae.noop=A,ae.identity=function(t){return t},ae.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},ae.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},ae.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):s},ae.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},ae.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},ae.syncOrAsync=function(t,e,r){var n;function i(){return ae.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,ae.promiseError);return r&&r(e)},ae.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},ae.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n=0&&a%1==0){var d=i?i[f]:f,y=n?n[d]:d;p(y)&&(t[y].selected=1)}}},ae.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=ae.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ae.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l};var le=/%{([^\s%{}]*)}/g,ue=/^\w*$/;ae.templateString=function(t,e){var r={};return t.replace(le,function(t,n){return ue.test(n)?e[n]||"":(r[n]=r[n]||ae.nestedProperty(e,n).get,r[n]()||"")})};ae.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a=48&&o<=57,u=s>=48&&s<=57;if(l&&(n=10*n+o-48),u&&(i=10*i+s-48),!l||!u){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n};var ce=2e9;ae.seedPseudoRandom=function(){ce=2e9},ae.pseudoRandom=function(){var t=ce;return ce=(69069*ce+1)%4294967296,Math.abs(ce-t)<429496729?ae.pseudoRandom():ce/4294967296};var pe={"X,X div":"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 .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"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":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","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 .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 he in pe){var fe=he.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");re.addStyleRule(fe,pe[he])}var de,ye,me,ge={undo:{width:857.1,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",ascent:850,descent:-150},home:{width:928.6,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",ascent:850,descent:-150},"camera-retro":{width:1e3,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",ascent:850,descent:-150},zoombox:{width:1e3,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",ascent:850,descent:-150},pan:{width:1e3,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",ascent:850,descent:-150},zoom_plus:{width:1e3,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",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,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",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,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",ascent:850,descent:-150},plotlylogo:{width:1542,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",ascent:850,descent:-150},"z-axis":{width:1e3,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",ascent:850,descent:-150},"3d_rotate":{width:1e3,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",ascent:850,descent:-150},camera:{width:1e3,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",ascent:850,descent:-150},movie:{width:1e3,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",ascent:850,descent:-150},question:{width:857.1,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",ascent:850,descent:-150},disk:{width:857.1,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",ascent:850,descent:-150},lasso:{width:1031,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",ascent:850,descent:-150},selectbox:{width:1e3,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",ascent:850,descent:-150},spikeline:{width:1e3,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",ascent:850,descent:-150}},ve=de={};function _e(){throw new Error("setTimeout has not been defined")}function xe(){throw new Error("clearTimeout has not been defined")}function be(t){if(ye===setTimeout)return setTimeout(t,0);if((ye===_e||!ye)&&setTimeout)return ye=setTimeout,setTimeout(t,0);try{return ye(t,0)}catch(e){try{return ye.call(null,t,0)}catch(e){return ye.call(this,t,0)}}}!function(){try{ye="function"==typeof setTimeout?setTimeout:_e}catch(t){ye=_e}try{me="function"==typeof clearTimeout?clearTimeout:xe}catch(t){me=xe}}();var we,ke=[],Ae=!1,Te=-1;function Me(){Ae&&we&&(Ae=!1,we.length?ke=we.concat(ke):Te=-1,ke.length&&Se())}function Se(){if(!Ae){var t=be(Me);Ae=!0;for(var e=ke.length;e;){for(we=ke,ke=[];++Te1)for(var r=1;r=0))return t;if(3===o)i[o]>1&&(i[o]=1);else if(i[o]>=1)return t}var s=Math.round(255*i[0])+", "+Math.round(255*i[1])+", "+Math.round(255*i[2]);return a?"rgba("+s+", "+i[3]+")":"rgb("+s+")"}Re.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},Re.rgb=function(t){return Re.tinyRGB(s(t))},Re.opacity=function(t){return t?s(t).getAlpha():0},Re.addOpacity=function(t,e){var r=s(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},Re.combine=function(t,e){var r=s(t).toRgb();if(1===r.a)return s(t).toRgbString();var n=s(e||Fe).toRgb(),i=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},a={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return s(a).toRgbString()},Re.contrast=function(t,e,r){var n=s(t);return 1!==n.getAlpha()&&(n=s(Re.combine(t,Fe))),(n.isDark()?e?n.lighten(e):Fe:r?n.darken(r):Be).toString()},Re.stroke=function(t,e){var r=s(e);t.style({stroke:Re.tinyRGB(r),"stroke-opacity":r.getAlpha()})},Re.fill=function(t,e){var r=s(e);t.style({fill:Re.tinyRGB(r),"fill-opacity":r.getAlpha()})},Re.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,a=Object.keys(t);for(e=0;e=0,d=r.indexOf("end")>=0,y=u.backoff*p+n.standoff,m=c.backoff*h+n.startstandoff;if("line"===l.nodeName){i={x:+e.attr("x1"),y:+e.attr("y1")},a={x:+e.attr("x2"),y:+e.attr("y2")};var g=i.x-a.x,v=i.y-a.y;if(s=(o=Math.atan2(v,g))+Math.PI,y&&m&&y+m>Math.sqrt(g*g+v*v))return void z();if(y){if(y*y>g*g+v*v)return void z();var _=y*Math.cos(o),x=y*Math.sin(o);a.x+=_,a.y+=x,e.attr({x2:a.x,y2:a.y})}if(m){if(m*m>g*g+v*v)return void z();var b=m*Math.cos(o),w=m*Math.sin(o);i.x-=b,i.y-=w,e.attr({x1:i.x,y1:i.y})}}else if("path"===l.nodeName){var k=l.getTotalLength(),A="";if(k0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},We.prototype.on=We.prototype.addListener,We.prototype.once=function(t,e){if(!Ye(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},We.prototype.removeListener=function(t,e){var r,n,i,a;if(!Ye(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=(r=this._events[t]).length,n=-1,r===e||Ye(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Je(r)){for(a=i;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},We.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(Ye(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},We.prototype.listeners=function(t){return this._events&&this._events[t]?Ye(this._events[t])?[this._events[t]]:this._events[t].slice():[]},We.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(Ye(e))return 1;if(e)return e.length}return 0},We.listenerCount=function(t,e){return t.listenerCount(e)};var $e,Qe=Xe.EventEmitter,tr={init:function(t){if(t._ev instanceof Qe)return t;var e=new Qe,r=new Qe;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;l4/3-s?o:s},nr.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:re.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:re.constrain(Math.floor(3*e),0,2),He[e][t]},nr.unhover=$e.wrapped,nr.unhoverRaw=$e.raw,nr.init=function(t){var e,r,n,i,a,o,s,l,u=t.gd,c=1,p=h.DBLCLICKDELAY,f=t.element;u._mouseDownTime||(u._mouseDownTime=0),f.style.pointerEvents="all",f.onmousedown=y,qe?(f._ontouchstart&&f.removeEventListener("touchstart",f._ontouchstart),f._ontouchstart=y,f.addEventListener("touchstart",y,{passive:!1})):f.ontouchstart=y;var d=t.clampFn||function(t,e,r){return Math.abs(t)p&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!l){var r;try{r=new MouseEvent("click",e)}catch(t){var n=ar(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}s.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&P.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},nr.coverSlip=ir;var or={zauto:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{zmin:void 0,zmax:void 0}},zmin:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},zmax:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},colorscale:{valType:"colorscale",editType:"calc",impliedEdits:{autocolorscale:!1}},autocolorscale:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{colorscale:void 0}},reversescale:{valType:"boolean",dflt:!1,editType:"calc"},showscale:{valType:"boolean",dflt:!0,editType:"calc"}},sr=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n},lr=function(t,e,r,n){var i,a;r?(i=re.nestedProperty(t,r).get(),a=re.nestedProperty(t._input,r).get()):(i=t,a=t._input);var o=n+"auto",s=n+"min",u=n+"max",c=i[o],p=i[s],h=i[u],f=i.colorscale;!1===c&&void 0!==p||(p=re.aggNums(Math.min,null,e)),!1===c&&void 0!==h||(h=re.aggNums(Math.max,null,e)),p===h&&(p-=.5,h+=.5),i[s]=p,i[u]=h,a[s]=p,a[u]=h,a[o]=!1!==c||void 0===p&&void 0===h,i.autocolorscale&&(f=p*h<0?l.RdBu:p>=0?l.Reds:l.Blues,a.colorscale=f,i.reversescale&&(f=sr(f)),i.colorscale=f)},ur=re.extendFlat,cr=re.isPlainObject,pr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},hr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},fr=pr.flags.slice().concat(["clearCalc","fullReplot"]),dr=hr.flags.slice().concat("layoutReplot"),yr={traces:pr,layout:hr,traceFlags:function(){return mr(fr)},layoutFlags:function(){return mr(dr)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i0?Number(l):s;else if("string"!=typeof l)r.dtick=s;else{var u=l.charAt(0),c=l.substr(1);((c=e(c)?Number(c):0)<=0||!("date"===i&&"M"===u&&c===Math.round(c)||"log"===i&&"L"===u||"log"===i&&"D"===u&&(1===c||2===c)))&&(r.dtick=s)}var p="date"===i?re.dateTick0(r.calendar):0,h=n("tick0",p);"date"===i?r.tick0=re.cleanDate(h,p):e(h)&&"D1"!==l&&"D2"!==l?r.tick0=Number(h):r.tick0=p}else{void 0===n("tickvals")?r.tickmode="auto":n("ticktext")}},zr=function(t){return void 0!==l[t]||c(t)},Lr=function(t,r,n,i,a){var o,s=a.prefix,l=a.cLetter,u=s.slice(0,s.length-1),c=s?re.nestedProperty(t,u).get()||{}:t,p=s?re.nestedProperty(r,u).get()||{}:r,h=c[l+"min"],f=c[l+"max"],d=c.colorscale;i(s+l+"auto",!(e(h)&&e(f)&&h","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},Fr={},Nr=Or.LINE_SPACING;function jr(t,e){return t.node().getBoundingClientRect()[e]}var Vr=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;Fr.convertToTspans=function(e,r,n){var i=e.text(),a=!e.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(Vr),o=t.select(e.node().parentNode);if(!o.empty()){var s=e.attr("class")?e.attr("class").split(" ")[0]:"text";return s+="-math",o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove(),e.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),a?(r&&r._promises||[]).push(new Promise(function(r){e.style("display","none");var u=parseInt(e.node().style.fontSize,10),c={fontSize:u};!function(e,r,n){var i="math-output-"+re.randstr([],64),a=t.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=e,o.replace(qr,"\\lt ").replace(Ur,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var r=t.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())re.log("There was an error in the tex syntax.",e),n();else{var i=a.select("svg").node().getBoundingClientRect();n(a.select(".MathJax_SVG"),r,i)}a.remove()})}(a[2],c,function(t,a,c){o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove();var p=t&&t.select("svg");if(!p||!p.node())return l(),void r();var h=o.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});h.node().appendChild(p.node()),a&&a.node()&&p.node().insertBefore(a.node().cloneNode(!0),p.node().firstChild),p.attr({class:s,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var f=e.node().style.fill||"black";p.select("g").attr({fill:f,stroke:f});var d=jr(p,"width"),y=jr(p,"height"),m=+e.attr("x")-d*{start:0,middle:.5,end:1}[e.attr("text-anchor")||"start"],g=-(u||jr(e,"height"))/4;"y"===s[0]?(h.attr({transform:"rotate("+[-90,+e.attr("x"),+e.attr("y")]+") translate("+[-d/2,g-y/2]+")"}),p.attr({x:+e.attr("x"),y:+e.attr("y")})):"l"===s[0]?p.attr({x:e.attr("x"),y:g-y/2}):"a"===s[0]?p.attr({x:0,y:g}):p.attr({x:m,y:+e.attr("y")+g-y/2}),n&&n.call(e,h),r(h)})})):l(),e}function l(){o.empty()||(s=e.attr("class")+"-math",o.select("svg."+s).remove()),e.text("").style("white-space","pre"),function(e,r){r=(n=r,function(t,e){if(!t)return"";for(var r=0;r1)for(var a=1;a doesnt match end tag <"+t+">. Pretending it did match.",r),i=o[o.length-1].node}else re.log("Ignoring unexpected end tag .",r)}tn.test(r)?l():(i=e,o=[{node:e}]);for(var h=r.split($r),f=0;f|>|>)/g;var Zr={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"},Hr={sub:"0.3em",sup:"-0.6em"},Gr={sub:"-0.21em",sup:"0.42em"},Wr="\u200b",Xr=["http:","https:","mailto:","",void 0,":"],Yr=new RegExp("]*)?/?>","g"),Jr=Object.keys(Br.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:Br.entityToUnicode[t]}}),Kr=/(\r\n?|\n)/g,$r=/(<[^<>]*>)/,Qr=/<(\/?)([^ >]*)(\s+(.*))?>/i,tn=//i,en=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,rn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,nn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,an=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function on(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var sn=/(^|;)\s*color:/;function ln(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}Fr.plainText=function(t){return(t||"").replace(Yr," ")},Fr.lineCount=function(t){return t.selectAll("tspan.line").size()||1},Fr.positionText=function(e,r,n){return e.each(function(){var e=t.select(this);function i(t,r){return void 0===r?null===(r=e.attr(t))&&(e.attr(t,0),r=0):e.attr(t,r),r}var a=i("x",r),o=i("y",n);"text"===this.nodeName&&e.selectAll("tspan.line").attr({x:a,y:o})})},Fr.makeEditable=function(e,r){var n=r.gd,i=r.delegate,a=t.dispatch("edit","input","cancel"),o=i||e;if(e.style({"pointer-events":i?"none":"all"}),1!==e.size())throw new Error("boo");function s(){var i,s,u,c;i=t.select(n).select(".svg-container"),s=i.append("div"),u=e.node().style,c=parseFloat(u.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:r.fill||u.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||e.attr("data-unformatted")).call(ln(e,i,r)).on("blur",function(){n._editing=!1,e.text(this.textContent).style({opacity:1});var r,i=t.select(this).attr("class");(r=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(r).style({opacity:0});var o=this.textContent;t.select(this).transition().duration(0).remove(),t.select(document).on("mouseup",null),a.edit.call(e,o)}).on("focus",function(){var e=this;n._editing=!0,t.select(document).on("mouseup",function(){if(t.event.target===e)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===t.event.which?(n._editing=!1,e.style({opacity:1}),t.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(e,this.textContent)):(a.input.call(e,this.textContent),t.select(this).call(ln(e,i,r)))}).on("keydown",function(){13===t.event.which&&this.blur()}).call(l),e.style({opacity:0});var p,h=o.attr("class");(p=h?"."+h.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(p).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return r.immediate?s():o.on("click",s),t.rebind(e,a,"on")};var un=function(t){var r=t.marker,n=r.sizeref||1,i=r.sizemin||0,a="area"===r.sizemode?function(t){return Math.sqrt(t/n)}:function(t){return t/n};return function(t){var r=a(t/2);return e(r)&&r>0?Math.max(r,i):0}},cn={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("markers")},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return re.isPlainObject(t.marker)&&re.isArrayOrTypedArray(t.marker.size)}},pn={},hn=Or.LINE_SPACING,fn=h.DESELECTDIM,dn=pn={};dn.font=function(t,e,r,n){re.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Oe.fill,n)},dn.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},dn.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},dn.setRect=function(t,e,r,n,i){t.call(dn.setPosition,e,r).call(dn.setSize,n,i)},dn.translatePoint=function(t,r,n,i){var a=n.c2p(t.x),o=i.c2p(t.y);return!!(e(a)&&e(o)&&r.node())&&("text"===r.node().nodeName?r.attr("x",a).attr("y",o):r.attr("transform","translate("+a+","+o+")"),!0)},dn.translatePoints=function(e,r,n){e.each(function(e){var i=t.select(this);dn.translatePoint(e,i,r,n)})},dn.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},dn.hideOutsideRangePoints=function(e,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var i=r.xaxis,a=r.yaxis;e.each(function(r){var o=r[0].trace,s=o.xcalendar,l=o.ycalendar;e.selectAll(n).each(function(e){dn.hideOutsideRangePoint(e,t.select(this),i,a,s,l)})})}},dn.crispRound=function(t,r,n){return r&&e(r)?t._context.staticPlot?r:r<1?1:Math.round(r):n||0},dn.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";Oe.stroke(e,n||a.color),dn.dashLine(e,s,o)},dn.lineGroupStyle=function(e,r,n,i){e.style("fill","none").each(function(e){var a=(((e||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";t.select(this).call(Oe.stroke,n||a.color).call(dn.dashLine,s,o)})},dn.dashLine=function(t,e,r){r=+r||0,e=dn.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},dn.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},dn.singleFillStyle=function(e){var r=(((t.select(e.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&e.call(Oe.fill,r)},dn.fillGroupStyle=function(e){e.style("stroke-width",0).each(function(r){var n=t.select(this);try{n.call(Oe.fill,r[0].trace.fillcolor)}catch(t){re.error(t,e),n.remove()}})},dn.symbolNames=[],dn.symbolFuncs=[],dn.symbolNeedLines={},dn.symbolNoDot={},dn.symbolNoFill={},dn.symbolList=[],Object.keys(Dr).forEach(function(t){var e=Dr[t];dn.symbolList=dn.symbolList.concat([e.n,t,e.n+100,t+"-open"]),dn.symbolNames[e.n]=t,dn.symbolFuncs[e.n]=e.f,e.needLine&&(dn.symbolNeedLines[e.n]=!0),e.noDot?dn.symbolNoDot[e.n]=!0:dn.symbolList=dn.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(dn.symbolNoFill[e.n]=!0)});var yn=dn.symbolNames.length,mn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function gn(t,e){var r=t%100;return dn.symbolFuncs[r](e)+(t>=200?mn:"")}dn.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=dn.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=yn||t>=400?0:Math.floor(Math.max(t,0))};var vn={x1:1,x2:0,y1:0,y2:0},_n={x1:0,x2:0,y1:1,y2:0};dn.gradient=function(e,r,n,i,a,o){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([i+a+o],re.identity);l.exit().remove(),l.enter().append("radial"===i?"radialGradient":"linearGradient").each(function(){var e=t.select(this);"horizontal"===i?e.attr(vn):"vertical"===i&&e.attr(_n),e.attr("id",n);var r=s(a),l=s(o);e.append("stop").attr({offset:"0%","stop-color":Oe.tinyRGB(l),"stop-opacity":l.getAlpha()}),e.append("stop").attr({offset:"100%","stop-color":Oe.tinyRGB(r),"stop-opacity":r.getAlpha()})}),e.style({fill:"url(#"+n+")","fill-opacity":null})},dn.initGradients=function(t){var e=t._fullLayout._defs.selectAll(".gradients").data([0]);e.enter().append("g").classed("gradients",!0),e.selectAll("linearGradient,radialGradient").remove()},dn.singlePointStyle=function(t,e,r,n,i,a){var o=r.marker;!function(t,e,r,n,i,a,o,s){if(P.traceIs(r,"symbols")){var l=un(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===a.size?3:cn.isBubble(r)?l(t.ms):(a.size||6)/2,t.mrc=e;var n=dn.symbolNumber(t.mx||a.symbol)||0;return t.om=n%200>=100,gn(n,e)})}e.style("opacity",function(t){return(t.mo+1||a.opacity+1)-1});var u,c,p,h=!1;if(t.so?(p=o.outlierwidth,c=o.outliercolor,u=a.outliercolor):(p=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=i(t.mlc):re.isArrayOrTypedArray(o.color)?Oe.defaultLine:o.color,re.isArrayOrTypedArray(a.color)&&(u=Oe.defaultLine,h=!0),u="mc"in t?t.mcc=n(t.mc):a.color||"rgba(0,0,0,0)"),t.om)e.call(Oe.stroke,u).style({"stroke-width":(p||1)+"px",fill:"none"});else{e.style("stroke-width",p+"px");var f=a.gradient,d=t.mgt;if(d?h=!0:d=f&&f.type,d&&"none"!==d){var y=t.mgc;y?h=!0:y=f.color;var m="g"+s._fullLayout._uid+"-"+r.uid;h&&(m+="-"+t.i),e.call(dn.gradient,s,m,d,u,y)}else e.call(Oe.fill,u);p&&e.call(Oe.stroke,c)}}(t,e,r,n,i,o,o.line,a)},dn.pointStyle=function(e,r,n){if(e.size()){var i=r.marker,a=dn.tryColorscale(i,""),o=dn.tryColorscale(i,"line");e.each(function(e){dn.singlePointStyle(e,t.select(this),r,a,o,n)})}},dn.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},a=r.marker||{},o=n.marker||{},s=i.opacity,l=a.opacity,u=o.opacity,c=void 0!==l,p=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||p){if(!t.selected)return p?u:fn*(r?e:s);if(c)return l}};var h=a.color,f=o.color;(h||f)&&(e.colorFn=function(t){if(t.selected){if(h)return h}else if(f)return f});var d=a.size,y=o.size,m=void 0!==d,g=void 0!==y;return(m||g)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?m?d/2:e:g?y/2:e}),e},dn.selectedPointStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=dn.makeSelectedPointStyleFns(r),i=r.marker||{};e.each(function(e){var r=t.select(this),i=n.opacityFn(e);void 0!==i&&r.style("opacity",i)}),n.colorFn&&e.each(function(e){var r=t.select(this),i=n.colorFn(e);i&&Oe.fill(r,i)}),P.traceIs(r,"symbols")&&n.sizeFn&&e.each(function(e){var r=t.select(this),a=e.mx||i.symbol||0,o=n.sizeFn(e);r.attr("d",gn(dn.symbolNumber(a),o)),e.mrc2=o})}},dn.tryColorscale=function(t,e){var r=e?re.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&re.isArrayOrTypedArray(i)?Ir.makeColorScaleFunc(Ir.extractScale(n,r.cmin,r.cmax)):re.identity};var xn={start:1,end:-1,middle:0,bottom:1,top:-1};function bn(e,r,n,i){var a=t.select(e.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",s=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",l=i?i/.8+1:0,u=(Fr.lineCount(e)-1)*hn+1,c=xn[s]*l,p=.75*n+xn[o]*l+(xn[o]-1)*u*n/2;e.attr("text-anchor",s),a.attr("transform","translate("+c+","+p+")")}function wn(t,r){var n=t.ts||r.textfont.size;return e(n)&&n>0?n:0}dn.textPointStyle=function(e,r,n){e.each(function(e){var i=t.select(this),a=re.extractOption(e,r,"tx","text");if(a){var o=e.tp||r.textposition,s=wn(e,r);i.call(dn.font,e.tf||r.textfont.family,s,e.tc||r.textfont.color).text(a).call(Fr.convertToTspans,n).call(bn,o,s,e.mrc)}else i.remove()})},dn.selectedTextStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=r.selected||{},i=r.unselected||{};e.each(function(e){var a,o=t.select(this),s=e.tc||r.textfont.color,l=e.tp||r.textposition,u=wn(e,r),c=(n.textfont||{}).color,p=(i.textfont||{}).color;e.selected?c&&(a=c):p?a=p:c||(a=Oe.addOpacity(s,fn)),a&&Oe.fill(o,a),bn(o,l,u,e.mrc2||e.mrc)})}};var kn=.5;function An(e,r,n,i){var a=e[0]-r[0],o=e[1]-r[1],s=n[0]-r[0],l=n[1]-r[1],u=Math.pow(a*a+o*o,kn/2),c=Math.pow(s*s+l*l,kn/2),p=(c*c*a-u*u*s)*i,h=(c*c*o-u*u*l)*i,f=3*c*(u+c),d=3*u*(u+c);return[[t.round(r[0]+(f&&p/f),2),t.round(r[1]+(f&&h/f),2)],[t.round(r[0]-(d&&p/d),2),t.round(r[1]-(d&&h/d),2)]]}dn.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(dn.savedBBoxes={},Sn=0),n&&(dn.savedBBoxes[n]=d),Sn++,re.extendFlat({},d)},dn.setClipUrl=function(e,r){if(r){var n="#"+r,i=t.select("base");i.size()&&i.attr("href")&&(n=window.location.href.split("#")[0]+n),e.attr("clip-path","url("+n+")")}else e.attr("clip-path",null)},dn.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},dn.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},dn.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},dn.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a},dn.setPointGroupScale=function(t,e,r){var n,i,a;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",a=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(a,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var zn=/translate\([^)]*\)\s*$/;dn.setTextPointsScale=function(e,r,n){e.each(function(){var e,i=t.select(this),a=i.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(i.attr("transform")||"").match(zn);e=1===r&&1===n?[]:["translate("+o+","+s+")","scale("+r+","+n+")","translate("+-o+","+-s+")"],l&&e.push(l),i.attr("transform",e.join(" "))}})};function Ln(t,e,r,n){n=n||re.identity,Array.isArray(t)&&(e[0][r]=n(t))}var En={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},flat:function(t,e){for(var r=new Array(t.length),n=0;n=0&&r.index=a.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!oi(o))return!1;t=a[i][o]}else t=a[i]}else t=a}}return t}function oi(t){return t===Math.round(t)&&t>=0}function si(t){return function(t){Qn.crawl(t,function(t,e,r){Qn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):re.isPlainObject(t)&&(t.role="object")})}(t),function(t){Qn.crawl(t,function(t,e,r){if(!t)return;var n=t[ni];if(!n)return;delete t[ni],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),t}function li(t,e,r){var n=re.nestedProperty(t,r),i=ei({},e.layoutAttributes);i[ri]=!0,n.set(i)}function ui(t,e,r){var n=re.nestedProperty(t,r);n.set(ei(n.get()||{},e))}Qn.IS_SUBPLOT_OBJ=ri,Qn.IS_LINKED_TO_ARRAY=ni,Qn.DEPRECATED="_deprecated",Qn.UNDERSCORE_ATTRS=ii,Qn.get=function(){var t={};P.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:Wn},r={}):(e=P.modules[t]._module,r=e.basePlotModule);var n={type:null};ei(n,C),ei(n,e.attributes),r.attributes&&ei(n,r.attributes);n.type=t;var i={meta:e.meta||{},attributes:si(n)};if(e.layoutAttributes){var a={};ei(a,e.layoutAttributes),i.layoutAttributes=si(a)}return i}(e)});var e,r={};return Object.keys(P.transformsRegistry).forEach(function(t){r[t]=function(t){var e=P.transformsRegistry[t],r=ei({},e.attributes);return Object.keys(P.componentsRegistry).forEach(function(e){var n=P.componentsRegistry[e];n.schema&&n.schema.transforms&&n.schema.transforms[t]&&Object.keys(n.schema.transforms[t]).forEach(function(e){ui(r,n.schema.transforms[t][e],e)})}),{attributes:si(r)}}(t)}),{defs:{valObjects:re.valObjectMeta,metaKeys:ii.concat(["description","role","editType","impliedEdits"]),editType:{traces:yr.traces,layout:yr.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in ei(r,E),P.subplotsRegistry)if((e=P.subplotsRegistry[t]).layoutAttributes)if("cartesian"===e.name)li(r,e,"xaxis"),li(r,e,"yaxis");else{var n="subplot"===e.attr?e.name:e.attr;li(r,e,n)}for(t in r=function(t){return ti(t,{radialaxis:$n.radialaxis,angularaxis:$n.angularaxis}),ti(t,$n.layout),t}(r),P.componentsRegistry){var i=(e=P.componentsRegistry[t]).schema;if(i&&(i.subplots||i.layout)){var a=i.subplots;if(a&&a.xaxis&&!a.yaxis)for(var o in a.xaxis)delete r.yaxis[o]}else e.layoutAttributes&&ui(r,e.layoutAttributes,e.name)}return{layoutAttributes:si(r)}}(),transforms:r,frames:(e={frames:re.extendDeepAll({},Nn)},si(e),e.frames),animation:si(Fn)}},Qn.crawl=function(t,e,r,n){var i=r||0;n=n||"",Object.keys(t).forEach(function(r){var a=t[r];if(-1===ii.indexOf(r)){var o=(n?n+".":"")+r;e(a,r,t,i,o),Qn.isValObject(a)||re.isPlainObject(a)&&"impliedEdits"!==r&&Qn.crawl(a,e,i+1,o)}})},Qn.isValObject=function(t){return t&&void 0!==t.valType},Qn.findArrayAttributes=function(t){var e=[],r=[];function n(n,i,a,o){if(r=r.slice(0,o).concat([i]),n&&("data_array"===n.valType||!0===n.arrayOk)&&!("colorbar"===r[o-1]&&("ticktext"===i||"tickvals"===i))){var s=function(t){return t.join(".")}(r),l=re.nestedProperty(t,s).get();re.isArrayOrTypedArray(l)&&e.push(s)}}if(Qn.crawl(C,n),t._module&&t._module.attributes&&Qn.crawl(t._module.attributes,n),t.transforms)for(var i=t.transforms,a=0;a=t.transforms.length)return!1;n=(r=(P.transformsRegistry[t.transforms[o].type]||{}).attributes)&&r[e[2]],a=3}else if("area"===t.type)n=Wn[i];else{var s=t._module;if(s||(s=(P.modules[t.type||C.type.dflt]||{})._module),!s)return!1;if(!(n=(r=s.attributes)&&r[i])){var l=s.basePlotModule;l&&l.attributes&&(n=l.attributes[i])}n||(n=C[i])}return ai(n,e,a)},Qn.getLayoutValObject=function(t,e){return ai(function(t,e){var r,n,i,a,o=t._basePlotModules;if(o){var s;for(r=0;rn?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},pi={};function hi(t,e,r){var n,i,a,o=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=re.nestedProperty(n,e.prop).get(),(a=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&a[e.prop]!==i&&(o=!0),a[e.prop]=i,{changed:o,value:i}}function fi(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!re.isPlainObject(n))return r;i=n}return yi(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function di(t,e){var r,n,i,a,o=[];if(n=e[0],i=e[1],r=e[2],a={},"string"==typeof n)a[n]=i;else{if(!re.isPlainObject(n))return o;a=n,void 0===r&&(r=i)}return void 0===r&&(r=null),yi(a,function(e,n,i){var a;if(Array.isArray(i)){var s=Math.min(i.length,t.data.length);r&&(s=Math.min(s,r.length)),a=[];for(var l=0;l0?".":"")+i;re.isPlainObject(a)?yi(a,e,o,n+1):e(o,i,a)}})}pi.manageCommandObserver=function(t,e,r,n){var i={},a=!0;e&&e._commandObserver&&(i=e._commandObserver),i.cache||(i.cache={}),i.lookupTable={};var o=pi.hasSimpleAPICommandBindings(t,r,i.lookupTable);if(e&&e._commandObserver){if(o)return i;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,i}if(o){hi(t,o,i.cache),i.check=function(){if(a){var e=hi(t,o,i.cache);return e.changed&&n&&void 0!==i.lookupTable[e.value]&&(i.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:i.lookupTable[e.value]})).then(i.enable,i.enable)),e.changed}};for(var s=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],l=0;l=r.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=r._paper.attr("width")-7),n.attr(a);var o=n.select(".js-link-to-tool"),s=n.select(".js-link-spacer"),l=n.select(".js-sourcelinks");e._context.showSources&&e._context.showSources(e),e._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){_i.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(e,o),s.text(o.text()&&l.text()?" - ":"")}},_i.sendDataToCloud=function(e){e.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=t.select(e).append("div").attr("id","hiddenform").style("display","none"),i=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=_i.graphJson(e,!1,"keepdata"),i.node().submit(),n.remove(),e.emit("plotly_afterexport"),!1};var wi,ki=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Ai=["year","month","dayMonth","dayMonthYear"];function Ti(t,e){var r,n,i=t.trace,a=i._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},_i.cleanPlot=function(t,e,r,n){var i,a,o=n._basePlotModules||[];for(i=0;i0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,p=u.bottom+u.top,h=1-2*s,f=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};i=Math.round(h*(f.width-c)),a=Math.round(h*(f.height-p))}else{var d=l?window.getComputedStyle(t):{};i=parseFloat(d.width)||n.width,a=parseFloat(d.height)||n.height}var y=_i.layoutAttributes.width.min,m=_i.layoutAttributes.height.min;i1,v=!r.height&&Math.abs(n.height-a)>1;(v||g)&&(g&&(n.width=i),v&&(n.height=a)),t._initialAutoSize||(t._initialAutoSize={width:i,height:a}),_i.sanitizeMargins(n)},_i.supplyLayoutModuleDefaults=function(t,e,r,n){var i,a,o,s=P.componentsRegistry,l=e._basePlotModules,u=P.subplotsRegistry.cartesian;for(i in s)(o=s[i]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in l.length||l.push(u),e._has("cartesian")&&(P.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(re.subplotSort);for(a=0;a.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||_i.doAutoMargin(t)}},_i.doAutoMargin=function(t){var r=t._fullLayout;r._size||(r._size={}),r._pushmargin||(r._pushmargin={});var n=r._size,i=JSON.stringify(n),a=Math.max(r.margin.l||0,0),o=Math.max(r.margin.r||0,0),s=Math.max(r.margin.t||0,0),l=Math.max(r.margin.b||0,0),u=r._pushmargin;if(!1!==r.margin.autoexpand)for(var c in u.base={l:{val:0,size:a},r:{val:1,size:o},t:{val:1,size:s},b:{val:0,size:l}},u){var p=u[c].l||{},h=u[c].b||{},f=p.val,d=p.size,y=h.val,m=h.size;for(var g in u){if(e(d)&&u[g].r){var v=u[g].r.val,_=u[g].r.size;if(v>f){var x=(d*v+(_-r.width)*f)/(v-f),b=(_*(1-f)+(d-r.width)*(1-v))/(v-f);x>=0&&b>=0&&x+b>a+o&&(a=x,o=b)}}if(e(m)&&u[g].t){var w=u[g].t.val,k=u[g].t.size;if(w>y){var A=(m*w+(k-r.height)*y)/(w-y),T=(k*(1-y)+(m-r.height)*(1-w))/(w-y);A>=0&&T>=0&&A+T>l+s&&(l=A,s=T)}}}}if(n.l=Math.round(a),n.r=Math.round(o),n.t=Math.round(s),n.b=Math.round(l),n.p=Math.round(r.margin.pad),n.w=Math.round(r.width)-n.l-n.r,n.h=Math.round(r.height)-n.t-n.b,!r._replotting&&"{}"!==i&&i!==JSON.stringify(r._size))return P.call("plot",t)},_i.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&_i.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(re.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!re.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):re.isJSDate(t)?re.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},_i.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){p=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return P.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,s=0,l=0;function u(){return s++,function(){var r;p||++l!==s||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return P.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var h=t._fullLayout._basePlotModules,f=!1;if(r)for(o=0;o=0;a--)if(y[a].enabled){r._indexToPoints=y[a]._indexToPoints;break}n&&n.calc&&(d=n.calc(t,r))}Array.isArray(d)&&d[0]||(d=[{x:vi,y:vi}]),d[0].t||(d[0].t={}),d[0].trace=r,u[i]=d}P.getComponentMethod("fx","calc")(t)},_i.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},_i.generalUpdatePerTraceModule=function(t,e,r,n){var i,a=e.traceHash,o={};for(i=0;i0||p<0){var d={left:[-i,0],right:[i,0],top:[0,-i],bottom:[0,i]}[c.side];n.attr("transform","translate("+d+")")}}}T.call(M),k&&(w?T.on(".opacity",null):(x=0,b=!0,T.text(l).on("mouseover.opacity",function(){t.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){t.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(Fr.makeEditable,{gd:r}).on("edit",function(t){void 0!==u?P.call("restyle",r,s,t,u):P.call("relayout",r,s,t)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(M)}).on("input",function(t){this.text(t||" ").call(Fr.positionText,p.x,p.y)}));return T.classed("js-placeholder",b),d}},Li=/ [XY][0-9]* /;var Ei=r.FP_SAFE,Pi=Ri,Ii=Bi,Di=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=Ri(t),t._r=t.range.slice(),t._rl=re.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?Ri(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=re.extendFlat({},n)}},Oi=function(t,r,n){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!r)return;t._min||(t._min=[]);t._max||(t._max=[]);n||(n={});t._m||t.setScale();var i,a,o,s,l,u,c,p,h,f,d,y,m=r.length,g=n.padded||!1,v=n.tozero&&("linear"===t.type||"-"===t.type),_="log"===t.type,x=!1;function b(t){if(Array.isArray(t))return x=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=b((t._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),k=b((t._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),A=b(n.vpadplus||n.vpad),T=b(n.vpadminus||n.vpad);if(!x){if(d=1/0,y=-1/0,_)for(i=0;i0&&(d=s),s>y&&s-Ei&&(d=s),s>y&&s=x&&(s.extrapad||!g)){f=!1;break}b(i,s.val)&&s.pad<=x&&(g||!s.extrapad)&&(m.splice(a,1),a--)}if(f){var M=v&&0===i;m.push({val:i,pad:M?0:x,extrapad:!M&&g})}}}}var S=Math.min(6,m);for(i=0;i=S;i--)M(i)};function Ri(t){var e,r,n,i,a,o,s,l,u=[],c=t._min[0].val,p=t._max[0].val,h=0,f=!1,d=Bi(t);for(e=1;e0&&s>0&&l/s>h&&(a=n,o=i,h=l/s);if(c===p){var m=c-1,g=c+1;u="tozero"===t.rangemode?c<0?[m,0]:[0,g]:"nonnegative"===t.rangemode?[Math.max(0,m),Math.max(0,g)]:[m,g]}else h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(a.val>=0&&(a={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(a.val-h*d(a)<0&&(a={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),h=(o.val-a.val)/(t._length-d(a)-d(o))),u=[a.val-h*d(a),o.val+h*d(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),f&&u.reverse(),re.simpleMap(u,t.l2r||Number)}function Bi(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function Fi(t){return e(t)&&Math.abs(t)=e}var Vi=r.BADNUM,qi=function(t,r){return function(t,r){for(var n,i=0,a=0,o=Math.max(1,(t.length-1)/1e3),s=0;s2*a}(t,r)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}(t)?"category":function(t){if(!t)return!1;for(var r=0;r0)return Math.log(t)/Math.LN10;if(t<=0&&e&&r.range&&2===r.range.length){var n=r.range[0],i=r.range[1];return.5*(n+i-3*a*Math.abs(n-i))}return Xi}function s(t,n,i){var a=Hi(t,i||r.calendar);if(a===Xi){if(!e(t))return Xi;a=Hi(new Date(+t))}return a}function l(t,e,n){return Zi(t,e,n||r.calendar)}function u(t){return r._categories[Math.round(t)]}function c(t){if(r._categoriesMap){var n=r._categoriesMap[t];if(void 0!==n)return n}if(e(t))return+t}function p(n){return e(n)?t.round(r._b+r._m*n,2):Xi}function h(t){return(t-r._b)/r._m}r.c2l="log"===r.type?o:Gi,r.l2c="log"===r.type?Yi:Gi,r.l2p=p,r.p2l=h,r.c2p="log"===r.type?function(t,e){return p(o(t,e))}:p,r.p2c="log"===r.type?function(t){return Yi(h(t))}:h,-1!==["linear","-"].indexOf(r.type)?(r.d2r=r.r2d=r.d2c=r.r2c=r.d2l=r.r2l=Ui,r.c2d=r.c2r=r.l2d=r.l2r=Gi,r.d2p=r.r2p=function(t){return r.l2p(Ui(t))},r.p2d=r.p2r=h,r.cleanPos=Gi):"log"===r.type?(r.d2r=r.d2l=function(t,e){return o(Ui(t),e)},r.r2d=r.r2c=function(t){return Yi(Ui(t))},r.d2c=r.r2l=Ui,r.c2d=r.l2r=Gi,r.c2r=o,r.l2d=Yi,r.d2p=function(t,e){return r.l2p(r.d2r(t,e))},r.p2d=function(t){return Yi(h(t))},r.r2p=function(t){return r.l2p(Ui(t))},r.p2r=h,r.cleanPos=Gi):"date"===r.type?(r.d2r=r.r2d=re.identity,r.d2c=r.r2c=r.d2l=r.r2l=s,r.c2d=r.c2r=r.l2d=r.l2r=l,r.d2p=r.r2p=function(t,e,n){return r.l2p(s(t,0,n))},r.p2d=r.p2r=function(t,e,r){return l(h(t),e,r)},r.cleanPos=function(t){return re.cleanDate(t,Xi,r.calendar)}):"category"===r.type&&(r.d2c=r.d2l=function(t){if(null!==t&&void 0!==t){if(void 0===r._categoriesMap&&(r._categoriesMap={}),void 0!==r._categoriesMap[t])return r._categoriesMap[t];r._categories.push(t);var e=r._categories.length-1;return r._categoriesMap[t]=e,e}return Xi},r.r2d=r.c2d=r.l2d=u,r.d2r=r.d2l_noadd=c,r.r2c=function(t){var e=c(t);return void 0!==e?e:r.fraction2r(.5)},r.l2r=r.c2r=Gi,r.r2l=c,r.d2p=function(t){return r.l2p(r.r2c(t))},r.p2d=function(t){return u(h(t))},r.r2p=r.d2p,r.p2r=h,r.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Gi(t)}),r.fraction2r=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return r.l2r(e+t*(n-e))},r.r2fraction=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return(r.r2l(t)-e)/(n-e)},r.cleanRange=function(t,n){n||(n={}),t||(t="range");var a,o,s=re.nestedProperty(r,t).get();if(o=(o="date"===r.type?re.dfltRange(r.calendar):"y"===i?Ie.DFLTRANGEY:n.dfltRange||Ie.DFLTRANGEX).slice(),s&&2===s.length)for("date"===r.type&&(s[0]=re.cleanDate(s[0],Xi,r.calendar),s[1]=re.cleanDate(s[1],Xi,r.calendar)),a=0;a<2;a++)if("date"===r.type){if(!re.isDateTime(s[a],r.calendar)){r[t]=o;break}if(r.r2l(s[0])===r.r2l(s[1])){var l=re.constrain(r.r2l(s[0]),re.MIN_MS+1e3,re.MAX_MS-1e3);s[0]=r.l2r(l-1e3),s[1]=r.l2r(l+1e3);break}}else{if(!e(s[a])){if(!e(s[1-a])){r[t]=o;break}s[a]=s[1-a]*(a?10:.1)}if(s[a]<-Wi?s[a]=-Wi:s[a]>Wi&&(s[a]=Wi),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else re.nestedProperty(r,t).set(o)},r.setScale=function(t){var e=n._size;if(r._categories||(r._categories=[]),r._categoriesMap||(r._categoriesMap={}),r.overlaying){var a=ci.getFromId({_fullLayout:n},r.overlaying);r.domain=a.domain}var o=t&&r._r?"_r":"range",s=r.calendar;r.cleanRange(o);var l=r.r2l(r[o][0],s),u=r.r2l(r[o][1],s);if("y"===i?(r._offset=e.t+(1-r.domain[1])*e.h,r._length=e.h*(r.domain[1]-r.domain[0]),r._m=r._length/(l-u),r._b=-r._m*u):(r._offset=e.l+r.domain[0]*e.w,r._length=e.w*(r.domain[1]-r.domain[0]),r._m=r._length/(u-l),r._b=-r._m*l),!isFinite(r._m)||!isFinite(r._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},r.makeCalcdata=function(t,e){var n,i,a,o,s=r.type,l="date"===s&&t[e+"calendar"];if(e in t){if(n=t[e],o=t._length||n.length,re.isTypedArray(n)&&("linear"===s||"log"===s)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(i=new Array(o),a=0;a=r.r2l(r.range[0])&&n<=r.r2l(r.range[1])},r.clearCalc=function(){r._min=[],r._max=[],r._categories=(r._initialCategories||[]).slice(),r._categoriesMap={};for(var t=0;t2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},la.saveRangeInitial=function(t,e){for(var r=la.list(t,"",!0),n=!1,i=0;i.3*h||c(i)||c(a))){var f=n.dtick/2;t+=t+f.8){var o=Number(r.substr(1));a.exactYears>.8&&o%12==0?t=la.tickIncrement(t,"M6","reverse")+1.5*ta:a.exactMonths>.8?t=la.tickIncrement(t,"M1","reverse")+15.5*ta:t-=ta/2;var s=la.tickIncrement(t,r);if(s<=n)return s}return t}(d,t,s.dtick,l,a)),f=d,0;f<=u;)f=la.tickIncrement(f,s.dtick,!1,a),0;return{start:r.c2r(d,0,a),end:r.c2r(f,0,a),size:s.dtick,_dataSpan:u-l}},la.prepTicks=function(t){var e=re.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=re.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),la.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),xa(t)},la.calcTicks=function(t){la.prepTicks(t);var e=re.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),o=re.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],l=1.0001*o[1]-1e-4*o[0],u=Math.min(s,l),c=Math.max(s,l),p=0;Array.isArray(i)||(i=[]);var h="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:l<=n)&&!(a.length>s||l===o);l=la.tickIncrement(l,t.dtick,i,t.calendar))o=l,a.push(l);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(a.length),c=0;c10||"01-01"!==i.substr(5)?t._tickround="d":t._tickround=+r.substr(1)%12==0?"y":"m";else if(r>=ta&&a<=10||r>=15*ta)t._tickround="d";else if(r>=ra&&a<=16||r>=ea)t._tickround="M";else if(r>=na&&a<=19||r>=ra)t._tickround="S";else{var o=t.l2r(n+r).replace(/^-/,"").length;t._tickround=Math.max(a,o)-20}}else if(e(r)||"L"===r.charAt(0)){var s=t.range.map(t.r2d||Number);e(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),u=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(u)>3&&(ka(t.exponentformat)&&!Aa(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function ba(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}la.autoTicks=function(t,r){var n;function i(t){return Math.pow(t,Math.floor(Math.log(r)/Math.LN10))}if("date"===t.type){t.tick0=re.dateTick0(t.calendar);var a=2*r;a>$i?(r/=$i,n=i(10),t.dtick="M"+12*_a(r,n,ha)):a>Qi?(r/=Qi,t.dtick="M"+_a(r,1,fa)):a>ta?(t.dtick=_a(r,ta,ya),t.tick0=re.dateTick0(t.calendar,!0)):a>ea?t.dtick=_a(r,ea,fa):a>ra?t.dtick=_a(r,ra,da):a>na?t.dtick=_a(r,na,da):(n=i(10),t.dtick=_a(r,n,ha))}else if("log"===t.type){t.tick0=0;var o=re.simpleMap(t.range,t.r2l);if(r>.7)t.dtick=Math.ceil(r);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/r);r=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,n=i(10),t.dtick="L"+_a(r,n,ha)}else t.dtick=r>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(r,1))):"angular"===t._id?(t.tick0=0,n=1,t.dtick=_a(r,n,va)):(t.tick0=0,n=i(10),t.dtick=_a(r,n,ha));if(0===t.dtick&&(t.dtick=1),!e(t.dtick)&&"string"!=typeof t.dtick){var l=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(l)}},la.tickIncrement=function(r,n,i,a){var o=i?-1:1;if(e(n))return r+o*n;var s=n.charAt(0),l=o*Number(n.substr(1));if("M"===s)return re.incrementMonth(r,l,a);if("L"===s)return Math.log(Math.pow(10,r)+l)/Math.LN10;if("D"===s){var u="D2"===n?ga:ma,c=r+.01*o,p=re.roundUp(re.mod(c,1),u,i);return Math.floor(c)+Math.log(t.round(Math.pow(10,p),1))/Math.LN10}throw"unrecognized dtick "+String(n)},la.tickFirst=function(r){var n=r.r2l||Number,i=re.simpleMap(r.range,n),a=i[1]"+s,t._prevDateHead=s));r.text=l}(t,o,n,l):"log"===t.type?function(t,r,n,i,a){var o=t.dtick,s=r.x,l=t.tickformat;"never"===a&&(a="");!i||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(l||"string"==typeof o&&"L"===o.charAt(0))r.text=Ta(Math.pow(10,s),t,a,i);else if(e(o)||"D"===o.charAt(0)&&re.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||ka(t.exponentformat)&&Aa(u)?(r.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+ia+-u+"",r.fontSize*=1.25):(r.text=Ta(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(r.dy-=r.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);r.text=String(Math.round(Math.pow(10,re.mod(s,1)))),r.fontSize*=.75}if("D1"===t.dtick){var c=String(r.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?r.dx-=r.fontSize/4:(r.dy+=r.fontSize/2,r.dx+=(t.range[1]>t.range[0]?1:-1)*r.fontSize*(s<0?.5:.25)))}}(t,o,0,l,i):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=Ta(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(o[1]>=100)e.text=Ta(re.deg2rad(e.x),t,i,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),s&&(e.text=ia+e.text)}}}}(t,o,n,l,i):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=Ta(e.x,t,i,n)}(t,o,0,l,i),t.tickprefix&&!h(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!h(t.showticksuffix)&&(o.text+=t.ticksuffix),o},la.hoverLabelText=function(t,e,r){if(r!==aa&&r!==e)return la.hoverLabelText(t,e)+" - "+la.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=la.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":ia+i:i};var wa=["f","p","n","\u03bc","m","","k","M","G","T"];function ka(t){return"SI"===t||"B"===t}function Aa(t){return t>14||t<-15}function Ta(t,r,n,i){var a=t<0,o=r._tickround,s=n||r.exponentformat||"B",l=r._tickexponent,u=la.getTickFormat(r),c=r.separatethousands;if(i){var p={exponentformat:s,dtick:"none"===r.showexponent?r.dtick:e(t)&&Math.abs(t)||1,range:"none"===r.showexponent?r.range.map(r.r2d):[0,t||1]};xa(p),o=(Number(p._tickround)||0)+4,l=p._tickexponent,r.hoverformat&&(u=r.hoverformat)}if(u)return r._numFormat(u)(t).replace(/-/g,ia);var h,f=Math.pow(10,-o)/2;if("none"===s&&(l=0),(t=Math.abs(t))"+h+"":"B"===s&&9===l?t+="B":ka(s)&&(t+=wa[l/3+5]));return a?ia+t:t}function Ma(t,e){for(var r=0;r=0,a=u(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=a(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n-1&&s.length>d&&(s=d>3?s.substr(0,d-3)+"...":s.substr(0,d))}void 0!==e.extraText&&(l+=e.extraText),void 0!==e.zLabel?(void 0!==e.xLabel&&(l+="x: "+e.xLabel+"
"),void 0!==e.yLabel&&(l+="y: "+e.yLabel+"
"),l+=(l?"z: ":"")+e.zLabel):w&&e[i+"Label"]===m?l=e[("x"===i?"y":"x")+"Label"]||"":void 0===e.xLabel?void 0!==e.yLabel&&(l=e.yLabel):l=void 0===e.yLabel?e.xLabel:"("+e.xLabel+", "+e.yLabel+")",e.text&&!Array.isArray(e.text)&&(l+=(l?"
":"")+e.text),""===l&&(""===s&&r.remove(),l=s);var y=r.select("text.nums").call(pn.font,e.fontFamily||c,e.fontSize||p,e.fontColor||f).text(l).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),g=r.select("text.name"),v=0;s&&s!==l?(g.call(pn.font,e.fontFamily||c,e.fontSize||p,h).text(s).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),v=g.node().getBoundingClientRect().width+2*Ra):(g.remove(),r.select("rect").remove()),r.select("path").style({fill:h,stroke:f});var k,A,T=y.node().getBoundingClientRect(),M=e.xa._offset+(e.x0+e.x1)/2,S=e.ya._offset+(e.y0+e.y1)/2,C=Math.abs(e.x1-e.x0),z=Math.abs(e.y1-e.y0),L=T.width+Oa+Ra+v;e.ty0=_-T.top,e.bx=T.width+2*Ra,e.by=T.height+2*Ra,e.anchor="start",e.txwidth=T.width,e.tx2width=v,e.offset=0,a?(e.pos=M,k=S+z/2+L<=b,A=S-z/2-L>=0,"top"!==e.idealAlign&&k||!A?k?(S+=z/2,e.anchor="start"):e.anchor="middle":(S-=z/2,e.anchor="end")):(e.pos=S,k=M+C/2+L<=x,A=M-C/2-L>=0,"left"!==e.idealAlign&&k||!A?k?(M+=C/2,e.anchor="start"):e.anchor="middle":(M-=C/2,e.anchor="end")),y.attr("text-anchor",e.anchor),v&&g.attr("text-anchor",e.anchor),r.attr("transform","translate("+M+","+S+")"+(a?"rotate("+La+")":""))}),C}function Fa(e,r){e.each(function(e){var n=t.select(this);if(e.del)n.remove();else{var i="end"===e.anchor?-1:1,a=n.select("text.nums"),o={start:1,end:-1,middle:0}[e.anchor],s=o*(Oa+Ra),l=s+o*(e.txwidth+Ra),u=0,c=e.offset;"middle"===e.anchor&&(s-=e.tx2width/2,l+=e.txwidth/2+Ra),r&&(c*=-Da,u=e.offset*Ia),n.select("path").attr("d","middle"===e.anchor?"M-"+(e.bx/2+e.tx2width/2)+","+(c-e.by/2)+"h"+e.bx+"v"+e.by+"h-"+e.bx+"Z":"M0,0L"+(i*Oa+u)+","+(Oa+c)+"v"+(e.by/2-Oa)+"h"+i*e.bx+"v-"+e.by+"H"+(i*Oa+u)+"V"+(c-Oa)+"Z"),a.call(Fr.positionText,s+u,c+e.ty0-e.by/2+Ra),e.tx2width&&(n.select("text.name").call(Fr.positionText,l+o*Ra+u,c+e.ty0-e.by/2+Ra),n.select("rect").call(pn.setRect,l+(o-1)*e.tx2width/2+u,c-e.by/2-1,e.tx2width,e.by+2))}})}function Na(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return re.castOption(i,r,t)||re.extractOption({},n,"",e)}:function(t,e){return re.extractOption(a,n,t,e)};function s(e,r,n){var i=o(r,n);i&&(t[e]=i)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=re.constrain(t.x0,0,t.xa._length),t.x1=re.constrain(t.x1,0,t.xa._length),t.y0=re.constrain(t.y0,0,t.ya._length),t.y1=re.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:Ki.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:Ki.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var l=Ki.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+l+" / -"+Ki.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+l,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=Ki.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+Ki.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function ja(t,e){var r,n,i=e.container,a=e.fullLayout,o=e.event,l=!!t.hLinePoint,u=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),u||l){var c=Oe.combine(a.plot_bgcolor,a.paper_bgcolor);if(l){var p,h,f=t.hLinePoint;r=f&&f.xa,"cursor"===(n=f&&f.ya).spikesnap?(p=o.pointerX,h=o.pointerY):(p=r._offset+f.x,h=n._offset+f.y);var d,y,m=s.readability(f.color,c)<1.5?Oe.contrast(c):f.color,g=n.spikemode,v=n.spikethickness,_=n.spikecolor||m,x=n._boundingBox,b=(x.left+x.right)/2U.width||V<0||V>U.height)return rr.unhoverRaw(r,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(b="xval"in n?En.flat(o,n.xval):En.p2c(f,j),w="yval"in n?En.flat(o,n.yval):En.p2c(d,V),!e(b[0])||!e(w[0]))return re.warn("Fx.hover failed",n,r),rr.unhoverRaw(r,n)}var Z=1/0;for(A=0;AD&&(B.splice(0,D),Z=B[0].distance),c&&0!==R&&0===B.length){I.distance=R,I.index=!1;var Y=M._module.hoverPoints(I,L,E,"closest",s._hoverlayer);if(Y&&(Y=Y.filter(function(t){return t.spikeDistance<=R})),Y&&Y.length){var J,K=Y.filter(function(t){return t.xa.showspikes});if(K.length){var $=K[0];e($.x0)&&e($.y0)&&(J=rt($),(!N.vLinePoint||N.vLinePoint.spikeDistance>J.spikeDistance)&&(N.vLinePoint=J))}var Q=Y.filter(function(t){return t.ya.showspikes});if(Q.length){var tt=Q[0];e(tt.x0)&&e(tt.y0)&&(J=rt(tt),(!N.hLinePoint||N.hLinePoint.spikeDistance>J.spikeDistance)&&(N.hLinePoint=J))}}}}function et(t,e){for(var r,n=null,i=1/0,a=0;a1,yt=Oe.combine(s.plot_bgcolor||Oe.background,s.paper_bgcolor),mt={hovermode:x,rotateLabels:dt,bgColor:yt,container:s._hoverlayer,outerContainer:s._paperdiv,commonLabelOpts:s.hoverlabel,hoverdistance:s.hoverdistance},gt=Ba(B,mt,r);if(function(t,e,r){var n,i,a,o,s,l,u,c=0,p=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?Pa:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function h(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&y.pmin===m.pmin&&y.pmax===m.pmax){for(s=d.length-1;s>=0;s--)d[s].dp+=i;for(f.push.apply(f,d),p.splice(o+1,1),u=0,s=f.length-1;s>=0;s--)u+=f[s].dp;for(a=u/f.length,s=f.length-1;s>=0;s--)f[s].dp-=a;n=!1}else o++}p.forEach(h)}for(o=p.length-1;o>=0;o--){var g=p[o];for(s=g.length-1;s>=0;s--){var v=g[s],_=t[v.i];_.offset=v.dp,_.del=v.del}}}(B,dt?"xa":"ya",s),Fa(gt,dt),n.target&&n.target.tagName){var vt=P.getComponentMethod("annotations","hasClickToShow")(r,ht);Bn(t.select(n.target),vt?"pointer":"")}if(!n.target||a||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}(r,0,pt))return;pt&&r.emit("plotly_unhover",{event:n,points:pt});r.emit("plotly_hover",{event:n,points:r._hoverdata,xaxes:f,yaxes:d,xvals:b,yvals:w})}(r,n,i,a)})},za.loneHover=function(e,r){var n={color:e.color||Oe.defaultLine,x0:e.x0||e.x||0,x1:e.x1||e.x||0,y0:e.y0||e.y||0,y1:e.y1||e.y||0,xLabel:e.xLabel,yLabel:e.yLabel,zLabel:e.zLabel,text:e.text,name:e.name,idealAlign:e.idealAlign,borderColor:e.borderColor,fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},i=t.select(r.container),a=r.outerContainer?t.select(r.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||Oe.background,container:i,outerContainer:a},s=Ba([n],o,r.gd);return Fa(s,o.rotateLabels),s.node()};var qa=za.hover,Ua=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),re.coerceFont(r,"hoverlabel.font",n.font)},Za=M({editType:"none"});Za.family.dflt=Ge.HOVERFONT,Za.size.dflt=Ge.HOVERFONTSIZE;var Ha={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Za,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var Ga={moduleType:"component",name:"fx",constants:Ge,schema:{layout:Ha},attributes:S,layoutAttributes:Ha,supplyLayoutGlobalDefaults:function(t,e){Ua(0,0,function(r,n){return re.coerce(t,e,Ha,r,n)})},supplyDefaults:function(t,e,r,n){Ua(0,0,function(r,n){return re.coerce(t,e,S,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return re.coerce(t,e,Ha,r,n)}var i;n("dragmode"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}r._w=C,r._h=z;for(var D=!1,O=["x","y"],R=0;R1)&&(Z===U?((Q=H.r2fraction(r["a"+q]))<0||Q>1)&&(D=!0):D=!0,D))continue;B=H._offset+H.r2p(r[q]),j=.5}else"x"===q?(N=r[q],B=c.l+c.w*N):(N=1-r[q],B=c.t+c.h*N),j=r.showarrow?.5:N;if(r.showarrow){$.head=B;var tt=r["a"+q];V=W*I(.5,r.xanchor)-X*I(.5,r.yanchor),Z===U?($.tail=H._offset+H.r2p(tt),F=V):($.tail=B+tt,F=V+tt),$.text=$.tail+V;var et=u["x"===q?"width":"height"];if("paper"===U&&($.head=re.constrain($.head,1,et-1)),"pixel"===Z){var rt=-Math.max($.tail-3,$.text),nt=Math.min($.tail+3,$.text)-et;rt>0?($.tail+=rt,$.text+=rt):nt>0&&($.tail-=nt,$.text-=nt)}$.tail+=K,$.head+=K}else F=V=Y*I(j,J),$.text=B+V;$.text+=K,V+=K,F+=K,r["_"+q+"padplus"]=Y/2+F,r["_"+q+"padminus"]=Y/2-F,r["_"+q+"size"]=Y,r["_"+q+"shift"]=V}if(D)_.remove();else{var it=0,at=0;if("left"!==r.align&&(it=(C-b)*("center"===r.align?.5:1)),"top"!==r.valign&&(at=(z-M)*("middle"===r.valign?.5:1)),s)n.select("svg").attr({x:w+it-1,y:w+at}).call(pn.setClipUrl,A?h:null);else{var ot=w+at-v.top,st=w+it-v.left;S.call(Fr.positionText,st,ot).call(pn.setClipUrl,A?h:null)}T.select("rect").call(pn.setRect,w,w,C,z),k.call(pn.setRect,x/2,x/2,L-x,E-x),_.call(pn.setTranslate,Math.round(f.x.text-L/2),Math.round(f.y.text-E/2)),m.attr({transform:"rotate("+d+","+f.x.text+","+f.y.text+")"});var lt,ut,ct=function(t,n){y.selectAll(".annotation-arrow-g").remove();var s=f.x.head,u=f.y.head,h=f.x.tail+t,g=f.y.tail+n,v=f.x.text+t,x=f.y.text+n,b=re.rotationXYMatrix(d,v,x),w=re.apply2DTransform(b),A=re.apply2DTransform2(b),T=+k.attr("width"),M=+k.attr("height"),S=v-.5*T,C=S+T,z=x-.5*M,L=z+M,E=[[S,z,S,L],[S,L,C,L],[C,L,C,z],[C,z,S,z]].map(A);if(!E.reduce(function(t,e){return t^!!re.segmentsIntersect(s,u,s+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){E.forEach(function(t){var e=re.segmentsIntersect(h,g,s,u,t[0],t[1],t[2],t[3]);e&&(h=e.x,g=e.y)});var I=r.arrowwidth,D=r.arrowcolor,O=r.arrowside,R=y.append("g").style({opacity:Oe.opacity(D)}).classed("annotation-arrow-g",!0),B=R.append("path").attr("d","M"+h+","+g+"L"+s+","+u).style("stroke-width",I+"px").call(Oe.stroke,Oe.rgb(D));if(je(B,O,r),p.annotationPosition&&B.node().parentNode&&!i){var F=s,N=u;if(r.standoff){var j=Math.sqrt(Math.pow(s-h,2)+Math.pow(u-g,2));F+=r.standoff*(h-s)/j,N+=r.standoff*(g-u)/j}var V,q,U,Z=R.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(h-F)+","+(g-N),transform:"translate("+F+","+N+")"}).style("stroke-width",I+6+"px").call(Oe.stroke,"rgba(0,0,0,0)").call(Oe.fill,"rgba(0,0,0,0)");rr.init({element:Z.node(),gd:e,prepFn:function(){var t=pn.getTranslate(_);q=t.x,U=t.y,V={},a&&a.autorange&&(V[a._name+".autorange"]=!0),o&&o.autorange&&(V[o._name+".autorange"]=!0)},moveFn:function(t,e){var n=w(q,U),i=n[0]+t,s=n[1]+e;_.call(pn.setTranslate,i,s),V[l+".x"]=a?a.p2r(a.r2p(r.x)+t):r.x+t/c.w,V[l+".y"]=o?o.p2r(o.r2p(r.y)+e):r.y-e/c.h,r.axref===r.xref&&(V[l+".ax"]=a.p2r(a.r2p(r.ax)+t)),r.ayref===r.yref&&(V[l+".ay"]=o.p2r(o.r2p(r.ay)+e)),R.attr("transform","translate("+t+","+e+")"),m.attr({transform:"rotate("+d+","+i+","+s+")"})},doneFn:function(){P.call("relayout",e,V);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}};if(r.showarrow&&ct(0,0),g)rr.init({element:_.node(),gd:e,prepFn:function(){ut=m.attr("transform"),lt={}},moveFn:function(t,e){var n="pointer";if(r.showarrow)r.axref===r.xref?lt[l+".ax"]=a.p2r(a.r2p(r.ax)+t):lt[l+".ax"]=r.ax+t,r.ayref===r.yref?lt[l+".ay"]=o.p2r(o.r2p(r.ay)+e):lt[l+".ay"]=r.ay+e,ct(t,e);else{if(i)return;if(a)lt[l+".x"]=a.p2r(a.r2p(r.x)+t);else{var s=r._xsize/c.w,u=r.x+(r._xshift-r.xshift)/c.w-s/2;lt[l+".x"]=rr.align(u+t/c.w,s,0,1,r.xanchor)}if(o)lt[l+".y"]=o.p2r(o.r2p(r.y)+e);else{var p=r._ysize/c.h,h=r.y-(r._yshift+r.yshift)/c.h-p/2;lt[l+".y"]=rr.align(h-e/c.h,p,0,1,r.yanchor)}a&&o||(n=rr.getCursor(a?.5:lt[l+".x"],o?.5:lt[l+".y"],r.xanchor,r.yanchor))}m.attr({transform:"translate("+t+","+e+")"+ut}),On(_,n)},doneFn:function(){On(_),P.call("relayout",e,lt);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}}var Ja=Wa.draw;function Ka(t){var e=t._fullLayout;re.filterVisible(e.annotations).forEach(function(e){var r,n,i,a,o=Ki.getFromId(t,e.xref),s=Ki.getFromId(t,e.yref),l=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=l+e.xshift,n=l-e.xshift,i=u+e.xshift,a=u-e.xshift,e.axref===e.xref?(Ki.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),Ki.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,a)})):(i=e.ax?i+e.ax:i,a=e.ax?a-e.ax:a,Ki.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,a)}))),s&&s.autorange&&(r=l-e.yshift,n=l+e.yshift,i=u-e.yshift,a=u+e.yshift,e.ayref===e.yref?(Ki.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),Ki.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,a)})):(i=e.ay?i+e.ay:i,a=e.ay?a-e.ay:a,Ki.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,a)})))})}var $a={hasClickToShow:function(t,e){var r=Qa(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=Qa(t,e),i=n.on,a=n.off.concat(n.explicitOff),o={};if(!i.length&&!a.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+i+'"]').remove():(a._pdata=co(t.glplot.cameraParams,[e.xaxis.r2l(a.x)*r[0],e.yaxis.r2l(a.y)*r[1],e.zaxis.r2l(a.z)*r[2]]),po(t.graphDiv,a,i,t.id,a._xa,a._ya))}}};var yo={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},mo=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+n[e],a=+i[e];return isNaN(r)&&isNaN(a)?[NaN,NaN]:[a||0,r||0]}}var a=go(e,t.value),o=go(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=a(t);return[e,e]}:function(t){return[o(t),a(t)]}};function go(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var vo=function(t){for(var e=t.calcdata,r=0;r0;r.each(function(r){var l,u=r[0].trace,c=u.error_x||{},p=u.error_y||{};u.ids&&(l=function(t){return t.id});var h=cn.hasMarkers(u)&&u.marker.maxdisplayed>0;p.visible||c.visible||(r=[]);var f=t.select(this).selectAll("g.errorbar").data(r,l);if(f.exit().remove(),r.length){c.visible||f.selectAll("path.xerror").remove(),p.visible||f.selectAll("path.yerror").remove(),f.style("opacity",1);var d=f.enter().append("g").classed("errorbar",!0);s&&d.style("opacity",0).transition().duration(i.duration).style("opacity",1),pn.setClipUrl(f,n.layerClipId),f.each(function(r){var n=t.select(this),l=function(t,r,n){var i={x:r.c2p(t.x),y:n.c2p(t.y)};return void 0!==t.yh&&(i.yh=n.c2p(t.yh),i.ys=n.c2p(t.ys),e(i.ys)||(i.noYS=!0,i.ys=n.c2p(t.ys,!0))),void 0!==t.xh&&(i.xh=r.c2p(t.xh),i.xs=r.c2p(t.xs),e(i.xs)||(i.noXS=!0,i.xs=r.c2p(t.xs,!0))),i}(r,a,o);if(!h||r.vis){var u,f=n.select("path.yerror");if(p.visible&&e(l.x)&&e(l.yh)&&e(l.ys)){var d=p.width;u="M"+(l.x-d)+","+l.yh+"h"+2*d+"m-"+d+",0V"+l.ys,l.noYS||(u+="m-"+d+",0h"+2*d),f.size()?s&&(f=f.transition().duration(i.duration).ease(i.easing)):f=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),f.attr("d",u)}else f.remove();var y=n.select("path.xerror");if(c.visible&&e(l.y)&&e(l.xh)&&e(l.xs)){var m=(c.copy_ystyle?p:c).width;u="M"+l.xh+","+(l.y-m)+"v"+2*m+"m0,-"+m+"H"+l.xs,l.noXS||(u+="m0,-"+m+"v"+2*m),y.size()?s&&(y=y.transition().duration(i.duration).ease(i.easing)):y=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),y.attr("d",u)}else y.remove()}})}})},style:function(e){e.each(function(e){var r=e[0].trace,n=r.error_y||{},i=r.error_x||{},a=t.select(this);a.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(Oe.stroke,n.color),i.copy_ystyle&&(i=n),a.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(Oe.stroke,i.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var Ao={},To=g.extendFlat;Ao.attributes=function(t,e){t=t||{},e=e||{};var r={valType:"info_array",editType:t.editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},n=(t.name&&t.name,t.trace,e.description&&e.description,{x:To({},r,{}),y:To({},r,{}),editType:t.editType});return t.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:t.editType},n.column={valType:"integer",min:0,dflt:0,editType:t.editType}),n},Ao.defaults=function(t,e,r,n){var i=n&&n.x||[0,1],a=n&&n.y||[0,1],o=e.grid;if(o){var s=r("domain.column");void 0!==s&&(s1){a||o||s||"independent"===h("pattern")&&(a=!0),l._hasSubplotGrid=a;var p="top to bottom"===h("roworder");l._domains={x:Lo("x",h,a?.2:.1,c),y:Lo("y",h,a?.3:.1,u,p)}}}function h(t,e){return re.coerce(r,l,zo,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,a,o,s,l,u,c=t.grid,p=e._subplots,h=r._hasSubplotGrid,f=r.rows,d=r.columns,y="independent"===r.pattern,m=r._axisMap={};if(h){var g=c.subplots||[];l=r.subplots=new Array(f);var v=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},No={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},jo=!0,Vo=function(t,e,r){if(!e._dragged&&!e._editing){var n,i,a,o,s,l=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,p=u.trace,h=p.legendgroup,f={},d=[],y=[],m=[];if(1===r&&jo&&e.data&&e._context.showTips?(re.notifier(re._(e,"Double-click on legend to isolate one trace"),"long"),jo=!1):jo=!1,P.traceIs(p,"pie")){var g=u.label,v=l.indexOf(g);1===r?-1===v?l.push(g):l.splice(v,1):2===r&&(l=[],e.calcdata[0].forEach(function(t){g!==t.label&&l.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===l.length&&-1===v&&(l=[])),P.call("relayout",e,"hiddenlabels",l)}else{var _,x=h&&h.length,b=[];if(x)for(n=0;nr[1])return r[1]}return i}function p(t){return t[0]}if(s||l||u){var h={},f={};s&&(h.mc=c("marker.color",p),h.mo=c("marker.opacity",re.mean,[.2,1]),h.ms=c("marker.size",re.mean,[2,16]),h.mlc=c("marker.line.color",p),h.mlw=c("marker.line.width",re.mean,[0,5]),f.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(f.line={width:c("line.width",p,[0,10])}),l&&(h.tx="Aa",h.tp=c("textposition",p),h.ts=10,h.tc=c("textfont.color",p),h.tf=c("textfont.family",p)),n=[re.minExtend(a,h)],i=re.minExtend(o,f)}var d=t.select(this).select("g.legendpoints"),y=d.selectAll("path.scatterpts").data(s?n:[]);y.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),y.exit().remove(),y.call(pn.pointStyle,i,r),s&&(n[0].mrc=3);var m=d.selectAll("g.pointtext").data(l?n:[]);m.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),m.exit().remove(),m.selectAll("text").call(pn.textPointStyle,i,r)})},Go=Or.LINE_SPACING,Wo=Or.FROM_TL,Xo=Or.FROM_BR,Yo=h.DBLCLICKDELAY;function Jo(t,e){var r=t.data()[0][0],n=e._fullLayout,i=r.trace,a=P.traceIs(i,"pie"),o=i.index,s=a?r.label:i.name,l=t.selectAll("text.legendtext").data([0]);function u(r){Fr.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*Go;if(o){var l=pn.bBox(o);n=l.height,i=l.width,pn.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),c=Fr.lineCount(u),p=u.node();n=s*c,i=p?pn.bBox(p).width:0;var h=s*(.3+(1-c)/2);Fr.positionText(u,40,h)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}l.enter().append("text").classed("legendtext",!0),l.attr("text-anchor","start").classed("user-select-none",!0).call(pn.font,n.legend.font).text(s),e._context.edits.legendText&&!a?l.call(Fr.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n,i=t;this.text()||(t=" ");var a=r.trace._fullInput||{},s={};if(-1!==["ohlc","candlestick"].indexOf(a.type))s[(n=r.trace.transforms)[n.length-1].direction+".name"]=t;else if(P.hasTransform(a,"groupby")){var l=P.getTransformIndices(a,"groupby"),c=l[l.length-1],p=re.keyedContainer(a,"transforms["+c+"].styles","target","value.name");""===i?p.remove(r.trace._group):p.set(r.trace._group,t),s=p.constructUpdate()}else s.name=t;return P.call("restyle",e,s,o)}):u(l)}function Ko(t,e){var r,n=1,i=t.selectAll("rect").data([0]);i.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(Oe.fill,"rgba(0,0,0,0)"),i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimeYo&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Vo(t,e,n)},Yo):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,Vo(t,e,n))}})}function $o(e,r,n){var i=e._fullLayout,a=i.legend,o=a.borderwidth,s=Bo.isGrouped(a),l=0;if(a._width=0,a._height=0,Bo.isVertical(a))s&&r.each(function(t,e){pn.setTranslate(this,0,e*a.tracegroupgap)}),n.each(function(t){var e=t[0],r=e.height,n=e.width;pn.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],c=r.data(),p=0,h=c.length;po+x-b,n.each(function(t){var e=t[0],r=y?40+t[0].width:v;o+_+b+r>i.width-(i.margin.r+i.margin.l)&&(_=0,m+=g,a._height=a._height+g,g=0),pn.setTranslate(this,o+_,5+o+e.height/2+m),a._width+=b+r,a._height=Math.max(a._height,e.height),_+=b+r,g=Math.max(e.height,g)}),a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height),n.each(function(r){var n=r[0],i=t.select(this).select(".legendtoggle");pn.setRect(i,0,-n.height/2,(e._context.edits.legendText?0:a._width)+l,n.height)})}function Qo(t){var e=t._fullLayout.legend,r="left";Fo.isRightAnchor(e)?r="right":Fo.isCenterAnchor(e)&&(r="center");var n="top";Fo.isBottomAnchor(e)?n="bottom":Fo.isMiddleAnchor(e)&&(n="middle"),mi.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*Wo[r],r:e._width*Xo[r],b:e._height*Xo[n],t:e._height*Wo[n]})}var ts={moduleType:"component",name:"legend",layoutAttributes:Ro,supplyLayoutDefaults:function(t,e,r){for(var n,i,a,o,s=t.legend||{},l={},u=0,c="normal",p=0;p1)){if(e.legend=l,f("bgcolor",e.paper_bgcolor),f("bordercolor"),f("borderwidth"),re.coerceFont(f,"font",e.font),f("orientation"),"h"===l.orientation){var d=t.xaxis;d&&d.rangeslider&&d.rangeslider.visible?(n=0,a="left",i=1.1,o="bottom"):(n=0,a="left",i=-.1,o="top")}f("traceorder",c),Bo.isGrouped(e.legend)&&f("tracegroupgap"),f("x",n),f("xanchor",a),f("y",i),f("yanchor",o),re.noneOrAll(s,l,["x","y"])}},draw:function(e){var r=e._fullLayout,n="legend"+r._uid;if(r._infolayer&&e.calcdata){e._legendMouseDownTime||(e._legendMouseDownTime=0);var i=r.legend,a=r.showlegend&&function(t,e){var r,n,i={},a=[],o=!1,s={},l=0;function u(t,r){if(""!==t&&Bo.isGrouped(e))-1===a.indexOf(t)?(a.push(t),o=!0,i[t]=[[r]]):i[t].push([r]);else{var n="~~i"+l;a.push(n),i[n]=[[r]],l++}}for(r=0;ry?function(t){var e=t._fullLayout.legend,r="left";Fo.isRightAnchor(e)?r="right":Fo.isCenterAnchor(e)&&(r="center"),mi.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*Wo[r],r:e._width*Xo[r],b:0,t:0})}(e):Qo(e);var m=r._size,g=m.l+m.w*i.x,v=m.t+m.h*(1-i.y);Fo.isRightAnchor(i)?g-=i._width:Fo.isCenterAnchor(i)&&(g-=i._width/2),Fo.isBottomAnchor(i)?v-=i._height:Fo.isMiddleAnchor(i)&&(v-=i._height/2);var _=i._width,x=m.w;_>x?(g=m.l,_=x):(g+_>d&&(g=d-_),g<0&&(g=0),_=Math.min(d-g,i._width));var b,w,k,A,T=i._height,M=m.h;if(T>M?(v=m.t,T=M):(v+T>y&&(v=y-T),v<0&&(v=0),T=Math.min(y-v,i._height)),pn.setTranslate(s,g,v),p.on(".drag",null),s.on("wheel",null),i._height<=T||e._context.staticPlot)u.attr({width:_-i.borderwidth,height:T-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),pn.setTranslate(c,0,0),l.select("rect").attr({width:_-2*i.borderwidth,height:T-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth}),pn.setClipUrl(c,n),pn.setRect(p,0,0,0,0),delete i._scrollY;else{var S,C,z=Math.max(No.scrollBarMinHeight,T*T/i._height),L=T-z-2*No.scrollBarMargin,E=i._height-T,I=L/E,D=Math.min(i._scrollY||0,E);u.attr({width:_-2*i.borderwidth+No.scrollBarWidth+No.scrollBarMargin,height:T-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),l.select("rect").attr({width:_-2*i.borderwidth+No.scrollBarWidth+No.scrollBarMargin,height:T-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth+D}),pn.setClipUrl(c,n),R(D,z,I),s.on("wheel",function(){R(D=re.constrain(i._scrollY+t.event.deltaY/L*E,0,E),z,I),0!==D&&D!==E&&t.event.preventDefault()});var O=t.behavior.drag().on("dragstart",function(){S=t.event.sourceEvent.clientY,C=D}).on("drag",function(){var e=t.event.sourceEvent;2===e.buttons||e.ctrlKey||R(D=re.constrain((e.clientY-S)/I+C,0,E),z,I)});p.call(O)}e._context.edits.legendPosition&&(s.classed("cursor-move",!0),rr.init({element:s.node(),gd:e,prepFn:function(){var t=pn.getTranslate(s);k=t.x,A=t.y},moveFn:function(t,e){var r=k+t,n=A+e;pn.setTranslate(s,r,n),b=rr.align(r,0,m.l,m.l+m.w,i.xanchor),w=rr.align(n,0,m.t+m.h,m.t,i.yanchor)},doneFn:function(){void 0!==b&&void 0!==w&&P.call("relayout",e,{"legend.x":b,"legend.y":w})},clickFn:function(t,n){var i=r._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===t?s._clickTimeout=setTimeout(function(){Vo(i,e,t)},Yo):2===t&&(s._clickTimeout&&clearTimeout(s._clickTimeout),Vo(i,e,t)))}}))}function R(t,r,n){i._scrollY=e._fullLayout.legend._scrollY=t,pn.setTranslate(c,0,-t),pn.setRect(p,_,No.scrollBarMargin+t*n,No.scrollBarWidth,r),l.select("rect").attr({y:i.borderwidth+t})}},style:Ho},es={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},rs=g.extendFlat,ns={visible:{valType:"boolean",editType:"plot"},buttons:es=rs(es,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:M({editType:"plot"}),bgcolor:{valType:"color",dflt:z.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:z.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},is={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var as=function(e,r){var n=e._name,i={};if("all"===r.step)i[n+".autorange"]=!0;else{var a=function(e,r){var n,i=e.range,a=new Date(e.r2l(i[1])),o=r.step,s=r.count;switch(r.stepmode){case"backward":n=e.l2r(+t.time[o].utc.offset(a,-s));break;case"todate":var l=t.time[o].utc.offset(a,-s);n=e.l2r(+t.time[o].utc.ceil(l))}var u=i[1];return[n,u]}(e,r);i[n+".range[0]"]=a[0],i[n+".range[1]"]=a[1]}return i};var os=Or.LINE_SPACING,ss=Or.FROM_TL,ls=Or.FROM_BR;function us(t){return t._id}function cs(t,e,r){var n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("selector-rect",!0),n.attr("shape-rendering","crispEdges"),n.attr({rx:is.rx,ry:is.ry}),n.call(Oe.stroke,e.bordercolor).call(Oe.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function ps(t,e,r,n){var i,a=t.selectAll("text").data([0]);a.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),a.attr("text-anchor","middle"),a.call(pn.font,e.font).text((i=r,i.label?i.label:"all"===i.step?"all":i.count+i.step.charAt(0))).call(function(t){Fr.convertToTspans(t,n)})}var hs={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:ns}}},layoutAttributes:ns,handleDefaults:function(t,e,r,n,i){var a=t.rangeselector||{},o=e.rangeselector={};function s(t,e){return re.coerce(a,o,ns,t,e)}if(s("visible",function(t,e,r){var n,i,a=t.buttons||[],o=e.buttons=[];function s(t,e){return re.coerce(n,i,es,t,e)}for(var l=0;l0)){var l=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;a0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}(e,r,n),r._initialCategories="category"===u?function(e,r,n,i){switch(r){case"array":return Array.isArray(n)?n.slice():[];case"category ascending":return xs(e,t.ascending,i);case"category descending":return xs(e,t.descending,i);case"trace":default:return[]}}(o,r.categoryorder,r.categoryarray,i.data):[],"category"===u||i.noHover||n("hoverformat"),!l)return r;var p=n("color"),h=p===e.color?p:s.color;return n("title",a._dfltTitle[o]),re.coerceFont(n,"titlefont",{family:s.family,size:Math.round(1.2*s.size),color:h}),Cr(e,r,n,u),Tr(e,r,n,u,i),Mr(e,r,n,i),function(t,e,r,n){var i=(n=n||{}).dfltColor;function a(r,i){return re.coerce2(t,e,n.attributes,r,i)}var o=a("linecolor",i),s=a("linewidth");r("showline",n.showLine||!!o||!!s)||(delete e.linecolor,delete e.linewidth);var l=a("gridcolor",vs(i,n.bgColor,n.blend||_s).toRgbString()),u=a("gridwidth");if(r("showgrid",n.showGrid||!!l||!!u)||(delete e.gridcolor,delete e.gridwidth),!n.noZeroLine){var c=a("zerolinecolor",i),p=a("zerolinewidth");r("zeroline",n.showGrid||!!c||!!p)||(delete e.zerolinecolor,delete e.zerolinewidth)}}(e,r,n,{dfltColor:p,bgColor:i.bgColor,showGrid:i.showGrid,attributes:wr}),(r.showline||r.ticks)&&n("mirror"),i.automargin&&n("automargin"),r},ws=ci.id2name,ks=function(t,e,r,n,i){var a=i._axisConstraintGroups,o=e._id,s=o.charAt(0);if(!e.fixedrange&&(r("constrain"),re.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===s?["left","center","right"]:["bottom","middle","top"],dflt:"x"===s?"center":"middle"}},"constraintoward"),t.scaleanchor)){var l=function(t,e,r,n){var i,a,o,s,l=n[ws(e)].type,u=[];for(a=0;ad[1]-.01&&(r.domain=o),re.noneOrAll(t.domain,r.domain,o)}return n("layer"),r},Ts=ci.name2id,Ms=function(t,e,r,n,i){i&&(e._name=i,e._id=Ts(i)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var i=function(t,e,r){for(var n=0;n rect").call(pn.setTranslate,0,0).call(pn.setScale,1,1),t.plot.call(pn.setTranslate,e._offset,r._offset).call(pn.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(pn.setPointGroupScale,1,1),n.selectAll(".textpoint").call(pn.setTextPointsScale,1,1),n.call(pn.hideOutsideRangePoints,t)}function y(t,r){var n,i,o,s=p[t.xaxis._id],l=p[t.yaxis._id],u=[];if(s){i=(n=e._fullLayout[s.axisName])._r,o=s.to,u[0]=(i[0]*(1-r)+r*o[0]-i[0])/(i[1]-i[0])*t.xaxis._length;var c=i[1]-i[0],h=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[2]=t.xaxis._length*(1-r+r*h/c)}else u[0]=0,u[2]=t.xaxis._length;if(l){i=(n=e._fullLayout[l.axisName])._r,o=l.to,u[1]=(i[1]*(1-r)+r*o[1]-i[1])/(i[0]-i[1])*t.yaxis._length;var f=i[1]-i[0],d=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[3]=t.yaxis._length*(1-r+r*d/f)}else u[1]=0,u[3]=t.yaxis._length;!function(t,r){var n,i=[];for(i=[t._id,r._id],n=0;n rect").call(pn.setTranslate,b,w).call(pn.setScale,1/_,1/x),t.plot.call(pn.setTranslate,T,M).call(pn.setScale,_,x).selectAll(".points").selectAll(".point").call(pn.setPointGroupScale,1/_,1/x),t.plot.selectAll(".points").selectAll(".textpoint").call(pn.setTextPointsScale,1/_,1/x)}i&&(s=i());var m=t.ease(n.easing);return e._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(c),c=null,function(){for(var t={},r=0;rn.duration?(function(){for(var t={},r=0;rp&&(p=u)));return p>=c?[c,p]:void 0}}var Qs=function(t,e,r,n,i){function a(r,n){return re.coerce(t,e,Ys,r,n)}if(n=n||{},!a("visible",!(i=i||{}).itemIsNotPlainObject))return e;a("layer"),a("opacity"),a("fillcolor"),a("line.color"),a("line.width"),a("line.dash");for(var o=a("type",t.path?"path":"rect"),s=["x","y"],l=0;l<2;l++){var u=s[l],c={_fullLayout:r},p=Ki.coerceRef(t,e,c,u,"","paper");if("path"!==o){var h,f,d;"paper"!==p?(h=Ki.getFromId(c,p),d=Ks.rangeToShapePosition(h),f=Ks.shapePositionToRange(h)):f=d=re.identity;var y=u+"0",m=u+"1",g=t[y],v=t[m];t[y]=f(t[y],!0),t[m]=f(t[m],!0),Ki.coercePosition(e,c,a,p,y,.25),Ki.coercePosition(e,c,a,p,m,.75),e[y]=d(e[y]),e[m]=d(e[m]),t[y]=g,t[m]=v}}return"path"===o?a("path"):re.noneOrAll(t,e,["x0","x1","y0","y1"]),e},tl={draw:function(t){var e=t._fullLayout;e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._shapeSubplotLayers.selectAll("path").remove();for(var r=0;rO&&n>R&&!t.shiftKey?rr.getCursor(i/r,1-a/n):"move";On(e,o),D=o.split("-")[0]}function j(n,f){if("path"===r.type){var d=function(t){return E(z(t)+n)};S&&"date"===S.type&&(d=Ks.encodeDate(d));var y=function(t){return I(L(t)+f)};C&&"date"===C.type&&(y=Ks.encodeDate(y)),r.path=nl(T,d,y),i[M]=r.path}else i[u]=r.x0=E(a+n),i[c]=r.y0=I(o+f),i[p]=r.x1=E(s+n),i[h]=r.y1=I(l+f);e.attr("d",rl(t,r))}function V(n,a){if("path"===r.type){var o=function(t){return E(z(t)+n)};S&&"date"===S.type&&(o=Ks.encodeDate(o));var s=function(t){return I(L(t)+a)};C&&"date"===C.type&&(s=Ks.encodeDate(s)),r.path=nl(T,o,s),i[M]=r.path}else{var l=~D.indexOf("n")?f+a:f,u=~D.indexOf("s")?d+a:d,c=~D.indexOf("w")?y+n:y,p=~D.indexOf("e")?m+n:m;u-l>R&&(i[g]=r[b]=I(l),i[v]=r[w]=I(u)),p-c>O&&(i[_]=r[k]=E(c),i[x]=r[A]=E(p))}e.attr("d",rl(t,r))}rr.init(B),e.node().onmousemove=N}(t,o,n,e)}}function rl(t,e){var r,n,i,a,o=e.type,s=Ki.getFromId(t,e.xref),l=Ki.getFromId(t,e.yref),u=t._fullLayout._size;if(s?(r=Ks.shapePositionToRange(s),n=function(t){return s._offset+s.r2p(r(t,!0))}):n=function(t){return u.l+u.w*t},l?(i=Ks.shapePositionToRange(l),a=function(t){return l._offset+l.r2p(i(t,!0))}):a=function(t){return u.t+u.h*(1-t)},"path"===o)return s&&"date"===s.type&&(n=Ks.decodeDate(n)),l&&"date"===l.type&&(a=Ks.decodeDate(a)),function(t,e,r){return t.replace(Js.segmentRE,function(t){var n=0,i=t.charAt(0),a=Js.paramIsX[i],o=Js.paramIsY[i],s=Js.numParams[i],l=t.substr(1).replace(Js.paramRE,function(t){return a[n]?t=e(t):o[n]&&(t=r(t)),++n>s&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),re.log("Ignoring extra params in segment "+t)),i+l})}(e.path,n,a);var c=n(e.x0),p=n(e.x1),h=a(e.y0),f=a(e.y1);if("line"===o)return"M"+c+","+h+"L"+p+","+f;if("rect"===o)return"M"+c+","+h+"H"+p+"V"+f+"H"+c+"Z";var d=(c+p)/2,y=(h+f)/2,m=Math.abs(d-c),g=Math.abs(y-h),v="A"+m+","+g,_=d+m+","+y;return"M"+_+v+" 0 1,1 "+(d+","+(y-g))+v+" 0 0,1 "+_+"Z"}function nl(t,e,r){return t.replace(Js.segmentRE,function(t){var n=0,i=t.charAt(0),a=Js.paramIsX[i],o=Js.paramIsY[i],s=Js.numParams[i];return i+t.substr(1).replace(Js.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var il={moduleType:"component",name:"shapes",layoutAttributes:Ys,supplyLayoutDefaults:function(t,e){no(t,e,{name:"shapes",handleItemDefaults:Qs})},includeBasePlot:io("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=re.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),re.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var hl=Or.LINE_SPACING,fl=Or.FROM_TL,dl=Or.FROM_BR;function yl(t){return t._index}function ml(e,r){var n=pn.tester.selectAll("g."+al.labelGroupClass).data(r.steps);n.enter().append("g").classed(al.labelGroupClass,!0);var i=0,a=0;n.each(function(e){var n=_l(t.select(this),{step:e},r).node();if(n){var o=pn.bBox(n);a=Math.max(a,o.height),i=Math.max(i,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(al.railWidth,al.gripHeight);var s=e._fullLayout._size;o.lx=s.l+s.w*r.x,o.ly=s.t+s.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(s.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var l=(o.inputAreaLength-2*al.stepInset)/(r.steps.length-1),u=i+al.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/l)),o.labelHeight=a,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var c=pn.tester.append("g");n.each(function(t){var e=gl(c,r,t.label),n=e.node()&&pn.bBox(e.node())||{width:0,height:0},i=Fr.lineCount(e);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,i)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+al.tickOffset+r.ticklen+al.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var p="left";Fo.isRightAnchor(r)&&(o.lx-=o.outerLength,p="right"),Fo.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,p="center");var h="top";Fo.isBottomAnchor(r)&&(o.ly-=o.height,h="bottom"),Fo.isMiddleAnchor(r)&&(o.ly-=o.height/2,h="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),mi.autoMargin(e,al.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*fl[p],r:o.outerLength*dl[p],b:o.height*dl[h],t:o.height*fl[h]})}function gl(t,e,r){if(e.currentvalue.visible){var n,i,a=t.selectAll("text").data([0]),o=e._dims;switch(e.currentvalue.xanchor){case"right":n=o.inputAreaLength-al.currentValueInset-o.currentValueMaxWidth,i="left";break;case"center":n=.5*o.inputAreaLength,i="middle";break;default:n=al.currentValueInset,i="left"}a.enter().append("text").classed(al.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1});var s=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)s+=r;else s+=e.steps[e.active].label;e.currentvalue.suffix&&(s+=e.currentvalue.suffix),a.call(pn.font,e.currentvalue.font).text(s).call(Fr.convertToTspans,e._gd);var l=Fr.lineCount(a),u=(o.currentValueMaxLines+1-l)*e.currentvalue.font.size*hl;return Fr.positionText(a,n,u),a}}function vl(t,e,r){var n=t.selectAll("rect."+al.gripRectClass).data([0]);n.enter().append("rect").classed(al.gripRectClass,!0).call(kl,e,t,r).style("pointer-events","all"),n.attr({width:al.gripWidth,height:al.gripHeight,rx:al.gripRadius,ry:al.gripRadius}).call(Oe.stroke,r.bordercolor).call(Oe.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function _l(t,e,r){var n=t.selectAll("text").data([0]);return n.enter().append("text").classed(al.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(pn.font,r.font).text(e.step.label).call(Fr.convertToTspans,r._gd),n}function xl(e,r){var n=e.selectAll("g."+al.labelsClass).data([0]),i=r._dims;n.enter().append("g").classed(al.labelsClass,!0);var a=n.selectAll("g."+al.labelGroupClass).data(i.labelSteps);a.enter().append("g").classed(al.labelGroupClass,!0),a.exit().remove(),a.each(function(e){var n=t.select(this);n.call(_l,e,r),pn.setTranslate(n,Ml(r,e.fraction),al.tickOffset+r.ticklen+r.font.size*hl+al.labelOffset+i.currentValueTotalHeight)})}function bl(t,e,r,n,i){var a=Math.round(n*(r.steps.length-1));a!==r.active&&wl(t,e,r,a,!0,i)}function wl(t,e,r,n,i,a){var o=r.active;r._input.active=r.active=n;var s=r.steps[r.active];e.call(Tl,r,r.active/(r.steps.length-1),a),e.call(gl,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:o}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=a):(e._nextMethod={step:s,doCallback:i,doTransition:a},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&mi.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function kl(e,r,n){var i=n.node(),a=t.select(r);function o(){return n.data()[0]}e.on("mousedown",function(){var e=o();r.emit("plotly_sliderstart",{slider:e});var s=n.select("."+al.gripRectClass);t.event.stopPropagation(),t.event.preventDefault(),s.call(Oe.fill,e.activebgcolor);var l=Sl(e,t.mouse(i)[0]);bl(r,n,e,l,!0),e._dragging=!0,a.on("mousemove",function(){var e=o(),a=Sl(e,t.mouse(i)[0]);bl(r,n,e,a,!1)}),a.on("mouseup",function(){var t=o();t._dragging=!1,s.call(Oe.fill,t.bgcolor),a.on("mouseup",null),a.on("mousemove",null),r.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function Al(e,r){var n=e.selectAll("rect."+al.tickRectClass).data(r.steps),i=r._dims;n.enter().append("rect").classed(al.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(e,n){var a=n%i.labelStride==0,o=t.select(this);o.attr({height:a?r.ticklen:r.minorticklen}).call(Oe.fill,r.tickcolor),pn.setTranslate(o,Ml(r,n/(r.steps.length-1))-.5*r.tickwidth,(a?al.tickOffset:al.minorTickOffset)+i.currentValueTotalHeight)})}function Tl(t,e,r,n){var i=t.select("rect."+al.gripRectClass),a=Ml(e,r);if(!e._invokingCommand){var o=i;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(a-.5*al.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function Ml(t,e){var r=t._dims;return r.inputAreaStart+al.stepInset+(r.inputAreaLength-2*al.stepInset)*Math.min(1,Math.max(0,e))}function Sl(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-al.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*al.stepInset-2*r.inputAreaStart)))}function Cl(t,e,r){var n=t.selectAll("rect."+al.railTouchRectClass).data([0]),i=r._dims;n.enter().append("rect").classed(al.railTouchRectClass,!0).call(kl,e,t,r).style("pointer-events","all"),n.attr({width:i.inputAreaLength,height:Math.max(i.inputAreaWidth,al.tickOffset+r.ticklen+i.labelHeight)}).call(Oe.fill,r.bgcolor).attr("opacity",0),pn.setTranslate(n,0,i.currentValueTotalHeight)}function zl(t,e){var r=t.selectAll("rect."+al.railRectClass).data([0]),n=e._dims;r.enter().append("rect").classed(al.railRectClass,!0);var i=n.inputAreaLength-2*al.railInset;r.attr({width:i,height:al.railWidth,rx:al.railRadius,ry:al.railRadius,"shape-rendering":"crispEdges"}).call(Oe.stroke,e.bordercolor).call(Oe.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),pn.setTranslate(r,al.railInset,.5*(n.inputAreaWidth-al.railWidth)+n.currentValueTotalHeight)}var Ll={moduleType:"component",name:al.name,layoutAttributes:ll,supplyLayoutDefaults:function(t,e){no(t,e,{name:ul,handleItemDefaults:pl})},draw:function(e){var r=e._fullLayout,n=function(t,e){for(var r=t[al.name],n=[],i=0;i0?[0]:[]);if(i.enter().append("g").classed(al.containerClassName,!0).style("cursor","ew-resize"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(gl,r).call(zl,r).call(xl,r).call(Al,r).call(Cl,t,r).call(vl,t,r);var n=r._dims;pn.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(Tl,r,r.active/(r.steps.length-1),!1),e.call(gl,r)}(e,t.select(this),r)}})}}},El=g.extendFlat,Pl=(0,yr.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:El({},ol,{}),font:M({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:z.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Il={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Dl=Il.name,Ol=Pl.buttons;function Rl(t,e,r){function n(r,n){return re.coerce(t,e,Pl,r,n)}n("visible",function(t,e){var r,n,i=t.buttons||[],a=e.buttons=[];function o(t,e){return re.coerce(r,n,Ol,t,e)}for(var s=0;s0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var Bl=Fl;function Fl(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Fl.barWidth=2,Fl.barLength=20,Fl.barRadius=2,Fl.barPad=1,Fl.barColor="#808BA4",Fl.prototype.enable=function(e,r,n){var i=this.gd._fullLayout,a=i.width,o=i.height;this.position=e;var s,l,u,c,p=this.position.l,h=this.position.w,f=this.position.t,d=this.position.h,y=this.position.direction,m="down"===y,g="left"===y,v="up"===y,_=h,x=d;m||g||"right"===y||v||(this.position.direction="down",m=!0),m||v?(l=(s=p)+_,m?(u=f,x=(c=Math.min(u+x,o))-u):x=(c=f+x)-(u=Math.max(c-x,0))):(c=(u=f)+x,g?_=(l=p+_)-(s=Math.max(l-_,0)):(s=p,_=(l=Math.min(s+_,a))-s)),this._box={l:s,t:u,w:_,h:x};var b=h>_,w=Fl.barLength+2*Fl.barPad,k=Fl.barWidth+2*Fl.barPad,A=p,T=f+d;T+k>o&&(T=o-k);var M=this.container.selectAll("rect.scrollbar-horizontal").data(b?[0]:[]);M.exit().on(".drag",null).remove(),M.enter().append("rect").classed("scrollbar-horizontal",!0).call(Oe.fill,Fl.barColor),b?(this.hbar=M.attr({rx:Fl.barRadius,ry:Fl.barRadius,x:A,y:T,width:w,height:k}),this._hbarXMin=A+w/2,this._hbarTranslateMax=_-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var S=d>x,C=Fl.barWidth+2*Fl.barPad,z=Fl.barLength+2*Fl.barPad,L=p+h,E=f;L+C>a&&(L=a-C);var P=this.container.selectAll("rect.scrollbar-vertical").data(S?[0]:[]);P.exit().on(".drag",null).remove(),P.enter().append("rect").classed("scrollbar-vertical",!0).call(Oe.fill,Fl.barColor),S?(this.vbar=P.attr({rx:Fl.barRadius,ry:Fl.barRadius,x:L,y:E,width:C,height:z}),this._vbarYMin=E+z/2,this._vbarTranslateMax=x-z):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var I=this.id,D=s-.5,O=S?l+C+.5:l+.5,R=u-.5,B=b?c+k+.5:c+.5,F=i._topdefs.selectAll("#"+I).data(b||S?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",I).append("rect"),b||S?(this._clipRect=F.select("rect").attr({x:Math.floor(D),y:Math.floor(R),width:Math.ceil(O)-Math.floor(D),height:Math.ceil(B)-Math.floor(R)}),this.container.call(pn.setClipUrl,I),this.bg.attr({x:p,y:f,width:h,height:d})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(pn.setClipUrl,null),delete this._clipRect),b||S){var N=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(N);var j=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault(),t.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));b&&this.hbar.on(".drag",null).call(j),S&&this.vbar.on(".drag",null).call(j)}this.setTranslate(r,n)},Fl.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(pn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Fl.prototype._onBoxDrag=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e-=t.event.dx),this.vbar&&(r-=t.event.dy),this.setTranslate(e,r)},Fl.prototype._onBoxWheel=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e+=t.event.deltaY),this.vbar&&(r+=t.event.deltaY),this.setTranslate(e,r)},Fl.prototype._onBarDrag=function(){var e=this.translateX,r=this.translateY;if(this.hbar){var n=e+this._hbarXMin,i=n+this._hbarTranslateMax;e=(re.constrain(t.event.x,n,i)-n)/(i-n)*(this.position.w-this._box.w)}if(this.vbar){var a=r+this._vbarYMin,o=a+this._vbarTranslateMax;r=(re.constrain(t.event.y,a,o)-a)/(o-a)*(this.position.h-this._box.h)}this.setTranslate(e,r)},Fl.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=re.constrain(t||0,0,r),e=re.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(pn.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(pn.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var a=e/n;this.vbar.call(pn.setTranslate,t,e+a*this._vbarTranslateMax)}};var Nl=Or.LINE_SPACING;function jl(t){return t._index}function Vl(t,e){return+t.attr(Il.menuIndexAttrName)===e._index}function ql(t,e,r,n,i,a,o,s){e._input.active=e.active=o,"buttons"===e.type?Zl(t,n,null,null,e):"dropdown"===e.type&&(i.attr(Il.menuIndexAttrName,"-1"),Ul(t,n,i,a,e),s||Zl(t,n,i,a,e))}function Ul(t,e,r,n,i){var a=e.selectAll("g."+Il.headerClassName).data([0]),o=i._dims;a.enter().append("g").classed(Il.headerClassName,!0).style("pointer-events","all");var s=i.active,l=i.buttons[s]||Il.blankHeaderOpts,u={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};a.call(Hl,i,l,t).call($l,i,u,c);var p=e.selectAll("text."+Il.headerArrowClassName).data([0]);p.enter().append("text").classed(Il.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(pn.font,i.font).text(Il.arrowSymbol[i.direction]),p.attr({x:o.headerWidth-Il.arrowOffsetX+i.pad.l,y:o.headerHeight/2+Il.textOffsetY+i.pad.t}),a.on("click",function(){r.call(Ql),r.attr(Il.menuIndexAttrName,Vl(r,i)?-1:String(i._index)),Zl(t,e,r,n,i)}),a.on("mouseover",function(){a.call(Yl)}),a.on("mouseout",function(){a.call(Jl,i)}),pn.setTranslate(e,o.lx,o.ly)}function Zl(e,r,n,i,a){n||(n=r).attr("pointer-events","all");var o=function(t){return-1==+t.attr(Il.menuIndexAttrName)}(n)&&"buttons"!==a.type?[]:a.buttons,s="dropdown"===a.type?Il.dropdownButtonClassName:Il.buttonClassName,l=n.selectAll("g."+s).data(o),u=l.enter().append("g").classed(s,!0),c=l.exit();"dropdown"===a.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var p=0,h=0,f=a._dims,d=-1!==["up","down"].indexOf(a.direction);"dropdown"===a.type&&(d?h=f.headerHeight+Il.gapButtonHeader:p=f.headerWidth+Il.gapButtonHeader),"dropdown"===a.type&&"up"===a.direction&&(h=-Il.gapButtonHeader+Il.gapButton-f.openHeight),"dropdown"===a.type&&"left"===a.direction&&(p=-Il.gapButtonHeader+Il.gapButton-f.openWidth);var y={x:f.lx+p+a.pad.l,y:f.ly+h+a.pad.t,yPad:Il.gapButton,xPad:Il.gapButton,index:0},m={l:y.x+a.borderwidth,t:y.y+a.borderwidth};l.each(function(o,s){var u=t.select(this);u.call(Hl,a,o,e).call($l,a,y),u.on("click",function(){t.event.defaultPrevented||(ql(e,a,0,r,n,i,s),o.execute&&mi.executeAPICommand(e,o.method,o.args),e.emit("plotly_buttonclicked",{menu:a,button:o,active:a.active}))}),u.on("mouseover",function(){u.call(Yl)}),u.on("mouseout",function(){u.call(Jl,a),l.call(Xl,a)})}),l.call(Xl,a),d?(m.w=Math.max(f.openWidth,f.headerWidth),m.h=y.y-m.t):(m.w=y.x-m.l,m.h=Math.max(f.openHeight,f.headerHeight)),m.direction=a.direction,i&&(l.size()?function(t,e,r,n,i,a){var o,s,l,u=i.direction,c="up"===u||"down"===u,p=i._dims,h=i.active;if(c)for(s=0,l=0;l0?[0]:[]);if(i.enter().append("g").classed(Il.containerClassName,!0).style("cursor","pointer"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nx.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&re.log("Clearing previous rejected promises from queue."),t._promises=[]},au.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(mi.subplotsRegistry.cartesian||{}).attrRegex,i=(mi.subplotsRegistry.gl3d||{}).attrRegex,a=Object.keys(t);for(e=0;e3?(_.x=1.02,_.xanchor="left"):_.x<-2&&(_.x=-.02,_.xanchor="right"),_.y>3?(_.y=1.02,_.yanchor="bottom"):_.y<-2&&(_.y=-.02,_.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Oe.clean(t),t},au.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),i=0;i0)return t.substr(0,e)}au.hasParent=function(t,e){for(var r=hu(e);r;){if(r in t)return!0;r=hu(r)}return!1};var fu=["x","y","z"];au.clearAxisTypes=function(t,e,r){for(var n=0;n1&&b.warn("Full array edits are incompatible with other edits",i);var p=r[""][""];if(gu(p))e.set(null);else{if(!Array.isArray(p))return b.warn("Unrecognized full array edit value",i,p),!0;e.set(p)}return!l&&(a(u,c),o(t),!0)}var h,f,d,y,m,g,v,_=Object.keys(r).map(Number).sort(yu),x=e.get(),w=x||[],k=G(c,i).get(),T=[],M=-1,S=w.length;for(h=0;h<_.length;h++)if(y=r[d=_[h]],m=Object.keys(y),g=y[""],v=mu(g),d<0||d>w.length-(v?0:1))b.warn("index out of range",i,d);else if(void 0!==g)m.length>1&&b.warn("Insertion & removal are incompatible with edits to the same index.",i,d),gu(g)?T.push(d):v?("add"===g&&(g={}),w.splice(d,0,g),k&&k.splice(d,0,{})):b.warn("Unrecognized full object edit value",i,d,g),-1===M&&(M=d);else for(f=0;f=0;h--)w.splice(T[h],1),k&&k.splice(T[h],1);if(w.length?x||e.set(w):e.set(null),l)return!1;if(a(u,c),s!==A){var C;if(-1===M)C=_;else{for(S=Math.max(w.length,S),C=[],h=0;h<_.length&&!((d=_[h])>=M);h++)C.push(d);for(h=M;h1?(g=["toggleHover"],v=["resetViews"]):s?(m=["zoomInGeo","zoomOutGeo"],g=["hoverClosestGeo"],v=["resetGeo"]):o?(g=["hoverClosest3d"],v=["resetCameraDefault3d","resetCameraLastSave3d"]):p?(g=["toggleHover"],v=["resetViewMapbox"]):g=u?["hoverClosestGl2d"]:l?["hoverClosestPie"]:["toggleHover"],a&&(g=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!a&&!u||f||(m=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==v[0]&&(v=["resetScale2d"])),o?_=["zoom3d","pan3d","orbitRotation","tableRotation"]:(a||u)&&!f||c?_=["zoom2d","pan2d"]:p||s?_=["pan2d"]:h&&(_=["zoom2d"]),function(t){for(var e=!1,r=0;r0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,l=i.end,u=a.start,c=a.end;r&&r.checkIntersection(i,a);var p=e.linesIntersect(o,l,u,c);if(!1===p){if(!e.pointsCollinear(o,l,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(l,u))return!1;var h=e.pointsSame(o,u),f=e.pointsSame(l,c);if(h&&f)return n;var d=!h&&e.pointBetween(o,u,c),y=!f&&e.pointBetween(l,u,c);if(h)return y?s(n,l):s(t,c),n;d&&(f||(y?s(n,l):s(t,c)),s(n,o))}else 0===p.alongA&&(-1===p.alongB?s(t,u):0===p.alongB?s(t,p.pt):1===p.alongB&&s(t,c)),0===p.alongB&&(-1===p.alongA?s(n,o):0===p.alongA?s(n,p.pt):1===p.alongA&&s(n,l));return!1}for(var c=[];!i.isEmpty();){var p=i.getHead();if(r&&r.vert(p.pt[0]),p.isStart){r&&r.segmentNew(p.seg,p.primary);var h=l(p),f=h.before?h.before.ev:null,d=h.after?h.after.ev:null;function y(){if(f){var t=u(p,f);if(t)return t}return!!d&&u(p,d)}r&&r.tempStatus(p.seg,!!f&&f.seg,!!d&&d.seg);var m,g,v=y();if(v)t?(g=null===p.seg.myFill.below||p.seg.myFill.above!==p.seg.myFill.below)&&(v.seg.myFill.above=!v.seg.myFill.above):v.seg.otherFill=p.seg.myFill,r&&r.segmentUpdate(v.seg),p.other.remove(),p.remove();if(i.getHead()!==p){r&&r.rewind(p.seg);continue}t?(g=null===p.seg.myFill.below||p.seg.myFill.above!==p.seg.myFill.below,p.seg.myFill.below=d?d.seg.myFill.above:n,p.seg.myFill.above=g?!p.seg.myFill.below:p.seg.myFill.below):null===p.seg.otherFill&&(m=d?p.primary===d.primary?d.seg.otherFill.above:d.seg.myFill.above:p.primary?a:n,p.seg.otherFill={above:m,below:m}),r&&r.status(p.seg,!!f&&f.seg,!!d&&d.seg),p.other.status=h.insert(Ru.node({ev:p}))}else{var _=p.status;if(null===_)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(_.prev)&&o.exists(_.next)&&u(_.prev.ev,_.next.ev),r&&r.statusRemove(_.ev.seg),_.remove(),!p.primary){var x=p.seg.myFill;p.seg.myFill=p.seg.otherFill,p.seg.otherFill=x}c.push(p.seg)}i.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,i,a,s=t[t.length-1],l=0;l=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-i>t&&(a-u)*(i-c)/(o-c)+u-n>t&&(s=!s),a=u,o=c}return s}};return e}();function Zu(t,e,r){var n=ju.segments(t),i=ju.segments(e),a=r(ju.combine(n,i));return ju.polygon(a)}ju={buildLog:function(t){return!0===t?qu=Du():!1===t&&(qu=!1),!1!==qu&&qu.list},epsilon:function(t){return Uu.epsilon(t)},segments:function(t){var e=Bu(!0,Uu,qu);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:Bu(!1,Uu,qu).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:Vu.union(t.combined,qu),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:Vu.intersect(t.combined,qu),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:Vu.difference(t.combined,qu),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:Vu.differenceRev(t.combined,qu),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:Vu.xor(t.combined,qu),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:Fu(t.segments,Uu,qu),inverted:t.inverted}},polygonFromGeoJSON:function(t){return Ou.toPolygon(ju,t)},polygonToGeoJSON:function(t){return Ou.fromPolygon(ju,Uu,t)},union:function(t,e){return Zu(t,e,ju.selectUnion)},intersect:function(t,e){return Zu(t,e,ju.selectIntersect)},difference:function(t,e){return Zu(t,e,ju.selectDifference)},differenceRev:function(t,e){return Zu(t,e,ju.selectDifferenceRev)},xor:function(t,e){return Zu(t,e,ju.selectXor)}},"object"==typeof window&&(window.PolyBool=ju);var Hu,Gu=ju,Wu=jt.dot,Xu=r.BADNUM,Yu=Hu={};Yu.tester=function(t){if(Array.isArray(t[0][0]))return Yu.multitester(t);var e,r=t.slice(),n=r[0][0],i=n,a=r[0][1],o=a;for(r.push(r[0]),e=1;ei||l===Xu||lo||e&&s(t))}:function(t,e){var s=t[0],l=t[1];if(s===Xu||si||l===Xu||lo)return!1;var u,c,p,h,f,d=r.length,y=r[0][0],m=r[0][1],g=0;for(u=1;uMath.max(c,y)||l>Math.max(p,m)))if(lu||Math.abs(Wu(a,p))>n)return!0;return!1};Yu.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var o=r.length,s=n;r.splice(i+1);for(var l=s+1;l1&&a(t.pop());return{addPt:a,raw:t,filtered:r}};var Ku=En.makeEventData,$u=Hu.filter,Qu=Hu.tester,tc=Hu.multitester,ec=Ie.MINSELECT;function rc(t){return t._id}var nc=function(t,e,r,n,i){var a,o,s,l,u=n.gd,c=u._fullLayout,p=c._zoomlayer,h=n.element.getBoundingClientRect(),f=n.plotinfo,d=f.xaxis._offset,y=f.yaxis._offset,m=e-h.left,g=r-h.top,v=m,_=g,x="M"+m+","+g,b=n.xaxes[0]._length,w=n.yaxes[0]._length,k=n.xaxes.map(rc),A=n.yaxes.map(rc),T=n.xaxes.concat(n.yaxes),M=t.altKey;(t.shiftKey||t.altKey)&&f.selection&&f.selection.polygons&&!n.polygons?(n.polygons=f.selection.polygons,n.mergedPolygons=f.selection.mergedPolygons):(!t.shiftKey&&!t.altKey||(t.shiftKey||t.altKey)&&!f.selection)&&(f.selection={},f.selection.polygons=n.polygons=[],f.selection.mergedPolygons=n.mergedPolygons=[]),"lasso"===i&&(a=$u([[m,g]],Ie.BENDPX));var S=p.selectAll("path.select-outline-"+f.id).data([1,2]);S.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+f.id}).attr("transform","translate("+d+", "+y+")").attr("d",x+"Z");var C,z,L,E,P,I,D=p.append("path").attr("class","zoombox-corners").style({fill:Oe.background,stroke:Oe.defaultLine,"stroke-width":1}).attr("transform","translate("+d+", "+y+")").attr("d","M0,0Z"),O=[],R=c._uid+Ie.SELECTID,B=[];for(C=0;C=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function vc(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function _c(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Oe.background,stroke:Oe.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function xc(t){t.selectAll(".select-outline").remove()}function bc(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),wc(t,e,i,a)}function wc(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function kc(e){t.select(e).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Ac(t){pc&&t.data&&t._context.showTips&&(re.notifier(re._(t,"Double-click to zoom back out"),"long"),pc=!1)}function Tc(t){return"lasso"===t||"select"===t}function Mc(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,cc)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function Sc(t,e){if(qe){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}var Cc=function(e,r,n,i,a,o,l,u){var c,p,h,f,d,y,m,g,v,_,x,b,w,k=e._fullLayout,A=e._fullLayout._zoomlayer,T=l+u==="nsew",M=1===(l+u).length;function S(){p=[r.xaxis],h=[r.yaxis];var t=p[0],n=h[0];y=t._length,m=n._length;var i,a,o=k._axisConstraintGroups,s=[t._id],A=[n._id];c=[r].concat(l&&u?r.overlays:[]);for(var T=1;Tcc||o>cc?(B="xy",a/y>o/m?(o=a*m/y,E>i?I.t=E-o:I.b=E+o):(a=o*y/m,L>n?I.l=L-a:I.r=L+a),N.attr("d",Mc(I))):s():!v||o rect").call(pn.setTranslate,i,a).call(pn.setScale,r,n);var P=_.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");_.plot.call(pn.setTranslate,L,E).call(pn.setScale,1/r,1/n),P.selectAll(".point").call(pn.setPointGroupScale,r,n),P.selectAll(".textpoint").call(pn.setTextPointsScale,r,n),P.call(pn.hideOutsideRangePoints,_),_.plot.selectAll(".barlayer .trace").call(pn.hideOutsideRangePoints,_,".bartext")}}}return l.length*u.length!=1&&Sc(C,function(t){if(e._context.scrollZoom||k._enablescrollzoom){if(null===H&&xc(A),e._transitioningWithDuration)return t.preventDefault(),void t.stopPropagation();var r=e.querySelector(".plotly");if(S(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(H);var n=-t.deltaY;if(isFinite(n)||(n=t.wheelDelta/10),isFinite(n)){var i,a=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=W.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(t.clientX-o.left)/o.width,c=(o.bottom-t.clientY)/o.height;if(u||x){for(u||(s=.5),i=0;i=t[1]||i[1]<=t[0])&&a[0]e[0])return!0}return!1}(r,i,f)?(h.push(t),f.push([r,i])):a=[0];var o=e.plotgroup.selectAll(".bg").data(a);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){e.bg=o;var t=e.plotgroup.node();t.insertBefore(this,t.childNodes[0])})});var d=n._bgLayer.selectAll(".bg").data(h);return d.enter().append("rect").classed("bg",!0),d.exit().remove(),d.each(function(e){n._plots[e].bg=t.select(this)}),p.each(function(t){var e=n._plots[t],i=e.xaxis,u=e.yaxis;e.bg&&s&&e.bg.call(pn.setRect,i._offset-a,u._offset-a,i._length+2*a,u._length+2*a).call(Oe.fill,n.plot_bgcolor).style("stroke-width",0),e.clipId="clip"+n._uid+t+"plot";var c,p,h=n._clips.selectAll("#"+e.clipId).data([0]);for(h.enter().append("clipPath").attr({class:"plotclip",id:e.clipId}).append("rect"),h.selectAll("rect").attr({width:i._length,height:u._length}),pn.setTranslate(e.plot,i._offset,u._offset),e._hasClipOnAxisFalse?(c=null,p=e.clipId):(c=e.clipId,p=null),pn.setClipUrl(e.plot,c),r=0;rBc*f)||g)for(r=0;rS&&LT&&(T=L);s/=(T-A)/(2*M),A=i.l2r(A),T=i.l2r(T),i.range=i._input.range=b=0?u.angularAxis.domain:t.extent(_),A=Math.abs(_[1]-_[0]);b&&!x&&(A=0);var T=k.slice();w&&x&&(T[1]+=A);var M=u.angularAxis.ticksCount||4;M>8&&(M=M/(M/8)+M%8),u.angularAxis.ticksStep&&(M=(T[1]-T[0])/M);var S=u.angularAxis.ticksStep||(T[1]-T[0])/(M*(u.minorTicks+1));v&&(S=Math.max(Math.round(S),1)),T[2]||(T[2]=S);var C=t.range.apply(this,T);if(C=C.map(function(t,e){return parseFloat(t.toPrecision(12))}),i=t.scale.linear().domain(T.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),s.layout.angularAxis.domain=i.domain(),s.layout.angularAxis.endPadding=w?A:0,void 0===(e=t.select(this).select("svg.chart-root"))||e.empty()){var z=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),L=this.appendChild(this.ownerDocument.importNode(z.documentElement,!0));e=t.select(L)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var E,P=e.select(".chart-group"),I={fill:"none",stroke:u.tickColor},D={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){E=e.select(".legend-group").attr({transform:"translate("+[y,u.margin.top]+")"}).style({display:"block"});var O=c.map(function(t,e){var r=Uc.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});Uc.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:Vc({},Uc.Legend.defaultConfig().legendConfig,{container:E,elements:O,reverseOrder:u.legend.reverseOrder})})();var R=E.node().getBBox();y=Math.min(u.width-R.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,y=Math.max(10,y),g=[u.margin.left+y,u.margin.top+y],n.range([0,y]),s.layout.radialAxis.domain=n.domain(),E.attr("transform","translate("+[g[0]+y,g[1]-y]+")")}else E=e.select(".legend-group").style({display:"none"});e.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),P.attr("transform","translate("+g+")").style({cursor:"crosshair"});var B=[(u.width-(u.margin.left+u.margin.right+2*y+(R?R.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*y))/2];if(B[0]=Math.max(0,B[0]),B[1]=Math.max(0,B[1]),e.select(".outer-group").attr("transform","translate("+B+")"),u.title){var F=e.select("g.title-group text").style(D).text(u.title),N=F.node().getBBox();F.attr({x:g[0]-N.width/2,y:g[1]-y-20})}var j=e.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var V=j.selectAll("circle.grid-circle").data(n.ticks(5));V.enter().append("circle").attr({class:"grid-circle"}).style(I),V.attr("r",n),V.exit().remove()}j.select("circle.outside-circle").attr({r:y}).style(I);var q=e.select("circle.background-circle").attr({r:y}).style({fill:u.backgroundColor,stroke:u.stroke});function U(t,e){return i(t)%360+u.orientation}if(u.radialAxis.visible){var Z=t.svg.axis().scale(n).ticks(5).tickSize(5);j.call(Z).attr({transform:"rotate("+u.radialAxis.orientation+")"}),j.selectAll(".domain").style(I),j.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(D).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,D["font-size"]]+")":"translate("+[0,D["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var H=e.select(".angular.axis-group").selectAll("g.angular-tick").data(C),G=H.enter().append("g").classed("angular-tick",!0);H.attr({transform:function(t,e){return"rotate("+U(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),H.exit().remove(),G.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(I),G.selectAll(".minor").style({stroke:u.minorTickColor}),H.select("line.grid-line").attr({x1:u.tickLength?y-u.tickLength:0,x2:y}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),G.append("text").classed("axis-text",!0).style(D);var W=H.select("text.axis-text").attr({x:y+u.labelOffset,dy:qc+"em",transform:function(t,e){var r=U(t),n=y+u.labelOffset,i=u.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":v?v[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(D);u.angularAxis.rewriteTicks&&W.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var X=t.max(P.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));E.attr({transform:"translate("+[y+X,u.margin.top]+")"});var Y=e.select("g.geometry-group").selectAll("g").size()>0,J=e.select("g.geometry-group").selectAll("g.geometry").data(c);if(J.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),J.exit().remove(),c[0]||Y){var K=[];c.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=i,r.container=J.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=u.orientation,r.direction=u.direction,r.index=e,K.push({data:t,geometryConfig:r})});var $=[];t.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(K).forEach(function(t,e){"unstacked"===t.key?$=$.concat(t.values.map(function(t,e){return[t]})):$.push(t.values)}),$.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return Vc(Uc[r].defaultConfig(),t)});Uc[r]().config(n)()})}var Q,tt,et=e.select(".guides-group"),rt=e.select(".tooltips-group"),nt=Uc.tooltipPanel().config({container:rt,fontSize:8})(),it=Uc.tooltipPanel().config({container:rt,fontSize:8})(),at=Uc.tooltipPanel().config({container:rt,hasTick:!0})();if(!x){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});P.on("mousemove.angular-guide",function(t,e){var r=Uc.util.getMousePos(q).angle;ot.attr({x2:-y,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;Q=i.invert(n);var a=Uc.util.convertToCartesian(y+12,r+180);nt.text(Uc.util.round(Q)).move([a[0]+g[0],a[1]+g[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var st=et.select("circle").style({stroke:"grey",fill:"none"});P.on("mousemove.radial-guide",function(t,e){var r=Uc.util.getMousePos(q).radius;st.attr({r:r}).style({opacity:.5}),tt=n.invert(Uc.util.getMousePos(q).radius);var i=Uc.util.convertToCartesian(r,u.radialAxis.orientation);it.text(Uc.util.round(tt)).move([i[0]+g[0],i[1]+g[1]])}).on("mouseout.radial-guide",function(t,e){st.style({opacity:0}),at.hide(),nt.hide(),it.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var i=t.select(this),a=this.style.fill,o="black",s=this.style.opacity||1;if(i.attr({"data-opacity":s}),a&&"none"!==a){i.attr({"data-fill":a}),o=t.hsl(a).darker().toString(),i.style({fill:o,opacity:1});var l={t:Uc.util.round(r[0]),r:Uc.util.round(r[1])};x&&(l.t=v[r[0]]);var u="t: "+l.t+", r: "+l.r,c=this.getBoundingClientRect(),p=e.node().getBoundingClientRect(),h=[c.left+c.width/2-B[0]-p.left,c.top+c.height/2-B[1]-p.top];at.config({color:o}).text(u),at.move(h)}else a=this.style.stroke||"black",i.attr({"data-stroke":a}),o=t.hsl(a).darker().toString(),i.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(e,r){if(0!=t.event.which)return!1;t.select(this).attr("data-fill")&&at.show()}).on("mouseout.tooltip",function(e,r){at.hide();var n=t.select(this),i=n.attr("data-fill");i?n.style({fill:i,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return a;var e=Uc.util.cloneJson(t);return e.data.forEach(function(t,e){a.data[e]||(a.data[e]={}),Vc(a.data[e],Uc.Axis.defaultConfig().data[0]),Vc(a.data[e],t)}),Vc(a.layout,Uc.Axis.defaultConfig().layout),Vc(a.layout,e.layout),this},u.getLiveConfig=function(){return s},u.getinputConfig=function(){return o},u.radialScale=function(t){return n},u.angularScale=function(t){return i},u.svg=function(){return e},t.rebind(u,l,"on"),u},Uc.Axis.defaultConfig=function(e,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:t.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Uc.util={},Uc.DATAEXTENT="dataExtent",Uc.AREA="AreaChart",Uc.LINE="LinePlot",Uc.DOT="DotPlot",Uc.BAR="BarChart",Uc.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},Uc.util._extend=function(t,e){for(var r in t)e[r]=t[r]},Uc.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Uc.util.dataFromEquation2=function(e,r){var n=r||6;return t.range(0,360+n,n).map(function(t,r){var n=t*Math.PI/180;return[t,e(n)]})},Uc.util.dataFromEquation=function(e,r,n){var i=r||6,a=[],o=[];t.range(0,360+i,i).forEach(function(t,r){var n=t*Math.PI/180,i=e(n);a.push(t),o.push(i)});var s={t:a,r:o};return n&&(s.name=n),s},Uc.util.ensureArray=function(e,r){if(void 0===e)return null;var n=[].concat(e);return t.range(r).map(function(t,e){return n[e]||n[0]})},Uc.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=Uc.util.ensureArray(t[e],r)}),t},Uc.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},Uc.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},Uc.util.sumArrays=function(e,r){return t.zip(e,r).map(function(e,r){return t.sum(e)})},Uc.util.arrayLast=function(t){return t[t.length-1]},Uc.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},Uc.util.flattenArray=function(t){for(var e=[];!Uc.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},Uc.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},Uc.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},Uc.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},Uc.util.getMousePos=function(e){var r=t.mouse(e.node()),n=r[0],i=r[1],a={};return a.x=n,a.y=i,a.pos=r,a.angle=180*(Math.atan2(i,n)+Math.PI)/Math.PI,a.radius=Math.sqrt(n*n+i*i),a},Uc.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i0)){var l=t.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:c(s),transform:function(t,e){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return d.fill(n,i,a)},"fill-opacity":0,stroke:function(t,e){return d.stroke(n,i,a)},"stroke-width":function(t,e){return d["stroke-width"](n,i,a)},"stroke-dasharray":function(t,e){return d["stroke-dasharray"](n,i,a)},opacity:function(t,e){return d.opacity(n,i,a)},display:function(t,e){return d.display(n,i,a)}})}};var p=r.angularScale.range(),h=Math.abs(p[1]-p[0])/o[0].length*Math.PI/180,f=t.svg.arc().startAngle(function(t){return-h/2}).endAngle(function(t){return h/2}).innerRadius(function(t){return r.radialScale(l+(t[2]||0))}).outerRadius(function(t){return r.radialScale(l+(t[2]||0))+r.radialScale(t[1])});u.arc=function(e,n,i){t.select(this).attr({class:"mark arc",d:f,transform:function(t,e){return"rotate("+(r.orientation+s(t[0])+90)+")"}})};var d={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,i){return n[e[i].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return void 0===e[n].data.visible||e[n].data.visible?"block":"none"}},y=t.select(this).selectAll("g.layer").data(o);y.enter().append("g").attr({class:"layer"});var m=y.selectAll("path.mark").data(function(t,e){return t});m.enter().append("path").attr({class:"mark"}),m.style(d).each(u[r.geometryType]),m.exit().remove(),y.exit().remove()})}return i.config=function(t){return arguments.length?(t.forEach(function(t,r){e[r]||(e[r]={}),Vc(e[r],Uc.PolyChart.defaultConfig()),Vc(e[r],t)}),this):e},i.getColorScale=function(){},t.rebind(i,r,"on"),i},Uc.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:t.scale.category20()}}},Uc.BarChart=function(){return Uc.PolyChart()},Uc.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Uc.AreaChart=function(){return Uc.PolyChart()},Uc.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Uc.DotPlot=function(){return Uc.PolyChart()},Uc.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Uc.LinePlot=function(){return Uc.PolyChart()},Uc.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Uc.Legend=function(){var e=Uc.Legend.defaultConfig(),r=t.dispatch("hover");function n(){var r=e.legendConfig,i=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=Vc({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=t.merge(i);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||void 0===r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=t.select(o));var s=a.map(function(t,e){return t.color}),l=r.fontSize,u=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,c=u?r.height:l*a.length,p=o.classed("legend-group",!0).selectAll("svg").data([0]),h=p.enter().append("svg").attr({width:300,height:c+l,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});h.append("g").classed("legend-axis",!0),h.append("g").classed("legend-marks",!0);var f=t.range(a.length),d=t.scale[u?"linear":"ordinal"]().domain(f).range(s),y=t.scale[u?"linear":"ordinal"]().domain(f)[u?"range":"rangePoints"]([0,c]);if(u){var m=p.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);m.enter().append("stop"),m.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),p.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var g=p.select(".legend-marks").selectAll("path.legend-mark").data(a);g.enter().append("path").classed("legend-mark",!0),g.attr({transform:function(t,e){return"translate("+[l/2,y(e)+l/2]+")"},d:function(e,r){var n,i,a,o=e.symbol;return a=3*(i=l),"line"===(n=o)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=t.svg.symbolTypes.indexOf(n)?t.svg.symbol().type(n).size(a)():t.svg.symbol().type("square").size(a)()},fill:function(t,e){return d(e)}}),g.exit().remove()}var v=t.svg.axis().scale(y).orient("right"),_=p.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:l,l/2]+")"}).call(v);return _.selectAll(".domain").style({fill:"none",stroke:"none"}),_.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),_.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),n}return n.config=function(t){return arguments.length?(Vc(e,t),this):e},t.rebind(n,r,"on"),n},Uc.Legend.defaultConfig=function(t,e){return{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:!1}}},Uc.tooltipPanel=function(){var e,r,n,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},a="tooltip-"+Uc.tooltipPanel.uid++,o=10,s=function(){var t=(e=i.container.selectAll("g."+a).data([0])).enter().append("g").classed(a,!0).style({"pointer-events":"none",display:"none"});return n=t.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=t.append("text").attr({dx:i.padding+o,dy:.3*+i.fontSize}),s};return s.text=function(a){var l=t.hsl(i.color).l,u=l>=.5?"#aaa":"white",c=l>=.5?"black":"white",p=a||"";r.style({fill:c,"font-size":i.fontSize+"px"}).text(p);var h=i.padding,f=r.node().getBBox(),d={fill:i.color,stroke:u,"stroke-width":"2px"},y=f.width+2*h+o,m=f.height+2*h;return n.attr({d:"M"+[[o,-m/2],[o,-m/4],[i.hasTick?0:o,0],[o,m/4],[o,m/2],[y,m/2],[y,-m/2]].join("L")+"Z"}).style(d),e.attr({transform:"translate("+[o,-m/2+2*h]+")"}),e.style({display:"block"}),s},s.move=function(t){if(e)return e.attr({transform:"translate("+[t[0],t[1]]+")"}).style({display:"block"}),s},s.hide=function(){if(e)return e.style({display:"none"}),s},s.show=function(){if(e)return e.style({display:"block"}),s},s.config=function(t){return Vc(i,t),s},s},Uc.tooltipPanel.uid=1,Uc.adapter={},Uc.adapter.plotly=function(){var e={convert:function(e,r){var n={};if(e.data&&(n.data=e.data.map(function(t,e){var n=Vc({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,e){Uc.util.translator.apply(null,t.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&e.layout&&"stack"===e.layout.barmode)){var i=Uc.util.duplicates(n.data.map(function(t,e){return t.geometry}));n.data.forEach(function(t,e){var r=i.indexOf(t.geometry);-1!=r&&(n.data[e].groupId=r)})}if(e.layout){var a=Vc({},e.layout);if([[a,["plot_bgcolor"],["backgroundColor"]],[a,["showlegend"],["showLegend"]],[a,["radialaxis"],["radialAxis"]],[a,["angularaxis"],["angularAxis"]],[a.angularaxis,["showline"],["gridLinesVisible"]],[a.angularaxis,["showticklabels"],["labelsVisible"]],[a.angularaxis,["nticks"],["ticksCount"]],[a.angularaxis,["tickorientation"],["tickOrientation"]],[a.angularaxis,["ticksuffix"],["ticksSuffix"]],[a.angularaxis,["range"],["domain"]],[a.angularaxis,["endpadding"],["endPadding"]],[a.radialaxis,["showline"],["gridLinesVisible"]],[a.radialaxis,["tickorientation"],["tickOrientation"]],[a.radialaxis,["ticksuffix"],["ticksSuffix"]],[a.radialaxis,["range"],["domain"]],[a.angularAxis,["showline"],["gridLinesVisible"]],[a.angularAxis,["showticklabels"],["labelsVisible"]],[a.angularAxis,["nticks"],["ticksCount"]],[a.angularAxis,["tickorientation"],["tickOrientation"]],[a.angularAxis,["ticksuffix"],["ticksSuffix"]],[a.angularAxis,["range"],["domain"]],[a.angularAxis,["endpadding"],["endPadding"]],[a.radialAxis,["showline"],["gridLinesVisible"]],[a.radialAxis,["tickorientation"],["tickOrientation"]],[a.radialAxis,["ticksuffix"],["ticksSuffix"]],[a.radialAxis,["range"],["domain"]],[a.font,["outlinecolor"],["outlineColor"]],[a.legend,["traceorder"],["reverseOrder"]],[a,["labeloffset"],["labelOffset"]],[a,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,e){Uc.util.translator.apply(null,t.concat(r))}),r?(void 0!==a.tickLength&&(a.angularaxis.ticklen=a.tickLength,delete a.tickLength),a.tickColor&&(a.angularaxis.tickcolor=a.tickColor,delete a.tickColor)):(a.angularAxis&&void 0!==a.angularAxis.ticklen&&(a.tickLength=a.angularAxis.ticklen),a.angularAxis&&void 0!==a.angularAxis.tickcolor&&(a.tickColor=a.angularAxis.tickcolor)),a.legend&&"boolean"!=typeof a.legend.reverseOrder&&(a.legend.reverseOrder="normal"!=a.legend.reverseOrder),a.legend&&"boolean"==typeof a.legend.traceorder&&(a.legend.traceorder=a.legend.traceorder?"reversed":"normal",delete a.legend.reverseOrder),a.margin&&void 0!==a.margin.t){var o=["t","r","b","l","pad"],s=["top","right","bottom","left","pad"],l={};t.entries(a.margin).forEach(function(t,e){l[s[o.indexOf(t.key)]]=t.value}),a.margin=l}r&&(delete a.needsEndSpacing,delete a.minorTickColor,delete a.minorTicks,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksStep,delete a.angularaxis.rewriteTicks,delete a.angularaxis.nticks,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksStep,delete a.radialaxis.rewriteTicks,delete a.radialaxis.nticks),n.layout=a}return n}};return e};var Zc,Hc=re.extendDeepAll,Gc=Zc={};Gc.framework=function(e){var r,n,i,a,o,s=new function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?Hc(r,n):n,i||(i=jc.Axis()),a=jc.adapter.plotly().convert(r),i.config(a).render(o),e.data=r.data,e.layout=r.layout,Gc.fillLayout(e),r}return l.isPolar=!0,l.svg=function(){return i.svg()},l.getConfig=function(){return r},l.getLiveConfig=function(){return jc.adapter.plotly().convert(i.getLiveConfig(),!0)},l.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},l.setUndoPoint=function(){var t,e,i=this,a=jc.util.cloneJson(r);t=a,e=n,s.add({undo:function(){e&&i(e)},redo:function(){i(t)}}),n=jc.util.cloneJson(a)},l.undo=function(){s.undo()},l.redo=function(){s.redo()},l},Gc.fillLayout=function(e){var r=t.select(e).selectAll(".plot-container"),n=r.selectAll(".svg-container"),i=e.framework&&e.framework.svg&&e.framework.svg(),a={width:800,height:600,paper_bgcolor:Oe.background,_container:r,_paperdiv:n,_paper:i};e._fullLayout=Hc(a,e.layout)};var Wc={};(Wc=jc).manager=Zc;var Xc={},Yc=Dc.enforce,Jc=Dc.clean,Kc=Di,$c=0;function Qc(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){re.error(t)}}function tp(t,e){Qc(t,Oe.combine(e,"white"))}function ep(t,e){t._context||(t._context=re.extendDeep({},x));var r,n,i,a=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function ip(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),np(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&np(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function ap(t,r,n,i,a){!function(t,e,r,n){var i=re.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!re.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var a in np(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,r,n,i);for(var o=function(t,r,n,i){var a,o,s,l,u,c=re.isPlainObject(i),p=[];for(var h in Array.isArray(n)||(n=[n]),n=rp(n,t.data.length-1),r)for(var f=0;f0&&"string"!=typeof b.parts[k-1];)A--;var T=b.parts[A],M=b.parts[A-1]+"."+T,S=b.parts.slice(0,A).join("."),C=re.nestedProperty(t.layout,S).get(),z=re.nestedProperty(o,S).get(),L=b.get();if(void 0!==w){d[x]=w,y[x]="reverse"===T?w:sp(L);var E=Qn.getLayoutValObject(o,b.parts);if(E&&E.impliedEdits&&null!==w)for(var I in E.impliedEdits)m(re.relativeAttr(x,I),E.impliedEdits[I]);if(-1!==["width","height"].indexOf(x)&&null===w)o[x]=t._initialAutoSize[x];else if(M.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))_(M),re.nestedProperty(o,S+"._inputRange").set(null);else if(M.match(/^[xyz]axis[0-9]*\.autorange$/)){_(M),re.nestedProperty(o,S+"._inputRange").set(null);var D=re.nestedProperty(o,S).get();D._inputDomain&&(D._input.domain=D._inputDomain.slice())}else M.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&re.nestedProperty(o,S+"._inputDomain").set(null);if("type"===T){var O=C,R="linear"===z.type&&"log"===w,B="log"===z.type&&"linear"===w;if(R||B){if(O&&O.range)if(z.autorange)R&&(O.range=O.range[1]>O.range[0]?[1,2]:[2,1]);else{var F=O.range[0],N=O.range[1];R?(F<=0&&N<=0&&m(S+".autorange",!0),F<=0?F=N/1e6:N<=0&&(N=F/1e6),m(S+".range[0]",Math.log(F)/Math.LN10),m(S+".range[1]",Math.log(N)/Math.LN10)):(m(S+".range[0]",Math.pow(10,F)),m(S+".range[1]",Math.pow(10,N)))}else m(S+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[b.parts[0]]&&"radialaxis"===b.parts[1]&&delete o[b.parts[0]]._subplot.viewInitial["radialaxis.range"],P.getComponentMethod("annotations","convertCoords")(t,z,w,m),P.getComponentMethod("images","convertCoords")(t,z,w,m)}else m(S+".autorange",!0),m(S+".range",null);re.nestedProperty(o,S+"._inputRange").set(null)}else if(T.match(Ie.AX_NAME_PATTERN)){var j=re.nestedProperty(o,x).get(),V=(w||{}).type;V&&"-"!==V||(V="linear"),P.getComponentMethod("annotations","convertCoords")(t,j,V,m),P.getComponentMethod("images","convertCoords")(t,j,V,m)}var q=du.containerArrayMatch(x);if(q){r=q.array,n=q.index;var U=q.property,Z=(re.nestedProperty(a,r)||[])[n]||{},H=Z,G=E||{editType:"calc"},W=-1!==G.editType.indexOf("calcIfAutorange");""===n?(W?f.calc=!0:yr.update(f,G),W=!1):""===U&&(H=w,du.isAddVal(w)?y[x]=null:du.isRemoveVal(w)?(y[x]=Z,H=Z):re.warn("unrecognized full object value",e)),W&&(pp(t,H,"x")||pp(t,H,"y"))?f.calc=!0:yr.update(f,G),u[r]||(u[r]={});var X=u[r][n];X||(X=u[r][n]={}),X[U]=w,delete e[x]}else"reverse"===T?(C.range?C.range.reverse():(m(S+".autorange",!0),C.range=[1,0]),z.autorange?f.calc=!0:f.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===x&&("lasso"===w||"select"===w)&&"lasso"!==L&&"select"!==L?f.plot=!0:E?yr.update(f,E):f.calc=!0,b.set(w))}}for(r in u){du.applyContainerArrayChanges(t,re.nestedProperty(a,r),u[r],f)||(f.plot=!0)}var Y=o._axisConstraintGroups||[];for(g in v)for(n=0;n=0&&r=0&&r=i.length?i[0]:i[t]:i}function s(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function l(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,mi.transition(t,e.frame.data,e.frame.layout,au.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function p(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var h,f,d=0;function y(t){return Array.isArray(i)?d>=i.length?t.transitionOpts=i[d]:t.transitionOpts=i[0]:t.transitionOpts=i,d++,t}var m=[],g=void 0===e||null===e,v=Array.isArray(e);if(!g&&!v&&re.isPlainObject(e))m.push({type:"object",data:y(re.extendFlat({},e))});else if(g||-1!==["string","number"].indexOf(typeof e))for(h=0;h0&&bb)&&w.push(f);m=w}}m.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(re.isPlainObject(e[n])){var h=e[n].name,f=(l[h]||p[h]||{}).name,d=e[n].name,y=l[f]||p[f];f&&d&&"number"==typeof d&&y&&$c<5&&($c++,re.warn('addFrames: overwriting frame "'+(l[f]||p[f]).name+'" with a frame whose name of type "number" also equates to "'+f+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===$c&&re.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),p[h]={name:h},c.push({frame:mi.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=c[n].frame).name&&re.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;l[i.name="frame "+t._transitionData._counter++];);if(l[i.name]){for(a=0;a=0;r--)n=e[r],a.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:i[n]});var s=mi.modifyFrames,l=mi.modifyFrames,u=[t,o],c=[t,a];return nu&&nu.add(t,s,u,l,c),mi.modifyFrames(t,a)},Xc.purge=function(t){var e=(t=re.getGraphDiv(t))._fullLayout||{},r=t._fullData||[];return mi.cleanPlot([],{},r,e),mi.purge(t),tr.purge(t),e._container&&e._container.remove(),delete t._context,t};var dp={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},yp=Xe.EventEmitter;var mp=function(t){var e=t.emitter||new yp,r=new Promise(function(n,i){var a=window.Image,o=t.svg,s=t.format||"png";if(re.isIE()&&"svg"!==s){var l=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(l),t.promise?r:e.emit("error",l)}var u=t.canvas,c=t.scale||1,p=c*(t.width||300),h=c*(t.height||150),f=u.getContext("2d"),d=new a,y="data:image/svg+xml,"+encodeURIComponent(o);u.width=p,u.height=h,d.onload=function(){var r;switch("svg"!==s&&f.drawImage(d,0,0,p,h),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=y;break;default:var a="Image format is not jpeg, png, svg or webp.";if(i(new Error(a)),!t.promise)return e.emit("error",a)}n(r),t.promise||e.emit("success",r)},d.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},d.src=y});return t.promise?r:e},gp=/"/g,vp=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var _p=function(e,r,n){var i,a=e._fullLayout,o=a._paper,s=a._toppaper,l=a.width,u=a.height;o.insert("rect",":first-child").call(pn.setRect,0,0,l,u).call(Oe.fill,a.paper_bgcolor);var c=a._basePlotModules||[];for(i=0;i")?"":r.html(t).text()});return r.remove(),n}(y),y=(y=y.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(vp,"'"),re.isIE()&&(y=(y=(y=y.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),y},xp={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},bp=/^data:image\/\w+;base64,/;var wp=function(t,e){var r,n,i;function a(t){return!(t in e)||re.validate(e[t],xp[t])}if(e=e||{},re.isPlainObject(t)?(r=t.data||[],n=t.layout||{},i=t.config||{}):(t=re.getGraphDiv(t),r=re.extendDeep([],t.data),n=re.extendDeep({},t.layout),i=t._context),!a("width")||!a("height"))throw new Error("Height and width should be pixel values.");if(!a("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function s(t,r){return re.coerce(e,o,xp,t,r)}var l=s("format"),u=s("width"),c=s("height"),p=s("scale"),h=s("setBackground"),f=s("imageDataOnly"),d=document.createElement("div");d.style.position="absolute",d.style.left="-5000px",document.body.appendChild(d);var y=re.extendFlat({},n);u&&(y.width=u),c&&(y.height=c);var m=re.extendFlat({},i,{staticPlot:!0,setBackground:h}),g=dp.getRedrawFunc(d);function v(){return new Promise(function(t){setTimeout(t,dp.getDelay(d._fullLayout))})}function _(){return new Promise(function(t,e){var r=_p(d,l,p),n=d._fullLayout.width,i=d._fullLayout.height;if(Xc.purge(d),document.body.removeChild(d),"svg"===l)return t(f?r:"data:image/svg+xml,"+encodeURIComponent(r));var a=document.createElement("canvas");a.id=re.randstr(),mp({format:l,width:n,height:i,scale:p,canvas:a,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){Xc.plot(d,r,y,m).then(g).then(v).then(_).then(function(e){t(function(t){return f?t.replace(bp,""):t}(e))}).catch(function(t){e(t)})})},kp=re.isPlainObject,Ap=Array.isArray,Tp=re.isArrayOrTypedArray;function Mp(t,e,r,n,i,a){a=a||[];for(var o=Object.keys(t),s=0;sp.length&&n.push(zp("unused",i,u.concat(p.length)));var m,g,v,_,x,b=p.length,w=Array.isArray(y);if(w&&(b=Math.min(b,y.length)),2===h.dimensions)for(g=0;gp[g].length&&n.push(zp("unused",i,u.concat(g,p[g].length)));var k=p[g].length;for(m=0;m<(w?Math.min(k,y[g].length):k);m++)v=w?y[g][m]:y,_=c[g][m],x=p[g][m],re.validate(_,v)?x!==_&&x!==+_&&n.push(zp("dynamic",i,u.concat(g,m),_,x)):n.push(zp("value",i,u.concat(g,m),_))}else n.push(zp("array",i,u.concat(g),c[g]));else for(g=0;g1&&a.push(zp("object","layout"))),mi.supplyDefaults(o);for(var s=o._fullData,l=r.length,u=0;u-1&&(s[u[r]].title="");for(r=0;r0?u>=m:u<=m));c++)u>v&&u<_&&h.push(u);if("function"==typeof n.fillcolor)if(n.filllevels)for(m=n.filllevels.end+n.filllevels.size/100,g=n.filllevels.size,c=0;c<1e5&&(u=n.filllevels.start+c*g,!(g>0?u>=m:u<=m));c++)u>p[0]&&u1){var q=Math.pow(10,Math.floor(Math.log(V)/Math.LN10));N*=q*re.roundUp(V/q,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(B.tick0=0)}B.dtick=N}B.domain=[I+z,I+M-z],B.setScale();var U=o._infolayer.selectAll("g."+r).data([0]);U.enter().append("g").classed(r,!0).classed(th.colorbar,!0).each(function(){var e=t.select(this);e.append("rect").classed(th.cbbg,!0),e.append("g").classed(th.cbfills,!0),e.append("g").classed(th.cblines,!0),e.append("g").classed(th.cbaxis,!0).classed(th.crisp,!0),e.append("g").classed(th.cbtitleunshift,!0).append("g").classed(th.cbtitle,!0),e.append("rect").classed(th.cboutline,!0),e.select(".cbtitle").datum(0)}),U.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var Z=U.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");B._axislayer=U.select(".cbaxis");var H=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var G,W=l.l+(n.x+S)*l.w,X=B.titlefont.size;G="top"===n.titleside?(1-(I+M-z))*l.h+l.t+3+.75*X:(1-(I+z))*l.h+l.t-3-.25*X,tt(B._id+"title",{attributes:{x:W,y:G,"text-anchor":"start"}})}var Y,J,K,$=re.syncOrAsync([mi.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=U.select(".cbtitle"),i=r.select("text"),a=[-n.outlinewidth/2,n.outlinewidth/2],u=r.select(".h"+B._id+"title-math-group").node(),c=15.6;if(i.node()&&(c=parseInt(i.node().style.fontSize,10)*Qp),u?(H=pn.bBox(u).height)>c&&(a[1]-=(H-c)/2):i.node()&&!i.classed(th.jsPlaceholder)&&(H=pn.bBox(i.node()).height),H){if(H+=5,"top"===n.titleside)B.domain[1]-=H/l.h,a[1]*=-1;else{B.domain[0]+=H/l.h;var m=Fr.lineCount(i);a[1]+=(1-m)*c}r.attr("transform","translate("+a+")"),B.setScale()}}U.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-B.domain[1]))+")"),B._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var g=U.select(".cbfills").selectAll("rect.cbfill").data(f);g.enter().append("rect").classed(th.cbfill,!0).style("stroke","none"),g.exit().remove(),g.each(function(e,r){var n=[0===r?p[0]:(f[r]+f[r-1])/2,r===f.length-1?p[1]:(f[r]+f[r+1])/2].map(B.c2p).map(Math.round);r!==f.length-1&&(n[1]+=n[1]>n[0]?1:-1);var i=y(e).replace("e-",""),a=s(i).toHexString();t.select(this).attr({x:L,width:Math.max(k,2),y:t.min(n),height:Math.max(t.max(n)-t.min(n),2),fill:a})});var v=U.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?h:[]);return v.enter().append("path").classed(th.cbline,!0),v.exit().remove(),v.each(function(e){t.select(this).attr("d","M"+L+","+(Math.round(B.c2p(e))+n.line.width/2%1)+"h"+k).call(pn.lineGroupStyle,n.line.width,d(e),n.line.dash)}),B._axislayer.selectAll("g."+B._id+"tick,path").remove(),B._pos=L+k+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),B.side="right",re.syncOrAsync([function(){return Ki.doTicks(e,B,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=B.titlefont.size,i=B._offset+B._length/2,a=l.l+(B.position||0)*l.w+("right"===B.side?10+r*(B.showticklabels?1:.5):-10-r*(B.showticklabels?.5:0));tt("h"+B._id+"title",{avoid:{selection:t.select(e).selectAll("g."+B._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:a,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},mi.previousPromises,function(){var t=k+n.outlinewidth/2+pn.bBox(B._axislayer.node()).width;if((x=Z.select("text")).node()&&!x.classed(th.jsPlaceholder)){var i,a=Z.select(".h"+B._id+"title-math-group").node();i=a&&-1!==["top","bottom"].indexOf(n.titleside)?pn.bBox(a).width:pn.bBox(Z.node()).right-L-l.l,t=Math.max(t,i)}var o=2*n.xpad+t+n.borderwidth+n.outlinewidth/2,s=D-O;U.select(".cbbg").attr({x:L-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:O-C,width:Math.max(o,2),height:Math.max(s+2*C,2)}).call(Oe.fill,n.bgcolor).call(Oe.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),U.selectAll(".cboutline").attr({x:L,y:O+n.ypad+("top"===n.titleside?H:0),width:Math.max(k,2),height:Math.max(s-2*n.ypad-H,2)}).call(Oe.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var u=({center:.5,right:1}[n.xanchor]||0)*o;U.attr("transform","translate("+(l.l-u)+","+l.t+")"),mi.autoMargin(e,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],e);return $&&$.then&&(e._promises||[]).push($),e._context.edits.colorbarPosition&&rr.init({element:U.node(),gd:e,prepFn:function(){Y=U.attr("transform"),On(U)},moveFn:function(t,e){U.attr("transform",Y+" translate("+t+","+e+")"),J=rr.align(E+t/l.w,A,0,1,n.xanchor),K=rr.align(I-e/l.h,M,0,1,n.yanchor);var r=rr.getCursor(J,K,n.xanchor,n.yanchor);On(U,r)},doneFn:function(){On(U),void 0!==J&&void 0!==K&&P.call("restyle",e,{"colorbar.x":J,"colorbar.y":K},a().index)}}),$}function Q(t,e){return re.coerce(R,B,wr,t,e)}function tt(t,r){var n,i=a();n=P.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var s={propContainer:B,propName:n,traceIndex:i.index,placeholder:o._dfltTitle.colorbar,containerGroup:U.select(".cbtitle")},l="h"===t.charAt(0)?t.substr(1):"h"+t;U.selectAll("."+l+",."+l+"-math-group").remove(),zi.draw(e,t,$p(s,r||{}))}o._infolayer.selectAll("g."+r).remove()}function a(){var t,n,i=r.substr(2);for(t=0;tV||t[1]U)return[dh(t[0],j,V),dh(t[1],q,U)]}function G(t,e){return t[0]===e[0]&&(t[0]===j||t[0]===V)||(t[1]===e[1]&&(t[1]===q||t[1]===U)||void 0)}function W(t,e,r){return function(n,i){var a=H(n),o=H(i),s=[];if(a&&o&&G(a,o))return s;a&&s.push(a),o&&s.push(o);var l=2*re.constrain((n[t]+i[t])/2,e,r)-((a||n)[t]+(o||i)[t]);l&&((a&&o?l>0==a[t]>o[t]?a:o:a||o)[t]+=l);return s}}function X(t){var e=t[0],r=t[1],n=e===S[C-1][0],i=r===S[C-1][1];if(!n||!i)if(C>1){var a=e===S[C-2][0],o=r===S[C-2][1];n&&(e===j||e===V)&&a?o?C--:S[C-1]=t:i&&(r===q||r===U)&&o?a?C--:S[C-1]=t:S[C++]=t}else S[C++]=t}function Y(t){S[C-1][0]!==t[0]&&S[C-1][1]!==t[1]&&X([D,O]),X(t),R=null,D=O=0}function J(t){if(P=t[0]V?V:0,I=t[1]U?U:0,P||I){if(C)if(R){var e=F(R,t);e.length>1&&(Y(e[0]),S[C++]=e[1])}else B=F(S[C-1],t)[0],S[C++]=B;else S[C++]=[P||t[0],I||t[1]];var r=S[C-1];P&&I&&(r[0]!==P||r[1]!==I)?(R&&(D!==P&&O!==I?X(D&&O?(n=R,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?j:V,U]:[o>0?V:j,q]):[D||P,O||I]):D&&O&&X([D,O])),X([P,I])):D-P&&O-I&&X([P||D,I||O]),R=t,D=P,O=I}else R&&Y(F(R,t)[0]),S[C++]=t;var n,i,a,o}for("linear"===k||"spline"===k?F=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var a=Z[i],o=fh(t[0],t[1],e[0],e[1],a[0],a[1],a[2],a[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&E(o,t)L(s))break;i=s,(d=c[0]*u[0]+c[1]*u[1])>h?(h=d,a=s,l=!1):d=t.length||!s)break;J(s),n=s}}else J(a)}R&&X([D||R[0],O||R[1]]),T.push(S.slice(0,C))}return T},mh=Hu.tester;function gh(e,r,n,i,a,o,s){var l,u;!function(e,r,n,i,a){var o=n.xaxis,s=n.yaxis,l=t.extent(re.simpleMap(o.range,o.r2c)),u=t.extent(re.simpleMap(s.range,s.r2c)),c=i[0].trace;if(!cn.hasMarkers(c))return;var p=c.marker.maxdisplayed;if(0===p)return;var h=i.filter(function(t){return t.x>=l[0]&&t.x<=l[1]&&t.y>=u[0]&&t.y<=u[1]}),f=Math.ceil(h.length/p),d=0;a.forEach(function(t,e){var n=t[0].trace;cn.hasMarkers(n)&&n.marker.maxdisplayed>0&&e0;function p(t){return c?t.transition():t}var h=n.xaxis,f=n.yaxis,d=i[0].trace,y=d.line,m=t.select(o);if(P.getComponentMethod("errorbars","plot")(m,n,s),!0===d.visible){var g,v;p(m).style("opacity",d.opacity);var _=d.fill.charAt(d.fill.length-1);"x"!==_&&"y"!==_&&(_=""),i[0].node3=m;var x="",b=[],w=d._prevtrace;w&&(x=w._prevRevpath||"",v=w._nextFill,b=w._polygons);var k,A,T,M,S,C,z,L,E,I="",D="",O=[],R=re.noop;if(g=d._ownFill,cn.hasLines(d)||"none"!==d.fill){for(v&&v.datum(i),-1!==["hv","vh","hvh","vhv"].indexOf(y.shape)?(T=pn.steps(y.shape),M=pn.steps(y.shape.split("").reverse().join(""))):T=M="spline"===y.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?pn.smoothclosed(t.slice(1),y.smoothing):pn.smoothopen(t,y.smoothing)}:function(t){return"M"+t.join("L")},S=function(t){return M(t.reverse())},O=yh(i,{xaxis:h,yaxis:f,connectGaps:d.connectgaps,baseTolerance:Math.max(y.width||1,3)/4,shape:y.shape,simplify:y.simplify}),E=d._polygons=new Array(O.length),u=0;u1){var n=t.select(this);if(n.datum(i),e)p(n.style("opacity",0).attr("d",k).call(pn.lineGroupStyle)).style("opacity",1);else{var a=p(n);a.attr("d",k),pn.singleLineStyle(i,a)}}}}}var B=m.selectAll(".js-line").data(O);p(B.exit()).style("opacity",0).remove(),B.each(R(!1)),B.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(pn.lineGroupStyle).each(R(!0)),pn.setClipUrl(B,n.layerClipId),O.length?(g?C&&L&&(_?("y"===_?C[1]=L[1]=f.c2p(0,!0):"x"===_&&(C[0]=L[0]=h.c2p(0,!0)),p(g).attr("d","M"+L+"L"+C+"L"+I.substr(1)).call(pn.singleFillStyle)):p(g).attr("d",I+"Z").call(pn.singleFillStyle)):v&&("tonext"===d.fill.substr(0,6)&&I&&x?("tonext"===d.fill?p(v).attr("d",I+"Z"+x+"Z").call(pn.singleFillStyle):p(v).attr("d",I+"L"+x.substr(1)+"Z").call(pn.singleFillStyle),d._polygons=d._polygons.concat(b)):(N(v),d._polygons=null)),d._prevRevpath=D,d._prevPolygons=E):(g?N(g):v&&N(v),d._polygons=d._prevRevpath=d._prevPolygons=null);var F=m.selectAll(".points");l=F.data([i]),F.each(Z),l.enter().append("g").classed("points",!0).each(Z),l.exit().remove(),l.each(function(e){var r=!1===e[0].trace.cliponaxis;pn.setClipUrl(t.select(this),r?null:n.layerClipId)})}function N(t){p(t).attr("d","M0,0Z")}function j(t){return t.filter(function(t){return t.vis})}function V(t){return t.id}function q(t){if(t.ids)return V}function U(){return!1}function Z(r){var i,a=r[0].trace,o=t.select(this),s=cn.hasMarkers(a),l=cn.hasText(a),u=q(a),d=U,y=U;s&&(d=a.marker.maxdisplayed||a._needsCull?j:re.identity),l&&(y=a.marker.maxdisplayed||a._needsCull?j:re.identity);var m=(i=o.selectAll("path.point").data(d,u)).enter().append("path").classed("point",!0);c&&m.call(pn.pointStyle,a,e).call(pn.translatePoints,h,f).style("opacity",0).transition().style("opacity",1);var g=s&&pn.tryColorscale(a.marker,""),v=s&&pn.tryColorscale(a.marker,"line");i.order(),i.each(function(r){var i=t.select(this),o=p(i);pn.translatePoint(r,o,h,f)?(pn.singlePointStyle(r,o,a,g,v,e),n.layerClipId&&pn.hideOutsideRangePoint(r,o,h,f,a.xcalendar,a.ycalendar),a.customdata&&i.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),c?i.exit().transition().style("opacity",0).remove():i.exit().remove(),(i=o.selectAll("g").data(y,u)).enter().append("g").classed("textpoint",!0).append("text"),i.order(),i.each(function(e){var r=t.select(this),i=p(r.select("text"));pn.translatePoint(e,i,h,f)?n.layerClipId&&pn.hideOutsideRangePoint(e,r,h,f,a.xcalendar,a.ycalendar):r.remove()}),i.selectAll("text").call(pn.textPointStyle,a,e).each(function(e){var r=h.c2p(e.x),n=f.c2p(e.y);t.select(this).selectAll("tspan.line").each(function(){p(t.select(this)).attr({x:r,y:n})})}),i.exit().remove()}}function vh(t,e,r){var n=t.selectAll("path.point"),i=t.selectAll("text");pn.pointStyle(n,e,r),pn.textPointStyle(i,e,r),pn.selectedPointStyle(n,e),pn.selectedTextStyle(i,e)}var _h=function(e,r){var n=r?r[0].node3:t.select(e).selectAll("g.trace.scatter");n.style("opacity",function(t){return t[0].trace.opacity}),n.selectAll("g.points").each(function(r){vh(t.select(this),r.trace||r[0].trace,e)}),n.selectAll("g.trace path.js-line").call(pn.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(pn.fillGroupStyle),P.getComponentMethod("errorbars","style")(n)},xh={};xh.hasLines=cn.hasLines,xh.hasMarkers=cn.hasMarkers,xh.hasText=cn.hasText,xh.isBubble=cn.isBubble,xh.attributes=Hn,xh.supplyDefaults=function(t,e,r,n){function i(r,n){return re.coerce(t,e,Hn,r,n)}var a=function(t,e,r,n){var i,a=n("x"),o=n("y");if(P.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),a)o?i=Math.min(a.length,o.length):(i=a.length,n("y0"),n("dy"));else{if(!o)return 0;i=e.y.length,n("x0"),n("dx")}return e._length=i,i}(t,e,n,i),o=a=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}},xh.calc=Kp,xh.arraysToCalcdata=Zp,xh.plot=function(e,r,n,i,a){var o,s,l,u,c=r.plot.select("g.scatterlayer"),p=!i,h=!!i&&i.duration>0;for((l=c.selectAll("g.trace").data(n,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),function(t,e,r){var n,i,a=null;for(i=0;is[e[0].trace.uid]?1:-1}),h?(a&&(u=a()),t.transition().duration(i.duration).ease(i.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(t,a){gh(e,a,r,t,n,this,i)})})):c.selectAll("g.trace").each(function(t,a){gh(e,a,r,t,n,this,i)});p&&l.exit().remove(),c.selectAll("path:not([d])").remove()},xh.colorbar=eh,xh.style=_h,xh.hoverPoints=function(t,e,r,n){var i=t.cd,a=i[0].trace,o=t.xa,s=t.ya,l=o.c2p(e),u=s.c2p(r),c=[l,u],p=a.hoveron||"",h=-1!==a.mode.indexOf("markers")?3:.5;if(-1!==p.indexOf("points")){var f=function(t){var e=Math.max(h,t.mrc||0),r=o.c2p(t.x)-l,n=s.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-h/e)},d=Ga.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-l);return nR!=(S=w[x][1])>=R&&(A=w[x-1][0],T=w[x][0],S-M&&(k=A+(T-A)*(R-M)/(S-M),E=Math.min(E,k),I=Math.max(I,k)));E=Math.max(E,0),I=Math.min(I,o._length);var B=Oe.defaultLine;return Oe.opacity(a.fillcolor)?B=a.fillcolor:Oe.opacity((a.line||{}).color)&&(B=a.line.color),re.extendFlat(t,{distance:t.maxHoverDistance,x0:E,x1:I,y0:R,y1:R,color:B}),delete t.index,a.text&&!Array.isArray(a.text)?t.text=String(a.text):t.text=a.name,[t]}}},xh.selectPoints=function(t,e){var r,n,i,a,o=t.cd,s=t.xaxis,l=t.yaxis,u=[],c=o[0].trace;if(!cn.hasMarkers(c)&&!cn.hasText(c))return[];if(!1===e)for(r=0;r0){e+=Math.abs(i(t[0]));for(var r=1;r2){for(l=0;li.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(o=i.maxw*i.maxh-t*r)a.free)){if(r===a.h)return this.allocShelf(s,t,r,n);r>a.h||rc)&&(p=2*Math.max(t,c)),(ll)&&(u=2*Math.max(r,l)),this.resize(p,u),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;rthis.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,a,o){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=a||n,this.maxh=o||i,this.refcount=0}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t},"object"==typeof r&&void 0!==e?e.exports=i():n.ShelfPack=i()},{}],6:[function(t,e,r){function n(t,e,r,n,i,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=i||"sans-serif",this.fontWeight=a||"normal",this.radius=r||8;var o=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=o,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(o*o),this.gridInner=new Float64Array(o*o),this.f=new Float64Array(o),this.d=new Float64Array(o),this.z=new Float64Array(o+1),this.v=new Int16Array(o),this.middle=Math.round(o/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1))}function i(t,e,r,n,i,o,s){for(var l=0;ln)return n;for(;ra?r=i:n=i,i=.5*(n-r)+r}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},{}],8:[function(t,e,r){e.exports.VectorTile=t("./lib/vectortile.js"),e.exports.VectorTileFeature=t("./lib/vectortilefeature.js"),e.exports.VectorTileLayer=t("./lib/vectortilelayer.js")},{"./lib/vectortile.js":9,"./lib/vectortilefeature.js":10,"./lib/vectortilelayer.js":11}],9:[function(t,e,r){function n(t,e,r){if(3===t){var n=new i(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n)}}var i=t("./vectortilelayer");e.exports=function(t,e){this.layers=t.readFields(n,{},e)}},{"./vectortilelayer":11}],10:[function(t,e,r){function n(t,e,r,n,a){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=a,t.readFields(i,this,e)}function i(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3}if(i--,1===n||2===n)a+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&l.push(e),e=[]),e.push(new o(a,s));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone())}}return e&&l.push(e),l},n.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,l=1/0,u=-1/0;t.pos>3}if(n--,1===r||2===r)i+=t.readSVarint(),a+=t.readSVarint(),is&&(s=i),au&&(u=a);else if(7!==r)throw new Error("unknown command "+r)}return[o,l,s,u]},n.prototype.toGeoJSON=function(t,e,r){function i(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}var a=t("./vectortilefeature.js");e.exports=n,n.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new a(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":10}],12:[function(t,e,r){var n;n=this,function(t){function e(t,e,n){var i=r(256*t,256*(e=Math.pow(2,n)-e-1),n),a=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+a[0]+","+a[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return[t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}t.getURL=function(t,r,n,i,a,o){return o=o||{},t+"?"+["bbox="+e(n,i,a),"format="+(o.format||"image/png"),"service="+(o.service||"WMS"),"version="+(o.version||"1.1.1"),"request="+(o.request||"GetMap"),"srs="+(o.srs||"EPSG:3857"),"width="+(o.width||256),"height="+(o.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.WhooTS=n.WhooTS||{})},{}],13:[function(t,e,r){function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return function(t){return t<0?0:t>1?1:t}("%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}var s={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};try{r.parseCSSColor=function(t){var e,r=t.replace(/ /g,"").toLowerCase();if(r in s)return s[r].slice();if("#"===r[0])return 4===r.length?(e=parseInt(r.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===r.length&&(e=parseInt(r.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var l=r.indexOf("("),u=r.indexOf(")");if(-1!==l&&u+1===r.length){var c=r.substr(0,l),p=r.substr(l+1,u-(l+1)).split(","),h=1;switch(c){case"rgba":if(4!==p.length)return null;h=a(p.pop());case"rgb":return 3!==p.length?null:[i(p[0]),i(p[1]),i(p[2]),h];case"hsla":if(4!==p.length)return null;h=a(p.pop());case"hsl":if(3!==p.length)return null;var f=(parseFloat(p[0])%360+360)%360/360,d=a(p[1]),y=a(p[2]),m=y<=.5?y*(d+1):y+d-y*d,g=2*y-m;return[n(255*o(g,m,f+1/3)),n(255*o(g,m,f)),n(255*o(g,m,f-1/3)),h];default:return null}}return null}}catch(t){}},{}],14:[function(t,e,r){function n(t,e,r){r=r||2;var n,s,l,u,c,f,y,m=e&&e.length,g=m?e[0]*r:t.length,v=i(t,0,g,r,!0),_=[];if(!v)return _;if(m&&(v=function(t,e,r,n){var o,s,l,u,c,f=[];for(o=0,s=e.length;o80*r){n=l=t[0],s=u=t[1];for(var x=r;xl&&(l=c),f>u&&(u=f);y=0!==(y=Math.max(l-n,u-s))?1/y:0}return o(v,_,r,n,s,y),_}function i(t,e,r,n,i){var a,o;if(i===T(t,e,r,n)>0)for(a=e;a=e;a-=n)o=w(a,t[a],t[a+1],o);return o&&v(o,o.next)&&(k(o),o=o.next),o}function a(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!v(n,n.next)&&0!==g(n.prev,n,n.next))n=n.next;else{if(k(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function o(t,e,r,n,i,p,h){if(t){!h&&p&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=f(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,u=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,u*=2}while(o>1)}(i)}(t,n,i,p);for(var d,y,m=t;t.prev!==t.next;)if(d=t.prev,y=t.next,p?l(t,n,i,p):s(t))e.push(d.i/r),e.push(t.i/r),e.push(y.i/r),k(t),t=y.next,m=y.next;else if((t=y)===m){h?1===h?o(t=u(t,e,r),e,r,n,i,p,2):2===h&&c(t,e,r,n,i,p):o(a(t),e,r,n,i,p,1);break}}}function s(t){var e=t.prev,r=t,n=t.next;if(g(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(y(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&g(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function l(t,e,r,n){var i=t.prev,a=t,o=t.next;if(g(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,c=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,p=f(s,l,e,r,n),h=f(u,c,e,r,n),d=t.prevZ,m=t.nextZ;d&&d.z>=p&&m&&m.z<=h;){if(d!==t.prev&&d!==t.next&&y(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&g(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,m!==t.prev&&m!==t.next&&y(i.x,i.y,a.x,a.y,o.x,o.y,m.x,m.y)&&g(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;d&&d.z>=p;){if(d!==t.prev&&d!==t.next&&y(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&g(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;m&&m.z<=h;){if(m!==t.prev&&m!==t.next&&y(i.x,i.y,a.x,a.y,o.x,o.y,m.x,m.y)&&g(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0}function u(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!v(i,a)&&_(i,n,n.next,a)&&x(i,a)&&x(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),k(n),k(n.next),n=t=a),n=n.next}while(n!==t);return n}function c(t,e,r,n,i,s){var l=t;do{for(var u=l.next.next;u!==l.prev;){if(l.i!==u.i&&m(l,u)){var c=b(l,u);return l=a(l,l.next),c=a(c,c.next),o(l,e,r,n,i,s),void o(c,e,r,n,i,s)}u=u.next}l=l.next}while(l!==t)}function p(t,e){return t.x-e.x}function h(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&i!==n.x&&y(ar.x)&&x(n,t)&&(r=n,h=l),n=n.next;return r}(t,e)){var r=b(e,t);a(r,r.next)}}function f(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function m(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&_(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&x(t,e)&&x(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function g(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function v(t,e){return t.x===e.x&&t.y===e.y}function _(t,e,r,n){return!!(v(t,e)&&v(r,n)||v(t,n)&&v(r,e))||g(t,e,r)>0!=g(t,e,n)>0&&g(r,n,t)>0!=g(r,n,e)>0}function x(t,e){return g(t.prev,t,t.next)<0?g(t,e,t.next)>=0&&g(t,t.prev,e)>=0:g(t,e,t.prev)<0||g(t,t.next,e)<0}function b(t,e){var r=new A(t.i,t.x,t.y),n=new A(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function w(t,e,r,n){var i=new A(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function k(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function A(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function T(t,e,r,n){for(var i=0,a=e,o=r-n;a0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],15:[function(t,e,r){function n(t,e){return function(r){return t(r,e)}}function i(t,e){e=!!e,t[0]=a(t[0],e);for(var r=1;r=0}(t)===e?t:t.reverse()}var o=t("@mapbox/geojson-area");e.exports=function t(e,r){switch(e&&e.type||null){case"FeatureCollection":return e.features=e.features.map(n(t,r)),e;case"Feature":return e.geometry=t(e.geometry,r),e;case"Polygon":case"MultiPolygon":return function(t,e){return"Polygon"===t.type?t.coordinates=i(t.coordinates,e):"MultiPolygon"===t.type&&(t.coordinates=t.coordinates.map(n(i,e))),t}(e,r);default:return e}}},{"@mapbox/geojson-area":1}],16:[function(t,e,r){function n(t,e,r,n,i){for(var a=0;a=r&&o<=n&&(e.push(t[a]),e.push(t[a+1]),e.push(t[a+2]))}}function i(t,e,r,n,i,a){for(var u=[],c=0===i?s:l,p=0;p=r&&c(u,h,f,y,m,r):g>n?v<=n&&c(u,h,f,y,m,n):o(u,h,f,d),v=r&&(c(u,h,f,y,m,r),_=!0),v>n&&g<=n&&(c(u,h,f,y,m,n),_=!0),!a&&_&&(u.size=t.size,e.push(u),u=[])}var x=t.length-3;h=t[x],f=t[x+1],d=t[x+2],(g=0===i?h:f)>=r&&g<=n&&o(u,h,f,d),x=u.length-3,a&&x>=3&&(u[x]!==u[0]||u[x+1]!==u[1])&&o(u,u[0],u[1],u[2]),u.length&&(u.size=t.size,e.push(u))}function a(t,e,r,n,a,o){for(var s=0;s=(r/=e)&&c<=o)return t;if(l>o||c=r&&g<=o)p.push(f);else if(!(m>o||g0&&(o+=n?(i*h-p*a)/2:Math.sqrt(Math.pow(p-i,2)+Math.pow(h-a,2))),i=p,a=h}var f=e.length-3;e[2]=1,u(e,0,f,r),e[f+2]=1,e.size=Math.abs(o)}function o(t,e,r,n){for(var i=0;i1?1:r}e.exports=function(t,e){var r=[];if("FeatureCollection"===t.type)for(var i=0;i24)throw new Error("maxZoom should be in the 0-24 range");var n=1<1&&console.time("creation"),y=this.tiles[d]=u(t,f,r,n,m,e===p.maxZoom),this.tileCoords.push({z:e,x:r,y:n}),h)){h>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,y.numFeatures,y.numPoints,y.numSimplified),console.timeEnd("creation"));var g="z"+e;this.stats[g]=(this.stats[g]||0)+1,this.total++}if(y.source=t,a){if(e===p.maxZoom||e===a)continue;var v=1<1&&console.time("clipping");var _,x,b,w,k,A,T=.5*p.buffer/p.extent,M=.5-T,S=.5+T,C=1+T;_=x=b=w=null,k=s(t,f,r-T,r+S,0,y.minX,y.maxX),A=s(t,f,r+M,r+C,0,y.minX,y.maxX),t=null,k&&(_=s(k,f,n-T,n+S,1,y.minY,y.maxY),x=s(k,f,n+M,n+C,1,y.minY,y.maxY),k=null),A&&(b=s(A,f,n-T,n+S,1,y.minY,y.maxY),w=s(A,f,n+M,n+C,1,y.minY,y.maxY),A=null),h>1&&console.timeEnd("clipping"),c.push(_||[],e+1,2*r,2*n),c.push(x||[],e+1,2*r,2*n+1),c.push(b||[],e+1,2*r+1,2*n),c.push(w||[],e+1,2*r+1,2*n+1)}}},n.prototype.getTile=function(t,e,r){var n=this.options,a=n.extent,s=n.debug;if(t<0||t>24)return null;var l=1<1&&console.log("drilling down to z%d-%d-%d",t,e,r);for(var c,p=t,h=e,f=r;!c&&p>0;)p--,h=Math.floor(h/2),f=Math.floor(f/2),c=this.tiles[i(p,h,f)];return c&&c.source?(s>1&&console.log("found parent tile z%d-%d-%d",p,h,f),s>1&&console.time("drilling down"),this.splitTile(c.source,p,h,f,t,e,r),s>1&&console.timeEnd("drilling down"),this.tiles[u]?o.tile(this.tiles[u],a):null):null}},{"./clip":16,"./convert":17,"./tile":21,"./transform":22,"./wrap":23}],20:[function(t,e,r){function n(t,e,r,n,i,a){var o=i-r,s=a-n;if(0!==o||0!==s){var l=((t-r)*o+(e-n)*s)/(o*o+s*s);l>1?(r=i,n=a):l>0&&(r+=o*l,n+=s*l)}return(o=t-r)*o+(s=e-n)*s}e.exports=function t(e,r,i,a){for(var o,s=a,l=e[r],u=e[r+1],c=e[i],p=e[i+1],h=r+3;hs&&(o=h,s=f)}s>a&&(o-r>3&&t(e,r,o,a),e[o+2]=s,i-o>3&&t(e,o,i,a))}},{}],21:[function(t,e,r){function n(t,e,r,n){var a=e.geometry,o=e.type,s=[];if("Point"===o||"MultiPoint"===o)for(var l=0;ls)&&(r.numSimplified++,l.push(e[u]),l.push(e[u+1])),r.numPoints++;a&&function(t,e){for(var r=0,n=0,i=t.length,a=i-2;n0===e)for(n=0,i=t.length;ns.maxX&&(s.maxX=p),h>s.maxY&&(s.maxY=h)}return s}},{}],22:[function(t,e,r){function n(t,e,r,n,i,a){return[Math.round(r*(t*n-i)),Math.round(r*(e*n-a))]}r.tile=function(t,e){if(t.transformed)return t;var r,i,a,o=t.z2,s=t.x,l=t.y;for(r=0;r=u[h+0]&&n>=u[h+1]?(o[p]=!0,a.push(l[p])):o[p]=!1}}},n.prototype._forEachCell=function(t,e,r,n,i,a,o){for(var s=this._convertToCellCoord(t),l=this._convertToCellCoord(e),u=this._convertToCellCoord(r),c=this._convertToCellCoord(n),p=s;p<=u;p++)for(var h=l;h<=c;h++){var f=this.d*h+p;if(i.call(this,t,e,r,n,f,a,o))return}},n.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},n.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=i+this.cells.length+1+1,r=0,n=0;n>1,c=-7,p=r?i-1:0,h=r?-1:1,f=t[e+p];for(p+=h,a=f&(1<<-c)-1,f>>=-c,c+=s;c>0;a=256*a+t[e+p],p+=h,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+p],p+=h,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=u}return(f?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+p>=1?h/l:h*Math.pow(2,1-p))*l>=2&&(o++,l/=2),o+p>=c?(s=0,o=c):o+p>=1?(s=(e*l-1)*Math.pow(2,i),o+=p):(s=e*Math.pow(2,p-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&s,f+=d,s/=256,i-=8);for(o=o<0;t[r+f]=255&o,f+=d,o/=256,u-=8);t[r+f-d]|=128*y}},{}],26:[function(t,e,r){function n(t,e,r,n,s){e=e||i,r=r||a,s=s||Array,this.nodeSize=n||64,this.points=t,this.ids=new s(t.length),this.coords=new s(2*t.length);for(var l=0;l=r&&s<=i&&l>=n&&l<=a&&c.push(t[d]);else{var y=Math.floor((f+h)/2);s=e[2*y],l=e[2*y+1],s>=r&&s<=i&&l>=n&&l<=a&&c.push(t[y]);var m=(p+1)%2;(0===p?r<=s:n<=l)&&(u.push(f),u.push(y-1),u.push(m)),(0===p?i>=s:a>=l)&&(u.push(y+1),u.push(h),u.push(m))}}return c}},{}],28:[function(t,e,r){function n(t,e,r,n){i(t,r,n),i(e,2*r,2*n),i(e,2*r+1,2*n+1)}function i(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}e.exports=function t(e,r,i,a,o,s){if(!(o-a<=i)){var l=Math.floor((a+o)/2);(function t(e,r,i,a,o,s){for(;o>a;){if(o-a>600){var l=o-a+1,u=i-a+1,c=Math.log(l),p=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*p*(l-p)/l)*(u-l/2<0?-1:1);t(e,r,i,Math.max(a,Math.floor(i-u*p/l+h)),Math.min(o,Math.floor(i+(l-u)*p/l+h)),s)}var f=r[2*i+s],d=a,y=o;for(n(e,r,a,i),r[2*o+s]>f&&n(e,r,a,o);df;)y--}r[2*a+s]===f?n(e,r,a,y):n(e,r,++y,o),y<=i&&(a=y+1),i<=y&&(o=y-1)}})(e,r,l,a,o,s%2),t(e,r,i,a,l-1,s+1),t(e,r,i,l+1,o,s+1)}}},{}],29:[function(t,e,r){function n(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}e.exports=function(t,e,r,i,a,o){for(var s=[0,t.length-1,0],l=[],u=a*a;s.length;){var c=s.pop(),p=s.pop(),h=s.pop();if(p-h<=o)for(var f=h;f<=p;f++)n(e[2*f],e[2*f+1],r,i)<=u&&l.push(t[f]);else{var d=Math.floor((h+p)/2),y=e[2*d],m=e[2*d+1];n(y,m,r,i)<=u&&l.push(t[d]);var g=(c+1)%2;(0===c?r-a<=y:i-a<=m)&&(s.push(h),s.push(d-1),s.push(g)),(0===c?r+a>=y:i+a>=m)&&(s.push(d+1),s.push(p),s.push(g))}}return l}},{}],30:[function(t,e,r){function n(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}function i(t){return t.type===n.Bytes?t.readVarint()+t.pos:t.pos+1}function a(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function o(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}function s(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24}function v(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}e.exports=n;var _=t("ieee754");n.Varint=0,n.Fixed64=1,n.Bytes=2,n.Fixed32=5;n.prototype={destroy:function(){this.buf=null},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=m(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=m(this.buf,this.pos)+4294967296*m(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=m(this.buf,this.pos)+4294967296*v(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=_.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=_.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,o=r.buf;if(n=(112&(i=o[r.pos++]))>>4,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<3,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<10,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<17,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<24,i<128)return a(t,n,e);if(n|=(1&(i=o[r.pos++]))<<31,i<128)return a(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(a=t[i+1]))&&(u=(31&l)<<6|63&a)<=127&&(u=null):3===c?(a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&((u=(15&l)<<12|(63&a)<<6|63&o)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&((u=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=i(this);for(t=t||[];this.pos127;);else if(e===n.Bytes)this.pos=this.readVarint()+this.pos;else if(e===n.Fixed32)this.pos+=4;else{if(e!==n.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128)}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&o(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(t){this.realloc(4),_.write(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),_.write(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&o(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,n.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){this.writeMessage(t,s,e)},writePackedSVarint:function(t,e){this.writeMessage(t,l,e)},writePackedBoolean:function(t,e){this.writeMessage(t,p,e)},writePackedFloat:function(t,e){this.writeMessage(t,u,e)},writePackedDouble:function(t,e){this.writeMessage(t,c,e)},writePackedFixed32:function(t,e){this.writeMessage(t,h,e)},writePackedSFixed32:function(t,e){this.writeMessage(t,f,e)},writePackedFixed64:function(t,e){this.writeMessage(t,d,e)},writePackedSFixed64:function(t,e){this.writeMessage(t,y,e)},writeBytesField:function(t,e){this.writeTag(t,n.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,n.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,n.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,n.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}}},{ieee754:25}],31:[function(t,e,r){function n(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function i(t,e){return te?1:0}e.exports=function t(e,r,a,o,s){for(a=a||0,o=o||e.length-1,s=s||i;o>a;){if(o-a>600){var l=o-a+1,u=r-a+1,c=Math.log(l),p=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*p*(l-p)/l)*(u-l/2<0?-1:1);t(e,r,Math.max(a,Math.floor(r-u*p/l+h)),Math.min(o,Math.floor(r+(l-u)*p/l+h)),s)}var f=e[r],d=a,y=o;for(n(e,a,r),s(e[o],f)>0&&n(e,a,o);d0;)y--}0===s(e[a],f)?n(e,a,y):n(e,++y,o),y<=r&&(a=y+1),r<=y&&(o=y-1)}}},{}],32:[function(t,e,r){function n(t){this.options=c(Object.create(this.options),t),this.trees=new Array(this.options.maxZoom+1)}function i(t,e,r,n,i){return{x:t,y:e,zoom:1/0,id:n,properties:i,parentId:-1,numPoints:r}}function a(t,e){var r=t.geometry.coordinates;return{x:l(r[0]),y:u(r[1]),zoom:1/0,id:e,parentId:-1}}function o(t){return{type:"Feature",properties:s(t),geometry:{type:"Point",coordinates:[function(t){return 360*(t-.5)}(t.x),function(t){var e=(180-360*t)*Math.PI/180;return 360*Math.atan(Math.exp(e))/Math.PI-90}(t.y)]}}}function s(t){var e=t.numPoints,r=e>=1e4?Math.round(e/1e3)+"k":e>=1e3?Math.round(e/100)/10+"k":e;return c(c({},t.properties),{cluster:!0,cluster_id:t.id,point_count:e,point_count_abbreviated:r})}function l(t){return t/360+.5}function u(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function c(t,e){for(var r in e)t[r]=e[r];return t}function p(t){return t.x}function h(t){return t.y}var f=t("kdbush");e.exports=function(t){return new n(t)},n.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(t){return t}},load:function(t){var e=this.options.log;e&&console.time("total time");var r="prepare "+t.length+" points";e&&console.time(r),this.points=t;var n=t.map(a);e&&console.timeEnd(r);for(var i=this.options.maxZoom;i>=this.options.minZoom;i--){var o=+Date.now();this.trees[i+1]=f(n,p,h,this.options.nodeSize,Float32Array),n=this._cluster(n,i),e&&console.log("z%d: %d clusters in %dms",i,n.length,+Date.now()-o)}return this.trees[this.options.minZoom]=f(n,p,h,this.options.nodeSize,Float32Array),e&&console.timeEnd("total time"),this},getClusters:function(t,e){for(var r=this.trees[this._limitZoom(e)],n=r.range(l(t[0]),u(t[3]),l(t[2]),u(t[1])),i=[],a=0;a0)for(var r=this.length>>1;r>=0;r--)this._down(r)}function i(t,e){return te?1:0}e.exports=n,n.prototype={push:function(t){this.data.push(t),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var t=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),t}},peek:function(){return this.data[0]},_up:function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i}e[t]=n},_down:function(t){for(var e=this.data,r=this.compare,n=this.length,i=n>>1,a=e[t];t=0)break;e[t]=l,t=o}e[t]=a}}},{}],34:[function(t,e,r){function n(t){var e=new p;return function(t,e){for(var r in t.layers)e.writeMessage(3,i,t.layers[r])}(t,e),e.finish()}function i(t,e){e.writeVarintField(15,t.version||1),e.writeStringField(1,t.name||""),e.writeVarintField(5,t.extent||4096);var r,n={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function u(t,e){for(var r=t.loadGeometry(),n=t.type,i=0,a=0,o=r.length,u=0;u=c||p<0||p>=c)){var h=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray),f=h.vertexLength;n(r.layoutVertexArray,u,p,-1,-1),n(r.layoutVertexArray,u,p,1,-1),n(r.layoutVertexArray,u,p,1,1),n(r.layoutVertexArray,u,p,-1,1),r.indexArray.emplaceBack(f,f+1,f+2),r.indexArray.emplaceBack(f,f+3,f+2),h.vertexLength+=4,h.primitiveLength+=2}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},p("CircleBucket",h,{omit:["layers"]}),e.exports=h},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./circle_attributes":41}],43:[function(t,e,r){arguments[4][41][0].apply(r,arguments)},{"../../util/struct_array":271,dup:41}],44:[function(t,e,r){var n=t("../array_types").FillLayoutArray,i=t("./fill_attributes").members,a=t("../segment").SegmentVector,o=t("../program_configuration").ProgramConfigurationSet,s=t("../index_array_type"),l=s.LineIndexArray,u=s.TriangleIndexArray,c=t("../load_geometry"),p=t("earcut"),h=t("../../util/classify_rings"),f=t("../../util/web_worker_transfer").register,d=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new n,this.indexArray=new u,this.indexArray2=new l,this.programConfigurations=new o(i,t.layers,t.zoom),this.segments=new a,this.segments2=new a};d.prototype.populate=function(t,e){for(var r=this,n=0,i=t;nd)||t.y===e.y&&(t.y<0||t.y>d)}function a(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>d})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>d})}var o=t("../array_types").FillExtrusionLayoutArray,s=t("./fill_extrusion_attributes").members,l=t("../segment"),u=l.SegmentVector,c=l.MAX_VERTEX_ARRAY_LENGTH,p=t("../program_configuration").ProgramConfigurationSet,h=t("../index_array_type").TriangleIndexArray,f=t("../load_geometry"),d=t("../extent"),y=t("earcut"),m=t("../../util/classify_rings"),g=t("../../util/web_worker_transfer").register,v=Math.pow(2,13),_=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new o,this.indexArray=new h,this.programConfigurations=new p(s,t.layers,t.zoom),this.segments=new u};_.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=1){var w=v[x-1];if(!i(b,w)){f.vertexLength+4>c&&(f=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray));var k=b.sub(w)._perp()._unit(),A=w.dist(b);_+A>32768&&(_=0),n(r.layoutVertexArray,b.x,b.y,k.x,k.y,0,0,_),n(r.layoutVertexArray,b.x,b.y,k.x,k.y,0,1,_),_+=A,n(r.layoutVertexArray,w.x,w.y,k.x,k.y,0,0,_),n(r.layoutVertexArray,w.x,w.y,k.x,k.y,0,1,_);var T=f.vertexLength;r.indexArray.emplaceBack(T,T+1,T+2),r.indexArray.emplaceBack(T+1,T+2,T+3),f.vertexLength+=4,f.primitiveLength+=2}}}}f.vertexLength+u>c&&(f=r.segments.prepareSegment(u,r.layoutVertexArray,r.indexArray));for(var M=[],S=[],C=f.vertexLength,z=0,L=l;z>6)}var i=t("../array_types").LineLayoutArray,a=t("./line_attributes").members,o=t("../segment").SegmentVector,s=t("../program_configuration").ProgramConfigurationSet,l=t("../index_array_type").TriangleIndexArray,u=t("../load_geometry"),c=t("../extent"),p=t("@mapbox/vector-tile").VectorTileFeature.types,h=t("../../util/web_worker_transfer").register,f=63,d=Math.cos(Math.PI/180*37.5),y=.5,m=Math.pow(2,14)/y,g=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new i,this.indexArray=new l,this.programConfigurations=new s(a,t.layers,t.zoom),this.segments=new o};g.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=2&&t[l-1].equals(t[l-2]);)l--;for(var u=0;uu){var E=m.dist(w);if(E>2*h){var P=m.sub(m.sub(w)._mult(h/E)._round());o.distance+=P.dist(w),o.addCurrentVertex(P,o.distance,A.mult(1),0,0,!1,y),w=P}}var I=w&&k,D=I?r:k?_:x;if(I&&"round"===D&&(zi&&(D="bevel"),"bevel"===D&&(z>2&&(D="flipbevel"),z100)S=T.clone().mult(-1);else{var O=A.x*T.y-A.y*T.x>0?-1:1,R=z*A.add(T).mag()/A.sub(T).mag();S._perp()._mult(R*O)}o.addCurrentVertex(m,o.distance,S,0,0,!1,y),o.addCurrentVertex(m,o.distance,S.mult(-1),0,0,!1,y)}else if("bevel"===D||"fakeround"===D){var B=A.x*T.y-A.y*T.x>0,F=-Math.sqrt(z*z-1);if(B?(v=0,g=F):(g=0,v=F),b||o.addCurrentVertex(m,o.distance,A,g,v,!1,y),"fakeround"===D){for(var N=Math.floor(8*(.5-(C-.5))),j=void 0,V=0;V=0;q--)j=A.mult((q+1)/(N+1))._add(T)._unit(),o.addPieSliceVertex(m,o.distance,j,B,y)}k&&o.addCurrentVertex(m,o.distance,T,-g,-v,!1,y)}else"butt"===D?(b||o.addCurrentVertex(m,o.distance,A,0,0,!1,y),k&&o.addCurrentVertex(m,o.distance,T,0,0,!1,y)):"square"===D?(b||(o.addCurrentVertex(m,o.distance,A,1,1,!1,y),o.e1=o.e2=-1),k&&o.addCurrentVertex(m,o.distance,T,-1,-1,!1,y)):"round"===D&&(b||(o.addCurrentVertex(m,o.distance,A,0,0,!1,y),o.addCurrentVertex(m,o.distance,A,1,1,!0,y),o.e1=o.e2=-1),k&&(o.addCurrentVertex(m,o.distance,T,-1,-1,!0,y),o.addCurrentVertex(m,o.distance,T,0,0,!1,y)));if(L&&M2*h){var Z=m.add(k.sub(m)._mult(h/U)._round());o.distance+=Z.dist(m),o.addCurrentVertex(Z,o.distance,T.mult(1),0,0,!1,y),m=Z}}b=!1}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e)}},g.prototype.addCurrentVertex=function(t,e,r,i,a,o,s){var l,u=this.layoutVertexArray,c=this.indexArray;l=r.clone(),i&&l._sub(r.perp()._mult(i)),n(u,t,l,o,!1,i,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,l=r.mult(-1),a&&l._sub(r.perp()._mult(a)),n(u,t,l,o,!0,-a,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>m/2&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,i,a,o,s))},g.prototype.addPieSliceVertex=function(t,e,r,i,a){r=r.mult(i?-1:1);var o=this.layoutVertexArray,s=this.indexArray;n(o,t,r,!1,i,0,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),i?this.e2=this.e3:this.e1=this.e3},h("LineBucket",g,{omit:["layers"]}),e.exports=g},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./line_attributes":48,"@mapbox/vector-tile":8}],50:[function(t,e,r){var n=t("../../util/struct_array").createLayout,i={symbolLayoutAttributes:n([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),dynamicLayoutAttributes:n([{name:"a_projected_pos",components:3,type:"Float32"}],4),placementOpacityAttributes:n([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),collisionVertexAttributes:n([{name:"a_placed",components:2,type:"Uint8"}],4),collisionBox:n([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),collisionBoxLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),collisionCircleLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),placement:n([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),glyphOffset:n([{type:"Float32",name:"offsetX"}]),lineVertex:n([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}])};e.exports=i},{"../../util/struct_array":271}],51:[function(t,e,r){function n(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,Math.round(64*n),Math.round(64*i),a,o,s?s[0]:0,s?s[1]:0)}function i(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r)}var a=t("./symbol_attributes"),o=a.symbolLayoutAttributes,s=a.collisionVertexAttributes,l=a.collisionBoxLayout,u=a.collisionCircleLayout,c=a.dynamicLayoutAttributes,p=t("../array_types"),h=p.SymbolLayoutArray,f=p.SymbolDynamicLayoutArray,d=p.SymbolOpacityArray,y=p.CollisionBoxLayoutArray,m=p.CollisionCircleLayoutArray,g=p.CollisionVertexArray,v=p.PlacedSymbolArray,_=p.GlyphOffsetArray,x=p.SymbolLineVertexArray,b=t("@mapbox/point-geometry"),w=t("../segment").SegmentVector,k=t("../program_configuration").ProgramConfigurationSet,A=t("../index_array_type"),T=A.TriangleIndexArray,M=A.LineIndexArray,S=t("../../symbol/transform_text"),C=t("../../symbol/mergelines"),z=t("../../util/script_detection"),L=t("../load_geometry"),E=t("@mapbox/vector-tile").VectorTileFeature.types,P=t("../../util/verticalize_punctuation"),I=(t("../../symbol/anchor"),t("../../symbol/symbol_size").getSizeData),D=t("../../util/web_worker_transfer").register,O=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}],R=function(t){this.layoutVertexArray=new h,this.indexArray=new T,this.programConfigurations=t,this.segments=new w,this.dynamicLayoutVertexArray=new f,this.opacityVertexArray=new d,this.placedSymbolArray=new v};R.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,o.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,c.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,O,!0),this.opacityVertexBuffer.itemSize=1},R.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy())},D("SymbolBuffers",R);var B=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new w,this.collisionVertexArray=new g};B.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,s.members,!0)},B.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy())},D("CollisionBuffers",B);var F=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=I(this.zoom,e["text-size"]),this.iconSizeData=I(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")};F.prototype.createArrays=function(){this.text=new R(new k(o.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new R(new k(o.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new B(y,l.members,M),this.collisionCircle=new B(m,u.members,T),this.glyphOffsetArray=new _,this.lineVertexArray=new x},F.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),a=n.get("text-field"),o=n.get("icon-image"),s=("constant"!==a.value.kind||a.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),l="constant"!==o.value.kind||o.value.value&&o.value.value.length>0;if(this.features=[],s||l){for(var u=e.iconDependencies,c=e.glyphDependencies,p={zoom:this.zoom},h=0,f=t;h=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var l=0;l0;t.addCollisionDebugVertices(l,u,c,p,h?t.collisionCircle:t.collisionBox,s.anchorPoint,n,h)}}}},F.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var a={},o=e;o0},F.prototype.hasIconData=function(){return this.icon.segments.get().length>0},F.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},F.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},F.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},a("Level",o);var s=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new o(256,512),this.loaded=!!r};s.prototype.loadFromImage=function(t){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");for(var e=this.level=new o(t.width,t.width/2),r=t.data,n=0;no.max||u.yo.max)&&i.warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return r}},{"../util/util":275,"./extent":53}],57:[function(t,e,r){var n=t("../util/struct_array").createLayout;e.exports=n([{name:"a_pos",type:"Int16",components:2}])},{"../util/struct_array":271}],58:[function(t,e,r){function n(t){return[a(255*t.r,255*t.g),a(255*t.b,255*t.a)]}function i(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}var a=t("../shaders/encode_attribute").packUint8ToFloat,o=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),s=t("../style/properties").PossiblyEvaluatedPropertyValue,l=t("./array_types"),u=l.StructArrayLayout1f4,c=l.StructArrayLayout2f8,p=l.StructArrayLayout4f16,h=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0}};h.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},h.prototype.populatePaintArray=function(){},h.prototype.upload=function(){},h.prototype.destroy=function(){},h.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),a=t.gl;"color"===this.type?a.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):a.uniform1f(e.uniforms["u_"+this.name],i)};var f=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?c:u;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n};f.prototype.defines=function(){return[]},f.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,i=r.length;r.reserve(t);var a=this.expression.evaluate({zoom:0},e);if("color"===this.type)for(var o=n(a),s=i;sa&&n("Max vertices per segment is "+a+": bucket requested "+t),(!o||o.vertexLength+t>e.exports.MAX_VERTEX_ARRAY_LENGTH)&&(o={vertexOffset:r.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0},this.segments.push(o)),o},o.prototype.get=function(){return this.segments},o.prototype.destroy=function(){for(var t=0,e=this.segments;t90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};i.prototype.wrap=function(){return new i(n(this.lng,-180,180),this.lat)},i.prototype.toArray=function(){return[this.lng,this.lat]},i.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},i.prototype.toBounds=function(e){var r=360*e/40075017,n=r/Math.cos(Math.PI/180*this.lat);return new(t("./lng_lat_bounds"))(new i(this.lng-n,this.lat-r),new i(this.lng+n,this.lat+r))},i.convert=function(t){if(t instanceof i)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new i(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new i(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, or an array of [, ]")},e.exports=i},{"../util/util":275,"./lng_lat_bounds":63}],63:[function(t,e,r){var n=t("./lng_lat"),i=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]))};i.prototype.setNorthEast=function(t){return this._ne=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.setSouthWest=function(t){return this._sw=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.extend=function(t){var e,r,a=this._sw,o=this._ne;if(t instanceof n)e=t,r=t;else{if(!(t instanceof i))return Array.isArray(t)?t.every(Array.isArray)?this.extend(i.convert(t)):this.extend(n.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return a||o?(a.lng=Math.min(e.lng,a.lng),a.lat=Math.min(e.lat,a.lat),o.lng=Math.max(r.lng,o.lng),o.lat=Math.max(r.lat,o.lat)):(this._sw=new n(e.lng,e.lat),this._ne=new n(r.lng,r.lat)),this},i.prototype.getCenter=function(){return new n((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},i.prototype.getSouthWest=function(){return this._sw},i.prototype.getNorthEast=function(){return this._ne},i.prototype.getNorthWest=function(){return new n(this.getWest(),this.getNorth())},i.prototype.getSouthEast=function(){return new n(this.getEast(),this.getSouth())},i.prototype.getWest=function(){return this._sw.lng},i.prototype.getSouth=function(){return this._sw.lat},i.prototype.getEast=function(){return this._ne.lng},i.prototype.getNorth=function(){return this._ne.lat},i.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},i.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},i.prototype.isEmpty=function(){return!(this._sw&&this._ne)},i.convert=function(t){return!t||t instanceof i?t:new i(t)},e.exports=i},{"./lng_lat":62}],64:[function(t,e,r){var n=t("./lng_lat"),i=t("@mapbox/point-geometry"),a=t("./coordinate"),o=t("../util/util"),s=t("../style-spec/util/interpolate").number,l=t("../util/tile_cover"),u=t("../source/tile_id"),c=(u.CanonicalTileID,u.UnwrappedTileID),p=t("../data/extent"),h=t("@mapbox/gl-matrix"),f=h.vec4,d=h.mat4,y=h.mat2,m=function(t,e,r){this.tileSize=512,this._renderWorldCopies=void 0===r||r,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new n(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={}},g={minZoom:{},maxZoom:{},renderWorldCopies:{},worldSize:{},centerPoint:{},size:{},bearing:{},pitch:{},fov:{},zoom:{},center:{},unmodified:{},x:{},y:{},point:{}};m.prototype.clone=function(){var t=new m(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},g.minZoom.get=function(){return this._minZoom},g.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))},g.maxZoom.get=function(){return this._maxZoom},g.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))},g.renderWorldCopies.get=function(){return this._renderWorldCopies},g.worldSize.get=function(){return this.tileSize*this.scale},g.centerPoint.get=function(){return this.size._div(2)},g.size.get=function(){return new i(this.width,this.height)},g.bearing.get=function(){return-this.angle/Math.PI*180},g.bearing.set=function(t){var e=-o.wrap(t,-180,180)*Math.PI/180;this.angle!==e&&(this._unmodified=!1,this.angle=e,this._calcMatrices(),this.rotationMatrix=y.create(),y.rotate(this.rotationMatrix,this.rotationMatrix,this.angle))},g.pitch.get=function(){return this._pitch/Math.PI*180},g.pitch.set=function(t){var e=o.clamp(t,0,60)/180*Math.PI;this._pitch!==e&&(this._unmodified=!1,this._pitch=e,this._calcMatrices())},g.fov.get=function(){return this._fov/Math.PI*180},g.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices())},g.zoom.get=function(){return this._zoom},g.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices())},g.center.get=function(){return this._center},g.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices())},m.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},m.prototype.getVisibleUnwrappedCoordinates=function(t){var e=this.pointCoordinate(new i(0,0),0),r=this.pointCoordinate(new i(this.width,0),0),n=Math.floor(e.column),a=Math.floor(r.column),o=[new c(0,t)];if(this._renderWorldCopies)for(var s=n;s<=a;s++)0!==s&&o.push(new c(s,t));return o},m.prototype.coveringTiles=function(t){var e=this.coveringZoomLevel(t),r=e;if(void 0!==t.minzoom&&et.maxzoom&&(e=t.maxzoom);var n=this.pointCoordinate(this.centerPoint,e),a=new i(n.column-.5,n.row-.5),o=[this.pointCoordinate(new i(0,0),e),this.pointCoordinate(new i(this.width,0),e),this.pointCoordinate(new i(this.width,this.height),e),this.pointCoordinate(new i(0,this.height),e)];return l(e,o,t.reparseOverscaled?r:e,this._renderWorldCopies).sort(function(t,e){return a.dist(t.canonical)-a.dist(e.canonical)})},m.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices()},g.unmodified.get=function(){return this._unmodified},m.prototype.zoomScale=function(t){return Math.pow(2,t)},m.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},m.prototype.project=function(t){return new i(this.lngX(t.lng),this.latY(t.lat))},m.prototype.unproject=function(t){return new n(this.xLng(t.x),this.yLat(t.y))},g.x.get=function(){return this.lngX(this.center.lng)},g.y.get=function(){return this.latY(this.center.lat)},g.point.get=function(){return new i(this.x,this.y)},m.prototype.lngX=function(t){return(180+t)*this.worldSize/360},m.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},m.prototype.xLng=function(t){return 360*t/this.worldSize-180},m.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},m.prototype.setLocationAtPoint=function(t,e){var r=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(r)),this._renderWorldCopies&&(this.center=this.center.wrap())},m.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},m.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},m.prototype.locationCoordinate=function(t){return new a(this.lngX(t.lng)/this.tileSize,this.latY(t.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},m.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new n(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},m.prototype.pointCoordinate=function(t,e){void 0===e&&(e=this.tileZoom);var r=[t.x,t.y,0,1],n=[t.x,t.y,1,1];f.transformMat4(r,r,this.pixelMatrixInverse),f.transformMat4(n,n,this.pixelMatrixInverse);var i=r[3],o=n[3],l=r[1]/i,u=n[1]/o,c=r[2]/i,p=n[2]/o,h=c===p?0:(0-c)/(p-c);return new a(s(r[0]/i,n[0]/o,h)/this.tileSize,s(l,u,h)/this.tileSize,this.zoom)._zoomTo(e)},m.prototype.coordinatePoint=function(t){var e=t.zoomTo(this.zoom),r=[e.column*this.tileSize,e.row*this.tileSize,0,1];return f.transformMat4(r,r,this.pixelMatrix),new i(r[0]/r[3],r[1]/r[3])},m.prototype.calculatePosMatrix=function(t,e){void 0===e&&(e=!1);var r=t.key,n=e?this._alignedPosMatrixCache:this._posMatrixCache;if(n[r])return n[r];var i=t.canonical,a=this.worldSize/this.zoomScale(i.z),o=i.x+Math.pow(2,i.z)*t.wrap,s=d.identity(new Float64Array(16));return d.translate(s,s,[o*a,i.y*a,0]),d.scale(s,s,[a/p,a/p,1]),d.multiply(s,e?this.alignedProjMatrix:this.projMatrix,s),n[r]=new Float32Array(s),n[r]},m.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var t,e,r,n,a=-90,o=90,s=-180,l=180,u=this.size,c=this._unmodified;if(this.latRange){var p=this.latRange;a=this.latY(p[1]),t=(o=this.latY(p[0]))-ao&&(n=o-y)}if(this.lngRange){var m=this.x,g=u.x/2;m-gl&&(r=l-g)}void 0===r&&void 0===n||(this.center=this.unproject(new i(void 0!==r?r:this.x,void 0!==n?n:this.y))),this._unmodified=c,this._constraining=!1}},m.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,r=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,i=this.y,a=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),o=new Float64Array(16);d.perspective(o,this._fov,this.width/this.height,1,a),d.scale(o,o,[1,-1,1]),d.translate(o,o,[0,0,-this.cameraToCenterDistance]),d.rotateX(o,o,this._pitch),d.rotateZ(o,o,this.angle),d.translate(o,o,[-n,-i,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));d.scale(o,o,[1,1,s,1]),this.projMatrix=o;var l=this.width%2/2,u=this.height%2/2,c=Math.cos(this.angle),p=Math.sin(this.angle),h=n-Math.round(n)+c*l+p*u,f=i-Math.round(i)+c*u+p*l,y=new Float64Array(o);if(d.translate(y,y,[h>.5?h-1:h,f>.5?f-1:f,0]),this.alignedProjMatrix=y,o=d.create(),d.scale(o,o,[this.width/2,-this.height/2,1]),d.translate(o,o,[1,-1,0]),this.pixelMatrix=d.multiply(new Float64Array(16),o,this.projMatrix),!(o=d.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=o,this._posMatrixCache={},this._alignedPosMatrixCache={}}},Object.defineProperties(m.prototype,g),e.exports=m},{"../data/extent":53,"../source/tile_id":114,"../style-spec/util/interpolate":158,"../util/tile_cover":273,"../util/util":275,"./coordinate":61,"./lng_lat":62,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],65:[function(t,e,r){var n=t("../style-spec/util/color"),i=function(t,e,r){this.blendFunction=t,this.blendColor=e,this.mask=r};i.disabled=new i(i.Replace=[1,0],n.transparent,[!1,!1,!1,!1]),i.unblended=new i(i.Replace,n.transparent,[!0,!0,!0,!0]),i.alphaBlended=new i([1,771],n.transparent,[!0,!0,!0,!0]),e.exports=i},{"../style-spec/util/color":153}],66:[function(t,e,r){var n=t("./index_buffer"),i=t("./vertex_buffer"),a=t("./framebuffer"),o=(t("./depth_mode"),t("./stencil_mode"),t("./color_mode")),s=t("../util/util"),l=t("./value"),u=l.ClearColor,c=l.ClearDepth,p=l.ClearStencil,h=l.ColorMask,f=l.DepthMask,d=l.StencilMask,y=l.StencilFunc,m=l.StencilOp,g=l.StencilTest,v=l.DepthRange,_=l.DepthTest,x=l.DepthFunc,b=l.Blend,w=l.BlendFunc,k=l.BlendColor,A=l.Program,T=l.LineWidth,M=l.ActiveTextureUnit,S=l.Viewport,C=l.BindFramebuffer,z=l.BindRenderbuffer,L=l.BindTexture,E=l.BindVertexBuffer,P=l.BindElementBuffer,I=l.BindVertexArrayOES,D=l.PixelStoreUnpack,O=l.PixelStoreUnpackPremultiplyAlpha,R=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new u(this),this.clearDepth=new c(this),this.clearStencil=new p(this),this.colorMask=new h(this),this.depthMask=new f(this),this.stencilMask=new d(this),this.stencilFunc=new y(this),this.stencilOp=new m(this),this.stencilTest=new g(this),this.depthRange=new v(this),this.depthTest=new _(this),this.depthFunc=new x(this),this.blend=new b(this),this.blendFunc=new w(this),this.blendColor=new k(this),this.program=new A(this),this.lineWidth=new T(this),this.activeTexture=new M(this),this.viewport=new S(this),this.bindFramebuffer=new C(this),this.bindRenderbuffer=new z(this),this.bindTexture=new L(this),this.bindVertexBuffer=new E(this),this.bindElementBuffer=new P(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new I(this),this.pixelStoreUnpack=new D(this),this.pixelStoreUnpackPremultiplyAlpha=new O(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear")};R.prototype.createIndexBuffer=function(t,e){return new n(this,t,e)},R.prototype.createVertexBuffer=function(t,e,r){return new i(this,t,e,r)},R.prototype.createRenderbuffer=function(t,e,r){var n=this.gl,i=n.createRenderbuffer();return this.bindRenderbuffer.set(i),n.renderbufferStorage(n.RENDERBUFFER,t,e,r),this.bindRenderbuffer.set(null),i},R.prototype.createFramebuffer=function(t,e){return new a(this,t,e)},R.prototype.clear=function(t){var e=t.color,r=t.depth,n=this.gl,i=0;e&&(i|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==r&&(i|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(r),this.depthMask.set(!0)),n.clear(i)},R.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1)},R.prototype.setStencilMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1)},R.prototype.setColorMode=function(t){s.deepEqual(t.blendFunction,o.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(t.blendFunction),this.blendColor.set(t.blendColor)),this.colorMask.set(t.mask)},e.exports=R},{"../util/util":275,"./color_mode":65,"./depth_mode":67,"./framebuffer":68,"./index_buffer":69,"./stencil_mode":70,"./value":71,"./vertex_buffer":72}],67:[function(t,e,r){var n=function(t,e,r){this.func=t,this.mask=e,this.range=r};n.ReadOnly=!1,n.ReadWrite=!0,n.disabled=new n(519,n.ReadOnly,[0,1]),e.exports=n},{}],68:[function(t,e,r){var n=t("./value"),i=n.ColorAttachment,a=n.DepthAttachment,o=function(t,e,r){this.context=t,this.width=e,this.height=r;var n=t.gl,o=this.framebuffer=n.createFramebuffer();this.colorAttachment=new i(t,o),this.depthAttachment=new a(t,o)};o.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var r=this.depthAttachment.get();r&&t.deleteRenderbuffer(r),t.deleteFramebuffer(this.framebuffer)},e.exports=o},{"./value":71}],69:[function(t,e,r){var n=function(t,e,r){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(r),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};n.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null)},n.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer)},n.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)},n.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer)},e.exports=n},{}],70:[function(t,e,r){var n=function(t,e,r,n,i,a){this.test=t,this.ref=e,this.mask=r,this.fail=n,this.depthFail=i,this.pass=a};n.disabled=new n({func:519,mask:0},0,0,7680,7680,7680),e.exports=n},{}],71:[function(t,e,r){var n=t("../style-spec/util/color"),i=t("../util/util"),a=function(t){this.context=t,this.current=n.transparent};a.prototype.get=function(){return this.current},a.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t)};var o=function(t){this.context=t,this.current=1};o.prototype.get=function(){return this.current},o.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t)};var s=function(t){this.context=t,this.current=0};s.prototype.get=function(){return this.current},s.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t)};var l=function(t){this.context=t,this.current=[!0,!0,!0,!0]};l.prototype.get=function(){return this.current},l.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t)};var u=function(t){this.context=t,this.current=!0};u.prototype.get=function(){return this.current},u.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t)};var c=function(t){this.context=t,this.current=255};c.prototype.get=function(){return this.current},c.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t)};var p=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255}};p.prototype.get=function(){return this.current},p.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t)};var h=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP]};h.prototype.get=function(){return this.current},h.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t)};var f=function(t){this.context=t,this.current=!1};f.prototype.get=function(){return this.current},f.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t}};var d=function(t){this.context=t,this.current=[0,1]};d.prototype.get=function(){return this.current},d.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t)};var y=function(t){this.context=t,this.current=!1};y.prototype.get=function(){return this.current},y.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t}};var m=function(t){this.context=t,this.current=t.gl.LESS};m.prototype.get=function(){return this.current},m.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t)};var g=function(t){this.context=t,this.current=!1};g.prototype.get=function(){return this.current},g.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t}};var v=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO]};v.prototype.get=function(){return this.current},v.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t)};var _=function(t){this.context=t,this.current=n.transparent};_.prototype.get=function(){return this.current},_.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t)};var x=function(t){this.context=t,this.current=null};x.prototype.get=function(){return this.current},x.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t)};var b=function(t){this.context=t,this.current=1};b.prototype.get=function(){return this.current},b.prototype.set=function(t){var e=this.context.lineWidthRange,r=i.clamp(t,e[0],e[1]);this.current!==r&&(this.context.gl.lineWidth(r),this.current=t)};var w=function(t){this.context=t,this.current=t.gl.TEXTURE0};w.prototype.get=function(){return this.current},w.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t)};var k=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight]};k.prototype.get=function(){return this.current},k.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t)};var A=function(t){this.context=t,this.current=null};A.prototype.get=function(){return this.current},A.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t}};var T=function(t){this.context=t,this.current=null};T.prototype.get=function(){return this.current},T.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t}};var M=function(t){this.context=t,this.current=null};M.prototype.get=function(){return this.current},M.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t}};var S=function(t){this.context=t,this.current=null};S.prototype.get=function(){return this.current},S.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t}};var C=function(t){this.context=t,this.current=null};C.prototype.get=function(){return this.current},C.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t};var z=function(t){this.context=t,this.current=null};z.prototype.get=function(){return this.current},z.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t)};var L=function(t){this.context=t,this.current=4};L.prototype.get=function(){return this.current},L.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t}};var E=function(t){this.context=t,this.current=!1};E.prototype.get=function(){return this.current},E.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t}};var P=function(t,e){this.context=t,this.current=null,this.parent=e};P.prototype.get=function(){return this.current};var I=function(t){function e(e,r){t.call(this,e,r),this.dirty=!1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1}},e.prototype.setDirty=function(){this.dirty=!0},e}(P),D=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t}},e}(P);e.exports={ClearColor:a,ClearDepth:o,ClearStencil:s,ColorMask:l,DepthMask:u,StencilMask:c,StencilFunc:p,StencilOp:h,StencilTest:f,DepthRange:d,DepthTest:y,DepthFunc:m,Blend:g,BlendFunc:v,BlendColor:_,Program:x,LineWidth:b,ActiveTextureUnit:w,Viewport:k,BindFramebuffer:A,BindRenderbuffer:T,BindTexture:M,BindVertexBuffer:S,BindElementBuffer:C,BindVertexArrayOES:z,PixelStoreUnpack:L,PixelStoreUnpackPremultiplyAlpha:E,ColorAttachment:I,DepthAttachment:D}},{"../style-spec/util/color":153,"../util/util":275}],72:[function(t,e,r){var n={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},i=function(t,e,r,n){this.length=e.length,this.attributes=r,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var i=t.gl;this.buffer=i.createBuffer(),t.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};i.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer)},i.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer)},i.prototype.enableAttributes=function(t,e){for(var r=0;r":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]}},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../util/browser":252,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],78:[function(t,e,r){function n(t,e,r,n,i){if(!s.isPatternMissing(r.paint.get("fill-pattern"),t))for(var a=!0,o=0,l=n;o0){var l=o.now(),u=(l-t.timeAdded)/s,c=e?(l-e.timeAdded)/s:-1,p=r.getSource(),h=a.coveringZoomLevel({tileSize:p.tileSize,roundZoom:p.roundZoom}),f=!e||Math.abs(e.tileID.overscaledZ-h)>Math.abs(t.tileID.overscaledZ-h),d=f&&t.refreshedUponExpiration?1:i.clamp(f?u:1-c,0,1);return t.refreshedUponExpiration&&u>=1&&(t.refreshedUponExpiration=!1),e?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return{opacity:1,mix:0}}var i=t("../util/util"),a=t("../source/image_source"),o=t("../util/browser"),s=t("../gl/stencil_mode"),l=t("../gl/depth_mode");e.exports=function(t,e,r,i){if("translucent"===t.renderPass&&0!==r.paint.get("raster-opacity")){var o=t.context,u=o.gl,c=e.getSource(),p=t.useProgram("raster");o.setStencilMode(s.disabled),o.setColorMode(t.colorModeForRenderPass()),u.uniform1f(p.uniforms.u_brightness_low,r.paint.get("raster-brightness-min")),u.uniform1f(p.uniforms.u_brightness_high,r.paint.get("raster-brightness-max")),u.uniform1f(p.uniforms.u_saturation_factor,function(t){return t>0?1-1/(1.001-t):-t}(r.paint.get("raster-saturation"))),u.uniform1f(p.uniforms.u_contrast_factor,function(t){return t>0?1/(1-t):1+t}(r.paint.get("raster-contrast"))),u.uniform3fv(p.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),r=Math.cos(t);return[(2*r+1)/3,(-Math.sqrt(3)*e-r+1)/3,(Math.sqrt(3)*e-r+1)/3]}(r.paint.get("raster-hue-rotate"))),u.uniform1f(p.uniforms.u_buffer_scale,1),u.uniform1i(p.uniforms.u_image0,0),u.uniform1i(p.uniforms.u_image1,1);for(var h=i.length&&i[0].overscaledZ,f=0,d=i;f65535)e(new Error("glyphs > 65535 not supported"));else{var u=o.requests[l];u||(u=o.requests[l]=[],n(i,l,r.url,r.requestTransform,function(t,e){if(e)for(var r in e)o.glyphs[+r]=e[+r];for(var n=0,i=u;nthis.height)return n.warnOnce("LineAtlas out of space"),null;for(var o=0,s=0;s=0;this.currentLayer--){var m=r.style._layers[o[r.currentLayer]];m.source!==(d&&d.id)&&(y=[],(d=r.style.sourceCaches[m.source])&&(r.clearStencil(),y=d.getVisibleCoordinates(),d.getSource().isTileClipped&&r._renderTileClippingMasks(y))),r.renderLayer(r,d,m,y)}this.renderPass="translucent";var g,v=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer0?e.pop():null},M.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var r=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[r]||(this.cache[r]=new v(this.context,g[t],e,this._showOverdrawInspector)),this.cache[r]},M.prototype.useProgram=function(t,e){var r=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(r.program),r},e.exports=M},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../data/program_configuration":58,"../data/raster_bounds_attributes":59,"../gl/color_mode":65,"../gl/context":66,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../shaders":97,"../source/pixels_to_tile_units":104,"../source/source_cache":111,"../style-spec/util/color":153,"../symbol/cross_tile_symbol_index":218,"../util/browser":252,"../util/util":275,"./draw_background":74,"./draw_circle":75,"./draw_debug":77,"./draw_fill":78,"./draw_fill_extrusion":79,"./draw_heatmap":80,"./draw_hillshade":81,"./draw_line":82,"./draw_raster":83,"./draw_symbol":84,"./program":92,"./texture":93,"./tile_mask":94,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],91:[function(t,e,r){var n=t("../source/pixels_to_tile_units");r.isPatternMissing=function(t,e){if(!t)return!1;var r=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!r||!n},r.prepare=function(t,e,r){var n=e.context,i=n.gl,a=e.imageManager.getPattern(t.from),o=e.imageManager.getPattern(t.to);i.uniform1i(r.uniforms.u_image,0),i.uniform2fv(r.uniforms.u_pattern_tl_a,a.tl),i.uniform2fv(r.uniforms.u_pattern_br_a,a.br),i.uniform2fv(r.uniforms.u_pattern_tl_b,o.tl),i.uniform2fv(r.uniforms.u_pattern_br_b,o.br);var s=e.imageManager.getPixelSize(),l=s.width,u=s.height;i.uniform2fv(r.uniforms.u_texsize,[l,u]),i.uniform1f(r.uniforms.u_mix,t.t),i.uniform2fv(r.uniforms.u_pattern_size_a,a.displaySize),i.uniform2fv(r.uniforms.u_pattern_size_b,o.displaySize),i.uniform1f(r.uniforms.u_scale_a,t.fromScale),i.uniform1f(r.uniforms.u_scale_b,t.toScale),n.activeTexture.set(i.TEXTURE0),e.imageManager.bind(e.context)},r.setTile=function(t,e,r){var i=e.context.gl;i.uniform1f(r.uniforms.u_tile_units_to_pixels,1/n(t,1,e.transform.tileZoom));var a=Math.pow(2,t.tileID.overscaledZ),o=t.tileSize*Math.pow(2,e.transform.tileZoom)/a,s=o*(t.tileID.canonical.x+t.tileID.wrap*a),l=o*t.tileID.canonical.y;i.uniform2f(r.uniforms.u_pixel_coord_upper,s>>16,l>>16),i.uniform2f(r.uniforms.u_pixel_coord_lower,65535&s,65535&l)}},{"../source/pixels_to_tile_units":104}],92:[function(t,e,r){var n=t("../util/browser"),i=t("../shaders"),a=(t("../data/program_configuration").ProgramConfiguration,t("./vertex_array_object")),o=(t("../gl/context"),function(t,e,r,a){var o=this,s=t.gl;this.program=s.createProgram();var l=r.defines().concat("#define DEVICE_PIXEL_RATIO "+n.devicePixelRatio.toFixed(1));a&&l.push("#define OVERDRAW_INSPECTOR;");var u=l.concat(i.prelude.fragmentSource,e.fragmentSource).join("\n"),c=l.concat(i.prelude.vertexSource,e.vertexSource).join("\n"),p=s.createShader(s.FRAGMENT_SHADER);s.shaderSource(p,u),s.compileShader(p),s.attachShader(this.program,p);var h=s.createShader(s.VERTEX_SHADER);s.shaderSource(h,c),s.compileShader(h),s.attachShader(this.program,h);for(var f=r.layoutAttributes||[],d=0;d 0.5) {\n gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n gl_FragColor *= .1;\n }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n float alpha = 0.5;\n\n // Red = collision, hide label\n vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n // Blue = no collision, label is showing\n if (v_placed > 0.5) {\n color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n color *= .2;\n }\n\n float extrude_scale_length = length(v_extrude_scale);\n float extrude_length = length(v_extrude) * extrude_scale_length;\n float stroke_width = 15.0 * extrude_scale_length;\n float radius = v_radius * extrude_scale_length;\n\n float distance_to_edge = abs(extrude_length - radius);\n float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n v_extrude = a_extrude * padding_factor;\n v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n // find distance to outline for alpha interpolation\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n vec3 normal = a_normal_ed.xyz;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n\n gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n // Relative luminance (how dark/bright is the surface color?)\n float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n // Add slight ambient lighting so no extrusions are totally black\n vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n color += ambientlight;\n\n // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n // Adjust directional so that\n // the range of values for highlight/shading is narrower\n // with lower light intensity\n // and with lighter/brighter surface colors\n directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n // Add gradient along z axis of side surfaces\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n // with lower bounds adjusted to hue of light\n // so that shading is tinted with the complementary (opposite) color to the light color\n v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n vec4 mixedColor = mix(color1, color2, u_mix);\n\n gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec3 normal = a_normal_ed.xyz;\n float edgedistance = a_normal_ed.w;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n float z = t > 0.0 ? height : base;\n\n gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n ? a_pos // extrusion top\n : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n v_pos.x = a_pos.x;\n v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\n\nfloat getElevation(vec2 coord, float bias) {\n // Convert encoded elevation value to meters\n vec4 data = texture2D(u_image, coord) * 255.0;\n return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n vec2 epsilon = 1.0 / u_dimension;\n\n // queried pixels:\n // +-----------+\n // | | | |\n // | a | b | c |\n // | | | |\n // +-----------+\n // | | | |\n // | d | e | f |\n // | | | |\n // +-----------+\n // | | | |\n // | g | h | i |\n // | | | |\n // +-----------+\n\n float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n float e = getElevation(v_pos, 0.0);\n float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n // here we divide the x and y slopes by 8 * pixel size\n // where pixel size (aka meters/pixel) is:\n // circumference of the world / (pixels per tile * number of tiles)\n // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n // we want to vertically exaggerate the hillshading though, because otherwise\n // it is barely noticeable at low zooms. to do this, we multiply this by some\n // scale factor pow(2, (u_zoom - 14) * a) where a is an arbitrary value and 14 is the\n // maxzoom of the tile source. here we use a=0.3 which works out to the\n // expression below. see nickidlugash's awesome breakdown for more info\n // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n vec2 deriv = vec2(\n (c + f + f + i) - (a + d + d + g),\n (g + h + h + i) - (a + b + b + c)\n ) / pow(2.0, (u_zoom - 14.0) * exaggeration + 19.2562 - u_zoom);\n\n gl_FragColor = clamp(vec4(\n deriv.x / 2.0 + 0.5,\n deriv.y / 2.0 + 0.5,\n 1.0,\n 1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n vec4 pixel = texture2D(u_image, v_pos);\n\n vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n // to account for mercator projection distortion. see #4807 for details\n float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n // We also multiply the slope by an arbitrary z-factor of 1.25\n float slope = atan(1.25 * length(deriv) / scaleFactor);\n float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n float intensity = u_light.x;\n // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n float azimuth = u_light.y + PI;\n\n // We scale the slope exponentially based on intensity, using a calculation similar to\n // the exponential interpolation function in the style spec:\n // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n // so that higher intensity values create more opaque hillshading.\n float base = 1.875 - intensity * 1.75;\n float maxValue = 0.5 * PI;\n float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n // so that the accent color's rate of change eases in while the shade color's eases out.\n float accent = cos(scaledSlope);\n // We multiply both the accent and shade color by a clamped intensity value\n // so that intensities >= 0.5 do not additionally affect the color values\n // while intensity values < 0.5 make the overall color more transparent.\n vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n float y_a = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_a.y);\n float y_b = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_b.y);\n vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_linesofar = a_linesofar;\n v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float sdfdist_a = texture2D(u_image, v_tex_a).a;\n float sdfdist_b = texture2D(u_image, v_tex_b).a;\n float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist =outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n // read and cross-fade colors from the main and parent tiles\n vec4 color0 = texture2D(u_image0, v_pos0);\n vec4 color1 = texture2D(u_image1, v_pos1);\n if (color0.a > 0.0) {\n color0.rgb = color0.rgb / color0.a;\n }\n if (color1.a > 0.0) {\n color1.rgb = color1.rgb / color1.a;\n }\n vec4 color = mix(color0, color1, u_fade_t);\n color.a *= u_opacity;\n vec3 rgb = color.rgb;\n\n // spin\n rgb = vec3(\n dot(rgb, u_spin_weights.xyz),\n dot(rgb, u_spin_weights.zxy),\n dot(rgb, u_spin_weights.yzx));\n\n // saturation\n float average = (color.r + color.g + color.b) / 3.0;\n rgb += (average - rgb) * u_saturation_factor;\n\n // contrast\n rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n // brightness\n vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n // We are using Int16 for texture position coordinates to give us enough precision for\n // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n // as an arbitrarily high number to preserve adequate precision when rendering.\n // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n // so math for modifying either is consistent.\n v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n lowp float alpha = opacity * v_fade_opacity;\n gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n\n float size;\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // See comments in symbol_sdf.vertex\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // See comments in symbol_sdf.vertex\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n\n v_tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 tex = v_data0.xy;\n float gamma_scale = v_data1.x;\n float size = v_data1.y;\n float fade_opacity = v_data1[2];\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n lowp vec4 color = fill_color;\n highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n lowp float buff = (256.0 - 64.0) / 256.0;\n if (u_is_halo) {\n color = halo_color;\n gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n buff = (6.0 - halo_width / fontScale) / SDF_PX;\n }\n\n lowp float dist = texture2D(u_texture, tex).a;\n highp float gamma_scaled = gamma * gamma_scale;\n highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n// text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n float size;\n\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // If the label is pitched with the map, layout is done in pitched space,\n // which makes labels in the distance smaller relative to viewport space.\n // We counteract part of that effect by multiplying by the perspective ratio.\n // If the label isn't pitched with the map, we do layout in viewport space,\n // which makes labels in the distance larger relative to the features around\n // them. We counteract part of that effect by dividing by the perspective ratio.\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n // To figure out that angle in projected space, we draw a short horizontal line in tile\n // space, project it, and measure its angle in projected space.\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n float gamma_scale = gl_Position.w;\n\n vec2 tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n v_data0 = vec2(tex.x, tex.y);\n v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,a=function(t){var e=n[t],r={};e.fragmentSource=e.fragmentSource.replace(i,function(t,e,n,i,a){return r[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(i,function(t,e,n,i,a){var o="float"===i?"vec2":"vec4";return r[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+n+" "+i+" "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"})};for(var o in n)a(o);e.exports=n},{}],98:[function(t,e,r){var n=t("./image_source"),i=t("../util/window"),a=t("../data/raster_bounds_attributes"),o=t("../render/vertex_array_object"),s=t("../render/texture"),l=function(t){function e(e,r,n,i){t.call(this,e,r,n,i),this.options=r,this.animate=void 0===r.animate||r.animate}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.load=function(){this.canvas=this.canvas||i.document.getElementById(this.options.canvas),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire("error",new Error("Canvas dimensions cannot be less than or equal to zero.")):(this.play=function(){this._playing=!0,this.map._rerender()},this.pause=function(){this._playing=!1},this._finishLoading())},e.prototype.getCanvas=function(){return this.canvas},e.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()},e.prototype.onRemove=function(){this.pause()},e.prototype.prepare=function(){var t=this,e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var r=this.map.painter.context,n=r.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=r.createVertexBuffer(this._boundsArray,a.members)),this.boundsVAO||(this.boundsVAO=new o),this.texture?e?this.texture.update(this.canvas):this._playing&&(this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.canvas)):(this.texture=new s(r,this.canvas,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE)),t.tiles){var l=t.tiles[i];"loaded"!==l.state&&(l.state="loaded",l.texture=t.texture)}}},e.prototype.serialize=function(){return{type:"canvas",canvas:this.canvas,coordinates:this.coordinates}},e.prototype.hasTransition=function(){return this._playing},e.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t0&&(r.resourceTiming=t._resourceTiming,t._resourceTiming=[]),t.fire("data",r)}})},e.prototype.onAdd=function(t){this.map=t,this.load()},e.prototype.setData=function(t){var e=this;return this._data=t,this.fire("dataloading",{dataType:"source"}),this._updateWorkerData(function(t){if(t)return e.fire("error",{error:t});var r={dataType:"source",sourceDataType:"content"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(r.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire("data",r)}),this},e.prototype._updateWorkerData=function(t){var e=this,r=i.extend({},this.workerOptions),n=this._data;"string"==typeof n?(r.request=this.map._transformRequest(function(t){var e=a.document.createElement("a");return e.href=t,e.href}(n),s.Source),r.request.collectResourceTiming=this._collectResourceTiming):r.data=JSON.stringify(n),this.workerID=this.dispatcher.send(this.type+".loadData",r,function(r,n){e._loaded=!0,n&&n.resourceTiming&&n.resourceTiming[e.id]&&(e._resourceTiming=n.resourceTiming[e.id].slice(0)),t(r)},this.workerID)},e.prototype.loadTile=function(t,e){var r=this,n=void 0===t.workerID||"expired"===t.state?"loadTile":"reloadTile",i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:l.devicePixelRatio,overscaling:t.tileID.overscaleFactor(),showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,i,function(i,a){return t.unloadVectorData(),t.aborted?e(null):i?e(i):(t.loadVectorData(a,r.map.painter,"reloadTile"===n),e(null))},this.workerID)},e.prototype.abortTile=function(t){t.aborted=!0},e.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID)},e.prototype.onRemove=function(){this.dispatcher.broadcast("removeSource",{type:this.type,source:this.id})},e.prototype.serialize=function(){return i.extend({},this._options,{type:this.type,data:this._data})},e.prototype.hasTransition=function(){return!1},e}(n);e.exports=u},{"../data/extent":53,"../util/ajax":251,"../util/browser":252,"../util/evented":260,"../util/util":275,"../util/window":254}],100:[function(t,e,r){function n(t,e){var r=t.source,n=t.tileID.canonical;if(!this._geoJSONIndexes[r])return e(null,null);var i=this._geoJSONIndexes[r].getTile(n.z,n.x,n.y);if(!i)return e(null,null);var a=new s(i.features),o=l(a);0===o.byteOffset&&o.byteLength===o.buffer.byteLength||(o=new Uint8Array(o)),e(null,{vectorTile:a,rawData:o.buffer})}var i=t("../util/ajax"),a=t("../util/performance"),o=t("geojson-rewind"),s=t("./geojson_wrapper"),l=t("vt-pbf"),u=t("supercluster"),c=t("geojson-vt"),p=function(t){function e(e,r,i){t.call(this,e,r,n),i&&(this.loadGeoJSON=i),this._geoJSONIndexes={}}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.loadData=function(t,e){var r=this;this.loadGeoJSON(t,function(n,i){if(n||!i)return e(n);if("object"!=typeof i)return e(new Error("Input data is not a valid GeoJSON object."));o(i,!0);try{r._geoJSONIndexes[t.source]=t.cluster?u(t.superclusterOptions).load(i.features):c(i,t.geojsonVtOptions)}catch(n){return e(n)}r.loaded[t.source]={};var s={};if(t.request&&t.request.collectResourceTiming){var l=a.getEntriesByName(t.request.url);l&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(l)))}e(null,s)})},e.prototype.reloadTile=function(e,r){var n=this.loaded[e.source],i=e.uid;return n&&n[i]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},e.prototype.loadGeoJSON=function(t,e){if(t.request)i.getJSON(t.request,e);else{if("string"!=typeof t.data)return e(new Error("Input data is not a valid GeoJSON object."));try{return e(null,JSON.parse(t.data))}catch(t){return e(new Error("Input data is not a valid GeoJSON object."))}}},e.prototype.removeSource=function(t,e){this._geoJSONIndexes[t.source]&&delete this._geoJSONIndexes[t.source],e()},e}(t("./vector_tile_worker_source"));e.exports=p},{"../util/ajax":251,"../util/performance":268,"./geojson_wrapper":101,"./vector_tile_worker_source":116,"geojson-rewind":15,"geojson-vt":19,supercluster:32,"vt-pbf":34}],101:[function(t,e,r){var n=t("@mapbox/point-geometry"),i=t("@mapbox/vector-tile").VectorTileFeature.prototype.toGeoJSON,a=t("../data/extent"),o=function(t){this._feature=t,this.extent=a,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10))};o.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],e=0,r=this._feature.geometry;e0&&(l[new s(t.overscaledZ,i,e.z,n,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,t.wrap,e.z,e.x,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,o,e.z,a,e.y-1).key]={backfilled:!1}),e.y+11||(Math.abs(r)>1&&(1===Math.abs(r+i)?r+=i:1===Math.abs(r-i)&&(r-=i)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,r,n),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)))}for(var r=this.getRenderableIds(),n=0;ne)){var s=Math.pow(2,o.tileID.canonical.z-t.canonical.z);if(Math.floor(o.tileID.canonical.x/s)===t.canonical.x&&Math.floor(o.tileID.canonical.y/s)===t.canonical.y)for(r[a]=o.tileID,i=!0;o&&o.tileID.overscaledZ-1>t.overscaledZ;){var l=o.tileID.scaledTo(o.tileID.overscaledZ-1);if(!l)break;(o=n._tiles[l.key])&&o.hasData()&&(delete r[a],r[l.key]=l)}}}return i},e.prototype.findLoadedParent=function(t,e,r){for(var n=this,i=t.overscaledZ-1;i>=e;i--){var a=t.scaledTo(i);if(!a)return;var o=String(a.key),s=n._tiles[o];if(s&&s.hasData())return r[o]=a,s;if(n._cache.has(o))return r[o]=a,n._cache.get(o)}},e.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),r=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)},e.prototype.update=function(t){var r=this;if(this.transform=t,this._sourceLoaded&&!this._paused){var n;this.updateCacheSize(t),this._coveredTiles={},this.used?this._source.tileID?n=t.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(t){return new d(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y)}):(n=t.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(n=n.filter(function(t){return r._source.hasTile(t)}))):n=[];var a,o=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(t)),s=Math.max(o-e.maxOverzooming,this._source.minzoom),l=Math.max(o+e.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(n,o),p={};if(i(this._source.type))for(var h=Object.keys(u),y=0;y=f.now())){r._findLoadedChildren(g,l,u)&&(u[m]=g);var _=r.findLoadedParent(g,s,p);_&&r._addTile(_.tileID)}}for(a in p)u[a]||(r._coveredTiles[a]=!0);for(a in p)u[a]=p[a];for(var x=c.keysDifference(this._tiles,u),b=0;bn._source.maxzoom){var f=u.children(n._source.maxzoom)[0],d=n.getTile(f);d&&d.hasData()?i[f.key]=f:h=!1}else{n._findLoadedChildren(u,s,i);for(var y=u.children(n._source.maxzoom),m=0;m=o;--g){var v=u.scaledTo(g);if(a[v.key])break;if(a[v.key]=!0,!(c=n.getTile(v))&&p&&(c=n._addTile(v)),c&&(i[v.key]=v,p=c.wasRequested(),c.hasData()))break}}}return i},e.prototype._addTile=function(t){var e=this._tiles[t.key];if(e)return e;(e=this._cache.getAndRemove(t.key))&&this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,e));var r=Boolean(e);return r||(e=new o(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(e,this._tileLoaded.bind(this,e,t.key,e.state))),e?(e.uses++,this._tiles[t.key]=e,r||this._source.fire("dataloading",{tile:e,coord:e.tileID,dataType:"source"}),e):null},e.prototype._setTileReloadTimer=function(t,e){var r=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){r._reloadTile(t,"expired"),delete r._timers[t]},n))},e.prototype._setCacheInvalidationTimer=function(t,e){var r=this;t in this._cacheTimers&&(clearTimeout(this._cacheTimers[t]),delete this._cacheTimers[t]);var n=e.getExpiryTimeout();n&&(this._cacheTimers[t]=setTimeout(function(){r._cache.remove(t),delete r._cacheTimers[t]},n))},e.prototype._removeTile=function(t){var e=this._tiles[t];if(e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),!(e.uses>0)))if(e.hasData()){e.tileID=e.tileID.wrapped();var r=e.tileID.key;this._cache.add(r,e),this._setCacheInvalidationTimer(r,e)}else e.aborted=!0,this._abortTile(e),this._unloadTile(e)},e.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._resetCache()},e.prototype._resetCache=function(){for(var t in this._cacheTimers)clearTimeout(this._cacheTimers[t]);this._cacheTimers={},this._cache.reset()},e.prototype.tilesIn=function(t){for(var e=[],r=this.getIds(),i=1/0,a=1/0,o=-1/0,s=-1/0,l=t[0].zoom,c=0;c=0&&m[1].y>=0){for(var g=[],v=0;v=f.now())return!0}return!1},e}(s);y.maxOverzooming=10,y.maxUnderzooming=3,e.exports=y},{"../data/extent":53,"../geo/coordinate":61,"../gl/context":66,"../util/browser":252,"../util/evented":260,"../util/lru_cache":266,"../util/util":275,"./source":110,"./tile":112,"./tile_id":114,"@mapbox/point-geometry":4}],112:[function(t,e,r){var n=t("../util/util"),i=t("../data/bucket").deserialize,a=(t("../data/feature_index"),t("@mapbox/vector-tile")),o=t("pbf"),s=t("../util/vectortile_to_geojson"),l=t("../style-spec/feature_filter"),u=(t("../symbol/collision_index"),t("../data/bucket/symbol_bucket")),c=t("../data/array_types"),p=c.RasterBoundsArray,h=c.CollisionBoxArray,f=t("../data/raster_bounds_attributes"),d=t("../data/extent"),y=t("@mapbox/point-geometry"),m=t("../render/texture"),g=t("../data/segment").SegmentVector,v=t("../data/index_array_type").TriangleIndexArray,_=t("../util/browser"),x=function(t,e){this.tileID=t,this.uid=n.uniqueId(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.expiredRequestCount=0,this.state="loading"};x.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<_.now()||this.fadeEndTime&&e>s.z,u=new y(s.x*l,s.y*l),c=new y(u.x+l,u.y+l),h=this.segments.prepareSegment(4,r,i);r.emplaceBack(u.x,u.y,u.x,u.y),r.emplaceBack(c.x,u.y,c.x,u.y),r.emplaceBack(u.x,c.y,u.x,c.y),r.emplaceBack(c.x,c.y,c.x,c.y);var m=h.vertexLength;i.emplaceBack(m,m+1,m+2),i.emplaceBack(m+1,m+2,m+3),h.vertexLength+=4,h.primitiveLength+=2}this.maskedBoundsBuffer=e.createVertexBuffer(r,f.members),this.maskedIndexBuffer=e.createIndexBuffer(i)}},x.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},x.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=n.parseCacheControl(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"])}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var i=Date.now(),a=!1;if(this.expirationTime>i)a=!1;else if(e)if(this.expirationTime=e&&t.x=r&&t.y0;a--)i+=(e&(n=1<this.canonical.z?new u(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new u(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},u.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e},u.prototype.children=function(t){if(this.overscaledZ>=t)return[new u(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new u(e,this.wrap,e,r,n),new u(e,this.wrap,e,r+1,n),new u(e,this.wrap,e,r,n+1),new u(e,this.wrap,e,r+1,n+1)]},u.prototype.isLessThan=function(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=z.maxzoom||"none"===z.visibility||(n(C,d.zoom),(g[z.id]=z.createBucket({index:m.bucketLayerIDs.length,layers:C,zoom:d.zoom,pixelRatio:d.pixelRatio,overscaling:d.overscaling,collisionBoxArray:d.collisionBoxArray})).populate(k,v),m.bucketLayerIDs.push(C.map(function(t){return t.id})))}}}var L,E,P,I=u.mapObject(v.glyphDependencies,function(t){return Object.keys(t).map(Number)});Object.keys(I).length?r.send("getGlyphs",{uid:this.uid,stacks:I},function(t,e){L||(L=t,E=e,f.call(d))}):E={};var D=Object.keys(v.iconDependencies);D.length?r.send("getImages",{icons:D},function(t,e){L||(L=t,P=e,f.call(d))}):P={},f.call(this)},e.exports=d},{"../data/array_types":39,"../data/bucket/symbol_bucket":51,"../data/feature_index":54,"../render/glyph_atlas":85,"../render/image_atlas":87,"../style/evaluation_parameters":182,"../symbol/symbol_layout":227,"../util/dictionary_coder":257,"../util/util":275,"./tile_id":114}],120:[function(t,e,r){function n(t,e){var r={};for(var n in t)"ref"!==n&&(r[n]=t[n]);return i.forEach(function(t){t in e&&(r[t]=e[t])}),r}var i=t("./util/ref_properties");e.exports=function(t){t=t.slice();for(var e=Object.create(null),r=0;r4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in f))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=f[i]}else r=o;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2]}var s=a(r,n),l=e.parse(t[t.length-1],t.length-1,o);return l?new d(s,l):null},d.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(c(this.type,p(e)))throw new h("Expected value to be of type "+i(this.type)+", but found "+i(p(e))+" instead.");return e},d.prototype.eachChild=function(t){t(this.input)},d.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},e.exports=d},{"../runtime_error":143,"../types":146,"../values":147}],125:[function(t,e,r){var n=t("../types"),i=n.ObjectType,a=n.ValueType,o=n.StringType,s=n.NumberType,l=n.BooleanType,u=t("../runtime_error"),c=t("../types"),p=c.checkSubtype,h=c.toString,f=t("../values").typeOf,d={string:o,number:s,boolean:l,object:i},y=function(t,e){this.type=t,this.args=e};y.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=d[r],i=[],o=1;o=r.length)throw new s("Array index out of bounds: "+e+" > "+r.length+".");if(e!==Math.floor(e))throw new s("Array index must be an integer, but found "+e+" instead.");return r[e]},l.prototype.eachChild=function(t){t(this.index),t(this.input)},l.prototype.possibleOutputs=function(){return[void 0]},e.exports=l},{"../runtime_error":143,"../types":146}],127:[function(t,e,r){var n=t("../types").BooleanType,i=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r};i.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var a=[],o=1;o4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":u(e[0],e[1],e[2],e[3])))return new l(e[0]/255,e[1]/255,e[2]/255,e[3]);throw new c(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var o=null,s=0,p=this.args;sn.evaluate(t)}function u(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function c(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}var p=t("../types"),h=p.NumberType,f=p.StringType,d=p.BooleanType,y=p.ColorType,m=p.ObjectType,g=p.ValueType,v=p.ErrorType,_=p.array,x=p.toString,b=t("../values"),w=b.typeOf,k=b.Color,A=b.validateRGBA,T=t("../compound_expression"),M=T.CompoundExpression,S=T.varargs,C=t("../runtime_error"),z=t("./let"),L=t("./var"),E=t("./literal"),P=t("./assertion"),I=t("./array"),D=t("./coercion"),O=t("./at"),R=t("./match"),B=t("./case"),F=t("./step"),N=t("./interpolate"),j=t("./coalesce"),V=t("./equals"),q={"==":V.Equals,"!=":V.NotEquals,array:I,at:O,boolean:P,case:B,coalesce:j,interpolate:N,let:z,literal:E,match:R,number:P,object:P,step:F,string:P,"to-color":D,"to-number":D,var:L};M.register(q,{error:[v,[f],function(t,e){var r=e[0];throw new C(r.evaluate(t))}],typeof:[f,[g],function(t,e){var r=e[0];return x(w(r.evaluate(t)))}],"to-string":[f,[g],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r||"string"===n||"number"===n||"boolean"===n?String(r):r instanceof k?r.toString():JSON.stringify(r)}],"to-boolean":[d,[g],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[_(h,4),[y],function(t,e){var r=e[0].evaluate(t),n=r.r,i=r.g,a=r.b,o=r.a;return[255*n/o,255*i/o,255*a/o,o]}],rgb:[y,[h,h,h],n],rgba:[y,[h,h,h,h],n],length:{type:h,overloads:[[[f],o],[[_(g)],o]]},has:{type:d,overloads:[[[f],function(t,e){return i(e[0].evaluate(t),t.properties())}],[[f,m],function(t,e){var r=e[0],n=e[1];return i(r.evaluate(t),n.evaluate(t))}]]},get:{type:g,overloads:[[[f],function(t,e){return a(e[0].evaluate(t),t.properties())}],[[f,m],function(t,e){var r=e[0],n=e[1];return a(r.evaluate(t),n.evaluate(t))}]]},properties:[m,[],function(t){return t.properties()}],"geometry-type":[f,[],function(t){return t.geometryType()}],id:[g,[],function(t){return t.id()}],zoom:[h,[],function(t){return t.globals.zoom}],"heatmap-density":[h,[],function(t){return t.globals.heatmapDensity||0}],"+":[h,S(h),function(t,e){for(var r=0,n=0,i=e;n":[d,[f,g],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[d,[g],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[d,[f,g],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[d,[g],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[d,[f,g],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[d,[g],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[d,[g],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[d,[],function(t){return null!==t.id()}],"filter-type-in":[d,[_(f)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[d,[_(g)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[d,[f,_(g)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[d,[f,_(g)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:d,overloads:[[[h,h],l],[[f,f],l]]},"<":{type:d,overloads:[[[h,h],s],[[f,f],s]]},">=":{type:d,overloads:[[[h,h],c],[[f,f],c]]},"<=":{type:d,overloads:[[[h,h],u],[[f,f],u]]},all:{type:d,overloads:[[[d,d],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[S(d),function(t,e){for(var r=0,n=e;r1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:o}}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,l)))return null;var u=[],p=null;e.expectedType&&"value"!==e.expectedType.kind&&(p=e.expectedType);for(var h=0;h=f)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',y);var g=e.parse(d,m,p);if(!g)return null;p=p||g.type,u.push([f,g])}return"number"===p.kind||"color"===p.kind||"array"===p.kind&&"number"===p.itemType.kind&&"number"==typeof p.N?new c(p,r,n,u):e.error("Type "+s(p)+" is not interpolatable.")},c.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var o=u(e,n),s=e[o],l=e[o+1],p=c.interpolationFactor(this.interpolation,n,s,l),h=r[o].evaluate(t),f=r[o+1].evaluate(t);return a[this.type.kind.toLowerCase()](h,f,p)},c.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;eNumber.MAX_SAFE_INTEGER)return p.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof d&&Math.floor(d)!==d)return p.error("Numeric branch labels must be integer values.");if(r){if(p.checkSubtype(r,n(d)))return null}else r=n(d);if(void 0!==o[String(d)])return p.error("Branch labels must be unique.");o[String(d)]=s.length}var y=e.parse(c,l,a);if(!y)return null;a=a||y.type,s.push(y)}var m=e.parse(t[1],1,r);if(!m)return null;var g=e.parse(t[t.length-1],t.length-1,a);return g?new i(r,a,m,o,s,g):null},i.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},i.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)},i.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t},e.exports=i},{"../values":147}],136:[function(t,e,r){var n=t("../types").NumberType,i=t("../stops").findStopLessThanOrEqualTo,a=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n=u)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',p);var f=e.parse(c,h,s);if(!f)return null;s=s||f.type,o.push([u,f])}return new a(s,r,o)},a.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var a=e.length;return n>=e[a-1]?r[a-1].evaluate(t):r[i(e,n)].evaluate(t)},a.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e0&&"string"==typeof t[0]&&t[0]in y}function i(t,e,r){void 0===r&&(r={});var n=new l(y,[],function(t){var e={color:E,string:P,number:I,enum:P,boolean:D};return"array"===t.type?R(e[t.value]||O,t.length):e[t.type]||null}(e)),i=n.parse(t);return i?_(!1===r.handleErrors?new b(i):new w(i,e)):x(n.errors)}function a(t,e,r){if(void 0===r&&(r={}),"error"===(t=i(t,e,r)).result)return t;var n=t.value.expression,a=m.isFeatureConstant(n);if(!a&&!e["property-function"])return x([new s("","property expressions not supported")]);var o=m.isGlobalPropertyConstant(n,["zoom"]);if(!o&&!1===e["zoom-function"])return x([new s("","zoom expressions not supported")]);var l=function t(e){var r=null;if(e instanceof d)r=t(e.result);else if(e instanceof f)for(var n=0,i=e.args;n=0)return!1;var i=!0;return e.eachChild(function(e){i&&!t(e,r)&&(i=!1)}),i}}},{"./compound_expression":123}],141:[function(t,e,r){var n=t("./scope"),i=t("./types").checkSubtype,a=t("./parsing_error"),o=t("./definitions/literal"),s=t("./definitions/assertion"),l=t("./definitions/array"),u=t("./definitions/coercion"),c=function(t,e,r,i,a){void 0===e&&(e=[]),void 0===i&&(i=new n),void 0===a&&(a=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=i,this.errors=a,this.expectedType=r};c.prototype.parse=function(e,r,n,i,a){void 0===a&&(a={});var c=this;if(r&&(c=c.concat(r,n,i)),null!==e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e||(e=["literal",e]),Array.isArray(e)){if(0===e.length)return c.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var p=e[0];if("string"!=typeof p)return c.error("Expression name must be a string, but found "+typeof p+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var h=c.registry[p];if(h){var f=h.parse(e,c);if(!f)return null;if(c.expectedType){var d=c.expectedType,y=f.type;if("string"!==d.kind&&"number"!==d.kind&&"boolean"!==d.kind||"value"!==y.kind)if("array"===d.kind&&"value"===y.kind)a.omitTypeAnnotations||(f=new l(d,f));else if("color"!==d.kind||"value"!==y.kind&&"string"!==y.kind){if(c.checkSubtype(c.expectedType,f.type))return null}else a.omitTypeAnnotations||(f=new u(d,[f]));else a.omitTypeAnnotations||(f=new s(d,[f]))}if(!(f instanceof o)&&function(e){var r=t("./compound_expression").CompoundExpression,n=t("./is_constant"),i=n.isGlobalPropertyConstant,a=n.isFeatureConstant;if(e instanceof t("./definitions/var"))return!1;if(e instanceof r&&"error"===e.name)return!1;var s=!0;return e.eachChild(function(t){t instanceof o||(s=!1)}),!!s&&a(e)&&i(e,["zoom","heatmap-density"])}(f)){var m=new(t("./evaluation_context"));try{f=new o(f.type,f.evaluate(m))}catch(e){return c.error(e.message),null}}return f}return c.error('Unknown expression "'+p+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===e?c.error("'undefined' value invalid. Use null instead."):"object"==typeof e?c.error('Bare objects invalid. Use ["literal", {...}] instead.'):c.error("Expected an array, but found "+typeof e+" instead.")},c.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new c(this.registry,n,e||null,i,this.errors)},c.prototype.error=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];var i=""+this.key+r.map(function(t){return"["+t+"]"}).join("");this.errors.push(new a(i,t))},c.prototype.checkSubtype=function(t,e){var r=i(t,e);return r&&this.error(r),r},e.exports=c},{"./compound_expression":123,"./definitions/array":124,"./definitions/assertion":125,"./definitions/coercion":129,"./definitions/literal":134,"./definitions/var":137,"./evaluation_context":138,"./is_constant":140,"./parsing_error":142,"./scope":144,"./types":146}],142:[function(t,e,r){var n=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);e.exports=n},{}],143:[function(t,e,r){var n=function(t){this.name="ExpressionEvaluationError",this.message=t};n.prototype.toJSON=function(){return this.message},e.exports=n},{}],144:[function(t,e,r){var n=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;rr&&ee))throw new n("Input is not a number.");o=s-1}}return Math.max(s-1,0)}}},{"./runtime_error":143}],146:[function(t,e,r){function n(t,e){return{kind:"array",itemType:t,N:e}}function i(t){if("array"===t.kind){var e=i(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var a={kind:"null"},o={kind:"number"},s={kind:"string"},l={kind:"boolean"},u={kind:"color"},c={kind:"object"},p={kind:"value"},h=[a,o,s,l,u,c,n(p)];e.exports={NullType:a,NumberType:o,StringType:s,BooleanType:l,ColorType:u,ObjectType:c,ValueType:p,array:n,ErrorType:{kind:"error"},toString:i,checkSubtype:function t(e,r){if("error"===r.kind)return null;if("array"===e.kind){if("array"===r.kind&&!t(e.itemType,r.itemType)&&("number"!=typeof e.N||e.N===r.N))return null}else{if(e.kind===r.kind)return null;if("value"===e.kind)for(var n=0,a=h;n=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."},isValue:function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof n)return!0;if(Array.isArray(e)){for(var r=0,i=e;r=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);ee?1:0}function a(t){if(!t)return!0;var e=t[0];return t.length<=1?"any"!==e:"=="===e?o(t[1],t[2],"=="):"!="===e?u(o(t[1],t[2],"==")):"<"===e||">"===e||"<="===e||">="===e?o(t[1],t[2],e):"any"===e?function(t){return["any"].concat(t.map(a))}(t.slice(1)):"all"===e?["all"].concat(t.slice(1).map(a)):"none"===e?["all"].concat(t.slice(1).map(a).map(u)):"in"===e?s(t[1],t.slice(2)):"!in"===e?u(s(t[1],t.slice(2))):"has"===e?l(t[1]):"!has"!==e||u(l(t[1]))}function o(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function s(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(i)]]:["filter-in-small",t,["literal",e]]}}function l(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function u(t){return["!",t]}var c=t("../expression").createExpression;e.exports=function(t){if(!t)return function(){return!0};n(t)||(t=a(t));var e=c(t,p);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}},e.exports.isExpressionFilter=n;var p={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0}},{"../expression":139}],149:[function(t,e,r){function n(t){return t}function i(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function a(t,e,r,n,a){return i(typeof r===a?n[r]:void 0,t.default,e.default)}function o(t,e,r){if("number"!==f(r))return i(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var a=u(t.stops,r);return t.stops[a][1]}function s(t,e,r){var a=void 0!==t.base?t.base:1;if("number"!==f(r))return i(t.default,e.default);var o=t.stops.length;if(1===o)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[o-1][0])return t.stops[o-1][1];var s=u(t.stops,r),l=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,a,t.stops[s][0],t.stops[s+1][0]),p=t.stops[s][1],h=t.stops[s+1][1],y=d[e.type]||n;if(t.colorSpace&&"rgb"!==t.colorSpace){var m=c[t.colorSpace];y=function(t,e){return m.reverse(m.interpolate(m.forward(t),m.forward(e),l))}}return"function"==typeof p.evaluate?{evaluate:function(){for(var t=arguments,e=[],r=arguments.length;r--;)e[r]=t[r];var n=p.evaluate.apply(void 0,e),i=h.evaluate.apply(void 0,e);if(void 0!==n&&void 0!==i)return y(n,i,l)}}:y(p,h,l)}function l(t,e,r){return"color"===e.type?r=p.parse(r):f(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),i(r,t.default,e.default)}function u(t,e){for(var r,n,i=0,a=t.length-1,o=0;i<=a;){if(r=t[o=Math.floor((i+a)/2)][0],n=t[o+1][0],e===r||e>r&&ee&&(a=o-1)}return Math.max(o-1,0)}var c=t("../util/color_spaces"),p=t("../util/color"),h=t("../util/extend"),f=t("../util/get_type"),d=t("../util/interpolate"),y=t("../expression/definitions/interpolate");e.exports={createFunction:function t(e,r){var n,u,f,d="color"===r.type,m=e.stops&&"object"==typeof e.stops[0][0],g=m||void 0!==e.property,v=m||!g,_=e.type||("interpolated"===r.function?"exponential":"interval");if(d&&((e=h({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],p.parse(t[1])]})),e.default?e.default=p.parse(e.default):e.default=p.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!c[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===_)n=s;else if("interval"===_)n=o;else if("categorical"===_){n=a,u=Object.create(null);for(var x=0,b=e.stops;x":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}}}},{}],153:[function(t,e,r){var n=t("csscolorparser").parseCSSColor,i=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n};i.parse=function(t){if(t){if(t instanceof i)return t;if("string"==typeof t){var e=n(t);if(e)return new i(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},i.prototype.toString=function(){var t=this;return"rgba("+[this.r,this.g,this.b].map(function(e){return Math.round(255*e/t.a)}).concat(this.a).join(",")+")"},i.black=new i(0,0,0,1),i.white=new i(1,1,1,1),i.transparent=new i(0,0,0,0),e.exports=i},{csscolorparser:13}],154:[function(t,e,r){function n(t){return t>g?Math.pow(t,1/3):t/m+d}function i(t){return t>y?t*t*t:m*(t-d)}function a(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function o(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function s(t){var e=o(t.r),r=o(t.g),i=o(t.b),a=n((.4124564*e+.3575761*r+.1804375*i)/p),s=n((.2126729*e+.7151522*r+.072175*i)/h);return{l:116*s-16,a:500*(a-s),b:200*(s-n((.0193339*e+.119192*r+.9503041*i)/f)),alpha:t.a}}function l(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=h*i(e),r=p*i(r),n=f*i(n),new u(a(3.2404542*r-1.5371385*e-.4985314*n),a(-.969266*r+1.8760108*e+.041556*n),a(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var u=t("./color"),c=t("./interpolate").number,p=.95047,h=1,f=1.08883,d=4/29,y=6/29,m=3*y*y,g=y*y*y,v=Math.PI/180,_=180/Math.PI;e.exports={lab:{forward:s,reverse:l,interpolate:function(t,e,r){return{l:c(t.l,e.l,r),a:c(t.a,e.a,r),b:c(t.b,e.b,r),alpha:c(t.alpha,e.alpha,r)}}},hcl:{forward:function(t){var e=s(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*_;return{h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*v,r=t.c;return l({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:c(t.c,e.c,r),l:c(t.l,e.l,r),alpha:c(t.alpha,e.alpha,r)}}}}},{"./color":153,"./interpolate":158}],155:[function(t,e,r){e.exports=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n0;)r[n]=e[n+1];for(var i=0,a=r;i":case">=":r.length>=2&&"$type"===s(r[1])&&c.push(new n(i,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&c.push(new n(i,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(l=o(r[1]))&&c.push(new n(i+"[1]",r[1],"string expected, "+l+" found"));for(var p=2;pu(s[0].zoom))return[new n(c,s[0].zoom,"stop zoom values must appear in ascending order")];u(s[0].zoom)!==h&&(h=u(s[0].zoom),p=void 0,y={}),e=e.concat(o({key:c+"[0]",value:s[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:l,value:r}}))}else e=e.concat(r({key:c+"[0]",value:s[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},s));return e.concat(a({key:c+"[1]",value:s[1],valueSpec:f,style:t.style,styleSpec:t.styleSpec}))}function r(t,e){var r=i(t.value),a=u(t.value),o=null!==t.value?t.value:e;if(c){if(r!==c)return[new n(t.key,o,r+" stop domain type must match previous stop domain type "+c)]}else c=r;if("number"!==r&&"string"!==r&&"boolean"!==r)return[new n(t.key,o,"stop domain value must be a number, string, or boolean")];if("number"!==r&&"categorical"!==d){var s="number expected, "+r+" found";return f["property-function"]&&void 0===d&&(s+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new n(t.key,o,s)]}return"categorical"!==d||"number"!==r||isFinite(a)&&Math.floor(a)===a?"categorical"!==d&&"number"===r&&void 0!==p&&a=8&&(g&&!t.valueSpec["property-function"]?_.push(new n(t.key,t.value,"property functions not supported")):m&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&_.push(new n(t.key,t.value,"zoom functions not supported"))),"categorical"!==d&&!v||void 0!==t.value.property||_.push(new n(t.key,t.value,'"property" property is required')),_}},{"../error/validation_error":122,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162,"./validate_array":163,"./validate_number":175,"./validate_object":176}],171:[function(t,e,r){var n=t("../error/validation_error"),i=t("./validate_string");e.exports=function(t){var e=t.value,r=t.key,a=i(t);return a.length?a:(-1===e.indexOf("{fontstack}")&&a.push(new n(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&a.push(new n(r,e,'"glyphs" url must include a "{range}" token')),a)}},{"../error/validation_error":122,"./validate_string":180}],172:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_filter"),s=t("./validate_paint_property"),l=t("./validate_layout_property"),u=t("./validate"),c=t("../util/extend");e.exports=function(t){var e=[],r=t.value,p=t.key,h=t.style,f=t.styleSpec;r.type||r.ref||e.push(new n(p,r,'either "type" or "ref" is required'));var d,y=i(r.type),m=i(r.ref);if(r.id)for(var g=i(r.id),v=0;va.maximum?[new i(e,r,r+" is greater than the maximum value "+a.maximum)]:[]}},{"../error/validation_error":122,"../util/get_type":157}],176:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/get_type"),a=t("./validate");e.exports=function(t){var e=t.key,r=t.value,o=t.valueSpec||{},s=t.objectElementValidators||{},l=t.style,u=t.styleSpec,c=[],p=i(r);if("object"!==p)return[new n(e,r,"object expected, "+p+" found")];for(var h in r){var f=h.split(".")[0],d=o[f]||o["*"],y=void 0;if(s[f])y=s[f];else if(o[f])y=a;else if(s["*"])y=s["*"];else{if(!o["*"]){c.push(new n(e,r[h],'unknown property "'+h+'"'));continue}y=a}c=c.concat(y({key:(e?e+".":e)+h,value:r[h],valueSpec:d,style:l,styleSpec:u,object:r,objectKey:h},r))}for(var m in o)s[m]||o[m].required&&void 0===o[m].default&&void 0===r[m]&&c.push(new n(e,r,'missing required property "'+m+'"'));return c}},{"../error/validation_error":122,"../util/get_type":157,"./validate":162}],177:[function(t,e,r){var n=t("./validate_property");e.exports=function(t){return n(t,"paint")}},{"./validate_property":178}],178:[function(t,e,r){var n=t("./validate"),i=t("../error/validation_error"),a=t("../util/get_type"),o=t("../function").isFunction,s=t("../util/unbundle_jsonlint");e.exports=function(t,e){var r=t.key,l=t.style,u=t.styleSpec,c=t.value,p=t.objectKey,h=u[e+"_"+t.layerType];if(!h)return[];var f=p.match(/^(.*)-transition$/);if("paint"===e&&f&&h[f[1]]&&h[f[1]].transition)return n({key:r,value:c,valueSpec:u.transition,style:l,styleSpec:u});var d,y=t.valueSpec||h[p];if(!y)return[new i(r,c,'unknown property "'+p+'"')];if("string"===a(c)&&y["property-function"]&&!y.tokens&&(d=/^{([^}]+)}$/.exec(c)))return[new i(r,c,'"'+p+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(d[1])+" }`.")];var m=[];return"symbol"===t.layerType&&("text-field"===p&&l&&!l.glyphs&&m.push(new i(r,c,'use of "text-field" requires a style "glyphs" property')),"text-font"===p&&o(s.deep(c))&&"identity"===s(c.type)&&m.push(new i(r,c,'"text-font" does not support identity functions'))),m.concat(n({key:t.key,value:c,valueSpec:y,style:l,styleSpec:u,expressionContext:"property",propertyKey:p}))}},{"../error/validation_error":122,"../function":149,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162}],179:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_enum");e.exports=function(t){var e=t.value,r=t.key,s=t.styleSpec,l=t.style;if(!e.type)return[new n(r,e,'"type" is required')];var u=i(e.type),c=[];switch(u){case"vector":case"raster":case"raster-dem":if(c=c.concat(a({key:r,value:e,valueSpec:s["source_"+u.replace("-","_")],style:t.style,styleSpec:s})),"url"in e)for(var p in e)["type","url","tileSize"].indexOf(p)<0&&c.push(new n(r+"."+p,e[p],'a source with a "url" property may not include a "'+p+'" property'));return c;case"geojson":return a({key:r,value:e,valueSpec:s.source_geojson,style:l,styleSpec:s});case"video":return a({key:r,value:e,valueSpec:s.source_video,style:l,styleSpec:s});case"image":return a({key:r,value:e,valueSpec:s.source_image,style:l,styleSpec:s});case"canvas":return a({key:r,value:e,valueSpec:s.source_canvas,style:l,styleSpec:s});default:return o({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image","canvas"]},style:l,styleSpec:s})}}},{"../error/validation_error":122,"../util/unbundle_jsonlint":161,"./validate_enum":167,"./validate_object":176}],180:[function(t,e,r){var n=t("../util/get_type"),i=t("../error/validation_error");e.exports=function(t){var e=t.value,r=t.key,a=n(e);return"string"!==a?[new i(r,e,"string expected, "+a+" found")]:[]}},{"../error/validation_error":122,"../util/get_type":157}],181:[function(t,e,r){function n(t,e){e=e||l;var r=[];return r=r.concat(s({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:u,"*":function(){return[]}}})),t.constants&&(r=r.concat(o({key:"constants",value:t.constants,style:t,styleSpec:e}))),i(r)}function i(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function a(t){return function(){return i(t.apply(this,arguments))}}var o=t("./validate/validate_constants"),s=t("./validate/validate"),l=t("./reference/latest"),u=t("./validate/validate_glyphs_url");n.source=a(t("./validate/validate_source")),n.light=a(t("./validate/validate_light")),n.layer=a(t("./validate/validate_layer")),n.filter=a(t("./validate/validate_filter")),n.paintProperty=a(t("./validate/validate_paint_property")),n.layoutProperty=a(t("./validate/validate_layout_property")),e.exports=n},{"./reference/latest":151,"./validate/validate":162,"./validate/validate_constants":166,"./validate/validate_filter":169,"./validate/validate_glyphs_url":171,"./validate/validate_layer":172,"./validate/validate_layout_property":173,"./validate/validate_light":174,"./validate/validate_paint_property":177,"./validate/validate_source":179}],182:[function(t,e,r){var n=t("./zoom_history"),i=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new n,this.transition={})};i.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},e.exports=i},{"./zoom_history":212}],183:[function(t,e,r){var n=t("../style-spec/reference/latest"),i=t("../util/util"),a=t("../util/evented"),o=t("./validate_style"),s=t("../util/util").sphericalToCartesian,l=(t("../style-spec/util/color"),t("../style-spec/util/interpolate")),u=t("./properties"),c=u.Properties,p=u.Transitionable,h=(u.Transitioning,u.PossiblyEvaluated,u.DataConstantProperty),f=function(){this.specification=n.light.position};f.prototype.possiblyEvaluate=function(t,e){return s(t.expression.evaluate(e))},f.prototype.interpolate=function(t,e,r){return{x:l.number(t.x,e.x,r),y:l.number(t.y,e.y,r),z:l.number(t.z,e.z,r)}};var d=new c({anchor:new h(n.light.anchor),position:new f,color:new h(n.light.color),intensity:new h(n.light.intensity)}),y=function(t){function e(e){t.call(this),this._transitionable=new p(d),this.setLight(e),this._transitioning=this._transitionable.untransitioned()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLight=function(){return this._transitionable.serialize()},e.prototype.setLight=function(t){if(!this._validate(o.light,t))for(var e in t){var r=t[e];i.endsWith(e,"-transition")?this._transitionable.setTransition(e.slice(0,-"-transition".length),r):this._transitionable.setValue(e,r)}},e.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning)},e.prototype.hasTransition=function(){return this._transitioning.hasTransition()},e.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t)},e.prototype._validate=function(t,e){return o.emitErrors(this,t.call(o,i.extend({value:e,style:{glyphs:!0,sprite:!0},styleSpec:n})))},e}(a);e.exports=y},{"../style-spec/reference/latest":151,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/evented":260,"../util/util":275,"./properties":188,"./validate_style":211}],184:[function(t,e,r){var n=t("../util/mapbox").normalizeGlyphsURL,i=t("../util/ajax"),a=t("./parse_glyph_pbf");e.exports=function(t,e,r,o,s){var l=256*e,u=l+255,c=o(n(r).replace("{fontstack}",t).replace("{range}",l+"-"+u),i.ResourceType.Glyphs);i.getArrayBuffer(c,function(t,e){if(t)s(t);else if(e){for(var r={},n=0,i=a(e.data);n1?"@2x":"";n.getJSON(e(a(t,p,".json"),n.ResourceType.SpriteJSON),function(t,e){c||(c=t,l=e,s())}),n.getImage(e(a(t,p,".png"),n.ResourceType.SpriteImage),function(t,e){c||(c=t,u=e,s())})}},{"../util/ajax":251,"../util/browser":252,"../util/image":263,"../util/mapbox":267}],186:[function(t,e,r){function n(t,e,r){1===t&&r.readMessage(i,e)}function i(t,e,r){if(3===t){var n=r.readMessage(a,{}),i=n.id,s=n.bitmap,u=n.width,c=n.height,p=n.left,h=n.top,f=n.advance;e.push({id:i,bitmap:new o({width:u+2*l,height:c+2*l},s),metrics:{width:u,height:c,left:p,top:h,advance:f}})}}function a(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint())}var o=t("../util/image").AlphaImage,s=t("pbf"),l=3;e.exports=function(t){return new s(t).readFields(n,[])},e.exports.GLYPH_PBF_BORDER=l},{"../util/image":263,pbf:30}],187:[function(t,e,r){var n=t("../util/browser"),i=t("../symbol/placement"),a=function(){this._currentTileIndex=0,this._seenCrossTileIDs={}};a.prototype.continuePlacement=function(t,e,r,n,i){for(var a=this;this._currentTileIndex2};this._currentPlacementIndex>=0;){var l=e[t[i._currentPlacementIndex]],u=i.placement.collisionIndex.transform.zoom;if("symbol"===l.type&&(!l.minzoom||l.minzoom<=u)&&(!l.maxzoom||l.maxzoom>u)){if(i._inProgressLayer||(i._inProgressLayer=new a),i._inProgressLayer.continuePlacement(r[l.source],i.placement,i._showCollisionBoxes,l,s))return;delete i._inProgressLayer}i._currentPlacementIndex--}this._done=!0},o.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement},e.exports=o},{"../symbol/placement":223,"../util/browser":252}],188:[function(t,e,r){var n=t("../util/util"),i=n.clone,a=n.extend,o=n.easeCubicInOut,s=t("../style-spec/util/interpolate"),l=t("../style-spec/expression").normalizePropertyExpression,u=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),c=function(t,e){this.property=t,this.value=e,this.expression=l(void 0===e?t.specification.default:e,t.specification)};c.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},c.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var p=function(t){this.property=t,this.value=new c(t,void 0)};p.prototype.transitioned=function(t,e){return new f(this.property,this.value,e,a({},t.transition,this.transition),t.now)},p.prototype.untransitioned=function(){return new f(this.property,this.value,null,{},0)};var h=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)};h.prototype.getValue=function(t){return i(this._values[t].value.value)},h.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new p(this._values[t].property)),this._values[t].value=new c(this._values[t].property,null===e?void 0:i(e))},h.prototype.getTransition=function(t){return i(this._values[t].transition)},h.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new p(this._values[t].property)),this._values[t].transition=i(e)||void 0},h.prototype.serialize=function(){for(var t=this,e={},r=0,n=Object.keys(t._values);rthis.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(en.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:a+(1-a)*o}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-o)*a}},x.prototype.interpolate=function(t){return t};var b=function(t){this.specification=t};b.prototype.possiblyEvaluate=function(){},b.prototype.interpolate=function(){};u("DataDrivenProperty",_),u("DataConstantProperty",v),u("CrossFadedProperty",x),u("HeatmapColorProperty",b),e.exports={PropertyValue:c,Transitionable:h,Transitioning:d,Layout:y,PossiblyEvaluatedPropertyValue:m,PossiblyEvaluated:g,DataConstantProperty:v,DataDrivenProperty:_,CrossFadedProperty:x,HeatmapColorProperty:b,Properties:function(t){var e=this;for(var r in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var n=t[r],i=e.defaultPropertyValues[r]=new c(n,void 0),a=e.defaultTransitionablePropertyValues[r]=new p(n);e.defaultTransitioningPropertyValues[r]=a.untransitioned(),e.defaultPossiblyEvaluatedValues[r]=i.possiblyEvaluate({})}}}},{"../style-spec/expression":139,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/util":275,"../util/web_worker_transfer":278}],189:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports={getMaximumPaintValue:function(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max},translateDistance:function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},translate:function(t,e,r,i,a){if(!e[0]&&!e[1])return t;var o=n.convert(e);"viewport"===r&&o._rotate(-i);for(var s=[],l=0;l0)throw new Error("Unimplemented: "+n.map(function(t){return t.command}).join(", ")+".");return r.forEach(function(t){"setTransition"!==t.command&&e[t.command].apply(e,t.args)}),this.stylesheet=t,!0},e.prototype.addImage=function(t,e){if(this.getImage(t))return this.fire("error",{error:new Error("An image with this name already exists.")});this.imageManager.addImage(t,e),this.fire("data",{dataType:"style"})},e.prototype.getImage=function(t){return this.imageManager.getImage(t)},e.prototype.removeImage=function(t){if(!this.getImage(t))return this.fire("error",{error:new Error("No image with this name exists.")});this.imageManager.removeImage(t),this.fire("data",{dataType:"style"})},e.prototype.addSource=function(t,e,r){var n=this;if(this._checkLoaded(),void 0!==this.sourceCaches[t])throw new Error("There is already a source with this ID");if(!e.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(e).join(", ")+".");if(!(["vector","raster","geojson","video","image","canvas"].indexOf(e.type)>=0&&this._validate(y.source,"sources."+t,e,null,r))){this.map&&this.map._collectResourceTiming&&(e.collectResourceTiming=!0);var i=this.sourceCaches[t]=new _(t,e,this.dispatcher);i.style=this,i.setEventedParent(this,function(){return{isSourceLoaded:n.loaded(),source:i.serialize(),sourceId:t}}),i.onAdd(this.map),this._changed=!0}},e.prototype.removeSource=function(t){var e=this;if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error("There is no source with this ID");for(var r in e._layers)if(e._layers[r].source===t)return e.fire("error",{error:new Error('Source "'+t+'" cannot be removed while layer "'+r+'" is using it.')});var n=this.sourceCaches[t];delete this.sourceCaches[t],delete this._updatedSources[t],n.fire("data",{sourceDataType:"metadata",dataType:"source",sourceId:t}),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0},e.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0},e.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},e.prototype.addLayer=function(t,e,r){this._checkLoaded();var n=t.id;if("object"==typeof t.source&&(this.addSource(n,t.source),t=c.clone(t),t=c.extend(t,{source:n})),!this._validate(y.layer,"layers."+n,t,{arrayIndex:-1},r)){var a=i.create(t);this._validateLayer(a),a.setEventedParent(this,{layer:{id:n}});var o=e?this._order.indexOf(e):this._order.length;if(e&&-1===o)return void this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')});if(this._order.splice(o,0,n),this._layerOrderChanged=!0,this._layers[n]=a,this._removedLayers[n]&&a.source){var s=this._removedLayers[n];delete this._removedLayers[n],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause())}this._updateLayer(a)}},e.prototype.moveLayer=function(t,e){if(this._checkLoaded(),this._changed=!0,this._layers[t]){var r=this._order.indexOf(t);this._order.splice(r,1);var n=e?this._order.indexOf(e):this._order.length;e&&-1===n?this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')}):(this._order.splice(n,0,t),this._layerOrderChanged=!0)}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be moved.")})},e.prototype.removeLayer=function(t){this._checkLoaded();var e=this._layers[t];if(e){e.setEventedParent(null);var r=this._order.indexOf(t);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[t]=e,delete this._layers[t],delete this._updatedLayers[t],delete this._updatedPaintProps[t]}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be removed.")})},e.prototype.getLayer=function(t){return this._layers[t]},e.prototype.setLayerZoomRange=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?n.minzoom===e&&n.maxzoom===r||(null!=e&&(n.minzoom=e),null!=r&&(n.maxzoom=r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot have zoom extent.")})},e.prototype.setFilter=function(t,e){this._checkLoaded();var r=this.getLayer(t);if(r)return c.deepEqual(r.filter,e)?void 0:null===e||void 0===e?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(y.filter,"layers."+r.id+".filter",e)||(r.filter=c.clone(e),this._updateLayer(r)));this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be filtered.")})},e.prototype.getFilter=function(t){return c.clone(this.getLayer(t).filter)},e.prototype.setLayoutProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?c.deepEqual(n.getLayoutProperty(e),r)||(n.setLayoutProperty(e,r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},e.prototype.setPaintProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);if(n){if(!c.deepEqual(n.getPaintProperty(e),r)){var i=n._transitionablePaint._values[e].value.isDataDriven();n.setPaintProperty(e,r),(n._transitionablePaint._values[e].value.isDataDriven()||i)&&this._updateLayer(n),this._changed=!0,this._updatedPaintProps[t]=!0}}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},e.prototype.getTransition=function(){return c.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},e.prototype.serialize=function(){var t=this;return c.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:c.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(e){return t._layers[e].serialize()})},function(t){return void 0!==t})},e.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0},e.prototype._flattenRenderedFeatures=function(t){for(var e=[],r=this._order.length-1;r>=0;r--)for(var n=this._order[r],i=0,a=t;i=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t)},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),n.filterObject(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,o){return(!o||!1!==o.validate)&&a.emitErrors(this,t.call(a,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:i,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(o));e.exports=c;var p={circle:t("./style_layer/circle_style_layer"),heatmap:t("./style_layer/heatmap_style_layer"),hillshade:t("./style_layer/hillshade_style_layer"),fill:t("./style_layer/fill_style_layer"),"fill-extrusion":t("./style_layer/fill_extrusion_style_layer"),line:t("./style_layer/line_style_layer"),symbol:t("./style_layer/symbol_style_layer"),background:t("./style_layer/background_style_layer"),raster:t("./style_layer/raster_style_layer")};c.create=function(t){return new p[t.type](t)}},{"../style-spec/reference/latest":151,"../util/evented":260,"../util/util":275,"./properties":188,"./style_layer/background_style_layer":192,"./style_layer/circle_style_layer":194,"./style_layer/fill_extrusion_style_layer":196,"./style_layer/fill_style_layer":198,"./style_layer/heatmap_style_layer":200,"./style_layer/hillshade_style_layer":202,"./style_layer/line_style_layer":204,"./style_layer/raster_style_layer":206,"./style_layer/symbol_style_layer":208,"./validate_style":211}],192:[function(t,e,r){var n=t("../style_layer"),i=t("./background_style_layer_properties"),a=t("../properties"),o=(a.Transitionable,a.Transitioning,a.PossiblyEvaluated,function(t){function e(e){t.call(this,e,i)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(n));e.exports=o},{"../properties":188,"../style_layer":191,"./background_style_layer_properties":193}],193:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=(i.DataDrivenProperty,i.CrossFadedProperty),l=(i.HeatmapColorProperty,new a({"background-color":new o(n.paint_background["background-color"]),"background-pattern":new s(n.paint_background["background-pattern"]),"background-opacity":new o(n.paint_background["background-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],194:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/circle_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiPoint,o=t("../query_utils"),s=o.getMaximumPaintValue,l=o.translateDistance,u=o.translate,c=t("./circle_style_layer_properties"),p=t("../properties"),h=(p.Transitionable,p.Transitioning,p.PossiblyEvaluated,function(t){function e(e){t.call(this,e,c)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(t){var e=t;return s("circle-radius",this,e)+s("circle-stroke-width",this,e)+l(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=u(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i,o),l=this.paint.get("circle-radius").evaluate(e)*o,c=this.paint.get("circle-stroke-width").evaluate(e)*o;return a(s,r,l+c)},e}(n));e.exports=h},{"../../data/bucket/circle_bucket":42,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./circle_style_layer_properties":195}],195:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=(i.CrossFadedProperty,i.HeatmapColorProperty,new a({"circle-radius":new s(n.paint_circle["circle-radius"]),"circle-color":new s(n.paint_circle["circle-color"]),"circle-blur":new s(n.paint_circle["circle-blur"]),"circle-opacity":new s(n.paint_circle["circle-opacity"]),"circle-translate":new o(n.paint_circle["circle-translate"]),"circle-translate-anchor":new o(n.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new o(n.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new o(n.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new s(n.paint_circle["circle-stroke-width"]),"circle-stroke-color":new s(n.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new s(n.paint_circle["circle-stroke-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],196:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_extrusion_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,o=t("../query_utils"),s=o.translateDistance,l=o.translate,u=t("./fill_extrusion_style_layer_properties"),c=t("../properties"),p=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=l(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i,o);return a(s,r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null)},e}(n));e.exports=p},{"../../data/bucket/fill_extrusion_bucket":46,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_extrusion_style_layer_properties":197}],197:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new a({"fill-extrusion-opacity":new o(n["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new s(n["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new o(n["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new o(n["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new l(n["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new s(n["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new s(n["paint_fill-extrusion"]["fill-extrusion-base"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],198:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,o=t("../query_utils"),s=o.translateDistance,l=o.translate,u=t("./fill_style_layer_properties"),c=t("../properties"),p=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t),void 0===this._transitionablePaint.getValue("fill-outline-color")&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])},e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=l(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i,o);return a(s,r)},e}(n));e.exports=p},{"../../data/bucket/fill_bucket":44,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_style_layer_properties":199}],199:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new a({"fill-antialias":new o(n.paint_fill["fill-antialias"]),"fill-opacity":new s(n.paint_fill["fill-opacity"]),"fill-color":new s(n.paint_fill["fill-color"]),"fill-outline-color":new s(n.paint_fill["fill-outline-color"]),"fill-translate":new o(n.paint_fill["fill-translate"]),"fill-translate-anchor":new o(n.paint_fill["fill-translate-anchor"]),"fill-pattern":new l(n.paint_fill["fill-pattern"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],200:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/heatmap_bucket"),a=t("../../util/image").RGBAImage,o=t("./heatmap_style_layer_properties"),s=t("../properties"),l=(s.Transitionable,s.Transitioning,s.PossiblyEvaluated,function(t){function e(e){t.call(this,e,o),this._updateColorRamp()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp()},e.prototype._updateColorRamp=function(){for(var t=this._transitionablePaint._values["heatmap-color"].value.expression,e=new Uint8Array(1024),r=e.length,n=4;n0?e+2*t:t}var i=t("@mapbox/point-geometry"),a=t("../style_layer"),o=t("../../data/bucket/line_bucket"),s=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiLine,l=t("../query_utils"),u=l.getMaximumPaintValue,c=l.translateDistance,p=l.translate,h=t("./line_style_layer_properties"),f=t("../../util/util").extend,d=t("../evaluation_parameters"),y=t("../properties"),m=(y.Transitionable,y.Transitioning,y.Layout,y.PossiblyEvaluated,new(function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new d(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=f({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(y.DataDrivenProperty))(h.paint.properties["line-width"].specification));m.useIntegerZoom=!0;var g=function(t){function e(e){t.call(this,e,h)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=m.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)},e.prototype.createBucket=function(t){return new o(t)},e.prototype.queryRadius=function(t){var e=t,r=n(u("line-width",this,e),u("line-gap-width",this,e)),i=u("line-offset",this,e);return r/2+Math.abs(i)+c(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,a,o,l){var u=p(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o,l),c=l/2*n(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),h=this.paint.get("line-offset").evaluate(e);return h&&(r=function(t,e){for(var r=[],n=new i(0,0),a=0;ar?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom-r/2;){if(--o<0)return!1;s-=t[o].dist(a),a=t[o]}s+=t[o].dist(t[o+1]),o++;for(var l=[],u=0;sn;)u-=l.shift().angleDelta;if(u>i)return!1;o++,s+=p.dist(h)}return!0}},{}],215:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports=function(t,e,r,i,a){for(var o=[],s=0;s=i&&h.x>=i||(p.x>=i?p=new n(i,p.y+(h.y-p.y)*((i-p.x)/(h.x-p.x)))._round():h.x>=i&&(h=new n(i,p.y+(h.y-p.y)*((i-p.x)/(h.x-p.x)))._round()),p.y>=a&&h.y>=a||(p.y>=a?p=new n(p.x+(h.x-p.x)*((a-p.y)/(h.y-p.y)),a)._round():h.y>=a&&(h=new n(p.x+(h.x-p.x)*((a-p.y)/(h.y-p.y)),a)._round()),u&&p.equals(u[u.length-1])||(u=[p],o.push(u)),u.push(h)))))}return o}},{"@mapbox/point-geometry":4}],216:[function(t,e,r){var n=function(t,e,r,n,i,a,o,s,l,u,c){var p=o.top*s-l,h=o.bottom*s+l,f=o.left*s-l,d=o.right*s+l;if(this.boxStartIndex=t.length,u){var y=h-p,m=d-f;y>0&&(y=Math.max(10*s,y),this._addLineCollisionCircles(t,e,r,r.segment,m,y,n,i,a,c))}else t.emplaceBack(r.x,r.y,f,p,d,h,n,i,a,0,0);this.boxEndIndex=t.length};n.prototype._addLineCollisionCircles=function(t,e,r,n,i,a,o,s,l,u){var c=a/2,p=Math.floor(i/c),h=1+.4*Math.log(u)/Math.LN2,f=Math.floor(p*h/2),d=-a/2,y=r,m=n+1,g=d,v=-i/2,_=v-i/4;do{if(--m<0){if(g>v)return;m=0;break}g-=e[m].dist(y),y=e[m]}while(g>_);for(var x=e[m].dist(e[m+1]),b=-f;bi&&(k+=w-i),!(k=e.length)return;x=e[m].dist(e[m+1])}var A=k-g,T=e[m],M=e[m+1].sub(T)._unit()._mult(A)._add(T)._round(),S=Math.abs(k-d)L)n(t,E,!1);else{var R=m.projectPoint(h,P,I),B=D*S;if(g.length>0){var F=R.x-g[g.length-4],N=R.y-g[g.length-3];if(B*B*2>F*F+N*N&&E+8-z&&j=this.screenRightBoundary||n<100||e>this.screenBottomBoundary},e.exports=l},{"../symbol/projection":224,"../util/intersection_tests":264,"./grid_index":220,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],218:[function(t,e,r){var n=t("../data/extent"),i=512/n/2,a=function(t,e,r){var n=this;this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=r;for(var i=0,a=e;it.overscaledZ)for(var u in l){var c=l[u];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,o)}else{var p=l[t.scaledTo(Number(s)).key];p&&p.findMatches(e.symbolInstances,t,o)}}for(var h=0,f=e.symbolInstances;h=0&&T=0&&M=0&&g+f<=d){var S=new i(T,M,k,_);S._round(),s&&!a(e,S,u,s,l)||v.push(S)}}m+=w}return p||v.length||c||(v=t(e,m/2,o,s,l,u,c,!0,h)),v}(t,d?e/2*c%e:(f/2+2*l)*u*c%e,e,h,r,f*u,d,!1,p)}},{"../style-spec/util/interpolate":158,"../symbol/anchor":213,"./check_max_angle":214}],220:[function(t,e,r){var n=function(t,e,r){var n=this.boxCells=[],i=this.circleCells=[];this.xCellCount=Math.ceil(t/r),this.yCellCount=Math.ceil(e/r);for(var a=0;athis.width||n<0||e>this.height)return!i&&[];var a=[];if(t<=0&&e<=0&&this.width<=r&&this.height<=n)a=Array.prototype.slice.call(this.boxKeys).concat(this.circleKeys);else{var o={hitTest:i,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,r,n,this._queryCell,a,o)}return i?a.length>0:a},n.prototype._queryCircle=function(t,e,r,n){var i=t-r,a=t+r,o=e-r,s=e+r;if(a<0||i>this.width||s<0||o>this.height)return!n&&[];var l=[],u={hitTest:n,circle:{x:t,y:e,radius:r},seenUids:{box:{},circle:{}}};return this._forEachCell(i,o,a,s,this._queryCellCircle,l,u),n?l.length>0:l},n.prototype.query=function(t,e,r,n){return this._query(t,e,r,n,!1)},n.prototype.hitTest=function(t,e,r,n){return this._query(t,e,r,n,!0)},n.prototype.hitTestCircle=function(t,e,r){return this._queryCircle(t,e,r,!0)},n.prototype._queryCell=function(t,e,r,n,i,a,o){var s=this,l=o.seenUids,u=this.boxCells[i];if(null!==u)for(var c=this.bboxes,p=0,h=u;p=c[d+0]&&n>=c[d+1]){if(o.hitTest)return a.push(!0),!0;a.push(s.boxKeys[f])}}}var y=this.circleCells[i];if(null!==y)for(var m=this.circles,g=0,v=y;go*o+s*s},n.prototype._circleAndRectCollide=function(t,e,r,n,i,a,o){var s=(a-n)/2,l=Math.abs(t-(n+s));if(l>s+r)return!1;var u=(o-i)/2,c=Math.abs(e-(i+u));if(c>u+r)return!1;if(l<=s||c<=u)return!0;var p=l-s,h=c-u;return p*p+h*h<=r*r},e.exports=n},{}],221:[function(t,e,r){e.exports=function(t){function e(e){s.push(t[e]),l++}function r(t,e,r){var n=o[t];return delete o[t],o[e]=n,s[n].geometry[0].pop(),s[n].geometry[0]=s[n].geometry[0].concat(r[0]),n}function n(t,e,r){var n=a[e];return delete a[e],a[t]=n,s[n].geometry[0].shift(),s[n].geometry[0]=r[0].concat(s[n].geometry[0]),n}function i(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var a={},o={},s=[],l=0,u=0;u0,A=A&&T.offscreen);var C=b.collisionArrays.textCircles;if(C){var z=t.text.placedSymbolArray.get(b.placedTextSymbolIndices[0]),L=s.evaluateSizeForFeature(t.textSizeData,m,z);M=d.collisionIndex.placeCollisionCircles(C,y.get("text-allow-overlap"),i,a,b.key,z,t.lineVertexArray,t.glyphOffsetArray,L,e,r,o,"map"===y.get("text-pitch-alignment")),w=y.get("text-allow-overlap")||M.circles.length>0,A=A&&M.offscreen}b.collisionArrays.iconBox&&(k=(S=d.collisionIndex.placeCollisionBox(b.collisionArrays.iconBox,y.get("icon-allow-overlap"),a,e)).box.length>0,A=A&&S.offscreen),g||v?v?g||(k=k&&w):w=k&&w:k=w=k&&w,w&&T&&d.collisionIndex.insertCollisionBox(T.box,y.get("text-ignore-placement"),p,h,t.bucketInstanceId,b.textBoxStartIndex),k&&S&&d.collisionIndex.insertCollisionBox(S.box,y.get("icon-ignore-placement"),p,h,t.bucketInstanceId,b.iconBoxStartIndex),w&&M&&d.collisionIndex.insertCollisionCircles(M.circles,y.get("text-ignore-placement"),p,h,t.bucketInstanceId,b.textBoxStartIndex),d.placements[b.crossTileID]=new f(w,k,A||t.justReloaded),l[b.crossTileID]=!0}}t.justReloaded=!1},d.prototype.commit=function(t,e){var r=this;this.commitTime=e;var n=!1,i=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,a=t?t.opacities:{};for(var o in r.placements){var s=r.placements[o],l=a[o];l?(r.opacities[o]=new h(l,i,s.text,s.icon),n=n||s.text!==l.text.placed||s.icon!==l.icon.placed):(r.opacities[o]=new h(null,i,s.text,s.icon,s.skipFade),n=n||s.text||s.icon)}for(var u in a){var c=a[u];if(!r.opacities[u]){var p=new h(c,i,!1,!1);p.isHidden()||(r.opacities[u]=p,n=n||c.text.placed||c.icon.placed)}}n?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)},d.prototype.updateLayerOpacities=function(t,e){for(var r={},n=0,i=e;n0||l.numVerticalGlyphVertices>0,f=l.numIconVertices>0;if(p){for(var d=i(c.text),y=(l.numGlyphVertices+l.numVerticalGlyphVertices)/4,m=0;mt},d.prototype.setStale=function(){this.stale=!0};var y=Math.pow(2,25),m=Math.pow(2,24),g=Math.pow(2,17),v=Math.pow(2,16),_=Math.pow(2,9),x=Math.pow(2,8),b=Math.pow(2,1);e.exports=d},{"../data/extent":53,"../source/pixels_to_tile_units":104,"../style/style_layer/symbol_style_layer_properties":209,"./collision_index":217,"./projection":224,"./symbol_size":228}],224:[function(t,e,r){function n(t,e){var r=[t.x,t.y,0,1];p(r,r,e);var n=r[3];return{point:new h(r[0]/n,r[1]/n),signedDistanceFromCamera:n}}function i(t,e){var r=t[0]/t[3],n=t[1]/t[3];return r>=-e[0]&&r<=e[0]&&n>=-e[1]&&n<=e[1]}function a(t,e,r,n,i,a,o,s,l,c,p,h){var f=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,y=s.lineStartIndex+s.lineLength,m=e.getoffsetX(s.glyphStartIndex),g=e.getoffsetX(f-1),v=u(t*m,r,n,i,a,o,s.segment,d,y,l,c,p,h);if(!v)return null;var _=u(t*g,r,n,i,a,o,s.segment,d,y,l,c,p,h);return _?{first:v,last:_}:null}function o(t,e,r,n){return t===_.horizontal&&Math.abs(r.y-e.y)>Math.abs(r.x-e.x)*n?{useVertical:!0}:(t===_.vertical?e.yr.x)?{needsFlipping:!0}:null}function s(t,e,r,i,s,c,p,f,d,y,m,v,_,x){var b,w=e/24,k=t.lineOffsetX*e,A=t.lineOffsetY*e;if(t.numGlyphs>1){var T=t.glyphStartIndex+t.numGlyphs,M=t.lineStartIndex,S=t.lineStartIndex+t.lineLength,C=a(w,f,k,A,r,m,v,t,d,c,_,!1);if(!C)return{notEnoughRoom:!0};var z=n(C.first.point,p).point,L=n(C.last.point,p).point;if(i&&!r){var E=o(t.writingMode,z,L,x);if(E)return E}b=[C.first];for(var P=t.glyphStartIndex+1;P0?R.point:l(v,O,I,1,s),F=o(t.writingMode,I,B,x);if(F)return F}var N=u(w*f.getoffsetX(t.glyphStartIndex),k,A,r,m,v,t.segment,t.lineStartIndex,t.lineStartIndex+t.lineLength,d,c,_,!1);if(!N)return{notEnoughRoom:!0};b=[N]}for(var j=0,V=b;j0?1:-1,v=0;i&&(g*=-1,v=Math.PI),g<0&&(v+=Math.PI);for(var _=g>0?u+s:u+s+1,x=_,b=a,w=a,k=0,A=0,T=Math.abs(m);k+A<=T;){if((_+=g)=c)return null;if(w=b,void 0===(b=d[_])){var M=new h(p.getx(_),p.gety(_)),S=n(M,f);if(S.signedDistanceFromCamera>0)b=d[_]=S.point;else{var C=_-g;b=l(0===k?o:new h(p.getx(C),p.gety(C)),M,w,T-k+1,f)}}k+=A,A=w.dist(b)}var z=(T-k)/A,L=b.sub(w),E=L.mult(z)._add(w);return E._add(L._unit()._perp()._mult(r*g)),{point:E,angle:v+Math.atan2(b.y-w.y,b.x-w.x),tileDistance:y?{prevTileDistance:_-g===x?0:p.gettileUnitDistanceFromAnchor(_-g),lastSegmentViewportDistance:T-k}:null}}function c(t,e){for(var r=0;r=w||o.y<0||o.y>=w||t.symbolInstances.push(function(t,e,r,n,a,o,s,l,c,p,h,d,y,_,x,b,w,A,T,M,S,C){var z,L,E=t.addToLineVertexArray(e,r),P=0,I=0,D=0,O=n.horizontal?n.horizontal.text:"",R=[];n.horizontal&&(z=new g(s,r,e,l,c,p,n.horizontal,h,d,y,t.overscaling),I+=i(t,e,n.horizontal,o,y,T,M,_,E,n.vertical?f.horizontal:f.horizontalOnly,R,S,C),n.vertical&&(D+=i(t,e,n.vertical,o,y,T,M,_,E,f.vertical,R,S,C)));var B=z?z.boxStartIndex:t.collisionBoxArray.length,F=z?z.boxEndIndex:t.collisionBoxArray.length;if(a){var N=m(e,a,o,w,n.horizontal,T,M);L=new g(s,r,e,l,c,p,a,x,b,!1,t.overscaling),P=4*N.length;var j=t.iconSizeData,V=null;"source"===j.functionType?V=[10*o.layout.get("icon-size").evaluate(M)]:"composite"===j.functionType&&(V=[10*C.compositeIconSizes[0].evaluate(M),10*C.compositeIconSizes[1].evaluate(M)]),t.addSymbols(t.icon,N,V,A,w,M,!1,e,E.lineStartIndex,E.lineLength)}var q=L?L.boxStartIndex:t.collisionBoxArray.length,U=L?L.boxEndIndex:t.collisionBoxArray.length;return t.glyphOffsetArray.length>=k.MAX_GLYPHS&&v.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),{key:O,textBoxStartIndex:B,textBoxEndIndex:F,iconBoxStartIndex:q,iconBoxEndIndex:U,textOffset:_,iconOffset:A,anchor:e,line:r,featureIndex:l,feature:M,numGlyphVertices:I,numVerticalGlyphVertices:D,numIconVertices:P,textOpacityState:new u,iconOpacityState:new u,isDuplicate:!1,placedTextSymbolIndices:R,crossTileID:0}}(t,o,a,r,n,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,S,E,D,A,z,P,O,T,{zoom:t.zoom},e,c,p))};if("line"===_.get("symbol-placement"))for(var F=0,N=l(e.geometry,0,0,w,w);F=0;o--)if(n.dist(a[o])1||(h?(clearTimeout(h),h=null,o("dblclick",e)):h=setTimeout(r,300))},!1),l.addEventListener("touchend",function(t){s("touchend",t)},!1),l.addEventListener("touchmove",function(t){s("touchmove",t)},!1),l.addEventListener("touchcancel",function(t){s("touchcancel",t)},!1),l.addEventListener("click",function(t){n.mousePos(l,t).equals(p)&&o("click",t)},!1),l.addEventListener("dblclick",function(t){o("dblclick",t),t.preventDefault()},!1),l.addEventListener("contextmenu",function(e){var r=t.dragRotate&&t.dragRotate.isActive();c||r?c&&(u=e):o("contextmenu",e),e.preventDefault()},!1)}},{"../util/dom":259,"./handler/box_zoom":239,"./handler/dblclick_zoom":240,"./handler/drag_pan":241,"./handler/drag_rotate":242,"./handler/keyboard":243,"./handler/scroll_zoom":244,"./handler/touch_zoom_rotate":245,"@mapbox/point-geometry":4}],231:[function(t,e,r){var n=t("../util/util"),i=t("../style-spec/util/interpolate").number,a=t("../util/browser"),o=t("../geo/lng_lat"),s=t("../geo/lng_lat_bounds"),l=t("@mapbox/point-geometry"),u=function(t){function e(e,r){t.call(this),this.moving=!1,this.transform=e,this._bearingSnap=r.bearingSnap}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getCenter=function(){return this.transform.center},e.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},e.prototype.panBy=function(t,e,r){return t=l.convert(t).mult(-1),this.panTo(this.transform.center,n.extend({offset:t},e),r)},e.prototype.panTo=function(t,e,r){return this.easeTo(n.extend({center:t},e),r)},e.prototype.getZoom=function(){return this.transform.zoom},e.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},e.prototype.zoomTo=function(t,e,r){return this.easeTo(n.extend({zoom:t},e),r)},e.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},e.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},e.prototype.getBearing=function(){return this.transform.bearing},e.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},e.prototype.rotateTo=function(t,e,r){return this.easeTo(n.extend({bearing:t},e),r)},e.prototype.resetNorth=function(t,e){return this.rotateTo(0,n.extend({duration:1e3},t),e),this},e.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())e?1:0}),["bottom","left","right","top"]))return n.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;t=s.convert(t);var a=[(e.padding.left-e.padding.right)/2,(e.padding.top-e.padding.bottom)/2],o=Math.min(e.padding.right,e.padding.left),u=Math.min(e.padding.top,e.padding.bottom);e.offset=[e.offset[0]+a[0],e.offset[1]+a[1]];var c=l.convert(e.offset),p=this.transform,h=p.project(t.getNorthWest()),f=p.project(t.getSouthEast()),d=f.sub(h),y=(p.width-2*o-2*Math.abs(c.x))/d.x,m=(p.height-2*u-2*Math.abs(c.y))/d.y;return m<0||y<0?(n.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(e.center=p.unproject(h.add(f).div(2)),e.zoom=Math.min(p.scaleZoom(p.scale*Math.min(y,m)),e.maxZoom),e.bearing=0,e.linear?this.easeTo(e,r):this.flyTo(e,r))},e.prototype.jumpTo=function(t,e){this.stop();var r=this.transform,n=!1,i=!1,a=!1;return"zoom"in t&&r.zoom!==+t.zoom&&(n=!0,r.zoom=+t.zoom),void 0!==t.center&&(r.center=o.convert(t.center)),"bearing"in t&&r.bearing!==+t.bearing&&(i=!0,r.bearing=+t.bearing),"pitch"in t&&r.pitch!==+t.pitch&&(a=!0,r.pitch=+t.pitch),this.fire("movestart",e).fire("move",e),n&&this.fire("zoomstart",e).fire("zoom",e).fire("zoomend",e),i&&this.fire("rotate",e),a&&this.fire("pitchstart",e).fire("pitch",e).fire("pitchend",e),this.fire("moveend",e)},e.prototype.easeTo=function(t,e){var r=this;this.stop(),!1===(t=n.extend({offset:[0,0],duration:500,easing:n.ease},t)).animate&&(t.duration=0);var a=this.transform,s=this.getZoom(),u=this.getBearing(),c=this.getPitch(),p="zoom"in t?+t.zoom:s,h="bearing"in t?this._normalizeBearing(t.bearing,u):u,f="pitch"in t?+t.pitch:c,d=a.centerPoint.add(l.convert(t.offset)),y=a.pointLocation(d),m=o.convert(t.center||y);this._normalizeCenter(m);var g,v,_=a.project(y),x=a.project(m).sub(_),b=a.zoomScale(p-s);return t.around&&(g=o.convert(t.around),v=a.locationPoint(g)),this.zooming=p!==s,this.rotating=u!==h,this.pitching=f!==c,this._prepareEase(e,t.noMoveStart),clearTimeout(this._onEaseEnd),this._ease(function(t){if(r.zooming&&(a.zoom=i(s,p,t)),r.rotating&&(a.bearing=i(u,h,t)),r.pitching&&(a.pitch=i(c,f,t)),g)a.setLocationAtPoint(g,v);else{var n=a.zoomScale(a.zoom-s),o=p>s?Math.min(2,b):Math.max(.5,b),l=Math.pow(o,1-t),y=a.unproject(_.add(x.mult(t*l)).mult(n));a.setLocationAtPoint(a.renderWorldCopies?y.wrap():y,d)}r._fireMoveEvents(e)},function(){t.delayEndEvents?r._onEaseEnd=setTimeout(function(){return r._afterEase(e)},t.delayEndEvents):r._afterEase(e)},t),this},e.prototype._prepareEase=function(t,e){this.moving=!0,e||this.fire("movestart",t),this.zooming&&this.fire("zoomstart",t),this.pitching&&this.fire("pitchstart",t)},e.prototype._fireMoveEvents=function(t){this.fire("move",t),this.zooming&&this.fire("zoom",t),this.rotating&&this.fire("rotate",t),this.pitching&&this.fire("pitch",t)},e.prototype._afterEase=function(t){var e=this.zooming,r=this.pitching;this.moving=!1,this.zooming=!1,this.rotating=!1,this.pitching=!1,e&&this.fire("zoomend",t),r&&this.fire("pitchend",t),this.fire("moveend",t)},e.prototype.flyTo=function(t,e){function r(t){var e=(T*T-A*A+(t?-1:1)*z*z*M*M)/(2*(t?T:A)*z*M);return Math.log(Math.sqrt(e*e+1)-e)}function a(t){return(Math.exp(t)-Math.exp(-t))/2}function s(t){return(Math.exp(t)+Math.exp(-t))/2}var u=this;this.stop(),t=n.extend({offset:[0,0],speed:1.2,curve:1.42,easing:n.ease},t);var c=this.transform,p=this.getZoom(),h=this.getBearing(),f=this.getPitch(),d="zoom"in t?n.clamp(+t.zoom,c.minZoom,c.maxZoom):p,y="bearing"in t?this._normalizeBearing(t.bearing,h):h,m="pitch"in t?+t.pitch:f,g=c.zoomScale(d-p),v=c.centerPoint.add(l.convert(t.offset)),_=c.pointLocation(v),x=o.convert(t.center||_);this._normalizeCenter(x);var b=c.project(_),w=c.project(x).sub(b),k=t.curve,A=Math.max(c.width,c.height),T=A/g,M=w.mag();if("minZoom"in t){var S=n.clamp(Math.min(t.minZoom,p,d),c.minZoom,c.maxZoom),C=A/c.zoomScale(S-p);k=Math.sqrt(C/M*2)}var z=k*k,L=r(0),E=function(t){return s(L)/s(L+k*t)},P=function(t){return A*((s(L)*function(t){return a(t)/s(t)}(L+k*t)-a(L))/z)/M},I=(r(1)-L)/k;if(Math.abs(M)<1e-6||!isFinite(I)){if(Math.abs(A-T)<1e-6)return this.easeTo(t,e);var D=Tt.maxDuration&&(t.duration=0),this.zooming=!0,this.rotating=h!==y,this.pitching=m!==f,this._prepareEase(e,!1),this._ease(function(t){var r=t*I,n=1/E(r);c.zoom=p+c.scaleZoom(n),u.rotating&&(c.bearing=i(h,y,t)),u.pitching&&(c.pitch=i(f,m,t));var a=c.unproject(b.add(w.mult(P(r))).mult(n));c.setLocationAtPoint(c.renderWorldCopies?a.wrap():a,v),u._fireMoveEvents(e)},function(){return u._afterEase(e)},t),this},e.prototype.isEasing=function(){return!!this._isEasing},e.prototype.isMoving=function(){return this.moving},e.prototype.stop=function(){return this._onFrame&&this._finishAnimation(),this},e.prototype._ease=function(t,e,r){var n=this;!1===r.animate||0===r.duration?(t(1),e()):(this._easeStart=a.now(),this._isEasing=!0,this._easeOptions=r,this._startAnimation(function(e){var r=Math.min((a.now()-n._easeStart)/n._easeOptions.duration,1);t(n._easeOptions.easing(r)),1===r&&n.stop()},function(){n._isEasing=!1,e()}))},e.prototype._updateCamera=function(){this._onFrame&&this._onFrame(this.transform)},e.prototype._startAnimation=function(t,e){return void 0===e&&(e=function(){}),this.stop(),this._onFrame=t,this._finishFn=e,this._update(),this},e.prototype._finishAnimation=function(){delete this._onFrame;var t=this._finishFn;delete this._finishFn,t.call(this)},e.prototype._normalizeBearing=function(t,e){t=n.wrap(t,-180,180);var r=Math.abs(t-e);return Math.abs(t-360-e)180?-360:r<-180?360:0}},e}(t("../util/evented"));e.exports=u},{"../geo/lng_lat":62,"../geo/lng_lat_bounds":63,"../style-spec/util/interpolate":158,"../util/browser":252,"../util/evented":260,"../util/util":275,"@mapbox/point-geometry":4}],232:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/config"),o=function(t){this.options=t,i.bindAll(["_updateEditLink","_updateData","_updateCompact"],this)};o.prototype.getDefaultPosition=function(){return"bottom-right"},o.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0},o.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:a.ACCESS_TOKEN}];if(t){var r=e.reduce(function(t,r,n){return r.value&&(t+=r.key+"="+r.value+(n=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null}},o.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact")},e.exports=o},{"../../util/config":256,"../../util/dom":259,"../../util/util":275}],233:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=function(){this._fullscreen=!1,i.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in a.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in a.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in a.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in a.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl"};o.prototype.onAdd=function(t){return this._map=t,this._mapContainer=this._map.getContainer(),this._container=n.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",i.warnOnce("This device does not support fullscreen mode.")),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map=null,a.document.removeEventListener(this._fullscreenchange,this._changeIcon)},o.prototype._checkFullscreenSupport=function(){return!!(a.document.fullscreenEnabled||a.document.mozFullScreenEnabled||a.document.msFullscreenEnabled||a.document.webkitFullscreenEnabled)},o.prototype._setupUI=function(){var t=this._fullscreenButton=n.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);t.setAttribute("aria-label","Toggle fullscreen"),t.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),a.document.addEventListener(this._fullscreenchange,this._changeIcon)},o.prototype._isFullscreen=function(){return this._fullscreen},o.prototype._changeIcon=function(){(a.document.fullscreenElement||a.document.mozFullScreenElement||a.document.webkitFullscreenElement||a.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"))},o.prototype._onClickFullscreen=function(){this._isFullscreen()?a.document.exitFullscreen?a.document.exitFullscreen():a.document.mozCancelFullScreen?a.document.mozCancelFullScreen():a.document.msExitFullscreen?a.document.msExitFullscreen():a.document.webkitCancelFullScreen&&a.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen()},e.exports=o},{"../../util/dom":259,"../../util/util":275,"../../util/window":254}],234:[function(t,e,r){var n,i=t("../../util/evented"),a=t("../../util/dom"),o=t("../../util/window"),s=t("../../util/util"),l=t("../../geo/lng_lat"),u=t("../marker"),c={positionOptions:{enableHighAccuracy:!1,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0},p=function(t){function e(e){t.call(this),this.options=s.extend({},c,e),s.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker","_onClickGeolocate"],this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onAdd=function(t){return this._map=t,this._container=a.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),function(t){void 0!==n?t(n):void 0!==o.navigator.permissions?o.navigator.permissions.query({name:"geolocation"}).then(function(e){n="denied"!==e.state,t(n)}):(n=!!o.navigator.geolocation,t(n))}(this._setupUI),this._container},e.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(o.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),a.remove(this._container),this._map=void 0},e.prototype._onSuccess=function(t){if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire("geolocate",t),this._finish()},e.prototype._updateCamera=function(t){var e=new l(t.coords.longitude,t.coords.latitude),r=t.coords.accuracy;this._map.fitBounds(e.toBounds(r),this.options.fitBoundsOptions,{geolocateSource:!0})},e.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove()},e.prototype._onError=function(t){if(this.options.trackUserLocation)if(1===t.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire("error",t),this._finish()},e.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},e.prototype._setupUI=function(t){var e=this;!1!==t&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=a.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=a.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new u(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this._onClickGeolocate.bind(this)),this.options.trackUserLocation&&this._map.on("movestart",function(t){t.geolocateSource||"ACTIVE_LOCK"!==e._watchState||(e._watchState="BACKGROUND",e._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),e._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),e.fire("trackuserlocationend"))}))},e.prototype._onClickGeolocate=function(){if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire("trackuserlocationstart");break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire("trackuserlocationend");break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire("trackuserlocationstart")}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=o.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions))}else o.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4)},e.prototype._clearWatch=function(){o.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)},e}(i);e.exports=p},{"../../geo/lng_lat":62,"../../util/dom":259,"../../util/evented":260,"../../util/util":275,"../../util/window":254,"../marker":248}],235:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=function(){i.bindAll(["_updateLogo"],this)};a.prototype.onAdd=function(t){this._map=t,this._container=n.create("div","mapboxgl-ctrl");var e=n.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},a.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateLogo)},a.prototype.getDefaultPosition=function(){return"bottom-left"},a.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")},a.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return!0;return!1}},e.exports=a},{"../../util/dom":259,"../../util/util":275}],236:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../handler/drag_rotate"),o={showCompass:!0,showZoom:!0},s=function(t){var e=this;this.options=i.extend({},o,t),this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return e._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return e._map.zoomOut()})),this.options.showCompass&&(i.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return e._map.resetNorth()}),this._compassArrow=n.create("span","mapboxgl-ctrl-compass-arrow",this._compass))};s.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t},s.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new a(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},s.prototype.onRemove=function(){n.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map},s.prototype._createButton=function(t,e,r){var i=n.create("button",t,this._container);return i.type="button",i.setAttribute("aria-label",e),i.addEventListener("click",r),i},e.exports=s},{"../../util/dom":259,"../../util/util":275,"../handler/drag_rotate":242}],237:[function(t,e,r){function n(t,e,r){var n=r&&r.maxWidth||100,a=t._container.clientHeight/2,o=function(t,e){var r=Math.PI/180,n=t.lat*r,i=e.lat*r,a=Math.sin(n)*Math.sin(i)+Math.cos(n)*Math.cos(i)*Math.cos((e.lng-t.lng)*r);return 6371e3*Math.acos(Math.min(a,1))}(t.unproject([0,a]),t.unproject([n,a]));if(r&&"imperial"===r.unit){var s=3.2808*o;s>5280?i(e,n,s/5280,"mi"):i(e,n,s,"ft")}else if(r&&"nautical"===r.unit){i(e,n,o/1852,"nm")}else i(e,n,o,"m")}function i(t,e,r,n){var i=function(t){var e=Math.pow(10,(""+Math.floor(t)).length-1),r=t/e;return e*(r=r>=10?10:r>=5?5:r>=3?3:r>=2?2:1)}(r),a=i/r;"m"===n&&i>=1e3&&(i/=1e3,n="km"),t.style.width=e*a+"px",t.innerHTML=i+n}var a=t("../../util/dom"),o=t("../../util/util"),s=function(t){this.options=t,o.bindAll(["_onMove"],this)};s.prototype.getDefaultPosition=function(){return"bottom-left"},s.prototype._onMove=function(){n(this._map,this._container,this.options)},s.prototype.onAdd=function(t){return this._map=t,this._container=a.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},s.prototype.onRemove=function(){a.remove(this._container),this._map.off("move",this._onMove),this._map=void 0},e.exports=s},{"../../util/dom":259,"../../util/util":275}],238:[function(t,e,r){},{}],239:[function(t,e,r){var n=t("../../util/dom"),i=t("../../geo/lng_lat_bounds"),a=t("../../util/util"),o=t("../../util/window"),s=function(t){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),a.bindAll(["_onMouseDown","_onMouseMove","_onMouseUp","_onKeyDown"],this)};s.prototype.isEnabled=function(){return!!this._enabled},s.prototype.isActive=function(){return!!this._active},s.prototype.enable=function(){this.isEnabled()||(this._map.dragPan&&this._map.dragPan.disable(),this._el.addEventListener("mousedown",this._onMouseDown,!1),this._map.dragPan&&this._map.dragPan.enable(),this._enabled=!0)},s.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onMouseDown),this._enabled=!1)},s.prototype._onMouseDown=function(t){t.shiftKey&&0===t.button&&(o.document.addEventListener("mousemove",this._onMouseMove,!1),o.document.addEventListener("keydown",this._onKeyDown,!1),o.document.addEventListener("mouseup",this._onMouseUp,!1),n.disableDrag(),this._startPos=n.mousePos(this._el,t),this._active=!0)},s.prototype._onMouseMove=function(t){var e=this._startPos,r=n.mousePos(this._el,t);this._box||(this._box=n.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var i=Math.min(e.x,r.x),a=Math.max(e.x,r.x),o=Math.min(e.y,r.y),s=Math.max(e.y,r.y);n.setTransform(this._box,"translate("+i+"px,"+o+"px)"),this._box.style.width=a-i+"px",this._box.style.height=s-o+"px"},s.prototype._onMouseUp=function(t){if(0===t.button){var e=this._startPos,r=n.mousePos(this._el,t),a=(new i).extend(this._map.unproject(e)).extend(this._map.unproject(r));this._finish(),e.x===r.x&&e.y===r.y?this._fireEvent("boxzoomcancel",t):this._map.fitBounds(a,{linear:!0}).fire("boxzoomend",{originalEvent:t,boxZoomBounds:a})}},s.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t))},s.prototype._finish=function(){this._active=!1,o.document.removeEventListener("mousemove",this._onMouseMove,!1),o.document.removeEventListener("keydown",this._onKeyDown,!1),o.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag()},s.prototype._fireEvent=function(t,e){return this._map.fire(t,{originalEvent:e})},e.exports=s},{"../../geo/lng_lat_bounds":63,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],240:[function(t,e,r){var n=t("../../util/util"),i=function(t){this._map=t,n.bindAll(["_onDblClick","_onZoomEnd"],this)};i.prototype.isEnabled=function(){return!!this._enabled},i.prototype.isActive=function(){return!!this._active},i.prototype.enable=function(){this.isEnabled()||(this._map.on("dblclick",this._onDblClick),this._enabled=!0)},i.prototype.disable=function(){this.isEnabled()&&(this._map.off("dblclick",this._onDblClick),this._enabled=!1)},i.prototype._onDblClick=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t)},i.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd)},e.exports=i},{"../../util/util":275}],241:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.3,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onDown","_onMove","_onUp","_onTouchEnd","_onMouseUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._el.addEventListener("mousedown",this._onDown),this._el.addEventListener("touchstart",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._el.removeEventListener("mousedown",this._onDown),this._el.removeEventListener("touchstart",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){this._ignoreEvent(t)||this.isActive()||(t.touches?(a.document.addEventListener("touchmove",this._onMove),a.document.addEventListener("touchend",this._onTouchEnd)):(a.document.addEventListener("mousemove",this._onMove),a.document.addEventListener("mouseup",this._onMouseUp)),a.addEventListener("blur",this._onMouseUp),this._active=!1,this._previousPos=n.mousePos(this._el,t),this._inertia=[[o.now(),this._previousPos]])},l.prototype._onMove=function(t){if(!this._ignoreEvent(t)){this._lastMoveEvent=t,t.preventDefault();var e=n.mousePos(this._el,t);if(this._drainInertiaBuffer(),this._inertia.push([o.now(),e]),!this._previousPos)return void(this._previousPos=e);this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("dragstart",t),this._fireEvent("movestart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()}},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;e&&(t.setLocationAtPoint(t.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",e),this._fireEvent("move",e),this._previousPos=this._pos,delete this._lastMoveEvent)},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,delete this._pos,this._fireEvent("dragend",t),this._drainInertiaBuffer();var r=function(){e._map.moving=!1,e._fireEvent("moveend",t)},n=this._inertia;if(n.length<2)return void r();var i=n[n.length-1],a=n[0],o=i[1].sub(a[1]),l=(i[0]-a[0])/1e3;if(0===l||i[1].equals(a[1]))return void r();var u=o.mult(.3/l),c=u.mag();c>1400&&(c=1400,u._unit()._mult(c));var p=c/750,h=u.mult(-p/2);this._map.panBy(h,{duration:1e3*p,easing:s,noMoveStart:!0},{originalEvent:t})}},l.prototype._onUp=function(t){this._onDragFinished(t)},l.prototype._onMouseUp=function(t){this._ignoreEvent(t)||(this._onUp(t),a.document.removeEventListener("mousemove",this._onMove),a.document.removeEventListener("mouseup",this._onMouseUp),a.removeEventListener("blur",this._onMouseUp))},l.prototype._onTouchEnd=function(t){this._ignoreEvent(t)||(this._onUp(t),a.document.removeEventListener("touchmove",this._onMove),a.document.removeEventListener("touchend",this._onTouchEnd))},l.prototype._fireEvent=function(t,e){return this._map.fire(t,e?{originalEvent:e}:{})},l.prototype._ignoreEvent=function(t){var e=this._map;return!(!e.boxZoom||!e.boxZoom.isActive())||!(!e.dragRotate||!e.dragRotate.isActive())||(t.touches?t.touches.length>1:!!t.ctrlKey||"mousemove"!==t.type&&t.button&&0!==t.button)},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=o.now();t.length>0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],242:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.25,1),l=function(t,e){this._map=t,this._el=e.element||t.getCanvasContainer(),this._button=e.button||"right",this._bearingSnap=e.bearingSnap||0,this._pitchWithRotate=!1!==e.pitchWithRotate,i.bindAll(["_onDown","_onMove","_onUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){if(!(this._map.boxZoom&&this._map.boxZoom.isActive()||this._map.dragPan&&this._map.dragPan.isActive()||this.isActive())){if("right"===this._button){var e=t.ctrlKey?0:2,r=t.button;if(void 0!==a.InstallTrigger&&2===t.button&&t.ctrlKey&&a.navigator.platform.toUpperCase().indexOf("MAC")>=0&&(r=0),r!==e)return}else if(t.ctrlKey||0!==t.button)return;n.disableDrag(),a.document.addEventListener("mousemove",this._onMove,{capture:!0}),a.document.addEventListener("mouseup",this._onUp),a.addEventListener("blur",this._onUp),this._active=!1,this._inertia=[[o.now(),this._map.getBearing()]],this._previousPos=n.mousePos(this._el,t),this._center=this._map.transform.centerPoint,t.preventDefault()}},l.prototype._onMove=function(t){this._lastMoveEvent=t;var e=n.mousePos(this._el,t);this._previousPos?(this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()):this._previousPos=e},l.prototype._onUp=function(t){a.document.removeEventListener("mousemove",this._onMove,{capture:!0}),a.document.removeEventListener("mouseup",this._onUp),a.removeEventListener("blur",this._onUp),n.enableDrag(),this._onDragFinished(t)},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;if(e){var r=this._previousPos,n=this._pos,i=.8*(r.x-n.x),a=-.5*(r.y-n.y),s=t.bearing-i,l=t.pitch-a,u=this._inertia,c=u[u.length-1];this._drainInertiaBuffer(),u.push([o.now(),this._map._normalizeBearing(s,c[1])]),t.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",e),t.pitch=l),this._fireEvent("rotate",e),this._fireEvent("move",e),delete this._lastMoveEvent,this._previousPos=this._pos}},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,this._fireEvent("rotateend",t),this._drainInertiaBuffer();var r=this._map,n=r.getBearing(),i=this._inertia,a=function(){Math.abs(n)180&&(d=180);var y=d/180;c+=h*d*(y/2),Math.abs(r._normalizeBearing(c,0))0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],243:[function(t,e,r){function n(t){return t*(2-t)}var i=t("../../util/util"),a=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onKeyDown"],this)};a.prototype.isEnabled=function(){return!!this._enabled},a.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0)},a.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1)},a.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,r=0,i=0,a=0,o=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?r=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?r=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?i=1:(t.preventDefault(),o=-1);break;case 40:t.shiftKey?i=-1:(o=1,t.preventDefault());break;default:return}var s=this._map,l=s.getZoom(),u={duration:300,delayEndEvents:500,easing:n,zoom:e?Math.round(l)+e*(t.shiftKey?2:1):l,bearing:s.getBearing()+15*r,pitch:s.getPitch()+10*i,offset:[100*-a,100*-o],center:s.getCenter()};s.easeTo(u,{originalEvent:t})}},e.exports=a},{"../../util/util":275}],244:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/browser"),o=t("../../util/window"),s=t("../../style-spec/util/interpolate").number,l=t("../../geo/lng_lat"),u=o.navigator.userAgent.toLowerCase(),c=-1!==u.indexOf("firefox"),p=-1!==u.indexOf("safari")&&-1===u.indexOf("chrom"),h=function(t){this._map=t,this._el=t.getCanvasContainer(),this._delta=0,i.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this)};h.prototype.isEnabled=function(){return!!this._enabled},h.prototype.isActive=function(){return!!this._active},h.prototype.enable=function(t){this.isEnabled()||(this._el.addEventListener("wheel",this._onWheel,!1),this._el.addEventListener("mousewheel",this._onWheel,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},h.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("wheel",this._onWheel),this._el.removeEventListener("mousewheel",this._onWheel),this._enabled=!1)},h.prototype._onWheel=function(t){var e=0;"wheel"===t.type?(e=t.deltaY,c&&t.deltaMode===o.WheelEvent.DOM_DELTA_PIXEL&&(e/=a.devicePixelRatio),t.deltaMode===o.WheelEvent.DOM_DELTA_LINE&&(e*=40)):"mousewheel"===t.type&&(e=-t.wheelDeltaY,p&&(e/=3));var r=a.now(),n=r-(this._lastWheelEventTime||0);this._lastWheelEventTime=r,0!==e&&e%4.000244140625==0?this._type="wheel":0!==e&&Math.abs(e)<4?this._type="trackpad":n>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(n*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&(this._lastWheelEvent=t,this._delta-=e,this.isActive()||this._start(t)),t.preventDefault()},h.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t)},h.prototype._start=function(t){if(this._delta){this._active=!0,this._map.moving=!0,this._map.zooming=!0,this._map.fire("movestart",{originalEvent:t}),this._map.fire("zoomstart",{originalEvent:t}),clearTimeout(this._finishTimeout);var e=n.mousePos(this._el,t);this._around=l.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(e)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._map._startAnimation(this._onScrollFrame,this._onScrollFinished)}},h.prototype._onScrollFrame=function(t){if(this.isActive()){if(0!==this._delta){var e="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,r=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==r&&(r=1/r);var n="number"==typeof this._targetZoom?t.zoomScale(this._targetZoom):t.scale;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(n*r))),"wheel"===this._type&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}if("wheel"===this._type){var i=Math.min((a.now()-this._lastWheelEventTime)/200,1),o=this._easing(i);t.zoom=s(this._startZoom,this._targetZoom,o),1===i&&this._map.stop()}else t.zoom=this._targetZoom,this._map.stop();t.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire("move",{originalEvent:this._lastWheelEvent}),this._map.fire("zoom",{originalEvent:this._lastWheelEvent})}},h.prototype._onScrollFinished=function(){var t=this;this.isActive()&&(this._active=!1,this._finishTimeout=setTimeout(function(){t._map.moving=!1,t._map.zooming=!1,t._map.fire("zoomend"),t._map.fire("moveend"),delete t._targetZoom},200))},h.prototype._smoothOutEasing=function(t){var e=i.ease;if(this._prevEase){var r=this._prevEase,n=(a.now()-r.start)/r.duration,o=r.easing(n+.01)-r.easing(n),s=.27/Math.sqrt(o*o+1e-4)*.01,l=Math.sqrt(.0729-s*s);e=i.bezier(s,l,.25,1)}return this._prevEase={start:a.now(),duration:t,easing:e},e},e.exports=h},{"../../geo/lng_lat":62,"../../style-spec/util/interpolate":158,"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],245:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.15,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onStart","_onMove","_onEnd"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._el.addEventListener("touchstart",this._onStart,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._el.removeEventListener("touchstart",this._onStart),this._enabled=!1)},l.prototype.disableRotation=function(){this._rotationDisabled=!0},l.prototype.enableRotation=function(){this._rotationDisabled=!1},l.prototype._onStart=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]);this._startVec=e.sub(r),this._startScale=this._map.transform.scale,this._startBearing=this._map.transform.bearing,this._gestureIntent=void 0,this._inertia=[],a.document.addEventListener("touchmove",this._onMove,!1),a.document.addEventListener("touchend",this._onEnd,!1)}},l.prototype._onMove=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]),i=e.add(r).div(2),a=e.sub(r),s=a.mag()/this._startVec.mag(),l=this._rotationDisabled?0:180*a.angleWith(this._startVec)/Math.PI,u=this._map;if(this._gestureIntent){var c={duration:0,around:u.unproject(i)};"rotate"===this._gestureIntent&&(c.bearing=this._startBearing+l),"zoom"!==this._gestureIntent&&"rotate"!==this._gestureIntent||(c.zoom=u.transform.scaleZoom(this._startScale*s)),u.stop(),this._drainInertiaBuffer(),this._inertia.push([o.now(),s,i]),u.easeTo(c,{originalEvent:t})}else{var p=Math.abs(1-s)>.15;Math.abs(l)>10?this._gestureIntent="rotate":p&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._startVec=a,this._startScale=u.transform.scale,this._startBearing=u.transform.bearing)}t.preventDefault()}},l.prototype._onEnd=function(t){a.document.removeEventListener("touchmove",this._onMove),a.document.removeEventListener("touchend",this._onEnd),this._drainInertiaBuffer();var e=this._inertia,r=this._map;if(e.length<2)r.snapToNorth({},{originalEvent:t});else{var n=e[e.length-1],i=e[0],o=r.transform.scaleZoom(this._startScale*n[1]),l=r.transform.scaleZoom(this._startScale*i[1]),u=o-l,c=(n[0]-i[0])/1e3,p=n[2];if(0!==c&&o!==l){var h=.15*u/c;Math.abs(h)>2.5&&(h=h>0?2.5:-2.5);var f=1e3*Math.abs(h/(12*.15)),d=o+h*f/2e3;d<0&&(d=0),r.easeTo({zoom:d,duration:f,easing:s,around:this._aroundCenter?r.getCenter():r.unproject(p)},{originalEvent:t})}else r.snapToNorth({},{originalEvent:t})}},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=o.now();t.length>2&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],246:[function(t,e,r){var n=t("../util/util"),i=t("../util/window"),a=t("../util/throttle"),o=function(){n.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=a(this._updateHashUnthrottled.bind(this),300)};o.prototype.addTo=function(t){return this._map=t,i.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},o.prototype.remove=function(){return i.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),delete this._map,this},o.prototype.getHashString=function(t){var e=this._map.getCenter(),r=Math.round(100*this._map.getZoom())/100,n=Math.ceil((r*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.pow(10,n),a=Math.round(e.lng*i)/i,o=Math.round(e.lat*i)/i,s=this._map.getBearing(),l=this._map.getPitch(),u="";return u+=t?"#/"+a+"/"+o+"/"+r:"#"+r+"/"+o+"/"+a,(s||l)&&(u+="/"+Math.round(10*s)/10),l&&(u+="/"+Math.round(l)),u},o.prototype._onHashChange=function(){var t=i.location.hash.replace("#","").split("/");return t.length>=3&&(this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:+(t[3]||0),pitch:+(t[4]||0)}),!0)},o.prototype._updateHashUnthrottled=function(){var t=this.getHashString();i.history.replaceState("","",t)},e.exports=o},{"../util/throttle":272,"../util/util":275,"../util/window":254}],247:[function(t,e,r){function n(t){t.parentNode&&t.parentNode.removeChild(t)}var i=t("../util/util"),a=t("../util/browser"),o=t("../util/window"),s=t("../util/window"),l=s.HTMLImageElement,u=s.HTMLElement,c=t("../util/dom"),p=t("../util/ajax"),h=t("../style/style"),f=t("../style/evaluation_parameters"),d=t("../render/painter"),y=t("../geo/transform"),m=t("./hash"),g=t("./bind_handlers"),v=t("./camera"),_=t("../geo/lng_lat"),x=t("../geo/lng_lat_bounds"),b=t("@mapbox/point-geometry"),w=t("./control/attribution_control"),k=t("./control/logo_control"),A=t("@mapbox/mapbox-gl-supported"),T=t("../util/image").RGBAImage;t("./events");var M={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},S=function(t){function e(e){if(null!=(e=i.extend({},M,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var r=new y(e.minZoom,e.maxZoom,e.renderWorldCopies);t.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming;var n=e.transformRequest;if(this._transformRequest=n?function(t,e){return n(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var a=o.document.getElementById(e.container);if(!a)throw new Error("Container '"+e.container+"' not found.");this._container=a}else{if(!(e.container instanceof u))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}e.maxBounds&&this.setMaxBounds(e.maxBounds),i.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==o&&(o.addEventListener("online",this._onWindowOnline,!1),o.addEventListener("resize",this._onWindowResize,!1)),g(this,e),this._hash=e.hash&&(new m).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new w),this.addControl(new k,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet)}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={showTileBoundaries:{},showCollisionBoxes:{},showOverdrawInspector:{},repaint:{},vertices:{}};return e.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var r=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(r,n.firstChild):n.appendChild(r),this},e.prototype.removeControl=function(t){return t.onRemove(this),this},e.prototype.resize=function(){var t=this._containerDimensions(),e=t[0],r=t[1];return this._resizeCanvas(e,r),this.transform.resize(e,r),this.painter.resize(e,r),this.fire("movestart").fire("move").fire("resize").fire("moveend")},e.prototype.getBounds=function(){var t=new x(this.transform.pointLocation(new b(0,this.transform.height)),this.transform.pointLocation(new b(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(t.extend(this.transform.pointLocation(new b(this.transform.size.x,0))),t.extend(this.transform.pointLocation(new b(0,this.transform.size.y)))),t},e.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new x([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},e.prototype.setMaxBounds=function(t){if(t){var e=x.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update()}else null!==t&&void 0!==t||(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},e.prototype.setMinZoom=function(t){if((t=null===t||void 0===t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},e.prototype.getMaxZoom=function(){return this.transform.maxZoom},e.prototype.project=function(t){return this.transform.locationPoint(_.convert(t))},e.prototype.unproject=function(t){return this.transform.pointLocation(b.convert(t))},e.prototype.on=function(e,r,n){var a=this;if(void 0===n)return t.prototype.on.call(this,e,r);var o=function(){if("mouseenter"===e||"mouseover"===e){var t=!1;return{layer:r,listener:n,delegates:{mousemove:function(o){var s=a.getLayer(r)?a.queryRenderedFeatures(o.point,{layers:[r]}):[];s.length?t||(t=!0,n.call(a,i.extend({features:s},o,{type:e}))):t=!1},mouseout:function(){t=!1}}}}if("mouseleave"===e||"mouseout"===e){var o=!1;return{layer:r,listener:n,delegates:{mousemove:function(t){(a.getLayer(r)?a.queryRenderedFeatures(t.point,{layers:[r]}):[]).length?o=!0:o&&(o=!1,n.call(a,i.extend({},t,{type:e})))},mouseout:function(t){o&&(o=!1,n.call(a,i.extend({},t,{type:e})))}}}}var s;return{layer:r,listener:n,delegates:(s={},s[e]=function(t){var e=a.getLayer(r)?a.queryRenderedFeatures(t.point,{layers:[r]}):[];e.length&&n.call(a,i.extend({features:e},t))},s)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(o),o.delegates)a.on(s,o.delegates[s]);return this},e.prototype.off=function(e,r,n){if(void 0===n)return t.prototype.off.call(this,e,r);if(this._delegatedListeners&&this._delegatedListeners[e])for(var i=this._delegatedListeners[e],a=0;athis._map.transform.height-i?["bottom"]:[],t.xthis._map.transform.width-n/2&&e.push("right"),e=0===e.length?"bottom":e.join("-")}var o=t.add(r[e]).round(),l={top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},c=this._container.classList;for(var p in l)c.remove("mapboxgl-popup-anchor-"+p);c.add("mapboxgl-popup-anchor-"+e),a.setTransform(this._container,l[e]+" translate("+o.x+"px,"+o.y+"px)")}},e.prototype._onClickClose=function(){this.remove()},e}(i);e.exports=p},{"../geo/lng_lat":62,"../util/dom":259,"../util/evented":260,"../util/smart_wrap":270,"../util/util":275,"../util/window":254,"@mapbox/point-geometry":4}],250:[function(t,e,r){var n=t("./util"),i=t("./web_worker_transfer"),a=i.serialize,o=i.deserialize,s=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,n.bindAll(["receive"],this),this.target.addEventListener("message",this.receive,!1)};s.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var o=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:a(e,o)},o)},s.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var s=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"",id:String(i),error:t?String(t):null,data:a(e,n)},n)};if(""===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(new Error(n.error)):e&&e(null,o(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,o(n.data),s);else if(void 0!==n.id&&this.parent.getWorkerSource){var l=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,l[0])[l[1]](o(n.data),s)}else this.parent[n.type](o(n.data))}},s.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1)},e.exports=s},{"./util":275,"./web_worker_transfer":278}],251:[function(t,e,r){function n(t){var e=new a.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}function i(t){var e=a.document.createElement("a");return e.href=t,e.protocol===a.document.location.protocol&&e.host===a.document.location.host}var a=t("./window"),o={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};r.ResourceType=o,"function"==typeof Object.freeze&&Object.freeze(o);var s=function(t){function e(e,r){t.call(this,e),this.status=r}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);r.getJSON=function(t,e){var r=n(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var t;try{t=JSON.parse(r.response)}catch(t){return e(t)}e(null,t)}else e(new s(r.statusText,r.status))},r.send(),r},r.getArrayBuffer=function(t,e){var r=n(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){var t=r.response;if(0===t.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:t,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new s(r.statusText,r.status))},r.send(),r};r.getImage=function(t,e){return r.getArrayBuffer(t,function(t,r){if(t)e(t);else if(r){var n=new a.Image,i=a.URL||a.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src)};var o=new a.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(o):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII="}})},r.getVideo=function(t,e){var r=a.document.createElement("video");r.onloadstart=function(){e(null,r)};for(var n=0;n1)for(var p=0;p0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},o.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this},e.exports=o},{"./util":275}],261:[function(t,e,r){function n(t,e){return e.max-t.max}function i(t,e,r,n){this.p=new o(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;it.y!=p.y>t.y&&t.x<(p.x-c.x)*(t.y-c.y)/(p.y-c.y)+c.x&&(r=!r),n=Math.min(n,s(t,c,p))}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2}var a=t("tinyqueue"),o=t("@mapbox/point-geometry"),s=t("./intersection_tests").distToSegmentSquared;e.exports=function(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var s=1/0,l=1/0,u=-1/0,c=-1/0,p=t[0],h=0;hu)&&(u=f.x),(!h||f.y>c)&&(c=f.y)}var d=u-s,y=c-l,m=Math.min(d,y),g=m/2,v=new a(null,n);if(0===m)return new o(s,l);for(var _=s;_b.d||!b.d)&&(b=k,r&&console.log("found best %d after %d probes",Math.round(1e4*k.d)/1e4,w)),k.max-b.d<=e||(g=k.h/2,v.push(new i(k.p.x-g,k.p.y-g,g,t)),v.push(new i(k.p.x+g,k.p.y-g,g,t)),v.push(new i(k.p.x-g,k.p.y+g,g,t)),v.push(new i(k.p.x+g,k.p.y+g,g,t)),w+=4)}return r&&(console.log("num probes: "+w),console.log("best distance: "+b.d)),b.p}},{"./intersection_tests":264,"@mapbox/point-geometry":4,tinyqueue:33}],262:[function(t,e,r){var n,i=t("./worker_pool");e.exports=function(){return n||(n=new i),n}},{"./worker_pool":279}],263:[function(t,e,r){function n(t,e,r,n){var i=e.width,a=e.height;if(n){if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function i(t,e,r){var i=e.width,o=e.height;if(i!==t.width||o!==t.height){var s=n({},{width:i,height:o},r);a(t,s,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,i),height:Math.min(t.height,o)},r),t.width=i,t.height=o,t.data=s.data}}function a(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,l=0;l1){if(i(t,e))return!0;for(var n=0;n1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function l(t,e){for(var r,n,i,a=!1,o=0;oe.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function u(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r)}return r}var c=t("./util").isCounterClockwise;e.exports={multiPolygonIntersectsBufferedMultiPoint:function(t,e,r){for(var n=0;n=3)for(var l=0;l=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}}},{}],266:[function(t,e,r){var n=function(t,e){this.max=t,this.onRemove=e,this.reset()};n.prototype.reset=function(){var t=this;for(var e in t.data)t.onRemove(t.data[e]);return this.data={},this.order=[],this},n.prototype.add=function(t,e){if(this.has(t))this.order.splice(this.order.indexOf(t),1),this.data[t]=e,this.order.push(t);else if(this.data[t]=e,this.order.push(t),this.order.length>this.max){var r=this.getAndRemove(this.order[0]);r&&this.onRemove(r)}return this},n.prototype.has=function(t){return t in this.data},n.prototype.keys=function(){return this.order},n.prototype.getAndRemove=function(t){if(!this.has(t))return null;var e=this.data[t];return delete this.data[t],this.order.splice(this.order.indexOf(t),1),e},n.prototype.get=function(t){return this.has(t)?this.data[t]:null},n.prototype.remove=function(t){if(!this.has(t))return this;var e=this.data[t];return delete this.data[t],this.onRemove(e),this.order.splice(this.order.indexOf(t),1),this},n.prototype.setMaxSize=function(t){var e=this;for(this.max=t;this.order.length>this.max;){var r=e.getAndRemove(e.order[0]);r&&e.onRemove(r)}return this},e.exports=n},{}],267:[function(t,e,r){function n(t,e){var r=a(s.API_URL);if(t.protocol=r.protocol,t.authority=r.authority,"/"!==r.path&&(t.path=""+r.path+t.path),!s.REQUIRE_ACCESS_TOKEN)return o(t);if(!(e=e||s.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+u);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+u);return t.params.push("access_token="+e),o(t)}function i(t){return 0===t.indexOf("mapbox:")}function a(t){var e=t.match(p);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function o(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var s=t("./config"),l=t("./browser"),u="See https://www.mapbox.com/api-documentation/#access-tokens";r.isMapboxURL=i,r.normalizeStyleURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/styles/v1"+r.path,n(r,e)},r.normalizeGlyphsURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/fonts/v1"+r.path,n(r,e)},r.normalizeSourceURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),n(r,e)},r.normalizeSpriteURL=function(t,e,r,s){var l=a(t);return i(t)?(l.path="/styles/v1"+l.path+"/sprite"+e+r,n(l,s)):(l.path+=""+e+r,o(l))};var c=/(\.(png|jpg)\d*)(?=$)/;r.normalizeTileURL=function(t,e,r){if(!e||!i(e))return t;var n=a(t),u=l.devicePixelRatio>=2||512===r?"@2x":"",p=l.supportsWebp?".webp":"$1";return n.path=n.path.replace(c,""+u+p),function(t){for(var e=0;e=65097&&t<=65103)||n["CJK Compatibility Ideographs"](t)||n["CJK Compatibility"](t)||n["CJK Radicals Supplement"](t)||n["CJK Strokes"](t)||!(!n["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||n["CJK Unified Ideographs Extension A"](t)||n["CJK Unified Ideographs"](t)||n["Enclosed CJK Letters and Months"](t)||n["Hangul Compatibility Jamo"](t)||n["Hangul Jamo Extended-A"](t)||n["Hangul Jamo Extended-B"](t)||n["Hangul Jamo"](t)||n["Hangul Syllables"](t)||n.Hiragana(t)||n["Ideographic Description Characters"](t)||n.Kanbun(t)||n["Kangxi Radicals"](t)||n["Katakana Phonetic Extensions"](t)||n.Katakana(t)&&12540!==t||!(!n["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!n["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||n["Unified Canadian Aboriginal Syllabics"](t)||n["Unified Canadian Aboriginal Syllabics Extended"](t)||n["Vertical Forms"](t)||n["Yijing Hexagram Symbols"](t)||n["Yi Syllables"](t)||n["Yi Radicals"](t)))},r.charHasNeutralVerticalOrientation=function(t){return!!(n["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||n["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||n["Letterlike Symbols"](t)||n["Number Forms"](t)||n["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||n["Control Pictures"](t)&&9251!==t||n["Optical Character Recognition"](t)||n["Enclosed Alphanumerics"](t)||n["Geometric Shapes"](t)||n["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||n["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||n["CJK Symbols and Punctuation"](t)||n.Katakana(t)||n["Private Use Area"](t)||n["CJK Compatibility Forms"](t)||n["Small Form Variants"](t)||n["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)},r.charHasRotatedVerticalOrientation=function(t){return!(r.charHasUprightVerticalOrientation(t)||r.charHasNeutralVerticalOrientation(t))}},{"./is_char_in_unicode_block":265}],270:[function(t,e,r){var n=t("../geo/lng_lat");e.exports=function(t,e,r){if(t=new n(t.lng,t.lat),e){var i=new n(t.lng-360,t.lat),a=new n(t.lng+360,t.lat),o=r.locationPoint(t).distSqr(e);r.locationPoint(i).distSqr(e)180;){var s=r.locationPoint(t);if(s.x>=0&&s.y>=0&&s.x<=r.width&&s.y<=r.height)break;t.lng>r.center.lng?t.lng-=360:t.lng+=360}return t}},{"../geo/lng_lat":62}],271:[function(t,e,r){function n(t,e){return Math.ceil(t/e)*e}var i={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},a=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0)};a.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},a.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},a.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())},a.prototype.clear=function(){this.length=0},a.prototype.resize=function(t){this.reserve(t),this.length=t},a.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}},a.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")},e.exports.StructArray=a,e.exports.Struct=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8},e.exports.viewTypes=i,e.exports.createLayout=function(t,e){void 0===e&&(e=1);var r=0,a=0;return{members:t.map(function(t){var o=function(t){return i[t].BYTES_PER_ELEMENT}(t.type),s=r=n(r,Math.max(e,o)),l=t.components||1;return a=Math.max(a,o),r+=o*l,{name:t.name,type:t.type,components:l,offset:s}}),size:n(r,Math.max(a,e)),alignment:e}}},{}],272:[function(t,e,r){e.exports=function(t,e){var r=!1,n=0,i=function(){n=0,r&&(t(),n=setTimeout(i,e),r=!1)};return function(){return r=!0,n||i(),n}}},{}],273:[function(t,e,r){function n(t,e){if(t.row>e.row){var r=t;t=e,e=r}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function i(t,e,r,n,i){var a=Math.max(r,Math.floor(e.y0)),o=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx0,p=e.dx<0,h=a;hc.dy&&(l=u,u=c,c=l),u.dy>p.dy&&(l=u,u=p,p=l),c.dy>p.dy&&(l=c,c=p,p=l),u.dy&&i(p,u,a,o,s),c.dy&&i(p,c,a,o,s)}t("../geo/coordinate");var o=t("../source/tile_id").OverscaledTileID;e.exports=function(t,e,r,n){function i(e,i,a){var u,c,p;if(a>=0&&a<=s)for(u=e;u=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)},r.bezier=function(t,e,r,i){var a=new n(t,e,r,i);return function(t){return a.solve(t)}},r.ease=r.bezier(.25,.1,.25,1),r.clamp=function(t,e,r){return Math.min(r,Math.max(e,t))},r.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},r.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach(function(t,o){e(t,function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i)})})},r.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},r.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},r.extend=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];for(var i=0,a=r;i=0)return!0;return!1};var o={};r.warnOnce=function(t){o[t]||("undefined"!=typeof console&&console.warn(t),o[t]=!0)},r.isCounterClockwise=function(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)},r.calculateSignedArea=function(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r0||Math.abs(e.y-n.y)>0)&&Math.abs(r.calculateSignedArea(t))>.01},r.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},r.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r}return e}},{"../geo/coordinate":61,"../style-spec/util/deep_equal":155,"@mapbox/point-geometry":4,"@mapbox/unitbezier":7}],276:[function(t,e,r){var n=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id)},i={geometry:{}};i.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},i.geometry.set=function(t){this._geometry=t},n.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(n.prototype,i),e.exports=n},{}],277:[function(t,e,r){var n=t("./script_detection");e.exports=function(t){for(var r="",i=0;i":"\ufe40","?":"\ufe16","@":"\uff20","[":"\ufe47","\\":"\uff3c","]":"\ufe48","^":"\uff3e",_:"\ufe33","`":"\uff40","{":"\ufe37","|":"\u2015","}":"\ufe38","~":"\uff5e","\xa2":"\uffe0","\xa3":"\uffe1","\xa5":"\uffe5","\xa6":"\uffe4","\xac":"\uffe2","\xaf":"\uffe3","\u2013":"\ufe32","\u2014":"\ufe31","\u2018":"\ufe43","\u2019":"\ufe44","\u201c":"\ufe41","\u201d":"\ufe42","\u2026":"\ufe19","\u2027":"\u30fb","\u20a9":"\uffe6","\u3001":"\ufe11","\u3002":"\ufe12","\u3008":"\ufe3f","\u3009":"\ufe40","\u300a":"\ufe3d","\u300b":"\ufe3e","\u300c":"\ufe41","\u300d":"\ufe42","\u300e":"\ufe43","\u300f":"\ufe44","\u3010":"\ufe3b","\u3011":"\ufe3c","\u3014":"\ufe39","\u3015":"\ufe3a","\u3016":"\ufe17","\u3017":"\ufe18","\uff01":"\ufe15","\uff08":"\ufe35","\uff09":"\ufe36","\uff0c":"\ufe10","\uff0d":"\ufe32","\uff0e":"\u30fb","\uff1a":"\ufe13","\uff1b":"\ufe14","\uff1c":"\ufe3f","\uff1e":"\ufe40","\uff1f":"\ufe16","\uff3b":"\ufe47","\uff3d":"\ufe48","\uff3f":"\ufe33","\uff5b":"\ufe37","\uff5c":"\u2015","\uff5d":"\ufe38","\uff5f":"\ufe35","\uff60":"\ufe36","\uff61":"\ufe12","\uff62":"\ufe41","\uff63":"\ufe42"}},{"./script_detection":269}],278:[function(t,e,r){function n(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),y[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]}}var i=t("grid-index"),a=t("../style-spec/util/color"),o=t("../style-spec/expression"),s=o.StylePropertyFunction,l=o.StyleExpression,u=o.StyleExpressionWithErrorHandling,c=o.ZoomDependentExpression,p=o.ZoomConstantExpression,h=t("../style-spec/expression/compound_expression").CompoundExpression,f=t("../style-spec/expression/definitions"),d=t("./window").ImageData,y={};for(var m in n("Object",Object),i.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},i.deserialize=function(t){return new i(t)},n("Grid",i),n("Color",a),n("StylePropertyFunction",s),n("StyleExpression",l,{omit:["_evaluator"]}),n("StyleExpressionWithErrorHandling",u,{omit:["_evaluator"]}),n("ZoomDependentExpression",c),n("ZoomConstantExpression",p),n("CompoundExpression",h,{omit:["_evaluate"]}),f)f[m]._classRegistryKey||n("Expression_"+m,f[m]);e.exports={register:n,serialize:function t(e,r){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp)return e;if(e instanceof ArrayBuffer)return r&&r.push(e),e;if(ArrayBuffer.isView(e)){var n=e;return r&&r.push(n.buffer),n}if(e instanceof d)return r&&r.push(e.data.buffer),e;if(Array.isArray(e)){for(var i=[],a=0,o=e;a=0)){var h=e[p];c[p]=y[u].shallow.indexOf(p)>=0?h:t(h,r)}return{name:u,properties:c}}throw new Error("can't serialize object of type "+typeof e)},deserialize:function t(e){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof d)return e;if(Array.isArray(e))return e.map(function(e){return t(e)});if("object"==typeof e){var r=e,n=r.name,i=r.properties;if(!n)throw new Error("can't deserialize object of anonymous class");var a=y[n].klass;if(!a)throw new Error("can't deserialize unregistered class "+n);if(a.deserialize)return a.deserialize(i._serialized);for(var o=Object.create(a.prototype),s=0,l=Object.keys(i);s=0?i[u]:t(i[u])}return o}throw new Error("can't deserialize object of type "+typeof e)}}},{"../style-spec/expression":139,"../style-spec/expression/compound_expression":123,"../style-spec/expression/definitions":131,"../style-spec/util/color":153,"./window":254,"grid-index":24}],279:[function(t,e,r){var n=t("./web_worker"),i=function(){this.active={}};i.prototype.acquire=function(e){if(!this.workers){var r=t("../").workerCount;for(this.workers=[];this.workers.length0}function qh(t){var e={},r={};switch(t.type){case"circle":re.extendFlat(r,{"circle-radius":t.circle.radius,"circle-color":t.color,"circle-opacity":t.opacity});break;case"line":re.extendFlat(r,{"line-width":t.line.width,"line-color":t.color,"line-opacity":t.opacity});break;case"fill":re.extendFlat(r,{"fill-color":t.color,"fill-outline-color":t.fill.outlinecolor,"fill-opacity":t.opacity});break;case"symbol":var n=t.symbol,i=Fh(n.textposition,n.iconsize);re.extendFlat(e,{"icon-image":n.icon+"-15","icon-size":n.iconsize/10,"text-field":n.text,"text-size":n.textfont.size,"text-anchor":i.anchor,"text-offset":i.offset}),re.extendFlat(r,{"icon-color":t.color,"text-color":n.textfont.color,"text-opacity":t.opacity})}return{layout:e,paint:r}}jh.update=function(t){this.visible?this.needsNewSource(t)?(this.updateLayer(t),this.updateSource(t)):this.needsNewLayer(t)?this.updateLayer(t):this.updateStyle(t):(this.updateSource(t),this.updateLayer(t)),this.visible=Vh(t)},jh.needsNewSource=function(t){return this.sourceType!==t.sourcetype||this.source!==t.source||this.layerType!==t.type},jh.needsNewLayer=function(t){return this.layerType!==t.type||this.below!==t.below},jh.updateSource=function(t){var e=this.map;if(e.getSource(this.idSource)&&e.removeSource(this.idSource),this.sourceType=t.sourcetype,this.source=t.source,Vh(t)){var r=function(t){var e,r=t.sourcetype,n=t.source,i={type:r};"geojson"===r?e="data":"vector"===r&&(e="string"==typeof n?"url":"tiles");return i[e]=n,i}(t);e.addSource(this.idSource,r)}},jh.updateLayer=function(t){var e=this.map,r=qh(t);e.getLayer(this.idLayer)&&e.removeLayer(this.idLayer),this.layerType=t.type,Vh(t)&&e.addLayer({id:this.idLayer,source:this.idSource,"source-layer":t.sourcelayer||"",type:t.type,layout:r.layout,paint:r.paint},t.below)},jh.updateStyle=function(t){if(Vh(t)){var e=qh(t);this.mapbox.setOptions(this.idLayer,"setLayoutProperty",e.layout),this.mapbox.setOptions(this.idLayer,"setPaintProperty",e.paint)}},jh.dispose=function(){var t=this.map;t.removeLayer(this.idLayer),t.removeSource(this.idSource)};var Uh=function(t,e,r){var n=new Nh(t,e);return n.update(r),n};function Zh(t){this.id=t.id,this.gd=t.gd,this.container=t.container,this.isStatic=t.staticPlot;var e=t.fullLayout;this.uid=e._uid+"-"+this.id,this.opts=e[this.id],this.div=null,this.xaxis=null,this.yaxis=null,this.createFramework(e),this.map=null,this.accessToken=null,this.styleObj=null,this.traceHash={},this.layerList=[]}var Hh=Zh.prototype,Gh=function(t){return new Zh(t)};function Wh(t){var e=Oh.style.values,r=Oh.style.dflt,n={};return re.isPlainObject(t)?(n.id=t.id,n.style=t):"string"==typeof t?(n.id=t,n.style=-1!==e.indexOf(t)?Xh(t):t):(n.id=r,n.style=Xh(r)),n.transition={duration:0,delay:0},n}function Xh(t){return zh.styleUrlPrefix+t+"-"+zh.styleUrlSuffix}function Yh(t){return[t.lon,t.lat]}Hh.plot=function(t,e,r){var n,i=this,a=i.opts=e[this.id];i.map&&a.accesstoken!==i.accessToken&&(i.map.remove(),i.map=null,i.styleObj=null,i.traceHash=[],i.layerList={}),n=i.map?new Promise(function(r,n){i.updateMap(t,e,r,n)}):new Promise(function(r,n){i.createMap(t,e,r,n)}),r.push(n)},Hh.createMap=function(t,e,r,n){var i=this,a=i.gd,o=i.opts,s=i.styleObj=Wh(o.style);i.accessToken=o.accesstoken;var l=i.map=new Ch.Map({container:i.div,style:s.style,center:Yh(o.center),zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,interactive:!i.isStatic,preserveDrawingBuffer:i.isStatic,doubleClickZoom:!1,boxZoom:!1}),u=zh.controlContainerClassName,c=i.div.getElementsByClassName(u)[0];function p(){Ga.loneUnhover(e._toppaper)}i.div.removeChild(c),l._canvas.style.left="0px",l._canvas.style.top="0px",i.rejectOnError(n),l.once("load",function(){i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)}),i.isStatic||(l.on("moveend",function(t){if(i.map){var e=i.getView();if(o._input.center=o.center=e.center,o._input.zoom=o.zoom=e.zoom,o._input.bearing=o.bearing=e.bearing,o._input.pitch=o.pitch=e.pitch,t.originalEvent){var r={};r[i.id]=re.extendFlat({},e),a.emit("plotly_relayout",r)}}}),l.on("mousemove",function(t){var e=i.div.getBoundingClientRect();t.clientX=t.point.x+e.left,t.clientY=t.point.y+e.top,t.target.getBoundingClientRect=function(){return e},i.xaxis.p2c=function(){return t.lngLat.lng},i.yaxis.p2c=function(){return t.lngLat.lat},Ga.hover(a,t,i.id)}),l.on("click",function(t){Ga.click(a,t.originalEvent)}),l.on("dragstart",p),l.on("zoomstart",p),l.on("dblclick",function(){var t=i.viewInitial;l.setCenter(Yh(t.center)),l.setZoom(t.zoom),l.setBearing(t.bearing),l.setPitch(t.pitch);var e=i.getView();o._input.center=o.center=e.center,o._input.zoom=o.zoom=e.zoom,o._input.bearing=o.bearing=e.bearing,o._input.pitch=o.pitch=e.pitch,a.emit("plotly_doubleclick",null)}),i.clearSelect=function(){a._fullLayout._zoomlayer.selectAll(".select-outline").remove()})},Hh.updateMap=function(t,e,r,n){var i=this,a=i.map;i.rejectOnError(n);var o=Wh(i.opts.style);i.styleObj.id!==o.id?(i.styleObj=o,a.setStyle(o.style),a.once("styledata",function(){i.traceHash={},i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)})):(i.updateData(t),i.updateLayout(e),i.resolveOnRender(r))},Hh.updateData=function(t){var e,r,n,i,a=this.traceHash;for(n=0;n0&&(r.push(n),n=[])}return n.length>0&&r.push(n),r},yf.makeLine=function(t){return 1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t}},yf.makePolygon=function(t){if(1===t.length)return{type:"Polygon",coordinates:t};for(var e=new Array(t.length),r=0;r=0?Math.floor((e+180)/360):Math.ceil((e-180)/360)),u=e-l;if(Ga.getClosest(n,function(t){var e=t.lonlat;if(e[0]===df)return 1/0;var n=re.wrap180(e[0]),i=e[1],l=s.project([n,i]),c=l.x-a.c2p([u,i]),p=l.y-o.c2p([n,r]),h=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(c*c+p*p)-h,1-3/h)},t),!1!==t.index){var c=n[t.index],p=c.lonlat,h=[re.wrap180(p[0])+l,p[1]],f=a.c2p(h),d=o.c2p(h),y=c.mrc||1;return t.x0=f-y,t.x1=f+y,t.y0=d-y,t.y1=d+y,t.color=ph(i,c),t.extraText=function(t,e,r){var n=(e.hi||t.hoverinfo).split("+"),i=-1!==n.indexOf("all"),a=-1!==n.indexOf("lon"),o=-1!==n.indexOf("lat"),s=e.lonlat,l=[];function u(t){return t+"\xb0"}return i||a&&o?l.push("("+u(s[0])+", "+u(s[1])+")"):a?l.push(r.lon+u(s[0])):o&&l.push(r.lat+u(s[1])),(i||-1!==n.indexOf("text"))&&uh(e,t,l),l.join("
")}(i,c,n[0].t.labels),[t]}},Tf.eventData=function(t,e){return t.lon=e.lon,t.lat=e.lat,t},Tf.selectPoints=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[],s=n[0].trace;if(!cn.hasMarkers(s))return[];if(!1===e)for(r=0;re?1:t>=e?0:NaN}function f(t){return null===t?NaN:+t}function d(t){return!isNaN(t)}function y(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[o],r)<0?n=o+1:i=o}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[o],r)>0?i=o:n=o+1}return n}}}e.ascending=h,e.descending=function(t,e){return et?1:e>=t?0:NaN},e.min=function(t,e){var r,n,i=-1,o=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},e.max=function(t,e){var r,n,i=-1,o=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},e.extent=function(t,e){var r,n,i,o=-1,a=t.length;if(1===arguments.length){for(;++o=n){r=i=n;break}for(;++on&&(r=n),i=n){r=i=n;break}for(;++on&&(r=n),i1)return a/(l-1)},e.deviation=function(){var t=e.variance.apply(this,arguments);return t?Math.sqrt(t):t};var m=y(h);function g(t){return t.length}e.bisectLeft=m.left,e.bisect=e.bisectRight=m.right,e.bisector=function(t){return y(1===t.length?function(e,r){return h(t(e),r)}:t)},e.shuffle=function(t,e,r){(o=arguments.length)<3&&(r=t.length,o<2&&(e=0));for(var n,i,o=r-e;o;)i=Math.random()*o--|0,n=t[o+e],t[o+e]=t[i+e],t[i+e]=n;return t},e.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},e.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--a]=n[e];return r};var v=Math.abs;function _(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function x(){this._=Object.create(null)}e.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],o=function(t){var e=1;for(;t*e%1;)e*=10;return e}(v(r)),a=-1;if(t*=o,e*=o,(r*=o)<0)for(;(n=t+r*++a)>e;)i.push(n/o);else for(;(n=t+r*++a)=i.length)return r?r.call(n,o):t?o.sort(t):o;for(var l,u,c,p,h=-1,f=o.length,d=i[s++],y=new x;++h=i.length)return e;var n=[],a=o[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),a?n.sort(function(t,e){return a(t.key,e.key)}):n}(a(e.map,t,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return o[i.length-1]=t,n},n.sortValues=function(e){return t=e,n},n.rollup=function(t){return r=t,n},n},e.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},e.event=null,e.requote=function(t){return t.replace(V,"\\$&")};var V=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function U(t){return q(t,W),t}var H=function(t,e){return e.querySelector(t)},Z=function(t,e){return e.querySelectorAll(t)},G=function(t,e){var r=t.matches||t[I(t,"matchesSelector")];return(G=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(H=function(t,e){return Sizzle(t,e)[0]||null},Z=Sizzle,G=Sizzle.matchesSelector),e.selection=function(){return e.select(i.documentElement)};var W=e.selection.prototype=[];function X(t){return"function"==typeof t?t:function(){return H(t,this)}}function Y(t){return"function"==typeof t?t:function(){return Z(t,this)}}W.select=function(t){var e,r,n,i,o=[];t=X(t);for(var a=-1,s=this.length;++a=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},W.attr=function(t,r){if(arguments.length<2){if("string"==typeof t){var n=this.node();return(t=e.ns.qualify(t)).local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(r in t)this.each($(r,t[r]));return this}return this.each($(t,r))},W.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(o&&o!==r.nextSibling&&o.parentNode.insertBefore(r,o),o=r);return this},W.sort=function(t){t=function(t){arguments.length||(t=h);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(t=t.slice(0,a));var l=dt.get(t);function u(){var e=this[o];e&&(this.removeEventListener(t,e,e.$),delete this[o])}return l&&(t=l,s=mt),a?r?function(){var e=s(r,n(arguments));u.call(this),this.addEventListener(t,this[o]=e,e.$=i),e._=r}:u:r?O:function(){var r,n=new RegExp("^__on([^.]+)"+e.requote(t)+"$");for(var i in this)if(r=i.match(n)){var o=this[i];this.removeEventListener(r[1],o,o.$),delete this[i]}}}e.selection.enter=pt,e.selection.enter.prototype=ht,ht.append=W.append,ht.empty=W.empty,ht.node=W.node,ht.call=W.call,ht.size=W.size,ht.select=function(t){for(var e,r,n,i,o,a=[],s=-1,l=this.length;++s=n&&(n=e+1);!(a=s[n])&&++n0?1:t<0?-1:0}function Pt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function It(t){return t>1?0:t<-1?Tt:Math.acos(t)}function Dt(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function Ot(t){return((t=Math.exp(t))+1/t)/2}function Rt(t){return(t=Math.sin(t/2))*t}var Bt=Math.SQRT2;e.interpolateZoom=function(t,e){var r,n,i=t[0],o=t[1],a=t[2],s=e[0],l=e[1],u=e[2],c=s-i,p=l-o,h=c*c+p*p;if(h0&&(t=t.transition().duration(y)),t.call(w.event)}function S(){u&&u.domain(l.range().map(function(t){return(t-h.x)/h.k}).map(l.invert)),p&&p.domain(c.range().map(function(t){return(t-h.y)/h.k}).map(c.invert))}function C(t){m++||t({type:"zoomstart"})}function z(t){S(),t({type:"zoom",scale:h.k,translate:[h.x,h.y]})}function L(t){--m||(t({type:"zoomend"}),r=null)}function E(){var t=this,r=b.of(t,arguments),n=0,i=e.select(a(t)).on(v,function(){n=1,T(e.mouse(t),o),z(r)}).on(_,function(){i.on(v,null).on(_,null),s(n),L(r)}),o=k(e.mouse(t)),s=_t(t);ss.call(t),C(r)}function P(){var t,r=this,n=b.of(r,arguments),i={},o=0,a=".zoom-"+e.event.changedTouches[0].identifier,l="touchmove"+a,u="touchend"+a,c=[],p=e.select(r),f=_t(r);function d(){var n=e.touches(r);return t=h.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=k(t))}),n}function y(){var t=e.event.target;e.select(t).on(l,m).on(u,v),c.push(t);for(var n=e.event.changedTouches,a=0,p=n.length;a1){g=f[0];var _=f[1],x=g[0]-_[0],b=g[1]-_[1];o=x*x+b*b}}function m(){var a,l,u,c,p=e.touches(r);ss.call(r);for(var h=0,f=p.length;h360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new oe(o(t+120),o(t),o(t-120))}function Zt(t,r,n){return this instanceof Zt?(this.h=+t,this.c=+r,void(this.l=+n)):arguments.length<2?t instanceof Zt?new Zt(t.h,t.c,t.l):ee(t instanceof Xt?t.l:(t=he((t=e.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new Zt(t,r,n)}Ut.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,this.l/t)},Ut.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,t*this.l)},Ut.rgb=function(){return Ht(this.h,this.s,this.l)},e.hcl=Zt;var Gt=Zt.prototype=new Vt;function Wt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Xt(r,Math.cos(t*=zt)*e,Math.sin(t)*e)}function Xt(t,e,r){return this instanceof Xt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Xt?new Xt(t.l,t.a,t.b):t instanceof Zt?Wt(t.h,t.c,t.l):he((t=oe(t)).r,t.g,t.b):new Xt(t,e,r)}Gt.brighter=function(t){return new Zt(this.h,this.c,Math.min(100,this.l+Yt*(arguments.length?t:1)))},Gt.darker=function(t){return new Zt(this.h,this.c,Math.max(0,this.l-Yt*(arguments.length?t:1)))},Gt.rgb=function(){return Wt(this.h,this.c,this.l).rgb()},e.lab=Xt;var Yt=18,Jt=.95047,Kt=1,$t=1.08883,Qt=Xt.prototype=new Vt;function te(t,e,r){var n=(t+16)/116,i=n+e/500,o=n-r/200;return new oe(ie(3.2404542*(i=re(i)*Jt)-1.5371385*(n=re(n)*Kt)-.4985314*(o=re(o)*$t)),ie(-.969266*i+1.8760108*n+.041556*o),ie(.0556434*i-.2040259*n+1.0572252*o))}function ee(t,e,r){return t>0?new Zt(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Zt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function oe(t,e,r){return this instanceof oe?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof oe?new oe(t.r,t.g,t.b):ce(""+t,oe,Ht):new oe(t,e,r)}function ae(t){return new oe(t>>16,t>>8&255,255&t)}function se(t){return ae(t)+""}Qt.brighter=function(t){return new Xt(Math.min(100,this.l+Yt*(arguments.length?t:1)),this.a,this.b)},Qt.darker=function(t){return new Xt(Math.max(0,this.l-Yt*(arguments.length?t:1)),this.a,this.b)},Qt.rgb=function(){return te(this.l,this.a,this.b)},e.rgb=oe;var le=oe.prototype=new Vt;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,i,o,a=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(de(i[0]),de(i[1]),de(i[2]))}return(o=ye.get(t))?e(o.r,o.g,o.b):(null==t||"#"!==t.charAt(0)||isNaN(o=parseInt(t.slice(1),16))||(4===t.length?(a=(3840&o)>>4,a|=a>>4,s=240&o,s|=s>>4,l=15&o,l|=l<<4):7===t.length&&(a=(16711680&o)>>16,s=(65280&o)>>8,l=255&o)),e(a,s,l))}function pe(t,e,r){var n,i,o=Math.min(t/=255,e/=255,r/=255),a=Math.max(t,e,r),s=a-o,l=(a+o)/2;return s?(i=l<.5?s/(a+o):s/(2-a-o),n=t==a?(e-r)/s+(e0&&l<1?0:n),new qt(n,i,l)}function he(t,e,r){var n=ne((.4124564*(t=fe(t))+.3575761*(e=fe(e))+.1804375*(r=fe(r)))/Jt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Xt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function fe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function de(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(a,u)}catch(t){return void s.error.call(a,t)}s.load.call(a,t)}else s.error.call(a,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(t)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=p:u.onreadystatechange=function(){u.readyState>3&&p()},u.onprogress=function(t){var r=e.event;e.event=t;try{s.progress.call(a,u)}finally{e.event=r}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",a):r},a.responseType=function(t){return arguments.length?(c=t,a):c},a.response=function(t){return i=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(n(arguments)))}}),a.send=function(e,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),u.open(e,t,!0),null==r||"accept"in l||(l.accept=r+",*/*"),u.setRequestHeader)for(var o in l)u.setRequestHeader(o,l[o]);return null!=r&&u.overrideMimeType&&u.overrideMimeType(r),null!=c&&(u.responseType=c),null!=i&&a.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(a,u),u.send(null==n?null:n),a},a.abort=function(){return u.abort(),a},e.rebind(a,s,"on"),null==o?a:a.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(o))}ye.forEach(function(t,e){ye.set(t,ae(e))}),e.functor=me,e.xhr=ge(E),e.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ve(t,e,null==r?o:a(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?o:a(t)):r},i}function o(t){return i.parse(t.responseText)}function a(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,o={},a={},s=[],l=t.length,u=0,c=0;function p(){if(u>=l)return a;if(i)return i=!1,o;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),be=0):(be=1,ke(Te))}function Me(){for(var t=Date.now(),e=_e;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Se(){for(var t,e=_e,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});e.formatPrefix=function(t,r){var n=0;return(t=+t)&&(t<0&&(t*=-1),r&&(t=e.round(t,Ce(t,r))),n=1+Math.floor(1e-12+Math.log(t)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),ze[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Ee=e.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,r){return(t=e.round(t,Ce(t,r))).toFixed(Math.max(0,Math.min(20,Ce(t*(1+1e-15),r))))}});function Pe(t){return t+""}var Ie=e.time={},De=Date;function Oe(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Oe.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(){Re.setUTCDate.apply(this._,arguments)},setDay:function(){Re.setUTCDay.apply(this._,arguments)},setFullYear:function(){Re.setUTCFullYear.apply(this._,arguments)},setHours:function(){Re.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Re.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Re.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Re.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Re.setUTCSeconds.apply(this._,arguments)},setTime:function(){Re.setTime.apply(this._,arguments)}};var Re=Date.prototype;function Be(t,e,r){function n(e){var r=t(e),n=o(r,1);return e-r1)for(;a68?1900:2e3),r+i[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=v(e)/60|0,i=v(e)%60;return r+qe(n,"0",2)+qe(i,"0",2)}function or(t,e,r){Ve.lastIndex=0;var n=Ve.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function ar(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),o.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[a=(a+1)%i.length];return o.reverse().join(n)}:E;return function(t){var n=Le.exec(t),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",u=n[4]||"",c=n[5],p=+n[6],h=n[7],f=n[8],d=n[9],y=1,m="",g="",v=!1,_=!0;switch(f&&(f=+f.substring(1)),(c||"0"===i&&"="===s)&&(c=i="0",s="="),d){case"n":h=!0,d="g";break;case"%":y=100,g="%",d="f";break;case"p":y=100,g="%",d="r";break;case"b":case"o":case"x":case"X":"#"===u&&(m="0"+d.toLowerCase());case"c":_=!1;case"d":v=!0,f=0;break;case"s":y=-1,d="r"}"$"===u&&(m=o[0],g=o[1]),"r"!=d||f||(d="g"),null!=f&&("g"==d?f=Math.max(1,Math.min(21,f)):"e"!=d&&"f"!=d||(f=Math.max(0,Math.min(20,f)))),d=Ee.get(d)||Pe;var x=c&&h;return function(t){var n=g;if(v&&t%1)return"";var o=t<0||0===t&&1/t<0?(t=-t,"-"):"-"===l?"":l;if(y<0){var u=e.formatPrefix(t,f);t=u.scale(t),n=u.symbol+g}else t*=y;var b,w,k=(t=d(t,f)).lastIndexOf(".");if(k<0){var A=_?t.lastIndexOf("e"):-1;A<0?(b=t,w=""):(b=t.substring(0,A),w=t.substring(A))}else b=t.substring(0,k),w=r+t.substring(k+1);!c&&h&&(b=a(b,1/0));var T=m.length+b.length+w.length+(x?0:o.length),M=T"===s?M+o+t:"^"===s?M.substring(0,T>>=1)+o+t+M.substring(T):o+(x?t:M+t))+n}}}(t),timeFormat:function(t){var r=t.dateTime,n=t.date,i=t.time,o=t.periods,a=t.days,s=t.shortDays,l=t.months,u=t.shortMonths;function c(t){var e=t.length;function r(r){for(var n,i,o,a=[],s=-1,l=0;++s=u)return-1;if(37===(i=e.charCodeAt(s++))){if(a=e.charAt(s++),!(o=w[a in Ne?e.charAt(s++):a])||(n=o(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(De=Oe);return r._=t,e(r)}finally{De=Date}}return r.parse=function(t){try{De=Oe;var r=e.parse(t);return r&&r._}finally{De=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=ar;var h=e.map(),f=Ue(a),d=He(a),y=Ue(s),m=He(s),g=Ue(l),v=He(l),_=Ue(u),x=He(u);o.forEach(function(t,e){h.set(t.toLowerCase(),e)});var b={a:function(t){return s[t.getDay()]},A:function(t){return a[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:c(r),d:function(t,e){return qe(t.getDate(),e,2)},e:function(t,e){return qe(t.getDate(),e,2)},H:function(t,e){return qe(t.getHours(),e,2)},I:function(t,e){return qe(t.getHours()%12||12,e,2)},j:function(t,e){return qe(1+Ie.dayOfYear(t),e,3)},L:function(t,e){return qe(t.getMilliseconds(),e,3)},m:function(t,e){return qe(t.getMonth()+1,e,2)},M:function(t,e){return qe(t.getMinutes(),e,2)},p:function(t){return o[+(t.getHours()>=12)]},S:function(t,e){return qe(t.getSeconds(),e,2)},U:function(t,e){return qe(Ie.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return qe(Ie.mondayOfYear(t),e,2)},x:c(n),X:c(i),y:function(t,e){return qe(t.getFullYear()%100,e,2)},Y:function(t,e){return qe(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){y.lastIndex=0;var n=y.exec(e.slice(r));return n?(t.w=m.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){f.lastIndex=0;var n=f.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){_.lastIndex=0;var n=_.exec(e.slice(r));return n?(t.m=x.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.m=v.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return p(t,b.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Qe,L:nr,m:Ke,M:er,p:function(t,e,r){var n=h.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Ge,w:Ze,W:We,x:function(t,e,r){return p(t,b.x.toString(),e,r)},X:function(t,e,r){return p(t,b.X.toString(),e,r)},y:Ye,Y:Xe,Z:Je,"%":or};return c}(t)}};var sr=e.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"]});function lr(){}e.format=sr.numberFormat,e.geo={},lr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new lr;function cr(t,e,r){var n=r.s=t+e,i=n-t,o=n-i;r.t=t-o+(e-i)}function pr(t,e){t&&fr.hasOwnProperty(t.type)&&fr[t.type](t,e)}e.geo.stream=function(t,e){t&&hr.hasOwnProperty(t.type)?hr[t.type](t,e):pr(t,e)};var hr={Feature:function(t,e){pr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=a*o,l=Math.cos(e),u=Math.sin(e),c=i*u,p=n*l+c*Math.cos(s),h=c*a*Math.sin(s);Cr.add(Math.atan2(h,p)),r=t,n=l,i=u}zr.point=function(a,s){zr.point=o,r=(t=a)*zt,n=Math.cos(s=(e=s)*zt/2+Tt/4),i=Math.sin(s)},zr.lineEnd=function(){o(t,e)}}function Er(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Pr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Ir(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Dr(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Or(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Rr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Br(t){return[Math.atan2(t[1],t[0]),Dt(t[2])]}function Fr(t,e){return v(t[0]-e[0])kt?i=90:u<-kt&&(r=-90),p[0]=t,p[1]=n}};function f(e,o){c.push(p=[t=e,n=e]),oi&&(i=o)}function d(e,a){var s=Er([e*zt,a*zt]);if(l){var u=Ir(l,s),c=Ir([u[1],-u[0],0],u);Rr(c),c=Br(c);var p=e-o,h=p>0?1:-1,d=c[0]*Lt*h,y=v(p)>180;if(y^(h*oi&&(i=m);else if(y^(h*o<(d=(d+360)%360-180)&&di&&(i=a);y?eb(t,n)&&(n=e):b(e,n)>b(t,n)&&(t=e):n>=t?(en&&(n=e)):e>o?b(t,e)>b(t,n)&&(n=e):b(e,n)>b(t,n)&&(t=e)}else f(e,a);l=s,o=e}function y(){h.point=d}function m(){p[0]=t,p[1]=n,h.point=f,l=null}function g(t,e){if(l){var r=t-o;u+=v(r)>180?r+(r>0?360:-360):r}else a=t,s=e;zr.point(t,e),d(t,e)}function _(){zr.lineStart()}function x(){g(a,s),zr.lineEnd(),v(u)>kt&&(t=-(n=180)),p[0]=t,p[1]=n,l=null}function b(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function k(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:tb(y[0],y[1])&&(y[1]=f[1]),b(f[0],y[1])>b(y[0],y[1])&&(y[0]=f[0])):s.push(y=f);for(var l,u,f,d=-1/0,y=(a=0,s[u=s.length-1]);a<=u;y=f,++a)f=s[a],(l=b(y[1],f[0]))>d&&(d=l,t=f[0],n=y[1])}return c=p=null,t===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[t,r],[n,i]]}}(),e.geo.centroid=function(t){gr=vr=_r=xr=br=wr=kr=Ar=Tr=Mr=Sr=0,e.geo.stream(t,Nr);var r=Tr,n=Mr,i=Sr,o=r*r+n*n+i*i;return o=0;--s)i.point((p=c[s])[0],p[1]);else n(f.x,f.p.x,-1,i);f=f.p}c=(f=f.o).z,d=!d}while(!f.v);i.lineEnd()}}}function Xr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,k=w*b,A=k>Tt,T=d*_;if(Cr.add(Math.atan2(T*w*Math.sin(k),y*x+T*Math.cos(k))),o+=A?b+w*Mt:b,A^h>=r^g>=r){var M=Ir(Er(p),Er(t));Rr(M);var S=Ir(i,M);Rr(S);var C=(A^b>=0?-1:1)*Dt(S[2]);(n>C||n===C&&(M[0]||M[1]))&&(a+=A^b>=0?1:-1)}if(!m++)break;h=g,d=_,y=x,p=t}}return(o<-kt||o0){for(_||(a.polygonStart(),_=!0),a.lineStart();++o1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return c}}function Kr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:O,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Qr(t,e){return((t=t.x)[0]<0?t[1]-Ct-kt:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-kt:Ct-e[1])}var tn=Jr(Gr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(o,a){var s=o>0?Tt:-Tt,l=v(o-r);v(l-Tt)0?Ct:-Ct),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(o,n),e=0):i!==s&&l>=Tt&&(v(r-i)kt?Math.atan((Math.sin(e)*(o=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*o*a)):(e+n)/2}(r,n,o,a),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=o,n=a),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Ct,n.point(-Tt,i),n.point(0,i),n.point(Tt,i),n.point(Tt,0),n.point(Tt,-i),n.point(0,-i),n.point(-Tt,-i),n.point(-Tt,0),n.point(-Tt,i);else if(v(t[0]-e[0])>kt){var o=t[0]0)){if(o/=h,h<0){if(o0){if(o>p)return;o>c&&(c=o)}if(o=r-l,h||!(o<0)){if(o/=h,h<0){if(o>p)return;o>c&&(c=o)}else if(h>0){if(o0)){if(o/=f,f<0){if(o0){if(o>p)return;o>c&&(c=o)}if(o=n-u,f||!(o<0)){if(o/=f,f<0){if(o>p)return;o>c&&(c=o)}else if(f>0){if(o0&&(i.a={x:l+c*h,y:u+c*f}),p<1&&(i.b={x:l+p*h,y:u+p*f}),i}}}}}}var rn=1e9;function nn(t,r,n,i){return function(l){var u,c,p,h,f,d,y,m,g,v,_,x=l,b=$r(),w=en(t,r,n,i),k={point:M,lineStart:function(){k.point=S,c&&c.push(p=[]);v=!0,g=!1,y=m=NaN},lineEnd:function(){u&&(S(h,f),d&&g&&b.rejoin(),u.push(b.buffer()));k.point=M,g&&l.lineEnd()},polygonStart:function(){l=b,u=[],c=[],_=!0},polygonEnd:function(){l=x,u=e.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],i=0;in&&Pt(u,o,t)>0&&++e:o[1]<=n&&Pt(u,o,t)<0&&--e,u=o;return 0!==e}([t,i]),n=_&&r,o=u.length;(n||o)&&(l.polygonStart(),n&&(l.lineStart(),A(null,null,1,l),l.lineEnd()),o&&Wr(u,a,r,A,l),l.polygonEnd()),u=c=p=null}};function A(e,a,l,u){var c=0,p=0;if(null==e||(c=o(e,l))!==(p=o(a,l))||s(e,a)<0^l>0)do{u.point(0===c||3===c?t:n,c>1?i:r)}while((c=(c+l+4)%4)!==p);else u.point(a[0],a[1])}function T(e,o){return t<=e&&e<=n&&r<=o&&o<=i}function M(t,e){T(t,e)&&l.point(t,e)}function S(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&p.push([t,e]),v)h=t,f=e,d=r,v=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&g)l.point(t,e);else{var n={a:{x:y,y:m},b:{x:t,y:e}};w(n)?(g||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),_=!1):r&&(l.lineStart(),l.point(t,e),_=!1)}y=t,m=e,g=r}return k};function o(e,i){return v(e[0]-t)0?0:3:v(e[0]-n)0?2:1:v(e[1]-r)0?1:0:i>0?3:2}function a(t,e){return s(t.x,e.x)}function s(t,e){var r=o(t,1),n=o(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function on(t){var e=0,r=Tt/3,n=Sn(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},i}function an(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),o=Math.sqrt(i)/n;function a(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),o-r*Math.cos(t)]}return a.invert=function(t,e){var r=o-e;return[Math.atan2(t,r)/n,Dt((i-(t*t+r*r)*n*n)/(2*n))]},a}e.geo.clipExtent=function(){var t,e,r,n,i,o,a={stream:function(t){return i&&(i.valid=!1),(i=o(t)).valid=!0,i},extent:function(s){return arguments.length?(o=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),a):[[t,e],[r,n]]}};return a.extent([[0,0],[960,500]])},(e.geo.conicEqualArea=function(){return on(an)}).raw=an,e.geo.albers=function(){return e.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},e.geo.albersUsa=function(){var t,r,n,i,o=e.geo.albers(),a=e.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=e.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(e,r){t=[e,r]}};function u(e){var o=e[0],a=e[1];return t=null,r(o,a),t||(n(o,a),t)||i(o,a),t}return u.invert=function(t){var e=o.scale(),r=o.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?a:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:o).invert(t)},u.stream=function(t){var e=o.stream(t),r=a.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(o.precision(t),a.precision(t),s.precision(t),u):o.precision()},u.scale=function(t){return arguments.length?(o.scale(t),a.scale(.35*t),s.scale(t),u.translate(o.translate())):o.scale()},u.translate=function(t){if(!arguments.length)return o.translate();var e=o.scale(),c=+t[0],p=+t[1];return r=o.translate(t).clipExtent([[c-.455*e,p-.238*e],[c+.455*e,p+.238*e]]).stream(l).point,n=a.translate([c-.307*e,p+.201*e]).clipExtent([[c-.425*e+kt,p+.12*e+kt],[c-.214*e-kt,p+.234*e-kt]]).stream(l).point,i=s.translate([c-.205*e,p+.212*e]).clipExtent([[c-.214*e+kt,p+.166*e+kt],[c-.115*e-kt,p+.234*e-kt]]).stream(l).point,u},u.scale(1070)};var sn,ln,un,cn,pn,hn,fn={point:O,lineStart:O,lineEnd:O,polygonStart:function(){ln=0,fn.lineStart=dn},polygonEnd:function(){fn.lineStart=fn.lineEnd=fn.point=O,sn+=v(ln/2)}};function dn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}fn.point=function(o,a){fn.point=i,t=r=o,e=n=a},fn.lineEnd=function(){i(t,e)}}var yn={point:function(t,e){tpn&&(pn=t);ehn&&(hn=e)},lineStart:O,lineEnd:O,polygonStart:O,polygonEnd:O};function mn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var gn,vn={point:_n,lineStart:xn,lineEnd:bn,polygonStart:function(){vn.lineStart=wn},polygonEnd:function(){vn.point=_n,vn.lineStart=xn,vn.lineEnd=bn}};function _n(t,e){_r+=t,xr+=e,++br}function xn(){var t,e;function r(r,n){var i=r-t,o=n-e,a=Math.sqrt(i*i+o*o);wr+=a*(t+r)/2,kr+=a*(e+n)/2,Ar+=a,_n(t=r,e=n)}vn.point=function(n,i){vn.point=r,_n(t=n,e=i)}}function bn(){vn.point=_n}function wn(){var t,e,r,n;function i(t,e){var i=t-r,o=e-n,a=Math.sqrt(i*i+o*o);wr+=a*(r+t)/2,kr+=a*(n+e)/2,Ar+=a,Tr+=(a=n*t-r*e)*(r+t),Mr+=a*(n+e),Sr+=3*a,_n(r=t,n=e)}vn.point=function(o,a){vn.point=i,_n(t=r=o,e=n=a)},vn.lineEnd=function(){i(t,e)}}function kn(t){var e=.5,r=Math.cos(30*zt),n=16;function i(e){return(n?function(e){var r,i,a,s,l,u,c,p,h,f,d,y,m={point:g,lineStart:v,lineEnd:x,polygonStart:function(){e.polygonStart(),m.lineStart=b},polygonEnd:function(){e.polygonEnd(),m.lineStart=v}};function g(r,n){r=t(r,n),e.point(r[0],r[1])}function v(){p=NaN,m.point=_,e.lineStart()}function _(r,i){var a=Er([r,i]),s=t(r,i);o(p,h,c,f,d,y,p=s[0],h=s[1],c=r,f=a[0],d=a[1],y=a[2],n,e),e.point(p,h)}function x(){m.point=g,e.lineEnd()}function b(){v(),m.point=w,m.lineEnd=k}function w(t,e){_(r=t,e),i=p,a=h,s=f,l=d,u=y,m.point=_}function k(){o(p,h,c,f,d,y,i,a,r,s,l,u,n,e),m.lineEnd=x,x()}return m}:function(e){return Tn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function o(n,i,a,s,l,u,c,p,h,f,d,y,m,g){var _=c-n,x=p-i,b=_*_+x*x;if(b>4*e&&m--){var w=s+f,k=l+d,A=u+y,T=Math.sqrt(w*w+k*k+A*A),M=Math.asin(A/=T),S=v(v(A)-1)e||v((_*E+x*P)/b-.5)>.3||s*f+l*d+u*y0&&16,i):Math.sqrt(e)},i}function An(t){this.stream=t}function Tn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Mn(t){return Sn(function(){return t})()}function Sn(t){var r,n,i,o,a,s,l=kn(function(t,e){return[(t=r(t,e))[0]*u+o,a-t[1]*u]}),u=150,c=480,p=250,h=0,f=0,d=0,y=0,m=0,g=tn,_=E,x=null,b=null;function w(t){return[(t=i(t[0]*zt,t[1]*zt))[0]*u+o,a-t[1]*u]}function k(t){return(t=i.invert((t[0]-o)/u,(a-t[1])/u))&&[t[0]*Lt,t[1]*Lt]}function A(){i=Zr(n=En(d,y,m),r);var t=r(h,f);return o=c-t[0]*u,a=p+t[1]*u,T()}function T(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Cn(g(n,l(_(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(g=null==t?(x=t,tn):function(t){var e=Math.cos(t),r=e>0,n=v(e)>kt;return Jr(i,function(t){var e,s,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(p,h){var f,d=[p,h],y=i(p,h),m=r?y?0:a(p,h):y?a(p+(p<0?Tt:-Tt),h):0;if(!e&&(u=l=y)&&t.lineStart(),y!==l&&(f=o(e,d),(Fr(e,f)||Fr(d,f))&&(d[0]+=kt,d[1]+=kt,y=i(d[0],d[1]))),y!==l)c=0,y?(t.lineStart(),f=o(d,e),t.point(f[0],f[1])):(f=o(e,d),t.point(f[0],f[1]),t.lineEnd()),e=f;else if(n&&e&&r^y){var g;m&s||!(g=o(d,e,!0))||(c=0,r?(t.lineStart(),t.point(g[0][0],g[0][1]),t.point(g[1][0],g[1][1]),t.lineEnd()):(t.point(g[1][0],g[1][1]),t.lineEnd(),t.lineStart(),t.point(g[0][0],g[0][1])))}!y||e&&Fr(e,d)||t.point(d[0],d[1]),e=d,l=y,s=m},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return c|(u&&l)<<1}}},On(t,6*zt),r?[0,-t]:[-Tt,t-Tt]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function o(t,r,n){var i=[1,0,0],o=Ir(Er(t),Er(r)),a=Pr(o,o),s=o[0],l=a-s*s;if(!l)return!n&&t;var u=e*a/l,c=-e*s/l,p=Ir(i,o),h=Or(i,u);Dr(h,Or(o,c));var f=p,d=Pr(h,f),y=Pr(f,f),m=d*d-y*(Pr(h,h)-1);if(!(m<0)){var g=Math.sqrt(m),_=Or(f,(-d-g)/y);if(Dr(_,h),_=Br(_),!n)return _;var x,b=t[0],w=r[0],k=t[1],A=r[1];w0^_[1]<(v(_[0]-b)Tt^(b<=_[0]&&_[0]<=w)){var S=Or(f,(-d+g)/y);return Dr(S,h),[_,Br(S)]}}}function a(e,n){var i=r?t:Tt-t,o=0;return e<-i?o|=1:e>i&&(o|=2),n<-i?o|=4:n>i&&(o|=8),o}}((x=+t)*zt),T()):x},w.clipExtent=function(t){return arguments.length?(b=t,_=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):E,T()):b},w.scale=function(t){return arguments.length?(u=+t,A()):u},w.translate=function(t){return arguments.length?(c=+t[0],p=+t[1],A()):[c,p]},w.center=function(t){return arguments.length?(h=t[0]%360*zt,f=t[1]%360*zt,A()):[h*Lt,f*Lt]},w.rotate=function(t){return arguments.length?(d=t[0]%360*zt,y=t[1]%360*zt,m=t.length>2?t[2]%360*zt:0,A()):[d*Lt,y*Lt,m*Lt]},e.rebind(w,l,"precision"),function(){return r=t.apply(this,arguments),w.invert=r.invert&&k,A()}}function Cn(t){return Tn(t,function(e,r){t.point(e*zt,r*zt)})}function zn(t,e){return[t,e]}function Ln(t,e){return[t>Tt?t-Mt:t<-Tt?t+Mt:t,e]}function En(t,e,r){return t?e||r?Zr(In(t),Dn(e,r)):In(t):e||r?Dn(e,r):Ln}function Pn(t){return function(e,r){return[(e+=t)>Tt?e-Mt:e<-Tt?e+Mt:e,r]}}function In(t){var e=Pn(t);return e.invert=Pn(-t),e}function Dn(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),o=Math.sin(e);function a(t,e){var a=Math.cos(e),s=Math.cos(t)*a,l=Math.sin(t)*a,u=Math.sin(e),c=u*r+s*n;return[Math.atan2(l*i-c*o,s*r-u*n),Dt(c*i+l*o)]}return a.invert=function(t,e){var a=Math.cos(e),s=Math.cos(t)*a,l=Math.sin(t)*a,u=Math.sin(e),c=u*i-l*o;return[Math.atan2(l*i+u*o,s*r+c*n),Dt(c*r-s*n)]},a}function On(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,o,a,s){var l=a*e;null!=i?(i=Rn(r,i),o=Rn(r,o),(a>0?io)&&(i+=a*Mt)):(i=t+a*Mt,o=t-.5*l);for(var u,c=i;a>0?c>o:c2?t[2]*zt:0),e.invert=function(e){return(e=t.invert(e[0]*zt,e[1]*zt))[0]*=Lt,e[1]*=Lt,e},e},Ln.invert=zn,e.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=En(-t[0]*zt,-t[1]*zt,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=On((t=+r)*zt,n*zt),i):t},i.precision=function(r){return arguments.length?(e=On(t*zt,(n=+r)*zt),i):n},i.angle(90)},e.geo.distance=function(t,e){var r,n=(e[0]-t[0])*zt,i=t[1]*zt,o=e[1]*zt,a=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(o),p=Math.cos(o);return Math.atan2(Math.sqrt((r=p*a)*r+(r=u*c-l*p*s)*r),l*c+u*p*s)},e.geo.graticule=function(){var t,r,n,i,o,a,s,l,u,c,p,h,f=10,d=f,y=90,m=360,g=2.5;function _(){return{type:"MultiLineString",coordinates:x()}}function x(){return e.range(Math.ceil(i/y)*y,n,y).map(p).concat(e.range(Math.ceil(l/m)*m,s,m).map(h)).concat(e.range(Math.ceil(r/f)*f,t,f).filter(function(t){return v(t%y)>kt}).map(u)).concat(e.range(Math.ceil(a/d)*d,o,d).filter(function(t){return v(t%m)>kt}).map(c))}return _.lines=function(){return x().map(function(t){return{type:"LineString",coordinates:t}})},_.outline=function(){return{type:"Polygon",coordinates:[p(i).concat(h(s).slice(1),p(n).reverse().slice(1),h(l).reverse().slice(1))]}},_.extent=function(t){return arguments.length?_.majorExtent(t).minorExtent(t):_.minorExtent()},_.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),_.precision(g)):[[i,l],[n,s]]},_.minorExtent=function(e){return arguments.length?(r=+e[0][0],t=+e[1][0],a=+e[0][1],o=+e[1][1],r>t&&(e=r,r=t,t=e),a>o&&(e=a,a=o,o=e),_.precision(g)):[[r,a],[t,o]]},_.step=function(t){return arguments.length?_.majorStep(t).minorStep(t):_.minorStep()},_.majorStep=function(t){return arguments.length?(y=+t[0],m=+t[1],_):[y,m]},_.minorStep=function(t){return arguments.length?(f=+t[0],d=+t[1],_):[f,d]},_.precision=function(e){return arguments.length?(g=+e,u=Bn(a,o,90),c=Fn(r,t,g),p=Bn(l,s,90),h=Fn(i,n,g),_):g},_.majorExtent([[-180,-90+kt],[180,90-kt]]).minorExtent([[-180,-80-kt],[180,80+kt]])},e.geo.greatArc=function(){var t,r,n=Nn,i=jn;function o(){return{type:"LineString",coordinates:[t||n.apply(this,arguments),r||i.apply(this,arguments)]}}return o.distance=function(){return e.geo.distance(t||n.apply(this,arguments),r||i.apply(this,arguments))},o.source=function(e){return arguments.length?(n=e,t="function"==typeof e?null:e,o):n},o.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,o):i},o.precision=function(){return arguments.length?o:0},o},e.geo.interpolate=function(t,e){return r=t[0]*zt,n=t[1]*zt,i=e[0]*zt,o=e[1]*zt,a=Math.cos(n),s=Math.sin(n),l=Math.cos(o),u=Math.sin(o),c=a*Math.cos(r),p=a*Math.sin(r),h=l*Math.cos(i),f=l*Math.sin(i),d=2*Math.asin(Math.sqrt(Rt(o-n)+a*l*Rt(i-r))),y=1/Math.sin(d),(m=d?function(t){var e=Math.sin(t*=d)*y,r=Math.sin(d-t)*y,n=r*c+e*h,i=r*p+e*f,o=r*s+e*u;return[Math.atan2(i,n)*Lt,Math.atan2(o,Math.sqrt(n*n+i*i))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=d,m;var r,n,i,o,a,s,l,u,c,p,h,f,d,y,m},e.geo.length=function(t){return gn=0,e.geo.stream(t,Vn),gn};var Vn={sphere:O,point:O,lineStart:function(){var t,e,r;function n(n,i){var o=Math.sin(i*=zt),a=Math.cos(i),s=v((n*=zt)-t),l=Math.cos(s);gn+=Math.atan2(Math.sqrt((s=a*Math.sin(s))*s+(s=r*o-e*a*l)*s),e*o+r*a*l),t=n,e=o,r=a}Vn.point=function(i,o){t=i*zt,e=Math.sin(o*=zt),r=Math.cos(o),Vn.point=n},Vn.lineEnd=function(){Vn.point=Vn.lineEnd=O}},lineEnd:O,polygonStart:O,polygonEnd:O};function qn(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),o=t(n*i);return[o*i*Math.sin(e),o*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),o=Math.sin(i),a=Math.cos(i);return[Math.atan2(t*o,n*a),Math.asin(n&&r*o/n)]},r}var Un=qn(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(e.geo.azimuthalEqualArea=function(){return Mn(Un)}).raw=Un;var Hn=qn(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},E);function Zn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),o=r*Math.pow(n(t),i)/i;if(!i)return Xn;function a(t,e){o>0?e<-Ct+kt&&(e=-Ct+kt):e>Ct-kt&&(e=Ct-kt);var r=o/Math.pow(n(e),i);return[r*Math.sin(i*t),o-r*Math.cos(i*t)]}return a.invert=function(t,e){var r=o-e,n=Et(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(o/n,1/i))-Ct]},a}function Gn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(v(n)1&&Pt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(e.geo.stereographic=function(){return Mn(Kn)}).raw=Kn,$n.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(e.geo.transverseMercator=function(){var t=Yn($n),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=$n,e.geom={},e.geom.hull=function(t){var e=Qn,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=me(e),o=me(r),a=t.length,s=[],l=[];for(n=0;n=0;--n)f.push(t[s[u[n]][2]]);for(n=+p;nkt)s=s.L;else{if(!((i=o-_i(s,a))>kt)){n>-kt?(e=s.P,r=s):i>-kt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=di(t);if(ui.insert(e,l),e||r){if(e===r)return ki(e),r=di(e.site),ui.insert(l,r),l.edge=r.edge=Mi(e.site,l.site),wi(e),void wi(r);if(r){ki(e),ki(r);var u=e.site,c=u.x,p=u.y,h=t.x-c,f=t.y-p,d=r.site,y=d.x-c,m=d.y-p,g=2*(h*m-f*y),v=h*h+f*f,_=y*y+m*m,x={x:(m*v-f*_)/g+c,y:(h*_-y*v)/g+p};Si(r.edge,u,d,x),l.edge=Mi(u,t,null,x),r.edge=Mi(t,d,null,x),wi(e),wi(r)}else l.edge=Mi(e.site,l.site)}}function vi(t,e){var r=t.site,n=r.x,i=r.y,o=i-e;if(!o)return n;var a=t.P;if(!a)return-1/0;var s=(r=a.site).x,l=r.y,u=l-e;if(!u)return s;var c=s-n,p=1/o-1/u,h=c/u;return p?(-h+Math.sqrt(h*h-2*p*(c*c/(-2*u)-l+u/2+i-o/2)))/p+n:(n+s)/2}function _i(t,e){var r=t.N;if(r)return vi(r,e);var n=t.site;return n.y===e?n.x:1/0}function xi(t){this.site=t,this.edges=[]}function bi(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,o=r.site;if(n!==o){var a=i.x,s=i.y,l=n.x-a,u=n.y-s,c=o.x-a,p=2*(l*(m=o.y-s)-u*c);if(!(p>=-At)){var h=l*l+u*u,f=c*c+m*m,d=(m*h-u*f)/p,y=(l*f-c*h)/p,m=y+s,g=fi.pop()||new function(){Li(this),this.x=this.y=this.arc=this.site=this.cy=null};g.arc=t,g.site=i,g.x=d+a,g.y=m+Math.sqrt(d*d+y*y),g.cy=m,t.circle=g;for(var v=null,_=pi._;_;)if(g.y<_.y||g.y===_.y&&g.x<=_.x){if(!_.L){v=_.P;break}_=_.L}else{if(!_.R){v=_;break}_=_.R}pi.insert(v,g),v||(ci=g)}}}}function ki(t){var e=t.circle;e&&(e.P||(ci=e.N),pi.remove(e),fi.push(e),Li(e),t.circle=null)}function Ai(t,e){var r=t.b;if(r)return!0;var n,i,o=t.a,a=e[0][0],s=e[1][0],l=e[0][1],u=e[1][1],c=t.l,p=t.r,h=c.x,f=c.y,d=p.x,y=p.y,m=(h+d)/2,g=(f+y)/2;if(y===f){if(m=s)return;if(h>d){if(o){if(o.y>=u)return}else o={x:m,y:l};r={x:m,y:u}}else{if(o){if(o.y1)if(h>d){if(o){if(o.y>=u)return}else o={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(o){if(o.y=s)return}else o={x:a,y:n*a+i};r={x:s,y:n*s+i}}else{if(o){if(o.xkt||v(i-r)>kt)&&(s.splice(a,0,new Ci((g=o.site,_=c,x=v(n-p)kt?{x:p,y:v(e-p)kt?{x:v(r-d)kt?{x:h,y:v(e-h)kt?{x:v(r-f)=r&&u.x<=i&&u.y>=n&&u.y<=a?[[r,a],[i,a],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/kt)*kt,y:Math.round(i(t,e)/kt)*kt,i:e}})}return a.links=function(t){return Di(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},a.triangles=function(t){var e=[];return Di(s(t)).cells.forEach(function(r,n){for(var i,o,a,s,l=r.site,u=r.edges.sort(bi),c=-1,p=u.length,h=u[p-1].edge,f=h.l===l?h.r:h.l;++co&&(i=e.slice(o,i),s[a]?s[a]+=i:s[++a]=i),(r=r[0])===(n=n[0])?s[a]?s[a]+=n:s[++a]=n:(s[++a]=null,l.push({i:a,x:Vi(r,n)})),o=Hi.lastIndex;return oy&&(y=l.x),l.y>m&&(m=l.y),u.push(l.x),c.push(l.y);else for(p=0;py&&(y=x),b>m&&(m=b),u.push(x),c.push(b)}var w=y-f,k=m-d;function A(t,e,r,n,i,o,a,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,u=t.y;if(null!=l)if(v(l-r)+v(u-n)<.01)T(t,e,r,n,i,o,a,s);else{var c=t.point;t.x=t.y=t.point=null,T(t,c,l,u,i,o,a,s),T(t,e,r,n,i,o,a,s)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,i,o,a,s)}function T(t,e,r,n,i,o,a,s){var l=.5*(i+a),u=.5*(o+s),c=r>=l,p=n>=u,h=p<<1|c;t.leaf=!1,t=t.nodes[h]||(t.nodes[h]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(M,t,+g(t,++p),+_(t,p),f,d,y,m)}}),c?i=l:a=l,p?o=u:s=u,A(t,e,r,n,i,o,a,s)}w>k?m=d+w:y=f+k;var M={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(M,t,+g(t,++p),+_(t,p),f,d,y,m)}};if(M.visit=function(t){!function t(e,r,n,i,o,a){if(!e(r,n,i,o,a)){var s=.5*(n+o),l=.5*(i+a),u=r.nodes;u[0]&&t(e,u[0],n,i,s,l),u[1]&&t(e,u[1],s,i,o,l),u[2]&&t(e,u[2],n,l,s,a),u[3]&&t(e,u[3],s,l,o,a)}}(t,M,f,d,y,m)},M.find=function(t){return function(t,e,r,n,i,o,a){var s,l=1/0;return function t(u,c,p,h,f){if(!(c>o||p>a||h=b)<<1|e>=x,k=w+4;w=0&&!(n=e.interpolators[i](t,r)););return n}function Gi(t,e){var r,n=[],i=[],o=t.length,a=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function eo(t){return 1-Math.cos(t*Ct)}function ro(t){return Math.pow(2,10*(t-1))}function no(t){return 1-Math.sqrt(1-t*t)}function io(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}function oo(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function ao(t){var e,r,n,i=[t.a,t.b],o=[t.c,t.d],a=lo(i),s=so(i,o),l=lo(((e=o)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*o[1]=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"in";return i=Xi.get(i)||Wi,o=Yi.get(o)||E,e=o(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},e.interpolateHcl=function(t,r){t=e.hcl(t),r=e.hcl(r);var n=t.h,i=t.c,o=t.l,a=r.h-n,s=r.c-i,l=r.l-o;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(a)?(a=0,n=isNaN(n)?r.h:n):a>180?a-=360:a<-180&&(a+=360);return function(t){return Wt(n+a*t,i+s*t,o+l*t)+""}},e.interpolateHsl=function(t,r){t=e.hsl(t),r=e.hsl(r);var n=t.h,i=t.s,o=t.l,a=r.h-n,s=r.s-i,l=r.l-o;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(a)?(a=0,n=isNaN(n)?r.h:n):a>180?a-=360:a<-180&&(a+=360);return function(t){return Ht(n+a*t,i+s*t,o+l*t)+""}},e.interpolateLab=function(t,r){t=e.lab(t),r=e.lab(r);var n=t.l,i=t.a,o=t.b,a=r.l-n,s=r.a-i,l=r.b-o;return function(t){return te(n+a*t,i+s*t,o+l*t)+""}},e.interpolateRound=oo,e.transform=function(t){var r=i.createElementNS(e.ns.prefix.svg,"g");return(e.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new ao(e?e.matrix:uo)})(t)},ao.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var uo={a:1,b:0,c:0,d:1,e:0,f:0};function co(t){return t.length?t.pop()+",":""}function po(t,r){var n=[],i=[];return t=e.transform(t),r=e.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(t.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(co(r)+"rotate(",null,")")-2,x:Vi(t,e)})):e&&r.push(co(r)+"rotate("+e+")")}(t.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(co(r)+"skewX(",null,")")-2,x:Vi(t,e)}):e&&r.push(co(r)+"skewX("+e+")")}(t.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(co(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(co(r)+"scale("+e+")")}(t.scale,r.scale,n,i),t=r=null,function(t){for(var e,r=-1,o=i.length;++r0?n=e:(t.c=null,t.t=NaN,t=null,l.end({type:"end",alpha:n=0})):e>0&&(l.start({type:"start",alpha:n=e}),t=Ae(s.tick)),s):n},s.start=function(){var t,e,r,n=g.length,l=v.length,c=u[0],d=u[1];for(t=0;t=0;)r.push(i[n])}function Mo(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(o=t.children)&&(i=o.length))for(var i,o,a=-1;++a=0;)a.push(c=u[l]),c.parent=o,c.depth=o.depth+1;r&&(o.value=0),o.children=u}else r&&(o.value=+r.call(n,o,o.depth)||0),delete o.children;return Mo(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(To(t,function(t){t.children&&(t.value=0)}),Mo(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},e.layout.partition=function(){var t=e.layout.hierarchy(),r=[1,1];function n(e,n){var i=t.call(this,e,n);return function t(e,r,n,i){var o=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,o&&(a=o.length)){var a,s,l,u=-1;for(n=e.value?n/e.value:0;++us&&(s=n),a.push(n)}for(r=0;ri&&(n=r,i=e);return n}function jo(t){return t.reduce(Vo,0)}function Vo(t,e){return t+e[1]}function qo(t,e){return Uo(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Uo(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,o=[];++r<=e;)o[r]=i*r+n;return o}function Ho(t){return[e.min(t),e.max(t)]}function Zo(t,e){return t.value-e.value}function Go(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Wo(t,e){t._pack_next=e,e._pack_prev=t}function Xo(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Yo(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,o,a,s,l,u=1/0,c=-1/0,p=1/0,h=-1/0;if(e.forEach(Jo),(r=e[0]).x=-r.r,r.y=0,_(r),l>1&&((n=e[1]).x=n.r,n.y=0,_(n),l>2))for($o(r,n,i=e[2]),_(i),Go(r,i),r._pack_prev=i,Go(i,n),n=r._pack_next,o=3;o0)for(a=-1;++a=p[0]&&l<=p[1]&&((s=u[e.bisect(h,l,1,d)-1]).y+=y,s.push(o[a]));return u}return o.value=function(t){return arguments.length?(r=t,o):r},o.range=function(t){return arguments.length?(n=me(t),o):n},o.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Uo(e,t)}:me(t),o):i},o.frequency=function(e){return arguments.length?(t=!!e,o):t},o},e.layout.pack=function(){var t,r=e.layout.hierarchy().sort(Zo),n=0,i=[1,1];function o(e,o){var a=r.call(this,e,o),s=a[0],l=i[0],u=i[1],c=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(s.x=s.y=0,Mo(s,function(t){t.r=+c(t.value)}),Mo(s,Yo),n){var p=n*(t?1:Math.max(2*s.r/l,2*s.r/u))/2;Mo(s,function(t){t.r+=p}),Mo(s,Yo),Mo(s,function(t){t.r-=p})}return function t(e,r,n,i){var o=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(o)for(var a=-1,s=o.length;++af.x&&(f=t),t.depth>d.depth&&(d=t)});var y=r(h,f)/2-h.x,m=n[0]/(f.x+r(f,h)/2+y),g=n[1]/(d.depth||1);To(c,function(t){t.x=(t.x+y)*m,t.y=t.depth*g})}return u}function a(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,o=i.length;for(;--o>=0;)(e=i[o]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var o=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-o):t.z=o}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,o=t,a=t,s=e,l=o.parent.children[0],u=o.m,c=a.m,p=s.m,h=l.m;s=ea(s),o=ta(o),s&&o;)l=ta(l),(a=ea(a)).a=t,(i=s.z+p-o.z-u+r(s._,o._))>0&&(ra(na(s,t,n),t,i),u+=i,c+=i),p+=s.m,u+=o.m,h+=l.m,c+=a.m;s&&!ea(a)&&(a.t=s,a.m+=p-c),o&&!ta(l)&&(l.t=o,l.m+=u-h,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return o.separation=function(t){return arguments.length?(r=t,o):r},o.size=function(t){return arguments.length?(i=null==(n=t)?l:null,o):i?null:n},o.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,o):i?n:null},Ao(o,t)},e.layout.cluster=function(){var t=e.layout.hierarchy().sort(null).value(null),r=Qo,n=[1,1],i=!1;function o(o,a){var s,l=t.call(this,o,a),u=l[0],c=0;Mo(u,function(t){var n=t.children;n&&n.length?(t.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),t.y=function(t){return 1+e.max(t,function(t){return t.y})}(n)):(t.x=s?c+=r(t,s):0,t.y=0,s=t)});var p=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),h=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),f=p.x-r(p,h)/2,d=h.x+r(h,p)/2;return Mo(u,i?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-f)/(d-f)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),l}return o.separation=function(t){return arguments.length?(r=t,o):r},o.size=function(t){return arguments.length?(i=null==(n=t),o):i?null:n},o.nodeSize=function(t){return arguments.length?(i=null!=(n=t),o):i?n:null},Ao(o,t)},e.layout.treemap=function(){var t,r=e.layout.hierarchy(),n=Math.round,i=[1,1],o=null,a=ia,s=!1,l="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,i=-1,o=t.length;++i0;)s.push(r=u[i-1]),s.area+=r.area,"squarify"!==l||(n=f(s,y))<=h?(u.pop(),h=n):(s.area-=s.pop().area,d(s,y,o,!1),y=Math.min(o.dx,o.dy),s.length=s.area=0,h=1/0);s.length&&(d(s,y,o,!0),s.length=s.area=0),e.forEach(p)}}function h(t){var e=t.children;if(e&&e.length){var r,n=a(t),i=e.slice(),o=[];for(c(i,n.dx*n.dy/t.value),o.area=0;r=i.pop();)o.push(r),o.area+=r.area,null!=r.z&&(d(o,r.z?n.dx:n.dy,n,!i.length),o.length=o.area=0);e.forEach(h)}}function f(t,e){for(var r,n=t.area,i=0,o=1/0,a=-1,s=t.length;++ai&&(i=r));return e*=e,(n*=n)?Math.max(e*i*u/n,n/(e*o*u)):1/0}function d(t,e,r,i){var o,a=-1,s=t.length,l=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((i||c>r.dy)&&(c=r.dy);++ar.dx)&&(c=r.dx);++a1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=e.random.normal.apply(e,arguments);return function(){return Math.exp(t())}},bates:function(t){var r=e.random.irwinHall(t);return function(){return r()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?ha:la,s=i?fo:ho;return o=t(e,r,s,n),a=t(r,e,s,Zi),l}function l(t){return o(t)}l.invert=function(t){return a(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(oo)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return ma(e,t)};l.tickFormat=function(t,r){return ga(e,t,r)};l.nice=function(t){return da(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Zi,!1)};var va={s:1,g:1,p:1,r:1,e:1};function _a(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}e.scale.log=function(){return function t(r,n,i,o){function a(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(a(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((o=t.map(Number)).map(a)),l):o};l.base=function(t){return arguments.length?(n=+t,r.domain(o.map(a)),l):n};l.nice=function(){var t=ua(o.map(a),i?Math:ba);return r.domain(t),o=t.map(s),l};l.ticks=function(){var t=aa(o),e=[],r=t[0],l=t[1],u=Math.floor(a(r)),c=Math.ceil(a(l)),p=n%1?2:n;if(isFinite(c-u)){if(i){for(;u0;h--)e.push(s(u)*h);for(u=0;e[u]l;c--);e=e.slice(u,c)}return e};l.tickFormat=function(t,r){if(!arguments.length)return xa;arguments.length<2?r=xa:"function"!=typeof r&&(r=e.format(r));var i=Math.max(1,n*t/l.ticks().length);return function(t){var e=t/s(Math.round(a(t)));return e*n0?i[t-1]:r[0],tp?0:1;if(u=St)return l(u,f)+(s?l(s,1-f):"")+"Z";var d,y,m,g,v,_,x,b,w,k,A,T,M=0,S=0,C=[];if((g=(+a.apply(this,arguments)||0)/2)&&(m=n===Ca?Math.sqrt(s*s+u*u):+n.apply(this,arguments),f||(S*=-1),u&&(S=Dt(m/u*Math.sin(g))),s&&(M=Dt(m/s*Math.sin(g)))),u){v=u*Math.cos(c+S),_=u*Math.sin(c+S),x=u*Math.cos(p-S),b=u*Math.sin(p-S);var z=Math.abs(p-c-2*S)<=Tt?0:1;if(S&&Da(v,_,x,b)===f^z){var L=(c+p)/2;v=u*Math.cos(L),_=u*Math.sin(L),x=b=null}}else v=_=0;if(s){w=s*Math.cos(p-M),k=s*Math.sin(p-M),A=s*Math.cos(c+M),T=s*Math.sin(c+M);var E=Math.abs(c-p+2*M)<=Tt?0:1;if(M&&Da(w,k,A,T)===1-f^E){var P=(c+p)/2;w=s*Math.cos(P),k=s*Math.sin(P),A=T=null}}else w=k=0;if(h>kt&&(d=Math.min(Math.abs(u-s)/2,+r.apply(this,arguments)))>.001){y=s0?0:1}function Oa(t,e,r,n,i){var o=t[0]-e[0],a=t[1]-e[1],s=(i?n:-n)/Math.sqrt(o*o+a*a),l=s*a,u=-s*o,c=t[0]+l,p=t[1]+u,h=e[0]+l,f=e[1]+u,d=(c+h)/2,y=(p+f)/2,m=h-c,g=f-p,v=m*m+g*g,_=r-n,x=c*f-h*p,b=(g<0?-1:1)*Math.sqrt(Math.max(0,_*_*v-x*x)),w=(x*g-m*b)/v,k=(-x*m-g*b)/v,A=(x*g+m*b)/v,T=(-x*m+g*b)/v,M=w-d,S=k-y,C=A-d,z=T-y;return M*M+S*S>C*C+z*z&&(w=A,k=T),[[w-l,k-u],[w*r/_,k*r/_]]}function Ra(t){var e=Qn,r=ti,n=Gr,i=Fa,o=i.key,a=.7;function s(o){var s,l=[],u=[],c=-1,p=o.length,h=me(e),f=me(r);function d(){l.push("M",i(t(u),a))}for(;++c1&&i.push("H",n[0]);return i.join("")},"step-before":ja,"step-after":Va,basis:Ha,"basis-open":function(t){if(t.length<4)return Fa(t);var e,r=[],n=-1,i=t.length,o=[0],a=[0];for(;++n<3;)e=t[n],o.push(e[0]),a.push(e[1]);r.push(Za(Xa,o)+","+Za(Xa,a)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),a[s]=i*r,a[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+a[s]*a[s])),o.push([i||0,a[s]*i||0]);return o}(t))}});function Fa(t){return t.length>1?t.join("L"):t+"Z"}function Na(t){return t.join("L")+"Z"}function ja(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],o=t[l],l++,n+="C"+(i[0]+a[0])+","+(i[1]+a[1])+","+(o[0]-s[0])+","+(o[1]-s[1])+","+o[0]+","+o[1];for(var u=2;uTt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return o.radius=function(t){return arguments.length?(r=me(t),o):r},o.source=function(e){return arguments.length?(t=me(e),o):t},o.target=function(t){return arguments.length?(e=me(t),o):e},o.startAngle=function(t){return arguments.length?(n=me(t),o):n},o.endAngle=function(t){return arguments.length?(i=me(t),o):i},o},e.svg.diagonal=function(){var t=Nn,e=jn,r=ts;function n(n,i){var o=t.call(this,n,i),a=e.call(this,n,i),s=(o.y+a.y)/2,l=[o,{x:o.x,y:s},{x:a.x,y:s},a];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=me(e),n):t},n.target=function(t){return arguments.length?(e=me(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},e.svg.diagonal.radial=function(){var t=e.svg.diagonal(),r=ts,n=t.projection;return t.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},t},e.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=me(e),r):t},r.size=function(t){return arguments.length?(e=me(t),r):e},r};var is=e.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*as)),r=e*as;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/os),r=e*os/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/os),r=e*os/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});e.svg.symbolTypes=is.keys();var os=Math.sqrt(3),as=Math.tan(30*zt);W.transition=function(t){for(var e,r,n=cs||++fs,i=ms(t),o=[],a=ps||{time:Date.now(),ease:to,delay:0,duration:250},s=-1,l=this.length;++s0;)u[--h].call(t,a);if(o>=1)return p.event&&p.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}p||(o=i.time,a=Ae(function(t){var e=p.delay;if(a.t=e+o,e<=t)return h(t-e);a.c=h},0,o),p=c[n]={tween:new x,time:o,timer:a,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++c.count)}hs.call=W.call,hs.empty=W.empty,hs.node=W.node,hs.size=W.size,e.transition=function(t,r){return t&&t.transition?cs?t.transition(r):t:e.selection().transition(t)},e.transition.prototype=hs,hs.select=function(t){var e,r,n,i=this.id,o=this.namespace,a=[];t=X(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function y(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function m(){var p,m,g=this,v=e.select(e.event.target),_=n.of(g,arguments),x=e.select(g),b=v.datum(),w=!/^(n|s)$/.test(b)&&i,k=!/^(e|w)$/.test(b)&&o,A=v.classed("extent"),T=_t(g),M=e.mouse(g),S=e.select(a(g)).on("keydown.brush",function(){32==e.event.keyCode&&(A||(p=null,M[0]-=s[1],M[1]-=l[1],A=2),F())}).on("keyup.brush",function(){32==e.event.keyCode&&2==A&&(M[0]+=s[1],M[1]+=l[1],A=0,F())});if(e.event.changedTouches?S.on("touchmove.brush",L).on("touchend.brush",P):S.on("mousemove.brush",L).on("mouseup.brush",P),x.interrupt().selectAll("*").interrupt(),A)M[0]=s[0]-M[0],M[1]=l[0]-M[1];else if(b){var C=+/w$/.test(b),z=+/^n/.test(b);m=[s[1-C]-M[0],l[1-z]-M[1]],M[0]=s[C],M[1]=l[z]}else e.event.altKey&&(p=M.slice());function L(){var t=e.mouse(g),r=!1;m&&(t[0]+=m[0],t[1]+=m[1]),A||(e.event.altKey?(p||(p=[(s[0]+s[1])/2,(l[0]+l[1])/2]),M[0]=s[+(t[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=zs(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=zs(+e+1);return e}}:t))},i.ticks=function(t,e){var r=aa(i.domain()),n=null==t?o(r,10):"number"==typeof t?o(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],zs(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Cs(t.copy(),r,n)},fa(i,t)}function zs(t){return new Date(t)}As.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ss:Ms,Ss.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Ss.toString=Ms.toString,Ie.second=Be(function(t){return new De(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Ie.seconds=Ie.second.range,Ie.seconds.utc=Ie.second.utc.range,Ie.minute=Be(function(t){return new De(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Ie.minutes=Ie.minute.range,Ie.minutes.utc=Ie.minute.utc.range,Ie.hour=Be(function(t){var e=t.getTimezoneOffset()/60;return new De(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Ie.hours=Ie.hour.range,Ie.hours.utc=Ie.hour.utc.range,Ie.month=Be(function(t){return(t=Ie.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Ie.months=Ie.month.range,Ie.months.utc=Ie.month.utc.range;var Ls=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Es=[[Ie.second,1],[Ie.second,5],[Ie.second,15],[Ie.second,30],[Ie.minute,1],[Ie.minute,5],[Ie.minute,15],[Ie.minute,30],[Ie.hour,1],[Ie.hour,3],[Ie.hour,6],[Ie.hour,12],[Ie.day,1],[Ie.day,2],[Ie.week,1],[Ie.month,1],[Ie.month,3],[Ie.year,1]],Ps=As.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Gr]]),Is={range:function(t,r,n){return e.range(Math.ceil(t/n)*n,+r,n).map(zs)},floor:E,ceil:E};Es.year=Ie.year,Ie.scale=function(){return Cs(e.scale.linear(),Es,Ps)};var Ds=Es.map(function(t){return[t[0].utc,t[1]]}),Os=Ts.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Gr]]);function Rs(t){return JSON.parse(t.responseText)}function Bs(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Ds.year=Ie.year.utc,Ie.scale.utc=function(){return Cs(e.scale.linear(),Ds,Os)},e.text=ge(function(t){return t.responseText}),e.json=function(t,e){return ve(t,"application/json",Rs,e)},e.html=function(t,e){return ve(t,"text/html",Bs,e)},e.xml=ge(function(t){return t.responseXML}),t.exports?t.exports=e:this.d3=e}(),t=t.exports;var e=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},r={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},n={},i=Math.PI;n.deg2rad=function(t){return t/180*i},n.rad2deg=function(t){return t/i*180},n.wrap360=function(t){var e=t%360;return e<0?e+360:e},n.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var o=r.BADNUM,a=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,i=t.round,o=t.min,a=t.max,l=t.random;function u(s,l){if(s=s||"",l=l||{},s instanceof u)return s;if(!(this instanceof u))return new u(s,l);var c=function(n){var i={r:0,g:0,b:0},s=1,l=null,u=null,c=null,p=!1,h=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,i=!1;if(S[t])t=S[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=j.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=j.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=j.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=j.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=j.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=j.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=j.hex8.exec(t))return{r:P(n[1]),g:P(n[2]),b:P(n[3]),a:R(n[4]),format:i?"name":"hex8"};if(n=j.hex6.exec(t))return{r:P(n[1]),g:P(n[2]),b:P(n[3]),format:i?"name":"hex"};if(n=j.hex4.exec(t))return{r:P(n[1]+""+n[1]),g:P(n[2]+""+n[2]),b:P(n[3]+""+n[3]),a:R(n[4]+""+n[4]),format:i?"name":"hex8"};if(n=j.hex3.exec(t))return{r:P(n[1]+""+n[1]),g:P(n[2]+""+n[2]),b:P(n[3]+""+n[3]),format:i?"name":"hex"};return!1}(n));"object"==typeof n&&(V(n.r)&&V(n.g)&&V(n.b)?(f=n.r,d=n.g,y=n.b,i={r:255*L(f,255),g:255*L(d,255),b:255*L(y,255)},p=!0,h="%"===String(n.r).substr(-1)?"prgb":"rgb"):V(n.h)&&V(n.s)&&V(n.v)?(l=D(n.s),u=D(n.v),i=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var i=t.floor(e),o=e-i,a=n*(1-r),s=n*(1-o*r),l=n*(1-(1-o)*r),u=i%6;return{r:255*[n,s,a,a,l,n][u],g:255*[l,n,n,s,a,a][u],b:255*[a,a,l,n,n,s][u]}}(n.h,l,u),p=!0,h="hsv"):V(n.h)&&V(n.s)&&V(n.l)&&(l=D(n.s),c=D(n.l),i=function(t,e,r){var n,i,o;function a(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=i=o=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=a(l,s,t+1/3),i=a(l,s,t),o=a(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*o}}(n.h,l,c),p=!0,h="hsl"),n.hasOwnProperty("a")&&(s=n.a));var f,d,y;return s=z(s),{ok:p,format:n.format||h,r:o(255,a(i.r,0)),g:o(255,a(i.g,0)),b:o(255,a(i.b,0)),a:s}}(s);this._originalInput=s,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=i(100*this._a)/100,this._format=l.format||c.format,this._gradientType=l.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=c.ok,this._tc_id=n++}function c(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,i,s=a(t,e,r),l=o(t,e,r),u=(s+l)/2;if(s==l)n=i=0;else{var c=s-l;switch(i=u>.5?c/(2-s-l):c/(s+l),s){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,o.push(u(n));return o}function M(t,e){e=e||6;for(var r=u(t).toHsv(),n=r.h,i=r.s,o=r.v,a=[],s=1/e;e--;)a.push(u({h:n,s:i,v:o})),o=(o+s)%1;return a}u.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=z(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=p(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=p(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=c(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=c(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return h(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,o){var a=[I(i(t).toString(16)),I(i(e).toString(16)),I(i(r).toString(16)),I(O(n))];if(o&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)&&a[3].charAt(0)==a[3].charAt(1))return a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0)+a[3].charAt(0);return a.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*L(this._r,255))+"%",g:i(100*L(this._g,255))+"%",b:i(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%)":"rgba("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[h(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+f(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=u(t);r="#"+f(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return u(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(g,arguments)},brighten:function(){return this._applyModification(v,arguments)},darken:function(){return this._applyModification(_,arguments)},desaturate:function(){return this._applyModification(d,arguments)},saturate:function(){return this._applyModification(y,arguments)},greyscale:function(){return this._applyModification(m,arguments)},spin:function(){return this._applyModification(x,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(b,arguments)},monochromatic:function(){return this._applyCombination(M,arguments)},splitcomplement:function(){return this._applyCombination(A,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},u.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:D(t[n]));t=r}return u(t,e)},u.equals=function(t,e){return!(!t||!e)&&u(t).toRgbString()==u(e).toRgbString()},u.random=function(){return u.fromRatio({r:l(),g:l(),b:l()})},u.mix=function(t,e,r){r=0===r?0:r||50;var n=u(t).toRgb(),i=u(e).toRgb(),o=r/100;return u({r:(i.r-n.r)*o+n.r,g:(i.g-n.g)*o+n.g,b:(i.b-n.b)*o+n.b,a:(i.a-n.a)*o+n.a})},u.readability=function(e,r){var n=u(e),i=u(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},u.isReadable=function(t,e,r){var n,i,o=u.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=o>=4.5;break;case"AAlarge":i=o>=3;break;case"AAAsmall":i=o>=7}return i},u.mostReadable=function(t,e,r){var n,i,o,a,s=null,l=0;i=(r=r||{}).includeFallbackColors,o=r.level,a=r.size;for(var c=0;cl&&(l=n,s=u(e[c]));return u.isReadable(t,s,{level:o,size:a})||!i?s:(r.includeFallbackColors=!1,u.mostReadable(t,["#fff","#000"],r))};var S=u.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"},C=u.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(S);function z(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=o(r,a(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function E(t){return o(1,a(0,t))}function P(t){return parseInt(t,16)}function I(t){return 1==t.length?"0"+t:""+t}function D(t){return t<=1&&(t=100*t+"%"),t}function O(e){return t.round(255*parseFloat(e)).toString(16)}function R(t){return P(t)/255}var B,F,N,j=(F="[\\s|\\(]+("+(B="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+B+")[,|\\s]+("+B+")\\s*\\)?",N="[\\s|\\(]+("+B+")[,|\\s]+("+B+")[,|\\s]+("+B+")[,|\\s]+("+B+")\\s*\\)?",{CSS_UNIT:new RegExp(B),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+N),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})$/});function V(t){return!!j.CSS_UNIT.exec(t)}s.exports?s.exports=u:window.tinycolor=u}(Math),s=s.exports;var l={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=l.RdBu,c=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],i=t[e][1],a=!1,Z(n))for(r=n.length-1;r>=0;r--)Y(n[r],K(i,r))?a?n[r]=void 0:n.pop():a=!0;else if("object"==typeof n&&null!==n)for(o=Object.keys(n),a=!1,r=o.length-1;r>=0;r--)Y(n[o[r]],K(i,o[r]))?delete n[o[r]]:a=!0;if(a)return}}(l)):a[e[o]]=n}}function K(t,r){var n=r;return e(r)?n="["+r+"]":t&&(n="."+r),t+n}function $(t,e,r,n){var i,o=Z(r),a=!0,s=r,l=n.replace("-1",0),u=!o&&Y(r,l),c=e[0];for(i=0;ii.max?r.set(n):r.set(+t)}},integer:{coerceFunction:function(t,r,n,i){t%1||!e(t)||void 0!==i.min&&ti.max?r.set(n):r.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){s(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return s(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(p(t,r))}},angle:{coerceFunction:function(t,r,n){"auto"===t?r.set("auto"):e(t)?r.set(it(+t)):r.set(n)}},subplotid:{coerceFunction:function(t,e,r,n){var i=n.regex||rt(r);"string"==typeof t&&i.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!rt(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),o=0;o=at&&t<=st?t:ct;if("string"!=typeof t&&"number"!=typeof t)return ct;t=String(t);var r=xt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var i=r&&"chinese"===e.substr(0,7),o=t.match(i?vt:gt);if(!o)return ct;var a=o[1],s=o[3]||"1",l=Number(o[5]||1),u=Number(o[7]||0),c=Number(o[9]||0),p=Number(o[11]||0);if(r){if(2===a.length)return ct;var h;a=Number(a);try{var f=P.getComponentMethod("calendars","getCal")(e);if(i){var d="i"===s.charAt(s.length-1);s=parseInt(s,10),h=f.newDate(a,f.toMonthIndex(a,s,d),l)}else h=f.newDate(a,Number(s),l)}catch(t){return ct}return h?(h.toJD()-yt)*pt+u*ht+c*ft+p*dt:ct}a=2===a.length?(Number(a)+2e3-_t)%100+_t:Number(a),s-=1;var y=new Date(Date.UTC(2e3,s,l,u,c));return y.setUTCFullYear(a),y.getUTCMonth()!==s?ct:y.getUTCDate()!==l?ct:y.getTime()+p*dt},at=ut.MIN_MS=ut.dateTime2ms("-9999"),st=ut.MAX_MS=ut.dateTime2ms("9999-12-31 23:59:59.9999"),ut.isDateTime=function(t,e){return ut.dateTime2ms(t,e)!==ct};var wt=90*pt,kt=3*ht,At=5*ft;function Tt(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+bt(e,2)+":"+bt(r,2),(n||i)&&(t+=":"+bt(n,2),i))){for(var o=4;i%10==0;)o-=1,i/=10;t+="."+bt(i,o)}return t}ut.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=at&&t<=st))return ct;e||(e=0);var n,i,o,a,s,l,u=Math.floor(10*lt(t+.05,1)),c=Math.round(t-u/10);if(xt(r)){var p=Math.floor(c/pt)+yt,h=Math.floor(lt(t,pt));try{n=P.getComponentMethod("calendars","getCal")(r).fromJD(p).formatDate("yyyy-mm-dd")}catch(t){n=mt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;i=e=at+pt&&e<=st-pt))return ct;var r=Math.floor(10*lt(e+.05,1)),n=new Date(Math.round(e-r/10));return Tt(t.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ut.cleanDate=function(t,e,r){if(ut.isJSDate(t)||"number"==typeof t){if(xt(r))return b.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ut.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ut.isDateTime(t,r))return b.error("unrecognized date",t),e;return t};var Mt=/%\d?f/g;function St(t,e,r,n){t=t.replace(Mt,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(xt(n))try{t=P.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var Ct=[59,59.9,59.99,59.999,59.9999];ut.formatDate=function(t,r,n,i,o,a){if(o=xt(o)&&o,!r)if("y"===n)r=a.year;else if("m"===n)r=a.month;else{if("d"!==n)return function(t,r){var n=lt(t+.05,pt),i=bt(Math.floor(n/ht),2)+":"+bt(lt(Math.floor(n/ft),60),2);if("M"!==r){e(r)||(r=0);var o=(100+Math.min(lt(t/dt,60),Ct[r])).toFixed(r).substr(1);r>0&&(o=o.replace(/0+$/,"").replace(/[\.]$/,"")),i+=":"+o}return i}(t,n)+"\n"+St(a.dayMonthYear,t,i,o);r=a.dayMonth+"\n"+a.year}return St(r,t,i,o)};var zt=3*pt;ut.incrementMonth=function(t,e,r){r=xt(r)&&r;var n=lt(t,pt);if(t=Math.round(t-n),r)try{var i=Math.round(t/pt)+yt,o=P.getComponentMethod("calendars","getCal")(r),a=o.fromJD(i);return e%12?o.add(a,e,"m"):o.add(a,e/12,"y"),(a.toJD()-yt)*pt+n}catch(e){b.error("invalid ms "+t+" in calendar "+r)}var s=new Date(t+zt);return s.setUTCMonth(s.getUTCMonth()+e)+n-zt},ut.findExactDates=function(t,r){for(var n,i,o=0,a=0,s=0,l=0,u=xt(r)&&P.getComponentMethod("calendars","getCal")(r),c=0;c1||y<0||y>1?null:{x:t+l*y,y:e+p*y}}function Bt(t,e,r,n,i){var o=n*t+i*e;if(o<0)return n*n+i*i;if(o>r){var a=n-t,s=i-e;return a*a+s*s}var l=n*e-i*t;return l*l/r}Ot.segmentsIntersect=Rt,Ot.segmentDistance=function(t,e,r,n,i,o,a,s){if(Rt(t,e,r,n,i,o,a,s))return 0;var l=r-t,u=n-e,c=a-i,p=s-o,h=l*l+u*u,f=c*c+p*p,d=Math.min(Bt(l,u,h,i-t,o-e),Bt(l,u,h,a-t,s-e),Bt(c,p,f,t-i,e-o),Bt(c,p,f,r-i,n-o));return Math.sqrt(d)},Ot.getTextLocation=function(t,e,r,n){if(t===It&&n===Dt||(Pt={},It=t,Dt=n),Pt[r])return Pt[r];var i=t.getPointAtLength(lt(r-n/2,e)),o=t.getPointAtLength(lt(r+n/2,e)),a=Math.atan((o.y-i.y)/(o.x-i.x)),s=t.getPointAtLength(lt(r,e)),l={x:(4*s.x+i.x+o.x)/6,y:(4*s.y+i.y+o.y)/6,theta:a};return Pt[r]=l,l},Ot.clearLocationCache=function(){It=null},Ot.getVisibleSegment=function(t,e,r){var n,i,o=e.left,a=e.right,s=e.top,l=e.bottom,u=0,c=t.getTotalLength(),p=c;function h(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(i=r);var u=r.xa?r.x-a:0,p=r.yl?r.y-l:0;return Math.sqrt(u*u+p*p)}for(var f=h(u);f;){if((u+=f+r)>p)return;f=h(u)}for(f=h(p);f;){if(u>(p-=f+r))return;f=h(p)}return{min:u,max:p,len:p-u,total:c,isClosed:0===u&&p===c&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},Ot.findPointOnPath=function(t,e,r,n){for(var i,o,a,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,p=0,h=0,f=s;p0?f=i:h=i,p++}return o};var Ft=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},Nt=/^\w*$/,jt={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Yt(t,e){return t>=e}Zt.findBin=function(t,r,n){if(e(r.start))return n?Math.ceil((t-r.start)/r.size-1e-9)-1:Math.floor((t-r.start)/r.size+1e-9);var i,o,a=0,s=r.length,l=0,u=s>1?(r[s-1]-r[0])/(s-1):1;for(o=u>=0?n?Gt:Wt:n?Yt:Xt,t+=1e-9*u*(n?-1:1)*(u>=0?1:-1);a90&&b.log("Long binary search..."),a-1},Zt.sorterAsc=function(t,e){return t-e},Zt.sorterDes=function(t,e){return e-t},Zt.distinctVals=function(t){var e=t.slice();e.sort(Zt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,i=n/(r||1)/1e4,o=[e[0]],a=0;ae[a]+i&&(n=Math.min(n,e[a+1]-e[a]),o.push(e[a+1]));return{vals:o,minDiff:n}},Zt.roundUp=function(t,e,r){for(var n,i=0,o=e.length-1,a=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;in.length)&&(i=n.length),e(r)||(r=!1),Kt(n[0])){for(a=new Array(i),o=0;ot.length-1)return t[t.length-1];var n=r%1;return n*t[Math.ceil(r)]+(1-n)*t[Math.floor(r)]};var $t={},Qt={};function te(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}$t.throttle=function(t,e,r){var n=Qt[t],i=Date.now();if(!n){for(var o in Qt)Qt[o].tsn.ts+e?a():n.timer=setTimeout(function(){a(),n.timer=null},e)},$t.done=function(t){var e=Qt[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},$t.clear=function(t){if(t)te(Qt[t]),delete Qt[t];else for(var e in Qt)$t.clear(e)};var ee=function(t,r){if(t>0)return Math.log(t)/Math.LN10;var n=Math.log(Math.min(r[0],r[1]))/Math.LN10;return e(n)||(n=Math.log(Math.max(r[0],r[1]))/Math.LN10-6),n},re={},ne=r.FP_SAFE,ie=r.BADNUM,oe=re={};oe.nestedProperty=G,oe.keyedContainer=function(t,e,r,n){var i,o;r=r||"name",n=n||"value";var a={};o=e&&e.length?G(t,e).get():t,e=e||"",o=o||[];var s={};for(i=0;i2)return a[e]=2|a[e],u.set(t,null);if(l){for(i=e;i/g),s=0;sne?ie:e(t)?Number(t):ie:ie},oe.noop=A,oe.identity=function(t){return t},oe.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},oe.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},oe.simpleMap=function(t,e,r,n){for(var i=t.length,o=new Array(i),a=0;a-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):s},oe.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},oe.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,o,a=t.length,s=2*a,l=2*e-1,u=new Array(l),c=new Array(a);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=a&&(i=s-1-i),o+=t[i]*u[n];c[r]=o}return c},oe.syncOrAsync=function(t,e,r){var n;function i(){return oe.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,oe.promiseError);return r&&r(e)},oe.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},oe.noneOrAll=function(t,e,r){if(t){var n,i,o=!1,a=!0;for(n=0;n=0&&o%1==0){var d=i?i[f]:f,y=n?n[d]:d;p(y)&&(t[y].selected=1)}}},oe.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=oe.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},oe.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,o,a=Object.keys(t);for(n=0;n1?i+a[1]:"";if(o&&(a.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+o+"$2");return s+l};var le=/%{([^\s%{}]*)}/g,ue=/^\w*$/;oe.templateString=function(t,e){var r={};return t.replace(le,function(t,n){return ue.test(n)?e[n]||"":(r[n]=r[n]||oe.nestedProperty(e,n).get,r[n]()||"")})};oe.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,o=0;o=48&&a<=57,u=s>=48&&s<=57;if(l&&(n=10*n+a-48),u&&(i=10*i+s-48),!l||!u){if(n!==i)return n-i;if(a!==s)return a-s}}return i-n};var ce=2e9;oe.seedPseudoRandom=function(){ce=2e9},oe.pseudoRandom=function(){var t=ce;return ce=(69069*ce+1)%4294967296,Math.abs(ce-t)<429496729?oe.pseudoRandom():ce/4294967296};var pe={"X,X div":"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 .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"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":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","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 .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 he in pe){var fe=he.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");re.addStyleRule(fe,pe[he])}var de,ye,me,ge={undo:{width:857.1,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",ascent:850,descent:-150},home:{width:928.6,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",ascent:850,descent:-150},"camera-retro":{width:1e3,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",ascent:850,descent:-150},zoombox:{width:1e3,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",ascent:850,descent:-150},pan:{width:1e3,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",ascent:850,descent:-150},zoom_plus:{width:1e3,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",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,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",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,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",ascent:850,descent:-150},plotlylogo:{width:1542,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",ascent:850,descent:-150},"z-axis":{width:1e3,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",ascent:850,descent:-150},"3d_rotate":{width:1e3,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",ascent:850,descent:-150},camera:{width:1e3,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",ascent:850,descent:-150},movie:{width:1e3,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",ascent:850,descent:-150},question:{width:857.1,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",ascent:850,descent:-150},disk:{width:857.1,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",ascent:850,descent:-150},lasso:{width:1031,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",ascent:850,descent:-150},selectbox:{width:1e3,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",ascent:850,descent:-150},spikeline:{width:1e3,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",ascent:850,descent:-150}},ve=de={};function _e(){throw new Error("setTimeout has not been defined")}function xe(){throw new Error("clearTimeout has not been defined")}function be(t){if(ye===setTimeout)return setTimeout(t,0);if((ye===_e||!ye)&&setTimeout)return ye=setTimeout,setTimeout(t,0);try{return ye(t,0)}catch(e){try{return ye.call(null,t,0)}catch(e){return ye.call(this,t,0)}}}!function(){try{ye="function"==typeof setTimeout?setTimeout:_e}catch(t){ye=_e}try{me="function"==typeof clearTimeout?clearTimeout:xe}catch(t){me=xe}}();var we,ke=[],Ae=!1,Te=-1;function Me(){Ae&&we&&(Ae=!1,we.length?ke=we.concat(ke):Te=-1,ke.length&&Se())}function Se(){if(!Ae){var t=be(Me);Ae=!0;for(var e=ke.length;e;){for(we=ke,ke=[];++Te1)for(var r=1;r=0))return t;if(3===a)i[a]>1&&(i[a]=1);else if(i[a]>=1)return t}var s=Math.round(255*i[0])+", "+Math.round(255*i[1])+", "+Math.round(255*i[2]);return o?"rgba("+s+", "+i[3]+")":"rgb("+s+")"}Re.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},Re.rgb=function(t){return Re.tinyRGB(s(t))},Re.opacity=function(t){return t?s(t).getAlpha():0},Re.addOpacity=function(t,e){var r=s(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},Re.combine=function(t,e){var r=s(t).toRgb();if(1===r.a)return s(t).toRgbString();var n=s(e||Fe).toRgb(),i=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},o={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return s(o).toRgbString()},Re.contrast=function(t,e,r){var n=s(t);return 1!==n.getAlpha()&&(n=s(Re.combine(t,Fe))),(n.isDark()?e?n.lighten(e):Fe:r?n.darken(r):Be).toString()},Re.stroke=function(t,e){var r=s(e);t.style({stroke:Re.tinyRGB(r),"stroke-opacity":r.getAlpha()})},Re.fill=function(t,e){var r=s(e);t.style({fill:Re.tinyRGB(r),"fill-opacity":r.getAlpha()})},Re.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,o=Object.keys(t);for(e=0;e=0,d=r.indexOf("end")>=0,y=u.backoff*p+n.standoff,m=c.backoff*h+n.startstandoff;if("line"===l.nodeName){i={x:+e.attr("x1"),y:+e.attr("y1")},o={x:+e.attr("x2"),y:+e.attr("y2")};var g=i.x-o.x,v=i.y-o.y;if(s=(a=Math.atan2(v,g))+Math.PI,y&&m&&y+m>Math.sqrt(g*g+v*v))return void z();if(y){if(y*y>g*g+v*v)return void z();var _=y*Math.cos(a),x=y*Math.sin(a);o.x+=_,o.y+=x,e.attr({x2:o.x,y2:o.y})}if(m){if(m*m>g*g+v*v)return void z();var b=m*Math.cos(a),w=m*Math.sin(a);i.x-=b,i.y-=w,e.attr({x1:i.x,y1:i.y})}}else if("path"===l.nodeName){var k=l.getTotalLength(),A="";if(k0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},We.prototype.on=We.prototype.addListener,We.prototype.once=function(t,e){if(!Ye(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},We.prototype.removeListener=function(t,e){var r,n,i,o;if(!Ye(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=(r=this._events[t]).length,n=-1,r===e||Ye(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Je(r)){for(o=i;o-- >0;)if(r[o]===e||r[o].listener&&r[o].listener===e){n=o;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},We.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(Ye(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},We.prototype.listeners=function(t){return this._events&&this._events[t]?Ye(this._events[t])?[this._events[t]]:this._events[t].slice():[]},We.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(Ye(e))return 1;if(e)return e.length}return 0},We.listenerCount=function(t,e){return t.listenerCount(e)};var $e,Qe=Xe.EventEmitter,tr={init:function(t){if(t._ev instanceof Qe)return t;var e=new Qe,r=new Qe;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var o=t._ev;if(!o)return n;var a=o._events[e];if(!a)return n;"function"==typeof a&&(a=[a]);for(var s=a.pop(),l=0;l4/3-s?a:s},nr.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:re.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:re.constrain(Math.floor(3*e),0,2),Ze[e][t]},nr.unhover=$e.wrapped,nr.unhoverRaw=$e.raw,nr.init=function(t){var e,r,n,i,o,a,s,l,u=t.gd,c=1,p=h.DBLCLICKDELAY,f=t.element;u._mouseDownTime||(u._mouseDownTime=0),f.style.pointerEvents="all",f.onmousedown=y,qe?(f._ontouchstart&&f.removeEventListener("touchstart",f._ontouchstart),f._ontouchstart=y,f.addEventListener("touchstart",y,{passive:!1})):f.ontouchstart=y;var d=t.clampFn||function(t,e,r){return Math.abs(t)p&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,a),!l){var r;try{r=new MouseEvent("click",e)}catch(t){var n=or(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}s.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&P.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},nr.coverSlip=ir;var ar={zauto:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{zmin:void 0,zmax:void 0}},zmin:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},zmax:{valType:"number",dflt:null,editType:"plot",impliedEdits:{zauto:!1}},colorscale:{valType:"colorscale",editType:"calc",impliedEdits:{autocolorscale:!1}},autocolorscale:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{colorscale:void 0}},reversescale:{valType:"boolean",dflt:!1,editType:"calc"},showscale:{valType:"boolean",dflt:!0,editType:"calc"}},sr=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,o=0;i>=0;i--,o++)e=t[i],n[o]=[1-e[0],e[1]];return n},lr=function(t,e,r,n){var i,o;r?(i=re.nestedProperty(t,r).get(),o=re.nestedProperty(t._input,r).get()):(i=t,o=t._input);var a=n+"auto",s=n+"min",u=n+"max",c=i[a],p=i[s],h=i[u],f=i.colorscale;!1===c&&void 0!==p||(p=re.aggNums(Math.min,null,e)),!1===c&&void 0!==h||(h=re.aggNums(Math.max,null,e)),p===h&&(p-=.5,h+=.5),i[s]=p,i[u]=h,o[s]=p,o[u]=h,o[a]=!1!==c||void 0===p&&void 0===h,i.autocolorscale&&(f=p*h<0?l.RdBu:p>=0?l.Reds:l.Blues,o.colorscale=f,i.reversescale&&(f=sr(f)),i.colorscale=f)},ur=re.extendFlat,cr=re.isPlainObject,pr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},hr={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},fr=pr.flags.slice().concat(["clearCalc","fullReplot"]),dr=hr.flags.slice().concat("layoutReplot"),yr={traces:pr,layout:hr,traceFlags:function(){return mr(fr)},layoutFlags:function(){return mr(dr)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i0?Number(l):s;else if("string"!=typeof l)r.dtick=s;else{var u=l.charAt(0),c=l.substr(1);((c=e(c)?Number(c):0)<=0||!("date"===i&&"M"===u&&c===Math.round(c)||"log"===i&&"L"===u||"log"===i&&"D"===u&&(1===c||2===c)))&&(r.dtick=s)}var p="date"===i?re.dateTick0(r.calendar):0,h=n("tick0",p);"date"===i?r.tick0=re.cleanDate(h,p):e(h)&&"D1"!==l&&"D2"!==l?r.tick0=Number(h):r.tick0=p}else{void 0===n("tickvals")?r.tickmode="auto":n("ticktext")}},zr=function(t){return void 0!==l[t]||c(t)},Lr=function(t,r,n,i,o){var a,s=o.prefix,l=o.cLetter,u=s.slice(0,s.length-1),c=s?re.nestedProperty(t,u).get()||{}:t,p=s?re.nestedProperty(r,u).get()||{}:r,h=c[l+"min"],f=c[l+"max"],d=c.colorscale;i(s+l+"auto",!(e(h)&&e(f)&&h","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},Fr={},Nr=Or.LINE_SPACING;function jr(t,e){return t.node().getBoundingClientRect()[e]}var Vr=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;Fr.convertToTspans=function(e,r,n){var i=e.text(),o=!e.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(Vr),a=t.select(e.node().parentNode);if(!a.empty()){var s=e.attr("class")?e.attr("class").split(" ")[0]:"text";return s+="-math",a.selectAll("svg."+s).remove(),a.selectAll("g."+s+"-group").remove(),e.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),o?(r&&r._promises||[]).push(new Promise(function(r){e.style("display","none");var u=parseInt(e.node().style.fontSize,10),c={fontSize:u};!function(e,r,n){var i="math-output-"+re.randstr([],64),o=t.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((a=e,a.replace(qr,"\\lt ").replace(Ur,"\\gt ")));var a;MathJax.Hub.Queue(["Typeset",MathJax.Hub,o.node()],function(){var r=t.select("body").select("#MathJax_SVG_glyphs");if(o.select(".MathJax_SVG").empty()||!o.select("svg").node())re.log("There was an error in the tex syntax.",e),n();else{var i=o.select("svg").node().getBoundingClientRect();n(o.select(".MathJax_SVG"),r,i)}o.remove()})}(o[2],c,function(t,o,c){a.selectAll("svg."+s).remove(),a.selectAll("g."+s+"-group").remove();var p=t&&t.select("svg");if(!p||!p.node())return l(),void r();var h=a.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});h.node().appendChild(p.node()),o&&o.node()&&p.node().insertBefore(o.node().cloneNode(!0),p.node().firstChild),p.attr({class:s,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var f=e.node().style.fill||"black";p.select("g").attr({fill:f,stroke:f});var d=jr(p,"width"),y=jr(p,"height"),m=+e.attr("x")-d*{start:0,middle:.5,end:1}[e.attr("text-anchor")||"start"],g=-(u||jr(e,"height"))/4;"y"===s[0]?(h.attr({transform:"rotate("+[-90,+e.attr("x"),+e.attr("y")]+") translate("+[-d/2,g-y/2]+")"}),p.attr({x:+e.attr("x"),y:+e.attr("y")})):"l"===s[0]?p.attr({x:e.attr("x"),y:g-y/2}):"a"===s[0]?p.attr({x:0,y:g}):p.attr({x:m,y:+e.attr("y")+g-y/2}),n&&n.call(e,h),r(h)})})):l(),e}function l(){a.empty()||(s=e.attr("class")+"-math",a.select("svg."+s).remove()),e.text("").style("white-space","pre"),function(e,r){r=(n=r,function(t,e){if(!t)return"";for(var r=0;r1)for(var o=1;o doesnt match end tag <"+t+">. Pretending it did match.",r),i=a[a.length-1].node}else re.log("Ignoring unexpected end tag .",r)}tn.test(r)?l():(i=e,a=[{node:e}]);for(var h=r.split($r),f=0;f|>|>)/g;var Hr={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"},Zr={sub:"0.3em",sup:"-0.6em"},Gr={sub:"-0.21em",sup:"0.42em"},Wr="\u200b",Xr=["http:","https:","mailto:","",void 0,":"],Yr=new RegExp("]*)?/?>","g"),Jr=Object.keys(Br.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:Br.entityToUnicode[t]}}),Kr=/(\r\n?|\n)/g,$r=/(<[^<>]*>)/,Qr=/<(\/?)([^ >]*)(\s+(.*))?>/i,tn=//i,en=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,rn=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,nn=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,on=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function an(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var sn=/(^|;)\s*color:/;function ln(t,e,r){var n,i,o,a=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},o="right"===a?function(){return l.right-n.width}:"center"===a?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:o()-u.left+"px","z-index":1e3}),this}}Fr.plainText=function(t){return(t||"").replace(Yr," ")},Fr.lineCount=function(t){return t.selectAll("tspan.line").size()||1},Fr.positionText=function(e,r,n){return e.each(function(){var e=t.select(this);function i(t,r){return void 0===r?null===(r=e.attr(t))&&(e.attr(t,0),r=0):e.attr(t,r),r}var o=i("x",r),a=i("y",n);"text"===this.nodeName&&e.selectAll("tspan.line").attr({x:o,y:a})})},Fr.makeEditable=function(e,r){var n=r.gd,i=r.delegate,o=t.dispatch("edit","input","cancel"),a=i||e;if(e.style({"pointer-events":i?"none":"all"}),1!==e.size())throw new Error("boo");function s(){var i,s,u,c;i=t.select(n).select(".svg-container"),s=i.append("div"),u=e.node().style,c=parseFloat(u.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:r.fill||u.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||e.attr("data-unformatted")).call(ln(e,i,r)).on("blur",function(){n._editing=!1,e.text(this.textContent).style({opacity:1});var r,i=t.select(this).attr("class");(r=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(r).style({opacity:0});var a=this.textContent;t.select(this).transition().duration(0).remove(),t.select(document).on("mouseup",null),o.edit.call(e,a)}).on("focus",function(){var e=this;n._editing=!0,t.select(document).on("mouseup",function(){if(t.event.target===e)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===t.event.which?(n._editing=!1,e.style({opacity:1}),t.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),o.cancel.call(e,this.textContent)):(o.input.call(e,this.textContent),t.select(this).call(ln(e,i,r)))}).on("keydown",function(){13===t.event.which&&this.blur()}).call(l),e.style({opacity:0});var p,h=a.attr("class");(p=h?"."+h.split(" ")[0]+"-math-group":"[class*=-math-group]")&&t.select(e.node().parentNode).select(p).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return r.immediate?s():a.on("click",s),t.rebind(e,o,"on")};var un=function(t){var r=t.marker,n=r.sizeref||1,i=r.sizemin||0,o="area"===r.sizemode?function(t){return Math.sqrt(t/n)}:function(t){return t/n};return function(t){var r=o(t/2);return e(r)&&r>0?Math.max(r,i):0}},cn={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return re.isPlainObject(t.marker)&&re.isArrayOrTypedArray(t.marker.size)}},pn={},hn=Or.LINE_SPACING,fn=h.DESELECTDIM,dn=pn={};dn.font=function(t,e,r,n){re.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Oe.fill,n)},dn.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},dn.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},dn.setRect=function(t,e,r,n,i){t.call(dn.setPosition,e,r).call(dn.setSize,n,i)},dn.translatePoint=function(t,r,n,i){var o=n.c2p(t.x),a=i.c2p(t.y);return!!(e(o)&&e(a)&&r.node())&&("text"===r.node().nodeName?r.attr("x",o).attr("y",a):r.attr("transform","translate("+o+","+a+")"),!0)},dn.translatePoints=function(e,r,n){e.each(function(e){var i=t.select(this);dn.translatePoint(e,i,r,n)})},dn.hideOutsideRangePoint=function(t,e,r,n,i,o){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,o)?null:"none")},dn.hideOutsideRangePoints=function(e,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var i=r.xaxis,o=r.yaxis;e.each(function(r){var a=r[0].trace,s=a.xcalendar,l=a.ycalendar;e.selectAll(n).each(function(e){dn.hideOutsideRangePoint(e,t.select(this),i,o,s,l)})})}},dn.crispRound=function(t,r,n){return r&&e(r)?t._context.staticPlot?r:r<1?1:Math.round(r):n||0},dn.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var o=(((t||[])[0]||{}).trace||{}).line||{},a=r||o.width||0,s=i||o.dash||"";Oe.stroke(e,n||o.color),dn.dashLine(e,s,a)},dn.lineGroupStyle=function(e,r,n,i){e.style("fill","none").each(function(e){var o=(((e||[])[0]||{}).trace||{}).line||{},a=r||o.width||0,s=i||o.dash||"";t.select(this).call(Oe.stroke,n||o.color).call(dn.dashLine,s,a)})},dn.dashLine=function(t,e,r){r=+r||0,e=dn.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},dn.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},dn.singleFillStyle=function(e){var r=(((t.select(e.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&e.call(Oe.fill,r)},dn.fillGroupStyle=function(e){e.style("stroke-width",0).each(function(r){var n=t.select(this);try{n.call(Oe.fill,r[0].trace.fillcolor)}catch(t){re.error(t,e),n.remove()}})},dn.symbolNames=[],dn.symbolFuncs=[],dn.symbolNeedLines={},dn.symbolNoDot={},dn.symbolNoFill={},dn.symbolList=[],Object.keys(Dr).forEach(function(t){var e=Dr[t];dn.symbolList=dn.symbolList.concat([e.n,t,e.n+100,t+"-open"]),dn.symbolNames[e.n]=t,dn.symbolFuncs[e.n]=e.f,e.needLine&&(dn.symbolNeedLines[e.n]=!0),e.noDot?dn.symbolNoDot[e.n]=!0:dn.symbolList=dn.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(dn.symbolNoFill[e.n]=!0)});var yn=dn.symbolNames.length,mn="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function gn(t,e){var r=t%100;return dn.symbolFuncs[r](e)+(t>=200?mn:"")}dn.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=dn.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=yn||t>=400?0:Math.floor(Math.max(t,0))};var vn={x1:1,x2:0,y1:0,y2:0},_n={x1:0,x2:0,y1:1,y2:0};dn.gradient=function(e,r,n,i,o,a){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([i+o+a],re.identity);l.exit().remove(),l.enter().append("radial"===i?"radialGradient":"linearGradient").each(function(){var e=t.select(this);"horizontal"===i?e.attr(vn):"vertical"===i&&e.attr(_n),e.attr("id",n);var r=s(o),l=s(a);e.append("stop").attr({offset:"0%","stop-color":Oe.tinyRGB(l),"stop-opacity":l.getAlpha()}),e.append("stop").attr({offset:"100%","stop-color":Oe.tinyRGB(r),"stop-opacity":r.getAlpha()})}),e.style({fill:"url(#"+n+")","fill-opacity":null})},dn.initGradients=function(t){re.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},dn.singlePointStyle=function(t,e,r,n,i,o){var a=r.marker;!function(t,e,r,n,i,o,a,s){if(P.traceIs(r,"symbols")){var l=un(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===o.size?3:cn.isBubble(r)?l(t.ms):(o.size||6)/2,t.mrc=e;var n=dn.symbolNumber(t.mx||o.symbol)||0;return t.om=n%200>=100,gn(n,e)})}e.style("opacity",function(t){return(t.mo+1||o.opacity+1)-1});var u,c,p,h=!1;if(t.so?(p=a.outlierwidth,c=a.outliercolor,u=o.outliercolor):(p=(t.mlw+1||a.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=i(t.mlc):re.isArrayOrTypedArray(a.color)?Oe.defaultLine:a.color,re.isArrayOrTypedArray(o.color)&&(u=Oe.defaultLine,h=!0),u="mc"in t?t.mcc=n(t.mc):o.color||"rgba(0,0,0,0)"),t.om)e.call(Oe.stroke,u).style({"stroke-width":(p||1)+"px",fill:"none"});else{e.style("stroke-width",p+"px");var f=o.gradient,d=t.mgt;if(d?h=!0:d=f&&f.type,d&&"none"!==d){var y=t.mgc;y?h=!0:y=f.color;var m="g"+s._fullLayout._uid+"-"+r.uid;h&&(m+="-"+t.i),e.call(dn.gradient,s,m,d,u,y)}else e.call(Oe.fill,u);p&&e.call(Oe.stroke,c)}}(t,e,r,n,i,a,a.line,o)},dn.pointStyle=function(e,r,n){if(e.size()){var i=r.marker,o=dn.tryColorscale(i,""),a=dn.tryColorscale(i,"line");e.each(function(e){dn.singlePointStyle(e,t.select(this),r,o,a,n)})}},dn.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},o=r.marker||{},a=n.marker||{},s=i.opacity,l=o.opacity,u=a.opacity,c=void 0!==l,p=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||p){if(!t.selected)return p?u:fn*(r?e:s);if(c)return l}};var h=o.color,f=a.color;(h||f)&&(e.colorFn=function(t){if(t.selected){if(h)return h}else if(f)return f});var d=o.size,y=a.size,m=void 0!==d,g=void 0!==y;return(m||g)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?m?d/2:e:g?y/2:e}),e},dn.selectedPointStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=dn.makeSelectedPointStyleFns(r),i=r.marker||{};e.each(function(e){var r=t.select(this),i=n.opacityFn(e);void 0!==i&&r.style("opacity",i)}),n.colorFn&&e.each(function(e){var r=t.select(this),i=n.colorFn(e);i&&Oe.fill(r,i)}),P.traceIs(r,"symbols")&&n.sizeFn&&e.each(function(e){var r=t.select(this),o=e.mx||i.symbol||0,a=n.sizeFn(e);r.attr("d",gn(dn.symbolNumber(o),a)),e.mrc2=a})}},dn.tryColorscale=function(t,e){var r=e?re.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&re.isArrayOrTypedArray(i)?Ir.makeColorScaleFunc(Ir.extractScale(n,r.cmin,r.cmax)):re.identity};var xn={start:1,end:-1,middle:0,bottom:1,top:-1};function bn(e,r,n,i){var o=t.select(e.node().parentNode),a=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",s=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",l=i?i/.8+1:0,u=(Fr.lineCount(e)-1)*hn+1,c=xn[s]*l,p=.75*n+xn[a]*l+(xn[a]-1)*u*n/2;e.attr("text-anchor",s),o.attr("transform","translate("+c+","+p+")")}function wn(t,r){var n=t.ts||r.textfont.size;return e(n)&&n>0?n:0}dn.textPointStyle=function(e,r,n){e.each(function(e){var i=t.select(this),o=re.extractOption(e,r,"tx","text");if(o){var a=e.tp||r.textposition,s=wn(e,r);i.call(dn.font,e.tf||r.textfont.family,s,e.tc||r.textfont.color).text(o).call(Fr.convertToTspans,n).call(bn,a,s,e.mrc)}else i.remove()})},dn.selectedTextStyle=function(e,r){if(e.size()&&r.selectedpoints){var n=r.selected||{},i=r.unselected||{};e.each(function(e){var o,a=t.select(this),s=e.tc||r.textfont.color,l=e.tp||r.textposition,u=wn(e,r),c=(n.textfont||{}).color,p=(i.textfont||{}).color;e.selected?c&&(o=c):p?o=p:c||(o=Oe.addOpacity(s,fn)),o&&Oe.fill(a,o),bn(a,l,u,e.mrc2||e.mrc)})}};var kn=.5;function An(e,r,n,i){var o=e[0]-r[0],a=e[1]-r[1],s=n[0]-r[0],l=n[1]-r[1],u=Math.pow(o*o+a*a,kn/2),c=Math.pow(s*s+l*l,kn/2),p=(c*c*o-u*u*s)*i,h=(c*c*a-u*u*l)*i,f=3*c*(u+c),d=3*u*(u+c);return[[t.round(r[0]+(f&&p/f),2),t.round(r[1]+(f&&h/f),2)],[t.round(r[0]-(d&&p/d),2),t.round(r[1]-(d&&h/d),2)]]}dn.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(dn.savedBBoxes={},Sn=0),n&&(dn.savedBBoxes[n]=d),Sn++,re.extendFlat({},d)},dn.setClipUrl=function(e,r){if(r){if(void 0===dn.baseUrl){var n=t.select("base");n.size()&&n.attr("href")?dn.baseUrl=window.location.href.split("#")[0]:dn.baseUrl=""}e.attr("clip-path","url("+dn.baseUrl+"#"+r+")")}else e.attr("clip-path",null)},dn.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},dn.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",o=t[n]("transform")||"";return e=e||0,r=r||0,o=o.replace(/(\btranslate\(.*?\);?)/,"").trim(),o=(o+=" translate("+e+", "+r+")").trim(),t[i]("transform",o),o},dn.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},dn.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",o=t[n]("transform")||"";return e=e||1,r=r||1,o=o.replace(/(\bscale\(.*?\);?)/,"").trim(),o=(o+=" scale("+e+", "+r+")").trim(),t[i]("transform",o),o},dn.setPointGroupScale=function(t,e,r){var n,i,o;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",o=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(o,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var zn=/translate\([^)]*\)\s*$/;dn.setTextPointsScale=function(e,r,n){e.each(function(){var e,i=t.select(this),o=i.select("text");if(o.node()){var a=parseFloat(o.attr("x")||0),s=parseFloat(o.attr("y")||0),l=(i.attr("transform")||"").match(zn);e=1===r&&1===n?[]:["translate("+a+","+s+")","scale("+r+","+n+")","translate("+-a+","+-s+")"],l&&e.push(l),i.attr("transform",e.join(" "))}})};function Ln(t,e,r,n){n=n||re.identity,Array.isArray(t)&&(e[0][r]=n(t))}var En={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},isTraceInSubplots:function(t,e){if("splom"===t.type){for(var r=t.xaxes||[],n=t.yaxes||[],i=0;i=0&&r.index=o.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var a=e[r];if(!si(a))return!1;t=o[i][a]}else t=o[i]}else t=o}}return t}function si(t){return t===Math.round(t)&&t>=0}function li(t){return function(t){Qn.crawl(t,function(t,e,r){Qn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):ri(t)&&(t.role="object")})}(t),function(t){Qn.crawl(t,function(t,e,r){if(!t)return;var n=t[ii];if(!n)return;delete t[ii],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(ri(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n=a.length)return!1;n=(r=(P.transformsRegistry[a[s].type]||{}).attributes)&&r[e[2]],o=3}else if("area"===t.type)n=Wn[i];else{var l=t._module;if(l||(l=(P.modules[t.type||C.type.dflt]||{})._module),!l)return!1;if(!(n=(r=l.attributes)&&r[i])){var u=l.basePlotModule;u&&u.attributes&&(n=u.attributes[i])}n||(n=C[i])}return ai(n,e,o)},Qn.getLayoutValObject=function(t,e){return ai(function(t,e){var r,n,i,o,a=t._basePlotModules;if(a){var s;for(r=0;rn?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},hi={};function fi(t,e,r){var n,i,o,a=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=re.nestedProperty(n,e.prop).get(),(o=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&o[e.prop]!==i&&(a=!0),o[e.prop]=i,{changed:a,value:i}}function di(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!re.isPlainObject(n))return r;i=n}return mi(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function yi(t,e){var r,n,i,o,a=[];if(n=e[0],i=e[1],r=e[2],o={},"string"==typeof n)o[n]=i;else{if(!re.isPlainObject(n))return a;o=n,void 0===r&&(r=i)}return void 0===r&&(r=null),mi(o,function(e,n,i){var o;if(Array.isArray(i)){var s=Math.min(i.length,t.data.length);r&&(s=Math.min(s,r.length)),o=[];for(var l=0;l0?".":"")+i;re.isPlainObject(o)?mi(o,e,a,n+1):e(a,i,o)}})}function gi(t,e){return"splom"===t?-1:"splom"===e?1:0}hi.manageCommandObserver=function(t,e,r,n){var i={},o=!0;e&&e._commandObserver&&(i=e._commandObserver),i.cache||(i.cache={}),i.lookupTable={};var a=hi.hasSimpleAPICommandBindings(t,r,i.lookupTable);if(e&&e._commandObserver){if(a)return i;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,i}if(a){fi(t,a,i.cache),i.check=function(){if(o){var e=fi(t,a,i.cache);return e.changed&&n&&void 0!==i.lookupTable[e.value]&&(i.disable(),Promise.resolve(n({value:e.value,type:a.type,prop:a.prop,traces:a.traces,index:i.lookupTable[e.value]})).then(i.enable,i.enable)),e.changed}};for(var s=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],l=0;l=r.width-20?(o["text-anchor"]="start",o.x=5):(o["text-anchor"]="end",o.x=r._paper.attr("width")-7),n.attr(o);var a=n.select(".js-link-to-tool"),s=n.select(".js-link-spacer"),l=n.select(".js-sourcelinks");e._context.showSources&&e._context.showSources(e),e._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){Ai.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(e,a),s.text(a.text()&&l.text()?" - ":"")}},Ai.sendDataToCloud=function(e){e.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=t.select(e).append("div").attr("id","hiddenform").style("display","none"),i=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=Ai.graphJson(e,!1,"keepdata"),i.node().submit(),n.remove(),e.emit("plotly_afterexport"),!1};var Mi,Si=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Ci=["year","month","dayMonth","dayMonthYear"];function zi(t,e){var r,n,i=t.trace,o=i._arrayAttrs,a={};for(r=0;r1&&b.length>1){for(P.getComponentMethod("grid","sizeDefaults")(o,i),n=0;n15&&b.length>15&&0===i.shapes.length&&0===i.images.length,i._hasCartesian=i._has("cartesian"),i._hasGeo=i._has("geo"),i._hasGL3D=i._has("gl3d"),i._hasGL2D=i._has("gl2d"),i._hasTernary=i._has("ternary"),i._hasPie=i._has("pie"),Ai.cleanPlot(s,i,a,r,u),Ai.linkSubplots(s,i,a,r),wi(i,r),Ai.doAutoMargin(e);var T=pi.list(e);for(n=0;n0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,p=u.bottom+u.top,h=1-2*s,f=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};i=Math.round(h*(f.width-c)),o=Math.round(h*(f.height-p))}else{var d=l?window.getComputedStyle(t):{};i=parseFloat(d.width)||n.width,o=parseFloat(d.height)||n.height}var y=Ai.layoutAttributes.width.min,m=Ai.layoutAttributes.height.min;i1,v=!r.height&&Math.abs(n.height-o)>1;(v||g)&&(g&&(n.width=i),v&&(n.height=o)),t._initialAutoSize||(t._initialAutoSize={width:i,height:o}),Ai.sanitizeMargins(n)},Ai.supplyLayoutModuleDefaults=function(t,e,r,n){var i,o,a,s=P.componentsRegistry,l=e._basePlotModules,u=P.subplotsRegistry.cartesian;for(i in s)(a=s[i]).includeBasePlot&&a.includeBasePlot(t,e);for(var c in l.length||l.push(u),e._has("cartesian")&&(P.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(re.subplotSort);for(o=0;o.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||Ai.doAutoMargin(t)}},Ai.doAutoMargin=function(t){var r=t._fullLayout;r._size||(r._size={}),r._pushmargin||(r._pushmargin={});var n=r._size,i=JSON.stringify(n),o=Math.max(r.margin.l||0,0),a=Math.max(r.margin.r||0,0),s=Math.max(r.margin.t||0,0),l=Math.max(r.margin.b||0,0),u=r._pushmargin;if(!1!==r.margin.autoexpand)for(var c in u.base={l:{val:0,size:o},r:{val:1,size:a},t:{val:1,size:s},b:{val:0,size:l}},u){var p=u[c].l||{},h=u[c].b||{},f=p.val,d=p.size,y=h.val,m=h.size;for(var g in u){if(e(d)&&u[g].r){var v=u[g].r.val,_=u[g].r.size;if(v>f){var x=(d*v+(_-r.width)*f)/(v-f),b=(_*(1-f)+(d-r.width)*(1-v))/(v-f);x>=0&&b>=0&&x+b>o+a&&(o=x,a=b)}}if(e(m)&&u[g].t){var w=u[g].t.val,k=u[g].t.size;if(w>y){var A=(m*w+(k-r.height)*y)/(w-y),T=(k*(1-y)+(m-r.height)*(1-w))/(w-y);A>=0&&T>=0&&A+T>l+s&&(l=A,s=T)}}}}if(n.l=Math.round(o),n.r=Math.round(a),n.t=Math.round(s),n.b=Math.round(l),n.p=Math.round(r.margin.pad),n.w=Math.round(r.width)-n.l-n.r,n.h=Math.round(r.height)-n.t-n.b,!r._replotting&&"{}"!==i&&i!==JSON.stringify(r._size))return P.call("plot",t)},Ai.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&Ai.supplyDefaults(t);var o=i?t._fullData:t.data,a=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(re.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!re.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):re.isJSDate(t)?re.ms2DateTimeLocal(+t):t}var u={data:(o||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(a)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},Ai.modifyFrames=function(t,e){var r,n,i,o=t._transitionData._frames,a=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){p=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return P.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,a,s=0,l=0;function u(){return s++,function(){var r;p||++l!==s||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return P.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var h=t._fullLayout._basePlotModules,f=!1;if(r)for(a=0;a=0;o--)if(l[o].enabled){r._indexToPoints=l[o]._indexToPoints;break}n&&n.calc&&(a=n.calc(t,r))}Array.isArray(a)&&a[0]||(a=[{x:xi,y:xi}]),a[0].t||(a[0].t={}),a[0].trace=r,u[e]=a}}for(h&&Pi(a),i=0;i0||p<0){var d={left:[-i,0],right:[i,0],top:[0,-i],bottom:[0,i]}[c.side];n.attr("transform","translate("+d+")")}}}T.call(M),k&&(w?T.on(".opacity",null):(x=0,b=!0,T.text(l).on("mouseover.opacity",function(){t.select(this).transition().duration(h.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){t.select(this).transition().duration(h.HIDE_PLACEHOLDER).style("opacity",0)})),T.call(Fr.makeEditable,{gd:r}).on("edit",function(t){void 0!==u?P.call("restyle",r,s,t,u):P.call("relayout",r,s,t)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(M)}).on("input",function(t){this.text(t||" ").call(Fr.positionText,p.x,p.y)}));return T.classed("js-placeholder",b),d}},Di=/ [XY][0-9]* /;var Oi=r.FP_SAFE,Ri=ji,Bi=Vi,Fi=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=ji(t),t._r=t.range.slice(),t._rl=re.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?ji(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=re.extendFlat({},n)}},Ni=function(t,r,n){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!r)return;t._min||(t._min=[]);t._max||(t._max=[]);n||(n={});t._m||t.setScale();var i,o,a,s,l,u,c,p,h,f,d,y,m=r.length,g=n.padded||!1,v=n.tozero&&("linear"===t.type||"-"===t.type),_="log"===t.type,x=!1;function b(t){if(Array.isArray(t))return x=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=b((t._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),k=b((t._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),A=b(n.vpadplus||n.vpad),T=b(n.vpadminus||n.vpad);if(!x){if(d=1/0,y=-1/0,_)for(i=0;i0&&(d=s),s>y&&s-Oi&&(d=s),s>y&&s=x&&(s.extrapad||!g)){f=!1;break}b(i,s.val)&&s.pad<=x&&(g||!s.extrapad)&&(m.splice(o,1),o--)}if(f){var M=v&&0===i;m.push({val:i,pad:M?0:x,extrapad:!M&&g})}}}}var S=Math.min(6,m);for(i=0;i=S;i--)M(i)};function ji(t){var e,r,n,i,o,a,s,l,u=[],c=t._min[0].val,p=t._max[0].val,h=0,f=!1,d=Vi(t);for(e=1;e0&&s>0&&l/s>h&&(o=n,a=i,h=l/s);if(c===p){var m=c-1,g=c+1;u="tozero"===t.rangemode?c<0?[m,0]:[0,g]:"nonnegative"===t.rangemode?[Math.max(0,m),Math.max(0,g)]:[m,g]}else h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(o.val>=0&&(o={val:0,pad:0}),a.val<=0&&(a={val:0,pad:0})):"nonnegative"===t.rangemode&&(o.val-h*d(o)<0&&(o={val:0,pad:0}),a.val<0&&(a={val:1,pad:0})),h=(a.val-o.val)/(t._length-d(o)-d(a))),u=[o.val-h*d(o),a.val+h*d(a)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),f&&u.reverse(),re.simpleMap(u,t.l2r||Number)}function Vi(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function qi(t){return e(t)&&Math.abs(t)=e}var Zi=r.BADNUM,Gi=function(t,r){return function(t,r){for(var n,i=0,o=0,a=Math.max(1,(t.length-1)/1e3),s=0;s2*o}(t,r)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,o=0;o2*n}(t)?"category":function(t){if(!t)return!1;for(var r=0;r0)return Math.log(t)/Math.LN10;if(t<=0&&e&&r.range&&2===r.range.length){var n=r.range[0],i=r.range[1];return.5*(n+i-3*o*Math.abs(n-i))}return $i}function s(t,n,i){var o=Yi(t,i||r.calendar);if(o===$i){if(!e(t))return $i;o=Yi(new Date(+t))}return o}function l(t,e,n){return Xi(t,e,n||r.calendar)}function u(t){return r._categories[Math.round(t)]}function c(t){if(r._categoriesMap){var n=r._categoriesMap[t];if(void 0!==n)return n}if(e(t))return+t}function p(n){return e(n)?t.round(r._b+r._m*n,2):$i}function h(t){return(t-r._b)/r._m}r.c2l="log"===r.type?a:Ji,r.l2c="log"===r.type?Qi:Ji,r.l2p=p,r.p2l=h,r.c2p="log"===r.type?function(t,e){return p(a(t,e))}:p,r.p2c="log"===r.type?function(t){return Qi(h(t))}:h,-1!==["linear","-"].indexOf(r.type)?(r.d2r=r.r2d=r.d2c=r.r2c=r.d2l=r.r2l=Wi,r.c2d=r.c2r=r.l2d=r.l2r=Ji,r.d2p=r.r2p=function(t){return r.l2p(Wi(t))},r.p2d=r.p2r=h,r.cleanPos=Ji):"log"===r.type?(r.d2r=r.d2l=function(t,e){return a(Wi(t),e)},r.r2d=r.r2c=function(t){return Qi(Wi(t))},r.d2c=r.r2l=Wi,r.c2d=r.l2r=Ji,r.c2r=a,r.l2d=Qi,r.d2p=function(t,e){return r.l2p(r.d2r(t,e))},r.p2d=function(t){return Qi(h(t))},r.r2p=function(t){return r.l2p(Wi(t))},r.p2r=h,r.cleanPos=Ji):"date"===r.type?(r.d2r=r.r2d=re.identity,r.d2c=r.r2c=r.d2l=r.r2l=s,r.c2d=r.c2r=r.l2d=r.l2r=l,r.d2p=r.r2p=function(t,e,n){return r.l2p(s(t,0,n))},r.p2d=r.p2r=function(t,e,r){return l(h(t),e,r)},r.cleanPos=function(t){return re.cleanDate(t,$i,r.calendar)}):"category"===r.type&&(r.d2c=r.d2l=function(t){if(null!==t&&void 0!==t){if(void 0===r._categoriesMap&&(r._categoriesMap={}),void 0!==r._categoriesMap[t])return r._categoriesMap[t];r._categories.push(t);var e=r._categories.length-1;return r._categoriesMap[t]=e,e}return $i},r.r2d=r.c2d=r.l2d=u,r.d2r=r.d2l_noadd=c,r.r2c=function(t){var e=c(t);return void 0!==e?e:r.fraction2r(.5)},r.l2r=r.c2r=Ji,r.r2l=c,r.d2p=function(t){return r.l2p(r.r2c(t))},r.p2d=function(t){return u(h(t))},r.r2p=r.d2p,r.p2r=h,r.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Ji(t)}),r.fraction2r=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return r.l2r(e+t*(n-e))},r.r2fraction=function(t){var e=r.r2l(r.range[0]),n=r.r2l(r.range[1]);return(r.r2l(t)-e)/(n-e)},r.cleanRange=function(t,n){n||(n={}),t||(t="range");var o,a,s=re.nestedProperty(r,t).get();if(a=(a="date"===r.type?re.dfltRange(r.calendar):"y"===i?Ie.DFLTRANGEY:n.dfltRange||Ie.DFLTRANGEX).slice(),s&&2===s.length)for("date"===r.type&&(s[0]=re.cleanDate(s[0],$i,r.calendar),s[1]=re.cleanDate(s[1],$i,r.calendar)),o=0;o<2;o++)if("date"===r.type){if(!re.isDateTime(s[o],r.calendar)){r[t]=a;break}if(r.r2l(s[0])===r.r2l(s[1])){var l=re.constrain(r.r2l(s[0]),re.MIN_MS+1e3,re.MAX_MS-1e3);s[0]=r.l2r(l-1e3),s[1]=r.l2r(l+1e3);break}}else{if(!e(s[o])){if(!e(s[1-o])){r[t]=a;break}s[o]=s[1-o]*(o?10:.1)}if(s[o]<-Ki?s[o]=-Ki:s[o]>Ki&&(s[o]=Ki),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else re.nestedProperty(r,t).set(a)},r.setScale=function(t){var e=n._size;if(r._categories||(r._categories=[]),r._categoriesMap||(r._categoriesMap={}),r.overlaying){var o=pi.getFromId({_fullLayout:n},r.overlaying);r.domain=o.domain}var a=t&&r._r?"_r":"range",s=r.calendar;r.cleanRange(a);var l=r.r2l(r[a][0],s),u=r.r2l(r[a][1],s);if("y"===i?(r._offset=e.t+(1-r.domain[1])*e.h,r._length=e.h*(r.domain[1]-r.domain[0]),r._m=r._length/(l-u),r._b=-r._m*u):(r._offset=e.l+r.domain[0]*e.w,r._length=e.w*(r.domain[1]-r.domain[0]),r._m=r._length/(u-l),r._b=-r._m*l),!isFinite(r._m)||!isFinite(r._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},r.makeCalcdata=function(t,e){var n,i,o,a,s=r.type,l="date"===s&&t[e+"calendar"];if(e in t){if(n=t[e],a=t._length||n.length,re.isTypedArray(n)&&("linear"===s||"log"===s)){if(a===n.length)return n;if(n.subarray)return n.subarray(0,a)}for(i=new Array(a),o=0;o2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},ho.saveRangeInitial=function(t,e){for(var r=ho.list(t,"",!0),n=!1,i=0;i.3*h||c(i)||c(o))){var f=n.dtick/2;t+=t+f.8){var a=Number(r.substr(1));o.exactYears>.8&&a%12==0?t=ho.tickIncrement(t,"M6","reverse")+1.5*io:o.exactMonths>.8?t=ho.tickIncrement(t,"M1","reverse")+15.5*io:t-=io/2;var s=ho.tickIncrement(t,r);if(s<=n)return s}return t}(d,t,s.dtick,l,o)),f=d,0;f<=u;)f=ho.tickIncrement(f,s.dtick,!1,o),0;return{start:r.c2r(d,0,o),end:r.c2r(f,0,o),size:s.dtick,_dataSpan:u-l}},ho.prepTicks=function(t){var e=re.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=re.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),ho.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),To(t)},ho.calcTicks=function(t){ho.prepTicks(t);var e=re.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,o=new Array(n.length),a=re.simpleMap(t.range,t.r2l),s=1.0001*a[0]-1e-4*a[1],l=1.0001*a[1]-1e-4*a[0],u=Math.min(s,l),c=Math.max(s,l),p=0;Array.isArray(i)||(i=[]);var h="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:l<=n)&&!(o.length>s||l===a);l=ho.tickIncrement(l,t.dtick,i,t.calendar))a=l,o.push(l);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&o.pop(),t._tmax=o[o.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(o.length),c=0;c10||"01-01"!==i.substr(5)?t._tickround="d":t._tickround=+r.substr(1)%12==0?"y":"m";else if(r>=io&&o<=10||r>=15*io)t._tickround="d";else if(r>=ao&&o<=16||r>=oo)t._tickround="M";else if(r>=so&&o<=19||r>=ao)t._tickround="S";else{var a=t.l2r(n+r).replace(/^-/,"").length;t._tickround=Math.max(o,a)-20}}else if(e(r)||"L"===r.charAt(0)){var s=t.range.map(t.r2d||Number);e(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),u=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(u)>3&&(Co(t.exponentformat)&&!zo(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function Mo(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}ho.autoTicks=function(t,r){var n;function i(t){return Math.pow(t,Math.floor(Math.log(r)/Math.LN10))}if("date"===t.type){t.tick0=re.dateTick0(t.calendar);var o=2*r;o>ro?(r/=ro,n=i(10),t.dtick="M"+12*Ao(r,n,go)):o>no?(r/=no,t.dtick="M"+Ao(r,1,vo)):o>io?(t.dtick=Ao(r,io,xo),t.tick0=re.dateTick0(t.calendar,!0)):o>oo?t.dtick=Ao(r,oo,vo):o>ao?t.dtick=Ao(r,ao,_o):o>so?t.dtick=Ao(r,so,_o):(n=i(10),t.dtick=Ao(r,n,go))}else if("log"===t.type){t.tick0=0;var a=re.simpleMap(t.range,t.r2l);if(r>.7)t.dtick=Math.ceil(r);else if(Math.abs(a[1]-a[0])<1){var s=1.5*Math.abs((a[1]-a[0])/r);r=Math.abs(Math.pow(10,a[1])-Math.pow(10,a[0]))/s,n=i(10),t.dtick="L"+Ao(r,n,go)}else t.dtick=r>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(r,1))):"angular"===t._id?(t.tick0=0,n=1,t.dtick=Ao(r,n,ko)):(t.tick0=0,n=i(10),t.dtick=Ao(r,n,go));if(0===t.dtick&&(t.dtick=1),!e(t.dtick)&&"string"!=typeof t.dtick){var l=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(l)}},ho.tickIncrement=function(r,n,i,o){var a=i?-1:1;if(e(n))return r+a*n;var s=n.charAt(0),l=a*Number(n.substr(1));if("M"===s)return re.incrementMonth(r,l,o);if("L"===s)return Math.log(Math.pow(10,r)+l)/Math.LN10;if("D"===s){var u="D2"===n?wo:bo,c=r+.01*a,p=re.roundUp(re.mod(c,1),u,i);return Math.floor(c)+Math.log(t.round(Math.pow(10,p),1))/Math.LN10}throw"unrecognized dtick "+String(n)},ho.tickFirst=function(r){var n=r.r2l||Number,i=re.simpleMap(r.range,n),o=i[1]"+s,t._prevDateHead=s));r.text=l}(t,a,n,l):"log"===t.type?function(t,r,n,i,o){var a=t.dtick,s=r.x,l=t.tickformat;"never"===o&&(o="");!i||"string"==typeof a&&"L"===a.charAt(0)||(a="L3");if(l||"string"==typeof a&&"L"===a.charAt(0))r.text=Lo(Math.pow(10,s),t,o,i);else if(e(a)||"D"===a.charAt(0)&&re.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||Co(t.exponentformat)&&zo(u)?(r.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+lo+-u+"",r.fontSize*=1.25):(r.text=Lo(Math.pow(10,s),t,"","fakehover"),"D1"===a&&"y"===t._id.charAt(0)&&(r.dy-=r.fontSize/6))}else{if("D"!==a.charAt(0))throw"unrecognized dtick "+String(a);r.text=String(Math.round(Math.pow(10,re.mod(s,1)))),r.fontSize*=.75}if("D1"===t.dtick){var c=String(r.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?r.dx-=r.fontSize/4:(r.dy+=r.fontSize/2,r.dx+=(t.range[1]>t.range[0]?1:-1)*r.fontSize*(s<0?.5:.25)))}}(t,a,0,l,i):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,a):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=Lo(e.x,t,i,n);else{var o=e.x/180;if(0===o)e.text="0";else{var a=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(o);if(a[1]>=100)e.text=Lo(re.deg2rad(e.x),t,i,n);else{var s=e.x<0;1===a[1]?1===a[0]?e.text="\u03c0":e.text=a[0]+"\u03c0":e.text=["",a[0],"","\u2044","",a[1],"","\u03c0"].join(""),s&&(e.text=lo+e.text)}}}}(t,a,n,l,i):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=Lo(e.x,t,i,n)}(t,a,0,l,i),t.tickprefix&&!h(t.showtickprefix)&&(a.text=t.tickprefix+a.text),t.ticksuffix&&!h(t.showticksuffix)&&(a.text+=t.ticksuffix),a},ho.hoverLabelText=function(t,e,r){if(r!==uo&&r!==e)return ho.hoverLabelText(t,e)+" - "+ho.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=ho.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":lo+i:i};var So=["f","p","n","\u03bc","m","","k","M","G","T"];function Co(t){return"SI"===t||"B"===t}function zo(t){return t>14||t<-15}function Lo(t,r,n,i){var o=t<0,a=r._tickround,s=n||r.exponentformat||"B",l=r._tickexponent,u=ho.getTickFormat(r),c=r.separatethousands;if(i){var p={exponentformat:s,dtick:"none"===r.showexponent?r.dtick:e(t)&&Math.abs(t)||1,range:"none"===r.showexponent?r.range.map(r.r2d):[0,t||1]};To(p),a=(Number(p._tickround)||0)+4,l=p._tickexponent,r.hoverformat&&(u=r.hoverformat)}if(u)return r._numFormat(u)(t).replace(/-/g,lo);var h,f=Math.pow(10,-a)/2;if("none"===s&&(l=0),(t=Math.abs(t))"+h+"":"B"===s&&9===l?t+="B":Co(s)&&(t+=So[l/3+5]));return o?lo+t:t}function Eo(t,e){for(var r=0;r=0,o=u(t,e[1])<=0;return(r||i)&&(n||o)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=o(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;n-1&&s.length>d&&(s=d>3?s.substr(0,d-3)+"...":s.substr(0,d))}void 0!==e.zLabel?(void 0!==e.xLabel&&(l+="x: "+e.xLabel+"
"),void 0!==e.yLabel&&(l+="y: "+e.yLabel+"
"),l+=(l?"z: ":"")+e.zLabel):w&&e[i+"Label"]===m?l=e[("x"===i?"y":"x")+"Label"]||"":void 0===e.xLabel?void 0!==e.yLabel&&(l=e.yLabel):l=void 0===e.yLabel?e.xLabel:"("+e.xLabel+", "+e.yLabel+")",e.text&&!Array.isArray(e.text)&&(l+=(l?"
":"")+e.text),void 0!==e.extraText&&(l+=(l?"
":"")+e.extraText),""===l&&(""===s&&r.remove(),l=s);var y=r.select("text.nums").call(pn.font,e.fontFamily||c,e.fontSize||p,e.fontColor||f).text(l).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),g=r.select("text.name"),v=0;s&&s!==l?(g.call(pn.font,e.fontFamily||c,e.fontSize||p,h).text(s).attr("data-notex",1).call(Fr.positionText,0,0).call(Fr.convertToTspans,n),v=g.node().getBoundingClientRect().width+2*Vo):(g.remove(),r.select("rect").remove()),r.select("path").style({fill:h,stroke:f});var k,A,T=y.node().getBoundingClientRect(),M=e.xa._offset+(e.x0+e.x1)/2,S=e.ya._offset+(e.y0+e.y1)/2,C=Math.abs(e.x1-e.x0),z=Math.abs(e.y1-e.y0),L=T.width+jo+Vo+v;e.ty0=_-T.top,e.bx=T.width+2*Vo,e.by=T.height+2*Vo,e.anchor="start",e.txwidth=T.width,e.tx2width=v,e.offset=0,o?(e.pos=M,k=S+z/2+L<=b,A=S-z/2-L>=0,"top"!==e.idealAlign&&k||!A?k?(S+=z/2,e.anchor="start"):e.anchor="middle":(S-=z/2,e.anchor="end")):(e.pos=S,k=M+C/2+L<=x,A=M-C/2-L>=0,"left"!==e.idealAlign&&k||!A?k?(M+=C/2,e.anchor="start"):e.anchor="middle":(M-=C/2,e.anchor="end")),y.attr("text-anchor",e.anchor),v&&g.attr("text-anchor",e.anchor),r.attr("transform","translate("+M+","+S+")"+(o?"rotate("+Oo+")":""))}),C}function Uo(e,r){e.each(function(e){var n=t.select(this);if(e.del)n.remove();else{var i="end"===e.anchor?-1:1,o=n.select("text.nums"),a={start:1,end:-1,middle:0}[e.anchor],s=a*(jo+Vo),l=s+a*(e.txwidth+Vo),u=0,c=e.offset;"middle"===e.anchor&&(s-=e.tx2width/2,l+=e.txwidth/2+Vo),r&&(c*=-No,u=e.offset*Fo),n.select("path").attr("d","middle"===e.anchor?"M-"+(e.bx/2+e.tx2width/2)+","+(c-e.by/2)+"h"+e.bx+"v"+e.by+"h-"+e.bx+"Z":"M0,0L"+(i*jo+u)+","+(jo+c)+"v"+(e.by/2-jo)+"h"+i*e.bx+"v-"+e.by+"H"+(i*jo+u)+"V"+(c-jo)+"Z"),o.call(Fr.positionText,s+u,c+e.ty0-e.by/2+Vo),e.tx2width&&(n.select("text.name").call(Fr.positionText,l+a*Vo+u,c+e.ty0-e.by/2+Vo),n.select("rect").call(pn.setRect,l+(a-1)*e.tx2width/2+u,c-e.by/2-1,e.tx2width,e.by+2))}})}function Ho(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],o=t.cd[r]||{},a=Array.isArray(r)?function(t,e){return re.castOption(i,r,t)||re.extractOption({},n,"",e)}:function(t,e){return re.extractOption(o,n,t,e)};function s(e,r,n){var i=a(r,n);i&&(t[e]=i)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=re.constrain(t.x0,0,t.xa._length),t.x1=re.constrain(t.x1,0,t.xa._length),t.y0=re.constrain(t.y0,0,t.ya._length),t.y1=re.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:eo.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:eo.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var l=eo.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+l+" / -"+eo.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+l,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=eo.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+eo.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function Zo(t,e){var r,n,i=e.container,o=e.fullLayout,a=e.event,l=!!t.hLinePoint,u=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),u||l){var c=Oe.combine(o.plot_bgcolor,o.paper_bgcolor);if(l){var p,h,f=t.hLinePoint;r=f&&f.xa,"cursor"===(n=f&&f.ya).spikesnap?(p=a.pointerX,h=a.pointerY):(p=r._offset+f.x,h=n._offset+f.y);var d,y,m=s.readability(f.color,c)<1.5?Oe.contrast(c):f.color,g=n.spikemode,v=n.spikethickness,_=n.spikecolor||m,x=n._boundingBox,b=(x.left+x.right)/2U.width||V<0||V>U.height)return rr.unhoverRaw(r,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(b="xval"in n?En.flat(a,n.xval):En.p2c(f,j),w="yval"in n?En.flat(a,n.yval):En.p2c(d,V),!e(b[0])||!e(w[0]))return re.warn("Fx.hover failed",n,r),rr.unhoverRaw(r,n)}var H=1/0;for(A=0;AD&&(B.splice(0,D),H=B[0].distance),c&&0!==R&&0===B.length){I.distance=R,I.index=!1;var Y=M._module.hoverPoints(I,L,E,"closest",s._hoverlayer);if(Y&&(Y=Y.filter(function(t){return t.spikeDistance<=R})),Y&&Y.length){var J,K=Y.filter(function(t){return t.xa.showspikes});if(K.length){var $=K[0];e($.x0)&&e($.y0)&&(J=rt($),(!N.vLinePoint||N.vLinePoint.spikeDistance>J.spikeDistance)&&(N.vLinePoint=J))}var Q=Y.filter(function(t){return t.ya.showspikes});if(Q.length){var tt=Q[0];e(tt.x0)&&e(tt.y0)&&(J=rt(tt),(!N.hLinePoint||N.hLinePoint.spikeDistance>J.spikeDistance)&&(N.hLinePoint=J))}}}}function et(t,e){for(var r,n=null,i=1/0,o=0;o1,yt=Oe.combine(s.plot_bgcolor||Oe.background,s.paper_bgcolor),mt={hovermode:x,rotateLabels:dt,bgColor:yt,container:s._hoverlayer,outerContainer:s._paperdiv,commonLabelOpts:s.hoverlabel,hoverdistance:s.hoverdistance},gt=qo(B,mt,r);if(function(t,e,r){var n,i,o,a,s,l,u,c=0,p=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?Bo:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function h(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,o=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(o<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=o;n=!1}if(n){var u=0;for(a=0;ae.pmax&&u++;for(a=t.length-1;a>=0&&!(u<=0);a--)(l=t[a]).pos>e.pmax-1&&(l.del=!0,u--);for(a=0;a=0;s--)t[s].dp-=o;for(a=t.length-1;a>=0&&!(u<=0);a--)(l=t[a]).pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,a=0;a.01&&y.pmin===m.pmin&&y.pmax===m.pmax){for(s=d.length-1;s>=0;s--)d[s].dp+=i;for(f.push.apply(f,d),p.splice(a+1,1),u=0,s=f.length-1;s>=0;s--)u+=f[s].dp;for(o=u/f.length,s=f.length-1;s>=0;s--)f[s].dp-=o;n=!1}else a++}p.forEach(h)}for(a=p.length-1;a>=0;a--){var g=p[a];for(s=g.length-1;s>=0;s--){var v=g[s],_=t[v.i];_.offset=v.dp,_.del=v.del}}}(B,dt?"xa":"ya",s),Uo(gt,dt),n.target&&n.target.tagName){var vt=P.getComponentMethod("annotations","hasClickToShow")(r,ht);Bn(t.select(n.target),vt?"pointer":"")}if(!n.target||o||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],o=t._hoverdata[n];if(i.curveNumber!==o.curveNumber||String(i.pointNumber)!==String(o.pointNumber))return!0}return!1}(r,0,pt))return;pt&&r.emit("plotly_unhover",{event:n,points:pt});r.emit("plotly_hover",{event:n,points:r._hoverdata,xaxes:f,yaxes:d,xvals:b,yvals:w})}(r,n,i,o)})},Do.loneHover=function(e,r){var n={color:e.color||Oe.defaultLine,x0:e.x0||e.x||0,x1:e.x1||e.x||0,y0:e.y0||e.y||0,y1:e.y1||e.y||0,xLabel:e.xLabel,yLabel:e.yLabel,zLabel:e.zLabel,text:e.text,name:e.name,idealAlign:e.idealAlign,borderColor:e.borderColor,fontFamily:e.fontFamily,fontSize:e.fontSize,fontColor:e.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},i=t.select(r.container),o=r.outerContainer?t.select(r.outerContainer):i,a={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||Oe.background,container:i,outerContainer:o},s=qo([n],a,r.gd);return Uo(s,a.rotateLabels),s.node()};var Wo=Do.hover,Xo=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),re.coerceFont(r,"hoverlabel.font",n.font)},Yo=M({editType:"none"});Yo.family.dflt=Ge.HOVERFONT,Yo.size.dflt=Ge.HOVERFONTSIZE;var Jo={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Yo,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var Ko={moduleType:"component",name:"fx",constants:Ge,schema:{layout:Jo},attributes:S,layoutAttributes:Jo,supplyLayoutGlobalDefaults:function(t,e){Xo(0,0,function(r,n){return re.coerce(t,e,Jo,r,n)})},supplyDefaults:function(t,e,r,n){Xo(0,0,function(r,n){return re.coerce(t,e,S,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return re.coerce(t,e,Jo,r,n)}var i;"select"===n("dragmode")&&n("selectdirection"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}r._w=C,r._h=z;for(var D=!1,O=["x","y"],R=0;R1)&&(H===U?((Q=Z.r2fraction(r["a"+q]))<0||Q>1)&&(D=!0):D=!0,D))continue;B=Z._offset+Z.r2p(r[q]),j=.5}else"x"===q?(N=r[q],B=c.l+c.w*N):(N=1-r[q],B=c.t+c.h*N),j=r.showarrow?.5:N;if(r.showarrow){$.head=B;var tt=r["a"+q];V=W*I(.5,r.xanchor)-X*I(.5,r.yanchor),H===U?($.tail=Z._offset+Z.r2p(tt),F=V):($.tail=B+tt,F=V+tt),$.text=$.tail+V;var et=u["x"===q?"width":"height"];if("paper"===U&&($.head=re.constrain($.head,1,et-1)),"pixel"===H){var rt=-Math.max($.tail-3,$.text),nt=Math.min($.tail+3,$.text)-et;rt>0?($.tail+=rt,$.text+=rt):nt>0&&($.tail-=nt,$.text-=nt)}$.tail+=K,$.head+=K}else F=V=Y*I(j,J),$.text=B+V;$.text+=K,V+=K,F+=K,r["_"+q+"padplus"]=Y/2+F,r["_"+q+"padminus"]=Y/2-F,r["_"+q+"size"]=Y,r["_"+q+"shift"]=V}if(D)_.remove();else{var it=0,ot=0;if("left"!==r.align&&(it=(C-b)*("center"===r.align?.5:1)),"top"!==r.valign&&(ot=(z-M)*("middle"===r.valign?.5:1)),s)n.select("svg").attr({x:w+it-1,y:w+ot}).call(pn.setClipUrl,A?h:null);else{var at=w+ot-v.top,st=w+it-v.left;S.call(Fr.positionText,st,at).call(pn.setClipUrl,A?h:null)}T.select("rect").call(pn.setRect,w,w,C,z),k.call(pn.setRect,x/2,x/2,L-x,E-x),_.call(pn.setTranslate,Math.round(f.x.text-L/2),Math.round(f.y.text-E/2)),m.attr({transform:"rotate("+d+","+f.x.text+","+f.y.text+")"});var lt,ut,ct=function(t,n){y.selectAll(".annotation-arrow-g").remove();var s=f.x.head,u=f.y.head,h=f.x.tail+t,g=f.y.tail+n,v=f.x.text+t,x=f.y.text+n,b=re.rotationXYMatrix(d,v,x),w=re.apply2DTransform(b),A=re.apply2DTransform2(b),T=+k.attr("width"),M=+k.attr("height"),S=v-.5*T,C=S+T,z=x-.5*M,L=z+M,E=[[S,z,S,L],[S,L,C,L],[C,L,C,z],[C,z,S,z]].map(A);if(!E.reduce(function(t,e){return t^!!re.segmentsIntersect(s,u,s+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){E.forEach(function(t){var e=re.segmentsIntersect(h,g,s,u,t[0],t[1],t[2],t[3]);e&&(h=e.x,g=e.y)});var I=r.arrowwidth,D=r.arrowcolor,O=r.arrowside,R=y.append("g").style({opacity:Oe.opacity(D)}).classed("annotation-arrow-g",!0),B=R.append("path").attr("d","M"+h+","+g+"L"+s+","+u).style("stroke-width",I+"px").call(Oe.stroke,Oe.rgb(D));if(je(B,O,r),p.annotationPosition&&B.node().parentNode&&!i){var F=s,N=u;if(r.standoff){var j=Math.sqrt(Math.pow(s-h,2)+Math.pow(u-g,2));F+=r.standoff*(h-s)/j,N+=r.standoff*(g-u)/j}var V,q,U,H=R.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(h-F)+","+(g-N),transform:"translate("+F+","+N+")"}).style("stroke-width",I+6+"px").call(Oe.stroke,"rgba(0,0,0,0)").call(Oe.fill,"rgba(0,0,0,0)");rr.init({element:H.node(),gd:e,prepFn:function(){var t=pn.getTranslate(_);q=t.x,U=t.y,V={},o&&o.autorange&&(V[o._name+".autorange"]=!0),a&&a.autorange&&(V[a._name+".autorange"]=!0)},moveFn:function(t,e){var n=w(q,U),i=n[0]+t,s=n[1]+e;_.call(pn.setTranslate,i,s),V[l+".x"]=o?o.p2r(o.r2p(r.x)+t):r.x+t/c.w,V[l+".y"]=a?a.p2r(a.r2p(r.y)+e):r.y-e/c.h,r.axref===r.xref&&(V[l+".ax"]=o.p2r(o.r2p(r.ax)+t)),r.ayref===r.yref&&(V[l+".ay"]=a.p2r(a.r2p(r.ay)+e)),R.attr("transform","translate("+t+","+e+")"),m.attr({transform:"rotate("+d+","+i+","+s+")"})},doneFn:function(){P.call("relayout",e,V);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}};if(r.showarrow&&ct(0,0),g)rr.init({element:_.node(),gd:e,prepFn:function(){ut=m.attr("transform"),lt={}},moveFn:function(t,e){var n="pointer";if(r.showarrow)r.axref===r.xref?lt[l+".ax"]=o.p2r(o.r2p(r.ax)+t):lt[l+".ax"]=r.ax+t,r.ayref===r.yref?lt[l+".ay"]=a.p2r(a.r2p(r.ay)+e):lt[l+".ay"]=r.ay+e,ct(t,e);else{if(i)return;if(o)lt[l+".x"]=o.p2r(o.r2p(r.x)+t);else{var s=r._xsize/c.w,u=r.x+(r._xshift-r.xshift)/c.w-s/2;lt[l+".x"]=rr.align(u+t/c.w,s,0,1,r.xanchor)}if(a)lt[l+".y"]=a.p2r(a.r2p(r.y)+e);else{var p=r._ysize/c.h,h=r.y-(r._yshift+r.yshift)/c.h-p/2;lt[l+".y"]=rr.align(h-e/c.h,p,0,1,r.yanchor)}o&&a||(n=rr.getCursor(o?.5:lt[l+".x"],a?.5:lt[l+".y"],r.xanchor,r.yanchor))}m.attr({transform:"translate("+t+","+e+")"+ut}),On(_,n)},doneFn:function(){On(_),P.call("relayout",e,lt);var t=document.querySelector(".js-notes-box-panel");t&&t.redraw(t.selectedObj)}})}}}var ea=$o.draw;function ra(t){var e=t._fullLayout;re.filterVisible(e.annotations).forEach(function(e){var r,n,i,o,a=eo.getFromId(t,e.xref),s=eo.getFromId(t,e.yref),l=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;a&&a.autorange&&(r=l+e.xshift,n=l-e.xshift,i=u+e.xshift,o=u-e.xshift,e.axref===e.xref?(eo.expand(a,[a.r2c(e.x)],{ppadplus:r,ppadminus:n}),eo.expand(a,[a.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,o)})):(i=e.ax?i+e.ax:i,o=e.ax?o-e.ax:o,eo.expand(a,[a.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,o)}))),s&&s.autorange&&(r=l-e.yshift,n=l+e.yshift,i=u-e.yshift,o=u+e.yshift,e.ayref===e.yref?(eo.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),eo.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,o)})):(i=e.ay?i+e.ay:i,o=e.ay?o-e.ay:o,eo.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,o)})))})}var na={hasClickToShow:function(t,e){var r=ia(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=ia(t,e),i=n.on,o=n.off.concat(n.explicitOff),a={};if(!i.length&&!o.length)return;for(r=0;r1){a=!0;break}}a?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+i+'"]').remove():(o._pdata=ya(t.glplot.cameraParams,[e.xaxis.r2l(o.x)*r[0],e.yaxis.r2l(o.y)*r[1],e.zaxis.r2l(o.z)*r[2]]),ma(t.graphDiv,o,i,t.id,o._xa,o._ya))}}};var _a={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},xa=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+n[e],o=+i[e];return isNaN(r)&&isNaN(o)?[NaN,NaN]:[o||0,r||0]}}var o=ba(e,t.value),a=ba(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=o(t);return[e,e]}:function(t){return[a(t),o(t)]}};function ba(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var wa=function(t){for(var e=t.calcdata,r=0;r0;r.each(function(r){var l,u=r[0].trace,c=u.error_x||{},p=u.error_y||{};u.ids&&(l=function(t){return t.id});var h=cn.hasMarkers(u)&&u.marker.maxdisplayed>0;p.visible||c.visible||(r=[]);var f=t.select(this).selectAll("g.errorbar").data(r,l);if(f.exit().remove(),r.length){c.visible||f.selectAll("path.xerror").remove(),p.visible||f.selectAll("path.yerror").remove(),f.style("opacity",1);var d=f.enter().append("g").classed("errorbar",!0);s&&d.style("opacity",0).transition().duration(i.duration).style("opacity",1),pn.setClipUrl(f,n.layerClipId),f.each(function(r){var n=t.select(this),l=function(t,r,n){var i={x:r.c2p(t.x),y:n.c2p(t.y)};return void 0!==t.yh&&(i.yh=n.c2p(t.yh),i.ys=n.c2p(t.ys),e(i.ys)||(i.noYS=!0,i.ys=n.c2p(t.ys,!0))),void 0!==t.xh&&(i.xh=r.c2p(t.xh),i.xs=r.c2p(t.xs),e(i.xs)||(i.noXS=!0,i.xs=r.c2p(t.xs,!0))),i}(r,o,a);if(!h||r.vis){var u,f=n.select("path.yerror");if(p.visible&&e(l.x)&&e(l.yh)&&e(l.ys)){var d=p.width;u="M"+(l.x-d)+","+l.yh+"h"+2*d+"m-"+d+",0V"+l.ys,l.noYS||(u+="m-"+d+",0h"+2*d),f.size()?s&&(f=f.transition().duration(i.duration).ease(i.easing)):f=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),f.attr("d",u)}else f.remove();var y=n.select("path.xerror");if(c.visible&&e(l.y)&&e(l.xh)&&e(l.xs)){var m=(c.copy_ystyle?p:c).width;u="M"+l.xh+","+(l.y-m)+"v"+2*m+"m0,-"+m+"H"+l.xs,l.noXS||(u+="m0,-"+m+"v"+2*m),y.size()?s&&(y=y.transition().duration(i.duration).ease(i.easing)):y=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),y.attr("d",u)}else y.remove()}})}})},style:function(e){e.each(function(e){var r=e[0].trace,n=r.error_y||{},i=r.error_x||{},o=t.select(this);o.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(Oe.stroke,n.color),i.copy_ystyle&&(i=n),o.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(Oe.stroke,i.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var Ca={},za=g.extendFlat;Ca.attributes=function(t,e){t=t||{},e=e||{};var r={valType:"info_array",editType:t.editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},n=(t.name&&t.name,t.trace,e.description&&e.description,{x:za({},r,{}),y:za({},r,{}),editType:t.editType});return t.noGridCell||(n.row={valType:"integer",min:0,dflt:0,editType:t.editType},n.column={valType:"integer",min:0,dflt:0,editType:t.editType}),n},Ca.defaults=function(t,e,r,n){var i=n&&n.x||[0,1],o=n&&n.y||[0,1],a=e.grid;if(a){var s=r("domain.column");void 0!==s&&(s1){s||l||u||"independent"===_("pattern")&&(s=!0),p._hasSubplotGrid=s;var d,y,m="top to bottom"===_("roworder"),g=s?.2:.1,v=s?.3:.1;c&&(d="bottom",y="left"),p._domains={x:Oa("x",_,g,d,f),y:Oa("y",_,v,y,h,m)}}}function _(t,e){return re.coerce(r,p,Ia,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,o,a,s,l,u,c=t.grid||{},p=e._subplots,h=r._hasSubplotGrid,f=r.rows,d=r.columns,y="independent"===r.pattern,m=r._axisMap={};if(h){var g=c.subplots||[];l=r.subplots=new Array(f);var v=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},Ha={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Za=!0,Ga=function(t,e,r){if(!e._dragged&&!e._editing){var n,i,o,a,s,l=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,p=u.trace,h=p.legendgroup,f={},d=[],y=[],m=[];if(1===r&&Za&&e.data&&e._context.showTips?(re.notifier(re._(e,"Double-click on legend to isolate one trace"),"long"),Za=!1):Za=!1,P.traceIs(p,"pie")){var g=u.label,v=l.indexOf(g);1===r?-1===v?l.push(g):l.splice(v,1):2===r&&(l=[],e.calcdata[0].forEach(function(t){g!==t.label&&l.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===l.length&&-1===v&&(l=[])),P.call("relayout",e,"hiddenlabels",l)}else{var _,x=h&&h.length,b=[];if(x)for(n=0;nr[1])return r[1]}return i}function p(t){return t[0]}if(s||l||u){var h={},f={};s&&(h.mc=c("marker.color",p),h.mo=c("marker.opacity",re.mean,[.2,1]),h.ms=c("marker.size",re.mean,[2,16]),h.mlc=c("marker.line.color",p),h.mlw=c("marker.line.width",re.mean,[0,5]),f.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(f.line={width:c("line.width",p,[0,10])}),l&&(h.tx="Aa",h.tp=c("textposition",p),h.ts=10,h.tc=c("textfont.color",p),h.tf=c("textfont.family",p)),n=[re.minExtend(o,h)],i=re.minExtend(a,f)}var d=t.select(this).select("g.legendpoints"),y=d.selectAll("path.scatterpts").data(s?n:[]);y.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),y.exit().remove(),y.call(pn.pointStyle,i,r),s&&(n[0].mrc=3);var m=d.selectAll("g.pointtext").data(l?n:[]);m.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),m.exit().remove(),m.selectAll("text").call(pn.textPointStyle,i,r)}).each(function(e){var r=e[0].trace,n=t.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===r.type&&r.visible?[e,e]:[]);n.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),n.exit().remove(),n.each(function(e,n){var i=r[n?"increasing":"decreasing"],o=i.line.width,a=t.select(this);a.style("stroke-width",o+"px").call(Oe.fill,i.fillcolor),o&&Oe.stroke(a,i.line.color)})}).each(function(e){var r=e[0].trace,n=t.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===r.type&&r.visible?[e,e]:[]);n.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),n.exit().remove(),n.each(function(e,n){var i=r[n?"increasing":"decreasing"],o=i.line.width,a=t.select(this);a.style("fill","none").call(pn.dashLine,i.line.dash,o),o&&Oe.stroke(a,i.line.color)})})},Ka=Or.LINE_SPACING,$a=Or.FROM_TL,Qa=Or.FROM_BR,ts=h.DBLCLICKDELAY;function es(t,e){var r=t.data()[0][0],n=e._fullLayout,i=r.trace,o=P.traceIs(i,"pie"),a=i.index,s=o?r.label:i.name,l=re.ensureSingle(t,"text","legendtext");function u(r){Fr.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,o=t.select("g[class*=math-group]"),a=o.node(),s=e._fullLayout.legend.font.size*Ka;if(a){var l=pn.bBox(a);n=l.height,i=l.width,pn.setTranslate(o,0,n/4)}else{var u=t.select(".legendtext"),c=Fr.lineCount(u),p=u.node();n=s*c,i=p?pn.bBox(p).width:0;var h=s*(.3+(1-c)/2);Fr.positionText(u,40,h)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}l.attr("text-anchor","start").classed("user-select-none",!0).call(pn.font,n.legend.font).text(s),e._context.edits.legendText&&!o?l.call(Fr.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n=t;this.text()||(t=" ");var i=r.trace._fullInput||{},o={};if(P.hasTransform(i,"groupby")){var s=P.getTransformIndices(i,"groupby"),l=s[s.length-1],c=re.keyedContainer(i,"transforms["+l+"].styles","target","value.name");""===n?c.remove(r.trace._group):c.set(r.trace._group,t),o=c.constructUpdate()}else o.name=t;return P.call("restyle",e,o,a)}):u(l)}function rs(t,e){var r,n=1,i=re.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call(Oe.fill,"rgba(0,0,0,0)")});i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimets&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Ga(t,e,n)},ts):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,Ga(t,e,n))}})}function ns(e,r,n){var i=e._fullLayout,o=i.legend,a=o.borderwidth,s=qa.isGrouped(o),l=0;if(o._width=0,o._height=0,qa.isVertical(o))s&&r.each(function(t,e){pn.setTranslate(this,0,e*o.tracegroupgap)}),n.each(function(t){var e=t[0],r=e.height,n=e.width;pn.setTranslate(this,a,5+a+o._height+r/2),o._height+=r,o._width=Math.max(o._width,n)}),o._width+=45+2*a,o._height+=10+2*a,s&&(o._height+=(o._lgroupsLength-1)*o.tracegroupgap),l=40;else if(s){for(var u=[o._width],c=r.data(),p=0,h=c.length;pa+x-b,n.each(function(t){var e=t[0],r=y?40+t[0].width:v;a+_+b+r>i.width-(i.margin.r+i.margin.l)&&(_=0,m+=g,o._height=o._height+g,g=0),pn.setTranslate(this,a+_,5+a+e.height/2+m),o._width+=b+r,o._height=Math.max(o._height,e.height),_+=b+r,g=Math.max(e.height,g)}),o._width+=2*a,o._height+=10+2*a}o._width=Math.ceil(o._width),o._height=Math.ceil(o._height),n.each(function(r){var n=r[0],i=t.select(this).select(".legendtoggle");pn.setRect(i,0,-n.height/2,(e._context.edits.legendText?0:o._width)+l,n.height)})}function is(t){var e=t._fullLayout.legend,r="left";Ua.isRightAnchor(e)?r="right":Ua.isCenterAnchor(e)&&(r="center");var n="top";Ua.isBottomAnchor(e)?n="bottom":Ua.isMiddleAnchor(e)&&(n="middle"),_i.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*$a[r],r:e._width*Qa[r],b:e._height*Qa[n],t:e._height*$a[n]})}var os={moduleType:"component",name:"legend",layoutAttributes:Va,supplyLayoutDefaults:function(t,e,r){for(var n,i,o,a,s=t.legend||{},l={},u=0,c="normal",p=0;p1)){if(e.legend=l,f("bgcolor",e.paper_bgcolor),f("bordercolor"),f("borderwidth"),re.coerceFont(f,"font",e.font),f("orientation"),"h"===l.orientation){var d=t.xaxis;d&&d.rangeslider&&d.rangeslider.visible?(n=0,o="left",i=1.1,a="bottom"):(n=0,o="left",i=-.1,a="top")}f("traceorder",c),qa.isGrouped(e.legend)&&f("tracegroupgap"),f("x",n),f("xanchor",o),f("y",i),f("yanchor",a),re.noneOrAll(s,l,["x","y"])}},draw:function(e){var r=e._fullLayout,n="legend"+r._uid;if(r._infolayer&&e.calcdata){e._legendMouseDownTime||(e._legendMouseDownTime=0);var i=r.legend,o=r.showlegend&&function(t,e){var r,n,i={},o=[],a=!1,s={},l=0;function u(t,r){if(""!==t&&qa.isGrouped(e))-1===o.indexOf(t)?(o.push(t),a=!0,i[t]=[[r]]):i[t].push([r]);else{var n="~~i"+l;o.push(n),i[n]=[[r]],l++}}for(r=0;rm?function(t){var e=t._fullLayout.legend,r="left";Ua.isRightAnchor(e)?r="right":Ua.isCenterAnchor(e)&&(r="center"),_i.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*$a[r],r:e._width*Qa[r],b:0,t:0})}(e):is(e);var g=r._size,v=g.l+g.w*i.x,_=g.t+g.h*(1-i.y);Ua.isRightAnchor(i)?v-=i._width:Ua.isCenterAnchor(i)&&(v-=i._width/2),Ua.isBottomAnchor(i)?_-=i._height:Ua.isMiddleAnchor(i)&&(_-=i._height/2);var x=i._width,b=g.w;x>b?(v=g.l,x=b):(v+x>y&&(v=y-x),v<0&&(v=0),x=Math.min(y-v,i._width));var w,k,A,T,M=i._height,S=g.h;if(M>S?(_=g.t,M=S):(_+M>m&&(_=m-M),_<0&&(_=0),M=Math.min(m-_,i._height)),pn.setTranslate(l,v,_),h.on(".drag",null),l.on("wheel",null),i._height<=M||e._context.staticPlot)c.attr({width:x-i.borderwidth,height:M-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),pn.setTranslate(p,0,0),u.select("rect").attr({width:x-2*i.borderwidth,height:M-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth}),pn.setClipUrl(p,n),pn.setRect(h,0,0,0,0),delete i._scrollY;else{var C,z,L=Math.max(Ha.scrollBarMinHeight,M*M/i._height),E=M-L-2*Ha.scrollBarMargin,I=i._height-M,D=E/I,O=Math.min(i._scrollY||0,I);c.attr({width:x-2*i.borderwidth+Ha.scrollBarWidth+Ha.scrollBarMargin,height:M-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),u.select("rect").attr({width:x-2*i.borderwidth+Ha.scrollBarWidth+Ha.scrollBarMargin,height:M-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth+O}),pn.setClipUrl(p,n),B(O,L,D),l.on("wheel",function(){B(O=re.constrain(i._scrollY+t.event.deltaY/E*I,0,I),L,D),0!==O&&O!==I&&t.event.preventDefault()});var R=t.behavior.drag().on("dragstart",function(){C=t.event.sourceEvent.clientY,z=O}).on("drag",function(){var e=t.event.sourceEvent;2===e.buttons||e.ctrlKey||B(O=re.constrain((e.clientY-C)/D+z,0,I),L,D)});h.call(R)}e._context.edits.legendPosition&&(l.classed("cursor-move",!0),rr.init({element:l.node(),gd:e,prepFn:function(){var t=pn.getTranslate(l);A=t.x,T=t.y},moveFn:function(t,e){var r=A+t,n=T+e;pn.setTranslate(l,r,n),w=rr.align(r,0,g.l,g.l+g.w,i.xanchor),k=rr.align(n,0,g.t+g.h,g.t,i.yanchor)},doneFn:function(){void 0!==w&&void 0!==k&&P.call("relayout",e,{"legend.x":w,"legend.y":k})},clickFn:function(t,n){var i=r._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===t?l._clickTimeout=setTimeout(function(){Ga(i,e,t)},ts):2===t&&(l._clickTimeout&&clearTimeout(l._clickTimeout),Ga(i,e,t)))}}))}function B(t,r,n){i._scrollY=e._fullLayout.legend._scrollY=t,pn.setTranslate(p,0,-t),pn.setRect(h,x,Ha.scrollBarMargin+t*n,Ha.scrollBarWidth,r),u.select("rect").attr({y:i.borderwidth+t})}},style:Ja},as={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},ss=g.extendFlat,ls={visible:{valType:"boolean",editType:"plot"},buttons:as=ss(as,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:M({editType:"plot"}),bgcolor:{valType:"color",dflt:z.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:z.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},us={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var cs=function(e,r){var n=e._name,i={};if("all"===r.step)i[n+".autorange"]=!0;else{var o=function(e,r){var n,i=e.range,o=new Date(e.r2l(i[1])),a=r.step,s=r.count;switch(r.stepmode){case"backward":n=e.l2r(+t.time[a].utc.offset(o,-s));break;case"todate":var l=t.time[a].utc.offset(o,-s);n=e.l2r(+t.time[a].utc.ceil(l))}var u=i[1];return[n,u]}(e,r);i[n+".range[0]"]=o[0],i[n+".range[1]"]=o[1]}return i};var ps=Or.LINE_SPACING,hs=Or.FROM_TL,fs=Or.FROM_BR;function ds(t){return t._id}function ys(t,e,r){var n=re.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:us.rx,ry:us.ry}),n.call(Oe.stroke,e.bordercolor).call(Oe.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function ms(t,e,r,n){var i;re.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(pn.font,e.font).text((i=r,i.label?i.label:"all"===i.step?"all":i.count+i.step.charAt(0))).call(function(t){Fr.convertToTspans(t,n)})}var gs={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:ls}}},layoutAttributes:ls,handleDefaults:function(t,e,r,n,i){var o=t.rangeselector||{},a=e.rangeselector={};function s(t,e){return re.coerce(o,a,ls,t,e)}if(s("visible",function(t,e,r){var n,i,o=t.buttons||[],a=e.buttons=[];function s(t,e){return re.coerce(n,i,as,t,e)}for(var l=0;l0)){var l=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,o=0;o0})}function u(t,n){var i=t.seg,o=n.seg,a=i.start,l=i.end,u=o.start,c=o.end;r&&r.checkIntersection(i,o);var p=e.linesIntersect(a,l,u,c);if(!1===p){if(!e.pointsCollinear(a,l,u))return!1;if(e.pointsSame(a,c)||e.pointsSame(l,u))return!1;var h=e.pointsSame(a,u),f=e.pointsSame(l,c);if(h&&f)return n;var d=!h&&e.pointBetween(a,u,c),y=!f&&e.pointBetween(l,u,c);if(h)return y?s(n,l):s(t,c),n;d&&(f||(y?s(n,l):s(t,c)),s(n,a))}else 0===p.alongA&&(-1===p.alongB?s(t,u):0===p.alongB?s(t,p.pt):1===p.alongB&&s(t,c)),0===p.alongB&&(-1===p.alongA?s(n,a):0===p.alongA?s(n,p.pt):1===p.alongA&&s(n,l));return!1}for(var c=[];!i.isEmpty();){var p=i.getHead();if(r&&r.vert(p.pt[0]),p.isStart){r&&r.segmentNew(p.seg,p.primary);var h=l(p),f=h.before?h.before.ev:null,d=h.after?h.after.ev:null;function y(){if(f){var t=u(p,f);if(t)return t}return!!d&&u(p,d)}r&&r.tempStatus(p.seg,!!f&&f.seg,!!d&&d.seg);var m,g,v=y();if(v)t?(g=null===p.seg.myFill.below||p.seg.myFill.above!==p.seg.myFill.below)&&(v.seg.myFill.above=!v.seg.myFill.above):v.seg.otherFill=p.seg.myFill,r&&r.segmentUpdate(v.seg),p.other.remove(),p.remove();if(i.getHead()!==p){r&&r.rewind(p.seg);continue}t?(g=null===p.seg.myFill.below||p.seg.myFill.above!==p.seg.myFill.below,p.seg.myFill.below=d?d.seg.myFill.above:n,p.seg.myFill.above=g?!p.seg.myFill.below:p.seg.myFill.below):null===p.seg.otherFill&&(m=d?p.primary===d.primary?d.seg.otherFill.above:d.seg.myFill.above:p.primary?o:n,p.seg.otherFill={above:m,below:m}),r&&r.status(p.seg,!!f&&f.seg,!!d&&d.seg),p.other.status=h.insert(Cs.node({ev:p}))}else{var _=p.status;if(null===_)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(a.exists(_.prev)&&a.exists(_.next)&&u(_.prev.ev,_.next.ev),r&&r.statusRemove(_.ev.seg),_.remove(),!p.primary){var x=p.seg.myFill;p.seg.myFill=p.seg.otherFill,p.seg.otherFill=x}c.push(p.seg)}i.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,i,o,s=t[t.length-1],l=0;l=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],o=n[0]-r[0],a=e[0]-r[0],s=n[1]-r[1],l=a*o+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=a-i>t&&(o-u)*(i-c)/(a-c)+u-n>t&&(s=!s),o=u,a=c}return s}};return e}();function Rs(t,e,r){var n=Ps.segments(t),i=Ps.segments(e),o=r(Ps.combine(n,i));return Ps.polygon(o)}Ps={buildLog:function(t){return!0===t?Ds=Ms():!1===t&&(Ds=!1),!1!==Ds&&Ds.list},epsilon:function(t){return Os.epsilon(t)},segments:function(t){var e=zs(!0,Os,Ds);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:zs(!1,Os,Ds).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:Is.union(t.combined,Ds),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:Is.intersect(t.combined,Ds),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:Is.difference(t.combined,Ds),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:Is.differenceRev(t.combined,Ds),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:Is.xor(t.combined,Ds),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:Ls(t.segments,Os,Ds),inverted:t.inverted}},polygonFromGeoJSON:function(t){return Ss.toPolygon(Ps,t)},polygonToGeoJSON:function(t){return Ss.fromPolygon(Ps,Os,t)},union:function(t,e){return Rs(t,e,Ps.selectUnion)},intersect:function(t,e){return Rs(t,e,Ps.selectIntersect)},difference:function(t,e){return Rs(t,e,Ps.selectDifference)},differenceRev:function(t,e){return Rs(t,e,Ps.selectDifferenceRev)},xor:function(t,e){return Rs(t,e,Ps.selectXor)}},"object"==typeof window&&(window.PolyBool=Ps);var Bs,Fs=Ps,Ns=jt.dot,js=r.BADNUM,Vs=Bs={};Vs.tester=function(t){if(Array.isArray(t[0][0]))return Vs.multitester(t);var e,r=t.slice(),n=r[0][0],i=n,o=r[0][1],a=o;for(r.push(r[0]),e=1;ei||l===js||la||e&&s(t))}:function(t,e){var s=t[0],l=t[1];if(s===js||si||l===js||la)return!1;var u,c,p,h,f,d=r.length,y=r[0][0],m=r[0][1],g=0;for(u=1;uMath.max(c,y)||l>Math.max(p,m)))if(lu||Math.abs(Ns(o,p))>n)return!0;return!1};Vs.filter=function(t,e){var r=[t[0]],n=0,i=0;function o(o){t.push(o);var a=r.length,s=n;r.splice(i+1);for(var l=s+1;l1&&o(t.pop());return{addPt:o,raw:t,filtered:r}};var Us=En.makeEventData,Hs=pi.getFromId,Zs=vi,Gs=Ie.MINSELECT,Ws=Bs.filter,Xs=Bs.tester,Ys=Bs.multitester;function Js(t){return t._id}function Ks(t,e,r){var n,i,o,a;if(r){var s=r.points||[];for(n=0;n=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function ml(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function gl(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Oe.background,stroke:Oe.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function vl(t,e,r,n,i,o){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),_l(t,e,i,o)}function _l(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function xl(e){t.select(e).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function bl(t){ul&&t.data&&t._context.showTips&&(re.notifier(re._(t,"Double-click to zoom back out"),"long"),ul=!1)}function wl(t){return"lasso"===t||"select"===t}function kl(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,ll)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function Al(t,e){if(qe){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function Tl(t){var e=[];for(var r in t)e.push(t[r]);return e}var Ml={},Sl=function(e,r,n,i,o,a,l,u){var c,p,h,f,d,y,m,g,v,_,x,b,w,k,A,T,M,S=e._fullLayout._zoomlayer,C=l+u==="nsew",z=1===(l+u).length;function L(){if(c=r.xaxis,p=r.yaxis,v=c._length,_=p._length,m=c._offset,g=p._offset,(h={})[c._id]=c,(f={})[p._id]=p,l&&u)for(var t=r.overlays,n=0;nll||a>ll?(j="xy",o/v>a/_?(a=o*_/v,O>i?R.t=O-a:R.b=O+a):(o=a*v/_,D>n?R.l=D-o:R.r=D+o),q.attr("d",kl(R))):s():!w||a10||r.scrollWidth-r.clientWidth>10)){clearTimeout(X);var n=-t.deltaY;if(isFinite(n)||(n=t.wheelDelta/10),isFinite(n)){var i,o=Math.exp(-Math.min(Math.max(n,-20),20)/200),a=J.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(t.clientX-a.left)/a.width,c=(a.bottom-t.clientY)/a.height;if(T){for(u||(s=.5),i=0;i0;a&&(i="array");var s,l=r("categoryorder",i);"array"===l&&(s=r("categoryarray")),a||"array"!==l||(l=e.categoryorder="trace"),"trace"===l?e._initialCategories=[]:"array"===l?e._initialCategories=s.slice():(s=function(t,e){var r,n,i,o=e.dataAttr||t._id.charAt(0),a={};if(e.axData)r=e.axData;else for(r=[],n=0;nd[1]-.01&&(r.domain=a),re.noneOrAll(t.domain,r.domain,a)}return n("layer"),r},Rl=pi.name2id,Bl=function(t,e,r,n,i){i&&(e._name=i,e._id=Rl(i)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var i=function(t,e,r){for(var n=0;n0&&i["_"+r+"axes"][e])return i;if((i[r+"axis"]||r)===e){if(Nl(i,r))return i;if((i[r]||[]).length||i[r+"0"])return i}}}(e,r,n);if(!i)return;if("histogram"===i.type&&n==={v:"y",h:"x"}[i.orientation||"v"])return void(t.type="linear");var o,a=n+"calendar",s=i[a];if(Nl(i,n)){var l=Fl(i),u=[];for(o=0;o rect").call(pn.setTranslate,0,0).call(pn.setScale,1,1),t.plot.call(pn.setTranslate,e._offset,r._offset).call(pn.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(pn.setPointGroupScale,1,1),n.selectAll(".textpoint").call(pn.setTextPointsScale,1,1),n.call(pn.hideOutsideRangePoints,t)}function y(t,r){var n,i,a,s=p[t.xaxis._id],l=p[t.yaxis._id],u=[];if(s){i=(n=e._fullLayout[s.axisName])._r,a=s.to,u[0]=(i[0]*(1-r)+r*a[0]-i[0])/(i[1]-i[0])*t.xaxis._length;var c=i[1]-i[0],h=a[1]-a[0];n.range[0]=i[0]*(1-r)+r*a[0],n.range[1]=i[1]*(1-r)+r*a[1],u[2]=t.xaxis._length*(1-r+r*h/c)}else u[0]=0,u[2]=t.xaxis._length;if(l){i=(n=e._fullLayout[l.axisName])._r,a=l.to,u[1]=(i[1]*(1-r)+r*a[1]-i[1])/(i[0]-i[1])*t.yaxis._length;var f=i[1]-i[0],d=a[1]-a[0];n.range[0]=i[0]*(1-r)+r*a[0],n.range[1]=i[1]*(1-r)+r*a[1],u[3]=t.yaxis._length*(1-r+r*d/f)}else u[1]=0,u[3]=t.yaxis._length;!function(t,r){var n,i=[];for(i=[t._id,r._id],n=0;nn.duration?(function(){for(var t={},r=0;r0?u+a:a;return{ppad:a,ppadplus:s?p:h,ppadminus:s?h:p}}return{ppad:a}}function fu(t,e,r,n,i){var o="category"===t.type?t.r2c:t.d2c;if(void 0!==e)return[o(e),o(r)];if(n){var a,s,l,u,c=1/0,p=-1/0,h=n.match(lu.segmentRE);for("date"===t.type&&(o=uu.decodeDate(o)),a=0;ap&&(p=u)));return p>=c?[c,p]:void 0}}var du=function(t,e,r,n,i){function o(r,n){return re.coerce(t,e,su,r,n)}if(n=n||{},!o("visible",!(i=i||{}).itemIsNotPlainObject))return e;o("layer"),o("opacity"),o("fillcolor"),o("line.color"),o("line.width"),o("line.dash");for(var a=o("type",t.path?"path":"rect"),s=o("xsizemode"),l=o("ysizemode"),u=["x","y"],c=0;c<2;c++){var p,h,f,d=u[c],y=d+"anchor",m="x"===d?s:l,g={_fullLayout:r},v=eo.coerceRef(t,e,g,d,"","paper");if("paper"!==v?(p=eo.getFromId(g,v),f=uu.rangeToShapePosition(p),h=uu.shapePositionToRange(p)):h=f=re.identity,"path"!==a){var _=d+"0",x=d+"1",b=t[_],w=t[x];t[_]=h(t[_],!0),t[x]=h(t[x],!0),"pixel"===m?(o(_,0),o(x,10)):(eo.coercePosition(e,g,o,v,_,.25),eo.coercePosition(e,g,o,v,x,.75)),e[_]=f(e[_]),e[x]=f(e[x]),t[_]=b,t[x]=w}if("pixel"===m){var k=t[y];t[y]=h(t[y],!0),eo.coercePosition(e,g,o,v,y,.25),e[y]=f(e[y]),t[y]=k}}return"path"===a?o("path"):re.noneOrAll(t,e,["x0","x1","y0","y1"]),e},yu={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var i=0;il?(g=a,b=P+".y0",T="y0",v=l,w=P+".y1",M="y1"):(g=l,b=P+".y1",T="y1",v=a,w=P+".y0",M="y0");i={},H(e),U.moveFn="move"===F?Z:G},doneFn:function(){On(e),P.call("relayout",t,i)}};function H(t){var r=U.element.getBoundingClientRect(),n=r.right-r.left,i=r.bottom-r.top,o=t.clientX-r.left,a=t.clientY-r.top,s=n>N&&i>j&&!t.shiftKey?rr.getCursor(o/n,1-a/i):"move";On(e,s),F=s.split("-")[0]}function Z(n,g){if("path"===r.type){var v=function(t){return t},_=v,x=v;V?i[y]=r.xanchor=R(u+n):(_=function(t){return R(D(t)+n)},E&&"date"===E.type&&(_=uu.encodeDate(_))),q?i[m]=r.yanchor=B(c+g):(x=function(t){return B(O(t)+g)},I&&"date"===I.type&&(x=uu.encodeDate(x))),r.path=vu(z,_,x),i[L]=r.path}else V?i[y]=r.xanchor=R(u+n):(i[p]=r.x0=R(o+n),i[f]=r.x1=R(s+n)),q?i[m]=r.yanchor=B(c+g):(i[h]=r.y0=B(a+g),i[d]=r.y1=B(l+g));e.attr("d",gu(t,r))}function G(n,o){if("path"===r.type){var a=function(t){return t},s=a,l=a;V?i[y]=r.xanchor=R(u+n):(s=function(t){return R(D(t)+n)},E&&"date"===E.type&&(s=uu.encodeDate(s))),q?i[m]=r.yanchor=B(c+o):(l=function(t){return B(O(t)+o)},I&&"date"===I.type&&(l=uu.encodeDate(l))),r.path=vu(z,s,l),i[L]=r.path}else{var p=~F.indexOf("n")?g+o:g,h=~F.indexOf("s")?v+o:v,f=~F.indexOf("w")?_+n:_,d=~F.indexOf("e")?x+n:x;~F.indexOf("n")&&q&&(p=g-o),~F.indexOf("s")&&q&&(h=v-o),(!q&&h-p>j||q&&p-h>j)&&(i[b]=r[T]=q?p:B(p),i[w]=r[M]=q?h:B(h)),d-f>N&&(i[k]=r[S]=V?f:R(f),i[A]=r[C]=V?d:R(d))}e.attr("d",gu(t,r))}rr.init(U),e.node().onmousemove=H}(t,a,n,e)}}function gu(t,e){var r,n,i,o,a,s,l,u,c=e.type,p=eo.getFromId(t,e.xref),h=eo.getFromId(t,e.yref),f=t._fullLayout._size;if(p?(r=uu.shapePositionToRange(p),n=function(t){return p._offset+p.r2p(r(t,!0))}):n=function(t){return f.l+f.w*t},h?(i=uu.shapePositionToRange(h),o=function(t){return h._offset+h.r2p(i(t,!0))}):o=function(t){return f.t+f.h*(1-t)},"path"===c)return p&&"date"===p.type&&(n=uu.decodeDate(n)),h&&"date"===h.type&&(o=uu.decodeDate(o)),function(t,e,r){var n=t.path,i=t.xsizemode,o=t.ysizemode,a=t.xanchor,s=t.yanchor;return n.replace(lu.segmentRE,function(t){var n=0,l=t.charAt(0),u=lu.paramIsX[l],c=lu.paramIsY[l],p=lu.numParams[l],h=t.substr(1).replace(lu.paramRE,function(t){return u[n]?t="pixel"===i?e(a)+Number(t):e(t):c[n]&&(t="pixel"===o?r(s)-Number(t):r(t)),++n>p&&(t="X"),t});return n>p&&(h=h.replace(/[\s,]*X.*/,""),re.log("Ignoring extra params in segment "+t)),l+h})}(e,n,o);if("pixel"===e.xsizemode){var d=n(e.xanchor);a=d+e.x0,s=d+e.x1}else a=n(e.x0),s=n(e.x1);if("pixel"===e.ysizemode){var y=o(e.yanchor);l=y-e.y0,u=y-e.y1}else l=o(e.y0),u=o(e.y1);if("line"===c)return"M"+a+","+l+"L"+s+","+u;if("rect"===c)return"M"+a+","+l+"H"+s+"V"+u+"H"+a+"Z";var m=(a+s)/2,g=(l+u)/2,v=Math.abs(m-a),_=Math.abs(g-l),x="A"+v+","+_,b=m+v+","+g;return"M"+b+x+" 0 1,1 "+(m+","+(g-_))+x+" 0 0,1 "+b+"Z"}function vu(t,e,r){return t.replace(lu.segmentRE,function(t){var n=0,i=t.charAt(0),o=lu.paramIsX[i],a=lu.paramIsY[i],s=lu.numParams[i];return i+t.substr(1).replace(lu.paramRE,function(t){return n>=s?t:(o[n]?t=e(t):a[n]&&(t=r(t)),n++,t)})})}var _u={moduleType:"component",name:"shapes",layoutAttributes:su,supplyLayoutDefaults:function(t,e){la(t,e,{name:"shapes",handleItemDefaults:du})},includeBasePlot:ua("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=re.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),re.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var Su=Or.LINE_SPACING,Cu=Or.FROM_TL,zu=Or.FROM_BR;function Lu(t){return t._index}function Eu(e,r){var n=pn.tester.selectAll("g."+xu.labelGroupClass).data(r.steps);n.enter().append("g").classed(xu.labelGroupClass,!0);var i=0,o=0;n.each(function(e){var n=Du(t.select(this),{step:e},r).node();if(n){var a=pn.bBox(n);o=Math.max(o,a.height),i=Math.max(i,a.width)}}),n.remove();var a=r._dims={};a.inputAreaWidth=Math.max(xu.railWidth,xu.gripHeight);var s=e._fullLayout._size;a.lx=s.l+s.w*r.x,a.ly=s.t+s.h*(1-r.y),"fraction"===r.lenmode?a.outerLength=Math.round(s.w*r.len):a.outerLength=r.len,a.inputAreaStart=0,a.inputAreaLength=Math.round(a.outerLength-r.pad.l-r.pad.r);var l=(a.inputAreaLength-2*xu.stepInset)/(r.steps.length-1),u=i+xu.labelPadding;if(a.labelStride=Math.max(1,Math.ceil(u/l)),a.labelHeight=o,a.currentValueMaxWidth=0,a.currentValueHeight=0,a.currentValueTotalHeight=0,a.currentValueMaxLines=1,r.currentvalue.visible){var c=pn.tester.append("g");n.each(function(t){var e=Pu(c,r,t.label),n=e.node()&&pn.bBox(e.node())||{width:0,height:0},i=Fr.lineCount(e);a.currentValueMaxWidth=Math.max(a.currentValueMaxWidth,Math.ceil(n.width)),a.currentValueHeight=Math.max(a.currentValueHeight,Math.ceil(n.height)),a.currentValueMaxLines=Math.max(a.currentValueMaxLines,i)}),a.currentValueTotalHeight=a.currentValueHeight+r.currentvalue.offset,c.remove()}a.height=a.currentValueTotalHeight+xu.tickOffset+r.ticklen+xu.labelOffset+a.labelHeight+r.pad.t+r.pad.b;var p="left";Ua.isRightAnchor(r)&&(a.lx-=a.outerLength,p="right"),Ua.isCenterAnchor(r)&&(a.lx-=a.outerLength/2,p="center");var h="top";Ua.isBottomAnchor(r)&&(a.ly-=a.height,h="bottom"),Ua.isMiddleAnchor(r)&&(a.ly-=a.height/2,h="middle"),a.outerLength=Math.ceil(a.outerLength),a.height=Math.ceil(a.height),a.lx=Math.round(a.lx),a.ly=Math.round(a.ly),_i.autoMargin(e,xu.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:a.outerLength*Cu[p],r:a.outerLength*zu[p],b:a.height*zu[h],t:a.height*Cu[h]})}function Pu(t,e,r){if(e.currentvalue.visible){var n,i,o=e._dims;switch(e.currentvalue.xanchor){case"right":n=o.inputAreaLength-xu.currentValueInset-o.currentValueMaxWidth,i="left";break;case"center":n=.5*o.inputAreaLength,i="middle";break;default:n=xu.currentValueInset,i="left"}var a=re.ensureSingle(t,"text",xu.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1})}),s=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)s+=r;else s+=e.steps[e.active].label;e.currentvalue.suffix&&(s+=e.currentvalue.suffix),a.call(pn.font,e.currentvalue.font).text(s).call(Fr.convertToTspans,e._gd);var l=Fr.lineCount(a),u=(o.currentValueMaxLines+1-l)*e.currentvalue.font.size*Su;return Fr.positionText(a,n,u),a}}function Iu(t,e,r){re.ensureSingle(t,"rect",xu.gripRectClass,function(n){n.call(Fu,e,t,r).style("pointer-events","all")}).attr({width:xu.gripWidth,height:xu.gripHeight,rx:xu.gripRadius,ry:xu.gripRadius}).call(Oe.stroke,r.bordercolor).call(Oe.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function Du(t,e,r){var n=re.ensureSingle(t,"text",xu.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return n.call(pn.font,r.font).text(e.step.label).call(Fr.convertToTspans,r._gd),n}function Ou(e,r){var n=re.ensureSingle(e,"g",xu.labelsClass),i=r._dims,o=n.selectAll("g."+xu.labelGroupClass).data(i.labelSteps);o.enter().append("g").classed(xu.labelGroupClass,!0),o.exit().remove(),o.each(function(e){var n=t.select(this);n.call(Du,e,r),pn.setTranslate(n,Vu(r,e.fraction),xu.tickOffset+r.ticklen+r.font.size*Su+xu.labelOffset+i.currentValueTotalHeight)})}function Ru(t,e,r,n,i){var o=Math.round(n*(r.steps.length-1));o!==r.active&&Bu(t,e,r,o,!0,i)}function Bu(t,e,r,n,i,o){var a=r.active;r._input.active=r.active=n;var s=r.steps[r.active];e.call(ju,r,r.active/(r.steps.length-1),o),e.call(Pu,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:a}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=o):(e._nextMethod={step:s,doCallback:i,doTransition:o},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&_i.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function Fu(e,r,n){var i=n.node(),o=t.select(r);function a(){return n.data()[0]}e.on("mousedown",function(){var e=a();r.emit("plotly_sliderstart",{slider:e});var s=n.select("."+xu.gripRectClass);t.event.stopPropagation(),t.event.preventDefault(),s.call(Oe.fill,e.activebgcolor);var l=qu(e,t.mouse(i)[0]);Ru(r,n,e,l,!0),e._dragging=!0,o.on("mousemove",function(){var e=a(),o=qu(e,t.mouse(i)[0]);Ru(r,n,e,o,!1)}),o.on("mouseup",function(){var t=a();t._dragging=!1,s.call(Oe.fill,t.bgcolor),o.on("mouseup",null),o.on("mousemove",null),r.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function Nu(e,r){var n=e.selectAll("rect."+xu.tickRectClass).data(r.steps),i=r._dims;n.enter().append("rect").classed(xu.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(e,n){var o=n%i.labelStride==0,a=t.select(this);a.attr({height:o?r.ticklen:r.minorticklen}).call(Oe.fill,r.tickcolor),pn.setTranslate(a,Vu(r,n/(r.steps.length-1))-.5*r.tickwidth,(o?xu.tickOffset:xu.minorTickOffset)+i.currentValueTotalHeight)})}function ju(t,e,r,n){var i=t.select("rect."+xu.gripRectClass),o=Vu(e,r);if(!e._invokingCommand){var a=i;n&&e.transition.duration>0&&(a=a.transition().duration(e.transition.duration).ease(e.transition.easing)),a.attr("transform","translate("+(o-.5*xu.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function Vu(t,e){var r=t._dims;return r.inputAreaStart+xu.stepInset+(r.inputAreaLength-2*xu.stepInset)*Math.min(1,Math.max(0,e))}function qu(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-xu.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*xu.stepInset-2*r.inputAreaStart)))}function Uu(t,e,r){var n=r._dims,i=re.ensureSingle(t,"rect",xu.railTouchRectClass,function(n){n.call(Fu,e,t,r).style("pointer-events","all")});i.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,xu.tickOffset+r.ticklen+n.labelHeight)}).call(Oe.fill,r.bgcolor).attr("opacity",0),pn.setTranslate(i,0,n.currentValueTotalHeight)}function Hu(t,e){var r=e._dims,n=r.inputAreaLength-2*xu.railInset,i=re.ensureSingle(t,"rect",xu.railRectClass);i.attr({width:n,height:xu.railWidth,rx:xu.railRadius,ry:xu.railRadius,"shape-rendering":"crispEdges"}).call(Oe.stroke,e.bordercolor).call(Oe.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),pn.setTranslate(i,xu.railInset,.5*(r.inputAreaWidth-xu.railWidth)+r.currentValueTotalHeight)}var Zu={moduleType:"component",name:xu.name,layoutAttributes:ku,supplyLayoutDefaults:function(t,e){la(t,e,{name:Au,handleItemDefaults:Mu})},draw:function(e){var r=e._fullLayout,n=function(t,e){for(var r=t[xu.name],n=[],i=0;i0?[0]:[]);if(i.enter().append("g").classed(xu.containerClassName,!0).style("cursor","ew-resize"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(Pu,r).call(Hu,r).call(Ou,r).call(Nu,r).call(Uu,t,r).call(Iu,t,r);var n=r._dims;pn.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(ju,r,r.active/(r.steps.length-1),!1),e.call(Pu,r)}(e,t.select(this),r)}})}}},Gu=g.extendFlat,Wu=(0,yr.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:Gu({},bu,{}),font:M({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:z.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),Xu={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},Yu=Xu.name,Ju=Wu.buttons;function Ku(t,e,r){function n(r,n){return re.coerce(t,e,Wu,r,n)}n("visible",function(t,e){var r,n,i=t.buttons||[],o=e.buttons=[];function a(t,e){return re.coerce(r,n,Ju,t,e)}for(var s=0;s0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),re.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),re.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var $u=Qu;function Qu(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}Qu.barWidth=2,Qu.barLength=20,Qu.barRadius=2,Qu.barPad=1,Qu.barColor="#808BA4",Qu.prototype.enable=function(e,r,n){var i=this.gd._fullLayout,o=i.width,a=i.height;this.position=e;var s,l,u,c,p=this.position.l,h=this.position.w,f=this.position.t,d=this.position.h,y=this.position.direction,m="down"===y,g="left"===y,v="up"===y,_=h,x=d;m||g||"right"===y||v||(this.position.direction="down",m=!0),m||v?(l=(s=p)+_,m?(u=f,x=(c=Math.min(u+x,a))-u):x=(c=f+x)-(u=Math.max(c-x,0))):(c=(u=f)+x,g?_=(l=p+_)-(s=Math.max(l-_,0)):(s=p,_=(l=Math.min(s+_,o))-s)),this._box={l:s,t:u,w:_,h:x};var b=h>_,w=Qu.barLength+2*Qu.barPad,k=Qu.barWidth+2*Qu.barPad,A=p,T=f+d;T+k>a&&(T=a-k);var M=this.container.selectAll("rect.scrollbar-horizontal").data(b?[0]:[]);M.exit().on(".drag",null).remove(),M.enter().append("rect").classed("scrollbar-horizontal",!0).call(Oe.fill,Qu.barColor),b?(this.hbar=M.attr({rx:Qu.barRadius,ry:Qu.barRadius,x:A,y:T,width:w,height:k}),this._hbarXMin=A+w/2,this._hbarTranslateMax=_-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var S=d>x,C=Qu.barWidth+2*Qu.barPad,z=Qu.barLength+2*Qu.barPad,L=p+h,E=f;L+C>o&&(L=o-C);var P=this.container.selectAll("rect.scrollbar-vertical").data(S?[0]:[]);P.exit().on(".drag",null).remove(),P.enter().append("rect").classed("scrollbar-vertical",!0).call(Oe.fill,Qu.barColor),S?(this.vbar=P.attr({rx:Qu.barRadius,ry:Qu.barRadius,x:L,y:E,width:C,height:z}),this._vbarYMin=E+z/2,this._vbarTranslateMax=x-z):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var I=this.id,D=s-.5,O=S?l+C+.5:l+.5,R=u-.5,B=b?c+k+.5:c+.5,F=i._topdefs.selectAll("#"+I).data(b||S?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",I).append("rect"),b||S?(this._clipRect=F.select("rect").attr({x:Math.floor(D),y:Math.floor(R),width:Math.ceil(O)-Math.floor(D),height:Math.ceil(B)-Math.floor(R)}),this.container.call(pn.setClipUrl,I),this.bg.attr({x:p,y:f,width:h,height:d})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(pn.setClipUrl,null),delete this._clipRect),b||S){var N=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(N);var j=t.behavior.drag().on("dragstart",function(){t.event.sourceEvent.preventDefault(),t.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));b&&this.hbar.on(".drag",null).call(j),S&&this.vbar.on(".drag",null).call(j)}this.setTranslate(r,n)},Qu.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(pn.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},Qu.prototype._onBoxDrag=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e-=t.event.dx),this.vbar&&(r-=t.event.dy),this.setTranslate(e,r)},Qu.prototype._onBoxWheel=function(){var e=this.translateX,r=this.translateY;this.hbar&&(e+=t.event.deltaY),this.vbar&&(r+=t.event.deltaY),this.setTranslate(e,r)},Qu.prototype._onBarDrag=function(){var e=this.translateX,r=this.translateY;if(this.hbar){var n=e+this._hbarXMin,i=n+this._hbarTranslateMax;e=(re.constrain(t.event.x,n,i)-n)/(i-n)*(this.position.w-this._box.w)}if(this.vbar){var o=r+this._vbarYMin,a=o+this._vbarTranslateMax;r=(re.constrain(t.event.y,o,a)-o)/(a-o)*(this.position.h-this._box.h)}this.setTranslate(e,r)},Qu.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=re.constrain(t||0,0,r),e=re.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(pn.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(pn.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var o=e/n;this.vbar.call(pn.setTranslate,t,e+o*this._vbarTranslateMax)}};var tc=Or.LINE_SPACING;function ec(t){return t._index}function rc(t,e){return+t.attr(Xu.menuIndexAttrName)===e._index}function nc(t,e,r,n,i,o,a,s){e._input.active=e.active=a,"buttons"===e.type?oc(t,n,null,null,e):"dropdown"===e.type&&(i.attr(Xu.menuIndexAttrName,"-1"),ic(t,n,i,o,e),s||oc(t,n,i,o,e))}function ic(t,e,r,n,i){var o=re.ensureSingle(e,"g",Xu.headerClassName,function(t){t.style("pointer-events","all")}),a=i._dims,s=i.active,l=i.buttons[s]||Xu.blankHeaderOpts,u={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},c={width:a.headerWidth,height:a.headerHeight};o.call(ac,i,l,t).call(fc,i,u,c),re.ensureSingle(e,"text",Xu.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(pn.font,i.font).text(Xu.arrowSymbol[i.direction])}).attr({x:a.headerWidth-Xu.arrowOffsetX+i.pad.l,y:a.headerHeight/2+Xu.textOffsetY+i.pad.t}),o.on("click",function(){r.call(dc),r.attr(Xu.menuIndexAttrName,rc(r,i)?-1:String(i._index)),oc(t,e,r,n,i)}),o.on("mouseover",function(){o.call(cc)}),o.on("mouseout",function(){o.call(pc,i)}),pn.setTranslate(e,a.lx,a.ly)}function oc(e,r,n,i,o){n||(n=r).attr("pointer-events","all");var a=function(t){return-1==+t.attr(Xu.menuIndexAttrName)}(n)&&"buttons"!==o.type?[]:o.buttons,s="dropdown"===o.type?Xu.dropdownButtonClassName:Xu.buttonClassName,l=n.selectAll("g."+s).data(a),u=l.enter().append("g").classed(s,!0),c=l.exit();"dropdown"===o.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var p=0,h=0,f=o._dims,d=-1!==["up","down"].indexOf(o.direction);"dropdown"===o.type&&(d?h=f.headerHeight+Xu.gapButtonHeader:p=f.headerWidth+Xu.gapButtonHeader),"dropdown"===o.type&&"up"===o.direction&&(h=-Xu.gapButtonHeader+Xu.gapButton-f.openHeight),"dropdown"===o.type&&"left"===o.direction&&(p=-Xu.gapButtonHeader+Xu.gapButton-f.openWidth);var y={x:f.lx+p+o.pad.l,y:f.ly+h+o.pad.t,yPad:Xu.gapButton,xPad:Xu.gapButton,index:0},m={l:y.x+o.borderwidth,t:y.y+o.borderwidth};l.each(function(a,s){var u=t.select(this);u.call(ac,o,a,e).call(fc,o,y),u.on("click",function(){t.event.defaultPrevented||(nc(e,o,0,r,n,i,s),a.execute&&_i.executeAPICommand(e,a.method,a.args),e.emit("plotly_buttonclicked",{menu:o,button:a,active:o.active}))}),u.on("mouseover",function(){u.call(cc)}),u.on("mouseout",function(){u.call(pc,o),l.call(uc,o)})}),l.call(uc,o),d?(m.w=Math.max(f.openWidth,f.headerWidth),m.h=y.y-m.t):(m.w=y.x-m.l,m.h=Math.max(f.openHeight,f.headerHeight)),m.direction=o.direction,i&&(l.size()?function(t,e,r,n,i,o){var a,s,l,u=i.direction,c="up"===u||"down"===u,p=i._dims,h=i.active;if(c)for(s=0,l=0;l0?[0]:[]);if(i.enter().append("g").classed(Xu.containerClassName,!0).style("cursor","pointer"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nx.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&re.log("Clearing previous rejected promises from queue."),t._promises=[]},xc.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(_i.subplotsRegistry.cartesian||{}).attrRegex,i=(_i.subplotsRegistry.gl3d||{}).attrRegex,o=Object.keys(t);for(e=0;e3?(_.x=1.02,_.xanchor="left"):_.x<-2&&(_.x=-.02,_.xanchor="right"),_.y>3?(_.y=1.02,_.yanchor="bottom"):_.y<-2&&(_.y=-.02,_.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Oe.clean(t),t},xc.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),i=0;i0)return t.substr(0,e)}xc.hasParent=function(t,e){for(var r=zc(e);r;){if(r in t)return!0;r=zc(r)}return!1};var Lc=["x","y","z"];xc.clearAxisTypes=function(t,e,r){for(var n=0;n1&&b.warn("Full array edits are incompatible with other edits",i);var p=r[""][""];if(Dc(p))e.set(null);else{if(!Array.isArray(p))return b.warn("Unrecognized full array edit value",i,p),!0;e.set(p)}return!l&&(o(u,c),a(t),!0)}var h,f,d,y,m,g,v,_=Object.keys(r).map(Number).sort(Pc),x=e.get(),w=x||[],k=G(c,i).get(),T=[],M=-1,S=w.length;for(h=0;h<_.length;h++)if(y=r[d=_[h]],m=Object.keys(y),g=y[""],v=Ic(g),d<0||d>w.length-(v?0:1))b.warn("index out of range",i,d);else if(void 0!==g)m.length>1&&b.warn("Insertion & removal are incompatible with edits to the same index.",i,d),Dc(g)?T.push(d):v?("add"===g&&(g={}),w.splice(d,0,g),k&&k.splice(d,0,{})):b.warn("Unrecognized full object edit value",i,d,g),-1===M&&(M=d);else for(f=0;f=0;h--)w.splice(T[h],1),k&&k.splice(T[h],1);if(w.length?x||e.set(w):e.set(null),l)return!1;if(o(u,c),s!==A){var C;if(-1===M)C=_;else{for(S=Math.max(w.length,S),C=[],h=0;h<_.length&&!((d=_[h])>=M);h++)C.push(d);for(h=M;h1?(g=["toggleHover"],v=["resetViews"]):s?(m=["zoomInGeo","zoomOutGeo"],g=["hoverClosestGeo"],v=["resetGeo"]):a?(g=["hoverClosest3d"],v=["resetCameraDefault3d","resetCameraLastSave3d"]):p?(g=["toggleHover"],v=["resetViewMapbox"]):g=u?["hoverClosestGl2d"]:l?["hoverClosestPie"]:["toggleHover"],o&&(g=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!o&&!u||f||(m=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==v[0]&&(v=["resetScale2d"])),a?_=["zoom3d","pan3d","orbitRotation","tableRotation"]:(o||u)&&!f||c?_=["zoom2d","pan2d"]:p||s?_=["pan2d"]:h&&(_=["zoom2d"]),function(t){for(var e=!1,r=0;r$c*f)||g)for(r=0;rS&&LT&&(T=L);s/=(T-A)/(2*M),A=i.l2r(A),T=i.l2r(T),i.range=i._input.range=b=t[1]||i[1]<=t[0])&&o[0]e[0])return!0}return!1}(r,i,f)){var a=o.node(),s=e.bg=re.ensureSingle(o,"rect","bg");a.insertBefore(s.node(),a.childNodes[0])}else o.select("rect.bg").remove(),h.push(t),f.push([r,i])});var d=n._bgLayer.selectAll(".bg").data(h);return d.enter().append("rect").classed("bg",!0),d.exit().remove(),d.each(function(e){n._plots[e].bg=t.select(this)}),p.each(function(t){var e=n._plots[t],i=e.xaxis,u=e.yaxis;e.bg&&s&&e.bg.call(pn.setRect,i._offset-o,u._offset-o,i._length+2*o,u._length+2*o).call(Oe.fill,n.plot_bgcolor).style("stroke-width",0);var c,p,h=e.clipId="clip"+n._uid+t+"plot",f=re.ensureSingleById(n._clips,"clipPath",h,function(t){t.classed("plotclip",!0).append("rect")});for(e.clipRect=f.select("rect").attr({width:i._length,height:u._length}),pn.setTranslate(e.plot,i._offset,u._offset),e._hasClipOnAxisFalse?(c=null,p=h):(c=h,p=null),pn.setClipUrl(e.plot,c),r=0;r=0?u.angularAxis.domain:t.extent(_),A=Math.abs(_[1]-_[0]);b&&!x&&(A=0);var T=k.slice();w&&x&&(T[1]+=A);var M=u.angularAxis.ticksCount||4;M>8&&(M=M/(M/8)+M%8),u.angularAxis.ticksStep&&(M=(T[1]-T[0])/M);var S=u.angularAxis.ticksStep||(T[1]-T[0])/(M*(u.minorTicks+1));v&&(S=Math.max(Math.round(S),1)),T[2]||(T[2]=S);var C=t.range.apply(this,T);if(C=C.map(function(t,e){return parseFloat(t.toPrecision(12))}),i=t.scale.linear().domain(T.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),s.layout.angularAxis.domain=i.domain(),s.layout.angularAxis.endPadding=w?A:0,void 0===(e=t.select(this).select("svg.chart-root"))||e.empty()){var z=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),L=this.appendChild(this.ownerDocument.importNode(z.documentElement,!0));e=t.select(L)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var E,P=e.select(".chart-group"),I={fill:"none",stroke:u.tickColor},D={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){E=e.select(".legend-group").attr({transform:"translate("+[y,u.margin.top]+")"}).style({display:"block"});var O=c.map(function(t,e){var r=pp.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});pp.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:up({},pp.Legend.defaultConfig().legendConfig,{container:E,elements:O,reverseOrder:u.legend.reverseOrder})})();var R=E.node().getBBox();y=Math.min(u.width-R.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,y=Math.max(10,y),g=[u.margin.left+y,u.margin.top+y],n.range([0,y]),s.layout.radialAxis.domain=n.domain(),E.attr("transform","translate("+[g[0]+y,g[1]-y]+")")}else E=e.select(".legend-group").style({display:"none"});e.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),P.attr("transform","translate("+g+")").style({cursor:"crosshair"});var B=[(u.width-(u.margin.left+u.margin.right+2*y+(R?R.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*y))/2];if(B[0]=Math.max(0,B[0]),B[1]=Math.max(0,B[1]),e.select(".outer-group").attr("transform","translate("+B+")"),u.title){var F=e.select("g.title-group text").style(D).text(u.title),N=F.node().getBBox();F.attr({x:g[0]-N.width/2,y:g[1]-y-20})}var j=e.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var V=j.selectAll("circle.grid-circle").data(n.ticks(5));V.enter().append("circle").attr({class:"grid-circle"}).style(I),V.attr("r",n),V.exit().remove()}j.select("circle.outside-circle").attr({r:y}).style(I);var q=e.select("circle.background-circle").attr({r:y}).style({fill:u.backgroundColor,stroke:u.stroke});function U(t,e){return i(t)%360+u.orientation}if(u.radialAxis.visible){var H=t.svg.axis().scale(n).ticks(5).tickSize(5);j.call(H).attr({transform:"rotate("+u.radialAxis.orientation+")"}),j.selectAll(".domain").style(I),j.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(D).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,D["font-size"]]+")":"translate("+[0,D["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var Z=e.select(".angular.axis-group").selectAll("g.angular-tick").data(C),G=Z.enter().append("g").classed("angular-tick",!0);Z.attr({transform:function(t,e){return"rotate("+U(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),Z.exit().remove(),G.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(I),G.selectAll(".minor").style({stroke:u.minorTickColor}),Z.select("line.grid-line").attr({x1:u.tickLength?y-u.tickLength:0,x2:y}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),G.append("text").classed("axis-text",!0).style(D);var W=Z.select("text.axis-text").attr({x:y+u.labelOffset,dy:cp+"em",transform:function(t,e){var r=U(t),n=y+u.labelOffset,i=u.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":v?v[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(D);u.angularAxis.rewriteTicks&&W.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var X=t.max(P.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));E.attr({transform:"translate("+[y+X,u.margin.top]+")"});var Y=e.select("g.geometry-group").selectAll("g").size()>0,J=e.select("g.geometry-group").selectAll("g.geometry").data(c);if(J.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),J.exit().remove(),c[0]||Y){var K=[];c.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=i,r.container=J.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=u.orientation,r.direction=u.direction,r.index=e,K.push({data:t,geometryConfig:r})});var $=[];t.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(K).forEach(function(t,e){"unstacked"===t.key?$=$.concat(t.values.map(function(t,e){return[t]})):$.push(t.values)}),$.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return up(pp[r].defaultConfig(),t)});pp[r]().config(n)()})}var Q,tt,et=e.select(".guides-group"),rt=e.select(".tooltips-group"),nt=pp.tooltipPanel().config({container:rt,fontSize:8})(),it=pp.tooltipPanel().config({container:rt,fontSize:8})(),ot=pp.tooltipPanel().config({container:rt,hasTick:!0})();if(!x){var at=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});P.on("mousemove.angular-guide",function(t,e){var r=pp.util.getMousePos(q).angle;at.attr({x2:-y,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;Q=i.invert(n);var o=pp.util.convertToCartesian(y+12,r+180);nt.text(pp.util.round(Q)).move([o[0]+g[0],o[1]+g[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var st=et.select("circle").style({stroke:"grey",fill:"none"});P.on("mousemove.radial-guide",function(t,e){var r=pp.util.getMousePos(q).radius;st.attr({r:r}).style({opacity:.5}),tt=n.invert(pp.util.getMousePos(q).radius);var i=pp.util.convertToCartesian(r,u.radialAxis.orientation);it.text(pp.util.round(tt)).move([i[0]+g[0],i[1]+g[1]])}).on("mouseout.radial-guide",function(t,e){st.style({opacity:0}),ot.hide(),nt.hide(),it.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var i=t.select(this),o=this.style.fill,a="black",s=this.style.opacity||1;if(i.attr({"data-opacity":s}),o&&"none"!==o){i.attr({"data-fill":o}),a=t.hsl(o).darker().toString(),i.style({fill:a,opacity:1});var l={t:pp.util.round(r[0]),r:pp.util.round(r[1])};x&&(l.t=v[r[0]]);var u="t: "+l.t+", r: "+l.r,c=this.getBoundingClientRect(),p=e.node().getBoundingClientRect(),h=[c.left+c.width/2-B[0]-p.left,c.top+c.height/2-B[1]-p.top];ot.config({color:a}).text(u),ot.move(h)}else o=this.style.stroke||"black",i.attr({"data-stroke":o}),a=t.hsl(o).darker().toString(),i.style({stroke:a,opacity:1})}).on("mousemove.tooltip",function(e,r){if(0!=t.event.which)return!1;t.select(this).attr("data-fill")&&ot.show()}).on("mouseout.tooltip",function(e,r){ot.hide();var n=t.select(this),i=n.attr("data-fill");i?n.style({fill:i,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(a),this},u.config=function(t){if(!arguments.length)return o;var e=pp.util.cloneJson(t);return e.data.forEach(function(t,e){o.data[e]||(o.data[e]={}),up(o.data[e],pp.Axis.defaultConfig().data[0]),up(o.data[e],t)}),up(o.layout,pp.Axis.defaultConfig().layout),up(o.layout,e.layout),this},u.getLiveConfig=function(){return s},u.getinputConfig=function(){return a},u.radialScale=function(t){return n},u.angularScale=function(t){return i},u.svg=function(){return e},t.rebind(u,l,"on"),u},pp.Axis.defaultConfig=function(e,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:t.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},pp.util={},pp.DATAEXTENT="dataExtent",pp.AREA="AreaChart",pp.LINE="LinePlot",pp.DOT="DotPlot",pp.BAR="BarChart",pp.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},pp.util._extend=function(t,e){for(var r in t)e[r]=t[r]},pp.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},pp.util.dataFromEquation2=function(e,r){var n=r||6;return t.range(0,360+n,n).map(function(t,r){var n=t*Math.PI/180;return[t,e(n)]})},pp.util.dataFromEquation=function(e,r,n){var i=r||6,o=[],a=[];t.range(0,360+i,i).forEach(function(t,r){var n=t*Math.PI/180,i=e(n);o.push(t),a.push(i)});var s={t:o,r:a};return n&&(s.name=n),s},pp.util.ensureArray=function(e,r){if(void 0===e)return null;var n=[].concat(e);return t.range(r).map(function(t,e){return n[e]||n[0]})},pp.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=pp.util.ensureArray(t[e],r)}),t},pp.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},pp.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},pp.util.sumArrays=function(e,r){return t.zip(e,r).map(function(e,r){return t.sum(e)})},pp.util.arrayLast=function(t){return t[t.length-1]},pp.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},pp.util.flattenArray=function(t){for(var e=[];!pp.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},pp.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},pp.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},pp.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},pp.util.getMousePos=function(e){var r=t.mouse(e.node()),n=r[0],i=r[1],o={};return o.x=n,o.y=i,o.pos=r,o.angle=180*(Math.atan2(i,n)+Math.PI)/Math.PI,o.radius=Math.sqrt(n*n+i*i),o},pp.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,o=t.length;i0)){var l=t.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:c(s),transform:function(t,e){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return d.fill(n,i,o)},"fill-opacity":0,stroke:function(t,e){return d.stroke(n,i,o)},"stroke-width":function(t,e){return d["stroke-width"](n,i,o)},"stroke-dasharray":function(t,e){return d["stroke-dasharray"](n,i,o)},opacity:function(t,e){return d.opacity(n,i,o)},display:function(t,e){return d.display(n,i,o)}})}};var p=r.angularScale.range(),h=Math.abs(p[1]-p[0])/a[0].length*Math.PI/180,f=t.svg.arc().startAngle(function(t){return-h/2}).endAngle(function(t){return h/2}).innerRadius(function(t){return r.radialScale(l+(t[2]||0))}).outerRadius(function(t){return r.radialScale(l+(t[2]||0))+r.radialScale(t[1])});u.arc=function(e,n,i){t.select(this).attr({class:"mark arc",d:f,transform:function(t,e){return"rotate("+(r.orientation+s(t[0])+90)+")"}})};var d={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,i){return n[e[i].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return void 0===e[n].data.visible||e[n].data.visible?"block":"none"}},y=t.select(this).selectAll("g.layer").data(a);y.enter().append("g").attr({class:"layer"});var m=y.selectAll("path.mark").data(function(t,e){return t});m.enter().append("path").attr({class:"mark"}),m.style(d).each(u[r.geometryType]),m.exit().remove(),y.exit().remove()})}return i.config=function(t){return arguments.length?(t.forEach(function(t,r){e[r]||(e[r]={}),up(e[r],pp.PolyChart.defaultConfig()),up(e[r],t)}),this):e},i.getColorScale=function(){},t.rebind(i,r,"on"),i},pp.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:t.scale.category20()}}},pp.BarChart=function(){return pp.PolyChart()},pp.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},pp.AreaChart=function(){return pp.PolyChart()},pp.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},pp.DotPlot=function(){return pp.PolyChart()},pp.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},pp.LinePlot=function(){return pp.PolyChart()},pp.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},pp.Legend=function(){var e=pp.Legend.defaultConfig(),r=t.dispatch("hover");function n(){var r=e.legendConfig,i=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=up({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),o=t.merge(i);o=o.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||void 0===r.elements[e].visibleInLegend)}),r.reverseOrder&&(o=o.reverse());var a=r.container;("string"==typeof a||a.nodeName)&&(a=t.select(a));var s=o.map(function(t,e){return t.color}),l=r.fontSize,u=null==r.isContinuous?"number"==typeof o[0]:r.isContinuous,c=u?r.height:l*o.length,p=a.classed("legend-group",!0).selectAll("svg").data([0]),h=p.enter().append("svg").attr({width:300,height:c+l,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});h.append("g").classed("legend-axis",!0),h.append("g").classed("legend-marks",!0);var f=t.range(o.length),d=t.scale[u?"linear":"ordinal"]().domain(f).range(s),y=t.scale[u?"linear":"ordinal"]().domain(f)[u?"range":"rangePoints"]([0,c]);if(u){var m=p.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);m.enter().append("stop"),m.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),p.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var g=p.select(".legend-marks").selectAll("path.legend-mark").data(o);g.enter().append("path").classed("legend-mark",!0),g.attr({transform:function(t,e){return"translate("+[l/2,y(e)+l/2]+")"},d:function(e,r){var n,i,o,a=e.symbol;return o=3*(i=l),"line"===(n=a)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=t.svg.symbolTypes.indexOf(n)?t.svg.symbol().type(n).size(o)():t.svg.symbol().type("square").size(o)()},fill:function(t,e){return d(e)}}),g.exit().remove()}var v=t.svg.axis().scale(y).orient("right"),_=p.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:l,l/2]+")"}).call(v);return _.selectAll(".domain").style({fill:"none",stroke:"none"}),_.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),_.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return o[e].name}),n}return n.config=function(t){return arguments.length?(up(e,t),this):e},t.rebind(n,r,"on"),n},pp.Legend.defaultConfig=function(t,e){return{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:!1}}},pp.tooltipPanel=function(){var e,r,n,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},o="tooltip-"+pp.tooltipPanel.uid++,a=10,s=function(){var t=(e=i.container.selectAll("g."+o).data([0])).enter().append("g").classed(o,!0).style({"pointer-events":"none",display:"none"});return n=t.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=t.append("text").attr({dx:i.padding+a,dy:.3*+i.fontSize}),s};return s.text=function(o){var l=t.hsl(i.color).l,u=l>=.5?"#aaa":"white",c=l>=.5?"black":"white",p=o||"";r.style({fill:c,"font-size":i.fontSize+"px"}).text(p);var h=i.padding,f=r.node().getBBox(),d={fill:i.color,stroke:u,"stroke-width":"2px"},y=f.width+2*h+a,m=f.height+2*h;return n.attr({d:"M"+[[a,-m/2],[a,-m/4],[i.hasTick?0:a,0],[a,m/4],[a,m/2],[y,m/2],[y,-m/2]].join("L")+"Z"}).style(d),e.attr({transform:"translate("+[a,-m/2+2*h]+")"}),e.style({display:"block"}),s},s.move=function(t){if(e)return e.attr({transform:"translate("+[t[0],t[1]]+")"}).style({display:"block"}),s},s.hide=function(){if(e)return e.style({display:"none"}),s},s.show=function(){if(e)return e.style({display:"block"}),s},s.config=function(t){return up(i,t),s},s},pp.tooltipPanel.uid=1,pp.adapter={},pp.adapter.plotly=function(){var e={convert:function(e,r){var n={};if(e.data&&(n.data=e.data.map(function(t,e){var n=up({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,e){pp.util.translator.apply(null,t.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&e.layout&&"stack"===e.layout.barmode)){var i=pp.util.duplicates(n.data.map(function(t,e){return t.geometry}));n.data.forEach(function(t,e){var r=i.indexOf(t.geometry);-1!=r&&(n.data[e].groupId=r)})}if(e.layout){var o=up({},e.layout);if([[o,["plot_bgcolor"],["backgroundColor"]],[o,["showlegend"],["showLegend"]],[o,["radialaxis"],["radialAxis"]],[o,["angularaxis"],["angularAxis"]],[o.angularaxis,["showline"],["gridLinesVisible"]],[o.angularaxis,["showticklabels"],["labelsVisible"]],[o.angularaxis,["nticks"],["ticksCount"]],[o.angularaxis,["tickorientation"],["tickOrientation"]],[o.angularaxis,["ticksuffix"],["ticksSuffix"]],[o.angularaxis,["range"],["domain"]],[o.angularaxis,["endpadding"],["endPadding"]],[o.radialaxis,["showline"],["gridLinesVisible"]],[o.radialaxis,["tickorientation"],["tickOrientation"]],[o.radialaxis,["ticksuffix"],["ticksSuffix"]],[o.radialaxis,["range"],["domain"]],[o.angularAxis,["showline"],["gridLinesVisible"]],[o.angularAxis,["showticklabels"],["labelsVisible"]],[o.angularAxis,["nticks"],["ticksCount"]],[o.angularAxis,["tickorientation"],["tickOrientation"]],[o.angularAxis,["ticksuffix"],["ticksSuffix"]],[o.angularAxis,["range"],["domain"]],[o.angularAxis,["endpadding"],["endPadding"]],[o.radialAxis,["showline"],["gridLinesVisible"]],[o.radialAxis,["tickorientation"],["tickOrientation"]],[o.radialAxis,["ticksuffix"],["ticksSuffix"]],[o.radialAxis,["range"],["domain"]],[o.font,["outlinecolor"],["outlineColor"]],[o.legend,["traceorder"],["reverseOrder"]],[o,["labeloffset"],["labelOffset"]],[o,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,e){pp.util.translator.apply(null,t.concat(r))}),r?(void 0!==o.tickLength&&(o.angularaxis.ticklen=o.tickLength,delete o.tickLength),o.tickColor&&(o.angularaxis.tickcolor=o.tickColor,delete o.tickColor)):(o.angularAxis&&void 0!==o.angularAxis.ticklen&&(o.tickLength=o.angularAxis.ticklen),o.angularAxis&&void 0!==o.angularAxis.tickcolor&&(o.tickColor=o.angularAxis.tickcolor)),o.legend&&"boolean"!=typeof o.legend.reverseOrder&&(o.legend.reverseOrder="normal"!=o.legend.reverseOrder),o.legend&&"boolean"==typeof o.legend.traceorder&&(o.legend.traceorder=o.legend.traceorder?"reversed":"normal",delete o.legend.reverseOrder),o.margin&&void 0!==o.margin.t){var a=["t","r","b","l","pad"],s=["top","right","bottom","left","pad"],l={};t.entries(o.margin).forEach(function(t,e){l[s[a.indexOf(t.key)]]=t.value}),o.margin=l}r&&(delete o.needsEndSpacing,delete o.minorTickColor,delete o.minorTicks,delete o.angularaxis.ticksCount,delete o.angularaxis.ticksCount,delete o.angularaxis.ticksStep,delete o.angularaxis.rewriteTicks,delete o.angularaxis.nticks,delete o.radialaxis.ticksCount,delete o.radialaxis.ticksCount,delete o.radialaxis.ticksStep,delete o.radialaxis.rewriteTicks,delete o.radialaxis.nticks),n.layout=o}return n}};return e};var hp,fp=re.extendDeepAll,dp=hp={};dp.framework=function(e){var r,n,i,o,a,s=new function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?fp(r,n):n,i||(i=lp.Axis()),o=lp.adapter.plotly().convert(r),i.config(o).render(a),e.data=r.data,e.layout=r.layout,dp.fillLayout(e),r}return l.isPolar=!0,l.svg=function(){return i.svg()},l.getConfig=function(){return r},l.getLiveConfig=function(){return lp.adapter.plotly().convert(i.getLiveConfig(),!0)},l.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},l.setUndoPoint=function(){var t,e,i=this,o=lp.util.cloneJson(r);t=o,e=n,s.add({undo:function(){e&&i(e)},redo:function(){i(t)}}),n=lp.util.cloneJson(o)},l.undo=function(){s.undo()},l.redo=function(){s.redo()},l},dp.fillLayout=function(e){var r=t.select(e).selectAll(".plot-container"),n=r.selectAll(".svg-container"),i=e.framework&&e.framework.svg&&e.framework.svg(),o={width:800,height:600,paper_bgcolor:Oe.background,_container:r,_paperdiv:n,_paper:i};e._fullLayout=fp(o,e.layout)};var yp={};(yp=lp).manager=hp;var mp={},gp=Ml.initInteractions,vp=Ie.AX_NAME_PATTERN,_p=0;function xp(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){re.error(t)}}function bp(t,e){xp(t,Oe.combine(e,"white"))}function wp(t,e){t._context||(t._context=re.extendDeep({},x));var r,n,i,o=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function Tp(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),Ap(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&Ap(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function Mp(t,r,n,i,o){!function(t,e,r,n){var i=re.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!re.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var o in Ap(t,r,"indices"),e){if(!Array.isArray(e[o])||e[o].length!==r.length)throw new Error("attribute "+o+" must be an array of length equal to indices array length");if(i&&(!(o in n)||!Array.isArray(n[o])||n[o].length!==e[o].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,r,n,i);for(var a=function(t,r,n,i){var o,a,s,l,u,c=re.isPlainObject(i),p=[];for(var h in Array.isArray(n)||(n=[n]),n=kp(n,t.data.length-1),r)for(var f=0;f0&&"string"!=typeof b.parts[k-1];)A--;var T=b.parts[A],M=b.parts[A-1]+"."+T,S=b.parts.slice(0,A).join("."),C=re.nestedProperty(t.layout,S).get(),z=re.nestedProperty(a,S).get(),L=b.get();if(void 0!==w){d[x]=w,y[x]="reverse"===T?w:Cp(L);var E=Qn.getLayoutValObject(a,b.parts);if(E&&E.impliedEdits&&null!==w)for(var I in E.impliedEdits)m(re.relativeAttr(x,I),E.impliedEdits[I]);if(-1!==["width","height"].indexOf(x)&&null===w)a[x]=t._initialAutoSize[x];else if(M.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))_(M),re.nestedProperty(a,S+"._inputRange").set(null);else if(M.match(/^[xyz]axis[0-9]*\.autorange$/)){_(M),re.nestedProperty(a,S+"._inputRange").set(null);var D=re.nestedProperty(a,S).get();D._inputDomain&&(D._input.domain=D._inputDomain.slice())}else M.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&re.nestedProperty(a,S+"._inputDomain").set(null);if("type"===T){var O=C,R="linear"===z.type&&"log"===w,B="log"===z.type&&"linear"===w;if(R||B){if(O&&O.range)if(z.autorange)R&&(O.range=O.range[1]>O.range[0]?[1,2]:[2,1]);else{var F=O.range[0],N=O.range[1];R?(F<=0&&N<=0&&m(S+".autorange",!0),F<=0?F=N/1e6:N<=0&&(N=F/1e6),m(S+".range[0]",Math.log(F)/Math.LN10),m(S+".range[1]",Math.log(N)/Math.LN10)):(m(S+".range[0]",Math.pow(10,F)),m(S+".range[1]",Math.pow(10,N)))}else m(S+".autorange",!0);Array.isArray(a._subplots.polar)&&a._subplots.polar.length&&a[b.parts[0]]&&"radialaxis"===b.parts[1]&&delete a[b.parts[0]]._subplot.viewInitial["radialaxis.range"],P.getComponentMethod("annotations","convertCoords")(t,z,w,m),P.getComponentMethod("images","convertCoords")(t,z,w,m)}else m(S+".autorange",!0),m(S+".range",null);re.nestedProperty(a,S+"._inputRange").set(null)}else if(T.match(vp)){var j=re.nestedProperty(a,x).get(),V=(w||{}).type;V&&"-"!==V||(V="linear"),P.getComponentMethod("annotations","convertCoords")(t,j,V,m),P.getComponentMethod("images","convertCoords")(t,j,V,m)}var q=Ec.containerArrayMatch(x);if(q){r=q.array,n=q.index;var U=q.property,H=(re.nestedProperty(o,r)||[])[n]||{},Z=H,G=E||{editType:"calc"},W=-1!==G.editType.indexOf("calcIfAutorange");""===n?(W?f.calc=!0:yr.update(f,G),W=!1):""===U&&(Z=w,Ec.isAddVal(w)?y[x]=null:Ec.isRemoveVal(w)?(y[x]=H,Z=H):re.warn("unrecognized full object value",e)),W&&(Pp(t,Z,"x")||Pp(t,Z,"y"))?f.calc=!0:yr.update(f,G),u[r]||(u[r]={});var X=u[r][n];X||(X=u[r][n]={}),X[U]=w,delete e[x]}else"reverse"===T?(C.range?C.range.reverse():(m(S+".autorange",!0),C.range=[1,0]),z.autorange?f.calc=!0:f.plot=!0):(a._has("scatter-like")&&a._has("regl")&&"dragmode"===x&&("lasso"===w||"select"===w)&&"lasso"!==L&&"select"!==L?f.plot=!0:E?yr.update(f,E):f.calc=!0,b.set(w))}}for(r in u){Ec.applyContainerArrayChanges(t,re.nestedProperty(o,r),u[r],f)||(f.plot=!0)}var Y=a._axisConstraintGroups||[];for(g in v)for(n=0;n=0&&r=0&&r=i.length?i[0]:i[t]:i}function s(t){return Array.isArray(o)?t>=o.length?o[0]:o[t]:o}function l(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(o,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,_i.transition(t,e.frame.data,e.frame.layout,xc.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function p(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var h,f,d=0;function y(t){return Array.isArray(i)?d>=i.length?t.transitionOpts=i[d]:t.transitionOpts=i[0]:t.transitionOpts=i,d++,t}var m=[],g=void 0===e||null===e,v=Array.isArray(e);if(!g&&!v&&re.isPlainObject(e))m.push({type:"object",data:y(re.extendFlat({},e))});else if(g||-1!==["string","number"].indexOf(typeof e))for(h=0;h0&&bb)&&w.push(f);m=w}}m.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(re.isPlainObject(e[n])){var h=e[n].name,f=(l[h]||p[h]||{}).name,d=e[n].name,y=l[f]||p[f];f&&d&&"number"==typeof d&&y&&_p<5&&(_p++,re.warn('addFrames: overwriting frame "'+(l[f]||p[f]).name+'" with a frame whose name of type "number" also equates to "'+f+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===_p&&re.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),p[h]={name:h},c.push({frame:_i.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=c[n].frame).name&&re.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;l[i.name="frame "+t._transitionData._counter++];);if(l[i.name]){for(o=0;o=0;r--)n=e[r],o.push({type:"delete",index:n}),a.unshift({type:"insert",index:n,value:i[n]});var s=_i.modifyFrames,l=_i.modifyFrames,u=[t,a],c=[t,o];return vc&&vc.add(t,s,u,l,c),_i.modifyFrames(t,o)},mp.purge=function(t){var e=(t=re.getGraphDiv(t))._fullLayout||{},r=t._fullData||[],n=t.calcdata||[];return _i.cleanPlot([],{},r,e,n),_i.purge(t),tr.purge(t),e._container&&e._container.remove(),delete t._context,t};var Op={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},Rp=Xe.EventEmitter;var Bp=function(t){var e=t.emitter||new Rp,r=new Promise(function(n,i){var o=window.Image,a=t.svg,s=t.format||"png";if(re.isIE()&&"svg"!==s){var l=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(l),t.promise?r:e.emit("error",l)}var u=t.canvas,c=t.scale||1,p=c*(t.width||300),h=c*(t.height||150),f=u.getContext("2d"),d=new o,y="data:image/svg+xml,"+encodeURIComponent(a);u.width=p,u.height=h,d.onload=function(){var r;switch("svg"!==s&&f.drawImage(d,0,0,p,h),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=y;break;default:var o="Image format is not jpeg, png, svg or webp.";if(i(new Error(o)),!t.promise)return e.emit("error",o)}n(r),t.promise||e.emit("success",r)},d.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},d.src=y});return t.promise?r:e},Fp=/"/g,Np=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var jp=function(e,r,n){var i,o=e._fullLayout,a=o._paper,s=o._toppaper,l=o.width,u=o.height;a.insert("rect",":first-child").call(pn.setRect,0,0,l,u).call(Oe.fill,o.paper_bgcolor);var c=o._basePlotModules||[];for(i=0;i")?"":r.html(t).text()});return r.remove(),n}(y),y=(y=y.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(Np,"'"),re.isIE()&&(y=(y=(y=y.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),y},Vp={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},qp=/^data:image\/\w+;base64,/;var Up=function(t,e){var r,n,i;function o(t){return!(t in e)||re.validate(e[t],Vp[t])}if(e=e||{},re.isPlainObject(t)?(r=t.data||[],n=t.layout||{},i=t.config||{}):(t=re.getGraphDiv(t),r=re.extendDeep([],t.data),n=re.extendDeep({},t.layout),i=t._context),!o("width")||!o("height"))throw new Error("Height and width should be pixel values.");if(!o("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var a={};function s(t,r){return re.coerce(e,a,Vp,t,r)}var l=s("format"),u=s("width"),c=s("height"),p=s("scale"),h=s("setBackground"),f=s("imageDataOnly"),d=document.createElement("div");d.style.position="absolute",d.style.left="-5000px",document.body.appendChild(d);var y=re.extendFlat({},n);u&&(y.width=u),c&&(y.height=c);var m=re.extendFlat({},i,{staticPlot:!0,setBackground:h}),g=Op.getRedrawFunc(d);function v(){return new Promise(function(t){setTimeout(t,Op.getDelay(d._fullLayout))})}function _(){return new Promise(function(t,e){var r=jp(d,l,p),n=d._fullLayout.width,i=d._fullLayout.height;if(mp.purge(d),document.body.removeChild(d),"svg"===l)return t(f?r:"data:image/svg+xml,"+encodeURIComponent(r));var o=document.createElement("canvas");o.id=re.randstr(),Bp({format:l,width:n,height:i,scale:p,canvas:o,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){mp.plot(d,r,y,m).then(g).then(v).then(_).then(function(e){t(function(t){return f?t.replace(qp,""):t}(e))}).catch(function(t){e(t)})})},Hp=re.isPlainObject,Zp=Array.isArray,Gp=re.isArrayOrTypedArray;function Wp(t,e,r,n,i,o){o=o||[];for(var a=Object.keys(t),s=0;sp.length&&n.push(Jp("unused",i,u.concat(p.length)));var m,g,v,_,x,b=p.length,w=Array.isArray(y);if(w&&(b=Math.min(b,y.length)),2===h.dimensions)for(g=0;gp[g].length&&n.push(Jp("unused",i,u.concat(g,p[g].length)));var k=p[g].length;for(m=0;m<(w?Math.min(k,y[g].length):k);m++)v=w?y[g][m]:y,_=c[g][m],x=p[g][m],re.validate(_,v)?x!==_&&x!==+_&&n.push(Jp("dynamic",i,u.concat(g,m),_,x)):n.push(Jp("value",i,u.concat(g,m),_))}else n.push(Jp("array",i,u.concat(g),c[g]));else for(g=0;g1&&o.push(Jp("object","layout"))),_i.supplyDefaults(a);for(var s=a._fullData,l=r.length,u=0;u-1&&(s[u[r]].title="");for(r=0;r0?u>=m:u<=m));c++)u>v&&u<_&&h.push(u);if("function"==typeof n.fillcolor)if(n.filllevels)for(m=n.filllevels.end+n.filllevels.size/100,g=n.filllevels.size,c=0;c<1e5&&(u=n.filllevels.start+c*g,!(g>0?u>=m:u<=m));c++)u>p[0]&&u1){var q=Math.pow(10,Math.floor(Math.log(V)/Math.LN10));N*=q*re.roundUp(V/q,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(B.tick0=0)}B.dtick=N}B.domain=[I+z,I+M-z],B.setScale();var U=re.ensureSingle(a._infolayer,"g",r,function(e){e.classed(bh.colorbar,!0).each(function(){var e=t.select(this);e.append("rect").classed(bh.cbbg,!0),e.append("g").classed(bh.cbfills,!0),e.append("g").classed(bh.cblines,!0),e.append("g").classed(bh.cbaxis,!0).classed(bh.crisp,!0),e.append("g").classed(bh.cbtitleunshift,!0).append("g").classed(bh.cbtitle,!0),e.append("rect").classed(bh.cboutline,!0),e.select(".cbtitle").datum(0)})});U.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var H=U.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");B._axislayer=U.select(".cbaxis");var Z=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var G,W=l.l+(n.x+S)*l.w,X=B.titlefont.size;G="top"===n.titleside?(1-(I+M-z))*l.h+l.t+3+.75*X:(1-(I+z))*l.h+l.t-3-.25*X,tt(B._id+"title",{attributes:{x:W,y:G,"text-anchor":"start"}})}var Y,J,K,$=re.syncOrAsync([_i.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=U.select(".cbtitle"),i=r.select("text"),o=[-n.outlinewidth/2,n.outlinewidth/2],u=r.select(".h"+B._id+"title-math-group").node(),c=15.6;if(i.node()&&(c=parseInt(i.node().style.fontSize,10)*xh),u?(Z=pn.bBox(u).height)>c&&(o[1]-=(Z-c)/2):i.node()&&!i.classed(bh.jsPlaceholder)&&(Z=pn.bBox(i.node()).height),Z){if(Z+=5,"top"===n.titleside)B.domain[1]-=Z/l.h,o[1]*=-1;else{B.domain[0]+=Z/l.h;var m=Fr.lineCount(i);o[1]+=(1-m)*c}r.attr("transform","translate("+o+")"),B.setScale()}}U.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-B.domain[1]))+")"),B._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var g=U.select(".cbfills").selectAll("rect.cbfill").data(f);g.enter().append("rect").classed(bh.cbfill,!0).style("stroke","none"),g.exit().remove(),g.each(function(e,r){var n=[0===r?p[0]:(f[r]+f[r-1])/2,r===f.length-1?p[1]:(f[r]+f[r+1])/2].map(B.c2p).map(Math.round);r!==f.length-1&&(n[1]+=n[1]>n[0]?1:-1);var i=y(e).replace("e-",""),o=s(i).toHexString();t.select(this).attr({x:L,width:Math.max(k,2),y:t.min(n),height:Math.max(t.max(n)-t.min(n),2),fill:o})});var v=U.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?h:[]);return v.enter().append("path").classed(bh.cbline,!0),v.exit().remove(),v.each(function(e){t.select(this).attr("d","M"+L+","+(Math.round(B.c2p(e))+n.line.width/2%1)+"h"+k).call(pn.lineGroupStyle,n.line.width,d(e),n.line.dash)}),B._axislayer.selectAll("g."+B._id+"tick,path").remove(),B._pos=L+k+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),B.side="right",re.syncOrAsync([function(){return eo.doTicks(e,B,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=B.titlefont.size,i=B._offset+B._length/2,o=l.l+(B.position||0)*l.w+("right"===B.side?10+r*(B.showticklabels?1:.5):-10-r*(B.showticklabels?.5:0));tt("h"+B._id+"title",{avoid:{selection:t.select(e).selectAll("g."+B._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:a.width},attributes:{x:o,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},_i.previousPromises,function(){var t=k+n.outlinewidth/2+pn.bBox(B._axislayer.node()).width;if((x=H.select("text")).node()&&!x.classed(bh.jsPlaceholder)){var i,o=H.select(".h"+B._id+"title-math-group").node();i=o&&-1!==["top","bottom"].indexOf(n.titleside)?pn.bBox(o).width:pn.bBox(H.node()).right-L-l.l,t=Math.max(t,i)}var a=2*n.xpad+t+n.borderwidth+n.outlinewidth/2,s=D-O;U.select(".cbbg").attr({x:L-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:O-C,width:Math.max(a,2),height:Math.max(s+2*C,2)}).call(Oe.fill,n.bgcolor).call(Oe.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),U.selectAll(".cboutline").attr({x:L,y:O+n.ypad+("top"===n.titleside?Z:0),width:Math.max(k,2),height:Math.max(s-2*n.ypad-Z,2)}).call(Oe.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var u=({center:.5,right:1}[n.xanchor]||0)*a;U.attr("transform","translate("+(l.l-u)+","+l.t+")"),_i.autoMargin(e,r,{x:n.x,y:n.y,l:a*({right:1,center:.5}[n.xanchor]||0),r:a*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],e);return $&&$.then&&(e._promises||[]).push($),e._context.edits.colorbarPosition&&rr.init({element:U.node(),gd:e,prepFn:function(){Y=U.attr("transform"),On(U)},moveFn:function(t,e){U.attr("transform",Y+" translate("+t+","+e+")"),J=rr.align(E+t/l.w,A,0,1,n.xanchor),K=rr.align(I-e/l.h,M,0,1,n.yanchor);var r=rr.getCursor(J,K,n.xanchor,n.yanchor);On(U,r)},doneFn:function(){On(U),void 0!==J&&void 0!==K&&P.call("restyle",e,{"colorbar.x":J,"colorbar.y":K},o().index)}}),$}function Q(t,e){return re.coerce(R,B,wr,t,e)}function tt(t,r){var n,i=o();n=P.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var s={propContainer:B,propName:n,traceIndex:i.index,placeholder:a._dfltTitle.colorbar,containerGroup:U.select(".cbtitle")},l="h"===t.charAt(0)?t.substr(1):"h"+t;U.selectAll("."+l+",."+l+"-math-group").remove(),Ii.draw(e,t,_h(s,r||{}))}a._infolayer.selectAll("g."+r).remove()}function o(){var t,n,i=r.substr(2);for(t=0;tV||t[1]U)return[Oh(t[0],j,V),Oh(t[1],q,U)]}function G(t,e){return t[0]===e[0]&&(t[0]===j||t[0]===V)||(t[1]===e[1]&&(t[1]===q||t[1]===U)||void 0)}function W(t,e,r){return function(n,i){var o=Z(n),a=Z(i),s=[];if(o&&a&&G(o,a))return s;o&&s.push(o),a&&s.push(a);var l=2*re.constrain((n[t]+i[t])/2,e,r)-((o||n)[t]+(a||i)[t]);l&&((o&&a?l>0==o[t]>a[t]?o:a:o||a)[t]+=l);return s}}function X(t){var e=t[0],r=t[1],n=e===S[C-1][0],i=r===S[C-1][1];if(!n||!i)if(C>1){var o=e===S[C-2][0],a=r===S[C-2][1];n&&(e===j||e===V)&&o?a?C--:S[C-1]=t:i&&(r===q||r===U)&&a?o?C--:S[C-1]=t:S[C++]=t}else S[C++]=t}function Y(t){S[C-1][0]!==t[0]&&S[C-1][1]!==t[1]&&X([D,O]),X(t),R=null,D=O=0}function J(t){if(P=t[0]V?V:0,I=t[1]U?U:0,P||I){if(C)if(R){var e=F(R,t);e.length>1&&(Y(e[0]),S[C++]=e[1])}else B=F(S[C-1],t)[0],S[C++]=B;else S[C++]=[P||t[0],I||t[1]];var r=S[C-1];P&&I&&(r[0]!==P||r[1]!==I)?(R&&(D!==P&&O!==I?X(D&&O?(n=R,o=(i=t)[0]-n[0],a=(i[1]-n[1])/o,(n[1]*i[0]-i[1]*n[0])/o>0?[a>0?j:V,U]:[a>0?V:j,q]):[D||P,O||I]):D&&O&&X([D,O])),X([P,I])):D-P&&O-I&&X([P||D,I||O]),R=t,D=P,O=I}else R&&Y(F(R,t)[0]),S[C++]=t;var n,i,o,a}for("linear"===k||"spline"===k?F=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var o=H[i],a=Dh(t[0],t[1],e[0],e[1],o[0],o[1],o[2],o[3]);a&&(!n||Math.abs(a.x-r[0][0])>1||Math.abs(a.y-r[0][1])>1)&&(a=[a.x,a.y],n&&E(a,t)L(s))break;i=s,(d=c[0]*u[0]+c[1]*u[1])>h?(h=d,o=s,l=!1):d=t.length||!s)break;J(s),n=s}}else J(o)}R&&X([D||R[0],O||R[1]]),T.push(S.slice(0,C))}return T},Bh=Bs.tester;function Fh(e,r,n,i,o,a,s){var l,u;!function(e,r,n,i,o){var a=n.xaxis,s=n.yaxis,l=t.extent(re.simpleMap(a.range,a.r2c)),u=t.extent(re.simpleMap(s.range,s.r2c)),c=i[0].trace;if(!cn.hasMarkers(c))return;var p=c.marker.maxdisplayed;if(0===p)return;var h=i.filter(function(t){return t.x>=l[0]&&t.x<=l[1]&&t.y>=u[0]&&t.y<=u[1]}),f=Math.ceil(h.length/p),d=0;o.forEach(function(t,e){var n=t[0].trace;cn.hasMarkers(n)&&n.marker.maxdisplayed>0&&e0;function p(t){return c?t.transition():t}var h=n.xaxis,f=n.yaxis,d=i[0].trace,y=d.line,m=t.select(a);if(P.getComponentMethod("errorbars","plot")(m,n,s),!0===d.visible){var g,v;p(m).style("opacity",d.opacity);var _=d.fill.charAt(d.fill.length-1);"x"!==_&&"y"!==_&&(_=""),n.isRangePlot||(i[0].node3=m);var x="",b=[],w=d._prevtrace;w&&(x=w._prevRevpath||"",v=w._nextFill,b=w._polygons);var k,A,T,M,S,C,z,L,E,I="",D="",O=[],R=re.noop;if(g=d._ownFill,cn.hasLines(d)||"none"!==d.fill){for(v&&v.datum(i),-1!==["hv","vh","hvh","vhv"].indexOf(y.shape)?(T=pn.steps(y.shape),M=pn.steps(y.shape.split("").reverse().join(""))):T=M="spline"===y.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?pn.smoothclosed(t.slice(1),y.smoothing):pn.smoothopen(t,y.smoothing)}:function(t){return"M"+t.join("L")},S=function(t){return M(t.reverse())},O=Rh(i,{xaxis:h,yaxis:f,connectGaps:d.connectgaps,baseTolerance:Math.max(y.width||1,3)/4,shape:y.shape,simplify:y.simplify}),E=d._polygons=new Array(O.length),u=0;u1){var n=t.select(this);if(n.datum(i),e)p(n.style("opacity",0).attr("d",k).call(pn.lineGroupStyle)).style("opacity",1);else{var o=p(n);o.attr("d",k),pn.singleLineStyle(i,o)}}}}}var B=m.selectAll(".js-line").data(O);p(B.exit()).style("opacity",0).remove(),B.each(R(!1)),B.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(pn.lineGroupStyle).each(R(!0)),pn.setClipUrl(B,n.layerClipId),O.length?(g?C&&L&&(_?("y"===_?C[1]=L[1]=f.c2p(0,!0):"x"===_&&(C[0]=L[0]=h.c2p(0,!0)),p(g).attr("d","M"+L+"L"+C+"L"+I.substr(1)).call(pn.singleFillStyle)):p(g).attr("d",I+"Z").call(pn.singleFillStyle)):v&&("tonext"===d.fill.substr(0,6)&&I&&x?("tonext"===d.fill?p(v).attr("d",I+"Z"+x+"Z").call(pn.singleFillStyle):p(v).attr("d",I+"L"+x.substr(1)+"Z").call(pn.singleFillStyle),d._polygons=d._polygons.concat(b)):(N(v),d._polygons=null)),d._prevRevpath=D,d._prevPolygons=E):(g?N(g):v&&N(v),d._polygons=d._prevRevpath=d._prevPolygons=null);var F=m.selectAll(".points");l=F.data([i]),F.each(H),l.enter().append("g").classed("points",!0).each(H),l.exit().remove(),l.each(function(e){var r=!1===e[0].trace.cliponaxis;pn.setClipUrl(t.select(this),r?null:n.layerClipId)})}function N(t){p(t).attr("d","M0,0Z")}function j(t){return t.filter(function(t){return t.vis})}function V(t){return t.id}function q(t){if(t.ids)return V}function U(){return!1}function H(r){var i,o=r[0].trace,a=t.select(this),s=cn.hasMarkers(o),l=cn.hasText(o),u=q(o),d=U,y=U;s&&(d=o.marker.maxdisplayed||o._needsCull?j:re.identity),l&&(y=o.marker.maxdisplayed||o._needsCull?j:re.identity);var m=(i=a.selectAll("path.point").data(d,u)).enter().append("path").classed("point",!0);c&&m.call(pn.pointStyle,o,e).call(pn.translatePoints,h,f).style("opacity",0).transition().style("opacity",1);var g=s&&pn.tryColorscale(o.marker,""),v=s&&pn.tryColorscale(o.marker,"line");i.order(),i.each(function(r){var i=t.select(this),a=p(i);pn.translatePoint(r,a,h,f)?(pn.singlePointStyle(r,a,o,g,v,e),n.layerClipId&&pn.hideOutsideRangePoint(r,a,h,f,o.xcalendar,o.ycalendar),o.customdata&&i.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):a.remove()}),c?i.exit().transition().style("opacity",0).remove():i.exit().remove(),(i=a.selectAll("g").data(y,u)).enter().append("g").classed("textpoint",!0).append("text"),i.order(),i.each(function(e){var r=t.select(this),i=p(r.select("text"));pn.translatePoint(e,i,h,f)?n.layerClipId&&pn.hideOutsideRangePoint(e,r,h,f,o.xcalendar,o.ycalendar):r.remove()}),i.selectAll("text").call(pn.textPointStyle,o,e).each(function(e){var r=h.c2p(e.x),n=f.c2p(e.y);t.select(this).selectAll("tspan.line").each(function(){p(t.select(this)).attr({x:r,y:n})})}),i.exit().remove()}}function Nh(t,e,r){var n=t.selectAll("path.point"),i=t.selectAll("text");pn.pointStyle(n,e,r),pn.textPointStyle(i,e,r),pn.selectedPointStyle(n,e),pn.selectedTextStyle(i,e)}var jh=function(e,r){var n=r?r[0].node3:t.select(e).selectAll("g.trace.scatter");n.style("opacity",function(t){return t[0].trace.opacity}),n.selectAll("g.points").each(function(r){Nh(t.select(this),r.trace||r[0].trace,e)}),n.selectAll("g.trace path.js-line").call(pn.lineGroupStyle),n.selectAll("g.trace path.js-fill").call(pn.fillGroupStyle),P.getComponentMethod("errorbars","style")(n)},Vh={};Vh.hasLines=cn.hasLines,Vh.hasMarkers=cn.hasMarkers,Vh.hasText=cn.hasText,Vh.isBubble=cn.isBubble,Vh.attributes=Zn,Vh.supplyDefaults=function(t,e,r,n){function i(r,n){return re.coerce(t,e,Zn,r,n)}var o=function(t,e,r,n){var i,o=n("x"),a=n("y");if(P.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),o)a?i=Math.min(o.length,a.length):(i=o.length,n("y0"),n("dy"));else{if(!a)return 0;i=e.y.length,n("x0"),n("dx")}return e._length=i,i}(t,e,n,i),a=o=0;i--){var o=t[i];if("scatter"===o.type&&o.xaxis===r.xaxis&&o.yaxis===r.yaxis){o.opacity=void 0;break}}}}},Vh.calc=vh,Vh.arraysToCalcdata=ph,Vh.plot=function(e,r,n,i,o){var a,s,l,u,c=r.plot.select("g.scatterlayer"),p=!i,h=!!i&&i.duration>0;for((l=c.selectAll("g.trace").data(n,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),function(t,e,r){var n,i,o=null;for(i=0;is[e[0].trace.uid]?1:-1}),h?(o&&(u=o()),t.transition().duration(i.duration).ease(i.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(t,o){Fh(e,o,r,t,n,this,i)})})):c.selectAll("g.trace").each(function(t,o){Fh(e,o,r,t,n,this,i)});p&&l.exit().remove(),c.selectAll("path:not([d])").remove()},Vh.colorbar=wh,Vh.style=jh,Vh.hoverPoints=function(t,e,r,n){var i=t.cd,o=i[0].trace,a=t.xa,s=t.ya,l=a.c2p(e),u=s.c2p(r),c=[l,u],p=o.hoveron||"",h=-1!==o.mode.indexOf("markers")?3:.5;if(-1!==p.indexOf("points")){var f=function(t){var e=Math.max(h,t.mrc||0),r=a.c2p(t.x)-l,n=s.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-h/e)},d=Ko.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(a.c2p(t.x)-l);return nR!=(S=w[x][1])>=R&&(A=w[x-1][0],T=w[x][0],S-M&&(k=A+(T-A)*(R-M)/(S-M),E=Math.min(E,k),I=Math.max(I,k)));E=Math.max(E,0),I=Math.min(I,a._length);var B=Oe.defaultLine;return Oe.opacity(o.fillcolor)?B=o.fillcolor:Oe.opacity((o.line||{}).color)&&(B=o.line.color),re.extendFlat(t,{distance:t.maxHoverDistance,x0:E,x1:I,y0:R,y1:R,color:B}),delete t.index,o.text&&!Array.isArray(o.text)?t.text=String(o.text):t.text=o.name,[t]}}},Vh.selectPoints=function(t,e){var r,n,i,o,a=t.cd,s=t.xaxis,l=t.yaxis,u=[],c=a[0].trace;if(!cn.hasMarkers(c)&&!cn.hasText(c))return[];if(!1===e)for(r=0;r0){e+=Math.abs(i(t[0]));for(var r=1;r2){for(l=0;li.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(a=i.maxw*i.maxh-t*r)o.free)){if(r===o.h)return this.allocShelf(s,t,r,n);r>o.h||rc)&&(p=2*Math.max(t,c)),(ll)&&(u=2*Math.max(r,l)),this.resize(p,u),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;rthis.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,o,a){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=o||n,this.maxh=a||i,this.refcount=0}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t},"object"==typeof r&&void 0!==e?e.exports=i():n.ShelfPack=i()},{}],6:[function(t,e,r){function n(t,e,r,n,i,o){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=i||"sans-serif",this.fontWeight=o||"normal",this.radius=r||8;var a=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=a,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(a*a),this.gridInner=new Float64Array(a*a),this.f=new Float64Array(a),this.d=new Float64Array(a),this.z=new Float64Array(a+1),this.v=new Int16Array(a),this.middle=Math.round(a/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1))}function i(t,e,r,n,i,a,s){for(var l=0;ln)return n;for(;ro?r=i:n=i,i=.5*(n-r)+r}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},{}],8:[function(t,e,r){e.exports.VectorTile=t("./lib/vectortile.js"),e.exports.VectorTileFeature=t("./lib/vectortilefeature.js"),e.exports.VectorTileLayer=t("./lib/vectortilelayer.js")},{"./lib/vectortile.js":9,"./lib/vectortilefeature.js":10,"./lib/vectortilelayer.js":11}],9:[function(t,e,r){function n(t,e,r){if(3===t){var n=new i(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n)}}var i=t("./vectortilelayer");e.exports=function(t,e){this.layers=t.readFields(n,{},e)}},{"./vectortilelayer":11}],10:[function(t,e,r){function n(t,e,r,n,o){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=o,t.readFields(i,this,e)}function i(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3}if(i--,1===n||2===n)o+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&l.push(e),e=[]),e.push(new a(o,s));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone())}}return e&&l.push(e),l},n.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,o=0,a=1/0,s=-1/0,l=1/0,u=-1/0;t.pos>3}if(n--,1===r||2===r)i+=t.readSVarint(),o+=t.readSVarint(),is&&(s=i),ou&&(u=o);else if(7!==r)throw new Error("unknown command "+r)}return[a,l,s,u]},n.prototype.toGeoJSON=function(t,e,r){function i(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}var o=t("./vectortilefeature.js");e.exports=n,n.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new o(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":10}],12:[function(t,e,r){var n;n=this,function(t){function e(t,e,n){var i=r(256*t,256*(e=Math.pow(2,n)-e-1),n),o=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+o[0]+","+o[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return[t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}t.getURL=function(t,r,n,i,o,a){return a=a||{},t+"?"+["bbox="+e(n,i,o),"format="+(a.format||"image/png"),"service="+(a.service||"WMS"),"version="+(a.version||"1.1.1"),"request="+(a.request||"GetMap"),"srs="+(a.srs||"EPSG:3857"),"width="+(a.width||256),"height="+(a.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.WhooTS=n.WhooTS||{})},{}],13:[function(t,e,r){function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function o(t){return function(t){return t<0?0:t>1?1:t}("%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))}function a(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}var s={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};try{r.parseCSSColor=function(t){var e,r=t.replace(/ /g,"").toLowerCase();if(r in s)return s[r].slice();if("#"===r[0])return 4===r.length?(e=parseInt(r.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===r.length&&(e=parseInt(r.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var l=r.indexOf("("),u=r.indexOf(")");if(-1!==l&&u+1===r.length){var c=r.substr(0,l),p=r.substr(l+1,u-(l+1)).split(","),h=1;switch(c){case"rgba":if(4!==p.length)return null;h=o(p.pop());case"rgb":return 3!==p.length?null:[i(p[0]),i(p[1]),i(p[2]),h];case"hsla":if(4!==p.length)return null;h=o(p.pop());case"hsl":if(3!==p.length)return null;var f=(parseFloat(p[0])%360+360)%360/360,d=o(p[1]),y=o(p[2]),m=y<=.5?y*(d+1):y+d-y*d,g=2*y-m;return[n(255*a(g,m,f+1/3)),n(255*a(g,m,f)),n(255*a(g,m,f-1/3)),h];default:return null}}return null}}catch(t){}},{}],14:[function(t,e,r){function n(t,e,r){r=r||2;var n,s,l,u,c,f,y,m=e&&e.length,g=m?e[0]*r:t.length,v=i(t,0,g,r,!0),_=[];if(!v)return _;if(m&&(v=function(t,e,r,n){var a,s,l,u,c,f=[];for(a=0,s=e.length;a80*r){n=l=t[0],s=u=t[1];for(var x=r;xl&&(l=c),f>u&&(u=f);y=0!==(y=Math.max(l-n,u-s))?1/y:0}return a(v,_,r,n,s,y),_}function i(t,e,r,n,i){var o,a;if(i===T(t,e,r,n)>0)for(o=e;o=e;o-=n)a=w(o,t[o],t[o+1],a);return a&&v(a,a.next)&&(k(a),a=a.next),a}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!v(n,n.next)&&0!==g(n.prev,n,n.next))n=n.next;else{if(k(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function a(t,e,r,n,i,p,h){if(t){!h&&p&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=f(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,o,a,s,l,u=1;do{for(r=t,t=null,o=null,a=0;r;){for(a++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,u*=2}while(a>1)}(i)}(t,n,i,p);for(var d,y,m=t;t.prev!==t.next;)if(d=t.prev,y=t.next,p?l(t,n,i,p):s(t))e.push(d.i/r),e.push(t.i/r),e.push(y.i/r),k(t),t=y.next,m=y.next;else if((t=y)===m){h?1===h?a(t=u(t,e,r),e,r,n,i,p,2):2===h&&c(t,e,r,n,i,p):a(o(t),e,r,n,i,p,1);break}}}function s(t){var e=t.prev,r=t,n=t.next;if(g(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(y(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&g(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function l(t,e,r,n){var i=t.prev,o=t,a=t.next;if(g(i,o,a)>=0)return!1;for(var s=i.xo.x?i.x>a.x?i.x:a.x:o.x>a.x?o.x:a.x,c=i.y>o.y?i.y>a.y?i.y:a.y:o.y>a.y?o.y:a.y,p=f(s,l,e,r,n),h=f(u,c,e,r,n),d=t.prevZ,m=t.nextZ;d&&d.z>=p&&m&&m.z<=h;){if(d!==t.prev&&d!==t.next&&y(i.x,i.y,o.x,o.y,a.x,a.y,d.x,d.y)&&g(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,m!==t.prev&&m!==t.next&&y(i.x,i.y,o.x,o.y,a.x,a.y,m.x,m.y)&&g(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;d&&d.z>=p;){if(d!==t.prev&&d!==t.next&&y(i.x,i.y,o.x,o.y,a.x,a.y,d.x,d.y)&&g(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;m&&m.z<=h;){if(m!==t.prev&&m!==t.next&&y(i.x,i.y,o.x,o.y,a.x,a.y,m.x,m.y)&&g(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0}function u(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!v(i,o)&&_(i,n,n.next,o)&&x(i,o)&&x(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),k(n),k(n.next),n=t=o),n=n.next}while(n!==t);return n}function c(t,e,r,n,i,s){var l=t;do{for(var u=l.next.next;u!==l.prev;){if(l.i!==u.i&&m(l,u)){var c=b(l,u);return l=o(l,l.next),c=o(c,c.next),a(l,e,r,n,i,s),void a(c,e,r,n,i,s)}u=u.next}l=l.next}while(l!==t)}function p(t,e){return t.x-e.x}function h(t,e){if(e=function(t,e){var r,n=e,i=t.x,o=t.y,a=-1/0;do{if(o<=n.y&&o>=n.next.y&&n.next.y!==n.y){var s=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>a){if(a=s,s===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&i!==n.x&&y(or.x)&&x(n,t)&&(r=n,h=l),n=n.next;return r}(t,e)){var r=b(e,t);o(r,r.next)}}function f(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,r=t;do{e.x=0&&(t-a)*(n-s)-(r-a)*(e-s)>=0&&(r-a)*(o-s)-(i-a)*(n-s)>=0}function m(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&_(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&x(t,e)&&x(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function g(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function v(t,e){return t.x===e.x&&t.y===e.y}function _(t,e,r,n){return!!(v(t,e)&&v(r,n)||v(t,n)&&v(r,e))||g(t,e,r)>0!=g(t,e,n)>0&&g(r,n,t)>0!=g(r,n,e)>0}function x(t,e){return g(t.prev,t,t.next)<0?g(t,e,t.next)>=0&&g(t,t.prev,e)>=0:g(t,e,t.prev)<0||g(t,t.next,e)<0}function b(t,e){var r=new A(t.i,t.x,t.y),n=new A(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function w(t,e,r,n){var i=new A(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function k(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function A(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function T(t,e,r,n){for(var i=0,o=e,a=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],15:[function(t,e,r){function n(t,e){return function(r){return t(r,e)}}function i(t,e){e=!!e,t[0]=o(t[0],e);for(var r=1;r=0}(t)===e?t:t.reverse()}var a=t("@mapbox/geojson-area");e.exports=function t(e,r){switch(e&&e.type||null){case"FeatureCollection":return e.features=e.features.map(n(t,r)),e;case"Feature":return e.geometry=t(e.geometry,r),e;case"Polygon":case"MultiPolygon":return function(t,e){return"Polygon"===t.type?t.coordinates=i(t.coordinates,e):"MultiPolygon"===t.type&&(t.coordinates=t.coordinates.map(n(i,e))),t}(e,r);default:return e}}},{"@mapbox/geojson-area":1}],16:[function(t,e,r){function n(t,e,r,n,i){for(var o=0;o=r&&a<=n&&(e.push(t[o]),e.push(t[o+1]),e.push(t[o+2]))}}function i(t,e,r,n,i,o){for(var u=[],c=0===i?s:l,p=0;p=r&&c(u,h,f,y,m,r):g>n?v<=n&&c(u,h,f,y,m,n):a(u,h,f,d),v=r&&(c(u,h,f,y,m,r),_=!0),v>n&&g<=n&&(c(u,h,f,y,m,n),_=!0),!o&&_&&(u.size=t.size,e.push(u),u=[])}var x=t.length-3;h=t[x],f=t[x+1],d=t[x+2],(g=0===i?h:f)>=r&&g<=n&&a(u,h,f,d),x=u.length-3,o&&x>=3&&(u[x]!==u[0]||u[x+1]!==u[1])&&a(u,u[0],u[1],u[2]),u.length&&(u.size=t.size,e.push(u))}function o(t,e,r,n,o,a){for(var s=0;s=(r/=e)&&c<=a)return t;if(l>a||c=r&&g<=a)p.push(f);else if(!(m>a||g0&&(a+=n?(i*h-p*o)/2:Math.sqrt(Math.pow(p-i,2)+Math.pow(h-o,2))),i=p,o=h}var f=e.length-3;e[2]=1,u(e,0,f,r),e[f+2]=1,e.size=Math.abs(a)}function a(t,e,r,n){for(var i=0;i1?1:r}e.exports=function(t,e){var r=[];if("FeatureCollection"===t.type)for(var i=0;i24)throw new Error("maxZoom should be in the 0-24 range");var n=1<1&&console.time("creation"),y=this.tiles[d]=u(t,f,r,n,m,e===p.maxZoom),this.tileCoords.push({z:e,x:r,y:n}),h)){h>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,y.numFeatures,y.numPoints,y.numSimplified),console.timeEnd("creation"));var g="z"+e;this.stats[g]=(this.stats[g]||0)+1,this.total++}if(y.source=t,o){if(e===p.maxZoom||e===o)continue;var v=1<1&&console.time("clipping");var _,x,b,w,k,A,T=.5*p.buffer/p.extent,M=.5-T,S=.5+T,C=1+T;_=x=b=w=null,k=s(t,f,r-T,r+S,0,y.minX,y.maxX),A=s(t,f,r+M,r+C,0,y.minX,y.maxX),t=null,k&&(_=s(k,f,n-T,n+S,1,y.minY,y.maxY),x=s(k,f,n+M,n+C,1,y.minY,y.maxY),k=null),A&&(b=s(A,f,n-T,n+S,1,y.minY,y.maxY),w=s(A,f,n+M,n+C,1,y.minY,y.maxY),A=null),h>1&&console.timeEnd("clipping"),c.push(_||[],e+1,2*r,2*n),c.push(x||[],e+1,2*r,2*n+1),c.push(b||[],e+1,2*r+1,2*n),c.push(w||[],e+1,2*r+1,2*n+1)}}},n.prototype.getTile=function(t,e,r){var n=this.options,o=n.extent,s=n.debug;if(t<0||t>24)return null;var l=1<1&&console.log("drilling down to z%d-%d-%d",t,e,r);for(var c,p=t,h=e,f=r;!c&&p>0;)p--,h=Math.floor(h/2),f=Math.floor(f/2),c=this.tiles[i(p,h,f)];return c&&c.source?(s>1&&console.log("found parent tile z%d-%d-%d",p,h,f),s>1&&console.time("drilling down"),this.splitTile(c.source,p,h,f,t,e,r),s>1&&console.timeEnd("drilling down"),this.tiles[u]?a.tile(this.tiles[u],o):null):null}},{"./clip":16,"./convert":17,"./tile":21,"./transform":22,"./wrap":23}],20:[function(t,e,r){function n(t,e,r,n,i,o){var a=i-r,s=o-n;if(0!==a||0!==s){var l=((t-r)*a+(e-n)*s)/(a*a+s*s);l>1?(r=i,n=o):l>0&&(r+=a*l,n+=s*l)}return(a=t-r)*a+(s=e-n)*s}e.exports=function t(e,r,i,o){for(var a,s=o,l=e[r],u=e[r+1],c=e[i],p=e[i+1],h=r+3;hs&&(a=h,s=f)}s>o&&(a-r>3&&t(e,r,a,o),e[a+2]=s,i-a>3&&t(e,a,i,o))}},{}],21:[function(t,e,r){function n(t,e,r,n){var o=e.geometry,a=e.type,s=[];if("Point"===a||"MultiPoint"===a)for(var l=0;ls)&&(r.numSimplified++,l.push(e[u]),l.push(e[u+1])),r.numPoints++;o&&function(t,e){for(var r=0,n=0,i=t.length,o=i-2;n0===e)for(n=0,i=t.length;ns.maxX&&(s.maxX=p),h>s.maxY&&(s.maxY=h)}return s}},{}],22:[function(t,e,r){function n(t,e,r,n,i,o){return[Math.round(r*(t*n-i)),Math.round(r*(e*n-o))]}r.tile=function(t,e){if(t.transformed)return t;var r,i,o,a=t.z2,s=t.x,l=t.y;for(r=0;r=u[h+0]&&n>=u[h+1]?(a[p]=!0,o.push(l[p])):a[p]=!1}}},n.prototype._forEachCell=function(t,e,r,n,i,o,a){for(var s=this._convertToCellCoord(t),l=this._convertToCellCoord(e),u=this._convertToCellCoord(r),c=this._convertToCellCoord(n),p=s;p<=u;p++)for(var h=l;h<=c;h++){var f=this.d*h+p;if(i.call(this,t,e,r,n,f,o,a))return}},n.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},n.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=i+this.cells.length+1+1,r=0,n=0;n>1,c=-7,p=r?i-1:0,h=r?-1:1,f=t[e+p];for(p+=h,o=f&(1<<-c)-1,f>>=-c,c+=s;c>0;o=256*o+t[e+p],p+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=n;c>0;a=256*a+t[e+p],p+=h,c-=8);if(0===o)o=1-u;else{if(o===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),o-=u}return(f?-1:1)*a*Math.pow(2,o-n)},r.write=function(t,e,r,n,i,o){var a,s,l,u=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+p>=1?h/l:h*Math.pow(2,1-p))*l>=2&&(a++,l/=2),a+p>=c?(s=0,a=c):a+p>=1?(s=(e*l-1)*Math.pow(2,i),a+=p):(s=e*Math.pow(2,p-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&s,f+=d,s/=256,i-=8);for(a=a<0;t[r+f]=255&a,f+=d,a/=256,u-=8);t[r+f-d]|=128*y}},{}],26:[function(t,e,r){function n(t,e,r,n,s){e=e||i,r=r||o,s=s||Array,this.nodeSize=n||64,this.points=t,this.ids=new s(t.length),this.coords=new s(2*t.length);for(var l=0;l=r&&s<=i&&l>=n&&l<=o&&c.push(t[d]);else{var y=Math.floor((f+h)/2);s=e[2*y],l=e[2*y+1],s>=r&&s<=i&&l>=n&&l<=o&&c.push(t[y]);var m=(p+1)%2;(0===p?r<=s:n<=l)&&(u.push(f),u.push(y-1),u.push(m)),(0===p?i>=s:o>=l)&&(u.push(y+1),u.push(h),u.push(m))}}return c}},{}],28:[function(t,e,r){function n(t,e,r,n){i(t,r,n),i(e,2*r,2*n),i(e,2*r+1,2*n+1)}function i(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}e.exports=function t(e,r,i,o,a,s){if(!(a-o<=i)){var l=Math.floor((o+a)/2);(function t(e,r,i,o,a,s){for(;a>o;){if(a-o>600){var l=a-o+1,u=i-o+1,c=Math.log(l),p=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*p*(l-p)/l)*(u-l/2<0?-1:1);t(e,r,i,Math.max(o,Math.floor(i-u*p/l+h)),Math.min(a,Math.floor(i+(l-u)*p/l+h)),s)}var f=r[2*i+s],d=o,y=a;for(n(e,r,o,i),r[2*a+s]>f&&n(e,r,o,a);df;)y--}r[2*o+s]===f?n(e,r,o,y):n(e,r,++y,a),y<=i&&(o=y+1),i<=y&&(a=y-1)}})(e,r,l,o,a,s%2),t(e,r,i,o,l-1,s+1),t(e,r,i,l+1,a,s+1)}}},{}],29:[function(t,e,r){function n(t,e,r,n){var i=t-r,o=e-n;return i*i+o*o}e.exports=function(t,e,r,i,o,a){for(var s=[0,t.length-1,0],l=[],u=o*o;s.length;){var c=s.pop(),p=s.pop(),h=s.pop();if(p-h<=a)for(var f=h;f<=p;f++)n(e[2*f],e[2*f+1],r,i)<=u&&l.push(t[f]);else{var d=Math.floor((h+p)/2),y=e[2*d],m=e[2*d+1];n(y,m,r,i)<=u&&l.push(t[d]);var g=(c+1)%2;(0===c?r-o<=y:i-o<=m)&&(s.push(h),s.push(d-1),s.push(g)),(0===c?r+o>=y:i+o>=m)&&(s.push(d+1),s.push(p),s.push(g))}}return l}},{}],30:[function(t,e,r){function n(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}function i(t){return t.type===n.Bytes?t.readVarint()+t.pos:t.pos+1}function o(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function a(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}function s(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24}function v(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}e.exports=n;var _=t("ieee754");n.Varint=0,n.Fixed64=1,n.Bytes=2,n.Fixed32=5;n.prototype={destroy:function(){this.buf=null},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,o=this.pos;this.type=7&n,t(i,e,this),this.pos===o&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=m(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=m(this.buf,this.pos)+4294967296*m(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=m(this.buf,this.pos)+4294967296*v(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=_.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=_.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(n=(112&(i=a[r.pos++]))>>4,i<128)return o(t,n,e);if(n|=(127&(i=a[r.pos++]))<<3,i<128)return o(t,n,e);if(n|=(127&(i=a[r.pos++]))<<10,i<128)return o(t,n,e);if(n|=(127&(i=a[r.pos++]))<<17,i<128)return o(t,n,e);if(n|=(127&(i=a[r.pos++]))<<24,i<128)return o(t,n,e);if(n|=(1&(i=a[r.pos++]))<<31,i<128)return o(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(o=t[i+1]))&&(u=(31&l)<<6|63&o)<=127&&(u=null):3===c?(o=t[i+1],a=t[i+2],128==(192&o)&&128==(192&a)&&((u=(15&l)<<12|(63&o)<<6|63&a)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(o=t[i+1],a=t[i+2],s=t[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&((u=(15&l)<<18|(63&o)<<12|(63&a)<<6|63&s)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=i(this);for(t=t||[];this.pos127;);else if(e===n.Bytes)this.pos=this.readVarint()+this.pos;else if(e===n.Fixed32)this.pos+=4;else{if(e!==n.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,o=0;o55295&&n<57344){if(!i){n>56319||o+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128)}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&a(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(t){this.realloc(4),_.write(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),_.write(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&a(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,n.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){this.writeMessage(t,s,e)},writePackedSVarint:function(t,e){this.writeMessage(t,l,e)},writePackedBoolean:function(t,e){this.writeMessage(t,p,e)},writePackedFloat:function(t,e){this.writeMessage(t,u,e)},writePackedDouble:function(t,e){this.writeMessage(t,c,e)},writePackedFixed32:function(t,e){this.writeMessage(t,h,e)},writePackedSFixed32:function(t,e){this.writeMessage(t,f,e)},writePackedFixed64:function(t,e){this.writeMessage(t,d,e)},writePackedSFixed64:function(t,e){this.writeMessage(t,y,e)},writeBytesField:function(t,e){this.writeTag(t,n.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,n.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,n.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,n.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}}},{ieee754:25}],31:[function(t,e,r){function n(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function i(t,e){return te?1:0}e.exports=function t(e,r,o,a,s){for(o=o||0,a=a||e.length-1,s=s||i;a>o;){if(a-o>600){var l=a-o+1,u=r-o+1,c=Math.log(l),p=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*p*(l-p)/l)*(u-l/2<0?-1:1);t(e,r,Math.max(o,Math.floor(r-u*p/l+h)),Math.min(a,Math.floor(r+(l-u)*p/l+h)),s)}var f=e[r],d=o,y=a;for(n(e,o,r),s(e[a],f)>0&&n(e,o,a);d0;)y--}0===s(e[o],f)?n(e,o,y):n(e,++y,a),y<=r&&(o=y+1),r<=y&&(a=y-1)}}},{}],32:[function(t,e,r){function n(t){this.options=c(Object.create(this.options),t),this.trees=new Array(this.options.maxZoom+1)}function i(t,e,r,n,i){return{x:t,y:e,zoom:1/0,id:n,properties:i,parentId:-1,numPoints:r}}function o(t,e){var r=t.geometry.coordinates;return{x:l(r[0]),y:u(r[1]),zoom:1/0,id:e,parentId:-1}}function a(t){return{type:"Feature",properties:s(t),geometry:{type:"Point",coordinates:[function(t){return 360*(t-.5)}(t.x),function(t){var e=(180-360*t)*Math.PI/180;return 360*Math.atan(Math.exp(e))/Math.PI-90}(t.y)]}}}function s(t){var e=t.numPoints,r=e>=1e4?Math.round(e/1e3)+"k":e>=1e3?Math.round(e/100)/10+"k":e;return c(c({},t.properties),{cluster:!0,cluster_id:t.id,point_count:e,point_count_abbreviated:r})}function l(t){return t/360+.5}function u(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function c(t,e){for(var r in e)t[r]=e[r];return t}function p(t){return t.x}function h(t){return t.y}var f=t("kdbush");e.exports=function(t){return new n(t)},n.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(t){return t}},load:function(t){var e=this.options.log;e&&console.time("total time");var r="prepare "+t.length+" points";e&&console.time(r),this.points=t;var n=t.map(o);e&&console.timeEnd(r);for(var i=this.options.maxZoom;i>=this.options.minZoom;i--){var a=+Date.now();this.trees[i+1]=f(n,p,h,this.options.nodeSize,Float32Array),n=this._cluster(n,i),e&&console.log("z%d: %d clusters in %dms",i,n.length,+Date.now()-a)}return this.trees[this.options.minZoom]=f(n,p,h,this.options.nodeSize,Float32Array),e&&console.timeEnd("total time"),this},getClusters:function(t,e){for(var r=this.trees[this._limitZoom(e)],n=r.range(l(t[0]),u(t[3]),l(t[2]),u(t[1])),i=[],o=0;o0)for(var r=this.length>>1;r>=0;r--)this._down(r)}function i(t,e){return te?1:0}e.exports=n,n.prototype={push:function(t){this.data.push(t),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var t=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),t}},peek:function(){return this.data[0]},_up:function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,o=e[i];if(r(n,o)>=0)break;e[t]=o,t=i}e[t]=n},_down:function(t){for(var e=this.data,r=this.compare,n=this.length,i=n>>1,o=e[t];t=0)break;e[t]=l,t=a}e[t]=o}}},{}],34:[function(t,e,r){function n(t){var e=new p;return function(t,e){for(var r in t.layers)e.writeMessage(3,i,t.layers[r])}(t,e),e.finish()}function i(t,e){e.writeVarintField(15,t.version||1),e.writeStringField(1,t.name||""),e.writeVarintField(5,t.extent||4096);var r,n={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function u(t,e){for(var r=t.loadGeometry(),n=t.type,i=0,o=0,a=r.length,u=0;u=c||p<0||p>=c)){var h=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray),f=h.vertexLength;n(r.layoutVertexArray,u,p,-1,-1),n(r.layoutVertexArray,u,p,1,-1),n(r.layoutVertexArray,u,p,1,1),n(r.layoutVertexArray,u,p,-1,1),r.indexArray.emplaceBack(f,f+1,f+2),r.indexArray.emplaceBack(f,f+3,f+2),h.vertexLength+=4,h.primitiveLength+=2}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},p("CircleBucket",h,{omit:["layers"]}),e.exports=h},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./circle_attributes":41}],43:[function(t,e,r){arguments[4][41][0].apply(r,arguments)},{"../../util/struct_array":271,dup:41}],44:[function(t,e,r){var n=t("../array_types").FillLayoutArray,i=t("./fill_attributes").members,o=t("../segment").SegmentVector,a=t("../program_configuration").ProgramConfigurationSet,s=t("../index_array_type"),l=s.LineIndexArray,u=s.TriangleIndexArray,c=t("../load_geometry"),p=t("earcut"),h=t("../../util/classify_rings"),f=t("../../util/web_worker_transfer").register,d=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new n,this.indexArray=new u,this.indexArray2=new l,this.programConfigurations=new a(i,t.layers,t.zoom),this.segments=new o,this.segments2=new o};d.prototype.populate=function(t,e){for(var r=this,n=0,i=t;nd)||t.y===e.y&&(t.y<0||t.y>d)}function o(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>d})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>d})}var a=t("../array_types").FillExtrusionLayoutArray,s=t("./fill_extrusion_attributes").members,l=t("../segment"),u=l.SegmentVector,c=l.MAX_VERTEX_ARRAY_LENGTH,p=t("../program_configuration").ProgramConfigurationSet,h=t("../index_array_type").TriangleIndexArray,f=t("../load_geometry"),d=t("../extent"),y=t("earcut"),m=t("../../util/classify_rings"),g=t("../../util/web_worker_transfer").register,v=Math.pow(2,13),_=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new a,this.indexArray=new h,this.programConfigurations=new p(s,t.layers,t.zoom),this.segments=new u};_.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=1){var w=v[x-1];if(!i(b,w)){f.vertexLength+4>c&&(f=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray));var k=b.sub(w)._perp()._unit(),A=w.dist(b);_+A>32768&&(_=0),n(r.layoutVertexArray,b.x,b.y,k.x,k.y,0,0,_),n(r.layoutVertexArray,b.x,b.y,k.x,k.y,0,1,_),_+=A,n(r.layoutVertexArray,w.x,w.y,k.x,k.y,0,0,_),n(r.layoutVertexArray,w.x,w.y,k.x,k.y,0,1,_);var T=f.vertexLength;r.indexArray.emplaceBack(T,T+1,T+2),r.indexArray.emplaceBack(T+1,T+2,T+3),f.vertexLength+=4,f.primitiveLength+=2}}}}f.vertexLength+u>c&&(f=r.segments.prepareSegment(u,r.layoutVertexArray,r.indexArray));for(var M=[],S=[],C=f.vertexLength,z=0,L=l;z>6)}var i=t("../array_types").LineLayoutArray,o=t("./line_attributes").members,a=t("../segment").SegmentVector,s=t("../program_configuration").ProgramConfigurationSet,l=t("../index_array_type").TriangleIndexArray,u=t("../load_geometry"),c=t("../extent"),p=t("@mapbox/vector-tile").VectorTileFeature.types,h=t("../../util/web_worker_transfer").register,f=63,d=Math.cos(Math.PI/180*37.5),y=.5,m=Math.pow(2,14)/y,g=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new i,this.indexArray=new l,this.programConfigurations=new s(o,t.layers,t.zoom),this.segments=new a};g.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=2&&t[l-1].equals(t[l-2]);)l--;for(var u=0;uu){var E=m.dist(w);if(E>2*h){var P=m.sub(m.sub(w)._mult(h/E)._round());a.distance+=P.dist(w),a.addCurrentVertex(P,a.distance,A.mult(1),0,0,!1,y),w=P}}var I=w&&k,D=I?r:k?_:x;if(I&&"round"===D&&(zi&&(D="bevel"),"bevel"===D&&(z>2&&(D="flipbevel"),z100)S=T.clone().mult(-1);else{var O=A.x*T.y-A.y*T.x>0?-1:1,R=z*A.add(T).mag()/A.sub(T).mag();S._perp()._mult(R*O)}a.addCurrentVertex(m,a.distance,S,0,0,!1,y),a.addCurrentVertex(m,a.distance,S.mult(-1),0,0,!1,y)}else if("bevel"===D||"fakeround"===D){var B=A.x*T.y-A.y*T.x>0,F=-Math.sqrt(z*z-1);if(B?(v=0,g=F):(g=0,v=F),b||a.addCurrentVertex(m,a.distance,A,g,v,!1,y),"fakeround"===D){for(var N=Math.floor(8*(.5-(C-.5))),j=void 0,V=0;V=0;q--)j=A.mult((q+1)/(N+1))._add(T)._unit(),a.addPieSliceVertex(m,a.distance,j,B,y)}k&&a.addCurrentVertex(m,a.distance,T,-g,-v,!1,y)}else"butt"===D?(b||a.addCurrentVertex(m,a.distance,A,0,0,!1,y),k&&a.addCurrentVertex(m,a.distance,T,0,0,!1,y)):"square"===D?(b||(a.addCurrentVertex(m,a.distance,A,1,1,!1,y),a.e1=a.e2=-1),k&&a.addCurrentVertex(m,a.distance,T,-1,-1,!1,y)):"round"===D&&(b||(a.addCurrentVertex(m,a.distance,A,0,0,!1,y),a.addCurrentVertex(m,a.distance,A,1,1,!0,y),a.e1=a.e2=-1),k&&(a.addCurrentVertex(m,a.distance,T,-1,-1,!0,y),a.addCurrentVertex(m,a.distance,T,0,0,!1,y)));if(L&&M2*h){var H=m.add(k.sub(m)._mult(h/U)._round());a.distance+=H.dist(m),a.addCurrentVertex(H,a.distance,T.mult(1),0,0,!1,y),m=H}}b=!1}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e)}},g.prototype.addCurrentVertex=function(t,e,r,i,o,a,s){var l,u=this.layoutVertexArray,c=this.indexArray;l=r.clone(),i&&l._sub(r.perp()._mult(i)),n(u,t,l,a,!1,i,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,l=r.mult(-1),o&&l._sub(r.perp()._mult(o)),n(u,t,l,a,!0,-o,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>m/2&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,i,o,a,s))},g.prototype.addPieSliceVertex=function(t,e,r,i,o){r=r.mult(i?-1:1);var a=this.layoutVertexArray,s=this.indexArray;n(a,t,r,!1,i,0,e),this.e3=o.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),o.primitiveLength++),i?this.e2=this.e3:this.e1=this.e3},h("LineBucket",g,{omit:["layers"]}),e.exports=g},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./line_attributes":48,"@mapbox/vector-tile":8}],50:[function(t,e,r){var n=t("../../util/struct_array").createLayout,i={symbolLayoutAttributes:n([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),dynamicLayoutAttributes:n([{name:"a_projected_pos",components:3,type:"Float32"}],4),placementOpacityAttributes:n([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),collisionVertexAttributes:n([{name:"a_placed",components:2,type:"Uint8"}],4),collisionBox:n([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),collisionBoxLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),collisionCircleLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),placement:n([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),glyphOffset:n([{type:"Float32",name:"offsetX"}]),lineVertex:n([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}])};e.exports=i},{"../../util/struct_array":271}],51:[function(t,e,r){function n(t,e,r,n,i,o,a,s){t.emplaceBack(e,r,Math.round(64*n),Math.round(64*i),o,a,s?s[0]:0,s?s[1]:0)}function i(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r)}var o=t("./symbol_attributes"),a=o.symbolLayoutAttributes,s=o.collisionVertexAttributes,l=o.collisionBoxLayout,u=o.collisionCircleLayout,c=o.dynamicLayoutAttributes,p=t("../array_types"),h=p.SymbolLayoutArray,f=p.SymbolDynamicLayoutArray,d=p.SymbolOpacityArray,y=p.CollisionBoxLayoutArray,m=p.CollisionCircleLayoutArray,g=p.CollisionVertexArray,v=p.PlacedSymbolArray,_=p.GlyphOffsetArray,x=p.SymbolLineVertexArray,b=t("@mapbox/point-geometry"),w=t("../segment").SegmentVector,k=t("../program_configuration").ProgramConfigurationSet,A=t("../index_array_type"),T=A.TriangleIndexArray,M=A.LineIndexArray,S=t("../../symbol/transform_text"),C=t("../../symbol/mergelines"),z=t("../../util/script_detection"),L=t("../load_geometry"),E=t("@mapbox/vector-tile").VectorTileFeature.types,P=t("../../util/verticalize_punctuation"),I=(t("../../symbol/anchor"),t("../../symbol/symbol_size").getSizeData),D=t("../../util/web_worker_transfer").register,O=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}],R=function(t){this.layoutVertexArray=new h,this.indexArray=new T,this.programConfigurations=t,this.segments=new w,this.dynamicLayoutVertexArray=new f,this.opacityVertexArray=new d,this.placedSymbolArray=new v};R.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,a.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,c.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,O,!0),this.opacityVertexBuffer.itemSize=1},R.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy())},D("SymbolBuffers",R);var B=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new w,this.collisionVertexArray=new g};B.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,s.members,!0)},B.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy())},D("CollisionBuffers",B);var F=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=I(this.zoom,e["text-size"]),this.iconSizeData=I(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")};F.prototype.createArrays=function(){this.text=new R(new k(a.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new R(new k(a.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new B(y,l.members,M),this.collisionCircle=new B(m,u.members,T),this.glyphOffsetArray=new _,this.lineVertexArray=new x},F.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),o=n.get("text-field"),a=n.get("icon-image"),s=("constant"!==o.value.kind||o.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),l="constant"!==a.value.kind||a.value.value&&a.value.value.length>0;if(this.features=[],s||l){for(var u=e.iconDependencies,c=e.glyphDependencies,p={zoom:this.zoom},h=0,f=t;h=0;s--)o[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var l=0;l0;t.addCollisionDebugVertices(l,u,c,p,h?t.collisionCircle:t.collisionBox,s.anchorPoint,n,h)}}}},F.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var o={},a=e;a0},F.prototype.hasIconData=function(){return this.icon.segments.get().length>0},F.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},F.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},F.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},o("Level",a);var s=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new a(256,512),this.loaded=!!r};s.prototype.loadFromImage=function(t){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");for(var e=this.level=new a(t.width,t.width/2),r=t.data,n=0;na.max||u.ya.max)&&i.warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return r}},{"../util/util":275,"./extent":53}],57:[function(t,e,r){var n=t("../util/struct_array").createLayout;e.exports=n([{name:"a_pos",type:"Int16",components:2}])},{"../util/struct_array":271}],58:[function(t,e,r){function n(t){return[o(255*t.r,255*t.g),o(255*t.b,255*t.a)]}function i(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}var o=t("../shaders/encode_attribute").packUint8ToFloat,a=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),s=t("../style/properties").PossiblyEvaluatedPropertyValue,l=t("./array_types"),u=l.StructArrayLayout1f4,c=l.StructArrayLayout2f8,p=l.StructArrayLayout4f16,h=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0}};h.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},h.prototype.populatePaintArray=function(){},h.prototype.upload=function(){},h.prototype.destroy=function(){},h.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),o=t.gl;"color"===this.type?o.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):o.uniform1f(e.uniforms["u_"+this.name],i)};var f=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?c:u;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n};f.prototype.defines=function(){return[]},f.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,i=r.length;r.reserve(t);var o=this.expression.evaluate({zoom:0},e);if("color"===this.type)for(var a=n(o),s=i;so&&n("Max vertices per segment is "+o+": bucket requested "+t),(!a||a.vertexLength+t>e.exports.MAX_VERTEX_ARRAY_LENGTH)&&(a={vertexOffset:r.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0},this.segments.push(a)),a},a.prototype.get=function(){return this.segments},a.prototype.destroy=function(){for(var t=0,e=this.segments;t90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};i.prototype.wrap=function(){return new i(n(this.lng,-180,180),this.lat)},i.prototype.toArray=function(){return[this.lng,this.lat]},i.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},i.prototype.toBounds=function(e){var r=360*e/40075017,n=r/Math.cos(Math.PI/180*this.lat);return new(t("./lng_lat_bounds"))(new i(this.lng-n,this.lat-r),new i(this.lng+n,this.lat+r))},i.convert=function(t){if(t instanceof i)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new i(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new i(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, or an array of [, ]")},e.exports=i},{"../util/util":275,"./lng_lat_bounds":63}],63:[function(t,e,r){var n=t("./lng_lat"),i=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]))};i.prototype.setNorthEast=function(t){return this._ne=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.setSouthWest=function(t){return this._sw=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.extend=function(t){var e,r,o=this._sw,a=this._ne;if(t instanceof n)e=t,r=t;else{if(!(t instanceof i))return Array.isArray(t)?t.every(Array.isArray)?this.extend(i.convert(t)):this.extend(n.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return o||a?(o.lng=Math.min(e.lng,o.lng),o.lat=Math.min(e.lat,o.lat),a.lng=Math.max(r.lng,a.lng),a.lat=Math.max(r.lat,a.lat)):(this._sw=new n(e.lng,e.lat),this._ne=new n(r.lng,r.lat)),this},i.prototype.getCenter=function(){return new n((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},i.prototype.getSouthWest=function(){return this._sw},i.prototype.getNorthEast=function(){return this._ne},i.prototype.getNorthWest=function(){return new n(this.getWest(),this.getNorth())},i.prototype.getSouthEast=function(){return new n(this.getEast(),this.getSouth())},i.prototype.getWest=function(){return this._sw.lng},i.prototype.getSouth=function(){return this._sw.lat},i.prototype.getEast=function(){return this._ne.lng},i.prototype.getNorth=function(){return this._ne.lat},i.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},i.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},i.prototype.isEmpty=function(){return!(this._sw&&this._ne)},i.convert=function(t){return!t||t instanceof i?t:new i(t)},e.exports=i},{"./lng_lat":62}],64:[function(t,e,r){var n=t("./lng_lat"),i=t("@mapbox/point-geometry"),o=t("./coordinate"),a=t("../util/util"),s=t("../style-spec/util/interpolate").number,l=t("../util/tile_cover"),u=t("../source/tile_id"),c=(u.CanonicalTileID,u.UnwrappedTileID),p=t("../data/extent"),h=t("@mapbox/gl-matrix"),f=h.vec4,d=h.mat4,y=h.mat2,m=function(t,e,r){this.tileSize=512,this._renderWorldCopies=void 0===r||r,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new n(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={}},g={minZoom:{},maxZoom:{},renderWorldCopies:{},worldSize:{},centerPoint:{},size:{},bearing:{},pitch:{},fov:{},zoom:{},center:{},unmodified:{},x:{},y:{},point:{}};m.prototype.clone=function(){var t=new m(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},g.minZoom.get=function(){return this._minZoom},g.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))},g.maxZoom.get=function(){return this._maxZoom},g.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))},g.renderWorldCopies.get=function(){return this._renderWorldCopies},g.worldSize.get=function(){return this.tileSize*this.scale},g.centerPoint.get=function(){return this.size._div(2)},g.size.get=function(){return new i(this.width,this.height)},g.bearing.get=function(){return-this.angle/Math.PI*180},g.bearing.set=function(t){var e=-a.wrap(t,-180,180)*Math.PI/180;this.angle!==e&&(this._unmodified=!1,this.angle=e,this._calcMatrices(),this.rotationMatrix=y.create(),y.rotate(this.rotationMatrix,this.rotationMatrix,this.angle))},g.pitch.get=function(){return this._pitch/Math.PI*180},g.pitch.set=function(t){var e=a.clamp(t,0,60)/180*Math.PI;this._pitch!==e&&(this._unmodified=!1,this._pitch=e,this._calcMatrices())},g.fov.get=function(){return this._fov/Math.PI*180},g.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices())},g.zoom.get=function(){return this._zoom},g.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices())},g.center.get=function(){return this._center},g.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices())},m.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},m.prototype.getVisibleUnwrappedCoordinates=function(t){var e=this.pointCoordinate(new i(0,0),0),r=this.pointCoordinate(new i(this.width,0),0),n=Math.floor(e.column),o=Math.floor(r.column),a=[new c(0,t)];if(this._renderWorldCopies)for(var s=n;s<=o;s++)0!==s&&a.push(new c(s,t));return a},m.prototype.coveringTiles=function(t){var e=this.coveringZoomLevel(t),r=e;if(void 0!==t.minzoom&&et.maxzoom&&(e=t.maxzoom);var n=this.pointCoordinate(this.centerPoint,e),o=new i(n.column-.5,n.row-.5),a=[this.pointCoordinate(new i(0,0),e),this.pointCoordinate(new i(this.width,0),e),this.pointCoordinate(new i(this.width,this.height),e),this.pointCoordinate(new i(0,this.height),e)];return l(e,a,t.reparseOverscaled?r:e,this._renderWorldCopies).sort(function(t,e){return o.dist(t.canonical)-o.dist(e.canonical)})},m.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices()},g.unmodified.get=function(){return this._unmodified},m.prototype.zoomScale=function(t){return Math.pow(2,t)},m.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},m.prototype.project=function(t){return new i(this.lngX(t.lng),this.latY(t.lat))},m.prototype.unproject=function(t){return new n(this.xLng(t.x),this.yLat(t.y))},g.x.get=function(){return this.lngX(this.center.lng)},g.y.get=function(){return this.latY(this.center.lat)},g.point.get=function(){return new i(this.x,this.y)},m.prototype.lngX=function(t){return(180+t)*this.worldSize/360},m.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},m.prototype.xLng=function(t){return 360*t/this.worldSize-180},m.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},m.prototype.setLocationAtPoint=function(t,e){var r=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(r)),this._renderWorldCopies&&(this.center=this.center.wrap())},m.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},m.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},m.prototype.locationCoordinate=function(t){return new o(this.lngX(t.lng)/this.tileSize,this.latY(t.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},m.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new n(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},m.prototype.pointCoordinate=function(t,e){void 0===e&&(e=this.tileZoom);var r=[t.x,t.y,0,1],n=[t.x,t.y,1,1];f.transformMat4(r,r,this.pixelMatrixInverse),f.transformMat4(n,n,this.pixelMatrixInverse);var i=r[3],a=n[3],l=r[1]/i,u=n[1]/a,c=r[2]/i,p=n[2]/a,h=c===p?0:(0-c)/(p-c);return new o(s(r[0]/i,n[0]/a,h)/this.tileSize,s(l,u,h)/this.tileSize,this.zoom)._zoomTo(e)},m.prototype.coordinatePoint=function(t){var e=t.zoomTo(this.zoom),r=[e.column*this.tileSize,e.row*this.tileSize,0,1];return f.transformMat4(r,r,this.pixelMatrix),new i(r[0]/r[3],r[1]/r[3])},m.prototype.calculatePosMatrix=function(t,e){void 0===e&&(e=!1);var r=t.key,n=e?this._alignedPosMatrixCache:this._posMatrixCache;if(n[r])return n[r];var i=t.canonical,o=this.worldSize/this.zoomScale(i.z),a=i.x+Math.pow(2,i.z)*t.wrap,s=d.identity(new Float64Array(16));return d.translate(s,s,[a*o,i.y*o,0]),d.scale(s,s,[o/p,o/p,1]),d.multiply(s,e?this.alignedProjMatrix:this.projMatrix,s),n[r]=new Float32Array(s),n[r]},m.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var t,e,r,n,o=-90,a=90,s=-180,l=180,u=this.size,c=this._unmodified;if(this.latRange){var p=this.latRange;o=this.latY(p[1]),t=(a=this.latY(p[0]))-oa&&(n=a-y)}if(this.lngRange){var m=this.x,g=u.x/2;m-gl&&(r=l-g)}void 0===r&&void 0===n||(this.center=this.unproject(new i(void 0!==r?r:this.x,void 0!==n?n:this.y))),this._unmodified=c,this._constraining=!1}},m.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,r=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,i=this.y,o=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),a=new Float64Array(16);d.perspective(a,this._fov,this.width/this.height,1,o),d.scale(a,a,[1,-1,1]),d.translate(a,a,[0,0,-this.cameraToCenterDistance]),d.rotateX(a,a,this._pitch),d.rotateZ(a,a,this.angle),d.translate(a,a,[-n,-i,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));d.scale(a,a,[1,1,s,1]),this.projMatrix=a;var l=this.width%2/2,u=this.height%2/2,c=Math.cos(this.angle),p=Math.sin(this.angle),h=n-Math.round(n)+c*l+p*u,f=i-Math.round(i)+c*u+p*l,y=new Float64Array(a);if(d.translate(y,y,[h>.5?h-1:h,f>.5?f-1:f,0]),this.alignedProjMatrix=y,a=d.create(),d.scale(a,a,[this.width/2,-this.height/2,1]),d.translate(a,a,[1,-1,0]),this.pixelMatrix=d.multiply(new Float64Array(16),a,this.projMatrix),!(a=d.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=a,this._posMatrixCache={},this._alignedPosMatrixCache={}}},Object.defineProperties(m.prototype,g),e.exports=m},{"../data/extent":53,"../source/tile_id":114,"../style-spec/util/interpolate":158,"../util/tile_cover":273,"../util/util":275,"./coordinate":61,"./lng_lat":62,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],65:[function(t,e,r){var n=t("../style-spec/util/color"),i=function(t,e,r){this.blendFunction=t,this.blendColor=e,this.mask=r};i.disabled=new i(i.Replace=[1,0],n.transparent,[!1,!1,!1,!1]),i.unblended=new i(i.Replace,n.transparent,[!0,!0,!0,!0]),i.alphaBlended=new i([1,771],n.transparent,[!0,!0,!0,!0]),e.exports=i},{"../style-spec/util/color":153}],66:[function(t,e,r){var n=t("./index_buffer"),i=t("./vertex_buffer"),o=t("./framebuffer"),a=(t("./depth_mode"),t("./stencil_mode"),t("./color_mode")),s=t("../util/util"),l=t("./value"),u=l.ClearColor,c=l.ClearDepth,p=l.ClearStencil,h=l.ColorMask,f=l.DepthMask,d=l.StencilMask,y=l.StencilFunc,m=l.StencilOp,g=l.StencilTest,v=l.DepthRange,_=l.DepthTest,x=l.DepthFunc,b=l.Blend,w=l.BlendFunc,k=l.BlendColor,A=l.Program,T=l.LineWidth,M=l.ActiveTextureUnit,S=l.Viewport,C=l.BindFramebuffer,z=l.BindRenderbuffer,L=l.BindTexture,E=l.BindVertexBuffer,P=l.BindElementBuffer,I=l.BindVertexArrayOES,D=l.PixelStoreUnpack,O=l.PixelStoreUnpackPremultiplyAlpha,R=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new u(this),this.clearDepth=new c(this),this.clearStencil=new p(this),this.colorMask=new h(this),this.depthMask=new f(this),this.stencilMask=new d(this),this.stencilFunc=new y(this),this.stencilOp=new m(this),this.stencilTest=new g(this),this.depthRange=new v(this),this.depthTest=new _(this),this.depthFunc=new x(this),this.blend=new b(this),this.blendFunc=new w(this),this.blendColor=new k(this),this.program=new A(this),this.lineWidth=new T(this),this.activeTexture=new M(this),this.viewport=new S(this),this.bindFramebuffer=new C(this),this.bindRenderbuffer=new z(this),this.bindTexture=new L(this),this.bindVertexBuffer=new E(this),this.bindElementBuffer=new P(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new I(this),this.pixelStoreUnpack=new D(this),this.pixelStoreUnpackPremultiplyAlpha=new O(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear")};R.prototype.createIndexBuffer=function(t,e){return new n(this,t,e)},R.prototype.createVertexBuffer=function(t,e,r){return new i(this,t,e,r)},R.prototype.createRenderbuffer=function(t,e,r){var n=this.gl,i=n.createRenderbuffer();return this.bindRenderbuffer.set(i),n.renderbufferStorage(n.RENDERBUFFER,t,e,r),this.bindRenderbuffer.set(null),i},R.prototype.createFramebuffer=function(t,e){return new o(this,t,e)},R.prototype.clear=function(t){var e=t.color,r=t.depth,n=this.gl,i=0;e&&(i|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==r&&(i|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(r),this.depthMask.set(!0)),n.clear(i)},R.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1)},R.prototype.setStencilMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1)},R.prototype.setColorMode=function(t){s.deepEqual(t.blendFunction,a.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(t.blendFunction),this.blendColor.set(t.blendColor)),this.colorMask.set(t.mask)},e.exports=R},{"../util/util":275,"./color_mode":65,"./depth_mode":67,"./framebuffer":68,"./index_buffer":69,"./stencil_mode":70,"./value":71,"./vertex_buffer":72}],67:[function(t,e,r){var n=function(t,e,r){this.func=t,this.mask=e,this.range=r};n.ReadOnly=!1,n.ReadWrite=!0,n.disabled=new n(519,n.ReadOnly,[0,1]),e.exports=n},{}],68:[function(t,e,r){var n=t("./value"),i=n.ColorAttachment,o=n.DepthAttachment,a=function(t,e,r){this.context=t,this.width=e,this.height=r;var n=t.gl,a=this.framebuffer=n.createFramebuffer();this.colorAttachment=new i(t,a),this.depthAttachment=new o(t,a)};a.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var r=this.depthAttachment.get();r&&t.deleteRenderbuffer(r),t.deleteFramebuffer(this.framebuffer)},e.exports=a},{"./value":71}],69:[function(t,e,r){var n=function(t,e,r){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(r),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};n.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null)},n.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer)},n.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)},n.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer)},e.exports=n},{}],70:[function(t,e,r){var n=function(t,e,r,n,i,o){this.test=t,this.ref=e,this.mask=r,this.fail=n,this.depthFail=i,this.pass=o};n.disabled=new n({func:519,mask:0},0,0,7680,7680,7680),e.exports=n},{}],71:[function(t,e,r){var n=t("../style-spec/util/color"),i=t("../util/util"),o=function(t){this.context=t,this.current=n.transparent};o.prototype.get=function(){return this.current},o.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t)};var a=function(t){this.context=t,this.current=1};a.prototype.get=function(){return this.current},a.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t)};var s=function(t){this.context=t,this.current=0};s.prototype.get=function(){return this.current},s.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t)};var l=function(t){this.context=t,this.current=[!0,!0,!0,!0]};l.prototype.get=function(){return this.current},l.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t)};var u=function(t){this.context=t,this.current=!0};u.prototype.get=function(){return this.current},u.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t)};var c=function(t){this.context=t,this.current=255};c.prototype.get=function(){return this.current},c.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t)};var p=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255}};p.prototype.get=function(){return this.current},p.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t)};var h=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP]};h.prototype.get=function(){return this.current},h.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t)};var f=function(t){this.context=t,this.current=!1};f.prototype.get=function(){return this.current},f.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t}};var d=function(t){this.context=t,this.current=[0,1]};d.prototype.get=function(){return this.current},d.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t)};var y=function(t){this.context=t,this.current=!1};y.prototype.get=function(){return this.current},y.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t}};var m=function(t){this.context=t,this.current=t.gl.LESS};m.prototype.get=function(){return this.current},m.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t)};var g=function(t){this.context=t,this.current=!1};g.prototype.get=function(){return this.current},g.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t}};var v=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO]};v.prototype.get=function(){return this.current},v.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t)};var _=function(t){this.context=t,this.current=n.transparent};_.prototype.get=function(){return this.current},_.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t)};var x=function(t){this.context=t,this.current=null};x.prototype.get=function(){return this.current},x.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t)};var b=function(t){this.context=t,this.current=1};b.prototype.get=function(){return this.current},b.prototype.set=function(t){var e=this.context.lineWidthRange,r=i.clamp(t,e[0],e[1]);this.current!==r&&(this.context.gl.lineWidth(r),this.current=t)};var w=function(t){this.context=t,this.current=t.gl.TEXTURE0};w.prototype.get=function(){return this.current},w.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t)};var k=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight]};k.prototype.get=function(){return this.current},k.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t)};var A=function(t){this.context=t,this.current=null};A.prototype.get=function(){return this.current},A.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t}};var T=function(t){this.context=t,this.current=null};T.prototype.get=function(){return this.current},T.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t}};var M=function(t){this.context=t,this.current=null};M.prototype.get=function(){return this.current},M.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t}};var S=function(t){this.context=t,this.current=null};S.prototype.get=function(){return this.current},S.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t}};var C=function(t){this.context=t,this.current=null};C.prototype.get=function(){return this.current},C.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t};var z=function(t){this.context=t,this.current=null};z.prototype.get=function(){return this.current},z.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t)};var L=function(t){this.context=t,this.current=4};L.prototype.get=function(){return this.current},L.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t}};var E=function(t){this.context=t,this.current=!1};E.prototype.get=function(){return this.current},E.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t}};var P=function(t,e){this.context=t,this.current=null,this.parent=e};P.prototype.get=function(){return this.current};var I=function(t){function e(e,r){t.call(this,e,r),this.dirty=!1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1}},e.prototype.setDirty=function(){this.dirty=!0},e}(P),D=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t}},e}(P);e.exports={ClearColor:o,ClearDepth:a,ClearStencil:s,ColorMask:l,DepthMask:u,StencilMask:c,StencilFunc:p,StencilOp:h,StencilTest:f,DepthRange:d,DepthTest:y,DepthFunc:m,Blend:g,BlendFunc:v,BlendColor:_,Program:x,LineWidth:b,ActiveTextureUnit:w,Viewport:k,BindFramebuffer:A,BindRenderbuffer:T,BindTexture:M,BindVertexBuffer:S,BindElementBuffer:C,BindVertexArrayOES:z,PixelStoreUnpack:L,PixelStoreUnpackPremultiplyAlpha:E,ColorAttachment:I,DepthAttachment:D}},{"../style-spec/util/color":153,"../util/util":275}],72:[function(t,e,r){var n={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},i=function(t,e,r,n){this.length=e.length,this.attributes=r,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var i=t.gl;this.buffer=i.createBuffer(),t.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};i.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer)},i.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer)},i.prototype.enableAttributes=function(t,e){for(var r=0;r":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]}},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../util/browser":252,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],78:[function(t,e,r){function n(t,e,r,n,i){if(!s.isPatternMissing(r.paint.get("fill-pattern"),t))for(var o=!0,a=0,l=n;a0){var l=a.now(),u=(l-t.timeAdded)/s,c=e?(l-e.timeAdded)/s:-1,p=r.getSource(),h=o.coveringZoomLevel({tileSize:p.tileSize,roundZoom:p.roundZoom}),f=!e||Math.abs(e.tileID.overscaledZ-h)>Math.abs(t.tileID.overscaledZ-h),d=f&&t.refreshedUponExpiration?1:i.clamp(f?u:1-c,0,1);return t.refreshedUponExpiration&&u>=1&&(t.refreshedUponExpiration=!1),e?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return{opacity:1,mix:0}}var i=t("../util/util"),o=t("../source/image_source"),a=t("../util/browser"),s=t("../gl/stencil_mode"),l=t("../gl/depth_mode");e.exports=function(t,e,r,i){if("translucent"===t.renderPass&&0!==r.paint.get("raster-opacity")){var a=t.context,u=a.gl,c=e.getSource(),p=t.useProgram("raster");a.setStencilMode(s.disabled),a.setColorMode(t.colorModeForRenderPass()),u.uniform1f(p.uniforms.u_brightness_low,r.paint.get("raster-brightness-min")),u.uniform1f(p.uniforms.u_brightness_high,r.paint.get("raster-brightness-max")),u.uniform1f(p.uniforms.u_saturation_factor,function(t){return t>0?1-1/(1.001-t):-t}(r.paint.get("raster-saturation"))),u.uniform1f(p.uniforms.u_contrast_factor,function(t){return t>0?1/(1-t):1+t}(r.paint.get("raster-contrast"))),u.uniform3fv(p.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),r=Math.cos(t);return[(2*r+1)/3,(-Math.sqrt(3)*e-r+1)/3,(Math.sqrt(3)*e-r+1)/3]}(r.paint.get("raster-hue-rotate"))),u.uniform1f(p.uniforms.u_buffer_scale,1),u.uniform1i(p.uniforms.u_image0,0),u.uniform1i(p.uniforms.u_image1,1);for(var h=i.length&&i[0].overscaledZ,f=0,d=i;f65535)e(new Error("glyphs > 65535 not supported"));else{var u=a.requests[l];u||(u=a.requests[l]=[],n(i,l,r.url,r.requestTransform,function(t,e){if(e)for(var r in e)a.glyphs[+r]=e[+r];for(var n=0,i=u;nthis.height)return n.warnOnce("LineAtlas out of space"),null;for(var a=0,s=0;s=0;this.currentLayer--){var m=r.style._layers[a[r.currentLayer]];m.source!==(d&&d.id)&&(y=[],(d=r.style.sourceCaches[m.source])&&(r.clearStencil(),y=d.getVisibleCoordinates(),d.getSource().isTileClipped&&r._renderTileClippingMasks(y))),r.renderLayer(r,d,m,y)}this.renderPass="translucent";var g,v=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer0?e.pop():null},M.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var r=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[r]||(this.cache[r]=new v(this.context,g[t],e,this._showOverdrawInspector)),this.cache[r]},M.prototype.useProgram=function(t,e){var r=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(r.program),r},e.exports=M},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../data/program_configuration":58,"../data/raster_bounds_attributes":59,"../gl/color_mode":65,"../gl/context":66,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../shaders":97,"../source/pixels_to_tile_units":104,"../source/source_cache":111,"../style-spec/util/color":153,"../symbol/cross_tile_symbol_index":218,"../util/browser":252,"../util/util":275,"./draw_background":74,"./draw_circle":75,"./draw_debug":77,"./draw_fill":78,"./draw_fill_extrusion":79,"./draw_heatmap":80,"./draw_hillshade":81,"./draw_line":82,"./draw_raster":83,"./draw_symbol":84,"./program":92,"./texture":93,"./tile_mask":94,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],91:[function(t,e,r){var n=t("../source/pixels_to_tile_units");r.isPatternMissing=function(t,e){if(!t)return!1;var r=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!r||!n},r.prepare=function(t,e,r){var n=e.context,i=n.gl,o=e.imageManager.getPattern(t.from),a=e.imageManager.getPattern(t.to);i.uniform1i(r.uniforms.u_image,0),i.uniform2fv(r.uniforms.u_pattern_tl_a,o.tl),i.uniform2fv(r.uniforms.u_pattern_br_a,o.br),i.uniform2fv(r.uniforms.u_pattern_tl_b,a.tl),i.uniform2fv(r.uniforms.u_pattern_br_b,a.br);var s=e.imageManager.getPixelSize(),l=s.width,u=s.height;i.uniform2fv(r.uniforms.u_texsize,[l,u]),i.uniform1f(r.uniforms.u_mix,t.t),i.uniform2fv(r.uniforms.u_pattern_size_a,o.displaySize),i.uniform2fv(r.uniforms.u_pattern_size_b,a.displaySize),i.uniform1f(r.uniforms.u_scale_a,t.fromScale),i.uniform1f(r.uniforms.u_scale_b,t.toScale),n.activeTexture.set(i.TEXTURE0),e.imageManager.bind(e.context)},r.setTile=function(t,e,r){var i=e.context.gl;i.uniform1f(r.uniforms.u_tile_units_to_pixels,1/n(t,1,e.transform.tileZoom));var o=Math.pow(2,t.tileID.overscaledZ),a=t.tileSize*Math.pow(2,e.transform.tileZoom)/o,s=a*(t.tileID.canonical.x+t.tileID.wrap*o),l=a*t.tileID.canonical.y;i.uniform2f(r.uniforms.u_pixel_coord_upper,s>>16,l>>16),i.uniform2f(r.uniforms.u_pixel_coord_lower,65535&s,65535&l)}},{"../source/pixels_to_tile_units":104}],92:[function(t,e,r){var n=t("../util/browser"),i=t("../shaders"),o=(t("../data/program_configuration").ProgramConfiguration,t("./vertex_array_object")),a=(t("../gl/context"),function(t,e,r,o){var a=this,s=t.gl;this.program=s.createProgram();var l=r.defines().concat("#define DEVICE_PIXEL_RATIO "+n.devicePixelRatio.toFixed(1));o&&l.push("#define OVERDRAW_INSPECTOR;");var u=l.concat(i.prelude.fragmentSource,e.fragmentSource).join("\n"),c=l.concat(i.prelude.vertexSource,e.vertexSource).join("\n"),p=s.createShader(s.FRAGMENT_SHADER);s.shaderSource(p,u),s.compileShader(p),s.attachShader(this.program,p);var h=s.createShader(s.VERTEX_SHADER);s.shaderSource(h,c),s.compileShader(h),s.attachShader(this.program,h);for(var f=r.layoutAttributes||[],d=0;d 0.5) {\n gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n gl_FragColor *= .1;\n }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n float alpha = 0.5;\n\n // Red = collision, hide label\n vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n // Blue = no collision, label is showing\n if (v_placed > 0.5) {\n color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n color *= .2;\n }\n\n float extrude_scale_length = length(v_extrude_scale);\n float extrude_length = length(v_extrude) * extrude_scale_length;\n float stroke_width = 15.0 * extrude_scale_length;\n float radius = v_radius * extrude_scale_length;\n\n float distance_to_edge = abs(extrude_length - radius);\n float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n v_extrude = a_extrude * padding_factor;\n v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n // find distance to outline for alpha interpolation\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n vec3 normal = a_normal_ed.xyz;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n\n gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n // Relative luminance (how dark/bright is the surface color?)\n float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n // Add slight ambient lighting so no extrusions are totally black\n vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n color += ambientlight;\n\n // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n // Adjust directional so that\n // the range of values for highlight/shading is narrower\n // with lower light intensity\n // and with lighter/brighter surface colors\n directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n // Add gradient along z axis of side surfaces\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n // with lower bounds adjusted to hue of light\n // so that shading is tinted with the complementary (opposite) color to the light color\n v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n vec4 mixedColor = mix(color1, color2, u_mix);\n\n gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec3 normal = a_normal_ed.xyz;\n float edgedistance = a_normal_ed.w;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n float z = t > 0.0 ? height : base;\n\n gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n ? a_pos // extrusion top\n : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n v_pos.x = a_pos.x;\n v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\n\nfloat getElevation(vec2 coord, float bias) {\n // Convert encoded elevation value to meters\n vec4 data = texture2D(u_image, coord) * 255.0;\n return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n vec2 epsilon = 1.0 / u_dimension;\n\n // queried pixels:\n // +-----------+\n // | | | |\n // | a | b | c |\n // | | | |\n // +-----------+\n // | | | |\n // | d | e | f |\n // | | | |\n // +-----------+\n // | | | |\n // | g | h | i |\n // | | | |\n // +-----------+\n\n float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n float e = getElevation(v_pos, 0.0);\n float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n // here we divide the x and y slopes by 8 * pixel size\n // where pixel size (aka meters/pixel) is:\n // circumference of the world / (pixels per tile * number of tiles)\n // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n // we want to vertically exaggerate the hillshading though, because otherwise\n // it is barely noticeable at low zooms. to do this, we multiply this by some\n // scale factor pow(2, (u_zoom - 14) * a) where a is an arbitrary value and 14 is the\n // maxzoom of the tile source. here we use a=0.3 which works out to the\n // expression below. see nickidlugash's awesome breakdown for more info\n // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n vec2 deriv = vec2(\n (c + f + f + i) - (a + d + d + g),\n (g + h + h + i) - (a + b + b + c)\n ) / pow(2.0, (u_zoom - 14.0) * exaggeration + 19.2562 - u_zoom);\n\n gl_FragColor = clamp(vec4(\n deriv.x / 2.0 + 0.5,\n deriv.y / 2.0 + 0.5,\n 1.0,\n 1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n vec4 pixel = texture2D(u_image, v_pos);\n\n vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n // to account for mercator projection distortion. see #4807 for details\n float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n // We also multiply the slope by an arbitrary z-factor of 1.25\n float slope = atan(1.25 * length(deriv) / scaleFactor);\n float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n float intensity = u_light.x;\n // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n float azimuth = u_light.y + PI;\n\n // We scale the slope exponentially based on intensity, using a calculation similar to\n // the exponential interpolation function in the style spec:\n // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n // so that higher intensity values create more opaque hillshading.\n float base = 1.875 - intensity * 1.75;\n float maxValue = 0.5 * PI;\n float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n // so that the accent color's rate of change eases in while the shade color's eases out.\n float accent = cos(scaledSlope);\n // We multiply both the accent and shade color by a clamped intensity value\n // so that intensities >= 0.5 do not additionally affect the color values\n // while intensity values < 0.5 make the overall color more transparent.\n vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n float y_a = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_a.y);\n float y_b = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_b.y);\n vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_linesofar = a_linesofar;\n v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float sdfdist_a = texture2D(u_image, v_tex_a).a;\n float sdfdist_b = texture2D(u_image, v_tex_b).a;\n float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist =outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n // read and cross-fade colors from the main and parent tiles\n vec4 color0 = texture2D(u_image0, v_pos0);\n vec4 color1 = texture2D(u_image1, v_pos1);\n if (color0.a > 0.0) {\n color0.rgb = color0.rgb / color0.a;\n }\n if (color1.a > 0.0) {\n color1.rgb = color1.rgb / color1.a;\n }\n vec4 color = mix(color0, color1, u_fade_t);\n color.a *= u_opacity;\n vec3 rgb = color.rgb;\n\n // spin\n rgb = vec3(\n dot(rgb, u_spin_weights.xyz),\n dot(rgb, u_spin_weights.zxy),\n dot(rgb, u_spin_weights.yzx));\n\n // saturation\n float average = (color.r + color.g + color.b) / 3.0;\n rgb += (average - rgb) * u_saturation_factor;\n\n // contrast\n rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n // brightness\n vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n // We are using Int16 for texture position coordinates to give us enough precision for\n // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n // as an arbitrarily high number to preserve adequate precision when rendering.\n // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n // so math for modifying either is consistent.\n v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n lowp float alpha = opacity * v_fade_opacity;\n gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n\n float size;\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // See comments in symbol_sdf.vertex\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // See comments in symbol_sdf.vertex\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n\n v_tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 tex = v_data0.xy;\n float gamma_scale = v_data1.x;\n float size = v_data1.y;\n float fade_opacity = v_data1[2];\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n lowp vec4 color = fill_color;\n highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n lowp float buff = (256.0 - 64.0) / 256.0;\n if (u_is_halo) {\n color = halo_color;\n gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n buff = (6.0 - halo_width / fontScale) / SDF_PX;\n }\n\n lowp float dist = texture2D(u_texture, tex).a;\n highp float gamma_scaled = gamma * gamma_scale;\n highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n// text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n float size;\n\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // If the label is pitched with the map, layout is done in pitched space,\n // which makes labels in the distance smaller relative to viewport space.\n // We counteract part of that effect by multiplying by the perspective ratio.\n // If the label isn't pitched with the map, we do layout in viewport space,\n // which makes labels in the distance larger relative to the features around\n // them. We counteract part of that effect by dividing by the perspective ratio.\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n // To figure out that angle in projected space, we draw a short horizontal line in tile\n // space, project it, and measure its angle in projected space.\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n float gamma_scale = gl_Position.w;\n\n vec2 tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n v_data0 = vec2(tex.x, tex.y);\n v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o=function(t){var e=n[t],r={};e.fragmentSource=e.fragmentSource.replace(i,function(t,e,n,i,o){return r[o]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+o+"\nvarying "+n+" "+i+" "+o+";\n#else\nuniform "+n+" "+i+" u_"+o+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+o+"\n "+n+" "+i+" "+o+" = u_"+o+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(i,function(t,e,n,i,o){var a="float"===i?"vec2":"vec4";return r[o]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+o+"\nuniform lowp float a_"+o+"_t;\nattribute "+n+" "+a+" a_"+o+";\nvarying "+n+" "+i+" "+o+";\n#else\nuniform "+n+" "+i+" u_"+o+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+o+"\n "+o+" = unpack_mix_"+a+"(a_"+o+", a_"+o+"_t);\n#else\n "+n+" "+i+" "+o+" = u_"+o+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+o+"\nuniform lowp float a_"+o+"_t;\nattribute "+n+" "+a+" a_"+o+";\n#else\nuniform "+n+" "+i+" u_"+o+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+o+"\n "+n+" "+i+" "+o+" = unpack_mix_"+a+"(a_"+o+", a_"+o+"_t);\n#else\n "+n+" "+i+" "+o+" = u_"+o+";\n#endif\n"})};for(var a in n)o(a);e.exports=n},{}],98:[function(t,e,r){var n=t("./image_source"),i=t("../util/window"),o=t("../data/raster_bounds_attributes"),a=t("../render/vertex_array_object"),s=t("../render/texture"),l=function(t){function e(e,r,n,i){t.call(this,e,r,n,i),this.options=r,this.animate=void 0===r.animate||r.animate}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.load=function(){this.canvas=this.canvas||i.document.getElementById(this.options.canvas),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire("error",new Error("Canvas dimensions cannot be less than or equal to zero.")):(this.play=function(){this._playing=!0,this.map._rerender()},this.pause=function(){this._playing=!1},this._finishLoading())},e.prototype.getCanvas=function(){return this.canvas},e.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()},e.prototype.onRemove=function(){this.pause()},e.prototype.prepare=function(){var t=this,e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var r=this.map.painter.context,n=r.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=r.createVertexBuffer(this._boundsArray,o.members)),this.boundsVAO||(this.boundsVAO=new a),this.texture?e?this.texture.update(this.canvas):this._playing&&(this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.canvas)):(this.texture=new s(r,this.canvas,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE)),t.tiles){var l=t.tiles[i];"loaded"!==l.state&&(l.state="loaded",l.texture=t.texture)}}},e.prototype.serialize=function(){return{type:"canvas",canvas:this.canvas,coordinates:this.coordinates}},e.prototype.hasTransition=function(){return this._playing},e.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t0&&(r.resourceTiming=t._resourceTiming,t._resourceTiming=[]),t.fire("data",r)}})},e.prototype.onAdd=function(t){this.map=t,this.load()},e.prototype.setData=function(t){var e=this;return this._data=t,this.fire("dataloading",{dataType:"source"}),this._updateWorkerData(function(t){if(t)return e.fire("error",{error:t});var r={dataType:"source",sourceDataType:"content"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(r.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire("data",r)}),this},e.prototype._updateWorkerData=function(t){var e=this,r=i.extend({},this.workerOptions),n=this._data;"string"==typeof n?(r.request=this.map._transformRequest(function(t){var e=o.document.createElement("a");return e.href=t,e.href}(n),s.Source),r.request.collectResourceTiming=this._collectResourceTiming):r.data=JSON.stringify(n),this.workerID=this.dispatcher.send(this.type+".loadData",r,function(r,n){e._loaded=!0,n&&n.resourceTiming&&n.resourceTiming[e.id]&&(e._resourceTiming=n.resourceTiming[e.id].slice(0)),t(r)},this.workerID)},e.prototype.loadTile=function(t,e){var r=this,n=void 0===t.workerID||"expired"===t.state?"loadTile":"reloadTile",i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:l.devicePixelRatio,overscaling:t.tileID.overscaleFactor(),showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,i,function(i,o){return t.unloadVectorData(),t.aborted?e(null):i?e(i):(t.loadVectorData(o,r.map.painter,"reloadTile"===n),e(null))},this.workerID)},e.prototype.abortTile=function(t){t.aborted=!0},e.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID)},e.prototype.onRemove=function(){this.dispatcher.broadcast("removeSource",{type:this.type,source:this.id})},e.prototype.serialize=function(){return i.extend({},this._options,{type:this.type,data:this._data})},e.prototype.hasTransition=function(){return!1},e}(n);e.exports=u},{"../data/extent":53,"../util/ajax":251,"../util/browser":252,"../util/evented":260,"../util/util":275,"../util/window":254}],100:[function(t,e,r){function n(t,e){var r=t.source,n=t.tileID.canonical;if(!this._geoJSONIndexes[r])return e(null,null);var i=this._geoJSONIndexes[r].getTile(n.z,n.x,n.y);if(!i)return e(null,null);var o=new s(i.features),a=l(o);0===a.byteOffset&&a.byteLength===a.buffer.byteLength||(a=new Uint8Array(a)),e(null,{vectorTile:o,rawData:a.buffer})}var i=t("../util/ajax"),o=t("../util/performance"),a=t("geojson-rewind"),s=t("./geojson_wrapper"),l=t("vt-pbf"),u=t("supercluster"),c=t("geojson-vt"),p=function(t){function e(e,r,i){t.call(this,e,r,n),i&&(this.loadGeoJSON=i),this._geoJSONIndexes={}}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.loadData=function(t,e){var r=this;this.loadGeoJSON(t,function(n,i){if(n||!i)return e(n);if("object"!=typeof i)return e(new Error("Input data is not a valid GeoJSON object."));a(i,!0);try{r._geoJSONIndexes[t.source]=t.cluster?u(t.superclusterOptions).load(i.features):c(i,t.geojsonVtOptions)}catch(n){return e(n)}r.loaded[t.source]={};var s={};if(t.request&&t.request.collectResourceTiming){var l=o.getEntriesByName(t.request.url);l&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(l)))}e(null,s)})},e.prototype.reloadTile=function(e,r){var n=this.loaded[e.source],i=e.uid;return n&&n[i]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},e.prototype.loadGeoJSON=function(t,e){if(t.request)i.getJSON(t.request,e);else{if("string"!=typeof t.data)return e(new Error("Input data is not a valid GeoJSON object."));try{return e(null,JSON.parse(t.data))}catch(t){return e(new Error("Input data is not a valid GeoJSON object."))}}},e.prototype.removeSource=function(t,e){this._geoJSONIndexes[t.source]&&delete this._geoJSONIndexes[t.source],e()},e}(t("./vector_tile_worker_source"));e.exports=p},{"../util/ajax":251,"../util/performance":268,"./geojson_wrapper":101,"./vector_tile_worker_source":116,"geojson-rewind":15,"geojson-vt":19,supercluster:32,"vt-pbf":34}],101:[function(t,e,r){var n=t("@mapbox/point-geometry"),i=t("@mapbox/vector-tile").VectorTileFeature.prototype.toGeoJSON,o=t("../data/extent"),a=function(t){this._feature=t,this.extent=o,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10))};a.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],e=0,r=this._feature.geometry;e0&&(l[new s(t.overscaledZ,i,e.z,n,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,t.wrap,e.z,e.x,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,a,e.z,o,e.y-1).key]={backfilled:!1}),e.y+11||(Math.abs(r)>1&&(1===Math.abs(r+i)?r+=i:1===Math.abs(r-i)&&(r-=i)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,r,n),t.neighboringTiles&&t.neighboringTiles[o]&&(t.neighboringTiles[o].backfilled=!0)))}for(var r=this.getRenderableIds(),n=0;ne)){var s=Math.pow(2,a.tileID.canonical.z-t.canonical.z);if(Math.floor(a.tileID.canonical.x/s)===t.canonical.x&&Math.floor(a.tileID.canonical.y/s)===t.canonical.y)for(r[o]=a.tileID,i=!0;a&&a.tileID.overscaledZ-1>t.overscaledZ;){var l=a.tileID.scaledTo(a.tileID.overscaledZ-1);if(!l)break;(a=n._tiles[l.key])&&a.hasData()&&(delete r[o],r[l.key]=l)}}}return i},e.prototype.findLoadedParent=function(t,e,r){for(var n=this,i=t.overscaledZ-1;i>=e;i--){var o=t.scaledTo(i);if(!o)return;var a=String(o.key),s=n._tiles[a];if(s&&s.hasData())return r[a]=o,s;if(n._cache.has(a))return r[a]=o,n._cache.get(a)}},e.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),r=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)},e.prototype.update=function(t){var r=this;if(this.transform=t,this._sourceLoaded&&!this._paused){var n;this.updateCacheSize(t),this._coveredTiles={},this.used?this._source.tileID?n=t.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(t){return new d(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y)}):(n=t.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(n=n.filter(function(t){return r._source.hasTile(t)}))):n=[];var o,a=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(t)),s=Math.max(a-e.maxOverzooming,this._source.minzoom),l=Math.max(a+e.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(n,a),p={};if(i(this._source.type))for(var h=Object.keys(u),y=0;y=f.now())){r._findLoadedChildren(g,l,u)&&(u[m]=g);var _=r.findLoadedParent(g,s,p);_&&r._addTile(_.tileID)}}for(o in p)u[o]||(r._coveredTiles[o]=!0);for(o in p)u[o]=p[o];for(var x=c.keysDifference(this._tiles,u),b=0;bn._source.maxzoom){var f=u.children(n._source.maxzoom)[0],d=n.getTile(f);d&&d.hasData()?i[f.key]=f:h=!1}else{n._findLoadedChildren(u,s,i);for(var y=u.children(n._source.maxzoom),m=0;m=a;--g){var v=u.scaledTo(g);if(o[v.key])break;if(o[v.key]=!0,!(c=n.getTile(v))&&p&&(c=n._addTile(v)),c&&(i[v.key]=v,p=c.wasRequested(),c.hasData()))break}}}return i},e.prototype._addTile=function(t){var e=this._tiles[t.key];if(e)return e;(e=this._cache.getAndRemove(t.key))&&this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,e));var r=Boolean(e);return r||(e=new a(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(e,this._tileLoaded.bind(this,e,t.key,e.state))),e?(e.uses++,this._tiles[t.key]=e,r||this._source.fire("dataloading",{tile:e,coord:e.tileID,dataType:"source"}),e):null},e.prototype._setTileReloadTimer=function(t,e){var r=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){r._reloadTile(t,"expired"),delete r._timers[t]},n))},e.prototype._setCacheInvalidationTimer=function(t,e){var r=this;t in this._cacheTimers&&(clearTimeout(this._cacheTimers[t]),delete this._cacheTimers[t]);var n=e.getExpiryTimeout();n&&(this._cacheTimers[t]=setTimeout(function(){r._cache.remove(t),delete r._cacheTimers[t]},n))},e.prototype._removeTile=function(t){var e=this._tiles[t];if(e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),!(e.uses>0)))if(e.hasData()){e.tileID=e.tileID.wrapped();var r=e.tileID.key;this._cache.add(r,e),this._setCacheInvalidationTimer(r,e)}else e.aborted=!0,this._abortTile(e),this._unloadTile(e)},e.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._resetCache()},e.prototype._resetCache=function(){for(var t in this._cacheTimers)clearTimeout(this._cacheTimers[t]);this._cacheTimers={},this._cache.reset()},e.prototype.tilesIn=function(t){for(var e=[],r=this.getIds(),i=1/0,o=1/0,a=-1/0,s=-1/0,l=t[0].zoom,c=0;c=0&&m[1].y>=0){for(var g=[],v=0;v=f.now())return!0}return!1},e}(s);y.maxOverzooming=10,y.maxUnderzooming=3,e.exports=y},{"../data/extent":53,"../geo/coordinate":61,"../gl/context":66,"../util/browser":252,"../util/evented":260,"../util/lru_cache":266,"../util/util":275,"./source":110,"./tile":112,"./tile_id":114,"@mapbox/point-geometry":4}],112:[function(t,e,r){var n=t("../util/util"),i=t("../data/bucket").deserialize,o=(t("../data/feature_index"),t("@mapbox/vector-tile")),a=t("pbf"),s=t("../util/vectortile_to_geojson"),l=t("../style-spec/feature_filter"),u=(t("../symbol/collision_index"),t("../data/bucket/symbol_bucket")),c=t("../data/array_types"),p=c.RasterBoundsArray,h=c.CollisionBoxArray,f=t("../data/raster_bounds_attributes"),d=t("../data/extent"),y=t("@mapbox/point-geometry"),m=t("../render/texture"),g=t("../data/segment").SegmentVector,v=t("../data/index_array_type").TriangleIndexArray,_=t("../util/browser"),x=function(t,e){this.tileID=t,this.uid=n.uniqueId(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.expiredRequestCount=0,this.state="loading"};x.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e<_.now()||this.fadeEndTime&&e>s.z,u=new y(s.x*l,s.y*l),c=new y(u.x+l,u.y+l),h=this.segments.prepareSegment(4,r,i);r.emplaceBack(u.x,u.y,u.x,u.y),r.emplaceBack(c.x,u.y,c.x,u.y),r.emplaceBack(u.x,c.y,u.x,c.y),r.emplaceBack(c.x,c.y,c.x,c.y);var m=h.vertexLength;i.emplaceBack(m,m+1,m+2),i.emplaceBack(m+1,m+2,m+3),h.vertexLength+=4,h.primitiveLength+=2}this.maskedBoundsBuffer=e.createVertexBuffer(r,f.members),this.maskedIndexBuffer=e.createIndexBuffer(i)}},x.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},x.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=n.parseCacheControl(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"])}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var i=Date.now(),o=!1;if(this.expirationTime>i)o=!1;else if(e)if(this.expirationTime=e&&t.x=r&&t.y0;o--)i+=(e&(n=1<this.canonical.z?new u(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new u(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},u.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e},u.prototype.children=function(t){if(this.overscaledZ>=t)return[new u(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new u(e,this.wrap,e,r,n),new u(e,this.wrap,e,r+1,n),new u(e,this.wrap,e,r,n+1),new u(e,this.wrap,e,r+1,n+1)]},u.prototype.isLessThan=function(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=z.maxzoom||"none"===z.visibility||(n(C,d.zoom),(g[z.id]=z.createBucket({index:m.bucketLayerIDs.length,layers:C,zoom:d.zoom,pixelRatio:d.pixelRatio,overscaling:d.overscaling,collisionBoxArray:d.collisionBoxArray})).populate(k,v),m.bucketLayerIDs.push(C.map(function(t){return t.id})))}}}var L,E,P,I=u.mapObject(v.glyphDependencies,function(t){return Object.keys(t).map(Number)});Object.keys(I).length?r.send("getGlyphs",{uid:this.uid,stacks:I},function(t,e){L||(L=t,E=e,f.call(d))}):E={};var D=Object.keys(v.iconDependencies);D.length?r.send("getImages",{icons:D},function(t,e){L||(L=t,P=e,f.call(d))}):P={},f.call(this)},e.exports=d},{"../data/array_types":39,"../data/bucket/symbol_bucket":51,"../data/feature_index":54,"../render/glyph_atlas":85,"../render/image_atlas":87,"../style/evaluation_parameters":182,"../symbol/symbol_layout":227,"../util/dictionary_coder":257,"../util/util":275,"./tile_id":114}],120:[function(t,e,r){function n(t,e){var r={};for(var n in t)"ref"!==n&&(r[n]=t[n]);return i.forEach(function(t){t in e&&(r[t]=e[t])}),r}var i=t("./util/ref_properties");e.exports=function(t){t=t.slice();for(var e=Object.create(null),r=0;r4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in f))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=f[i]}else r=a;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2]}var s=o(r,n),l=e.parse(t[t.length-1],t.length-1,a);return l?new d(s,l):null},d.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(c(this.type,p(e)))throw new h("Expected value to be of type "+i(this.type)+", but found "+i(p(e))+" instead.");return e},d.prototype.eachChild=function(t){t(this.input)},d.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},e.exports=d},{"../runtime_error":143,"../types":146,"../values":147}],125:[function(t,e,r){var n=t("../types"),i=n.ObjectType,o=n.ValueType,a=n.StringType,s=n.NumberType,l=n.BooleanType,u=t("../runtime_error"),c=t("../types"),p=c.checkSubtype,h=c.toString,f=t("../values").typeOf,d={string:a,number:s,boolean:l,object:i},y=function(t,e){this.type=t,this.args=e};y.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=d[r],i=[],a=1;a=r.length)throw new s("Array index out of bounds: "+e+" > "+r.length+".");if(e!==Math.floor(e))throw new s("Array index must be an integer, but found "+e+" instead.");return r[e]},l.prototype.eachChild=function(t){t(this.index),t(this.input)},l.prototype.possibleOutputs=function(){return[void 0]},e.exports=l},{"../runtime_error":143,"../types":146}],127:[function(t,e,r){var n=t("../types").BooleanType,i=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r};i.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var o=[],a=1;a4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":u(e[0],e[1],e[2],e[3])))return new l(e[0]/255,e[1]/255,e[2]/255,e[3]);throw new c(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var a=null,s=0,p=this.args;sn.evaluate(t)}function u(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function c(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}var p=t("../types"),h=p.NumberType,f=p.StringType,d=p.BooleanType,y=p.ColorType,m=p.ObjectType,g=p.ValueType,v=p.ErrorType,_=p.array,x=p.toString,b=t("../values"),w=b.typeOf,k=b.Color,A=b.validateRGBA,T=t("../compound_expression"),M=T.CompoundExpression,S=T.varargs,C=t("../runtime_error"),z=t("./let"),L=t("./var"),E=t("./literal"),P=t("./assertion"),I=t("./array"),D=t("./coercion"),O=t("./at"),R=t("./match"),B=t("./case"),F=t("./step"),N=t("./interpolate"),j=t("./coalesce"),V=t("./equals"),q={"==":V.Equals,"!=":V.NotEquals,array:I,at:O,boolean:P,case:B,coalesce:j,interpolate:N,let:z,literal:E,match:R,number:P,object:P,step:F,string:P,"to-color":D,"to-number":D,var:L};M.register(q,{error:[v,[f],function(t,e){var r=e[0];throw new C(r.evaluate(t))}],typeof:[f,[g],function(t,e){var r=e[0];return x(w(r.evaluate(t)))}],"to-string":[f,[g],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r||"string"===n||"number"===n||"boolean"===n?String(r):r instanceof k?r.toString():JSON.stringify(r)}],"to-boolean":[d,[g],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[_(h,4),[y],function(t,e){var r=e[0].evaluate(t),n=r.r,i=r.g,o=r.b,a=r.a;return[255*n/a,255*i/a,255*o/a,a]}],rgb:[y,[h,h,h],n],rgba:[y,[h,h,h,h],n],length:{type:h,overloads:[[[f],a],[[_(g)],a]]},has:{type:d,overloads:[[[f],function(t,e){return i(e[0].evaluate(t),t.properties())}],[[f,m],function(t,e){var r=e[0],n=e[1];return i(r.evaluate(t),n.evaluate(t))}]]},get:{type:g,overloads:[[[f],function(t,e){return o(e[0].evaluate(t),t.properties())}],[[f,m],function(t,e){var r=e[0],n=e[1];return o(r.evaluate(t),n.evaluate(t))}]]},properties:[m,[],function(t){return t.properties()}],"geometry-type":[f,[],function(t){return t.geometryType()}],id:[g,[],function(t){return t.id()}],zoom:[h,[],function(t){return t.globals.zoom}],"heatmap-density":[h,[],function(t){return t.globals.heatmapDensity||0}],"+":[h,S(h),function(t,e){for(var r=0,n=0,i=e;n":[d,[f,g],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i>o}],"filter-id->":[d,[g],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[d,[f,g],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i<=o}],"filter-id-<=":[d,[g],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[d,[f,g],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],o=n.value;return typeof i==typeof o&&i>=o}],"filter-id->=":[d,[g],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[d,[g],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[d,[],function(t){return null!==t.id()}],"filter-type-in":[d,[_(f)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[d,[_(g)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[d,[f,_(g)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[d,[f,_(g)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:d,overloads:[[[h,h],l],[[f,f],l]]},"<":{type:d,overloads:[[[h,h],s],[[f,f],s]]},">=":{type:d,overloads:[[[h,h],c],[[f,f],c]]},"<=":{type:d,overloads:[[[h,h],u],[[f,f],u]]},all:{type:d,overloads:[[[d,d],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[S(d),function(t,e){for(var r=0,n=e;r1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:a}}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,l)))return null;var u=[],p=null;e.expectedType&&"value"!==e.expectedType.kind&&(p=e.expectedType);for(var h=0;h=f)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',y);var g=e.parse(d,m,p);if(!g)return null;p=p||g.type,u.push([f,g])}return"number"===p.kind||"color"===p.kind||"array"===p.kind&&"number"===p.itemType.kind&&"number"==typeof p.N?new c(p,r,n,u):e.error("Type "+s(p)+" is not interpolatable.")},c.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=u(e,n),s=e[a],l=e[a+1],p=c.interpolationFactor(this.interpolation,n,s,l),h=r[a].evaluate(t),f=r[a+1].evaluate(t);return o[this.type.kind.toLowerCase()](h,f,p)},c.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;eNumber.MAX_SAFE_INTEGER)return p.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof d&&Math.floor(d)!==d)return p.error("Numeric branch labels must be integer values.");if(r){if(p.checkSubtype(r,n(d)))return null}else r=n(d);if(void 0!==a[String(d)])return p.error("Branch labels must be unique.");a[String(d)]=s.length}var y=e.parse(c,l,o);if(!y)return null;o=o||y.type,s.push(y)}var m=e.parse(t[1],1,r);if(!m)return null;var g=e.parse(t[t.length-1],t.length-1,o);return g?new i(r,o,m,a,s,g):null},i.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},i.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)},i.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t},e.exports=i},{"../values":147}],136:[function(t,e,r){var n=t("../types").NumberType,i=t("../stops").findStopLessThanOrEqualTo,o=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n=u)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',p);var f=e.parse(c,h,s);if(!f)return null;s=s||f.type,a.push([u,f])}return new o(s,r,a)},o.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var o=e.length;return n>=e[o-1]?r[o-1].evaluate(t):r[i(e,n)].evaluate(t)},o.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e0&&"string"==typeof t[0]&&t[0]in y}function i(t,e,r){void 0===r&&(r={});var n=new l(y,[],function(t){var e={color:E,string:P,number:I,enum:P,boolean:D};return"array"===t.type?R(e[t.value]||O,t.length):e[t.type]||null}(e)),i=n.parse(t);return i?_(!1===r.handleErrors?new b(i):new w(i,e)):x(n.errors)}function o(t,e,r){if(void 0===r&&(r={}),"error"===(t=i(t,e,r)).result)return t;var n=t.value.expression,o=m.isFeatureConstant(n);if(!o&&!e["property-function"])return x([new s("","property expressions not supported")]);var a=m.isGlobalPropertyConstant(n,["zoom"]);if(!a&&!1===e["zoom-function"])return x([new s("","zoom expressions not supported")]);var l=function t(e){var r=null;if(e instanceof d)r=t(e.result);else if(e instanceof f)for(var n=0,i=e.args;n=0)return!1;var i=!0;return e.eachChild(function(e){i&&!t(e,r)&&(i=!1)}),i}}},{"./compound_expression":123}],141:[function(t,e,r){var n=t("./scope"),i=t("./types").checkSubtype,o=t("./parsing_error"),a=t("./definitions/literal"),s=t("./definitions/assertion"),l=t("./definitions/array"),u=t("./definitions/coercion"),c=function(t,e,r,i,o){void 0===e&&(e=[]),void 0===i&&(i=new n),void 0===o&&(o=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=i,this.errors=o,this.expectedType=r};c.prototype.parse=function(e,r,n,i,o){void 0===o&&(o={});var c=this;if(r&&(c=c.concat(r,n,i)),null!==e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e||(e=["literal",e]),Array.isArray(e)){if(0===e.length)return c.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var p=e[0];if("string"!=typeof p)return c.error("Expression name must be a string, but found "+typeof p+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var h=c.registry[p];if(h){var f=h.parse(e,c);if(!f)return null;if(c.expectedType){var d=c.expectedType,y=f.type;if("string"!==d.kind&&"number"!==d.kind&&"boolean"!==d.kind||"value"!==y.kind)if("array"===d.kind&&"value"===y.kind)o.omitTypeAnnotations||(f=new l(d,f));else if("color"!==d.kind||"value"!==y.kind&&"string"!==y.kind){if(c.checkSubtype(c.expectedType,f.type))return null}else o.omitTypeAnnotations||(f=new u(d,[f]));else o.omitTypeAnnotations||(f=new s(d,[f]))}if(!(f instanceof a)&&function(e){var r=t("./compound_expression").CompoundExpression,n=t("./is_constant"),i=n.isGlobalPropertyConstant,o=n.isFeatureConstant;if(e instanceof t("./definitions/var"))return!1;if(e instanceof r&&"error"===e.name)return!1;var s=!0;return e.eachChild(function(t){t instanceof a||(s=!1)}),!!s&&o(e)&&i(e,["zoom","heatmap-density"])}(f)){var m=new(t("./evaluation_context"));try{f=new a(f.type,f.evaluate(m))}catch(e){return c.error(e.message),null}}return f}return c.error('Unknown expression "'+p+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===e?c.error("'undefined' value invalid. Use null instead."):"object"==typeof e?c.error('Bare objects invalid. Use ["literal", {...}] instead.'):c.error("Expected an array, but found "+typeof e+" instead.")},c.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new c(this.registry,n,e||null,i,this.errors)},c.prototype.error=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];var i=""+this.key+r.map(function(t){return"["+t+"]"}).join("");this.errors.push(new o(i,t))},c.prototype.checkSubtype=function(t,e){var r=i(t,e);return r&&this.error(r),r},e.exports=c},{"./compound_expression":123,"./definitions/array":124,"./definitions/assertion":125,"./definitions/coercion":129,"./definitions/literal":134,"./definitions/var":137,"./evaluation_context":138,"./is_constant":140,"./parsing_error":142,"./scope":144,"./types":146}],142:[function(t,e,r){var n=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);e.exports=n},{}],143:[function(t,e,r){var n=function(t){this.name="ExpressionEvaluationError",this.message=t};n.prototype.toJSON=function(){return this.message},e.exports=n},{}],144:[function(t,e,r){var n=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;rr&&ee))throw new n("Input is not a number.");a=s-1}}return Math.max(s-1,0)}}},{"./runtime_error":143}],146:[function(t,e,r){function n(t,e){return{kind:"array",itemType:t,N:e}}function i(t){if("array"===t.kind){var e=i(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var o={kind:"null"},a={kind:"number"},s={kind:"string"},l={kind:"boolean"},u={kind:"color"},c={kind:"object"},p={kind:"value"},h=[o,a,s,l,u,c,n(p)];e.exports={NullType:o,NumberType:a,StringType:s,BooleanType:l,ColorType:u,ObjectType:c,ValueType:p,array:n,ErrorType:{kind:"error"},toString:i,checkSubtype:function t(e,r){if("error"===r.kind)return null;if("array"===e.kind){if("array"===r.kind&&!t(e.itemType,r.itemType)&&("number"!=typeof e.N||e.N===r.N))return null}else{if(e.kind===r.kind)return null;if("value"===e.kind)for(var n=0,o=h;n=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."},isValue:function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof n)return!0;if(Array.isArray(e)){for(var r=0,i=e;r=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);ee?1:0}function o(t){if(!t)return!0;var e=t[0];return t.length<=1?"any"!==e:"=="===e?a(t[1],t[2],"=="):"!="===e?u(a(t[1],t[2],"==")):"<"===e||">"===e||"<="===e||">="===e?a(t[1],t[2],e):"any"===e?function(t){return["any"].concat(t.map(o))}(t.slice(1)):"all"===e?["all"].concat(t.slice(1).map(o)):"none"===e?["all"].concat(t.slice(1).map(o).map(u)):"in"===e?s(t[1],t.slice(2)):"!in"===e?u(s(t[1],t.slice(2))):"has"===e?l(t[1]):"!has"!==e||u(l(t[1]))}function a(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function s(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(i)]]:["filter-in-small",t,["literal",e]]}}function l(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function u(t){return["!",t]}var c=t("../expression").createExpression;e.exports=function(t){if(!t)return function(){return!0};n(t)||(t=o(t));var e=c(t,p);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}},e.exports.isExpressionFilter=n;var p={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0}},{"../expression":139}],149:[function(t,e,r){function n(t){return t}function i(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function o(t,e,r,n,o){return i(typeof r===o?n[r]:void 0,t.default,e.default)}function a(t,e,r){if("number"!==f(r))return i(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var o=u(t.stops,r);return t.stops[o][1]}function s(t,e,r){var o=void 0!==t.base?t.base:1;if("number"!==f(r))return i(t.default,e.default);var a=t.stops.length;if(1===a)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[a-1][0])return t.stops[a-1][1];var s=u(t.stops,r),l=function(t,e,r,n){var i=n-r,o=t-r;return 0===i?0:1===e?o/i:(Math.pow(e,o)-1)/(Math.pow(e,i)-1)}(r,o,t.stops[s][0],t.stops[s+1][0]),p=t.stops[s][1],h=t.stops[s+1][1],y=d[e.type]||n;if(t.colorSpace&&"rgb"!==t.colorSpace){var m=c[t.colorSpace];y=function(t,e){return m.reverse(m.interpolate(m.forward(t),m.forward(e),l))}}return"function"==typeof p.evaluate?{evaluate:function(){for(var t=arguments,e=[],r=arguments.length;r--;)e[r]=t[r];var n=p.evaluate.apply(void 0,e),i=h.evaluate.apply(void 0,e);if(void 0!==n&&void 0!==i)return y(n,i,l)}}:y(p,h,l)}function l(t,e,r){return"color"===e.type?r=p.parse(r):f(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),i(r,t.default,e.default)}function u(t,e){for(var r,n,i=0,o=t.length-1,a=0;i<=o;){if(r=t[a=Math.floor((i+o)/2)][0],n=t[a+1][0],e===r||e>r&&ee&&(o=a-1)}return Math.max(a-1,0)}var c=t("../util/color_spaces"),p=t("../util/color"),h=t("../util/extend"),f=t("../util/get_type"),d=t("../util/interpolate"),y=t("../expression/definitions/interpolate");e.exports={createFunction:function t(e,r){var n,u,f,d="color"===r.type,m=e.stops&&"object"==typeof e.stops[0][0],g=m||void 0!==e.property,v=m||!g,_=e.type||("interpolated"===r.function?"exponential":"interval");if(d&&((e=h({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],p.parse(t[1])]})),e.default?e.default=p.parse(e.default):e.default=p.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!c[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===_)n=s;else if("interval"===_)n=a;else if("categorical"===_){n=o,u=Object.create(null);for(var x=0,b=e.stops;x":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}}}},{}],153:[function(t,e,r){var n=t("csscolorparser").parseCSSColor,i=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n};i.parse=function(t){if(t){if(t instanceof i)return t;if("string"==typeof t){var e=n(t);if(e)return new i(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},i.prototype.toString=function(){var t=this;return"rgba("+[this.r,this.g,this.b].map(function(e){return Math.round(255*e/t.a)}).concat(this.a).join(",")+")"},i.black=new i(0,0,0,1),i.white=new i(1,1,1,1),i.transparent=new i(0,0,0,0),e.exports=i},{csscolorparser:13}],154:[function(t,e,r){function n(t){return t>g?Math.pow(t,1/3):t/m+d}function i(t){return t>y?t*t*t:m*(t-d)}function o(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function a(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function s(t){var e=a(t.r),r=a(t.g),i=a(t.b),o=n((.4124564*e+.3575761*r+.1804375*i)/p),s=n((.2126729*e+.7151522*r+.072175*i)/h);return{l:116*s-16,a:500*(o-s),b:200*(s-n((.0193339*e+.119192*r+.9503041*i)/f)),alpha:t.a}}function l(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=h*i(e),r=p*i(r),n=f*i(n),new u(o(3.2404542*r-1.5371385*e-.4985314*n),o(-.969266*r+1.8760108*e+.041556*n),o(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var u=t("./color"),c=t("./interpolate").number,p=.95047,h=1,f=1.08883,d=4/29,y=6/29,m=3*y*y,g=y*y*y,v=Math.PI/180,_=180/Math.PI;e.exports={lab:{forward:s,reverse:l,interpolate:function(t,e,r){return{l:c(t.l,e.l,r),a:c(t.a,e.a,r),b:c(t.b,e.b,r),alpha:c(t.alpha,e.alpha,r)}}},hcl:{forward:function(t){var e=s(t),r=e.l,n=e.a,i=e.b,o=Math.atan2(i,n)*_;return{h:o<0?o+360:o,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*v,r=t.c;return l({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:c(t.c,e.c,r),l:c(t.l,e.l,r),alpha:c(t.alpha,e.alpha,r)}}}}},{"./color":153,"./interpolate":158}],155:[function(t,e,r){e.exports=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n0;)r[n]=e[n+1];for(var i=0,o=r;i":case">=":r.length>=2&&"$type"===s(r[1])&&c.push(new n(i,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&c.push(new n(i,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(l=a(r[1]))&&c.push(new n(i+"[1]",r[1],"string expected, "+l+" found"));for(var p=2;pu(s[0].zoom))return[new n(c,s[0].zoom,"stop zoom values must appear in ascending order")];u(s[0].zoom)!==h&&(h=u(s[0].zoom),p=void 0,y={}),e=e.concat(a({key:c+"[0]",value:s[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:l,value:r}}))}else e=e.concat(r({key:c+"[0]",value:s[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},s));return e.concat(o({key:c+"[1]",value:s[1],valueSpec:f,style:t.style,styleSpec:t.styleSpec}))}function r(t,e){var r=i(t.value),o=u(t.value),a=null!==t.value?t.value:e;if(c){if(r!==c)return[new n(t.key,a,r+" stop domain type must match previous stop domain type "+c)]}else c=r;if("number"!==r&&"string"!==r&&"boolean"!==r)return[new n(t.key,a,"stop domain value must be a number, string, or boolean")];if("number"!==r&&"categorical"!==d){var s="number expected, "+r+" found";return f["property-function"]&&void 0===d&&(s+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new n(t.key,a,s)]}return"categorical"!==d||"number"!==r||isFinite(o)&&Math.floor(o)===o?"categorical"!==d&&"number"===r&&void 0!==p&&o=8&&(g&&!t.valueSpec["property-function"]?_.push(new n(t.key,t.value,"property functions not supported")):m&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&_.push(new n(t.key,t.value,"zoom functions not supported"))),"categorical"!==d&&!v||void 0!==t.value.property||_.push(new n(t.key,t.value,'"property" property is required')),_}},{"../error/validation_error":122,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162,"./validate_array":163,"./validate_number":175,"./validate_object":176}],171:[function(t,e,r){var n=t("../error/validation_error"),i=t("./validate_string");e.exports=function(t){var e=t.value,r=t.key,o=i(t);return o.length?o:(-1===e.indexOf("{fontstack}")&&o.push(new n(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&o.push(new n(r,e,'"glyphs" url must include a "{range}" token')),o)}},{"../error/validation_error":122,"./validate_string":180}],172:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),o=t("./validate_object"),a=t("./validate_filter"),s=t("./validate_paint_property"),l=t("./validate_layout_property"),u=t("./validate"),c=t("../util/extend");e.exports=function(t){var e=[],r=t.value,p=t.key,h=t.style,f=t.styleSpec;r.type||r.ref||e.push(new n(p,r,'either "type" or "ref" is required'));var d,y=i(r.type),m=i(r.ref);if(r.id)for(var g=i(r.id),v=0;vo.maximum?[new i(e,r,r+" is greater than the maximum value "+o.maximum)]:[]}},{"../error/validation_error":122,"../util/get_type":157}],176:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/get_type"),o=t("./validate");e.exports=function(t){var e=t.key,r=t.value,a=t.valueSpec||{},s=t.objectElementValidators||{},l=t.style,u=t.styleSpec,c=[],p=i(r);if("object"!==p)return[new n(e,r,"object expected, "+p+" found")];for(var h in r){var f=h.split(".")[0],d=a[f]||a["*"],y=void 0;if(s[f])y=s[f];else if(a[f])y=o;else if(s["*"])y=s["*"];else{if(!a["*"]){c.push(new n(e,r[h],'unknown property "'+h+'"'));continue}y=o}c=c.concat(y({key:(e?e+".":e)+h,value:r[h],valueSpec:d,style:l,styleSpec:u,object:r,objectKey:h},r))}for(var m in a)s[m]||a[m].required&&void 0===a[m].default&&void 0===r[m]&&c.push(new n(e,r,'missing required property "'+m+'"'));return c}},{"../error/validation_error":122,"../util/get_type":157,"./validate":162}],177:[function(t,e,r){var n=t("./validate_property");e.exports=function(t){return n(t,"paint")}},{"./validate_property":178}],178:[function(t,e,r){var n=t("./validate"),i=t("../error/validation_error"),o=t("../util/get_type"),a=t("../function").isFunction,s=t("../util/unbundle_jsonlint");e.exports=function(t,e){var r=t.key,l=t.style,u=t.styleSpec,c=t.value,p=t.objectKey,h=u[e+"_"+t.layerType];if(!h)return[];var f=p.match(/^(.*)-transition$/);if("paint"===e&&f&&h[f[1]]&&h[f[1]].transition)return n({key:r,value:c,valueSpec:u.transition,style:l,styleSpec:u});var d,y=t.valueSpec||h[p];if(!y)return[new i(r,c,'unknown property "'+p+'"')];if("string"===o(c)&&y["property-function"]&&!y.tokens&&(d=/^{([^}]+)}$/.exec(c)))return[new i(r,c,'"'+p+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(d[1])+" }`.")];var m=[];return"symbol"===t.layerType&&("text-field"===p&&l&&!l.glyphs&&m.push(new i(r,c,'use of "text-field" requires a style "glyphs" property')),"text-font"===p&&a(s.deep(c))&&"identity"===s(c.type)&&m.push(new i(r,c,'"text-font" does not support identity functions'))),m.concat(n({key:t.key,value:c,valueSpec:y,style:l,styleSpec:u,expressionContext:"property",propertyKey:p}))}},{"../error/validation_error":122,"../function":149,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162}],179:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),o=t("./validate_object"),a=t("./validate_enum");e.exports=function(t){var e=t.value,r=t.key,s=t.styleSpec,l=t.style;if(!e.type)return[new n(r,e,'"type" is required')];var u=i(e.type),c=[];switch(u){case"vector":case"raster":case"raster-dem":if(c=c.concat(o({key:r,value:e,valueSpec:s["source_"+u.replace("-","_")],style:t.style,styleSpec:s})),"url"in e)for(var p in e)["type","url","tileSize"].indexOf(p)<0&&c.push(new n(r+"."+p,e[p],'a source with a "url" property may not include a "'+p+'" property'));return c;case"geojson":return o({key:r,value:e,valueSpec:s.source_geojson,style:l,styleSpec:s});case"video":return o({key:r,value:e,valueSpec:s.source_video,style:l,styleSpec:s});case"image":return o({key:r,value:e,valueSpec:s.source_image,style:l,styleSpec:s});case"canvas":return o({key:r,value:e,valueSpec:s.source_canvas,style:l,styleSpec:s});default:return a({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image","canvas"]},style:l,styleSpec:s})}}},{"../error/validation_error":122,"../util/unbundle_jsonlint":161,"./validate_enum":167,"./validate_object":176}],180:[function(t,e,r){var n=t("../util/get_type"),i=t("../error/validation_error");e.exports=function(t){var e=t.value,r=t.key,o=n(e);return"string"!==o?[new i(r,e,"string expected, "+o+" found")]:[]}},{"../error/validation_error":122,"../util/get_type":157}],181:[function(t,e,r){function n(t,e){e=e||l;var r=[];return r=r.concat(s({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:u,"*":function(){return[]}}})),t.constants&&(r=r.concat(a({key:"constants",value:t.constants,style:t,styleSpec:e}))),i(r)}function i(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function o(t){return function(){return i(t.apply(this,arguments))}}var a=t("./validate/validate_constants"),s=t("./validate/validate"),l=t("./reference/latest"),u=t("./validate/validate_glyphs_url");n.source=o(t("./validate/validate_source")),n.light=o(t("./validate/validate_light")),n.layer=o(t("./validate/validate_layer")),n.filter=o(t("./validate/validate_filter")),n.paintProperty=o(t("./validate/validate_paint_property")),n.layoutProperty=o(t("./validate/validate_layout_property")),e.exports=n},{"./reference/latest":151,"./validate/validate":162,"./validate/validate_constants":166,"./validate/validate_filter":169,"./validate/validate_glyphs_url":171,"./validate/validate_layer":172,"./validate/validate_layout_property":173,"./validate/validate_light":174,"./validate/validate_paint_property":177,"./validate/validate_source":179}],182:[function(t,e,r){var n=t("./zoom_history"),i=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new n,this.transition={})};i.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},e.exports=i},{"./zoom_history":212}],183:[function(t,e,r){var n=t("../style-spec/reference/latest"),i=t("../util/util"),o=t("../util/evented"),a=t("./validate_style"),s=t("../util/util").sphericalToCartesian,l=(t("../style-spec/util/color"),t("../style-spec/util/interpolate")),u=t("./properties"),c=u.Properties,p=u.Transitionable,h=(u.Transitioning,u.PossiblyEvaluated,u.DataConstantProperty),f=function(){this.specification=n.light.position};f.prototype.possiblyEvaluate=function(t,e){return s(t.expression.evaluate(e))},f.prototype.interpolate=function(t,e,r){return{x:l.number(t.x,e.x,r),y:l.number(t.y,e.y,r),z:l.number(t.z,e.z,r)}};var d=new c({anchor:new h(n.light.anchor),position:new f,color:new h(n.light.color),intensity:new h(n.light.intensity)}),y=function(t){function e(e){t.call(this),this._transitionable=new p(d),this.setLight(e),this._transitioning=this._transitionable.untransitioned()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLight=function(){return this._transitionable.serialize()},e.prototype.setLight=function(t){if(!this._validate(a.light,t))for(var e in t){var r=t[e];i.endsWith(e,"-transition")?this._transitionable.setTransition(e.slice(0,-"-transition".length),r):this._transitionable.setValue(e,r)}},e.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning)},e.prototype.hasTransition=function(){return this._transitioning.hasTransition()},e.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t)},e.prototype._validate=function(t,e){return a.emitErrors(this,t.call(a,i.extend({value:e,style:{glyphs:!0,sprite:!0},styleSpec:n})))},e}(o);e.exports=y},{"../style-spec/reference/latest":151,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/evented":260,"../util/util":275,"./properties":188,"./validate_style":211}],184:[function(t,e,r){var n=t("../util/mapbox").normalizeGlyphsURL,i=t("../util/ajax"),o=t("./parse_glyph_pbf");e.exports=function(t,e,r,a,s){var l=256*e,u=l+255,c=a(n(r).replace("{fontstack}",t).replace("{range}",l+"-"+u),i.ResourceType.Glyphs);i.getArrayBuffer(c,function(t,e){if(t)s(t);else if(e){for(var r={},n=0,i=o(e.data);n1?"@2x":"";n.getJSON(e(o(t,p,".json"),n.ResourceType.SpriteJSON),function(t,e){c||(c=t,l=e,s())}),n.getImage(e(o(t,p,".png"),n.ResourceType.SpriteImage),function(t,e){c||(c=t,u=e,s())})}},{"../util/ajax":251,"../util/browser":252,"../util/image":263,"../util/mapbox":267}],186:[function(t,e,r){function n(t,e,r){1===t&&r.readMessage(i,e)}function i(t,e,r){if(3===t){var n=r.readMessage(o,{}),i=n.id,s=n.bitmap,u=n.width,c=n.height,p=n.left,h=n.top,f=n.advance;e.push({id:i,bitmap:new a({width:u+2*l,height:c+2*l},s),metrics:{width:u,height:c,left:p,top:h,advance:f}})}}function o(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint())}var a=t("../util/image").AlphaImage,s=t("pbf"),l=3;e.exports=function(t){return new s(t).readFields(n,[])},e.exports.GLYPH_PBF_BORDER=l},{"../util/image":263,pbf:30}],187:[function(t,e,r){var n=t("../util/browser"),i=t("../symbol/placement"),o=function(){this._currentTileIndex=0,this._seenCrossTileIDs={}};o.prototype.continuePlacement=function(t,e,r,n,i){for(var o=this;this._currentTileIndex2};this._currentPlacementIndex>=0;){var l=e[t[i._currentPlacementIndex]],u=i.placement.collisionIndex.transform.zoom;if("symbol"===l.type&&(!l.minzoom||l.minzoom<=u)&&(!l.maxzoom||l.maxzoom>u)){if(i._inProgressLayer||(i._inProgressLayer=new o),i._inProgressLayer.continuePlacement(r[l.source],i.placement,i._showCollisionBoxes,l,s))return;delete i._inProgressLayer}i._currentPlacementIndex--}this._done=!0},a.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement},e.exports=a},{"../symbol/placement":223,"../util/browser":252}],188:[function(t,e,r){var n=t("../util/util"),i=n.clone,o=n.extend,a=n.easeCubicInOut,s=t("../style-spec/util/interpolate"),l=t("../style-spec/expression").normalizePropertyExpression,u=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),c=function(t,e){this.property=t,this.value=e,this.expression=l(void 0===e?t.specification.default:e,t.specification)};c.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},c.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var p=function(t){this.property=t,this.value=new c(t,void 0)};p.prototype.transitioned=function(t,e){return new f(this.property,this.value,e,o({},t.transition,this.transition),t.now)},p.prototype.untransitioned=function(){return new f(this.property,this.value,null,{},0)};var h=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)};h.prototype.getValue=function(t){return i(this._values[t].value.value)},h.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new p(this._values[t].property)),this._values[t].value=new c(this._values[t].property,null===e?void 0:i(e))},h.prototype.getTransition=function(t){return i(this._values[t].transition)},h.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new p(this._values[t].property)),this._values[t].transition=i(e)||void 0},h.prototype.serialize=function(){for(var t=this,e={},r=0,n=Object.keys(t._values);rthis.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(en.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:o+(1-o)*a}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-a)*o}},x.prototype.interpolate=function(t){return t};var b=function(t){this.specification=t};b.prototype.possiblyEvaluate=function(){},b.prototype.interpolate=function(){};u("DataDrivenProperty",_),u("DataConstantProperty",v),u("CrossFadedProperty",x),u("HeatmapColorProperty",b),e.exports={PropertyValue:c,Transitionable:h,Transitioning:d,Layout:y,PossiblyEvaluatedPropertyValue:m,PossiblyEvaluated:g,DataConstantProperty:v,DataDrivenProperty:_,CrossFadedProperty:x,HeatmapColorProperty:b,Properties:function(t){var e=this;for(var r in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var n=t[r],i=e.defaultPropertyValues[r]=new c(n,void 0),o=e.defaultTransitionablePropertyValues[r]=new p(n);e.defaultTransitioningPropertyValues[r]=o.untransitioned(),e.defaultPossiblyEvaluatedValues[r]=i.possiblyEvaluate({})}}}},{"../style-spec/expression":139,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/util":275,"../util/web_worker_transfer":278}],189:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports={getMaximumPaintValue:function(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max},translateDistance:function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},translate:function(t,e,r,i,o){if(!e[0]&&!e[1])return t;var a=n.convert(e);"viewport"===r&&a._rotate(-i);for(var s=[],l=0;l0)throw new Error("Unimplemented: "+n.map(function(t){return t.command}).join(", ")+".");return r.forEach(function(t){"setTransition"!==t.command&&e[t.command].apply(e,t.args)}),this.stylesheet=t,!0},e.prototype.addImage=function(t,e){if(this.getImage(t))return this.fire("error",{error:new Error("An image with this name already exists.")});this.imageManager.addImage(t,e),this.fire("data",{dataType:"style"})},e.prototype.getImage=function(t){return this.imageManager.getImage(t)},e.prototype.removeImage=function(t){if(!this.getImage(t))return this.fire("error",{error:new Error("No image with this name exists.")});this.imageManager.removeImage(t),this.fire("data",{dataType:"style"})},e.prototype.addSource=function(t,e,r){var n=this;if(this._checkLoaded(),void 0!==this.sourceCaches[t])throw new Error("There is already a source with this ID");if(!e.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(e).join(", ")+".");if(!(["vector","raster","geojson","video","image","canvas"].indexOf(e.type)>=0&&this._validate(y.source,"sources."+t,e,null,r))){this.map&&this.map._collectResourceTiming&&(e.collectResourceTiming=!0);var i=this.sourceCaches[t]=new _(t,e,this.dispatcher);i.style=this,i.setEventedParent(this,function(){return{isSourceLoaded:n.loaded(),source:i.serialize(),sourceId:t}}),i.onAdd(this.map),this._changed=!0}},e.prototype.removeSource=function(t){var e=this;if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error("There is no source with this ID");for(var r in e._layers)if(e._layers[r].source===t)return e.fire("error",{error:new Error('Source "'+t+'" cannot be removed while layer "'+r+'" is using it.')});var n=this.sourceCaches[t];delete this.sourceCaches[t],delete this._updatedSources[t],n.fire("data",{sourceDataType:"metadata",dataType:"source",sourceId:t}),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0},e.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0},e.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},e.prototype.addLayer=function(t,e,r){this._checkLoaded();var n=t.id;if("object"==typeof t.source&&(this.addSource(n,t.source),t=c.clone(t),t=c.extend(t,{source:n})),!this._validate(y.layer,"layers."+n,t,{arrayIndex:-1},r)){var o=i.create(t);this._validateLayer(o),o.setEventedParent(this,{layer:{id:n}});var a=e?this._order.indexOf(e):this._order.length;if(e&&-1===a)return void this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')});if(this._order.splice(a,0,n),this._layerOrderChanged=!0,this._layers[n]=o,this._removedLayers[n]&&o.source){var s=this._removedLayers[n];delete this._removedLayers[n],s.type!==o.type?this._updatedSources[o.source]="clear":(this._updatedSources[o.source]="reload",this.sourceCaches[o.source].pause())}this._updateLayer(o)}},e.prototype.moveLayer=function(t,e){if(this._checkLoaded(),this._changed=!0,this._layers[t]){var r=this._order.indexOf(t);this._order.splice(r,1);var n=e?this._order.indexOf(e):this._order.length;e&&-1===n?this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')}):(this._order.splice(n,0,t),this._layerOrderChanged=!0)}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be moved.")})},e.prototype.removeLayer=function(t){this._checkLoaded();var e=this._layers[t];if(e){e.setEventedParent(null);var r=this._order.indexOf(t);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[t]=e,delete this._layers[t],delete this._updatedLayers[t],delete this._updatedPaintProps[t]}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be removed.")})},e.prototype.getLayer=function(t){return this._layers[t]},e.prototype.setLayerZoomRange=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?n.minzoom===e&&n.maxzoom===r||(null!=e&&(n.minzoom=e),null!=r&&(n.maxzoom=r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot have zoom extent.")})},e.prototype.setFilter=function(t,e){this._checkLoaded();var r=this.getLayer(t);if(r)return c.deepEqual(r.filter,e)?void 0:null===e||void 0===e?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(y.filter,"layers."+r.id+".filter",e)||(r.filter=c.clone(e),this._updateLayer(r)));this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be filtered.")})},e.prototype.getFilter=function(t){return c.clone(this.getLayer(t).filter)},e.prototype.setLayoutProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?c.deepEqual(n.getLayoutProperty(e),r)||(n.setLayoutProperty(e,r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},e.prototype.setPaintProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);if(n){if(!c.deepEqual(n.getPaintProperty(e),r)){var i=n._transitionablePaint._values[e].value.isDataDriven();n.setPaintProperty(e,r),(n._transitionablePaint._values[e].value.isDataDriven()||i)&&this._updateLayer(n),this._changed=!0,this._updatedPaintProps[t]=!0}}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},e.prototype.getTransition=function(){return c.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},e.prototype.serialize=function(){var t=this;return c.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:c.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(e){return t._layers[e].serialize()})},function(t){return void 0!==t})},e.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0},e.prototype._flattenRenderedFeatures=function(t){for(var e=[],r=this._order.length-1;r>=0;r--)for(var n=this._order[r],i=0,o=t;i=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t)},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),n.filterObject(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,a){return(!a||!1!==a.validate)&&o.emitErrors(this,t.call(o,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:i,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(a));e.exports=c;var p={circle:t("./style_layer/circle_style_layer"),heatmap:t("./style_layer/heatmap_style_layer"),hillshade:t("./style_layer/hillshade_style_layer"),fill:t("./style_layer/fill_style_layer"),"fill-extrusion":t("./style_layer/fill_extrusion_style_layer"),line:t("./style_layer/line_style_layer"),symbol:t("./style_layer/symbol_style_layer"),background:t("./style_layer/background_style_layer"),raster:t("./style_layer/raster_style_layer")};c.create=function(t){return new p[t.type](t)}},{"../style-spec/reference/latest":151,"../util/evented":260,"../util/util":275,"./properties":188,"./style_layer/background_style_layer":192,"./style_layer/circle_style_layer":194,"./style_layer/fill_extrusion_style_layer":196,"./style_layer/fill_style_layer":198,"./style_layer/heatmap_style_layer":200,"./style_layer/hillshade_style_layer":202,"./style_layer/line_style_layer":204,"./style_layer/raster_style_layer":206,"./style_layer/symbol_style_layer":208,"./validate_style":211}],192:[function(t,e,r){var n=t("../style_layer"),i=t("./background_style_layer_properties"),o=t("../properties"),a=(o.Transitionable,o.Transitioning,o.PossiblyEvaluated,function(t){function e(e){t.call(this,e,i)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(n));e.exports=a},{"../properties":188,"../style_layer":191,"./background_style_layer_properties":193}],193:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),o=i.Properties,a=i.DataConstantProperty,s=(i.DataDrivenProperty,i.CrossFadedProperty),l=(i.HeatmapColorProperty,new o({"background-color":new a(n.paint_background["background-color"]),"background-pattern":new s(n.paint_background["background-pattern"]),"background-opacity":new a(n.paint_background["background-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],194:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/circle_bucket"),o=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiPoint,a=t("../query_utils"),s=a.getMaximumPaintValue,l=a.translateDistance,u=a.translate,c=t("./circle_style_layer_properties"),p=t("../properties"),h=(p.Transitionable,p.Transitioning,p.PossiblyEvaluated,function(t){function e(e){t.call(this,e,c)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(t){var e=t;return s("circle-radius",this,e)+s("circle-stroke-width",this,e)+l(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a){var s=u(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i,a),l=this.paint.get("circle-radius").evaluate(e)*a,c=this.paint.get("circle-stroke-width").evaluate(e)*a;return o(s,r,l+c)},e}(n));e.exports=h},{"../../data/bucket/circle_bucket":42,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./circle_style_layer_properties":195}],195:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),o=i.Properties,a=i.DataConstantProperty,s=i.DataDrivenProperty,l=(i.CrossFadedProperty,i.HeatmapColorProperty,new o({"circle-radius":new s(n.paint_circle["circle-radius"]),"circle-color":new s(n.paint_circle["circle-color"]),"circle-blur":new s(n.paint_circle["circle-blur"]),"circle-opacity":new s(n.paint_circle["circle-opacity"]),"circle-translate":new a(n.paint_circle["circle-translate"]),"circle-translate-anchor":new a(n.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new a(n.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new a(n.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new s(n.paint_circle["circle-stroke-width"]),"circle-stroke-color":new s(n.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new s(n.paint_circle["circle-stroke-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],196:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_extrusion_bucket"),o=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,a=t("../query_utils"),s=a.translateDistance,l=a.translate,u=t("./fill_extrusion_style_layer_properties"),c=t("../properties"),p=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a){var s=l(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i,a);return o(s,r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null)},e}(n));e.exports=p},{"../../data/bucket/fill_extrusion_bucket":46,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_extrusion_style_layer_properties":197}],197:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),o=i.Properties,a=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new o({"fill-extrusion-opacity":new a(n["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new s(n["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new a(n["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new a(n["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new l(n["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new s(n["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new s(n["paint_fill-extrusion"]["fill-extrusion-base"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],198:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_bucket"),o=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,a=t("../query_utils"),s=a.translateDistance,l=a.translate,u=t("./fill_style_layer_properties"),c=t("../properties"),p=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t),void 0===this._transitionablePaint.getValue("fill-outline-color")&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])},e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a){var s=l(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i,a);return o(s,r)},e}(n));e.exports=p},{"../../data/bucket/fill_bucket":44,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_style_layer_properties":199}],199:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),o=i.Properties,a=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new o({"fill-antialias":new a(n.paint_fill["fill-antialias"]),"fill-opacity":new s(n.paint_fill["fill-opacity"]),"fill-color":new s(n.paint_fill["fill-color"]),"fill-outline-color":new s(n.paint_fill["fill-outline-color"]),"fill-translate":new a(n.paint_fill["fill-translate"]),"fill-translate-anchor":new a(n.paint_fill["fill-translate-anchor"]),"fill-pattern":new l(n.paint_fill["fill-pattern"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],200:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/heatmap_bucket"),o=t("../../util/image").RGBAImage,a=t("./heatmap_style_layer_properties"),s=t("../properties"),l=(s.Transitionable,s.Transitioning,s.PossiblyEvaluated,function(t){function e(e){t.call(this,e,a),this._updateColorRamp()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp()},e.prototype._updateColorRamp=function(){for(var t=this._transitionablePaint._values["heatmap-color"].value.expression,e=new Uint8Array(1024),r=e.length,n=4;n0?e+2*t:t}var i=t("@mapbox/point-geometry"),o=t("../style_layer"),a=t("../../data/bucket/line_bucket"),s=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiLine,l=t("../query_utils"),u=l.getMaximumPaintValue,c=l.translateDistance,p=l.translate,h=t("./line_style_layer_properties"),f=t("../../util/util").extend,d=t("../evaluation_parameters"),y=t("../properties"),m=(y.Transitionable,y.Transitioning,y.Layout,y.PossiblyEvaluated,new(function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new d(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=f({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(y.DataDrivenProperty))(h.paint.properties["line-width"].specification));m.useIntegerZoom=!0;var g=function(t){function e(e){t.call(this,e,h)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=m.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)},e.prototype.createBucket=function(t){return new a(t)},e.prototype.queryRadius=function(t){var e=t,r=n(u("line-width",this,e),u("line-gap-width",this,e)),i=u("line-offset",this,e);return r/2+Math.abs(i)+c(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,o,a,l){var u=p(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),a,l),c=l/2*n(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),h=this.paint.get("line-offset").evaluate(e);return h&&(r=function(t,e){for(var r=[],n=new i(0,0),o=0;or?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom-r/2;){if(--a<0)return!1;s-=t[a].dist(o),o=t[a]}s+=t[a].dist(t[a+1]),a++;for(var l=[],u=0;sn;)u-=l.shift().angleDelta;if(u>i)return!1;a++,s+=p.dist(h)}return!0}},{}],215:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports=function(t,e,r,i,o){for(var a=[],s=0;s=i&&h.x>=i||(p.x>=i?p=new n(i,p.y+(h.y-p.y)*((i-p.x)/(h.x-p.x)))._round():h.x>=i&&(h=new n(i,p.y+(h.y-p.y)*((i-p.x)/(h.x-p.x)))._round()),p.y>=o&&h.y>=o||(p.y>=o?p=new n(p.x+(h.x-p.x)*((o-p.y)/(h.y-p.y)),o)._round():h.y>=o&&(h=new n(p.x+(h.x-p.x)*((o-p.y)/(h.y-p.y)),o)._round()),u&&p.equals(u[u.length-1])||(u=[p],a.push(u)),u.push(h)))))}return a}},{"@mapbox/point-geometry":4}],216:[function(t,e,r){var n=function(t,e,r,n,i,o,a,s,l,u,c){var p=a.top*s-l,h=a.bottom*s+l,f=a.left*s-l,d=a.right*s+l;if(this.boxStartIndex=t.length,u){var y=h-p,m=d-f;y>0&&(y=Math.max(10*s,y),this._addLineCollisionCircles(t,e,r,r.segment,m,y,n,i,o,c))}else t.emplaceBack(r.x,r.y,f,p,d,h,n,i,o,0,0);this.boxEndIndex=t.length};n.prototype._addLineCollisionCircles=function(t,e,r,n,i,o,a,s,l,u){var c=o/2,p=Math.floor(i/c),h=1+.4*Math.log(u)/Math.LN2,f=Math.floor(p*h/2),d=-o/2,y=r,m=n+1,g=d,v=-i/2,_=v-i/4;do{if(--m<0){if(g>v)return;m=0;break}g-=e[m].dist(y),y=e[m]}while(g>_);for(var x=e[m].dist(e[m+1]),b=-f;bi&&(k+=w-i),!(k=e.length)return;x=e[m].dist(e[m+1])}var A=k-g,T=e[m],M=e[m+1].sub(T)._unit()._mult(A)._add(T)._round(),S=Math.abs(k-d)L)n(t,E,!1);else{var R=m.projectPoint(h,P,I),B=D*S;if(g.length>0){var F=R.x-g[g.length-4],N=R.y-g[g.length-3];if(B*B*2>F*F+N*N&&E+8-z&&j=this.screenRightBoundary||n<100||e>this.screenBottomBoundary},e.exports=l},{"../symbol/projection":224,"../util/intersection_tests":264,"./grid_index":220,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],218:[function(t,e,r){var n=t("../data/extent"),i=512/n/2,o=function(t,e,r){var n=this;this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=r;for(var i=0,o=e;it.overscaledZ)for(var u in l){var c=l[u];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,a)}else{var p=l[t.scaledTo(Number(s)).key];p&&p.findMatches(e.symbolInstances,t,a)}}for(var h=0,f=e.symbolInstances;h=0&&T=0&&M=0&&g+f<=d){var S=new i(T,M,k,_);S._round(),s&&!o(e,S,u,s,l)||v.push(S)}}m+=w}return p||v.length||c||(v=t(e,m/2,a,s,l,u,c,!0,h)),v}(t,d?e/2*c%e:(f/2+2*l)*u*c%e,e,h,r,f*u,d,!1,p)}},{"../style-spec/util/interpolate":158,"../symbol/anchor":213,"./check_max_angle":214}],220:[function(t,e,r){var n=function(t,e,r){var n=this.boxCells=[],i=this.circleCells=[];this.xCellCount=Math.ceil(t/r),this.yCellCount=Math.ceil(e/r);for(var o=0;othis.width||n<0||e>this.height)return!i&&[];var o=[];if(t<=0&&e<=0&&this.width<=r&&this.height<=n)o=Array.prototype.slice.call(this.boxKeys).concat(this.circleKeys);else{var a={hitTest:i,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,r,n,this._queryCell,o,a)}return i?o.length>0:o},n.prototype._queryCircle=function(t,e,r,n){var i=t-r,o=t+r,a=e-r,s=e+r;if(o<0||i>this.width||s<0||a>this.height)return!n&&[];var l=[],u={hitTest:n,circle:{x:t,y:e,radius:r},seenUids:{box:{},circle:{}}};return this._forEachCell(i,a,o,s,this._queryCellCircle,l,u),n?l.length>0:l},n.prototype.query=function(t,e,r,n){return this._query(t,e,r,n,!1)},n.prototype.hitTest=function(t,e,r,n){return this._query(t,e,r,n,!0)},n.prototype.hitTestCircle=function(t,e,r){return this._queryCircle(t,e,r,!0)},n.prototype._queryCell=function(t,e,r,n,i,o,a){var s=this,l=a.seenUids,u=this.boxCells[i];if(null!==u)for(var c=this.bboxes,p=0,h=u;p=c[d+0]&&n>=c[d+1]){if(a.hitTest)return o.push(!0),!0;o.push(s.boxKeys[f])}}}var y=this.circleCells[i];if(null!==y)for(var m=this.circles,g=0,v=y;ga*a+s*s},n.prototype._circleAndRectCollide=function(t,e,r,n,i,o,a){var s=(o-n)/2,l=Math.abs(t-(n+s));if(l>s+r)return!1;var u=(a-i)/2,c=Math.abs(e-(i+u));if(c>u+r)return!1;if(l<=s||c<=u)return!0;var p=l-s,h=c-u;return p*p+h*h<=r*r},e.exports=n},{}],221:[function(t,e,r){e.exports=function(t){function e(e){s.push(t[e]),l++}function r(t,e,r){var n=a[t];return delete a[t],a[e]=n,s[n].geometry[0].pop(),s[n].geometry[0]=s[n].geometry[0].concat(r[0]),n}function n(t,e,r){var n=o[e];return delete o[e],o[t]=n,s[n].geometry[0].shift(),s[n].geometry[0]=r[0].concat(s[n].geometry[0]),n}function i(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var o={},a={},s=[],l=0,u=0;u0,A=A&&T.offscreen);var C=b.collisionArrays.textCircles;if(C){var z=t.text.placedSymbolArray.get(b.placedTextSymbolIndices[0]),L=s.evaluateSizeForFeature(t.textSizeData,m,z);M=d.collisionIndex.placeCollisionCircles(C,y.get("text-allow-overlap"),i,o,b.key,z,t.lineVertexArray,t.glyphOffsetArray,L,e,r,a,"map"===y.get("text-pitch-alignment")),w=y.get("text-allow-overlap")||M.circles.length>0,A=A&&M.offscreen}b.collisionArrays.iconBox&&(k=(S=d.collisionIndex.placeCollisionBox(b.collisionArrays.iconBox,y.get("icon-allow-overlap"),o,e)).box.length>0,A=A&&S.offscreen),g||v?v?g||(k=k&&w):w=k&&w:k=w=k&&w,w&&T&&d.collisionIndex.insertCollisionBox(T.box,y.get("text-ignore-placement"),p,h,t.bucketInstanceId,b.textBoxStartIndex),k&&S&&d.collisionIndex.insertCollisionBox(S.box,y.get("icon-ignore-placement"),p,h,t.bucketInstanceId,b.iconBoxStartIndex),w&&M&&d.collisionIndex.insertCollisionCircles(M.circles,y.get("text-ignore-placement"),p,h,t.bucketInstanceId,b.textBoxStartIndex),d.placements[b.crossTileID]=new f(w,k,A||t.justReloaded),l[b.crossTileID]=!0}}t.justReloaded=!1},d.prototype.commit=function(t,e){var r=this;this.commitTime=e;var n=!1,i=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,o=t?t.opacities:{};for(var a in r.placements){var s=r.placements[a],l=o[a];l?(r.opacities[a]=new h(l,i,s.text,s.icon),n=n||s.text!==l.text.placed||s.icon!==l.icon.placed):(r.opacities[a]=new h(null,i,s.text,s.icon,s.skipFade),n=n||s.text||s.icon)}for(var u in o){var c=o[u];if(!r.opacities[u]){var p=new h(c,i,!1,!1);p.isHidden()||(r.opacities[u]=p,n=n||c.text.placed||c.icon.placed)}}n?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)},d.prototype.updateLayerOpacities=function(t,e){for(var r={},n=0,i=e;n0||l.numVerticalGlyphVertices>0,f=l.numIconVertices>0;if(p){for(var d=i(c.text),y=(l.numGlyphVertices+l.numVerticalGlyphVertices)/4,m=0;mt},d.prototype.setStale=function(){this.stale=!0};var y=Math.pow(2,25),m=Math.pow(2,24),g=Math.pow(2,17),v=Math.pow(2,16),_=Math.pow(2,9),x=Math.pow(2,8),b=Math.pow(2,1);e.exports=d},{"../data/extent":53,"../source/pixels_to_tile_units":104,"../style/style_layer/symbol_style_layer_properties":209,"./collision_index":217,"./projection":224,"./symbol_size":228}],224:[function(t,e,r){function n(t,e){var r=[t.x,t.y,0,1];p(r,r,e);var n=r[3];return{point:new h(r[0]/n,r[1]/n),signedDistanceFromCamera:n}}function i(t,e){var r=t[0]/t[3],n=t[1]/t[3];return r>=-e[0]&&r<=e[0]&&n>=-e[1]&&n<=e[1]}function o(t,e,r,n,i,o,a,s,l,c,p,h){var f=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,y=s.lineStartIndex+s.lineLength,m=e.getoffsetX(s.glyphStartIndex),g=e.getoffsetX(f-1),v=u(t*m,r,n,i,o,a,s.segment,d,y,l,c,p,h);if(!v)return null;var _=u(t*g,r,n,i,o,a,s.segment,d,y,l,c,p,h);return _?{first:v,last:_}:null}function a(t,e,r,n){return t===_.horizontal&&Math.abs(r.y-e.y)>Math.abs(r.x-e.x)*n?{useVertical:!0}:(t===_.vertical?e.yr.x)?{needsFlipping:!0}:null}function s(t,e,r,i,s,c,p,f,d,y,m,v,_,x){var b,w=e/24,k=t.lineOffsetX*e,A=t.lineOffsetY*e;if(t.numGlyphs>1){var T=t.glyphStartIndex+t.numGlyphs,M=t.lineStartIndex,S=t.lineStartIndex+t.lineLength,C=o(w,f,k,A,r,m,v,t,d,c,_,!1);if(!C)return{notEnoughRoom:!0};var z=n(C.first.point,p).point,L=n(C.last.point,p).point;if(i&&!r){var E=a(t.writingMode,z,L,x);if(E)return E}b=[C.first];for(var P=t.glyphStartIndex+1;P0?R.point:l(v,O,I,1,s),F=a(t.writingMode,I,B,x);if(F)return F}var N=u(w*f.getoffsetX(t.glyphStartIndex),k,A,r,m,v,t.segment,t.lineStartIndex,t.lineStartIndex+t.lineLength,d,c,_,!1);if(!N)return{notEnoughRoom:!0};b=[N]}for(var j=0,V=b;j0?1:-1,v=0;i&&(g*=-1,v=Math.PI),g<0&&(v+=Math.PI);for(var _=g>0?u+s:u+s+1,x=_,b=o,w=o,k=0,A=0,T=Math.abs(m);k+A<=T;){if((_+=g)=c)return null;if(w=b,void 0===(b=d[_])){var M=new h(p.getx(_),p.gety(_)),S=n(M,f);if(S.signedDistanceFromCamera>0)b=d[_]=S.point;else{var C=_-g;b=l(0===k?a:new h(p.getx(C),p.gety(C)),M,w,T-k+1,f)}}k+=A,A=w.dist(b)}var z=(T-k)/A,L=b.sub(w),E=L.mult(z)._add(w);return E._add(L._unit()._perp()._mult(r*g)),{point:E,angle:v+Math.atan2(b.y-w.y,b.x-w.x),tileDistance:y?{prevTileDistance:_-g===x?0:p.gettileUnitDistanceFromAnchor(_-g),lastSegmentViewportDistance:T-k}:null}}function c(t,e){for(var r=0;r=w||a.y<0||a.y>=w||t.symbolInstances.push(function(t,e,r,n,o,a,s,l,c,p,h,d,y,_,x,b,w,A,T,M,S,C){var z,L,E=t.addToLineVertexArray(e,r),P=0,I=0,D=0,O=n.horizontal?n.horizontal.text:"",R=[];n.horizontal&&(z=new g(s,r,e,l,c,p,n.horizontal,h,d,y,t.overscaling),I+=i(t,e,n.horizontal,a,y,T,M,_,E,n.vertical?f.horizontal:f.horizontalOnly,R,S,C),n.vertical&&(D+=i(t,e,n.vertical,a,y,T,M,_,E,f.vertical,R,S,C)));var B=z?z.boxStartIndex:t.collisionBoxArray.length,F=z?z.boxEndIndex:t.collisionBoxArray.length;if(o){var N=m(e,o,a,w,n.horizontal,T,M);L=new g(s,r,e,l,c,p,o,x,b,!1,t.overscaling),P=4*N.length;var j=t.iconSizeData,V=null;"source"===j.functionType?V=[10*a.layout.get("icon-size").evaluate(M)]:"composite"===j.functionType&&(V=[10*C.compositeIconSizes[0].evaluate(M),10*C.compositeIconSizes[1].evaluate(M)]),t.addSymbols(t.icon,N,V,A,w,M,!1,e,E.lineStartIndex,E.lineLength)}var q=L?L.boxStartIndex:t.collisionBoxArray.length,U=L?L.boxEndIndex:t.collisionBoxArray.length;return t.glyphOffsetArray.length>=k.MAX_GLYPHS&&v.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),{key:O,textBoxStartIndex:B,textBoxEndIndex:F,iconBoxStartIndex:q,iconBoxEndIndex:U,textOffset:_,iconOffset:A,anchor:e,line:r,featureIndex:l,feature:M,numGlyphVertices:I,numVerticalGlyphVertices:D,numIconVertices:P,textOpacityState:new u,iconOpacityState:new u,isDuplicate:!1,placedTextSymbolIndices:R,crossTileID:0}}(t,a,o,r,n,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,S,E,D,A,z,P,O,T,{zoom:t.zoom},e,c,p))};if("line"===_.get("symbol-placement"))for(var F=0,N=l(e.geometry,0,0,w,w);F=0;a--)if(n.dist(o[a])1||(h?(clearTimeout(h),h=null,a("dblclick",e)):h=setTimeout(r,300))},!1),l.addEventListener("touchend",function(t){s("touchend",t)},!1),l.addEventListener("touchmove",function(t){s("touchmove",t)},!1),l.addEventListener("touchcancel",function(t){s("touchcancel",t)},!1),l.addEventListener("click",function(t){n.mousePos(l,t).equals(p)&&a("click",t)},!1),l.addEventListener("dblclick",function(t){a("dblclick",t),t.preventDefault()},!1),l.addEventListener("contextmenu",function(e){var r=t.dragRotate&&t.dragRotate.isActive();c||r?c&&(u=e):a("contextmenu",e),e.preventDefault()},!1)}},{"../util/dom":259,"./handler/box_zoom":239,"./handler/dblclick_zoom":240,"./handler/drag_pan":241,"./handler/drag_rotate":242,"./handler/keyboard":243,"./handler/scroll_zoom":244,"./handler/touch_zoom_rotate":245,"@mapbox/point-geometry":4}],231:[function(t,e,r){var n=t("../util/util"),i=t("../style-spec/util/interpolate").number,o=t("../util/browser"),a=t("../geo/lng_lat"),s=t("../geo/lng_lat_bounds"),l=t("@mapbox/point-geometry"),u=function(t){function e(e,r){t.call(this),this.moving=!1,this.transform=e,this._bearingSnap=r.bearingSnap}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getCenter=function(){return this.transform.center},e.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},e.prototype.panBy=function(t,e,r){return t=l.convert(t).mult(-1),this.panTo(this.transform.center,n.extend({offset:t},e),r)},e.prototype.panTo=function(t,e,r){return this.easeTo(n.extend({center:t},e),r)},e.prototype.getZoom=function(){return this.transform.zoom},e.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},e.prototype.zoomTo=function(t,e,r){return this.easeTo(n.extend({zoom:t},e),r)},e.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},e.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},e.prototype.getBearing=function(){return this.transform.bearing},e.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},e.prototype.rotateTo=function(t,e,r){return this.easeTo(n.extend({bearing:t},e),r)},e.prototype.resetNorth=function(t,e){return this.rotateTo(0,n.extend({duration:1e3},t),e),this},e.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())e?1:0}),["bottom","left","right","top"]))return n.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;t=s.convert(t);var o=[(e.padding.left-e.padding.right)/2,(e.padding.top-e.padding.bottom)/2],a=Math.min(e.padding.right,e.padding.left),u=Math.min(e.padding.top,e.padding.bottom);e.offset=[e.offset[0]+o[0],e.offset[1]+o[1]];var c=l.convert(e.offset),p=this.transform,h=p.project(t.getNorthWest()),f=p.project(t.getSouthEast()),d=f.sub(h),y=(p.width-2*a-2*Math.abs(c.x))/d.x,m=(p.height-2*u-2*Math.abs(c.y))/d.y;return m<0||y<0?(n.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(e.center=p.unproject(h.add(f).div(2)),e.zoom=Math.min(p.scaleZoom(p.scale*Math.min(y,m)),e.maxZoom),e.bearing=0,e.linear?this.easeTo(e,r):this.flyTo(e,r))},e.prototype.jumpTo=function(t,e){this.stop();var r=this.transform,n=!1,i=!1,o=!1;return"zoom"in t&&r.zoom!==+t.zoom&&(n=!0,r.zoom=+t.zoom),void 0!==t.center&&(r.center=a.convert(t.center)),"bearing"in t&&r.bearing!==+t.bearing&&(i=!0,r.bearing=+t.bearing),"pitch"in t&&r.pitch!==+t.pitch&&(o=!0,r.pitch=+t.pitch),this.fire("movestart",e).fire("move",e),n&&this.fire("zoomstart",e).fire("zoom",e).fire("zoomend",e),i&&this.fire("rotate",e),o&&this.fire("pitchstart",e).fire("pitch",e).fire("pitchend",e),this.fire("moveend",e)},e.prototype.easeTo=function(t,e){var r=this;this.stop(),!1===(t=n.extend({offset:[0,0],duration:500,easing:n.ease},t)).animate&&(t.duration=0);var o=this.transform,s=this.getZoom(),u=this.getBearing(),c=this.getPitch(),p="zoom"in t?+t.zoom:s,h="bearing"in t?this._normalizeBearing(t.bearing,u):u,f="pitch"in t?+t.pitch:c,d=o.centerPoint.add(l.convert(t.offset)),y=o.pointLocation(d),m=a.convert(t.center||y);this._normalizeCenter(m);var g,v,_=o.project(y),x=o.project(m).sub(_),b=o.zoomScale(p-s);return t.around&&(g=a.convert(t.around),v=o.locationPoint(g)),this.zooming=p!==s,this.rotating=u!==h,this.pitching=f!==c,this._prepareEase(e,t.noMoveStart),clearTimeout(this._onEaseEnd),this._ease(function(t){if(r.zooming&&(o.zoom=i(s,p,t)),r.rotating&&(o.bearing=i(u,h,t)),r.pitching&&(o.pitch=i(c,f,t)),g)o.setLocationAtPoint(g,v);else{var n=o.zoomScale(o.zoom-s),a=p>s?Math.min(2,b):Math.max(.5,b),l=Math.pow(a,1-t),y=o.unproject(_.add(x.mult(t*l)).mult(n));o.setLocationAtPoint(o.renderWorldCopies?y.wrap():y,d)}r._fireMoveEvents(e)},function(){t.delayEndEvents?r._onEaseEnd=setTimeout(function(){return r._afterEase(e)},t.delayEndEvents):r._afterEase(e)},t),this},e.prototype._prepareEase=function(t,e){this.moving=!0,e||this.fire("movestart",t),this.zooming&&this.fire("zoomstart",t),this.pitching&&this.fire("pitchstart",t)},e.prototype._fireMoveEvents=function(t){this.fire("move",t),this.zooming&&this.fire("zoom",t),this.rotating&&this.fire("rotate",t),this.pitching&&this.fire("pitch",t)},e.prototype._afterEase=function(t){var e=this.zooming,r=this.pitching;this.moving=!1,this.zooming=!1,this.rotating=!1,this.pitching=!1,e&&this.fire("zoomend",t),r&&this.fire("pitchend",t),this.fire("moveend",t)},e.prototype.flyTo=function(t,e){function r(t){var e=(T*T-A*A+(t?-1:1)*z*z*M*M)/(2*(t?T:A)*z*M);return Math.log(Math.sqrt(e*e+1)-e)}function o(t){return(Math.exp(t)-Math.exp(-t))/2}function s(t){return(Math.exp(t)+Math.exp(-t))/2}var u=this;this.stop(),t=n.extend({offset:[0,0],speed:1.2,curve:1.42,easing:n.ease},t);var c=this.transform,p=this.getZoom(),h=this.getBearing(),f=this.getPitch(),d="zoom"in t?n.clamp(+t.zoom,c.minZoom,c.maxZoom):p,y="bearing"in t?this._normalizeBearing(t.bearing,h):h,m="pitch"in t?+t.pitch:f,g=c.zoomScale(d-p),v=c.centerPoint.add(l.convert(t.offset)),_=c.pointLocation(v),x=a.convert(t.center||_);this._normalizeCenter(x);var b=c.project(_),w=c.project(x).sub(b),k=t.curve,A=Math.max(c.width,c.height),T=A/g,M=w.mag();if("minZoom"in t){var S=n.clamp(Math.min(t.minZoom,p,d),c.minZoom,c.maxZoom),C=A/c.zoomScale(S-p);k=Math.sqrt(C/M*2)}var z=k*k,L=r(0),E=function(t){return s(L)/s(L+k*t)},P=function(t){return A*((s(L)*function(t){return o(t)/s(t)}(L+k*t)-o(L))/z)/M},I=(r(1)-L)/k;if(Math.abs(M)<1e-6||!isFinite(I)){if(Math.abs(A-T)<1e-6)return this.easeTo(t,e);var D=Tt.maxDuration&&(t.duration=0),this.zooming=!0,this.rotating=h!==y,this.pitching=m!==f,this._prepareEase(e,!1),this._ease(function(t){var r=t*I,n=1/E(r);c.zoom=p+c.scaleZoom(n),u.rotating&&(c.bearing=i(h,y,t)),u.pitching&&(c.pitch=i(f,m,t));var o=c.unproject(b.add(w.mult(P(r))).mult(n));c.setLocationAtPoint(c.renderWorldCopies?o.wrap():o,v),u._fireMoveEvents(e)},function(){return u._afterEase(e)},t),this},e.prototype.isEasing=function(){return!!this._isEasing},e.prototype.isMoving=function(){return this.moving},e.prototype.stop=function(){return this._onFrame&&this._finishAnimation(),this},e.prototype._ease=function(t,e,r){var n=this;!1===r.animate||0===r.duration?(t(1),e()):(this._easeStart=o.now(),this._isEasing=!0,this._easeOptions=r,this._startAnimation(function(e){var r=Math.min((o.now()-n._easeStart)/n._easeOptions.duration,1);t(n._easeOptions.easing(r)),1===r&&n.stop()},function(){n._isEasing=!1,e()}))},e.prototype._updateCamera=function(){this._onFrame&&this._onFrame(this.transform)},e.prototype._startAnimation=function(t,e){return void 0===e&&(e=function(){}),this.stop(),this._onFrame=t,this._finishFn=e,this._update(),this},e.prototype._finishAnimation=function(){delete this._onFrame;var t=this._finishFn;delete this._finishFn,t.call(this)},e.prototype._normalizeBearing=function(t,e){t=n.wrap(t,-180,180);var r=Math.abs(t-e);return Math.abs(t-360-e)180?-360:r<-180?360:0}},e}(t("../util/evented"));e.exports=u},{"../geo/lng_lat":62,"../geo/lng_lat_bounds":63,"../style-spec/util/interpolate":158,"../util/browser":252,"../util/evented":260,"../util/util":275,"@mapbox/point-geometry":4}],232:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../../util/config"),a=function(t){this.options=t,i.bindAll(["_updateEditLink","_updateData","_updateCompact"],this)};a.prototype.getDefaultPosition=function(){return"bottom-right"},a.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},a.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0},a.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:o.ACCESS_TOKEN}];if(t){var r=e.reduce(function(t,r,n){return r.value&&(t+=r.key+"="+r.value+(n=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null}},a.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact")},e.exports=a},{"../../util/config":256,"../../util/dom":259,"../../util/util":275}],233:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../../util/window"),a=function(){this._fullscreen=!1,i.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in o.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in o.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in o.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in o.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl"};a.prototype.onAdd=function(t){return this._map=t,this._mapContainer=this._map.getContainer(),this._container=n.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",i.warnOnce("This device does not support fullscreen mode.")),this._container},a.prototype.onRemove=function(){n.remove(this._container),this._map=null,o.document.removeEventListener(this._fullscreenchange,this._changeIcon)},a.prototype._checkFullscreenSupport=function(){return!!(o.document.fullscreenEnabled||o.document.mozFullScreenEnabled||o.document.msFullscreenEnabled||o.document.webkitFullscreenEnabled)},a.prototype._setupUI=function(){var t=this._fullscreenButton=n.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);t.setAttribute("aria-label","Toggle fullscreen"),t.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),o.document.addEventListener(this._fullscreenchange,this._changeIcon)},a.prototype._isFullscreen=function(){return this._fullscreen},a.prototype._changeIcon=function(){(o.document.fullscreenElement||o.document.mozFullScreenElement||o.document.webkitFullscreenElement||o.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"))},a.prototype._onClickFullscreen=function(){this._isFullscreen()?o.document.exitFullscreen?o.document.exitFullscreen():o.document.mozCancelFullScreen?o.document.mozCancelFullScreen():o.document.msExitFullscreen?o.document.msExitFullscreen():o.document.webkitCancelFullScreen&&o.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen()},e.exports=a},{"../../util/dom":259,"../../util/util":275,"../../util/window":254}],234:[function(t,e,r){var n,i=t("../../util/evented"),o=t("../../util/dom"),a=t("../../util/window"),s=t("../../util/util"),l=t("../../geo/lng_lat"),u=t("../marker"),c={positionOptions:{enableHighAccuracy:!1,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0},p=function(t){function e(e){t.call(this),this.options=s.extend({},c,e),s.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker","_onClickGeolocate"],this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onAdd=function(t){return this._map=t,this._container=o.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),function(t){void 0!==n?t(n):void 0!==a.navigator.permissions?a.navigator.permissions.query({name:"geolocation"}).then(function(e){n="denied"!==e.state,t(n)}):(n=!!a.navigator.geolocation,t(n))}(this._setupUI),this._container},e.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(a.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),o.remove(this._container),this._map=void 0},e.prototype._onSuccess=function(t){if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire("geolocate",t),this._finish()},e.prototype._updateCamera=function(t){var e=new l(t.coords.longitude,t.coords.latitude),r=t.coords.accuracy;this._map.fitBounds(e.toBounds(r),this.options.fitBoundsOptions,{geolocateSource:!0})},e.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove()},e.prototype._onError=function(t){if(this.options.trackUserLocation)if(1===t.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire("error",t),this._finish()},e.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},e.prototype._setupUI=function(t){var e=this;!1!==t&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=o.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=o.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new u(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this._onClickGeolocate.bind(this)),this.options.trackUserLocation&&this._map.on("movestart",function(t){t.geolocateSource||"ACTIVE_LOCK"!==e._watchState||(e._watchState="BACKGROUND",e._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),e._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),e.fire("trackuserlocationend"))}))},e.prototype._onClickGeolocate=function(){if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire("trackuserlocationstart");break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire("trackuserlocationend");break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire("trackuserlocationstart")}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=a.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions))}else a.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4)},e.prototype._clearWatch=function(){a.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)},e}(i);e.exports=p},{"../../geo/lng_lat":62,"../../util/dom":259,"../../util/evented":260,"../../util/util":275,"../../util/window":254,"../marker":248}],235:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=function(){i.bindAll(["_updateLogo"],this)};o.prototype.onAdd=function(t){this._map=t,this._container=n.create("div","mapboxgl-ctrl");var e=n.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateLogo)},o.prototype.getDefaultPosition=function(){return"bottom-left"},o.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")},o.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return!0;return!1}},e.exports=o},{"../../util/dom":259,"../../util/util":275}],236:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../handler/drag_rotate"),a={showCompass:!0,showZoom:!0},s=function(t){var e=this;this.options=i.extend({},a,t),this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return e._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return e._map.zoomOut()})),this.options.showCompass&&(i.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return e._map.resetNorth()}),this._compassArrow=n.create("span","mapboxgl-ctrl-compass-arrow",this._compass))};s.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t},s.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new o(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},s.prototype.onRemove=function(){n.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map},s.prototype._createButton=function(t,e,r){var i=n.create("button",t,this._container);return i.type="button",i.setAttribute("aria-label",e),i.addEventListener("click",r),i},e.exports=s},{"../../util/dom":259,"../../util/util":275,"../handler/drag_rotate":242}],237:[function(t,e,r){function n(t,e,r){var n=r&&r.maxWidth||100,o=t._container.clientHeight/2,a=function(t,e){var r=Math.PI/180,n=t.lat*r,i=e.lat*r,o=Math.sin(n)*Math.sin(i)+Math.cos(n)*Math.cos(i)*Math.cos((e.lng-t.lng)*r);return 6371e3*Math.acos(Math.min(o,1))}(t.unproject([0,o]),t.unproject([n,o]));if(r&&"imperial"===r.unit){var s=3.2808*a;s>5280?i(e,n,s/5280,"mi"):i(e,n,s,"ft")}else if(r&&"nautical"===r.unit){i(e,n,a/1852,"nm")}else i(e,n,a,"m")}function i(t,e,r,n){var i=function(t){var e=Math.pow(10,(""+Math.floor(t)).length-1),r=t/e;return e*(r=r>=10?10:r>=5?5:r>=3?3:r>=2?2:1)}(r),o=i/r;"m"===n&&i>=1e3&&(i/=1e3,n="km"),t.style.width=e*o+"px",t.innerHTML=i+n}var o=t("../../util/dom"),a=t("../../util/util"),s=function(t){this.options=t,a.bindAll(["_onMove"],this)};s.prototype.getDefaultPosition=function(){return"bottom-left"},s.prototype._onMove=function(){n(this._map,this._container,this.options)},s.prototype.onAdd=function(t){return this._map=t,this._container=o.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},s.prototype.onRemove=function(){o.remove(this._container),this._map.off("move",this._onMove),this._map=void 0},e.exports=s},{"../../util/dom":259,"../../util/util":275}],238:[function(t,e,r){},{}],239:[function(t,e,r){var n=t("../../util/dom"),i=t("../../geo/lng_lat_bounds"),o=t("../../util/util"),a=t("../../util/window"),s=function(t){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),o.bindAll(["_onMouseDown","_onMouseMove","_onMouseUp","_onKeyDown"],this)};s.prototype.isEnabled=function(){return!!this._enabled},s.prototype.isActive=function(){return!!this._active},s.prototype.enable=function(){this.isEnabled()||(this._map.dragPan&&this._map.dragPan.disable(),this._el.addEventListener("mousedown",this._onMouseDown,!1),this._map.dragPan&&this._map.dragPan.enable(),this._enabled=!0)},s.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onMouseDown),this._enabled=!1)},s.prototype._onMouseDown=function(t){t.shiftKey&&0===t.button&&(a.document.addEventListener("mousemove",this._onMouseMove,!1),a.document.addEventListener("keydown",this._onKeyDown,!1),a.document.addEventListener("mouseup",this._onMouseUp,!1),n.disableDrag(),this._startPos=n.mousePos(this._el,t),this._active=!0)},s.prototype._onMouseMove=function(t){var e=this._startPos,r=n.mousePos(this._el,t);this._box||(this._box=n.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var i=Math.min(e.x,r.x),o=Math.max(e.x,r.x),a=Math.min(e.y,r.y),s=Math.max(e.y,r.y);n.setTransform(this._box,"translate("+i+"px,"+a+"px)"),this._box.style.width=o-i+"px",this._box.style.height=s-a+"px"},s.prototype._onMouseUp=function(t){if(0===t.button){var e=this._startPos,r=n.mousePos(this._el,t),o=(new i).extend(this._map.unproject(e)).extend(this._map.unproject(r));this._finish(),e.x===r.x&&e.y===r.y?this._fireEvent("boxzoomcancel",t):this._map.fitBounds(o,{linear:!0}).fire("boxzoomend",{originalEvent:t,boxZoomBounds:o})}},s.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t))},s.prototype._finish=function(){this._active=!1,a.document.removeEventListener("mousemove",this._onMouseMove,!1),a.document.removeEventListener("keydown",this._onKeyDown,!1),a.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag()},s.prototype._fireEvent=function(t,e){return this._map.fire(t,{originalEvent:e})},e.exports=s},{"../../geo/lng_lat_bounds":63,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],240:[function(t,e,r){var n=t("../../util/util"),i=function(t){this._map=t,n.bindAll(["_onDblClick","_onZoomEnd"],this)};i.prototype.isEnabled=function(){return!!this._enabled},i.prototype.isActive=function(){return!!this._active},i.prototype.enable=function(){this.isEnabled()||(this._map.on("dblclick",this._onDblClick),this._enabled=!0)},i.prototype.disable=function(){this.isEnabled()&&(this._map.off("dblclick",this._onDblClick),this._enabled=!1)},i.prototype._onDblClick=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t)},i.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd)},e.exports=i},{"../../util/util":275}],241:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../../util/window"),a=t("../../util/browser"),s=i.bezier(0,0,.3,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onDown","_onMove","_onUp","_onTouchEnd","_onMouseUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._el.addEventListener("mousedown",this._onDown),this._el.addEventListener("touchstart",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._el.removeEventListener("mousedown",this._onDown),this._el.removeEventListener("touchstart",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){this._ignoreEvent(t)||this.isActive()||(t.touches?(o.document.addEventListener("touchmove",this._onMove),o.document.addEventListener("touchend",this._onTouchEnd)):(o.document.addEventListener("mousemove",this._onMove),o.document.addEventListener("mouseup",this._onMouseUp)),o.addEventListener("blur",this._onMouseUp),this._active=!1,this._previousPos=n.mousePos(this._el,t),this._inertia=[[a.now(),this._previousPos]])},l.prototype._onMove=function(t){if(!this._ignoreEvent(t)){this._lastMoveEvent=t,t.preventDefault();var e=n.mousePos(this._el,t);if(this._drainInertiaBuffer(),this._inertia.push([a.now(),e]),!this._previousPos)return void(this._previousPos=e);this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("dragstart",t),this._fireEvent("movestart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()}},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;e&&(t.setLocationAtPoint(t.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",e),this._fireEvent("move",e),this._previousPos=this._pos,delete this._lastMoveEvent)},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,delete this._pos,this._fireEvent("dragend",t),this._drainInertiaBuffer();var r=function(){e._map.moving=!1,e._fireEvent("moveend",t)},n=this._inertia;if(n.length<2)return void r();var i=n[n.length-1],o=n[0],a=i[1].sub(o[1]),l=(i[0]-o[0])/1e3;if(0===l||i[1].equals(o[1]))return void r();var u=a.mult(.3/l),c=u.mag();c>1400&&(c=1400,u._unit()._mult(c));var p=c/750,h=u.mult(-p/2);this._map.panBy(h,{duration:1e3*p,easing:s,noMoveStart:!0},{originalEvent:t})}},l.prototype._onUp=function(t){this._onDragFinished(t)},l.prototype._onMouseUp=function(t){this._ignoreEvent(t)||(this._onUp(t),o.document.removeEventListener("mousemove",this._onMove),o.document.removeEventListener("mouseup",this._onMouseUp),o.removeEventListener("blur",this._onMouseUp))},l.prototype._onTouchEnd=function(t){this._ignoreEvent(t)||(this._onUp(t),o.document.removeEventListener("touchmove",this._onMove),o.document.removeEventListener("touchend",this._onTouchEnd))},l.prototype._fireEvent=function(t,e){return this._map.fire(t,e?{originalEvent:e}:{})},l.prototype._ignoreEvent=function(t){var e=this._map;return!(!e.boxZoom||!e.boxZoom.isActive())||!(!e.dragRotate||!e.dragRotate.isActive())||(t.touches?t.touches.length>1:!!t.ctrlKey||"mousemove"!==t.type&&t.button&&0!==t.button)},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=a.now();t.length>0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],242:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../../util/window"),a=t("../../util/browser"),s=i.bezier(0,0,.25,1),l=function(t,e){this._map=t,this._el=e.element||t.getCanvasContainer(),this._button=e.button||"right",this._bearingSnap=e.bearingSnap||0,this._pitchWithRotate=!1!==e.pitchWithRotate,i.bindAll(["_onDown","_onMove","_onUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){if(!(this._map.boxZoom&&this._map.boxZoom.isActive()||this._map.dragPan&&this._map.dragPan.isActive()||this.isActive())){if("right"===this._button){var e=t.ctrlKey?0:2,r=t.button;if(void 0!==o.InstallTrigger&&2===t.button&&t.ctrlKey&&o.navigator.platform.toUpperCase().indexOf("MAC")>=0&&(r=0),r!==e)return}else if(t.ctrlKey||0!==t.button)return;n.disableDrag(),o.document.addEventListener("mousemove",this._onMove,{capture:!0}),o.document.addEventListener("mouseup",this._onUp),o.addEventListener("blur",this._onUp),this._active=!1,this._inertia=[[a.now(),this._map.getBearing()]],this._previousPos=n.mousePos(this._el,t),this._center=this._map.transform.centerPoint,t.preventDefault()}},l.prototype._onMove=function(t){this._lastMoveEvent=t;var e=n.mousePos(this._el,t);this._previousPos?(this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()):this._previousPos=e},l.prototype._onUp=function(t){o.document.removeEventListener("mousemove",this._onMove,{capture:!0}),o.document.removeEventListener("mouseup",this._onUp),o.removeEventListener("blur",this._onUp),n.enableDrag(),this._onDragFinished(t)},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;if(e){var r=this._previousPos,n=this._pos,i=.8*(r.x-n.x),o=-.5*(r.y-n.y),s=t.bearing-i,l=t.pitch-o,u=this._inertia,c=u[u.length-1];this._drainInertiaBuffer(),u.push([a.now(),this._map._normalizeBearing(s,c[1])]),t.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",e),t.pitch=l),this._fireEvent("rotate",e),this._fireEvent("move",e),delete this._lastMoveEvent,this._previousPos=this._pos}},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,this._fireEvent("rotateend",t),this._drainInertiaBuffer();var r=this._map,n=r.getBearing(),i=this._inertia,o=function(){Math.abs(n)180&&(d=180);var y=d/180;c+=h*d*(y/2),Math.abs(r._normalizeBearing(c,0))0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],243:[function(t,e,r){function n(t){return t*(2-t)}var i=t("../../util/util"),o=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onKeyDown"],this)};o.prototype.isEnabled=function(){return!!this._enabled},o.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0)},o.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1)},o.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,r=0,i=0,o=0,a=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?r=-1:(t.preventDefault(),o=-1);break;case 39:t.shiftKey?r=1:(t.preventDefault(),o=1);break;case 38:t.shiftKey?i=1:(t.preventDefault(),a=-1);break;case 40:t.shiftKey?i=-1:(a=1,t.preventDefault());break;default:return}var s=this._map,l=s.getZoom(),u={duration:300,delayEndEvents:500,easing:n,zoom:e?Math.round(l)+e*(t.shiftKey?2:1):l,bearing:s.getBearing()+15*r,pitch:s.getPitch()+10*i,offset:[100*-o,100*-a],center:s.getCenter()};s.easeTo(u,{originalEvent:t})}},e.exports=o},{"../../util/util":275}],244:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../../util/browser"),a=t("../../util/window"),s=t("../../style-spec/util/interpolate").number,l=t("../../geo/lng_lat"),u=a.navigator.userAgent.toLowerCase(),c=-1!==u.indexOf("firefox"),p=-1!==u.indexOf("safari")&&-1===u.indexOf("chrom"),h=function(t){this._map=t,this._el=t.getCanvasContainer(),this._delta=0,i.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this)};h.prototype.isEnabled=function(){return!!this._enabled},h.prototype.isActive=function(){return!!this._active},h.prototype.enable=function(t){this.isEnabled()||(this._el.addEventListener("wheel",this._onWheel,!1),this._el.addEventListener("mousewheel",this._onWheel,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},h.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("wheel",this._onWheel),this._el.removeEventListener("mousewheel",this._onWheel),this._enabled=!1)},h.prototype._onWheel=function(t){var e=0;"wheel"===t.type?(e=t.deltaY,c&&t.deltaMode===a.WheelEvent.DOM_DELTA_PIXEL&&(e/=o.devicePixelRatio),t.deltaMode===a.WheelEvent.DOM_DELTA_LINE&&(e*=40)):"mousewheel"===t.type&&(e=-t.wheelDeltaY,p&&(e/=3));var r=o.now(),n=r-(this._lastWheelEventTime||0);this._lastWheelEventTime=r,0!==e&&e%4.000244140625==0?this._type="wheel":0!==e&&Math.abs(e)<4?this._type="trackpad":n>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(n*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&(this._lastWheelEvent=t,this._delta-=e,this.isActive()||this._start(t)),t.preventDefault()},h.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t)},h.prototype._start=function(t){if(this._delta){this._active=!0,this._map.moving=!0,this._map.zooming=!0,this._map.fire("movestart",{originalEvent:t}),this._map.fire("zoomstart",{originalEvent:t}),clearTimeout(this._finishTimeout);var e=n.mousePos(this._el,t);this._around=l.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(e)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._map._startAnimation(this._onScrollFrame,this._onScrollFinished)}},h.prototype._onScrollFrame=function(t){if(this.isActive()){if(0!==this._delta){var e="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,r=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==r&&(r=1/r);var n="number"==typeof this._targetZoom?t.zoomScale(this._targetZoom):t.scale;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(n*r))),"wheel"===this._type&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}if("wheel"===this._type){var i=Math.min((o.now()-this._lastWheelEventTime)/200,1),a=this._easing(i);t.zoom=s(this._startZoom,this._targetZoom,a),1===i&&this._map.stop()}else t.zoom=this._targetZoom,this._map.stop();t.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire("move",{originalEvent:this._lastWheelEvent}),this._map.fire("zoom",{originalEvent:this._lastWheelEvent})}},h.prototype._onScrollFinished=function(){var t=this;this.isActive()&&(this._active=!1,this._finishTimeout=setTimeout(function(){t._map.moving=!1,t._map.zooming=!1,t._map.fire("zoomend"),t._map.fire("moveend"),delete t._targetZoom},200))},h.prototype._smoothOutEasing=function(t){var e=i.ease;if(this._prevEase){var r=this._prevEase,n=(o.now()-r.start)/r.duration,a=r.easing(n+.01)-r.easing(n),s=.27/Math.sqrt(a*a+1e-4)*.01,l=Math.sqrt(.0729-s*s);e=i.bezier(s,l,.25,1)}return this._prevEase={start:o.now(),duration:t,easing:e},e},e.exports=h},{"../../geo/lng_lat":62,"../../style-spec/util/interpolate":158,"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],245:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),o=t("../../util/window"),a=t("../../util/browser"),s=i.bezier(0,0,.15,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onStart","_onMove","_onEnd"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._el.addEventListener("touchstart",this._onStart,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._el.removeEventListener("touchstart",this._onStart),this._enabled=!1)},l.prototype.disableRotation=function(){this._rotationDisabled=!0},l.prototype.enableRotation=function(){this._rotationDisabled=!1},l.prototype._onStart=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]);this._startVec=e.sub(r),this._startScale=this._map.transform.scale,this._startBearing=this._map.transform.bearing,this._gestureIntent=void 0,this._inertia=[],o.document.addEventListener("touchmove",this._onMove,!1),o.document.addEventListener("touchend",this._onEnd,!1)}},l.prototype._onMove=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]),i=e.add(r).div(2),o=e.sub(r),s=o.mag()/this._startVec.mag(),l=this._rotationDisabled?0:180*o.angleWith(this._startVec)/Math.PI,u=this._map;if(this._gestureIntent){var c={duration:0,around:u.unproject(i)};"rotate"===this._gestureIntent&&(c.bearing=this._startBearing+l),"zoom"!==this._gestureIntent&&"rotate"!==this._gestureIntent||(c.zoom=u.transform.scaleZoom(this._startScale*s)),u.stop(),this._drainInertiaBuffer(),this._inertia.push([a.now(),s,i]),u.easeTo(c,{originalEvent:t})}else{var p=Math.abs(1-s)>.15;Math.abs(l)>10?this._gestureIntent="rotate":p&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._startVec=o,this._startScale=u.transform.scale,this._startBearing=u.transform.bearing)}t.preventDefault()}},l.prototype._onEnd=function(t){o.document.removeEventListener("touchmove",this._onMove),o.document.removeEventListener("touchend",this._onEnd),this._drainInertiaBuffer();var e=this._inertia,r=this._map;if(e.length<2)r.snapToNorth({},{originalEvent:t});else{var n=e[e.length-1],i=e[0],a=r.transform.scaleZoom(this._startScale*n[1]),l=r.transform.scaleZoom(this._startScale*i[1]),u=a-l,c=(n[0]-i[0])/1e3,p=n[2];if(0!==c&&a!==l){var h=.15*u/c;Math.abs(h)>2.5&&(h=h>0?2.5:-2.5);var f=1e3*Math.abs(h/(12*.15)),d=a+h*f/2e3;d<0&&(d=0),r.easeTo({zoom:d,duration:f,easing:s,around:this._aroundCenter?r.getCenter():r.unproject(p)},{originalEvent:t})}else r.snapToNorth({},{originalEvent:t})}},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=a.now();t.length>2&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],246:[function(t,e,r){var n=t("../util/util"),i=t("../util/window"),o=t("../util/throttle"),a=function(){n.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=o(this._updateHashUnthrottled.bind(this),300)};a.prototype.addTo=function(t){return this._map=t,i.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},a.prototype.remove=function(){return i.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),delete this._map,this},a.prototype.getHashString=function(t){var e=this._map.getCenter(),r=Math.round(100*this._map.getZoom())/100,n=Math.ceil((r*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.pow(10,n),o=Math.round(e.lng*i)/i,a=Math.round(e.lat*i)/i,s=this._map.getBearing(),l=this._map.getPitch(),u="";return u+=t?"#/"+o+"/"+a+"/"+r:"#"+r+"/"+a+"/"+o,(s||l)&&(u+="/"+Math.round(10*s)/10),l&&(u+="/"+Math.round(l)),u},a.prototype._onHashChange=function(){var t=i.location.hash.replace("#","").split("/");return t.length>=3&&(this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:+(t[3]||0),pitch:+(t[4]||0)}),!0)},a.prototype._updateHashUnthrottled=function(){var t=this.getHashString();i.history.replaceState("","",t)},e.exports=a},{"../util/throttle":272,"../util/util":275,"../util/window":254}],247:[function(t,e,r){function n(t){t.parentNode&&t.parentNode.removeChild(t)}var i=t("../util/util"),o=t("../util/browser"),a=t("../util/window"),s=t("../util/window"),l=s.HTMLImageElement,u=s.HTMLElement,c=t("../util/dom"),p=t("../util/ajax"),h=t("../style/style"),f=t("../style/evaluation_parameters"),d=t("../render/painter"),y=t("../geo/transform"),m=t("./hash"),g=t("./bind_handlers"),v=t("./camera"),_=t("../geo/lng_lat"),x=t("../geo/lng_lat_bounds"),b=t("@mapbox/point-geometry"),w=t("./control/attribution_control"),k=t("./control/logo_control"),A=t("@mapbox/mapbox-gl-supported"),T=t("../util/image").RGBAImage;t("./events");var M={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},S=function(t){function e(e){if(null!=(e=i.extend({},M,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var r=new y(e.minZoom,e.maxZoom,e.renderWorldCopies);t.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming;var n=e.transformRequest;if(this._transformRequest=n?function(t,e){return n(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var o=a.document.getElementById(e.container);if(!o)throw new Error("Container '"+e.container+"' not found.");this._container=o}else{if(!(e.container instanceof u))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}e.maxBounds&&this.setMaxBounds(e.maxBounds),i.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==a&&(a.addEventListener("online",this._onWindowOnline,!1),a.addEventListener("resize",this._onWindowResize,!1)),g(this,e),this._hash=e.hash&&(new m).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new w),this.addControl(new k,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet)}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={showTileBoundaries:{},showCollisionBoxes:{},showOverdrawInspector:{},repaint:{},vertices:{}};return e.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var r=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(r,n.firstChild):n.appendChild(r),this},e.prototype.removeControl=function(t){return t.onRemove(this),this},e.prototype.resize=function(){var t=this._containerDimensions(),e=t[0],r=t[1];return this._resizeCanvas(e,r),this.transform.resize(e,r),this.painter.resize(e,r),this.fire("movestart").fire("move").fire("resize").fire("moveend")},e.prototype.getBounds=function(){var t=new x(this.transform.pointLocation(new b(0,this.transform.height)),this.transform.pointLocation(new b(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(t.extend(this.transform.pointLocation(new b(this.transform.size.x,0))),t.extend(this.transform.pointLocation(new b(0,this.transform.size.y)))),t},e.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new x([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},e.prototype.setMaxBounds=function(t){if(t){var e=x.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update()}else null!==t&&void 0!==t||(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},e.prototype.setMinZoom=function(t){if((t=null===t||void 0===t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},e.prototype.getMaxZoom=function(){return this.transform.maxZoom},e.prototype.project=function(t){return this.transform.locationPoint(_.convert(t))},e.prototype.unproject=function(t){return this.transform.pointLocation(b.convert(t))},e.prototype.on=function(e,r,n){var o=this;if(void 0===n)return t.prototype.on.call(this,e,r);var a=function(){if("mouseenter"===e||"mouseover"===e){var t=!1;return{layer:r,listener:n,delegates:{mousemove:function(a){var s=o.getLayer(r)?o.queryRenderedFeatures(a.point,{layers:[r]}):[];s.length?t||(t=!0,n.call(o,i.extend({features:s},a,{type:e}))):t=!1},mouseout:function(){t=!1}}}}if("mouseleave"===e||"mouseout"===e){var a=!1;return{layer:r,listener:n,delegates:{mousemove:function(t){(o.getLayer(r)?o.queryRenderedFeatures(t.point,{layers:[r]}):[]).length?a=!0:a&&(a=!1,n.call(o,i.extend({},t,{type:e})))},mouseout:function(t){a&&(a=!1,n.call(o,i.extend({},t,{type:e})))}}}}var s;return{layer:r,listener:n,delegates:(s={},s[e]=function(t){var e=o.getLayer(r)?o.queryRenderedFeatures(t.point,{layers:[r]}):[];e.length&&n.call(o,i.extend({features:e},t))},s)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(a),a.delegates)o.on(s,a.delegates[s]);return this},e.prototype.off=function(e,r,n){if(void 0===n)return t.prototype.off.call(this,e,r);if(this._delegatedListeners&&this._delegatedListeners[e])for(var i=this._delegatedListeners[e],o=0;othis._map.transform.height-i?["bottom"]:[],t.xthis._map.transform.width-n/2&&e.push("right"),e=0===e.length?"bottom":e.join("-")}var a=t.add(r[e]).round(),l={top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},c=this._container.classList;for(var p in l)c.remove("mapboxgl-popup-anchor-"+p);c.add("mapboxgl-popup-anchor-"+e),o.setTransform(this._container,l[e]+" translate("+a.x+"px,"+a.y+"px)")}},e.prototype._onClickClose=function(){this.remove()},e}(i);e.exports=p},{"../geo/lng_lat":62,"../util/dom":259,"../util/evented":260,"../util/smart_wrap":270,"../util/util":275,"../util/window":254,"@mapbox/point-geometry":4}],250:[function(t,e,r){var n=t("./util"),i=t("./web_worker_transfer"),o=i.serialize,a=i.deserialize,s=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,n.bindAll(["receive"],this),this.target.addEventListener("message",this.receive,!1)};s.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var a=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:o(e,a)},a)},s.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var s=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"",id:String(i),error:t?String(t):null,data:o(e,n)},n)};if(""===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(new Error(n.error)):e&&e(null,a(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,a(n.data),s);else if(void 0!==n.id&&this.parent.getWorkerSource){var l=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,l[0])[l[1]](a(n.data),s)}else this.parent[n.type](a(n.data))}},s.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1)},e.exports=s},{"./util":275,"./web_worker_transfer":278}],251:[function(t,e,r){function n(t){var e=new o.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}function i(t){var e=o.document.createElement("a");return e.href=t,e.protocol===o.document.location.protocol&&e.host===o.document.location.host}var o=t("./window"),a={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};r.ResourceType=a,"function"==typeof Object.freeze&&Object.freeze(a);var s=function(t){function e(e,r){t.call(this,e),this.status=r}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);r.getJSON=function(t,e){var r=n(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var t;try{t=JSON.parse(r.response)}catch(t){return e(t)}e(null,t)}else e(new s(r.statusText,r.status))},r.send(),r},r.getArrayBuffer=function(t,e){var r=n(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){var t=r.response;if(0===t.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:t,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new s(r.statusText,r.status))},r.send(),r};r.getImage=function(t,e){return r.getArrayBuffer(t,function(t,r){if(t)e(t);else if(r){var n=new o.Image,i=o.URL||o.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src)};var a=new o.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(a):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII="}})},r.getVideo=function(t,e){var r=o.document.createElement("video");r.onloadstart=function(){e(null,r)};for(var n=0;n1)for(var p=0;p0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},a.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this},e.exports=a},{"./util":275}],261:[function(t,e,r){function n(t,e){return e.max-t.max}function i(t,e,r,n){this.p=new a(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;it.y!=p.y>t.y&&t.x<(p.x-c.x)*(t.y-c.y)/(p.y-c.y)+c.x&&(r=!r),n=Math.min(n,s(t,c,p))}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2}var o=t("tinyqueue"),a=t("@mapbox/point-geometry"),s=t("./intersection_tests").distToSegmentSquared;e.exports=function(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var s=1/0,l=1/0,u=-1/0,c=-1/0,p=t[0],h=0;hu)&&(u=f.x),(!h||f.y>c)&&(c=f.y)}var d=u-s,y=c-l,m=Math.min(d,y),g=m/2,v=new o(null,n);if(0===m)return new a(s,l);for(var _=s;_b.d||!b.d)&&(b=k,r&&console.log("found best %d after %d probes",Math.round(1e4*k.d)/1e4,w)),k.max-b.d<=e||(g=k.h/2,v.push(new i(k.p.x-g,k.p.y-g,g,t)),v.push(new i(k.p.x+g,k.p.y-g,g,t)),v.push(new i(k.p.x-g,k.p.y+g,g,t)),v.push(new i(k.p.x+g,k.p.y+g,g,t)),w+=4)}return r&&(console.log("num probes: "+w),console.log("best distance: "+b.d)),b.p}},{"./intersection_tests":264,"@mapbox/point-geometry":4,tinyqueue:33}],262:[function(t,e,r){var n,i=t("./worker_pool");e.exports=function(){return n||(n=new i),n}},{"./worker_pool":279}],263:[function(t,e,r){function n(t,e,r,n){var i=e.width,o=e.height;if(n){if(n.length!==i*o*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*o*r);return t.width=i,t.height=o,t.data=n,t}function i(t,e,r){var i=e.width,a=e.height;if(i!==t.width||a!==t.height){var s=n({},{width:i,height:a},r);o(t,s,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,i),height:Math.min(t.height,a)},r),t.width=i,t.height=a,t.data=s.data}}function o(t,e,r,n,i,o){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var a=t.data,s=e.data,l=0;l1){if(i(t,e))return!0;for(var n=0;n1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function l(t,e){for(var r,n,i,o=!1,a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(o=!o);return o}function u(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-o.x)*(e.y-o.y)/(a.y-o.y)+o.x&&(r=!r)}return r}var c=t("./util").isCounterClockwise;e.exports={multiPolygonIntersectsBufferedMultiPoint:function(t,e,r){for(var n=0;n=3)for(var l=0;l=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}}},{}],266:[function(t,e,r){var n=function(t,e){this.max=t,this.onRemove=e,this.reset()};n.prototype.reset=function(){var t=this;for(var e in t.data)t.onRemove(t.data[e]);return this.data={},this.order=[],this},n.prototype.add=function(t,e){if(this.has(t))this.order.splice(this.order.indexOf(t),1),this.data[t]=e,this.order.push(t);else if(this.data[t]=e,this.order.push(t),this.order.length>this.max){var r=this.getAndRemove(this.order[0]);r&&this.onRemove(r)}return this},n.prototype.has=function(t){return t in this.data},n.prototype.keys=function(){return this.order},n.prototype.getAndRemove=function(t){if(!this.has(t))return null;var e=this.data[t];return delete this.data[t],this.order.splice(this.order.indexOf(t),1),e},n.prototype.get=function(t){return this.has(t)?this.data[t]:null},n.prototype.remove=function(t){if(!this.has(t))return this;var e=this.data[t];return delete this.data[t],this.onRemove(e),this.order.splice(this.order.indexOf(t),1),this},n.prototype.setMaxSize=function(t){var e=this;for(this.max=t;this.order.length>this.max;){var r=e.getAndRemove(e.order[0]);r&&e.onRemove(r)}return this},e.exports=n},{}],267:[function(t,e,r){function n(t,e){var r=o(s.API_URL);if(t.protocol=r.protocol,t.authority=r.authority,"/"!==r.path&&(t.path=""+r.path+t.path),!s.REQUIRE_ACCESS_TOKEN)return a(t);if(!(e=e||s.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+u);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+u);return t.params.push("access_token="+e),a(t)}function i(t){return 0===t.indexOf("mapbox:")}function o(t){var e=t.match(p);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function a(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var s=t("./config"),l=t("./browser"),u="See https://www.mapbox.com/api-documentation/#access-tokens";r.isMapboxURL=i,r.normalizeStyleURL=function(t,e){if(!i(t))return t;var r=o(t);return r.path="/styles/v1"+r.path,n(r,e)},r.normalizeGlyphsURL=function(t,e){if(!i(t))return t;var r=o(t);return r.path="/fonts/v1"+r.path,n(r,e)},r.normalizeSourceURL=function(t,e){if(!i(t))return t;var r=o(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),n(r,e)},r.normalizeSpriteURL=function(t,e,r,s){var l=o(t);return i(t)?(l.path="/styles/v1"+l.path+"/sprite"+e+r,n(l,s)):(l.path+=""+e+r,a(l))};var c=/(\.(png|jpg)\d*)(?=$)/;r.normalizeTileURL=function(t,e,r){if(!e||!i(e))return t;var n=o(t),u=l.devicePixelRatio>=2||512===r?"@2x":"",p=l.supportsWebp?".webp":"$1";return n.path=n.path.replace(c,""+u+p),function(t){for(var e=0;e=65097&&t<=65103)||n["CJK Compatibility Ideographs"](t)||n["CJK Compatibility"](t)||n["CJK Radicals Supplement"](t)||n["CJK Strokes"](t)||!(!n["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||n["CJK Unified Ideographs Extension A"](t)||n["CJK Unified Ideographs"](t)||n["Enclosed CJK Letters and Months"](t)||n["Hangul Compatibility Jamo"](t)||n["Hangul Jamo Extended-A"](t)||n["Hangul Jamo Extended-B"](t)||n["Hangul Jamo"](t)||n["Hangul Syllables"](t)||n.Hiragana(t)||n["Ideographic Description Characters"](t)||n.Kanbun(t)||n["Kangxi Radicals"](t)||n["Katakana Phonetic Extensions"](t)||n.Katakana(t)&&12540!==t||!(!n["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!n["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||n["Unified Canadian Aboriginal Syllabics"](t)||n["Unified Canadian Aboriginal Syllabics Extended"](t)||n["Vertical Forms"](t)||n["Yijing Hexagram Symbols"](t)||n["Yi Syllables"](t)||n["Yi Radicals"](t)))},r.charHasNeutralVerticalOrientation=function(t){return!!(n["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||n["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||n["Letterlike Symbols"](t)||n["Number Forms"](t)||n["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||n["Control Pictures"](t)&&9251!==t||n["Optical Character Recognition"](t)||n["Enclosed Alphanumerics"](t)||n["Geometric Shapes"](t)||n["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||n["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||n["CJK Symbols and Punctuation"](t)||n.Katakana(t)||n["Private Use Area"](t)||n["CJK Compatibility Forms"](t)||n["Small Form Variants"](t)||n["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)},r.charHasRotatedVerticalOrientation=function(t){return!(r.charHasUprightVerticalOrientation(t)||r.charHasNeutralVerticalOrientation(t))}},{"./is_char_in_unicode_block":265}],270:[function(t,e,r){var n=t("../geo/lng_lat");e.exports=function(t,e,r){if(t=new n(t.lng,t.lat),e){var i=new n(t.lng-360,t.lat),o=new n(t.lng+360,t.lat),a=r.locationPoint(t).distSqr(e);r.locationPoint(i).distSqr(e)180;){var s=r.locationPoint(t);if(s.x>=0&&s.y>=0&&s.x<=r.width&&s.y<=r.height)break;t.lng>r.center.lng?t.lng-=360:t.lng+=360}return t}},{"../geo/lng_lat":62}],271:[function(t,e,r){function n(t,e){return Math.ceil(t/e)*e}var i={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},o=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0)};o.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},o.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},o.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())},o.prototype.clear=function(){this.length=0},o.prototype.resize=function(t){this.reserve(t),this.length=t},o.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}},o.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")},e.exports.StructArray=o,e.exports.Struct=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8},e.exports.viewTypes=i,e.exports.createLayout=function(t,e){void 0===e&&(e=1);var r=0,o=0;return{members:t.map(function(t){var a=function(t){return i[t].BYTES_PER_ELEMENT}(t.type),s=r=n(r,Math.max(e,a)),l=t.components||1;return o=Math.max(o,a),r+=a*l,{name:t.name,type:t.type,components:l,offset:s}}),size:n(r,Math.max(o,e)),alignment:e}}},{}],272:[function(t,e,r){e.exports=function(t,e){var r=!1,n=0,i=function(){n=0,r&&(t(),n=setTimeout(i,e),r=!1)};return function(){return r=!0,n||i(),n}}},{}],273:[function(t,e,r){function n(t,e){if(t.row>e.row){var r=t;t=e,e=r}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function i(t,e,r,n,i){var o=Math.max(r,Math.floor(e.y0)),a=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx0,p=e.dx<0,h=o;hc.dy&&(l=u,u=c,c=l),u.dy>p.dy&&(l=u,u=p,p=l),c.dy>p.dy&&(l=c,c=p,p=l),u.dy&&i(p,u,o,a,s),c.dy&&i(p,c,o,a,s)}t("../geo/coordinate");var a=t("../source/tile_id").OverscaledTileID;e.exports=function(t,e,r,n){function i(e,i,o){var u,c,p;if(o>=0&&o<=s)for(u=e;u=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)},r.bezier=function(t,e,r,i){var o=new n(t,e,r,i);return function(t){return o.solve(t)}},r.ease=r.bezier(.25,.1,.25,1),r.clamp=function(t,e,r){return Math.min(r,Math.max(e,t))},r.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},r.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),o=null;t.forEach(function(t,a){e(t,function(t,e){t&&(o=t),i[a]=e,0==--n&&r(o,i)})})},r.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},r.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},r.extend=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];for(var i=0,o=r;i=0)return!0;return!1};var a={};r.warnOnce=function(t){a[t]||("undefined"!=typeof console&&console.warn(t),a[t]=!0)},r.isCounterClockwise=function(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)},r.calculateSignedArea=function(t){for(var e=0,r=0,n=t.length,i=n-1,o=void 0,a=void 0;r0||Math.abs(e.y-n.y)>0)&&Math.abs(r.calculateSignedArea(t))>.01},r.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},r.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var o=n||i;return e[r]=!o||o.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r}return e}},{"../geo/coordinate":61,"../style-spec/util/deep_equal":155,"@mapbox/point-geometry":4,"@mapbox/unitbezier":7}],276:[function(t,e,r){var n=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id)},i={geometry:{}};i.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},i.geometry.set=function(t){this._geometry=t},n.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(n.prototype,i),e.exports=n},{}],277:[function(t,e,r){var n=t("./script_detection");e.exports=function(t){for(var r="",i=0;i":"\ufe40","?":"\ufe16","@":"\uff20","[":"\ufe47","\\":"\uff3c","]":"\ufe48","^":"\uff3e",_:"\ufe33","`":"\uff40","{":"\ufe37","|":"\u2015","}":"\ufe38","~":"\uff5e","\xa2":"\uffe0","\xa3":"\uffe1","\xa5":"\uffe5","\xa6":"\uffe4","\xac":"\uffe2","\xaf":"\uffe3","\u2013":"\ufe32","\u2014":"\ufe31","\u2018":"\ufe43","\u2019":"\ufe44","\u201c":"\ufe41","\u201d":"\ufe42","\u2026":"\ufe19","\u2027":"\u30fb","\u20a9":"\uffe6","\u3001":"\ufe11","\u3002":"\ufe12","\u3008":"\ufe3f","\u3009":"\ufe40","\u300a":"\ufe3d","\u300b":"\ufe3e","\u300c":"\ufe41","\u300d":"\ufe42","\u300e":"\ufe43","\u300f":"\ufe44","\u3010":"\ufe3b","\u3011":"\ufe3c","\u3014":"\ufe39","\u3015":"\ufe3a","\u3016":"\ufe17","\u3017":"\ufe18","\uff01":"\ufe15","\uff08":"\ufe35","\uff09":"\ufe36","\uff0c":"\ufe10","\uff0d":"\ufe32","\uff0e":"\u30fb","\uff1a":"\ufe13","\uff1b":"\ufe14","\uff1c":"\ufe3f","\uff1e":"\ufe40","\uff1f":"\ufe16","\uff3b":"\ufe47","\uff3d":"\ufe48","\uff3f":"\ufe33","\uff5b":"\ufe37","\uff5c":"\u2015","\uff5d":"\ufe38","\uff5f":"\ufe35","\uff60":"\ufe36","\uff61":"\ufe12","\uff62":"\ufe41","\uff63":"\ufe42"}},{"./script_detection":269}],278:[function(t,e,r){function n(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),y[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]}}var i=t("grid-index"),o=t("../style-spec/util/color"),a=t("../style-spec/expression"),s=a.StylePropertyFunction,l=a.StyleExpression,u=a.StyleExpressionWithErrorHandling,c=a.ZoomDependentExpression,p=a.ZoomConstantExpression,h=t("../style-spec/expression/compound_expression").CompoundExpression,f=t("../style-spec/expression/definitions"),d=t("./window").ImageData,y={};for(var m in n("Object",Object),i.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},i.deserialize=function(t){return new i(t)},n("Grid",i),n("Color",o),n("StylePropertyFunction",s),n("StyleExpression",l,{omit:["_evaluator"]}),n("StyleExpressionWithErrorHandling",u,{omit:["_evaluator"]}),n("ZoomDependentExpression",c),n("ZoomConstantExpression",p),n("CompoundExpression",h,{omit:["_evaluate"]}),f)f[m]._classRegistryKey||n("Expression_"+m,f[m]);e.exports={register:n,serialize:function t(e,r){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp)return e;if(e instanceof ArrayBuffer)return r&&r.push(e),e;if(ArrayBuffer.isView(e)){var n=e;return r&&r.push(n.buffer),n}if(e instanceof d)return r&&r.push(e.data.buffer),e;if(Array.isArray(e)){for(var i=[],o=0,a=e;o=0)){var h=e[p];c[p]=y[u].shallow.indexOf(p)>=0?h:t(h,r)}return{name:u,properties:c}}throw new Error("can't serialize object of type "+typeof e)},deserialize:function t(e){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof d)return e;if(Array.isArray(e))return e.map(function(e){return t(e)});if("object"==typeof e){var r=e,n=r.name,i=r.properties;if(!n)throw new Error("can't deserialize object of anonymous class");var o=y[n].klass;if(!o)throw new Error("can't deserialize unregistered class "+n);if(o.deserialize)return o.deserialize(i._serialized);for(var a=Object.create(o.prototype),s=0,l=Object.keys(i);s=0?i[u]:t(i[u])}return a}throw new Error("can't deserialize object of type "+typeof e)}}},{"../style-spec/expression":139,"../style-spec/expression/compound_expression":123,"../style-spec/expression/definitions":131,"../style-spec/util/color":153,"./window":254,"grid-index":24}],279:[function(t,e,r){var n=t("./web_worker"),i=function(){this.active={}};i.prototype.acquire=function(e){if(!this.workers){var r=t("../").workerCount;for(this.workers=[];this.workers.length0}function cf(t){var e={},r={};switch(t.type){case"circle":re.extendFlat(r,{"circle-radius":t.circle.radius,"circle-color":t.color,"circle-opacity":t.opacity});break;case"line":re.extendFlat(r,{"line-width":t.line.width,"line-color":t.color,"line-opacity":t.opacity});break;case"fill":re.extendFlat(r,{"fill-color":t.color,"fill-outline-color":t.fill.outlinecolor,"fill-opacity":t.opacity});break;case"symbol":var n=t.symbol,i=af(n.textposition,n.iconsize);re.extendFlat(e,{"icon-image":n.icon+"-15","icon-size":n.iconsize/10,"text-field":n.text,"text-size":n.textfont.size,"text-anchor":i.anchor,"text-offset":i.offset}),re.extendFlat(r,{"icon-color":t.color,"text-color":n.textfont.color,"text-opacity":t.opacity})}return{layout:e,paint:r}}lf.update=function(t){this.visible?this.needsNewSource(t)?(this.updateLayer(t),this.updateSource(t)):this.needsNewLayer(t)?this.updateLayer(t):this.updateStyle(t):(this.updateSource(t),this.updateLayer(t)),this.visible=uf(t)},lf.needsNewSource=function(t){return this.sourceType!==t.sourcetype||this.source!==t.source||this.layerType!==t.type},lf.needsNewLayer=function(t){return this.layerType!==t.type||this.below!==t.below},lf.updateSource=function(t){var e=this.map;if(e.getSource(this.idSource)&&e.removeSource(this.idSource),this.sourceType=t.sourcetype,this.source=t.source,uf(t)){var r=function(t){var e,r=t.sourcetype,n=t.source,i={type:r};"geojson"===r?e="data":"vector"===r&&(e="string"==typeof n?"url":"tiles");return i[e]=n,i}(t);e.addSource(this.idSource,r)}},lf.updateLayer=function(t){var e=this.map,r=cf(t);e.getLayer(this.idLayer)&&e.removeLayer(this.idLayer),this.layerType=t.type,uf(t)&&e.addLayer({id:this.idLayer,source:this.idSource,"source-layer":t.sourcelayer||"",type:t.type,layout:r.layout,paint:r.paint},t.below)},lf.updateStyle=function(t){if(uf(t)){var e=cf(t);this.mapbox.setOptions(this.idLayer,"setLayoutProperty",e.layout),this.mapbox.setOptions(this.idLayer,"setPaintProperty",e.paint)}},lf.dispose=function(){var t=this.map;t.removeLayer(this.idLayer),t.removeSource(this.idSource)};var pf=function(t,e,r){var n=new sf(t,e);return n.update(r),n},hf=tl;function ff(t){this.id=t.id,this.gd=t.gd,this.container=t.container,this.isStatic=t.staticPlot;var e=t.fullLayout;this.uid=e._uid+"-"+this.id,this.opts=e[this.id],this.div=null,this.xaxis=null,this.yaxis=null,this.createFramework(e),this.map=null,this.accessToken=null,this.styleObj=null,this.traceHash={},this.layerList=[]}var df=ff.prototype,yf=function(t){return new ff(t)};function mf(t){var e=rf.style.values,r=rf.style.dflt,n={};return re.isPlainObject(t)?(n.id=t.id,n.style=t):"string"==typeof t?(n.id=t,n.style=-1!==e.indexOf(t)?gf(t):t):(n.id=r,n.style=gf(r)),n.transition={duration:0,delay:0},n}function gf(t){return Jh.styleUrlPrefix+t+"-"+Jh.styleUrlSuffix}function vf(t){return[t.lon,t.lat]}df.plot=function(t,e,r){var n,i=this,o=i.opts=e[this.id];i.map&&o.accesstoken!==i.accessToken&&(i.map.remove(),i.map=null,i.styleObj=null,i.traceHash=[],i.layerList={}),n=i.map?new Promise(function(r,n){i.updateMap(t,e,r,n)}):new Promise(function(r,n){i.createMap(t,e,r,n)}),r.push(n)},df.createMap=function(t,e,r,n){var i=this,o=i.gd,a=i.opts,s=i.styleObj=mf(a.style);i.accessToken=a.accesstoken;var l=i.map=new Yh.Map({container:i.div,style:s.style,center:vf(a.center),zoom:a.zoom,bearing:a.bearing,pitch:a.pitch,interactive:!i.isStatic,preserveDrawingBuffer:i.isStatic,doubleClickZoom:!1,boxZoom:!1}),u=Jh.controlContainerClassName,c=i.div.getElementsByClassName(u)[0];function p(){Ko.loneUnhover(e._toppaper)}i.div.removeChild(c),l._canvas.style.left="0px",l._canvas.style.top="0px",i.rejectOnError(n),l.once("load",function(){i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)}),i.isStatic||(l.on("moveend",function(t){if(i.map){var e=i.getView();if(a._input.center=a.center=e.center,a._input.zoom=a.zoom=e.zoom,a._input.bearing=a.bearing=e.bearing,a._input.pitch=a.pitch=e.pitch,t.originalEvent){var r={};r[i.id]=re.extendFlat({},e),o.emit("plotly_relayout",r)}}}),l.on("mousemove",function(t){var e=i.div.getBoundingClientRect();t.clientX=t.point.x+e.left,t.clientY=t.point.y+e.top,t.target.getBoundingClientRect=function(){return e},i.xaxis.p2c=function(){return t.lngLat.lng},i.yaxis.p2c=function(){return t.lngLat.lat},Ko.hover(o,t,i.id)}),l.on("click",function(t){Ko.click(o,t.originalEvent)}),l.on("dragstart",p),l.on("zoomstart",p),l.on("dblclick",function(){var t=i.viewInitial;l.setCenter(vf(t.center)),l.setZoom(t.zoom),l.setBearing(t.bearing),l.setPitch(t.pitch);var e=i.getView();a._input.center=a.center=e.center,a._input.zoom=a.zoom=e.zoom,a._input.bearing=a.bearing=e.bearing,a._input.pitch=a.pitch=e.pitch,o.emit("plotly_doubleclick",null)}),i.clearSelect=function(){o._fullLayout._zoomlayer.selectAll(".select-outline").remove()})},df.updateMap=function(t,e,r,n){var i=this,o=i.map;i.rejectOnError(n);var a=mf(i.opts.style);i.styleObj.id!==a.id?(i.styleObj=a,o.setStyle(a.style),o.once("styledata",function(){i.traceHash={},i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)})):(i.updateData(t),i.updateLayout(e),i.resolveOnRender(r))},df.updateData=function(t){var e,r,n,i,o=this.traceHash;for(n=0;n0&&(r.push(n),n=[])}return n.length>0&&r.push(n),r},Bf.makeLine=function(t){return 1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t}},Bf.makePolygon=function(t){if(1===t.length)return{type:"Polygon",coordinates:t};for(var e=new Array(t.length),r=0;r=0?Math.floor((e+180)/360):Math.ceil((e-180)/360)),u=e-l;if(Ko.getClosest(n,function(t){var e=t.lonlat;if(e[0]===Rf)return 1/0;var n=re.wrap180(e[0]),i=e[1],l=s.project([n,i]),c=l.x-o.c2p([u,i]),p=l.y-a.c2p([n,r]),h=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(c*c+p*p)-h,1-3/h)},t),!1!==t.index){var c=n[t.index],p=c.lonlat,h=[re.wrap180(p[0])+l,p[1]],f=o.c2p(h),d=a.c2p(h),y=c.mrc||1;return t.x0=f-y,t.x1=f+y,t.y0=d-y,t.y1=d+y,t.color=Ph(i,c),t.extraText=function(t,e,r){var n=(e.hi||t.hoverinfo).split("+"),i=-1!==n.indexOf("all"),o=-1!==n.indexOf("lon"),a=-1!==n.indexOf("lat"),s=e.lonlat,l=[];function u(t){return t+"\xb0"}return i||o&&a?l.push("("+u(s[0])+", "+u(s[1])+")"):o?l.push(r.lon+u(s[0])):a&&l.push(r.lat+u(s[1])),(i||-1!==n.indexOf("text"))&&Lh(e,t,l),l.join("
")}(i,c,n[0].t.labels),[t]}},Xf.eventData=function(t,e){return t.lon=e.lon,t.lat=e.lat,t},Xf.selectPoints=function(t,e){var r,n=t.cd,i=t.xaxis,o=t.yaxis,a=[],s=n[0].trace;if(!cn.hasMarkers(s))return[];if(!1===e)for(r=0;r * but significantly simplified and sped up by ignoring number and string constructors @@ -9662,7 +9812,7 @@ function allBlankCharCodes(str){ return true; } -var _$fastIsnumeric_139 = function(n) { +var _$fastIsnumeric_196 = function(n) { var type = typeof n; if(type === 'string') { var original = n; @@ -9675,7 +9825,7 @@ var _$fastIsnumeric_139 = function(n) { return n - n < 1; }; -var _$angles_522 = {}; +var _$angles_583 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -9688,20 +9838,20 @@ var _$angles_522 = {}; var PI = Math.PI; -_$angles_522.deg2rad = function(deg) { +_$angles_583.deg2rad = function(deg) { return deg / 180 * PI; }; -_$angles_522.rad2deg = function(rad) { +_$angles_583.rad2deg = function(rad) { return rad / PI * 180; }; -_$angles_522.wrap360 = function(deg) { +_$angles_583.wrap360 = function(deg) { var out = deg % 360; return out < 0 ? out + 360 : out; }; -_$angles_522.wrap180 = function(deg) { +_$angles_583.wrap180 = function(deg) { if(Math.abs(deg) > 180) deg -= Math.round(deg / 360) * 360; return deg; }; @@ -9717,9 +9867,9 @@ _$angles_522.wrap180 = function(deg) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -var BADNUM = _$numerical_517.BADNUM; +var BADNUM = _$numerical_578.BADNUM; // precompile for speed var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; @@ -9728,17 +9878,17 @@ var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; * cleanNumber: remove common leading and trailing cruft * Always returns either a number or BADNUM. */ -var _$cleanNumber_523 = function cleanNumber(v) { +var _$cleanNumber_584 = function cleanNumber(v) { if(typeof v === 'string') { v = v.replace(JUNK, ''); } - if(_$fastIsnumeric_139(v)) return Number(v); + if(_$fastIsnumeric_196(v)) return Number(v); return BADNUM; }; -var _$tinycolor_352 = { exports: {} }; +var _$tinycolor_414 = { exports: {} }; // TinyColor v1.4.1 // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License @@ -10921,8 +11071,8 @@ function validateWCAG2Parms(parms) { } // Node: Export function -if ("object" !== "undefined" && _$tinycolor_352.exports) { - _$tinycolor_352.exports = tinycolor; +if ("object" !== "undefined" && _$tinycolor_414.exports) { + _$tinycolor_414.exports = tinycolor; } // AMD/requirejs: Define the module else if (typeof define === 'function' && define.amd) { @@ -10935,7 +11085,7 @@ else { })(Math); -_$tinycolor_352 = _$tinycolor_352.exports +_$tinycolor_414 = _$tinycolor_414.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -10947,7 +11097,7 @@ _$tinycolor_352 = _$tinycolor_352.exports 'use strict'; -var _$scales_430 = { +var _$scales_492 = { 'Greys': [ [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)'] ], @@ -11088,10 +11238,10 @@ var _$scales_430 = { 'use strict'; -/* removed: var _$scales_430 = require('./scales'); */; +/* removed: var _$scales_492 = require('./scales'); */; -var _$default_scale_420 = _$scales_430.RdBu; +var _$default_scale_482 = _$scales_492.RdBu; /** * Copyright 2012-2018, Plotly, Inc. @@ -11104,10 +11254,10 @@ var _$default_scale_420 = _$scales_430.RdBu; 'use strict'; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -var _$isValidScaleArray_428 = function isValidScaleArray(scl) { +var _$isValidScaleArray_490 = function isValidScaleArray(scl) { var highestVal = 0; if(!Array.isArray(scl) || scl.length < 2) return false; @@ -11119,7 +11269,7 @@ var _$isValidScaleArray_428 = function isValidScaleArray(scl) { for(var i = 0; i < scl.length; i++) { var si = scl[i]; - if(si.length !== 2 || +si[0] < highestVal || !_$tinycolor_352(si[1]).isValid()) { + if(si.length !== 2 || +si[0] < highestVal || !_$tinycolor_414(si[1]).isValid()) { return false; } @@ -11140,18 +11290,18 @@ var _$isValidScaleArray_428 = function isValidScaleArray(scl) { 'use strict'; -/* removed: var _$scales_430 = require('./scales'); */; -/* removed: var _$default_scale_420 = require('./default_scale'); */; -/* removed: var _$isValidScaleArray_428 = require('./is_valid_scale_array'); */; +/* removed: var _$scales_492 = require('./scales'); */; +/* removed: var _$default_scale_482 = require('./default_scale'); */; +/* removed: var _$isValidScaleArray_490 = require('./is_valid_scale_array'); */; -var _$getScale_424 = function getScale(scl, dflt) { - if(!dflt) dflt = _$default_scale_420; +var _$getScale_486 = function getScale(scl, dflt) { + if(!dflt) dflt = _$default_scale_482; if(!scl) return dflt; function parseScale() { try { - scl = _$scales_430[scl] || JSON.parse(scl); + scl = _$scales_492[scl] || JSON.parse(scl); } catch(e) { scl = dflt; @@ -11164,7 +11314,7 @@ var _$getScale_424 = function getScale(scl, dflt) { if(typeof scl === 'string') parseScale(); } - if(!_$isValidScaleArray_428(scl)) return dflt; + if(!_$isValidScaleArray_490(scl)) return dflt; return scl; }; @@ -11179,7 +11329,7 @@ var _$getScale_424 = function getScale(scl, dflt) { 'use strict'; -var _$interactions_516 = { +var _$interactions_577 = { /** * Timing information for interactive elements */ @@ -11194,7 +11344,7 @@ var _$interactions_516 = { DESELECTDIM: 0.2 }; -var _$is_array_540 = {}; +var _$is_array_602 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11215,12 +11365,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_540.isTypedArray = function(a) { +_$is_array_602.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_540.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_540.isTypedArray(a); +_$is_array_602.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_602.isTypedArray(a); }; /** @@ -11235,7 +11385,7 @@ _$is_array_540.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_541 = function isPlainObject(obj) { +var _$isPlainObject_603 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11251,7 +11401,7 @@ var _$isPlainObject_541 = function isPlainObject(obj) { ); }; -var _$extend_528 = {}; +var _$extend_590 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11263,7 +11413,7 @@ var _$extend_528 = {}; 'use strict'; -/* removed: var _$isPlainObject_541 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_603 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11280,19 +11430,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_528.extendFlat = function() { +_$extend_590.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_528.extendDeep = function() { +_$extend_590.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_528.extendDeepAll = function() { +_$extend_590.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_528.extendDeepNoArrays = function() { +_$extend_590.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11345,12 +11495,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_541(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_603(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_541(src) ? src : {}; + clone = src && _$isPlainObject_603(src) ? src : {}; } // never move original objects, clone them @@ -11385,7 +11535,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_574 = { +var _$plot_config_637 = { // no interactivity, for export or image generation staticPlot: false, @@ -11553,7 +11703,7 @@ var _$plot_config_574 = { locales: {} }; -var _$loggers_544 = {}; +var _$loggers_606 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11566,9 +11716,9 @@ var _$loggers_544 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_574 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_637 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_544 = {}; +var loggers = _$loggers_606 = {}; /** * ------------------------------------------ @@ -11577,7 +11727,7 @@ var loggers = _$loggers_544 = {}; */ loggers.log = function() { - if(_$plot_config_574.logging > 1) { + if(_$plot_config_637.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11589,7 +11739,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_574.logging > 0) { + if(_$plot_config_637.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11601,7 +11751,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_574.logging > 0) { + if(_$plot_config_637.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11640,7 +11790,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_548 = function noop() {}; +var _$noop_610 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11665,7 +11815,7 @@ var _$noop_548 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_552 = function pushUnique(array, item) { +var _$pushUnique_615 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11706,7 +11856,7 @@ var _$pushUnique_552 = function pushUnique(array, item) { * * @return {object} attributes object containing {family, size, color} as specified */ -var _$font_attributes_611 = function(opts) { +var _$font_attributes_673 = function(opts) { var editType = opts.editType; var colorEditType = opts.colorEditType; if(colorEditType === undefined) colorEditType = editType; @@ -11766,9 +11916,9 @@ var _$font_attributes_611 = function(opts) { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; -var _$attributes_445 = { +var _$attributes_507 = { hoverlabel: { bgcolor: { valType: 'color', @@ -11788,7 +11938,7 @@ var _$attributes_445 = { 'Sets the border color of the hover labels for this trace.' ].join(' ') }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ arrayOk: true, editType: 'none', description: 'Sets the font used in hover labels.' @@ -11822,9 +11972,9 @@ var _$attributes_445 = { 'use strict'; -/* removed: var _$attributes_445 = require('../components/fx/attributes'); */; +/* removed: var _$attributes_507 = require('../components/fx/attributes'); */; -var _$attributes_581 = { +var _$attributes_644 = { type: { valType: 'enumerated', role: 'info', @@ -11942,7 +12092,7 @@ var _$attributes_581 = { 'But, if `none` is set, click and hover events are still fired.' ].join(' ') }, - hoverlabel: _$attributes_445.hoverlabel, + hoverlabel: _$attributes_507.hoverlabel, stream: { token: { valType: 'string', @@ -11973,7 +12123,7 @@ var _$attributes_581 = { } }; -var _$attributes_410 = {}; +var _$attributes_472 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11986,7 +12136,7 @@ var _$attributes_410 = {}; // IMPORTANT - default colors should be in hex for compatibility -_$attributes_410.defaults = [ +_$attributes_472.defaults = [ '#1f77b4', // muted blue '#ff7f0e', // safety orange '#2ca02c', // cooked asparagus green @@ -11999,19 +12149,19 @@ _$attributes_410.defaults = [ '#17becf' // blue-teal ]; -_$attributes_410.defaultLine = '#444'; +_$attributes_472.defaultLine = '#444'; -_$attributes_410.lightLine = '#eee'; +_$attributes_472.lightLine = '#eee'; -_$attributes_410.background = '#fff'; +_$attributes_472.background = '#fff'; -_$attributes_410.borderLine = '#BEC8D9'; +_$attributes_472.borderLine = '#BEC8D9'; // with axis.color and Color.interp we aren't using lightLine // itself anymore, instead interpolating between axis.color // and the background color using tinycolor.mix. lightFraction // gives back exactly lightLine if the other colors are defaults. -_$attributes_410.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); +_$attributes_472.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); /** * Copyright 2012-2018, Plotly, Inc. @@ -12023,10 +12173,10 @@ _$attributes_410.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); 'use strict'; -/* removed: var _$font_attributes_611 = require('./font_attributes'); */; -/* removed: var _$attributes_410 = require('../components/color/attributes'); */; +/* removed: var _$font_attributes_673 = require('./font_attributes'); */; +/* removed: var _$attributes_472 = require('../components/color/attributes'); */; -var globalFont = _$font_attributes_611({ +var globalFont = _$font_attributes_673({ editType: 'calc', description: [ 'Sets the global font.', @@ -12036,9 +12186,9 @@ var globalFont = _$font_attributes_611({ }); globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; globalFont.size.dflt = 12; -globalFont.color.dflt = _$attributes_410.defaultLine; +globalFont.color.dflt = _$attributes_472.defaultLine; -var _$layout_attributes_638 = { +var _$layout_attributes_700 = { font: globalFont, title: { valType: 'string', @@ -12048,7 +12198,7 @@ var _$layout_attributes_638 = { 'Sets the plot\'s title.' ].join(' ') }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ editType: 'layoutstyle', description: 'Sets the title font.' }), @@ -12144,7 +12294,7 @@ var _$layout_attributes_638 = { paper_bgcolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, editType: 'plot', description: 'Sets the color of paper where the graph is drawn.' }, @@ -12153,7 +12303,7 @@ var _$layout_attributes_638 = { // because it needs to know if there are (2D) axes or not valType: 'color', role: 'style', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, editType: 'layoutstyle', description: [ 'Sets the color of plotting area in-between x and y axes.' @@ -12192,7 +12342,7 @@ var _$layout_attributes_638 = { }, colorway: { valType: 'colorlist', - dflt: _$attributes_410.defaults, + dflt: _$attributes_472.defaults, role: 'style', editType: 'calc', description: 'Sets the default trace colors.' @@ -12213,7 +12363,7 @@ var _$layout_attributes_638 = { } }; -var _$registry_668 = {}; +var _$registry_731 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12224,29 +12374,29 @@ var _$registry_668 = {}; 'use strict'; -/* removed: var _$loggers_544 = require('./lib/loggers'); */; -/* removed: var _$noop_548 = require('./lib/noop'); */; -/* removed: var _$pushUnique_552 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_541 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_528 = require('./lib/extend'); */; +/* removed: var _$loggers_606 = require('./lib/loggers'); */; +/* removed: var _$noop_610 = require('./lib/noop'); */; +/* removed: var _$pushUnique_615 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_603 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_590 = require('./lib/extend'); */; -/* removed: var _$attributes_581 = require('./plots/attributes'); */; -/* removed: var _$layout_attributes_638 = require('./plots/layout_attributes'); */; +/* removed: var _$attributes_644 = require('./plots/attributes'); */; +/* removed: var _$layout_attributes_700 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_528.extendFlat; -var extendDeepAll = _$extend_528.extendDeepAll; +var extendFlat = _$extend_590.extendFlat; +var extendDeepAll = _$extend_590.extendDeepAll; -_$registry_668.modules = {}; -_$registry_668.allCategories = {}; -_$registry_668.allTypes = []; -_$registry_668.subplotsRegistry = {}; -_$registry_668.transformsRegistry = {}; -_$registry_668.componentsRegistry = {}; -_$registry_668.layoutArrayContainers = []; -_$registry_668.layoutArrayRegexes = []; -_$registry_668.traceLayoutAttributes = {}; -_$registry_668.localeRegistry = {}; -_$registry_668.apiMethodRegistry = {}; +_$registry_731.modules = {}; +_$registry_731.allCategories = {}; +_$registry_731.allTypes = []; +_$registry_731.subplotsRegistry = {}; +_$registry_731.transformsRegistry = {}; +_$registry_731.componentsRegistry = {}; +_$registry_731.layoutArrayContainers = []; +_$registry_731.layoutArrayRegexes = []; +_$registry_731.traceLayoutAttributes = {}; +_$registry_731.localeRegistry = {}; +_$registry_731.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12287,7 +12437,7 @@ _$registry_668.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_668.register = function register(_modules) { +_$registry_731.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12316,7 +12466,7 @@ _$registry_668.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_668.apiMethodRegistry[name] = newModule.fn; + _$registry_731.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12332,8 +12482,8 @@ _$registry_668.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_668.getModule = function(trace) { - var _module = _$registry_668.modules[getTraceType(trace)]; +_$registry_731.getModule = function(trace) { + var _module = _$registry_731.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12347,20 +12497,20 @@ _$registry_668.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_668.traceIs = function(traceType, category) { +_$registry_731.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_668.modules[traceType]; + var _module = _$registry_731.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_544.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_606.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_668.modules[_$attributes_581.type.dflt]; + _module = _$registry_731.modules[_$attributes_644.type.dflt]; } return !!_module.categories[category]; @@ -12377,7 +12527,7 @@ _$registry_668.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_668.getTransformIndices = function(data, type) { +_$registry_731.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12397,7 +12547,7 @@ _$registry_668.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_668.hasTransform = function(data, type) { +_$registry_731.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12417,11 +12567,11 @@ _$registry_668.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_668.getComponentMethod = function(name, method) { - var _module = _$registry_668.componentsRegistry[name]; +_$registry_731.getComponentMethod = function(name, method) { + var _module = _$registry_731.componentsRegistry[name]; - if(!_module) return _$noop_548; - return _module[method] || _$noop_548; + if(!_module) return _$noop_610; + return _module[method] || _$noop_610; }; /** @@ -12431,10 +12581,10 @@ _$registry_668.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_668.call = function() { +_$registry_731.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_668.apiMethodRegistry[name].apply(null, args); + return _$registry_731.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12442,33 +12592,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_668.modules[thisType]) { - _$loggers_544.log('Type ' + thisType + ' already registered'); + if(_$registry_731.modules[thisType]) { + _$loggers_606.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_668.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_731.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_668.allCategories[categoriesIn[i]] = true; + _$registry_731.allCategories[categoriesIn[i]] = true; } - _$registry_668.modules[thisType] = { + _$registry_731.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_668.modules[thisType].meta = meta; + _$registry_731.modules[thisType].meta = meta; } - _$registry_668.allTypes.push(thisType); + _$registry_731.allTypes.push(thisType); - for(var componentName in _$registry_668.componentsRegistry) { + for(var componentName in _$registry_731.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12478,15 +12628,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_668.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_731.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_668.subplotsRegistry[plotType]) { - _$loggers_544.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_731.subplotsRegistry[plotType]) { + _$loggers_606.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12496,9 +12646,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_668.subplotsRegistry[plotType] = _module; + _$registry_731.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_668.componentsRegistry) { + for(var componentName in _$registry_731.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12509,29 +12659,29 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_668.componentsRegistry[name] = _module; + _$registry_731.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_552(_$registry_668.layoutArrayContainers, name); + _$pushUnique_615(_$registry_731.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_668.modules) { + for(var traceType in _$registry_731.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_668.subplotsRegistry) { + for(var subplotName in _$registry_731.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_668.transformsRegistry) { + for(var transformType in _$registry_731.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } if(_module.schema && _module.schema.layout) { - extendDeepAll(_$layout_attributes_638, _module.schema.layout); + extendDeepAll(_$layout_attributes_700, _module.schema.layout); } } @@ -12548,22 +12698,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_544.log([ + _$loggers_606.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_541(_module.attributes)) { - _$loggers_544.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_603(_module.attributes)) { + _$loggers_606.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_544.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_606.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_668.transformsRegistry[_module.name] = _module; + _$registry_731.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_668.componentsRegistry) { + for(var componentName in _$registry_731.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12577,7 +12727,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_668.localeRegistry; + var locales = _$registry_731.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12609,37 +12759,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_552(_$registry_668.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_615(_$registry_731.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_668.componentsRegistry[componentName].schema; + var componentSchema = _$registry_731.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_668.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_731.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_668.componentsRegistry[componentName].schema; + var componentSchema = _$registry_731.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_668.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_731.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_668.componentsRegistry[componentName].schema; + var componentSchema = _$registry_731.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_668.subplotsRegistry[subplotName]; + var subplotModule = _$registry_731.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12666,7 +12816,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$registry_731 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12681,9 +12831,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_568 = function containerArrayMatch(astr) { - var rootContainers = _$registry_668.layoutArrayContainers, - regexpContainers = _$registry_668.layoutArrayRegexes, +var _$containerArrayMatch_631 = function containerArrayMatch(astr) { + var rootContainers = _$registry_731.layoutArrayContainers, + regexpContainers = _$registry_731.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12723,10 +12873,10 @@ var _$containerArrayMatch_568 = function containerArrayMatch(astr) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_540.isArrayOrTypedArray; -/* removed: var _$isPlainObject_541 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_568 = require('../plot_api/container_array_match'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var isArrayOrTypedArray = _$is_array_602.isArrayOrTypedArray; +/* removed: var _$isPlainObject_603 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_631 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12742,8 +12892,8 @@ var isArrayOrTypedArray = _$is_array_540.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_547 = function nestedProperty(container, propStr) { - if(_$fastIsnumeric_139(propStr)) propStr = String(propStr); +var _$nestedProperty_609 = function nestedProperty(container, propStr) { + if(_$fastIsnumeric_196(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { throw 'bad property string'; @@ -12853,7 +13003,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_541(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_603(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12862,7 +13012,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_568(propStr); + var match = _$containerArrayMatch_631(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12917,7 +13067,7 @@ function npSet(cont, parts, propStr) { function joinPropStr(propStr, newPart) { var toAdd = newPart; - if(_$fastIsnumeric_139(newPart)) toAdd = '[' + newPart + ']'; + if(_$fastIsnumeric_196(newPart)) toAdd = '[' + newPart + ']'; else if(propStr) toAdd = '.' + newPart; return propStr + toAdd; @@ -13015,7 +13165,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_554 = {}; +var _$regex_617 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13035,7 +13185,7 @@ var _$regex_554 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_554.counter = function(head, tail, openEnded) { +_$regex_617.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -13043,7 +13193,7 @@ _$regex_554.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_524 = {}; +var _$coerce_586 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13055,19 +13205,19 @@ var _$coerce_524 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$attributes_581 = require('../plots/attributes'); */; -/* removed: var _$getScale_424 = require('../components/colorscale/get_scale'); */; -var colorscaleNames = Object.keys(_$scales_430); -/* removed: var _$nestedProperty_547 = require('./nested_property'); */; -var counterRegex = _$regex_554.counter; -var DESELECTDIM = _$interactions_516.DESELECTDIM; -var wrap180 = _$angles_522.wrap180; -var __isArrayOrTypedArray_524 = _$is_array_540.isArrayOrTypedArray; +/* removed: var _$attributes_644 = require('../plots/attributes'); */; +/* removed: var _$getScale_486 = require('../components/colorscale/get_scale'); */; +var colorscaleNames = Object.keys(_$scales_492); +/* removed: var _$nestedProperty_609 = require('./nested_property'); */; +var counterRegex = _$regex_617.counter; +var DESELECTDIM = _$interactions_577.DESELECTDIM; +var wrap180 = _$angles_583.wrap180; +var __isArrayOrTypedArray_586 = _$is_array_602.isArrayOrTypedArray; -_$coerce_524.valObjectMeta = { +_$coerce_586.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. description: [ @@ -13079,7 +13229,7 @@ _$coerce_524.valObjectMeta = { otherOpts: ['dflt'], coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_524(v)) propOut.set(v); + if(__isArrayOrTypedArray_586(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13129,7 +13279,7 @@ _$coerce_524.valObjectMeta = { requiredOpts: [], otherOpts: ['dflt', 'min', 'max', 'arrayOk'], coerceFunction: function(v, propOut, dflt, opts) { - if(!_$fastIsnumeric_139(v) || + if(!_$fastIsnumeric_196(v) || (opts.min !== undefined && v < opts.min) || (opts.max !== undefined && v > opts.max)) { propOut.set(dflt); @@ -13146,7 +13296,7 @@ _$coerce_524.valObjectMeta = { requiredOpts: [], otherOpts: ['dflt', 'min', 'max', 'arrayOk'], coerceFunction: function(v, propOut, dflt, opts) { - if(v % 1 || !_$fastIsnumeric_139(v) || + if(v % 1 || !_$fastIsnumeric_196(v) || (opts.min !== undefined && v < opts.min) || (opts.max !== undefined && v > opts.max)) { propOut.set(dflt); @@ -13188,7 +13338,7 @@ _$coerce_524.valObjectMeta = { requiredOpts: [], otherOpts: ['dflt', 'arrayOk'], coerceFunction: function(v, propOut, dflt) { - if(_$tinycolor_352(v).isValid()) propOut.set(v); + if(_$tinycolor_414(v).isValid()) propOut.set(v); else propOut.set(dflt); } }, @@ -13201,7 +13351,7 @@ _$coerce_524.valObjectMeta = { otherOpts: ['dflt'], coerceFunction: function(v, propOut, dflt) { function isColor(color) { - return _$tinycolor_352(color).isValid(); + return _$tinycolor_414(color).isValid(); } if(!Array.isArray(v) || !v.length) propOut.set(dflt); else if(v.every(isColor)) propOut.set(v); @@ -13220,7 +13370,7 @@ _$coerce_524.valObjectMeta = { requiredOpts: [], otherOpts: ['dflt'], coerceFunction: function(v, propOut, dflt) { - propOut.set(_$getScale_424(v, dflt)); + propOut.set(_$getScale_486(v, dflt)); } }, angle: { @@ -13231,7 +13381,7 @@ _$coerce_524.valObjectMeta = { otherOpts: ['dflt'], coerceFunction: function(v, propOut, dflt) { if(v === 'auto') propOut.set('auto'); - else if(!_$fastIsnumeric_139(v)) propOut.set(dflt); + else if(!_$fastIsnumeric_196(v)) propOut.set(dflt); else propOut.set(wrap180(+v)); } }, @@ -13242,9 +13392,10 @@ _$coerce_524.valObjectMeta = { '\'geo\', \'geo2\', \'geo3\', ...' ].join(' '), requiredOpts: ['dflt'], - otherOpts: [], - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + otherOpts: ['regex'], + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13306,9 +13457,11 @@ _$coerce_524.valObjectMeta = { 'An {array} of plot information.' ].join(' '), requiredOpts: ['items'], - // set dimensions=2 for a 2D 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 otherOpts: ['dflt', 'freeLength', 'dimensions'], coerceFunction: function(v, propOut, dflt, opts) { @@ -13319,12 +13472,12 @@ _$coerce_524.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_524.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_586.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13334,19 +13487,28 @@ _$coerce_524.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13377,12 +13539,12 @@ _$coerce_524.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_524.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_586.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_524.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_586.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13402,10 +13564,10 @@ _$coerce_524.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_524.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_547(attributes, attribute).get(), - propIn = _$nestedProperty_547(containerIn, attribute), - propOut = _$nestedProperty_547(containerOut, attribute), +_$coerce_586.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_609(attributes, attribute).get(), + propIn = _$nestedProperty_609(containerIn, attribute), + propOut = _$nestedProperty_609(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13416,12 +13578,12 @@ _$coerce_524.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_524(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_586(v)) { propOut.set(v); return v; } - _$coerce_524.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_586.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13433,9 +13595,9 @@ _$coerce_524.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_524.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_547(containerIn, attribute), - propOut = _$coerce_524.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_586.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_609(containerIn, attribute), + propOut = _$coerce_586.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13446,7 +13608,7 @@ _$coerce_524.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_524.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_586.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13466,11 +13628,9 @@ _$coerce_524.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_524.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_586.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_581; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_644; var valObj = attrs.hoverinfo; var dflt; @@ -13484,7 +13644,7 @@ _$coerce_524.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_524.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_586.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13498,7 +13658,7 @@ _$coerce_524.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_524.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_586.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13513,7 +13673,7 @@ _$coerce_524.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_524(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_586(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13522,10 +13682,10 @@ _$coerce_524.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_524.validate = function(value, opts) { - var valObjectDef = _$coerce_524.valObjectMeta[opts.valType]; +_$coerce_586.validate = function(value, opts) { + var valObjectDef = _$coerce_586.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_524(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_586(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13555,12 +13715,12 @@ _$coerce_524.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_546 = function mod(v, d) { +var _$mod_608 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_525 = {}; +var _$dates_587 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13572,23 +13732,23 @@ var _$dates_525 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$loggers_544 = require('./loggers'); */; -/* removed: var _$mod_546 = require('./mod'); */; +/* removed: var _$loggers_606 = require('./loggers'); */; +/* removed: var _$mod_608 = require('./mod'); */; -/* removed: var _$numerical_517 = require('../constants/numerical'); */; -var __BADNUM_525 = _$numerical_517.BADNUM; -var ONEDAY = _$numerical_517.ONEDAY; -var ONEHOUR = _$numerical_517.ONEHOUR; -var ONEMIN = _$numerical_517.ONEMIN; -var ONESEC = _$numerical_517.ONESEC; -var EPOCHJD = _$numerical_517.EPOCHJD; +/* removed: var _$numerical_578 = require('../constants/numerical'); */; +var __BADNUM_587 = _$numerical_578.BADNUM; +var ONEDAY = _$numerical_578.ONEDAY; +var ONEHOUR = _$numerical_578.ONEHOUR; +var ONEMIN = _$numerical_578.ONEMIN; +var ONESEC = _$numerical_578.ONESEC; +var EPOCHJD = _$numerical_578.EPOCHJD; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$registry_731 = require('../registry'); */; -var utcFormat = _$d3_127.time.format.utc; +var utcFormat = _$d3_130.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 @@ -13600,7 +13760,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_668.componentsRegistry.calendars && + _$registry_731.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13610,11 +13770,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_525.dateTick0 = function(calendar, sunday) { +_$dates_587.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_668.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_668.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_731.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_731.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13624,9 +13784,9 @@ _$dates_525.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_525.dfltRange = function(calendar) { +_$dates_587.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_668.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_731.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13634,7 +13794,7 @@ _$dates_525.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_525.isJSDate = function(v) { +_$dates_587.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13696,17 +13856,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_525.dateTime2ms = function(s, calendar) { +_$dates_587.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_525.isJSDate(s)) { + if(_$dates_587.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_525; + return __BADNUM_587; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_525; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_587; s = String(s); @@ -13723,7 +13883,7 @@ _$dates_525.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_525; + if(!match) return __BADNUM_587; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13733,12 +13893,12 @@ _$dates_525.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_525; + if(y.length === 2) return __BADNUM_587; y = Number(y); var cDate; try { - var calInstance = _$registry_668.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_731.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13748,9 +13908,9 @@ _$dates_525.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_525; } // Invalid ... date + catch(e) { return __BADNUM_587; } // Invalid ... date - if(!cDate) return __BADNUM_525; + if(!cDate) return __BADNUM_587; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13771,18 +13931,18 @@ _$dates_525.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_525; - if(date.getUTCDate() !== d) return __BADNUM_525; + if(date.getUTCMonth() !== m) return __BADNUM_587; + if(date.getUTCDate() !== d) return __BADNUM_587; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_525.MIN_MS = _$dates_525.dateTime2ms('-9999'); -MAX_MS = _$dates_525.MAX_MS = _$dates_525.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_587.MIN_MS = _$dates_587.dateTime2ms('-9999'); +MAX_MS = _$dates_587.MAX_MS = _$dates_587.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_525.isDateTime = function(s, calendar) { - return (_$dates_525.dateTime2ms(s, calendar) !== __BADNUM_525); +_$dates_587.isDateTime = function(s, calendar) { + return (_$dates_587.dateTime2ms(s, calendar) !== __BADNUM_587); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13801,20 +13961,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_525.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_525; +_$dates_587.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_587; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_546(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_608(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_546(ms, ONEDAY)); + timeMs = Math.floor(_$mod_608(ms, ONEDAY)); try { - dateStr = _$registry_668.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_731.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13862,12 +14022,12 @@ _$dates_525.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_525.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_525; +_$dates_587.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_587; - var msecTenths = Math.floor(_$mod_546(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_608(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), - dateStr = _$d3_127.time.format('%Y-%m-%d')(d), + dateStr = _$d3_130.time.format('%Y-%m-%d')(d), h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), @@ -13898,23 +14058,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_525.cleanDate = function(v, dflt, calendar) { - if(_$dates_525.isJSDate(v) || typeof v === 'number') { +_$dates_587.cleanDate = function(v, dflt, calendar) { + if(_$dates_587.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_544.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_606.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 = _$dates_525.ms2DateTimeLocal(+v); + v = _$dates_587.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_525.isDateTime(v, calendar)) { - _$loggers_544.error('unrecognized date', v); + else if(!_$dates_587.isDateTime(v, calendar)) { + _$loggers_606.error('unrecognized date', v); return dflt; } return v; @@ -13944,7 +14104,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_668.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_731.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13961,13 +14121,13 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_546(x + 0.05, ONEDAY); + var timePart = _$mod_608(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_546(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_608(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { - if(!_$fastIsnumeric_139(tr)) tr = 0; // should only be 'S' + if(!_$fastIsnumeric_196(tr)) tr = 0; // should only be 'S' /* * this is a weird one - and shouldn't come up unless people @@ -13984,7 +14144,7 @@ function formatTime(x, tr) { * 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_546(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_608(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -14013,7 +14173,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_525.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_587.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -14057,19 +14217,19 @@ _$dates_525.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_525.incrementMonth = function(ms, dMonth, calendar) { +_$dates_587.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_546(ms, ONEDAY); + var timeMs = _$mod_608(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_668.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_731.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -14078,7 +14238,7 @@ _$dates_525.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_544.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_606.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -14093,7 +14253,7 @@ _$dates_525.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_525.findExactDates = function(data, calendar) { +_$dates_587.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -14103,14 +14263,14 @@ _$dates_525.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_668.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_731.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { di = data[i]; // not date data at all - if(!_$fastIsnumeric_139(di)) { + if(!_$fastIsnumeric_196(di)) { blankCount ++; continue; } @@ -14170,7 +14330,7 @@ _$dates_525.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_526 = function ensureArray(out, n) { +var _$ensureArray_588 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14213,7 +14373,7 @@ var _$ensureArray_526 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_529 = function filterUnique(array) { +var _$filterUnique_591 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14247,7 +14407,7 @@ var _$filterUnique_529 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_530 = function filterVisible(container) { +var _$filterVisible_592 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14276,7 +14436,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_533 = {}; +var _$geometry2d_595 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14287,13 +14447,13 @@ var _$geometry2d_533 = {}; 'use strict'; -/* removed: var _$mod_546 = require('./mod'); */; +/* removed: var _$mod_608 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_533.segmentsIntersect = segmentsIntersect; +_$geometry2d_595.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14316,7 +14476,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_533.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_595.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 @@ -14369,7 +14529,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_533.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_595.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14381,13 +14541,13 @@ _$geometry2d_533.getTextLocation = function getTextLocation(path, totalPathLen, // 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_546(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_546(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_608(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_608(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_546(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_608(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14396,7 +14556,7 @@ _$geometry2d_533.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_533.clearLocationCache = function() { +_$geometry2d_595.clearLocationCache = function() { workingPath = null; }; @@ -14424,7 +14584,7 @@ _$geometry2d_533.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_533.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_595.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14485,7 +14645,7 @@ _$geometry2d_533.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_533.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_595.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14540,7 +14700,7 @@ _$geometry2d_533.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_534 = function(gd) { +var _$get_graph_div_596 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14572,7 +14732,7 @@ var _$get_graph_div_534 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_538 = function identity(d) { return d; }; +var _$identity_600 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14584,7 +14744,7 @@ var _$identity_538 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_547 = require('./nested_property'); */; +/* removed: var _$nestedProperty_609 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14606,13 +14766,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_604 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_547(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_609(baseObj, path).get(); } else { arr = baseObj; } @@ -14638,7 +14798,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_547(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_609(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14648,7 +14808,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_547(newValue, valueName).set(value); + _$nestedProperty_609(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14669,7 +14829,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_547(arr[idx], valueName).get(); + return _$nestedProperty_609(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14710,7 +14870,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value } 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_547(object, valueName).set(null); + _$nestedProperty_609(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, @@ -14737,7 +14897,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_547(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_609(arr[idx], valueName).get(); } } } else { @@ -14763,7 +14923,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$registry_731 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14774,7 +14934,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_543 = function localize(gd, s) { +var _$localize_605 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14796,7 +14956,7 @@ var _$localize_543 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_668.localeRegistry; + locales = _$registry_731.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14807,7 +14967,7 @@ var _$localize_543 = function localize(gd, s) { return s; }; -var _$matrix_545 = {}; +var _$matrix_607 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14820,7 +14980,7 @@ var _$matrix_545 = {}; 'use strict'; -_$matrix_545.init2dArray = function(rowLength, colLength) { +_$matrix_607.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14831,7 +14991,7 @@ _$matrix_545.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_545.transposeRagged = function(z) { +_$matrix_607.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14849,7 +15009,7 @@ _$matrix_545.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_545.dot = function(x, y) { +_$matrix_607.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14859,13 +15019,13 @@ _$matrix_545.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_545.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_607.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_545.transposeRagged(y); + var yTranspose = _$matrix_607.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_545.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_607.dot(x, yTranspose[i]); } else { // vec-vec @@ -14877,12 +15037,12 @@ _$matrix_545.dot = function(x, y) { }; // translate by (x,y) -_$matrix_545.translationMatrix = function(x, y) { +_$matrix_607.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_545.rotationMatrix = function(alpha) { +_$matrix_607.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14890,28 +15050,28 @@ _$matrix_545.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_545.rotationXYMatrix = function(a, x, y) { - return _$matrix_545.dot( - _$matrix_545.dot(_$matrix_545.translationMatrix(x, y), - _$matrix_545.rotationMatrix(a)), - _$matrix_545.translationMatrix(-x, -y)); +_$matrix_607.rotationXYMatrix = function(a, x, y) { + return _$matrix_607.dot( + _$matrix_607.dot(_$matrix_607.translationMatrix(x, y), + _$matrix_607.rotationMatrix(a)), + _$matrix_607.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_545.apply2DTransform = function(transform) { +_$matrix_607.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_545.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_607.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_545.apply2DTransform2 = function(transform) { - var at = _$matrix_545.apply2DTransform(transform); +_$matrix_607.apply2DTransform2 = function(transform) { + var at = _$matrix_607.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14928,8 +15088,8 @@ _$matrix_545.apply2DTransform2 = function(transform) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; var NOTEDATA = []; @@ -14940,16 +15100,16 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_549 = function(text, displayLength) { +var _$notifier_611 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); var ts = 1000; - if(_$fastIsnumeric_139(displayLength)) ts = displayLength; + if(_$fastIsnumeric_196(displayLength)) ts = displayLength; else if(displayLength === 'long') ts = 3000; - var notifierContainer = _$d3_127.select('body') + var notifierContainer = _$d3_130.select('body') .selectAll('.plotly-notifier') .data([0]); notifierContainer.enter() @@ -14965,7 +15125,7 @@ var _$notifier_549 = function(text, displayLength) { .each('end', function(thisText) { var thisIndex = NOTEDATA.indexOf(thisText); if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1); - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); }); } @@ -14973,7 +15133,7 @@ var _$notifier_549 = function(text, displayLength) { .classed('notifier-note', true) .style('opacity', 0) .each(function(thisText) { - var note = _$d3_127.select(this); + var note = _$d3_130.select(this); note.append('button') .classed('notifier-close', true) @@ -15032,7 +15192,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_555 = function(baseAttr, relativeAttr) { +var _$relative_attr_618 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -15061,8 +15221,8 @@ var _$relative_attr_555 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_556 = _$is_array_540.isArrayOrTypedArray; -/* removed: var _$isPlainObject_541 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_619 = _$is_array_602.isArrayOrTypedArray; +/* removed: var _$isPlainObject_603 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -15071,7 +15231,7 @@ var __isArrayOrTypedArray_556 = _$is_array_540.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_619 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -15087,7 +15247,7 @@ var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_556(fromVal) && __isArrayOrTypedArray_556(toVal) && _$isPlainObject_541(fromVal[0])) { + else if(__isArrayOrTypedArray_619(fromVal) && __isArrayOrTypedArray_619(toVal) && _$isPlainObject_603(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -15097,12 +15257,12 @@ var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContai // 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_541(fromVal[j]) && _$isPlainObject_541(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_603(fromVal[j]) && _$isPlainObject_603(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_541(fromVal) && _$isPlainObject_541(toVal)) { + else if(_$isPlainObject_603(fromVal) && _$isPlainObject_603(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -15112,7 +15272,7 @@ var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_557 = {}; +var _$search_620 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15124,8 +15284,8 @@ var _$search_557 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$loggers_544 = require('./loggers'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$loggers_606 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -15143,8 +15303,8 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_557.findBin = function(val, bins, linelow) { - if(_$fastIsnumeric_139(bins.start)) { +_$search_620.findBin = function(val, bins, linelow) { + if(_$fastIsnumeric_196(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError); @@ -15167,7 +15327,7 @@ _$search_557.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_544.log('Long binary search...'); + if(c > 90) _$loggers_606.log('Long binary search...'); return n1 - 1; } }; @@ -15177,17 +15337,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_557.sorterAsc = function(a, b) { return a - b; }; -_$search_557.sorterDes = function(a, b) { return b - a; }; +_$search_620.sorterAsc = function(a, b) { return a - b; }; +_$search_620.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_557.distinctVals = function(valsIn) { +_$search_620.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_557.sorterAsc); + vals.sort(_$search_620.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15212,7 +15372,7 @@ _$search_557.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_557.roundUp = function(val, arrayIn, reverse) { +_$search_620.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15229,7 +15389,7 @@ _$search_557.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_560 = {}; +var _$stats_623 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15241,8 +15401,8 @@ var _$stats_560 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_560 = _$is_array_540.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_623 = _$is_array_602.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15257,20 +15417,20 @@ var __isArrayOrTypedArray_560 = _$is_array_540.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_560.aggNums = function(f, v, a, len) { +_$stats_623.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; - if(!_$fastIsnumeric_139(v)) v = false; - if(__isArrayOrTypedArray_560(a[0])) { + if(!_$fastIsnumeric_196(v)) v = false; + if(__isArrayOrTypedArray_623(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_560.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_623.aggNums(f, v, a[i]); a = b; } for(i = 0; i < len; i++) { - if(!_$fastIsnumeric_139(v)) v = a[i]; - else if(_$fastIsnumeric_139(a[i])) v = f(+v, +a[i]); + if(!_$fastIsnumeric_196(v)) v = a[i]; + else if(_$fastIsnumeric_196(a[i])) v = f(+v, +a[i]); } return v; }; @@ -15279,26 +15439,26 @@ _$stats_560.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_560.len = function(data) { - return _$stats_560.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_623.len = function(data) { + return _$stats_623.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_560.mean = function(data, len) { - if(!len) len = _$stats_560.len(data); - return _$stats_560.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_623.mean = function(data, len) { + if(!len) len = _$stats_623.len(data); + return _$stats_623.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_560.variance = function(data, len, mean) { - if(!len) len = _$stats_560.len(data); - if(!_$fastIsnumeric_139(mean)) mean = _$stats_560.mean(data, len); +_$stats_623.variance = function(data, len, mean) { + if(!len) len = _$stats_623.len(data); + if(!_$fastIsnumeric_196(mean)) mean = _$stats_623.mean(data, len); - return _$stats_560.aggNums(function(a, b) { + return _$stats_623.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_560.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_560.variance(data, len, mean)); +_$stats_623.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_623.variance(data, len, mean)); }; /** @@ -15316,8 +15476,8 @@ _$stats_560.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_560.interp = function(arr, n) { - if(!_$fastIsnumeric_139(n)) throw 'n should be a finite number'; +_$stats_623.interp = function(arr, n) { + if(!_$fastIsnumeric_196(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; if(n > arr.length - 1) return arr[arr.length - 1]; @@ -15325,7 +15485,7 @@ _$stats_560.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_563 = {}; +var _$throttle_626 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15352,7 +15512,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_563.throttle = function throttle(id, minInterval, callback) { +_$throttle_626.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15392,7 +15552,7 @@ _$throttle_563.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_563.done = function(id) { +_$throttle_626.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15412,13 +15572,13 @@ _$throttle_563.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_563.clear = function(id) { +_$throttle_626.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_563.clear(idi); + for(var idi in timerCache) _$throttle_626.clear(idi); } }; @@ -15439,160 +15599,160 @@ function _clearTimeout(cache) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; /** * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_564 = function toLogRange(val, range) { +var _$toLogRange_627 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the // result at the lowest range value on the plot (or if the range also went negative, // one millionth of the top of the range) var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10; - if(!_$fastIsnumeric_139(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; + if(!_$fastIsnumeric_196(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; return newVal; }; -var _$lib_539 = {}; -/** +var _$lib_601 = {}; +/** * Copyright 2012-2018, Plotly, Inc. * All 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 source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. */ - + 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -/* removed: var _$numerical_517 = require('../constants/numerical'); */; -var FP_SAFE = _$numerical_517.FP_SAFE; -var __BADNUM_539 = _$numerical_517.BADNUM; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; + +/* removed: var _$numerical_578 = require('../constants/numerical'); */; +var FP_SAFE = _$numerical_578.FP_SAFE; +var __BADNUM_601 = _$numerical_578.BADNUM; -var lib = _$lib_539 = {}; +var lib = _$lib_601 = {}; -lib.nestedProperty = _$nestedProperty_547; -lib.keyedContainer = _$keyedContainer_542; -lib.relativeAttr = _$relative_attr_555; -lib.isPlainObject = _$isPlainObject_541; -lib.mod = _$mod_546; -lib.toLogRange = _$toLogRange_564; -lib.relinkPrivateKeys = _$relinkPrivateKeys_556; -lib.ensureArray = _$ensureArray_526; +lib.nestedProperty = _$nestedProperty_609; +lib.keyedContainer = _$keyedContainer_604; +lib.relativeAttr = _$relative_attr_618; +lib.isPlainObject = _$isPlainObject_603; +lib.mod = _$mod_608; +lib.toLogRange = _$toLogRange_627; +lib.relinkPrivateKeys = _$relinkPrivateKeys_619; +lib.ensureArray = _$ensureArray_588; -/* removed: var _$is_array_540 = require('./is_array'); */; -lib.isTypedArray = _$is_array_540.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_540.isArrayOrTypedArray; +/* removed: var _$is_array_602 = require('./is_array'); */; +lib.isTypedArray = _$is_array_602.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_602.isArrayOrTypedArray; -/* removed: var _$coerce_524 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_524.valObjectMeta; -lib.coerce = _$coerce_524.coerce; -lib.coerce2 = _$coerce_524.coerce2; -lib.coerceFont = _$coerce_524.coerceFont; -lib.coerceHoverinfo = _$coerce_524.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_524.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_524.validate; +/* removed: var _$coerce_586 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_586.valObjectMeta; +lib.coerce = _$coerce_586.coerce; +lib.coerce2 = _$coerce_586.coerce2; +lib.coerceFont = _$coerce_586.coerceFont; +lib.coerceHoverinfo = _$coerce_586.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_586.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_586.validate; -/* removed: var _$dates_525 = require('./dates'); */; -lib.dateTime2ms = _$dates_525.dateTime2ms; -lib.isDateTime = _$dates_525.isDateTime; -lib.ms2DateTime = _$dates_525.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_525.ms2DateTimeLocal; -lib.cleanDate = _$dates_525.cleanDate; -lib.isJSDate = _$dates_525.isJSDate; -lib.formatDate = _$dates_525.formatDate; -lib.incrementMonth = _$dates_525.incrementMonth; -lib.dateTick0 = _$dates_525.dateTick0; -lib.dfltRange = _$dates_525.dfltRange; -lib.findExactDates = _$dates_525.findExactDates; -lib.MIN_MS = _$dates_525.MIN_MS; -lib.MAX_MS = _$dates_525.MAX_MS; +/* removed: var _$dates_587 = require('./dates'); */; +lib.dateTime2ms = _$dates_587.dateTime2ms; +lib.isDateTime = _$dates_587.isDateTime; +lib.ms2DateTime = _$dates_587.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_587.ms2DateTimeLocal; +lib.cleanDate = _$dates_587.cleanDate; +lib.isJSDate = _$dates_587.isJSDate; +lib.formatDate = _$dates_587.formatDate; +lib.incrementMonth = _$dates_587.incrementMonth; +lib.dateTick0 = _$dates_587.dateTick0; +lib.dfltRange = _$dates_587.dfltRange; +lib.findExactDates = _$dates_587.findExactDates; +lib.MIN_MS = _$dates_587.MIN_MS; +lib.MAX_MS = _$dates_587.MAX_MS; -/* removed: var _$search_557 = require('./search'); */; -lib.findBin = _$search_557.findBin; -lib.sorterAsc = _$search_557.sorterAsc; -lib.sorterDes = _$search_557.sorterDes; -lib.distinctVals = _$search_557.distinctVals; -lib.roundUp = _$search_557.roundUp; +/* removed: var _$search_620 = require('./search'); */; +lib.findBin = _$search_620.findBin; +lib.sorterAsc = _$search_620.sorterAsc; +lib.sorterDes = _$search_620.sorterDes; +lib.distinctVals = _$search_620.distinctVals; +lib.roundUp = _$search_620.roundUp; -/* removed: var _$stats_560 = require('./stats'); */; -lib.aggNums = _$stats_560.aggNums; -lib.len = _$stats_560.len; -lib.mean = _$stats_560.mean; -lib.variance = _$stats_560.variance; -lib.stdev = _$stats_560.stdev; -lib.interp = _$stats_560.interp; +/* removed: var _$stats_623 = require('./stats'); */; +lib.aggNums = _$stats_623.aggNums; +lib.len = _$stats_623.len; +lib.mean = _$stats_623.mean; +lib.variance = _$stats_623.variance; +lib.stdev = _$stats_623.stdev; +lib.interp = _$stats_623.interp; -/* removed: var _$matrix_545 = require('./matrix'); */; -lib.init2dArray = _$matrix_545.init2dArray; -lib.transposeRagged = _$matrix_545.transposeRagged; -lib.dot = _$matrix_545.dot; -lib.translationMatrix = _$matrix_545.translationMatrix; -lib.rotationMatrix = _$matrix_545.rotationMatrix; -lib.rotationXYMatrix = _$matrix_545.rotationXYMatrix; -lib.apply2DTransform = _$matrix_545.apply2DTransform; -lib.apply2DTransform2 = _$matrix_545.apply2DTransform2; +/* removed: var _$matrix_607 = require('./matrix'); */; +lib.init2dArray = _$matrix_607.init2dArray; +lib.transposeRagged = _$matrix_607.transposeRagged; +lib.dot = _$matrix_607.dot; +lib.translationMatrix = _$matrix_607.translationMatrix; +lib.rotationMatrix = _$matrix_607.rotationMatrix; +lib.rotationXYMatrix = _$matrix_607.rotationXYMatrix; +lib.apply2DTransform = _$matrix_607.apply2DTransform; +lib.apply2DTransform2 = _$matrix_607.apply2DTransform2; -/* removed: var _$angles_522 = require('./angles'); */; -lib.deg2rad = _$angles_522.deg2rad; -lib.rad2deg = _$angles_522.rad2deg; -lib.wrap360 = _$angles_522.wrap360; -lib.wrap180 = _$angles_522.wrap180; +/* removed: var _$angles_583 = require('./angles'); */; +lib.deg2rad = _$angles_583.deg2rad; +lib.rad2deg = _$angles_583.rad2deg; +lib.wrap360 = _$angles_583.wrap360; +lib.wrap180 = _$angles_583.wrap180; -/* removed: var _$geometry2d_533 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_533.segmentsIntersect; -lib.segmentDistance = _$geometry2d_533.segmentDistance; -lib.getTextLocation = _$geometry2d_533.getTextLocation; -lib.clearLocationCache = _$geometry2d_533.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_533.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_533.findPointOnPath; +/* removed: var _$geometry2d_595 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_595.segmentsIntersect; +lib.segmentDistance = _$geometry2d_595.segmentDistance; +lib.getTextLocation = _$geometry2d_595.getTextLocation; +lib.clearLocationCache = _$geometry2d_595.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_595.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_595.findPointOnPath; -/* removed: var _$extend_528 = require('./extend'); */; -lib.extendFlat = _$extend_528.extendFlat; -lib.extendDeep = _$extend_528.extendDeep; -lib.extendDeepAll = _$extend_528.extendDeepAll; -lib.extendDeepNoArrays = _$extend_528.extendDeepNoArrays; +/* removed: var _$extend_590 = require('./extend'); */; +lib.extendFlat = _$extend_590.extendFlat; +lib.extendDeep = _$extend_590.extendDeep; +lib.extendDeepAll = _$extend_590.extendDeepAll; +lib.extendDeepNoArrays = _$extend_590.extendDeepNoArrays; -/* removed: var _$loggers_544 = require('./loggers'); */; -lib.log = _$loggers_544.log; -lib.warn = _$loggers_544.warn; -lib.error = _$loggers_544.error; - -/* removed: var _$regex_554 = require('./regex'); */; -lib.counterRegex = _$regex_554.counter; - -/* removed: var _$throttle_563 = require('./throttle'); */; -lib.throttle = _$throttle_563.throttle; -lib.throttleDone = _$throttle_563.done; -lib.clearThrottle = _$throttle_563.clear; - -lib.getGraphDiv = _$get_graph_div_534; - -lib._ = _$localize_543; - -lib.notifier = _$notifier_549; - -lib.filterUnique = _$filterUnique_529; -lib.filterVisible = _$filterVisible_530; -lib.pushUnique = _$pushUnique_552; - -lib.cleanNumber = _$cleanNumber_523; +/* removed: var _$loggers_606 = require('./loggers'); */; +lib.log = _$loggers_606.log; +lib.warn = _$loggers_606.warn; +lib.error = _$loggers_606.error; + +/* removed: var _$regex_617 = require('./regex'); */; +lib.counterRegex = _$regex_617.counter; + +/* removed: var _$throttle_626 = require('./throttle'); */; +lib.throttle = _$throttle_626.throttle; +lib.throttleDone = _$throttle_626.done; +lib.clearThrottle = _$throttle_626.clear; + +lib.getGraphDiv = _$get_graph_div_596; + +lib._ = _$localize_605; + +lib.notifier = _$notifier_611; + +lib.filterUnique = _$filterUnique_591; +lib.filterVisible = _$filterVisible_592; +lib.pushUnique = _$pushUnique_615; + +lib.cleanNumber = _$cleanNumber_584; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_139(v)) return __BADNUM_539; + if(!_$fastIsnumeric_196(v)) return __BADNUM_601; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_539; - return _$fastIsnumeric_139(v) ? Number(v) : __BADNUM_539; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_601; + return _$fastIsnumeric_196(v) ? Number(v) : __BADNUM_601; }; -lib.noop = _$noop_548; -lib.identity = _$identity_538; +lib.noop = _$noop_610; +lib.identity = _$identity_600; /** * swap x and y of the same attribute in container cont @@ -15952,7 +16112,7 @@ lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) { } function isPtIndexValid(v) { - return _$fastIsnumeric_139(v) && v >= 0 && v % 1 === 0; + return _$fastIsnumeric_196(v) && v >= 0 && v % 1 === 0; } function isCdIndexValid(v) { @@ -16044,7 +16204,7 @@ lib.containsAny = function(s, fragments) { }; lib.isPlotDiv = function(el) { - var el3 = _$d3_127.select(el); + var el3 = _$d3_130.select(el); return el3.node() instanceof HTMLElement && el3.size() && el3.classed('js-plotly-plot'); @@ -16091,6 +16251,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16284,7 +16501,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_539 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_601 = /^\w*$/; /* * Substitute values from an object into a string @@ -16305,7 +16522,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_539.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_601.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16365,9 +16582,9 @@ lib.pseudoRandom = function() { 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -var __extendFlat_569 = _$lib_539.extendFlat; -var __isPlainObject_569 = _$lib_539.isPlainObject; +/* removed: var _$lib_601 = require('../lib'); */; +var __extendFlat_632 = _$lib_601.extendFlat; +var __isPlainObject_632 = _$lib_601.isPlainObject; var traceOpts = { valType: 'flaglist', @@ -16392,7 +16609,7 @@ var layoutOpts = { valType: 'flaglist', extras: ['none'], flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', 'layoutstyle', 'modebar', 'camera', 'arraydraw' ], description: [ @@ -16405,6 +16622,7 @@ var layoutOpts = { '*legend* only redraws the legend.', '*ticks* only redraws axis ticks, labels, and gridlines.', '*margins* recomputes ticklabel automargins.', + '*axrange* minimal sequence when updating axis ranges.', '*layoutstyle* reapplies global and SVG cartesian axis styles.', '*modebar* just updates the modebar.', '*camera* just updates the camera settings for gl3d scenes.', @@ -16422,7 +16640,7 @@ var traceEditTypeFlags = traceOpts.flags.slice() var layoutEditTypeFlags = layoutOpts.flags.slice() .concat('layoutReplot'); -var _$edit_types_569 = { +var _$edit_types_632 = { traces: traceOpts, layout: layoutOpts, /* @@ -16475,10 +16693,10 @@ function falseObj(keys) { * @return {object} a new attributes object with `editType` modified as directed */ function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_569({}, attrs); + var out = __extendFlat_632({}, attrs); for(var key in out) { var attr = out[key]; - if(__isPlainObject_569(attr)) { + if(__isPlainObject_632(attr)) { out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } @@ -16489,7 +16707,7 @@ function overrideAll(attrs, editTypeOverride, overrideContainers) { function overrideOne(attr, editTypeOverride, overrideContainers, key) { if(attr.valType) { - var out = __extendFlat_569({}, attr); + var out = __extendFlat_632({}, attr); out.editType = editTypeOverride; if(Array.isArray(attr.items)) { @@ -16517,7 +16735,7 @@ function overrideOne(attr, editTypeOverride, overrideContainers, key) { 'use strict'; -var _$animation_attributes_579 = { +var _$animation_attributes_642 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -16640,7 +16858,7 @@ var _$animation_attributes_579 = { 'use strict'; -var _$frame_attributes_612 = { +var _$frame_attributes_674 = { _isLinkedToArray: 'frames_entry', group: { @@ -16691,7 +16909,7 @@ var _$frame_attributes_612 = { } }; -var _$attributes_435 = {}; +var _$attributes_497 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16703,7 +16921,7 @@ var _$attributes_435 = {}; 'use strict'; -_$attributes_435.dash = { +_$attributes_497.dash = { valType: 'string', // string type usually doesn't take values... this one should really be // a special type or at least a special coercion function, from the GUI @@ -16729,21 +16947,21 @@ _$attributes_435.dash = { */ 'use strict'; -var __counterRegex_589 = _$regex_554.counter; +var __counterRegex_652 = _$regex_617.counter; -var _$constants_589 = { +var _$constants_652 = { idRegex: { - x: __counterRegex_589('x'), - y: __counterRegex_589('y') + x: __counterRegex_652('x'), + y: __counterRegex_652('y') }, - attrRegex: __counterRegex_589('[xy]axis'), + attrRegex: __counterRegex_652('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_589('xaxis'), - yAxisMatch: __counterRegex_589('yaxis'), + xAxisMatch: __counterRegex_652('xaxis'), + yAxisMatch: __counterRegex_652('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -16790,6 +17008,7 @@ var _$constants_589 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -16809,15 +17028,15 @@ var _$constants_589 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../font_attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -var dash = _$attributes_435.dash; -var __extendFlat_596 = _$extend_528.extendFlat; +/* removed: var _$font_attributes_673 = require('../font_attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +var dash = _$attributes_497.dash; +var __extendFlat_659 = _$extend_590.extendFlat; -/* removed: var _$constants_589 = require('./constants'); */; +/* removed: var _$constants_652 = require('./constants'); */; -var _$layout_attributes_596 = { +var _$layout_attributes_659 = { visible: { valType: 'boolean', role: 'info', @@ -16830,7 +17049,7 @@ var _$layout_attributes_596 = { }, color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'ticks', description: [ @@ -16846,7 +17065,7 @@ var _$layout_attributes_596 = { editType: 'ticks+margins', description: 'Sets the title of this axis.' }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ editType: 'ticks+margins', description: [ 'Sets this axis\' title font.' @@ -16901,10 +17120,10 @@ var _$layout_attributes_596 = { valType: 'info_array', role: 'info', items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} ], - editType: 'plot+margins', + editType: 'axrange+margins', impliedEdits: {'autorange': false}, description: [ 'Sets the range of this axis.', @@ -16934,8 +17153,8 @@ var _$layout_attributes_596 = { scaleanchor: { valType: 'enumerated', values: [ - _$constants_589.idRegex.x.toString(), - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.x.toString(), + _$constants_652.idRegex.y.toString() ], role: 'info', editType: 'plot', @@ -17133,7 +17352,7 @@ var _$layout_attributes_596 = { }, tickcolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'ticks', description: 'Sets the tick color.' @@ -17179,7 +17398,7 @@ var _$layout_attributes_596 = { editType: 'none', description: 'Sets the width (in px) of the zero line.' }, - spikedash: __extendFlat_596({}, dash, {dflt: 'dash', editType: 'none'}), + spikedash: __extendFlat_659({}, dash, {dflt: 'dash', editType: 'none'}), spikemode: { valType: 'flaglist', flags: ['toaxis', 'across', 'marker'], @@ -17206,7 +17425,7 @@ var _$layout_attributes_596 = { editType: 'none', description: 'Determines whether spikelines are stuck to the cursor or to the closest datapoints.' }, - tickfont: _$font_attributes_611({ + tickfont: _$font_attributes_673({ editType: 'ticks+margins', description: 'Sets the tick font.' }), @@ -17367,7 +17586,7 @@ var _$layout_attributes_596 = { }, linecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'layoutstyle', description: 'Sets the axis line color.' @@ -17391,7 +17610,7 @@ var _$layout_attributes_596 = { }, gridcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, role: 'style', editType: 'ticks', description: 'Sets the color of the grid lines.' @@ -17416,7 +17635,7 @@ var _$layout_attributes_596 = { }, zerolinecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'ticks', description: 'Sets the line color of the zero line.' @@ -17435,8 +17654,8 @@ var _$layout_attributes_596 = { valType: 'enumerated', values: [ 'free', - _$constants_589.idRegex.x.toString(), - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.x.toString(), + _$constants_652.idRegex.y.toString() ], role: 'info', editType: 'plot+margins', @@ -17466,8 +17685,8 @@ var _$layout_attributes_596 = { valType: 'enumerated', values: [ 'free', - _$constants_589.idRegex.x.toString(), - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.x.toString(), + _$constants_652.idRegex.y.toString() ], role: 'info', editType: 'plot', @@ -17575,13 +17794,13 @@ var _$layout_attributes_596 = { 'use strict'; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __extendFlat_412 = _$extend_528.extendFlat; -var __overrideAll_412 = _$edit_types_569.overrideAll; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __extendFlat_474 = _$extend_590.extendFlat; +var __overrideAll_474 = _$edit_types_632.overrideAll; -var _$attributes_412 = __overrideAll_412({ +var _$attributes_474 = __overrideAll_474({ // TODO: only right is supported currently // orient: { // valType: 'enumerated', @@ -17696,11 +17915,11 @@ var _$attributes_412 = __overrideAll_412({ description: 'Sets the amount of padding (in px) along the y direction.' }, // a possible line around the bar itself - outlinecolor: _$layout_attributes_596.linecolor, - outlinewidth: _$layout_attributes_596.linewidth, + outlinecolor: _$layout_attributes_659.linecolor, + outlinewidth: _$layout_attributes_659.linewidth, // Should outlinewidth have {dflt: 0} ? // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_596.linecolor, + bordercolor: _$layout_attributes_659.linecolor, borderwidth: { valType: 'number', role: 'style', @@ -17717,36 +17936,36 @@ var _$attributes_412 = __overrideAll_412({ description: 'Sets the color of padded area.' }, // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_596.tickmode, - nticks: _$layout_attributes_596.nticks, - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: __extendFlat_412({}, _$layout_attributes_596.ticks, {dflt: ''}), - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - tickfont: _$font_attributes_611({ + tickmode: _$layout_attributes_659.tickmode, + nticks: _$layout_attributes_659.nticks, + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: __extendFlat_474({}, _$layout_attributes_659.ticks, {dflt: ''}), + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + tickfont: _$font_attributes_673({ description: 'Sets the color bar\'s tick label font' }), - tickangle: _$layout_attributes_596.tickangle, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - tickprefix: _$layout_attributes_596.tickprefix, - showtickprefix: _$layout_attributes_596.showtickprefix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showticksuffix: _$layout_attributes_596.showticksuffix, - separatethousands: _$layout_attributes_596.separatethousands, - exponentformat: _$layout_attributes_596.exponentformat, - showexponent: _$layout_attributes_596.showexponent, + tickangle: _$layout_attributes_659.tickangle, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + tickprefix: _$layout_attributes_659.tickprefix, + showtickprefix: _$layout_attributes_659.showtickprefix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showticksuffix: _$layout_attributes_659.showticksuffix, + separatethousands: _$layout_attributes_659.separatethousands, + exponentformat: _$layout_attributes_659.exponentformat, + showexponent: _$layout_attributes_659.showexponent, title: { valType: 'string', role: 'info', description: 'Sets the title of the color bar.' }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ description: 'Sets this color bar\'s title font.' }), titleside: { @@ -17771,7 +17990,7 @@ var _$attributes_412 = __overrideAll_412({ 'use strict'; -var _$attributes_417 = { +var _$attributes_479 = { zauto: { valType: 'boolean', role: 'info', @@ -17855,9 +18074,9 @@ var _$attributes_417 = { 'use strict'; -/* removed: var _$attributes_417 = require('./attributes'); */; -var __extendFlat_419 = _$extend_528.extendFlat; -/* removed: var _$scales_430 = require('./scales.js'); */; +/* removed: var _$attributes_479 = require('./attributes'); */; +var __extendFlat_481 = _$extend_590.extendFlat; +/* removed: var _$scales_492 = require('./scales.js'); */; /* * Make all the attributes for a regular colorscale: @@ -17873,7 +18092,7 @@ var __extendFlat_419 = _$extend_528.extendFlat; * * @return {object} the finished attributes object */ -var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) { +var _$makeColorScaleAttributes_481 = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) { var contextHead = context ? (context + '.') : ''; return { @@ -17889,7 +18108,7 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, '`cmin` and `cmax` if set.' ].join(' ') }, - colorscale: __extendFlat_419({}, _$attributes_417.colorscale, { + colorscale: __extendFlat_481({}, _$attributes_479.colorscale, { description: [ 'Sets the colorscale and only has an effect', 'if `' + contextHead + 'color` is set to a numerical array.', @@ -17903,10 +18122,10 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, 'use `' + contextHead + 'cmin` and `' + contextHead + 'cmax`.', 'Alternatively, `colorscale` may be a palette name string', 'of the following list:', - Object.keys(_$scales_430).join(', ') + Object.keys(_$scales_492).join(', ') ].join(' ') }), - cauto: __extendFlat_419({}, _$attributes_417.zauto, { + cauto: __extendFlat_481({}, _$attributes_479.zauto, { impliedEdits: {cmin: undefined, cmax: undefined}, description: [ 'Has an effect only if `' + contextHead + 'color` is set to a numerical array', @@ -17917,8 +18136,8 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, 'Defaults to `false` when `cmin`, `cmax` are set by the user.' ].join(' ') }), - cmax: __extendFlat_419({}, _$attributes_417.zmax, { - editType: editTypeOverride || _$attributes_417.zmax.editType, + cmax: __extendFlat_481({}, _$attributes_479.zmax, { + editType: editTypeOverride || _$attributes_479.zmax.editType, impliedEdits: {cauto: false}, description: [ 'Has an effect only if `' + contextHead + 'color` is set to a numerical array.', @@ -17927,8 +18146,8 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, 'and if set, `' + contextHead + 'cmin` must be set as well.' ].join(' ') }), - cmin: __extendFlat_419({}, _$attributes_417.zmin, { - editType: editTypeOverride || _$attributes_417.zmin.editType, + cmin: __extendFlat_481({}, _$attributes_479.zmin, { + editType: editTypeOverride || _$attributes_479.zmin.editType, impliedEdits: {cauto: false}, description: [ 'Has an effect only if `' + contextHead + 'color` is set to a numerical array.', @@ -17937,7 +18156,7 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, 'and if set, `' + contextHead + 'cmax` must be set as well.' ].join(' ') }), - autocolorscale: __extendFlat_419({}, _$attributes_417.autocolorscale, { + autocolorscale: __extendFlat_481({}, _$attributes_479.autocolorscale, { description: [ 'Has an effect only if `' + contextHead + 'color` is set to a numerical array.', 'Determines whether the colorscale is a default palette (`autocolorscale: true`)', @@ -17946,9 +18165,9 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, 'palette will be chosen according to whether numbers in the `color` array are', 'all positive, all negative or mixed.' ].join(' '), - dflt: autoColorDflt === false ? autoColorDflt : _$attributes_417.autocolorscale.dflt + dflt: autoColorDflt === false ? autoColorDflt : _$attributes_479.autocolorscale.dflt }), - reversescale: __extendFlat_419({}, _$attributes_417.reversescale, { + reversescale: __extendFlat_481({}, _$attributes_479.reversescale, { description: [ 'Has an effect only if `' + contextHead + 'color` is set to a numerical array.', 'Reverses the color mapping if true (`cmin` will correspond to the last color', @@ -17958,7 +18177,7 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, }; }; -var _$color_411 = {}; +var _$color_473 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17970,16 +18189,16 @@ var _$color_411 = {}; 'use strict'; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -var color = _$color_411 = {}; +var color = _$color_473 = {}; -/* removed: var _$attributes_410 = require('./attributes'); */; -color.defaults = _$attributes_410.defaults; -var defaultLine = color.defaultLine = _$attributes_410.defaultLine; -color.lightLine = _$attributes_410.lightLine; -var background = color.background = _$attributes_410.background; +/* removed: var _$attributes_472 = require('./attributes'); */; +color.defaults = _$attributes_472.defaults; +var defaultLine = color.defaultLine = _$attributes_472.defaultLine; +color.lightLine = _$attributes_472.lightLine; +var background = color.background = _$attributes_472.background; /* * tinyRGB: turn a tinycolor into an rgb string, but @@ -17991,12 +18210,12 @@ color.tinyRGB = function(tc) { Math.round(c.g) + ', ' + Math.round(c.b) + ')'; }; -color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_352(cstr)); }; +color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_414(cstr)); }; -color.opacity = function(cstr) { return cstr ? _$tinycolor_352(cstr).getAlpha() : 0; }; +color.opacity = function(cstr) { return cstr ? _$tinycolor_414(cstr).getAlpha() : 0; }; color.addOpacity = function(cstr, op) { - var c = _$tinycolor_352(cstr).toRgb(); + var c = _$tinycolor_414(cstr).toRgb(); return 'rgba(' + Math.round(c.r) + ', ' + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; }; @@ -18005,10 +18224,10 @@ color.addOpacity = function(cstr, op) { // if back has transparency or is missing, // color.background is assumed behind it color.combine = function(front, back) { - var fc = _$tinycolor_352(front).toRgb(); - if(fc.a === 1) return _$tinycolor_352(front).toRgbString(); + var fc = _$tinycolor_414(front).toRgb(); + if(fc.a === 1) return _$tinycolor_414(front).toRgbString(); - var bc = _$tinycolor_352(back || background).toRgb(), + var bc = _$tinycolor_414(back || background).toRgb(), bcflat = bc.a === 1 ? bc : { r: 255 * (1 - bc.a) + bc.r * bc.a, g: 255 * (1 - bc.a) + bc.g * bc.a, @@ -18019,7 +18238,7 @@ color.combine = function(front, back) { g: bcflat.g * (1 - fc.a) + fc.g * fc.a, b: bcflat.b * (1 - fc.a) + fc.b * fc.a }; - return _$tinycolor_352(fcflat).toRgbString(); + return _$tinycolor_414(fcflat).toRgbString(); }; /* @@ -18031,9 +18250,9 @@ color.combine = function(front, back) { * otherwise we go all the way to white or black. */ color.contrast = function(cstr, lightAmount, darkAmount) { - var tc = _$tinycolor_352(cstr); + var tc = _$tinycolor_414(cstr); - if(tc.getAlpha() !== 1) tc = _$tinycolor_352(color.combine(cstr, background)); + if(tc.getAlpha() !== 1) tc = _$tinycolor_414(color.combine(cstr, background)); var newColor = tc.isDark() ? (lightAmount ? tc.lighten(lightAmount) : background) : @@ -18043,12 +18262,12 @@ color.contrast = function(cstr, lightAmount, darkAmount) { }; color.stroke = function(s, c) { - var tc = _$tinycolor_352(c); + var tc = _$tinycolor_414(c); s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); }; color.fill = function(s, c) { - var tc = _$tinycolor_352(c); + var tc = _$tinycolor_414(c); s.style({ 'fill': color.tinyRGB(tc), 'fill-opacity': tc.getAlpha() @@ -18095,7 +18314,7 @@ color.clean = function(container) { }; function cleanOne(val) { - if(_$fastIsnumeric_139(val) || typeof val !== 'string') return val; + if(_$fastIsnumeric_196(val) || typeof val !== 'string') return val; var valTrim = val.trim(); if(valTrim.substr(0, 3) !== 'rgb') return val; @@ -18140,7 +18359,7 @@ function cleanOne(val) { 'use strict'; -var _$flipScale_423 = function flipScale(scl) { +var _$flipScale_485 = function flipScale(scl) { var N = scl.length, sclNew = new Array(N), si; @@ -18164,18 +18383,18 @@ var _$flipScale_423 = function flipScale(scl) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$scales_430 = require('./scales'); */; -/* removed: var _$flipScale_423 = require('./flip_scale'); */; +/* removed: var _$scales_492 = require('./scales'); */; +/* removed: var _$flipScale_485 = require('./flip_scale'); */; -var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { +var _$calc_480 = function calc(trace, vals, containerStr, cLetter) { var container, inputContainer; if(containerStr) { - container = _$lib_539.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_539.nestedProperty(trace._input, containerStr).get(); + container = _$lib_601.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_601.nestedProperty(trace._input, containerStr).get(); } else { container = trace; @@ -18191,11 +18410,11 @@ var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { scl = container.colorscale; if(auto !== false || min === undefined) { - min = _$lib_539.aggNums(Math.min, null, vals); + min = _$lib_601.aggNums(Math.min, null, vals); } if(auto !== false || max === undefined) { - max = _$lib_539.aggNums(Math.max, null, vals); + max = _$lib_601.aggNums(Math.max, null, vals); } if(min === max) { @@ -18220,13 +18439,13 @@ var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { (min === undefined && max === undefined)); if(container.autocolorscale) { - if(min * max < 0) scl = _$scales_430.RdBu; - else if(min >= 0) scl = _$scales_430.Reds; - else scl = _$scales_430.Blues; + if(min * max < 0) scl = _$scales_492.RdBu; + else if(min >= 0) scl = _$scales_492.Reds; + else scl = _$scales_492.Blues; // reversescale is handled at the containerOut level inputContainer.colorscale = scl; - if(container.reversescale) scl = _$flipScale_423(scl); + if(container.reversescale) scl = _$flipScale_485(scl); container.colorscale = scl; } }; @@ -18242,10 +18461,10 @@ var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; -var _$handleTickLabelDefaults_604 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { +var _$handleTickLabelDefaults_666 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); var tickPrefix = coerce('tickprefix'); @@ -18261,7 +18480,7 @@ var _$handleTickLabelDefaults_604 = function handleTickLabelDefaults(containerIn // explicitly provided var dfltFontColor = (containerOut.color === containerIn.color) ? containerOut.color : font.color; - _$lib_539.coerceFont(coerce, 'tickfont', { + _$lib_601.coerceFont(coerce, 'tickfont', { family: font.family, size: font.size, color: dfltFontColor @@ -18319,7 +18538,7 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_539.coerce(valueIn, valueOut, _$layout_attributes_596.tickformatstops, attr, dflt); + return _$lib_601.coerce(valueIn, valueOut, _$layout_attributes_659.tickformatstops, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -18344,18 +18563,18 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; /** * options: inherits outerTicks from axes.handleAxisDefaults */ -var _$handleTickDefaults_605 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_539.coerce2(containerIn, containerOut, _$layout_attributes_596, 'ticklen'), - tickWidth = _$lib_539.coerce2(containerIn, containerOut, _$layout_attributes_596, 'tickwidth'), - tickColor = _$lib_539.coerce2(containerIn, containerOut, _$layout_attributes_596, 'tickcolor', containerOut.color), +var _$handleTickDefaults_667 = function handleTickDefaults(containerIn, containerOut, coerce, options) { + var tickLen = _$lib_601.coerce2(containerIn, containerOut, _$layout_attributes_659, 'ticklen'), + tickWidth = _$lib_601.coerce2(containerIn, containerOut, _$layout_attributes_659, 'tickwidth'), + tickColor = _$lib_601.coerce2(containerIn, containerOut, _$layout_attributes_659, 'tickcolor', containerOut.color), showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); if(!showTicks) { @@ -18376,12 +18595,12 @@ var _$handleTickDefaults_605 = function handleTickDefaults(containerIn, containe 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __ONEDAY_606 = _$numerical_517.ONEDAY; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __ONEDAY_668 = _$numerical_578.ONEDAY; -var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { +var _$handleTickValueDefaults_668 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { var tickmodeDefault = 'auto'; if(containerIn.tickmode === 'array' && @@ -18400,9 +18619,9 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn // dtick is usually a positive number, but there are some // special strings available for log or date axes // default is 1 day for dates, otherwise 1 - var dtickDflt = (axType === 'date') ? __ONEDAY_606 : 1; + var dtickDflt = (axType === 'date') ? __ONEDAY_668 : 1; var dtick = coerce('dtick', dtickDflt); - if(_$fastIsnumeric_139(dtick)) { + if(_$fastIsnumeric_196(dtick)) { containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; } else if(typeof dtick !== 'string') { @@ -18413,7 +18632,7 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn var prefix = dtick.charAt(0), dtickNum = dtick.substr(1); - dtickNum = _$fastIsnumeric_139(dtickNum) ? Number(dtickNum) : 0; + dtickNum = _$fastIsnumeric_196(dtickNum) ? Number(dtickNum) : 0; if((dtickNum <= 0) || !( // "M" gives ticks every (integer) n months (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || @@ -18428,13 +18647,13 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn // tick0 can have different valType for different axis types, so // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_539.dateTick0(containerOut.calendar) : 0; + var tick0Dflt = (axType === 'date') ? _$lib_601.dateTick0(containerOut.calendar) : 0; var tick0 = coerce('tick0', tick0Dflt); if(axType === 'date') { - containerOut.tick0 = _$lib_539.cleanDate(tick0, tick0Dflt); + containerOut.tick0 = _$lib_601.cleanDate(tick0, tick0Dflt); } // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely - else if(_$fastIsnumeric_139(tick0) && dtick !== 'D1' && dtick !== 'D2') { + else if(_$fastIsnumeric_196(tick0) && dtick !== 'D1' && dtick !== 'D2') { containerOut.tick0 = Number(tick0); } else { @@ -18459,20 +18678,20 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_606 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('../../plots/cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../../plots/cartesian/tick_label_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('../../plots/cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../../plots/cartesian/tick_label_defaults'); */; -/* removed: var _$attributes_412 = require('./attributes'); */; +/* removed: var _$attributes_474 = require('./attributes'); */; -var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut, layout) { +var _$colorbarDefaults_476 = function colorbarDefaults(containerIn, containerOut, layout) { var colorbarOut = containerOut.colorbar = {}, colorbarIn = containerIn.colorbar || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(colorbarIn, colorbarOut, _$attributes_412, attr, dflt); + return _$lib_601.coerce(colorbarIn, colorbarOut, _$attributes_474, attr, dflt); } var thicknessmode = coerce('thicknessmode'); @@ -18493,7 +18712,7 @@ var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut coerce('y'); coerce('yanchor'); coerce('ypad'); - _$lib_539.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + _$lib_601.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); coerce('outlinecolor'); coerce('outlinewidth'); @@ -18501,14 +18720,14 @@ var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut coerce('borderwidth'); coerce('bgcolor'); - _$handleTickValueDefaults_606(colorbarIn, colorbarOut, coerce, 'linear'); + _$handleTickValueDefaults_668(colorbarIn, colorbarOut, coerce, 'linear'); var opts = {outerTicks: false, font: layout.font}; - _$handleTickLabelDefaults_604(colorbarIn, colorbarOut, coerce, 'linear', opts); - _$handleTickDefaults_605(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickLabelDefaults_666(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickDefaults_667(colorbarIn, colorbarOut, coerce, 'linear', opts); coerce('title', layout._dfltTitle.colorbar); - _$lib_539.coerceFont(coerce, 'titlefont', layout.font); + _$lib_601.coerceFont(coerce, 'titlefont', layout.font); coerce('titleside'); }; @@ -18523,11 +18742,11 @@ var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$hasColorbar_416 = function hasColorbar(container) { - return _$lib_539.isPlainObject(container.colorbar); +var _$hasColorbar_478 = function hasColorbar(container) { + return _$lib_601.isPlainObject(container.colorbar); }; /** @@ -18541,13 +18760,13 @@ var _$hasColorbar_416 = function hasColorbar(container) { 'use strict'; -/* removed: var _$scales_430 = require('./scales'); */; -/* removed: var _$isValidScaleArray_428 = require('./is_valid_scale_array'); */; +/* removed: var _$scales_492 = require('./scales'); */; +/* removed: var _$isValidScaleArray_490 = require('./is_valid_scale_array'); */; -var _$isValidScale_427 = function isValidScale(scl) { - if(_$scales_430[scl] !== undefined) return true; - else return _$isValidScaleArray_428(scl); +var _$isValidScale_489 = function isValidScale(scl) { + if(_$scales_492[scl] !== undefined) return true; + else return _$isValidScaleArray_490(scl); }; /** @@ -18561,31 +18780,31 @@ var _$isValidScale_427 = function isValidScale(scl) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$hasColorbar_416 = require('../colorbar/has_colorbar'); */; -/* removed: var _$colorbarDefaults_414 = require('../colorbar/defaults'); */; -/* removed: var _$isValidScale_427 = require('./is_valid_scale'); */; -/* removed: var _$flipScale_423 = require('./flip_scale'); */; +/* removed: var _$hasColorbar_478 = require('../colorbar/has_colorbar'); */; +/* removed: var _$colorbarDefaults_476 = require('../colorbar/defaults'); */; +/* removed: var _$isValidScale_489 = require('./is_valid_scale'); */; +/* removed: var _$flipScale_485 = require('./flip_scale'); */; -var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { +var _$colorScaleDefaults_483 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { var prefix = opts.prefix, cLetter = opts.cLetter, containerStr = prefix.slice(0, prefix.length - 1), containerIn = prefix ? - _$lib_539.nestedProperty(traceIn, containerStr).get() || {} : + _$lib_601.nestedProperty(traceIn, containerStr).get() || {} : traceIn, containerOut = prefix ? - _$lib_539.nestedProperty(traceOut, containerStr).get() || {} : + _$lib_601.nestedProperty(traceOut, containerStr).get() || {} : traceOut, minIn = containerIn[cLetter + 'min'], maxIn = containerIn[cLetter + 'max'], sclIn = containerIn.colorscale; - var validMinMax = _$fastIsnumeric_139(minIn) && _$fastIsnumeric_139(maxIn) && (minIn < maxIn); + var validMinMax = _$fastIsnumeric_196(minIn) && _$fastIsnumeric_196(maxIn) && (minIn < maxIn); coerce(prefix + cLetter + 'auto', !validMinMax); coerce(prefix + cLetter + 'min'); coerce(prefix + cLetter + 'max'); @@ -18593,13 +18812,13 @@ var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, la // handles both the trace case (autocolorscale is false by default) and // the marker and marker.line case (autocolorscale is true by default) var autoColorscaleDftl; - if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_427(sclIn); + if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_489(sclIn); coerce(prefix + 'autocolorscale', autoColorscaleDftl); var sclOut = coerce(prefix + 'colorscale'); // reversescale is handled at the containerOut level var reverseScale = coerce(prefix + 'reversescale'); - if(reverseScale) containerOut.colorscale = _$flipScale_423(sclOut); + if(reverseScale) containerOut.colorscale = _$flipScale_485(sclOut); // ... until Scatter.colorbar can handle marker line colorbars if(prefix === 'marker.line.') return; @@ -18607,10 +18826,10 @@ var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, la // handle both the trace case where the dflt is listed in attributes and // the marker case where the dflt is determined by hasColorbar var showScaleDftl; - if(prefix) showScaleDftl = _$hasColorbar_416(containerIn); + if(prefix) showScaleDftl = _$hasColorbar_478(containerIn); var showScale = coerce(prefix + 'showscale', showScaleDftl); - if(showScale) _$colorbarDefaults_414(containerIn, containerOut, layout); + if(showScale) _$colorbarDefaults_476(containerIn, containerOut, layout); }; /** @@ -18631,7 +18850,7 @@ var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, la * @param {number} cmin minimum color value (used to clamp scale) * @param {number} cmax maximum color value (used to clamp scale) */ -var _$extractScale_422 = function extractScale(scl, cmin, cmax) { +var _$extractScale_484 = function extractScale(scl, cmin, cmax) { var N = scl.length, domain = new Array(N), range = new Array(N); @@ -18659,20 +18878,20 @@ var _$extractScale_422 = function extractScale(scl, cmin, cmax) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$isValidScale_427 = require('./is_valid_scale'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$isValidScale_489 = require('./is_valid_scale'); */; -var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { +var _$hasColorscale_487 = function hasColorscale(trace, containerStr) { var container = containerStr ? - _$lib_539.nestedProperty(trace, containerStr).get() || {} : + _$lib_601.nestedProperty(trace, containerStr).get() || {} : trace; var color = container.color; var isArrayWithOneNumber = false; - if(_$lib_539.isArrayOrTypedArray(color)) { + if(_$lib_601.isArrayOrTypedArray(color)) { for(var i = 0; i < color.length; i++) { - if(_$fastIsnumeric_139(color[i])) { + if(_$fastIsnumeric_196(color[i])) { isArrayWithOneNumber = true; break; } @@ -18680,12 +18899,12 @@ var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { } return ( - _$lib_539.isPlainObject(container) && ( + _$lib_601.isPlainObject(container) && ( isArrayWithOneNumber || container.showscale === true || - (_$fastIsnumeric_139(container.cmin) && _$fastIsnumeric_139(container.cmax)) || - _$isValidScale_427(container.colorscale) || - _$lib_539.isPlainObject(container.colorbar) + (_$fastIsnumeric_196(container.cmin) && _$fastIsnumeric_196(container.cmax)) || + _$isValidScale_489(container.colorscale) || + _$lib_601.isPlainObject(container.colorbar) ) ); }; @@ -18701,11 +18920,11 @@ var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$color_473 = require('../color'); */; /** * General colorscale function generator. @@ -18720,7 +18939,7 @@ var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { * * @return {function} */ -var _$makeColorScaleFunc_429 = function makeColorScaleFunc(specs, opts) { +var _$makeColorScaleFunc_491 = function makeColorScaleFunc(specs, opts) { opts = opts || {}; var domain = specs.domain, @@ -18729,11 +18948,11 @@ var _$makeColorScaleFunc_429 = function makeColorScaleFunc(specs, opts) { _range = new Array(N); for(var i = 0; i < N; i++) { - var rgba = _$tinycolor_352(range[i]).toRgb(); + var rgba = _$tinycolor_414(range[i]).toRgb(); _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a]; } - var _sclFunc = _$d3_127.scale.linear() + var _sclFunc = _$d3_130.scale.linear() .domain(domain) .range(_range) .clamp(true); @@ -18752,16 +18971,16 @@ var _$makeColorScaleFunc_429 = function makeColorScaleFunc(specs, opts) { } else if(returnArray) { sclFunc = function(v) { - if(_$fastIsnumeric_139(v)) return _sclFunc(v); - else if(_$tinycolor_352(v).isValid()) return v; - else return _$color_411.defaultLine; + if(_$fastIsnumeric_196(v)) return _sclFunc(v); + else if(_$tinycolor_414(v).isValid()) return v; + else return _$color_473.defaultLine; }; } else { sclFunc = function(v) { - if(_$fastIsnumeric_139(v)) return colorArray2rbga(_sclFunc(v)); - else if(_$tinycolor_352(v).isValid()) return v; - else return _$color_411.defaultLine; + if(_$fastIsnumeric_196(v)) return colorArray2rbga(_sclFunc(v)); + else if(_$tinycolor_414(v).isValid()) return v; + else return _$color_473.defaultLine; }; } @@ -18782,10 +19001,10 @@ function colorArray2rbga(colorArray) { a: colorArray[3] }; - return _$tinycolor_352(colorObj).toRgbString(); + return _$tinycolor_414(colorObj).toRgbString(); } -var _$colorscale_426 = {}; +var _$colorscale_488 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18797,27 +19016,27 @@ var _$colorscale_426 = {}; 'use strict'; -_$colorscale_426.scales = _$scales_430; +_$colorscale_488.scales = _$scales_492; -_$colorscale_426.defaultScale = _$default_scale_420; +_$colorscale_488.defaultScale = _$default_scale_482; -_$colorscale_426.attributes = _$attributes_417; +_$colorscale_488.attributes = _$attributes_479; -_$colorscale_426.handleDefaults = _$colorScaleDefaults_421; +_$colorscale_488.handleDefaults = _$colorScaleDefaults_483; -_$colorscale_426.calc = _$calc_418; +_$colorscale_488.calc = _$calc_480; -_$colorscale_426.hasColorscale = _$hasColorscale_425; +_$colorscale_488.hasColorscale = _$hasColorscale_487; -_$colorscale_426.isValidScale = _$isValidScale_427; +_$colorscale_488.isValidScale = _$isValidScale_489; -_$colorscale_426.getScale = _$getScale_424; +_$colorscale_488.getScale = _$getScale_486; -_$colorscale_426.flipScale = _$flipScale_423; +_$colorscale_488.flipScale = _$flipScale_485; -_$colorscale_426.extractScale = _$extractScale_422; +_$colorscale_488.extractScale = _$extractScale_484; -_$colorscale_426.makeColorScaleFunc = _$makeColorScaleFunc_429; +_$colorscale_488.makeColorScaleFunc = _$makeColorScaleFunc_491; /** * Copyright 2012-2018, Plotly, Inc. @@ -18830,7 +19049,7 @@ _$colorscale_426.makeColorScaleFunc = _$makeColorScaleFunc_429; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; /** Marker symbol definitions * users can specify markers either by number or name @@ -18840,11 +19059,11 @@ _$colorscale_426.makeColorScaleFunc = _$makeColorScaleFunc_429; * add both and you get both */ -var _$symbol_defs_437 = { +var _$symbol_defs_499 = { circle: { n: 0, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; } @@ -18852,22 +19071,22 @@ var _$symbol_defs_437 = { square: { n: 1, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; } }, diamond: { n: 2, f: function(r) { - var rd = _$d3_127.round(r * 1.3, 2); + var rd = _$d3_130.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z'; } }, cross: { n: 3, f: function(r) { - var rc = _$d3_127.round(r * 0.4, 2), - rc2 = _$d3_127.round(r * 1.2, 2); + var rc = _$d3_130.round(r * 0.4, 2), + rc2 = _$d3_130.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'; @@ -18876,7 +19095,7 @@ var _$symbol_defs_437 = { x: { n: 4, f: function(r) { - var rx = _$d3_127.round(r * 0.8 / Math.sqrt(2), 2), + var rx = _$d3_130.round(r * 0.8 / Math.sqrt(2), 2), ne = 'l' + rx + ',' + rx, se = 'l' + rx + ',-' + rx, sw = 'l-' + rx + ',-' + rx, @@ -18887,79 +19106,79 @@ var _$symbol_defs_437 = { 'triangle-up': { n: 5, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z'; } }, 'triangle-down': { n: 6, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z'; } }, 'triangle-left': { n: 7, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z'; } }, 'triangle-right': { n: 8, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z'; } }, 'triangle-ne': { n: 9, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z'; } }, 'triangle-se': { n: 10, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z'; } }, 'triangle-sw': { n: 11, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z'; } }, 'triangle-nw': { n: 12, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z'; } }, pentagon: { n: 13, f: function(r) { - var x1 = _$d3_127.round(r * 0.951, 2), - x2 = _$d3_127.round(r * 0.588, 2), - y0 = _$d3_127.round(-r, 2), - y1 = _$d3_127.round(r * -0.309, 2), - y2 = _$d3_127.round(r * 0.809, 2); + var x1 = _$d3_130.round(r * 0.951, 2), + x2 = _$d3_130.round(r * 0.588, 2), + y0 = _$d3_130.round(-r, 2), + y1 = _$d3_130.round(r * -0.309, 2), + y2 = _$d3_130.round(r * 0.809, 2); return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 + 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z'; } @@ -18967,9 +19186,9 @@ var _$symbol_defs_437 = { hexagon: { n: 14, f: function(r) { - var y0 = _$d3_127.round(r, 2), - y1 = _$d3_127.round(r / 2, 2), - x = _$d3_127.round(r * Math.sqrt(3) / 2, 2); + var y0 = _$d3_130.round(r, 2), + y1 = _$d3_130.round(r / 2, 2), + x = _$d3_130.round(r * Math.sqrt(3) / 2, 2); return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 + 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z'; } @@ -18977,9 +19196,9 @@ var _$symbol_defs_437 = { hexagon2: { n: 15, f: function(r) { - var x0 = _$d3_127.round(r, 2), - x1 = _$d3_127.round(r / 2, 2), - y = _$d3_127.round(r * Math.sqrt(3) / 2, 2); + var x0 = _$d3_130.round(r, 2), + x1 = _$d3_130.round(r / 2, 2), + y = _$d3_130.round(r * Math.sqrt(3) / 2, 2); return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 + ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z'; } @@ -18987,8 +19206,8 @@ var _$symbol_defs_437 = { octagon: { n: 16, f: function(r) { - var a = _$d3_127.round(r * 0.924, 2), - b = _$d3_127.round(r * 0.383, 2); + var a = _$d3_130.round(r * 0.924, 2), + b = _$d3_130.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'; } @@ -18997,15 +19216,15 @@ var _$symbol_defs_437 = { n: 17, f: function(r) { var rs = r * 1.4, - x1 = _$d3_127.round(rs * 0.225, 2), - x2 = _$d3_127.round(rs * 0.951, 2), - x3 = _$d3_127.round(rs * 0.363, 2), - x4 = _$d3_127.round(rs * 0.588, 2), - y0 = _$d3_127.round(-rs, 2), - y1 = _$d3_127.round(rs * -0.309, 2), - y3 = _$d3_127.round(rs * 0.118, 2), - y4 = _$d3_127.round(rs * 0.809, 2), - y5 = _$d3_127.round(rs * 0.382, 2); + x1 = _$d3_130.round(rs * 0.225, 2), + x2 = _$d3_130.round(rs * 0.951, 2), + x3 = _$d3_130.round(rs * 0.363, 2), + x4 = _$d3_130.round(rs * 0.588, 2), + y0 = _$d3_130.round(-rs, 2), + y1 = _$d3_130.round(rs * -0.309, 2), + y3 = _$d3_130.round(rs * 0.118, 2), + y4 = _$d3_130.round(rs * 0.809, 2), + y5 = _$d3_130.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 + @@ -19015,9 +19234,9 @@ var _$symbol_defs_437 = { hexagram: { n: 18, f: function(r) { - var y = _$d3_127.round(r * 0.66, 2), - x1 = _$d3_127.round(r * 0.38, 2), - x2 = _$d3_127.round(r * 0.76, 2); + var y = _$d3_130.round(r * 0.66, 2), + x1 = _$d3_130.round(r * 0.38, 2), + x2 = _$d3_130.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 + @@ -19027,10 +19246,10 @@ var _$symbol_defs_437 = { 'star-triangle-up': { n: 19, f: function(r) { - var x = _$d3_127.round(r * Math.sqrt(3) * 0.8, 2), - y1 = _$d3_127.round(r * 0.8, 2), - y2 = _$d3_127.round(r * 1.6, 2), - rc = _$d3_127.round(r * 4, 2), + var x = _$d3_130.round(r * Math.sqrt(3) * 0.8, 2), + y1 = _$d3_130.round(r * 0.8, 2), + y2 = _$d3_130.round(r * 1.6, 2), + rc = _$d3_130.round(r * 4, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 + aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z'; @@ -19039,10 +19258,10 @@ var _$symbol_defs_437 = { 'star-triangle-down': { n: 20, f: function(r) { - var x = _$d3_127.round(r * Math.sqrt(3) * 0.8, 2), - y1 = _$d3_127.round(r * 0.8, 2), - y2 = _$d3_127.round(r * 1.6, 2), - rc = _$d3_127.round(r * 4, 2), + var x = _$d3_130.round(r * Math.sqrt(3) * 0.8, 2), + y1 = _$d3_130.round(r * 0.8, 2), + y2 = _$d3_130.round(r * 1.6, 2), + rc = _$d3_130.round(r * 4, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 + aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z'; @@ -19051,8 +19270,8 @@ var _$symbol_defs_437 = { 'star-square': { n: 21, f: function(r) { - var rp = _$d3_127.round(r * 1.1, 2), - rc = _$d3_127.round(r * 2, 2), + var rp = _$d3_130.round(r * 1.1, 2), + rc = _$d3_130.round(r * 2, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp + aPart + rp + ',' + rp + aPart + rp + ',-' + rp + @@ -19062,8 +19281,8 @@ var _$symbol_defs_437 = { 'star-diamond': { n: 22, f: function(r) { - var rp = _$d3_127.round(r * 1.4, 2), - rc = _$d3_127.round(r * 1.9, 2), + var rp = _$d3_130.round(r * 1.4, 2), + rc = _$d3_130.round(r * 1.9, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',0' + aPart + '0,' + rp + aPart + rp + ',0' + aPart + '0,-' + rp + @@ -19073,23 +19292,23 @@ var _$symbol_defs_437 = { 'diamond-tall': { n: 23, f: function(r) { - var x = _$d3_127.round(r * 0.7, 2), - y = _$d3_127.round(r * 1.4, 2); + var x = _$d3_130.round(r * 0.7, 2), + y = _$d3_130.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_127.round(r * 1.4, 2), - y = _$d3_127.round(r * 0.7, 2); + var x = _$d3_130.round(r * 1.4, 2), + y = _$d3_130.round(r * 0.7, 2); return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; } }, hourglass: { n: 25, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z'; }, noDot: true @@ -19097,7 +19316,7 @@ var _$symbol_defs_437 = { bowtie: { n: 26, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z'; }, noDot: true @@ -19105,7 +19324,7 @@ var _$symbol_defs_437 = { 'circle-cross': { n: 27, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.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'; @@ -19116,8 +19335,8 @@ var _$symbol_defs_437 = { 'circle-x': { n: 28, f: function(r) { - var rs = _$d3_127.round(r, 2), - rc = _$d3_127.round(r / Math.sqrt(2), 2); + var rs = _$d3_130.round(r, 2), + rc = _$d3_130.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 + @@ -19129,7 +19348,7 @@ var _$symbol_defs_437 = { 'square-cross': { n: 29, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; }, @@ -19139,7 +19358,7 @@ var _$symbol_defs_437 = { 'square-x': { n: 30, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.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'; @@ -19150,7 +19369,7 @@ var _$symbol_defs_437 = { 'diamond-cross': { n: 31, f: function(r) { - var rd = _$d3_127.round(r * 1.3, 2); + var rd = _$d3_130.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + 'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd; }, @@ -19160,8 +19379,8 @@ var _$symbol_defs_437 = { 'diamond-x': { n: 32, f: function(r) { - var rd = _$d3_127.round(r * 1.3, 2), - r2 = _$d3_127.round(r * 0.65, 2); + var rd = _$d3_130.round(r * 1.3, 2), + r2 = _$d3_130.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; @@ -19172,7 +19391,7 @@ var _$symbol_defs_437 = { 'cross-thin': { n: 33, f: function(r) { - var rc = _$d3_127.round(r * 1.4, 2); + var rc = _$d3_130.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc; }, needLine: true, @@ -19182,7 +19401,7 @@ var _$symbol_defs_437 = { 'x-thin': { n: 34, f: function(r) { - var rx = _$d3_127.round(r, 2); + var rx = _$d3_130.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx + 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, @@ -19193,8 +19412,8 @@ var _$symbol_defs_437 = { asterisk: { n: 35, f: function(r) { - var rc = _$d3_127.round(r * 1.2, 2); - var rs = _$d3_127.round(r * 0.85, 2); + var rc = _$d3_130.round(r * 1.2, 2); + var rs = _$d3_130.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; @@ -19206,8 +19425,8 @@ var _$symbol_defs_437 = { hash: { n: 36, f: function(r) { - var r1 = _$d3_127.round(r / 2, 2), - r2 = _$d3_127.round(r, 2); + var r1 = _$d3_130.round(r / 2, 2), + r2 = _$d3_130.round(r, 2); return 'M' + r1 + ',' + r2 + 'V-' + r2 + 'm-' + r2 + ',0V' + r2 + 'M' + r2 + ',' + r1 + 'H-' + r2 + @@ -19219,9 +19438,9 @@ var _$symbol_defs_437 = { 'y-up': { n: 37, f: function(r) { - var x = _$d3_127.round(r * 1.2, 2), - y0 = _$d3_127.round(r * 1.6, 2), - y1 = _$d3_127.round(r * 0.8, 2); + var x = _$d3_130.round(r * 1.2, 2), + y0 = _$d3_130.round(r * 1.6, 2), + y1 = _$d3_130.round(r * 0.8, 2); return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0'; }, needLine: true, @@ -19231,9 +19450,9 @@ var _$symbol_defs_437 = { 'y-down': { n: 38, f: function(r) { - var x = _$d3_127.round(r * 1.2, 2), - y0 = _$d3_127.round(r * 1.6, 2), - y1 = _$d3_127.round(r * 0.8, 2); + var x = _$d3_130.round(r * 1.2, 2), + y0 = _$d3_130.round(r * 1.6, 2), + y1 = _$d3_130.round(r * 0.8, 2); return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0'; }, needLine: true, @@ -19243,9 +19462,9 @@ var _$symbol_defs_437 = { 'y-left': { n: 39, f: function(r) { - var y = _$d3_127.round(r * 1.2, 2), - x0 = _$d3_127.round(r * 1.6, 2), - x1 = _$d3_127.round(r * 0.8, 2); + var y = _$d3_130.round(r * 1.2, 2), + x0 = _$d3_130.round(r * 1.6, 2), + x1 = _$d3_130.round(r * 0.8, 2); return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0'; }, needLine: true, @@ -19255,9 +19474,9 @@ var _$symbol_defs_437 = { 'y-right': { n: 40, f: function(r) { - var y = _$d3_127.round(r * 1.2, 2), - x0 = _$d3_127.round(r * 1.6, 2), - x1 = _$d3_127.round(r * 0.8, 2); + var y = _$d3_130.round(r * 1.2, 2), + x0 = _$d3_130.round(r * 1.6, 2), + x1 = _$d3_130.round(r * 0.8, 2); return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0'; }, needLine: true, @@ -19267,7 +19486,7 @@ var _$symbol_defs_437 = { 'line-ew': { n: 41, f: function(r) { - var rc = _$d3_127.round(r * 1.4, 2); + var rc = _$d3_130.round(r * 1.4, 2); return 'M' + rc + ',0H-' + rc; }, needLine: true, @@ -19277,7 +19496,7 @@ var _$symbol_defs_437 = { 'line-ns': { n: 42, f: function(r) { - var rc = _$d3_127.round(r * 1.4, 2); + var rc = _$d3_130.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc; }, needLine: true, @@ -19287,7 +19506,7 @@ var _$symbol_defs_437 = { 'line-ne': { n: 43, f: function(r) { - var rx = _$d3_127.round(r, 2); + var rx = _$d3_130.round(r, 2); return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, needLine: true, @@ -19297,7 +19516,7 @@ var _$symbol_defs_437 = { 'line-nw': { n: 44, f: function(r) { - var rx = _$d3_127.round(r, 2); + var rx = _$d3_130.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx; }, needLine: true, @@ -19317,7 +19536,7 @@ var _$symbol_defs_437 = { 'use strict'; // fraction of some size to get to a named position -var _$alignment_511 = { +var _$alignment_573 = { // from bottom left: this is the origin of our paper-reference // positioning system FROM_BL: { @@ -19365,7 +19584,7 @@ var _$alignment_511 = { } }; -var _$xmlns_namespaces_519 = {}; +var _$xmlns_namespaces_580 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -19378,15 +19597,15 @@ var _$xmlns_namespaces_519 = {}; 'use strict'; -_$xmlns_namespaces_519.xmlns = 'http://www.w3.org/2000/xmlns/'; -_$xmlns_namespaces_519.svg = 'http://www.w3.org/2000/svg'; -_$xmlns_namespaces_519.xlink = 'http://www.w3.org/1999/xlink'; +_$xmlns_namespaces_580.xmlns = 'http://www.w3.org/2000/xmlns/'; +_$xmlns_namespaces_580.svg = 'http://www.w3.org/2000/svg'; +_$xmlns_namespaces_580.xlink = 'http://www.w3.org/1999/xlink'; // the 'old' d3 quirk got fix in v3.5.7 // https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed -_$xmlns_namespaces_519.svgAttrs = { - xmlns: _$xmlns_namespaces_519.svg, - 'xmlns:xlink': _$xmlns_namespaces_519.xlink +_$xmlns_namespaces_580.svgAttrs = { + xmlns: _$xmlns_namespaces_580.svg, + 'xmlns:xlink': _$xmlns_namespaces_580.xlink }; /** @@ -19403,7 +19622,7 @@ _$xmlns_namespaces_519.svgAttrs = { // N.B. HTML entities are listed without the leading '&' and trailing ';' // https://www.freeformatter.com/html-entities.html -var _$string_mappings_518 = { +var _$string_mappings_579 = { entityToUnicode: { 'mu': 'μ', '#956': 'μ', @@ -19431,7 +19650,7 @@ var _$string_mappings_518 = { } }; -var _$svg_text_utils_562 = {}; +var _$svg_text_utils_625 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -19445,12 +19664,12 @@ var _$svg_text_utils_562 = {}; /* global MathJax:false */ -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$xmlns_namespaces_519 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$string_mappings_518 = require('../constants/string_mappings'); */; -var LINE_SPACING = _$alignment_511.LINE_SPACING; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$xmlns_namespaces_580 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$string_mappings_579 = require('../constants/string_mappings'); */; +var LINE_SPACING = _$alignment_573.LINE_SPACING; // text converter @@ -19460,7 +19679,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_562.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_625.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) @@ -19469,7 +19688,7 @@ _$svg_text_utils_562.convertToTspans = function(_context, gd, _callback) { (typeof MathJax !== 'undefined') && str.match(FIND_TEX); - var parent = _$d3_127.select(_context.node().parentNode); + var parent = _$d3_130.select(_context.node().parentNode); if(parent.empty()) return; var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text'; svgClass += '-math'; @@ -19503,7 +19722,7 @@ _$svg_text_utils_562.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_562.positionText(_context); + _$svg_text_utils_625.positionText(_context); if(_callback) _callback.call(_context); } @@ -19598,18 +19817,18 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_539.randstr([], 64); - var tmpDiv = _$d3_127.select('body').append('div') + var randomID = 'math-output-' + _$lib_601.randstr([], 64); + var tmpDiv = _$d3_130.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) .style({'font-size': _config.fontSize + 'px'}) .text(cleanEscapesForTex(_texString)); MathJax.Hub.Queue(['Typeset', MathJax.Hub, tmpDiv.node()], function() { - var glyphDefs = _$d3_127.select('body').select('#MathJax_SVG_glyphs'); + var glyphDefs = _$d3_130.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_539.log('There was an error in the tex syntax.', _texString); + _$lib_601.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -19657,10 +19876,10 @@ var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':']; var STRIP_TAGS = new RegExp(']*)?/?>', 'g'); -var ENTITY_TO_UNICODE = Object.keys(_$string_mappings_518.entityToUnicode).map(function(k) { +var ENTITY_TO_UNICODE = Object.keys(_$string_mappings_579.entityToUnicode).map(function(k) { return { regExp: new RegExp('&' + k + ';', 'g'), - sub: _$string_mappings_518.entityToUnicode[k] + sub: _$string_mappings_579.entityToUnicode[k] }; }); @@ -19704,7 +19923,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_562.plainText = function(_str) { +_$svg_text_utils_625.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -19758,8 +19977,8 @@ function buildSVGText(containerNode, str) { function newLine() { currentLine++; - var lineNode = document.createElementNS(_$xmlns_namespaces_519.svg, 'tspan'); - _$d3_127.select(lineNode).attr({ + var lineNode = document.createElementNS(_$xmlns_namespaces_580.svg, 'tspan'); + _$d3_130.select(lineNode).attr({ class: 'line', dy: (currentLine * LINE_SPACING) + 'em' }); @@ -19805,15 +20024,15 @@ function buildSVGText(containerNode, str) { if(nodeSpec.style) nodeAttrs.style = nodeSpec.style; - var newNode = document.createElementNS(_$xmlns_namespaces_519.svg, nodeType); + var newNode = document.createElementNS(_$xmlns_namespaces_580.svg, nodeType); if(type === 'sup' || type === 'sub') { addTextNode(currentNode, ZERO_WIDTH_SPACE); currentNode.appendChild(newNode); - var resetter = document.createElementNS(_$xmlns_namespaces_519.svg, 'tspan'); + var resetter = document.createElementNS(_$xmlns_namespaces_580.svg, 'tspan'); addTextNode(resetter, ZERO_WIDTH_SPACE); - _$d3_127.select(resetter).attr('dy', RESET_DY[type]); + _$d3_130.select(resetter).attr('dy', RESET_DY[type]); nodeAttrs.dy = SHIFT_DY[type]; currentNode.appendChild(newNode); @@ -19823,7 +20042,7 @@ function buildSVGText(containerNode, str) { currentNode.appendChild(newNode); } - _$d3_127.select(newNode).attr(nodeAttrs); + _$d3_130.select(newNode).attr(nodeAttrs); currentNode = nodeSpec.node = newNode; nodeStack.push(nodeSpec); @@ -19837,14 +20056,14 @@ function buildSVGText(containerNode, str) { // 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_539.log('Ignoring unexpected end tag .', str); + _$lib_601.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_539.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_601.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -19903,7 +20122,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -19918,13 +20140,13 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_562.lineCount = function lineCount(s) { +_$svg_text_utils_625.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_562.positionText = function positionText(s, x, y) { +_$svg_text_utils_625.positionText = function positionText(s, x, y) { return s.each(function() { - var text = _$d3_127.select(this); + var text = _$d3_130.select(this); function setOrGet(attr, val) { if(val === undefined) { @@ -19998,10 +20220,10 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_562.makeEditable = function(context, options) { +_$svg_text_utils_625.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; - var dispatch = _$d3_127.dispatch('edit', 'input', 'cancel'); + var dispatch = _$d3_130.dispatch('edit', 'input', 'cancel'); var handlerElement = _delegate || context; context.style({'pointer-events': _delegate ? 'none' : 'all'}); @@ -20017,7 +20239,7 @@ _$svg_text_utils_562.makeEditable = function(context, options) { if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group'; else mathjaxClass = '[class*=-math-group]'; if(mathjaxClass) { - _$d3_127.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); + _$d3_130.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); } } @@ -20032,7 +20254,7 @@ _$svg_text_utils_562.makeEditable = function(context, options) { } function appendEditable() { - var plotDiv = _$d3_127.select(gd); + var plotDiv = _$d3_130.select(gd); var container = plotDiv.select('.svg-container'); var div = container.append('div'); var cStyle = context.node().style; @@ -20058,31 +20280,31 @@ _$svg_text_utils_562.makeEditable = function(context, options) { gd._editing = false; context.text(this.textContent) .style({opacity: 1}); - var svgClass = _$d3_127.select(this).attr('class'), + var svgClass = _$d3_130.select(this).attr('class'), mathjaxClass; if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group'; else mathjaxClass = '[class*=-math-group]'; if(mathjaxClass) { - _$d3_127.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); + _$d3_130.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); } var text = this.textContent; - _$d3_127.select(this).transition().duration(0).remove(); - _$d3_127.select(document).on('mouseup', null); + _$d3_130.select(this).transition().duration(0).remove(); + _$d3_130.select(document).on('mouseup', null); dispatch.edit.call(context, text); }) .on('focus', function() { var editDiv = this; gd._editing = true; - _$d3_127.select(document).on('mouseup', function() { - if(_$d3_127.event.target === editDiv) return false; + _$d3_130.select(document).on('mouseup', function() { + if(_$d3_130.event.target === editDiv) return false; if(document.activeElement === div.node()) div.node().blur(); }); }) .on('keyup', function() { - if(_$d3_127.event.which === 27) { + if(_$d3_130.event.which === 27) { gd._editing = false; context.style({opacity: 1}); - _$d3_127.select(this) + _$d3_130.select(this) .style({opacity: 0}) .on('blur', function() { return false; }) .transition().remove(); @@ -20090,11 +20312,11 @@ _$svg_text_utils_562.makeEditable = function(context, options) { } else { dispatch.input.call(context, this.textContent); - _$d3_127.select(this).call(alignHTMLWith(context, container, options)); + _$d3_130.select(this).call(alignHTMLWith(context, container, options)); } }) .on('keydown', function() { - if(_$d3_127.event.which === 13) this.blur(); + if(_$d3_130.event.which === 13) this.blur(); }) .call(selectElementContents); } @@ -20102,7 +20324,7 @@ _$svg_text_utils_562.makeEditable = function(context, options) { if(options.immediate) handleClick(); else handlerElement.on('click', handleClick); - return _$d3_127.rebind(context, dispatch, 'on'); + return _$d3_130.rebind(context, dispatch, 'on'); }; /** @@ -20116,12 +20338,12 @@ _$svg_text_utils_562.makeEditable = function(context, options) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_879 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_944 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -20140,7 +20362,7 @@ var _$makeBubbleSizeFn_879 = function makeBubbleSizeFn(trace) { var baseSize = baseFn(v / 2); // don't show non-numeric and negative sizes - return (_$fastIsnumeric_139(baseSize) && (baseSize > 0)) ? + return (_$fastIsnumeric_196(baseSize) && (baseSize > 0)) ? Math.max(baseSize, sizeMin) : 0; }; @@ -20157,17 +20379,20 @@ var _$makeBubbleSizeFn_879 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$subtypes_884 = { +var _$subtypes_949 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -20176,12 +20401,12 @@ var _$subtypes_884 = { }, isBubble: function(trace) { - return _$lib_539.isPlainObject(trace.marker) && - _$lib_539.isArrayOrTypedArray(trace.marker.size); + return _$lib_601.isPlainObject(trace.marker) && + _$lib_601.isArrayOrTypedArray(trace.marker.size); } }; -var _$drawing_436 = {}; +var _$drawing_498 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -20193,25 +20418,25 @@ var _$drawing_436 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$colorscale_426 = require('../colorscale'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$colorscale_488 = require('../colorscale'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_436 = _$alignment_511.LINE_SPACING; -var __DESELECTDIM_436 = _$interactions_516.DESELECTDIM; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_498 = _$alignment_573.LINE_SPACING; +var __DESELECTDIM_498 = _$interactions_577.DESELECTDIM; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../../traces/scatter/make_bubble_size_func'); */; -var drawing = _$drawing_436 = {}; +var drawing = _$drawing_498 = {}; // ----------------------------------------------------- // styling functions for plot elements @@ -20219,14 +20444,14 @@ var drawing = _$drawing_436 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_539.isPlainObject(family)) { + if(_$lib_601.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_411.fill, color); + if(color) s.call(_$color_473.fill, color); }; /* @@ -20256,7 +20481,7 @@ drawing.translatePoint = function(d, sel, xa, ya) { var x = xa.c2p(d.x); var y = ya.c2p(d.y); - if(_$fastIsnumeric_139(x) && _$fastIsnumeric_139(y) && sel.node()) { + if(_$fastIsnumeric_196(x) && _$fastIsnumeric_196(y) && sel.node()) { // for multiline text this works better if(sel.node().nodeName === 'text') { sel.attr('x', x).attr('y', y); @@ -20272,7 +20497,7 @@ drawing.translatePoint = function(d, sel, xa, ya) { drawing.translatePoints = function(s, xa, ya) { s.each(function(d) { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); drawing.translatePoint(d, sel, xa, ya); }); }; @@ -20298,7 +20523,7 @@ drawing.hideOutsideRangePoints = function(traceGroups, subplot, selector) { var ycalendar = trace.ycalendar; traceGroups.selectAll(selector).each(function(d) { - drawing.hideOutsideRangePoint(d, _$d3_127.select(this), xa, ya, xcalendar, ycalendar); + drawing.hideOutsideRangePoint(d, _$d3_130.select(this), xa, ya, xcalendar, ycalendar); }); }); }; @@ -20307,7 +20532,7 @@ 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 || !_$fastIsnumeric_139(lineWidth)) return dflt || 0; + if(!lineWidth || !_$fastIsnumeric_196(lineWidth)) return dflt || 0; // but not for static plots - these don't get antialiased anyway. if(gd._context.staticPlot) return lineWidth; @@ -20322,7 +20547,7 @@ drawing.singleLineStyle = function(d, s, lw, lc, ld) { lw1 = lw || line.width||0, dash = ld || line.dash || ''; - _$color_411.stroke(s, lc || line.color); + _$color_473.stroke(s, lc || line.color); drawing.dashLine(s, dash, lw1); }; @@ -20333,8 +20558,8 @@ drawing.lineGroupStyle = function(s, lw, lc, ld) { lw1 = lw || line.width||0, dash = ld || line.dash || ''; - _$d3_127.select(this) - .call(_$color_411.stroke, lc || line.color) + _$d3_130.select(this) + .call(_$color_473.stroke, lc || line.color) .call(drawing.dashLine, dash, lw1); }); }; @@ -20371,29 +20596,29 @@ drawing.dashStyle = function(dash, lineWidth) { // Same as fillGroupStyle, except in this case the selection may be a transition drawing.singleFillStyle = function(sel) { - var node = _$d3_127.select(sel.node()); + var node = _$d3_130.select(sel.node()); var data = node.data(); var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor; if(fillcolor) { - sel.call(_$color_411.fill, fillcolor); + sel.call(_$color_473.fill, fillcolor); } }; drawing.fillGroupStyle = function(s) { s.style('stroke-width', 0) .each(function(d) { - var shape = _$d3_127.select(this); + var shape = _$d3_130.select(this); try { - shape.call(_$color_411.fill, d[0].trace.fillcolor); + shape.call(_$color_473.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_539.error(e, s); + _$lib_601.error(e, s); shape.remove(); } }); }; -/* removed: var _$symbol_defs_437 = require('./symbol_defs'); */; +/* removed: var _$symbol_defs_499 = require('./symbol_defs'); */; drawing.symbolNames = []; drawing.symbolFuncs = []; @@ -20402,8 +20627,8 @@ drawing.symbolNoDot = {}; drawing.symbolNoFill = {}; drawing.symbolList = []; -Object.keys(_$symbol_defs_437).forEach(function(k) { - var symDef = _$symbol_defs_437[k]; +Object.keys(_$symbol_defs_499).forEach(function(k) { + var symDef = _$symbol_defs_499[k]; drawing.symbolList = drawing.symbolList.concat( [symDef.n, k, symDef.n + 100, k + '-open']); drawing.symbolNames[symDef.n] = k; @@ -20450,8 +20675,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_668.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_879(trace); + if(_$registry_731.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_944(trace); sel.attr('d', function(d) { var r; @@ -20460,7 +20685,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_884.isBubble(trace) ? + r = _$subtypes_949.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -20500,11 +20725,11 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_539.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_411.defaultLine; + else if(_$lib_601.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_473.defaultLine; else lineColor = markerLine.color; - if(_$lib_539.isArrayOrTypedArray(marker.color)) { - fillColor = _$color_411.defaultLine; + if(_$lib_601.isArrayOrTypedArray(marker.color)) { + fillColor = _$color_473.defaultLine; perPointGradient = true; } @@ -20515,7 +20740,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.om) { // open markers can't have zero linewidth, default to 1px, // and use fill color as stroke color - sel.call(_$color_411.stroke, fillColor) + sel.call(_$color_473.stroke, fillColor) .style({ 'stroke-width': (lineWidth || 1) + 'px', fill: 'none' @@ -20541,11 +20766,11 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL sel.call(drawing.gradient, gd, gradientID, gradientType, fillColor, gradientColor); } else { - sel.call(_$color_411.fill, fillColor); + sel.call(_$color_473.fill, fillColor); } if(lineWidth) { - sel.call(_$color_411.stroke, lineColor); + sel.call(_$color_473.stroke, lineColor); } } } @@ -20556,31 +20781,31 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_539.identity); + .data([type + color1 + color2], _$lib_601.identity); gradient.exit().remove(); gradient.enter() .append(type === 'radial' ? 'radialGradient' : 'linearGradient') .each(function() { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); if(type === 'horizontal') el.attr(HORZGRADIENT); else if(type === 'vertical') el.attr(VERTGRADIENT); el.attr('id', gradientID); - var tc1 = _$tinycolor_352(color1); - var tc2 = _$tinycolor_352(color2); + var tc1 = _$tinycolor_414(color1); + var tc2 = _$tinycolor_414(color2); el.append('stop').attr({ offset: '0%', - 'stop-color': _$color_411.tinyRGB(tc2), + 'stop-color': _$color_473.tinyRGB(tc2), 'stop-opacity': tc2.getAlpha() }); el.append('stop').attr({ offset: '100%', - 'stop-color': _$color_411.tinyRGB(tc1), + 'stop-color': _$color_473.tinyRGB(tc1), 'stop-opacity': tc1.getAlpha() }); }); @@ -20599,9 +20824,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_601.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -20621,7 +20844,7 @@ drawing.pointStyle = function(s, trace, gd) { var lineScale = drawing.tryColorscale(marker, 'line'); s.each(function(d) { - drawing.singlePointStyle(d, _$d3_127.select(this), trace, markerScale, lineScale, gd); + drawing.singlePointStyle(d, _$d3_130.select(this), trace, markerScale, lineScale, gd); }); }; @@ -20650,7 +20873,7 @@ drawing.makeSelectedPointStyleFns = function(trace) { if(smoIsDefined) return smo; } else { if(usmoIsDefined) return usmo; - return __DESELECTDIM_436 * (dmoIsDefined ? dmo : mo); + return __DESELECTDIM_498 * (dmoIsDefined ? dmo : mo); } } }; @@ -20694,22 +20917,22 @@ drawing.selectedPointStyle = function(s, trace) { var marker = trace.marker || {}; s.each(function(d) { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var mo2 = fns.opacityFn(d); if(mo2 !== undefined) pt.style('opacity', mo2); }); if(fns.colorFn) { s.each(function(d) { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var mc2 = fns.colorFn(d); - if(mc2) _$color_411.fill(pt, mc2); + if(mc2) _$color_473.fill(pt, mc2); }); } - if(_$registry_668.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_731.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var mx = d.mx || marker.symbol || 0; var mrc2 = fns.sizeFn(d); @@ -20722,22 +20945,22 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_539.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_601.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_539.isArrayOrTypedArray(colorArray)) { - return _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale(scl, cont.cmin, cont.cmax) + if(scl && _$lib_601.isArrayOrTypedArray(colorArray)) { + return _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_539.identity; + else return _$lib_601.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; function textPointPosition(s, textPosition, fontSize, markerRadius) { - var group = _$d3_127.select(s.node().parentNode); + var group = _$d3_130.select(s.node().parentNode); var v = textPosition.indexOf('top') !== -1 ? 'top' : @@ -20751,7 +20974,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_562.lineCount(s) - 1) * __LINE_SPACING_436 + 1; + var numLines = (_$svg_text_utils_625.lineCount(s) - 1) * __LINE_SPACING_498 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -20763,14 +20986,14 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { function extracTextFontSize(d, trace) { var fontSize = d.ts || trace.textfont.size; - return (_$fastIsnumeric_139(fontSize) && fontSize > 0) ? fontSize : 0; + return (_$fastIsnumeric_196(fontSize) && fontSize > 0) ? fontSize : 0; } // draw text at points drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { - var p = _$d3_127.select(this); - var text = _$lib_539.extractOption(d, trace, 'tx', 'text'); + var p = _$d3_130.select(this); + var text = _$lib_601.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -20785,7 +21008,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_562.convertToTspans, gd) + .call(_$svg_text_utils_625.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -20797,7 +21020,7 @@ drawing.selectedTextStyle = function(s, trace) { var unselectedAttrs = trace.unselected || {}; s.each(function(d) { - var tx = _$d3_127.select(this); + var tx = _$d3_130.select(this); var tc = d.tc || trace.textfont.color; var tp = d.tp || trace.textposition; var fontSize = extracTextFontSize(d, trace); @@ -20809,10 +21032,10 @@ drawing.selectedTextStyle = function(s, trace) { if(stc) tc2 = stc; } else { if(utc) tc2 = utc; - else if(!stc) tc2 = _$color_411.addOpacity(tc, __DESELECTDIM_436); + else if(!stc) tc2 = _$color_473.addOpacity(tc, __DESELECTDIM_498); } - if(tc2) _$color_411.fill(tx, tc2); + if(tc2) _$color_473.fill(tx, tc2); textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc); }); }; @@ -20869,11 +21092,11 @@ function makeTangent(prevpt, thispt, nextpt, smoothness) { denom2 = 3 * d1a * (d1a + d2a); return [ [ - _$d3_127.round(thispt[0] + (denom1 && numx / denom1), 2), - _$d3_127.round(thispt[1] + (denom1 && numy / denom1), 2) + _$d3_130.round(thispt[0] + (denom1 && numx / denom1), 2), + _$d3_130.round(thispt[1] + (denom1 && numy / denom1), 2) ], [ - _$d3_127.round(thispt[0] - (denom2 && numx / denom2), 2), - _$d3_127.round(thispt[1] - (denom2 && numy / denom2), 2) + _$d3_130.round(thispt[0] - (denom2 && numx / denom2), 2), + _$d3_130.round(thispt[1] - (denom2 && numy / denom2), 2) ] ]; } @@ -20882,27 +21105,27 @@ function makeTangent(prevpt, thispt, nextpt, smoothness) { // with the given step shape var STEPPATH = { hv: function(p0, p1) { - return 'H' + _$d3_127.round(p1[0], 2) + 'V' + _$d3_127.round(p1[1], 2); + return 'H' + _$d3_130.round(p1[0], 2) + 'V' + _$d3_130.round(p1[1], 2); }, vh: function(p0, p1) { - return 'V' + _$d3_127.round(p1[1], 2) + 'H' + _$d3_127.round(p1[0], 2); + return 'V' + _$d3_130.round(p1[1], 2) + 'H' + _$d3_130.round(p1[0], 2); }, hvh: function(p0, p1) { - return 'H' + _$d3_127.round((p0[0] + p1[0]) / 2, 2) + 'V' + - _$d3_127.round(p1[1], 2) + 'H' + _$d3_127.round(p1[0], 2); + return 'H' + _$d3_130.round((p0[0] + p1[0]) / 2, 2) + 'V' + + _$d3_130.round(p1[1], 2) + 'H' + _$d3_130.round(p1[0], 2); }, vhv: function(p0, p1) { - return 'V' + _$d3_127.round((p0[1] + p1[1]) / 2, 2) + 'H' + - _$d3_127.round(p1[0], 2) + 'V' + _$d3_127.round(p1[1], 2); + return 'V' + _$d3_130.round((p0[1] + p1[1]) / 2, 2) + 'H' + + _$d3_130.round(p1[0], 2) + 'V' + _$d3_130.round(p1[1], 2); } }; var STEPLINEAR = function(p0, p1) { - return 'L' + _$d3_127.round(p1[0], 2) + ',' + _$d3_127.round(p1[1], 2); + return 'L' + _$d3_130.round(p1[0], 2) + ',' + _$d3_130.round(p1[1], 2); }; drawing.steps = function(shape) { var onestep = STEPPATH[shape] || STEPLINEAR; return function(pts) { - var path = 'M' + _$d3_127.round(pts[0][0], 2) + ',' + _$d3_127.round(pts[0][1], 2); + var path = 'M' + _$d3_130.round(pts[0][0], 2) + ',' + _$d3_130.round(pts[0][1], 2); for(var i = 1; i < pts.length; i++) { path += onestep(pts[i - 1], pts[i]); } @@ -20913,33 +21136,28 @@ drawing.steps = function(shape) { // 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 = _$d3_127.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_519.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_601.ensureSingleById(_$d3_130.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_580.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_601.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; @@ -20984,7 +21202,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_539.extendFlat({}, out); + if(out) return _$lib_601.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -21028,7 +21246,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_539.extendFlat({}, out); + if(out) return _$lib_601.extendFlat({}, out); } } var testNode, tester; @@ -21044,9 +21262,9 @@ drawing.bBox = function(node, inTester, hash) { } // standardize its position (and newline tspans if any) - _$d3_127.select(testNode) + _$d3_130.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_562.positionText, 0, 0); + .call(_$svg_text_utils_625.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -21076,7 +21294,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_539.extendFlat({}, bb); + return _$lib_601.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -21101,15 +21319,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_127.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_130.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -21219,7 +21443,7 @@ var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/; drawing.setTextPointsScale = function(selection, xScale, yScale) { selection.each(function() { var transforms; - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var text = el.select('text'); if(!text.node()) return; @@ -21258,7 +21482,7 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -var _$constants_868 = { +var _$constants_933 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -21283,16 +21507,16 @@ var _$constants_868 = { 'use strict'; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __dash_862 = _$attributes_435.dash; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __dash_927 = _$attributes_497.dash; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$constants_868 = require('./constants'); */; -var __extendFlat_862 = _$extend_528.extendFlat; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$constants_933 = require('./constants'); */; +var __extendFlat_927 = _$extend_590.extendFlat; -var _$attributes_862 = { +var _$attributes_927 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -21389,7 +21613,7 @@ var _$attributes_862 = { 'If the provided `mode` includes *text* then the `text` elements', 'appear at the coordinates. Otherwise, the `text` elements', 'appear on hover.', - 'If there are less than ' + _$constants_868.PTS_LINESONLY + ' points,', + 'If there are less than ' + _$constants_933.PTS_LINESONLY + ' points,', 'then the default is *lines+markers*. Otherwise, *lines*.' ].join(' ') }, @@ -21445,7 +21669,7 @@ var _$attributes_862 = { '*0* corresponds to no smoothing (equivalent to a *linear* shape).' ].join(' ') }, - dash: __extendFlat_862({}, __dash_862, {editType: 'style'}), + dash: __extendFlat_927({}, __dash_927, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -21517,10 +21741,10 @@ var _$attributes_862 = { 'marker color, or marker line color, whichever is available.' ].join(' ') }, - marker: __extendFlat_862({ + marker: __extendFlat_927({ symbol: { valType: 'enumerated', - values: _$drawing_436.symbolList, + values: _$drawing_498.symbolList, dflt: 'circle', arrayOk: true, role: 'style', @@ -21607,9 +21831,9 @@ var _$attributes_862 = { 'Determines whether or not a colorbar is displayed.' ].join(' ') }, - colorbar: _$attributes_412, + colorbar: _$attributes_474, - line: __extendFlat_862({ + line: __extendFlat_927({ width: { valType: 'number', min: 0, @@ -21620,7 +21844,7 @@ var _$attributes_862 = { }, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ), gradient: { type: { @@ -21649,7 +21873,7 @@ var _$attributes_862 = { }, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker') + _$makeColorScaleAttributes_481('marker') ), selected: { marker: { @@ -21740,7 +21964,7 @@ var _$attributes_862 = { 'with respects to the (x,y) coordinates.' ].join(' ') }, - textfont: _$font_attributes_611({ + textfont: _$font_attributes_673({ editType: 'calc', colorEditType: 'style', arrayOk: true, @@ -21777,12 +22001,12 @@ var _$attributes_862 = { 'use strict'; -/* removed: var _$attributes_862 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_862.marker; +/* removed: var _$attributes_927 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_927.marker; -var _$area_attributes_653 = { - r: _$attributes_862.r, - t: _$attributes_862.t, +var _$area_attributes_715 = { + r: _$attributes_927.r, + t: _$attributes_927.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -21803,11 +22027,11 @@ var _$area_attributes_653 = { 'use strict'; -/* removed: var _$layout_attributes_596 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_654 = _$extend_528.extendFlat; -var __overrideAll_654 = _$edit_types_569.overrideAll; +/* removed: var _$layout_attributes_659 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_716 = _$extend_590.extendFlat; +var __overrideAll_716 = _$edit_types_632.overrideAll; -var domainAttr = __extendFlat_654({}, _$layout_attributes_596.domain, { +var domainAttr = __extendFlat_716({}, _$layout_attributes_659.domain, { description: [ 'Polar chart subplots are not supported yet.', 'This key has currently no effect.' @@ -21878,10 +22102,10 @@ function mergeAttrs(axisName, nonCommonAttrs) { } }; - return __extendFlat_654({}, nonCommonAttrs, commonAttrs); + return __extendFlat_716({}, nonCommonAttrs, commonAttrs); } -var _$axis_attributes_654 = __overrideAll_654({ +var _$axis_attributes_716 = __overrideAll_716({ radialaxis: mergeAttrs('radial', { range: { valType: 'info_array', @@ -21942,7 +22166,7 @@ var _$axis_attributes_654 = __overrideAll_654({ } }, 'plot', 'nested'); -var _$plot_schema_575 = {}; +var _$plot_schema_638 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21954,22 +22178,23 @@ var _$plot_schema_575 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; -/* removed: var _$attributes_581 = require('../plots/attributes'); */; -/* removed: var _$layout_attributes_638 = require('../plots/layout_attributes'); */; -/* removed: var _$frame_attributes_612 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_579 = require('../plots/animation_attributes'); */; +/* removed: var _$attributes_644 = require('../plots/attributes'); */; +/* removed: var _$layout_attributes_700 = require('../plots/layout_attributes'); */; +/* removed: var _$frame_attributes_674 = require('../plots/frame_attributes'); */; +/* removed: var _$animation_attributes_642 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet -/* removed: var _$area_attributes_653 = require('../plots/polar/legacy/area_attributes'); */; -/* removed: var _$axis_attributes_654 = require('../plots/polar/legacy/axis_attributes'); */; +/* removed: var _$area_attributes_715 = require('../plots/polar/legacy/area_attributes'); */; +/* removed: var _$axis_attributes_716 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_569 = require('./edit_types'); */; +/* removed: var _$edit_types_632 = require('./edit_types'); */; -var __extendFlat_575 = _$lib_539.extendFlat; -var __extendDeepAll_575 = _$lib_539.extendDeepAll; +var __extendFlat_638 = _$lib_601.extendFlat; +var __extendDeepAll_638 = _$lib_601.extendDeepAll; +var __isPlainObject_638 = _$lib_601.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -21977,10 +22202,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_575.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_575.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_575.DEPRECATED = DEPRECATED; -_$plot_schema_575.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_638.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_638.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_638.DEPRECATED = DEPRECATED; +_$plot_schema_638.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -21993,26 +22218,26 @@ _$plot_schema_575.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_575.get = function() { +_$plot_schema_638.get = function() { var traces = {}; - _$registry_668.allTypes.concat('area').forEach(function(type) { + _$registry_731.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_668.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_731.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_539.valObjectMeta, + valObjects: _$lib_601.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_569.traces, - layout: _$edit_types_569.layout + traces: _$edit_types_632.traces, + layout: _$edit_types_632.layout }, impliedEdits: { description: [ @@ -22040,7 +22265,7 @@ _$plot_schema_575.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_579) + animation: formatAttributes(_$animation_attributes_642) }; }; @@ -22071,7 +22296,7 @@ _$plot_schema_575.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_575.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_638.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -22083,10 +22308,10 @@ _$plot_schema_575.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_575.isValObject(attr)) return; + if(_$plot_schema_638.isValObject(attr)) return; - if(_$lib_539.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_575.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_638(attr) && attrName !== 'impliedEdits') { + _$plot_schema_638.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -22098,7 +22323,7 @@ _$plot_schema_575.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_575.isValObject = function(obj) { +_$plot_schema_638.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -22112,7 +22337,7 @@ _$plot_schema_575.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_575.findArrayAttributes = function(trace) { +_$plot_schema_638.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -22135,8 +22360,8 @@ _$plot_schema_575.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_539.nestedProperty(trace, astr).get(); - if(!_$lib_539.isArrayOrTypedArray(val)) return; + var val = _$lib_601.nestedProperty(trace, astr).get(); + if(!_$lib_601.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -22145,9 +22370,9 @@ _$plot_schema_575.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_575.crawl(_$attributes_581, callback); + _$plot_schema_638.crawl(_$attributes_644, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_575.crawl(trace._module.attributes, callback); + _$plot_schema_638.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -22160,7 +22385,7 @@ _$plot_schema_575.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_575.crawl(module.attributes, callback, 1); + _$plot_schema_638.crawl(module.attributes, callback, 1); } } } @@ -22172,8 +22397,8 @@ _$plot_schema_575.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_575.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_539.filterUnique(arrayAttributes); + _$plot_schema_638.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_601.filterUnique(arrayAttributes); } return arrayAttributes; @@ -22194,29 +22419,30 @@ _$plot_schema_575.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_575.getTraceValObject = function(trace, parts) { +_$plot_schema_638.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_668.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_731.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } else if(trace.type === 'area') { - valObject = _$area_attributes_653[head]; + valObject = _$area_attributes_715[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_668.modules[trace.type || _$attributes_581.type.dflt] || {})._module; + if(!_module) _module = (_$registry_731.modules[trace.type || _$attributes_644.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -22231,7 +22457,7 @@ _$plot_schema_575.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_581[head]; + if(!valObject) valObject = _$attributes_644[head]; } return recurseIntoValObject(valObject, parts, i); @@ -22250,7 +22476,7 @@ _$plot_schema_575.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_575.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_638.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -22301,21 +22527,21 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_668.componentsRegistry) { - _module = _$registry_668.componentsRegistry[key]; + for(key in _$registry_731.componentsRegistry) { + _module = _$registry_731.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } } - if(head in _$layout_attributes_638) return _$layout_attributes_638[head]; + if(head in _$layout_attributes_700) return _$layout_attributes_700[head]; // Polar doesn't populate _modules or _basePlotModules // just fall back on these when the others fail if(head === 'radialaxis' || head === 'angularaxis') { - return _$axis_attributes_654[head]; + return _$axis_attributes_716[head]; } - return _$axis_attributes_654.layout[head] || false; + return _$axis_attributes_716.layout[head] || false; } function recurseIntoValObject(valObject, parts, i) { @@ -22332,7 +22558,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_539.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_638(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -22375,11 +22601,11 @@ function getTraceAttributes(type) { var _module, basePlotModule; if(type === 'area') { - _module = { attributes: _$area_attributes_653 }; + _module = { attributes: _$area_attributes_715 }; basePlotModule = {}; } else { - _module = _$registry_668.modules[type]._module, + _module = _$registry_731.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -22389,14 +22615,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_575(attributes, _$attributes_581); + __extendDeepAll_638(attributes, _$attributes_644); // module attributes - __extendDeepAll_575(attributes, _module.attributes); + __extendDeepAll_638(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_575(attributes, basePlotModule.attributes); + __extendDeepAll_638(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -22411,7 +22637,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_575(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_638(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -22423,21 +22649,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_575(layoutAttributes, _$layout_attributes_638); + __extendDeepAll_638(layoutAttributes, _$layout_attributes_700); // add base plot module layout attributes - for(key in _$registry_668.subplotsRegistry) { - _module = _$registry_668.subplotsRegistry[key]; + for(key in _$registry_731.subplotsRegistry) { + _module = _$registry_731.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -22446,8 +22671,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_668.componentsRegistry) { - _module = _$registry_668.componentsRegistry[key]; + for(key in _$registry_731.componentsRegistry) { + _module = _$registry_731.componentsRegistry[key]; var schema = _module.schema; /* @@ -22478,12 +22703,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_668.transformsRegistry[type]; - var attributes = __extendDeepAll_575({}, _module.attributes); + var _module = _$registry_731.transformsRegistry[type]; + var attributes = __extendDeepAll_638({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_668.componentsRegistry).forEach(function(k) { - var _module = _$registry_668.componentsRegistry[k]; + Object.keys(_$registry_731.componentsRegistry).forEach(function(k) { + var _module = _$registry_731.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -22499,7 +22724,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_539.extendDeepAll({}, _$frame_attributes_612) + frames: _$lib_601.extendDeepAll({}, _$frame_attributes_674) }; formatAttributes(attrs); @@ -22510,6 +22735,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -22529,7 +22755,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_575.isValObject(attr)) { + if(_$plot_schema_638.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -22541,13 +22767,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_539.isPlainObject(attr)) { + else if(__isPlainObject_638(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_575.crawl(attrs, callback); + _$plot_schema_638.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -22566,35 +22792,58 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_575.crawl(attrs, callback); + _$plot_schema_638.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_638(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_575(layoutAttributes, { - radialaxis: _$axis_attributes_654.radialaxis, - angularaxis: _$axis_attributes_654.angularaxis + __extendFlat_638(layoutAttributes, { + radialaxis: _$axis_attributes_716.radialaxis, + angularaxis: _$axis_attributes_716.angularaxis }); - __extendFlat_575(layoutAttributes, _$axis_attributes_654.layout); + __extendFlat_638(layoutAttributes, _$axis_attributes_716.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_539.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_575({}, _module.layoutAttributes); + var np = _$lib_601.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_638({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_539.nestedProperty(baseAttrs, astr); + var np = _$lib_601.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_575(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_638(np.get() || {}, newAttrs)); } -var _$axis_ids_587 = {}; +var _$axis_ids_650 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22605,30 +22854,30 @@ var _$axis_ids_587 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -/* removed: var _$constants_589 = require('./constants'); */; +/* removed: var _$constants_652 = require('./constants'); */; // 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. -_$axis_ids_587.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_589.AX_ID_PATTERN)) return; +_$axis_ids_650.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_652.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_587.name2id = function name2id(name) { - if(!name.match(_$constants_589.AX_NAME_PATTERN)) return; +_$axis_ids_650.name2id = function name2id(name) { + if(!name.match(_$constants_652.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_587.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_589.AX_ID_PATTERN)) return; +_$axis_ids_650.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_652.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -22637,11 +22886,11 @@ _$axis_ids_587.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_587.list = function(gd, axLetter, only2d) { +_$axis_ids_650.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_587.listIds(gd, axLetter); + var idList = _$axis_ids_650.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -22666,7 +22915,7 @@ _$axis_ids_587.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_587.listIds = function(gd, axLetter) { +_$axis_ids_650.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -22677,42 +22926,42 @@ _$axis_ids_587.listIds = function(gd, axLetter) { // 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 -_$axis_ids_587.getFromId = function(gd, id, type) { +_$axis_ids_650.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[_$axis_ids_587.id2name(id)]; + return fullLayout[_$axis_ids_650.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_587.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_650.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_668.traceIs(fullTrace, 'gl3d')) { + if(_$registry_731.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_587.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_650.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_587.idSort = function(id1, id2) { +_$axis_ids_650.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); }; -var _$command_609 = {}; +var _$command_671 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22723,8 +22972,8 @@ var _$command_609 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -22742,7 +22991,7 @@ var _$command_609 = {}; * A listener called when the value is changed. Receives data object * with information about the new state. */ -_$command_609.manageCommandObserver = function(gd, container, commandList, onchange) { +_$command_671.manageCommandObserver = function(gd, container, commandList, onchange) { var ret = {}; var enabled = true; @@ -22757,7 +23006,7 @@ _$command_609.manageCommandObserver = function(gd, container, commandList, oncha // Either create or just recompute this: ret.lookupTable = {}; - var binding = _$command_609.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); + var binding = _$command_671.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); if(container && container._commandObserver) { if(!binding) { @@ -22828,7 +23077,7 @@ _$command_609.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_539.log('Unable to automatically bind plot updates to API command'); + _$lib_601.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -22858,7 +23107,7 @@ _$command_609.manageCommandObserver = function(gd, container, commandList, oncha * 2. only one property may be affected * 3. the same property must be affected by all commands */ -_$command_609.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { +_$command_671.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { var i; var n = commandList.length; @@ -22876,7 +23125,7 @@ _$command_609.hasSimpleAPICommandBindings = function(gd, commandList, bindingsBy if(!method) { return false; } - var bindings = _$command_609.computeAPICommandBindings(gd, method, args); + var bindings = _$command_671.computeAPICommandBindings(gd, method, args); // Right now, handle one and *only* one property being set: if(bindings.length !== 1) { @@ -22946,7 +23195,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_539.nestedProperty(container, binding.prop).get(); + value = _$lib_601.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -22975,10 +23224,10 @@ function bindingValueHasChanged(gd, binding, cache) { * @param {array} args * A list of arguments passed to the API command */ -_$command_609.executeAPICommand = function(gd, method, args) { +_$command_671.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_668.apiMethodRegistry[method]; + var _method = _$registry_731.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -22987,12 +23236,12 @@ _$command_609.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_539.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_601.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; -_$command_609.computeAPICommandBindings = function(gd, method, args) { +_$command_671.computeAPICommandBindings = function(gd, method, args) { var bindings; if(!Array.isArray(args)) args = []; @@ -23037,7 +23286,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_539.isPlainObject(astr)) { + } else if(_$lib_601.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -23061,7 +23310,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_539.isPlainObject(astr)) { + } else if(_$lib_601.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -23127,7 +23376,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_539.isPlainObject(attr)) { + if(_$lib_601.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -23136,7 +23385,33 @@ function crawl(attrs, callback, path, depth) { }); } -var _$plots_647 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_722 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + +var _$plots_709 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -23148,56 +23423,58 @@ var _$plots_647 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$plot_schema_575 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_587 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_539 = require('../lib'); */; -var _ = _$lib_539._; -/* removed: var _$color_411 = require('../components/color'); */; -var __BADNUM_647 = _$numerical_517.BADNUM; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$plot_schema_638 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$color_473 = require('../components/color'); */; +var __BADNUM_709 = _$numerical_578.BADNUM; -var plots = _$plots_647 = {}; +/* removed: var _$axis_ids_650 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_709 = _$sort_modules_722.sortBasePlotModules; -/* removed: var _$animation_attributes_579 = require('./animation_attributes'); */; -/* removed: var _$frame_attributes_612 = require('./frame_attributes'); */; +/* removed: var _$animation_attributes_642 = require('./animation_attributes'); */; +/* removed: var _$frame_attributes_674 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_539.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_601.relinkPrivateKeys; +var _ = _$lib_601._; + +var plots = _$plots_709 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_539.extendFlat(plots, _$registry_668); +_$lib_601.extendFlat(plots, _$registry_731); -plots.attributes = _$attributes_581; +plots.attributes = _$attributes_644; plots.attributes.type.values = plots.allTypes; -plots.fontAttrs = _$font_attributes_611; -plots.layoutAttributes = _$layout_attributes_638; +plots.fontAttrs = _$font_attributes_673; +plots.layoutAttributes = _$layout_attributes_700; // TODO make this a plot attribute? plots.fontWeight = 'normal'; var transformsRegistry = plots.transformsRegistry; -/* removed: var _$command_609 = require('./command'); */; -plots.executeAPICommand = _$command_609.executeAPICommand; -plots.computeAPICommandBindings = _$command_609.computeAPICommandBindings; -plots.manageCommandObserver = _$command_609.manageCommandObserver; -plots.hasSimpleAPICommandBindings = _$command_609.hasSimpleAPICommandBindings; +/* removed: var _$command_671 = require('./command'); */; +plots.executeAPICommand = _$command_671.executeAPICommand; +plots.computeAPICommandBindings = _$command_671.computeAPICommandBindings; +plots.manageCommandObserver = _$command_671.manageCommandObserver; +plots.hasSimpleAPICommandBindings = _$command_671.hasSimpleAPICommandBindings; // in some cases the browser doesn't seem to know how big // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_668.getComponentMethod('annotations', 'draw')(gd); - _$registry_668.getComponentMethod('legend', 'draw')(gd); + _$registry_731.getComponentMethod('annotations', 'draw')(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -23210,7 +23487,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -23241,7 +23518,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_668.call('relayout', gd, {autosize: true}).then(function() { + _$registry_731.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -23271,29 +23548,24 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_601.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', - 'fill': _$color_411.defaultLine, + 'fill': _$color_473.defaultLine, 'pointer-events': 'all' }) .each(function() { - var links = _$d3_127.select(this); + var links = _$d3_130.select(this); links.append('tspan').classed('js-link-to-tool', true); links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -23358,7 +23630,7 @@ plots.sendDataToCloud = function(gd) { var baseUrl = (window.PLOTLYENV && window.PLOTLYENV.BASE_URL) || 'https://plot.ly'; - var hiddenformDiv = _$d3_127.select(gd) + var hiddenformDiv = _$d3_130.select(gd) .append('div') .attr('id', 'hiddenform') .style('display', 'none'); @@ -23431,6 +23703,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -23465,7 +23739,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -23508,12 +23781,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_731.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_601.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_601.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_601.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -23524,7 +23823,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -23533,6 +23832,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -23543,7 +23853,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -23555,17 +23865,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_587.list(gd); + var axList = _$axis_ids_650.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -23575,6 +23885,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_709); }; /** @@ -23593,7 +23906,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_668.subplotsRegistry; + var subplotsRegistry = _$registry_731.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -23606,7 +23919,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_539.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_601.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -23627,14 +23940,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_539.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_601.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_539.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_601.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -23679,7 +23992,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_668.localeRegistry; + locales = _$registry_731.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -23688,7 +24001,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_668.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_731.localeRegistry.en.format); return formatObj; } @@ -23709,7 +24022,7 @@ function getFormatter(formatObj, separators) { formatObj.decimal = separators.charAt(0); formatObj.thousands = separators.charAt(1); - return _$d3_127.locale(formatObj); + return _$d3_130.locale(formatObj); } // Create storage for all of the data related to frames and transitions: @@ -23740,30 +24053,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_731.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -23771,7 +24082,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -23843,8 +24154,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_587.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_587.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_650.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_650.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -23889,13 +24200,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_587.list(mockGd, null, true); + var axList = _$axis_ids_650.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_587.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_650.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -23917,7 +24228,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_587.getFromId(mockGd, ax.anchor); + _$axis_ids_650.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -23946,7 +24257,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_587.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_650.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -23987,17 +24298,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_575.crawl( + _$plot_schema_638.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_539.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_601.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_539.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_601.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -24019,8 +24330,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_539.pushUnique(modules, _module); - _$lib_539.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_601.pushUnique(modules, _module); + _$lib_601.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -24080,11 +24391,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_668.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_731.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_668.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_731.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -24113,7 +24424,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts || {}, optsOut, _$animation_attributes_579, attr, dflt); + return _$lib_601.coerce(opts || {}, optsOut, _$animation_attributes_642, attr, dflt); } coerce('mode'); @@ -24145,7 +24456,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts || {}, optsOut, _$animation_attributes_579.frame, attr, dflt); + return _$lib_601.coerce(opts || {}, optsOut, _$animation_attributes_642.frame, attr, dflt); } coerce('duration'); @@ -24158,7 +24469,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts || {}, optsOut, _$animation_attributes_579.transition, attr, dflt); + return _$lib_601.coerce(opts || {}, optsOut, _$animation_attributes_642.transition, attr, dflt); } coerce('duration'); @@ -24171,7 +24482,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(frameIn, frameOut, _$frame_attributes_612, attr, dflt); + return _$lib_601.coerce(frameIn, frameOut, _$frame_attributes_674, attr, dflt); } coerce('group'); @@ -24185,14 +24496,14 @@ plots.supplyFrameDefaults = function(frameIn) { }; plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) { - var colorway = layout.colorway || _$color_411.defaults; + var colorway = layout.colorway || _$color_473.defaults; var traceOut = {}, defaultColor = colorway[colorIndex % colorway.length]; var i; function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -24208,9 +24519,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -24220,18 +24531,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_539.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_601.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_539.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_601.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_539.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_601.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_539.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_601.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -24241,12 +24552,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_668.traceIs(traceOut, 'showLegend')) { + if(_$registry_731.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_668.getComponentMethod( + _$registry_731.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -24255,12 +24566,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_539.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_601.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_668.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_731.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_668.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_731.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -24304,17 +24615,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_539.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_601.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_539.pushUnique(transformModules, _module); + _$lib_601.pushUnique(transformModules, _module); } else { - transformOut = _$lib_539.extendFlat({}, transformIn); + transformOut = _$lib_601.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -24346,14 +24657,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_539.coerceFont(coerce, 'font'); + var globalFont = _$lib_601.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_539.coerceFont(coerce, 'titlefont', { + _$lib_601.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -24381,7 +24692,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_668.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_731.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -24392,12 +24703,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_668.getComponentMethod( + _$registry_731.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_668.getComponentMethod( + _$registry_731.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -24409,7 +24720,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_539.isPlotDiv(gd); + var isPlotDiv = _$lib_601.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -24423,7 +24734,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { // just hide it document.body.style.overflow = 'hidden'; } - else if(_$fastIsnumeric_139(frameMargins) && frameMargins > 0) { + else if(_$fastIsnumeric_196(frameMargins) && frameMargins > 0) { var reservedMargins = calculateReservedMargins(gd._boundingBoxMargins), reservedWidth = reservedMargins.left + reservedMargins.right, reservedHeight = reservedMargins.bottom + reservedMargins.top, @@ -24497,11 +24808,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_668.componentsRegistry; + var componentsRegistry = _$registry_731.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_668.subplotsRegistry.cartesian; + var Cartesian = _$registry_731.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -24520,13 +24831,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_668.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_731.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_539.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_601.subplotSort); } // base plot module layout defaults @@ -24598,7 +24909,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_539.clearThrottle(); + _$lib_601.clearThrottle(); // data and layout delete gd.data; @@ -24654,7 +24965,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_539.pushUnique(styleModules, _module.style); + _$lib_601.pushUnique(styleModules, _module.style); } } @@ -24763,7 +25074,7 @@ plots.doAutoMargin = function(gd) { pb = pushbottom.size; for(var k2 in pm) { - if(_$fastIsnumeric_139(pl) && pm[k2].r) { + if(_$fastIsnumeric_196(pl) && pm[k2].r) { var fr = pm[k2].r.val, pr = pm[k2].r.size; @@ -24779,7 +25090,7 @@ plots.doAutoMargin = function(gd) { } } - if(_$fastIsnumeric_139(pb) && pm[k2].t) { + if(_$fastIsnumeric_196(pb) && pm[k2].t) { var ft = pm[k2].t.val, pt = pm[k2].t.size; @@ -24809,7 +25120,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_668.call('plot', gd); + return _$registry_731.call('plot', gd); } }; @@ -24850,7 +25161,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_539.isPlainObject(d)) { + if(_$lib_601.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -24873,7 +25184,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_539.isPlainObject(d.stream)) { + if(!_$lib_601.isPlainObject(d.stream)) { continue; } } @@ -24899,7 +25210,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_539.isJSDate(d)) return _$lib_539.ms2DateTimeLocal(+d); + if(_$lib_601.isJSDate(d)) return _$lib_601.ms2DateTimeLocal(+d); return d; } @@ -25096,8 +25407,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_539.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_539.expandObjectPaths(copy); + var copy = _$lib_601.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_601.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -25105,29 +25416,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_539.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_601.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_539.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_601.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_539.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_601.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_539.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_601.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_539.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_601.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_539.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_601.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -25152,7 +25463,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_668.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_731.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -25226,7 +25537,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_539.expandObjectPaths(_$lib_539.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_601.expandObjectPaths(_$lib_601.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -25253,7 +25564,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_668.getComponentMethod('errorbars', 'calc')(gd); + _$registry_731.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -25301,7 +25612,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_668.call('redraw', gd); + return _$registry_731.call('redraw', gd); }); } @@ -25333,7 +25644,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_539.expandObjectPaths(layout); + var newLayout = _$lib_601.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -25343,7 +25654,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_539.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_601.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -25373,7 +25684,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_668.call('redraw', gd); + return _$registry_731.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -25408,7 +25719,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_539.syncOrAsync(seq, gd); + var transitionStarting = _$lib_601.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -25420,7 +25731,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_587.list(gd), + var axList = _$axis_ids_650.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -25464,7 +25775,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_575.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_638.findArrayAttributes(trace); } // add polar axes to axis list @@ -25508,14 +25819,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -25538,7 +25850,7 @@ plots.doCalcdata = function(gd, traces) { // This ensures there is a calcdata item for every trace, // even if cartesian logic doesn't handle it (for things like legends). if(!Array.isArray(cd) || !cd[0]) { - cd = [{x: __BADNUM_647, y: __BADNUM_647}]; + cd = [{x: __BADNUM_709, y: __BADNUM_709}]; } // add the trace-wide properties to the first point, @@ -25550,7 +25862,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_668.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_731.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -25601,7 +25918,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_539.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_601.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -25619,18 +25936,18 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$interactions_516 = require('../../constants/interactions'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$interactions_577 = require('../../constants/interactions'); */; -var _$titles_504 = { +var _$titles_566 = { draw: draw }; @@ -25708,10 +26025,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_601.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -25729,7 +26043,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_539.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_601.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -25751,19 +26065,19 @@ function draw(gd, titleClass, options) { titleEl.style({ 'font-family': font, - 'font-size': _$d3_127.round(fontSize, 2) + 'px', - fill: _$color_411.rgb(fontColor), - opacity: opacity * _$color_411.opacity(fontColor), - 'font-weight': _$plots_647.fontWeight + 'font-size': _$d3_130.round(fontSize, 2) + 'px', + fill: _$color_473.rgb(fontColor), + opacity: opacity * _$color_473.opacity(fontColor), + 'font-weight': _$plots_709.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); } function scootTitle(titleElIn) { - var titleGroup = _$d3_127.select(titleElIn.node().parentNode); + var titleGroup = _$d3_130.select(titleElIn.node().parentNode); if(avoid && avoid.selection && avoid.side && txt) { titleGroup.attr('transform', null); @@ -25779,8 +26093,8 @@ function draw(gd, titleClass, options) { }[avoid.side]; var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ? -1 : 1; - var pad = _$fastIsnumeric_139(avoid.pad) ? avoid.pad : 2; - var titlebb = _$drawing_436.bBox(titleGroup.node()); + var pad = _$fastIsnumeric_196(avoid.pad) ? avoid.pad : 2; + var titlebb = _$drawing_498.bBox(titleGroup.node()); var paperbb = { left: 0, top: 0, @@ -25805,9 +26119,9 @@ function draw(gd, titleClass, options) { // iterate over a set of elements (avoid.selection) // to avoid collisions with avoid.selection.each(function() { - var avoidbb = _$drawing_436.bBox(this); + var avoidbb = _$drawing_498.bBox(this); - if(_$lib_539.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_601.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -25834,12 +26148,12 @@ function draw(gd, titleClass, options) { isplaceholder = true; el.text(placeholder) .on('mouseover.opacity', function() { - _$d3_127.select(this).transition() - .duration(_$interactions_516.SHOW_PLACEHOLDER).style('opacity', 1); + _$d3_130.select(this).transition() + .duration(_$interactions_577.SHOW_PLACEHOLDER).style('opacity', 1); }) .on('mouseout.opacity', function() { - _$d3_127.select(this).transition() - .duration(_$interactions_516.HIDE_PLACEHOLDER).style('opacity', 0); + _$d3_130.select(this).transition() + .duration(_$interactions_577.HIDE_PLACEHOLDER).style('opacity', 0); }); } @@ -25847,12 +26161,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_562.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_625.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_668.call('restyle', gd, prop, text, traceIndex); + _$registry_731.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_668.call('relayout', gd, prop, text); + _$registry_731.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -25861,7 +26175,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_562.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_625.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -25880,12 +26194,12 @@ function draw(gd, titleClass, options) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __FP_SAFE_583 = _$numerical_517.FP_SAFE; +/* removed: var _$lib_601 = require('../../lib'); */; +var __FP_SAFE_646 = _$numerical_578.FP_SAFE; -var _$autorange_583 = { +var _$autorange_646 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -25930,7 +26244,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -26023,7 +26337,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_539.simpleMap(newRange, ax.l2r || Number); + return _$lib_601.simpleMap(newRange, ax.l2r || Number); } /* @@ -26055,7 +26369,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_539.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_601.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -26077,7 +26391,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_539.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_601.extendFlat({}, axeRangeOpts); } } @@ -26090,6 +26404,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -26150,14 +26466,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_583) vmax = v; + if(v > vmax && v < __FP_SAFE_646) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_583) vmin = v; - if(v > vmax && v < __FP_SAFE_583) vmax = v; + if(v < vmin && v > -__FP_SAFE_646) vmin = v; + if(v > vmax && v < __FP_SAFE_646) vmax = v; } } @@ -26167,7 +26483,7 @@ function expand(ax, data, options) { function addItem(i) { di = data[i]; - if(!_$fastIsnumeric_139(di)) return; + if(!_$fastIsnumeric_196(di)) return; ppadiplus = ppadplus(i); ppadiminus = ppadminus(i); vmin = di - vpadminus(i); @@ -26191,7 +26507,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_583 : __lessOrEqual_583; + var atLeastAsExtreme = k ? __greaterOrEqual_646 : __lessOrEqual_646; includeThis = true; /* @@ -26242,11 +26558,11 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_139(v) && Math.abs(v) < __FP_SAFE_583; + return _$fastIsnumeric_196(v) && Math.abs(v) < __FP_SAFE_646; } -function __lessOrEqual_583(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_583(v0, v1) { return v0 >= v1; } +function __lessOrEqual_646(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_646(v0, v1) { return v0 >= v1; } /** * Copyright 2012-2018, Plotly, Inc. @@ -26259,12 +26575,12 @@ function __greaterOrEqual_583(v0, v1) { return v0 >= v1; } 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_585 = _$numerical_517.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_648 = _$numerical_578.BADNUM; -var _$autoType_585 = function autoType(array, calendar) { +var _$autoType_648 = function autoType(array, calendar) { if(moreDates(array, calendar)) return 'date'; if(category(array)) return 'category'; if(linearOK(array)) return 'linear'; @@ -26277,7 +26593,7 @@ function linearOK(array) { if(!array) return false; for(var i = 0; i < array.length; i++) { - if(_$fastIsnumeric_139(array[i])) return true; + if(_$fastIsnumeric_196(array[i])) return true; } return false; @@ -26297,8 +26613,8 @@ function moreDates(a, calendar) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_539.isDateTime(ai, calendar)) dcnt += 1; - if(_$fastIsnumeric_139(ai)) ncnt += 1; + if(_$lib_601.isDateTime(ai, calendar)) dcnt += 1; + if(_$fastIsnumeric_196(ai)) ncnt += 1; } return (dcnt > ncnt * 2); @@ -26315,7 +26631,7 @@ function category(a) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_539.cleanNumber(ai) !== __BADNUM_585) curvenums++; + if(_$lib_601.cleanNumber(ai) !== __BADNUM_648) curvenums++; else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; } @@ -26333,21 +26649,21 @@ function category(a) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var cleanNumber = _$lib_539.cleanNumber; -var ms2DateTime = _$lib_539.ms2DateTime; -var dateTime2ms = _$lib_539.dateTime2ms; -var ensureNumber = _$lib_539.ensureNumber; +/* removed: var _$lib_601 = require('../../lib'); */; +var cleanNumber = _$lib_601.cleanNumber; +var ms2DateTime = _$lib_601.ms2DateTime; +var dateTime2ms = _$lib_601.dateTime2ms; +var ensureNumber = _$lib_601.ensureNumber; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var __FP_SAFE_603 = _$numerical_517.FP_SAFE; -var __BADNUM_603 = _$numerical_517.BADNUM; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var __FP_SAFE_665 = _$numerical_578.FP_SAFE; +var __BADNUM_665 = _$numerical_578.BADNUM; -/* removed: var _$constants_589 = require('./constants'); */; -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; +/* removed: var _$constants_652 = require('./constants'); */; +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; function fromLog(v) { return Math.pow(10, v); @@ -26379,7 +26695,7 @@ function fromLog(v) { * also clears the autorange bounds ._min and ._max * and the autotick constraints ._minDtick, ._forceTick0 */ -var _$setConvert_603 = function setConvert(ax, fullLayout) { +var _$setConvert_665 = function setConvert(ax, fullLayout) { fullLayout = fullLayout || {}; var axLetter = (ax._id || 'x').charAt(0); @@ -26400,7 +26716,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); } - else return __BADNUM_603; + else return __BADNUM_665; } /* @@ -26415,9 +26731,9 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { // 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_603) { - if(_$fastIsnumeric_139(v)) ms = dateTime2ms(new Date(+v)); - else return __BADNUM_603; + if(ms === __BADNUM_665) { + if(_$fastIsnumeric_196(v)) ms = dateTime2ms(new Date(+v)); + else return __BADNUM_665; } return ms; } @@ -26461,7 +26777,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { return curLength; } } - return __BADNUM_603; + return __BADNUM_665; } function getCategoryIndex(v) { @@ -26472,14 +26788,14 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { if(index !== undefined) return index; } - if(_$fastIsnumeric_139(v)) return +v; + if(_$fastIsnumeric_196(v)) return +v; } function l2p(v) { - if(!_$fastIsnumeric_139(v)) return __BADNUM_603; + if(!_$fastIsnumeric_196(v)) return __BADNUM_665; // include 2 fractional digits on pixel, for PDF zooming etc - return _$d3_127.round(ax._b + ax._m * v, 2); + return _$d3_130.round(ax._b + ax._m * v, 2); } function p2l(px) { return (px - ax._b) / ax._m; } @@ -26539,7 +26855,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { * 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_539.identity; + ax.d2r = ax.r2d = _$lib_601.identity; ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; @@ -26547,7 +26863,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { 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_539.cleanDate(v, __BADNUM_603, ax.calendar); }; + ax.cleanPos = function(v) { return _$lib_601.cleanDate(v, __BADNUM_665, ax.calendar); }; } else if(ax.type === 'category') { // d is categories (string) @@ -26604,47 +26920,47 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { if(!opts) opts = {}; if(!rangeAttr) rangeAttr = 'range'; - var range = _$lib_539.nestedProperty(ax, rangeAttr).get(); + var range = _$lib_601.nestedProperty(ax, rangeAttr).get(); var i, dflt; - if(ax.type === 'date') dflt = _$lib_539.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_589.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_589.DFLTRANGEX; + if(ax.type === 'date') dflt = _$lib_601.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_652.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_652.DFLTRANGEX; // make sure we don't later mutate the defaults dflt = dflt.slice(); if(!range || range.length !== 2) { - _$lib_539.nestedProperty(ax, rangeAttr).set(dflt); + _$lib_601.nestedProperty(ax, rangeAttr).set(dflt); return; } if(ax.type === 'date') { // check if milliseconds or js date objects are provided for range // and convert to date strings - range[0] = _$lib_539.cleanDate(range[0], __BADNUM_603, ax.calendar); - range[1] = _$lib_539.cleanDate(range[1], __BADNUM_603, ax.calendar); + range[0] = _$lib_601.cleanDate(range[0], __BADNUM_665, ax.calendar); + range[1] = _$lib_601.cleanDate(range[1], __BADNUM_665, ax.calendar); } for(i = 0; i < 2; i++) { if(ax.type === 'date') { - if(!_$lib_539.isDateTime(range[i], ax.calendar)) { + if(!_$lib_601.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_539.constrain(ax.r2l(range[0]), - _$lib_539.MIN_MS + 1000, _$lib_539.MAX_MS - 1000); + var linCenter = _$lib_601.constrain(ax.r2l(range[0]), + _$lib_601.MIN_MS + 1000, _$lib_601.MAX_MS - 1000); range[0] = ax.l2r(linCenter - 1000); range[1] = ax.l2r(linCenter + 1000); break; } } else { - if(!_$fastIsnumeric_139(range[i])) { - if(_$fastIsnumeric_139(range[1 - i])) { + if(!_$fastIsnumeric_196(range[i])) { + if(_$fastIsnumeric_196(range[1 - i])) { range[i] = range[1 - i] * (i ? 10 : 0.1); } else { @@ -26653,8 +26969,8 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { } } - if(range[i] < -__FP_SAFE_603) range[i] = -__FP_SAFE_603; - else if(range[i] > __FP_SAFE_603) range[i] = __FP_SAFE_603; + if(range[i] < -__FP_SAFE_665) range[i] = -__FP_SAFE_665; + else if(range[i] > __FP_SAFE_665) range[i] = __FP_SAFE_665; if(range[0] === range[1]) { // somewhat arbitrary: split by 1 or 1ppm, whichever is bigger @@ -26678,7 +26994,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { // make sure we have a domain (pull it in from the axis // this one is overlaying if necessary) if(ax.overlaying) { - var ax2 = _$axis_ids_587.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + var ax2 = _$axis_ids_650.getFromId({ _fullLayout: fullLayout }, ax.overlaying); ax.domain = ax2.domain; } @@ -26731,7 +27047,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { arrayIn = trace[axLetter]; len = trace._length || arrayIn.length; - if(_$lib_539.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(_$lib_601.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { if(len === arrayIn.length) { return arrayIn; } else if(arrayIn.subarray) { @@ -26765,18 +27081,22 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { return ( Array.isArray(range) && range.length === 2 && - _$fastIsnumeric_139(ax.r2l(range[0])) && - _$fastIsnumeric_139(ax.r2l(range[1])) + _$fastIsnumeric_196(ax.r2l(range[0])) && + _$fastIsnumeric_196(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]); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } }; ax.clearCalc = function() { @@ -26807,20 +27127,20 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { // 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_127.time.format.utc; + ax._dateFormat = locale ? locale.timeFormat.utc : _$d3_130.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_127.format; + ax._numFormat = locale ? locale.numberFormat : _$d3_130.format; // and for bar charts and box plots: reset forced minimum tick spacing delete ax._minDtick; delete ax._forceTick0; }; -var _$axes_584 = {}; +var _$axes_647 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -26832,47 +27152,47 @@ var _$axes_584 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$titles_504 = require('../../components/titles'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$titles_566 = require('../../components/titles'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var ONEAVGYEAR = _$numerical_517.ONEAVGYEAR; -var ONEAVGMONTH = _$numerical_517.ONEAVGMONTH; -var __ONEDAY_584 = _$numerical_517.ONEDAY; -var __ONEHOUR_584 = _$numerical_517.ONEHOUR; -var __ONEMIN_584 = _$numerical_517.ONEMIN; -var __ONESEC_584 = _$numerical_517.ONESEC; -var MINUS_SIGN = _$numerical_517.MINUS_SIGN; -var __BADNUM_584 = _$numerical_517.BADNUM; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var ONEAVGYEAR = _$numerical_578.ONEAVGYEAR; +var ONEAVGMONTH = _$numerical_578.ONEAVGMONTH; +var __ONEDAY_647 = _$numerical_578.ONEDAY; +var __ONEHOUR_647 = _$numerical_578.ONEHOUR; +var __ONEMIN_647 = _$numerical_578.ONEMIN; +var __ONESEC_647 = _$numerical_578.ONESEC; +var MINUS_SIGN = _$numerical_578.MINUS_SIGN; +var __BADNUM_647 = _$numerical_578.BADNUM; -var MID_SHIFT = _$alignment_511.MID_SHIFT; -var __LINE_SPACING_584 = _$alignment_511.LINE_SPACING; +var MID_SHIFT = _$alignment_573.MID_SHIFT; +var __LINE_SPACING_647 = _$alignment_573.LINE_SPACING; -var axes = _$axes_584 = {}; +var axes = _$axes_647 = {}; -axes.setConvert = _$setConvert_603; -/* removed: var _$autoType_585 = require('./axis_autotype'); */; +axes.setConvert = _$setConvert_665; +/* removed: var _$autoType_648 = require('./axis_autotype'); */; -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_587.id2name; -axes.name2id = _$axis_ids_587.name2id; -axes.cleanId = _$axis_ids_587.cleanId; -axes.list = _$axis_ids_587.list; -axes.listIds = _$axis_ids_587.listIds; -axes.getFromId = _$axis_ids_587.getFromId; -axes.getFromTrace = _$axis_ids_587.getFromTrace; +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_650.id2name; +axes.name2id = _$axis_ids_650.name2id; +axes.cleanId = _$axis_ids_650.cleanId; +axes.list = _$axis_ids_650.list; +axes.listIds = _$axis_ids_650.listIds; +axes.getFromId = _$axis_ids_650.getFromId; +axes.getFromTrace = _$axis_ids_650.getFromTrace; -/* removed: var _$autorange_583 = require('./autorange'); */; -axes.expand = _$autorange_583.expand; -axes.getAutoRange = _$autorange_583.getAutoRange; +/* removed: var _$autorange_646 = require('./autorange'); */; +axes.expand = _$autorange_646.expand; +axes.getAutoRange = _$autorange_646.getAutoRange; /* * find the list of possible axes to reference with an xref or yref attribute @@ -26903,7 +27223,7 @@ axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption }; // xref, yref - return _$lib_539.coerce(containerIn, containerOut, attrDef, refAttr); + return _$lib_601.coerce(containerIn, containerOut, attrDef, refAttr); }; /* @@ -26932,7 +27252,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { var cleanPos, pos; if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_539.ensureNumber; + cleanPos = _$lib_601.ensureNumber; pos = coerce(attr, dflt); } else { var ax = axes.getFromId(gd, axRef); @@ -26946,7 +27266,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { axes.cleanPosition = function(pos, gd, axRef) { var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_539.ensureNumber : + _$lib_601.ensureNumber : axes.getFromId(gd, axRef).cleanPos; return cleanPos(pos); @@ -26966,7 +27286,7 @@ var getDataConversions = axes.getDataConversions = function(gd, trace, target, t // setup the data-to-calc method. if(Array.isArray(d2cTarget)) { ax = { - type: _$autoType_585(targetArray), + type: _$autoType_648(targetArray), _categories: [] }; axes.setConvert(ax); @@ -27102,8 +27422,8 @@ axes.saveShowSpikeInitial = function(gd, overwrite) { }; axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_539.aggNums(Math.min, null, data), - dataMax = _$lib_539.aggNums(Math.max, null, data); + var dataMin = _$lib_601.aggNums(Math.min, null, data), + dataMax = _$lib_601.aggNums(Math.max, null, data); if(!calendar) calendar = ax.calendar; @@ -27123,18 +27443,18 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { // 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_539.distinctVals(data), + var distinctData = _$lib_601.distinctVals(data), msexp = Math.pow(10, Math.floor( Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_539.roundUp( + minSize = msexp * _$lib_601.roundUp( distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_539.stdev(data) / + size0 = Math.max(minSize, 2 * _$lib_601.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(!_$fastIsnumeric_139(size0)) size0 = 1; + if(!_$fastIsnumeric_196(size0)) size0 = 1; } // piggyback off autotick code to make "nice" bin sizes @@ -27148,7 +27468,7 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { else { dummyAx = { type: ax.type, - range: _$lib_539.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + range: _$lib_601.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), calendar: calendar }; } @@ -27210,7 +27530,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { for(var i = 0; i < data.length; i++) { if(data[i] % 1 === 0) intcount++; - else if(!_$fastIsnumeric_139(data[i])) blankCount++; + else if(!_$fastIsnumeric_196(data[i])) blankCount++; if(nearEdge(data[i])) edgecount++; if(nearEdge(data[i] + ax.dtick / 2)) midcount++; @@ -27247,7 +27567,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_539.findExactDates(data, calendar); + var stats = _$lib_601.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; @@ -27259,21 +27579,21 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // 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_584 * 1.5; + binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + __ONEDAY_647 * 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_584 * 15.5; + binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + __ONEDAY_647 * 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_584 / 2; + binStart -= __ONEDAY_647 / 2; } var nextBinStart = axes.tickIncrement(binStart, dtick); @@ -27288,7 +27608,7 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // ensure we have tick0, dtick, and tick rounding calculated axes.prepTicks = function(ax) { - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); // calculate max number of (auto) ticks to display based on plot size if(ax.tickmode === 'auto' || !ax.dtick) { @@ -27301,7 +27621,7 @@ axes.prepTicks = function(ax) { } else { minPx = ax._id.charAt(0) === 'y' ? 40 : 80; - nt = _$lib_539.constrain(ax._length / minPx, 4, 9) + 1; + nt = _$lib_601.constrain(ax._length / minPx, 4, 9) + 1; } // radial axes span half their domain, @@ -27336,7 +27656,7 @@ axes.prepTicks = function(ax) { // or codes to this effect for log and date scales axes.calcTicks = function calcTicks(ax) { axes.prepTicks(ax); - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.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 @@ -27404,7 +27724,7 @@ function arrayTicks(ax) { var vals = ax.tickvals, text = ax.ticktext, ticksOut = new Array(vals.length), - rng = _$lib_539.simpleMap(ax.range, ax.r2l), + rng = _$lib_601.simpleMap(ax.range, ax.r2l), r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, tickMin = Math.min(r0expanded, r1expanded), @@ -27453,7 +27773,7 @@ var roundBase10 = [2, 5, 10], roundAngles = [15, 30, 45, 90, 180]; function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_539.roundUp(roughDTick / base, roundingSet); + return base * _$lib_601.roundUp(roughDTick / base, roundingSet); } // autoTicks: calculate best guess at pleasant ticks for this axis @@ -27480,7 +27800,7 @@ axes.autoTicks = function(ax, roughDTick) { } if(ax.type === 'date') { - ax.tick0 = _$lib_539.dateTick0(ax.calendar); + ax.tick0 = _$lib_601.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; @@ -27494,21 +27814,21 @@ axes.autoTicks = function(ax, roughDTick) { roughDTick /= ONEAVGMONTH; ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); } - else if(roughX2 > __ONEDAY_584) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_584, roundDays); + else if(roughX2 > __ONEDAY_647) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_647, 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_539.dateTick0(ax.calendar, true); + ax.tick0 = _$lib_601.dateTick0(ax.calendar, true); } - else if(roughX2 > __ONEHOUR_584) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_584, roundBase24); + else if(roughX2 > __ONEHOUR_647) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_647, roundBase24); } - else if(roughX2 > __ONEMIN_584) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_584, roundBase60); + else if(roughX2 > __ONEMIN_647) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_647, roundBase60); } - else if(roughX2 > __ONESEC_584) { - ax.dtick = roundDTick(roughDTick, __ONESEC_584, roundBase60); + else if(roughX2 > __ONESEC_647) { + ax.dtick = roundDTick(roughDTick, __ONESEC_647, roundBase60); } else { // milliseconds @@ -27518,7 +27838,7 @@ axes.autoTicks = function(ax, roughDTick) { } else if(ax.type === 'log') { ax.tick0 = 0; - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); if(roughDTick > 0.7) { // only show powers of 10 @@ -27561,7 +27881,7 @@ axes.autoTicks = function(ax, roughDTick) { if(ax.dtick === 0) ax.dtick = 1; // TODO: this is from log axis histograms with autorange off - if(!_$fastIsnumeric_139(ax.dtick) && typeof ax.dtick !== 'string') { + if(!_$fastIsnumeric_196(ax.dtick) && typeof ax.dtick !== 'string') { var olddtick = ax.dtick; ax.dtick = 1; throw 'ax.dtick error: ' + String(olddtick); @@ -27577,7 +27897,7 @@ function autoTickRound(ax) { var dtick = ax.dtick; ax._tickexponent = 0; - if(!_$fastIsnumeric_139(dtick) && typeof dtick !== 'string') { + if(!_$fastIsnumeric_196(dtick) && typeof dtick !== 'string') { dtick = 1; } @@ -27599,9 +27919,9 @@ function autoTickRound(ax) { // 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_584 && tick0len <= 10) || (dtick >= __ONEDAY_584 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_584 && tick0len <= 16) || (dtick >= __ONEHOUR_584)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_584 && tick0len <= 19) || (dtick >= __ONEMIN_584)) ax._tickround = 'S'; + else if((dtick >= __ONEDAY_647 && tick0len <= 10) || (dtick >= __ONEDAY_647 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_647 && tick0len <= 16) || (dtick >= __ONEHOUR_647)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_647 && tick0len <= 19) || (dtick >= __ONEMIN_647)) 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 @@ -27610,10 +27930,10 @@ function autoTickRound(ax) { ax._tickround = Math.max(tick0len, tick1len) - 20; } } - else if(_$fastIsnumeric_139(dtick) || dtick.charAt(0) === 'L') { + else if(_$fastIsnumeric_196(dtick) || dtick.charAt(0) === 'L') { // linear or log (except D1, D2) var rng = ax.range.map(ax.r2d || Number); - if(!_$fastIsnumeric_139(dtick)) dtick = Number(dtick.substr(1)); + if(!_$fastIsnumeric_196(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); @@ -27641,14 +27961,14 @@ 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(_$fastIsnumeric_139(dtick)) return x + axSign * dtick; + if(_$fastIsnumeric_196(dtick)) return x + axSign * dtick; // everything else is a string, one character plus a number var tType = dtick.charAt(0), dtSigned = axSign * Number(dtick.substr(1)); // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_539.incrementMonth(x, dtSigned, calendar); + if(tType === 'M') return _$lib_601.incrementMonth(x, dtSigned, calendar); // Log scales: Linear, Digits else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; @@ -27658,10 +27978,10 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, x2 = x + axSign * 0.01, - frac = _$lib_539.roundUp(_$lib_539.mod(x2, 1), tickset, axrev); + frac = _$lib_601.roundUp(_$lib_601.mod(x2, 1), tickset, axrev); return Math.floor(x2) + - Math.log(_$d3_127.round(Math.pow(10, frac), 1)) / Math.LN10; + Math.log(_$d3_130.round(Math.pow(10, frac), 1)) / Math.LN10; } else throw 'unrecognized dtick ' + String(dtick); }; @@ -27669,7 +27989,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { // calculate the first tick on an axis axes.tickFirst = function(ax) { var r2l = ax.r2l || Number, - rng = _$lib_539.simpleMap(ax.range, r2l), + rng = _$lib_601.simpleMap(ax.range, r2l), axrev = rng[1] < rng[0], sRound = axrev ? Math.floor : Math.ceil, // add a tiny extra bit to make sure we get ticks @@ -27678,12 +27998,12 @@ axes.tickFirst = function(ax) { dtick = ax.dtick, tick0 = r2l(ax.tick0); - if(_$fastIsnumeric_139(dtick)) { + if(_$fastIsnumeric_196(dtick)) { var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; // make sure no ticks outside the category list if(ax.type === 'category') { - tmin = _$lib_539.constrain(tmin, 0, ax._categories.length - 1); + tmin = _$lib_601.constrain(tmin, 0, ax._categories.length - 1); } return tmin; } @@ -27713,7 +28033,7 @@ axes.tickFirst = function(ax) { t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); cnt++; } - _$lib_539.error('tickFirst did not converge', ax); + _$lib_601.error('tickFirst did not converge', ax); return t0; } @@ -27724,10 +28044,10 @@ axes.tickFirst = function(ax) { } else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_539.roundUp(_$lib_539.mod(r0, 1), tickset, axrev); + frac = _$lib_601.roundUp(_$lib_601.mod(r0, 1), tickset, axrev); return Math.floor(r0) + - Math.log(_$d3_127.round(Math.pow(10, frac), 1)) / Math.LN10; + Math.log(_$d3_130.round(Math.pow(10, frac), 1)) / Math.LN10; } else throw 'unrecognized dtick ' + String(dtick); }; @@ -27747,7 +28067,7 @@ axes.tickText = function(ax, x, hover) { tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_539.simpleMap(ax.range, ax.r2l), + var rng = _$lib_601.simpleMap(ax.range, ax.r2l), 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; @@ -27804,7 +28124,7 @@ axes.tickText = function(ax, x, hover) { * it's different from `val`. */ axes.hoverLabelText = function(ax, val, val2) { - if(val2 !== __BADNUM_584 && val2 !== val) { + if(val2 !== __BADNUM_647 && val2 !== val) { return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } @@ -27843,11 +28163,11 @@ function formatDate(ax, out, hover, extraPrecision) { if(extraPrecision) { // second or sub-second precision: extra always shows max digits. // for other fields, extra precision just adds one field. - if(_$fastIsnumeric_139(tr)) tr = 4; + if(_$fastIsnumeric_196(tr)) tr = 4; else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; } - var dateStr = _$lib_539.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + var dateStr = _$lib_601.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), headStr; var splitIndex = dateStr.indexOf('\n'); @@ -27912,7 +28232,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); } - else if(_$fastIsnumeric_139(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_539.mod(x + 0.01, 1) < 0.1))) { + else if(_$fastIsnumeric_196(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_601.mod(x + 0.01, 1) < 0.1))) { var p = Math.round(x); if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || (isSIFormat(ax.exponentformat) && beyondSI(p))) { @@ -27931,7 +28251,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { } } else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_539.mod(x, 1)))); + out.text = String(Math.round(Math.pow(10, _$lib_601.mod(x, 1)))); out.fontSize *= 0.75; } else throw 'unrecognized dtick ' + String(dtick); @@ -27986,7 +28306,7 @@ function formatAngle(ax, out, hover, extraPrecision, hideexp) { var frac = num2frac(num); if(frac[1] >= 100) { - out.text = numFormat(_$lib_539.deg2rad(out.x), ax, hideexp, extraPrecision); + out.text = numFormat(_$lib_601.deg2rad(out.x), ax, hideexp, extraPrecision); } else { var isNeg = out.x < 0; @@ -28079,7 +28399,7 @@ function numFormat(v, ax, fmtoverride, hover) { var ah = { exponentformat: exponentFormat, dtick: ax.showexponent === 'none' ? ax.dtick : - (_$fastIsnumeric_139(v) ? Math.abs(v) || 1 : 1), + (_$fastIsnumeric_196(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] @@ -28134,7 +28454,7 @@ function numFormat(v, ax, fmtoverride, hover) { if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); } // insert appropriate decimal point and thousands separator - v = _$lib_539.numSeparate(v, ax._separators, separatethousands); + v = _$lib_601.numSeparate(v, ax._separators, separatethousands); } // add exponent @@ -28308,7 +28628,7 @@ axes.makeClipPaths = function(gd) { axClips.exit().remove(); axClips.each(function(d) { - _$d3_127.select(this).select('rect').attr({ + _$d3_130.select(this).select('rect').attr({ x: d.x._offset || 0, y: d.y._offset || 0, width: d.x._length || 1, @@ -28325,9 +28645,9 @@ axes.makeClipPaths = function(gd) { // ax._rl (stored linearized range for use by zoom/pan) // or can pass in an axis object directly axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + var fullLayout = gd._fullLayout; + var ax; + var independent = false; // allow passing an independent axis object instead of id if(typeof axid === 'object') { @@ -28340,32 +28660,26 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'redraw') { fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); }); } if(!axid || axid === 'redraw') { - return _$lib_539.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return _$lib_601.syncOrAsync(axes.list(gd, '', true).map(function(ax) { return function() { if(!ax._id) return; var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_539.simpleMap(ax._r, ax.r2l); - } + ax._r = ax.range.slice(); + ax._rl = _$lib_601.simpleMap(ax._r, ax.r2l); return axDone; }; })); @@ -28375,21 +28689,22 @@ axes.doTicks = function(gd, axid, skipTitle) { // set scaling to pixels ax.setScale(); - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_436.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_436.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_436.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + var axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_498.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_498.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_498.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; if(ax._counterangle && ax.ticks === 'outside') { var caRad = ax._counterangle * Math.PI / 180; @@ -28436,13 +28751,14 @@ axes.doTicks = function(gd, axid, skipTitle) { }; } else { - _$lib_539.warn('Unrecognized doTicks axis:', axid); + _$lib_601.warn('Unrecognized doTicks axis:', axid); return; } - var axside = ax.side || sides[0], + + var axside = ax.side || sides[0]; // which direction do the side[0], side[1], and free ticks go? // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; if((ax.ticks !== 'inside') === (axLetter === 'x')) { ticksign = ticksign.map(function(v) { return -v; }); } @@ -28470,10 +28786,11 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawTicks(container, tickpath) { var ticks = container.selectAll('path.' + tcls) .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); + if(tickpath && ax.ticks) { ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) .classed('crisp', 1) - .call(_$color_411.stroke, ax.tickcolor) + .call(_$color_473.stroke, ax.tickcolor) .style('stroke-width', tickWidth + 'px') .attr('d', tickpath); ticks.attr('transform', transfn); @@ -28485,9 +28802,9 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawLabels(container, position) { // tick labels - for now just the main labels. // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); - if(!_$fastIsnumeric_139(position)) { + if(!_$fastIsnumeric_196(position)) { tickLabels.remove(); drawAxTitle(); return; @@ -28509,7 +28826,7 @@ axes.doTicks = function(gd, axid, skipTitle) { ((axside === 'bottom') ? 1 : -0.2); }; labelanchor = function(angle) { - if(!_$fastIsnumeric_139(angle) || angle === 0 || angle === 180) { + if(!_$fastIsnumeric_196(angle) || angle === 0 || angle === 180) { return 'middle'; } return (angle * flipit < 0) ? 'end' : 'start'; @@ -28525,7 +28842,7 @@ axes.doTicks = function(gd, axid, skipTitle) { ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; }; labelanchor = function(angle) { - if(_$fastIsnumeric_139(angle) && Math.abs(angle) === 90) { + if(_$fastIsnumeric_196(angle) && Math.abs(angle) === 90) { return 'middle'; } return axside === 'right' ? 'start' : 'end'; @@ -28550,13 +28867,13 @@ axes.doTicks = function(gd, axid, skipTitle) { // alter later .attr('text-anchor', 'middle') .each(function(d) { - var thisLabel = _$d3_127.select(this), + var thisLabel = _$d3_130.select(this), newPromise = gd._promises.length; thisLabel - .call(_$svg_text_utils_562.positionText, labelx(d), labely(d)) - .call(_$drawing_436.font, d.font, d.fontSize, d.fontColor) + .call(_$svg_text_utils_625.positionText, labelx(d), labely(d)) + .call(_$drawing_498.font, d.font, d.fontSize, d.fontColor) .text(d.text) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); newPromise = gd._promises[newPromise]; if(newPromise) { // if we have an async label, we'll deal with that @@ -28580,8 +28897,8 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'angular') { tickLabels.each(function(d) { - _$d3_127.select(this).select('text') - .call(_$svg_text_utils_562.positionText, labelx(d), labely(d)); + _$d3_130.select(this).select('text') + .call(_$svg_text_utils_625.positionText, labelx(d), labely(d)); }); } @@ -28608,17 +28925,17 @@ axes.doTicks = function(gd, axid, skipTitle) { function positionLabels(s, angle) { s.each(function(d) { var anchor = labelanchor(angle, d); - var thisLabel = _$d3_127.select(this), + var thisLabel = _$d3_130.select(this), mathjaxGroup = thisLabel.select('.text-math-group'), transform = transfn.call(thisLabel.node(), d) + - ((_$fastIsnumeric_139(angle) && +angle !== 0) ? + ((_$fastIsnumeric_196(angle) && +angle !== 0) ? (' rotate(' + angle + ',' + labelx(d) + ',' + (labely(d) - d.fontSize / 2) + ')') : ''); var anchorHeight = getAnchorHeight( - _$svg_text_utils_562.lineCount(thisLabel), - __LINE_SPACING_584 * d.fontSize, - _$fastIsnumeric_139(angle) ? +angle : 0); + _$svg_text_utils_625.lineCount(thisLabel), + __LINE_SPACING_647 * d.fontSize, + _$fastIsnumeric_196(angle) ? +angle : 0); if(anchorHeight) { transform += ' translate(0, ' + anchorHeight + ')'; } @@ -28630,7 +28947,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } else { var mjShift = - _$drawing_436.bBox(mathjaxGroup.node()).width * + _$drawing_498.bBox(mathjaxGroup.node()).width * {end: -0.5, start: 0.5}[anchor]; mathjaxGroup.attr('transform', transform + (mjShift ? 'translate(' + mjShift + ',0)' : '')); @@ -28655,16 +28972,16 @@ axes.doTicks = function(gd, axid, skipTitle) { // check for auto-angling if x labels overlap // don't auto-angle at all for log axes with // base and digit format - if(axLetter === 'x' && !_$fastIsnumeric_139(ax.tickangle) && + if(axLetter === 'x' && !_$fastIsnumeric_196(ax.tickangle) && (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { var lbbArray = []; tickLabels.each(function(d) { - var s = _$d3_127.select(this), + var s = _$d3_130.select(this), thisLabel = s.select('.text-math-group'), x = ax.l2p(d.x); if(thisLabel.empty()) thisLabel = s.select('text'); - var bb = _$drawing_436.bBox(thisLabel.node()); + var bb = _$drawing_498.bBox(thisLabel.node()); lbbArray.push({ // ignore about y, just deal with x overlaps @@ -28678,7 +28995,7 @@ axes.doTicks = function(gd, axid, skipTitle) { }); }); for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_539.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + if(_$lib_601.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { // any overlap at all - set 30 degrees autoangle = 30; break; @@ -28816,11 +29133,11 @@ axes.doTicks = function(gd, axid, skipTitle) { var pushKey = ax._name + '.automargin'; var prevPush = fullLayout._pushmargin[pushKey]; if(!prevPush || prevPush[s].size < push[s]) { - _$plots_647.autoMargin(gd, pushKey, push); + _$plots_709.autoMargin(gd, pushKey, push); } } - var done = _$lib_539.syncOrAsync([ + var done = _$lib_601.syncOrAsync([ allLabelsReady, fixLabelOverlaps, calcBoundingBox, @@ -28836,14 +29153,12 @@ axes.doTicks = function(gd, axid, skipTitle) { // now this only applies to regular cartesian axes; colorbars and // others ALWAYS call doTicks with skipTitle=true so they can // configure their own titles. - var ax = _$axis_ids_587.getFromId(gd, axid); // rangeslider takes over a bottom title so drop it here if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - var avoidSelection = _$d3_127.select(gd).selectAll('g.' + axid + 'tick'); var avoid = { - selection: avoidSelection, + selection: tickLabels, side: ax.side }; var axLetter = axid.charAt(0); @@ -28853,8 +29168,8 @@ axes.doTicks = function(gd, axid, skipTitle) { var transform, counterAxis, x, y; - if(avoidSelection.size()) { - var translation = _$drawing_436.getTranslate(avoidSelection.node().parentNode); + if(tickLabels.size()) { + var translation = _$drawing_498.getTranslate(tickLabels.node().parentNode); avoid.offsetLeft = translation.x; avoid.offsetTop = translation.y; } @@ -28865,7 +29180,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axLetter === 'x') { counterAxis = (ax.anchor === 'free') ? {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_587.getFromId(gd, ax.anchor); + _$axis_ids_650.getFromId(gd, ax.anchor); x = ax._offset + ax._length / 2; @@ -28883,7 +29198,7 @@ axes.doTicks = function(gd, axid, skipTitle) { else { counterAxis = (ax.anchor === 'free') ? {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_587.getFromId(gd, ax.anchor); + _$axis_ids_650.getFromId(gd, ax.anchor); y = ax._offset + ax._length / 2; if(ax.side === 'right') { @@ -28899,7 +29214,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(!avoid.side) avoid.side = 'left'; } - _$titles_504.draw(gd, axid + 'title', { + _$titles_566.draw(gd, axid + 'title', { propContainer: ax, propName: ax._name + '.title', placeholder: fullLayout._dfltTitle[axLetter], @@ -28911,11 +29226,13 @@ axes.doTicks = function(gd, axid, skipTitle) { function traceHasBarsOrFill(trace, subplot) { if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_668.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + if(_$registry_731.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; } function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); var zlcontainer = plotinfo.zerolinelayer; var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; @@ -28931,11 +29248,11 @@ axes.doTicks = function(gd, axid, skipTitle) { .each(function(d) { if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && Math.abs(d.x) < ax.dtick / 100) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); } }); grid.attr('transform', transfn) - .call(_$color_411.stroke, ax.gridcolor || '#ddd') + .call(_$color_473.stroke, ax.gridcolor || '#ddd') .style('stroke-width', gridWidth + 'px'); if(typeof gridpath === 'function') grid.attr('d', gridpath); grid.exit().remove(); @@ -28949,7 +29266,7 @@ axes.doTicks = function(gd, axid, skipTitle) { break; } } - var rng = _$lib_539.simpleMap(ax.range, ax.r2l), + var rng = _$lib_601.simpleMap(ax.range, ax.r2l), showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && (ax.type === 'linear' || ax.type === '-') && gridvals.length && (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); @@ -28963,11 +29280,11 @@ axes.doTicks = function(gd, axid, skipTitle) { // If several zerolines enter at the same time we will sort once per, // but generally this should be a minimal overhead. zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_587.idSort(da.id, db.id); + return _$axis_ids_650.idSort(da.id, db.id); }); }); zl.attr('transform', transfn) - .call(_$color_411.stroke, ax.zerolinecolor || _$color_411.defaultLine) + .call(_$color_473.stroke, ax.zerolinecolor || _$color_473.defaultLine) .style('stroke-width', zeroLineWidth + 'px'); zl.exit().remove(); } @@ -29014,7 +29331,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - tickSubplots = Object.keys(ax._linepositions); + tickSubplots = Object.keys(ax._linepositions || {}); } tickSubplots.map(function(subplot) { @@ -29153,7 +29470,7 @@ function swapAxisGroup(gd, xIds, yIds) { var ann = gd._fullLayout.annotations[i]; if(xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { - _$lib_539.swapAttrs(layout.annotations[i], ['?']); + _$lib_601.swapAttrs(layout.annotations[i], ['?']); } } } @@ -29162,7 +29479,7 @@ 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_539.nestedProperty, + var np = _$lib_601.nestedProperty, xVal = np(layout[xFullAxes[0]._name], key).get(), yVal = np(layout[yFullAxes[0]._name], key).get(), i; @@ -29184,7 +29501,7 @@ function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) { } } -var _$helpers_965 = {}; +var _$helpers_1036 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29195,7 +29512,7 @@ var _$helpers_965 = {}; 'use strict'; -_$helpers_965.pointsAccessorFunction = function(transforms, opts) { +_$helpers_1036.pointsAccessorFunction = function(transforms, opts) { var tr; var prevIndexToPoints; for(var i = 0; i < transforms.length; i++) { @@ -29210,7 +29527,7 @@ _$helpers_965.pointsAccessorFunction = function(transforms, opts) { return originalPointsAccessor; }; -var _$aggregate_962 = {}; +var _$aggregate_1033 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29221,17 +29538,17 @@ var _$aggregate_962 = {}; 'use strict'; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plot_schema_575 = require('../plot_api/plot_schema'); */; -var pointsAccessorFunction = _$helpers_965.pointsAccessorFunction; -var __BADNUM_962 = _$numerical_517.BADNUM; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plot_schema_638 = require('../plot_api/plot_schema'); */; +var pointsAccessorFunction = _$helpers_1036.pointsAccessorFunction; +var __BADNUM_1033 = _$numerical_578.BADNUM; -_$aggregate_962.moduleType = 'transform'; +_$aggregate_1033.moduleType = 'transform'; -_$aggregate_962.name = 'aggregate'; +_$aggregate_1033.name = 'aggregate'; -var attrs = _$aggregate_962.attributes = { +var attrs = _$aggregate_1033.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -29344,12 +29661,12 @@ var aggAttrs = attrs.aggregations; * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$aggregate_962.supplyDefaults = function(transformIn, traceOut) { +_$aggregate_1033.supplyDefaults = function(transformIn, traceOut) { var transformOut = {}; var i; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, attrs, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, attrs, attr, dflt); } var enabled = coerce('enabled'); @@ -29366,7 +29683,7 @@ _$aggregate_962.supplyDefaults = function(transformIn, traceOut) { * as distinct from undefined which means this array isn't present in the input * missing arrays can still be aggregate outputs for *count* aggregations. */ - var arrayAttrArray = _$plot_schema_575.findArrayAttributes(traceOut); + var arrayAttrArray = _$plot_schema_638.findArrayAttributes(traceOut); var arrayAttrs = {}; for(i = 0; i < arrayAttrArray.length; i++) arrayAttrs[arrayAttrArray[i]] = 1; @@ -29385,7 +29702,7 @@ _$aggregate_962.supplyDefaults = function(transformIn, traceOut) { var aggregationOut; function coercei(attr, dflt) { - return _$lib_539.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt); + return _$lib_601.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt); } for(i = 0; i < aggregationsIn.length; i++) { @@ -29421,12 +29738,12 @@ _$aggregate_962.supplyDefaults = function(transformIn, traceOut) { }; -_$aggregate_962.calcTransform = function(gd, trace, opts) { +_$aggregate_1033.calcTransform = function(gd, trace, opts) { if(!opts.enabled) return; var groups = opts.groups; - var groupArray = _$lib_539.getTargetArray(trace, {target: groups}); + var groupArray = _$lib_601.getTargetArray(trace, {target: groups}); if(!groupArray) return; var i, vi, groupIndex, newGrouping; @@ -29473,9 +29790,9 @@ function aggregateOneArray(gd, trace, groupings, aggregation) { if(!aggregation.enabled) return; var attr = aggregation.target; - var targetNP = _$lib_539.nestedProperty(trace, attr); + var targetNP = _$lib_601.nestedProperty(trace, attr); var arrayIn = targetNP.get(); - var conversions = _$axes_584.getDataConversions(gd, trace, attr, arrayIn); + var conversions = _$axes_647.getDataConversions(gd, trace, attr, arrayIn); var func = getAggregateFunction(aggregation, conversions); var arrayOut = new Array(groupings.length); @@ -29507,7 +29824,7 @@ function getAggregateFunction(opts, conversions) { var total = 0; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) total += vi; + if(vi !== __BADNUM_1033) total += vi; } return c2d(total); }; @@ -29519,12 +29836,12 @@ function getAggregateFunction(opts, conversions) { var cnt = 0; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { total += vi; cnt++; } } - return cnt ? c2d(total / cnt) : __BADNUM_962; + return cnt ? c2d(total / cnt) : __BADNUM_1033; }; case 'min': @@ -29532,9 +29849,9 @@ function getAggregateFunction(opts, conversions) { var out = Infinity; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) out = Math.min(out, vi); + if(vi !== __BADNUM_1033) out = Math.min(out, vi); } - return (out === Infinity) ? __BADNUM_962 : c2d(out); + return (out === Infinity) ? __BADNUM_1033 : c2d(out); }; case 'max': @@ -29542,9 +29859,9 @@ function getAggregateFunction(opts, conversions) { var out = -Infinity; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) out = Math.max(out, vi); + if(vi !== __BADNUM_1033) out = Math.max(out, vi); } - return (out === -Infinity) ? __BADNUM_962 : c2d(out); + return (out === -Infinity) ? __BADNUM_1033 : c2d(out); }; case 'median': @@ -29552,9 +29869,9 @@ function getAggregateFunction(opts, conversions) { var sortCalc = []; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) sortCalc.push(vi); + if(vi !== __BADNUM_1033) sortCalc.push(vi); } - if(!sortCalc.length) return __BADNUM_962; + if(!sortCalc.length) return __BADNUM_1033; sortCalc.sort(); var mid = (sortCalc.length - 1) / 2; return c2d((sortCalc[Math.floor(mid)] + sortCalc[Math.ceil(mid)]) / 2); @@ -29564,10 +29881,10 @@ function getAggregateFunction(opts, conversions) { return function(array, indices) { var counts = {}; var maxCnt = 0; - var out = __BADNUM_962; + var out = __BADNUM_1033; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { var counti = counts[vi] = (counts[vi] || 0) + 1; if(counti > maxCnt) { maxCnt = counti; @@ -29575,7 +29892,7 @@ function getAggregateFunction(opts, conversions) { } } } - return maxCnt ? c2d(out) : __BADNUM_962; + return maxCnt ? c2d(out) : __BADNUM_1033; }; case 'rms': @@ -29584,12 +29901,12 @@ function getAggregateFunction(opts, conversions) { var cnt = 0; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { total += vi * vi; cnt++; } } - return cnt ? c2d(Math.sqrt(total / cnt)) : __BADNUM_962; + return cnt ? c2d(Math.sqrt(total / cnt)) : __BADNUM_1033; }; case 'stddev': @@ -29600,16 +29917,16 @@ function getAggregateFunction(opts, conversions) { var total = 0; var total2 = 0; var cnt = 1; - var v0 = __BADNUM_962; + var v0 = __BADNUM_1033; var i; - for(i = 0; i < indices.length && v0 === __BADNUM_962; i++) { + for(i = 0; i < indices.length && v0 === __BADNUM_1033; i++) { v0 = d2c(array[indices[i]]); } - if(v0 === __BADNUM_962) return __BADNUM_962; + if(v0 === __BADNUM_1033) return __BADNUM_1033; for(; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { var dv = vi - v0; total += dv; total2 += dv * dv; @@ -29654,7 +29971,7 @@ function last(array, indices) { 'use strict'; -var _$aggregate_3 = _$aggregate_962; +var _$aggregate_3 = _$aggregate_1033; /** * Copyright 2012-2018, Plotly, Inc. @@ -29667,7 +29984,7 @@ var _$aggregate_3 = _$aggregate_962; 'use strict'; -var _$attributes_582 = { +var _$attributes_645 = { xaxis: { valType: 'subplotid', role: 'info', @@ -29691,11 +30008,80 @@ var _$attributes_582 = { 'a 2D cartesian y axis.', 'If *y* (the default value), the y coordinates refer to', '`layout.yaxis`.', - 'If *y2*, the y coordinates refer to `layout.xaxis2`, and so on.' + 'If *y2*, the y coordinates refer to `layout.yaxis2`, and so on.' ].join(' ') } }; +var _$client_303 = true; +var _$hasHover_296 = {}; +(function (global){ +'use strict' + +/* removed: var _$client_303 = require('is-browser') */; +var hasHover + +if (typeof global.matchMedia === 'function') { + hasHover = !global.matchMedia('(hover: none)').matches +} +else { + hasHover = _$client_303 +} + +_$hasHover_296 = hasHover + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + +/* removed: var _$client_303 = require('is-browser') */; + +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 +} + +var _$hasPassiveEvents_297 = _$client_303 && detect() + +var rootPosition = { left: 0, top: 0 } + +var _$mouseEventOffset_321 = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29704,29 +30090,28 @@ var _$attributes_582 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - - -var _$handleCategoryOrderDefaults_588 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; - - var arrayIn = containerIn.categoryarray, - orderDefault; - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); +'use strict'; - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; - var order = coerce('categoryorder', orderDefault); +// 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 +var _$align_493 = function align(v, dv, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0), + vmax = vmin + dv / (v1 - v0), + vc = (vmin + vmax) / 2; - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + // explicitly specified anchor + if(anchor === 'left' || anchor === 'bottom') return vmin; + if(anchor === 'center' || anchor === 'middle') return vc; + if(anchor === 'right' || anchor === 'top') return vmax; - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } + // automatic based on position + if(vmin < (2 / 3) - vc) return vmin; + if(vmax > (4 / 3) - vc) return vmax; + return vc; }; /** @@ -29737,60 +30122,33 @@ var _$handleCategoryOrderDefaults_588 = function handleCategoryOrderDefaults(con * LICENSE file in the root directory of this source tree. */ -'use strict'; - -var colorMix = _$tinycolor_352.mix; -var lightFraction = _$attributes_410.lightFraction; -/* removed: var _$lib_539 = require('../../lib'); */; - -/** - * @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 - */ -var _$handleLineGridDefaults_598 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; - - var dfltColor = opts.dfltColor; - function coerce2(attr, dflt) { - return _$lib_539.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); - } +'use strict'; - var lineColor = coerce2('linecolor', dfltColor); - var lineWidth = coerce2('linewidth'); - var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); +/* removed: var _$lib_601 = require('../../lib'); */; - 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); +// 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'] +]; - if(!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } +var _$getCursor_494 = 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_601.constrain(Math.floor(x * 3), 0, 2); - if(!opts.noZeroLine) { - var zeroLineColor = coerce2('zerolinecolor', dfltColor); - var zeroLineWidth = coerce2('zerolinewidth'); - var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); + if(yanchor === 'bottom') y = 0; + else if(yanchor === 'middle') y = 1; + else if(yanchor === 'top') y = 2; + else y = _$lib_601.constrain(Math.floor(y * 3), 0, 2); - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } + return cursorset[y][x]; }; /** @@ -29801,177 +30159,332 @@ var _$handleLineGridDefaults_598 = function handleLineGridDefaults(containerIn, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +var _$constants_510 = { + // 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', -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { + // minimum time (msec) between hover calls + HOVERMINTIME: 50, - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. + // ID suffix (with fullLayout._uid) for hover events in the throttle cache + HOVERID: '-hover' +}; - var categoryArray = []; +// 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 traceLines = data.map(function(d) {return d[axisLetter];}); +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +var _$EventEmitter_194 = EventEmitter; - var i, j, tracePoints, category, insertionIndex; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - var bisector = _$d3_127.bisector(sortFunction).left; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - for(i = 0; i < traceLines.length; i++) { +// 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. +EventEmitter.defaultMaxListeners = 10; - tracePoints = traceLines[i]; +// 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(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; - for(j = 0; j < tracePoints.length; j++) { +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; - category = tracePoints[j]; + if (!this._events) + this._events = {}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - insertionIndex = bisector(categoryArray, category); + handler = this._events[type]; - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; + if (isUndefined(handler)) + return false; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - return categoryArray; -} + return true; +}; +EventEmitter.prototype.addListener = function(type, listener) { + var m; -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_599 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_127.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_127.descending, data); - case 'trace': return []; - default: return []; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } } + } + + return this; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +EventEmitter.prototype.on = EventEmitter.prototype.addListener; -'use strict'; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; + var fired = false; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_606 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_588 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_598 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_603 = require('./set_convert'); */; -/* removed: var _$orderedCategories_599 = require('./ordered_categories'); */; + function g() { + this.removeListener(type, g); -/** - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_586 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - var visible = coerce('visible', !options.cheateronly); + g.listener = listener; + this.on(type, g); - var axType = containerOut.type; + return this; +}; - if(axType === 'date') { - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - _$setConvert_603(containerOut, layoutOut); + if (position < 0) + return this; - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } - if(autoRange) coerce('rangemode'); + return this; +}; - coerce('range'); - containerOut.cleanRange(); +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - _$handleCategoryOrderDefaults_588(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_599(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + if (!this._events) + return this; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - if(!visible) return containerOut; + listeners = this._events[type]; - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_539.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + return this; +}; - _$handleTickValueDefaults_606(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_604(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_605(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_598(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_596 - }); +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - if(containerOut.showline || containerOut.ticks) coerce('mirror'); +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - if(options.automargin) coerce('automargin'); + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - return containerOut; +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); }; +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29983,148 +30496,161 @@ var _$handleAxisDefaults_586 = function handleAxisDefaults(containerIn, containe 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var id2name = _$axis_ids_587.id2name; +/* global jQuery:false */ +var __EventEmitter_589 = _$EventEmitter_194.EventEmitter; -var _$handleConstraintDefaults_590 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); +var Events = { - if(containerOut.fixedrange) return; + init: function(plotObj) { - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_539.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); + /* + * If we have already instantiated an emitter for this plot + * return early. + */ + if(plotObj._ev instanceof __EventEmitter_589) return plotObj; - if(!containerIn.scaleanchor) return; + var ev = new __EventEmitter_589(); + var internalEv = new __EventEmitter_589(); - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + /* + * Assign to plot._ev while we still live in a land + * where plot is a DOM element with stuff attached to it. + * In the future we can make plot the event emitter itself. + */ + plotObj._ev = ev; - var scaleanchor = _$lib_539.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); + /* + * Create a second event handler that will manage events *internally*. + * This allows parts of plotly to respond to thing like relayout without + * having to use the user-facing event handler. They cannot peacefully + * coexist on the same handler because a user invoking + * plotObj.removeAllListeners() would detach internal events, breaking + * plotly. + */ + plotObj._internalEv = internalEv; - 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; + /* + * Assign bound methods from the ev to the plot object. These methods + * will reference the 'this' of plot._ev even though they are methods + * of plot. This will keep the event machinery away from the plot object + * which currently is often a DOM element but presents an API that will + * continue to function when plot becomes an emitter. Not all EventEmitter + * methods have been bound to `plot` as some do not currently add value to + * the Plotly event API. + */ + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_539.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.'); - } -}; + /* + * Create funtions for managing internal events. These are *only* triggered + * by the mirroring of external events via the emit function. + */ + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. + /* + * We must wrap emit to continue to support JQuery events. The idea + * is to check to see if the user is using JQuery events, if they are + * we emit JQuery events to trigger user handlers as well as the EventEmitter + * events. + */ + plotObj.emit = function(event, data) { + if(typeof jQuery !== 'undefined') { + jQuery(plotObj).trigger(event, data); + } - var thisType = layoutOut[id2name(thisID)].type; + ev.emit(event, data); + internalEv.emit(event, data); + }; - var i, j, idj, axj; + return plotObj; + }, - var linkableAxes = []; - for(j = 0; j < allAxisIds.length; j++) { - idj = allAxisIds[j]; - if(idj === thisID) continue; + /* + * This function behaves like jQueries triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. + * + * Note: triggerHandler has been recommended for deprecation in v2.0.0, + * so the additional behavior of triggerHandler triggering internal events + * is deliberate excluded in order to avoid reinforcing more usage. + */ + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + /* + * If Jquery exists run all its handlers for this event and + * collect the return value of the LAST handler function + */ + if(typeof jQuery !== 'undefined') { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } - axj = layoutOut[id2name(idj)]; - if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); - } + /* + * Now run all the node style event handlers + */ + var ev = plotObj._ev; + if(!ev) return jQueryHandlerValue; - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[i]; + var handlers = ev._events[event]; + if(!handlers) return jQueryHandlerValue; - var linkableAxesNoLoops = []; - for(j = 0; j < linkableAxes.length; j++) { - idj = linkableAxes[j]; - if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); - } - return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; - } - } + /* + * handlers can be function or an array of functions + */ + if(typeof handlers === 'function') handlers = [handlers]; + var lastHandler = handlers.pop(); - return {linkableAxes: linkableAxes, thisGroup: null}; -} + /* + * Call all the handlers except the last one. + */ + for(var i = 0; i < handlers.length; i++) { + handlers[i](data); + } + /* + * Now call the final handler and collect its value + */ + nodeEventHandlerValue = lastHandler(data); -/* - * 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; + /* + * Return either the jquery handler value if it exists or the + * nodeEventHandler value. Jquery event value superceeds nodejs + * events for backwards compatability reasons. + */ + return jQueryHandlerValue !== undefined ? jQueryHandlerValue : + nodeEventHandlerValue; + }, - if(thisGroup === null) { - thisGroup = {}; - thisGroup[thisID] = 1; - thisGroupIndex = constraintGroups.length; - constraintGroups.push(thisGroup); - } - else { - thisGroupIndex = constraintGroups.indexOf(thisGroup); - } + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; - var thisGroupKeys = Object.keys(thisGroup); + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; - // 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; - } + return plotObj; } - // 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; -} +}; +var _$Events_589 = Events; + +var _$unhover_496 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -30136,78 +30662,53 @@ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$Events_589 = require('../../lib/events'); */; +/* removed: var _$throttle_626 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_596 = require('../../lib/get_graph_div'); */; -var _$handlePositionDefaults_600 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; +/* removed: var _$constants_510 = require('../fx/constants'); */; - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; +var unhover = _$unhover_496 = {}; - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } - } - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_139(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; +unhover.wrapped = function(gd, evt, subplot) { + gd = _$get_graph_div_596(gd); - var anchor = _$lib_539.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); + // Important, clear any queued hovers + if(gd._fullLayout) { + _$throttle_626.clear(gd._fullLayout._uid + _$constants_510.HOVERID); + } - if(anchor === 'free') coerce('position', dfltPosition); + unhover.raw(gd, evt, subplot); +}; - _$lib_539.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_539.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); - } +// remove hover effects on mouse out, and emit unhover event +unhover.raw = function unhoverRaw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_539.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + if(!evt) evt = {}; + if(evt.target && + _$Events_589.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; } - coerce('layer'); + fullLayout._hoverlayer.selectAll('g').remove(); + fullLayout._hoverlayer.selectAll('line').remove(); + fullLayout._hoverlayer.selectAll('circle').remove(); + gd._hoverdata = undefined; - return containerOut; + if(evt.target && oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); + } }; +var _$dragelement_495 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -30219,354 +30720,284 @@ var _$handlePositionDefaults_600 = function handlePositionDefaults(containerIn, 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$autoType_585 = require('./axis_autotype'); */; -var name2id = _$axis_ids_587.name2id; - -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored - */ -var _$handleTypeDefaults_608 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } - - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; - } - } -}; - -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; +/* removed: var _$mouseEventOffset_321 = require('mouse-event-offset'); */; +/* removed: var _$hasHover_296 = require('has-hover'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; +/* removed: var _$constants_652 = require('../../plots/cartesian/constants'); */; +/* removed: var _$interactions_577 = require('../../constants/interactions'); */; - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; +var dragElement = _$dragelement_495 = {}; - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_668.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; +dragElement.align = _$align_493; +dragElement.getCursor = _$getCursor_494; - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); +/* removed: var _$unhover_496 = require('./unhover'); */; +dragElement.unhover = _$unhover_496.wrapped; +dragElement.unhoverRaw = _$unhover_496.raw; - if(trace[calAttr] !== calendar) calendar = undefined; - } - - ax.type = _$autoType_585(boxPositions, calendar); - } - else { - ax.type = _$autoType_585(d0[axLetter] || [d0[axLetter + '0']], calendar); - } -} - -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; - - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; - } - } - } -} - -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_668.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_668.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + * 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 DBLCLICKDELAY = _$interactions_577.DBLCLICKDELAY; + var element = options.element; + var startX, + startY, + newMouseDownTime, + cursor, + dragCover, + initialEvent, + initialTarget, + rightClick; -'use strict'; + if(!gd._mouseDownTime) gd._mouseDownTime = 0; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$layout_attributes_638 = require('../layout_attributes'); */; + element.style.pointerEvents = 'all'; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_608 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_586 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_590 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_600 = require('./position_defaults'); */; -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; + element.onmousedown = onStart; + if(!_$hasPassiveEvents_297) { + element.ontouchstart = onStart; + } + else { + if(element._ontouchstart) { + element.removeEventListener('touchstart', element._ontouchstart); + } + element._ontouchstart = onStart; + element.addEventListener('touchstart', onStart, {passive: false}); + } -var _$supplyLayoutDefaults_597 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; + function _clampFn(dx, dy, minDrag) { + if(Math.abs(dx) < minDrag) dx = 0; + if(Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + var clampFn = options.clampFn || _clampFn; - if(!_$registry_668.traceIs(trace, 'cartesian') && !_$registry_668.traceIs(trace, 'gl2d')) { - continue; - } + function onStart(e) { + e.preventDefault(); - var xaName = _$axis_ids_587.id2name(trace.xaxis); - var yaName = _$axis_ids_587.id2name(trace.yaxis); + // 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; - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_668.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { + // in a click train + numClicks += 1; } - - // 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) xaCheater[xaName] = 1; + else { + // new click train + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; } - // check for default formatting tweaks - if(_$registry_668.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } + if(options.prepFn) options.prepFn(e, startX, startY); - if(_$registry_668.traceIs(trace, 'oriented')) { - var positionAxis = trace.orientation === 'h' ? yaName : xaName; - noGrids[positionAxis] = true; + if(_$hasHover_296 && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } + else if(!_$hasHover_296) { + // 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; } - } - var subplots = layoutOut._subplots; - var xIds = subplots.xaxis; - var yIds = subplots.yaxis; - var xNames = _$lib_539.simpleMap(xIds, _$axis_ids_587.id2name); - var yNames = _$lib_539.simpleMap(yIds, _$axis_ids_587.id2name); - var axNames = xNames.concat(yNames); + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onDone); + document.addEventListener('touchmove', onMove); + document.addEventListener('touchend', onDone); - // plot_bgcolor only makes sense if there's a (2D) plot! - // TODO: bgcolor for each subplot, to inherit from the main one - var plot_bgcolor = _$color_411.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_638, 'plot_bgcolor'); + return; } - var bgColor = _$color_411.combine(plot_bgcolor, layoutOut.paper_bgcolor); + function onMove(e) { + e.preventDefault(); - var axName, axLetter, axLayoutIn, axLayoutOut; + var offset = pointerOffset(e); + var minDrag = options.minDrag || _$constants_652.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; - function coerce(attr, dflt) { - return _$lib_539.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_596, attr, dflt); - } + if(dx || dy) { + gd._dragged = true; + dragElement.unhover(gd); + } - function coerce2(attr, dflt) { - return _$lib_539.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_596, attr, dflt); - } + if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; + return; } - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - - function getOverlayableAxes(axLetter, axName) { - var list = (axLetter === 'x') ? xNames : yNames; - var out = []; + function onDone(e) { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onDone); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onDone); - for(var j = 0; j < list.length; j++) { - var axName2 = list[j]; + e.preventDefault(); - if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { - out.push(_$axis_ids_587.name2id(axName2)); - } + if(_$hasHover_296) { + _$lib_601.removeElement(dragCover); } - - 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]; - - if(!_$lib_539.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; + else if(cursor) { + dragCover.documentElement.style.cursor = cursor; + cursor = null; } - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; - - _$handleTypeDefaults_608(axLayoutIn, axLayoutOut, coerce, fullData, axName); - - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); - - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; - - _$handleAxisDefaults_586(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; + if(!gd._dragging) { + gd._dragged = false; + return; } + gd._dragging = false; - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; - - _$handlePositionDefaults_600(axLayoutIn, axLayoutOut, coerce, positioningOptions); - - axLayoutOut._input = axLayoutIn; - } + // don't count as a dblClick unless the mouseUp is also within + // the dblclick delay + if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_668.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_668.getComponentMethod('rangeselector', 'handleDefaults'); + if(gd._dragged) { + if(options.doneFn) options.doneFn(e); + } + else { + if(options.clickFn) options.clickFn(numClicks, initialEvent); - for(i = 0; i < xNames.length; i++) { - axName = xNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + // 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; - rangeSliderDefaults(layoutIn, layoutOut, axName); + 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); + } - if(axLayoutOut.type === 'date') { - rangeSelectorDefaults( - axLayoutIn, - axLayoutOut, - layoutOut, - yNames, - axLayoutOut.calendar - ); + initialTarget.dispatchEvent(e2); + } } - coerce('fixedrange'); - } + finishDrag(gd); - for(i = 0; i < yNames.length; i++) { - axName = yNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + gd._dragged = false; - var anchoredAxis = layoutOut[_$axis_ids_587.id2name(axLayoutOut.anchor)]; + return; + } +}; - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); +function coverSlip() { + var cover = document.createElement('div'); - coerce('fixedrange', fixedRangeDflt); - } + 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'; - // Finally, handle scale constraints. 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). + document.body.appendChild(cover); - // sets of axes linked by `scaleanchor` along with the scaleratios compounded - // together, populated in handleConstraintDefaults - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); + return cover; +} - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); +dragElement.coverSlip = coverSlip; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; +function finishDrag(gd) { + gd._dragging = false; + if(gd._replotPending) _$registry_731.call('plot', gd); +} - _$handleConstraintDefaults_590(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } -}; +function pointerOffset(e) { + return _$mouseEventOffset_321( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -30578,328 +31009,294 @@ var _$supplyLayoutDefaults_597 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$axes_584 = require('./axes'); */; -var axisRegex = _$constants_589.attrRegex; - -var _$transitionAxes_607 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { +var _$calc_508 = function calc(gd) { + var calcdata = gd.calcdata; var fullLayout = gd._fullLayout; - var axes = []; - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + function makeCoerceHoverInfo(trace) { + return function(val) { + return _$lib_601.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + }; + } - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); - } - } - if(!update.to) continue; + // 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_731.traceIs(trace, 'pie')) continue; - update.axisName = axisName; - update.length = axis._length; + var fillFn = _$registry_731.traceIs(trace, '2dMap') ? paste : _$lib_601.fillArray; - axes.push(axisLetter); + fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); - updates[axisLetter] = update; - } - } + if(!trace.hoverlabel) continue; - return updates; + 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'); } +}; - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; - - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || _$lib_601.identity; - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + if(Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; +var _$helpers_512 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); +'use strict'; - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; - } +/* removed: var _$lib_601 = require('../../lib'); */; - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; +// look for either subplot or xaxis and yaxis attributes +// does not handle splom case +_$helpers_512.getSubplot = function getSubplot(trace) { + return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +}; - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); +// is trace in given list of subplots? +// does handle splom case +_$helpers_512.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } } } - - return affectedSubplots; + return false; } - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); - - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } + return subplots.indexOf(_$helpers_512.getSubplot(trace)) !== -1; +}; - redrawObjs(fullLayout.annotations || [], _$registry_668.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_668.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_668.getComponentMethod('images', 'draw'), true); +// convenience functions for mapping all relevant axes +_$helpers_512.flat = function flat(subplots, v) { + var out = new Array(subplots.length); + for(var i = 0; i < subplots.length; i++) { + out[i] = v; } + return out; +}; - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; +_$helpers_512.p2c = function p2c(axArray, v) { + var out = new Array(axArray.length); + for(var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); } + return out; +}; - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; - - activeAxIds = [xa._id, ya._id]; +_$helpers_512.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { + if(mode === 'closest') return dxy || _$helpers_512.quadrature(dx, dy); + return mode === 'x' ? dx : dy; +}; - for(i = 0; i < activeAxIds.length; i++) { - _$axes_584.doTicks(gd, activeAxIds[i], true); +_$helpers_512.getClosest = function getClosest(cd, distfn, pointData) { + // do we already have a point number? (array mode only) + if(pointData.index !== false) { + if(pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; } - - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; - - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - } - - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + else pointData.index = false; + } + else { + // apply the distance function to each data point + // this is the longest loop... if this bogs down, we may need + // to create pre-sorted data (by x or y), not sure how to + // do this for 'closest' + for(var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if(newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; } } - - redrawObjs(fullLayout.annotations || [], _$registry_668.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_668.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_668.getComponentMethod('images', 'draw'), true); - } - - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; - - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_436.setTranslate, 0, 0) - .call(_$drawing_436.setScale, 1, 1); - - subplot.plot - .call(_$drawing_436.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_436.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_436.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_436.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_436.hideOutsideRangePoints, subplot); } + return pointData; +}; - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; - - var viewBox = []; - - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; +/* + * pseudo-distance function for hover effects on areas: inside the region + * distance is finite (`passVal`), outside it's Infinity. + * + * @param {number} v0: signed difference between the current position and the left edge + * @param {number} v1: signed difference between the current position and the right edge + * @param {number} passVal: the value to return on success + */ +_$helpers_512.inbox = function inbox(v0, v1, passVal) { + return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; +}; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; +_$helpers_512.quadrature = function quadrature(dx, dy) { + return function(di) { + var x = dx(di), + y = dy(di); + return Math.sqrt(x * x + y * y); + }; +}; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; - } +/** Fill event data point object for hover and selection. + * Invokes _module.eventData if present. + * + * N.B. note that point 'index' corresponds to input data array index + * whereas 'number' is its post-transform version. + * + * If the hovered/selected pt corresponds to an multiple input points + * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' + * are include in the event data. + * + * @param {object} pt + * @param {object} trace + * @param {object} cd + * @return {object} + */ +_$helpers_512.makeEventData = function makeEventData(pt, trace, cd) { + // hover uses 'index', select uses 'pointNumber' + var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber: pointNumber + }; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + if(trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + if(pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; + out.pointIndices = pointIndices; } + } else { + out.pointIndex = pointNumber; + } - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; - - var editX = !!xUpdate; - var editY = !!yUpdate; - - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + if(trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if('xVal' in pt) out.x = pt.xVal; + else if('x' in pt) out.x = pt.x; - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + if('yVal' in pt) out.y = pt.yVal; + else if('y' in pt) out.y = pt.y; - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + if(pt.xa) out.xaxis = pt.xa; + if(pt.ya) out.yaxis = pt.ya; + if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_436.setTranslate, clipDx, clipDy) - .call(_$drawing_436.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + _$helpers_512.appendArrayPointValue(out, trace, pointNumber); - subplot.plot - .call(_$drawing_436.setTranslate, plotDx, plotDy) - .call(_$drawing_436.setScale, xScaleFactor, yScaleFactor) + return out; +}; - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_436.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); +/** Appends values inside array attributes corresponding to given point number + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {number|Array(number)} pointNumber : point number. May be a length-2 array + * [row, col] to dig into 2D arrays + */ +_$helpers_512.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_436.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + if(!arrayAttrs) { + return; } - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); - } + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; + if(pointData[key] === undefined) { + var val = _$lib_601.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); - axi.range = to.slice(); + if(pointVal !== undefined) pointData[key] = pointVal; } + } +}; - // Signal that this transition has completed: - onComplete && onComplete(); +/** + * Appends values inside array attributes corresponding to given point number array + * For use when pointData references a plot entity that arose (or potentially arose) + * from multiple points in the input data + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. + * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays + */ +_$helpers_512.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; - return _$registry_668.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); + if(!arrayAttrs) { + return; } - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); - axi.range = axi._r.slice(); - } + if(pointData[key] === undefined) { + var val = _$lib_601.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); - return _$registry_668.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + for(var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); } - }); + pointData[key] = keyVal; + } } +}; - var t1, t2, raf; - var easeFn = _$d3_127.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); +var pointKeyMap = { + ids: 'id', + locations: 'location', + labels: 'label', + values: 'value', + 'marker.colors': 'color' +}; - for(var i = 0; i < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } +function getPointKey(astr) { + return pointKeyMap[astr] || astr; +} - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); +function getPointData(val, pointNumber) { + if(Array.isArray(pointNumber)) { + if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; } + } else { + return val[pointNumber]; } +} - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); - - return Promise.resolve(); -}; - -var _$get_data_621 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -30908,92 +31305,69 @@ var _$get_data_621 = {}; * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$registry_668 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_589.SUBPLOT_PATTERN; - -/** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces - */ -_$get_data_621.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_668.subplotsRegistry[type]; - if(!basePlotModule) return []; - - var attr = basePlotModule.attr; - var subplotCalcData = []; - - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); - } - - return subplotCalcData; -}; - -_$get_data_621.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_668.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; +'use strict'; - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); - } +// works with our CSS cursor classes (see css/_cursor.scss) +// to apply cursors to d3 single-element selections. +// omit cursor to revert to the default. +var _$setCursor_621 = function setCursor(el3, csr) { + (el3.attr('class') || '').split(' ').forEach(function(cls) { + if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); + }); - return moduleCalcData; + if(csr) el3.classed('cursor-' + csr, true); }; /** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. - * - * @return {array} list of trace objects. - * - */ -_$get_data_621.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_668.subplotsRegistry[type]) return []; +* Copyright 2012-2018, Plotly, Inc. +* All 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 attr = _$registry_668.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; - } +'use strict'; - for(var i = 0; i < data.length; i++) { - trace = data[i]; +/* removed: var _$setCursor_621 = require('./setcursor'); */; - if(type === 'gl2d' && _$registry_668.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); +var STASHATTR = 'data-savedcursor'; +var NO_CURSOR = '!!'; + +/* + * works with our CSS cursor classes (see css/_cursor.scss) + * to override a previous cursor set on d3 single-element selections, + * by moving the name of the original cursor to the data-savedcursor attr. + * omit cursor to revert to the previously set value. + */ +var _$overrideCursor_612 = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if(csr) { + if(!savedCursor) { + var classes = (el3.attr('class') || '').split(' '); + for(var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if(cls.indexOf('cursor-') === 0) { + el3.attr(STASHATTR, cls.substr(7)) + .classed(cls, false); + } + } + if(!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); } } - else { - if(trace[attr] === subplotId) subplotData.push(trace); - } + _$setCursor_621(el3, csr); } + else if(savedCursor) { + el3.attr(STASHATTR, null); - return subplotData; + if(savedCursor === NO_CURSOR) _$setCursor_621(el3); + else _$setCursor_621(el3, savedCursor); + } }; -var _$cartesian_595 = {}; +var _$hover_513 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31002,903 +31376,1454 @@ var _$cartesian_595 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../plots'); */; -var getModuleCalcData = _$get_data_621.getModuleCalcData; - -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; -/* removed: var _$constants_589 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -_$cartesian_595.name = 'cartesian'; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$Events_589 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_612 = require('../../lib/override_cursor'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -_$cartesian_595.attr = ['xaxis', 'yaxis']; +/* removed: var _$helpers_512 = require('./helpers'); */; +/* removed: var _$constants_510 = require('./constants'); */; -_$cartesian_595.idRoot = ['x', 'y']; +// hover labels for multiple horizontal bars get tilted by some angle, +// then need to be offset differently if they overlap +var YANGLE = _$constants_510.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; -_$cartesian_595.idRegex = _$constants_589.idRegex; +// expansion of projected height +var YFACTOR = 1 / Math.sin(YA_RADIANS); -_$cartesian_595.attrRegex = _$constants_589.attrRegex; +// to make the appropriate post-rotation x offset, +// you need both x and y offsets +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); -_$cartesian_595.attributes = _$attributes_582; +// size and display constants for hover text +var HOVERARROWSIZE = _$constants_510.HOVERARROWSIZE; +var HOVERTEXTPAD = _$constants_510.HOVERTEXTPAD; -_$cartesian_595.layoutAttributes = _$layout_attributes_596; +// fx.hover: highlight data on hover +// evt can be a mousemove event, or an object with data about what points +// to hover on +// {xpx,ypx[,hovermode]} - pixel locations from top left +// (with optional overriding hovermode) +// {xval,yval[,hovermode]} - data values +// [{curveNumber,(pointNumber|xval and/or yval)}] - +// array of specific points to highlight +// pointNumber is a single integer if gd.data[curveNumber] is 1D, +// or a two-element array if it's 2D +// xval and yval are data values, +// 1D data may specify either or both, +// 2D data must specify both +// subplot is an id string (default "xy") +// makes use of gl.hovermode, which can be: +// x (find the points with the closest x values, ie a column), +// closest (find the single closest point) +// internally there are two more that occasionally get used: +// y (pick out a row - only used for multiple horizontal bar charts) +// array (used when the user specifies an explicit +// array of points to hover on) +// +// We wrap the hovers in a timer, to limit their frequency. +// The actual rendering is done by private function _hover. +_$hover_513.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = _$lib_601.getGraphDiv(gd); -_$cartesian_595.supplyLayoutDefaults = _$supplyLayoutDefaults_597; + _$lib_601.throttle( + gd._fullLayout._uid + _$constants_510.HOVERID, + _$constants_510.HOVERMINTIME, + function() { _hover(gd, evt, subplot, noHoverEvent); } + ); +}; -_$cartesian_595.transitionAxes = _$transitionAxes_607; +/* + * Draw a single hover item in a pre-existing svg container somewhere + * hoverItem should have keys: + * - x and y (or x0, x1, y0, and y1): + * the pixel position to mark, relative to opts.container + * - xLabel, yLabel, zLabel, text, and name: + * info to go in the label + * - color: + * the background color for the label. + * - idealAlign (optional): + * 'left' or 'right' for which side of the x/y box to try to put this on first + * - borderColor (optional): + * color for the border, defaults to strongest contrast with color + * - fontFamily (optional): + * string, the font for this label, defaults to constants.HOVERFONT + * - fontSize (optional): + * the label font size, defaults to constants.HOVERFONTSIZE + * - fontColor (optional): + * defaults to borderColor + * opts should have keys: + * - bgColor: + * the background color this is against, used if the trace is + * non-opaque, and for the name, which goes outside the box + * - container: + * a or element to add the hover label to + * - outerContainer: + * normally a parent of `container`, sets the bounding box to use to + * constrain the hover label and determine whether to show it on the left or right + */ +_$hover_513.loneHover = function loneHover(hoverItem, opts) { + var pointData = { + color: hoverItem.color || _$color_473.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, -_$cartesian_595.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; + // optional extra bits of styling + borderColor: hoverItem.borderColor, + fontFamily: hoverItem.fontFamily, + fontSize: hoverItem.fontSize, + fontColor: hoverItem.fontColor, - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } + // filler to make createHoverText happy + trace: { + index: 0, + hoverinfo: '' + }, + xa: {_offset: 0}, + ya: {_offset: 0}, + index: 0 + }; - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_587.id2name(xi)] || {}).anchor; - if(!_$constants_589.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var container3 = _$d3_130.select(opts.container), + outerContainer3 = opts.outerContainer ? + _$d3_130.select(opts.outerContainer) : container3; - if(!allY[yi]) { - allY[yi] = 1; - _$lib_539.pushUnique(yList, yi); - } - } - } + var fullOpts = { + hovermode: 'closest', + rotateLabels: false, + bgColor: opts.bgColor || _$color_473.background, + container: container3, + outerContainer: outerContainer3 + }; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_587.id2name(yi)] || {}).anchor; - if(!_$constants_589.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); + alignHoverText(hoverLabel, fullOpts.rotateLabels); - if(!allX[xi]) { - allX[xi] = 1; - _$lib_539.pushUnique(xList, xi); - } - } - } - - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_589.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_587.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_587.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } + return hoverLabel.node(); }; -_$cartesian_595.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; +// The actual implementation is here: +function _hover(gd, evt, subplot, noHoverEvent) { + if(!subplot) subplot = 'xy'; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + // if the user passed in an array of subplots, + // use those instead of finding overlayed plots + var subplots = Array.isArray(subplot) ? subplot : [subplot]; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var fullLayout = gd._fullLayout; + var plots = fullLayout._plots || []; + var plotinfo = plots[subplot]; + var hasCartesian = fullLayout._has('cartesian'); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } + // list of all overlaid subplots to look at + if(plotinfo) { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; }); - } - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + subplots = subplots.concat(overlayedSubplots); + } - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; + var len = subplots.length; + var xaArray = new Array(len); + var yaArray = new Array(len); + var supportsCompare = false; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + for(var i = 0; i < len; i++) { + var spId = subplots[i]; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + // 'cartesian' case + var plotObj = plots[spId]; + if(plotObj) { + supportsCompare = true; - cdSubplot.push(cd); - } + // TODO make sure that fullLayout_plots axis refs + // get updated properly so that we don't have + // to use Axes.getFromId in general. - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; - } + xaArray[i] = _$axes_647.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_647.getFromId(gd, plotObj.yaxis._id); + continue; } - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + // other subplot types + var _subplot = fullLayout[spId]._subplot; + xaArray[i] = _subplot.xaxis; + yaArray[i] = _subplot.yaxis; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; + var hovermode = evt.hovermode || fullLayout.hovermode; - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + if(hovermode && !supportsCompare) hovermode = 'closest'; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || + gd.querySelector('.zoombox') || gd._dragging) { + return _$dragelement_495.unhoverRaw(gd, evt); } -} -_$cartesian_595.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; + var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + // hoverData: the set of candidate points we've found to highlight + var hoverData = [], + // searchData: the data to search in. Mostly this is just a copy of + // gd.calcdata, filtered to the subplot and overlays we're on + // but if a point array is supplied it will be a mapping + // of indicated curves + searchData = [], - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; - } + // [x|y]valArray: the axis values of the hover event + // mapped onto each of the currently selected overlaid subplots + xvalArray, + yvalArray, - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + // used in loops + itemnum, + curvenum, + cd, + trace, + subplotId, + subploti, + mode, + xval, + yval, + pointData, + closedataPreviousLength, - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // spikePoints: the set of candidate points we've found to draw spikes to + spikePoints = { + hLinePoint: null, + vLinePoint: null + }; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + // Figure out what we're hovering on: + // mouse location or user-supplied data - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + if(Array.isArray(evt)) { + // user specified an array of points to highlight + hovermode = 'array'; + for(itemnum = 0; itemnum < evt.length; itemnum++) { + cd = gd.calcdata[evt[itemnum].curveNumber||0]; + if(cd[0].trace.hoverinfo !== 'skip') { + searchData.push(cd); } } - - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); } + else { + for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { + cd = gd.calcdata[curvenum]; + trace = cd[0].trace; + if(trace.hoverinfo !== 'skip' && _$helpers_512.isTraceInSubplots(trace, subplots)) { + searchData.push(cd); + } + } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // [x|y]px: the pixels (from top left) of the mouse location + // on the currently selected plot area + // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation + var hasUserCalledHover = !evt.target, + xpx, ypx; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(hasUserCalledHover) { + if('xpx' in evt) xpx = evt.xpx; + else xpx = xaArray[0]._length / 2; + evt.pointerX = xpx + xaArray[0]._offset; - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } + if('ypx' in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + evt.pointerY = ypx + yaArray[0]._offset; } - } + else { + // fire the beforehover event and quit if it returns false + // note that we're only calling this on real mouse events, so + // manual calls to fx.hover will always run. + if(_$Events_589.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + var dbb = evt.target.getBoundingClientRect(); - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // in case hover was called from mouseout into hovertext, + // it's possible you're not actually over the plot anymore + if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { + return _$dragelement_495.unhoverRaw(gd, evt); } + evt.pointerX = evt.offsetX; + evt.pointerY = evt.offsetY; } - } - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + if('xval' in evt) xvalArray = _$helpers_512.flat(subplots, evt.xval); + else xvalArray = _$helpers_512.p2c(xaArray, xpx); - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } + if('yval' in evt) yvalArray = _$helpers_512.flat(subplots, evt.yval); + else yvalArray = _$helpers_512.p2c(yaArray, ypx); + + if(!_$fastIsnumeric_196(xvalArray[0]) || !_$fastIsnumeric_196(yvalArray[0])) { + _$lib_601.warn('Fx.hover failed', evt, gd); + return _$dragelement_495.unhoverRaw(gd, evt); } } -}; -_$cartesian_595.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); + // the pixel distance to beat as a matching point + // in 'x' or 'y' mode this resets for each trace + var distance = Infinity; - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_539.identity); + // find the closest point in each trace + // this is minimum dx and/or dy, depending on mode + // and the pixel position for the label (labelXpx, labelYpx) + for(curvenum = 0; curvenum < searchData.length; curvenum++) { + cd = searchData[curvenum]; - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + // filter out invisible or broken data + if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; - subplotLayers.order(); + trace = cd[0].trace; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + // Explicitly bail out for these two. I don't know how to otherwise prevent + // the rest of this function from running and failing + if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_512.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } - // keep ref to plot group - plotinfo.plotgroup = _$d3_127.select(this); + // within one trace mode can sometimes be overridden + mode = hovermode; - // initialize list of overlay subplots - plotinfo.overlays = []; + // container for new point, also used to pass info into module.hoverPoints + pointData = { + // trace properties + cd: cd, + trace: trace, + xa: xaArray[subploti], + ya: yaArray[subploti], - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); - } + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + // point properties - override all of these + index: false, // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance -_$cartesian_595.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_647.style(gd); -}; + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: undefined, + ySpike: undefined, - var subplotData = [], - overlays = []; + // where and how to display the hover label + color: _$color_473.defaultLine, // trace color + name: trace.name, + x0: undefined, + x1: undefined, + y0: undefined, + y1: undefined, + xLabelVal: undefined, + yLabelVal: undefined, + zLabelVal: undefined, + text: undefined + }; - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + // add ref to subplot object (non-cartesian case) + if(fullLayout[subplotId]) { + pointData.subplot = fullLayout[subplotId]._subplot; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + closedataPreviousLength = hoverData.length; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); + // for a highlighting array, figure out what + // we're searching for with this element + if(mode === 'array') { + var selection = evt[curvenum]; + if('pointNumber' in selection) { + pointData.index = selection.pointNumber; + mode = 'closest'; + } + else { + mode = ''; + if('xval' in selection) { + xval = selection.xval; + mode = 'x'; + } + if('yval' in selection) { + yval = selection.yval; + mode = mode ? 'closest' : 'y'; + } + } } else { - subplotData.push(subplot); + xval = xvalArray[subploti]; + yval = yvalArray[subploti]; } - } - - // main subplots before overlays - subplotData = subplotData.concat(overlays); - - return subplotData; -} - -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_589.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_589.layerValue2layerClass[plotinfo.yaxis.layer]; - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); + // Now if there is range to look in, find the points to hover. + if(hoverdistance !== 0) { + if(trace._module && trace._module.hoverPoints) { + var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); + if(newPoints) { + var newPoint; + for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { + newPoint = newPoints[newPointNum]; + if(_$fastIsnumeric_196(newPoint.x0) && _$fastIsnumeric_196(newPoint.y0)) { + hoverData.push(cleanPoint(newPoint, hovermode)); + } + } + } + } + else { + _$lib_601.log('Unrecognized trace type in hover:', trace); + } + } - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); + // in closest mode, remove any existing (farther) points + // and don't look any farther than this latest point (or points, some + // traces like box & violin make multiple hover labels at once) + if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); + // Now if there is range to look in, find the points to draw the spikelines + // Do it only if there is no hoverData + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); + if(closestPoints) { + closestPoints = closestPoints.filter(function(point) { + // some hover points, like scatter fills, do not allow spikes, + // so will generate a hover point but without a valid spikeDistance + return point.spikeDistance <= spikedistance; + }); + } + if(closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes; + }); + if(closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if(_$fastIsnumeric_196(closestVPt.x0) && _$fastIsnumeric_196(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.vLinePoint = tmpPoint; + } + } + } - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes; + }); + if(closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if(_$fastIsnumeric_196(closestHPt.x0) && _$fastIsnumeric_196(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } + } - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); + function selectClosestPoint(pointsData, spikedistance) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for(var i = 0; i < pointsData.length; i++) { + thisSpikeDistance = pointsData[i].spikeDistance; + if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { + resultPoint = pointsData[i]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + function fillSpikePoint(point) { + if(!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + var spikelineOpts = { + fullLayout: fullLayout, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + event: evt + }; + var oldspikepoints = gd._spikepoints, + newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + // Now if it is not restricted by spikedistance option, set the points to draw the spikelines + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } } - else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + // if hoverData is empty check for the spikes to draw and quit if there are none + if(hoverData.length === 0) { + var result = _$dragelement_495.unhoverRaw(gd, evt); + if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } + return result; + } - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + if(hasCartesian) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); + // lastly, emit custom hover/unhover events + var oldhoverdata = gd._hoverdata, + newhoverdata = []; - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + // pull out just the data that's useful to + // other people and send it to the event + for(itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + newhoverdata.push(_$helpers_512.makeEventData(pt, pt.trace, pt.cd)); } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_587.idSort); + gd._hoverdata = newhoverdata; - // common attributes for all subplots, overlays or not + // if there's more than one horz bar trace, + // rotate the labels so they don't overlap + var rotateLabels = hovermode === 'y' && searchData.length > 1; - for(var i = 0; i < _$constants_589.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_589.traceLayerClasses[i]); - } + var bgColor = _$color_473.combine( + fullLayout.plot_bgcolor || _$color_473.background, + fullLayout.paper_bgcolor + ); - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + var labelOpts = { + hovermode: hovermode, + rotateLabels: rotateLabels, + bgColor: bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }; - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); -} + var hoverLabels = createHoverText(hoverData, labelOpts, gd); -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; + hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); - var overlayIdsToRemove = {}; + alignHoverText(hoverLabels, rotateLabels); - layers.each(function(subplotId) { - var plotgroup = _$d3_127.select(this); + // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true + // we should improve the "fx" API so other plots can use it without these hack. + if(evt.target && evt.target.tagName) { + var hasClickToShow = _$registry_731.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_612(_$d3_130.select(evt.target), hasClickToShow ? 'pointer' : ''); + } - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + // don't emit events if called manually + if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; - overlayIdsToRemove[subplotId] = true; + if(oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); + } - // do not remove individual axis s here - // as other subplots may need them + gd.emit('plotly_hover', { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray }); +} - // must remove overlaid subplot trace layers 'manually' +function createHoverText(hoverData, opts, gd) { + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + // opts.fontFamily/Size are used for the common label + // and as defaults for each hover label, though the individual labels + // can override this. + var fontFamily = opts.fontFamily || _$constants_510.HOVERFONT; + var fontSize = opts.fontSize || _$constants_510.HOVERFONTSIZE; - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; + var t0 = c0[commonAttr]; + var t00 = (String(t0) || '').split(' ')[0]; + var outerContainerBB = outerContainer.node().getBoundingClientRect(); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; + // show the common label, if any, on the axis + // never show a common label in array mode, + // even if sometimes there could be one + var showCommonLabel = ( + (t0 !== undefined) && + (c0.distance <= opts.hoverdistance) && + (hovermode === 'x' || hovermode === 'y') + ); - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); + // all hover traces hoverinfo must contain the hovermode + // to have common labels + if(showCommonLabel) { + var i, traceHoverinfo; + var allHaveZ = true; + for(i = 0; i < hoverData.length; i++) { + if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + + traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; + var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); + if(parts.indexOf('all') === -1 && + parts.indexOf(hovermode) === -1) { + showCommonLabel = false; + break; } } + + // xyz labels put all info in their main label, so have no need of a common label + if(allHaveZ) showCommonLabel = false; } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); -} + var commonLabel = container.selectAll('g.axistext') + .data(showCommonLabel ? [0] : []); + commonLabel.enter().append('g') + .classed('axistext', true); + commonLabel.exit().remove(); -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); + commonLabel.each(function() { + var label = _$d3_130.select(this); + var lpath = _$lib_601.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_601.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); - layer.enter().append(nodeType) - .classed(className, true); + lpath.style({ + fill: commonLabelOpts.bgcolor || _$color_473.defaultLine, + stroke: commonLabelOpts.bordercolor || _$color_473.background, + }); - return layer; -} + ltext.text(t0) + .call(_$drawing_498.font, + commonLabelOpts.font.family || fontFamily, + commonLabelOpts.font.size || fontSize, + commonLabelOpts.font.color || _$color_473.background + ) + .call(_$svg_text_utils_625.positionText, 0, 0) + .call(_$svg_text_utils_625.convertToTspans, gd); -_$cartesian_595.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_127.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); + label.attr('transform', ''); - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); + var tbb = ltext.node().getBoundingClientRect(); + if(hovermode === 'x') { + ltext.attr('text-anchor', 'middle') + .call(_$svg_text_utils_625.positionText, 0, (xa.side === 'top' ? + (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : + (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); - image.attr({ - xmlns: _$xmlns_namespaces_519.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height + var topsign = xa.side === 'top' ? '-' : ''; + lpath.attr('d', 'M0,0' + + 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + + 'H' + (HOVERTEXTPAD + tbb.width / 2) + + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + + 'H-' + (HOVERTEXTPAD + tbb.width / 2) + + 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); + + label.attr('transform', 'translate(' + + (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + + (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + } + else { + ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') + .call(_$svg_text_utils_625.positionText, + (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), + outerTop - tbb.top - tbb.height / 2); + + var leftsign = ya.side === 'right' ? '' : '-'; + lpath.attr('d', 'M0,0' + + 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + + 'V' + (HOVERTEXTPAD + tbb.height / 2) + + 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + + 'V-' + (HOVERTEXTPAD + tbb.height / 2) + + 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); + + label.attr('transform', 'translate(' + + (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + + (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); + } + // remove the "close but not quite" points + // because of error bars, only take up to a space + hoverData = hoverData.filter(function(d) { + return (d.zLabelVal !== undefined) || + (d[commonAttr] || '').split(' ')[0] === t00; }); - } + }); - canvases.each(canvasToImage); -}; + // show all the individual labels -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // first create the objects + var hoverLabels = container.selectAll('g.hovertext') + .data(hoverData, function(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); + }); + hoverLabels.enter().append('g') + .classed('hovertext', true) + .each(function() { + var g = _$d3_130.select(this); + // trace name label (rect and text.name) + g.append('rect') + .call(_$color_473.fill, _$color_473.addOpacity(bgColor, 0.8)); + g.append('text').classed('name', true); + // trace data label (path and text.nums) + g.append('path') + .style('stroke-width', '1px'); + g.append('text').classed('nums', true) + .call(_$drawing_498.font, fontFamily, fontSize); + }); + hoverLabels.exit().remove(); + // then put the text in, position the pointer to the data, + // and figure out sizes + hoverLabels.each(function(d) { + var g = _$d3_130.select(this).attr('transform', ''), + name = '', + text = ''; -'use strict'; + // combine possible non-opaque trace color with bgColor + var baseColor = _$color_473.opacity(d.color) ? d.color : _$color_473.defaultLine; + var traceColor = _$color_473.combine(baseColor, bgColor); -var mergeArray = _$lib_539.mergeArray; + // find a contrasting color for border and text + var contrastColor = d.borderColor || _$color_473.contrast(traceColor); + // to get custom 'name' labels pass cleanPoint + if(d.nameOverride !== undefined) d.name = d.nameOverride; -// arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_677 = function arraysToCalcdata(cd, trace) { - for(var i = 0; i < cd.length; i++) cd[i].i = i; + if(d.name) { + // strip out our pseudo-html elements from d.name (if it exists at all) + name = _$svg_text_utils_625.plainText(d.name || ''); - mergeArray(trace.text, cd, 'tx'); - mergeArray(trace.hovertext, cd, 'htx'); + var nameLength = Math.round(d.nameLength); - var marker = trace.marker; - if(marker) { - mergeArray(marker.opacity, cd, 'mo'); - mergeArray(marker.color, cd, 'mc'); + if(nameLength > -1 && name.length > nameLength) { + if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; + else name = name.substr(0, nameLength); + } + } - var markerLine = marker.line; - if(markerLine) { - mergeArray(markerLine.color, cd, 'mlc'); - mergeArray(markerLine.width, cd, 'mlw'); + if(d.zLabel !== undefined) { + if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; + if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; + text += (text ? 'z: ' : '') + d.zLabel; } - } -}; + else if(showCommonLabel && d[hovermode + 'Label'] === t0) { + text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; + } + else if(d.xLabel === undefined) { + if(d.yLabel !== undefined) text = d.yLabel; + } + else if(d.yLabel === undefined) text = d.xLabel; + else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(d.text && !Array.isArray(d.text)) { + text += (text ? '
' : '') + d.text; + } -'use strict'; + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; + // if 'text' is empty at this point, + // put 'name' in main label and don't show secondary label + if(text === '') { + // if 'name' is also empty, remove entire label + if(name === '') g.remove(); + text = name; + } -var __extendFlat_678 = _$extend_528.extendFlat; + // main label + var tx = g.select('text.nums') + .call(_$drawing_498.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + d.fontColor || contrastColor) + .text(text) + .attr('data-notex', 1) + .call(_$svg_text_utils_625.positionText, 0, 0) + .call(_$svg_text_utils_625.convertToTspans, gd); -var textFontAttrs = _$font_attributes_611({ - editType: 'calc', - arrayOk: true, - description: '' -}); + var tx2 = g.select('text.name'), + tx2width = 0; -var __scatterMarkerAttrs_678 = _$attributes_862.marker; -var scatterMarkerLineAttrs = __scatterMarkerAttrs_678.line; + // secondary label for non-empty 'name' + if(name && name !== text) { + tx2.call(_$drawing_498.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + traceColor) + .text(name) + .attr('data-notex', 1) + .call(_$svg_text_utils_625.positionText, 0, 0) + .call(_$svg_text_utils_625.convertToTspans, gd); + tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; + } + else { + tx2.remove(); + g.select('rect').remove(); + } -var markerLineWidth = __extendFlat_678({}, - scatterMarkerLineAttrs.width, { dflt: 0 }); + g.select('path') + .style({ + fill: traceColor, + stroke: contrastColor + }); + var tbb = tx.node().getBoundingClientRect(), + htx = d.xa._offset + (d.x0 + d.x1) / 2, + hty = d.ya._offset + (d.y0 + d.y1) / 2, + dx = Math.abs(d.x1 - d.x0), + dy = Math.abs(d.y1 - d.y0), + txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, + anchorStartOK, + anchorEndOK; -var markerLine = __extendFlat_678({ - width: markerLineWidth, - editType: 'calc' -}, _$makeColorScaleAttributes_419('marker.line')); + d.ty0 = outerTop - tbb.top; + d.bx = tbb.width + 2 * HOVERTEXTPAD; + d.by = tbb.height + 2 * HOVERTEXTPAD; + d.anchor = 'start'; + d.txwidth = tbb.width; + d.tx2width = tx2width; + d.offset = 0; -var marker = __extendFlat_678({ - line: markerLine, - editType: 'calc' -}, _$makeColorScaleAttributes_419('marker'), { - showscale: __scatterMarkerAttrs_678.showscale, - colorbar: _$attributes_412, - opacity: { - valType: 'number', - arrayOk: true, - dflt: 1, - min: 0, - max: 1, - role: 'style', - editType: 'style', - description: 'Sets the opacity of the bars.' - } -}); + if(rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + hty += dy / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } + else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + htx += dx / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } -var _$attributes_678 = { - x: _$attributes_862.x, - x0: _$attributes_862.x0, - dx: _$attributes_862.dx, - y: _$attributes_862.y, - y0: _$attributes_862.y0, - dy: _$attributes_862.dy, + tx.attr('text-anchor', d.anchor); + if(tx2width) tx2.attr('text-anchor', d.anchor); + g.attr('transform', 'translate(' + htx + ',' + hty + ')' + + (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); + }); - text: _$attributes_862.text, - hovertext: _$attributes_862.hovertext, + return hoverLabels; +} - textposition: { - valType: 'enumerated', - role: 'info', - values: ['inside', 'outside', 'auto', 'none'], - dflt: 'none', - arrayOk: true, - editType: 'calc', - description: [ - 'Specifies the location of the `text`.', - '*inside* positions `text` inside, next to the bar end', - '(rotated and scaled if needed).', - '*outside* positions `text` outside, next to the bar end', - '(scaled if needed).', - '*auto* positions `text` inside or outside', - 'so that `text` size is maximized.' - ].join(' ') - }, +// Make groups of touching points, and within each group +// move each point so that no labels overlap, but the average +// label position is the same as it was before moving. Indicentally, +// this is equivalent to saying all the labels are on equal linear +// springs about their initial position. Initially, each point is +// its own group, but as we find overlaps we will clump the points. +// +// Also, there are hard constraints at the edges of the graphs, +// that push all groups to the middle so they are visible. I don't +// know what happens if the group spans all the way from one edge to +// the other, though it hardly matters - there's just too much +// information then. +function hoverAvoidOverlaps(hoverData, ax, fullLayout) { + var nummoves = 0, - textfont: __extendFlat_678({}, textFontAttrs, { - description: 'Sets the font used for `text`.' - }), + // make groups of touching points + pointgroups = hoverData + .map(function(d, i) { + var axis = d[ax]; + return [{ + i: i, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, + pmin: 0, + pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) + }]; + }) + .sort(function(a, b) { return a[0].posref - b[0].posref; }), + donepositioning, + topOverlap, + bottomOverlap, + i, j, + pti, + sumdp; - insidetextfont: __extendFlat_678({}, textFontAttrs, { - description: 'Sets the font used for `text` lying inside the bar.' - }), + function constrainGroup(grp) { + var minPt = grp[0], + maxPt = grp[grp.length - 1]; - outsidetextfont: __extendFlat_678({}, textFontAttrs, { - description: 'Sets the font used for `text` lying outside the bar.' - }), + // overlap with the top - positive vals are overlaps + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; - constraintext: { - valType: 'enumerated', - values: ['inside', 'outside', 'both', 'none'], - role: 'info', - dflt: 'both', - editType: 'calc', - description: [ - 'Constrain the size of text inside or outside a bar to be no', - 'larger than the bar itself.' - ].join(' ') - }, + // overlap with the bottom - positive vals are overlaps + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; - cliponaxis: __extendFlat_678({}, _$attributes_862.cliponaxis, { - description: [ - 'Determines whether the text nodes', - 'are clipped about the subplot axes.', - 'To show the text nodes above axis lines and tick labels,', - 'make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*.' - ].join(' ') - }), + // check for min overlap first, so that we always + // see the largest labels + // allow for .01px overlap, so we don't get an + // infinite loop from rounding errors + if(topOverlap > 0.01) { + for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; + donepositioning = false; + } + if(bottomOverlap < 0.01) return; + if(topOverlap < -0.01) { + // make sure we're not pushing back and forth + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + donepositioning = false; + } + if(!donepositioning) return; - orientation: { - valType: 'enumerated', - role: 'info', - values: ['v', 'h'], - editType: 'calc+clearAxisTypes', - description: [ - 'Sets the orientation of the bars.', - 'With *v* (*h*), the value of the each bar spans', - 'along the vertical (horizontal).' - ].join(' ') - }, - - base: { - valType: 'any', - dflt: null, - arrayOk: true, - role: 'info', - editType: 'calc', - description: [ - 'Sets where the bar base is drawn (in position axis units).', - 'In *stack* or *relative* barmode,', - 'traces that set *base* will be excluded', - 'and drawn in *overlay* mode instead.' - ].join(' ') - }, - - offset: { - valType: 'number', - dflt: null, - arrayOk: true, - role: 'info', - editType: 'calc', - description: [ - 'Shifts the position where the bar is drawn', - '(in position axis units).', - 'In *group* barmode,', - 'traces that set *offset* will be excluded', - 'and drawn in *overlay* mode instead.' - ].join(' ') - }, + // no room to fix positioning, delete off-screen points - width: { - valType: 'number', - dflt: null, - min: 0, - arrayOk: true, - role: 'info', - editType: 'calc', - description: [ - 'Sets the bar width (in position axis units).' - ].join(' ') - }, + // first see how many points we need to delete + var deleteCount = 0; + for(i = 0; i < grp.length; i++) { + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } - marker: marker, + // start by deleting points whose data is off screen + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; - selected: { - marker: { - opacity: _$attributes_862.selected.marker.opacity, - color: _$attributes_862.selected.marker.color, - editType: 'style' - }, - textfont: _$attributes_862.selected.textfont, - editType: 'style' - }, - unselected: { - marker: { - opacity: _$attributes_862.unselected.marker.opacity, - color: _$attributes_862.unselected.marker.color, - editType: 'style' - }, - textfont: _$attributes_862.unselected.textfont, - editType: 'style' - }, + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } + } + for(i = 0; i < grp.length; i++) { + if(deleteCount <= 0) break; + pti = grp[i]; - r: _$attributes_862.r, - t: _$attributes_862.t, + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; - _deprecated: { - bardir: { - valType: 'enumerated', - role: 'info', - editType: 'calc', - values: ['v', 'h'], - description: 'Renamed to `orientation`.' + // shift the whole group minus into this new space + bottomOverlap = pti.size * 2; + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + } + } + // then delete points that go off the bottom + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } } } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // loop through groups, combining them if they overlap, + // until nothing moves + while(!donepositioning && nummoves <= hoverData.length) { + // to avoid infinite loops, don't move more times + // than there are traces + nummoves++; -'use strict'; + // assume nothing will move in this iteration, + // reverse this if it does + donepositioning = true; + i = 0; + while(i < pointgroups.length - 1) { + // the higher (g0) and lower (g1) point group + var g0 = pointgroups[i], + g1 = pointgroups[i + 1], + + // the lowest point in the higher group (p0) + // the highest point in the lower group (p1) + p0 = g0[g0.length - 1], + p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; + + // Only group points that lie on the same axes + if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { + // push the new point(s) added to this group out of the way + for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; + + // add them to the group + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); -/* removed: var _$lib_539 = require('../../lib'); */; + // adjust for minimum average movement + sumdp = 0; + for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } + else i++; + } -var _$calcSelection_864 = function calcSelection(cd, trace) { - if(_$lib_539.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_539.tagSelected(cd, trace); + // check if we're going off the plot on either side and fix + pointgroups.forEach(constrainGroup); } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // now put these offsets into hoverData + for(i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for(j = grp.length - 1; j >= 0; j--) { + var pt = grp[j], + hoverPt = hoverData[pt.i]; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } + } +} +function alignHoverText(hoverLabels, rotateLabels) { + // finally set the text positioning relative to the data and draw the + // box around it + hoverLabels.each(function(d) { + var g = _$d3_130.select(this); + if(d.del) { + g.remove(); + return; + } + var horzSign = d.anchor === 'end' ? -1 : 1, + tx = g.select('text.nums'), + alignShift = {start: 1, end: -1, middle: 0}[d.anchor], + txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), + tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), + offsetX = 0, + offsetY = d.offset; + if(d.anchor === 'middle') { + txx -= d.tx2width / 2; + tx2x += d.txwidth / 2 + HOVERTEXTPAD; + } + if(rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = d.offset * YSHIFTX; + } -'use strict'; + g.select('path').attr('d', d.anchor === 'middle' ? + // middle aligned: rect centered on data + ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + + 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : + // left or right aligned: side rect with arrow to data + ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + + 'v' + (d.by / 2 - HOVERARROWSIZE) + + 'h' + (horzSign * d.bx) + + 'v-' + d.by + + 'H' + (horzSign * HOVERARROWSIZE + offsetX) + + 'V' + (offsetY - HOVERARROWSIZE) + + 'Z')); -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_679 = _$lib_539.isArrayOrTypedArray; + tx.call(_$svg_text_utils_625.positionText, + txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_677 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; + if(d.tx2width) { + g.select('text.name') + .call(_$svg_text_utils_625.positionText, + tx2x + alignShift * HOVERTEXTPAD + offsetX, + offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + g.select('rect') + .call(_$drawing_498.setRect, + tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, + offsetY - d.by / 2 - 1, + d.tx2width, d.by + 2); + } + }); +} -var _$calc_679 = function calc(gd, trace) { - // depending on bar direction, set position and size axes - // and data ranges - // note: this logic for choosing orientation is - // duplicated in graph_obj->setstyles +function cleanPoint(d, hovermode) { + var index = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index] || {}; - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'), - orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), - sa, pos, size, i, scalendar; + var getVal = Array.isArray(index) ? + function(calcKey, traceKey) { + return _$lib_601.castOption(cd0, index, calcKey) || + _$lib_601.extractOption({}, trace, '', traceKey); + } : + function(calcKey, traceKey) { + return _$lib_601.extractOption(cd, trace, calcKey, traceKey); + }; - if(orientation === 'h') { - sa = xa; - size = xa.makeCalcdata(trace, 'x'); - pos = ya.makeCalcdata(trace, 'y'); + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if(val) d[key] = val; + } - // 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. - scalendar = trace.xcalendar; + fill('hoverinfo', 'hi', 'hoverinfo'); + fill('color', 'hbg', 'hoverlabel.bgcolor'); + fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); + fill('fontFamily', 'htf', 'hoverlabel.font.family'); + fill('fontSize', 'hts', 'hoverlabel.font.size'); + fill('fontColor', 'htc', 'hoverlabel.font.color'); + fill('nameLength', 'hnl', 'hoverlabel.namelength'); + + d.posref = hovermode === 'y' ? + (d.xa._offset + (d.x0 + d.x1) / 2) : + (d.ya._offset + (d.y0 + d.y1) / 2); + + // then constrain all the positions to be on the plot + d.x0 = _$lib_601.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_601.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_601.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_601.constrain(d.y1, 0, d.ya._length); + + // and convert the x and y label values into formatted text + if(d.xLabelVal !== undefined) { + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_647.hoverLabelText(d.xa, d.xLabelVal); + d.xVal = d.xa.c2d(d.xLabelVal); } - else { - sa = ya; - size = ya.makeCalcdata(trace, 'y'); - pos = xa.makeCalcdata(trace, 'x'); - scalendar = trace.ycalendar; + if(d.yLabelVal !== undefined) { + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_647.hoverLabelText(d.ya, d.yLabelVal); + d.yVal = d.ya.c2d(d.yLabelVal); } - // create the "calculated data" to plot - var serieslen = Math.min(pos.length, size.length); - var cd = new Array(serieslen); + // Traces like heatmaps generate the zLabel in their hoverPoints function + if(d.zLabelVal !== undefined && d.zLabel === undefined) { + d.zLabel = String(d.zLabelVal); + } - // set position and size - for(i = 0; i < serieslen; i++) { - cd[i] = { p: pos[i], s: size[i] }; + // for box means and error bars, add the range to the label + if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { + var xeText = _$axes_647.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + if(d.xerrneg !== undefined) { + d.xLabel += ' +' + xeText + ' / -' + + _$axes_647.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + else d.xLabel += ' ± ' + xeText; - if(trace.ids) { - cd[i].id = String(trace.ids[i]); + // small distance penalty for error bars, so that if there are + // traces with errors and some without, the error bar label will + // hoist up to the point + if(hovermode === 'x') d.distance += 1; + } + if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { + var yeText = _$axes_647.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + if(d.yerrneg !== undefined) { + d.yLabel += ' +' + yeText + ' / -' + + _$axes_647.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; } + else d.yLabel += ' ± ' + yeText; + + if(hovermode === 'y') d.distance += 1; } - // set base - var base = trace.base, - b; + var infomode = d.hoverinfo || d.trace.hoverinfo; - if(__isArrayOrTypedArray_679(base)) { - for(i = 0; i < Math.min(base.length, cd.length); i++) { - b = sa.d2c(base[i], 0, scalendar); - if(_$fastIsnumeric_139(b)) { - cd[i].b = +b; - cd[i].hasB = 1; + if(infomode !== 'all') { + infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); + if(infomode.indexOf('x') === -1) d.xLabel = undefined; + if(infomode.indexOf('y') === -1) d.yLabel = undefined; + if(infomode.indexOf('z') === -1) d.zLabel = undefined; + if(infomode.indexOf('text') === -1) d.text = undefined; + if(infomode.indexOf('name') === -1) d.name = undefined; + } + + return d; +} + +function createSpikelines(closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var evt = opts.event; + var xa, + ya; + + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; + + // Remove old spikeline items + container.selectAll('.spikeline').remove(); + + if(!(showX || showY)) return; + + var contrastColor = _$color_473.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + + // Horizontal line (to y-axis) + if(showY) { + var hLinePoint = closestPoints.hLinePoint, + hLinePointX, + hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; + + if(ySnap === 'cursor') { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = _$tinycolor_414.readability(hLinePoint.color, contrastColor) < 1.5 ? + _$color_473.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode, + yThickness = ya.spikethickness, + yColor = ya.spikecolor || dfltHLineColor, + yBB = ya._boundingBox, + xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, + xBase, + xEndSpike; + + if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { + if(yMode.indexOf('toaxis') !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; } - else cd[i].b = 0; + if(yMode.indexOf('across') !== -1) { + xBase = ya._counterSpan[0]; + xEndSpike = ya._counterSpan[1]; + } + + // Foreground horizontal line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness, + 'stroke': yColor, + 'stroke-dasharray': _$drawing_498.dashStyle(ya.spikedash, yThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background horizontal Line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); } - for(; i < cd.length; i++) { - cd[i].b = 0; + // Y axis marker + if(yMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), + 'cy': hLinePointY, + 'r': yThickness, + 'fill': yColor + }) + .classed('spikeline', true); } } - else { - b = sa.d2c(base, 0, scalendar); - var hasBase = _$fastIsnumeric_139(b); - b = hasBase ? b : 0; - for(i = 0; i < cd.length; i++) { - cd[i].b = b; - if(hasBase) cd[i].hasB = 1; + + if(showX) { + var vLinePoint = closestPoints.vLinePoint, + vLinePointX, + vLinePointY; + + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; + + if(xSnap === 'cursor') { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; } - } + var dfltVLineColor = _$tinycolor_414.readability(vLinePoint.color, contrastColor) < 1.5 ? + _$color_473.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode, + xThickness = xa.spikethickness, + xColor = xa.spikecolor || dfltVLineColor, + xBB = xa._boundingBox, + yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, + yBase, + yEndSpike; - // auto-z and autocolorscale if applicable - if(_$hasColorscale_425(trace, 'marker')) { - _$calc_418(trace, trace.marker.color, 'marker', 'c'); - } - if(_$hasColorscale_425(trace, 'marker.line')) { - _$calc_418(trace, trace.marker.line.color, 'marker.line', 'c'); + if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { + if(xMode.indexOf('toaxis') !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if(xMode.indexOf('across') !== -1) { + yBase = xa._counterSpan[0]; + yEndSpike = xa._counterSpan[1]; + } + + // Foreground vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness, + 'stroke': xColor, + 'stroke-dasharray': _$drawing_498.dashStyle(xa.spikedash, xThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + + // X axis marker + if(xMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': vLinePointX, + 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), + 'r': xThickness, + 'fill': xColor + }) + .classed('spikeline', true); + } } +} - _$arraysToCalcdata_677(cd, trace); - _$calcSelection_864(cd, trace); +function hoverChanged(gd, evt, oldhoverdata) { + // don't emit any events if nothing changed + if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; - return cd; -}; + for(var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i], + newPt = gd._hoverdata[i]; + if(oldPt.curveNumber !== newPt.curveNumber || + String(oldPt.pointNumber) !== String(newPt.pointNumber)) { + return true; + } + } + return false; +} + +function spikesChanged(gd, oldspikepoints) { + // don't relayout the plot because of new spikelines if spikelines points didn't change + if(!oldspikepoints) return true; + if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || + oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint + ) return true; + return false; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -31908,34 +32833,33 @@ var _$calc_679 = function calc(gd, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +var hover = _$hover_513.hover; -var _$handleStyleDefaults_690 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { - coerce('marker.color', defaultColor); +var _$click_509 = function click(gd, evt, subplot) { + var annotationsDone = _$registry_731.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); - if(_$hasColorscale_425(traceIn, 'marker')) { - _$colorScaleDefaults_421( - traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} - ); + // 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); } - coerce('marker.line.color', _$color_411.defaultLine); + function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } - if(_$hasColorscale_425(traceIn, 'marker.line')) { - _$colorScaleDefaults_421( - traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} - ); - } + if(gd._hoverdata && evt && evt.target) { + if(annotationsDone && annotationsDone.then) { + annotationsDone.then(emitClick); + } + else emitClick(); - coerce('marker.line.width'); - coerce('marker.opacity'); - coerce('selected.marker.color'); - coerce('unselected.marker.color'); + // why do we get a double event without this??? + if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); + } }; /** @@ -31946,41 +32870,39 @@ var _$handleStyleDefaults_690 = function handleStyleDefaults(traceIn, traceOut, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var _$handleHoverLabelDefaults_514 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { + opts = opts || {}; -var _$handleXYDefaults_886 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { - var len, - x = coerce('x'), - y = coerce('y'); + coerce('hoverlabel.bgcolor', opts.bgcolor); + coerce('hoverlabel.bordercolor', opts.bordercolor); + coerce('hoverlabel.namelength', opts.namelength); + _$lib_601.coerceFont(coerce, 'hoverlabel.font', opts.font); +}; - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(x) { - if(y) { - len = Math.min(x.length, y.length); - } - else { - len = x.length; - coerce('y0'); - coerce('dy'); - } - } - else { - if(!y) return 0; +'use strict'; - len = traceOut.y.length; - coerce('x0'); - coerce('dx'); - } +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_507 = require('./attributes'); */; +/* removed: var _$handleHoverLabelDefaults_514 = require('./hoverlabel_defaults'); */; - traceOut._length = len; +var _$supplyDefaults_511 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_507, attr, dflt); + } - return len; + _$handleHoverLabelDefaults_514(traceIn, traceOut, coerce, layout.hoverlabel); }; /** @@ -31991,131 +32913,180 @@ var _$handleXYDefaults_886 = function handleXYDefaults(traceIn, traceOut, layout * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$constants_510 = require('./constants'); */; -/* removed: var _$handleXYDefaults_886 = require('../scatter/xy_defaults'); */; -/* removed: var _$handleStyleDefaults_690 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_678 = require('./attributes'); */; +var __fontAttrs_516 = _$font_attributes_673({ + editType: 'none', + description: 'Sets the default hover label font used by all traces on the graph.' +}); +__fontAttrs_516.family.dflt = _$constants_510.HOVERFONT; +__fontAttrs_516.size.dflt = _$constants_510.HOVERFONTSIZE; -var _$supplyDefaults_680 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_678, attr, dflt); +var _$layout_attributes_516 = { + dragmode: { + valType: 'enumerated', + role: 'info', + values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], + dflt: 'zoom', + editType: 'modebar', + description: [ + 'Determines the mode of drag interactions.', + '*select* and *lasso* apply only to scatter traces with', + 'markers or text. *orbit* and *turntable* apply only to', + '3D scenes.' + ].join(' ') + }, + hovermode: { + valType: 'enumerated', + role: 'info', + values: ['x', 'y', 'closest', false], + editType: 'modebar', + description: 'Determines the mode of hover interactions.' + }, + hoverdistance: { + valType: 'integer', + min: -1, + dflt: 20, + role: 'info', + editType: 'none', + description: [ + 'Sets the default distance (in pixels) to look for data', + 'to add hover labels (-1 means no cutoff, 0 means no looking for data).', + 'This is only a real distance for hovering on point-like objects,', + 'like scatter points. For area-like objects (bars, scatter fills, etc)', + 'hovering is on inside the area and off outside, but these objects', + 'will not supersede hover on point-like objects in case of conflict.' + ].join(' ') + }, + spikedistance: { + valType: 'integer', + min: -1, + dflt: 20, + role: 'info', + editType: 'none', + description: [ + 'Sets the default distance (in pixels) to look for data to draw', + 'spikelines to (-1 means no cutoff, 0 means no looking for data).', + 'As with hoverdistance, distance does not apply to area-like objects.', + 'In addition, some objects can be hovered on but will not generate', + 'spikelines, such as scatter fills.' + ].join(' ') + }, + hoverlabel: { + bgcolor: { + valType: 'color', + role: 'style', + editType: 'none', + description: [ + 'Sets the background color of all hover labels on graph' + ].join(' ') + }, + bordercolor: { + valType: 'color', + role: 'style', + editType: 'none', + description: [ + 'Sets the border color of all hover labels on graph.' + ].join(' ') + }, + font: __fontAttrs_516, + namelength: { + valType: 'integer', + min: -1, + dflt: 15, + role: 'style', + editType: 'none', + description: [ + 'Sets the default length (in number of characters) of the trace name in', + 'the hover labels for all traces. -1 shows the whole name', + 'regardless of length. 0-3 shows the first 0-3 characters, and', + 'an integer >3 will show the whole name if it is less than that', + 'many characters, but if it is longer, will truncate to', + '`namelength - 3` characters and add an ellipsis.' + ].join(' ') + }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + role: 'info', + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + description: [ + 'When "dragmode" is set to "select", this limits the selection of the drag to', + 'horizontal, vertical or diagonal. "h" only allows horizontal selection,', + '"v" only vertical, "d" only diagonal and "any" sets no limit.' + ].join(' '), + editType: 'none' } +}; - var coerceFont = _$lib_539.coerceFont; - - var len = _$handleXYDefaults_886(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); - coerce('base'); - coerce('offset'); - coerce('width'); +'use strict'; - coerce('text'); - coerce('hovertext'); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_516 = require('./layout_attributes'); */; - var textPosition = coerce('textposition'); +var _$supplyLayoutDefaults_517 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_516, attr, dflt); + } - var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', - hasInside = hasBoth || textPosition === 'inside', - hasOutside = hasBoth || textPosition === 'outside'; + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); - if(hasInside || hasOutside) { - var textFont = coerceFont(coerce, 'textfont', layout.font); - if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); - if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); - coerce('constraintext'); - coerce('selected.textfont.color'); - coerce('unselected.textfont.color'); - coerce('cliponaxis'); + var hovermodeDflt; + if(layoutOut._has('cartesian')) { + // flag for 'horizontal' plots: + // determines the state of the mode bar 'compare' hovermode button + layoutOut._isHoriz = isHoriz(fullData); + hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; } + else hovermodeDflt = 'closest'; - _$handleStyleDefaults_690(traceIn, traceOut, coerce, defaultColor, layout); + var hoverMode = coerce('hovermode', hovermodeDflt); + if(hoverMode) { + coerce('hoverdistance'); + coerce('spikedistance'); + } - // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'x', inherit: 'y'}); + // if only mapbox or geo subplots is present on graph, + // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, + // so that the correct modebar button is active + var hasMapbox = layoutOut._has('mapbox'); + var hasGeo = layoutOut._has('geo'); + var len = layoutOut._basePlotModules.length; - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + if(layoutOut.dragmode === 'zoom' && ( + ((hasMapbox || hasGeo) && len === 1) || + (hasMapbox && hasGeo && len === 2) + )) { + layoutOut.dragmode = 'pan'; + } }; -var _$client_246 = true; -var _$hasHover_239 = {}; -(function (global){ -'use strict' - -/* removed: var _$client_246 = require('is-browser') */; -var hasHover - -if (typeof global.matchMedia === 'function') { - hasHover = !global.matchMedia('(hover: none)').matches -} -else { - hasHover = _$client_246 -} - -_$hasHover_239 = hasHover - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -'use strict' - -/* removed: var _$client_246 = require('is-browser') */; - -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 -} - -var _$hasPassiveEvents_240 = _$client_246 && detect() +function isHoriz(fullData) { + var out = true; -var rootPosition = { left: 0, top: 0 } + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -var _$mouseEventOffset_263 = mouseEventOffset -function mouseEventOffset (ev, target, out) { - target = target || ev.currentTarget || ev.srcElement - if (!Array.isArray(out)) { - out = [ 0, 0 ] - } - var cx = ev.clientX || 0 - var cy = ev.clientY || 0 - var rect = getBoundingClientOffset(target) - out[0] = cx - rect.left - out[1] = cy - rect.top - return out -} + if(trace.orientation !== 'h') { + out = false; + break; + } + } -function getBoundingClientOffset (element) { - if (element === window || - element === document || - element === document.body) { - return rootPosition - } else { - return element.getBoundingClientRect() - } + return out; } /** @@ -32126,28 +33097,18 @@ function getBoundingClientOffset (element) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleHoverLabelDefaults_514 = require('./hoverlabel_defaults'); */; +/* removed: var _$layout_attributes_516 = require('./layout_attributes'); */; -// 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 -var _$align_431 = function align(v, dv, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0), - vmax = vmin + dv / (v1 - v0), - 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; +var _$supplyLayoutGlobalDefaults_518 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce(attr, dflt) { + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_516, attr, dflt); + } - // automatic based on position - if(vmin < (2 / 3) - vc) return vmin; - if(vmax > (4 / 3) - vc) return vmax; - return vc; + _$handleHoverLabelDefaults_514(layoutIn, layoutOut, coerce); }; /** @@ -32158,882 +33119,4090 @@ var _$align_431 = function align(v, dv, v0, v1, anchor) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$helpers_512 = require('./helpers'); */; +/* removed: var _$layout_attributes_516 = require('./layout_attributes'); */; +var _$fx_515 = { + moduleType: 'component', + name: 'fx', -// 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'] -]; - -var _$getCursor_432 = 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_539.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_539.constrain(Math.floor(y * 3), 0, 2); + constants: _$constants_510, + schema: { + layout: _$layout_attributes_516 + }, - return cursorset[y][x]; -}; + attributes: _$attributes_507, + layoutAttributes: _$layout_attributes_516, -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_518, + supplyDefaults: _$supplyDefaults_511, + supplyLayoutDefaults: _$supplyLayoutDefaults_517, -'use strict'; + calc: _$calc_508, -var _$constants_448 = { - // hover labels for multiple horizontal bars get tilted by this angle - YANGLE: 60, + getDistanceFunction: _$helpers_512.getDistanceFunction, + getClosest: _$helpers_512.getClosest, + inbox: _$helpers_512.inbox, + quadrature: _$helpers_512.quadrature, + appendArrayPointValue: _$helpers_512.appendArrayPointValue, - // size and display constants for hover text + castHoverOption: castHoverOption, + castHoverinfo: castHoverinfo, - // pixel size of hover arrows - HOVERARROWSIZE: 6, - // pixels padding around text - HOVERTEXTPAD: 3, - // hover font - HOVERFONTSIZE: 13, - HOVERFONT: 'Arial, sans-serif', + hover: _$hover_513.hover, + unhover: _$dragelement_495.unhover, - // minimum time (msec) between hover calls - HOVERMINTIME: 50, + loneHover: _$hover_513.loneHover, + loneUnhover: loneUnhover, - // ID suffix (with fullLayout._uid) for hover events in the throttle cache - HOVERID: '-hover' + click: _$click_509 }; -// 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. +function loneUnhover(containerOrSelection) { + // duck type whether the arg is a d3 selection because ie9 doesn't + // handle instanceof like modern browsers do. + var selection = _$lib_601.isD3Selection(containerOrSelection) ? + containerOrSelection : + _$d3_130.select(containerOrSelection); -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; + selection.selectAll('g.hovertext').remove(); + selection.selectAll('.spikeline').remove(); } -var _$EventEmitter_137 = EventEmitter; -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; +// helpers for traces that use Fx.loneHover -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; +function castHoverOption(trace, ptNumber, attr) { + return _$lib_601.castOption(trace, ptNumber, 'hoverlabel.' + attr); +} -// 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. -EventEmitter.defaultMaxListeners = 10; +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return _$lib_601.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + } -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; + return _$lib_601.castOption(trace, ptNumber, 'hoverinfo', _coerce); +} -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (!this._events) - this._events = {}; +'use strict'; - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } +/** + * 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 + */ +var _$clearGlCanvases_585 = 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}); + }); } - } +}; - handler = this._events[type]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (isUndefined(handler)) - return false; - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } +'use strict'; - return true; -}; +var FROM_BL = _$alignment_573.FROM_BL; -EventEmitter.prototype.addListener = function(type, listener) { - var m; +var _$scaleZoom_663 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; + } - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - if (!this._events) - this._events = {}; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; +}; - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - return this; -}; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; +} -EventEmitter.prototype.on = EventEmitter.prototype.addListener; +var _$BuildLog_358 = BuildLog; -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - var fired = false; +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// - function g() { - this.removeListener(type, g); +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; - g.listener = listener; - this.on(type, g); + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; - return this; -}; + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - if (!isFunction(listener)) - throw TypeError('listener must be a function'); + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - if (!this._events || !this._events[type]) - return this; + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; - list = this._events[type]; - length = list.length; - position = -1; + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); + // categorize where intersection point is along A and B - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; - if (position < 0) - return this; + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside - return this; -}; + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; +var _$Epsilon_359 = Epsilon; - if (!this._events) - return this; +// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } +// +// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) +// - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ - listeners = this._events[type]; + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; + // 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] }); + } - return this; -}; + // the first LineString is considered the outside + var out = LineString(coords[0]); -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; + // 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]))); -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + return out; + } - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; + 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'); + }, -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; + // 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)); -function isFunction(arg) { - return typeof arg === 'function'; -} + // 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); + } -function isNumber(arg) { - return typeof arg === 'number'; -} + // calculate inside heirarchy + // + // _____________________ _______ roots -> A -> F + // | A | | F | | | + // | _______ _______ | | ___ | +-- B +-- G + // | | B | | C | | | | | | | | + // | | ___ | | ___ | | | | | | | +-- D + // | | | D | | | | E | | | | | G | | | + // | | |___| | | |___| | | | | | | +-- C + // | |_______| |_______| | | |___| | | + // |_____________________| |_______| +-- E -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} + function newNode(region){ + return { + region: region, + children: [] + }; + } -function isUndefined(arg) { - return arg === void 0; -} + var roots = newNode(null); -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + 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--; + } + } -'use strict'; + // now we can add ourselves + root.children.push(node); + } -/* global jQuery:false */ + // 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); + } -var __EventEmitter_527 = _$EventEmitter_137.EventEmitter; + // 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 -var Events = { + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - init: function(plotObj) { + 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; + } - /* - * If we have already instantiated an emitter for this plot - * return early. - */ - if(plotObj._ev instanceof __EventEmitter_527) return plotObj; + var geopolys = []; - var ev = new __EventEmitter_527(); - var internalEv = new __EventEmitter_527(); + 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])); + } - /* - * Assign to plot._ev while we still live in a land - * where plot is a DOM element with stuff attached to it. - * In the future we can make plot the event emitter itself. - */ - plotObj._ev = ev; + 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); + } - /* - * Create a second event handler that will manage events *internally*. - * This allows parts of plotly to respond to thing like relayout without - * having to use the user-facing event handler. They cannot peacefully - * coexist on the same handler because a user invoking - * plotObj.removeAllListeners() would detach internal events, breaking - * plotly. - */ - plotObj._internalEv = internalEv; + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - /* - * Assign bound methods from the ev to the plot object. These methods - * will reference the 'this' of plot._ev even though they are methods - * of plot. This will keep the event machinery away from the plot object - * which currently is often a DOM element but presents an API that will - * continue to function when plot becomes an emitter. Not all EventEmitter - * methods have been bound to `plot` as some do not currently add value to - * the Plotly event API. - */ - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); + // lastly, construct the approrpriate GeoJSON object - /* - * Create funtions for managing internal events. These are *only* triggered - * by the mirroring of external events via the emit function. - */ - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); + 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 + }; + } +}; - /* - * We must wrap emit to continue to support JQuery events. The idea - * is to check to see if the user is using JQuery events, if they are - * we emit JQuery events to trigger user handlers as well as the EventEmitter - * events. - */ - plotObj.emit = function(event, data) { - if(typeof jQuery !== 'undefined') { - jQuery(plotObj).trigger(event, data); - } +var _$GeoJSON_360 = GeoJSON; - ev.emit(event, data); - internalEv.emit(event, data); - }; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - return plotObj; - }, +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// - /* - * This function behaves like jQueries triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - * - * Note: triggerHandler has been recommended for deprecation in v2.0.0, - * so the additional behavior of triggerHandler triggering internal events - * is deliberate excluded in order to avoid reinforcing more usage. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - /* - * If Jquery exists run all its handlers for this event and - * collect the return value of the LAST handler function - */ - if(typeof jQuery !== 'undefined') { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); - } +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } +}; - /* - * Now run all the node style event handlers - */ - var ev = plotObj._ev; - if(!ev) return jQueryHandlerValue; +var _$LinkedList_362 = LinkedList; - var handlers = ev._events[event]; - if(!handlers) return jQueryHandlerValue; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - /* - * handlers can be function or an array of functions - */ - if(typeof handlers === 'function') handlers = [handlers]; - var lastHandler = handlers.pop(); +// +// this is the core work-horse +// - /* - * Call all the handlers except the last one. - */ - for(var i = 0; i < handlers.length; i++) { - handlers[i](data); - } +/* removed: var _$LinkedList_362 = require('./linked-list'); */; - /* - * Now call the final handler and collect its value - */ - nodeEventHandlerValue = lastHandler(data); +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm - /* - * Return either the jquery handler value if it exists or the - * nodeEventHandler value. Jquery event value superceeds nodejs - * events for backwards compatability reasons. - */ - return jQueryHandlerValue !== undefined ? jQueryHandlerValue : - nodeEventHandlerValue; - }, + // + // segment creation + // - purge: function(plotObj) { - delete plotObj._ev; - delete plotObj.on; - delete plotObj.once; - delete plotObj.removeListener; - delete plotObj.removeAllListeners; - delete plotObj.emit; + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } - return plotObj; - } + // + // event logic + // -}; + var event_root = _$LinkedList_362.create(); -var _$Events_527 = Events; + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same -var _$unhover_434 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start -'use strict'; + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } -/* removed: var _$Events_527 = require('../../lib/events'); */; -/* removed: var _$throttle_563 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_534 = require('../../lib/get_graph_div'); */; + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_362.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } -/* removed: var _$constants_448 = require('../fx/constants'); */; + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_362.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } -var unhover = _$unhover_434 = {}; + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) -unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_534(gd); + if (buildLog) + buildLog.segmentChop(ev.seg, end); - // Important, clear any queued hovers - if(gd._fullLayout) { - _$throttle_563.clear(gd._fullLayout._uid + _$constants_448.HOVERID); - } + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } - unhover.raw(gd, evt, subplot); -}; + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used -// remove hover effects on mouse out, and emit unhover event -unhover.raw = function unhoverRaw(gd, evt) { - var fullLayout = gd._fullLayout; - var oldhoverdata = gd._hoverdata; + // + // status logic + // - if(!evt) evt = {}; - if(evt.target && - _$Events_527.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } + var status_root = _$LinkedList_362.create(); - fullLayout._hoverlayer.selectAll('g').remove(); - fullLayout._hoverlayer.selectAll('line').remove(); - fullLayout._hoverlayer.selectAll('circle').remove(); - gd._hoverdata = undefined; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; - if(evt.target && oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } -}; + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } -var _$dragelement_433 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal -'use strict'; + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; -/* removed: var _$mouseEventOffset_263 = require('mouse-event-offset'); */; -/* removed: var _$hasHover_239 = require('has-hover'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; + if (buildLog) + buildLog.checkIntersection(seg1, seg2); -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; + var i = eps.linesIntersect(a1, a2, b1, b2); -/* removed: var _$constants_589 = require('../../plots/cartesian/constants'); */; -/* removed: var _$interactions_516 = require('../../constants/interactions'); */; + if (i === false){ + // segments are parallel or coincident -var dragElement = _$dragelement_433 = {}; + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) -dragElement.align = _$align_431; -dragElement.getCursor = _$getCursor_432; + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection -/* removed: var _$unhover_434 = require('./unhover'); */; -dragElement.unhover = _$unhover_434.wrapped; -dragElement.unhoverRaw = _$unhover_434.raw; + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal -/** - * 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 DBLCLICKDELAY = _$interactions_516.DBLCLICKDELAY; - var element = options.element; + var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - var startX, - startY, - newMouseDownTime, - cursor, - dragCover, - initialEvent, - initialTarget, - rightClick; + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); + + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } + + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } + + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } + + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); + + if (buildLog) + buildLog.vert(ev.pt[0]); + + if (ev.isStart){ + + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); + + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; + + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } + + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } + + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev + + // merge ev.seg's fill information into eve.seg + + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } + + if (buildLog) + buildLog.segmentUpdate(eve.seg); + + ev.other.remove(); + ev.remove(); + } + + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } + + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } + + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point + + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } + + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } + + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_362.node({ ev: ev })); + } + else{ + var st = ev.status; + + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } + + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); + + if (buildLog) + buildLog.statusRemove(st.ev.seg); + + // remove the status + st.remove(); + + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } + + // remove the event and continue + event_root.getHead().remove(); + } + + if (buildLog) + buildLog.done(); + + return segments; + } + + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } + + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; + + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it + + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} + +var _$Intersecter_361 = Intersecter; + +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs + +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// + +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; + + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } + + if (buildLog) + buildLog.chainStart(seg); + + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } + + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } + + if (next_match === second_match){ + // we matched a single chain + + if (buildLog) + buildLog.chainMatch(first_match.index); + + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop + + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head + + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } + + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); + + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } + + if (buildLog) + buildLog.chainClose(first_match.index); + + // we have a closed chain! + regions.push(chain); + return; + } + + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } + + // otherwise, we matched two chains, so we need to combine those chains together + + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } + + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; + + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } + + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } + + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } + + var F = first_match.index; + var S = second_match.index; + + if (buildLog) + buildLog.chainConnect(F, S); + + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); + + return regions; +} + +var _$SegmentChainer_363 = SegmentChainer; + +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs + +// +// filter a list of segments based on boolean operations +// + +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); + + if (buildLog) + buildLog.selected(result); + + return result; +} + +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; + +var _$SegmentSelector_364 = SegmentSelector; + +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ + +/* removed: var _$BuildLog_358 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_359 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_361 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_363 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_364 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_360 = require('./lib/geojson'); */; + +var buildLog = false; +var epsilon = _$Epsilon_359(); + +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_358(); + 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_361(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_361(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_364.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_364.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_364.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_364.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_364.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_363(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, + + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_360.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_360.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; + +var _$PolyBool_357 = PolyBool; + +var _$polygon_613 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +var dot = _$matrix_607.dot; +var __BADNUM_613 = _$numerical_578.BADNUM; + +var polygon = _$polygon_613 = {}; + +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); + + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; + + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); + } + + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed + + var isRect = false, + rectFirstEdgeTest; + + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; + } + } + } + + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; + + if(x === __BADNUM_613 || x < xmin || x > xmax || y === __BADNUM_613 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + + return true; + } + + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; + + if(x === __BADNUM_613 || x < xmin || x > xmax || y === __BADNUM_613 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; + + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); + + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); + + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } + + if(y <= ycross && x !== xmini) crossings++; + } + } + + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; + } + + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; + } + } + + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; +}; + +/** + * Test multiple polygons + */ +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; + + for(var i = 0; i < list.length; i++) { + 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); + } + + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } + + return yes; + } + + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; +}; + +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; + + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); + + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; + } + return false; +}; + +/** + * Make a filtering polygon, to minimize the number of segments + * + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon + * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs + */ +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; + + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); + + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } + } + } + + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } + + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$PolyBool_357 = require('polybooljs'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; + +/* removed: var _$polygon_613 = require('../../lib/polygon'); */; +/* removed: var _$throttle_626 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_512.makeEventData; +var getFromId = _$axis_ids_650.getFromId; +var __sortModules_664 = _$sort_modules_722.sortModules; + +/* removed: var _$constants_652 = require('./constants'); */; +var MINSELECT = _$constants_652.MINSELECT; + +var filteredPolygon = _$polygon_613.filter; +var polygonTester = _$polygon_613.tester; +var multipolygonTester = _$polygon_613.multitester; + +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; + + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); + + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + } + + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } + + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_652.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_473.background, + stroke: _$color_473.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); + + + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_652.SELECTID; + var selection = []; + + 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(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); + } + } + + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(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] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(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), + 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.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } + + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); + } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); + + _$throttle_626.throttle( + throttleID, + _$constants_652.SELECTDELAY, + function() { + selection = []; + + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + 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) { + corners.remove(); + + _$throttle_626.done(throttleID).then(function() { + _$throttle_626.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); + gd.emit('plotly_deselect', null); + } + else { + // 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. + gd.emit('plotly_selected', undefined); + } + + _$fx_515.click(gd, evt); + }); + }; + + dragOptions.doneFn = function() { + corners.remove(); + + _$throttle_626.done(throttleID).then(function() { + _$throttle_626.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); + + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); + + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} + +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; + + if(eventData) { + var pts = eventData.points || []; + + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.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); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + 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; + } + } + + // group searchInfo traces by trace modules + var lookup = {}; + + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; + } + } + + var keys = Object.keys(lookup).sort(__sortModules_664); + + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_731.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } + } + } +} + +function mergePolygons(list, poly, subtract) { + var res; + + if(subtract) { + res = _$PolyBool_357.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); + + return res.regions; + } + + res = _$PolyBool_357.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; +} + +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); +} + +var _$select_664 = { + prepSelect: prepSelect, + clearSelect: clearSelect +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_585 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +var FROM_TL = _$alignment_573.FROM_TL; + +/* removed: var _$plots_709 = require('../plots'); */; + +var doTicks = _$axes_647.doTicks; +var __getFromId_655 = _$axis_ids_650.getFromId; +var __prepSelect_655 = _$select_664.prepSelect; +var __clearSelect_655 = _$select_664.clearSelect; +/* removed: var _$scaleZoom_663 = require('./scale_zoom'); */; + +/* removed: var _$constants_652 = require('./constants'); */; +var MINDRAG = _$constants_652.MINDRAG; +var MINZOOM = _$constants_652.MINZOOM; + + +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; + +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; + + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; + + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; + + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; + + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } + + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; + + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; + } + + recomputeAxisLists(); + + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; + } + + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; + + recomputeAxisLists(); + + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } + + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; + + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_655(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_655(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; + + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; + + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_655(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); + + if(numClicks === 2 && !singleEnd) doubleClick(); + + if(isMainDrag) { + _$fx_515.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; + + if(ax.fixedrange) return; + + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; + + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_130.select(dragger) + .call(_$svg_text_utils_625.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_731.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; + + _$dragelement_495.init(dragOptions); + + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; + + // collected changes to be made to the plot by relayout at the end + var updates = {}; + + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_414(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; + + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); + + corners = makeCorners(zoomlayer, xs, ys); + + __clearSelect_655(zoomlayer); + } + + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } + + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); + + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); + + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); + } + + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; + + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; + } + + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } + + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } + + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } + + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_652.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; + + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } + + if(redrawTimer === null) { + __clearSelect_655(zoomlayer); + } + + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } + + var pc = gd.querySelector('.plotly'); + + recomputeAxisLists(); + + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } + + clearTimeout(redrawTimer); + + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_601.log('Did not find wheel motion attributes: ', e); + return; + } + + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; + + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; + + var axRange = _$lib_601.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } + + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; + + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } + + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; + + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } + + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } + + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); + + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; + + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + + dragTail(zoomMode); + }, REDRAWDELAY); + + e.preventDefault(); + return; + } + + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); + } + + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } + + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } + + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); + + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } + + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } + + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; + + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; + + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; + + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_663(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_663(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } + + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } + + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; + + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } + + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } + + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_655(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } + + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; + + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // 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 + + redrawObjs(gd._fullLayout.annotations || [], _$registry_731.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_731.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_731.getComponentMethod('images', 'draw'), true); + } + + function doubleClick() { + if(gd._transitioningWithDuration) return; + + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; + + var ax, i, rangeInitial; + + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { + + doubleClickConfig = 'autosize'; + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } + + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); + + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } + + gd.emit('plotly_doubleclick', null); + _$registry_731.call('relayout', gd, attrs); + } + + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); + + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_601.syncOrAsync([ + _$plots_709.previousPromises, + function() { _$registry_731.call('relayout', gd, updates); } + ], gd); + } + + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; + + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); + + var i, sp, xa, ya; + + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_585(gd); + } + + if(hasSplom) { + _$registry_731.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; + } + + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_601.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_601.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } + + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; + + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; + + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; + + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } + + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } + + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } + + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_498.setTranslate, clipDx, clipDy) + .call(_$drawing_498.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_498.setTranslate, plotDx, plotDy) + .call(_$drawing_498.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_498.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_498.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_498.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_498.hideOutsideRangePoints, sp, '.bartext'); + } + } + } + } + + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; + + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } + + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_663(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } + + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle']; + } + + return dragger; +} + +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_601.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); + }); + + dragger3.call(_$setCursor_621, cursor); + + return dragger3.node(); +} + +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_130.select(dragger).call(_$drawing_498.setRect, x, y, w, h); + return dragger; +} + +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} + +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; + + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_130.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_130.format('.' + String(dig) + 'g')(initialVal); + } +} + +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; + + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; + + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } + + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} + +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} + +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} + +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} + +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} + +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_473.background, + stroke: _$color_473.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} + +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} + +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); + } +} + +function removeZoombox(gd) { + _$d3_130.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} + +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_601.notifier(_$lib_601._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} + +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} + +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} + +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} + +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} + +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; + + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } + + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } + } + } + + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } + } + } + + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_601.extendFlat(xLinks, yLinks); + yLinks = {}; + } + + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_655(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; + } + + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_655(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; + } + + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} + +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_297) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; + } + else { + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; + + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); + } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); + } +} + +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; +} + +var _$dragbox_655 = { + makeDragBox: makeDragBox, + + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, + + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, + + attachWheelEventHandler: attachWheelEventHandler +}; + +var _$graph_interact_656 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_130 = require('d3'); */; + +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; + +var __makeDragBox_656 = _$dragbox_655.makeDragBox; +var DRAGGERSIZE = _$constants_652.DRAGGERSIZE; + +_$graph_interact_656.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; + + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_130.select(gd).selectAll('.drag').remove(); + return; + } + + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !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'), + 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_656(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) { + _$fx_515.hover(gd, evt, subplot); + } + }; + + _$fx_515.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_495.unhover(gd, evt); + }; + + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_656(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_656(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_656(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_656(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_656(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_656(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_656(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_656(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_656(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_656(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_515.hover(gd, evt, fullLayout._hoversubplot); + }; + + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_515.click(gd, evt); + }; + + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; + + _$graph_interact_656.updateFx(fullLayout); +}; + +// 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. +_$graph_interact_656.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_621(fullLayout._draggers, cursor); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; + + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } + + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } + } + + return Object.keys(lookup); +} + +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_651 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; - if(!gd._mouseDownTime) gd._mouseDownTime = 0; + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); - element.style.pointerEvents = 'all'; + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; - element.onmousedown = onStart; + var order = coerce('categoryorder', orderDefault); + var array; - if(!_$hasPassiveEvents_240) { - element.ontouchstart = onStart; + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); } - else { - if(element._ontouchstart) { - element.removeEventListener('touchstart', element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener('touchstart', onStart, {passive: false}); + + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; } - function _clampFn(dx, dy, minDrag) { - if(Math.abs(dx) < minDrag) dx = 0; - if(Math.abs(dy) < minDrag) dy = 0; - return [dx, dy]; + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } } +}; - var clampFn = options.clampFn || _clampFn; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function onStart(e) { - e.preventDefault(); +'use strict'; - // 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; +var colorMix = _$tinycolor_414.mix; +var lightFraction = _$attributes_472.lightFraction; +/* removed: var _$lib_601 = require('../../lib'); */; - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { - // in a click train - numClicks += 1; - } - else { - // new click train - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } +/** + * @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 + */ +var _$handleLineGridDefaults_661 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; - if(options.prepFn) options.prepFn(e, startX, startY); + var dfltColor = opts.dfltColor; - if(_$hasHover_239 && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } - else if(!_$hasHover_239) { - // 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; - } + function coerce2(attr, dflt) { + return _$lib_601.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + } - document.addEventListener('mousemove', onMove); - document.addEventListener('mouseup', onDone); - document.addEventListener('touchmove', onMove); - document.addEventListener('touchend', onDone); + var lineColor = coerce2('linecolor', dfltColor); + var lineWidth = coerce2('linewidth'); + var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); - return; + if(!showLine) { + delete containerOut.linecolor; + delete containerOut.linewidth; } - function onMove(e) { - e.preventDefault(); + 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); - var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_589.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; + if(!showGridLines) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; + } - if(dx || dy) { - gd._dragged = true; - dragElement.unhover(gd); + 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; } + } +}; - if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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; - } +'use strict'; - function onDone(e) { - document.removeEventListener('mousemove', onMove); - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchmove', onMove); - document.removeEventListener('touchend', onDone); +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; - e.preventDefault(); +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_668 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_651 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_661 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_665 = require('./set_convert'); */; - if(_$hasHover_239) { - _$lib_539.removeElement(dragCover); - } - else if(cursor) { - dragCover.documentElement.style.cursor = cursor; - cursor = null; - } +/** + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors + */ +var _$handleAxisDefaults_649 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; - if(!gd._dragging) { - gd._dragged = false; - return; - } - gd._dragging = false; + var visible = coerce('visible', !options.cheateronly); - // don't count as a dblClick unless the mouseUp is also within - // the dblclick delay - if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } + var axType = containerOut.type; - if(gd._dragged) { - if(options.doneFn) options.doneFn(e); - } - else { - if(options.clickFn) options.clickFn(numClicks, initialEvent); + if(axType === 'date') { + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); + } - // 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; + _$setConvert_665(containerOut, layoutOut); - 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); - } + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - initialTarget.dispatchEvent(e2); - } - } + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; - finishDrag(gd); + if(autoRange) coerce('rangemode'); - gd._dragged = false; + coerce('range'); + containerOut.cleanRange(); - return; - } -}; + _$handleCategoryOrderDefaults_651(containerIn, containerOut, coerce, options); -function coverSlip() { - var cover = document.createElement('div'); + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); - 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'; + if(!visible) return containerOut; - document.body.appendChild(cover); + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; - return cover; -} + coerce('title', dfltTitle); + _$lib_601.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); -dragElement.coverSlip = coverSlip; + _$handleTickValueDefaults_668(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_666(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_667(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_661(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_659 + }); -function finishDrag(gd) { - gd._dragging = false; - if(gd._replotPending) _$registry_668.call('plot', gd); -} + if(containerOut.showline || containerOut.ticks) coerce('mirror'); -function pointerOffset(e) { - return _$mouseEventOffset_263( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); -} + if(options.automargin) coerce('automargin'); + + return containerOut; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -33043,54 +37212,151 @@ function pointerOffset(e) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var id2name = _$axis_ids_650.id2name; -var _$calc_446 = function calc(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; - function makeCoerceHoverInfo(trace) { - return function(val) { - return _$lib_539.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); - }; - } +var _$handleConstraintDefaults_653 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + if(containerOut.fixedrange) return; - // 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_668.traceIs(trace, 'pie')) continue; + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_601.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' + } + }, 'constraintoward'); - var fillFn = _$registry_668.traceIs(trace, '2dMap') ? paste : _$lib_539.fillArray; + if(!containerIn.scaleanchor) return; - fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); - if(!trace.hoverlabel) continue; + var scaleanchor = _$lib_601.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes + } + }, 'scaleanchor'); - 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'); + 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, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_601.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.'); } }; -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_539.identity; +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. - if(Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); + 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 && !axj.fixedrange) linkableAxes.push(idj); + } + + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[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; } -var _$helpers_450 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -33099,220 +37365,225 @@ var _$helpers_450 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -// look for either subplot or xaxis and yaxis attributes -_$helpers_450.getSubplot = function getSubplot(trace) { - return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; -}; +/* removed: var _$lib_601 = require('../../lib'); */; -// convenience functions for mapping all relevant axes -_$helpers_450.flat = function flat(subplots, v) { - var out = new Array(subplots.length); - for(var i = 0; i < subplots.length; i++) { - out[i] = v; - } - return out; -}; -_$helpers_450.p2c = function p2c(axArray, v) { - var out = new Array(axArray.length); - for(var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); - } - return out; -}; +var _$handlePositionDefaults_662 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; -_$helpers_450.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { - if(mode === 'closest') return dxy || _$helpers_450.quadrature(dx, dy); - return mode === 'x' ? dx : dy; -}; + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; -_$helpers_450.getClosest = function getClosest(cd, distfn, pointData) { - // do we already have a point number? (array mode only) - if(pointData.index !== false) { - if(pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } - else pointData.index = false; - } - else { - // apply the distance function to each data point - // this is the longest loop... if this bogs down, we may need - // to create pre-sorted data (by x or y), not sure how to - // do this for 'closest' - for(var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if(newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; } } - return pointData; -}; -/* - * pseudo-distance function for hover effects on areas: inside the region - * distance is finite (`passVal`), outside it's Infinity. - * - * @param {number} v0: signed difference between the current position and the left edge - * @param {number} v1: signed difference between the current position and the right edge - * @param {number} passVal: the value to return on success - */ -_$helpers_450.inbox = function inbox(v0, v1, passVal) { - return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; -}; + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_196(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; -_$helpers_450.quadrature = function quadrature(dx, dy) { - return function(di) { - var x = dx(di), - y = dy(di); - return Math.sqrt(x * x + y * y); - }; -}; + var anchor = _$lib_601.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor + } + }, 'anchor'); -/** Fill event data point object for hover and selection. - * Invokes _module.eventData if present. - * - * N.B. note that point 'index' corresponds to input data array index - * whereas 'number' is its post-transform version. - * - * If the hovered/selected pt corresponds to an multiple input points - * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' - * are include in the event data. - * - * @param {object} pt - * @param {object} trace - * @param {object} cd - * @return {object} - */ -_$helpers_450.makeEventData = function makeEventData(pt, trace, cd) { - // hover uses 'index', select uses 'pointNumber' - var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; + if(anchor === 'free') coerce('position', dfltPosition); - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber: pointNumber - }; + _$lib_601.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide + } + }, 'side'); - if(trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_601.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); + } - if(pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_601.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); } - if(trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if('xVal' in pt) out.x = pt.xVal; - else if('x' in pt) out.x = pt.x; + coerce('layer'); - if('yVal' in pt) out.y = pt.yVal; - else if('y' in pt) out.y = pt.y; + return containerOut; +}; - if(pt.xa) out.xaxis = pt.xa; - if(pt.ya) out.yaxis = pt.ya; - if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - _$helpers_450.appendArrayPointValue(out, trace, pointNumber); - return out; -}; +'use strict'; -/** Appends values inside array attributes corresponding to given point number - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {number|Array(number)} pointNumber : point number. May be a length-2 array - * [row, col] to dig into 2D arrays - */ -_$helpers_450.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$autoType_648 = require('./axis_autotype'); */; +var name2id = _$axis_ids_650.name2id; - if(!arrayAttrs) { - return; +/* + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored + */ +var _$handleTypeDefaults_670 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); - - if(pointData[key] === undefined) { - var val = _$lib_539.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); - if(pointVal !== undefined) pointData[key] = pointVal; + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; } } }; -/** - * Appends values inside array attributes corresponding to given point number array - * For use when pointData references a plot entity that arose (or potentially arose) - * from multiple points in the input data - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. - * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays - */ -_$helpers_450.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; - if(!arrayAttrs) { + var id = ax._id; + var axLetter = id.charAt(0); + + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; + + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; + + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; return; } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; - if(pointData[key] === undefined) { - var val = _$lib_539.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; - for(var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_731.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; + + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); + + if(trace[calAttr] !== calendar) calendar = undefined; + } + + ax.type = _$autoType_648(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_648(dim.values, calendar); + break; } - pointData[key] = keyVal; } } -}; + else { + ax.type = _$autoType_648(d0[axLetter] || [d0[axLetter + '0']], calendar); + } +} -var pointKeyMap = { - ids: 'id', - locations: 'location', - labels: 'label', - values: 'value', - 'marker.colors': 'color' -}; +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; -function getPointKey(astr) { - return pointKeyMap[astr] || astr; -} + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } -function getPointData(val, pointNumber) { - if(Array.isArray(pointNumber)) { - if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } } - } else { - return val[pointNumber]; } } +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} + +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_731.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_731.traceIs(trace._fullInput || {}, 'candlestick'); + + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -33324,1518 +37595,1241 @@ function getPointData(val, pointNumber) { 'use strict'; -// works with our CSS cursor classes (see css/_cursor.scss) -// to apply cursors to d3 single-element selections. -// omit cursor to revert to the default. -var _$setCursor_558 = function setCursor(el3, csr) { - (el3.attr('class') || '').split(' ').forEach(function(cls) { - if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); - }); +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$layout_attributes_700 = require('../layout_attributes'); */; - if(csr) el3.classed('cursor-' + csr, true); -}; +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_670 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_649 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_653 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_662 = require('./position_defaults'); */; +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 _$supplyLayoutDefaults_660 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -'use strict'; + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -/* removed: var _$setCursor_558 = require('./setcursor'); */; + if(!_$registry_731.traceIs(trace, 'cartesian') && !_$registry_731.traceIs(trace, 'gl2d')) { + continue; + } -var STASHATTR = 'data-savedcursor'; -var NO_CURSOR = '!!'; + var xaName = _$axis_ids_650.id2name(trace.xaxis); + var yaName = _$axis_ids_650.id2name(trace.yaxis); -/* - * works with our CSS cursor classes (see css/_cursor.scss) - * to override a previous cursor set on d3 single-element selections, - * by moving the name of the original cursor to the data-savedcursor attr. - * omit cursor to revert to the previously set value. - */ -var _$overrideCursor_550 = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if(csr) { - if(!savedCursor) { - var classes = (el3.attr('class') || '').split(' '); - for(var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if(cls.indexOf('cursor-') === 0) { - el3.attr(STASHATTR, cls.substr(7)) - .classed(cls, false); - } - } - if(!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_731.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } + + // 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) xaCheater[xaName] = 1; + } + + // check for default formatting tweaks + if(_$registry_731.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } + + if(_$registry_731.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_601.simpleMap(xIds, _$axis_ids_650.id2name); + var yNames = _$lib_601.simpleMap(yIds, _$axis_ids_650.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 plot_bgcolor = _$color_473.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_700, 'plot_bgcolor'); + } + + var bgColor = _$color_473.combine(plot_bgcolor, layoutOut.paper_bgcolor); + + var axName, axLetter, axLayoutIn, axLayoutOut; + + function coerce(attr, dflt) { + return _$lib_601.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_659, attr, dflt); + } + + function coerce2(attr, dflt) { + return _$lib_601.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_659, attr, dflt); + } + + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } + + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('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(_$axis_ids_650.name2id(axName2)); } } - _$setCursor_558(el3, csr); + + return out; } - else if(savedCursor) { - el3.attr(STASHATTR, null); - if(savedCursor === NO_CURSOR) _$setCursor_558(el3); - else _$setCursor_558(el3, savedCursor); + // first pass creates the containers, determines types, and handles most of the settings + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + + if(!_$lib_601.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; + + _$handleTypeDefaults_670(axLayoutIn, axLayoutOut, coerce, fullData, axName); + + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); + + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; + + _$handleAxisDefaults_649(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); + + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + 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; + } + + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; + + _$handlePositionDefaults_662(axLayoutIn, axLayoutOut, coerce, positioningOptions); + + axLayoutOut._input = axLayoutIn; } -}; -var _$hover_451 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_731.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_731.getComponentMethod('rangeselector', 'handleDefaults'); -'use strict'; + for(i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; + rangeSliderDefaults(layoutIn, layoutOut, axName); -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$Events_527 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_550 = require('../../lib/override_cursor'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_668 = require('../../registry'); */; + if(axLayoutOut.type === 'date') { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); + } -/* removed: var _$helpers_450 = require('./helpers'); */; -/* removed: var _$constants_448 = require('./constants'); */; + coerce('fixedrange'); + } -// hover labels for multiple horizontal bars get tilted by some angle, -// then need to be offset differently if they overlap -var YANGLE = _$constants_448.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; + for(i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; -// expansion of projected height -var YFACTOR = 1 / Math.sin(YA_RADIANS); + var anchoredAxis = layoutOut[_$axis_ids_650.id2name(axLayoutOut.anchor)]; -// to make the appropriate post-rotation x offset, -// you need both x and y offsets -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); -// size and display constants for hover text -var HOVERARROWSIZE = _$constants_448.HOVERARROWSIZE; -var HOVERTEXTPAD = _$constants_448.HOVERTEXTPAD; + coerce('fixedrange', fixedRangeDflt); + } -// fx.hover: highlight data on hover -// evt can be a mousemove event, or an object with data about what points -// to hover on -// {xpx,ypx[,hovermode]} - pixel locations from top left -// (with optional overriding hovermode) -// {xval,yval[,hovermode]} - data values -// [{curveNumber,(pointNumber|xval and/or yval)}] - -// array of specific points to highlight -// pointNumber is a single integer if gd.data[curveNumber] is 1D, -// or a two-element array if it's 2D -// xval and yval are data values, -// 1D data may specify either or both, -// 2D data must specify both -// subplot is an id string (default "xy") -// makes use of gl.hovermode, which can be: -// x (find the points with the closest x values, ie a column), -// closest (find the single closest point) -// internally there are two more that occasionally get used: -// y (pick out a row - only used for multiple horizontal bar charts) -// array (used when the user specifies an explicit -// array of points to hover on) -// -// We wrap the hovers in a timer, to limit their frequency. -// The actual rendering is done by private function _hover. -_$hover_451.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_539.getGraphDiv(gd); + // Finally, handle scale constraints. 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). - _$lib_539.throttle( - gd._fullLayout._uid + _$constants_448.HOVERID, - _$constants_448.HOVERMINTIME, - function() { _hover(gd, evt, subplot, noHoverEvent); } - ); + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); + + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + + _$handleConstraintDefaults_653(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); + } }; -/* - * Draw a single hover item in a pre-existing svg container somewhere - * hoverItem should have keys: - * - x and y (or x0, x1, y0, and y1): - * the pixel position to mark, relative to opts.container - * - xLabel, yLabel, zLabel, text, and name: - * info to go in the label - * - color: - * the background color for the label. - * - idealAlign (optional): - * 'left' or 'right' for which side of the x/y box to try to put this on first - * - borderColor (optional): - * color for the border, defaults to strongest contrast with color - * - fontFamily (optional): - * string, the font for this label, defaults to constants.HOVERFONT - * - fontSize (optional): - * the label font size, defaults to constants.HOVERFONTSIZE - * - fontColor (optional): - * defaults to borderColor - * opts should have keys: - * - bgColor: - * the background color this is against, used if the trace is - * non-opaque, and for the name, which goes outside the box - * - container: - * a or element to add the hover label to - * - outerContainer: - * normally a parent of `container`, sets the bounding box to use to - * constrain the hover label and determine whether to show it on the left or right - */ -_$hover_451.loneHover = function loneHover(hoverItem, opts) { - var pointData = { - color: hoverItem.color || _$color_411.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, +'use strict'; - // filler to make createHoverText happy - trace: { - index: 0, - hoverinfo: '' - }, - xa: {_offset: 0}, - ya: {_offset: 0}, - index: 0 - }; +/* removed: var _$d3_130 = require('d3'); */; - var container3 = _$d3_127.select(opts.container), - outerContainer3 = opts.outerContainer ? - _$d3_127.select(opts.outerContainer) : container3; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$axes_647 = require('./axes'); */; +var axisRegex = _$constants_652.attrRegex; - var fullOpts = { - hovermode: 'closest', - rotateLabels: false, - bgColor: opts.bgColor || _$color_411.background, - container: container3, - outerContainer: outerContainer3 - }; +var _$transitionAxes_669 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var axes = []; + + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; + + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; + + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; - var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); - alignHoverText(hoverLabel, fullOpts.rotateLabels); + update.axisName = axisName; + update.length = axis._length; - return hoverLabel.node(); -}; + axes.push(axisLetter); -// The actual implementation is here: -function _hover(gd, evt, subplot, noHoverEvent) { - if(!subplot) subplot = 'xy'; + updates[axisLetter] = update; + } + } - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; + return updates; + } - var fullLayout = gd._fullLayout; - var plots = fullLayout._plots || []; - var plotinfo = plots[subplot]; - var hasCartesian = fullLayout._has('cartesian'); + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - subplots = subplots.concat(overlayedSubplots); - } + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; - var len = subplots.length; - var xaArray = new Array(len); - var yaArray = new Array(len); - var supportsCompare = false; + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; - for(var i = 0; i < len; i++) { - var spId = subplots[i]; + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); - // 'cartesian' case - var plotObj = plots[spId]; - if(plotObj) { - supportsCompare = true; + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; + } - // TODO make sure that fullLayout_plots axis refs - // get updated properly so that we don't have - // to use Axes.getFromId in general. + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; - xaArray[i] = _$axes_584.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_584.getFromId(gd, plotObj.yaxis._id); - continue; + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } } - // other subplot types - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; + return affectedSubplots; } - var hovermode = evt.hovermode || fullLayout.hovermode; + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - if(hovermode && !supportsCompare) hovermode = 'closest'; + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); - if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || - gd.querySelector('.zoombox') || gd._dragging) { - return _$dragelement_433.unhoverRaw(gd, evt); - } + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; + } + } - var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; - var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; + redrawObjs(fullLayout.annotations || [], _$registry_731.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_731.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_731.getComponentMethod('images', 'draw'), true); + } - // hoverData: the set of candidate points we've found to highlight - var hoverData = [], + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; + } - // searchData: the data to search in. Mostly this is just a copy of - // gd.calcdata, filtered to the subplot and overlays we're on - // but if a point array is supplied it will be a mapping - // of indicated curves - searchData = [], + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; - // [x|y]valArray: the axis values of the hover event - // mapped onto each of the currently selected overlaid subplots - xvalArray, - yvalArray, + activeAxIds = [xa._id, ya._id]; - // used in loops - itemnum, - curvenum, - cd, - trace, - subplotId, - subploti, - mode, - xval, - yval, - pointData, - closedataPreviousLength, + for(i = 0; i < activeAxIds.length; i++) { + _$axes_647.doTicks(gd, activeAxIds[i], true); + } - // spikePoints: the set of candidate points we've found to draw spikes to - spikePoints = { - hLinePoint: null, - vLinePoint: null - }; + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - // Figure out what we're hovering on: - // mouse location or user-supplied data + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } - if(Array.isArray(evt)) { - // user specified an array of points to highlight - hovermode = 'array'; - for(itemnum = 0; itemnum < evt.length; itemnum++) { - cd = gd.calcdata[evt[itemnum].curveNumber||0]; - if(cd[0].trace.hoverinfo !== 'skip') { - searchData.push(cd); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; } } + + redrawObjs(fullLayout.annotations || [], _$registry_731.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_731.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_731.getComponentMethod('images', 'draw'), true); } - else { - for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { - cd = gd.calcdata[curvenum]; - trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_450.getSubplot(trace)) !== -1) { - searchData.push(cd); - } - } - // [x|y]px: the pixels (from top left) of the mouse location - // on the currently selected plot area - // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation - var hasUserCalledHover = !evt.target, - xpx, ypx; + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - if(hasUserCalledHover) { - if('xpx' in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - evt.pointerX = xpx + xaArray[0]._offset; + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_498.setTranslate, 0, 0) + .call(_$drawing_498.setScale, 1, 1); - if('ypx' in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - evt.pointerY = ypx + yaArray[0]._offset; - } - else { - // fire the beforehover event and quit if it returns false - // note that we're only calling this on real mouse events, so - // manual calls to fx.hover will always run. - if(_$Events_527.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } + subplot.plot + .call(_$drawing_498.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_498.setScale, 1, 1); - var dbb = evt.target.getBoundingClientRect(); + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; + // 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_498.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_498.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_498.hideOutsideRangePoints, subplot); + } - // in case hover was called from mouseout into hovertext, - // it's possible you're not actually over the plot anymore - if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { - return _$dragelement_433.unhoverRaw(gd, evt); - } - evt.pointerX = evt.offsetX; - evt.pointerY = evt.offsetY; - } + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - if('xval' in evt) xvalArray = _$helpers_450.flat(subplots, evt.xval); - else xvalArray = _$helpers_450.p2c(xaArray, xpx); + var viewBox = []; - if('yval' in evt) yvalArray = _$helpers_450.flat(subplots, evt.yval); - else yvalArray = _$helpers_450.p2c(yaArray, ypx); + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - if(!_$fastIsnumeric_139(xvalArray[0]) || !_$fastIsnumeric_139(yvalArray[0])) { - _$lib_539.warn('Fx.hover failed', evt, gd); - return _$dragelement_433.unhoverRaw(gd, evt); - } - } + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - // the pixel distance to beat as a matching point - // in 'x' or 'y' mode this resets for each trace - var distance = Infinity; + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; + } - // find the closest point in each trace - // this is minimum dx and/or dy, depending on mode - // and the pixel position for the label (labelXpx, labelYpx) - for(curvenum = 0; curvenum < searchData.length; curvenum++) { - cd = searchData[curvenum]; + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // filter out invisible or broken data - if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - trace = cd[0].trace; + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; + } - // Explicitly bail out for these two. I don't know how to otherwise prevent - // the rest of this function from running and failing - if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - subplotId = _$helpers_450.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - // within one trace mode can sometimes be overridden - mode = hovermode; + var editX = !!xUpdate; + var editY = !!yUpdate; - // container for new point, also used to pass info into module.hoverPoints - pointData = { - // trace properties - cd: cd, - trace: trace, - xa: xaArray[subploti], - ya: yaArray[subploti], + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - // max distances for hover and spikes - for points that want to show but do not - // want to override other points, set distance/spikeDistance equal to max*Distance - // and it will not get filtered out but it will be guaranteed to have a greater - // distance than any point that calculated a real distance. - maxHoverDistance: hoverdistance, - maxSpikeDistance: spikedistance, + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - // point properties - override all of these - index: false, // point index in trace - only used by plotly.js hoverdata consumers - distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - // distance/pseudo-distance for spikes. This distance should always be calculated - // as if in "closest" mode, and should only be set if this point should - // generate a spike. - spikeDistance: Infinity, + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - // in some cases the spikes have different positioning from the hover label - // they don't need x0/x1, just one position - xSpike: undefined, - ySpike: undefined, + subplot.clipRect + .call(_$drawing_498.setTranslate, clipDx, clipDy) + .call(_$drawing_498.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - // where and how to display the hover label - color: _$color_411.defaultLine, // trace color - name: trace.name, - x0: undefined, - x1: undefined, - y0: undefined, - y1: undefined, - xLabelVal: undefined, - yLabelVal: undefined, - zLabelVal: undefined, - text: undefined - }; + subplot.plot + .call(_$drawing_498.setTranslate, plotDx, plotDy) + .call(_$drawing_498.setScale, xScaleFactor, yScaleFactor) - // add ref to subplot object (non-cartesian case) - if(fullLayout[subplotId]) { - pointData.subplot = fullLayout[subplotId]._subplot; - } + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_498.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - closedataPreviousLength = hoverData.length; + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_498.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + } - // for a highlighting array, figure out what - // we're searching for with this element - if(mode === 'array') { - var selection = evt[curvenum]; - if('pointNumber' in selection) { - pointData.index = selection.pointNumber; - mode = 'closest'; - } - else { - mode = ''; - if('xval' in selection) { - xval = selection.xval; - mode = 'x'; - } - if('yval' in selection) { - yval = selection.yval; - mode = mode ? 'closest' : 'y'; - } - } - } - else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; - } + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } - // Now if there is range to look in, find the points to hover. - if(hoverdistance !== 0) { - if(trace._module && trace._module.hoverPoints) { - var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); - if(newPoints) { - var newPoint; - for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { - newPoint = newPoints[newPointNum]; - if(_$fastIsnumeric_139(newPoint.x0) && _$fastIsnumeric_139(newPoint.y0)) { - hoverData.push(cleanPoint(newPoint, hovermode)); - } - } - } - } - else { - _$lib_539.log('Unrecognized trace type in hover:', trace); - } - } + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; - // in closest mode, remove any existing (farther) points - // and don't look any farther than this latest point (or points, some - // traces like box & violin make multiple hover labels at once) - if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; + axi.range = to.slice(); } - // Now if there is range to look in, find the points to draw the spikelines - // Do it only if there is no hoverData - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length === 0) { - pointData.distance = spikedistance; - pointData.index = false; - var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); - if(closestPoints) { - closestPoints = closestPoints.filter(function(point) { - // some hover points, like scatter fills, do not allow spikes, - // so will generate a hover point but without a valid spikeDistance - return point.spikeDistance <= spikedistance; - }); - } - if(closestPoints && closestPoints.length) { - var tmpPoint; - var closestVPoints = closestPoints.filter(function(point) { - return point.xa.showspikes; - }); - if(closestVPoints.length) { - var closestVPt = closestVPoints[0]; - if(_$fastIsnumeric_139(closestVPt.x0) && _$fastIsnumeric_139(closestVPt.y0)) { - tmpPoint = fillSpikePoint(closestVPt); - if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.vLinePoint = tmpPoint; - } - } - } + // Signal that this transition has completed: + onComplete && onComplete(); - var closestHPoints = closestPoints.filter(function(point) { - return point.ya.showspikes; - }); - if(closestHPoints.length) { - var closestHPt = closestHPoints[0]; - if(_$fastIsnumeric_139(closestHPt.x0) && _$fastIsnumeric_139(closestHPt.y0)) { - tmpPoint = fillSpikePoint(closestHPt); - if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } + return _$registry_731.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); } - } + }); } - function selectClosestPoint(pointsData, spikedistance) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for(var i = 0; i < pointsData.length; i++) { - thisSpikeDistance = pointsData[i].spikeDistance; - if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { - resultPoint = pointsData[i]; - minDistance = thisSpikeDistance; - } + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; + + axi.range = axi._r.slice(); } - return resultPoint; - } - function fillSpikePoint(point) { - if(!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; + return _$registry_731.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); } - var spikelineOpts = { - fullLayout: fullLayout, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - event: evt - }; - var oldspikepoints = gd._spikepoints, - newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; + var t1, t2, raf; + var easeFn = _$d3_130.ease(transitionOpts.easing); - // Now if it is not restricted by spikedistance option, set the points to draw the spikelines - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); - } - } + function doFrame() { + t2 = Date.now(); - // if hoverData is empty check for the spikes to draw and quit if there are none - if(hoverData.length === 0) { - var result = _$dragelement_433.unhoverRaw(gd, evt); - if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); - } + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); + + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); } - return result; - } - if(hasCartesian) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); } } - hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); - - // lastly, emit custom hover/unhover events - var oldhoverdata = gd._hoverdata, - newhoverdata = []; - - // pull out just the data that's useful to - // other people and send it to the event - for(itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - newhoverdata.push(_$helpers_450.makeEventData(pt, pt.trace, pt.cd)); - } + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - gd._hoverdata = newhoverdata; + return Promise.resolve(); +}; - // if there's more than one horz bar trace, - // rotate the labels so they don't overlap - var rotateLabels = hovermode === 'y' && searchData.length > 1; +var _$get_data_683 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 bgColor = _$color_411.combine( - fullLayout.plot_bgcolor || _$color_411.background, - fullLayout.paper_bgcolor - ); +'use strict'; - var labelOpts = { - hovermode: hovermode, - rotateLabels: rotateLabels, - bgColor: bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }; +/* removed: var _$registry_731 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_652.SUBPLOT_PATTERN; - var hoverLabels = createHoverText(hoverData, labelOpts, gd); +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_683.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_731.subplotsRegistry[type]; + if(!basePlotModule) return []; - hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); + var attr = basePlotModule.attr; + var subplotCalcData = []; - alignHoverText(hoverLabels, rotateLabels); + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; - // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true - // we should improve the "fx" API so other plots can use it without these hack. - if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_668.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_550(_$d3_127.select(evt.target), hasClickToShow ? 'pointer' : ''); + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); } - // don't emit events if called manually - if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; + return subplotCalcData; +}; +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_683.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_731.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; - if(oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; - gd.emit('plotly_hover', { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); -} + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } + } -function createHoverText(hoverData, opts, gd) { - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; + return [moduleCalcData, remainingCalcData]; +}; - // opts.fontFamily/Size are used for the common label - // and as defaults for each hover label, though the individual labels - // can override this. - var fontFamily = opts.fontFamily || _$constants_448.HOVERFONT; - var fontSize = opts.fontSize || _$constants_448.HOVERFONTSIZE; +/** + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_683.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_731.subplotsRegistry[type]) return []; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; - var t0 = c0[commonAttr]; - var t00 = (String(t0) || '').split(' ')[0]; - var outerContainerBB = outerContainer.node().getBoundingClientRect(); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; + var attr = _$registry_731.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; - // show the common label, if any, on the axis - // never show a common label in array mode, - // even if sometimes there could be one - var showCommonLabel = ( - (t0 !== undefined) && - (c0.distance <= opts.hoverdistance) && - (hovermode === 'x' || hovermode === 'y') - ); + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } - // all hover traces hoverinfo must contain the hovermode - // to have common labels - if(showCommonLabel) { - var i, traceHoverinfo; - var allHaveZ = true; - for(i = 0; i < hoverData.length; i++) { - if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + for(var i = 0; i < data.length; i++) { + trace = data[i]; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); - if(parts.indexOf('all') === -1 && - parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; + if(type === 'gl2d' && _$registry_731.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); } } - - // xyz labels put all info in their main label, so have no need of a common label - if(allHaveZ) showCommonLabel = false; + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } } - var commonLabel = container.selectAll('g.axistext') - .data(showCommonLabel ? [0] : []); - commonLabel.enter().append('g') - .classed('axistext', true); - commonLabel.exit().remove(); + return subplotData; +}; - commonLabel.each(function() { - var label = _$d3_127.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); +var _$cartesian_658 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - lpath.enter().append('path') - .style({'stroke-width': '1px'}); - lpath.style({ - fill: commonLabelOpts.bgcolor || _$color_411.defaultLine, - stroke: commonLabelOpts.bordercolor || _$color_411.background, - }); +'use strict'; - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../plots'); */; +var getModuleCalcData = _$get_data_683.getModuleCalcData; - ltext.text(t0) - .call(_$drawing_436.font, - commonLabelOpts.font.family || fontFamily, - commonLabelOpts.font.size || fontSize, - commonLabelOpts.font.color || _$color_411.background - ) - .call(_$svg_text_utils_562.positionText, 0, 0) - .call(_$svg_text_utils_562.convertToTspans, gd); +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; +/* removed: var _$constants_652 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; - label.attr('transform', ''); +var ensureSingle = _$lib_601.ensureSingle; - var tbb = ltext.node().getBoundingClientRect(); - if(hovermode === 'x') { - ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_562.positionText, 0, (xa.side === 'top' ? - (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : - (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_601.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} - var topsign = xa.side === 'top' ? '-' : ''; - lpath.attr('d', 'M0,0' + - 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + - 'H' + (HOVERTEXTPAD + tbb.width / 2) + - 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + - 'H-' + (HOVERTEXTPAD + tbb.width / 2) + - 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); +_$cartesian_658.name = 'cartesian'; - label.attr('transform', 'translate(' + - (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + - (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); - } - else { - ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_562.positionText, - (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), - outerTop - tbb.top - tbb.height / 2); +_$cartesian_658.attr = ['xaxis', 'yaxis']; - var leftsign = ya.side === 'right' ? '' : '-'; - lpath.attr('d', 'M0,0' + - 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + - 'V' + (HOVERTEXTPAD + tbb.height / 2) + - 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + - 'V-' + (HOVERTEXTPAD + tbb.height / 2) + - 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); +_$cartesian_658.idRoot = ['x', 'y']; - label.attr('transform', 'translate(' + - (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + - (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); - } - // remove the "close but not quite" points - // because of error bars, only take up to a space - hoverData = hoverData.filter(function(d) { - return (d.zLabelVal !== undefined) || - (d[commonAttr] || '').split(' ')[0] === t00; - }); - }); +_$cartesian_658.idRegex = _$constants_652.idRegex; - // show all the individual labels +_$cartesian_658.attrRegex = _$constants_652.attrRegex; - // first create the objects - var hoverLabels = container.selectAll('g.hovertext') - .data(hoverData, function(d) { - return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); - }); - hoverLabels.enter().append('g') - .classed('hovertext', true) - .each(function() { - var g = _$d3_127.select(this); - // trace name label (rect and text.name) - g.append('rect') - .call(_$color_411.fill, _$color_411.addOpacity(bgColor, 0.8)); - g.append('text').classed('name', true); - // trace data label (path and text.nums) - g.append('path') - .style('stroke-width', '1px'); - g.append('text').classed('nums', true) - .call(_$drawing_436.font, fontFamily, fontSize); - }); - hoverLabels.exit().remove(); +_$cartesian_658.attributes = _$attributes_645; - // then put the text in, position the pointer to the data, - // and figure out sizes - hoverLabels.each(function(d) { - var g = _$d3_127.select(this).attr('transform', ''), - name = '', - text = ''; +_$cartesian_658.layoutAttributes = _$layout_attributes_659; - // combine possible non-opaque trace color with bgColor - var baseColor = _$color_411.opacity(d.color) ? d.color : _$color_411.defaultLine; - var traceColor = _$color_411.combine(baseColor, bgColor); +_$cartesian_658.supplyLayoutDefaults = _$supplyLayoutDefaults_660; - // find a contrasting color for border and text - var contrastColor = d.borderColor || _$color_411.contrast(traceColor); +_$cartesian_658.transitionAxes = _$transitionAxes_669; - // to get custom 'name' labels pass cleanPoint - if(d.nameOverride !== undefined) d.name = d.nameOverride; +_$cartesian_658.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - if(d.name) { - // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_562.plainText(d.name || ''); + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; + } - var nameLength = Math.round(d.nameLength); + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_650.id2name(xi)] || {}).anchor; + if(!_$constants_652.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - if(nameLength > -1 && name.length > nameLength) { - if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; - else name = name.substr(0, nameLength); + if(!allY[yi]) { + allY[yi] = 1; + _$lib_601.pushUnique(yList, yi); } } + } - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_650.id2name(yi)] || {}).anchor; + if(!_$constants_652.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - if(d.zLabel !== undefined) { - if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; - if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; - text += (text ? 'z: ' : '') + d.zLabel; - } - else if(showCommonLabel && d[hovermode + 'Label'] === t0) { - text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; - } - else if(d.xLabel === undefined) { - if(d.yLabel !== undefined) text = d.yLabel; + if(!allX[xi]) { + allX[xi] = 1; + _$lib_601.pushUnique(xList, xi); + } } - else if(d.yLabel === undefined) text = d.xLabel; - else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; + } - if(d.text && !Array.isArray(d.text)) { - text += (text ? '
' : '') + d.text; + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_652.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } } + xi = xi ? _$axis_ids_650.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_650.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; - // if 'text' is empty at this point, - // put 'name' in main label and don't show secondary label - if(text === '') { - // if 'name' is also empty, remove entire label - if(name === '') g.remove(); - text = name; +_$cartesian_658.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; + + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; + + for(i = 0; i < calcdata.length; i++) { + traces.push(i); } + } - // main label - var tx = g.select('text.nums') - .call(_$drawing_436.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - d.fontColor || contrastColor) - .text(text) - .attr('data-notex', 1) - .call(_$svg_text_utils_562.positionText, 0, 0) - .call(_$svg_text_utils_562.convertToTspans, gd); + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; - var tx2 = g.select('text.name'), - tx2width = 0; + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; - // secondary label for non-empty 'name' - if(name && name !== text) { - tx2.call(_$drawing_436.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - traceColor) - .text(name) - .attr('data-notex', 1) - .call(_$svg_text_utils_562.positionText, 0, 0) - .call(_$svg_text_utils_562.convertToTspans, gd); - tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; - } - else { - tx2.remove(); - g.select('rect').remove(); - } + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; - g.select('path') - .style({ - fill: traceColor, - stroke: contrastColor - }); - var tbb = tx.node().getBoundingClientRect(), - htx = d.xa._offset + (d.x0 + d.x1) / 2, - hty = d.ya._offset + (d.y0 + d.y1) / 2, - dx = Math.abs(d.x1 - d.x0), - dy = Math.abs(d.y1 - d.y0), - txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, - anchorStartOK, - anchorEndOK; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - d.ty0 = outerTop - tbb.top; - d.bx = tbb.width + 2 * HOVERTEXTPAD; - d.by = tbb.height + 2 * HOVERTEXTPAD; - d.anchor = 'start'; - d.txwidth = tbb.width; - d.tx2width = tx2width; - d.offset = 0; + cdSubplot.push(cd); + } - if(rotateLabels) { - d.pos = htx; - anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; - anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - hty += dy / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } - else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - htx += dx / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } } - tx.attr('text-anchor', d.anchor); - if(tx2width) tx2.attr('text-anchor', d.anchor); - g.attr('transform', 'translate(' + htx + ',' + hty + ')' + - (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); - }); + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + } +}; - return hoverLabels; -} +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; -// Make groups of touching points, and within each group -// move each point so that no labels overlap, but the average -// label position is the same as it was before moving. Indicentally, -// this is equivalent to saying all the labels are on equal linear -// springs about their initial position. Initially, each point is -// its own group, but as we find overlaps we will clump the points. -// -// Also, there are hard constraints at the edges of the graphs, -// that push all groups to the middle so they are visible. I don't -// know what happens if the group spans all the way from one edge to -// the other, though it hardly matters - there's just too much -// information then. -function hoverAvoidOverlaps(hoverData, ax, fullLayout) { - var nummoves = 0, + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); + } - // make groups of touching points - pointgroups = hoverData - .map(function(d, i) { - var axis = d[ax]; - return [{ - i: i, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, - pmin: 0, - pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) - }]; - }) - .sort(function(a, b) { return a[0].posref - b[0].posref; }), - donepositioning, - topOverlap, - bottomOverlap, - i, j, - pti, - sumdp; + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; + + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; - function constrainGroup(grp) { - var minPt = grp[0], - maxPt = grp[grp.length - 1]; + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; - // overlap with the top - positive vals are overlaps - topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + } +} - // overlap with the bottom - positive vals are overlaps - bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; +_$cartesian_658.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; - // check for min overlap first, so that we always - // see the largest labels - // allow for .01px overlap, so we don't get an - // infinite loop from rounding errors - if(topOverlap > 0.01) { - for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; - donepositioning = false; - } - if(bottomOverlap < 0.01) return; - if(topOverlap < -0.01) { - // make sure we're not pushing back and forth - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - donepositioning = false; + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; + + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); } - if(!donepositioning) return; + } - // no room to fix positioning, delete off-screen points + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } - // first see how many points we need to delete - var deleteCount = 0; - for(i = 0; i < grp.length; i++) { - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; - } + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } - // start by deleting points whose data is off screen - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } } + + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); } - for(i = 0; i < grp.length; i++) { - if(deleteCount <= 0) break; - pti = grp[i]; + } - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - // shift the whole group minus into this new space - bottomOverlap = pti.size * 2; - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); } } - // then delete points that go off the bottom - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; + } + + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); } } } - // loop through groups, combining them if they overlap, - // until nothing moves - while(!donepositioning && nummoves <= hoverData.length) { - // to avoid infinite loops, don't move more times - // than there are traces - nummoves++; + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - // assume nothing will move in this iteration, - // reverse this if it does - donepositioning = true; - i = 0; - while(i < pointgroups.length - 1) { - // the higher (g0) and lower (g1) point group - var g0 = pointgroups[i], - g1 = pointgroups[i + 1], + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } + } +}; - // the lowest point in the higher group (p0) - // the highest point in the lower group (p1) - p0 = g0[g0.length - 1], - p1 = g1[0]; - topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; +_$cartesian_658.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); - // Only group points that lie on the same axes - if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { - // push the new point(s) added to this group out of the way - for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_601.identity); - // add them to the group - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); - // adjust for minimum average movement - sumdp = 0; - for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; - } - else i++; - } + subplotLayers.order(); - // check if we're going off the plot on either side and fix - pointgroups.forEach(constrainGroup); - } + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - // now put these offsets into hoverData - for(i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for(j = grp.length - 1; j >= 0; j--) { - var pt = grp[j], - hoverPt = hoverData[pt.i]; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; - } - } -} + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; -function alignHoverText(hoverLabels, rotateLabels) { - // finally set the text positioning relative to the data and draw the - // box around it - hoverLabels.each(function(d) { - var g = _$d3_127.select(this); - if(d.del) { - g.remove(); - return; - } - var horzSign = d.anchor === 'end' ? -1 : 1, - tx = g.select('text.nums'), - alignShift = {start: 1, end: -1, middle: 0}[d.anchor], - txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), - tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), - offsetX = 0, - offsetY = d.offset; - if(d.anchor === 'middle') { - txx -= d.tx2width / 2; - tx2x += d.txwidth / 2 + HOVERTEXTPAD; - } - if(rotateLabels) { - offsetY *= -YSHIFTY; - offsetX = d.offset * YSHIFTX; - } + // keep ref to plot group + plotinfo.plotgroup = _$d3_130.select(this); - g.select('path').attr('d', d.anchor === 'middle' ? - // middle aligned: rect centered on data - ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + - 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : - // left or right aligned: side rect with arrow to data - ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + - 'v' + (d.by / 2 - HOVERARROWSIZE) + - 'h' + (horzSign * d.bx) + - 'v-' + d.by + - 'H' + (horzSign * HOVERARROWSIZE + offsetX) + - 'V' + (offsetY - HOVERARROWSIZE) + - 'Z')); + // initialize list of overlay subplots + plotinfo.overlays = []; - tx.call(_$svg_text_utils_562.positionText, - txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + makeSubplotLayer(gd, plotinfo); - if(d.tx2width) { - g.select('text.name') - .call(_$svg_text_utils_562.positionText, - tx2x + alignShift * HOVERTEXTPAD + offsetX, - offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); - g.select('rect') - .call(_$drawing_436.setRect, - tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, - offsetY - d.by / 2 - 1, - d.tx2width, d.by + 2); + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); } + + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); }); -} +}; -function cleanPoint(d, hovermode) { - var index = d.index; - var trace = d.trace || {}; - var cd0 = d.cd[0]; - var cd = d.cd[index] || {}; +_$cartesian_658.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_709.style(gd); +}; - var getVal = Array.isArray(index) ? - function(calcKey, traceKey) { - return _$lib_539.castOption(cd0, index, calcKey) || - _$lib_539.extractOption({}, trace, '', traceKey); - } : - function(calcKey, traceKey) { - return _$lib_539.extractOption(cd, trace, calcKey, traceKey); - }; +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; - function fill(key, calcKey, traceKey) { - var val = getVal(calcKey, traceKey); - if(val) d[key] = val; + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; + + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; + } } - fill('hoverinfo', 'hi', 'hoverinfo'); - fill('color', 'hbg', 'hoverlabel.bgcolor'); - fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); - fill('fontFamily', 'htf', 'hoverlabel.font.family'); - fill('fontSize', 'hts', 'hoverlabel.font.size'); - fill('fontColor', 'htc', 'hoverlabel.font.color'); - fill('nameLength', 'hnl', 'hoverlabel.namelength'); + // main subplots before overlays + subplotData = subplotData.concat(overlays); - d.posref = hovermode === 'y' ? - (d.xa._offset + (d.x0 + d.x1) / 2) : - (d.ya._offset + (d.y0 + d.y1) / 2); + return subplotData; +} - // then constrain all the positions to be on the plot - d.x0 = _$lib_539.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_539.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_539.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_539.constrain(d.y1, 0, d.ya._length); +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_652.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_652.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; - // and convert the x and y label values into formatted text - if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_584.hoverLabelText(d.xa, d.xLabelVal); - d.xVal = d.xa.c2d(d.xLabelVal); - } - if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_584.hoverLabelText(d.ya, d.yLabelVal); - d.yVal = d.ya.c2d(d.yLabelVal); - } + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); - // Traces like heatmaps generate the zLabel in their hoverPoints function - if(d.zLabelVal !== undefined && d.zLabel === undefined) { - d.zLabel = String(d.zLabelVal); - } + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); - // for box means and error bars, add the range to the label - if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_584.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; - if(d.xerrneg !== undefined) { - d.xLabel += ' +' + xeText + ' / -' + - _$axes_584.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; - } - else d.xLabel += ' ± ' + xeText; + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - // small distance penalty for error bars, so that if there are - // traces with errors and some without, the error bar label will - // hoist up to the point - if(hovermode === 'x') d.distance += 1; - } - if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_584.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; - if(d.yerrneg !== undefined) { - d.yLabel += ' +' + yeText + ' / -' + - _$axes_584.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; - } - else d.yLabel += ' ± ' + yeText; + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - if(hovermode === 'y') d.distance += 1; - } + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); - var infomode = d.hoverinfo || d.trace.hoverinfo; + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); - if(infomode !== 'all') { - infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); - if(infomode.indexOf('x') === -1) d.xLabel = undefined; - if(infomode.indexOf('y') === -1) d.yLabel = undefined; - if(infomode.indexOf('z') === -1) d.zLabel = undefined; - if(infomode.indexOf('text') === -1) d.text = undefined; - if(infomode.indexOf('name') === -1) d.name = undefined; + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); + + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - return d; -} + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. -function createSpikelines(closestPoints, opts) { - var container = opts.container; - var fullLayout = opts.fullLayout; - var evt = opts.event; - var xa, - ya; + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - var showY = !!closestPoints.hLinePoint; - var showX = !!closestPoints.vLinePoint; + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - // Remove old spikeline items - container.selectAll('.spikeline').remove(); + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - if(!(showX || showY)) return; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - var contrastColor = _$color_411.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + } - // Horizontal line (to y-axis) - if(showY) { - var hLinePoint = closestPoints.hLinePoint, - hLinePointX, - hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; + // common attributes for all subplots, overlays or not - if(ySnap === 'cursor') { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_650.idSort); + + for(var i = 0; i < _$constants_652.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_652.traceLayerClasses[i]); } - var dfltHLineColor = _$tinycolor_352.readability(hLinePoint.color, contrastColor) < 1.5 ? - _$color_411.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode, - yThickness = ya.spikethickness, - yColor = ya.spikecolor || dfltHLineColor, - yBB = ya._boundingBox, - xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, - xBase, - xEndSpike; + } - if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { - if(yMode.indexOf('toaxis') !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; - } - if(yMode.indexOf('across') !== -1) { - xBase = ya._counterSpan[0]; - xEndSpike = ya._counterSpan[1]; - } + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - // Foreground horizontal line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness, - 'stroke': yColor, - 'stroke-dasharray': _$drawing_436.dashStyle(ya.spikedash, yThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - // Background horizontal Line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } - // Y axis marker - if(yMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), - 'cy': hLinePointY, - 'r': yThickness, - 'fill': yColor - }) - .classed('spikeline', true); - } - } +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - if(showX) { - var vLinePoint = closestPoints.vLinePoint, - vLinePointX, - vLinePointY; + var overlayIdsToRemove = {}; - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; + layers.each(function(subplotId) { + var plotgroup = _$d3_130.select(this); - if(xSnap === 'cursor') { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; - } - var dfltVLineColor = _$tinycolor_352.readability(vLinePoint.color, contrastColor) < 1.5 ? - _$color_411.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode, - xThickness = xa.spikethickness, - xColor = xa.spikecolor || dfltVLineColor, - xBB = xa._boundingBox, - yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, - yBase, - yEndSpike; + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { - if(xMode.indexOf('toaxis') !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if(xMode.indexOf('across') !== -1) { - yBase = xa._counterSpan[0]; - yEndSpike = xa._counterSpan[1]; - } + overlayIdsToRemove[subplotId] = true; - // Foreground vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness, - 'stroke': xColor, - 'stroke-dasharray': _$drawing_436.dashStyle(xa.spikedash, xThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + // do not remove individual axis s here + // as other subplots may need them + }); - // Background vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } + // must remove overlaid subplot trace layers 'manually' - // X axis marker - if(xMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': vLinePointX, - 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), - 'r': xThickness, - 'fill': xColor - }) - .classed('spikeline', true); - } - } -} + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); -function hoverChanged(gd, evt, oldhoverdata) { - // don't emit any events if nothing changed - if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - for(var i = oldhoverdata.length - 1; i >= 0; i--) { - var oldPt = oldhoverdata[i], - newPt = gd._hoverdata[i]; - if(oldPt.curveNumber !== newPt.curveNumber || - String(oldPt.pointNumber) !== String(newPt.pointNumber)) { - return true; + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; + + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } } } - return false; } -function spikesChanged(gd, oldspikepoints) { - // don't relayout the plot because of new spikelines if spikelines points didn't change - if(!oldspikepoints) return true; - if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || - oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint - ) return true; - return false; +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); } +_$cartesian_658.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_130.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); + + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); + + image.attr({ + xmlns: _$xmlns_namespaces_580.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); + } + + canvases.each(canvasToImage); +}; + +_$cartesian_658.updateFx = _$graph_interact_656.updateFx; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -34844,32 +38838,29 @@ function spikesChanged(gd, oldspikepoints) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -var hover = _$hover_451.hover; +var mergeArray = _$lib_601.mergeArray; -var _$click_447 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_668.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); - } +// arrayOk attributes, merge them into calcdata array +var _$arraysToCalcdata_740 = function arraysToCalcdata(cd, trace) { + for(var i = 0; i < cd.length; i++) cd[i].i = i; - function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } + mergeArray(trace.text, cd, 'tx'); + mergeArray(trace.hovertext, cd, 'htx'); - if(gd._hoverdata && evt && evt.target) { - if(annotationsDone && annotationsDone.then) { - annotationsDone.then(emitClick); - } - else emitClick(); + var marker = trace.marker; + if(marker) { + mergeArray(marker.opacity, cd, 'mo'); + mergeArray(marker.color, cd, 'mc'); - // why do we get a double event without this??? - if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); + var markerLine = marker.line; + if(markerLine) { + mergeArray(markerLine.color, cd, 'mlc'); + mergeArray(markerLine.width, cd, 'mlw'); + } } }; @@ -34883,142 +38874,195 @@ var _$click_447 = function click(gd, evt, subplot) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; -var _$handleHoverLabelDefaults_452 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { - opts = opts || {}; +var __extendFlat_741 = _$extend_590.extendFlat; - coerce('hoverlabel.bgcolor', opts.bgcolor); - coerce('hoverlabel.bordercolor', opts.bordercolor); - coerce('hoverlabel.namelength', opts.namelength); - _$lib_539.coerceFont(coerce, 'hoverlabel.font', opts.font); -}; +var textFontAttrs = _$font_attributes_673({ + editType: 'calc', + arrayOk: true, + description: '' +}); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 __scatterMarkerAttrs_741 = _$attributes_927.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_741.line; -'use strict'; +var markerLineWidth = __extendFlat_741({}, + scatterMarkerLineAttrs.width, { dflt: 0 }); -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_445 = require('./attributes'); */; -/* removed: var _$handleHoverLabelDefaults_452 = require('./hoverlabel_defaults'); */; +var markerLine = __extendFlat_741({ + width: markerLineWidth, + editType: 'calc' +}, _$makeColorScaleAttributes_481('marker.line')); -var _$supplyDefaults_449 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_445, attr, dflt); +var marker = __extendFlat_741({ + line: markerLine, + editType: 'calc' +}, _$makeColorScaleAttributes_481('marker'), { + showscale: __scatterMarkerAttrs_741.showscale, + colorbar: _$attributes_474, + opacity: { + valType: 'number', + arrayOk: true, + dflt: 1, + min: 0, + max: 1, + role: 'style', + editType: 'style', + description: 'Sets the opacity of the bars.' } +}); - _$handleHoverLabelDefaults_452(traceIn, traceOut, coerce, layout.hoverlabel); -}; +var _$attributes_741 = { + x: _$attributes_927.x, + x0: _$attributes_927.x0, + dx: _$attributes_927.dx, + y: _$attributes_927.y, + y0: _$attributes_927.y0, + dy: _$attributes_927.dy, -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + text: _$attributes_927.text, + hovertext: _$attributes_927.hovertext, -'use strict'; + textposition: { + valType: 'enumerated', + role: 'info', + values: ['inside', 'outside', 'auto', 'none'], + dflt: 'none', + arrayOk: true, + editType: 'calc', + description: [ + 'Specifies the location of the `text`.', + '*inside* positions `text` inside, next to the bar end', + '(rotated and scaled if needed).', + '*outside* positions `text` outside, next to the bar end', + '(scaled if needed).', + '*auto* positions `text` inside or outside', + 'so that `text` size is maximized.' + ].join(' ') + }, + + textfont: __extendFlat_741({}, textFontAttrs, { + description: 'Sets the font used for `text`.' + }), -/* removed: var _$constants_448 = require('./constants'); */; + insidetextfont: __extendFlat_741({}, textFontAttrs, { + description: 'Sets the font used for `text` lying inside the bar.' + }), -var __fontAttrs_454 = _$font_attributes_611({ - editType: 'none', - description: 'Sets the default hover label font used by all traces on the graph.' -}); -__fontAttrs_454.family.dflt = _$constants_448.HOVERFONT; -__fontAttrs_454.size.dflt = _$constants_448.HOVERFONTSIZE; + outsidetextfont: __extendFlat_741({}, textFontAttrs, { + description: 'Sets the font used for `text` lying outside the bar.' + }), -var _$layout_attributes_454 = { - dragmode: { + constraintext: { valType: 'enumerated', + values: ['inside', 'outside', 'both', 'none'], role: 'info', - values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], - dflt: 'zoom', - editType: 'modebar', + dflt: 'both', + editType: 'calc', description: [ - 'Determines the mode of drag interactions.', - '*select* and *lasso* apply only to scatter traces with', - 'markers or text. *orbit* and *turntable* apply only to', - '3D scenes.' + 'Constrain the size of text inside or outside a bar to be no', + 'larger than the bar itself.' ].join(' ') }, - hovermode: { + + cliponaxis: __extendFlat_741({}, _$attributes_927.cliponaxis, { + description: [ + 'Determines whether the text nodes', + 'are clipped about the subplot axes.', + 'To show the text nodes above axis lines and tick labels,', + 'make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*.' + ].join(' ') + }), + + orientation: { valType: 'enumerated', role: 'info', - values: ['x', 'y', 'closest', false], - editType: 'modebar', - description: 'Determines the mode of hover interactions.' + values: ['v', 'h'], + editType: 'calc+clearAxisTypes', + description: [ + 'Sets the orientation of the bars.', + 'With *v* (*h*), the value of the each bar spans', + 'along the vertical (horizontal).' + ].join(' ') }, - hoverdistance: { - valType: 'integer', - min: -1, - dflt: 20, + + base: { + valType: 'any', + dflt: null, + arrayOk: true, role: 'info', - editType: 'none', + editType: 'calc', description: [ - 'Sets the default distance (in pixels) to look for data', - 'to add hover labels (-1 means no cutoff, 0 means no looking for data).', - 'This is only a real distance for hovering on point-like objects,', - 'like scatter points. For area-like objects (bars, scatter fills, etc)', - 'hovering is on inside the area and off outside, but these objects', - 'will not supersede hover on point-like objects in case of conflict.' + 'Sets where the bar base is drawn (in position axis units).', + 'In *stack* or *relative* barmode,', + 'traces that set *base* will be excluded', + 'and drawn in *overlay* mode instead.' ].join(' ') }, - spikedistance: { - valType: 'integer', - min: -1, - dflt: 20, + + offset: { + valType: 'number', + dflt: null, + arrayOk: true, role: 'info', - editType: 'none', + editType: 'calc', description: [ - 'Sets the default distance (in pixels) to look for data to draw', - 'spikelines to (-1 means no cutoff, 0 means no looking for data).', - 'As with hoverdistance, distance does not apply to area-like objects.', - 'In addition, some objects can be hovered on but will not generate', - 'spikelines, such as scatter fills.' + 'Shifts the position where the bar is drawn', + '(in position axis units).', + 'In *group* barmode,', + 'traces that set *offset* will be excluded', + 'and drawn in *overlay* mode instead.' ].join(' ') }, - hoverlabel: { - bgcolor: { - valType: 'color', - role: 'style', - editType: 'none', - description: [ - 'Sets the background color of all hover labels on graph' - ].join(' ') - }, - bordercolor: { - valType: 'color', - role: 'style', - editType: 'none', - description: [ - 'Sets the border color of all hover labels on graph.' - ].join(' ') + + width: { + valType: 'number', + dflt: null, + min: 0, + arrayOk: true, + role: 'info', + editType: 'calc', + description: [ + 'Sets the bar width (in position axis units).' + ].join(' ') + }, + + marker: marker, + + selected: { + marker: { + opacity: _$attributes_927.selected.marker.opacity, + color: _$attributes_927.selected.marker.color, + editType: 'style' }, - font: __fontAttrs_454, - namelength: { - valType: 'integer', - min: -1, - dflt: 15, - role: 'style', - editType: 'none', - description: [ - 'Sets the default length (in number of characters) of the trace name in', - 'the hover labels for all traces. -1 shows the whole name', - 'regardless of length. 0-3 shows the first 0-3 characters, and', - 'an integer >3 will show the whole name if it is less than that', - 'many characters, but if it is longer, will truncate to', - '`namelength - 3` characters and add an ellipsis.' - ].join(' ') + textfont: _$attributes_927.selected.textfont, + editType: 'style' + }, + unselected: { + marker: { + opacity: _$attributes_927.unselected.marker.opacity, + color: _$attributes_927.unselected.marker.color, + editType: 'style' }, - editType: 'none' + textfont: _$attributes_927.unselected.textfont, + editType: 'style' + }, + + r: _$attributes_927.r, + t: _$attributes_927.t, + + _deprecated: { + bardir: { + valType: 'enumerated', + role: 'info', + editType: 'calc', + values: ['v', 'h'], + description: 'Renamed to `orientation`.' + } } }; @@ -35032,60 +39076,116 @@ var _$layout_attributes_454 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_454 = require('./layout_attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$supplyLayoutDefaults_455 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_454, attr, dflt); +var _$calcSelection_929 = function calcSelection(cd, trace) { + if(_$lib_601.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_601.tagSelected(cd, trace); } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('dragmode'); - var hovermodeDflt; - if(layoutOut._has('cartesian')) { - // flag for 'horizontal' plots: - // determines the state of the mode bar 'compare' hovermode button - layoutOut._isHoriz = isHoriz(fullData); - hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; - } - else hovermodeDflt = 'closest'; +'use strict'; - var hoverMode = coerce('hovermode', hovermodeDflt); - if(hoverMode) { - coerce('hoverdistance'); - coerce('spikedistance'); - } +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_742 = _$lib_601.isArrayOrTypedArray; - // if only mapbox or geo subplots is present on graph, - // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, - // so that the correct modebar button is active - var hasMapbox = layoutOut._has('mapbox'); - var hasGeo = layoutOut._has('geo'); - var len = layoutOut._basePlotModules.length; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_740 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; - if(layoutOut.dragmode === 'zoom' && ( - ((hasMapbox || hasGeo) && len === 1) || - (hasMapbox && hasGeo && len === 2) - )) { - layoutOut.dragmode = 'pan'; +var _$calc_742 = function calc(gd, trace) { + // depending on bar direction, set position and size axes + // and data ranges + // note: this logic for choosing orientation is + // duplicated in graph_obj->setstyles + + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'), + orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), + sa, pos, size, i, scalendar; + + if(orientation === 'h') { + sa = xa; + size = xa.makeCalcdata(trace, 'x'); + pos = ya.makeCalcdata(trace, 'y'); + + // 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. + scalendar = trace.xcalendar; + } + else { + sa = ya; + size = ya.makeCalcdata(trace, 'y'); + pos = xa.makeCalcdata(trace, 'x'); + scalendar = trace.ycalendar; } -}; -function isHoriz(fullData) { - var out = true; + // create the "calculated data" to plot + var serieslen = Math.min(pos.length, size.length); + var cd = new Array(serieslen); - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + // set position and size + for(i = 0; i < serieslen; i++) { + cd[i] = { p: pos[i], s: size[i] }; - if(trace.orientation !== 'h') { - out = false; - break; + if(trace.ids) { + cd[i].id = String(trace.ids[i]); } } - return out; -} + // set base + var base = trace.base, + b; + + if(__isArrayOrTypedArray_742(base)) { + for(i = 0; i < Math.min(base.length, cd.length); i++) { + b = sa.d2c(base[i], 0, scalendar); + if(_$fastIsnumeric_196(b)) { + cd[i].b = +b; + cd[i].hasB = 1; + } + else cd[i].b = 0; + } + for(; i < cd.length; i++) { + cd[i].b = 0; + } + } + else { + b = sa.d2c(base, 0, scalendar); + var hasBase = _$fastIsnumeric_196(b); + b = hasBase ? b : 0; + for(i = 0; i < cd.length; i++) { + cd[i].b = b; + if(hasBase) cd[i].hasB = 1; + } + } + + // auto-z and autocolorscale if applicable + if(_$hasColorscale_487(trace, 'marker')) { + _$calc_480(trace, trace.marker.color, 'marker', 'c'); + } + if(_$hasColorscale_487(trace, 'marker.line')) { + _$calc_480(trace, trace.marker.line.color, 'marker.line', 'c'); + } + + _$arraysToCalcdata_740(cd, trace); + _$calcSelection_929(cd, trace); + + return cd; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -35095,18 +39195,34 @@ function isHoriz(fullData) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleHoverLabelDefaults_452 = require('./hoverlabel_defaults'); */; -/* removed: var _$layout_attributes_454 = require('./layout_attributes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; -var _$supplyLayoutGlobalDefaults_456 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { - function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_454, attr, dflt); +var _$handleStyleDefaults_753 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { + coerce('marker.color', defaultColor); + + if(_$hasColorscale_487(traceIn, 'marker')) { + _$colorScaleDefaults_483( + traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} + ); + } + + coerce('marker.line.color', _$color_473.defaultLine); + + if(_$hasColorscale_487(traceIn, 'marker.line')) { + _$colorScaleDefaults_483( + traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} + ); } - _$handleHoverLabelDefaults_452(layoutIn, layoutOut, coerce); + coerce('marker.line.width'); + coerce('marker.opacity'); + coerce('selected.marker.color'); + coerce('unselected.marker.color'); }; /** @@ -35117,74 +39233,108 @@ var _$supplyLayoutGlobalDefaults_456 = function supplyLayoutGlobalDefaults(layou * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$helpers_450 = require('./helpers'); */; -/* removed: var _$layout_attributes_454 = require('./layout_attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$fx_453 = { - moduleType: 'component', - name: 'fx', - constants: _$constants_448, - schema: { - layout: _$layout_attributes_454 - }, +var _$handleXYDefaults_951 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { + var len, + x = coerce('x'), + y = coerce('y'); - attributes: _$attributes_445, - layoutAttributes: _$layout_attributes_454, + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); - supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_456, - supplyDefaults: _$supplyDefaults_449, - supplyLayoutDefaults: _$supplyLayoutDefaults_455, + if(x) { + if(y) { + len = Math.min(x.length, y.length); + } + else { + len = x.length; + coerce('y0'); + coerce('dy'); + } + } + else { + if(!y) return 0; - calc: _$calc_446, + len = traceOut.y.length; + coerce('x0'); + coerce('dx'); + } - getDistanceFunction: _$helpers_450.getDistanceFunction, - getClosest: _$helpers_450.getClosest, - inbox: _$helpers_450.inbox, - quadrature: _$helpers_450.quadrature, - appendArrayPointValue: _$helpers_450.appendArrayPointValue, + traceOut._length = len; - castHoverOption: castHoverOption, - castHoverinfo: castHoverinfo, + return len; +}; - hover: _$hover_451.hover, - unhover: _$dragelement_433.unhover, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - loneHover: _$hover_451.loneHover, - loneUnhover: loneUnhover, - click: _$click_447 -}; +'use strict'; -function loneUnhover(containerOrSelection) { - // duck type whether the arg is a d3 selection because ie9 doesn't - // handle instanceof like modern browsers do. - var selection = _$lib_539.isD3Selection(containerOrSelection) ? - containerOrSelection : - _$d3_127.select(containerOrSelection); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$registry_731 = require('../../registry'); */; - selection.selectAll('g.hovertext').remove(); - selection.selectAll('.spikeline').remove(); -} +/* removed: var _$handleXYDefaults_951 = require('../scatter/xy_defaults'); */; +/* removed: var _$handleStyleDefaults_753 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_741 = require('./attributes'); */; -// helpers for traces that use Fx.loneHover +var _$supplyDefaults_743 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_741, attr, dflt); + } -function castHoverOption(trace, ptNumber, attr) { - return _$lib_539.castOption(trace, ptNumber, 'hoverlabel.' + attr); -} + var coerceFont = _$lib_601.coerceFont; -function castHoverinfo(trace, fullLayout, ptNumber) { - function _coerce(val) { - return _$lib_539.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + var len = _$handleXYDefaults_951(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; } - return _$lib_539.castOption(trace, ptNumber, 'hoverinfo', _coerce); -} + coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); + coerce('base'); + coerce('offset'); + coerce('width'); + + coerce('text'); + coerce('hovertext'); + + var textPosition = coerce('textposition'); + + var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', + hasInside = hasBoth || textPosition === 'inside', + hasOutside = hasBoth || textPosition === 'outside'; + + if(hasInside || hasOutside) { + var textFont = coerceFont(coerce, 'textfont', layout.font); + if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); + if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); + coerce('constraintext'); + coerce('selected.textfont.color'); + coerce('unselected.textfont.color'); + coerce('cliponaxis'); + } + + _$handleStyleDefaults_753(traceIn, traceOut, coerce, defaultColor, layout); + + // override defaultColor for error bars with defaultLine + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'x', inherit: 'y'}); + + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -35196,7 +39346,7 @@ function castHoverinfo(trace, fullLayout, ptNumber) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** Fill hover 'pointData' container with 'correct' hover text value * @@ -35211,15 +39361,15 @@ function castHoverinfo(trace, fullLayout, ptNumber) { * @param {object} trace * @param {object || array} contOut (mutated here) */ -var _$fillHoverText_870 = function fillHoverText(calcPt, trace, contOut) { +var _$fillHoverText_935 = function fillHoverText(calcPt, trace, contOut) { var fill = Array.isArray(contOut) ? function(v) { contOut.push(v); } : function(v) { contOut.text = v; }; - var htx = _$lib_539.extractOption(calcPt, trace, 'htx', 'hovertext'); + var htx = _$lib_601.extractOption(calcPt, trace, 'htx', 'hovertext'); if(isValid(htx)) return fill(htx); - var tx = _$lib_539.extractOption(calcPt, trace, 'tx', 'text'); + var tx = _$lib_601.extractOption(calcPt, trace, 'tx', 'text'); if(isValid(tx)) return fill(tx); }; @@ -35239,12 +39389,12 @@ function isValid(v) { 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; -var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_744 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var t = cd[0].t; @@ -35284,7 +39434,7 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { function _positionFn(_minPos, _maxPos) { // add a little to the pseudo-distance for wider bars, so that like scatter, // if you are over two overlapping bars, the narrower one wins. - return _$fx_453.inbox(_minPos - posVal, _maxPos - posVal, + return _$fx_515.inbox(_minPos - posVal, _maxPos - posVal, maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); } @@ -35299,7 +39449,7 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { function sizeFn(di) { // add a gradient so hovering near the end of a // bar makes it a little closer match - return _$fx_453.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, + return _$fx_515.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); } @@ -35326,8 +39476,8 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_453.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_453.getClosest(cd, distfn, pointData); + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_515.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index === false) return; @@ -35351,8 +39501,8 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { var mlc = di.mlcc || trace.marker.line.color; var mlw = di.mlw || trace.marker.line.width; - if(_$color_411.opacity(mc)) pointData.color = mc; - else if(_$color_411.opacity(mlc) && mlw) pointData.color = mlc; + if(_$color_473.opacity(mc)) pointData.color = mc; + else if(_$color_473.opacity(mlc) && mlw) pointData.color = mlc; var size = (trace.base) ? di.b + di.s : di.s; pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); @@ -35369,8 +39519,8 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { // in case of bars shifted within groups pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); - _$fillHoverText_870(di, trace, pointData); - _$registry_668.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_935(di, trace, pointData); + _$registry_731.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; }; @@ -35386,7 +39536,7 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var _$layout_attributes_683 = { +var _$layout_attributes_746 = { barmode: { valType: 'enumerated', values: ['stack', 'group', 'overlay', 'relative'], @@ -35454,16 +39604,16 @@ var _$layout_attributes_683 = { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$layout_attributes_683 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_746 = require('./layout_attributes'); */; -var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { +var _$layout_defaults_747 = function(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_683, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_746, attr, dflt); } var hasBars = false, @@ -35473,7 +39623,7 @@ var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { for(var i = 0; i < fullData.length; i++) { var trace = fullData[i]; - if(_$registry_668.traceIs(trace, 'bar')) hasBars = true; + if(_$registry_731.traceIs(trace, 'bar')) hasBars = true; else continue; // if we have at least 2 grouped bar traces on the same subplot, @@ -35485,7 +39635,7 @@ var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { } if(trace.visible && trace.type === 'histogram') { - var pa = _$axes_584.getFromId({_fullLayout: layoutOut}, + var pa = _$axes_647.getFromId({_fullLayout: layoutOut}, trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); if(pa.type !== 'category') shouldBeGapless = true; } @@ -35511,28 +39661,28 @@ var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var __dummy_685$0 = 0, - attributeText = _$attributes_678.text, - attributeTextPosition = _$attributes_678.textposition, - attributeTextFont = _$attributes_678.textfont, - attributeInsideTextFont = _$attributes_678.insidetextfont, - attributeOutsideTextFont = _$attributes_678.outsidetextfont; +var __dummy_748$0 = 0, + attributeText = _$attributes_741.text, + attributeTextPosition = _$attributes_741.textposition, + attributeTextFont = _$attributes_741.textfont, + attributeInsideTextFont = _$attributes_741.insidetextfont, + attributeOutsideTextFont = _$attributes_741.outsidetextfont; // padding in pixels around text var TEXTPAD = 3; -var _$plot_685 = function plot(gd, plotinfo, cdbar) { +var _$plot_748 = function plot(gd, plotinfo, cdbar) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, fullLayout = gd._fullLayout; @@ -35544,21 +39694,23 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { bartraces.enter().append('g') .attr('class', 'trace bars'); - bartraces.each(function(d) { - d[0].node3 = _$d3_127.select(this); - }); + if(!plotinfo.isRangePlot) { + bartraces.each(function(d) { + d[0].node3 = _$d3_130.select(this); + }); + } bartraces.append('g') .attr('class', 'points') .each(function(d) { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var t = d[0].t; var trace = d[0].trace; var poffset = t.poffset; var poffsetIsArray = Array.isArray(poffset); sel.selectAll('g.point') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('g').classed('point', true) .each(function(di, i) { // now display the bar @@ -35590,22 +39742,22 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { di.ct = [(x0 + x1) / 2, y1]; } - if(!_$fastIsnumeric_139(x0) || !_$fastIsnumeric_139(x1) || - !_$fastIsnumeric_139(y0) || !_$fastIsnumeric_139(y1) || + if(!_$fastIsnumeric_196(x0) || !_$fastIsnumeric_196(x1) || + !_$fastIsnumeric_196(y0) || !_$fastIsnumeric_196(y1) || x0 === x1 || y0 === y1) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); return; } var lw = (di.mlw + 1 || trace.marker.line.width + 1 || (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, - offset = _$d3_127.round((lw / 2) % 1, 2); + offset = _$d3_130.round((lw / 2) % 1, 2); function roundWithLine(v) { // if there are explicit gaps, don't round, // it can make the gaps look crappy return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? - _$d3_127.round(Math.round(v) - offset, 2) : v; + _$d3_130.round(Math.round(v) - offset, 2) : v; } function expandToVisible(v, vc) { @@ -35625,7 +39777,7 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { // pixelation. if the bars ARE fully opaque and have // no line, expand to a full pixel to make sure we // can see them - var op = _$color_411.opacity(di.mc || trace.marker.color), + var op = _$color_473.opacity(di.mc || trace.marker.color), fixpx = (op < 1 || lw > 0.01) ? roundWithLine : expandToVisible; x0 = fixpx(x0, x1); @@ -35635,30 +39787,30 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { } // append bar path and text - var bar = _$d3_127.select(this); + var bar = _$d3_130.select(this); bar.append('path') .style('vector-effect', 'non-scaling-stroke') .attr('d', 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') - .call(_$drawing_436.setClipUrl, plotinfo.layerClipId); + .call(_$drawing_498.setClipUrl, plotinfo.layerClipId); appendBarText(gd, bar, d, i, x0, x1, y0, y1); if(plotinfo.layerClipId) { - _$drawing_436.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_498.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); } }); }); // error bars are on the top - _$registry_668.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); + _$registry_731.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); // lastly, clip points groups of `cliponaxis !== false` traces // on `plotinfo._hasClipOnAxisFalse === true` subplots bartraces.each(function(d) { var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_436.setClipUrl(_$d3_127.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + _$drawing_498.setClipUrl(_$d3_130.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); }); }; @@ -35676,8 +39828,8 @@ function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { // tex and regular text together 'data-notex': 1 }) - .call(_$drawing_436.font, textFont) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$drawing_498.font, textFont) + .call(_$svg_text_utils_625.convertToTspans, gd); return textSelection; } @@ -35723,7 +39875,7 @@ function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { textPosition = 'inside'; textSelection = appendTextNode(bar, text, insideTextFont); - textBB = _$drawing_436.bBox(textSelection.node()), + textBB = _$drawing_498.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height; @@ -35753,7 +39905,7 @@ function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { (textPosition === 'outside') ? outsideTextFont : insideTextFont); - textBB = _$drawing_436.bBox(textSelection.node()), + textBB = _$drawing_498.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height; @@ -36016,7 +40168,7 @@ function coerceEnumerated(attributeDefinition, value, defaultValue) { } function coerceNumber(attributeDefinition, value, defaultValue) { - if(_$fastIsnumeric_139(value)) { + if(_$fastIsnumeric_196(value)) { value = +value; var min = attributeDefinition.min, @@ -36033,7 +40185,7 @@ function coerceNumber(attributeDefinition, value, defaultValue) { } function coerceColor(attributeDefinition, value, defaultValue) { - if(_$tinycolor_352(value).isValid()) return value; + if(_$tinycolor_414(value).isValid()) return value; return (defaultValue !== undefined) ? defaultValue : @@ -36050,7 +40202,7 @@ function coerceColor(attributeDefinition, value, defaultValue) { 'use strict'; -var _$selectPoints_686 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_749 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -36092,10 +40244,10 @@ var _$selectPoints_686 = function selectPoints(searchInfo, polygon) { 'use strict'; -var _$Sieve_688 = Sieve; +var _$Sieve_751 = Sieve; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_688 = _$numerical_517.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_751 = _$numerical_578.BADNUM; /** * Helper class to sieve data from traces into bins @@ -36122,7 +40274,7 @@ function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { var trace = traces[i]; for(var j = 0; j < trace.length; j++) { var bar = trace[j]; - if(bar.p !== __BADNUM_688) positions.push(bar.p); + if(bar.p !== __BADNUM_751) positions.push(bar.p); } if(trace[0] && trace[0].width1) { width1 = Math.min(trace[0].width1, width1); @@ -36130,7 +40282,7 @@ function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { } this.positions = positions; - var dv = _$lib_539.distinctVals(positions); + var dv = _$lib_601.distinctVals(positions); this.distinctPositions = dv.vals; if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; else this.minDiff = Math.min(dv.minDiff, width1); @@ -36201,13 +40353,13 @@ Sieve.prototype.getLabel = function getLabel(position, value) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_687 = _$lib_539.isArrayOrTypedArray; -var __BADNUM_687 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_750 = _$lib_601.isArrayOrTypedArray; +var __BADNUM_750 = _$numerical_578.BADNUM; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$Sieve_688 = require('./sieve.js'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$Sieve_751 = require('./sieve.js'); */; /* * Bar chart stacking/grouping positioning and autoscaling calculations @@ -36216,7 +40368,7 @@ var __BADNUM_687 = _$numerical_517.BADNUM; * now doing this one subplot at a time */ -var _$setPositions_687 = function setPositions(gd, plotinfo) { +var _$setPositions_750 = function setPositions(gd, plotinfo) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis; @@ -36229,7 +40381,7 @@ var _$setPositions_687 = function setPositions(gd, plotinfo) { var fullTrace = fullTraces[i]; if( fullTrace.visible === true && - _$registry_668.traceIs(fullTrace, 'bar') && + _$registry_731.traceIs(fullTrace, 'bar') && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id ) { @@ -36312,7 +40464,7 @@ function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { for(var i = 0; i < calcTraces.length; i++) { var calcTrace = calcTraces[i]; - var sieve = new _$Sieve_688( + var sieve = new _$Sieve_751( [calcTrace], separateNegativeValues, dontMergeOverlappingData ); @@ -36340,7 +40492,7 @@ function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { barnorm = fullLayout.barnorm, separateNegativeValues = false, dontMergeOverlappingData = !barnorm, - sieve = new _$Sieve_688( + sieve = new _$Sieve_751( calcTraces, separateNegativeValues, dontMergeOverlappingData ); @@ -36366,7 +40518,7 @@ function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { barnorm = gd._fullLayout.barnorm, separateNegativeValues = relative, dontMergeOverlappingData = !(barnorm || stack || relative), - sieve = new _$Sieve_688( + sieve = new _$Sieve_751( calcTraces, separateNegativeValues, dontMergeOverlappingData ); @@ -36383,7 +40535,7 @@ function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { for(var j = 0; j < calcTrace.length; j++) { var bar = calcTrace[j]; - if(bar.s === __BADNUM_687) continue; + if(bar.s === __BADNUM_750) continue; var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); if(isOutmostBar) bar._outmost = true; @@ -36506,13 +40658,13 @@ function applyAttributes(sieve) { initialPoffset = t.poffset, newPoffset; - if(__isArrayOrTypedArray_687(offset)) { + if(__isArrayOrTypedArray_750(offset)) { // if offset is an array, then clone it into t.poffset. newPoffset = offset.slice(0, calcTrace.length); // guard against non-numeric items for(j = 0; j < newPoffset.length; j++) { - if(!_$fastIsnumeric_139(newPoffset[j])) { + if(!_$fastIsnumeric_196(newPoffset[j])) { newPoffset[j] = initialPoffset; } } @@ -36532,13 +40684,13 @@ function applyAttributes(sieve) { var width = fullTrace.width, initialBarwidth = t.barwidth; - if(__isArrayOrTypedArray_687(width)) { + if(__isArrayOrTypedArray_750(width)) { // if width is an array, then clone it into t.barwidth. var newBarwidth = width.slice(0, calcTrace.length); // guard against non-numeric items for(j = 0; j < newBarwidth.length; j++) { - if(!_$fastIsnumeric_139(newBarwidth[j])) newBarwidth[j] = initialBarwidth; + if(!_$fastIsnumeric_196(newBarwidth[j])) newBarwidth[j] = initialBarwidth; } // if the length of the array is too short, @@ -36608,7 +40760,7 @@ function updatePositionAxis(gd, pa, sieve, allowMinDtick) { minDiff = sieve.minDiff, vpad = minDiff / 2; - _$axes_584.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + _$axes_647.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); // If the user set the bar width or the offset, // then bars can be shifted away from their positions @@ -36647,14 +40799,14 @@ function updatePositionAxis(gd, pa, sieve, allowMinDtick) { } } - _$axes_584.expand(pa, [pMin, pMax], {padded: false}); + _$axes_647.expand(pa, [pMin, pMax], {padded: false}); } function expandRange(range, newValue) { - if(_$fastIsnumeric_139(range[0])) range[0] = Math.min(range[0], newValue); + if(_$fastIsnumeric_196(range[0])) range[0] = Math.min(range[0], newValue); else range[0] = newValue; - if(_$fastIsnumeric_139(range[1])) range[1] = Math.max(range[1], newValue); + if(_$fastIsnumeric_196(range[1])) range[1] = Math.max(range[1], newValue); else range[1] = newValue; } @@ -36676,12 +40828,12 @@ function setBaseAndTop(gd, sa, sieve) { bar[sLetter] = barTop; - if(_$fastIsnumeric_139(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_139(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$fastIsnumeric_196(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_196(sa.c2l(barBase))) expandRange(sRange, barBase); } } - _$axes_584.expand(sa, sRange, {tozero: true, padded: true}); + _$axes_647.expand(sa, sRange, {tozero: true, padded: true}); } @@ -36701,7 +40853,7 @@ function stackBars(gd, sa, sieve) { for(j = 0; j < trace.length; j++) { bar = trace[j]; - if(bar.s === __BADNUM_687) continue; + if(bar.s === __BADNUM_750) continue; // stack current bar and get previous sum var barBase = sieve.put(bar.p, bar.b + bar.s), @@ -36712,14 +40864,14 @@ function stackBars(gd, sa, sieve) { bar[sLetter] = barTop; if(!barnorm) { - if(_$fastIsnumeric_139(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_139(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$fastIsnumeric_196(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_196(sa.c2l(barBase))) expandRange(sRange, barBase); } } } // if barnorm is set, let normalizeBars update the axis range - if(!barnorm) _$axes_584.expand(sa, sRange, {tozero: true, padded: true}); + if(!barnorm) _$axes_647.expand(sa, sRange, {tozero: true, padded: true}); } @@ -36732,7 +40884,7 @@ function sieveBars(gd, sa, sieve) { for(var j = 0; j < trace.length; j++) { var bar = trace[j]; - if(bar.s !== __BADNUM_687) sieve.put(bar.p, bar.b + bar.s); + if(bar.s !== __BADNUM_750) sieve.put(bar.p, bar.b + bar.s); } } } @@ -36754,8 +40906,8 @@ function normalizeBars(gd, sa, sieve) { padded = false; function maybeExpand(newValue) { - if(_$fastIsnumeric_139(sa.c2l(newValue)) && - ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_139(sMin)) + if(_$fastIsnumeric_196(sa.c2l(newValue)) && + ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_196(sMin)) ) { padded = true; expandRange(sRange, newValue); @@ -36768,7 +40920,7 @@ function normalizeBars(gd, sa, sieve) { for(var j = 0; j < trace.length; j++) { var bar = trace[j]; - if(bar.s === __BADNUM_687) continue; + if(bar.s === __BADNUM_750) continue; var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); bar.b *= scale; @@ -36784,7 +40936,7 @@ function normalizeBars(gd, sa, sieve) { } // update range of size axis - _$axes_584.expand(sa, sRange, {tozero: true, padded: padded}); + _$axes_647.expand(sa, sRange, {tozero: true, padded: padded}); } @@ -36808,7 +40960,7 @@ function collectExtents(calcTraces, pa) { cd = calcTraces[i]; for(j = 0; j < cd.length; j++) { var p = cd[j].p; - if(_$fastIsnumeric_139(p)) { + if(_$fastIsnumeric_196(p)) { pMin = Math.min(pMin, p); pMax = Math.max(pMax, p); } @@ -36829,7 +40981,7 @@ function collectExtents(calcTraces, pa) { for(j = 0; j < cd.length; j++) { var di = cd[j]; var p0 = di[posLetter] - di.w / 2; - if(_$fastIsnumeric_139(p0)) { + if(_$fastIsnumeric_196(p0)) { var p1 = di[posLetter] + di.w / 2; var pVal = round(di.p); if(extents[pVal]) { @@ -36854,12 +41006,12 @@ function collectExtents(calcTraces, pa) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$style_689 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.bars'); +var _$style_752 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.trace.bars'); var barcount = s.size(); var fullLayout = gd._fullLayout; @@ -36874,21 +41026,21 @@ var _$style_689 = function style(gd, cd) { (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width)) { - _$d3_127.select(this).attr('shape-rendering', 'crispEdges'); + _$d3_130.select(this).attr('shape-rendering', 'crispEdges'); } }); s.selectAll('g.points').each(function(d) { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var pts = sel.selectAll('path'); var txs = sel.selectAll('text'); var trace = d[0].trace; - _$drawing_436.pointStyle(pts, trace, gd); - _$drawing_436.selectedPointStyle(pts, trace); + _$drawing_498.pointStyle(pts, trace, gd); + _$drawing_498.selectedPointStyle(pts, trace); txs.each(function(d) { - var tx = _$d3_127.select(this); + var tx = _$d3_130.select(this); var textFont; if(tx.classed('bartext-inside')) { @@ -36903,13 +41055,13 @@ var _$style_689 = function style(gd, cd) { return Array.isArray(cont) ? cont[d.i] : cont; } - _$drawing_436.font(tx, cast('family'), cast('size'), cast('color')); + _$drawing_498.font(tx, cast('family'), cast('size'), cast('color')); }); - _$drawing_436.selectedTextStyle(txs, trace); + _$drawing_498.selectedTextStyle(txs, trace); }); - _$registry_668.getComponentMethod('errorbars', 'style')(s); + _$registry_731.getComponentMethod('errorbars', 'style')(s); }; /** @@ -36922,7 +41074,7 @@ var _$style_689 = function style(gd, cd) { 'use strict'; -var _$constants_413 = { +var _$constants_475 = { cn: { colorbar: 'colorbar', cbbg: 'cbbg', @@ -36950,34 +41102,34 @@ var _$constants_413 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __extendFlat_415 = _$extend_528.extendFlat; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$titles_504 = require('../titles'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -var __LINE_SPACING_415 = _$alignment_511.LINE_SPACING; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __extendFlat_477 = _$extend_590.extendFlat; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$titles_566 = require('../titles'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +var __LINE_SPACING_477 = _$alignment_573.LINE_SPACING; -/* removed: var _$handleAxisDefaults_586 = require('../../plots/cartesian/axis_defaults'); */; -/* removed: var _$handlePositionDefaults_600 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$handleAxisDefaults_649 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handlePositionDefaults_662 = require('../../plots/cartesian/position_defaults'); */; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$attributes_412 = require('./attributes'); */; -var cn = _$constants_413.cn; +/* removed: var _$attributes_474 = require('./attributes'); */; +var cn = _$constants_475.cn; -var _$draw_415 = function draw(gd, id) { +var _$draw_477 = function draw(gd, id) { // opts: options object, containing everything from attributes // plus a few others that are the equivalent of the colorbar "data" var opts = {}; - Object.keys(_$attributes_412).forEach(function(k) { + Object.keys(_$attributes_474).forEach(function(k) { opts[k] = null; }); // fillcolor can be a d3 scale, domain is z values, range is colors @@ -37004,7 +41156,7 @@ var _$draw_415 = function draw(gd, id) { fullLayout._infolayer.selectAll('g.' + id).remove(); return; } - var zrange = _$d3_127.extent(((typeof opts.fillcolor === 'function') ? + var zrange = _$d3_130.extent(((typeof opts.fillcolor === 'function') ? opts.fillcolor : opts.line.color).domain()); var linelevels = []; var filllevels = []; @@ -37132,12 +41284,12 @@ var _$draw_415 = function draw(gd, id) { // Coerce w.r.t. Axes layoutAttributes: // re-use axes.js logic without updating _fullData function coerce(attr, dflt) { - return _$lib_539.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_596, attr, dflt); + return _$lib_601.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_659, attr, dflt); } // Prepare the Plotly axis object - _$handleAxisDefaults_586(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); - _$handlePositionDefaults_600(cbAxisIn, cbAxisOut, coerce, axisOptions); + _$handleAxisDefaults_649(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handlePositionDefaults_662(cbAxisIn, cbAxisOut, coerce, axisOptions); // position can't go in through supplyDefaults // because that restricts it to [0,1] @@ -37158,14 +41310,14 @@ var _$draw_415 = function draw(gd, id) { cbAxisOut.tick0 = opts.levels.start; var dtick = opts.levels.size; // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_539.constrain( + var autoNtick = _$lib_601.constrain( (yBottomPx - yTopPx) / 50, 4, 15) + 1, dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick); if(dtFactor > 1) { var dtexp = Math.pow(10, Math.floor( Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_539.roundUp(dtFactor / dtexp, [2, 5, 10]); + dtick *= dtexp * _$lib_601.roundUp(dtFactor / dtexp, [2, 5, 10]); // if the contours are at round multiples, reset tick0 // so they're still at round multiples. Otherwise, // keep the first label on the first contour level @@ -37186,20 +41338,21 @@ var _$draw_415 = function draw(gd, id) { cbAxisOut.setScale(); // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_127.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); + var container = _$lib_601.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_130.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); + container.attr('transform', 'translate(' + Math.round(gs.l) + ',' + Math.round(gs.t) + ')'); // TODO: this opposite transform is a hack until we make it @@ -37245,10 +41398,10 @@ var _$draw_415 = function draw(gd, id) { lineSize = 15.6; if(titleText.node()) { lineSize = - parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_415; + parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_477; } if(mathJaxNode) { - titleHeight = _$drawing_436.bBox(mathJaxNode).height; + titleHeight = _$drawing_498.bBox(mathJaxNode).height; if(titleHeight > lineSize) { // not entirely sure how mathjax is doing // vertical alignment, but this seems to work. @@ -37257,7 +41410,7 @@ var _$draw_415 = function draw(gd, id) { } else if(titleText.node() && !titleText.classed(cn.jsPlaceholder)) { - titleHeight = _$drawing_436.bBox(titleText.node()).height; + titleHeight = _$drawing_498.bBox(titleText.node()).height; } if(titleHeight) { // buffer btwn colorbar and title @@ -37270,7 +41423,7 @@ var _$draw_415 = function draw(gd, id) { } else { cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_562.lineCount(titleText); + var nlines = _$svg_text_utils_625.lineCount(titleText); titleTrans[1] += (1 - nlines) * lineSize; } @@ -37315,15 +41468,15 @@ var _$draw_415 = function draw(gd, id) { // Tinycolor can't handle exponents and // at this scale, removing it makes no difference. var colorString = fillcolormap(d).replace('e-', ''), - opaqueColor = _$tinycolor_352(colorString).toHexString(); + opaqueColor = _$tinycolor_414(colorString).toHexString(); // Colorbar cannot currently support opacities so we // use an opaque fill even when alpha channels present - _$d3_127.select(this).attr({ + _$d3_130.select(this).attr({ x: xLeft, width: Math.max(thickPx, 2), - y: _$d3_127.min(z), - height: Math.max(_$d3_127.max(z) - _$d3_127.min(z), 2), + y: _$d3_130.min(z), + height: Math.max(_$d3_130.max(z) - _$d3_130.min(z), 2), fill: opaqueColor }); }); @@ -37336,11 +41489,11 @@ var _$draw_415 = function draw(gd, id) { .classed(cn.cbline, true); lines.exit().remove(); lines.each(function(d) { - _$d3_127.select(this) + _$d3_130.select(this) .attr('d', 'M' + xLeft + ',' + (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + 'h' + thickPx) - .call(_$drawing_436.lineGroupStyle, + .call(_$drawing_498.lineGroupStyle, opts.line.width, linecolormap(d), opts.line.dash); }); @@ -37356,9 +41509,9 @@ var _$draw_415 = function draw(gd, id) { // so we don't need such complicated logic in Titles.draw // if title is on the top or bottom, we've already drawn it // this title call only handles side=right - return _$lib_539.syncOrAsync([ + return _$lib_601.syncOrAsync([ function() { - return _$axes_584.doTicks(gd, cbAxisOut, true); + return _$axes_647.doTicks(gd, cbAxisOut, true); }, function() { if(['top', 'bottom'].indexOf(opts.titleside) === -1) { @@ -37373,7 +41526,7 @@ var _$draw_415 = function draw(gd, id) { // TODO: find a better way to control this. drawTitle('h' + cbAxisOut._id + 'title', { avoid: { - selection: _$d3_127.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), + selection: _$d3_130.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), side: opts.titleside, offsetLeft: gs.l, offsetTop: 0, @@ -37389,7 +41542,7 @@ var _$draw_415 = function draw(gd, id) { function drawTitle(titleClass, titleOpts) { var trace = getTrace(), propName; - if(_$registry_668.traceIs(trace, 'markerColorscale')) { + if(_$registry_731.traceIs(trace, 'markerColorscale')) { propName = 'marker.colorbar.title'; } else propName = 'colorbar.title'; @@ -37411,8 +41564,8 @@ var _$draw_415 = function draw(gd, id) { container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') .remove(); - _$titles_504.draw(gd, titleClass, - __extendFlat_415(dfltTitleOpts, titleOpts || {})); + _$titles_566.draw(gd, titleClass, + __extendFlat_477(dfltTitleOpts, titleOpts || {})); } function positionCB() { @@ -37421,7 +41574,7 @@ var _$draw_415 = function draw(gd, id) { // TODO: why are we redrawing multiple times now with this? // I guess autoMargin doesn't like being post-promise? var innerWidth = thickPx + opts.outlinewidth / 2 + - _$drawing_436.bBox(cbAxisOut._axislayer.node()).width; + _$drawing_498.bBox(cbAxisOut._axislayer.node()).width; titleEl = titleCont.select('text'); if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { var mathJaxNode = titleCont @@ -37430,7 +41583,7 @@ var _$draw_415 = function draw(gd, id) { titleWidth; if(mathJaxNode && ['top', 'bottom'].indexOf(opts.titleside) !== -1) { - titleWidth = _$drawing_436.bBox(mathJaxNode).width; + titleWidth = _$drawing_498.bBox(mathJaxNode).width; } else { // note: the formula below works for all titlesides, @@ -37438,7 +41591,7 @@ var _$draw_415 = function draw(gd, id) { // but the weird gs.l is because the titleunshift // transform gets removed by Drawing.bBox titleWidth = - _$drawing_436.bBox(titleCont.node()).right - + _$drawing_498.bBox(titleCont.node()).right - xLeft - gs.l; } innerWidth = Math.max(innerWidth, titleWidth); @@ -37455,8 +41608,8 @@ var _$draw_415 = function draw(gd, id) { width: Math.max(outerwidth, 2), height: Math.max(outerheight + 2 * yExtraPx, 2) }) - .call(_$color_411.fill, opts.bgcolor) - .call(_$color_411.stroke, opts.bordercolor) + .call(_$color_473.fill, opts.bgcolor) + .call(_$color_473.stroke, opts.bordercolor) .style({'stroke-width': opts.borderwidth}); container.selectAll('.cboutline').attr({ @@ -37466,7 +41619,7 @@ var _$draw_415 = function draw(gd, id) { width: Math.max(thickPx, 2), height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) }) - .call(_$color_411.stroke, opts.outlinecolor) + .call(_$color_473.stroke, opts.outlinecolor) .style({ fill: 'None', 'stroke-width': opts.outlinewidth @@ -37479,7 +41632,7 @@ var _$draw_415 = function draw(gd, id) { 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); // auto margin adjustment - _$plots_647.autoMargin(gd, id, { + _$plots_709.autoMargin(gd, id, { x: opts.x, y: opts.y, l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), @@ -37489,10 +41642,10 @@ var _$draw_415 = function draw(gd, id) { }); } - var cbDone = _$lib_539.syncOrAsync([ - _$plots_647.previousPromises, + var cbDone = _$lib_601.syncOrAsync([ + _$plots_709.previousPromises, drawAxis, - _$plots_647.previousPromises, + _$plots_709.previousPromises, positionCB ], gd); @@ -37504,31 +41657,31 @@ var _$draw_415 = function draw(gd, id) { xf, yf; - _$dragelement_433.init({ + _$dragelement_495.init({ element: container.node(), gd: gd, prepFn: function() { t0 = container.attr('transform'); - _$setCursor_558(container); + _$setCursor_621(container); }, moveFn: function(dx, dy) { container.attr('transform', t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); - xf = _$dragelement_433.align(xLeftFrac + (dx / gs.w), thickFrac, + xf = _$dragelement_495.align(xLeftFrac + (dx / gs.w), thickFrac, 0, 1, opts.xanchor); - yf = _$dragelement_433.align(yBottomFrac - (dy / gs.h), lenFrac, + yf = _$dragelement_495.align(yBottomFrac - (dy / gs.h), lenFrac, 0, 1, opts.yanchor); - var csr = _$dragelement_433.getCursor(xf, yf, + var csr = _$dragelement_495.getCursor(xf, yf, opts.xanchor, opts.yanchor); - _$setCursor_558(container, csr); + _$setCursor_621(container, csr); }, doneFn: function() { - _$setCursor_558(container); + _$setCursor_621(container); if(xf !== undefined && yf !== undefined) { - _$registry_668.call('restyle', + _$registry_731.call('restyle', gd, {'colorbar.x': xf, 'colorbar.y': yf}, getTrace().index @@ -37558,8 +41711,8 @@ var _$draw_415 = function draw(gd, id) { // setter - for multi-part properties, // set only the parts that are provided - opts[name] = _$lib_539.isPlainObject(opts[name]) ? - _$lib_539.extendFlat(opts[name], v) : + opts[name] = _$lib_601.isPlainObject(opts[name]) ? + _$lib_601.extendFlat(opts[name], v) : v; return component; @@ -37594,15 +41747,15 @@ var _$draw_415 = function draw(gd, id) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_866 = function colorbar(gd, cd) { +var _$colorbar_931 = function colorbar(gd, cd) { var trace = cd[0].trace, marker = trace.marker, cbId = 'cb' + trace.uid; @@ -37612,7 +41765,7 @@ var _$colorbar_866 = function colorbar(gd, cd) { // TODO make Colorbar.draw support multiple colorbar per trace if((marker === undefined) || !marker.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } @@ -37620,12 +41773,12 @@ var _$colorbar_866 = function colorbar(gd, cd) { cmin = marker.cmin, cmax = marker.cmax; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( marker.colorscale, cmin, cmax @@ -37651,23 +41804,23 @@ var _$colorbar_866 = function colorbar(gd, cd) { var Bar = {}; -Bar.attributes = _$attributes_678; -Bar.layoutAttributes = _$layout_attributes_683; -Bar.supplyDefaults = _$supplyDefaults_680; -Bar.supplyLayoutDefaults = _$layout_defaults_684; -Bar.calc = _$calc_679; -Bar.setPositions = _$setPositions_687; -Bar.colorbar = _$colorbar_866; -Bar.arraysToCalcdata = _$arraysToCalcdata_677; -Bar.plot = _$plot_685; -Bar.style = _$style_689; -Bar.hoverPoints = _$hoverPoints_681; -Bar.selectPoints = _$selectPoints_686; +Bar.attributes = _$attributes_741; +Bar.layoutAttributes = _$layout_attributes_746; +Bar.supplyDefaults = _$supplyDefaults_743; +Bar.supplyLayoutDefaults = _$layout_defaults_747; +Bar.calc = _$calc_742; +Bar.setPositions = _$setPositions_750; +Bar.colorbar = _$colorbar_931; +Bar.arraysToCalcdata = _$arraysToCalcdata_740; +Bar.plot = _$plot_748; +Bar.style = _$style_752; +Bar.hoverPoints = _$hoverPoints_744; +Bar.selectPoints = _$selectPoints_749; Bar.moduleType = 'trace'; Bar.name = 'bar'; -Bar.basePlotModule = _$cartesian_595; -Bar.categories = ['cartesian', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend']; +Bar.basePlotModule = _$cartesian_658; +Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend', 'draggedPts']; Bar.meta = { description: [ 'The data visualized by the span of the bars is set in `y`', @@ -37677,7 +41830,7 @@ Bar.meta = { ].join(' ') }; -var _$Bar_682 = Bar; +var _$Bar_745 = Bar; /** * Copyright 2012-2018, Plotly, Inc. @@ -37689,7 +41842,7 @@ var _$Bar_682 = Bar; 'use strict'; -var _$bar_4 = _$Bar_682; +var _$bar_4 = _$Bar_745; /** * Copyright 2012-2018, Plotly, Inc. @@ -37701,14 +41854,14 @@ var _$bar_4 = _$Bar_682; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -var __extendFlat_691 = _$extend_528.extendFlat; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +var __extendFlat_754 = _$extend_590.extendFlat; -var __scatterMarkerAttrs_691 = _$attributes_862.marker; -var __scatterMarkerLineAttrs_691 = __scatterMarkerAttrs_691.line; +var __scatterMarkerAttrs_754 = _$attributes_927.marker; +var __scatterMarkerLineAttrs_754 = __scatterMarkerAttrs_754.line; -var _$attributes_691 = { +var _$attributes_754 = { y: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -37755,7 +41908,7 @@ var _$attributes_691 = { 'missing and the position axis is categorical' ].join(' ') }, - text: __extendFlat_691({}, _$attributes_862.text, { + text: __extendFlat_754({}, _$attributes_927.text, { description: [ 'Sets the text elements associated with each sample value.', 'If a single string, the same string appears over', @@ -37872,19 +42025,19 @@ var _$attributes_691 = { editType: 'style', description: 'Sets the color of the outlier sample points.' }, - symbol: __extendFlat_691({}, __scatterMarkerAttrs_691.symbol, + symbol: __extendFlat_754({}, __scatterMarkerAttrs_754.symbol, {arrayOk: false, editType: 'plot'}), - opacity: __extendFlat_691({}, __scatterMarkerAttrs_691.opacity, + opacity: __extendFlat_754({}, __scatterMarkerAttrs_754.opacity, {arrayOk: false, dflt: 1, editType: 'style'}), - size: __extendFlat_691({}, __scatterMarkerAttrs_691.size, + size: __extendFlat_754({}, __scatterMarkerAttrs_754.size, {arrayOk: false, editType: 'calcIfAutorange'}), - color: __extendFlat_691({}, __scatterMarkerAttrs_691.color, + color: __extendFlat_754({}, __scatterMarkerAttrs_754.color, {arrayOk: false, editType: 'style'}), line: { - color: __extendFlat_691({}, __scatterMarkerLineAttrs_691.color, - {arrayOk: false, dflt: _$attributes_410.defaultLine, editType: 'style'} + color: __extendFlat_754({}, __scatterMarkerLineAttrs_754.color, + {arrayOk: false, dflt: _$attributes_472.defaultLine, editType: 'style'} ), - width: __extendFlat_691({}, __scatterMarkerLineAttrs_691.width, + width: __extendFlat_754({}, __scatterMarkerLineAttrs_754.width, {arrayOk: false, dflt: 0, editType: 'style'} ), outliercolor: { @@ -37927,14 +42080,14 @@ var _$attributes_691 = { }, editType: 'plot' }, - fillcolor: _$attributes_862.fillcolor, + fillcolor: _$attributes_927.fillcolor, selected: { - marker: _$attributes_862.selected.marker, + marker: _$attributes_927.selected.marker, editType: 'style' }, unselected: { - marker: _$attributes_862.unselected.marker, + marker: _$attributes_927.unselected.marker, editType: 'style' }, @@ -37961,17 +42114,17 @@ var _$attributes_691 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var ____692 = _$lib_539._; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var ____755 = _$lib_601._; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; // outlier definition based on http://www.physics.csbsju.edu/stats/box2.html -var _$calc_692 = function calc(gd, trace) { +var _$calc_755 = function calc(gd, trace) { var fullLayout = gd._fullLayout; - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'); var cd = []; // N.B. violin reuses same Box.calc @@ -37996,7 +42149,7 @@ var _$calc_692 = function calc(gd, trace) { var val = valAxis.makeCalcdata(trace, valLetter); var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]); - var dv = _$lib_539.distinctVals(pos); + var dv = _$lib_601.distinctVals(pos); var posDistinct = dv.vals; var dPos = dv.minDiff / 2; var posBins = makeBins(posDistinct, dPos); @@ -38008,12 +42161,12 @@ var _$calc_692 = function calc(gd, trace) { // bin pts info per position bins for(i = 0; i < vLen; i++) { var v = val[i]; - if(!_$fastIsnumeric_139(v)) continue; + if(!_$fastIsnumeric_196(v)) continue; - var n = _$lib_539.findBin(pos[i], posBins); + var n = _$lib_601.findBin(pos[i], posBins); if(n >= 0 && n < pLen) { var pt = {v: v, i: i}; - __arraysToCalcdata_692(pt, trace, i); + __arraysToCalcdata_755(pt, trace, i); ptsPerBin[n].push(pt); } } @@ -38032,29 +42185,29 @@ var _$calc_692 = function calc(gd, trace) { cdi.min = boxVals[0]; cdi.max = boxVals[bvLen - 1]; - cdi.mean = _$lib_539.mean(boxVals, bvLen); - cdi.sd = _$lib_539.stdev(boxVals, bvLen, cdi.mean); + cdi.mean = _$lib_601.mean(boxVals, bvLen); + cdi.sd = _$lib_601.stdev(boxVals, bvLen, cdi.mean); // first quartile - cdi.q1 = _$lib_539.interp(boxVals, 0.25); + cdi.q1 = _$lib_601.interp(boxVals, 0.25); // median - cdi.med = _$lib_539.interp(boxVals, 0.5); + cdi.med = _$lib_601.interp(boxVals, 0.5); // third quartile - cdi.q3 = _$lib_539.interp(boxVals, 0.75); + cdi.q3 = _$lib_601.interp(boxVals, 0.75); // lower and upper fences - last point inside // 1.5 interquartile ranges from quartiles cdi.lf = Math.min( cdi.q1, boxVals[Math.min( - _$lib_539.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, + _$lib_601.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, bvLen - 1 )] ); cdi.uf = Math.max( cdi.q3, boxVals[Math.max( - _$lib_539.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), + _$lib_601.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), 0 )] ); @@ -38075,8 +42228,8 @@ var _$calc_692 = function calc(gd, trace) { } } - __calcSelection_692(cd, trace); - _$axes_584.expand(valAxis, val, {padded: true}); + __calcSelection_755(cd, trace); + _$axes_647.expand(valAxis, val, {padded: true}); if(cd.length > 0) { cd[0].t = { @@ -38085,22 +42238,17 @@ var _$calc_692 = function calc(gd, trace) { posLetter: posLetter, valLetter: valLetter, labels: { - med: ____692(gd, 'median:'), - min: ____692(gd, 'min:'), - q1: ____692(gd, 'q1:'), - q3: ____692(gd, 'q3:'), - max: ____692(gd, 'max:'), - mean: trace.boxmean === 'sd' ? ____692(gd, 'mean ± σ:') : ____692(gd, 'mean:'), - lf: ____692(gd, 'lower fence:'), - uf: ____692(gd, 'upper fence:') + med: ____755(gd, 'median:'), + min: ____755(gd, 'min:'), + q1: ____755(gd, 'q1:'), + q3: ____755(gd, 'q3:'), + max: ____755(gd, 'max:'), + mean: trace.boxmean === 'sd' ? ____755(gd, 'mean ± σ:') : ____755(gd, 'mean:'), + lf: ____755(gd, 'lower fence:'), + uf: ____755(gd, 'upper fence:') } }; - // don't show labels in candlestick hover labels - if(trace._fullInput && trace._fullInput.type === 'candlestick') { - delete cd[0].t.labels; - } - fullLayout[numKey]++; return cd; } else { @@ -38124,10 +42272,10 @@ function getPos(trace, posLetter, posAxis, val, num) { pos0 = trace[posLetter + '0']; } else if('name' in trace && ( posAxis.type === 'category' || ( - _$fastIsnumeric_139(trace.name) && + _$fastIsnumeric_196(trace.name) && ['linear', 'log'].indexOf(posAxis.type) !== -1 ) || ( - _$lib_539.isDateTime(trace.name) && + _$lib_601.isDateTime(trace.name) && posAxis.type === 'date' ) )) { @@ -38160,7 +42308,7 @@ function initNestedArray(len) { return arr; } -function __arraysToCalcdata_692(pt, trace, i) { +function __arraysToCalcdata_755(pt, trace, i) { var trace2calc = { text: 'tx' }; @@ -38172,8 +42320,8 @@ function __arraysToCalcdata_692(pt, trace, i) { } } -function __calcSelection_692(cd, trace) { - if(_$lib_539.isArrayOrTypedArray(trace.selectedpoints)) { +function __calcSelection_755(cd, trace) { + if(_$lib_601.isArrayOrTypedArray(trace.selectedpoints)) { for(var i = 0; i < cd.length; i++) { var pts = cd[i].pts || []; var ptNumber2cdIndex = {}; @@ -38182,7 +42330,7 @@ function __calcSelection_692(cd, trace) { ptNumber2cdIndex[pts[j].i] = j; } - _$lib_539.tagSelected(pts, trace, ptNumber2cdIndex); + _$lib_601.tagSelected(pts, trace, ptNumber2cdIndex); } } } @@ -38201,15 +42349,15 @@ function extractVal(o) { return o.v; } 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$attributes_691 = require('./attributes'); */; +/* removed: var _$attributes_754 = require('./attributes'); */; function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_691, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_754, attr, dflt); } handleSampleDefaults(traceIn, traceOut, coerce, layout); @@ -38217,7 +42365,7 @@ function supplyDefaults(traceIn, traceOut, defaultColor, layout) { coerce('line.color', (traceIn.marker || {}).color || defaultColor); coerce('line.width'); - coerce('fillcolor', _$color_411.addOpacity(traceOut.line.color, 0.5)); + coerce('fillcolor', _$color_473.addOpacity(traceOut.line.color, 0.5)); coerce('whiskerwidth'); coerce('boxmean'); @@ -38245,7 +42393,7 @@ function handleSampleDefaults(traceIn, traceOut, coerce, layout) { return; } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); coerce('orientation', defaultOrientation); @@ -38254,7 +42402,7 @@ function handleSampleDefaults(traceIn, traceOut, coerce, layout) { function handlePointsDefaults(traceIn, traceOut, coerce, opts) { var prefix = opts.prefix; - var outlierColorDflt = _$lib_539.coerce2(traceIn, traceOut, _$attributes_691, 'marker.outliercolor'); + var outlierColorDflt = _$lib_601.coerce2(traceIn, traceOut, _$attributes_754, 'marker.outliercolor'); var lineoutliercolor = coerce('marker.line.outliercolor'); var points = coerce( @@ -38290,10 +42438,10 @@ function handlePointsDefaults(traceIn, traceOut, coerce, opts) { coerce('hoveron'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); } -var _$defaults_693 = { +var _$defaults_756 = { supplyDefaults: supplyDefaults, handleSampleDefaults: handleSampleDefaults, handlePointsDefaults: handlePointsDefaults @@ -38309,11 +42457,11 @@ var _$defaults_693 = { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; @@ -38359,25 +42507,26 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { hoverPseudoDistance, spikePseudoDistance; var boxDelta = t.bdPos; + var posAcceptance = t.wHover; var shiftPos = function(di) { return di.pos + t.bPos - pVal; }; if(isViolin && trace.side !== 'both') { if(trace.side === 'positive') { dPos = function(di) { var pos = shiftPos(di); - return _$fx_453.inbox(pos, pos + boxDelta, hoverPseudoDistance); + return _$fx_515.inbox(pos, pos + posAcceptance, hoverPseudoDistance); }; } if(trace.side === 'negative') { dPos = function(di) { var pos = shiftPos(di); - return _$fx_453.inbox(pos - boxDelta, pos, hoverPseudoDistance); + return _$fx_515.inbox(pos - posAcceptance, pos, hoverPseudoDistance); }; } } else { dPos = function(di) { var pos = shiftPos(di); - return _$fx_453.inbox(pos - boxDelta, pos + boxDelta, hoverPseudoDistance); + return _$fx_515.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance); }; } @@ -38385,11 +42534,11 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { if(isViolin) { dVal = function(di) { - return _$fx_453.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); + return _$fx_515.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); }; } else { dVal = function(di) { - return _$fx_453.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); + return _$fx_515.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); }; } @@ -38419,8 +42568,8 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_453.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_453.getClosest(cd, distfn, pointData); + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_515.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point // and create the item(s) in closedata for this point @@ -38430,14 +42579,13 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { var lc = trace.line.color; var mc = (trace.marker || {}).color; - if(_$color_411.opacity(lc) && trace.line.width) pointData.color = lc; - else if(_$color_411.opacity(mc) && trace.boxpoints) pointData.color = mc; + if(_$color_473.opacity(lc) && trace.line.width) pointData.color = lc; + else if(_$color_473.opacity(mc) && trace.boxpoints) pointData.color = mc; else pointData.color = trace.fillcolor; - pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - t.bdPos, true); - pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + t.bdPos, true); + pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDelta, true); + pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDelta, true); - _$axes_584.tickText(pAxis, pAxis.c2l(di.pos), 'hover').text; pointData[pLetter + 'LabelVal'] = di.pos; var spikePosAttr = pLetter + 'Spike'; @@ -38464,11 +42612,11 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { // copy out to a new object for each value to label var val = di[attr]; var valPx = vAxis.c2p(val, true); - var pointData2 = _$lib_539.extendFlat({}, pointData); + var pointData2 = _$lib_601.extendFlat({}, pointData); pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx; pointData2[vLetter + 'LabelVal'] = val; - pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_584.hoverLabelText(vAxis, val); + pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_647.hoverLabelText(vAxis, val); if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') { pointData2[vLetter + 'err'] = di.sd; @@ -38501,7 +42649,7 @@ function hoverOnPoints(pointData, xval, yval) { var rad = Math.max(3, di.mrc || 0); return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad); }; - var distfn = _$fx_453.quadrature(dx, dy); + var distfn = _$fx_515.quadrature(dx, dy); // show one point per trace var ijClosest = false; @@ -38530,7 +42678,7 @@ function hoverOnPoints(pointData, xval, yval) { var yc = ya.c2p(pt.y, true); var rad = pt.mrc || 1; - closePtData = _$lib_539.extendFlat({}, pointData, { + closePtData = _$lib_601.extendFlat({}, pointData, { // corresponds to index in x/y input data array index: pt.i, color: (trace.marker || {}).color, @@ -38546,12 +42694,12 @@ function hoverOnPoints(pointData, xval, yval) { var pLetter = trace.orientation === 'h' ? 'y' : 'x'; var pa = trace.orientation === 'h' ? ya : xa; closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true); - _$fillHoverText_870(pt, trace, closePtData); + _$fillHoverText_935(pt, trace, closePtData); return closePtData; } -var _$hover_694 = { +var _$hover_757 = { hoverPoints: hoverPoints, hoverOnBoxes: hoverOnBoxes, hoverOnPoints: hoverOnPoints @@ -38568,7 +42716,7 @@ var _$hover_694 = { 'use strict'; -var _$layout_attributes_696 = { +var _$layout_attributes_759 = { boxmode: { valType: 'enumerated', values: ['group', 'overlay'], @@ -38620,13 +42768,15 @@ var _$layout_attributes_696 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_696 = require('./layout_attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_759 = require('./layout_attributes'); */; function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { var hasTraceType; + var category = traceType + 'Layout'; for(var i = 0; i < fullData.length; i++) { - if(fullData[i].type === traceType) { + if(_$registry_731.traceIs(fullData[i], category)) { hasTraceType = true; break; } @@ -38640,12 +42790,12 @@ function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_696, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_759, attr, dflt); } _supply(layoutIn, layoutOut, fullData, coerce, 'box'); } -var _$layout_defaults_697 = { +var _$layout_defaults_760 = { supplyLayoutDefaults: supplyLayoutDefaults, _supply: _supply }; @@ -38660,10 +42810,10 @@ var _$layout_defaults_697 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; // constants for dynamic jitter (ie less jitter for sparser points) var JITTERCOUNT = 5; // points either side of this to include @@ -38684,19 +42834,22 @@ function plot(gd, plotinfo, cdbox) { var cd0 = d[0]; var t = cd0.t; var trace = cd0.trace; - var sel = cd0.node3 = _$d3_127.select(this); + var sel = _$d3_130.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; var numBoxes = fullLayout._numBoxes; + var groupFraction = (1 - fullLayout.boxgap); + var group = (fullLayout.boxmode === 'group' && numBoxes > 1); // box half width - var bdPos = t.dPos * (1 - fullLayout.boxgap) * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); + var bdPos = t.dPos * groupFraction * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); // box center offset - var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * (1 - fullLayout.boxgap) : 0; + var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * groupFraction : 0; // whisker width var wdPos = bdPos * trace.whiskerwidth; if(trace.visible !== true || t.empty) { - _$d3_127.select(this).remove(); + sel.remove(); return; } @@ -38714,6 +42867,9 @@ function plot(gd, plotinfo, cdbox) { t.bPos = bPos; t.bdPos = bdPos; t.wdPos = wdPos; + // half-width within which to accept hover for this box + // always split the distance to the closest box + t.wHover = t.dPos * (group ? groupFraction / numBoxes : 1); // boxes and whiskers plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, t); @@ -38752,7 +42908,7 @@ function plotBoxAndWhiskers(sel, axes, trace, t) { } sel.selectAll('path.box') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .style('vector-effect', 'non-scaling-stroke') .attr('class', 'box') @@ -38769,17 +42925,25 @@ function plotBoxAndWhiskers(sel, axes, trace, t) { var q3 = valAxis.c2p(d.q3, true); // make sure median isn't identical to either of the // quartiles, so we can see it - var m = _$lib_539.constrain( + var m = _$lib_601.constrain( valAxis.c2p(d.med, true), Math.min(q1, q3) + 1, Math.max(q1, q3) - 1 ); - var lf = valAxis.c2p(trace.boxpoints === false ? d.min : d.lf, true); - var uf = valAxis.c2p(trace.boxpoints === false ? d.max : d.uf, true); + + // for compatibility with box, violin, and candlestick + // perhaps we should put this into cd0.t instead so it's more explicit, + // but what we have now is: + // - box always has d.lf, but boxpoints can be anything + // - violin has d.lf and should always use it (boxpoints is undefined) + // - candlestick has only min/max + var useExtremes = (d.lf === undefined) || (trace.boxpoints === false); + var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true); + var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true); var ln = valAxis.c2p(d.ln, true); var un = valAxis.c2p(d.un, true); if(trace.orientation === 'h') { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + m + ',' + posm0 + 'V' + posm1 + // median line 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge @@ -38791,7 +42955,7 @@ function plotBoxAndWhiskers(sel, axes, trace, t) { ((whiskerWidth === 0) ? '' : // whisker caps 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1)); } else { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + posm0 + ',' + m + 'H' + posm1 + // median line 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge @@ -38816,7 +42980,7 @@ function plotPoints(sel, axes, trace, t) { var mode = trace.boxpoints || trace.points; // repeatable pseudo-random number generator - _$lib_539.seedPseudoRandom(); + _$lib_601.seedPseudoRandom(); sel.selectAll('g.points') // since box plot points get an extra level of nesting, each @@ -38868,13 +43032,13 @@ function plotPoints(sel, axes, trace, t) { } var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0; - jitterFactor = _$lib_539.constrain(Math.abs(jitterFactor), 0, 1); + jitterFactor = _$lib_601.constrain(Math.abs(jitterFactor), 0, 1); jitterFactors.push(jitterFactor); maxJitterFactor = Math.max(jitterFactor, maxJitterFactor); } } - newJitter = trace.jitter * 2 / maxJitterFactor; + newJitter = trace.jitter * 2 / (maxJitterFactor || 1); } // fills in 'x' and 'y' in calcdata 'pts' item @@ -38883,7 +43047,7 @@ function plotPoints(sel, axes, trace, t) { var v = pt.v; var jitterOffset = trace.jitter ? - (newJitter * jitterFactors[i] * (_$lib_539.pseudoRandom() - 0.5)) : + (newJitter * jitterFactors[i] * (_$lib_601.pseudoRandom() - 0.5)) : 0; var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset); @@ -38906,7 +43070,7 @@ function plotPoints(sel, axes, trace, t) { }) .enter().append('path') .classed('point', true) - .call(_$drawing_436.translatePoints, xa, ya); + .call(_$drawing_498.translatePoints, xa, ya); } function plotBoxMean(sel, axes, trace, t) { @@ -38927,7 +43091,7 @@ function plotBoxMean(sel, axes, trace, t) { } sel.selectAll('path.mean') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .attr('class', 'mean') .style({ @@ -38943,14 +43107,14 @@ function plotBoxMean(sel, axes, trace, t) { var sh = valAxis.c2p(d.mean + d.sd, true); if(trace.orientation === 'h') { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + m + ',' + pos0 + 'V' + pos1 + (trace.boxmean === 'sd' ? 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : '') ); } else { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + pos0 + ',' + m + 'H' + pos1 + (trace.boxmean === 'sd' ? 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : @@ -38960,7 +43124,7 @@ function plotBoxMean(sel, axes, trace, t) { }); } -var _$plot_698 = { +var _$plot_761 = { plot: plot, plotBoxAndWhiskers: plotBoxAndWhiskers, plotPoints: plotPoints, @@ -38977,7 +43141,7 @@ var _$plot_698 = { 'use strict'; -var _$selectPoints_699 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_762 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -39025,8 +43189,8 @@ var _$selectPoints_699 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; var orientations = ['v', 'h']; @@ -39042,21 +43206,23 @@ function setPositions(gd, plotinfo) { var minPad = 0; var maxPad = 0; - // make list of boxes + // make list of boxes / candlesticks + // For backward compatibility, candlesticks are treated as if they *are* box traces here for(var j = 0; j < calcdata.length; j++) { var cd = calcdata[j]; var t = cd[0].t; var trace = cd[0].trace; - if(trace.visible === true && trace.type === 'box' && + if(trace.visible === true && + (trace.type === 'box' || trace.type === 'candlestick') && !t.empty && - trace.orientation === orientation && + (trace.orientation || 'v') === orientation && trace.xaxis === xa._id && trace.yaxis === ya._id ) { boxList.push(j); - if(trace.boxpoints !== false) { + if(trace.boxpoints) { minPad = Math.max(minPad, trace.jitter - trace.pointpos - 1); maxPad = Math.max(maxPad, trace.jitter + trace.pointpos - 1); } @@ -39089,7 +43255,7 @@ function setPositionOffset(traceType, gd, boxList, posAxis, pad) { // box plots - update dPos based on multiple traces // and then use for posAxis autorange - var boxdv = _$lib_539.distinctVals(pointList); + var boxdv = _$lib_601.distinctVals(pointList); var dPos = boxdv.minDiff / 2; // if there's no duplication of x points, @@ -39099,7 +43265,7 @@ function setPositionOffset(traceType, gd, boxList, posAxis, pad) { } // check for forced minimum dtick - _$axes_584.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); + _$axes_647.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); // set the width of all boxes for(i = 0; i < boxList.length; i++) { @@ -39114,13 +43280,13 @@ function setPositionOffset(traceType, gd, boxList, posAxis, pad) { // autoscale the x axis - including space for points if they're off the side // TODO: this will overdo it if the outermost boxes don't have // their points as far out as the other boxes - _$axes_584.expand(posAxis, boxdv.vals, { + _$axes_647.expand(posAxis, boxdv.vals, { vpadminus: dPos + pad[0] * padfactor, vpadplus: dPos + pad[1] * padfactor }); } -var _$set_positions_700 = { +var _$set_positions_763 = { setPositions: setPositions, setPositionOffset: setPositionOffset }; @@ -39135,35 +43301,50 @@ var _$set_positions_700 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -var _$style_701 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.boxes'); +var _$style_764 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.trace.boxes'); s.style('opacity', function(d) { return d[0].trace.opacity; }); s.each(function(d) { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var trace = d[0].trace; var lineWidth = trace.line.width; - el.selectAll('path.box') - .style('stroke-width', lineWidth + 'px') - .call(_$color_411.stroke, trace.line.color) - .call(_$color_411.fill, trace.fillcolor); + function styleBox(boxSel, lineWidth, lineColor, fillColor) { + boxSel.style('stroke-width', lineWidth + 'px') + .call(_$color_473.stroke, lineColor) + .call(_$color_473.fill, fillColor); + } - el.selectAll('path.mean') - .style({ - 'stroke-width': lineWidth, - 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' - }) - .call(_$color_411.stroke, trace.line.color); + var allBoxes = el.selectAll('path.box'); + + if(trace.type === 'candlestick') { + allBoxes.each(function(boxData) { + var thisBox = _$d3_130.select(this); + var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing' + styleBox(thisBox, container.line.width, container.line.color, container.fillcolor); + // TODO: custom selection style for candlesticks + thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1); + }); + } + else { + styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor); + el.selectAll('path.mean') + .style({ + 'stroke-width': lineWidth, + 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' + }) + .call(_$color_473.stroke, trace.line.color); - var pts = el.selectAll('path.point'); - _$drawing_436.pointStyle(pts, trace, gd); - _$drawing_436.selectedPointStyle(pts, trace); + var pts = el.selectAll('path.point'); + _$drawing_498.pointStyle(pts, trace, gd); + _$drawing_498.selectedPointStyle(pts, trace); + } }); }; @@ -39179,21 +43360,21 @@ var _$style_701 = function style(gd, cd) { var Box = {}; -Box.attributes = _$attributes_691; -Box.layoutAttributes = _$layout_attributes_696; -Box.supplyDefaults = _$defaults_693.supplyDefaults; -Box.supplyLayoutDefaults = _$layout_defaults_697.supplyLayoutDefaults; -Box.calc = _$calc_692; -Box.setPositions = _$set_positions_700.setPositions; -Box.plot = _$plot_698.plot; -Box.style = _$style_701; -Box.hoverPoints = _$hover_694.hoverPoints; -Box.selectPoints = _$selectPoints_699; +Box.attributes = _$attributes_754; +Box.layoutAttributes = _$layout_attributes_759; +Box.supplyDefaults = _$defaults_756.supplyDefaults; +Box.supplyLayoutDefaults = _$layout_defaults_760.supplyLayoutDefaults; +Box.calc = _$calc_755; +Box.setPositions = _$set_positions_763.setPositions; +Box.plot = _$plot_761.plot; +Box.style = _$style_764; +Box.hoverPoints = _$hover_757.hoverPoints; +Box.selectPoints = _$selectPoints_762; Box.moduleType = 'trace'; Box.name = 'box'; -Box.basePlotModule = _$cartesian_595; -Box.categories = ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend']; +Box.basePlotModule = _$cartesian_658; +Box.categories = ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'draggedPts', 'boxLayout']; Box.meta = { description: [ 'In vertical (horizontal) box plots,', @@ -39211,7 +43392,7 @@ Box.meta = { ].join(' ') }; -var _$Box_695 = Box; +var _$Box_758 = Box; /** * Copyright 2012-2018, Plotly, Inc. @@ -39223,7 +43404,7 @@ var _$Box_695 = Box; 'use strict'; -var _$box_5 = _$Box_695; +var _$box_5 = _$Box_758; /* object-assign @@ -39289,7 +43470,7 @@ function shouldUseNative() { } } -var _$objectAssign_281 = shouldUseNative() ? Object.assign : function (target, source) { +var _$objectAssign_339 = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; @@ -39316,7 +43497,7 @@ var _$objectAssign_281 = shouldUseNative() ? Object.assign : function (target, s return to; }; -var _$main_388 = {}; +var _$main_450 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -39334,7 +43515,7 @@ var _$main_388 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; function Calendars() { @@ -39355,7 +43536,7 @@ function Calendars() {

Provides support for various world calendars in a consistent manner.

@class Calendars @example _exports.instance('julian').newDate(2014, 12, 25) */ -_$objectAssign_281(Calendars.prototype, { +_$objectAssign_339(Calendars.prototype, { /** Obtain a calendar implementation and localisation. @memberof Calendars @@ -39458,7 +43639,7 @@ function pad(value, length) { return '000000'.substring(0, length - value.length) + value; } -_$objectAssign_281(CDate.prototype, { +_$objectAssign_339(CDate.prototype, { /** Create a new date. @memberof CDate @@ -39684,7 +43865,7 @@ function BaseCalendar() { this.shortYearCutoff = '+10'; } -_$objectAssign_281(BaseCalendar.prototype, { +_$objectAssign_339(BaseCalendar.prototype, { _validateLevel: 0, // "Stack" to turn validation on/off /** Create a new date within this calendar - today if no parameters given. @@ -40026,7 +44207,7 @@ function GregorianCalendar(language) { GregorianCalendar.prototype = new BaseCalendar; -_$objectAssign_281(GregorianCalendar.prototype, { +_$objectAssign_339(GregorianCalendar.prototype, { /** The calendar name. @memberof GregorianCalendar */ name: 'Gregorian', @@ -40209,7 +44390,7 @@ _$objectAssign_281(GregorianCalendar.prototype, { }); // Singleton manager -var _exports = _$main_388 = new Calendars(); +var _exports = _$main_450 = new Calendars(); // Date template _exports.cdate = CDate; @@ -40221,7 +44402,7 @@ _exports.baseCalendar = BaseCalendar; _exports.calendars.gregorian = GregorianCalendar; -var _$chinese_374 = {}; +var _$chinese_436 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -40239,11 +44420,11 @@ var _$chinese_374 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; -var gregorianCalendar = _$main_388.instance(); +var gregorianCalendar = _$main_450.instance(); /** Implementation of the traditional Chinese calendar. Source of calendar tables https://github.com/isee15/Lunar-Solar-Calendar-Converter . @@ -40253,9 +44434,9 @@ function ChineseCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -ChineseCalendar.prototype = new _$main_388.baseCalendar; +ChineseCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(ChineseCalendar.prototype, { +_$objectAssign_339(ChineseCalendar.prototype, { /** The calendar name. @memberof ChineseCalendar */ name: 'Chinese', @@ -40425,7 +44606,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { var invalidIntercalaryMonth = (isIntercalary && month !== intercalaryMonth); if (invalidIntercalaryMonth || month < 1 || month > 12) { - throw _$main_388.local.invalidMonth + throw _$main_450.local.invalidMonth .replace(/\{0\}/, this.local.name); } @@ -40461,7 +44642,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { // validate month var maxMonthIndex = (intercalaryMonth) ? 12 : 11; if (monthIndex < 0 || monthIndex > maxMonthIndex) { - throw _$main_388.local.invalidMonth + throw _$main_450.local.invalidMonth .replace(/\{0\}/, this.local.name); } @@ -40529,7 +44710,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { weekOfYear: function(year, monthIndex, day) { // compute Chinese new year var validatedYear = - this._validateYear(year, _$main_388.local.invalidyear); + this._validateYear(year, _$main_450.local.invalidyear); var packedDate = CHINESE_NEW_YEAR[validatedYear - CHINESE_NEW_YEAR[0]]; @@ -40576,7 +44757,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { var intercalaryMonth = monthDaysTable >> 13; var maxMonthIndex = (intercalaryMonth) ? 12 : 11; if (monthIndex > maxMonthIndex) { - throw _$main_388.local.invalidMonth + throw _$main_450.local.invalidMonth .replace(/\{0\}/, this.local.name); } @@ -40606,7 +44787,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, monthIndex, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = this._validateYear(date.year()); monthIndex = date.month(); day = date.day(); @@ -40698,7 +44879,7 @@ var MONTH_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?月/m; var MONTH_SHORT_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?/m; // Chinese calendar implementation -_$main_388.calendars.chinese = ChineseCalendar; +_$main_450.calendars.chinese = ChineseCalendar; // Chinese calendar tables from year 1888 to 2111 // @@ -40954,7 +45135,7 @@ function toSolar(yearOrDate, monthOrResult, day, isIntercalaryOrResult, result) } -var _$coptic_375 = {}; +var _$coptic_437 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -40972,8 +45153,8 @@ var _$coptic_375 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Coptic calendar. @@ -40986,9 +45167,9 @@ function CopticCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -CopticCalendar.prototype = new _$main_388.baseCalendar; +CopticCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(CopticCalendar.prototype, { +_$objectAssign_339(CopticCalendar.prototype, { /** The calendar name. @memberof CopticCalendar */ name: 'Coptic', @@ -41050,7 +45231,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero return year % 4 === 3 || year % 4 === -1; }, @@ -41062,7 +45243,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ monthsInYear: function(year) { this._validate(year, this.minMonth, this.minDay, - _$main_388.local.invalidYear || _$main_388.regionalOptions[''].invalidYear); + _$main_450.local.invalidYear || _$main_450.regionalOptions[''].invalidYear); return 13; }, @@ -41087,7 +45268,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0); }, @@ -41112,7 +45293,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); if (year < 0) { year++; } // No year zero return date.day() + (date.month() - 1) * 30 + @@ -41135,10 +45316,10 @@ _$objectAssign_281(CopticCalendar.prototype, { }); // Coptic calendar implementation -_$main_388.calendars.coptic = CopticCalendar; +_$main_450.calendars.coptic = CopticCalendar; -var _$discworld_376 = {}; +var _$discworld_438 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41156,8 +45337,8 @@ var _$discworld_376 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Discworld calendar - Unseen University version. @@ -41169,9 +45350,9 @@ function DiscworldCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -DiscworldCalendar.prototype = new _$main_388.baseCalendar; +DiscworldCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(DiscworldCalendar.prototype, { +_$objectAssign_339(DiscworldCalendar.prototype, { /** The calendar name. @memberof DiscworldCalendar */ name: 'Discworld', @@ -41232,7 +45413,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return false; }, @@ -41242,7 +45423,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 13; }, @@ -41252,7 +45433,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function(year) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 400; }, @@ -41277,7 +45458,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1]; }, @@ -41296,7 +45477,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return (date.day() + 1) % 8; }, @@ -41320,7 +45501,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return {century: centuries[Math.floor((date.year() - 1) / 100) + 1] || ''}; }, @@ -41333,7 +45514,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year() + (date.year() < 0 ? 1 : 0); month = date.month(); day = date.day(); @@ -41363,10 +45544,10 @@ var centuries = { }; // Discworld calendar implementation -_$main_388.calendars.discworld = DiscworldCalendar; +_$main_450.calendars.discworld = DiscworldCalendar; -var _$ethiopian_377 = {}; +var _$ethiopian_439 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41384,8 +45565,8 @@ var _$ethiopian_377 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Ethiopian calendar. @@ -41398,9 +45579,9 @@ function EthiopianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -EthiopianCalendar.prototype = new _$main_388.baseCalendar; +EthiopianCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(EthiopianCalendar.prototype, { +_$objectAssign_339(EthiopianCalendar.prototype, { /** The calendar name. @memberof EthiopianCalendar */ name: 'Ethiopian', @@ -41462,7 +45643,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero return year % 4 === 3 || year % 4 === -1; }, @@ -41474,7 +45655,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ monthsInYear: function(year) { this._validate(year, this.minMonth, this.minDay, - _$main_388.local.invalidYear || _$main_388.regionalOptions[''].invalidYear); + _$main_450.local.invalidYear || _$main_450.regionalOptions[''].invalidYear); return 13; }, @@ -41499,7 +45680,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0); }, @@ -41524,7 +45705,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); if (year < 0) { year++; } // No year zero return date.day() + (date.month() - 1) * 30 + @@ -41547,10 +45728,10 @@ _$objectAssign_281(EthiopianCalendar.prototype, { }); // Ethiopian calendar implementation -_$main_388.calendars.ethiopian = EthiopianCalendar; +_$main_450.calendars.ethiopian = EthiopianCalendar; -var _$hebrew_378 = {}; +var _$hebrew_440 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41568,8 +45749,8 @@ var _$hebrew_378 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Hebrew civil calendar. @@ -41581,9 +45762,9 @@ function HebrewCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -HebrewCalendar.prototype = new _$main_388.baseCalendar; +HebrewCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(HebrewCalendar.prototype, { +_$objectAssign_339(HebrewCalendar.prototype, { /** The calendar name. @memberof HebrewCalendar */ name: 'Hebrew', @@ -41644,7 +45825,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return this._leapYear(date.year()); }, @@ -41656,7 +45837,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ _leapYear: function(year) { year = (year < 0 ? year + 1 : year); - return __mod_378(year * 7 + 1, 19) < 7; + return __mod_440(year * 7 + 1, 19) < 7; }, /** Retrieve the number of months in a year. @@ -41665,7 +45846,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return this._leapYear(year.year ? year.year() : year) ? 13 : 12; }, @@ -41689,7 +45870,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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, _$main_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); year = date.year(); return this.toJD((year === -1 ? +1 : year + 1), 7, 1) - this.toJD(year, 7, 1); }, @@ -41705,10 +45886,10 @@ _$objectAssign_281(HebrewCalendar.prototype, { month = year.month(); year = year.year(); } - this._validate(year, month, this.minDay, _$main_388.local.invalidMonth); + this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return (month === 12 && this.leapYear(year) ? 30 : // Adar I - (month === 8 && __mod_378(this.daysInYear(year), 10) === 5 ? 30 : // Cheshvan in shlemah year - (month === 9 && __mod_378(this.daysInYear(year), 10) === 3 ? 29 : // Kislev in chaserah year + (month === 8 && __mod_440(this.daysInYear(year), 10) === 5 ? 30 : // Cheshvan in shlemah year + (month === 9 && __mod_440(this.daysInYear(year), 10) === 3 ? 29 : // Kislev in chaserah year this.daysPerMonth[month - 1]))); }, @@ -41731,7 +45912,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return {yearType: (this.leapYear(date) ? 'embolismic' : 'common') + ' ' + ['deficient', 'regular', 'complete'][this.daysInYear(date) % 10 - 3]}; }, @@ -41745,7 +45926,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); @@ -41778,7 +45959,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { var months = Math.floor((235 * year - 234) / 19); var parts = 12084 + 13753 * months; var day = months * 29 + Math.floor(parts / 25920); - if (__mod_378(3 * (day + 1), 7) < 3) { + if (__mod_440(3 * (day + 1), 7) < 3) { day++; } return day; @@ -41816,15 +45997,15 @@ _$objectAssign_281(HebrewCalendar.prototype, { }); // Modulus function which works for non-integers. -function __mod_378(a, b) { +function __mod_440(a, b) { return a - (b * Math.floor(a / b)); } // Hebrew calendar implementation -_$main_388.calendars.hebrew = HebrewCalendar; +_$main_450.calendars.hebrew = HebrewCalendar; -var _$islamic_379 = {}; +var _$islamic_441 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41842,8 +46023,8 @@ var _$islamic_379 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Islamic or '16 civil' calendar. @@ -41855,9 +46036,9 @@ function IslamicCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -IslamicCalendar.prototype = new _$main_388.baseCalendar; +IslamicCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(IslamicCalendar.prototype, { +_$objectAssign_339(IslamicCalendar.prototype, { /** The calendar name. @memberof IslamicCalendar */ name: 'Islamic', @@ -41919,7 +46100,7 @@ _$objectAssign_281(IslamicCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return (date.year() * 11 + 14) % 30 < 11; }, @@ -41953,7 +46134,7 @@ _$objectAssign_281(IslamicCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, @@ -41978,7 +46159,7 @@ _$objectAssign_281(IslamicCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); @@ -42002,10 +46183,10 @@ _$objectAssign_281(IslamicCalendar.prototype, { }); // Islamic (16 civil) calendar implementation -_$main_388.calendars.islamic = IslamicCalendar; +_$main_450.calendars.islamic = IslamicCalendar; -var _$julian_380 = {}; +var _$julian_442 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42023,8 +46204,8 @@ var _$julian_380 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Julian calendar. @@ -42037,9 +46218,9 @@ function JulianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -JulianCalendar.prototype = new _$main_388.baseCalendar; +JulianCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(JulianCalendar.prototype, { +_$objectAssign_339(JulianCalendar.prototype, { /** The calendar name. @memberof JulianCalendar */ name: 'Julian', @@ -42100,7 +46281,7 @@ _$objectAssign_281(JulianCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = (date.year() < 0 ? date.year() + 1 : date.year()); // No year zero return (year % 4) === 0; }, @@ -42126,7 +46307,7 @@ _$objectAssign_281(JulianCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, @@ -42151,7 +46332,7 @@ _$objectAssign_281(JulianCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); @@ -42185,10 +46366,10 @@ _$objectAssign_281(JulianCalendar.prototype, { }); // Julian calendar implementation -_$main_388.calendars.julian = JulianCalendar; +_$main_450.calendars.julian = JulianCalendar; -var _$mayan_381 = {}; +var _$mayan_443 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42206,8 +46387,8 @@ var _$mayan_381 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Mayan Long Count calendar. @@ -42218,9 +46399,9 @@ function MayanCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -MayanCalendar.prototype = new _$main_388.baseCalendar; +MayanCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(MayanCalendar.prototype, { +_$objectAssign_339(MayanCalendar.prototype, { /** The calendar name. @memberof MayanCalendar */ name: 'Mayan', @@ -42288,7 +46469,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return false; }, @@ -42298,7 +46479,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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, _$main_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; @@ -42334,7 +46515,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 18; }, @@ -42346,7 +46527,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { - this._validate(year, month, day, _$main_388.local.invalidDate); + this._validate(year, month, day, _$main_450.local.invalidDate); return 0; }, @@ -42356,7 +46537,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function(year) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 360; }, @@ -42367,7 +46548,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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) { - this._validate(year, month, this.minDay, _$main_388.local.invalidMonth); + this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return 20; }, @@ -42386,7 +46567,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return date.day(); }, @@ -42398,7 +46579,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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) { - this._validate(year, month, day, _$main_388.local.invalidDate); + this._validate(year, month, day, _$main_450.local.invalidDate); return true; }, @@ -42410,7 +46591,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); @@ -42427,8 +46608,8 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {number[]} Corresponding Haab month and day. */ _toHaab: function(jd) { jd -= this.jdEpoch; - var day = __mod_381(jd + 8 + ((18 - 1) * 20), 365); - return [Math.floor(day / 20) + 1, __mod_381(day, 20)]; + var day = __mod_443(jd + 8 + ((18 - 1) * 20), 365); + return [Math.floor(day / 20) + 1, __mod_443(day, 20)]; }, /** Retrieve Tzolkin date from a Julian date. @@ -42450,7 +46631,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return date.day() + (date.month() * 20) + (date.year() * 360) + this.jdEpoch; }, @@ -42470,20 +46651,20 @@ _$objectAssign_281(MayanCalendar.prototype, { }); // Modulus function which works for non-integers. -function __mod_381(a, b) { +function __mod_443(a, b) { return a - (b * Math.floor(a / b)); } // Modulus function which returns numerator if modulus is zero. function amod(a, b) { - return __mod_381(a - 1, b) + 1; + return __mod_443(a - 1, b) + 1; } // Mayan calendar implementation -_$main_388.calendars.mayan = MayanCalendar; +_$main_450.calendars.mayan = MayanCalendar; -var _$nanakshahi_382 = {}; +var _$nanakshahi_444 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42501,8 +46682,8 @@ var _$nanakshahi_382 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Nanakshahi calendar. @@ -42513,11 +46694,11 @@ function NanakshahiCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -NanakshahiCalendar.prototype = new _$main_388.baseCalendar; +NanakshahiCalendar.prototype = new _$main_450.baseCalendar; -var gregorian = _$main_388.instance('gregorian'); +var gregorian = _$main_450.instance('gregorian'); -_$objectAssign_281(NanakshahiCalendar.prototype, { +_$objectAssign_339(NanakshahiCalendar.prototype, { /** The calendar name. @memberof NanakshahiCalendar */ name: 'Nanakshahi', @@ -42579,7 +46760,7 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, - _$main_388.local.invalidYear || _$main_388.regionalOptions[''].invalidYear); + _$main_450.local.invalidYear || _$main_450.regionalOptions[''].invalidYear); return gregorian.leapYear(date.year() + (date.year() < 1 ? 1 : 0) + 1469); }, @@ -42604,7 +46785,7 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, @@ -42629,7 +46810,7 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, day, _$main_450.local.invalidMonth); var year = date.year(); if (year < 0) { year++; } // No year zero var doy = date.day(); @@ -42660,10 +46841,10 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { }); // Nanakshahi calendar implementation -_$main_388.calendars.nanakshahi = NanakshahiCalendar; +_$main_450.calendars.nanakshahi = NanakshahiCalendar; -var _$nepali_383 = {}; +var _$nepali_445 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42681,8 +46862,8 @@ var _$nepali_383 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Nepali civil calendar. @@ -42697,9 +46878,9 @@ function NepaliCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -NepaliCalendar.prototype = new _$main_388.baseCalendar; +NepaliCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(NepaliCalendar.prototype, { +_$objectAssign_339(NepaliCalendar.prototype, { /** The calendar name. @memberof NepaliCalendar */ name: 'Nepali', @@ -42786,7 +46967,7 @@ _$objectAssign_281(NepaliCalendar.prototype, { @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, _$main_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); year = date.year(); if (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined') { return this.daysPerYear; @@ -42809,7 +46990,7 @@ _$objectAssign_281(NepaliCalendar.prototype, { month = year.month(); year = year.year(); } - this._validate(year, month, this.minDay, _$main_388.local.invalidMonth); + this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined' ? this.daysPerMonth[month - 1] : this.NEPALI_CALENDAR_DATA[year][month]); }, @@ -42834,11 +47015,11 @@ _$objectAssign_281(NepaliCalendar.prototype, { @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(nepaliYear, nepaliMonth, nepaliDay) { - var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, _$main_388.local.invalidDate); + var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, _$main_450.local.invalidDate); nepaliYear = date.year(); nepaliMonth = date.month(); nepaliDay = date.day(); - var gregorianCalendar = _$main_388.instance(); + var gregorianCalendar = _$main_450.instance(); var gregorianDayOfYear = 0; // We will add all the days that went by since // the 1st. January and then we can get the Gregorian Date var nepaliMonthToCheck = nepaliMonth; @@ -42887,7 +47068,7 @@ _$objectAssign_281(NepaliCalendar.prototype, { @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { - var gregorianCalendar = _$main_388.instance(); + var gregorianCalendar = _$main_450.instance(); var gregorianDate = gregorianCalendar.fromJD(jd); var gregorianYear = gregorianDate.year(); var gregorianDayOfYear = gregorianDate.dayOfYear(); @@ -43083,10 +47264,10 @@ _$objectAssign_281(NepaliCalendar.prototype, { }); // Nepali calendar implementation -_$main_388.calendars.nepali = NepaliCalendar; +_$main_450.calendars.nepali = NepaliCalendar; -var _$persian_384 = {}; +var _$persian_446 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -43104,8 +47285,8 @@ var _$persian_384 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Persian or Jalali calendar. @@ -43117,9 +47298,9 @@ function PersianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -PersianCalendar.prototype = new _$main_388.baseCalendar; +PersianCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(PersianCalendar.prototype, { +_$objectAssign_339(PersianCalendar.prototype, { /** The calendar name. @memberof PersianCalendar */ name: 'Persian', @@ -43180,7 +47361,7 @@ _$objectAssign_281(PersianCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return (((((date.year() - (date.year() > 0 ? 474 : 473)) % 2820) + 474 + 38) * 682) % 2816) < 682; }, @@ -43206,7 +47387,7 @@ _$objectAssign_281(PersianCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, @@ -43231,12 +47412,12 @@ _$objectAssign_281(PersianCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); var epBase = year - (year >= 0 ? 474 : 473); - var epYear = 474 + __mod_384(epBase, 2820); + var epYear = 474 + __mod_446(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; @@ -43250,11 +47431,11 @@ _$objectAssign_281(PersianCalendar.prototype, { jd = Math.floor(jd) + 0.5; var depoch = jd - this.toJD(475, 1, 1); var cycle = Math.floor(depoch / 1029983); - var cyear = __mod_384(depoch, 1029983); + var cyear = __mod_446(depoch, 1029983); var ycycle = 2820; if (cyear !== 1029982) { var aux1 = Math.floor(cyear / 366); - var aux2 = __mod_384(cyear, 366); + var aux2 = __mod_446(cyear, 366); ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1; } var year = ycycle + (2820 * cycle) + 474; @@ -43267,16 +47448,16 @@ _$objectAssign_281(PersianCalendar.prototype, { }); // Modulus function which works for non-integers. -function __mod_384(a, b) { +function __mod_446(a, b) { return a - (b * Math.floor(a / b)); } // Persian (Jalali) calendar implementation -_$main_388.calendars.persian = PersianCalendar; -_$main_388.calendars.jalali = PersianCalendar; +_$main_450.calendars.persian = PersianCalendar; +_$main_450.calendars.jalali = PersianCalendar; -var _$taiwan_385 = {}; +var _$taiwan_447 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -43294,11 +47475,11 @@ var _$taiwan_385 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; -var __gregorianCalendar_385 = _$main_388.instance(); +var __gregorianCalendar_447 = _$main_450.instance(); /** Implementation of the Taiwanese calendar. See http://en.wikipedia.org/wiki/Minguo_calendar. @@ -43308,9 +47489,9 @@ function TaiwanCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -TaiwanCalendar.prototype = new _$main_388.baseCalendar; +TaiwanCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(TaiwanCalendar.prototype, { +_$objectAssign_339(TaiwanCalendar.prototype, { /** The calendar name. @memberof TaiwanCalendar */ name: 'Taiwan', @@ -43374,9 +47555,9 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_385.leapYear(year); + return __gregorianCalendar_447.leapYear(year); }, /** Determine the week of the year for a date - ISO 8601. @@ -43387,9 +47568,9 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_385.weekOfYear(year, date.month(), date.day()); + return __gregorianCalendar_447.weekOfYear(year, date.month(), date.day()); }, /** Retrieve the number of days in a month. @@ -43399,7 +47580,7 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, @@ -43424,9 +47605,9 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); var year = this._t2gYear(date.year()); - return __gregorianCalendar_385.toJD(year, date.month(), date.day()); + return __gregorianCalendar_447.toJD(year, date.month(), date.day()); }, /** Create a new date from a Julian date. @@ -43434,7 +47615,7 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { - var date = __gregorianCalendar_385.fromJD(jd); + var date = __gregorianCalendar_447.fromJD(jd); var year = this._g2tYear(date.year()); return this.newDate(year, date.month(), date.day()); }, @@ -43459,10 +47640,10 @@ _$objectAssign_281(TaiwanCalendar.prototype, { }); // Taiwan calendar implementation -_$main_388.calendars.taiwan = TaiwanCalendar; +_$main_450.calendars.taiwan = TaiwanCalendar; -var _$thai_386 = {}; +var _$thai_448 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -43480,11 +47661,11 @@ var _$thai_386 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; -var __gregorianCalendar_386 = _$main_388.instance(); +var __gregorianCalendar_448 = _$main_450.instance(); /** Implementation of the Thai calendar. See http://en.wikipedia.org/wiki/Thai_calendar. @@ -43494,9 +47675,9 @@ function ThaiCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -ThaiCalendar.prototype = new _$main_388.baseCalendar; +ThaiCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(ThaiCalendar.prototype, { +_$objectAssign_339(ThaiCalendar.prototype, { /** The calendar name. @memberof ThaiCalendar */ name: 'Thai', @@ -43560,9 +47741,9 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_386.leapYear(year); + return __gregorianCalendar_448.leapYear(year); }, /** Determine the week of the year for a date - ISO 8601. @@ -43573,9 +47754,9 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_386.weekOfYear(year, date.month(), date.day()); + return __gregorianCalendar_448.weekOfYear(year, date.month(), date.day()); }, /** Retrieve the number of days in a month. @@ -43585,7 +47766,7 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, @@ -43610,9 +47791,9 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); var year = this._t2gYear(date.year()); - return __gregorianCalendar_386.toJD(year, date.month(), date.day()); + return __gregorianCalendar_448.toJD(year, date.month(), date.day()); }, /** Create a new date from a Julian date. @@ -43620,7 +47801,7 @@ _$objectAssign_281(ThaiCalendar.prototype, { @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { - var date = __gregorianCalendar_386.fromJD(jd); + var date = __gregorianCalendar_448.fromJD(jd); var year = this._g2tYear(date.year()); return this.newDate(year, date.month(), date.day()); }, @@ -43645,10 +47826,10 @@ _$objectAssign_281(ThaiCalendar.prototype, { }); // Thai calendar implementation -_$main_388.calendars.thai = ThaiCalendar; +_$main_450.calendars.thai = ThaiCalendar; -var _$ummalqura_387 = {}; +var _$ummalqura_449 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -43667,8 +47848,8 @@ var _$ummalqura_387 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the UmmAlQura or 'saudi' calendar. @@ -43681,9 +47862,9 @@ function UmmAlQuraCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -UmmAlQuraCalendar.prototype = new _$main_388.baseCalendar; +UmmAlQuraCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(UmmAlQuraCalendar.prototype, { +_$objectAssign_339(UmmAlQuraCalendar.prototype, { /** The calendar name. @memberof UmmAlQuraCalendar */ name: 'UmmAlQura', @@ -43739,7 +47920,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return (this.daysInYear(date.year()) === 355); }, @@ -43777,7 +47958,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.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; @@ -43810,7 +47991,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.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) @@ -43844,7 +48025,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.baseCalendar.prototype.isValid.apply(this, arguments); + var valid = _$main_450.baseCalendar.prototype.isValid.apply(this, arguments); if (valid) { year = (year.year != null ? year.year : year); valid = (year >= 1276 && year <= 1500); @@ -43861,7 +48042,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.baseCalendar.prototype._validate.apply(this, arguments); + var date = _$main_450.baseCalendar.prototype._validate.apply(this, arguments); if (date.year < 1276 || date.year > 1500) { throw error.replace(/\{0\}/, this.local.name); } @@ -43870,7 +48051,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { }); // UmmAlQura calendar implementation -_$main_388.calendars.ummalqura = UmmAlQuraCalendar; +_$main_450.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, @@ -44013,7 +48194,7 @@ var ummalqura_dat = [ 79990]; -var _$plus_389 = {}; +var _$plus_451 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -44031,11 +48212,11 @@ var _$plus_389 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$objectAssign_281 = require('object-assign'); */; -/* removed: var _$main_388 = require('./main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; +/* removed: var _$main_450 = require('./main'); */; -_$objectAssign_281(_$main_388.regionalOptions[''], { +_$objectAssign_339(_$main_450.regionalOptions[''], { invalidArguments: 'Invalid arguments', invalidFormat: 'Cannot format a date from another calendar', missingNumberAt: 'Missing number at position {0}', @@ -44043,9 +48224,9 @@ _$objectAssign_281(_$main_388.regionalOptions[''], { unexpectedLiteralAt: 'Unexpected literal at position {0}', unexpectedText: 'Additional text found at end' }); -_$main_388.local = _$main_388.regionalOptions['']; +_$main_450.local = _$main_450.regionalOptions['']; -_$objectAssign_281(_$main_388.cdate.prototype, { +_$objectAssign_339(_$main_450.cdate.prototype, { /** Format this date. Found in the jquery.calendars.plus.js module. @@ -44062,11 +48243,11 @@ _$objectAssign_281(_$main_388.cdate.prototype, { } }); -_$objectAssign_281(_$main_388.baseCalendar.prototype, { +_$objectAssign_339(_$main_450.baseCalendar.prototype, { - UNIX_EPOCH: _$main_388.instance().newDate(1970, 1, 1).toJD(), + UNIX_EPOCH: _$main_450.instance().newDate(1970, 1, 1).toJD(), SECS_PER_DAY: 24 * 60 * 60, - TICKS_EPOCH: _$main_388.instance().jdEpoch, // 1 January 0001 CE + TICKS_EPOCH: _$main_450.instance().jdEpoch, // 1 January 0001 CE TICKS_PER_DAY: 24 * 60 * 60 * 10000000, /** Date form for ATOM (RFC 3339/ISO 8601). @@ -44174,7 +48355,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { return ''; } if (date.calendar() !== this) { - throw _$main_388.local.invalidFormat || _$main_388.regionalOptions[''].invalidFormat; + throw _$main_450.local.invalidFormat || _$main_450.regionalOptions[''].invalidFormat; } format = format || this.local.dateFormat; settings = settings || {}; @@ -44299,7 +48480,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { if the value doesn't match the format, or if the date is invalid. */ parseDate: function(format, value, settings) { if (value == null) { - throw _$main_388.local.invalidArguments || _$main_388.regionalOptions[''].invalidArguments; + throw _$main_450.local.invalidArguments || _$main_450.regionalOptions[''].invalidArguments; } value = (typeof value === 'object' ? value.toString() : value + ''); if (value === '') { @@ -44339,7 +48520,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { var digits = new RegExp('^-?\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) { - throw (_$main_388.local.missingNumberAt || _$main_388.regionalOptions[''].missingNumberAt). + throw (_$main_450.local.missingNumberAt || _$main_450.regionalOptions[''].missingNumberAt). replace(/\{0\}/, iValue); } iValue += num[0].length; @@ -44366,7 +48547,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { return i + calendar.minMonth; } } - throw (_$main_388.local.unknownNameAt || _$main_388.regionalOptions[''].unknownNameAt). + throw (_$main_450.local.unknownNameAt || _$main_450.regionalOptions[''].unknownNameAt). replace(/\{0\}/, iValue); }; // Extract a month number from the string value @@ -44384,8 +48565,8 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { - throw (_$main_388.local.unexpectedLiteralAt || - _$main_388.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue); + throw (_$main_450.local.unexpectedLiteralAt || + _$main_450.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue); } iValue++; }; @@ -44437,7 +48618,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { } } if (iValue < value.length) { - throw _$main_388.local.unexpectedText || _$main_388.regionalOptions[''].unexpectedText; + throw _$main_450.local.unexpectedText || _$main_450.regionalOptions[''].unexpectedText; } if (year === -1) { year = this.today().year(); @@ -44528,24 +48709,24 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { // a trimmed down version of: // https://github.com/alexcjohnson/world-calendars/blob/master/dist/index.js -var _$calendars_408 = _$main_388; +var _$calendars_470 = _$main_450; -_$plus_389; +_$plus_451; -_$chinese_374; -_$coptic_375; -_$discworld_376; -_$ethiopian_377; -_$hebrew_378; -_$islamic_379; -_$julian_380; -_$mayan_381; -_$nanakshahi_382; -_$nepali_383; -_$persian_384; -_$taiwan_385; -_$thai_386; -_$ummalqura_387; +_$chinese_436; +_$coptic_437; +_$discworld_438; +_$ethiopian_439; +_$hebrew_440; +_$islamic_441; +_$julian_442; +_$mayan_443; +_$nanakshahi_444; +_$nepali_445; +_$persian_446; +_$taiwan_447; +_$thai_448; +_$ummalqura_449; /** * Copyright 2012-2018, Plotly, Inc. @@ -44557,17 +48738,17 @@ _$ummalqura_387; 'use strict'; -/* removed: var _$calendars_408 = require('./calendars'); */; +/* removed: var _$calendars_470 = require('./calendars'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; -var __EPOCHJD_409 = _$numerical_517.EPOCHJD; -var __ONEDAY_409 = _$numerical_517.ONEDAY; +var __EPOCHJD_471 = _$numerical_578.EPOCHJD; +var __ONEDAY_471 = _$numerical_578.ONEDAY; -var __attributes_409 = { +var __attributes_471 = { valType: 'enumerated', - values: Object.keys(_$calendars_408.calendars), + values: Object.keys(_$calendars_470.calendars), role: 'info', editType: 'calc', dflt: 'gregorian' @@ -44575,9 +48756,9 @@ var __attributes_409 = { var handleDefaults = function(contIn, contOut, attr, dflt) { var attrs = {}; - attrs[attr] = __attributes_409; + attrs[attr] = __attributes_471; - return _$lib_539.coerce(contIn, contOut, attrs, attr, dflt); + return _$lib_601.coerce(contIn, contOut, attrs, attr, dflt); }; var handleTraceDefaults = function(traceIn, traceOut, coords, layout) { @@ -44675,7 +48856,7 @@ var d3ToWorldCalendars = { }; function worldCalFmt(fmt, x, calendar) { - var dateJD = Math.floor((x + 0.05) / __ONEDAY_409) + __EPOCHJD_409, + var dateJD = Math.floor((x + 0.05) / __ONEDAY_471) + __EPOCHJD_471, cDate = getCal(calendar).fromJD(dateJD), i = 0, modifier, directive, directiveLen, directiveObj, replacementPart; @@ -44716,12 +48897,12 @@ function getCal(calendar) { var calendarObj = allCals[calendar]; if(calendarObj) return calendarObj; - calendarObj = allCals[calendar] = _$calendars_408.instance(calendar); + calendarObj = allCals[calendar] = _$calendars_470.instance(calendar); return calendarObj; } function makeAttrs(description) { - return _$lib_539.extendFlat({}, __attributes_409, { description: description }); + return _$lib_601.extendFlat({}, __attributes_471, { description: description }); } function makeTraceAttrsDescription(coord) { @@ -44732,11 +48913,11 @@ var xAttrs = { xcalendar: makeAttrs(makeTraceAttrsDescription('x')) }; -var xyAttrs = _$lib_539.extendFlat({}, xAttrs, { +var xyAttrs = _$lib_601.extendFlat({}, xAttrs, { ycalendar: makeAttrs(makeTraceAttrsDescription('y')) }); -var xyzAttrs = _$lib_539.extendFlat({}, xyAttrs, { +var xyzAttrs = _$lib_601.extendFlat({}, xyAttrs, { zcalendar: makeAttrs(makeTraceAttrsDescription('z')) }); @@ -44747,7 +48928,7 @@ var axisAttrs = makeAttrs([ 'or via the global `layout.calendar`' ].join(' ')); -var _$calendars_409 = { +var _$calendars_471 = { moduleType: 'component', name: 'calendars', @@ -44807,7 +48988,7 @@ var _$calendars_409 = { } }, - layoutAttributes: __attributes_409, + layoutAttributes: __attributes_471, handleDefaults: handleDefaults, handleTraceDefaults: handleTraceDefaults, @@ -44830,7 +49011,7 @@ var _$calendars_409 = { 'use strict'; -var _$calendars_6 = _$calendars_409; +var _$calendars_6 = _$calendars_471; /** * Copyright 2012-2018, Plotly, Inc. @@ -44843,49 +49024,28 @@ var _$calendars_6 = _$calendars_409; 'use strict'; -var __extendFlat_820 = _$lib_539.extendFlat; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -var __dash_820 = _$attributes_435.dash; +var __extendFlat_882 = _$lib_601.extendFlat; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +var __dash_882 = _$attributes_497.dash; var INCREASING_COLOR = '#3D9970'; var DECREASING_COLOR = '#FF4136'; -var lineAttrs = _$attributes_862.line; +var lineAttrs = _$attributes_927.line; function directionAttrs(lineColorDefault) { return { - name: { - valType: 'string', - role: 'info', - editType: 'style', - description: [ - 'Sets the segment name.', - 'The segment name appear as the legend item and on hover.' - ].join(' ') - }, - - showlegend: { - valType: 'boolean', - role: 'info', - dflt: true, - editType: 'style', - description: [ - 'Determines whether or not an item corresponding to this', - 'segment is shown in the legend.' - ].join(' ') - }, - line: { - color: __extendFlat_820({}, lineAttrs.color, {dflt: lineColorDefault}), + color: __extendFlat_882({}, lineAttrs.color, {dflt: lineColorDefault}), width: lineAttrs.width, - dash: __dash_820, + dash: __dash_882, editType: 'style' }, editType: 'style' }; } -var _$attributes_820 = { +var _$attributes_882 = { x: { valType: 'data_array', @@ -44898,34 +49058,30 @@ var _$attributes_820 = { open: { valType: 'data_array', - dflt: [], editType: 'calc', description: 'Sets the open values.' }, high: { valType: 'data_array', - dflt: [], editType: 'calc', description: 'Sets the high values.' }, low: { valType: 'data_array', - dflt: [], editType: 'calc', description: 'Sets the low values.' }, close: { valType: 'data_array', - dflt: [], editType: 'calc', description: 'Sets the close values.' }, line: { - width: __extendFlat_820({}, lineAttrs.width, { + width: __extendFlat_882({}, lineAttrs.width, { description: [ lineAttrs.width, 'Note that this style setting can also be set per', @@ -44933,9 +49089,9 @@ var _$attributes_820 = { '`decreasing.line.width`.' ].join(' ') }), - dash: __extendFlat_820({}, __dash_820, { + dash: __extendFlat_882({}, __dash_882, { description: [ - __dash_820.description, + __dash_882.description, 'Note that this style setting can also be set per', 'direction via `increasing.line.dash` and', '`decreasing.line.dash`.' @@ -44988,37 +49144,34 @@ var _$attributes_820 = { 'use strict'; -var __extendFlat_702 = _$lib_539.extendFlat; -/* removed: var _$attributes_820 = require('../ohlc/attributes'); */; -/* removed: var _$attributes_691 = require('../box/attributes'); */; +var __extendFlat_765 = _$lib_601.extendFlat; +/* removed: var _$attributes_882 = require('../ohlc/attributes'); */; +/* removed: var _$attributes_754 = require('../box/attributes'); */; -function __directionAttrs_702(lineColorDefault) { +function __directionAttrs_765(lineColorDefault) { return { - name: _$attributes_820.increasing.name, - showlegend: _$attributes_820.increasing.showlegend, - line: { - color: __extendFlat_702({}, _$attributes_691.line.color, {dflt: lineColorDefault}), - width: _$attributes_691.line.width, + color: __extendFlat_765({}, _$attributes_754.line.color, {dflt: lineColorDefault}), + width: _$attributes_754.line.width, editType: 'style' }, - fillcolor: _$attributes_691.fillcolor, + fillcolor: _$attributes_754.fillcolor, editType: 'style' }; } -var _$attributes_702 = { - x: _$attributes_820.x, - open: _$attributes_820.open, - high: _$attributes_820.high, - low: _$attributes_820.low, - close: _$attributes_820.close, +var _$attributes_765 = { + x: _$attributes_882.x, + open: _$attributes_882.open, + high: _$attributes_882.high, + low: _$attributes_882.low, + close: _$attributes_882.close, line: { - width: __extendFlat_702({}, _$attributes_691.line.width, { + width: __extendFlat_765({}, _$attributes_754.line.width, { description: [ - _$attributes_691.line.width.description, + _$attributes_754.line.width.description, 'Note that this style setting can also be set per', 'direction via `increasing.line.width` and', '`decreasing.line.width`.' @@ -45027,12 +49180,12 @@ var _$attributes_702 = { editType: 'style' }, - increasing: __directionAttrs_702(_$attributes_820.increasing.line.color.dflt), + increasing: __directionAttrs_765(_$attributes_882.increasing.line.color.dflt), - decreasing: __directionAttrs_702(_$attributes_820.decreasing.line.color.dflt), + decreasing: __directionAttrs_765(_$attributes_882.decreasing.line.color.dflt), - text: _$attributes_820.text, - whiskerwidth: __extendFlat_702({}, _$attributes_691.whiskerwidth, { dflt: 0 }) + text: _$attributes_882.text, + whiskerwidth: __extendFlat_765({}, _$attributes_754.whiskerwidth, { dflt: 0 }) }; /** @@ -45043,172 +49196,212 @@ var _$attributes_702 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$lib_601 = require('../../lib'); */; +var ____883 = _$lib_601._; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __BADNUM_883 = _$numerical_578.BADNUM; -var _$handleDirectionDefaults_822 = function handleDirectionDefaults(traceIn, traceOut, coerce, direction) { - coerce(direction + '.showlegend'); +function calc(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis); + var ya = _$axes_647.getFromId(gd, trace.yaxis); + + var tickLen = convertTickWidth(gd, xa, trace); + var minDiff = trace._minDiff; + trace._minDiff = null; + var x = trace._xcalc; + trace._xcalc = null; + + var cd = calcCommon(gd, trace, x, ya, ptFunc); - // trace-wide *showlegend* overrides direction *showlegend* - if(traceIn.showlegend === false) { - traceOut[direction].showlegend = false; + _$axes_647.expand(xa, x, {vpad: minDiff / 2}); + + if(cd.length) { + _$lib_601.extendFlat(cd[0].t, { + wHover: minDiff / 2, + tickLen: tickLen + }); + return cd; + } else { + return [{t: {empty: true}}]; } +} - var nameDflt = traceOut.name + ' - ' + direction; +function ptFunc(o, h, l, c) { + return { + o: o, + h: h, + l: l, + c: c + }; +} - coerce(direction + '.name', nameDflt); -}; -var _$helpers_823 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// shared between OHLC and candlestick +// ptFunc makes a calcdata point specific to each trace type, from oi, hi, li, ci +function calcCommon(gd, trace, x, ya, ptFunc) { + var o = ya.makeCalcdata(trace, 'open'); + var h = ya.makeCalcdata(trace, 'high'); + var l = ya.makeCalcdata(trace, 'low'); + var c = ya.makeCalcdata(trace, 'close'); + var hasTextArray = Array.isArray(trace.text); -'use strict'; + // we're optimists - before we have any changing data, assume increasing + var increasing = true; + var cPrev = null; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; + var cd = []; + for(var i = 0; i < x.length; i++) { + var xi = x[i]; + var oi = o[i]; + var hi = h[i]; + var li = l[i]; + var ci = c[i]; -/* removed: var _$lib_539 = require('../../lib'); */; + if(xi !== __BADNUM_883 && oi !== __BADNUM_883 && hi !== __BADNUM_883 && li !== __BADNUM_883 && ci !== __BADNUM_883) { + if(ci === oi) { + // if open == close, look for a change from the previous close + if(cPrev !== null && ci !== cPrev) increasing = ci > cPrev; + // else (c === cPrev or cPrev is null) no change + } + else increasing = ci > oi; -// This routine gets called during the trace supply-defaults step. -// -// This is a hacky way to make 'ohlc' and 'candlestick' trace types -// go through the transform machinery. -// -// Note that, we must mutate user data (here traceIn) as opposed -// to full data (here traceOut) as - at the moment - transform -// defaults (which are called after trace defaults) start -// from a clear transforms container. The mutations inflicted are -// cleared in exports.clearEphemeralTransformOpts. -_$helpers_823.pushDummyTransformOpts = function(traceIn, traceOut) { - var transformOpts = { + cPrev = ci; - // give dummy transform the same type as trace - type: traceOut.type, + var pt = ptFunc(oi, hi, li, ci); - // track ephemeral transforms in user data - _ephemeral: true - }; + pt.pos = xi; + pt.yc = (oi + ci) / 2; + pt.i = i; + pt.dir = increasing ? 'increasing' : 'decreasing'; - if(Array.isArray(traceIn.transforms)) { - traceIn.transforms.push(transformOpts); - } - else { - traceIn.transforms = [transformOpts]; - } -}; + if(hasTextArray) pt.tx = trace.text[i]; -// This routine gets called during the transform supply-defaults step -// where it clears ephemeral transform opts in user data -// and effectively put back user date in its pre-supplyDefaults state. -_$helpers_823.clearEphemeralTransformOpts = function(traceIn) { - var transformsIn = traceIn.transforms; + cd.push(pt); + } + } - if(!Array.isArray(transformsIn)) return; + _$axes_647.expand(ya, l.concat(h), {padded: true}); - for(var i = 0; i < transformsIn.length; i++) { - if(transformsIn[i]._ephemeral) transformsIn.splice(i, 1); + if(cd.length) { + cd[0].t = { + labels: { + open: ____883(gd, 'open:') + ' ', + high: ____883(gd, 'high:') + ' ', + low: ____883(gd, 'low:') + ' ', + close: ____883(gd, 'close:') + ' ' + } + }; } - if(transformsIn.length === 0) delete traceIn.transforms; -}; + return cd; +} -// This routine gets called during the transform supply-defaults step -// where it passes 'ohlc' and 'candlestick' attributes -// (found the transform container via exports.makeTransform) -// to the traceOut container such that they can -// be compatible with filter and groupby transforms. -// -// Note that this routine only has an effect during the -// second round of transform defaults done on generated traces -_$helpers_823.copyOHLC = function(container, traceOut) { - if(container.open) traceOut.open = container.open; - if(container.high) traceOut.high = container.high; - if(container.low) traceOut.low = container.low; - if(container.close) traceOut.close = container.close; -}; +/* + * find min x-coordinates difference of all traces + * attached to this x-axis and stash the result in _minDiff + * in all traces; when a trace uses this in its + * calc step it deletes _minDiff, so that next calc this is + * done again in case the data changed. + * also since we need it here, stash _xcalc on the trace + */ +function convertTickWidth(gd, xa, trace) { + var minDiff = trace._minDiff; -// This routine gets called during the applyTransform step. -// -// We need to track trace attributes and which direction -// ('increasing' or 'decreasing') -// the generated correspond to for the calcTransform step. -// -// To make sure that the attributes reach the calcTransform, -// store it in the transform opts object. -_$helpers_823.makeTransform = function(traceIn, state, direction) { - var out = _$lib_539.extendFlat([], traceIn.transforms); + if(!minDiff) { + var fullData = gd._fullData, + ohlcTracesOnThisXaxis = []; - out[state.transformIndex] = { - type: traceIn.type, - direction: direction, + minDiff = Infinity; - // these are copied to traceOut during exports.copyOHLC - open: traceIn.open, - high: traceIn.high, - low: traceIn.low, - close: traceIn.close - }; + var i; - return out; -}; + for(i = 0; i < fullData.length; i++) { + var tracei = fullData[i]; -_$helpers_823.getFilterFn = function(direction) { - return new _getFilterFn(direction); -}; + if(tracei.type === 'ohlc' && + tracei.visible === true && + tracei.xaxis === xa._id + ) { + ohlcTracesOnThisXaxis.push(tracei); -function _getFilterFn(direction) { - // we're optimists - before we have any changing data, assume increasing - var isPrevIncreasing = true; - var cPrev = null; + var xcalc = xa.makeCalcdata(tracei, 'x'); + tracei._xcalc = xcalc; - function _isIncreasing(o, c) { - if(o === c) { - if(c > cPrev) { - isPrevIncreasing = true; // increasing - } else if(c < cPrev) { - isPrevIncreasing = false; // decreasing + var _minDiff = _$lib_601.distinctVals(xcalc).minDiff; + if(_minDiff && isFinite(_minDiff)) { + minDiff = Math.min(minDiff, _minDiff); + } } - // else isPrevIncreasing is not changed } - else isPrevIncreasing = (o < c); - cPrev = c; - return isPrevIncreasing; - } - function isIncreasing(o, c) { - return _$fastIsnumeric_139(o) && _$fastIsnumeric_139(c) && _isIncreasing(+o, +c); - } + // if minDiff is still Infinity here, set it to 1 + if(minDiff === Infinity) minDiff = 1; - function isDecreasing(o, c) { - return _$fastIsnumeric_139(o) && _$fastIsnumeric_139(c) && !_isIncreasing(+o, +c); + for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) { + ohlcTracesOnThisXaxis[i]._minDiff = minDiff; + } } - return direction === 'increasing' ? isIncreasing : isDecreasing; + return minDiff * trace.tickwidth; } -_$helpers_823.addRangeSlider = function(data, layout) { - var hasOneVisibleTrace = false; +var _$calc_883 = { + calc: calc, + calcCommon: calcCommon +}; - for(var i = 0; i < data.length; i++) { - if(data[i].visible === true) { - hasOneVisibleTrace = true; - break; - } - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; - if(hasOneVisibleTrace) { - if(!layout.xaxis) layout.xaxis = {}; - if(!layout.xaxis.rangeslider) layout.xaxis.rangeslider = {}; +var __calcCommon_766 = _$calc_883.calcCommon; + +var _$calc_766 = function(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axes_647.getFromId(gd, trace.xaxis); + var ya = _$axes_647.getFromId(gd, trace.yaxis); + + var x = xa.makeCalcdata(trace, 'x'); + + var cd = __calcCommon_766(gd, trace, x, ya, __ptFunc_766); + + if(cd.length) { + _$lib_601.extendFlat(cd[0].t, { + num: fullLayout._numBoxes, + dPos: _$lib_601.distinctVals(x).minDiff / 2, + posLetter: 'x', + valLetter: 'y', + }); + + fullLayout._numBoxes++; + return cd; + } else { + return [{t: {empty: true}}]; } }; +function __ptFunc_766(o, h, l, c) { + return { + min: l, + q1: Math.min(o, c), + med: c, + q3: Math.max(o, c), + max: h, + }; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45220,32 +49413,26 @@ _$helpers_823.addRangeSlider = function(data, layout) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - +/* removed: var _$registry_731 = require('../../registry'); */; -var _$handleOHLC_825 = function handleOHLC(traceIn, traceOut, coerce, layout) { - var len; - var x = coerce('x'), - open = coerce('open'), - high = coerce('high'), - low = coerce('low'), - close = coerce('close'); +var _$handleOHLC_887 = 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'); - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x'], layout); - len = Math.min(open.length, high.length, low.length, close.length); + if(!(open && high && low && close)) return; - if(x) { - len = Math.min(len, x.length); - if(len < x.length) traceOut.x = x.slice(0, len); - } + var len = Math.min(open.length, high.length, low.length, close.length); - if(len < open.length) traceOut.open = open.slice(0, len); - if(len < high.length) traceOut.high = high.slice(0, len); - if(len < low.length) traceOut.low = low.slice(0, len); - if(len < close.length) traceOut.close = close.slice(0, len); + if(x) len = Math.min(len, x.length); + + traceOut._length = len; return len; }; @@ -45261,21 +49448,18 @@ var _$handleOHLC_825 = function handleOHLC(traceIn, traceOut, coerce, layout) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleOHLC_825 = require('../ohlc/ohlc_defaults'); */; -/* removed: var _$handleDirectionDefaults_822 = require('../ohlc/direction_defaults'); */; -/* removed: var _$helpers_823 = require('../ohlc/helpers'); */; -/* removed: var _$attributes_702 = require('./attributes'); */; - -var _$supplyDefaults_703 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - _$helpers_823.pushDummyTransformOpts(traceIn, traceOut); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$handleOHLC_887 = require('../ohlc/ohlc_defaults'); */; +/* removed: var _$attributes_765 = require('./attributes'); */; +var _$supplyDefaults_767 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_702, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_765, attr, dflt); } - var len = _$handleOHLC_825(traceIn, traceOut, coerce, layout); - if(len === 0) { + var len = _$handleOHLC_887(traceIn, traceOut, coerce, layout); + if(!len) { traceOut.visible = false; return; } @@ -45287,17 +49471,16 @@ var _$supplyDefaults_703 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('whiskerwidth'); + + layout._requestRangeslider[traceOut.xaxis] = true; }; function handleDirection(traceIn, traceOut, coerce, direction) { - _$handleDirectionDefaults_822(traceIn, traceOut, coerce, direction); - - coerce(direction + '.line.color'); + var lineColor = coerce(direction + '.line.color'); coerce(direction + '.line.width', traceOut.line.width); - coerce(direction + '.fillcolor'); + coerce(direction + '.fillcolor', _$color_473.addOpacity(lineColor, 0.5)); } -var _$transform_705 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45306,125 +49489,150 @@ var _$transform_705 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$helpers_823 = require('../ohlc/helpers'); */; - -_$transform_705.moduleType = 'transform'; - -_$transform_705.name = 'candlestick'; - -_$transform_705.attributes = {}; - -_$transform_705.supplyDefaults = function(transformIn, traceOut, layout, traceIn) { - _$helpers_823.clearEphemeralTransformOpts(traceIn); - _$helpers_823.copyOHLC(transformIn, traceOut); +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; - return transformIn; +var DIRSYMBOL = { + increasing: '▲', + decreasing: '▼' }; -_$transform_705.transform = function transform(dataIn, state) { - var dataOut = []; +var _$hoverPoints_885 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var xa = pointData.xa; + var ya = pointData.ya; + var trace = cd[0].trace; + var t = cd[0].t; - for(var i = 0; i < dataIn.length; i++) { - var traceIn = dataIn[i]; + var type = trace.type; + var minAttr = type === 'ohlc' ? 'l' : 'min'; + var maxAttr = type === 'ohlc' ? 'h' : 'max'; - if(traceIn.type !== 'candlestick') { - dataOut.push(traceIn); - continue; - } + // potentially shift xval for grouped candlesticks + var centerShift = t.bPos || 0; + var x0 = xval - centerShift; - dataOut.push( - makeTrace(traceIn, state, 'increasing'), - makeTrace(traceIn, state, 'decreasing') - ); - } + // ohlc and candlestick call displayHalfWidth different things... + var displayHalfWidth = t.bdPos || t.tickLen; + var hoverHalfWidth = t.wHover; - _$helpers_823.addRangeSlider(dataOut, state.layout); + // if two items are overlaying, let the narrowest one win + var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0]))); + var hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; + var spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; - return dataOut; -}; + function dx(di) { + var pos = di.pos - x0; + return _$fx_515.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance); + } -function makeTrace(traceIn, state, direction) { - var traceOut = { - type: 'box', - boxpoints: false, + function dy(di) { + return _$fx_515.inbox(di[minAttr] - yval, di[maxAttr] - yval, hoverPseudoDistance); + } - visible: traceIn.visible, - hoverinfo: traceIn.hoverinfo, - opacity: traceIn.opacity, - xaxis: traceIn.xaxis, - yaxis: traceIn.yaxis, + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_515.getClosest(cd, distfn, pointData); - transforms: _$helpers_823.makeTransform(traceIn, state, direction) - }; + // skip the rest (for this trace) if we didn't find a close point + if(pointData.index === false) return []; - // the rest of below may not have been coerced + // we don't make a calcdata point if we're missing any piece (x/o/h/l/c) + // so we need to fix the index here to point to the data arrays + var cdIndex = pointData.index; + var di = cd[cdIndex]; + var i = pointData.index = di.i; - var directionOpts = traceIn[direction]; + var dir = di.dir; + var container = trace[dir]; + var lc = container.line.color; - if(directionOpts) { - _$lib_539.extendFlat(traceOut, { + if(_$color_473.opacity(lc) && container.line.width) pointData.color = lc; + else pointData.color = container.fillcolor; - // to make autotype catch date axes soon!! - x: traceIn.x || [0], - xcalendar: traceIn.xcalendar, + pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true); + pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true); - // concat low and high to get correct autorange - y: [].concat(traceIn.low).concat(traceIn.high), + pointData.xLabelVal = di.pos; - whiskerwidth: traceIn.whiskerwidth, - text: traceIn.text, + pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; + pointData.xSpike = xa.c2p(di.pos, true); - name: directionOpts.name, - showlegend: directionOpts.showlegend, - line: directionOpts.line, - fillcolor: directionOpts.fillcolor - }); + function getLabelLine(attr) { + return t.labels[attr] + _$axes_647.hoverLabelText(ya, trace[attr][i]); } - return traceOut; -} + var hoverinfo = trace.hoverinfo; + var hoverParts = hoverinfo.split('+'); + var isAll = hoverinfo === 'all'; + var hasY = isAll || hoverParts.indexOf('y') !== -1; + var hasText = isAll || hoverParts.indexOf('text') !== -1; + + var textParts = hasY ? [ + getLabelLine('open'), + getLabelLine('high'), + getLabelLine('low'), + getLabelLine('close') + ' ' + DIRSYMBOL[dir] + ] : []; + if(hasText) _$fillHoverText_935(di, trace, textParts); + + // don't make .yLabelVal or .text, since we're managing hoverinfo + // put it all in .extraText + pointData.extraText = textParts.join('
'); + + // this puts the label *and the spike* at the midpoint of the box, ie + // halfway between open and close, not between high and low. + pointData.y0 = pointData.y1 = ya.c2p(di.yc, true); -_$transform_705.calcTransform = function calcTransform(gd, trace, opts) { - var direction = opts.direction, - filterFn = _$helpers_823.getFilterFn(direction); + return [pointData]; +}; - var open = trace.open, - high = trace.high, - low = trace.low, - close = trace.close; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 len = open.length, - x = [], - y = []; +'use strict'; - var appendX = trace._fullInput.x ? - function(i) { - var v = trace.x[i]; - x.push(v, v, v, v, v, v); - } : - function(i) { - x.push(i, i, i, i, i, i); - }; +var _$selectPoints_889 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + // for (potentially grouped) candlesticks + var posOffset = cd[0].t.bPos || 0; - var appendY = function(o, h, l, c) { - y.push(l, o, c, c, c, h); - }; + if(polygon === 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]; - for(var i = 0; i < len; i++) { - if(filterFn(open[i], close[i]) && _$fastIsnumeric_139(high[i]) && _$fastIsnumeric_139(low[i])) { - appendX(i); - appendY(open[i], high[i], low[i], close[i]); + if(polygon.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)])) { + selection.push({ + pointNumber: di.i, + x: xa.c2d(di.pos), + y: ya.c2d(di.yc) + }); + di.selected = 1; + } else { + di.selected = 0; + } } } - trace.x = x; - trace.y = y; + return selection; }; /** @@ -45437,13 +49645,11 @@ _$transform_705.calcTransform = function calcTransform(gd, trace, opts) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - -var _$candlestick_704 = { +var _$candlestick_768 = { moduleType: 'trace', name: 'candlestick', - basePlotModule: _$cartesian_595, - categories: ['cartesian', 'showLegend', 'candlestick'], + basePlotModule: _$cartesian_658, + categories: ['cartesian', 'svg', 'showLegend', 'candlestick', 'boxLayout'], meta: { description: [ 'The candlestick is a style of financial chart describing', @@ -45460,13 +49666,18 @@ var _$candlestick_704 = { ].join(' ') }, - attributes: _$attributes_702, - supplyDefaults: _$supplyDefaults_703, + attributes: _$attributes_765, + layoutAttributes: _$layout_attributes_759, + supplyLayoutDefaults: _$layout_defaults_760.supplyLayoutDefaults, + setPositions: _$set_positions_763.setPositions, + supplyDefaults: _$supplyDefaults_767, + calc: _$calc_766, + plot: _$plot_761.plot, + style: _$style_764, + hoverPoints: _$hoverPoints_885, + selectPoints: _$selectPoints_889 }; -_$registry_668.register(_$Box_695); -_$registry_668.register(_$transform_705); - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -45477,7 +49688,7 @@ _$registry_668.register(_$transform_705); 'use strict'; -var _$candlestick_7 = _$candlestick_704; +var _$candlestick_7 = _$candlestick_768; /** * Copyright 2012-2018, Plotly, Inc. @@ -45489,12 +49700,12 @@ var _$candlestick_7 = _$candlestick_704; 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; -var __overrideAll_710 = _$edit_types_569.overrideAll; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; +var __overrideAll_773 = _$edit_types_632.overrideAll; -var _$axis_attributes_710 = { +var _$axis_attributes_773 = { color: { valType: 'color', role: 'style', @@ -45520,7 +49731,7 @@ var _$axis_attributes_710 = { editType: 'calc', description: 'Sets the title of this axis.' }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ editType: 'calc', description: [ 'Sets this axis\' title font.' @@ -45668,7 +49879,7 @@ var _$axis_attributes_710 = { 'the high side, both, or neither side of the axis.' ].join(' ') }, - tickfont: _$font_attributes_611({ + tickfont: _$font_attributes_673({ editType: 'calc', description: 'Sets the tick font.' }), @@ -45773,7 +49984,7 @@ var _$axis_attributes_710 = { '*%H~%M~%S.%2f* would display *09~15~23.46*' ].join(' ') }, - tickformatstops: __overrideAll_710(_$layout_attributes_596.tickformatstops, 'calc', 'from-root'), + tickformatstops: __overrideAll_773(_$layout_attributes_659.tickformatstops, 'calc', 'from-root'), categoryorder: { valType: 'enumerated', values: [ @@ -45837,7 +50048,7 @@ var _$axis_attributes_710 = { }, linecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'calc', description: 'Sets the axis line color.' @@ -45892,7 +50103,7 @@ var _$axis_attributes_710 = { }, minorgridcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, role: 'style', editType: 'calc', description: 'Sets the color of the grid lines.' @@ -45988,20 +50199,20 @@ var _$axis_attributes_710 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$axis_attributes_710 = require('./axis_attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$axis_attributes_773 = require('./axis_attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; -var carpetFont = _$font_attributes_611({ +var carpetFont = _$font_attributes_673({ editType: 'calc', description: 'The default font used for axis & tick labels on this carpet' }); // TODO: inherit from global font carpetFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; carpetFont.size.dflt = 12; -carpetFont.color.dflt = _$attributes_410.defaultLine; +carpetFont.color.dflt = _$attributes_472.defaultLine; -var _$attributes_708 = { +var _$attributes_771 = { carpet: { valType: 'string', role: 'info', @@ -46092,12 +50303,12 @@ var _$attributes_708 = { 'Only used if `x` is been ommitted.' ].join(' ') }, - aaxis: _$axis_attributes_710, - baxis: _$axis_attributes_710, + aaxis: _$axis_attributes_773, + baxis: _$axis_attributes_773, font: carpetFont, color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'plot', description: [ @@ -46119,9 +50330,9 @@ var _$attributes_708 = { 'use strict'; -var __isArrayOrTypedArray_707 = _$lib_539.isArrayOrTypedArray; +var __isArrayOrTypedArray_770 = _$lib_601.isArrayOrTypedArray; -var _$array_minmax_707 = function(a) { +var _$array_minmax_770 = function(a) { return minMax(a, 0); }; @@ -46129,7 +50340,7 @@ 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_707(a) || depth >= 10) { + if(!__isArrayOrTypedArray_770(a) || depth >= 10) { return null; } @@ -46139,7 +50350,7 @@ function minMax(a, depth) { for(var i = 0; i < n; i++) { var datum = a[i]; - if(__isArrayOrTypedArray_707(datum)) { + if(__isArrayOrTypedArray_770(datum)) { var result = minMax(datum, depth + 1); if(result) { @@ -46166,7 +50377,7 @@ function minMax(a, depth) { 'use strict'; -var _$makeClipPath_713 = function makeClipPath(xctrl, yctrl, aax, bax) { +var _$makeClipPath_776 = function makeClipPath(xctrl, yctrl, aax, bax) { var i, x, y; var segments = []; @@ -46216,36 +50427,36 @@ var _$makeClipPath_713 = function makeClipPath(xctrl, yctrl, aax, bax) { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __extendFlat_714 = _$extend_528.extendFlat; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __extendFlat_777 = _$extend_590.extendFlat; -var _$calcGridlines_714 = function calcGridlines(trace, cd, axisLetter, crossAxisLetter) { +var _$calcGridlines_777 = 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 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 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 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; + var na = trace._a.length; + var nb = trace._b.length; - _$axes_584.prepTicks(axis); + _$axes_647.prepTicks(axis); // don't leave tickvals in axis looking like an attribute if(axis.tickmode === 'array') delete axis.tickvals; @@ -46439,7 +50650,7 @@ var _$calcGridlines_714 = function calcGridlines(trace, cd, axisLetter, crossAxi for(n = n1; n < n2; n++) { j = axis.arraytick0 + axis.arraydtick * n; if(j < 0 || j > data.length - 1) continue; - gridlines.push(__extendFlat_714(constructArrayGridline(j), { + gridlines.push(__extendFlat_777(constructArrayGridline(j), { color: axis.gridcolor, width: axis.gridwidth })); @@ -46460,859 +50671,153 @@ var _$calcGridlines_714 = function calcGridlines(trace, cd, axisLetter, crossAxi 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_714(constructValueGridline(v), { - color: axis.minorgridcolor, - width: axis.minorgridwidth - })); - } - } - - if(axis.startline) { - boundarylines.push(__extendFlat_714(constructArrayGridline(0), { - color: axis.startlinecolor, - width: axis.startlinewidth - })); - } - - if(axis.endline) { - boundarylines.push(__extendFlat_714(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_714(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_714(constructValueGridline(v), { - color: axis.minorgridcolor, - width: axis.minorgridwidth - })); - } - } - - if(axis.startline) { - boundarylines.push(__extendFlat_714(constructValueGridline(data[0]), { - color: axis.startlinecolor, - width: axis.startlinewidth - })); - } - - if(axis.endline) { - boundarylines.push(__extendFlat_714(constructValueGridline(data[data.length - 1]), { - color: axis.endlinecolor, - width: axis.endlinewidth - })); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __extendFlat_715 = _$extend_528.extendFlat; - -var _$calcLabels_715 = function calcLabels(trace, axis) { - var i, tobj, prefix, suffix, gridline; - - var labels = axis._labels = []; - var gridlines = axis._gridlines; - - for(i = 0; i < gridlines.length; i++) { - gridline = gridlines[i]; - - if(['start', 'both'].indexOf(axis.showticklabels) !== -1) { - tobj = _$axes_584.tickText(axis, gridline.value); - - __extendFlat_715(tobj, { - prefix: prefix, - suffix: suffix, - endAnchor: true, - xy: gridline.xy(0), - dxy: gridline.dxy(0, 0), - axis: gridline.axis, - length: gridline.crossAxis.length, - font: gridline.axis.tickfont, - isFirst: i === 0, - isLast: i === gridlines.length - 1 - }); - - labels.push(tobj); - } - - if(['end', 'both'].indexOf(axis.showticklabels) !== -1) { - tobj = _$axes_584.tickText(axis, gridline.value); - - __extendFlat_715(tobj, { - endAnchor: false, - xy: gridline.xy(gridline.crossLength - 1), - dxy: gridline.dxy(gridline.crossLength - 2, 1), - axis: gridline.axis, - length: gridline.crossAxis.length, - font: gridline.axis.tickfont, - isFirst: i === 0, - isLast: i === gridlines.length - 1 - }); - - labels.push(tobj); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_717 = _$lib_539.isArrayOrTypedArray; - -/* - * Construct a 2D array of cheater values given a, b, and a slope. - * If - */ -var _$cheater_basis_717 = function(a, b, cheaterslope) { - var i, j, ascal, bscal, aval, bval; - var data = []; - - var na = __isArrayOrTypedArray_717(a) ? a.length : a; - var nb = __isArrayOrTypedArray_717(b) ? b.length : b; - var adata = __isArrayOrTypedArray_717(a) ? a : null; - var bdata = __isArrayOrTypedArray_717(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; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_729 = _$lib_539.isArrayOrTypedArray; - -/* - * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p). - * The output array is optional, but if provided, it will be reused without - * reallocation to the extent possible. - */ -var _$mapArray_729 = function mapArray(out, data, func) { - var i, j; - - if(!Array.isArray(out)) { - // If not an array, make it an array: - out = []; - } else if(out.length > data.length) { - // If too long, truncate. (If too short, it will grow - // automatically so we don't care about that case) - out = out.slice(0, data.length); - } - - for(i = 0; i < data.length; i++) { - if(!__isArrayOrTypedArray_729(out[i])) { - // If not an array, make it an array: - out[i] = []; - } else if(out[i].length > data.length) { - // If too long, truncate. (If too short, it will grow - // automatically so we don't care about[i] that case) - out[i] = out[i].slice(0, data.length); - } - - for(j = 0; j < data[0].length; j++) { - out[i][j] = func(data[i][j]); - } - } - return out; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; - -/* - * 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 - */ -var _$smoothFill2dArray_733 = 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_539.log('Smoother converged to', resid, 'after', iter, 'iterations'); - - return data; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -var _$clean2dArray_775 = function clean2dArray(zOld, transpose) { - var rowlen, collen, getCollen, old2new, i, j; - - function cleanZvalue(v) { - if(!_$fastIsnumeric_139(v)) return undefined; - return +v; - } - - if(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 zNew = new Array(rowlen); - - for(i = 0; i < rowlen; i++) { - collen = getCollen(zOld, i); - zNew[i] = new Array(collen); - for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); - } - - return zNew; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$cheater_basis_717 = require('./cheater_basis'); */; -/* removed: var _$array_minmax_707 = require('./array_minmax'); */; -/* removed: var _$mapArray_729 = require('./map_2d_array'); */; -/* removed: var _$calcGridlines_714 = require('./calc_gridlines'); */; -/* removed: var _$calcLabels_715 = require('./calc_labels'); */; -/* removed: var _$makeClipPath_713 = require('./calc_clippath'); */; -/* removed: var _$clean2dArray_775 = require('../heatmap/clean_2d_array'); */; -/* removed: var _$smoothFill2dArray_733 = require('./smooth_fill_2d_array'); */; - -var _$calc_712 = function calc(gd, trace) { - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); - var aax = trace.aaxis; - var bax = trace.baxis; - var a = trace._a = trace.a; - var b = trace._b = trace.b; - - var t = {}; - var x; - var y = trace.y; - - if(trace._cheater) { - var avals = aax.cheatertype === 'index' ? a.length : a; - var bvals = bax.cheatertype === 'index' ? b.length : b; - x = _$cheater_basis_717(avals, bvals, trace.cheaterslope); - } else { - x = trace.x; - } - - trace._x = x = _$clean2dArray_775(x); - trace._y = y = _$clean2dArray_775(y); - - // Fill in any undefined values with elliptic smoothing. This doesn't take - // into account the spacing of the values. That is, the derivatives should - // be modified to use a and b values. It's not that hard, but this is already - // moderate overkill for just filling in missing values. - _$smoothFill2dArray_733(x, a, b); - _$smoothFill2dArray_733(y, a, b); - - // create conversion functions that depend on the data - trace.setScale(); - - // Convert cartesian-space x/y coordinates to screen space pixel coordinates: - t.xp = trace.xp = _$mapArray_729(trace.xp, x, xa.c2p); - t.yp = trace.yp = _$mapArray_729(trace.yp, y, ya.c2p); - - // This is a rather expensive scan. Nothing guarantees monotonicity, - // so we need to scan through all data to get proper ranges: - var xrange = _$array_minmax_707(x); - var yrange = _$array_minmax_707(y); - - var dx = 0.5 * (xrange[1] - xrange[0]); - var xc = 0.5 * (xrange[1] + xrange[0]); - - var dy = 0.5 * (yrange[1] - yrange[0]); - var yc = 0.5 * (yrange[1] + yrange[0]); - - // Expand the axes to fit the plot, except just grow it by a factor of 1.3 - // because the labels should be taken into account except that's difficult - // hence 1.3. - var grow = 1.3; - xrange = [xc - dx * grow, xc + dx * grow]; - yrange = [yc - dy * grow, yc + dy * grow]; - - _$axes_584.expand(xa, xrange, {padded: true}); - _$axes_584.expand(ya, yrange, {padded: true}); - - // Enumerate the gridlines, both major and minor, and store them on the trace - // object: - _$calcGridlines_714(trace, t, 'a', 'b'); - _$calcGridlines_714(trace, t, 'b', 'a'); - - // Calculate the text labels for each major gridline and store them on the - // trace object: - _$calcLabels_715(trace, aax); - _$calcLabels_715(trace, bax); - - // Tabulate points for the four segments that bound the axes so that we can - // map to pixel coordinates in the plot function and create a clip rect: - t.clipsegments = _$makeClipPath_713(trace.xctrl, trace.yctrl, aax, bax); - - t.x = x; - t.y = y; - t.a = a; - t.b = b; - - return [t]; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_708 = require('./attributes'); */; - -var addOpacity = _$color_411.addOpacity; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_606 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../../plots/cartesian/tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_588 = require('../../plots/cartesian/category_order_defaults'); */; -/* removed: var _$setConvert_603 = require('../../plots/cartesian/set_convert'); */; -/* removed: var _$orderedCategories_599 = require('../../plots/cartesian/ordered_categories'); */; -/* removed: var _$autoType_585 = require('../../plots/cartesian/axis_autotype'); */; - -/** - * options: object containing: - * - * letter: 'x' or 'y' - * title: name of the axis (ie 'Colorbar') to go in default title - * name: axis object name (ie 'xaxis') if one should be stored - * font: the default font to inherit - * outerTicks: boolean, should ticks default to outside? - * showGrid: boolean, should gridlines be shown by default? - * data: the plot data to use in choosing auto type - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_711 = function handleAxisDefaults(containerIn, containerOut, options) { - var letter = options.letter, - font = options.font || {}, - attributes = _$attributes_708[letter + 'axis']; - - function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, attributes, attr, dflt); - } - - function coerce2(attr, dflt) { - return _$lib_539.coerce2(containerIn, containerOut, attributes, attr, dflt); - } - - // set up some private properties - if(options.name) { - containerOut._name = options.name; - containerOut._id = options.name; - } - - // now figure out type and do some more initialization - var axType = coerce('type'); - if(axType === '-') { - if(options.data) __setAutoType_711(containerOut, options.data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - axType = containerIn.type = containerOut.type; - } - } - - coerce('smoothing'); - coerce('cheatertype'); - - coerce('showticklabels'); - coerce('labelprefix', letter + ' = '); - coerce('labelsuffix'); - coerce('showtickprefix'); - coerce('showticksuffix'); - - coerce('separatethousands'); - coerce('tickformat'); - coerce('exponentformat'); - coerce('showexponent'); - coerce('categoryorder'); - - coerce('tickmode'); - coerce('tickvals'); - coerce('ticktext'); - coerce('tick0'); - coerce('dtick'); - - if(containerOut.tickmode === 'array') { - coerce('arraytick0'); - coerce('arraydtick'); - } - - coerce('labelpadding'); - - containerOut._hovertitle = letter; - - - if(axType === 'date') { - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } - - _$setConvert_603(containerOut, options.fullLayout); - - var dfltColor = coerce('color', options.dfltColor); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; - - coerce('title'); - _$lib_539.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); - - coerce('titleoffset'); - - coerce('tickangle'); - - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); + // 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; - if(autoRange) coerce('rangemode'); + // XXX: This calculation isn't quite right. Off by one somewhere? + v = v0 + (v1 - v0) * (i + 1) / (axis.minorgridcount + 1) * (axis.arraydtick / d); - coerce('range'); - containerOut.cleanRange(); + // 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_777(constructValueGridline(v), { + color: axis.minorgridcolor, + width: axis.minorgridwidth + })); + } + } - coerce('fixedrange'); + if(axis.startline) { + boundarylines.push(__extendFlat_777(constructArrayGridline(0), { + color: axis.startlinecolor, + width: axis.startlinewidth + })); + } - _$handleTickValueDefaults_606(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_604(containerIn, containerOut, coerce, axType, options); - _$handleCategoryOrderDefaults_588(containerIn, containerOut, coerce); + if(axis.endline) { + boundarylines.push(__extendFlat_777(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. - var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3)); - var gridWidth = coerce2('gridwidth'); - var showGrid = coerce('showgrid'); + // 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;}); - if(!showGrid) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } + // Unpack sorted values so we can be sure to avoid infinite loops if something + // is backwards: + n1 = bounds[0]; + n2 = bounds[1]; - var startLineColor = coerce2('startlinecolor', dfltColor); - var startLineWidth = coerce2('startlinewidth', gridWidth); - var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth); + for(n = n1; n <= n2; n++) { + value = axis.tick0 + axis.dtick * n; - if(!showStartLine) { - delete containerOut.startlinecolor; - delete containerOut.startlinewidth; - } + gridlines.push(__extendFlat_777(constructValueGridline(value), { + color: axis.gridcolor, + width: axis.gridwidth + })); + } - var endLineColor = coerce2('endlinecolor', dfltColor); - var endLineWidth = coerce2('endlinewidth', gridWidth); - var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth); + for(n = n1 - 1; n < n2 + 1; n++) { + value = axis.tick0 + axis.dtick * n; - if(!showEndLine) { - delete containerOut.endlinecolor; - delete containerOut.endlinewidth; - } + 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_777(constructValueGridline(v), { + color: axis.minorgridcolor, + width: axis.minorgridwidth + })); + } + } - if(!showGrid) { - delete containerOut.gridcolor; - delete containerOut.gridWidth; - } else { - coerce('minorgridcount'); - coerce('minorgridwidth', gridWidth); - coerce('minorgridcolor', addOpacity(gridColor, 0.06)); + if(axis.startline) { + boundarylines.push(__extendFlat_777(constructValueGridline(data[0]), { + color: axis.startlinecolor, + width: axis.startlinewidth + })); + } - if(!containerOut.minorgridcount) { - delete containerOut.minorgridwidth; - delete containerOut.minorgridcolor; + if(axis.endline) { + boundarylines.push(__extendFlat_777(constructValueGridline(data[data.length - 1]), { + color: axis.endlinecolor, + width: axis.endlinewidth + })); } } +}; - // fill in categories - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_599(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(containerOut.showticklabels === 'none') { - delete containerOut.tickfont; - delete containerOut.tickangle; - delete containerOut.showexponent; - delete containerOut.exponentformat; - delete containerOut.tickformat; - delete containerOut.showticksuffix; - delete containerOut.showtickprefix; - } +'use strict'; - if(!containerOut.showticksuffix) { - delete containerOut.ticksuffix; - } +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __extendFlat_778 = _$extend_590.extendFlat; - if(!containerOut.showtickprefix) { - delete containerOut.tickprefix; - } +var _$calcLabels_778 = function calcLabels(trace, axis) { + var i, tobj, prefix, suffix, gridline; - // It needs to be coerced, then something above overrides this deep in the axis code, - // but no, we *actually* want to coerce this. - coerce('tickmode'); + var labels = axis._labels = []; + var gridlines = axis._gridlines; - if(!containerOut.title || (containerOut.title && containerOut.title.length === 0)) { - delete containerOut.titlefont; - delete containerOut.titleoffset; - } + for(i = 0; i < gridlines.length; i++) { + gridline = gridlines[i]; - return containerOut; -}; + if(['start', 'both'].indexOf(axis.showticklabels) !== -1) { + tobj = _$axes_647.tickText(axis, gridline.value); -function __setAutoType_711(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; + __extendFlat_778(tobj, { + prefix: prefix, + suffix: suffix, + endAnchor: true, + xy: gridline.xy(0), + dxy: gridline.dxy(0, 0), + axis: gridline.axis, + length: gridline.crossAxis.length, + font: gridline.axis.tickfont, + isFirst: i === 0, + isLast: i === gridlines.length - 1 + }); - var id = ax._id, - axLetter = id.charAt(0); + labels.push(tobj); + } - var calAttr = axLetter + 'calendar', - calendar = ax[calAttr]; + if(['end', 'both'].indexOf(axis.showticklabels) !== -1) { + tobj = _$axes_647.tickText(axis, gridline.value); - ax.type = _$autoType_585(data, calendar); -} + __extendFlat_778(tobj, { + endAnchor: false, + xy: gridline.xy(gridline.crossLength - 1), + dxy: gridline.dxy(gridline.crossLength - 2, 1), + axis: gridline.axis, + length: gridline.crossAxis.length, + font: gridline.axis.tickfont, + isFirst: i === 0, + isLast: i === gridlines.length - 1 + }); + + labels.push(tobj); + } + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -47324,62 +50829,78 @@ function __setAutoType_711(ax, data) { 'use strict'; -/* removed: var _$handleAxisDefaults_711 = require('./axis_defaults'); */; +var __isArrayOrTypedArray_780 = _$lib_601.isArrayOrTypedArray; -var _$handleABDefaults_706 = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) { - var a = coerce('a'); +/* + * Construct a 2D array of cheater values given a, b, and a slope. + * If + */ +var _$cheater_basis_780 = function(a, b, cheaterslope) { + var i, j, ascal, bscal, aval, bval; + var data = []; - if(!a) { - coerce('da'); - coerce('a0'); + var na = __isArrayOrTypedArray_780(a) ? a.length : a; + var nb = __isArrayOrTypedArray_780(b) ? b.length : b; + var adata = __isArrayOrTypedArray_780(a) ? a : null; + var bdata = __isArrayOrTypedArray_780(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); } - var b = coerce('b'); + if(bdata) { + bscal = (bdata.length - 1) / (bdata[bdata.length - 1] - bdata[0]) / (nb - 1); + } - if(!b) { - coerce('db'); - coerce('b0'); + 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; + } } - mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor); + // 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; + return data; }; -function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) { - var axesList = ['aaxis', 'baxis']; - - axesList.forEach(function(axName) { - var axLetter = axName.charAt(0); - var axIn = traceIn[axName] || {}; - var axOut = {}; - - var defaultOptions = { - tickfont: 'x', - id: axLetter + 'axis', - letter: axLetter, - font: traceOut.font, - name: axName, - data: traceIn[axLetter], - calendar: traceOut.calendar, - dfltColor: dfltColor, - bgColor: fullLayout.paper_bgcolor, - fullLayout: fullLayout - }; - - _$handleAxisDefaults_711(axIn, axOut, defaultOptions); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - axOut._categories = axOut._categories || []; +'use strict'; - traceOut[axName] = axOut; +var __isArrayOrTypedArray_787 = _$lib_601.isArrayOrTypedArray; - // so we don't have to repeat autotype unnecessarily, - // copy an autotype back to traceIn - if(!traceIn[axName] && axIn.type !== '-') { - traceIn[axName] = {type: axIn.type}; - } - }); -} +var _$has_columns_787 = function(data) { + return __isArrayOrTypedArray_787(data[0]); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -47401,14 +50922,14 @@ function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) { * to make a nice grid, we'll need to divide the tangent by 2 instead of 3. (The * math works out this way if you work through the bezier derivatives) */ -var __CatmullRomExp_716 = 0.5; -var _$makeControlPoints_716 = function makeControlPoints(p0, p1, p2, smoothness) { +var __CatmullRomExp_779 = 0.5; +var _$makeControlPoints_779 = function makeControlPoints(p0, p1, p2, smoothness) { var d1x = p0[0] - p1[0], d1y = p0[1] - p1[1], d2x = p2[0] - p1[0], d2y = p2[1] - p1[1], - d1a = Math.pow(d1x * d1x + d1y * d1y, __CatmullRomExp_716 / 2), - d2a = Math.pow(d2x * d2x + d2y * d2y, __CatmullRomExp_716 / 2), + d1a = Math.pow(d1x * d1x + d1y * d1y, __CatmullRomExp_779 / 2), + d2a = Math.pow(d2x * d2x + d2y * d2y, __CatmullRomExp_779 / 2), numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness, numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness, denom1 = d2a * (d1a + d2a) * 3, @@ -47432,8 +50953,8 @@ var _$makeControlPoints_716 = function makeControlPoints(p0, p1, p2, smoothness) 'use strict'; -/* removed: var _$makeControlPoints_716 = require('./catmull_rom'); */; -var ensureArray = _$lib_539.ensureArray; +/* removed: var _$makeControlPoints_779 = require('./catmull_rom'); */; +var ensureArray = _$lib_601.ensureArray; /* * Turns a coarse grid into a fine grid with control points. @@ -47551,7 +51072,7 @@ function inferCubicControlPoint(p0, p2, p3) { ]; } -var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) { +var _$computeControlPoints_781 = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) { var i, j, ie, je, xej, yej, xj, yj, cp, p1; // At this point, we know these dimensions are correct and representative of // the whole 2D arrays: @@ -47619,7 +51140,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm for(j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) { // Fill in the points marked X for this a-row: for(i = 1, ie = 3; i < na - 1; i++, ie += 3) { - cp = _$makeControlPoints_716( + cp = _$makeControlPoints_779( [x[j][i - 1], y[j][i - 1]], [x[j][i ], y[j][i]], [x[j][i + 1], y[j][i + 1]], @@ -47678,7 +51199,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm // for(ie = 0; ie < nea; ie++) { for(je = 3; je < neb - 3; je += 3) { - cp = _$makeControlPoints_716( + cp = _$makeControlPoints_779( [xe[je - 3][ie], ye[je - 3][ie]], [xe[je][ie], ye[je][ie]], [xe[je + 3][ie], ye[je + 3][ie]], @@ -47737,7 +51258,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm for(je = 1; je < neb; je += (je + 1) % 3 === 0 ? 2 : 1) { // Fill in the points marked X for this a-row: for(ie = 3; ie < nea - 3; ie += 3) { - cp = _$makeControlPoints_716( + cp = _$makeControlPoints_779( [xe[je][ie - 3], ye[je][ie - 3]], [xe[je][ie], ye[je][ie]], [xe[je][ie + 3], ye[je][ie + 3]], @@ -47784,7 +51305,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm 'use strict'; -var _$constants_719 = { +var _$constants_782 = { RELATIVE_CULL_TOLERANCE: 1e-6 }; @@ -47828,7 +51349,7 @@ var _$constants_719 = { * NB: It's presumed that at this point all data has been sanitized and is valid numerical data arrays * of the correct dimension. */ -var _$create_i_derivative_evaluator_720 = function(arrays, asmoothing, bsmoothing) { +var _$create_i_derivative_evaluator_783 = function(arrays, asmoothing, bsmoothing) { if(asmoothing && bsmoothing) { return function(out, i0, j0, u, v) { if(!out) out = []; @@ -47949,7 +51470,7 @@ var _$create_i_derivative_evaluator_720 = function(arrays, asmoothing, bsmoothin 'use strict'; -var _$create_j_derivative_evaluator_721 = function(arrays, asmoothing, bsmoothing) { +var _$create_j_derivative_evaluator_784 = function(arrays, asmoothing, bsmoothing) { if(asmoothing && bsmoothing) { return function(out, i0, j0, u, v) { if(!out) out = []; @@ -48089,7 +51610,7 @@ var _$create_j_derivative_evaluator_721 = function(arrays, asmoothing, bsmoothin * to be able control whether the derivative at a cell boundary is approached * from one side or the other. */ -var _$create_spline_evaluator_722 = function(arrays, na, nb, asmoothing, bsmoothing) { +var _$create_spline_evaluator_785 = function(arrays, na, nb, asmoothing, bsmoothing) { var imax = na - 2; var jmax = nb - 2; @@ -48226,12 +51747,12 @@ var _$create_spline_evaluator_722 = function(arrays, na, nb, asmoothing, bsmooth 'use strict'; -/* removed: var _$constants_719 = require('./constants'); */; -var search = _$search_557.findBin; -/* removed: var _$computeControlPoints_718 = require('./compute_control_points'); */; -/* removed: var _$create_spline_evaluator_722 = require('./create_spline_evaluator'); */; -/* removed: var _$create_i_derivative_evaluator_720 = require('./create_i_derivative_evaluator'); */; -/* removed: var _$create_j_derivative_evaluator_721 = require('./create_j_derivative_evaluator'); */; +/* removed: var _$constants_782 = require('./constants'); */; +var search = _$search_620.findBin; +/* removed: var _$computeControlPoints_781 = require('./compute_control_points'); */; +/* removed: var _$create_spline_evaluator_785 = require('./create_spline_evaluator'); */; +/* removed: var _$create_i_derivative_evaluator_783 = require('./create_i_derivative_evaluator'); */; +/* removed: var _$create_j_derivative_evaluator_784 = require('./create_j_derivative_evaluator'); */; /* * Create conversion functions to go from one basis to another. In particular the letter @@ -48242,11 +51763,11 @@ var search = _$search_557.findBin; * c: cartesian x-y coordinates * p: screen-space pixel coordinates */ -var _$setConvert_732 = function setConvert(trace) { - var a = trace.a; - var b = trace.b; - var na = trace.a.length; - var nb = trace.b.length; +var _$setConvert_794 = function setConvert(trace) { + var a = trace._a; + var b = trace._b; + var na = a.length; + var nb = b.length; var aax = trace.aaxis; var bax = trace.baxis; @@ -48261,8 +51782,8 @@ var _$setConvert_732 = function setConvert(trace) { // Compute the tolerance so that points are visible slightly outside the // defined carpet axis: - var atol = arange * _$constants_719.RELATIVE_CULL_TOLERANCE; - var btol = brange * _$constants_719.RELATIVE_CULL_TOLERANCE; + var atol = arange * _$constants_782.RELATIVE_CULL_TOLERANCE; + var btol = brange * _$constants_782.RELATIVE_CULL_TOLERANCE; // Expand the limits to include the relative tolerance: amin -= atol; @@ -48270,1370 +51791,500 @@ var _$setConvert_732 = function setConvert(trace) { bmin -= btol; bmax += btol; - trace.isVisible = function(a, b) { - return a > amin && a < amax && b > bmin && b < bmax; - }; - - trace.isOccluded = function(a, b) { - return a < amin || a > amax || b < bmin || b > bmax; - }; - - // XXX: ONLY PASSTHRU. ONLY. No, ONLY. - aax.c2p = function(v) { return v; }; - bax.c2p = function(v) { return v; }; - - trace.setScale = function() { - var x = trace._x; - var y = trace._y; - - // This is potentially a very expensive step! It does the bulk of the work of constructing - // an expanded basis of control points. Note in particular that it overwrites the existing - // basis without creating a new array since that would potentially thrash the garbage - // collector. - var result = _$computeControlPoints_718(trace.xctrl, trace.yctrl, x, y, aax.smoothing, bax.smoothing); - trace.xctrl = result[0]; - trace.yctrl = result[1]; - - // This step is the second step in the process, but it's somewhat simpler. It just unrolls - // some logic since it would be unnecessarily expensive to compute both interpolations - // nearly identically but separately and to include a bunch of linear vs. bicubic logic in - // every single call. - trace.evalxy = _$create_spline_evaluator_722([trace.xctrl, trace.yctrl], na, nb, aax.smoothing, bax.smoothing); - - trace.dxydi = _$create_i_derivative_evaluator_720([trace.xctrl, trace.yctrl], aax.smoothing, bax.smoothing); - trace.dxydj = _$create_j_derivative_evaluator_721([trace.xctrl, trace.yctrl], aax.smoothing, bax.smoothing); - }; - - /* - * Convert from i/j data grid coordinates to a/b values. Note in particular that this - * is *linear* interpolation, even if the data is interpolated bicubically. - */ - trace.i2a = function(i) { - var i0 = Math.max(0, Math.floor(i[0]), na - 2); - var ti = i[0] - i0; - return (1 - ti) * a[i0] + ti * a[i0 + 1]; - }; - - trace.j2b = function(j) { - var j0 = Math.max(0, Math.floor(j[1]), na - 2); - var tj = j[1] - j0; - return (1 - tj) * b[j0] + tj * b[j0 + 1]; - }; - - trace.ij2ab = function(ij) { - return [trace.i2a(ij[0]), trace.j2b(ij[1])]; - }; - - /* - * Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching - * through the a/b data arrays and assumes they are monotonic, which is presumed to have - * been enforced already. - */ - trace.a2i = function(aval) { - var i0 = Math.max(0, Math.min(search(aval, a), na - 2)); - var a0 = a[i0]; - var a1 = a[i0 + 1]; - return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0))); - }; - - trace.b2j = function(bval) { - var j0 = Math.max(0, Math.min(search(bval, b), nb - 2)); - var b0 = b[j0]; - var b1 = b[j0 + 1]; - return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0))); - }; - - trace.ab2ij = function(ab) { - return [trace.a2i(ab[0]), trace.b2j(ab[1])]; - }; - - /* - * Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear - * or bicubic spline evaluation, but the hard part is already done at this point. - */ - trace.i2c = function(i, j) { - return trace.evalxy([], i, j); - }; - - trace.ab2xy = function(aval, bval, extrapolate) { - if(!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) { - return [false, false]; - } - var i = trace.a2i(aval); - var j = trace.b2j(bval); - - var pt = trace.evalxy([], i, j); - - if(extrapolate) { - // This section uses the boundary derivatives to extrapolate linearly outside - // the defined range. Consider a scatter line with one point inside the carpet - // axis and one point outside. If we don't extrapolate, we can't draw the line - // at all. - var iex = 0; - var jex = 0; - var der = []; - - var i0, ti, j0, tj; - if(aval < a[0]) { - i0 = 0; - ti = 0; - iex = (aval - a[0]) / (a[1] - a[0]); - } else if(aval > a[na - 1]) { - i0 = na - 2; - ti = 1; - iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]); - } else { - i0 = Math.max(0, Math.min(na - 2, Math.floor(i))); - ti = i - i0; - } - - if(bval < b[0]) { - j0 = 0; - tj = 0; - jex = (bval - b[0]) / (b[1] - b[0]); - } else if(bval > b[nb - 1]) { - j0 = nb - 2; - tj = 1; - jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]); - } else { - j0 = Math.max(0, Math.min(nb - 2, Math.floor(j))); - tj = j - j0; - } - - if(iex) { - trace.dxydi(der, i0, j0, ti, tj); - pt[0] += der[0] * iex; - pt[1] += der[1] * iex; - } - - if(jex) { - trace.dxydj(der, i0, j0, ti, tj); - pt[0] += der[0] * jex; - pt[1] += der[1] * jex; - } - } - - return pt; - }; - - - trace.c2p = function(xy, xa, ya) { - return [xa.c2p(xy[0]), ya.c2p(xy[1])]; - }; - - trace.p2x = function(p, xa, ya) { - return [xa.p2c(p[0]), ya.p2c(p[1])]; - }; - - trace.dadi = function(i /* , u*/) { - // Right now only a piecewise linear a or b basis is permitted since smoother interpolation - // would cause monotonicity problems. As a retult, u is entirely disregarded in this - // computation, though we'll specify it as a parameter for the sake of completeness and - // future-proofing. It would be possible to use monotonic cubic interpolation, for example. - // - // See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation - - // u = u || 0; - - var i0 = Math.max(0, Math.min(a.length - 2, i)); - - // The step (demoninator) is implicitly 1 since that's the grid spacing. - return a[i0 + 1] - a[i0]; - }; - - trace.dbdj = function(j /* , v*/) { - // See above caveats for dadi which also apply here - var j0 = Math.max(0, Math.min(b.length - 2, j)); - - // The step (demoninator) is implicitly 1 since that's the grid spacing. - return b[j0 + 1] - b[j0]; - }; - - // Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v) - // Returns: (dx/da, dy/db) - // - // NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous - // derivative, as described better in create_i_derivative_evaluator.js - trace.dxyda = function(i0, j0, u, v) { - var dxydi = trace.dxydi(null, i0, j0, u, v); - var dadi = trace.dadi(i0, u); - - return [dxydi[0] / dadi, dxydi[1] / dadi]; - }; - - trace.dxydb = function(i0, j0, u, v) { - var dxydj = trace.dxydj(null, i0, j0, u, v); - var dbdj = trace.dbdj(j0, v); - - return [dxydj[0] / dbdj, dxydj[1] / dbdj]; - }; - - // Sometimes we don't care about precision and all we really want is decent rough - // directions (as is the case with labels). In that case, we can do a very rough finite - // difference and spare having to worry about precise grid coordinates: - trace.dxyda_rough = function(a, b, reldiff) { - var h = arange * (reldiff || 0.1); - var plus = trace.ab2xy(a + h, b, true); - var minus = trace.ab2xy(a - h, b, true); - - return [ - (plus[0] - minus[0]) * 0.5 / h, - (plus[1] - minus[1]) * 0.5 / h - ]; - }; - - trace.dxydb_rough = function(a, b, reldiff) { - var h = brange * (reldiff || 0.1); - var plus = trace.ab2xy(a, b + h, true); - var minus = trace.ab2xy(a, b - h, true); - - return [ - (plus[0] - minus[0]) * 0.5 / h, - (plus[1] - minus[1]) * 0.5 / h - ]; - }; - - trace.dpdx = function(xa) { - return xa._m; - }; - - trace.dpdy = function(ya) { - return ya._m; - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_724 = _$lib_539.isArrayOrTypedArray; - -var _$has_columns_724 = function(data) { - return __isArrayOrTypedArray_724(data[0]); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_777 = _$numerical_517.BADNUM; - -var _$convertColumnData_777 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { - var1Name = var1Name || 'x'; - var2Name = var2Name || 'y'; - arrayVarNames = arrayVarNames || ['z']; - - var col1 = trace[var1Name].slice(), - col2 = trace[var2Name].slice(), - textCol = trace.text, - colLen = Math.min(col1.length, col2.length), - hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), - col1Calendar = trace[var1Name + 'calendar'], - col2Calendar = trace[var2Name + 'calendar']; - - var i, j, arrayVar, newArray, arrayVarName; - - for(i = 0; i < arrayVarNames.length; i++) { - arrayVar = trace[arrayVarNames[i]]; - if(arrayVar) colLen = Math.min(colLen, arrayVar.length); - } - - if(colLen < col1.length) col1 = col1.slice(0, colLen); - if(colLen < col2.length) col2 = col2.slice(0, colLen); - - for(i = 0; i < colLen; i++) { - col1[i] = ax1.d2c(col1[i], 0, col1Calendar); - col2[i] = ax2.d2c(col2[i], 0, col2Calendar); - } - - var col1dv = _$lib_539.distinctVals(col1), - col1vals = col1dv.vals, - col2dv = _$lib_539.distinctVals(col2), - col2vals = col2dv.vals, - newArrays = []; - - for(i = 0; i < arrayVarNames.length; i++) { - newArrays[i] = _$lib_539.init2dArray(col2vals.length, col1vals.length); - } - - var i1, i2, text; - - if(hasColumnText) text = _$lib_539.init2dArray(col2vals.length, col1vals.length); - - for(i = 0; i < colLen; i++) { - if(col1[i] !== __BADNUM_777 && col2[i] !== __BADNUM_777) { - i1 = _$lib_539.findBin(col1[i] + col1dv.minDiff / 2, col1vals); - i2 = _$lib_539.findBin(col2[i] + col2dv.minDiff / 2, col2vals); - - for(j = 0; j < arrayVarNames.length; j++) { - arrayVarName = arrayVarNames[j]; - arrayVar = trace[arrayVarName]; - newArray = newArrays[j]; - newArray[i2][i1] = arrayVar[i]; - } - - if(hasColumnText) text[i2][i1] = textCol[i]; - } - } - - // hack for Plotly.react - save the input arrays for diffing purposes - trace['_input_' + var1Name] = trace[var1Name]; - trace['_input_' + var2Name] = trace[var2Name]; - trace[var1Name] = col1vals; - trace[var2Name] = col2vals; - for(j = 0; j < arrayVarNames.length; j++) { - trace['_input_' + arrayVarNames[j]] = trace[arrayVarNames[j]]; - trace[arrayVarNames[j]] = newArrays[j]; - } - if(hasColumnText) trace.text = text; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$has_columns_724 = require('./has_columns'); */; -/* removed: var _$convertColumnData_777 = require('../heatmap/convert_column_xyz'); */; - -var _$handleXYDefaults_734 = function handleXYDefaults(traceIn, traceOut, coerce) { - var cols = []; - var x = coerce('x'); - - var needsXTransform = x && !_$has_columns_724(x); - if(needsXTransform) cols.push('x'); - - traceOut._cheater = !x; - - var y = coerce('y'); - - var needsYTransform = y && !_$has_columns_724(y); - if(needsYTransform) cols.push('y'); - - if(!x && !y) return; - - if(cols.length) { - _$convertColumnData_777(traceOut, traceOut.aaxis, traceOut.baxis, 'a', 'b', cols); - } - - return true; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleXYDefaults_734 = require('./xy_defaults'); */; -/* removed: var _$handleABDefaults_706 = require('./ab_defaults'); */; -/* removed: var _$setConvert_732 = require('./set_convert'); */; -/* removed: var _$attributes_708 = require('./attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; - -var _$supplyDefaults_723 = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_708, attr, dflt); - } - - traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet'; - - var defaultColor = coerce('color', _$attributes_410.defaultLine); - _$lib_539.coerceFont(coerce, 'font'); - - coerce('carpet'); - - _$handleABDefaults_706(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 len = _$handleXYDefaults_734(traceIn, traceOut, coerce); - - _$setConvert_732(traceOut); - - if(traceOut._cheater) { - coerce('cheaterslope'); - } - - if(!len) { - traceOut.visible = false; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$makePath_727 = function makePath(xp, yp, isBicubic) { - // Prevent d3 errors that would result otherwise: - if(xp.length === 0) return ''; - - var i, path = []; - var stride = isBicubic ? 3 : 1; - for(i = 0; i < xp.length; i += stride) { - path.push(xp[i] + ',' + yp[i]); - - if(isBicubic && i < xp.length - stride) { - path.push('C'); - path.push([ - xp[i + 1] + ',' + yp[i + 1], - xp[i + 2] + ',' + yp[i + 2] + ' ', - ].join(' ')); - } - } - return path.join(isBicubic ? '' : 'L'); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_728 = _$lib_539.isArrayOrTypedArray; - -/* - * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p). - * The output array is optional, but if provided, it will be reused without - * reallocation to the extent possible. - */ -var _$mapArray_728 = function mapArray(out, data, func) { - var i; - - if(!__isArrayOrTypedArray_728(out)) { - // If not an array, make it an array: - out = []; - } else if(out.length > data.length) { - // If too long, truncate. (If too short, it will grow - // automatically so we don't care about that case) - out = out.slice(0, data.length); - } - - for(i = 0; i < data.length; i++) { - out[i] = func(data[i]); - } - - return out; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var _$orientText_730 = 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 - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$mapArray_728 = require('./map_1d_array'); */; -/* removed: var _$makePath_727 = require('./makepath'); */; -/* removed: var _$orientText_730 = require('./orient_text'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; - -var _$plot_731 = function plot(gd, plotinfo, cdcarpet) { - for(var i = 0; i < cdcarpet.length; i++) { - __plotOne_731(gd, plotinfo, cdcarpet[i]); - } -}; - -function makeg(el, type, klass) { - var join = el.selectAll(type + '.' + klass).data([0]); - join.enter().append(type).classed(klass, true); - return join; -} - -function __plotOne_731(gd, plotinfo, cd) { - var t = cd[0]; - var trace = cd[0].trace, - xa = plotinfo.xaxis, - ya = plotinfo.yaxis, - aax = trace.aaxis, - bax = trace.baxis, - fullLayout = gd._fullLayout; - - var gridLayer = plotinfo.plot.selectAll('.carpetlayer'); - var clipLayer = fullLayout._clips; - - var axisLayer = makeg(gridLayer, 'g', 'carpet' + trace.uid).classed('trace', true); - var minorLayer = makeg(axisLayer, 'g', 'minorlayer'); - var majorLayer = makeg(axisLayer, 'g', 'majorlayer'); - var boundaryLayer = makeg(axisLayer, 'g', 'boundarylayer'); - var labelLayer = makeg(axisLayer, 'g', 'labellayer'); - - axisLayer.style('opacity', trace.opacity); - - drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true); - drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true); - drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true); - drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true); - - // NB: These are not ommitted if the lines are not active. The joins must be executed - // in order for them to get cleaned up without a full redraw - drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines); - drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines); - - var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, aax._labels, 'a-label'); - var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, bax._labels, 'b-label'); - - drawAxisTitles(gd, labelLayer, trace, t, xa, ya, labelOrientationA, labelOrientationB); - - drawClipPath(trace, t, clipLayer, xa, ya); -} - -function drawClipPath(trace, t, layer, xaxis, yaxis) { - var seg, xp, yp, i; - - var clip = layer.select('#' + trace._clipPathId); - - if(!clip.size()) { - clip = layer.append('clipPath') - .classed('carpetclip', true); - } - - var path = makeg(clip, 'path', 'carpetboundary'); - var segments = t.clipsegments; - var segs = []; - - for(i = 0; i < segments.length; i++) { - seg = segments[i]; - xp = _$mapArray_728([], seg.x, xaxis.c2p); - yp = _$mapArray_728([], seg.y, yaxis.c2p); - segs.push(_$makePath_727(xp, yp, seg.bicubic)); - } - - // This could be optimized ever so slightly to avoid no-op L segments - // at the corners, but it's so negligible that I don't think it's worth - // the extra complexity - var clipPathData = 'M' + segs.join('L') + 'Z'; - clip.attr('id', trace._clipPathId); - path.attr('d', clipPathData); -} - -function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines) { - var lineClass = 'const-' + axisLetter + '-lines'; - var gridJoin = layer.selectAll('.' + lineClass).data(gridlines); - - gridJoin.enter().append('path') - .classed(lineClass, true) - .style('vector-effect', 'non-scaling-stroke'); - - gridJoin.each(function(d) { - var gridline = d; - var x = gridline.x; - var y = gridline.y; - - var xp = _$mapArray_728([], x, xaxis.c2p); - var yp = _$mapArray_728([], y, yaxis.c2p); - - var path = 'M' + _$makePath_727(xp, yp, gridline.smoothing); - - var el = _$d3_127.select(this); - - el.attr('d', path) - .style('stroke-width', gridline.width) - .style('stroke', gridline.color) - .style('fill', 'none'); - }); - - gridJoin.exit().remove(); -} - -function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) { - var labelJoin = layer.selectAll('text.' + labelClass).data(labels); - - labelJoin.enter().append('text') - .classed(labelClass, true); - - var maxExtent = 0; - var labelOrientation = {}; - - labelJoin.each(function(label, i) { - // Most of the positioning is done in calc_labels. Only the parts that depend upon - // the screen space representation of the x and y axes are here: - var orientation; - if(label.axis.tickangle === 'auto') { - orientation = _$orientText_730(trace, xaxis, yaxis, label.xy, label.dxy); - } else { - var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0; - orientation = _$orientText_730(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]); - } - - if(!i) { - // TODO: offsetMultiplier? Not currently used anywhere... - labelOrientation = {angle: orientation.angle, flip: orientation.flip}; - } - var direction = (label.endAnchor ? -1 : 1) * orientation.flip; - - var labelEl = _$d3_127.select(this) - .attr({ - 'text-anchor': direction > 0 ? 'start' : 'end', - 'data-notex': 1 - }) - .call(_$drawing_436.font, label.font) - .text(label.text) - .call(_$svg_text_utils_562.convertToTspans, gd); - - var bbox = _$drawing_436.bBox(this); - - labelEl.attr('transform', - // Translate to the correct point: - 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + - // Rotate to line up with grid line tangent: - 'rotate(' + orientation.angle + ')' + - // Adjust the baseline and indentation: - 'translate(' + label.axis.labelpadding * direction + ',' + bbox.height * 0.3 + ')' - ); - - maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding); - }); - - labelJoin.exit().remove(); - - labelOrientation.maxExtent = maxExtent; - return labelOrientation; -} - -function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) { - var a, b, xy, dxy; - - a = 0.5 * (trace.a[0] + trace.a[trace.a.length - 1]); - b = trace.b[0]; - xy = trace.ab2xy(a, b, true); - dxy = trace.dxyda_rough(a, b); - if(labelOrientationA.angle === undefined) { - _$lib_539.extendFlat(labelOrientationA, _$orientText_730(trace, xa, ya, xy, trace.dxydb_rough(a, b))); - } - drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title'); - - a = trace.a[0]; - b = 0.5 * (trace.b[0] + trace.b[trace.b.length - 1]); - xy = trace.ab2xy(a, b, true); - dxy = trace.dxydb_rough(a, b); - if(labelOrientationB.angle === undefined) { - _$lib_539.extendFlat(labelOrientationB, _$orientText_730(trace, xa, ya, xy, trace.dxyda_rough(a, b))); - } - drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title'); -} - -var lineSpacing = _$alignment_511.LINE_SPACING; -var midShift = ((1 - _$alignment_511.MID_SHIFT) / lineSpacing) + 1; - -function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) { - var data = []; - if(axis.title) data.push(axis.title); - var titleJoin = layer.selectAll('text.' + labelClass).data(data); - var offset = labelOrientation.maxExtent; - - titleJoin.enter().append('text') - .classed(labelClass, true); - - // There's only one, but we'll do it as a join so it's updated nicely: - titleJoin.each(function() { - var orientation = _$orientText_730(trace, xa, ya, xy, dxy); - - if(['start', 'both'].indexOf(axis.showticklabels) === -1) { - offset = 0; - } - - // In addition to the size of the labels, add on some extra padding: - var titleSize = axis.titlefont.size; - offset += titleSize + axis.titleoffset; - - var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0); - var angleDiff = (labelNorm - orientation.angle + 450) % 360; - var reverseTitle = angleDiff > 90 && angleDiff < 270; - - var el = _$d3_127.select(this); - - el.text(axis.title || '') - .call(_$svg_text_utils_562.convertToTspans, gd); - - if(reverseTitle) { - offset = (-_$svg_text_utils_562.lineCount(el) + midShift) * lineSpacing * titleSize - offset; - } - - el.attr('transform', - 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + - 'rotate(' + orientation.angle + ') ' + - 'translate(0,' + offset + ')' - ) - .classed('user-select-none', true) - .attr('text-anchor', 'middle') - .call(_$drawing_436.font, axis.titlefont); - }); - - titleJoin.exit().remove(); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var Carpet = {}; - -Carpet.attributes = _$attributes_708; -Carpet.supplyDefaults = _$supplyDefaults_723; -Carpet.plot = _$plot_731; -Carpet.calc = _$calc_712; -Carpet.animatable = true; - -Carpet.moduleType = 'trace'; -Carpet.name = 'carpet'; -Carpet.basePlotModule = _$cartesian_595; -Carpet.categories = ['cartesian', 'carpet', 'carpetAxis', 'notLegendIsolatable']; -Carpet.meta = { - description: [ - 'The data describing carpet axis layout is set in `y` and (optionally)', - 'also `x`. If only `y` is present, `x` the plot is interpreted as a', - 'cheater plot and is filled in using the `y` values.', - - '`x` and `y` may either be 2D arrays matching with each dimension matching', - 'that of `a` and `b`, or they may be 1D arrays with total length equal to', - 'that of `a` and `b`.' - ].join(' ') -}; - -var _$Carpet_725 = Carpet; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$carpet_8 = _$Carpet_725; - -var _$topojsonClient_355 = { exports: {} }; -// https://github.com/topojson/topojson-client Version 2.1.0. Copyright 2016 Mike Bostock. -(function (global, factory) { - typeof _$topojsonClient_355.exports === 'object' && "object" !== 'undefined' ? factory(_$topojsonClient_355.exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.topojson = global.topojson || {}))); -}(this, (function (exports) { 'use strict'; - -var identity = function(x) { - return x; -}; - -var transform = function(topology) { - if ((transform = topology.transform) == null) return identity; - var transform, - x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - point[0] = (x0 += point[0]) * kx + dx; - point[1] = (y0 += point[1]) * ky + dy; - return point; - }; -}; - -var bbox = function(topology) { - var bbox = topology.bbox; + trace.isVisible = function(a, b) { + return a > amin && a < amax && b > bmin && b < bmax; + }; - function bboxPoint(p0) { - p1[0] = p0[0], p1[1] = p0[1], t(p1); - if (p1[0] < x0) x0 = p1[0]; - if (p1[0] > x1) x1 = p1[0]; - if (p1[1] < y0) y0 = p1[1]; - if (p1[1] > y1) y1 = p1[1]; - } + trace.isOccluded = function(a, b) { + return a < amin || a > amax || b < bmin || b > bmax; + }; - function bboxGeometry(o) { - switch (o.type) { - case "GeometryCollection": o.geometries.forEach(bboxGeometry); break; - case "Point": bboxPoint(o.coordinates); break; - case "MultiPoint": o.coordinates.forEach(bboxPoint); break; - } - } + trace.setScale = function() { + var x = trace._x; + var y = trace._y; - if (!bbox) { - var t = transform(topology), p0, p1 = new Array(2), name, - x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0; + // This is potentially a very expensive step! It does the bulk of the work of constructing + // an expanded basis of control points. Note in particular that it overwrites the existing + // basis without creating a new array since that would potentially thrash the garbage + // collector. + var result = _$computeControlPoints_781(trace._xctrl, trace._yctrl, x, y, aax.smoothing, bax.smoothing); + trace._xctrl = result[0]; + trace._yctrl = result[1]; - topology.arcs.forEach(function(arc) { - var i = -1, n = arc.length; - while (++i < n) { - p0 = arc[i], p1[0] = p0[0], p1[1] = p0[1], t(p1, i); - if (p1[0] < x0) x0 = p1[0]; - if (p1[0] > x1) x1 = p1[0]; - if (p1[1] < y0) y0 = p1[1]; - if (p1[1] > y1) y1 = p1[1]; - } - }); + // This step is the second step in the process, but it's somewhat simpler. It just unrolls + // some logic since it would be unnecessarily expensive to compute both interpolations + // nearly identically but separately and to include a bunch of linear vs. bicubic logic in + // every single call. + trace.evalxy = _$create_spline_evaluator_785([trace._xctrl, trace._yctrl], na, nb, aax.smoothing, bax.smoothing); - for (name in topology.objects) { - bboxGeometry(topology.objects[name]); - } + trace.dxydi = _$create_i_derivative_evaluator_783([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing); + trace.dxydj = _$create_j_derivative_evaluator_784([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing); + }; - bbox = topology.bbox = [x0, y0, x1, y1]; - } + /* + * Convert from i/j data grid coordinates to a/b values. Note in particular that this + * is *linear* interpolation, even if the data is interpolated bicubically. + */ + trace.i2a = function(i) { + var i0 = Math.max(0, Math.floor(i[0]), na - 2); + var ti = i[0] - i0; + return (1 - ti) * a[i0] + ti * a[i0 + 1]; + }; - return bbox; -}; + trace.j2b = function(j) { + var j0 = Math.max(0, Math.floor(j[1]), na - 2); + var tj = j[1] - j0; + return (1 - tj) * b[j0] + tj * b[j0 + 1]; + }; -var reverse = function(array, n) { - var t, j = array.length, i = j - n; - while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; -}; + trace.ij2ab = function(ij) { + return [trace.i2a(ij[0]), trace.j2b(ij[1])]; + }; -var feature = function(topology, o) { - return o.type === "GeometryCollection" - ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })} - : feature$1(topology, o); -}; + /* + * Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching + * through the a/b data arrays and assumes they are monotonic, which is presumed to have + * been enforced already. + */ + trace.a2i = function(aval) { + var i0 = Math.max(0, Math.min(search(aval, a), na - 2)); + var a0 = a[i0]; + var a1 = a[i0 + 1]; + return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0))); + }; -function feature$1(topology, o) { - var id = o.id, - bbox = o.bbox, - properties = o.properties == null ? {} : o.properties, - geometry = object(topology, o); - return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} - : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} - : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; -} + trace.b2j = function(bval) { + var j0 = Math.max(0, Math.min(search(bval, b), nb - 2)); + var b0 = b[j0]; + var b1 = b[j0 + 1]; + return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0))); + }; -function object(topology, o) { - var transformPoint = transform(topology), - arcs = topology.arcs; + trace.ab2ij = function(ab) { + return [trace.a2i(ab[0]), trace.b2j(ab[1])]; + }; - function arc(i, points) { - if (points.length) points.pop(); - for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { - points.push(transformPoint(a[k].slice(), k)); - } - if (i < 0) reverse(points, n); - } + /* + * Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear + * or bicubic spline evaluation, but the hard part is already done at this point. + */ + trace.i2c = function(i, j) { + return trace.evalxy([], i, j); + }; - function point(p) { - return transformPoint(p.slice()); - } + trace.ab2xy = function(aval, bval, extrapolate) { + if(!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) { + return [false, false]; + } + var i = trace.a2i(aval); + var j = trace.b2j(bval); - function line(arcs) { - var points = []; - for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); - if (points.length < 2) points.push(points[0].slice()); - return points; - } + var pt = trace.evalxy([], i, j); - function ring(arcs) { - var points = line(arcs); - while (points.length < 4) points.push(points[0].slice()); - return points; - } + if(extrapolate) { + // This section uses the boundary derivatives to extrapolate linearly outside + // the defined range. Consider a scatter line with one point inside the carpet + // axis and one point outside. If we don't extrapolate, we can't draw the line + // at all. + var iex = 0; + var jex = 0; + var der = []; - function polygon(arcs) { - return arcs.map(ring); - } + var i0, ti, j0, tj; + if(aval < a[0]) { + i0 = 0; + ti = 0; + iex = (aval - a[0]) / (a[1] - a[0]); + } else if(aval > a[na - 1]) { + i0 = na - 2; + ti = 1; + iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]); + } else { + i0 = Math.max(0, Math.min(na - 2, Math.floor(i))); + ti = i - i0; + } - function geometry(o) { - var type = o.type, coordinates; - switch (type) { - case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; - case "Point": coordinates = point(o.coordinates); break; - case "MultiPoint": coordinates = o.coordinates.map(point); break; - case "LineString": coordinates = line(o.arcs); break; - case "MultiLineString": coordinates = o.arcs.map(line); break; - case "Polygon": coordinates = polygon(o.arcs); break; - case "MultiPolygon": coordinates = o.arcs.map(polygon); break; - default: return null; - } - return {type: type, coordinates: coordinates}; - } + if(bval < b[0]) { + j0 = 0; + tj = 0; + jex = (bval - b[0]) / (b[1] - b[0]); + } else if(bval > b[nb - 1]) { + j0 = nb - 2; + tj = 1; + jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]); + } else { + j0 = Math.max(0, Math.min(nb - 2, Math.floor(j))); + tj = j - j0; + } - return geometry(o); -} + if(iex) { + trace.dxydi(der, i0, j0, ti, tj); + pt[0] += der[0] * iex; + pt[1] += der[1] * iex; + } -var stitch = function(topology, arcs) { - var stitchedArcs = {}, - fragmentByStart = {}, - fragmentByEnd = {}, - fragments = [], - emptyIndex = -1; + if(jex) { + trace.dxydj(der, i0, j0, ti, tj); + pt[0] += der[0] * jex; + pt[1] += der[1] * jex; + } + } - // Stitch empty arcs first, since they may be subsumed by other arcs. - arcs.forEach(function(i, j) { - var arc = topology.arcs[i < 0 ? ~i : i], t; - if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { - t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; - } - }); + return pt; + }; - arcs.forEach(function(i) { - var e = ends(i), - start = e[0], - end = e[1], - f, g; - if (f = fragmentByEnd[start]) { - delete fragmentByEnd[f.end]; - f.push(i); - f.end = end; - if (g = fragmentByStart[end]) { - delete fragmentByStart[g.start]; - var fg = g === f ? f : f.concat(g); - fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else if (f = fragmentByStart[end]) { - delete fragmentByStart[f.start]; - f.unshift(i); - f.start = start; - if (g = fragmentByEnd[start]) { - delete fragmentByEnd[g.end]; - var gf = g === f ? f : g.concat(f); - fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else { - f = [i]; - fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; - } - }); + trace.c2p = function(xy, xa, ya) { + return [xa.c2p(xy[0]), ya.c2p(xy[1])]; + }; - function ends(i) { - var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; - if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); - else p1 = arc[arc.length - 1]; - return i < 0 ? [p1, p0] : [p0, p1]; - } + trace.p2x = function(p, xa, ya) { + return [xa.p2c(p[0]), ya.p2c(p[1])]; + }; - function flush(fragmentByEnd, fragmentByStart) { - for (var k in fragmentByEnd) { - var f = fragmentByEnd[k]; - delete fragmentByStart[f.start]; - delete f.start; - delete f.end; - f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); - fragments.push(f); - } - } + trace.dadi = function(i /* , u*/) { + // Right now only a piecewise linear a or b basis is permitted since smoother interpolation + // would cause monotonicity problems. As a retult, u is entirely disregarded in this + // computation, though we'll specify it as a parameter for the sake of completeness and + // future-proofing. It would be possible to use monotonic cubic interpolation, for example. + // + // See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation - flush(fragmentByEnd, fragmentByStart); - flush(fragmentByStart, fragmentByEnd); - arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); + // u = u || 0; - return fragments; -}; + var i0 = Math.max(0, Math.min(a.length - 2, i)); -var mesh = function(topology) { - return object(topology, meshArcs.apply(this, arguments)); -}; + // The step (demoninator) is implicitly 1 since that's the grid spacing. + return a[i0 + 1] - a[i0]; + }; -function meshArcs(topology, object$$1, filter) { - var arcs, i, n; - if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter); - else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i; - return {type: "MultiLineString", arcs: stitch(topology, arcs)}; -} + trace.dbdj = function(j /* , v*/) { + // See above caveats for dadi which also apply here + var j0 = Math.max(0, Math.min(b.length - 2, j)); -function extractArcs(topology, object$$1, filter) { - var arcs = [], - geomsByArc = [], - geom; + // The step (demoninator) is implicitly 1 since that's the grid spacing. + return b[j0 + 1] - b[j0]; + }; - function extract0(i) { - var j = i < 0 ? ~i : i; - (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); - } + // Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v) + // Returns: (dx/da, dy/db) + // + // NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous + // derivative, as described better in create_i_derivative_evaluator.js + trace.dxyda = function(i0, j0, u, v) { + var dxydi = trace.dxydi(null, i0, j0, u, v); + var dadi = trace.dadi(i0, u); - function extract1(arcs) { - arcs.forEach(extract0); - } + return [dxydi[0] / dadi, dxydi[1] / dadi]; + }; - function extract2(arcs) { - arcs.forEach(extract1); - } + trace.dxydb = function(i0, j0, u, v) { + var dxydj = trace.dxydj(null, i0, j0, u, v); + var dbdj = trace.dbdj(j0, v); - function extract3(arcs) { - arcs.forEach(extract2); - } + return [dxydj[0] / dbdj, dxydj[1] / dbdj]; + }; - function geometry(o) { - switch (geom = o, o.type) { - case "GeometryCollection": o.geometries.forEach(geometry); break; - case "LineString": extract1(o.arcs); break; - case "MultiLineString": case "Polygon": extract2(o.arcs); break; - case "MultiPolygon": extract3(o.arcs); break; - } - } + // Sometimes we don't care about precision and all we really want is decent rough + // directions (as is the case with labels). In that case, we can do a very rough finite + // difference and spare having to worry about precise grid coordinates: + trace.dxyda_rough = function(a, b, reldiff) { + var h = arange * (reldiff || 0.1); + var plus = trace.ab2xy(a + h, b, true); + var minus = trace.ab2xy(a - h, b, true); - geometry(object$$1); + return [ + (plus[0] - minus[0]) * 0.5 / h, + (plus[1] - minus[1]) * 0.5 / h + ]; + }; - geomsByArc.forEach(filter == null - ? function(geoms) { arcs.push(geoms[0].i); } - : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); + trace.dxydb_rough = function(a, b, reldiff) { + var h = brange * (reldiff || 0.1); + var plus = trace.ab2xy(a, b + h, true); + var minus = trace.ab2xy(a, b - h, true); - return arcs; -} + return [ + (plus[0] - minus[0]) * 0.5 / h, + (plus[1] - minus[1]) * 0.5 / h + ]; + }; -function planarRingArea(ring) { - var i = -1, n = ring.length, a, b = ring[n - 1], area = 0; - while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0]; - return Math.abs(area); // Note: doubled area! -} + trace.dpdx = function(xa) { + return xa._m; + }; -var merge = function(topology) { - return object(topology, mergeArcs.apply(this, arguments)); + trace.dpdy = function(ya) { + return ya._m; + }; }; -function mergeArcs(topology, objects) { - var polygonsByArc = {}, - polygons = [], - groups = []; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - objects.forEach(geometry); +'use strict'; - function geometry(o) { - switch (o.type) { - case "GeometryCollection": o.geometries.forEach(geometry); break; - case "Polygon": extract(o.arcs); break; - case "MultiPolygon": o.arcs.forEach(extract); break; - } - } +/* removed: var _$lib_601 = require('../../lib'); */; - function extract(polygon) { - polygon.forEach(function(ring) { - ring.forEach(function(arc) { - (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); - }); - }); - polygons.push(polygon); - } +/* + * 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 + */ +var _$smoothFill2dArray_795 = function smoothFill2dArray(data, a, b) { + var i, j, k; + var ip = []; + var jp = []; + // var neighborCnts = []; - function area(ring) { - return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]); - } + var ni = data[0].length; + var nj = data.length; - polygons.forEach(function(polygon) { - if (!polygon._) { - var group = [], - neighbors = [polygon]; - polygon._ = 1; - groups.push(group); - while (polygon = neighbors.pop()) { - group.push(polygon); - polygon.forEach(function(ring) { - ring.forEach(function(arc) { - polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { - if (!polygon._) { - polygon._ = 1; - neighbors.push(polygon); - } - }); - }); - }); - } - } - }); + 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); - polygons.forEach(function(polygon) { - delete polygon._; - }); + } - return { - type: "MultiPolygon", - arcs: groups.map(function(polygons) { - var arcs = [], n; + // 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); - // Extract the exterior (unique) arcs. - polygons.forEach(function(polygon) { - polygon.forEach(function(ring) { - ring.forEach(function(arc) { - if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { - arcs.push(arc); + data[j][i] = avgSurrounding(i, j); + // neighborCnts.push(result.neighbors); } - }); - }); - }); + dmax = Math.max(dmax, Math.abs(data[j][i])); + } + } - // Stitch the arcs into one or more rings. - arcs = stitch(topology, arcs); + if(!ip.length) return data; - // If more than one ring is returned, - // at most one of these rings can be the exterior; - // choose the one with the greatest absolute area. - if ((n = arcs.length) > 1) { - for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { - if ((ki = area(arcs[i])) > k) { - t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; - } - } - } + // 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]; - return arcs; - }) - }; -} + // 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 bisect = function(a, x) { - var lo = 0, hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (a[mid] < x) lo = mid + 1; - else hi = mid; - } - return lo; -}; + 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++; + } -var neighbors = function(objects) { - var indexesByArc = {}, // arc index -> array of object indexes - neighbors = objects.map(function() { return []; }); + 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++; + } - function line(arcs, i) { - arcs.forEach(function(a) { - if (a < 0) a = ~a; - var o = indexesByArc[a]; - if (o) o.push(i); - else indexesByArc[a] = [i]; - }); - } + 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++; + } - function polygon(arcs, i) { - arcs.forEach(function(arc) { line(arc, i); }); - } + 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++; + } - function geometry(o, i) { - if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); - else if (o.type in geometryType) geometryType[o.type](o.arcs, i); - } + 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]; - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } - }; + // 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); - objects.forEach(geometry); + 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; + } - for (var i in indexesByArc) { - for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { - for (var k = j + 1; k < m; ++k) { - var ij = indexes[j], ik = indexes[k], n; - if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); - if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); - } - } - } + // 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; - return neighbors; -}; + // 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; -var quantize = function(topology, n) { - if (!((n = Math.floor(n)) >= 2)) throw new Error("n must be ≥2"); - if (topology.transform) throw new Error("already quantized"); - var bb = bbox(topology), name, - dx = bb[0], kx = (bb[2] - dx) / (n - 1) || 1, - dy = bb[1], ky = (bb[3] - dy) / (n - 1) || 1; + // 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; - function quantizePoint(p) { - p[0] = Math.round((p[0] - dx) / kx); - p[1] = Math.round((p[1] - dy) / ky); - } + data[j][i] += diff * (1 + overrelaxation); + } - function quantizeGeometry(o) { - switch (o.type) { - case "GeometryCollection": o.geometries.forEach(quantizeGeometry); break; - case "Point": quantizePoint(o.coordinates); break; - case "MultiPoint": o.coordinates.forEach(quantizePoint); break; - } - } + resid = Math.sqrt(resid); + } while(iter++ < itermax && resid > tol); - topology.arcs.forEach(function(arc) { - var i = 1, - j = 1, - n = arc.length, - pi = arc[0], - x0 = pi[0] = Math.round((pi[0] - dx) / kx), - y0 = pi[1] = Math.round((pi[1] - dy) / ky), - pj, - x1, - y1; + _$lib_601.log('Smoother converged to', resid, 'after', iter, 'iterations'); - for (; i < n; ++i) { - pi = arc[i]; - x1 = Math.round((pi[0] - dx) / kx); - y1 = Math.round((pi[1] - dy) / ky); - if (x1 !== x0 || y1 !== y0) { - pj = arc[j++]; - pj[0] = x1 - x0, x0 = x1; - pj[1] = y1 - y0, y0 = y1; - } - } + return data; +}; - if (j < 2) { - pj = arc[j++]; - pj[0] = 0; - pj[1] = 0; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - arc.length = j; - }); +'use strict'; - for (name in topology.objects) { - quantizeGeometry(topology.objects[name]); - } +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; - topology.transform = { - scale: [kx, ky], - translate: [dx, dy] - }; +var _$clean2dArray_837 = function clean2dArray(zOld, transpose) { + var rowlen, collen, getCollen, old2new, i, j; - return topology; -}; + function cleanZvalue(v) { + if(!_$fastIsnumeric_196(v)) return undefined; + return +v; + } -var untransform = function(topology) { - if ((transform = topology.transform) == null) return identity; - var transform, - x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - var x1 = Math.round((point[0] - dx) / kx), - y1 = Math.round((point[1] - dy) / ky); - point[0] = x1 - x0, x0 = x1; - point[1] = y1 - y0, y0 = y1; - return point; - }; -}; + if(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]; }; + } -exports.bbox = bbox; -exports.feature = feature; -exports.mesh = mesh; -exports.meshArcs = meshArcs; -exports.merge = merge; -exports.mergeArcs = mergeArcs; -exports.neighbors = neighbors; -exports.quantize = quantize; -exports.transform = transform; -exports.untransform = untransform; + var zNew = new Array(rowlen); -Object.defineProperty(exports, '__esModule', { value: true }); + for(i = 0; i < rowlen; i++) { + collen = getCollen(zOld, i); + zNew[i] = new Array(collen); + for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); + } -}))); + return zNew; +}; -_$topojsonClient_355 = _$topojsonClient_355.exports -var _$constants_613 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49642,173 +52293,74 @@ var _$constants_613 = {}; * LICENSE file in the root directory of this source tree. */ -'use strict'; -// projection names to d3 function name -_$constants_613.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' -}; +'use strict'; -// name of the axes -_$constants_613.axesNames = ['lonaxis', 'lataxis']; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_839 = _$numerical_578.BADNUM; -// max longitudinal angular span (EXPERIMENTAL) -_$constants_613.lonaxisSpan = { - 'orthographic': 180, - 'azimuthal equal area': 360, - 'azimuthal equidistant': 360, - 'conic conformal': 180, - 'gnomonic': 160, - 'stereographic': 180, - 'transverse mercator': 180, - '*': 360 -}; +var _$convertColumnData_839 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { + var col1 = trace[var1Name].slice(), + col2 = trace[var2Name].slice(), + textCol = trace.text, + colLen = Math.min(col1.length, col2.length), + hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), + col1Calendar = trace[var1Name + 'calendar'], + col2Calendar = trace[var2Name + 'calendar']; -// max latitudinal angular span (EXPERIMENTAL) -_$constants_613.lataxisSpan = { - 'conic conformal': 150, - 'stereographic': 179.5, - '*': 180 -}; + var i, j, arrayVar, newArray, arrayVarName; -// defaults for each scope -_$constants_613.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] + for(i = 0; i < arrayVarNames.length; i++) { + arrayVar = trace[arrayVarNames[i]]; + if(arrayVar) colLen = Math.min(colLen, arrayVar.length); } -}; - -// angular pad to avoid rounding error around clip angles -_$constants_613.clipPad = 1e-3; -// map projection precision -_$constants_613.precision = 0.1; + if(colLen < col1.length) col1 = col1.slice(0, colLen); + if(colLen < col2.length) col2 = col2.slice(0, colLen); -// default land and water fill colors -_$constants_613.landColor = '#F0DC82'; -_$constants_613.waterColor = '#3399FF'; + for(i = 0; i < colLen; i++) { + col1[i] = ax1.d2c(col1[i], 0, col1Calendar); + col2[i] = ax2.d2c(col2[i], 0, col2Calendar); + } -// locationmode to layer name -_$constants_613.locationmodeToLayer = { - 'ISO-3': 'countries', - 'USA-states': 'subunits', - 'country names': 'countries' -}; + var col1dv = _$lib_601.distinctVals(col1), + col1vals = col1dv.vals, + col2dv = _$lib_601.distinctVals(col2), + col2vals = col2dv.vals, + newArrays = []; -// SVG element for a sphere (use to frame maps) -_$constants_613.sphereSVG = {type: 'Sphere'}; + for(i = 0; i < arrayVarNames.length; i++) { + newArrays[i] = _$lib_601.init2dArray(col2vals.length, col1vals.length); + } -// N.B. base layer names must be the same as in the topojson files + var i1, i2, text; -// base layer with a fill color -_$constants_613.fillLayers = { - ocean: 1, - land: 1, - lakes: 1 -}; + if(hasColumnText) text = _$lib_601.init2dArray(col2vals.length, col1vals.length); -// base layer with a only a line color -_$constants_613.lineLayers = { - subunits: 1, - countries: 1, - coastlines: 1, - rivers: 1, - frame: 1 -}; + for(i = 0; i < colLen; i++) { + if(col1[i] !== __BADNUM_839 && col2[i] !== __BADNUM_839) { + i1 = _$lib_601.findBin(col1[i] + col1dv.minDiff / 2, col1vals); + i2 = _$lib_601.findBin(col2[i] + col2dv.minDiff / 2, col2vals); -_$constants_613.layers = [ - 'bg', - 'ocean', 'land', 'lakes', - 'subunits', 'countries', 'coastlines', 'rivers', - 'lataxis', 'lonaxis', 'frame', - 'backplot', - 'frontplot' -]; + for(j = 0; j < arrayVarNames.length; j++) { + arrayVarName = arrayVarNames[j]; + arrayVar = trace[arrayVarName]; + newArray = newArrays[j]; + newArray[i2][i1] = arrayVar[i]; + } -_$constants_613.layersForChoropleth = [ - 'bg', - 'ocean', 'land', - 'subunits', 'countries', 'coastlines', - 'lataxis', 'lonaxis', 'frame', - 'backplot', - 'rivers', 'lakes', - 'frontplot' -]; + if(hasColumnText) text[i2][i1] = textCol[i]; + } + } -_$constants_613.layerNameToAdjective = { - ocean: 'ocean', - land: 'land', - lakes: 'lake', - subunits: 'subunit', - countries: 'country', - coastlines: 'coastline', - rivers: 'river', - frame: 'frame' + trace['_' + var1Name] = col1vals; + trace['_' + var2Name] = col2vals; + for(j = 0; j < arrayVarNames.length; j++) { + trace['_' + arrayVarNames[j]] = newArrays[j]; + } + if(hasColumnText) trace._text = text; }; -var _$topojson_utils_565 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -49817,1643 +52369,874 @@ var _$topojson_utils_565 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var topojsonUtils = _$topojson_utils_565 = {}; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$cheater_basis_780 = require('./cheater_basis'); */; +/* removed: var _$array_minmax_770 = require('./array_minmax'); */; +/* removed: var _$calcGridlines_777 = require('./calc_gridlines'); */; +/* removed: var _$calcLabels_778 = require('./calc_labels'); */; +/* removed: var _$makeClipPath_776 = require('./calc_clippath'); */; +/* removed: var _$clean2dArray_837 = require('../heatmap/clean_2d_array'); */; +/* removed: var _$smoothFill2dArray_795 = require('./smooth_fill_2d_array'); */; +/* removed: var _$has_columns_787 = require('./has_columns'); */; +/* removed: var _$convertColumnData_839 = require('../heatmap/convert_column_xyz'); */; +/* removed: var _$setConvert_794 = require('./set_convert'); */; + +var _$calc_775 = function calc(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis); + var ya = _$axes_647.getFromId(gd, trace.yaxis); + var aax = trace.aaxis; + var bax = trace.baxis; + + var x = trace.x; + var y = trace.y; + var cols = []; + if(x && !_$has_columns_787(x)) cols.push('x'); + if(y && !_$has_columns_787(y)) cols.push('y'); -var locationmodeToLayer = _$constants_613.locationmodeToLayer; -var topojsonFeature = _$topojsonClient_355.feature; + if(cols.length) { + _$convertColumnData_839(trace, aax, bax, 'a', 'b', cols); + } + var a = trace._a = trace._a || trace.a; + var b = trace._b = trace._b || trace.b; + x = trace._x || trace.x; + y = trace._y || trace.y; -topojsonUtils.getTopojsonName = function(geoLayout) { - return [ - geoLayout.scope.replace(/ /g, '-'), '_', - geoLayout.resolution.toString(), 'm' - ].join(''); -}; + var t = {}; -topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) { - return topojsonURL + topojsonName + '.json'; -}; + if(trace._cheater) { + var avals = aax.cheatertype === 'index' ? a.length : a; + var bvals = bax.cheatertype === 'index' ? b.length : b; + x = _$cheater_basis_780(avals, bvals, trace.cheaterslope); + } -topojsonUtils.getTopojsonFeatures = function(trace, topojson) { - var layer = locationmodeToLayer[trace.locationmode], - obj = topojson.objects[layer]; + trace._x = x = _$clean2dArray_837(x); + trace._y = y = _$clean2dArray_837(y); - return topojsonFeature(topojson, obj).features; -}; + // Fill in any undefined values with elliptic smoothing. This doesn't take + // into account the spacing of the values. That is, the derivatives should + // be modified to use a and b values. It's not that hard, but this is already + // moderate overkill for just filling in missing values. + _$smoothFill2dArray_795(x, a, b); + _$smoothFill2dArray_795(y, a, b); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + _$setConvert_794(trace); + + // create conversion functions that depend on the data + trace.setScale(); -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// + // This is a rather expensive scan. Nothing guarantees monotonicity, + // so we need to scan through all data to get proper ranges: + var xrange = _$array_minmax_770(x); + var yrange = _$array_minmax_770(y); -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + var dx = 0.5 * (xrange[1] - xrange[0]); + var xc = 0.5 * (xrange[1] + xrange[0]); - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + var dy = 0.5 * (yrange[1] - yrange[0]); + var yc = 0.5 * (yrange[1] + yrange[0]); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + // Expand the axes to fit the plot, except just grow it by a factor of 1.3 + // because the labels should be taken into account except that's difficult + // hence 1.3. + var grow = 1.3; + xrange = [xc - dx * grow, xc + dx * grow]; + yrange = [yc - dy * grow, yc + dy * grow]; -var _$BuildLog_296 = BuildLog; + _$axes_647.expand(xa, xrange, {padded: true}); + _$axes_647.expand(ya, yrange, {padded: true}); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // Enumerate the gridlines, both major and minor, and store them on the trace + // object: + _$calcGridlines_777(trace, 'a', 'b'); + _$calcGridlines_777(trace, 'b', 'a'); -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + // Calculate the text labels for each major gridline and store them on the + // trace object: + _$calcLabels_778(trace, aax); + _$calcLabels_778(trace, bax); -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // Tabulate points for the four segments that bound the axes so that we can + // map to pixel coordinates in the plot function and create a clip rect: + t.clipsegments = _$makeClipPath_776(trace._xctrl, trace._yctrl, aax, bax); - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + t.x = x; + t.y = y; + t.a = a; + t.b = b; - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + return [t]; +}; - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident +'use strict'; - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; +/* removed: var _$attributes_771 = require('./attributes'); */; - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; +var addOpacity = _$color_473.addOpacity; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../../plots/cartesian/tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_651 = require('../../plots/cartesian/category_order_defaults'); */; +/* removed: var _$setConvert_665 = require('../../plots/cartesian/set_convert'); */; +/* removed: var _$autoType_648 = require('../../plots/cartesian/axis_autotype'); */; - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; +/** + * options: object containing: + * + * letter: 'a' or 'b' + * title: name of the axis (ie 'Colorbar') to go in default title + * name: axis object name (ie 'xaxis') if one should be stored + * font: the default font to inherit + * outerTicks: boolean, should ticks default to outside? + * showGrid: boolean, should gridlines be shown by default? + * data: the plot data to use in choosing auto type + * bgColor: the plot background color, to calculate default gridline colors + */ +var _$handleAxisDefaults_774 = function handleAxisDefaults(containerIn, containerOut, options) { + var letter = options.letter, + font = options.font || {}, + attributes = _$attributes_771[letter + 'axis']; - // categorize where intersection point is along A and B + function coerce(attr, dflt) { + return _$lib_601.coerce(containerIn, containerOut, attributes, attr, dflt); + } - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + function coerce2(attr, dflt) { + return _$lib_601.coerce2(containerIn, containerOut, attributes, attr, dflt); + } - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + // set up some private properties + if(options.name) { + containerOut._name = options.name; + containerOut._id = options.name; + } - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + // now figure out type and do some more initialization + var axType = coerce('type'); + if(axType === '-') { + if(options.data) __setAutoType_774(containerOut, options.data); - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + axType = containerIn.type = containerOut.type; + } + } - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; -} + coerce('smoothing'); + coerce('cheatertype'); -var _$Epsilon_297 = Epsilon; + coerce('showticklabels'); + coerce('labelprefix', letter + ' = '); + coerce('labelsuffix'); + coerce('showtickprefix'); + coerce('showticksuffix'); -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + coerce('separatethousands'); + coerce('tickformat'); + coerce('exponentformat'); + coerce('showexponent'); + coerce('categoryorder'); -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + coerce('tickmode'); + coerce('tickvals'); + coerce('ticktext'); + coerce('tick0'); + coerce('dtick'); -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + if(containerOut.tickmode === 'array') { + coerce('arraytick0'); + coerce('arraydtick'); + } - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + coerce('labelpadding'); - // 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] }); - } + containerOut._hovertitle = letter; - // 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]))); + if(axType === 'date') { + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); + } - return out; - } + // we need some of the other functions setConvert attaches, but for + // path finding, override pixel scaling to simple passthrough (identity) + _$setConvert_665(containerOut, options.fullLayout); + containerOut.c2p = _$lib_601.identity; - 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'); - }, + var dfltColor = coerce('color', options.dfltColor); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; - // 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)); + coerce('title'); + _$lib_601.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); - // 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); - } + coerce('titleoffset'); - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E + coerce('tickangle'); - function newNode(region){ - return { - region: region, - children: [] - }; - } + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - var roots = newNode(null); + if(autoRange) coerce('rangemode'); - 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; - } - } + coerce('range'); + containerOut.cleanRange(); - // 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--; - } - } + coerce('fixedrange'); - // now we can add ourselves - root.children.push(node); - } + _$handleTickValueDefaults_668(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_666(containerIn, containerOut, coerce, axType, options); + _$handleCategoryOrderDefaults_651(containerIn, containerOut, coerce, { + data: options.data, + dataAttr: letter + }); - // 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); - } + var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3)); + var gridWidth = coerce2('gridwidth'); + var showGrid = coerce('showgrid'); - // 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 + if(!showGrid) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; + } - // while we're at it, exteriors are counter-clockwise, and interiors are clockwise + var startLineColor = coerce2('startlinecolor', dfltColor); + var startLineWidth = coerce2('startlinewidth', gridWidth); + var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth); - 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; - } + if(!showStartLine) { + delete containerOut.startlinecolor; + delete containerOut.startlinewidth; + } - var geopolys = []; + var endLineColor = coerce2('endlinecolor', dfltColor); + var endLineWidth = coerce2('endlinewidth', gridWidth); + var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth); - 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])); - } + if(!showEndLine) { + delete containerOut.endlinecolor; + delete containerOut.endlinewidth; + } - 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); - } + if(!showGrid) { + delete containerOut.gridcolor; + delete containerOut.gridWidth; + } else { + coerce('minorgridcount'); + coerce('minorgridwidth', gridWidth); + coerce('minorgridcolor', addOpacity(gridColor, 0.06)); - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); + if(!containerOut.minorgridcount) { + delete containerOut.minorgridwidth; + delete containerOut.minorgridcolor; + } + } - // lastly, construct the approrpriate GeoJSON object + if(containerOut.showticklabels === 'none') { + delete containerOut.tickfont; + delete containerOut.tickangle; + delete containerOut.showexponent; + delete containerOut.exponentformat; + delete containerOut.tickformat; + delete containerOut.showticksuffix; + delete containerOut.showtickprefix; + } - 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 - }; - } -}; + if(!containerOut.showticksuffix) { + delete containerOut.ticksuffix; + } -var _$GeoJSON_298 = GeoJSON; + if(!containerOut.showtickprefix) { + delete containerOut.tickprefix; + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // It needs to be coerced, then something above overrides this deep in the axis code, + // but no, we *actually* want to coerce this. + coerce('tickmode'); -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + if(!containerOut.title || (containerOut.title && containerOut.title.length === 0)) { + delete containerOut.titlefont; + delete containerOut.titleoffset; + } -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } + return containerOut; }; -var _$LinkedList_300 = LinkedList; - -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +function __setAutoType_774(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; -// -// this is the core work-horse -// + var id = ax._id, + axLetter = id.charAt(0); -/* removed: var _$LinkedList_300 = require('./linked-list'); */; + var calAttr = axLetter + 'calendar', + calendar = ax[calAttr]; -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm + ax.type = _$autoType_648(data, calendar); +} - // - // segment creation - // +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } +'use strict'; - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } +/* removed: var _$handleAxisDefaults_774 = require('./axis_defaults'); */; - // - // event logic - // +var _$handleABDefaults_769 = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) { + var a = coerce('a'); - var event_root = _$LinkedList_300.create(); + if(!a) { + coerce('da'); + coerce('a0'); + } - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same + var b = coerce('b'); - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + if(!b) { + coerce('db'); + coerce('b0'); + } - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor); - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + return; +}; - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } +function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) { + var axesList = ['aaxis', 'baxis']; - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_300.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } + axesList.forEach(function(axName) { + var axLetter = axName.charAt(0); + var axIn = traceIn[axName] || {}; + var axOut = {}; - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_300.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + var defaultOptions = { + tickfont: 'x', + id: axLetter + 'axis', + letter: axLetter, + font: traceOut.font, + name: axName, + data: traceIn[axLetter], + calendar: traceOut.calendar, + dfltColor: dfltColor, + bgColor: fullLayout.paper_bgcolor, + fullLayout: fullLayout + }; - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + _$handleAxisDefaults_774(axIn, axOut, defaultOptions); - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) + axOut._categories = axOut._categories || []; - if (buildLog) - buildLog.segmentChop(ev.seg, end); + traceOut[axName] = axOut; - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } + // so we don't have to repeat autotype unnecessarily, + // copy an autotype back to traceIn + if(!traceIn[axName] && axIn.type !== '-') { + traceIn[axName] = {type: axIn.type}; + } + }); +} - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used - // - // status logic - // +'use strict'; - var status_root = _$LinkedList_300.create(); +var _$handleXYDefaults_796 = function handleXYDefaults(traceIn, traceOut, coerce) { + var x = coerce('x'); + var y = coerce('y'); - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; + traceOut._cheater = !x; - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } + return !!x || !!y; +}; - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; +'use strict'; - if (buildLog) - buildLog.checkIntersection(seg1, seg2); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleXYDefaults_796 = require('./xy_defaults'); */; +/* removed: var _$handleABDefaults_769 = require('./ab_defaults'); */; +/* removed: var _$attributes_771 = require('./attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; - var i = eps.linesIntersect(a1, a2, b1, b2); +var _$supplyDefaults_786 = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_771, attr, dflt); + } - if (i === false){ - // segments are parallel or coincident + traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet'; - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) + var defaultColor = coerce('color', _$attributes_472.defaultLine); + _$lib_601.coerceFont(coerce, 'font'); - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection + coerce('carpet'); - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); + _$handleABDefaults_769(traceIn, traceOut, fullLayout, coerce, defaultColor); - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal + if(!traceOut.a || !traceOut.b) { + traceOut.visible = false; + return; + } - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); + if(traceOut.a.length < 3) { + traceOut.aaxis.smoothing = 0; + } - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); + if(traceOut.b.length < 3) { + traceOut.baxis.smoothing = 0; + } - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } + // 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 len = _$handleXYDefaults_796(traceIn, traceOut, coerce); - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + if(traceOut._cheater) { + coerce('cheaterslope'); + } - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + if(!len) { + traceOut.visible = false; + } +}; - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); +'use strict'; - if (buildLog) - buildLog.vert(ev.pt[0]); +var _$makePath_790 = function makePath(xp, yp, isBicubic) { + // Prevent d3 errors that would result otherwise: + if(xp.length === 0) return ''; - if (ev.isStart){ + var i, path = []; + var stride = isBicubic ? 3 : 1; + for(i = 0; i < xp.length; i += stride) { + path.push(xp[i] + ',' + yp[i]); - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + if(isBicubic && i < xp.length - stride) { + path.push('C'); + path.push([ + xp[i + 1] + ',' + yp[i + 1], + xp[i + 2] + ',' + yp[i + 2] + ' ', + ].join(' ')); + } + } + return path.join(isBicubic ? '' : 'L'); +}; - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } +'use strict'; - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } +var __isArrayOrTypedArray_791 = _$lib_601.isArrayOrTypedArray; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev +/* + * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p). + * The output array is optional, but if provided, it will be reused without + * reallocation to the extent possible. + */ +var _$mapArray_791 = function mapArray(out, data, func) { + var i; - // merge ev.seg's fill information into eve.seg + if(!__isArrayOrTypedArray_791(out)) { + // If not an array, make it an array: + out = []; + } else if(out.length > data.length) { + // If too long, truncate. (If too short, it will grow + // automatically so we don't care about that case) + out = out.slice(0, data.length); + } - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + for(i = 0; i < data.length; i++) { + out[i] = func(data[i]); + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } + return out; +}; - if (buildLog) - buildLog.segmentUpdate(eve.seg); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - ev.other.remove(); - ev.remove(); - } - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } +'use strict'; - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle +var _$orientText_792 = 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; - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } + 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); + } - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + var angle = Math.atan2(dy, dx) * 180 / Math.PI; + if(angle < -90) { + angle += 180; + flip = -flip; + } else if(angle > 90) { + angle -= 180; + flip = -flip; + } - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + return { + angle: angle, + flip: flip, + p: trace.c2p(xy, xaxis, yaxis), + offsetMultplier: offsetMultiplier + }; +}; - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_300.node({ ev: ev })); - } - else{ - var st = ev.status; - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } +'use strict'; - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$mapArray_791 = require('./map_1d_array'); */; +/* removed: var _$makePath_790 = require('./makepath'); */; +/* removed: var _$orientText_792 = require('./orient_text'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; - if (buildLog) - buildLog.statusRemove(st.ev.seg); +var _$plot_793 = function plot(gd, plotinfo, cdcarpet) { + for(var i = 0; i < cdcarpet.length; i++) { + __plotOne_793(gd, plotinfo, cdcarpet[i]); + } +}; - // remove the status - st.remove(); +function __plotOne_793(gd, plotinfo, cd) { + var t = cd[0]; + var trace = cd[0].trace, + xa = plotinfo.xaxis, + ya = plotinfo.yaxis, + aax = trace.aaxis, + bax = trace.baxis, + fullLayout = gd._fullLayout; - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } + var gridLayer = plotinfo.plot.selectAll('.carpetlayer'); + var clipLayer = fullLayout._clips; - // remove the event and continue - event_root.getHead().remove(); - } + var axisLayer = _$lib_601.ensureSingle(gridLayer, 'g', 'carpet' + trace.uid).classed('trace', true); + var minorLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'minorlayer'); + var majorLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'majorlayer'); + var boundaryLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'boundarylayer'); + var labelLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'labellayer'); - if (buildLog) - buildLog.done(); + axisLayer.style('opacity', trace.opacity); - return segments; - } + drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true); + drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true); + drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true); + drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true); - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } + // NB: These are not ommitted if the lines are not active. The joins must be executed + // in order for them to get cleaned up without a full redraw + drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines); + drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines); - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; + var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, aax._labels, 'a-label'); + var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, bax._labels, 'b-label'); - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + drawAxisTitles(gd, labelLayer, trace, t, xa, ya, labelOrientationA, labelOrientationB); - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; + drawClipPath(trace, t, clipLayer, xa, ya); } -var _$Intersecter_299 = Intersecter; - -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +function drawClipPath(trace, t, layer, xaxis, yaxis) { + var seg, xp, yp, i; -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// + var clip = layer.select('#' + trace._clipPathId); -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; + if(!clip.size()) { + clip = layer.append('clipPath') + .classed('carpetclip', true); + } - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } + var path = _$lib_601.ensureSingle(clip, 'path', 'carpetboundary'); + var segments = t.clipsegments; + var segs = []; - if (buildLog) - buildLog.chainStart(seg); + for(i = 0; i < segments.length; i++) { + seg = segments[i]; + xp = _$mapArray_791([], seg.x, xaxis.c2p); + yp = _$mapArray_791([], seg.y, yaxis.c2p); + segs.push(_$makePath_790(xp, yp, seg.bicubic)); + } - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + // This could be optimized ever so slightly to avoid no-op L segments + // at the corners, but it's so negligible that I don't think it's worth + // the extra complexity + var clipPathData = 'M' + segs.join('L') + 'Z'; + clip.attr('id', trace._clipPathId); + path.attr('d', clipPathData); +} - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } +function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines) { + var lineClass = 'const-' + axisLetter + '-lines'; + var gridJoin = layer.selectAll('.' + lineClass).data(gridlines); - if (next_match === second_match){ - // we matched a single chain + gridJoin.enter().append('path') + .classed(lineClass, true) + .style('vector-effect', 'non-scaling-stroke'); - if (buildLog) - buildLog.chainMatch(first_match.index); + gridJoin.each(function(d) { + var gridline = d; + var x = gridline.x; + var y = gridline.y; - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop + var xp = _$mapArray_791([], x, xaxis.c2p); + var yp = _$mapArray_791([], y, yaxis.c2p); - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head + var path = 'M' + _$makePath_790(xp, yp, gridline.smoothing); - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + var el = _$d3_130.select(this); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + el.attr('d', path) + .style('stroke-width', gridline.width) + .style('stroke', gridline.color) + .style('fill', 'none'); + }); - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); + gridJoin.exit().remove(); +} - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } +function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) { + var labelJoin = layer.selectAll('text.' + labelClass).data(labels); - if (buildLog) - buildLog.chainClose(first_match.index); + labelJoin.enter().append('text') + .classed(labelClass, true); - // we have a closed chain! - regions.push(chain); - return; - } + var maxExtent = 0; + var labelOrientation = {}; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } + labelJoin.each(function(label, i) { + // Most of the positioning is done in calc_labels. Only the parts that depend upon + // the screen space representation of the x and y axes are here: + var orientation; + if(label.axis.tickangle === 'auto') { + orientation = _$orientText_792(trace, xaxis, yaxis, label.xy, label.dxy); + } else { + var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0; + orientation = _$orientText_792(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]); + } - // otherwise, we matched two chains, so we need to combine those chains together + if(!i) { + // TODO: offsetMultiplier? Not currently used anywhere... + labelOrientation = {angle: orientation.angle, flip: orientation.flip}; + } + var direction = (label.endAnchor ? -1 : 1) * orientation.flip; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + var labelEl = _$d3_130.select(this) + .attr({ + 'text-anchor': direction > 0 ? 'start' : 'end', + 'data-notex': 1 + }) + .call(_$drawing_498.font, label.font) + .text(label.text) + .call(_$svg_text_utils_625.convertToTspans, gd); - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + var bbox = _$drawing_498.bBox(this); - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + labelEl.attr('transform', + // Translate to the correct point: + 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + + // Rotate to line up with grid line tangent: + 'rotate(' + orientation.angle + ')' + + // Adjust the baseline and indentation: + 'translate(' + label.axis.labelpadding * direction + ',' + bbox.height * 0.3 + ')' + ); - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } + maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding); + }); - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } + labelJoin.exit().remove(); - var F = first_match.index; - var S = second_match.index; + labelOrientation.maxExtent = maxExtent; + return labelOrientation; +} - if (buildLog) - buildLog.chainConnect(F, S); +function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) { + var a, b, xy, dxy; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); + a = 0.5 * (trace.a[0] + trace.a[trace.a.length - 1]); + b = trace.b[0]; + xy = trace.ab2xy(a, b, true); + dxy = trace.dxyda_rough(a, b); + if(labelOrientationA.angle === undefined) { + _$lib_601.extendFlat(labelOrientationA, _$orientText_792(trace, xa, ya, xy, trace.dxydb_rough(a, b))); + } + drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title'); - return regions; + a = trace.a[0]; + b = 0.5 * (trace.b[0] + trace.b[trace.b.length - 1]); + xy = trace.ab2xy(a, b, true); + dxy = trace.dxydb_rough(a, b); + if(labelOrientationB.angle === undefined) { + _$lib_601.extendFlat(labelOrientationB, _$orientText_792(trace, xa, ya, xy, trace.dxyda_rough(a, b))); + } + drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title'); } -var _$SegmentChainer_301 = SegmentChainer; +var lineSpacing = _$alignment_573.LINE_SPACING; +var midShift = ((1 - _$alignment_573.MID_SHIFT) / lineSpacing) + 1; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) { + var data = []; + if(axis.title) data.push(axis.title); + var titleJoin = layer.selectAll('text.' + labelClass).data(data); + var offset = labelOrientation.maxExtent; -// -// filter a list of segments based on boolean operations -// + titleJoin.enter().append('text') + .classed(labelClass, true); -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + // There's only one, but we'll do it as a join so it's updated nicely: + titleJoin.each(function() { + var orientation = _$orientText_792(trace, xa, ya, xy, dxy); - if (buildLog) - buildLog.selected(result); + if(['start', 'both'].indexOf(axis.showticklabels) === -1) { + offset = 0; + } - return result; -} + // In addition to the size of the labels, add on some extra padding: + var titleSize = axis.titlefont.size; + offset += titleSize + axis.titleoffset; -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } -}; + var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0); + var angleDiff = (labelNorm - orientation.angle + 450) % 360; + var reverseTitle = angleDiff > 90 && angleDiff < 270; -var _$SegmentSelector_302 = SegmentSelector; + var el = _$d3_130.select(this); -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs - */ + el.text(axis.title || '') + .call(_$svg_text_utils_625.convertToTspans, gd); -/* removed: var _$BuildLog_296 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_297 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_299 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_301 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_302 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_298 = require('./lib/geojson'); */; + if(reverseTitle) { + offset = (-_$svg_text_utils_625.lineCount(el) + midShift) * lineSpacing * titleSize - offset; + } -var buildLog = false; -var epsilon = _$Epsilon_297(); + el.attr('transform', + 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + + 'rotate(' + orientation.angle + ') ' + + 'translate(0,' + offset + ')' + ) + .classed('user-select-none', true) + .attr('text-anchor', 'middle') + .call(_$drawing_498.font, axis.titlefont); + }); -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_296(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + titleJoin.exit().remove(); +} - // core API - segments: function(poly){ - var i = _$Intersecter_299(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_299(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_302.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_302.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_302.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_302.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_302.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_301(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_298.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_298.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); - } -}; +'use strict'; -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); -} +var Carpet = {}; -if (typeof window === 'object') - window.PolyBool = PolyBool; +Carpet.attributes = _$attributes_771; +Carpet.supplyDefaults = _$supplyDefaults_786; +Carpet.plot = _$plot_793; +Carpet.calc = _$calc_775; +Carpet.animatable = true; +Carpet.isContainer = true; // so carpet traces get `calc` before other traces + +Carpet.moduleType = 'trace'; +Carpet.name = 'carpet'; +Carpet.basePlotModule = _$cartesian_658; +Carpet.categories = ['cartesian', 'svg', 'carpet', 'carpetAxis', 'notLegendIsolatable']; +Carpet.meta = { + description: [ + 'The data describing carpet axis layout is set in `y` and (optionally)', + 'also `x`. If only `y` is present, `x` the plot is interpreted as a', + 'cheater plot and is filled in using the `y` values.', + + '`x` and `y` may either be 2D arrays matching with each dimension matching', + 'that of `a` and `b`, or they may be 1D arrays with total length equal to', + 'that of `a` and `b`.' + ].join(' ') +}; -var _$PolyBool_295 = PolyBool; +var _$Carpet_788 = Carpet; -var _$polygon_551 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -51462,686 +53245,741 @@ var _$polygon_551 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var dot = _$matrix_545.dot; -var __BADNUM_551 = _$numerical_517.BADNUM; +var _$carpet_8 = _$Carpet_788; -var polygon = _$polygon_551 = {}; +var _$topojsonClient_417 = { exports: {} }; +// https://github.com/topojson/topojson-client Version 2.1.0. Copyright 2016 Mike Bostock. +(function (global, factory) { + typeof _$topojsonClient_417.exports === 'object' && "object" !== 'undefined' ? factory(_$topojsonClient_417.exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.topojson = global.topojson || {}))); +}(this, (function (exports) { 'use strict'; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); +var identity = function(x) { + return x; +}; + +var transform = function(topology) { + if ((transform = topology.transform) == null) return identity; + var transform, + x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + point[0] = (x0 += point[0]) * kx + dx; + point[1] = (y0 += point[1]) * ky + dy; + return point; + }; +}; + +var bbox = function(topology) { + var bbox = topology.bbox; + + function bboxPoint(p0) { + p1[0] = p0[0], p1[1] = p0[1], t(p1); + if (p1[0] < x0) x0 = p1[0]; + if (p1[0] > x1) x1 = p1[0]; + if (p1[1] < y0) y0 = p1[1]; + if (p1[1] > y1) y1 = p1[1]; + } + + function bboxGeometry(o) { + switch (o.type) { + case "GeometryCollection": o.geometries.forEach(bboxGeometry); break; + case "Point": bboxPoint(o.coordinates); break; + case "MultiPoint": o.coordinates.forEach(bboxPoint); break; + } + } + + if (!bbox) { + var t = transform(topology), p0, p1 = new Array(2), name, + x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0; + + topology.arcs.forEach(function(arc) { + var i = -1, n = arc.length; + while (++i < n) { + p0 = arc[i], p1[0] = p0[0], p1[1] = p0[1], t(p1, i); + if (p1[0] < x0) x0 = p1[0]; + if (p1[0] > x1) x1 = p1[0]; + if (p1[1] < y0) y0 = p1[1]; + if (p1[1] > y1) y1 = p1[1]; + } + }); + + for (name in topology.objects) { + bboxGeometry(topology.objects[name]); + } + + bbox = topology.bbox = [x0, y0, x1, y1]; + } + + return bbox; +}; + +var reverse = function(array, n) { + var t, j = array.length, i = j - n; + while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; +}; + +var feature = function(topology, o) { + return o.type === "GeometryCollection" + ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })} + : feature$1(topology, o); +}; + +function feature$1(topology, o) { + var id = o.id, + bbox = o.bbox, + properties = o.properties == null ? {} : o.properties, + geometry = object(topology, o); + return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} + : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} + : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; +} + +function object(topology, o) { + var transformPoint = transform(topology), + arcs = topology.arcs; + + function arc(i, points) { + if (points.length) points.pop(); + for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { + points.push(transformPoint(a[k].slice(), k)); + } + if (i < 0) reverse(points, n); + } - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; + function point(p) { + return transformPoint(p.slice()); + } - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } + function line(arcs) { + var points = []; + for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); + if (points.length < 2) points.push(points[0].slice()); + return points; + } - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed + function ring(arcs) { + var points = line(arcs); + while (points.length < 4) points.push(points[0].slice()); + return points; + } - var isRect = false, - rectFirstEdgeTest; + function polygon(arcs) { + return arcs.map(ring); + } - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } - } + function geometry(o) { + var type = o.type, coordinates; + switch (type) { + case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; + case "Point": coordinates = point(o.coordinates); break; + case "MultiPoint": coordinates = o.coordinates.map(point); break; + case "LineString": coordinates = line(o.arcs); break; + case "MultiLineString": coordinates = o.arcs.map(line); break; + case "Polygon": coordinates = polygon(o.arcs); break; + case "MultiPolygon": coordinates = o.arcs.map(polygon); break; + default: return null; } + return {type: type, coordinates: coordinates}; + } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + return geometry(o); +} - if(x === __BADNUM_551 || x < xmin || x > xmax || y === __BADNUM_551 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; +var stitch = function(topology, arcs) { + var stitchedArcs = {}, + fragmentByStart = {}, + fragmentByEnd = {}, + fragments = [], + emptyIndex = -1; - return true; + // Stitch empty arcs first, since they may be subsumed by other arcs. + arcs.forEach(function(i, j) { + var arc = topology.arcs[i < 0 ? ~i : i], t; + if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { + t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; } + }); - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + arcs.forEach(function(i) { + var e = ends(i), + start = e[0], + end = e[1], + f, g; - if(x === __BADNUM_551 || x < xmin || x > xmax || y === __BADNUM_551 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + if (f = fragmentByEnd[start]) { + delete fragmentByEnd[f.end]; + f.push(i); + f.end = end; + if (g = fragmentByStart[end]) { + delete fragmentByStart[g.start]; + var fg = g === f ? f : f.concat(g); + fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else if (f = fragmentByStart[end]) { + delete fragmentByStart[f.start]; + f.unshift(i); + f.start = start; + if (g = fragmentByEnd[start]) { + delete fragmentByEnd[g.end]; + var gf = g === f ? f : g.concat(f); + fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else { + f = [i]; + fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; + } + }); - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + function ends(i) { + var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; + if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); + else p1 = arc[arc.length - 1]; + return i < 0 ? [p1, p0] : [p0, p1]; + } - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + function flush(fragmentByEnd, fragmentByStart) { + for (var k in fragmentByEnd) { + var f = fragmentByEnd[k]; + delete fragmentByStart[f.start]; + delete f.start; + delete f.end; + f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); + fragments.push(f); + } + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; - } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; - } - // inside the bounding box, check the actual line intercept - else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); + flush(fragmentByEnd, fragmentByStart); + flush(fragmentByStart, fragmentByEnd); + arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } + return fragments; +}; - if(y <= ycross && x !== xmini) crossings++; - } - } +var mesh = function(topology) { + return object(topology, meshArcs.apply(this, arguments)); +}; - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } +function meshArcs(topology, object$$1, filter) { + var arcs, i, n; + if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter); + else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i; + return {type: "MultiLineString", arcs: stitch(topology, arcs)}; +} - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; - } - } +function extractArcs(topology, object$$1, filter) { + var arcs = [], + geomsByArc = [], + geom; - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; + function extract0(i) { + var j = i < 0 ? ~i : i; + (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); + } -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; + function extract1(arcs) { + arcs.forEach(extract0); + } - for(var i = 0; i < list.length; i++) { - 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); - } + function extract2(arcs) { + arcs.forEach(extract1); + } - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; - } - } + function extract3(arcs) { + arcs.forEach(extract2); + } - return yes; + function geometry(o) { + switch (geom = o, o.type) { + case "GeometryCollection": o.geometries.forEach(geometry); break; + case "LineString": extract1(o.arcs); break; + case "MultiLineString": case "Polygon": extract2(o.arcs); break; + case "MultiPolygon": extract3(o.arcs); break; } + } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; + geometry(object$$1); -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; + geomsByArc.forEach(filter == null + ? function(geoms) { arcs.push(geoms[0].i); } + : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); + return arcs; +} - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; - } - return false; -}; +function planarRingArea(ring) { + var i = -1, n = ring.length, a, b = ring[n - 1], area = 0; + while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0]; + return Math.abs(area); // Note: doubled area! +} -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; +var merge = function(topology) { + return object(topology, mergeArcs.apply(this, arguments)); +}; - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); +function mergeArcs(topology, objects) { + var polygonsByArc = {}, + polygons = [], + groups = []; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; - } - } - } + objects.forEach(geometry); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); + function geometry(o) { + switch (o.type) { + case "GeometryCollection": o.geometries.forEach(geometry); break; + case "Polygon": extract(o.arcs); break; + case "MultiPolygon": o.arcs.forEach(extract); break; } + } - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function extract(polygon) { + polygon.forEach(function(ring) { + ring.forEach(function(arc) { + (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); + }); + }); + polygons.push(polygon); + } + function area(ring) { + return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]); + } -'use strict'; + polygons.forEach(function(polygon) { + if (!polygon._) { + var group = [], + neighbors = [polygon]; + polygon._ = 1; + groups.push(group); + while (polygon = neighbors.pop()) { + group.push(polygon); + polygon.forEach(function(ring) { + ring.forEach(function(arc) { + polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { + if (!polygon._) { + polygon._ = 1; + neighbors.push(polygon); + } + }); + }); + }); + } + } + }); -/* removed: var _$PolyBool_295 = require('polybooljs'); */; -/* removed: var _$polygon_551 = require('../../lib/polygon'); */; -/* removed: var _$throttle_563 = require('../../lib/throttle'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -var makeEventData = _$helpers_450.makeEventData; -/* removed: var _$fx_453 = require('../../components/fx'); */; + polygons.forEach(function(polygon) { + delete polygon._; + }); -/* removed: var _$axes_584 = require('./axes'); */; -/* removed: var _$constants_589 = require('./constants'); */; + return { + type: "MultiPolygon", + arcs: groups.map(function(polygons) { + var arcs = [], n; -var filteredPolygon = _$polygon_551.filter; -var polygonTester = _$polygon_551.tester; -var multipolygonTester = _$polygon_551.multitester; -var MINSELECT = _$constants_589.MINSELECT; + // Extract the exterior (unique) arcs. + polygons.forEach(function(polygon) { + polygon.forEach(function(ring) { + ring.forEach(function(arc) { + if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { + arcs.push(arc); + } + }); + }); + }); -function getAxId(ax) { return ax._id; } + // Stitch the arcs into one or more rings. + arcs = stitch(topology, arcs); -var _$prepSelect_602 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } + // If more than one ring is returned, + // at most one of these rings can be the exterior; + // choose the one with the greatest absolute area. + if ((n = arcs.length) > 1) { + for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { + if ((ki = area(arcs[i])) > k) { + t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; + } + } + } - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_589.BENDPX); - } - var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); + return arcs; + }) + }; +} - 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 bisect = function(a, x) { + var lo = 0, hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; + } + return lo; +}; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_411.background, - stroke: _$color_411.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +var neighbors = function(objects) { + var indexesByArc = {}, // arc index -> array of object indexes + neighbors = objects.map(function() { return []; }); + function line(arcs, i) { + arcs.forEach(function(a) { + if (a < 0) a = ~a; + var o = indexesByArc[a]; + if (o) o.push(i); + else indexesByArc[a] = [i]; + }); + } - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_589.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; + function polygon(arcs, i) { + arcs.forEach(function(arc) { line(arc, 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; + function geometry(o, i) { + if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); + else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + } - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } + }; - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_584.getFromId(gd, trace.xaxis), - yaxis: _$axes_584.getFromId(gd, trace.yaxis) - }); - } - } + objects.forEach(geometry); - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + for (var i in indexesByArc) { + for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { + for (var k = j + 1; k < m; ++k) { + var ij = indexes[j], ik = indexes[k], n; + if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); + if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); + } } + } - function ascending(a, b) { return a - b; } + return neighbors; +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +var quantize = function(topology, n) { + if (!((n = Math.floor(n)) >= 2)) throw new Error("n must be ≥2"); + if (topology.transform) throw new Error("already quantized"); + var bb = bbox(topology), name, + dx = bb[0], kx = (bb[2] - dx) / (n - 1) || 1, + dy = bb[1], ky = (bb[3] - dy) / (n - 1) || 1; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; + function quantizePoint(p) { + p[0] = Math.round((p[0] - dx) / kx); + p[1] = Math.round((p[1] - dy) / ky); + } - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); + function quantizeGeometry(o) { + switch (o.type) { + case "GeometryCollection": o.geometries.forEach(quantizeGeometry); break; + case "Point": quantizePoint(o.coordinates); break; + case "MultiPoint": o.coordinates.forEach(quantizePoint); break; + } + } - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; + topology.arcs.forEach(function(arc) { + var i = 1, + j = 1, + n = arc.length, + pi = arc[0], + x0 = pi[0] = Math.round((pi[0] - dx) / kx), + y0 = pi[1] = Math.round((pi[1] - dy) / ky), + pj, + x1, + y1; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } + for (; i < n; ++i) { + pi = arc[i]; + x1 = Math.round((pi[0] - dx) / kx); + y1 = Math.round((pi[1] - dy) / ky); + if (x1 !== x0 || y1 !== y0) { + pj = arc[j++]; + pj[0] = x1 - x0, x0 = x1; + pj[1] = y1 - y0, y0 = y1; + } } - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); + if (j < 2) { + pj = arc[j++]; + pj[0] = 0; + pj[1] = 0; + } - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); + arc.length = j; + }); - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); + for (name in topology.objects) { + quantizeGeometry(topology.objects[name]); + } - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } + topology.transform = { + scale: [kx, ky], + translate: [dx, dy] + }; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } + return topology; +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +var untransform = function(topology) { + if ((transform = topology.transform) == null) return identity; + var transform, + x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + var x1 = Math.round((point[0] - dx) / kx), + y1 = Math.round((point[1] - dy) / ky); + point[0] = x1 - x0, x0 = x1; + point[1] = y1 - y0, y0 = y1; + return point; + }; +}; - _$throttle_563.throttle( - throttleID, - _$constants_589.SELECTDELAY, - function() { - selection = []; +exports.bbox = bbox; +exports.feature = feature; +exports.mesh = mesh; +exports.meshArcs = meshArcs; +exports.merge = merge; +exports.mergeArcs = mergeArcs; +exports.neighbors = neighbors; +exports.quantize = quantize; +exports.transform = transform; +exports.untransform = untransform; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; +Object.defineProperty(exports, '__esModule', { value: true }); - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); +}))); - thisSelection = fillSelectionItem(traceSelection, searchInfo); +_$topojsonClient_417 = _$topojsonClient_417.exports +var _$constants_675 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); - } - } - else selection = thisSelection; - } +'use strict'; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; +// projection names to d3 function name +_$constants_675.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' +}; - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); +// name of the axes +_$constants_675.axesNames = ['lonaxis', 'lataxis']; - _$throttle_563.done(throttleID).then(function() { - _$throttle_563.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); - } +// max longitudinal angular span (EXPERIMENTAL) +_$constants_675.lonaxisSpan = { + 'orthographic': 180, + 'azimuthal equal area': 360, + 'azimuthal equidistant': 360, + 'conic conformal': 180, + 'gnomonic': 160, + 'stereographic': 180, + 'transverse mercator': 180, + '*': 360 +}; - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); - } - else { - // 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. - gd.emit('plotly_selected', undefined); - } +// max latitudinal angular span (EXPERIMENTAL) +_$constants_675.lataxisSpan = { + 'conic conformal': 150, + 'stereographic': 179.5, + '*': 180 +}; - _$fx_453.click(gd, evt); - }); - }; +// defaults for each scope +_$constants_675.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] + } +}; - dragOptions.doneFn = function() { - corners.remove(); +// angular pad to avoid rounding error around clip angles +_$constants_675.clipPad = 1e-3; - _$throttle_563.done(throttleID).then(function() { - _$throttle_563.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); +// map projection precision +_$constants_675.precision = 0.1; - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +// default land and water fill colors +_$constants_675.landColor = '#F0DC82'; +_$constants_675.waterColor = '#3399FF'; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +// locationmode to layer name +_$constants_675.locationmodeToLayer = { + 'ISO-3': 'countries', + 'USA-states': 'subunits', + 'country names': 'countries' }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +// SVG element for a sphere (use to frame maps) +_$constants_675.sphereSVG = {type: 'Sphere'}; - if(eventData) { - var pts = eventData.points || []; +// N.B. base layer names must be the same as in the topojson files - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +// base layer with a fill color +_$constants_675.fillLayers = { + ocean: 1, + land: 1, + lakes: 1 +}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; +// base layer with a only a line color +_$constants_675.lineLayers = { + subunits: 1, + countries: 1, + coastlines: 1, + rivers: 1, + frame: 1 +}; - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - 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; +_$constants_675.layers = [ + 'bg', + 'ocean', 'land', 'lakes', + 'subunits', 'countries', 'coastlines', 'rivers', + 'lataxis', 'lonaxis', 'frame', + 'backplot', + 'frontplot' +]; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } - } - } +_$constants_675.layersForChoropleth = [ + 'bg', + 'ocean', 'land', + 'subunits', 'countries', 'coastlines', + 'lataxis', 'lonaxis', 'frame', + 'backplot', + 'rivers', 'lakes', + 'frontplot' +]; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } -} +_$constants_675.layerNameToAdjective = { + ocean: 'ocean', + land: 'land', + lakes: 'lake', + subunits: 'subunit', + countries: 'country', + coastlines: 'coastline', + rivers: 'river', + frame: 'frame' +}; -function mergePolygons(list, poly, subtract) { - var res; +var _$topojson_utils_628 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(subtract) { - res = _$PolyBool_295.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); - return res.regions; - } +'use strict'; - res = _$PolyBool_295.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +var topojsonUtils = _$topojson_utils_628 = {}; - return res.regions; -} +var locationmodeToLayer = _$constants_675.locationmodeToLayer; +var topojsonFeature = _$topojsonClient_417.feature; -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); - } - } +topojsonUtils.getTopojsonName = function(geoLayout) { + return [ + geoLayout.scope.replace(/ /g, '-'), '_', + geoLayout.resolution.toString(), 'm' + ].join(''); +}; - return selection; -} +topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) { + return topojsonURL + topojsonName + '.json'; +}; + +topojsonUtils.getTopojsonFeatures = function(trace, topojson) { + var layer = locationmodeToLayer[trace.locationmode], + obj = topojson.objects[layer]; + + return topojsonFeature(topojson, obj).features; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -52586,7 +54424,7 @@ function addProjectionsToD3(d3) { }).raw = winkel3; } -var _$addProjectionsToD3_619 = addProjectionsToD3; +var _$addProjectionsToD3_681 = addProjectionsToD3; /** * Copyright 2012-2018, Plotly, Inc. @@ -52599,8 +54437,8 @@ var _$addProjectionsToD3_619 = addProjectionsToD3; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; var radians = Math.PI / 180; var degrees = 180 / Math.PI; @@ -52624,11 +54462,11 @@ function createGeoZoom(geo, geoLayout) { return zoomConstructor(geo, projection); } -var _$createGeoZoom_620 = createGeoZoom; +var _$createGeoZoom_682 = createGeoZoom; // common to all zoom types function initZoom(geo, projection) { - return _$d3_127.behavior.zoom() + return _$d3_130.behavior.zoom() .translate(projection.translate()) .scale(projection.scale()); } @@ -52643,11 +54481,11 @@ function sync(geo, projection, cb) { var eventData = {}; function set(propStr, val) { - var fullNp = _$lib_539.nestedProperty(fullOpts, propStr); + var fullNp = _$lib_601.nestedProperty(fullOpts, propStr); if(fullNp.get() !== val) { fullNp.set(val); - _$lib_539.nestedProperty(userOpts, propStr).set(val); + _$lib_601.nestedProperty(userOpts, propStr).set(val); eventData[id + '.' + propStr] = val; } } @@ -52662,13 +54500,13 @@ function zoomScoped(geo, projection) { var zoom = initZoom(geo, projection); function handleZoomstart() { - _$d3_127.select(this).style(zoomstartStyle); + _$d3_130.select(this).style(zoomstartStyle); } function handleZoom() { projection - .scale(_$d3_127.event.scale) - .translate(_$d3_127.event.translate); + .scale(_$d3_130.event.scale) + .translate(_$d3_130.event.translate); geo.render(); } @@ -52680,7 +54518,7 @@ function zoomScoped(geo, projection) { } function handleZoomend() { - _$d3_127.select(this).style(zoomendStyle); + _$d3_130.select(this).style(zoomendStyle); sync(geo, projection, syncCb); } @@ -52710,9 +54548,9 @@ function zoomNonClipped(geo, projection) { } function handleZoomstart() { - _$d3_127.select(this).style(zoomstartStyle); + _$d3_130.select(this).style(zoomstartStyle); - mouse0 = _$d3_127.mouse(this); + mouse0 = _$d3_130.mouse(this); rotate0 = projection.rotate(); translate0 = projection.translate(); lastRotate = rotate0; @@ -52720,7 +54558,7 @@ function zoomNonClipped(geo, projection) { } function handleZoom() { - mouse1 = _$d3_127.mouse(this); + mouse1 = _$d3_130.mouse(this); if(outside(mouse0)) { zoom.scale(projection.scale()); @@ -52728,8 +54566,8 @@ function zoomNonClipped(geo, projection) { return; } - projection.scale(_$d3_127.event.scale); - projection.translate([translate0[0], _$d3_127.event.translate[1]]); + projection.scale(_$d3_130.event.scale); + projection.translate([translate0[0], _$d3_130.event.translate[1]]); if(!zoomPoint) { mouse0 = mouse1; @@ -52746,7 +54584,7 @@ function zoomNonClipped(geo, projection) { } function handleZoomend() { - _$d3_127.select(this).style(zoomendStyle); + _$d3_130.select(this).style(zoomendStyle); sync(geo, projection, syncCb); } @@ -52779,9 +54617,9 @@ function zoomClipped(geo, projection) { var zoomPoint; zoom.on('zoomstart', function() { - _$d3_127.select(this).style(zoomstartStyle); + _$d3_130.select(this).style(zoomstartStyle); - var mouse0 = _$d3_127.mouse(this), + var mouse0 = _$d3_130.mouse(this), rotate0 = projection.rotate(), lastRotate = rotate0, translate0 = projection.translate(), @@ -52790,9 +54628,9 @@ function zoomClipped(geo, projection) { zoomPoint = position(projection, mouse0); zoomOn.call(zoom, 'zoom', function() { - var mouse1 = _$d3_127.mouse(this); + var mouse1 = _$d3_130.mouse(this); - projection.scale(view.k = _$d3_127.event.scale); + projection.scale(view.k = _$d3_130.event.scale); if(!zoomPoint) { // if no zoomPoint, the mouse wasn't over the actual geography yet @@ -52833,7 +54671,7 @@ function zoomClipped(geo, projection) { zoomstarted(event.of(this, arguments)); }) .on('zoomend', function() { - _$d3_127.select(this).style(zoomendStyle); + _$d3_130.select(this).style(zoomendStyle); zoomOn.call(zoom, 'zoom', null); zoomended(event.of(this, arguments)); sync(geo, projection, syncCb); @@ -52860,7 +54698,7 @@ function zoomClipped(geo, projection) { set('projection.rotation.lat', -_rotate[1]); } - return _$d3_127.rebind(zoom, event, 'on'); + return _$d3_130.rebind(zoom, event, 'on'); } // -- helper functions for zoomClipped @@ -52899,8 +54737,8 @@ function multiply(a, b) { function rotateBetween(a, b) { if(!a || !b) return; var axis = cross(a, b), - norm = Math.sqrt(__dot_620(axis, axis)), - halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, __dot_620(a, b)))), + norm = Math.sqrt(__dot_682(axis, axis)), + halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, __dot_682(a, b)))), k = Math.sin(halfgamma) / norm; return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k]; } @@ -53002,7 +54840,7 @@ function cartesian(spherical) { ]; } -function __dot_620(a, b) { +function __dot_682(a, b) { var s = 0; for(var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i]; return s; @@ -53027,7 +54865,7 @@ function d3_eventDispatch(target) { while(++i < n) argumentz.push(arguments[i]); - var dispatch = _$d3_127.dispatch.apply(null, argumentz); + var dispatch = _$d3_130.dispatch.apply(null, argumentz); // Creates a dispatch context for the specified `thiz` (typically, the target // DOM element that received the source event) and `argumentz` (typically, the @@ -53042,12 +54880,12 @@ function d3_eventDispatch(target) { return function(e1) { var e0; try { - e0 = e1.sourceEvent = _$d3_127.event; + e0 = e1.sourceEvent = _$d3_130.event; e1.target = target; - _$d3_127.event = e1; + _$d3_130.event = e1; dispatch[e1.type].apply(thiz, argumentz); } finally { - _$d3_127.event = e0; + _$d3_130.event = e0; } }; }; @@ -53067,25 +54905,25 @@ function d3_eventDispatch(target) { /* global PlotlyGeoAssets:false */ -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$plots_647 = require('../plots'); */; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$plots_709 = require('../plots'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +var __prepSelect_676 = _$select_664.prepSelect; -/* removed: var _$createGeoZoom_620 = require('./zoom'); */; -/* removed: var _$constants_613 = require('./constants'); */; +/* removed: var _$createGeoZoom_682 = require('./zoom'); */; +/* removed: var _$constants_675 = require('./constants'); */; -/* removed: var _$topojson_utils_565 = require('../../lib/topojson_utils'); */; -var __topojsonFeature_614 = _$topojsonClient_355.feature; +/* removed: var _$topojson_utils_628 = require('../../lib/topojson_utils'); */; +var __topojsonFeature_676 = _$topojsonClient_417.feature; -_$addProjectionsToD3_619(_$d3_127); +_$addProjectionsToD3_681(_$d3_130); function Geo(opts) { this.id = opts.id; @@ -53120,14 +54958,14 @@ function Geo(opts) { var proto = Geo.prototype; -var _$createGeo_614 = function createGeo(opts) { +var _$createGeo_676 = function createGeo(opts) { return new Geo(opts); }; proto.plot = function(geoCalcData, fullLayout, promises) { var _this = this; var geoLayout = fullLayout[this.id]; - var topojsonNameNew = _$topojson_utils_565.getTopojsonName(geoLayout); + var topojsonNameNew = _$topojson_utils_628.getTopojsonName(geoLayout); if(_this.topojson === null || topojsonNameNew !== _this.topojsonName) { _this.topojsonName = topojsonNameNew; @@ -53148,12 +54986,12 @@ proto.plot = function(geoCalcData, fullLayout, promises) { }; proto.fetchTopojson = function() { - var topojsonPath = _$topojson_utils_565.getTopojsonPath( + var topojsonPath = _$topojson_utils_628.getTopojsonPath( this.topojsonURL, this.topojsonName ); return new Promise(function(resolve, reject) { - _$d3_127.json(topojsonPath, function(err, topojson) { + _$d3_130.json(topojsonPath, function(err, topojson) { if(err) { if(err.status === 404) { return reject(new Error([ @@ -53197,7 +55035,7 @@ proto.update = function(geoCalcData, fullLayout) { this.updateDims(fullLayout, geoLayout); this.updateFx(fullLayout, geoLayout); - _$plots_647.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout); + _$plots_709.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout); var scatterLayer = this.layers.frontplot.select('.scatterlayer'); this.dataPoints.point = scatterLayer.selectAll('.point'); @@ -53264,8 +55102,8 @@ proto.updateProjection = function(fullLayout, geoLayout) { this.viewInitial = null; - _$lib_539.warn(msg); - gd._promises.push(_$registry_668.call('relayout', gd, updateObj)); + _$lib_601.warn(msg); + gd._promises.push(_$registry_731.call('relayout', gd, updateObj)); return msg; } @@ -53306,16 +55144,16 @@ proto.updateBaseLayers = function(fullLayout, geoLayout) { } function isLineLayer(d) { - return Boolean(_$constants_613.lineLayers[d]); + return Boolean(_$constants_675.lineLayers[d]); } function isFillLayer(d) { - return Boolean(_$constants_613.fillLayers[d]); + return Boolean(_$constants_675.fillLayers[d]); } var allLayers = this.hasChoropleth ? - _$constants_613.layersForChoropleth : - _$constants_613.layers; + _$constants_675.layersForChoropleth : + _$constants_675.layers; var layerData = allLayers.filter(function(d) { return (isLineLayer(d) || isFillLayer(d)) ? geoLayout['show' + d] : @@ -53329,13 +55167,13 @@ proto.updateBaseLayers = function(fullLayout, geoLayout) { join.exit().each(function(d) { delete layers[d]; delete basePaths[d]; - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); }); join.enter().append('g') .attr('class', function(d) { return 'layer ' + d; }) .each(function(d) { - var layer = layers[d] = _$d3_127.select(this); + var layer = layers[d] = _$d3_130.select(this); if(d === 'bg') { _this.bgRect = layer.append('rect') @@ -53363,23 +55201,23 @@ proto.updateBaseLayers = function(fullLayout, geoLayout) { join.each(function(d) { var path = basePaths[d]; - var adj = _$constants_613.layerNameToAdjective[d]; + var adj = _$constants_675.layerNameToAdjective[d]; if(d === 'frame') { - path.datum(_$constants_613.sphereSVG); + path.datum(_$constants_675.sphereSVG); } else if(isLineLayer(d) || isFillLayer(d)) { - path.datum(__topojsonFeature_614(topojson, topojson.objects[d])); + path.datum(__topojsonFeature_676(topojson, topojson.objects[d])); } else if(isAxisLayer(d)) { path.datum(makeGraticule(d, geoLayout)) - .call(_$color_411.stroke, geoLayout[d].gridcolor) - .call(_$drawing_436.dashLine, '', geoLayout[d].gridwidth); + .call(_$color_473.stroke, geoLayout[d].gridcolor) + .call(_$drawing_498.dashLine, '', geoLayout[d].gridwidth); } if(isLineLayer(d)) { - path.call(_$color_411.stroke, geoLayout[adj + 'color']) - .call(_$drawing_436.dashLine, '', geoLayout[adj + 'width']); + path.call(_$color_473.stroke, geoLayout[adj + 'color']) + .call(_$drawing_498.dashLine, '', geoLayout[adj + 'width']); } else if(isFillLayer(d)) { - path.call(_$color_411.fill, geoLayout[adj + 'color']); + path.call(_$color_473.fill, geoLayout[adj + 'color']); } }); }; @@ -53393,11 +55231,11 @@ proto.updateDims = function(fullLayout, geoLayout) { var w = b[1][0] - l + hFrameWidth; var h = b[1][1] - t + hFrameWidth; - _$drawing_436.setRect(this.clipRect, l, t, w, h); + _$drawing_498.setRect(this.clipRect, l, t, w, h); this.bgRect - .call(_$drawing_436.setRect, l, t, w, h) - .call(_$color_411.fill, geoLayout.bgcolor); + .call(_$drawing_498.setRect, l, t, w, h) + .call(_$color_473.fill, geoLayout.bgcolor); this.xaxis._offset = l; this.xaxis._length = w; @@ -53422,7 +55260,7 @@ proto.updateFx = function(fullLayout, geoLayout) { updateObj[_this.id + '.' + k] = viewInitial[k]; } - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); gd.emit('plotly_doubleclick', null); } @@ -53435,7 +55273,7 @@ proto.updateFx = function(fullLayout, geoLayout) { if(dragMode === 'pan') { bgRect.node().onmousedown = null; - bgRect.call(_$createGeoZoom_620(_this, geoLayout)); + bgRect.call(_$createGeoZoom_682(_this, geoLayout)); bgRect.on('dblclick.zoom', zoomReset); } else if(dragMode === 'select' || dragMode === 'lasso') { @@ -53477,27 +55315,27 @@ proto.updateFx = function(fullLayout, geoLayout) { }; dragOptions.prepFn = function(e, startX, startY) { - _$prepSelect_602(e, startX, startY, dragOptions, dragMode); + __prepSelect_676(e, startX, startY, dragOptions, dragMode); }; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); } bgRect.on('mousemove', function() { - var lonlat = _this.projection.invert(_$d3_127.mouse(this)); + var lonlat = _this.projection.invert(_$d3_130.mouse(this)); if(!lonlat || isNaN(lonlat[0]) || isNaN(lonlat[1])) { - return _$dragelement_433.unhover(gd, _$d3_127.event); + return _$dragelement_495.unhover(gd, _$d3_130.event); } _this.xaxis.p2c = function() { return lonlat[0]; }; _this.yaxis.p2c = function() { return lonlat[1]; }; - _$fx_453.hover(gd, _$d3_127.event, _this.id); + _$fx_515.hover(gd, _$d3_130.event, _this.id); }); bgRect.on('mouseout', function() { - _$dragelement_433.unhover(gd, _$d3_127.event); + _$dragelement_495.unhover(gd, _$d3_130.event); }); bgRect.on('click', function() { @@ -53505,7 +55343,7 @@ proto.updateFx = function(fullLayout, geoLayout) { // actually this one is worse, as right-click starts a pan, or leaves // select in a weird state. // Also, only tangentially related, we should cancel hover during pan - _$fx_453.click(gd, _$d3_127.event); + _$fx_515.click(gd, _$d3_130.event); }); }; @@ -53519,9 +55357,9 @@ proto.makeFramework = function() { _this.clipRect = _this.clipDef.append('rect'); - _this.framework = _$d3_127.select(_this.container).append('g') + _this.framework = _$d3_130.select(_this.container).append('g') .attr('class', 'geo ' + _this.id) - .call(_$drawing_436.setClipUrl, clipId); + .call(_$drawing_498.setClipUrl, clipId); // sane lonlat to px _this.project = function(v) { @@ -53547,7 +55385,7 @@ proto.makeFramework = function() { showexponent: 'all', exponentformat: 'B' }; - _$axes_584.setConvert(_this.mockAxis, fullLayout); + _$axes_647.setConvert(_this.mockAxis, fullLayout); }; proto.saveViewInitial = function(geoLayout) { @@ -53624,10 +55462,10 @@ function getProjection(geoLayout) { var projLayout = geoLayout.projection; var projType = projLayout.type; - var projection = _$d3_127.geo[_$constants_613.projNames[projType]](); + var projection = _$d3_130.geo[_$constants_675.projNames[projType]](); var clipAngle = geoLayout._isClipped ? - _$constants_613.lonaxisSpan[projType] / 2 : + _$constants_675.lonaxisSpan[projType] / 2 : null; var methods = ['center', 'rotate', 'parallels', 'clipExtent']; @@ -53647,7 +55485,7 @@ function getProjection(geoLayout) { if(clipAngle) { var r = projection.rotate(); - var angle = _$d3_127.geo.distance(lonlat, [-r[0], -r[1]]); + var angle = _$d3_130.geo.distance(lonlat, [-r[0], -r[1]]); var maxAngle = clipAngle * Math.PI / 180; return angle > maxAngle; } else { @@ -53656,7 +55494,7 @@ function getProjection(geoLayout) { }; projection.getPath = function() { - return _$d3_127.geo.path().projection(projection); + return _$d3_130.geo.path().projection(projection); }; projection.getBounds = function(object) { @@ -53688,10 +55526,10 @@ function getProjection(geoLayout) { .translate([x, y]); }; - projection.precision(_$constants_613.precision); + projection.precision(_$constants_675.precision); if(clipAngle) { - projection.clipAngle(clipAngle - _$constants_613.clipPad); + projection.clipAngle(clipAngle - _$constants_675.clipPad); } return projection; @@ -53700,12 +55538,12 @@ function getProjection(geoLayout) { function makeGraticule(axisName, geoLayout) { var axisLayout = geoLayout[axisName]; var dtick = axisLayout.dtick; - var scopeDefaults = _$constants_613.scopeDefaults[geoLayout.scope]; + var scopeDefaults = _$constants_675.scopeDefaults[geoLayout.scope]; var lonaxisRange = scopeDefaults.lonaxisRange; var lataxisRange = scopeDefaults.lataxisRange; var step = axisName === 'lonaxis' ? [dtick] : [0, dtick]; - return _$d3_127.geo.graticule() + return _$d3_130.geo.graticule() .extent([ [lonaxisRange[0], lataxisRange[0]], [lonaxisRange[1], lataxisRange[1]] @@ -53718,7 +55556,7 @@ function makeGraticule(axisName, geoLayout) { // // Note that clipPad padding is added around range to avoid aliasing. function makeRangeBox(lon, lat) { - var clipPad = _$constants_613.clipPad; + var clipPad = _$constants_675.clipPad; var lon0 = lon[0] + clipPad; var lon1 = lon[1] - clipPad; var lat0 = lat[0] + clipPad; @@ -53758,7 +55596,7 @@ function makeRangeBox(lon, lat) { 'use strict'; -var _$attributes_616 = { +var _$attributes_678 = { geo: { valType: 'subplotid', role: 'info', @@ -53775,7 +55613,7 @@ var _$attributes_616 = { } }; -var _$domain_610 = {}; +var _$domain_672 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53786,7 +55624,7 @@ var _$domain_610 = {}; 'use strict'; -var __extendFlat_610 = _$extend_528.extendFlat; +var __extendFlat_672 = _$extend_590.extendFlat; /** * Make a xy domain attribute group @@ -53809,7 +55647,7 @@ var __extendFlat_610 = _$extend_528.extendFlat; * * @return {object} attributes object containing {x,y} as specified */ -_$domain_610.attributes = function(opts, extra) { +_$domain_672.attributes = function(opts, extra) { opts = opts || {}; extra = extra || {}; @@ -53829,7 +55667,7 @@ _$domain_610.attributes = function(opts, extra) { var descPart = extra.description ? ' ' + extra.description : ''; var out = { - x: __extendFlat_610({}, base, { + x: __extendFlat_672({}, base, { description: [ 'Sets the horizontal domain of this ', namePart, @@ -53838,7 +55676,7 @@ _$domain_610.attributes = function(opts, extra) { descPart ].join('') }), - y: __extendFlat_610({}, base, { + y: __extendFlat_672({}, base, { description: [ 'Sets the vertical domain of this ', namePart, @@ -53886,7 +55724,7 @@ _$domain_610.attributes = function(opts, extra) { return out; }; -_$domain_610.defaults = function(containerOut, layout, coerce, dfltDomains) { +_$domain_672.defaults = function(containerOut, layout, coerce, dfltDomains) { var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; @@ -53919,10 +55757,10 @@ _$domain_610.defaults = function(containerOut, layout, coerce, dfltDomains) { 'use strict'; -/* removed: var _$attributes_410 = require('../../../components/color/attributes'); */; -var domainAttrs = _$domain_610.attributes; -/* removed: var _$constants_613 = require('../constants'); */; -var __overrideAll_618 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_472 = require('../../../components/color/attributes'); */; +var domainAttrs = _$domain_672.attributes; +/* removed: var _$constants_675 = require('../constants'); */; +var __overrideAll_680 = _$edit_types_632.overrideAll; var geoAxesAttrs = { range: { @@ -53960,7 +55798,7 @@ var geoAxesAttrs = { gridcolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, description: [ 'Sets the graticule\'s stroke color.' ].join(' ') @@ -53976,7 +55814,7 @@ var geoAxesAttrs = { } }; -var _$layout_attributes_618 = __overrideAll_618({ +var _$layout_attributes_680 = __overrideAll_680({ domain: domainAttrs({name: 'geo'}, { description: [ 'Note that geo subplots are constrained by domain.', @@ -54000,7 +55838,7 @@ var _$layout_attributes_618 = __overrideAll_618({ scope: { valType: 'enumerated', role: 'info', - values: Object.keys(_$constants_613.scopeDefaults), + values: Object.keys(_$constants_675.scopeDefaults), dflt: 'world', description: 'Set the scope of the map.' }, @@ -54008,7 +55846,7 @@ var _$layout_attributes_618 = __overrideAll_618({ type: { valType: 'enumerated', role: 'info', - values: Object.keys(_$constants_613.projNames), + values: Object.keys(_$constants_675.projNames), description: 'Sets the projection type.' }, rotation: { @@ -54091,7 +55929,7 @@ var _$layout_attributes_618 = __overrideAll_618({ coastlinecolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, description: 'Sets the coastline color.' }, coastlinewidth: { @@ -54110,7 +55948,7 @@ var _$layout_attributes_618 = __overrideAll_618({ landcolor: { valType: 'color', role: 'style', - dflt: _$constants_613.landColor, + dflt: _$constants_675.landColor, description: 'Sets the land mass color.' }, showocean: { @@ -54122,7 +55960,7 @@ var _$layout_attributes_618 = __overrideAll_618({ oceancolor: { valType: 'color', role: 'style', - dflt: _$constants_613.waterColor, + dflt: _$constants_675.waterColor, description: 'Sets the ocean color' }, showlakes: { @@ -54134,7 +55972,7 @@ var _$layout_attributes_618 = __overrideAll_618({ lakecolor: { valType: 'color', role: 'style', - dflt: _$constants_613.waterColor, + dflt: _$constants_675.waterColor, description: 'Sets the color of the lakes.' }, showrivers: { @@ -54146,7 +55984,7 @@ var _$layout_attributes_618 = __overrideAll_618({ rivercolor: { valType: 'color', role: 'style', - dflt: _$constants_613.waterColor, + dflt: _$constants_675.waterColor, description: 'Sets color of the rivers.' }, riverwidth: { @@ -54164,7 +56002,7 @@ var _$layout_attributes_618 = __overrideAll_618({ countrycolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, description: 'Sets line color of the country boundaries.' }, countrywidth: { @@ -54185,7 +56023,7 @@ var _$layout_attributes_618 = __overrideAll_618({ subunitcolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, description: 'Sets the color of the subunits boundaries.' }, subunitwidth: { @@ -54203,7 +56041,7 @@ var _$layout_attributes_618 = __overrideAll_618({ framecolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, description: 'Sets the color the frame.' }, framewidth: { @@ -54216,7 +56054,7 @@ var _$layout_attributes_618 = __overrideAll_618({ bgcolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, description: 'Set the background color of the map' }, lonaxis: geoAxesAttrs, @@ -54234,8 +56072,8 @@ var _$layout_attributes_618 = __overrideAll_618({ 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -var handleDomainDefaults = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../lib'); */; +var handleDomainDefaults = _$domain_672.defaults; /** @@ -54265,7 +56103,7 @@ var handleDomainDefaults = _$domain_610.defaults; * additional items needed by this function here as well * } */ -var _$handleSubplotDefaults_660 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { +var _$handleSubplotDefaults_723 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { var subplotType = opts.type; var subplotAttributes = opts.attributes; var handleDefaults = opts.handleDefaults; @@ -54277,7 +56115,7 @@ var _$handleSubplotDefaults_660 = function handleSubplotDefaults(layoutIn, layou var subplotLayoutIn, subplotLayoutOut; function coerce(attr, dflt) { - return _$lib_539.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); + return _$lib_601.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); } for(var i = 0; i < idsLength; i++) { @@ -54309,16 +56147,16 @@ var _$handleSubplotDefaults_660 = function handleSubplotDefaults(layoutIn, layou 'use strict'; -/* removed: var _$handleSubplotDefaults_660 = require('../../subplot_defaults'); */; -/* removed: var _$constants_613 = require('../constants'); */; -/* removed: var _$layout_attributes_618 = require('./layout_attributes'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../../subplot_defaults'); */; +/* removed: var _$constants_675 = require('../constants'); */; +/* removed: var _$layout_attributes_680 = require('./layout_attributes'); */; -var axesNames = _$constants_613.axesNames; +var axesNames = _$constants_675.axesNames; -var _$supplyLayoutDefaults_617 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_679 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'geo', - attributes: _$layout_attributes_618, + attributes: _$layout_attributes_680, handleDefaults: handleGeoDefaults, partition: 'y' }); @@ -54329,7 +56167,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { var resolution = coerce('resolution'); var scope = coerce('scope'); - var scopeParams = _$constants_613.scopeDefaults[scope]; + var scopeParams = _$constants_675.scopeDefaults[scope]; var projType = coerce('projection.type', scopeParams.projType); var isAlbersUsa = geoLayoutOut._isAlbersUsa = projType === 'albers usa'; @@ -54339,7 +56177,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { var isScoped = geoLayoutOut._isScoped = (scope !== 'world'); var isConic = geoLayoutOut._isConic = projType.indexOf('conic') !== -1; - geoLayoutOut._isClipped = !!_$constants_613.lonaxisSpan[projType]; + geoLayoutOut._isClipped = !!_$constants_675.lonaxisSpan[projType]; for(var i = 0; i < axesNames.length; i++) { var axisName = axesNames[i]; @@ -54349,7 +56187,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { if(isScoped) { rangeDflt = scopeParams[axisName + 'Range']; } else { - var dfltSpans = _$constants_613[axisName + 'Span']; + var dfltSpans = _$constants_675[axisName + 'Span']; var hSpan = (dfltSpans[projType] || dfltSpans['*']) / 2; var rot = coerce( 'projection.rotation.' + axisName.substr(0, 3), @@ -54461,7 +56299,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { coerce('bgcolor'); } -var _$geo_615 = {}; +var _$geo_677 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -54473,27 +56311,27 @@ var _$geo_615 = {}; 'use strict'; -/* removed: var _$createGeo_614 = require('./geo'); */; -var getSubplotCalcData = _$get_data_621.getSubplotCalcData; -var __counterRegex_615 = _$lib_539.counterRegex; +/* removed: var _$createGeo_676 = require('./geo'); */; +var getSubplotCalcData = _$get_data_683.getSubplotCalcData; +var __counterRegex_677 = _$lib_601.counterRegex; var GEO = 'geo'; -_$geo_615.name = GEO; +_$geo_677.name = GEO; -_$geo_615.attr = GEO; +_$geo_677.attr = GEO; -_$geo_615.idRoot = GEO; +_$geo_677.idRoot = GEO; -_$geo_615.idRegex = _$geo_615.attrRegex = __counterRegex_615(GEO); +_$geo_677.idRegex = _$geo_677.attrRegex = __counterRegex_677(GEO); -_$geo_615.attributes = _$attributes_616; +_$geo_677.attributes = _$attributes_678; -_$geo_615.layoutAttributes = _$layout_attributes_618; +_$geo_677.layoutAttributes = _$layout_attributes_680; -_$geo_615.supplyLayoutDefaults = _$supplyLayoutDefaults_617; +_$geo_677.supplyLayoutDefaults = _$supplyLayoutDefaults_679; -_$geo_615.plot = function plotGeo(gd) { +_$geo_677.plot = function plotGeo(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var geoIds = fullLayout._subplots[GEO]; @@ -54513,7 +56351,7 @@ _$geo_615.plot = function plotGeo(gd) { var geo = geoLayout._subplot; if(!geo) { - geo = _$createGeo_614({ + geo = _$createGeo_676({ id: geoId, graphDiv: gd, container: fullLayout._geolayer.node(), @@ -54528,7 +56366,7 @@ _$geo_615.plot = function plotGeo(gd) { } }; -_$geo_615.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$geo_677.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldGeoKeys = oldFullLayout._subplots[GEO] || []; for(var i = 0; i < oldGeoKeys.length; i++) { @@ -54542,7 +56380,7 @@ _$geo_615.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayou } }; -_$geo_615.updateFx = function(fullLayout) { +_$geo_677.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots[GEO]; for(var i = 0; i < subplotIds.length; i++) { @@ -54562,19 +56400,19 @@ _$geo_615.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -var __dash_900 = _$attributes_435.dash; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +var __dash_965 = _$attributes_497.dash; -var __extendFlat_900 = _$extend_528.extendFlat; -var __overrideAll_900 = _$edit_types_569.overrideAll; +var __extendFlat_965 = _$extend_590.extendFlat; +var __overrideAll_965 = _$edit_types_632.overrideAll; -var __scatterMarkerAttrs_900 = _$attributes_862.marker, - scatterLineAttrs = _$attributes_862.line, - __scatterMarkerLineAttrs_900 = __scatterMarkerAttrs_900.line; +var __scatterMarkerAttrs_965 = _$attributes_927.marker, + scatterLineAttrs = _$attributes_927.line, + __scatterMarkerLineAttrs_965 = __scatterMarkerAttrs_965.line; -var _$attributes_900 = __overrideAll_900({ +var _$attributes_965 = __overrideAll_965({ lon: { valType: 'data_array', description: 'Sets the longitude coordinates (in degrees East).' @@ -54603,9 +56441,9 @@ var _$attributes_900 = __overrideAll_900({ ].join(' ') }, - mode: __extendFlat_900({}, _$attributes_862.mode, {dflt: 'markers'}), + mode: __extendFlat_965({}, _$attributes_927.mode, {dflt: 'markers'}), - text: __extendFlat_900({}, _$attributes_862.text, { + text: __extendFlat_965({}, _$attributes_927.text, { description: [ 'Sets text elements associated with each (lon,lat) pair', 'or item in `locations`.', @@ -54617,7 +56455,7 @@ var _$attributes_900 = __overrideAll_900({ 'these elements will be seen in the hover labels.' ].join(' ') }), - hovertext: __extendFlat_900({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_965({}, _$attributes_927.hovertext, { description: [ 'Sets hover text elements associated with each (lon,lat) pair', 'or item in `locations`.', @@ -54629,33 +56467,33 @@ var _$attributes_900 = __overrideAll_900({ ].join(' ') }), - textfont: _$attributes_862.textfont, - textposition: _$attributes_862.textposition, + textfont: _$attributes_927.textfont, + textposition: _$attributes_927.textposition, line: { color: scatterLineAttrs.color, width: scatterLineAttrs.width, - dash: __dash_900 - }, - connectgaps: _$attributes_862.connectgaps, - - marker: __extendFlat_900({ - symbol: __scatterMarkerAttrs_900.symbol, - opacity: __scatterMarkerAttrs_900.opacity, - size: __scatterMarkerAttrs_900.size, - sizeref: __scatterMarkerAttrs_900.sizeref, - sizemin: __scatterMarkerAttrs_900.sizemin, - sizemode: __scatterMarkerAttrs_900.sizemode, - showscale: __scatterMarkerAttrs_900.showscale, - colorbar: __scatterMarkerAttrs_900.colorbar, - line: __extendFlat_900({ - width: __scatterMarkerLineAttrs_900.width + dash: __dash_965 + }, + connectgaps: _$attributes_927.connectgaps, + + marker: __extendFlat_965({ + symbol: __scatterMarkerAttrs_965.symbol, + opacity: __scatterMarkerAttrs_965.opacity, + size: __scatterMarkerAttrs_965.size, + sizeref: __scatterMarkerAttrs_965.sizeref, + sizemin: __scatterMarkerAttrs_965.sizemin, + sizemode: __scatterMarkerAttrs_965.sizemode, + showscale: __scatterMarkerAttrs_965.showscale, + colorbar: __scatterMarkerAttrs_965.colorbar, + line: __extendFlat_965({ + width: __scatterMarkerLineAttrs_965.width }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ), - gradient: __scatterMarkerAttrs_900.gradient + gradient: __scatterMarkerAttrs_965.gradient }, - _$makeColorScaleAttributes_419('marker') + _$makeColorScaleAttributes_481('marker') ), fill: { @@ -54670,12 +56508,12 @@ var _$attributes_900 = __overrideAll_900({ 'of the trace if it has gaps) into a closed shape.' ].join(' ') }, - fillcolor: _$attributes_862.fillcolor, + fillcolor: _$attributes_927.fillcolor, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected, + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected, - hoverinfo: __extendFlat_900({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_965({}, _$attributes_644.hoverinfo, { flags: ['lon', 'lat', 'location', 'text', 'name'] }) }, 'calc', 'nested'); @@ -54690,18 +56528,18 @@ var _$attributes_900 = __overrideAll_900({ 'use strict'; -/* removed: var _$attributes_900 = require('../scattergeo/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; +/* removed: var _$attributes_965 = require('../scattergeo/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; -/* removed: var _$extend_528 = require('../../lib/extend'); */; -var __extendFlat_735 = _$extend_528.extendFlat; -var __extendDeepAll_735 = _$extend_528.extendDeepAll; +/* removed: var _$extend_590 = require('../../lib/extend'); */; +var __extendFlat_797 = _$extend_590.extendFlat; +var __extendDeepAll_797 = _$extend_590.extendDeepAll; -var scatterGeoMarkerLineAttrs = _$attributes_900.marker.line; +var scatterGeoMarkerLineAttrs = _$attributes_965.marker.line; -var _$attributes_735 = __extendFlat_735({ +var _$attributes_797 = __extendFlat_797({ locations: { valType: 'data_array', editType: 'calc', @@ -54710,19 +56548,19 @@ var _$attributes_735 = __extendFlat_735({ 'See `locationmode` for more info.' ].join(' ') }, - locationmode: _$attributes_900.locationmode, + locationmode: _$attributes_965.locationmode, z: { valType: 'data_array', editType: 'calc', description: 'Sets the color values.' }, - text: __extendFlat_735({}, _$attributes_900.text, { + text: __extendFlat_797({}, _$attributes_965.text, { description: 'Sets the text elements associated with each location.' }), marker: { line: { color: scatterGeoMarkerLineAttrs.color, - width: __extendFlat_735({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}), + width: __extendFlat_797({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}), editType: 'calc' }, opacity: { @@ -54740,29 +56578,29 @@ var _$attributes_735 = __extendFlat_735({ selected: { marker: { - opacity: _$attributes_900.selected.marker.opacity, + opacity: _$attributes_965.selected.marker.opacity, editType: 'plot' }, editType: 'plot' }, unselected: { marker: { - opacity: _$attributes_900.unselected.marker.opacity, + opacity: _$attributes_965.unselected.marker.opacity, editType: 'plot' }, editType: 'plot' }, - hoverinfo: __extendFlat_735({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_797({}, _$attributes_644.hoverinfo, { editType: 'calc', flags: ['location', 'z', 'text', 'name'] }) }, - __extendDeepAll_735({}, _$attributes_417, { + __extendDeepAll_797({}, _$attributes_479, { zmax: {editType: 'calc'}, zmin: {editType: 'calc'} }), - { colorbar: _$attributes_412 } + { colorbar: _$attributes_474 } ); /** @@ -54776,42 +56614,42 @@ var _$attributes_735 = __extendFlat_735({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_861 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_926 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_539.mergeArray(trace.text, cd, 'tx'); - _$lib_539.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_539.mergeArray(trace.customdata, cd, 'data'); - _$lib_539.mergeArray(trace.textposition, cd, 'tp'); + _$lib_601.mergeArray(trace.text, cd, 'tx'); + _$lib_601.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_601.mergeArray(trace.customdata, cd, 'data'); + _$lib_601.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_539.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_539.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_539.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_601.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_601.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_601.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_539.mergeArray(marker.size, cd, 'ms'); - _$lib_539.mergeArray(marker.opacity, cd, 'mo'); - _$lib_539.mergeArray(marker.symbol, cd, 'mx'); - _$lib_539.mergeArray(marker.color, cd, 'mc'); + _$lib_601.mergeArray(marker.size, cd, 'ms'); + _$lib_601.mergeArray(marker.opacity, cd, 'mo'); + _$lib_601.mergeArray(marker.symbol, cd, 'mx'); + _$lib_601.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_539.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_539.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_601.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_601.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_539.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_539.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_601.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_601.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -54827,14 +56665,14 @@ var _$arraysToCalcdata_861 = function arraysToCalcdata(cd, trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __BADNUM_736 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __BADNUM_798 = _$numerical_578.BADNUM; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; -var _$calc_736 = function calc(gd, trace) { +var _$calc_798 = function calc(gd, trace) { var len = trace.locations.length; var calcTrace = new Array(len); @@ -54844,12 +56682,12 @@ var _$calc_736 = function calc(gd, trace) { var z = trace.z[i]; calcPt.loc = typeof loc === 'string' ? loc : null; - calcPt.z = _$fastIsnumeric_139(z) ? z : __BADNUM_736; + calcPt.z = _$fastIsnumeric_196(z) ? z : __BADNUM_798; } - _$arraysToCalcdata_861(calcTrace, trace); - _$calc_418(trace, trace.z, '', 'z'); - _$calcSelection_864(calcTrace, trace); + _$arraysToCalcdata_926(calcTrace, trace); + _$calc_480(trace, trace.z, '', 'z'); + _$calcSelection_929(calcTrace, trace); return calcTrace; }; @@ -54865,13 +56703,13 @@ var _$calc_736 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_735 = require('./attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_797 = require('./attributes'); */; -var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_799 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_735, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_797, attr, dflt); } var locations = coerce('locations'); @@ -54885,7 +56723,7 @@ var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultCol } var z = coerce('z'); - if(!_$lib_539.isArrayOrTypedArray(z)) { + if(!_$lib_601.isArrayOrTypedArray(z)) { traceOut.visible = false; return; } @@ -54900,11 +56738,11 @@ var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('marker.line.width'); coerce('marker.opacity'); - _$colorScaleDefaults_421( + _$colorScaleDefaults_483( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -54918,7 +56756,7 @@ var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_738 = function eventData(out, pt) { +var _$eventData_800 = function eventData(out, pt) { out.location = pt.location; out.z = pt.z; @@ -54936,11 +56774,11 @@ var _$eventData_738 = function eventData(out, pt) { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$attributes_735 = require('./attributes'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$attributes_797 = require('./attributes'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; -var _$hoverPoints_739 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_801 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var geo = pointData.subplot; @@ -54984,7 +56822,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { var hoverinfo = pt.hi || trace.hoverinfo; var parts = (hoverinfo === 'all') ? - _$attributes_735.hoverinfo.flags : + _$attributes_797.hoverinfo.flags : hoverinfo.split('+'); var hasName = (parts.indexOf('name') !== -1); @@ -54996,7 +56834,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { var text = []; function formatter(val) { - return _$axes_584.tickText(axis, axis.c2l(val), 'hover').text; + return _$axes_647.tickText(axis, axis.c2l(val), 'hover').text; } if(hasIdAsNameLabel) { @@ -55008,13 +56846,13 @@ function makeHoverInfo(pointData, trace, pt, axis) { if(hasZ) text.push(formatter(pt.z)); if(hasText) { - _$fillHoverText_870(pt, trace, text); + _$fillHoverText_935(pt, trace, text); } pointData.extraText = text.join('
'); } -var _$countryRegex_113 = { +var _$countryRegex_114 = { AFG: 'afghan', ALA: '\\b\\wland', ALB: 'albania', @@ -55272,7 +57110,7 @@ var _$countryRegex_113 = { ZWE: 'zimbabwe|^(?!.*northern).*rhodesia' } -var _$geo_location_utils_531 = {}; +var _$geo_location_utils_593 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -55284,20 +57122,20 @@ var _$geo_location_utils_531 = {}; 'use strict'; -/* removed: var _$countryRegex_113 = require('country-regex'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$countryRegex_114 = require('country-regex'); */; +/* removed: var _$lib_601 = require('../lib'); */; // make list of all country iso3 ids from at runtime -var countryIds = Object.keys(_$countryRegex_113); +var countryIds = Object.keys(_$countryRegex_114); var locationmodeToIdFinder = { - 'ISO-3': _$lib_539.identity, - 'USA-states': _$lib_539.identity, + 'ISO-3': _$lib_601.identity, + 'USA-states': _$lib_601.identity, 'country names': countryNameToISO3 }; -_$geo_location_utils_531.locationToFeature = function(locationmode, location, features) { +_$geo_location_utils_593.locationToFeature = function(locationmode, location, features) { if(!location || typeof location !== 'string') return false; var locationId = getLocationId(locationmode, location); @@ -55309,7 +57147,7 @@ _$geo_location_utils_531.locationToFeature = function(locationmode, location, fe if(feature.id === locationId) return feature; } - _$lib_539.log([ + _$lib_601.log([ 'Location with id', locationId, 'does not have a matching topojson feature at this resolution.' ].join(' ')); @@ -55326,12 +57164,12 @@ function getLocationId(locationmode, location) { function countryNameToISO3(countryName) { for(var i = 0; i < countryIds.length; i++) { var iso3 = countryIds[i], - regex = new RegExp(_$countryRegex_113[iso3]); + regex = new RegExp(_$countryRegex_114[iso3]); if(regex.test(countryName.trim().toLowerCase())) return iso3; } - _$lib_539.log('Unrecognized country name: ' + countryName + '.'); + _$lib_601.log('Unrecognized country name: ' + countryName + '.'); return false; } @@ -55346,12 +57184,12 @@ function countryNameToISO3(countryName) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; -var _$style_743 = function style(gd, calcTrace) { +var _$style_805 = function style(gd, calcTrace) { if(calcTrace) styleTrace(gd, calcTrace); }; @@ -55362,8 +57200,8 @@ function styleTrace(gd, calcTrace) { var marker = trace.marker || {}; var markerLine = marker.line || {}; - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, trace.zmin, trace.zmax @@ -55371,14 +57209,14 @@ function styleTrace(gd, calcTrace) { ); locs.each(function(d) { - _$d3_127.select(this) + _$d3_130.select(this) .attr('fill', sclFunc(d.z)) - .call(_$color_411.stroke, d.mlc || markerLine.color) - .call(_$drawing_436.dashLine, '', d.mlw || markerLine.width || 0) + .call(_$color_473.stroke, d.mlc || markerLine.color) + .call(_$drawing_498.dashLine, '', d.mlw || markerLine.width || 0) .style('opacity', marker.opacity); }); - _$drawing_436.selectedPointStyle(locs, trace); + _$drawing_498.selectedPointStyle(locs, trace); } /** @@ -55391,16 +57229,16 @@ function styleTrace(gd, calcTrace) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$polygon_551 = require('../../lib/polygon'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$polygon_613 = require('../../lib/polygon'); */; -var getTopojsonFeatures = _$topojson_utils_565.getTopojsonFeatures; -var locationToFeature = _$geo_location_utils_531.locationToFeature; -/* removed: var _$style_743 = require('./style'); */; +var getTopojsonFeatures = _$topojson_utils_628.getTopojsonFeatures; +var locationToFeature = _$geo_location_utils_593.locationToFeature; +/* removed: var _$style_805 = require('./style'); */; -var _$plot_741 = function plot(gd, geo, calcData) { +var _$plot_803 = function plot(gd, geo, calcData) { for(var i = 0; i < calcData.length; i++) { calcGeoJSON(calcData[i], geo.topojson); } @@ -55417,10 +57255,10 @@ var _$plot_741 = function plot(gd, geo, calcData) { gTraces.exit().remove(); gTraces.each(function(calcTrace) { - var sel = calcTrace[0].node3 = _$d3_127.select(this); + var sel = calcTrace[0].node3 = _$d3_130.select(this); var paths = sel.selectAll('path.choroplethlocation') - .data(_$lib_539.identity); + .data(_$lib_601.identity); paths.enter().append('path') .classed('choroplethlocation', true); @@ -55428,7 +57266,7 @@ var _$plot_741 = function plot(gd, geo, calcData) { paths.exit().remove(); // call style here within topojson request callback - _$style_743(gd, calcTrace); + _$style_805(gd, calcTrace); }); }; @@ -55493,7 +57331,7 @@ function feature2polygons(feature) { } } - polygons.push(_$polygon_551.tester(pts)); + polygons.push(_$polygon_613.tester(pts)); }; } else if(loc === 'ATA') { // Antarctica has a landmass that wraps around every longitudes which @@ -55503,7 +57341,7 @@ function feature2polygons(feature) { // polygon that do not cross anti-meridian need no special handling if(crossAntiMeridianIndex === null) { - return polygons.push(_$polygon_551.tester(pts)); + return polygons.push(_$polygon_613.tester(pts)); } // stitch polygon by adding pt over South Pole, @@ -55529,14 +57367,14 @@ function feature2polygons(feature) { // 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_551.tester(stitch); + var tester = _$polygon_613.tester(stitch); tester.pts.pop(); polygons.push(tester); }; } else { // otherwise using same array ref is fine appendPolygon = function(pts) { - polygons.push(_$polygon_551.tester(pts)); + polygons.push(_$polygon_613.tester(pts)); }; } @@ -55568,7 +57406,7 @@ function feature2polygons(feature) { 'use strict'; -var _$selectPoints_742 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_804 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -55617,33 +57455,33 @@ var _$selectPoints_742 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_776 = function colorbar(gd, cd) { +var _$colorbar_838 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, zmin = trace.zmin, zmax = trace.zmax; - if(!_$fastIsnumeric_139(zmin)) zmin = _$lib_539.aggNums(Math.min, null, trace.z); - if(!_$fastIsnumeric_139(zmax)) zmax = _$lib_539.aggNums(Math.max, null, trace.z); + if(!_$fastIsnumeric_196(zmin)) zmin = _$lib_601.aggNums(Math.min, null, trace.z); + if(!_$fastIsnumeric_196(zmax)) zmax = _$lib_601.aggNums(Math.max, null, trace.z); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, zmin, zmax @@ -55669,19 +57507,19 @@ var _$colorbar_776 = function colorbar(gd, cd) { var Choropleth = {}; -Choropleth.attributes = _$attributes_735; -Choropleth.supplyDefaults = _$supplyDefaults_737; -Choropleth.colorbar = _$colorbar_776; -Choropleth.calc = _$calc_736; -Choropleth.plot = _$plot_741; -Choropleth.style = _$style_743; -Choropleth.hoverPoints = _$hoverPoints_739; -Choropleth.eventData = _$eventData_738; -Choropleth.selectPoints = _$selectPoints_742; +Choropleth.attributes = _$attributes_797; +Choropleth.supplyDefaults = _$supplyDefaults_799; +Choropleth.colorbar = _$colorbar_838; +Choropleth.calc = _$calc_798; +Choropleth.plot = _$plot_803; +Choropleth.style = _$style_805; +Choropleth.hoverPoints = _$hoverPoints_801; +Choropleth.eventData = _$eventData_800; +Choropleth.selectPoints = _$selectPoints_804; Choropleth.moduleType = 'trace'; Choropleth.name = 'choropleth'; -Choropleth.basePlotModule = _$geo_615; +Choropleth.basePlotModule = _$geo_677; Choropleth.categories = ['geo', 'noOpacity']; Choropleth.meta = { description: [ @@ -55692,7 +57530,7 @@ Choropleth.meta = { ].join(' ') }; -var _$Choropleth_740 = Choropleth; +var _$Choropleth_802 = Choropleth; /** * Copyright 2012-2018, Plotly, Inc. @@ -55704,7 +57542,7 @@ var _$Choropleth_740 = Choropleth; 'use strict'; -var _$choropleth_9 = _$Choropleth_740; +var _$choropleth_9 = _$Choropleth_802; /** * Copyright 2012-2018, Plotly, Inc. @@ -55716,7 +57554,7 @@ var _$choropleth_9 = _$Choropleth_740; 'use strict'; -var _$filter_ops_512 = { +var _$filter_ops_574 = { COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='], COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], @@ -55753,24 +57591,24 @@ var _$filter_ops_512 = { 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_773 = _$extend_528.extendFlat; +var __extendFlat_835 = _$extend_590.extendFlat; -var _$attributes_773 = __extendFlat_773({}, { +var _$attributes_835 = __extendFlat_835({}, { z: { valType: 'data_array', editType: 'calc', description: 'Sets the z data.' }, - x: __extendFlat_773({}, _$attributes_862.x, {impliedEdits: {xtype: 'array'}}), - x0: __extendFlat_773({}, _$attributes_862.x0, {impliedEdits: {xtype: 'scaled'}}), - dx: __extendFlat_773({}, _$attributes_862.dx, {impliedEdits: {xtype: 'scaled'}}), - y: __extendFlat_773({}, _$attributes_862.y, {impliedEdits: {ytype: 'array'}}), - y0: __extendFlat_773({}, _$attributes_862.y0, {impliedEdits: {ytype: 'scaled'}}), - dy: __extendFlat_773({}, _$attributes_862.dy, {impliedEdits: {ytype: 'scaled'}}), + x: __extendFlat_835({}, _$attributes_927.x, {impliedEdits: {xtype: 'array'}}), + x0: __extendFlat_835({}, _$attributes_927.x0, {impliedEdits: {xtype: 'scaled'}}), + dx: __extendFlat_835({}, _$attributes_927.dx, {impliedEdits: {xtype: 'scaled'}}), + y: __extendFlat_835({}, _$attributes_927.y, {impliedEdits: {ytype: 'array'}}), + y0: __extendFlat_835({}, _$attributes_927.y0, {impliedEdits: {ytype: 'scaled'}}), + dy: __extendFlat_835({}, _$attributes_927.dy, {impliedEdits: {ytype: 'scaled'}}), text: { valType: 'data_array', @@ -55857,9 +57695,9 @@ var _$attributes_773 = __extendFlat_773({}, { ].join(' ') }, }, - _$attributes_417, - { autocolorscale: __extendFlat_773({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } + _$attributes_479, + { autocolorscale: __extendFlat_835({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); /** @@ -55872,35 +57710,35 @@ var _$attributes_773 = __extendFlat_773({}, { 'use strict'; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -var __dash_744 = _$attributes_435.dash; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __extendFlat_744 = _$extend_528.extendFlat; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +var __dash_806 = _$attributes_497.dash; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __extendFlat_806 = _$extend_590.extendFlat; -/* removed: var _$filter_ops_512 = require('../../constants/filter_ops'); */; -var COMPARISON_OPS2 = _$filter_ops_512.COMPARISON_OPS2; -var INTERVAL_OPS = _$filter_ops_512.INTERVAL_OPS; +/* removed: var _$filter_ops_574 = require('../../constants/filter_ops'); */; +var COMPARISON_OPS2 = _$filter_ops_574.COMPARISON_OPS2; +var INTERVAL_OPS = _$filter_ops_574.INTERVAL_OPS; -var __scatterLineAttrs_744 = _$attributes_862.line; +var __scatterLineAttrs_806 = _$attributes_927.line; -var _$attributes_744 = __extendFlat_744({ - z: _$attributes_773.z, - x: _$attributes_773.x, - x0: _$attributes_773.x0, - dx: _$attributes_773.dx, - y: _$attributes_773.y, - y0: _$attributes_773.y0, - dy: _$attributes_773.dy, - text: _$attributes_773.text, - transpose: _$attributes_773.transpose, - xtype: _$attributes_773.xtype, - ytype: _$attributes_773.ytype, - zhoverformat: _$attributes_773.zhoverformat, +var _$attributes_806 = __extendFlat_806({ + z: _$attributes_835.z, + x: _$attributes_835.x, + x0: _$attributes_835.x0, + dx: _$attributes_835.dx, + y: _$attributes_835.y, + y0: _$attributes_835.y0, + dy: _$attributes_835.dy, + text: _$attributes_835.text, + transpose: _$attributes_835.transpose, + xtype: _$attributes_835.xtype, + ytype: _$attributes_835.ytype, + zhoverformat: _$attributes_835.zhoverformat, - connectgaps: _$attributes_773.connectgaps, + connectgaps: _$attributes_835.connectgaps, fillcolor: { valType: 'color', @@ -56027,7 +57865,7 @@ var _$attributes_744 = __extendFlat_744({ 'Determines whether to label the contour lines with their values.' ].join(' ') }, - labelfont: _$font_attributes_611({ + labelfont: _$font_attributes_673({ editType: 'plot', colorEditType: 'style', description: [ @@ -56093,18 +57931,18 @@ var _$attributes_744 = __extendFlat_744({ }, line: { - color: __extendFlat_744({}, __scatterLineAttrs_744.color, { + color: __extendFlat_806({}, __scatterLineAttrs_806.color, { editType: 'style+colorbars', description: [ 'Sets the color of the contour level.', 'Has no effect if `contours.coloring` is set to *lines*.' ].join(' ') }), - width: __extendFlat_744({}, __scatterLineAttrs_744.width, { + width: __extendFlat_806({}, __scatterLineAttrs_806.width, { editType: 'style+colorbars' }), - dash: __dash_744, - smoothing: __extendFlat_744({}, __scatterLineAttrs_744.smoothing, { + dash: __dash_806, + smoothing: __extendFlat_806({}, __scatterLineAttrs_806.smoothing, { description: [ 'Sets the amount of smoothing for the contour lines,', 'where *0* corresponds to no smoothing.' @@ -56113,12 +57951,12 @@ var _$attributes_744 = __extendFlat_744({ editType: 'plot' } }, - _$attributes_417, { - autocolorscale: __extendFlat_744({}, _$attributes_417.autocolorscale, {dflt: false}), - zmin: __extendFlat_744({}, _$attributes_417.zmin, {editType: 'calc'}), - zmax: __extendFlat_744({}, _$attributes_417.zmax, {editType: 'calc'}) + _$attributes_479, { + autocolorscale: __extendFlat_806({}, _$attributes_479.autocolorscale, {dflt: false}), + zmin: __extendFlat_806({}, _$attributes_479.zmin, {editType: 'calc'}), + zmax: __extendFlat_806({}, _$attributes_479.zmax, {editType: 'calc'}) }, - { colorbar: _$attributes_412 } + { colorbar: _$attributes_474 } ); /** @@ -56132,11 +57970,11 @@ var _$attributes_744 = __extendFlat_744({ 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __extendFlat_763 = _$lib_539.extendFlat; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __extendFlat_825 = _$lib_601.extendFlat; -var _$setContours_763 = function setContours(trace) { +var _$setContours_825 = function setContours(trace) { var contours = trace.contours; // check if we need to auto-choose contour levels @@ -56145,9 +57983,9 @@ var _$setContours_763 = function setContours(trace) { contours.size = dummyAx.dtick; - contours.start = _$axes_584.tickFirst(dummyAx); + contours.start = _$axes_647.tickFirst(dummyAx); dummyAx.range.reverse(); - contours.end = _$axes_584.tickFirst(dummyAx); + contours.end = _$axes_647.tickFirst(dummyAx); if(contours.start === trace.zmin) contours.start += contours.size; if(contours.end === trace.zmax) contours.end -= contours.size; @@ -56163,7 +58001,7 @@ var _$setContours_763 = function setContours(trace) { // previously we copied the whole contours object back, but that had // other info (coloring, showlines) that should be left to supplyDefaults if(!trace._input.contours) trace._input.contours = {}; - __extendFlat_763(trace._input.contours, { + __extendFlat_825(trace._input.contours, { start: contours.start, end: contours.end, size: contours.size @@ -56210,7 +58048,7 @@ function autoContours(start, end, ncontours) { range: [start, end] }; - _$axes_584.autoTicks( + _$axes_647.autoTicks( dummyAx, (end - start) / (ncontours || 15) ); @@ -56229,7 +58067,7 @@ function autoContours(start, end, ncontours) { 'use strict'; -var _$maxRowLength_785 = function maxRowLength(z) { +var _$maxRowLength_847 = function maxRowLength(z) { var len = 0; for(var i = 0; i < z.length; i++) { @@ -56249,7 +58087,7 @@ var _$maxRowLength_785 = function maxRowLength(z) { 'use strict'; -/* removed: var _$maxRowLength_785 = require('./max_row_length'); */; +/* removed: var _$maxRowLength_847 = require('./max_row_length'); */; /* Return a list of empty points in 2D array z * each empty point z[i][j] gives an array [i, j, neighborCount] @@ -56258,14 +58096,14 @@ var _$maxRowLength_785 = function maxRowLength(z) { * if no neighbors exist, we iteratively look for neighbors that HAVE * neighbors, and add a fractional neighborCount */ -var _$findEmpties_779 = function findEmpties(z) { +var _$findEmpties_841 = function findEmpties(z) { var empties = [], neighborHash = {}, noNeighborList = [], nextRow = z[0], row = [], blank = [0, 0, 0], - rowLength = _$maxRowLength_785(z), + rowLength = _$maxRowLength_847(z), prevRow, i, j, @@ -56354,10 +58192,10 @@ var _$findEmpties_779 = function findEmpties(z) { 'use strict'; -var __isArrayOrTypedArray_780 = _$lib_539.isArrayOrTypedArray; +var __isArrayOrTypedArray_842 = _$lib_601.isArrayOrTypedArray; -var _$has_columns_780 = function(trace) { - return !__isArrayOrTypedArray_780(trace.z[0]); +var _$has_columns_842 = function(trace) { + return !__isArrayOrTypedArray_842(trace.z[0]); }; /** @@ -56370,7 +58208,7 @@ var _$has_columns_780 = function(trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; var INTERPTHRESHOLD = 1e-2, NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; @@ -56381,7 +58219,7 @@ function correctionOvershoot(maxFractionalChange) { return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5); } -var _$interp2d_783 = function interp2d(z, emptyPoints, savedInterpZ) { +var _$interp2d_845 = function interp2d(z, emptyPoints, savedInterpZ) { // fill in any missing data in 2D array z using an iterative // poisson equation solver with zero-derivative BC at edges // amazingly, this just amounts to repeatedly averaging all the existing @@ -56414,7 +58252,7 @@ var _$interp2d_783 = function interp2d(z, emptyPoints, savedInterpZ) { correctionOvershoot(maxFractionalChange)); } if(maxFractionalChange > INTERPTHRESHOLD) { - _$lib_539.log('interp2d didn\'t converge quickly', maxFractionalChange); + _$lib_601.log('interp2d didn\'t converge quickly', maxFractionalChange); } return z; @@ -56501,19 +58339,19 @@ function iterateInterp2d(z, emptyPoints, overshoot) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -var __isArrayOrTypedArray_784 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$registry_731 = require('../../registry'); */; +var __isArrayOrTypedArray_846 = _$lib_601.isArrayOrTypedArray; -var _$makeBoundArray_784 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { +var _$makeBoundArray_846 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { var arrayOut = [], - isContour = _$registry_668.traceIs(trace, 'contour'), - isHist = _$registry_668.traceIs(trace, 'histogram'), - isGL2D = _$registry_668.traceIs(trace, 'gl2d'), + isContour = _$registry_731.traceIs(trace, 'contour'), + isHist = _$registry_731.traceIs(trace, 'histogram'), + isGL2D = _$registry_731.traceIs(trace, 'gl2d'), v0, dv, i; - var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_784(arrayIn) && arrayIn.length > 1; + var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_846(arrayIn) && arrayIn.length > 1; if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) { var len = arrayIn.length; @@ -56561,7 +58399,7 @@ var _$makeBoundArray_784 = function makeBoundArray(trace, arrayIn, v0In, dvIn, n var calendar = trace[ax._id.charAt(0) + 'calendar']; if(isHist || ax.type === 'category') v0 = ax.r2c(v0In, 0, calendar) || 0; - else if(__isArrayOrTypedArray_784(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; + else if(__isArrayOrTypedArray_846(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; else if(v0In === undefined) v0 = 0; else v0 = ax.d2c(v0In, 0, calendar); @@ -56585,7 +58423,7 @@ var _$makeBoundArray_784 = function makeBoundArray(trace, arrayIn, v0In, dvIn, n 'use strict'; -var _$doAvg_794 = function doAvg(size, counts) { +var _$doAvg_856 = function doAvg(size, counts) { var nMax = size.length, total = 0; for(var i = 0; i < nMax; i++) { @@ -56609,10 +58447,10 @@ var _$doAvg_794 = function doAvg(size, counts) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -var _$bin_functions_796 = { +var _$bin_functions_858 = { count: function(n, i, size) { size[n]++; return 1; @@ -56620,7 +58458,7 @@ var _$bin_functions_796 = { sum: function(n, i, size, counterData) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); size[n] += v; return v; @@ -56630,7 +58468,7 @@ var _$bin_functions_796 = { avg: function(n, i, size, counterData, counts) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); size[n] += v; counts[n]++; @@ -56640,9 +58478,9 @@ var _$bin_functions_796 = { min: function(n, i, size, counterData) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); - if(!_$fastIsnumeric_139(size[n])) { + if(!_$fastIsnumeric_196(size[n])) { size[n] = v; return v; } @@ -56657,9 +58495,9 @@ var _$bin_functions_796 = { max: function(n, i, size, counterData) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); - if(!_$fastIsnumeric_139(size[n])) { + if(!_$fastIsnumeric_196(size[n])) { size[n] = v; return v; } @@ -56684,14 +58522,14 @@ var _$bin_functions_796 = { 'use strict'; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var oneYear = _$numerical_517.ONEAVGYEAR; -var oneMonth = _$numerical_517.ONEAVGMONTH; -var oneDay = _$numerical_517.ONEDAY; -var oneHour = _$numerical_517.ONEHOUR; -var oneMin = _$numerical_517.ONEMIN; -var oneSec = _$numerical_517.ONESEC; -var tickIncrement = _$axes_584.tickIncrement; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var oneYear = _$numerical_578.ONEAVGYEAR; +var oneMonth = _$numerical_578.ONEAVGMONTH; +var oneDay = _$numerical_578.ONEDAY; +var oneHour = _$numerical_578.ONEHOUR; +var oneMin = _$numerical_578.ONEMIN; +var oneSec = _$numerical_578.ONESEC; +var tickIncrement = _$axes_647.tickIncrement; /* @@ -56705,7 +58543,7 @@ var tickIncrement = _$axes_584.tickIncrement; * @return {function(v, isRightEdge)}: * find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v` */ -var _$getBinSpanLabelRound_797 = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) { +var _$getBinSpanLabelRound_859 = 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) @@ -56860,11 +58698,11 @@ function dateParts(v, pa, calendar) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var cleanDate = _$lib_539.cleanDate; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var __ONEDAY_799 = _$numerical_517.ONEDAY; -var __BADNUM_799 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var cleanDate = _$lib_601.cleanDate; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var __ONEDAY_861 = _$numerical_578.ONEDAY; +var __BADNUM_861 = _$numerical_578.BADNUM; /* * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) @@ -56875,7 +58713,7 @@ var __BADNUM_799 = _$numerical_517.BADNUM; * after trace supplyDefaults are completed. So this gets called during the * calc step, when data are inserted into bins. */ -var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { +var _$cleanBins_861 = function cleanBins(trace, ax, binDirection) { var axType = ax.type, binAttr = binDirection + 'bins', bins = trace[binAttr]; @@ -56883,8 +58721,8 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { if(!bins) bins = trace[binAttr] = {}; var cleanBound = (axType === 'date') ? - function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_799, bins.calendar) : null; } : - function(v) { return _$fastIsnumeric_139(v) ? Number(v) : null; }; + function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_861, bins.calendar) : null; } : + function(v) { return _$fastIsnumeric_196(v) ? Number(v) : null; }; bins.start = cleanBound(bins.start); bins.end = cleanBound(bins.end); @@ -56892,10 +58730,10 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) // but without the extra string options for log axes // ie the only strings we accept are M for months - var sizeDflt = (axType === 'date') ? __ONEDAY_799 : 1, + var sizeDflt = (axType === 'date') ? __ONEDAY_861 : 1, binSize = bins.size; - if(_$fastIsnumeric_139(binSize)) { + if(_$fastIsnumeric_196(binSize)) { bins.size = (binSize > 0) ? Number(binSize) : sizeDflt; } else if(typeof binSize !== 'string') { @@ -56906,7 +58744,7 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { var prefix = binSize.charAt(0), sizeNum = binSize.substr(1); - sizeNum = _$fastIsnumeric_139(sizeNum) ? Number(sizeNum) : 0; + sizeNum = _$fastIsnumeric_196(sizeNum) ? Number(sizeNum) : 0; if((sizeNum <= 0) || !( axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum) )) { @@ -56941,7 +58779,7 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { 'use strict'; -var _$norm_functions_804 = { +var _$norm_functions_866 = { percent: function(size, total) { var nMax = size.length, norm = 100 / total; @@ -56974,20 +58812,20 @@ var _$norm_functions_804 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$bin_functions_796 = require('../histogram/bin_functions'); */; -/* removed: var _$norm_functions_804 = require('../histogram/norm_functions'); */; -/* removed: var _$doAvg_794 = require('../histogram/average'); */; -/* removed: var _$cleanBins_799 = require('../histogram/clean_bins'); */; -/* removed: var _$getBinSpanLabelRound_797 = require('../histogram/bin_label_vals'); */; +/* removed: var _$bin_functions_858 = require('../histogram/bin_functions'); */; +/* removed: var _$norm_functions_866 = require('../histogram/norm_functions'); */; +/* removed: var _$doAvg_856 = require('../histogram/average'); */; +/* removed: var _$cleanBins_861 = require('../histogram/clean_bins'); */; +/* removed: var _$getBinSpanLabelRound_859 = require('../histogram/bin_label_vals'); */; -var _$calc_806 = function calc(gd, trace) { - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); +var _$calc_868 = function calc(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'); var x = trace.x ? xa.makeCalcdata(trace, 'x') : []; - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); + var ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'); var y = trace.y ? ya.makeCalcdata(trace, 'y') : []; var xcalendar = trace.xcalendar; var ycalendar = trace.ycalendar; @@ -57024,8 +58862,8 @@ var _$calc_806 = function calc(gd, trace) { var densitynorm = (norm.indexOf('density') !== -1); var extremefunc = (func === 'max' || func === 'min'); var sizeinit = (extremefunc ? null : 0); - var binfunc = _$bin_functions_796.count; - var normfunc = _$norm_functions_804[norm]; + var binfunc = _$bin_functions_858.count; + var normfunc = _$norm_functions_866[norm]; var doavg = false; var xinc = []; var yinc = []; @@ -57041,16 +58879,16 @@ var _$calc_806 = function calc(gd, trace) { trace.marker.color : ''); if(rawCounterData && func !== 'count') { doavg = func === 'avg'; - binfunc = _$bin_functions_796[func]; + binfunc = _$bin_functions_858[func]; } // decrease end a little in case of rounding errors var binSpec = trace.xbins, binStart = xr2c(binSpec.start), binEnd = xr2c(binSpec.end) + - (binStart - _$axes_584.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; + (binStart - _$axes_647.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; - for(i = binStart; i < binEnd; i = _$axes_584.tickIncrement(i, binSpec.size, false, xcalendar)) { + for(i = binStart; i < binEnd; i = _$axes_647.tickIncrement(i, binSpec.size, false, xcalendar)) { onecol.push(sizeinit); xEdges.push(i); if(doavg) zerocol.push(0); @@ -57065,9 +58903,9 @@ var _$calc_806 = function calc(gd, trace) { binSpec = trace.ybins; binStart = yr2c(binSpec.start); binEnd = yr2c(binSpec.end) + - (binStart - _$axes_584.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; + (binStart - _$axes_647.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; - for(i = binStart; i < binEnd; i = _$axes_584.tickIncrement(i, binSpec.size, false, ycalendar)) { + for(i = binStart; i < binEnd; i = _$axes_647.tickIncrement(i, binSpec.size, false, ycalendar)) { z.push(onecol.slice()); yEdges.push(i); var ipCol = new Array(nx); @@ -57104,8 +58942,8 @@ var _$calc_806 = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { var xi = x[i]; var yi = y[i]; - n = _$lib_539.findBin(xi, xbins); - m = _$lib_539.findBin(yi, ybins); + n = _$lib_601.findBin(xi, xbins); + m = _$lib_601.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); @@ -57127,7 +58965,7 @@ var _$calc_806 = function calc(gd, trace) { } // normalize, if needed if(doavg) { - for(m = 0; m < ny; m++) total += _$doAvg_794(z[m], counts[m]); + for(m = 0; m < ny; m++) total += _$doAvg_856(z[m], counts[m]); } if(normfunc) { for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); @@ -57152,16 +58990,16 @@ function cleanAndAutobin(trace, axLetter, data, ax, r2c, c2r, calendar) { var autoBinAttr = 'autobin' + axLetter; var binSpec = trace[binSpecAttr]; - _$cleanBins_799(trace, ax, axLetter); + _$cleanBins_861(trace, ax, axLetter); if(trace[autoBinAttr] || !binSpec || binSpec.start === null || binSpec.end === null) { - binSpec = _$axes_584.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); + binSpec = _$axes_647.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); if(trace.type === 'histogram2dcontour') { // the "true" last argument reverses the tick direction (which we can't // just do with a minus sign because of month bins) - binSpec.start = c2r(_$axes_584.tickIncrement( + binSpec.start = c2r(_$axes_647.tickIncrement( r2c(binSpec.start), binSpec.size, true, calendar)); - binSpec.end = c2r(_$axes_584.tickIncrement( + binSpec.end = c2r(_$axes_647.tickIncrement( r2c(binSpec.end), binSpec.size, false, calendar)); } @@ -57204,7 +59042,7 @@ function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]]; } else { - var roundFn = _$getBinSpanLabelRound_797(gapLow, gapHigh, edges, ax, calendar); + var roundFn = _$getBinSpanLabelRound_859(gapLow, gapHigh, edges, ax, calendar); for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)]; } return out; @@ -57221,29 +59059,29 @@ function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calc_806 = require('../histogram2d/calc'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$has_columns_780 = require('./has_columns'); */; -/* removed: var _$convertColumnData_777 = require('./convert_column_xyz'); */; -/* removed: var _$maxRowLength_785 = require('./max_row_length'); */; -/* removed: var _$clean2dArray_775 = require('./clean_2d_array'); */; -/* removed: var _$interp2d_783 = require('./interp2d'); */; -/* removed: var _$findEmpties_779 = require('./find_empties'); */; -/* removed: var _$makeBoundArray_784 = require('./make_bound_array'); */; +/* removed: var _$calc_868 = require('../histogram2d/calc'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$has_columns_842 = require('./has_columns'); */; +/* removed: var _$convertColumnData_839 = require('./convert_column_xyz'); */; +/* removed: var _$maxRowLength_847 = require('./max_row_length'); */; +/* removed: var _$clean2dArray_837 = require('./clean_2d_array'); */; +/* removed: var _$interp2d_845 = require('./interp2d'); */; +/* removed: var _$findEmpties_841 = require('./find_empties'); */; +/* removed: var _$makeBoundArray_846 = require('./make_bound_array'); */; -var _$calc_774 = function calc(gd, trace) { +var _$calc_836 = 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_584.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'), - isContour = _$registry_668.traceIs(trace, 'contour'), - isHist = _$registry_668.traceIs(trace, 'histogram'), - isGL2D = _$registry_668.traceIs(trace, 'gl2d'), + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'), + isContour = _$registry_731.traceIs(trace, 'contour'), + isHist = _$registry_731.traceIs(trace, 'histogram'), + isGL2D = _$registry_731.traceIs(trace, 'gl2d'), zsmooth = isContour ? 'best' : trace.zsmooth, x, x0, @@ -57260,7 +59098,7 @@ var _$calc_774 = function calc(gd, trace) { ya._minDtick = 0; if(isHist) { - binned = _$calc_806(gd, trace); + binned = _$calc_868(gd, trace); x = binned.x; x0 = binned.x0; dx = binned.dx; @@ -57270,10 +59108,12 @@ var _$calc_774 = function calc(gd, trace) { z = binned.z; } else { - if(_$has_columns_780(trace)) { - _$convertColumnData_777(trace, xa, ya, 'x', 'y', ['z']); - x = trace.x; - y = trace.y; + var zIn = trace.z; + if(_$has_columns_842(trace)) { + _$convertColumnData_839(trace, xa, ya, 'x', 'y', ['z']); + x = trace._x; + y = trace._y; + zIn = trace._z; } else { x = trace.x ? xa.makeCalcdata(trace, 'x') : []; y = trace.y ? ya.makeCalcdata(trace, 'y') : []; @@ -57284,17 +59124,17 @@ var _$calc_774 = function calc(gd, trace) { y0 = trace.y0 || 0; dy = trace.dy || 1; - z = _$clean2dArray_775(trace.z, trace.transpose); + z = _$clean2dArray_837(zIn, trace.transpose); if(isContour || trace.connectgaps) { - trace._emptypoints = _$findEmpties_779(z); - trace._interpz = _$interp2d_783(z, trace._emptypoints, trace._interpz); + trace._emptypoints = _$findEmpties_841(z); + trace._interpz = _$interp2d_845(z, trace._emptypoints, trace._interpz); } } function noZsmooth(msg) { zsmooth = trace._input.zsmooth = trace.zsmooth = false; - _$lib_539.warn('cannot use zsmooth: "fast": ' + msg); + _$lib_601.warn('cannot use zsmooth: "fast": ' + msg); } // check whether we really can smooth (ie all boxes are about the same size) @@ -57327,23 +59167,23 @@ var _$calc_774 = function calc(gd, trace) { } // create arrays of brick boundaries, to be used by autorange and heatmap.plot - var xlen = _$maxRowLength_785(z); + var xlen = _$maxRowLength_847(z); var xIn = trace.xtype === 'scaled' ? '' : x; - var xArray = _$makeBoundArray_784(trace, xIn, x0, dx, xlen, xa); + var xArray = _$makeBoundArray_846(trace, xIn, x0, dx, xlen, xa); var yIn = trace.ytype === 'scaled' ? '' : y; - var yArray = _$makeBoundArray_784(trace, yIn, y0, dy, z.length, ya); + var yArray = _$makeBoundArray_846(trace, yIn, y0, dy, z.length, ya); // handled in gl2d convert step if(!isGL2D) { - _$axes_584.expand(xa, xArray); - _$axes_584.expand(ya, yArray); + _$axes_647.expand(xa, xArray); + _$axes_647.expand(ya, yArray); } var cd0 = { x: xArray, y: yArray, z: z, - text: trace.text + text: trace._text || trace.text }; if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn; @@ -57357,7 +59197,7 @@ var _$calc_774 = function calc(gd, trace) { // auto-z and autocolorscale if applicable if(!isContour || trace.contours.type !== 'constraint') { - _$calc_418(trace, z, '', 'z'); + _$calc_480(trace, z, '', 'z'); } if(isContour && trace.contours && trace.contours.coloring === 'heatmap') { @@ -57366,8 +59206,8 @@ var _$calc_774 = function calc(gd, trace) { xcalendar: trace.xcalendar, ycalendar: trace.ycalendar }; - cd0.xfill = _$makeBoundArray_784(dummyTrace, xIn, x0, dx, xlen, xa); - cd0.yfill = _$makeBoundArray_784(dummyTrace, yIn, y0, dy, z.length, ya); + cd0.xfill = _$makeBoundArray_846(dummyTrace, xIn, x0, dx, xlen, xa); + cd0.yfill = _$makeBoundArray_846(dummyTrace, yIn, y0, dy, z.length, ya); } return [cd0]; @@ -57384,15 +59224,15 @@ var _$calc_774 = function calc(gd, trace) { 'use strict'; -/* removed: var _$calc_774 = require('../heatmap/calc'); */; -/* removed: var _$setContours_763 = require('./set_contours'); */; +/* removed: var _$calc_836 = require('../heatmap/calc'); */; +/* removed: var _$setContours_825 = require('./set_contours'); */; // 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 -var _$calc_745 = function calc(gd, trace) { - var cd = _$calc_774(gd, trace); - _$setContours_763(trace); +var _$calc_807 = function calc(gd, trace) { + var cd = _$calc_836(gd, trace); + _$setContours_825(trace); return cd; }; @@ -57411,7 +59251,7 @@ var _$calc_745 = function calc(gd, trace) { * tiny helper to move the end of the contours a little to prevent * losing the last contour to rounding errors */ -var _$endPlus_755 = function endPlus(contours) { +var _$endPlus_817 = function endPlus(contours) { return contours.end + contours.size / 1e6; }; @@ -57426,14 +59266,14 @@ var _$endPlus_755 = function endPlus(contours) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$endPlus_755 = require('./end_plus'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$endPlus_817 = require('./end_plus'); */; -var _$makeColorMap_760 = function makeColorMap(trace) { +var _$makeColorMap_822 = function makeColorMap(trace) { var contours = trace.contours, start = contours.start, - end = _$endPlus_755(contours), + end = _$endPlus_817(contours), cs = contours.size || 1, nc = Math.floor((end - start) / cs) + 1, extra = contours.coloring === 'lines' ? 0 : 1; @@ -57466,7 +59306,7 @@ var _$makeColorMap_760 = function makeColorMap(trace) { // do the contours extend beyond the colorscale? // if so, extend the colorscale with constants - var zRange = _$d3_127.extent([trace.zmin, trace.zmax, contours.start, + var zRange = _$d3_130.extent([trace.zmin, trace.zmax, contours.start, contours.start + cs * (nc - 1)]), zmin = zRange[trace.zmin < trace.zmax ? 0 : 1], zmax = zRange[trace.zmin < trace.zmax ? 1 : 0]; @@ -57490,7 +59330,7 @@ var _$makeColorMap_760 = function makeColorMap(trace) { } } - return _$colorscale_426.makeColorScaleFunc({ + return _$colorscale_488.makeColorScaleFunc({ domain: domain, range: range, }, { @@ -57509,25 +59349,25 @@ var _$makeColorMap_760 = function makeColorMap(trace) { 'use strict'; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -/* removed: var _$makeColorMap_760 = require('./make_color_map'); */; -/* removed: var _$endPlus_755 = require('./end_plus'); */; +/* removed: var _$makeColorMap_822 = require('./make_color_map'); */; +/* removed: var _$endPlus_817 = require('./end_plus'); */; -var _$colorbar_747 = function colorbar(gd, cd) { +var _$colorbar_809 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid; gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = _$draw_415(gd, cbId); + var cb = _$draw_477(gd, cbId); cd[0].t.cb = cb; var contours = trace.contours, @@ -57535,7 +59375,7 @@ var _$colorbar_747 = function colorbar(gd, cd) { cs = contours.size || 1, coloring = contours.coloring; - var colorMap = _$makeColorMap_760(trace, {isColorbar: true}); + var colorMap = _$makeColorMap_822(trace, {isColorbar: true}); if(coloring === 'heatmap') { cb.filllevels({ @@ -57553,7 +59393,7 @@ var _$colorbar_747 = function colorbar(gd, cd) { }) .levels({ start: contours.start, - end: _$endPlus_755(contours), + end: _$endPlus_817(contours), size: cs }) .options(trace.colorbar)(); @@ -57570,14 +59410,14 @@ var _$colorbar_747 = function colorbar(gd, cd) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$handleLabelDefaults_759 = function handleLabelDefaults(coerce, layout, lineColor, opts) { +var _$handleLabelDefaults_821 = function handleLabelDefaults(coerce, layout, lineColor, opts) { if(!opts) opts = {}; var showLabels = coerce('contours.showlabels'); if(showLabels) { var globalFont = layout.font; - _$lib_539.coerceFont(coerce, 'contours.labelfont', { + _$lib_601.coerceFont(coerce, 'contours.labelfont', { family: globalFont.family, size: globalFont.size, color: lineColor @@ -57598,19 +59438,19 @@ var _$handleLabelDefaults_759 = function handleLabelDefaults(coerce, layout, lin 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$handleLabelDefaults_759 = require('./label_defaults'); */; +/* removed: var _$handleLabelDefaults_821 = require('./label_defaults'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -var __addOpacity_749 = _$color_411.addOpacity; -var opacity = _$color_411.opacity; +/* removed: var _$color_473 = require('../../components/color'); */; +var __addOpacity_811 = _$color_473.addOpacity; +var opacity = _$color_473.opacity; -/* removed: var _$filter_ops_512 = require('../../constants/filter_ops'); */; -var CONSTRAINT_REDUCTION = _$filter_ops_512.CONSTRAINT_REDUCTION; -var __COMPARISON_OPS2_749 = _$filter_ops_512.COMPARISON_OPS2; +/* removed: var _$filter_ops_574 = require('../../constants/filter_ops'); */; +var CONSTRAINT_REDUCTION = _$filter_ops_574.CONSTRAINT_REDUCTION; +var __COMPARISON_OPS2_811 = _$filter_ops_574.COMPARISON_OPS2; -var _$handleConstraintDefaults_749 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { +var _$handleConstraintDefaults_811 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { var contours = traceOut.contours; var showLines, lineColor, fillColor; @@ -57624,14 +59464,14 @@ var _$handleConstraintDefaults_749 = function handleConstraintDefaults(traceIn, } else { showLines = coerce('contours.showlines'); - fillColor = coerce('fillcolor', __addOpacity_749( + fillColor = coerce('fillcolor', __addOpacity_811( (traceIn.line || {}).color || defaultColor, 0.5 )); } if(showLines) { var lineDfltColor = fillColor && opacity(fillColor) ? - __addOpacity_749(traceOut.fillcolor, 1) : + __addOpacity_811(traceOut.fillcolor, 1) : defaultColor; lineColor = coerce('line.color', lineDfltColor); coerce('line.width', 2); @@ -57640,18 +59480,18 @@ var _$handleConstraintDefaults_749 = function handleConstraintDefaults(traceIn, coerce('line.smoothing'); - _$handleLabelDefaults_759(coerce, layout, lineColor, opts); + _$handleLabelDefaults_821(coerce, layout, lineColor, opts); }; function handleConstraintValueDefaults(coerce, contours) { var zvalue; - if(__COMPARISON_OPS2_749.indexOf(contours.operation) === -1) { + if(__COMPARISON_OPS2_811.indexOf(contours.operation) === -1) { // Requires an array of two numbers: coerce('contours.value', [0, 1]); if(!Array.isArray(contours.value)) { - if(_$fastIsnumeric_139(contours.value)) { + if(_$fastIsnumeric_196(contours.value)) { zvalue = parseFloat(contours.value); contours.value = [zvalue, zvalue + 1]; } @@ -57672,7 +59512,7 @@ function handleConstraintValueDefaults(coerce, contours) { // Requires a single scalar: coerce('contours.value', 0); - if(!_$fastIsnumeric_139(contours.value)) { + if(!_$fastIsnumeric_196(contours.value)) { if(Array.isArray(contours.value)) { contours.value = parseFloat(contours.value[0]); } else { @@ -57692,7 +59532,7 @@ function handleConstraintValueDefaults(coerce, contours) { 'use strict'; -var _$handleContourDefaults_751 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { +var _$handleContourDefaults_813 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { var contourStart = coerce2('contours.start'); var contourEnd = coerce2('contours.end'); var missingEnd = (contourStart === false) || (contourEnd === false); @@ -57721,11 +59561,11 @@ var _$handleContourDefaults_751 = function handleContourDefaults(traceIn, traceO 'use strict'; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$handleLabelDefaults_759 = require('./label_defaults'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$handleLabelDefaults_821 = require('./label_defaults'); */; -var _$handleStyleDefaults_765 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { +var _$handleStyleDefaults_827 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { var coloring = coerce('contours.coloring'); var showLines; @@ -57739,14 +59579,14 @@ var _$handleStyleDefaults_765 = function handleStyleDefaults(traceIn, traceOut, } if(coloring !== 'none') { - _$colorScaleDefaults_421( + _$colorScaleDefaults_483( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); } coerce('line.smoothing'); - _$handleLabelDefaults_759(coerce, layout, lineColor, opts); + _$handleLabelDefaults_821(coerce, layout, lineColor, opts); }; /** @@ -57760,13 +59600,13 @@ var _$handleStyleDefaults_765 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_789 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_851 = _$lib_601.isArrayOrTypedArray; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$has_columns_780 = require('./has_columns'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$has_columns_842 = require('./has_columns'); */; -var _$handleXYZDefaults_789 = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) { +var _$handleXYZDefaults_851 = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) { var z = coerce('z'); xName = xName || 'x'; yName = yName || 'y'; @@ -57774,7 +59614,7 @@ var _$handleXYZDefaults_789 = function handleXYZDefaults(traceIn, traceOut, coer if(z === undefined || !z.length) return 0; - if(_$has_columns_780(traceIn)) { + if(_$has_columns_842(traceIn)) { x = coerce(xName); y = coerce(yName); @@ -57791,7 +59631,7 @@ var _$handleXYZDefaults_789 = function handleXYZDefaults(traceIn, traceOut, coer coerce('transpose'); } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout); return traceOut.z.length; @@ -57827,13 +59667,13 @@ function isValidZ(z) { for(var i = 0; i < z.length; i++) { zi = z[i]; - if(!__isArrayOrTypedArray_789(zi)) { + if(!__isArrayOrTypedArray_851(zi)) { allRowsAreArrays = false; break; } if(zi.length > 0) oneRowIsFilled = true; for(var j = 0; j < zi.length; j++) { - if(_$fastIsnumeric_139(zi[j])) { + if(_$fastIsnumeric_196(zi[j])) { hasOneNumber = true; break; } @@ -57854,26 +59694,26 @@ function isValidZ(z) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$has_columns_780 = require('../heatmap/has_columns'); */; -/* removed: var _$handleXYZDefaults_789 = require('../heatmap/xyz_defaults'); */; -/* removed: var _$handleConstraintDefaults_749 = require('./constraint_defaults'); */; -/* removed: var _$handleContourDefaults_751 = require('./contours_defaults'); */; -/* removed: var _$handleStyleDefaults_765 = require('./style_defaults'); */; -/* removed: var _$attributes_744 = require('./attributes'); */; +/* removed: var _$has_columns_842 = require('../heatmap/has_columns'); */; +/* removed: var _$handleXYZDefaults_851 = require('../heatmap/xyz_defaults'); */; +/* removed: var _$handleConstraintDefaults_811 = require('./constraint_defaults'); */; +/* removed: var _$handleContourDefaults_813 = require('./contours_defaults'); */; +/* removed: var _$handleStyleDefaults_827 = require('./style_defaults'); */; +/* removed: var _$attributes_806 = require('./attributes'); */; -var _$supplyDefaults_753 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_815 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_744, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_806, attr, dflt); } function coerce2(attr) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_744, attr); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_806, attr); } - var len = _$handleXYZDefaults_789(traceIn, traceOut, coerce, layout); + var len = _$handleXYZDefaults_851(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -57881,17 +59721,17 @@ var _$supplyDefaults_753 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); var isConstraint = (coerce('contours.type') === 'constraint'); - coerce('connectgaps', _$has_columns_780(traceOut)); + coerce('connectgaps', _$has_columns_842(traceOut)); // trace-level showlegend has already been set, but is only allowed if this is a constraint if(!isConstraint) delete traceOut.showlegend; if(isConstraint) { - _$handleConstraintDefaults_749(traceIn, traceOut, coerce, layout, defaultColor); + _$handleConstraintDefaults_811(traceIn, traceOut, coerce, layout, defaultColor); } else { - _$handleContourDefaults_751(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_765(traceIn, traceOut, coerce, layout); + _$handleContourDefaults_813(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_827(traceIn, traceOut, coerce, layout); } }; @@ -57906,11 +59746,11 @@ var _$supplyDefaults_753 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { +var _$hoverPoints_843 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { var cd0 = pointData.cd[0]; var trace = cd0.trace; var xa = pointData.xa; @@ -57934,7 +59774,7 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h ny = Math.round(pointData.index[0]); } catch(e) { - _$lib_539.error('Error hovering on heatmap, ' + + _$lib_601.error('Error hovering on heatmap, ' + 'pointNumber must be [row,col], found:', pointData.index); return; } @@ -57942,8 +59782,8 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h return; } } - else if(_$fx_453.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || - _$fx_453.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) { + else if(_$fx_515.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || + _$fx_515.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) { return; } else { @@ -57962,8 +59802,8 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h } y2.push([2 * y[y.length - 1] - y[y.length - 2]]); } - nx = Math.max(0, Math.min(x2.length - 2, _$lib_539.findBin(xval, x2))); - ny = Math.max(0, Math.min(y2.length - 2, _$lib_539.findBin(yval, y2))); + nx = Math.max(0, Math.min(x2.length - 2, _$lib_601.findBin(xval, x2))); + ny = Math.max(0, Math.min(y2.length - 2, _$lib_601.findBin(yval, y2))); } var x0 = xa.c2p(x[nx]), @@ -58003,10 +59843,10 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h _separators: xa._separators, _numFormat: xa._numFormat }; - var zLabelObj = _$axes_584.tickText(dummyAx, zVal, 'hover'); + var zLabelObj = _$axes_647.tickText(dummyAx, zVal, 'hover'); zLabel = zLabelObj.text; - return [_$lib_539.extendFlat(pointData, { + return [_$lib_601.extendFlat(pointData, { index: [ny, nx], // never let a 2D override 1D type as closest point distance: pointData.maxHoverDistance, @@ -58034,22 +59874,22 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$hoverPoints_781 = require('../heatmap/hover'); */; +/* removed: var _$hoverPoints_843 = require('../heatmap/hover'); */; -var _$hoverPoints_757 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { - var hoverData = _$hoverPoints_781(pointData, xval, yval, hovermode, hoverLayer, true); +var _$hoverPoints_819 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { + var hoverData = _$hoverPoints_843(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_411.opacity(trace.fillcolor)) { - hoverPt.color = _$color_411.addOpacity(trace.fillcolor, 1); + if(trace.fillcolor && _$color_473.opacity(trace.fillcolor)) { + hoverPt.color = _$color_473.addOpacity(trace.fillcolor, 1); } - else if(trace.contours.showlines && _$color_411.opacity(trace.line.color)) { - hoverPt.color = _$color_411.addOpacity(trace.line.color, 1); + else if(trace.contours.showlines && _$color_473.opacity(trace.line.color)) { + hoverPt.color = _$color_473.addOpacity(trace.line.color, 1); } } }); @@ -58068,7 +59908,7 @@ var _$hoverPoints_757 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -var _$close_boundaries_746 = function(pathinfo, operation, perimeter, trace) { +var _$close_boundaries_808 = function(pathinfo, operation, perimeter, trace) { // Abandon all hope, ye who enter here. var i, v1, v2; var pi0 = pathinfo[0]; @@ -58133,7 +59973,7 @@ var _$close_boundaries_746 = function(pathinfo, operation, perimeter, trace) { */ 'use strict'; -var _$constants_748 = { +var _$constants_810 = { // some constants to help with marching squares algorithm // where does the path start for each index? BOTTOMSTART: [1, 9, 13, 104, 713], @@ -58211,13 +60051,13 @@ var _$constants_748 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; // 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. -var _$convert_to_constraints_752 = function(pathinfo, operation) { +var _$convert_to_constraints_814 = function(pathinfo, operation) { var i, pi0, pi1; var op0 = function(arr) { return arr.reverse(); }; @@ -58229,7 +60069,7 @@ var _$convert_to_constraints_752 = function(pathinfo, operation) { return pathinfo; case '>': if(pathinfo.length !== 1) { - _$lib_539.warn('Contour data invalid for the specified inequality operation.'); + _$lib_601.warn('Contour data invalid for the specified inequality operation.'); } // In this case there should be exactly two contour levels in pathinfo. We @@ -58254,7 +60094,7 @@ var _$convert_to_constraints_752 = function(pathinfo, operation) { case '[]': /* eslint-enable: no-fallthrough */ if(pathinfo.length !== 2) { - _$lib_539.warn('Contour data invalid for the specified inequality range operation.'); + _$lib_601.warn('Contour data invalid for the specified inequality range operation.'); } // In this case there should be exactly two contour levels in pathinfo. We @@ -58282,9 +60122,9 @@ var _$convert_to_constraints_752 = function(pathinfo, operation) { }; function copyPathinfo(pi) { - return _$lib_539.extendFlat({}, pi, { - edgepaths: _$lib_539.extendDeep([], pi.edgepaths), - paths: _$lib_539.extendDeep([], pi.paths) + return _$lib_601.extendFlat({}, pi, { + edgepaths: _$lib_601.extendDeep([], pi.edgepaths), + paths: _$lib_601.extendDeep([], pi.paths) }); } @@ -58298,12 +60138,12 @@ function copyPathinfo(pi) { 'use strict'; -/* removed: var _$filter_ops_512 = require('../../constants/filter_ops'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$filter_ops_574 = require('../../constants/filter_ops'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; // This syntax conforms to the existing filter transform syntax, but we don't care // about open vs. closed intervals for simply drawing contours constraints: -var _$constraint_mapping_750 = { +var _$constraint_mapping_812 = { '[]': makeRangeSettings('[]'), '][': makeRangeSettings(']['), '>': makeInequalitySettings('>'), @@ -58319,16 +60159,16 @@ function coerceValue(operation, value) { var coercedValue; function coerce(value) { - return _$fastIsnumeric_139(value) ? (+value) : null; + return _$fastIsnumeric_196(value) ? (+value) : null; } - if(_$filter_ops_512.COMPARISON_OPS2.indexOf(operation) !== -1) { + if(_$filter_ops_574.COMPARISON_OPS2.indexOf(operation) !== -1) { coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value); - } else if(_$filter_ops_512.INTERVAL_OPS.indexOf(operation) !== -1) { + } else if(_$filter_ops_574.INTERVAL_OPS.indexOf(operation) !== -1) { coercedValue = hasArrayValue ? [coerce(value[0]), coerce(value[1])] : [coerce(value), coerce(value)]; - } else if(_$filter_ops_512.SET_OPS.indexOf(operation) !== -1) { + } else if(_$filter_ops_574.SET_OPS.indexOf(operation) !== -1) { coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)]; } @@ -58376,20 +60216,20 @@ function makeInequalitySettings(operation) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$constraint_mapping_750 = require('./constraint_mapping'); */; -/* removed: var _$endPlus_755 = require('./end_plus'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$constraint_mapping_812 = require('./constraint_mapping'); */; +/* removed: var _$endPlus_817 = require('./end_plus'); */; -var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { +var _$emptyPathinfo_816 = function emptyPathinfo(contours, plotinfo, cd0) { var contoursFinal = (contours.type === 'constraint') ? - _$constraint_mapping_750[contours._operation](contours.value) : + _$constraint_mapping_812[contours._operation](contours.value) : contours; var cs = contoursFinal.size; var pathinfo = []; - var end = _$endPlus_755(contoursFinal); + var end = _$endPlus_817(contoursFinal); - var carpet = cd0.trace.carpetTrace; + var carpet = cd0.trace._carpetTrace; var basePathinfo = carpet ? { // store axes so we can convert to px @@ -58406,7 +60246,7 @@ var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { }; for(var ci = contoursFinal.start; ci < end; ci += cs) { - pathinfo.push(_$lib_539.extendFlat({ + pathinfo.push(_$lib_601.extendFlat({ level: ci, // all the cells with nontrivial marching index crossings: {}, @@ -58422,7 +60262,7 @@ var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { }, basePathinfo)); if(pathinfo.length > 1000) { - _$lib_539.warn('Too many contours, clipping at 1000', contours); + _$lib_601.warn('Too many contours, clipping at 1000', contours); break; } } @@ -58439,10 +60279,10 @@ var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$constants_748 = require('./constants'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$constants_810 = require('./constants'); */; -var _$findAllPaths_756 = function findAllPaths(pathinfo, xtol, ytol) { +var _$findAllPaths_818 = function findAllPaths(pathinfo, xtol, ytol) { var cnt, startLoc, i, @@ -58467,7 +60307,7 @@ var _$findAllPaths_756 = function findAllPaths(pathinfo, xtol, ytol) { startLoc = Object.keys(pi.crossings)[0].split(',').map(Number); makePath(pi, startLoc, undefined, xtol, ytol); } - if(cnt === 10000) _$lib_539.log('Infinite loop in contour?'); + if(cnt === 10000) _$lib_601.log('Infinite loop in contour?'); } }; @@ -58498,16 +60338,16 @@ function makePath(pi, loc, edgeflag, xtol, ytol) { // now follow the path for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops if(mi > 20) { - mi = _$constants_748.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1]; - pi.crossings[locStr] = _$constants_748.SADDLEREMAINDER[mi]; + mi = _$constants_810.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1]; + pi.crossings[locStr] = _$constants_810.SADDLEREMAINDER[mi]; } else { delete pi.crossings[locStr]; } - marchStep = _$constants_748.NEWDELTA[mi]; + marchStep = _$constants_810.NEWDELTA[mi]; if(!marchStep) { - _$lib_539.log('Found bad marching index:', mi, loc, pi.level); + _$lib_601.log('Found bad marching index:', mi, loc, pi.level); break; } @@ -58531,7 +60371,7 @@ function makePath(pi, loc, edgeflag, xtol, ytol) { } if(cnt === 10000) { - _$lib_539.log('Infinite loop in contour?'); + _$lib_601.log('Infinite loop in contour?'); } var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol); var totaldist = 0; @@ -58618,7 +60458,7 @@ function makePath(pi, loc, edgeflag, xtol, ytol) { } else { if(!edgeflag) { - _$lib_539.log('Unclosed interior contour?', + _$lib_601.log('Unclosed interior contour?', pi.level, startLocStr, pts.join('L')); } @@ -58684,9 +60524,9 @@ function startStep(mi, edgeflag, loc) { dy = loc[1] === 0 ? 1 : -1; } } - else if(_$constants_748.BOTTOMSTART.indexOf(mi) !== -1) dy = 1; - else if(_$constants_748.LEFTSTART.indexOf(mi) !== -1) dx = 1; - else if(_$constants_748.TOPSTART.indexOf(mi) !== -1) dy = -1; + else if(_$constants_810.BOTTOMSTART.indexOf(mi) !== -1) dy = 1; + else if(_$constants_810.LEFTSTART.indexOf(mi) !== -1) dx = 1; + else if(_$constants_810.TOPSTART.indexOf(mi) !== -1) dy = -1; else dx = -1; return [dx, dy]; } @@ -58738,13 +60578,13 @@ function getInterpPx(pi, loc, step) { 'use strict'; -/* removed: var _$constants_748 = require('./constants'); */; +/* removed: var _$constants_810 = require('./constants'); */; // Calculate all the marching indices, for ALL levels at once. // since we want to be exhaustive we'll check for contour crossings // at every intersection, rather than just following a path // TODO: shorten the inner loop to only the relevant levels -var _$makeCrossings_761 = function makeCrossings(pathinfo) { +var _$makeCrossings_823 = function makeCrossings(pathinfo) { var z = pathinfo[0].z, m = z.length, n = z[0].length, // we already made sure z isn't ragged in interp2d @@ -58761,13 +60601,13 @@ var _$makeCrossings_761 = function makeCrossings(pathinfo) { for(yi = 0; yi < m - 1; yi++) { ystartIndices = []; - if(yi === 0) ystartIndices = ystartIndices.concat(_$constants_748.BOTTOMSTART); - if(yi === m - 2) ystartIndices = ystartIndices.concat(_$constants_748.TOPSTART); + if(yi === 0) ystartIndices = ystartIndices.concat(_$constants_810.BOTTOMSTART); + if(yi === m - 2) ystartIndices = ystartIndices.concat(_$constants_810.TOPSTART); for(xi = 0; xi < n - 1; xi++) { startIndices = ystartIndices.slice(); - if(xi === 0) startIndices = startIndices.concat(_$constants_748.LEFTSTART); - if(xi === n - 2) startIndices = startIndices.concat(_$constants_748.RIGHTSTART); + if(xi === 0) startIndices = startIndices.concat(_$constants_810.LEFTSTART); + if(xi === n - 2) startIndices = startIndices.concat(_$constants_810.RIGHTSTART); label = xi + ',' + yi; corners = [[z[yi][xi], z[yi][xi + 1]], @@ -58830,23 +60670,23 @@ function getMarchingIndex(val, corners) { 'use strict'; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$maxRowLength_785 = require('./max_row_length'); */; +/* removed: var _$maxRowLength_847 = require('./max_row_length'); */; -var _$plot_786 = function(gd, plotinfo, cdheatmaps) { +var _$plot_848 = function(gd, plotinfo, cdheatmaps) { for(var i = 0; i < cdheatmaps.length; i++) { - __plotOne_786(gd, plotinfo, cdheatmaps[i]); + __plotOne_848(gd, plotinfo, cdheatmaps[i]); } }; -function __plotOne_786(gd, plotinfo, cd) { +function __plotOne_848(gd, plotinfo, cd) { var cd0 = cd[0]; var trace = cd0.trace; var uid = trace.uid; @@ -58871,12 +60711,12 @@ function __plotOne_786(gd, plotinfo, cd) { var y = cd0.y; var xc = cd0.xCenter; var yc = cd0.yCenter; - var isContour = _$registry_668.traceIs(trace, 'contour'); + var isContour = _$registry_731.traceIs(trace, 'contour'); var zsmooth = isContour ? 'best' : trace.zsmooth; // get z dims var m = z.length; - var n = _$maxRowLength_785(z); + var n = _$maxRowLength_847(z); var xrev = false; var yrev = false; @@ -58986,8 +60826,8 @@ function __plotOne_786(gd, plotinfo, cd) { canvas.height = canvasH; var context = canvas.getContext('2d'); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, trace.zmin, trace.zmax @@ -59001,18 +60841,18 @@ function __plotOne_786(gd, plotinfo, cd) { if(zsmooth === 'fast') { xpx = xrev ? function(index) { return n - 1 - index; } : - _$lib_539.identity; + _$lib_601.identity; ypx = yrev ? function(index) { return m - 1 - index; } : - _$lib_539.identity; + _$lib_601.identity; } else { xpx = function(index) { - return _$lib_539.constrain(Math.round(xa.c2p(x[index]) - left), + return _$lib_601.constrain(Math.round(xa.c2p(x[index]) - left), 0, imageWidth); }; ypx = function(index) { - return _$lib_539.constrain(Math.round(ya.c2p(y[index]) - top), + return _$lib_601.constrain(Math.round(ya.c2p(y[index]) - top), 0, imageHeight); }; } @@ -59181,7 +61021,7 @@ function __plotOne_786(gd, plotinfo, cd) { rcount = Math.round(rcount / pixcount); gcount = Math.round(gcount / pixcount); bcount = Math.round(bcount / pixcount); - var avgColor = _$tinycolor_352('rgb(' + rcount + ',' + gcount + ',' + bcount + ')'); + var avgColor = _$tinycolor_414('rgb(' + rcount + ',' + gcount + ',' + bcount + ')'); gd._hmpixcount = (gd._hmpixcount||0) + pixcount; gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance(); @@ -59190,7 +61030,7 @@ function __plotOne_786(gd, plotinfo, cd) { .data(cd); image3.enter().append('svg:image').attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, preserveAspectRatio: 'none' }); @@ -59208,10 +61048,10 @@ function __plotOne_786(gd, plotinfo, cd) { // get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin} function findInterp(pixel, pixArray) { var maxBin = pixArray.length - 2; - var bin = _$lib_539.constrain(_$lib_539.findBin(pixel, pixArray), 0, maxBin); + var bin = _$lib_601.constrain(_$lib_601.findBin(pixel, pixArray), 0, maxBin); var pix0 = pixArray[bin]; var pix1 = pixArray[bin + 1]; - var interp = _$lib_539.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin); + var interp = _$lib_601.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin); var bin0 = Math.round(interp); var frac = Math.abs(interp - bin0); @@ -59231,7 +61071,7 @@ function findInterp(pixel, pixArray) { function findInterpFromCenters(pixel, centerPixArray) { var maxBin = centerPixArray.length - 1; - var bin = _$lib_539.constrain(_$lib_539.findBin(pixel, centerPixArray), 0, maxBin); + var bin = _$lib_601.constrain(_$lib_601.findBin(pixel, centerPixArray), 0, maxBin); var pix0 = centerPixArray[bin]; var pix1 = centerPixArray[bin + 1]; var frac = ((pixel - pix0) / (pix1 - pix0)) || 0; @@ -59263,7 +61103,7 @@ function putColor(pixels, pxIndex, c) { pixels[pxIndex + 3] = Math.round(c[3] * 255); } -var _$plot_762 = {}; +var _$plot_824 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -59275,31 +61115,31 @@ var _$plot_762 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$setConvert_603 = require('../../plots/cartesian/set_convert'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$setConvert_665 = require('../../plots/cartesian/set_convert'); */; -/* removed: var _$plot_786 = require('../heatmap/plot'); */; -/* removed: var _$makeCrossings_761 = require('./make_crossings'); */; -/* removed: var _$findAllPaths_756 = require('./find_all_paths'); */; -/* removed: var _$emptyPathinfo_754 = require('./empty_pathinfo'); */; -/* removed: var _$convert_to_constraints_752 = require('./convert_to_constraints'); */; -/* removed: var _$close_boundaries_746 = require('./close_boundaries'); */; -/* removed: var _$constants_748 = require('./constants'); */; -var costConstants = _$constants_748.LABELOPTIMIZER; +/* removed: var _$plot_848 = require('../heatmap/plot'); */; +/* removed: var _$makeCrossings_823 = require('./make_crossings'); */; +/* removed: var _$findAllPaths_818 = require('./find_all_paths'); */; +/* removed: var _$emptyPathinfo_816 = require('./empty_pathinfo'); */; +/* removed: var _$convert_to_constraints_814 = require('./convert_to_constraints'); */; +/* removed: var _$close_boundaries_808 = require('./close_boundaries'); */; +/* removed: var _$constants_810 = require('./constants'); */; +var costConstants = _$constants_810.LABELOPTIMIZER; -_$plot_762.plot = function plot(gd, plotinfo, cdcontours) { +_$plot_824.plot = function plot(gd, plotinfo, cdcontours) { for(var i = 0; i < cdcontours.length; i++) { - __plotOne_762(gd, plotinfo, cdcontours[i]); + __plotOne_824(gd, plotinfo, cdcontours[i]); } }; -function __plotOne_762(gd, plotinfo, cd) { +function __plotOne_824(gd, plotinfo, cd) { var trace = cd[0].trace, x = cd[0].x, y = cd[0].y, @@ -59309,7 +61149,7 @@ function __plotOne_762(gd, plotinfo, cd) { ya = plotinfo.yaxis, fullLayout = gd._fullLayout, id = 'contour' + uid, - pathinfo = _$emptyPathinfo_754(contours, plotinfo, cd[0]); + pathinfo = _$emptyPathinfo_816(contours, plotinfo, cd[0]); if(trace.visible !== true) { fullLayout._paper.selectAll('.' + id + ',.hm' + uid).remove(); @@ -59326,7 +61166,7 @@ function __plotOne_762(gd, plotinfo, cd) { trace.zmin + pathinfo.length * contours.size; } - _$plot_786(gd, plotinfo, [cd]); + _$plot_848(gd, plotinfo, [cd]); } // in case this used to be a heatmap (or have heatmap fill) else { @@ -59335,8 +61175,8 @@ function __plotOne_762(gd, plotinfo, cd) { .selectAll('.hm' + uid).remove(); } - _$makeCrossings_761(pathinfo); - _$findAllPaths_756(pathinfo); + _$makeCrossings_823(pathinfo); + _$findAllPaths_818(pathinfo); var leftedge = xa.c2p(x[0], true), rightedge = xa.c2p(x[x.length - 1], true), @@ -59351,19 +61191,19 @@ function __plotOne_762(gd, plotinfo, cd) { var fillPathinfo = pathinfo; if(contours.type === 'constraint') { - fillPathinfo = _$convert_to_constraints_752(pathinfo, contours._operation); - _$close_boundaries_746(fillPathinfo, contours._operation, perimeter, trace); + fillPathinfo = _$convert_to_constraints_814(pathinfo, contours._operation); + _$close_boundaries_808(fillPathinfo, contours._operation, perimeter, trace); } // draw everything - var plotGroup = _$plot_762.makeContourGroup(plotinfo, cd, id); + var plotGroup = _$plot_824.makeContourGroup(plotinfo, cd, id); makeBackground(plotGroup, perimeter, contours); makeFills(plotGroup, fillPathinfo, perimeter, contours); makeLinesAndLabels(plotGroup, pathinfo, gd, cd[0], contours, perimeter); clipGaps(plotGroup, plotinfo, fullLayout._clips, cd[0], perimeter); } -_$plot_762.makeContourGroup = function(plotinfo, cd, id) { +_$plot_824.makeContourGroup = function(plotinfo, cd, id) { var plotgroup = plotinfo.plot.select('.maplayer') .selectAll('g.contour.' + id) .data(cd); @@ -59378,8 +61218,7 @@ _$plot_762.makeContourGroup = function(plotinfo, cd, id) { }; function makeBackground(plotgroup, perimeter, contours) { - var bggroup = plotgroup.selectAll('g.contourbg').data([0]); - bggroup.enter().append('g').classed('contourbg', true); + var bggroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourbg'); var bgfill = bggroup.selectAll('path') .data(contours.coloring === 'fill' ? [0] : []); @@ -59391,10 +61230,7 @@ function makeBackground(plotgroup, perimeter, contours) { } function makeFills(plotgroup, pathinfo, perimeter, contours) { - var fillgroup = plotgroup.selectAll('g.contourfill') - .data([0]); - fillgroup.enter().append('g') - .classed('contourfill', true); + var fillgroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourfill'); var fillitems = fillgroup.selectAll('path') .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? pathinfo : []); @@ -59408,8 +61244,8 @@ function makeFills(plotgroup, pathinfo, perimeter, contours) { // that we always fill everything above the contour, nothing below var fullpath = joinAllPaths(pi, perimeter); - if(!fullpath) _$d3_127.select(this).remove(); - else _$d3_127.select(this).attr('d', fullpath).style('stroke', 'none'); + if(!fullpath) _$d3_130.select(this).remove(); + else _$d3_130.select(this).attr('d', fullpath).style('stroke', 'none'); }); } @@ -59446,7 +61282,7 @@ function joinAllPaths(pi, perimeter) { function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < 0.01; } while(startsleft.length) { - addpath = _$drawing_436.smoothopen(pi.edgepaths[i], pi.smoothing); + addpath = _$drawing_498.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]; @@ -59455,7 +61291,7 @@ function joinAllPaths(pi, perimeter) { // 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_539.log('Missing end?', i, pi); + _$lib_601.log('Missing end?', i, pi); break; } @@ -59482,7 +61318,7 @@ function joinAllPaths(pi, perimeter) { } } else { - _$lib_539.log('endpt to newendpt is not vert. or horz.', + _$lib_601.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); } } @@ -59494,7 +61330,7 @@ function joinAllPaths(pi, perimeter) { } if(nexti === pi.edgepaths.length) { - _$lib_539.log('unclosed perimeter path'); + _$lib_601.log('unclosed perimeter path'); break; } @@ -59511,18 +61347,14 @@ function joinAllPaths(pi, perimeter) { // finally add the interior paths for(i = 0; i < pi.paths.length; i++) { - fullpath += _$drawing_436.smoothclosed(pi.paths[i], pi.smoothing); + fullpath += _$drawing_498.smoothclosed(pi.paths[i], pi.smoothing); } return fullpath; } function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { - var lineContainer = plotgroup.selectAll('g.contourlines').data([0]); - - lineContainer.enter().append('g') - .classed('contourlines', true); - + var lineContainer = _$lib_601.ensureSingle(plotgroup, 'g', 'contourlines'); var showLines = contours.showlines !== false; var showLabels = contours.showlabels; var clipLinesForLabels = showLines && showLabels; @@ -59531,9 +61363,9 @@ function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { // 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 = _$plot_762.createLines(lineContainer, showLines || showLabels, pathinfo); + var linegroup = _$plot_824.createLines(lineContainer, showLines || showLabels, pathinfo); - var lineClip = _$plot_762.createLineClip(lineContainer, clipLinesForLabels, + var lineClip = _$plot_824.createLineClip(lineContainer, clipLinesForLabels, gd._fullLayout._clips, cd0.trace.uid); var labelGroup = plotgroup.selectAll('g.contourlabels') @@ -59550,13 +61382,13 @@ function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { var labelData = []; // invalidate the getTextLocation cache in case paths changed - _$lib_539.clearLocationCache(); + _$lib_601.clearLocationCache(); - var contourFormat = _$plot_762.labelFormatter(contours, cd0.t.cb, gd._fullLayout); + var contourFormat = _$plot_824.labelFormatter(contours, cd0.t.cb, gd._fullLayout); - var dummyText = _$drawing_436.tester.append('text') + var dummyText = _$drawing_498.tester.append('text') .attr('data-notex', 1) - .call(_$drawing_436.font, contours.labelfont); + .call(_$drawing_498.font, contours.labelfont); var xLen = pathinfo[0].xaxis._length; var yLen = pathinfo[0].yaxis._length; @@ -59575,43 +61407,43 @@ function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen); // the path length to use to scale the number of labels to draw: - var normLength = _$constants_748.LABELDISTANCE * plotDiagonal / - Math.max(1, pathinfo.length / _$constants_748.LABELINCREASE); + var normLength = _$constants_810.LABELDISTANCE * plotDiagonal / + Math.max(1, pathinfo.length / _$constants_810.LABELINCREASE); linegroup.each(function(d) { - var textOpts = _$plot_762.calcTextOpts(d.level, contourFormat, dummyText, gd); + var textOpts = _$plot_824.calcTextOpts(d.level, contourFormat, dummyText, gd); - _$d3_127.select(this).selectAll('path').each(function() { + _$d3_130.select(this).selectAll('path').each(function() { var path = this; - var pathBounds = _$lib_539.getVisibleSegment(path, bounds, textOpts.height / 2); + var pathBounds = _$lib_601.getVisibleSegment(path, bounds, textOpts.height / 2); if(!pathBounds) return; - if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_748.LABELMIN) return; + if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_810.LABELMIN) return; var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), - _$constants_748.LABELMAX); + _$constants_810.LABELMAX); for(var i = 0; i < maxLabels; i++) { - var loc = _$plot_762.findBestTextLocation(path, pathBounds, textOpts, + var loc = _$plot_824.findBestTextLocation(path, pathBounds, textOpts, labelData, bounds); if(!loc) break; - _$plot_762.addLabelData(loc, textOpts, labelData, labelClipPathData); + _$plot_824.addLabelData(loc, textOpts, labelData, labelClipPathData); } }); }); dummyText.remove(); - _$plot_762.drawLabels(labelGroup, labelData, gd, lineClip, + _$plot_824.drawLabels(labelGroup, labelData, gd, lineClip, clipLinesForLabels ? labelClipPathData : null); } if(showLabels && !showLines) linegroup.remove(); } -_$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { +_$plot_824.createLines = function(lineContainer, makeLines, pathinfo) { var smoothing = pathinfo[0].smoothing; var linegroup = lineContainer.selectAll('g.contourlevel') @@ -59633,7 +61465,7 @@ _$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { opencontourlines .attr('d', function(d) { - return _$drawing_436.smoothopen(d, smoothing); + return _$drawing_498.smoothopen(d, smoothing); }) .style('stroke-miterlimit', 1) .style('vector-effect', 'non-scaling-stroke'); @@ -59647,7 +61479,7 @@ _$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { closedcontourlines .attr('d', function(d) { - return _$drawing_436.smoothclosed(d, smoothing); + return _$drawing_498.smoothclosed(d, smoothing); }) .style('stroke-miterlimit', 1) .style('vector-effect', 'non-scaling-stroke'); @@ -59656,7 +61488,7 @@ _$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { return linegroup; }; -_$plot_762.createLineClip = function(lineContainer, clipLinesForLabels, clips, uid) { +_$plot_824.createLineClip = function(lineContainer, clipLinesForLabels, clips, uid) { var clipId = clipLinesForLabels ? ('clipline' + uid) : null; var lineClip = clips.selectAll('#' + clipId) @@ -59667,12 +61499,12 @@ _$plot_762.createLineClip = function(lineContainer, clipLinesForLabels, clips, u .classed('contourlineclip', true) .attr('id', clipId); - _$drawing_436.setClipUrl(lineContainer, clipId); + _$drawing_498.setClipUrl(lineContainer, clipId); return lineClip; }; -_$plot_762.labelFormatter = function(contours, colorbar, fullLayout) { +_$plot_824.labelFormatter = function(contours, colorbar, fullLayout) { if(contours.labelformat) { return fullLayout._d3locale.numberFormat(contours.labelformat); } @@ -59705,22 +61537,22 @@ _$plot_762.labelFormatter = function(contours, colorbar, fullLayout) { } if(!formatAxis.nticks) formatAxis.nticks = 1000; - _$setConvert_603(formatAxis, fullLayout); - _$axes_584.prepTicks(formatAxis); + _$setConvert_665(formatAxis, fullLayout); + _$axes_647.prepTicks(formatAxis); formatAxis._tmin = null; formatAxis._tmax = null; } return function(v) { - return _$axes_584.tickText(formatAxis, v).text; + return _$axes_647.tickText(formatAxis, v).text; }; } }; -_$plot_762.calcTextOpts = function(level, contourFormat, dummyText, gd) { +_$plot_824.calcTextOpts = function(level, contourFormat, dummyText, gd) { var text = contourFormat(level); dummyText.text(text) - .call(_$svg_text_utils_562.convertToTspans, gd); - var bBox = _$drawing_436.bBox(dummyText.node(), true); + .call(_$svg_text_utils_625.convertToTspans, gd); + var bBox = _$drawing_498.bBox(dummyText.node(), true); return { text: text, @@ -59731,7 +61563,7 @@ _$plot_762.calcTextOpts = function(level, contourFormat, dummyText, gd) { }; }; -_$plot_762.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) { +_$plot_824.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) { var textWidth = textOpts.width; var p0, dp, pMax, pMin, loc; @@ -59749,7 +61581,7 @@ _$plot_762.findBestTextLocation = function(path, pathBounds, textOpts, labelData var cost = Infinity; for(var j = 0; j < costConstants.ITERATIONS; j++) { for(var p = p0; p < pMax; p += dp) { - var newLocation = _$lib_539.getTextLocation(path, pathBounds.total, p, textWidth); + var newLocation = _$lib_601.getTextLocation(path, pathBounds.total, p, textWidth); var newCost = locationCost(newLocation, textOpts, labelData, plotBounds); if(newCost < cost) { cost = newCost; @@ -59804,7 +61636,7 @@ function locationCost(loc, textOpts, labelData, bounds) { 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_539.segmentDistance( + var dist = _$lib_601.segmentDistance( x1, y1, x2, y2, labeli.x - dxd, labeli.y - dyd, @@ -59825,7 +61657,7 @@ function locationCost(loc, textOpts, labelData, bounds) { return cost; } -_$plot_762.addLabelData = function(loc, textOpts, labelData, labelClipPathData) { +_$plot_824.addLabelData = function(loc, textOpts, labelData, labelClipPathData) { var halfWidth = textOpts.width / 2; var halfHeight = textOpts.height / 2; @@ -59860,7 +61692,7 @@ _$plot_762.addLabelData = function(loc, textOpts, labelData, labelClipPathData) labelClipPathData.push(bBoxPts); }; -_$plot_762.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipPathData) { +_$plot_824.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; @@ -59876,14 +61708,14 @@ _$plot_762.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipP .each(function(d) { var x = d.x + Math.sin(d.theta) * d.dy; var y = d.y - Math.cos(d.theta) * d.dy; - _$d3_127.select(this) + _$d3_130.select(this) .text(d.text) .attr({ x: x, y: y, transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')' }) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); }); if(labelClipPathData) { @@ -59892,8 +61724,7 @@ _$plot_762.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipP clipPath += 'M' + labelClipPathData[i].join('L') + 'Z'; } - var lineClipPath = lineClip.selectAll('path').data([0]); - lineClipPath.enter().append('path'); + var lineClipPath = _$lib_601.ensureSingle(lineClip, 'path', ''); lineClipPath.attr('d', clipPath); } }; @@ -59928,20 +61759,18 @@ function clipGaps(plotGroup, plotinfo, clips, cd0, perimeter) { smoothing: 0 }; - _$makeCrossings_761([clipPathInfo]); - _$findAllPaths_756([clipPathInfo]); + _$makeCrossings_823([clipPathInfo]); + _$findAllPaths_818([clipPathInfo]); var fullpath = joinAllPaths(clipPathInfo, perimeter); - var path = clipPath.selectAll('path') - .data([0]); - path.enter().append('path'); + var path = _$lib_601.ensureSingle(clipPath, 'path', ''); path.attr('d', fullpath); } else clipId = null; - plotGroup.call(_$drawing_436.setClipUrl, clipId); + plotGroup.call(_$drawing_498.setClipUrl, clipId); plotinfo.plot.selectAll('.hm' + cd0.trace.uid) - .call(_$drawing_436.setClipUrl, clipId); + .call(_$drawing_498.setClipUrl, clipId); } function makeClipMask(cd0) { @@ -59975,10 +61804,10 @@ function makeClipMask(cd0) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -var _$style_787 = function style(gd) { - _$d3_127.select(gd).selectAll('.hm image') +var _$style_849 = function style(gd) { + _$d3_130.select(gd).selectAll('.hm image') .style('opacity', function(d) { return d.trace.opacity; }); @@ -59995,23 +61824,23 @@ var _$style_787 = function style(gd) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$style_787 = require('../heatmap/style'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$style_849 = require('../heatmap/style'); */; -/* removed: var _$makeColorMap_760 = require('./make_color_map'); */; +/* removed: var _$makeColorMap_822 = require('./make_color_map'); */; -var _$style_764 = function style(gd) { - var contours = _$d3_127.select(gd).selectAll('g.contour'); +var _$style_826 = function style(gd) { + var contours = _$d3_130.select(gd).selectAll('g.contour'); contours.style('opacity', function(d) { return d.trace.opacity; }); contours.each(function(d) { - var c = _$d3_127.select(this); + var c = _$d3_130.select(this); var trace = d.trace; var contours = trace.contours; var line = trace.line; @@ -60023,11 +61852,11 @@ var _$style_764 = function style(gd) { var colorLines = !isConstraintType && contours.coloring === 'lines'; var colorFills = !isConstraintType && contours.coloring === 'fill'; - var colorMap = (colorLines || colorFills) ? _$makeColorMap_760(trace) : null; + var colorMap = (colorLines || colorFills) ? _$makeColorMap_822(trace) : null; c.selectAll('g.contourlevel').each(function(d) { - _$d3_127.select(this).selectAll('path') - .call(_$drawing_436.lineGroupStyle, + _$d3_130.select(this).selectAll('path') + .call(_$drawing_498.lineGroupStyle, line.width, colorLines ? colorMap(d.level) : line.color, line.dash); @@ -60035,7 +61864,7 @@ var _$style_764 = function style(gd) { var labelFont = contours.labelfont; c.selectAll('g.contourlabels text').each(function(d) { - _$drawing_436.font(_$d3_127.select(this), { + _$drawing_498.font(_$d3_130.select(this), { family: labelFont.family, size: labelFont.size, color: labelFont.color || (colorLines ? colorMap(d.level) : line.color) @@ -60062,7 +61891,7 @@ var _$style_764 = function style(gd) { } }); - _$style_787(gd); + _$style_849(gd); }; /** @@ -60078,18 +61907,18 @@ var _$style_764 = function style(gd) { var Contour = {}; -Contour.attributes = _$attributes_744; -Contour.supplyDefaults = _$supplyDefaults_753; -Contour.calc = _$calc_745; -Contour.plot = _$plot_762.plot; -Contour.style = _$style_764; -Contour.colorbar = _$colorbar_747; -Contour.hoverPoints = _$hoverPoints_757; +Contour.attributes = _$attributes_806; +Contour.supplyDefaults = _$supplyDefaults_815; +Contour.calc = _$calc_807; +Contour.plot = _$plot_824.plot; +Contour.style = _$style_826; +Contour.colorbar = _$colorbar_809; +Contour.hoverPoints = _$hoverPoints_819; Contour.moduleType = 'trace'; Contour.name = 'contour'; -Contour.basePlotModule = _$cartesian_595; -Contour.categories = ['cartesian', '2dMap', 'contour', 'showLegend']; +Contour.basePlotModule = _$cartesian_658; +Contour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'showLegend']; Contour.meta = { description: [ 'The data from which contour lines are computed is set in `z`.', @@ -60103,7 +61932,7 @@ Contour.meta = { ].join(' ') }; -var _$Contour_758 = Contour; +var _$Contour_820 = Contour; /** * Copyright 2012-2018, Plotly, Inc. @@ -60115,7 +61944,7 @@ var _$Contour_758 = Contour; 'use strict'; -var _$contour_10 = _$Contour_758; +var _$contour_10 = _$Contour_820; /** * Copyright 2012-2018, Plotly, Inc. @@ -60127,18 +61956,18 @@ var _$contour_10 = _$Contour_758; 'use strict'; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_744 = require('../contour/attributes'); */; -var contourContourAttrs = _$attributes_744.contours; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_806 = require('../contour/attributes'); */; +var contourContourAttrs = _$attributes_806.contours; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_766 = _$extend_528.extendFlat; +var __extendFlat_828 = _$extend_590.extendFlat; -var __scatterLineAttrs_766 = _$attributes_862.line; +var __scatterLineAttrs_828 = _$attributes_927.line; -var _$attributes_766 = __extendFlat_766({}, { +var _$attributes_828 = __extendFlat_828({}, { carpet: { valType: 'string', role: 'info', @@ -60147,25 +61976,25 @@ var _$attributes_766 = __extendFlat_766({}, { 'The `carpet` of the carpet axes on which this contour trace lies' ].join(' ') }, - z: _$attributes_773.z, - a: _$attributes_773.x, - a0: _$attributes_773.x0, - da: _$attributes_773.dx, - b: _$attributes_773.y, - b0: _$attributes_773.y0, - db: _$attributes_773.dy, - text: _$attributes_773.text, - transpose: _$attributes_773.transpose, - atype: _$attributes_773.xtype, - btype: _$attributes_773.ytype, + z: _$attributes_835.z, + a: _$attributes_835.x, + a0: _$attributes_835.x0, + da: _$attributes_835.dx, + b: _$attributes_835.y, + b0: _$attributes_835.y0, + db: _$attributes_835.dy, + text: _$attributes_835.text, + transpose: _$attributes_835.transpose, + atype: _$attributes_835.xtype, + btype: _$attributes_835.ytype, // unimplemented - looks like connectgaps is implied true // connectgaps: heatmapAttrs.connectgaps, - fillcolor: _$attributes_744.fillcolor, + fillcolor: _$attributes_806.fillcolor, - autocontour: _$attributes_744.autocontour, - ncontours: _$attributes_744.ncontours, + autocontour: _$attributes_806.autocontour, + ncontours: _$attributes_806.ncontours, contours: { type: contourContourAttrs.type, @@ -60197,15 +62026,15 @@ var _$attributes_766 = __extendFlat_766({}, { }, line: { - color: __extendFlat_766({}, __scatterLineAttrs_766.color, { + color: __extendFlat_828({}, __scatterLineAttrs_828.color, { description: [ 'Sets the color of the contour level.', 'Has no if `contours.coloring` is set to *lines*.' ].join(' ') }), - width: __scatterLineAttrs_766.width, - dash: __scatterLineAttrs_766.dash, - smoothing: __extendFlat_766({}, __scatterLineAttrs_766.smoothing, { + width: __scatterLineAttrs_828.width, + dash: __scatterLineAttrs_828.dash, + smoothing: __extendFlat_828({}, __scatterLineAttrs_828.smoothing, { description: [ 'Sets the amount of smoothing for the contour lines,', 'where *0* corresponds to no smoothing.' @@ -60214,9 +62043,9 @@ var _$attributes_766 = __extendFlat_766({}, { editType: 'plot' } }, - _$attributes_417, - { autocolorscale: __extendFlat_766({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } + _$attributes_479, + { autocolorscale: __extendFlat_828({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); /** @@ -60232,7 +62061,7 @@ var _$attributes_766 = __extendFlat_766({}, { /* * Given a trace, look up the carpet axis by carpet. */ -var _$lookup_carpetid_726 = function(gd, trace) { +var _$lookup_carpetid_789 = function(gd, trace) { var n = gd._fullData.length; var firstAxis; for(var i = 0; i < n; i++) { @@ -60265,21 +62094,21 @@ var _$lookup_carpetid_726 = function(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleXYZDefaults_789 = require('../heatmap/xyz_defaults'); */; -/* removed: var _$attributes_766 = require('./attributes'); */; -/* removed: var _$handleConstraintDefaults_749 = require('../contour/constraint_defaults'); */; -/* removed: var _$handleContourDefaults_751 = require('../contour/contours_defaults'); */; -/* removed: var _$handleStyleDefaults_765 = require('../contour/style_defaults'); */; +/* removed: var _$handleXYZDefaults_851 = require('../heatmap/xyz_defaults'); */; +/* removed: var _$attributes_828 = require('./attributes'); */; +/* removed: var _$handleConstraintDefaults_811 = require('../contour/constraint_defaults'); */; +/* removed: var _$handleContourDefaults_813 = require('../contour/contours_defaults'); */; +/* removed: var _$handleStyleDefaults_827 = require('../contour/style_defaults'); */; -var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_830 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_766, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_828, attr, dflt); } function coerce2(attr) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_766, attr); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_828, attr); } coerce('carpet'); @@ -60301,7 +62130,7 @@ var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultCol // straightforward. if(traceIn.a && traceIn.b) { - var len = _$handleXYZDefaults_789(traceIn, traceOut, coerce, layout, 'a', 'b'); + var len = _$handleXYZDefaults_851(traceIn, traceOut, coerce, layout, 'a', 'b'); if(!len) { traceOut.visible = false; @@ -60318,10 +62147,10 @@ var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultCol if(!isConstraint) delete traceOut.showlegend; if(isConstraint) { - _$handleConstraintDefaults_749(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false}); + _$handleConstraintDefaults_811(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false}); } else { - _$handleContourDefaults_751(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_765(traceIn, traceOut, coerce, layout, {hasHover: false}); + _$handleContourDefaults_813(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_827(traceIn, traceOut, coerce, layout, {hasHover: false}); } } else { traceOut._defaultColor = defaultColor; @@ -60338,23 +62167,23 @@ var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$has_columns_780 = require('../heatmap/has_columns'); */; -/* removed: var _$convertColumnData_777 = require('../heatmap/convert_column_xyz'); */; -/* removed: var _$clean2dArray_775 = require('../heatmap/clean_2d_array'); */; -/* removed: var _$maxRowLength_785 = require('../heatmap/max_row_length'); */; -/* removed: var _$interp2d_783 = require('../heatmap/interp2d'); */; -/* removed: var _$findEmpties_779 = require('../heatmap/find_empties'); */; -/* removed: var _$makeBoundArray_784 = require('../heatmap/make_bound_array'); */; -/* removed: var _$supplyDefaults_768 = require('./defaults'); */; -/* removed: var _$lookup_carpetid_726 = require('../carpet/lookup_carpetid'); */; -/* removed: var _$setContours_763 = require('../contour/set_contours'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$has_columns_842 = require('../heatmap/has_columns'); */; +/* removed: var _$convertColumnData_839 = require('../heatmap/convert_column_xyz'); */; +/* removed: var _$clean2dArray_837 = require('../heatmap/clean_2d_array'); */; +/* removed: var _$maxRowLength_847 = require('../heatmap/max_row_length'); */; +/* removed: var _$interp2d_845 = require('../heatmap/interp2d'); */; +/* removed: var _$findEmpties_841 = require('../heatmap/find_empties'); */; +/* removed: var _$makeBoundArray_846 = require('../heatmap/make_bound_array'); */; +/* removed: var _$supplyDefaults_830 = require('./defaults'); */; +/* removed: var _$lookup_carpetid_789 = require('../carpet/lookup_carpetid'); */; +/* removed: var _$setContours_825 = require('../contour/set_contours'); */; // 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 -var _$calc_767 = function calc(gd, trace) { - var carpet = trace.carpetTrace = _$lookup_carpetid_726(gd, trace); +var _$calc_829 = function calc(gd, trace) { + var carpet = trace._carpetTrace = _$lookup_carpetid_789(gd, trace); if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return; if(!trace.a || !trace.b) { @@ -60371,12 +62200,12 @@ var _$calc_767 = function calc(gd, trace) { if(!tracedata.a) tracedata.a = carpetdata.a; if(!tracedata.b) tracedata.b = carpetdata.b; - _$supplyDefaults_768(tracedata, trace, trace._defaultColor, gd._fullLayout); + _$supplyDefaults_830(tracedata, trace, trace._defaultColor, gd._fullLayout); } var cd = heatmappishCalc(gd, trace); - _$setContours_763(trace); + _$setContours_825(trace); return cd; }; @@ -60384,7 +62213,7 @@ var _$calc_767 = function calc(gd, trace) { 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 carpet = trace._carpetTrace; var aax = carpet.aaxis; var bax = carpet.baxis; var a, @@ -60399,26 +62228,28 @@ function heatmappishCalc(gd, trace) { aax._minDtick = 0; bax._minDtick = 0; - if(_$has_columns_780(trace)) _$convertColumnData_777(trace, aax, bax, 'a', 'b', ['z']); + if(_$has_columns_842(trace)) _$convertColumnData_839(trace, aax, bax, 'a', 'b', ['z']); + a = trace._a = trace._a || trace.a; + b = trace._b = trace._b || trace.b; - a = trace.a ? aax.makeCalcdata(trace, 'a') : []; - b = trace.b ? bax.makeCalcdata(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 = _$clean2dArray_775(trace.z, trace.transpose); + z = trace._z = _$clean2dArray_837(trace._z || trace.z, trace.transpose); - trace._emptypoints = _$findEmpties_779(z); - trace._interpz = _$interp2d_783(z, trace._emptypoints, trace._interpz); + trace._emptypoints = _$findEmpties_841(z); + trace._interpz = _$interp2d_845(z, trace._emptypoints, trace._interpz); // create arrays of brick boundaries, to be used by autorange and heatmap.plot - var xlen = _$maxRowLength_785(z), + var xlen = _$maxRowLength_847(z), xIn = trace.xtype === 'scaled' ? '' : a, - xArray = _$makeBoundArray_784(trace, xIn, a0, da, xlen, aax), + xArray = _$makeBoundArray_846(trace, xIn, a0, da, xlen, aax), yIn = trace.ytype === 'scaled' ? '' : b, - yArray = _$makeBoundArray_784(trace, yIn, b0, db, z.length, bax); + yArray = _$makeBoundArray_846(trace, yIn, b0, db, z.length, bax); var cd0 = { a: xArray, @@ -60428,7 +62259,7 @@ function heatmappishCalc(gd, trace) { if(trace.contours.type === 'levels') { // auto-z and autocolorscale if applicable - _$calc_418(trace, z, '', 'z'); + _$calc_480(trace, z, '', 'z'); } return [cd0]; @@ -60444,7 +62275,7 @@ function heatmappishCalc(gd, trace) { 'use strict'; -var __isArrayOrTypedArray_709 = _$lib_539.isArrayOrTypedArray; +var __isArrayOrTypedArray_772 = _$lib_601.isArrayOrTypedArray; /* This function retrns a set of control points that define a curve aligned along * either the a or b axis. Exactly one of a or b must be an array defining the range @@ -60453,11 +62284,11 @@ var __isArrayOrTypedArray_709 = _$lib_539.isArrayOrTypedArray; * Honestly this is the most complicated function I've implemente here so far because * of the way it handles knot insertion and direction/axis-agnostic slices. */ -var _$axis_aligned_line_709 = function(carpet, carpetcd, a, b) { +var _$axis_aligned_line_772 = function(carpet, carpetcd, a, b) { var idx, tangent, tanIsoIdx, tanIsoPar, segment, refidx; var p0, p1, v0, v1, start, end, range; - var axis = __isArrayOrTypedArray_709(a) ? 'a' : 'b'; + var axis = __isArrayOrTypedArray_772(a) ? 'a' : 'b'; var ax = axis === 'a' ? carpet.aaxis : carpet.baxis; var smoothing = ax.smoothing; var toIdx = axis === 'a' ? carpet.a2i : carpet.b2j; @@ -60550,11 +62381,11 @@ var _$axis_aligned_line_709 = function(carpet, carpetcd, a, b) { 'use strict'; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$axis_aligned_line_709 = require('../carpet/axis_aligned_line'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$axis_aligned_line_772 = require('../carpet/axis_aligned_line'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) { +var _$joinAllPaths_832 = function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) { var i; var fullpath = ''; @@ -60576,10 +62407,10 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe if((istop(pt0) && !isright(pt0)) || (isbottom(pt0) && !isleft(pt0))) { axis = carpet.aaxis; - segments = _$axis_aligned_line_709(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1])); + segments = _$axis_aligned_line_772(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1])); } else { axis = carpet.baxis; - segments = _$axis_aligned_line_709(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]); + segments = _$axis_aligned_line_772(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]); } for(i = 1; i < segments.length; i++) { @@ -60602,7 +62433,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe fullpath += pathto(endpt, startpt); } - addpath = _$drawing_436.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing); + addpath = _$drawing_498.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing); fullpath += newloop ? addpath : addpath.replace(/^M/, 'L'); startsleft.splice(startsleft.indexOf(i), 1); endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1]; @@ -60611,7 +62442,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe // 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_539.log('Missing end?', i, pi); + _$lib_601.log('Missing end?', i, pi); break; } @@ -60639,7 +62470,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe nexti = possiblei; } } else { - _$lib_539.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); + _$lib_601.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); } } @@ -60649,7 +62480,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe } if(nexti === pi.edgepaths.length) { - _$lib_539.log('unclosed perimeter path'); + _$lib_601.log('unclosed perimeter path'); break; } @@ -60667,7 +62498,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe // finally add the interior paths for(i = 0; i < pi.paths.length; i++) { - fullpath += _$drawing_436.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing); + fullpath += _$drawing_498.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing); } return fullpath; @@ -60683,7 +62514,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe 'use strict'; -var _$mapPathinfo_771 = function mapPathinfo(pathinfo, map) { +var _$mapPathinfo_833 = function mapPathinfo(pathinfo, map) { var i, j, k, pi, pedgepaths, ppaths, pedgepath, ppath, path; for(i = 0; i < pathinfo.length; i++) { @@ -60719,34 +62550,34 @@ var _$mapPathinfo_771 = function mapPathinfo(pathinfo, map) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$mapArray_728 = require('../carpet/map_1d_array'); */; -/* removed: var _$makePath_727 = require('../carpet/makepath'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$mapArray_791 = require('../carpet/map_1d_array'); */; +/* removed: var _$makePath_790 = require('../carpet/makepath'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$makeCrossings_761 = require('../contour/make_crossings'); */; -/* removed: var _$findAllPaths_756 = require('../contour/find_all_paths'); */; -/* removed: var _$plot_762 = require('../contour/plot'); */; -/* removed: var _$constants_748 = require('../contour/constants'); */; -/* removed: var _$convert_to_constraints_752 = require('../contour/convert_to_constraints'); */; -/* removed: var _$joinAllPaths_770 = require('./join_all_paths'); */; -/* removed: var _$emptyPathinfo_754 = require('../contour/empty_pathinfo'); */; -/* removed: var _$mapPathinfo_771 = require('./map_pathinfo'); */; -/* removed: var _$lookup_carpetid_726 = require('../carpet/lookup_carpetid'); */; -/* removed: var _$close_boundaries_746 = require('../contour/close_boundaries'); */; +/* removed: var _$makeCrossings_823 = require('../contour/make_crossings'); */; +/* removed: var _$findAllPaths_818 = require('../contour/find_all_paths'); */; +/* removed: var _$plot_824 = require('../contour/plot'); */; +/* removed: var _$constants_810 = require('../contour/constants'); */; +/* removed: var _$convert_to_constraints_814 = require('../contour/convert_to_constraints'); */; +/* removed: var _$joinAllPaths_832 = require('./join_all_paths'); */; +/* removed: var _$emptyPathinfo_816 = require('../contour/empty_pathinfo'); */; +/* removed: var _$mapPathinfo_833 = require('./map_pathinfo'); */; +/* removed: var _$lookup_carpetid_789 = require('../carpet/lookup_carpetid'); */; +/* removed: var _$close_boundaries_808 = require('../contour/close_boundaries'); */; -var _$plot_772 = function plot(gd, plotinfo, cdcontours) { +var _$plot_834 = function plot(gd, plotinfo, cdcontours) { for(var i = 0; i < cdcontours.length; i++) { - __plotOne_772(gd, plotinfo, cdcontours[i]); + __plotOne_834(gd, plotinfo, cdcontours[i]); } }; -function __plotOne_772(gd, plotinfo, cd) { +function __plotOne_834(gd, plotinfo, cd) { var trace = cd[0].trace; - var carpet = trace.carpetTrace = _$lookup_carpetid_726(gd, trace); + var carpet = trace._carpetTrace = _$lookup_carpetid_789(gd, trace); var carpetcd = gd.calcdata[carpet.index][0]; if(!carpet.visible || carpet.visible === 'legendonly') return; @@ -60759,7 +62590,7 @@ function __plotOne_772(gd, plotinfo, cd) { var ya = plotinfo.yaxis; var fullLayout = gd._fullLayout; var id = 'contour' + uid; - var pathinfo = _$emptyPathinfo_754(contours, plotinfo, cd[0]); + var pathinfo = _$emptyPathinfo_816(contours, plotinfo, cd[0]); var isConstraint = contours.type === 'constraint'; var operation = contours._operation; var coloring = isConstraint ? (operation === '=' ? 'lines' : 'fill') : contours.coloring; @@ -60784,10 +62615,10 @@ function __plotOne_772(gd, plotinfo, cd) { ]; // Extract the contour levels: - _$makeCrossings_761(pathinfo); + _$makeCrossings_823(pathinfo); var atol = (a[a.length - 1] - a[0]) * 1e-8; var btol = (b[b.length - 1] - b[0]) * 1e-8; - _$findAllPaths_756(pathinfo, atol, btol); + _$findAllPaths_818(pathinfo, atol, btol); // Constraints might need to be draw inverted, which is not something contours // handle by default since they're assumed fully opaque so that they can be @@ -60799,52 +62630,48 @@ function __plotOne_772(gd, plotinfo, cd) { // See: https://github.com/plotly/plotly.js/issues/1356 var fillPathinfo = pathinfo; if(contours.type === 'constraint') { - fillPathinfo = _$convert_to_constraints_752(pathinfo, operation); - _$close_boundaries_746(fillPathinfo, operation, perimeter, trace); + fillPathinfo = _$convert_to_constraints_814(pathinfo, operation); + _$close_boundaries_808(fillPathinfo, operation, perimeter, trace); } // Map the paths in a/b coordinates to pixel coordinates: - _$mapPathinfo_771(pathinfo, ab2p); + _$mapPathinfo_833(pathinfo, ab2p); // draw everything - var plotGroup = _$plot_762.makeContourGroup(plotinfo, cd, id); + var plotGroup = _$plot_824.makeContourGroup(plotinfo, cd, id); // Compute the boundary path var seg, xp, yp, i; var segs = []; for(i = carpetcd.clipsegments.length - 1; i >= 0; i--) { seg = carpetcd.clipsegments[i]; - xp = _$mapArray_728([], seg.x, xa.c2p); - yp = _$mapArray_728([], seg.y, ya.c2p); + xp = _$mapArray_791([], seg.x, xa.c2p); + yp = _$mapArray_791([], seg.y, ya.c2p); xp.reverse(); yp.reverse(); - segs.push(_$makePath_727(xp, yp, seg.bicubic)); + segs.push(_$makePath_790(xp, yp, seg.bicubic)); } var boundaryPath = 'M' + segs.join('L') + 'Z'; // Draw the baseline background fill that fills in the space behind any other // contour levels: - __makeBackground_772(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring); + __makeBackground_834(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring); // Draw the specific contour fills. As a simplification, they're assumed to be // fully opaque so that it's easy to draw them simply overlapping. The alternative // would be to flip adjacent paths and draw closed paths for each level instead. - __makeFills_772(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath); + __makeFills_834(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath); // Draw contour lines: - __makeLinesAndLabels_772(plotGroup, pathinfo, gd, cd[0], contours, plotinfo, carpet); + __makeLinesAndLabels_834(plotGroup, pathinfo, gd, cd[0], contours, plotinfo, carpet); // Clip the boundary of the plot - _$drawing_436.setClipUrl(plotGroup, carpet._clipPathId); + _$drawing_498.setClipUrl(plotGroup, carpet._clipPathId); } -function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) { - var lineContainer = plotgroup.selectAll('g.contourlines').data([0]); - - lineContainer.enter().append('g') - .classed('contourlines', true); - +function __makeLinesAndLabels_834(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) { + var lineContainer = _$lib_601.ensureSingle(plotgroup, 'g', 'contourlines'); var showLines = contours.showlines !== false; var showLabels = contours.showlabels; var clipLinesForLabels = showLines && showLabels; @@ -60853,9 +62680,9 @@ function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotin // 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 = _$plot_762.createLines(lineContainer, showLines || showLabels, pathinfo); + var linegroup = _$plot_824.createLines(lineContainer, showLines || showLabels, pathinfo); - var lineClip = _$plot_762.createLineClip(lineContainer, clipLinesForLabels, + var lineClip = _$plot_824.createLineClip(lineContainer, clipLinesForLabels, gd._fullLayout._defs, cd0.trace.uid); var labelGroup = plotgroup.selectAll('g.contourlabels') @@ -60883,13 +62710,13 @@ function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotin var labelData = []; // invalidate the getTextLocation cache in case paths changed - _$lib_539.clearLocationCache(); + _$lib_601.clearLocationCache(); - var contourFormat = _$plot_762.labelFormatter(contours, cd0.t.cb, gd._fullLayout); + var contourFormat = _$plot_824.labelFormatter(contours, cd0.t.cb, gd._fullLayout); - var dummyText = _$drawing_436.tester.append('text') + var dummyText = _$drawing_498.tester.append('text') .attr('data-notex', 1) - .call(_$drawing_436.font, contours.labelfont); + .call(_$drawing_498.font, contours.labelfont); // use `bounds` only to keep labels away from the x/y boundaries // `constrainToCarpet` below ensures labels don't go off the @@ -60906,38 +62733,38 @@ function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotin var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen); // the path length to use to scale the number of labels to draw: - var normLength = _$constants_748.LABELDISTANCE * plotDiagonal / - Math.max(1, pathinfo.length / _$constants_748.LABELINCREASE); + var normLength = _$constants_810.LABELDISTANCE * plotDiagonal / + Math.max(1, pathinfo.length / _$constants_810.LABELINCREASE); linegroup.each(function(d) { - var textOpts = _$plot_762.calcTextOpts(d.level, contourFormat, dummyText, gd); + var textOpts = _$plot_824.calcTextOpts(d.level, contourFormat, dummyText, gd); - _$d3_127.select(this).selectAll('path').each(function(pathData) { + _$d3_130.select(this).selectAll('path').each(function(pathData) { var path = this; - var pathBounds = _$lib_539.getVisibleSegment(path, bounds, textOpts.height / 2); + var pathBounds = _$lib_601.getVisibleSegment(path, bounds, textOpts.height / 2); if(!pathBounds) return; constrainToCarpet(path, pathData, d, pathBounds, carpet, textOpts.height); - if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_748.LABELMIN) return; + if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_810.LABELMIN) return; var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), - _$constants_748.LABELMAX); + _$constants_810.LABELMAX); for(var i = 0; i < maxLabels; i++) { - var loc = _$plot_762.findBestTextLocation(path, pathBounds, textOpts, + var loc = _$plot_824.findBestTextLocation(path, pathBounds, textOpts, labelData, bounds); if(!loc) break; - _$plot_762.addLabelData(loc, textOpts, labelData, labelClipPathData); + _$plot_824.addLabelData(loc, textOpts, labelData, labelClipPathData); } }); }); dummyText.remove(); - _$plot_762.drawLabels(labelGroup, labelData, gd, lineClip, + _$plot_824.drawLabels(labelGroup, labelData, gd, lineClip, clipLinesForLabels ? labelClipPathData : null); } @@ -61007,10 +62834,9 @@ function vectorTan(v0, v1) { return sin / cos; } -function __makeBackground_772(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) { +function __makeBackground_834(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) { var seg, xp, yp, i; - var bggroup = plotgroup.selectAll('g.contourbg').data([0]); - bggroup.enter().append('g').classed('contourbg', true); + var bggroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourbg'); var bgfill = bggroup.selectAll('path') .data((coloring === 'fill' && !isConstraint) ? [0] : []); @@ -61020,9 +62846,9 @@ function __makeBackground_772(plotgroup, clipsegments, xaxis, yaxis, isConstrain var segs = []; for(i = 0; i < clipsegments.length; i++) { seg = clipsegments[i]; - xp = _$mapArray_728([], seg.x, xaxis.c2p); - yp = _$mapArray_728([], seg.y, yaxis.c2p); - segs.push(_$makePath_727(xp, yp, seg.bicubic)); + xp = _$mapArray_791([], seg.x, xaxis.c2p); + yp = _$mapArray_791([], seg.y, yaxis.c2p); + segs.push(_$makePath_790(xp, yp, seg.bicubic)); } bgfill @@ -61030,11 +62856,8 @@ function __makeBackground_772(plotgroup, clipsegments, xaxis, yaxis, isConstrain .style('stroke', 'none'); } -function __makeFills_772(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) { - var fillgroup = plotgroup.selectAll('g.contourfill') - .data([0]); - fillgroup.enter().append('g') - .classed('contourfill', true); +function __makeFills_834(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) { + var fillgroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourfill'); var fillitems = fillgroup.selectAll('path') .data(coloring === 'fill' ? pathinfo : []); @@ -61046,16 +62869,16 @@ function __makeFills_772(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, ca // 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 = _$joinAllPaths_770(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya); + var fullpath = _$joinAllPaths_832(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya); if(pi.prefixBoundary) { fullpath = boundaryPath + fullpath; } if(!fullpath) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); } else { - _$d3_127.select(this) + _$d3_130.select(this) .attr('d', fullpath) .style('stroke', 'none'); } @@ -61074,17 +62897,17 @@ function __makeFills_772(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, ca var ContourCarpet = {}; -ContourCarpet.attributes = _$attributes_766; -ContourCarpet.supplyDefaults = _$supplyDefaults_768; -ContourCarpet.colorbar = _$colorbar_747; -ContourCarpet.calc = _$calc_767; -ContourCarpet.plot = _$plot_772; -ContourCarpet.style = _$style_764; +ContourCarpet.attributes = _$attributes_828; +ContourCarpet.supplyDefaults = _$supplyDefaults_830; +ContourCarpet.colorbar = _$colorbar_809; +ContourCarpet.calc = _$calc_829; +ContourCarpet.plot = _$plot_834; +ContourCarpet.style = _$style_826; ContourCarpet.moduleType = 'trace'; ContourCarpet.name = 'contourcarpet'; -ContourCarpet.basePlotModule = _$cartesian_595; -ContourCarpet.categories = ['cartesian', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent']; +ContourCarpet.basePlotModule = _$cartesian_658; +ContourCarpet.categories = ['cartesian', 'svg', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent']; ContourCarpet.meta = { hrName: 'contour_carpet', description: [ @@ -61095,7 +62918,7 @@ ContourCarpet.meta = { ].join(' ') }; -var _$ContourCarpet_769 = ContourCarpet; +var _$ContourCarpet_831 = ContourCarpet; /** * Copyright 2012-2018, Plotly, Inc. @@ -61107,12 +62930,12 @@ var _$ContourCarpet_769 = ContourCarpet; 'use strict'; -var _$contourcarpet_11 = _$ContourCarpet_769; +var _$contourcarpet_11 = _$ContourCarpet_831; var _$plotcss_1 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../src/lib'); */; +/* removed: var _$lib_601 = require('../src/lib'); */; var rules = { "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;", "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;", @@ -61171,7 +62994,7 @@ for(var selector in rules) { var fullSelector = selector.replace(/^,/,' ,') .replace(/X/g, '.js-plotly-plot .plotly') .replace(/Y/g, '.plotly-notifier'); - _$lib_539.addStyleRule(fullSelector, rules[selector]); + _$lib_601.addStyleRule(fullSelector, rules[selector]); } 'use strict'; @@ -61299,9 +63122,9 @@ var _$ploticon_2 = { } }; -var _$browser_304 = {}; +var _$browser_366 = {}; // shim for using process in browser -var process = _$browser_304 = {}; +var process = _$browser_366 = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is @@ -61461,17 +63284,17 @@ process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; -function __noop_304() {} +function __noop_366() {} -process.on = __noop_304; -process.addListener = __noop_304; -process.once = __noop_304; -process.off = __noop_304; -process.removeListener = __noop_304; -process.removeAllListeners = __noop_304; -process.emit = __noop_304; -process.prependListener = __noop_304; -process.prependOnceListener = __noop_304; +process.on = __noop_366; +process.addListener = __noop_366; +process.once = __noop_366; +process.off = __noop_366; +process.removeListener = __noop_366; +process.removeAllListeners = __noop_366; +process.emit = __noop_366; +process.prependListener = __noop_366; +process.prependOnceListener = __noop_366; process.listeners = function (name) { return [] } @@ -61485,7 +63308,7 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -var _$es6Promise_136 = { exports: {} }; +var _$es6Promise_184 = { exports: {} }; (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. @@ -61496,7 +63319,7 @@ var _$es6Promise_136 = { exports: {} }; */ (function (global, factory) { - typeof _$es6Promise_136.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_136.exports = factory() : + typeof _$es6Promise_184.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_184.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; @@ -62641,8 +64464,8 @@ return Promise; }))); //# sourceMappingURL=es6-promise.map -}).call(this,_$browser_304,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$es6Promise_136 = _$es6Promise_136.exports +}).call(this,_$browser_366,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +_$es6Promise_184 = _$es6Promise_184.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -62668,7 +64491,7 @@ _$es6Promise_136 = _$es6Promise_136.exports * circles, for which it's irrelevant. */ -var _$arrow_paths_393 = [ +var _$arrow_paths_455 = [ // no arrow { path: '', @@ -62723,12 +64546,12 @@ var _$arrow_paths_393 = [ 'use strict'; -/* removed: var _$arrow_paths_393 = require('./arrow_paths'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_589 = require('../../plots/cartesian/constants'); */; +/* removed: var _$arrow_paths_455 = require('./arrow_paths'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$constants_652 = require('../../plots/cartesian/constants'); */; -var _$attributes_394 = { +var _$attributes_456 = { _isLinkedToArray: 'annotation', visible: { @@ -62763,7 +64586,7 @@ var _$attributes_394 = { 'with respect to the horizontal.' ].join(' ') }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'calcIfAutorange+arraydraw', colorEditType: 'arraydraw', description: 'Sets the annotation text font.' @@ -62884,7 +64707,7 @@ var _$attributes_394 = { arrowhead: { valType: 'integer', min: 0, - max: _$arrow_paths_393.length, + max: _$arrow_paths_455.length, dflt: 1, role: 'style', editType: 'arraydraw', @@ -62893,7 +64716,7 @@ var _$attributes_394 = { startarrowhead: { valType: 'integer', min: 0, - max: _$arrow_paths_393.length, + max: _$arrow_paths_455.length, dflt: 1, role: 'style', editType: 'arraydraw', @@ -62996,7 +64819,7 @@ var _$attributes_394 = { dflt: 'pixel', values: [ 'pixel', - _$constants_589.idRegex.x.toString() + _$constants_652.idRegex.x.toString() ], role: 'info', editType: 'calc', @@ -63014,7 +64837,7 @@ var _$attributes_394 = { dflt: 'pixel', values: [ 'pixel', - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.y.toString() ], role: 'info', editType: 'calc', @@ -63032,7 +64855,7 @@ var _$attributes_394 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.x.toString() + _$constants_652.idRegex.x.toString() ], role: 'info', editType: 'calc', @@ -63095,7 +64918,7 @@ var _$attributes_394 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.y.toString() ], role: 'info', editType: 'calc', @@ -63223,7 +65046,7 @@ var _$attributes_394 = { 'contrast with `hoverlabel.bgcolor`.' ].join(' ') }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'arraydraw', description: [ 'Sets the hover label text font.', @@ -63271,11 +65094,11 @@ var _$attributes_394 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$color_473 = require('../color'); */; -/* removed: var _$arrow_paths_393 = require('./arrow_paths'); */; +/* removed: var _$arrow_paths_455 = require('./arrow_paths'); */; /** * Add arrowhead(s) to a path or line element @@ -63297,10 +65120,10 @@ var _$attributes_394 = { * of both the line and head has opacity applied to it so there isn't greater opacity * where they overlap. */ -var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { +var _$drawArrowHead_463 = function drawArrowHead(el3, ends, options) { var el = el3.node(); - var headStyle = _$arrow_paths_393[options.arrowhead || 0]; - var startHeadStyle = _$arrow_paths_393[options.startarrowhead || 0]; + var headStyle = _$arrow_paths_455[options.arrowhead || 0]; + var startHeadStyle = _$arrow_paths_455[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; @@ -63394,7 +65217,7 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { if(!arrowHeadStyle.path) return; if(arrowHeadStyle.noRotate) rot = 0; - _$d3_127.select(el.parentNode).append('path') + _$d3_130.select(el.parentNode).append('path') .attr({ 'class': el3.attr('class'), d: arrowHeadStyle.path, @@ -63404,7 +65227,7 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { 'scale(' + arrowScale + ')' }) .style({ - fill: _$color_411.rgb(options.arrowcolor), + fill: _$color_473.rgb(options.arrowcolor), 'stroke-width': 0 }); } @@ -63423,19 +65246,19 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$fx_453 = require('../fx'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$drawArrowHead_401 = require('./draw_arrow_head'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$fx_515 = require('../fx'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$drawArrowHead_463 = require('./draw_arrow_head'); */; // Annotations are stored in gd.layout.annotations, an array of objects // index can point to one item in this array, @@ -63446,8 +65269,8 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { // if opt is blank, val can be 'add' or a full options object to add a new // annotation at that point in the array, or 'remove' to delete this one -var _$draw_400 = { - draw: __draw_400, +var _$draw_462 = { + draw: __draw_462, drawOne: drawOne, drawRaw: drawRaw }; @@ -63455,7 +65278,7 @@ var _$draw_400 = { /* * draw: draw all annotations without any new modifications */ -function __draw_400(gd) { +function __draw_462(gd) { var fullLayout = gd._fullLayout; fullLayout._infolayer.selectAll('.annotation').remove(); @@ -63466,7 +65289,7 @@ function __draw_400(gd) { } } - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); } /* @@ -63477,8 +65300,8 @@ function __draw_400(gd) { function drawOne(gd, index) { var fullLayout = gd._fullLayout; var options = fullLayout.annotations[index] || {}; - var xa = _$axes_584.getFromId(gd, options.xref); - var ya = _$axes_584.getFromId(gd, options.yref); + var xa = _$axes_647.getFromId(gd, options.xref); + var ya = _$axes_647.getFromId(gd, options.yref); drawRaw(gd, options, index, false, xa, ya); } @@ -63520,7 +65343,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // this annotation is gone - quit now after deleting it // TODO: use d3 idioms instead of deleting and redrawing every time if(!options._input || options.visible === false) { - _$d3_127.selectAll('#' + annClipID).remove(); + _$d3_130.selectAll('#' + annClipID).remove(); return; } @@ -63547,7 +65370,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextGroupInner = annTextGroup.append('g') .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_558, 'default') + .call(_$setCursor_621, 'default') .on('click', function() { gd._dragging = false; @@ -63555,7 +65378,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { index: index, annotation: options._input, fullAnnotation: options, - event: _$d3_127.event + event: _$d3_130.event }; if(subplotId) { @@ -63573,7 +65396,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var bBox = this.getBoundingClientRect(); var bBoxRef = gd.getBoundingClientRect(); - _$fx_453.loneHover({ + _$fx_515.loneHover({ x0: bBox.left - bBoxRef.left, x1: bBox.right - bBoxRef.left, y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, @@ -63590,7 +65413,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }) .on('mouseout', function() { - _$fx_453.loneUnhover(fullLayout._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout._hoverlayer.node()); }); } @@ -63601,8 +65424,8 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextBG = annTextGroupInner.append('rect') .attr('class', 'bg') .style('stroke-width', borderwidth + 'px') - .call(_$color_411.stroke, options.bordercolor) - .call(_$color_411.fill, options.bgcolor); + .call(_$color_473.stroke, options.bordercolor) + .call(_$color_473.fill, options.bgcolor); var isSizeConstrained = options.width || options.height; @@ -63623,7 +65446,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { .text(options.text); function textLayout(s) { - s.call(_$drawing_436.font, font) + s.call(_$drawing_498.font, font) .attr({ 'text-anchor': { left: 'start', @@ -63631,7 +65454,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }[options.align] || 'middle' }); - _$svg_text_utils_562.convertToTspans(s, gd, drawGraphicalElements); + _$svg_text_utils_625.convertToTspans(s, gd, drawGraphicalElements); return s; } @@ -63650,7 +65473,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = _$drawing_436.bBox( + var anntextBB = _$drawing_498.bBox( (hasMathjax ? mathjaxGroup : annText).node()); var textWidth = anntextBB.width; var textHeight = anntextBB.height; @@ -63772,7 +65595,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // partially visible var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height']; if(axRef === 'paper') { - posPx.head = _$lib_539.constrain(posPx.head, 1, maxPx - 1); + posPx.head = _$lib_601.constrain(posPx.head, 1, maxPx - 1); } if(tailRef === 'pixel') { var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), @@ -63831,23 +65654,23 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { x: borderfull + xShift - 1, y: borderfull + yShift }) - .call(_$drawing_436.setClipUrl, isSizeConstrained ? annClipID : null); + .call(_$drawing_498.setClipUrl, isSizeConstrained ? annClipID : null); } else { var texty = borderfull + yShift - anntextBB.top; var textx = borderfull + xShift - anntextBB.left; - annText.call(_$svg_text_utils_562.positionText, textx, texty) - .call(_$drawing_436.setClipUrl, isSizeConstrained ? annClipID : null); + annText.call(_$svg_text_utils_625.positionText, textx, texty) + .call(_$drawing_498.setClipUrl, isSizeConstrained ? annClipID : null); } - annTextClip.select('rect').call(_$drawing_436.setRect, borderfull, borderfull, + annTextClip.select('rect').call(_$drawing_498.setRect, borderfull, borderfull, annWidth, annHeight); - annTextBG.call(_$drawing_436.setRect, borderwidth / 2, borderwidth / 2, + annTextBG.call(_$drawing_498.setRect, borderwidth / 2, borderwidth / 2, outerWidth - borderwidth, outerHeight - borderwidth); - annTextGroupInner.call(_$drawing_436.setTranslate, + annTextGroupInner.call(_$drawing_498.setTranslate, Math.round(annPosPx.x.text - outerWidth / 2), Math.round(annPosPx.y.text - outerHeight / 2)); @@ -63880,9 +65703,9 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // find the edge of the text box, where we'll start the arrow: // create transform matrix to rotate the text box corners - transform = _$lib_539.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_539.apply2DTransform(transform), - applyTransform2 = _$lib_539.apply2DTransform2(transform), + transform = _$lib_601.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_601.apply2DTransform(transform), + applyTransform2 = _$lib_601.apply2DTransform2(transform), // calculate and transform bounding box width = +annTextBG.attr('width'), @@ -63904,7 +65727,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // to get the parity of the number of intersections. if(edges.reduce(function(a, x) { return a ^ - !!_$lib_539.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, + !!_$lib_601.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, x[0], x[1], x[2], x[3]); }, false)) { // no line or arrow - so quit drawArrow now @@ -63912,7 +65735,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } edges.forEach(function(x) { - var p = _$lib_539.segmentsIntersect(tailX, tailY, headX, headY, + var p = _$lib_601.segmentsIntersect(tailX, tailY, headX, headY, x[0], x[1], x[2], x[3]); if(p) { tailX = p.x; @@ -63925,15 +65748,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { arrowSide = options.arrowside; var arrowGroup = annGroup.append('g') - .style({opacity: _$color_411.opacity(arrowColor)}) + .style({opacity: _$color_473.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_411.stroke, _$color_411.rgb(arrowColor)); + .call(_$color_473.stroke, _$color_473.rgb(arrowColor)); - _$drawArrowHead_401(arrow, arrowSide, options); + _$drawArrowHead_463(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 @@ -63953,8 +65776,8 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' }) .style('stroke-width', (strokewidth + 6) + 'px') - .call(_$color_411.stroke, 'rgba(0,0,0,0)') - .call(_$color_411.fill, 'rgba(0,0,0,0)'); + .call(_$color_473.stroke, 'rgba(0,0,0,0)') + .call(_$color_473.fill, 'rgba(0,0,0,0)'); var update, annx0, @@ -63962,11 +65785,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // dragger for the arrow & head: translates the whole thing // (head/tail/text) all together - _$dragelement_433.init({ + _$dragelement_495.init({ element: arrowDrag.node(), gd: gd, prepFn: function() { - var pos = _$drawing_436.getTranslate(annTextGroupInner); + var pos = _$drawing_498.getTranslate(annTextGroupInner); annx0 = pos.x; anny0 = pos.y; @@ -63982,7 +65805,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annxy0 = applyTransform(annx0, anny0), xcenter = annxy0[0] + dx, ycenter = annxy0[1] + dy; - annTextGroupInner.call(_$drawing_436.setTranslate, xcenter, ycenter); + annTextGroupInner.call(_$drawing_498.setTranslate, xcenter, ycenter); update[annbase + '.x'] = xa ? xa.p2r(xa.r2p(options.x) + dx) : @@ -64006,7 +65829,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }, doneFn: function() { - _$registry_668.call('relayout', gd, update); + _$registry_731.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -64023,7 +65846,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // dragger for the textbox: if there's an arrow, just drag the // textbox and tail, leave the head untouched - _$dragelement_433.init({ + _$dragelement_495.init({ element: annTextGroupInner.node(), gd: gd, prepFn: function() { @@ -64056,7 +65879,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2; - update[annbase + '.x'] = _$dragelement_433.align(xLeft + dx / gs.w, + update[annbase + '.x'] = _$dragelement_495.align(xLeft + dx / gs.w, widthFraction, 0, 1, options.xanchor); } @@ -64067,11 +65890,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2; - update[annbase + '.y'] = _$dragelement_433.align(yBottom - dy / gs.h, + update[annbase + '.y'] = _$dragelement_495.align(yBottom - dy / gs.h, heightFraction, 0, 1, options.yanchor); } if(!xa || !ya) { - csr = _$dragelement_433.getCursor( + csr = _$dragelement_495.getCursor( xa ? 0.5 : update[annbase + '.x'], ya ? 0.5 : update[annbase + '.y'], options.xanchor, options.yanchor @@ -64084,11 +65907,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform }); - _$setCursor_558(annTextGroupInner, csr); + _$setCursor_621(annTextGroupInner, csr); }, doneFn: function() { - _$setCursor_558(annTextGroupInner); - _$registry_668.call('relayout', gd, update); + _$setCursor_621(annTextGroupInner); + _$registry_731.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -64097,7 +65920,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } if(edits.annotationText) { - annText.call(_$svg_text_utils_562.makeEditable, {delegate: annTextGroupInner, gd: gd}) + annText.call(_$svg_text_utils_625.makeEditable, {delegate: annTextGroupInner, gd: gd}) .call(textLayout) .on('edit', function(_text) { options.text = _text; @@ -64113,7 +65936,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { update[ya._name + '.autorange'] = true; } - _$registry_668.call('relayout', gd, update); + _$registry_731.call('relayout', gd, update); }); } else annText.call(textLayout); @@ -64130,15 +65953,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var __draw_395 = _$draw_400.draw; +var __draw_457 = _$draw_462.draw; -var _$calcAutorange_395 = function calcAutorange(gd) { +var _$calcAutorange_457 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - annotationList = _$lib_539.filterVisible(fullLayout.annotations); + annotationList = _$lib_601.filterVisible(fullLayout.annotations); if(!annotationList.length || !gd._fullData.length) return; @@ -64149,10 +65972,10 @@ var _$calcAutorange_395 = function calcAutorange(gd) { }); for(var axId in annotationAxes) { - var ax = _$axes_584.getFromId(gd, axId); + var ax = _$axes_647.getFromId(gd, axId); if(ax && ax.autorange) { - return _$lib_539.syncOrAsync([ - __draw_395, + return _$lib_601.syncOrAsync([ + __draw_457, annAutorange ], gd); } @@ -64166,9 +65989,9 @@ function annAutorange(gd) { // relative to their anchor points // use the arrow and the text bg rectangle, // as the whole anno may include hidden text in its bbox - _$lib_539.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_584.getFromId(gd, ann.xref), - ya = _$axes_584.getFromId(gd, ann.yref), + _$lib_601.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_647.getFromId(gd, ann.xref), + ya = _$axes_647.getFromId(gd, ann.yref), headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; @@ -64182,12 +66005,12 @@ function annAutorange(gd) { if(ann.axref === ann.xref) { // expand for the arrowhead (padded by arrowhead) - _$axes_584.expand(xa, [xa.r2c(ann.x)], { + _$axes_647.expand(xa, [xa.r2c(ann.x)], { ppadplus: headPlus, ppadminus: headMinus }); // again for the textbox (padded by textbox) - _$axes_584.expand(xa, [xa.r2c(ann.ax)], { + _$axes_647.expand(xa, [xa.r2c(ann.ax)], { ppadplus: Math.max(ann._xpadplus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, startHeadMinus) }); @@ -64195,7 +66018,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_584.expand(xa, [xa.r2c(ann.x)], { + _$axes_647.expand(xa, [xa.r2c(ann.x)], { ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) }); @@ -64209,11 +66032,11 @@ function annAutorange(gd) { startHeadMinus = startHeadSize + ann.yshift; if(ann.ayref === ann.yref) { - _$axes_584.expand(ya, [ya.r2c(ann.y)], { + _$axes_647.expand(ya, [ya.r2c(ann.y)], { ppadplus: headPlus, ppadminus: headMinus }); - _$axes_584.expand(ya, [ya.r2c(ann.ay)], { + _$axes_647.expand(ya, [ya.r2c(ann.ay)], { ppadplus: Math.max(ann._ypadplus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, startHeadMinus) }); @@ -64221,7 +66044,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_584.expand(ya, [ya.r2c(ann.y)], { + _$axes_647.expand(ya, [ya.r2c(ann.y)], { ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) }); @@ -64240,9 +66063,9 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$click_396 = { +var _$click_458 = { hasClickToShow: hasClickToShow, onClick: onClick }; @@ -64289,7 +66112,7 @@ function onClick(gd, hoverData) { update['annotations[' + offSet[i] + '].visible'] = false; } - return _$registry_668.call('update', gd, {}, update); + return _$registry_731.call('update', gd, {}, update); } /* @@ -64372,8 +66195,8 @@ function clickData2r(d, ax) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_564 = require('../../lib/to_log_range'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_627 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -64388,7 +66211,7 @@ function clickData2r(d, ax) { * Use this to make the changes as it's aware if any other changes in the * same relayout call should override this conversion. */ -var _$convertCoords_398 = function convertCoords(gd, ax, newType, doExtra) { +var _$convertCoords_460 = function convertCoords(gd, ax, newType, doExtra) { ax = ax || {}; var toLog = (newType === 'log') && (ax.type === 'linear'), @@ -64405,11 +66228,11 @@ var _$convertCoords_398 = function convertCoords(gd, ax, newType, doExtra) { var currentVal = ann[attr], newVal = null; - if(toLog) newVal = _$toLogRange_564(currentVal, ax.range); + if(toLog) newVal = _$toLogRange_627(currentVal, ax.range); else newVal = Math.pow(10, currentVal); // if conversion failed, delete the value so it gets a default value - if(!_$fastIsnumeric_139(newVal)) newVal = null; + if(!_$fastIsnumeric_196(newVal)) newVal = null; doExtra(attrPrefix + attr, newVal); } @@ -64433,16 +66256,16 @@ var _$convertCoords_398 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../color'); */; // defaults common to 'annotations' and 'annotations3d' -var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { +var _$handleAnnotationCommonDefaults_459 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { coerce('opacity'); var bgColor = coerce('bgcolor'); var borderColor = coerce('bordercolor'); - var borderOpacity = _$color_411.opacity(borderColor); + var borderOpacity = _$color_473.opacity(borderColor); coerce('borderpad'); @@ -64451,7 +66274,7 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); coerce('textangle'); - _$lib_539.coerceFont(coerce, 'font', fullLayout.font); + _$lib_601.coerceFont(coerce, 'font', fullLayout.font); coerce('width'); coerce('align'); @@ -64473,7 +66296,7 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul coerce('startarrowhead', arrowhead); coerce('startarrowsize', arrowsize); } - coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_411.defaultLine); + coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_473.defaultLine); coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); coerce('standoff'); coerce('startstandoff'); @@ -64485,14 +66308,14 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul if(hoverText) { var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || - (_$color_411.opacity(bgColor) ? _$color_411.rgb(bgColor) : _$color_411.defaultLine) + (_$color_473.opacity(bgColor) ? _$color_473.rgb(bgColor) : _$color_473.defaultLine) ); var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || - _$color_411.contrast(hoverBG) + _$color_473.contrast(hoverBG) ); - _$lib_539.coerceFont(coerce, 'hoverlabel.font', { + _$lib_601.coerceFont(coerce, 'hoverlabel.font', { family: globalHoverLabel.font.family, size: globalHoverLabel.font.size, color: globalHoverLabel.font.color || hoverBorder @@ -64513,18 +66336,18 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleAnnotationCommonDefaults_397 = require('./common_defaults'); */; -/* removed: var _$attributes_394 = require('./attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleAnnotationCommonDefaults_459 = require('./common_defaults'); */; +/* removed: var _$attributes_456 = require('./attributes'); */; -var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { +var _$handleAnnotationDefaults_454 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { opts = opts || {}; itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(annIn, annOut, _$attributes_394, attr, dflt); + return _$lib_601.coerce(annIn, annOut, _$attributes_456, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -64532,7 +66355,7 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an if(!(visible || clickToShow)) return annOut; - _$handleAnnotationCommonDefaults_397(annIn, annOut, fullLayout, coerce); + _$handleAnnotationCommonDefaults_459(annIn, annOut, fullLayout, coerce); var showArrow = annOut.showarrow; @@ -64544,15 +66367,15 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an var axLetter = axLetters[i]; // xref, yref - var axRef = _$axes_584.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_647.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); // x, y - _$axes_584.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + _$axes_647.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); if(showArrow) { var arrowPosAttr = 'a' + axLetter, // axref, ayref - aaxRef = _$axes_584.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + aaxRef = _$axes_647.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); // for now the arrow can only be on the same axis or specified as pixels // TODO: sometime it might be interesting to allow it to be on *any* axis @@ -64563,7 +66386,7 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an // ax, ay var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_584.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + _$axes_647.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } // xanchor, yanchor @@ -64574,11 +66397,11 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an } // if you have one coordinate you should have both - _$lib_539.noneOrAll(annIn, annOut, ['x', 'y']); + _$lib_601.noneOrAll(annIn, annOut, ['x', 'y']); // if you have one part of arrow length you should have both if(showArrow) { - _$lib_539.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_601.noneOrAll(annIn, annOut, ['ax', 'ay']); } if(clickToShow) { @@ -64589,10 +66412,10 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an // so we don't have to do this little bit of logic on every hover event annOut._xclick = (xClick === undefined) ? annOut.x : - _$axes_584.cleanPosition(xClick, gdMock, annOut.xref); + _$axes_647.cleanPosition(xClick, gdMock, annOut.xref); annOut._yclick = (yClick === undefined) ? annOut.y : - _$axes_584.cleanPosition(yClick, gdMock, annOut.yref); + _$axes_647.cleanPosition(yClick, gdMock, annOut.yref); } return annOut; @@ -64608,7 +66431,7 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$lib_601 = require('../lib'); */; /** Convenience wrapper for making array container logic DRY and consistent * @@ -64640,12 +66463,12 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an * links to supplementary data (e.g. fullData for layout components) * */ -var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { +var _$handleArrayContainerDefaults_643 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { var name = opts.name; var previousContOut = parentObjOut[name]; - var contIn = _$lib_539.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + var contIn = _$lib_601.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], contOut = parentObjOut[name] = [], i; @@ -64654,7 +66477,7 @@ var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(p itemOut = {}, itemOpts = {}; - if(!_$lib_539.isPlainObject(itemIn)) { + if(!_$lib_601.isPlainObject(itemIn)) { itemOpts.itemIsNotPlainObject = true; itemIn = {}; } @@ -64669,10 +66492,10 @@ var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(p // in case this array gets its defaults rebuilt independent of the whole layout, // relink the private keys just for this array. - if(_$lib_539.isArrayOrTypedArray(previousContOut)) { + if(_$lib_601.isArrayOrTypedArray(previousContOut)) { var len = Math.min(previousContOut.length, contOut.length); for(i = 0; i < len; i++) { - _$lib_539.relinkPrivateKeys(contOut[i], previousContOut[i]); + _$lib_601.relinkPrivateKeys(contOut[i], previousContOut[i]); } } }; @@ -64688,17 +66511,17 @@ var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(p 'use strict'; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationDefaults_392 = require('./annotation_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationDefaults_454 = require('./annotation_defaults'); */; -var _$supplyLayoutDefaults_399 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_461 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { name: 'annotations', - handleItemDefaults: _$handleAnnotationDefaults_392 + handleItemDefaults: _$handleAnnotationDefaults_454 }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; /** @@ -64712,8 +66535,8 @@ var _$supplyLayoutDefaults_399 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** * Factory function for checking component arrays for subplot references. @@ -64726,12 +66549,12 @@ var _$supplyLayoutDefaults_399 = function supplyLayoutDefaults(layoutIn, layoutO * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout) * as expected of a component includeBasePlot method */ -var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayName) { +var _$makeIncludeComponents_657 = function makeIncludeComponents(containerArrayName) { return function includeComponents(layoutIn, layoutOut) { var array = layoutIn[containerArrayName]; if(!Array.isArray(array)) return; - var Cartesian = _$registry_668.subplotsRegistry.cartesian; + var Cartesian = _$registry_731.subplotsRegistry.cartesian; var idRegex = Cartesian.idRegex; var subplots = layoutOut._subplots; var xaList = subplots.xaxis; @@ -64741,7 +66564,7 @@ var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayN for(var i = 0; i < array.length; i++) { var itemi = array[i]; - if(!_$lib_539.isPlainObject(itemi)) continue; + if(!_$lib_601.isPlainObject(itemi)) continue; var xref = itemi.xref; var yref = itemi.yref; @@ -64749,7 +66572,7 @@ var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayN var hasXref = idRegex.x.test(xref); var hasYref = idRegex.y.test(yref); if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_539.pushUnique(layoutOut._basePlotModules, Cartesian); + if(!hasCartesianOrGL2D) _$lib_601.pushUnique(layoutOut._basePlotModules, Cartesian); var newAxis = false; if(hasXref && xaList.indexOf(xref) === -1) { @@ -64786,26 +66609,26 @@ var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayN 'use strict'; -/* removed: var _$draw_400 = require('./draw'); */; -/* removed: var _$click_396 = require('./click'); */; +/* removed: var _$draw_462 = require('./draw'); */; +/* removed: var _$click_458 = require('./click'); */; -var _$annotations_402 = { +var _$annotations_464 = { moduleType: 'component', name: 'annotations', - layoutAttributes: _$attributes_394, - supplyLayoutDefaults: _$supplyLayoutDefaults_399, - includeBasePlot: _$makeIncludeComponents_594('annotations'), + layoutAttributes: _$attributes_456, + supplyLayoutDefaults: _$supplyLayoutDefaults_461, + includeBasePlot: _$makeIncludeComponents_657('annotations'), - calcAutorange: _$calcAutorange_395, - draw: _$draw_400.draw, - drawOne: _$draw_400.drawOne, - drawRaw: _$draw_400.drawRaw, + calcAutorange: _$calcAutorange_457, + draw: _$draw_462.draw, + drawOne: _$draw_462.drawOne, + drawRaw: _$draw_462.drawRaw, - hasClickToShow: _$click_396.hasClickToShow, - onClick: _$click_396.onClick, + hasClickToShow: _$click_458.hasClickToShow, + onClick: _$click_458.onClick, - convertCoords: _$convertCoords_398 + convertCoords: _$convertCoords_460 }; /** @@ -64819,13 +66642,13 @@ var _$annotations_402 = { 'use strict'; -/* removed: var _$attributes_394 = require('../annotations/attributes'); */; -var __overrideAll_403 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_456 = require('../annotations/attributes'); */; +var __overrideAll_465 = _$edit_types_632.overrideAll; -var _$attributes_403 = __overrideAll_403({ +var _$attributes_465 = __overrideAll_465({ _isLinkedToArray: 'annotation', - visible: _$attributes_394.visible, + visible: _$attributes_456.visible, x: { valType: 'any', role: 'info', @@ -64862,36 +66685,36 @@ var _$attributes_403 = __overrideAll_403({ ].join(' ') }, - xanchor: _$attributes_394.xanchor, - xshift: _$attributes_394.xshift, - yanchor: _$attributes_394.yanchor, - yshift: _$attributes_394.yshift, - - text: _$attributes_394.text, - textangle: _$attributes_394.textangle, - font: _$attributes_394.font, - width: _$attributes_394.width, - height: _$attributes_394.height, - opacity: _$attributes_394.opacity, - align: _$attributes_394.align, - valign: _$attributes_394.valign, - bgcolor: _$attributes_394.bgcolor, - bordercolor: _$attributes_394.bordercolor, - borderpad: _$attributes_394.borderpad, - borderwidth: _$attributes_394.borderwidth, - showarrow: _$attributes_394.showarrow, - arrowcolor: _$attributes_394.arrowcolor, - arrowhead: _$attributes_394.arrowhead, - startarrowhead: _$attributes_394.startarrowhead, - arrowside: _$attributes_394.arrowside, - arrowsize: _$attributes_394.arrowsize, - startarrowsize: _$attributes_394.startarrowsize, - arrowwidth: _$attributes_394.arrowwidth, - standoff: _$attributes_394.standoff, - startstandoff: _$attributes_394.startstandoff, - hovertext: _$attributes_394.hovertext, - hoverlabel: _$attributes_394.hoverlabel, - captureevents: _$attributes_394.captureevents, + xanchor: _$attributes_456.xanchor, + xshift: _$attributes_456.xshift, + yanchor: _$attributes_456.yanchor, + yshift: _$attributes_456.yshift, + + text: _$attributes_456.text, + textangle: _$attributes_456.textangle, + font: _$attributes_456.font, + width: _$attributes_456.width, + height: _$attributes_456.height, + opacity: _$attributes_456.opacity, + align: _$attributes_456.align, + valign: _$attributes_456.valign, + bgcolor: _$attributes_456.bgcolor, + bordercolor: _$attributes_456.bordercolor, + borderpad: _$attributes_456.borderpad, + borderwidth: _$attributes_456.borderwidth, + showarrow: _$attributes_456.showarrow, + arrowcolor: _$attributes_456.arrowcolor, + arrowhead: _$attributes_456.arrowhead, + startarrowhead: _$attributes_456.startarrowhead, + arrowside: _$attributes_456.arrowside, + arrowsize: _$attributes_456.arrowsize, + startarrowsize: _$attributes_456.startarrowsize, + arrowwidth: _$attributes_456.arrowwidth, + standoff: _$attributes_456.standoff, + startstandoff: _$attributes_456.startstandoff, + hovertext: _$attributes_456.hovertext, + hoverlabel: _$attributes_456.hoverlabel, + captureevents: _$attributes_456.captureevents, // maybes later? // clicktoshow: annAtts.clicktoshow, @@ -64916,10 +66739,10 @@ var _$attributes_403 = __overrideAll_403({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var _$convert_404 = function convert(scene) { +var _$convert_466 = function convert(scene) { var fullSceneLayout = scene.fullSceneLayout; var anns = fullSceneLayout.annotations; @@ -64954,16 +66777,16 @@ function mockAnnAxes(ann, scene) { }; ann._xa = {}; - _$lib_539.extendFlat(ann._xa, base); - _$axes_584.setConvert(ann._xa); + _$lib_601.extendFlat(ann._xa, base); + _$axes_647.setConvert(ann._xa); ann._xa._offset = size.l + domain.x[0] * size.w; ann._xa.l2p = function() { return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); }; ann._ya = {}; - _$lib_539.extendFlat(ann._ya, base); - _$axes_584.setConvert(ann._ya); + _$lib_601.extendFlat(ann._ya, base); + _$axes_647.setConvert(ann._ya); ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; ann._ya.l2p = function() { return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); @@ -64980,23 +66803,23 @@ function mockAnnAxes(ann, scene) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationCommonDefaults_397 = require('../annotations/common_defaults'); */; -/* removed: var _$attributes_403 = require('./attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationCommonDefaults_459 = require('../annotations/common_defaults'); */; +/* removed: var _$attributes_465 = require('./attributes'); */; -var _$handleDefaults_405 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_580(sceneLayoutIn, sceneLayoutOut, { +var _$handleDefaults_467 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + _$handleArrayContainerDefaults_643(sceneLayoutIn, sceneLayoutOut, { name: 'annotations', - handleItemDefaults: __handleAnnotationDefaults_405, + handleItemDefaults: __handleAnnotationDefaults_467, fullLayout: opts.fullLayout }); }; -function __handleAnnotationDefaults_405(annIn, annOut, sceneLayout, opts, itemOpts) { +function __handleAnnotationDefaults_467(annIn, annOut, sceneLayout, opts, itemOpts) { function coerce(attr, dflt) { - return _$lib_539.coerce(annIn, annOut, _$attributes_403, attr, dflt); + return _$lib_601.coerce(annIn, annOut, _$attributes_465, attr, dflt); } function coercePosition(axLetter) { @@ -65006,21 +66829,21 @@ function __handleAnnotationDefaults_405(annIn, annOut, sceneLayout, opts, itemOp var gdMock = { _fullLayout: {} }; gdMock._fullLayout[axName] = sceneLayout[axName]; - return _$axes_584.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + return _$axes_647.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); if(!visible) return annOut; - _$handleAnnotationCommonDefaults_397(annIn, annOut, opts.fullLayout, coerce); + _$handleAnnotationCommonDefaults_459(annIn, annOut, opts.fullLayout, coerce); coercePosition('x'); coercePosition('y'); coercePosition('z'); // if you have one coordinate you should all three - _$lib_539.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + _$lib_601.noneOrAll(annIn, annOut, ['x', 'y', 'z']); // hard-set here for completeness annOut.xref = 'x'; @@ -65041,7 +66864,7 @@ function __handleAnnotationDefaults_405(annIn, annOut, sceneLayout, opts, itemOp coerce('ay', -30); // if you have one part of arrow length you should have both - _$lib_539.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_601.noneOrAll(annIn, annOut, ['ax', 'ay']); } return annOut; @@ -65078,7 +66901,7 @@ function project(camera, v) { return p; } -var _$project_636 = project; +var _$project_698 = project; /** * Copyright 2012-2018, Plotly, Inc. @@ -65090,11 +66913,11 @@ var _$project_636 = project; 'use strict'; -var __drawRaw_406 = _$draw_400.drawRaw; -/* removed: var _$project_636 = require('../../plots/gl3d/project'); */; +var __drawRaw_468 = _$draw_462.drawRaw; +/* removed: var _$project_698 = require('../../plots/gl3d/project'); */; var axLetters = ['x', 'y', 'z']; -var _$draw_406 = function draw(scene) { +var _$draw_468 = function draw(scene) { var fullSceneLayout = scene.fullSceneLayout; var dataScale = scene.dataScale; var anns = fullSceneLayout.annotations; @@ -65120,13 +66943,13 @@ var _$draw_406 = function draw(scene) { .select('.annotation-' + scene.id + '[data-index="' + i + '"]') .remove(); } else { - ann._pdata = _$project_636(scene.glplot.cameraParams, [ + ann._pdata = _$project_698(scene.glplot.cameraParams, [ fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] ]); - __drawRaw_406(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + __drawRaw_468(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); } } }; @@ -65141,29 +66964,29 @@ var _$draw_406 = function draw(scene) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$annotations3d_407 = { +var _$annotations3d_469 = { moduleType: 'component', name: 'annotations3d', schema: { subplots: { - scene: {annotations: _$attributes_403} + scene: {annotations: _$attributes_465} } }, - layoutAttributes: _$attributes_403, - handleDefaults: _$handleDefaults_405, + layoutAttributes: _$attributes_465, + handleDefaults: _$handleDefaults_467, includeBasePlot: includeGL3D, - convert: _$convert_404, - draw: _$draw_406 + convert: _$convert_466, + draw: _$draw_468 }; function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_668.subplotsRegistry.gl3d; + var GL3D = _$registry_731.subplotsRegistry.gl3d; if(!GL3D) return; var attrRegex = GL3D.attrRegex; @@ -65172,8 +66995,8 @@ function includeGL3D(layoutIn, layoutOut) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_539.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_539.pushUnique(layoutOut._subplots.gl3d, k); + _$lib_601.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_601.pushUnique(layoutOut._subplots.gl3d, k); } } } @@ -65189,7 +67012,7 @@ function includeGL3D(layoutIn, layoutOut) { 'use strict'; -var _$attributes_438 = { +var _$attributes_500 = { visible: { valType: 'boolean', role: 'info', @@ -65362,7 +67185,7 @@ var _$attributes_438 = { * - error[0] : error magnitude in the negative direction * - error[1] : " " " " positive " */ -var _$makeComputeError_440 = function makeComputeError(opts) { +var _$makeComputeError_502 = function makeComputeError(opts) { var type = opts.type, symmetric = opts.symmetric; @@ -65449,25 +67272,25 @@ function makeComputeErrorValue(type, value) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$makeComputeError_440 = require('./compute_error'); */; +/* removed: var _$makeComputeError_502 = require('./compute_error'); */; -var _$calc_439 = function calc(gd) { +var _$calc_501 = function calc(gd) { var calcdata = gd.calcdata; for(var i = 0; i < calcdata.length; i++) { var calcTrace = calcdata[i], trace = calcTrace[0].trace; - if(!_$registry_668.traceIs(trace, 'errorBarsOK')) continue; + if(!_$registry_731.traceIs(trace, 'errorBarsOK')) continue; - var xa = _$axes_584.getFromId(gd, trace.xaxis), - ya = _$axes_584.getFromId(gd, trace.yaxis); + var xa = _$axes_647.getFromId(gd, trace.xaxis), + ya = _$axes_647.getFromId(gd, trace.yaxis); calcOneAxis(calcTrace, trace, xa, 'x'); calcOneAxis(calcTrace, trace, ya, 'y'); @@ -65481,23 +67304,23 @@ function calcOneAxis(calcTrace, trace, axis, coord) { if(!isVisible) return; - var computeError = _$makeComputeError_440(opts); + var computeError = _$makeComputeError_502(opts); for(var i = 0; i < calcTrace.length; i++) { var calcPt = calcTrace[i], calcCoord = calcPt[coord]; - if(!_$fastIsnumeric_139(axis.c2l(calcCoord))) continue; + if(!_$fastIsnumeric_196(axis.c2l(calcCoord))) continue; var errors = computeError(calcCoord, i); - if(_$fastIsnumeric_139(errors[0]) && _$fastIsnumeric_139(errors[1])) { + if(_$fastIsnumeric_196(errors[0]) && _$fastIsnumeric_196(errors[1])) { var shoe = calcPt[coord + 's'] = calcCoord - errors[0], hat = calcPt[coord + 'h'] = calcCoord + errors[1]; vals.push(shoe, hat); } } - _$axes_584.expand(axis, vals, {padded: true}); + _$axes_647.expand(axis, vals, {padded: true}); } /** @@ -65510,21 +67333,21 @@ function calcOneAxis(calcTrace, trace, axis, coord) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$attributes_438 = require('./attributes'); */; +/* removed: var _$attributes_500 = require('./attributes'); */; -var _$defaults_441 = function(traceIn, traceOut, defaultColor, opts) { +var _$defaults_503 = function(traceIn, traceOut, defaultColor, opts) { var objName = 'error_' + opts.axis, containerOut = traceOut[objName] = {}, containerIn = traceIn[objName] || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$attributes_438, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$attributes_500, attr, dflt); } var hasErrorBars = ( @@ -65563,14 +67386,14 @@ var _$defaults_441 = function(traceIn, traceOut, defaultColor, opts) { var inheritObj = traceOut['error_' + opts.inherit]; if((inheritObj || {}).visible) { coerce(copyAttr, !(containerIn.color || - _$fastIsnumeric_139(containerIn.thickness) || - _$fastIsnumeric_139(containerIn.width))); + _$fastIsnumeric_196(containerIn.thickness) || + _$fastIsnumeric_196(containerIn.width))); } } if(!opts.inherit || !containerOut[copyAttr]) { coerce('color', defaultColor); coerce('thickness'); - coerce('width', _$registry_668.traceIs(traceOut, 'gl3d') ? 0 : 4); + coerce('width', _$registry_731.traceIs(traceOut, 'gl3d') ? 0 : 4); } }; @@ -65585,13 +67408,13 @@ var _$defaults_441 = function(traceIn, traceOut, defaultColor, opts) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; -var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { +var _$plot_505 = function plot(traces, plotinfo, transitionOpts) { var isNew; var xa = plotinfo.xaxis; @@ -65615,13 +67438,13 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { } var sparse = ( - _$subtypes_884.hasMarkers(trace) && + _$subtypes_949.hasMarkers(trace) && trace.marker.maxdisplayed > 0 ); if(!yObj.visible && !xObj.visible) d = []; - var errorbars = _$d3_127.select(this).selectAll('g.errorbar') + var errorbars = _$d3_130.select(this).selectAll('g.errorbar') .data(d, keyFunc); errorbars.exit().remove(); @@ -65642,10 +67465,10 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { .style('opacity', 1); } - _$drawing_436.setClipUrl(errorbars, plotinfo.layerClipId); + _$drawing_498.setClipUrl(errorbars, plotinfo.layerClipId); errorbars.each(function(d) { - var errorbar = _$d3_127.select(this); + var errorbar = _$d3_130.select(this); var coords = errorCoords(d, xa, ya); if(sparse && !d.vis) return; @@ -65653,9 +67476,9 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { var path; var yerror = errorbar.select('path.yerror'); - if(yObj.visible && _$fastIsnumeric_139(coords.x) && - _$fastIsnumeric_139(coords.yh) && - _$fastIsnumeric_139(coords.ys)) { + if(yObj.visible && _$fastIsnumeric_196(coords.x) && + _$fastIsnumeric_196(coords.yh) && + _$fastIsnumeric_196(coords.ys)) { var yw = yObj.width; path = 'M' + (coords.x - yw) + ',' + @@ -65683,9 +67506,9 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { else yerror.remove(); var xerror = errorbar.select('path.xerror'); - if(xObj.visible && _$fastIsnumeric_139(coords.y) && - _$fastIsnumeric_139(coords.xh) && - _$fastIsnumeric_139(coords.xs)) { + if(xObj.visible && _$fastIsnumeric_196(coords.y) && + _$fastIsnumeric_196(coords.xh) && + _$fastIsnumeric_196(coords.xs)) { var xw = (xObj.copy_ystyle ? yObj : xObj).width; path = 'M' + coords.xh + ',' + @@ -65728,7 +67551,7 @@ function errorCoords(d, xa, ya) { // if the shoes go off-scale (ie log scale, error bars past zero) // clip the bar and hide the shoes - if(!_$fastIsnumeric_139(out.ys)) { + if(!_$fastIsnumeric_196(out.ys)) { out.noYS = true; out.ys = ya.c2p(d.ys, true); } @@ -65738,7 +67561,7 @@ function errorCoords(d, xa, ya) { out.xh = xa.c2p(d.xh); out.xs = xa.c2p(d.xs); - if(!_$fastIsnumeric_139(out.xs)) { + if(!_$fastIsnumeric_196(out.xs)) { out.noXS = true; out.xs = xa.c2p(d.xs, true); } @@ -65758,28 +67581,28 @@ function errorCoords(d, xa, ya) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$color_473 = require('../color'); */; -var _$style_444 = function style(traces) { +var _$style_506 = function style(traces) { traces.each(function(d) { var trace = d[0].trace, yObj = trace.error_y || {}, xObj = trace.error_x || {}; - var s = _$d3_127.select(this); + var s = _$d3_130.select(this); s.selectAll('path.yerror') .style('stroke-width', yObj.thickness + 'px') - .call(_$color_411.stroke, yObj.color); + .call(_$color_473.stroke, yObj.color); if(xObj.copy_ystyle) xObj = yObj; s.selectAll('path.xerror') .style('stroke-width', xObj.thickness + 'px') - .call(_$color_411.stroke, xObj.color); + .call(_$color_473.stroke, xObj.color); }); }; @@ -65793,51 +67616,51 @@ var _$style_444 = function style(traces) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var __overrideAll_442 = _$edit_types_569.overrideAll; +/* removed: var _$lib_601 = require('../../lib'); */; +var __overrideAll_504 = _$edit_types_632.overrideAll; -/* removed: var _$attributes_438 = require('./attributes'); */; -/* removed: var _$calc_439 = require('./calc'); */; +/* removed: var _$attributes_500 = require('./attributes'); */; +/* removed: var _$calc_501 = require('./calc'); */; -var __xyAttrs_442 = { - error_x: _$lib_539.extendFlat({}, _$attributes_438), - error_y: _$lib_539.extendFlat({}, _$attributes_438) +var __xyAttrs_504 = { + error_x: _$lib_601.extendFlat({}, _$attributes_500), + error_y: _$lib_601.extendFlat({}, _$attributes_500) }; -delete __xyAttrs_442.error_x.copy_zstyle; -delete __xyAttrs_442.error_y.copy_zstyle; -delete __xyAttrs_442.error_y.copy_ystyle; +delete __xyAttrs_504.error_x.copy_zstyle; +delete __xyAttrs_504.error_y.copy_zstyle; +delete __xyAttrs_504.error_y.copy_ystyle; -var __xyzAttrs_442 = { - error_x: _$lib_539.extendFlat({}, _$attributes_438), - error_y: _$lib_539.extendFlat({}, _$attributes_438), - error_z: _$lib_539.extendFlat({}, _$attributes_438) +var __xyzAttrs_504 = { + error_x: _$lib_601.extendFlat({}, _$attributes_500), + error_y: _$lib_601.extendFlat({}, _$attributes_500), + error_z: _$lib_601.extendFlat({}, _$attributes_500) }; -delete __xyzAttrs_442.error_x.copy_ystyle; -delete __xyzAttrs_442.error_y.copy_ystyle; -delete __xyzAttrs_442.error_z.copy_ystyle; -delete __xyzAttrs_442.error_z.copy_zstyle; +delete __xyzAttrs_504.error_x.copy_ystyle; +delete __xyzAttrs_504.error_y.copy_ystyle; +delete __xyzAttrs_504.error_z.copy_ystyle; +delete __xyzAttrs_504.error_z.copy_zstyle; -var _$errorbars_442 = { +var _$errorbars_504 = { moduleType: 'component', name: 'errorbars', schema: { traces: { - scatter: __xyAttrs_442, - bar: __xyAttrs_442, - histogram: __xyAttrs_442, - scatter3d: __overrideAll_442(__xyzAttrs_442, 'calc', 'nested'), - scattergl: __overrideAll_442(__xyAttrs_442, 'calc', 'nested') + scatter: __xyAttrs_504, + bar: __xyAttrs_504, + histogram: __xyAttrs_504, + scatter3d: __overrideAll_504(__xyzAttrs_504, 'calc', 'nested'), + scattergl: __overrideAll_504(__xyAttrs_504, 'calc', 'nested') } }, - supplyDefaults: _$defaults_441, + supplyDefaults: _$defaults_503, - calc: _$calc_439, + calc: _$calc_501, calcFromTrace: calcFromTrace, - plot: _$plot_443, - style: _$style_444, + plot: _$plot_505, + style: _$style_506, hoverInfo: hoverInfo }; @@ -65857,7 +67680,7 @@ function calcFromTrace(trace, layout) { calcdataMock[0].trace = trace; - _$calc_439({ + _$calc_501({ calcdata: [calcdataMock], _fullLayout: layout }); @@ -65886,10 +67709,10 @@ function hoverInfo(calcPoint, trace, hoverPoint) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var __counterRegex_457 = _$regex_554.counter; -var __domainAttrs_457 = _$domain_610.attributes; -var cartesianIdRegex = _$constants_589.idRegex; +/* removed: var _$lib_601 = require('../../lib'); */; +var __counterRegex_519 = _$regex_617.counter; +var __domainAttrs_519 = _$domain_672.attributes; +var cartesianIdRegex = _$constants_652.idRegex; var gridAttrs = { rows: { @@ -65932,7 +67755,7 @@ var gridAttrs = { valType: 'info_array', freeLength: true, dimensions: 2, - items: {valType: 'enumerated', values: [__counterRegex_457('xy').toString(), ''], editType: 'plot'}, + items: {valType: 'enumerated', values: [__counterRegex_519('xy').toString(), ''], editType: 'plot'}, role: 'info', editType: 'plot', description: [ @@ -66010,7 +67833,7 @@ var gridAttrs = { 'for coupled-axes grids and 0.3 for independent grids.' ].join(' ') }, - domain: __domainAttrs_457({name: 'grid', editType: 'plot', noGridCell: true}, { + domain: __domainAttrs_519({name: 'grid', editType: 'plot', noGridCell: true}, { description: [ 'The first and last cells end exactly at the domain', 'edges, with no grout around the edges.' @@ -66021,7 +67844,7 @@ var gridAttrs = { values: ['bottom', 'bottom plot', 'top plot', 'top'], dflt: 'bottom plot', role: 'info', - editType: 'ticks', + editType: 'plot', description: [ 'Sets where the x axis labels and titles go. *bottom* means', 'the very bottom of the grid. *bottom plot* is the lowest plot', @@ -66033,7 +67856,7 @@ var gridAttrs = { values: ['left', 'left plot', 'right plot', 'right'], dflt: 'left plot', role: 'info', - editType: 'ticks', + editType: 'plot', description: [ 'Sets where the y axis labels and titles go. *left* means', 'the very left edge of the grid. *left plot* is the leftmost plot', @@ -66043,15 +67866,30 @@ var gridAttrs = { 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; - if(!gridIn) return; + 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(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + var hasXaxes = Array.isArray(xAxes); + var hasYaxes = Array.isArray(yAxes); + var isSplomGenerated = ( + hasXaxes && xAxes !== gridIn.xaxes && + hasYaxes && yAxes !== gridIn.yaxes + ); var dfltRows, dfltColumns; @@ -66060,14 +67898,14 @@ function sizeDefaults(layoutIn, layoutOut) { dfltColumns = gridIn.subplots[0].length; } else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } var gridOut = layoutOut.grid = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + return _$lib_601.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } var rows = coerce('rows', dfltRows); @@ -66084,17 +67922,26 @@ function sizeDefaults(layoutIn, layoutOut) { 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) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } + gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) + 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, len, reversed) { +function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) { var dirGap = coerce(axLetter + 'gap', dfltGap); var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + coerce(axLetter + 'side', dfltSide); var out = new Array(len); var start = domain[0]; @@ -66114,7 +67961,7 @@ function contentDefaults(layoutIn, layoutOut) { // make sure we got to the end of handleGridSizing if(!gridOut || !gridOut._domains) return; - var gridIn = layoutIn.grid; + var gridIn = layoutIn.grid || {}; var subplots = layoutOut._subplots; var hasSubplotGrid = gridOut._hasSubplotGrid; var rows = gridOut.rows; @@ -66160,8 +68007,10 @@ function contentDefaults(layoutIn, layoutOut) { } } else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); + 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 = {}; @@ -66275,7 +68124,7 @@ function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { return out; } -var _$grid_457 = { +var _$grid_519 = { moduleType: 'component', name: 'grid', @@ -66298,10 +68147,10 @@ var _$grid_457 = { 'use strict'; -/* removed: var _$constants_589 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_652 = require('../../plots/cartesian/constants'); */; -var _$attributes_458 = { +var _$attributes_520 = { _isLinkedToArray: 'image', visible: { @@ -66434,7 +68283,7 @@ var _$attributes_458 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.x.toString() + _$constants_652.idRegex.x.toString() ], dflt: 'paper', role: 'info', @@ -66453,7 +68302,7 @@ var _$attributes_458 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.y.toString() ], dflt: 'paper', role: 'info', @@ -66481,8 +68330,8 @@ var _$attributes_458 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_564 = require('../../lib/to_log_range'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_627 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -66502,7 +68351,7 @@ var _$attributes_458 = { * Use this to make the changes as it's aware if any other changes in the * same relayout call should override this conversion. */ -var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { +var _$convertCoords_521 = function convertCoords(gd, ax, newType, doExtra) { ax = ax || {}; var toLog = (newType === 'log') && (ax.type === 'linear'), @@ -66526,7 +68375,7 @@ var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { newSize = null; if(toLog) { - newPos = _$toLogRange_564(currentPos, ax.range); + newPos = _$toLogRange_627(currentPos, ax.range); // this is the inverse of the conversion we do in fromLog below // so that the conversion is reversible (notice the fromLog conversion @@ -66540,11 +68389,11 @@ var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { } // if conversion failed, delete the value so it can get a default later on - if(!_$fastIsnumeric_139(newPos)) { + if(!_$fastIsnumeric_196(newPos)) { newPos = null; newSize = null; } - else if(!_$fastIsnumeric_139(newSize)) newSize = null; + else if(!_$fastIsnumeric_196(newSize)) newSize = null; doExtra(attrPrefix + axLetter, newPos); doExtra(attrPrefix + 'size' + axLetter, newSize); @@ -66562,27 +68411,27 @@ var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_458 = require('./attributes'); */; +/* removed: var _$attributes_520 = require('./attributes'); */; var name = 'images'; -var _$supplyLayoutDefaults_460 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_522 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { name: name, handleItemDefaults: imageDefaults }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; function imageDefaults(imageIn, imageOut, fullLayout) { function coerce(attr, dflt) { - return _$lib_539.coerce(imageIn, imageOut, _$attributes_458, attr, dflt); + return _$lib_601.coerce(imageIn, imageOut, _$attributes_520, attr, dflt); } var source = coerce('source'); @@ -66604,9 +68453,9 @@ function imageDefaults(imageIn, imageOut, fullLayout) { for(var i = 0; i < 2; i++) { // 'paper' is the fallback axref var axLetter = axLetters[i], - axRef = _$axes_584.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + axRef = _$axes_647.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - _$axes_584.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + _$axes_647.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); } return imageOut; @@ -66622,12 +68471,12 @@ function imageDefaults(imageIn, imageOut, fullLayout) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; -var _$draw_461 = function draw(gd) { +var _$draw_523 = function draw(gd) { var fullLayout = gd._fullLayout, imageDataAbove = [], imageDataSubplot = {}, @@ -66686,13 +68535,13 @@ var _$draw_461 = function draw(gd) { // Images must be converted to dataURL's for exporting. function setImage(d) { - var thisImage = _$d3_127.select(this); + var thisImage = _$d3_130.select(this); if(this.img && this.img.src === d.source) { return; } - thisImage.attr('xmlns', _$xmlns_namespaces_519.svg); + thisImage.attr('xmlns', _$xmlns_namespaces_580.svg); var imagePromise = new Promise(function(resolve) { @@ -66735,11 +68584,11 @@ var _$draw_461 = function draw(gd) { } function applyAttributes(d) { - var thisImage = _$d3_127.select(this); + var thisImage = _$d3_130.select(this); // Axes if specified - var xa = _$axes_584.getFromId(gd, d.xref), - ya = _$axes_584.getFromId(gd, d.yref); + var xa = _$axes_647.getFromId(gd, d.xref), + ya = _$axes_647.getFromId(gd, d.yref); var size = fullLayout._size, width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, @@ -66782,7 +68631,7 @@ var _$draw_461 = function draw(gd) { yId = ya ? ya._id : '', clipAxes = xId + yId; - thisImage.call(_$drawing_436.setClipUrl, clipAxes ? + thisImage.call(_$drawing_498.setClipUrl, clipAxes ? ('clip' + fullLayout._uid + clipAxes) : null ); @@ -66842,17 +68691,17 @@ var _$draw_461 = function draw(gd) { 'use strict'; -var _$images_462 = { +var _$images_524 = { moduleType: 'component', name: 'images', - layoutAttributes: _$attributes_458, - supplyLayoutDefaults: _$supplyLayoutDefaults_460, - includeBasePlot: _$makeIncludeComponents_594('images'), + layoutAttributes: _$attributes_520, + supplyLayoutDefaults: _$supplyLayoutDefaults_522, + includeBasePlot: _$makeIncludeComponents_657('images'), - draw: _$draw_461, + draw: _$draw_523, - convertCoords: _$convertCoords_459 + convertCoords: _$convertCoords_521 }; /** @@ -66865,11 +68714,11 @@ var _$images_462 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../color/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; -var _$attributes_464 = { +var _$attributes_526 = { bgcolor: { valType: 'color', role: 'style', @@ -66878,7 +68727,7 @@ var _$attributes_464 = { }, bordercolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'legend', description: 'Sets the color of the border enclosing the legend.' @@ -66891,7 +68740,7 @@ var _$attributes_464 = { editType: 'legend', description: 'Sets the width (in px) of the border enclosing the legend.' }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'legend', description: 'Sets the font used to text the legend items.' }), @@ -66980,7 +68829,7 @@ var _$attributes_464 = { editType: 'legend' }; -var _$helpers_470 = {}; +var _$helpers_532 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -66992,7 +68841,7 @@ var _$helpers_470 = {}; 'use strict'; -_$helpers_470.legendGetsTrace = function legendGetsTrace(trace) { +_$helpers_532.legendGetsTrace = function legendGetsTrace(trace) { // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. @@ -67002,15 +68851,15 @@ _$helpers_470.legendGetsTrace = function legendGetsTrace(trace) { return trace.visible && (trace.showlegend !== undefined); }; -_$helpers_470.isGrouped = function isGrouped(legendLayout) { +_$helpers_532.isGrouped = function isGrouped(legendLayout) { return (legendLayout.traceorder || '').indexOf('grouped') !== -1; }; -_$helpers_470.isVertical = function isVertical(legendLayout) { +_$helpers_532.isVertical = function isVertical(legendLayout) { return legendLayout.orientation !== 'h'; }; -_$helpers_470.isReversed = function isReversed(legendLayout) { +_$helpers_532.isReversed = function isReversed(legendLayout) { return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; @@ -67025,15 +68874,15 @@ _$helpers_470.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$attributes_464 = require('./attributes'); */; -/* removed: var _$layout_attributes_638 = require('../../plots/layout_attributes'); */; -/* removed: var _$helpers_470 = require('./helpers'); */; +/* removed: var _$attributes_526 = require('./attributes'); */; +/* removed: var _$layout_attributes_700 = require('../../plots/layout_attributes'); */; +/* removed: var _$helpers_532 = require('./helpers'); */; -var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData) { +var _$legendDefaults_528 = function legendDefaults(layoutIn, layoutOut, fullData) { var containerIn = layoutIn.legend || {}; var containerOut = {}; @@ -67045,30 +68894,30 @@ var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData for(var i = 0; i < fullData.length; i++) { var trace = fullData[i]; - if(_$helpers_470.legendGetsTrace(trace)) { + if(_$helpers_532.legendGetsTrace(trace)) { visibleTraces++; // always show the legend by default if there's a pie - if(_$registry_668.traceIs(trace, 'pie')) visibleTraces++; + if(_$registry_731.traceIs(trace, 'pie')) visibleTraces++; } - if((_$registry_668.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + if((_$registry_731.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { - defaultOrder = _$helpers_470.isGrouped({traceorder: defaultOrder}) ? + defaultOrder = _$helpers_532.isGrouped({traceorder: defaultOrder}) ? 'grouped+reversed' : 'reversed'; } if(trace.legendgroup !== undefined && trace.legendgroup !== '') { - defaultOrder = _$helpers_470.isReversed({traceorder: defaultOrder}) ? + defaultOrder = _$helpers_532.isReversed({traceorder: defaultOrder}) ? 'reversed+grouped' : 'grouped'; } } function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$attributes_464, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$attributes_526, attr, dflt); } - var showLegend = _$lib_539.coerce(layoutIn, layoutOut, - _$layout_attributes_638, 'showlegend', visibleTraces > 1); + var showLegend = _$lib_601.coerce(layoutIn, layoutOut, + _$layout_attributes_700, 'showlegend', visibleTraces > 1); if(showLegend === false) return; @@ -67077,7 +68926,7 @@ var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - _$lib_539.coerceFont(coerce, 'font', layoutOut.font); + _$lib_601.coerceFont(coerce, 'font', layoutOut.font); coerce('orientation'); if(containerOut.orientation === 'h') { @@ -67097,16 +68946,16 @@ var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData } coerce('traceorder', defaultOrder); - if(_$helpers_470.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); + if(_$helpers_532.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); coerce('x', defaultX); coerce('xanchor', defaultXAnchor); coerce('y', defaultY); coerce('yanchor', defaultYAnchor); - _$lib_539.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_601.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -var _$anchor_utils_463 = {}; +var _$anchor_utils_525 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67127,28 +68976,28 @@ var _$anchor_utils_463 = {}; * - values > 2/3 align the right at that fraction. */ -_$anchor_utils_463.isRightAnchor = function isRightAnchor(opts) { +_$anchor_utils_525.isRightAnchor = function isRightAnchor(opts) { return ( opts.xanchor === 'right' || (opts.xanchor === 'auto' && opts.x >= 2 / 3) ); }; -_$anchor_utils_463.isCenterAnchor = function isCenterAnchor(opts) { +_$anchor_utils_525.isCenterAnchor = function isCenterAnchor(opts) { return ( opts.xanchor === 'center' || (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) ); }; -_$anchor_utils_463.isBottomAnchor = function isBottomAnchor(opts) { +_$anchor_utils_525.isBottomAnchor = function isBottomAnchor(opts) { return ( opts.yanchor === 'bottom' || (opts.yanchor === 'auto' && opts.y <= 1 / 3) ); }; -_$anchor_utils_463.isMiddleAnchor = function isMiddleAnchor(opts) { +_$anchor_utils_525.isMiddleAnchor = function isMiddleAnchor(opts) { return ( opts.yanchor === 'middle' || (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) @@ -67165,7 +69014,7 @@ _$anchor_utils_463.isMiddleAnchor = function isMiddleAnchor(opts) { 'use strict'; -var _$constants_465 = { +var _$constants_527 = { scrollBarWidth: 6, scrollBarMinHeight: 20, scrollBarColor: '#808BA4', @@ -67183,11 +69032,11 @@ var _$constants_465 = { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$helpers_470 = require('./helpers'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$helpers_532 = require('./helpers'); */; -var _$getLegendData_468 = function getLegendData(calcdata, opts) { +var _$getLegendData_530 = function getLegendData(calcdata, opts) { var lgroupToTraces = {}, lgroups = [], hasOneNonBlankGroup = false, @@ -67198,7 +69047,7 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { function addOneItem(legendGroup, legendItem) { // each '' legend group is treated as a separate group - if(legendGroup === '' || !_$helpers_470.isGrouped(opts)) { + if(legendGroup === '' || !_$helpers_532.isGrouped(opts)) { var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? lgroups.push(uniqueGroup); @@ -67220,9 +69069,9 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { trace = cd0.trace, lgroup = trace.legendgroup; - if(!_$helpers_470.legendGetsTrace(trace) || !trace.showlegend) continue; + if(!_$helpers_532.legendGetsTrace(trace) || !trace.showlegend) continue; - if(_$registry_668.traceIs(trace, 'pie')) { + if(_$registry_731.traceIs(trace, 'pie')) { if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; for(j = 0; j < cd.length; j++) { @@ -67252,12 +69101,12 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { ltraces, legendData; - if(hasOneNonBlankGroup && _$helpers_470.isGrouped(opts)) { + if(hasOneNonBlankGroup && _$helpers_532.isGrouped(opts)) { legendData = new Array(lgroupsLength); for(i = 0; i < lgroupsLength; i++) { ltraces = lgroupToTraces[lgroups[i]]; - legendData[i] = _$helpers_470.isReversed(opts) ? ltraces.reverse() : ltraces; + legendData[i] = _$helpers_532.isReversed(opts) ? ltraces.reverse() : ltraces; } } else { @@ -67266,7 +69115,7 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { for(i = 0; i < lgroupsLength; i++) { ltraces = lgroupToTraces[lgroups[i]][0]; - legendData[0][_$helpers_470.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; + legendData[0][_$helpers_532.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; } lgroupsLength = 1; } @@ -67286,12 +69135,12 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; var SHOWISOLATETIP = true; -var _$handleClick_469 = function handleClick(g, gd, numClicks) { +var _$handleClick_531 = function handleClick(g, gd, numClicks) { if(gd._dragged || gd._editing) return; var hiddenSlices = gd._fullLayout.hiddenlabels ? @@ -67328,12 +69177,12 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { function setVisibility(fullTrace, visibility) { var fullInput = fullTrace._fullInput; - if(_$registry_668.hasTransform(fullInput, 'groupby')) { + if(_$registry_731.hasTransform(fullInput, 'groupby')) { var kcont = carrs[fullInput.index]; if(!kcont) { - var groupbyIndices = _$registry_668.getTransformIndices(fullInput, 'groupby'); + var groupbyIndices = _$registry_731.getTransformIndices(fullInput, 'groupby'); var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_539.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + kcont = _$lib_601.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); carrs[fullInput.index] = kcont; } @@ -67364,13 +69213,13 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { } if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_539.notifier(_$lib_539._(gd, 'Double-click on legend to isolate one trace'), 'long'); + _$lib_601.notifier(_$lib_601._(gd, 'Double-click on legend to isolate one trace'), 'long'); SHOWISOLATETIP = false; } else { SHOWISOLATETIP = false; } - if(_$registry_668.traceIs(fullTrace, 'pie')) { + if(_$registry_731.traceIs(fullTrace, 'pie')) { var thisLabel = legendItem.label, thisLabelIndex = hiddenSlices.indexOf(thisLabel); @@ -67389,7 +69238,7 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { } } - _$registry_668.call('relayout', gd, 'hiddenlabels', hiddenSlices); + _$registry_731.call('relayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; @@ -67439,7 +69288,7 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - if(!isInGroup && fullData[i].visible === true && !_$registry_668.traceIs(fullData[i], 'notLegendIsolatable')) { + if(!isInGroup && fullData[i].visible === true && !_$registry_731.traceIs(fullData[i], 'notLegendIsolatable')) { isIsolated = false; break; } @@ -67449,7 +69298,7 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { // False is sticky; we don't change it. if(fullData[i].visible === false) continue; - if(_$registry_668.traceIs(fullData[i], 'notLegendIsolatable')) { + if(_$registry_731.traceIs(fullData[i], 'notLegendIsolatable')) { continue; } @@ -67495,11 +69344,11 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { } } - _$registry_668.call('restyle', gd, attrUpdate, attrIndices); + _$registry_731.call('restyle', gd, attrUpdate, attrIndices); } }; -var _$helpers_842 = {}; +var _$helpers_907 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -67510,25 +69359,25 @@ var _$helpers_842 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -_$helpers_842.formatPiePercent = function formatPiePercent(v, separators) { +_$helpers_907.formatPiePercent = function formatPiePercent(v, separators) { var vRounded = (v * 100).toPrecision(3); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_539.numSeparate(vRounded, separators) + '%'; + return _$lib_601.numSeparate(vRounded, separators) + '%'; }; -_$helpers_842.formatPieValue = function formatPieValue(v, separators) { +_$helpers_907.formatPieValue = function formatPieValue(v, separators) { var vRounded = v.toPrecision(10); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_539.numSeparate(vRounded, separators); + return _$lib_601.numSeparate(vRounded, separators); }; -_$helpers_842.getFirstFilled = function getFirstFilled(array, indices) { +_$helpers_907.getFirstFilled = function getFirstFilled(array, indices) { if(!Array.isArray(array)) return; for(var i = 0; i < indices.length; i++) { var v = array[indices[i]]; @@ -67536,8 +69385,8 @@ _$helpers_842.getFirstFilled = function getFirstFilled(array, indices) { } }; -_$helpers_842.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_842.getFirstFilled(item, indices); +_$helpers_907.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_907.getFirstFilled(item, indices); else if(item) return item; }; @@ -67551,17 +69400,17 @@ _$helpers_842.castOption = function castOption(item, indices) { 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -var castOption = _$helpers_842.castOption; +/* removed: var _$color_473 = require('../../components/color'); */; +var castOption = _$helpers_907.castOption; -var _$styleOne_848 = function styleOne(s, pt, trace) { +var _$styleOne_913 = function styleOne(s, pt, trace) { var line = trace.marker.line; - var lineColor = castOption(line.color, pt.pts) || _$color_411.defaultLine; + var lineColor = castOption(line.color, pt.pts) || _$color_473.defaultLine; var lineWidth = castOption(line.width, pt.pts) || 0; s.style({'stroke-width': lineWidth}) - .call(_$color_411.fill, pt.color) - .call(_$color_411.stroke, lineColor); + .call(_$color_473.fill, pt.color) + .call(_$color_473.stroke, lineColor); }; /** @@ -67572,28 +69421,23 @@ var _$styleOne_848 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; - -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_848 = require('../../traces/pie/style_one'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_913 = require('../../traces/pie/style_one'); */; -var _$style_472 = function style(s, gd) { +var _$style_534 = function style(s, gd) { s.each(function(d) { - var traceGroup = _$d3_127.select(this); + var traceGroup = _$d3_130.select(this); - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); + var layers = _$lib_601.ensureSingle(traceGroup, 'g', 'layers'); layers.style('opacity', d[0].trace.opacity); var fill = layers @@ -67623,12 +69467,14 @@ var _$style_472 = function style(s, gd) { .each(styleBoxes) .each(stylePies) .each(styleLines) - .each(stylePoints); + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); function styleLines(d) { var trace = d[0].trace; var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_884.hasLines(trace); + var showLine = _$subtypes_949.hasLines(trace); var contours = trace.contours; if(contours && contours.type === 'constraint') { @@ -67636,27 +69482,27 @@ var _$style_472 = function style(s, gd) { showFill = contours._operation !== '='; } - var fill = _$d3_127.select(this).select('.legendfill').selectAll('path') + var fill = _$d3_130.select(this).select('.legendfill').selectAll('path') .data(showFill ? [d] : []); fill.enter().append('path').classed('js-fill', true); fill.exit().remove(); fill.attr('d', 'M5,0h30v6h-30z') - .call(_$drawing_436.fillGroupStyle); + .call(_$drawing_498.fillGroupStyle); - var line = _$d3_127.select(this).select('.legendlines').selectAll('path') + var line = _$d3_130.select(this).select('.legendlines').selectAll('path') .data(showLine ? [d] : []); line.enter().append('path').classed('js-line', true) .attr('d', 'M5,0h30'); line.exit().remove(); - line.call(_$drawing_436.lineGroupStyle); + line.call(_$drawing_498.lineGroupStyle); } function stylePoints(d) { var d0 = d[0], trace = d0.trace, - showMarkers = _$subtypes_884.hasMarkers(trace), - showText = _$subtypes_884.hasText(trace), - showLines = _$subtypes_884.hasLines(trace); + showMarkers = _$subtypes_949.hasMarkers(trace), + showText = _$subtypes_949.hasText(trace), + showLines = _$subtypes_949.hasLines(trace); var dMod, tMod; @@ -67664,7 +69510,7 @@ var _$style_472 = function style(s, gd) { // use d0.trace to infer arrayOk attributes function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_539.nestedProperty(trace, attrIn).get(), + var valIn = _$lib_601.nestedProperty(trace, attrIn).get(), valToBound = (Array.isArray(valIn) && arrayToValFn) ? arrayToValFn(valIn) : valIn; @@ -67684,10 +69530,10 @@ var _$style_472 = function style(s, gd) { if(showMarkers) { dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_539.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_539.mean, [2, 16]); + dEdit.mo = boundVal('marker.opacity', _$lib_601.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_601.mean, [2, 16]); dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_539.mean, [0, 5]); + dEdit.mlw = boundVal('marker.line.width', _$lib_601.mean, [0, 5]); tEdit.marker = { sizeref: 1, sizemin: 1, @@ -67709,18 +69555,18 @@ var _$style_472 = function style(s, gd) { dEdit.tf = boundVal('textfont.family', pickFirst); } - dMod = [_$lib_539.minExtend(d0, dEdit)]; - tMod = _$lib_539.minExtend(trace, tEdit); + dMod = [_$lib_601.minExtend(d0, dEdit)]; + tMod = _$lib_601.minExtend(trace, tEdit); } - var ptgroup = _$d3_127.select(this).select('g.legendpoints'); + var ptgroup = _$d3_130.select(this).select('g.legendpoints'); var pts = ptgroup.selectAll('path.scatterpts') .data(showMarkers ? dMod : []); pts.enter().append('path').classed('scatterpts', true) .attr('transform', 'translate(20,0)'); pts.exit().remove(); - pts.call(_$drawing_436.pointStyle, tMod, gd); + pts.call(_$drawing_498.pointStyle, tMod, gd); // 'mrc' is set in pointStyle and used in textPointStyle: // constrain it here @@ -67732,39 +69578,39 @@ var _$style_472 = function style(s, gd) { .append('g').classed('pointtext', true) .append('text').attr('transform', 'translate(20,0)'); txt.exit().remove(); - txt.selectAll('text').call(_$drawing_436.textPointStyle, tMod, gd); + txt.selectAll('text').call(_$drawing_498.textPointStyle, tMod, gd); } function styleBars(d) { var trace = d[0].trace, marker = trace.marker || {}, markerLine = marker.line || {}, - barpath = _$d3_127.select(this).select('g.legendpoints') + barpath = _$d3_130.select(this).select('g.legendpoints') .selectAll('path.legendbar') - .data(_$registry_668.traceIs(trace, 'bar') ? [d] : []); + .data(_$registry_731.traceIs(trace, 'bar') ? [d] : []); barpath.enter().append('path').classed('legendbar', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); barpath.exit().remove(); barpath.each(function(d) { - var p = _$d3_127.select(this), + var p = _$d3_130.select(this), d0 = d[0], w = (d0.mlw + 1 || markerLine.width + 1) - 1; p.style('stroke-width', w + 'px') - .call(_$color_411.fill, d0.mc || marker.color); + .call(_$color_473.fill, d0.mc || marker.color); if(w) { - p.call(_$color_411.stroke, d0.mlc || markerLine.color); + p.call(_$color_473.stroke, d0.mlc || markerLine.color); } }); } function styleBoxes(d) { var trace = d[0].trace, - pts = _$d3_127.select(this).select('g.legendpoints') + pts = _$d3_130.select(this).select('g.legendpoints') .selectAll('path.legendbox') - .data(_$registry_668.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + .data(_$registry_731.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendbox', true) // if we want the median bar, prepend M6,0H-6 .attr('d', 'M6,6H-6V-6H6Z') @@ -67772,28 +69618,82 @@ var _$style_472 = function style(s, gd) { pts.exit().remove(); pts.each(function() { var w = trace.line.width, - p = _$d3_127.select(this); + p = _$d3_130.select(this); p.style('stroke-width', w + 'px') - .call(_$color_411.fill, trace.fillcolor); + .call(_$color_473.fill, trace.fillcolor); if(w) { - p.call(_$color_411.stroke, trace.line.color); + _$color_473.stroke(p, trace.line.color); + } + }); + } + + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_130.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_130.select(this); + + p.style('stroke-width', w + 'px') + .call(_$color_473.fill, container.fillcolor); + + if(w) { + _$color_473.stroke(p, container.line.color); + } + }); + } + + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_130.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_130.select(this); + + p.style('fill', 'none') + .call(_$drawing_498.dashLine, container.line.dash, w); + + if(w) { + _$color_473.stroke(p, container.line.color); } }); } function stylePies(d) { var trace = d[0].trace, - pts = _$d3_127.select(this).select('g.legendpoints') + pts = _$d3_130.select(this).select('g.legendpoints') .selectAll('path.legendpie') - .data(_$registry_668.traceIs(trace, 'pie') && trace.visible ? [d] : []); + .data(_$registry_731.traceIs(trace, 'pie') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendpie', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); pts.exit().remove(); - if(pts.size()) pts.call(_$styleOne_848, d[0], trace); + if(pts.size()) pts.call(_$styleOne_913, d[0], trace); } }; @@ -67807,32 +69707,32 @@ var _$style_472 = function style(s, gd) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$handleClick_469 = require('./handle_click'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$handleClick_531 = require('./handle_click'); */; -/* removed: var _$constants_465 = require('./constants'); */; -/* removed: var _$interactions_516 = require('../../constants/interactions'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_467 = _$alignment_511.LINE_SPACING; -var FROM_TL = _$alignment_511.FROM_TL; -var FROM_BR = _$alignment_511.FROM_BR; +/* removed: var _$constants_527 = require('./constants'); */; +/* removed: var _$interactions_577 = require('../../constants/interactions'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_529 = _$alignment_573.LINE_SPACING; +var __FROM_TL_529 = _$alignment_573.FROM_TL; +var FROM_BR = _$alignment_573.FROM_BR; -/* removed: var _$getLegendData_468 = require('./get_legend_data'); */; -/* removed: var _$style_472 = require('./style'); */; -/* removed: var _$helpers_470 = require('./helpers'); */; -/* removed: var _$anchor_utils_463 = require('./anchor_utils'); */; +/* removed: var _$getLegendData_530 = require('./get_legend_data'); */; +/* removed: var _$style_534 = require('./style'); */; +/* removed: var _$helpers_532 = require('./helpers'); */; +/* removed: var _$anchor_utils_525 = require('./anchor_utils'); */; -var DBLCLICKDELAY = _$interactions_516.DBLCLICKDELAY; +var DBLCLICKDELAY = _$interactions_577.DBLCLICKDELAY; -var _$draw_467 = function draw(gd) { +var _$draw_529 = function draw(gd) { var fullLayout = gd._fullLayout; var clipId = 'legend' + fullLayout._uid; @@ -67841,63 +69741,46 @@ var _$draw_467 = function draw(gd) { if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; var opts = fullLayout.legend, - legendData = fullLayout.showlegend && _$getLegendData_468(gd.calcdata, opts), + legendData = fullLayout.showlegend && _$getLegendData_530(gd.calcdata, opts), hiddenSlices = fullLayout.hiddenlabels || []; if(!fullLayout.showlegend || !legendData.length) { fullLayout._infolayer.selectAll('.legend').remove(); fullLayout._topdefs.select('#' + clipId).remove(); - _$plots_647.autoMargin(gd, 'legend'); + _$plots_709.autoMargin(gd, 'legend'); return; } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); - - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); - - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var firstRender = false; + var legend = _$lib_601.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - var bg = legend.selectAll('rect.bg') - .data([0]); + var clipPath = _$lib_601.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' + var bg = _$lib_601.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); }); - bg.call(_$color_411.stroke, opts.bordercolor) - .call(_$color_411.fill, opts.bgcolor) + bg.call(_$color_473.stroke, opts.bordercolor) + .call(_$color_473.fill, opts.bgcolor) .style('stroke-width', opts.borderwidth + 'px'); - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); - - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); - - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); + var scrollBox = _$lib_601.ensureSingle(legend, 'g', 'scrollbox'); - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', + var scrollBar = _$lib_601.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ rx: 20, ry: 3, width: 0, height: 0 }) - .call(_$color_411.fill, '#808BA4'); + .call(_$color_473.fill, '#808BA4'); + }); var groups = scrollBox.selectAll('g.groups') .data(legendData); @@ -67908,27 +69791,26 @@ var _$draw_467 = function draw(gd) { groups.exit().remove(); var traces = groups.selectAll('g.traces') - .data(_$lib_539.identity); + .data(_$lib_601.identity); traces.enter().append('g').attr('class', 'traces'); traces.exit().remove(); - traces.call(_$style_472, gd) + traces.call(_$style_534, gd) .style('opacity', function(d) { var trace = d[0].trace; - if(_$registry_668.traceIs(trace, 'pie')) { + if(_$registry_731.traceIs(trace, 'pie')) { return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; } else { return trace.visible === 'legendonly' ? 0.5 : 1; } }) .each(function() { - _$d3_127.select(this) + _$d3_130.select(this) .call(drawTexts, gd) .call(setupTraceToggle, gd); }); - var firstRender = legend.enter().size() !== 0; if(firstRender) { computeLegendDimensions(gd, groups, traces); expandMargin(gd); @@ -67957,17 +69839,17 @@ var _$draw_467 = function draw(gd) { lx = gs.l + gs.w * opts.x, ly = gs.t + gs.h * (1 - opts.y); - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { lx -= opts._width; } - else if(_$anchor_utils_463.isCenterAnchor(opts)) { + else if(_$anchor_utils_525.isCenterAnchor(opts)) { lx -= opts._width / 2; } - if(_$anchor_utils_463.isBottomAnchor(opts)) { + if(_$anchor_utils_525.isBottomAnchor(opts)) { ly -= opts._height; } - else if(_$anchor_utils_463.isMiddleAnchor(opts)) { + else if(_$anchor_utils_525.isMiddleAnchor(opts)) { ly -= opts._height / 2; } @@ -68003,7 +69885,7 @@ var _$draw_467 = function draw(gd) { // Set size and position of all the elements that make up a legend: // legend, background and border, scroll box and scroll bar - _$drawing_436.setTranslate(legend, lx, ly); + _$drawing_498.setTranslate(legend, lx, ly); // to be safe, remove previous listeners scrollBar.on('.drag', null); @@ -68018,7 +69900,7 @@ var _$draw_467 = function draw(gd) { y: opts.borderwidth / 2 }); - _$drawing_436.setTranslate(scrollBox, 0, 0); + _$drawing_498.setTranslate(scrollBox, 0, 0); clipPath.select('rect').attr({ width: legendWidth - 2 * opts.borderwidth, @@ -68027,17 +69909,17 @@ var _$draw_467 = function draw(gd) { y: opts.borderwidth }); - _$drawing_436.setClipUrl(scrollBox, clipId); + _$drawing_498.setClipUrl(scrollBox, clipId); - _$drawing_436.setRect(scrollBar, 0, 0, 0, 0); + _$drawing_498.setRect(scrollBar, 0, 0, 0, 0); delete opts._scrollY; } else { - var scrollBarHeight = Math.max(_$constants_465.scrollBarMinHeight, + var scrollBarHeight = Math.max(_$constants_527.scrollBarMinHeight, legendHeight * legendHeight / opts._height); var scrollBarYMax = legendHeight - scrollBarHeight - - 2 * _$constants_465.scrollBarMargin; + 2 * _$constants_527.scrollBarMargin; var scrollBoxYMax = opts._height - legendHeight; var scrollRatio = scrollBarYMax / scrollBoxYMax; @@ -68048,8 +69930,8 @@ var _$draw_467 = function draw(gd) { bg.attr({ width: legendWidth - 2 * opts.borderwidth + - _$constants_465.scrollBarWidth + - _$constants_465.scrollBarMargin, + _$constants_527.scrollBarWidth + + _$constants_527.scrollBarMargin, height: legendHeight - opts.borderwidth, x: opts.borderwidth / 2, y: opts.borderwidth / 2 @@ -68058,40 +69940,40 @@ var _$draw_467 = function draw(gd) { clipPath.select('rect').attr({ width: legendWidth - 2 * opts.borderwidth + - _$constants_465.scrollBarWidth + - _$constants_465.scrollBarMargin, + _$constants_527.scrollBarWidth + + _$constants_527.scrollBarMargin, height: legendHeight - 2 * opts.borderwidth, x: opts.borderwidth, y: opts.borderwidth + scrollBoxY }); - _$drawing_436.setClipUrl(scrollBox, clipId); + _$drawing_498.setClipUrl(scrollBox, clipId); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); legend.on('wheel', function() { - scrollBoxY = _$lib_539.constrain( + scrollBoxY = _$lib_601.constrain( opts._scrollY + - _$d3_127.event.deltaY / scrollBarYMax * scrollBoxYMax, + _$d3_130.event.deltaY / scrollBarYMax * scrollBoxYMax, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - _$d3_127.event.preventDefault(); + _$d3_130.event.preventDefault(); } }); var eventY0, scrollBoxY0; - var drag = _$d3_127.behavior.drag() + var drag = _$d3_130.behavior.drag() .on('dragstart', function() { - eventY0 = _$d3_127.event.sourceEvent.clientY; + eventY0 = _$d3_130.event.sourceEvent.clientY; scrollBoxY0 = scrollBoxY; }) .on('drag', function() { - var e = _$d3_127.event.sourceEvent; + var e = _$d3_130.event.sourceEvent; if(e.buttons === 2 || e.ctrlKey) return; - scrollBoxY = _$lib_539.constrain( + scrollBoxY = _$lib_601.constrain( (e.clientY - eventY0) / scrollRatio + scrollBoxY0, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); @@ -68103,13 +69985,13 @@ var _$draw_467 = function draw(gd) { function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; - _$drawing_436.setTranslate(scrollBox, 0, -scrollBoxY); + _$drawing_498.setTranslate(scrollBox, 0, -scrollBoxY); - _$drawing_436.setRect( + _$drawing_498.setRect( scrollBar, legendWidth, - _$constants_465.scrollBarMargin + scrollBoxY * scrollRatio, - _$constants_465.scrollBarWidth, + _$constants_527.scrollBarMargin + scrollBoxY * scrollRatio, + _$constants_527.scrollBarWidth, scrollBarHeight ); clipPath.select('rect').attr({ @@ -68122,11 +70004,11 @@ var _$draw_467 = function draw(gd) { legend.classed('cursor-move', true); - _$dragelement_433.init({ + _$dragelement_495.init({ element: legend.node(), gd: gd, prepFn: function() { - var transform = _$drawing_436.getTranslate(legend); + var transform = _$drawing_498.getTranslate(legend); x0 = transform.x; y0 = transform.y; @@ -68135,14 +70017,14 @@ var _$draw_467 = function draw(gd) { var newX = x0 + dx, newY = y0 + dy; - _$drawing_436.setTranslate(legend, newX, newY); + _$drawing_498.setTranslate(legend, newX, newY); - xf = _$dragelement_433.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); - yf = _$dragelement_433.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); + xf = _$dragelement_495.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); + yf = _$dragelement_495.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); }, doneFn: function() { if(xf !== undefined && yf !== undefined) { - _$registry_668.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + _$registry_731.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); } }, clickFn: function(numClicks, e) { @@ -68155,13 +70037,13 @@ var _$draw_467 = function draw(gd) { if(clickedTrace.size() > 0) { if(numClicks === 1) { legend._clickTimeout = setTimeout(function() { - _$handleClick_469(clickedTrace, gd, numClicks); + _$handleClick_531(clickedTrace, gd, numClicks); }, DBLCLICKDELAY); } else if(numClicks === 2) { if(legend._clickTimeout) { clearTimeout(legend._clickTimeout); } - _$handleClick_469(clickedTrace, gd, numClicks); + _$handleClick_531(clickedTrace, gd, numClicks); } } } @@ -68173,28 +70055,25 @@ function drawTexts(g, gd) { var legendItem = g.data()[0][0], fullLayout = gd._fullLayout, trace = legendItem.trace, - isPie = _$registry_668.traceIs(trace, 'pie'), + isPie = _$registry_731.traceIs(trace, 'pie'), traceIndex = trace.index, name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); + var text = _$lib_601.ensureSingle(g, 'text', 'legendtext'); text.attr('text-anchor', 'start') .classed('user-select-none', true) - .call(_$drawing_436.font, fullLayout.legend.font) + .call(_$drawing_498.font, fullLayout.legend.font) .text(name); function textLayout(s) { - _$svg_text_utils_562.convertToTspans(s, gd, function() { + _$svg_text_utils_625.convertToTspans(s, gd, function() { computeTextDimensions(g, gd); }); } if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_562.makeEditable, {gd: gd}) + text.call(_$svg_text_utils_625.makeEditable, {gd: gd}) .call(textLayout) .on('edit', function(text) { this.text(text) @@ -68204,24 +70083,14 @@ function drawTexts(g, gd) { if(!this.text()) text = ' \u0020\u0020 '; - var transforms, direction; var fullInput = legendItem.trace._fullInput || {}; var update = {}; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_668.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_668.getTransformIndices(fullInput, 'groupby'); + if(_$registry_731.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_731.getTransformIndices(fullInput, 'groupby'); var index = groupbyIndices[groupbyIndices.length - 1]; - var kcont = _$lib_539.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + var kcont = _$lib_601.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); if(origText === '') { kcont.remove(legendItem.trace._group); @@ -68234,7 +70103,7 @@ function drawTexts(g, gd) { update.name = text; } - return _$registry_668.call('restyle', gd, update, traceIndex); + return _$registry_731.call('restyle', gd, update, traceIndex); }); } else { textLayout(text); @@ -68245,15 +70114,11 @@ function setupTraceToggle(g, gd) { var newMouseDownTime, numClicks = 1; - var traceToggle = g.selectAll('rect') - .data([0]); - - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_411.fill, 'rgba(0,0,0,0)'); - + var traceToggle = _$lib_601.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_473.fill, 'rgba(0,0,0,0)'); + }); traceToggle.on('mousedown', function() { newMouseDownTime = (new Date()).getTime(); @@ -68276,13 +70141,13 @@ function setupTraceToggle(g, gd) { } if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { _$handleClick_469(g, gd, numClicks); }, DBLCLICKDELAY); + legend._clickTimeout = setTimeout(function() { _$handleClick_531(g, gd, numClicks); }, DBLCLICKDELAY); } else if(numClicks === 2) { if(legend._clickTimeout) { clearTimeout(legend._clickTimeout); } gd._legendMouseDownTime = 0; - _$handleClick_469(g, gd, numClicks); + _$handleClick_531(g, gd, numClicks); } }); } @@ -68298,31 +70163,31 @@ function computeTextDimensions(g, gd) { var mathjaxGroup = g.select('g[class*=math-group]'); var mathjaxNode = mathjaxGroup.node(); var opts = gd._fullLayout.legend; - var lineHeight = opts.font.size * __LINE_SPACING_467; + var lineHeight = opts.font.size * __LINE_SPACING_529; var height, width; if(mathjaxNode) { - var mathjaxBB = _$drawing_436.bBox(mathjaxNode); + var mathjaxBB = _$drawing_498.bBox(mathjaxNode); height = mathjaxBB.height; width = mathjaxBB.width; - _$drawing_436.setTranslate(mathjaxGroup, 0, (height / 4)); + _$drawing_498.setTranslate(mathjaxGroup, 0, (height / 4)); } else { var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_562.lineCount(text); + var textLines = _$svg_text_utils_625.lineCount(text); var textNode = text.node(); height = lineHeight * textLines; - width = textNode ? _$drawing_436.bBox(textNode).width : 0; + width = textNode ? _$drawing_498.bBox(textNode).width : 0; // approximation to height offset to center the font // to avoid getBoundingClientRect var textY = lineHeight * (0.3 + (1 - textLines) / 2); // TODO: this 40 should go in a constants file (along with other // values related to the legend symbol size) - _$svg_text_utils_562.positionText(text, 40, textY); + _$svg_text_utils_625.positionText(text, 40, textY); } height = Math.max(height, 16) + 3; @@ -68335,17 +70200,17 @@ function computeLegendDimensions(gd, groups, traces) { var fullLayout = gd._fullLayout; var opts = fullLayout.legend; var borderwidth = opts.borderwidth; - var isGrouped = _$helpers_470.isGrouped(opts); + var isGrouped = _$helpers_532.isGrouped(opts); var extraWidth = 0; opts._width = 0; opts._height = 0; - if(_$helpers_470.isVertical(opts)) { + if(_$helpers_532.isVertical(opts)) { if(isGrouped) { groups.each(function(d, i) { - _$drawing_436.setTranslate(this, 0, i * opts.tracegroupgap); + _$drawing_498.setTranslate(this, 0, i * opts.tracegroupgap); }); } @@ -68354,7 +70219,7 @@ function computeLegendDimensions(gd, groups, traces) { textHeight = legendItem.height, textWidth = legendItem.width; - _$drawing_436.setTranslate(this, + _$drawing_498.setTranslate(this, borderwidth, (5 + borderwidth + opts._height + textHeight / 2)); @@ -68388,11 +70253,11 @@ function computeLegendDimensions(gd, groups, traces) { } groups.each(function(d, i) { - _$drawing_436.setTranslate(this, groupXOffsets[i], 0); + _$drawing_498.setTranslate(this, groupXOffsets[i], 0); }); groups.each(function() { - var group = _$d3_127.select(this), + var group = _$d3_130.select(this), groupTraces = group.selectAll('g.traces'), groupHeight = 0; @@ -68400,7 +70265,7 @@ function computeLegendDimensions(gd, groups, traces) { var legendItem = d[0], textHeight = legendItem.height; - _$drawing_436.setTranslate(this, + _$drawing_498.setTranslate(this, 0, (5 + borderwidth + groupHeight + textHeight / 2)); @@ -68442,7 +70307,7 @@ function computeLegendDimensions(gd, groups, traces) { maxTraceHeight = 0; } - _$drawing_436.setTranslate(this, + _$drawing_498.setTranslate(this, (borderwidth + offsetX), (5 + borderwidth + legendItem.height / 2) + rowHeight); @@ -68465,9 +70330,9 @@ function computeLegendDimensions(gd, groups, traces) { traces.each(function(d) { var legendItem = d[0], - bg = _$d3_127.select(this).select('.legendtoggle'); + bg = _$d3_130.select(this).select('.legendtoggle'); - _$drawing_436.setRect(bg, + _$drawing_498.setRect(bg, 0, -legendItem.height / 2, (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, @@ -68481,29 +70346,29 @@ function expandMargin(gd) { opts = fullLayout.legend; var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { xanchor = 'right'; } - else if(_$anchor_utils_463.isCenterAnchor(opts)) { + else if(_$anchor_utils_525.isCenterAnchor(opts)) { xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(opts)) { + if(_$anchor_utils_525.isBottomAnchor(opts)) { yanchor = 'bottom'; } - else if(_$anchor_utils_463.isMiddleAnchor(opts)) { + else if(_$anchor_utils_525.isMiddleAnchor(opts)) { yanchor = 'middle'; } // lastly check if the margin auto-expand has changed - _$plots_647.autoMargin(gd, 'legend', { + _$plots_709.autoMargin(gd, 'legend', { x: opts.x, y: opts.y, - l: opts._width * (FROM_TL[xanchor]), + l: opts._width * (__FROM_TL_529[xanchor]), r: opts._width * (FROM_BR[xanchor]), b: opts._height * (FROM_BR[yanchor]), - t: opts._height * (FROM_TL[yanchor]) + t: opts._height * (__FROM_TL_529[yanchor]) }); } @@ -68512,18 +70377,18 @@ function expandHorizontalMargin(gd) { opts = fullLayout.legend; var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { xanchor = 'right'; } - else if(_$anchor_utils_463.isCenterAnchor(opts)) { + else if(_$anchor_utils_525.isCenterAnchor(opts)) { xanchor = 'center'; } // lastly check if the margin auto-expand has changed - _$plots_647.autoMargin(gd, 'legend', { + _$plots_709.autoMargin(gd, 'legend', { x: opts.x, y: 0.5, - l: opts._width * (FROM_TL[xanchor]), + l: opts._width * (__FROM_TL_529[xanchor]), r: opts._width * (FROM_BR[xanchor]), b: 0, t: 0 @@ -68542,15 +70407,15 @@ function expandHorizontalMargin(gd) { 'use strict'; -var _$legend_471 = { +var _$legend_533 = { moduleType: 'component', name: 'legend', - layoutAttributes: _$attributes_464, - supplyLayoutDefaults: _$legendDefaults_466, + layoutAttributes: _$attributes_526, + supplyLayoutDefaults: _$legendDefaults_528, - draw: _$draw_467, - style: _$style_472 + draw: _$draw_529, + style: _$style_534 }; /** @@ -68564,7 +70429,7 @@ var _$legend_471 = { 'use strict'; -var _$button_attributes_478 = { +var _$button_attributes_540 = { step: { valType: 'enumerated', role: 'info', @@ -68625,12 +70490,12 @@ var _$button_attributes_478 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../color/attributes'); */; -var __extendFlat_477 = _$extend_528.extendFlat; -/* removed: var _$button_attributes_478 = require('./button_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; +var __extendFlat_539 = _$extend_590.extendFlat; +/* removed: var _$button_attributes_540 = require('./button_attributes'); */; -_$button_attributes_478 = __extendFlat_477(_$button_attributes_478, { +_$button_attributes_540 = __extendFlat_539(_$button_attributes_540, { _isLinkedToArray: 'button', description: [ @@ -68639,7 +70504,7 @@ _$button_attributes_478 = __extendFlat_477(_$button_attributes_478, { ].join(' ') }); -var _$attributes_477 = { +var _$attributes_539 = { visible: { valType: 'boolean', role: 'info', @@ -68651,7 +70516,7 @@ var _$attributes_477 = { ].join(' ') }, - buttons: _$button_attributes_478, + buttons: _$button_attributes_540, x: { valType: 'number', @@ -68694,14 +70559,14 @@ var _$attributes_477 = { ].join(' ') }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'plot', description: 'Sets the font of the range selector button text.' }), bgcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, role: 'style', editType: 'plot', description: 'Sets the background color of the range selector buttons.' @@ -68714,7 +70579,7 @@ var _$attributes_477 = { }, bordercolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'plot', description: 'Sets the color of the border enclosing the range selector.' @@ -68741,7 +70606,7 @@ var _$attributes_477 = { 'use strict'; -var _$constants_479 = { +var _$constants_541 = { // 'y' position pad above counter axis domain yPad: 0.02, @@ -68768,20 +70633,20 @@ var _$constants_479 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../color'); */; -/* removed: var _$attributes_477 = require('./attributes'); */; -/* removed: var _$button_attributes_478 = require('./button_attributes'); */; -/* removed: var _$constants_479 = require('./constants'); */; +/* removed: var _$attributes_539 = require('./attributes'); */; +/* removed: var _$button_attributes_540 = require('./button_attributes'); */; +/* removed: var _$constants_541 = require('./constants'); */; -var _$handleDefaults_480 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { +var _$handleDefaults_542 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { var selectorIn = containerIn.rangeselector || {}, selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(selectorIn, selectorOut, _$attributes_477, attr, dflt); + return _$lib_601.coerce(selectorIn, selectorOut, _$attributes_539, attr, dflt); } var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); @@ -68792,15 +70657,15 @@ var _$handleDefaults_480 = function handleDefaults(containerIn, containerOut, la var posDflt = getPosDflt(containerOut, layout, counterAxes); coerce('x', posDflt[0]); coerce('y', posDflt[1]); - _$lib_539.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_601.noneOrAll(containerIn, containerOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); - _$lib_539.coerceFont(coerce, 'font', layout.font); + _$lib_601.coerceFont(coerce, 'font', layout.font); var bgColor = coerce('bgcolor'); - coerce('activecolor', _$color_411.contrast(bgColor, _$constants_479.lightAmount, _$constants_479.darkAmount)); + coerce('activecolor', _$color_473.contrast(bgColor, _$constants_541.lightAmount, _$constants_541.darkAmount)); coerce('bordercolor'); coerce('borderwidth'); }; @@ -68812,14 +70677,14 @@ function buttonsDefaults(containerIn, containerOut, calendar) { var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_539.coerce(buttonIn, buttonOut, _$button_attributes_478, attr, dflt); + return _$lib_601.coerce(buttonIn, buttonOut, _$button_attributes_540, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { buttonIn = buttonsIn[i]; buttonOut = {}; - if(!_$lib_539.isPlainObject(buttonIn)) continue; + if(!_$lib_601.isPlainObject(buttonIn)) continue; var step = coerce('step'); if(step !== 'all') { @@ -68853,7 +70718,7 @@ function getPosDflt(containerOut, layout, counterAxes) { if(domain) posY = Math.max(domain[1], posY); } - return [containerOut.domain[0], posY + _$constants_479.yPad]; + return [containerOut.domain[0], posY + _$constants_541.yPad]; } /** @@ -68867,9 +70732,9 @@ function getPosDflt(containerOut, layout, counterAxes) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -var _$getUpdateObject_482 = function getUpdateObject(axisLayout, buttonLayout) { +var _$getUpdateObject_544 = function getUpdateObject(axisLayout, buttonLayout) { var axName = axisLayout._name; var update = {}; @@ -68897,13 +70762,13 @@ function getXRange(axisLayout, buttonLayout) { switch(buttonLayout.stepmode) { case 'backward': - range0 = axisLayout.l2r(+_$d3_127.time[step].utc.offset(base, -count)); + range0 = axisLayout.l2r(+_$d3_130.time[step].utc.offset(base, -count)); break; case 'todate': - var base2 = _$d3_127.time[step].utc.offset(base, -count); + var base2 = _$d3_130.time[step].utc.offset(base, -count); - range0 = axisLayout.l2r(+_$d3_127.time[step].utc.ceil(base2)); + range0 = axisLayout.l2r(+_$d3_130.time[step].utc.ceil(base2)); break; } @@ -68922,26 +70787,27 @@ function getXRange(axisLayout, buttonLayout) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$anchor_utils_463 = require('../legend/anchor_utils'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$anchor_utils_525 = require('../legend/anchor_utils'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_481 = _$alignment_511.LINE_SPACING; -var __FROM_TL_481 = _$alignment_511.FROM_TL; -var __FROM_BR_481 = _$alignment_511.FROM_BR; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_543 = _$alignment_573.LINE_SPACING; +var __FROM_TL_543 = _$alignment_573.FROM_TL; +var __FROM_BR_543 = _$alignment_573.FROM_BR; -/* removed: var _$constants_479 = require('./constants'); */; -/* removed: var _$getUpdateObject_482 = require('./get_update_object'); */; +/* removed: var _$constants_541 = require('./constants'); */; +/* removed: var _$getUpdateObject_544 = require('./get_update_object'); */; -var _$draw_481 = function draw(gd) { +var _$draw_543 = function draw(gd) { var fullLayout = gd._fullLayout; var selectors = fullLayout._infolayer.selectAll('.rangeselector') @@ -68958,7 +70824,7 @@ var _$draw_481 = function draw(gd) { }); selectors.each(function(d) { - var selector = _$d3_127.select(this), + var selector = _$d3_130.select(this), axisLayout = d, selectorLayout = axisLayout.rangeselector; @@ -68971,8 +70837,8 @@ var _$draw_481 = function draw(gd) { buttons.exit().remove(); buttons.each(function(d) { - var button = _$d3_127.select(this); - var update = _$getUpdateObject_482(axisLayout, d); + var button = _$d3_130.select(this); + var update = _$getUpdateObject_544(axisLayout, d); d._isActive = isActive(axisLayout, d, update); @@ -68982,7 +70848,7 @@ var _$draw_481 = function draw(gd) { button.on('click', function() { if(gd._dragged) return; - _$registry_668.call('relayout', gd, update); + _$registry_731.call('relayout', gd, update); }); button.on('mouseover', function() { @@ -69002,7 +70868,7 @@ var _$draw_481 = function draw(gd) { }; function makeSelectorData(gd) { - var axes = _$axis_ids_587.list(gd, 'x', true); + var axes = _$axis_ids_650.list(gd, 'x', true); var data = []; for(var i = 0; i < axes.length; i++) { @@ -69035,21 +70901,17 @@ function isActive(axisLayout, opts, update) { } function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - - rect.attr('shape-rendering', 'crispEdges'); + var rect = _$lib_601.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); rect.attr({ - 'rx': _$constants_479.rx, - 'ry': _$constants_479.ry + 'rx': _$constants_541.rx, + 'ry': _$constants_541.ry }); - rect.call(_$color_411.stroke, selectorLayout.bordercolor) - .call(_$color_411.fill, getFillColor(selectorLayout, d)) + rect.call(_$color_473.stroke, selectorLayout.bordercolor) + .call(_$color_473.fill, getFillColor(selectorLayout, d)) .style('stroke-width', selectorLayout.borderwidth + 'px'); } @@ -69061,19 +70923,15 @@ function getFillColor(selectorLayout, d) { function drawButtonText(button, selectorLayout, d, gd) { function textLayout(s) { - _$svg_text_utils_562.convertToTspans(s, gd); + _$svg_text_utils_625.convertToTspans(s, gd); } - var text = button.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - - text.attr('text-anchor', 'middle'); + var text = _$lib_601.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); - text.call(_$drawing_436.font, selectorLayout.font) + text.call(_$drawing_498.font, selectorLayout.font) .text(getLabel(d)) .call(textLayout); } @@ -69093,25 +70951,25 @@ function reposition(gd, buttons, opts, axName, selector) { var borderWidth = opts.borderwidth; buttons.each(function() { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); var text = button.select('.selector-text'); - var tHeight = opts.font.size * __LINE_SPACING_481; - var hEff = Math.max(tHeight * _$svg_text_utils_562.lineCount(text), 16) + 3; + var tHeight = opts.font.size * __LINE_SPACING_543; + var hEff = Math.max(tHeight * _$svg_text_utils_625.lineCount(text), 16) + 3; height = Math.max(height, hEff); }); buttons.each(function() { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); var rect = button.select('.selector-rect'); var text = button.select('.selector-text'); - var tWidth = text.node() && _$drawing_436.bBox(text.node()).width; - var tHeight = opts.font.size * __LINE_SPACING_481; - var tLines = _$svg_text_utils_562.lineCount(text); + var tWidth = text.node() && _$drawing_498.bBox(text.node()).width; + var tHeight = opts.font.size * __LINE_SPACING_543; + var tLines = _$svg_text_utils_625.lineCount(text); - var wEff = Math.max(tWidth + 10, _$constants_479.minButtonWidth); + var wEff = Math.max(tWidth + 10, _$constants_541.minButtonWidth); // TODO add MathJax support @@ -69128,7 +70986,7 @@ function reposition(gd, buttons, opts, axName, selector) { height: height }); - _$svg_text_utils_562.positionText(text, wEff / 2, + _$svg_text_utils_625.positionText(text, wEff / 2, height / 2 - ((tLines - 1) * tHeight / 2) + 3); width += wEff + 5; @@ -69139,21 +70997,21 @@ function reposition(gd, buttons, opts, axName, selector) { var ly = graphSize.t + graphSize.h * (1 - opts.y); var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { lx -= width; xanchor = 'right'; } - if(_$anchor_utils_463.isCenterAnchor(opts)) { + if(_$anchor_utils_525.isCenterAnchor(opts)) { lx -= width / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(opts)) { + if(_$anchor_utils_525.isBottomAnchor(opts)) { ly -= height; yanchor = 'bottom'; } - if(_$anchor_utils_463.isMiddleAnchor(opts)) { + if(_$anchor_utils_525.isMiddleAnchor(opts)) { ly -= height / 2; yanchor = 'middle'; } @@ -69163,13 +71021,13 @@ function reposition(gd, buttons, opts, axName, selector) { lx = Math.round(lx); ly = Math.round(ly); - _$plots_647.autoMargin(gd, axName + '-range-selector', { + _$plots_709.autoMargin(gd, axName + '-range-selector', { x: opts.x, y: opts.y, - l: width * __FROM_TL_481[xanchor], - r: width * __FROM_BR_481[xanchor], - b: height * __FROM_BR_481[yanchor], - t: height * __FROM_TL_481[yanchor] + l: width * __FROM_TL_543[xanchor], + r: width * __FROM_BR_543[xanchor], + b: height * __FROM_BR_543[yanchor], + t: height * __FROM_TL_543[yanchor] }); selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); @@ -69185,20 +71043,20 @@ function reposition(gd, buttons, opts, axName, selector) { 'use strict'; -var _$rangeselector_483 = { +var _$rangeselector_545 = { moduleType: 'component', name: 'rangeselector', schema: { subplots: { - xaxis: {rangeselector: _$attributes_477} + xaxis: {rangeselector: _$attributes_539} } }, - layoutAttributes: _$attributes_477, - handleDefaults: _$handleDefaults_480, + layoutAttributes: _$attributes_539, + handleDefaults: _$handleDefaults_542, - draw: _$draw_481 + draw: _$draw_543 }; /** @@ -69211,19 +71069,19 @@ var _$rangeselector_483 = { 'use strict'; -/* removed: var _$attributes_410 = require('../color/attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; -var _$attributes_484 = { +var _$attributes_546 = { bgcolor: { valType: 'color', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, role: 'style', editType: 'plot', description: 'Sets the background color of the range slider.' }, bordercolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, role: 'style', editType: 'plot', description: 'Sets the border color of the range slider.' @@ -69305,7 +71163,7 @@ var _$attributes_484 = { 'use strict'; -var _$constants_486 = { +var _$constants_548 = { // attribute container name name: 'rangeslider', @@ -69360,11 +71218,11 @@ var _$constants_486 = { 'use strict'; -var listAxes = _$axis_ids_587.list; -var __getAutoRange_485 = _$autorange_583.getAutoRange; -/* removed: var _$constants_486 = require('./constants'); */; +var listAxes = _$axis_ids_650.list; +var __getAutoRange_547 = _$autorange_646.getAutoRange; +/* removed: var _$constants_548 = require('./constants'); */; -var _$calcAutorange_485 = function calcAutorange(gd) { +var _$calcAutorange_547 = function calcAutorange(gd) { var axes = listAxes(gd, 'x', true); // Compute new slider range using axis autorange if necessary. @@ -69374,14 +71232,14 @@ var _$calcAutorange_485 = function calcAutorange(gd) { for(var i = 0; i < axes.length; i++) { var ax = axes[i], - opts = ax[_$constants_486.name]; + opts = ax[_$constants_548.name]; // Don't try calling getAutoRange if _min and _max are filled in. // This happens on updates where the calc step is skipped. if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { opts._input.autorange = true; - opts._input.range = opts.range = __getAutoRange_485(ax); + opts._input.range = opts.range = __getAutoRange_547(ax); } } }; @@ -69396,7 +71254,7 @@ var _$calcAutorange_485 = function calcAutorange(gd) { 'use strict'; -var _$oppaxis_attributes_490 = { +var _$oppaxis_attributes_552 = { // not really a 'subplot' attribute container, // but this is the flag we use to denote attributes that // support yaxis, yaxis2, yaxis3, ... counters @@ -69442,29 +71300,31 @@ var _$oppaxis_attributes_490 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_484 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_490 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_546 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_552 = require('./oppaxis_attributes'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +var _$handleDefaults_549 = function handleDefaults(layoutIn, layoutOut, axName) { + var axIn = layoutIn[axName]; + var axOut = layoutOut[axName]; -var _$handleDefaults_487 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; + if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; // not super proud of this (maybe store _ in axis object instead - if(!_$lib_539.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; + if(!_$lib_601.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; } - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$attributes_484, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$attributes_546, attr, dflt); } function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_539.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_490, attr, dflt); + return _$lib_601.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_552, attr, dflt); } var visible = coerce('visible'); @@ -69482,12 +71342,12 @@ var _$handleDefaults_487 = function handleDefaults(layoutIn, layoutOut, axName) if(subplots) { var yIds = subplots.cartesian .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_587.name2id(axName); + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_650.name2id(axName); }) .map(function(subplotId) { return subplotId.substr(subplotId.indexOf('y'), subplotId.length); }); - var yNames = _$lib_539.simpleMap(yIds, _$axis_ids_587.id2name); + var yNames = _$lib_601.simpleMap(yIds, _$axis_ids_650.id2name); for(var i = 0; i < yNames.length; i++) { var yName = yNames[i]; @@ -69523,25 +71383,25 @@ var _$handleDefaults_487 = function handleDefaults(layoutIn, layoutOut, axName) 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$titles_504 = require('../titles'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$titles_566 = require('../titles'); */; -/* removed: var _$cartesian_595 = require('../../plots/cartesian'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$cartesian_658 = require('../../plots/cartesian'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; -/* removed: var _$constants_486 = require('./constants'); */; +/* removed: var _$constants_548 = require('./constants'); */; -var _$draw_488 = function(gd) { +var _$draw_550 = function(gd) { var fullLayout = gd._fullLayout, rangeSliderData = makeRangeSliderData(fullLayout); @@ -69567,17 +71427,17 @@ var _$draw_488 = function(gd) { } var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_486.containerClassName) + .selectAll('g.' + _$constants_548.containerClassName) .data(rangeSliderData, keyFunction); rangeSliders.enter().append('g') - .classed(_$constants_486.containerClassName, true) + .classed(_$constants_548.containerClassName, true) .attr('pointer-events', 'all'); // remove exiting sliders and their corresponding clip paths rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_127.select(this), - opts = axisOpts[_$constants_486.name]; + var rangeSlider = _$d3_130.select(this), + opts = axisOpts[_$constants_548.name]; rangeSlider.remove(); fullLayout._topdefs.select('#' + opts._clipId).remove(); @@ -69591,10 +71451,10 @@ var _$draw_488 = function(gd) { // for all present range sliders rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_127.select(this), - opts = axisOpts[_$constants_486.name], - oppAxisOpts = fullLayout[_$axes_584.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_584.id2name(axisOpts.anchor)]; + var rangeSlider = _$d3_130.select(this), + opts = axisOpts[_$constants_548.name], + oppAxisOpts = fullLayout[_$axes_647.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_647.id2name(axisOpts.anchor)]; // update range // Expand slider range to the axis range @@ -69619,13 +71479,13 @@ var _$draw_488 = function(gd) { var tickHeight = (axisOpts._boundingBox || {}).height || 0; var oppBottom = Infinity; - var subplotData = _$axes_584.getSubplots(gd, axisOpts); + var subplotData = _$axes_647.getSubplots(gd, axisOpts); for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_584.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + var oppAxis = _$axes_647.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - opts._id = _$constants_486.name + axisOpts._id; + opts._id = _$constants_548.name + axisOpts._id; opts._clipId = opts._id + '-' + fullLayout._uid; opts._width = graphSize.w * (domain[1] - domain[0]); @@ -69637,7 +71497,7 @@ var _$draw_488 = function(gd) { var y = Math.round( graphSize.t + graphSize.h * (1 - oppBottom) + tickHeight + - opts._offsetShift + _$constants_486.extraPad + opts._offsetShift + _$constants_548.extraPad ); rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); @@ -69687,7 +71547,7 @@ var _$draw_488 = function(gd) { // title goes next to range slider instead of tick labels, so // just take it over and draw it from here if(axisOpts.side === 'bottom') { - _$titles_504.draw(gd, axisOpts._id + 'title', { + _$titles_566.draw(gd, axisOpts._id + 'title', { propContainer: axisOpts, propName: axisOpts._name + '.title', placeholder: fullLayout._dfltTitle.x, @@ -69700,21 +71560,21 @@ var _$draw_488 = function(gd) { } // update margins - _$plots_647.autoMargin(gd, opts._id, { + _$plots_709.autoMargin(gd, opts._id, { x: domain[0], y: oppBottom, l: 0, r: 0, t: 0, b: opts._height + margin.b + tickHeight, - pad: _$constants_486.extraPad + opts._offsetShift * 2 + pad: _$constants_548.extraPad + opts._offsetShift * 2 }); }); }; function makeRangeSliderData(fullLayout) { - var axes = _$axes_584.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_486.name, + var axes = _$axes_647.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_548.name, out = []; if(fullLayout._has('gl2d')) return out; @@ -69729,19 +71589,19 @@ function makeRangeSliderData(fullLayout) { } function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_486.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_486.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_486.grabAreaMaxClassName).node(); + var slideBox = rangeSlider.select('rect.' + _$constants_548.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_548.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_548.grabAreaMaxClassName).node(); rangeSlider.on('mousedown', function() { - var event = _$d3_127.event, + var event = _$d3_130.event, target = event.target, startX = event.clientX, offsetX = startX - rangeSlider.node().getBoundingClientRect().left, minVal = opts.d2p(axisOpts._rl[0]), maxVal = opts.d2p(axisOpts._rl[1]); - var dragCover = _$dragelement_433.coverSlip(); + var dragCover = _$dragelement_495.coverSlip(); dragCover.addEventListener('mousemove', mouseMove); dragCover.addEventListener('mouseup', mouseUp); @@ -69785,14 +71645,14 @@ function setupDragElement(rangeSlider, gd, axisOpts, opts) { opts._pixelMin = pixelMin; opts._pixelMax = pixelMax; - _$setCursor_558(_$d3_127.select(dragCover), cursor); + _$setCursor_621(_$d3_130.select(dragCover), cursor); setDataRange(rangeSlider, gd, axisOpts, opts); } function mouseUp() { dragCover.removeEventListener('mousemove', mouseMove); dragCover.removeEventListener('mouseup', mouseUp); - _$lib_539.removeElement(dragCover); + _$lib_601.removeElement(dragCover); } }); } @@ -69800,43 +71660,43 @@ function setupDragElement(rangeSlider, gd, axisOpts, opts) { function setDataRange(rangeSlider, gd, axisOpts, opts) { function clamp(v) { - return axisOpts.l2r(_$lib_539.constrain(v, opts._rl[0], opts._rl[1])); + return axisOpts.l2r(_$lib_601.constrain(v, opts._rl[0], opts._rl[1])); } var dataMin = clamp(opts.p2d(opts._pixelMin)), dataMax = clamp(opts.p2d(opts._pixelMax)); window.requestAnimationFrame(function() { - _$registry_668.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + _$registry_731.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); }); } function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_486.handleWidth / 2; + var hw2 = _$constants_548.handleWidth / 2; function clamp(v) { - return _$lib_539.constrain(v, 0, opts._width); + return _$lib_601.constrain(v, 0, opts._width); } function clampOppAxis(v) { - return _$lib_539.constrain(v, 0, opts._height); + return _$lib_601.constrain(v, 0, opts._height); } function clampHandle(v) { - return _$lib_539.constrain(v, -hw2, opts._width + hw2); + return _$lib_601.constrain(v, -hw2, opts._width + hw2); } var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), pixelMax = clamp(opts.d2p(axisOpts._rl[1])); - rangeSlider.select('rect.' + _$constants_486.slideBoxClassName) + rangeSlider.select('rect.' + _$constants_548.slideBoxClassName) .attr('x', pixelMin) .attr('width', pixelMax - pixelMin); - rangeSlider.select('rect.' + _$constants_486.maskMinClassName) + rangeSlider.select('rect.' + _$constants_548.maskMinClassName) .attr('width', pixelMin); - rangeSlider.select('rect.' + _$constants_486.maskMaxClassName) + rangeSlider.select('rect.' + _$constants_548.maskMaxClassName) .attr('x', pixelMax) .attr('width', opts._width - pixelMax); @@ -69844,18 +71704,18 @@ function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRang var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - rangeSlider.select('rect.' + _$constants_486.maskMinOppAxisClassName) + rangeSlider.select('rect.' + _$constants_548.maskMinOppAxisClassName) .attr('x', pixelMin) .attr('height', pixelMinOppAxis) .attr('width', pixelMax - pixelMin); - rangeSlider.select('rect.' + _$constants_486.maskMaxOppAxisClassName) + rangeSlider.select('rect.' + _$constants_548.maskMaxOppAxisClassName) .attr('x', pixelMin) .attr('y', pixelMaxOppAxis) .attr('height', opts._height - pixelMaxOppAxis) .attr('width', pixelMax - pixelMin); - rangeSlider.select('rect.' + _$constants_486.slideBoxClassName) + rangeSlider.select('rect.' + _$constants_548.slideBoxClassName) .attr('y', pixelMinOppAxis) .attr('height', pixelMaxOppAxis - pixelMinOppAxis); } @@ -69867,31 +71727,28 @@ function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRang var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - rangeSlider.select('g.' + _$constants_486.grabberMinClassName) + rangeSlider.select('g.' + _$constants_548.grabberMinClassName) .attr('transform', 'translate(' + xMin + ',' + offset + ')'); - rangeSlider.select('g.' + _$constants_486.grabberMaxClassName) + rangeSlider.select('g.' + _$constants_548.grabberMaxClassName) .attr('transform', 'translate(' + xMax + ',' + offset + ')'); } function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_486.bgClassName) - .data([0]); - - bg.enter().append('rect') - .classed(_$constants_486.bgClassName, true) - .attr({ + var bg = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.bgClassName, function(s) { + s.attr({ x: 0, y: 0, 'shape-rendering': 'crispEdges' }); + }); var borderCorrect = (opts.borderwidth % 2) === 0 ? opts.borderwidth : opts.borderwidth - 1; var offsetShift = -opts._offsetShift; - var lw = _$drawing_436.crispRound(gd, opts.borderwidth); + var lw = _$drawing_498.crispRound(gd, opts.borderwidth); bg.attr({ width: opts._width + borderCorrect, @@ -69906,13 +71763,9 @@ function drawBg(rangeSlider, gd, axisOpts, opts) { function addClipPath(rangeSlider, gd, axisOpts, opts) { var fullLayout = gd._fullLayout; - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + var clipPath = _$lib_601.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); clipPath.select('rect').attr({ width: opts._width, @@ -69921,15 +71774,15 @@ function addClipPath(rangeSlider, gd, axisOpts, opts) { } function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_584.getSubplots(gd, axisOpts), + var subplotData = _$axes_647.getSubplots(gd, axisOpts), calcData = gd.calcdata; - var rangePlots = rangeSlider.selectAll('g.' + _$constants_486.rangePlotClassName) - .data(subplotData, _$lib_539.identity); + var rangePlots = rangeSlider.selectAll('g.' + _$constants_548.rangePlotClassName) + .data(subplotData, _$lib_601.identity); rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_486.rangePlotClassName + ' ' + id; }) - .call(_$drawing_436.setClipUrl, opts._clipId); + .attr('class', function(id) { return _$constants_548.rangePlotClassName + ' ' + id; }) + .call(_$drawing_498.setClipUrl, opts._clipId); rangePlots.order(); @@ -69938,10 +71791,10 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { var mainplotinfo; rangePlots.each(function(id, i) { - var plotgroup = _$d3_127.select(this), + var plotgroup = _$d3_130.select(this), isMainPlot = (i === 0); - var oppAxisOpts = _$axes_584.getFromId(gd, id, 'y'), + var oppAxisOpts = _$axes_647.getFromId(gd, id, 'y'), oppAxisName = oppAxisOpts._name, oppAxisRangeOpts = opts[oppAxisName]; @@ -69968,7 +71821,7 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { calendar: oppAxisOpts.calendar }; - _$plots_647.supplyDefaults(mockFigure); + _$plots_709.supplyDefaults(mockFigure); var xa = mockFigure._fullLayout.xaxis, ya = mockFigure._fullLayout[oppAxisName]; @@ -69977,7 +71830,8 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { id: id, plotgroup: plotgroup, xaxis: xa, - yaxis: ya + yaxis: ya, + isRangePlot: true }; if(isMainPlot) mainplotinfo = plotinfo; @@ -69986,7 +71840,7 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { plotinfo.mainplotinfo = mainplotinfo; } - _$cartesian_595.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + _$cartesian_658.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); }); } @@ -70006,146 +71860,121 @@ function filterRangePlotCalcData(calcData, subplotId) { } function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_486.maskMinClassName) - .data([0]); - - maskMin.enter().append('rect') - .classed(_$constants_486.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + var maskMin = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMin .attr('height', opts._height) - .call(_$color_411.fill, _$constants_486.maskColor); + .call(_$color_473.fill, _$constants_548.maskColor); - var maskMax = rangeSlider.selectAll('rect.' + _$constants_486.maskMaxClassName) - .data([0]); - - maskMax.enter().append('rect') - .classed(_$constants_486.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var maskMax = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMax .attr('height', opts._height) - .call(_$color_411.fill, _$constants_486.maskColor); + .call(_$color_473.fill, _$constants_548.maskColor); // masks used for oppAxis zoom if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_486.maskMinOppAxisClassName) - .data([0]); - - maskMinOppAxis.enter().append('rect') - .classed(_$constants_486.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var maskMinOppAxis = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMinOppAxis .attr('width', opts._width) - .call(_$color_411.fill, _$constants_486.maskOppAxisColor); + .call(_$color_473.fill, _$constants_548.maskOppAxisColor); - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_486.maskMaxOppAxisClassName) - .data([0]); - - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_486.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var maskMaxOppAxis = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMaxOppAxis .attr('width', opts._width) - .style('border-top', _$constants_486.maskOppBorder) - .call(_$color_411.fill, _$constants_486.maskOppAxisColor); + .style('border-top', _$constants_548.maskOppBorder) + .call(_$color_473.fill, _$constants_548.maskOppAxisColor); } } function drawSlideBox(rangeSlider, gd, axisOpts, opts) { if(gd._context.staticPlot) return; - var slideBox = rangeSlider.selectAll('rect.' + _$constants_486.slideBoxClassName) - .data([0]); - - slideBox.enter().append('rect') - .classed(_$constants_486.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_486.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); + var slideBox = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_548.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); slideBox.attr({ height: opts._height, - fill: _$constants_486.slideBoxFill + fill: _$constants_548.slideBoxFill }); } function drawGrabbers(rangeSlider, gd, axisOpts, opts) { - // - - var grabberMin = rangeSlider.selectAll('g.' + _$constants_486.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_486.grabberMinClassName, true); - - var grabberMax = rangeSlider.selectAll('g.' + _$constants_486.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_486.grabberMaxClassName, true); + var grabberMin = _$lib_601.ensureSingle(rangeSlider, 'g', _$constants_548.grabberMinClassName); + var grabberMax = _$lib_601.ensureSingle(rangeSlider, 'g', _$constants_548.grabberMaxClassName); // - var handleFixAttrs = { x: 0, - width: _$constants_486.handleWidth, - rx: _$constants_486.handleRadius, - fill: _$color_411.background, - stroke: _$color_411.defaultLine, - 'stroke-width': _$constants_486.handleStrokeWidth, + width: _$constants_548.handleWidth, + rx: _$constants_548.handleRadius, + fill: _$color_473.background, + stroke: _$color_473.defaultLine, + 'stroke-width': _$constants_548.handleStrokeWidth, 'shape-rendering': 'crispEdges' }; - var handleDynamicAttrs = { y: Math.round(opts._height / 4), height: Math.round(opts._height / 2), }; - - var handleMin = grabberMin.selectAll('rect.' + _$constants_486.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_486.handleMinClassName, true) - .attr(handleFixAttrs); + var handleMin = _$lib_601.ensureSingle(grabberMin, 'rect', _$constants_548.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); handleMin.attr(handleDynamicAttrs); - var handleMax = grabberMax.selectAll('rect.' + _$constants_486.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_486.handleMaxClassName, true) - .attr(handleFixAttrs); + var handleMax = _$lib_601.ensureSingle(grabberMax, 'rect', _$constants_548.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); handleMax.attr(handleDynamicAttrs); // - if(gd._context.staticPlot) return; var grabAreaFixAttrs = { - width: _$constants_486.grabAreaWidth, + width: _$constants_548.grabAreaWidth, x: 0, y: 0, - fill: _$constants_486.grabAreaFill, - cursor: _$constants_486.grabAreaCursor + fill: _$constants_548.grabAreaFill, + cursor: _$constants_548.grabAreaCursor }; - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_486.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_486.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); + var grabAreaMin = _$lib_601.ensureSingle(grabberMin, 'rect', _$constants_548.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); grabAreaMin.attr('height', opts._height); - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_486.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_486.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); + var grabAreaMax = _$lib_601.ensureSingle(grabberMax, 'rect', _$constants_548.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); grabAreaMax.attr('height', opts._height); } @@ -70156,8 +71985,8 @@ function clearPushMargins(gd) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_486.name) !== -1) { - _$plots_647.autoMargin(gd, k); + if(k.indexOf(_$constants_548.name) !== -1) { + _$plots_709.autoMargin(gd, k); } } } @@ -70172,28 +72001,28 @@ function clearPushMargins(gd) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_484 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_490 = require('./oppaxis_attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_546 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_552 = require('./oppaxis_attributes'); */; -var _$rangeslider_489 = { +var _$rangeslider_551 = { moduleType: 'component', name: 'rangeslider', schema: { subplots: { xaxis: { - rangeslider: _$lib_539.extendFlat({}, _$attributes_484, { - yaxis: _$oppaxis_attributes_490 + rangeslider: _$lib_601.extendFlat({}, _$attributes_546, { + yaxis: _$oppaxis_attributes_552 }) } } }, - layoutAttributes: _$attributes_484, - handleDefaults: _$handleDefaults_487, - calcAutorange: _$calcAutorange_485, - draw: _$draw_488 + layoutAttributes: _$attributes_546, + handleDefaults: _$handleDefaults_549, + calcAutorange: _$calcAutorange_547, + draw: _$draw_550 }; /** @@ -70206,12 +72035,12 @@ var _$rangeslider_489 = { 'use strict'; -/* removed: var _$attributes_394 = require('../annotations/attributes'); */; -var __scatterLineAttrs_491 = _$attributes_862.line; -var __dash_491 = _$attributes_435.dash; -var __extendFlat_491 = _$extend_528.extendFlat; +/* removed: var _$attributes_456 = require('../annotations/attributes'); */; +var __scatterLineAttrs_553 = _$attributes_927.line; +var __dash_553 = _$attributes_497.dash; +var __extendFlat_553 = _$extend_590.extendFlat; -var _$attributes_491 = { +var _$attributes_553 = { _isLinkedToArray: 'shape', visible: { @@ -70233,16 +72062,20 @@ var _$attributes_491 = { 'Specifies the shape type to be drawn.', 'If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`)', + 'with respect to the axes\' sizing mode.', 'If *circle*, a circle is drawn from', '((`x0`+`x1`)/2, (`y0`+`y1`)/2))', 'with radius', '(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|)', + 'with respect to the axes\' sizing mode.', 'If *rect*, a rectangle is drawn linking', '(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`)', + 'with respect to the axes\' sizing mode.', - 'If *path*, draw a custom SVG path using `path`.' + 'If *path*, draw a custom SVG path using `path`.', + 'with respect to the axes\' sizing mode.' ].join(' ') }, @@ -70255,11 +72088,11 @@ var _$attributes_491 = { description: 'Specifies whether shapes are drawn below or above traces.' }, - xref: __extendFlat_491({}, _$attributes_394.xref, { + xref: __extendFlat_553({}, _$attributes_456.xref, { description: [ 'Sets the shape\'s x coordinate axis.', 'If set to an x axis id (e.g. *x* or *x2*), the `x` position', - 'refers to an x coordinate', + 'refers to an x coordinate.', 'If set to *paper*, the `x` position refers to the distance from', 'the left side of the plotting area in normalized coordinates', 'where *0* (*1*) corresponds to the left (right) side.', @@ -70269,13 +72102,43 @@ var _$attributes_491 = { 'the date to unix time in milliseconds.' ].join(' ') }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + role: 'info', + editType: 'calcIfAutorange+arraydraw', + description: [ + 'Sets the shapes\'s sizing mode along the x axis.', + 'If set to *scaled*, `x0`, `x1` and x coordinates within `path` refer to', + 'data values on the x axis or a fraction of the plot area\'s width', + '(`xref` set to *paper*).', + 'If set to *pixel*, `xanchor` specifies the x position in terms', + 'of data or plot fraction but `x0`, `x1` and x coordinates within `path`', + 'are pixels relative to `xanchor`. This way, the shape can have', + 'a fixed width while maintaining a position relative to data or', + 'plot fraction.' + ].join(' ') + }, + xanchor: { + valType: 'any', + role: 'info', + editType: 'calcIfAutorange+arraydraw', + description: [ + 'Only relevant in conjunction with `xsizemode` set to *pixel*.', + 'Specifies the anchor point on the x axis to which `x0`, `x1`', + 'and x coordinates within `path` are relative to.', + 'E.g. useful to attach a pixel sized shape to a certain data value.', + 'No effect when `xsizemode` not set to *pixel*.' + ].join(' ') + }, x0: { valType: 'any', role: 'info', editType: 'calcIfAutorange+arraydraw', description: [ 'Sets the shape\'s starting x position.', - 'See `type` for more info.' + 'See `type` and `xsizemode` for more info.' ].join(' ') }, x1: { @@ -70284,11 +72147,11 @@ var _$attributes_491 = { editType: 'calcIfAutorange+arraydraw', description: [ 'Sets the shape\'s end x position.', - 'See `type` for more info.' + 'See `type` and `xsizemode` for more info.' ].join(' ') }, - yref: __extendFlat_491({}, _$attributes_394.yref, { + yref: __extendFlat_553({}, _$attributes_456.yref, { description: [ 'Sets the annotation\'s y coordinate axis.', 'If set to an y axis id (e.g. *y* or *y2*), the `y` position', @@ -70298,13 +72161,43 @@ var _$attributes_491 = { 'where *0* (*1*) corresponds to the bottom (top).' ].join(' ') }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + role: 'info', + editType: 'calcIfAutorange+arraydraw', + description: [ + 'Sets the shapes\'s sizing mode along the y axis.', + 'If set to *scaled*, `y0`, `y1` and y coordinates within `path` refer to', + 'data values on the y axis or a fraction of the plot area\'s height', + '(`yref` set to *paper*).', + 'If set to *pixel*, `yanchor` specifies the y position in terms', + 'of data or plot fraction but `y0`, `y1` and y coordinates within `path`', + 'are pixels relative to `yanchor`. This way, the shape can have', + 'a fixed height while maintaining a position relative to data or', + 'plot fraction.' + ].join(' ') + }, + yanchor: { + valType: 'any', + role: 'info', + editType: 'calcIfAutorange+arraydraw', + description: [ + 'Only relevant in conjunction with `ysizemode` set to *pixel*.', + 'Specifies the anchor point on the y axis to which `y0`, `y1`', + 'and y coordinates within `path` are relative to.', + 'E.g. useful to attach a pixel sized shape to a certain data value.', + 'No effect when `ysizemode` not set to *pixel*.' + ].join(' ') + }, y0: { valType: 'any', role: 'info', editType: 'calcIfAutorange+arraydraw', description: [ 'Sets the shape\'s starting y position.', - 'See `type` for more info.' + 'See `type` and `ysizemode` for more info.' ].join(' ') }, y1: { @@ -70313,7 +72206,7 @@ var _$attributes_491 = { editType: 'calcIfAutorange+arraydraw', description: [ 'Sets the shape\'s end y position.', - 'See `type` for more info.' + 'See `type` and `ysizemode` for more info.' ].join(' ') }, @@ -70322,8 +72215,11 @@ var _$attributes_491 = { role: 'info', editType: 'calcIfAutorange+arraydraw', description: [ - 'For `type` *path* - a valid SVG path but with the pixel values', - 'replaced by data values. There are a few restrictions / quirks', + 'For `type` *path* - a valid SVG path with the pixel values', + 'replaced by data values in `xsizemode`/`ysizemode` being *scaled*', + 'and taken unmodified as pixels relative to `xanchor` and `yanchor`', + 'in case of *pixel* size mode.', + 'There are a few restrictions / quirks', 'only absolute instructions, not relative. So the allowed segments', 'are: M, L, H, V, Q, C, T, S, and Z', 'arcs (A) are not allowed because radius rx and ry are relative.', @@ -70355,9 +72251,9 @@ var _$attributes_491 = { description: 'Sets the opacity of the shape.' }, line: { - color: __extendFlat_491({}, __scatterLineAttrs_491.color, {editType: 'arraydraw'}), - width: __extendFlat_491({}, __scatterLineAttrs_491.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_491({}, __dash_491, {editType: 'arraydraw'}), + color: __extendFlat_553({}, __scatterLineAttrs_553.color, {editType: 'arraydraw'}), + width: __extendFlat_553({}, __scatterLineAttrs_553.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_553({}, __dash_553, {editType: 'arraydraw'}), role: 'info', editType: 'calcIfAutorange+arraydraw' }, @@ -70385,7 +72281,7 @@ var _$attributes_491 = { 'use strict'; -var _$constants_493 = { +var _$constants_555 = { segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, paramRE: /[^\s,]+/g, @@ -70436,7 +72332,7 @@ var _$constants_493 = { } }; -var _$helpers_496 = {}; +var _$helpers_558 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -70457,37 +72353,37 @@ var _$helpers_496 = {}; // will be identical, so rangeToShapePosition and shapePositionToRange can be // removed entirely. -_$helpers_496.rangeToShapePosition = function(ax) { +_$helpers_558.rangeToShapePosition = function(ax) { return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; }; -_$helpers_496.shapePositionToRange = function(ax) { +_$helpers_558.shapePositionToRange = function(ax) { return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; }; -_$helpers_496.decodeDate = function(convertToPx) { +_$helpers_558.decodeDate = function(convertToPx) { return function(v) { if(v.replace) v = v.replace('_', ' '); return convertToPx(v); }; }; -_$helpers_496.encodeDate = function(convertToDate) { +_$helpers_558.encodeDate = function(convertToDate) { return function(v) { return convertToDate(v).replace(' ', '_'); }; }; -_$helpers_496.getDataToPixel = function(gd, axis, isVertical) { +_$helpers_558.getDataToPixel = function(gd, axis, isVertical) { var gs = gd._fullLayout._size, dataToPixel; if(axis) { - var d2r = _$helpers_496.shapePositionToRange(axis); + var d2r = _$helpers_558.shapePositionToRange(axis); dataToPixel = function(v) { return axis._offset + axis.r2p(d2r(v, true)); }; - if(axis.type === 'date') dataToPixel = _$helpers_496.decodeDate(dataToPixel); + if(axis.type === 'date') dataToPixel = _$helpers_558.decodeDate(dataToPixel); } else if(isVertical) { dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; @@ -70499,12 +72395,12 @@ _$helpers_496.getDataToPixel = function(gd, axis, isVertical) { return dataToPixel; }; -_$helpers_496.getPixelToData = function(gd, axis, isVertical) { +_$helpers_558.getPixelToData = function(gd, axis, isVertical) { var gs = gd._fullLayout._size, pixelToData; if(axis) { - var r2d = _$helpers_496.rangeToShapePosition(axis); + var r2d = _$helpers_558.rangeToShapePosition(axis); pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; } else if(isVertical) { @@ -70528,39 +72424,93 @@ _$helpers_496.getPixelToData = function(gd, axis, isVertical) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$constants_493 = require('./constants'); */; -/* removed: var _$helpers_496 = require('./helpers'); */; +/* removed: var _$constants_555 = require('./constants'); */; +/* removed: var _$helpers_558 = require('./helpers'); */; -var _$calcAutorange_492 = function calcAutorange(gd) { +var _$calcAutorange_554 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - shapeList = _$lib_539.filterVisible(fullLayout.shapes); + shapeList = _$lib_601.filterVisible(fullLayout.shapes); if(!shapeList.length || !gd._fullData.length) return; for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; + var shape = shapeList[i]; var ax, bounds; if(shape.xref !== 'paper') { - ax = _$axes_584.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_493.paramIsX); - if(bounds) _$axes_584.expand(ax, bounds, {ppad: ppad}); + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_647.getFromId(gd, shape.xref); + + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_555.paramIsX); + + if(bounds) _$axes_647.expand(ax, bounds, calcXPaddingOptions(shape)); } if(shape.yref !== 'paper') { - ax = _$axes_584.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_493.paramIsY); - if(bounds) _$axes_584.expand(ax, bounds, {ppad: ppad}); + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_647.getFromId(gd, shape.yref); + + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_555.paramIsY); + if(bounds) _$axes_647.expand(ax, bounds, calcYPaddingOptions(shape)); } } }; +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} + +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} + +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; + + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_555.paramIsY : _$constants_555.paramIsX) : + [v0, v1]; + var maxValue = _$lib_601.aggNums(Math.max, null, coords), + minValue = _$lib_601.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; + + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} + +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; + + var segments = path.match(_$constants_555.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; + + var params = segment.substr(1).match(_$constants_555.paramRE); + if(!params || params.length < relevantParamIdx) return; + + extractedCoordinates.push(params[relevantParamIdx]); + }); + + return extractedCoordinates; +} + function shapeBounds(ax, v0, v1, path, paramsToUse) { var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; @@ -70569,21 +72519,21 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { var min = Infinity, max = -Infinity, - segments = path.match(_$constants_493.segmentRE), + segments = path.match(_$constants_555.segmentRE), i, segment, drawnParam, params, val; - if(ax.type === 'date') convertVal = _$helpers_496.decodeDate(convertVal); + if(ax.type === 'date') convertVal = _$helpers_558.decodeDate(convertVal); for(i = 0; i < segments.length; i++) { segment = segments[i]; drawnParam = paramsToUse[segment.charAt(0)].drawn; if(drawnParam === undefined) continue; - params = segments[i].substr(1).match(_$constants_493.paramRE); + params = segments[i].substr(1).match(_$constants_555.paramRE); if(!params || params.length < drawnParam) continue; val = convertVal(params[drawnParam]); @@ -70604,19 +72554,19 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$attributes_491 = require('./attributes'); */; -/* removed: var _$helpers_496 = require('./helpers'); */; +/* removed: var _$attributes_553 = require('./attributes'); */; +/* removed: var _$helpers_558 = require('./helpers'); */; -var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { +var _$handleShapeDefaults_560 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { opts = opts || {}; itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(shapeIn, shapeOut, _$attributes_491, attr, dflt); + return _$lib_601.coerce(shapeIn, shapeOut, _$attributes_553, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -70631,32 +72581,37 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, coerce('line.dash'); var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); // positioning var axLetters = ['x', 'y']; for(var i = 0; i < 2; i++) { var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; // xref, yref - var axRef = _$axes_584.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_647.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + if(axRef !== 'paper') { + ax = _$axes_647.getFromId(gdMock, axRef); + r2pos = _$helpers_558.rangeToShapePosition(ax); + pos2r = _$helpers_558.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_601.identity; + } + + // Coerce x0, x1, y0, y1 if(shapeType !== 'path') { var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; - - if(axRef !== 'paper') { - ax = _$axes_584.getFromId(gdMock, axRef); - r2pos = _$helpers_496.rangeToShapePosition(ax); - pos2r = _$helpers_496.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_539.identity; - } + 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 @@ -70669,9 +72624,13 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, shapeIn[attr0] = pos2r(shapeIn[attr0], true); shapeIn[attr1] = pos2r(shapeIn[attr1], true); - // x0, x1 (and y0, y1) - _$axes_584.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_584.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_647.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_647.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } // hack part 2 shapeOut[attr0] = r2pos(shapeOut[attr0]); @@ -70679,13 +72638,26 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, 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_647.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_539.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + _$lib_601.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); } return shapeOut; @@ -70702,17 +72674,17 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, 'use strict'; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_498 = require('./shape_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_560 = require('./shape_defaults'); */; -var _$supplyLayoutDefaults_494 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_556 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_498 + handleItemDefaults: _$handleShapeDefaults_560 }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; /** @@ -70726,17 +72698,17 @@ var _$supplyLayoutDefaults_494 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; -/* removed: var _$constants_493 = require('./constants'); */; -/* removed: var _$helpers_496 = require('./helpers'); */; +/* removed: var _$constants_555 = require('./constants'); */; +/* removed: var _$helpers_558 = require('./helpers'); */; // Shapes are stored in gd.layout.shapes, an array of objects @@ -70748,22 +72720,26 @@ var _$supplyLayoutDefaults_494 = function supplyLayoutDefaults(layoutIn, layoutO // if opt is blank, val can be 'add' or a full options object to add a new // annotation at that point in the array, or 'remove' to delete this one -var _$draw_495 = { - draw: __draw_495, - drawOne: __drawOne_495 +var _$draw_557 = { + draw: __draw_557, + drawOne: __drawOne_557 }; -function __draw_495(gd) { +function __draw_557(gd) { var fullLayout = gd._fullLayout; // Remove previous shapes before drawing new in shapes in fullLayout.shapes fullLayout._shapeUpperLayer.selectAll('path').remove(); fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); + } for(var i = 0; i < fullLayout.shapes.length; i++) { if(fullLayout.shapes[i].visible) { - __drawOne_495(gd, i); + __drawOne_557(gd, i); } } @@ -70771,7 +72747,7 @@ function __draw_495(gd) { // return Plots.previousPromises(gd); } -function __drawOne_495(gd, index) { +function __drawOne_557(gd, index) { // remove the existing shape if there is one. // because indices can change, we need to look in all shape layers gd._fullLayout._paperdiv @@ -70817,30 +72793,33 @@ function __drawOne_495(gd, index) { var path = shapeLayer.append('path') .attr(attrs) .style('opacity', options.opacity) - .call(_$color_411.stroke, lineColor) - .call(_$color_411.fill, options.fillcolor) - .call(_$drawing_436.dashLine, options.line.dash, options.line.width); + .call(_$color_473.stroke, lineColor) + .call(_$color_473.fill, options.fillcolor) + .call(_$drawing_498.dashLine, options.line.dash, options.line.width); // note that for layer="below" the clipAxes can be different from the // subplot we're drawing this in. This could cause problems if the shape // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - path.call(_$drawing_436.setClipUrl, clipAxes ? + path.call(_$drawing_498.setClipUrl, clipAxes ? ('clip' + gd._fullLayout._uid + clipAxes) : null ); - if(gd._context.edits.shapePosition) __setupDragElement_495(gd, path, options, index); + if(gd._context.edits.shapePosition) __setupDragElement_557(gd, path, options, index); } } -function __setupDragElement_495(gd, shapePath, shapeOptions, index) { +function __setupDragElement_557(gd, shapePath, shapeOptions, index) { var MINWIDTH = 10, MINHEIGHT = 10; + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; + var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; var pathIn, astrPath; @@ -70852,14 +72831,17 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { prepFn: startDrag, doneFn: endDrag }, - dragBBox = dragOptions.element.getBoundingClientRect(), dragMode; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); shapePath.node().onmousemove = updateDragMode; function updateDragMode(evt) { + // 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, @@ -70867,10 +72849,10 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { x = evt.clientX - dragBBox.left, y = evt.clientY - dragBBox.top, cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_433.getCursor(x / w, 1 - y / h) : + _$dragelement_495.getCursor(x / w, 1 - y / h) : 'move'; - _$setCursor_558(shapePath, cursor); + _$setCursor_621(shapePath, cursor); // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' dragMode = cursor.split('-')[0]; @@ -70878,25 +72860,35 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { function startDrag(evt) { // setup conversion functions - xa = _$axes_584.getFromId(gd, shapeOptions.xref); - ya = _$axes_584.getFromId(gd, shapeOptions.yref); + xa = _$axes_647.getFromId(gd, shapeOptions.xref); + ya = _$axes_647.getFromId(gd, shapeOptions.yref); - x2p = _$helpers_496.getDataToPixel(gd, xa); - y2p = _$helpers_496.getDataToPixel(gd, ya, true); - p2x = _$helpers_496.getPixelToData(gd, xa); - p2y = _$helpers_496.getPixelToData(gd, ya, true); + x2p = _$helpers_558.getDataToPixel(gd, xa); + y2p = _$helpers_558.getDataToPixel(gd, ya, true); + p2x = _$helpers_558.getPixelToData(gd, xa); + p2y = _$helpers_558.getPixelToData(gd, ya, true); // setup update strings and initial values var astr = 'shapes[' + index + ']'; + + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } + if(shapeOptions.type === 'path') { pathIn = shapeOptions.path; astrPath = astr + '.path'; } else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + 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); astrX0 = astr + '.x0'; astrY0 = astr + '.y0'; @@ -70912,7 +72904,10 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { w0 = x1; astrW = astr + '.x1'; optW = 'x1'; e0 = x0; astrE = astr + '.x0'; optE = 'x0'; } - if(y0 < y1) { + + // 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; astrN = astr + '.y0'; optN = 'y0'; s0 = y1; astrS = astr + '.y1'; optS = 'y1'; } @@ -70929,26 +72924,47 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { } function endDrag() { - _$setCursor_558(shapePath); - _$registry_668.call('relayout', gd, update); + _$setCursor_621(shapePath); + _$registry_731.call('relayout', gd, update); } function moveShape(dx, dy) { if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_496.encodeDate(moveX); + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_496.encodeDate(moveY); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_558.encodeDate(moveX); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_558.encodeDate(moveY); + } shapeOptions.path = movePath(pathIn, moveX, moveY); update[astrPath] = shapeOptions.path; } else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } } shapePath.attr('d', getPathString(gd, shapeOptions)); @@ -70957,11 +72973,23 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { function resizeShape(dx, dy) { if(shapeOptions.type === 'path') { // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_496.encodeDate(moveX); + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_496.encodeDate(moveY); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_558.encodeDate(moveX); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_558.encodeDate(moveY); + } shapeOptions.path = movePath(pathIn, moveX, moveY); update[astrPath] = shapeOptions.path; @@ -70972,14 +73000,21 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + // 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); } } @@ -70989,16 +73024,14 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { function getPathString(gd, options) { var type = options.type, - xa = _$axes_584.getFromId(gd, options.xref), - ya = _$axes_584.getFromId(gd, options.yref), + xa = _$axes_647.getFromId(gd, options.xref), + ya = _$axes_647.getFromId(gd, options.yref), gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; if(xa) { - x2r = _$helpers_496.shapePositionToRange(xa); + x2r = _$helpers_558.shapePositionToRange(xa); x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; } else { @@ -71006,7 +73039,7 @@ function getPathString(gd, options) { } if(ya) { - y2r = _$helpers_496.shapePositionToRange(ya); + y2r = _$helpers_558.shapePositionToRange(ya); y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; } else { @@ -71014,15 +73047,30 @@ function getPathString(gd, options) { } if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_496.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_496.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); + if(xa && xa.type === 'date') x2p = _$helpers_558.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_558.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), + 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'; @@ -71039,18 +73087,30 @@ function getPathString(gd, options) { } -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_493.segmentRE, function(segment) { +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; + + + return pathIn.replace(_$constants_555.segmentRE, function(segment) { var paramNumber = 0, segmentType = segment.charAt(0), - xParams = _$constants_493.paramIsX[segmentType], - yParams = _$constants_493.paramIsY[segmentType], - nParams = _$constants_493.numParams[segmentType]; + xParams = _$constants_555.paramIsX[segmentType], + yParams = _$constants_555.paramIsY[segmentType], + nParams = _$constants_555.numParams[segmentType]; - var paramString = segment.substr(1).replace(_$constants_493.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); + var paramString = segment.substr(1).replace(_$constants_555.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'; @@ -71059,7 +73119,7 @@ function convertPath(pathIn, x2p, y2p) { if(paramNumber > nParams) { paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_539.log('Ignoring extra params in segment ' + segment); + _$lib_601.log('Ignoring extra params in segment ' + segment); } return segmentType + paramString; @@ -71067,14 +73127,14 @@ function convertPath(pathIn, x2p, y2p) { } function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_493.segmentRE, function(segment) { + return pathIn.replace(_$constants_555.segmentRE, function(segment) { var paramNumber = 0, segmentType = segment.charAt(0), - xParams = _$constants_493.paramIsX[segmentType], - yParams = _$constants_493.paramIsY[segmentType], - nParams = _$constants_493.numParams[segmentType]; + xParams = _$constants_555.paramIsX[segmentType], + yParams = _$constants_555.paramIsY[segmentType], + nParams = _$constants_555.numParams[segmentType]; - var paramString = segment.substr(1).replace(_$constants_493.paramRE, function(param) { + var paramString = segment.substr(1).replace(_$constants_555.paramRE, function(param) { if(paramNumber >= nParams) return param; if(xParams[paramNumber]) param = moveX(param); @@ -71100,19 +73160,19 @@ function movePath(pathIn, moveX, moveY) { 'use strict'; -/* removed: var _$draw_495 = require('./draw'); */; +/* removed: var _$draw_557 = require('./draw'); */; -var _$shapes_497 = { +var _$shapes_559 = { moduleType: 'component', name: 'shapes', - layoutAttributes: _$attributes_491, - supplyLayoutDefaults: _$supplyLayoutDefaults_494, - includeBasePlot: _$makeIncludeComponents_594('shapes'), + layoutAttributes: _$attributes_553, + supplyLayoutDefaults: _$supplyLayoutDefaults_556, + includeBasePlot: _$makeIncludeComponents_657('shapes'), - calcAutorange: _$calcAutorange_492, - draw: _$draw_495.draw, - drawOne: _$draw_495.drawOne + calcAutorange: _$calcAutorange_554, + draw: _$draw_557.draw, + drawOne: _$draw_557.drawOne }; /** @@ -71127,7 +73187,7 @@ var _$shapes_497 = { 'use strict'; -var _$constants_500 = { +var _$constants_562 = { // layout attribute name name: 'sliders', @@ -71221,7 +73281,7 @@ var _$constants_500 = { // This is used exclusively by components inside component arrays, // hence the 'arraydraw' editType. If this ever gets used elsewhere // we could generalize it as a function ala font_attributes -var _$pad_attributes_646 = { +var _$pad_attributes_708 = { t: { valType: 'number', dflt: 0, @@ -71263,12 +73323,12 @@ var _$pad_attributes_646 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_646 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_499 = _$extend_528.extendDeepAll; -var __overrideAll_499 = _$edit_types_569.overrideAll; -/* removed: var _$animation_attributes_579 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_500 = require('./constants'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_708 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_561 = _$extend_590.extendDeepAll; +var __overrideAll_561 = _$edit_types_632.overrideAll; +/* removed: var _$animation_attributes_642 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_562 = require('./constants'); */; var stepsAttrs = { _isLinkedToArray: 'step', @@ -71327,7 +73387,7 @@ var stepsAttrs = { } }; -var _$attributes_499 = __overrideAll_499({ +var _$attributes_561 = __overrideAll_561({ _isLinkedToArray: 'slider', visible: { @@ -71383,7 +73443,7 @@ var _$attributes_499 = __overrideAll_499({ role: 'style', description: 'Sets the x position (in normalized coordinates) of the slider.' }, - pad: __extendDeepAll_499({}, _$pad_attributes_646, { + pad: __extendDeepAll_561({}, _$pad_attributes_708, { description: 'Set the padding of the slider component along each side.' }, {t: {dflt: 20}}), xanchor: { @@ -71427,7 +73487,7 @@ var _$attributes_499 = __overrideAll_499({ }, easing: { valType: 'enumerated', - values: _$animation_attributes_579.transition.easing.values, + values: _$animation_attributes_642.transition.easing.values, role: 'info', dflt: 'cubic-in-out', description: 'Sets the easing function of the slider transition' @@ -71476,19 +73536,19 @@ var _$attributes_499 = __overrideAll_499({ description: 'When currentvalue.visible is true, this sets the suffix of the label.' }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ description: 'Sets the font of the current value label text.' }) }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ description: 'Sets the font of the slider step labels.' }), activebgcolor: { valType: 'color', role: 'style', - dflt: _$constants_500.gripBgActiveColor, + dflt: _$constants_562.gripBgActiveColor, description: [ 'Sets the background color of the slider grip', 'while dragging.' @@ -71497,32 +73557,32 @@ var _$attributes_499 = __overrideAll_499({ bgcolor: { valType: 'color', role: 'style', - dflt: _$constants_500.railBgColor, + dflt: _$constants_562.railBgColor, description: 'Sets the background color of the slider.' }, bordercolor: { valType: 'color', - dflt: _$constants_500.railBorderColor, + dflt: _$constants_562.railBorderColor, role: 'style', description: 'Sets the color of the border enclosing the slider.' }, borderwidth: { valType: 'number', min: 0, - dflt: _$constants_500.railBorderWidth, + dflt: _$constants_562.railBorderWidth, role: 'style', description: 'Sets the width (in px) of the border enclosing the slider.' }, ticklen: { valType: 'number', min: 0, - dflt: _$constants_500.tickLength, + dflt: _$constants_562.tickLength, role: 'style', description: 'Sets the length in pixels of step tick marks' }, tickcolor: { valType: 'color', - dflt: _$constants_500.tickColor, + dflt: _$constants_562.tickColor, role: 'style', description: 'Sets the color of the border enclosing the slider.' }, @@ -71536,7 +73596,7 @@ var _$attributes_499 = __overrideAll_499({ minorticklen: { valType: 'number', min: 0, - dflt: _$constants_500.minorTickLength, + dflt: _$constants_562.minorTickLength, role: 'style', description: 'Sets the length in pixels of minor step tick marks' } @@ -71552,29 +73612,29 @@ var _$attributes_499 = __overrideAll_499({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_499 = require('./attributes'); */; -/* removed: var _$constants_500 = require('./constants'); */; +/* removed: var _$attributes_561 = require('./attributes'); */; +/* removed: var _$constants_562 = require('./constants'); */; -var __name_501 = _$constants_500.name; -var stepAttrs = _$attributes_499.steps; +var __name_563 = _$constants_562.name; +var stepAttrs = _$attributes_561.steps; -var _$slidersDefaults_501 = function slidersDefaults(layoutIn, layoutOut) { +var _$slidersDefaults_563 = function slidersDefaults(layoutIn, layoutOut) { var opts = { - name: __name_501, + name: __name_563, handleItemDefaults: sliderDefaults }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; function sliderDefaults(sliderIn, sliderOut, layoutOut) { function coerce(attr, dflt) { - return _$lib_539.coerce(sliderIn, sliderOut, _$attributes_499, attr, dflt); + return _$lib_601.coerce(sliderIn, sliderOut, _$attributes_561, attr, dflt); } var steps = stepsDefaults(sliderIn, sliderOut); @@ -71586,7 +73646,7 @@ function sliderDefaults(sliderIn, sliderOut, layoutOut) { coerce('x'); coerce('y'); - _$lib_539.noneOrAll(sliderIn, sliderOut, ['x', 'y']); + _$lib_601.noneOrAll(sliderIn, sliderOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); @@ -71599,7 +73659,7 @@ function sliderDefaults(sliderIn, sliderOut, layoutOut) { coerce('pad.b'); coerce('pad.l'); - _$lib_539.coerceFont(coerce, 'font', layoutOut.font); + _$lib_601.coerceFont(coerce, 'font', layoutOut.font); var currentValueIsVisible = coerce('currentvalue.visible'); @@ -71609,7 +73669,7 @@ function sliderDefaults(sliderIn, sliderOut, layoutOut) { coerce('currentvalue.suffix'); coerce('currentvalue.offset'); - _$lib_539.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + _$lib_601.coerceFont(coerce, 'currentvalue.font', sliderOut.font); } coerce('transition.duration'); @@ -71632,7 +73692,7 @@ function stepsDefaults(sliderIn, sliderOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_539.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + return _$lib_601.coerce(valueIn, valueOut, stepAttrs, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -71641,7 +73701,7 @@ function stepsDefaults(sliderIn, sliderOut) { coerce('method'); - if(!_$lib_539.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + if(!_$lib_601.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { continue; } @@ -71664,58 +73724,57 @@ function stepsDefaults(sliderIn, sliderOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; - -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_463 = require('../legend/anchor_utils'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$constants_500 = require('./constants'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_502 = _$alignment_511.LINE_SPACING; -var __FROM_TL_502 = _$alignment_511.FROM_TL; -var __FROM_BR_502 = _$alignment_511.FROM_BR; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_525 = require('../legend/anchor_utils'); */; +/* removed: var _$constants_562 = require('./constants'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_564 = _$alignment_573.LINE_SPACING; +var __FROM_TL_564 = _$alignment_573.FROM_TL; +var __FROM_BR_564 = _$alignment_573.FROM_BR; -var _$draw_502 = function draw(gd) { +var _$draw_564 = function draw(gd) { var fullLayout = gd._fullLayout, sliderData = makeSliderData(fullLayout, gd); // draw a container for *all* sliders: var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_500.containerClassName) + .selectAll('g.' + _$constants_562.containerClassName) .data(sliderData.length > 0 ? [0] : []); sliders.enter().append('g') - .classed(_$constants_500.containerClassName, true) + .classed(_$constants_562.containerClassName, true) .style('cursor', 'ew-resize'); sliders.exit().remove(); // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_502(gd); + if(sliders.exit().size()) __clearPushMargins_564(gd); // Return early if no menus visible: if(sliderData.length === 0) return; - var sliderGroups = sliders.selectAll('g.' + _$constants_500.groupClassName) + var sliderGroups = sliders.selectAll('g.' + _$constants_562.groupClassName) .data(sliderData, keyFunction); sliderGroups.enter().append('g') - .classed(_$constants_500.groupClassName, true); + .classed(_$constants_562.groupClassName, true); sliderGroups.exit().each(function(sliderOpts) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); sliderOpts._commandObserver.remove(); delete sliderOpts._commandObserver; - _$plots_647.autoMargin(gd, _$constants_500.autoMarginIdRoot + sliderOpts._index); + _$plots_709.autoMargin(gd, _$constants_562.autoMarginIdRoot + sliderOpts._index); }); // Find the dimensions of the sliders: @@ -71728,11 +73787,11 @@ var _$draw_502 = function draw(gd) { // If it has fewer than two options, it's not really a slider: if(sliderOpts.steps.length < 2) return; - var gSlider = _$d3_127.select(this); + var gSlider = _$d3_130.select(this); computeLabelSteps(sliderOpts); - _$plots_647.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + _$plots_709.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { // NB: Same as below. This is *not* always the same as sliderOpts since // if a new set of steps comes in, the reference in this callback would // be invalid. We need to refetch it from the slider group, which is @@ -71747,13 +73806,13 @@ var _$draw_502 = function draw(gd) { setActive(gd, gSlider, opts, data.index, false, true); }); - drawSlider(gd, _$d3_127.select(this), sliderOpts); + drawSlider(gd, _$d3_130.select(this), sliderOpts); }); }; // This really only just filters by visibility: function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_500.name], + var contOpts = fullLayout[_$constants_562.name], sliderData = []; for(var i = 0; i < contOpts.length; i++) { @@ -71773,23 +73832,23 @@ function keyFunction(opts) { // Compute the dimensions (mutates sliderOpts): function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_436.tester.selectAll('g.' + _$constants_500.labelGroupClass) + var sliderLabels = _$drawing_498.tester.selectAll('g.' + _$constants_562.labelGroupClass) .data(sliderOpts.steps); sliderLabels.enter().append('g') - .classed(_$constants_500.labelGroupClass, true); + .classed(_$constants_562.labelGroupClass, true); // loop over fake buttons to find width / height var maxLabelWidth = 0; var labelHeight = 0; sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_127.select(this); + var labelGroup = _$d3_130.select(this); var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); var textNode = text.node(); if(textNode) { - var bBox = _$drawing_436.bBox(textNode); + var bBox = _$drawing_498.bBox(textNode); labelHeight = Math.max(labelHeight, bBox.height); maxLabelWidth = Math.max(maxLabelWidth, bBox.width); } @@ -71800,8 +73859,8 @@ function findDimensions(gd, sliderOpts) { var dims = sliderOpts._dims = {}; dims.inputAreaWidth = Math.max( - _$constants_500.railWidth, - _$constants_500.gripHeight + _$constants_562.railWidth, + _$constants_562.gripHeight ); // calculate some overall dimensions - some of these are needed for @@ -71822,9 +73881,9 @@ function findDimensions(gd, sliderOpts) { dims.inputAreaStart = 0; dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - var textableInputLength = dims.inputAreaLength - 2 * _$constants_500.stepInset; + var textableInputLength = dims.inputAreaLength - 2 * _$constants_562.stepInset; var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_500.labelPadding; + var computedSpacePerLabel = maxLabelWidth + _$constants_562.labelPadding; dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); dims.labelHeight = labelHeight; @@ -71837,12 +73896,12 @@ function findDimensions(gd, sliderOpts) { if(sliderOpts.currentvalue.visible) { // Get the dimensions of the current value label: - var dummyGroup = _$drawing_436.tester.append('g'); + var dummyGroup = _$drawing_498.tester.append('g'); sliderLabels.each(function(stepOpts) { var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_436.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_562.lineCount(curValPrefix); + var curValSize = (curValPrefix.node() && _$drawing_498.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_625.lineCount(curValPrefix); dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); @@ -71853,24 +73912,24 @@ function findDimensions(gd, sliderOpts) { dummyGroup.remove(); } - dims.height = dims.currentValueTotalHeight + _$constants_500.tickOffset + sliderOpts.ticklen + _$constants_500.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + dims.height = dims.currentValueTotalHeight + _$constants_562.tickOffset + sliderOpts.ticklen + _$constants_562.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(sliderOpts)) { + if(_$anchor_utils_525.isRightAnchor(sliderOpts)) { dims.lx -= dims.outerLength; xanchor = 'right'; } - if(_$anchor_utils_463.isCenterAnchor(sliderOpts)) { + if(_$anchor_utils_525.isCenterAnchor(sliderOpts)) { dims.lx -= dims.outerLength / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(sliderOpts)) { + if(_$anchor_utils_525.isBottomAnchor(sliderOpts)) { dims.ly -= dims.height; yanchor = 'bottom'; } - if(_$anchor_utils_463.isMiddleAnchor(sliderOpts)) { + if(_$anchor_utils_525.isMiddleAnchor(sliderOpts)) { dims.ly -= dims.height / 2; yanchor = 'middle'; } @@ -71880,13 +73939,13 @@ function findDimensions(gd, sliderOpts) { dims.lx = Math.round(dims.lx); dims.ly = Math.round(dims.ly); - _$plots_647.autoMargin(gd, _$constants_500.autoMarginIdRoot + sliderOpts._index, { + _$plots_709.autoMargin(gd, _$constants_562.autoMarginIdRoot + sliderOpts._index, { x: sliderOpts.x, y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_502[xanchor], - r: dims.outerLength * __FROM_BR_502[xanchor], - b: dims.height * __FROM_BR_502[yanchor], - t: dims.height * __FROM_TL_502[yanchor] + l: dims.outerLength * __FROM_TL_564[xanchor], + r: dims.outerLength * __FROM_BR_564[xanchor], + b: dims.height * __FROM_BR_564[yanchor], + t: dims.height * __FROM_TL_564[yanchor] }); } @@ -71912,7 +73971,7 @@ function drawSlider(gd, sliderGroup, sliderOpts) { var dims = sliderOpts._dims; // Position the rectangle: - _$drawing_436.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + _$drawing_498.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); sliderGroup.call(drawCurrentValue, sliderOpts); @@ -71922,17 +73981,15 @@ function drawSlider(gd, sliderGroup, sliderOpts) { function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { if(!sliderOpts.currentvalue.visible) return; - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); var dims = sliderOpts._dims; + var x0, textAnchor; switch(sliderOpts.currentvalue.xanchor) { case 'right': // This is anchored left and adjusted by the width of the longest label // so that the prefix doesn't move. The goal of this is to emphasize // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_500.currentValueInset - dims.currentValueMaxWidth; + x0 = dims.inputAreaLength - _$constants_562.currentValueInset - dims.currentValueMaxWidth; textAnchor = 'left'; break; case 'center': @@ -71940,17 +73997,17 @@ function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { textAnchor = 'middle'; break; default: - x0 = _$constants_500.currentValueInset; + x0 = _$constants_562.currentValueInset; textAnchor = 'left'; } - text.enter().append('text') - .classed(_$constants_500.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); + var text = _$lib_601.ensureSingle(sliderGroup, 'text', _$constants_562.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; @@ -71965,88 +74022,78 @@ function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { str += sliderOpts.currentvalue.suffix; } - text.call(_$drawing_436.font, sliderOpts.currentvalue.font) + text.call(_$drawing_498.font, sliderOpts.currentvalue.font) .text(str) - .call(_$svg_text_utils_562.convertToTspans, sliderOpts._gd); + .call(_$svg_text_utils_625.convertToTspans, sliderOpts._gd); - var lines = _$svg_text_utils_562.lineCount(text); + var lines = _$svg_text_utils_625.lineCount(text); var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_502; + sliderOpts.currentvalue.font.size * __LINE_SPACING_564; - _$svg_text_utils_562.positionText(text, x0, y0); + _$svg_text_utils_625.positionText(text, x0, y0); return text; } function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_500.gripRectClass) - .data([0]); - - grip.enter().append('rect') - .classed(_$constants_500.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + var grip = _$lib_601.ensureSingle(sliderGroup, 'rect', _$constants_562.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); grip.attr({ - width: _$constants_500.gripWidth, - height: _$constants_500.gripHeight, - rx: _$constants_500.gripRadius, - ry: _$constants_500.gripRadius, + width: _$constants_562.gripWidth, + height: _$constants_562.gripHeight, + rx: _$constants_562.gripRadius, + ry: _$constants_562.gripRadius, }) - .call(_$color_411.stroke, sliderOpts.bordercolor) - .call(_$color_411.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + .call(_$color_473.stroke, sliderOpts.bordercolor) + .call(_$color_473.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); } function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed(_$constants_500.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); + var text = _$lib_601.ensureSingle(item, 'text', _$constants_562.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); - text.call(_$drawing_436.font, sliderOpts.font) + text.call(_$drawing_498.font, sliderOpts.font) .text(data.step.label) - .call(_$svg_text_utils_562.convertToTspans, sliderOpts._gd); + .call(_$svg_text_utils_625.convertToTspans, sliderOpts._gd); return text; } function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_500.labelsClass) - .data([0]); + var labels = _$lib_601.ensureSingle(sliderGroup, 'g', _$constants_562.labelsClass); var dims = sliderOpts._dims; - labels.enter().append('g') - .classed(_$constants_500.labelsClass, true); - - var labelItems = labels.selectAll('g.' + _$constants_500.labelGroupClass) + var labelItems = labels.selectAll('g.' + _$constants_562.labelGroupClass) .data(dims.labelSteps); labelItems.enter().append('g') - .classed(_$constants_500.labelGroupClass, true); + .classed(_$constants_562.labelGroupClass, true); labelItems.exit().remove(); labelItems.each(function(d) { - var item = _$d3_127.select(this); + var item = _$d3_130.select(this); item.call(drawLabel, d, sliderOpts); - _$drawing_436.setTranslate(item, + _$drawing_498.setTranslate(item, normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_500.tickOffset + + _$constants_562.tickOffset + sliderOpts.ticklen + // position is the baseline of the top line of text only, even // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_502 + - _$constants_500.labelOffset + + sliderOpts.font.size * __LINE_SPACING_564 + + _$constants_562.labelOffset + dims.currentValueTotalHeight ); }); @@ -72090,7 +74137,7 @@ function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) if(!_step.method) return; if(_step.execute) { - _$plots_647.executeAPICommand(gd, _step.method, _step.args); + _$plots_709.executeAPICommand(gd, _step.method, _step.args); } sliderGroup._nextMethod = null; @@ -72102,7 +74149,7 @@ function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) function attachGripEvents(item, gd, sliderGroup) { var node = sliderGroup.node(); - var $gd = _$d3_127.select(gd); + var $gd = _$d3_130.select(gd); // NB: This is *not* the same as sliderOpts itself! These callbacks // are in a closure so this array won't actually be correct if the @@ -72117,26 +74164,26 @@ function attachGripEvents(item, gd, sliderGroup) { var sliderOpts = getSliderOpts(); gd.emit('plotly_sliderstart', {slider: sliderOpts}); - var grip = sliderGroup.select('.' + _$constants_500.gripRectClass); + var grip = sliderGroup.select('.' + _$constants_562.gripRectClass); - _$d3_127.event.stopPropagation(); - _$d3_127.event.preventDefault(); - grip.call(_$color_411.fill, sliderOpts.activebgcolor); + _$d3_130.event.stopPropagation(); + _$d3_130.event.preventDefault(); + grip.call(_$color_473.fill, sliderOpts.activebgcolor); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_127.mouse(node)[0]); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_130.mouse(node)[0]); handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); sliderOpts._dragging = true; $gd.on('mousemove', function() { var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_127.mouse(node)[0]); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_130.mouse(node)[0]); handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); }); $gd.on('mouseup', function() { var sliderOpts = getSliderOpts(); sliderOpts._dragging = false; - grip.call(_$color_411.fill, sliderOpts.bgcolor); + grip.call(_$color_473.fill, sliderOpts.bgcolor); $gd.on('mouseup', null); $gd.on('mousemove', null); @@ -72149,12 +74196,12 @@ function attachGripEvents(item, gd, sliderGroup) { } function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_500.tickRectClass) + var tick = sliderGroup.selectAll('rect.' + _$constants_562.tickRectClass) .data(sliderOpts.steps); var dims = sliderOpts._dims; tick.enter().append('rect') - .classed(_$constants_500.tickRectClass, true); + .classed(_$constants_562.tickRectClass, true); tick.exit().remove(); @@ -72165,15 +74212,15 @@ function drawTicks(sliderGroup, sliderOpts) { tick.each(function(d, i) { var isMajor = i % dims.labelStride === 0; - var item = _$d3_127.select(this); + var item = _$d3_130.select(this); item .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_411.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + .call(_$color_473.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - _$drawing_436.setTranslate(item, + _$drawing_498.setTranslate(item, normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_500.tickOffset : _$constants_500.minorTickOffset) + dims.currentValueTotalHeight + (isMajor ? _$constants_562.tickOffset : _$constants_562.minorTickOffset) + dims.currentValueTotalHeight ); }); @@ -72194,7 +74241,7 @@ function computeLabelSteps(sliderOpts) { } function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_500.gripRectClass); + var grip = sliderGroup.select('rect.' + _$constants_562.gripRectClass); var x = normalizedValueToPosition(sliderOpts, position); @@ -72211,78 +74258,70 @@ function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_500.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); + el.attr('transform', 'translate(' + (x - _$constants_562.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); } // Convert a number from [0-1] to a pixel position relative to the slider group container: function normalizedValueToPosition(sliderOpts, normalizedPosition) { var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_500.stepInset + - (dims.inputAreaLength - 2 * _$constants_500.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); + return dims.inputAreaStart + _$constants_562.stepInset + + (dims.inputAreaLength - 2 * _$constants_562.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); } // Convert a position relative to the slider group to a nubmer in [0, 1] function positionToNormalizedValue(sliderOpts, position) { var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_500.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_500.stepInset - 2 * dims.inputAreaStart))); + return Math.min(1, Math.max(0, (position - _$constants_562.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_562.stepInset - 2 * dims.inputAreaStart))); } function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_500.railTouchRectClass) - .data([0]); var dims = sliderOpts._dims; - - rect.enter().append('rect') - .classed(_$constants_500.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + var rect = _$lib_601.ensureSingle(sliderGroup, 'rect', _$constants_562.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); rect.attr({ width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_500.tickOffset + sliderOpts.ticklen + dims.labelHeight) + height: Math.max(dims.inputAreaWidth, _$constants_562.tickOffset + sliderOpts.ticklen + dims.labelHeight) }) - .call(_$color_411.fill, sliderOpts.bgcolor) + .call(_$color_473.fill, sliderOpts.bgcolor) .attr('opacity', 0); - _$drawing_436.setTranslate(rect, 0, dims.currentValueTotalHeight); + _$drawing_498.setTranslate(rect, 0, dims.currentValueTotalHeight); } function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_500.railRectClass) - .data([0]); var dims = sliderOpts._dims; - - rect.enter().append('rect') - .classed(_$constants_500.railRectClass, true); - - var computedLength = dims.inputAreaLength - _$constants_500.railInset * 2; + var computedLength = dims.inputAreaLength - _$constants_562.railInset * 2; + var rect = _$lib_601.ensureSingle(sliderGroup, 'rect', _$constants_562.railRectClass); rect.attr({ width: computedLength, - height: _$constants_500.railWidth, - rx: _$constants_500.railRadius, - ry: _$constants_500.railRadius, + height: _$constants_562.railWidth, + rx: _$constants_562.railRadius, + ry: _$constants_562.railRadius, 'shape-rendering': 'crispEdges' }) - .call(_$color_411.stroke, sliderOpts.bordercolor) - .call(_$color_411.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + .call(_$color_473.stroke, sliderOpts.bordercolor) + .call(_$color_473.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - _$drawing_436.setTranslate(rect, - _$constants_500.railInset, - (dims.inputAreaWidth - _$constants_500.railWidth) * 0.5 + dims.currentValueTotalHeight + _$drawing_498.setTranslate(rect, + _$constants_562.railInset, + (dims.inputAreaWidth - _$constants_562.railWidth) * 0.5 + dims.currentValueTotalHeight ); } -function __clearPushMargins_502(gd) { +function __clearPushMargins_564(gd) { var pushMargins = gd._fullLayout._pushmargin || {}, keys = Object.keys(pushMargins); for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_500.autoMarginIdRoot) !== -1) { - _$plots_647.autoMargin(gd, k); + if(k.indexOf(_$constants_562.autoMarginIdRoot) !== -1) { + _$plots_709.autoMargin(gd, k); } } } @@ -72297,16 +74336,16 @@ function __clearPushMargins_502(gd) { 'use strict'; -/* removed: var _$constants_500 = require('./constants'); */; +/* removed: var _$constants_562 = require('./constants'); */; -var _$sliders_503 = { +var _$sliders_565 = { moduleType: 'component', - name: _$constants_500.name, + name: _$constants_562.name, - layoutAttributes: _$attributes_499, - supplyLayoutDefaults: _$slidersDefaults_501, + layoutAttributes: _$attributes_561, + supplyLayoutDefaults: _$slidersDefaults_563, - draw: _$draw_502 + draw: _$draw_564 }; /** @@ -72319,11 +74358,11 @@ var _$sliders_503 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../color/attributes'); */; -var __extendFlat_505 = _$extend_528.extendFlat; -var __overrideAll_505 = _$edit_types_569.overrideAll; -/* removed: var _$pad_attributes_646 = require('../../plots/pad_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; +var __extendFlat_567 = _$extend_590.extendFlat; +var __overrideAll_567 = _$edit_types_632.overrideAll; +/* removed: var _$pad_attributes_708 = require('../../plots/pad_attributes'); */; var buttonsAttrs = { _isLinkedToArray: 'button', @@ -72375,7 +74414,7 @@ var buttonsAttrs = { } }; -var _$attributes_505 = __overrideAll_505({ +var _$attributes_567 = __overrideAll_567({ _isLinkedToArray: 'updatemenu', _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], @@ -72470,11 +74509,11 @@ var _$attributes_505 = __overrideAll_505({ ].join(' ') }, - pad: __extendFlat_505({}, _$pad_attributes_646, { + pad: __extendFlat_567({}, _$pad_attributes_708, { description: 'Sets the padding around the buttons or dropdown menu.' }), - font: _$font_attributes_611({ + font: _$font_attributes_673({ description: 'Sets the font of the update menu button text.' }), @@ -72485,7 +74524,7 @@ var _$attributes_505 = __overrideAll_505({ }, bordercolor: { valType: 'color', - dflt: _$attributes_410.borderLine, + dflt: _$attributes_472.borderLine, role: 'style', description: 'Sets the color of the border enclosing the update menu.' }, @@ -72511,7 +74550,7 @@ var _$attributes_505 = __overrideAll_505({ 'use strict'; -var _$constants_506 = { +var _$constants_568 = { // layout attribute name name: 'updatemenus', @@ -72589,32 +74628,32 @@ var _$constants_506 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_505 = require('./attributes'); */; -/* removed: var _$constants_506 = require('./constants'); */; +/* removed: var _$attributes_567 = require('./attributes'); */; +/* removed: var _$constants_568 = require('./constants'); */; -var __name_507 = _$constants_506.name; -var __buttonAttrs_507 = _$attributes_505.buttons; +var __name_569 = _$constants_568.name; +var __buttonAttrs_569 = _$attributes_567.buttons; -var _$updateMenusDefaults_507 = function updateMenusDefaults(layoutIn, layoutOut) { +var _$updateMenusDefaults_569 = function updateMenusDefaults(layoutIn, layoutOut) { var opts = { - name: __name_507, + name: __name_569, handleItemDefaults: menuDefaults }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; function menuDefaults(menuIn, menuOut, layoutOut) { function coerce(attr, dflt) { - return _$lib_539.coerce(menuIn, menuOut, _$attributes_505, attr, dflt); + return _$lib_601.coerce(menuIn, menuOut, _$attributes_567, attr, dflt); } - var buttons = __buttonsDefaults_507(menuIn, menuOut); + var buttons = __buttonsDefaults_569(menuIn, menuOut); var visible = coerce('visible', buttons.length > 0); if(!visible) return; @@ -72626,7 +74665,7 @@ function menuDefaults(menuIn, menuOut, layoutOut) { coerce('x'); coerce('y'); - _$lib_539.noneOrAll(menuIn, menuOut, ['x', 'y']); + _$lib_601.noneOrAll(menuIn, menuOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); @@ -72636,21 +74675,21 @@ function menuDefaults(menuIn, menuOut, layoutOut) { coerce('pad.b'); coerce('pad.l'); - _$lib_539.coerceFont(coerce, 'font', layoutOut.font); + _$lib_601.coerceFont(coerce, 'font', layoutOut.font); coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); } -function __buttonsDefaults_507(menuIn, menuOut) { +function __buttonsDefaults_569(menuIn, menuOut) { var buttonsIn = menuIn.buttons || [], buttonsOut = menuOut.buttons = []; var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_539.coerce(buttonIn, buttonOut, __buttonAttrs_507, attr, dflt); + return _$lib_601.coerce(buttonIn, buttonOut, __buttonAttrs_569, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { @@ -72659,7 +74698,7 @@ function __buttonsDefaults_507(menuIn, menuOut) { coerce('method'); - if(!_$lib_539.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + if(!_$lib_601.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { continue; } @@ -72684,14 +74723,14 @@ function __buttonsDefaults_507(menuIn, menuOut) { 'use strict'; -var _$ScrollBox_510 = ScrollBox; +var _$ScrollBox_572 = ScrollBox; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** * Helper class to setup a scroll box @@ -72843,7 +74882,7 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { hbar.enter().append('rect') .classed('scrollbar-horizontal', true) - .call(_$color_411.fill, ScrollBox.barColor); + .call(_$color_473.fill, ScrollBox.barColor); if(needsHorizontalScrollBar) { this.hbar = hbar.attr({ @@ -72884,7 +74923,7 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { vbar.enter().append('rect') .classed('scrollbar-vertical', true) - .call(_$color_411.fill, ScrollBox.barColor); + .call(_$color_473.fill, ScrollBox.barColor); if(needsVerticalScrollBar) { this.vbar = vbar.attr({ @@ -72930,7 +74969,7 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { height: Math.ceil(clipB) - Math.floor(clipT) }); - this.container.call(_$drawing_436.setClipUrl, clipId); + this.container.call(_$drawing_498.setClipUrl, clipId); this.bg.attr({ x: l, @@ -72947,15 +74986,15 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { this.container .on('wheel', null) .on('.drag', null) - .call(_$drawing_436.setClipUrl, null); + .call(_$drawing_498.setClipUrl, null); delete this._clipRect; } // set up drag listeners (if scroll bars are needed) if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_127.behavior.drag() + var onBoxDrag = _$d3_130.behavior.drag() .on('dragstart', function() { - _$d3_127.event.sourceEvent.preventDefault(); + _$d3_130.event.sourceEvent.preventDefault(); }) .on('drag', this._onBoxDrag.bind(this)); @@ -72965,10 +75004,10 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { .on('.drag', null) .call(onBoxDrag); - var onBarDrag = _$d3_127.behavior.drag() + var onBarDrag = _$d3_130.behavior.drag() .on('dragstart', function() { - _$d3_127.event.sourceEvent.preventDefault(); - _$d3_127.event.sourceEvent.stopPropagation(); + _$d3_130.event.sourceEvent.preventDefault(); + _$d3_130.event.sourceEvent.stopPropagation(); }) .on('drag', this._onBarDrag.bind(this)); @@ -73003,7 +75042,7 @@ ScrollBox.prototype.disable = function disable() { this.container .on('wheel', null) .on('.drag', null) - .call(_$drawing_436.setClipUrl, null); + .call(_$drawing_498.setClipUrl, null); delete this._clipRect; } @@ -73034,11 +75073,11 @@ ScrollBox.prototype._onBoxDrag = function onBarDrag() { translateY = this.translateY; if(this.hbar) { - translateX -= _$d3_127.event.dx; + translateX -= _$d3_130.event.dx; } if(this.vbar) { - translateY -= _$d3_127.event.dy; + translateY -= _$d3_130.event.dy; } this.setTranslate(translateX, translateY); @@ -73054,11 +75093,11 @@ ScrollBox.prototype._onBoxWheel = function onBarWheel() { translateY = this.translateY; if(this.hbar) { - translateX += _$d3_127.event.deltaY; + translateX += _$d3_130.event.deltaY; } if(this.vbar) { - translateY += _$d3_127.event.deltaY; + translateY += _$d3_130.event.deltaY; } this.setTranslate(translateX, translateY); @@ -73076,7 +75115,7 @@ ScrollBox.prototype._onBarDrag = function onBarDrag() { if(this.hbar) { var xMin = translateX + this._hbarXMin, xMax = xMin + this._hbarTranslateMax, - x = _$lib_539.constrain(_$d3_127.event.x, xMin, xMax), + x = _$lib_601.constrain(_$d3_130.event.x, xMin, xMax), xf = (x - xMin) / (xMax - xMin); var translateXMax = this.position.w - this._box.w; @@ -73087,7 +75126,7 @@ ScrollBox.prototype._onBarDrag = function onBarDrag() { if(this.vbar) { var yMin = translateY + this._vbarYMin, yMax = yMin + this._vbarTranslateMax, - y = _$lib_539.constrain(_$d3_127.event.y, yMin, yMax), + y = _$lib_601.constrain(_$d3_130.event.y, yMin, yMax), yf = (y - yMin) / (yMax - yMin); var translateYMax = this.position.h - this._box.h; @@ -73110,13 +75149,13 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) var translateXMax = this.position.w - this._box.w, translateYMax = this.position.h - this._box.h; - translateX = _$lib_539.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_539.constrain(translateY || 0, 0, translateYMax); + translateX = _$lib_601.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_601.constrain(translateY || 0, 0, translateYMax); this.translateX = translateX; this.translateY = translateY; - this.container.call(_$drawing_436.setTranslate, + this.container.call(_$drawing_498.setTranslate, this._box.l - this.position.l - translateX, this._box.t - this.position.t - translateY); @@ -73130,7 +75169,7 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) if(this.hbar) { var xf = translateX / translateXMax; - this.hbar.call(_$drawing_436.setTranslate, + this.hbar.call(_$drawing_498.setTranslate, translateX + xf * this._hbarTranslateMax, translateY); } @@ -73138,7 +75177,7 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) if(this.vbar) { var yf = translateY / translateYMax; - this.vbar.call(_$drawing_436.setTranslate, + this.vbar.call(_$drawing_498.setTranslate, translateX, translateY + yf * this._vbarTranslateMax); } @@ -73155,20 +75194,21 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_463 = require('../legend/anchor_utils'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_525 = require('../legend/anchor_utils'); */; -var __LINE_SPACING_508 = _$alignment_511.LINE_SPACING; +var __LINE_SPACING_570 = _$alignment_573.LINE_SPACING; -/* removed: var _$constants_506 = require('./constants'); */; -/* removed: var _$ScrollBox_510 = require('./scrollbox'); */; +/* removed: var _$constants_568 = require('./constants'); */; +/* removed: var _$ScrollBox_572 = require('./scrollbox'); */; -var _$draw_508 = function draw(gd) { +var _$draw_570 = function draw(gd) { var fullLayout = gd._fullLayout, menuData = makeMenuData(fullLayout); @@ -73201,45 +75241,42 @@ var _$draw_508 = function draw(gd) { // draw update menu container var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_506.containerClassName) + .selectAll('g.' + _$constants_568.containerClassName) .data(menuData.length > 0 ? [0] : []); menus.enter().append('g') - .classed(_$constants_506.containerClassName, true) + .classed(_$constants_568.containerClassName, true) .style('cursor', 'pointer'); menus.exit().remove(); // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_508(gd); + if(menus.exit().size()) __clearPushMargins_570(gd); // return early if no update menus are visible if(menuData.length === 0) return; // join header group - var headerGroups = menus.selectAll('g.' + _$constants_506.headerGroupClassName) - .data(menuData, __keyFunction_508); + var headerGroups = menus.selectAll('g.' + _$constants_568.headerGroupClassName) + .data(menuData, __keyFunction_570); headerGroups.enter().append('g') - .classed(_$constants_506.headerGroupClassName, true); + .classed(_$constants_568.headerGroupClassName, true); // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_506.dropdownButtonGroupClassName) - .data([0]); - - gButton.enter().append('g') - .classed(_$constants_506.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + var gButton = _$lib_601.ensureSingle(menus, 'g', _$constants_568.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); // find dimensions before plotting anything (this mutates menuOpts) for(var i = 0; i < menuData.length; i++) { var menuOpts = menuData[i]; - __findDimensions_508(gd, menuOpts); + __findDimensions_570(gd, menuOpts); } // setup scrollbox var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_510(gd, gButton, scrollBoxId); + scrollBox = new _$ScrollBox_572(gd, gButton, scrollBoxId); // remove exiting header, remove dropped buttons and reset margins if(headerGroups.enter().size()) { @@ -73248,33 +75285,33 @@ var _$draw_508 = function draw(gd) { gButton .call(removeAllButtons) - .attr(_$constants_506.menuIndexAttrName, '-1'); + .attr(_$constants_568.menuIndexAttrName, '-1'); } headerGroups.exit().each(function(menuOpts) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); gButton .call(removeAllButtons) - .attr(_$constants_506.menuIndexAttrName, '-1'); + .attr(_$constants_568.menuIndexAttrName, '-1'); - _$plots_647.autoMargin(gd, _$constants_506.autoMarginIdRoot + menuOpts._index); + _$plots_709.autoMargin(gd, _$constants_568.autoMarginIdRoot + menuOpts._index); }); // draw headers! headerGroups.each(function(menuOpts) { - var gHeader = _$d3_127.select(this); + var gHeader = _$d3_130.select(this); var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_647.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_508(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + _$plots_709.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_570(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); }); if(menuOpts.type === 'dropdown') { drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); // if this menu is active, update the dropdown container - if(__isActive_508(gButton, menuOpts)) { + if(__isActive_570(gButton, menuOpts)) { drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); } } else { @@ -73288,7 +75325,7 @@ var _$draw_508 = function draw(gd) { * get only visible menus for display */ function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_506.name]; + var contOpts = fullLayout[_$constants_568.name]; var menuData = []; for(var i = 0; i < contOpts.length; i++) { @@ -73304,19 +75341,19 @@ function makeMenuData(fullLayout) { // it corresponds to the menu index in the user layout update menu container. // Because a menu can be set invisible, // this is a more 'consistent' field than the index in the menuData. -function __keyFunction_508(menuOpts) { +function __keyFunction_570(menuOpts) { return menuOpts._index; } function isFolded(gButton) { - return +gButton.attr(_$constants_506.menuIndexAttrName) === -1; + return +gButton.attr(_$constants_568.menuIndexAttrName) === -1; } -function __isActive_508(gButton, menuOpts) { - return +gButton.attr(_$constants_506.menuIndexAttrName) === menuOpts._index; +function __isActive_570(gButton, menuOpts) { + return +gButton.attr(_$constants_568.menuIndexAttrName) === menuOpts._index; } -function __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { +function __setActive_570(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { // update 'active' attribute in menuOpts menuOpts._input.active = menuOpts.active = buttonIndex; @@ -73325,7 +75362,7 @@ function __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, } else if(menuOpts.type === 'dropdown') { // fold up buttons and redraw header - gButton.attr(_$constants_506.menuIndexAttrName, '-1'); + gButton.attr(_$constants_568.menuIndexAttrName, '-1'); drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); @@ -73336,40 +75373,34 @@ function __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, } function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_506.headerClassName) - .data([0]); - var dims = menuOpts._dims; - - header.enter().append('g') - .classed(_$constants_506.headerClassName, true) - .style('pointer-events', 'all'); + var header = _$lib_601.ensureSingle(gHeader, 'g', _$constants_568.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_506.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_568.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; header .call(drawItem, menuOpts, headerOpts, gd) .call(setItemPosition, menuOpts, posOpts, positionOverrides); // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_506.headerArrowClassName) - .data([0]); - - arrow.enter().append('text') - .classed(_$constants_506.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_436.font, menuOpts.font) - .text(_$constants_506.arrowSymbol[menuOpts.direction]); + var arrow = _$lib_601.ensureSingle(gHeader, 'text', _$constants_568.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_498.font, menuOpts.font) + .text(_$constants_568.arrowSymbol[menuOpts.direction]); + }); arrow.attr({ - x: dims.headerWidth - _$constants_506.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_506.textOffsetY + menuOpts.pad.t + x: dims.headerWidth - _$constants_568.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_568.textOffsetY + menuOpts.pad.t }); header.on('click', function() { @@ -73379,8 +75410,8 @@ function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { // if this menu is active, fold the dropdown container // otherwise, make this menu active gButton.attr( - _$constants_506.menuIndexAttrName, - __isActive_508(gButton, menuOpts) ? + _$constants_568.menuIndexAttrName, + __isActive_570(gButton, menuOpts) ? -1 : String(menuOpts._index) ); @@ -73397,7 +75428,7 @@ function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { }); // translate header group - _$drawing_436.setTranslate(gHeader, dims.lx, dims.ly); + _$drawing_498.setTranslate(gHeader, dims.lx, dims.ly); } function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { @@ -73413,7 +75444,7 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { menuOpts.buttons : []; - var klass = menuOpts.type === 'dropdown' ? _$constants_506.dropdownButtonClassName : _$constants_506.buttonClassName; + var klass = menuOpts.type === 'dropdown' ? _$constants_568.dropdownButtonClassName : _$constants_568.buttonClassName; var buttons = gButton.selectAll('g.' + klass) .data(buttonData); @@ -73443,25 +75474,25 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { if(menuOpts.type === 'dropdown') { if(isVertical) { - y0 = dims.headerHeight + _$constants_506.gapButtonHeader; + y0 = dims.headerHeight + _$constants_568.gapButtonHeader; } else { - x0 = dims.headerWidth + _$constants_506.gapButtonHeader; + x0 = dims.headerWidth + _$constants_568.gapButtonHeader; } } if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_506.gapButtonHeader + _$constants_506.gapButton - dims.openHeight; + y0 = -_$constants_568.gapButtonHeader + _$constants_568.gapButton - dims.openHeight; } if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_506.gapButtonHeader + _$constants_506.gapButton - dims.openWidth; + x0 = -_$constants_568.gapButtonHeader + _$constants_568.gapButton - dims.openWidth; } var posOpts = { x: dims.lx + x0 + menuOpts.pad.l, y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_506.gapButton, - xPad: _$constants_506.gapButton, + yPad: _$constants_568.gapButton, + xPad: _$constants_568.gapButton, index: 0, }; @@ -73471,7 +75502,7 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { }; buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); button .call(drawItem, menuOpts, buttonOpts, gd) @@ -73479,12 +75510,12 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { button.on('click', function() { // skip `dragend` events - if(_$d3_127.event.defaultPrevented) return; + if(_$d3_130.event.defaultPrevented) return; - __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + __setActive_570(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); if(buttonOpts.execute) { - _$plots_647.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + _$plots_709.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); } gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); @@ -73535,13 +75566,13 @@ function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { if(isVertical) { translateY = 0; for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_506.gapButton; + translateY += dims.heights[i] + _$constants_568.gapButton; } } else { translateX = 0; for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_506.gapButton; + translateX += dims.widths[i] + _$constants_568.gapButton; } } @@ -73593,64 +75624,58 @@ function drawItem(item, menuOpts, itemOpts, gd) { } function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed(_$constants_506.itemRectClassName, true) - .attr({ - rx: _$constants_506.rx, - ry: _$constants_506.ry, + var rect = _$lib_601.ensureSingle(item, 'rect', _$constants_568.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_568.rx, + ry: _$constants_568.ry, 'shape-rendering': 'crispEdges' }); + }); - rect.call(_$color_411.stroke, menuOpts.bordercolor) - .call(_$color_411.fill, menuOpts.bgcolor) + rect.call(_$color_473.stroke, menuOpts.bordercolor) + .call(_$color_473.fill, menuOpts.bgcolor) .style('stroke-width', menuOpts.borderwidth + 'px'); } function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed(_$constants_506.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + var text = _$lib_601.ensureSingle(item, 'text', _$constants_568.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); - text.call(_$drawing_436.font, menuOpts.font) + text.call(_$drawing_498.font, menuOpts.font) .text(itemOpts.label) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); } function styleButtons(buttons, menuOpts) { var active = menuOpts.active; buttons.each(function(buttonOpts, i) { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_506.itemRectClassName) - .call(_$color_411.fill, _$constants_506.activeColor); + button.select('rect.' + _$constants_568.itemRectClassName) + .call(_$color_473.fill, _$constants_568.activeColor); } }); } function styleOnMouseOver(item) { - item.select('rect.' + _$constants_506.itemRectClassName) - .call(_$color_411.fill, _$constants_506.hoverColor); + item.select('rect.' + _$constants_568.itemRectClassName) + .call(_$color_473.fill, _$constants_568.hoverColor); } function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_506.itemRectClassName) - .call(_$color_411.fill, menuOpts.bgcolor); + item.select('rect.' + _$constants_568.itemRectClassName) + .call(_$color_473.fill, menuOpts.bgcolor); } // find item dimensions (this mutates menuOpts) -function __findDimensions_508(gd, menuOpts) { +function __findDimensions_570(gd, menuOpts) { var dims = menuOpts._dims = { width1: 0, height1: 0, @@ -73664,30 +75689,30 @@ function __findDimensions_508(gd, menuOpts) { ly: 0 }; - var fakeButtons = _$drawing_436.tester.selectAll('g.' + _$constants_506.dropdownButtonClassName) + var fakeButtons = _$drawing_498.tester.selectAll('g.' + _$constants_568.dropdownButtonClassName) .data(menuOpts.buttons); fakeButtons.enter().append('g') - .classed(_$constants_506.dropdownButtonClassName, true); + .classed(_$constants_568.dropdownButtonClassName, true); var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; // loop over fake buttons to find width / height fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); button.call(drawItem, menuOpts, buttonOpts, gd); - var text = button.select('.' + _$constants_506.itemTextClassName); + var text = button.select('.' + _$constants_568.itemTextClassName); // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_436.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_506.textPadX, _$constants_506.minWidth); + var tWidth = text.node() && _$drawing_498.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_568.textPadX, _$constants_568.minWidth); // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_508; - var tLines = _$svg_text_utils_562.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_506.minHeight) + _$constants_506.textOffsetY; + var tHeight = menuOpts.font.size * __LINE_SPACING_570; + var tLines = _$svg_text_utils_625.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_568.minHeight) + _$constants_568.textOffsetY; hEff = Math.ceil(hEff); wEff = Math.ceil(wEff); @@ -73704,34 +75729,34 @@ function __findDimensions_508(gd, menuOpts) { if(isVertical) { dims.totalWidth = Math.max(dims.totalWidth, wEff); dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_506.gapButton; - dims.openHeight += hEff + _$constants_506.gapButton; + dims.totalHeight += hEff + _$constants_568.gapButton; + dims.openHeight += hEff + _$constants_568.gapButton; } else { - dims.totalWidth += wEff + _$constants_506.gapButton; - dims.openWidth += wEff + _$constants_506.gapButton; + dims.totalWidth += wEff + _$constants_568.gapButton; + dims.openWidth += wEff + _$constants_568.gapButton; dims.totalHeight = Math.max(dims.totalHeight, hEff); dims.openHeight = dims.totalHeight; } }); if(isVertical) { - dims.totalHeight -= _$constants_506.gapButton; + dims.totalHeight -= _$constants_568.gapButton; } else { - dims.totalWidth -= _$constants_506.gapButton; + dims.totalWidth -= _$constants_568.gapButton; } - dims.headerWidth = dims.width1 + _$constants_506.arrowPadX; + dims.headerWidth = dims.width1 + _$constants_568.arrowPadX; dims.headerHeight = dims.height1; if(menuOpts.type === 'dropdown') { if(isVertical) { - dims.width1 += _$constants_506.arrowPadX; + dims.width1 += _$constants_568.arrowPadX; dims.totalHeight = dims.height1; } else { dims.totalWidth = dims.width1; } - dims.totalWidth += _$constants_506.arrowPadX; + dims.totalWidth += _$constants_568.arrowPadX; } fakeButtons.remove(); @@ -73744,21 +75769,21 @@ function __findDimensions_508(gd, menuOpts) { dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(menuOpts)) { + if(_$anchor_utils_525.isRightAnchor(menuOpts)) { dims.lx -= paddedWidth; xanchor = 'right'; } - if(_$anchor_utils_463.isCenterAnchor(menuOpts)) { + if(_$anchor_utils_525.isCenterAnchor(menuOpts)) { dims.lx -= paddedWidth / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(menuOpts)) { + if(_$anchor_utils_525.isBottomAnchor(menuOpts)) { dims.ly -= paddedHeight; yanchor = 'bottom'; } - if(_$anchor_utils_463.isMiddleAnchor(menuOpts)) { + if(_$anchor_utils_525.isMiddleAnchor(menuOpts)) { dims.ly -= paddedHeight / 2; yanchor = 'middle'; } @@ -73768,7 +75793,7 @@ function __findDimensions_508(gd, menuOpts) { dims.lx = Math.round(dims.lx); dims.ly = Math.round(dims.ly); - _$plots_647.autoMargin(gd, _$constants_506.autoMarginIdRoot + menuOpts._index, { + _$plots_709.autoMargin(gd, _$constants_568.autoMarginIdRoot + menuOpts._index, { x: menuOpts.x, y: menuOpts.y, l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), @@ -73781,13 +75806,13 @@ function __findDimensions_508(gd, menuOpts) { // set item positions (mutates posOpts) function setItemPosition(item, menuOpts, posOpts, overrideOpts) { overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_506.itemRectClassName); - var text = item.select('.' + _$constants_506.itemTextClassName); + var rect = item.select('.' + _$constants_568.itemRectClassName); + var text = item.select('.' + _$constants_568.itemTextClassName); var borderWidth = menuOpts.borderwidth; var index = posOpts.index; var dims = menuOpts._dims; - _$drawing_436.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + _$drawing_498.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); @@ -73799,12 +75824,12 @@ function setItemPosition(item, menuOpts, posOpts, overrideOpts) { height: finalHeight }); - var tHeight = menuOpts.font.size * __LINE_SPACING_508; - var tLines = _$svg_text_utils_562.lineCount(text); + var tHeight = menuOpts.font.size * __LINE_SPACING_570; + var tLines = _$svg_text_utils_625.lineCount(text); var spanOffset = ((tLines - 1) * tHeight / 2); - _$svg_text_utils_562.positionText(text, _$constants_506.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_506.textOffsetY); + _$svg_text_utils_625.positionText(text, _$constants_568.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_568.textOffsetY); if(isVertical) { posOpts.y += dims.heights[index] + posOpts.yPad; @@ -73816,18 +75841,18 @@ function setItemPosition(item, menuOpts, posOpts, overrideOpts) { } function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_506.dropdownButtonClassName).remove(); + gButton.selectAll('g.' + _$constants_568.dropdownButtonClassName).remove(); } -function __clearPushMargins_508(gd) { +function __clearPushMargins_570(gd) { var pushMargins = gd._fullLayout._pushmargin || {}; var keys = Object.keys(pushMargins); for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_506.autoMarginIdRoot) !== -1) { - _$plots_647.autoMargin(gd, k); + if(k.indexOf(_$constants_568.autoMarginIdRoot) !== -1) { + _$plots_709.autoMargin(gd, k); } } } @@ -73842,19 +75867,19 @@ function __clearPushMargins_508(gd) { 'use strict'; -/* removed: var _$constants_506 = require('./constants'); */; +/* removed: var _$constants_568 = require('./constants'); */; -var _$updatemenus_509 = { +var _$updatemenus_571 = { moduleType: 'component', - name: _$constants_506.name, + name: _$constants_568.name, - layoutAttributes: _$attributes_505, - supplyLayoutDefaults: _$updateMenusDefaults_507, + layoutAttributes: _$attributes_567, + supplyLayoutDefaults: _$updateMenusDefaults_569, - draw: _$draw_508 + draw: _$draw_570 }; -var _$mathjax_config_521 = {}; +var _$mathjax_config_582 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -73871,7 +75896,7 @@ var _$mathjax_config_521 = {}; * Check and configure MathJax */ if(typeof MathJax !== 'undefined') { - _$mathjax_config_521.MathJax = true; + _$mathjax_config_582.MathJax = true; MathJax.Hub.Config({ messageStyle: 'none', @@ -73884,7 +75909,7 @@ if(typeof MathJax !== 'undefined') { MathJax.Hub.Configured(); } else { - _$mathjax_config_521.MathJax = false; + _$mathjax_config_582.MathJax = false; } /** @@ -73898,8 +75923,8 @@ if(typeof MathJax !== 'undefined') { 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plot_config_574 = require('../plot_api/plot_config'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plot_config_637 = require('../plot_api/plot_config'); */; /** @@ -73919,8 +75944,8 @@ function copyArgArray(gd, args) { if(arg === gd) copy[i] = arg; else if(typeof arg === 'object') { copy[i] = Array.isArray(arg) ? - _$lib_539.extendDeep([], arg) : - _$lib_539.extendDeepAll({}, arg); + _$lib_601.extendDeep([], arg) : + _$lib_601.extendDeepAll({}, arg); } else copy[i] = arg; } @@ -73934,7 +75959,7 @@ function copyArgArray(gd, args) { // ----------------------------------------------------- -var __queue_553 = {}; +var __queue_616 = {}; // TODO: disable/enable undo and redo buttons appropriately @@ -73947,7 +75972,7 @@ var __queue_553 = {}; * @param redoFunc Function to redo this operation * @param redoArgs Args to supply redoFunc with */ -__queue_553.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { +__queue_616.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { var queueObj, queueIndex; @@ -73980,7 +76005,7 @@ __queue_553.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { queueObj.redo.args.push(redoArgs); } - if(gd.undoQueue.queue.length > _$plot_config_574.queueLength) { + if(gd.undoQueue.queue.length > _$plot_config_637.queueLength) { gd.undoQueue.queue.shift(); gd.undoQueue.index--; } @@ -73991,7 +76016,7 @@ __queue_553.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { * * @param gd */ -__queue_553.startSequence = function(gd) { +__queue_616.startSequence = function(gd) { gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; gd.undoQueue.sequence = true; gd.undoQueue.beginSequence = true; @@ -74004,7 +76029,7 @@ __queue_553.startSequence = function(gd) { * * @param gd */ -__queue_553.stopSequence = function(gd) { +__queue_616.stopSequence = function(gd) { gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; gd.undoQueue.sequence = false; gd.undoQueue.beginSequence = false; @@ -74015,7 +76040,7 @@ __queue_553.stopSequence = function(gd) { * * @param gd */ -__queue_553.undo = function undo(gd) { +__queue_616.undo = function undo(gd) { var queueObj, i; if(gd.framework && gd.framework.isPolar) { @@ -74037,7 +76062,7 @@ __queue_553.undo = function undo(gd) { // this sequence keeps things from adding to the queue during undo/redo gd.undoQueue.inSequence = true; for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_553.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + __queue_616.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); } gd.undoQueue.inSequence = false; gd.autoplay = false; @@ -74048,7 +76073,7 @@ __queue_553.undo = function undo(gd) { * * @param gd */ -__queue_553.redo = function redo(gd) { +__queue_616.redo = function redo(gd) { var queueObj, i; if(gd.framework && gd.framework.isPolar) { @@ -74067,7 +76092,7 @@ __queue_553.redo = function redo(gd) { // this sequence keeps things from adding to the queue during undo/redo gd.undoQueue.inSequence = true; for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_553.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + __queue_616.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); } gd.undoQueue.inSequence = false; gd.autoplay = false; @@ -74085,7 +76110,7 @@ __queue_553.redo = function redo(gd) { * @param func * @param args */ -__queue_553.plotDo = function(gd, func, args) { +__queue_616.plotDo = function(gd, func, args) { gd.autoplay = true; // this *won't* copy gd and it preserves `undefined` properties! @@ -74095,7 +76120,7 @@ __queue_553.plotDo = function(gd, func, args) { func.apply(null, args); }; -var _$queue_553 = __queue_553; +var _$queue_616 = __queue_616; /** * Copyright 2012-2018, Plotly, Inc. @@ -74107,7 +76132,7 @@ var _$queue_553 = __queue_553; 'use strict'; -var _$localeEnUs_566 = { +var _$localeEnUs_629 = { moduleType: 'locale', name: 'en-US', dictionary: { @@ -74128,14 +76153,14 @@ var _$localeEnUs_566 = { 'use strict'; -var _$localeEn_567 = { +var _$localeEn_630 = { moduleType: 'locale', name: 'en', dictionary: { 'Click to enter Colorscale title': 'Click to enter Colourscale title' }, format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], + days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], months: [ 'January', 'February', 'March', 'April', 'May', 'June', @@ -74160,7 +76185,7 @@ var _$localeEn_567 = { } }; -var _$fromQuat_170 = fromQuat; +var _$fromQuat_227 = fromQuat; /** * Creates a matrix from a quaternion rotation. @@ -74207,7 +76232,7 @@ function fromQuat(out, q) { return out; }; -var _$helpers_570 = {}; +var _$helpers_633 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -74219,22 +76244,22 @@ var _$helpers_570 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_170 = require('gl-mat4/fromQuat'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_227 = require('gl-mat4/fromQuat'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$axis_ids_587 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_587.cleanId; -var getFromTrace = _$axis_ids_587.getFromTrace; -/* removed: var _$color_411 = require('../components/color'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +/* removed: var _$axis_ids_650 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_650.cleanId; +var getFromTrace = _$axis_ids_650.getFromTrace; +/* removed: var _$color_473 = require('../components/color'); */; // clear the promise queue if one of them got rejected -_$helpers_570.clearPromiseQueue = function(gd) { +_$helpers_633.clearPromiseQueue = function(gd) { if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_539.log('Clearing previous rejected promises from queue.'); + _$lib_601.log('Clearing previous rejected promises from queue.'); } gd._promises = []; @@ -74243,7 +76268,7 @@ _$helpers_570.clearPromiseQueue = function(gd) { // make a few changes to the layout right away // before it gets used for anything // backward compatibility and cleanup of nonstandard options -_$helpers_570.cleanLayout = function(layout) { +_$helpers_633.cleanLayout = function(layout) { var i, j; if(!layout) layout = {}; @@ -74262,8 +76287,8 @@ _$helpers_570.cleanLayout = function(layout) { delete layout.scene1; } - var axisAttrRegex = (_$plots_647.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_647.subplotsRegistry.gl3d || {}).attrRegex; + var axisAttrRegex = (_$plots_709.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_709.subplotsRegistry.gl3d || {}).attrRegex; var keys = Object.keys(layout); for(i = 0; i < keys.length; i++) { @@ -74314,7 +76339,7 @@ _$helpers_570.cleanLayout = function(layout) { var rotation = cameraposition[0], center = cameraposition[1], radius = cameraposition[2], - mat = _$fromQuat_170([], rotation), + mat = _$fromQuat_227([], rotation), eye = []; for(j = 0; j < 3; ++j) { @@ -74336,7 +76361,7 @@ _$helpers_570.cleanLayout = function(layout) { for(i = 0; i < annotationsLen; i++) { var ann = layout.annotations[i]; - if(!_$lib_539.isPlainObject(ann)) continue; + if(!_$lib_601.isPlainObject(ann)) continue; if(ann.ref) { if(ann.ref === 'paper') { @@ -74358,7 +76383,7 @@ _$helpers_570.cleanLayout = function(layout) { for(i = 0; i < shapesLen; i++) { var shape = layout.shapes[i]; - if(!_$lib_539.isPlainObject(shape)) continue; + if(!_$lib_601.isPlainObject(shape)) continue; cleanAxRef(shape, 'xref'); cleanAxRef(shape, 'yref'); @@ -74393,7 +76418,7 @@ _$helpers_570.cleanLayout = function(layout) { // sanitize rgb(fractions) and rgba(fractions) that old tinycolor // supported, but new tinycolor does not because they're not valid css - _$color_411.clean(layout); + _$color_473.clean(layout); return layout; }; @@ -74414,7 +76439,7 @@ function cleanAxRef(container, attr) { * Important: if you're going to add something here that modifies a data array, * update it in place so the new array === the old one. */ -_$helpers_570.cleanData = function(data, existingData) { +_$helpers_633.cleanData = function(data, existingData) { // Enforce unique IDs var suids = [], // seen uids --- so we can weed out incoming repeats uids = data.concat(Array.isArray(existingData) ? existingData : []) @@ -74430,10 +76455,10 @@ _$helpers_570.cleanData = function(data, existingData) { var newUid; for(i = 0; i < 100; i++) { - newUid = _$lib_539.randstr(uids); + newUid = _$lib_601.randstr(uids); if(suids.indexOf(newUid) === -1) break; } - trace.uid = _$lib_539.randstr(uids); + trace.uid = _$lib_601.randstr(uids); uids.push(trace.uid); } // keep track of already seen uids, so that if there are @@ -74451,29 +76476,29 @@ _$helpers_570.cleanData = function(data, existingData) { // error_y.opacity is obsolete - merge into color if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_411.defaults, + var dc = _$color_473.defaults, yeColor = trace.error_y.color || - (_$registry_668.traceIs(trace, 'bar') ? _$color_411.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_411.addOpacity( - _$color_411.rgb(yeColor), - _$color_411.opacity(yeColor) * trace.error_y.opacity); + (_$registry_731.traceIs(trace, 'bar') ? _$color_473.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_473.addOpacity( + _$color_473.rgb(yeColor), + _$color_473.opacity(yeColor) * trace.error_y.opacity); delete trace.error_y.opacity; } // convert bardir to orientation, and put the data into // the axes it's eventually going to be used with if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_668.traceIs(trace, 'bar') || + if(trace.bardir === 'h' && (_$registry_731.traceIs(trace, 'bar') || trace.type.substr(0, 9) === 'histogram')) { trace.orientation = 'h'; - _$helpers_570.swapXYData(trace); + _$helpers_633.swapXYData(trace); } delete trace.bardir; } // now we have only one 1D histogram type, and whether // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_570.swapXYData(trace); + if(trace.type === 'histogramy') _$helpers_633.swapXYData(trace); if(trace.type === 'histogramx' || trace.type === 'histogramy') { trace.type = 'histogram'; } @@ -74493,11 +76518,11 @@ _$helpers_570.cleanData = function(data, existingData) { if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); // scene ids scene1 -> scene - if(_$registry_668.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_647.subplotsRegistry.gl3d.cleanId(trace.scene); + if(_$registry_731.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_709.subplotsRegistry.gl3d.cleanId(trace.scene); } - if(!_$registry_668.traceIs(trace, 'pie') && !_$registry_668.traceIs(trace, 'bar')) { + if(!_$registry_731.traceIs(trace, 'pie') && !_$registry_731.traceIs(trace, 'bar')) { if(Array.isArray(trace.textposition)) { for(i = 0; i < trace.textposition.length; i++) { trace.textposition[i] = cleanTextPosition(trace.textposition[i]); @@ -74509,24 +76534,24 @@ _$helpers_570.cleanData = function(data, existingData) { } // fix typo in colorscale definition - if(_$registry_668.traceIs(trace, '2dMap')) { + if(_$registry_731.traceIs(trace, '2dMap')) { if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; } - if(_$registry_668.traceIs(trace, 'markerColorscale') && trace.marker) { + if(_$registry_731.traceIs(trace, 'markerColorscale') && trace.marker) { var cont = trace.marker; if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; } // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_539.isPlainObject(trace.contours)) { + if(trace.type === 'surface' && _$lib_601.isPlainObject(trace.contours)) { var dims = ['x', 'y', 'z']; for(i = 0; i < dims.length; i++) { var opts = trace.contours[dims[i]]; - if(!_$lib_539.isPlainObject(opts)) continue; + if(!_$lib_601.isPlainObject(opts)) continue; if(opts.highlightColor) { opts.highlightcolor = opts.highlightColor; @@ -74540,6 +76565,32 @@ _$helpers_570.cleanData = function(data, existingData) { } } + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); + + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names + + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } + // transforms backward compatibility fixes if(Array.isArray(trace.transforms)) { var transforms = trace.transforms; @@ -74547,7 +76598,7 @@ _$helpers_570.cleanData = function(data, existingData) { for(i = 0; i < transforms.length; i++) { var transform = transforms[i]; - if(!_$lib_539.isPlainObject(transform)) continue; + if(!_$lib_601.isPlainObject(transform)) continue; switch(transform.type) { case 'filter': @@ -74594,10 +76645,42 @@ _$helpers_570.cleanData = function(data, existingData) { // sanitize rgb(fractions) and rgba(fractions) that old tinycolor // supported, but new tinycolor does not because they're not valid css - _$color_411.clean(trace); + _$color_473.clean(trace); } }; +function cleanFinanceDir(dirContainer) { + if(!_$lib_601.isPlainObject(dirContainer)) return false; + + var dirName = dirContainer.name; + + delete dirContainer.name; + delete dirContainer.showlegend; + + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); +} + +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; + + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; + + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } + + var out = name1.substr(0, i); + return out.trim(); +} + // textposition - support partial attributes (ie just 'top') // and incorrect use of middle / center etc. function cleanTextPosition(textposition) { @@ -74620,9 +76703,9 @@ function emptyContainer(outer, innerStr) { // swap all the data and data attributes associated with x and y -_$helpers_570.swapXYData = function(trace) { +_$helpers_633.swapXYData = function(trace) { var i; - _$lib_539.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + _$lib_601.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { if(trace.transpose) delete trace.transpose; else trace.transpose = true; @@ -74631,9 +76714,9 @@ _$helpers_570.swapXYData = function(trace) { var errorY = trace.error_y, copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : !(errorY.color || errorY.thickness || errorY.width); - _$lib_539.swapAttrs(trace, ['error_?.copy_ystyle']); + _$lib_601.swapAttrs(trace, ['error_?.copy_ystyle']); if(copyYstyle) { - _$lib_539.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + _$lib_601.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); } } if(typeof trace.hoverinfo === 'string') { @@ -74647,8 +76730,8 @@ _$helpers_570.swapXYData = function(trace) { }; // coerce traceIndices input to array of trace indices -_$helpers_570.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_139(traceIndices)) { +_$helpers_633.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_196(traceIndices)) { return [traceIndices]; } else if(!Array.isArray(traceIndices) || !traceIndices.length) { @@ -74670,20 +76753,20 @@ _$helpers_570.coerceTraceIndices = function(gd, traceIndices) { * undo hash (N.B. undoit may be mutated here). * */ -_$helpers_570.manageArrayContainers = function(np, newVal, undoit) { +_$helpers_633.manageArrayContainers = function(np, newVal, undoit) { var obj = np.obj, parts = np.parts, pLength = parts.length, pLast = parts[pLength - 1]; - var pLastIsNumber = _$fastIsnumeric_139(pLast); + var pLastIsNumber = _$fastIsnumeric_196(pLast); // delete item if(pLastIsNumber && newVal === null) { // Clear item in array container when new value is null var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_539.nestedProperty(obj, contPath).get(); + cont = _$lib_601.nestedProperty(obj, contPath).get(); cont.splice(pLast, 1); // Note that nested property clears null / undefined at end of @@ -74730,7 +76813,7 @@ function getParent(attr) { * @returns {Boolean} * is a parent of attr present in aobj? */ -_$helpers_570.hasParent = function(aobj, attr) { +_$helpers_633.hasParent = function(aobj, attr) { var attrParent = getParent(attr); while(attrParent) { if(attrParent in aobj) return true; @@ -74747,12 +76830,12 @@ _$helpers_570.hasParent = function(aobj, attr) { * @param {object} layoutUpdate: any update being done concurrently to the layout, * which may supercede clearing the axis types */ -var __axLetters_570 = ['x', 'y', 'z']; -_$helpers_570.clearAxisTypes = function(gd, traces, layoutUpdate) { +var __axLetters_633 = ['x', 'y', 'z']; +_$helpers_633.clearAxisTypes = function(gd, traces, layoutUpdate) { for(var i = 0; i < traces.length; i++) { var trace = gd._fullData[i]; for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_570[j]); + var ax = getFromTrace(gd, trace, __axLetters_633[j]); // do not clear log type - that's never an auto result so must have been intentional if(ax && ax.type !== 'log') { @@ -74765,14 +76848,14 @@ _$helpers_570.clearAxisTypes = function(gd, traces, layoutUpdate) { var typeAttr = axAttr + '.type'; if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_539.nestedProperty(gd.layout, typeAttr).set(null); + _$lib_601.nestedProperty(gd.layout, typeAttr).set(null); } } } } }; -_$helpers_570.clearAxisAutomargins = function(gd) { +_$helpers_633.clearAxisAutomargins = function(gd) { var keys = Object.keys(gd._fullLayout._pushmargin); for(var i = 0; i < keys.length; i++) { if(keys[i].indexOf('automargin') !== -1) { @@ -74781,7 +76864,7 @@ _$helpers_570.clearAxisAutomargins = function(gd) { } }; -var _$manage_arrays_572 = {}; +var _$manage_arrays_635 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -74793,21 +76876,21 @@ var _$manage_arrays_572 = {}; 'use strict'; -/* removed: var _$nestedProperty_547 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_541 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_548 = require('../lib/noop'); */; -/* removed: var _$loggers_544 = require('../lib/loggers'); */; -var sorterAsc = _$search_557.sorterAsc; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$nestedProperty_609 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_603 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_610 = require('../lib/noop'); */; +/* removed: var _$loggers_606 = require('../lib/loggers'); */; +var sorterAsc = _$search_620.sorterAsc; +/* removed: var _$registry_731 = require('../registry'); */; -_$manage_arrays_572.containerArrayMatch = _$containerArrayMatch_568; +_$manage_arrays_635.containerArrayMatch = _$containerArrayMatch_631; -var isAddVal = _$manage_arrays_572.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_541(val); +var isAddVal = _$manage_arrays_635.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_603(val); }; -var isRemoveVal = _$manage_arrays_572.isRemoveVal = function isRemoveVal(val) { +var isRemoveVal = _$manage_arrays_635.isRemoveVal = function isRemoveVal(val) { return val === null || val === 'remove'; }; @@ -74854,19 +76937,19 @@ var isRemoveVal = _$manage_arrays_572.isRemoveVal = function isRemoveVal(val) { * @returns {bool} `true` if it managed to complete drawing of the changes * `false` would mean the parent should replot. */ -_$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { +_$manage_arrays_635.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { var componentType = np.astr, - supplyComponentDefaults = _$registry_668.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_668.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_668.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_548) || - (draw === _$noop_548), + supplyComponentDefaults = _$registry_731.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_731.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_731.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_610) || + (draw === _$noop_610), layout = gd.layout, fullLayout = gd._fullLayout; if(edits['']) { if(Object.keys(edits).length > 1) { - _$loggers_544.warn('Full array edits are incompatible with other edits', + _$loggers_606.warn('Full array edits are incompatible with other edits', componentType); } @@ -74875,7 +76958,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha if(isRemoveVal(fullVal)) np.set(null); else if(Array.isArray(fullVal)) np.set(fullVal); else { - _$loggers_544.warn('Unrecognized full array edit value', componentType, fullVal); + _$loggers_606.warn('Unrecognized full array edit value', componentType, fullVal); return true; } @@ -74894,7 +76977,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha // redoing supplyDefaults // TODO: this assumes componentArray is in gd.layout - which will not be // true after we extend this to restyle - componentArrayFull = _$nestedProperty_547(fullLayout, componentType).get(); + componentArrayFull = _$nestedProperty_609(fullLayout, componentType).get(); var deletes = [], firstIndexChange = -1, @@ -74916,13 +76999,13 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha adding = isAddVal(objVal); if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_544.warn('index out of range', componentType, componentNum); + _$loggers_606.warn('index out of range', componentType, componentNum); continue; } if(objVal !== undefined) { if(objKeys.length > 1) { - _$loggers_544.warn( + _$loggers_606.warn( 'Insertion & removal are incompatible with edits to the same index.', componentType, componentNum); } @@ -74936,7 +77019,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } else { - _$loggers_544.warn('Unrecognized full object edit value', + _$loggers_606.warn('Unrecognized full object edit value', componentType, componentNum, objVal); } @@ -74944,7 +77027,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha } else { for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_547(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); + _$nestedProperty_609(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } } @@ -74966,7 +77049,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha // finally draw all the components we need to // if we added or removed any, redraw all after it - if(drawOne !== _$noop_548) { + if(drawOne !== _$noop_610) { var indicesToDraw; if(firstIndexChange === -1) { // there's no re-indexing to do, so only redraw components that changed @@ -74995,7 +77078,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha return true; }; -var _$buttons_473 = {}; +var _$buttons_535 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -75007,15 +77090,15 @@ var _$buttons_473 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; -var ____473 = _$lib_539._; +var ____535 = _$lib_601._; -var modeBarButtons = _$buttons_473 = {}; +var modeBarButtons = _$buttons_535 = {}; /** * ModeBar buttons configuration @@ -75045,40 +77128,40 @@ var modeBarButtons = _$buttons_473 = {}; modeBarButtons.toImage = { name: 'toImage', - title: function(gd) { return ____473(gd, 'Download plot as a png'); }, + title: function(gd) { return ____535(gd, 'Download plot as a png'); }, icon: _$ploticon_2.camera, click: function(gd) { var format = 'png'; - _$lib_539.notifier(____473(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + _$lib_601.notifier(____535(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - if(_$lib_539.isIE()) { - _$lib_539.notifier(____473(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + if(_$lib_601.isIE()) { + _$lib_601.notifier(____535(gd, 'IE only supports svg. Changing format to svg.'), 'long'); format = 'svg'; } - _$registry_668.call('downloadImage', gd, {'format': format}) + _$registry_731.call('downloadImage', gd, {'format': format}) .then(function(filename) { - _$lib_539.notifier(____473(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + _$lib_601.notifier(____535(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); }) .catch(function() { - _$lib_539.notifier(____473(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + _$lib_601.notifier(____535(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); }); } }; modeBarButtons.sendDataToCloud = { name: 'sendDataToCloud', - title: function(gd) { return ____473(gd, 'Edit in Chart Studio'); }, + title: function(gd) { return ____535(gd, 'Edit in Chart Studio'); }, icon: _$ploticon_2.disk, click: function(gd) { - _$plots_647.sendDataToCloud(gd); + _$plots_709.sendDataToCloud(gd); } }; modeBarButtons.zoom2d = { name: 'zoom2d', - title: function(gd) { return ____473(gd, 'Zoom'); }, + title: function(gd) { return ____535(gd, 'Zoom'); }, attr: 'dragmode', val: 'zoom', icon: _$ploticon_2.zoombox, @@ -75087,7 +77170,7 @@ modeBarButtons.zoom2d = { modeBarButtons.pan2d = { name: 'pan2d', - title: function(gd) { return ____473(gd, 'Pan'); }, + title: function(gd) { return ____535(gd, 'Pan'); }, attr: 'dragmode', val: 'pan', icon: _$ploticon_2.pan, @@ -75096,7 +77179,7 @@ modeBarButtons.pan2d = { modeBarButtons.select2d = { name: 'select2d', - title: function(gd) { return ____473(gd, 'Box Select'); }, + title: function(gd) { return ____535(gd, 'Box Select'); }, attr: 'dragmode', val: 'select', icon: _$ploticon_2.selectbox, @@ -75105,7 +77188,7 @@ modeBarButtons.select2d = { modeBarButtons.lasso2d = { name: 'lasso2d', - title: function(gd) { return ____473(gd, 'Lasso Select'); }, + title: function(gd) { return ____535(gd, 'Lasso Select'); }, attr: 'dragmode', val: 'lasso', icon: _$ploticon_2.lasso, @@ -75114,7 +77197,7 @@ modeBarButtons.lasso2d = { modeBarButtons.zoomIn2d = { name: 'zoomIn2d', - title: function(gd) { return ____473(gd, 'Zoom in'); }, + title: function(gd) { return ____535(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: _$ploticon_2.zoom_plus, @@ -75123,7 +77206,7 @@ modeBarButtons.zoomIn2d = { modeBarButtons.zoomOut2d = { name: 'zoomOut2d', - title: function(gd) { return ____473(gd, 'Zoom out'); }, + title: function(gd) { return ____535(gd, 'Zoom out'); }, attr: 'zoom', val: 'out', icon: _$ploticon_2.zoom_minus, @@ -75132,7 +77215,7 @@ modeBarButtons.zoomOut2d = { modeBarButtons.autoScale2d = { name: 'autoScale2d', - title: function(gd) { return ____473(gd, 'Autoscale'); }, + title: function(gd) { return ____535(gd, 'Autoscale'); }, attr: 'zoom', val: 'auto', icon: _$ploticon_2.autoscale, @@ -75141,7 +77224,7 @@ modeBarButtons.autoScale2d = { modeBarButtons.resetScale2d = { name: 'resetScale2d', - title: function(gd) { return ____473(gd, 'Reset axes'); }, + title: function(gd) { return ____535(gd, 'Reset axes'); }, attr: 'zoom', val: 'reset', icon: _$ploticon_2.home, @@ -75150,7 +77233,7 @@ modeBarButtons.resetScale2d = { modeBarButtons.hoverClosestCartesian = { name: 'hoverClosestCartesian', - title: function(gd) { return ____473(gd, 'Show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Show closest data on hover'); }, attr: 'hovermode', val: 'closest', icon: _$ploticon_2.tooltip_basic, @@ -75160,7 +77243,7 @@ modeBarButtons.hoverClosestCartesian = { modeBarButtons.hoverCompareCartesian = { name: 'hoverCompareCartesian', - title: function(gd) { return ____473(gd, 'Compare data on hover'); }, + title: function(gd) { return ____535(gd, 'Compare data on hover'); }, attr: 'hovermode', val: function(gd) { return gd._fullLayout._isHoriz ? 'y' : 'x'; @@ -75176,7 +77259,7 @@ function handleCartesian(gd, ev) { var val = button.getAttribute('data-val') || true; var fullLayout = gd._fullLayout; var aobj = {}; - var axList = _$axis_ids_587.list(gd, null, true); + var axList = _$axis_ids_650.list(gd, null, true); var allSpikesEnabled = 'on'; var ax, i; @@ -75246,12 +77329,12 @@ function handleCartesian(gd, ev) { aobj[astr] = val; } - _$registry_668.call('relayout', gd, aobj); + _$registry_731.call('relayout', gd, aobj); } modeBarButtons.zoom3d = { name: 'zoom3d', - title: function(gd) { return ____473(gd, 'Zoom'); }, + title: function(gd) { return ____535(gd, 'Zoom'); }, attr: 'scene.dragmode', val: 'zoom', icon: _$ploticon_2.zoombox, @@ -75260,7 +77343,7 @@ modeBarButtons.zoom3d = { modeBarButtons.pan3d = { name: 'pan3d', - title: function(gd) { return ____473(gd, 'Pan'); }, + title: function(gd) { return ____535(gd, 'Pan'); }, attr: 'scene.dragmode', val: 'pan', icon: _$ploticon_2.pan, @@ -75269,7 +77352,7 @@ modeBarButtons.pan3d = { modeBarButtons.orbitRotation = { name: 'orbitRotation', - title: function(gd) { return ____473(gd, 'Orbital rotation'); }, + title: function(gd) { return ____535(gd, 'Orbital rotation'); }, attr: 'scene.dragmode', val: 'orbit', icon: _$ploticon_2['3d_rotate'], @@ -75278,7 +77361,7 @@ modeBarButtons.orbitRotation = { modeBarButtons.tableRotation = { name: 'tableRotation', - title: function(gd) { return ____473(gd, 'Turntable rotation'); }, + title: function(gd) { return ____535(gd, 'Turntable rotation'); }, attr: 'scene.dragmode', val: 'turntable', icon: _$ploticon_2['z-axis'], @@ -75302,12 +77385,12 @@ function handleDrag3d(gd, ev) { var val2d = (val === 'pan') ? val : 'zoom'; layoutUpdate.dragmode = val2d; - _$registry_668.call('relayout', gd, layoutUpdate); + _$registry_731.call('relayout', gd, layoutUpdate); } modeBarButtons.resetCameraDefault3d = { name: 'resetCameraDefault3d', - title: function(gd) { return ____473(gd, 'Reset camera to default'); }, + title: function(gd) { return ____535(gd, 'Reset camera to default'); }, attr: 'resetDefault', icon: _$ploticon_2.home, click: handleCamera3d @@ -75315,7 +77398,7 @@ modeBarButtons.resetCameraDefault3d = { modeBarButtons.resetCameraLastSave3d = { name: 'resetCameraLastSave3d', - title: function(gd) { return ____473(gd, 'Reset camera to last save'); }, + title: function(gd) { return ____535(gd, 'Reset camera to last save'); }, attr: 'resetLastSave', icon: _$ploticon_2.movie, click: handleCamera3d @@ -75337,16 +77420,16 @@ function handleCamera3d(gd, ev) { aobj[key] = null; } else if(attr === 'resetLastSave') { - aobj[key] = _$lib_539.extendDeep({}, scene.cameraInitial); + aobj[key] = _$lib_601.extendDeep({}, scene.cameraInitial); } } - _$registry_668.call('relayout', gd, aobj); + _$registry_731.call('relayout', gd, aobj); } modeBarButtons.hoverClosest3d = { name: 'hoverClosest3d', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -75371,7 +77454,7 @@ function handleHover3d(gd, ev) { var layoutUpdate = {}; if(val) { - layoutUpdate = _$lib_539.extendDeep(layout, val); + layoutUpdate = _$lib_601.extendDeep(layout, val); button._previousVal = null; } else { @@ -75399,15 +77482,15 @@ function handleHover3d(gd, ev) { } } - button._previousVal = _$lib_539.extendDeep({}, currentSpikes); + button._previousVal = _$lib_601.extendDeep({}, currentSpikes); } - _$registry_668.call('relayout', gd, layoutUpdate); + _$registry_731.call('relayout', gd, layoutUpdate); } modeBarButtons.zoomInGeo = { name: 'zoomInGeo', - title: function(gd) { return ____473(gd, 'Zoom in'); }, + title: function(gd) { return ____535(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: _$ploticon_2.zoom_plus, @@ -75416,7 +77499,7 @@ modeBarButtons.zoomInGeo = { modeBarButtons.zoomOutGeo = { name: 'zoomOutGeo', - title: function(gd) { return ____473(gd, 'Zoom out'); }, + title: function(gd) { return ____535(gd, 'Zoom out'); }, attr: 'zoom', val: 'out', icon: _$ploticon_2.zoom_minus, @@ -75425,7 +77508,7 @@ modeBarButtons.zoomOutGeo = { modeBarButtons.resetGeo = { name: 'resetGeo', - title: function(gd) { return ____473(gd, 'Reset'); }, + title: function(gd) { return ____535(gd, 'Reset'); }, attr: 'reset', val: null, icon: _$ploticon_2.autoscale, @@ -75434,7 +77517,7 @@ modeBarButtons.resetGeo = { modeBarButtons.hoverClosestGeo = { name: 'hoverClosestGeo', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -75458,7 +77541,7 @@ function handleGeo(gd, ev) { var scale = geoLayout.projection.scale; var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; - _$registry_668.call('relayout', gd, id + '.projection.scale', newScale); + _$registry_731.call('relayout', gd, id + '.projection.scale', newScale); } else if(attr === 'reset') { resetView(gd, 'geo'); } @@ -75467,7 +77550,7 @@ function handleGeo(gd, ev) { modeBarButtons.hoverClosestGl2d = { name: 'hoverClosestGl2d', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -75478,7 +77561,7 @@ modeBarButtons.hoverClosestGl2d = { modeBarButtons.hoverClosestPie = { name: 'hoverClosestPie', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: 'closest', icon: _$ploticon_2.tooltip_basic, @@ -75497,14 +77580,14 @@ function toggleHover(gd) { var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - _$registry_668.call('relayout', gd, 'hovermode', newHover); + _$registry_731.call('relayout', gd, 'hovermode', newHover); } // buttons when more then one plot types are present modeBarButtons.toggleHover = { name: 'toggleHover', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -75522,7 +77605,7 @@ modeBarButtons.toggleHover = { modeBarButtons.resetViews = { name: 'resetViews', - title: function(gd) { return ____473(gd, 'Reset views'); }, + title: function(gd) { return ____535(gd, 'Reset views'); }, icon: _$ploticon_2.home, click: function(gd, ev) { var button = ev.currentTarget; @@ -75541,7 +77624,7 @@ modeBarButtons.resetViews = { modeBarButtons.toggleSpikelines = { name: 'toggleSpikelines', - title: function(gd) { return ____473(gd, 'Toggle Spike Lines'); }, + title: function(gd) { return ____535(gd, 'Toggle Spike Lines'); }, icon: _$ploticon_2.spikeline, attr: '_cartesianSpikesEnabled', val: 'on', @@ -75552,13 +77635,13 @@ modeBarButtons.toggleSpikelines = { var aobj = setSpikelineVisibility(gd); - _$registry_668.call('relayout', gd, aobj); + _$registry_731.call('relayout', gd, aobj); } }; function setSpikelineVisibility(gd) { var fullLayout = gd._fullLayout; - var axList = _$axis_ids_587.list(gd, null, true); + var axList = _$axis_ids_650.list(gd, null, true); var aobj = {}; var ax, axName; @@ -75574,7 +77657,7 @@ function setSpikelineVisibility(gd) { modeBarButtons.resetViewMapbox = { name: 'resetViewMapbox', - title: function(gd) { return ____473(gd, 'Reset view'); }, + title: function(gd) { return ____535(gd, 'Reset view'); }, attr: 'reset', icon: _$ploticon_2.home, click: function(gd) { @@ -75599,7 +77682,7 @@ function resetView(gd, subplotType) { } } - _$registry_668.call('relayout', gd, aObj); + _$registry_731.call('relayout', gd, aObj); } /** @@ -75613,9 +77696,9 @@ function resetView(gd, subplotType) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; @@ -75636,7 +77719,7 @@ function ModeBar(opts) { this.container.appendChild(this.element); } -var __proto_476 = ModeBar.prototype; +var __proto_538 = ModeBar.prototype; /** * Update modeBar (buttons and logo) @@ -75645,7 +77728,7 @@ var __proto_476 = ModeBar.prototype; * @param {array of arrays} buttons nested arrays of grouped buttons to initialize * */ -__proto_476.update = function(graphInfo, buttons) { +__proto_538.update = function(graphInfo, buttons) { this.graphInfo = graphInfo; var context = this.graphInfo._context; @@ -75673,7 +77756,7 @@ __proto_476.update = function(graphInfo, buttons) { this.updateActiveButton(); }; -__proto_476.updateButtons = function(buttons) { +__proto_538.updateButtons = function(buttons) { var _this = this; this.buttons = buttons; @@ -75689,1607 +77772,484 @@ __proto_476.updateButtons = function(buttons) { 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_476.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_476.createButton = function(config) { - var _this = this, - 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_127.select(button).classed('active', true); - - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - 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 - * @Return {HTMLelement} - */ -__proto_476.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); - - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); - - return icon; -}; - -/** - * Updates active button with attribute specified in layout - * @Param {object} graphInfo plot object containing data and layout - * @Return {HTMLelement} - */ -__proto_476.updateActiveButton = function(buttonClicked) { - var fullLayout = this.graphInfo._fullLayout, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; - - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_127.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_539.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_476.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_476.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); - - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_539._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - - group.appendChild(a); - return group; -}; - -__proto_476.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); - } - - this.hasLogo = false; -}; - -__proto_476.destroy = function() { - _$lib_539.removeElement(this.container.querySelector('.modebar')); -}; - -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; - - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); - - if(fullLayout._privateplot) { - _$d3_127.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); - } - - return modeBar; -} - -var _$createModeBar_476 = createModeBar; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_668 = require('../../registry'); */; - -/* removed: var _$createModeBar_476 = require('./modebar'); */; -/* removed: var _$buttons_473 = require('./buttons'); */; - -/** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object - * - */ -var _$manageModeBar_475 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } - - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } - - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } - - var customButtons = context.modeBarButtons; - var buttonGroups; - - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } - - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_476(gd, buttonGroups); -}; - -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; - - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); - - var groups = []; - - function addGroup(newGroup) { - if(!newGroup.length) return; - - var out = []; - - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_473[button]); - } - - groups.push(out); - } - - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); - - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; - - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; - } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; - } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; - } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; - } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; - } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; - } - - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; - } - - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; - } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); - } - - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); - - return appendButtonsToGroups(groups, buttonsToAdd); -} - -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_587.list({_fullLayout: fullLayout}, null, true); - - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } - } - - return true; -} - -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; - - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; - - var trace = fullData[i]; - - if(!trace._module || !trace._module.selectPoints) continue; - - if(_$registry_668.traceIs(trace, 'scatter-like')) { - if(_$subtypes_884.hasMarkers(trace) || _$subtypes_884.hasText(trace)) { - selectable = true; - } - } else if(_$registry_668.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; - } - - return selectable; -} - -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } - } - else groups.push(buttons); - } - - return groups; -} - -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; - - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; - - if(typeof button === 'string') { - if(_$buttons_473[button] !== undefined) { - customButtons[i][j] = _$buttons_473[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } - } - - return customButtons; -} - -var _$modebar_474 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -_$modebar_474.manage = _$manageModeBar_475; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var FROM_BL = _$alignment_511.FROM_BL; - -var _$scaleZoom_601 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } - - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; - -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -var __FROM_TL_592 = _$alignment_511.FROM_TL; - -/* removed: var _$plots_647 = require('../plots'); */; - -var doTicks = _$axes_584.doTicks; -var getFromId = _$axis_ids_587.getFromId; -/* removed: var _$prepSelect_602 = require('./select'); */; -/* removed: var _$scaleZoom_601 = require('./scale_zoom'); */; - -/* removed: var _$constants_589 = require('./constants'); */; -var MINDRAG = _$constants_589.MINDRAG; -var MINZOOM = _$constants_589.MINZOOM; - - -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; - -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px - var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; - - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; - - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; - - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); - - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; - - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } - - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } - - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; - - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; - - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } - } - - recomputeAxisLists(); - - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - - var allFixedRanges = !yActive && !xActive; - - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; - } - - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_602(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; - - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; - - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); - - if(numClicks === 2 && !singleEnd) doubleClick(); - - if(isMainDrag) { - _$fx_453.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; - - if(ax.fixedrange) return; - - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; - - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_127.select(dragger) - .call(_$svg_text_utils_562.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_668.call('relayout', gd, attrStr, v); - } - }); - } - } - } - }; - - _$dragelement_433.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; - - // collected changes to be made to the plot by relayout at the end - var updates = {}; - - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_352(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; - - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - - corners = makeCorners(zoomlayer, xs, ys); - - clearSelect(zoomlayer); - } - - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } - - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); - - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } - - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; - - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } - - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } - - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); - - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); - } - - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_589.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } - - var pc = gd.querySelector('.plotly'); - - recomputeAxisLists(); - - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; - } - - clearTimeout(redrawTimer); - - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_539.log('Did not find wheel motion attributes: ', e); - return; - } - - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; - - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; - - var axRange = _$lib_539.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + throw new Error('button name \'' + buttonName + '\' is taken'); + } + _this.buttonsNames.push(buttonName); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +__proto_538.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * Create a new button div and set constant and configurable attributes + * @Param {object} config (see ./buttons.js for more info) + * @Return {HTMLelement} + */ +__proto_538.createButton = function(config) { + var _this = this, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_130.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +__proto_538.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_601(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_601(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * Updates active button with attribute specified in layout + * @Param {object} graphInfo plot object containing data and layout + * @Return {HTMLelement} + */ +__proto_538.updateActiveButton = function(buttonClicked) { + var fullLayout = this.graphInfo._fullLayout, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_130.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_601.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * Check if modeBar is configured as button configuration argument + * + * @Param {object} buttons 2d array of grouped button config objects + * @Return {boolean} + */ +__proto_538.hasButtons = function(buttons) { + var currentButtons = this.buttons; - if((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_668.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_668.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_668.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +__proto_538.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_601._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +__proto_538.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +__proto_538.destroy = function() { + _$lib_601.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_668.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_130.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_539.syncOrAsync([ - _$plots_647.previousPromises, - function() { _$registry_668.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_538 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_601(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_538 = require('./modebar'); */; +/* removed: var _$buttons_535 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_592[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_537 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_539.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_539.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_538(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_436.setTranslate, clipDx, clipDy) - .call(_$drawing_436.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_436.setTranslate, plotDx, plotDy) - .call(_$drawing_436.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_436.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_436.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_436.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_436.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_535[button]); } - } - - return dragger; -} -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - - dragger3.call(_$setCursor_558, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_127.select(dragger).call(_$drawing_436.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_127.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_127.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_650.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_411.background, - stroke: _$color_411.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_731.traceIs(trace, 'scatter-like')) { + if(_$subtypes_949.hasMarkers(trace) || _$subtypes_949.hasText(trace)) { + selectable = true; + } + } else if(_$registry_731.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_127.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_539.notifier(_$lib_539._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_535[button] !== undefined) { + customButtons[i][j] = _$buttons_535[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_539.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_240) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_592 = { - makeDragBox: makeDragBox, +var _$modebar_536 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_536.manage = _$manageModeBar_537; +var _$constraints_654 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -77301,152 +78261,202 @@ var _$dragbox_592 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +var __id2name_654 = _$axis_ids_650.id2name; +/* removed: var _$scaleZoom_663 = require('./scale_zoom'); */; +var __makePadFn_654 = _$autorange_646.makePadFn; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_578.ALMOST_EQUAL; -/* removed: var _$constants_589 = require('./constants'); */; -var __makeDragBox_593 = _$dragbox_592.makeDragBox; +var __FROM_BL_654 = _$alignment_573.FROM_BL; -var _$initInteractions_593 = function initInteractions(gd) { + +_$constraints_654.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_127.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; + + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + 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; - 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'), - 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)); + // 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_654(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_589.DRAGGERSIZE; + if(mode === 'range') { + _$scaleZoom_663(ax, factor); + } + else { + // mode === 'domain' - // 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_593(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + 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])); - 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) { - _$fx_453.hover(gd, evt, subplot); + 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_663(ax, factor); + continue; } - }; - _$fx_453.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_654(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_433.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_593(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_593(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_593(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_593(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_593(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_593(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_593(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_593(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_593(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_593(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_654.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_453.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_453.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_654[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_576 = {}; +var _$subroutines_639 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -77457,22 +78467,28 @@ var _$subroutines_576 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; -/* removed: var _$color_411 = require('../components/color'); */; -/* removed: var _$drawing_436 = require('../components/drawing'); */; -/* removed: var _$titles_504 = require('../components/titles'); */; -/* removed: var _$modebar_474 = require('../components/modebar'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_593 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_589 = require('../plots/cartesian/constants'); */; -/* removed: var _$alignment_511 = require('../constants/alignment'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$clearGlCanvases_585 = require('../lib/clear_gl_canvases'); */; -_$subroutines_576.layoutStyles = function(gd) { - return _$lib_539.syncOrAsync([_$plots_647.doAutoMargin, _$subroutines_576.lsInner], gd); +/* removed: var _$color_473 = require('../components/color'); */; +/* removed: var _$drawing_498 = require('../components/drawing'); */; +/* removed: var _$titles_566 = require('../components/titles'); */; +/* removed: var _$modebar_536 = require('../components/modebar'); */; + +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_652 = require('../plots/cartesian/constants'); */; +/* removed: var _$alignment_573 = require('../constants/alignment'); */; +/* removed: var _$constraints_654 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_654.enforce; +var cleanAxisConstraints = _$constraints_654.clean; +var __doAutoRange_639 = _$autorange_646.doAutoRange; + +_$subroutines_639.layoutStyles = function(gd) { + return _$lib_601.syncOrAsync([_$plots_709.doAutoMargin, _$subroutines_639.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -77490,11 +78506,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_576.lsInner = function(gd) { +_$subroutines_639.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_584.list(gd); + var axList = _$axes_647.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -77529,7 +78545,7 @@ _$subroutines_576.lsInner = function(gd) { ax._linepositions = {}; // stash crispRounded linewidth so we don't need to pass gd all over the place - ax._lw = _$drawing_436.crispRound(gd, ax.linewidth, 1); + ax._lw = _$drawing_498.crispRound(gd, ax.linewidth, 1); // figure out the main axis line and main mirror line position. // it's easier to follow the logic if we handle these separately from @@ -77538,7 +78554,7 @@ _$subroutines_576.lsInner = function(gd) { ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side); ax._mainMirrorPosition = (ax.mirror && counterAx) ? getLinePosition(ax, counterAx, - _$alignment_511.OPPOSITE_SIDE[ax.side]) : null; + _$alignment_573.OPPOSITE_SIDE[ax.side]) : null; } fullLayout._paperdiv @@ -77547,7 +78563,7 @@ _$subroutines_576.lsInner = function(gd) { height: fullLayout.height + 'px' }) .selectAll('.main-svg') - .call(_$drawing_436.setSize, fullLayout.width, fullLayout.height); + .call(_$drawing_498.setSize, fullLayout.width, fullLayout.height); gd._context.setBackground(gd, fullLayout.paper_bgcolor); @@ -77573,31 +78589,17 @@ _$subroutines_576.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_601.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -77611,7 +78613,7 @@ _$subroutines_576.lsInner = function(gd) { lowerBackgrounds.exit().remove(); lowerBackgrounds.each(function(subplot) { - fullLayout._plots[subplot].bg = _$d3_127.select(this); + fullLayout._plots[subplot].bg = _$d3_130.select(this); }); subplotSelection.each(function(subplot) { @@ -77621,51 +78623,45 @@ _$subroutines_576.lsInner = function(gd) { if(plotinfo.bg && hasSVGCartesian) { plotinfo.bg - .call(_$drawing_436.setRect, + .call(_$drawing_498.setRect, xa._offset - pad, ya._offset - pad, xa._length + 2 * pad, ya._length + 2 * pad) - .call(_$color_411.fill, fullLayout.plot_bgcolor) + .call(_$color_473.fill, fullLayout.plot_bgcolor) .style('stroke-width', 0); } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_601.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); - _$drawing_436.setTranslate(plotinfo.plot, xa._offset, ya._offset); + _$drawing_498.setTranslate(plotinfo.plot, xa._offset, ya._offset); var plotClipId; var layerClipId; if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } - _$drawing_436.setClipUrl(plotinfo.plot, plotClipId); + _$drawing_498.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_589.traceLayerClasses.length; i++) { - var layer = _$constants_589.traceLayerClasses[i]; + for(i = 0; i < _$constants_652.traceLayerClasses.length; i++) { + var layer = _$constants_652.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { - plotinfo.plot.selectAll('g.' + layer).call(_$drawing_436.setClipUrl, layerClipId); + plotinfo.plot.selectAll('g.' + layer).call(_$drawing_498.setClipUrl, layerClipId); } } @@ -77744,7 +78740,7 @@ _$subroutines_576.lsInner = function(gd) { plotinfo.xlines .style('stroke-width', xa._lw + 'px') - .call(_$color_411.stroke, xa.showline ? + .call(_$color_473.stroke, xa.showline ? xa.linecolor : 'rgba(0,0,0,0)'); } plotinfo.xlines.attr('d', xPath); @@ -77781,15 +78777,15 @@ _$subroutines_576.lsInner = function(gd) { plotinfo.ylines .style('stroke-width', ya._lw + 'px') - .call(_$color_411.stroke, ya.showline ? + .call(_$color_473.stroke, ya.showline ? ya.linecolor : 'rgba(0,0,0,0)'); } plotinfo.ylines.attr('d', yPath); }); - _$axes_584.makeClipPaths(gd); - _$subroutines_576.drawMainTitle(gd); - _$modebar_474.manage(gd); + _$axes_647.makeClipPaths(gd); + _$subroutines_639.drawMainTitle(gd); + _$modebar_536.manage(gd); return gd._promises.length && Promise.all(gd._promises); }; @@ -77819,7 +78815,7 @@ function shouldShowLineThisSide(ax, side, counterAx) { // in order to handle cases where the user forgot to anchor this axis correctly // (because its default anchor has the same domain on the relevant end) // check whether the relevant position is the same. - var sideIndex = _$alignment_511.FROM_BL[side]; + var sideIndex = _$alignment_573.FROM_BL[side]; if(counterAx.side === side) { return anchorAx.domain[sideIndex] === ax.domain[sideIndex]; } @@ -77845,10 +78841,10 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_576.drawMainTitle = function(gd) { +_$subroutines_639.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; - _$titles_504.draw(gd, 'gtitle', { + _$titles_566.draw(gd, 'gtitle', { propContainer: fullLayout, propName: 'title', placeholder: fullLayout._dfltTitle.plot, @@ -77864,7 +78860,7 @@ _$subroutines_576.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_576.doTraceStyle = function(gd) { +_$subroutines_639.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -77873,13 +78869,13 @@ _$subroutines_576.doTraceStyle = function(gd) { if(arraysToCalcdata) arraysToCalcdata(cdi, cdi[0].trace); } - _$plots_647.style(gd); - _$registry_668.getComponentMethod('legend', 'draw')(gd); + _$plots_709.style(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doColorBars = function(gd) { +_$subroutines_639.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -77887,7 +78883,7 @@ _$subroutines_576.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_668.traceIs(trace, 'contour')) { + if(_$registry_731.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -77896,49 +78892,54 @@ _$subroutines_576.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_668.traceIs(trace, 'markerColorscale')) { + if(_$registry_731.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); } } - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_576.layoutReplot = function(gd) { +_$subroutines_639.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_668.call('plot', gd, '', layout); + return _$registry_731.call('plot', gd, '', layout); }; -_$subroutines_576.doLegend = function(gd) { - _$registry_668.getComponentMethod('legend', 'draw')(gd); - return _$plots_647.previousPromises(gd); +_$subroutines_639.doLegend = function(gd) { + _$registry_731.getComponentMethod('legend', 'draw')(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doTicksRelayout = function(gd) { - _$axes_584.doTicks(gd, 'redraw'); - _$subroutines_576.drawMainTitle(gd); - return _$plots_647.previousPromises(gd); +_$subroutines_639.doTicksRelayout = function(gd) { + _$axes_647.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_585(gd); + _$registry_731.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_639.drawMainTitle(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doModeBar = function(gd) { +_$subroutines_639.doModeBar = function(gd) { var fullLayout = gd._fullLayout; - _$modebar_474.manage(gd); - _$initInteractions_593(gd); + _$modebar_536.manage(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; if(updateFx) updateFx(fullLayout); } - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doCamera = function(gd) { +_$subroutines_639.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -77950,214 +78951,88 @@ _$subroutines_576.doCamera = function(gd) { } }; -var _$constraints_591 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_591 = _$axis_ids_587.id2name; -/* removed: var _$scaleZoom_601 = require('./scale_zoom'); */; -var __makePadFn_591 = _$autorange_583.makePadFn; - -var ALMOST_EQUAL = _$numerical_517.ALMOST_EQUAL; - -var __FROM_BL_591 = _$alignment_511.FROM_BL; - - -_$constraints_591.enforce = function enforceAxisConstraints(gd) { +_$subroutines_639.drawData = function(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_591(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_731.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_601(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_601(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_585(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_591(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_709.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_731.getComponentMethod('shapes', 'draw')(gd); + _$registry_731.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_709.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_639.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_647.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_639(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_591.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_591[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_639.finalDraw = function(gd) { + _$registry_731.getComponentMethod('shapes', 'draw')(gd); + _$registry_731.getComponentMethod('images', 'draw')(gd); + _$registry_731.getComponentMethod('annotations', 'draw')(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); + _$registry_731.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_731.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_731.getComponentMethod('sliders', 'draw')(gd); + _$registry_731.getComponentMethod('updatemenus', 'draw')(gd); +}; -var _$micropolar_656 = {}; +var _$micropolar_718 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -78166,25 +79041,25 @@ var _$micropolar_656 = {}; * LICENSE file in the root directory of this source tree. */ -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../../lib'); */; -var __extendDeepAll_656 = _$lib_539.extendDeepAll; -var __MID_SHIFT_656 = _$alignment_511.MID_SHIFT; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +var __extendDeepAll_718 = _$lib_601.extendDeepAll; +var __MID_SHIFT_718 = _$alignment_573.MID_SHIFT; -var µ = _$micropolar_656 = { version: '0.2.2' }; +var µ = _$micropolar_718 = { version: '0.2.2' }; µ.Axis = function module() { var config = { data: [], layout: {} }, inputConfig = {}, liveConfig = {}; - var svg, container, dispatch = _$d3_127.dispatch('hover'), radialScale, angularScale; + var svg, container, dispatch = _$d3_130.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_127.select(container); + if (typeof container == 'string' || container.nodeName) container = _$d3_130.select(container); container.datum(data).each(function(_data, _index) { var dataOriginal = _data.slice(); liveConfig = { @@ -78198,7 +79073,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length; } if (!d.strokeColor) { - d.strokeColor = d.geometry === 'LinePlot' ? d.color : _$d3_127.rgb(d.color).darker().toString(); + d.strokeColor = d.geometry === 'LinePlot' ? d.color : _$d3_130.rgb(d.color).darker().toString(); } liveConfig.data[i].color = d.color; liveConfig.data[i].strokeColor = d.strokeColor; @@ -78215,7 +79090,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return d; }); if (isStacked) { - var grouped = _$d3_127.nest().key(function(d, i) { + var grouped = _$d3_130.nest().key(function(d, i) { return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked'; }).entries(dataWithGroupId); var dataYStack = []; @@ -78232,7 +79107,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return d.values; } }); - data = _$d3_127.merge(stacked); + data = _$d3_130.merge(stacked); } data.forEach(function(d, i) { d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ]; @@ -78243,13 +79118,13 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ]; var extent; if (isStacked) { - var highestStackedValue = _$d3_127.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); + var highestStackedValue = _$d3_130.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); extent = [ 0, highestStackedValue ]; - } else extent = _$d3_127.extent(µ.util.flattenArray(data.map(function(d, i) { + } else extent = _$d3_130.extent(µ.util.flattenArray(data.map(function(d, i) { return d.r; }))); if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0; - radialScale = _$d3_127.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]); + radialScale = _$d3_130.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; @@ -78259,7 +79134,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; if (isOrdinal) { angularDataMerged = µ.util.deduplicate(angularDataMerged); ticks = angularDataMerged.slice(); - angularDataMerged = _$d3_127.range(angularDataMerged.length); + angularDataMerged = _$d3_130.range(angularDataMerged.length); data = data.map(function(d, i) { var result = d; d.t = [ angularDataMerged ]; @@ -78272,7 +79147,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }).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_127.extent(angularDataMerged); + var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : _$d3_130.extent(angularDataMerged); var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]); if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0; var angularDomainWithPadding = angularDomain.slice(); @@ -78285,19 +79160,19 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; 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_127.range.apply(this, angularDomainWithPadding); + var angularAxisRange = _$d3_130.range.apply(this, angularDomainWithPadding); angularAxisRange = angularAxisRange.map(function(d, i) { return parseFloat(d.toPrecision(12)); }); - angularScale = _$d3_127.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]); + angularScale = _$d3_130.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_127.select(this).select('svg.chart-root'); + svg = _$d3_130.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_127.select(newSvg); + svg = _$d3_130.select(newSvg); } svg.select('.guides-group').style({ 'pointer-events': 'none' @@ -78340,7 +79215,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; data: data.map(function(d, i) { return d.name || 'Element' + i; }), - legendConfig: __extendDeepAll_656({}, + legendConfig: __extendDeepAll_718({}, µ.Legend.defaultConfig().legendConfig, { container: legendContainer, @@ -78405,7 +79280,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return angularScale(d) % 360 + axisConfig.orientation; } if (axisConfig.radialAxis.visible) { - var axis = _$d3_127.svg.axis().scale(radialScale).ticks(5).tickSize(5); + var axis = _$d3_130.svg.axis().scale(radialScale).ticks(5).tickSize(5); radialAxis.call(axis).attr({ transform: 'rotate(' + axisConfig.radialAxis.orientation + ')' }); @@ -78456,7 +79331,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle); var ticksText = angularAxis.select('text.axis-text').attr({ x: radius + axisConfig.labelOffset, - dy: __MID_SHIFT_656 + 'em', + dy: __MID_SHIFT_718 + 'em', transform: function(d, i) { var angle = currentAngle(d, i); var rad = radius + axisConfig.labelOffset; @@ -78476,7 +79351,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; if (i % (axisConfig.minorTicks + 1) != 0) return ''; return axisConfig.angularAxis.rewriteTicks(this.textContent, i); }); - var rightmostTickEndX = _$d3_127.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { + var rightmostTickEndX = _$d3_130.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { return d.getCTM().e + d.getBBox().width; })); legendContainer.attr({ @@ -78508,7 +79383,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; geometryConfig: geometryConfig }); }); - var geometryConfigsGrouped = _$d3_127.nest().key(function(d, i) { + var geometryConfigsGrouped = _$d3_130.nest().key(function(d, i) { return typeof d.data.groupId != 'undefined' || 'unstacked'; }).entries(geometryConfigs); var geometryConfigsGrouped2 = []; @@ -78521,7 +79396,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; 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_656(µ[geometry].defaultConfig(), dB); + return __extendDeepAll_718(µ[geometry].defaultConfig(), dB); }); µ[geometry]().config(finalGeometryConfig)(); }); @@ -78591,7 +79466,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; radialTooltip.hide(); }); svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var color = this.style.fill; var newColor = 'black'; var opacity = this.style.opacity || 1; @@ -78602,7 +79477,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; el.attr({ 'data-fill': color }); - newColor = _$d3_127.hsl(color).darker().toString(); + newColor = _$d3_130.hsl(color).darker().toString(); el.style({ fill: newColor, opacity: 1 @@ -78625,18 +79500,18 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; el.attr({ 'data-stroke': color }); - newColor = _$d3_127.hsl(color).darker().toString(); + newColor = _$d3_130.hsl(color).darker().toString(); el.style({ stroke: newColor, opacity: 1 }); } }).on('mousemove.tooltip', function(d, i) { - if (_$d3_127.event.which != 0) return false; - if (_$d3_127.select(this).attr('data-fill')) geometryTooltip.show(); + if (_$d3_130.event.which != 0) return false; + if (_$d3_130.select(this).attr('data-fill')) geometryTooltip.show(); }).on('mouseout.tooltip', function(d, i) { geometryTooltip.hide(); - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var fillColor = el.attr('data-fill'); if (fillColor) el.style({ fill: fillColor, @@ -78658,11 +79533,11 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var xClone = µ.util.cloneJson(_x); xClone.data.forEach(function(d, i) { if (!config.data[i]) config.data[i] = {}; - __extendDeepAll_656(config.data[i], µ.Axis.defaultConfig().data[0]); - __extendDeepAll_656(config.data[i], d); + __extendDeepAll_718(config.data[i], µ.Axis.defaultConfig().data[0]); + __extendDeepAll_718(config.data[i], d); }); - __extendDeepAll_656(config.layout, µ.Axis.defaultConfig().layout); - __extendDeepAll_656(config.layout, xClone.layout); + __extendDeepAll_718(config.layout, µ.Axis.defaultConfig().layout); + __extendDeepAll_718(config.layout, xClone.layout); return this; }; exports.getLiveConfig = function() { @@ -78680,7 +79555,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; exports.svg = function() { return svg; }; - _$d3_127.rebind(exports, dispatch, 'on'); + _$d3_130.rebind(exports, dispatch, 'on'); return exports; }; @@ -78699,7 +79574,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; opacity: 1 } ], layout: { - defaultColorRange: _$d3_127.scale.category10().range(), + defaultColorRange: _$d3_130.scale.category10().range(), title: null, height: 450, width: 500, @@ -78780,7 +79655,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.util.dataFromEquation2 = function(_equation, _step) { var step = _step || 6; - var data = _$d3_127.range(0, 360 + step, step).map(function(deg, index) { + var data = _$d3_130.range(0, 360 + step, step).map(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); return [ deg, radius ]; @@ -78791,7 +79666,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.util.dataFromEquation = function(_equation, _step, _name) { var step = _step || 6; var t = [], r = []; - _$d3_127.range(0, 360 + step, step).forEach(function(deg, index) { + _$d3_130.range(0, 360 + step, step).forEach(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); t.push(deg); @@ -78808,7 +79683,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.util.ensureArray = function(_val, _count) { if (typeof _val === 'undefined') return null; var arr = [].concat(_val); - return _$d3_127.range(_count).map(function(d, i) { + return _$d3_130.range(_count).map(function(d, i) { return arr[i] || arr[0]; }); }; @@ -78831,8 +79706,8 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; µ.util.sumArrays = function(a, b) { - return _$d3_127.zip(a, b).map(function(d, i) { - return _$d3_127.sum(d); + return _$d3_130.zip(a, b).map(function(d, i) { + return _$d3_130.sum(d); }); }; @@ -78875,7 +79750,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; µ.util.getMousePos = function(_referenceElement) { - var mousePos = _$d3_127.mouse(_referenceElement.node()); + var mousePos = _$d3_130.mouse(_referenceElement.node()); var mouseX = mousePos[0]; var mouseY = mousePos[1]; var mouse = {}; @@ -78930,7 +79805,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.PolyChart = function module() { var config = [ µ.PolyChart.defaultConfig() ]; - var dispatch = _$d3_127.dispatch('hover'); + var dispatch = _$d3_130.dispatch('hover'); var dashArray = { solid: 'none', dash: [ 5, 2 ], @@ -78940,11 +79815,11 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; function exports() { var geometryConfig = config[0].geometryConfig; var container = geometryConfig.container; - if (typeof container == 'string') container = _$d3_127.select(container); + if (typeof container == 'string') container = _$d3_130.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_127.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return _$d3_127.zip(d.data.t[0], d.data.r[0]); + if (isStack) return _$d3_130.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return _$d3_130.zip(d.data.t[0], d.data.r[0]); }); var angularScale = geometryConfig.angularScale; var domainMin = geometryConfig.radialScale.domain()[0]; @@ -78954,7 +79829,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0); var stackTop = geometryConfig.radialScale(d[2] || 0); var w = dataConfig.barWidth; - _$d3_127.select(this).attr({ + _$d3_130.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) { @@ -78964,8 +79839,8 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; generator.dot = function(d, i, pI) { var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d; - var symbol = _$d3_127.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); - _$d3_127.select(this).attr({ + var symbol = _$d3_130.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); + _$d3_130.select(this).attr({ 'class': 'mark dot', d: symbol, transform: function(d, i) { @@ -78974,7 +79849,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; } }); }; - var line = _$d3_127.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) { + var line = _$d3_130.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; @@ -78983,7 +79858,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var lineData = d[2] ? data[pI].map(function(d, i) { return [ d[0], d[1] + d[2] ]; }) : data[pI]; - _$d3_127.select(this).each(generator['dot']).style({ + _$d3_130.select(this).each(generator['dot']).style({ opacity: function(dB, iB) { return +_config[pI].data.dotVisible; }, @@ -78992,7 +79867,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; 'class': 'mark dot' }); if (i > 0) return; - var lineSelection = _$d3_127.select(this.parentNode).selectAll('path.line').data([ 0 ]); + var lineSelection = _$d3_130.select(this.parentNode).selectAll('path.line').data([ 0 ]); lineSelection.enter().insert('path'); lineSelection.attr({ 'class': 'line', @@ -79025,7 +79900,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; var angularRange = geometryConfig.angularScale.range(); var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180; - var arc = _$d3_127.svg.arc().startAngle(function(d) { + var arc = _$d3_130.svg.arc().startAngle(function(d) { return -triangleAngle / 2; }).endAngle(function(d) { return triangleAngle / 2; @@ -79035,7 +79910,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]); }); generator.arc = function(d, i, pI) { - _$d3_127.select(this).attr({ + _$d3_130.select(this).attr({ 'class': 'mark arc', d: arc, transform: function(d, i) { @@ -79063,7 +79938,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none'; } }; - var geometryLayer = _$d3_127.select(this).selectAll('g.layer').data(data); + var geometryLayer = _$d3_130.select(this).selectAll('g.layer').data(data); geometryLayer.enter().append('g').attr({ 'class': 'layer' }); @@ -79098,15 +79973,15 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; if (!arguments.length) return config; _x.forEach(function(d, i) { if (!config[i]) config[i] = {}; - __extendDeepAll_656(config[i], µ.PolyChart.defaultConfig()); - __extendDeepAll_656(config[i], d); + __extendDeepAll_718(config[i], µ.PolyChart.defaultConfig()); + __extendDeepAll_718(config[i], d); }); return this; }; exports.getColorScale = function() { return colorScale; }; - _$d3_127.rebind(exports, dispatch, 'on'); + _$d3_130.rebind(exports, dispatch, 'on'); return exports; }; @@ -79137,7 +80012,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; container: 'body', radialScale: null, angularScale: null, - colorScale: _$d3_127.scale.category20() + colorScale: _$d3_130.scale.category20() } }; return config; @@ -79198,24 +80073,24 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.Legend = function module() { var config = µ.Legend.defaultConfig(); - var dispatch = _$d3_127.dispatch('hover'); + var dispatch = _$d3_130.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_656({}, legendConfig.elements[i]); + var element = __extendDeepAll_718({}, legendConfig.elements[i]); element.name = dB; element.color = [].concat(legendConfig.elements[i].color)[iB]; return element; }); }); - var data = _$d3_127.merge(flattenData); + var data = _$d3_130.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_127.select(container); + if (typeof container == 'string' || container.nodeName) container = _$d3_130.select(container); var colors = data.map(function(d, i) { return d.color; }); @@ -79233,14 +80108,14 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }); svgEnter.append('g').classed('legend-axis', true); svgEnter.append('g').classed('legend-marks', true); - var dataNumbered = _$d3_127.range(data.length); - var colorScale = _$d3_127.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); - var dataScale = _$d3_127.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]); + var dataNumbered = _$d3_130.range(data.length); + var colorScale = _$d3_130.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); + var dataScale = _$d3_130.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_127.svg.symbolTypes.indexOf(_type) != -1) return _$d3_127.svg.symbol().type(_type).size(squareSize)(); else return _$d3_127.svg.symbol().type('square').size(squareSize)(); + } else if (_$d3_130.svg.symbolTypes.indexOf(_type) != -1) return _$d3_130.svg.symbol().type(_type).size(squareSize)(); else return _$d3_130.svg.symbol().type('square').size(squareSize)(); }; if (isContinuous) { var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({ @@ -79282,7 +80157,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }); legendElement.exit().remove(); } - var legendAxis = _$d3_127.svg.axis().scale(dataScale).orient('right'); + var legendAxis = _$d3_130.svg.axis().scale(dataScale).orient('right'); var axis = svg.select('g.legend-axis').attr({ transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')' }).call(legendAxis); @@ -79304,10 +80179,10 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; } exports.config = function(_x) { if (!arguments.length) return config; - __extendDeepAll_656(config, _x); + __extendDeepAll_718(config, _x); return this; }; - _$d3_127.rebind(exports, dispatch, 'on'); + _$d3_130.rebind(exports, dispatch, 'on'); return exports; }; @@ -79367,7 +80242,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return exports; }; exports.text = function(_text) { - var l = _$d3_127.hsl(config.color).l; + var l = _$d3_130.hsl(config.color).l; var strokeColor = l >= .5 ? '#aaa' : 'white'; var fillColor = l >= .5 ? 'black' : 'white'; var text = _text || ''; @@ -79419,7 +80294,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return exports; }; exports.config = function(_x) { - __extendDeepAll_656(config, _x); + __extendDeepAll_718(config, _x); return exports; }; return exports; @@ -79435,7 +80310,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var outputConfig = {}; if (_inputConfig.data) { outputConfig.data = _inputConfig.data.map(function(d, i) { - var r = __extendDeepAll_656({}, d); + var r = __extendDeepAll_718({}, d); var toTranslate = [ [ r, [ 'marker', 'color' ], [ 'color' ] ], [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ], @@ -79489,7 +80364,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; } } if (_inputConfig.layout) { - var r = __extendDeepAll_656({}, _inputConfig.layout); + var r = __extendDeepAll_718({}, _inputConfig.layout); var toTranslate = [ [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ], [ r, [ 'showlegend' ], [ 'showLegend' ] ], @@ -79550,7 +80425,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var source = [ 't', 'r', 'b', 'l', 'pad' ]; var target = [ 'top', 'right', 'bottom', 'left', 'pad' ]; var margin = {}; - _$d3_127.entries(r.margin).forEach(function(dB, iB) { + _$d3_130.entries(r.margin).forEach(function(dB, iB) { margin[target[source.indexOf(dB.key)]] = dB.value; }); r.margin = margin; @@ -79589,7 +80464,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; // Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager // Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com -var _$UndoManager_658 = function UndoManager() { +var _$UndoManager_720 = function UndoManager() { var undoCommands = [], index = -1, isExecuting = false, @@ -79642,7 +80517,7 @@ var _$UndoManager_658 = function UndoManager() { }; }; -var _$micropolar_manager_657 = {}; +var _$micropolar_manager_719 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -79655,30 +80530,30 @@ var _$micropolar_manager_657 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$color_411 = require('../../../components/color'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$color_473 = require('../../../components/color'); */; -/* removed: var _$micropolar_656 = require('./micropolar'); */; -/* removed: var _$UndoManager_658 = require('./undo_manager'); */; -var __extendDeepAll_657 = _$lib_539.extendDeepAll; +/* removed: var _$micropolar_718 = require('./micropolar'); */; +/* removed: var _$UndoManager_720 = require('./undo_manager'); */; +var __extendDeepAll_719 = _$lib_601.extendDeepAll; -var manager = _$micropolar_manager_657 = {}; +var manager = _$micropolar_manager_719 = {}; manager.framework = function(_gd) { var config, previousConfigClone, plot, convertedInput, container; - var undoManager = new _$UndoManager_658(); + var undoManager = new _$UndoManager_720(); function exports(_inputConfig, _container) { if(_container) container = _container; - _$d3_127.select(_$d3_127.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); + _$d3_130.select(_$d3_130.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); config = (!config) ? _inputConfig : - __extendDeepAll_657(config, _inputConfig); + __extendDeepAll_719(config, _inputConfig); - if(!plot) plot = _$micropolar_656.Axis(); - convertedInput = _$micropolar_656.adapter.plotly().convert(config); + if(!plot) plot = _$micropolar_718.Axis(); + convertedInput = _$micropolar_718.adapter.plotly().convert(config); plot.config(convertedInput).render(container); _gd.data = config.data; _gd.layout = config.layout; @@ -79689,12 +80564,12 @@ manager.framework = function(_gd) { exports.svg = function() { return plot.svg(); }; exports.getConfig = function() { return config; }; exports.getLiveConfig = function() { - return _$micropolar_656.adapter.plotly().convert(plot.getLiveConfig(), true); + return _$micropolar_718.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_656.util.cloneJson(config); + var configClone = _$micropolar_718.util.cloneJson(config); (function(_configClone, _previousConfigClone) { undoManager.add({ undo: function() { @@ -79705,7 +80580,7 @@ manager.framework = function(_gd) { } }); })(configClone, previousConfigClone); - previousConfigClone = _$micropolar_656.util.cloneJson(configClone); + previousConfigClone = _$micropolar_718.util.cloneJson(configClone); }; exports.undo = function() { undoManager.undo(); }; exports.redo = function() { undoManager.redo(); }; @@ -79713,22 +80588,22 @@ manager.framework = function(_gd) { }; manager.fillLayout = function(_gd) { - var container = _$d3_127.select(_gd).selectAll('.plot-container'), + var container = _$d3_130.select(_gd).selectAll('.plot-container'), paperDiv = container.selectAll('.svg-container'), paper = _gd.framework && _gd.framework.svg && _gd.framework.svg(), dflts = { width: 800, height: 600, - paper_bgcolor: _$color_411.background, + paper_bgcolor: _$color_473.background, _container: container, _paperdiv: paperDiv, _paper: paper }; - _gd._fullLayout = __extendDeepAll_657(dflts, _gd.layout); + _gd._fullLayout = __extendDeepAll_719(dflts, _gd.layout); }; -var _$legacy_655 = {}; +var _$legacy_717 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -79739,11 +80614,11 @@ var _$legacy_655 = {}; 'use strict'; -var Polar = _$legacy_655 = _$micropolar_656; +var Polar = _$legacy_717 = _$micropolar_718; -Polar.manager = _$micropolar_manager_657; +Polar.manager = _$micropolar_manager_719; -var _$plot_api_573 = {}; +var _$plot_api_636 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -79756,37 +80631,33 @@ var _$plot_api_573 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$hasHover_239 = require('has-hover'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$hasHover_296 = require('has-hover'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$Events_527 = require('../lib/events'); */; -/* removed: var _$queue_553 = require('../lib/queue'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$Events_589 = require('../lib/events'); */; +/* removed: var _$queue_616 = require('../lib/queue'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$plot_schema_575 = require('./plot_schema'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$legacy_655 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_593 = require('../plots/cartesian/graph_interact'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$plot_schema_638 = require('./plot_schema'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +/* removed: var _$legacy_717 = require('../plots/polar/legacy'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -/* removed: var _$drawing_436 = require('../components/drawing'); */; -/* removed: var _$color_411 = require('../components/color'); */; -/* removed: var _$xmlns_namespaces_519 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_562 = require('../lib/svg_text_utils'); */; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +/* removed: var _$drawing_498 = require('../components/drawing'); */; +/* removed: var _$color_473 = require('../components/color'); */; +var initInteractions = _$graph_interact_656.initInteractions; +/* removed: var _$xmlns_namespaces_580 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$svg_text_utils_625 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_574 = require('./plot_config'); */; -/* removed: var _$manage_arrays_572 = require('./manage_arrays'); */; -/* removed: var _$helpers_570 = require('./helpers'); */; -/* removed: var _$subroutines_576 = require('./subroutines'); */; -/* removed: var _$edit_types_569 = require('./edit_types'); */; +/* removed: var _$plot_config_637 = require('./plot_config'); */; +/* removed: var _$manage_arrays_635 = require('./manage_arrays'); */; +/* removed: var _$helpers_633 = require('./helpers'); */; +/* removed: var _$subroutines_639 = require('./subroutines'); */; +/* removed: var _$edit_types_632 = require('./edit_types'); */; -/* removed: var _$constants_589 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_591 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_591.enforce; -var cleanAxisConstraints = _$constraints_591.clean; -var __doAutoRange_573 = _$autorange_583.doAutoRange; +var AX_NAME_PATTERN = _$constants_652.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -79812,15 +80683,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_573.plot = function(gd, data, layout, config) { +_$plot_api_636.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_527.init(gd); + _$Events_589.init(gd); - if(_$lib_539.isPlainObject(data)) { + if(_$lib_601.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -79828,19 +80699,19 @@ _$plot_api_573.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_527.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_589.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_539.isPlotDiv(gd)) { - _$lib_539.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_601.isPlotDiv(gd)) { + _$lib_601.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_573.addFrames(gd, frames); + return _$plot_api_636.addFrames(gd, frames); } } @@ -79852,12 +80723,15 @@ _$plot_api_573.plot = function(gd, data, layout, config) { // hook class for plots main container (in case of plotly.js // this won't be #embedded-graph or .js-tab-contents) - _$d3_127.select(gd).classed('js-plotly-plot', true); + _$d3_130.select(gd).classed('js-plotly-plot', true); // off-screen getBoundingClientRect testing space, // in #js-plotly-tester (and stored as Drawing.tester) // so we can share cached text across tabs - _$drawing_436.makeTester(); + _$drawing_498.makeTester(); + + // clear stashed base url + delete _$drawing_498.baseUrl; // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then @@ -79870,7 +80744,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_570.cleanData(data, gd.data); + _$helpers_633.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -79881,7 +80755,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_570.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_633.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -79895,7 +80769,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { gd._replotPending = false; } - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); var fullLayout = gd._fullLayout; @@ -79903,7 +80777,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_539.log('Legacy polar charts are deprecated!'); + _$lib_601.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -79921,17 +80795,17 @@ _$plot_api_573.plot = function(gd, data, layout, config) { } // clear gradient defs on each .plot call, because we know we'll loop through all traces - _$drawing_436.initGradients(gd); + _$drawing_498.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_584.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_647.saveShowSpikeInitial(gd); // prepare the data and find the autorange // generate calcdata, if we need to // to force redoing calcdata, just delete it before calling Plotly.plot var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length; - if(recalc) _$plots_647.doCalcdata(gd); + if(recalc) _$plots_709.doCalcdata(gd); // in case it has changed, attach fullData traces to calcdata for(var i = 0; i < gd.calcdata.length; i++) { @@ -79991,9 +80865,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_539.syncOrAsync([ - _$subroutines_576.layoutStyles - ], gd); + return _$plots_709.previousPromises(gd); } // draw anything that can affect margins. @@ -80001,31 +80873,31 @@ _$plot_api_573.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_668.getComponentMethod('legend', 'draw')(gd); - _$registry_668.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_668.getComponentMethod('sliders', 'draw')(gd); - _$registry_668.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); + _$registry_731.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_731.getComponentMethod('sliders', 'draw')(gd); + _$registry_731.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; trace = cd[0].trace; if(trace.visible !== true || !trace._module.colorbar) { - _$plots_647.autoMargin(gd, 'cb' + trace.uid); + _$plots_709.autoMargin(gd, 'cb' + trace.uid); } else trace._module.colorbar(gd, cd); } - _$plots_647.doAutoMargin(gd); - return _$plots_647.previousPromises(gd); + _$plots_709.doAutoMargin(gd); + return _$plots_709.previousPromises(gd); } // in case the margins changed, draw margin pushers again function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_539.syncOrAsync([ + return _$lib_601.syncOrAsync([ marginPushers, - _$subroutines_576.layoutStyles + _$subroutines_639.layoutStyles ], gd); } @@ -80046,7 +80918,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_539.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_601.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -80060,136 +80932,55 @@ _$plot_api_573.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_668.getComponentMethod('errorbars', 'calc')(gd); + _$registry_731.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_539.syncOrAsync([ - _$registry_668.getComponentMethod('shapes', 'calcAutorange'), - _$registry_668.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_601.syncOrAsync([ + _$registry_731.getComponentMethod('shapes', 'calcAutorange'), + _$registry_731.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_668.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_731.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_584.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_573(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_639.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_584.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_647.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_584.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_668.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_647.style(gd); - - // show annotations and shapes - _$registry_668.getComponentMethod('shapes', 'draw')(gd); - _$registry_668.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_647.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_647.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_668.getComponentMethod('shapes', 'draw')(gd); - _$registry_668.getComponentMethod('images', 'draw')(gd); - _$registry_668.getComponentMethod('annotations', 'draw')(gd); - _$registry_668.getComponentMethod('legend', 'draw')(gd); - _$registry_668.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_668.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_668.getComponentMethod('sliders', 'draw')(gd); - _$registry_668.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_647.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ - _$plots_647.previousPromises, + _$plots_709.previousPromises, addFrames, drawFramework, marginPushers, marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_576.layoutStyles); + seq.push(_$subroutines_639.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_593, - _$plots_647.rehover, - _$plots_647.previousPromises + _$subroutines_639.drawData, + _$subroutines_639.finalDraw, + initInteractions, + _$plots_709.addLinks, + _$plots_709.rehover, + _$plots_709.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -80198,25 +80989,25 @@ _$plot_api_573.plot = function(gd, data, layout, config) { }); }; -_$plot_api_573.setPlotConfig = function setPlotConfig(obj) { - return _$lib_539.extendFlat(_$plot_config_574, obj); +_$plot_api_636.setPlotConfig = function setPlotConfig(obj) { + return _$lib_601.extendFlat(_$plot_config_637, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_539.error(e); + _$lib_601.error(e); } } function opaqueSetBackground(gd, bgColor) { - var blend = _$color_411.combine(bgColor, 'white'); + var blend = _$color_473.combine(bgColor, 'white'); setBackground(gd, blend); } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_539.extendDeep({}, _$plot_config_574); + if(!gd._context) gd._context = _$lib_601.extendDeep({}, _$plot_config_637); var context = gd._context; var i, keys, key; @@ -80277,7 +81068,7 @@ function setPlotContext(gd, config) { } // make sure hover-only devices have mode bar visible - if(context.displayModeBar === 'hover' && !_$hasHover_239) { + if(context.displayModeBar === 'hover' && !_$hasHover_296) { context.displayModeBar = true; } @@ -80289,7 +81080,7 @@ function setPlotContext(gd, config) { function plotPolar(gd, data, layout) { // build or reuse the container skeleton - var plotContainer = _$d3_127.select(gd).selectAll('.plot-container') + var plotContainer = _$d3_130.select(gd).selectAll('.plot-container') .data([0]); plotContainer.enter() .insert('div', ':first-child') @@ -80306,7 +81097,7 @@ function plotPolar(gd, data, layout) { // fulfill gd requirements if(data) gd.data = data; if(layout) gd.layout = layout; - _$legacy_655.manager.fillLayout(gd); + _$legacy_717.manager.fillLayout(gd); // resize canvas paperDiv.style({ @@ -80315,7 +81106,7 @@ function plotPolar(gd, data, layout) { }); // instantiate framework - gd.framework = _$legacy_655.manager.framework(gd); + gd.framework = _$legacy_717.manager.framework(gd); // plot gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node()); @@ -80332,7 +81123,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_562.convertToTspans, gd); + this.call(_$svg_text_utils_625.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -80341,7 +81132,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_539._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_601._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -80350,17 +81141,17 @@ function plotPolar(gd, data, layout) { .text(placeholderText) .style({opacity: opacity}) .on('mouseover.opacity', function() { - _$d3_127.select(this).transition().duration(100) + _$d3_130.select(this).transition().duration(100) .style('opacity', 1); }) .on('mouseout.opacity', function() { - _$d3_127.select(this).transition().duration(1000) + _$d3_130.select(this).transition().duration(1000) .style('opacity', 0); }); } var setContenteditable = function() { - this.call(_$svg_text_utils_562.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_625.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -80376,24 +81167,24 @@ function plotPolar(gd, data, layout) { } gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor); - _$plots_647.addLinks(gd); + _$plots_709.addLinks(gd); return Promise.resolve(); } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_573.redraw = function(gd) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.redraw = function(gd) { + gd = _$lib_601.getGraphDiv(gd); - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_570.cleanData(gd.data, gd.data); - _$helpers_570.cleanLayout(gd.layout); + _$helpers_633.cleanData(gd.data, gd.data); + _$helpers_633.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_573.plot(gd).then(function() { + return _$plot_api_636.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -80407,14 +81198,14 @@ _$plot_api_573.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_573.newPlot = function(gd, data, layout, config) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.newPlot = function(gd, data, layout, config) { + gd = _$lib_601.getGraphDiv(gd); // remove gl contexts - _$plots_647.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_709.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); - _$plots_647.purge(gd); - return _$plot_api_573.plot(gd, data, layout, config); + _$plots_709.purge(gd); + return _$plot_api_636.plot(gd, data, layout, config); }; /** @@ -80567,12 +81358,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_539.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_601.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_539.isPlainObject(update)) { + if(!_$lib_601.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -80615,7 +81406,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_539.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_601.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -80635,7 +81426,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_539.nestedProperty(trace, key); + prop = _$lib_601.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -80644,10 +81435,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_539.isArrayOrTypedArray(insert)) { + if(!_$lib_601.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_539.isArrayOrTypedArray(target)) { + if(!_$lib_601.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -80661,7 +81452,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints; // could have chosen null here, -1 just tells us to not take a window - if(!_$fastIsnumeric_139(maxp)) maxp = -1; + if(!_$fastIsnumeric_196(maxp)) maxp = -1; /* * Wrap the nestedProperty in an object containing required data @@ -80742,13 +81533,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_573.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_601.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_539.isTypedArray(target)) { + if(_$lib_601.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -80793,20 +81584,20 @@ _$plot_api_573.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_573.redraw(gd); + var promise = _$plot_api_636.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_553.add(gd, _$plot_api_573.prependTraces, undoArgs, extendTraces, arguments); + _$queue_616.add(gd, _$plot_api_636.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_573.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_601.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_539.isTypedArray(target)) { + if(_$lib_601.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -80850,9 +81641,9 @@ _$plot_api_573.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_573.redraw(gd); + var promise = _$plot_api_636.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_553.add(gd, _$plot_api_573.extendTraces, undoArgs, prependTraces, arguments); + _$queue_616.add(gd, _$plot_api_636.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -80866,11 +81657,11 @@ _$plot_api_573.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_601.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_573.deleteTraces, + undoFunc = _$plot_api_636.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -80887,10 +81678,10 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_539.extendFlat({}, trace); + return _$lib_601.extendFlat({}, trace); }); - _$helpers_570.cleanData(traces, gd.data); + _$helpers_633.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -80905,8 +81696,8 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_573.redraw(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_636.redraw(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -80929,10 +81720,10 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_553.startSequence(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_573.moveTraces(gd, currentIndices, newIndices); - _$queue_553.stopSequence(gd); + _$queue_616.startSequence(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_636.moveTraces(gd, currentIndices, newIndices); + _$queue_616.stopSequence(gd); return promise; }; @@ -80943,11 +81734,11 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_573.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_601.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_573.addTraces, + undoFunc = _$plot_api_636.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -80966,14 +81757,14 @@ _$plot_api_573.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_539.sorterDes); + indices.sort(_$lib_601.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_573.redraw(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_636.redraw(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -81009,8 +81800,8 @@ _$plot_api_573.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_573.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_601.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -81070,8 +81861,8 @@ _$plot_api_573.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_573.redraw(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_636.redraw(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -81106,55 +81897,55 @@ _$plot_api_573.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_573.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_539.getGraphDiv(gd); - _$helpers_570.clearPromiseQueue(gd); +_$plot_api_636.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_601.getGraphDiv(gd); + _$helpers_633.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_539.isPlainObject(astr)) { + else if(_$lib_601.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_539.extendFlat({}, astr); + aobj = _$lib_601.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_539.warn('Restyle fail.', astr, val, _traces); + _$lib_601.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_570.coerceTraceIndices(gd, _traces); + var traces = _$helpers_633.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_570.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_633.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_573.plot); + seq.push(_$plot_api_636.plot); } else { - seq.push(_$plots_647.previousPromises); + seq.push(_$plots_709.previousPromises); - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_576.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_576.doColorBars); + if(flags.style) seq.push(_$subroutines_639.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_639.doColorBars); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - _$queue_553.add(gd, + _$queue_616.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -81177,7 +81968,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_569.traceFlags(); + var flags = _$edit_types_632.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -81190,7 +81981,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_584.id2name(axid); + var axName = _$axes_647.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -81209,13 +82000,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_570.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_633.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_539.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_601.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_539.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_601.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -81232,7 +82023,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_570.hasParent(aobj, ai)) { + if(_$helpers_633.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -81247,7 +82038,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_539.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_601.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -81263,17 +82054,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_539.nestedProperty(cont, ai); + param = _$lib_601.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_575.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_638.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_539.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_601.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -81313,19 +82104,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_539.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_539.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_539.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_601.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_601.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_601.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_539.nestedProperty(cont, 'marker.color') - .set(_$lib_539.nestedProperty(cont, 'marker.colors').get()); + _$lib_601.nestedProperty(cont, 'marker.color') + .set(_$lib_601.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_668.traceIs(cont, 'cartesian')) { - _$lib_539.nestedProperty(cont, 'marker.colors') - .set(_$lib_539.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_731.traceIs(cont, 'cartesian')) { + _$lib_601.nestedProperty(cont, 'marker.colors') + .set(_$lib_601.nestedProperty(cont, 'marker.color').get()); } } @@ -81354,23 +82145,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_570.swapXYData(cont); + _$helpers_633.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } - else if(_$plots_647.dataArrayContainers.indexOf(param.parts[0]) !== -1) { + else if(_$plots_709.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_570.manageArrayContainers(param, newVal, undoit); + _$helpers_633.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_539.isArrayOrTypedArray(newVal) || _$lib_539.isArrayOrTypedArray(oldVal)) + _$lib_601.isArrayOrTypedArray(newVal) || _$lib_601.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_569.update(flags, valObject); + else _$edit_types_632.update(flags, valObject); } else { /* @@ -81389,12 +82180,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_584.swap(gd, traces); + _$axes_647.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_539.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_601.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -81409,7 +82200,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_668.traceIs(trace, 'cartesian')) { + if(_$registry_731.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -81426,7 +82217,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_584.list(gd); + var axList = _$axes_647.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -81447,7 +82238,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_539.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_601.extendDeepNoArrays([], [redoit, traces]) }; } @@ -81471,9 +82262,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_573.relayout = function relayout(gd, astr, val) { - gd = _$lib_539.getGraphDiv(gd); - _$helpers_570.clearPromiseQueue(gd); +_$plot_api_636.relayout = function relayout(gd, astr, val) { + gd = _$lib_601.getGraphDiv(gd); + _$helpers_633.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -81482,50 +82273,74 @@ _$plot_api_573.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_539.isPlainObject(astr)) { - aobj = _$lib_539.extendFlat({}, astr); + } else if(_$lib_601.isPlainObject(astr)) { + aobj = _$lib_601.extendFlat({}, astr); } else { - _$lib_539.warn('Relayout fail.', astr, val); + _$lib_601.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_570.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_633.clearAxisAutomargins(gd); // fill in redraw sequence // even if we don't have anything left in aobj, // something may have happened within relayout that we // need to wait for - var seq = [_$plots_647.previousPromises]; + var seq = [_$plots_709.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_576.layoutReplot); + seq.push(_$subroutines_639.layoutReplot); } else if(Object.keys(aobj).length) { - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); + + if(flags.legend) seq.push(_$subroutines_639.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_639.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_639.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_639.doTicksRelayout, + _$subroutines_639.drawData, + _$subroutines_639.finalDraw + ); + } - if(flags.legend) seq.push(_$subroutines_576.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_576.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_576.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_576.doModeBar); - if(flags.camera) seq.push(_$subroutines_576.doCamera); + if(flags.ticks) seq.push(_$subroutines_639.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_639.doModeBar); + if(flags.camera) seq.push(_$subroutines_639.doCamera); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - _$queue_553.add(gd, + _$queue_616.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -81538,7 +82353,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_584.list(gd), + axes = _$axes_647.list(gd), arrayEdits = {}, arrayStr, i, @@ -81561,7 +82376,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_569.layoutFlags(); + var flags = _$edit_types_632.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -81580,9 +82395,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_570.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_633.hasParent(aobj, attr)) return; - var p = _$lib_539.nestedProperty(layout, attr); + var p = _$lib_601.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -81596,18 +82411,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_584.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_647.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_570.hasParent(aobj, ai)) { + if(_$helpers_633.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_539.nestedProperty(layout, ai); + var p = _$lib_601.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -81619,8 +82434,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_539.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_539.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_601.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_601.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -81631,11 +82446,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_575.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_638.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_539.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_601.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -81649,12 +82464,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_539.nestedProperty(fullLayout, ptrunk).get(); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_601.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -81662,7 +82477,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -81722,8 +82537,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_668.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_668.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_731.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_731.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -81731,18 +82546,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_589.AX_NAME_PATTERN)) { - var fullProp = _$lib_539.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_601.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_668.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_668.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_731.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_731.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -81751,12 +82566,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_572.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_635.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_539.nestedProperty(layout, arrayStr); + var componentArray = _$lib_601.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -81766,28 +82581,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_569.update(flags, updateValObject); + else _$edit_types_632.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_572.isAddVal(vi)) { + if(_$manage_arrays_635.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_572.isRemoveVal(vi)) { + else if(_$manage_arrays_635.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_539.warn('unrecognized full object value', aobj); + else _$lib_601.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_569.update(flags, updateValObject); - + else { + _$edit_types_632.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -81816,7 +82632,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_569.update(flags, valObject); + else if(valObject) _$edit_types_632.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -81825,8 +82641,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_572.applyContainerArrayChanges(gd, - _$lib_539.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_635.applyContainerArrayChanges(gd, + _$lib_601.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -81844,7 +82660,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_584.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_647.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -81868,7 +82684,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_539.extendDeep({}, redoit) + eventData: _$lib_601.extendDeep({}, redoit) }; } @@ -81883,16 +82699,16 @@ function updateAutosize(gd) { var oldHeight = fullLayout.height; // calculate autosizing - if(gd.layout.autosize) _$plots_647.plotAutoSize(gd, gd.layout, fullLayout); + if(gd.layout.autosize) _$plots_709.plotAutoSize(gd, gd.layout, fullLayout); return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight); } // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_539.isPlainObject(obj)) return false; + if(!_$lib_601.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_584.getFromId(gd, axRef); + ax = _$axes_647.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -81902,7 +82718,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_584.getFromId(gd, axLetter); + ax = _$axes_647.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -81922,32 +82738,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_573.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_539.getGraphDiv(gd); - _$helpers_570.clearPromiseQueue(gd); +_$plot_api_636.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_601.getGraphDiv(gd); + _$helpers_633.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_539.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_539.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_601.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_601.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_570.coerceTraceIndices(gd, _traces); + var traces = _$helpers_633.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_539.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_601.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_539.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_601.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_570.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_570.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_633.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_633.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -81961,35 +82777,43 @@ _$plot_api_573.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_573.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_636.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_573.plot); + seq.push(_$plot_api_636.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_576.layoutReplot); + seq.push(_$subroutines_639.layoutReplot); } else { - seq.push(_$plots_647.previousPromises); - _$plots_647.supplyDefaults(gd); - - if(restyleFlags.style) seq.push(_$subroutines_576.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_576.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_576.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_576.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_576.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_576.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_576.doCamera); + seq.push(_$plots_709.previousPromises); + _$plots_709.supplyDefaults(gd); + + if(restyleFlags.style) seq.push(_$subroutines_639.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_639.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_639.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_639.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_639.doAutoRangeAndConstraints, + _$subroutines_639.doTicksRelayout, + _$subroutines_639.drawData, + _$subroutines_639.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_639.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_639.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_639.doCamera); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - _$queue_553.add(gd, + _$queue_616.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -82025,23 +82849,23 @@ _$plot_api_573.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_573.react = function(gd, data, layout, config) { +_$plot_api_636.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_573.addFrames(gd, frames); } + function addFrames() { return _$plot_api_636.addFrames(gd, frames); } - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_539.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_573.newPlot(gd, data, layout, config); + if(!_$lib_601.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_636.newPlot(gd, data, layout, config); } else { - if(_$lib_539.isPlainObject(data)) { + if(_$lib_601.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -82053,18 +82877,18 @@ _$plot_api_573.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_539.extendDeep({}, gd._context); + var oldConfig = _$lib_601.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_570.cleanData(gd.data, []); + _$helpers_633.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_570.cleanLayout(gd.layout); + _$helpers_633.cleanLayout(gd.layout); - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); var newFullData = gd._fullData; var newFullLayout = gd._fullLayout; @@ -82086,7 +82910,7 @@ _$plot_api_573.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_570.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_633.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -82096,27 +82920,27 @@ _$plot_api_573.react = function(gd, data, layout, config) { if(frames) { gd._transitionData = {}; - _$plots_647.createTransitionData(gd); + _$plots_709.createTransitionData(gd); seq.push(addFrames); } if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_573.plot); + seq.push(_$plot_api_636.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_668.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_539.noop) { + var drawOne = _$registry_731.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_601.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_668.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_539.noop) { + var draw = _$registry_731.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_601.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -82124,19 +82948,27 @@ _$plot_api_573.react = function(gd, data, layout, config) { } } - seq.push(_$plots_647.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_576.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_576.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_576.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_576.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_576.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_576.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_576.doCamera); + seq.push(_$plots_709.previousPromises); + if(restyleFlags.style) seq.push(_$subroutines_639.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_639.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_639.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_639.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_639.doAutoRangeAndConstraints, + _$subroutines_639.doTicksRelayout, + _$subroutines_639.drawData, + _$subroutines_639.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_639.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_639.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_639.doCamera); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - plotDone = _$lib_539.syncOrAsync(seq, gd); + plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -82159,12 +82991,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_569.traceFlags(); + var flags = _$edit_types_632.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_575.getTraceValObject(trace, parts); + return _$plot_schema_638.getTraceValObject(trace, parts); } var diffOpts = { @@ -82174,11 +83006,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_584.getFromId(gd, trace.xaxis).autorange || - _$axes_584.getFromId(gd, trace.yaxis).autorange + _$axes_647.getFromId(gd, trace.xaxis).autorange || + _$axes_647.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -82191,11 +83029,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_569.layoutFlags(); + var flags = _$edit_types_632.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_575.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_638.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -82234,10 +83072,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_539.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_601.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_569.update(flags, valObject); + _$edit_types_632.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -82317,7 +83155,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_539.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_601.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -82329,7 +83167,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_539.isPlainObject(oldVal)) { + else if(!valType && _$lib_601.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -82383,7 +83221,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_539.isPlainObject(oldVal) && _$lib_539.isPlainObject(newVal)) { + if(_$lib_601.isPlainObject(oldVal) && _$lib_601.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -82394,7 +83232,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_539.isPlainObject(oldVal[i]) && _$lib_539.isPlainObject(newVal[i])) { + if(_$lib_601.isPlainObject(oldVal[i]) && _$lib_601.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -82439,10 +83277,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_601.getGraphDiv(gd); - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -82458,7 +83296,7 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts trans._frameQueue = []; } - animationOpts = _$plots_647.supplyAnimationDefaults(animationOpts); + animationOpts = _$plots_709.supplyAnimationDefaults(animationOpts); var transitionOpts = animationOpts.transition; var frameOpts = animationOpts.frame; @@ -82532,7 +83370,7 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts if(frameList[i].type === 'byname') { // If it's a named frame, compute it: - computedFrame = _$plots_647.computeFrame(gd, frameList[i].name); + computedFrame = _$plots_709.computeFrame(gd, frameList[i].name); } else { // Otherwise we must have been given a simple object, so treat // the input itself as the computed frame. @@ -82613,10 +83451,10 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts // This is simply called and it's left to .transition to decide how to manage // interrupting current transitions. That means we don't need to worry about // how it resolves or what happens after this: - _$plots_647.transition(gd, + _$plots_709.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_570.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_633.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -82686,13 +83524,13 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_539.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_601.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_539.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_601.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -82721,10 +83559,10 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_539.isPlainObject(frameOrName)) { + } else if(_$lib_601.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_539.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_601.extendFlat({}, frameOrName)) }); } } @@ -82734,7 +83572,7 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_539.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_601.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -82803,14 +83641,14 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_573.addFrames = function(gd, frameList, indices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.addFrames = function(gd, frameList, indices) { + gd = _$lib_601.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -82837,7 +83675,7 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_539.isPlainObject(frameList[i])) continue; + if(!_$lib_601.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -82849,14 +83687,14 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_539.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_601.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_539.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_601.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -82865,7 +83703,7 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { _frameHashLocal[lookupName] = {name: lookupName}; insertions.push({ - frame: _$plots_647.supplyFrameDefaults(frameList[i]), + frame: _$plots_709.supplyFrameDefaults(frameList[i]), index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i }); } @@ -82885,7 +83723,7 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_539.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_601.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -82913,14 +83751,14 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { } } - var undoFunc = _$plots_647.modifyFrames, - redoFunc = _$plots_647.modifyFrames, + var undoFunc = _$plots_709.modifyFrames, + redoFunc = _$plots_709.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_553) _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_616) _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return _$plots_647.modifyFrames(gd, ops); + return _$plots_709.modifyFrames(gd, ops); }; /** @@ -82932,10 +83770,10 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_573.deleteFrames = function(gd, frameList) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.deleteFrames = function(gd, frameList) { + gd = _$lib_601.getGraphDiv(gd); - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -82960,14 +83798,14 @@ _$plot_api_573.deleteFrames = function(gd, frameList) { revops.unshift({type: 'insert', index: idx, value: _frames[idx]}); } - var undoFunc = _$plots_647.modifyFrames, - redoFunc = _$plots_647.modifyFrames, + var undoFunc = _$plots_709.modifyFrames, + redoFunc = _$plots_709.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_553) _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_616) _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return _$plots_647.modifyFrames(gd, ops); + return _$plots_709.modifyFrames(gd, ops); }; /** @@ -82976,20 +83814,21 @@ _$plot_api_573.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_573.purge = function purge(gd) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.purge = function purge(gd) { + gd = _$lib_601.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_647.cleanPlot([], {}, fullData, fullLayout); + _$plots_709.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties - _$plots_647.purge(gd); + _$plots_709.purge(gd); // purge event emitter methods - _$Events_527.purge(gd); + _$Events_589.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -83004,7 +83843,7 @@ _$plot_api_573.purge = function purge(gd) { // makePlotFramework: Create the plot container and axes // ------------------------------------------------------- function makePlotFramework(gd) { - var gd3 = _$d3_127.select(gd); + var gd3 = _$d3_130.select(gd); var fullLayout = gd._fullLayout; // Plot container @@ -83044,14 +83883,14 @@ function makePlotFramework(gd) { if(!fullLayout._uid) { var otherUids = []; - _$d3_127.selectAll('defs').each(function() { + _$d3_130.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_539.randstr(otherUids); + fullLayout._uid = _$lib_601.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') - .attr(_$xmlns_namespaces_519.svgAttrs); + .attr(_$xmlns_namespaces_580.svgAttrs); fullLayout._defs = fullLayout._paper.append('defs') .attr('id', 'defs-' + fullLayout._uid); @@ -83123,7 +83962,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_672 = {}; +var _$helpers_735 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -83135,7 +83974,7 @@ var _$helpers_672 = {}; 'use strict'; -_$helpers_672.getDelay = function(fullLayout) { +_$helpers_735.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -83145,7 +83984,7 @@ _$helpers_672.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_672.getRedrawFunc = function(gd) { +_$helpers_735.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -83170,11 +84009,11 @@ _$helpers_672.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -var __EventEmitter_674 = _$EventEmitter_137.EventEmitter; +/* removed: var _$lib_601 = require('../lib'); */; +var __EventEmitter_737 = _$EventEmitter_194.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_674(); + var ev = opts.emitter || new __EventEmitter_737(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -83182,7 +84021,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_539.isIE() && format !== 'svg') { + if(_$lib_601.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -83273,7 +84112,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_674 = svgToImg; +var _$svgToImg_737 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -83286,19 +84125,19 @@ var _$svgToImg_674 = svgToImg; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$drawing_436 = require('../components/drawing'); */; -/* removed: var _$color_411 = require('../components/color'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$drawing_498 = require('../components/drawing'); */; +/* removed: var _$color_473 = require('../components/color'); */; -/* removed: var _$xmlns_namespaces_519 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$xmlns_namespaces_580 = require('../constants/xmlns_namespaces'); */; var DOUBLEQUOTE_REGEX = /"/g; var DUMMY_SUB = 'TOBESTRIPPED'; var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g'); function htmlEntityDecode(s) { - var hiddenDiv = _$d3_127.select('body').append('div').style({display: 'none'}).html(''); + var hiddenDiv = _$d3_130.select('body').append('div').style({display: 'none'}).html(''); var replaced = s.replace(/(&[^;]*;)/gi, function(d) { if(d === '<') { return '<'; } // special handling for brackets if(d === '&rt;') { return '>'; } @@ -83313,7 +84152,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_676 = function toSVG(gd, format, scale) { +var _$toSVG_739 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -83327,8 +84166,8 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { // have to remove them, and providing the right namespaces in the svg to // begin with svg.insert('rect', ':first-child') - .call(_$drawing_436.setRect, 0, 0, width, height) - .call(_$color_411.fill, fullLayout.paper_bgcolor); + .call(_$drawing_498.setRect, 0, 0, width, height) + .call(_$color_473.fill, fullLayout.paper_bgcolor); // subplot-specific to-SVG methods // which notably add the contents of the gl-container @@ -83368,7 +84207,7 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { svg.selectAll('text') .attr({'data-unformatted': null, 'data-math': null}) .each(function() { - var txt = _$d3_127.select(this); + var txt = _$d3_130.select(this); // hidden text is pre-formatting mathjax, the browser ignores it // but in a static plot it's useless and it can confuse batik @@ -83394,7 +84233,7 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { }); svg.selectAll('.point,.scatterpts').each(function() { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var fill = this.style.fill; // similar to font family styles above, @@ -83413,8 +84252,8 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { // fix for IE namespacing quirk? // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie - svg.node().setAttributeNS(_$xmlns_namespaces_519.xmlns, 'xmlns', _$xmlns_namespaces_519.svg); - svg.node().setAttributeNS(_$xmlns_namespaces_519.xmlns, 'xmlns:xlink', _$xmlns_namespaces_519.xlink); + svg.node().setAttributeNS(_$xmlns_namespaces_580.xmlns, 'xmlns', _$xmlns_namespaces_580.svg); + svg.node().setAttributeNS(_$xmlns_namespaces_580.xmlns, 'xmlns:xlink', _$xmlns_namespaces_580.xlink); if(format === 'svg' && scale) { svg.attr('width', scale * width); @@ -83436,7 +84275,7 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_539.isIE()) { + if(_$lib_601.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -83461,14 +84300,14 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_573 = require('./plot_api'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$plot_api_636 = require('./plot_api'); */; +/* removed: var _$lib_601 = require('../lib'); */; -/* removed: var _$helpers_672 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_676 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_674 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_735 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_739 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_737 = require('../snapshot/svgtoimg'); */; -var __attrs_577 = { +var __attrs_640 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -83541,19 +84380,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_539.isPlainObject(gd)) { + if(_$lib_601.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_539.getGraphDiv(gd); - data = _$lib_539.extendDeep([], gd.data); - layout = _$lib_539.extendDeep({}, gd.layout); + gd = _$lib_601.getGraphDiv(gd); + data = _$lib_601.extendDeep([], gd.data); + layout = _$lib_601.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_539.validate(opts[attr], __attrs_577[attr]); + return !(attr in opts) || _$lib_601.validate(opts[attr], __attrs_640[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -83567,7 +84406,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts, fullOpts, __attrs_577, attr, dflt); + return _$lib_601.coerce(opts, fullOpts, __attrs_640, attr, dflt); } var format = coerce('format'); @@ -83584,31 +84423,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_539.extendFlat({}, layout); + var layoutImage = _$lib_601.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_539.extendFlat({}, config, { + var configImage = _$lib_601.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_672.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_735.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_672.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_735.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_676(clonedGd, format, scale); + var svg = _$toSVG_739(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_573.purge(clonedGd); + _$plot_api_636.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -83620,9 +84459,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_539.randstr(); + canvas.id = _$lib_601.randstr(); - _$svgToImg_674({ + _$svgToImg_737({ format: format, width: width, height: height, @@ -83649,7 +84488,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_573.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_636.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -83658,7 +84497,7 @@ function toImage(gd, opts) { }); } -var _$toImage_577 = toImage; +var _$toImage_640 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -83670,14 +84509,14 @@ var _$toImage_577 = toImage; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$plot_schema_575 = require('./plot_schema'); */; -/* removed: var _$plot_config_574 = require('./plot_config'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +/* removed: var _$plot_schema_638 = require('./plot_schema'); */; +/* removed: var _$plot_config_637 = require('./plot_config'); */; -var __isPlainObject_578 = _$lib_539.isPlainObject; -var __isArray_578 = Array.isArray; -var __isArrayOrTypedArray_578 = _$lib_539.isArrayOrTypedArray; +var __isPlainObject_641 = _$lib_601.isPlainObject; +var __isArray_641 = Array.isArray; +var __isArrayOrTypedArray_641 = _$lib_601.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -83700,15 +84539,15 @@ var __isArrayOrTypedArray_578 = _$lib_539.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_578 = function valiate(data, layout) { - var schema = _$plot_schema_575.get(); +var _$valiate_641 = function valiate(data, layout) { + var schema = _$plot_schema_638.get(); var errorList = []; - var gd = {_context: _$lib_539.extendFlat({}, _$plot_config_574)}; + var gd = {_context: _$lib_601.extendFlat({}, _$plot_config_637)}; var dataIn, layoutIn; - if(__isArray_578(data)) { - gd.data = _$lib_539.extendDeep([], data); + if(__isArray_641(data)) { + gd.data = _$lib_601.extendDeep([], data); dataIn = data; } else { @@ -83717,8 +84556,8 @@ var _$valiate_578 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_578(layout)) { - gd.layout = _$lib_539.extendDeep({}, layout); + if(__isPlainObject_641(layout)) { + gd.layout = _$lib_601.extendDeep({}, layout); layoutIn = layout; } else { @@ -83733,7 +84572,7 @@ var _$valiate_578 = function valiate(data, layout) { // gd.data and gd.layout after supplyDefaults as some attributes // in gd.data and gd.layout (still) get mutated during this step. - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); var dataOut = gd._fullData, len = dataIn.length; @@ -83742,7 +84581,7 @@ var _$valiate_578 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_578(traceIn)) { + if(!__isPlainObject_641(traceIn)) { errorList.push(format('object', base)); continue; } @@ -83762,13 +84601,13 @@ var _$valiate_578 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_578(traceIn, traceOut, traceSchema, errorList, base); + __crawl_641(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_578(transformsIn)) { + if(!__isArray_641(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -83778,7 +84617,7 @@ var _$valiate_578 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_578(transformsIn[j])) { + if(!__isPlainObject_641(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -83793,7 +84632,7 @@ var _$valiate_578 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_578(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_641(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -83801,13 +84640,13 @@ var _$valiate_578 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_578(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_641(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_578(objIn, objOut, schema, list, base, path) { +function __crawl_641(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -83832,10 +84671,10 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_578(valIn) && __isPlainObject_578(valOut)) { - __crawl_578(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_641(valIn) && __isPlainObject_641(valOut)) { + __crawl_641(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_578(valIn)) { + else if(isInfoArray && __isArray_641(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -83845,7 +84684,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_578(valIn[n])) { + if(__isArray_641(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -83854,7 +84693,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_539.validate(valInPart, item)) { + if(!_$lib_601.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -83872,7 +84711,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_539.validate(valInPart, item)) { + if(!_$lib_601.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -83881,7 +84720,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_578(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_641(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -83895,9 +84734,9 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_578(valIn[_index]) && __isPlainObject_578(valOut[j])) { + if(__isPlainObject_641(valIn[_index]) && __isPlainObject_641(valOut[j])) { indexList.push(_index); - __crawl_578(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_641(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -83906,7 +84745,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_578(valIn[j])) { + if(!__isPlainObject_641(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -83914,16 +84753,16 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_578(valIn) && __isPlainObject_578(valOut)) { + else if(!__isPlainObject_641(valIn) && __isPlainObject_641(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_578(valIn) && __isArrayOrTypedArray_578(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_641(valIn) && __isArrayOrTypedArray_641(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_539.validate(valIn, nestedSchema)) { + else if(!_$lib_601.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -83943,7 +84782,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_539.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_601.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -83975,7 +84814,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_578(valIn) ? 'container' : 'key'; + var target = __isPlainObject_641(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -84001,7 +84840,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_578(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_641(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -84014,7 +84853,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_578(base)) { + if(__isArray_641(base)) { container = base[0]; trace = base[1]; } @@ -84027,7 +84866,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_539.log(msg); + _$lib_601.log(msg); return { code: code, @@ -84057,7 +84896,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_539.counterRegex('([a-z]+)'); +var idRegex = _$lib_601.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -84069,7 +84908,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_578(path)) return String(path); + if(!__isArray_641(path)) return String(path); var astr = ''; @@ -84158,7 +84997,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_671 = fileSaver; +var _$fileSaver_734 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -84171,9 +85010,9 @@ var _$fileSaver_671 = fileSaver; 'use strict'; -/* removed: var _$toImage_577 = require('../plot_api/to_image'); */; -/* removed: var _$lib_539 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_671 = require('./filesaver'); */; +/* removed: var _$toImage_640 = require('../plot_api/to_image'); */; +/* removed: var _$lib_601 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_734 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -84201,19 +85040,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_539.isIE() && opts.format !== 'svg') { + if(_$lib_601.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_577(gd, opts); + var promise = _$toImage_640(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_671(result, filename); + return _$fileSaver_734(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -84223,9 +85062,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_670 = downloadImage; +var _$downloadImage_733 = downloadImage; -var _$plot_api_571 = {}; +var _$plot_api_634 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -84236,29 +85075,29 @@ var _$plot_api_571 = {}; 'use strict'; -/* removed: var _$plot_api_573 = require('./plot_api'); */; +/* removed: var _$plot_api_636 = require('./plot_api'); */; -_$plot_api_571.plot = _$plot_api_573.plot; -_$plot_api_571.newPlot = _$plot_api_573.newPlot; -_$plot_api_571.restyle = _$plot_api_573.restyle; -_$plot_api_571.relayout = _$plot_api_573.relayout; -_$plot_api_571.redraw = _$plot_api_573.redraw; -_$plot_api_571.update = _$plot_api_573.update; -_$plot_api_571.react = _$plot_api_573.react; -_$plot_api_571.extendTraces = _$plot_api_573.extendTraces; -_$plot_api_571.prependTraces = _$plot_api_573.prependTraces; -_$plot_api_571.addTraces = _$plot_api_573.addTraces; -_$plot_api_571.deleteTraces = _$plot_api_573.deleteTraces; -_$plot_api_571.moveTraces = _$plot_api_573.moveTraces; -_$plot_api_571.purge = _$plot_api_573.purge; -_$plot_api_571.addFrames = _$plot_api_573.addFrames; -_$plot_api_571.deleteFrames = _$plot_api_573.deleteFrames; -_$plot_api_571.animate = _$plot_api_573.animate; -_$plot_api_571.setPlotConfig = _$plot_api_573.setPlotConfig; +_$plot_api_634.plot = _$plot_api_636.plot; +_$plot_api_634.newPlot = _$plot_api_636.newPlot; +_$plot_api_634.restyle = _$plot_api_636.restyle; +_$plot_api_634.relayout = _$plot_api_636.relayout; +_$plot_api_634.redraw = _$plot_api_636.redraw; +_$plot_api_634.update = _$plot_api_636.update; +_$plot_api_634.react = _$plot_api_636.react; +_$plot_api_634.extendTraces = _$plot_api_636.extendTraces; +_$plot_api_634.prependTraces = _$plot_api_636.prependTraces; +_$plot_api_634.addTraces = _$plot_api_636.addTraces; +_$plot_api_634.deleteTraces = _$plot_api_636.deleteTraces; +_$plot_api_634.moveTraces = _$plot_api_636.moveTraces; +_$plot_api_634.purge = _$plot_api_636.purge; +_$plot_api_634.addFrames = _$plot_api_636.addFrames; +_$plot_api_634.deleteFrames = _$plot_api_636.deleteFrames; +_$plot_api_634.animate = _$plot_api_636.animate; +_$plot_api_634.setPlotConfig = _$plot_api_636.setPlotConfig; -_$plot_api_571.toImage = _$toImage_577; -_$plot_api_571.validate = _$valiate_578; -_$plot_api_571.downloadImage = _$downloadImage_670; +_$plot_api_634.toImage = _$toImage_640; +_$plot_api_634.validate = _$valiate_641; +_$plot_api_634.downloadImage = _$downloadImage_733; /** * Copyright 2012-2018, Plotly, Inc. @@ -84271,10 +85110,10 @@ _$plot_api_571.downloadImage = _$downloadImage_670; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$lib_601 = require('../lib'); */; -var __extendFlat_669 = _$lib_539.extendFlat; -var extendDeep = _$lib_539.extendDeep; +var __extendFlat_732 = _$lib_601.extendFlat; +var extendDeep = _$lib_601.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -84319,7 +85158,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_669 = function clonePlot(graphObj, options) { +var _$clonePlot_732 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -84392,9 +85231,9 @@ var _$clonePlot_669 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_669(scene.xaxis, axesImageOverride); - __extendFlat_669(scene.yaxis, axesImageOverride); - __extendFlat_669(scene.zaxis, axesImageOverride); + __extendFlat_732(scene.xaxis, axesImageOverride); + __extendFlat_732(scene.yaxis, axesImageOverride); + __extendFlat_732(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -84443,27 +85282,27 @@ var _$clonePlot_669 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_675 = _$EventEmitter_137.EventEmitter; +var __EventEmitter_738 = _$EventEmitter_194.EventEmitter; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; -/* removed: var _$helpers_672 = require('./helpers'); */; -/* removed: var _$clonePlot_669 = require('./cloneplot'); */; -/* removed: var _$toSVG_676 = require('./tosvg'); */; -/* removed: var _$svgToImg_674 = require('./svgtoimg'); */; +/* removed: var _$helpers_735 = require('./helpers'); */; +/* removed: var _$clonePlot_732 = require('./cloneplot'); */; +/* removed: var _$toSVG_739 = require('./tosvg'); */; +/* removed: var _$svgToImg_737 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_675(gd, opts) { +function __toImage_738(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_675(); + var ev = new __EventEmitter_738(); - var clone = _$clonePlot_669(gd, {format: 'png'}); + var clone = _$clonePlot_732(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -84472,15 +85311,15 @@ function __toImage_675(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_672.getDelay(clonedGd._fullLayout); + var delay = _$helpers_735.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_676(clonedGd); + var svg = _$toSVG_739(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_539.randstr(); + canvas.id = _$lib_601.randstr(); - ev = _$svgToImg_674({ + ev = _$svgToImg_737({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -84496,9 +85335,9 @@ function __toImage_675(gd, opts) { }, delay); } - var redrawFunc = _$helpers_672.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_735.getRedrawFunc(clonedGd); - _$registry_668.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_731.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -84509,7 +85348,7 @@ function __toImage_675(gd, opts) { return ev; } -var _$toImage_675 = __toImage_675; +var _$toImage_738 = __toImage_738; /** * Copyright 2012-2018, Plotly, Inc. @@ -84522,19 +85361,19 @@ var _$toImage_675 = __toImage_675; 'use strict'; -/* removed: var _$helpers_672 = require('./helpers'); */; +/* removed: var _$helpers_735 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_672.getDelay, - getRedrawFunc: _$helpers_672.getRedrawFunc, - clone: _$clonePlot_669, - toSVG: _$toSVG_676, - svgToImg: _$svgToImg_674, - toImage: _$toImage_675, - downloadImage: _$downloadImage_670 + getDelay: _$helpers_735.getDelay, + getRedrawFunc: _$helpers_735.getRedrawFunc, + clone: _$clonePlot_732, + toSVG: _$toSVG_739, + svgToImg: _$svgToImg_737, + toImage: _$toImage_738, + downloadImage: _$downloadImage_733 }; -var _$Snapshot_673 = Snapshot; +var _$Snapshot_736 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -84547,23 +85386,23 @@ var _$Snapshot_673 = Snapshot; 'use strict'; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; -var _$calcMarkerColorscale_867 = function calcMarkerColorscale(trace) { - if(_$subtypes_884.hasLines(trace) && _$hasColorscale_425(trace, 'line')) { - _$calc_418(trace, trace.line.color, 'line', 'c'); +var _$calcMarkerColorscale_932 = function calcMarkerColorscale(trace) { + if(_$subtypes_949.hasLines(trace) && _$hasColorscale_487(trace, 'line')) { + _$calc_480(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_884.hasMarkers(trace)) { - if(_$hasColorscale_425(trace, 'marker')) { - _$calc_418(trace, trace.marker.color, 'marker', 'c'); + if(_$subtypes_949.hasMarkers(trace)) { + if(_$hasColorscale_487(trace, 'marker')) { + _$calc_480(trace, trace.marker.color, 'marker', 'c'); } - if(_$hasColorscale_425(trace, 'marker.line')) { - _$calc_418(trace, trace.marker.line.color, 'marker.line', 'c'); + if(_$hasColorscale_487(trace, 'marker.line')) { + _$calc_480(trace, trace.marker.line.color, 'marker.line', 'c'); } } }; @@ -84578,20 +85417,20 @@ var _$calcMarkerColorscale_867 = function calcMarkerColorscale(trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_863 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_928 = _$lib_601.isArrayOrTypedArray; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __BADNUM_863 = _$numerical_517.BADNUM; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __BADNUM_928 = _$numerical_578.BADNUM; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_867 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('./calc_selection'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_932 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('./calc_selection'); */; -function __calc_863(gd, trace) { - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); +function __calc_928(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -84601,18 +85440,18 @@ function __calc_863(gd, trace) { calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); for(var i = 0; i < serieslen; i++) { - cd[i] = (_$fastIsnumeric_139(x[i]) && _$fastIsnumeric_139(y[i])) ? + cd[i] = (_$fastIsnumeric_196(x[i]) && _$fastIsnumeric_196(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_863, y: __BADNUM_863}; + {x: __BADNUM_928, y: __BADNUM_928}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_861(cd, trace); - _$calcMarkerColorscale_867(trace); - _$calcSelection_864(cd, trace); + _$arraysToCalcdata_926(cd, trace); + _$calcMarkerColorscale_932(trace); + _$calcSelection_929(cd, trace); gd.firstscatter = false; return cd; @@ -84645,9 +85484,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)) + (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -84666,12 +85505,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_584.expand(xa, x, xOptions); - _$axes_584.expand(ya, y, yOptions); + _$axes_647.expand(xa, x, xOptions); + _$axes_647.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_884.hasMarkers(trace)) return; + if(!_$subtypes_949.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -84689,10 +85528,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_863(marker.size)) { + if(__isArrayOrTypedArray_928(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_584.setConvert(ax); + _$axes_647.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -84707,8 +85546,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_863 = { - calc: __calc_863, +var _$calc_928 = { + calc: __calc_928, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -84726,7 +85565,7 @@ var _$calc_863 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_865 = function cleanData(fullData) { +var _$cleanData_930 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -84762,10 +85601,10 @@ var _$cleanData_865 = function cleanData(fullData) { 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -var __isArrayOrTypedArray_871 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$color_473 = require('../../components/color'); */; +var __isArrayOrTypedArray_936 = _$lib_601.isArrayOrTypedArray; -var _$fillColorDefaults_871 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_936 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -84773,15 +85612,15 @@ var _$fillColorDefaults_871 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_871(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_936(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_871(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_936(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } - coerce('fillcolor', _$color_411.addOpacity( + coerce('fillcolor', _$color_473.addOpacity( (traceOut.line || {}).color || inheritColorFromMarker || defaultColor, 0.5 @@ -84798,20 +85637,20 @@ var _$fillColorDefaults_871 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_875 = _$lib_539.isArrayOrTypedArray; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; +var __isArrayOrTypedArray_940 = _$lib_601.isArrayOrTypedArray; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_875 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_940 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); - if(_$hasColorscale_425(traceIn, 'line')) { - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); + if(_$hasColorscale_487(traceIn, 'line')) { + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_875(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_940(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -84832,7 +85671,7 @@ var _$lineDefaults_875 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_877 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_942 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -84848,11 +85687,11 @@ var _$handleLineShapeDefaults_877 = function handleLineShapeDefaults(traceIn, tr 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -84860,8 +85699,8 @@ var _$handleLineShapeDefaults_877 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_884.isBubble(traceIn), +var _$markerDefaults_945 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_949.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -84875,8 +85714,8 @@ var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultCol coerce('marker.size'); coerce('marker.color', defaultColor); - if(_$hasColorscale_425(traceIn, 'marker')) { - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); + if(_$hasColorscale_487(traceIn, 'marker')) { + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); } if(!opts.noSelect) { @@ -84894,12 +85733,12 @@ var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultCol if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) { defaultMLC = lineColor; } - else if(isBubble) defaultMLC = _$color_411.background; - else defaultMLC = _$color_411.defaultLine; + else if(isBubble) defaultMLC = _$color_473.background; + else defaultMLC = _$color_473.defaultLine; coerce('marker.line.color', defaultMLC); - if(_$hasColorscale_425(traceIn, 'marker.line')) { - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}); + if(_$hasColorscale_487(traceIn, 'marker.line')) { + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}); } coerce('marker.line.width', isBubble ? 1 : 0); @@ -84930,17 +85769,17 @@ var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_885 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_950 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_539.coerceFont(coerce, 'textfont', layout.font); + _$lib_601.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -84958,27 +85797,27 @@ var _$text_defaults_885 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -/* removed: var _$attributes_862 = require('./attributes'); */; -/* removed: var _$constants_868 = require('./constants'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_886 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_880 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_927 = require('./attributes'); */; +/* removed: var _$constants_933 = require('./constants'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_951 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_945 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_934 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_862, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_927, attr, dflt); } - var len = _$handleXYDefaults_886(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_951(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -84988,24 +85827,24 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -85013,8 +85852,8 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -85022,11 +85861,11 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -85040,18 +85879,18 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; -var _$getTraceColor_872 = function getTraceColor(trace, di) { +var _$getTraceColor_937 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes if(trace.mode === 'lines') { lc = trace.line.color; - return (lc && _$color_411.opacity(lc)) ? + return (lc && _$color_473.opacity(lc)) ? lc : trace.fillcolor; } else if(trace.mode === 'none') { @@ -85061,21 +85900,21 @@ var _$getTraceColor_872 = function getTraceColor(trace, di) { var mc = di.mcc || (trace.marker || {}).color, mlc = di.mlcc || ((trace.marker || {}).line || {}).color; - tc = (mc && _$color_411.opacity(mc)) ? mc : - (mlc && _$color_411.opacity(mlc) && + tc = (mc && _$color_473.opacity(mc)) ? mc : + (mlc && _$color_473.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : ''; if(tc) { // make sure the points aren't TOO transparent - if(_$color_411.opacity(tc) < 0.3) { - return _$color_411.addOpacity(tc, 0.3); + if(_$color_473.opacity(tc) < 0.3) { + return _$color_473.addOpacity(tc, 0.3); } else return tc; } else { lc = (trace.line || {}).color; - return (lc && _$color_411.opacity(lc) && - _$subtypes_884.hasLines(trace) && trace.line.width) ? + return (lc && _$color_473.opacity(lc) && + _$subtypes_949.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -85091,14 +85930,14 @@ var _$getTraceColor_872 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$getTraceColor_872 = require('./get_trace_color'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$fillHoverText_870 = require('./fill_hover_text'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$getTraceColor_937 = require('./get_trace_color'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('./fill_hover_text'); */; -var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_938 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -85138,9 +85977,9 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { var dy = ya.c2p(di.y) - ypx; return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad); }; - var distfn = _$fx_453.getDistanceFunction(hovermode, dx, dy, dxy); + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_453.getClosest(cd, distfn, pointData); + _$fx_515.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index !== false) { @@ -85151,8 +85990,8 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_539.extendFlat(pointData, { - color: _$getTraceColor_872(trace, di), + _$lib_601.extendFlat(pointData, { + color: _$getTraceColor_937(trace, di), x0: xc - rad, x1: xc + rad, @@ -85165,8 +86004,8 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_870(di, trace, pointData); - _$registry_668.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_935(di, trace, pointData); + _$registry_731.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -85232,13 +86071,13 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { xmax = Math.min(xmax, xa._length); // get only fill or line color for the hover color - var color = _$color_411.defaultLine; - if(_$color_411.opacity(trace.fillcolor)) color = trace.fillcolor; - else if(_$color_411.opacity((trace.line || {}).color)) { + var color = _$color_473.defaultLine; + if(_$color_473.opacity(trace.fillcolor)) color = trace.fillcolor; + else if(_$color_473.opacity((trace.line || {}).color)) { color = trace.line.color; } - _$lib_539.extendFlat(pointData, { + _$lib_601.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -85272,14 +86111,14 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_876 = _$numerical_517.BADNUM; -/* removed: var _$lib_539 = require('../../lib'); */; -var __segmentsIntersect_876 = _$lib_539.segmentsIntersect; -var constrain = _$lib_539.constrain; -/* removed: var _$constants_868 = require('./constants'); */; +var __BADNUM_941 = _$numerical_578.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +var __segmentsIntersect_941 = _$lib_601.segmentsIntersect; +var constrain = _$lib_601.constrain; +/* removed: var _$constants_933 = require('./constants'); */; -var _$linePoints_876 = function linePoints(d, opts) { +var _$linePoints_941 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -85288,7 +86127,7 @@ var _$linePoints_876 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_868.minTolerance; + var minTolerance = _$constants_933.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -85326,7 +86165,7 @@ var _$linePoints_876 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_876 || y === __BADNUM_876) return di.intoCenter || false; + if(x === __BADNUM_941 || y === __BADNUM_941) return di.intoCenter || false; return [x, y]; } @@ -85334,7 +86173,7 @@ var _$linePoints_876 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_868.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_933.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -85346,7 +86185,7 @@ var _$linePoints_876 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_868.maxScreensAway; + var maxScreensAway = _$constants_933.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -85375,7 +86214,7 @@ var _$linePoints_876 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_876(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_941(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -85429,7 +86268,7 @@ var _$linePoints_876 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_539.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_601.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -85682,7 +86521,7 @@ var _$linePoints_876 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_878 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_943 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -85722,19 +86561,19 @@ var _$linkTraces_878 = function linkTraces(gd, plotinfo, cdscatter) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -/* removed: var _$linePoints_876 = require('./line_points'); */; -/* removed: var _$linkTraces_878 = require('./link_traces'); */; -var __polygonTester_881 = _$polygon_551.tester; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +/* removed: var _$linePoints_941 = require('./line_points'); */; +/* removed: var _$linkTraces_943 = require('./link_traces'); */; +var __polygonTester_946 = _$polygon_613.tester; -var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_946 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -85743,9 +86582,8 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -85757,7 +86595,7 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_878(gd, plotinfo, cdscatter); + _$linkTraces_943(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -85782,7 +86620,7 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo onComplete = makeOnCompleteCallback(); } - var transition = _$d3_127.transition() + var transition = _$d3_130.transition() .duration(transitionOpts.duration) .ease(transitionOpts.easing) .each('end', function() { @@ -85796,12 +86634,12 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_881(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_946(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_881(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_946(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -85817,7 +86655,7 @@ function createFills(gd, scatterlayer, plotinfo) { var trace; scatterlayer.selectAll('g.trace').each(function(d) { - var tr = _$d3_127.select(this); + var tr = _$d3_130.select(this); // Loop only over the traces being redrawn: trace = d[0].trace; @@ -85852,11 +86690,11 @@ function createFills(gd, scatterlayer, plotinfo) { trace._ownFill = null; } - tr.selectAll('.js-fill').call(_$drawing_436.setClipUrl, plotinfo.layerClipId); + tr.selectAll('.js-fill').call(_$drawing_498.setClipUrl, plotinfo.layerClipId); }); } -function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_946(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -85875,10 +86713,10 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = cdscatter[0].trace, line = trace.line, - tr = _$d3_127.select(element); + tr = _$d3_130.select(element); // error bars are at the bottom - _$registry_668.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_731.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -85890,7 +86728,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -85916,11 +86754,11 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_539.noop; + makeUpdate = _$lib_601.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_884.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_949.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -85928,8 +86766,8 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran } if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = _$drawing_436.steps(line.shape); - revpathbase = _$drawing_436.steps( + pathfn = _$drawing_498.steps(line.shape); + revpathbase = _$drawing_498.steps( line.shape.split('').reverse().join('') ); } @@ -85939,10 +86777,10 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { // identical start and end points: treat it as a // closed curve so we don't get a kink - return _$drawing_436.smoothclosed(pts.slice(1), line.smoothing); + return _$drawing_498.smoothclosed(pts.slice(1), line.smoothing); } else { - return _$drawing_436.smoothopen(pts, line.smoothing); + return _$drawing_498.smoothopen(pts, line.smoothing); } }; } @@ -85957,7 +86795,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_876(cdscatter, { + segments = _$linePoints_941(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -85972,7 +86810,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_881(segments[i]); + trace._polygons[i] = __polygonTester_946(segments[i]); } if(segments.length) { @@ -85998,8 +86836,8 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_884.hasLines(trace) && pts.length > 1) { - var el = _$d3_127.select(this); + if(_$subtypes_949.hasLines(trace) && pts.length > 1) { + var el = _$d3_130.select(this); // This makes the coloring work correctly: el.datum(cdscatter); @@ -86007,12 +86845,12 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(isEnter) { transition(el.style('opacity', 0) .attr('d', thispath) - .call(_$drawing_436.lineGroupStyle)) + .call(_$drawing_498.lineGroupStyle)) .style('opacity', 1); } else { var sel = transition(el); sel.attr('d', thispath); - _$drawing_436.singleLineStyle(cdscatter, sel); + _$drawing_498.singleLineStyle(cdscatter, sel); } } }; @@ -86030,10 +86868,10 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran lineJoin.enter().append('path') .classed('js-line', true) .style('vector-effect', 'non-scaling-stroke') - .call(_$drawing_436.lineGroupStyle) + .call(_$drawing_498.lineGroupStyle) .each(makeUpdate(true)); - _$drawing_436.setClipUrl(lineJoin, plotinfo.layerClipId); + _$drawing_498.setClipUrl(lineJoin, plotinfo.layerClipId); function clearFill(selection) { transition(selection).attr('d', 'M0,0Z'); @@ -86056,11 +86894,11 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // the points on the axes are the first two points. Otherwise // animations get a little crazy if the number of points changes. transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1)) - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } else { // fill to self: just join the path to itself transition(ownFillEl3).attr('d', fullpath + 'Z') - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } } } @@ -86073,7 +86911,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z') - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -86082,7 +86920,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // things depending on whether the new endpoint projects onto the // existing curve or off the end of it transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z') - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } trace._polygons = trace._polygons.concat(prevPolygons); } @@ -86124,20 +86962,20 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var join, selection, hasNode; var trace = d[0].trace, - s = _$d3_127.select(this), - showMarkers = _$subtypes_884.hasMarkers(trace), - showText = _$subtypes_884.hasText(trace); + s = _$d3_130.select(this), + showMarkers = _$subtypes_949.hasMarkers(trace), + showText = _$subtypes_949.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_539.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_601.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_539.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_601.identity; } // marker points @@ -86151,28 +86989,28 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(hasTransition) { enter - .call(_$drawing_436.pointStyle, trace, gd) - .call(_$drawing_436.translatePoints, xa, ya) + .call(_$drawing_498.pointStyle, trace, gd) + .call(_$drawing_498.translatePoints, xa, ya) .style('opacity', 0) .transition() .style('opacity', 1); } - var markerScale = showMarkers && _$drawing_436.tryColorscale(trace.marker, ''); - var lineScale = showMarkers && _$drawing_436.tryColorscale(trace.marker, 'line'); + var markerScale = showMarkers && _$drawing_498.tryColorscale(trace.marker, ''); + var lineScale = showMarkers && _$drawing_498.tryColorscale(trace.marker, 'line'); join.order(); join.each(function(d) { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var sel = transition(el); - hasNode = _$drawing_436.translatePoint(d, sel, xa, ya); + hasNode = _$drawing_498.translatePoint(d, sel, xa, ya); if(hasNode) { - _$drawing_436.singlePointStyle(d, sel, trace, markerScale, lineScale, gd); + _$drawing_498.singlePointStyle(d, sel, trace, markerScale, lineScale, gd); if(plotinfo.layerClipId) { - _$drawing_436.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_498.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar); } if(trace.customdata) { @@ -86202,13 +87040,13 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran join.order(); join.each(function(d) { - var g = _$d3_127.select(this); + var g = _$d3_130.select(this); var sel = transition(g.select('text')); - hasNode = _$drawing_436.translatePoint(d, sel, xa, ya); + hasNode = _$drawing_498.translatePoint(d, sel, xa, ya); if(hasNode) { if(plotinfo.layerClipId) { - _$drawing_436.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_498.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar); } } else { g.remove(); @@ -86216,15 +87054,15 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran }); join.selectAll('text') - .call(_$drawing_436.textPointStyle, trace, gd) + .call(_$drawing_498.textPointStyle, trace, gd) .each(function(d) { // This just *has* to be totally custom becuase of SVG text positioning :( // It's obviously copied from translatePoint; we just can't use that var x = xa.c2p(d.x); var y = ya.c2p(d.y); - _$d3_127.select(this).selectAll('tspan.line').each(function() { - transition(_$d3_127.select(this)).attr({x: x, y: y}); + _$d3_130.select(this).selectAll('tspan.line').each(function() { + transition(_$d3_130.select(this)).attr({x: x, y: y}); }); }); @@ -86251,18 +87089,18 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // on `plotinfo._hasClipOnAxisFalse === true` subplots join.each(function(d) { var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_436.setClipUrl(_$d3_127.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + _$drawing_498.setClipUrl(_$d3_130.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); }); } function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_127.extent(_$lib_539.simpleMap(xa.range, xa.r2c)), - yr = _$d3_127.extent(_$lib_539.simpleMap(ya.range, ya.r2c)); + xr = _$d3_130.extent(_$lib_601.simpleMap(xa.range, xa.r2c)), + yr = _$d3_130.extent(_$lib_601.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_884.hasMarkers(trace)) return; + if(!_$subtypes_949.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -86277,7 +87115,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_884.hasMarkers(tracei) && + if(_$subtypes_949.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -86308,9 +87146,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; -var _$selectPoints_882 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_947 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -86321,7 +87159,7 @@ var _$selectPoints_882 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)); + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -86362,44 +87200,44 @@ var _$selectPoints_882 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -function __style_883(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.scatter'); +function __style_948(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.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_127.select(this); + var sel = _$d3_130.select(this); var trace = d.trace || d[0].trace; stylePoints(sel, trace, gd); }); s.selectAll('g.trace path.js-line') - .call(_$drawing_436.lineGroupStyle); + .call(_$drawing_498.lineGroupStyle); s.selectAll('g.trace path.js-fill') - .call(_$drawing_436.fillGroupStyle); + .call(_$drawing_498.fillGroupStyle); - _$registry_668.getComponentMethod('errorbars', 'style')(s); + _$registry_731.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { var pts = sel.selectAll('path.point'); var txs = sel.selectAll('text'); - _$drawing_436.pointStyle(pts, trace, gd); - _$drawing_436.textPointStyle(txs, trace, gd); - _$drawing_436.selectedPointStyle(pts, trace); - _$drawing_436.selectedTextStyle(txs, trace); + _$drawing_498.pointStyle(pts, trace, gd); + _$drawing_498.textPointStyle(txs, trace, gd); + _$drawing_498.selectedPointStyle(pts, trace); + _$drawing_498.selectedTextStyle(txs, trace); } -var _$style_883 = { - style: __style_883, +var _$style_948 = { + style: __style_948, stylePoints: stylePoints }; @@ -86416,30 +87254,30 @@ var _$style_883 = { var Scatter = {}; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_884.hasLines; -Scatter.hasMarkers = _$subtypes_884.hasMarkers; -Scatter.hasText = _$subtypes_884.hasText; -Scatter.isBubble = _$subtypes_884.isBubble; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_949.hasLines; +Scatter.hasMarkers = _$subtypes_949.hasMarkers; +Scatter.hasText = _$subtypes_949.hasText; +Scatter.isBubble = _$subtypes_949.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_862; -Scatter.supplyDefaults = _$supplyDefaults_869; -Scatter.cleanData = _$cleanData_865; -Scatter.calc = _$calc_863.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_861; -Scatter.plot = _$plot_881; -Scatter.colorbar = _$colorbar_866; -Scatter.style = _$style_883.style; -Scatter.hoverPoints = _$hoverPoints_873; -Scatter.selectPoints = _$selectPoints_882; +Scatter.attributes = _$attributes_927; +Scatter.supplyDefaults = _$supplyDefaults_934; +Scatter.cleanData = _$cleanData_930; +Scatter.calc = _$calc_928.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_926; +Scatter.plot = _$plot_946; +Scatter.colorbar = _$colorbar_931; +Scatter.style = _$style_948.style; +Scatter.hoverPoints = _$hoverPoints_938; +Scatter.selectPoints = _$selectPoints_947; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_595; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_658; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { description: [ 'The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts.', @@ -86450,9 +87288,9 @@ Scatter.meta = { ].join(' ') }; -var _$Scatter_874 = Scatter; +var _$Scatter_939 = Scatter; -var _$core_520 = {}; +var _$core_581 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -86464,71 +87302,71 @@ var _$core_520 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_520.version = '1.35.2'; +_$core_581.version = '1.36.0'; // inject promise polyfill -_$es6Promise_136.polyfill(); +_$es6Promise_184.polyfill(); // inject plot css _$plotcss_1; // inject default MathJax config -_$mathjax_config_521; +_$mathjax_config_582; // include registry module and expose register method -/* removed: var _$registry_668 = require('./registry'); */; -var register = _$core_520.register = _$registry_668.register; +/* removed: var _$registry_731 = require('./registry'); */; +var register = _$core_581.register = _$registry_731.register; // expose plot api methods -/* removed: var _$plot_api_571 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_571); +/* removed: var _$plot_api_634 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_634); for(var i = 0; i < methodNames.length; i++) { - var __name_520 = methodNames[i]; - _$core_520[__name_520] = _$plot_api_571[__name_520]; + var __name_581 = methodNames[i]; + _$core_581[__name_581] = _$plot_api_634[__name_581]; register({ moduleType: 'apiMethod', - name: __name_520, - fn: _$plot_api_571[__name_520] + name: __name_581, + fn: _$plot_api_634[__name_581] }); } // scatter is the only trace included by default -register(_$Scatter_874); +register(_$Scatter_939); // register all registrable components modules register([ - _$fx_453, - _$legend_471, - _$annotations_402, - _$annotations3d_407, - _$shapes_497, - _$images_462, - _$updatemenus_509, - _$sliders_503, - _$rangeslider_489, - _$rangeselector_483, - _$grid_457, - _$errorbars_442 + _$fx_515, + _$legend_533, + _$annotations_464, + _$annotations3d_469, + _$shapes_559, + _$images_524, + _$updatemenus_571, + _$sliders_565, + _$rangeslider_551, + _$rangeselector_545, + _$grid_519, + _$errorbars_504 ]); // locales en and en-US are required for default behavior register([ - _$localeEn_567, - _$localeEnUs_566 + _$localeEn_630, + _$localeEnUs_629 ]); // plot icons -_$core_520.Icons = _$ploticon_2; +_$core_581.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk -_$core_520.Plots = _$plots_647; -_$core_520.Fx = _$fx_453; -_$core_520.Snapshot = _$Snapshot_673; -_$core_520.PlotSchema = _$plot_schema_575; -_$core_520.Queue = _$queue_553; +_$core_581.Plots = _$plots_709; +_$core_581.Fx = _$fx_515; +_$core_581.Snapshot = _$Snapshot_736; +_$core_581.PlotSchema = _$plot_schema_638; +_$core_581.Queue = _$queue_616; // export d3 used in the bundle -_$core_520.d3 = _$d3_127; +_$core_581.d3 = _$d3_130; /** * Copyright 2012-2018, Plotly, Inc. @@ -86540,9 +87378,9 @@ _$core_520.d3 = _$d3_127; 'use strict'; -var _$core_12 = _$core_520; +var _$core_12 = _$core_581; -var _$filter_963 = {}; +var _$filter_1034 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -86553,21 +87391,21 @@ var _$filter_963 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -var __pointsAccessorFunction_963 = _$helpers_965.pointsAccessorFunction; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +var __pointsAccessorFunction_1034 = _$helpers_1036.pointsAccessorFunction; -/* removed: var _$filter_ops_512 = require('../constants/filter_ops'); */; -var COMPARISON_OPS = _$filter_ops_512.COMPARISON_OPS; -var __INTERVAL_OPS_963 = _$filter_ops_512.INTERVAL_OPS; -var SET_OPS = _$filter_ops_512.SET_OPS; +/* removed: var _$filter_ops_574 = require('../constants/filter_ops'); */; +var COMPARISON_OPS = _$filter_ops_574.COMPARISON_OPS; +var __INTERVAL_OPS_1034 = _$filter_ops_574.INTERVAL_OPS; +var SET_OPS = _$filter_ops_574.SET_OPS; -_$filter_963.moduleType = 'transform'; +_$filter_1034.moduleType = 'transform'; -_$filter_963.name = 'filter'; +_$filter_1034.name = 'filter'; -_$filter_963.attributes = { +_$filter_1034.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -86601,7 +87439,7 @@ _$filter_963.attributes = { valType: 'enumerated', values: [] .concat(COMPARISON_OPS) - .concat(__INTERVAL_OPS_963) + .concat(__INTERVAL_OPS_1034) .concat(SET_OPS), dflt: '=', role: 'info', @@ -86648,7 +87486,7 @@ _$filter_963.attributes = { '`value` is expected to be a number or a string.', 'When `operation` is set to one of the interval values', - '(' + __INTERVAL_OPS_963 + ')', + '(' + __INTERVAL_OPS_1034 + ')', '`value` is expected to be 2-item array where the first item', 'is the lower bound and the second item is the upper bound.', @@ -86673,11 +87511,11 @@ _$filter_963.attributes = { editType: 'calc' }; -_$filter_963.supplyDefaults = function(transformIn) { +_$filter_1034.supplyDefaults = function(transformIn) { var transformOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, _$filter_963.attributes, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, _$filter_1034.attributes, attr, dflt); } var enabled = coerce('enabled'); @@ -86688,7 +87526,7 @@ _$filter_963.supplyDefaults = function(transformIn) { coerce('value'); coerce('target'); - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleDefaults'); handleCalendarDefaults(transformIn, transformOut, 'valuecalendar', null); handleCalendarDefaults(transformIn, transformOut, 'targetcalendar', null); } @@ -86696,10 +87534,10 @@ _$filter_963.supplyDefaults = function(transformIn) { return transformOut; }; -_$filter_963.calcTransform = function(gd, trace, opts) { +_$filter_1034.calcTransform = function(gd, trace, opts) { if(!opts.enabled) return; - var targetArray = _$lib_539.getTargetArray(trace, opts); + var targetArray = _$lib_601.getTargetArray(trace, opts); if(!targetArray) return; var target = opts.target; @@ -86710,11 +87548,11 @@ _$filter_963.calcTransform = function(gd, trace, opts) { // even if you provide targetcalendar, if target is a string and there // is a calendar attribute matching target it will get used instead. if(typeof target === 'string') { - var attrTargetCalendar = _$lib_539.nestedProperty(trace, target + 'calendar').get(); + var attrTargetCalendar = _$lib_601.nestedProperty(trace, target + 'calendar').get(); if(attrTargetCalendar) targetCalendar = attrTargetCalendar; } - var d2c = _$axes_584.getDataToCoordFunc(gd, trace, target, targetArray); + var d2c = _$axes_647.getDataToCoordFunc(gd, trace, target, targetArray); var filterFunc = getFilterFunc(opts, d2c, targetCalendar); var originalArrays = {}; var indexToPoints = {}; @@ -86722,7 +87560,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { function forAllAttrs(fn, index) { for(var j = 0; j < arrayAttrs.length; j++) { - var np = _$lib_539.nestedProperty(trace, arrayAttrs[j]); + var np = _$lib_601.nestedProperty(trace, arrayAttrs[j]); fn(np, index); } } @@ -86731,7 +87569,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { var fillFn; if(opts.preservegaps) { initFn = function(np) { - originalArrays[np.astr] = _$lib_539.extendDeep([], np.get()); + originalArrays[np.astr] = _$lib_601.extendDeep([], np.get()); np.set(new Array(len)); }; fillFn = function(np, index) { @@ -86740,7 +87578,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { }; } else { initFn = function(np) { - originalArrays[np.astr] = _$lib_539.extendDeep([], np.get()); + originalArrays[np.astr] = _$lib_601.extendDeep([], np.get()); np.set([]); }; fillFn = function(np, index) { @@ -86752,7 +87590,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { // copy all original array attribute values, and clear arrays in trace forAllAttrs(initFn); - var originalPointsAccessor = __pointsAccessorFunction_963(trace.transforms, opts); + var originalPointsAccessor = __pointsAccessorFunction_1034(trace.transforms, opts); // loop through filter array, fill trace arrays if passed for(var i = 0; i < len; i++) { @@ -86784,7 +87622,7 @@ function getFilterFunc(opts, d2c, targetCalendar) { if(isOperationIn(COMPARISON_OPS)) { coercedValue = hasArrayValue ? d2cValue(value[0]) : d2cValue(value); } - else if(isOperationIn(__INTERVAL_OPS_963)) { + else if(isOperationIn(__INTERVAL_OPS_1034)) { coercedValue = hasArrayValue ? [d2cValue(value[0]), d2cValue(value[1])] : [d2cValue(value), d2cValue(value)]; @@ -86883,9 +87721,9 @@ function getFilterFunc(opts, d2c, targetCalendar) { 'use strict'; -var _$filter_13 = _$filter_963; +var _$filter_13 = _$filter_1034; -var _$groupby_964 = {}; +var _$groupby_1035 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -86896,16 +87734,16 @@ var _$groupby_964 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plot_schema_575 = require('../plot_api/plot_schema'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -var __pointsAccessorFunction_964 = _$helpers_965.pointsAccessorFunction; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plot_schema_638 = require('../plot_api/plot_schema'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +var __pointsAccessorFunction_1035 = _$helpers_1036.pointsAccessorFunction; -_$groupby_964.moduleType = 'transform'; +_$groupby_1035.moduleType = 'transform'; -_$groupby_964.name = 'groupby'; +_$groupby_1035.name = 'groupby'; -_$groupby_964.attributes = { +_$groupby_1035.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -86983,12 +87821,12 @@ _$groupby_964.attributes = { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$groupby_964.supplyDefaults = function(transformIn, traceOut, layout) { +_$groupby_1035.supplyDefaults = function(transformIn, traceOut, layout) { var i; var transformOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, _$groupby_964.attributes, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, _$groupby_1035.attributes, attr, dflt); } var enabled = coerce('enabled'); @@ -87004,8 +87842,8 @@ _$groupby_964.supplyDefaults = function(transformIn, traceOut, layout) { if(styleIn) { for(i = 0; i < styleIn.length; i++) { styleOut[i] = {}; - _$lib_539.coerce(styleIn[i], styleOut[i], _$groupby_964.attributes.styles, 'target'); - _$lib_539.coerce(styleIn[i], styleOut[i], _$groupby_964.attributes.styles, 'value'); + _$lib_601.coerce(styleIn[i], styleOut[i], _$groupby_1035.attributes.styles, 'target'); + _$lib_601.coerce(styleIn[i], styleOut[i], _$groupby_1035.attributes.styles, 'value'); } } @@ -87029,7 +87867,7 @@ _$groupby_964.supplyDefaults = function(transformIn, traceOut, layout) { * @return {object} newData * array of transformed traces */ -_$groupby_964.transform = function(data, state) { +_$groupby_1035.transform = function(data, state) { var newTraces, i, j; var newData = []; @@ -87050,17 +87888,17 @@ function transformOne(trace, state) { var opts = state.transform; var groups = trace.transforms[state.transformIndex].groups; - var originalPointsAccessor = __pointsAccessorFunction_964(trace.transforms, opts); + var originalPointsAccessor = __pointsAccessorFunction_1035(trace.transforms, opts); if(!(Array.isArray(groups)) || groups.length === 0) { return [trace]; } - var groupNames = _$lib_539.filterUnique(groups), + var groupNames = _$lib_601.filterUnique(groups), newData = new Array(groupNames.length), len = groups.length; - var arrayAttrs = _$plot_schema_575.findArrayAttributes(trace); + var arrayAttrs = _$plot_schema_638.findArrayAttributes(trace); var styles = opts.styles || []; var styleLookup = {}; @@ -87069,7 +87907,7 @@ function transformOne(trace, state) { } if(opts.styles) { - groupNameObj = _$lib_539.keyedContainer(opts, 'styles', 'target', 'value.name'); + groupNameObj = _$lib_601.keyedContainer(opts, 'styles', 'target', 'value.name'); } // An index to map group name --> expanded trace index @@ -87082,7 +87920,7 @@ function transformOne(trace, state) { indexCnts[groupName] = 0; // Start with a deep extend that just copies array references. - newTrace = newData[i] = _$lib_539.extendDeepNoArrays({}, trace); + newTrace = newData[i] = _$lib_601.extendDeepNoArrays({}, trace); newTrace._group = groupName; newTrace.transforms[state.transformIndex]._indexToPoints = {}; @@ -87094,7 +87932,7 @@ function transformOne(trace, state) { if(suppliedName) { newTrace.name = suppliedName; } else { - newTrace.name = _$lib_539.templateString(opts.nameformat, { + newTrace.name = _$lib_601.templateString(opts.nameformat, { trace: trace.name, group: groupName }); @@ -87109,12 +87947,12 @@ function transformOne(trace, state) { transforms = newTrace.transforms; newTrace.transforms = []; for(j = 0; j < transforms.length; j++) { - newTrace.transforms[j] = _$lib_539.extendDeepNoArrays({}, transforms[j]); + newTrace.transforms[j] = _$lib_601.extendDeepNoArrays({}, transforms[j]); } // Initialize empty arrays for the arrayAttrs, to be split in the next step for(j = 0; j < arrayAttrs.length; j++) { - _$lib_539.nestedProperty(newTrace, arrayAttrs[j]).set([]); + _$lib_601.nestedProperty(newTrace, arrayAttrs[j]).set([]); } } @@ -87126,11 +87964,11 @@ function transformOne(trace, state) { // Cache all the arrays to which we'll push: for(j = 0, arrayLookup = []; j < groupNames.length; j++) { - arrayLookup[j] = _$lib_539.nestedProperty(newData[j], attr).get(); + arrayLookup[j] = _$lib_601.nestedProperty(newData[j], attr).get(); } // Get the input data: - srcArray = _$lib_539.nestedProperty(trace, attr).get(); + srcArray = _$lib_601.nestedProperty(trace, attr).get(); // Send each data point to the appropriate expanded trace: for(j = 0; j < len; j++) { @@ -87151,11 +87989,11 @@ function transformOne(trace, state) { groupName = groupNames[i]; newTrace = newData[i]; - _$plots_647.clearExpandedTraceDefaultColors(newTrace); + _$plots_709.clearExpandedTraceDefaultColors(newTrace); // there's no need to coerce styleLookup[groupName] here // as another round of supplyDefaults is done on the transformed traces - newTrace = _$lib_539.extendDeepNoArrays(newTrace, styleLookup[groupName] || {}); + newTrace = _$lib_601.extendDeepNoArrays(newTrace, styleLookup[groupName] || {}); } return newData; @@ -87171,7 +88009,7 @@ function transformOne(trace, state) { 'use strict'; -var _$groupby_14 = _$groupby_964; +var _$groupby_14 = _$groupby_1035; /** * Copyright 2012-2018, Plotly, Inc. @@ -87184,7 +88022,7 @@ var _$groupby_14 = _$groupby_964; 'use strict'; -var _$handleStyleDefaults_788 = function handleStyleDefaults(traceIn, traceOut, coerce) { +var _$handleStyleDefaults_850 = function handleStyleDefaults(traceIn, traceOut, coerce) { var zsmooth = coerce('zsmooth'); if(zsmooth === false) { // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect. @@ -87206,21 +88044,21 @@ var _$handleStyleDefaults_788 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$has_columns_780 = require('./has_columns'); */; -/* removed: var _$handleXYZDefaults_789 = require('./xyz_defaults'); */; -/* removed: var _$handleStyleDefaults_788 = require('./style_defaults'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_773 = require('./attributes'); */; +/* removed: var _$has_columns_842 = require('./has_columns'); */; +/* removed: var _$handleXYZDefaults_851 = require('./xyz_defaults'); */; +/* removed: var _$handleStyleDefaults_850 = require('./style_defaults'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_835 = require('./attributes'); */; -var _$supplyDefaults_778 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_773, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_835, attr, dflt); } - var len = _$handleXYZDefaults_789(traceIn, traceOut, coerce, layout); + var len = _$handleXYZDefaults_851(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -87228,11 +88066,11 @@ var _$supplyDefaults_778 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); - _$handleStyleDefaults_788(traceIn, traceOut, coerce, layout); + _$handleStyleDefaults_850(traceIn, traceOut, coerce, layout); - coerce('connectgaps', _$has_columns_780(traceOut) && (traceOut.zsmooth !== false)); + coerce('connectgaps', _$has_columns_842(traceOut) && (traceOut.zsmooth !== false)); - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; /** @@ -87248,18 +88086,18 @@ var _$supplyDefaults_778 = function supplyDefaults(traceIn, traceOut, defaultCol var Heatmap = {}; -Heatmap.attributes = _$attributes_773; -Heatmap.supplyDefaults = _$supplyDefaults_778; -Heatmap.calc = _$calc_774; -Heatmap.plot = _$plot_786; -Heatmap.colorbar = _$colorbar_776; -Heatmap.style = _$style_787; -Heatmap.hoverPoints = _$hoverPoints_781; +Heatmap.attributes = _$attributes_835; +Heatmap.supplyDefaults = _$supplyDefaults_840; +Heatmap.calc = _$calc_836; +Heatmap.plot = _$plot_848; +Heatmap.colorbar = _$colorbar_838; +Heatmap.style = _$style_849; +Heatmap.hoverPoints = _$hoverPoints_843; Heatmap.moduleType = 'trace'; Heatmap.name = 'heatmap'; -Heatmap.basePlotModule = _$cartesian_595; -Heatmap.categories = ['cartesian', '2dMap']; +Heatmap.basePlotModule = _$cartesian_658; +Heatmap.categories = ['cartesian', 'svg', '2dMap']; Heatmap.meta = { description: [ 'The data that describes the heatmap value-to-color mapping', @@ -87287,7 +88125,7 @@ Heatmap.meta = { ].join(' ') }; -var _$Heatmap_782 = Heatmap; +var _$Heatmap_844 = Heatmap; /** * Copyright 2012-2018, Plotly, Inc. @@ -87299,7 +88137,7 @@ var _$Heatmap_782 = Heatmap; 'use strict'; -var _$heatmap_15 = _$Heatmap_782; +var _$heatmap_15 = _$Heatmap_844; "use strict" @@ -87357,11 +88195,11 @@ function unique(list, compare, sorted) { return unique_eq(list) } -var _$unique_362 = unique +var _$unique_424 = unique "use strict" -/* removed: var _$unique_362 = require("uniq") */; +/* removed: var _$unique_424 = require("uniq") */; // 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. @@ -87678,7 +88516,7 @@ function generateCWiseOp(proc, typesig) { } //Prepare this variables - var thisVars = _$unique_362([].concat(proc.pre.thisVars) + var thisVars = _$unique_424([].concat(proc.pre.thisVars) .concat(proc.body.thisVars) .concat(proc.post.thisVars)) vars = vars.concat(thisVars) @@ -87716,7 +88554,7 @@ function generateCWiseOp(proc, typesig) { var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) return f() } -var _$generateCWiseOp_116 = generateCWiseOp +var _$generateCWiseOp_117 = generateCWiseOp "use strict" @@ -87743,7 +88581,7 @@ var _$generateCWiseOp_116 = generateCWiseOp // return thunk(compile.bind1(proc)) // } -/* removed: var _$generateCWiseOp_116 = require("./compile.js") */; +/* removed: var _$generateCWiseOp_117 = require("./compile.js") */; function createThunk(proc) { var code = ["'use strict'", "var CACHED={}"] @@ -87800,14 +88638,14 @@ function createThunk(proc) { //Compile thunk var thunk = new Function("compile", code.join("\n")) - return thunk(_$generateCWiseOp_116.bind(undefined, proc)) + return thunk(_$generateCWiseOp_117.bind(undefined, proc)) } -var _$createThunk_117 = createThunk +var _$createThunk_118 = createThunk "use strict" -/* removed: var _$createThunk_117 = require("./lib/thunk.js") */; +/* removed: var _$createThunk_118 = require("./lib/thunk.js") */; function Procedure() { this.argTypes = [] @@ -87910,15 +88748,15 @@ function compileCwise(user_args) { //Read in block size proc.blockSize = user_args.blockSize || 64 - return _$createThunk_117(proc) + return _$createThunk_118(proc) } -var _$compileCwise_115 = compileCwise +var _$compileCwise_116 = compileCwise -var _$ndarrayOps_271 = {}; +var _$ndarrayOps_329 = {}; "use strict" -/* removed: var _$compileCwise_115 = require("cwise-compiler") */; +/* removed: var _$compileCwise_116 = require("cwise-compiler") */; var EmptyProc = { body: "", @@ -87949,7 +88787,7 @@ function fixup(x) { } function pcompile(user_args) { - return _$compileCwise_115({ + return _$compileCwise_116({ args: user_args.args, pre: fixup(user_args.pre), body: fixup(user_args.body), @@ -87985,26 +88823,26 @@ var assign_ops = { ;(function(){ for(var id in assign_ops) { var op = assign_ops[id] - _$ndarrayOps_271[id] = makeOp({ + _$ndarrayOps_329[id] = makeOp({ args: ["array","array","array"], body: {args:["a","b","c"], body: "a=b"+op+"c"}, funcName: id }) - _$ndarrayOps_271[id+"eq"] = makeOp({ + _$ndarrayOps_329[id+"eq"] = makeOp({ args: ["array","array"], body: {args:["a","b"], body:"a"+op+"=b"}, rvalue: true, funcName: id+"eq" }) - _$ndarrayOps_271[id+"s"] = makeOp({ + _$ndarrayOps_329[id+"s"] = makeOp({ args: ["array", "array", "scalar"], body: {args:["a","b","s"], body:"a=b"+op+"s"}, funcName: id+"s" }) - _$ndarrayOps_271[id+"seq"] = makeOp({ + _$ndarrayOps_329[id+"seq"] = makeOp({ args: ["array","scalar"], body: {args:["a","s"], body:"a"+op+"=s"}, @@ -88023,13 +88861,13 @@ var unary_ops = { ;(function(){ for(var id in unary_ops) { var op = unary_ops[id] - _$ndarrayOps_271[id] = makeOp({ + _$ndarrayOps_329[id] = makeOp({ args: ["array", "array"], body: {args:["a","b"], body:"a="+op+"b"}, funcName: id }) - _$ndarrayOps_271[id+"eq"] = makeOp({ + _$ndarrayOps_329[id+"eq"] = makeOp({ args: ["array"], body: {args:["a"], body:"a="+op+"a"}, @@ -88053,19 +88891,19 @@ var binary_ops = { ;(function() { for(var id in binary_ops) { var op = binary_ops[id] - _$ndarrayOps_271[id] = makeOp({ + _$ndarrayOps_329[id] = makeOp({ args: ["array","array","array"], body: {args:["a", "b", "c"], body:"a=b"+op+"c"}, funcName: id }) - _$ndarrayOps_271[id+"s"] = makeOp({ + _$ndarrayOps_329[id+"s"] = makeOp({ args: ["array","array","scalar"], body: {args:["a", "b", "s"], body:"a=b"+op+"s"}, funcName: id+"s" }) - _$ndarrayOps_271[id+"eq"] = makeOp({ + _$ndarrayOps_329[id+"eq"] = makeOp({ args: ["array", "array"], body: {args:["a", "b"], body:"a=a"+op+"b"}, @@ -88073,7 +88911,7 @@ var binary_ops = { count:2, funcName: id+"eq" }) - _$ndarrayOps_271[id+"seq"] = makeOp({ + _$ndarrayOps_329[id+"seq"] = makeOp({ args: ["array", "scalar"], body: {args:["a","s"], body:"a=a"+op+"s"}, @@ -88102,13 +88940,13 @@ var math_unary = [ ;(function() { for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, @@ -88250,7 +89088,7 @@ _$ndarrayOps_271.norminf = _$compileCwise_115({ funcName: "norminf" }) -_$ndarrayOps_271.norm1 = _$compileCwise_115({ +_$ndarrayOps_329.norm1 = _$compileCwise_116({ 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"]}, @@ -88258,7 +89096,7 @@ _$ndarrayOps_271.norm1 = _$compileCwise_115({ funcName: "norm1" }) -_$ndarrayOps_271.sup = _$compileCwise_115({ +_$ndarrayOps_329.sup = _$compileCwise_116({ args: [ "array" ], pre: { body: "this_h=-Infinity", @@ -88277,7 +89115,7 @@ _$ndarrayOps_271.sup = _$compileCwise_115({ localVars: [] } }) -_$ndarrayOps_271.inf = _$compileCwise_115({ +_$ndarrayOps_329.inf = _$compileCwise_116({ args: [ "array" ], pre: { body: "this_h=Infinity", @@ -88296,7 +89134,7 @@ _$ndarrayOps_271.inf = _$compileCwise_115({ localVars: [] } }) -_$ndarrayOps_271.argmin = _$compileCwise_115({ +_$ndarrayOps_329.argmin = _$compileCwise_116({ args:["index","array","shape"], pre:{ body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}", @@ -88321,7 +89159,7 @@ _$ndarrayOps_271.argmin = _$compileCwise_115({ localVars:[]} }) -_$ndarrayOps_271.argmax = _$compileCwise_115({ +_$ndarrayOps_329.argmax = _$compileCwise_116({ args:["index","array","shape"], pre:{ body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}", @@ -88346,25 +89184,25 @@ _$ndarrayOps_271.argmax = _$compileCwise_115({ localVars:[]} }) -_$ndarrayOps_271.random = makeOp({ +_$ndarrayOps_329.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" }) -_$ndarrayOps_271.assign = makeOp({ +_$ndarrayOps_329.assign = makeOp({ args:["array", "array"], body: {args:["a", "b"], body:"a=b"}, funcName: "assign" }) -_$ndarrayOps_271.assigns = makeOp({ +_$ndarrayOps_329.assigns = makeOp({ args:["array", "scalar"], body: {args:["a", "b"], body:"a=b"}, funcName: "assigns" }) -_$ndarrayOps_271.equals = _$compileCwise_115({ +_$ndarrayOps_329.equals = _$compileCwise_116({ args:["array", "array"], pre: EmptyProc, body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, @@ -88388,7 +89226,7 @@ function iota(n) { return result } -var _$iota_245 = iota +var _$iota_302 = iota /*! * Determine if an object is a Buffer * @@ -88398,7 +89236,7 @@ var _$iota_245 = iota // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually -var _$isBuffer_247 = function (obj) { +var _$isBuffer_304 = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } @@ -88411,8 +89249,8 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -/* removed: var _$iota_245 = require("iota-array") */; -/* removed: var _$isBuffer_247 = require("is-buffer") */; +/* removed: var _$iota_302 = require("iota-array") */; +/* removed: var _$isBuffer_304 = require("is-buffer") */; var hasTypedArrays = ((typeof Float64Array) !== "undefined") @@ -88497,7 +89335,7 @@ return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" var code = ["'use strict'"] //Create constructor for view - var indices = _$iota_245(dimension) + var indices = _$iota_302(dimension) var args = indices.map(function(i) { return "i"+i }) var index_str = "this.offset+" + indices.map(function(i) { return "this.stride[" + i + "]*i" + i @@ -88666,7 +89504,7 @@ b"+i+"*=d\ } function arrayDType(data) { - if(_$isBuffer_247(data)) { + if(_$isBuffer_304(data)) { return "buffer" } if(hasTypedArrays) { @@ -88753,9 +89591,9 @@ function wrappedNDArrayCtor(data, shape, stride, offset) { return ctor(data, shape, stride, offset) } -var _$wrappedNDArrayCtor_277 = wrappedNDArrayCtor +var _$wrappedNDArrayCtor_335 = wrappedNDArrayCtor -var _$twiddle_72 = {}; +var _$twiddle_73 = {}; /** * Bit twiddling hacks for JavaScript. * @@ -88771,38 +89609,38 @@ var _$twiddle_72 = {}; var INT_BITS = 32; //Constants -_$twiddle_72.INT_BITS = INT_BITS; -_$twiddle_72.INT_MAX = 0x7fffffff; -_$twiddle_72.INT_MIN = -1<<(INT_BITS-1); +_$twiddle_73.INT_BITS = INT_BITS; +_$twiddle_73.INT_MAX = 0x7fffffff; +_$twiddle_73.INT_MIN = -1<<(INT_BITS-1); //Returns -1, 0, +1 depending on sign of x -_$twiddle_72.sign = function(v) { +_$twiddle_73.sign = function(v) { return (v > 0) - (v < 0); } //Computes absolute value of integer -_$twiddle_72.abs = function(v) { +_$twiddle_73.abs = function(v) { var mask = v >> (INT_BITS-1); return (v ^ mask) - mask; } //Computes minimum of integers x and y -_$twiddle_72.min = function(x, y) { +_$twiddle_73.min = function(x, y) { return y ^ ((x ^ y) & -(x < y)); } //Computes maximum of integers x and y -_$twiddle_72.max = function(x, y) { +_$twiddle_73.max = function(x, y) { return x ^ ((x ^ y) & -(x < y)); } //Checks if a number is a power of two -_$twiddle_72.isPow2 = function(v) { +_$twiddle_73.isPow2 = function(v) { return !(v & (v-1)) && (!!v); } //Computes log base 2 of v -_$twiddle_72.log2 = function(v) { +_$twiddle_73.log2 = function(v) { var r, shift; r = (v > 0xFFFF) << 4; v >>>= r; shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; @@ -88812,14 +89650,14 @@ _$twiddle_72.log2 = function(v) { } //Computes log base 10 of v -_$twiddle_72.log10 = function(v) { +_$twiddle_73.log10 = function(v) { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } //Counts number of bits -_$twiddle_72.popCount = function(v) { +_$twiddle_73.popCount = function(v) { v = v - ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; @@ -88837,10 +89675,10 @@ function countTrailingZeros(v) { if (v & 0x55555555) c -= 1; return c; } -_$twiddle_72.countTrailingZeros = countTrailingZeros; +_$twiddle_73.countTrailingZeros = countTrailingZeros; //Rounds to next power of 2 -_$twiddle_72.nextPow2 = function(v) { +_$twiddle_73.nextPow2 = function(v) { v += v === 0; --v; v |= v >>> 1; @@ -88852,7 +89690,7 @@ _$twiddle_72.nextPow2 = function(v) { } //Rounds down to previous power of 2 -_$twiddle_72.prevPow2 = function(v) { +_$twiddle_73.prevPow2 = function(v) { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; @@ -88862,7 +89700,7 @@ _$twiddle_72.prevPow2 = function(v) { } //Computes parity of word -_$twiddle_72.parity = function(v) { +_$twiddle_73.parity = function(v) { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; @@ -88885,7 +89723,7 @@ var REVERSE_TABLE = new Array(256); })(REVERSE_TABLE); //Reverse bits in a 32 bit word -_$twiddle_72.reverse = function(v) { +_$twiddle_73.reverse = function(v) { return (REVERSE_TABLE[ v & 0xff] << 24) | (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | @@ -88893,7 +89731,7 @@ _$twiddle_72.reverse = function(v) { } //Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -_$twiddle_72.interleave2 = function(x, y) { +_$twiddle_73.interleave2 = function(x, y) { x &= 0xFFFF; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; @@ -88910,7 +89748,7 @@ _$twiddle_72.interleave2 = function(x, y) { } //Extracts the nth interleaved component -_$twiddle_72.deinterleave2 = function(v, n) { +_$twiddle_73.deinterleave2 = function(v, n) { v = (v >>> n) & 0x55555555; v = (v | (v >>> 1)) & 0x33333333; v = (v | (v >>> 2)) & 0x0F0F0F0F; @@ -88921,7 +89759,7 @@ _$twiddle_72.deinterleave2 = function(v, n) { //Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -_$twiddle_72.interleave3 = function(x, y, z) { +_$twiddle_73.interleave3 = function(x, y, z) { x &= 0x3FF; x = (x | (x<<16)) & 4278190335; x = (x | (x<<8)) & 251719695; @@ -88945,7 +89783,7 @@ _$twiddle_72.interleave3 = function(x, y, z) { } //Extracts nth interleaved component of a 3-tuple -_$twiddle_72.deinterleave3 = function(v, n) { +_$twiddle_73.deinterleave3 = function(v, n) { v = (v >>> n) & 1227133513; v = (v | (v>>>2)) & 3272356035; v = (v | (v>>>4)) & 251719695; @@ -88955,27 +89793,27 @@ _$twiddle_72.deinterleave3 = function(v, n) { } //Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -_$twiddle_72.nextCombination = function(v) { +_$twiddle_73.nextCombination = function(v) { var t = v | (v - 1); return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } -var _$base64Js_54 = {}; +var _$base64Js_55 = {}; 'use strict' -_$base64Js_54.byteLength = byteLength -_$base64Js_54.toByteArray = toByteArray -_$base64Js_54.fromByteArray = fromByteArray +_$base64Js_55.byteLength = byteLength +_$base64Js_55.toByteArray = toByteArray +_$base64Js_55.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var __i_54 = 0, len = code.length; __i_54 < len; ++__i_54) { - lookup[__i_54] = code[__i_54] - revLookup[code.charCodeAt(__i_54)] = __i_54 +for (var __i_55 = 0, len = code.length; __i_55 < len; ++__i_55) { + lookup[__i_55] = code[__i_55] + revLookup[code.charCodeAt(__i_55)] = __i_55 } // Support decoding URL-safe base64 strings, as Node.js does. @@ -89079,8 +89917,8 @@ function fromByteArray (uint8) { return parts.join('') } -var _$ieee754_241 = {}; -_$ieee754_241.read = function (buffer, offset, isLE, mLen, nBytes) { +var _$ieee754_298 = {}; +_$ieee754_298.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 @@ -89113,7 +89951,7 @@ _$ieee754_241.read = function (buffer, offset, isLE, mLen, nBytes) { return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } -_$ieee754_241.write = function (buffer, value, offset, isLE, mLen, nBytes) { +_$ieee754_298.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 @@ -89165,7 +90003,7 @@ _$ieee754_241.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -var _$buffer_84 = {}; +var _$buffer_85 = {}; /*! * The buffer module from node.js, for the browser. * @@ -89176,15 +90014,15 @@ var _$buffer_84 = {}; 'use strict' -/* removed: var _$base64Js_54 = require('base64-js') */; -/* removed: var _$ieee754_241 = require('ieee754') */; +/* removed: var _$base64Js_55 = require('base64-js') */; +/* removed: var _$ieee754_298 = require('ieee754') */; -_$buffer_84.Buffer = Buffer -_$buffer_84.SlowBuffer = SlowBuffer -_$buffer_84.INSPECT_MAX_BYTES = 50 +_$buffer_85.Buffer = Buffer +_$buffer_85.SlowBuffer = SlowBuffer +_$buffer_85.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff -_$buffer_84.kMaxLength = K_MAX_LENGTH +_$buffer_85.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -89377,7 +90215,7 @@ function fromString (string, encoding) { throw new TypeError('Unknown encoding: ' + encoding) } - var length = __byteLength_84(string, encoding) | 0 + var length = __byteLength_85(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) @@ -89549,7 +90387,7 @@ Buffer.concat = function concat (list, length) { return buffer } -function __byteLength_84 (string, encoding) { +function __byteLength_85 (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } @@ -89591,7 +90429,7 @@ function __byteLength_84 (string, encoding) { } } } -Buffer.byteLength = __byteLength_84 +Buffer.byteLength = __byteLength_85 function slowToString (encoding, start, end) { var loweredCase = false @@ -89731,7 +90569,7 @@ Buffer.prototype.equals = function equals (b) { Buffer.prototype.inspect = function inspect () { var str = '' - var max = _$buffer_84.INSPECT_MAX_BYTES + var max = _$buffer_85.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' @@ -90056,9 +90894,9 @@ Buffer.prototype.toJSON = function toJSON () { function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { - return _$base64Js_54.fromByteArray(buf) + return _$base64Js_55.fromByteArray(buf) } else { - return _$base64Js_54.fromByteArray(buf.slice(start, end)) + return _$base64Js_55.fromByteArray(buf.slice(start, end)) } } @@ -90384,25 +91222,25 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) - return _$ieee754_241.read(this, offset, true, 23, 4) + return _$ieee754_298.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) - return _$ieee754_241.read(this, offset, false, 23, 4) + return _$ieee754_298.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) - return _$ieee754_241.read(this, offset, true, 52, 8) + return _$ieee754_298.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) - return _$ieee754_241.read(this, offset, false, 52, 8) + return _$ieee754_298.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { @@ -90604,7 +91442,7 @@ function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } - _$ieee754_241.write(buf, value, offset, littleEndian, 23, 4) + _$ieee754_298.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } @@ -90622,7 +91460,7 @@ function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } - _$ieee754_241.write(buf, value, offset, littleEndian, 52, 8) + _$ieee754_298.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } @@ -90880,7 +91718,7 @@ function utf16leToBytes (str, units) { } function base64ToBytes (str) { - return _$base64Js_54.toByteArray(base64clean(str)) + return _$base64Js_55.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { @@ -90951,28 +91789,28 @@ function dupe(count, value) { return [] } -var _$dupe_133 = dupe -var _$pool_360 = {}; +var _$dupe_136 = dupe +var _$pool_422 = {}; (function (global,Buffer){ 'use strict' -/* removed: var _$twiddle_72 = require('bit-twiddle') */; -/* removed: var _$dupe_133 = require('dup') */; +/* removed: var _$twiddle_73 = require('bit-twiddle') */; +/* removed: var _$dupe_136 = require('dup') */; //Legacy pool support if(!global.__TYPEDARRAY_POOL) { global.__TYPEDARRAY_POOL = { - UINT8 : _$dupe_133([32, 0]) - , UINT16 : _$dupe_133([32, 0]) - , UINT32 : _$dupe_133([32, 0]) - , INT8 : _$dupe_133([32, 0]) - , INT16 : _$dupe_133([32, 0]) - , INT32 : _$dupe_133([32, 0]) - , FLOAT : _$dupe_133([32, 0]) - , DOUBLE : _$dupe_133([32, 0]) - , DATA : _$dupe_133([32, 0]) - , UINT8C : _$dupe_133([32, 0]) - , BUFFER : _$dupe_133([32, 0]) + UINT8 : _$dupe_136([32, 0]) + , UINT16 : _$dupe_136([32, 0]) + , UINT32 : _$dupe_136([32, 0]) + , INT8 : _$dupe_136([32, 0]) + , INT16 : _$dupe_136([32, 0]) + , INT32 : _$dupe_136([32, 0]) + , FLOAT : _$dupe_136([32, 0]) + , DOUBLE : _$dupe_136([32, 0]) + , DATA : _$dupe_136([32, 0]) + , UINT8C : _$dupe_136([32, 0]) + , BUFFER : _$dupe_136([32, 0]) } } @@ -90981,19 +91819,19 @@ var POOL = global.__TYPEDARRAY_POOL //Upgrade pool if(!POOL.UINT8C) { - POOL.UINT8C = _$dupe_133([32, 0]) + POOL.UINT8C = _$dupe_136([32, 0]) } if(!POOL.BUFFER) { - POOL.BUFFER = _$dupe_133([32, 0]) + POOL.BUFFER = _$dupe_136([32, 0]) } //New technique: Only allocate from ArrayBufferView and Buffer var DATA = POOL.DATA , BUFFER = POOL.BUFFER -_$pool_360.free = function free(array) { +_$pool_422.free = function free(array) { if(Buffer.isBuffer(array)) { - BUFFER[_$twiddle_72.log2(array.length)].push(array) + BUFFER[_$twiddle_73.log2(array.length)].push(array) } else { if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { array = array.buffer @@ -91002,7 +91840,7 @@ _$pool_360.free = function free(array) { return } var n = array.length || array.byteLength - var log_n = _$twiddle_72.log2(n)|0 + var log_n = _$twiddle_73.log2(n)|0 DATA[log_n].push(array) } } @@ -91012,7 +91850,7 @@ function freeArrayBuffer(buffer) { return } var n = buffer.length || buffer.byteLength - var log_n = _$twiddle_72.log2(n) + var log_n = _$twiddle_73.log2(n) DATA[log_n].push(buffer) } @@ -91020,26 +91858,26 @@ function freeTypedArray(array) { freeArrayBuffer(array.buffer) } -_$pool_360.freeUint8 = -_$pool_360.freeUint16 = -_$pool_360.freeUint32 = -_$pool_360.freeInt8 = -_$pool_360.freeInt16 = -_$pool_360.freeInt32 = -_$pool_360.freeFloat32 = -_$pool_360.freeFloat = -_$pool_360.freeFloat64 = -_$pool_360.freeDouble = -_$pool_360.freeUint8Clamped = -_$pool_360.freeDataView = freeTypedArray +_$pool_422.freeUint8 = +_$pool_422.freeUint16 = +_$pool_422.freeUint32 = +_$pool_422.freeInt8 = +_$pool_422.freeInt16 = +_$pool_422.freeInt32 = +_$pool_422.freeFloat32 = +_$pool_422.freeFloat = +_$pool_422.freeFloat64 = +_$pool_422.freeDouble = +_$pool_422.freeUint8Clamped = +_$pool_422.freeDataView = freeTypedArray -_$pool_360.freeArrayBuffer = freeArrayBuffer +_$pool_422.freeArrayBuffer = freeArrayBuffer -_$pool_360.freeBuffer = function freeBuffer(array) { - BUFFER[_$twiddle_72.log2(array.length)].push(array) +_$pool_422.freeBuffer = function freeBuffer(array) { + BUFFER[_$twiddle_73.log2(array.length)].push(array) } -_$pool_360.malloc = function malloc(n, dtype) { +_$pool_422.malloc = function malloc(n, dtype) { if(dtype === undefined || dtype === 'arraybuffer') { return mallocArrayBuffer(n) } else { @@ -91078,55 +91916,55 @@ _$pool_360.malloc = function malloc(n, dtype) { } function mallocArrayBuffer(n) { - var n = _$twiddle_72.nextPow2(n) - var log_n = _$twiddle_72.log2(n) + var n = _$twiddle_73.nextPow2(n) + var log_n = _$twiddle_73.log2(n) var d = DATA[log_n] if(d.length > 0) { return d.pop() } return new ArrayBuffer(n) } -_$pool_360.mallocArrayBuffer = mallocArrayBuffer +_$pool_422.mallocArrayBuffer = mallocArrayBuffer function mallocUint8(n) { return new Uint8Array(mallocArrayBuffer(n), 0, n) } -_$pool_360.mallocUint8 = mallocUint8 +_$pool_422.mallocUint8 = mallocUint8 function mallocUint16(n) { return new Uint16Array(mallocArrayBuffer(2*n), 0, n) } -_$pool_360.mallocUint16 = mallocUint16 +_$pool_422.mallocUint16 = mallocUint16 function mallocUint32(n) { return new Uint32Array(mallocArrayBuffer(4*n), 0, n) } -_$pool_360.mallocUint32 = mallocUint32 +_$pool_422.mallocUint32 = mallocUint32 function mallocInt8(n) { return new Int8Array(mallocArrayBuffer(n), 0, n) } -_$pool_360.mallocInt8 = mallocInt8 +_$pool_422.mallocInt8 = mallocInt8 function mallocInt16(n) { return new Int16Array(mallocArrayBuffer(2*n), 0, n) } -_$pool_360.mallocInt16 = mallocInt16 +_$pool_422.mallocInt16 = mallocInt16 function mallocInt32(n) { return new Int32Array(mallocArrayBuffer(4*n), 0, n) } -_$pool_360.mallocInt32 = mallocInt32 +_$pool_422.mallocInt32 = mallocInt32 function mallocFloat(n) { return new Float32Array(mallocArrayBuffer(4*n), 0, n) } -_$pool_360.mallocFloat32 = _$pool_360.mallocFloat = mallocFloat +_$pool_422.mallocFloat32 = _$pool_422.mallocFloat = mallocFloat function mallocDouble(n) { return new Float64Array(mallocArrayBuffer(8*n), 0, n) } -_$pool_360.mallocFloat64 = _$pool_360.mallocDouble = mallocDouble +_$pool_422.mallocFloat64 = _$pool_422.mallocDouble = mallocDouble function mallocUint8Clamped(n) { if(hasUint8C) { @@ -91135,25 +91973,25 @@ function mallocUint8Clamped(n) { return mallocUint8(n) } } -_$pool_360.mallocUint8Clamped = mallocUint8Clamped +_$pool_422.mallocUint8Clamped = mallocUint8Clamped function mallocDataView(n) { return new DataView(mallocArrayBuffer(n), 0, n) } -_$pool_360.mallocDataView = mallocDataView +_$pool_422.mallocDataView = mallocDataView function mallocBuffer(n) { - n = _$twiddle_72.nextPow2(n) - var log_n = _$twiddle_72.log2(n) + n = _$twiddle_73.nextPow2(n) + var log_n = _$twiddle_73.log2(n) var cache = BUFFER[log_n] if(cache.length > 0) { return cache.pop() } return new Buffer(n) } -_$pool_360.mallocBuffer = mallocBuffer +_$pool_422.mallocBuffer = mallocBuffer -_$pool_360.clearCache = function clearCache() { +_$pool_422.clearCache = function clearCache() { for(var i=0; i<32; ++i) { POOL.UINT8[i].length = 0 POOL.UINT16[i].length = 0 @@ -91168,12 +92006,12 @@ _$pool_360.clearCache = function clearCache() { BUFFER[i].length = 0 } } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_$buffer_84.Buffer) +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_$buffer_85.Buffer) "use strict" -/* removed: var _$pool_360 = require("typedarray-pool") */; -/* removed: var _$ndarrayOps_271 = require("ndarray-ops") */; -/* removed: var _$wrappedNDArrayCtor_277 = require("ndarray") */; +/* removed: var _$pool_422 = require("typedarray-pool") */; +/* removed: var _$ndarrayOps_329 = require("ndarray-ops") */; +/* removed: var _$wrappedNDArrayCtor_335 = require("ndarray") */; var SUPPORTED_TYPES = [ "uint8", @@ -91193,17 +92031,17 @@ function GLBuffer(gl, type, handle, length, usage) { this.usage = usage } -var __proto_153 = GLBuffer.prototype +var __proto_210 = GLBuffer.prototype -__proto_153.bind = function() { +__proto_210.bind = function() { this.gl.bindBuffer(this.type, this.handle) } -__proto_153.unbind = function() { +__proto_210.unbind = function() { this.gl.bindBuffer(this.type, null) } -__proto_153.dispose = function() { +__proto_210.dispose = function() { this.gl.deleteBuffer(this.handle) } @@ -91221,7 +92059,7 @@ function updateTypeArray(gl, type, len, usage, data, offset) { } function makeScratchTypeArray(array, dtype) { - var res = _$pool_360.malloc(array.length, dtype) + var res = _$pool_422.malloc(array.length, dtype) var n = array.length for(var i=0; i= 0) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type for attribute ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid data type for attribute ' + name + ': ' + type) } addVectorAttribute( gl @@ -91609,7 +92447,7 @@ function createAttributeWrapper( } else if(type.indexOf('mat') >= 0) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type for attribute ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid data type for attribute ' + name + ': ' + type) } addMatrixAttribute( gl @@ -91620,7 +92458,7 @@ function createAttributeWrapper( , obj , name) } else { - throw new _$GLError_207('', 'Unknown data type for attribute ' + name + ': ' + type) + throw new _$GLError_264('', 'Unknown data type for attribute ' + name + ': ' + type) } break } @@ -91630,7 +92468,7 @@ function createAttributeWrapper( 'use strict' -var _$makeReflectTypes_210 = makeReflectTypes +var _$makeReflectTypes_267 = makeReflectTypes //Construct type info for reflection. // @@ -91687,10 +92525,10 @@ function makeReflectTypes(uniforms, useIndex) { } 'use strict' -/* removed: var _$makeReflectTypes_210 = require('./reflect') */; -/* removed: var _$GLError_207 = require("./GLError") */; +/* removed: var _$makeReflectTypes_267 = require('./reflect') */; +/* removed: var _$GLError_264 = require("./GLError") */; -var _$createUniformWrapper_209 = createUniformWrapper +var _$createUniformWrapper_266 = createUniformWrapper //Binds a function and returns a value function identity(x) { @@ -91732,7 +92570,7 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type') + throw new _$GLError_264('', 'Invalid data type') } switch(type.charAt(0)) { case 'b': @@ -91741,16 +92579,16 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { case 'v': return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' default: - throw new _$GLError_207('', 'Unrecognized data type for vector ' + name + ': ' + type) + throw new _$GLError_264('', 'Unrecognized data type for vector ' + name + ': ' + type) } } else if(type.indexOf('mat') === 0 && type.length === 4) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' } else { - throw new _$GLError_207('', 'Unknown uniform data type for ' + name + ': ' + type) + throw new _$GLError_264('', 'Unknown uniform data type for ' + name + ': ' + type) } break } @@ -91809,7 +92647,7 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type') + throw new _$GLError_264('', 'Invalid data type') } if(type.charAt(0) === 'b') { return makeVector(d, false) @@ -91818,11 +92656,11 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { } else if(type.indexOf('mat') === 0 && type.length === 4) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } return makeVector(d*d, 0) } else { - throw new _$GLError_207('', 'Unknown uniform data type for ' + name + ': ' + type) + throw new _$GLError_264('', 'Unknown uniform data type for ' + name + ': ' + type) } break } @@ -91868,7 +92706,7 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { } //Return data - var coallesced = _$makeReflectTypes_210(uniforms, true) + var coallesced = _$makeReflectTypes_267(uniforms, true) return { get: identity(processObject(coallesced)), set: makeSetter(coallesced), @@ -91877,11 +92715,11 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { } } -var _$runtimeReflect_211 = {}; +var _$runtimeReflect_268 = {}; 'use strict' -_$runtimeReflect_211.uniforms = runtimeUniforms -_$runtimeReflect_211.attributes = runtimeAttributes +_$runtimeReflect_268.uniforms = runtimeUniforms +_$runtimeReflect_268.attributes = runtimeAttributes var GL_TO_GLSL_TYPES = { 'FLOAT': 'float', @@ -91977,7 +92815,7 @@ var cache; * Expose `repeat` */ -var _$repeat_316 = repeat; +var _$repeat_380 = repeat; /** * Repeat the given `string` the specified `number` @@ -92037,15 +92875,15 @@ function repeat(str, num) { 'use strict'; -/* removed: var _$repeat_316 = require('repeat-string'); */; +/* removed: var _$repeat_380 = require('repeat-string'); */; -var _$padLeft_284 = function padLeft(str, num, ch) { +var _$padLeft_342 = function padLeft(str, num, ch) { ch = typeof ch !== 'undefined' ? (ch + '') : ' '; - return _$repeat_316(ch, num) + str; + return _$repeat_380(ch, num) + str; }; -/* removed: var _$padLeft_284 = require('pad-left') */; +/* removed: var _$padLeft_342 = require('pad-left') */; -var _$addLineNumbers_44 = addLineNumbers +var _$addLineNumbers_45 = addLineNumbers function addLineNumbers (string, start, delim) { start = typeof start === 'number' ? start : 1 delim = delim || ': ' @@ -92055,12 +92893,12 @@ function addLineNumbers (string, start, delim) { return lines.map(function (line, i) { var c = i + start var digits = String(c).length - var prefix = _$padLeft_284(c, totalDigits - digits) + var prefix = _$padLeft_342(c, totalDigits - digits) return prefix + delim + line }).join('\n') } -var _$numbers_154 = { +var _$numbers_211 = { 0: 'NONE', 1: 'ONE', 2: 'LINE_LOOP', @@ -92359,17 +93197,17 @@ var _$numbers_154 = { 37444: 'BROWSER_DEFAULT_WEBGL' } -/* removed: var _$numbers_154 = require('./1.0/numbers') */; +/* removed: var _$numbers_211 = require('./1.0/numbers') */; -var _$lookupConstant_155 = function lookupConstant (number) { - return _$numbers_154[number] +var _$lookupConstant_212 = function lookupConstant (number) { + return _$numbers_211[number] } -var _$_atob_52 = function _atob(str) { +var _$_atob_53 = function _atob(str) { return atob(str) } -var _$builtins_233 = [ +var _$builtins_290 = [ // Keep this list sorted 'abs' , 'acos' @@ -92521,15 +93359,15 @@ var _$builtins_233 = [ ] // 300es builtins/reserved words that were previously valid in v100 -/* removed: var _$builtins_233 = require('./builtins') */; +/* removed: var _$builtins_290 = require('./builtins') */; // The texture2D|Cube functions have been removed // And the gl_ features are updated -_$builtins_233 = _$builtins_233.slice().filter(function (b) { +_$builtins_290 = _$builtins_290.slice().filter(function (b) { return !/^(gl\_|texture)/.test(b) }) -var _$builtins300es_232 = _$builtins_233.concat([ +var _$builtins300es_289 = _$builtins_290.concat([ // the updated gl_ constants 'gl_VertexID' , 'gl_InstanceID' @@ -92590,7 +93428,7 @@ var _$builtins300es_232 = _$builtins_233.concat([ , 'textureProjGradOffset' ]) -var _$literals_235 = [ +var _$literals_292 = [ // current 'precision' , 'highp' @@ -92684,9 +93522,9 @@ var _$literals_235 = [ , 'using' ] -/* removed: var _$literals_235 = require('./literals') */; +/* removed: var _$literals_292 = require('./literals') */; -var _$literals300es_234 = _$literals_235.slice().concat([ +var _$literals300es_291 = _$literals_292.slice().concat([ 'layout' , 'centroid' , 'smooth' @@ -92773,7 +93611,7 @@ var _$literals300es_234 = _$literals_235.slice().concat([ , 'usampler2DMSArray' ]) -var _$operators_236 = [ +var _$operators_293 = [ '<<=' , '>>=' , '++' @@ -92821,13 +93659,13 @@ var _$operators_236 = [ , '}' ] -var _$tokenize_231 = tokenize +var _$tokenize_288 = tokenize -var __dummy_231$0 = 0 - , __dummy_231$1 = 0 - , __dummy_231$2 = 0 - , __dummy_231$3 = 0 - , __dummy_231$4 = 0 +var __dummy_288$0 = 0 + , __dummy_288$1 = 0 + , __dummy_288$2 = 0 + , __dummy_288$3 = 0 + , __dummy_288$4 = 0 var NORMAL = 999 // <-- never emitted , TOKEN = 9999 // <-- never emitted @@ -92878,11 +93716,11 @@ function tokenize(opt) { , len opt = opt || {} - var allBuiltins = _$builtins_233 - var allLiterals = _$literals_235 + var allBuiltins = _$builtins_290 + var allLiterals = _$literals_292 if (opt.version === '300 es') { - allBuiltins = _$builtins300es_232 - allLiterals = _$literals300es_234 + allBuiltins = _$builtins300es_289 + allLiterals = _$literals300es_291 } return function(data) { @@ -93073,8 +93911,8 @@ function tokenize(opt) { , res do { - idx = _$operators_236.indexOf(buf.slice(0, buf.length + j).join('')) - res = _$operators_236[idx] + idx = _$operators_293.indexOf(buf.slice(0, buf.length + j).join('')) + res = _$operators_293[idx] if(idx === -1) { if(j-- + buf.length > 0) continue @@ -93184,12 +94022,12 @@ function tokenize(opt) { } } -/* removed: var _$tokenize_231 = require('./index') */; +/* removed: var _$tokenize_288 = require('./index') */; -var _$tokenizeString_237 = tokenizeString +var _$tokenizeString_294 = tokenizeString function tokenizeString(str, opt) { - var generator = _$tokenize_231(opt) + var generator = _$tokenize_288(opt) var tokens = [] tokens = tokens.concat(generator(str)) @@ -93198,15 +94036,15 @@ function tokenizeString(str, opt) { return tokens } -/* removed: var _$tokenizeString_237 = require('glsl-tokenizer') */; -/* removed: var _$_atob_52 = require('atob-lite') */; +/* removed: var _$tokenizeString_294 = require('glsl-tokenizer') */; +/* removed: var _$_atob_53 = require('atob-lite') */; -var _$getName_230 = getName +var _$getName_287 = getName function getName(src) { var tokens = Array.isArray(src) ? src - : _$tokenizeString_237(src) + : _$tokenizeString_294(src) for (var i = 0; i < tokens.length; i++) { var token = tokens[i] @@ -93218,11 +94056,11 @@ function getName(src) { var b64 = match[1] var name = match[2] - return (b64 ? _$_atob_52(name) : name).trim() + return (b64 ? _$_atob_53(name) : name).trim() } } -var _$sprintf_343 = {}; +var _$sprintf_405 = {}; /* global window, exports, define */ !function() { @@ -93422,9 +94260,9 @@ var _$sprintf_343 = {}; * export to either browser or node.js */ /* eslint-disable quote-props */ - if (typeof _$sprintf_343 !== 'undefined') { - _$sprintf_343['sprintf'] = sprintf - _$sprintf_343['vsprintf'] = vsprintf + if (typeof _$sprintf_405 !== 'undefined') { + _$sprintf_405['sprintf'] = sprintf + _$sprintf_405['vsprintf'] = vsprintf } if (typeof window !== 'undefined') { window['sprintf'] = sprintf @@ -93443,21 +94281,21 @@ var _$sprintf_343 = {}; }() -var sprintf = _$sprintf_343.sprintf; -/* removed: var _$lookupConstant_155 = require('gl-constants/lookup'); */; -/* removed: var _$getName_230 = require('glsl-shader-name'); */; -/* removed: var _$addLineNumbers_44 = require('add-line-numbers'); */; +var sprintf = _$sprintf_405.sprintf; +/* removed: var _$lookupConstant_212 = require('gl-constants/lookup'); */; +/* removed: var _$getName_287 = require('glsl-shader-name'); */; +/* removed: var _$addLineNumbers_45 = require('add-line-numbers'); */; -var _$formatCompilerError_159 = formatCompilerError; +var _$formatCompilerError_216 = formatCompilerError; function formatCompilerError(errLog, src, type) { "use strict"; - var name = _$getName_230(src) || 'of unknown name (see npm glsl-shader-name)'; + var name = _$getName_287(src) || 'of unknown name (see npm glsl-shader-name)'; var typeName = 'unknown type'; if (type !== undefined) { - typeName = type === _$lookupConstant_155.FRAGMENT_SHADER ? 'fragment' : 'vertex' + typeName = type === _$lookupConstant_212.FRAGMENT_SHADER ? 'fragment' : 'vertex' } var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name); @@ -93476,7 +94314,7 @@ function formatCompilerError(errLog, src, type) { errors[lineNo] = errorString; } - var lines = _$addLineNumbers_44(src).split('\n'); + var lines = _$addLineNumbers_45(src).split('\n'); for (var i = 0; i < lines.length; i++) { if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue; @@ -93496,7 +94334,7 @@ function formatCompilerError(errLog, src, type) { } -var _$hiddenStore_371 = hiddenStore; +var _$hiddenStore_433 = hiddenStore; function hiddenStore(obj, key) { var store = { identity: key }; @@ -93513,9 +94351,9 @@ function hiddenStore(obj, key) { return store; } -/* removed: var _$hiddenStore_371 = require('./hidden-store.js'); */; +/* removed: var _$hiddenStore_433 = require('./hidden-store.js'); */; -var _$createStore_370 = createStore; +var _$createStore_432 = createStore; function createStore() { var key = {}; @@ -93529,7 +94367,7 @@ function createStore() { var store = obj.valueOf(key); return store && store.identity === key ? - store : _$hiddenStore_371(obj, key); + store : _$hiddenStore_433(obj, key); }; } @@ -93537,12 +94375,12 @@ function createStore() { // https://gist.github.com/Gozala/1269991 // This is a reimplemented version (with a few bug fixes). -/* removed: var _$createStore_370 = require('./create-store.js'); */; +/* removed: var _$createStore_432 = require('./create-store.js'); */; -var _$weakMap_372 = weakMap; +var _$weakMap_434 = weakMap; function weakMap() { - var privates = _$createStore_370(); + var privates = _$createStore_432(); return { 'get': function (key, fallback) { @@ -93563,17 +94401,17 @@ function weakMap() { } } -var _$shaderCache_212 = {}; +var _$shaderCache_269 = {}; 'use strict' -_$shaderCache_212.shader = getShaderReference -_$shaderCache_212.program = createProgram +_$shaderCache_269.shader = getShaderReference +_$shaderCache_269.program = createProgram -/* removed: var _$GLError_207 = require("./GLError") */; -/* removed: var _$formatCompilerError_159 = require('gl-format-compiler-error'); */; +/* removed: var _$GLError_264 = require("./GLError") */; +/* removed: var _$formatCompilerError_216 = require('gl-format-compiler-error'); */; -var __weakMap_212 = typeof WeakMap === 'undefined' ? _$weakMap_372 : WeakMap -var CACHE = new __weakMap_212() +var __weakMap_269 = typeof WeakMap === 'undefined' ? _$weakMap_434 : WeakMap +var CACHE = new __weakMap_269() var SHADER_COUNTER = 0 @@ -93614,7 +94452,7 @@ function ContextCache(gl) { this.programs = {} } -var __proto_212 = ContextCache.prototype +var __proto_269 = ContextCache.prototype function compileShader(gl, type, src) { var shader = gl.createShader(type) @@ -93623,17 +94461,17 @@ function compileShader(gl, type, src) { if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { var errLog = gl.getShaderInfoLog(shader) try { - var fmt = _$formatCompilerError_159(errLog, src, type); + var fmt = _$formatCompilerError_216(errLog, src, type); } catch (e){ console.warn('Failed to format compiler error: ' + e); - throw new _$GLError_207(errLog, 'Error compiling shader:\n' + errLog) + throw new _$GLError_264(errLog, 'Error compiling shader:\n' + errLog) } - throw new _$GLError_207(errLog, fmt.short, fmt.long) + throw new _$GLError_264(errLog, fmt.short, fmt.long) } return shader } -__proto_212.getShaderReference = function(type, src) { +__proto_269.getShaderReference = function(type, src) { var gl = this.gl var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0] var shader = shaders[src] @@ -93663,12 +94501,12 @@ function linkProgram(gl, vshader, fshader, attribs, locations) { gl.linkProgram(program) if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { var errLog = gl.getProgramInfoLog(program) - throw new _$GLError_207(errLog, 'Error linking program: ' + errLog) + throw new _$GLError_264(errLog, 'Error linking program: ' + errLog) } return program } -__proto_212.getProgram = function(vref, fref, attribs, locations) { +__proto_269.getProgram = function(vref, fref, attribs, locations) { var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') var prog = this.programs[token] if(!prog || !this.gl.isProgram(prog)) { @@ -93703,12 +94541,12 @@ function createProgram(gl, vref, fref, attribs, locations) { 'use strict' -/* removed: var _$createUniformWrapper_209 = require('./lib/create-uniforms') */; -/* removed: var _$createAttributeWrapper_208 = require('./lib/create-attributes') */; -/* removed: var _$makeReflectTypes_210 = require('./lib/reflect') */; -/* removed: var _$shaderCache_212 = require('./lib/shader-cache') */; -/* removed: var _$runtimeReflect_211 = require('./lib/runtime-reflect') */; -/* removed: var _$GLError_207 = require("./lib/GLError") */; +/* removed: var _$createUniformWrapper_266 = require('./lib/create-uniforms') */; +/* removed: var _$createAttributeWrapper_265 = require('./lib/create-attributes') */; +/* removed: var _$makeReflectTypes_267 = require('./lib/reflect') */; +/* removed: var _$shaderCache_269 = require('./lib/shader-cache') */; +/* removed: var _$runtimeReflect_268 = require('./lib/runtime-reflect') */; +/* removed: var _$GLError_264 = require("./lib/GLError") */; //Shader object function Shader(gl) { @@ -93727,9 +94565,9 @@ function Shader(gl) { this.types = null } -var __proto_206 = Shader.prototype +var __proto_263 = Shader.prototype -__proto_206.bind = function() { +__proto_263.bind = function() { if(!this.program) { this._relink() } @@ -93754,7 +94592,7 @@ __proto_206.bind = function() { this.gl.useProgram(this.program) } -__proto_206.dispose = function() { +__proto_263.dispose = function() { // disabling vertex attributes so new shader starts with zero // and it's also useful if all shaders are disposed but the @@ -93789,7 +94627,7 @@ function compareAttributes(a, b) { } //Update export hook for glslify-live -__proto_206.update = function( +__proto_263.update = function( vertSource , fragSource , uniforms @@ -93809,13 +94647,13 @@ __proto_206.update = function( //Compile vertex and fragment shaders var pvref = wrapper._vref - wrapper._vref = _$shaderCache_212.shader(gl, gl.VERTEX_SHADER, vertSource) + wrapper._vref = _$shaderCache_269.shader(gl, gl.VERTEX_SHADER, vertSource) if(pvref) { pvref.dispose() } wrapper.vertShader = wrapper._vref.shader var pfref = this._fref - wrapper._fref = _$shaderCache_212.shader(gl, gl.FRAGMENT_SHADER, fragSource) + wrapper._fref = _$shaderCache_269.shader(gl, gl.FRAGMENT_SHADER, fragSource) if(pfref) { pfref.dispose() } @@ -93831,12 +94669,12 @@ __proto_206.update = function( gl.linkProgram(testProgram) if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) { var errLog = gl.getProgramInfoLog(testProgram) - throw new _$GLError_207(errLog, 'Error linking program:' + errLog) + throw new _$GLError_264(errLog, 'Error linking program:' + errLog) } //Load data from runtime - uniforms = uniforms || _$runtimeReflect_211.uniforms(gl, testProgram) - attributes = attributes || _$runtimeReflect_211.attributes(gl, testProgram) + uniforms = uniforms || _$runtimeReflect_268.uniforms(gl, testProgram) + attributes = attributes || _$runtimeReflect_268.attributes(gl, testProgram) //Release test program gl.deleteProgram(testProgram) @@ -93904,7 +94742,7 @@ __proto_206.update = function( //Rebuild program and recompute all uniform locations var uniformLocations = new Array(uniforms.length) function relink() { - wrapper.program = _$shaderCache_212.program( + wrapper.program = _$shaderCache_269.program( gl , wrapper._vref , wrapper._fref @@ -93926,19 +94764,19 @@ __proto_206.update = function( //Generate type info wrapper.types = { - uniforms: _$makeReflectTypes_210(uniforms), - attributes: _$makeReflectTypes_210(attributes) + uniforms: _$makeReflectTypes_267(uniforms), + attributes: _$makeReflectTypes_267(attributes) } //Generate attribute wrappers - wrapper.attributes = _$createAttributeWrapper_208( + wrapper.attributes = _$createAttributeWrapper_265( gl , wrapper , attributeUnpacked , attributeLocations) //Generate uniform wrappers - Object.defineProperty(wrapper, 'uniforms', _$createUniformWrapper_209( + Object.defineProperty(wrapper, 'uniforms', _$createUniformWrapper_266( gl , wrapper , uniforms @@ -93964,16 +94802,16 @@ function createShader( return shader } -var _$createShader_206 = createShader +var _$createShader_263 = createShader 'use strict' -var _$createBoxes_188 = createBoxes +var _$createBoxes_245 = createBoxes -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -/* removed: var _$shaders_191 = require('./shaders') */; +/* removed: var _$shaders_248 = require('./shaders') */; function Boxes(plot, vbo, shader) { this.plot = plot @@ -93981,9 +94819,9 @@ function Boxes(plot, vbo, shader) { this.shader = shader } -var __proto_188 = Boxes.prototype +var __proto_245 = Boxes.prototype -__proto_188.bind = function() { +__proto_245.bind = function() { var shader = this.shader this.vbo.bind() this.shader.bind() @@ -93991,7 +94829,7 @@ __proto_188.bind = function() { shader.uniforms.screenBox = this.plot.screenBox } -__proto_188.drawBox = (function() { +__proto_245.drawBox = (function() { var lo = [0,0] var hi = [0,0] return function(loX, loY, hiX, hiY, color) { @@ -94012,19 +94850,19 @@ __proto_188.drawBox = (function() { } }()) -__proto_188.dispose = function() { +__proto_245.dispose = function() { this.vbo.dispose() this.shader.dispose() } function createBoxes(plot) { var gl = plot.gl - var vbo = _$createBuffer_153(gl, [ + var vbo = _$createBuffer_210(gl, [ 0,0, 0,1, 1,0, 1,1]) - var shader = _$createShader_206(gl, _$shaders_191.boxVert, _$shaders_191.lineFrag) + var shader = _$createShader_263(gl, _$shaders_248.boxVert, _$shaders_248.lineFrag) return new Boxes(plot, vbo, shader) } @@ -94072,7 +94910,7 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_90 = { +var _$searchBounds_91 = { ge: compileBoundsSearch(">=", false, "GE"), gt: compileBoundsSearch(">", false, "GT"), lt: compileBoundsSearch("<", true, "LT"), @@ -94082,7 +94920,7 @@ var _$searchBounds_90 = { "use strict" -function __compileSearch_193(funcName, predicate, reversed, extraArgs, earlyOut) { +function __compileSearch_250(funcName, predicate, reversed, extraArgs, earlyOut) { var code = [ "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), @@ -94110,10 +94948,10 @@ function __compileSearch_193(funcName, predicate, reversed, extraArgs, earlyOut) return code.join("") } -function __compileBoundsSearch_193(predicate, reversed, suffix, earlyOut) { +function __compileBoundsSearch_250(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_193("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_193("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), + __compileSearch_250("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_250("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), "function dispatchBsearch", suffix, "(a,y,c,l,h){\ if(typeof(c)==='function'){\ return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ @@ -94124,22 +94962,22 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_193 = { - ge: __compileBoundsSearch_193(">=", false, "GE"), - gt: __compileBoundsSearch_193(">", false, "GT"), - lt: __compileBoundsSearch_193("<", true, "LT"), - le: __compileBoundsSearch_193("<=", true, "LE"), - eq: __compileBoundsSearch_193("-", true, "EQ", true) +var _$searchBounds_250 = { + ge: __compileBoundsSearch_250(">=", false, "GE"), + gt: __compileBoundsSearch_250(">", false, "GT"), + lt: __compileBoundsSearch_250("<", true, "LT"), + le: __compileBoundsSearch_250("<=", true, "LE"), + eq: __compileBoundsSearch_250("-", true, "EQ", true) } 'use strict' -var _$createGrid_189 = createGrid +var _$createGrid_246 = createGrid -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$searchBounds_193 = require('binary-search-bounds') */; -/* removed: var _$shaders_191 = require('./shaders') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$searchBounds_250 = require('binary-search-bounds') */; +/* removed: var _$shaders_248 = require('./shaders') */; function Grid(plot, vbo, shader, tickShader) { this.plot = plot @@ -94153,9 +94991,9 @@ function compareTickNum(a, b) { return a - b } -var __proto_189 = Grid.prototype +var __proto_246 = Grid.prototype -__proto_189.draw = (function() { +__proto_246.draw = (function() { var DATA_SHIFT = [0,0] var DATA_SCALE = [0,0] @@ -94208,7 +95046,7 @@ __proto_189.draw = (function() { } })() -__proto_189.drawTickMarks = (function() { +__proto_246.drawTickMarks = (function() { var DATA_SHIFT = [0,0] var DATA_SCALE = [0,0] var X_AXIS = [1,0] @@ -94265,13 +95103,13 @@ __proto_189.drawTickMarks = (function() { var xTicksOffset = 0 var yTicksOffset = ticks[0].length * 6 - var xStart = Math.min(_$searchBounds_193.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xEnd = Math.min(_$searchBounds_193.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xStart = Math.min(_$searchBounds_250.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xEnd = Math.min(_$searchBounds_250.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) var xOffset = xTicksOffset + 6 * xStart var xCount = 6 * Math.max(0, xEnd - xStart) - var yStart = Math.min(_$searchBounds_193.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yEnd = Math.min(_$searchBounds_193.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yStart = Math.min(_$searchBounds_250.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yEnd = Math.min(_$searchBounds_250.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) var yOffset = yTicksOffset + 6 * yStart var yCount = 6 * Math.max(0, yEnd - yStart) @@ -94329,7 +95167,7 @@ __proto_189.drawTickMarks = (function() { } })() -__proto_189.update = (function() { +__proto_246.update = (function() { var OFFSET_X = [1, 1, -1, -1, 1, -1] var OFFSET_Y = [1, -1, 1, 1, -1, -1] @@ -94363,7 +95201,7 @@ __proto_189.update = (function() { } })() -__proto_189.dispose = function() { +__proto_246.dispose = function() { this.vbo.dispose() this.shader.dispose() this.tickShader.dispose() @@ -94371,21 +95209,21 @@ __proto_189.dispose = function() { function createGrid(plot) { var gl = plot.gl - var vbo = _$createBuffer_153(gl) - var shader = _$createShader_206(gl, _$shaders_191.gridVert, _$shaders_191.gridFrag) - var tickShader = _$createShader_206(gl, _$shaders_191.tickVert, _$shaders_191.gridFrag) + var vbo = _$createBuffer_210(gl) + var shader = _$createShader_263(gl, _$shaders_248.gridVert, _$shaders_248.gridFrag) + var tickShader = _$createShader_263(gl, _$shaders_248.tickVert, _$shaders_248.gridFrag) var grid = new Grid(plot, vbo, shader, tickShader) return grid } 'use strict' -var _$createLines_190 = createLines +var _$createLines_247 = createLines -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -/* removed: var _$shaders_191 = require('./shaders') */; +/* removed: var _$shaders_248 = require('./shaders') */; function Lines(plot, vbo, shader) { this.plot = plot @@ -94393,9 +95231,9 @@ function Lines(plot, vbo, shader) { this.shader = shader } -var __proto_190 = Lines.prototype +var __proto_247 = Lines.prototype -__proto_190.bind = function() { +__proto_247.bind = function() { var shader = this.shader this.vbo.bind() this.shader.bind() @@ -94403,7 +95241,7 @@ __proto_190.bind = function() { shader.uniforms.screenBox = this.plot.screenBox } -__proto_190.drawLine = (function() { +__proto_247.drawLine = (function() { var start = [0,0] var end = [0,0] return function(startX, startY, endX, endY, width, color) { @@ -94425,26 +95263,26 @@ __proto_190.drawLine = (function() { } }()) -__proto_190.dispose = function() { +__proto_247.dispose = function() { this.vbo.dispose() this.shader.dispose() } function createLines(plot) { var gl = plot.gl - var vbo = _$createBuffer_153(gl, [ + var vbo = _$createBuffer_210(gl, [ -1,-1, -1,1, 1,-1, 1,1]) - var shader = _$createShader_206(gl, _$shaders_191.lineVert, _$shaders_191.lineFrag) + var shader = _$createShader_263(gl, _$shaders_248.lineVert, _$shaders_248.lineFrag) var lines = new Lines(plot, vbo, shader) return lines } "use strict" -var _$twoProduct_358 = twoProduct +var _$twoProduct_420 = twoProduct var SPLITTER = +(Math.pow(2, 27) + 1.0) @@ -94477,7 +95315,7 @@ function twoProduct(a, b, result) { } "use strict" -var _$fastTwoSum_359 = fastTwoSum +var _$fastTwoSum_421 = fastTwoSum function fastTwoSum(a, b, result) { var x = a + b @@ -94494,15 +95332,15 @@ function fastTwoSum(a, b, result) { } "use strict" -/* removed: var _$twoProduct_358 = require("two-product") */; -/* removed: var _$fastTwoSum_359 = require("two-sum") */; +/* removed: var _$twoProduct_420 = require("two-product") */; +/* removed: var _$fastTwoSum_421 = require("two-sum") */; -var _$scaleLinearExpansion_325 = scaleLinearExpansion +var _$scaleLinearExpansion_389 = scaleLinearExpansion function scaleLinearExpansion(e, scale) { var n = e.length if(n === 1) { - var ts = _$twoProduct_358(e[0], scale) + var ts = _$twoProduct_420(e[0], scale) if(ts[0]) { return ts } @@ -94512,14 +95350,14 @@ function scaleLinearExpansion(e, scale) { var q = [0.1, 0.1] var t = [0.1, 0.1] var count = 0 - _$twoProduct_358(e[0], scale, q) + _$twoProduct_420(e[0], scale, q) if(q[0]) { g[count++] = q[0] } for(var i=1; i>1 - return ["sum(", __generateSum_323(expr.slice(0, m)), ",", __generateSum_323(expr.slice(m)), ")"].join("") + return ["sum(", __generateSum_387(expr.slice(0, m)), ",", __generateSum_387(expr.slice(m)), ")"].join("") } } -function __determinant_323(m) { +function __determinant_387(m) { if(m.length === 2) { return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] } else { var expr = [] for(var i=0; i= 0 + return _$searchBounds_91.eq(this.edges, e, compareLex) >= 0 } })() -__proto_89.removeTriangle = function(i, j, k) { +__proto_90.removeTriangle = function(i, j, k) { var stars = this.stars removePair(stars[i], j, k) removePair(stars[j], k, i) removePair(stars[k], i, j) } -__proto_89.addTriangle = function(i, j, k) { +__proto_90.addTriangle = function(i, j, k) { var stars = this.stars stars[i].push(j, k) stars[j].push(k, i) stars[k].push(i, j) } -__proto_89.opposite = function(j, i) { +__proto_90.opposite = function(j, i) { var list = this.stars[i] for(var k=1, n=list.length; k>> 31 +_$double_133.sign = function(n) { + return _$double_133.hi(n) >>> 31 } -_$double_130.exponent = function(n) { - var b = _$double_130.hi(n) +_$double_133.exponent = function(n) { + var b = _$double_133.hi(n) return ((b<<1) >>> 21) - 1023 } -_$double_130.fraction = function(n) { - var lo = _$double_130.lo(n) - var hi = _$double_130.hi(n) +_$double_133.fraction = function(n) { + var lo = _$double_133.lo(n) + var hi = _$double_133.hi(n) var b = hi & ((1<<20) - 1) if(hi & 0x7ff00000) { b += (1<<20) @@ -99435,42 +100273,42 @@ _$double_130.fraction = function(n) { return [lo, b] } -_$double_130.denormalized = function(n) { - var hi = _$double_130.hi(n) +_$double_133.denormalized = function(n) { + var hi = _$double_133.hi(n) return !(hi & 0x7ff00000) } -}).call(this,_$buffer_84.Buffer) +}).call(this,_$buffer_85.Buffer) 'use strict' -/* removed: var _$bn_74 = require('bn.js') */; -/* removed: var _$double_130 = require('double-bits') */; +/* removed: var _$bn_75 = require('bn.js') */; +/* removed: var _$double_133 = require('double-bits') */; -var _$num2bn_64 = num2bn +var _$num2bn_65 = num2bn function num2bn(x) { - var e = _$double_130.exponent(x) + var e = _$double_133.exponent(x) if(e < 52) { - return new _$bn_74(x) + return new _$bn_75(x) } else { - return (new _$bn_74(x * Math.pow(2, 52-e))).ushln(e-52) + return (new _$bn_75(x * Math.pow(2, 52-e))).ushln(e-52) } } 'use strict' -/* removed: var _$num2bn_64 = require('./num-to-bn') */; -/* removed: var _$sign_60 = require('./bn-sign') */; +/* removed: var _$num2bn_65 = require('./num-to-bn') */; +/* removed: var _$sign_61 = require('./bn-sign') */; -var _$rationalize_65 = rationalize +var _$rationalize_66 = rationalize function rationalize(numer, denom) { - var snumer = _$sign_60(numer) - var sdenom = _$sign_60(denom) + var snumer = _$sign_61(numer) + var sdenom = _$sign_61(denom) if(snumer === 0) { - return [_$num2bn_64(0), _$num2bn_64(1)] + return [_$num2bn_65(0), _$num2bn_65(1)] } if(sdenom === 0) { - return [_$num2bn_64(0), _$num2bn_64(0)] + return [_$num2bn_65(0), _$num2bn_65(0)] } if(sdenom < 0) { numer = numer.neg() @@ -99485,19 +100323,19 @@ function rationalize(numer, denom) { 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$div_57 = div +var _$div_58 = div function div(a, b) { - return _$rationalize_65(a[0].mul(b[1]), a[1].mul(b[0])) + return _$rationalize_66(a[0].mul(b[1]), a[1].mul(b[0])) } 'use strict' -/* removed: var _$bn_74 = require('bn.js') */; +/* removed: var _$bn_75 = require('bn.js') */; -var _$isBN_63 = isBN +var _$isBN_64 = isBN //Test if x is a bignumber //FIXME: obviously this is the wrong way to do it @@ -99507,90 +100345,90 @@ function isBN(x) { 'use strict' -/* removed: var _$isBN_63 = require('./lib/is-bn') */; +/* removed: var _$isBN_64 = require('./lib/is-bn') */; -var _$isRat_59 = isRat +var _$isRat_60 = isRat function isRat(x) { - return Array.isArray(x) && x.length === 2 && _$isBN_63(x[0]) && _$isBN_63(x[1]) + return Array.isArray(x) && x.length === 2 && _$isBN_64(x[0]) && _$isBN_64(x[1]) } 'use strict' -/* removed: var _$bn_74 = require('bn.js') */; +/* removed: var _$bn_75 = require('bn.js') */; -var _$str2BN_66 = str2BN +var _$str2BN_67 = str2BN function str2BN(x) { - return new _$bn_74(x) + return new _$bn_75(x) } 'use strict' -/* removed: var _$isRat_59 = require('./is-rat') */; -/* removed: var _$isBN_63 = require('./lib/is-bn') */; -/* removed: var _$num2bn_64 = require('./lib/num-to-bn') */; -/* removed: var _$str2BN_66 = require('./lib/str-to-bn') */; -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; -/* removed: var _$div_57 = require('./div') */; +/* removed: var _$isRat_60 = require('./is-rat') */; +/* removed: var _$isBN_64 = require('./lib/is-bn') */; +/* removed: var _$num2bn_65 = require('./lib/num-to-bn') */; +/* removed: var _$str2BN_67 = require('./lib/str-to-bn') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; +/* removed: var _$div_58 = require('./div') */; -var _$makeRational_58 = makeRational +var _$makeRational_59 = makeRational function makeRational(numer, denom) { - if(_$isRat_59(numer)) { + if(_$isRat_60(numer)) { if(denom) { - return _$div_57(numer, makeRational(denom)) + return _$div_58(numer, makeRational(denom)) } return [numer[0].clone(), numer[1].clone()] } var shift = 0 var a, b - if(_$isBN_63(numer)) { + if(_$isBN_64(numer)) { a = numer.clone() } else if(typeof numer === 'string') { - a = _$str2BN_66(numer) + a = _$str2BN_67(numer) } else if(numer === 0) { - return [_$num2bn_64(0), _$num2bn_64(1)] + return [_$num2bn_65(0), _$num2bn_65(1)] } else if(numer === Math.floor(numer)) { - a = _$num2bn_64(numer) + a = _$num2bn_65(numer) } else { while(numer !== Math.floor(numer)) { numer = numer * Math.pow(2, 256) shift -= 256 } - a = _$num2bn_64(numer) + a = _$num2bn_65(numer) } - if(_$isRat_59(denom)) { + if(_$isRat_60(denom)) { a.mul(denom[1]) b = denom[0].clone() - } else if(_$isBN_63(denom)) { + } else if(_$isBN_64(denom)) { b = denom.clone() } else if(typeof denom === 'string') { - b = _$str2BN_66(denom) + b = _$str2BN_67(denom) } else if(!denom) { - b = _$num2bn_64(1) + b = _$num2bn_65(1) } else if(denom === Math.floor(denom)) { - b = _$num2bn_64(denom) + b = _$num2bn_65(denom) } else { while(denom !== Math.floor(denom)) { denom = denom * Math.pow(2, 256) shift += 256 } - b = _$num2bn_64(denom) + b = _$num2bn_65(denom) } if(shift > 0) { a = a.ushln(shift) } else if(shift < 0) { b = b.ushln(-shift) } - return _$rationalize_65(a, b) + return _$rationalize_66(a, b) } 'use strict' -/* removed: var _$sign_60 = require('./bn-sign') */; +/* removed: var _$sign_61 = require('./bn-sign') */; -var _$bn2num_61 = bn2num +var _$bn2num_62 = bn2num //TODO: Make this better function bn2num(b) { @@ -99607,23 +100445,23 @@ function bn2num(b) { out += w * Math.pow(0x4000000, i) } } - return _$sign_60(b) * out + return _$sign_61(b) * out } 'use strict' -/* removed: var _$double_130 = require('double-bits') */; -var ctz = _$twiddle_72.countTrailingZeros +/* removed: var _$double_133 = require('double-bits') */; +var ctz = _$twiddle_73.countTrailingZeros -var _$ctzNumber_62 = ctzNumber +var _$ctzNumber_63 = ctzNumber //Counts the number of trailing zeros function ctzNumber(x) { - var l = ctz(_$double_130.lo(x)) + var l = ctz(_$double_133.lo(x)) if(l < 32) { return l } - var h = ctz(_$double_130.hi(x)) + var h = ctz(_$double_133.hi(x)) if(h > 20) { return 52 } @@ -99632,10 +100470,10 @@ function ctzNumber(x) { 'use strict' -/* removed: var _$bn2num_61 = require('./lib/bn-to-num') */; -/* removed: var _$ctzNumber_62 = require('./lib/ctz') */; +/* removed: var _$bn2num_62 = require('./lib/bn-to-num') */; +/* removed: var _$ctzNumber_63 = require('./lib/ctz') */; -var _$roundRat_70 = roundRat +var _$roundRat_71 = roundRat // Round a rational to the closest float function roundRat (f) { @@ -99646,19 +100484,19 @@ function roundRat (f) { } var h = a.abs().divmod(b.abs()) var iv = h.div - var x = _$bn2num_61(iv) + var x = _$bn2num_62(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 = _$ctzNumber_62(x) + 4 - var y = _$bn2num_61(ir.ushln(s).divRound(b)) + var s = _$ctzNumber_63(x) + 4 + var y = _$bn2num_62(ir.ushln(s).divRound(b)) return sgn * (x + y * Math.pow(2, -s)) } else { var ybits = b.bitLength() - ir.bitLength() + 53 - var y = _$bn2num_61(ir.ushln(ybits).divRound(b)) + var y = _$bn2num_62(ir.ushln(ybits).divRound(b)) if (ybits < 1023) { return sgn * y * Math.pow(2, -ybits) } @@ -99667,7 +100505,7 @@ function roundRat (f) { } } -var _$brute_77 = {}; +var _$brute_78 = {}; 'use strict' var DIMENSION = 'd' @@ -99810,13 +100648,13 @@ function bruteForcePlanner(full) { } -_$brute_77.partial = bruteForcePlanner(false) -_$brute_77.full = bruteForcePlanner(true) +_$brute_78.partial = bruteForcePlanner(false) +_$brute_78.full = bruteForcePlanner(true) 'use strict' -var _$genPartition_80 = genPartition +var _$genPartition_81 = genPartition -var __code_80 = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' +var __code_81 = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' function genPartition(predicate, args) { var fargs ='abcdef'.split('').concat(args) @@ -99828,17 +100666,17 @@ function genPartition(predicate, args) { reads.push('hi=e[k+o]') } fargs.push( - __code_80.replace('_', reads.join()) + __code_81.replace('_', reads.join()) .replace('$', predicate)) return Function.apply(void 0, fargs) } 'use strict' -var _$findMedian_79 = findMedian +var _$findMedian_80 = findMedian -/* removed: var _$genPartition_80 = require('./partition') */; +/* removed: var _$genPartition_81 = require('./partition') */; -var partitionStartLessThan = _$genPartition_80('loright var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 var blueActive = 0 @@ -100390,7 +101228,7 @@ function sweepComplete(d, visit, //process events from left->right var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 var blueActive = 0 @@ -100500,7 +101338,7 @@ function scanBipartite( //process events from left->right var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 for(var i=0; iright var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 for(var i=0; i=p0)&&!(p1>=hi)', ['p0', 'p1']) -var partitionStartEqual = _$genPartition_80( +var partitionStartEqual = _$genPartition_81( 'lo===p0', ['p0']) -var __partitionStartLessThan_78 = _$genPartition_80( +var __partitionStartLessThan_79 = _$genPartition_81( 'lo mid point // - var blue0 = _$findMedian_79( + var blue0 = _$findMedian_80( d, axis, blueStart, blueEnd, blue, blueIndex) var mid = blue[elemSize * blue0 + axis] @@ -101048,7 +101886,7 @@ function boxIntersectIter( //Degenerate sweep intersection: // [red0, redX] with [blue0, blue1] if(red0 < redX) { - retval = _$sweep_82.sweepComplete( + retval = _$sweep_83.sweepComplete( d, visit, red0, redX, red, redIndex, blue0, blue1, blue, blueIndex) @@ -101060,7 +101898,7 @@ function boxIntersectIter( //Normal sweep intersection: // [redX, red1] with [blue0, blue1] if(redX < red1) { - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, redX, red1, red, redIndex, blue0, blue1, blue, blueIndex) @@ -101108,12 +101946,12 @@ function boxIntersectIter( if(red0 < red1) { if(axis === d-2) { if(flip) { - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, blue0, blue1, blue, blueIndex, red0, red1, red, redIndex) } else { - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, red0, red1, red, redIndex, blue0, blue1, blue, blueIndex) @@ -101140,11 +101978,11 @@ function boxIntersectIter( } 'use strict' -var _$boxIntersectWrapper_76 = boxIntersectWrapper +var _$boxIntersectWrapper_77 = boxIntersectWrapper -/* removed: var _$pool_360 = require('typedarray-pool') */; -/* removed: var _$sweep_82 = require('./lib/sweep') */; -/* removed: var _$boxIntersectIter_78 = require('./lib/intersect') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; +/* removed: var _$sweep_83 = require('./lib/sweep') */; +/* removed: var _$boxIntersectIter_79 = require('./lib/intersect') */; function boxEmpty(d, box) { for(var j=0; j 0) { if(d === 1 && full) { //Special case: 1d complete - _$sweep_82.init(n) - retval = _$sweep_82.sweepComplete( + _$sweep_83.init(n) + retval = _$sweep_83.sweepComplete( d, visit, 0, n, redList, redIds, 0, n, redList, redIds) } else { //Convert blue boxes - var blueList = _$pool_360.mallocDouble(2*d*m) - var blueIds = _$pool_360.mallocInt32(m) + var blueList = _$pool_422.mallocDouble(2*d*m) + var blueIds = _$pool_422.mallocInt32(m) m = convertBoxes(blue, d, blueList, blueIds) if(m > 0) { - _$sweep_82.init(n+m) + _$sweep_83.init(n+m) if(d === 1) { //Special case: 1d bipartite - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, 0, n, redList, redIds, 0, m, blueList, blueIds) } else { //General case: d>1 - retval = _$boxIntersectIter_78( + retval = _$boxIntersectIter_79( d, visit, full, n, redList, redIds, m, blueList, blueIds) } - _$pool_360.free(blueList) - _$pool_360.free(blueIds) + _$pool_422.free(blueList) + _$pool_422.free(blueIds) } } - _$pool_360.free(redList) - _$pool_360.free(redIds) + _$pool_422.free(redList) + _$pool_422.free(redIds) } return retval @@ -101278,107 +102116,107 @@ function boxIntersectWrapper(arg0, arg1, arg2) { } 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$mul_67 = mul +var _$mul_68 = mul function mul(a, b) { - return _$rationalize_65(a[0].mul(b[0]), a[1].mul(b[1])) + return _$rationalize_66(a[0].mul(b[0]), a[1].mul(b[1])) } 'use strict' -/* removed: var _$sign_60 = require('./lib/bn-sign') */; +/* removed: var _$sign_61 = require('./lib/bn-sign') */; -var _$sign_68 = __sign_68 +var _$sign_69 = __sign_69 -function __sign_68(x) { - return _$sign_60(x[0]) * _$sign_60(x[1]) +function __sign_69(x) { + return _$sign_61(x[0]) * _$sign_61(x[1]) } 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$sub_69 = sub +var _$sub_70 = sub function sub(a, b) { - return _$rationalize_65(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) + return _$rationalize_66(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) } 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$add_55 = add +var _$add_56 = add function add(a, b) { - return _$rationalize_65( + return _$rationalize_66( a[0].mul(b[1]).add(b[0].mul(a[1])), a[1].mul(b[1])) } 'use strict' -/* removed: var _$add_55 = require('big-rat/add') */; +/* removed: var _$add_56 = require('big-rat/add') */; -var _$add_306 = __add_306 +var _$add_369 = __add_369 -function __add_306 (a, b) { +function __add_369 (a, b) { var n = a.length var r = new Array(n) for (var i=0; i>>0 -var _$nextafter_278 = nextafter +var _$nextafter_336 = nextafter function nextafter(x, y) { if(isNaN(x) || isNaN(y)) { @@ -101431,8 +102269,8 @@ function nextafter(x, y) { return SMALLEST_DENORM } } - var hi = _$double_130.hi(x) - var lo = _$double_130.lo(x) + var hi = _$double_133.hi(x) + var lo = _$double_133.lo(x) if((y > x) === (x > 0)) { if(lo === UINT_MAX) { hi += 1 @@ -101448,27 +102286,27 @@ function nextafter(x, y) { lo -= 1 } } - return _$double_130.pack(lo, hi) + return _$double_133.pack(lo, hi) } 'use strict' -var _$float2rat_307 = float2rat +var _$float2rat_370 = float2rat -/* removed: var _$makeRational_58 = require('big-rat') */; +/* removed: var _$makeRational_59 = require('big-rat') */; function float2rat(v) { var result = new Array(v.length) for(var i=0; i 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { return false } - var x1 = __orient_326(b0, a0, a1) - var y1 = __orient_326(b1, a0, a1) + var x1 = __orient_390(b0, a0, a1) + var y1 = __orient_390(b1, a0, a1) if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { return false } @@ -101513,7 +102351,7 @@ function __segmentsIntersect_326(a0, a1, b0, b1) { } "use strict"; "use restrict"; -var _$UnionFind_361 = UnionFind; +var _$UnionFind_423 = UnionFind; function UnionFind(count) { this.roots = new Array(count); @@ -101525,22 +102363,22 @@ function UnionFind(count) { } } -var __proto_361 = UnionFind.prototype +var __proto_423 = UnionFind.prototype -Object.defineProperty(__proto_361, "length", { +Object.defineProperty(__proto_423, "length", { "get": function() { return this.roots.length } }) -__proto_361.makeSet = function() { +__proto_423.makeSet = function() { var n = this.roots.length; this.roots.push(n); this.ranks.push(0); return n; } -__proto_361.find = function(x) { +__proto_423.find = function(x) { var x0 = x var roots = this.roots; while(roots[x] !== x) { @@ -101554,7 +102392,7 @@ __proto_361.find = function(x) { return x; } -__proto_361.link = function(x, y) { +__proto_423.link = function(x, y) { var xr = this.find(x) , yr = this.find(y); if(xr === yr) { @@ -101575,25 +102413,25 @@ __proto_361.link = function(x, y) { } 'use strict' -var _$cleanPSLG_95 = cleanPSLG +var _$cleanPSLG_96 = cleanPSLG -/* removed: var _$UnionFind_361 = require('union-find') */; -/* removed: var _$boxIntersectWrapper_76 = require('box-intersect') */; -/* removed: var _$segmentsIntersect_326 = require('robust-segment-intersect') */; -/* removed: var _$makeRational_58 = require('big-rat') */; -/* removed: var _$cmp_56 = require('big-rat/cmp') */; -/* removed: var _$roundRat_70 = require('big-rat/to-float') */; -/* removed: var _$float2rat_307 = require('rat-vec') */; -/* removed: var _$nextafter_278 = require('nextafter') */; +/* removed: var _$UnionFind_423 = require('union-find') */; +/* removed: var _$boxIntersectWrapper_77 = require('box-intersect') */; +/* removed: var _$segmentsIntersect_390 = require('robust-segment-intersect') */; +/* removed: var _$makeRational_59 = require('big-rat') */; +/* removed: var _$cmp_57 = require('big-rat/cmp') */; +/* removed: var _$roundRat_71 = require('big-rat/to-float') */; +/* removed: var _$float2rat_370 = require('rat-vec') */; +/* removed: var _$nextafter_336 = require('nextafter') */; -/* removed: var _$solveIntersection_96 = require('./lib/rat-seg-intersect') */; +/* removed: var _$solveIntersection_97 = require('./lib/rat-seg-intersect') */; // Bounds on a rational number when rounded to a float function boundRat (r) { - var f = _$roundRat_70(r) + var f = _$roundRat_71(r) return [ - _$nextafter_278(f, -Infinity), - _$nextafter_278(f, Infinity) + _$nextafter_336(f, -Infinity), + _$nextafter_336(f, Infinity) ] } @@ -101605,10 +102443,10 @@ function boundEdges (points, edges) { var a = points[e[0]] var b = points[e[1]] bounds[i] = [ - _$nextafter_278(Math.min(a[0], b[0]), -Infinity), - _$nextafter_278(Math.min(a[1], b[1]), -Infinity), - _$nextafter_278(Math.max(a[0], b[0]), Infinity), - _$nextafter_278(Math.max(a[1], b[1]), Infinity) + _$nextafter_336(Math.min(a[0], b[0]), -Infinity), + _$nextafter_336(Math.min(a[1], b[1]), -Infinity), + _$nextafter_336(Math.max(a[0], b[0]), Infinity), + _$nextafter_336(Math.max(a[1], b[1]), Infinity) ] } return bounds @@ -101620,10 +102458,10 @@ function boundPoints (points) { for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ - _$nextafter_278(p[0], -Infinity), - _$nextafter_278(p[1], -Infinity), - _$nextafter_278(p[0], Infinity), - _$nextafter_278(p[1], Infinity) + _$nextafter_336(p[0], -Infinity), + _$nextafter_336(p[1], -Infinity), + _$nextafter_336(p[0], Infinity), + _$nextafter_336(p[1], Infinity) ] } return bounds @@ -101632,7 +102470,7 @@ function boundPoints (points) { // Find all pairs of crossing edges in a pslg (given edge bounds) function getCrossings (points, edges, edgeBounds) { var result = [] - _$boxIntersectWrapper_76(edgeBounds, function (i, j) { + _$boxIntersectWrapper_77(edgeBounds, function (i, j) { var e = edges[i] var f = edges[j] if (e[0] === f[0] || e[0] === f[1] || @@ -101643,7 +102481,7 @@ function getCrossings (points, edges, edgeBounds) { var b = points[e[1]] var c = points[f[0]] var d = points[f[1]] - if (_$segmentsIntersect_326(a, b, c, d)) { + if (_$segmentsIntersect_390(a, b, c, d)) { result.push([i, j]) } }) @@ -101653,7 +102491,7 @@ function getCrossings (points, edges, edgeBounds) { // Find all pairs of crossing vertices in a pslg (given edge/vert bounds) function getTJunctions (points, edges, edgeBounds, vertBounds) { var result = [] - _$boxIntersectWrapper_76(edgeBounds, vertBounds, function (i, v) { + _$boxIntersectWrapper_77(edgeBounds, vertBounds, function (i, v) { var e = edges[i] if (e[0] === v || e[1] === v) { return @@ -101661,7 +102499,7 @@ function getTJunctions (points, edges, edgeBounds, vertBounds) { var p = points[v] var a = points[e[0]] var b = points[e[1]] - if (_$segmentsIntersect_326(a, b, p, p)) { + if (_$segmentsIntersect_390(a, b, p, p)) { result.push([i, v]) } }) @@ -101675,8 +102513,8 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { // Convert crossings into tjunctions by constructing rational points var ratPoints = floatPoints.map(function(p) { return [ - _$makeRational_58(p[0]), - _$makeRational_58(p[1]) + _$makeRational_59(p[0]), + _$makeRational_59(p[1]) ] }) for (i = 0; i < crossings.length; ++i) { @@ -101685,17 +102523,17 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { var f = crossing[1] var ee = edges[e] var ef = edges[f] - var x = _$solveIntersection_96( - _$float2rat_307(floatPoints[ee[0]]), - _$float2rat_307(floatPoints[ee[1]]), - _$float2rat_307(floatPoints[ef[0]]), - _$float2rat_307(floatPoints[ef[1]])) + var x = _$solveIntersection_97( + _$float2rat_370(floatPoints[ee[0]]), + _$float2rat_370(floatPoints[ee[1]]), + _$float2rat_370(floatPoints[ef[0]]), + _$float2rat_370(floatPoints[ef[1]])) if (!x) { // Segments are parallel, should already be handled by t-junctions continue } var idx = floatPoints.length - floatPoints.push([_$roundRat_70(x[0]), _$roundRat_70(x[1])]) + floatPoints.push([_$roundRat_71(x[0]), _$roundRat_71(x[1])]) ratPoints.push(x) junctions.push([e, idx], [f, idx]) } @@ -101707,7 +102545,7 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { } var u = ratPoints[a[1]] var v = ratPoints[b[1]] - return _$cmp_56(u[0], v[0]) || _$cmp_56(u[1], v[1]) + return _$cmp_57(u[0], v[0]) || _$cmp_57(u[1], v[1]) }) // Split edges along junctions @@ -101765,7 +102603,7 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { // Merge overlapping points function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length - var uf = new _$UnionFind_361(numPoints) + var uf = new _$UnionFind_423(numPoints) // Compute rational bounds var bounds = [] @@ -101774,15 +102612,15 @@ function dedupPoints (floatPoints, ratPoints, floatBounds) { var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ - _$nextafter_278(xb[0], -Infinity), - _$nextafter_278(yb[0], -Infinity), - _$nextafter_278(xb[1], Infinity), - _$nextafter_278(yb[1], Infinity) + _$nextafter_336(xb[0], -Infinity), + _$nextafter_336(yb[0], -Infinity), + _$nextafter_336(xb[1], Infinity), + _$nextafter_336(yb[1], Infinity) ]) } // Link all points with over lapping boxes - _$boxIntersectWrapper_76(bounds, function (i, j) { + _$boxIntersectWrapper_77(bounds, function (i, j) { uf.link(i, j) }) @@ -101957,9 +102795,9 @@ function cleanPSLG (points, edges, colors) { "use strict" -var _$edgeToAdjacency_135 = edgeToAdjacency +var _$edgeToAdjacency_138 = edgeToAdjacency -/* removed: var _$unique_362 = require("uniq") */; +/* removed: var _$unique_424 = require("uniq") */; function edgeToAdjacency(edges, numVertices) { var numEdges = edges.length @@ -101982,7 +102820,7 @@ function edgeToAdjacency(edges, numVertices) { adj[e[1]].push(e[0]) } for(var j=0; j 0) { return 1 } return 0.0 } "use strict" -var _$compareAngle_106 = compareAngle +var _$compareAngle_107 = compareAngle -/* removed: var _$orientation_323 = require("robust-orientation") */; -/* removed: var _$signum_329 = require("signum") */; -/* removed: var _$fastTwoSum_359 = require("two-sum") */; -/* removed: var _$robustProduct_324 = require("robust-product") */; -/* removed: var _$linearExpansionSum_328 = require("robust-sum") */; +/* removed: var _$orientation_387 = require("robust-orientation") */; +/* removed: var _$signum_393 = require("signum") */; +/* removed: var _$fastTwoSum_421 = require("two-sum") */; +/* removed: var _$robustProduct_388 = require("robust-product") */; +/* removed: var _$linearExpansionSum_392 = require("robust-sum") */; function testInterior(a, b, c) { - var x0 = _$fastTwoSum_359(a[0], -b[0]) - var y0 = _$fastTwoSum_359(a[1], -b[1]) - var x1 = _$fastTwoSum_359(c[0], -b[0]) - var y1 = _$fastTwoSum_359(c[1], -b[1]) + var x0 = _$fastTwoSum_421(a[0], -b[0]) + var y0 = _$fastTwoSum_421(a[1], -b[1]) + var x1 = _$fastTwoSum_421(c[0], -b[0]) + var y1 = _$fastTwoSum_421(c[1], -b[1]) - var d = _$linearExpansionSum_328( - _$robustProduct_324(x0, x1), - _$robustProduct_324(y0, y1)) + var d = _$linearExpansionSum_392( + _$robustProduct_388(x0, x1), + _$robustProduct_388(y0, y1)) return d[d.length-1] >= 0 } function compareAngle(a, b, c, d) { - var bcd = _$orientation_323(b, c, d) + var bcd = _$orientation_387(b, c, d) if(bcd === 0) { //Handle degenerate cases - var sabc = _$signum_329(_$orientation_323(a, b, c)) - var sabd = _$signum_329(_$orientation_323(a, b, d)) + var sabc = _$signum_393(_$orientation_387(a, b, c)) + var sabd = _$signum_393(_$orientation_387(a, b, d)) if(sabc === sabd) { if(sabc === 0) { var ic = testInterior(a, b, c) @@ -102083,21 +102921,21 @@ function compareAngle(a, b, c, d) { return -1 } } - return _$signum_329(sabd - sabc) + return _$signum_393(sabd - sabc) } - var abc = _$orientation_323(a, b, c) + var abc = _$orientation_387(a, b, c) if(abc > 0) { - if(bcd > 0 && _$orientation_323(a, b, d) > 0) { + if(bcd > 0 && _$orientation_387(a, b, d) > 0) { return 1 } return -1 } else if(abc < 0) { - if(bcd > 0 || _$orientation_323(a, b, d) > 0) { + if(bcd > 0 || _$orientation_387(a, b, d) > 0) { return 1 } return -1 } else { - var abd = _$orientation_323(a, b, d) + var abd = _$orientation_387(a, b, d) if(abd > 0) { return 1 } else { @@ -102111,9 +102949,9 @@ function compareAngle(a, b, c, d) { } "use strict" -var _$planarDual_291 = planarDual +var _$planarDual_350 = planarDual -/* removed: var _$compareAngle_106 = require("compare-angle") */; +/* removed: var _$compareAngle_107 = require("compare-angle") */; function planarDual(cells, positions) { @@ -102162,7 +103000,7 @@ function planarDual(cells, positions) { for(var k=0; k>>1,x=a", useNdarray ? ".get(m)" : "[m]"] return code.join("") } -function __compileBoundsSearch_71(predicate, reversed, suffix, earlyOut) { +function __compileBoundsSearch_72(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_71("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), - __compileSearch_71("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), - __compileSearch_71("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), - __compileSearch_71("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut), + __compileSearch_72("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), + __compileSearch_72("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), + __compileSearch_72("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), + __compileSearch_72("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'){\ @@ -102347,23 +103185,23 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_71 = { - ge: __compileBoundsSearch_71(">=", false, "GE"), - gt: __compileBoundsSearch_71(">", false, "GT"), - lt: __compileBoundsSearch_71("<", true, "LT"), - le: __compileBoundsSearch_71("<=", true, "LE"), - eq: __compileBoundsSearch_71("-", true, "EQ", true) +var _$searchBounds_72 = { + ge: __compileBoundsSearch_72(">=", false, "GE"), + gt: __compileBoundsSearch_72(">", false, "GT"), + lt: __compileBoundsSearch_72("<", true, "LT"), + le: __compileBoundsSearch_72("<=", true, "LE"), + eq: __compileBoundsSearch_72("-", true, "EQ", true) } "use strict" -/* removed: var _$searchBounds_71 = require("binary-search-bounds") */; +/* removed: var _$searchBounds_72 = require("binary-search-bounds") */; var NOT_FOUND = 0 var SUCCESS = 1 var EMPTY = 2 -var _$createWrapper_243 = createWrapper +var _$createWrapper_300 = createWrapper function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { this.mid = mid @@ -102374,7 +103212,7 @@ function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length } -var __proto_243 = IntervalTreeNode.prototype +var __proto_300 = IntervalTreeNode.prototype function copy(a, b) { a.mid = b.mid @@ -102412,7 +103250,7 @@ function rebuildWithoutInterval(node, interval) { return SUCCESS } -__proto_243.intervals = function(result) { +__proto_300.intervals = function(result) { result.push.apply(result, this.leftPoints) if(this.left) { this.left.intervals(result) @@ -102423,7 +103261,7 @@ __proto_243.intervals = function(result) { return result } -__proto_243.insert = function(interval) { +__proto_300.insert = function(interval) { var weight = this.count - this.leftPoints.length this.count += 1 if(interval[1] < this.mid) { @@ -102447,14 +103285,14 @@ __proto_243.insert = function(interval) { this.right = createIntervalTree([interval]) } } else { - var l = _$searchBounds_71.ge(this.leftPoints, interval, compareBegin) - var r = _$searchBounds_71.ge(this.rightPoints, interval, compareEnd) + var l = _$searchBounds_72.ge(this.leftPoints, interval, compareBegin) + var r = _$searchBounds_72.ge(this.rightPoints, interval, compareEnd) this.leftPoints.splice(l, 0, interval) this.rightPoints.splice(r, 0, interval) } } -__proto_243.remove = function(interval) { +__proto_300.remove = function(interval) { var weight = this.count - this.leftPoints if(interval[1] < this.mid) { if(!this.left) { @@ -102525,14 +103363,14 @@ __proto_243.remove = function(interval) { } return SUCCESS } - for(var l = _$searchBounds_71.ge(this.leftPoints, interval, compareBegin); l 0) { @@ -103874,8 +104712,8 @@ function searchBucket(root, p) { return lastNode } -__proto_339.castUp = function(p) { - var bucket = _$searchBounds_71.le(this.coordinates, p[0]) +__proto_403.castUp = function(p) { + var bucket = _$searchBounds_72.le(this.coordinates, p[0]) if(bucket < 0) { return -1 } @@ -103895,7 +104733,7 @@ __proto_339.castUp = function(p) { var otherHitNode = searchBucket(this.slabs[bucket-1], p) if(otherHitNode) { if(lastSegment) { - if(_$orderSegments_338(otherHitNode.key, lastSegment) > 0) { + if(_$orderSegments_402(otherHitNode.key, lastSegment) > 0) { lastSegment = otherHitNode.key lastHit = otherHitNode.value } @@ -103907,7 +104745,7 @@ __proto_339.castUp = function(p) { } var horiz = this.horizontal[bucket] if(horiz.length > 0) { - var hbucket = _$searchBounds_71.ge(horiz, p[1], compareHorizontal) + var hbucket = _$searchBounds_72.ge(horiz, p[1], compareHorizontal) if(hbucket < horiz.length) { var e = horiz[hbucket] if(p[1] === e.y) { @@ -103933,7 +104771,7 @@ __proto_339.castUp = function(p) { //Check if e is above/below last segment if(e.start) { if(lastSegment) { - var o = _$orientation_323(lastSegment[0], lastSegment[1], [p[0], e.y]) + var o = _$orientation_387(lastSegment[0], lastSegment[1], [p[0], e.y]) if(lastSegment[0][0] > lastSegment[1][0]) { o = -o } @@ -103959,7 +104797,7 @@ function IntervalSegment(y, index, start, closed) { this.closed = closed } -function __Event_339(x, segment, create, index) { +function __Event_403(x, segment, create, index) { this.x = x this.segment = segment this.create = create @@ -103974,8 +104812,8 @@ function createSlabDecomposition(segments) { for(var i=0; i 0 } @@ -104272,7 +105110,7 @@ function planarGraphToPolyline(edges, positions) { var loopVertices = faces[i].map(function(v) { return positions[v] }) - var pmc = _$preprocessPolygon_294([loopVertices]) + var pmc = _$preprocessPolygon_356([loopVertices]) var count = 0 outer: for(var j=0; j 0) { var top = toVisit.pop() var nbhd = fadj[top] - _$unique_362(nbhd, function(a,b) { + _$unique_424(nbhd, function(a,b) { return a-b }) var nnbhr = nbhd.length @@ -104397,11 +105235,11 @@ function planarGraphToPolyline(edges, positions) { return result } -var _$topology_333 = {}; +var _$topology_397 = {}; "use strict"; "use restrict"; -var __dummy_333$0 = 0 - , __dummy_333$1 = 0 +var __dummy_397$0 = 0 + , __dummy_397$1 = 0 //Returns the dimension of a cell complex function dimension(cells) { @@ -104412,7 +105250,7 @@ function dimension(cells) { } return d-1 } -_$topology_333.dimension = dimension +_$topology_397.dimension = dimension //Counts the number of vertices in faces function countVertices(cells) { @@ -104426,7 +105264,7 @@ function countVertices(cells) { } return vc+1 } -_$topology_333.countVertices = countVertices +_$topology_397.countVertices = countVertices //Returns a deep copy of cells function cloneCells(cells) { @@ -104436,7 +105274,7 @@ function cloneCells(cells) { } return ncells } -_$topology_333.cloneCells = cloneCells +_$topology_397.cloneCells = cloneCells //Ranks a pair of cells up to permutation function compareCells(a, b) { @@ -104488,7 +105326,7 @@ function compareCells(a, b) { return 0 } } -_$topology_333.compareCells = compareCells +_$topology_397.compareCells = compareCells function compareZipped(a, b) { return compareCells(a[0], b[0]) @@ -104513,10 +105351,10 @@ function normalize(cells, attr) { return cells } } -_$topology_333.normalize = normalize +_$topology_397.normalize = normalize //Removes all duplicate cells in the complex -function __unique_333(cells) { +function __unique_397(cells) { if(cells.length === 0) { return [] } @@ -104535,7 +105373,7 @@ function __unique_333(cells) { cells.length = ptr return cells } -_$topology_333.unique = __unique_333; +_$topology_397.unique = __unique_397; //Finds a cell in a normalized cell complex function findCell(cells, c) { @@ -104556,7 +105394,7 @@ function findCell(cells, c) { } return r } -_$topology_333.findCell = findCell; +_$topology_397.findCell = findCell; //Builds an index for an n-cell. This is more general than dual, but less efficient function incidence(from_cells, to_cells) { @@ -104569,7 +105407,7 @@ function incidence(from_cells, to_cells) { var c = to_cells[i] var cl = c.length for(var k=1, kn=(1< 0) - (v < 0); } //Computes absolute value of integer -_$twiddle_334.abs = function(v) { - var mask = v >> (__INT_BITS_334-1); +_$twiddle_398.abs = function(v) { + var mask = v >> (__INT_BITS_398-1); return (v ^ mask) - mask; } //Computes minimum of integers x and y -_$twiddle_334.min = function(x, y) { +_$twiddle_398.min = function(x, y) { return y ^ ((x ^ y) & -(x < y)); } //Computes maximum of integers x and y -_$twiddle_334.max = function(x, y) { +_$twiddle_398.max = function(x, y) { return x ^ ((x ^ y) & -(x < y)); } //Checks if a number is a power of two -_$twiddle_334.isPow2 = function(v) { +_$twiddle_398.isPow2 = function(v) { return !(v & (v-1)) && (!!v); } //Computes log base 2 of v -_$twiddle_334.log2 = function(v) { +_$twiddle_398.log2 = function(v) { var r, shift; r = (v > 0xFFFF) << 4; v >>>= r; shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; @@ -104798,21 +105636,21 @@ _$twiddle_334.log2 = function(v) { } //Computes log base 10 of v -_$twiddle_334.log10 = function(v) { +_$twiddle_398.log10 = function(v) { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } //Counts number of bits -_$twiddle_334.popCount = function(v) { +_$twiddle_398.popCount = function(v) { v = v - ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; } //Counts number of trailing zeros -function __countTrailingZeros_334(v) { +function __countTrailingZeros_398(v) { var c = 32; v &= -v; if (v) c--; @@ -104823,10 +105661,10 @@ function __countTrailingZeros_334(v) { if (v & 0x55555555) c -= 1; return c; } -_$twiddle_334.countTrailingZeros = __countTrailingZeros_334; +_$twiddle_398.countTrailingZeros = __countTrailingZeros_398; //Rounds to next power of 2 -_$twiddle_334.nextPow2 = function(v) { +_$twiddle_398.nextPow2 = function(v) { v += v === 0; --v; v |= v >>> 1; @@ -104838,7 +105676,7 @@ _$twiddle_334.nextPow2 = function(v) { } //Rounds down to previous power of 2 -_$twiddle_334.prevPow2 = function(v) { +_$twiddle_398.prevPow2 = function(v) { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; @@ -104848,7 +105686,7 @@ _$twiddle_334.prevPow2 = function(v) { } //Computes parity of word -_$twiddle_334.parity = function(v) { +_$twiddle_398.parity = function(v) { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; @@ -104856,7 +105694,7 @@ _$twiddle_334.parity = function(v) { return (0x6996 >>> v) & 1; } -var __REVERSE_TABLE_334 = new Array(256); +var __REVERSE_TABLE_398 = new Array(256); (function(tab) { for(var i=0; i<256; ++i) { @@ -104868,18 +105706,18 @@ var __REVERSE_TABLE_334 = new Array(256); } tab[i] = (r << s) & 0xff; } -})(__REVERSE_TABLE_334); +})(__REVERSE_TABLE_398); //Reverse bits in a 32 bit word -_$twiddle_334.reverse = function(v) { - return (__REVERSE_TABLE_334[ v & 0xff] << 24) | - (__REVERSE_TABLE_334[(v >>> 8) & 0xff] << 16) | - (__REVERSE_TABLE_334[(v >>> 16) & 0xff] << 8) | - __REVERSE_TABLE_334[(v >>> 24) & 0xff]; +_$twiddle_398.reverse = function(v) { + return (__REVERSE_TABLE_398[ v & 0xff] << 24) | + (__REVERSE_TABLE_398[(v >>> 8) & 0xff] << 16) | + (__REVERSE_TABLE_398[(v >>> 16) & 0xff] << 8) | + __REVERSE_TABLE_398[(v >>> 24) & 0xff]; } //Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -_$twiddle_334.interleave2 = function(x, y) { +_$twiddle_398.interleave2 = function(x, y) { x &= 0xFFFF; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; @@ -104896,7 +105734,7 @@ _$twiddle_334.interleave2 = function(x, y) { } //Extracts the nth interleaved component -_$twiddle_334.deinterleave2 = function(v, n) { +_$twiddle_398.deinterleave2 = function(v, n) { v = (v >>> n) & 0x55555555; v = (v | (v >>> 1)) & 0x33333333; v = (v | (v >>> 2)) & 0x0F0F0F0F; @@ -104907,7 +105745,7 @@ _$twiddle_334.deinterleave2 = function(v, n) { //Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -_$twiddle_334.interleave3 = function(x, y, z) { +_$twiddle_398.interleave3 = function(x, y, z) { x &= 0x3FF; x = (x | (x<<16)) & 4278190335; x = (x | (x<<8)) & 251719695; @@ -104931,7 +105769,7 @@ _$twiddle_334.interleave3 = function(x, y, z) { } //Extracts nth interleaved component of a 3-tuple -_$twiddle_334.deinterleave3 = function(v, n) { +_$twiddle_398.deinterleave3 = function(v, n) { v = (v >>> n) & 1227133513; v = (v | (v>>>2)) & 3272356035; v = (v | (v>>>4)) & 251719695; @@ -104941,17 +105779,17 @@ _$twiddle_334.deinterleave3 = function(v, n) { } //Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -_$twiddle_334.nextCombination = function(v) { +_$twiddle_398.nextCombination = function(v) { var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (__countTrailingZeros_334(v) + 1)); + return (t + 1) | (((~t & -~t) - 1) >>> (__countTrailingZeros_398(v) + 1)); } "use strict"; "use restrict"; -var _$UnionFind_336 = __UnionFind_336; +var _$UnionFind_400 = __UnionFind_400; -function __UnionFind_336(count) { +function __UnionFind_400(count) { this.roots = new Array(count); this.ranks = new Array(count); @@ -104961,18 +105799,18 @@ function __UnionFind_336(count) { } } -__UnionFind_336.prototype.length = function() { +__UnionFind_400.prototype.length = function() { return this.roots.length; } -__UnionFind_336.prototype.makeSet = function() { +__UnionFind_400.prototype.makeSet = function() { var n = this.roots.length; this.roots.push(n); this.ranks.push(0); return n; } -__UnionFind_336.prototype.find = function(x) { +__UnionFind_400.prototype.find = function(x) { var roots = this.roots; while(roots[x] !== x) { var y = roots[x]; @@ -104982,7 +105820,7 @@ __UnionFind_336.prototype.find = function(x) { return x; } -__UnionFind_336.prototype.link = function(x, y) { +__UnionFind_400.prototype.link = function(x, y) { var xr = this.find(x) , yr = this.find(y); if(xr === yr) { @@ -105003,14 +105841,14 @@ __UnionFind_336.prototype.link = function(x, y) { } -var _$topology_335 = {}; +var _$topology_399 = {}; "use strict"; "use restrict"; -var __dummy_335$0 = 0 - , __dummy_335$1 = 0 +var __dummy_399$0 = 0 + , __dummy_399$1 = 0 //Returns the dimension of a cell complex -function __dimension_335(cells) { +function __dimension_399(cells) { var d = 0 , max = Math.max for(var i=0, il=cells.length; i> 1 - , s = __compareCells_335(cells[mid], c) + , s = __compareCells_399(cells[mid], c) if(s <= 0) { if(s === 0) { r = mid @@ -105162,10 +106000,10 @@ function __findCell_335(cells, c) { } return r } -_$topology_335.findCell = __findCell_335; +_$topology_399.findCell = __findCell_399; //Builds an index for an n-cell. This is more general than dual, but less efficient -function __incidence_335(from_cells, to_cells) { +function __incidence_399(from_cells, to_cells) { var index = new Array(from_cells.length) for(var i=0, il=index.length; i= from_cells.length || __compareCells_335(from_cells[idx], b) !== 0) { + if(idx >= from_cells.length || __compareCells_399(from_cells[idx], b) !== 0) { break } } @@ -105196,12 +106034,12 @@ function __incidence_335(from_cells, to_cells) { } return index } -_$topology_335.incidence = __incidence_335 +_$topology_399.incidence = __incidence_399 //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_335(cells, vertex_count) { +function __dual_399(cells, vertex_count) { if(!vertex_count) { - return __incidence_335(__unique_335(__skeleton_335(cells, 0)), cells, 0) + return __incidence_399(__unique_399(__skeleton_399(cells, 0)), cells, 0) } var res = new Array(vertex_count) for(var i=0; i maxSize || shape[1] < 0 || shape[1] > maxSize) { throw new Error('gl-texture2d: Invalid texture size') } - var packed = __isPacked_218(shape, array.stride.slice()) + var packed = __isPacked_275(shape, array.stride.slice()) var type = 0 if(dtype === 'float32') { type = gl.FLOAT @@ -107646,7 +108484,7 @@ function createTextureArray(gl, array) { if(shape.length === 2) { format = gl.LUMINANCE shape = [shape[0], shape[1], 1] - array = _$wrappedNDArrayCtor_277(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + array = _$wrappedNDArrayCtor_335(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) } else if(shape.length === 3) { if(shape[2] === 1) { format = gl.ALPHA @@ -107670,12 +108508,12 @@ function createTextureArray(gl, array) { var size = array.size if(!packed) { var stride = [shape[2], shape[2]*shape[0], 1] - buf_store = _$pool_360.malloc(size, dtype) - var buf_array = _$wrappedNDArrayCtor_277(buf_store, shape, stride, 0) + buf_store = _$pool_422.malloc(size, dtype) + var buf_array = _$wrappedNDArrayCtor_335(buf_store, shape, stride, 0) if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { convertFloatToUint8(buf_array, array) } else { - _$ndarrayOps_271.assign(buf_array, array) + _$ndarrayOps_329.assign(buf_array, array) } buffer = buf_store.subarray(0, size) } else if (array.offset === 0 && array.data.length === size) { @@ -107686,7 +108524,7 @@ function createTextureArray(gl, array) { var tex = initTexture(gl) gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) if(!packed) { - _$pool_360.free(buf_store) + _$pool_422.free(buf_store) } return new Texture2D(gl, tex, shape[0], shape[1], format, type) } @@ -107718,9 +108556,9 @@ function createTexture2D(gl) { 'use strict' -/* removed: var _$createTexture2D_218 = require('gl-texture2d') */; +/* removed: var _$createTexture2D_275 = require('gl-texture2d') */; -var _$createFBO_158 = createFBO +var _$createFBO_215 = createFBO var colorAttachmentArrays = null var FRAMEBUFFER_UNSUPPORTED @@ -107773,11 +108611,11 @@ function throwFBOError(status) { } //Initialize a texture object -function __initTexture_158(gl, width, height, type, format, attachment) { +function __initTexture_215(gl, width, height, type, format, attachment) { if(!type) { return null } - var result = _$createTexture2D_218(gl, width, height, format, type) + var result = _$createTexture2D_275(gl, width, height, format, type) result.magFilter = gl.NEAREST result.minFilter = gl.NEAREST result.mipSamples = 1 @@ -107816,7 +108654,7 @@ function rebuildFBO(fbo) { //Allocate color buffers for(var i=0; i this.buffer.length) { - _$pool_360.free(this.buffer) - var buffer = this.buffer = _$pool_360.mallocUint8(nextPow2(r*c*4)) + _$pool_422.free(this.buffer) + var buffer = this.buffer = _$pool_422.mallocUint8(nextPow2(r*c*4)) for(var i=0; i', idx); if(nidx < idx) break; - x = x.slice(0, idx) + _$toSuperScript_345(x.slice(idx + 5, nidx)) + x.slice(nidx + 6); + x = x.slice(0, idx) + _$toSuperScript_407(x.slice(idx + 5, nidx)) + x.slice(nidx + 6); } return x; @@ -109273,7 +110111,7 @@ function stripTags(x) { } function fixEntities(x) { - var entityToUnicode = _$string_mappings_518.entityToUnicode; + var entityToUnicode = _$string_mappings_579.entityToUnicode; var idx = 0; while((idx = x.indexOf('&', idx)) >= 0) { @@ -109303,7 +110141,7 @@ function convertHTMLToUnicode(html) { html)))); } -var _$convertHTMLToUnicode_537 = convertHTMLToUnicode; +var _$convertHTMLToUnicode_599 = convertHTMLToUnicode; /** * Copyright 2012-2018, Plotly, Inc. @@ -109316,9 +110154,9 @@ var _$convertHTMLToUnicode_537 = convertHTMLToUnicode; 'use strict'; -/* removed: var _$color_411 = require('../components/color'); */; +/* removed: var _$color_473 = require('../components/color'); */; -var __noop_559 = function() {}; +var __noop_622 = function() {}; /** @@ -109328,9 +110166,9 @@ var __noop_559 = function() {}; * Expects 'scene' to have property 'container' * */ -var _$showWebGlMsg_559 = function showWebGlMsg(scene) { +var _$showWebGlMsg_622 = function showWebGlMsg(scene) { for(var prop in scene) { - if(typeof scene[prop] === 'function') scene[prop] = __noop_559; + if(typeof scene[prop] === 'function') scene[prop] = __noop_622; } scene.destroy = function() { @@ -109341,7 +110179,7 @@ var _$showWebGlMsg_559 = function showWebGlMsg(scene) { div.textContent = 'Webgl is not supported by your browser - visit http://get.webgl.org for more info'; div.style.cursor = 'pointer'; div.style.fontSize = '24px'; - div.style.color = _$color_411.defaults[0]; + div.style.color = _$color_473.defaults[0]; scene.container.appendChild(div); scene.container.style.background = '#FFFFFF'; @@ -109353,7 +110191,7 @@ var _$showWebGlMsg_559 = function showWebGlMsg(scene) { return false; }; -var _$mouse_264 = {}; +var _$mouse_322 = {}; 'use strict' function mouseButtons(ev) { @@ -109382,12 +110220,12 @@ function mouseButtons(ev) { } return 0 } -_$mouse_264.buttons = mouseButtons +_$mouse_322.buttons = mouseButtons function mouseElement(ev) { return ev.target || ev.srcElement || window } -_$mouse_264.element = mouseElement +_$mouse_322.element = mouseElement function mouseRelativeX(ev) { if(typeof ev === 'object') { @@ -109400,7 +110238,7 @@ function mouseRelativeX(ev) { } return 0 } -_$mouse_264.x = mouseRelativeX +_$mouse_322.x = mouseRelativeX function mouseRelativeY(ev) { if(typeof ev === 'object') { @@ -109413,13 +110251,13 @@ function mouseRelativeY(ev) { } return 0 } -_$mouse_264.y = mouseRelativeY +_$mouse_322.y = mouseRelativeY 'use strict' -var _$mouseListen_262 = mouseListen +var _$mouseListen_320 = mouseListen -/* removed: var _$mouse_264 = require('mouse-event') */; +/* removed: var _$mouse_322 = require('mouse-event') */; function mouseListen (element, callback) { if (!callback) { @@ -109460,8 +110298,8 @@ function mouseListen (element, callback) { } function handleEvent (nextButtons, ev) { - var nextX = _$mouse_264.x(ev) - var nextY = _$mouse_264.y(ev) + var nextX = _$mouse_322.x(ev) + var nextY = _$mouse_322.y(ev) if ('buttons' in ev) { nextButtons = ev.buttons | 0 } @@ -109502,7 +110340,7 @@ function mouseListen (element, callback) { } function handleMouseMove (ev) { - if (_$mouse_264.buttons(ev) === 0) { + if (_$mouse_322.buttons(ev) === 0) { handleEvent(0, ev) } else { handleEvent(buttonState, ev) @@ -109510,11 +110348,11 @@ function mouseListen (element, callback) { } function handleMouseDown (ev) { - handleEvent(buttonState | _$mouse_264.buttons(ev), ev) + handleEvent(buttonState | _$mouse_322.buttons(ev), ev) } function handleMouseUp (ev) { - handleEvent(buttonState & ~_$mouse_264.buttons(ev), ev) + handleEvent(buttonState & ~_$mouse_322.buttons(ev), ev) } function attachListeners () { @@ -109621,7 +110459,7 @@ function mouseListen (element, callback) { return result } -var _$parseUnit_287 = function parseUnit(str, out) { +var _$parseUnit_345 = function parseUnit(str, out) { if (!out) out = [ 0, '' ] @@ -109633,14 +110471,14 @@ var _$parseUnit_287 = function parseUnit(str, out) { } 'use strict' -/* removed: var _$parseUnit_287 = require('parse-unit') */; +/* removed: var _$parseUnit_345 = require('parse-unit') */; -var _$toPX_354 = toPX +var _$toPX_416 = toPX var PIXELS_PER_INCH = 96 function getPropertyInPX(element, prop) { - var parts = _$parseUnit_287(getComputedStyle(element).getPropertyValue(prop)) + var parts = _$parseUnit_345(getComputedStyle(element).getPropertyValue(prop)) return parts[0] * toPX(parts[1], element) } @@ -109693,9 +110531,9 @@ function toPX(str, element) { } 'use strict' -/* removed: var _$toPX_354 = require('to-px') */; +/* removed: var _$toPX_416 = require('to-px') */; -var _$mouseWheelListen_265 = mouseWheelListen +var _$mouseWheelListen_323 = mouseWheelListen function mouseWheelListen(element, callback, noScroll) { if(typeof element === 'function') { @@ -109703,7 +110541,7 @@ function mouseWheelListen(element, callback, noScroll) { callback = element element = window } - var lineHeight = _$toPX_354('ex', element) + var lineHeight = _$toPX_416('ex', element) var listener = function(ev) { if(noScroll) { ev.preventDefault() @@ -109743,13 +110581,13 @@ function mouseWheelListen(element, callback, noScroll) { 'use strict'; -/* removed: var _$mouseListen_262 = require('mouse-change'); */; -/* removed: var _$mouseWheelListen_265 = require('mouse-wheel'); */; -/* removed: var _$mouseEventOffset_263 = require('mouse-event-offset'); */; -/* removed: var _$constants_589 = require('../cartesian/constants'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; +/* removed: var _$mouseListen_320 = require('mouse-change'); */; +/* removed: var _$mouseWheelListen_323 = require('mouse-wheel'); */; +/* removed: var _$mouseEventOffset_321 = require('mouse-event-offset'); */; +/* removed: var _$constants_652 = require('../cartesian/constants'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; -var _$createCamera_622 = createCamera; +var _$createCamera_684 = createCamera; function Camera2D(element, plot) { this.element = element; @@ -109791,28 +110629,28 @@ function createCamera(scene) { return false; } - result.mouseListener = _$mouseListen_262(element, handleInteraction); + result.mouseListener = _$mouseListen_320(element, handleInteraction); // enable simple touch interactions element.addEventListener('touchstart', function(ev) { - var xy = _$mouseEventOffset_263(ev.changedTouches[0], element); + var xy = _$mouseEventOffset_321(ev.changedTouches[0], element); handleInteraction(0, xy[0], xy[1]); handleInteraction(1, xy[0], xy[1]); ev.preventDefault(); - }, _$hasPassiveEvents_240 ? {passive: false} : false); + }, _$hasPassiveEvents_297 ? {passive: false} : false); element.addEventListener('touchmove', function(ev) { ev.preventDefault(); - var xy = _$mouseEventOffset_263(ev.changedTouches[0], element); + var xy = _$mouseEventOffset_321(ev.changedTouches[0], element); handleInteraction(1, xy[0], xy[1]); ev.preventDefault(); - }, _$hasPassiveEvents_240 ? {passive: false} : false); + }, _$hasPassiveEvents_297 ? {passive: false} : false); element.addEventListener('touchend', function(ev) { handleInteraction(0, result.lastPos[0], result.lastPos[1]); ev.preventDefault(); - }, _$hasPassiveEvents_240 ? {passive: false} : false); + }, _$hasPassiveEvents_297 ? {passive: false} : false); function handleInteraction(buttons, x, y) { var dataBox = scene.calcDataBox(), @@ -109821,8 +110659,8 @@ function createCamera(scene) { var lastX = result.lastPos[0], lastY = result.lastPos[1]; - var MINDRAG = _$constants_589.MINDRAG * plot.pixelRatio; - var MINZOOM = _$constants_589.MINZOOM * plot.pixelRatio; + var MINDRAG = _$constants_652.MINDRAG * plot.pixelRatio; + var MINZOOM = _$constants_652.MINZOOM * plot.pixelRatio; var dx, dy; @@ -109996,7 +110834,7 @@ function createCamera(scene) { result.lastPos[1] = y; } - result.wheelListener = _$mouseWheelListen_265(element, function(dx, dy) { + result.wheelListener = _$mouseWheelListen_323(element, function(dx, dy) { if(!scene.scrollZoom) return false; var dataBox = scene.calcDataBox(), @@ -110033,7 +110871,7 @@ function createCamera(scene) { return result; } -var _$clamp_94 = clamp +var _$clamp_95 = clamp function clamp(value, min, max) { return min < max @@ -110043,7 +110881,7 @@ function clamp(value, min, max) { 'use strict' -var _$colorName_98 = { +var _$colorName_99 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], @@ -110194,21 +111032,21 @@ var _$colorName_98 = { "yellowgreen": [154, 205, 50] }; -var _$defined_128 = function () { +var _$defined_131 = function () { for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) return arguments[i]; } }; 'use strict'; -var __toString_250 = Object.prototype.toString; +var __toString_308 = Object.prototype.toString; -var _$isPlainObj_250 = function (x) { +var _$isPlainObj_308 = function (x) { var prototype; - return __toString_250.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); + return __toString_308.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); }; -var _$parse_100 = {}; +var _$parse_101 = {}; (function (global){ /** * @module color-parse @@ -110216,11 +111054,11 @@ var _$parse_100 = {}; 'use strict' -/* removed: var _$colorName_98 = require('color-name') */; -/* removed: var _$isPlainObj_250 = require('is-plain-obj') */; -/* removed: var _$defined_128 = require('defined') */; +/* removed: var _$colorName_99 = require('color-name') */; +/* removed: var _$isPlainObj_308 = require('is-plain-obj') */; +/* removed: var _$defined_131 = require('defined') */; -_$parse_100 = parse +_$parse_101 = parse /** * Base hues @@ -110246,8 +111084,8 @@ function parse (cstr) { if (typeof cstr === 'string') { //keyword - if (_$colorName_98[cstr]) { - parts = _$colorName_98[cstr].slice() + if (_$colorName_99[cstr]) { + parts = _$colorName_99[cstr].slice() space = 'rgb' } @@ -110346,27 +111184,27 @@ function parse (cstr) { } //object case - detects css cases of rgb and hsl - else if (_$isPlainObj_250(cstr)) { - var r = _$defined_128(cstr.r, cstr.red, cstr.R, null) + else if (_$isPlainObj_308(cstr)) { + var r = _$defined_131(cstr.r, cstr.red, cstr.R, null) if (r !== null) { space = 'rgb' parts = [ r, - _$defined_128(cstr.g, cstr.green, cstr.G), - _$defined_128(cstr.b, cstr.blue, cstr.B) + _$defined_131(cstr.g, cstr.green, cstr.G), + _$defined_131(cstr.b, cstr.blue, cstr.B) ] } else { space = 'hsl' parts = [ - _$defined_128(cstr.h, cstr.hue, cstr.H), - _$defined_128(cstr.s, cstr.saturation, cstr.S), - _$defined_128(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness) + _$defined_131(cstr.h, cstr.hue, cstr.H), + _$defined_131(cstr.s, cstr.saturation, cstr.S), + _$defined_131(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness) ] } - alpha = _$defined_128(cstr.a, cstr.alpha, cstr.opacity, 1) + alpha = _$defined_131(cstr.a, cstr.alpha, cstr.opacity, 1) if (cstr.opacity != null) alpha /= 100 } @@ -110393,7 +111231,7 @@ function parse (cstr) { */ 'use strict' -var _$rgb_103 = { +var _$rgb_104 = { name: 'rgb', min: [0,0,0], max: [255,255,255], @@ -110406,9 +111244,9 @@ var _$rgb_103 = { */ 'use strict' -/* removed: var _$rgb_103 = require('./rgb'); */; +/* removed: var _$rgb_104 = require('./rgb'); */; -var _$hsl_102 = { +var _$hsl_103 = { name: 'hsl', min: [0,0,0], max: [360,100,100], @@ -110466,7 +111304,7 @@ var _$hsl_102 = { //extend rgb -_$rgb_103.hsl = function(rgb) { +_$rgb_104.hsl = function(rgb) { var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255, @@ -110513,35 +111351,35 @@ _$rgb_103.hsl = function(rgb) { 'use strict' -/* removed: var _$parse_100 = require('color-parse') */; -/* removed: var _$hsl_102 = require('color-space/hsl') */; -/* removed: var _$clamp_94 = require('clamp') */; +/* removed: var _$parse_101 = require('color-parse') */; +/* removed: var _$hsl_103 = require('color-space/hsl') */; +/* removed: var _$clamp_95 = require('clamp') */; -var _$rgba_101 = function rgba (color) { +var _$rgba_102 = function rgba (color) { var values, i, l if (typeof color !== 'string') throw Error('Argument should be a string') //attempt to parse non-array arguments - var parsed = _$parse_100(color) + var parsed = _$parse_101(color) if (!parsed.space) return [] values = Array(3) - values[0] = _$clamp_94(parsed.values[0], 0, 255) - values[1] = _$clamp_94(parsed.values[1], 0, 255) - values[2] = _$clamp_94(parsed.values[2], 0, 255) + values[0] = _$clamp_95(parsed.values[0], 0, 255) + values[1] = _$clamp_95(parsed.values[1], 0, 255) + values[2] = _$clamp_95(parsed.values[2], 0, 255) if (parsed.space[0] === 'h') { - values = _$hsl_102.rgb(values) + values = _$hsl_103.rgb(values) } - values.push(_$clamp_94(parsed.alpha, 0, 1)) + values.push(_$clamp_95(parsed.alpha, 0, 1)) return values } -var _$dtype_132 = function(dtype) { +var _$dtype_135 = function(dtype) { switch (dtype) { case 'int8': return Int8Array @@ -110570,15 +111408,15 @@ var _$dtype_132 = function(dtype) { 'use strict' -/* removed: var _$rgba_101 = require('color-rgba') */; -/* removed: var _$clamp_94 = require('clamp') */; -/* removed: var _$dtype_132 = require('dtype') */; +/* removed: var _$rgba_102 = require('color-rgba') */; +/* removed: var _$clamp_95 = require('clamp') */; +/* removed: var _$dtype_135 = require('dtype') */; -var _$normalize_99 = function normalize (color, type) { +var _$normalize_100 = 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_132(type) + var Ctor = _$dtype_135(type) var output = new Ctor(4) //same class does not change values @@ -110612,7 +111450,7 @@ var _$normalize_99 = function normalize (color, type) { //attempt to parse non-array arguments if (!color.length || typeof color === 'string') { - color = _$rgba_101(color) + color = _$rgba_102(color) color[0] /= 255 color[1] /= 255 color[2] /= 255 @@ -110620,10 +111458,10 @@ var _$normalize_99 = function normalize (color, type) { //consider every other array type as 0..1 float values if (!normalize) { - output[0] = _$clamp_94(Math.round(color[0] * 255), 0, 255) - output[1] = _$clamp_94(Math.round(color[1] * 255), 0, 255) - output[2] = _$clamp_94(Math.round(color[2] * 255), 0, 255) - output[3] = color[3] == null ? 255 : _$clamp_94(Math.floor(color[3] * 255), 0, 255) + output[0] = _$clamp_95(Math.round(color[0] * 255), 0, 255) + output[1] = _$clamp_95(Math.round(color[1] * 255), 0, 255) + output[2] = _$clamp_95(Math.round(color[2] * 255), 0, 255) + output[3] = color[3] == null ? 255 : _$clamp_95(Math.floor(color[3] * 255), 0, 255) } else { output[0] = color[0] output[1] = color[1] @@ -110645,14 +111483,14 @@ var _$normalize_99 = function normalize (color, type) { 'use strict'; -/* removed: var _$normalize_99 = require('color-normalize'); */; +/* removed: var _$normalize_100 = require('color-normalize'); */; function str2RgbaArray(color) { if(!color) return [0, 0, 0, 1]; - return _$normalize_99(color); + return _$normalize_100(color); } -var _$str2RgbaArray_561 = str2RgbaArray; +var _$str2RgbaArray_624 = str2RgbaArray; /** * Copyright 2012-2018, Plotly, Inc. @@ -110665,10 +111503,10 @@ var _$str2RgbaArray_561 = str2RgbaArray; 'use strict'; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; -/* removed: var _$convertHTMLToUnicode_537 = require('../../lib/html2unicode'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../lib/html2unicode'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; function Axes2DOptions(scene) { this.scene = scene; @@ -110748,15 +111586,15 @@ function Axes2DOptions(scene) { this.static = this.scene.staticPlot; } -var __proto_623 = Axes2DOptions.prototype; +var __proto_685 = Axes2DOptions.prototype; var AXES = ['xaxis', 'yaxis']; -__proto_623.merge = function(options) { +__proto_685.merge = function(options) { // titles are rendered in SVG this.titleEnable = false; - this.backgroundColor = _$str2RgbaArray_561(options.plot_bgcolor); + this.backgroundColor = _$str2RgbaArray_624(options.plot_bgcolor); var axisName, ax, axTitle, axMirror; var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks; @@ -110774,14 +111612,14 @@ __proto_623.merge = function(options) { for(j = 0; j <= 2; j += 2) { this.labelEnable[i + j] = false; - this.labels[i + j] = _$convertHTMLToUnicode_537(axTitle); - this.labelColor[i + j] = _$str2RgbaArray_561(ax.titlefont.color); + this.labels[i + j] = _$convertHTMLToUnicode_599(axTitle); + this.labelColor[i + j] = _$str2RgbaArray_624(ax.titlefont.color); this.labelFont[i + j] = ax.titlefont.family; this.labelSize[i + j] = ax.titlefont.size; this.labelPad[i + j] = this.getLabelPad(axisName, ax); this.tickEnable[i + j] = false; - this.tickColor[i + j] = _$str2RgbaArray_561((ax.tickfont || {}).color); + this.tickColor[i + j] = _$str2RgbaArray_624((ax.tickfont || {}).color); this.tickAngle[i + j] = (ax.tickangle === 'auto') ? 0 : Math.PI * -ax.tickangle / 180; @@ -110789,10 +111627,10 @@ __proto_623.merge = function(options) { this.tickMarkLength[i + j] = 0; this.tickMarkWidth[i + j] = ax.tickwidth || 0; - this.tickMarkColor[i + j] = _$str2RgbaArray_561(ax.tickcolor); + this.tickMarkColor[i + j] = _$str2RgbaArray_624(ax.tickcolor); this.borderLineEnable[i + j] = false; - this.borderLineColor[i + j] = _$str2RgbaArray_561(ax.linecolor); + this.borderLineColor[i + j] = _$str2RgbaArray_624(ax.linecolor); this.borderLineWidth[i + j] = ax.linewidth || 0; } @@ -110827,20 +111665,20 @@ __proto_623.merge = function(options) { if(hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i + 2] = this.getTickMarkLength(ax); this.gridLineEnable[i] = ax.showgrid; - this.gridLineColor[i] = _$str2RgbaArray_561(ax.gridcolor); + this.gridLineColor[i] = _$str2RgbaArray_624(ax.gridcolor); this.gridLineWidth[i] = ax.gridwidth; this.zeroLineEnable[i] = ax.zeroline; - this.zeroLineColor[i] = _$str2RgbaArray_561(ax.zerolinecolor); + this.zeroLineColor[i] = _$str2RgbaArray_624(ax.zerolinecolor); this.zeroLineWidth[i] = ax.zerolinewidth; } }; // is an axis shared with an already-drawn subplot ? -__proto_623.hasSharedAxis = function(ax) { +__proto_685.hasSharedAxis = function(ax) { var scene = this.scene; var subplotIds = scene.fullLayout._subplots.gl2d; - var list = _$axes_584.findSubplotsWithAxis(subplotIds, ax); + var list = _$axes_647.findSubplotsWithAxis(subplotIds, ax); // if index === 0, then the subplot is already drawn as subplots // are drawn in order. @@ -110848,7 +111686,7 @@ __proto_623.hasSharedAxis = function(ax) { }; // has an axis in default position (i.e. bottom/left) ? -__proto_623.hasAxisInDfltPos = function(axisName, ax) { +__proto_685.hasAxisInDfltPos = function(axisName, ax) { var axSide = ax.side; if(axisName === 'xaxis') return (axSide === 'bottom'); @@ -110856,14 +111694,14 @@ __proto_623.hasAxisInDfltPos = function(axisName, ax) { }; // has an axis in alternate position (i.e. top/right) ? -__proto_623.hasAxisInAltrPos = function(axisName, ax) { +__proto_685.hasAxisInAltrPos = function(axisName, ax) { var axSide = ax.side; if(axisName === 'xaxis') return (axSide === 'top'); else if(axisName === 'yaxis') return (axSide === 'right'); }; -__proto_623.getLabelPad = function(axisName, ax) { +__proto_685.getLabelPad = function(axisName, ax) { var offsetBase = 1.5, fontSize = ax.titlefont.size, showticklabels = ax.showticklabels; @@ -110880,11 +111718,11 @@ __proto_623.getLabelPad = function(axisName, ax) { } }; -__proto_623.getTickPad = function(ax) { +__proto_685.getTickPad = function(ax) { return (ax.ticks === 'outside') ? 10 + ax.ticklen : 15; }; -__proto_623.getTickMarkLength = function(ax) { +__proto_685.getTickMarkLength = function(ax) { if(!ax.ticks) return 0; var ticklen = ax.ticklen; @@ -110897,7 +111735,7 @@ function createAxes2D(scene) { return new Axes2DOptions(scene); } -var _$createAxes2D_623 = createAxes2D; +var _$createAxes2D_685 = createAxes2D; /** * Copyright 2012-2018, Plotly, Inc. @@ -110910,28 +111748,28 @@ var _$createAxes2D_623 = createAxes2D; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; -/* removed: var _$createGLPlot2D_194 = require('gl-plot2d'); */; -/* removed: var _$createSpikes2D_213 = require('gl-spikes2d'); */; -/* removed: var _$createSelectBox_204 = require('gl-select-box'); */; -/* removed: var _$getWebGLContext_373 = require('webgl-context'); */; +/* removed: var _$createGLPlot2D_251 = require('gl-plot2d'); */; +/* removed: var _$createSpikes2D_270 = require('gl-spikes2d'); */; +/* removed: var _$createSelectBox_261 = require('gl-select-box'); */; +/* removed: var _$getWebGLContext_435 = require('webgl-context'); */; -/* removed: var _$createAxes2D_623 = require('./convert'); */; -/* removed: var _$createCamera_622 = require('./camera'); */; -/* removed: var _$convertHTMLToUnicode_537 = require('../../lib/html2unicode'); */; -/* removed: var _$showWebGlMsg_559 = require('../../lib/show_no_webgl_msg'); */; -/* removed: var _$constraints_591 = require('../cartesian/constraints'); */; -var __enforceAxisConstraints_625 = _$constraints_591.enforce; -var __cleanAxisConstraints_625 = _$constraints_591.clean; -var __doAutoRange_625 = _$autorange_583.doAutoRange; +/* removed: var _$createAxes2D_685 = require('./convert'); */; +/* removed: var _$createCamera_684 = require('./camera'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../lib/html2unicode'); */; +/* removed: var _$showWebGlMsg_622 = require('../../lib/show_no_webgl_msg'); */; +/* removed: var _$constraints_654 = require('../cartesian/constraints'); */; +var __enforceAxisConstraints_687 = _$constraints_654.enforce; +var __cleanAxisConstraints_687 = _$constraints_654.clean; +var __doAutoRange_687 = _$autorange_646.doAutoRange; -var __AXES_625 = ['xaxis', 'yaxis']; +var __AXES_687 = ['xaxis', 'yaxis']; var STATIC_CANVAS, STATIC_CONTEXT; -var __SUBPLOT_PATTERN_625 = _$constants_589.SUBPLOT_PATTERN; +var __SUBPLOT_PATTERN_687 = _$constants_652.SUBPLOT_PATTERN; function Scene2D(options, fullLayout) { @@ -110948,22 +111786,22 @@ function Scene2D(options, fullLayout) { this.makeFramework(); // update options - this.glplotOptions = _$createAxes2D_623(this); + this.glplotOptions = _$createAxes2D_685(this); this.glplotOptions.merge(fullLayout); // create the plot - this.glplot = _$createGLPlot2D_194(this.glplotOptions); + this.glplot = _$createGLPlot2D_251(this.glplotOptions); // create camera - this.camera = _$createCamera_622(this); + this.camera = _$createCamera_684(this); // trace set this.traces = {}; // create axes spikes - this.spikes = _$createSpikes2D_213(this.glplot); + this.spikes = _$createSpikes2D_270(this.glplot); - this.selectBox = _$createSelectBox_204(this.glplot, { + this.selectBox = _$createSelectBox_261(this.glplot, { innerFill: false, outerFill: true }); @@ -110987,18 +111825,18 @@ function Scene2D(options, fullLayout) { this.redraw(); } -var _$Scene2D_625 = Scene2D; +var _$Scene2D_687 = Scene2D; -var __proto_625 = Scene2D.prototype; +var __proto_687 = Scene2D.prototype; -__proto_625.makeFramework = function() { +__proto_687.makeFramework = function() { // create canvas and gl context if(this.staticPlot) { if(!STATIC_CONTEXT) { STATIC_CANVAS = document.createElement('canvas'); - STATIC_CONTEXT = _$getWebGLContext_373({ + STATIC_CONTEXT = _$getWebGLContext_435({ canvas: STATIC_CANVAS, preserveDrawingBuffer: false, premultipliedAlpha: true, @@ -111016,13 +111854,13 @@ __proto_625.makeFramework = function() { else { var liveCanvas = this.container.querySelector('.gl-canvas-focus'); - var gl = _$getWebGLContext_373({ + var gl = _$getWebGLContext_435({ canvas: liveCanvas, preserveDrawingBuffer: true, premultipliedAlpha: true }); - if(!gl) _$showWebGlMsg_559(this); + if(!gl) _$showWebGlMsg_622(this); this.canvas = liveCanvas; this.gl = gl; @@ -111078,7 +111916,7 @@ __proto_625.makeFramework = function() { }); }; -__proto_625.toImage = function(format) { +__proto_687.toImage = function(format) { if(!format) format = 'png'; this.stopped = true; @@ -111143,7 +111981,7 @@ __proto_625.toImage = function(format) { return dataURL; }; -__proto_625.updateSize = function(canvas) { +__proto_687.updateSize = function(canvas) { if(!canvas) canvas = this.canvas; var pixelRatio = this.pixelRatio, @@ -111163,26 +112001,26 @@ __proto_625.updateSize = function(canvas) { return canvas; }; -__proto_625.computeTickMarks = function() { +__proto_687.computeTickMarks = function() { this.xaxis.setScale(); this.yaxis.setScale(); var nextTicks = [ - _$axes_584.calcTicks(this.xaxis), - _$axes_584.calcTicks(this.yaxis) + _$axes_647.calcTicks(this.xaxis), + _$axes_647.calcTicks(this.yaxis) ]; for(var j = 0; j < 2; ++j) { for(var i = 0; i < nextTicks[j].length; ++i) { // coercing tick value (may not be a string) to a string - nextTicks[j][i].text = _$convertHTMLToUnicode_537(nextTicks[j][i].text + ''); + nextTicks[j][i].text = _$convertHTMLToUnicode_599(nextTicks[j][i].text + ''); } } return nextTicks; }; -function __compareTicks_625(a, b) { +function __compareTicks_687(a, b) { for(var i = 0; i < 2; ++i) { var aticks = a[i], bticks = b[i]; @@ -111197,10 +112035,10 @@ function __compareTicks_625(a, b) { return false; } -__proto_625.updateRefs = function(newFullLayout) { +__proto_687.updateRefs = function(newFullLayout) { this.fullLayout = newFullLayout; - var spmatch = this.id.match(__SUBPLOT_PATTERN_625); + var spmatch = this.id.match(__SUBPLOT_PATTERN_687); var xaxisName = 'xaxis' + spmatch[1]; var yaxisName = 'yaxis' + spmatch[2]; @@ -111208,7 +112046,7 @@ __proto_625.updateRefs = function(newFullLayout) { this.yaxis = this.fullLayout[yaxisName]; }; -__proto_625.relayoutCallback = function() { +__proto_687.relayoutCallback = function() { var graphDiv = this.graphDiv, xaxis = this.xaxis, yaxis = this.yaxis, @@ -111233,7 +112071,7 @@ __proto_625.relayoutCallback = function() { graphDiv.emit('plotly_relayout', update); }; -__proto_625.cameraChanged = function() { +__proto_687.cameraChanged = function() { var camera = this.camera; this.glplot.setDataBox(this.calcDataBox()); @@ -111241,7 +112079,7 @@ __proto_625.cameraChanged = function() { var nextTicks = this.computeTickMarks(); var curTicks = this.glplotOptions.ticks; - if(__compareTicks_625(nextTicks, curTicks)) { + if(__compareTicks_687(nextTicks, curTicks)) { this.glplotOptions.ticks = nextTicks; this.glplotOptions.dataBox = camera.dataBox; this.glplot.update(this.glplotOptions); @@ -111249,7 +112087,7 @@ __proto_625.cameraChanged = function() { } }; -__proto_625.handleAnnotations = function() { +__proto_687.handleAnnotations = function() { var gd = this.graphDiv, annotations = this.fullLayout.annotations; @@ -111257,12 +112095,12 @@ __proto_625.handleAnnotations = function() { var ann = annotations[i]; if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) { - _$registry_668.getComponentMethod('annotations', 'drawOne')(gd, i); + _$registry_731.getComponentMethod('annotations', 'drawOne')(gd, i); } } }; -__proto_625.destroy = function() { +__proto_687.destroy = function() { if(!this.glplot) return; var traces = this.traces; @@ -111287,7 +112125,7 @@ __proto_625.destroy = function() { this.camera = null; }; -__proto_625.plot = function(fullData, calcData, fullLayout) { +__proto_687.plot = function(fullData, calcData, fullLayout) { var glplot = this.glplot; this.updateRefs(fullLayout); @@ -111311,8 +112149,8 @@ __proto_625.plot = function(fullData, calcData, fullLayout) { yaxis: this.yaxis }}; - __cleanAxisConstraints_625(mockGraphDiv, this.xaxis); - __cleanAxisConstraints_625(mockGraphDiv, this.yaxis); + __cleanAxisConstraints_687(mockGraphDiv, this.xaxis); + __cleanAxisConstraints_687(mockGraphDiv, this.yaxis); var size = fullLayout._size, domainX = this.xaxis.domain, @@ -111334,14 +112172,14 @@ __proto_625.plot = function(fullData, calcData, fullLayout) { var ax, i; for(i = 0; i < 2; ++i) { - ax = this[__AXES_625[i]]; + ax = this[__AXES_687[i]]; ax._length = options.viewBox[i + 2] - options.viewBox[i]; - __doAutoRange_625(ax); + __doAutoRange_687(ax); ax.setScale(); } - __enforceAxisConstraints_625(mockGraphDiv); + __enforceAxisConstraints_687(mockGraphDiv); options.ticks = this.computeTickMarks(); @@ -111354,7 +112192,7 @@ __proto_625.plot = function(fullData, calcData, fullLayout) { this.glplot.draw(); }; -__proto_625.calcDataBox = function() { +__proto_687.calcDataBox = function() { var xaxis = this.xaxis, yaxis = this.yaxis, xrange = xaxis.range, @@ -111365,7 +112203,7 @@ __proto_625.calcDataBox = function() { return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])]; }; -__proto_625.setRanges = function(dataBox) { +__proto_687.setRanges = function(dataBox) { var xaxis = this.xaxis, yaxis = this.yaxis, xl2r = xaxis.l2r, @@ -111375,7 +112213,7 @@ __proto_625.setRanges = function(dataBox) { yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])]; }; -__proto_625.updateTraces = function(fullData, calcData) { +__proto_687.updateTraces = function(fullData, calcData) { var traceIds = Object.keys(this.traces); var i, j, fullTrace; @@ -111418,7 +112256,7 @@ __proto_625.updateTraces = function(fullData, calcData) { }); }; -__proto_625.updateFx = function(dragmode) { +__proto_687.updateFx = function(dragmode) { // switch to svg interactions in lasso/select mode if(dragmode === 'lasso' || dragmode === 'select') { this.pickCanvas.style['pointer-events'] = 'none'; @@ -111440,7 +112278,7 @@ __proto_625.updateFx = function(dragmode) { } }; -__proto_625.emitPointAction = function(nextSelection, eventType) { +__proto_687.emitPointAction = function(nextSelection, eventType) { var uid = nextSelection.trace.uid; var ptNumber = nextSelection.pointIndex; var trace; @@ -111462,12 +112300,12 @@ __proto_625.emitPointAction = function(nextSelection, eventType) { yaxis: this.yaxis }; - _$fx_453.appendArrayPointValue(pointData, trace, ptNumber); + _$fx_515.appendArrayPointValue(pointData, trace, ptNumber); this.graphDiv.emit(eventType, {points: [pointData]}); }; -__proto_625.draw = function() { +__proto_687.draw = function() { if(this.stopped) return; requestAnimationFrame(this.redraw); @@ -111558,7 +112396,7 @@ __proto_625.draw = function() { var trace = this.fullData[selection.trace.index] || {}; var ptNumber = selection.pointIndex; - var hoverinfo = _$fx_453.castHoverinfo(trace, fullLayout, ptNumber); + var hoverinfo = _$fx_515.castHoverinfo(trace, fullLayout, ptNumber); if(hoverinfo && hoverinfo !== 'all') { var parts = hoverinfo.split('+'); @@ -111569,7 +112407,7 @@ __proto_625.draw = function() { if(parts.indexOf('name') === -1) selection.name = undefined; } - _$fx_453.loneHover({ + _$fx_515.loneHover({ x: selection.screenCoord[0], y: selection.screenCoord[1], xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]), @@ -111577,11 +112415,11 @@ __proto_625.draw = function() { zLabel: selection.traceCoord[2], text: selection.textLabel, name: selection.name, - color: _$fx_453.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color, - borderColor: _$fx_453.castHoverOption(trace, ptNumber, 'bordercolor'), - fontFamily: _$fx_453.castHoverOption(trace, ptNumber, 'font.family'), - fontSize: _$fx_453.castHoverOption(trace, ptNumber, 'font.size'), - fontColor: _$fx_453.castHoverOption(trace, ptNumber, 'font.color') + color: _$fx_515.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color, + borderColor: _$fx_515.castHoverOption(trace, ptNumber, 'bordercolor'), + fontFamily: _$fx_515.castHoverOption(trace, ptNumber, 'font.family'), + fontSize: _$fx_515.castHoverOption(trace, ptNumber, 'font.size'), + fontColor: _$fx_515.castHoverOption(trace, ptNumber, 'font.color') }, { container: this.svgContainer, gd: this.graphDiv @@ -111599,23 +112437,23 @@ __proto_625.draw = function() { glplot.draw(); }; -__proto_625.unhover = function() { +__proto_687.unhover = function() { if(this.lastPickResult) { this.spikes.update({}); this.lastPickResult = null; this.graphDiv.emit('plotly_unhover'); - _$fx_453.loneUnhover(this.svgContainer); + _$fx_515.loneUnhover(this.svgContainer); } }; -__proto_625.hoverFormatter = function(axisName, val) { +__proto_687.hoverFormatter = function(axisName, val) { if(val === undefined) return undefined; var axis = this[axisName]; - return _$axes_584.tickText(axis, axis.c2l(val), 'hover').text; + return _$axes_647.tickText(axis, axis.c2l(val), 'hover').text; }; -var _$gl2d_624 = {}; +var _$gl2d_686 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -111627,31 +112465,31 @@ var _$gl2d_624 = {}; 'use strict'; -var __overrideAll_624 = _$edit_types_569.overrideAll; +var __overrideAll_686 = _$edit_types_632.overrideAll; -/* removed: var _$Scene2D_625 = require('./scene2d'); */; -/* removed: var _$layout_attributes_638 = require('../layout_attributes'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$constants_589 = require('../cartesian/constants'); */; -/* removed: var _$cartesian_595 = require('../cartesian'); */; -/* removed: var _$layout_attributes_454 = require('../../components/fx/layout_attributes'); */; -var getSubplotData = _$get_data_621.getSubplotData; +/* removed: var _$Scene2D_687 = require('./scene2d'); */; +/* removed: var _$layout_attributes_700 = require('../layout_attributes'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$constants_652 = require('../cartesian/constants'); */; +/* removed: var _$cartesian_658 = require('../cartesian'); */; +/* removed: var _$layout_attributes_516 = require('../../components/fx/layout_attributes'); */; +var getSubplotData = _$get_data_683.getSubplotData; -_$gl2d_624.name = 'gl2d'; +_$gl2d_686.name = 'gl2d'; -_$gl2d_624.attr = ['xaxis', 'yaxis']; +_$gl2d_686.attr = ['xaxis', 'yaxis']; -_$gl2d_624.idRoot = ['x', 'y']; +_$gl2d_686.idRoot = ['x', 'y']; -_$gl2d_624.idRegex = _$constants_589.idRegex; +_$gl2d_686.idRegex = _$constants_652.idRegex; -_$gl2d_624.attrRegex = _$constants_589.attrRegex; +_$gl2d_686.attrRegex = _$constants_652.attrRegex; -_$gl2d_624.attributes = _$attributes_582; +_$gl2d_686.attributes = _$attributes_645; -_$gl2d_624.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { +_$gl2d_686.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { if(!layoutOut._has('cartesian')) { - _$cartesian_595.supplyLayoutDefaults(layoutIn, layoutOut, fullData); + _$cartesian_658.supplyLayoutDefaults(layoutIn, layoutOut, fullData); } }; @@ -111659,18 +112497,18 @@ _$gl2d_624.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { // 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 -_$gl2d_624.layoutAttrOverrides = __overrideAll_624(_$cartesian_595.layoutAttributes, 'plot', 'from-root'); +_$gl2d_686.layoutAttrOverrides = __overrideAll_686(_$cartesian_658.layoutAttributes, 'plot', 'from-root'); // similar overrides for base plot attributes (and those added by components) -_$gl2d_624.baseLayoutAttrOverrides = __overrideAll_624({ - plot_bgcolor: _$layout_attributes_638.plot_bgcolor, - hoverlabel: _$layout_attributes_454.hoverlabel +_$gl2d_686.baseLayoutAttrOverrides = __overrideAll_686({ + plot_bgcolor: _$layout_attributes_700.plot_bgcolor, + hoverlabel: _$layout_attributes_516.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'); -_$gl2d_624.plot = function plotGl2d(gd) { +_$gl2d_686.plot = function plotGl2d(gd) { var fullLayout = gd._fullLayout; var fullData = gd._fullData; var subplotIds = fullLayout._subplots.gl2d; @@ -111685,7 +112523,7 @@ _$gl2d_624.plot = function plotGl2d(gd) { // If Scene is not instantiated, create one! if(scene === undefined) { - scene = new _$Scene2D_625({ + scene = new _$Scene2D_687({ id: subplotId, graphDiv: gd, container: gd.querySelector('.gl-container'), @@ -111703,7 +112541,7 @@ _$gl2d_624.plot = function plotGl2d(gd) { } }; -_$gl2d_624.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$gl2d_686.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldSceneKeys = oldFullLayout._subplots.gl2d || []; for(var i = 0; i < oldSceneKeys.length; i++) { @@ -111722,16 +112560,16 @@ _$gl2d_624.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayo } // since we use cartesian interactions, do cartesian clean - _$cartesian_595.clean.apply(this, arguments); + _$cartesian_658.clean.apply(this, arguments); }; -_$gl2d_624.drawFramework = function(gd) { +_$gl2d_686.drawFramework = function(gd) { if(!gd._context.staticPlot) { - _$cartesian_595.drawFramework(gd); + _$cartesian_658.drawFramework(gd); } }; -_$gl2d_624.toSVG = function(gd) { +_$gl2d_686.toSVG = function(gd) { var fullLayout = gd._fullLayout; var subplotIds = fullLayout._subplots.gl2d; @@ -111743,7 +112581,7 @@ _$gl2d_624.toSVG = function(gd) { var image = fullLayout._glimages.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, x: 0, y: 0, @@ -111756,7 +112594,7 @@ _$gl2d_624.toSVG = function(gd) { } }; -_$gl2d_624.updateFx = function(fullLayout) { +_$gl2d_686.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots.gl2d; for(var i = 0; i < subplotIds.length; i++) { @@ -111776,12 +112614,12 @@ _$gl2d_624.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_790 = _$extend_528.extendFlat; -var __overrideAll_790 = _$edit_types_569.overrideAll; +var __extendFlat_852 = _$extend_590.extendFlat; +var __overrideAll_852 = _$edit_types_632.overrideAll; var commonList = [ @@ -111792,36 +112630,36 @@ var commonList = [ 'xtype', 'ytype' ]; -var __attrs_790 = {}; +var __attrs_852 = {}; -for(var __i_790 = 0; __i_790 < commonList.length; __i_790++) { - var k = commonList[__i_790]; - __attrs_790[k] = _$attributes_773[k]; +for(var __i_852 = 0; __i_852 < commonList.length; __i_852++) { + var k = commonList[__i_852]; + __attrs_852[k] = _$attributes_835[k]; } -__extendFlat_790( - __attrs_790, - _$attributes_417, - { autocolorscale: __extendFlat_790({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } +__extendFlat_852( + __attrs_852, + _$attributes_479, + { autocolorscale: __extendFlat_852({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); -var _$attributes_790 = __overrideAll_790(__attrs_790, 'calc', 'nested'); +var _$attributes_852 = __overrideAll_852(__attrs_852, 'calc', 'nested'); 'use strict' -/* removed: var _$browser_238 = require('glslify') */; +/* removed: var _$browser_295 = require('glslify') */; -var _$shaders_161 = { - fragment: _$browser_238(["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: _$browser_238(["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: _$browser_238(["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: _$browser_238(["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"]) +var _$shaders_218 = { + fragment: _$browser_295(["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: _$browser_295(["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: _$browser_295(["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: _$browser_295(["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"]) } "use strict" -function __compileSearch_162(funcName, predicate, reversed, extraArgs, earlyOut) { +function __compileSearch_219(funcName, predicate, reversed, extraArgs, earlyOut) { var code = [ "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), @@ -111849,10 +112687,10 @@ function __compileSearch_162(funcName, predicate, reversed, extraArgs, earlyOut) return code.join("") } -function __compileBoundsSearch_162(predicate, reversed, suffix, earlyOut) { +function __compileBoundsSearch_219(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_162("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_162("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), + __compileSearch_219("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_219("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), "function dispatchBsearch", suffix, "(a,y,c,l,h){\ if(typeof(c)==='function'){\ return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ @@ -111863,25 +112701,25 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_162 = { - ge: __compileBoundsSearch_162(">=", false, "GE"), - gt: __compileBoundsSearch_162(">", false, "GT"), - lt: __compileBoundsSearch_162("<", true, "LT"), - le: __compileBoundsSearch_162("<=", true, "LE"), - eq: __compileBoundsSearch_162("-", true, "EQ", true) +var _$searchBounds_219 = { + ge: __compileBoundsSearch_219(">=", false, "GE"), + gt: __compileBoundsSearch_219(">", false, "GT"), + lt: __compileBoundsSearch_219("<", true, "LT"), + le: __compileBoundsSearch_219("<=", true, "LE"), + eq: __compileBoundsSearch_219("-", true, "EQ", true) } 'use strict' -var _$createHeatmap2D_160 = createHeatmap2D +var _$createHeatmap2D_217 = createHeatmap2D -/* removed: var _$searchBounds_162 = require('binary-search-bounds') */; -/* removed: var _$iota_245 = require('iota-array') */; -/* removed: var _$pool_360 = require('typedarray-pool') */; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$createBuffer_153 = require('gl-buffer') */; +/* removed: var _$searchBounds_219 = require('binary-search-bounds') */; +/* removed: var _$iota_302 = require('iota-array') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; -/* removed: var _$shaders_161 = require('./lib/shaders') */; +/* removed: var _$shaders_218 = require('./lib/shaders') */; function GLHeatmap2D ( plot, @@ -111905,7 +112743,7 @@ function GLHeatmap2D ( this.pickOffset = 0 } -var __proto_160 = GLHeatmap2D.prototype +var __proto_217 = GLHeatmap2D.prototype var WEIGHTS = [ 0, 0, @@ -111916,7 +112754,7 @@ var WEIGHTS = [ 0, 1 ] -__proto_160.draw = (function () { +__proto_217.draw = (function () { var MATRIX = [ 1, 0, 0, 0, 1, 0, @@ -111967,7 +112805,7 @@ __proto_160.draw = (function () { } })() -__proto_160.drawPick = (function () { +__proto_217.drawPick = (function () { var MATRIX = [ 1, 0, 0, 0, 1, 0, @@ -112028,7 +112866,7 @@ __proto_160.drawPick = (function () { } })() -__proto_160.pick = function (x, y, value) { +__proto_217.pick = function (x, y, value) { var pickOffset = this.pickOffset var pointCount = this.shape[0] * this.shape[1] if (value < pickOffset || value >= pickOffset + pointCount) { @@ -112046,13 +112884,13 @@ __proto_160.pick = function (x, y, value) { } } -__proto_160.update = function (options) { +__proto_217.update = function (options) { options = options || {} var shape = options.shape || [0, 0] - var x = options.x || _$iota_245(shape[0]) - var y = options.y || _$iota_245(shape[1]) + var x = options.x || _$iota_302(shape[0]) + var y = options.y || _$iota_302(shape[1]) var z = options.z || new Float32Array(shape[0] * shape[1]) this.xData = x @@ -112080,10 +112918,10 @@ __proto_160.update = function (options) { this.numVertices = numVerts - var colors = _$pool_360.mallocUint8(numVerts * 4) - var positions = _$pool_360.mallocFloat32(numVerts * 2) - var weights = _$pool_360.mallocUint8 (numVerts * 2) - var ids = _$pool_360.mallocUint32(numVerts) + var colors = _$pool_422.mallocUint8(numVerts * 4) + var positions = _$pool_422.mallocFloat32(numVerts * 2) + var weights = _$pool_422.mallocUint8 (numVerts * 2) + var ids = _$pool_422.mallocUint32(numVerts) var ptr = 0 @@ -112099,7 +112937,7 @@ __proto_160.update = function (options) { var dy = WEIGHTS[dd + 1] var offset = (j + dy) * numX + (i + dx) var zc = z[offset] - var colorIdx = _$searchBounds_162.le(colorLevels, zc) + var colorIdx = _$searchBounds_219.le(colorLevels, zc) var r, g, b, a if (colorIdx < 0) { r = colorValues[0] @@ -112146,13 +112984,13 @@ __proto_160.update = function (options) { this.colorBuffer.update(colors) this.idBuffer.update(ids) - _$pool_360.free(positions) - _$pool_360.free(colors) - _$pool_360.free(weights) - _$pool_360.free(ids) + _$pool_422.free(positions) + _$pool_422.free(colors) + _$pool_422.free(weights) + _$pool_422.free(ids) } -__proto_160.dispose = function () { +__proto_217.dispose = function () { this.shader.dispose() this.pickShader.dispose() this.positionBuffer.dispose() @@ -112165,13 +113003,13 @@ __proto_160.dispose = function () { function createHeatmap2D (plot, options) { var gl = plot.gl - var shader = _$createShader_206(gl, _$shaders_161.vertex, _$shaders_161.fragment) - var pickShader = _$createShader_206(gl, _$shaders_161.pickVertex, _$shaders_161.pickFragment) + var shader = _$createShader_263(gl, _$shaders_218.vertex, _$shaders_218.fragment) + var pickShader = _$createShader_263(gl, _$shaders_218.pickVertex, _$shaders_218.pickFragment) - var positionBuffer = _$createBuffer_153(gl) - var weightBuffer = _$createBuffer_153(gl) - var colorBuffer = _$createBuffer_153(gl) - var idBuffer = _$createBuffer_153(gl) + var positionBuffer = _$createBuffer_210(gl) + var weightBuffer = _$createBuffer_210(gl) + var colorBuffer = _$createBuffer_210(gl) + var idBuffer = _$createBuffer_210(gl) var heatmap = new GLHeatmap2D( plot, @@ -112199,12 +113037,12 @@ function createHeatmap2D (plot, options) { 'use strict'; -/* removed: var _$createHeatmap2D_160 = require('gl-heatmap2d'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; +/* removed: var _$createHeatmap2D_217 = require('gl-heatmap2d'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; -function __Heatmap_791(scene, uid) { +function __Heatmap_853(scene, uid) { this.scene = scene; this.uid = uid; this.type = 'heatmapgl'; @@ -112229,13 +113067,13 @@ function __Heatmap_791(scene, uid) { colorValues: [0, 0, 0, 1] }; - this.heatmap = _$createHeatmap2D_160(scene.glplot, this.options); + this.heatmap = _$createHeatmap2D_217(scene.glplot, this.options); this.heatmap._trace = this; } -var __proto_791 = __Heatmap_791.prototype; +var __proto_853 = __Heatmap_853.prototype; -__proto_791.handlePick = function(pickResult) { +__proto_853.handlePick = function(pickResult) { var options = this.options, shape = options.shape, index = pickResult.pointId, @@ -112258,7 +113096,7 @@ __proto_791.handlePick = function(pickResult) { }; }; -__proto_791.update = function(fullTrace, calcTrace) { +__proto_853.update = function(fullTrace, calcTrace) { var calcPt = calcTrace[0]; this.index = fullTrace.index; @@ -112285,11 +113123,11 @@ __proto_791.update = function(fullTrace, calcTrace) { this.heatmap.update(this.options); - _$axes_584.expand(this.scene.xaxis, calcPt.x); - _$axes_584.expand(this.scene.yaxis, calcPt.y); + _$axes_647.expand(this.scene.xaxis, calcPt.x); + _$axes_647.expand(this.scene.yaxis, calcPt.y); }; -__proto_791.dispose = function() { +__proto_853.dispose = function() { this.heatmap.dispose(); }; @@ -112304,7 +113142,7 @@ function convertColorscale(fullTrace) { for(var i = 0; i < N; i++) { var si = scl[i]; - var color = _$str2RgbaArray_561(si[1]); + var color = _$str2RgbaArray_624(si[1]); domain[i] = zmin + si[0] * (zmax - zmin); @@ -112320,12 +113158,12 @@ function convertColorscale(fullTrace) { } function createHeatmap(scene, fullTrace, calcTrace) { - var plot = new __Heatmap_791(scene, fullTrace.uid); + var plot = new __Heatmap_853(scene, fullTrace.uid); plot.update(fullTrace, calcTrace); return plot; } -var _$createHeatmap_791 = createHeatmap; +var _$createHeatmap_853 = createHeatmap; /** * Copyright 2012-2018, Plotly, Inc. @@ -112340,16 +113178,16 @@ var _$createHeatmap_791 = createHeatmap; var HeatmapGl = {}; -HeatmapGl.attributes = _$attributes_790; -HeatmapGl.supplyDefaults = _$supplyDefaults_778; -HeatmapGl.colorbar = _$colorbar_776; +HeatmapGl.attributes = _$attributes_852; +HeatmapGl.supplyDefaults = _$supplyDefaults_840; +HeatmapGl.colorbar = _$colorbar_838; -HeatmapGl.calc = _$calc_774; -HeatmapGl.plot = _$createHeatmap_791; +HeatmapGl.calc = _$calc_836; +HeatmapGl.plot = _$createHeatmap_853; HeatmapGl.moduleType = 'trace'; HeatmapGl.name = 'heatmapgl'; -HeatmapGl.basePlotModule = _$gl2d_624; +HeatmapGl.basePlotModule = _$gl2d_686; HeatmapGl.categories = ['gl', 'gl2d', '2dMap']; HeatmapGl.meta = { description: [ @@ -112357,7 +113195,7 @@ HeatmapGl.meta = { ].join(' ') }; -var _$HeatmapGl_792 = HeatmapGl; +var _$HeatmapGl_854 = HeatmapGl; /** * Copyright 2012-2018, Plotly, Inc. @@ -112369,7 +113207,7 @@ var _$HeatmapGl_792 = HeatmapGl; 'use strict'; -var _$heatmapgl_16 = _$HeatmapGl_792; +var _$heatmapgl_16 = _$HeatmapGl_854; /** * Copyright 2012-2018, Plotly, Inc. @@ -112381,9 +113219,9 @@ var _$heatmapgl_16 = _$HeatmapGl_792; 'use strict'; -/* removed: var _$attributes_678 = require('../bar/attributes'); */; +/* removed: var _$attributes_741 = require('../bar/attributes'); */; -var _$attributes_793 = { +var _$attributes_855 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -112399,8 +113237,8 @@ var _$attributes_793 = { ].join(' ') }, - text: _$attributes_678.text, - orientation: _$attributes_678.orientation, + text: _$attributes_741.text, + orientation: _$attributes_741.orientation, histfunc: { valType: 'enumerated', @@ -112561,13 +113399,13 @@ var _$attributes_793 = { }, ybins: makeBinsAttr('y'), - marker: _$attributes_678.marker, + marker: _$attributes_741.marker, - selected: _$attributes_678.selected, - unselected: _$attributes_678.unselected, + selected: _$attributes_741.selected, + unselected: _$attributes_741.unselected, _deprecated: { - bardir: _$attributes_678._deprecated.bardir + bardir: _$attributes_741._deprecated.bardir } }; @@ -112627,20 +113465,20 @@ function makeBinsAttr(axLetter) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$arraysToCalcdata_677 = require('../bar/arrays_to_calcdata'); */; -/* removed: var _$bin_functions_796 = require('./bin_functions'); */; -/* removed: var _$norm_functions_804 = require('./norm_functions'); */; -/* removed: var _$doAvg_794 = require('./average'); */; -/* removed: var _$cleanBins_799 = require('./clean_bins'); */; -var __oneMonth_798 = _$numerical_517.ONEAVGMONTH; -/* removed: var _$getBinSpanLabelRound_797 = require('./bin_label_vals'); */; +/* removed: var _$arraysToCalcdata_740 = require('../bar/arrays_to_calcdata'); */; +/* removed: var _$bin_functions_858 = require('./bin_functions'); */; +/* removed: var _$norm_functions_866 = require('./norm_functions'); */; +/* removed: var _$doAvg_856 = require('./average'); */; +/* removed: var _$cleanBins_861 = require('./clean_bins'); */; +var __oneMonth_860 = _$numerical_578.ONEAVGMONTH; +/* removed: var _$getBinSpanLabelRound_859 = require('./bin_label_vals'); */; -var _$calc_798 = function calc(gd, trace) { +var _$calc_860 = function calc(gd, trace) { // ignore as much processing as possible (and including in autorange) if bar is not visible if(trace.visible !== true) return; @@ -112648,7 +113486,7 @@ var _$calc_798 = function calc(gd, trace) { // note: this logic for choosing orientation is duplicated in graph_obj->setstyles var pos = []; var size = []; - var pa = _$axes_584.getFromId(gd, trace.orientation === 'h' ? + var pa = _$axes_647.getFromId(gd, trace.orientation === 'h' ? (trace.yaxis || 'y') : (trace.xaxis || 'x')); var mainData = trace.orientation === 'h' ? 'y' : 'x'; var counterData = {x: 'y', y: 'x'}[mainData]; @@ -112656,7 +113494,7 @@ var _$calc_798 = function calc(gd, trace) { var cumulativeSpec = trace.cumulative; var i; - _$cleanBins_799(trace, pa, mainData); + _$cleanBins_861(trace, pa, mainData); var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData); var binSpec = binsAndPos[0]; @@ -112684,16 +113522,16 @@ var _$calc_798 = function calc(gd, trace) { var extremeFunc = func === 'max' || func === 'min'; var sizeInit = extremeFunc ? null : 0; - var binFunc = _$bin_functions_796.count; - var normFunc = _$norm_functions_804[norm]; + var binFunc = _$bin_functions_858.count; + var normFunc = _$norm_functions_866[norm]; var isAvg = false; var pr2c = function(v) { return pa.r2c(v, 0, calendar); }; var rawCounterData; - if(_$lib_539.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { + if(_$lib_601.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { rawCounterData = trace[counterData]; isAvg = func === 'avg'; - binFunc = _$bin_functions_796[func]; + binFunc = _$bin_functions_858[func]; } // create the bins (and any extra arrays needed) @@ -112701,10 +113539,10 @@ var _$calc_798 = function calc(gd, trace) { i = pr2c(binSpec.start); // decrease end a little in case of rounding errors - binEnd = pr2c(binSpec.end) + (i - _$axes_584.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; + binEnd = pr2c(binSpec.end) + (i - _$axes_647.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; while(i < binEnd && pos.length < 1e6) { - i2 = _$axes_584.tickIncrement(i, binSpec.size, false, calendar); + i2 = _$axes_647.tickIncrement(i, binSpec.size, false, calendar); pos.push((i + i2) / 2); size.push(sizeInit); inputPoints.push([]); @@ -112739,7 +113577,7 @@ var _$calc_798 = function calc(gd, trace) { var ptNumber2cdIndex = {}; for(i = 0; i < pos0.length; i++) { var posi = pos0[i]; - n = _$lib_539.findBin(posi, bins); + n = _$lib_601.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]]) { @@ -112755,11 +113593,11 @@ var _$calc_798 = function calc(gd, trace) { var roundFn; if(!uniqueValsPerBin) { - roundFn = _$getBinSpanLabelRound_797(leftGap, rightGap, binEdges, pa, calendar); + roundFn = _$getBinSpanLabelRound_859(leftGap, rightGap, binEdges, pa, calendar); } // average and/or normalize the data, if needed - if(isAvg) total = _$doAvg_794(size, counts); + if(isAvg) total = _$doAvg_856(size, counts); if(normFunc) normFunc(size, total, inc); // after all normalization etc, now we can accumulate if desired @@ -112787,7 +113625,7 @@ var _$calc_798 = function calc(gd, trace) { // create the "calculated data" to plot for(i = firstNonzero; i <= lastNonzero; i++) { - if((_$fastIsnumeric_139(pos[i]) && _$fastIsnumeric_139(size[i]))) { + if((_$fastIsnumeric_196(pos[i]) && _$fastIsnumeric_196(size[i]))) { var cdi = { p: pos[i], s: size[i], @@ -112812,13 +113650,13 @@ var _$calc_798 = function calc(gd, trace) { 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_584.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; + cd[0].width1 = _$axes_647.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; } - _$arraysToCalcdata_677(cd, trace); + _$arraysToCalcdata_740(cd, trace); - if(_$lib_539.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_539.tagSelected(cd, trace, ptNumber2cdIndex); + if(_$lib_601.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_601.tagSelected(cd, trace, ptNumber2cdIndex); } return cd; @@ -112867,7 +113705,7 @@ function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { calendar = tracei[mainData + 'calendar']; var cumulativeSpec = tracei.cumulative; - binSpec = _$axes_584.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); + binSpec = _$axes_647.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); // Edge case: single-valued histogram overlaying others // Use them all together to calculate the bin size for the single-valued one @@ -112921,7 +113759,7 @@ function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { // do what we can to match the auto bins to the first manual bins // but only if sizes are all numeric - if(firstManual && _$fastIsnumeric_139(firstManual.size) && _$fastIsnumeric_139(minSize)) { + if(firstManual && _$fastIsnumeric_196(firstManual.size) && _$fastIsnumeric_196(minSize)) { // first need to ensure the bin size is the same as or an integer fraction // of the first manual bin // allow the bin size to increase just under the autobin step size to match, @@ -113018,7 +113856,7 @@ function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) { // 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_539.distinctVals(dataVals).minDiff; + minSize = _$lib_601.distinctVals(dataVals).minDiff; } // now apply the min size we found to all single-valued traces @@ -113076,9 +113914,9 @@ function getMinSize(size1, size2) { } function numericSize(size) { - if(_$fastIsnumeric_139(size)) return size; + if(_$fastIsnumeric_196(size)) return size; if(typeof size === 'string' && size.charAt(0) === 'M') { - return __oneMonth_798 * +(size.substr(1)); + return __oneMonth_860 * +(size.substr(1)); } return Infinity; } @@ -113147,7 +113985,7 @@ function cdf(size, direction, currentBin) { 'use strict'; -var _$handleBinDefaults_795 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { +var _$handleBinDefaults_857 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { coerce('histnorm'); binDirections.forEach(function(binDirection) { @@ -113179,17 +114017,17 @@ var _$handleBinDefaults_795 = function handleBinDefaults(traceIn, traceOut, coer 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$handleBinDefaults_795 = require('./bin_defaults'); */; -/* removed: var _$handleStyleDefaults_690 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_793 = require('./attributes'); */; +/* removed: var _$handleBinDefaults_857 = require('./bin_defaults'); */; +/* removed: var _$handleStyleDefaults_753 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_855 = require('./attributes'); */; -var _$supplyDefaults_800 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_862 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_793, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_855, attr, dflt); } var x = coerce('x'), @@ -113211,23 +114049,23 @@ var _$supplyDefaults_800 = function supplyDefaults(traceIn, traceOut, defaultCol return; } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); var hasAggregationData = traceOut[orientation === 'h' ? 'x' : 'y']; if(hasAggregationData) coerce('histfunc'); var binDirections = (orientation === 'h') ? ['y'] : ['x']; - _$handleBinDefaults_795(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_857(traceIn, traceOut, coerce, binDirections); - _$handleStyleDefaults_690(traceIn, traceOut, coerce, defaultColor, layout); + _$handleStyleDefaults_753(traceIn, traceOut, coerce, defaultColor, layout); // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'x', inherit: 'y'}); + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'x', inherit: 'y'}); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -113240,7 +114078,7 @@ var _$supplyDefaults_800 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_801 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_863 = 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; @@ -113286,11 +114124,11 @@ var _$eventData_801 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_681 = require('../bar/hover'); */; -var hoverLabelText = _$axes_584.hoverLabelText; +/* removed: var _$hoverPoints_744 = require('../bar/hover'); */; +var hoverLabelText = _$axes_647.hoverLabelText; -var _$hoverPoints_802 = function hoverPoints(pointData, xval, yval, hovermode) { - var pts = _$hoverPoints_681(pointData, xval, yval, hovermode); +var _$hoverPoints_864 = function hoverPoints(pointData, xval, yval, hovermode) { + var pts = _$hoverPoints_744(pointData, xval, yval, hovermode); if(!pts) return; @@ -113334,23 +114172,23 @@ var _$hoverPoints_802 = function hoverPoints(pointData, xval, yval, hovermode) { var Histogram = {}; -Histogram.attributes = _$attributes_793; -Histogram.layoutAttributes = _$layout_attributes_683; -Histogram.supplyDefaults = _$supplyDefaults_800; -Histogram.supplyLayoutDefaults = _$layout_defaults_684; -Histogram.calc = _$calc_798; -Histogram.setPositions = _$setPositions_687; -Histogram.plot = _$plot_685; -Histogram.style = _$style_689; -Histogram.colorbar = _$colorbar_866; -Histogram.hoverPoints = _$hoverPoints_802; -Histogram.selectPoints = _$selectPoints_686; -Histogram.eventData = _$eventData_801; +Histogram.attributes = _$attributes_855; +Histogram.layoutAttributes = _$layout_attributes_746; +Histogram.supplyDefaults = _$supplyDefaults_862; +Histogram.supplyLayoutDefaults = _$layout_defaults_747; +Histogram.calc = _$calc_860; +Histogram.setPositions = _$setPositions_750; +Histogram.plot = _$plot_748; +Histogram.style = _$style_752; +Histogram.colorbar = _$colorbar_931; +Histogram.hoverPoints = _$hoverPoints_864; +Histogram.selectPoints = _$selectPoints_749; +Histogram.eventData = _$eventData_863; Histogram.moduleType = 'trace'; Histogram.name = 'histogram'; -Histogram.basePlotModule = _$cartesian_595; -Histogram.categories = ['cartesian', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; +Histogram.basePlotModule = _$cartesian_658; +Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; Histogram.meta = { description: [ 'The sample data from which statistics are computed is set in `x`', @@ -113361,7 +114199,7 @@ Histogram.meta = { ].join(' ') }; -var _$Histogram_803 = Histogram; +var _$Histogram_865 = Histogram; /** * Copyright 2012-2018, Plotly, Inc. @@ -113373,7 +114211,7 @@ var _$Histogram_803 = Histogram; 'use strict'; -var _$histogram_17 = _$Histogram_803; +var _$histogram_17 = _$Histogram_865; /** * Copyright 2012-2018, Plotly, Inc. @@ -113385,17 +114223,17 @@ var _$histogram_17 = _$Histogram_803; 'use strict'; -/* removed: var _$attributes_793 = require('../histogram/attributes'); */; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_855 = require('../histogram/attributes'); */; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_805 = _$extend_528.extendFlat; +var __extendFlat_867 = _$extend_590.extendFlat; -var _$attributes_805 = __extendFlat_805({}, +var _$attributes_867 = __extendFlat_867({}, { - x: _$attributes_793.x, - y: _$attributes_793.y, + x: _$attributes_855.x, + y: _$attributes_855.y, z: { valType: 'data_array', @@ -113411,23 +114249,23 @@ var _$attributes_805 = __extendFlat_805({}, editType: 'calc' }, - histnorm: _$attributes_793.histnorm, - histfunc: _$attributes_793.histfunc, - autobinx: _$attributes_793.autobinx, - nbinsx: _$attributes_793.nbinsx, - xbins: _$attributes_793.xbins, - autobiny: _$attributes_793.autobiny, - nbinsy: _$attributes_793.nbinsy, - ybins: _$attributes_793.ybins, - - xgap: _$attributes_773.xgap, - ygap: _$attributes_773.ygap, - zsmooth: _$attributes_773.zsmooth, - zhoverformat: _$attributes_773.zhoverformat - }, - _$attributes_417, - { autocolorscale: __extendFlat_805({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } + histnorm: _$attributes_855.histnorm, + histfunc: _$attributes_855.histfunc, + autobinx: _$attributes_855.autobinx, + nbinsx: _$attributes_855.nbinsx, + xbins: _$attributes_855.xbins, + autobiny: _$attributes_855.autobiny, + nbinsy: _$attributes_855.nbinsy, + ybins: _$attributes_855.ybins, + + xgap: _$attributes_835.xgap, + ygap: _$attributes_835.ygap, + zsmooth: _$attributes_835.zsmooth, + zhoverformat: _$attributes_835.zhoverformat + }, + _$attributes_479, + { autocolorscale: __extendFlat_867({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); /** @@ -113441,11 +114279,11 @@ var _$attributes_805 = __extendFlat_805({}, 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$handleBinDefaults_795 = require('../histogram/bin_defaults'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$handleBinDefaults_857 = require('../histogram/bin_defaults'); */; -var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut, coerce, layout) { +var _$handleSampleDefaults_872 = function handleSampleDefaults(traceIn, traceOut, coerce, layout) { var x = coerce('x'), y = coerce('y'); @@ -113457,7 +114295,7 @@ var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut return; } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); // if marker.color is an array, we can use it in aggregation instead of z @@ -113466,7 +114304,7 @@ var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut if(hasAggregationData) coerce('histfunc'); var binDirections = ['x', 'y']; - _$handleBinDefaults_795(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_857(traceIn, traceOut, coerce, binDirections); }; /** @@ -113480,24 +114318,24 @@ var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleSampleDefaults_810 = require('./sample_defaults'); */; -/* removed: var _$handleStyleDefaults_788 = require('../heatmap/style_defaults'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_805 = require('./attributes'); */; +/* removed: var _$handleSampleDefaults_872 = require('./sample_defaults'); */; +/* removed: var _$handleStyleDefaults_850 = require('../heatmap/style_defaults'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_867 = require('./attributes'); */; -var _$supplyDefaults_807 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_805, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_867, attr, dflt); } - _$handleSampleDefaults_810(traceIn, traceOut, coerce, layout); + _$handleSampleDefaults_872(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; - _$handleStyleDefaults_788(traceIn, traceOut, coerce, layout); - _$colorScaleDefaults_421( + _$handleStyleDefaults_850(traceIn, traceOut, coerce, layout); + _$colorScaleDefaults_483( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); }; @@ -113513,11 +114351,11 @@ var _$supplyDefaults_807 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$hoverPoints_781 = require('../heatmap/hover'); */; -var __hoverLabelText_808 = _$axes_584.hoverLabelText; +/* removed: var _$hoverPoints_843 = require('../heatmap/hover'); */; +var __hoverLabelText_870 = _$axes_647.hoverLabelText; -var _$hoverPoints_808 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { - var pts = _$hoverPoints_781(pointData, xval, yval, hovermode, hoverLayer, contour); +var _$hoverPoints_870 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { + var pts = _$hoverPoints_843(pointData, xval, yval, hovermode, hoverLayer, contour); if(!pts) return; @@ -113529,8 +114367,8 @@ var _$hoverPoints_808 = function hoverPoints(pointData, xval, yval, hovermode, h var xRange = cd0.xRanges[nx]; var yRange = cd0.yRanges[ny]; - pointData.xLabel = __hoverLabelText_808(pointData.xa, xRange[0], xRange[1]); - pointData.yLabel = __hoverLabelText_808(pointData.ya, yRange[0], yRange[1]); + pointData.xLabel = __hoverLabelText_870(pointData.xa, xRange[0], xRange[1]); + pointData.yLabel = __hoverLabelText_870(pointData.ya, yRange[0], yRange[1]); return pts; }; @@ -113548,19 +114386,19 @@ var _$hoverPoints_808 = function hoverPoints(pointData, xval, yval, hovermode, h var Histogram2D = {}; -Histogram2D.attributes = _$attributes_805; -Histogram2D.supplyDefaults = _$supplyDefaults_807; -Histogram2D.calc = _$calc_774; -Histogram2D.plot = _$plot_786; -Histogram2D.colorbar = _$colorbar_776; -Histogram2D.style = _$style_787; -Histogram2D.hoverPoints = _$hoverPoints_808; -Histogram2D.eventData = _$eventData_801; +Histogram2D.attributes = _$attributes_867; +Histogram2D.supplyDefaults = _$supplyDefaults_869; +Histogram2D.calc = _$calc_836; +Histogram2D.plot = _$plot_848; +Histogram2D.colorbar = _$colorbar_838; +Histogram2D.style = _$style_849; +Histogram2D.hoverPoints = _$hoverPoints_870; +Histogram2D.eventData = _$eventData_863; Histogram2D.moduleType = 'trace'; Histogram2D.name = 'histogram2d'; -Histogram2D.basePlotModule = _$cartesian_595; -Histogram2D.categories = ['cartesian', '2dMap', 'histogram']; +Histogram2D.basePlotModule = _$cartesian_658; +Histogram2D.categories = ['cartesian', 'svg', '2dMap', 'histogram']; Histogram2D.meta = { hrName: 'histogram_2d', description: [ @@ -113573,7 +114411,7 @@ Histogram2D.meta = { ].join(' ') }; -var _$Histogram2D_809 = Histogram2D; +var _$Histogram2D_871 = Histogram2D; /** * Copyright 2012-2018, Plotly, Inc. @@ -113585,7 +114423,7 @@ var _$Histogram2D_809 = Histogram2D; 'use strict'; -var _$histogram2d_18 = _$Histogram2D_809; +var _$histogram2d_18 = _$Histogram2D_871; /** * Copyright 2012-2018, Plotly, Inc. @@ -113597,39 +114435,39 @@ var _$histogram2d_18 = _$Histogram2D_809; 'use strict'; -/* removed: var _$attributes_805 = require('../histogram2d/attributes'); */; -/* removed: var _$attributes_744 = require('../contour/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_867 = require('../histogram2d/attributes'); */; +/* removed: var _$attributes_806 = require('../contour/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_811 = _$extend_528.extendFlat; +var __extendFlat_873 = _$extend_590.extendFlat; -var _$attributes_811 = __extendFlat_811({ - x: _$attributes_805.x, - y: _$attributes_805.y, - z: _$attributes_805.z, - marker: _$attributes_805.marker, +var _$attributes_873 = __extendFlat_873({ + x: _$attributes_867.x, + y: _$attributes_867.y, + z: _$attributes_867.z, + marker: _$attributes_867.marker, - histnorm: _$attributes_805.histnorm, - histfunc: _$attributes_805.histfunc, - autobinx: _$attributes_805.autobinx, - nbinsx: _$attributes_805.nbinsx, - xbins: _$attributes_805.xbins, - autobiny: _$attributes_805.autobiny, - nbinsy: _$attributes_805.nbinsy, - ybins: _$attributes_805.ybins, + histnorm: _$attributes_867.histnorm, + histfunc: _$attributes_867.histfunc, + autobinx: _$attributes_867.autobinx, + nbinsx: _$attributes_867.nbinsx, + xbins: _$attributes_867.xbins, + autobiny: _$attributes_867.autobiny, + nbinsy: _$attributes_867.nbinsy, + ybins: _$attributes_867.ybins, - autocontour: _$attributes_744.autocontour, - ncontours: _$attributes_744.ncontours, - contours: _$attributes_744.contours, - line: _$attributes_744.line, - zhoverformat: _$attributes_805.zhoverformat + autocontour: _$attributes_806.autocontour, + ncontours: _$attributes_806.ncontours, + contours: _$attributes_806.contours, + line: _$attributes_806.line, + zhoverformat: _$attributes_867.zhoverformat }, - _$attributes_417, { - zmin: __extendFlat_811({}, _$attributes_417.zmin, {editType: 'calc'}), - zmax: __extendFlat_811({}, _$attributes_417.zmax, {editType: 'calc'}) + _$attributes_479, { + zmin: __extendFlat_873({}, _$attributes_479.zmin, {editType: 'calc'}), + zmax: __extendFlat_873({}, _$attributes_479.zmax, {editType: 'calc'}) }, - { colorbar: _$attributes_412 } + { colorbar: _$attributes_474 } ); /** @@ -113643,28 +114481,28 @@ var _$attributes_811 = __extendFlat_811({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleSampleDefaults_810 = require('../histogram2d/sample_defaults'); */; -/* removed: var _$handleContourDefaults_751 = require('../contour/contours_defaults'); */; -/* removed: var _$handleStyleDefaults_765 = require('../contour/style_defaults'); */; -/* removed: var _$attributes_811 = require('./attributes'); */; +/* removed: var _$handleSampleDefaults_872 = require('../histogram2d/sample_defaults'); */; +/* removed: var _$handleContourDefaults_813 = require('../contour/contours_defaults'); */; +/* removed: var _$handleStyleDefaults_827 = require('../contour/style_defaults'); */; +/* removed: var _$attributes_873 = require('./attributes'); */; -var _$supplyDefaults_812 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_874 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_811, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_873, attr, dflt); } function coerce2(attr) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_811, attr); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_873, attr); } - _$handleSampleDefaults_810(traceIn, traceOut, coerce, layout); + _$handleSampleDefaults_872(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; - _$handleContourDefaults_751(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_765(traceIn, traceOut, coerce, layout); + _$handleContourDefaults_813(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_827(traceIn, traceOut, coerce, layout); }; /** @@ -113680,18 +114518,18 @@ var _$supplyDefaults_812 = function supplyDefaults(traceIn, traceOut, defaultCol var Histogram2dContour = {}; -Histogram2dContour.attributes = _$attributes_811; -Histogram2dContour.supplyDefaults = _$supplyDefaults_812; -Histogram2dContour.calc = _$calc_745; -Histogram2dContour.plot = _$plot_762.plot; -Histogram2dContour.style = _$style_764; -Histogram2dContour.colorbar = _$colorbar_747; -Histogram2dContour.hoverPoints = _$hoverPoints_757; +Histogram2dContour.attributes = _$attributes_873; +Histogram2dContour.supplyDefaults = _$supplyDefaults_874; +Histogram2dContour.calc = _$calc_807; +Histogram2dContour.plot = _$plot_824.plot; +Histogram2dContour.style = _$style_826; +Histogram2dContour.colorbar = _$colorbar_809; +Histogram2dContour.hoverPoints = _$hoverPoints_819; Histogram2dContour.moduleType = 'trace'; Histogram2dContour.name = 'histogram2dcontour'; -Histogram2dContour.basePlotModule = _$cartesian_595; -Histogram2dContour.categories = ['cartesian', '2dMap', 'contour', 'histogram']; +Histogram2dContour.basePlotModule = _$cartesian_658; +Histogram2dContour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'histogram']; Histogram2dContour.meta = { hrName: 'histogram_2d_contour', description: [ @@ -113704,7 +114542,7 @@ Histogram2dContour.meta = { ].join(' ') }; -var _$Histogram2dContour_813 = Histogram2dContour; +var _$Histogram2dContour_875 = Histogram2dContour; /** * Copyright 2012-2018, Plotly, Inc. @@ -113716,7 +114554,7 @@ var _$Histogram2dContour_813 = Histogram2dContour; 'use strict'; -var _$histogram2dcontour_19 = _$Histogram2dContour_813; +var _$histogram2dcontour_19 = _$Histogram2dContour_875; /** * Copyright 2012-2018, Plotly, Inc. @@ -113729,7 +114567,7 @@ var _$histogram2dcontour_19 = _$Histogram2dContour_813; 'use strict'; -var _$attributes_628 = { +var _$attributes_690 = { scene: { valType: 'subplotid', role: 'info', @@ -113756,14 +114594,14 @@ var _$attributes_628 = { 'use strict'; -/* removed: var _$color_411 = require('../../../components/color'); */; -/* removed: var _$layout_attributes_596 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_629 = _$extend_528.extendFlat; -var __overrideAll_629 = _$edit_types_569.overrideAll; +/* removed: var _$color_473 = require('../../../components/color'); */; +/* removed: var _$layout_attributes_659 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_691 = _$extend_590.extendFlat; +var __overrideAll_691 = _$edit_types_632.overrideAll; -var _$axis_attributes_629 = __overrideAll_629({ - visible: _$layout_attributes_596.visible, +var _$axis_attributes_691 = __overrideAll_691({ + visible: _$layout_attributes_659.visible, showspikes: { valType: 'boolean', role: 'info', @@ -113793,7 +114631,7 @@ var _$axis_attributes_629 = __overrideAll_629({ spikecolor: { valType: 'color', role: 'style', - dflt: _$color_411.defaultLine, + dflt: _$color_473.defaultLine, description: 'Sets the color of the spikes.' }, showbackground: { @@ -113817,51 +114655,51 @@ var _$axis_attributes_629 = __overrideAll_629({ dflt: true, description: 'Sets whether or not this axis is labeled' }, - color: _$layout_attributes_596.color, - categoryorder: _$layout_attributes_596.categoryorder, - categoryarray: _$layout_attributes_596.categoryarray, - title: _$layout_attributes_596.title, - titlefont: _$layout_attributes_596.titlefont, - type: _$layout_attributes_596.type, - autorange: _$layout_attributes_596.autorange, - rangemode: _$layout_attributes_596.rangemode, - range: _$layout_attributes_596.range, + color: _$layout_attributes_659.color, + categoryorder: _$layout_attributes_659.categoryorder, + categoryarray: _$layout_attributes_659.categoryarray, + title: _$layout_attributes_659.title, + titlefont: _$layout_attributes_659.titlefont, + type: _$layout_attributes_659.type, + autorange: _$layout_attributes_659.autorange, + rangemode: _$layout_attributes_659.rangemode, + range: _$layout_attributes_659.range, // ticks - tickmode: _$layout_attributes_596.tickmode, - nticks: _$layout_attributes_596.nticks, - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: _$layout_attributes_596.ticks, - mirror: _$layout_attributes_596.mirror, - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - tickfont: _$layout_attributes_596.tickfont, - tickangle: _$layout_attributes_596.tickangle, - tickprefix: _$layout_attributes_596.tickprefix, - showtickprefix: _$layout_attributes_596.showtickprefix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showticksuffix: _$layout_attributes_596.showticksuffix, - showexponent: _$layout_attributes_596.showexponent, - exponentformat: _$layout_attributes_596.exponentformat, - separatethousands: _$layout_attributes_596.separatethousands, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - hoverformat: _$layout_attributes_596.hoverformat, + tickmode: _$layout_attributes_659.tickmode, + nticks: _$layout_attributes_659.nticks, + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: _$layout_attributes_659.ticks, + mirror: _$layout_attributes_659.mirror, + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + tickfont: _$layout_attributes_659.tickfont, + tickangle: _$layout_attributes_659.tickangle, + tickprefix: _$layout_attributes_659.tickprefix, + showtickprefix: _$layout_attributes_659.showtickprefix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showticksuffix: _$layout_attributes_659.showticksuffix, + showexponent: _$layout_attributes_659.showexponent, + exponentformat: _$layout_attributes_659.exponentformat, + separatethousands: _$layout_attributes_659.separatethousands, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + hoverformat: _$layout_attributes_659.hoverformat, // lines and grids - showline: _$layout_attributes_596.showline, - linecolor: _$layout_attributes_596.linecolor, - linewidth: _$layout_attributes_596.linewidth, - showgrid: _$layout_attributes_596.showgrid, - gridcolor: __extendFlat_629({}, _$layout_attributes_596.gridcolor, // shouldn't this be on-par with 2D? + showline: _$layout_attributes_659.showline, + linecolor: _$layout_attributes_659.linecolor, + linewidth: _$layout_attributes_659.linewidth, + showgrid: _$layout_attributes_659.showgrid, + gridcolor: __extendFlat_691({}, _$layout_attributes_659.gridcolor, // shouldn't this be on-par with 2D? {dflt: 'rgb(204, 204, 204)'}), - gridwidth: _$layout_attributes_596.gridwidth, - zeroline: _$layout_attributes_596.zeroline, - zerolinecolor: _$layout_attributes_596.zerolinecolor, - zerolinewidth: _$layout_attributes_596.zerolinewidth + gridwidth: _$layout_attributes_659.gridwidth, + zeroline: _$layout_attributes_659.zeroline, + zerolinecolor: _$layout_attributes_659.zerolinecolor, + zerolinewidth: _$layout_attributes_659.zerolinewidth }, 'plot', 'from-root'); /** @@ -113875,29 +114713,29 @@ var _$axis_attributes_629 = __overrideAll_629({ 'use strict'; -var __colorMix_630 = _$tinycolor_352.mix; +var __colorMix_692 = _$tinycolor_414.mix; -/* removed: var _$lib_539 = require('../../../lib'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; -/* removed: var _$axis_attributes_629 = require('./axis_attributes'); */; -/* removed: var _$handleTypeDefaults_608 = require('../../cartesian/type_defaults'); */; -/* removed: var _$handleAxisDefaults_586 = require('../../cartesian/axis_defaults'); */; +/* removed: var _$axis_attributes_691 = require('./axis_attributes'); */; +/* removed: var _$handleTypeDefaults_670 = require('../../cartesian/type_defaults'); */; +/* removed: var _$handleAxisDefaults_649 = require('../../cartesian/axis_defaults'); */; -var __axesNames_630 = ['xaxis', 'yaxis', 'zaxis']; +var __axesNames_692 = ['xaxis', 'yaxis', 'zaxis']; // TODO: hard-coded lightness fraction based on gridline default colors // that differ from other subplot types. var gridLightness = 100 * (204 - 0x44) / (255 - 0x44); -var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutOut, options) { +var _$supplyLayoutDefaults_692 = function supplyLayoutDefaults(layoutIn, layoutOut, options) { var containerIn, containerOut; function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$axis_attributes_629, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$axis_attributes_691, attr, dflt); } - for(var j = 0; j < __axesNames_630.length; j++) { - var axName = __axesNames_630[j]; + for(var j = 0; j < __axesNames_692.length; j++) { + var axName = __axesNames_692[j]; containerIn = layoutIn[axName] || {}; containerOut = layoutOut[axName] = { @@ -113905,9 +114743,9 @@ var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutO _name: axName }; - _$handleTypeDefaults_608(containerIn, containerOut, coerce, options.data); + _$handleTypeDefaults_670(containerIn, containerOut, coerce, options.data); - _$handleAxisDefaults_586( + _$handleAxisDefaults_649( containerIn, containerOut, coerce, @@ -113921,10 +114759,10 @@ var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutO }, options.fullLayout); - coerce('gridcolor', __colorMix_630(containerOut.color, options.bgColor, gridLightness).toRgbString()); + coerce('gridcolor', __colorMix_692(containerOut.color, options.bgColor, gridLightness).toRgbString()); coerce('title', axName[0]); // shouldn't this be on-par with 2D? - containerOut.setScale = _$lib_539.noop; + containerOut.setScale = _$lib_601.noop; if(coerce('showspikes')) { coerce('spikesides'); @@ -113948,10 +114786,10 @@ var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$axis_attributes_629 = require('./axis_attributes'); */; -var __domainAttrs_633 = _$domain_610.attributes; -var __extendFlat_633 = _$extend_528.extendFlat; -var __counterRegex_633 = _$lib_539.counterRegex; +/* removed: var _$axis_attributes_691 = require('./axis_attributes'); */; +var __domainAttrs_695 = _$domain_672.attributes; +var __extendFlat_695 = _$extend_590.extendFlat; +var __counterRegex_695 = _$lib_601.counterRegex; function makeCameraVector(x, y, z) { return { @@ -113977,8 +114815,8 @@ function makeCameraVector(x, y, z) { }; } -var _$layout_attributes_633 = { - _arrayAttrRegexps: [__counterRegex_633('scene', '.annotations', true)], +var _$layout_attributes_695 = { + _arrayAttrRegexps: [__counterRegex_695('scene', '.annotations', true)], bgcolor: { valType: 'color', @@ -113987,7 +114825,7 @@ var _$layout_attributes_633 = { editType: 'plot' }, camera: { - up: __extendFlat_633(makeCameraVector(0, 0, 1), { + up: __extendFlat_695(makeCameraVector(0, 0, 1), { description: [ 'Sets the (x,y,z) components of the \'up\' camera vector.', 'This vector determines the up direction of this scene', @@ -113996,7 +114834,7 @@ var _$layout_attributes_633 = { 'the z axis points up.' ].join(' ') }), - center: __extendFlat_633(makeCameraVector(0, 0, 0), { + center: __extendFlat_695(makeCameraVector(0, 0, 0), { description: [ 'Sets the (x,y,z) components of the \'center\' camera vector', 'This vector determines the translation (x,y,z) space', @@ -114004,7 +114842,7 @@ var _$layout_attributes_633 = { 'By default, there is no such translation.' ].join(' ') }), - eye: __extendFlat_633(makeCameraVector(1.25, 1.25, 1.25), { + eye: __extendFlat_695(makeCameraVector(1.25, 1.25, 1.25), { description: [ 'Sets the (x,y,z) components of the \'eye\' camera vector.', 'This vector determines the view point about the origin', @@ -114013,7 +114851,7 @@ var _$layout_attributes_633 = { }), editType: 'camera' }, - domain: __domainAttrs_633({name: 'scene', editType: 'plot'}), + domain: __domainAttrs_695({name: 'scene', editType: 'plot'}), aspectmode: { valType: 'enumerated', role: 'info', @@ -114071,9 +114909,9 @@ var _$layout_attributes_633 = { ].join(' ') }, - xaxis: _$axis_attributes_629, - yaxis: _$axis_attributes_629, - zaxis: _$axis_attributes_629, + xaxis: _$axis_attributes_691, + yaxis: _$axis_attributes_691, + zaxis: _$axis_attributes_691, dragmode: { valType: 'enumerated', @@ -114118,16 +114956,16 @@ var _$layout_attributes_633 = { 'use strict'; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$color_411 = require('../../../components/color'); */; -/* removed: var _$registry_668 = require('../../../registry'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$color_473 = require('../../../components/color'); */; +/* removed: var _$registry_731 = require('../../../registry'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../../subplot_defaults'); */; -/* removed: var _$supplyLayoutDefaults_630 = require('./axis_defaults'); */; -/* removed: var _$layout_attributes_633 = require('./layout_attributes'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../../subplot_defaults'); */; +/* removed: var _$supplyLayoutDefaults_692 = require('./axis_defaults'); */; +/* removed: var _$layout_attributes_695 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_632 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { +var _$supplyLayoutDefaults_694 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { var hasNon3D = layoutOut._basePlotModules.length > 1; // some layout-wide attribute are used in all scenes @@ -114135,13 +114973,13 @@ var _$supplyLayoutDefaults_632 = function supplyLayoutDefaults(layoutIn, layoutO function getDfltFromLayout(attr) { if(hasNon3D) return; - var isValid = _$lib_539.validate(layoutIn[attr], _$layout_attributes_633[attr]); + var isValid = _$lib_601.validate(layoutIn[attr], _$layout_attributes_695[attr]); if(isValid) return layoutIn[attr]; } - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'gl3d', - attributes: _$layout_attributes_633, + attributes: _$layout_attributes_695, handleDefaults: handleGl3dDefaults, fullLayout: layoutOut, font: layoutOut.font, @@ -114166,7 +115004,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { */ var bgcolor = coerce('bgcolor'), - bgColorCombined = _$color_411.combine(bgcolor, opts.paper_bgcolor); + bgColorCombined = _$color_473.combine(bgcolor, opts.paper_bgcolor); var cameraKeys = ['up', 'center', 'eye']; @@ -114206,7 +115044,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { sceneLayoutIn.aspectmode = sceneLayoutOut.aspectmode; } - _$supplyLayoutDefaults_630(sceneLayoutIn, sceneLayoutOut, { + _$supplyLayoutDefaults_692(sceneLayoutIn, sceneLayoutOut, { font: opts.font, scene: opts.id, data: opts.fullData, @@ -114215,7 +115053,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { fullLayout: opts.fullLayout }); - _$registry_668.getComponentMethod('annotations3d', 'handleDefaults')( + _$registry_731.getComponentMethod('annotations3d', 'handleDefaults')( sceneLayoutIn, sceneLayoutOut, opts ); @@ -114223,7 +115061,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { coerce('hovermode', opts.getDfltFromLayout('hovermode')); } -var _$invert_173 = invert; +var _$invert_230 = invert; /** * Inverts a mat4 @@ -114278,7 +115116,7 @@ function invert(out, a) { return out; }; -var _$identity_172 = __identity_172; +var _$identity_229 = __identity_229; /** * Set a mat4 to the identity matrix @@ -114286,7 +115124,7 @@ var _$identity_172 = __identity_172; * @param {mat4} out the receiving matrix * @returns {mat4} out */ -function __identity_172(out) { +function __identity_229(out) { out[0] = 1; out[1] = 0; out[2] = 0; @@ -114305,9 +115143,9 @@ function __identity_172(out) { out[15] = 1; return out; }; -/* removed: var _$identity_172 = require('./identity'); */; +/* removed: var _$identity_229 = require('./identity'); */; -var _$lookAt_174 = lookAt; +var _$lookAt_231 = lookAt; /** * Generates a look-at matrix with the given eye position, focal point, and up axis @@ -114333,7 +115171,7 @@ function lookAt(out, eye, center, up) { if (Math.abs(eyex - centerx) < 0.000001 && Math.abs(eyey - centery) < 0.000001 && Math.abs(eyez - centerz) < 0.000001) { - return _$identity_172(out); + return _$identity_229(out); } z0 = eyex - centerx; @@ -114395,7 +115233,7 @@ function lookAt(out, eye, center, up) { return out; }; -var _$rotateX_178 = rotateX; +var _$rotateX_235 = rotateX; /** * Rotates a matrix by the given angle around the X axis @@ -114439,7 +115277,7 @@ function rotateX(out, a, rad) { out[11] = a23 * c - a13 * s; return out; }; -var _$rotateY_179 = rotateY; +var _$rotateY_236 = rotateY; /** * Rotates a matrix by the given angle around the Y axis @@ -114483,7 +115321,7 @@ function rotateY(out, a, rad) { out[11] = a03 * s + a23 * c; return out; }; -var _$rotateZ_180 = rotateZ; +var _$rotateZ_237 = rotateZ; /** * Rotates a matrix by the given angle around the Z axis @@ -114527,7 +115365,7 @@ function rotateZ(out, a, rad) { out[7] = a13 * c - a03 * s; return out; }; -var _$scale_181 = scale; +var _$scale_238 = scale; /** * Scales the mat4 by the dimensions in the given vec3 @@ -114558,7 +115396,7 @@ function scale(out, a, v) { out[15] = a[15]; return out; }; -var _$translate_182 = translate; +var _$translate_239 = translate; /** * Translate a mat4 by the given vector @@ -114596,7 +115434,7 @@ function translate(out, a, v) { return out; }; -var _$normalize_227 = __normalize_227; +var _$normalize_284 = __normalize_284; /** * Normalize a vec3 @@ -114605,7 +115443,7 @@ var _$normalize_227 = __normalize_227; * @param {vec3} a vector to normalize * @returns {vec3} out */ -function __normalize_227(out, a) { +function __normalize_284(out, a) { var x = a[0], y = a[1], z = a[2] @@ -114619,7 +115457,7 @@ function __normalize_227(out, a) { } return out } -var _$determinant_169 = __determinant_169; +var _$determinant_226 = __determinant_226; /** * Calculates the determinant of a mat4 @@ -114627,7 +115465,7 @@ var _$determinant_169 = __determinant_169; * @param {mat4} a the source matrix * @returns {Number} determinant of a */ -function __determinant_169(a) { +function __determinant_226(a) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], @@ -114649,7 +115487,7 @@ function __determinant_169(a) { // Calculate the determinant return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; }; -var _$lerp_226 = __lerp_226; +var _$lerp_283 = __lerp_283; /** * Performs a linear interpolation between two vec3's @@ -114660,7 +115498,7 @@ var _$lerp_226 = __lerp_226; * @param {Number} t interpolation amount between the two inputs * @returns {vec3} out */ -function __lerp_226(out, a, b, t) { +function __lerp_283(out, a, b, t) { var ax = a[0], ay = a[1], az = a[2] @@ -114669,7 +115507,7 @@ function __lerp_226(out, a, b, t) { out[2] = az + t * (b[2] - az) return out } -var _$clone_167 = clone; +var _$clone_224 = clone; /** * Creates a new mat4 initialized with values from an existing matrix @@ -114697,7 +115535,7 @@ function clone(a) { out[15] = a[15]; return out; }; -var _$create_168 = create; +var _$create_225 = create; /** * Creates a new identity mat4 @@ -114724,7 +115562,7 @@ function create() { out[15] = 1; return out; }; -var _$transpose_183 = transpose; +var _$transpose_240 = transpose; /** * Transpose the values of a mat4 @@ -114773,7 +115611,7 @@ function transpose(out, a) { return out; }; -var _$cross_223 = __cross_223; +var _$cross_280 = __cross_280; /** * Computes the cross product of two vec3's @@ -114783,7 +115621,7 @@ var _$cross_223 = __cross_223; * @param {vec3} b the second operand * @returns {vec3} out */ -function __cross_223(out, a, b) { +function __cross_280(out, a, b) { var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2] @@ -114792,7 +115630,7 @@ function __cross_223(out, a, b) { out[2] = ax * by - ay * bx return out } -var _$dot_224 = __dot_224; +var _$dot_281 = __dot_281; /** * Calculates the dot product of two vec3's @@ -114801,10 +115639,10 @@ var _$dot_224 = __dot_224; * @param {vec3} b the second operand * @returns {Number} dot product of a and b */ -function __dot_224(a, b) { +function __dot_281(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -var _$length_225 = length; +var _$length_282 = length; /** * Calculates the length of a vec3 @@ -114818,7 +115656,7 @@ function length(a) { z = a[2] return Math.sqrt(x*x + y*y + z*z) } -var _$normalize_257 = function normalize(out, mat) { +var _$normalize_314 = function normalize(out, mat) { var m44 = mat[15] // Cannot normalize. if (m44 === 0) @@ -114845,27 +115683,27 @@ https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix */ -/* removed: var _$normalize_257 = require('./normalize') */; +/* removed: var _$normalize_314 = require('./normalize') */; -/* removed: var _$create_168 = require('gl-mat4/create') */; -/* removed: var _$clone_167 = require('gl-mat4/clone') */; -/* removed: var _$determinant_169 = require('gl-mat4/determinant') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$transpose_183 = require('gl-mat4/transpose') */; +/* removed: var _$create_225 = require('gl-mat4/create') */; +/* removed: var _$clone_224 = require('gl-mat4/clone') */; +/* removed: var _$determinant_226 = require('gl-mat4/determinant') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$transpose_240 = require('gl-mat4/transpose') */; var vec3 = { - length: _$length_225, - normalize: _$normalize_227, - dot: _$dot_224, - cross: _$cross_223 + length: _$length_282, + normalize: _$normalize_284, + dot: _$dot_281, + cross: _$cross_280 } -var tmp = _$create_168() -var perspectiveMatrix = _$create_168() +var tmp = _$create_225() +var perspectiveMatrix = _$create_225() var tmpVec4 = [0, 0, 0, 0] var row = [ [0,0,0], [0,0,0], [0,0,0] ] var pdum3 = [0,0,0] -var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { +var _$decomposeMat4_313 = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { if (!translation) translation = [0,0,0] if (!scale) scale = [0,0,0] if (!skew) skew = [0,0,0] @@ -114873,12 +115711,12 @@ var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, ske if (!quaternion) quaternion = [0,0,0,1] //normalize, if not possible then bail out early - if (!_$normalize_257(tmp, matrix)) + if (!_$normalize_314(tmp, matrix)) return false // perspectiveMatrix is used to solve for perspective, but it also provides // an easy way to test for singularity of the upper 3x3 component. - _$clone_167(perspectiveMatrix, tmp) + _$clone_224(perspectiveMatrix, tmp) perspectiveMatrix[3] = 0 perspectiveMatrix[7] = 0 @@ -114887,7 +115725,7 @@ var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, ske // If the perspectiveMatrix is not invertible, we are also unable to // decompose, so we'll bail early. Constant taken from SkMatrix44::invert. - if (Math.abs(_$determinant_169(perspectiveMatrix) < 1e-8)) + if (Math.abs(_$determinant_226(perspectiveMatrix) < 1e-8)) return false var a03 = tmp[3], a13 = tmp[7], a23 = tmp[11], @@ -114903,9 +115741,9 @@ var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, ske // Solve the equation by inverting perspectiveMatrix and multiplying // rightHandSide by the inverse. // resuing the perspectiveMatrix here since it's no longer needed - var ret = _$invert_173(perspectiveMatrix, perspectiveMatrix) + var ret = _$invert_230(perspectiveMatrix, perspectiveMatrix) if (!ret) return false - _$transpose_183(perspectiveMatrix, perspectiveMatrix) + _$transpose_240(perspectiveMatrix, perspectiveMatrix) //multiply by transposed inverse perspective matrix, into perspective vec4 vec4multMat4(perspective, tmpVec4, perspectiveMatrix) @@ -115007,7 +115845,7 @@ function combine(out, a, b, scale1, scale2) { out[1] = a[1] * scale1 + b[1] * scale2 out[2] = a[2] * scale1 + b[2] * scale2 } -var _$fromRotationTranslation_171 = fromRotationTranslation; +var _$fromRotationTranslation_228 = fromRotationTranslation; /** * Creates a matrix from a quaternion rotation and vector translation @@ -115060,7 +115898,7 @@ function fromRotationTranslation(out, q, v) { return out; }; -var _$multiply_175 = __multiply_175; +var _$multiply_232 = __multiply_232; /** * Multiplies two mat4's @@ -115070,7 +115908,7 @@ var _$multiply_175 = __multiply_175; * @param {mat4} b the second operand * @returns {mat4} out */ -function __multiply_175(out, a, b) { +function __multiply_232(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], @@ -115114,18 +115952,18 @@ From: http://www.w3.org/TR/css3-transforms/#recomposing-to-a-3d-matrix */ var mat4 = { - identity: _$identity_172, - translate: _$translate_182, - multiply: _$multiply_175, - create: _$create_168, - scale: _$scale_181, - fromRotationTranslation: _$fromRotationTranslation_171 + identity: _$identity_229, + translate: _$translate_239, + multiply: _$multiply_232, + create: _$create_225, + scale: _$scale_238, + fromRotationTranslation: _$fromRotationTranslation_228 } var rotationMatrix = mat4.create() var temp = mat4.create() -var _$recomposeMat4_259 = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { +var _$recomposeMat4_316 = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { mat4.identity(matrix) //apply translation & rotation @@ -115162,7 +116000,7 @@ var _$recomposeMat4_259 = function recomposeMat4(matrix, translation, scale, ske mat4.scale(matrix, matrix, scale) return matrix } -var _$slerp_199 = slerp +var _$slerp_256 = slerp /** * Performs a spherical linear interpolation between two quat @@ -115214,53 +116052,53 @@ function slerp (out, a, b, t) { return out } -var _$quatSlerp_305 = _$slerp_199 -/* removed: var _$lerp_226 = require('gl-vec3/lerp') */; +var _$quatSlerp_367 = _$slerp_256 +/* removed: var _$lerp_283 = require('gl-vec3/lerp') */; -/* removed: var _$recomposeMat4_259 = require('mat4-recompose') */; -/* removed: var _$decomposeMat4_256 = require('mat4-decompose') */; -/* removed: var _$determinant_169 = require('gl-mat4/determinant') */; -/* removed: var _$quatSlerp_305 = require('quat-slerp') */; +/* removed: var _$recomposeMat4_316 = require('mat4-recompose') */; +/* removed: var _$decomposeMat4_313 = require('mat4-decompose') */; +/* removed: var _$determinant_226 = require('gl-mat4/determinant') */; +/* removed: var _$quatSlerp_367 = require('quat-slerp') */; var state0 = state() var state1 = state() -var __tmp_258 = state() +var __tmp_315 = state() -var _$interpolate_258 = interpolate +var _$interpolate_315 = interpolate function interpolate(out, start, end, alpha) { - if (_$determinant_169(start) === 0 || _$determinant_169(end) === 0) + if (_$determinant_226(start) === 0 || _$determinant_226(end) === 0) return false //decompose the start and end matrices into individual components - var r0 = _$decomposeMat4_256(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) - var r1 = _$decomposeMat4_256(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) + var r0 = _$decomposeMat4_313(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) + var r1 = _$decomposeMat4_313(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) if (!r0 || !r1) return false //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) - _$lerp_226(__tmp_258.translate, state0.translate, state1.translate, alpha) - _$lerp_226(__tmp_258.skew, state0.skew, state1.skew, alpha) - _$lerp_226(__tmp_258.scale, state0.scale, state1.scale, alpha) - _$lerp_226(__tmp_258.perspective, state0.perspective, state1.perspective, alpha) - _$quatSlerp_305(__tmp_258.quaternion, state0.quaternion, state1.quaternion, alpha) + _$lerp_283(__tmp_315.translate, state0.translate, state1.translate, alpha) + _$lerp_283(__tmp_315.skew, state0.skew, state1.skew, alpha) + _$lerp_283(__tmp_315.scale, state0.scale, state1.scale, alpha) + _$lerp_283(__tmp_315.perspective, state0.perspective, state1.perspective, alpha) + _$quatSlerp_367(__tmp_315.quaternion, state0.quaternion, state1.quaternion, alpha) //and recompose into our 'out' matrix - _$recomposeMat4_259(out, __tmp_258.translate, __tmp_258.scale, __tmp_258.skew, __tmp_258.perspective, __tmp_258.quaternion) + _$recomposeMat4_316(out, __tmp_315.translate, __tmp_315.scale, __tmp_315.skew, __tmp_315.perspective, __tmp_315.quaternion) return true } function state() { return { - translate: __vec3_258(), - scale: __vec3_258(1), - skew: __vec3_258(), + translate: __vec3_315(), + scale: __vec3_315(1), + skew: __vec3_315(), perspective: vec4(), quaternion: vec4() } } -function __vec3_258(n) { +function __vec3_315(n) { return [n||0,n||0,n||0] } @@ -115269,20 +116107,20 @@ function vec4() { } 'use strict' -/* removed: var _$searchBounds_71 = require('binary-search-bounds') */; -/* removed: var _$interpolate_258 = require('mat4-interpolate') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$rotateX_178 = require('gl-mat4/rotateX') */; -/* removed: var _$rotateY_179 = require('gl-mat4/rotateY') */; -/* removed: var _$rotateZ_180 = require('gl-mat4/rotateZ') */; -/* removed: var _$lookAt_174 = require('gl-mat4/lookAt') */; -/* removed: var _$translate_182 = require('gl-mat4/translate') */; -/* removed: var _$scale_181 = require('gl-mat4/scale') */; -/* removed: var _$normalize_227 = require('gl-vec3/normalize') */; +/* removed: var _$searchBounds_72 = require('binary-search-bounds') */; +/* removed: var _$interpolate_315 = require('mat4-interpolate') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$rotateX_235 = require('gl-mat4/rotateX') */; +/* removed: var _$rotateY_236 = require('gl-mat4/rotateY') */; +/* removed: var _$rotateZ_237 = require('gl-mat4/rotateZ') */; +/* removed: var _$lookAt_231 = require('gl-mat4/lookAt') */; +/* removed: var _$translate_239 = require('gl-mat4/translate') */; +/* removed: var _$scale_238 = require('gl-mat4/scale') */; +/* removed: var _$normalize_284 = require('gl-vec3/normalize') */; var DEFAULT_CENTER = [0,0,0] -var _$createMatrixCameraController_260 = createMatrixCameraController +var _$createMatrixCameraController_318 = createMatrixCameraController function MatrixCameraController(initialMatrix) { this._components = initialMatrix.slice() @@ -115298,11 +116136,11 @@ function MatrixCameraController(initialMatrix) { this._limits = [-Infinity, Infinity] } -var __proto_260 = MatrixCameraController.prototype +var __proto_318 = MatrixCameraController.prototype -__proto_260.recalcMatrix = function(t) { +__proto_318.recalcMatrix = function(t) { var time = this._time - var tidx = _$searchBounds_71.le(time, t) + var tidx = _$searchBounds_72.le(time, t) var mat = this.computedMatrix if(tidx < 0) { return @@ -115331,7 +116169,7 @@ __proto_260.recalcMatrix = function(t) { mat[i] = prev[i] } } else { - _$interpolate_258(mat, prev, next, (t - time[tidx])/dt) + _$interpolate_315(mat, prev, next, (t - time[tidx])/dt) } } @@ -115339,10 +116177,10 @@ __proto_260.recalcMatrix = function(t) { up[0] = mat[1] up[1] = mat[5] up[2] = mat[9] - _$normalize_227(up, up) + _$normalize_284(up, up) var imat = this.computedInverse - _$invert_173(imat, mat) + _$invert_230(imat, mat) var eye = this.computedEye var w = imat[15] eye[0] = imat[12]/w @@ -115356,7 +116194,7 @@ __proto_260.recalcMatrix = function(t) { } } -__proto_260.idle = function(t) { +__proto_318.idle = function(t) { if(t < this.lastT()) { return } @@ -115368,8 +116206,8 @@ __proto_260.idle = function(t) { this._time.push(t) } -__proto_260.flush = function(t) { - var idx = _$searchBounds_71.gt(this._time, t) - 2 +__proto_318.flush = function(t) { + var idx = _$searchBounds_72.gt(this._time, t) - 2 if(idx < 0) { return } @@ -115377,16 +116215,16 @@ __proto_260.flush = function(t) { this._components.splice(0, 16*idx) } -__proto_260.lastT = function() { +__proto_318.lastT = function() { return this._time[this._time.length-1] } -__proto_260.lookAt = function(t, eye, center, up) { +__proto_318.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_174(this.computedMatrix, eye, center, up)) + this.setMatrix(t, _$lookAt_231(this.computedMatrix, eye, center, up)) var d2 = 0.0 for(var i=0; i<3; ++i) { d2 += Math.pow(center[i] - eye[i], 2) @@ -115395,38 +116233,38 @@ __proto_260.lookAt = function(t, eye, center, up) { this.computedRadius[0] = d2 } -__proto_260.rotate = function(t, yaw, pitch, roll) { +__proto_318.rotate = function(t, yaw, pitch, roll) { this.recalcMatrix(t) var mat = this.computedInverse - if(yaw) _$rotateY_179(mat, mat, yaw) - if(pitch) _$rotateX_178(mat, mat, pitch) - if(roll) _$rotateZ_180(mat, mat, roll) - this.setMatrix(t, _$invert_173(this.computedMatrix, mat)) + if(yaw) _$rotateY_236(mat, mat, yaw) + if(pitch) _$rotateX_235(mat, mat, pitch) + if(roll) _$rotateZ_237(mat, mat, roll) + this.setMatrix(t, _$invert_230(this.computedMatrix, mat)) } var tvec = [0,0,0] -__proto_260.pan = function(t, dx, dy, dz) { +__proto_318.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_182(mat, mat, tvec) - this.setMatrix(t, _$invert_173(mat, mat)) + _$translate_239(mat, mat, tvec) + this.setMatrix(t, _$invert_230(mat, mat)) } -__proto_260.translate = function(t, dx, dy, dz) { +__proto_318.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_182(mat, mat, tvec) + _$translate_239(mat, mat, tvec) this.setMatrix(t, mat) } -__proto_260.setMatrix = function(t, mat) { +__proto_318.setMatrix = function(t, mat) { if(t < this.lastT()) { return } @@ -115436,17 +116274,17 @@ __proto_260.setMatrix = function(t, mat) { } } -__proto_260.setDistance = function(t, d) { +__proto_318.setDistance = function(t, d) { this.computedRadius[0] = d } -__proto_260.setDistanceLimits = function(a,b) { +__proto_318.setDistanceLimits = function(a,b) { var lim = this._limits lim[0] = a lim[1] = b } -__proto_260.getDistanceLimits = function(out) { +__proto_318.getDistanceLimits = function(out) { var lim = this._limits if(out) { out[0] = lim[0] @@ -115466,7 +116304,7 @@ function createMatrixCameraController(options) { return new MatrixCameraController(matrix) } -var _$hermite_114 = {}; +var _$hermite_115 = {}; "use strict" function dcubicHermite(p0, v0, p1, v1, t, f) { @@ -115504,16 +116342,16 @@ function cubicHermite(p0, v0, p1, v1, t, f) { return h00*p0 + h10*v0 + h01*p1 + h11*v1 } -_$hermite_114 = cubicHermite -_$hermite_114.derivative = dcubicHermite +_$hermite_115 = cubicHermite +_$hermite_115.derivative = dcubicHermite 'use strict' -var _$createFilteredVector_140 = createFilteredVector +var _$createFilteredVector_197 = createFilteredVector -/* removed: var _$hermite_114 = require('cubic-hermite') */; -/* removed: var _$searchBounds_71 = require('binary-search-bounds') */; +/* removed: var _$hermite_115 = require('cubic-hermite') */; +/* removed: var _$searchBounds_72 = require('binary-search-bounds') */; -function __clamp_140(lo, hi, x) { +function __clamp_197(lo, hi, x) { return Math.min(hi, Math.max(lo, x)) } @@ -115530,10 +116368,10 @@ function FilteredVector(state0, velocity0, t0) { this._scratch = [ state0.slice(), state0.slice(), state0.slice(), state0.slice(), state0.slice() ] } -var __proto_140 = FilteredVector.prototype +var __proto_197 = FilteredVector.prototype -__proto_140.flush = function(t) { - var idx = _$searchBounds_71.gt(this._time, t) - 1 +__proto_197.flush = function(t) { + var idx = _$searchBounds_72.gt(this._time, t) - 1 if(idx <= 0) { return } @@ -115542,10 +116380,10 @@ __proto_140.flush = function(t) { this._velocity.splice(0, idx * this.dimension) } -__proto_140.curve = function(t) { +__proto_197.curve = function(t) { var time = this._time var n = time.length - var idx = _$searchBounds_71.le(time, t) + var idx = _$searchBounds_72.le(time, t) var result = this._scratch[0] var state = this._state var velocity = this._velocity @@ -115584,21 +116422,21 @@ __proto_140.curve = function(t) { result[i] = x0[i] } } else { - _$hermite_114(x0, v0, x1, v1, (t-t0)/dt, result) + _$hermite_115(x0, v0, x1, v1, (t-t0)/dt, result) } } var lo = bounds[0] var hi = bounds[1] for(var i=0; i=0; --i) { @@ -115656,7 +116494,7 @@ __proto_140.stable = function() { return true } -__proto_140.jump = function(t) { +__proto_197.jump = function(t) { var t0 = this.lastT() var d = this.dimension if(t < t0 || arguments.length !== d+1) { @@ -115677,12 +116515,12 @@ __proto_140.jump = function(t) { } this._time.push(t) for(var i=d; i>0; --i) { - state.push(__clamp_140(lo[i-1], hi[i-1], arguments[i])) + state.push(__clamp_197(lo[i-1], hi[i-1], arguments[i])) velocity.push(0) } } -__proto_140.push = function(t) { +__proto_197.push = function(t) { var t0 = this.lastT() var d = this.dimension if(t < t0 || arguments.length !== d+1) { @@ -115698,13 +116536,13 @@ __proto_140.push = function(t) { var sf = (dt > 1e-6) ? 1/dt : 0 this._time.push(t) for(var i=d; i>0; --i) { - var xc = __clamp_140(lo[i-1], hi[i-1], arguments[i]) + var xc = __clamp_197(lo[i-1], hi[i-1], arguments[i]) state.push(xc) velocity.push((xc - state[ptr++]) * sf) } } -__proto_140.set = function(t) { +__proto_197.set = function(t) { var d = this.dimension if(t < this.lastT() || arguments.length !== d+1) { return @@ -115716,12 +116554,12 @@ __proto_140.set = function(t) { var hi = bounds[1] this._time.push(t) for(var i=d; i>0; --i) { - state.push(__clamp_140(lo[i-1], hi[i-1], arguments[i])) + state.push(__clamp_197(lo[i-1], hi[i-1], arguments[i])) velocity.push(0) } } -__proto_140.move = function(t) { +__proto_197.move = function(t) { var t0 = this.lastT() var d = this.dimension if(t <= t0 || arguments.length !== d+1) { @@ -115738,12 +116576,12 @@ __proto_140.move = function(t) { this._time.push(t) for(var i=d; i>0; --i) { var dx = arguments[i] - state.push(__clamp_140(lo[i-1], hi[i-1], state[statePtr++] + dx)) + state.push(__clamp_197(lo[i-1], hi[i-1], state[statePtr++] + dx)) velocity.push(dx * sf) } } -__proto_140.idle = function(t) { +__proto_197.idle = function(t) { var t0 = this.lastT() if(t < t0) { return @@ -115758,7 +116596,7 @@ __proto_140.idle = function(t) { var dt = t - t0 this._time.push(t) for(var i=d-1; i>=0; --i) { - state.push(__clamp_140(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) + state.push(__clamp_197(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) velocity.push(0) statePtr += 1 } @@ -115800,7 +116638,7 @@ function createFilteredVector(initState, initVelocity, initTime) { 'use strict' -var _$quatFromFrame_282 = quatFromFrame +var _$quatFromFrame_340 = quatFromFrame function quatFromFrame( out, @@ -115841,13 +116679,13 @@ function quatFromFrame( } 'use strict' -var _$createOrbitController_283 = createOrbitController +var _$createOrbitController_341 = createOrbitController -/* removed: var _$createFilteredVector_140 = require('filtered-vector') */; -/* removed: var _$lookAt_174 = require('gl-mat4/lookAt') */; -/* removed: var _$fromQuat_170 = require('gl-mat4/fromQuat') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$quatFromFrame_282 = require('./lib/quatFromFrame') */; +/* removed: var _$createFilteredVector_197 = require('filtered-vector') */; +/* removed: var _$lookAt_231 = require('gl-mat4/lookAt') */; +/* removed: var _$fromQuat_227 = require('gl-mat4/fromQuat') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$quatFromFrame_340 = require('./lib/quatFromFrame') */; function len3(x,y,z) { return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) @@ -115875,9 +116713,9 @@ function normalize4(out, a) { } function OrbitCameraController(initQuat, initCenter, initRadius) { - this.radius = _$createFilteredVector_140([initRadius]) - this.center = _$createFilteredVector_140(initCenter) - this.rotation = _$createFilteredVector_140(initQuat) + this.radius = _$createFilteredVector_197([initRadius]) + this.center = _$createFilteredVector_197(initCenter) + this.rotation = _$createFilteredVector_197(initQuat) this.computedRadius = this.radius.curve(0) this.computedCenter = this.center.curve(0) @@ -115889,16 +116727,16 @@ function OrbitCameraController(initQuat, initCenter, initRadius) { this.recalcMatrix(0) } -var __proto_283 = OrbitCameraController.prototype +var __proto_341 = OrbitCameraController.prototype -__proto_283.lastT = function() { +__proto_341.lastT = function() { return Math.max( this.radius.lastT(), this.center.lastT(), this.rotation.lastT()) } -__proto_283.recalcMatrix = function(t) { +__proto_341.recalcMatrix = function(t) { this.radius.curve(t) this.center.curve(t) this.rotation.curve(t) @@ -115907,7 +116745,7 @@ __proto_283.recalcMatrix = function(t) { normalize4(quat, quat) var mat = this.computedMatrix - _$fromQuat_170(mat, quat) + _$fromQuat_227(mat, quat) var center = this.computedCenter var eye = this.computedEye @@ -115930,7 +116768,7 @@ __proto_283.recalcMatrix = function(t) { } } -__proto_283.getMatrix = function(t, result) { +__proto_341.getMatrix = function(t, result) { this.recalcMatrix(t) var m = this.computedMatrix if(result) { @@ -115942,19 +116780,19 @@ __proto_283.getMatrix = function(t, result) { return m } -__proto_283.idle = function(t) { +__proto_341.idle = function(t) { this.center.idle(t) this.radius.idle(t) this.rotation.idle(t) } -__proto_283.flush = function(t) { +__proto_341.flush = function(t) { this.center.flush(t) this.radius.flush(t) this.rotation.flush(t) } -__proto_283.pan = function(t, dx, dy, dz) { +__proto_341.pan = function(t, dx, dy, dz) { dx = dx || 0.0 dy = dy || 0.0 dz = dz || 0.0 @@ -116007,7 +116845,7 @@ __proto_283.pan = function(t, dx, dy, dz) { this.radius.set(t, Math.log(radius)) } -__proto_283.rotate = function(t, dx, dy, dz) { +__proto_341.rotate = function(t, dx, dy, dz) { this.recalcMatrix(t) dx = dx||0.0 @@ -116087,7 +116925,7 @@ __proto_283.rotate = function(t, dx, dy, dz) { this.rotation.set(t, cx, cy, cz, cw) } -__proto_283.lookAt = function(t, eye, center, up) { +__proto_341.lookAt = function(t, eye, center, up) { this.recalcMatrix(t) center = center || this.computedCenter @@ -116095,10 +116933,10 @@ __proto_283.lookAt = function(t, eye, center, up) { up = up || this.computedUp var mat = this.computedMatrix - _$lookAt_174(mat, eye, center, up) + _$lookAt_231(mat, eye, center, up) var rotation = this.computedRotation - _$quatFromFrame_282(rotation, + _$quatFromFrame_340(rotation, mat[0], mat[1], mat[2], mat[4], mat[5], mat[6], mat[8], mat[9], mat[10]) @@ -116114,17 +116952,17 @@ __proto_283.lookAt = function(t, eye, center, up) { this.center.set(t, center[0], center[1], center[2]) } -__proto_283.translate = function(t, dx, dy, dz) { +__proto_341.translate = function(t, dx, dy, dz) { this.center.move(t, dx||0.0, dy||0.0, dz||0.0) } -__proto_283.setMatrix = function(t, matrix) { +__proto_341.setMatrix = function(t, matrix) { var rotation = this.computedRotation - _$quatFromFrame_282(rotation, + _$quatFromFrame_340(rotation, matrix[0], matrix[1], matrix[2], matrix[4], matrix[5], matrix[6], matrix[8], matrix[9], matrix[10]) @@ -116132,7 +116970,7 @@ __proto_283.setMatrix = function(t, matrix) { this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3]) var mat = this.computedMatrix - _$invert_173(mat, matrix) + _$invert_230(mat, matrix) var w = mat[15] if(Math.abs(w) > 1e-6) { var cx = mat[12]/w @@ -116149,13 +116987,13 @@ __proto_283.setMatrix = function(t, matrix) { } } -__proto_283.setDistance = function(t, d) { +__proto_341.setDistance = function(t, d) { if(d > 0) { this.radius.set(t, Math.log(d)) } } -__proto_283.setDistanceLimits = function(lo, hi) { +__proto_341.setDistanceLimits = function(lo, hi) { if(lo > 0) { lo = Math.log(lo) } else { @@ -116171,7 +117009,7 @@ __proto_283.setDistanceLimits = function(lo, hi) { this.radius.bounds[1][0] = hi } -__proto_283.getDistanceLimits = function(out) { +__proto_341.getDistanceLimits = function(out) { var bounds = this.radius.bounds if(out) { out[0] = Math.exp(bounds[0][0]) @@ -116181,7 +117019,7 @@ __proto_283.getDistanceLimits = function(out) { return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ] } -__proto_283.toJSON = function() { +__proto_341.toJSON = function() { this.recalcMatrix(this.lastT()) return { center: this.computedCenter.slice(), @@ -116192,7 +117030,7 @@ __proto_283.toJSON = function() { } } -__proto_283.fromJSON = function(options) { +__proto_341.fromJSON = function(options) { var t = this.lastT() var c = options.center if(c) { @@ -116232,7 +117070,7 @@ function createOrbitController(options) { return result } -var _$rotate_177 = __rotate_177; +var _$rotate_234 = __rotate_234; /** * Rotates a mat4 by the given angle @@ -116243,7 +117081,7 @@ var _$rotate_177 = __rotate_177; * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ -function __rotate_177(out, a, rad, axis) { +function __rotate_234(out, a, rad, axis) { var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, @@ -116298,16 +117136,16 @@ function __rotate_177(out, a, rad, axis) { }; 'use strict' -var _$createTurntableController_357 = createTurntableController +var _$createTurntableController_419 = createTurntableController -/* removed: var _$createFilteredVector_140 = require('filtered-vector') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$rotate_177 = require('gl-mat4/rotate') */; -/* removed: var _$cross_223 = require('gl-vec3/cross') */; -/* removed: var _$normalize_227 = require('gl-vec3/normalize') */; -/* removed: var _$dot_224 = require('gl-vec3/dot') */; +/* removed: var _$createFilteredVector_197 = require('filtered-vector') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$rotate_234 = require('gl-mat4/rotate') */; +/* removed: var _$cross_280 = require('gl-vec3/cross') */; +/* removed: var _$normalize_284 = require('gl-vec3/normalize') */; +/* removed: var _$dot_281 = require('gl-vec3/dot') */; -function __len3_357(x, y, z) { +function __len3_419(x, y, z) { return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2)) } @@ -116338,16 +117176,16 @@ function findOrthoPair(v) { for(var i=0; i<3; ++i) { u[i] -= (uv / vv) * v[i] } - _$normalize_227(u, u) + _$normalize_284(u, u) return u } function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, phi) { - this.center = _$createFilteredVector_140(center) - this.up = _$createFilteredVector_140(up) - this.right = _$createFilteredVector_140(right) - this.radius = _$createFilteredVector_140([radius]) - this.angle = _$createFilteredVector_140([theta, phi]) + this.center = _$createFilteredVector_197(center) + this.up = _$createFilteredVector_197(up) + this.right = _$createFilteredVector_197(right) + this.radius = _$createFilteredVector_197([radius]) + this.angle = _$createFilteredVector_197([theta, phi]) this.angle.bounds = [[-Infinity,-Math.PI/2], [Infinity,Math.PI/2]] this.setDistanceLimits(zoomMin, zoomMax) @@ -116366,9 +117204,9 @@ function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, this.recalcMatrix(0) } -var __proto_357 = TurntableController.prototype +var __proto_419 = TurntableController.prototype -__proto_357.setDistanceLimits = function(minDist, maxDist) { +__proto_419.setDistanceLimits = function(minDist, maxDist) { if(minDist > 0) { minDist = Math.log(minDist) } else { @@ -116384,7 +117222,7 @@ __proto_357.setDistanceLimits = function(minDist, maxDist) { this.radius.bounds[1][0] = maxDist } -__proto_357.getDistanceLimits = function(out) { +__proto_419.getDistanceLimits = function(out) { var bounds = this.radius.bounds[0] if(out) { out[0] = Math.exp(bounds[0][0]) @@ -116394,7 +117232,7 @@ __proto_357.getDistanceLimits = function(out) { return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ] } -__proto_357.recalcMatrix = function(t) { +__proto_419.recalcMatrix = function(t) { //Recompute curves this.center.curve(t) this.up.curve(t) @@ -116425,8 +117263,8 @@ __proto_357.recalcMatrix = function(t) { //Compute toward vector var toward = this.computedToward - _$cross_223(toward, up, right) - _$normalize_227(toward, toward) + _$cross_280(toward, up, right) + _$normalize_284(toward, toward) //Compute angular parameters var radius = Math.exp(this.computedRadius[0]) @@ -116466,7 +117304,7 @@ __proto_357.recalcMatrix = function(t) { var cx = ay * bz - az * by var cy = az * bx - ax * bz var cz = ax * by - ay * bx - var cl = __len3_357(cx, cy, cz) + var cl = __len3_419(cx, cy, cz) cx /= cl cy /= cl cz /= cl @@ -116488,7 +117326,7 @@ __proto_357.recalcMatrix = function(t) { mat[15] = 1.0 } -__proto_357.getMatrix = function(t, result) { +__proto_419.getMatrix = function(t, result) { this.recalcMatrix(t) var mat = this.computedMatrix if(result) { @@ -116501,7 +117339,7 @@ __proto_357.getMatrix = function(t, result) { } var zAxis = [0,0,0] -__proto_357.rotate = function(t, dtheta, dphi, droll) { +__proto_419.rotate = function(t, dtheta, dphi, droll) { this.angle.move(t, dtheta, dphi) if(droll) { this.recalcMatrix(t) @@ -116520,7 +117358,7 @@ __proto_357.rotate = function(t, dtheta, dphi, droll) { mat[4*i+1] = right[i] mat[4*i+2] = toward[i] } - _$rotate_177(mat, mat, droll, zAxis) + _$rotate_234(mat, mat, droll, zAxis) for(var i=0; i<3; ++i) { up[i] = mat[4*i] right[i] = mat[4*i+1] @@ -116531,7 +117369,7 @@ __proto_357.rotate = function(t, dtheta, dphi, droll) { } } -__proto_357.pan = function(t, dx, dy, dz) { +__proto_419.pan = function(t, dx, dy, dz) { dx = dx || 0.0 dy = dy || 0.0 dz = dz || 0.0 @@ -116544,7 +117382,7 @@ __proto_357.pan = function(t, dx, dy, dz) { var ux = mat[1] var uy = mat[5] var uz = mat[9] - var ul = __len3_357(ux, uy, uz) + var ul = __len3_419(ux, uy, uz) ux /= ul uy /= ul uz /= ul @@ -116556,7 +117394,7 @@ __proto_357.pan = function(t, dx, dy, dz) { rx -= ux * ru ry -= uy * ru rz -= uz * ru - var rl = __len3_357(rx, ry, rz) + var rl = __len3_419(rx, ry, rz) rx /= rl ry /= rl rz /= rl @@ -116572,7 +117410,7 @@ __proto_357.pan = function(t, dx, dy, dz) { this.radius.set(t, Math.log(radius)) } -__proto_357.translate = function(t, dx, dy, dz) { +__proto_419.translate = function(t, dx, dy, dz) { this.center.move(t, dx||0.0, dy||0.0, @@ -116580,7 +117418,7 @@ __proto_357.translate = function(t, dx, dy, dz) { } //Recenters the coordinate axes -__proto_357.setMatrix = function(t, mat, axes, noSnap) { +__proto_419.setMatrix = function(t, mat, axes, noSnap) { //Get the axes for tare var ushift = 1 @@ -116604,7 +117442,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { var uy = mat[ushift+4] var uz = mat[ushift+8] if(!noSnap) { - var ul = __len3_357(ux, uy, uz) + var ul = __len3_419(ux, uy, uz) ux /= ul uy /= ul uz /= ul @@ -116632,7 +117470,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { rx -= ux * ru ry -= uy * ru rz -= uz * ru - var rl = __len3_357(rx, ry, rz) + var rl = __len3_419(rx, ry, rz) rx /= rl ry /= rl rz /= rl @@ -116640,7 +117478,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { var fx = uy * rz - uz * ry var fy = uz * rx - ux * rz var fz = ux * ry - uy * rx - var fl = __len3_357(fx, fy, fz) + var fl = __len3_419(fx, fy, fz) fx /= fl fy /= fl fz /= fl @@ -116683,7 +117521,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { var dz = mat[10] var imat = this.computedMatrix - _$invert_173(imat, mat) + _$invert_230(imat, mat) var w = imat[15] var ex = imat[12] / w var ey = imat[13] / w @@ -116693,7 +117531,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { this.center.jump(t, ex-dx*gs, ey-dy*gs, ez-dz*gs) } -__proto_357.lastT = function() { +__proto_419.lastT = function() { return Math.max( this.center.lastT(), this.up.lastT(), @@ -116702,7 +117540,7 @@ __proto_357.lastT = function() { this.angle.lastT()) } -__proto_357.idle = function(t) { +__proto_419.idle = function(t) { this.center.idle(t) this.up.idle(t) this.right.idle(t) @@ -116710,7 +117548,7 @@ __proto_357.idle = function(t) { this.angle.idle(t) } -__proto_357.flush = function(t) { +__proto_419.flush = function(t) { this.center.flush(t) this.up.flush(t) this.right.flush(t) @@ -116718,13 +117556,13 @@ __proto_357.flush = function(t) { this.angle.flush(t) } -__proto_357.setDistance = function(t, d) { +__proto_419.setDistance = function(t, d) { if(d > 0) { this.radius.set(t, Math.log(d)) } } -__proto_357.lookAt = function(t, eye, center, up) { +__proto_419.lookAt = function(t, eye, center, up) { this.recalcMatrix(t) eye = eye || this.computedEye @@ -116734,7 +117572,7 @@ __proto_357.lookAt = function(t, eye, center, up) { var ux = up[0] var uy = up[1] var uz = up[2] - var ul = __len3_357(ux, uy, uz) + var ul = __len3_419(ux, uy, uz) if(ul < 1e-6) { return } @@ -116745,7 +117583,7 @@ __proto_357.lookAt = function(t, eye, center, up) { var tx = eye[0] - center[0] var ty = eye[1] - center[1] var tz = eye[2] - center[2] - var tl = __len3_357(tx, ty, tz) + var tl = __len3_419(tx, ty, tz) if(tl < 1e-6) { return } @@ -116761,13 +117599,13 @@ __proto_357.lookAt = function(t, eye, center, up) { rx -= ru * ux ry -= ru * uy rz -= ru * uz - var rl = __len3_357(rx, ry, rz) + var rl = __len3_419(rx, ry, rz) if(rl < 0.01) { rx = uy * tz - uz * ty ry = uz * tx - ux * tz rz = ux * ty - uy * tx - rl = __len3_357(rx, ry, rz) + rl = __len3_419(rx, ry, rz) if(rl < 1e-6) { return } @@ -116784,7 +117622,7 @@ __proto_357.lookAt = function(t, eye, center, up) { var fx = uy * rz - uz * ry var fy = uz * rx - ux * rz var fz = ux * ry - uy * rx - var fl = __len3_357(fx, fy, fz) + var fl = __len3_419(fx, fy, fz) fx /= fl fy /= fl fz /= fl @@ -116827,10 +117665,10 @@ function createTurntableController(options) { center = [].slice.call(center, 0, 3) up = [].slice.call(up, 0, 3) - _$normalize_227(up, up) + _$normalize_284(up, up) right = [].slice.call(right, 0, 3) - _$normalize_227(right, right) + _$normalize_284(right, right) if('eye' in options) { var eye = options.eye @@ -116839,17 +117677,17 @@ function createTurntableController(options) { eye[1]-center[1], eye[2]-center[2] ] - _$cross_223(right, toward, up) - if(__len3_357(right[0], right[1], right[2]) < 1e-6) { + _$cross_280(right, toward, up) + if(__len3_419(right[0], right[1], right[2]) < 1e-6) { right = findOrthoPair(up) } else { - _$normalize_227(right, right) + _$normalize_284(right, right) } - radius = __len3_357(toward[0], toward[1], toward[2]) + radius = __len3_419(toward[0], toward[1], toward[2]) - var ut = _$dot_224(up, toward) / radius - var rt = _$dot_224(right, toward) / radius + var ut = _$dot_281(up, toward) / radius + var rt = _$dot_281(right, toward) / radius phi = Math.acos(ut) theta = Math.acos(rt) } @@ -116870,11 +117708,11 @@ function createTurntableController(options) { } 'use strict' -var _$createViewController_40 = createViewController +var _$createViewController_41 = createViewController -/* removed: var _$createTurntableController_357 = require('turntable-camera-controller') */; -/* removed: var _$createOrbitController_283 = require('orbit-camera-controller') */; -/* removed: var _$createMatrixCameraController_260 = require('matrix-camera-controller') */; +/* removed: var _$createTurntableController_419 = require('turntable-camera-controller') */; +/* removed: var _$createOrbitController_341 = require('orbit-camera-controller') */; +/* removed: var _$createMatrixCameraController_318 = require('matrix-camera-controller') */; function ViewController(controllers, mode) { this._controllerNames = Object.keys(controllers) @@ -116895,7 +117733,7 @@ function ViewController(controllers, mode) { this.computedRadius = this._active.computedRadius } -var __proto_40 = ViewController.prototype +var __proto_41 = ViewController.prototype var COMMON_METHODS = [ ['flush', 1], @@ -116916,25 +117754,25 @@ COMMON_METHODS.forEach(function(method) { argNames.push('a'+i) } var code = 'var cc=this._controllerList;for(var i=0;i Math.abs(dy)) { view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) } else { @@ -117291,10 +118129,10 @@ function doBind(gl, elements, attributes) { } } -var _$doBind_219 = doBind +var _$doBind_276 = doBind "use strict" -/* removed: var _$doBind_219 = require("./do-bind.js") */; +/* removed: var _$doBind_276 = require("./do-bind.js") */; function VAOEmulated(gl) { this.gl = gl @@ -117304,7 +118142,7 @@ function VAOEmulated(gl) { } VAOEmulated.prototype.bind = function() { - _$doBind_219(this.gl, this._elements, this._attributes) + _$doBind_276(this.gl, this._elements, this._attributes) } VAOEmulated.prototype.update = function(attributes, elements, elementsType) { @@ -117330,10 +118168,10 @@ function createVAOEmulated(gl) { return new VAOEmulated(gl) } -var _$createVAOEmulated_220 = createVAOEmulated +var _$createVAOEmulated_277 = createVAOEmulated "use strict" -/* removed: var _$doBind_219 = require("./do-bind.js") */; +/* removed: var _$doBind_276 = require("./do-bind.js") */; function VertexAttribute(location, dimension, a, b, c, d) { this.location = location @@ -117387,7 +118225,7 @@ VAONative.prototype.dispose = function() { VAONative.prototype.update = function(attributes, elements, elementsType) { this.bind() - _$doBind_219(this.gl, elements, attributes) + _$doBind_276(this.gl, elements, attributes) this.unbind() this._attribs.length = 0 if(attributes) @@ -117417,11 +118255,11 @@ function createVAONative(gl, ext) { return new VAONative(gl, ext, ext.createVertexArrayOES()) } -var _$createVAONative_221 = createVAONative +var _$createVAONative_278 = createVAONative "use strict" -/* removed: var _$createVAONative_221 = require("./lib/vao-native.js") */; -/* removed: var _$createVAOEmulated_220 = require("./lib/vao-emulated.js") */; +/* removed: var _$createVAONative_278 = require("./lib/vao-native.js") */; +/* removed: var _$createVAOEmulated_277 = require("./lib/vao-emulated.js") */; function ExtensionShim (gl) { this.bindVertexArrayOES = gl.bindVertexArray.bind(gl) @@ -117436,17 +118274,17 @@ function createVAO(gl, attributes, elements, elementsType) { var vao if(ext) { - vao = _$createVAONative_221(gl, ext) + vao = _$createVAONative_278(gl, ext) } else { - vao = _$createVAOEmulated_220(gl) + vao = _$createVAOEmulated_277(gl) } vao.update(attributes, elements, elementsType) return vao } -var _$createVAO_222 = createVAO +var _$createVAO_279 = createVAO -var _$weakMap_369 = {}; +var _$weakMap_431 = {}; // Copyright (C) 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -117612,7 +118450,7 @@ var _$weakMap_369 = {}; doubleWeakMapCheckSilentFailure = true; // Fall through to installing our WeakMap. } else { - _$weakMap_369 = WeakMap; + _$weakMap_431 = WeakMap; return; } } @@ -118109,7 +118947,7 @@ var _$weakMap_369 = {}; }); } DoubleWeakMap.prototype = OurWeakMap.prototype; - _$weakMap_369 = DoubleWeakMap; + _$weakMap_431 = DoubleWeakMap; // define .constructor to hide OurWeakMap ctor Object.defineProperty(WeakMap.prototype, 'constructor', { @@ -118129,25 +118967,25 @@ var _$weakMap_369 = {}; Proxy = undefined; } - _$weakMap_369 = OurWeakMap; + _$weakMap_431 = OurWeakMap; } })(); 'use strict' -var __weakMap_42 = typeof WeakMap === 'undefined' ? _$weakMap_369 : WeakMap -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; +var __weakMap_43 = typeof WeakMap === 'undefined' ? _$weakMap_431 : WeakMap +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; -var TriangleCache = new __weakMap_42() +var TriangleCache = new __weakMap_43() function createABigTriangle(gl) { var triangleVAO = TriangleCache.get(gl) var handle = triangleVAO && (triangleVAO._triangleBuffer.handle || triangleVAO._triangleBuffer.buffer) if(!handle || !gl.isBuffer(handle)) { - var buf = _$createBuffer_153(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) - triangleVAO = _$createVAO_222(gl, [ + var buf = _$createBuffer_210(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) + triangleVAO = _$createVAO_279(gl, [ { buffer: buf, type: gl.FLOAT, size: 2 @@ -118161,34 +118999,34 @@ function createABigTriangle(gl) { triangleVAO.unbind() } -var _$createABigTriangle_42 = createABigTriangle +var _$createABigTriangle_43 = createABigTriangle -var _$shaders_149 = {}; +var _$shaders_206 = {}; 'use strict' -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -var lineVert = _$browser_238(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]) -var lineFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) -_$shaders_149.line = function(gl) { - return _$createShader_206(gl, lineVert, lineFrag, null, [ +var lineVert = _$browser_295(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]) +var lineFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) +_$shaders_206.line = function(gl) { + return _$createShader_263(gl, lineVert, lineFrag, null, [ {name: 'position', type: 'vec3'} ]) } -var textVert = _$browser_238(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}"]) -var textFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) -_$shaders_149.text = function(gl) { - return _$createShader_206(gl, textVert, textFrag, null, [ +var textVert = _$browser_295(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}"]) +var textFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) +_$shaders_206.text = function(gl) { + return _$createShader_263(gl, textVert, textFrag, null, [ {name: 'position', type: 'vec3'} ]) } -var bgVert = _$browser_238(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]) -var bgFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]) -_$shaders_149.bg = function(gl) { - return _$createShader_206(gl, bgVert, bgFrag, null, [ +var bgVert = _$browser_295(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]) +var bgFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]) +_$shaders_206.bg = function(gl) { + return _$createShader_263(gl, bgVert, bgFrag, null, [ {name: 'position', type: 'vec3'}, {name: 'normal', type: 'vec3'} ]) @@ -118196,11 +119034,11 @@ _$shaders_149.bg = function(gl) { 'use strict' -var _$createBackgroundCube_146 = createBackgroundCube +var _$createBackgroundCube_203 = createBackgroundCube -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -var __createShader_146 = _$shaders_149.bg +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +var __createShader_203 = _$shaders_206.bg function BackgroundCube(gl, buffer, vao, shader) { this.gl = gl @@ -118209,9 +119047,9 @@ function BackgroundCube(gl, buffer, vao, shader) { this.shader = shader } -var __proto_146 = BackgroundCube.prototype +var __proto_203 = BackgroundCube.prototype -__proto_146.draw = function(model, view, projection, bounds, enable, colors) { +__proto_203.draw = function(model, view, projection, bounds, enable, colors) { var needsBG = false for(var i=0; i<3; ++i) { needsBG = needsBG || enable[i] @@ -118241,7 +119079,7 @@ __proto_146.draw = function(model, view, projection, bounds, enable, colors) { gl.disable(gl.POLYGON_OFFSET_FILL) } -__proto_146.dispose = function() { +__proto_203.dispose = function() { this.vao.dispose() this.buffer.dispose() this.shader.dispose() @@ -118279,9 +119117,9 @@ function createBackgroundCube(gl) { } //Allocate buffer and vertex array - var buffer = _$createBuffer_153(gl, new Float32Array(vertices)) - var elements = _$createBuffer_153(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) - var vao = _$createVAO_222(gl, [ + var buffer = _$createBuffer_210(gl, new Float32Array(vertices)) + var elements = _$createBuffer_210(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) + var vao = _$createVAO_279(gl, [ { buffer: buffer, type: gl.FLOAT, @@ -118299,7 +119137,7 @@ function createBackgroundCube(gl) { ], elements) //Create shader object - var shader = __createShader_146(gl) + var shader = __createShader_203(gl) shader.attributes.position.location = 0 shader.attributes.normal.location = 1 @@ -118308,30 +119146,30 @@ function createBackgroundCube(gl) { "use strict" -/* removed: var _$twoProduct_358 = require("two-product") */; -/* removed: var _$linearExpansionSum_328 = require("robust-sum") */; +/* removed: var _$twoProduct_420 = require("two-product") */; +/* removed: var _$linearExpansionSum_392 = require("robust-sum") */; -var _$robustDotProduct_320 = robustDotProduct +var _$robustDotProduct_384 = robustDotProduct function robustDotProduct(a, b) { - var r = _$twoProduct_358(a[0], b[0]) + var r = _$twoProduct_420(a[0], b[0]) for(var i=1; i Math.abs(dy)) { view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth); } else { @@ -121164,8 +122002,8 @@ function __createCamera_626(element, options) { 'use strict'; -/* removed: var _$convertHTMLToUnicode_537 = require('../../../lib/html2unicode'); */; -/* removed: var _$str2RgbaArray_561 = require('../../../lib/str2rgbarray'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../../lib/html2unicode'); */; +/* removed: var _$str2RgbaArray_624 = require('../../../lib/str2rgbarray'); */; var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis']; @@ -121221,9 +122059,9 @@ function AxesOptions() { this._defaultLineTickLength = this.lineTickLength.slice(); } -var __proto_631 = AxesOptions.prototype; +var __proto_693 = AxesOptions.prototype; -__proto_631.merge = function(sceneLayout) { +__proto_693.merge = function(sceneLayout) { var opts = this; for(var i = 0; i < 3; ++i) { var axes = sceneLayout[AXES_NAMES[i]]; @@ -121240,27 +122078,27 @@ __proto_631.merge = function(sceneLayout) { } // Axes labels - opts.labels[i] = _$convertHTMLToUnicode_537(axes.title); + opts.labels[i] = _$convertHTMLToUnicode_599(axes.title); if('titlefont' in axes) { - if(axes.titlefont.color) opts.labelColor[i] = _$str2RgbaArray_561(axes.titlefont.color); + if(axes.titlefont.color) opts.labelColor[i] = _$str2RgbaArray_624(axes.titlefont.color); if(axes.titlefont.family) opts.labelFont[i] = axes.titlefont.family; if(axes.titlefont.size) opts.labelSize[i] = axes.titlefont.size; } // Lines if('showline' in axes) opts.lineEnable[i] = axes.showline; - if('linecolor' in axes) opts.lineColor[i] = _$str2RgbaArray_561(axes.linecolor); + if('linecolor' in axes) opts.lineColor[i] = _$str2RgbaArray_624(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_561(axes.gridcolor); + if('gridcolor' in axes) opts.gridColor[i] = _$str2RgbaArray_624(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_561(axes.zerolinecolor); + if('zerolinecolor' in axes) opts.zeroLineColor[i] = _$str2RgbaArray_624(axes.zerolinecolor); if('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth; // tick lines @@ -121270,7 +122108,7 @@ __proto_631.merge = function(sceneLayout) { if('ticklen' in axes) { opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen; } - if('tickcolor' in axes) opts.lineTickColor[i] = _$str2RgbaArray_561(axes.tickcolor); + if('tickcolor' in axes) opts.lineTickColor[i] = _$str2RgbaArray_624(axes.tickcolor); if('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth; if('tickangle' in axes) { opts.tickAngle[i] = (axes.tickangle === 'auto') ? @@ -121280,7 +122118,7 @@ __proto_631.merge = function(sceneLayout) { // tick labels if('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels; if('tickfont' in axes) { - if(axes.tickfont.color) opts.tickColor[i] = _$str2RgbaArray_561(axes.tickfont.color); + if(axes.tickfont.color) opts.tickColor[i] = _$str2RgbaArray_624(axes.tickfont.color); if(axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family; if(axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size; } @@ -121301,7 +122139,7 @@ __proto_631.merge = function(sceneLayout) { // grid background if('showbackground' in axes && axes.showbackground !== false) { opts.backgroundEnable[i] = true; - opts.backgroundColor[i] = _$str2RgbaArray_561(axes.backgroundcolor); + opts.backgroundColor[i] = _$str2RgbaArray_624(axes.backgroundcolor); } else opts.backgroundEnable[i] = false; } }; @@ -121313,7 +122151,7 @@ function createAxesOptions(plotlyOptions) { return result; } -var _$createAxesOptions_631 = createAxesOptions; +var _$createAxesOptions_693 = createAxesOptions; /** * Copyright 2012-2018, Plotly, Inc. @@ -121326,9 +122164,9 @@ var _$createAxesOptions_631 = createAxesOptions; 'use strict'; -/* removed: var _$str2RgbaArray_561 = require('../../../lib/str2rgbarray'); */; +/* removed: var _$str2RgbaArray_624 = require('../../../lib/str2rgbarray'); */; -var __AXES_NAMES_634 = ['xaxis', 'yaxis', 'zaxis']; +var __AXES_NAMES_696 = ['xaxis', 'yaxis', 'zaxis']; function SpikeOptions() { this.enabled = [true, true, true]; @@ -121339,11 +122177,11 @@ function SpikeOptions() { this.lineWidth = [1, 1, 1]; } -var __proto_634 = SpikeOptions.prototype; +var __proto_696 = SpikeOptions.prototype; -__proto_634.merge = function(sceneLayout) { +__proto_696.merge = function(sceneLayout) { for(var i = 0; i < 3; ++i) { - var axes = sceneLayout[__AXES_NAMES_634[i]]; + var axes = sceneLayout[__AXES_NAMES_696[i]]; if(!axes.visible) { this.enabled[i] = false; @@ -121352,7 +122190,7 @@ __proto_634.merge = function(sceneLayout) { } this.enabled[i] = axes.showspikes; - this.colors[i] = _$str2RgbaArray_561(axes.spikecolor); + this.colors[i] = _$str2RgbaArray_624(axes.spikecolor); this.drawSides[i] = axes.spikesides; this.lineWidth[i] = axes.spikethickness; } @@ -121364,7 +122202,7 @@ function createSpikeOptions(layout) { return result; } -var _$createSpikeOptions_634 = createSpikeOptions; +var _$createSpikeOptions_696 = createSpikeOptions; /** * Copyright 2012-2018, Plotly, Inc. @@ -121379,13 +122217,13 @@ var _$createSpikeOptions_634 = createSpikeOptions; 'use strict'; -var _$computeTickMarks_635 = computeTickMarks; +var _$computeTickMarks_697 = computeTickMarks; -/* removed: var _$axes_584 = require('../../cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$convertHTMLToUnicode_537 = require('../../../lib/html2unicode'); */; +/* removed: var _$axes_647 = require('../../cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../../lib/html2unicode'); */; -var __AXES_NAMES_635 = ['xaxis', 'yaxis', 'zaxis']; +var __AXES_NAMES_697 = ['xaxis', 'yaxis', 'zaxis']; var centerPoint = [0, 0, 0]; @@ -121410,7 +122248,7 @@ function computeTickMarks(scene) { var ticks = [[], [], []]; for(var i = 0; i < 3; ++i) { - var axes = sceneLayout[__AXES_NAMES_635[i]]; + var axes = sceneLayout[__AXES_NAMES_697[i]]; axes._length = (glRange[i].hi - glRange[i].lo) * glRange[i].pixelsPerDataUnit / scene.dataScale[i]; @@ -121434,13 +122272,13 @@ function computeTickMarks(scene) { var tickModeCached = axes.tickmode; if(axes.tickmode === 'auto') { axes.tickmode = 'linear'; - var nticks = axes.nticks || _$lib_539.constrain((axes._length / 40), 4, 9); - _$axes_584.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks); + var nticks = axes.nticks || _$lib_601.constrain((axes._length / 40), 4, 9); + _$axes_647.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks); } - var dataTicks = _$axes_584.calcTicks(axes); + var dataTicks = _$axes_647.calcTicks(axes); for(var j = 0; j < dataTicks.length; ++j) { dataTicks[j].x = dataTicks[j].x * scene.dataScale[i]; - dataTicks[j].text = _$convertHTMLToUnicode_537(dataTicks[j].text); + dataTicks[j].text = _$convertHTMLToUnicode_599(dataTicks[j].text); } ticks[i] = dataTicks; @@ -121473,27 +122311,27 @@ function computeTickMarks(scene) { 'use strict'; -/* removed: var _$createScene_196 = require('gl-plot3d'); */; -/* removed: var _$getWebGLContext_373 = require('webgl-context'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; +/* removed: var _$createScene_253 = require('gl-plot3d'); */; +/* removed: var _$getWebGLContext_435 = require('webgl-context'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; -/* removed: var _$showWebGlMsg_559 = require('../../lib/show_no_webgl_msg'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; +/* removed: var _$showWebGlMsg_622 = require('../../lib/show_no_webgl_msg'); */; -/* removed: var _$createCamera_626 = require('./camera'); */; -/* removed: var _$project_636 = require('./project'); */; -/* removed: var _$createAxesOptions_631 = require('./layout/convert'); */; -/* removed: var _$createSpikeOptions_634 = require('./layout/spikes'); */; -/* removed: var _$computeTickMarks_635 = require('./layout/tick_marks'); */; +/* removed: var _$createCamera_688 = require('./camera'); */; +/* removed: var _$project_698 = require('./project'); */; +/* removed: var _$createAxesOptions_693 = require('./layout/convert'); */; +/* removed: var _$createSpikeOptions_696 = require('./layout/spikes'); */; +/* removed: var _$computeTickMarks_697 = require('./layout/tick_marks'); */; -var __STATIC_CANVAS_637, __STATIC_CONTEXT_637; +var __STATIC_CANVAS_699, __STATIC_CONTEXT_699; function render(scene) { var trace; @@ -121506,7 +122344,7 @@ function render(scene) { svgContainer.setAttributeNS(null, 'width', width); svgContainer.setAttributeNS(null, 'height', height); - _$computeTickMarks_635(scene); + _$computeTickMarks_697(scene); scene.glplot.axes.update(scene.axesOptions); // check if pick has changed @@ -121525,16 +122363,16 @@ function render(scene) { function formatter(axisName, val) { var axis = scene.fullSceneLayout[axisName]; - return _$axes_584.tickText(axis, axis.d2l(val), 'hover').text; + return _$axes_647.tickText(axis, axis.d2l(val), 'hover').text; } var oldEventData; if(lastPicked !== null) { - var pdata = _$project_636(scene.glplot.cameraParams, selection.dataCoordinate); + var pdata = _$project_698(scene.glplot.cameraParams, selection.dataCoordinate); trace = lastPicked.data; var ptNumber = selection.index; - var hoverinfo = _$fx_453.castHoverinfo(trace, scene.fullLayout, ptNumber); + var hoverinfo = _$fx_515.castHoverinfo(trace, scene.fullLayout, ptNumber); var xVal = formatter('xaxis', selection.traceCoordinate[0]), yVal = formatter('yaxis', selection.traceCoordinate[1]), @@ -121550,7 +122388,7 @@ function render(scene) { } if(scene.fullSceneLayout.hovermode) { - _$fx_453.loneHover({ + _$fx_515.loneHover({ x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width, y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height, xLabel: xVal, @@ -121558,11 +122396,11 @@ function render(scene) { zLabel: zVal, text: selection.textLabel, name: lastPicked.name, - color: _$fx_453.castHoverOption(trace, ptNumber, 'bgcolor') || lastPicked.color, - borderColor: _$fx_453.castHoverOption(trace, ptNumber, 'bordercolor'), - fontFamily: _$fx_453.castHoverOption(trace, ptNumber, 'font.family'), - fontSize: _$fx_453.castHoverOption(trace, ptNumber, 'font.size'), - fontColor: _$fx_453.castHoverOption(trace, ptNumber, 'font.color') + color: _$fx_515.castHoverOption(trace, ptNumber, 'bgcolor') || lastPicked.color, + borderColor: _$fx_515.castHoverOption(trace, ptNumber, 'bordercolor'), + fontFamily: _$fx_515.castHoverOption(trace, ptNumber, 'font.family'), + fontSize: _$fx_515.castHoverOption(trace, ptNumber, 'font.size'), + fontColor: _$fx_515.castHoverOption(trace, ptNumber, 'font.color') }, { container: svgContainer, gd: scene.graphDiv @@ -121579,7 +122417,7 @@ function render(scene) { pointNumber: ptNumber }; - _$fx_453.appendArrayPointValue(pointData, trace, ptNumber); + _$fx_515.appendArrayPointValue(pointData, trace, ptNumber); var eventData = {points: [pointData]}; @@ -121593,7 +122431,7 @@ function render(scene) { oldEventData = eventData; } else { - _$fx_453.loneUnhover(svgContainer); + _$fx_515.loneUnhover(svgContainer); scene.graphDiv.emit('plotly_unhover', oldEventData); } @@ -121616,25 +122454,25 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { // for static plots, we reuse the WebGL context // as WebKit doesn't collect them reliably if(scene.staticMode) { - if(!__STATIC_CONTEXT_637) { - __STATIC_CANVAS_637 = document.createElement('canvas'); - __STATIC_CONTEXT_637 = _$getWebGLContext_373({ - canvas: __STATIC_CANVAS_637, + if(!__STATIC_CONTEXT_699) { + __STATIC_CANVAS_699 = document.createElement('canvas'); + __STATIC_CONTEXT_699 = _$getWebGLContext_435({ + canvas: __STATIC_CANVAS_699, preserveDrawingBuffer: true, premultipliedAlpha: true, antialias: true }); - if(!__STATIC_CONTEXT_637) { + if(!__STATIC_CONTEXT_699) { throw new Error('error creating static canvas/context for image server'); } } glplotOptions.pixelRatio = scene.pixelRatio; - glplotOptions.gl = __STATIC_CONTEXT_637; - glplotOptions.canvas = __STATIC_CANVAS_637; + glplotOptions.gl = __STATIC_CONTEXT_699; + glplotOptions.canvas = __STATIC_CANVAS_699; } try { - scene.glplot = _$createScene_196(glplotOptions); + scene.glplot = _$createScene_253(glplotOptions); } catch(e) { /* @@ -121643,7 +122481,7 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { * The destroy method - which will remove the container from the DOM * is overridden with a function that removes the container only. */ - _$showWebGlMsg_559(scene); + _$showWebGlMsg_622(scene); } var relayoutCallback = function(scene) { @@ -121656,18 +122494,18 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { }; scene.glplot.canvas.addEventListener('mouseup', relayoutCallback.bind(null, scene)); - scene.glplot.canvas.addEventListener('wheel', relayoutCallback.bind(null, scene), _$hasPassiveEvents_240 ? {passive: false} : false); + scene.glplot.canvas.addEventListener('wheel', relayoutCallback.bind(null, scene), _$hasPassiveEvents_297 ? {passive: false} : false); if(!scene.staticMode) { scene.glplot.canvas.addEventListener('webglcontextlost', function(ev) { - _$lib_539.warn('Lost WebGL context.'); + _$lib_601.warn('Lost WebGL context.'); ev.preventDefault(); }); } if(!scene.camera) { var cameraData = scene.fullSceneLayout.camera; - scene.camera = _$createCamera_626(scene.container, { + scene.camera = _$createCamera_688(scene.container, { center: [cameraData.center.x, cameraData.center.y, cameraData.center.z], eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z], up: [cameraData.up.x, cameraData.up.y, cameraData.up.z], @@ -121729,8 +122567,8 @@ function Scene(options, fullLayout) { /* * Move this to calc step? Why does it work here? */ - this.axesOptions = _$createAxesOptions_631(fullLayout[this.id]); - this.spikeOptions = _$createSpikeOptions_634(fullLayout[this.id]); + this.axesOptions = _$createAxesOptions_693(fullLayout[this.id]); + this.spikeOptions = _$createSpikeOptions_696(fullLayout[this.id]); this.container = sceneContainer; this.staticMode = !!options.staticPlot; this.pixelRatio = options.plotGlPixelRatio || 2; @@ -121740,15 +122578,15 @@ function Scene(options, fullLayout) { this.contourLevels = [ [], [], [] ]; - this.convertAnnotations = _$registry_668.getComponentMethod('annotations3d', 'convert'); - this.drawAnnotations = _$registry_668.getComponentMethod('annotations3d', 'draw'); + this.convertAnnotations = _$registry_731.getComponentMethod('annotations3d', 'convert'); + this.drawAnnotations = _$registry_731.getComponentMethod('annotations3d', 'draw'); if(!initializeGLPlot(this, fullLayout)) return; // todo check the necessity for this line } -var __proto_637 = Scene.prototype; +var __proto_699 = Scene.prototype; -__proto_637.recoverContext = function() { +__proto_699.recoverContext = function() { var scene = this; var gl = this.glplot.gl; var canvas = this.glplot.canvas; @@ -121760,7 +122598,7 @@ __proto_637.recoverContext = function() { return; } if(!initializeGLPlot(scene, scene.fullLayout, canvas, gl)) { - _$lib_539.error('Catastrophic and unrecoverable WebGL error. Context lost.'); + _$lib_601.error('Catastrophic and unrecoverable WebGL error. Context lost.'); return; } scene.plot.apply(scene, scene.plotArgs); @@ -121772,14 +122610,14 @@ var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ]; function coordinateBound(axis, coord, len, d, bounds, calendar) { var x; - if(!_$lib_539.isArrayOrTypedArray(coord)) { + if(!_$lib_601.isArrayOrTypedArray(coord)) { bounds[0][d] = Math.min(bounds[0][d], 0); bounds[1][d] = Math.max(bounds[1][d], len - 1); return; } for(var i = 0; i < (len || coord.length); ++i) { - if(_$lib_539.isArrayOrTypedArray(coord[i])) { + if(_$lib_601.isArrayOrTypedArray(coord[i])) { for(var j = 0; j < coord[i].length; ++j) { x = axis.d2l(coord[i][j], 0, calendar); if(!isNaN(x) && isFinite(x)) { @@ -121805,7 +122643,7 @@ function computeTraceBounds(scene, trace, bounds) { coordinateBound(sceneLayout.zaxis, trace.z, trace._zlength, 2, bounds, trace.zcalendar); } -__proto_637.plot = function(sceneData, fullLayout, layout) { +__proto_699.plot = function(sceneData, fullLayout, layout) { // Save parameters this.plotArgs = [sceneData, fullLayout, layout]; @@ -121817,7 +122655,7 @@ __proto_637.plot = function(sceneData, fullLayout, layout) { var fullSceneLayout = fullLayout[this.id]; var sceneLayout = layout[this.id]; - if(fullSceneLayout.bgcolor) this.glplot.clearColor = _$str2RgbaArray_561(fullSceneLayout.bgcolor); + if(fullSceneLayout.bgcolor) this.glplot.clearColor = _$str2RgbaArray_624(fullSceneLayout.bgcolor); else this.glplot.clearColor = [0, 0, 0, 0]; this.glplot.snapToData = true; @@ -122064,7 +122902,7 @@ __proto_637.plot = function(sceneData, fullLayout, layout) { this.glplot.redraw(); }; -__proto_637.destroy = function() { +__proto_699.destroy = function() { if(!this.glplot) return; this.camera.mouseListener.enabled = false; @@ -122096,20 +122934,20 @@ function getLayoutCamera(camera) { } // get camera position in plotly coords from 'orbit-camera' coords -__proto_637.getCamera = function getCamera() { +__proto_699.getCamera = function getCamera() { this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()); return getLayoutCamera(this.glplot.camera); }; // set camera position with a set of plotly coords -__proto_637.setCamera = function setCamera(cameraData) { +__proto_699.setCamera = function setCamera(cameraData) { this.glplot.camera.lookAt.apply(this, getOrbitCamera(cameraData)); }; // save camera to user layout (i.e. gd.layout) -__proto_637.saveCamera = function saveCamera(layout) { +__proto_699.saveCamera = function saveCamera(layout) { var cameraData = this.getCamera(), - cameraNestedProp = _$lib_539.nestedProperty(layout, this.id + '.camera'), + cameraNestedProp = _$lib_601.nestedProperty(layout, this.id + '.camera'), cameraDataLastSave = cameraNestedProp.get(), hasChanged = false; @@ -122136,7 +122974,7 @@ __proto_637.saveCamera = function saveCamera(layout) { return hasChanged; }; -__proto_637.updateFx = function(dragmode, hovermode) { +__proto_699.updateFx = function(dragmode, hovermode) { var camera = this.camera; if(camera) { @@ -122161,10 +122999,10 @@ __proto_637.updateFx = function(dragmode, hovermode) { this.fullSceneLayout.hovermode = hovermode; }; -__proto_637.toImage = function(format) { +__proto_699.toImage = function(format) { if(!format) format = 'png'; - if(this.staticMode) this.container.appendChild(__STATIC_CANVAS_637); + if(this.staticMode) this.container.appendChild(__STATIC_CANVAS_699); // Force redraw this.glplot.redraw(); @@ -122211,22 +123049,22 @@ __proto_637.toImage = function(format) { dataURL = canvas.toDataURL('image/png'); } - if(this.staticMode) this.container.removeChild(__STATIC_CANVAS_637); + if(this.staticMode) this.container.removeChild(__STATIC_CANVAS_699); return dataURL; }; -__proto_637.setConvert = function() { +__proto_699.setConvert = function() { for(var i = 0; i < 3; i++) { var ax = this.fullSceneLayout[axisProperties[i]]; - _$axes_584.setConvert(ax, this.fullLayout); - ax.setScale = _$lib_539.noop; + _$axes_647.setConvert(ax, this.fullLayout); + ax.setScale = _$lib_601.noop; } }; -var _$Scene_637 = Scene; +var _$Scene_699 = Scene; -var _$gl3d_627 = {}; +var _$gl3d_689 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -122238,49 +123076,49 @@ var _$gl3d_627 = {}; 'use strict'; -var __overrideAll_627 = _$edit_types_569.overrideAll; -/* removed: var _$layout_attributes_454 = require('../../components/fx/layout_attributes'); */; +var __overrideAll_689 = _$edit_types_632.overrideAll; +/* removed: var _$layout_attributes_516 = require('../../components/fx/layout_attributes'); */; -/* removed: var _$Scene_637 = require('./scene'); */; -var __getSubplotData_627 = _$get_data_621.getSubplotData; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$Scene_699 = require('./scene'); */; +var __getSubplotData_689 = _$get_data_683.getSubplotData; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; var GL3D = 'gl3d'; var SCENE = 'scene'; -_$gl3d_627.name = GL3D; +_$gl3d_689.name = GL3D; -_$gl3d_627.attr = SCENE; +_$gl3d_689.attr = SCENE; -_$gl3d_627.idRoot = SCENE; +_$gl3d_689.idRoot = SCENE; -_$gl3d_627.idRegex = _$gl3d_627.attrRegex = _$lib_539.counterRegex('scene'); +_$gl3d_689.idRegex = _$gl3d_689.attrRegex = _$lib_601.counterRegex('scene'); -_$gl3d_627.attributes = _$attributes_628; +_$gl3d_689.attributes = _$attributes_690; -_$gl3d_627.layoutAttributes = _$layout_attributes_633; +_$gl3d_689.layoutAttributes = _$layout_attributes_695; -_$gl3d_627.baseLayoutAttrOverrides = __overrideAll_627({ - hoverlabel: _$layout_attributes_454.hoverlabel +_$gl3d_689.baseLayoutAttrOverrides = __overrideAll_689({ + hoverlabel: _$layout_attributes_516.hoverlabel }, 'plot', 'nested'); -_$gl3d_627.supplyLayoutDefaults = _$supplyLayoutDefaults_632; +_$gl3d_689.supplyLayoutDefaults = _$supplyLayoutDefaults_694; -_$gl3d_627.plot = function plotGl3d(gd) { +_$gl3d_689.plot = function plotGl3d(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], - fullSceneData = __getSubplotData_627(fullData, GL3D, sceneId), + fullSceneData = __getSubplotData_689(fullData, GL3D, sceneId), sceneLayout = fullLayout[sceneId], scene = sceneLayout._scene; if(!scene) { - scene = new _$Scene_637({ + scene = new _$Scene_699({ id: sceneId, graphDiv: gd, container: gd.querySelector('.gl-container'), @@ -122296,14 +123134,14 @@ _$gl3d_627.plot = function plotGl3d(gd) { // save 'initial' camera settings for modebar button if(!scene.cameraInitial) { - scene.cameraInitial = _$lib_539.extendDeep({}, sceneLayout.camera); + scene.cameraInitial = _$lib_601.extendDeep({}, sceneLayout.camera); } scene.plot(fullSceneData, fullLayout, gd.layout); } }; -_$gl3d_627.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$gl3d_689.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldSceneKeys = oldFullLayout._subplots[GL3D] || []; for(var i = 0; i < oldSceneKeys.length; i++) { @@ -122321,7 +123159,7 @@ _$gl3d_627.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayo } }; -_$gl3d_627.toSVG = function(gd) { +_$gl3d_689.toSVG = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots[GL3D]; var size = fullLayout._size; @@ -122335,7 +123173,7 @@ _$gl3d_627.toSVG = function(gd) { var image = fullLayout._glimages.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, x: size.l + size.w * domain.x[0], y: size.t + size.h * (1 - domain.y[1]), @@ -122349,7 +123187,7 @@ _$gl3d_627.toSVG = function(gd) { }; // clean scene ids, 'scene1' -> 'scene' -_$gl3d_627.cleanId = function cleanId(id) { +_$gl3d_689.cleanId = function cleanId(id) { if(!id.match(/^scene[0-9]*$/)) return; var sceneNum = id.substr(5); @@ -122358,7 +123196,7 @@ _$gl3d_627.cleanId = function cleanId(id) { return SCENE + sceneNum; }; -_$gl3d_627.updateFx = function(fullLayout) { +_$gl3d_689.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots[GL3D]; for(var i = 0; i < subplotIds.length; i++) { @@ -122367,7 +123205,7 @@ _$gl3d_627.updateFx = function(fullLayout) { } }; -var _$attributes_936 = {}; +var _$attributes_1007 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -122378,13 +123216,13 @@ var _$attributes_936 = {}; 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; -var __extendFlat_936 = _$extend_528.extendFlat; -var __overrideAll_936 = _$edit_types_569.overrideAll; +var __extendFlat_1007 = _$extend_590.extendFlat; +var __overrideAll_1007 = _$edit_types_632.overrideAll; function makeContourProjAttr(axLetter) { return { @@ -122421,7 +123259,7 @@ function makeContourAttr(axLetter) { color: { valType: 'color', role: 'style', - dflt: _$color_411.defaultLine, + dflt: _$color_473.defaultLine, description: 'Sets the color of the contour lines.' }, usecolormap: { @@ -122454,7 +123292,7 @@ function makeContourAttr(axLetter) { highlightcolor: { valType: 'color', role: 'style', - dflt: _$color_411.defaultLine, + dflt: _$color_473.defaultLine, description: 'Sets the color of the highlighted contour lines.' }, highlightwidth: { @@ -122468,7 +123306,7 @@ function makeContourAttr(axLetter) { }; } -var __attrs_936 = _$attributes_936 = __overrideAll_936({ +var __attrs_1007 = _$attributes_1007 = __overrideAll_1007({ z: { valType: 'data_array', description: 'Sets the z coordinates.' @@ -122502,15 +123340,15 @@ var __attrs_936 = _$attributes_936 = __overrideAll_936({ ].join(' ') }, - cauto: _$attributes_417.zauto, - cmin: _$attributes_417.zmin, - cmax: _$attributes_417.zmax, - colorscale: _$attributes_417.colorscale, - autocolorscale: __extendFlat_936({}, _$attributes_417.autocolorscale, + cauto: _$attributes_479.zauto, + cmin: _$attributes_479.zmin, + cmax: _$attributes_479.zmax, + colorscale: _$attributes_479.colorscale, + autocolorscale: __extendFlat_1007({}, _$attributes_479.autocolorscale, {dflt: false}), - reversescale: _$attributes_417.reversescale, - showscale: _$attributes_417.showscale, - colorbar: _$attributes_412, + reversescale: _$attributes_479.reversescale, + showscale: _$attributes_479.showscale, + colorbar: _$attributes_474, contours: { x: makeContourAttr('x'), @@ -122612,21 +123450,21 @@ var __attrs_936 = _$attributes_936 = __overrideAll_936({ }, _deprecated: { - zauto: __extendFlat_936({}, _$attributes_417.zauto, { + zauto: __extendFlat_1007({}, _$attributes_479.zauto, { description: 'Obsolete. Use `cauto` instead.' }), - zmin: __extendFlat_936({}, _$attributes_417.zmin, { + zmin: __extendFlat_1007({}, _$attributes_479.zmin, { description: 'Obsolete. Use `cmin` instead.' }), - zmax: __extendFlat_936({}, _$attributes_417.zmax, { + zmax: __extendFlat_1007({}, _$attributes_479.zmax, { description: 'Obsolete. Use `cmax` instead.' }) }, - hoverinfo: __extendFlat_936({}, _$attributes_581.hoverinfo) + hoverinfo: __extendFlat_1007({}, _$attributes_644.hoverinfo) }, 'calc', 'nested'); -__attrs_936.x.editType = __attrs_936.y.editType = __attrs_936.z.editType = 'calc+clearAxisTypes'; +__attrs_1007.x.editType = __attrs_1007.y.editType = __attrs_1007.z.editType = 'calc+clearAxisTypes'; /** * Copyright 2012-2018, Plotly, Inc. @@ -122638,15 +123476,15 @@ __attrs_936.x.editType = __attrs_936.y.editType = __attrs_936.z.editType = 'calc 'use strict'; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_936 = require('../surface/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_1007 = require('../surface/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; -var __extendFlat_814 = _$extend_528.extendFlat; +var __extendFlat_876 = _$extend_590.extendFlat; -var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc', false), { +var _$attributes_876 = __extendFlat_876(_$makeColorScaleAttributes_481('', 'calc', false), { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -122798,7 +123636,7 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc }, // Opacity - opacity: _$attributes_936.opacity, + opacity: _$attributes_1007.opacity, // Flat shaded mode flatshading: { @@ -122813,26 +123651,26 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc }, contour: { - show: __extendFlat_814({}, _$attributes_936.contours.x.show, { + show: __extendFlat_876({}, _$attributes_1007.contours.x.show, { description: [ 'Sets whether or not dynamic contours are shown on hover' ].join(' ') }), - color: _$attributes_936.contours.x.color, - width: _$attributes_936.contours.x.width, + color: _$attributes_1007.contours.x.color, + width: _$attributes_1007.contours.x.width, editType: 'calc' }, - showscale: _$attributes_417.showscale, - colorbar: _$attributes_412, + showscale: _$attributes_479.showscale, + colorbar: _$attributes_474, lightposition: { - x: __extendFlat_814({}, _$attributes_936.lightposition.x, {dflt: 1e5}), - y: __extendFlat_814({}, _$attributes_936.lightposition.y, {dflt: 1e5}), - z: __extendFlat_814({}, _$attributes_936.lightposition.z, {dflt: 0}), + x: __extendFlat_876({}, _$attributes_1007.lightposition.x, {dflt: 1e5}), + y: __extendFlat_876({}, _$attributes_1007.lightposition.y, {dflt: 1e5}), + z: __extendFlat_876({}, _$attributes_1007.lightposition.z, {dflt: 0}), editType: 'calc' }, - lighting: __extendFlat_814({ + lighting: __extendFlat_876({ vertexnormalsepsilon: { valType: 'number', role: 'style', @@ -122852,9 +123690,9 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc description: 'Epsilon for face normals calculation avoids math issues arising from degenerate geometry.' }, editType: 'calc' - }, _$attributes_936.lighting), + }, _$attributes_1007.lighting), - hoverinfo: __extendFlat_814({}, _$attributes_581.hoverinfo, {editType: 'calc'}) + hoverinfo: __extendFlat_876({}, _$attributes_644.hoverinfo, {editType: 'calc'}) }); /** @@ -122867,11 +123705,11 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc 'use strict'; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; -var _$calc_815 = function calc(gd, trace) { +var _$calc_877 = function calc(gd, trace) { if(trace.intensity) { - _$calc_418(trace, trace.intensity, '', 'c'); + _$calc_480(trace, trace.intensity, '', 'c'); } }; @@ -122885,33 +123723,33 @@ var _$calc_815 = function calc(gd, trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_816 = function colorbar(gd, cd) { +var _$colorbar_878 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, cmin = trace.cmin, cmax = trace.cmax, vals = trace.intensity || []; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, cmin, cmax @@ -122926,7 +123764,7 @@ var _$colorbar_816 = function colorbar(gd, cd) { "use strict" -var _$compressExpansion_318 = compressExpansion +var _$compressExpansion_382 = compressExpansion function compressExpansion(e) { var m = e.length @@ -122958,17 +123796,17 @@ function compressExpansion(e) { e.length = top return e } -var _$robustDeterminant_319 = {}; +var _$robustDeterminant_383 = {}; "use strict" -/* removed: var _$twoProduct_358 = require("two-product") */; -/* removed: var _$linearExpansionSum_328 = require("robust-sum") */; -/* removed: var _$scaleLinearExpansion_325 = require("robust-scale") */; -/* removed: var _$compressExpansion_318 = require("robust-compress") */; +/* removed: var _$twoProduct_420 = require("two-product") */; +/* removed: var _$linearExpansionSum_392 = require("robust-sum") */; +/* removed: var _$scaleLinearExpansion_389 = require("robust-scale") */; +/* removed: var _$compressExpansion_382 = require("robust-compress") */; var NUM_EXPANDED = 6 -function __cofactor_319(m, c) { +function __cofactor_383(m, c) { var result = new Array(m.length-1) for(var i=1; i>1 - return ["sum(", __generateSum_319(expr.slice(0, m)), ",", __generateSum_319(expr.slice(m)), ")"].join("") + return ["sum(", __generateSum_383(expr.slice(0, m)), ",", __generateSum_383(expr.slice(m)), ")"].join("") } } -function __determinant_319(m) { +function __determinant_383(m) { if(m.length === 2) { return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") } else { var expr = [] for(var i=0; i 0) { var f = cells[ptr-1] - if(_$compareCells_107(c, f) === 0 && - _$orientation_91(f) !== o) { + if(_$compareCells_108(c, f) === 0 && + _$orientation_92(f) !== o) { ptr -= 1 continue } @@ -123991,26 +124829,26 @@ function reduceCellComplex(cells) { 'use strict' -var _$boundary_330 = __boundary_330 +var _$boundary_394 = __boundary_394 -/* removed: var _$boundary_75 = require('boundary-cells') */; -/* removed: var _$reduceCellComplex_310 = require('reduce-simplicial-complex') */; +/* removed: var _$boundary_76 = require('boundary-cells') */; +/* removed: var _$reduceCellComplex_373 = require('reduce-simplicial-complex') */; -function __boundary_330(cells) { - return _$reduceCellComplex_310(_$boundary_75(cells)) +function __boundary_394(cells) { + return _$reduceCellComplex_373(_$boundary_76(cells)) } -var _$alphaShape_47 = alphaShape +var _$alphaShape_48 = alphaShape -/* removed: var _$alphaComplex_46 = require('alpha-complex') */; -/* removed: var _$boundary_330 = require('simplicial-complex-boundary') */; +/* removed: var _$alphaComplex_47 = require('alpha-complex') */; +/* removed: var _$boundary_394 = require('simplicial-complex-boundary') */; function alphaShape(alpha, points) { - return _$boundary_330(_$alphaComplex_46(alpha, points)) + return _$boundary_394(_$alphaComplex_47(alpha, points)) } "use strict" -var _$convexHull1d_110 = convexHull1d +var _$convexHull1d_111 = convexHull1d function convexHull1d(points) { var lo = 0 @@ -124033,9 +124871,9 @@ function convexHull1d(points) { } 'use strict' -var _$monotoneConvexHull2D_261 = monotoneConvexHull2D +var _$monotoneConvexHull2D_319 = monotoneConvexHull2D -var __orient_261 = _$orientation_323[3] +var __orient_319 = _$orientation_387[3] function monotoneConvexHull2D(points) { var n = points.length @@ -124078,7 +124916,7 @@ function monotoneConvexHull2D(points) { //Insert into lower list var m = lower.length - while(m > 1 && __orient_261( + while(m > 1 && __orient_319( points[lower[m-2]], points[lower[m-1]], p) <= 0) { @@ -124089,7 +124927,7 @@ function monotoneConvexHull2D(points) { //Insert into upper list m = upper.length - while(m > 1 && __orient_261( + while(m > 1 && __orient_319( points[upper[m-2]], points[upper[m-1]], p) >= 0) { @@ -124114,12 +124952,12 @@ function monotoneConvexHull2D(points) { } 'use strict' -var _$convexHull2D_111 = convexHull2D +var _$convexHull2D_112 = convexHull2D -/* removed: var _$monotoneConvexHull2D_261 = require('monotone-convex-hull-2d') */; +/* removed: var _$monotoneConvexHull2D_319 = require('monotone-convex-hull-2d') */; function convexHull2D(points) { - var hull = _$monotoneConvexHull2D_261(points) + var hull = _$monotoneConvexHull2D_319(points) var h = hull.length if(h <= 2) { return [] @@ -124136,9 +124974,9 @@ function convexHull2D(points) { 'use strict' -var _$affineHull_45 = affineHull +var _$affineHull_46 = affineHull -/* removed: var _$orientation_323 = require('robust-orientation') */; +/* removed: var _$orientation_387 = require('robust-orientation') */; function linearlyIndependent(points, d) { var nhull = new Array(d+1) @@ -124153,7 +124991,7 @@ function linearlyIndependent(points, d) { } nhull[j] = x } - var o = _$orientation_323.apply(void 0, nhull) + var o = _$orientation_387.apply(void 0, nhull) if(o) { return true } @@ -124187,10 +125025,10 @@ function affineHull(points) { } 'use strict' -var _$convexHullnD_112 = convexHullnD +var _$convexHullnD_113 = convexHullnD -/* removed: var _$incrementalConvexHull_242 = require('incremental-convex-hull') */; -/* removed: var _$affineHull_45 = require('affine-hull') */; +/* removed: var _$incrementalConvexHull_299 = require('incremental-convex-hull') */; +/* removed: var _$affineHull_46 = require('affine-hull') */; function permute(points, front) { var n = points.length @@ -124232,26 +125070,26 @@ function invPermute(cells, front) { function convexHullnD(points, d) { try { - return _$incrementalConvexHull_242(points, true) + return _$incrementalConvexHull_299(points, true) } catch(e) { //If point set is degenerate, try to find a basis and rerun it - var ah = _$affineHull_45(points) + var ah = _$affineHull_46(points) if(ah.length <= d) { //No basis, no try return [] } var npoints = permute(points, ah) - var nhull = _$incrementalConvexHull_242(npoints, true) + var nhull = _$incrementalConvexHull_299(npoints, true) return invPermute(nhull, ah) } } "use strict" -/* removed: var _$convexHull1d_110 = require('./lib/ch1d') */; -/* removed: var _$convexHull2D_111 = require('./lib/ch2d') */; -/* removed: var _$convexHullnD_112 = require('./lib/chnd') */; +/* removed: var _$convexHull1d_111 = require('./lib/ch1d') */; +/* removed: var _$convexHull2D_112 = require('./lib/ch2d') */; +/* removed: var _$convexHullnD_113 = require('./lib/chnd') */; -var _$convexHull_109 = convexHull +var _$convexHull_110 = convexHull function convexHull(points) { var n = points.length @@ -124264,13 +125102,13 @@ function convexHull(points) { if(d === 0) { return [] } else if(d === 1) { - return _$convexHull1d_110(points) + return _$convexHull1d_111(points) } else if(d === 2) { - return _$convexHull2D_111(points) + return _$convexHull2D_112(points) } - return _$convexHullnD_112(points, d) + return _$convexHullnD_113(points, d) } -var _$colorScale_104={ +var _$colorScale_105={ "jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}], "hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}], @@ -124362,10 +125200,10 @@ var _$colorScale_104={ "cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}] }; -function __lerp_253(v0, v1, t) { +function __lerp_310(v0, v1, t) { return v0*(1-t)+v1*t } -var _$lerp_253 = __lerp_253 +var _$lerp_310 = __lerp_310 /* * Ben Postlethwaite * January 2013 @@ -124373,10 +125211,10 @@ var _$lerp_253 = __lerp_253 */ 'use strict'; -/* removed: var _$colorScale_104 = require('./colorScale'); */; -/* removed: var _$lerp_253 = require('lerp') */; +/* removed: var _$colorScale_105 = require('./colorScale'); */; +/* removed: var _$lerp_310 = require('lerp') */; -var _$createColormap_105 = createColormap; +var _$createColormap_106 = createColormap; function createColormap (spec) { /* @@ -124401,11 +125239,11 @@ function createColormap (spec) { if (typeof colormap === 'string') { colormap = colormap.toLowerCase(); - if (!_$colorScale_104[colormap]) { + if (!_$colorScale_105[colormap]) { throw Error(colormap + ' not a supported colorscale'); } - cmap = _$colorScale_104[colormap]; + cmap = _$colorScale_105[colormap]; } else if (Array.isArray(colormap)) { cmap = colormap.slice(); @@ -124473,10 +125311,10 @@ function createColormap (spec) { for (var j = 0; j < nsteps; j++) { var amt = j / nsteps colors.push([ - Math.round(_$lerp_253(fromrgba[0], torgba[0], amt)), - Math.round(_$lerp_253(fromrgba[1], torgba[1], amt)), - Math.round(_$lerp_253(fromrgba[2], torgba[2], amt)), - _$lerp_253(fromrgba[3], torgba[3], amt) + Math.round(_$lerp_310(fromrgba[0], torgba[0], amt)), + Math.round(_$lerp_310(fromrgba[1], torgba[1], amt)), + Math.round(_$lerp_310(fromrgba[2], torgba[2], amt)), + _$lerp_310(fromrgba[3], torgba[3], amt) ]) } } @@ -124516,11 +125354,11 @@ function rgbaStr (rgba) { 'use strict' -var _$barycentric_53 = barycentric +var _$barycentric_54 = barycentric -/* removed: var _$linsolve_322 = require('robust-linear-solve') */; +/* removed: var _$linsolve_386 = require('robust-linear-solve') */; -function __reduce_53(x) { +function __reduce_54(x) { var r = 0 for(var i=0; i 0.001) { return null } - return [closestIndex, __interpolate_185(simplex, weights), weights] -} -var _$shaders_186 = {}; -/* removed: var _$browser_238 = require('glslify') */; - -var triVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\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\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}"]) -var triFragSrc = _$browser_238(["precision mediump 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\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\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 = cookTorranceSpecular(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}"]) -var edgeVertSrc = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]) -var pointVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]) -var pickPointVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]) - -_$shaders_186.meshShader = { + return [closestIndex, __interpolate_242(simplex, weights), weights] +} +var _$shaders_243 = {}; +/* removed: var _$browser_295 = require('glslify') */; + +var triVertSrc = _$browser_295(["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;\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\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}\n"]) +var triFragSrc = _$browser_295(["#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\nvec3 normals(vec3 pos) {\n vec3 fdx = dFdx(pos);\n vec3 fdy = dFdy(pos);\n return normalize(cross(fdx, fdy));\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\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(any(lessThan(f_data, clipBounds[0])) ||\n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n vec3 normal = normals(f_data);\n\n if (\n dot(N, normal) < 0.0\n ) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}\n"]) +var edgeVertSrc = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]) +var pointVertSrc = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]) +var pickPointVertSrc = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]) + +_$shaders_243.meshShader = { vertex: triVertSrc, fragment: triFragSrc, attributes: [ @@ -124880,7 +125718,7 @@ _$shaders_186.meshShader = { {name: 'uv', type: 'vec2'} ] } -_$shaders_186.wireShader = { +_$shaders_243.wireShader = { vertex: edgeVertSrc, fragment: edgeFragSrc, attributes: [ @@ -124889,7 +125727,7 @@ _$shaders_186.wireShader = { {name: 'uv', type: 'vec2'} ] } -_$shaders_186.pointShader = { +_$shaders_243.pointShader = { vertex: pointVertSrc, fragment: pointFragSrc, attributes: [ @@ -124899,7 +125737,7 @@ _$shaders_186.pointShader = { {name: 'pointSize', type: 'float'} ] } -_$shaders_186.pickShader = { +_$shaders_243.pickShader = { vertex: pickVertSrc, fragment: pickFragSrc, attributes: [ @@ -124907,7 +125745,7 @@ _$shaders_186.pickShader = { {name: 'id', type: 'vec4'} ] } -_$shaders_186.pointPickShader = { +_$shaders_243.pointPickShader = { vertex: pickPointVertSrc, fragment: pickFragSrc, attributes: [ @@ -124916,7 +125754,7 @@ _$shaders_186.pointPickShader = { {name: 'id', type: 'vec4'} ] } -_$shaders_186.contourShader = { +_$shaders_243.contourShader = { vertex: contourVertSrc, fragment: contourFragSrc, attributes: [ @@ -124924,12 +125762,12 @@ _$shaders_186.contourShader = { ] } -var _$normals_280 = {}; +var _$normals_338 = {}; var DEFAULT_NORMALS_EPSILON = 1e-6; var DEFAULT_FACE_EPSILON = 1e-6; //Estimate the vertex normals of a mesh -_$normals_280.vertexNormals = function(faces, positions, specifiedEpsilon) { +_$normals_338.vertexNormals = function(faces, positions, specifiedEpsilon) { var N = positions.length; var normals = new Array(N); @@ -125006,7 +125844,7 @@ _$normals_280.vertexNormals = function(faces, positions, specifiedEpsilon) { } //Compute face normals of a mesh -_$normals_280.faceNormals = function(faces, positions, specifiedEpsilon) { +_$normals_338.faceNormals = function(faces, positions, specifiedEpsilon) { var N = faces.length; var normals = new Array(N); @@ -125051,28 +125889,28 @@ _$normals_280.faceNormals = function(faces, positions, specifiedEpsilon) { "use strict" -/* removed: var _$pool_360 = require("typedarray-pool") */; +/* removed: var _$pool_422 = require("typedarray-pool") */; var INSERTION_SORT_THRESHOLD = 32 function getMallocFree(dtype) { switch(dtype) { case "uint8": - return [_$pool_360.mallocUint8, _$pool_360.freeUint8] + return [_$pool_422.mallocUint8, _$pool_422.freeUint8] case "uint16": - return [_$pool_360.mallocUint16, _$pool_360.freeUint16] + return [_$pool_422.mallocUint16, _$pool_422.freeUint16] case "uint32": - return [_$pool_360.mallocUint32, _$pool_360.freeUint32] + return [_$pool_422.mallocUint32, _$pool_422.freeUint32] case "int8": - return [_$pool_360.mallocInt8, _$pool_360.freeInt8] + return [_$pool_422.mallocInt8, _$pool_422.freeInt8] case "int16": - return [_$pool_360.mallocInt16, _$pool_360.freeInt16] + return [_$pool_422.mallocInt16, _$pool_422.freeInt16] case "int32": - return [_$pool_360.mallocInt32, _$pool_360.freeInt32] + return [_$pool_422.mallocInt32, _$pool_422.freeInt32] case "float32": - return [_$pool_360.mallocFloat, _$pool_360.freeFloat] + return [_$pool_422.mallocFloat, _$pool_422.freeFloat] case "float64": - return [_$pool_360.mallocDouble, _$pool_360.freeDouble] + return [_$pool_422.mallocDouble, _$pool_422.freeDouble] default: return null } @@ -125776,31 +126614,31 @@ function compileSort(order, dtype) { return result(insertionSort, quickSort) } -var _$compileSort_274 = compileSort +var _$compileSort_332 = compileSort "use strict" -/* removed: var _$compileSort_274 = require("./lib/compile_sort.js") */; -var __CACHE_275 = {} +/* removed: var _$compileSort_332 = require("./lib/compile_sort.js") */; +var __CACHE_333 = {} function sort(array) { var order = array.order var dtype = array.dtype var typeSig = [order, dtype ] var typeName = typeSig.join(":") - var compiled = __CACHE_275[typeName] + var compiled = __CACHE_333[typeName] if(!compiled) { - __CACHE_275[typeName] = compiled = _$compileSort_274(order, dtype) + __CACHE_333[typeName] = compiled = _$compileSort_332(order, dtype) } compiled(array) return array } -var _$sort_275 = sort +var _$sort_333 = sort 'use strict' -var _$createTable_255 = createTable +var _$createTable_312 = createTable -/* removed: var _$convexHull_109 = require('convex-hull') */; +/* removed: var _$convexHull_110 = require('convex-hull') */; function constructVertex(d, a, b) { var x = new Array(d) @@ -125836,7 +126674,7 @@ function constructCell(dimension, mask) { } //Preprocess points so first d+1 points are linearly independent - var hull = _$convexHull_109(points) + var hull = _$convexHull_110(points) var faces = [] i_loop: for(var i=0; i= 1 } -__proto_187.isTransparent = function() { +__proto_244.isTransparent = function() { return this.opacity < 1 } -__proto_187.pickSlots = 1 +__proto_244.pickSlots = 1 -__proto_187.setPickBase = function(id) { +__proto_244.setPickBase = function(id) { this.pickId = id } function genColormap(param) { - var colors = _$createColormap_105({ + var colors = _$createColormap_106({ colormap: param , nshades: 256 , format: 'rgba' @@ -126279,7 +127118,7 @@ function genColormap(param) { result[4*i+3] = c[3]*255 } - return _$wrappedNDArrayCtor_277(result, [256,256,4], [4,0,1]) + return _$wrappedNDArrayCtor_335(result, [256,256,4], [4,0,1]) } function unpackIntensity(cells, numVerts, cellIntensity) { @@ -126306,17 +127145,17 @@ function takeZComponent(array) { return result } -__proto_187.highlight = function(selection) { +__proto_244.highlight = function(selection) { if(!selection || !this.contourEnable) { this.contourCount = 0 return } - var level = _$extractContour_331(this.cells, this.intensity, selection.intensity) + var level = _$extractContour_395(this.cells, this.intensity, selection.intensity) var cells = level.cells var vertexIds = level.vertexIds var vertexWeights = level.vertexWeights var numCells = cells.length - var result = _$pool_360.mallocFloat32(2 * 3 * numCells) + var result = _$pool_422.mallocFloat32(2 * 3 * numCells) var ptr = 0 for(var i=0; i 0) { - cells = _$alphaShape_47(data.alphahull, positions); + cells = _$alphaShape_48(data.alphahull, positions); } else { var d = ['x', 'y', 'z'].indexOf(data.delaunayaxis); - cells = _$triangulate_129(positions.map(function(c) { + cells = _$triangulate_132(positions.map(function(c) { return [c[(d + 1) % 3], c[(d + 2) % 3]]; })); } @@ -127266,7 +128110,7 @@ __proto_817.update = function(data) { faceNormalsEpsilon: data.lighting.facenormalsepsilon, opacity: data.opacity, contourEnable: data.contour.show, - contourColor: _$str2RgbaArray_561(data.contour.color).slice(0, 3), + contourColor: _$str2RgbaArray_624(data.contour.color).slice(0, 3), contourWidth: data.contour.width, useFacetNormals: data.flatshading }; @@ -127287,21 +128131,21 @@ __proto_817.update = function(data) { } else { this.color = data.color; - config.meshColor = _$str2RgbaArray_561(data.color); + config.meshColor = _$str2RgbaArray_624(data.color); } // Update mesh this.mesh.update(config); }; -__proto_817.dispose = function() { +__proto_879.dispose = function() { this.scene.glplot.remove(this.mesh); this.mesh.dispose(); }; function createMesh3DTrace(scene, data) { var gl = scene.glplot.gl; - var mesh = _$createSimplicialMesh_187({gl: gl}); + var mesh = _$createSimplicialMesh_244({gl: gl}); var result = new Mesh3DTrace(scene, mesh, data.uid); mesh._trace = result; result.update(data); @@ -127309,7 +128153,7 @@ function createMesh3DTrace(scene, data) { return result; } -var _$createMesh3DTrace_817 = createMesh3DTrace; +var _$createMesh3DTrace_879 = createMesh3DTrace; /** * Copyright 2012-2018, Plotly, Inc. @@ -127322,14 +128166,14 @@ var _$createMesh3DTrace_817 = createMesh3DTrace; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_814 = require('./attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_876 = require('./attributes'); */; -var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_880 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_814, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_876, attr, dflt); } // read in face/vertex properties @@ -127337,7 +128181,7 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol var ret = array.map(function(attr) { var result = coerce(attr); - if(result && _$lib_539.isArrayOrTypedArray(result)) return result; + if(result && _$lib_601.isArrayOrTypedArray(result)) return result; return null; }); @@ -127361,7 +128205,7 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol }); } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); // Coerce remaining properties @@ -127389,7 +128233,7 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol if('intensity' in traceIn) { coerce('intensity'); - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'}); + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'}); } else { traceOut.showscale = false; @@ -127414,15 +128258,15 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol var Mesh3D = {}; -Mesh3D.attributes = _$attributes_814; -Mesh3D.supplyDefaults = _$supplyDefaults_818; -Mesh3D.calc = _$calc_815; -Mesh3D.colorbar = _$colorbar_816; -Mesh3D.plot = _$createMesh3DTrace_817; +Mesh3D.attributes = _$attributes_876; +Mesh3D.supplyDefaults = _$supplyDefaults_880; +Mesh3D.calc = _$calc_877; +Mesh3D.colorbar = _$colorbar_878; +Mesh3D.plot = _$createMesh3DTrace_879; Mesh3D.moduleType = 'trace'; Mesh3D.name = 'mesh3d', -Mesh3D.basePlotModule = _$gl3d_627; +Mesh3D.basePlotModule = _$gl3d_689; Mesh3D.categories = ['gl3d']; Mesh3D.meta = { description: [ @@ -127435,7 +128279,7 @@ Mesh3D.meta = { ].join(' ') }; -var _$Mesh3D_819 = Mesh3D; +var _$Mesh3D_881 = Mesh3D; /** * Copyright 2012-2018, Plotly, Inc. @@ -127447,7 +128291,7 @@ var _$Mesh3D_819 = Mesh3D; 'use strict'; -var _$mesh3d_21 = _$Mesh3D_819; +var _$mesh3d_21 = _$Mesh3D_881; /** * Copyright 2012-2018, Plotly, Inc. @@ -127460,21 +128304,17 @@ var _$mesh3d_21 = _$Mesh3D_819; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleOHLC_825 = require('./ohlc_defaults'); */; -/* removed: var _$handleDirectionDefaults_822 = require('./direction_defaults'); */; -/* removed: var _$attributes_820 = require('./attributes'); */; -/* removed: var _$helpers_823 = require('./helpers'); */; - -var _$supplyDefaults_821 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - _$helpers_823.pushDummyTransformOpts(traceIn, traceOut); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleOHLC_887 = require('./ohlc_defaults'); */; +/* removed: var _$attributes_882 = require('./attributes'); */; +var _$supplyDefaults_884 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_820, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_882, attr, dflt); } - var len = _$handleOHLC_825(traceIn, traceOut, coerce, layout); - if(len === 0) { + var len = _$handleOHLC_887(traceIn, traceOut, coerce, layout); + if(!len) { traceOut.visible = false; return; } @@ -127482,22 +128322,21 @@ var _$supplyDefaults_821 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('line.width'); coerce('line.dash'); - __handleDirection_821(traceIn, traceOut, coerce, 'increasing'); - __handleDirection_821(traceIn, traceOut, coerce, 'decreasing'); + __handleDirection_884(traceIn, traceOut, coerce, 'increasing'); + __handleDirection_884(traceIn, traceOut, coerce, 'decreasing'); coerce('text'); coerce('tickwidth'); -}; -function __handleDirection_821(traceIn, traceOut, coerce, direction) { - _$handleDirectionDefaults_822(traceIn, traceOut, coerce, direction); + layout._requestRangeslider[traceOut.xaxis] = true; +}; +function __handleDirection_884(traceIn, traceOut, coerce, direction) { coerce(direction + '.line.color'); coerce(direction + '.line.width', traceOut.line.width); coerce(direction + '.line.dash', traceOut.line.dash); } -var _$transform_826 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -127506,264 +128345,100 @@ var _$transform_826 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var ____826 = _$lib_539._; -/* removed: var _$helpers_823 = require('./helpers'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -_$transform_826.moduleType = 'transform'; +var _$plot_888 = function plot(gd, plotinfo, cdOHLC) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -_$transform_826.name = 'ohlc'; + var ohlcLayer = plotinfo.plot.select('g.ohlclayer'); -_$transform_826.attributes = {}; + var traces = ohlcLayer.selectAll('g.trace') + .data(cdOHLC, function(d) { return d[0].trace.uid; }); -_$transform_826.supplyDefaults = function(transformIn, traceOut, layout, traceIn) { - _$helpers_823.clearEphemeralTransformOpts(traceIn); - _$helpers_823.copyOHLC(transformIn, traceOut); + traces.enter().append('g') + .attr('class', 'trace ohlc'); - return transformIn; -}; + traces.exit().remove(); -_$transform_826.transform = function transform(dataIn, state) { - var dataOut = []; + traces.order(); - for(var i = 0; i < dataIn.length; i++) { - var traceIn = dataIn[i]; + traces.each(function(d) { + var cd0 = d[0]; + var t = cd0.t; + var trace = cd0.trace; + var sel = _$d3_130.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; - if(traceIn.type !== 'ohlc') { - dataOut.push(traceIn); - continue; + if(trace.visible !== true || t.empty) { + sel.remove(); + return; } - dataOut.push( - __makeTrace_826(traceIn, state, 'increasing'), - __makeTrace_826(traceIn, state, 'decreasing') - ); - } - - _$helpers_823.addRangeSlider(dataOut, state.layout); - - return dataOut; -}; - -function __makeTrace_826(traceIn, state, direction) { - var traceOut = { - type: 'scatter', - mode: 'lines', - connectgaps: false, - - visible: traceIn.visible, - opacity: traceIn.opacity, - xaxis: traceIn.xaxis, - yaxis: traceIn.yaxis, - - hoverinfo: __makeHoverInfo_826(traceIn), - transforms: _$helpers_823.makeTransform(traceIn, state, direction) - }; - - // the rest of below may not have been coerced + var tickLen = t.tickLen; - var directionOpts = traceIn[direction]; + var paths = sel.selectAll('path').data(_$lib_601.identity); - if(directionOpts) { - _$lib_539.extendFlat(traceOut, { + paths.enter().append('path'); - // to make autotype catch date axes soon!! - x: traceIn.x || [0], - xcalendar: traceIn.xcalendar, + paths.exit().remove(); - // concat low and high to get correct autorange - y: [].concat(traceIn.low).concat(traceIn.high), + paths.attr('d', function(d) { + var x = xa.c2p(d.pos, true); + var xo = xa.c2p(d.pos - tickLen, true); + var xc = xa.c2p(d.pos + tickLen, true); - text: traceIn.text, + var yo = ya.c2p(d.o, true); + var yh = ya.c2p(d.h, true); + var yl = ya.c2p(d.l, true); + var yc = ya.c2p(d.c, true); - name: directionOpts.name, - showlegend: directionOpts.showlegend, - line: directionOpts.line + return 'M' + xo + ',' + yo + 'H' + x + + 'M' + x + ',' + yh + 'V' + yl + + 'M' + xc + ',' + yc + 'H' + x; }); - } - - return traceOut; -} - -// Let scatter hoverPoint format 'x' coordinates, if desired. -// -// Note that, this solution isn't perfect: it shows open and close -// values at slightly different 'x' coordinates then the rest of the -// segments, but is for more robust than calling `Axes.tickText` during -// calcTransform. -// -// A future iteration should perhaps try to add a hook for transforms in -// the hoverPoints handlers. -function __makeHoverInfo_826(traceIn) { - var hoverinfo = traceIn.hoverinfo; - - if(hoverinfo === 'all') return 'x+text+name'; - - var parts = hoverinfo.split('+'), - indexOfY = parts.indexOf('y'), - indexOfText = parts.indexOf('text'); - - if(indexOfY !== -1) { - parts.splice(indexOfY, 1); - - if(indexOfText === -1) parts.push('text'); - } - - return parts.join('+'); -} - -_$transform_826.calcTransform = function calcTransform(gd, trace, opts) { - var direction = opts.direction, - filterFn = _$helpers_823.getFilterFn(direction); - - var xa = _$axis_ids_587.getFromTrace(gd, trace, 'x'), - ya = _$axis_ids_587.getFromTrace(gd, trace, 'y'), - tickWidth = convertTickWidth(gd, xa, trace); - - var open = trace.open, - high = trace.high, - low = trace.low, - close = trace.close, - textIn = trace.text; - - var openName = ____826(gd, 'open:') + ' '; - var highName = ____826(gd, 'high:') + ' '; - var lowName = ____826(gd, 'low:') + ' '; - var closeName = ____826(gd, 'close:') + ' '; - - var len = open.length, - x = [], - y = [], - textOut = []; - - var appendX; - if(trace._fullInput.x) { - appendX = function(i) { - var xi = trace.x[i], - xcalendar = trace.xcalendar, - xcalc = xa.d2c(xi, 0, xcalendar); - - x.push( - xa.c2d(xcalc - tickWidth, 0, xcalendar), - xi, xi, xi, xi, - xa.c2d(xcalc + tickWidth, 0, xcalendar), - null); - }; - } - else { - appendX = function(i) { - x.push( - i - tickWidth, - i, i, i, i, - i + tickWidth, - null); - }; - } - - var appendY = function(o, h, l, c) { - y.push(o, o, h, l, c, c, null); - }; - - var format = function(ax, val) { - return _$axes_584.tickText(ax, ax.c2l(val), 'hover').text; - }; - - var hoverinfo = trace._fullInput.hoverinfo, - hoverParts = hoverinfo.split('+'), - hasAll = hoverinfo === 'all', - hasY = hasAll || hoverParts.indexOf('y') !== -1, - hasText = hasAll || hoverParts.indexOf('text') !== -1; - - var getTextItem = Array.isArray(textIn) ? - function(i) { return textIn[i] || ''; } : - function() { return textIn; }; - - var appendText = function(i, o, h, l, c) { - var t = []; - - if(hasY) { - t.push(openName + format(ya, o)); - t.push(highName + format(ya, h)); - t.push(lowName + format(ya, l)); - t.push(closeName + format(ya, c)); - } - - if(hasText) t.push(getTextItem(i)); - - var _t = t.join('
'); - - textOut.push(_t, _t, _t, _t, _t, _t, null); - }; - - for(var i = 0; i < len; i++) { - if(filterFn(open[i], close[i]) && _$fastIsnumeric_139(high[i]) && _$fastIsnumeric_139(low[i])) { - appendX(i); - appendY(open[i], high[i], low[i], close[i]); - appendText(i, open[i], high[i], low[i], close[i]); - } - } - - trace.x = x; - trace.y = y; - trace.text = textOut; - trace._length = x.length; + }); }; -function convertTickWidth(gd, xa, trace) { - var fullInput = trace._fullInput, - tickWidth = fullInput.tickwidth, - minDiff = fullInput._minDiff; - - if(!minDiff) { - var fullData = gd._fullData, - ohlcTracesOnThisXaxis = []; - - minDiff = Infinity; - - // find min x-coordinates difference of all traces - // attached to this x-axis and stash the result - - var i; - - for(i = 0; i < fullData.length; i++) { - var _trace = fullData[i]._fullInput; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(_trace.type === 'ohlc' && - _trace.visible === true && - _trace.xaxis === xa._id - ) { - ohlcTracesOnThisXaxis.push(_trace); +'use strict'; - // - _trace.x may be undefined here, - // it is filled later in calcTransform - // - // - handle trace of length 1 separately. +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$color_473 = require('../../components/color'); */; - if(_trace.x && _trace.x.length > 1) { - var xcalc = _$lib_539.simpleMap(_trace.x, xa.d2c, 0, trace.xcalendar), - _minDiff = _$lib_539.distinctVals(xcalc).minDiff; - minDiff = Math.min(minDiff, _minDiff); - } - } - } +var _$style_890 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.ohlclayer').selectAll('g.trace'); - // if minDiff is still Infinity here, set it to 1 - if(minDiff === Infinity) minDiff = 1; + s.style('opacity', function(d) { + return d[0].trace.opacity; + }); - for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) { - ohlcTracesOnThisXaxis[i]._minDiff = minDiff; - } - } + s.each(function(d) { + var trace = d[0].trace; - return minDiff * tickWidth; -} + _$d3_130.select(this).selectAll('path').each(function(di) { + var dirLine = trace[di.dir].line; + _$d3_130.select(this) + .style('fill', 'none') + .call(_$color_473.stroke, dirLine.color) + .call(_$drawing_498.dashLine, dirLine.dash, dirLine.width) + // TODO: custom selection style for OHLC + .style('opacity', trace.selectedpoints && !di.selected ? 0.3 : 1); + }); + }); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -127775,13 +128450,11 @@ function convertTickWidth(gd, xa, trace) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - -var _$ohlc_824 = { +var _$ohlc_886 = { moduleType: 'trace', name: 'ohlc', - basePlotModule: _$cartesian_595, - categories: ['cartesian', 'showLegend'], + basePlotModule: _$cartesian_658, + categories: ['cartesian', 'svg', 'showLegend'], meta: { description: [ 'The ohlc (short for Open-High-Low-Close) is a style of financial chart describing', @@ -127793,18 +128466,20 @@ var _$ohlc_824 = { 'Sample points where the close value is higher (lower) then the open', 'value are called increasing (decreasing).', - 'By default, increasing candles are drawn in green whereas', + 'By default, increasing items are drawn in green whereas', 'decreasing are drawn in red.' ].join(' ') }, - attributes: _$attributes_820, - supplyDefaults: _$supplyDefaults_821, + attributes: _$attributes_882, + supplyDefaults: _$supplyDefaults_884, + calc: _$calc_883.calc, + plot: _$plot_888, + style: _$style_890, + hoverPoints: _$hoverPoints_885, + selectPoints: _$selectPoints_889 }; -_$registry_668.register(_$Scatter_874); -_$registry_668.register(_$transform_826); - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -127815,7 +128490,7 @@ _$registry_668.register(_$transform_826); 'use strict'; -var _$ohlc_22 = _$ohlc_824; +var _$ohlc_22 = _$ohlc_886; /** * Copyright 2012-2018, Plotly, Inc. @@ -127827,29 +128502,29 @@ var _$ohlc_22 = _$ohlc_824; 'use strict'; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$scales_430 = require('../../components/colorscale/scales'); */; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __domainAttrs_827 = _$domain_610.attributes; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$scales_492 = require('../../components/colorscale/scales'); */; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __domainAttrs_891 = _$domain_672.attributes; -/* removed: var _$extend_528 = require('../../lib/extend'); */; -var __extendDeepAll_827 = _$extend_528.extendDeepAll; -var __extendFlat_827 = _$extend_528.extendFlat; +/* removed: var _$extend_590 = require('../../lib/extend'); */; +var __extendDeepAll_891 = _$extend_590.extendDeepAll; +var __extendFlat_891 = _$extend_590.extendFlat; -var _$attributes_827 = { - domain: __domainAttrs_827({name: 'parcoords', trace: true, editType: 'calc'}), +var _$attributes_891 = { + domain: __domainAttrs_891({name: 'parcoords', trace: true, editType: 'calc'}), - labelfont: _$font_attributes_611({ + labelfont: _$font_attributes_673({ editType: 'calc', description: 'Sets the font for the `dimension` labels.' }), - tickfont: _$font_attributes_611({ + tickfont: _$font_attributes_673({ editType: 'calc', description: 'Sets the font for the `dimension` tick values.' }), - rangefont: _$font_attributes_611({ + rangefont: _$font_attributes_673({ editType: 'calc', description: 'Sets the font for the `dimension` range values.' }), @@ -127862,8 +128537,10 @@ var _$attributes_827 = { editType: 'calc', description: 'The shown name of the dimension.' }, - tickvals: __extendFlat_827({}, _$layout_attributes_596.tickvals, {editType: 'calc'}), - ticktext: __extendFlat_827({}, _$layout_attributes_596.ticktext, {editType: 'calc'}), + // TODO: better way to determine ordinal vs continuous axes, + // so users can use tickvals/ticktext with a continuous axis. + tickvals: __extendFlat_891({}, _$layout_attributes_659.tickvals, {editType: 'calc'}), + ticktext: __extendFlat_891({}, _$layout_attributes_659.ticktext, {editType: 'calc'}), tickformat: { valType: 'string', dflt: '3s', @@ -127898,6 +128575,8 @@ var _$attributes_827 = { constraintrange: { valType: 'info_array', role: 'info', + freeLength: true, + dimensions: '1-2', items: [ {valType: 'number', editType: 'calc'}, {valType: 'number', editType: 'calc'} @@ -127905,9 +128584,17 @@ var _$attributes_827 = { editType: 'calc', description: [ 'The domain range to which the filter on the dimension is constrained. Must be an array', - 'of `[fromValue, toValue]` with finite numbers as elements.' + 'of `[fromValue, toValue]` with `fromValue <= toValue`, or if `multiselect` is not', + 'disabled, you may give an array of arrays, where each inner array is `[fromValue, toValue]`.' ].join(' ') }, + multiselect: { + valType: 'boolean', + dflt: true, + role: 'info', + editType: 'calc', + description: 'Do we allow multiple selection ranges or just a single range?' + }, values: { valType: 'data_array', role: 'info', @@ -127922,14 +128609,14 @@ var _$attributes_827 = { description: 'The dimensions (variables) of the parallel coordinates chart. 2..60 dimensions are supported.' }, - line: __extendFlat_827( + line: __extendFlat_891( // the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white) // autocolorscale therefore defaults to false too, to avoid being overridden by the blue-white-red autocolor palette - __extendDeepAll_827( - _$makeColorScaleAttributes_419('line', 'calc'), + __extendDeepAll_891( + _$makeColorScaleAttributes_481('line', 'calc'), { - colorscale: {dflt: _$scales_430.Viridis}, + colorscale: {dflt: _$scales_492.Viridis}, autocolorscale: { dflt: false, description: [ @@ -127956,14 +128643,14 @@ var _$attributes_827 = { 'Determines whether or not a colorbar is displayed.' ].join(' ') }, - colorbar: _$attributes_412, + colorbar: _$attributes_474, editType: 'calc' } ) }; -var _$regl_315 = { exports: {} }; -(function(da,ea){"object"===typeof _$regl_315.exports&&"undefined"!=="object"?_$regl_315.exports=ea():"function"===typeof define&&define.amd?define(ea):da.createREGL=ea()})(this,function(){function da(a,b){this.id=vb++;this.type=a;this.data=b}function ea(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1= 0; i--) { + var aNext = a[i]; + + // very close to the previous - snap down to it + if(v > closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev); + if(v > aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev); + + aPrevPrev = aPrev; + aPrev = 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', -_$constants_896.bar.captureWidth / 2) + .attr('width', _$constants_896.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 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 = _$constants_896.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_130.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_130.select(root).selectAll('.highlight, .highlight-shadow'); + var barToStyle = tweenCallback ? bar.transition().duration(_$constants_896.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 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_130.event.preventDefault(); + if(!d.parent.inBrushDrag) { + var y = d.height - _$d3_130.mouse(this)[1] - 2 * _$constants_896.verticalPadding; + var interval = getInterval(d, y); + + var cursor = 'crosshair'; + if(interval.clickableOrdinalRange) cursor = 'pointer'; + else if(interval.region) cursor = interval.region + '-resize'; + _$d3_130.select(document.body) + .style('cursor', cursor); + } + }) + .on('mouseleave', function(d) { + if(!d.parent.inBrushDrag) clearCursor(); + }) + .call(_$d3_130.behavior.drag() + .on('dragstart', function(d) { + _$d3_130.event.sourceEvent.stopPropagation(); + var y = d.height - _$d3_130.mouse(this)[1] - 2 * _$constants_896.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] - _$constants_896.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(); + }) + .on('drag', function(d) { + _$d3_130.event.sourceEvent.stopPropagation(); + var y = d.height - _$d3_130.mouse(this)[1] - 2 * _$constants_896.verticalPadding; + var s = d.brush.svgBrush; + s.wasDragged = 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); + } + + // take care of the parcoords axis height constraint: bar can't breach it + var bottomViolation = Math.max(0, -s.newExtent[0]); + var topViolation = Math.max(0, s.newExtent[1] - 1); + s.newExtent[0] += bottomViolation; + s.newExtent[1] -= topViolation; + if(s.grabbingBar) { + // in case of bar dragging (non-resizing interaction, unlike north/south resize or new bar creation) + // the constraint adjustment must apply to the other end of the bar as well, otherwise it'd + // shorten or lengthen + s.newExtent[1] += bottomViolation; + s.newExtent[0] -= topViolation; + } + + d.brush.filterSpecified = true; + s.extent = s.stayingIntervals.concat([s.newExtent]); + s.brushCallback(d); + renderHighlight(this.parentNode); + }) + .on('dragend', function(d) { + var e = _$d3_130.event; + e.sourceEvent.stopPropagation(); + var brush = d.brush; + var filter = brush.filter; + var s = brush.svgBrush; + 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(this.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 = [ + ordinalScaleSnapLo(a, s.newExtent[0], s.stayingIntervals), + ordinalScaleSnapHi(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(this.parentNode, mergeIntervals); + } + else { + // if no new interval, don't animate, just redraw the highlight immediately + mergeIntervals(); + renderHighlight(this.parentNode); + } + } else { + mergeIntervals(); // merging intervals immediately + } + s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []); + }) + ); +} + +function startAsc(a, b) { return a[0] - b[0]; } + +function renderAxisBrush(axisBrush) { + + var background = axisBrush.selectAll('.background').data(__repeat_892); + + 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 ' + _$constants_896.verticalPadding + ')'); + + background + .call(attachDragBehavior) + .attr('height', function(d) { + return d.height - _$constants_896.verticalPadding; + }); + + var highlightShadow = axisBrush.selectAll('.highlight-shadow').data(__repeat_892); // we have a set here, can't call it `extent` + + highlightShadow.enter() + .append('line') + .classed('highlight-shadow', true) + .attr('x', -_$constants_896.bar.width / 2) + .attr('stroke-width', _$constants_896.bar.width + _$constants_896.bar.strokeWidth) + .attr('stroke', _$constants_896.bar.strokeColor) + .attr('opacity', _$constants_896.bar.strokeOpacity) + .attr('stroke-linecap', 'butt'); + + highlightShadow + .attr('y1', function(d) { return d.height; }) + .call(styleHighlight); + + var highlight = axisBrush.selectAll('.highlight').data(__repeat_892); // we have a set here, can't call it `extent` + + highlight.enter() + .append('line') + .classed('highlight', true) + .attr('x', -_$constants_896.bar.width / 2) + .attr('stroke-width', _$constants_896.bar.width - _$constants_896.bar.strokeWidth) + .attr('stroke', _$constants_896.bar.fillColor) + .attr('opacity', _$constants_896.bar.fillOpacity) + .attr('stroke-linecap', 'butt'); + + highlight + .attr('y1', function(d) { return d.height; }) + .call(styleHighlight); +} + +function ensureAxisBrush(axisOverlays) { + var axisBrush = axisOverlays.selectAll('.' + _$constants_896.cn.axisBrush) + .data(__repeat_892, keyFun); + + axisBrush.enter() + .append('g') + .classed(_$constants_896.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 = [[0, 1]]; +} + +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); + 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 = [ + ordinalScaleSnapLo(sortedTickVals, ri[0], []), + ordinalScaleSnapHi(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]; +} + +var _$axisbrush_892 = { + makeBrush: makeBrush, + ensureAxisBrush: ensureAxisBrush, + cleanRanges: cleanRanges +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$browser_295 = require('glslify'); */; +var vertexShaderSource = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]); +var contextShaderSource = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depth,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]); +var pickVertexShaderSource = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n fragColor = vec4(pf.rgb, 1.0);\n}\n"]); +var fragmentShaderSource = _$browser_295(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]); + +/* removed: var _$lib_601 = require('../../lib'); */; + +// don't change; otherwise near/far plane lines are lost +var depthLimitEpsilon = 1e-6; +// just enough buffer for an extra bit at single-precision floating point +// which on [0, 1] is 6e-8 (1/2^24) +var filterEpsilon = 1e-7; + +// precision of multiselect is the full range divided into this many parts +var maskHeight = 2048; var gpuDimensionCount = 64; var sectionVertexCount = 2; var vec4NumberCount = 4; +var bitsPerByte = 8; +var channelCount = gpuDimensionCount / bitsPerByte; // == 8 bytes needed to have 64 bits var contextColor = [119, 119, 119]; // middle gray to not drawn the focus; looks good on a black or white background var dummyPixel = new Uint8Array(4); var pickPixel = new Uint8Array(4); +var paletteTextureConfig = { + shape: [256, 1], + format: 'rgba', + type: 'uint8', + mag: 'nearest', + min: 'nearest' +}; + function ensureDraw(regl) { regl.read({ x: 0, @@ -128318,7 +129600,8 @@ function calcPickColor(j, rgbIndex) { return (j >>> 8 * rgbIndex) % 256 / 255; } -function makePoints(sampleCount, dimensionCount, dimensions, color) { +function makePoints(sampleCount, dimensions, color) { + var dimensionCount = dimensions.length; var points = []; for(var j = 0; j < sampleCount; j++) { @@ -128337,7 +129620,6 @@ function makePoints(sampleCount, dimensionCount, dimensions, color) { } function makeVecAttr(sampleCount, points, vecIndex) { - var i, j, k; var pointPairs = []; @@ -128355,36 +129637,26 @@ function makeVecAttr(sampleCount, points, vecIndex) { return pointPairs; } -function makeAttributes(sampleCount, points) { - - var vecIndices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - var vectors = vecIndices.map(function(vecIndex) {return makeVecAttr(sampleCount, points, vecIndex);}); +function setAttributes(attributes, sampleCount, points) { + for(var i = 0; i < 16; i++) { + attributes['p' + i.toString(16)](makeVecAttr(sampleCount, points, i)); + } +} +function emptyAttributes(regl) { var attributes = {}; - vectors.forEach(function(v, vecIndex) { - attributes['p' + vecIndex.toString(16)] = v; - }); - + for(var i = 0; i < 16; i++) { + attributes['p' + i.toString(16)] = regl.buffer({usage: 'dynamic', type: 'float', data: null}); + } return attributes; } -function valid(i, offset, panelCount) { - return i + offset <= panelCount; -} - -var _$lines_834 = function(canvasGL, d, scatter) { - var model = d.model, - vm = d.viewModel, - domain = model.domain; +var _$lines_899 = function(canvasGL, d) { + // context & pick describe which canvas we're talking about - won't change with new data + var context = d.context; + var pick = d.pick; - var lines = model.lines, - canvasWidth = model.canvasWidth, - canvasHeight = model.canvasHeight, - initialDimensions = vm.dimensions, - initialPanels = vm.panels, - unitToColor = model.unitToColor, - context = d.context, - pick = d.pick; + var regl = d.regl; var renderState = { currentRafs: {}, @@ -128392,39 +129664,23 @@ var _$lines_834 = function(canvasGL, d, scatter) { clearOnly: false }; - var initialDims = initialDimensions.slice(); - - var dimensionCount = initialDims.length; - var sampleCount = initialDims[0] ? initialDims[0].values.length : 0; - - var focusAlphaBlending = context; + // 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 color = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color; - var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3)); - var overdrag = lines.canvasOverdrag; - - var panelCount = initialPanels.length; - - var points = makePoints(sampleCount, dimensionCount, initialDims, color); - var attributes = makeAttributes(sampleCount, points); - - var regl = d.regl; - - var paletteTexture = regl.texture({ - shape: [256, 1], - format: 'rgba', - type: 'uint8', - mag: 'nearest', - min: 'nearest', - data: palette(unitToColor, context, Math.round((context ? contextOpacity : 1) * 255)) - }); + update(d); var glAes = regl({ profile: false, blend: { - enable: focusAlphaBlending, + enable: context, func: { srcRGB: 'src alpha', dstRGB: 'one minus src alpha', @@ -128439,7 +129695,7 @@ var _$lines_834 = function(canvasGL, d, scatter) { }, depth: { - enable: !focusAlphaBlending, + enable: !context, mask: true, func: 'less', range: [0, 1] @@ -128470,7 +129726,7 @@ var _$lines_834 = function(canvasGL, d, scatter) { dither: false, - vert: pick ? pickVertexShaderSource : vertexShaderSource, + vert: pick ? pickVertexShaderSource : context ? contextShaderSource : vertexShaderSource, frag: fragmentShaderSource, @@ -128498,13 +129754,32 @@ var _$lines_834 = function(canvasGL, d, scatter) { loD: regl.prop('loD'), hiD: regl.prop('hiD'), palette: paletteTexture, - colorClamp: regl.prop('colorClamp'), - scatter: regl.prop('scatter') + mask: regl.prop('maskTexture'), + maskHeight: regl.prop('maskHeight'), + colorClamp: regl.prop('colorClamp') }, 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 = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color; + var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3)); + + var points = makePoints(sampleCount, initialDims, color); + setAttributes(attributes, sampleCount, points); + + paletteTexture = regl.texture(_$lib_601.extendFlat({ + data: palette(model.unitToColor, context, Math.round((context ? contextOpacity : 1) * 255)) + }, paletteTextureConfig)); + } + var colorClamp = [0, 1]; function setColorDomain(unitDomain) { @@ -128514,26 +129789,27 @@ var _$lines_834 = function(canvasGL, d, scatter) { var previousAxisOrder = []; - function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, scatter, I, leftmost, rightmost) { + function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, I, leftmost, rightmost, constraints) { var loHi, abcd, d, index; var leftRight = [i, ii]; - var filterEpsilon = _$constants_831.verticalPadding / canvasPanelSizeY; var dims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); - var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); for(loHi = 0; loHi < 2; loHi++) { index = leftRight[loHi]; for(abcd = 0; abcd < 4; abcd++) { for(d = 0; d < 16; d++) { - var dimP = d + 16 * abcd; dims[loHi][abcd][d] = d + 16 * abcd === index ? 1 : 0; - lims[loHi][abcd][d] = (!context && valid(d, 16 * abcd, panelCount) ? initialDims[dimP === 0 ? 0 : 1 + ((dimP - 1) % (initialDims.length - 1))].filter[loHi] : loHi) + (2 * loHi - 1) * filterEpsilon; } } } - return { + var overdrag = model.lines.canvasOverdrag; + var domain = model.domain; + var canvasWidth = model.canvasWidth; + var canvasHeight = model.canvasHeight; + + var itemModel = _$lib_601.extendFlat({ key: crossfilterDimensionIndex, resolution: [canvasWidth, canvasHeight], viewBoxPosition: [x + overdrag, y], @@ -128550,17 +129826,7 @@ var _$lines_834 = function(canvasGL, d, scatter) { dim2C: dims[1][2], dim2D: dims[1][3], - loA: lims[0][0], - loB: lims[0][1], - loC: lims[0][2], - loD: lims[0][3], - hiA: lims[1][0], - hiB: lims[1][1], - hiC: lims[1][2], - hiD: lims[1][3], - colorClamp: colorClamp, - scatter: scatter || 0, scissorX: (I === leftmost ? 0 : x + overdrag) + (model.pad.l - overdrag) + model.layoutWidth * domain.x[0], scissorWidth: (I === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (I === leftmost ? x + overdrag : 0), @@ -128571,11 +129837,87 @@ var _$lines_834 = function(canvasGL, d, scatter) { viewportY: model.pad.b + model.layoutHeight * domain.y[0], viewportWidth: canvasWidth, viewportHeight: canvasHeight + }, constraints); + + return itemModel; + } + + function makeConstraints() { + var loHi, abcd, d; + + var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); + + for(loHi = 0; loHi < 2; loHi++) { + for(abcd = 0; abcd < 4; abcd++) { + for(d = 0; d < 16; d++) { + var dimP = d + 16 * abcd; + var lim; + if(dimP < initialDims.length) { + lim = initialDims[dimP].brush.filter.getBounds()[loHi]; + } + else lim = loHi; + lims[loHi][abcd][d] = lim + (2 * loHi - 1) * filterEpsilon; + } + } + } + + function expandedPixelRange(dim, bounds) { + var maskHMinus = maskHeight - 1; + return [ + Math.max(0, Math.floor(bounds[0] * maskHMinus)), + Math.min(maskHMinus, Math.ceil(bounds[1] * maskHMinus)) + ]; + } + + var mask = Array.apply(null, new Array(maskHeight * channelCount)).map(function() { + return 255; + }); + for(var dimIndex = 0; dimIndex < initialDims.length; dimIndex++) { + var bitIndex = dimIndex % bitsPerByte; + var byteIndex = (dimIndex - bitIndex) / bitsPerByte; + var bitMask = Math.pow(2, bitIndex); + var dim = initialDims[dimIndex]; + var ranges = dim.brush.filter.get(); + if(ranges.length < 2) continue; // bail if the bounding box based filter is sufficient + + var prevEnd = expandedPixelRange(dim, ranges[0])[1]; + for(var ri = 1; ri < ranges.length; ri++) { + var nextRange = expandedPixelRange(dim, ranges[ri]); + for(var pi = prevEnd + 1; pi < nextRange[0]; pi++) { + mask[pi * channelCount + byteIndex] &= ~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: [channelCount, 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: lims[0][0], + loB: lims[0][1], + loC: lims[0][2], + loD: lims[0][3], + hiA: lims[1][0], + hiB: lims[1][1], + hiC: lims[1][2], + hiD: lims[1][3] }; } function renderGLParcoords(panels, setChanged, clearOnly) { - + var panelCount = panels.length; var I; var leftmost, rightmost, lowestX = Infinity, highestX = -Infinity; @@ -128593,8 +129935,9 @@ var _$lines_834 = function(canvasGL, d, scatter) { if(panelCount === 0) { // clear canvas here, as the panel iteration below will not enter the loop body - clear(regl, 0, 0, canvasWidth, canvasHeight); + clear(regl, 0, 0, model.canvasWidth, model.canvasHeight); } + var constraints = context ? {} : makeConstraints(); for(I = 0; I < panelCount; I++) { var panel = panels[I]; @@ -128609,9 +129952,9 @@ var _$lines_834 = function(canvasGL, d, scatter) { var xTo = x + panelSizeX; if(setChanged || !previousAxisOrder[i] || previousAxisOrder[i][0] !== x || previousAxisOrder[i][1] !== xTo) { previousAxisOrder[i] = [x, xTo]; - var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, scatter || dim1.scatter ? 1 : 0, I, leftmost, rightmost); + var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, I, leftmost, rightmost, constraints); renderState.clearOnly = clearOnly; - renderBlock(regl, glAes, renderState, setChanged ? lines.blockLineCount : sampleCount, sampleCount, item); + renderBlock(regl, glAes, renderState, setChanged ? model.lines.blockLineCount : sampleCount, sampleCount, item); } } } @@ -128642,6 +129985,8 @@ var _$lines_834 = function(canvasGL, d, scatter) { function destroy() { canvasGL.style['pointer-events'] = 'none'; paletteTexture.destroy(); + if(maskTexture) maskTexture.destroy(); + for(var k in attributes) attributes[k].destroy(); } return { @@ -128649,7 +129994,8 @@ var _$lines_834 = function(canvasGL, d, scatter) { render: renderGLParcoords, readPixel: readPixel, readPixels: readPixels, - destroy: destroy + destroy: destroy, + update: update }; }; @@ -128663,21 +130009,23 @@ var _$lines_834 = function(canvasGL, d, scatter) { 'use strict'; -/* removed: var _$lines_834 = require('./lines'); */; -/* removed: var _$constants_831 = require('./constants'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -var keyFun = _$gup_536.keyFun; -var __repeat_835 = _$gup_536.repeat; -var unwrap = _$gup_536.unwrap; +/* removed: var _$lines_899 = require('./lines'); */; +/* removed: var _$constants_896 = require('./constants'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$gup_598 = require('../../lib/gup'); */; +var __keyFun_900 = _$gup_598.keyFun; +var __repeat_900 = _$gup_598.repeat; +var unwrap = _$gup_598.unwrap; +/* removed: var _$axisbrush_892 = require('./axisbrush'); */; -function visible(dimension) {return !('visible' in dimension) || dimension.visible;} +function visible(dimension) { return !('visible' in dimension) || dimension.visible; } function dimensionExtent(dimension) { - var lo = dimension.range ? dimension.range[0] : _$lib_539.aggNums(Math.min, null, dimension.values, dimension._length); - var hi = dimension.range ? dimension.range[1] : _$lib_539.aggNums(Math.max, null, dimension.values, dimension._length); + var lo = dimension.range ? dimension.range[0] : _$lib_601.aggNums(Math.min, null, dimension.values, dimension._length); + var hi = dimension.range ? dimension.range[1] : _$lib_601.aggNums(Math.max, null, dimension.values, dimension._length); if(isNaN(lo) || !isFinite(lo)) { lo = 0; @@ -128689,10 +130037,7 @@ function dimensionExtent(dimension) { // avoid a degenerate (zero-width) domain if(lo === hi) { - if(lo === void(0)) { - lo = 0; - hi = 1; - } else if(lo === 0) { + if(lo === 0) { // no use to multiplying zero, so add/subtract in this case lo -= 1; hi += 1; @@ -128706,68 +130051,63 @@ function dimensionExtent(dimension) { return [lo, hi]; } -function ordinalScaleSnap(scale, v) { - var i, a, prevDiff, prevValue, diff; - for(i = 0, a = scale.range(), prevDiff = Infinity, prevValue = a[0], diff; i < a.length; i++) { - if((diff = Math.abs(a[i] - v)) > prevDiff) { - return prevValue; - } - prevDiff = diff; - prevValue = a[i]; - } - return a[a.length - 1]; -} - function toText(formatter, texts) { - return function(v, i) { - if(texts) { + if(texts) { + return function(v, i) { var text = texts[i]; - if(text === null || text === undefined) { - return formatter(v); - } else { - return text; - } - } else { - return formatter(v); - } - }; + if(text === null || text === undefined) return formatter(v); + return text; + }; + } + return formatter; } -function domainScale(height, padding, dimension) { +function domainScale(height, padding, dimension, tickvals, ticktext) { var extent = dimensionExtent(dimension); - var texts = dimension.ticktext; - return dimension.tickvals ? - _$d3_127.scale.ordinal() - .domain(dimension.tickvals.map(toText(_$d3_127.format(dimension.tickformat), texts))) - .range(dimension.tickvals - .map(function(d) {return (d - extent[0]) / (extent[1] - extent[0]);}) - .map(function(d) {return (height - padding + d * (padding - (height - padding)));})) : - _$d3_127.scale.linear() - .domain(extent) - .range([height - padding, padding]); + if(tickvals) { + return _$d3_130.scale.ordinal() + .domain(tickvals.map(toText(_$d3_130.format(dimension.tickformat), ticktext))) + .range(tickvals + .map(function(d) { + var unitVal = (d - extent[0]) / (extent[1] - extent[0]); + return (height - padding + unitVal * (2 * padding - height)); + }) + ); + } + return _$d3_130.scale.linear() + .domain(extent) + .range([height - padding, padding]); } -function unitScale(height, padding) {return _$d3_127.scale.linear().range([height - padding, padding]);} -function domainToUnitScale(dimension) {return _$d3_127.scale.linear().domain(dimensionExtent(dimension));} +function unitToPaddedPx(height, padding) { return _$d3_130.scale.linear().range([padding, height - padding]); } + +function domainToPaddedUnitScale(dimension, padFraction) { + return _$d3_130.scale.linear() + .domain(dimensionExtent(dimension)) + .range([padFraction, 1 - padFraction]); +} function ordinalScale(dimension) { + if(!dimension.tickvals) return; + var extent = dimensionExtent(dimension); - return dimension.tickvals && _$d3_127.scale.ordinal() - .domain(dimension.tickvals) - .range(dimension.tickvals.map(function(d) {return (d - extent[0]) / (extent[1] - extent[0]);})); + return _$d3_130.scale.ordinal() + .domain(dimension.tickvals) + .range(dimension.tickvals.map(function(d) { + return (d - extent[0]) / (extent[1] - extent[0]); + })); } function unitToColorScale(cscale) { - var colorStops = cscale.map(function(d) {return d[0];}); - var colorStrings = cscale.map(function(d) {return d[1];}); - var colorTuples = colorStrings.map(function(c) {return _$d3_127.rgb(c);}); - var prop = function(n) {return function(o) {return o[n];};}; + var colorStops = cscale.map(function(d) { return d[0]; }); + var colorTuples = cscale.map(function(d) { return _$d3_130.rgb(d[1]); }); + var prop = function(n) { return function(o) { return o[n]; }; }; // We can't use d3 color interpolation as we may have non-uniform color palette raster // (various color stop distances). var polylinearUnitScales = 'rgb'.split('').map(function(key) { - return _$d3_127.scale.linear() + return _$d3_130.scale.linear() .clamp(true) .domain(colorStops) .range(colorTuples.map(prop(key))); @@ -128780,6 +130120,12 @@ function unitToColorScale(cscale) { }; } +function someFiltersActive(view) { + return view.dimensions.some(function(p) { + return p.brush.filterSpecified; + }); +} + function model(layout, d, i) { var cd0 = unwrap(d), trace = cd0.trace, @@ -128793,14 +130139,14 @@ function model(layout, d, i) { tickFont = trace.tickfont, rangeFont = trace.rangefont; - var lines = _$lib_539.extendDeep({}, line, { - color: lineColor.map(domainToUnitScale({ + var lines = _$lib_601.extendDeepNoArrays({}, line, { + color: lineColor.map(_$d3_130.scale.linear().domain(dimensionExtent({ values: lineColor, range: [line.cmin, line.cmax], _length: trace._commonLength - })), - blockLineCount: _$constants_831.blockLineCount, - canvasOverdrag: _$constants_831.overdrag * _$constants_831.canvasPixelRatio + }))), + blockLineCount: _$constants_896.blockLineCount, + canvasOverdrag: _$constants_896.overdrag * _$constants_896.canvasPixelRatio }); var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0])); @@ -128814,7 +130160,7 @@ function model(layout, d, i) { key: i, colCount: dimensions.filter(visible).length, dimensions: dimensions, - tickDistance: _$constants_831.tickDistance, + tickDistance: _$constants_896.tickDistance, unitToColor: unitToColorScale(cscale), lines: lines, labelFont: labelFont, @@ -128826,15 +130172,15 @@ function model(layout, d, i) { translateX: domain.x[0] * width, translateY: layout.height - domain.y[1] * layout.height, pad: pad, - canvasWidth: rowContentWidth * _$constants_831.canvasPixelRatio + 2 * lines.canvasOverdrag, - canvasHeight: rowHeight * _$constants_831.canvasPixelRatio, + canvasWidth: rowContentWidth * _$constants_896.canvasPixelRatio + 2 * lines.canvasOverdrag, + canvasHeight: rowHeight * _$constants_896.canvasPixelRatio, width: rowContentWidth, height: rowHeight, - canvasPixelRatio: _$constants_831.canvasPixelRatio + canvasPixelRatio: _$constants_896.canvasPixelRatio }; } -function viewModel(model) { +function viewModel(state, callbacks, model) { var width = model.width; var height = model.height; @@ -128843,53 +130189,128 @@ function viewModel(model) { var xScale = function(d) {return width * d / Math.max(1, model.colCount - 1);}; - var unitPad = _$constants_831.verticalPadding / (height * canvasPixelRatio); - var unitPadScale = (1 - 2 * unitPad); - var paddedUnitScale = function(d) {return unitPad + unitPadScale * d;}; + var unitPad = _$constants_896.verticalPadding / height; + var _unitToPaddedPx = unitToPaddedPx(height, _$constants_896.verticalPadding); var viewModel = { key: model.key, xScale: xScale, - model: model + model: model, + inBrushDrag: false // consider factoring it out and putting it in a centralized global-ish gesture state object }; var uniqueKeys = {}; viewModel.dimensions = dimensions.filter(visible).map(function(dimension, i) { - var domainToUnit = domainToUnitScale(dimension); + var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad); var foundKey = uniqueKeys[dimension.label]; uniqueKeys[dimension.label] = (foundKey || 0) + 1; var key = dimension.label + (foundKey ? '__' + foundKey : ''); + var specifiedConstraint = dimension.constraintrange; + var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length; + if(filterRangeSpecified && !Array.isArray(specifiedConstraint[0])) { + specifiedConstraint = [specifiedConstraint]; + } + var filterRange = filterRangeSpecified ? + specifiedConstraint.map(function(d) { return d.map(domainToPaddedUnit); }) : + [[0, 1]]; + var brushMove = function() { + var p = viewModel; + p.focusLayer && p.focusLayer.render(p.panels, true); + var filtersActive = someFiltersActive(p); + if(!state.contextShown() && filtersActive) { + p.contextLayer && p.contextLayer.render(p.panels, true); + state.contextShown(true); + } else if(state.contextShown() && !filtersActive) { + p.contextLayer && p.contextLayer.render(p.panels, true, true); + state.contextShown(false); + } + }; var truncatedValues = dimension.values; if(truncatedValues.length > dimension._length) { truncatedValues = truncatedValues.slice(0, dimension._length); } + var tickvals = dimension.tickvals; + var ticktext; + function makeTickItem(v, i) { return {val: v, text: ticktext[i]}; } + function sortTickItem(a, b) { return a.val - b.val; } + if(Array.isArray(tickvals) && tickvals.length) { + ticktext = dimension.ticktext; + + // ensure ticktext and tickvals have same length + if(!Array.isArray(ticktext) || !ticktext.length) { + ticktext = tickvals.map(_$d3_130.format(dimension.tickformat)); + } + else if(ticktext.length > tickvals.length) { + ticktext = ticktext.slice(0, tickvals.length); + } + else if(tickvals.length > ticktext.length) { + tickvals = tickvals.slice(0, ticktext.length); + } + + // check if we need to sort tickvals/ticktext + for(var j = 1; j < tickvals.length; j++) { + if(tickvals[j] < tickvals[j - 1]) { + var tickItems = tickvals.map(makeTickItem).sort(sortTickItem); + for(var k = 0; k < tickvals.length; k++) { + tickvals[k] = tickItems[k].val; + ticktext[k] = tickItems[k].text; + } + break; + } + } + } + else tickvals = undefined; + return { key: key, label: dimension.label, tickFormat: dimension.tickformat, - tickvals: dimension.tickvals, - ticktext: dimension.ticktext, - ordinal: !!dimension.tickvals, - scatter: _$constants_831.scatter || dimension.scatter, + tickvals: tickvals, + ticktext: ticktext, + ordinal: !!tickvals, + multiselect: dimension.multiselect, xIndex: i, crossfilterDimensionIndex: i, visibleIndex: dimension._index, height: height, values: truncatedValues, - paddedUnitValues: truncatedValues.map(domainToUnit).map(paddedUnitScale), + paddedUnitValues: truncatedValues.map(domainToPaddedUnit), + unitTickvals: tickvals && tickvals.map(domainToPaddedUnit), xScale: xScale, x: xScale(i), canvasX: xScale(i) * canvasPixelRatio, - unitScale: unitScale(height, _$constants_831.verticalPadding), - domainScale: domainScale(height, _$constants_831.verticalPadding, dimension), + unitToPaddedPx: _unitToPaddedPx, + domainScale: domainScale(height, _$constants_896.verticalPadding, dimension, tickvals, ticktext), ordinalScale: ordinalScale(dimension), - domainToUnitScale: domainToUnit, - filter: dimension.constraintrange ? dimension.constraintrange.map(domainToUnit) : [0, 1], parent: viewModel, - model: model + model: model, + brush: _$axisbrush_892.makeBrush( + state, + filterRangeSpecified, + filterRange, + function() { + state.linePickActive(false); + }, + brushMove, + function(f) { + var p = viewModel; + p.focusLayer.render(p.panels, true); + p.pickLayer && p.pickLayer.render(p.panels, true); + state.linePickActive(true); + if(callbacks && callbacks.filterChanged) { + var invScale = domainToPaddedUnit.invert; + + // update gd.data as if a Plotly.restyle were fired + var newRanges = f.map(function(r) { + return r.map(invScale).sort(_$lib_601.sorterAsc); + }).sort(function(a, b) { return a[0] - b[0]; }); + callbacks.filterChanged(p.key, dimension._index, newRanges); + } + } + ) }; }); @@ -128898,61 +130319,32 @@ function viewModel(model) { function styleExtentTexts(selection) { selection - .classed(_$constants_831.cn.axisExtentText, true) + .classed(_$constants_896.cn.axisExtentText, true) .attr('text-anchor', 'middle') .style('cursor', 'default') .style('user-select', 'none'); } -var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) { - var domainBrushing = false; +function parcoordsInteractionState() { var linePickActive = true; + var contextShown = false; + return { + linePickActive: function(val) {return arguments.length ? linePickActive = !!val : linePickActive;}, + contextShown: function(val) {return arguments.length ? contextShown = !!val : contextShown;} + }; +} - function enterSvgDefs(root) { - var defs = root.selectAll('defs') - .data(__repeat_835, keyFun); - - defs.enter() - .append('defs'); - - var filterBarPattern = defs.selectAll('#' + _$constants_831.id.filterBarPattern) - .data(__repeat_835, keyFun); - - filterBarPattern.enter() - .append('pattern') - .attr('id', _$constants_831.id.filterBarPattern) - .attr('patternUnits', 'userSpaceOnUse'); - - filterBarPattern - .attr('x', -_$constants_831.bar.width) - .attr('width', _$constants_831.bar.capturewidth) - .attr('height', function(d) {return d.model.height;}); - - var filterBarPatternGlyph = filterBarPattern.selectAll('rect') - .data(__repeat_835, keyFun); - - filterBarPatternGlyph.enter() - .append('rect') - .attr('shape-rendering', 'crispEdges'); +var _$parcoords_900 = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) { - filterBarPatternGlyph - .attr('height', function(d) {return d.model.height;}) - .attr('width', _$constants_831.bar.width) - .attr('x', _$constants_831.bar.width / 2) - .attr('fill', _$constants_831.bar.fillcolor) - .attr('fill-opacity', _$constants_831.bar.fillopacity) - .attr('stroke', _$constants_831.bar.strokecolor) - .attr('stroke-opacity', _$constants_831.bar.strokeopacity) - .attr('stroke-width', _$constants_831.bar.strokewidth); - } + var state = parcoordsInteractionState(); var vm = styledData .filter(function(d) { return unwrap(d).trace.visible; }) .map(model.bind(0, layout)) - .map(viewModel); + .map(viewModel.bind(0, state, callbacks)); parcoordsLineLayers.each(function(d, i) { - return _$lib_539.extendFlat(d, vm[i]); + return _$lib_601.extendFlat(d, vm[i]); }); var parcoordsLineLayer = parcoordsLineLayers.selectAll('.gl-canvas') @@ -128962,21 +130354,19 @@ var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layou d.model = d.viewModel ? d.viewModel.model : null; }); - var tweakables = {renderers: [], dimensions: []}; - var lastHovered = null; - parcoordsLineLayer - .filter(function(d) { - return d.pick; - }) + var pickLayer = parcoordsLineLayer.filter(function(d) {return d.pick;}); + + // emit hover / unhover event + pickLayer .style('pointer-events', 'auto') .on('mousemove', function(d) { - if(linePickActive && d.lineLayer && callbacks && callbacks.hover) { - var event = _$d3_127.event; + if(state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) { + var event = _$d3_130.event; var cw = this.width; var ch = this.height; - var pointer = _$d3_127.mouse(this); + var pointer = _$d3_130.mouse(this); var x = pointer[0]; var y = pointer[1]; @@ -129010,193 +130400,145 @@ var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layou .style('opacity', function(d) {return d.pick ? 0.01 : 1;}); svg.style('background', 'rgba(255, 255, 255, 0)'); - var parcoordsControlOverlay = svg.selectAll('.' + _$constants_831.cn.parcoords) - .data(vm, keyFun); + var parcoordsControlOverlay = svg.selectAll('.' + _$constants_896.cn.parcoords) + .data(vm, __keyFun_900); parcoordsControlOverlay.exit().remove(); parcoordsControlOverlay.enter() .append('g') - .classed(_$constants_831.cn.parcoords, true) - .attr('overflow', 'visible') - .style('box-sizing', 'content-box') - .style('position', 'absolute') - .style('left', 0) - .style('overflow', 'visible') + .classed(_$constants_896.cn.parcoords, true) .style('shape-rendering', 'crispEdges') - .style('pointer-events', 'none') - .call(enterSvgDefs); + .style('pointer-events', 'none'); - parcoordsControlOverlay - .attr('width', function(d) {return d.model.width + d.model.pad.l + d.model.pad.r;}) - .attr('height', function(d) {return d.model.height + d.model.pad.t + d.model.pad.b;}) - .attr('transform', function(d) { - return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')'; - }); + parcoordsControlOverlay.attr('transform', function(d) { + return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')'; + }); - var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + _$constants_831.cn.parcoordsControlView) - .data(__repeat_835, keyFun); + var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + _$constants_896.cn.parcoordsControlView) + .data(__repeat_900, __keyFun_900); parcoordsControlView.enter() .append('g') - .classed(_$constants_831.cn.parcoordsControlView, true) - .style('box-sizing', 'content-box'); + .classed(_$constants_896.cn.parcoordsControlView, true); - parcoordsControlView - .attr('transform', function(d) {return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')';}); - - var yAxis = parcoordsControlView.selectAll('.' + _$constants_831.cn.yAxis) - .data(function(vm) {return vm.dimensions;}, keyFun); + parcoordsControlView.attr('transform', function(d) { + return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')'; + }); - function someFiltersActive(view) { - return view.dimensions.some(function(p) {return p.filter[0] !== 0 || p.filter[1] !== 1;}); - } + var yAxis = parcoordsControlView.selectAll('.' + _$constants_896.cn.yAxis) + .data(function(vm) { return vm.dimensions; }, __keyFun_900); - function updatePanelLayoutParcoords(yAxis, vm) { - var panels = vm.panels || (vm.panels = []); - var yAxes = yAxis.each(function(d) {return d;})[vm.key].map(function(e) {return e.__data__;}); - var panelCount = yAxes.length - 1; - var rowCount = 1; - for(var row = 0; row < rowCount; row++) { - for(var p = 0; p < panelCount; p++) { - var panel = panels[p + row * panelCount] || (panels[p + row * panelCount] = {}); - var dim1 = yAxes[p]; - var dim2 = yAxes[p + 1]; - panel.dim1 = dim1; - panel.dim2 = dim2; - panel.canvasX = dim1.canvasX; - panel.panelSizeX = dim2.canvasX - dim1.canvasX; - panel.panelSizeY = vm.model.canvasHeight / rowCount; - panel.y = row * panel.panelSizeY; - panel.canvasY = vm.model.canvasHeight - panel.y - panel.panelSizeY; - } - } - } - - function updatePanelLayoutScatter(yAxis, vm) { + function updatePanelLayout(yAxis, vm) { var panels = vm.panels || (vm.panels = []); - var yAxes = yAxis.each(function(d) {return d;})[vm.key].map(function(e) {return e.__data__;}); - var panelCount = yAxes.length - 1; - var rowCount = panelCount; - for(var row = 0; row < panelCount; row++) { - for(var p = 0; p < panelCount; p++) { - var panel = panels[p + row * panelCount] || (panels[p + row * panelCount] = {}); - var dim1 = yAxes[p]; - var dim2 = yAxes[p + 1]; - panel.dim1 = yAxes[row + 1]; - panel.dim2 = dim2; - panel.canvasX = dim1.canvasX; - panel.panelSizeX = dim2.canvasX - dim1.canvasX; - panel.panelSizeY = vm.model.canvasHeight / rowCount; - panel.y = row * panel.panelSizeY; - panel.canvasY = vm.model.canvasHeight - panel.y - panel.panelSizeY; - } + var dimData = yAxis.data(); + var panelCount = dimData.length - 1; + for(var p = 0; p < panelCount; p++) { + var panel = panels[p] || (panels[p] = {}); + var dim1 = dimData[p]; + var dim2 = dimData[p + 1]; + panel.dim1 = dim1; + panel.dim2 = dim2; + panel.canvasX = dim1.canvasX; + panel.panelSizeX = dim2.canvasX - dim1.canvasX; + panel.panelSizeY = vm.model.canvasHeight; + panel.y = 0; + panel.canvasY = 0; } } - function updatePanelLayout(yAxis, vm) { - return (_$constants_831.scatter ? updatePanelLayoutScatter : updatePanelLayoutParcoords)(yAxis, vm); - } - yAxis.enter() .append('g') - .classed(_$constants_831.cn.yAxis, true) - .each(function(d) {tweakables.dimensions.push(d);}); + .classed(_$constants_896.cn.yAxis, true); parcoordsControlView.each(function(vm) { updatePanelLayout(yAxis, vm); }); parcoordsLineLayer - .filter(function(d) {return !!d.viewModel;}) .each(function(d) { - d.lineLayer = _$lines_834(this, d, _$constants_831.scatter); - d.viewModel[d.key] = d.lineLayer; - tweakables.renderers.push(function() {d.lineLayer.render(d.viewModel.panels, true);}); - d.lineLayer.render(d.viewModel.panels, !d.context); - }); + if(d.viewModel) { + if(d.lineLayer) d.lineLayer.update(d); + else d.lineLayer = _$lines_899(this, d); - yAxis - .attr('transform', function(d) {return 'translate(' + d.xScale(d.xIndex) + ', 0)';}); + d.viewModel[d.key] = d.lineLayer; + d.lineLayer.render(d.viewModel.panels, !d.context); + } + }); - yAxis - .call(_$d3_127.behavior.drag() - .origin(function(d) {return d;}) - .on('drag', function(d) { - var p = d.parent; - linePickActive = false; - if(domainBrushing) { - return; - } - d.x = Math.max(-_$constants_831.overdrag, Math.min(d.model.width + _$constants_831.overdrag, _$d3_127.event.x)); - d.canvasX = d.x * d.model.canvasPixelRatio; - yAxis - .sort(function(a, b) {return a.x - b.x;}) - .each(function(dd, i) { - dd.xIndex = i; - dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex); - dd.canvasX = dd.x * dd.model.canvasPixelRatio; - }); + yAxis.attr('transform', function(d) { + return 'translate(' + d.xScale(d.xIndex) + ', 0)'; + }); - updatePanelLayout(yAxis, p); + // drag column for reordering columns + yAxis.call(_$d3_130.behavior.drag() + .origin(function(d) { return d; }) + .on('drag', function(d) { + var p = d.parent; + state.linePickActive(false); + d.x = Math.max(-_$constants_896.overdrag, Math.min(d.model.width + _$constants_896.overdrag, _$d3_130.event.x)); + d.canvasX = d.x * d.model.canvasPixelRatio; + yAxis + .sort(function(a, b) { return a.x - b.x; }) + .each(function(dd, i) { + dd.xIndex = i; + dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex); + dd.canvasX = dd.x * dd.model.canvasPixelRatio; + }); - yAxis.filter(function(dd) {return Math.abs(d.xIndex - dd.xIndex) !== 0;}) - .attr('transform', function(d) {return 'translate(' + d.xScale(d.xIndex) + ', 0)';}); - _$d3_127.select(this).attr('transform', 'translate(' + d.x + ', 0)'); - yAxis.each(function(dd, i, ii) {if(ii === d.parent.key) p.dimensions[i] = dd;}); - p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); - p.focusLayer.render && p.focusLayer.render(p.panels); - }) - .on('dragend', function(d) { - var p = d.parent; - if(domainBrushing) { - if(domainBrushing === 'ending') { - domainBrushing = false; - } - return; - } - d.x = d.xScale(d.xIndex); - d.canvasX = d.x * d.model.canvasPixelRatio; - updatePanelLayout(yAxis, p); - _$d3_127.select(this) - .attr('transform', function(d) {return 'translate(' + d.x + ', 0)';}); - p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); - p.focusLayer && p.focusLayer.render(p.panels); - p.pickLayer && p.pickLayer.render(p.panels, true); - linePickActive = true; + updatePanelLayout(yAxis, p); - if(callbacks && callbacks.axesMoved) { - callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;})); - } - }) - ); + yAxis.filter(function(dd) { return Math.abs(d.xIndex - dd.xIndex) !== 0; }) + .attr('transform', function(d) { return 'translate(' + d.xScale(d.xIndex) + ', 0)'; }); + _$d3_130.select(this).attr('transform', 'translate(' + d.x + ', 0)'); + yAxis.each(function(dd, i, ii) { if(ii === d.parent.key) p.dimensions[i] = dd; }); + p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); + p.focusLayer.render && p.focusLayer.render(p.panels); + }) + .on('dragend', function(d) { + var p = d.parent; + d.x = d.xScale(d.xIndex); + d.canvasX = d.x * d.model.canvasPixelRatio; + updatePanelLayout(yAxis, p); + _$d3_130.select(this) + .attr('transform', function(d) { return 'translate(' + d.x + ', 0)'; }); + p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); + p.focusLayer && p.focusLayer.render(p.panels); + p.pickLayer && p.pickLayer.render(p.panels, true); + state.linePickActive(true); + + if(callbacks && callbacks.axesMoved) { + callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;})); + } + }) + ); yAxis.exit() .remove(); - var axisOverlays = yAxis.selectAll('.' + _$constants_831.cn.axisOverlays) - .data(__repeat_835, keyFun); + var axisOverlays = yAxis.selectAll('.' + _$constants_896.cn.axisOverlays) + .data(__repeat_900, __keyFun_900); axisOverlays.enter() .append('g') - .classed(_$constants_831.cn.axisOverlays, true); + .classed(_$constants_896.cn.axisOverlays, true); - axisOverlays.selectAll('.' + _$constants_831.cn.axis).remove(); + axisOverlays.selectAll('.' + _$constants_896.cn.axis).remove(); - var axis = axisOverlays.selectAll('.' + _$constants_831.cn.axis) - .data(__repeat_835, keyFun); + var axis = axisOverlays.selectAll('.' + _$constants_896.cn.axis) + .data(__repeat_900, __keyFun_900); axis.enter() .append('g') - .classed(_$constants_831.cn.axis, true); + .classed(_$constants_896.cn.axis, true); axis .each(function(d) { var wantedTickCount = d.model.height / d.model.tickDistance; var scale = d.domainScale; var sdom = scale.domain(); - _$d3_127.select(this) - .call(_$d3_127.svg.axis() + _$d3_130.select(this) + .call(_$d3_130.svg.axis() .orient('left') .tickSize(4) .outerTickSize(2) @@ -129204,221 +130546,108 @@ var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layou .tickValues(d.ordinal ? // and this works for ordinal scales sdom : null) - .tickFormat(d.ordinal ? function(d) {return d;} : null) + .tickFormat(d.ordinal ? function(d) { return d; } : null) .scale(scale)); - _$drawing_436.font(axis.selectAll('text'), d.model.tickFont); + _$drawing_498.font(axis.selectAll('text'), d.model.tickFont); }); - axis - .selectAll('.domain, .tick>line') + axis.selectAll('.domain, .tick>line') .attr('fill', 'none') .attr('stroke', 'black') .attr('stroke-opacity', 0.25) .attr('stroke-width', '1px'); - axis - .selectAll('text') + axis.selectAll('text') .style('text-shadow', '1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff') .style('cursor', 'default') .style('user-select', 'none'); - var axisHeading = axisOverlays.selectAll('.' + _$constants_831.cn.axisHeading) - .data(__repeat_835, keyFun); + var axisHeading = axisOverlays.selectAll('.' + _$constants_896.cn.axisHeading) + .data(__repeat_900, __keyFun_900); axisHeading.enter() .append('g') - .classed(_$constants_831.cn.axisHeading, true); + .classed(_$constants_896.cn.axisHeading, true); - var axisTitle = axisHeading.selectAll('.' + _$constants_831.cn.axisTitle) - .data(__repeat_835, keyFun); + var axisTitle = axisHeading.selectAll('.' + _$constants_896.cn.axisTitle) + .data(__repeat_900, __keyFun_900); axisTitle.enter() .append('text') - .classed(_$constants_831.cn.axisTitle, true) + .classed(_$constants_896.cn.axisTitle, true) .attr('text-anchor', 'middle') .style('cursor', 'ew-resize') .style('user-select', 'none') .style('pointer-events', 'auto'); axisTitle - .attr('transform', 'translate(0,' + -_$constants_831.axisTitleOffset + ')') - .text(function(d) {return d.label;}) - .each(function(d) {_$drawing_436.font(axisTitle, d.model.labelFont);}); + .attr('transform', 'translate(0,' + -_$constants_896.axisTitleOffset + ')') + .text(function(d) { return d.label; }) + .each(function(d) { _$drawing_498.font(_$d3_130.select(this), d.model.labelFont); }); - var axisExtent = axisOverlays.selectAll('.' + _$constants_831.cn.axisExtent) - .data(__repeat_835, keyFun); + var axisExtent = axisOverlays.selectAll('.' + _$constants_896.cn.axisExtent) + .data(__repeat_900, __keyFun_900); axisExtent.enter() .append('g') - .classed(_$constants_831.cn.axisExtent, true); + .classed(_$constants_896.cn.axisExtent, true); - var axisExtentTop = axisExtent.selectAll('.' + _$constants_831.cn.axisExtentTop) - .data(__repeat_835, keyFun); + var axisExtentTop = axisExtent.selectAll('.' + _$constants_896.cn.axisExtentTop) + .data(__repeat_900, __keyFun_900); axisExtentTop.enter() .append('g') - .classed(_$constants_831.cn.axisExtentTop, true); + .classed(_$constants_896.cn.axisExtentTop, true); axisExtentTop - .attr('transform', 'translate(' + 0 + ',' + -_$constants_831.axisExtentOffset + ')'); + .attr('transform', 'translate(' + 0 + ',' + -_$constants_896.axisExtentOffset + ')'); - var axisExtentTopText = axisExtentTop.selectAll('.' + _$constants_831.cn.axisExtentTopText) - .data(__repeat_835, keyFun); + var axisExtentTopText = axisExtentTop.selectAll('.' + _$constants_896.cn.axisExtentTopText) + .data(__repeat_900, __keyFun_900); - function formatExtreme(d) { - return d.ordinal ? function() {return '';} : _$d3_127.format(d.tickFormat); + function extremeText(d, isTop) { + if(d.ordinal) return ''; + var domain = d.domainScale.domain(); + return _$d3_130.format(d.tickFormat)(domain[isTop ? domain.length - 1 : 0]); } axisExtentTopText.enter() .append('text') - .classed(_$constants_831.cn.axisExtentTopText, true) + .classed(_$constants_896.cn.axisExtentTopText, true) .call(styleExtentTexts); axisExtentTopText - .text(function(d) {return formatExtreme(d)(d.domainScale.domain().slice(-1)[0]);}) - .each(function(d) {_$drawing_436.font(axisExtentTopText, d.model.rangeFont);}); + .text(function(d) { return extremeText(d, true); }) + .each(function(d) { _$drawing_498.font(_$d3_130.select(this), d.model.rangeFont); }); - var axisExtentBottom = axisExtent.selectAll('.' + _$constants_831.cn.axisExtentBottom) - .data(__repeat_835, keyFun); + var axisExtentBottom = axisExtent.selectAll('.' + _$constants_896.cn.axisExtentBottom) + .data(__repeat_900, __keyFun_900); axisExtentBottom.enter() .append('g') - .classed(_$constants_831.cn.axisExtentBottom, true); + .classed(_$constants_896.cn.axisExtentBottom, true); axisExtentBottom - .attr('transform', function(d) {return 'translate(' + 0 + ',' + (d.model.height + _$constants_831.axisExtentOffset) + ')';}); + .attr('transform', function(d) { + return 'translate(' + 0 + ',' + (d.model.height + _$constants_896.axisExtentOffset) + ')'; + }); - var axisExtentBottomText = axisExtentBottom.selectAll('.' + _$constants_831.cn.axisExtentBottomText) - .data(__repeat_835, keyFun); + var axisExtentBottomText = axisExtentBottom.selectAll('.' + _$constants_896.cn.axisExtentBottomText) + .data(__repeat_900, __keyFun_900); axisExtentBottomText.enter() .append('text') - .classed(_$constants_831.cn.axisExtentBottomText, true) + .classed(_$constants_896.cn.axisExtentBottomText, true) .attr('dy', '0.75em') .call(styleExtentTexts); axisExtentBottomText - .text(function(d) {return formatExtreme(d)(d.domainScale.domain()[0]);}) - .each(function(d) {_$drawing_436.font(axisExtentBottomText, d.model.rangeFont);}); - - var axisBrush = axisOverlays.selectAll('.' + _$constants_831.cn.axisBrush) - .data(__repeat_835, keyFun); + .text(function(d) { return extremeText(d); }) + .each(function(d) { _$drawing_498.font(_$d3_130.select(this), d.model.rangeFont); }); - var axisBrushEnter = axisBrush.enter() - .append('g') - .classed(_$constants_831.cn.axisBrush, true); - - axisBrush - .each(function(d) { - if(!d.brush) { - d.brush = _$d3_127.svg.brush() - .y(d.unitScale) - .on('brushstart', axisBrushStarted) - .on('brush', axisBrushMoved) - .on('brushend', axisBrushEnded); - if(d.filter[0] !== 0 || d.filter[1] !== 1) { - d.brush.extent(d.filter); - } - _$d3_127.select(this).call(d.brush); - } - }); - - axisBrushEnter - .selectAll('rect') - .attr('x', -_$constants_831.bar.capturewidth / 2) - .attr('width', _$constants_831.bar.capturewidth); - - axisBrushEnter - .selectAll('rect.extent') - .attr('fill', 'url(#' + _$constants_831.id.filterBarPattern + ')') - .style('cursor', 'ns-resize') - .filter(function(d) {return d.filter[0] === 0 && d.filter[1] === 1;}) - .attr('y', -100); // // zero-size rectangle pointer issue workaround - - axisBrushEnter - .selectAll('.resize rect') - .attr('height', _$constants_831.bar.handleheight) - .attr('opacity', 0) - .style('visibility', 'visible'); - - axisBrushEnter - .selectAll('.resize.n rect') - .style('cursor', 'n-resize') - .attr('y', _$constants_831.bar.handleoverlap - _$constants_831.bar.handleheight); - - axisBrushEnter - .selectAll('.resize.s rect') - .style('cursor', 's-resize') - .attr('y', _$constants_831.bar.handleoverlap); - - var justStarted = false; - var contextShown = false; - - function axisBrushStarted() { - justStarted = true; - domainBrushing = true; - } - - function axisBrushMoved(dimension) { - linePickActive = false; - var p = dimension.parent; - var extent = dimension.brush.extent(); - var dimensions = p.dimensions; - var filter = dimensions[dimension.xIndex].filter; - var reset = justStarted && (extent[0] === extent[1]); - if(reset) { - dimension.brush.clear(); - _$d3_127.select(this).select('rect.extent').attr('y', -100); // zero-size rectangle pointer issue workaround - } - var newExtent = reset ? [0, 1] : extent.slice(); - if(newExtent[0] !== filter[0] || newExtent[1] !== filter[1]) { - dimensions[dimension.xIndex].filter = newExtent; - p.focusLayer && p.focusLayer.render(p.panels, true); - var filtersActive = someFiltersActive(p); - if(!contextShown && filtersActive) { - p.contextLayer && p.contextLayer.render(p.panels, true); - contextShown = true; - } else if(contextShown && !filtersActive) { - p.contextLayer && p.contextLayer.render(p.panels, true, true); - contextShown = false; - } - } - justStarted = false; - } - - function axisBrushEnded(dimension) { - var p = dimension.parent; - var extent = dimension.brush.extent(); - var empty = extent[0] === extent[1]; - var dimensions = p.dimensions; - var f = dimensions[dimension.xIndex].filter; - if(!empty && dimension.ordinal) { - f[0] = ordinalScaleSnap(dimension.ordinalScale, f[0]); - f[1] = ordinalScaleSnap(dimension.ordinalScale, f[1]); - if(f[0] === f[1]) { - f[0] = Math.max(0, f[0] - 0.05); - f[1] = Math.min(1, f[1] + 0.05); - } - _$d3_127.select(this).transition().duration(150).call(dimension.brush.extent(f)); - p.focusLayer.render(p.panels, true); - } - p.pickLayer && p.pickLayer.render(p.panels, true); - linePickActive = true; - domainBrushing = 'ending'; - if(callbacks && callbacks.filterChanged) { - var invScale = dimension.domainToUnitScale.invert; - - // update gd.data as if a Plotly.restyle were fired - var newRange = f.map(invScale); - callbacks.filterChanged(p.key, dimension.visibleIndex, newRange); - } - } - - return tweakables; + _$axisbrush_892.ensureAxisBrush(axisOverlays); }; -var _$plot_836 = {}; -(function (global){ /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -129429,27 +130658,16 @@ var _$plot_836 = {}; 'use strict'; -/* removed: var _$parcoords_835 = require('./parcoords'); */; -/* removed: var _$regl_315 = require('regl'); */; +/* removed: var _$parcoords_900 = require('./parcoords'); */; +/* removed: var _$prepareRegl_614 = require('../../lib/prepare_regl'); */; -_$plot_836 = function plot(gd, cdparcoords) { +var _$plot_901 = function plot(gd, cdparcoords) { var fullLayout = gd._fullLayout; var svg = fullLayout._toppaper; var root = fullLayout._paperdiv; var container = fullLayout._glcontainer; - // make sure proper regl instances are created - fullLayout._glcanvas.each(function(d) { - if(d.regl) return; - d.regl = _$regl_315({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio - }); - }); + _$prepareRegl_614(gd); var gdDimensions = {}; var gdDimensionsOriginalOrder = {}; @@ -129461,21 +130679,28 @@ _$plot_836 = function plot(gd, cdparcoords) { gdDimensionsOriginalOrder[i] = gd.data[i].dimensions.slice(); }); - var filterChanged = function(i, originalDimensionIndex, newRange) { + var filterChanged = function(i, originalDimensionIndex, 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 gdDimension = gdDimensionsOriginalOrder[i][originalDimensionIndex]; - var gdConstraintRange = gdDimension.constraintrange; - - if(!gdConstraintRange || gdConstraintRange.length !== 2) { - gdConstraintRange = gdDimension.constraintrange = []; + var newConstraints = newRanges.map(function(r) { return r.slice(); }); + if(!newConstraints.length) { + delete gdDimension.constraintrange; + newConstraints = null; + } + else { + if(newConstraints.length === 1) newConstraints = newConstraints[0]; + gdDimension.constraintrange = newConstraints; + // wrap in another array for restyle event data + newConstraints = [newConstraints]; } - gdConstraintRange[0] = newRange[0]; - gdConstraintRange[1] = newRange[1]; - gd.emit('plotly_restyle'); + var restyleData = {}; + var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange'; + restyleData[aStr] = newConstraints; + gd.emit('plotly_restyle', [restyleData, [i]]); }; var hover = function(eventData) { @@ -129530,7 +130755,7 @@ _$plot_836 = function plot(gd, cdparcoords) { gd.emit('plotly_restyle'); }; - _$parcoords_835( + _$parcoords_900( root, svg, container, @@ -129553,8 +130778,7 @@ _$plot_836 = function plot(gd, cdparcoords) { }); }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$base_plot_828 = {}; +var _$base_plot_893 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -129565,21 +130789,21 @@ var _$base_plot_828 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -var __getModuleCalcData_828 = _$get_data_621.getModuleCalcData; -/* removed: var _$plot_836 = require('./plot'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_130 = require('d3'); */; +var __getModuleCalcData_893 = _$get_data_683.getModuleCalcData; +/* removed: var _$plot_901 = require('./plot'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; var PARCOORDS = 'parcoords'; -_$base_plot_828.name = PARCOORDS; +_$base_plot_893.name = PARCOORDS; -_$base_plot_828.plot = function(gd) { - var calcData = __getModuleCalcData_828(gd.calcdata, PARCOORDS); - if(calcData.length) _$plot_836(gd, calcData); +_$base_plot_893.plot = function(gd) { + var calcData = __getModuleCalcData_893(gd.calcdata, PARCOORDS)[0]; + if(calcData.length) _$plot_901(gd, calcData); }; -_$base_plot_828.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_893.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadParcoords = (oldFullLayout._has && oldFullLayout._has(PARCOORDS)); var hasParcoords = (newFullLayout._has && newFullLayout._has(PARCOORDS)); @@ -129589,9 +130813,9 @@ _$base_plot_828.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -_$base_plot_828.toSVG = function(gd) { +_$base_plot_893.toSVG = function(gd) { var imageRoot = gd._fullLayout._glimages; - var root = _$d3_127.select(gd).selectAll('.svg-container'); + var root = _$d3_130.select(gd).selectAll('.svg-container'); var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) .selectAll('.gl-canvas-context, .gl-canvas-focus'); @@ -129601,7 +130825,7 @@ _$base_plot_828.toSVG = function(gd) { var image = imageRoot.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, preserveAspectRatio: 'none', x: 0, @@ -129618,7 +130842,7 @@ _$base_plot_828.toSVG = function(gd) { // on a subsequent interaction. // Firefox works fine without this workaround window.setTimeout(function() { - _$d3_127.selectAll('#filterBarPattern') + _$d3_130.selectAll('#filterBarPattern') .attr('id', 'filterBarPattern'); }, 60); }; @@ -129633,21 +130857,21 @@ _$base_plot_828.toSVG = function(gd) { 'use strict'; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __wrap_829 = _$gup_536.wrap; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __wrap_894 = _$gup_598.wrap; -var _$calc_829 = function calc(gd, trace) { - var cs = !!trace.line.colorscale && _$lib_539.isArrayOrTypedArray(trace.line.color); +var _$calc_894 = function calc(gd, trace) { + var cs = !!trace.line.colorscale && _$lib_601.isArrayOrTypedArray(trace.line.color); var color = cs ? trace.line.color : constHalf(trace._commonLength); var cscale = cs ? trace.line.colorscale : [[0, trace.line.color], [1, trace.line.color]]; - if(_$hasColorscale_425(trace, 'line')) { - _$calc_418(trace, color, 'line', 'c'); + if(_$hasColorscale_487(trace, 'line')) { + _$calc_480(trace, color, 'line', 'c'); } - return __wrap_829({ + return __wrap_894({ lineColor: color, cscale: cscale }); @@ -129672,15 +130896,15 @@ function constHalf(len) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_830 = function colorbar(gd, cd) { +var _$colorbar_895 = function colorbar(gd, cd) { var trace = cd[0].trace, line = trace.line, cbId = 'cb' + trace.uid; @@ -129688,7 +130912,7 @@ var _$colorbar_830 = function colorbar(gd, cd) { gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if((line === undefined) || !line.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } @@ -129696,12 +130920,12 @@ var _$colorbar_830 = function colorbar(gd, cd) { cmin = line.cmin, cmax = line.cmax; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( line.colorscale, cmin, cmax @@ -129724,20 +130948,21 @@ var _$colorbar_830 = function colorbar(gd, cd) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_827 = require('./attributes'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -var maxDimensionCount = _$constants_831.maxDimensionCount; -var __handleDomainDefaults_832 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_891 = require('./attributes'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +var maxDimensionCount = _$constants_896.maxDimensionCount; +var __handleDomainDefaults_897 = _$domain_672.defaults; +/* removed: var _$axisbrush_892 = require('./axisbrush'); */; -function __handleLineDefaults_832(traceIn, traceOut, defaultColor, layout, coerce) { +function __handleLineDefaults_897(traceIn, traceOut, defaultColor, layout, coerce) { var lineColor = coerce('line.color', defaultColor); - if(_$hasColorscale_425(traceIn, 'line') && _$lib_539.isArrayOrTypedArray(lineColor)) { + if(_$hasColorscale_487(traceIn, 'line') && _$lib_601.isArrayOrTypedArray(lineColor)) { if(lineColor.length) { coerce('line.colorscale'); - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); // TODO: I think it would be better to keep showing lines beyond the last line color // but I'm not sure what color to give these lines - probably black or white // depending on the background color? @@ -129757,19 +130982,19 @@ function dimensionsDefaults(traceIn, traceOut) { var commonLength = Infinity; if(dimensionsIn.length > maxDimensionCount) { - _$lib_539.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment'); + _$lib_601.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment'); dimensionsIn.splice(maxDimensionCount); } function coerce(attr, dflt) { - return _$lib_539.coerce(dimensionIn, dimensionOut, _$attributes_827.dimensions, attr, dflt); + return _$lib_601.coerce(dimensionIn, dimensionOut, _$attributes_891.dimensions, attr, dflt); } for(i = 0; i < dimensionsIn.length; i++) { dimensionIn = dimensionsIn[i]; dimensionOut = {}; - if(!_$lib_539.isPlainObject(dimensionIn)) { + if(!_$lib_601.isPlainObject(dimensionIn)) { continue; } @@ -129785,7 +131010,12 @@ function dimensionsDefaults(traceIn, traceOut) { coerce('ticktext'); coerce('tickformat'); coerce('range'); - coerce('constraintrange'); + + coerce('multiselect'); + var constraintRange = coerce('constraintrange'); + if(constraintRange) { + dimensionOut.constraintrange = _$axisbrush_892.cleanRanges(constraintRange, dimensionOut); + } commonLength = Math.min(commonLength, values.length); } @@ -129799,16 +131029,16 @@ function dimensionsDefaults(traceIn, traceOut) { return dimensionsOut; } -var _$supplyDefaults_832 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_897 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_827, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_891, attr, dflt); } var dimensions = dimensionsDefaults(traceIn, traceOut); - __handleLineDefaults_832(traceIn, traceOut, defaultColor, layout, coerce); + __handleLineDefaults_897(traceIn, traceOut, defaultColor, layout, coerce); - __handleDomainDefaults_832(traceOut, layout, coerce); + __handleDomainDefaults_897(traceOut, layout, coerce); if(!Array.isArray(dimensions) || !dimensions.length) { traceOut.visible = false; @@ -129829,9 +131059,9 @@ var _$supplyDefaults_832 = function supplyDefaults(traceIn, traceOut, defaultCol color: layout.font.color }; - _$lib_539.coerceFont(coerce, 'labelfont', fontDflt); - _$lib_539.coerceFont(coerce, 'tickfont', fontDflt); - _$lib_539.coerceFont(coerce, 'rangefont', fontDflt); + _$lib_601.coerceFont(coerce, 'labelfont', fontDflt); + _$lib_601.coerceFont(coerce, 'tickfont', fontDflt); + _$lib_601.coerceFont(coerce, 'rangefont', fontDflt); }; /** @@ -129846,15 +131076,15 @@ var _$supplyDefaults_832 = function supplyDefaults(traceIn, traceOut, defaultCol var Parcoords = {}; -Parcoords.attributes = _$attributes_827; -Parcoords.supplyDefaults = _$supplyDefaults_832; -Parcoords.calc = _$calc_829; -Parcoords.plot = _$plot_836; -Parcoords.colorbar = _$colorbar_830; +Parcoords.attributes = _$attributes_891; +Parcoords.supplyDefaults = _$supplyDefaults_897; +Parcoords.calc = _$calc_894; +Parcoords.plot = _$plot_901; +Parcoords.colorbar = _$colorbar_895; Parcoords.moduleType = 'trace'; Parcoords.name = 'parcoords'; -Parcoords.basePlotModule = _$base_plot_828; +Parcoords.basePlotModule = _$base_plot_893; Parcoords.categories = ['gl', 'regl', 'noOpacity']; Parcoords.meta = { description: [ @@ -129864,7 +131094,7 @@ Parcoords.meta = { ].join(' ') }; -var _$Parcoords_833 = Parcoords; +var _$Parcoords_898 = Parcoords; /** * Copyright 2012-2018, Plotly, Inc. @@ -129876,7 +131106,7 @@ var _$Parcoords_833 = Parcoords; 'use strict'; -var _$parcoords_23 = _$Parcoords_833; +var _$parcoords_23 = _$Parcoords_898; /** * Copyright 2012-2018, Plotly, Inc. @@ -129888,20 +131118,20 @@ var _$parcoords_23 = _$Parcoords_833; 'use strict'; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -var __domainAttrs_837 = _$domain_610.attributes; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +var __domainAttrs_902 = _$domain_672.attributes; -var __extendFlat_837 = _$extend_528.extendFlat; +var __extendFlat_902 = _$extend_590.extendFlat; -var __textFontAttrs_837 = _$font_attributes_611({ +var __textFontAttrs_902 = _$font_attributes_673({ editType: 'calc', colorEditType: 'style', description: 'Sets the font used for `textinfo`.' }); -var _$attributes_837 = { +var _$attributes_902 = { labels: { valType: 'data_array', editType: 'calc', @@ -129958,7 +131188,7 @@ var _$attributes_837 = { color: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, arrayOk: true, editType: 'style', description: [ @@ -130035,7 +131265,7 @@ var _$attributes_837 = { 'Determines which trace information appear on the graph.' ].join(' ') }, - hoverinfo: __extendFlat_837({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_902({}, _$attributes_644.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'] }), textposition: { @@ -130050,18 +131280,18 @@ var _$attributes_837 = { ].join(' ') }, // TODO make those arrayOk? - textfont: __extendFlat_837({}, __textFontAttrs_837, { + textfont: __extendFlat_902({}, __textFontAttrs_902, { description: 'Sets the font used for `textinfo`.' }), - insidetextfont: __extendFlat_837({}, __textFontAttrs_837, { + insidetextfont: __extendFlat_902({}, __textFontAttrs_902, { description: 'Sets the font used for `textinfo` lying inside the pie.' }), - outsidetextfont: __extendFlat_837({}, __textFontAttrs_837, { + outsidetextfont: __extendFlat_902({}, __textFontAttrs_902, { description: 'Sets the font used for `textinfo` lying outside the pie.' }), // position and shape - domain: __domainAttrs_837({name: 'pie', trace: true, editType: 'calc'}), + domain: __domainAttrs_902({name: 'pie', trace: true, editType: 'calc'}), hole: { valType: 'number', @@ -130135,7 +131365,7 @@ var _$attributes_837 = { } }; -var _$base_plot_838 = {}; +var _$base_plot_903 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -130146,19 +131376,19 @@ var _$base_plot_838 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - +/* removed: var _$registry_731 = require('../../registry'); */; +var __getModuleCalcData_903 = _$get_data_683.getModuleCalcData; -_$base_plot_838.name = 'pie'; +_$base_plot_903.name = 'pie'; -_$base_plot_838.plot = function(gd) { - var Pie = _$registry_668.getModule('pie'); - var cdPie = getCdModule(gd.calcdata, Pie); +_$base_plot_903.plot = function(gd) { + var Pie = _$registry_731.getModule('pie'); + var cdPie = __getModuleCalcData_903(gd.calcdata, Pie)[0]; if(cdPie.length) Pie.plot(gd, cdPie); }; -_$base_plot_838.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_903.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPie = (oldFullLayout._has && oldFullLayout._has('pie')); var hasPie = (newFullLayout._has && newFullLayout._has('pie')); @@ -130167,21 +131397,6 @@ _$base_plot_838.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -function getCdModule(calcdata, _module) { - var cdModule = []; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - - if((trace._module === _module) && (trace.visible === true)) { - cdModule.push(cd); - } - } - - return cdModule; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -130192,16 +131407,16 @@ function getCdModule(calcdata, _module) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_839 = _$lib_539.isArrayOrTypedArray; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_904 = _$lib_601.isArrayOrTypedArray; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$helpers_842 = require('./helpers'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$helpers_907 = require('./helpers'); */; -var _$calc_839 = function calc(gd, trace) { +var _$calc_904 = function calc(gd, trace) { var vals = trace.values; - var hasVals = __isArrayOrTypedArray_839(vals) && vals.length; + var hasVals = __isArrayOrTypedArray_904(vals) && vals.length; var labels = trace.labels; var colors = trace.marker.colors || []; var cd = []; @@ -130214,7 +131429,7 @@ var _$calc_839 = function calc(gd, trace) { var i, v, label, hidden, pt; - if(!fullLayout._piecolorway && colorWay !== _$color_411.defaults) { + if(!fullLayout._piecolorway && colorWay !== _$color_473.defaults) { fullLayout._piecolorway = generateDefaultColors(colorWay); } @@ -130228,10 +131443,10 @@ var _$calc_839 = function calc(gd, trace) { function pullColor(color, label) { if(!color) return false; - color = _$tinycolor_352(color); + color = _$tinycolor_414(color); if(!color.isValid()) return false; - color = _$color_411.addOpacity(color, color.getAlpha()); + color = _$color_473.addOpacity(color, color.getAlpha()); if(!colorMap[label]) colorMap[label] = color; return color; @@ -130242,7 +131457,7 @@ var _$calc_839 = function calc(gd, trace) { for(i = 0; i < seriesLen; i++) { if(hasVals) { v = vals[i]; - if(!_$fastIsnumeric_139(v)) continue; + if(!_$fastIsnumeric_196(v)) continue; v = +v; if(v < 0) continue; } @@ -130323,11 +131538,11 @@ var _$calc_839 = function calc(gd, trace) { pt = cd[i]; thisText = hasLabel ? [pt.label] : []; if(hasText) { - var texti = _$helpers_842.getFirstFilled(trace.text, pt.pts); + var texti = _$helpers_907.getFirstFilled(trace.text, pt.pts); if(texti) thisText.push(texti); } - if(hasValue) thisText.push(_$helpers_842.formatPieValue(pt.v, separators)); - if(hasPercent) thisText.push(_$helpers_842.formatPiePercent(pt.v / vTotal, separators)); + if(hasValue) thisText.push(_$helpers_907.formatPieValue(pt.v, separators)); + if(hasPercent) thisText.push(_$helpers_907.formatPiePercent(pt.v / vTotal, separators)); pt.text = thisText.join('
'); } } @@ -130344,7 +131559,7 @@ var pieDefaultColors; function nextDefaultColor(index, pieColorWay) { if(!pieDefaultColors) { // generate this default set on demand (but then it gets saved in the module) - var mainDefaults = _$color_411.defaults; + var mainDefaults = _$color_473.defaults; pieDefaultColors = generateDefaultColors(mainDefaults); } @@ -130358,11 +131573,11 @@ function generateDefaultColors(colorList) { var pieColors = colorList.slice(); for(i = 0; i < colorList.length; i++) { - pieColors.push(_$tinycolor_352(colorList[i]).lighten(20).toHexString()); + pieColors.push(_$tinycolor_414(colorList[i]).lighten(20).toHexString()); } for(i = 0; i < colorList.length; i++) { - pieColors.push(_$tinycolor_352(colorList[i]).darken(20).toHexString()); + pieColors.push(_$tinycolor_414(colorList[i]).darken(20).toHexString()); } return pieColors; @@ -130378,21 +131593,21 @@ function generateDefaultColors(colorList) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_837 = require('./attributes'); */; -var __handleDomainDefaults_840 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_902 = require('./attributes'); */; +var __handleDomainDefaults_905 = _$domain_672.defaults; -var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_905 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_837, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_902, attr, dflt); } - var coerceFont = _$lib_539.coerceFont; + var coerceFont = _$lib_601.coerceFont; var vals = coerce('values'); var labels = coerce('labels'); if(!Array.isArray(labels)) { - if(!_$lib_539.isArrayOrTypedArray(vals) || !vals.length) { + if(!_$lib_601.isArrayOrTypedArray(vals) || !vals.length) { // must have at least one of vals or labels traceOut.visible = false; return; @@ -130427,7 +131642,7 @@ var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultCol } } - __handleDomainDefaults_840(traceOut, layout, coerce); + __handleDomainDefaults_905(traceOut, layout, coerce); coerce('hole'); @@ -130448,7 +131663,7 @@ var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$layout_attributes_844 = { +var _$layout_attributes_909 = { /** * hiddenlabels is the pie chart analog of visible:'legendonly' * but it can contain many labels, and can hide slices @@ -130470,13 +131685,13 @@ var _$layout_attributes_844 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$layout_attributes_844 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_909 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_845 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_910 = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_844, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_909, attr, dflt); } coerce('hiddenlabels'); }; @@ -130492,13 +131707,13 @@ var _$supplyLayoutDefaults_845 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -var appendArrayMultiPointValues = _$helpers_450.appendArrayMultiPointValues; +var appendArrayMultiPointValues = _$helpers_512.appendArrayMultiPointValues; // Note: like other eventData routines, this creates the data for hover/unhover/click events // but it has a different API and goes through a totally different pathway. // So to ensure it doesn't get misused, it's not attached to the Pie module. -var _$eventData_841 = function eventData(pt, trace) { +var _$eventData_906 = function eventData(pt, trace) { var out = { curveNumber: trace.index, pointNumbers: pt.pts, @@ -130533,17 +131748,18 @@ var _$eventData_841 = function eventData(pt, trace) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; -/* removed: var _$helpers_842 = require('./helpers'); */; -/* removed: var _$eventData_841 = require('./event_data'); */; +/* removed: var _$helpers_907 = require('./helpers'); */; +/* removed: var _$eventData_906 = require('./event_data'); */; -var _$plot_846 = function plot(gd, cdpie) { +var _$plot_911 = function plot(gd, cdpie) { var fullLayout = gd._fullLayout; scalePies(cdpie, fullLayout._size); @@ -130560,14 +131776,14 @@ var _$plot_846 = function plot(gd, cdpie) { pieGroups.order(); pieGroups.each(function(cd) { - var pieGroup = _$d3_127.select(this); + var pieGroup = _$d3_130.select(this); var cd0 = cd[0]; var trace = cd0.trace; setCoords(cd); pieGroup.each(function() { - var slices = _$d3_127.select(this).selectAll('g.slice').data(cd); + var slices = _$d3_130.select(this).selectAll('g.slice').data(cd); slices.enter().append('g') .classed('slice', true); @@ -130581,7 +131797,7 @@ var _$plot_846 = function plot(gd, cdpie) { slices.each(function(pt) { if(pt.hidden) { - _$d3_127.select(this).selectAll('path,g').remove(); + _$d3_130.select(this).selectAll('path,g').remove(); return; } @@ -130593,7 +131809,7 @@ var _$plot_846 = function plot(gd, cdpie) { var cx = cd0.cx; var cy = cd0.cy; - var sliceTop = _$d3_127.select(this); + var sliceTop = _$d3_130.select(this); var slicePath = sliceTop.selectAll('path.surface').data([pt]); // hover state vars @@ -130619,8 +131835,8 @@ var _$plot_846 = function plot(gd, cdpie) { // and call castHoverinfo on that. // TODO: do we want to have Fx.castHoverinfo somehow handle this? // it already takes an array for index, for 2D, so this seems tricky. - hoverinfo = _$fx_453.castHoverinfo({ - hoverinfo: [_$helpers_842.castOption(hoverinfo, pt.pts)], + hoverinfo = _$fx_515.castHoverinfo({ + hoverinfo: [_$helpers_907.castOption(hoverinfo, pt.pts)], _module: trace._module }, fullLayout2, 0); } @@ -130638,27 +131854,27 @@ var _$plot_846 = function plot(gd, cdpie) { if(hoverinfo.indexOf('label') !== -1) thisText.push(pt.label); if(hoverinfo.indexOf('text') !== -1) { - var texti = _$helpers_842.castOption(trace2.hovertext || trace2.text, pt.pts); + var texti = _$helpers_907.castOption(trace2.hovertext || trace2.text, pt.pts); if(texti) thisText.push(texti); } - if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_842.formatPieValue(pt.v, separators)); - if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_842.formatPiePercent(pt.v / cd0.vTotal, separators)); + if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_907.formatPieValue(pt.v, separators)); + if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_907.formatPiePercent(pt.v / cd0.vTotal, separators)); var hoverLabel = trace.hoverlabel; var hoverFont = hoverLabel.font; - _$fx_453.loneHover({ + _$fx_515.loneHover({ x0: hoverCenterX - rInscribed * cd0.r, x1: hoverCenterX + rInscribed * cd0.r, y: hoverCenterY, text: thisText.join('
'), name: hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined, idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right', - color: _$helpers_842.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, - borderColor: _$helpers_842.castOption(hoverLabel.bordercolor, pt.pts), - fontFamily: _$helpers_842.castOption(hoverFont.family, pt.pts), - fontSize: _$helpers_842.castOption(hoverFont.size, pt.pts), - fontColor: _$helpers_842.castOption(hoverFont.color, pt.pts) + color: _$helpers_907.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, + borderColor: _$helpers_907.castOption(hoverLabel.bordercolor, pt.pts), + fontFamily: _$helpers_907.castOption(hoverFont.family, pt.pts), + fontSize: _$helpers_907.castOption(hoverFont.size, pt.pts), + fontColor: _$helpers_907.castOption(hoverFont.color, pt.pts) }, { container: fullLayout2._hoverlayer.node(), outerContainer: fullLayout2._paper.node(), @@ -130669,8 +131885,8 @@ var _$plot_846 = function plot(gd, cdpie) { } gd.emit('plotly_hover', { - points: [_$eventData_841(pt, trace2)], - event: _$d3_127.event + points: [_$eventData_906(pt, trace2)], + event: _$d3_130.event }); hasHoverEvent = true; } @@ -130680,16 +131896,16 @@ var _$plot_846 = function plot(gd, cdpie) { var trace2 = gd._fullData[trace.index]; if(hasHoverEvent) { - evt.originalEvent = _$d3_127.event; + evt.originalEvent = _$d3_130.event; gd.emit('plotly_unhover', { - points: [_$eventData_841(pt, trace2)], - event: _$d3_127.event + points: [_$eventData_906(pt, trace2)], + event: _$d3_130.event }); hasHoverEvent = false; } if(hasHoverLabel) { - _$fx_453.loneUnhover(fullLayout2._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout2._hoverlayer.node()); hasHoverLabel = false; } } @@ -130705,8 +131921,8 @@ var _$plot_846 = function plot(gd, cdpie) { if(gd._dragging || fullLayout2.hovermode === false) return; - gd._hoverdata = [_$eventData_841(pt, trace2)]; - _$fx_453.click(gd, _$d3_127.event); + gd._hoverdata = [_$eventData_906(pt, trace2)]; + _$fx_515.click(gd, _$d3_130.event); } slicePath.enter().append('path') @@ -130721,7 +131937,7 @@ var _$plot_846 = function plot(gd, cdpie) { .on('click', handleClick); if(trace.pull) { - var pull = +_$helpers_842.castOption(trace.pull, pt.pts) || 0; + var pull = +_$helpers_907.castOption(trace.pull, pt.pts) || 0; if(pull > 0) { cx += pull * pt.pxmid[0]; cy += pull * pt.pxmid[1]; @@ -130772,7 +131988,7 @@ var _$plot_846 = function plot(gd, cdpie) { } // add text - var textPosition = _$helpers_842.castOption(trace.textposition, pt.pts); + var textPosition = _$helpers_907.castOption(trace.textposition, pt.pts); var sliceTextGroup = sliceTop.selectAll('g.slicetext') .data(pt.text && (textPosition !== 'none') ? [0] : []); @@ -130781,13 +131997,11 @@ var _$plot_846 = function plot(gd, cdpie) { sliceTextGroup.exit().remove(); sliceTextGroup.each(function() { - var sliceText = _$d3_127.select(this).selectAll('text').data([0]); - - sliceText.enter().append('text') + var sliceText = _$lib_601.ensureSingle(_$d3_130.select(this), 'text', '', function(s) { // prohibit tex interpretation until we can handle // tex and regular text together - .attr('data-notex', 1); - sliceText.exit().remove(); + s.attr('data-notex', 1); + }); sliceText.text(pt.text) .attr({ @@ -130795,12 +132009,12 @@ var _$plot_846 = function plot(gd, cdpie) { transform: '', 'text-anchor': 'middle' }) - .call(_$drawing_436.font, textPosition === 'outside' ? + .call(_$drawing_498.font, textPosition === 'outside' ? trace.outsidetextfont : trace.insidetextfont) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); // position the text relative to the slice - var textBB = _$drawing_436.bBox(sliceText.node()); + var textBB = _$drawing_498.bBox(sliceText.node()); var transform; if(textPosition === 'outside') { @@ -130808,10 +132022,10 @@ var _$plot_846 = function plot(gd, cdpie) { } else { transform = transformInsideText(textBB, pt, cd0); if(textPosition === 'auto' && transform.scale < 1) { - sliceText.call(_$drawing_436.font, trace.outsidetextfont); + sliceText.call(_$drawing_498.font, trace.outsidetextfont); if(trace.outsidetextfont.family !== trace.insidetextfont.family || trace.outsidetextfont.size !== trace.insidetextfont.size) { - textBB = _$drawing_436.bBox(sliceText.node()); + textBB = _$drawing_498.bBox(sliceText.node()); } transform = transformOutsideText(textBB, pt); } @@ -130846,7 +132060,7 @@ var _$plot_846 = function plot(gd, cdpie) { slices.each(function(pt) { if(pt.labelExtraX || pt.labelExtraY) { // first move the text to its new location - var sliceTop = _$d3_127.select(this); + var sliceTop = _$d3_130.select(this); var sliceText = sliceTop.select('g.slicetext text'); sliceText.attr('transform', 'translate(' + pt.labelExtraX + ',' + pt.labelExtraY + ')' + @@ -130879,7 +132093,7 @@ var _$plot_846 = function plot(gd, cdpie) { sliceTop.append('path') .classed('textline', true) - .call(_$color_411.stroke, trace.outsidetextfont.color) + .call(_$color_473.stroke, trace.outsidetextfont.color) .attr({ 'stroke-width': Math.min(2, trace.outsidetextfont.size / 8), d: textLinePath, @@ -130898,7 +132112,7 @@ var _$plot_846 = function plot(gd, cdpie) { // it gets the initial draw correct but on redraw it gets confused. setTimeout(function() { pieGroups.selectAll('tspan').each(function() { - var s = _$d3_127.select(this); + var s = _$d3_130.select(this); if(s.attr('dy')) s.attr('dy', s.attr('dy')); }); }, 0); @@ -131018,8 +132232,8 @@ function scootLabels(quadrants, trace) { // overlap can only happen if the other point is pulled more than this one if(otherPt === thisPt || ( - (_$helpers_842.castOption(trace.pull, thisPt.pts) || 0) >= - (_$helpers_842.castOption(trace.pull, otherPt.pts) || 0)) + (_$helpers_907.castOption(trace.pull, thisPt.pts) || 0) >= + (_$helpers_907.castOption(trace.pull, otherPt.pts) || 0)) ) { continue; } @@ -131204,20 +132418,20 @@ function setCoords(cd) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$styleOne_848 = require('./style_one'); */; +/* removed: var _$styleOne_913 = require('./style_one'); */; -var _$style_847 = function style(gd) { +var _$style_912 = function style(gd) { gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) { var cd0 = cd[0]; var trace = cd0.trace; - var traceSelection = _$d3_127.select(this); + var traceSelection = _$d3_130.select(this); traceSelection.style({opacity: trace.opacity}); traceSelection.selectAll('path.surface').each(function(pt) { - _$d3_127.select(this).call(_$styleOne_848, pt, trace); + _$d3_130.select(this).call(_$styleOne_913, pt, trace); }); }); }; @@ -131234,18 +132448,18 @@ var _$style_847 = function style(gd) { var Pie = {}; -Pie.attributes = _$attributes_837; -Pie.supplyDefaults = _$supplyDefaults_840; -Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_845; -Pie.layoutAttributes = _$layout_attributes_844; -Pie.calc = _$calc_839; -Pie.plot = _$plot_846; -Pie.style = _$style_847; -Pie.styleOne = _$styleOne_848; +Pie.attributes = _$attributes_902; +Pie.supplyDefaults = _$supplyDefaults_905; +Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_910; +Pie.layoutAttributes = _$layout_attributes_909; +Pie.calc = _$calc_904; +Pie.plot = _$plot_911; +Pie.style = _$style_912; +Pie.styleOne = _$styleOne_913; Pie.moduleType = 'trace'; Pie.name = 'pie'; -Pie.basePlotModule = _$base_plot_838; +Pie.basePlotModule = _$base_plot_903; Pie.categories = ['pie', 'showLegend']; Pie.meta = { description: [ @@ -131255,7 +132469,7 @@ Pie.meta = { ].join(' ') }; -var _$Pie_843 = Pie; +var _$Pie_908 = Pie; /** * Copyright 2012-2018, Plotly, Inc. @@ -131267,7 +132481,7 @@ var _$Pie_843 = Pie; 'use strict'; -var _$pie_24 = _$Pie_843; +var _$pie_24 = _$Pie_908; /** * Copyright 2012-2018, Plotly, Inc. @@ -131279,11 +132493,11 @@ var _$pie_24 = _$Pie_843; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; -var _$attributes_849 = { - x: _$attributes_862.x, - y: _$attributes_862.y, +var _$attributes_914 = { + x: _$attributes_927.x, + y: _$attributes_927.y, xy: { valType: 'data_array', editType: 'calc', @@ -131321,7 +132535,7 @@ var _$attributes_849 = { 'the `xy` typed array. Use it in conjunction with `xy` and `xbounds` for the performance benefits.' ].join(' ') }, - text: _$attributes_862.text, + text: _$attributes_927.text, marker: { color: { valType: 'color', @@ -131415,24 +132629,24 @@ var _$attributes_849 = { } }; -var _$shader_197 = {}; -/* removed: var _$browser_238 = require('glslify') */; +var _$shader_254 = {}; +/* removed: var _$browser_295 = require('glslify') */; -_$shader_197.pointVertex = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]) -_$shader_197.pointFragment = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]) -_$shader_197.pickVertex = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]) -_$shader_197.pickFragment = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]) +_$shader_254.pointVertex = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]) +_$shader_254.pointFragment = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]) +_$shader_254.pickVertex = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]) +_$shader_254.pickFragment = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]) 'use strict' -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$createBuffer_153 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; -/* removed: var _$pool_360 = require('typedarray-pool') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; -/* removed: var _$shader_197 = require('./lib/shader') */; +/* removed: var _$shader_254 = require('./lib/shader') */; -var _$createPointcloud2D_198 = createPointcloud2D +var _$createPointcloud2D_255 = createPointcloud2D function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) { this.plot = plot @@ -131452,9 +132666,9 @@ function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) { this.points = null } -var __proto_198 = Pointcloud2D.prototype +var __proto_255 = Pointcloud2D.prototype -__proto_198.dispose = function() { +__proto_255.dispose = function() { this.shader.dispose() this.pickShader.dispose() this.offsetBuffer.dispose() @@ -131462,7 +132676,7 @@ __proto_198.dispose = function() { this.plot.removeObject(this) } -__proto_198.update = function(options) { +__proto_255.update = function(options) { var i @@ -131492,8 +132706,8 @@ __proto_198.update = function(options) { var idStraightThrough = options.idToIndex instanceof Int32Array && options.idToIndex.length >= pointCount // permit larger to help reuse var data = options.positions - var packed = dataStraightThrough ? data : _$pool_360.mallocFloat32(data.length) - var packedId = idStraightThrough ? options.idToIndex : _$pool_360.mallocInt32(pointCount) + var packed = dataStraightThrough ? data : _$pool_422.mallocFloat32(data.length) + var packedId = idStraightThrough ? options.idToIndex : _$pool_422.mallocInt32(pointCount) if(!dataStraightThrough) { packed.set(data) @@ -131512,18 +132726,18 @@ __proto_198.update = function(options) { this.pickBuffer.update(packedId) if(!dataStraightThrough) { - _$pool_360.free(packed) + _$pool_422.free(packed) } if(!idStraightThrough) { - _$pool_360.free(packedId) + _$pool_422.free(packedId) } this.pointCount = pointCount this.pickOffset = 0 } -function __count_198(points, dataBox) { +function __count_255(points, dataBox) { var visiblePointCountEstimate = 0 var length = points.length >>> 1 var i @@ -131536,7 +132750,7 @@ function __count_198(points, dataBox) { return visiblePointCountEstimate } -__proto_198.unifiedDraw = (function() { +__proto_255.unifiedDraw = (function() { var MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1] @@ -131555,7 +132769,7 @@ return function(pickOffset) { var dataX = dataBox[2] - dataBox[0] var dataY = dataBox[3] - dataBox[1] - var visiblePointCountEstimate = __count_198(this.points, dataBox) + var visiblePointCountEstimate = __count_255(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 @@ -131608,10 +132822,10 @@ return function(pickOffset) { } })() -__proto_198.draw = __proto_198.unifiedDraw -__proto_198.drawPick = __proto_198.unifiedDraw +__proto_255.draw = __proto_255.unifiedDraw +__proto_255.drawPick = __proto_255.unifiedDraw -__proto_198.pick = function(x, y, value) { +__proto_255.pick = function(x, y, value) { var pickOffset = this.pickOffset var pointCount = this.pointCount if(value < pickOffset || value >= pickOffset + pointCount) { @@ -131628,10 +132842,10 @@ __proto_198.pick = function(x, y, value) { function createPointcloud2D(plot, options) { var gl = plot.gl - var buffer = _$createBuffer_153(gl) - var pickBuffer = _$createBuffer_153(gl) - var shader = _$createShader_206(gl, _$shader_197.pointVertex, _$shader_197.pointFragment) - var pickShader = _$createShader_206(gl, _$shader_197.pickVertex, _$shader_197.pickFragment) + var buffer = _$createBuffer_210(gl) + var pickBuffer = _$createBuffer_210(gl) + var shader = _$createShader_263(gl, _$shader_254.pointVertex, _$shader_254.pointFragment) + var pickShader = _$createShader_263(gl, _$shader_254.pickVertex, _$shader_254.pickFragment) var result = new Pointcloud2D(plot, buffer, pickBuffer, shader, pickShader) result.update(options) @@ -131652,11 +132866,11 @@ function createPointcloud2D(plot, options) { 'use strict'; -/* removed: var _$createPointcloud2D_198 = require('gl-pointcloud2d'); */; +/* removed: var _$createPointcloud2D_255 = require('gl-pointcloud2d'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; -var expandAxis = _$autorange_583.expand; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; +var expandAxis = _$autorange_646.expand; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; function Pointcloud(scene, uid) { this.scene = scene; @@ -131684,13 +132898,13 @@ function Pointcloud(scene, uid) { areaRatio: 1, borderColor: [0, 0, 0, 1] }; - this.pointcloud = _$createPointcloud2D_198(scene.glplot, this.pointcloudOptions); + this.pointcloud = _$createPointcloud2D_255(scene.glplot, this.pointcloudOptions); this.pointcloud._trace = this; // scene2d requires this prop } -var __proto_850 = Pointcloud.prototype; +var __proto_915 = Pointcloud.prototype; -__proto_850.handlePick = function(pickResult) { +__proto_915.handlePick = function(pickResult) { var index = this.idToIndex[pickResult.pointId]; // prefer the readout from XY, if present @@ -131710,7 +132924,7 @@ __proto_850.handlePick = function(pickResult) { }; }; -__proto_850.update = function(options) { +__proto_915.update = function(options) { this.index = options.index; this.textLabels = options.text; this.name = options.name; @@ -131719,10 +132933,10 @@ __proto_850.update = function(options) { this.updateFast(options); - this.color = _$getTraceColor_872(options, {}); + this.color = _$getTraceColor_937(options, {}); }; -__proto_850.updateFast = function(options) { +__proto_915.updateFast = function(options) { var x = this.xData = this.pickXData = options.x; var y = this.yData = this.pickYData = options.y; var xy = this.pickXYData = options.xy; @@ -131811,8 +133025,8 @@ __proto_850.updateFast = function(options) { this.pointcloudOptions.positions = positions; - var markerColor = _$str2RgbaArray_561(options.marker.color), - borderColor = _$str2RgbaArray_561(options.marker.border.color), + var markerColor = _$str2RgbaArray_624(options.marker.color), + borderColor = _$str2RgbaArray_624(options.marker.border.color), opacity = options.opacity * options.marker.opacity; markerColor[3] *= opacity; @@ -131842,14 +133056,14 @@ __proto_850.updateFast = function(options) { this.expandAxesFast(bounds, markerSizeMax / 2); // avoid axis reexpand just because of the adaptive point size }; -__proto_850.expandAxesFast = function(bounds, markerSize) { +__proto_915.expandAxesFast = function(bounds, markerSize) { var pad = markerSize || 0.5; expandAxis(this.scene.xaxis, [bounds[0], bounds[2]], {ppad: pad}); expandAxis(this.scene.yaxis, [bounds[1], bounds[3]], {ppad: pad}); }; -__proto_850.dispose = function() { +__proto_915.dispose = function() { this.pointcloud.dispose(); }; @@ -131859,7 +133073,7 @@ function createPointcloud(scene, data) { return plot; } -var _$createPointcloud_850 = createPointcloud; +var _$createPointcloud_915 = createPointcloud; /** * Copyright 2012-2018, Plotly, Inc. @@ -131872,13 +133086,13 @@ var _$createPointcloud_850 = createPointcloud; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$attributes_849 = require('./attributes'); */; +/* removed: var _$attributes_914 = require('./attributes'); */; -var _$supplyDefaults_851 = function supplyDefaults(traceIn, traceOut, defaultColor) { +var _$supplyDefaults_916 = function supplyDefaults(traceIn, traceOut, defaultColor) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_849, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_914, attr, dflt); } coerce('x'); @@ -131915,8 +133129,8 @@ var _$supplyDefaults_851 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; /** @@ -131924,11 +133138,11 @@ var _$supplyDefaults_851 = function supplyDefaults(traceIn, traceOut, defaultCol * calcdata the way Scatter.plot does, so that legends and * popovers know what to do with them. */ -var _$calc_888 = function calc(gd, trace) { +var _$calc_953 = function calc(gd, trace) { var cd = [{x: false, y: false, trace: trace, t: {}}]; - _$arraysToCalcdata_861(cd, trace); - _$calcMarkerColorscale_867(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcMarkerColorscale_932(trace); return cd; }; @@ -131945,16 +133159,16 @@ var _$calc_888 = function calc(gd, trace) { var pointcloud = {}; -pointcloud.attributes = _$attributes_849; -pointcloud.supplyDefaults = _$supplyDefaults_851; +pointcloud.attributes = _$attributes_914; +pointcloud.supplyDefaults = _$supplyDefaults_916; // reuse the Scatter3D 'dummy' calc step so that legends know what to do -pointcloud.calc = _$calc_888; -pointcloud.plot = _$createPointcloud_850; +pointcloud.calc = _$calc_953; +pointcloud.plot = _$createPointcloud_915; pointcloud.moduleType = 'trace'; pointcloud.name = 'pointcloud'; -pointcloud.basePlotModule = _$gl2d_624; +pointcloud.basePlotModule = _$gl2d_686; pointcloud.categories = ['gl', 'gl2d', 'showLegend']; pointcloud.meta = { description: [ @@ -131963,7 +133177,7 @@ pointcloud.meta = { ].join(' ') }; -var _$pointcloud_852 = pointcloud; +var _$pointcloud_917 = pointcloud; /** * Copyright 2012-2018, Plotly, Inc. @@ -131975,7 +133189,7 @@ var _$pointcloud_852 = pointcloud; 'use strict'; -var _$pointcloud_25 = _$pointcloud_852; +var _$pointcloud_25 = _$pointcloud_917; /** * Copyright 2012-2018, Plotly, Inc. @@ -131987,22 +133201,22 @@ var _$pointcloud_25 = _$pointcloud_852; 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$attributes_445 = require('../../components/fx/attributes'); */; -var __domainAttrs_853 = _$domain_610.attributes; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$attributes_507 = require('../../components/fx/attributes'); */; +var __domainAttrs_918 = _$domain_672.attributes; -var __extendFlat_853 = _$extend_528.extendFlat; -var __overrideAll_853 = _$edit_types_569.overrideAll; +var __extendFlat_918 = _$extend_590.extendFlat; +var __overrideAll_918 = _$edit_types_632.overrideAll; -var _$attributes_853 = __overrideAll_853({ - hoverinfo: __extendFlat_853({}, _$attributes_581.hoverinfo, { +var _$attributes_918 = __overrideAll_918({ + hoverinfo: __extendFlat_918({}, _$attributes_644.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'], }), - hoverlabel: _$attributes_445.hoverlabel, // needs editType override + hoverlabel: _$attributes_507.hoverlabel, // needs editType override - domain: __domainAttrs_853({name: 'sankey', trace: true}), + domain: __domainAttrs_918({name: 'sankey', trace: true}), orientation: { valType: 'enumerated', @@ -132047,7 +133261,7 @@ var _$attributes_853 = __overrideAll_853({ ].join(' ') }, - textfont: _$font_attributes_611({ + textfont: _$font_attributes_673({ description: 'Sets the font for node labels' }), @@ -132073,7 +133287,7 @@ var _$attributes_853 = __overrideAll_853({ color: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, arrayOk: true, description: [ 'Sets the color of the `line` around each `node`.' @@ -132129,7 +133343,7 @@ var _$attributes_853 = __overrideAll_853({ color: { valType: 'color', role: 'style', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, arrayOk: true, description: [ 'Sets the color of the `line` around each `link`.' @@ -132178,7 +133392,7 @@ var _$attributes_853 = __overrideAll_853({ 'use strict'; -var _$constants_856 = { +var _$constants_921 = { nodeTextOffsetHorizontal: 4, nodeTextOffsetVertical: 3, nodePadAcross: 10, @@ -132202,10 +133416,10 @@ var _$constants_856 = { } }; -var _$d3Array_119 = { exports: {} }; +var _$d3Array_122 = { exports: {} }; // https://d3js.org/d3-array/ Version 1.2.1. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Array_119.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Array_119.exports) : + typeof _$d3Array_122.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Array_122.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -132794,11 +134008,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Array_119 = _$d3Array_119.exports -var _$d3Collection_120 = { exports: {} }; +_$d3Array_122 = _$d3Array_122.exports +var _$d3Collection_123 = { exports: {} }; // https://d3js.org/d3-collection/ Version 1.0.4. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Collection_120.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Collection_120.exports) : + typeof _$d3Collection_123.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Collection_123.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -133014,11 +134228,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Collection_120 = _$d3Collection_120.exports -var _$d3Color_121 = { exports: {} }; +_$d3Collection_123 = _$d3Collection_123.exports +var _$d3Color_124 = { exports: {} }; // https://d3js.org/d3-color/ Version 1.0.3. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Color_121.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Color_121.exports) : + typeof _$d3Color_124.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Color_124.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -133540,11 +134754,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Color_121 = _$d3Color_121.exports -var _$d3Interpolate_124 = { exports: {} }; +_$d3Color_124 = _$d3Color_124.exports +var _$d3Interpolate_127 = { exports: {} }; // https://d3js.org/d3-interpolate/ Version 1.1.6. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Interpolate_124.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Interpolate_124.exports, _$d3Color_121) : + typeof _$d3Interpolate_127.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Interpolate_127.exports, _$d3Color_124) : typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) : (factory((global.d3 = global.d3 || {}),global.d3)); }(this, (function (exports,d3Color) { 'use strict'; @@ -134088,11 +135302,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Interpolate_124 = _$d3Interpolate_124.exports -var _$d3Sankey_41 = { exports: {} }; +_$d3Interpolate_127 = _$d3Interpolate_127.exports +var _$d3Sankey_42 = { exports: {} }; // https://github.com/d3/d3-sankey Version 0.5.0. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Sankey_41.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Sankey_41.exports, _$d3Array_119, _$d3Collection_120, _$d3Interpolate_124) : + typeof _$d3Sankey_42.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Sankey_42.exports, _$d3Array_122, _$d3Collection_123, _$d3Interpolate_127) : typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-interpolate'], factory) : (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3)); }(this, (function (exports,d3Array,d3Collection,d3Interpolate) { 'use strict'; @@ -134406,11 +135620,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Sankey_41 = _$d3Sankey_41.exports -var _$d3Dispatch_122 = { exports: {} }; +_$d3Sankey_42 = _$d3Sankey_42.exports +var _$d3Dispatch_125 = { exports: {} }; // https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Dispatch_122.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Dispatch_122.exports) : + typeof _$d3Dispatch_125.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Dispatch_125.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -134504,11 +135718,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Dispatch_122 = _$d3Dispatch_122.exports -var _$d3Quadtree_125 = { exports: {} }; +_$d3Dispatch_125 = _$d3Dispatch_125.exports +var _$d3Quadtree_128 = { exports: {} }; // https://d3js.org/d3-quadtree/ Version 1.0.3. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Quadtree_125.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Quadtree_125.exports) : + typeof _$d3Quadtree_128.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Quadtree_128.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -134942,11 +136156,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Quadtree_125 = _$d3Quadtree_125.exports -var _$d3Timer_126 = { exports: {} }; +_$d3Quadtree_128 = _$d3Quadtree_128.exports +var _$d3Timer_129 = { exports: {} }; // https://d3js.org/d3-timer/ Version 1.0.7. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Timer_126.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Timer_126.exports) : + typeof _$d3Timer_129.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Timer_129.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -135094,11 +136308,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Timer_126 = _$d3Timer_126.exports -var _$d3Force_123 = { exports: {} }; +_$d3Timer_129 = _$d3Timer_129.exports +var _$d3Force_126 = { exports: {} }; // https://d3js.org/d3-force/ Version 1.1.0. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Force_123.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Force_123.exports, _$d3Quadtree_125, _$d3Collection_120, _$d3Dispatch_122, _$d3Timer_126) : + typeof _$d3Force_126.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Force_126.exports, _$d3Quadtree_128, _$d3Collection_123, _$d3Dispatch_125, _$d3Timer_129) : typeof define === 'function' && define.amd ? define(['exports', 'd3-quadtree', 'd3-collection', 'd3-dispatch', 'd3-timer'], factory) : (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3)); }(this, (function (exports,d3Quadtree,d3Collection,d3Dispatch,d3Timer) { 'use strict'; @@ -135757,7 +136971,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Force_123 = _$d3Force_123.exports +_$d3Force_126 = _$d3Force_126.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -135768,17 +136982,17 @@ _$d3Force_123 = _$d3Force_123.exports 'use strict'; -/* removed: var _$constants_856 = require('./constants'); */; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -var d3sankey = _$d3Sankey_41.sankey; -/* removed: var _$d3Force_123 = require('d3-force'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __keyFun_860 = _$gup_536.keyFun; -var __repeat_860 = _$gup_536.repeat; -var __unwrap_860 = _$gup_536.unwrap; +/* removed: var _$constants_921 = require('./constants'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +var d3sankey = _$d3Sankey_42.sankey; +/* removed: var _$d3Force_126 = require('d3-force'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __keyFun_925 = _$gup_598.keyFun; +var __repeat_925 = _$gup_598.repeat; +var __unwrap_925 = _$gup_598.unwrap; // basic data utilities @@ -135824,7 +137038,7 @@ function switchToSankeyFormat(nodes) { // view models function sankeyModel(layout, d, i) { - var trace = __unwrap_860(d).trace, + var trace = __unwrap_925(d).trace, domain = trace.domain, nodeSpec = trace.node, linkSpec = trace.link, @@ -135847,7 +137061,7 @@ function sankeyModel(layout, d, i) { return { pointNumber: i, label: l, - color: _$lib_539.isArrayOrTypedArray(nodeSpec.color) ? nodeSpec.color[i] : nodeSpec.color + color: _$lib_601.isArrayOrTypedArray(nodeSpec.color) ? nodeSpec.color[i] : nodeSpec.color }; }); @@ -135855,7 +137069,7 @@ function sankeyModel(layout, d, i) { return { pointNumber: i, label: linkSpec.label[i], - color: _$lib_539.isArrayOrTypedArray(linkSpec.color) ? linkSpec.color[i] : linkSpec.color, + color: _$lib_601.isArrayOrTypedArray(linkSpec.color) ? linkSpec.color[i] : linkSpec.color, source: linkSpec.source[i], target: linkSpec.target[i], value: d @@ -135868,7 +137082,7 @@ function sankeyModel(layout, d, i) { .nodePadding(nodePad) .nodes(nodes) .links(links) - .layout(_$constants_856.sankeyIterations); + .layout(_$constants_921.sankeyIterations); var node, sankeyNodes = sankey.nodes(); for(var n = 0; n < sankeyNodes.length; n++) { @@ -135911,7 +137125,7 @@ function sankeyModel(layout, d, i) { } function linkModel(uniqueKeys, d, l) { - var tc = _$tinycolor_352(l.color); + var tc = _$tinycolor_414(l.color); var basicKey = l.source.label + '|' + l.target.label; var foundKey = uniqueKeys[basicKey]; uniqueKeys[basicKey] = (foundKey || 0) + 1; @@ -135925,7 +137139,7 @@ function linkModel(uniqueKeys, d, l) { key: key, traceId: d.key, link: l, - tinyColorHue: _$color_411.tinyRGB(tc), + tinyColorHue: _$color_473.tinyRGB(tc), tinyColorAlpha: tc.getAlpha(), linkLineColor: d.linkLineColor, linkLineWidth: d.linkLineWidth, @@ -135937,8 +137151,8 @@ function linkModel(uniqueKeys, d, l) { } function nodeModel(uniqueKeys, d, n) { - var tc = _$tinycolor_352(n.color), - zoneThicknessPad = _$constants_856.nodePadAcross, + var tc = _$tinycolor_414(n.color), + zoneThicknessPad = _$constants_921.nodePadAcross, zoneLengthPad = d.nodePad / 2, visibleThickness = n.dx, visibleLength = Math.max(0.5, n.dy); @@ -135973,7 +137187,7 @@ function nodeModel(uniqueKeys, d, n) { forceLayouts: d.forceLayouts, horizontal: d.horizontal, darkBackground: tc.getBrightness() <= 128, - tinyColorHue: _$color_411.tinyRGB(tc), + tinyColorHue: _$color_473.tinyRGB(tc), tinyColorAlpha: tc.getAlpha(), valueFormat: d.valueFormat, valueSuffix: d.valueSuffix, @@ -136027,9 +137241,9 @@ function nodeCentering(d) { } function textGuidePath(d) { - return _$d3_127.svg.line()([ - [d.horizontal ? (d.left ? -d.sizeAcross : d.visibleWidth + _$constants_856.nodeTextOffsetHorizontal) : _$constants_856.nodeTextOffsetHorizontal, 0], - [d.horizontal ? (d.left ? - _$constants_856.nodeTextOffsetHorizontal : d.sizeAcross) : d.visibleHeight - _$constants_856.nodeTextOffsetHorizontal, 0] + return _$d3_130.svg.line()([ + [d.horizontal ? (d.left ? -d.sizeAcross : d.visibleWidth + _$constants_921.nodeTextOffsetHorizontal) : _$constants_921.nodeTextOffsetHorizontal, 0], + [d.horizontal ? (d.left ? - _$constants_921.nodeTextOffsetHorizontal : d.sizeAcross) : d.visibleHeight - _$constants_921.nodeTextOffsetHorizontal, 0] ]);} function sankeyInverseTransform(d) {return d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)';} @@ -136073,13 +137287,13 @@ function attachPointerEvents(selection, sankey, eventSet) { function attachDragHandler(sankeyNode, sankeyLink, callbacks) { - var dragBehavior = _$d3_127.behavior.drag() + var dragBehavior = _$d3_130.behavior.drag() .origin(function(d) {return d.node;}) .on('dragstart', function(d) { if(d.arrangement === 'fixed') return; - _$lib_539.raiseToTop(this); + _$lib_601.raiseToTop(this); d.interactionState.dragInProgress = d.node; saveCurrentDragPosition(d.node); if(d.interactionState.hovered) { @@ -136099,8 +137313,8 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks) { .on('drag', function(d) { if(d.arrangement === 'fixed') return; - var x = _$d3_127.event.x; - var y = _$d3_127.event.y; + var x = _$d3_130.event.x; + var y = _$d3_130.event.y; if(d.arrangement === 'snap') { d.node.x = x; d.node.y = y; @@ -136128,19 +137342,19 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks) { function attachForce(sankeyNode, forceKey, d) { var nodes = d.sankey.nodes().filter(function(n) {return n.originalX === d.node.originalX;}); - d.forceLayouts[forceKey] = _$d3Force_123.forceSimulation(nodes) + d.forceLayouts[forceKey] = _$d3Force_126.forceSimulation(nodes) .alphaDecay(0) - .force('collide', _$d3Force_123.forceCollide() + .force('collide', _$d3Force_126.forceCollide() .radius(function(n) {return n.dy / 2 + d.nodePad / 2;}) .strength(1) - .iterations(_$constants_856.forceIterations)) + .iterations(_$constants_921.forceIterations)) .force('constrain', snappingForce(sankeyNode, forceKey, nodes, d)) .stop(); } function startForce(sankeyNode, sankeyLink, d, forceKey) { window.requestAnimationFrame(function faster() { - for(var i = 0; i < _$constants_856.forceTicksPerFrame; i++) { + for(var i = 0; i < _$constants_921.forceTicksPerFrame; i++) { d.forceLayouts[forceKey].tick(); } d.sankey.relayout(); @@ -136160,7 +137374,7 @@ function snappingForce(sankeyNode, forceKey, nodes, d) { n.x = n.lastDraggedX; n.y = n.lastDraggedY; } else { - n.vx = (n.originalX - n.x) / _$constants_856.forceTicksPerFrame; // snap to layer + n.vx = (n.originalX - n.x) / _$constants_921.forceTicksPerFrame; // snap to layer n.y = Math.min(d.size - n.dy / 2, Math.max(n.dy / 2, n.y)); // constrain to extent } maxVelocity = Math.max(maxVelocity, Math.abs(n.vx), Math.abs(n.vy)); @@ -136172,19 +137386,19 @@ function snappingForce(sankeyNode, forceKey, nodes, d) { } // scene graph -var _$render_860 = function(svg, styledData, layout, callbacks) { - var sankey = svg.selectAll('.' + _$constants_856.cn.sankey) +var _$render_925 = function(svg, styledData, layout, callbacks) { + var sankey = svg.selectAll('.' + _$constants_921.cn.sankey) .data(styledData - .filter(function(d) {return __unwrap_860(d).trace.visible;}) + .filter(function(d) {return __unwrap_925(d).trace.visible;}) .map(sankeyModel.bind(null, layout)), - __keyFun_860); + __keyFun_925); sankey.exit() .remove(); sankey.enter() .append('g') - .classed(_$constants_856.cn.sankey, true) + .classed(_$constants_921.cn.sankey, true) .style('box-sizing', 'content-box') .style('position', 'absolute') .style('left', 0) @@ -136194,57 +137408,57 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .attr('transform', sankeyTransform); sankey.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('transform', sankeyTransform); - var sankeyLinks = sankey.selectAll('.' + _$constants_856.cn.sankeyLinks) - .data(__repeat_860, __keyFun_860); + var sankeyLinks = sankey.selectAll('.' + _$constants_921.cn.sankeyLinks) + .data(__repeat_925, __keyFun_925); sankeyLinks.enter() .append('g') - .classed(_$constants_856.cn.sankeyLinks, true) + .classed(_$constants_921.cn.sankeyLinks, true) .style('fill', 'none'); - var sankeyLink = sankeyLinks.selectAll('.' + _$constants_856.cn.sankeyLink) + var sankeyLink = sankeyLinks.selectAll('.' + _$constants_921.cn.sankeyLink) .data(function(d) { var uniqueKeys = {}; return d.sankey.links() .filter(function(l) {return l.value;}) .map(linkModel.bind(null, uniqueKeys, d)); - }, __keyFun_860); + }, __keyFun_925); sankeyLink.enter() .append('path') - .classed(_$constants_856.cn.sankeyLink, true) + .classed(_$constants_921.cn.sankeyLink, true) .attr('d', linkPath) .call(attachPointerEvents, sankey, callbacks.linkEvents); sankeyLink .style('stroke', function(d) { - return salientEnough(d) ? _$color_411.tinyRGB(_$tinycolor_352(d.linkLineColor)) : d.tinyColorHue; + return salientEnough(d) ? _$color_473.tinyRGB(_$tinycolor_414(d.linkLineColor)) : d.tinyColorHue; }) .style('stroke-opacity', function(d) { - return salientEnough(d) ? _$color_411.opacity(d.linkLineColor) : d.tinyColorAlpha; + return salientEnough(d) ? _$color_473.opacity(d.linkLineColor) : d.tinyColorAlpha; }) .style('stroke-width', function(d) {return salientEnough(d) ? d.linkLineWidth : 1;}) .style('fill', function(d) {return d.tinyColorHue;}) .style('fill-opacity', function(d) {return d.tinyColorAlpha;}); sankeyLink.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('d', linkPath); sankeyLink.exit().transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .style('opacity', 0) .remove(); - var sankeyNodeSet = sankey.selectAll('.' + _$constants_856.cn.sankeyNodeSet) - .data(__repeat_860, __keyFun_860); + var sankeyNodeSet = sankey.selectAll('.' + _$constants_921.cn.sankeyNodeSet) + .data(__repeat_925, __keyFun_925); sankeyNodeSet.enter() .append('g') - .classed(_$constants_856.cn.sankeyNodeSet, true); + .classed(_$constants_921.cn.sankeyNodeSet, true); sankeyNodeSet .style('cursor', function(d) { @@ -136255,7 +137469,7 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { } }); - var sankeyNode = sankeyNodeSet.selectAll('.' + _$constants_856.cn.sankeyNode) + var sankeyNode = sankeyNodeSet.selectAll('.' + _$constants_921.cn.sankeyNode) .data(function(d) { var nodes = d.sankey.nodes(); var uniqueKeys = {}; @@ -136263,11 +137477,11 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { return nodes .filter(function(n) {return n.value;}) .map(nodeModel.bind(null, uniqueKeys, d)); - }, __keyFun_860); + }, __keyFun_925); sankeyNode.enter() .append('g') - .classed(_$constants_856.cn.sankeyNode, true) + .classed(_$constants_921.cn.sankeyNode, true) .call(updateNodePositions) .call(attachPointerEvents, sankey, callbacks.nodeEvents); @@ -136275,39 +137489,39 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .call(attachDragHandler, sankeyLink, callbacks); // has to be here as it binds sankeyLink sankeyNode.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .call(updateNodePositions); sankeyNode.exit().transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .style('opacity', 0) .remove(); - var nodeRect = sankeyNode.selectAll('.' + _$constants_856.cn.nodeRect) - .data(__repeat_860); + var nodeRect = sankeyNode.selectAll('.' + _$constants_921.cn.nodeRect) + .data(__repeat_925); nodeRect.enter() .append('rect') - .classed(_$constants_856.cn.nodeRect, true) + .classed(_$constants_921.cn.nodeRect, true) .call(sizeNode); nodeRect .style('stroke-width', function(d) {return d.nodeLineWidth;}) - .style('stroke', function(d) {return _$color_411.tinyRGB(_$tinycolor_352(d.nodeLineColor));}) - .style('stroke-opacity', function(d) {return _$color_411.opacity(d.nodeLineColor);}) + .style('stroke', function(d) {return _$color_473.tinyRGB(_$tinycolor_414(d.nodeLineColor));}) + .style('stroke-opacity', function(d) {return _$color_473.opacity(d.nodeLineColor);}) .style('fill', function(d) {return d.tinyColorHue;}) .style('fill-opacity', function(d) {return d.tinyColorAlpha;}); nodeRect.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .call(sizeNode); - var nodeCapture = sankeyNode.selectAll('.' + _$constants_856.cn.nodeCapture) - .data(__repeat_860); + var nodeCapture = sankeyNode.selectAll('.' + _$constants_921.cn.nodeCapture) + .data(__repeat_925); nodeCapture.enter() .append('rect') - .classed(_$constants_856.cn.nodeCapture, true) + .classed(_$constants_921.cn.nodeCapture, true) .style('fill-opacity', 0); nodeCapture @@ -136316,41 +137530,41 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .attr('width', function(d) {return d.zoneWidth;}) .attr('height', function(d) {return d.zoneHeight;}); - var nodeCentered = sankeyNode.selectAll('.' + _$constants_856.cn.nodeCentered) - .data(__repeat_860); + var nodeCentered = sankeyNode.selectAll('.' + _$constants_921.cn.nodeCentered) + .data(__repeat_925); nodeCentered.enter() .append('g') - .classed(_$constants_856.cn.nodeCentered, true) + .classed(_$constants_921.cn.nodeCentered, true) .attr('transform', nodeCentering); nodeCentered .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('transform', nodeCentering); - var nodeLabelGuide = nodeCentered.selectAll('.' + _$constants_856.cn.nodeLabelGuide) - .data(__repeat_860); + var nodeLabelGuide = nodeCentered.selectAll('.' + _$constants_921.cn.nodeLabelGuide) + .data(__repeat_925); nodeLabelGuide.enter() .append('path') - .classed(_$constants_856.cn.nodeLabelGuide, true) + .classed(_$constants_921.cn.nodeLabelGuide, true) .attr('id', function(d) {return d.uniqueNodeLabelPathId;}) .attr('d', textGuidePath) .attr('transform', sankeyInverseTransform); nodeLabelGuide .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('d', textGuidePath) .attr('transform', sankeyInverseTransform); - var nodeLabel = nodeCentered.selectAll('.' + _$constants_856.cn.nodeLabel) - .data(__repeat_860); + var nodeLabel = nodeCentered.selectAll('.' + _$constants_921.cn.nodeLabel) + .data(__repeat_925); nodeLabel.enter() .append('text') - .classed(_$constants_856.cn.nodeLabel, true) + .classed(_$constants_921.cn.nodeLabel, true) .attr('transform', textFlip) .style('user-select', 'none') .style('cursor', 'default') @@ -136360,19 +137574,19 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .style('text-shadow', function(d) { return d.horizontal ? '-1px 1px 1px #fff, 1px 1px 1px #fff, 1px -1px 1px #fff, -1px -1px 1px #fff' : 'none'; }) - .each(function(d) {_$drawing_436.font(nodeLabel, d.textFont);}); + .each(function(d) {_$drawing_498.font(nodeLabel, d.textFont);}); nodeLabel .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('transform', textFlip); - var nodeLabelTextPath = nodeLabel.selectAll('.' + _$constants_856.cn.nodeLabelTextPath) - .data(__repeat_860); + var nodeLabelTextPath = nodeLabel.selectAll('.' + _$constants_921.cn.nodeLabelTextPath) + .data(__repeat_925); nodeLabelTextPath.enter() .append('textPath') - .classed(_$constants_856.cn.nodeLabelTextPath, true) + .classed(_$constants_921.cn.nodeLabelTextPath, true) .attr('alignment-baseline', 'middle') .attr('xlink:href', function(d) {return '#' + d.uniqueNodeLabelPathId;}) .attr('startOffset', nodeTextOffset) @@ -136384,7 +137598,7 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { nodeLabelTextPath .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('startOffset', nodeTextOffset) .style('fill', nodeTextColor); }; @@ -136399,14 +137613,14 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$render_860 = require('./render'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __cn_859 = _$constants_856.cn; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$render_925 = require('./render'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __cn_924 = _$constants_921.cn; -var ____859 = _$lib_539._; +var ____924 = _$lib_601._; function renderableValuePresent(d) {return d !== '';} @@ -136415,16 +137629,16 @@ function ownTrace(selection, d) { } function makeTranslucent(element, alpha) { - _$d3_127.select(element) + _$d3_130.select(element) .select('path') .style('fill-opacity', alpha); - _$d3_127.select(element) + _$d3_130.select(element) .select('rect') .style('fill-opacity', alpha); } function makeTextContrasty(element) { - _$d3_127.select(element) + _$d3_130.select(element) .select('text.name') .style('fill', 'black'); } @@ -136444,7 +137658,7 @@ function relatedNodes(l) { function nodeHoveredStyle(sankeyNode, d, sankey) { if(d && sankey) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(relatedLinks(d)) .call(linkHoveredStyle.bind(0, d, sankey, false)); } @@ -136453,7 +137667,7 @@ function nodeHoveredStyle(sankeyNode, d, sankey) { function nodeNonHoveredStyle(sankeyNode, d, sankey) { if(d && sankey) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(relatedLinks(d)) .call(linkNonHoveredStyle.bind(0, d, sankey, false)); } @@ -136467,14 +137681,14 @@ function linkHoveredStyle(d, sankey, visitNodes, sankeyLink) { if(label) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(function(l) {return l.link.label === label;}) .style('fill-opacity', 0.4); } if(visitNodes) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyNode) + .selectAll('.' + __cn_924.sankeyNode) .filter(relatedNodes(d)) .call(nodeHoveredStyle); } @@ -136488,50 +137702,50 @@ function linkNonHoveredStyle(d, sankey, visitNodes, sankeyLink) { if(label) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(function(l) {return l.link.label === label;}) .style('fill-opacity', function(d) {return d.tinyColorAlpha;}); } if(visitNodes) { ownTrace(sankey, d) - .selectAll(__cn_859.sankeyNode) + .selectAll(__cn_924.sankeyNode) .filter(relatedNodes(d)) .call(nodeNonHoveredStyle); } } // does not support array values for now -function __castHoverOption_859(trace, attr) { +function __castHoverOption_924(trace, attr) { var labelOpts = trace.hoverlabel || {}; - var val = _$lib_539.nestedProperty(labelOpts, attr).get(); + var val = _$lib_601.nestedProperty(labelOpts, attr).get(); return Array.isArray(val) ? false : val; } -var _$plot_859 = function plot(gd, calcData) { +var _$plot_924 = function plot(gd, calcData) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var size = fullLayout._size; var linkSelect = function(element, d) { var evt = d.link; - evt.originalEvent = _$d3_127.event; + evt.originalEvent = _$d3_130.event; gd._hoverdata = [evt]; - _$fx_453.click(gd, { target: true }); + _$fx_515.click(gd, { target: true }); }; var linkHover = function(element, d, sankey) { - _$d3_127.select(element).call(linkHoveredStyle.bind(0, d, sankey, true)); + _$d3_130.select(element).call(linkHoveredStyle.bind(0, d, sankey, true)); gd.emit('plotly_hover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.link] }); }; - var sourceLabel = ____859(gd, 'source:') + ' '; - var targetLabel = ____859(gd, 'target:') + ' '; - var incomingLabel = ____859(gd, 'incoming flow count:') + ' '; - var outgoingLabel = ____859(gd, 'outgoing flow count:') + ' '; + var sourceLabel = ____924(gd, 'source:') + ' '; + var targetLabel = ____924(gd, 'target:') + ' '; + var incomingLabel = ____924(gd, 'incoming flow count:') + ' '; + var outgoingLabel = ____924(gd, 'outgoing flow count:') + ' '; var linkHoverFollow = function(element, d) { var trace = d.link.trace; @@ -136540,21 +137754,21 @@ var _$plot_859 = function plot(gd, calcData) { var hoverCenterX = boundingBox.left + boundingBox.width / 2; var hoverCenterY = boundingBox.top + boundingBox.height / 2; - var tooltip = _$fx_453.loneHover({ + var tooltip = _$fx_515.loneHover({ x: hoverCenterX - rootBBox.left, y: hoverCenterY - rootBBox.top, - name: _$d3_127.format(d.valueFormat)(d.link.value) + d.valueSuffix, + name: _$d3_130.format(d.valueFormat)(d.link.value) + d.valueSuffix, text: [ d.link.label || '', sourceLabel + d.link.source.label, targetLabel + d.link.target.label ].filter(renderableValuePresent).join('
'), - color: __castHoverOption_859(trace, 'bgcolor') || _$color_411.addOpacity(d.tinyColorHue, 1), - borderColor: __castHoverOption_859(trace, 'bordercolor'), - fontFamily: __castHoverOption_859(trace, 'font.family'), - fontSize: __castHoverOption_859(trace, 'font.size'), - fontColor: __castHoverOption_859(trace, 'font.color'), - idealAlign: _$d3_127.event.x < hoverCenterX ? 'right' : 'left' + color: __castHoverOption_924(trace, 'bgcolor') || _$color_473.addOpacity(d.tinyColorHue, 1), + borderColor: __castHoverOption_924(trace, 'bordercolor'), + fontFamily: __castHoverOption_924(trace, 'font.family'), + fontSize: __castHoverOption_924(trace, 'font.size'), + fontColor: __castHoverOption_924(trace, 'font.color'), + idealAlign: _$d3_130.event.x < hoverCenterX ? 'right' : 'left' }, { container: fullLayout._hoverlayer.node(), outerContainer: fullLayout._paper.node(), @@ -136566,55 +137780,55 @@ var _$plot_859 = function plot(gd, calcData) { }; var linkUnhover = function(element, d, sankey) { - _$d3_127.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true)); + _$d3_130.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true)); gd.emit('plotly_unhover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.link] }); - _$fx_453.loneUnhover(fullLayout._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout._hoverlayer.node()); }; var nodeSelect = function(element, d, sankey) { var evt = d.node; - evt.originalEvent = _$d3_127.event; + evt.originalEvent = _$d3_130.event; gd._hoverdata = [evt]; - _$d3_127.select(element).call(nodeNonHoveredStyle, d, sankey); - _$fx_453.click(gd, { target: true }); + _$d3_130.select(element).call(nodeNonHoveredStyle, d, sankey); + _$fx_515.click(gd, { target: true }); }; var nodeHover = function(element, d, sankey) { - _$d3_127.select(element).call(nodeHoveredStyle, d, sankey); + _$d3_130.select(element).call(nodeHoveredStyle, d, sankey); gd.emit('plotly_hover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.node] }); }; var nodeHoverFollow = function(element, d) { var trace = d.node.trace; - var nodeRect = _$d3_127.select(element).select('.' + __cn_859.nodeRect); + var nodeRect = _$d3_130.select(element).select('.' + __cn_924.nodeRect); var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect(); var boundingBox = nodeRect.node().getBoundingClientRect(); var hoverCenterX0 = boundingBox.left - 2 - rootBBox.left; var hoverCenterX1 = boundingBox.right + 2 - rootBBox.left; var hoverCenterY = boundingBox.top + boundingBox.height / 4 - rootBBox.top; - var tooltip = _$fx_453.loneHover({ + var tooltip = _$fx_515.loneHover({ x0: hoverCenterX0, x1: hoverCenterX1, y: hoverCenterY, - name: _$d3_127.format(d.valueFormat)(d.node.value) + d.valueSuffix, + name: _$d3_130.format(d.valueFormat)(d.node.value) + d.valueSuffix, text: [ d.node.label, incomingLabel + d.node.targetLinks.length, outgoingLabel + d.node.sourceLinks.length ].filter(renderableValuePresent).join('
'), - color: __castHoverOption_859(trace, 'bgcolor') || d.tinyColorHue, - borderColor: __castHoverOption_859(trace, 'bordercolor'), - fontFamily: __castHoverOption_859(trace, 'font.family'), - fontSize: __castHoverOption_859(trace, 'font.size'), - fontColor: __castHoverOption_859(trace, 'font.color'), + color: __castHoverOption_924(trace, 'bgcolor') || d.tinyColorHue, + borderColor: __castHoverOption_924(trace, 'bordercolor'), + fontFamily: __castHoverOption_924(trace, 'font.family'), + fontSize: __castHoverOption_924(trace, 'font.size'), + fontColor: __castHoverOption_924(trace, 'font.color'), idealAlign: 'left' }, { container: fullLayout._hoverlayer.node(), @@ -136627,16 +137841,16 @@ var _$plot_859 = function plot(gd, calcData) { }; var nodeUnhover = function(element, d, sankey) { - _$d3_127.select(element).call(nodeNonHoveredStyle, d, sankey); + _$d3_130.select(element).call(nodeNonHoveredStyle, d, sankey); gd.emit('plotly_unhover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.node] }); - _$fx_453.loneUnhover(fullLayout._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout._hoverlayer.node()); }; - _$render_860( + _$render_925( svg, calcData, { @@ -136666,7 +137880,7 @@ var _$plot_859 = function plot(gd, calcData) { ); }; -var _$base_plot_854 = {}; +var _$base_plot_919 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -136677,25 +137891,25 @@ var _$base_plot_854 = {}; 'use strict'; -var __overrideAll_854 = _$edit_types_569.overrideAll; -var __getModuleCalcData_854 = _$get_data_621.getModuleCalcData; -/* removed: var _$plot_859 = require('./plot'); */; -/* removed: var _$layout_attributes_454 = require('../../components/fx/layout_attributes'); */; +var __overrideAll_919 = _$edit_types_632.overrideAll; +var __getModuleCalcData_919 = _$get_data_683.getModuleCalcData; +/* removed: var _$plot_924 = require('./plot'); */; +/* removed: var _$layout_attributes_516 = require('../../components/fx/layout_attributes'); */; var SANKEY = 'sankey'; -_$base_plot_854.name = SANKEY; +_$base_plot_919.name = SANKEY; -_$base_plot_854.baseLayoutAttrOverrides = __overrideAll_854({ - hoverlabel: _$layout_attributes_454.hoverlabel +_$base_plot_919.baseLayoutAttrOverrides = __overrideAll_919({ + hoverlabel: _$layout_attributes_516.hoverlabel }, 'plot', 'nested'); -_$base_plot_854.plot = function(gd) { - var calcData = __getModuleCalcData_854(gd.calcdata, SANKEY); - _$plot_859(gd, calcData); +_$base_plot_919.plot = function(gd) { + var calcData = __getModuleCalcData_919(gd.calcdata, SANKEY)[0]; + _$plot_924(gd, calcData); }; -_$base_plot_854.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_919.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPlot = (oldFullLayout._has && oldFullLayout._has(SANKEY)); var hasPlot = (newFullLayout._has && newFullLayout._has(SANKEY)); @@ -136706,7 +137920,7 @@ _$base_plot_854.clean = function(newFullData, newFullLayout, oldFullData, oldFul "use strict" -var _$stronglyConnectedComponents_344 = stronglyConnectedComponents +var _$stronglyConnectedComponents_406 = stronglyConnectedComponents function stronglyConnectedComponents(adjList) { var numVertices = adjList.length; @@ -136829,9 +138043,9 @@ function stronglyConnectedComponents(adjList) { 'use strict'; -/* removed: var _$stronglyConnectedComponents_344 = require('strongly-connected-components'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __wrap_855 = _$gup_536.wrap; +/* removed: var _$stronglyConnectedComponents_406 = require('strongly-connected-components'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __wrap_920 = _$gup_598.wrap; function circularityPresent(nodeList, sources, targets) { @@ -136844,7 +138058,7 @@ function circularityPresent(nodeList, sources, targets) { nodes[sources[i]].push(targets[i]); } - var scc = _$stronglyConnectedComponents_344(nodes); + var scc = _$stronglyConnectedComponents_406(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 @@ -136853,10 +138067,10 @@ function circularityPresent(nodeList, sources, targets) { }); } -var _$calc_855 = function calc(gd, trace) { +var _$calc_920 = function calc(gd, trace) { if(circularityPresent(trace.node.label, trace.link.source, trace.link.target)) { - _$lib_539.error('Circularity is present in the Sankey data. Removing all nodes and links.'); + _$lib_601.error('Circularity is present in the Sankey data. Removing all nodes and links.'); trace.link.label = []; trace.link.source = []; trace.link.target = []; @@ -136866,7 +138080,7 @@ var _$calc_855 = function calc(gd, trace) { trace.node.color = []; } - return __wrap_855({ + return __wrap_920({ link: trace.link, node: trace.node }); @@ -136882,15 +138096,15 @@ var _$calc_855 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_853 = require('./attributes'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -var __handleDomainDefaults_857 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_918 = require('./attributes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +var __handleDomainDefaults_922 = _$domain_672.defaults; -var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_853, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_918, attr, dflt); } coerce('node.label'); @@ -136904,7 +138118,7 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol var defaultNodePalette = function(i) {return colors[i % colors.length];}; coerce('node.color', traceOut.node.label.map(function(d, i) { - return _$color_411.addOpacity(defaultNodePalette(i), 0.8); + return _$color_473.addOpacity(defaultNodePalette(i), 0.8); })); coerce('link.label'); @@ -136915,19 +138129,19 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('link.line.width'); coerce('link.color', traceOut.link.value.map(function() { - return _$tinycolor_352(layout.paper_bgcolor).getLuminance() < 0.333 ? + return _$tinycolor_414(layout.paper_bgcolor).getLuminance() < 0.333 ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.2)'; })); - __handleDomainDefaults_857(traceOut, layout, coerce); + __handleDomainDefaults_922(traceOut, layout, coerce); coerce('orientation'); coerce('valueformat'); coerce('valuesuffix'); coerce('arrangement'); - _$lib_539.coerceFont(coerce, 'textfont', _$lib_539.extendFlat({}, layout.font)); + _$lib_601.coerceFont(coerce, 'textfont', _$lib_601.extendFlat({}, layout.font)); var missing = function(n, i) { return traceOut.link.source.indexOf(i) === -1 && @@ -136935,7 +138149,7 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol }; if(traceOut.node.label.some(missing)) { - _$lib_539.warn('Some of the nodes are neither sources nor targets, they will not be displayed.'); + _$lib_601.warn('Some of the nodes are neither sources nor targets, they will not be displayed.'); } }; @@ -136951,14 +138165,14 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol var Plot = {}; -Plot.attributes = _$attributes_853; -Plot.supplyDefaults = _$supplyDefaults_857; -Plot.calc = _$calc_855; -Plot.plot = _$plot_859; +Plot.attributes = _$attributes_918; +Plot.supplyDefaults = _$supplyDefaults_922; +Plot.calc = _$calc_920; +Plot.plot = _$plot_924; Plot.moduleType = 'trace'; Plot.name = 'sankey'; -Plot.basePlotModule = _$base_plot_854; +Plot.basePlotModule = _$base_plot_919; Plot.categories = ['noOpacity']; Plot.meta = { description: [ @@ -136968,7 +138182,7 @@ Plot.meta = { ].join(' ') }; -var _$Plot_858 = Plot; +var _$Plot_923 = Plot; /** * Copyright 2012-2018, Plotly, Inc. @@ -136980,7 +138194,7 @@ var _$Plot_858 = Plot; 'use strict'; -var _$sankey_26 = _$Plot_858; +var _$sankey_26 = _$Plot_923; /** * Copyright 2012-2018, Plotly, Inc. @@ -136993,7 +138207,7 @@ var _$sankey_26 = _$Plot_858; 'use strict'; -var _$gl3d_markers_515 = { +var _$gl3d_markers_576 = { circle: '●', 'circle-open': '○', square: '■', @@ -137015,7 +138229,7 @@ var _$gl3d_markers_515 = { 'use strict'; -var _$gl3d_dashes_514 = { +var _$gl3d_dashes_575 = { solid: [[], 0], dot: [[0.5, 1], 200], dash: [[0.5, 1], 50], @@ -137024,7 +138238,7 @@ var _$gl3d_dashes_514 = { longdashdot: [[0.5, 0.7, 0.8, 1], 10] }; -var _$attributes_887 = {}; +var _$attributes_952 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -137035,18 +138249,18 @@ var _$attributes_887 = {}; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$gl3d_dashes_514 = require('../../constants/gl3d_dashes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$gl3d_dashes_575 = require('../../constants/gl3d_dashes'); */; -/* removed: var _$gl3d_markers_515 = require('../../constants/gl3d_markers'); */; -var __extendFlat_887 = _$extend_528.extendFlat; -var __overrideAll_887 = _$edit_types_569.overrideAll; +/* removed: var _$gl3d_markers_576 = require('../../constants/gl3d_markers'); */; +var __extendFlat_952 = _$extend_590.extendFlat; +var __overrideAll_952 = _$edit_types_632.overrideAll; -var __scatterLineAttrs_887 = _$attributes_862.line; -var __scatterMarkerAttrs_887 = _$attributes_862.marker; -var __scatterMarkerLineAttrs_887 = __scatterMarkerAttrs_887.line; +var __scatterLineAttrs_952 = _$attributes_927.line; +var __scatterMarkerAttrs_952 = _$attributes_927.marker; +var __scatterMarkerLineAttrs_952 = __scatterMarkerAttrs_952.line; function makeProjectionAttr(axLetter) { return { @@ -137081,15 +138295,15 @@ function makeProjectionAttr(axLetter) { }; } -var __attrs_887 = _$attributes_887 = __overrideAll_887({ - x: _$attributes_862.x, - y: _$attributes_862.y, +var __attrs_952 = _$attributes_952 = __overrideAll_952({ + x: _$attributes_927.x, + y: _$attributes_927.y, z: { valType: 'data_array', description: 'Sets the z coordinates.' }, - text: __extendFlat_887({}, _$attributes_862.text, { + text: __extendFlat_952({}, _$attributes_927.text, { description: [ 'Sets text elements associated with each (x,y,z) triplet.', 'If a single string, the same string appears over', @@ -137100,7 +138314,7 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ 'these elements will be seen in the hover labels.' ].join(' ') }), - hovertext: __extendFlat_887({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_952({}, _$attributes_927.hovertext, { description: [ 'Sets text elements associated with each (x,y,z) triplet.', 'If a single string, the same string appears over', @@ -137111,7 +138325,7 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ ].join(' ') }), - mode: __extendFlat_887({}, _$attributes_862.mode, // shouldn't this be on-par with 2D? + mode: __extendFlat_952({}, _$attributes_927.mode, // shouldn't this be on-par with 2D? {dflt: 'lines+markers'}), surfaceaxis: { valType: 'enumerated', @@ -137134,12 +138348,12 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ y: makeProjectionAttr('y'), z: makeProjectionAttr('z') }, - connectgaps: _$attributes_862.connectgaps, - line: __extendFlat_887({ - width: __scatterLineAttrs_887.width, + connectgaps: _$attributes_927.connectgaps, + line: __extendFlat_952({ + width: __scatterLineAttrs_952.width, dash: { valType: 'enumerated', - values: Object.keys(_$gl3d_dashes_514), + values: Object.keys(_$gl3d_dashes_575), dflt: 'solid', role: 'style', description: 'Sets the dash style of the lines.' @@ -137154,22 +138368,22 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ ].join(' ') } }, - _$makeColorScaleAttributes_419('line') + _$makeColorScaleAttributes_481('line') ), - marker: __extendFlat_887({ // Parity with scatter.js? + marker: __extendFlat_952({ // Parity with scatter.js? symbol: { valType: 'enumerated', - values: Object.keys(_$gl3d_markers_515), + values: Object.keys(_$gl3d_markers_576), role: 'style', dflt: 'circle', arrayOk: true, description: 'Sets the marker symbol type.' }, - size: __extendFlat_887({}, __scatterMarkerAttrs_887.size, {dflt: 8}), - sizeref: __scatterMarkerAttrs_887.sizeref, - sizemin: __scatterMarkerAttrs_887.sizemin, - sizemode: __scatterMarkerAttrs_887.sizemode, - opacity: __extendFlat_887({}, __scatterMarkerAttrs_887.opacity, { + size: __extendFlat_952({}, __scatterMarkerAttrs_952.size, {dflt: 8}), + sizeref: __scatterMarkerAttrs_952.sizeref, + sizemin: __scatterMarkerAttrs_952.sizemin, + sizemode: __scatterMarkerAttrs_952.sizemode, + opacity: __extendFlat_952({}, __scatterMarkerAttrs_952.opacity, { arrayOk: false, description: [ 'Sets the marker opacity.', @@ -137180,36 +138394,36 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ 'to an rgba color and use its alpha channel.' ].join(' ') }), - showscale: __scatterMarkerAttrs_887.showscale, - colorbar: __scatterMarkerAttrs_887.colorbar, + showscale: __scatterMarkerAttrs_952.showscale, + colorbar: __scatterMarkerAttrs_952.colorbar, - line: __extendFlat_887({ - width: __extendFlat_887({}, __scatterMarkerLineAttrs_887.width, {arrayOk: false}) + line: __extendFlat_952({ + width: __extendFlat_952({}, __scatterMarkerLineAttrs_952.width, {arrayOk: false}) }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ) }, - _$makeColorScaleAttributes_419('marker') + _$makeColorScaleAttributes_481('marker') ), - textposition: __extendFlat_887({}, _$attributes_862.textposition, {dflt: 'top center'}), - textfont: _$attributes_862.textfont, + textposition: __extendFlat_952({}, _$attributes_927.textposition, {dflt: 'top center'}), + textfont: _$attributes_927.textfont, - hoverinfo: __extendFlat_887({}, _$attributes_581.hoverinfo) + hoverinfo: __extendFlat_952({}, _$attributes_644.hoverinfo) }, 'calc', 'nested'); -__attrs_887.x.editType = __attrs_887.y.editType = __attrs_887.z.editType = 'calc+clearAxisTypes'; +__attrs_952.x.editType = __attrs_952.y.editType = __attrs_952.z.editType = 'calc+clearAxisTypes'; 'use strict' -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -var __vertSrc_157 = _$browser_238(["precision mediump 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_157 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}"]) +var __vertSrc_214 = _$browser_295(["precision mediump 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_214 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}"]) -var _$shaders_157 = function(gl) { - return _$createShader_206(gl, __vertSrc_157, __fragSrc_157, null, [ +var _$shaders_214 = function(gl) { + return _$createShader_263(gl, __vertSrc_214, __fragSrc_214, null, [ {name: 'position', type: 'vec3'}, {name: 'color', type: 'vec4'}, {name: 'offset', type: 'vec3'} @@ -137218,11 +138432,11 @@ var _$shaders_157 = function(gl) { 'use strict' -var _$createErrorBars_156 = createErrorBars +var _$createErrorBars_213 = createErrorBars -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -/* removed: var _$shaders_157 = require('./shaders/index') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +/* removed: var _$shaders_214 = require('./shaders/index') */; var IDENTITY = [1,0,0,0, 0,1,0,0, @@ -137244,17 +138458,17 @@ function ErrorBars(gl, buffer, vao, shader) { this.opacity = 1 } -var __proto_156 = ErrorBars.prototype +var __proto_213 = ErrorBars.prototype -__proto_156.isOpaque = function() { +__proto_213.isOpaque = function() { return this.opacity >= 1 } -__proto_156.isTransparent = function() { +__proto_213.isTransparent = function() { return this.opacity < 1 } -__proto_156.drawTransparent = __proto_156.draw = function(cameraParams) { +__proto_213.drawTransparent = __proto_213.draw = function(cameraParams) { var gl = this.gl var uniforms = this.shader.uniforms @@ -137319,7 +138533,7 @@ function emitFace(verts, x, c, d) { return offsets.length } -__proto_156.update = function(options) { +__proto_213.update = function(options) { options = options || {} if('lineWidth' in options) { @@ -137410,7 +138624,7 @@ i_loop: } } -__proto_156.dispose = function() { +__proto_213.dispose = function() { this.shader.dispose() this.buffer.dispose() this.vao.dispose() @@ -137418,8 +138632,8 @@ __proto_156.dispose = function() { function createErrorBars(options) { var gl = options.gl - var buffer = _$createBuffer_153(gl) - var vao = _$createVAO_222(gl, [ + var buffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { buffer: buffer, type: gl.FLOAT, @@ -137443,7 +138657,7 @@ function createErrorBars(options) { } ]) - var shader = _$shaders_157(gl) + var shader = _$shaders_214(gl) shader.attributes.position.location = 0 shader.attributes.color.location = 1 shader.attributes.offset.location = 2 @@ -137453,13 +138667,13 @@ function createErrorBars(options) { return result } -var _$shaders_163 = {}; -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +var _$shaders_220 = {}; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -var __vertSrc_163 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]) -var forwardFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]) -var pickFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]) +var __vertSrc_220 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]) +var forwardFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]) +var pickFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]) var ATTRIBUTES = [ {name: 'position', type: 'vec3'}, @@ -137469,15 +138683,15 @@ var ATTRIBUTES = [ {name: 'color', type: 'vec4'} ] -_$shaders_163.createShader = function(gl) { - return _$createShader_206(gl, __vertSrc_163, forwardFrag, null, ATTRIBUTES) +_$shaders_220.createShader = function(gl) { + return _$createShader_263(gl, __vertSrc_220, forwardFrag, null, ATTRIBUTES) } -_$shaders_163.createPickShader = function(gl) { - return _$createShader_206(gl, __vertSrc_163, pickFrag, null, ATTRIBUTES) +_$shaders_220.createPickShader = function(gl) { + return _$createShader_263(gl, __vertSrc_220, pickFrag, null, ATTRIBUTES) } -var _$decodeFloat_229 = decodeFloat +var _$decodeFloat_286 = decodeFloat var UINT8_VIEW = new Uint8Array(4) var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) @@ -137492,20 +138706,20 @@ function decodeFloat(x, y, z, w) { 'use strict' -var _$createLinePlot_164 = createLinePlot +var _$createLinePlot_221 = createLinePlot -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -/* removed: var _$createTexture2D_218 = require('gl-texture2d') */; -/* removed: var _$decodeFloat_229 = require('glsl-read-float') */; -/* removed: var _$searchBounds_71 = require('binary-search-bounds') */; -/* removed: var _$wrappedNDArrayCtor_277 = require('ndarray') */; -/* removed: var _$shaders_163 = require('./lib/shaders') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +/* removed: var _$createTexture2D_275 = require('gl-texture2d') */; +/* removed: var _$decodeFloat_286 = require('glsl-read-float') */; +/* removed: var _$searchBounds_72 = require('binary-search-bounds') */; +/* removed: var _$wrappedNDArrayCtor_335 = require('ndarray') */; +/* removed: var _$shaders_220 = require('./lib/shaders') */; -var __createShader_164 = _$shaders_163.createShader -var __createPickShader_164 = _$shaders_163.createPickShader +var __createShader_221 = _$shaders_220.createShader +var __createPickShader_221 = _$shaders_220.createPickShader -var __identity_164 = [1, 0, 0, 0, +var __identity_221 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] @@ -137557,31 +138771,31 @@ function LinePlot (gl, shader, pickShader, buffer, vao, texture) { this.pixelRatio = 1 } -var __proto_164 = LinePlot.prototype +var __proto_221 = LinePlot.prototype -__proto_164.isTransparent = function () { +__proto_221.isTransparent = function () { return this.opacity < 1 } -__proto_164.isOpaque = function () { +__proto_221.isOpaque = function () { return this.opacity >= 1 } -__proto_164.pickSlots = 1 +__proto_221.pickSlots = 1 -__proto_164.setPickBase = function (id) { +__proto_221.setPickBase = function (id) { this.pickId = id } -__proto_164.drawTransparent = __proto_164.draw = function (camera) { +__proto_221.drawTransparent = __proto_221.draw = function (camera) { var gl = this.gl var shader = this.shader var vao = this.vao shader.bind() shader.uniforms = { - model: camera.model || __identity_164, - view: camera.view || __identity_164, - projection: camera.projection || __identity_164, + model: camera.model || __identity_221, + view: camera.view || __identity_221, + projection: camera.projection || __identity_221, clipBounds: filterClipBounds(this.clipBounds), dashTexture: this.texture.bind(), dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], @@ -137594,15 +138808,15 @@ __proto_164.drawTransparent = __proto_164.draw = function (camera) { vao.unbind() } -__proto_164.drawPick = function (camera) { +__proto_221.drawPick = function (camera) { var gl = this.gl var shader = this.pickShader var vao = this.vao shader.bind() shader.uniforms = { - model: camera.model || __identity_164, - view: camera.view || __identity_164, - projection: camera.projection || __identity_164, + model: camera.model || __identity_221, + view: camera.view || __identity_221, + projection: camera.projection || __identity_221, pickId: this.pickId, clipBounds: filterClipBounds(this.clipBounds), screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], @@ -137613,7 +138827,7 @@ __proto_164.drawPick = function (camera) { vao.unbind() } -__proto_164.update = function (options) { +__proto_221.update = function (options) { var i, j this.dirty = true @@ -137737,12 +138951,12 @@ __proto_164.update = function (options) { prefixSum[i] = prefixSum[i - 1] + prefixSum[i] } - var dashTexture = _$wrappedNDArrayCtor_277(new Array(256 * 4), [256, 1, 4]) + var dashTexture = _$wrappedNDArrayCtor_335(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 (_$searchBounds_71.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { + if (_$searchBounds_72.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { dashTexture.set(i, 0, 0, 0) } else { dashTexture.set(i, 0, 0, 255) @@ -137753,25 +138967,25 @@ __proto_164.update = function (options) { } } -__proto_164.dispose = function () { +__proto_221.dispose = function () { this.shader.dispose() this.vao.dispose() this.buffer.dispose() } -__proto_164.pick = function (selection) { +__proto_221.pick = function (selection) { if (!selection) { return null } if (selection.id !== this.pickId) { return null } - var tau = _$decodeFloat_229( + var tau = _$decodeFloat_286( selection.value[0], selection.value[1], selection.value[2], 0) - var index = _$searchBounds_71.le(this.arcLength, tau) + var index = _$searchBounds_72.le(this.arcLength, tau) if (index < 0) { return null } @@ -137800,22 +139014,22 @@ __proto_164.pick = function (selection) { function createLinePlot (options) { var gl = options.gl || (options.scene && options.scene.gl) - var shader = __createShader_164(gl) + var shader = __createShader_221(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_164(gl) + var pickShader = __createPickShader_221(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_153(gl) - var vao = _$createVAO_222(gl, [ + var buffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { 'buffer': buffer, 'size': 3, @@ -137849,11 +139063,11 @@ function createLinePlot (options) { ]) // Create texture for dash pattern - var defaultTexture = _$wrappedNDArrayCtor_277(new Array(256 * 4), [256, 1, 4]) + var defaultTexture = _$wrappedNDArrayCtor_335(new Array(256 * 4), [256, 1, 4]) for (var i = 0; i < 256 * 4; ++i) { defaultTexture.data[i] = 255 } - var texture = _$createTexture2D_218(gl, defaultTexture) + var texture = _$createTexture2D_275(gl, defaultTexture) texture.wrap = gl.REPEAT var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) @@ -137863,9 +139077,9 @@ function createLinePlot (options) { "use strict" -/* removed: var _$createText_367 = require("vectorize-text") */; +/* removed: var _$createText_429 = require("vectorize-text") */; -var _$getGlyph_200 = getGlyph +var _$getGlyph_257 = getGlyph var GLYPH_CACHE = {} @@ -137879,13 +139093,13 @@ function getGlyph(symbol, font) { } //Get line and triangle meshes for glyph - var lineSymbol = _$createText_367(symbol, { + var lineSymbol = _$createText_429(symbol, { textAlign: "center", textBaseline: "middle", lineHeight: 1.0, font: font }) - var triSymbol = _$createText_367(symbol, { + var triSymbol = _$createText_429(symbol, { triangles: true, textAlign: "center", textBaseline: "middle", @@ -137906,56 +139120,56 @@ function getGlyph(symbol, font) { //Save cached symbol return fontCache[symbol] = [triSymbol, lineSymbol, bounds] } -var _$shaders_201 = {}; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$browser_238 = require('glslify') */; +var _$shaders_258 = {}; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; -var perspectiveVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n"]) -var __pickFragSrc_201 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}"]) +var perspectiveVertSrc = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n"]) +var __pickFragSrc_258 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}"]) -var __ATTRIBUTES_201 = [ +var __ATTRIBUTES_258 = [ {name: 'position', type: 'vec3'}, {name: 'color', type: 'vec4'}, {name: 'glyph', type: 'vec2'}, {name: 'id', type: 'vec4'} ] -var __perspective_201 = { +var __perspective_258 = { vertex: perspectiveVertSrc, fragment: drawFragSrc, - attributes: __ATTRIBUTES_201 + attributes: __ATTRIBUTES_258 }, ortho = { vertex: orthographicVertSrc, fragment: drawFragSrc, - attributes: __ATTRIBUTES_201 + attributes: __ATTRIBUTES_258 }, - __project_201 = { + __project_258 = { vertex: projectionVertSrc, fragment: drawFragSrc, - attributes: __ATTRIBUTES_201 + attributes: __ATTRIBUTES_258 }, pickPerspective = { vertex: perspectiveVertSrc, - fragment: __pickFragSrc_201, - attributes: __ATTRIBUTES_201 + fragment: __pickFragSrc_258, + attributes: __ATTRIBUTES_258 }, pickOrtho = { vertex: orthographicVertSrc, - fragment: __pickFragSrc_201, - attributes: __ATTRIBUTES_201 + fragment: __pickFragSrc_258, + attributes: __ATTRIBUTES_258 }, pickProject = { vertex: projectionVertSrc, - fragment: __pickFragSrc_201, - attributes: __ATTRIBUTES_201 + fragment: __pickFragSrc_258, + attributes: __ATTRIBUTES_258 } -function __createShader_201(gl, src) { - var shader = _$createShader_206(gl, src) +function __createShader_258(gl, src) { + var shader = _$createShader_263(gl, src) var attr = shader.attributes attr.position.location = 0 attr.color.location = 1 @@ -137964,42 +139178,42 @@ function __createShader_201(gl, src) { return shader } -_$shaders_201.createPerspective = function(gl) { - return __createShader_201(gl, __perspective_201) +_$shaders_258.createPerspective = function(gl) { + return __createShader_258(gl, __perspective_258) } -_$shaders_201.createOrtho = function(gl) { - return __createShader_201(gl, ortho) +_$shaders_258.createOrtho = function(gl) { + return __createShader_258(gl, ortho) } -_$shaders_201.createProject = function(gl) { - return __createShader_201(gl, __project_201) +_$shaders_258.createProject = function(gl) { + return __createShader_258(gl, __project_258) } -_$shaders_201.createPickPerspective = function(gl) { - return __createShader_201(gl, pickPerspective) +_$shaders_258.createPickPerspective = function(gl) { + return __createShader_258(gl, pickPerspective) } -_$shaders_201.createPickOrtho = function(gl) { - return __createShader_201(gl, pickOrtho) +_$shaders_258.createPickOrtho = function(gl) { + return __createShader_258(gl, pickOrtho) } -_$shaders_201.createPickProject = function(gl) { - return __createShader_201(gl, pickProject) +_$shaders_258.createPickProject = function(gl) { + return __createShader_258(gl, pickProject) } 'use strict' -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -/* removed: var _$pool_360 = require('typedarray-pool') */; -/* removed: var _$multiply_175 = require('gl-mat4/multiply') */; -/* removed: var _$shaders_201 = require('./lib/shaders') */; -/* removed: var _$getGlyph_200 = require('./lib/glyphs') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; +/* removed: var _$multiply_232 = require('gl-mat4/multiply') */; +/* removed: var _$shaders_258 = require('./lib/shaders') */; +/* removed: var _$getGlyph_257 = require('./lib/glyphs') */; -var __IDENTITY_202 = [1,0,0,0, +var __IDENTITY_259 = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] -var _$createPointCloud_202 = createPointCloud +var _$createPointCloud_259 = createPointCloud -function __transformMat4_202(x, m) { +function __transformMat4_259(x, m) { var x0 = x[0] var x1 = x[1] var x2 = x[2] @@ -138011,10 +139225,10 @@ function __transformMat4_202(x, m) { return x } -function __project_202(p, v, m, x) { - __transformMat4_202(x, x, m) - __transformMat4_202(x, x, v) - return __transformMat4_202(x, x, p) +function __project_259(p, v, m, x) { + __transformMat4_259(x, x, m) + __transformMat4_259(x, x, v) + return __transformMat4_259(x, x, p) } function clampVec(v) { @@ -138092,15 +139306,15 @@ function PointCloud( this.dirty = true } -var __proto_202 = PointCloud.prototype +var __proto_259 = PointCloud.prototype -__proto_202.pickSlots = 1 +__proto_259.pickSlots = 1 -__proto_202.setPickBase = function(pickBase) { +__proto_259.setPickBase = function(pickBase) { this.pickId = pickBase } -__proto_202.isTransparent = function() { +__proto_259.isTransparent = function() { if(this.opacity < 1) { return true } @@ -138112,7 +139326,7 @@ __proto_202.isTransparent = function() { return false } -__proto_202.isOpaque = function() { +__proto_259.isOpaque = function() { if(this.opacity >= 1) { return true } @@ -138129,11 +139343,11 @@ var U_VEC = [0,0,0] var V_VEC = [0,0,0] var MU_VEC = [0,0,0,1] var MV_VEC = [0,0,0,1] -var SCRATCH_MATRIX = __IDENTITY_202.slice() +var SCRATCH_MATRIX = __IDENTITY_259.slice() var SCRATCH_VEC = [0,0,0] var CLIP_BOUNDS = [[0,0,0], [0,0,0]] -function __zeroVec_202(a) { +function __zeroVec_259(a) { a[0] = a[1] = a[2] = 0 return a } @@ -138169,9 +139383,9 @@ function drawProject(shader, points, camera, transparent, forceDraw) { var gl = points.gl var uniforms = shader.uniforms - var model = camera.model || __IDENTITY_202 - var view = camera.view || __IDENTITY_202 - var projection = camera.projection || __IDENTITY_202 + var model = camera.model || __IDENTITY_259 + var view = camera.view || __IDENTITY_259 + var projection = camera.projection || __IDENTITY_259 var bounds = points.axesBounds var clipBounds = getClipBounds(points.clipBounds) @@ -138220,20 +139434,20 @@ function drawProject(shader, points, camera, transparent, forceDraw) { } else { pmodel[12+i] = bounds[1][i] } - _$multiply_175(pmodel, model, pmodel) + _$multiply_232(pmodel, model, pmodel) uniforms.model = pmodel //Compute initial axes var u = (i+1)%3 var v = (i+2)%3 - var du = __zeroVec_202(U_VEC) - var dv = __zeroVec_202(V_VEC) + var du = __zeroVec_259(U_VEC) + var dv = __zeroVec_259(V_VEC) du[u] = 1 dv[v] = 1 //Align orientation relative to viewer - var mdu = __project_202(projection, view, model, augment(MU_VEC, du)) - var mdv = __project_202(projection, view, model, augment(MV_VEC, dv)) + var mdu = __project_259(projection, view, model, augment(MU_VEC, du)) + var mdv = __project_259(projection, view, model, augment(MV_VEC, dv)) if(Math.abs(mdu[1]) > Math.abs(mdv[1])) { var tmp = mdu mdu = mdv @@ -138291,9 +139505,9 @@ function drawFull(shader, pshader, points, camera, transparent, forceDraw) { shader.bind() var uniforms = shader.uniforms - uniforms.model = camera.model || __IDENTITY_202 - uniforms.view = camera.view || __IDENTITY_202 - uniforms.projection = camera.projection || __IDENTITY_202 + uniforms.model = camera.model || __IDENTITY_259 + uniforms.view = camera.view || __IDENTITY_259 + uniforms.projection = camera.projection || __IDENTITY_259 VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight @@ -138325,22 +139539,22 @@ function drawFull(shader, pshader, points, camera, transparent, forceDraw) { points.vao.unbind() } -__proto_202.draw = function(camera) { +__proto_259.draw = function(camera) { var shader = this.useOrtho ? this.orthoShader : this.shader drawFull(shader, this.projectShader, this, camera, false, false) } -__proto_202.drawTransparent = function(camera) { +__proto_259.drawTransparent = function(camera) { var shader = this.useOrtho ? this.orthoShader : this.shader drawFull(shader, this.projectShader, this, camera, true, false) } -__proto_202.drawPick = function(camera) { +__proto_259.drawPick = function(camera) { var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader drawFull(shader, this.pickProjectShader, this, camera, false, true) } -__proto_202.pick = function(selected) { +__proto_259.pick = function(selected) { if(!selected) { return null } @@ -138362,7 +139576,7 @@ __proto_202.pick = function(selected) { return result } -__proto_202.highlight = function(selection) { +__proto_259.highlight = function(selection) { if(!selection) { this.highlightId = [1,1,1,1] } else { @@ -138374,7 +139588,7 @@ __proto_202.highlight = function(selection) { } } -__proto_202.update = function(options) { +__proto_259.update = function(options) { options = options || {} @@ -138460,11 +139674,11 @@ count_loop: var glyphData if(Array.isArray(glyphs)) { - glyphData = _$getGlyph_200(glyphs[i], font) + glyphData = _$getGlyph_257(glyphs[i], font) } else if(glyphs) { - glyphData = _$getGlyph_200(glyphs, font) + glyphData = _$getGlyph_257(glyphs, font) } else { - glyphData = _$getGlyph_200('●', font) + glyphData = _$getGlyph_257('●', font) } var glyphMesh = glyphData[0] var glyphLines = glyphData[1] @@ -138477,10 +139691,10 @@ count_loop: //Preallocate data var vertexCount = triVertexCount + lineVertexCount - var positionArray = _$pool_360.mallocFloat(3*vertexCount) - var colorArray = _$pool_360.mallocFloat(4*vertexCount) - var glyphArray = _$pool_360.mallocFloat(2*vertexCount) - var idArray = _$pool_360.mallocUint32(vertexCount) + var positionArray = _$pool_422.mallocFloat(3*vertexCount) + var colorArray = _$pool_422.mallocFloat(4*vertexCount) + var glyphArray = _$pool_422.mallocFloat(2*vertexCount) + var idArray = _$pool_422.mallocUint32(vertexCount) var textOffset = [0,alignment[1]] @@ -138507,11 +139721,11 @@ fill_loop: var glyphData if(Array.isArray(glyphs)) { - glyphData = _$getGlyph_200(glyphs[i], font) + glyphData = _$getGlyph_257(glyphs[i], font) } else if(glyphs) { - glyphData = _$getGlyph_200(glyphs, font) + glyphData = _$getGlyph_257(glyphs, font) } else { - glyphData = _$getGlyph_200('●', font) + glyphData = _$getGlyph_257('●', font) } var glyphMesh = glyphData[0] var glyphLines = glyphData[1] @@ -138653,10 +139867,10 @@ fill_loop: this.glyphBuffer.update(glyphArray) this.idBuffer.update(new Uint32Array(idArray)) - _$pool_360.free(positionArray) - _$pool_360.free(colorArray) - _$pool_360.free(glyphArray) - _$pool_360.free(idArray) + _$pool_422.free(positionArray) + _$pool_422.free(colorArray) + _$pool_422.free(glyphArray) + _$pool_422.free(idArray) //Update bounds this.bounds = [lowerBound, upperBound] @@ -138668,7 +139882,7 @@ fill_loop: this.pointCount = points.length } -__proto_202.dispose = function() { +__proto_259.dispose = function() { //Shaders this.shader.dispose() this.orthoShader.dispose() @@ -138688,18 +139902,18 @@ __proto_202.dispose = function() { function createPointCloud(options) { var gl = options.gl - var shader = _$shaders_201.createPerspective(gl) - var orthoShader = _$shaders_201.createOrtho(gl) - var projectShader = _$shaders_201.createProject(gl) - var pickPerspectiveShader = _$shaders_201.createPickPerspective(gl) - var pickOrthoShader = _$shaders_201.createPickOrtho(gl) - var pickProjectShader = _$shaders_201.createPickProject(gl) - - var pointBuffer = _$createBuffer_153(gl) - var colorBuffer = _$createBuffer_153(gl) - var glyphBuffer = _$createBuffer_153(gl) - var idBuffer = _$createBuffer_153(gl) - var vao = _$createVAO_222(gl, [ + var shader = _$shaders_258.createPerspective(gl) + var orthoShader = _$shaders_258.createOrtho(gl) + var projectShader = _$shaders_258.createProject(gl) + var pickPerspectiveShader = _$shaders_258.createPickPerspective(gl) + var pickOrthoShader = _$shaders_258.createPickOrtho(gl) + var pickProjectShader = _$shaders_258.createPickProject(gl) + + var pointBuffer = _$createBuffer_210(gl) + var colorBuffer = _$createBuffer_210(gl) + var glyphBuffer = _$createBuffer_210(gl) + var idBuffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { buffer: pointBuffer, size: 3, @@ -138753,13 +139967,13 @@ function createPointCloud(options) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$normalize_99 = require('color-normalize'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$normalize_100 = require('color-normalize'); */; -/* removed: var _$colorscale_426 = require('../components/colorscale'); */; -var colorDflt = _$attributes_410.defaultLine; +/* removed: var _$colorscale_488 = require('../components/colorscale'); */; +var colorDflt = _$attributes_472.defaultLine; -var colorDfltRgba = _$normalize_99(colorDflt); +var colorDfltRgba = _$normalize_100(colorDflt); var opacityDflt = 1; function calculateColor(colorIn, opacityIn) { @@ -138769,15 +139983,15 @@ function calculateColor(colorIn, opacityIn) { } function validateColor(colorIn) { - if(_$fastIsnumeric_139(colorIn)) return colorDfltRgba; + if(_$fastIsnumeric_196(colorIn)) return colorDfltRgba; - var colorOut = _$normalize_99(colorIn); + var colorOut = _$normalize_100(colorIn); return colorOut.length ? colorOut : colorDfltRgba; } function validateOpacity(opacityIn) { - return _$fastIsnumeric_139(opacityIn) ? opacityIn : opacityDflt; + return _$fastIsnumeric_196(opacityIn) ? opacityIn : opacityDflt; } function formatColor(containerIn, opacityIn, len) { @@ -138789,8 +140003,8 @@ function formatColor(containerIn, opacityIn, len) { var sclFunc, getColor, getOpacity, colori, opacityi; if(containerIn.colorscale !== undefined) { - sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( containerIn.colorscale, containerIn.cmin, containerIn.cmax @@ -138804,7 +140018,7 @@ function formatColor(containerIn, opacityIn, len) { if(isArrayColorIn) { getColor = function(c, i) { // FIXME: there is double work, considering that sclFunc does the opposite - return c[i] === undefined ? colorDfltRgba : _$normalize_99(sclFunc(c[i])); + return c[i] === undefined ? colorDfltRgba : _$normalize_100(sclFunc(c[i])); }; } else getColor = validateColor; @@ -138823,12 +140037,12 @@ function formatColor(containerIn, opacityIn, len) { colorOut[i] = calculateColor(colori, opacityi); } } - else colorOut = calculateColor(_$normalize_99(colorIn), opacityIn); + else colorOut = calculateColor(_$normalize_100(colorIn), opacityIn); return colorOut; } -var _$formatColor_535 = formatColor; +var _$formatColor_597 = formatColor; /** * Copyright 2012-2018, Plotly, Inc. @@ -138841,12 +140055,12 @@ var _$formatColor_535 = formatColor; 'use strict'; -/* removed: var _$makeComputeError_440 = require('../../components/errorbars/compute_error'); */; +/* removed: var _$makeComputeError_502 = require('../../components/errorbars/compute_error'); */; function calculateAxisErrors(data, params, scaleFactor) { if(!params || !params.visible) return null; - var computeError = _$makeComputeError_440(params); + var computeError = _$makeComputeError_502(params); var result = new Array(data.length); for(var i = 0; i < data.length; i++) { @@ -138897,7 +140111,7 @@ function calculateErrors(data, scaleFactor) { return errorBounds; } -var _$calculateErrors_889 = calculateErrors; +var _$calculateErrors_954 = calculateErrors; /** * Copyright 2012-2018, Plotly, Inc. @@ -138910,20 +140124,20 @@ var _$calculateErrors_889 = calculateErrors; 'use strict'; -/* removed: var _$createLinePlot_164 = require('gl-line3d'); */; -/* removed: var _$createPointCloud_202 = require('gl-scatter3d'); */; -/* removed: var _$createErrorBars_156 = require('gl-error3d'); */; -/* removed: var _$createSimplicialMesh_187 = require('gl-mesh3d'); */; -/* removed: var _$triangulate_129 = require('delaunay-triangulate'); */; +/* removed: var _$createLinePlot_221 = require('gl-line3d'); */; +/* removed: var _$createPointCloud_259 = require('gl-scatter3d'); */; +/* removed: var _$createErrorBars_213 = require('gl-error3d'); */; +/* removed: var _$createSimplicialMesh_244 = require('gl-mesh3d'); */; +/* removed: var _$triangulate_132 = require('delaunay-triangulate'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; -/* removed: var _$formatColor_535 = require('../../lib/gl_format_color'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$gl3d_dashes_514 = require('../../constants/gl3d_dashes'); */; -/* removed: var _$gl3d_markers_515 = require('../../constants/gl3d_markers'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; +/* removed: var _$formatColor_597 = require('../../lib/gl_format_color'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../scatter/make_bubble_size_func'); */; +/* removed: var _$gl3d_dashes_575 = require('../../constants/gl3d_dashes'); */; +/* removed: var _$gl3d_markers_576 = require('../../constants/gl3d_markers'); */; -/* removed: var _$calculateErrors_889 = require('./calc_errors'); */; +/* removed: var _$calculateErrors_954 = require('./calc_errors'); */; function LineWithMarkers(scene, uid) { this.scene = scene; @@ -138944,9 +140158,9 @@ function LineWithMarkers(scene, uid) { this.data = null; } -var __proto_890 = LineWithMarkers.prototype; +var __proto_955 = LineWithMarkers.prototype; -__proto_890.handlePick = function(selection) { +__proto_955.handlePick = function(selection) { if(selection.object && (selection.object === this.linePlot || selection.object === this.delaunayMesh || @@ -138995,7 +140209,7 @@ function constructDelaunay(points, color, axis) { filteredPoints.push([p[u], p[v]]); filteredIds.push(i); } - var cells = _$triangulate_129(filteredPoints); + var cells = _$triangulate_132(filteredPoints); for(i = 0; i < cells.length; ++i) { var c = cells[i]; for(var j = 0; j < c.length; ++j) { @@ -139021,7 +140235,7 @@ function calculateErrorParams(errors) { if(!e) continue; capSize[i] = e.width / 2; // ballpark rescaling - color[i] = _$str2RgbaArray_561(e.color); + color[i] = _$str2RgbaArray_624(e.color); lineWidth = e.thickness; } @@ -139047,13 +140261,13 @@ function calculateSize(sizeIn, sizeFn) { } function calculateSymbol(symbolIn) { - return _$gl3d_markers_515[symbolIn]; + return _$gl3d_markers_576[symbolIn]; } function formatParam(paramIn, len, calculate, dflt, extraFn) { var paramOut = null; - if(_$lib_539.isArrayOrTypedArray(paramIn)) { + if(_$lib_601.isArrayOrTypedArray(paramIn)) { paramOut = []; for(var i = 0; i < len; i++) { @@ -139062,7 +140276,7 @@ function formatParam(paramIn, len, calculate, dflt, extraFn) { } } - else paramOut = calculate(paramIn, _$lib_539.identity); + else paramOut = calculate(paramIn, _$lib_601.identity); return paramOut; } @@ -139112,26 +140326,26 @@ function convertPlotlyOptions(scene, data) { }; if('line' in data) { - params.lineColor = _$formatColor_535(line, 1, len); + params.lineColor = _$formatColor_597(line, 1, len); params.lineWidth = line.width; params.lineDashes = line.dash; } if('marker' in data) { - var sizeFn = _$makeBubbleSizeFn_879(data); + var sizeFn = _$makeBubbleSizeFn_944(data); - params.scatterColor = _$formatColor_535(marker, 1, len); + params.scatterColor = _$formatColor_597(marker, 1, len); params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn); params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, '●'); params.scatterLineWidth = marker.line.width; // arrayOk === false - params.scatterLineColor = _$formatColor_535(marker.line, 1, len); + params.scatterLineColor = _$formatColor_597(marker.line, 1, len); params.scatterAngle = 0; } if('textposition' in data) { params.textOffset = calculateTextOffset(data.textposition); // arrayOk === false - params.textColor = _$formatColor_535(data.textfont, 1, len); - params.textSize = formatParam(data.textfont.size, len, _$lib_539.identity, 12); + params.textColor = _$formatColor_597(data.textfont, 1, len); + params.textSize = formatParam(data.textfont.size, len, _$lib_601.identity, 12); params.textFont = data.textfont.family; // arrayOk === false params.textAngle = 0; } @@ -139148,7 +140362,7 @@ function convertPlotlyOptions(scene, data) { } } - params.errorBounds = _$calculateErrors_889(data, scaleFactor); + params.errorBounds = _$calculateErrors_954(data, scaleFactor); var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]); params.errorColor = errorParams.color; @@ -139156,7 +140370,7 @@ function convertPlotlyOptions(scene, data) { params.errorCapSize = errorParams.capSize; params.delaunayAxis = data.surfaceaxis; - params.delaunayColor = _$str2RgbaArray_561(data.surfacecolor); + params.delaunayColor = _$str2RgbaArray_624(data.surfacecolor); return params; } @@ -139175,13 +140389,13 @@ function arrayToColor(color) { return null; } -__proto_890.update = function(data) { +__proto_955.update = function(data) { var gl = this.scene.glplot.gl, lineOptions, scatterOptions, errorOptions, textOptions, - dashPattern = _$gl3d_dashes_514.solid; + dashPattern = _$gl3d_dashes_575.solid; // Save data this.data = data; @@ -139193,8 +140407,8 @@ __proto_890.update = function(data) { this.mode = options.mode; } if('lineDashes' in options) { - if(options.lineDashes in _$gl3d_dashes_514) { - dashPattern = _$gl3d_dashes_514[options.lineDashes]; + if(options.lineDashes in _$gl3d_dashes_575) { + dashPattern = _$gl3d_dashes_575[options.lineDashes]; } } @@ -139218,7 +140432,7 @@ __proto_890.update = function(data) { if(this.mode.indexOf('lines') !== -1) { if(this.linePlot) this.linePlot.update(lineOptions); else { - this.linePlot = _$createLinePlot_164(lineOptions); + this.linePlot = _$createLinePlot_221(lineOptions); this.linePlot._trace = this; this.scene.glplot.add(this.linePlot); } @@ -139250,7 +140464,7 @@ __proto_890.update = function(data) { if(this.mode.indexOf('markers') !== -1) { if(this.scatterPlot) this.scatterPlot.update(scatterOptions); else { - this.scatterPlot = _$createPointCloud_202(scatterOptions); + this.scatterPlot = _$createPointCloud_259(scatterOptions); this.scatterPlot._trace = this; this.scatterPlot.highlightScale = 1; this.scene.glplot.add(this.scatterPlot); @@ -139281,7 +140495,7 @@ __proto_890.update = function(data) { if(this.mode.indexOf('text') !== -1) { if(this.textMarkers) this.textMarkers.update(textOptions); else { - this.textMarkers = _$createPointCloud_202(textOptions); + this.textMarkers = _$createPointCloud_259(textOptions); this.textMarkers._trace = this; this.textMarkers.highlightScale = 1; this.scene.glplot.add(this.textMarkers); @@ -139310,7 +140524,7 @@ __proto_890.update = function(data) { this.errorBars = null; } } else if(options.errorBounds) { - this.errorBars = _$createErrorBars_156(errorOptions); + this.errorBars = _$createErrorBars_213(errorOptions); this.errorBars._trace = this; this.scene.glplot.add(this.errorBars); } @@ -139327,7 +140541,7 @@ __proto_890.update = function(data) { this.delaunayMesh.update(delaunayOptions); } else { delaunayOptions.gl = gl; - this.delaunayMesh = _$createSimplicialMesh_187(delaunayOptions); + this.delaunayMesh = _$createSimplicialMesh_244(delaunayOptions); this.delaunayMesh._trace = this; this.scene.glplot.add(this.delaunayMesh); } @@ -139338,7 +140552,7 @@ __proto_890.update = function(data) { } }; -__proto_890.dispose = function() { +__proto_955.dispose = function() { if(this.linePlot) { this.scene.glplot.remove(this.linePlot); this.linePlot.dispose(); @@ -139367,7 +140581,7 @@ function createLineWithMarkers(scene, data) { return plot; } -var _$createLineWithMarkers_890 = createLineWithMarkers; +var _$createLineWithMarkers_955 = createLineWithMarkers; /** * Copyright 2012-2018, Plotly, Inc. @@ -139380,23 +140594,23 @@ var _$createLineWithMarkers_890 = createLineWithMarkers; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; -/* removed: var _$attributes_887 = require('./attributes'); */; +/* removed: var _$attributes_952 = require('./attributes'); */; -var _$supplyDefaults_891 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_956 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_887, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_952, attr, dflt); } - var len = __handleXYZDefaults_891(traceIn, traceOut, coerce, layout); + var len = __handleXYZDefaults_956(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -139406,17 +140620,17 @@ var _$supplyDefaults_891 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_884.hasLines(traceOut)) { + if(_$subtypes_949.hasLines(traceOut)) { coerce('connectgaps'); - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce, {noSelect: true}); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce, {noSelect: true}); } var lineColor = (traceOut.line || {}).color, @@ -139432,19 +140646,19 @@ var _$supplyDefaults_891 = function supplyDefaults(traceIn, traceOut, defaultCol } } - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'z'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y', inherit: 'z'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'z'}); }; -function __handleXYZDefaults_891(traceIn, traceOut, coerce, layout) { +function __handleXYZDefaults_956(traceIn, traceOut, coerce, layout) { var len = 0, x = coerce('x'), y = coerce('y'), z = coerce('z'); - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); if(x && y && z) { @@ -139468,16 +140682,16 @@ function __handleXYZDefaults_891(traceIn, traceOut, coerce, layout) { var Scatter3D = {}; -Scatter3D.plot = _$createLineWithMarkers_890; -Scatter3D.attributes = _$attributes_887; -Scatter3D.markerSymbols = _$gl3d_markers_515; -Scatter3D.supplyDefaults = _$supplyDefaults_891; -Scatter3D.colorbar = _$colorbar_866; -Scatter3D.calc = _$calc_888; +Scatter3D.plot = _$createLineWithMarkers_955; +Scatter3D.attributes = _$attributes_952; +Scatter3D.markerSymbols = _$gl3d_markers_576; +Scatter3D.supplyDefaults = _$supplyDefaults_956; +Scatter3D.colorbar = _$colorbar_931; +Scatter3D.calc = _$calc_953; Scatter3D.moduleType = 'trace'; Scatter3D.name = 'scatter3d'; -Scatter3D.basePlotModule = _$gl3d_627; +Scatter3D.basePlotModule = _$gl3d_689; Scatter3D.categories = ['gl3d', 'symbols', 'markerColorscale', 'showLegend']; Scatter3D.meta = { hrName: 'scatter_3d', @@ -139491,7 +140705,7 @@ Scatter3D.meta = { ].join(' ') }; -var _$Scatter3D_892 = Scatter3D; +var _$Scatter3D_957 = Scatter3D; /** * Copyright 2012-2018, Plotly, Inc. @@ -139503,7 +140717,7 @@ var _$Scatter3D_892 = Scatter3D; 'use strict'; -var _$scatter3d_27 = _$Scatter3D_892; +var _$scatter3d_27 = _$Scatter3D_957; /** * Copyright 2012-2018, Plotly, Inc. @@ -139515,18 +140729,18 @@ var _$scatter3d_27 = _$Scatter3D_892; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_893 = _$extend_528.extendFlat; +var __extendFlat_958 = _$extend_590.extendFlat; -var __scatterMarkerAttrs_893 = _$attributes_862.marker, - __scatterLineAttrs_893 = _$attributes_862.line, - __scatterMarkerLineAttrs_893 = __scatterMarkerAttrs_893.line; +var __scatterMarkerAttrs_958 = _$attributes_927.marker, + __scatterLineAttrs_958 = _$attributes_927.line, + __scatterMarkerLineAttrs_958 = __scatterMarkerAttrs_958.line; -var _$attributes_893 = { +var _$attributes_958 = { carpet: { valType: 'string', role: 'info', @@ -139559,8 +140773,8 @@ var _$attributes_893 = { '`ternary.sum`.' ].join(' ') }, - mode: __extendFlat_893({}, _$attributes_862.mode, {dflt: 'markers'}), - text: __extendFlat_893({}, _$attributes_862.text, { + mode: __extendFlat_958({}, _$attributes_927.mode, {dflt: 'markers'}), + text: __extendFlat_958({}, _$attributes_927.text, { description: [ 'Sets text elements associated with each (a,b,c) point.', 'If a single string, the same string appears over', @@ -139570,16 +140784,16 @@ var _$attributes_893 = { ].join(' ') }), line: { - color: __scatterLineAttrs_893.color, - width: __scatterLineAttrs_893.width, - dash: __scatterLineAttrs_893.dash, - shape: __extendFlat_893({}, __scatterLineAttrs_893.shape, + color: __scatterLineAttrs_958.color, + width: __scatterLineAttrs_958.width, + dash: __scatterLineAttrs_958.dash, + shape: __extendFlat_958({}, __scatterLineAttrs_958.shape, {values: ['linear', 'spline']}), - smoothing: __scatterLineAttrs_893.smoothing, + smoothing: __scatterLineAttrs_958.smoothing, editType: 'calc' }, - connectgaps: _$attributes_862.connectgaps, - fill: __extendFlat_893({}, _$attributes_862.fill, { + connectgaps: _$attributes_927.connectgaps, + fill: __extendFlat_958({}, _$attributes_927.fill, { values: ['none', 'toself', 'tonext'], description: [ 'Sets the area to fill with a solid color.', @@ -139593,38 +140807,38 @@ var _$attributes_893 = { 'used if one trace does not enclose the other.' ].join(' ') }), - fillcolor: _$attributes_862.fillcolor, - marker: __extendFlat_893({ - symbol: __scatterMarkerAttrs_893.symbol, - opacity: __scatterMarkerAttrs_893.opacity, - maxdisplayed: __scatterMarkerAttrs_893.maxdisplayed, - size: __scatterMarkerAttrs_893.size, - sizeref: __scatterMarkerAttrs_893.sizeref, - sizemin: __scatterMarkerAttrs_893.sizemin, - sizemode: __scatterMarkerAttrs_893.sizemode, - line: __extendFlat_893({ - width: __scatterMarkerLineAttrs_893.width, + fillcolor: _$attributes_927.fillcolor, + marker: __extendFlat_958({ + symbol: __scatterMarkerAttrs_958.symbol, + opacity: __scatterMarkerAttrs_958.opacity, + maxdisplayed: __scatterMarkerAttrs_958.maxdisplayed, + size: __scatterMarkerAttrs_958.size, + sizeref: __scatterMarkerAttrs_958.sizeref, + sizemin: __scatterMarkerAttrs_958.sizemin, + sizemode: __scatterMarkerAttrs_958.sizemode, + line: __extendFlat_958({ + width: __scatterMarkerLineAttrs_958.width, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker'.line) + _$makeColorScaleAttributes_481('marker'.line) ), - gradient: __scatterMarkerAttrs_893.gradient, + gradient: __scatterMarkerAttrs_958.gradient, editType: 'calc' - }, _$makeColorScaleAttributes_419('marker'), { - showscale: __scatterMarkerAttrs_893.showscale, - colorbar: _$attributes_412 + }, _$makeColorScaleAttributes_481('marker'), { + showscale: __scatterMarkerAttrs_958.showscale, + colorbar: _$attributes_474 }), - textfont: _$attributes_862.textfont, - textposition: _$attributes_862.textposition, + textfont: _$attributes_927.textfont, + textposition: _$attributes_927.textposition, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected, + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected, - hoverinfo: __extendFlat_893({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_958({}, _$attributes_644.hoverinfo, { flags: ['a', 'b', 'text', 'name'] }), - hoveron: _$attributes_862.hoveron, + hoveron: _$attributes_927.hoveron, }; /** @@ -139638,16 +140852,16 @@ var _$attributes_893 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_894 = _$calc_863.calcMarkerSize; -/* removed: var _$lookup_carpetid_726 = require('../carpet/lookup_carpetid'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_959 = _$calc_928.calcMarkerSize; +/* removed: var _$lookup_carpetid_789 = require('../carpet/lookup_carpetid'); */; -var _$calc_894 = function calc(gd, trace) { - var carpet = trace.carpetTrace = _$lookup_carpetid_726(gd, trace); +var _$calc_959 = function calc(gd, trace) { + var carpet = trace._carpetTrace = _$lookup_carpetid_789(gd, trace); if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return; var i; @@ -139664,7 +140878,7 @@ var _$calc_894 = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { a = trace.a[i]; b = trace.b[i]; - if(_$fastIsnumeric_139(a) && _$fastIsnumeric_139(b)) { + if(_$fastIsnumeric_196(a) && _$fastIsnumeric_196(b)) { var xy = carpet.ab2xy(+a, +b, true); var visible = carpet.isVisible(+a, +b); if(!visible) needsCull = true; @@ -139678,10 +140892,10 @@ var _$calc_894 = function calc(gd, trace) { cd[0].carpet = carpet; cd[0].trace = trace; - __calcMarkerSize_894(trace, serieslen); - _$calcMarkerColorscale_867(trace); - _$arraysToCalcdata_861(cd, trace); - _$calcSelection_864(cd, trace); + __calcMarkerSize_959(trace, serieslen); + _$calcMarkerColorscale_932(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcSelection_929(cd, trace); return cd; }; @@ -139697,21 +140911,21 @@ var _$calc_894 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$constants_868 = require('../scatter/constants'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$constants_933 = require('../scatter/constants'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_893 = require('./attributes'); */; +/* removed: var _$attributes_958 = require('./attributes'); */; -var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_960 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_893, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_958, attr, dflt); } coerce('carpet'); @@ -139737,34 +140951,34 @@ var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); - var defaultMode = len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'; + var defaultMode = len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'; coerce('mode', defaultMode); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -139772,7 +140986,7 @@ var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -139785,7 +140999,7 @@ var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_896 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_961 = function eventData(out, pt, trace, cd, pointNumber) { var cdi = cd[pointNumber]; out.a = cdi.a; @@ -139805,10 +141019,10 @@ var _$eventData_896 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_873 = require('../scatter/hover'); */; +/* removed: var _$hoverPoints_938 = require('../scatter/hover'); */; -var _$hoverPoints_897 = function hoverPoints(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_873(pointData, xval, yval, hovermode); +var _$hoverPoints_962 = function hoverPoints(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_938(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -139890,23 +141104,23 @@ var _$hoverPoints_897 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -/* removed: var _$plot_881 = require('../scatter/plot'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$plot_946 = require('../scatter/plot'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -var _$plot_899 = function plot(gd, plotinfoproxy, data) { +var _$plot_964 = function plot(gd, plotinfoproxy, data) { var i, trace, node; var carpet = data[0][0].carpet; // mimic cartesian plotinfo var plotinfo = { - xaxis: _$axes_584.getFromId(gd, carpet.xaxis || 'x'), - yaxis: _$axes_584.getFromId(gd, carpet.yaxis || 'y'), + xaxis: _$axes_647.getFromId(gd, carpet.xaxis || 'x'), + yaxis: _$axes_647.getFromId(gd, carpet.yaxis || 'y'), plot: plotinfoproxy.plot }; - _$plot_881(gd, plotinfo, data); + _$plot_946(gd, plotinfo, data); for(i = 0; i < data.length; i++) { trace = data[i][0].trace; @@ -139919,7 +141133,7 @@ var _$plot_899 = function plot(gd, plotinfoproxy, data) { // separately to all scattercarpet traces, but that would require // lots of reorganization of scatter traces that is otherwise not // necessary. That makes this a potential optimization. - _$drawing_436.setClipUrl(node, carpet._clipPathId); + _$drawing_498.setClipUrl(node, carpet._clipPathId); } }; @@ -139935,20 +141149,20 @@ var _$plot_899 = function plot(gd, plotinfoproxy, data) { var ScatterCarpet = {}; -ScatterCarpet.attributes = _$attributes_893; -ScatterCarpet.supplyDefaults = _$supplyDefaults_895; -ScatterCarpet.colorbar = _$colorbar_866; -ScatterCarpet.calc = _$calc_894; -ScatterCarpet.plot = _$plot_899; -ScatterCarpet.style = _$style_883.style; -ScatterCarpet.hoverPoints = _$hoverPoints_897; -ScatterCarpet.selectPoints = _$selectPoints_882; -ScatterCarpet.eventData = _$eventData_896; +ScatterCarpet.attributes = _$attributes_958; +ScatterCarpet.supplyDefaults = _$supplyDefaults_960; +ScatterCarpet.colorbar = _$colorbar_931; +ScatterCarpet.calc = _$calc_959; +ScatterCarpet.plot = _$plot_964; +ScatterCarpet.style = _$style_948.style; +ScatterCarpet.hoverPoints = _$hoverPoints_962; +ScatterCarpet.selectPoints = _$selectPoints_947; +ScatterCarpet.eventData = _$eventData_961; ScatterCarpet.moduleType = 'trace'; ScatterCarpet.name = 'scattercarpet'; -ScatterCarpet.basePlotModule = _$cartesian_595; -ScatterCarpet.categories = ['carpet', 'symbols', 'markerColorscale', 'showLegend', 'carpetDependent']; +ScatterCarpet.basePlotModule = _$cartesian_658; +ScatterCarpet.categories = ['svg', 'carpet', 'symbols', 'markerColorscale', 'showLegend', 'carpetDependent', 'draggedPts']; ScatterCarpet.meta = { hrName: 'scatter_carpet', description: [ @@ -139957,7 +141171,7 @@ ScatterCarpet.meta = { ].join(' ') }; -var _$ScatterCarpet_898 = ScatterCarpet; +var _$ScatterCarpet_963 = ScatterCarpet; /** * Copyright 2012-2018, Plotly, Inc. @@ -139969,7 +141183,7 @@ var _$ScatterCarpet_898 = ScatterCarpet; 'use strict'; -var _$scattercarpet_28 = _$ScatterCarpet_898; +var _$scattercarpet_28 = _$ScatterCarpet_963; /** * Copyright 2012-2018, Plotly, Inc. @@ -139982,16 +141196,16 @@ var _$scattercarpet_28 = _$ScatterCarpet_898; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __BADNUM_901 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __BADNUM_966 = _$numerical_578.BADNUM; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; -var ____901 = _$lib_539._; +var ____966 = _$lib_601._; -var _$calc_901 = function calc(gd, trace) { +var _$calc_966 = function calc(gd, trace) { var hasLocationData = Array.isArray(trace.locations); var len = hasLocationData ? trace.locations.length : trace._length; var calcTrace = new Array(len); @@ -140006,20 +141220,20 @@ var _$calc_901 = function calc(gd, trace) { var lon = trace.lon[i]; var lat = trace.lat[i]; - if(_$fastIsnumeric_139(lon) && _$fastIsnumeric_139(lat)) calcPt.lonlat = [+lon, +lat]; - else calcPt.lonlat = [__BADNUM_901, __BADNUM_901]; + if(_$fastIsnumeric_196(lon) && _$fastIsnumeric_196(lat)) calcPt.lonlat = [+lon, +lat]; + else calcPt.lonlat = [__BADNUM_966, __BADNUM_966]; } } - _$arraysToCalcdata_861(calcTrace, trace); - _$calcMarkerColorscale_867(trace); - _$calcSelection_864(calcTrace, trace); + _$arraysToCalcdata_926(calcTrace, trace); + _$calcMarkerColorscale_932(trace); + _$calcSelection_929(calcTrace, trace); if(len) { calcTrace[0].t = { labels: { - lat: ____901(gd, 'lat:') + ' ', - lon: ____901(gd, 'lon:') + ' ' + lat: ____966(gd, 'lat:') + ' ', + lon: ____966(gd, 'lon:') + ' ' } }; } @@ -140038,20 +141252,20 @@ var _$calc_901 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_900 = require('./attributes'); */; +/* removed: var _$attributes_965 = require('./attributes'); */; -var _$supplyDefaults_902 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_967 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_900, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_965, attr, dflt); } var len = handleLonLatLocDefaults(traceIn, traceOut, coerce); @@ -140064,22 +141278,22 @@ var _$supplyDefaults_902 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); } }; @@ -140115,7 +141329,7 @@ function handleLonLatLocDefaults(traceIn, traceOut, coerce) { 'use strict'; -var _$eventData_903 = function eventData(out, pt) { +var _$eventData_968 = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; out.location = pt.loc ? pt.loc : null; @@ -140134,15 +141348,15 @@ var _$eventData_903 = function eventData(out, pt) { 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __BADNUM_904 = _$numerical_517.BADNUM; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __BADNUM_969 = _$numerical_578.BADNUM; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; -/* removed: var _$attributes_900 = require('./attributes'); */; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; +/* removed: var _$attributes_965 = require('./attributes'); */; -var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_969 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -140155,7 +141369,7 @@ var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { function distFn(d) { var lonlat = d.lonlat; - if(lonlat[0] === __BADNUM_904) return Infinity; + if(lonlat[0] === __BADNUM_969) return Infinity; if(isLonLatOverEdges(lonlat)) return Infinity; var pt = project(lonlat); @@ -140170,7 +141384,7 @@ var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad); } - _$fx_453.getClosest(cd, distFn, pointData); + _$fx_515.getClosest(cd, distFn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index === false) return; @@ -140189,7 +141403,7 @@ var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { pointData.lon = lonlat[0]; pointData.lat = lonlat[1]; - pointData.color = _$getTraceColor_872(trace, di); + pointData.color = _$getTraceColor_937(trace, di); pointData.extraText = getExtraText(trace, di, geo.mockAxis, cd[0].t.labels); return [pointData]; @@ -140199,7 +141413,7 @@ function getExtraText(trace, pt, axis, labels) { var hoverinfo = pt.hi || trace.hoverinfo; var parts = hoverinfo === 'all' ? - _$attributes_900.hoverinfo.flags : + _$attributes_965.hoverinfo.flags : hoverinfo.split('+'); var hasLocation = parts.indexOf('location') !== -1 && Array.isArray(trace.locations); @@ -140209,7 +141423,7 @@ function getExtraText(trace, pt, axis, labels) { var text = []; function format(val) { - return _$axes_584.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0'; + return _$axes_647.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0'; } if(hasLocation) { @@ -140223,13 +141437,13 @@ function getExtraText(trace, pt, axis, labels) { } if(hasText) { - _$fillHoverText_870(pt, trace, text); + _$fillHoverText_935(pt, trace, text); } return text.join('
'); } -var _$geojson_utils_532 = {}; +var _$geojson_utils_594 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -140241,7 +141455,7 @@ var _$geojson_utils_532 = {}; 'use strict'; -var __BADNUM_532 = _$numerical_517.BADNUM; +var __BADNUM_594 = _$numerical_578.BADNUM; /** * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays @@ -140254,7 +141468,7 @@ var __BADNUM_532 = _$numerical_517.BADNUM; * return line coords array (or array of arrays) * */ -_$geojson_utils_532.calcTraceToLineCoords = function(calcTrace) { +_$geojson_utils_594.calcTraceToLineCoords = function(calcTrace) { var trace = calcTrace[0].trace; var connectgaps = trace.connectgaps; @@ -140265,7 +141479,7 @@ _$geojson_utils_532.calcTraceToLineCoords = function(calcTrace) { var calcPt = calcTrace[i]; var lonlat = calcPt.lonlat; - if(lonlat[0] !== __BADNUM_532) { + if(lonlat[0] !== __BADNUM_594) { lineString.push(lonlat); } else if(!connectgaps && lineString.length > 0) { coords.push(lineString); @@ -140290,7 +141504,7 @@ _$geojson_utils_532.calcTraceToLineCoords = function(calcTrace) { * GeoJSON object * */ -_$geojson_utils_532.makeLine = function(coords) { +_$geojson_utils_594.makeLine = function(coords) { if(coords.length === 1) { return { type: 'LineString', @@ -140312,7 +141526,7 @@ _$geojson_utils_532.makeLine = function(coords) { * @return {object} out * GeoJSON object */ -_$geojson_utils_532.makePolygon = function(coords) { +_$geojson_utils_594.makePolygon = function(coords) { if(coords.length === 1) { return { type: 'Polygon', @@ -140339,7 +141553,7 @@ _$geojson_utils_532.makePolygon = function(coords) { * Blank GeoJSON object * */ -_$geojson_utils_532.makeBlank = function() { +_$geojson_utils_594.makeBlank = function() { return { type: 'Point', coordinates: [] @@ -140356,37 +141570,37 @@ _$geojson_utils_532.makeBlank = function() { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -var __stylePoints_908 = _$style_883.stylePoints; +var __stylePoints_973 = _$style_948.stylePoints; -var _$style_908 = function style(gd, calcTrace) { - if(calcTrace) __styleTrace_908(gd, calcTrace); +var _$style_973 = function style(gd, calcTrace) { + if(calcTrace) __styleTrace_973(gd, calcTrace); }; -function __styleTrace_908(gd, calcTrace) { +function __styleTrace_973(gd, calcTrace) { var trace = calcTrace[0].trace; var s = calcTrace[0].node3; s.style('opacity', calcTrace[0].trace.opacity); - __stylePoints_908(s, trace, gd); + __stylePoints_973(s, trace, gd); // this part is incompatible with Drawing.lineGroupStyle s.selectAll('path.js-line') .style('fill', 'none') .each(function(d) { - var path = _$d3_127.select(this); + var path = _$d3_130.select(this); var trace = d.trace; var line = trace.line || {}; - path.call(_$color_411.stroke, line.color) - .call(_$drawing_436.dashLine, line.dash || '', line.width || 0); + path.call(_$color_473.stroke, line.color) + .call(_$drawing_498.dashLine, line.dash || '', line.width || 0); if(trace.fill !== 'none') { - path.call(_$color_411.fill, trace.fillcolor); + path.call(_$color_473.fill, trace.fillcolor); } }); } @@ -140402,26 +141616,26 @@ function __styleTrace_908(gd, calcTrace) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_906 = _$numerical_517.BADNUM; -var __getTopojsonFeatures_906 = _$topojson_utils_565.getTopojsonFeatures; -var __locationToFeature_906 = _$geo_location_utils_531.locationToFeature; -/* removed: var _$geojson_utils_532 = require('../../lib/geojson_utils'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$style_908 = require('./style'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_971 = _$numerical_578.BADNUM; +var __getTopojsonFeatures_971 = _$topojson_utils_628.getTopojsonFeatures; +var __locationToFeature_971 = _$geo_location_utils_593.locationToFeature; +/* removed: var _$geojson_utils_594 = require('../../lib/geojson_utils'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$style_973 = require('./style'); */; -var _$plot_906 = function plot(gd, geo, calcData) { +var _$plot_971 = function plot(gd, geo, calcData) { for(var i = 0; i < calcData.length; i++) { - __calcGeoJSON_906(calcData[i], geo.topojson); + __calcGeoJSON_971(calcData[i], geo.topojson); } function keyFunc(d) { return d[0].trace.uid; } function removeBADNUM(d, node) { - if(d.lonlat[0] === __BADNUM_906) { - _$d3_127.select(node).remove(); + if(d.lonlat[0] === __BADNUM_971) { + _$d3_130.select(node).remove(); } } @@ -140438,15 +141652,15 @@ var _$plot_906 = function plot(gd, geo, calcData) { gTraces.selectAll('*').remove(); gTraces.each(function(calcTrace) { - var s = calcTrace[0].node3 = _$d3_127.select(this); + var s = calcTrace[0].node3 = _$d3_130.select(this); var trace = calcTrace[0].trace; - if(_$subtypes_884.hasLines(trace) || trace.fill !== 'none') { - var lineCoords = _$geojson_utils_532.calcTraceToLineCoords(calcTrace); + if(_$subtypes_949.hasLines(trace) || trace.fill !== 'none') { + var lineCoords = _$geojson_utils_594.calcTraceToLineCoords(calcTrace); var lineData = (trace.fill !== 'none') ? - _$geojson_utils_532.makePolygon(lineCoords) : - _$geojson_utils_532.makeLine(lineCoords); + _$geojson_utils_594.makePolygon(lineCoords) : + _$geojson_utils_594.makeLine(lineCoords); s.selectAll('path.js-line') .data([{geojson: lineData, trace: trace}]) @@ -140455,40 +141669,40 @@ var _$plot_906 = function plot(gd, geo, calcData) { .style('stroke-miterlimit', 2); } - if(_$subtypes_884.hasMarkers(trace)) { + if(_$subtypes_949.hasMarkers(trace)) { s.selectAll('path.point') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .classed('point', true) .each(function(calcPt) { removeBADNUM(calcPt, this); }); } - if(_$subtypes_884.hasText(trace)) { + if(_$subtypes_949.hasText(trace)) { s.selectAll('g') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('g') .append('text') .each(function(calcPt) { removeBADNUM(calcPt, this); }); } // call style here within topojson request callback - _$style_908(gd, calcTrace); + _$style_973(gd, calcTrace); }); }; -function __calcGeoJSON_906(calcTrace, topojson) { +function __calcGeoJSON_971(calcTrace, topojson) { var trace = calcTrace[0].trace; if(!Array.isArray(trace.locations)) return; - var features = __getTopojsonFeatures_906(trace, topojson); + var features = __getTopojsonFeatures_971(trace, topojson); var locationmode = trace.locationmode; for(var i = 0; i < calcTrace.length; i++) { var calcPt = calcTrace[i]; - var feature = __locationToFeature_906(locationmode, calcPt.loc, features); + var feature = __locationToFeature_971(locationmode, calcPt.loc, features); - calcPt.lonlat = feature ? feature.properties.ct : [__BADNUM_906, __BADNUM_906]; + calcPt.lonlat = feature ? feature.properties.ct : [__BADNUM_971, __BADNUM_971]; } } @@ -140502,9 +141716,9 @@ function __calcGeoJSON_906(calcTrace, topojson) { 'use strict'; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; -var _$selectPoints_907 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_972 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -140513,7 +141727,7 @@ var _$selectPoints_907 = function selectPoints(searchInfo, polygon) { var di, lonlat, x, y, i; - var hasOnlyLines = (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)); + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { @@ -140556,19 +141770,19 @@ var _$selectPoints_907 = function selectPoints(searchInfo, polygon) { var ScatterGeo = {}; -ScatterGeo.attributes = _$attributes_900; -ScatterGeo.supplyDefaults = _$supplyDefaults_902; -ScatterGeo.colorbar = _$colorbar_866; -ScatterGeo.calc = _$calc_901; -ScatterGeo.plot = _$plot_906; -ScatterGeo.style = _$style_908; -ScatterGeo.hoverPoints = _$hoverPoints_904; -ScatterGeo.eventData = _$eventData_903; -ScatterGeo.selectPoints = _$selectPoints_907; +ScatterGeo.attributes = _$attributes_965; +ScatterGeo.supplyDefaults = _$supplyDefaults_967; +ScatterGeo.colorbar = _$colorbar_931; +ScatterGeo.calc = _$calc_966; +ScatterGeo.plot = _$plot_971; +ScatterGeo.style = _$style_973; +ScatterGeo.hoverPoints = _$hoverPoints_969; +ScatterGeo.eventData = _$eventData_968; +ScatterGeo.selectPoints = _$selectPoints_972; ScatterGeo.moduleType = 'trace'; ScatterGeo.name = 'scattergeo'; -ScatterGeo.basePlotModule = _$geo_615; +ScatterGeo.basePlotModule = _$geo_677; ScatterGeo.categories = ['geo', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like']; ScatterGeo.meta = { hrName: 'scatter_geo', @@ -140579,7 +141793,7 @@ ScatterGeo.meta = { ].join(' ') }; -var _$ScatterGeo_905 = ScatterGeo; +var _$ScatterGeo_970 = ScatterGeo; /** * Copyright 2012-2018, Plotly, Inc. @@ -140591,10 +141805,10 @@ var _$ScatterGeo_905 = ScatterGeo; 'use strict'; -var _$scattergeo_29 = _$ScatterGeo_905; +var _$scattergeo_29 = _$ScatterGeo_970; -var _$newArray_50 = function newArray(start, end) { +var _$newArray_51 = function newArray(start, end) { var n0 = typeof start === 'number', n1 = typeof end === 'number' @@ -140617,199 +141831,11 @@ var _$newArray_50 = function newArray(start, end) { a[i] = c return a } -/** - * @module kdgrass - * - * Static kdbush - */ - 'use strict' -var _$KDTree_252 = KDTree - -//optimized kdbush -function KDTree(points, nodeSize) { - if (!(this instanceof KDTree)) return new KDTree(points, nodeSize) - - this.nodeSize = nodeSize || 64; - - this.coords = points.slice(); - - var l = Math.floor(points.length / 2) - this.ids = Array(l); - - for (var i = 0; i < l; i++) { - this.ids[i] = i; - } - - sortKD(this.ids, this.coords, this.nodeSize, 0, this.ids.length - 1, 0); -} - - -KDTree.prototype.range = function range(minX, minY, maxX, maxY) { - var ids = this.ids, coords = this.coords, nodeSize = this.nodeSize - var stack = [0, ids.length - 1, 0]; - var result = []; - var x, y; - - while (stack.length) { - var axis = stack.pop(); - var right = stack.pop(); - var left = stack.pop(); - - if (right - left <= nodeSize) { - for (var i = left; i <= right; i++) { - x = coords[2 * i]; - y = coords[2 * i + 1]; - if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); - } - continue; - } - - var m = Math.floor((left + right) / 2); - - x = coords[2 * m]; - y = coords[2 * m + 1]; - - if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); - - var nextAxis = (axis + 1) % 2; - - if (axis === 0 ? minX <= x : minY <= y) { - stack.push(left); - stack.push(m - 1); - stack.push(nextAxis); - } - if (axis === 0 ? maxX >= x : maxY >= y) { - stack.push(m + 1); - stack.push(right); - stack.push(nextAxis); - } - } - - return result; -} - - -KDTree.prototype.within = function within(qx, qy, r) { - var ids = this.ids, coords = this.coords, nodeSize = this.nodeSize - var stack = [0, ids.length - 1, 0]; - var result = []; - var r2 = r * r; - - while (stack.length) { - var axis = stack.pop(); - var right = stack.pop(); - var left = stack.pop(); - - if (right - left <= nodeSize) { - for (var i = left; i <= right; i++) { - if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); - } - continue; - } - - var m = Math.floor((left + right) / 2); - - var x = coords[2 * m]; - var y = coords[2 * m + 1]; - - if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); - - var nextAxis = (axis + 1) % 2; - - if (axis === 0 ? qx - r <= x : qy - r <= y) { - stack.push(left); - stack.push(m - 1); - stack.push(nextAxis); - } - if (axis === 0 ? qx + r >= x : qy + r >= y) { - stack.push(m + 1); - stack.push(right); - stack.push(nextAxis); - } - } - - return result; -} - -function sqDist(ax, ay, bx, by) { - var dx = ax - bx; - var dy = ay - by; - return dx * dx + dy * dy; -} - - -function sortKD(ids, coords, nodeSize, left, right, depth) { - if (right - left <= nodeSize) return; - - var m = Math.floor((left + right) / 2); - - __select_252(ids, coords, m, left, right, depth % 2); - - sortKD(ids, coords, nodeSize, left, m - 1, depth + 1); - sortKD(ids, coords, nodeSize, m + 1, right, depth + 1); -} - -function __select_252(ids, coords, k, left, right, inc) { - - while (right > left) { - if (right - left > 600) { - var n = right - left + 1; - var m = k - left + 1; - var z = Math.log(n); - var s = 0.5 * Math.exp(2 * z / 3); - var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); - var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); - var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); - __select_252(ids, coords, k, newLeft, newRight, inc); - } - - var t = coords[2 * k + inc]; - var i = left; - var j = right; - - swapItem(ids, coords, left, k); - if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right); - - while (i < j) { - swapItem(ids, coords, i, j); - i++; - j--; - while (coords[2 * i + inc] < t) i++; - while (coords[2 * j + inc] > t) j--; - } - - if (coords[2 * left + inc] === t) swapItem(ids, coords, left, j); - else { - j++; - swapItem(ids, coords, j, right); - } - - if (j <= k) left = j + 1; - if (k <= j) right = j - 1; - } -} - -function swapItem(ids, coords, i, j) { - __swap_252(ids, i, j); - __swap_252(coords, 2 * i, 2 * j); - __swap_252(coords, 2 * i + 1, 2 * j + 1); -} - -function __swap_252(arr, i, j) { - var tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; -} - - - -'use strict' - -var _$normalize_48 = __normalize_48; +var _$normalize_49 = __normalize_49; -function __normalize_48 (arr, dim) { +function __normalize_49 (arr, dim) { if (!arr || arr.length == null) throw Error('Argument should be an array') if (dim == null) dim = 1 @@ -140833,8 +141859,8 @@ function __normalize_48 (arr, dim) { } /*eslint new-cap:0*/ -/* removed: var _$dtype_132 = require('dtype') */; -var _$flattenVertexData_141 = flattenVertexData +/* removed: var _$dtype_135 = require('dtype') */; +var _$flattenVertexData_198 = flattenVertexData function flattenVertexData (data, output, offset) { if (!data) throw new TypeError('must specify data as first parameter') offset = +(offset || 0) | 0 @@ -140845,7 +141871,7 @@ function flattenVertexData (data, output, offset) { // no output specified, create a new typed array if (!output || typeof output === 'string') { - output = new (_$dtype_132(output || 'float32'))(length + offset) + output = new (_$dtype_135(output || 'float32'))(length + offset) } var dstLength = output.length - offset @@ -140862,7 +141888,7 @@ function flattenVertexData (data, output, offset) { } else { if (!output || typeof output === 'string') { // no output, create a new one - var Ctor = _$dtype_132(output || 'float32') + var Ctor = _$dtype_135(output || 'float32') if (offset === 0) { output = new Ctor(data) } else { @@ -140878,10 +141904,21 @@ function flattenVertexData (data, output, offset) { return output } +'use strict'; +var _$isObj_307 = function (x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); +}; + +'use strict'; +var _$mathLog2_317 = Math.log2 || function (x) { + return Math.log(x) * Math.LOG2E; +}; + 'use strict' -var _$pick_290 = function pick (src, props, keepRest) { +var _$pick_349 = function pick (src, props, keepRest) { var result = {}, prop, i if (typeof props === 'string') props = toList(props) @@ -140946,26 +141983,512 @@ var _$pick_290 = function pick (src, props, keepRest) { return result } -var __CACHE_290 = {} +var __CACHE_349 = {} function toList(arg) { - if (__CACHE_290[arg]) return __CACHE_290[arg] + if (__CACHE_349[arg]) return __CACHE_349[arg] if (typeof arg === 'string') { - arg = __CACHE_290[arg] = arg.split(/\s*,\s*|\s+/) + arg = __CACHE_349[arg] = arg.split(/\s*,\s*|\s+/) } return arg } -var _$toFloat32_353 = {}; +'use strict' + +/* removed: var _$pick_349 = require('pick-by-alias') */; + +var _$parseRect_343 = 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_349(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 +} + +"use strict" + +function __compileSearch_354(funcName, predicate, reversed, extraArgs, 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[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_354(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_354("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_354("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() +} + +var _$searchBounds_354 = { + ge: __compileBoundsSearch_354(">=", false, "GE"), + gt: __compileBoundsSearch_354(">", false, "GT"), + lt: __compileBoundsSearch_354("<", true, "LT"), + le: __compileBoundsSearch_354("<=", true, "LE"), + eq: __compileBoundsSearch_354("-", true, "EQ", true) +} + +/** + * @module point-cluster/quad + * + * Bucket based quad tree clustering + */ + +'use strict' + +/* removed: var _$searchBounds_354 = require('binary-search-bounds') */; +/* removed: var _$clamp_95 = require('clamp') */; +/* removed: var _$parseRect_343 = require('parse-rect') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$defined_131 = require('defined') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$isObj_307 = require('is-obj') */; +/* removed: var _$dtype_135 = require('dtype') */; +/* removed: var _$mathLog2_317 = require('math-log2') */; + + +var _$cluster_355 = function cluster (srcPoints, options) { + if (!options) { options = {} } + + srcPoints = _$flattenVertexData_198(srcPoints, 'float64') + + options = _$pick_349(options, { + bounds: 'range bounds dataBox databox', + maxDepth: 'depth maxDepth maxdepth level maxLevel maxlevel levels', + dtype: 'type dtype format out dst output destination' + // sort: 'sortBy sortby sort', + // pick: 'pick levelPoint', + // nodeSize: 'node nodeSize minNodeSize minSize size' + }) + + // let nodeSize = defined(options.nodeSize, 1) + var maxDepth = _$defined_131(options.maxDepth, 255) + var bounds = _$defined_131(options.bounds, _$normalize_49(srcPoints, 2)) + if (bounds[0] === bounds[2]) { bounds[2]++ } + if (bounds[1] === bounds[3]) { bounds[3]++ } + + var points = __normalize_355(srcPoints, bounds) + + // init variables + var n = srcPoints.length >>> 1 + var ids + if (!options.dtype) { options.dtype = 'array' } + + if (typeof options.dtype === 'string') { + ids = new (_$dtype_135(options.dtype))(n) + } + else if (options.dtype) { + ids = options.dtype + if (Array.isArray(ids)) { ids.length = n } + } + for (var i = 0; i < n; ++i) { + ids[i] = i + } + + // point indexes for levels [0: [a,b,c,d], 1: [a,b,c,d,e,f,...], ...] + var levels = [] + + // starting indexes of subranges in sub levels, levels.length * 4 + var sublevels = [] + + // unique group ids, sorted in z-curve fashion within levels + var groups = [] + + // level offsets in `ids` + var offsets = [] + + + // sort points + sort(0, 0, 1, ids, 0, 1) + + + // return reordered ids with provided methods + // save level offsets in output buffer + var offset = 0 + for (var level = 0; level < levels.length; level++) { + var levelItems = levels[level] + if (ids.set) { ids.set(levelItems, offset) } + else { + for (var i$1 = 0, l = levelItems.length; i$1 < l; i$1++) { + ids[i$1 + offset] = levelItems[i$1] + } + } + var nextOffset = offset + levels[level].length + offsets[level] = [offset, nextOffset] + offset = nextOffset + } + + ids.range = range + + return ids + + + + // FIXME: it is possible to create one typed array heap and reuse that to avoid memory blow + function sort (x, y, diam, ids, level, group) { + if (!ids.length) { return null } + + // save first point as level representative + var levelItems = levels[level] || (levels[level] = []) + var levelGroups = groups[level] || (groups[level] = []) + var sublevel = sublevels[level] || (sublevels[level] = []) + var offset = levelItems.length + + level++ + + // max depth reached - put all items into a first group + if (level > maxDepth) { + for (var i = 0; i < ids.length; i++) { + levelItems.push(ids[i]) + levelGroups.push(group) + sublevel.push(null, null, null, null) + } + + return offset + } + + levelItems.push(ids[0]) + levelGroups.push(group) + + if (ids.length <= 1) { + sublevel.push(null, null, null, null) + return offset + } + + + var d2 = diam * .5 + var cx = x + d2, cy = y + d2 + + // distribute points by 4 buckets + var lolo = [], lohi = [], hilo = [], hihi = [] + + for (var i$1 = 1, l = ids.length; i$1 < l; i$1++) { + var idx = ids[i$1], + x$1 = points[idx * 2], + y$1 = points[idx * 2 + 1] + x$1 < cx ? (y$1 < cy ? lolo.push(idx) : lohi.push(idx)) : (y$1 < cy ? hilo.push(idx) : hihi.push(idx)) + } + + group <<= 2 + sublevel.push( + sort(x, y, d2, lolo, level, group), + sort(x, cy, d2, lohi, level, group + 1), + sort(cx, y, d2, hilo, level, group + 2), + sort(cx, cy, d2, hihi, level, group + 3) + ) + + return offset + } + + // get all points within the passed range + function range () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var options + + if (_$isObj_307(args[args.length - 1])) { + var arg = args.pop() + + // detect if that was a rect object + if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) { + args = [arg] + options = {} + } + + options = _$pick_349(arg, { + level: 'level maxLevel', + d: 'd diam diameter r radius px pxSize pixel pixelSize maxD size minSize', + lod: 'lod details ranges offsets' + }) + } + else { + options = {} + } + + if (!args.length) { args = bounds } + + var box = _$parseRect_343.apply( void 0, args ) + + var ref = [ + Math.min(box.x, box.x + box.width), + Math.min(box.y, box.y + box.height), + Math.max(box.x, box.x + box.width), + Math.max(box.y, box.y + box.height) + ]; + var minX = ref[0]; + var minY = ref[1]; + var maxX = ref[2]; + var maxY = ref[3]; + + var ref$1 = __normalize_355([minX, minY, maxX, maxY], bounds ); + var nminX = ref$1[0]; + var nminY = ref$1[1]; + var nmaxX = ref$1[2]; + var nmaxY = ref$1[3]; + + var maxLevel = _$defined_131(options.level, levels.length) + + // limit maxLevel by px size + if (options.d != null) { + var d + if (typeof options.d === 'number') { d = [options.d, options.d] } + else if (options.d.length) { d = options.d } + + maxLevel = Math.min( + Math.ceil(-_$mathLog2_317(Math.abs(d[0]) / (bounds[2] - bounds[0]))), + Math.ceil(-_$mathLog2_317(Math.abs(d[1]) / (bounds[3] - bounds[1]))), + maxLevel + ) + } + + // return levels of details + if (options.lod) { + return lod(nminX, nminY, nmaxX, nmaxY, maxLevel) + } + + + + // do selection ids + var selection = [] + + // FIXME: probably we can do LOD here beforehead + select( 0, 0, 1, 0, 0, 1) + + function select ( lox, loy, d, level, from, to ) { + if (from === null || to === null) { return } + + var hix = lox + d + var hiy = loy + d + + // if box does not intersect level - ignore + if ( nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy ) { return } + if ( level >= maxLevel ) { return } + if ( from === to ) { return } + + // if points fall into box range - take it + var levelItems = levels[level] + + if (to === undefined) { to = levelItems.length } + + for (var i = from; i < to; i++) { + var id = levelItems[i] + + var px = srcPoints[ id * 2 ] + var py = srcPoints[ id * 2 + 1 ] + + if ( px >= minX && px <= maxX && py >= minY && py <= maxY ) {selection.push(id) + } + } + + // for every subsection do select + var offsets = sublevels[ level ] + var off0 = offsets[ from * 4 + 0 ] + var off1 = offsets[ from * 4 + 1 ] + var off2 = offsets[ from * 4 + 2 ] + var off3 = offsets[ from * 4 + 3 ] + var end = nextOffset(offsets, from + 1) + + var d2 = d * .5 + var nextLevel = level + 1 + select( lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end) + select( lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end) + select( lox + d2, loy, d2, nextLevel, off2, off3 || end) + select( lox + d2, loy + d2, d2, nextLevel, off3, end) + } + + function nextOffset(offsets, from) { + var offset = null, i = 0 + while(offset === null) { + offset = offsets[ from * 4 + i ] + i++ + if (i > offsets.length) { return null } + } + return offset + } + + return selection + } + + // get range offsets within levels to render lods appropriate for zoom level + // TODO: it is possible to store minSize of a point to optimize neede level calc + function lod (lox, loy, hix, hiy, maxLevel) { + var ranges = [] + + for (var level = 0; level < maxLevel; level++) { + var levelGroups = groups[level] + var from = offsets[level][0] + + var levelGroupStart = group(lox, loy, level) + var levelGroupEnd = group(hix, hiy, level) + + // FIXME: utilize sublevels to speed up search range here + var startOffset = _$searchBounds_354.ge(levelGroups, levelGroupStart) + var endOffset = _$searchBounds_354.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1) + + ranges[level] = [startOffset + from, endOffset + from] + } + + return ranges + } + + // get group id closest to the x,y coordinate, corresponding to a level + function group (x, y, level) { + var group = 1 + + var cx = .5, cy = .5 + var diam = .5 + + for (var i = 0; i < level; i++) { + group <<= 2 + + group += x < cx ? (y < cy ? 0 : 1) : (y < cy ? 2 : 3) + + diam *= .5 + + cx += x < cx ? -diam : diam + cy += y < cy ? -diam : diam + } + + return group + } +} + + +// normalize points by bounds +function __normalize_355 (pts, bounds) { + var lox = bounds[0]; + var loy = bounds[1]; + var hix = bounds[2]; + var hiy = bounds[3]; + var scaleX = 1.0 / (hix - lox) + var scaleY = 1.0 / (hiy - loy) + var result = new Array(pts.length) + + for (var i = 0, n = pts.length / 2; i < n; i++) { + result[2*i] = _$clamp_95((pts[2*i] - lox) * scaleX, 0, 1) + result[2*i+1] = _$clamp_95((pts[2*i+1] - loy) * scaleY, 0, 1) + } + + return result +} +'use strict' + +var _$pointCluster_353 = _$cluster_355 +var _$toFloat32_415 = {}; /* @module to-float32 */ 'use strict' -_$toFloat32_353 = float32 -_$toFloat32_353.float32 = -_$toFloat32_353.float = float32 -_$toFloat32_353.fract32 = -_$toFloat32_353.fract = fract32 +_$toFloat32_415 = float32 +_$toFloat32_415.float32 = +_$toFloat32_415.float = float32 +_$toFloat32_415.fract32 = +_$toFloat32_415.fract = fract32 // return fractional part of float32 array function fract32 (arr) { @@ -140998,7 +142521,7 @@ function float32 (arr) { 'use strict' -var _$updateDiff_363 = function updateDiff (obj, diff, mappers) { +var _$updateDiff_425 = function updateDiff (obj, diff, mappers) { if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2) for (var i = 0, l = mappers.length; i < l; i++) { @@ -141026,19 +142549,19 @@ var _$updateDiff_363 = function updateDiff (obj, diff, mappers) { 'use strict' -/* removed: var _$normalize_48 = require('array-bounds') */; -/* removed: var _$normalize_99 = require('color-normalize') */; -/* removed: var _$updateDiff_363 = require('update-diff') */; -/* removed: var _$pick_290 = require('pick-by-alias') */; -/* removed: var _$objectAssign_281 = require('object-assign') */; -/* removed: var _$flattenVertexData_141 = require('flatten-vertex-data') */; -/* removed: var _$toFloat32_353 = require('to-float32'); */; -var __float32_311 = _$toFloat32_353.float32; -var __fract32_311 = _$toFloat32_353.fract32; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$normalize_100 = require('color-normalize') */; +/* removed: var _$updateDiff_425 = require('update-diff') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$toFloat32_415 = require('to-float32'); */; +var __float32_374 = _$toFloat32_415.float32; +var __fract32_374 = _$toFloat32_415.fract32; -var _$Error2D_311 = Error2D +var _$Error2D_374 = Error2D -var __WEIGHTS_311 = [ +var __WEIGHTS_374 = [ //direction, lineWidth shift, capSize shift // x-error bar @@ -141156,7 +142679,7 @@ function Error2D (regl, options) { meshBuffer = regl.buffer({ usage: 'static', type: 'float', - data: __WEIGHTS_311 + data: __WEIGHTS_374 }) update(options) @@ -141249,11 +142772,11 @@ function Error2D (regl, options) { stencil: false, instances: regl.prop('count'), - count: __WEIGHTS_311.length + count: __WEIGHTS_374.length }) //expose API - _$objectAssign_281(error2d, { + _$objectAssign_339(error2d, { update: update, draw: draw, destroy: destroy, @@ -141348,7 +142871,7 @@ function Error2D (regl, options) { else if (typeof options[0] === 'number') { options = {positions: options} } //copy options to avoid mutation & handle aliases - options = _$pick_290(options, { + options = _$pick_349(options, { color: 'color colors fill', capSize: 'capSize cap capsize cap-size', lineWidth: 'lineWidth line-width width line thickness', @@ -141368,23 +142891,23 @@ function Error2D (regl, options) { translateFract: null, draw: true } - options = _$objectAssign_281({}, defaults, options) + options = _$objectAssign_339({}, defaults, options) } - _$updateDiff_363(group, options, [{ + _$updateDiff_425(group, options, [{ lineWidth: function (v) { return +v * .5; }, capSize: function (v) { return +v * .5; }, opacity: parseFloat, errors: function (errors) { - errors = _$flattenVertexData_141(errors) + errors = _$flattenVertexData_198(errors) errorCount += errors.length return errors }, positions: function (positions, state) { - positions = _$flattenVertexData_141(positions, 'float64') + positions = _$flattenVertexData_198(positions, 'float64') state.count = Math.floor(positions.length / 2) - state.bounds = _$normalize_48(positions, 2) + state.bounds = _$normalize_49(positions, 2) state.offset = pointCount pointCount += state.count @@ -141412,7 +142935,7 @@ function Error2D (regl, options) { //convert colors to float arrays for (var i$1 = 0; i$1 < count; i$1++) { - var c = _$normalize_99(colors[i$1], 'uint8') + var c = _$normalize_100(colors[i$1], 'uint8') colorData.set(c, i$1 * 4) } @@ -141426,8 +142949,8 @@ function Error2D (regl, options) { state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] state.translate = [-range[0], -range[1]] - state.scaleFract = __fract32_311(state.scale) - state.translateFract = __fract32_311(state.translate) + state.scaleFract = __fract32_374(state.scale) + state.translateFract = __fract32_374(state.translate) return range }, @@ -141493,8 +143016,8 @@ function Error2D (regl, options) { positionData.set(positions, offset * 2) }) - positionBuffer(__float32_311(positionData)) - positionFractBuffer(__fract32_311(positionData)) + positionBuffer(__float32_374(positionData)) + positionFractBuffer(__fract32_374(positionData)) colorBuffer(colorData) errorBuffer(errorData) } @@ -141511,15 +143034,15 @@ function Error2D (regl, options) { } 'use strict' -/* removed: var _$normalize_48 = require('array-bounds') */; +/* removed: var _$normalize_49 = require('array-bounds') */; -var _$normalize_49 = __normalize_49; +var _$normalize_50 = __normalize_50; -function __normalize_49 (arr, dim, bounds) { +function __normalize_50 (arr, dim, bounds) { if (!arr || arr.length == null) throw Error('Argument should be an array') if (dim == null) dim = 1 - if (bounds == null) bounds = _$normalize_48(arr, dim) + if (bounds == null) bounds = _$normalize_49(arr, dim) for (var offset = 0; offset < dim; offset++) { var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length; @@ -141550,11 +143073,11 @@ function __normalize_49 (arr, dim, bounds) { return arr; } -var _$earcut_134 = {}; +var _$earcut_137 = {}; 'use strict'; -_$earcut_134 = earcut; -_$earcut_134.default = earcut; +_$earcut_137 = earcut; +_$earcut_137.default = earcut; function earcut(data, holeIndices, dim) { @@ -141796,7 +143319,7 @@ function splitEarcut(start, triangles, dim, minX, minY, invSize) { while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { // split the polygon in two by the diagonal - var c = __splitPolygon_134(a, b); + var c = __splitPolygon_137(a, b); // filter colinear points around the cuts a = filterPoints(a, a.next); @@ -141845,7 +143368,7 @@ function compareX(a, b) { function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { - var b = __splitPolygon_134(outerNode, hole); + var b = __splitPolygon_137(outerNode, hole); filterPoints(b, b.next); } } @@ -142072,155 +143595,1288 @@ function middleInside(a, b) { p = p.next; } while (p !== a); - return inside; -} + 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_137(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) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice 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; +}; + +'use strict'; + +var _$isImplemented_191 = function () { + var weakMap, x; + if (typeof WeakMap !== 'function') return false; + try { + // WebKit doesn't support arguments and crashes + weakMap = new WeakMap([[x = {}, '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(x) !== 'one') return false; + + return true; +}; + +"use strict"; + +var _$isImplemented_153 = 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"; +}; + +"use strict"; + +var _$isImplemented_162 = function () { + try { + Object.keys("primitive"); + return true; + } catch (e) { + return false; +} +}; + +"use strict"; + +// eslint-disable-next-line no-empty-function +var _$noop_145 = function () {}; + +"use strict"; + +var _undefined = _$noop_145(); // Support ES3 engines + +var _$isValue_160 = function (val) { + return (val !== _undefined) && (val !== null); +}; + +"use strict"; + +/* removed: var _$isValue_160 = require("../is-value"); */; + +var keys = Object.keys; + +var _$shim_163 = function (object) { + return keys(_$isValue_160(object) ? Object(object) : object); +}; + +"use strict"; + +var _$keys_161 = _$isImplemented_162() + ? Object.keys + : _$shim_163; + +"use strict"; + +/* removed: var _$isValue_160 = require("./is-value"); */; + +var _$validValue_171 = function (value) { + if (!_$isValue_160(value)) throw new TypeError("Cannot use null or undefined"); + return value; +}; + +"use strict"; + +var __dummy_154$0 = 0 + , __dummy_154$1 = 0 + , max = Math.max; + +var _$shim_154 = function (dest, src /*, …srcn*/) { + var error, i, length = max(arguments.length, 2), assign; + dest = Object(_$validValue_171(dest)); + assign = function (key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + _$keys_161(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; + +"use strict"; + +var _$assign_152 = _$isImplemented_153() + ? Object.assign + : _$shim_154; + +// Deprecated + +"use strict"; + +var _$isCallable_158 = function (obj) { + return typeof obj === "function"; +}; + +"use strict"; + +/* removed: var _$isValue_160 = require("./is-value"); */; + +var forEach = Array.prototype.forEach, __create_165 = Object.create; + +var __process_165 = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +// eslint-disable-next-line no-unused-vars +var _$normalizeOptions_165 = function (opts1 /*, …options*/) { + var result = __create_165(null); + forEach.call(arguments, function (options) { + if (!_$isValue_160(options)) return; + __process_165(Object(options), result); + }); + return result; +}; + +"use strict"; + +var str = "razdwatrzy"; + +var _$isImplemented_173 = function () { + if (typeof str.contains !== "function") return false; + return (str.contains("dwa") === true) && (str.contains("foo") === false); +}; + +"use strict"; + +var indexOf = String.prototype.indexOf; + +var _$shim_174 = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; + +"use strict"; + +var _$contains_172 = _$isImplemented_173() + ? String.prototype.contains + : _$shim_174; + +var _$d_121 = {}; +'use strict'; + +var __dummy_121$0 = 0 + , __dummy_121$1 = 0 + , __dummy_121$2 = 0 + , __dummy_121$3 = 0 + + , d; + +d = _$d_121 = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = _$contains_172.call(dscr, 'c'); + e = _$contains_172.call(dscr, 'e'); + w = _$contains_172.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : _$assign_152(_$normalizeOptions_165(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!_$isCallable_158(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!_$isCallable_158(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = _$contains_172.call(dscr, 'c'); + e = _$contains_172.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : _$assign_152(_$normalizeOptions_165(options), desc); +}; + +"use strict"; + +var __create_167 = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; + +var _$isImplemented_167 = function (/* CustomCreate*/) { + var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || __create_167; + if (typeof setPrototypeOf !== "function") return false; + return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject; +}; + +"use strict"; + +/* removed: var _$isValue_160 = require("./is-value"); */; + +var __map_159 = { function: true, object: true }; + +var _$isObject_159 = function (value) { + return (_$isValue_160(value) && __map_159[typeof value]) || false; +}; + +"use strict"; + +var _$setPrototypeOf_166 = _$isImplemented_167() + ? Object.setPrototypeOf + : _$shim_168({}); + +"use strict"; + +/* removed: var _$isObject_159 = require("./is-object"); */; + +var _$validObject_170 = function (value) { + if (!_$isObject_159(value)) throw new TypeError(value + " is not an Object"); + return value; +}; + +"use strict"; + +var generated = Object.create(null), random = Math.random; + +var _$randomUniq_176 = function () { + var str; + do { + str = random() + .toString(36) + .slice(2); + } while (generated[str]); + return str; +}; + +"use strict"; + +var objToString = Object.prototype.toString + , id = objToString.call( + (function () { + return arguments; + })() +); + +var _$isArguments_143 = function (value) { + return objToString.call(value) === id; +}; + +"use strict"; + +var _$validCallable_169 = function (fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; +}; + +"use strict"; + +var __objToString_175 = Object.prototype.toString, __id_175 = __objToString_175.call(""); + +var _$isString_175 = function (value) { + return ( + typeof value === "string" || + (value && + typeof value === "object" && + (value instanceof String || __objToString_175.call(value) === __id_175)) || + false + ); +}; + +"use strict"; + +var _$isImplemented_141 = 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")); +}; + +"use strict"; + +var __objToString_144 = Object.prototype.toString, __id_144 = __objToString_144.call(_$noop_145); + +var _$isFunction_144 = function (value) { + return typeof value === "function" && __objToString_144.call(value) === __id_144; +}; + +"use strict"; + +var _$isImplemented_147 = function () { + var sign = Math.sign; + if (typeof sign !== "function") return false; + return (sign(10) === 1) && (sign(-20) === -1); +}; + +"use strict"; + +var _$shim_148 = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return value > 0 ? 1 : -1; +}; + +"use strict"; + +var _$sign_146 = _$isImplemented_147() + ? Math.sign + : _$shim_148; + +"use strict"; + +var __dummy_149$0 = 0 + + , abs = Math.abs, floor = Math.floor; + +var _$toInteger_149 = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if ((value === 0) || !isFinite(value)) return value; + return _$sign_146(value) * floor(abs(value)); +}; + +"use strict"; + +var __dummy_150$0 = 0 + + , __max_150 = Math.max; + +var _$toPosInteger_150 = function (value) { + return __max_150(0, _$toInteger_149(value)); +}; + +'use strict'; + +var validTypes = { object: true, symbol: true }; + +var _$isImplemented_186 = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + + // Return 'true' also for polyfills + if (!validTypes[typeof Symbol.iterator]) return false; + if (!validTypes[typeof Symbol.toPrimitive]) return false; + if (!validTypes[typeof Symbol.toStringTag]) return false; + + return true; +}; + +'use strict'; + +var _$isSymbol_187 = function (x) { + if (!x) return false; + if (typeof x === 'symbol') return true; + if (!x.constructor) return false; + if (x.constructor.name !== 'Symbol') return false; + return (x[x.constructor.toStringTag] === 'Symbol'); +}; + +'use strict'; + +/* removed: var _$isSymbol_187 = require('./is-symbol'); */; + +var _$validateSymbol_189 = function (value) { + if (!_$isSymbol_187(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; + +// ES2015 Symbol polyfill for environments that do not (or partially) support it + +'use strict'; + +var __dummy_188$0 = 0 + , __dummy_188$1 = 0 + + , __create_188 = Object.create, defineProperties = Object.defineProperties + , __defineProperty_188 = Object.defineProperty, objPrototype = Object.prototype + , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = __create_188(null) + , isNativeSafe; + +if (typeof Symbol === 'function') { + NativeSymbol = Symbol; + try { + String(NativeSymbol()); + isNativeSafe = true; + } catch (ignore) {} +} + +var generateName = (function () { + var created = __create_188(null); + return function (desc) { + var postfix = 0, name, ie11BugWorkaround; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + __defineProperty_188(objPrototype, name, _$d_121.gs(null, function (value) { + // For IE11 issue see: + // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ + // ie11-broken-getters-on-dom-objects + // https://github.com/medikoo/es6-symbol/issues/12 + if (ie11BugWorkaround) return; + ie11BugWorkaround = true; + __defineProperty_188(this, name, _$d_121(value)); + ie11BugWorkaround = false; + })); + return name; + }; +}()); + +// Internal constructor (not one exposed) for creating Symbol instances. +// This one is used to ensure that `someSymbol instanceof Symbol` always return false +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor'); + return SymbolPolyfill(description); +}; + +// Exposed `Symbol` constructor +// (returns instances of HiddenSymbol) +var _$polyfill_188 = SymbolPolyfill = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor'); + if (isNativeSafe) return NativeSymbol(description); + symbol = __create_188(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: _$d_121('', description), + __name__: _$d_121('', generateName(description)) + }); +}; +defineProperties(SymbolPolyfill, { + for: _$d_121(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = SymbolPolyfill(String(key))); + }), + keyFor: _$d_121(function (s) { + var key; + _$validateSymbol_189(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + + // To ensure proper interoperability with other native functions (e.g. Array.from) + // fallback to eventual native implementation of given symbol + hasInstance: _$d_121('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')), + isConcatSpreadable: _$d_121('', (NativeSymbol && NativeSymbol.isConcatSpreadable) || + SymbolPolyfill('isConcatSpreadable')), + iterator: _$d_121('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')), + match: _$d_121('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')), + replace: _$d_121('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')), + search: _$d_121('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')), + species: _$d_121('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')), + split: _$d_121('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')), + toPrimitive: _$d_121('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')), + toStringTag: _$d_121('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')), + unscopables: _$d_121('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables')) +}); + +// Internal tweaks for real symbol producer +defineProperties(HiddenSymbol.prototype, { + constructor: _$d_121(SymbolPolyfill), + toString: _$d_121('', function () { return this.__name__; }) +}); + +// Proper implementation of methods exposed on Symbol.prototype +// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype +defineProperties(SymbolPolyfill.prototype, { + toString: _$d_121(function () { return 'Symbol (' + _$validateSymbol_189(this).__description__ + ')'; }), + valueOf: _$d_121(function () { return _$validateSymbol_189(this); }) +}); +__defineProperty_188(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, _$d_121('', function () { + var symbol = _$validateSymbol_189(this); + if (typeof symbol === 'symbol') return symbol; + return symbol.toString(); +})); +__defineProperty_188(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, _$d_121('c', 'Symbol')); + +// Proper implementaton of toPrimitive and toStringTag for returned symbol instances +__defineProperty_188(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, + _$d_121('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); + +// Note: It's important to define `toPrimitive` as last one, as some implementations +// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) +// And that may invoke error in definition flow: +// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 +__defineProperty_188(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, + _$d_121('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); + +'use strict'; + +var _$es6Symbol_185 = _$isImplemented_186() ? Symbol : _$polyfill_188; + +"use strict"; + +var iteratorSymbol = _$es6Symbol_185.iterator + , __dummy_142$0 = 0 + , __dummy_142$1 = 0 + , __dummy_142$2 = 0 + , __dummy_142$3 = 0 + , __dummy_142$4 = 0 + , __dummy_142$5 = 0 + , __dummy_142$6 = 0 + , __isArray_142 = Array.isArray + , call = Function.prototype.call + , desc = { configurable: true, enumerable: true, writable: true, value: null } + , __defineProperty_142 = Object.defineProperty; + +// eslint-disable-next-line complexity +var _$shim_142 = function (arrayLike /*, mapFn, thisArg*/) { + var mapFn = arguments[1] + , thisArg = arguments[2] + , Context + , i + , j + , arr + , length + , code + , iterator + , result + , getIterator + , value; + + arrayLike = Object(_$validValue_171(arrayLike)); + + if (_$isValue_160(mapFn)) _$validCallable_169(mapFn); + if (!this || this === Array || !_$isFunction_144(this)) { + // Result: Plain array + if (!mapFn) { + if (_$isArguments_143(arrayLike)) { + // Source: Arguments + length = arrayLike.length; + if (length !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (__isArray_142(arrayLike)) { + // Source: Array + arr = new Array(length = arrayLike.length); + for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + // Result: Non plain array + Context = this; + } + + if (!__isArray_142(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { + // Source: Iterator + iterator = _$validCallable_169(getIterator).call(arrayLike); + if (Context) arr = new Context(); + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (Context) { + desc.value = value; + __defineProperty_142(arr, i, desc); + } else { + arr[i] = value; + } + result = iterator.next(); + ++i; + } + length = i; + } else if (_$isString_175(arrayLike)) { + // Source: String + length = arrayLike.length; + if (Context) arr = new Context(); + for (i = 0, j = 0; i < length; ++i) { + value = arrayLike[i]; + if (i + 1 < length) { + code = value.charCodeAt(0); + // eslint-disable-next-line max-depth + if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (Context) { + desc.value = value; + __defineProperty_142(arr, j, desc); + } else { + arr[j] = value; + } + ++j; + } + length = j; + } + } + if (length === undefined) { + // Source: array or array-like + length = _$toPosInteger_150(arrayLike.length); + if (Context) arr = new Context(length); + for (i = 0; i < length; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (Context) { + desc.value = value; + __defineProperty_142(arr, i, desc); + } else { + arr[i] = value; + } + } + } + if (Context) { + desc.value = null; + arr.length = length; + } + return arr; +}; + +"use strict"; + +var _$from_140 = _$isImplemented_141() + ? Array.from + : _$shim_142; + +"use strict"; + +var __dummy_155$0 = 0 + , __dummy_155$1 = 0 + , __dummy_155$2 = 0; + +var _$copy_155 = function (obj/*, propertyNames, options*/) { + var copy = Object(_$validValue_171(obj)), propertyNames = arguments[1], options = Object(arguments[2]); + if (copy !== obj && !propertyNames) return copy; + var result = {}; + if (propertyNames) { + _$from_140(propertyNames, function (propertyName) { + if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; + }); + } else { + _$assign_152(result, obj); + } + return result; +}; + +// Internal method, used by iteration functions. +// Calls a function for each key-value pair found in object +// Optionally takes compareFn to iterate object in specific order + +"use strict"; + +var __dummy_151$0 = 0 + , __dummy_151$1 = 0 + , bind = Function.prototype.bind + , __call_151 = Function.prototype.call + , __keys_151 = Object.keys + , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +var _$_iterate_151 = function (method, defVal) { + return function (obj, cb /*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(_$validValue_171(obj)); + _$validCallable_169(cb); + + list = __keys_151(obj); + if (compareFn) { + list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); + } + if (typeof method !== "function") method = list[method]; + return __call_151.call(method, list, function (key, index) { + if (!objPropertyIsEnumerable.call(obj, key)) return defVal; + return __call_151.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; + +"use strict"; + +var _$forEach_157 = _$_iterate_151("forEach"); + +"use strict"; + +var __dummy_164$0 = 0 + , __dummy_164$1 = 0 + , __call_164 = Function.prototype.call; + +var _$map_164 = function (obj, cb /*, thisArg*/) { + var result = {}, thisArg = arguments[2]; + _$validCallable_169(cb); + _$forEach_157(obj, function (value, key, targetObj, index) { + result[key] = __call_164.call(cb, thisArg, value, key, targetObj, index); + }); + return result; +}; + +'use strict'; + +var __dummy_120$0 = 0 + , __dummy_120$1 = 0 + , __dummy_120$2 = 0 + , __dummy_120$3 = 0 + , __dummy_120$4 = 0 + , __dummy_120$5 = 0 + + , __bind_120 = Function.prototype.bind, __defineProperty_120 = Object.defineProperty + , __hasOwnProperty_120 = Object.prototype.hasOwnProperty + , define; + +define = function (name, desc, options) { + var value = _$validValue_171(desc) && _$validCallable_169(desc.value), dgs; + dgs = _$copy_155(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function () { + if (!options.overwriteDefinition && __hasOwnProperty_120.call(this, name)) return value; + desc.value = __bind_120.call(value, options.resolveContext ? options.resolveContext(this) : this); + __defineProperty_120(this, name, desc); + return this[name]; + }; + return dgs; +}; + +var _$autoBind_120 = function (props/*, options*/) { + var options = _$normalizeOptions_165(arguments[1]); + if (options.resolveContext != null) _$validCallable_169(options.resolveContext); + return _$map_164(props, function (desc, name) { return define(name, desc, options); }); +}; + +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear + +"use strict"; + +/* removed: var _$validValue_171 = require("../../object/valid-value"); */; + +var _$clear_139 = function () { + _$validValue_171(this).length = 0; + return this; +}; + +"use strict"; + +var __dummy_180$0 = 0 + , __dummy_180$1 = 0 + , __dummy_180$2 = 0 + , __dummy_180$3 = 0 + , __dummy_180$4 = 0 + , __dummy_180$5 = 0 + , __dummy_180$6 = 0; + +var __defineProperty_180 = Object.defineProperty, __defineProperties_180 = Object.defineProperties, Iterator; + +var _$es6Iterator_180 = Iterator = function (list, context) { + if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); + __defineProperties_180(this, { + __list__: _$d_121("w", _$validValue_171(list)), + __context__: _$d_121("w", context), + __nextIndex__: _$d_121("w", 0) + }); + if (!context) return; + _$validCallable_169(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_180( + Iterator.prototype, + _$assign_152( + { + _next: _$d_121(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_121(function () { + return this._createResult(this._next()); + }), + _createResult: _$d_121(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: _$d_121(function (i) { + return this.__list__[i]; + }), + _unBind: _$d_121(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_121(function () { + return "[object " + (this[_$es6Symbol_185.toStringTag] || "Object") + "]"; + }) + }, + _$autoBind_120({ + _onAdd: _$d_121(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + __defineProperty_180(this, "__redo__", _$d_121("c", [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: _$d_121(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_121(function () { + if (this.__redo__) _$clear_139.call(this.__redo__); + this.__nextIndex__ = 0; + }) + }) + ) +); + +__defineProperty_180( + Iterator.prototype, + _$es6Symbol_185.iterator, + _$d_121(function () { + return this; + }) +); + +var _$array_177 = {}; +"use strict"; + +var __dummy_177$0 = 0 + , __dummy_177$1 = 0 + , __dummy_177$2 = 0 + , __dummy_177$3 = 0 + , __dummy_177$4 = 0; + +var __defineProperty_177 = Object.defineProperty, ArrayIterator; + +ArrayIterator = _$array_177 = function (arr, kind) { + if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); + _$es6Iterator_180.call(this, arr); + if (!kind) kind = "value"; + else if (_$contains_172.call(kind, "key+value")) kind = "key+value"; + else if (_$contains_172.call(kind, "key")) kind = "key"; + else kind = "value"; + __defineProperty_177(this, "__kind__", _$d_121("", kind)); +}; +if (_$setPrototypeOf_166) _$setPrototypeOf_166(ArrayIterator, _$es6Iterator_180); + +// Internal %ArrayIteratorPrototype% doesn't expose its constructor +delete ArrayIterator.prototype.constructor; + +ArrayIterator.prototype = Object.create(_$es6Iterator_180.prototype, { + _resolve: _$d_121(function (i) { + if (this.__kind__ === "value") return this.__list__[i]; + if (this.__kind__ === "key+value") return [i, this.__list__[i]]; + return i; + }) +}); +__defineProperty_177(ArrayIterator.prototype, _$es6Symbol_185.toStringTag, _$d_121("c", "Array Iterator")); + +var _$string_182 = {}; +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols -// 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_134(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; +"use strict"; - a.next = b; - b.prev = a; +var __dummy_182$0 = 0 + , __dummy_182$1 = 0 + , __dummy_182$2 = 0 + , __dummy_182$3 = 0; + +var __defineProperty_182 = Object.defineProperty, StringIterator; + +StringIterator = _$string_182 = function (str) { + if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); + str = String(str); + _$es6Iterator_180.call(this, str); + __defineProperty_182(this, "__length__", _$d_121("", str.length)); +}; +if (_$setPrototypeOf_166) _$setPrototypeOf_166(StringIterator, _$es6Iterator_180); + +// Internal %ArrayIteratorPrototype% doesn't expose its constructor +delete StringIterator.prototype.constructor; + +StringIterator.prototype = Object.create(_$es6Iterator_180.prototype, { + _next: _$d_121(function () { + if (!this.__list__) return undefined; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + return undefined; + }), + _resolve: _$d_121(function (i) { + var char = this.__list__[i], code; + if (this.__nextIndex__ === this.__length__) return char; + code = char.charCodeAt(0); + if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++]; + return char; + }) +}); +__defineProperty_182(StringIterator.prototype, _$es6Symbol_185.toStringTag, _$d_121("c", "String Iterator")); - a2.next = an; - an.prev = a2; +"use strict"; - b2.next = a2; - a2.prev = b2; +var __dummy_181$0 = 0 + , __dummy_181$1 = 0 + , __dummy_181$2 = 0; - bp.next = b2; - b2.prev = bp; +var __iteratorSymbol_181 = _$es6Symbol_185.iterator + , __isArray_181 = Array.isArray; - return b2; -} +var _$isIterable_181 = function (value) { + if (!_$isValue_160(value)) return false; + if (__isArray_181(value)) return true; + if (_$isString_175(value)) return true; + if (_$isArguments_143(value)) return true; + return typeof value[__iteratorSymbol_181] === "function"; +}; -// 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); +"use strict"; - if (!last) { - p.prev = p; - p.next = p; +/* removed: var _$isIterable_181 = require("./is-iterable"); */; - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} +var _$validIterable_183 = function (value) { + if (!_$isIterable_181(value)) throw new TypeError(value + " is not iterable"); + return value; +}; -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; +"use strict"; - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} +var __dummy_179$0 = 0 + , __dummy_179$1 = 0 + , __dummy_179$2 = 0 + , __dummy_179$3 = 0 + , __dummy_179$4 = 0 + , __iteratorSymbol_179 = _$es6Symbol_185.iterator; -function Node(i, x, y) { - // vertice index in coordinates array - this.i = i; +var _$get_179 = function (obj) { + if (typeof _$validIterable_183(obj)[__iteratorSymbol_179] === "function") return obj[__iteratorSymbol_179](); + if (_$isArguments_143(obj)) return new _$array_177(obj); + if (_$isString_175(obj)) return new _$string_182(obj); + return new _$array_177(obj); +}; - // vertex coordinates - this.x = x; - this.y = y; +"use strict"; - // previous and next vertice nodes in a polygon ring - this.prev = null; - this.next = null; +var __dummy_178$0 = 0 + , __dummy_178$1 = 0 + , __dummy_178$2 = 0 + , __dummy_178$3 = 0; - // z-order curve value - this.z = null; +var __isArray_178 = Array.isArray, __call_178 = Function.prototype.call, some = Array.prototype.some; - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; +var _$forOf_178 = function (iterable, cb /*, thisArg*/) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code; + if (__isArray_178(iterable) || _$isArguments_143(iterable)) mode = "array"; + else if (_$isString_175(iterable)) mode = "string"; + else iterable = _$get_179(iterable); - // indicates whether this is a steiner point - this.steiner = false; -} + _$validCallable_169(cb); + doBreak = function () { + broken = true; + }; + if (mode === "array") { + some.call(iterable, function (value) { + __call_178.call(cb, thisArg, value, doBreak); + return broken; + }); + return; + } + if (mode === "string") { + length = iterable.length; + for (i = 0; i < length; ++i) { + char = iterable[i]; + if (i + 1 < length) { + code = char.charCodeAt(0); + if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i]; + } + __call_178.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); -// 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; + while (!result.done) { + __call_178.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } +}; - 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)); - } - } +// Exports true if environment provides native `WeakMap` implementation, whatever that is. - 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])); - } +'use strict'; - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); +var _$isNativeImplemented_192 = (function () { + if (typeof WeakMap !== 'function') return false; + return (Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'); +}()); + +'use strict'; + +var __dummy_193$0 = 0 + , __dummy_193$1 = 0 + , __dummy_193$2 = 0 + , __dummy_193$3 = 0 + , __dummy_193$4 = 0 + , __dummy_193$5 = 0 + , __dummy_193$6 = 0 + , toStringTagSymbol = _$es6Symbol_185.toStringTag + , __dummy_193$7 = 0 + + , __isArray_193 = Array.isArray, __defineProperty_193 = Object.defineProperty + , __hasOwnProperty_193 = Object.prototype.hasOwnProperty, __getPrototypeOf_193 = Object.getPrototypeOf + , WeakMapPoly; + +var _$polyfill_193 = WeakMapPoly = function (/*iterable*/) { + var iterable = arguments[0], self; + if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\''); + if (_$isNativeImplemented_192 && _$setPrototypeOf_166 && (WeakMap !== WeakMapPoly)) { + self = _$setPrototypeOf_166(new WeakMap(), __getPrototypeOf_193(this)); + } else { + self = this; + } + if (iterable != null) { + if (!__isArray_193(iterable)) iterable = _$get_179(iterable); + } + __defineProperty_193(self, '__weakMapData__', _$d_121('c', '$weakMap$' + _$randomUniq_176())); + if (!iterable) return self; + _$forOf_178(iterable, function (val) { + _$validValue_171(val); + self.set(val[0], val[1]); + }); + return self; }; -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; +if (_$isNativeImplemented_192) { + if (_$setPrototypeOf_166) _$setPrototypeOf_166(WeakMapPoly, WeakMap); + WeakMapPoly.prototype = Object.create(WeakMap.prototype, { + constructor: _$d_121(WeakMapPoly) + }); } -// 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; +Object.defineProperties(WeakMapPoly.prototype, { + delete: _$d_121(function (key) { + if (__hasOwnProperty_193.call(_$validObject_170(key), this.__weakMapData__)) { + delete key[this.__weakMapData__]; + return true; + } + return false; + }), + get: _$d_121(function (key) { + if (__hasOwnProperty_193.call(_$validObject_170(key), this.__weakMapData__)) { + return key[this.__weakMapData__]; + } + }), + has: _$d_121(function (key) { + return __hasOwnProperty_193.call(_$validObject_170(key), this.__weakMapData__); + }), + set: _$d_121(function (key, value) { + __defineProperty_193(_$validObject_170(key), this.__weakMapData__, _$d_121('c', value)); + return this; + }), + toString: _$d_121(function () { return '[object WeakMap]'; }) +}); +__defineProperty_193(WeakMapPoly.prototype, toStringTagSymbol, _$d_121('c', 'WeakMap')); - 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; -}; +'use strict'; + +var _$es6WeakMap_190 = _$isImplemented_191() ? WeakMap : _$polyfill_193; 'use strict' -/* removed: var _$normalize_99 = require('color-normalize') */; -/* removed: var _$normalize_48 = require('array-bounds') */; -/* removed: var _$objectAssign_281 = require('object-assign') */; -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$pick_290 = require('pick-by-alias') */; -/* removed: var _$updateDiff_363 = require('update-diff') */; -/* removed: var _$flattenVertexData_141 = require('flatten-vertex-data') */; -/* removed: var _$earcut_134 = require('earcut') */; -/* removed: var _$normalize_49 = require('array-normalize') */; -var _$createLine_312 = __createLine_312 +/* removed: var _$normalize_100 = require('color-normalize') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$earcut_137 = require('earcut') */; +/* removed: var _$normalize_50 = require('array-normalize') */; +/* removed: var _$toFloat32_415 = require('to-float32'); */; +var __float32_375 = _$toFloat32_415.float32; +var __fract32_375 = _$toFloat32_415.fract32; +/* removed: var _$es6WeakMap_190 = require('es6-weak-map') */; +/* removed: var _$parseRect_343 = require('parse-rect') */; -var MAX_SCALE = 1e10; +var _$Line2D_375 = Line2D -function __createLine_312 (regl, options) { +/** @constructor */ +function Line2D (regl, options) { + if (!(this instanceof Line2D)) { return new Line2D(regl, options) } + if (typeof regl === 'function') { if (!options) { options = {} } options.regl = regl @@ -142236,63 +144892,39 @@ function __createLine_312 (regl, options) { } // persistent variables - var gl = regl._gl, drawMiterLine, drawRectLine, drawFill, colorBuffer, offsetBuffer, positionBuffer, positionFractBuffer, dashTexture, - - // used to for new lines instances - defaults = { - positions: [], - dashes: null, - join: null, - miterLimit: 1, - thickness: 10, - cap: 'square', - color: 'black', - opacity: 1, - overlay: false, - viewport: null, - range: null, - close: null, - fill: null - }, + this.gl = regl._gl + this.regl = regl - // list of options for lines - lines = [] + // list of options for lines + this.passes = [] - var dashMult = 2, maxPatternLength = 256, maxLinesNumber = 2048, precisionThreshold = 3e6, maxPoints = 1e4 + // cached shaders instance + this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl) - // color per-point - colorBuffer = regl.buffer({ - usage: 'dynamic', - type: 'uint8', - data: null - }) - offsetBuffer = regl.buffer({ + // init defaults + this.update(options) +} + + +Line2D.dashMult = 2 +Line2D.maxPatternLength = 256 +Line2D.precisionThreshold = 3e6 +Line2D.maxPoints = 1e4 + + + +// cache of created draw calls per-regl instance +Line2D.shaders = new _$es6WeakMap_190() + + +// create static shaders once +Line2D.createShaders = function (regl) { + var offsetBuffer = regl.buffer({ usage: 'static', type: 'float', data: [0,1, 0,0, 1,1, 1,0] }) - positionBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - positionFractBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - dashTexture = regl.texture({ - channels: 1, - data: new Uint8Array(maxPatternLength * maxLinesNumber), - width: maxPatternLength, - height: maxLinesNumber, - mag: 'linear', - min: 'linear' - }) - - // init defaults - update(options) var shaderOptions = { primitive: 'triangle strip', @@ -142308,13 +144940,11 @@ function __createLine_312 (regl, options) { translateFract: regl.prop('translateFract'), translate: regl.prop('translate'), thickness: regl.prop('thickness'), - dashPattern: dashTexture, - dashLength: regl.prop('dashLength'), - dashShape: [maxPatternLength, maxLinesNumber], + dashPattern: regl.prop('dashTexture'), opacity: regl.prop('opacity'), pixelRatio: regl.context('pixelRatio'), id: regl.prop('id'), - scaleRatio: regl.prop('scaleRatio'), + dashSize: regl.prop('dashLength'), viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; } }, @@ -142333,141 +144963,157 @@ function __createLine_312 (regl, options) { } }, depth: { + // FIXME: that fills up stencil buffer enable: function (ctx, prop) { return !prop.overlay } }, + stencil: {enable: false}, scissor: { enable: true, box: regl.prop('viewport') }, - stencil: false, viewport: regl.prop('viewport') } - // create regl draw - drawMiterLine = regl(_$objectAssign_281({ - // culling removes polygon creasing - cull: { - enable: true, - face: 'back' - }, - - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, dashLength, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIST = 1.;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevDirection = normalize(prevDiff);\n\tvec2 currDirection = normalize(currDiff);\n\tvec2 nextDirection = normalize(nextDiff);\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tif (prevDirection == currDirection) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (nextDirection == currDirection) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]), - frag: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), - - attributes: { - lineEnd: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 0 - }, - lineTop: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 4 - }, - aColor: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4; }, - divisor: 1 - }, - bColor: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4 + 4; }, - divisor: 1 - }, - prevCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return prop.offset * 8; }, - divisor: 1 - }, - aCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, - divisor: 1 - }, - bCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, - divisor: 1 - }, - nextCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 24 + prop.offset * 8; }, - divisor: 1 - } - } - }, shaderOptions)) // simplified rectangular line shader - drawRectLine = regl(_$objectAssign_281({ - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\t// vec2 scaleRatio = scale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scaleRatio);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), - frag: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + var drawRectLine = regl(_$objectAssign_339({ + vert: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), + frag: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), attributes: { + // if point is at the end of segment lineEnd: { buffer: offsetBuffer, divisor: 0, stride: 8, offset: 0 }, + // if point is at the top of segment lineTop: { buffer: offsetBuffer, divisor: 0, stride: 8, offset: 4 }, + // beginning of line coordinate aCoord: { - buffer: positionBuffer, + buffer: regl.prop('positionBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, + offset: 8, divisor: 1 }, + // end of line coordinate bCoord: { - buffer: positionBuffer, + buffer: regl.prop('positionBuffer'), stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, + offset: 16, divisor: 1 }, aCoordFract: { - buffer: positionFractBuffer, + buffer: regl.prop('positionFractBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, + offset: 8, divisor: 1 }, bCoordFract: { - buffer: positionFractBuffer, + buffer: regl.prop('positionFractBuffer'), stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, + offset: 16, divisor: 1 }, color: { - buffer: colorBuffer, + buffer: regl.prop('colorBuffer'), stride: 4, - offset: function (ctx, prop) { return prop.offset * 4; }, + offset: 0, divisor: 1 } } }, shaderOptions)) + // create regl draw + var drawMiterLine + + try { + drawMiterLine = regl(_$objectAssign_339({ + // culling removes polygon creasing + cull: { + enable: true, + face: 'back' + }, + + vert: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n\t// adjust scale for horizontal bars\n\tvec2 scale = max(scale, MIN_DIFF);\n\tvec2 scaleRatio = scale * viewport.zw;\n\n\tvec2 normalWidth = thickness / (scale * viewport.zw);\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]), + frag: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + + attributes: { + // is line end + lineEnd: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 0 + }, + // is line top + lineTop: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 4 + }, + // left color + aColor: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 0, + divisor: 1 + }, + // right color + bColor: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 4, + divisor: 1 + }, + prevCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 0, + divisor: 1 + }, + aCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 8, + divisor: 1 + }, + bCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 16, + divisor: 1 + }, + nextCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 24, + divisor: 1 + } + } + }, shaderOptions)) + } catch (e) { + // IE/bad Webkit fallback + drawMiterLine = drawRectLine + } // fill shader - drawFill = regl({ + var drawFill = regl({ primitive: 'triangle', elements: function (ctx, prop) { return prop.triangles; }, offset: 0, - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), - frag: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= opacity;\n}\n"]), + vert: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]), + frag: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]), uniforms: { scale: regl.prop('scale'), @@ -142483,494 +145129,456 @@ function __createLine_312 (regl, options) { attributes: { position: { - buffer: positionBuffer, + buffer: regl.prop('positionBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; } + offset: 8 }, positionFract: { - buffer: positionFractBuffer, + buffer: regl.prop('positionFractBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; } + offset: 8 } }, blend: shaderOptions.blend, - depth: { - enable: false - }, + depth: { enable: false }, scissor: shaderOptions.scissor, stencil: shaderOptions.stencil, viewport: shaderOptions.viewport }) - // expose API - _$objectAssign_281(line2d, { - update: update, - draw: draw, - destroy: destroy, - regl: regl, - gl: gl, - canvas: gl.canvas, - lines: lines - }) + return { + fill: drawFill, rect: drawRectLine, miter: drawMiterLine + } +} - function line2d (opts) { - // update - if (opts) { - update(opts) - } - // destroy - else if (opts === null) { - destroy() - } +// used to for new lines instances +Line2D.defaults = { + dashes: null, + join: 'miter', + miterLimit: 1, + thickness: 10, + cap: 'square', + color: 'black', + opacity: 1, + overlay: false, + viewport: null, + range: null, + close: false, + fill: null +} - draw() + +Line2D.prototype.render = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (args.length) { + (ref = this).update.apply(ref, args) } - function draw (options) { - if (typeof options === 'number') { return drawLine(options) } + this.draw() + var ref; +} - // make options a batch - if (options && !Array.isArray(options)) { options = [options] } - // render multiple polylines via regl batch - lines.forEach(function (s, i) { - drawLine(i) - }) - } +Line2D.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - // draw single line by id - function drawLine (s) { - if (typeof s === 'number') { s = lines[s] } + // render multiple polylines via regl batch + (args.length ? args : this.passes).forEach(function (s, i) { + // render array pass as a list of passes + if (s && Array.isArray(s)) { return (ref = this$1).draw.apply(ref, s) } - if (!(s && s.count && s.opacity && s.positions && s.positions.length > 2)) { return } + if (typeof s === 'number') { s = this$1.passes[s] } - regl._refresh() + if (!(s && s.count > 1 && s.opacity)) { return } + + this$1.regl._refresh() if (s.fill && s.triangles && s.triangles.length > 2) { - drawFill(s) + this$1.shaders.fill(s) } - if (!s.thickness || !s.color) { return } - - s.scaleRatio = [ - s.scale[0] * s.viewport.width, - s.scale[1] * s.viewport.height - ] + if (!s.thickness) { return } // high scale is only available for rect mode with precision - if (s.scaleRatio[0] > precisionThreshold || s.scaleRatio[1] > precisionThreshold) { - drawRectLine(s) + if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) { + this$1.shaders.rect(s) } - // thin lines or too many points are rendered as simplified rect shader - else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.positions.length >= maxPoints))) { - drawRectLine(s) + // thin this.passes or too many points are rendered as simplified rect shader + else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints))) { + this$1.shaders.rect(s) } else { - drawMiterLine(s) - } - - if (s.after) { s.after(s) } - } - - function update (options) { - if (!options) { return } - - if (options.length != null) { - if (typeof options[0] === 'number') { options = [{positions: options}] } - } - - // make options a batch - else if (!Array.isArray(options)) { options = [options] } + this$1.shaders.miter(s) + } + var ref; + }) - // global count of points - var pointCount = 0 + return this +} - // process per-line settings - line2d.lines = lines = options.map(function (options, i) { - var state = lines[i] - if (options === undefined) { return state } +Line2D.prototype.update = function (options) { + var this$1 = this; - // null-argument resets positions - if (options === null) { options = { positions: null } } - else if (typeof options === 'function') { options = {after: options} } - else if (typeof options[0] === 'number') { options = {positions: options} } + if (!options) { return } - // reduce by aliases - options = _$pick_290(options, { - positions: 'positions points data coords', - thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth', - join: 'lineJoin linejoin join type mode', - miterLimit: 'miterlimit miterLimit', - dashes: 'dash dashes dasharray dash-array dashArray', - color: 'color stroke colors stroke-color strokeColor', - fill: 'fill fill-color fillColor', - opacity: 'alpha opacity', - overlay: 'overlay crease overlap intersect', - close: 'closed close closed-path closePath', - range: 'range dataBox', - viewport: 'viewport viewBox', - hole: 'holes hole hollow', - after: 'after callback done pass' - }) + if (options.length != null) { + if (typeof options[0] === 'number') { options = [{positions: options}] } + } - // reset positions - if (options.positions === null) { options.positions = [] } + // make options a batch + else if (!Array.isArray(options)) { options = [options] } - if (!state) { - lines[i] = state = { - id: i, - scale: null, - scaleFract: null, - translate: null, - translateFract: null, - count: 0, - offset: 0, - dashLength: 0, - hole: true - } - options = _$objectAssign_281({}, defaults, options) - } + var ref = this; + var regl = ref.regl; + var gl = ref.gl; + // process per-line settings + options.forEach(function (o, i) { + var state = this$1.passes[i] - // calculate state values - _$updateDiff_363(state, options, [{ - thickness: parseFloat, - opacity: parseFloat, - miterLimit: parseFloat, - overlay: Boolean, - join: function (j) { return j; }, - after: function (fn) { return fn; }, - hole: function (h) { return h || []; }, + if (o === undefined) { return } - positions: function (positions, state, options) { - positions = _$flattenVertexData_141(positions, 'float64') + // null-argument removes pass + if (o === null) { + this$1.passes[i] = null + return + } - var count = Math.floor(positions.length / 2) - var bounds = _$normalize_48(positions, 2) + if (typeof o[0] === 'number') { o = {positions: o} } + + // handle aliases + o = _$pick_349(o, { + positions: 'positions points data coords', + thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth', + join: 'lineJoin linejoin join type mode', + miterLimit: 'miterlimit miterLimit', + dashes: 'dash dashes dasharray dash-array dashArray', + color: 'color colour stroke colors colours stroke-color strokeColor', + fill: 'fill fill-color fillColor', + opacity: 'alpha opacity', + overlay: 'overlay crease overlap intersect', + close: 'closed close closed-path closePath', + range: 'range dataBox', + viewport: 'viewport viewBox', + hole: 'holes hole hollow' + }) - // FIXME: make it dynamic - if (!state.range && !options.range) { - options.range = bounds - } + // init state + if (!state) { + this$1.passes[i] = state = { + id: i, + scale: null, + scaleFract: null, + translate: null, + translateFract: null, + count: 0, + hole: [], + + dashLength: 1, + dashTexture: regl.texture({ + channels: 1, + data: new Uint8Array([255]), + width: 1, + height: 1, + mag: 'linear', + min: 'linear' + }), + + colorBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8', + data: null + }), + positionBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }), + positionFractBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }) + } - state.count = count - state.bounds = bounds + o = _$objectAssign_339({}, Line2D.defaults, o) + } + if (o.thickness != null) { state.thickness = parseFloat(o.thickness) } + if (o.opacity != null) { state.opacity = parseFloat(o.opacity) } + if (o.miterLimit != null) { state.miterLimit = parseFloat(o.miterLimit) } + if (o.overlay != null) { state.overlay = !!o.overlay } + if (o.join != null) { state.join = o.join } + if (o.hole != null) { state.hole = o.hole } + if (o.fill != null) { state.fill = !o.fill ? null : _$normalize_100(o.fill, 'uint8') } + if (o.viewport != null) { state.viewport = _$parseRect_343(o.viewport) } + + if (!state.viewport) { + state.viewport = _$parseRect_343([ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]) + } - pointCount += count + if (o.close != null) { state.close = o.close } + + // reset positions + if (o.positions === null) { o.positions = [] } + if (o.positions) { + var positions, count + + // if positions are an object with x/y + if (o.positions.x && o.positions.y) { + var xPos = o.positions.x + var yPos = o.positions.y + count = state.count = Math.max( + xPos.length, + yPos.length + ) + positions = new Float64Array(count * 2) + for (var i$1 = 0; i$1 < count; i$1++) { + positions[i$1 * 2] = xPos[i$1] + positions[i$1 * 2 + 1] = yPos[i$1] + } + } + else { + positions = _$flattenVertexData_198(o.positions, 'float64') + count = state.count = Math.floor(positions.length / 2) + } - return positions - }, + var bounds = state.bounds = _$normalize_49(positions, 2) - fill: function (c) { - return !c ? null : _$normalize_99(c, 'uint8') - }, + // create fill positions + // FIXME: fill positions can be set only along with positions + if (state.fill) { + var pos = [] - dashes: function (dashes, state, options) { - var dashLength = state.dashLength, - dashData + // filter bad vertices and remap triangles to ensure shape + var ids = {} + var lastId = 0 - if (!dashes || dashes.length < 2) { - dashLength = 1. - dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]) + for (var i$2 = 0, ptr = 0, l = state.count; i$2 < l; i$2++) { + var x = positions[i$2*2] + var y = positions[i$2*2 + 1] + if (isNaN(x) || isNaN(y) || x == null || y == null) { + x = positions[lastId*2] + y = positions[lastId*2 + 1] + ids[i$2] = lastId } - else { - dashLength = 0.; - for(var i = 0; i < dashes.length; ++i) { - dashLength += dashes[i] - } - dashData = new Uint8Array(dashLength * dashMult) - var ptr = 0 - var fillColor = 255 - - // repeat texture two times to provide smooth 0-step - for (var k = 0; k < 2; k++) { - for(var i$1 = 0; i$1 < dashes.length; ++i$1) { - for(var j = 0, l = dashes[i$1] * dashMult * .5; j < l; ++j) { - dashData[ptr++] = fillColor - } - fillColor ^= 255 - } - } + lastId = i$2 } - - dashTexture.subimage({ - // channels: 1, - data: dashData, - width: dashData.length, - height: 1 - }, 0, state.id) - - state.dashLength = dashLength - - return dashData + pos[ptr++] = x + pos[ptr++] = y } - }, - - // dependent properties & complement actions - { - close: function (close, state, options) { - if (close != null) { return close } - if (state.positions.length >= 4 && - state.positions[0] === state.positions[state.positions.length - 2] && - state.positions[1] === state.positions[state.positions.length - 1]) { - return true - } - return false - }, - - positions: function (p, state, options) { - if (state.fill && p.length) { - var pos = [] - - // filter bad vertices and remap triangles to ensure shape - var ids = {} - var lastId = 0 - - for (var i = 0, ptr = 0, l = state.count; i < l; i++) { - var x = state.positions[i*2] - var y = state.positions[i*2 + 1] - if (Number.isNaN(x) || Number.isNaN(y)) { - x = state.positions[lastId*2] - y = state.positions[lastId*2 + 1] - ids[i] = lastId - } - else { - lastId = i - } - pos[ptr++] = x - pos[ptr++] = y - } - - var triangles = _$earcut_134(pos, state.hole) - - for (var i$1 = 0, l$1 = triangles.length; i$1 < l$1; i$1++) { - if (ids[triangles[i$1]] != null) { triangles[i$1] = ids[triangles[i$1]] } - } - state.triangles = triangles - } - return state.positions - }, - - color: function (colors, state, options) { - var count = state.count + var triangles = _$earcut_137(pos, state.hole || []) - if (!colors) { colors = 'transparent' } + for (var i$3 = 0, l$1 = triangles.length; i$3 < l$1; i$3++) { + if (ids[triangles[i$3]] != null) { triangles[i$3] = ids[triangles[i$3]] } + } - // 'black' or [0,0,0,0] case - if (!Array.isArray(colors) || typeof colors[0] === 'number') { - var color = colors; - colors = Array(count); - for (var i = 0; i < count; i++) { - colors[i] = color - } - } + state.triangles = triangles + } - if (colors.length < count) { throw Error('Not enough colors') } + // update position buffers + var npos = new Float64Array(positions) + _$normalize_50(npos, 2, bounds) - var colorData = new Uint8Array(count * 4 + 4) + var positionData = new Float64Array(count * 2 + 6) - // convert colors to float arrays - for (var i$1 = 0; i$1 < count; i$1++) { - var c = _$normalize_99(colors[i$1], 'uint8') - colorData.set(c, i$1 * 4) - } + // rotate first segment join + if (state.close) { + if (positions[0] === positions[count*2 - 2] && + positions[1] === positions[count*2 - 1]) { + positionData[0] = npos[count*2 - 4] + positionData[1] = npos[count*2 - 3] + } + else { + positionData[0] = npos[count*2 - 2] + positionData[1] = npos[count*2 - 1] + } + } + else { + positionData[0] = npos[0] + positionData[1] = npos[1] + } - return colorData - }, + positionData.set(npos, 2) - range: function (range, state, options) { - if (!state.count) { return null } + // add last segment + if (state.close) { + // ignore coinciding start/end + if (positions[0] === positions[count*2 - 2] && + positions[1] === positions[count*2 - 1]) { + positionData[count*2 + 2] = npos[2] + positionData[count*2 + 3] = npos[3] + state.count -= 1 + } + else { + positionData[count*2 + 2] = npos[0] + positionData[count*2 + 3] = npos[1] + positionData[count*2 + 4] = npos[2] + positionData[count*2 + 5] = npos[3] + } + } + // add stub + else { + positionData[count*2 + 2] = npos[count*2 - 2] + positionData[count*2 + 3] = npos[count*2 - 1] + positionData[count*2 + 4] = npos[count*2 - 2] + positionData[count*2 + 5] = npos[count*2 - 1] + } - var bounds = state.bounds - if (!range) { range = bounds } + state.positionBuffer(__float32_375(positionData)) + state.positionFractBuffer(__fract32_375(positionData)) + } - var boundsW = bounds[2] - bounds[0], - boundsH = bounds[3] - bounds[1] + if (o.range) { + state.range = o.range + } else if (!state.range) { + state.range = state.bounds + } - var rangeW = range[2] - range[0], - rangeH = range[3] - range[1] + if ((o.range || o.positions) && state.count) { + var bounds$1 = state.bounds - state.scale = [ - boundsW / rangeW, - boundsH / rangeH - ] - state.translate = [ - -range[0] / rangeW + bounds[0] / rangeW || 0, - -range[1] / rangeH + bounds[1] / rangeH || 0 - ] + var boundsW = bounds$1[2] - bounds$1[0], + boundsH = bounds$1[3] - bounds$1[1] - state.scaleFract = __fract32_312(state.scale) - state.translateFract = __fract32_312(state.translate) + var rangeW = state.range[2] - state.range[0], + rangeH = state.range[3] - state.range[1] - return range - }, + state.scale = [ + boundsW / rangeW, + boundsH / rangeH + ] + state.translate = [ + -state.range[0] / rangeW + bounds$1[0] / rangeW || 0, + -state.range[1] / rangeH + bounds$1[1] / rangeH || 0 + ] - viewport: function (vp) { - var viewport + state.scaleFract = __fract32_375(state.scale) + state.translateFract = __fract32_375(state.translate) + } - if (Array.isArray(vp)) { - viewport = { - x: vp[0], - y: vp[1], - width: vp[2] - vp[0], - height: vp[3] - vp[1] - } - } - else if (vp) { - viewport = { - x: vp.x || vp.left || 0, - y: vp.y || vp.top || 0 - } + if (o.dashes) { + var dashLength = 0., dashData - if (vp.right) { viewport.width = vp.right - viewport.x } - else { viewport.width = vp.w || vp.width || 0 } + if (!o.dashes || o.dashes.length < 2) { + dashLength = 1. + dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]) + } - if (vp.bottom) { viewport.height = vp.bottom - viewport.y } - else { viewport.height = vp.h || vp.height || 0 } - } - else { - viewport = { - x: 0, y: 0, - width: gl.drawingBufferWidth, - height: gl.drawingBufferHeight + else { + dashLength = 0.; + for(var i$4 = 0; i$4 < o.dashes.length; ++i$4) { + dashLength += o.dashes[i$4] + } + dashData = new Uint8Array(dashLength * Line2D.dashMult) + var ptr$1 = 0 + var fillColor = 255 + + // repeat texture two times to provide smooth 0-step + for (var k = 0; k < 2; k++) { + for(var i$5 = 0; i$5 < o.dashes.length; ++i$5) { + for(var j = 0, l$2 = o.dashes[i$5] * Line2D.dashMult * .5; j < l$2; ++j) { + dashData[ptr$1++] = fillColor } + fillColor ^= 255 } - - return viewport } - }]) + } - return state - }) + state.dashLength = dashLength + state.dashTexture({ + channels: 1, + data: dashData, + width: dashData.length, + height: 1, + mag: 'linear', + min: 'linear' + }, 0, 0) + } - // put collected data into buffers - // FIXME: possible optimization is updating only segment subdata - if (pointCount) { - var len = pointCount * 2 + lines.length * 6; - var positionData = new Float64Array(len) - var offset = 0 - var colorData = new Uint8Array(len * 2) + if (o.color) { + var count$1 = state.count + var colors = o.color - lines.forEach(function (state, i) { - if (!state) { return } + if (!colors) { colors = 'transparent' } - var positions = state.positions; - var count = state.count; - var color = state.color; - state.offset = offset + var colorData = new Uint8Array(count$1 * 4 + 4) - if (!count) { return } + // convert colors to typed arrays + if (!Array.isArray(colors) || typeof colors[0] === 'number') { + var c = _$normalize_100(colors, 'uint8') - // provide normalized positions - var npos = new Float64Array(positions.length) - npos.set(positions) - _$normalize_49(npos, 2, state.bounds) - - // rotate first segment join - if (state.close) { - if (positions[0] === positions[count*2 - 2] && - positions[1] === positions[count*2 - 1]) { - positionData[offset*2 + 0] = npos[count*2 - 4] - positionData[offset*2 + 1] = npos[count*2 - 3] - } - else { - positionData[offset*2 + 0] = npos[count*2 - 2] - positionData[offset*2 + 1] = npos[count*2 - 1] - } - } - else { - positionData[offset*2 + 0] = npos[0] - positionData[offset*2 + 1] = npos[1] - } - colorData[offset*4 + 0] = color[0] - colorData[offset*4 + 1] = color[1] - colorData[offset*4 + 2] = color[2] - colorData[offset*4 + 3] = color[3] - - positionData.set(npos, offset * 2 + 2) - colorData.set(color, offset * 4 + 4) - - // add last segment - if (state.close) { - // ignore coinciding start/end - if (positions[0] === positions[count*2 - 2] && - positions[1] === positions[count*2 - 1]) { - positionData[offset*2 + count*2 + 2] = npos[2] - positionData[offset*2 + count*2 + 3] = npos[3] - offset += count + 2 - state.count -= 1 - } - else { - positionData[offset*2 + count*2 + 2] = npos[0] - positionData[offset*2 + count*2 + 3] = npos[1] - positionData[offset*2 + count*2 + 4] = npos[2] - positionData[offset*2 + count*2 + 5] = npos[3] - offset += count + 3 - } + for (var i$6 = 0; i$6 < count$1 + 1; i$6++) { + colorData.set(c, i$6 * 4) } - // add stub - else { - positionData[offset*2 + count*2 + 2] = npos[count*2 - 2] - positionData[offset*2 + count*2 + 3] = npos[count*2 - 1] - positionData[offset*2 + count*2 + 4] = npos[count*2 - 2] - positionData[offset*2 + count*2 + 5] = npos[count*2 - 1] - offset += count + 3 + } else { + for (var i$7 = 0; i$7 < count$1; i$7++) { + var c$1 = _$normalize_100(colors[i$7], 'uint8') + colorData.set(c$1, i$7 * 4) } - }) + colorData.set(_$normalize_100(colors[0], 'uint8'), count$1 * 4) + } - colorBuffer(colorData) - positionBuffer(__float32_312(positionData)) - positionFractBuffer(__fract32_312(positionData)) + state.colorBuffer({ + usage: 'dynamic', + type: 'uint8', + data: colorData + }) } + }) - return line2d + // remove unmentioned passes + if (options.length < this.passes.length) { + for (var i = options.length; i < this.passes.length; i++) { + var pass = this$1.passes[i] + if (!pass) { continue } + pass.colorBuffer.destroy() + pass.positionBuffer.destroy() + pass.dashTexture.destroy() + } + this.passes.length = options.length } - function destroy () { - lines.length = 0 - colorBuffer.destroy() - offsetBuffer.destroy() - positionBuffer.destroy() - dashTexture.destroy() - } + // remove null items + this.passes = this.passes.filter(Boolean) - return line2d + return this } +Line2D.prototype.destroy = function () { + this.passes.forEach(function (pass) { + pass.colorBuffer.destroy() + pass.positionBuffer.destroy() + pass.dashTexture.destroy() + }) -// return fractional part of float32 array -function __fract32_312 (arr) { - var fract = new Float32Array(arr.length) - fract.set(arr) - for (var i = 0, l = fract.length; i < l; i++) { - fract[i] = arr[i] - fract[i] - } - return fract -} -function __float32_312 (arr) { - if (arr instanceof Float32Array) { return arr } + this.passes.length = 0 - var float = new Float32Array(arr) - float.set(arr) - return float + return this } -var _$colorId_97 = {}; +var _$colorId_98 = {}; /** @module color-id */ 'use strict' -/* removed: var _$clamp_94 = require('clamp') */; +/* removed: var _$clamp_95 = require('clamp') */; -_$colorId_97 = toNumber -_$colorId_97.to = toNumber -_$colorId_97.from = fromNumber +_$colorId_98 = toNumber +_$colorId_98.to = toNumber +_$colorId_98.from = fromNumber function toNumber (rgba, normalized) { if(normalized == null) normalized = true @@ -142986,10 +145594,10 @@ function toNumber (rgba, normalized) { a *= 255 } - r = _$clamp_94(r, 0, 255) & 0xFF - g = _$clamp_94(g, 0, 255) & 0xFF - b = _$clamp_94(b, 0, 255) & 0xFF - a = _$clamp_94(a, 0, 255) & 0xFF + r = _$clamp_95(r, 0, 255) & 0xFF + g = _$clamp_95(g, 0, 255) & 0xFF + b = _$clamp_95(b, 0, 255) & 0xFF + a = _$clamp_95(a, 0, 255) & 0xFF //hi-order shift converts to -1, so we can't use <<24 var n = (r * 0x01000000) + (g << 16) + (b << 8) + (a) @@ -143011,597 +145619,35 @@ function fromNumber (n, normalized) { } 'use strict'; -var _$isIexplorer_248 = typeof navigator !== 'undefined' && +var _$isIexplorer_305 = typeof navigator !== 'undefined' && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); 'use strict' -/* removed: var _$pick_290 = require('pick-by-alias') */; - -var _$parseRect_285 = 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) - } - - // 0, 0, 100, 100 - array-like - if (arg.length && typeof arg[0] === 'number') { - if (arg.length === 2) { - rect = { - width: arg[0], - height: arg[1], - x: 0, - y: 0 - } - } - else { - rect = { - x: arg[0], - y: arg[1], - width: (arg[2] - arg[0]) || 0, - height: (arg[3] - arg[1]) || 0 - } - } - } - else if (arg) { - arg = _$pick_290(arg, { - left: 'x l left Left', - top: 'y t top Top', - width: 'w width', - height: 'h height', - bottom: 'b bottom', - right: 'r 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 -} - -"use strict" - -function __compileSearch_314(funcName, predicate, reversed, extraArgs, 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[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_314(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - __compileSearch_314("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_314("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() -} - -var _$searchBounds_314 = { - ge: __compileBoundsSearch_314(">=", false, "GE"), - gt: __compileBoundsSearch_314(">", false, "GT"), - lt: __compileBoundsSearch_314("<", true, "LT"), - le: __compileBoundsSearch_314("<=", true, "LE"), - eq: __compileBoundsSearch_314("-", true, "EQ", true) -} - -'use strict' - -var _$sortLevels_340 = sortLevels - -var __INSERT_SORT_CUTOFF_340 = 32 - -function sortLevels(data_levels, data_points, data_ids, data_weights, n0) { - if (n0 <= 4*__INSERT_SORT_CUTOFF_340) { - __insertionSort_340(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } -} - -function __insertionSort_340(left, right, data_levels, data_points, data_ids, data_weights) { - for(var i=left+1; i<=right; ++i) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - var j = i - while(j > left) { - var b_level = data_levels[j-1] - var b_x = data_points[2*(j-1)] - if(((b_level - a_level) || (a_x - b_x)) >= 0) { - break - } - data_levels[j] = b_level - data_points[2*j] = b_x - data_points[2*j+1] = data_points[2*j-1] - data_ids[j] = data_ids[j-1] - data_weights[j] = data_weights[j-1] - j -= 1 - } - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight - } -} - -function __swap_340(i, j, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} - -function __move_340(i, j, data_levels, data_points, data_ids, data_weights) { - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] -} - -function __rotate_340(i, j, k, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = data_levels[k] - data_points[2*j] = data_points[2*k] - data_points[2*j+1] = data_points[2*k+1] - data_ids[j] = data_ids[k] - data_weights[j] = data_weights[k] - - data_levels[k] = a_level - data_points[2*k] = a_x - data_points[2*k+1] = a_y - data_ids[k] = a_id - data_weights[k] = a_weight -} - -function __shufflePivot_340( - i, j, - a_level, a_x, a_y, a_id, a_weight, - data_levels, data_points, data_ids, data_weights) { - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} - -function __compare_340(i, j, data_levels, data_points, data_ids) { - return ((data_levels[i] - data_levels[j]) || - (data_points[2*j] - data_points[2*i]) || - (data_ids[i] - data_ids[j])) < 0 -} - -function __comparePivot_340(i, level, x, y, id, data_levels, data_points, data_ids) { - return ((level - data_levels[i]) || - (data_points[2*i] - x) || - (id - data_ids[i])) < 0 -} - -function __quickSort_340(left, right, data_levels, data_points, data_ids, data_weights) { - 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_340(el1, el2, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el2 - el2 = tmp - } - if(__compare_340(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - if(__compare_340(el1, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el3 - el3 = tmp - } - if(__compare_340(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(__compare_340(el1, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el4 - el4 = tmp - } - if(__compare_340(el3, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el3 - el3 = el4 - el4 = tmp - } - if(__compare_340(el2, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el5 - el5 = tmp - } - if(__compare_340(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(__compare_340(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - - var pivot1_level = data_levels[el2] - var pivot1_x = data_points[2*el2] - var pivot1_y = data_points[2*el2+1] - var pivot1_id = data_ids[el2] - var pivot1_weight = data_weights[el2] - - var pivot2_level = data_levels[el4] - var pivot2_x = data_points[2*el4] - var pivot2_y = data_points[2*el4+1] - var pivot2_id = data_ids[el4] - var pivot2_weight = data_weights[el4] - - var ptr0 = el1 - var ptr2 = el3 - var ptr4 = el5 - var ptr5 = index1 - var ptr6 = index3 - var ptr7 = index5 - - var level_x = data_levels[ptr0] - var level_y = data_levels[ptr2] - var level_z = data_levels[ptr4] - data_levels[ptr5] = level_x - data_levels[ptr6] = level_y - data_levels[ptr7] = level_z - - for (var i1 = 0; i1 < 2; ++i1) { - var x = data_points[2*ptr0+i1] - var y = data_points[2*ptr2+i1] - var z = data_points[2*ptr4+i1] - data_points[2*ptr5+i1] = x - data_points[2*ptr6+i1] = y - data_points[2*ptr7+i1] = z - } - - var id_x = data_ids[ptr0] - var id_y = data_ids[ptr2] - var id_z = data_ids[ptr4] - data_ids[ptr5] = id_x - data_ids[ptr6] = id_y - data_ids[ptr7] = id_z - - var weight_x = data_weights[ptr0] - var weight_y = data_weights[ptr2] - var weight_z = data_weights[ptr4] - data_weights[ptr5] = weight_x - data_weights[ptr6] = weight_y - data_weights[ptr7] = weight_z - - __move_340(index2, left, data_levels, data_points, data_ids, data_weights) - __move_340(index4, right, data_levels, data_points, data_ids, data_weights) - for (var k = less; k <= great; ++k) { - if (__comparePivot_340(k, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - if (k !== less) { - __swap_340(k, less, data_levels, data_points, data_ids, data_weights) - } - ++less; - } else { - if (!__comparePivot_340(k, - pivot2_level, pivot2_x, pivot2_y, pivot2_id, - data_levels, data_points, data_ids)) { - while (true) { - if (!__comparePivot_340(great, - pivot2_level, pivot2_x, pivot2_y, pivot2_id, - data_levels, data_points, data_ids)) { - if (--great < k) { - break; - } - continue; - } else { - if (__comparePivot_340(great, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - __rotate_340(k, less, great, data_levels, data_points, data_ids, data_weights) - ++less; - --great; - } else { - __swap_340(k, great, data_levels, data_points, data_ids, data_weights) - --great; - } - break; - } - } - } - } - } - __shufflePivot_340(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) - __shufflePivot_340(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) - if (less - 2 - left <= __INSERT_SORT_CUTOFF_340) { - __insertionSort_340(left, less - 2, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(left, less - 2, data_levels, data_points, data_ids, data_weights) - } - if (right - (great + 2) <= __INSERT_SORT_CUTOFF_340) { - __insertionSort_340(great + 2, right, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(great + 2, right, data_levels, data_points, data_ids, data_weights) - } - if (great - less <= __INSERT_SORT_CUTOFF_340) { - __insertionSort_340(less, great, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(less, great, data_levels, data_points, data_ids, data_weights) - } -} - -'use strict' - -/* removed: var _$sortLevels_340 = require('./lib/sort') */; -/* removed: var _$normalize_48 = require('array-bounds') */; - -var _$snapPoints_341 = snapPoints - -function partition(points, ids, start, end, lox, loy, hix, hiy) { - var mid = start - for(var i=start; i>> 1 - if(n < 1) { - return [] - } - - if (!ids) ids = Array(n) - if (!weights) weights = Array(n) - if (!bounds) bounds = [] - - for(var i=0; i= bounds[2] || bounds[1] >= bounds[3]) { - var b = _$normalize_48(points, 2) - - if(b[0] === b[2]) { - b[2] += 1 - } - if(b[1] === b[3]) { - b[3] += 1 - } - - bounds[0] = b[0] - bounds[1] = b[1] - bounds[2] = b[2] - bounds[3] = b[3] - } - - var lox = bounds[0] - var loy = bounds[1] - var hix = bounds[2] - var hiy = bounds[3] - - //Calculate diameter - var scaleX = 1.0 / (hix - lox) - var scaleY = 1.0 / (hiy - loy) - var diam = Math.max(hix - lox, hiy - loy) - - +/* removed: var _$normalize_100 = require('color-normalize') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$colorId_98 = require('color-id') */; +/* removed: var _$pointCluster_353 = require('point-cluster') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$updateDiff_425 = require('update-diff') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$isIexplorer_305 = require('is-iexplorer') */; +/* removed: var _$toFloat32_415 = require('to-float32'); */; +var __float32_377 = _$toFloat32_415.float32; +var __fract32_377 = _$toFloat32_415.fract32; +/* removed: var _$parseRect_343 = require('parse-rect') */; - var levels = new Int32Array(n) - var ptr = 0 - - function snapRec(x, y, diam, start, end, level) { - var diam_2 = diam * 0.5 - var offset = start + 1 - var count = end - start - weights[ptr] = count - levels[ptr++] = level - for(var i=0; i<2; ++i) { - for(var j=0; j<2; ++j) { - var nx = x+i*diam_2 - var ny = y+j*diam_2 - var nextOffset = partition( - points - , ids - , offset - , end - , nx, ny - , nx+diam_2, ny+diam_2) - if(nextOffset === offset) { - continue - } - if(nextOffset - offset >= Math.max(0.9 * count, 32)) { - var mid = (end + start)>>>1 - snapRec(nx, ny, diam_2, offset, mid, level+1) - offset = mid - } - snapRec(nx, ny, diam_2, offset, nextOffset, level+1) - offset = nextOffset - } - } - } - snapRec(lox, loy, diam, 0, n, 0) - _$sortLevels_340(levels, points, ids, weights, n) - - var lod = [] - var lastLevel = 0 - var prevOffset = n - for(var ptr=n-1; ptr>=0; --ptr) { - points[2*ptr] = (points[2*ptr] - lox) * scaleX - points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY - - var level = levels[ptr] - if(level === lastLevel) { - continue - } - lod.push(new SnapInterval( - diam * Math.pow(0.5, level), - ptr+1, - prevOffset - (ptr+1) - )) - prevOffset = ptr+1 +var _$Scatter_377 = __Scatter_377 - lastLevel = level - } - lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) +function __Scatter_377 (regl, options) { + var this$1 = this; - return lod -} - -'use strict' + if (!(this instanceof __Scatter_377)) { return new __Scatter_377(regl, options) } -/* removed: var _$normalize_99 = require('color-normalize') */; -/* removed: var _$normalize_48 = require('array-bounds') */; -/* removed: var _$colorId_97 = require('color-id') */; -/* removed: var _$snapPoints_341 = require('snap-points-2d') */; -/* removed: var _$objectAssign_281 = require('object-assign') */; -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$searchBounds_314 = require('binary-search-bounds') */; -/* removed: var _$pick_290 = require('pick-by-alias') */; -/* removed: var _$updateDiff_363 = require('update-diff') */; -/* removed: var _$flattenVertexData_141 = require('flatten-vertex-data') */; -/* removed: var _$isIexplorer_248 = require('is-iexplorer') */; -/* removed: var _$toFloat32_353 = require('to-float32'); */; -var __float32_313 = _$toFloat32_353.float32; -var __fract32_313 = _$toFloat32_353.fract32; -/* removed: var _$newArray_50 = require('array-range') */; -/* removed: var _$parseRect_285 = require('parse-rect') */; - -var _$Scatter_313 = __Scatter_313 - - -function __Scatter_313 (regl, options) { if (typeof regl === 'function') { if (!options) { options = {} } options.regl = regl @@ -143612,29 +145658,11 @@ function __Scatter_313 (regl, options) { } if (options && options.length) { options.positions = options } + regl = options.regl // persistent variables - var gl = regl._gl, - drawMarker, drawCircle, - sizeBuffer, positionBuffer, positionFractBuffer, colorBuffer, - paletteTexture, palette = [], paletteIds = {}, - defaults = { - color: 'black', - borderColor: 'transparent', - borderSize: 1, - size: 12, - opacity: 1, - marker: undefined, - viewport: null, - range: null, - pixelSize: null, - offset: 0, - count: 0, - bounds: null, - positions: [], - snap: 1e4 - }, + var gl = regl._gl, paletteTexture, palette = [], paletteIds = {}, // state groups = [], @@ -143643,7 +145671,11 @@ function __Scatter_313 (regl, options) { markerTextures = [null], markerCache = [null] - var maxColors = 4096, maxSize = 100 + var maxColors = 255, maxSize = 100 + + // direct color buffer mode + // IE does not support palette anyways + this.tooManyColors = _$isIexplorer_305 // texture with color palette paletteTexture = regl.texture({ @@ -143658,110 +145690,94 @@ function __Scatter_313 (regl, options) { min: 'nearest' }) - // buffers to reuse - sizeBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - colorBuffer = regl.buffer({ - usage: 'dynamic', - type: 'uint16', - data: null - }) - positionBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - positionFractBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null + _$objectAssign_339(this, { + regl: regl, + gl: gl, + groups: groups, + markerCache: markerCache, + markerTextures: markerTextures, + palette: palette, + paletteIds: paletteIds, + paletteTexture: paletteTexture, + maxColors: maxColors, + maxSize: maxSize, + canvas: gl.canvas }) - // fast-create from existing regl-scatter instance - if (options.clone) { - groups = options.clone.groups.map(function (group) { - group = _$objectAssign_281({}, group) - if (group.markerIds) { - group.markerIds = group.markerIds.map(function (ids) { - // recreate regl elements here - var newIds = ids.slice() - newIds.lod = ids.lod - newIds.snap = ids.snap - newIds.data = ids.data - newIds.id = ids.id - newIds.x = ids.x - newIds.w = ids.w - newIds.elements = regl.elements({ - primitive: 'points', - type: 'uint32', - data: ids.data - }) - return newIds - }) - } - return group - }) - - // create marker textures - options.clone.markers.forEach(function (markers) { - addMarker(markers) - }) - // clone palette texture - updatePalette(options.clone.palette) - updateBuffers({point: true, color: true, size: true}) - } - // full create from options - else { - update(options) - } - + this.update(options) // common shader options var shaderOptions = { uniforms: { pixelRatio: regl.context('pixelRatio'), palette: paletteTexture, - paletteSize: function (ctx, prop) { return [maxColors, paletteTexture.height]; }, + paletteSize: function (ctx, prop) { return [this$1.tooManyColors ? 0 : maxColors, paletteTexture.height]; }, scale: regl.prop('scale'), scaleFract: regl.prop('scaleFract'), translate: regl.prop('translate'), translateFract: regl.prop('translateFract'), opacity: regl.prop('opacity'), - marker: regl.prop('marker'), + marker: regl.prop('markerTexture'), }, attributes: { - position: positionBuffer, - positionFract: positionFractBuffer, + // FIXME: optimize these parts + x: function (ctx, prop) { return prop.xAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 0 + }; }, + y: function (ctx, prop) { return prop.yAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 4 + }; }, + xFract: function (ctx, prop) { return prop.xAttr ? { constant: [0, 0] } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 0 + }; }, + yFract: function (ctx, prop) { return prop.yAttr ? { constant: [0, 0] } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 4 + }; }, size: function (ctx, prop) { return prop.size.length ? { - buffer: sizeBuffer, + buffer: prop.sizeBuffer, stride: 2, offset: 0 - } : {constant: [Math.round(prop.size * 255 / maxSize)]}; }, + } : { + constant: [ Math.round(prop.size * 255 / this$1.maxSize) ] + }; }, borderSize: function (ctx, prop) { return prop.borderSize.length ? { - buffer: sizeBuffer, + buffer: prop.sizeBuffer, stride: 2, offset: 1 - } : {constant: [Math.round(prop.borderSize * 255 / maxSize)]}; }, + } : { + constant: [ Math.round(prop.borderSize * 255 / this$1.maxSize) ] + }; }, colorId: function (ctx, prop) { return prop.color.length ? { - buffer: colorBuffer, - stride: 8, + buffer: prop.colorBuffer, + stride: this$1.tooManyColors ? 8 : 4, offset: 0 - } : {constant: [prop.color]}; }, + } : { + constant: this$1.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [ prop.color ] + }; }, borderColorId: function (ctx, prop) { return prop.borderColor.length ? { - buffer: colorBuffer, - stride: 8, - offset: 4 - } : {constant: [prop.borderColor]}; } + buffer: prop.colorBuffer, + stride: this$1.tooManyColors ? 8 : 4, + offset: this$1.tooManyColors ? 4 : 2 + } : { + constant: this$1.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [ prop.borderColor ] + }; }, + isActive: function (ctx, prop) { return prop.activation === true ? { constant: [1] } : prop.activation ? prop.activation : { constant: [0] }; } }, - blend: { enable: true, color: [0,0,0,1], + + // photoshop blending func: { srcRGB: 'src alpha', dstRGB: 'one minus src alpha', @@ -143779,7 +145795,6 @@ function __Scatter_313 (regl, options) { stencil: {enable: false}, depth: {enable: false}, - elements: regl.prop('elements'), count: regl.prop('count'), offset: regl.prop('offset'), @@ -143787,673 +145802,904 @@ function __Scatter_313 (regl, options) { primitive: 'points' } - // IE11 shader workaround - if (_$isIexplorer_248) { - drawCircle = regl(_$objectAssign_281({}, shaderOptions, { - frag: _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n\n float centerFraction = fragBorderSize == 0. ? 2. : fragSize / (fragSize + fragBorderSize + 1.25);\n\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, 1.);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"]), - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nvoid main() {\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n fragBorderSize = borderSize;\n fragSize = size;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragWidth = 1. / gl_PointSize;\n}\n"]), - uniforms: { - // FIXME: generate attribute color data - color: function (ctx, p) { - var id = p.color.length ? p.color[0] : p.color; - return palette.slice(id * 4, id * 4 + 4).map(function (v) { return v / 255; }) - }, - borderColor: function (ctx, p) { - var id = p.borderColor.length ? p.borderColor[0] : p.borderColor; - return palette.slice(id * 4, id * 4 + 4).map(function (v) { return v / 255; }) - }, - pixelRatio: regl.context('pixelRatio'), - palette: paletteTexture, - paletteSize: function (ctx, prop) { return [maxColors, paletteTexture.height]; }, - scale: regl.prop('scale'), - scaleFract: regl.prop('scaleFract'), - translate: regl.prop('translate'), - translateFract: regl.prop('translateFract'), - opacity: regl.prop('opacity'), - marker: regl.prop('marker') - }, - attributes: { - position: positionBuffer, - positionFract: positionFractBuffer, - size: shaderOptions.attributes.size, - borderSize: shaderOptions.attributes.borderSize - } - })) - } - else { - // draw sdf-marker - var markerOptions = _$objectAssign_281({}, shaderOptions) - markerOptions.frag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n //max-distance alpha\n if (dist < 0.003) discard;\n\n //null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]) - markerOptions.vert = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n\t\tfragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]) - - drawMarker = regl(markerOptions) - - // draw circle - var circleOptions = _$objectAssign_281({}, shaderOptions) - circleOptions.frag = _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif(radius > 1.0 + delta) {\n\t\tdiscard;\n\t\treturn;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]) - circleOptions.vert = _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]) + // draw sdf-marker + var markerOptions = _$objectAssign_339({}, shaderOptions) + markerOptions.frag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]) + markerOptions.vert = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n fragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]) - drawCircle = regl(circleOptions) + try { + this.drawMarker = regl(markerOptions) + } catch (e) { } - // expose API - _$objectAssign_281(scatter2d, { - update: update, - draw: draw, - destroy: destroy, - regl: regl, - gl: gl, - canvas: gl.canvas, - groups: groups, - markers: markerCache, - palette: palette - }) - - - // main update/draw function - function scatter2d (opts) { - // update - if (opts) { - update(opts) - } + // draw circle + var circleOptions = _$objectAssign_339({}, shaderOptions) + circleOptions.frag = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]) + circleOptions.vert = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]) - // destroy - else if (opts === null) { - destroy() - } + // polyfill IE + if (_$isIexplorer_305) { circleOptions.frag = circleOptions.frag.replace('smoothstep', 'smoothStep') } - draw() - } + this.drawCircle = regl(circleOptions) +} - // draw all groups or only indicated ones - function draw (opts) { - if (typeof opts === 'number') { return drawGroup(opts) } +// single pass defaults +__Scatter_377.defaults = { + color: 'black', + borderColor: 'transparent', + borderSize: 0, + size: 12, + opacity: 1, + marker: undefined, + viewport: null, + range: null, + pixelSize: null, + count: 0, + offset: 0, + bounds: null, + positions: [], + snap: 1e4 +} - // highlight elements - if (Array.isArray(opts)) { - opts.forEach(function (els, i) { - if (els == null) { return } - if (els.length) { return drawGroup(els, i) } - return drawGroup(els) - }) - return - } - // make options a batch - groups.forEach(function (group, i) { - if (!group) { return } +// update & redraw +__Scatter_377.prototype.render = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - drawGroup(i) - }) + if (args.length) { + (ref = this).update.apply(ref, args) } - // draw specific scatter group - function drawGroup (group, id) { - if (typeof group === 'number') { group = groups[group] } + this.draw() - var els + return this + var ref; +} - if (Array.isArray(group)) { - els = group - group = groups[id] - } - if (!(group && group.count && group.opacity)) { return } +// draw all groups or only indicated ones +__Scatter_377.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - // if subset of elements to redraw passed - form a whitelist - var whitelist - if (els) { - whitelist = Array(group.count); + var ref = this; + var groups = ref.groups; - for (var i = 0; i < els.length; i++) { - whitelist[els[i]] = true - } + // if directly array passed - treat as passes + if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) { + args = args[0] + } + + if (args.length) { + for (var i = 0; i < args.length; i++) { + this$1.drawItem(i, args[i]) } + } + // draw all passes + else { + groups.forEach(function (group, i) { + this$1.drawItem(i) + }) + } - // draw circles - // FIXME remove regl._refresh hooks once regl issue #427 is fixed - if (group.markerIds[0]) { - regl._refresh() + return this +} - var opts = getMarkerDrawOptions(group.markerIds[0], group, whitelist) +// draw specific scatter group +__Scatter_377.prototype.drawItem = function (id, els) { + var this$1 = this; + + var ref = this; + var groups = ref.groups; + var group = groups[id] + + // debug viewport + // let { viewport } = group + // gl.enable(gl.SCISSOR_TEST); + // gl.scissor(viewport.x, viewport.y, viewport.width, viewport.height); + // gl.clearColor(0, 0, 0, .5); + // gl.clear(gl.COLOR_BUFFER_BIT); + + if (typeof els === 'number') { + id = els + group = groups[els] + els = null + } - drawCircle(opts) - } + if (!(group && group.count && group.opacity)) { return } - // draw all other available markers - var batch = [] - for (var i$1 = 1; i$1 < group.markerIds.length; i$1++) { - var ids = group.markerIds[i$1] + // draw circles + if (group.activation[0]) { + // TODO: optimize this performance by making groups and regl.this props + this.drawCircle(this.getMarkerDrawOptions(0, group, els)) + } - if (!ids || !ids.length) { continue } + // draw all other available markers + var batch = [] - [].push.apply(batch, getMarkerDrawOptions(ids, group, whitelist)) - } + for (var i = 1; i < group.activation.length; i++) { + if (!group.activation[i] || (group.activation[i] !== true && !group.activation[i].data.length)) { continue } - if (batch.length) { - regl._refresh() - drawMarker(batch) - } + batch.push.apply(batch, this$1.getMarkerDrawOptions(i, group, els)) } - // get options for the marker ids - function getMarkerDrawOptions(ids, group, whitelist) { - var range = group.range; - var offset = group.offset; - // unsnapped options - if (!ids.snap) { - var elements = whitelist ? filter(ids.data, whitelist) : ids.elements; + if (batch.length) { + this.drawMarker(batch) + } +} - return [_$objectAssign_281({}, group, { +// get options for the marker ids +__Scatter_377.prototype.getMarkerDrawOptions = function(markerId, group, elements) { + var this$1 = this; + + var range = group.range; + var tree = group.tree; + var viewport = group.viewport; + var activation = group.activation; + var selectionBuffer = group.selectionBuffer; + var count = group.count; + var ref = this; + var regl = ref.regl; + + // direct points + if (!tree) { + // if elements array - draw unclustered points + if (elements) { + return [_$objectAssign_339({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + count: elements.length, elements: elements, - offset: 0, - count: whitelist ? elements.length : ids.length, - marker: markerTextures[ids.id] + offset: 0 })] } - // scales batch - var batch = [] - var lod = ids.lod; - var x = ids.x; - var id = ids.id; - - var pixelSize = Math.min((range[2] - range[0]) / group.viewport.width, (range[3] - range[1]) / group.viewport.height) + return [ _$objectAssign_339({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + offset: 0 + }) ] + } - for (var scaleNum = lod.length; scaleNum--;) { - var level = lod[scaleNum] + // clustered points + var batch = [] + + var lod = tree.range(range, { lod: true, px: [ + (range[2] - range[0]) / viewport.width, + (range[3] - range[1]) / viewport.height + ]}) + + // enable elements by using selection buffer + if (elements) { + var markerActivation = activation[markerId] + var mask = markerActivation.data + var data = new Uint8Array(count) + for (var i = 0; i < elements.length; i++) { + var id = elements[i] + data[id] = mask ? mask[id] : 1 + } + selectionBuffer.subdata(data) + } - // FIXME: use minSize-adaptive coeff here, if makes sense, mb we need dist tho - if (level.pixelSize && level.pixelSize < pixelSize && scaleNum > 1) { - continue - } + for (var l = lod.length; l--;) { + var ref$1 = lod[l]; + var from = ref$1[0]; + var to = ref$1[1]; - var intervalStart = level.offset - var intervalEnd = level.count + intervalStart + batch.push(_$objectAssign_339({}, group, { + markerTexture: this$1.markerTextures[markerId], + activation: elements ? selectionBuffer : activation[markerId], + offset: from, + count: to - from, - var startOffset = _$searchBounds_314.ge(x, range[0], intervalStart, intervalEnd - 1) - var endOffset = _$searchBounds_314.lt(x, range[2], startOffset, intervalEnd - 1) + 1 + // send tree elements + elements: group.elements + })) + } - if (endOffset <= startOffset) { continue } + return batch +} - // whitelisted level requires subelements from the range - if (whitelist) { - var elements$1 = filter(ids.data.subarray(startOffset, endOffset), whitelist) +// update groups options +__Scatter_377.prototype.update = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { return } + + // passes are as single array + if (args.length === 1 && Array.isArray(args[0])) { args = args[0] } + + var ref = this; + var groups = ref.groups; + var gl = ref.gl; + var regl = ref.regl; + var maxSize = ref.maxSize; + var maxColors = ref.maxColors; + var palette = ref.palette; + + this.groups = groups = args.map(function (options, i) { + var group = groups[i] + + if (options === undefined) { return group } + + if (options === null) { options = { positions: null } } + else if (typeof options === 'function') { options = { ondraw: options } } + else if (typeof options[0] === 'number') { options = { positions: options } } + + // copy options to avoid mutation & handle aliases + options = _$pick_349(options, { + positions: 'positions data points', + snap: 'snap cluster lod tree', + size: 'sizes size radius', + borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline', + color: 'colors color fill fill-color fillColor', + borderColor: 'borderColors borderColor stroke stroke-color strokeColor', + marker: 'markers marker shape', + range: 'range dataBox databox', + viewport: 'viewport viewPort viewBox viewbox', + opacity: 'opacity alpha transparency', + bounds: 'bound bounds boundaries limits' + }) - batch.push(_$objectAssign_281({}, group, { - elements: elements$1, - marker: markerTextures[id], - offset: 0, - count: elements$1.length - })) - } - else { - batch.push(_$objectAssign_281({}, group, { - elements: ids.elements, - marker: markerTextures[id], - offset: startOffset, - count: endOffset - startOffset - })) + if (options.positions === null) { options.positions = [] } + + if (!group) { + groups[i] = group = { + id: i, + scale: null, + translate: null, + scaleFract: null, + translateFract: null, + + // buffers for active markers + activation: [], + + // buffer for filtered markers + selectionBuffer: regl.buffer({ + usage: 'stream', + type: 'uint8' + }), + + // buffers with data: it is faster to switch them per-pass + // than provide one congregate buffer + sizeBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8' + }), + colorBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8' + }), + positionBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float' + }), + positionFractBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float' + }) } + options = _$objectAssign_339({}, __Scatter_377.defaults, options) } - function filter(offsets, whitelist) { - var subEls = [] - for (var i = 0, l = offsets.length; i < l; i++) { - var el = offsets[i] - var id = el - offset - if (whitelist[id]) { - subEls.push(el) - } - } - return subEls + // force update triggers + if (options.positions && !('marker' in options)) { + options.marker = group.marker + delete group.marker } - return batch - } - - // update groups options - function update (options) { - if (!options) { return } - - // direct points argument - if (options.length != null) { - if (typeof options[0] === 'number') { options = [{positions: options}] } + // updating markers cause recalculating snapping + if (options.marker && !('positions' in options)) { + options.positions = group.positions + delete group.positions } - // make options a batch - else if (!Array.isArray(options)) { options = [options] } // global count of points - var pointCount = 0, sizeCount = 0, colorCount = 0 - - scatter2d.groups = groups = options.map(function (options, i) { - var group = groups[i] - - if (options === undefined) { return group } - - if (options === null) { options = { positions: null } } - else if (typeof options === 'function') { options = {after: options} } - else if (typeof options[0] === 'number') { options = {positions: options} } - - // copy options to avoid mutation & handle aliases - options = _$pick_290(options, { - positions: 'positions data points', - snap: 'snap cluster', - size: 'sizes size radius', - borderSize: 'borderSizes borderSize stroke-width strokeWidth outline', - color: 'colors color fill fill-color fillColor', - borderColor: 'borderColors borderColor stroke stroke-color strokeColor', - palette: 'palette swatch', - marker: 'markers marker shape', - range: 'range dataBox', - viewport: 'viewport viewBox', - opacity: 'opacity alpha' - }) + var hasSize = 0, hasColor = 0 + + _$updateDiff_425(group, options, [{ + snap: true, + size: function (s, group) { + if (s == null) { s = __Scatter_377.defaults.size } + hasSize += s && s.length ? 1 : 0 + return s + }, + borderSize: function (s, group) { + if (s == null) { s = __Scatter_377.defaults.borderSize } + hasSize += s && s.length ? 1 : 0 + return s + }, + opacity: parseFloat, + + // add colors to palette, save references + color: function (c, group) { + if (c == null) { c = __Scatter_377.defaults.color } + c = this$1.updateColor(c) + hasColor++ + return c + }, + borderColor: function (c, group) { + if (c == null) { c = __Scatter_377.defaults.borderColor } + c = this$1.updateColor(c) + hasColor++ + return c + }, - if (options.positions === null) { options.positions = [] } + bounds: function (bounds, group, options) { + if (!('range' in options)) { options.range = null } + return bounds + }, - if (!group) { - groups[i] = group = { - id: i, - scale: null, - translate: null, - scaleFract: null, - translateFract: null, + positions: function (positions, group, options) { + var snap = options.snap; + var positionBuffer = group.positionBuffer; + var positionFractBuffer = group.positionFractBuffer; + var selectionBuffer = group.selectionBuffer; + + // separate buffers for x/y coordinates + if (positions.x || positions.y) { + if (positions.x.length) { + group.xAttr = { + buffer: regl.buffer(positions.x), + offset: 0, + stride: 4, + count: positions.x.length + } + } + else { + group.xAttr = { + buffer: positions.x.buffer, + offset: positions.x.offset * 4 || 0, + stride: (positions.x.stride || 1) * 4, + count: positions.x.count + } + } + if (positions.y.length) { + group.yAttr = { + buffer: regl.buffer(positions.y), + offset: 0, + stride: 4, + count: positions.y.length + } + } + else { + group.yAttr = { + buffer: positions.y.buffer, + offset: positions.y.offset * 4 || 0, + stride: (positions.y.stride || 1) * 4, + count: positions.y.count + } + } + group.count = Math.max(group.xAttr.count, group.yAttr.count) - // list of ids corresponding to markers, with inner props - markerIds: [] + return positions } - options = _$objectAssign_281({}, defaults, options) - } - - // force update triggers - if (options.positions && !('marker' in options)) { - options.marker = group.marker - delete group.marker - } - // updating markers cause recalculating snapping - if (options.marker && !('positions' in options)) { - options.positions = group.positions - delete group.positions - } + positions = _$flattenVertexData_198(positions, 'float64') - _$updateDiff_363(group, options, [{ - snap: true, - size: function (s) { - sizeCount += s.length ? 1 : 0 - return s - }, - borderSize: function (s) { - sizeCount += s.length ? 1 : 0 - return s - }, - opacity: parseFloat, + var count = group.count = Math.floor(positions.length / 2) + var bounds = group.bounds = count ? _$normalize_49(positions, 2) : null - // add colors to palette, save references - color: function (c) { - c = updateColor(c) - colorCount++ - return c - }, - borderColor: function (c) { - c = updateColor(c) - colorCount++ - return c - }, + // if range is not provided updated - recalc it + if (!options.range && !group.range) { + delete group.range + options.range = bounds + } - positions: function (positions, group, options) { - positions = _$flattenVertexData_141(positions, 'float64') + // reset marker + if (!options.marker && !group.marker) { + delete group.marker; + options.marker = null; + } - var count = group.count = Math.floor(positions.length / 2) - var bounds = group.bounds = count ? _$normalize_48(positions, 2) : null + // build cluster tree if required + if (snap && (snap === true || count > snap)) { + group.tree = _$pointCluster_353(positions, { bounds: bounds }) + } + // existing tree instance + else if (snap && snap.length) { + group.tree = snap + } - // if range is not provided updated - recalc it - if (!options.range && !group.range) { - delete group.range - options.range = bounds + if (group.tree) { + var opts = { + primitive: 'points', + usage: 'static', + data: group.tree, + type: 'uint32' } + if (group.elements) { group.elements(opts) } + else { group.elements = regl.elements(opts) } + } - group.offset = pointCount - pointCount += count + // update position buffers + positionBuffer({ + data: __float32_377(positions), + usage: 'dynamic' + }) + positionFractBuffer({ + data: __fract32_377(positions), + usage: 'dynamic' + }) - // reset marker - if (!options.marker && !group.marker) { - delete group.marker; - options.marker = null; - } + // expand selectionBuffer + selectionBuffer({ + data: new Uint8Array(count), + type: 'uint8', + usage: 'stream' + }) - return positions + return positions + } + }, { + // create marker ids corresponding to known marker textures + marker: function (markers, group, options) { + var activation = group.activation; + + // reset marker elements + activation.forEach(function (buffer) { return buffer && buffer.destroy && buffer.destroy(); }) + activation.length = 0 + + // single sdf marker + if (!markers || typeof markers[0] === 'number') { + var id = this$1.addMarker(markers) + activation[id] = true } - }, { - // create marker ids corresponding to known marker textures - marker: function (markers, group, options) { - // reset marker elements - group.markerIds.length = 0 - // single sdf marker - if (!markers || typeof markers[0] === 'number') { - var id = addMarker(markers) + // per-point markers use mask buffers to enable markers in vert shader + else { + var markerMasks = [] - var elements = _$newArray_50(group.count) + for (var i = 0, l = Math.min(markers.length, group.count); i < l; i++) { + var id$1 = this$1.addMarker(markers[i]) - group.markerIds[id] = elements - } - // per-point markers - else { - for (var i = 0, l = markers.length; i < l; i++) { - var id$1 = addMarker(markers[i]) + if (!markerMasks[id$1]) { markerMasks[id$1] = new Uint8Array(group.count) } - if (!group.markerIds[id$1]) { group.markerIds[id$1] = [] } - group.markerIds[id$1].push(i) - } + // enable marker by default + markerMasks[id$1][i] = 1 } - return markers - } - }, { - // recalculate per-marker snapping - // first, it is faster to snap 100 points 100 times than 10000 points once (practically, not theoretically) - // second, it is easier to subset render per-marker than per-generic set - positions: function (positions, group) { - var markerIds = group.markerIds; - var snap = group.snap; - var bounds = group.bounds; - var offset = group.offset; - - for (var i = 0; i < markerIds.length; i++) { - var ids = markerIds[i] - if (!ids || !ids.length) { continue } - - var l = ids.length, els = (void 0) - - ids.id = i; - - if (snap && (snap === true || l > snap)) { - ids.snap = true - var x = ids.x = Array(l) - var w = ids.w = Array(l) - var markerPoints = (void 0) - - // multimarker snapping is computationally more intense - if (markerIds.length > 1) { - markerPoints = Array(l * 2) - - for (var i$1 = 0; i$1 < l; i$1++) { - var id = ids[i$1] - markerPoints[i$1 * 2] = positions[id * 2] - markerPoints[i$1 * 2 + 1] = positions[id * 2 + 1] - } - } - else { - markerPoints = new Float64Array(positions.length) - markerPoints.set(positions) - } - - // shuffled_id: real_id - var i2id = new Uint32Array(l) - - ids.lod = _$snapPoints_341(markerPoints, i2id, w, bounds) - - els = new Uint32Array(l) - for (var i$2 = 0; i$2 < l; i$2++) { - var id$1 = i2id[i$2], iid = ids[id$1] - els[i$2] = iid + offset - x[i$2] = positions[iid * 2] - } + for (var id$2 = 0; id$2 < markerMasks.length; id$2++) { + if (!markerMasks[id$2]) { continue } + + var opts = { + data: markerMasks[id$2], + type: 'uint8', + usage: 'static' + } + if (!activation[id$2]) { + activation[id$2] = regl.buffer(opts) } else { - els = new Uint32Array(l) - for (var i$3 = 0; i$3 < l; i$3++) { - els[i$3] = ids[i$3] + offset - } + activation[id$2](opts) } - ids.data = els; - ids.elements = regl.elements({ - primitive: 'points', - type: 'uint32', - data: els - }) + activation[id$2].data = markerMasks[id$2] } - }, - - range: function (range, group, options) { - var bounds = group.bounds - - if (!bounds) { return } - if (!range) { range = bounds } - - group.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] - group.translate = [-range[0], -range[1]] - - group.scaleFract = __fract32_313(group.scale) - group.translateFract = __fract32_313(group.translate) - - return range - }, - - viewport: function (vp) { - return _$parseRect_285(vp || [ - gl.drawingBufferWidth, - gl.drawingBufferHeight - ]) } - }]) - - return group - }) - updateBuffers({ - point: pointCount, - size: sizeCount, - color: colorCount - }) - } + return markers + }, - // update buffers data based on existing groups - function updateBuffers(ref) { - var point = ref.point; - var size = ref.size; - var color = ref.color; + range: function (range, group, options) { + var bounds = group.bounds - // put point/color data into buffers, if updated any of them - var len = groups.reduce(function (acc, group, i) { - return acc + (group ? group.count : 0) - }, 0) + // FIXME: why do we need this? + if (!bounds) { return } + if (!range) { range = bounds } - if (point) { - var positionData = new Float32Array(len * 2) - var positionFractData = new Float32Array(len * 2) + group.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] + group.translate = [-range[0], -range[1]] - groups.forEach(function (group, i) { - if (!group) { return } - var positions = group.positions; - var count = group.count; - var offset = group.offset; - if (!count) { return } - positionData.set(__float32_313(positions), offset * 2) - positionFractData.set(__fract32_313(positions), offset * 2) - }) + group.scaleFract = __fract32_377(group.scale) + group.translateFract = __fract32_377(group.translate) - positionBuffer(positionData) - positionFractBuffer(positionFractData) - } + return range + }, - if (size) { - var sizeData = new Uint8Array(len * 2) + viewport: function (vp) { + var rect = _$parseRect_343(vp || [ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]) - groups.forEach(function (group, i) { - if (!group) { return } - var count = group.count; - var offset = group.offset; - var size = group.size; - var borderSize = group.borderSize; - if (!count) { return } + // normalize viewport to the canvas coordinates + // rect.y = gl.drawingBufferHeight - rect.height - rect.y - if (size.length || borderSize.length) { - var sizes = new Uint8Array(count*2) - for (var i$1 = 0; i$1 < count; i$1++) { - // we downscale size to allow for fractions - sizes[i$1*2] = Math.round((size[i$1] == null ? size : size[i$1]) * 255 / maxSize) - sizes[i$1*2 + 1] = Math.round((borderSize[i$1] == null ? borderSize : borderSize[i$1]) * 255 / maxSize) - } - sizeData.set(sizes, offset * 2) + return rect + } + }]) + + // update size buffer, if needed + if (hasSize) { + var count = group.count; + var size = group.size; + var borderSize = group.borderSize; + var sizeBuffer = group.sizeBuffer; + + var sizes = new Uint8Array(count*2) + if (size.length || borderSize.length) { + for (var i$1 = 0; i$1 < count; i$1++) { + // we downscale size to allow for fractions + sizes[i$1*2] = Math.round((size[i$1] == null ? size : size[i$1]) * 255 / maxSize) + sizes[i$1*2 + 1] = Math.round((borderSize[i$1] == null ? borderSize : borderSize[i$1]) * 255 / maxSize) } + } + sizeBuffer({ + data: sizes, + usage: 'dynamic' }) - sizeBuffer(sizeData) } - if (color) { - var colorData = new Uint16Array(len * 4) + // update color buffer if needed + if (hasColor) { + var count$1 = group.count; + var color = group.color; + var borderColor = group.borderColor; + var colorBuffer = group.colorBuffer; + var colors - groups.forEach(function (group, i) { - if (!group) { return } - var count = group.count; - var offset = group.offset; - var color = group.color; - var borderColor = group.borderColor; - if (!count) { return } + // if too many colors - put colors to buffer directly + if (this$1.tooManyColors) { + if (color.length || borderColor.length) { + colors = new Uint8Array(count$1 * 8) + for (var i$2 = 0; i$2 < count$1; i$2++) { + var colorId = color[i$2] + colors[i$2*8] = palette[colorId*4] + colors[i$2*8 + 1] = palette[colorId*4 + 1] + colors[i$2*8 + 2] = palette[colorId*4 + 2] + colors[i$2*8 + 3] = palette[colorId*4 + 3] + + var borderColorId = borderColor[i$2] + colors[i$2*8 + 4] = palette[borderColorId*4] + colors[i$2*8 + 5] = palette[borderColorId*4 + 1] + colors[i$2*8 + 6] = palette[borderColorId*4 + 2] + colors[i$2*8 + 7] = palette[borderColorId*4 + 3] + } + } + } + // if limited amount of colors - keep palette color picking + // that saves significant memory + else { if (color.length || borderColor.length) { - var colorIds = new Uint16Array(count * 4) - for (var i$1 = 0; i$1 < count; i$1++) { - if (color[i$1] != null) { - colorIds[i$1*4] = color[i$1] % maxColors - colorIds[i$1*4 + 1] = Math.floor(color[i$1] / maxColors) + // we need slight data increase by 2 due to vec4 borderId in shader + colors = new Uint8Array(count$1 * 4 + 2) + for (var i$3 = 0; i$3 < count$1; i$3++) { + // put color coords in palette texture + if (color[i$3] != null) { + colors[i$3*4] = color[i$3] % maxColors + colors[i$3*4 + 1] = Math.floor(color[i$3] / maxColors) } - if (borderColor[i$1] != null) { - colorIds[i$1*4 + 2] = borderColor[i$1] % maxColors - colorIds[i$1*4 + 3] = Math.floor(borderColor[i$1] / maxColors) + if (borderColor[i$3] != null) { + colors[i$3*4 + 2] = borderColor[i$3] % maxColors + colors[i$3*4 + 3] = Math.floor(borderColor[i$3] / maxColors) } } - - colorData.set(colorIds, offset * 4) } + } + + colorBuffer({ + data: colors, + type: 'uint8', + usage: 'dynamic' }) + } + return group + }) +} - colorBuffer(colorData) + +// get (and create) marker texture id +__Scatter_377.prototype.addMarker = function (sdf) { + var ref = this; + var markerTextures = ref.markerTextures; + var regl = ref.regl; + var markerCache = ref.markerCache; + + var pos = sdf == null ? 0 : markerCache.indexOf(sdf) + + if (pos >= 0) { return pos } + + // convert sdf to 0..255 range + var distArr + if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { + distArr = sdf + } + else { + distArr = new Uint8Array(sdf.length) + for (var i = 0, l = sdf.length; i < l; i++) { + distArr[i] = sdf[i] * 255 } } - // get (and create) marker texture id - function addMarker (sdf) { - var pos = sdf == null ? 0 : markerCache.indexOf(sdf) + var radius = Math.floor(Math.sqrt(distArr.length)) + + pos = markerTextures.length + + markerCache.push(sdf) + markerTextures.push(regl.texture({ + channels: 1, + data: distArr, + radius: radius, + mag: 'linear', + min: 'linear' + })) + + return pos +} + +// register color to palette, return it's index or list of indexes +__Scatter_377.prototype.updateColor = function (colors) { + var ref = this; + var paletteIds = ref.paletteIds; + var palette = ref.palette; + var maxColors = ref.maxColors; + + if (!Array.isArray(colors)) { + colors = [colors] + } + + var idx = [] - if (pos >= 0) { return pos } + // if color groups - flatten them + if (typeof colors[0] === 'number') { + var grouped = [] - // convert sdf to 0..255 range - var distArr - if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { - distArr = sdf + if (Array.isArray(colors)) { + for (var i = 0; i < colors.length; i+=4) { + grouped.push(colors.slice(i, i+4)) + } } else { - distArr = new Uint8Array(sdf.length) - for (var i = 0, l = sdf.length; i < l; i++) { - distArr[i] = sdf[i] * 255 + for (var i$1 = 0; i$1 < colors.length; i$1+=4) { + grouped.push(colors.subarray(i$1, i$1+4)) } } - var radius = Math.floor(Math.sqrt(distArr.length)) + colors = grouped + } - pos = markerTextures.length + for (var i$2 = 0; i$2 < colors.length; i$2++) { + var color = colors[i$2] - markerCache.push(sdf) - markerTextures.push(regl.texture({ - channels: 1, - data: distArr, - radius: radius, - mag: 'linear', - min: 'linear' - })) + color = _$normalize_100(color, 'uint8') - return pos - } + var id = _$colorId_98(color, false) - // register color to palette, return it's index or list of indexes - function updateColor (colors) { - if (!Array.isArray(colors)) { - colors = [colors] + // if new color - save it + if (paletteIds[id] == null) { + var pos = palette.length + paletteIds[id] = Math.floor(pos / 4) + palette[pos] = color[0] + palette[pos+1] = color[1] + palette[pos+2] = color[2] + palette[pos+3] = color[3] } - var idx = [] + idx[i$2] = paletteIds[id] + } + + // detect if too many colors in palette + if (!this.tooManyColors && palette.length > maxColors * maxColors * 4) { this.tooManyColors = true } - for (var i = 0; i < colors.length; i++) { - var color = colors[i] + // limit max color + this.updatePalette(palette) - // idx colors directly - if (typeof color === 'number') { - idx[i] = color - continue - } + // keep static index for single-color property + return idx.length === 1 ? idx[0] : idx +} - color = _$normalize_99(color, 'uint8') +__Scatter_377.prototype.updatePalette = function (palette) { + if (this.tooManyColors) { return } - var id = _$colorId_97(color, false) + var ref = this; + var maxColors = ref.maxColors; + var paletteTexture = ref.paletteTexture; - // if new color - save it - if (paletteIds[id] == null) { - var pos = palette.length - paletteIds[id] = Math.floor(pos / 4) - palette[pos] = color[0] - palette[pos+1] = color[1] - palette[pos+2] = color[2] - palette[pos+3] = color[3] - } + var requiredHeight = Math.ceil(palette.length * .25 / maxColors) - idx[i] = paletteIds[id] + // pad data + if (requiredHeight > 1) { + palette = palette.slice() + for (var i = (palette.length * .25) % maxColors; i < requiredHeight * maxColors; i++) { + palette.push(0, 0, 0, 0) } + } - // limit max color - updatePalette(palette) - - // keep static index for single-color property - return idx.length === 1 ? idx[0] : idx + // ensure height + if (paletteTexture.height < requiredHeight) { + paletteTexture.resize(maxColors, requiredHeight) } - function updatePalette(palette) { - var requiredHeight = Math.ceil(palette.length * .25 / maxColors) + // update full data + paletteTexture.subimage({ + width: Math.min(palette.length * .25, maxColors), + height: requiredHeight, + data: palette + }, 0, 0) +} - // pad data - if (requiredHeight > 1) { - palette = palette.slice() - for (var i = (palette.length * .25) % maxColors; i < requiredHeight * maxColors; i++) { - palette.push(0, 0, 0, 0) - } - } +// remove unused stuff +__Scatter_377.prototype.destroy = function () { + this.groups.forEach(function (group) { + group.sizeBuffer.destroy() + group.positionBuffer.destroy() + group.positionFractBuffer.destroy() + group.colorBuffer.destroy() + group.activation.forEach(function (b) { return b && b.destroy && b.destroy(); }) + group.selectionBuffer.destroy() + + if (group.elements) { group.elements.destroy() } + }) + this.groups.length = 0 - // ensure height - if (paletteTexture.height < requiredHeight) { - paletteTexture.resize(maxColors, requiredHeight) - } + this.paletteTexture.destroy() - // update full data - paletteTexture.subimage({ - width: Math.min(palette.length * .25, maxColors), - height: requiredHeight, - data: palette - }, 0, 0) - } + this.markerTextures.forEach(function (txt) { return txt && txt.destroy && txt.destroy(); }) - // remove unused stuff - function destroy () { - groups.length = 0 + return this +} +'use strict' - sizeBuffer.destroy() - positionBuffer.destroy() - positionFractBuffer.destroy() - colorBuffer.destroy() - paletteTexture.destroy() - } +/* removed: var _$Scatter_377 = require('./scatter') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; + +var _$reglScatter2d_376 = function (regl, options) { + var scatter = new _$Scatter_377(regl, options) + + var render = scatter.render.bind(scatter) + + // expose API + _$objectAssign_339(render, { + render: render, + update: scatter.update.bind(scatter), + draw: scatter.draw.bind(scatter), + destroy: scatter.destroy.bind(scatter), + regl: scatter.regl, + gl: scatter.gl, + canvas: scatter.gl.canvas, + groups: scatter.groups, + markers: scatter.markerCache, + palette: scatter.palette + }) - return scatter2d + return render } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var SYMBOL_SIZE = 20; + +var _$constants_975 = { + TOO_MANY_POINTS: 1e5, + + SYMBOL_SDF_SIZE: 200, + SYMBOL_SIZE: SYMBOL_SIZE, + SYMBOL_STROKE: SYMBOL_SIZE / 20, + + DOT_RE: /-dot/, + OPEN_RE: /-open/, + + DASHES: { + solid: [1], + dot: [1, 1], + dash: [4, 1], + longdash: [8, 1], + dashdot: [4, 1, 1, 1], + longdashdot: [8, 1, 1, 1] + } +}; + +var _$attributes_974 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; + +var __extendFlat_974 = _$extend_590.extendFlat; +var __overrideAll_974 = _$edit_types_632.overrideAll; +var __DASHES_974 = _$constants_975.DASHES; + +var __scatterLineAttrs_974 = _$attributes_927.line; +var __scatterMarkerAttrs_974 = _$attributes_927.marker; +var __scatterMarkerLineAttrs_974 = __scatterMarkerAttrs_974.line; + +var __attrs_974 = _$attributes_974 = __overrideAll_974({ + x: _$attributes_927.x, + x0: _$attributes_927.x0, + dx: _$attributes_927.dx, + y: _$attributes_927.y, + y0: _$attributes_927.y0, + dy: _$attributes_927.dy, + + text: __extendFlat_974({}, _$attributes_927.text, { + description: [ + 'Sets text elements associated with each (x,y) pair to appear on hover.', + 'If a single string, the same string appears over', + 'all the data points.', + 'If an array of string, the items are mapped in order to the', + 'this trace\'s (x,y) coordinates.' + ].join(' ') + }), + mode: { + valType: 'flaglist', + flags: ['lines', 'markers'], + extras: ['none'], + role: 'info', + description: [ + 'Determines the drawing mode for this scatter trace.' + ].join(' ') + }, + line: { + color: __scatterLineAttrs_974.color, + width: __scatterLineAttrs_974.width, + dash: { + valType: 'enumerated', + values: Object.keys(__DASHES_974), + dflt: 'solid', + role: 'style', + description: 'Sets the style of the lines.' + } + }, + marker: __extendFlat_974({}, _$makeColorScaleAttributes_481('marker'), { + symbol: __scatterMarkerAttrs_974.symbol, + size: __scatterMarkerAttrs_974.size, + sizeref: __scatterMarkerAttrs_974.sizeref, + sizemin: __scatterMarkerAttrs_974.sizemin, + sizemode: __scatterMarkerAttrs_974.sizemode, + opacity: __scatterMarkerAttrs_974.opacity, + showscale: __scatterMarkerAttrs_974.showscale, + colorbar: __scatterMarkerAttrs_974.colorbar, + line: __extendFlat_974({}, _$makeColorScaleAttributes_481('marker.line'), { + width: __scatterMarkerLineAttrs_974.width + }) + }), + connectgaps: _$attributes_927.connectgaps, + fill: _$attributes_927.fill, + fillcolor: _$attributes_927.fillcolor, + + hoveron: _$attributes_927.hoveron, + + selected: { + marker: _$attributes_927.selected.marker + }, + unselected: { + marker: _$attributes_927.unselected.marker + }, + + opacity: _$attributes_644.opacity + +}, 'calc', 'nested'); + +__attrs_974.x.editType = __attrs_974.y.editType = __attrs_974.x0.editType = __attrs_974.y0.editType = 'calc+clearAxisTypes'; + 'use strict' -/* removed: var _$clamp_94 = require('clamp') */; +/* removed: var _$clamp_95 = require('clamp') */; -var _$calcSDF_73 = calcSDF +var _$calcSDF_74 = calcSDF var INF = 1e20; @@ -144534,7 +146780,7 @@ function calcSDF(src, options) { var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h) for (i = 0, l = w*h; i < l; i++) { - dist[i] = _$clamp_94(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1) + dist[i] = _$clamp_95(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1) } return dist @@ -144587,7 +146833,7 @@ function edt1d(f, d, v, z, n) { } -var _$absolutize_43 = absolutize +var _$absolutize_44 = absolutize /** * redefine `path` with absolute coordinates @@ -144656,9 +146902,9 @@ function absolutize(path){ var π = Math.PI -var _120 = __radians_279(120) +var _120 = __radians_337(120) -var _$normalize_279 = __normalize_279 +var _$normalize_337 = __normalize_337 /** * describe `path` in terms of cubic bézier @@ -144668,7 +146914,7 @@ var _$normalize_279 = __normalize_279 * @return {Array} */ -function __normalize_279(path){ +function __normalize_337(path){ // init state var prev var result = [] @@ -144690,7 +146936,7 @@ function __normalize_279(path){ startY = seg[2] break case 'A': - seg = arc(x, y,seg[1],seg[2],__radians_279(seg[3]),seg[4],seg[5],seg[6],seg[7]) + seg = arc(x, y,seg[1],seg[2],__radians_337(seg[3]),seg[4],seg[5],seg[6],seg[7]) // split multi part seg.unshift('C') if (seg.length > 7) { @@ -144777,10 +147023,10 @@ function quadratic(x1, y1, cx, cy, x2, y2){ function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { if (!recursive) { - var xy = __rotate_279(x1, y1, -angle) + var xy = __rotate_337(x1, y1, -angle) x1 = xy.x y1 = xy.y - xy = __rotate_279(x2, y2, -angle) + xy = __rotate_337(x2, y2, -angle) x2 = xy.x y2 = xy.y var x = (x1 - x2) / 2 @@ -144837,37 +147083,37 @@ function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursiv if (recursive) return curve if (res) curve = curve.concat(res) for (var i = 0; i < curve.length;) { - var rot = __rotate_279(curve[i], curve[i+1], angle) + var rot = __rotate_337(curve[i], curve[i+1], angle) curve[i++] = rot.x curve[i++] = rot.y } return curve } -function __rotate_279(x, y, rad){ +function __rotate_337(x, y, rad){ return { x: x * Math.cos(rad) - y * Math.sin(rad), y: x * Math.sin(rad) + y * Math.cos(rad) } } -function __radians_279(degress){ +function __radians_337(degress){ return degress * (π / 180) } -/* removed: var _$absolutize_43 = require('abs-svg-path') */; -/* removed: var _$normalize_279 = require('normalize-svg-path') */; +/* removed: var _$absolutize_44 = require('abs-svg-path') */; +/* removed: var _$normalize_337 = require('normalize-svg-path') */; var methods = { 'M': 'moveTo', 'C': 'bezierCurveTo' } -var _$drawSvgPath_131 = function(context, segments) { +var _$drawSvgPath_134 = function(context, segments) { context.beginPath() // Make path easy to reproduce. - _$normalize_279(_$absolutize_43(segments)).forEach( + _$normalize_337(_$absolutize_44(segments)).forEach( function(segment) { var command = segment[0] var args = segment.slice(1) @@ -144882,7 +147128,7 @@ var _$drawSvgPath_131 = function(context, segments) { 'use strict' -var _$isPath_251 = function isPath(str) { +var _$isPath_309 = function isPath(str) { if (typeof str !== 'string') return false str = str.trim() @@ -144894,14 +147140,14 @@ var _$isPath_251 = function isPath(str) { } -var _$parse_286 = __parse_286 +var _$parse_344 = __parse_344 /** * expected argument lengths * @type {Object} */ -var __length_286 = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} +var __length_344 = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} /** * segment pattern @@ -144919,7 +147165,7 @@ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig * @return {Array} */ -function __parse_286(path) { +function __parse_344(path) { var data = [] path.replace(segment, function(_, command, args){ var type = command.toLowerCase() @@ -144933,12 +147179,12 @@ function __parse_286(path) { } while (true) { - if (args.length == __length_286[type]) { + if (args.length == __length_344[type]) { args.unshift(command) return data.push(args) } - if (args.length < __length_286[type]) throw new Error('malformed path data') - data.push([command].concat(args.splice(0, __length_286[type]))) + if (args.length < __length_344[type]) throw new Error('malformed path data') + data.push([command].concat(args.splice(0, __length_344[type]))) } }) return data @@ -144951,10 +147197,10 @@ function parseValues(args) { return numbers ? numbers.map(Number) : [] } -var _$inherits_browser_364 = {}; +var _$inherits_browser_426 = {}; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module - _$inherits_browser_364 = function inherits(ctor, superCtor) { + _$inherits_browser_426 = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { @@ -144967,7 +147213,7 @@ if (typeof Object.create === 'function') { }; } else { // old school shim for old browsers - _$inherits_browser_364 = function inherits(ctor, superCtor) { + _$inherits_browser_426 = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype @@ -144976,13 +147222,13 @@ if (typeof Object.create === 'function') { } } -var _$isBuffer_365 = function isBuffer(arg) { +var _$isBuffer_427 = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -var _$util_366 = {}; +var _$util_428 = {}; (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -145006,7 +147252,7 @@ var _$util_366 = {}; // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; -_$util_366.format = function(f) { +_$util_428.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { @@ -145048,11 +147294,11 @@ _$util_366.format = function(f) { // 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. -_$util_366.deprecate = function(fn, msg) { +_$util_428.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { - return _$util_366.deprecate(fn, msg).apply(this, arguments); + return _$util_428.deprecate(fn, msg).apply(this, arguments); }; } @@ -145081,7 +147327,7 @@ _$util_366.deprecate = function(fn, msg) { var debugs = {}; var debugEnviron; -_$util_366.debuglog = function(set) { +_$util_428.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); @@ -145089,7 +147335,7 @@ _$util_366.debuglog = function(set) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { - var msg = _$util_366.format.apply(_$util_366, arguments); + var msg = _$util_428.format.apply(_$util_428, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { @@ -145122,7 +147368,7 @@ function inspect(obj, opts) { ctx.showHidden = opts; } else if (opts) { // got an "options" object - _$util_366._extend(ctx, opts); + _$util_428._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; @@ -145132,7 +147378,7 @@ function inspect(obj, opts) { if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } -_$util_366.inspect = inspect; +_$util_428.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics @@ -145201,7 +147447,7 @@ function formatValue(ctx, value, recurseTimes) { value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special - value.inspect !== _$util_366.inspect && + value.inspect !== _$util_428.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); @@ -145436,68 +147682,68 @@ function reduceToSingleString(output, base, braces) { function isArray(ar) { return Array.isArray(ar); } -_$util_366.isArray = isArray; +_$util_428.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } -_$util_366.isBoolean = isBoolean; +_$util_428.isBoolean = isBoolean; function isNull(arg) { return arg === null; } -_$util_366.isNull = isNull; +_$util_428.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } -_$util_366.isNullOrUndefined = isNullOrUndefined; +_$util_428.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } -_$util_366.isNumber = isNumber; +_$util_428.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } -_$util_366.isString = isString; +_$util_428.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } -_$util_366.isSymbol = isSymbol; +_$util_428.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } -_$util_366.isUndefined = isUndefined; +_$util_428.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } -_$util_366.isRegExp = isRegExp; +_$util_428.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } -_$util_366.isObject = isObject; +_$util_428.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } -_$util_366.isDate = isDate; +_$util_428.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } -_$util_366.isError = isError; +_$util_428.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } -_$util_366.isFunction = isFunction; +_$util_428.isFunction = isFunction; function isPrimitive(arg) { return arg === null || @@ -145507,9 +147753,9 @@ function isPrimitive(arg) { typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } -_$util_366.isPrimitive = isPrimitive; +_$util_428.isPrimitive = isPrimitive; -_$util_366.isBuffer = _$isBuffer_365; +_$util_428.isBuffer = _$isBuffer_427; function objectToString(o) { return Object.prototype.toString.call(o); @@ -145535,8 +147781,8 @@ function timestamp() { // log is just a thin wrapper to console.log that prepends a timestamp -_$util_366.log = function() { - console.log('%s - %s', timestamp(), _$util_366.format.apply(_$util_366, arguments)); +_$util_428.log = function() { + console.log('%s - %s', timestamp(), _$util_428.format.apply(_$util_428, arguments)); }; @@ -145553,9 +147799,9 @@ _$util_366.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -_$util_366.inherits = _$inherits_browser_364; +_$util_428.inherits = _$inherits_browser_426; -_$util_366._extend = function(origin, add) { +_$util_428._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; @@ -145571,8 +147817,8 @@ function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } -}).call(this,_$browser_304,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$assert_51 = {}; +}).call(this,_$browser_366,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +var _$assert_52 = {}; (function (global){ 'use strict'; @@ -145642,7 +147888,7 @@ function isBuffer(b) { // 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. -/* removed: var _$util_366 = require('util/'); */; +/* removed: var _$util_428 = require('util/'); */; var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { @@ -145676,7 +147922,7 @@ function isView(arrbuf) { // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. -var assert = _$assert_51 = ok; +var assert = _$assert_52 = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, @@ -145686,7 +147932,7 @@ var assert = _$assert_51 = ok; var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { - if (!_$util_366.isFunction(func)) { + if (!_$util_428.isFunction(func)) { return; } if (functionsHaveNames) { @@ -145733,7 +147979,7 @@ assert.AssertionError = function AssertionError(options) { }; // assert.AssertionError instanceof Error -_$util_366.inherits(assert.AssertionError, Error); +_$util_428.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { @@ -145743,8 +147989,8 @@ function truncate(s, n) { } } function inspect(something) { - if (functionsHaveNames || !_$util_366.isFunction(something)) { - return _$util_366.inspect(something); + if (functionsHaveNames || !_$util_428.isFunction(something)) { + return _$util_428.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; @@ -145833,13 +148079,13 @@ function _deepEqual(actual, expected, strict, memos) { // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. - } else if (_$util_366.isDate(actual) && _$util_366.isDate(expected)) { + } else if (_$util_428.isDate(actual) && _$util_428.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (_$util_366.isRegExp(actual) && _$util_366.isRegExp(expected)) { + } else if (_$util_428.isRegExp(actual) && _$util_428.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && @@ -145898,7 +148144,7 @@ function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same - if (_$util_366.isPrimitive(a) || _$util_366.isPrimitive(b)) + if (_$util_428.isPrimitive(a) || _$util_428.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; @@ -146027,7 +148273,7 @@ function _throws(shouldThrow, block, expected, message) { } var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && _$util_366.isError(actual); + var isUnwantedException = !shouldThrow && _$util_428.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && @@ -146066,10 +148312,10 @@ var objectKeys = Object.keys || function (obj) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$cjs_347 = {}; +var _$cjs_409 = {}; "use strict"; -Object.defineProperty(_$cjs_347, "__esModule", { +Object.defineProperty(_$cjs_409, "__esModule", { value: true }); @@ -146245,15 +148491,15 @@ var arcToBezier = function arcToBezier(_ref2) { }); }; -_$cjs_347.default = arcToBezier; -_$cjs_347 = _$cjs_347["default"]; +_$cjs_409.default = arcToBezier; +_$cjs_409 = _$cjs_409["default"]; 'use strict' -var _$normalize_349 = __normalize_349 +var _$normalize_411 = __normalize_411 -/* removed: var _$cjs_347 = require('svg-arc-to-cubic-bezier') */; +/* removed: var _$cjs_409 = require('svg-arc-to-cubic-bezier') */; -function __normalize_349(path){ +function __normalize_411(path){ // init state var prev var result = [] @@ -146276,7 +148522,7 @@ function __normalize_349(path){ startY = seg[2] break case 'A': - var curves = _$cjs_347({ + var curves = _$cjs_409({ px: x, py: y, cx: seg[6], @@ -146316,24 +148562,24 @@ function __normalize_349(path){ quadX = x quadY = y } - seg = __quadratic_349(x, y, quadX, quadY, seg[1], seg[2]) + seg = __quadratic_411(x, y, quadX, quadY, seg[1], seg[2]) break case 'Q': quadX = seg[1] quadY = seg[2] - seg = __quadratic_349(x, y, seg[1], seg[2], seg[3], seg[4]) + seg = __quadratic_411(x, y, seg[1], seg[2], seg[3], seg[4]) break case 'L': - seg = __line_349(x, y, seg[1], seg[2]) + seg = __line_411(x, y, seg[1], seg[2]) break case 'H': - seg = __line_349(x, y, seg[1], y) + seg = __line_411(x, y, seg[1], y) break case 'V': - seg = __line_349(x, y, x, seg[1]) + seg = __line_411(x, y, x, seg[1]) break case 'Z': - seg = __line_349(x, y, startX, startY) + seg = __line_411(x, y, startX, startY) break } @@ -146354,11 +148600,11 @@ function __normalize_349(path){ return result } -function __line_349(x1, y1, x2, y2){ +function __line_411(x1, y1, x2, y2){ return ['C', x1, y1, x2, y2, x2, y2] } -function __quadratic_349(x1, y1, cx, cy, x2, y2){ +function __quadratic_411(x1, y1, cx, cy, x2, y2){ return [ 'C', x1/3 + (2/3) * cx, @@ -146372,13 +148618,13 @@ function __quadratic_349(x1, y1, cx, cy, x2, y2){ 'use strict' -/* removed: var _$parse_286 = require('parse-svg-path') */; -/* removed: var _$absolutize_43 = require('abs-svg-path') */; -/* removed: var _$normalize_349 = require('normalize-svg-path') */; -/* removed: var _$isPath_251 = require('is-svg-path') */; -/* removed: var _$assert_51 = require('assert') */; +/* removed: var _$parse_344 = require('parse-svg-path') */; +/* removed: var _$absolutize_44 = require('abs-svg-path') */; +/* removed: var _$normalize_411 = require('normalize-svg-path') */; +/* removed: var _$isPath_309 = require('is-svg-path') */; +/* removed: var _$assert_52 = require('assert') */; -var _$pathBounds_348 = pathBounds +var _$pathBounds_410 = pathBounds function pathBounds(path) { @@ -146387,14 +148633,14 @@ function pathBounds(path) { // svg path string if (typeof path === 'string') { - _$assert_51(_$isPath_251(path), 'String is not an SVG path.') - path = _$parse_286(path) + _$assert_52(_$isPath_309(path), 'String is not an SVG path.') + path = _$parse_344(path) } - _$assert_51(Array.isArray(path), 'Argument should be a string or an array of path segments.') + _$assert_52(Array.isArray(path), 'Argument should be a string or an array of path segments.') - path = _$absolutize_43(path) - path = _$normalize_349(path) + path = _$absolutize_44(path) + path = _$normalize_411(path) if (!path.length) return [0, 0, 0, 0] @@ -146414,24 +148660,24 @@ function pathBounds(path) { return bounds } -var _$pathSdf_350 = {}; +var _$pathSdf_412 = {}; (function (global){ 'use strict' -/* removed: var _$pathBounds_348 = require('svg-path-bounds') */; -/* removed: var _$parse_286 = require('parse-svg-path') */; -/* removed: var _$drawSvgPath_131 = require('draw-svg-path') */; -/* removed: var _$isPath_251 = require('is-svg-path') */; -/* removed: var _$calcSDF_73 = require('bitmap-sdf') */; +/* removed: var _$pathBounds_410 = require('svg-path-bounds') */; +/* removed: var _$parse_344 = require('parse-svg-path') */; +/* removed: var _$drawSvgPath_134 = require('draw-svg-path') */; +/* removed: var _$isPath_309 = require('is-svg-path') */; +/* removed: var _$calcSDF_74 = require('bitmap-sdf') */; var canvas = document.createElement('canvas') var ctx = canvas.getContext('2d') -_$pathSdf_350 = pathSdf +_$pathSdf_412 = pathSdf function pathSdf (path, options) { - if (!_$isPath_251(path)) throw Error('Argument should be valid svg path string') + if (!_$isPath_309(path)) throw Error('Argument should be valid svg path string') if (!options) options = {} @@ -146448,7 +148694,7 @@ function pathSdf (path, options) { var stroke = options.stroke || 0 - var viewbox = options.viewbox || options.viewBox || _$pathBounds_348(path) + var viewbox = options.viewbox || options.viewBox || _$pathBounds_410(path) var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])] var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2 @@ -146481,15 +148727,15 @@ function pathSdf (path, options) { } //fallback to bezier-curves else { - var segments = _$parse_286(path) - _$drawSvgPath_131(ctx, segments) + var segments = _$parse_344(path) + _$drawSvgPath_134(ctx, segments) ctx.fill() stroke && ctx.stroke() } ctx.setTransform(1, 0, 0, 1, 0, 0); - var data = _$calcSDF_73(ctx, { + var data = _$calcSDF_74(ctx, { cutoff: options.cutoff != null ? options.cutoff : .5, radius: options.radius != null ? options.radius : size * .5 }) @@ -146506,832 +148752,270 @@ function pathSdf (path, options) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var _$gl2d_dashes_513 = { - solid: [1], - dot: [1, 1], - dash: [4, 1], - longdash: [8, 1], - dashdot: [4, 1, 1, 1], - longdashdot: [8, 1, 1, 1] -}; - -var _$attributes_909 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; - -/* removed: var _$gl2d_dashes_513 = require('../../constants/gl2d_dashes'); */; -var __extendFlat_909 = _$extend_528.extendFlat; -var __overrideAll_909 = _$edit_types_569.overrideAll; - -var __scatterLineAttrs_909 = _$attributes_862.line, - __scatterMarkerAttrs_909 = _$attributes_862.marker, - __scatterMarkerLineAttrs_909 = __scatterMarkerAttrs_909.line; - -var __attrs_909 = _$attributes_909 = __overrideAll_909({ - x: _$attributes_862.x, - x0: _$attributes_862.x0, - dx: _$attributes_862.dx, - y: _$attributes_862.y, - y0: _$attributes_862.y0, - dy: _$attributes_862.dy, - - text: __extendFlat_909({}, _$attributes_862.text, { - description: [ - 'Sets text elements associated with each (x,y) pair to appear on hover.', - 'If a single string, the same string appears over', - 'all the data points.', - 'If an array of string, the items are mapped in order to the', - 'this trace\'s (x,y) coordinates.' - ].join(' ') - }), - mode: { - valType: 'flaglist', - flags: ['lines', 'markers'], - extras: ['none'], - role: 'info', - description: [ - 'Determines the drawing mode for this scatter trace.' - ].join(' ') - }, - line: { - color: __scatterLineAttrs_909.color, - width: __scatterLineAttrs_909.width, - dash: { - valType: 'enumerated', - values: Object.keys(_$gl2d_dashes_513), - dflt: 'solid', - role: 'style', - description: 'Sets the style of the lines.' - } - }, - marker: __extendFlat_909({}, _$makeColorScaleAttributes_419('marker'), { - symbol: __scatterMarkerAttrs_909.symbol, - size: __scatterMarkerAttrs_909.size, - sizeref: __scatterMarkerAttrs_909.sizeref, - sizemin: __scatterMarkerAttrs_909.sizemin, - sizemode: __scatterMarkerAttrs_909.sizemode, - opacity: __scatterMarkerAttrs_909.opacity, - showscale: __scatterMarkerAttrs_909.showscale, - colorbar: __scatterMarkerAttrs_909.colorbar, - line: __extendFlat_909({}, _$makeColorScaleAttributes_419('marker.line'), { - width: __scatterMarkerLineAttrs_909.width - }) - }), - connectgaps: _$attributes_862.connectgaps, - fill: _$attributes_862.fill, - fillcolor: _$attributes_862.fillcolor, - - hoveron: _$attributes_862.hoveron, +/* removed: var _$pathSdf_412 = require('svg-path-sdf'); */; +/* removed: var _$normalize_100 = require('color-normalize'); */; - selected: { - marker: _$attributes_862.selected.marker - }, - unselected: { - marker: _$attributes_862.unselected.marker - }, - - opacity: _$attributes_581.opacity +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; -}, 'calc', 'nested'); +/* removed: var _$formatColor_597 = require('../../lib/gl_format_color'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../scatter/make_bubble_size_func'); */; -__attrs_909.x.editType = __attrs_909.y.editType = __attrs_909.x0.editType = __attrs_909.y0.editType = 'calc+clearAxisTypes'; +/* removed: var _$constants_975 = require('./constants'); */; +var __DESELECTDIM_976 = _$interactions_577.DESELECTDIM; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; - -/* removed: var _$attributes_909 = require('./attributes'); */; -/* removed: var _$constants_868 = require('../scatter/constants'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$handleXYDefaults_886 = require('../scatter/xy_defaults'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; - -var _$supplyDefaults_910 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_909, attr, dflt); - } - - var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false; - var isBubble = _$subtypes_884.isBubble(traceIn); - - var len = _$handleXYDefaults_886(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; - } - - coerce('text'); - coerce('mode', len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'); - - if(_$subtypes_884.hasLines(traceOut)) { - coerce('connectgaps'); - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - } +function convertStyle(gd, trace) { + var i; - var dfltHoverOn = []; + var opts = { + marker: undefined, + line: undefined, + fill: undefined, + errorX: undefined, + errorY: undefined, + selected: undefined, + unselected: undefined + }; - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce); - coerce('marker.line.width', isOpen || isBubble ? 1 : 0); - dfltHoverOn.push('points'); - } + if(trace.visible !== true) return opts; - coerce('fill'); - if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - } + if(_$subtypes_949.hasMarkers(trace)) { + opts.marker = convertMarkerStyle(trace); + opts.selected = convertMarkerSelection(trace, trace.selected); + opts.unselected = convertMarkerSelection(trace, trace.unselected); - if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { - dfltHoverOn.push('fills'); + if(!trace.unselected && Array.isArray(trace.marker.opacity)) { + var mo = trace.marker.opacity; + opts.unselected.opacity = new Array(mo.length); + for(i = 0; i < mo.length; i++) { + opts.unselected.opacity[i] = __DESELECTDIM_976 * mo[i]; + } + } } - coerce('hoveron', dfltHoverOn.join('+') || 'points'); - - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); -}; - -var _$scattergl_911 = {}; -(function (global){ -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$regl_315 = require('regl'); */; -/* removed: var _$Scatter_313 = require('regl-scatter2d'); */; -/* removed: var _$createLine_312 = require('regl-line2d'); */; -/* removed: var _$Error2D_311 = require('regl-error2d'); */; -/* removed: var _$KDTree_252 = require('kdgrass'); */; -/* removed: var _$normalize_99 = require('color-normalize'); */; -/* removed: var _$pathSdf_350 = require('svg-path-sdf'); */; -/* removed: var _$newArray_50 = require('array-range'); */; - -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$formatColor_535 = require('../../lib/gl_format_color'); */; - -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -var calcMarkerSize = _$calc_863.calcMarkerSize; -var calcAxisExpansion = _$calc_863.calcAxisExpansion; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$linkTraces_878 = require('../scatter/link_traces'); */; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; - -/* removed: var _$gl2d_dashes_513 = require('../../constants/gl2d_dashes'); */; -var BADNUM = _$numerical_517.BADNUM; -var SYMBOL_SDF_SIZE = 200; -var SYMBOL_SIZE = 20; -var SYMBOL_STROKE = SYMBOL_SIZE / 20; -var SYMBOL_SDF = {}; -var SYMBOL_SVG_CIRCLE = _$drawing_436.symbolFuncs[0](SYMBOL_SIZE * 0.05); -var TOO_MANY_POINTS = 1e5; -var DOT_RE = /-dot/; -var OPEN_RE = /-open/; - -function calc(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = _$axis_ids_587.getFromId(gd, trace.xaxis); - var ya = _$axis_ids_587.getFromId(gd, trace.yaxis); - var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; - var count = trace._length; - var count2 = count * 2; - var stash = {}; - var i, xx, yy; - - var x = xa.makeCalcdata(trace, 'x'); - var y = ya.makeCalcdata(trace, 'y'); - - // we need hi-precision for scatter2d, - // regl-scatter2d uses NaNs for bad/missing values - var positions = new Array(count2); - for(i = 0; i < count; i++) { - xx = x[i]; - yy = y[i]; - positions[i * 2] = xx === BADNUM ? NaN : xx; - positions[i * 2 + 1] = yy === BADNUM ? NaN : yy; - } + if(_$subtypes_949.hasLines(trace)) { + opts.line = { + overlay: true, + thickness: trace.line.width, + color: trace.line.color, + opacity: trace.opacity + }; - if(xa.type === 'log') { - for(i = 0; i < count2; i += 2) { - positions[i] = xa.c2l(positions[i]); - } - } - if(ya.type === 'log') { - for(i = 1; i < count2; i += 2) { - positions[i] = ya.c2l(positions[i]); + var dashes = (_$constants_975.DASHES[trace.line.dash] || [1]).slice(); + for(i = 0; i < dashes.length; ++i) { + dashes[i] *= trace.line.width; } + opts.line.dashes = dashes; } - // we don't build a tree for log axes since it takes long to convert log2px - // and it is also - if(xa.type !== 'log' && ya.type !== 'log') { - // FIXME: delegate this to webworker - stash.tree = _$KDTree_252(positions, 512); - } else { - var ids = stash.ids = new Array(count); - for(i = 0; i < count; i++) { - ids[i] = i; - } + if(trace.error_x && trace.error_x.visible) { + opts.errorX = convertErrorBarStyle(trace, trace.error_x); } - // create scene options and scene - _$calcMarkerColorscale_867(trace); - var options = sceneOptions(gd, subplot, trace, positions); - var markerOptions = options.marker; - var scene = sceneUpdate(gd, subplot); - var ppad; - - // Re-use SVG scatter axis expansion routine except - // for graph with very large number of points where it - // performs poorly. - // In big data case, fake Axes.expand outputs with data bounds, - // and an average size for array marker.size inputs. - if(count < TOO_MANY_POINTS) { - ppad = calcMarkerSize(trace, count); - } else if(markerOptions) { - ppad = 2 * (markerOptions.sizeAvg || Math.max(markerOptions.size, 3)); + if(trace.error_y && trace.error_y.visible) { + opts.errorY = convertErrorBarStyle(trace, trace.error_y); } - calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); - - // set flags to create scene renderers - if(options.fill && !scene.fill2d) scene.fill2d = true; - if(options.marker && !scene.scatter2d) scene.scatter2d = true; - if(options.line && !scene.line2d) scene.line2d = true; - if((options.errorX || options.errorY) && !scene.error2d) scene.error2d = true; - - // save scene options batch - scene.lineOptions.push(options.line); - scene.errorXOptions.push(options.errorX); - scene.errorYOptions.push(options.errorY); - scene.fillOptions.push(options.fill); - scene.markerOptions.push(options.marker); - scene.selectedOptions.push(options.selected); - scene.unselectedOptions.push(options.unselected); - scene.count++; - // stash scene ref - stash.scene = scene; - stash.index = scene.count - 1; - stash.x = x; - stash.y = y; - stash.positions = positions; - stash.count = count; + if(!!trace.fill && trace.fill !== 'none') { + opts.fill = { + closed: true, + fill: trace.fillcolor, + thickness: 0 + }; + } - gd.firstscatter = false; - return [{x: false, y: false, t: stash, trace: trace}]; + return opts; } -// create scene options -function sceneOptions(gd, subplot, trace, positions) { - var fullLayout = gd._fullLayout; - var count = positions.length / 2; - var markerOpts = trace.marker; +function convertMarkerStyle(trace) { + var count = trace._length || trace._commonLength; + var optsIn = trace.marker; + var optsOut = {}; var i; - var hasLines, hasErrorX, hasErrorY, hasMarkers, hasFill; + var multiSymbol = Array.isArray(optsIn.symbol); + var multiColor = _$lib_601.isArrayOrTypedArray(optsIn.color); + var multiLineColor = _$lib_601.isArrayOrTypedArray(optsIn.line.color); + var multiOpacity = _$lib_601.isArrayOrTypedArray(optsIn.opacity); + var multiSize = _$lib_601.isArrayOrTypedArray(optsIn.size); + var multiLineWidth = _$lib_601.isArrayOrTypedArray(optsIn.line.width); - if(trace.visible !== true) { - hasLines = false; - hasErrorX = false; - hasErrorY = false; - hasMarkers = false; - hasFill = false; - } else { - hasLines = _$subtypes_884.hasLines(trace) && positions.length > 1; - hasErrorX = trace.error_x && trace.error_x.visible === true; - hasErrorY = trace.error_y && trace.error_y.visible === true; - hasMarkers = _$subtypes_884.hasMarkers(trace); - hasFill = !!trace.fill && trace.fill !== 'none'; - } + var isOpen; + if(!multiSymbol) isOpen = _$constants_975.OPEN_RE.test(optsIn.symbol); - var lineOptions, markerOptions, fillOptions; - var errorXOptions, errorYOptions; - var selectedOptions, unselectedOptions; - var linePositions; + // prepare colors + if(multiSymbol || multiColor || multiLineColor || multiOpacity) { + optsOut.colors = new Array(count); + optsOut.borderColors = new Array(count); - if(hasErrorX || hasErrorY) { - var calcFromTrace = _$registry_668.getComponentMethod('errorbars', 'calcFromTrace'); - var errorVals = calcFromTrace(trace, fullLayout); + var colors = _$formatColor_597(optsIn, optsIn.opacity, count); + var borderColors = _$formatColor_597(optsIn.line, optsIn.opacity, count); - if(hasErrorX) { - errorXOptions = makeErrorOptions('x', trace.error_x, errorVals); - } - if(hasErrorY) { - errorYOptions = makeErrorOptions('y', trace.error_y, errorVals); - } - } - - if(hasLines) { - lineOptions = {}; - lineOptions.thickness = trace.line.width; - lineOptions.color = trace.line.color; - lineOptions.opacity = trace.opacity; - lineOptions.overlay = true; - - var dashes = (_$gl2d_dashes_513[trace.line.dash] || [1]).slice(); - for(i = 0; i < dashes.length; ++i) dashes[i] *= lineOptions.thickness; - lineOptions.dashes = dashes; - - if(trace.line.shape === 'hv') { - linePositions = []; - for(i = 0; i < Math.floor(positions.length / 2) - 1; i++) { - if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - } - else { - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 1]); - linePositions.push(positions[i * 2 + 2]); - linePositions.push(positions[i * 2 + 1]); - } - } - linePositions.push(positions[positions.length - 2]); - linePositions.push(positions[positions.length - 1]); - } - else if(trace.line.shape === 'vh') { - linePositions = []; - for(i = 0; i < Math.floor(positions.length / 2) - 1; i++) { - if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - } - else { - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 1]); - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 3]); - } + if(!Array.isArray(borderColors[0])) { + var borderColor = borderColors; + borderColors = Array(count); + for(i = 0; i < count; i++) { + borderColors[i] = borderColor; } - linePositions.push(positions[positions.length - 2]); - linePositions.push(positions[positions.length - 1]); - } - else { - linePositions = positions; } - - // If we have data with gaps, we ought to use rect joins - // FIXME: get rid of this - var hasNaN = false; - for(i = 0; i < linePositions.length; i++) { - if(isNaN(linePositions[i])) { - hasNaN = true; - break; + if(!Array.isArray(colors[0])) { + var color = colors; + colors = Array(count); + for(i = 0; i < count; i++) { + colors[i] = color; } } - lineOptions.join = (hasNaN || linePositions.length > TOO_MANY_POINTS) ? 'rect' : - hasMarkers ? 'rect' : 'round'; + optsOut.colors = colors; + optsOut.borderColors = borderColors; - // fill gaps - if(hasNaN && trace.connectgaps) { - var lastX = linePositions[0], lastY = linePositions[1]; - for(i = 0; i < linePositions.length; i += 2) { - if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { - linePositions[i] = lastX; - linePositions[i + 1] = lastY; - } - else { - lastX = linePositions[i]; - lastY = linePositions[i + 1]; - } + for(i = 0; i < count; i++) { + if(multiSymbol) { + var symbol = optsIn.symbol[i]; + isOpen = _$constants_975.OPEN_RE.test(symbol); + } + if(isOpen) { + borderColors[i] = colors[i].slice(); + colors[i] = colors[i].slice(); + colors[i][3] = 0; } } - lineOptions.positions = linePositions; - } - - if(hasFill) { - fillOptions = {}; - fillOptions.fill = trace.fillcolor; - fillOptions.thickness = 0; - fillOptions.closed = true; - } - - if(hasMarkers) { - markerOptions = makeMarkerOptions(markerOpts); - selectedOptions = makeSelectedOptions(trace.selected, markerOpts); - unselectedOptions = makeSelectedOptions(trace.unselected, markerOpts); - markerOptions.positions = positions; - } - - function makeErrorOptions(axLetter, errorOpts, vals) { - var options = {}; - options.positions = positions; - - var ax = _$axis_ids_587.getFromId(gd, trace[axLetter + 'axis']); - var errors = options.errors = new Float64Array(4 * count); - var pOffset = {x: 0, y: 1}[axLetter]; - var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter]; - - for(var i = 0, p = 0; i < count; i++, p += 4) { - errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0; - errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0; - errors[p + eOffset[2]] = 0; - errors[p + eOffset[3]] = 0; - } - - if(errorOpts.copy_ystyle) { - errorOpts = trace.error_y; + optsOut.opacity = trace.opacity; + } else { + if(isOpen) { + optsOut.color = _$normalize_100(optsIn.color, 'uint8'); + optsOut.color[3] = 0; + optsOut.borderColor = _$normalize_100(optsIn.color, 'uint8'); + } else { + optsOut.color = _$normalize_100(optsIn.color, 'uint8'); + optsOut.borderColor = _$normalize_100(optsIn.line.color, 'uint8'); } - options.capSize = errorOpts.width * 2; - options.lineWidth = errorOpts.thickness; - options.color = errorOpts.color; - - return options; + optsOut.opacity = trace.opacity * optsIn.opacity; } - function makeSelectedOptions(selected, markerOpts) { - var options = {}; - - if(!selected) return options; - - if(selected.marker && selected.marker.symbol) { - options = makeMarkerOptions(_$lib_539.extendFlat({}, markerOpts, selected.marker)); - } - - // shortcut simple selection logic - else { - options = {}; - if(selected.marker.size) options.sizes = selected.marker.size; - if(selected.marker.color) options.colors = selected.marker.color; - if(selected.marker.opacity !== undefined) options.opacity = selected.marker.opacity; + // prepare symbols + if(multiSymbol) { + optsOut.markers = new Array(count); + for(i = 0; i < count; i++) { + optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]); } - - return options; + } else { + optsOut.marker = getSymbolSdf(optsIn.symbol); } - function makeMarkerOptions(markerOpts) { - var markerOptions = {}; - var i; - - var multiSymbol = Array.isArray(markerOpts.symbol); - var multiColor = _$lib_539.isArrayOrTypedArray(markerOpts.color); - var multiLineColor = _$lib_539.isArrayOrTypedArray(markerOpts.line.color); - var multiOpacity = _$lib_539.isArrayOrTypedArray(markerOpts.opacity); - var multiSize = _$lib_539.isArrayOrTypedArray(markerOpts.size); - var multiLineWidth = _$lib_539.isArrayOrTypedArray(markerOpts.line.width); - - var isOpen; - if(!multiSymbol) isOpen = OPEN_RE.test(markerOpts.symbol); + // prepare sizes + var markerSizeFunc = _$makeBubbleSizeFn_944(trace); + var s; - // prepare colors - if(multiSymbol || multiColor || multiLineColor || multiOpacity) { - markerOptions.colors = new Array(count); - markerOptions.borderColors = new Array(count); - var colors = _$formatColor_535(markerOpts, markerOpts.opacity, count); - var borderColors = _$formatColor_535(markerOpts.line, markerOpts.opacity, count); + if(multiSize || multiLineWidth) { + var sizes = optsOut.sizes = new Array(count); + var borderSizes = optsOut.borderSizes = new Array(count); + var sizeTotal = 0; + var sizeAvg; - if(!Array.isArray(borderColors[0])) { - var borderColor = borderColors; - borderColors = Array(count); - for(i = 0; i < count; i++) { - borderColors[i] = borderColor; - } - } - if(!Array.isArray(colors[0])) { - var color = colors; - colors = Array(count); - for(i = 0; i < count; i++) { - colors[i] = color; - } + if(multiSize) { + for(i = 0; i < count; i++) { + sizes[i] = markerSizeFunc(optsIn.size[i]); + sizeTotal += sizes[i]; } - - markerOptions.colors = colors; - markerOptions.borderColors = borderColors; - + sizeAvg = sizeTotal / count; + } else { + s = markerSizeFunc(optsIn.size); for(i = 0; i < count; i++) { - if(multiSymbol) { - var symbol = markerOpts.symbol[i]; - isOpen = OPEN_RE.test(symbol); - } - if(isOpen) { - borderColors[i] = colors[i].slice(); - colors[i] = colors[i].slice(); - colors[i][3] = 0; - } + sizes[i] = s; } - - markerOptions.opacity = trace.opacity; } - else { - if(isOpen) { - markerOptions.color = _$normalize_99(markerOpts.color, 'uint8'); - markerOptions.color[3] = 0; - markerOptions.borderColor = _$normalize_99(markerOpts.color, 'uint8'); - } else { - markerOptions.color = _$normalize_99(markerOpts.color, 'uint8'); - markerOptions.borderColor = _$normalize_99(markerOpts.line.color, 'uint8'); - } - markerOptions.opacity = trace.opacity * markerOpts.opacity; - } - - // prepare symbols - if(multiSymbol) { - markerOptions.markers = new Array(count); + // See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798 + if(multiLineWidth) { for(i = 0; i < count; i++) { - markerOptions.markers[i] = getSymbolSdf(markerOpts.symbol[i]); + borderSizes[i] = markerSizeFunc(optsIn.line.width[i]); } } else { - markerOptions.marker = getSymbolSdf(markerOpts.symbol); - } - - // prepare sizes - var markerSizeFunc = _$makeBubbleSizeFn_879(trace); - var s; - - if(multiSize || multiLineWidth) { - var sizes = markerOptions.sizes = new Array(count); - var borderSizes = markerOptions.borderSizes = new Array(count); - var sizeTotal = 0; - var sizeAvg; - - if(multiSize) { - for(i = 0; i < count; i++) { - sizes[i] = markerSizeFunc(markerOpts.size[i]); - sizeTotal += sizes[i]; - } - sizeAvg = sizeTotal / count; - } else { - s = markerSizeFunc(markerOpts.size); - for(i = 0; i < count; i++) { - sizes[i] = s; - } - } - - // See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798 - if(multiLineWidth) { - for(i = 0; i < count; i++) { - borderSizes[i] = markerSizeFunc(markerOpts.line.width[i]); - } - } else { - s = markerSizeFunc(markerOpts.line.width); - for(i = 0; i < count; i++) { - borderSizes[i] = s; - } + s = markerSizeFunc(optsIn.line.width); + for(i = 0; i < count; i++) { + borderSizes[i] = s; } - - markerOptions.sizeAvg = sizeAvg; - } else { - markerOptions.size = markerSizeFunc(markerOpts && markerOpts.size || 10); - markerOptions.borderSizes = markerSizeFunc(markerOpts.line.width); } - return markerOptions; + optsOut.sizeAvg = sizeAvg; + } else { + optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10); + optsOut.borderSizes = markerSizeFunc(optsIn.line.width); } - return { - line: lineOptions, - marker: markerOptions, - errorX: errorXOptions, - errorY: errorYOptions, - fill: fillOptions, - selected: selectedOptions, - unselected: unselectedOptions - }; + return optsOut; } -// make sure scene exists on subplot, return it -function sceneUpdate(gd, subplot) { - var scene = subplot._scene; - var fullLayout = gd._fullLayout; - - var reset = { - // 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: [], - selectedOptions: [], - unselectedOptions: [], - errorXOptions: [], - errorYOptions: [] - }; - - var first = { - selectBatch: null, - unselectBatch: null, - // regl- component stubs, initialized in dirty plot call - fill2d: false, - scatter2d: false, - error2d: false, - line2d: false, - select2d: null - }; - - if(!subplot._scene) { - scene = subplot._scene = _$lib_539.extendFlat({}, reset, first); - - // apply new option to all regl components (used on drag) - scene.update = function update(opt) { - var opts = new Array(scene.count); - for(var i = 0; i < scene.count; i++) { - opts[i] = opt; - } - - 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); - - scene.draw(); - }; - - // draw traces in proper order - scene.draw = function draw() { - var i; - for(i = 0; i < scene.count; i++) { - if(scene.fill2d && scene.fillOptions[i]) { - // must do all fills first - scene.fill2d.draw(i); - } - } - for(i = 0; i < scene.count; i++) { - if(scene.line2d && scene.lineOptions[i]) { - scene.line2d.draw(i); - } - if(scene.error2d && scene.errorXOptions[i]) { - scene.error2d.draw(i); - } - if(scene.error2d && scene.errorYOptions[i]) { - scene.error2d.draw(i + scene.count); - } - if(scene.scatter2d && scene.markerOptions[i] && (!scene.selectBatch || !scene.selectBatch[i])) { - // traces in no-selection mode - scene.scatter2d.draw(i); - } - } - - // draw traces in selection mode - if(scene.scatter2d && scene.select2d && scene.selectBatch) { - scene.select2d.draw(scene.selectBatch); - scene.scatter2d.draw(scene.unselectBatch); - } - - scene.dirty = false; - }; - - // make sure canvas is clear - scene.clear = function clear() { - var vpSize = fullLayout._size; - var width = fullLayout.width; - var height = fullLayout.height; - var xaxis = subplot.xaxis; - var yaxis = subplot.yaxis; - var vp, gl, regl; - - // multisubplot case - if(xaxis && xaxis.domain && yaxis && yaxis.domain) { - vp = [ - vpSize.l + xaxis.domain[0] * vpSize.w, - vpSize.b + yaxis.domain[0] * vpSize.h, - (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, - (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h - ]; - } - else { - vp = [ - vpSize.l, - vpSize.b, - (width - vpSize.r), - (height - vpSize.t) - ]; - } - - if(scene.select2d) { - regl = scene.select2d.regl; - gl = regl._gl; - gl.enable(gl.SCISSOR_TEST); - gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - - if(scene.scatter2d) { - regl = scene.scatter2d.regl; - gl = regl._gl; - gl.enable(gl.SCISSOR_TEST); - gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - }; +function convertMarkerSelection(trace, target) { + var optsIn = trace.marker; + var optsOut = {}; - // remove selection - scene.clearSelect = function clearSelect() { - if(!scene.selectBatch) return; - scene.selectBatch = null; - scene.unselectBatch = null; - scene.scatter2d.update(scene.markerOptions); - scene.clear(); - scene.draw(); - }; + if(!target) return optsOut; - // remove scene resources - scene.destroy = function destroy() { - if(scene.fill2d) scene.fill2d.destroy(); - if(scene.scatter2d) scene.scatter2d.destroy(); - if(scene.error2d) scene.error2d.destroy(); - if(scene.line2d) scene.line2d.destroy(); - if(scene.select2d) scene.select2d.destroy(); + if(target.marker && target.marker.symbol) { + optsOut = convertMarkerStyle(_$lib_601.extendFlat({}, optsIn, target.marker)); + } else if(target.marker) { + if(target.marker.size) optsOut.sizes = target.marker.size; + if(target.marker.color) optsOut.colors = target.marker.color; + if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity; + } - scene.lineOptions = null; - scene.fillOptions = null; - scene.markerOptions = null; - scene.selectedOptions = null; - scene.unselectedOptions = null; - scene.errorXOptions = null; - scene.errorYOptions = null; - scene.selectBatch = null; - scene.unselectBatch = null; + return optsOut; +} - // 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; - }; - } +function convertErrorBarStyle(trace, target) { + var optsOut = { + capSize: target.width * 2, + lineWidth: target.thickness, + color: target.color + }; - // In case if we have scene from the last calc - reset data - if(!scene.dirty) { - _$lib_539.extendFlat(scene, reset); + if(target.copy_ystyle) { + optsOut = trace.error_y; } - return scene; + return optsOut; } +var SYMBOL_SDF_SIZE = _$constants_975.SYMBOL_SDF_SIZE; +var __SYMBOL_SIZE_976 = _$constants_975.SYMBOL_SIZE; +var SYMBOL_STROKE = _$constants_975.SYMBOL_STROKE; +var SYMBOL_SDF = {}; +var SYMBOL_SVG_CIRCLE = _$drawing_498.symbolFuncs[0](__SYMBOL_SIZE_976 * 0.05); + function getSymbolSdf(symbol) { if(symbol === 'circle') return null; var symbolPath, symbolSdf; - var symbolNumber = _$drawing_436.symbolNumber(symbol); - var symbolFunc = _$drawing_436.symbolFuncs[symbolNumber % 100]; - var symbolNoDot = !!_$drawing_436.symbolNoDot[symbolNumber % 100]; - var symbolNoFill = !!_$drawing_436.symbolNoFill[symbolNumber % 100]; + var symbolNumber = _$drawing_498.symbolNumber(symbol); + var symbolFunc = _$drawing_498.symbolFuncs[symbolNumber % 100]; + var symbolNoDot = !!_$drawing_498.symbolNoDot[symbolNumber % 100]; + var symbolNoFill = !!_$drawing_498.symbolNoFill[symbolNumber % 100]; - var isDot = DOT_RE.test(symbol); + var isDot = _$constants_975.DOT_RE.test(symbol); // get symbol sdf from cache or generate it if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol]; if(isDot && !symbolNoDot) { - symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE; + symbolPath = symbolFunc(__SYMBOL_SIZE_976 * 1.1) + SYMBOL_SVG_CIRCLE; } else { - symbolPath = symbolFunc(SYMBOL_SIZE); + symbolPath = symbolFunc(__SYMBOL_SIZE_976); } - symbolSdf = _$pathSdf_350(symbolPath, { + symbolSdf = _$pathSdf_412(symbolPath, { w: SYMBOL_SDF_SIZE, h: SYMBOL_SDF_SIZE, - viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE], + viewBox: [-__SYMBOL_SIZE_976, -__SYMBOL_SIZE_976, __SYMBOL_SIZE_976, __SYMBOL_SIZE_976], stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE }); SYMBOL_SDF[symbol] = symbolSdf; @@ -147339,11 +149023,524 @@ function getSymbolSdf(symbol) { return symbolSdf || null; } -function plot(gd, subplot, cdata) { +function convertLinePositions(gd, trace, positions) { + var count = positions.length / 2; + var linePositions; + var i; + + if(_$subtypes_949.hasLines(trace) && count) { + if(trace.line.shape === 'hv') { + linePositions = []; + for(i = 0; i < count - 1; i++) { + if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + } + else { + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 1]); + linePositions.push(positions[i * 2 + 2]); + linePositions.push(positions[i * 2 + 1]); + } + } + linePositions.push(positions[positions.length - 2]); + linePositions.push(positions[positions.length - 1]); + } else if(trace.line.shape === 'vh') { + linePositions = []; + for(i = 0; i < count - 1; i++) { + if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + } + else { + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 1]); + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 3]); + } + } + linePositions.push(positions[positions.length - 2]); + linePositions.push(positions[positions.length - 1]); + } else { + linePositions = positions; + } + } + + // If we have data with gaps, we ought to use rect joins + // FIXME: get rid of this + var hasNaN = false; + for(i = 0; i < linePositions.length; i++) { + if(isNaN(linePositions[i])) { + hasNaN = true; + break; + } + } + + var join = (hasNaN || linePositions.length > _$constants_975.TOO_MANY_POINTS) ? 'rect' : + _$subtypes_949.hasMarkers(trace) ? 'rect' : 'round'; + + // fill gaps + if(hasNaN && trace.connectgaps) { + var lastX = linePositions[0]; + var lastY = linePositions[1]; + + for(i = 0; i < linePositions.length; i += 2) { + if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { + linePositions[i] = lastX; + linePositions[i + 1] = lastY; + } + else { + lastX = linePositions[i]; + lastY = linePositions[i + 1]; + } + } + } + + return { + join: join, + positions: linePositions + }; +} + +function convertErrorBarPositions(gd, trace, positions) { + var calcFromTrace = _$registry_731.getComponentMethod('errorbars', 'calcFromTrace'); + var vals = calcFromTrace(trace, gd._fullLayout); + var count = positions.length / 2; + var out = {}; + + function put(axLetter) { + var errors = new Float64Array(4 * count); + var ax = _$axis_ids_650.getFromId(gd, trace[axLetter + 'axis']); + var pOffset = {x: 0, y: 1}[axLetter]; + var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter]; + + for(var i = 0, p = 0; i < count; i++, p += 4) { + errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0; + errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0; + errors[p + eOffset[2]] = 0; + errors[p + eOffset[3]] = 0; + } + + return errors; + } + + + if(trace.error_x && trace.error_x.visible) { + out.x = { + positions: positions, + errors: put('x') + }; + } + if(trace.error_y && trace.error_y.visible) { + out.y = { + positions: positions, + errors: put('y') + }; + } + + return out; +} + +var _$convert_976 = { + convertStyle: convertStyle, + convertMarkerStyle: convertMarkerStyle, + convertMarkerSelection: convertMarkerSelection, + convertLinePositions: convertLinePositions, + convertErrorBarPositions: convertErrorBarPositions +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; + +/* removed: var _$attributes_974 = require('./attributes'); */; +/* removed: var _$constants_933 = require('../scatter/constants'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$handleXYDefaults_951 = require('../scatter/xy_defaults'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; + +var _$supplyDefaults_977 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_974, attr, dflt); + } + + var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false; + var isBubble = _$subtypes_949.isBubble(traceIn); + + var len = _$handleXYDefaults_951(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; + } + + coerce('text'); + coerce('mode', len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'); + + if(_$subtypes_949.hasLines(traceOut)) { + coerce('connectgaps'); + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + } + + var dfltHoverOn = []; + + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce); + coerce('marker.line.width', isOpen || isBubble ? 1 : 0); + dfltHoverOn.push('points'); + } + + coerce('fill'); + if(traceOut.fill !== 'none') { + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + } + + if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { + dfltHoverOn.push('fills'); + } + + coerce('hoveron', dfltHoverOn.join('+') || 'points'); + + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); + + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$reglScatter2d_376 = require('regl-scatter2d'); */; +/* removed: var _$Line2D_375 = require('regl-line2d'); */; +/* removed: var _$Error2D_374 = require('regl-error2d'); */; +/* removed: var _$pointCluster_353 = require('point-cluster'); */; +/* removed: var _$newArray_51 = require('array-range'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$prepareRegl_614 = require('../../lib/prepare_regl'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +var __calcMarkerSize_978 = _$calc_928.calcMarkerSize; +var __calcAxisExpansion_978 = _$calc_928.calcAxisExpansion; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$linkTraces_943 = require('../scatter/link_traces'); */; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; + +var __convertStyle_978 = _$convert_976.convertStyle; +var __convertLinePositions_978 = _$convert_976.convertLinePositions; +var __convertErrorBarPositions_978 = _$convert_976.convertErrorBarPositions; + +var __BADNUM_978 = _$numerical_578.BADNUM; +var TOO_MANY_POINTS = _$constants_975.TOO_MANY_POINTS; + +function __calc_978(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axis_ids_650.getFromId(gd, trace.xaxis); + var ya = _$axis_ids_650.getFromId(gd, trace.yaxis); + var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; + var count = trace._length; + var count2 = count * 2; + var stash = {}; + var i, xx, yy; + + var x = xa.makeCalcdata(trace, 'x'); + var y = ya.makeCalcdata(trace, 'y'); + + // we need hi-precision for scatter2d, + // regl-scatter2d uses NaNs for bad/missing values + var positions = new Array(count2); + for(i = 0; i < count; i++) { + xx = x[i]; + yy = y[i]; + positions[i * 2] = xx === __BADNUM_978 ? NaN : xx; + positions[i * 2 + 1] = yy === __BADNUM_978 ? NaN : yy; + } + + if(xa.type === 'log') { + for(i = 0; i < count2; i += 2) { + positions[i] = xa.c2l(positions[i]); + } + } + if(ya.type === 'log') { + for(i = 1; i < count2; i += 2) { + positions[i] = ya.c2l(positions[i]); + } + } + + // we don't build a tree for log axes since it takes long to convert log2px + // and it is also + if(xa.type !== 'log' && ya.type !== 'log') { + // FIXME: delegate this to webworker + stash.tree = _$pointCluster_353(positions); + } else { + var ids = stash.ids = new Array(count); + for(i = 0; i < count; i++) { + ids[i] = i; + } + } + + // create scene options and scene + _$calcMarkerColorscale_932(trace); + var opts = sceneOptions(gd, subplot, trace, positions); + var scene = sceneUpdate(gd, subplot); + + // Re-use SVG scatter axis expansion routine except + // for graph with very large number of points where it + // performs poorly. + // In big data case, fake Axes.expand outputs with data bounds, + // and an average size for array marker.size inputs. + var ppad; + if(count < TOO_MANY_POINTS) { + ppad = __calcMarkerSize_978(trace, count); + } else if(opts.marker) { + ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3)); + } + __calcAxisExpansion_978(gd, trace, xa, ya, x, y, ppad); + + // set flags to create scene renderers + if(opts.fill && !scene.fill2d) scene.fill2d = true; + if(opts.marker && !scene.scatter2d) scene.scatter2d = true; + if(opts.line && !scene.line2d) scene.line2d = true; + if((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true; + + // FIXME: organize it in a more appropriate manner, probably in sceneOptions + // put point-cluster instance for optimized regl calc + if(opts.marker && count >= TOO_MANY_POINTS) { + opts.marker.cluster = stash.tree; + } + + // save scene opts batch + scene.lineOptions.push(opts.line); + scene.errorXOptions.push(opts.errorX); + scene.errorYOptions.push(opts.errorY); + scene.fillOptions.push(opts.fill); + scene.markerOptions.push(opts.marker); + scene.selectedOptions.push(opts.selected); + scene.unselectedOptions.push(opts.unselected); + scene.count++; + + // stash scene ref + stash._scene = scene; + stash.index = scene.count - 1; + stash.x = x; + stash.y = y; + stash.positions = positions; + stash.count = count; + + gd.firstscatter = false; + return [{x: false, y: false, t: stash, trace: trace}]; +} + +// create scene options +function sceneOptions(gd, subplot, trace, positions) { + var opts = __convertStyle_978(gd, trace); + + if(opts.marker) { + opts.marker.positions = positions; + } + + if(opts.line && positions.length > 1) { + _$lib_601.extendFlat( + opts.line, + __convertLinePositions_978(gd, trace, positions) + ); + } + + if(opts.errorX || opts.errorY) { + var errors = __convertErrorBarPositions_978(gd, trace, positions); + + if(opts.errorX) { + _$lib_601.extendFlat(opts.errorX, errors.x); + } + if(opts.errorY) { + _$lib_601.extendFlat(opts.errorY, errors.y); + } + } + + return opts; +} + +// make sure scene exists on subplot, return it +function sceneUpdate(gd, subplot) { + var scene = subplot._scene; + var fullLayout = gd._fullLayout; + + var reset = { + // 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: [], + selectedOptions: [], + unselectedOptions: [], + errorXOptions: [], + errorYOptions: [] + }; + + var first = { + selectBatch: null, + unselectBatch: null, + // regl- component stubs, initialized in dirty plot call + fill2d: false, + scatter2d: false, + error2d: false, + line2d: false, + select2d: null + }; + + if(!subplot._scene) { + scene = subplot._scene = _$lib_601.extendFlat({}, reset, first); + + // apply new option to all regl components (used on drag) + scene.update = function update(opt) { + var opts = new Array(scene.count); + for(var i = 0; i < scene.count; i++) { + opts[i] = opt; + } + + 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); + + scene.draw(); + }; + + // draw traces in proper order + scene.draw = function draw() { + var i; + for(i = 0; i < scene.count; i++) { + if(scene.fill2d && scene.fillOptions[i]) { + // must do all fills first + scene.fill2d.draw(i); + } + } + for(i = 0; i < scene.count; i++) { + if(scene.line2d && scene.lineOptions[i]) { + scene.line2d.draw(i); + } + if(scene.error2d && scene.errorXOptions[i]) { + scene.error2d.draw(i); + } + if(scene.error2d && scene.errorYOptions[i]) { + scene.error2d.draw(i + scene.count); + } + if(scene.scatter2d && scene.markerOptions[i] && (!scene.selectBatch || !scene.selectBatch[i])) { + // traces in no-selection mode + scene.scatter2d.draw(i); + } + } + + // draw traces in selection mode + if(scene.scatter2d && scene.select2d && scene.selectBatch) { + scene.select2d.draw(scene.selectBatch); + scene.scatter2d.draw(scene.unselectBatch); + } + + scene.dirty = false; + }; + + // make sure canvas is clear + scene.clear = function clear() { + var vpSize = fullLayout._size; + var width = fullLayout.width; + var height = fullLayout.height; + var xaxis = subplot.xaxis; + var yaxis = subplot.yaxis; + var vp = [ + vpSize.l + xaxis.domain[0] * vpSize.w, + vpSize.b + yaxis.domain[0] * vpSize.h, + (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, + (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h + ]; + + var gl, regl; + + if(scene.select2d) { + regl = scene.select2d.regl; + gl = regl._gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + + if(scene.scatter2d) { + regl = scene.scatter2d.regl; + gl = regl._gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + }; + + // remove scene resources + scene.destroy = function destroy() { + if(scene.fill2d) scene.fill2d.destroy(); + if(scene.scatter2d) scene.scatter2d.destroy(); + if(scene.error2d) scene.error2d.destroy(); + if(scene.line2d) scene.line2d.destroy(); + if(scene.select2d) scene.select2d.destroy(); + + scene.lineOptions = null; + scene.fillOptions = null; + scene.markerOptions = null; + scene.selectedOptions = null; + scene.unselectedOptions = null; + scene.errorXOptions = null; + scene.errorYOptions = 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_601.extendFlat(scene, reset); + } + + return scene; +} + +function __plot_978(gd, subplot, cdata) { if(!cdata.length) return; var fullLayout = gd._fullLayout; - var scene = cdata[0][0].t.scene; + var scene = cdata[0][0].t._scene; var dragmode = fullLayout.dragmode; // we may have more subplots than initialized data due to Axes.getSubplots method @@ -147353,38 +149550,25 @@ function plot(gd, subplot, cdata) { var width = fullLayout.width; var height = fullLayout.height; - // make sure proper regl instances are created - fullLayout._glcanvas.each(function(d) { - if(d.regl || d.pick) return; - d.regl = _$regl_315({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - extensions: ['ANGLE_instanced_arrays', 'OES_element_index_uint'], - pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio - }); - }); - + _$prepareRegl_614(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']); var regl = fullLayout._glcanvas.data()[0].regl; // that is needed for fills - _$linkTraces_878(gd, subplot, cdata); + _$linkTraces_943(gd, subplot, cdata); if(scene.dirty) { // make sure scenes are created if(scene.error2d === true) { - scene.error2d = _$Error2D_311(regl); + scene.error2d = _$Error2D_374(regl); } if(scene.line2d === true) { - scene.line2d = _$createLine_312(regl); + scene.line2d = _$Line2D_375(regl); } if(scene.scatter2d === true) { - scene.scatter2d = _$Scatter_313(regl); + scene.scatter2d = _$reglScatter2d_376(regl); } if(scene.fill2d === true) { - scene.fill2d = _$createLine_312(regl); + scene.fill2d = _$Line2D_375(regl); } // update main marker options @@ -147491,6 +149675,8 @@ function plot(gd, subplot, cdata) { } var selectMode = dragmode === 'lasso' || dragmode === 'select'; + scene.selectBatch = null; + scene.unselectBatch = null; // provide viewport and range var vpRange = cdata.map(function(cdscatter) { @@ -147502,8 +149688,8 @@ function plot(gd, subplot, cdata) { var x = stash.x; var y = stash.y; - var xaxis = subplot.xaxis || _$axis_ids_587.getFromId(gd, trace.xaxis || 'x'); - var yaxis = subplot.yaxis || _$axis_ids_587.getFromId(gd, trace.yaxis || 'y'); + var xaxis = subplot.xaxis || _$axis_ids_650.getFromId(gd, trace.xaxis || 'x'); + var yaxis = subplot.yaxis || _$axis_ids_650.getFromId(gd, trace.yaxis || 'y'); var i; var range = [ @@ -147523,8 +149709,10 @@ function plot(gd, subplot, cdata) { if(trace.selectedpoints || selectMode) { if(!selectMode) selectMode = true; - if(!scene.selectBatch) scene.selectBatch = []; - if(!scene.unselectBatch) scene.unselectBatch = []; + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } // regenerate scene batch, if traces number changed during selection if(trace.selectedpoints) { @@ -147566,7 +149754,7 @@ function plot(gd, subplot, cdata) { // create select2d if(!scene.select2d) { // create scatter instance by cloning scatter2d - scene.select2d = _$Scatter_313(fullLayout._glcanvas.data()[1].regl, {clone: scene.scatter2d}); + scene.select2d = _$reglScatter2d_376(fullLayout._glcanvas.data()[1].regl); } if(scene.scatter2d && scene.selectBatch && scene.selectBatch.length) { @@ -147604,7 +149792,7 @@ function plot(gd, subplot, cdata) { return; } -function hoverPoints(pointData, xval, yval, hovermode) { +function __hoverPoints_978(pointData, xval, yval, hovermode) { var cd = pointData.cd; var stash = cd[0].t; var trace = cd[0].trace; @@ -147644,9 +149832,9 @@ function hoverPoints(pointData, xval, yval, hovermode) { // pick the id closest to the point // note that point possibly may not be found - var minDist = maxDistance; var id, ptx, pty, i, dx, dy, dist, dxy; + var minDist = maxDistance; if(hovermode === 'x') { for(i = 0; i < ids.length; i++) { ptx = x[ids[i]]; @@ -147675,9 +149863,24 @@ function hoverPoints(pointData, xval, yval, hovermode) { } pointData.index = id; + pointData.distance = minDist; + pointData.dxy = dxy; if(id === undefined) return [pointData]; + calcHover(pointData, x, y, trace); + + return [pointData]; +} + + +function calcHover(pointData, x, y, trace) { + var xa = pointData.xa; + var ya = pointData.ya; + var minDist = pointData.distance; + var dxy = pointData.dxy; + var id = pointData.index; + // the closest data point var di = { pointNumber: id, @@ -147700,16 +149903,16 @@ function hoverPoints(pointData, xval, yval, hovermode) { var marker = trace.marker; if(marker) { - di.ms = _$lib_539.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size; - di.mo = _$lib_539.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity; + di.ms = _$lib_601.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size; + di.mo = _$lib_601.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity; di.mx = Array.isArray(marker.symbol) ? marker.symbol[id] : marker.symbol; - di.mc = _$lib_539.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color; + di.mc = _$lib_601.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color; } var line = marker && marker.line; if(line) { di.mlc = Array.isArray(line.color) ? line.color[id] : line.color; - di.mlw = _$lib_539.isArrayOrTypedArray(line.width) ? line.width[id] : line.width; + di.mlw = _$lib_601.isArrayOrTypedArray(line.width) ? line.width[id] : line.width; } var grad = marker && marker.gradient; @@ -147740,8 +149943,8 @@ function hoverPoints(pointData, xval, yval, hovermode) { var fakeCd = {}; fakeCd[pointData.index] = di; - _$lib_539.extendFlat(pointData, { - color: _$getTraceColor_872(trace, di), + _$lib_601.extendFlat(pointData, { + color: _$getTraceColor_937(trace, di), x0: xp - rad, x1: xp + rad, @@ -147760,12 +149963,13 @@ function hoverPoints(pointData, xval, yval, hovermode) { else if(di.tx) pointData.text = di.tx; else if(trace.text) pointData.text = trace.text; - _$fillHoverText_870(di, trace, pointData); - _$registry_668.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_935(di, trace, pointData); + _$registry_731.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); - return [pointData]; + return pointData; } + function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var selection = []; @@ -147773,11 +149977,11 @@ function selectPoints(searchInfo, polygon) { var stash = cd[0].t; var x = stash.x; var y = stash.y; - var scene = stash.scene; + var scene = stash._scene; if(!scene) return selection; - var hasOnlyLines = (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)); + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); if(trace.visible !== true || hasOnlyLines) return selection; // degenerate polygon does not enable selection @@ -147801,7 +150005,7 @@ function selectPoints(searchInfo, polygon) { } } } else { - unels = _$newArray_50(stash.count); + unels = _$newArray_51(stash.count); } // make sure selectBatch is created @@ -147826,33 +150030,40 @@ function selectPoints(searchInfo, polygon) { return selection; } -function style(gd, cd) { - if(cd) { - var stash = cd[0].t; - var scene = stash.scene; +function __style_978(gd, cds) { + if(!cds) return; + + var stash = cds[0][0].t; + var scene = stash._scene; + + // don't clear the subplot if there are splom traces + // on the graph + if(!gd._fullLayout._has('splom')) { scene.clear(); - scene.draw(); } + + scene.draw(); } -_$scattergl_911 = { +var _$scattergl_978 = { moduleType: 'trace', name: 'scattergl', - basePlotModule: _$cartesian_595, + basePlotModule: _$cartesian_658, categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'markerColorscale', 'showLegend', 'scatter-like'], - attributes: _$attributes_909, - supplyDefaults: _$supplyDefaults_910, - cleanData: _$cleanData_865, - colorbar: _$colorbar_866, - calc: calc, - plot: plot, - hoverPoints: hoverPoints, - style: style, + attributes: _$attributes_974, + supplyDefaults: _$supplyDefaults_977, + cleanData: _$cleanData_930, + colorbar: _$colorbar_931, + calc: __calc_978, + plot: __plot_978, + hoverPoints: __hoverPoints_978, + style: __style_978, selectPoints: selectPoints, sceneOptions: sceneOptions, sceneUpdate: sceneUpdate, + calcHover: calcHover, meta: { hrName: 'scatter_gl', @@ -147865,7 +150076,6 @@ _$scattergl_911 = { } }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -147876,13 +150086,13 @@ _$scattergl_911 = { 'use strict'; -var _$scattergl_30 = _$scattergl_911; +var _$scattergl_30 = _$scattergl_978; -var _$mapboxGl_254 = { exports: {} }; +var _$mapboxGl_311 = { exports: {} }; (function (global){ 'use strict';(function (f) { - if (typeof _$mapboxGl_254.exports === 'object' && "object" !== 'undefined') { - _$mapboxGl_254.exports = f(); + if (typeof _$mapboxGl_311.exports === 'object' && "object" !== 'undefined') { + _$mapboxGl_311.exports = f(); } else if (typeof define === 'function' && define.amd) { define([], f); } else { @@ -172859,7 +175069,7 @@ var _$mapboxGl_254 = { exports: {} }; }, {}, [73])(73); })); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$mapboxGl_254 = _$mapboxGl_254.exports +_$mapboxGl_311 = _$mapboxGl_311.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -172872,7 +175082,7 @@ _$mapboxGl_254 = _$mapboxGl_254.exports var requiredVersion = '0.44.1'; -var _$constants_639 = { +var _$constants_701 = { requiredVersion: requiredVersion, styleUrlPrefix: 'mapbox://styles/mapbox/', @@ -172913,14 +175123,14 @@ var _$constants_639 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var __defaultLine_643 = _$color_411.defaultLine; -var __domainAttrs_643 = _$domain_610.attributes; -/* removed: var _$font_attributes_611 = require('../font_attributes'); */; -var textposition = _$attributes_862.textposition; -var __overrideAll_643 = _$edit_types_569.overrideAll; +/* removed: var _$lib_601 = require('../../lib'); */; +var __defaultLine_705 = _$color_473.defaultLine; +var __domainAttrs_705 = _$domain_672.attributes; +/* removed: var _$font_attributes_673 = require('../font_attributes'); */; +var textposition = _$attributes_927.textposition; +var __overrideAll_705 = _$edit_types_632.overrideAll; -var fontAttr = _$font_attributes_611({ +var fontAttr = _$font_attributes_673({ description: [ 'Sets the icon text font.', 'Has an effect only when `type` is set to *symbol*.' @@ -172928,10 +175138,10 @@ var fontAttr = _$font_attributes_611({ }); fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular'; -var _$layout_attributes_643 = __overrideAll_643({ - _arrayAttrRegexps: [_$lib_539.counterRegex('mapbox', '.layers', true)], +var _$layout_attributes_705 = __overrideAll_705({ + _arrayAttrRegexps: [_$lib_601.counterRegex('mapbox', '.layers', true)], - domain: __domainAttrs_643({name: 'mapbox'}), + domain: __domainAttrs_705({name: 'mapbox'}), accesstoken: { valType: 'string', @@ -173054,7 +175264,7 @@ var _$layout_attributes_643 = __overrideAll_643({ }, color: { valType: 'color', - dflt: __defaultLine_643, + dflt: __defaultLine_705, role: 'style', description: [ 'Sets the primary layer color.', @@ -173101,7 +175311,7 @@ var _$layout_attributes_643 = __overrideAll_643({ fill: { outlinecolor: { valType: 'color', - dflt: __defaultLine_643, + dflt: __defaultLine_705, role: 'style', description: [ 'Sets the fill outline color.', @@ -173138,7 +175348,7 @@ var _$layout_attributes_643 = __overrideAll_643({ ].join(' ') }, textfont: fontAttr, - textposition: _$lib_539.extendFlat({}, textposition, { arrayOk: false }) + textposition: _$lib_601.extendFlat({}, textposition, { arrayOk: false }) } } }, 'plot', 'from-root'); @@ -173154,23 +175364,23 @@ var _$layout_attributes_643 = __overrideAll_643({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../subplot_defaults'); */; -/* removed: var _$layout_attributes_643 = require('./layout_attributes'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../subplot_defaults'); */; +/* removed: var _$layout_attributes_705 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_644 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_706 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'mapbox', - attributes: _$layout_attributes_643, - handleDefaults: __handleDefaults_644, + attributes: _$layout_attributes_705, + handleDefaults: __handleDefaults_706, partition: 'y', accessToken: layoutOut._mapboxAccessToken }); }; -function __handleDefaults_644(containerIn, containerOut, coerce, opts) { +function __handleDefaults_706(containerIn, containerOut, coerce, opts) { coerce('accesstoken', opts.accessToken); coerce('style'); coerce('center.lon'); @@ -173192,14 +175402,14 @@ function handleLayerDefaults(containerIn, containerOut) { var layerIn, layerOut; function coerce(attr, dflt) { - return _$lib_539.coerce(layerIn, layerOut, _$layout_attributes_643.layers, attr, dflt); + return _$lib_601.coerce(layerIn, layerOut, _$layout_attributes_705.layers, attr, dflt); } for(var i = 0; i < layersIn.length; i++) { layerIn = layersIn[i]; layerOut = {}; - if(!_$lib_539.isPlainObject(layerIn)) continue; + if(!_$lib_601.isPlainObject(layerIn)) continue; var sourceType = coerce('sourcetype'); coerce('source'); @@ -173230,7 +175440,7 @@ function handleLayerDefaults(containerIn, containerOut) { coerce('symbol.iconsize'); coerce('symbol.text'); - _$lib_539.coerceFont(coerce, 'symbol.textfont'); + _$lib_601.coerceFont(coerce, 'symbol.textfont'); coerce('symbol.textposition'); } @@ -173250,7 +175460,7 @@ function handleLayerDefaults(containerIn, containerOut) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** * Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset' @@ -173263,13 +175473,13 @@ function handleLayerDefaults(containerIn, containerOut) { * - anchor * - offset */ -var _$convertTextOpts_640 = function convertTextOpts(textposition, iconSize) { +var _$convertTextOpts_702 = function convertTextOpts(textposition, iconSize) { var parts = textposition.split(' '), vPos = parts[0], hPos = parts[1]; // ballpack values - var factor = _$lib_539.isArrayOrTypedArray(iconSize) ? _$lib_539.mean(iconSize) : iconSize, + var factor = _$lib_601.isArrayOrTypedArray(iconSize) ? _$lib_601.mean(iconSize) : iconSize, xInc = 0.5 + (factor / 100), yInc = 1.5 + (factor / 100); @@ -173321,8 +175531,8 @@ var _$convertTextOpts_640 = function convertTextOpts(textposition, iconSize) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$convertTextOpts_640 = require('./convert_text_opts'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$convertTextOpts_702 = require('./convert_text_opts'); */; function MapboxLayer(mapbox, index) { this.mapbox = mapbox; @@ -173343,9 +175553,9 @@ function MapboxLayer(mapbox, index) { this.visible = false; } -var __proto_642 = MapboxLayer.prototype; +var __proto_704 = MapboxLayer.prototype; -__proto_642.update = function update(opts) { +__proto_704.update = function update(opts) { if(!this.visible) { // IMPORTANT: must create source before layer to not cause errors this.updateSource(opts); @@ -173363,7 +175573,7 @@ __proto_642.update = function update(opts) { this.visible = isVisible(opts); }; -__proto_642.needsNewSource = function(opts) { +__proto_704.needsNewSource = function(opts) { // for some reason changing layer to 'fill' or 'symbol' // w/o changing the source throws an exception in mapbox-gl 0.18 ; // stay safe and make new source on type changes @@ -173374,14 +175584,14 @@ __proto_642.needsNewSource = function(opts) { ); }; -__proto_642.needsNewLayer = function(opts) { +__proto_704.needsNewLayer = function(opts) { return ( this.layerType !== opts.type || this.below !== opts.below ); }; -__proto_642.updateSource = function(opts) { +__proto_704.updateSource = function(opts) { var map = this.map; if(map.getSource(this.idSource)) map.removeSource(this.idSource); @@ -173396,7 +175606,7 @@ __proto_642.updateSource = function(opts) { map.addSource(this.idSource, sourceOpts); }; -__proto_642.updateLayer = function(opts) { +__proto_704.updateLayer = function(opts) { var map = this.map; var convertedOpts = convertOpts(opts); @@ -173416,7 +175626,7 @@ __proto_642.updateLayer = function(opts) { } }; -__proto_642.updateStyle = function(opts) { +__proto_704.updateStyle = function(opts) { if(isVisible(opts)) { var convertedOpts = convertOpts(opts); this.mapbox.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout); @@ -173424,7 +175634,7 @@ __proto_642.updateStyle = function(opts) { } }; -__proto_642.dispose = function dispose() { +__proto_704.dispose = function dispose() { var map = this.map; map.removeLayer(this.idLayer); map.removeSource(this.idSource); @@ -173434,7 +175644,7 @@ function isVisible(opts) { var source = opts.source; return ( - _$lib_539.isPlainObject(source) || + _$lib_601.isPlainObject(source) || (typeof source === 'string' && source.length > 0) ); } @@ -173446,7 +175656,7 @@ function convertOpts(opts) { switch(opts.type) { case 'circle': - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'circle-radius': opts.circle.radius, 'circle-color': opts.color, 'circle-opacity': opts.opacity @@ -173454,7 +175664,7 @@ function convertOpts(opts) { break; case 'line': - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'line-width': opts.line.width, 'line-color': opts.color, 'line-opacity': opts.opacity @@ -173462,7 +175672,7 @@ function convertOpts(opts) { break; case 'fill': - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'fill-color': opts.color, 'fill-outline-color': opts.fill.outlinecolor, 'fill-opacity': opts.opacity @@ -173473,9 +175683,9 @@ function convertOpts(opts) { case 'symbol': var symbol = opts.symbol, - textOpts = _$convertTextOpts_640(symbol.textposition, symbol.iconsize); + textOpts = _$convertTextOpts_702(symbol.textposition, symbol.iconsize); - _$lib_539.extendFlat(layout, { + _$lib_601.extendFlat(layout, { 'icon-image': symbol.icon + '-15', 'icon-size': symbol.iconsize / 10, @@ -173488,7 +175698,7 @@ function convertOpts(opts) { // 'text-font': symbol.textfont.family.split(', '), }); - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'icon-color': opts.color, 'text-color': symbol.textfont.color, 'text-opacity': opts.opacity @@ -173515,7 +175725,7 @@ function convertSourceOpts(opts) { return sourceOpts; } -var _$createMapboxLayer_642 = function createMapboxLayer(mapbox, index, opts) { +var _$createMapboxLayer_704 = function createMapboxLayer(mapbox, index, opts) { var mapboxLayer = new MapboxLayer(mapbox, index); mapboxLayer.update(opts); @@ -173534,15 +175744,15 @@ var _$createMapboxLayer_642 = function createMapboxLayer(mapbox, index, opts) { 'use strict'; -/* removed: var _$mapboxGl_254 = require('mapbox-gl'); */; +/* removed: var _$mapboxGl_311 = require('mapbox-gl'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; -/* removed: var _$constants_639 = require('./constants'); */; -/* removed: var _$layout_attributes_643 = require('./layout_attributes'); */; -/* removed: var _$createMapboxLayer_642 = require('./layers'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +var __prepSelect_707 = _$select_664.prepSelect; +/* removed: var _$constants_701 = require('./constants'); */; +/* removed: var _$layout_attributes_705 = require('./layout_attributes'); */; +/* removed: var _$createMapboxLayer_704 = require('./layers'); */; function Mapbox(opts) { this.id = opts.id; @@ -173572,13 +175782,13 @@ function Mapbox(opts) { this.layerList = []; } -var __proto_645 = Mapbox.prototype; +var __proto_707 = Mapbox.prototype; -var _$createMapbox_645 = function createMapbox(opts) { +var _$createMapbox_707 = function createMapbox(opts) { return new Mapbox(opts); }; -__proto_645.plot = function(calcData, fullLayout, promises) { +__proto_707.plot = function(calcData, fullLayout, promises) { var self = this; // feed in new mapbox options @@ -173608,7 +175818,7 @@ __proto_645.plot = function(calcData, fullLayout, promises) { promises.push(promise); }; -__proto_645.createMap = function(calcData, fullLayout, resolve, reject) { +__proto_707.createMap = function(calcData, fullLayout, resolve, reject) { var self = this; var gd = self.gd; var opts = self.opts; @@ -173620,7 +175830,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { self.accessToken = opts.accesstoken; // create the map! - var map = self.map = new _$mapboxGl_254.Map({ + var map = self.map = new _$mapboxGl_311.Map({ container: self.div, style: styleObj.style, @@ -173637,7 +175847,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { }); // clear navigation container - var className = _$constants_639.controlContainerClassName; + var className = _$constants_701.controlContainerClassName; var controlContainer = self.div.getElementsByClassName(className)[0]; self.div.removeChild(controlContainer); @@ -173676,7 +175886,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { if(eventData.originalEvent) { var update = {}; - update[self.id] = _$lib_539.extendFlat({}, view); + update[self.id] = _$lib_601.extendFlat({}, view); gd.emit('plotly_relayout', update); } }); @@ -173693,7 +175903,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { self.xaxis.p2c = function() { return evt.lngLat.lng; }; self.yaxis.p2c = function() { return evt.lngLat.lat; }; - _$fx_453.hover(gd, evt, self.id); + _$fx_515.hover(gd, evt, self.id); }); map.on('click', function(evt) { @@ -173702,11 +175912,11 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { // 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_453.click(gd, evt.originalEvent); + _$fx_515.click(gd, evt.originalEvent); }); function unhover() { - _$fx_453.loneUnhover(fullLayout._toppaper); + _$fx_515.loneUnhover(fullLayout._toppaper); } map.on('dragstart', unhover); @@ -173737,7 +175947,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { }; }; -__proto_645.updateMap = function(calcData, fullLayout, resolve, reject) { +__proto_707.updateMap = function(calcData, fullLayout, resolve, reject) { var self = this; var map = self.map; @@ -173764,7 +175974,7 @@ __proto_645.updateMap = function(calcData, fullLayout, resolve, reject) { } }; -__proto_645.updateData = function(calcData) { +__proto_707.updateData = function(calcData) { var traceHash = this.traceHash; var traceObj, trace, i, j; @@ -173799,7 +176009,7 @@ __proto_645.updateData = function(calcData) { } }; -__proto_645.updateLayout = function(fullLayout) { +__proto_707.updateLayout = function(fullLayout) { var map = this.map, opts = this.opts; @@ -173814,7 +176024,7 @@ __proto_645.updateLayout = function(fullLayout) { this.map.resize(); }; -__proto_645.resolveOnRender = function(resolve) { +__proto_707.resolveOnRender = function(resolve) { var map = this.map; map.on('render', function onRender() { @@ -173826,11 +176036,11 @@ __proto_645.resolveOnRender = function(resolve) { }); }; -__proto_645.rejectOnError = function(reject) { +__proto_707.rejectOnError = function(reject) { var map = this.map; function handler() { - reject(new Error(_$constants_639.mapOnErrorMsg)); + reject(new Error(_$constants_701.mapOnErrorMsg)); } map.once('error', handler); @@ -173840,7 +176050,7 @@ __proto_645.rejectOnError = function(reject) { map.once('layer.error', handler); }; -__proto_645.createFramework = function(fullLayout) { +__proto_707.createFramework = function(fullLayout) { var self = this; var div = self.div = document.createElement('div'); @@ -173861,7 +176071,7 @@ __proto_645.createFramework = function(fullLayout) { self.updateFramework(fullLayout); }; -__proto_645.updateFx = function(fullLayout) { +__proto_707.updateFx = function(fullLayout) { var self = this; var map = self.map; var gd = self.gd; @@ -173909,10 +176119,10 @@ __proto_645.updateFx = function(fullLayout) { }; dragOptions.prepFn = function(e, startX, startY) { - _$prepSelect_602(e, startX, startY, dragOptions, dragMode); + __prepSelect_707(e, startX, startY, dragOptions, dragMode); }; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); } else { map.dragPan.enable(); map.off('zoomstart', self.clearSelect); @@ -173920,7 +176130,7 @@ __proto_645.updateFx = function(fullLayout) { } }; -__proto_645.updateFramework = function(fullLayout) { +__proto_707.updateFramework = function(fullLayout) { var domain = fullLayout[this.id].domain; var size = fullLayout._size; @@ -173937,7 +176147,7 @@ __proto_645.updateFramework = function(fullLayout) { this.yaxis._length = size.h * (domain.y[1] - domain.y[0]); }; -__proto_645.updateLayers = function() { +__proto_707.updateLayers = function() { var opts = this.opts; var layers = opts.layers; var layerList = this.layerList; @@ -173955,7 +176165,7 @@ __proto_645.updateLayers = function() { layerList = this.layerList = []; for(i = 0; i < layers.length; i++) { - layerList.push(_$createMapboxLayer_642(this, i, layers[i])); + layerList.push(_$createMapboxLayer_704(this, i, layers[i])); } } else { for(i = 0; i < layers.length; i++) { @@ -173964,7 +176174,7 @@ __proto_645.updateLayers = function() { } }; -__proto_645.destroy = function() { +__proto_707.destroy = function() { if(this.map) { this.map.remove(); this.map = null; @@ -173972,26 +176182,26 @@ __proto_645.destroy = function() { } }; -__proto_645.toImage = function() { +__proto_707.toImage = function() { this.map.stop(); return this.map.getCanvas().toDataURL(); }; // convenience wrapper to create set multiple layer // 'layout' or 'paint options at once. -__proto_645.setOptions = function(id, methodName, opts) { +__proto_707.setOptions = function(id, methodName, opts) { for(var k in opts) { this.map[methodName](id, k, opts[k]); } }; // convenience method to project a [lon, lat] array to pixel coords -__proto_645.project = function(v) { - return this.map.project(new _$mapboxGl_254.LngLat(v[0], v[1])); +__proto_707.project = function(v) { + return this.map.project(new _$mapboxGl_311.LngLat(v[0], v[1])); }; // get map's current view values in plotly.js notation -__proto_645.getView = function() { +__proto_707.getView = function() { var map = this.map; var mapCenter = map.getCenter(); @@ -174006,11 +176216,11 @@ __proto_645.getView = function() { }; function getStyleObj(val) { - var styleValues = _$layout_attributes_643.style.values; - var styleDflt = _$layout_attributes_643.style.dflt; + var styleValues = _$layout_attributes_705.style.values; + var styleDflt = _$layout_attributes_705.style.dflt; var styleObj = {}; - if(_$lib_539.isPlainObject(val)) { + if(_$lib_601.isPlainObject(val)) { styleObj.id = val.id; styleObj.style = val; } else if(typeof val === 'string') { @@ -174030,14 +176240,14 @@ function getStyleObj(val) { // if style is part of the 'official' mapbox values, add URL prefix and suffix function convertStyleVal(val) { - return _$constants_639.styleUrlPrefix + val + '-' + _$constants_639.styleUrlSuffix; + return _$constants_701.styleUrlPrefix + val + '-' + _$constants_701.styleUrlSuffix; } function convertCenter(center) { return [center.lon, center.lat]; } -var _$mapbox_641 = {}; +var _$mapbox_703 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -174048,30 +176258,30 @@ var _$mapbox_641 = {}; 'use strict'; -/* removed: var _$mapboxGl_254 = require('mapbox-gl'); */; +/* removed: var _$mapboxGl_311 = require('mapbox-gl'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __getSubplotCalcData_641 = _$get_data_621.getSubplotCalcData; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __getSubplotCalcData_703 = _$get_data_683.getSubplotCalcData; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$createMapbox_645 = require('./mapbox'); */; -/* removed: var _$constants_639 = require('./constants'); */; +/* removed: var _$createMapbox_707 = require('./mapbox'); */; +/* removed: var _$constants_701 = require('./constants'); */; var MAPBOX = 'mapbox'; -for(var __k_641 in _$constants_639.styleRules) { - _$lib_539.addStyleRule('.mapboxgl-' + __k_641, _$constants_639.styleRules[__k_641]); +for(var __k_703 in _$constants_701.styleRules) { + _$lib_601.addStyleRule('.mapboxgl-' + __k_703, _$constants_701.styleRules[__k_703]); } -_$mapbox_641.name = MAPBOX; +_$mapbox_703.name = MAPBOX; -_$mapbox_641.attr = 'subplot'; +_$mapbox_703.attr = 'subplot'; -_$mapbox_641.idRoot = MAPBOX; +_$mapbox_703.idRoot = MAPBOX; -_$mapbox_641.idRegex = _$mapbox_641.attrRegex = _$lib_539.counterRegex(MAPBOX); +_$mapbox_703.idRegex = _$mapbox_703.attrRegex = _$lib_601.counterRegex(MAPBOX); -_$mapbox_641.attributes = { +_$mapbox_703.attributes = { subplot: { valType: 'subplotid', role: 'info', @@ -174086,30 +176296,30 @@ _$mapbox_641.attributes = { } }; -_$mapbox_641.layoutAttributes = _$layout_attributes_643; +_$mapbox_703.layoutAttributes = _$layout_attributes_705; -_$mapbox_641.supplyLayoutDefaults = _$supplyLayoutDefaults_644; +_$mapbox_703.supplyLayoutDefaults = _$supplyLayoutDefaults_706; -_$mapbox_641.plot = function plotMapbox(gd) { +_$mapbox_703.plot = function plotMapbox(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var mapboxIds = fullLayout._subplots[MAPBOX]; - if(_$mapboxGl_254.version !== _$constants_639.requiredVersion) { - throw new Error(_$constants_639.wrongVersionErrorMsg); + if(_$mapboxGl_311.version !== _$constants_701.requiredVersion) { + throw new Error(_$constants_701.wrongVersionErrorMsg); } var accessToken = findAccessToken(gd, mapboxIds); - _$mapboxGl_254.accessToken = accessToken; + _$mapboxGl_311.accessToken = accessToken; for(var i = 0; i < mapboxIds.length; i++) { var id = mapboxIds[i], - subplotCalcData = __getSubplotCalcData_641(calcData, MAPBOX, id), + subplotCalcData = __getSubplotCalcData_703(calcData, MAPBOX, id), opts = fullLayout[id], mapbox = opts._subplot; if(!mapbox) { - mapbox = _$createMapbox_645({ + mapbox = _$createMapbox_707({ gd: gd, container: fullLayout._glcontainer.node(), id: id, @@ -174122,7 +176332,7 @@ _$mapbox_641.plot = function plotMapbox(gd) { if(!mapbox.viewInitial) { mapbox.viewInitial = { - center: _$lib_539.extendFlat({}, opts.center), + center: _$lib_601.extendFlat({}, opts.center), zoom: opts.zoom, bearing: opts.bearing, pitch: opts.pitch @@ -174133,7 +176343,7 @@ _$mapbox_641.plot = function plotMapbox(gd) { } }; -_$mapbox_641.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$mapbox_703.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || []; for(var i = 0; i < oldMapboxKeys.length; i++) { @@ -174145,7 +176355,7 @@ _$mapbox_641.clean = function(newFullData, newFullLayout, oldFullData, oldFullLa } }; -_$mapbox_641.toSVG = function(gd) { +_$mapbox_703.toSVG = function(gd) { var fullLayout = gd._fullLayout; var subplotIds = fullLayout._subplots[MAPBOX]; var size = fullLayout._size; @@ -174159,7 +176369,7 @@ _$mapbox_641.toSVG = function(gd) { var image = fullLayout._glimages.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, x: size.l + size.w * domain.x[0], y: size.t + size.h * (1 - domain.y[1]), @@ -174189,10 +176399,10 @@ function findAccessToken(gd, mapboxIds) { } } - throw new Error(_$constants_639.noAccessTokenErrorMsg); + throw new Error(_$constants_701.noAccessTokenErrorMsg); } -_$mapbox_641.updateFx = function(fullLayout) { +_$mapbox_703.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots[MAPBOX]; for(var i = 0; i < subplotIds.length; i++) { @@ -174211,26 +176421,26 @@ _$mapbox_641.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_900 = require('../scattergeo/attributes'); */; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$layout_attributes_643 = require('../../plots/mapbox/layout_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_965 = require('../scattergeo/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$layout_attributes_705 = require('../../plots/mapbox/layout_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_912 = _$extend_528.extendFlat; -var __overrideAll_912 = _$edit_types_569.overrideAll; +var __extendFlat_979 = _$extend_590.extendFlat; +var __overrideAll_979 = _$edit_types_632.overrideAll; -var __lineAttrs_912 = _$attributes_900.line; -var markerAttrs = _$attributes_900.marker; +var __lineAttrs_979 = _$attributes_965.line; +var markerAttrs = _$attributes_965.marker; -var _$attributes_912 = __overrideAll_912({ - lon: _$attributes_900.lon, - lat: _$attributes_900.lat, +var _$attributes_979 = __overrideAll_979({ + lon: _$attributes_965.lon, + lat: _$attributes_965.lat, // locations // locationmode - mode: __extendFlat_912({}, _$attributes_862.mode, { + mode: __extendFlat_979({}, _$attributes_927.mode, { dflt: 'markers', description: [ 'Determines the drawing mode for this scatter trace.', @@ -174240,7 +176450,7 @@ var _$attributes_912 = __overrideAll_912({ ].join(' ') }), - text: __extendFlat_912({}, _$attributes_862.text, { + text: __extendFlat_979({}, _$attributes_927.text, { description: [ 'Sets text elements associated with each (lon,lat) pair', 'If a single string, the same string appears over', @@ -174251,7 +176461,7 @@ var _$attributes_912 = __overrideAll_912({ 'these elements will be seen in the hover labels.' ].join(' ') }), - hovertext: __extendFlat_912({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_979({}, _$attributes_927.hovertext, { description: [ 'Sets hover text elements associated with each (lon,lat) pair', 'If a single string, the same string appears over', @@ -174263,14 +176473,14 @@ var _$attributes_912 = __overrideAll_912({ }), line: { - color: __lineAttrs_912.color, - width: __lineAttrs_912.width + color: __lineAttrs_979.color, + width: __lineAttrs_979.width // TODO // dash: dash }, - connectgaps: _$attributes_862.connectgaps, + connectgaps: _$attributes_927.connectgaps, marker: { symbol: { @@ -174298,25 +176508,25 @@ var _$attributes_912 = __overrideAll_912({ autocolorscale: markerAttrs.autocolorscale, reversescale: markerAttrs.reversescale, showscale: markerAttrs.showscale, - colorbar: _$attributes_412, + colorbar: _$attributes_474, // line }, - fill: _$attributes_900.fill, - fillcolor: _$attributes_862.fillcolor, + fill: _$attributes_965.fill, + fillcolor: _$attributes_927.fillcolor, - textfont: _$layout_attributes_643.layers.symbol.textfont, - textposition: _$layout_attributes_643.layers.symbol.textposition, + textfont: _$layout_attributes_705.layers.symbol.textfont, + textposition: _$layout_attributes_705.layers.symbol.textposition, selected: { - marker: _$attributes_862.selected.marker + marker: _$attributes_927.selected.marker }, unselected: { - marker: _$attributes_862.unselected.marker + marker: _$attributes_927.unselected.marker }, - hoverinfo: __extendFlat_912({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_979({}, _$attributes_644.hoverinfo, { flags: ['lon', 'lat', 'text', 'name'] }) }, 'calc', 'nested'); @@ -174331,18 +176541,18 @@ var _$attributes_912 = __overrideAll_912({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_912 = require('./attributes'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$attributes_979 = require('./attributes'); */; -var _$supplyDefaults_914 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_981 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_912, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_979, attr, dflt); } var len = handleLonLatDefaults(traceIn, traceOut, coerce); @@ -174355,13 +176565,13 @@ var _$supplyDefaults_914 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); // array marker.size and marker.color are only supported with circles @@ -174370,21 +176580,21 @@ var _$supplyDefaults_914 = function supplyDefaults(traceIn, traceOut, defaultCol marker.line = {width: 0}; if(marker.symbol !== 'circle') { - if(_$lib_539.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0]; - if(_$lib_539.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0]; + if(_$lib_601.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0]; + if(_$lib_601.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0]; } } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce, {noSelect: true}); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce, {noSelect: true}); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); } - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; function handleLonLatDefaults(traceIn, traceOut, coerce) { @@ -174408,7 +176618,7 @@ function handleLonLatDefaults(traceIn, traceOut, coerce) { 'use strict'; -var _$eventData_915 = function eventData(out, pt) { +var _$eventData_982 = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; @@ -174426,13 +176636,13 @@ var _$eventData_915 = function eventData(out, pt) { 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; -var __BADNUM_916 = _$numerical_517.BADNUM; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; +var __BADNUM_983 = _$numerical_578.BADNUM; -var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_983 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -174450,9 +176660,9 @@ var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { function distFn(d) { var lonlat = d.lonlat; - if(lonlat[0] === __BADNUM_916) return Infinity; + if(lonlat[0] === __BADNUM_983) return Infinity; - var lon = _$lib_539.wrap180(lonlat[0]); + var lon = _$lib_601.wrap180(lonlat[0]); var lat = lonlat[1]; var pt = subplot.project([lon, lat]); var dx = pt.x - xa.c2p([xval2, lat]); @@ -174462,14 +176672,14 @@ var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad); } - _$fx_453.getClosest(cd, distFn, pointData); + _$fx_515.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_539.wrap180(lonlat[0]) + lonShift, lonlat[1]]; + var lonlatShifted = [_$lib_601.wrap180(lonlat[0]) + lonShift, lonlat[1]]; // shift labels back to original winded globe var xc = xa.c2p(lonlatShifted); @@ -174481,13 +176691,13 @@ var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { pointData.y0 = yc - rad; pointData.y1 = yc + rad; - pointData.color = _$getTraceColor_872(trace, di); - pointData.extraText = __getExtraText_916(trace, di, cd[0].t.labels); + pointData.color = _$getTraceColor_937(trace, di); + pointData.extraText = __getExtraText_983(trace, di, cd[0].t.labels); return [pointData]; }; -function __getExtraText_916(trace, di, labels) { +function __getExtraText_983(trace, di, labels) { var hoverinfo = di.hi || trace.hoverinfo; var parts = hoverinfo.split('+'); var isAll = parts.indexOf('all') !== -1; @@ -174511,7 +176721,7 @@ function __getExtraText_916(trace, di, labels) { } if(isAll || parts.indexOf('text') !== -1) { - _$fillHoverText_870(di, trace, text); + _$fillHoverText_935(di, trace, text); } return text.join('
'); @@ -174527,26 +176737,26 @@ function __getExtraText_916(trace, di, labels) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_913 = _$numerical_517.BADNUM; -/* removed: var _$geojson_utils_532 = require('../../lib/geojson_utils'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_980 = _$numerical_578.BADNUM; +/* removed: var _$geojson_utils_594 = require('../../lib/geojson_utils'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$convertTextOpts_640 = require('../../plots/mapbox/convert_text_opts'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$convertTextOpts_702 = require('../../plots/mapbox/convert_text_opts'); */; -var _$convert_913 = function convert(calcTrace) { +var _$convert_980 = function convert(calcTrace) { var trace = calcTrace[0].trace; var isVisible = (trace.visible === true); var hasFill = (trace.fill !== 'none'); - var hasLines = _$subtypes_884.hasLines(trace); - var hasMarkers = _$subtypes_884.hasMarkers(trace); - var hasText = _$subtypes_884.hasText(trace); + var hasLines = _$subtypes_949.hasLines(trace); + var hasMarkers = _$subtypes_949.hasMarkers(trace); + var hasText = _$subtypes_949.hasText(trace); var hasCircles = (hasMarkers && trace.marker.symbol === 'circle'); var hasSymbols = (hasMarkers && trace.marker.symbol !== 'circle'); @@ -174568,23 +176778,23 @@ var _$convert_913 = function convert(calcTrace) { // fill layer and line layer use the same coords var lineCoords; if(hasFill || hasLines) { - lineCoords = _$geojson_utils_532.calcTraceToLineCoords(calcTrace); + lineCoords = _$geojson_utils_594.calcTraceToLineCoords(calcTrace); } if(hasFill) { - fill.geojson = _$geojson_utils_532.makePolygon(lineCoords); + fill.geojson = _$geojson_utils_594.makePolygon(lineCoords); fill.layout.visibility = 'visible'; - _$lib_539.extendFlat(fill.paint, { + _$lib_601.extendFlat(fill.paint, { 'fill-color': trace.fillcolor }); } if(hasLines) { - line.geojson = _$geojson_utils_532.makeLine(lineCoords); + line.geojson = _$geojson_utils_594.makeLine(lineCoords); line.layout.visibility = 'visible'; - _$lib_539.extendFlat(line.paint, { + _$lib_601.extendFlat(line.paint, { 'line-width': trace.line.width, 'line-color': trace.line.color, 'line-opacity': trace.opacity @@ -174598,7 +176808,7 @@ var _$convert_913 = function convert(calcTrace) { circle.geojson = circleOpts.geojson; circle.layout.visibility = 'visible'; - _$lib_539.extendFlat(circle.paint, { + _$lib_601.extendFlat(circle.paint, { 'circle-color': circleOpts.mcc, 'circle-radius': circleOpts.mrc, 'circle-opacity': circleOpts.mo @@ -174608,18 +176818,18 @@ var _$convert_913 = function convert(calcTrace) { if(hasSymbols || hasText) { symbol.geojson = makeSymbolGeoJSON(calcTrace); - _$lib_539.extendFlat(symbol.layout, { + _$lib_601.extendFlat(symbol.layout, { visibility: 'visible', 'icon-image': '{symbol}-15', 'text-field': '{text}' }); if(hasSymbols) { - _$lib_539.extendFlat(symbol.layout, { + _$lib_601.extendFlat(symbol.layout, { 'icon-size': trace.marker.size / 10 }); - _$lib_539.extendFlat(symbol.paint, { + _$lib_601.extendFlat(symbol.paint, { 'icon-opacity': trace.opacity * trace.marker.opacity, // TODO does not work ?? @@ -174629,11 +176839,11 @@ var _$convert_913 = function convert(calcTrace) { if(hasText) { var iconSize = (trace.marker || {}).size, - textOpts = _$convertTextOpts_640(trace.textposition, iconSize); + textOpts = _$convertTextOpts_702(trace.textposition, iconSize); // all data-driven below !! - _$lib_539.extendFlat(symbol.layout, { + _$lib_601.extendFlat(symbol.layout, { 'text-size': trace.textfont.size, 'text-anchor': textOpts.anchor, 'text-offset': textOpts.offset @@ -174642,7 +176852,7 @@ var _$convert_913 = function convert(calcTrace) { // 'text-font': symbol.textfont.family.split(', '), }); - _$lib_539.extendFlat(symbol.paint, { + _$lib_601.extendFlat(symbol.paint, { 'text-color': trace.textfont.color, 'text-opacity': trace.opacity }); @@ -174654,7 +176864,7 @@ var _$convert_913 = function convert(calcTrace) { function initContainer() { return { - geojson: _$geojson_utils_532.makeBlank(), + geojson: _$geojson_utils_594.makeBlank(), layout: { visibility: 'none' }, paint: {} }; @@ -174664,9 +176874,9 @@ function makeCircleOpts(calcTrace) { var trace = calcTrace[0].trace; var marker = trace.marker; var selectedpoints = trace.selectedpoints; - var arrayColor = _$lib_539.isArrayOrTypedArray(marker.color); - var arraySize = _$lib_539.isArrayOrTypedArray(marker.size); - var arrayOpacity = _$lib_539.isArrayOrTypedArray(marker.opacity); + var arrayColor = _$lib_601.isArrayOrTypedArray(marker.color); + var arraySize = _$lib_601.isArrayOrTypedArray(marker.size); + var arrayOpacity = _$lib_601.isArrayOrTypedArray(marker.opacity); var i; function addTraceOpacity(o) { return trace.opacity * o; } @@ -174675,24 +176885,24 @@ function makeCircleOpts(calcTrace) { var colorFn; if(arrayColor) { - if(_$colorscale_426.hasColorscale(trace, 'marker')) { - colorFn = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale(marker.colorscale, marker.cmin, marker.cmax) + if(_$colorscale_488.hasColorscale(trace, 'marker')) { + colorFn = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale(marker.colorscale, marker.cmin, marker.cmax) ); } else { - colorFn = _$lib_539.identity; + colorFn = _$lib_601.identity; } } var sizeFn; if(arraySize) { - sizeFn = _$makeBubbleSizeFn_879(trace); + sizeFn = _$makeBubbleSizeFn_944(trace); } var opacityFn; if(arrayOpacity) { opacityFn = function(mo) { - var mo2 = _$fastIsnumeric_139(mo) ? +_$lib_539.constrain(mo, 0, 1) : 0; + var mo2 = _$fastIsnumeric_196(mo) ? +_$lib_601.constrain(mo, 0, 1) : 0; return addTraceOpacity(mo2); }; } @@ -174719,7 +176929,7 @@ function makeCircleOpts(calcTrace) { var fns; if(selectedpoints) { - fns = _$drawing_436.makeSelectedPointStyleFns(trace); + fns = _$drawing_498.makeSelectedPointStyleFns(trace); for(i = 0; i < features.length; i++) { var d = features[i].properties; @@ -174767,7 +176977,7 @@ function makeSymbolGeoJSON(calcTrace) { getFillFunc(symbol) : blankFillFunc; - var fillText = _$subtypes_884.hasText(trace) ? + var fillText = _$subtypes_949.hasText(trace) ? getFillFunc(text) : blankFillFunc; @@ -174798,7 +177008,7 @@ function makeSymbolGeoJSON(calcTrace) { } function getFillFunc(attr) { - if(_$lib_539.isArrayOrTypedArray(attr)) { + if(_$lib_601.isArrayOrTypedArray(attr)) { return function(v) { return v; }; } else if(attr) { @@ -174813,7 +177023,7 @@ function blankFillFunc() { return ''; } // only need to check lon (OR lat) function isBADNUM(lonlat) { - return lonlat[0] === __BADNUM_913; + return lonlat[0] === __BADNUM_980; } /** @@ -174826,7 +177036,7 @@ function isBADNUM(lonlat) { 'use strict'; -/* removed: var _$convert_913 = require('./convert'); */; +/* removed: var _$convert_980 = require('./convert'); */; function ScatterMapbox(subplot, uid) { this.subplot = subplot; @@ -174853,22 +177063,22 @@ function ScatterMapbox(subplot, uid) { // for up-to 4 sources per 'scattermapbox' traces becomes a problem. } -var __proto_918 = ScatterMapbox.prototype; +var __proto_985 = ScatterMapbox.prototype; -__proto_918.addSource = function(k, opts) { +__proto_985.addSource = function(k, opts) { this.subplot.map.addSource(this.sourceIds[k], { type: 'geojson', data: opts.geojson }); }; -__proto_918.setSourceData = function(k, opts) { +__proto_985.setSourceData = function(k, opts) { this.subplot.map .getSource(this.sourceIds[k]) .setData(opts.geojson); }; -__proto_918.addLayer = function(k, opts) { +__proto_985.addLayer = function(k, opts) { this.subplot.map.addLayer({ type: k, id: this.layerIds[k], @@ -174878,9 +177088,9 @@ __proto_918.addLayer = function(k, opts) { }); }; -__proto_918.update = function update(calcTrace) { +__proto_985.update = function update(calcTrace) { var subplot = this.subplot; - var optsAll = _$convert_913(calcTrace); + var optsAll = _$convert_980(calcTrace); for(var i = 0; i < this.order.length; i++) { var k = this.order[i]; @@ -174898,7 +177108,7 @@ __proto_918.update = function update(calcTrace) { calcTrace[0].trace._glTrace = this; }; -__proto_918.dispose = function dispose() { +__proto_985.dispose = function dispose() { var map = this.subplot.map; for(var i = 0; i < this.order.length; i++) { @@ -174908,10 +177118,10 @@ __proto_918.dispose = function dispose() { } }; -var _$createScatterMapbox_918 = function createScatterMapbox(subplot, calcTrace) { +var _$createScatterMapbox_985 = function createScatterMapbox(subplot, calcTrace) { var trace = calcTrace[0].trace; var scatterMapbox = new ScatterMapbox(subplot, trace.uid); - var optsAll = _$convert_913(calcTrace); + var optsAll = _$convert_980(calcTrace); for(var i = 0; i < scatterMapbox.order.length; i++) { var k = scatterMapbox.order[i]; @@ -174937,10 +177147,11 @@ var _$createScatterMapbox_918 = function createScatterMapbox(subplot, calcTrace) 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +var __BADNUM_986 = _$numerical_578.BADNUM; -var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_986 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -174948,7 +177159,7 @@ var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { var trace = cd[0].trace; var i; - if(!_$subtypes_884.hasMarkers(trace)) return []; + if(!_$subtypes_949.hasMarkers(trace)) return []; if(polygon === false) { for(i = 0; i < cd.length; i++) { @@ -174958,18 +177169,21 @@ var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { for(i = 0; i < cd.length; i++) { var di = cd[i]; var lonlat = di.lonlat; - var lonlat2 = [_$lib_539.wrap180(lonlat[0]), lonlat[1]]; - var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)]; - if(polygon.contains(xy)) { - selection.push({ - pointNumber: i, - lon: lonlat[0], - lat: lonlat[1] - }); - di.selected = 1; - } else { - di.selected = 0; + if(lonlat[0] !== __BADNUM_986) { + var lonlat2 = [_$lib_601.wrap180(lonlat[0]), lonlat[1]]; + var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)]; + + if(polygon.contains(xy)) { + selection.push({ + pointNumber: i, + lon: lonlat[0], + lat: lonlat[1] + }); + di.selected = 1; + } else { + di.selected = 0; + } } } } @@ -174988,29 +177202,29 @@ var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { 'use strict'; -var __ScatterMapbox_917 = {}; +var __ScatterMapbox_984 = {}; -__ScatterMapbox_917.attributes = _$attributes_912; -__ScatterMapbox_917.supplyDefaults = _$supplyDefaults_914; -__ScatterMapbox_917.colorbar = _$colorbar_866; -__ScatterMapbox_917.calc = _$calc_901; -__ScatterMapbox_917.plot = _$createScatterMapbox_918; -__ScatterMapbox_917.hoverPoints = _$hoverPoints_916; -__ScatterMapbox_917.eventData = _$eventData_915; -__ScatterMapbox_917.selectPoints = _$selectPoints_919; +__ScatterMapbox_984.attributes = _$attributes_979; +__ScatterMapbox_984.supplyDefaults = _$supplyDefaults_981; +__ScatterMapbox_984.colorbar = _$colorbar_931; +__ScatterMapbox_984.calc = _$calc_966; +__ScatterMapbox_984.plot = _$createScatterMapbox_985; +__ScatterMapbox_984.hoverPoints = _$hoverPoints_983; +__ScatterMapbox_984.eventData = _$eventData_982; +__ScatterMapbox_984.selectPoints = _$selectPoints_986; -__ScatterMapbox_917.style = function(_, cd) { +__ScatterMapbox_984.style = function(_, cd) { if(cd) { var trace = cd[0].trace; trace._glTrace.update(cd); } }; -__ScatterMapbox_917.moduleType = 'trace'; -__ScatterMapbox_917.name = 'scattermapbox'; -__ScatterMapbox_917.basePlotModule = _$mapbox_641; -__ScatterMapbox_917.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike']; -__ScatterMapbox_917.meta = { +__ScatterMapbox_984.moduleType = 'trace'; +__ScatterMapbox_984.name = 'scattermapbox'; +__ScatterMapbox_984.basePlotModule = _$mapbox_703; +__ScatterMapbox_984.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike']; +__ScatterMapbox_984.meta = { hrName: 'scatter_mapbox', description: [ 'The data visualized as scatter point, lines or marker symbols', @@ -175019,7 +177233,7 @@ __ScatterMapbox_917.meta = { ].join(' ') }; -var _$ScatterMapbox_917 = __ScatterMapbox_917; +var _$ScatterMapbox_984 = __ScatterMapbox_984; /** * Copyright 2012-2018, Plotly, Inc. @@ -175031,7 +177245,7 @@ var _$ScatterMapbox_917 = __ScatterMapbox_917; 'use strict'; -var _$scattermapbox_31 = _$ScatterMapbox_917; +var _$scattermapbox_31 = _$ScatterMapbox_984; /** * Copyright 2012-2018, Plotly, Inc. @@ -175043,7 +177257,7 @@ var _$scattermapbox_31 = _$ScatterMapbox_917; 'use strict'; -var _$constants_648 = { +var _$constants_710 = { attr: 'subplot', name: 'polar', @@ -175087,20 +177301,20 @@ var _$constants_648 = { 'use strict'; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$layout_attributes_596 = require('../cartesian/layout_attributes'); */; -var __domainAttrs_651 = _$domain_610.attributes; -var __extendFlat_651 = _$lib_539.extendFlat; -var __overrideAll_651 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$layout_attributes_659 = require('../cartesian/layout_attributes'); */; +var __domainAttrs_713 = _$domain_672.attributes; +var __extendFlat_713 = _$lib_601.extendFlat; +var __overrideAll_713 = _$edit_types_632.overrideAll; -var axisLineGridAttr = __overrideAll_651({ - color: _$layout_attributes_596.color, - showline: __extendFlat_651({}, _$layout_attributes_596.showline, {dflt: true}), - linecolor: _$layout_attributes_596.linecolor, - linewidth: _$layout_attributes_596.linewidth, - showgrid: __extendFlat_651({}, _$layout_attributes_596.showgrid, {dflt: true}), - gridcolor: _$layout_attributes_596.gridcolor, - gridwidth: _$layout_attributes_596.gridwidth +var axisLineGridAttr = __overrideAll_713({ + color: _$layout_attributes_659.color, + showline: __extendFlat_713({}, _$layout_attributes_659.showline, {dflt: true}), + linecolor: _$layout_attributes_659.linecolor, + linewidth: _$layout_attributes_659.linewidth, + showgrid: __extendFlat_713({}, _$layout_attributes_659.showgrid, {dflt: true}), + gridcolor: _$layout_attributes_659.gridcolor, + gridwidth: _$layout_attributes_659.gridwidth // TODO add spike* attributes down the road @@ -175108,37 +177322,37 @@ var axisLineGridAttr = __overrideAll_651({ }, 'plot', 'from-root'); -var axisTickAttrs = __overrideAll_651({ - tickmode: _$layout_attributes_596.tickmode, - nticks: _$layout_attributes_596.nticks, - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: _$layout_attributes_596.ticks, - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - showtickprefix: _$layout_attributes_596.showtickprefix, - tickprefix: _$layout_attributes_596.tickprefix, - showticksuffix: _$layout_attributes_596.showticksuffix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showexponent: _$layout_attributes_596.showexponent, - exponentformat: _$layout_attributes_596.exponentformat, - separatethousands: _$layout_attributes_596.separatethousands, - tickfont: _$layout_attributes_596.tickfont, - tickangle: _$layout_attributes_596.tickangle, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - layer: _$layout_attributes_596.layer +var axisTickAttrs = __overrideAll_713({ + tickmode: _$layout_attributes_659.tickmode, + nticks: _$layout_attributes_659.nticks, + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: _$layout_attributes_659.ticks, + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + showtickprefix: _$layout_attributes_659.showtickprefix, + tickprefix: _$layout_attributes_659.tickprefix, + showticksuffix: _$layout_attributes_659.showticksuffix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showexponent: _$layout_attributes_659.showexponent, + exponentformat: _$layout_attributes_659.exponentformat, + separatethousands: _$layout_attributes_659.separatethousands, + tickfont: _$layout_attributes_659.tickfont, + tickangle: _$layout_attributes_659.tickangle, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + layer: _$layout_attributes_659.layer }, 'plot', 'from-root'); var radialAxisAttrs = { - visible: __extendFlat_651({}, _$layout_attributes_596.visible, {dflt: true}), - type: _$layout_attributes_596.type, + visible: __extendFlat_713({}, _$layout_attributes_659.visible, {dflt: true}), + type: _$layout_attributes_659.type, - autorange: _$layout_attributes_596.autorange, + autorange: _$layout_attributes_659.autorange, rangemode: { valType: 'enumerated', values: ['tozero', 'nonnegative', 'normal'], @@ -175154,10 +177368,10 @@ var radialAxisAttrs = { 'of the input data (same behavior as for cartesian axes).' ].join(' ') }, - range: _$layout_attributes_596.range, + range: _$layout_attributes_659.range, - categoryorder: _$layout_attributes_596.categoryorder, - categoryarray: _$layout_attributes_596.categoryarray, + categoryorder: _$layout_attributes_659.categoryorder, + categoryarray: _$layout_attributes_659.categoryarray, angle: { valType: 'angle', @@ -175185,11 +177399,11 @@ var radialAxisAttrs = { }, - title: __extendFlat_651({}, _$layout_attributes_596.title, {editType: 'plot', dflt: ''}), - titlefont: __overrideAll_651(_$layout_attributes_596.titlefont, 'plot', 'from-root'), + title: __extendFlat_713({}, _$layout_attributes_659.title, {editType: 'plot', dflt: ''}), + titlefont: __overrideAll_713(_$layout_attributes_659.titlefont, 'plot', 'from-root'), // might need a 'titleside' and even 'titledirection' down the road - hoverformat: _$layout_attributes_596.hoverformat, + hoverformat: _$layout_attributes_659.hoverformat, // More attributes: @@ -175209,7 +177423,7 @@ var radialAxisAttrs = { editType: 'calc' }; -__extendFlat_651( +__extendFlat_713( radialAxisAttrs, // N.B. radialaxis grid lines are circular, @@ -175219,7 +177433,7 @@ __extendFlat_651( ); var angularAxisAttrs = { - visible: __extendFlat_651({}, _$layout_attributes_596.visible, {dflt: true}), + visible: __extendFlat_713({}, _$layout_attributes_659.visible, {dflt: true}), type: { valType: 'enumerated', // 'linear' should maybe be called 'angle' or 'angular' here @@ -175239,8 +177453,8 @@ var angularAxisAttrs = { ].join(' ') }, - categoryorder: _$layout_attributes_596.categoryorder, - categoryarray: _$layout_attributes_596.categoryarray, + categoryorder: _$layout_attributes_659.categoryorder, + categoryarray: _$layout_attributes_659.categoryarray, thetaunit: { valType: 'enumerated', @@ -175300,12 +177514,12 @@ var angularAxisAttrs = { ].join(' ') }, - hoverformat: _$layout_attributes_596.hoverformat, + hoverformat: _$layout_attributes_659.hoverformat, editType: 'calc' }; -__extendFlat_651( +__extendFlat_713( angularAxisAttrs, // N.B. angular grid lines are straight lines from circle center to outer bound @@ -175316,13 +177530,13 @@ __extendFlat_651( axisTickAttrs ); -var _$layout_attributes_651 = { +var _$layout_attributes_713 = { // TODO for x/y/zoom system for paper-based zooming: // x: {}, // y: {}, // zoom: {}, - domain: __domainAttrs_651({name: 'polar', editType: 'plot'}), + domain: __domainAttrs_713({name: 'polar', editType: 'plot'}), sector: { valType: 'info_array', @@ -175344,7 +177558,7 @@ var _$layout_attributes_651 = { valType: 'color', role: 'style', editType: 'plot', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, description: 'Set the background color of the subplot' }, @@ -175357,7 +177571,7 @@ var _$layout_attributes_651 = { editType: 'calc' }; -var _$helpers_649 = {}; +var _$helpers_711 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -175368,11 +177582,11 @@ var _$helpers_649 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -_$helpers_649.setConvertAngular = function setConvertAngular(ax) { +_$helpers_711.setConvertAngular = function setConvertAngular(ax) { var dir = {clockwise: -1, counterclockwise: 1}[ax.direction]; - var rot = _$lib_539.deg2rad(ax.rotation); + var rot = _$lib_601.deg2rad(ax.rotation); var _c2rad; var _rad2c; @@ -175384,11 +177598,11 @@ _$helpers_649.setConvertAngular = function setConvertAngular(ax) { if(ax.type === 'linear') { _c2rad = function(v, unit) { - if(unit === 'degrees') return _$lib_539.deg2rad(v); + if(unit === 'degrees') return _$lib_601.deg2rad(v); return v; }; _rad2c = function(v, unit) { - if(unit === 'degrees') return _$lib_539.rad2deg(v); + if(unit === 'degrees') return _$lib_601.rad2deg(v); return v; }; } @@ -175416,8 +177630,8 @@ _$helpers_649.setConvertAngular = function setConvertAngular(ax) { ax.c2rad = function(v, unit) { return transformRad(_c2rad(v, unit)); }; ax.rad2c = function(v, unit) { return _rad2c(unTransformRad(v), unit); }; - ax.c2deg = function(v, unit) { return _$lib_539.rad2deg(ax.c2rad(v, unit)); }; - ax.deg2c = function(v, unit) { return ax.rad2c(_$lib_539.deg2rad(v), unit); }; + ax.c2deg = function(v, unit) { return _$lib_601.rad2deg(ax.c2rad(v, unit)); }; + ax.deg2c = function(v, unit) { return ax.rad2c(_$lib_601.deg2rad(v), unit); }; }; /** @@ -175430,33 +177644,32 @@ _$helpers_649.setConvertAngular = function setConvertAngular(ax) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../subplot_defaults'); */; -var __getSubplotData_652 = _$get_data_621.getSubplotData; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../subplot_defaults'); */; +var __getSubplotData_714 = _$get_data_683.getSubplotData; -/* removed: var _$handleTickValueDefaults_606 = require('../cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('../cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../cartesian/tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_588 = require('../cartesian/category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_598 = require('../cartesian/line_grid_defaults'); */; -/* removed: var _$autoType_585 = require('../cartesian/axis_autotype'); */; -/* removed: var _$orderedCategories_599 = require('../cartesian/ordered_categories'); */; -/* removed: var _$setConvert_603 = require('../cartesian/set_convert'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('../cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../cartesian/tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_651 = require('../cartesian/category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_661 = require('../cartesian/line_grid_defaults'); */; +/* removed: var _$autoType_648 = require('../cartesian/axis_autotype'); */; +/* removed: var _$setConvert_665 = require('../cartesian/set_convert'); */; -var setConvertAngular = _$helpers_649.setConvertAngular; -/* removed: var _$layout_attributes_651 = require('./layout_attributes'); */; -/* removed: var _$constants_648 = require('./constants'); */; -var axisNames = _$constants_648.axisNames; +var setConvertAngular = _$helpers_711.setConvertAngular; +/* removed: var _$layout_attributes_713 = require('./layout_attributes'); */; +/* removed: var _$constants_710 = require('./constants'); */; +var axisNames = _$constants_710.axisNames; -function __handleDefaults_652(contIn, contOut, coerce, opts) { +function __handleDefaults_714(contIn, contOut, coerce, opts) { var bgColor = coerce('bgcolor'); - opts.bgColor = _$color_411.combine(bgColor, opts.paper_bgcolor); + opts.bgColor = _$color_473.combine(bgColor, opts.paper_bgcolor); var sector = coerce('sector'); // could optimize, subplotData is not always needed! - var subplotData = __getSubplotData_652(opts.fullData, _$constants_648.name, opts.id); + var subplotData = __getSubplotData_714(opts.fullData, _$constants_710.name, opts.id); var layoutOut = opts.layoutOut; var axName; @@ -175467,7 +177680,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { for(var i = 0; i < axisNames.length; i++) { axName = axisNames[i]; - if(!_$lib_539.isPlainObject(contIn[axName])) { + if(!_$lib_601.isPlainObject(contIn[axName])) { contIn[axName] = {}; } @@ -175475,16 +177688,16 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { var axOut = contOut[axName] = {}; axOut._id = axOut._name = axName; - var dataAttr = _$constants_648.axisName2dataArray[axName]; + var dataAttr = _$constants_710.axisName2dataArray[axName]; var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr); - _$handleCategoryOrderDefaults_588(axIn, axOut, coerceAxis); - axOut._initialCategories = axType === 'category' ? - _$orderedCategories_599(dataAttr, axOut.categoryorder, axOut.categoryarray, subplotData) : - []; + _$handleCategoryOrderDefaults_651(axIn, axOut, coerceAxis, { + axData: subplotData, + dataAttr: dataAttr + }); var visible = coerceAxis('visible'); - _$setConvert_603(axOut, layoutOut); + _$setConvert_665(axOut, layoutOut); var dfltColor; var dfltFontColor; @@ -175521,7 +177734,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { coerceAxis('angle', sector[0]); coerceAxis('title'); - _$lib_539.coerceFont(coerceAxis, 'titlefont', { + _$lib_601.coerceFont(coerceAxis, 'titlefont', { family: opts.font.family, size: Math.round(opts.font.size * 1.2), color: dfltFontColor @@ -175539,7 +177752,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { // when we do add support for data angular axes, the new // behavior won't conflict with existing behavior if(axType === 'date') { - _$lib_539.log('Polar plots do not support date angular axes yet.'); + _$lib_601.log('Polar plots do not support date angular axes yet.'); for(var j = 0; j < subplotData.length; j++) { subplotData[j].visible = false; @@ -175564,15 +177777,15 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { } if(visible) { - _$handleTickValueDefaults_606(axIn, axOut, coerceAxis, axOut.type); - _$handleTickLabelDefaults_604(axIn, axOut, coerceAxis, axOut.type, { + _$handleTickValueDefaults_668(axIn, axOut, coerceAxis, axOut.type); + _$handleTickLabelDefaults_666(axIn, axOut, coerceAxis, axOut.type, { tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined }); - _$handleTickDefaults_605(axIn, axOut, coerceAxis, {outerTicks: true}); + _$handleTickDefaults_667(axIn, axOut, coerceAxis, {outerTicks: true}); var showTickLabels = coerceAxis('showticklabels'); if(showTickLabels) { - _$lib_539.coerceFont(coerceAxis, 'tickfont', { + _$lib_601.coerceFont(coerceAxis, 'tickfont', { family: opts.font.family, size: opts.font.size, color: dfltFontColor @@ -175581,7 +177794,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { coerceAxis('tickformat'); } - _$handleLineGridDefaults_598(axIn, axOut, coerceAxis, { + _$handleLineGridDefaults_661(axIn, axOut, coerceAxis, { dfltColor: dfltColor, bgColor: opts.bgColor, // default grid color is darker here (60%, vs cartesian default ~91%) @@ -175590,7 +177803,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { showLine: true, showGrid: true, noZeroLine: true, - attributes: _$layout_attributes_651[axName] + attributes: _$layout_attributes_713[axName] }); coerceAxis('layer'); @@ -175616,7 +177829,7 @@ function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) { } if(trace) { - axOut.type = _$autoType_585(trace[dataAttr], 'gregorian'); + axOut.type = _$autoType_648(trace[dataAttr], 'gregorian'); } if(axOut.type === '-') { @@ -175633,11 +177846,11 @@ function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) { return axOut.type; } -var _$supplyLayoutDefaults_652 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { - type: _$constants_648.name, - attributes: _$layout_attributes_651, - handleDefaults: __handleDefaults_652, +var _$supplyLayoutDefaults_714 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { + type: _$constants_710.name, + attributes: _$layout_attributes_713, + handleDefaults: __handleDefaults_714, font: layoutOut.font, paper_bgcolor: layoutOut.paper_bgcolor, fullData: fullData, @@ -175655,35 +177868,36 @@ var _$supplyLayoutDefaults_652 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$plots_647 = require('../plots'); */; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; -var __doAutoRange_659 = _$autorange_583.doAutoRange; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$dragbox_592 = require('../cartesian/dragbox'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$titles_504 = require('../../components/titles'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$plots_709 = require('../plots'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; +var __doAutoRange_721 = _$autorange_646.doAutoRange; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +/* removed: var _$dragbox_655 = require('../cartesian/dragbox'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$titles_566 = require('../../components/titles'); */; +var __prepSelect_721 = _$select_664.prepSelect; +var __clearSelect_721 = _$select_664.clearSelect; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; -var __MID_SHIFT_659 = _$alignment_511.MID_SHIFT; +var __MID_SHIFT_721 = _$alignment_573.MID_SHIFT; -var ____659 = _$lib_539._; -var deg2rad = _$lib_539.deg2rad; -var rad2deg = _$lib_539.rad2deg; -var wrap360 = _$lib_539.wrap360; -var __wrap180_659 = _$lib_539.wrap180; +var ____721 = _$lib_601._; +var deg2rad = _$lib_601.deg2rad; +var rad2deg = _$lib_601.rad2deg; +var wrap360 = _$lib_601.wrap360; +var __wrap180_721 = _$lib_601.wrap180; -var __setConvertAngular_659 = _$helpers_649.setConvertAngular; -/* removed: var _$constants_648 = require('./constants'); */; +var __setConvertAngular_721 = _$helpers_711.setConvertAngular; +/* removed: var _$constants_710 = require('./constants'); */; -function __Polar_659(gd, id) { +function __Polar_721(gd, id) { this.id = id; this.gd = gd; @@ -175711,13 +177925,13 @@ function __Polar_659(gd, id) { this.angularTickLayout = null; } -var __proto_659 = __Polar_659.prototype; +var __proto_721 = __Polar_721.prototype; -var _$createPolar_659 = function createPolar(gd, id) { - return new __Polar_659(gd, id); +var _$createPolar_721 = function createPolar(gd, id) { + return new __Polar_721(gd, id); }; -__proto_659.plot = function(polarCalcData, fullLayout) { +__proto_721.plot = function(polarCalcData, fullLayout) { var _this = this; var polarLayout = fullLayout[_this.id]; @@ -175732,16 +177946,16 @@ __proto_659.plot = function(polarCalcData, fullLayout) { _this.updateLayers(fullLayout, polarLayout); _this.updateLayout(fullLayout, polarLayout); - _$plots_647.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout); + _$plots_709.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout); _this.updateFx(fullLayout, polarLayout); }; -__proto_659.updateLayers = function(fullLayout, polarLayout) { +__proto_721.updateLayers = function(fullLayout, polarLayout) { var _this = this; var layers = _this.layers; var radialLayout = polarLayout.radialaxis; var angularLayout = polarLayout.angularaxis; - var layerNames = _$constants_648.layerNames; + var layerNames = _$constants_710.layerNames; var frontPlotIndex = layerNames.indexOf('frontplot'); var layerData = layerNames.slice(0, frontPlotIndex); @@ -175766,7 +177980,7 @@ __proto_659.updateLayers = function(fullLayout, polarLayout) { join.enter().append('g') .attr('class', function(d) { return 'polarsublayer ' + d;}) .each(function(d) { - var sel = layers[d] = _$d3_127.select(this); + var sel = layers[d] = _$d3_130.select(this); switch(d) { case 'frontplot': @@ -175798,7 +178012,7 @@ __proto_659.updateLayers = function(fullLayout, polarLayout) { join.order(); }; -__proto_659.updateLayout = function(fullLayout, polarLayout) { +__proto_721.updateLayout = function(fullLayout, polarLayout) { var _this = this; var layers = _this.layers; var gs = fullLayout._size; @@ -175866,7 +178080,7 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { range: [sectorBBox[0] * rSpan, sectorBBox[2] * rSpan], domain: xDomain2 }; - _$axes_584.setConvert(xaxis, fullLayout); + _$axes_647.setConvert(xaxis, fullLayout); xaxis.setScale(); var yaxis = _this.yaxis = { @@ -175875,7 +178089,7 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { range: [sectorBBox[1] * rSpan, sectorBBox[3] * rSpan], domain: yDomain2 }; - _$axes_584.setConvert(yaxis, fullLayout); + _$axes_647.setConvert(yaxis, fullLayout); yaxis.setScale(); xaxis.isPtWithinRange = function(d) { return _this.isPtWithinSector(d); }; @@ -175883,13 +178097,13 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { layers.frontplot .attr('transform', strTranslate(xOffset2, yOffset2)) - .call(_$drawing_436.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.circle); + .call(_$drawing_498.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.circle); layers.bgcircle.attr({ d: pathSectorClosed(radius, sector), transform: strTranslate(cx, cy) }) - .call(_$color_411.fill, polarLayout.bgcolor); + .call(_$color_473.fill, polarLayout.bgcolor); _this.clipPaths.circle.select('path') .attr('d', pathSectorClosed(radius, sector)) @@ -175900,7 +178114,7 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { _this.framework.selectAll('.crisp').classed('crisp', 0); }; -__proto_659.updateRadialAxis = function(fullLayout, polarLayout) { +__proto_721.updateRadialAxis = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -175914,7 +178128,7 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { _this.fillViewInitialKey('radialaxis.angle', radialLayout.angle); - var ax = _this.radialAxis = _$lib_539.extendFlat({}, radialLayout, { + var ax = _this.radialAxis = _$lib_601.extendFlat({}, radialLayout, { _axislayer: layers['radial-axis'], _gridlayer: layers['radial-grid'], @@ -175940,7 +178154,7 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { }); setScale(ax, radialLayout, fullLayout); - __doAutoRange_659(ax); + __doAutoRange_721(ax); radialLayout.range = ax.range.slice(); radialLayout._input.range = ax.range.slice(); _this.fillViewInitialKey('radialaxis.range', ax.range.slice()); @@ -175970,7 +178184,7 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { _this.radialTickLayout = newTickLayout; } - _$axes_584.doTicks(gd, ax, true); + _$axes_647.doTicks(gd, ax, true); updateElement(layers['radial-axis'], radialLayout.showticklabels || radialLayout.ticks, { transform: strTranslate(cx, cy) + strRotate(-radialLayout.angle) @@ -175991,10 +178205,10 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { transform: strTranslate(cx, cy) + strRotate(-radialLayout.angle) }) .attr('stroke-width', radialLayout.linewidth) - .call(_$color_411.stroke, radialLayout.linecolor); + .call(_$color_473.stroke, radialLayout.linecolor); }; -__proto_659.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { +__proto_721.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { var _this = this; var gd = _this.gd; var radius = _this.radius; @@ -176010,17 +178224,17 @@ __proto_659.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { var pad = 0; if(radialLayout.title) { - var h = _$drawing_436.bBox(_this.layers['radial-axis'].node()).height; + var h = _$drawing_498.bBox(_this.layers['radial-axis'].node()).height; var ts = radialLayout.titlefont.size; pad = radialLayout.side === 'counterclockwise' ? -h - ts * 0.4 : h + ts * 0.8; } - _this.layers['radial-axis-title'] = _$titles_504.draw(gd, titleClass, { + _this.layers['radial-axis-title'] = _$titles_566.draw(gd, titleClass, { propContainer: radialLayout, propName: _this.id + '.radialaxis.title', - placeholder: ____659(gd, 'Click to enter radial axis title'), + placeholder: ____721(gd, 'Click to enter radial axis title'), attributes: { x: cx + (radius / 2) * cosa + pad * sina, y: cy - (radius / 2) * sina + pad * cosa, @@ -176030,7 +178244,7 @@ __proto_659.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { }); }; -__proto_659.updateAngularAxis = function(fullLayout, polarLayout) { +__proto_721.updateAngularAxis = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -176043,7 +178257,7 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { _this.fillViewInitialKey('angularaxis.rotation', angularLayout.rotation); - var ax = _this.angularAxis = _$lib_539.extendFlat({}, angularLayout, { + var ax = _this.angularAxis = _$lib_601.extendFlat({}, angularLayout, { _axislayer: layers['angular-axis'], _gridlayer: layers['angular-grid'], @@ -176122,7 +178336,7 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { var out = strTranslate(cx + xy[0], cy - xy[1]); // must also rotate ticks, but don't rotate labels and grid lines - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); if(sel && sel.node() && sel.classed('ticks')) { out += strRotate(-rad2deg(rad)); } @@ -176157,7 +178371,7 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { var labelShift = ax._labelShift; var pad = ax._pad; - var offset4tx = d.dy + d.fontSize * __MID_SHIFT_659 - labelShift; + var offset4tx = d.dy + d.fontSize * __MID_SHIFT_721 - labelShift; var offset4tick = -Math.sin(rad) * (labelStandoff + pad + offset4fontsize * d.fontSize); return offset4tx + offset4tick; @@ -176176,17 +178390,17 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { _this.angularTickLayout = newTickLayout; } - _$axes_584.doTicks(gd, ax, true); + _$axes_647.doTicks(gd, ax, true); updateElement(layers['angular-line'].select('path'), angularLayout.showline, { d: pathSectorClosed(radius, sector), transform: strTranslate(cx, cy) }) .attr('stroke-width', angularLayout.linewidth) - .call(_$color_411.stroke, angularLayout.linecolor); + .call(_$color_473.stroke, angularLayout.linecolor); }; -__proto_659.updateFx = function(fullLayout, polarLayout) { +__proto_721.updateFx = function(fullLayout, polarLayout) { if(!this.gd._context.staticPlot) { this.updateAngularDrag(fullLayout, polarLayout); this.updateRadialDrag(fullLayout, polarLayout); @@ -176194,13 +178408,13 @@ __proto_659.updateFx = function(fullLayout, polarLayout) { } }; -__proto_659.updateMainDrag = function(fullLayout, polarLayout) { +__proto_721.updateMainDrag = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; var zoomlayer = fullLayout._zoomlayer; - var MINZOOM = _$constants_648.MINZOOM; - var OFFEDGE = _$constants_648.OFFEDGE; + var MINZOOM = _$constants_710.MINZOOM; + var OFFEDGE = _$constants_710.OFFEDGE; var radius = _this.radius; var cx = _this.cx; var cy = _this.cy; @@ -176208,9 +178422,9 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { var cyy = _this.cyy; var sector = polarLayout.sector; - var mainDrag = _$dragbox_592.makeDragger(layers, 'path', 'maindrag', 'crosshair'); + var mainDrag = _$dragbox_655.makeDragger(layers, 'path', 'maindrag', 'crosshair'); - _$d3_127.select(mainDrag) + _$d3_130.select(mainDrag) .attr('d', pathSectorClosed(radius, sector)) .attr('transform', strTranslate(cx, cy)); @@ -176250,8 +178464,8 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { } function pathCorner(r, a) { - var clen = _$constants_648.cornerLen; - var chw = _$constants_648.cornerHalfWidth; + var clen = _$constants_710.cornerLen; + var chw = _$constants_710.cornerHalfWidth; if(r === 0) return pathSectorClosed(2 * chw, sector); @@ -176276,12 +178490,12 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { dimmed = false; var polarLayoutNow = gd._fullLayout[_this.id]; - lum = _$tinycolor_352(polarLayoutNow.bgcolor).getLuminance(); + lum = _$tinycolor_414(polarLayoutNow.bgcolor).getLuminance(); - zb = _$dragbox_592.makeZoombox(zoomlayer, lum, cx, cy, path0); + zb = _$dragbox_655.makeZoombox(zoomlayer, lum, cx, cy, path0); zb.attr('fill-rule', 'evenodd'); - corners = _$dragbox_592.makeCorners(zoomlayer, cx, cy); - _$dragbox_592.clearSelect(zoomlayer); + corners = _$dragbox_655.makeCorners(zoomlayer, cx, cy); + __clearSelect_721(zoomlayer); } function zoomMove(dx, dy) { @@ -176325,16 +178539,16 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { zb.attr('d', path1); corners.attr('d', cpath); - _$dragbox_592.transitionZoombox(zb, corners, dimmed, lum); + _$dragbox_655.transitionZoombox(zb, corners, dimmed, lum); dimmed = true; } function zoomDone() { - _$dragbox_592.removeZoombox(gd); + _$dragbox_655.removeZoombox(gd); if(r0 === null || r1 === null) return; - _$dragbox_592.showDoubleClickNotifier(gd); + _$dragbox_655.showDoubleClickNotifier(gd); var radialAxis = _this.radialAxis; var radialRange = radialAxis.range; @@ -176345,7 +178559,7 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { radialRange[0] + r1 * drange / radius ]; - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); } dragOpts.prepFn = function(evt, startX, startY) { @@ -176363,13 +178577,13 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { break; case 'select': case 'lasso': - _$prepSelect_602(evt, startX, startY, dragOpts, dragModeNow); + __prepSelect_721(evt, startX, startY, dragOpts, dragModeNow); break; } }; dragOpts.clickFn = function(numClicks, evt) { - _$dragbox_592.removeZoombox(gd); + _$dragbox_655.removeZoombox(gd); // TODO double once vs twice logic (autorange vs fixed range) if(numClicks === 2) { @@ -176379,27 +178593,27 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { } gd.emit('plotly_doubleclick', null); - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); } - _$fx_453.click(gd, evt, _this.id); + _$fx_515.click(gd, evt, _this.id); }; mainDrag.onmousemove = function(evt) { - _$fx_453.hover(gd, evt, _this.id); + _$fx_515.hover(gd, evt, _this.id); gd._fullLayout._lasthover = mainDrag; gd._fullLayout._hoversubplot = _this.id; }; mainDrag.onmouseout = function(evt) { if(gd._dragging) return; - _$dragelement_433.unhover(gd, evt); + _$dragelement_495.unhover(gd, evt); }; - _$dragelement_433.init(dragOpts); + _$dragelement_495.init(dragOpts); }; -__proto_659.updateRadialDrag = function(fullLayout, polarLayout) { +__proto_721.updateRadialDrag = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -176411,17 +178625,17 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { var angle0 = deg2rad(radialLayout.angle); var range0 = radialAxis.range.slice(); var drange = range0[1] - range0[0]; - var bl = _$constants_648.radialDragBoxSize; + var bl = _$constants_710.radialDragBoxSize; var bl2 = bl / 2; if(!radialLayout.visible) return; - var radialDrag = _$dragbox_592.makeRectDragger(layers, 'radialdrag', 'crosshair', -bl2, -bl2, bl, bl); + var radialDrag = _$dragbox_655.makeRectDragger(layers, 'radialdrag', 'crosshair', -bl2, -bl2, bl, bl); var dragOpts = {element: radialDrag, gd: gd}; var tx = cx + (radius + bl2) * Math.cos(angle0); var ty = cy - (radius + bl2) * Math.sin(angle0); - _$d3_127.select(radialDrag) + _$d3_130.select(radialDrag) .attr('transform', strTranslate(tx, ty)); // move function (either rotate or re-range flavor) @@ -176437,7 +178651,7 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { } else { var dvec = [dx, -dy]; var rvec = [Math.cos(angle0), Math.sin(angle0)]; - var comp = Math.abs(_$lib_539.dot(dvec, rvec) / Math.sqrt(_$lib_539.dot(dvec, dvec))); + var comp = Math.abs(_$lib_601.dot(dvec, rvec) / Math.sqrt(_$lib_601.dot(dvec, dvec))); // mostly perpendicular motions rotate, // mostly parallel motions re-range @@ -176449,9 +178663,9 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { function doneFn() { if(angle1 !== null) { - _$registry_668.call('relayout', gd, _this.id + '.radialaxis.angle', angle1); + _$registry_731.call('relayout', gd, _this.id + '.radialaxis.angle', angle1); } else if(rng1 !== null) { - _$registry_668.call('relayout', gd, _this.id + '.radialaxis.range[1]', rng1); + _$registry_731.call('relayout', gd, _this.id + '.radialaxis.range[1]', rng1); } } @@ -176472,14 +178686,14 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { function rerangeMove(dx, dy) { // project (dx, dy) unto unit radial axis vector - var dr = _$lib_539.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]); + var dr = _$lib_601.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]); var rprime = range0[1] - drange * dr / radius * 0.75; // make sure new range[1] does not change the range[0] -> range[1] sign if((drange > 0) !== (rprime > range0[0])) return; rng1 = radialAxis.range[1] = rprime; - _$axes_584.doTicks(gd, _this.radialAxis, true); + _$axes_647.doTicks(gd, _this.radialAxis, true); layers['radial-grid'] .attr('transform', strTranslate(cx, cy)) .selectAll('path').attr('transform', null); @@ -176493,13 +178707,13 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { for(var k in _this.traceHash) { var moduleCalcData = _this.traceHash[k]; - var moduleCalcDataVisible = _$lib_539.filterVisible(moduleCalcData); + var moduleCalcDataVisible = _$lib_601.filterVisible(moduleCalcData); var _module = moduleCalcData[0][0].trace._module; var polarLayoutNow = gd._fullLayout[_this.id]; _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow); - if(!_$registry_668.traceIs(k, 'gl')) { + if(!_$registry_731.traceIs(k, 'gl')) { for(var i = 0; i < moduleCalcDataVisible.length; i++) { _module.style(gd, moduleCalcDataVisible[i]); } @@ -176515,21 +178729,21 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { dragOpts.moveFn = moveFn; dragOpts.doneFn = doneFn; - _$dragbox_592.clearSelect(fullLayout._zoomlayer); + __clearSelect_721(fullLayout._zoomlayer); }; dragOpts.clampFn = function(dx, dy) { - if(Math.sqrt(dx * dx + dy * dy) < _$constants_648.MINDRAG) { + if(Math.sqrt(dx * dx + dy * dy) < _$constants_710.MINDRAG) { dx = 0; dy = 0; } return [dx, dy]; }; - _$dragelement_433.init(dragOpts); + _$dragelement_495.init(dragOpts); }; -__proto_659.updateAngularDrag = function(fullLayout, polarLayout) { +__proto_721.updateAngularDrag = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -176539,15 +178753,15 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { var cxx = _this.cxx; var cyy = _this.cyy; var sector = polarLayout.sector; - var dbs = _$constants_648.angularDragBoxSize; + var dbs = _$constants_710.angularDragBoxSize; - var angularDrag = _$dragbox_592.makeDragger(layers, 'path', 'angulardrag', 'move'); + var angularDrag = _$dragbox_655.makeDragger(layers, 'path', 'angulardrag', 'move'); var dragOpts = {element: angularDrag, gd: gd}; - _$d3_127.select(angularDrag) + _$d3_130.select(angularDrag) .attr('d', pathAnnulus(radius, radius + dbs, sector)) .attr('transform', strTranslate(cx, cy)) - .call(_$setCursor_558, 'move'); + .call(_$setCursor_621, 'move'); function xy2a(x, y) { return Math.atan2(cyy + dbs - y, x - cxx - dbs); @@ -176584,20 +178798,20 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { // 'un-rotate' marker and text points scatterPoints.each(function() { - var sel = _$d3_127.select(this); - var xy = _$drawing_436.getTranslate(sel); + var sel = _$d3_130.select(this); + var xy = _$drawing_498.getTranslate(sel); sel.attr('transform', strTranslate(xy.x, xy.y) + strRotate([da])); }); scatterTextPoints.each(function() { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var tx = sel.select('text'); - var xy = _$drawing_436.getTranslate(sel); + var xy = _$drawing_498.getTranslate(sel); // N.B rotate -> translate ordering matters sel.attr('transform', strRotate([da, tx.attr('x'), tx.attr('y')]) + strTranslate(xy.x, xy.y)); }); var angularAxis = _this.angularAxis; - angularAxis.rotation = __wrap180_659(rot1); + angularAxis.rotation = __wrap180_721(rot1); if(angularAxis.type === 'linear' && !isFullCircle(sector)) { angularAxis.range = sector0 @@ -176606,19 +178820,19 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { .map(rad2deg); } - __setConvertAngular_659(angularAxis); - _$axes_584.doTicks(gd, angularAxis, true); + __setConvertAngular_721(angularAxis); + _$axes_647.doTicks(gd, angularAxis, true); if(_this._hasClipOnAxisFalse && !isFullCircle(sector)) { // mutate sector to trick isPtWithinSector _this.sector = [sector0[0] - da, sector0[1] - da]; - scatterTraces.call(_$drawing_436.hideOutsideRangePoints, _this); + scatterTraces.call(_$drawing_498.hideOutsideRangePoints, _this); } for(var k in _this.traceHash) { - if(_$registry_668.traceIs(k, 'gl')) { + if(_$registry_731.traceIs(k, 'gl')) { var moduleCalcData = _this.traceHash[k]; - var moduleCalcDataVisible = _$lib_539.filterVisible(moduleCalcData); + var moduleCalcDataVisible = _$lib_601.filterVisible(moduleCalcData); var _module = moduleCalcData[0][0].trace._module; var polarLayoutNow = gd._fullLayout[_this.id]; @@ -176631,7 +178845,7 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { scatterTextPoints.select('text').attr('transform', null); var updateObj = {}; updateObj[_this.id + '.angularaxis.rotation'] = rot1; - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); } dragOpts.prepFn = function(evt, startX, startY) { @@ -176647,13 +178861,13 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { dragOpts.moveFn = moveFn; dragOpts.doneFn = doneFn; - _$dragbox_592.clearSelect(fullLayout._zoomlayer); + __clearSelect_721(fullLayout._zoomlayer); }; - _$dragelement_433.init(dragOpts); + _$dragelement_495.init(dragOpts); }; -__proto_659.isPtWithinSector = function(d) { +__proto_721.isPtWithinSector = function(d) { var sector = this.sector; var radialAxis = this.radialAxis; var radialRange = radialAxis.range; @@ -176684,14 +178898,14 @@ __proto_659.isPtWithinSector = function(d) { ); }; -__proto_659.fillViewInitialKey = function(key, val) { +__proto_721.fillViewInitialKey = function(key, val) { if(!(key in this.viewInitial)) { this.viewInitial[key] = val; } }; function setScale(ax, axLayout, fullLayout) { - _$axes_584.setConvert(ax, fullLayout); + _$axes_647.setConvert(ax, fullLayout); // _min and _max are filled in during Axes.expand // and cleared during Axes.setConvert @@ -176764,7 +178978,7 @@ function computeSectorBBox(sector) { function pathSector(r, sector) { if(isFullCircle(sector)) { - return _$drawing_436.symbolFuncs[0](r); + return _$drawing_498.symbolFuncs[0](r); } var xs = r * Math.cos(deg2rad(sector[0])); @@ -176847,17 +179061,17 @@ function strRotate(angle) { // because Math.sign(Math.cos(Math.PI / 2)) === 1 // oh javascript ;) -function __sign_659(v) { +function __sign_721(v) { return Math.abs(v) < 1e-10 ? 0 : v > 0 ? 1 : -1; } function signCos(v) { - return __sign_659(Math.cos(v)); + return __sign_721(Math.cos(v)); } function signSin(v) { - return __sign_659(Math.sin(v)); + return __sign_721(Math.sin(v)); } /** @@ -176870,21 +179084,21 @@ function signSin(v) { 'use strict'; -var __getSubplotCalcData_650 = _$get_data_621.getSubplotCalcData; -var __counterRegex_650 = _$lib_539.counterRegex; +var __getSubplotCalcData_712 = _$get_data_683.getSubplotCalcData; +var __counterRegex_712 = _$lib_601.counterRegex; -/* removed: var _$createPolar_659 = require('./polar'); */; -/* removed: var _$constants_648 = require('./constants'); */; +/* removed: var _$createPolar_721 = require('./polar'); */; +/* removed: var _$constants_710 = require('./constants'); */; -var attr = _$constants_648.attr; -var __name_650 = _$constants_648.name; -var counter = __counterRegex_650(__name_650); +var attr = _$constants_710.attr; +var __name_712 = _$constants_710.name; +var counter = __counterRegex_712(__name_712); -var __attributes_650 = {}; -__attributes_650[attr] = { +var __attributes_712 = {}; +__attributes_712[attr] = { valType: 'subplotid', role: 'info', - dflt: __name_650, + dflt: __name_712, editType: 'calc', description: [ 'Sets a reference between this trace\'s data coordinates and', @@ -176894,18 +179108,18 @@ __attributes_650[attr] = { ].join(' ') }; -function __plot_650(gd) { +function __plot_712(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; - var subplotIds = fullLayout._subplots[__name_650]; + var subplotIds = fullLayout._subplots[__name_712]; for(var i = 0; i < subplotIds.length; i++) { var id = subplotIds[i]; - var subplotCalcData = __getSubplotCalcData_650(calcData, __name_650, id); + var subplotCalcData = __getSubplotCalcData_712(calcData, __name_712, id); var subplot = fullLayout[id]._subplot; if(!subplot) { - subplot = _$createPolar_659(gd, id); + subplot = _$createPolar_721(gd, id); fullLayout[id]._subplot = subplot; } @@ -176914,7 +179128,7 @@ function __plot_650(gd) { } function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldIds = oldFullLayout._subplots[__name_650] || []; + var oldIds = oldFullLayout._subplots[__name_712] || []; for(var i = 0; i < oldIds.length; i++) { var id = oldIds[i]; @@ -176931,18 +179145,18 @@ function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) { } } -var _$polar_650 = { +var _$polar_712 = { attr: attr, - name: __name_650, - idRoot: __name_650, + name: __name_712, + idRoot: __name_712, idRegex: counter, attrRegex: counter, - attributes: __attributes_650, - layoutAttributes: _$layout_attributes_651, - supplyLayoutDefaults: _$supplyLayoutDefaults_652, - plot: __plot_650, + attributes: __attributes_712, + layoutAttributes: _$layout_attributes_713, + supplyLayoutDefaults: _$supplyLayoutDefaults_714, + plot: __plot_712, clean: clean, - toSVG: _$cartesian_595.toSVG + toSVG: _$cartesian_658.toSVG }; /** @@ -176955,13 +179169,13 @@ var _$polar_650 = { 'use strict'; -var __extendFlat_920 = _$extend_528.extendFlat; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -var __lineAttrs_920 = _$attributes_862.line; +var __extendFlat_987 = _$extend_590.extendFlat; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +var __lineAttrs_987 = _$attributes_927.line; -var _$attributes_920 = { - mode: _$attributes_862.mode, +var _$attributes_987 = { + mode: _$attributes_927.mode, r: { valType: 'data_array', @@ -176987,28 +179201,28 @@ var _$attributes_920 = { ].join(' ') }, - text: _$attributes_862.text, - hovertext: _$attributes_862.hovertext, + text: _$attributes_927.text, + hovertext: _$attributes_927.hovertext, line: { - color: __lineAttrs_920.color, - width: __lineAttrs_920.width, - dash: __lineAttrs_920.dash, - shape: __extendFlat_920({}, __lineAttrs_920.shape, { + color: __lineAttrs_987.color, + width: __lineAttrs_987.width, + dash: __lineAttrs_987.dash, + shape: __extendFlat_987({}, __lineAttrs_987.shape, { values: ['linear', 'spline'] }), - smoothing: __lineAttrs_920.smoothing, + smoothing: __lineAttrs_987.smoothing, editType: 'calc' }, - connectgaps: _$attributes_862.connectgaps, + connectgaps: _$attributes_927.connectgaps, - marker: _$attributes_862.marker, - cliponaxis: __extendFlat_920({}, _$attributes_862.cliponaxis, {dflt: false}), + marker: _$attributes_927.marker, + cliponaxis: __extendFlat_987({}, _$attributes_927.cliponaxis, {dflt: false}), - textposition: _$attributes_862.textposition, - textfont: _$attributes_862.textfont, + textposition: _$attributes_927.textposition, + textfont: _$attributes_927.textfont, - fill: __extendFlat_920({}, _$attributes_862.fill, { + fill: __extendFlat_987({}, _$attributes_927.fill, { values: ['none', 'toself', 'tonext'], description: [ 'Sets the area to fill with a solid color.', @@ -177022,20 +179236,20 @@ var _$attributes_920 = { 'used if one trace does not enclose the other.' ].join(' ') }), - fillcolor: _$attributes_862.fillcolor, + fillcolor: _$attributes_927.fillcolor, // TODO error bars // https://stackoverflow.com/a/26597487/4068492 // error_x (error_r, error_theta) // error_y - hoverinfo: __extendFlat_920({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_987({}, _$attributes_644.hoverinfo, { flags: ['r', 'theta', 'text', 'name'] }), - hoveron: _$attributes_862.hoveron, + hoveron: _$attributes_927.hoveron, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected }; /** @@ -177049,17 +179263,17 @@ var _$attributes_920 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __BADNUM_921 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __BADNUM_988 = _$numerical_578.BADNUM; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_921 = _$calc_863.calcMarkerSize; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_988 = _$calc_928.calcMarkerSize; -var _$calc_921 = function calc(gd, trace) { +var _$calc_988 = function calc(gd, trace) { var fullLayout = gd._fullLayout; var subplotId = trace.subplot; var radialAxis = fullLayout[subplotId].radialaxis; @@ -177078,21 +179292,21 @@ var _$calc_921 = function calc(gd, trace) { var theta = thetaArray[i]; var cdi = cd[i] = {}; - if(_$fastIsnumeric_139(r) && _$fastIsnumeric_139(theta)) { + if(_$fastIsnumeric_196(r) && _$fastIsnumeric_196(theta)) { cdi.r = r; cdi.theta = theta; cdi.rad = c2rad(theta); } else { - cdi.r = __BADNUM_921; + cdi.r = __BADNUM_988; } } - var ppad = __calcMarkerSize_921(trace, len); - _$axes_584.expand(radialAxis, rArray, {ppad: ppad}); + var ppad = __calcMarkerSize_988(trace, len); + _$axes_647.expand(radialAxis, rArray, {ppad: ppad}); - _$calcMarkerColorscale_867(trace); - _$arraysToCalcdata_861(cd, trace); - _$calcSelection_864(cd, trace); + _$calcMarkerColorscale_932(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcSelection_929(cd, trace); return cd; }; @@ -177107,21 +179321,21 @@ var _$calc_921 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; -var PTS_LINESONLY = _$constants_868.PTS_LINESONLY; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; +var PTS_LINESONLY = _$constants_933.PTS_LINESONLY; -/* removed: var _$attributes_920 = require('./attributes'); */; +/* removed: var _$attributes_987 = require('./attributes'); */; -var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_989 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_920, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_987, attr, dflt); } var r = coerce('r'); @@ -177140,23 +179354,23 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('hovertext'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -177165,8 +179379,8 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -177174,7 +179388,7 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -177187,12 +179401,12 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$hoverPoints_873 = require('../scatter/hover'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$hoverPoints_938 = require('../scatter/hover'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -function __hoverPoints_923(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_873(pointData, xval, yval, hovermode); +function __hoverPoints_990(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_938(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -177230,13 +179444,13 @@ function makeHoverPointText(cdi, trace, subplot) { // show theta value in unit of angular axis var theta; if(angularAxis.type === 'linear' && trace.thetaunit !== angularAxis.thetaunit) { - theta = angularAxis.thetaunit === 'degrees' ? _$lib_539.rad2deg(rad) : rad; + theta = angularAxis.thetaunit === 'degrees' ? _$lib_601.rad2deg(rad) : rad; } else { theta = cdi.theta; } function textPart(ax, val) { - text.push(ax._hovertitle + ': ' + _$axes_584.tickText(ax, val, 'hover').text); + text.push(ax._hovertitle + ': ' + _$axes_647.tickText(ax, val, 'hover').text); } if(parts.indexOf('all') !== -1) parts = ['r', 'theta']; @@ -177246,8 +179460,8 @@ function makeHoverPointText(cdi, trace, subplot) { return text.join('
'); } -var _$hover_923 = { - hoverPoints: __hoverPoints_923, +var _$hover_990 = { + hoverPoints: __hoverPoints_990, makeHoverPointText: makeHoverPointText }; @@ -177261,10 +179475,10 @@ var _$hover_923 = { 'use strict'; -/* removed: var _$plot_881 = require('../scatter/plot'); */; -var __BADNUM_925 = _$numerical_517.BADNUM; +/* removed: var _$plot_946 = require('../scatter/plot'); */; +var __BADNUM_992 = _$numerical_578.BADNUM; -var _$plot_925 = function plot(gd, subplot, moduleCalcData) { +var _$plot_992 = function plot(gd, subplot, moduleCalcData) { var i, j; var plotinfo = { @@ -177292,7 +179506,7 @@ var _$plot_925 = function plot(gd, subplot, moduleCalcData) { var cdi = moduleCalcData[i][j]; var r = cdi.r; - if(r !== __BADNUM_925) { + if(r !== __BADNUM_992) { // convert to 'r' data to fit with mocked polar x/y axis // which are always `type: 'linear'` var rr = radialAxis.c2r(r) - radialRange[0]; @@ -177308,12 +179522,12 @@ var _$plot_925 = function plot(gd, subplot, moduleCalcData) { } } - cdi.x = __BADNUM_925; - cdi.y = __BADNUM_925; + cdi.x = __BADNUM_992; + cdi.y = __BADNUM_992; } } - _$plot_881(gd, plotinfo, moduleCalcData); + _$plot_946(gd, plotinfo, moduleCalcData); }; /** @@ -177326,19 +179540,19 @@ var _$plot_925 = function plot(gd, subplot, moduleCalcData) { 'use strict'; -var _$scatterpolar_924 = { +var _$scatterpolar_991 = { moduleType: 'trace', name: 'scatterpolar', - basePlotModule: _$polar_650, + basePlotModule: _$polar_712, categories: ['polar', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], - attributes: _$attributes_920, - supplyDefaults: _$supplyDefaults_922, - calc: _$calc_921, - plot: _$plot_925, - style: _$style_883.style, - hoverPoints: _$hover_923.hoverPoints, - selectPoints: _$selectPoints_882, + attributes: _$attributes_987, + supplyDefaults: _$supplyDefaults_989, + calc: _$calc_988, + plot: _$plot_992, + style: _$style_948.style, + hoverPoints: _$hover_990.hoverPoints, + selectPoints: _$selectPoints_947, meta: { hrName: 'scatter_polar', @@ -177364,7 +179578,7 @@ var _$scatterpolar_924 = { 'use strict'; -var _$scatterpolar_32 = _$scatterpolar_924; +var _$scatterpolar_32 = _$scatterpolar_991; /** * Copyright 2012-2018, Plotly, Inc. @@ -177376,32 +179590,32 @@ var _$scatterpolar_32 = _$scatterpolar_924; 'use strict'; -/* removed: var _$attributes_920 = require('../scatterpolar/attributes'); */; -/* removed: var _$attributes_909 = require('../scattergl/attributes'); */; +/* removed: var _$attributes_987 = require('../scatterpolar/attributes'); */; +/* removed: var _$attributes_974 = require('../scattergl/attributes'); */; -var _$attributes_926 = { - mode: _$attributes_920.mode, - r: _$attributes_920.r, - theta: _$attributes_920.theta, - thetaunit: _$attributes_920.thetaunit, +var _$attributes_993 = { + mode: _$attributes_987.mode, + r: _$attributes_987.r, + theta: _$attributes_987.theta, + thetaunit: _$attributes_987.thetaunit, - text: _$attributes_920.text, + text: _$attributes_987.text, // no hovertext - line: _$attributes_909.line, - connectgaps: _$attributes_909.connectgaps, + line: _$attributes_974.line, + connectgaps: _$attributes_974.connectgaps, - marker: _$attributes_909.marker, + marker: _$attributes_974.marker, // no cliponaxis - fill: _$attributes_909.fill, - fillcolor: _$attributes_909.fillcolor, + fill: _$attributes_974.fill, + fillcolor: _$attributes_974.fillcolor, - hoverinfo: _$attributes_920.hoverinfo, - hoveron: _$attributes_920.hoveron, + hoverinfo: _$attributes_987.hoverinfo, + hoveron: _$attributes_987.hoveron, - selected: _$attributes_920.selected, - unselected: _$attributes_920.unselected + selected: _$attributes_987.selected, + unselected: _$attributes_987.unselected }; /** @@ -177414,19 +179628,19 @@ var _$attributes_926 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; -var __PTS_LINESONLY_927 = _$constants_868.PTS_LINESONLY; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; +var __PTS_LINESONLY_994 = _$constants_933.PTS_LINESONLY; -/* removed: var _$attributes_926 = require('./attributes'); */; +/* removed: var _$attributes_993 = require('./attributes'); */; -var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_994 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_926, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_993, attr, dflt); } var r = coerce('r'); @@ -177441,24 +179655,24 @@ var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultCol traceOut._length = len; coerce('thetaunit'); - coerce('mode', len < __PTS_LINESONLY_927 ? 'lines+markers' : 'lines'); + coerce('mode', len < __PTS_LINESONLY_994 ? 'lines+markers' : 'lines'); coerce('text'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); coerce('connectgaps'); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce); dfltHoverOn.push('points'); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -177466,7 +179680,7 @@ var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -177479,16 +179693,18 @@ var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$KDTree_252 = require('kdgrass'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$pointCluster_353 = require('point-cluster'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$scattergl_911 = require('../scattergl'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __makeHoverPointText_928 = _$hover_923.makeHoverPointText; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; +/* removed: var _$scattergl_978 = require('../scattergl'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __makeHoverPointText_995 = _$hover_990.makeHoverPointText; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; -function __calc_928(container, trace) { +var __TOO_MANY_POINTS_995 = _$constants_975.TOO_MANY_POINTS; + +function __calc_995(container, trace) { var layout = container._fullLayout; var subplotId = trace.subplot; var radialAxis = layout[subplotId].radialaxis; @@ -177500,28 +179716,28 @@ function __calc_928(container, trace) { if(trace._length < rArray.length) rArray = rArray.slice(0, trace._length); if(trace._length < thetaArray.length) thetaArray = thetaArray.slice(0, trace._length); - _$calcMarkerColorscale_867(trace); + _$calcMarkerColorscale_932(trace); stash.r = rArray; stash.theta = thetaArray; - _$axes_584.expand(radialAxis, rArray, {tozero: true}); + _$axes_647.expand(radialAxis, rArray, {tozero: true}); if(angularAxis.type !== 'linear') { angularAxis.autorange = true; - _$axes_584.expand(angularAxis, thetaArray); + _$axes_647.expand(angularAxis, thetaArray); delete angularAxis.autorange; } return [{x: false, y: false, t: stash, trace: trace}]; } -function __plot_928(container, subplot, cdata) { +function __plot_995(container, subplot, cdata) { var radialAxis = subplot.radialAxis; var angularAxis = subplot.angularAxis; var rRange = radialAxis.range; - var scene = _$scattergl_911.sceneUpdate(container, subplot); + var scene = _$scattergl_978.sceneUpdate(container, subplot); scene.clear(); cdata.forEach(function(cdscatter, traceIndex) { @@ -177558,7 +179774,7 @@ function __plot_928(container, subplot, cdata) { r = subRArray[i]; theta = subThetaArray[i]; - if(_$fastIsnumeric_139(r) && _$fastIsnumeric_139(theta) && r >= 0) { + if(_$fastIsnumeric_196(r) && _$fastIsnumeric_196(theta) && r >= 0) { rr = radialAxis.c2r(r) - rRange[0]; rad = c2rad(theta); @@ -177569,7 +179785,7 @@ function __plot_928(container, subplot, cdata) { } } - var options = _$scattergl_911.sceneOptions(container, subplot, trace, positions); + var options = _$scattergl_978.sceneOptions(container, subplot, trace, positions); // set flags to create scene renderers if(options.fill && !scene.fill2d) scene.fill2d = true; @@ -177577,8 +179793,15 @@ function __plot_928(container, subplot, cdata) { if(options.line && !scene.line2d) scene.line2d = true; if((options.errorX || options.errorY) && !scene.error2d) scene.error2d = true; + stash.tree = _$pointCluster_353(positions); + + // FIXME: see scattergl.js#109 + if(options.marker && count >= __TOO_MANY_POINTS_995) { + options.marker.cluster = stash.tree; + } + // bring positions to selected/unselected options - if(_$subtypes_884.hasMarkers(trace)) { + if(_$subtypes_949.hasMarkers(trace)) { options.selected.positions = options.unselected.positions = options.marker.positions; } @@ -177593,7 +179816,7 @@ function __plot_928(container, subplot, cdata) { scene.count = cdata.length; // stash scene ref - stash.scene = scene; + stash._scene = scene; stash.index = traceIndex; stash.x = x; stash.y = y; @@ -177603,19 +179826,18 @@ function __plot_928(container, subplot, cdata) { stash.theta = thetaArray; stash.positions = positions; stash.count = count; - stash.tree = _$KDTree_252(positions, 512); }); - return _$scattergl_911.plot(container, subplot, cdata); + return _$scattergl_978.plot(container, subplot, cdata); } -function __hoverPoints_928(pointData, xval, yval, hovermode) { +function __hoverPoints_995(pointData, xval, yval, hovermode) { var cd = pointData.cd; var stash = cd[0].t; var rArray = stash.r; var thetaArray = stash.theta; - var scatterPointData = _$scattergl_911.hoverPoints(pointData, xval, yval, hovermode); + var scatterPointData = _$scattergl_978.hoverPoints(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -177638,25 +179860,25 @@ function __hoverPoints_928(pointData, xval, yval, hovermode) { newPointData.xLabelVal = undefined; newPointData.yLabelVal = undefined; - newPointData.extraText = __makeHoverPointText_928(cdi, trace, subplot); + newPointData.extraText = __makeHoverPointText_995(cdi, trace, subplot); return scatterPointData; } -var _$scatterpolargl_928 = { +var _$scatterpolargl_995 = { moduleType: 'trace', name: 'scatterpolargl', - basePlotModule: _$polar_650, + basePlotModule: _$polar_712, categories: ['gl', 'regl', 'polar', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], - attributes: _$attributes_926, - supplyDefaults: _$supplyDefaults_927, + attributes: _$attributes_993, + supplyDefaults: _$supplyDefaults_994, - calc: __calc_928, - plot: __plot_928, - hoverPoints: __hoverPoints_928, - style: _$scattergl_911.style, - selectPoints: _$scattergl_911.selectPoints, + calc: __calc_995, + plot: __plot_995, + hoverPoints: __hoverPoints_995, + style: _$scattergl_978.style, + selectPoints: _$scattergl_978.selectPoints, meta: { hrName: 'scatter_polar_gl', @@ -177681,7 +179903,7 @@ var _$scatterpolargl_928 = { 'use strict'; -var _$scatterpolargl_33 = _$scatterpolargl_928; +var _$scatterpolargl_33 = _$scatterpolargl_995; /** * Copyright 2012-2018, Plotly, Inc. @@ -177694,7 +179916,7 @@ var _$scatterpolargl_33 = _$scatterpolargl_928; 'use strict'; -var _$attributes_662 = { +var _$attributes_725 = { subplot: { valType: 'subplotid', role: 'info', @@ -177720,46 +179942,46 @@ var _$attributes_662 = { 'use strict'; -/* removed: var _$layout_attributes_596 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_663 = _$extend_528.extendFlat; +/* removed: var _$layout_attributes_659 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_726 = _$extend_590.extendFlat; -var _$axis_attributes_663 = { - title: _$layout_attributes_596.title, - titlefont: _$layout_attributes_596.titlefont, - color: _$layout_attributes_596.color, +var _$axis_attributes_726 = { + title: _$layout_attributes_659.title, + titlefont: _$layout_attributes_659.titlefont, + color: _$layout_attributes_659.color, // ticks - tickmode: _$layout_attributes_596.tickmode, - nticks: __extendFlat_663({}, _$layout_attributes_596.nticks, {dflt: 6, min: 1}), - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: _$layout_attributes_596.ticks, - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - showtickprefix: _$layout_attributes_596.showtickprefix, - tickprefix: _$layout_attributes_596.tickprefix, - showticksuffix: _$layout_attributes_596.showticksuffix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showexponent: _$layout_attributes_596.showexponent, - exponentformat: _$layout_attributes_596.exponentformat, - separatethousands: _$layout_attributes_596.separatethousands, - tickfont: _$layout_attributes_596.tickfont, - tickangle: _$layout_attributes_596.tickangle, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - hoverformat: _$layout_attributes_596.hoverformat, + tickmode: _$layout_attributes_659.tickmode, + nticks: __extendFlat_726({}, _$layout_attributes_659.nticks, {dflt: 6, min: 1}), + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: _$layout_attributes_659.ticks, + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + showtickprefix: _$layout_attributes_659.showtickprefix, + tickprefix: _$layout_attributes_659.tickprefix, + showticksuffix: _$layout_attributes_659.showticksuffix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showexponent: _$layout_attributes_659.showexponent, + exponentformat: _$layout_attributes_659.exponentformat, + separatethousands: _$layout_attributes_659.separatethousands, + tickfont: _$layout_attributes_659.tickfont, + tickangle: _$layout_attributes_659.tickangle, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + hoverformat: _$layout_attributes_659.hoverformat, // lines and grids - showline: __extendFlat_663({}, _$layout_attributes_596.showline, {dflt: true}), - linecolor: _$layout_attributes_596.linecolor, - linewidth: _$layout_attributes_596.linewidth, - showgrid: __extendFlat_663({}, _$layout_attributes_596.showgrid, {dflt: true}), - gridcolor: _$layout_attributes_596.gridcolor, - gridwidth: _$layout_attributes_596.gridwidth, - layer: _$layout_attributes_596.layer, + showline: __extendFlat_726({}, _$layout_attributes_659.showline, {dflt: true}), + linecolor: _$layout_attributes_659.linecolor, + linewidth: _$layout_attributes_659.linewidth, + showgrid: __extendFlat_726({}, _$layout_attributes_659.showgrid, {dflt: true}), + gridcolor: _$layout_attributes_659.gridcolor, + gridwidth: _$layout_attributes_659.gridwidth, + layer: _$layout_attributes_659.layer, // range min: { valType: 'number', @@ -177785,16 +180007,16 @@ var _$axis_attributes_663 = { 'use strict'; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$axis_attributes_663 = require('./axis_attributes'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../../cartesian/tick_label_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('../../cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickValueDefaults_606 = require('../../cartesian/tick_value_defaults'); */; -/* removed: var _$handleLineGridDefaults_598 = require('../../cartesian/line_grid_defaults'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$axis_attributes_726 = require('./axis_attributes'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../../cartesian/tick_label_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('../../cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../../cartesian/tick_value_defaults'); */; +/* removed: var _$handleLineGridDefaults_661 = require('../../cartesian/line_grid_defaults'); */; -var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, containerOut, options) { +var _$supplyLayoutDefaults_727 = function supplyLayoutDefaults(containerIn, containerOut, options) { function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$axis_attributes_663, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$axis_attributes_726, attr, dflt); } containerOut.type = 'linear'; // no other types allowed for ternary @@ -177811,7 +180033,7 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont var title = coerce('title', dfltTitle); containerOut._hovertitle = title === dfltTitle ? title : letterUpper; - _$lib_539.coerceFont(coerce, 'titlefont', { + _$lib_601.coerceFont(coerce, 'titlefont', { family: options.font.family, size: Math.round(options.font.size * 1.2), color: dfltFontColor @@ -177820,14 +180042,14 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont // range is just set by 'min' - max is determined by the other axes mins coerce('min'); - _$handleTickValueDefaults_606(containerIn, containerOut, coerce, 'linear'); - _$handleTickLabelDefaults_604(containerIn, containerOut, coerce, 'linear', {}); - _$handleTickDefaults_605(containerIn, containerOut, coerce, + _$handleTickValueDefaults_668(containerIn, containerOut, coerce, 'linear'); + _$handleTickLabelDefaults_666(containerIn, containerOut, coerce, 'linear', {}); + _$handleTickDefaults_667(containerIn, containerOut, coerce, { outerTicks: true }); var showTickLabels = coerce('showticklabels'); if(showTickLabels) { - _$lib_539.coerceFont(coerce, 'tickfont', { + _$lib_601.coerceFont(coerce, 'tickfont', { family: options.font.family, size: options.font.size, color: dfltFontColor @@ -177836,7 +180058,7 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont coerce('tickformat'); } - _$handleLineGridDefaults_598(containerIn, containerOut, coerce, { + _$handleLineGridDefaults_661(containerIn, containerOut, coerce, { dfltColor: dfltColor, bgColor: options.bgColor, // default grid color is darker here (60%, vs cartesian default ~91%) @@ -177845,7 +180067,7 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont showLine: true, showGrid: true, noZeroLine: true, - attributes: _$axis_attributes_663 + attributes: _$axis_attributes_726 }); coerce('hoverformat'); @@ -177862,18 +180084,18 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont 'use strict'; -/* removed: var _$attributes_410 = require('../../../components/color/attributes'); */; -var __domainAttrs_666 = _$domain_610.attributes; -/* removed: var _$axis_attributes_663 = require('./axis_attributes'); */; -var __overrideAll_666 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_472 = require('../../../components/color/attributes'); */; +var __domainAttrs_729 = _$domain_672.attributes; +/* removed: var _$axis_attributes_726 = require('./axis_attributes'); */; +var __overrideAll_729 = _$edit_types_632.overrideAll; -var _$layout_attributes_666 = __overrideAll_666({ - domain: __domainAttrs_666({name: 'ternary'}), +var _$layout_attributes_729 = __overrideAll_729({ + domain: __domainAttrs_729({name: 'ternary'}), bgcolor: { valType: 'color', role: 'style', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, description: 'Set the background color of the subplot' }, sum: { @@ -177886,9 +180108,9 @@ var _$layout_attributes_666 = __overrideAll_666({ 'and the maximum range of each axis' ].join(' ') }, - aaxis: _$axis_attributes_663, - baxis: _$axis_attributes_663, - caxis: _$axis_attributes_663 + aaxis: _$axis_attributes_726, + baxis: _$axis_attributes_726, + caxis: _$axis_attributes_726 }, 'plot', 'from-root'); /** @@ -177902,18 +180124,18 @@ var _$layout_attributes_666 = __overrideAll_666({ 'use strict'; -/* removed: var _$color_411 = require('../../../components/color'); */; +/* removed: var _$color_473 = require('../../../components/color'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../../subplot_defaults'); */; -/* removed: var _$layout_attributes_666 = require('./layout_attributes'); */; -/* removed: var _$supplyLayoutDefaults_664 = require('./axis_defaults'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../../subplot_defaults'); */; +/* removed: var _$layout_attributes_729 = require('./layout_attributes'); */; +/* removed: var _$supplyLayoutDefaults_727 = require('./axis_defaults'); */; -var __axesNames_665 = ['aaxis', 'baxis', 'caxis']; +var __axesNames_728 = ['aaxis', 'baxis', 'caxis']; -var _$supplyLayoutDefaults_665 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_728 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'ternary', - attributes: _$layout_attributes_666, + attributes: _$layout_attributes_729, handleDefaults: handleTernaryDefaults, font: layoutOut.font, paper_bgcolor: layoutOut.paper_bgcolor @@ -177923,18 +180145,18 @@ var _$supplyLayoutDefaults_665 = function supplyLayoutDefaults(layoutIn, layoutO function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) { var bgColor = coerce('bgcolor'); var sum = coerce('sum'); - options.bgColor = _$color_411.combine(bgColor, options.paper_bgcolor); + options.bgColor = _$color_473.combine(bgColor, options.paper_bgcolor); var axName, containerIn, containerOut; // TODO: allow most (if not all) axis attributes to be set // in the outer container and used as defaults in the individual axes? - for(var j = 0; j < __axesNames_665.length; j++) { - axName = __axesNames_665[j]; + for(var j = 0; j < __axesNames_728.length; j++) { + axName = __axesNames_728[j]; containerIn = ternaryLayoutIn[axName] || {}; containerOut = ternaryLayoutOut[axName] = {_name: axName, type: 'linear'}; - _$supplyLayoutDefaults_664(containerIn, containerOut, options); + _$supplyLayoutDefaults_727(containerIn, containerOut, options); } // if the min values contradict each other, set them all to default (0) @@ -177964,23 +180186,24 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var ____667 = _$lib_539._; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$setConvert_603 = require('../cartesian/set_convert'); */; -var __extendFlat_667 = _$extend_528.extendFlat; -/* removed: var _$plots_647 = require('../plots'); */; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$titles_504 = require('../../components/titles'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; -/* removed: var _$constants_589 = require('../cartesian/constants'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var ____730 = _$lib_601._; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$setConvert_665 = require('../cartesian/set_convert'); */; +var __extendFlat_730 = _$extend_590.extendFlat; +/* removed: var _$plots_709 = require('../plots'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$titles_566 = require('../../components/titles'); */; +var __prepSelect_730 = _$select_664.prepSelect; +var __clearSelect_730 = _$select_664.clearSelect; +/* removed: var _$constants_652 = require('../cartesian/constants'); */; function Ternary(options, fullLayout) { this.id = options.id; @@ -177989,11 +180212,11 @@ function Ternary(options, fullLayout) { this.makeFramework(fullLayout); } -var _$Ternary_667 = Ternary; +var _$Ternary_730 = Ternary; -var __proto_667 = Ternary.prototype; +var __proto_730 = Ternary.prototype; -__proto_667.init = function(fullLayout) { +__proto_730.init = function(fullLayout) { this.container = fullLayout._ternarylayer; this.defs = fullLayout._defs; this.layoutId = fullLayout._uid; @@ -178001,7 +180224,7 @@ __proto_667.init = function(fullLayout) { this.layers = {}; }; -__proto_667.plot = function(ternaryCalcData, fullLayout) { +__proto_730.plot = function(ternaryCalcData, fullLayout) { var _this = this; var ternaryLayout = fullLayout[_this.id]; var graphSize = fullLayout._size; @@ -178018,41 +180241,36 @@ __proto_667.plot = function(ternaryCalcData, fullLayout) { _this.updateLayers(ternaryLayout); _this.adjustLayout(ternaryLayout, graphSize); - _$plots_647.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout); - _this.layers.plotbg.select('path').call(_$color_411.fill, ternaryLayout.bgcolor); + _$plots_709.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout); + _this.layers.plotbg.select('path').call(_$color_473.fill, ternaryLayout.bgcolor); }; -__proto_667.makeFramework = function(fullLayout) { +__proto_730.makeFramework = function(fullLayout) { var _this = this; 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 = fullLayout._clips.selectAll('#' + clipId) - .data([0]); - _this.clipDef.enter().append('clipPath').attr('id', clipId) - .append('path').attr('d', 'M0,0Z'); + _this.clipDef = _$lib_601.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.append('path').attr('d', 'M0,0Z'); + }); // 'relative' clippath (i.e. no translation) for this ternary subplot - var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id; - _this.clipDefRelative = fullLayout._clips.selectAll('#' + clipIdRelative) - .data([0]); - _this.clipDefRelative.enter().append('clipPath').attr('id', clipIdRelative) - .append('path').attr('d', 'M0,0Z'); + _this.clipDefRelative = _$lib_601.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function(s) { + s.append('path').attr('d', 'M0,0Z'); + }); // container for everything in this ternary subplot - _this.plotContainer = _this.container.selectAll('g.' + _this.id) - .data([0]); - _this.plotContainer.enter().append('g') - .classed(_this.id, true); - + _this.plotContainer = _$lib_601.ensureSingle(_this.container, 'g', _this.id); _this.updateLayers(ternaryLayout); - _$drawing_436.setClipUrl(_this.layers.backplot, clipId); - _$drawing_436.setClipUrl(_this.layers.grids, clipId); + _$drawing_498.setClipUrl(_this.layers.backplot, clipId); + _$drawing_498.setClipUrl(_this.layers.grids, clipId); }; -__proto_667.updateLayers = function(ternaryLayout) { +__proto_730.updateLayers = function(ternaryLayout) { var _this = this; var layers = _this.layers; @@ -178091,7 +180309,7 @@ __proto_667.updateLayers = function(ternaryLayout) { toplevel.enter().append('g') .attr('class', function(d) { return 'toplevel ' + d; }) .each(function(d) { - var s = _$d3_127.select(this); + var s = _$d3_130.select(this); layers[d] = s; // containers for different trace types. @@ -178122,7 +180340,7 @@ __proto_667.updateLayers = function(ternaryLayout) { var w_over_h = Math.sqrt(4 / 3); -__proto_667.adjustLayout = function(ternaryLayout, graphSize) { +__proto_730.adjustLayout = function(ternaryLayout, graphSize) { var _this = this, domain = ternaryLayout.domain, xDomainCenter = (domain.x[0] + domain.x[1]) / 2, @@ -178169,7 +180387,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { ], _id: 'x' }; - _$setConvert_603(_this.xaxis, _this.graphDiv._fullLayout); + _$setConvert_665(_this.xaxis, _this.graphDiv._fullLayout); _this.xaxis.setScale(); _this.xaxis.isPtWithinRange = function(d) { return ( @@ -178191,7 +180409,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { ], _id: 'y' }; - _$setConvert_603(_this.yaxis, _this.graphDiv._fullLayout); + _$setConvert_665(_this.yaxis, _this.graphDiv._fullLayout); _this.yaxis.setScale(); _this.yaxis.isPtWithinRange = function() { return true; }; @@ -178201,7 +180419,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { // 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_667({}, ternaryLayout.aaxis, { + var aaxis = _this.aaxis = __extendFlat_730({}, ternaryLayout.aaxis, { visible: true, range: [amin, sum - bmin - cmin], side: 'left', @@ -178218,12 +180436,12 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _gridpath: 'M0,0l' + h + ',-' + (w / 2), automargin: false // don't use automargins routine for labels }); - _$setConvert_603(aaxis, _this.graphDiv._fullLayout); + _$setConvert_665(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_667({}, ternaryLayout.baxis, { + var baxis = _this.baxis = __extendFlat_730({}, ternaryLayout.baxis, { visible: true, range: [sum - amin - cmin, bmin], side: 'bottom', @@ -178238,13 +180456,13 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _gridpath: 'M0,0l-' + (w / 2) + ',-' + h, automargin: false // don't use automargins routine for labels }); - _$setConvert_603(baxis, _this.graphDiv._fullLayout); + _$setConvert_665(baxis, _this.graphDiv._fullLayout); baxis.setScale(); aaxis._counteraxis = baxis; // caxis goes down the right side. Set it up as a y axis, with // post-transformation similar to aaxis - var caxis = _this.caxis = __extendFlat_667({}, ternaryLayout.caxis, { + var caxis = _this.caxis = __extendFlat_730({}, ternaryLayout.caxis, { visible: true, range: [sum - amin - bmin, cmin], side: 'right', @@ -178260,7 +180478,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _gridpath: 'M0,0l-' + h + ',' + (w / 2), automargin: false // don't use automargins routine for labels }); - _$setConvert_603(caxis, _this.graphDiv._fullLayout); + _$setConvert_665(caxis, _this.graphDiv._fullLayout); caxis.setScale(); var triangleClip = 'M' + x0 + ',' + (y0 + h) + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z'; @@ -178303,30 +180521,30 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _this.layers.aline.select('path') .attr('d', aaxis.showline ? 'M' + x0 + ',' + (y0 + h) + 'l' + (w / 2) + ',-' + h : 'M0,0') - .call(_$color_411.stroke, aaxis.linecolor || '#000') + .call(_$color_473.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_411.stroke, baxis.linecolor || '#000') + .call(_$color_473.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_411.stroke, caxis.linecolor || '#000') + .call(_$color_473.stroke, caxis.linecolor || '#000') .style('stroke-width', (caxis.linewidth || 0) + 'px'); if(!_this.graphDiv._context.staticPlot) { _this.initInteractions(); } - _$drawing_436.setClipUrl( + _$drawing_498.setClipUrl( _this.layers.frontplot, _this._hasClipOnAxisFalse ? null : _this.clipId ); }; -__proto_667.drawAxes = function(doTitles) { +__proto_730.drawAxes = function(doTitles) { var _this = this, gd = _this.graphDiv, titlesuffix = _this.id.substr(7) + 'title', @@ -178335,18 +180553,18 @@ __proto_667.drawAxes = function(doTitles) { caxis = _this.caxis; // 3rd arg true below skips titles, so we can configure them // correctly later on. - _$axes_584.doTicks(gd, aaxis, true); - _$axes_584.doTicks(gd, baxis, true); - _$axes_584.doTicks(gd, caxis, true); + _$axes_647.doTicks(gd, aaxis, true); + _$axes_647.doTicks(gd, baxis, true); + _$axes_647.doTicks(gd, caxis, true); 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)); - _this.layers['a-title'] = _$titles_504.draw(gd, 'a' + titlesuffix, { + _this.layers['a-title'] = _$titles_566.draw(gd, 'a' + titlesuffix, { propContainer: aaxis, propName: _this.id + '.aaxis.title', - placeholder: ____667(gd, 'Click to enter Component A title'), + placeholder: ____730(gd, 'Click to enter Component A title'), attributes: { x: _this.x0 + _this.w / 2, y: _this.y0 - aaxis.titlefont.size / 3 - apad, @@ -178358,10 +180576,10 @@ __proto_667.drawAxes = function(doTitles) { var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) + (baxis.ticks === 'outside' ? baxis.ticklen : 0) + 3; - _this.layers['b-title'] = _$titles_504.draw(gd, 'b' + titlesuffix, { + _this.layers['b-title'] = _$titles_566.draw(gd, 'b' + titlesuffix, { propContainer: baxis, propName: _this.id + '.baxis.title', - placeholder: ____667(gd, 'Click to enter Component B title'), + placeholder: ____730(gd, 'Click to enter Component B title'), attributes: { x: _this.x0 - bpad, y: _this.y0 + _this.h + baxis.titlefont.size * 0.83 + bpad, @@ -178369,10 +180587,10 @@ __proto_667.drawAxes = function(doTitles) { } }); - _this.layers['c-title'] = _$titles_504.draw(gd, 'c' + titlesuffix, { + _this.layers['c-title'] = _$titles_566.draw(gd, 'c' + titlesuffix, { propContainer: caxis, propName: _this.id + '.caxis.title', - placeholder: ____667(gd, 'Click to enter Component C title'), + placeholder: ____730(gd, 'Click to enter Component C title'), attributes: { x: _this.x0 + _this.w + bpad, y: _this.y0 + _this.h + caxis.titlefont.size * 0.83 + bpad, @@ -178384,7 +180602,7 @@ __proto_667.drawAxes = function(doTitles) { // hard coded paths for zoom corners // uses the same sizing as cartesian, length is MINZOOM/2, width is 3px -var CLEN = _$constants_589.MINZOOM / 2 + 0.87; +var CLEN = _$constants_652.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'; @@ -178398,9 +180616,9 @@ var TOPPATH = 'm0,1l' + (CLEN / 2) + ',' + (CLEN * 0.87) + 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_667 = true; +var __SHOWZOOMOUTTIP_730 = true; -__proto_667.initInteractions = function() { +__proto_730.initInteractions = function() { var _this = this, dragger = _this.layers.plotbg.select('path').node(), gd = _this.graphDiv, @@ -178438,14 +180656,14 @@ __proto_667.initInteractions = function() { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragDone; panPrep(); - clearSelect(); + __clearSelect_730(zoomContainer); } else if(dragModeNow === 'select' || dragModeNow === 'lasso') { - _$prepSelect_602(e, startX, startY, dragOptions, dragModeNow); + __prepSelect_730(e, startX, startY, dragOptions, dragModeNow); } }, clickFn: function(numClicks, evt) { - __removeZoombox_667(gd); + __removeZoombox_730(gd); if(numClicks === 2) { var attrs = {}; @@ -178453,9 +180671,9 @@ __proto_667.initInteractions = function() { attrs[_this.id + '.baxis.min'] = 0; attrs[_this.id + '.caxis.min'] = 0; gd.emit('plotly_doubleclick', null); - _$registry_668.call('relayout', gd, attrs); + _$registry_731.call('relayout', gd, attrs); } - _$fx_453.click(gd, evt, _this.id); + _$fx_515.click(gd, evt, _this.id); } }; @@ -178472,7 +180690,7 @@ __proto_667.initInteractions = function() { }; mins = mins0; span0 = _this.aaxis.range[1] - mins0.a; - lum = _$tinycolor_352(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance(); + lum = _$tinycolor_414(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance(); path0 = 'M0,' + _this.h + 'L' + (_this.w / 2) + ', 0L' + _this.w + ',' + _this.h + 'Z'; dimmed = false; @@ -178489,14 +180707,14 @@ __proto_667.initInteractions = function() { .attr('class', 'zoombox-corners') .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')') .style({ - fill: _$color_411.background, - stroke: _$color_411.defaultLine, + fill: _$color_473.background, + stroke: _$color_473.defaultLine, 'stroke-width': 1, opacity: 0 }) .attr('d', 'M0,0Z'); - clearSelect(); + __clearSelect_730(zoomContainer); } function getAFrac(x, y) { return 1 - (y / _this.h); } @@ -178516,7 +180734,7 @@ __proto_667.initInteractions = function() { yBottom = (1 - afrac) * _this.h, yTop = yBottom - xSpan / w_over_h; - if(xSpan < _$constants_589.MINZOOM) { + if(xSpan < _$constants_652.MINZOOM) { mins = mins0; zb.attr('d', path0); corners.attr('d', 'M0,0Z'); @@ -178549,7 +180767,7 @@ __proto_667.initInteractions = function() { } function zoomDone() { - __removeZoombox_667(gd); + __removeZoombox_730(gd); if(mins === mins0) return; @@ -178558,11 +180776,11 @@ __proto_667.initInteractions = function() { attrs[_this.id + '.baxis.min'] = mins.b; attrs[_this.id + '.caxis.min'] = mins.c; - _$registry_668.call('relayout', gd, attrs); + _$registry_731.call('relayout', gd, attrs); - if(__SHOWZOOMOUTTIP_667 && gd.data && gd._context.showTips) { - _$lib_539.notifier(____667(gd, 'Double-click to zoom back out'), 'long'); - __SHOWZOOMOUTTIP_667 = false; + if(__SHOWZOOMOUTTIP_730 && gd.data && gd._context.showTips) { + _$lib_601.notifier(____730(gd, 'Double-click to zoom back out'), 'long'); + __SHOWZOOMOUTTIP_730 = false; } } @@ -178627,7 +180845,7 @@ __proto_667.initInteractions = function() { if(_this._hasClipOnAxisFalse) { _this.plotContainer .select('.scatterlayer').selectAll('.trace') - .call(_$drawing_436.hideOutsideRangePoints, _this); + .call(_$drawing_498.hideOutsideRangePoints, _this); } } @@ -178637,21 +180855,14 @@ __proto_667.initInteractions = function() { attrs[_this.id + '.baxis.min'] = mins.b; attrs[_this.id + '.caxis.min'] = mins.c; - _$registry_668.call('relayout', gd, attrs); - } - - function clearSelect() { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomContainer.selectAll('.select-outline').remove(); + _$registry_731.call('relayout', gd, attrs); } // 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_453.hover(gd, evt, _this.id); + _$fx_515.hover(gd, evt, _this.id); gd._fullLayout._lasthover = dragger; gd._fullLayout._hoversubplot = _this.id; }; @@ -178659,19 +180870,19 @@ __proto_667.initInteractions = function() { dragger.onmouseout = function(evt) { if(gd._dragging) return; - _$dragelement_433.unhover(gd, evt); + _$dragelement_495.unhover(gd, evt); }; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); }; -function __removeZoombox_667(gd) { - _$d3_127.select(gd) +function __removeZoombox_730(gd) { + _$d3_130.select(gd) .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') .remove(); } -var _$ternary_661 = {}; +var _$ternary_724 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -178683,39 +180894,39 @@ var _$ternary_661 = {}; 'use strict'; -/* removed: var _$Ternary_667 = require('./ternary'); */; +/* removed: var _$Ternary_730 = require('./ternary'); */; -var __getSubplotCalcData_661 = _$get_data_621.getSubplotCalcData; -var __counterRegex_661 = _$lib_539.counterRegex; +var __getSubplotCalcData_724 = _$get_data_683.getSubplotCalcData; +var __counterRegex_724 = _$lib_601.counterRegex; var TERNARY = 'ternary'; -_$ternary_661.name = TERNARY; +_$ternary_724.name = TERNARY; -_$ternary_661.attr = 'subplot'; +_$ternary_724.attr = 'subplot'; -_$ternary_661.idRoot = TERNARY; +_$ternary_724.idRoot = TERNARY; -_$ternary_661.idRegex = _$ternary_661.attrRegex = __counterRegex_661(TERNARY); +_$ternary_724.idRegex = _$ternary_724.attrRegex = __counterRegex_724(TERNARY); -_$ternary_661.attributes = _$attributes_662; +_$ternary_724.attributes = _$attributes_725; -_$ternary_661.layoutAttributes = _$layout_attributes_666; +_$ternary_724.layoutAttributes = _$layout_attributes_729; -_$ternary_661.supplyLayoutDefaults = _$supplyLayoutDefaults_665; +_$ternary_724.supplyLayoutDefaults = _$supplyLayoutDefaults_728; -_$ternary_661.plot = function plotTernary(gd) { +_$ternary_724.plot = function plotTernary(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var ternaryIds = fullLayout._subplots[TERNARY]; for(var i = 0; i < ternaryIds.length; i++) { var ternaryId = ternaryIds[i], - ternaryCalcData = __getSubplotCalcData_661(calcData, TERNARY, ternaryId), + ternaryCalcData = __getSubplotCalcData_724(calcData, TERNARY, ternaryId), ternary = fullLayout[ternaryId]._subplot; // If ternary is not instantiated, create one! if(!ternary) { - ternary = new _$Ternary_667({ + ternary = new _$Ternary_730({ id: ternaryId, graphDiv: gd, container: fullLayout._ternarylayer.node() @@ -178730,7 +180941,7 @@ _$ternary_661.plot = function plotTernary(gd) { } }; -_$ternary_661.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$ternary_724.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || []; for(var i = 0; i < oldTernaryKeys.length; i++) { @@ -178758,19 +180969,19 @@ _$ternary_661.clean = function(newFullData, newFullLayout, oldFullData, oldFullL 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -var __dash_929 = _$attributes_435.dash; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +var __dash_996 = _$attributes_497.dash; -var __extendFlat_929 = _$extend_528.extendFlat; +var __extendFlat_996 = _$extend_590.extendFlat; -var __scatterMarkerAttrs_929 = _$attributes_862.marker, - __scatterLineAttrs_929 = _$attributes_862.line, - __scatterMarkerLineAttrs_929 = __scatterMarkerAttrs_929.line; +var __scatterMarkerAttrs_996 = _$attributes_927.marker, + __scatterLineAttrs_996 = _$attributes_927.line, + __scatterMarkerLineAttrs_996 = __scatterMarkerAttrs_996.line; -var _$attributes_929 = { +var _$attributes_996 = { a: { valType: 'data_array', editType: 'calc', @@ -178818,8 +181029,8 @@ var _$attributes_929 = { '0 (or missing) means to use ternary.sum' ].join(' ') }, - mode: __extendFlat_929({}, _$attributes_862.mode, {dflt: 'markers'}), - text: __extendFlat_929({}, _$attributes_862.text, { + mode: __extendFlat_996({}, _$attributes_927.mode, {dflt: 'markers'}), + text: __extendFlat_996({}, _$attributes_927.text, { description: [ 'Sets text elements associated with each (a,b,c) point.', 'If a single string, the same string appears over', @@ -178830,7 +181041,7 @@ var _$attributes_929 = { 'these elements will be seen in the hover labels.' ].join(' ') }), - hovertext: __extendFlat_929({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_996({}, _$attributes_927.hovertext, { description: [ 'Sets hover text elements associated with each (a,b,c) point.', 'If a single string, the same string appears over', @@ -178841,17 +181052,17 @@ var _$attributes_929 = { ].join(' ') }), line: { - color: __scatterLineAttrs_929.color, - width: __scatterLineAttrs_929.width, - dash: __dash_929, - shape: __extendFlat_929({}, __scatterLineAttrs_929.shape, + color: __scatterLineAttrs_996.color, + width: __scatterLineAttrs_996.width, + dash: __dash_996, + shape: __extendFlat_996({}, __scatterLineAttrs_996.shape, {values: ['linear', 'spline']}), - smoothing: __scatterLineAttrs_929.smoothing, + smoothing: __scatterLineAttrs_996.smoothing, editType: 'calc' }, - connectgaps: _$attributes_862.connectgaps, - cliponaxis: _$attributes_862.cliponaxis, - fill: __extendFlat_929({}, _$attributes_862.fill, { + connectgaps: _$attributes_927.connectgaps, + cliponaxis: _$attributes_927.cliponaxis, + fill: __extendFlat_996({}, _$attributes_927.fill, { values: ['none', 'toself', 'tonext'], description: [ 'Sets the area to fill with a solid color.', @@ -178865,38 +181076,38 @@ var _$attributes_929 = { 'used if one trace does not enclose the other.' ].join(' ') }), - fillcolor: _$attributes_862.fillcolor, - marker: __extendFlat_929({ - symbol: __scatterMarkerAttrs_929.symbol, - opacity: __scatterMarkerAttrs_929.opacity, - maxdisplayed: __scatterMarkerAttrs_929.maxdisplayed, - size: __scatterMarkerAttrs_929.size, - sizeref: __scatterMarkerAttrs_929.sizeref, - sizemin: __scatterMarkerAttrs_929.sizemin, - sizemode: __scatterMarkerAttrs_929.sizemode, - line: __extendFlat_929({ - width: __scatterMarkerLineAttrs_929.width, + fillcolor: _$attributes_927.fillcolor, + marker: __extendFlat_996({ + symbol: __scatterMarkerAttrs_996.symbol, + opacity: __scatterMarkerAttrs_996.opacity, + maxdisplayed: __scatterMarkerAttrs_996.maxdisplayed, + size: __scatterMarkerAttrs_996.size, + sizeref: __scatterMarkerAttrs_996.sizeref, + sizemin: __scatterMarkerAttrs_996.sizemin, + sizemode: __scatterMarkerAttrs_996.sizemode, + line: __extendFlat_996({ + width: __scatterMarkerLineAttrs_996.width, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ), - gradient: __scatterMarkerAttrs_929.gradient, + gradient: __scatterMarkerAttrs_996.gradient, editType: 'calc' - }, _$makeColorScaleAttributes_419('marker'), { - showscale: __scatterMarkerAttrs_929.showscale, - colorbar: _$attributes_412 + }, _$makeColorScaleAttributes_481('marker'), { + showscale: __scatterMarkerAttrs_996.showscale, + colorbar: _$attributes_474 }), - textfont: _$attributes_862.textfont, - textposition: _$attributes_862.textposition, + textfont: _$attributes_927.textfont, + textposition: _$attributes_927.textposition, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected, + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected, - hoverinfo: __extendFlat_929({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_996({}, _$attributes_644.hoverinfo, { flags: ['a', 'b', 'c', 'text', 'name'] }), - hoveron: _$attributes_862.hoveron, + hoveron: _$attributes_927.hoveron, }; /** @@ -178910,17 +181121,17 @@ var _$attributes_929 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_930 = _$calc_863.calcMarkerSize; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_997 = _$calc_928.calcMarkerSize; var dataArrays = ['a', 'b', 'c']; var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']}; -var _$calc_930 = function calc(gd, trace) { +var _$calc_997 = function calc(gd, trace) { var ternary = gd._fullLayout[trace.subplot]; var displaySum = ternary.sum; var normSum = trace.sum || displaySum; @@ -178950,7 +181161,7 @@ var _$calc_930 = function calc(gd, trace) { a = arrays.a[i]; b = arrays.b[i]; c = arrays.c[i]; - if(_$fastIsnumeric_139(a) && _$fastIsnumeric_139(b) && _$fastIsnumeric_139(c)) { + if(_$fastIsnumeric_196(a) && _$fastIsnumeric_196(b) && _$fastIsnumeric_196(c)) { a = +a; b = +b; c = +c; @@ -178972,10 +181183,10 @@ var _$calc_930 = function calc(gd, trace) { else cd[i] = {x: false, y: false}; } - __calcMarkerSize_930(trace, serieslen); - _$calcMarkerColorscale_867(trace); - _$arraysToCalcdata_861(cd, trace); - _$calcSelection_864(cd, trace); + __calcMarkerSize_997(trace, serieslen); + _$calcMarkerColorscale_932(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcSelection_929(cd, trace); return cd; }; @@ -178991,22 +181202,22 @@ var _$calc_930 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$constants_868 = require('../scatter/constants'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$constants_933 = require('../scatter/constants'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_929 = require('./attributes'); */; +/* removed: var _$attributes_996 = require('./attributes'); */; -var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_998 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_929, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_996, attr, dflt); } var a = coerce('a'), @@ -179044,26 +181255,26 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('hovertext'); - var defaultMode = len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'; + var defaultMode = len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'; coerce('mode', defaultMode); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -179071,8 +181282,8 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -179080,7 +181291,7 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -179093,7 +181304,7 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_932 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_999 = function eventData(out, pt, trace, cd, pointNumber) { if(pt.xa) out.xaxis = pt.xa; if(pt.ya) out.yaxis = pt.ya; @@ -179125,12 +181336,12 @@ var _$eventData_932 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_873 = require('../scatter/hover'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hoverPoints_938 = require('../scatter/hover'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var _$hoverPoints_933 = function hoverPoints(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_873(pointData, xval, yval, hovermode); +var _$hoverPoints_1000 = function hoverPoints(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_938(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -179172,7 +181383,7 @@ var _$hoverPoints_933 = function hoverPoints(pointData, xval, yval, hovermode) { var text = []; function textPart(ax, val) { - text.push(ax._hovertitle + ': ' + _$axes_584.tickText(ax, val, 'hover').text); + text.push(ax._hovertitle + ': ' + _$axes_647.tickText(ax, val, 'hover').text); } if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'c']; @@ -179196,9 +181407,9 @@ var _$hoverPoints_933 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -/* removed: var _$plot_881 = require('../scatter/plot'); */; +/* removed: var _$plot_946 = require('../scatter/plot'); */; -var _$plot_935 = function plot(gd, ternary, moduleCalcData) { +var _$plot_1002 = function plot(gd, ternary, moduleCalcData) { var plotContainer = ternary.plotContainer; // remove all nodes inside the scatter layer @@ -179212,7 +181423,7 @@ var _$plot_935 = function plot(gd, ternary, moduleCalcData) { layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null }; - _$plot_881(gd, plotinfo, moduleCalcData); + _$plot_946(gd, plotinfo, moduleCalcData); }; /** @@ -179227,19 +181438,19 @@ var _$plot_935 = function plot(gd, ternary, moduleCalcData) { var ScatterTernary = {}; -ScatterTernary.attributes = _$attributes_929; -ScatterTernary.supplyDefaults = _$supplyDefaults_931; -ScatterTernary.colorbar = _$colorbar_866; -ScatterTernary.calc = _$calc_930; -ScatterTernary.plot = _$plot_935; -ScatterTernary.style = _$style_883.style; -ScatterTernary.hoverPoints = _$hoverPoints_933; -ScatterTernary.selectPoints = _$selectPoints_882; -ScatterTernary.eventData = _$eventData_932; +ScatterTernary.attributes = _$attributes_996; +ScatterTernary.supplyDefaults = _$supplyDefaults_998; +ScatterTernary.colorbar = _$colorbar_931; +ScatterTernary.calc = _$calc_997; +ScatterTernary.plot = _$plot_1002; +ScatterTernary.style = _$style_948.style; +ScatterTernary.hoverPoints = _$hoverPoints_1000; +ScatterTernary.selectPoints = _$selectPoints_947; +ScatterTernary.eventData = _$eventData_999; ScatterTernary.moduleType = 'trace'; ScatterTernary.name = 'scatterternary'; -ScatterTernary.basePlotModule = _$ternary_661; +ScatterTernary.basePlotModule = _$ternary_724; ScatterTernary.categories = ['ternary', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like']; ScatterTernary.meta = { hrName: 'scatter_ternary', @@ -179249,7 +181460,7 @@ ScatterTernary.meta = { ].join(' ') }; -var _$ScatterTernary_934 = ScatterTernary; +var _$ScatterTernary_1001 = ScatterTernary; /** * Copyright 2012-2018, Plotly, Inc. @@ -179261,9 +181472,9 @@ var _$ScatterTernary_934 = ScatterTernary; 'use strict'; -var _$scatterternary_34 = _$ScatterTernary_934; +var _$scatterternary_34 = _$ScatterTernary_1001; -var _$sort_966 = {}; +var _$sort_1037 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -179274,15 +181485,15 @@ var _$sort_966 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -var __pointsAccessorFunction_966 = _$helpers_965.pointsAccessorFunction; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +var __pointsAccessorFunction_1037 = _$helpers_1036.pointsAccessorFunction; -_$sort_966.moduleType = 'transform'; +_$sort_1037.moduleType = 'transform'; -_$sort_966.name = 'sort'; +_$sort_1037.name = 'sort'; -_$sort_966.attributes = { +_$sort_1037.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -179326,11 +181537,11 @@ _$sort_966.attributes = { editType: 'calc' }; -_$sort_966.supplyDefaults = function(transformIn) { +_$sort_1037.supplyDefaults = function(transformIn) { var transformOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, _$sort_966.attributes, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, _$sort_1037.attributes, attr, dflt); } var enabled = coerce('enabled'); @@ -179343,23 +181554,23 @@ _$sort_966.supplyDefaults = function(transformIn) { return transformOut; }; -_$sort_966.calcTransform = function(gd, trace, opts) { +_$sort_1037.calcTransform = function(gd, trace, opts) { if(!opts.enabled) return; - var targetArray = _$lib_539.getTargetArray(trace, opts); + var targetArray = _$lib_601.getTargetArray(trace, opts); if(!targetArray) return; var target = opts.target; var len = targetArray.length; var arrayAttrs = trace._arrayAttrs; - var d2c = _$axes_584.getDataToCoordFunc(gd, trace, target, targetArray); + var d2c = _$axes_647.getDataToCoordFunc(gd, trace, target, targetArray); var indices = getIndices(opts, targetArray, d2c); - var originalPointsAccessor = __pointsAccessorFunction_966(trace.transforms, opts); + var originalPointsAccessor = __pointsAccessorFunction_1037(trace.transforms, opts); var indexToPoints = {}; var i, j; for(i = 0; i < arrayAttrs.length; i++) { - var np = _$lib_539.nestedProperty(trace, arrayAttrs[i]); + var np = _$lib_601.nestedProperty(trace, arrayAttrs[i]); var arrayOld = np.get(); var arrayNew = new Array(len); @@ -179424,7 +181635,1605 @@ function getSortFunc(opts, d2c) { 'use strict'; -var _$sort_35 = _$sort_966; +var _$sort_35 = _$sort_1037; + +var _$performanceNow_346 = {}; +(function (process){ +// Generated by CoffeeScript 1.12.2 +(function() { + var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; + + if ((typeof performance !== "undefined" && performance !== null) && performance.now) { + _$performanceNow_346 = function() { + return performance.now(); + }; + } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { + _$performanceNow_346 = 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) { + _$performanceNow_346 = function() { + return Date.now() - loadTime; + }; + loadTime = Date.now(); + } else { + _$performanceNow_346 = function() { + return new Date().getTime() - loadTime; + }; + loadTime = new Date().getTime(); + } + +}).call(this); + +//# sourceMappingURL=performance-now.js.map + +}).call(this,_$browser_366) +var _$raf_368 = {}; +(function (global){ +var __dummy_368$0 = 0 + , root = typeof window === 'undefined' ? global : window + , vendors = ['moz', 'webkit'] + , suffix = 'AnimationFrame' + , raf = root['request' + suffix] + , caf = root['cancel' + suffix] || root['cancelRequest' + suffix] + +for(var i = 0; !raf && i < vendors.length; i++) { + raf = root[vendors[i] + 'Request' + suffix] + caf = root[vendors[i] + 'Cancel' + suffix] + || root[vendors[i] + 'CancelRequest' + suffix] +} + +// Some versions of FF have rAF but not cAF +if(!raf || !caf) { + var last = 0 + , id = 0 + , queue = [] + , frameDuration = 1000 / 60 + + raf = function(callback) { + if(queue.length === 0) { + var _now = _$performanceNow_346() + , next = Math.max(0, frameDuration - (_now - last)) + last = next + _now + setTimeout(function() { + var cp = queue.slice(0) + // Clear queue here to prevent + // callbacks from appending listeners + // to the current frame's queue + queue.length = 0 + for(var i = 0; i < cp.length; i++) { + if(!cp[i].cancelled) { + try{ + cp[i].callback(last) + } catch(e) { + setTimeout(function() { throw e }, 0) + } + } + } + }, Math.round(next)) + } + queue.push({ + handle: ++id, + callback: callback, + cancelled: false + }) + return id + } + + caf = function(handle) { + for(var i = 0; i < queue.length; i++) { + if(queue[i].handle === handle) { + queue[i].cancelled = true + } + } + } +} + +_$raf_368 = function(fn) { + // Wrap in a new function to prevent + // `cancel` potentially being assigned + // to the native rAF function + return raf.call(root, fn) +} +_$raf_368.cancel = function() { + caf.apply(root, arguments) +} +_$raf_368.polyfill = function(object) { + if (!object) { + object = root; + } + object.requestAnimationFrame = raf + object.cancelAnimationFrame = caf +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + + +/* removed: var _$Scatter_377 = require('regl-scatter2d/scatter') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$raf_368 = require('raf') */; +/* removed: var _$newArray_51 = require('array-range') */; +/* removed: var _$parseRect_343 = require('parse-rect') */; + + +var _$SPLOM_378 = SPLOM + + +// @constructor +function SPLOM (regl, options) { + if (!(this instanceof SPLOM)) { return new SPLOM(regl, options) } + + // render passes + this.traces = [] + + // passes for scatter, combined across traces + this.passes = {} + + this.regl = regl + + // main scatter drawing instance + this.scatter = _$Scatter_377(regl) + + this.canvas = this.scatter.canvas +} + + +// update & draw passes once per frame +SPLOM.prototype.render = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (args.length) { + (ref = this).update.apply(ref, args) + } + + if (this.regl.attributes.preserveDrawingBuffer) { return this.draw() } + + // make sure draw is not called more often than once a frame + if (this.dirty) { + if (this.planned == null) { + this.planned = _$raf_368(function () { + this$1.draw() + this$1.dirty = true + this$1.planned = null + }) + } + } + else { + this.draw() + this.dirty = true + _$raf_368(function () { + this$1.dirty = false + }) + } + + return this + var ref; +} + + +// update passes +SPLOM.prototype.update = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { return } + + for (var i = 0; i < args.length; i++) { + this$1.updateItem(i, args[i]) + } + + // remove nulled passes + this.traces = this.traces.filter(Boolean) + + // FIXME: update passes independently + var passes = [] + var offset = 0 + for (var i$1 = 0; i$1 < this.traces.length; i$1++) { + var trace = this$1.traces[i$1] + var tracePasses = this$1.traces[i$1].passes + for (var j = 0; j < tracePasses.length; j++) { + passes.push(this$1.passes[tracePasses[j]]) + } + // save offset of passes + trace.passOffset = offset + offset += trace.passes.length + } + + (ref = this.scatter).update.apply(ref, passes) + + return this + var ref; +} + + +// update trace by index, not supposed to be called directly +SPLOM.prototype.updateItem = function (i, options) { + var this$1 = this; + + var ref = this; + var regl = ref.regl; + + // remove pass if null + if (options === null) { + this.traces[i] = null + return this + } + + if (!options) { return this } + + var o = _$pick_349(options, { + data: 'data items columns rows values dimensions samples x', + snap: 'snap cluster', + size: 'sizes size radius', + color: 'colors color fill fill-color fillColor', + opacity: 'opacity alpha transparency opaque', + borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline', + borderColor: 'borderColors borderColor bordercolor stroke stroke-color strokeColor', + marker: 'markers marker shape', + range: 'range ranges databox dataBox', + viewport: 'viewport viewBox viewbox', + domain: 'domain domains area areas', + padding: 'pad padding paddings pads margin margins', + transpose: 'transpose transposed', + diagonal: 'diagonal diag showDiagonal', + upper: 'upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf', + lower: 'lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower' + }) + + // we provide regl buffer per-trace, since trace data can be changed + var trace = (this.traces[i] || (this.traces[i] = { + id: i, + buffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }), + color: 'black', + marker: null, + size: 12, + borderColor: 'transparent', + borderSize: 1, + viewport: _$parseRect_343([regl._gl.drawingBufferWidth, regl._gl.drawingBufferHeight]), + padding: [0, 0, 0, 0], + opacity: 1, + diagonal: true, + upper: true, + lower: true + })) + + + // save styles + if (o.color != null) { + trace.color = o.color + } + if (o.size != null) { + trace.size = o.size + } + if (o.marker != null) { + trace.marker = o.marker + } + if (o.borderColor != null) { + trace.borderColor = o.borderColor + } + if (o.borderSize != null) { + trace.borderSize = o.borderSize + } + if (o.opacity != null) { + trace.opacity = o.opacity + } + if (o.viewport) { + trace.viewport = _$parseRect_343(o.viewport) + } + if (o.diagonal != null) { trace.diagonal = o.diagonal } + if (o.upper != null) { trace.upper = o.upper } + if (o.lower != null) { trace.lower = o.lower } + + // put flattened data into buffer + if (o.data) { + trace.buffer(_$flattenVertexData_198(o.data)) + trace.columns = o.data.length + trace.count = o.data[0].length + + // detect bounds per-column + trace.bounds = [] + + for (var i$1 = 0; i$1 < trace.columns; i$1++) { + trace.bounds[i$1] = _$normalize_49(o.data[i$1], 1) + } + } + + // add proper range updating markers + var multirange + if (o.range) { + trace.range = o.range + multirange = trace.range && typeof trace.range[0] !== 'number' + } + + if (o.domain) { + trace.domain = o.domain + } + var multipadding = false + if (o.padding != null) { + // multiple paddings + if (Array.isArray(o.padding) && o.padding.length === trace.columns && typeof o.padding[o.padding.length - 1] === 'number') { + trace.padding = o.padding.map(getPad) + multipadding = true + } + // single padding + else { + trace.padding = getPad(o.padding) + } + } + + // create passes + var m = trace.columns + var n = trace.count + + var w = trace.viewport.width + var h = trace.viewport.height + var left = trace.viewport.x + var top = trace.viewport.y + var iw = w / m + var ih = h / m + + trace.passes = [] + + for (var i$2 = 0; i$2 < m; i$2++) { + for (var j = 0; j < m; j++) { + if (!trace.diagonal && j === i$2) { continue } + if (!trace.upper && i$2 > j) { continue } + if (!trace.lower && i$2 < j) { continue } + + var key = passId(trace.id, i$2, j) + + var pass = this$1.passes[key] || (this$1.passes[key] = {}) + + if (o.data) { + if (o.transpose) { + pass.positions = { + x: {buffer: trace.buffer, offset: j, count: n, stride: m}, + y: {buffer: trace.buffer, offset: i$2, count: n, stride: m} + } + } + else { + pass.positions = { + x: {buffer: trace.buffer, offset: j * n, count: n}, + y: {buffer: trace.buffer, offset: i$2 * n, count: n} + } + } + + pass.bounds = getBox(trace.bounds, i$2, j) + } + + if (o.domain || o.viewport || o.data) { + var pad = multipadding ? getBox(trace.padding, i$2, j) : trace.padding + if (trace.domain) { + var ref$1 = getBox(trace.domain, i$2, j); + var lox = ref$1[0]; + var loy = ref$1[1]; + var hix = ref$1[2]; + var hiy = ref$1[3]; + + pass.viewport = [ + left + lox * w + pad[0], + top + loy * h + pad[1], + left + hix * w - pad[2], + top + hiy * h - pad[3] + ] + } + // consider auto-domain equipartial + else { + pass.viewport = [ + left + j * iw + iw * pad[0], + top + i$2 * ih + ih * pad[1], + left + (j + 1) * iw - iw * pad[2], + top + (i$2 + 1) * ih - ih * pad[3] + ] + } + } + + if (o.color) { pass.color = trace.color } + if (o.size) { pass.size = trace.size } + if (o.marker) { pass.marker = trace.marker } + if (o.borderSize) { pass.borderSize = trace.borderSize } + if (o.borderColor) { pass.borderColor = trace.borderColor } + if (o.opacity) { pass.opacity = trace.opacity } + + if (o.range) { + pass.range = multirange ? getBox(trace.range, i$2, j) : trace.range || pass.bounds + } + + trace.passes.push(key) + } + } + + return this +} + + +// draw all or passed passes +SPLOM.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { + this.scatter.draw() + } + else { + var idx = [] + for (var i = 0; i < args.length; i++) { + // draw(0, 2, 5) - draw traces + if (typeof args[i] === 'number' ) { + var ref = this$1.traces[args[i]]; + var passes = ref.passes; + var passOffset = ref.passOffset; + idx.push.apply(idx, _$newArray_51(passOffset, passOffset + passes.length)) + } + // draw([0, 1, 2 ...], [3, 4, 5]) - draw points + else if (args[i].length) { + var els = args[i] + var ref$1 = this$1.traces[i]; + var passes$1 = ref$1.passes; + var passOffset$1 = ref$1.passOffset; + passes$1 = passes$1.map(function (passId, i) { + idx[passOffset$1 + i] = els + }) + } + } + (ref$2 = this.scatter).draw.apply(ref$2, idx) + } + + return this + var ref$2; +} + + +// dispose resources +SPLOM.prototype.destroy = function () { + this.traces.forEach(function (trace) { + if (trace.buffer && trace.buffer.destroy) { trace.buffer.destroy() } + }) + this.traces = null + this.passes = null + + this.scatter.destroy() + + return this +} + + +// return pass corresponding to trace i- j- square +function passId (trace, i, j) { + var id = (trace.id != null ? trace.id : trace) + var n = i + var m = j + var key = id << 16 | (n & 0xff) << 8 | m & 0xff + + return key +} + + +// return bounding box corresponding to a pass +function getBox (items, i, j) { + var ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy + var iitem = items[i], jitem = items[j] + + if (iitem.length > 2) { + ilox = iitem[0] + ihix = iitem[2] + iloy = iitem[1] + ihiy = iitem[3] + } + else if (iitem.length) { + ilox = iloy = iitem[0] + ihix = ihiy = iitem[1] + } + else { + ilox = iitem.x + iloy = iitem.y + ihix = iitem.x + iitem.width + ihiy = iitem.y + iitem.height + } + + if (jitem.length > 2) { + jlox = jitem[0] + jhix = jitem[2] + jloy = jitem[1] + jhiy = jitem[3] + } + else if (jitem.length) { + jlox = jloy = jitem[0] + jhix = jhiy = jitem[1] + } + else { + jlox = jitem.x + jloy = jitem.y + jhix = jitem.x + jitem.width + jhiy = jitem.y + jitem.height + } + + return [ jlox, iloy, jhix, ihiy ] +} + + +function getPad (arg) { + if (typeof arg === 'number') { return [arg, arg, arg, arg] } + else if (arg.length === 2) { return [arg[0], arg[1], arg[0], arg[1]] } + else { + var box = _$parseRect_343(arg) + return [box.x, box.y, box.x + box.width, box.y + box.height] + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$attributes_974 = require('../scattergl/attributes'); */; +var __cartesianIdRegex_1003 = _$constants_652.idRegex; + +function makeAxesValObject(axLetter) { + return { + valType: 'info_array', + freeLength: true, + role: 'info', + editType: 'calc', + items: { + valType: 'subplotid', + regex: __cartesianIdRegex_1003[axLetter], + editType: 'plot' + }, + description: [ + 'Sets the list of ' + axLetter + ' axes', + 'corresponding to this splom trace.', + 'By default, a splom will match the first N ' + axLetter + 'axes', + 'where N is the number of input dimensions.' + ].join(' ') + }; +} + +var _$attributes_1003 = { + dimensions: { + _isLinkedToArray: 'dimension', + + visible: { + valType: 'boolean', + role: 'info', + dflt: true, + editType: 'calc', + description: [ + 'Determines whether or not this dimension is shown on the graph.', + 'Note that even visible false dimension contribute to the', + 'default grid generate by this splom trace.' + ].join(' ') + }, + label: { + valType: 'string', + role: 'info', + editType: 'calc', + description: 'Sets the label corresponding to this splom dimension.' + }, + values: { + valType: 'data_array', + role: 'info', + editType: 'calc+clearAxisTypes', + description: 'Sets the dimension values to be plotted.' + }, + + // 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: _$attributes_974.text, + marker: _$attributes_974.marker, + + xaxes: makeAxesValObject('x'), + yaxes: makeAxesValObject('y'), + + diagonal: { + visible: { + valType: 'boolean', + role: 'info', + dflt: true, + editType: 'calc', + description: [ + 'Determines whether or not subplots on the diagonal are displayed.' + ].join(' ') + }, + + // type: 'scattergl' | 'histogram' | 'box' | 'violin' + // ... + // more options + + editType: 'calc' + }, + + showupperhalf: { + valType: 'boolean', + role: 'info', + dflt: true, + editType: 'calc', + description: [ + 'Determines whether or not subplots on the upper half', + 'from the diagonal are displayed.' + ].join(' ') + }, + showlowerhalf: { + valType: 'boolean', + role: 'info', + dflt: true, + editType: 'calc', + description: [ + 'Determines whether or not subplots on the lower half', + 'from the diagonal are displayed.' + ].join(' ') + }, + + selected: { + marker: _$attributes_974.selected.marker, + editType: 'calc' + }, + unselected: { + marker: _$attributes_974.unselected.marker, + editType: 'calc' + }, + + opacity: _$attributes_974.opacity +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$Line2D_375 = require('regl-line2d'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$prepareRegl_614 = require('../../lib/prepare_regl'); */; +var __getModuleCalcData_1004 = _$get_data_683.getModuleCalcData; +/* removed: var _$cartesian_658 = require('../../plots/cartesian'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +var __SPLOM_1004 = 'splom'; + +function __plot_1004(gd) { + var fullLayout = gd._fullLayout; + var _module = _$registry_731.getModule(__SPLOM_1004); + var splomCalcData = __getModuleCalcData_1004(gd.calcdata, _module)[0]; + + _$prepareRegl_614(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']); + + if(fullLayout._hasOnlyLargeSploms) { + drawGrid(gd); + } + + _module.plot(gd, {}, splomCalcData); +} + +function drag(gd) { + var cd = gd.calcdata; + var fullLayout = gd._fullLayout; + + if(fullLayout._hasOnlyLargeSploms) { + drawGrid(gd); + } + + for(var i = 0; i < cd.length; i++) { + var cd0 = cd[i][0]; + var trace = cd0.trace; + var scene = cd0.t._scene; + + if(trace.type === 'splom' && scene && scene.matrix) { + dragOne(gd, trace, scene); + } + } +} + +function dragOne(gd, trace, scene) { + var dimensions = trace.dimensions; + var visibleLength = scene.matrixOptions.data.length; + var ranges = new Array(visibleLength); + + for(var i = 0, k = 0; i < dimensions.length; i++) { + if(dimensions[i].visible) { + var rng = ranges[k] = new Array(4); + + var xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]); + if(xa) { + rng[0] = xa.r2l(xa.range[0]); + rng[2] = xa.r2l(xa.range[1]); + } + + var ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]); + if(ya) { + rng[1] = ya.r2l(ya.range[0]); + rng[3] = ya.r2l(ya.range[1]); + } + + k++; + } + } + + if(scene.selectBatch) { + scene.matrix.update({ranges: ranges}, {ranges: ranges}); + scene.matrix.draw(scene.unselectBatch, scene.selectBatch); + } else { + scene.matrix.update({ranges: ranges}); + scene.matrix.draw(); + } +} + +function drawGrid(gd) { + var fullLayout = gd._fullLayout; + var regl = fullLayout._glcanvas.data()[0].regl; + var splomGrid = fullLayout._splomGrid; + + if(!splomGrid) { + splomGrid = fullLayout._splomGrid = _$Line2D_375(regl); + } + + splomGrid.update(makeGridData(gd)); + splomGrid.draw(); +} + +function makeGridData(gd) { + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var fullView = [0, 0, fullLayout.width, fullLayout.height]; + var lookup = {}; + var k; + + function push(prefix, ax, x0, x1, y0, y1) { + var lcolor = ax[prefix + 'color']; + var lwidth = ax[prefix + 'width']; + var key = String(lcolor + lwidth); + + if(key in lookup) { + lookup[key].data.push(NaN, NaN, x0, x1, y0, y1); + } else { + lookup[key] = { + data: [x0, x1, y0, y1], + join: 'rect', + thickness: lwidth, + color: lcolor, + viewport: fullView, + range: fullView, + overlay: false + }; + } + } + + for(k in fullLayout._splomSubplots) { + var sp = fullLayout._plots[k]; + var xa = sp.xaxis; + var ya = sp.yaxis; + var xVals = xa._vals; + var yVals = ya._vals; + // ya.l2p assumes top-to-bottom coordinate system (a la SVG), + // we need to compute bottom-to-top offsets and slopes: + var yOffset = gs.b + ya.domain[0] * gs.h; + var ym = -ya._m; + var yb = -ym * ya.r2l(ya.range[0], ya.calendar); + var x, y; + + if(xa.showgrid) { + for(k = 0; k < xVals.length; k++) { + x = xa._offset + xa.l2p(xVals[k].x); + push('grid', xa, x, yOffset, x, yOffset + ya._length); + } + } + if(showZeroLine(xa)) { + x = xa._offset + xa.l2p(0); + push('zeroline', xa, x, yOffset, x, yOffset + ya._length); + } + if(ya.showgrid) { + for(k = 0; k < yVals.length; k++) { + y = yOffset + yb + ym * yVals[k].x; + push('grid', ya, xa._offset, y, xa._offset + xa._length, y); + } + } + if(showZeroLine(ya)) { + y = yOffset + yb + 0; + push('zeroline', ya, xa._offset, y, xa._offset + xa._length, y); + } + } + + var gridBatches = []; + for(k in lookup) { + gridBatches.push(lookup[k]); + } + + return gridBatches; +} + +// just like in Axes.doTicks but without the loop over traces +function showZeroLine(ax) { + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); + var p0 = ax.l2p(0); + + return ( + ax.zeroline && + ax._vals && ax._vals.length && + (rng[0] * rng[1] <= 0) && + (ax.type === 'linear' || ax.type === '-') && + ((p0 > 1 && p0 < ax._length - 1) || !ax.showline) + ); +} + +function __clean_1004(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + + var hadSplom, hasSplom; + var i; + + for(i = 0; i < oldModules.length; i++) { + if(oldModules[i].name === 'splom') { + hadSplom = true; + break; + } + } + for(i = 0; i < newModules.length; i++) { + if(newModules[i].name === 'splom') { + hasSplom = true; + break; + } + } + + if(hadSplom && !hasSplom) { + for(i = 0; i < oldCalcdata.length; i++) { + var cd0 = oldCalcdata[i][0]; + var trace = cd0.trace; + var scene = cd0.t._scene; + + if(trace.type === 'splom' && scene && scene.matrix) { + scene.matrix.destroy(); + cd0.t._scene = null; + } + } + } + + if(oldFullLayout._splomGrid && + (!newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms)) { + oldFullLayout._splomGrid.destroy(); + oldFullLayout._splomGrid = null; + } + + _$cartesian_658.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); +} + +var _$base_plot_1004 = { + name: __SPLOM_1004, + attr: _$cartesian_658.attr, + attrRegex: _$cartesian_658.attrRegex, + layoutAttributes: _$cartesian_658.layoutAttributes, + supplyLayoutDefaults: _$cartesian_658.supplyLayoutDefaults, + drawFramework: _$cartesian_658.drawFramework, + plot: __plot_1004, + drag: drag, + clean: __clean_1004, + updateFx: _$cartesian_658.updateFx, + toSVG: _$cartesian_658.toSVG +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_601 = require('../../lib'); */; + +/* removed: var _$attributes_1003 = require('./attributes'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +var OPEN_RE = /-open/; + +var _$supplyDefaults_1005 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_1003, attr, dflt); + } + + var dimLength = handleDimensionsDefaults(traceIn, traceOut); + + var showDiag = coerce('diagonal.visible'); + var showUpper = coerce('showupperhalf'); + var showLower = coerce('showlowerhalf'); + + if(!dimLength || (!showDiag && !showUpper && !showLower)) { + traceOut.visible = false; + return; + } + + coerce('text'); + + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce); + + var isOpen = OPEN_RE.test(traceOut.marker.symbol); + var isBubble = _$subtypes_949.isBubble(traceOut); + coerce('marker.line.width', isOpen || isBubble ? 1 : 0); + + __handleAxisDefaults_1005(traceIn, traceOut, layout, coerce); + + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); +}; + +function handleDimensionsDefaults(traceIn, traceOut) { + var dimensionsIn = traceIn.dimensions; + if(!Array.isArray(dimensionsIn)) return 0; + + var dimLength = dimensionsIn.length; + var commonLength = 0; + var dimensionsOut = traceOut.dimensions = new Array(dimLength); + var dimIn; + var dimOut; + var i; + + function coerce(attr, dflt) { + return _$lib_601.coerce(dimIn, dimOut, _$attributes_1003.dimensions, attr, dflt); + } + + for(i = 0; i < dimLength; i++) { + dimIn = dimensionsIn[i]; + dimOut = dimensionsOut[i] = {}; + + // coerce label even if dimensions may be `visible: false`, + // to fill in axis title defaults + coerce('label'); + + // wait until plot step to filter out visible false dimensions + var visible = coerce('visible'); + if(!visible) continue; + + var values = coerce('values'); + if(!values || !values.length) { + dimOut.visible = false; + continue; + } + + commonLength = Math.max(commonLength, values.length); + dimOut._index = i; + } + + for(i = 0; i < dimLength; i++) { + dimOut = dimensionsOut[i]; + if(dimOut.visible) dimOut._length = commonLength; + } + + traceOut._commonLength = commonLength; + + return dimensionsOut.length; +} + +function __handleAxisDefaults_1005(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; + + // N.B. one less x axis AND one less y axis when hiding one half and the diagonal + var axDfltLength = !showDiag && (!showUpper || !showLower) ? dimLength - 1 : dimLength; + + var xaxes = coerce('xaxes', fillAxisIdArray('x', axDfltLength)); + var yaxes = coerce('yaxes', fillAxisIdArray('y', axDfltLength)); + + // to avoid costly indexOf + traceOut._xaxes = arrayToHashObject(xaxes); + traceOut._yaxes = arrayToHashObject(yaxes); + + // allow users to under-specify number of axes + var axLength = Math.min(axDfltLength, xaxes.length, yaxes.length); + + // fill in splom subplot keys + for(i = 0; i < axLength; i++) { + for(j = 0; j < axLength; j++) { + var id = [xaxes[i] + yaxes[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; + } + } + } + + // 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); + + // cases where showDiag and showLower or showUpper are false + // no special treatment as the xaxes and yaxes items no longer match + // the dimensions items 1-to-1 + var xShift = !showDiag && !showLower ? -1 : 0; + var yShift = !showDiag && !showUpper ? -1 : 0; + + for(i = 0; i < dimLength; i++) { + var dim = dimensions[i]; + var xa = xaxes[i + xShift]; + var ya = yaxes[i + yShift]; + + fillAxisStash(layout, xa, dim); + fillAxisStash(layout, ya, dim); + + // note that some the entries here may be undefined + diag[i] = [xa, ya]; + } +} + +function fillAxisIdArray(axLetter, len) { + var out = new Array(len); + + for(var i = 0; i < len; i++) { + out[i] = axLetter + (i ? i + 1 : ''); + } + + return out; +} + +function fillAxisStash(layout, axId, dim) { + if(!axId) return; + + var axLetter = axId.charAt(0); + var stash = layout._splomAxes[axLetter]; + + if(!(axId in stash)) { + stash[axId] = (dim || {}).label || ''; + } +} + +function arrayToHashObject(arr) { + var obj = {}; + for(var i = 0; i < arr.length; i++) { + obj[arr[i]] = 1; + } + return obj; +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$SPLOM_378 = require('regl-splom'); */; +/* removed: var _$newArray_51 = require('array-range'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$grid_519 = require('../../components/grid'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +var __calcMarkerSize_1006 = _$calc_928.calcMarkerSize; +var __calcAxisExpansion_1006 = _$calc_928.calcAxisExpansion; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +var __convertMarkerSelection_1006 = _$convert_976.convertMarkerSelection; +var __convertMarkerStyle_1006 = _$convert_976.convertMarkerStyle; +var __calcHover_1006 = _$scattergl_978.calcHover; + +var __BADNUM_1006 = _$numerical_578.BADNUM; +var __TOO_MANY_POINTS_1006 = _$constants_975.TOO_MANY_POINTS; + +function __calc_1006(gd, trace) { + var dimensions = trace.dimensions; + var commonLength = trace._commonLength; + var stash = {}; + var opts = {}; + // 'c' for calculated, 'l' for linear, + // only differ here for log axes, pass ldata to createMatrix as 'data' + var cdata = opts.cdata = []; + var ldata = opts.data = []; + var i, k, dim; + + for(i = 0; i < dimensions.length; i++) { + dim = dimensions[i]; + + if(dim.visible) { + var axId = trace._diag[i][0] || trace._diag[i][1]; + var ax = _$axis_ids_650.getFromId(gd, axId); + if(ax) { + var ccol = makeCalcdata(ax, trace, dim); + var lcol = ax.type === 'log' ? _$lib_601.simpleMap(ccol, ax.c2l) : ccol; + cdata.push(ccol); + ldata.push(lcol); + } + } + } + + _$calcMarkerColorscale_932(trace); + _$lib_601.extendFlat(opts, __convertMarkerStyle_1006(trace)); + + var visibleLength = cdata.length; + var hasTooManyPoints = (visibleLength * commonLength) > __TOO_MANY_POINTS_1006; + + for(i = 0, k = 0; i < dimensions.length; i++) { + dim = dimensions[i]; + + if(dim.visible) { + var xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]) || {}; + var ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]) || {}; + + // Re-use SVG scatter axis expansion routine except + // for graph with very large number of points where it + // performs poorly. + // In big data case, fake Axes.expand outputs with data bounds, + // and an average size for array marker.size inputs. + var ppad; + if(hasTooManyPoints) { + ppad = 2 * (opts.sizeAvg || Math.max(opts.size, 3)); + } else { + ppad = __calcMarkerSize_1006(trace, commonLength); + } + + __calcAxisExpansion_1006(gd, trace, xa, ya, cdata[k], cdata[k], ppad); + k++; + } + } + + var scene = stash._scene = __sceneUpdate_1006(gd, stash); + if(!scene.matrix) scene.matrix = true; + scene.matrixOptions = opts; + + scene.selectedOptions = __convertMarkerSelection_1006(trace, trace.selected); + scene.unselectedOptions = __convertMarkerSelection_1006(trace, trace.unselected); + + return [{x: false, y: false, t: stash, trace: trace}]; +} + +function makeCalcdata(ax, trace, dim) { + // call makeCalcdata with fake input + var ccol = ax.makeCalcdata({ + v: dim.values, + vcalendar: trace.calendar + }, 'v'); + + for(var i = 0; i < ccol.length; i++) { + ccol[i] = ccol[i] === __BADNUM_1006 ? NaN : ccol[i]; + } + + return ccol; +} + +function __sceneUpdate_1006(gd, stash) { + var scene = stash._scene; + + var reset = { + dirty: true + }; + + var first = { + selectBatch: null, + unselectBatch: null, + matrix: false, + select: null + }; + + if(!scene) { + scene = stash._scene = _$lib_601.extendFlat({}, reset, first); + + scene.draw = function draw() { + // draw traces in selection mode + if(scene.matrix && scene.selectBatch) { + scene.matrix.draw(scene.unselectBatch, scene.selectBatch); + } + + else if(scene.matrix) { + scene.matrix.draw(); + } + + scene.dirty = false; + }; + + // remove scene resources + scene.destroy = function destroy() { + if(scene.matrix) scene.matrix.destroy(); + + scene.matrixOptions = null; + scene.selectBatch = null; + scene.unselectBatch = null; + + stash._scene = null; + }; + } + + // In case if we have scene from the last calc - reset data + if(!scene.dirty) { + _$lib_601.extendFlat(scene, reset); + } + + return scene; +} + +function __plot_1006(gd, _, splomCalcData) { + if(!splomCalcData.length) return; + + for(var i = 0; i < splomCalcData.length; i++) { + __plotOne_1006(gd, splomCalcData[i][0]); + } +} + +function __plotOne_1006(gd, cd0) { + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var trace = cd0.trace; + var stash = cd0.t; + var scene = stash._scene; + var matrixOpts = scene.matrixOptions; + var cdata = matrixOpts.cdata; + var regl = fullLayout._glcanvas.data()[0].regl; + var dragmode = fullLayout.dragmode; + var xa, ya; + var i, j, k; + + if(cdata.length === 0) return; + + // augment options with proper upper/lower halves + // regl-splom's default grid starts from bottom-left + matrixOpts.lower = trace.showupperhalf; + matrixOpts.upper = trace.showlowerhalf; + matrixOpts.diagonal = trace.diagonal.visible; + + var dimensions = trace.dimensions; + var visibleLength = cdata.length; + var viewOpts = {}; + viewOpts.ranges = new Array(visibleLength); + viewOpts.domains = new Array(visibleLength); + + for(i = 0, k = 0; i < dimensions.length; i++) { + if(trace.dimensions[i].visible) { + var rng = viewOpts.ranges[k] = new Array(4); + var dmn = viewOpts.domains[k] = new Array(4); + + xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]); + if(xa) { + rng[0] = xa._rl[0]; + rng[2] = xa._rl[1]; + dmn[0] = xa.domain[0]; + dmn[2] = xa.domain[1]; + } + + ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]); + if(ya) { + rng[1] = ya._rl[0]; + rng[3] = ya._rl[1]; + dmn[1] = ya.domain[0]; + dmn[3] = ya.domain[1]; + } + + k++; + } + } + + viewOpts.viewport = [gs.l, gs.b, gs.w + gs.l, gs.h + gs.b]; + + if(scene.matrix === true) { + scene.matrix = _$SPLOM_378(regl); + } + + var selectMode = dragmode === 'lasso' || dragmode === 'select' || !!trace.selectedpoints; + scene.selectBatch = null; + scene.unselectBatch = null; + + if(selectMode) { + var commonLength = trace._commonLength; + + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } + + // regenerate scene batch, if traces number changed during selection + if(trace.selectedpoints) { + scene.selectBatch = trace.selectedpoints; + + var selPts = trace.selectedpoints; + var selDict = {}; + for(i = 0; i < selPts.length; i++) { + selDict[selPts[i]] = true; + } + var unselPts = []; + for(i = 0; i < commonLength; i++) { + if(!selDict[i]) unselPts.push(i); + } + scene.unselectBatch = unselPts; + } + + // precalculate px coords since we are not going to pan during select + var xpx = stash.xpx = new Array(visibleLength); + var ypx = stash.ypx = new Array(visibleLength); + + for(i = 0, k = 0; i < dimensions.length; i++) { + if(trace.dimensions[i].visible) { + xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]); + if(xa) { + xpx[k] = new Array(commonLength); + for(j = 0; j < commonLength; j++) { + xpx[k][j] = xa.c2p(cdata[k][j]); + } + } + + ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]); + if(ya) { + ypx[k] = new Array(commonLength); + for(j = 0; j < commonLength; j++) { + ypx[k][j] = ya.c2p(cdata[k][j]); + } + } + + k++; + } + } + + if(scene.selectBatch) { + scene.matrix.update(matrixOpts, matrixOpts); + scene.matrix.update(scene.unselectedOptions, scene.selectedOptions); + scene.matrix.update(viewOpts, viewOpts); + } + else { + // delete selection pass + scene.matrix.update(viewOpts, null); + } + } + else { + scene.matrix.update(matrixOpts); + scene.matrix.update(viewOpts); + stash.xpx = stash.ypx = null; + } + + scene.draw(); +} + +function __hoverPoints_1006(pointData, xval, yval) { + var cd = pointData.cd; + var trace = cd[0].trace; + var stash = cd[0].t; + var scene = stash._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 = getDimIndex(trace, xa); + var yi = 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]; + + __calcHover_1006(pointData, x, y, trace); + + return [pointData]; +} + +function __selectPoints_1006(searchInfo, polygon) { + var cd = searchInfo.cd; + var trace = cd[0].trace; + var stash = cd[0].t; + var scene = stash._scene; + var cdata = scene.matrixOptions.cdata; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + + if(!scene) return selection; + + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); + if(trace.visible !== true || hasOnlyLines) return selection; + + var xi = getDimIndex(trace, xa); + var yi = 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]; + + // degenerate polygon does not enable selection + // filter out points by visible scatter ones + var els = null; + var unels = null; + if(polygon !== false && !polygon.degenerate) { + els = [], unels = []; + for(i = 0; i < x.length; i++) { + if(polygon.contains([xpx[i], ypx[i]])) { + els.push(i); + selection.push({ + pointNumber: i, + x: x[i], + y: y[i] + }); + } + else { + unels.push(i); + } + } + } else { + unels = _$newArray_51(stash.count); + } + + // make sure selectBatch is created + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } + + if(!scene.selectBatch) { + // enter every trace select mode + for(i = 0; i < scene.count; i++) { + scene.selectBatch = []; + scene.unselectBatch = []; + } + // we should turn scatter2d into unselected once we have any points selected + scene.matrix.update(scene.unselectedOptions, scene.selectedOptions); + } + + scene.selectBatch = els; + scene.unselectBatch = unels; + + + return selection; +} + +function __style_1006(gd, cds) { + if(!cds) return; + + var fullLayout = gd._fullLayout; + var cd0 = cds[0]; + var scene0 = cd0[0].t._scene; + scene0.matrix.regl.clear({color: true, depth: true}); + + if(fullLayout._splomGrid) { + fullLayout._splomGrid.draw(); + } + + for(var i = 0; i < cds.length; i++) { + var scene = cds[i][0].t._scene; + scene.draw(); + } + + // redraw all subplot with scattergl traces, + // as we cleared the whole canvas above + if(fullLayout._has('cartesian')) { + for(var k in fullLayout._plots) { + var sp = fullLayout._plots[k]; + if(sp._scene) sp._scene.draw(); + } + } +} + +function getDimIndex(trace, ax) { + var axId = ax._id; + var axLetter = axId.charAt(0); + var ind = {x: 0, y: 1}[axLetter]; + var dimensions = trace.dimensions; + + for(var i = 0, k = 0; i < dimensions.length; i++) { + if(dimensions[i].visible) { + if(trace._diag[i][ind] === axId) return k; + k++; + } + } + return false; +} + +var _$splom_1006 = { + moduleType: 'trace', + name: 'splom', + + basePlotModule: _$base_plot_1004, + categories: ['gl', 'regl', 'cartesian', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], + + attributes: _$attributes_1003, + supplyDefaults: _$supplyDefaults_1005, + + calc: __calc_1006, + plot: __plot_1006, + hoverPoints: __hoverPoints_1006, + selectPoints: __selectPoints_1006, + style: __style_1006, + + meta: { + description: [ + 'Splom traces generate scatter plot matrix visualizations.', + 'Each splom `dimensions` items correspond to a generated axis.', + 'Values for each of those dimensions are set in `dimensions[i].values`.', + 'Splom traces support all `scattergl` marker style attributes.', + 'Specify `layout.grid` attributes and/or layout x-axis and y-axis attributes', + 'for more control over the axis positioning and style. ' + ].join(' ') + } +}; + +// splom traces use the 'grid' component to generate their axes, +// register it here +_$registry_731.register(_$grid_519); + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$splom_36 = _$splom_1006; /** * Copyright 2012-2018, Plotly, Inc. @@ -179437,15 +183246,15 @@ var _$sort_35 = _$sort_966; 'use strict'; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; // Compute auto-z and autocolorscale if applicable -var _$calc_937 = function calc(gd, trace) { +var _$calc_1008 = function calc(gd, trace) { if(trace.surfacecolor) { - _$calc_418(trace, trace.surfacecolor, '', 'c'); + _$calc_480(trace, trace.surfacecolor, '', 'c'); } else { - _$calc_418(trace, trace.z, '', 'c'); + _$calc_480(trace, trace.z, '', 'c'); } }; @@ -179460,34 +183269,34 @@ var _$calc_937 = function calc(gd, trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_938 = function colorbar(gd, cd) { +var _$colorbar_1009 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, cmin = trace.cmin, cmax = trace.cmax, vals = trace.surfacecolor || trace.z; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, cmin, cmax @@ -179500,17 +183309,17 @@ var _$colorbar_938 = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -var _$shaders_216 = {}; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$browser_238 = require('glslify') */; +var _$shaders_273 = {}; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; -var __vertSrc_216 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\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 worldCoordinate = vec3(uv.zw, f.x);\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_216 = _$browser_238(["precision mediump 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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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_216 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]) +var __vertSrc_273 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\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 worldCoordinate = vec3(uv.zw, f.x);\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_273 = _$browser_295(["precision mediump 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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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_273 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]) -_$shaders_216.createShader = function (gl) { - var shader = _$createShader_206(gl, __vertSrc_216, __fragSrc_216, null, [ +_$shaders_273.createShader = function (gl) { + var shader = _$createShader_263(gl, __vertSrc_273, __fragSrc_273, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'vec3'}, {name: 'normal', type: 'vec3'} @@ -179520,8 +183329,8 @@ _$shaders_216.createShader = function (gl) { shader.attributes.normal.location = 2 return shader } -_$shaders_216.createPickShader = function (gl) { - var shader = _$createShader_206(gl, __vertSrc_216, pickSrc, null, [ +_$shaders_273.createPickShader = function (gl) { + var shader = _$createShader_263(gl, __vertSrc_273, pickSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'vec3'}, {name: 'normal', type: 'vec3'} @@ -179531,8 +183340,8 @@ _$shaders_216.createPickShader = function (gl) { shader.attributes.normal.location = 2 return shader } -_$shaders_216.createContourShader = function (gl) { - var shader = _$createShader_206(gl, __contourVertSrc_216, __fragSrc_216, null, [ +_$shaders_273.createContourShader = function (gl) { + var shader = _$createShader_263(gl, __contourVertSrc_273, __fragSrc_273, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'float'} ]) @@ -179540,8 +183349,8 @@ _$shaders_216.createContourShader = function (gl) { shader.attributes.f.location = 1 return shader } -_$shaders_216.createPickContourShader = function (gl) { - var shader = _$createShader_206(gl, __contourVertSrc_216, pickSrc, null, [ +_$shaders_273.createPickContourShader = function (gl) { + var shader = _$createShader_263(gl, __contourVertSrc_273, pickSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'float'} ]) @@ -179552,25 +183361,25 @@ _$shaders_216.createPickContourShader = function (gl) { 'use strict' -var _$gradient_268 = __gradient_268 +var _$gradient_326 = __gradient_326 -/* removed: var _$dupe_133 = require('dup') */; -/* removed: var _$compileCwise_115 = require('cwise-compiler') */; +/* removed: var _$dupe_136 = require('dup') */; +/* removed: var _$compileCwise_116 = require('cwise-compiler') */; var TEMPLATE_CACHE = {} var GRADIENT_CACHE = {} -var __EmptyProc_268 = { +var __EmptyProc_326 = { body: "", args: [], thisVars: [], localVars: [] } -var centralDiff = _$compileCwise_115({ +var centralDiff = _$compileCwise_116({ args: [ 'array', 'array', 'array' ], - pre: __EmptyProc_268, - post: __EmptyProc_268, + pre: __EmptyProc_326, + post: __EmptyProc_326, body: { args: [ { name: 'out', @@ -179595,10 +183404,10 @@ var centralDiff = _$compileCwise_115({ funcName: 'cdiff' }) -var zeroOut = _$compileCwise_115({ +var zeroOut = _$compileCwise_116({ args: [ 'array' ], - pre: __EmptyProc_268, - post: __EmptyProc_268, + pre: __EmptyProc_326, + post: __EmptyProc_326, body: { args: [ { name: 'out', @@ -179626,7 +183435,7 @@ function generateTemplate(d) { for(var i=0; i= 1) { return true } @@ -180063,9 +183872,9 @@ __proto_217.isOpaque = function () { return false } -__proto_217.pickSlots = 1 +__proto_274.pickSlots = 1 -__proto_217.setPickBase = function (id) { +__proto_274.setPickBase = function (id) { this.pickId = id } @@ -180074,7 +183883,7 @@ var ZERO_VEC = [0, 0, 0] var PROJECT_DATA = { showSurface: false, showContour: false, - projections: [__IDENTITY_217.slice(), __IDENTITY_217.slice(), __IDENTITY_217.slice()], + projections: [__IDENTITY_274.slice(), __IDENTITY_274.slice(), __IDENTITY_274.slice()], clipBounds: [ [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]], @@ -180108,7 +183917,7 @@ function computeProjectionData (camera, obj) { } axisSquish[5 * i] = 0 axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] - _$multiply_175(axisSquish, camera.model, axisSquish) + _$multiply_232(axisSquish, camera.model, axisSquish) var nclipBounds = PROJECT_DATA.clipBounds[i] for (k = 0; k < 2; ++k) { @@ -180127,10 +183936,10 @@ function computeProjectionData (camera, obj) { } var UNIFORMS = { - model: __IDENTITY_217, - view: __IDENTITY_217, - projection: __IDENTITY_217, - inverseModel: __IDENTITY_217.slice(), + model: __IDENTITY_274, + view: __IDENTITY_274, + projection: __IDENTITY_274, + inverseModel: __IDENTITY_274.slice(), lowerBound: [0, 0, 0], upperBound: [0, 0, 0], colorMap: 0, @@ -180151,7 +183960,7 @@ var UNIFORMS = { vertexColor: 0 } -var MATRIX_INVERSE = __IDENTITY_217.slice() +var MATRIX_INVERSE = __IDENTITY_274.slice() var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] function drawCore (params, transparent) { @@ -180163,14 +183972,14 @@ function drawCore (params, transparent) { this._colorMap.bind(0) var uniforms = UNIFORMS - uniforms.model = params.model || __IDENTITY_217 - uniforms.view = params.view || __IDENTITY_217 - uniforms.projection = params.projection || __IDENTITY_217 + uniforms.model = params.model || __IDENTITY_274 + uniforms.view = params.view || __IDENTITY_274 + uniforms.projection = params.projection || __IDENTITY_274 uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] uniforms.contourColor = this.contourColor[0] - uniforms.inverseModel = _$invert_173(uniforms.inverseModel, uniforms.model) + uniforms.inverseModel = _$invert_230(uniforms.inverseModel, uniforms.model) for (var i = 0; i < 2; ++i) { var clipClamped = uniforms.clipBounds[i] @@ -180194,9 +184003,9 @@ function drawCore (params, transparent) { // Compute camera matrix inverse var invCameraMatrix = MATRIX_INVERSE - _$multiply_175(invCameraMatrix, uniforms.view, uniforms.model) - _$multiply_175(invCameraMatrix, uniforms.projection, invCameraMatrix) - _$invert_173(invCameraMatrix, invCameraMatrix) + _$multiply_232(invCameraMatrix, uniforms.view, uniforms.model) + _$multiply_232(invCameraMatrix, uniforms.projection, invCameraMatrix) + _$invert_230(invCameraMatrix, invCameraMatrix) for (i = 0; i < 3; ++i) { uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15] @@ -180338,19 +184147,19 @@ function drawCore (params, transparent) { } } -__proto_217.draw = function (params) { +__proto_274.draw = function (params) { return drawCore.call(this, params, false) } -__proto_217.drawTransparent = function (params) { +__proto_274.drawTransparent = function (params) { return drawCore.call(this, params, true) } var PICK_UNIFORMS = { - model: __IDENTITY_217, - view: __IDENTITY_217, - projection: __IDENTITY_217, - inverseModel: __IDENTITY_217, + model: __IDENTITY_274, + view: __IDENTITY_274, + projection: __IDENTITY_274, + inverseModel: __IDENTITY_274, clipBounds: [[0, 0, 0], [0, 0, 0]], height: 0.0, shape: [0, 0], @@ -180363,15 +184172,15 @@ var PICK_UNIFORMS = { eyePosition: [0, 0, 0] } -__proto_217.drawPick = function (params) { +__proto_274.drawPick = function (params) { params = params || {} var gl = this.gl gl.disable(gl.CULL_FACE) var uniforms = PICK_UNIFORMS - uniforms.model = params.model || __IDENTITY_217 - uniforms.view = params.view || __IDENTITY_217 - uniforms.projection = params.projection || __IDENTITY_217 + uniforms.model = params.model || __IDENTITY_274 + uniforms.view = params.view || __IDENTITY_274 + uniforms.projection = params.projection || __IDENTITY_274 uniforms.shape = this._field[2].shape uniforms.pickId = this.pickId / 255.0 uniforms.lowerBound = this.bounds[0] @@ -180454,7 +184263,7 @@ __proto_217.drawPick = function (params) { } } -__proto_217.pick = function (selection) { +__proto_274.pick = function (selection) { if (!selection) { return null } @@ -180500,7 +184309,7 @@ __proto_217.pick = function (selection) { // Find closest level var levelIndex = this._pickResult.level for (var j = 0; j < 3; ++j) { - levelIndex[j] = _$searchBounds_71.le(this.contourLevels[j], pos[j]) + levelIndex[j] = _$searchBounds_72.le(this.contourLevels[j], pos[j]) if (levelIndex[j] < 0) { if (this.contourLevels[j].length > 0) { levelIndex[j] = 0 @@ -180532,16 +184341,16 @@ function padField (nfield, field) { var nshape = nfield.shape.slice() // Center - _$ndarrayOps_271.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) + _$ndarrayOps_329.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) // Edges - _$ndarrayOps_271.assign(nfield.lo(1).hi(shape[0], 1), + _$ndarrayOps_329.assign(nfield.lo(1).hi(shape[0], 1), field.hi(shape[0], 1)) - _$ndarrayOps_271.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), + _$ndarrayOps_329.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), field.lo(0, shape[1] - 1).hi(shape[0], 1)) - _$ndarrayOps_271.assign(nfield.lo(0, 1).hi(1, shape[1]), + _$ndarrayOps_329.assign(nfield.lo(0, 1).hi(1, shape[1]), field.hi(1)) - _$ndarrayOps_271.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), + _$ndarrayOps_329.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), field.lo(shape[0] - 1)) // Corners nfield.set(0, 0, field.get(0, 0)) @@ -180584,7 +184393,7 @@ function handleColor (param) { } } -__proto_217.update = function (params) { +__proto_274.update = function (params) { params = params || {} this.dirty = true @@ -180648,12 +184457,12 @@ __proto_217.update = function (params) { // Resize if necessary if (fsize > this._field[2].data.length) { - _$pool_360.freeFloat(this._field[2].data) - this._field[2].data = _$pool_360.mallocFloat(_$twiddle_72.nextPow2(fsize)) + _$pool_422.freeFloat(this._field[2].data) + this._field[2].data = _$pool_422.mallocFloat(_$twiddle_73.nextPow2(fsize)) } // Pad field - this._field[2] = _$wrappedNDArrayCtor_277(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) + this._field[2] = _$wrappedNDArrayCtor_335(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) padField(this._field[2], field) // Save shape of field @@ -180663,10 +184472,10 @@ __proto_217.update = function (params) { // Resize coordinate fields if necessary for (var i = 0; i < 2; ++i) { if (this._field[2].size > this._field[i].data.length) { - _$pool_360.freeFloat(this._field[i].data) - this._field[i].data = _$pool_360.mallocFloat(this._field[2].size) + _$pool_422.freeFloat(this._field[i].data) + this._field[i].data = _$pool_422.mallocFloat(this._field[2].size) } - this._field[i] = _$wrappedNDArrayCtor_277(this._field[i].data, [shape[0] + 2, shape[1] + 2]) + this._field[i] = _$wrappedNDArrayCtor_335(this._field[i].data, [shape[0] + 2, shape[1] + 2]) } // Generate x/y coordinates @@ -180692,13 +184501,13 @@ __proto_217.update = function (params) { for (i = 0; i < 2; ++i) { var tick = ticks[i] if (Array.isArray(tick) || tick.length) { - tick = _$wrappedNDArrayCtor_277(tick) + tick = _$wrappedNDArrayCtor_335(tick) } if (tick.shape[0] !== shape[i]) { throw new Error('gl-surface: invalid tick length') } // Make a copy view of the tick array - var tick2 = _$wrappedNDArrayCtor_277(tick.data, shape) + var tick2 = _$wrappedNDArrayCtor_335(tick.data, shape) tick2.stride[i] = tick.stride[0] tick2.stride[i ^ 1] = 0 @@ -180709,7 +184518,7 @@ __proto_217.update = function (params) { for (i = 0; i < 2; ++i) { var offset = [0, 0] offset[i] = 1 - this._field[i] = _$wrappedNDArrayCtor_277(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) + this._field[i] = _$wrappedNDArrayCtor_335(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) } this._field[0].set(0, 0, 0) for (var j = 0; j < shape[0]; ++j) { @@ -180727,11 +184536,11 @@ __proto_217.update = function (params) { var fields = this._field // Compute surface normals - var dfields = _$wrappedNDArrayCtor_277(_$pool_360.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) + var dfields = _$wrappedNDArrayCtor_335(_$pool_422.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) for (i = 0; i < 3; ++i) { - _$gradient_268(dfields.pick(i), fields[i], 'mirror') + _$gradient_326(dfields.pick(i), fields[i], 'mirror') } - var normals = _$wrappedNDArrayCtor_277(_$pool_360.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) + var normals = _$wrappedNDArrayCtor_335(_$pool_422.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) for (i = 0; i < shape[0] + 2; ++i) { for (j = 0; j < shape[1] + 2; ++j) { var dxdu = dfields.get(0, i, j, 0) @@ -180764,7 +184573,7 @@ __proto_217.update = function (params) { normals.set(i, j, 2, nz * nl) } } - _$pool_360.free(dfields.data) + _$pool_422.free(dfields.data) // Initialize surface var lo = [ Infinity, Infinity, Infinity ] @@ -180772,7 +184581,7 @@ __proto_217.update = function (params) { var lo_intensity = Infinity var hi_intensity = -Infinity var count = (shape[0] - 1) * (shape[1] - 1) * 6 - var tverts = _$pool_360.mallocFloat(_$twiddle_72.nextPow2(10 * count)) + var tverts = _$pool_422.mallocFloat(_$twiddle_73.nextPow2(10 * count)) var tptr = 0 var vertexCount = 0 for (i = 0; i < shape[0] - 1; ++i) { @@ -180843,8 +184652,8 @@ __proto_217.update = function (params) { this._vertexCount = vertexCount this._coordinateBuffer.update(tverts.subarray(0, tptr)) - _$pool_360.freeFloat(tverts) - _$pool_360.free(normals.data) + _$pool_422.freeFloat(tverts) + _$pool_422.free(normals.data) // Update bounds this.bounds = [lo, hi] @@ -180905,7 +184714,7 @@ __proto_217.update = function (params) { var parts = [0, 0, 0] for (i = 0; i < levels.length; ++i) { - var graph = _$surfaceNets_346(this._field[dim], levels[i]) + var graph = _$surfaceNets_408(this._field[dim], levels[i]) levelOffsets.push((contourVerts.length / 5) | 0) vertexCount = 0 @@ -180974,20 +184783,20 @@ __proto_217.update = function (params) { this._contourCounts[dim] = levelCounts } - var floatBuffer = _$pool_360.mallocFloat(contourVerts.length) + var floatBuffer = _$pool_422.mallocFloat(contourVerts.length) for (i = 0; i < contourVerts.length; ++i) { floatBuffer[i] = contourVerts[i] } this._contourBuffer.update(floatBuffer) - _$pool_360.freeFloat(floatBuffer) + _$pool_422.freeFloat(floatBuffer) } if (params.colormap) { - this._colorMap.setPixels(__genColormap_217(params.colormap)) + this._colorMap.setPixels(__genColormap_274(params.colormap)) } } -__proto_217.dispose = function () { +__proto_274.dispose = function () { this._shader.dispose() this._vao.dispose() this._coordinateBuffer.dispose() @@ -180999,11 +184808,11 @@ __proto_217.dispose = function () { this._dynamicBuffer.dispose() this._dynamicVAO.dispose() for (var i = 0; i < 3; ++i) { - _$pool_360.freeFloat(this._field[i].data) + _$pool_422.freeFloat(this._field[i].data) } } -__proto_217.highlight = function (selection) { +__proto_274.highlight = function (selection) { if (!selection) { this._dynamicCounts = [0, 0, 0] this.dyanamicLevel = [NaN, NaN, NaN] @@ -181033,7 +184842,7 @@ __proto_217.highlight = function (selection) { var vertexCount = 0 var shape = this.shape - var scratchBuffer = _$pool_360.mallocFloat(12 * shape[0] * shape[1]) + var scratchBuffer = _$pool_422.mallocFloat(12 * shape[0] * shape[1]) for (var d = 0; d < 3; ++d) { if (!this.enableDynamic[d]) { @@ -181052,7 +184861,7 @@ __proto_217.highlight = function (selection) { var h = this._field[v] var intensity = this.intensity - var graph = _$surfaceNets_346(f, levels[d]) + var graph = _$surfaceNets_408(f, levels[d]) var edges = graph.cells var positions = graph.positions @@ -181108,18 +184917,18 @@ __proto_217.highlight = function (selection) { } this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) - _$pool_360.freeFloat(scratchBuffer) + _$pool_422.freeFloat(scratchBuffer) } function createSurfacePlot (params) { var gl = params.gl - var shader = __createShader_217(gl) - var pickShader = __createPickShader_217(gl) - var contourShader = __createContourShader_217(gl) + var shader = __createShader_274(gl) + var pickShader = __createPickShader_274(gl) + var contourShader = __createContourShader_274(gl) var contourPickShader = createPickContourShader(gl) - var coordinateBuffer = _$createBuffer_153(gl) - var vao = _$createVAO_222(gl, [ + var coordinateBuffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { buffer: coordinateBuffer, size: 4, stride: SURFACE_VERTEX_SIZE, @@ -181138,8 +184947,8 @@ function createSurfacePlot (params) { } ]) - var contourBuffer = _$createBuffer_153(gl) - var contourVAO = _$createVAO_222(gl, [ + var contourBuffer = _$createBuffer_210(gl) + var contourVAO = _$createVAO_279(gl, [ { buffer: contourBuffer, size: 4, @@ -181154,15 +184963,15 @@ function createSurfacePlot (params) { } ]) - var dynamicBuffer = _$createBuffer_153(gl) - var dynamicVAO = _$createVAO_222(gl, [ + var dynamicBuffer = _$createBuffer_210(gl) + var dynamicVAO = _$createVAO_279(gl, [ { buffer: dynamicBuffer, size: 2, type: gl.FLOAT }]) - var cmap = _$createTexture2D_218(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) + var cmap = _$createTexture2D_275(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) cmap.minFilter = gl.LINEAR cmap.magFilter = gl.LINEAR @@ -181200,14 +185009,14 @@ function createSurfacePlot (params) { -var fill = _$wrapper_118({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_19_arg1_=_inline_19_arg2_.apply(void 0,_inline_19_arg0_)}","args":[{"name":"_inline_19_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_19_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_19_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) +var fill = _$wrapper_119({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_19_arg1_=_inline_19_arg2_.apply(void 0,_inline_19_arg0_)}","args":[{"name":"_inline_19_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_19_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_19_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) -var _$ndarrayFill_267 = function(array, f) { +var _$ndarrayFill_325 = function(array, f) { fill(array, f) return array } -var _$invert_165 = __invert_165 +var _$invert_222 = __invert_222 /** * Inverts a mat2 @@ -181217,7 +185026,7 @@ var _$invert_165 = __invert_165 * @param {mat2} a the source matrix * @returns {mat2} out */ -function __invert_165(out, a) { +function __invert_222(out, a) { var a0 = a[0] var a1 = a[1] var a2 = a[2] @@ -181235,7 +185044,7 @@ function __invert_165(out, a) { return out } -var _$invert_166 = __invert_166 +var _$invert_223 = __invert_223 /** * Inverts a mat3 @@ -181245,7 +185054,7 @@ var _$invert_166 = __invert_166 * @param {mat3} a the source matrix * @returns {mat3} out */ -function __invert_166(out, a) { +function __invert_223(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2] var a10 = a[3], a11 = a[4], a12 = a[5] var a20 = a[6], a21 = a[7], a22 = a[8] @@ -181275,13 +185084,13 @@ function __invert_166(out, a) { 'use strict' -var _$invert_184 = __invert_184 +var _$invert_241 = __invert_241 -/* removed: var _$invert_165 = require('gl-mat2/invert') */; -/* removed: var _$invert_166 = require('gl-mat3/invert') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; +/* removed: var _$invert_222 = require('gl-mat2/invert') */; +/* removed: var _$invert_223 = require('gl-mat3/invert') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; -function __invert_184(out, M) { +function __invert_241(out, M) { switch(M.length) { case 0: break @@ -181289,13 +185098,13 @@ function __invert_184(out, M) { out[0] = 1.0 / M[0] break case 4: - _$invert_165(out, M) + _$invert_222(out, M) break case 9: - _$invert_166(out, M) + _$invert_223(out, M) break case 16: - _$invert_173(out, M) + _$invert_230(out, M) break default: throw new Error('currently supports matrices up to 4x4') @@ -181303,7 +185112,7 @@ function __invert_184(out, M) { } return out } -var _$interp_270 = {}; +var _$interp_328 = {}; "use strict" function interp1d(arr, x) { @@ -181316,7 +185125,7 @@ function interp1d(arr, x) { return (1.0-fx)*w0 + fx*w1 } -function __interp2d_270(arr, x, y) { +function __interp2d_328(arr, x, y) { var ix = Math.floor(x) , fx = x - ix , s0 = 0 <= ix && ix < arr.shape[0] @@ -181395,51 +185204,51 @@ i_loop: return r } -function __interpolate_270(arr, x, y, z) { +function __interpolate_328(arr, x, y, z) { switch(arr.shape.length) { case 0: return 0.0 case 1: return interp1d(arr, x) case 2: - return __interp2d_270(arr, x, y) + return __interp2d_328(arr, x, y) case 3: return interp3d(arr, x, y, z) default: return interpNd.apply(undefined, arguments) } } -_$interp_270 = __interpolate_270 -_$interp_270.d1 = interp1d -_$interp_270.d2 = __interp2d_270 -_$interp_270.d3 = interp3d +_$interp_328 = __interpolate_328 +_$interp_328.d1 = interp1d +_$interp_328.d2 = __interp2d_328 +_$interp_328.d3 = interp3d 'use strict' -/* removed: var _$interp_270 = require('ndarray-linear-interpolate') */; +/* removed: var _$interp_328 = require('ndarray-linear-interpolate') */; -var do_warp = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_21_arg4_)}","args":[{"name":"_inline_21_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_22_arg2_(this_warped,_inline_22_arg0_),_inline_22_arg1_=_inline_22_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_22_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_22_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_22_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_22_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_22_arg4_","lvalue":false,"rvalue":false,"count":0}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64}) +var do_warp = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_21_arg4_)}","args":[{"name":"_inline_21_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_21_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_22_arg2_(this_warped,_inline_22_arg0_),_inline_22_arg1_=_inline_22_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_22_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_22_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_22_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_22_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_22_arg4_","lvalue":false,"rvalue":false,"count":0}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64}) -var do_warp_1 = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_25_arg2_(this_warped,_inline_25_arg0_),_inline_25_arg1_=_inline_25_arg3_(_inline_25_arg4_,this_warped[0])}","args":[{"name":"_inline_25_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_25_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_25_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_25_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_25_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64}) +var do_warp_1 = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_25_arg2_(this_warped,_inline_25_arg0_),_inline_25_arg1_=_inline_25_arg3_(_inline_25_arg4_,this_warped[0])}","args":[{"name":"_inline_25_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_25_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_25_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_25_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_25_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64}) -var do_warp_2 = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_28_arg2_(this_warped,_inline_28_arg0_),_inline_28_arg1_=_inline_28_arg3_(_inline_28_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_28_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_28_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_28_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_28_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_28_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64}) +var do_warp_2 = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_28_arg2_(this_warped,_inline_28_arg0_),_inline_28_arg1_=_inline_28_arg3_(_inline_28_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_28_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_28_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_28_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_28_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_28_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64}) -var do_warp_3 = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_31_arg2_(this_warped,_inline_31_arg0_),_inline_31_arg1_=_inline_31_arg3_(_inline_31_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_31_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_31_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64}) +var do_warp_3 = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_31_arg2_(this_warped,_inline_31_arg0_),_inline_31_arg1_=_inline_31_arg3_(_inline_31_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_31_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_31_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64}) -var _$warp_276 = function warp(dest, src, func) { +var _$warp_334 = function warp(dest, src, func) { switch(src.shape.length) { case 1: - do_warp_1(dest, func, _$interp_270.d1, src) + do_warp_1(dest, func, _$interp_328.d1, src) break case 2: - do_warp_2(dest, func, _$interp_270.d2, src) + do_warp_2(dest, func, _$interp_328.d2, src) break case 3: - do_warp_3(dest, func, _$interp_270.d3, src) + do_warp_3(dest, func, _$interp_328.d3, src) break default: - do_warp(dest, func, _$interp_270.bind(undefined, src), src.shape.length) + do_warp(dest, func, _$interp_328.bind(undefined, src), src.shape.length) break } return dest @@ -181447,15 +185256,15 @@ var _$warp_276 = function warp(dest, src, func) { 'use strict' -/* removed: var _$warp_276 = require('ndarray-warp') */; -/* removed: var _$invert_184 = require('gl-matrix-invert') */; +/* removed: var _$warp_334 = require('ndarray-warp') */; +/* removed: var _$invert_241 = require('gl-matrix-invert') */; -var _$applyHomography_269 = applyHomography +var _$applyHomography_327 = applyHomography function applyHomography(dest, src, Xi) { var n = src.dimension - var X = _$invert_184([], Xi) - _$warp_276(dest, src, function(out_c, inp_c) { + var X = _$invert_241([], Xi) + _$warp_334(dest, src, function(out_c, inp_c) { for(var i=0; i and doesn't seem to cause a speed difference columnBoundaryClippath.enter() .append('clipPath') - .classed(_$constants_945.cn.columnBoundaryClippath, true); + .classed(_$constants_1016.cn.columnBoundaryClippath, true); columnBoundaryClippath .attr('id', function(d) {return columnBoundaryClipKey(gd, d);}); - var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + _$constants_945.cn.columnBoundaryRect) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + _$constants_1016.cn.columnBoundaryRect) + .data(_$gup_598.repeat, _$gup_598.keyFun); columnBoundaryRect.enter() .append('rect') - .classed(_$constants_945.cn.columnBoundaryRect, true) + .classed(_$constants_1016.cn.columnBoundaryRect, true) .attr('fill', 'none'); columnBoundaryRect - .attr('width', function(d) {return d.columnWidth;}) - .attr('height', function(d) {return d.calcdata.height + _$constants_945.uplift;}); + .attr('width', function(d) { return d.columnWidth + 2 * roundHalfWidth(d); }) + .attr('height', function(d) {return d.calcdata.height + 2 * roundHalfWidth(d) + _$constants_1016.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; } @@ -182762,12 +186630,12 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { return firstRowAnchor(blocks, blocks.length - 1) + (blocks.length ? rowsHeight(blocks[blocks.length - 1], Infinity) : 1); } - var scrollbarKit = tableControlView.selectAll('.' + _$constants_945.cn.scrollbarKit) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarKit = tableControlView.selectAll('.' + _$constants_1016.cn.scrollbarKit) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarKit.enter() .append('g') - .classed(_$constants_945.cn.scrollbarKit, true) + .classed(_$constants_1016.cn.scrollbarKit, true) .style('shape-rendering', 'geometricPrecision'); scrollbarKit @@ -182777,7 +186645,7 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { 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, _$constants_945.goldenRatio * _$constants_945.scrollbarWidth); + s.barLength = Math.max(s.ratio * s.currentlyVisibleHeight, _$constants_1016.goldenRatio * _$constants_1016.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; @@ -182785,43 +186653,43 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { s.dragMultiplier = s.wiggleRoom / s.barWiggleRoom; }) .attr('transform', function(d) { - var xPosition = d.width + _$constants_945.scrollbarWidth / 2 + _$constants_945.scrollbarOffset; + var xPosition = d.width + _$constants_1016.scrollbarWidth / 2 + _$constants_1016.scrollbarOffset; return 'translate(' + xPosition + ' ' + headerHeight(d) + ')'; }); - var scrollbar = scrollbarKit.selectAll('.' + _$constants_945.cn.scrollbar) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbar = scrollbarKit.selectAll('.' + _$constants_1016.cn.scrollbar) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbar.enter() .append('g') - .classed(_$constants_945.cn.scrollbar, true); + .classed(_$constants_1016.cn.scrollbar, true); - var scrollbarSlider = scrollbar.selectAll('.' + _$constants_945.cn.scrollbarSlider) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarSlider = scrollbar.selectAll('.' + _$constants_1016.cn.scrollbarSlider) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarSlider.enter() .append('g') - .classed(_$constants_945.cn.scrollbarSlider, true); + .classed(_$constants_1016.cn.scrollbarSlider, true); scrollbarSlider .attr('transform', function(d) { return 'translate(0 ' + (d.scrollbarState.topY || 0) + ')'; }); - var scrollbarGlyph = scrollbarSlider.selectAll('.' + _$constants_945.cn.scrollbarGlyph) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarGlyph = scrollbarSlider.selectAll('.' + _$constants_1016.cn.scrollbarGlyph) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarGlyph.enter() .append('line') - .classed(_$constants_945.cn.scrollbarGlyph, true) + .classed(_$constants_1016.cn.scrollbarGlyph, true) .attr('stroke', 'black') - .attr('stroke-width', _$constants_945.scrollbarWidth) + .attr('stroke-width', _$constants_1016.scrollbarWidth) .attr('stroke-linecap', 'round') - .attr('y1', _$constants_945.scrollbarWidth / 2); + .attr('y1', _$constants_1016.scrollbarWidth / 2); scrollbarGlyph .attr('y2', function(d) { - return d.scrollbarState.barLength - _$constants_945.scrollbarWidth / 2; + return d.scrollbarState.barLength - _$constants_1016.scrollbarWidth / 2; }) .attr('stroke-opacity', function(d) { return d.columnDragInProgress || !d.scrollbarState.barWiggleRoom || bypassVisibleBar ? 0 : 0.4; @@ -182832,33 +186700,33 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { .transition().delay(0).duration(0); scrollbarGlyph - .transition().delay(_$constants_945.scrollbarHideDelay).duration(_$constants_945.scrollbarHideDuration) + .transition().delay(_$constants_1016.scrollbarHideDelay).duration(_$constants_1016.scrollbarHideDuration) .attr('stroke-opacity', 0); - var scrollbarCaptureZone = scrollbar.selectAll('.' + _$constants_945.cn.scrollbarCaptureZone) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarCaptureZone = scrollbar.selectAll('.' + _$constants_1016.cn.scrollbarCaptureZone) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarCaptureZone.enter() .append('line') - .classed(_$constants_945.cn.scrollbarCaptureZone, true) + .classed(_$constants_1016.cn.scrollbarCaptureZone, true) .attr('stroke', 'white') .attr('stroke-opacity', 0.01) // some browser might get rid of a 0 opacity element - .attr('stroke-width', _$constants_945.scrollbarCaptureWidth) + .attr('stroke-width', _$constants_1016.scrollbarCaptureWidth) .attr('stroke-linecap', 'butt') .attr('y1', 0) .on('mousedown', function(d) { - var y = _$d3_127.event.y; + var y = _$d3_130.event.y; var bbox = this.getBoundingClientRect(); var s = d.scrollbarState; var pixelVal = y - bbox.top; - var inverseScale = _$d3_127.scale.linear().domain([0, s.scrollableAreaHeight]).range([0, s.totalHeight]).clamp(true); + var inverseScale = _$d3_130.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_127.behavior.drag() + .call(_$d3_130.behavior.drag() .origin(function(d) { - _$d3_127.event.stopPropagation(); + _$d3_130.event.stopPropagation(); d.scrollbarState.scrollbarScrollInProgress = true; return d; }) @@ -182902,12 +186770,12 @@ function renderColumnCellTree(gd, tableControlView, columnBlock, allColumnBlock) function renderColumnCells(columnBlock) { - var columnCells = columnBlock.selectAll('.' + _$constants_945.cn.columnCells) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var columnCells = columnBlock.selectAll('.' + _$constants_1016.cn.columnCells) + .data(_$gup_598.repeat, _$gup_598.keyFun); columnCells.enter() .append('g') - .classed(_$constants_945.cn.columnCells, true); + .classed(_$constants_1016.cn.columnCells, true); columnCells.exit() .remove(); @@ -182917,12 +186785,12 @@ function renderColumnCells(columnBlock) { function renderColumnCell(columnCells) { - var columnCell = columnCells.selectAll('.' + _$constants_945.cn.columnCell) - .data(_$data_split_helpers_947.splitToCells, function(d) {return d.keyWithinBlock;}); + var columnCell = columnCells.selectAll('.' + _$constants_1016.cn.columnCell) + .data(_$data_split_helpers_1018.splitToCells, function(d) {return d.keyWithinBlock;}); columnCell.enter() .append('g') - .classed(_$constants_945.cn.columnCell, true); + .classed(_$constants_1016.cn.columnCell, true); columnCell.exit() .remove(); @@ -182932,38 +186800,38 @@ function renderColumnCell(columnCells) { function renderCellRect(columnCell) { - var cellRect = columnCell.selectAll('.' + _$constants_945.cn.cellRect) - .data(_$gup_536.repeat, function(d) {return d.keyWithinBlock;}); + var cellRect = columnCell.selectAll('.' + _$constants_1016.cn.cellRect) + .data(_$gup_598.repeat, function(d) {return d.keyWithinBlock;}); cellRect.enter() .append('rect') - .classed(_$constants_945.cn.cellRect, true); + .classed(_$constants_1016.cn.cellRect, true); return cellRect; } function renderCellText(cellTextHolder) { - var cellText = cellTextHolder.selectAll('.' + _$constants_945.cn.cellText) - .data(_$gup_536.repeat, function(d) {return d.keyWithinBlock;}); + var cellText = cellTextHolder.selectAll('.' + _$constants_1016.cn.cellText) + .data(_$gup_598.repeat, function(d) {return d.keyWithinBlock;}); cellText.enter() .append('text') - .classed(_$constants_945.cn.cellText, true) + .classed(_$constants_1016.cn.cellText, true) .style('cursor', function() {return 'auto';}) - .on('mousedown', function() {_$d3_127.event.stopPropagation();}); + .on('mousedown', function() {_$d3_130.event.stopPropagation();}); return cellText; } function renderCellTextHolder(columnCell) { - var cellTextHolder = columnCell.selectAll('.' + _$constants_945.cn.cellTextHolder) - .data(_$gup_536.repeat, function(d) {return d.keyWithinBlock;}); + var cellTextHolder = columnCell.selectAll('.' + _$constants_1016.cn.cellTextHolder) + .data(_$gup_598.repeat, function(d) {return d.keyWithinBlock;}); cellTextHolder.enter() .append('g') - .classed(_$constants_945.cn.cellTextHolder, true) + .classed(_$constants_1016.cn.cellTextHolder, true) .style('shape-rendering', 'geometricPrecision'); return cellTextHolder; @@ -182989,7 +186857,7 @@ function supplyStylingValues(columnCell) { function setFont(cellText) { cellText .each(function(d) { - _$drawing_436.font(_$d3_127.select(this), d.font); + _$drawing_498.font(_$d3_130.select(this), d.font); }); } @@ -182998,9 +186866,9 @@ function sizeAndStyleRect(cellRect) { .attr('width', function(d) {return d.column.columnWidth;}) .attr('stroke-width', function(d) {return d.cellBorderWidth;}) .each(function(d) { - var atomicSelection = _$d3_127.select(this); - _$color_411.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber)); - _$color_411.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber)); + var atomicSelection = _$d3_130.select(this); + _$color_473.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber)); + _$color_473.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber)); }); } @@ -183024,7 +186892,7 @@ function populateCellText(cellText, tableControlView, allColumnBlock, gd) { 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_127.format(format)(d.value) : d.value) + suffix; + var prefixSuffixedText = prefix + (format ? _$d3_130.format(format)(d.value) : d.value) + suffix; var hasWrapSplitCharacter; d.wrappingNeeded = !d.wrapped && !userBrokenText && !latex && (hasWrapSplitCharacter = hasWrapCharacter(prefixSuffixedText)); @@ -183033,12 +186901,12 @@ function populateCellText(cellText, tableControlView, allColumnBlock, gd) { var textToRender; if(d.wrappingNeeded) { - var hrefPreservedText = _$constants_945.wrapSplitCharacter === ' ' ? prefixSuffixedText.replace(/ rowLengthLimit) { - d.value += currentRow.join(_$constants_945.wrapSpacer) + _$constants_945.lineBreaker; + d.value += currentRow.join(_$constants_1016.wrapSpacer) + _$constants_1016.lineBreaker; currentRow = []; currentRowLength = 0; } @@ -183258,7 +187126,7 @@ function wrapTextMaker(columnBlock, element, tableControlView) { currentRowLength += currentAdditionLength; } if(currentRowLength) { - d.value += currentRow.join(_$constants_945.wrapSpacer); + d.value += currentRow.join(_$constants_1016.wrapSpacer); } d.wrapped = true; }); @@ -183267,21 +187135,21 @@ function wrapTextMaker(columnBlock, element, tableControlView) { cellTextHolder.selectAll('tspan.line').remove(); // resupply text, now wrapped - populateCellText(cellTextHolder.select('.' + _$constants_945.cn.cellText), tableControlView, columnBlock); - _$d3_127.select(element.parentNode.parentNode).call(setCellHeightAndPositionY); + populateCellText(cellTextHolder.select('.' + _$constants_1016.cn.cellText), tableControlView, columnBlock); + _$d3_130.select(element.parentNode.parentNode).call(setCellHeightAndPositionY); }; } function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { return function updateYPosition() { if(d.settledY) return; - var cellTextHolder = _$d3_127.select(element.parentNode); + var cellTextHolder = _$d3_130.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 * _$constants_945.cellPad : declaredRowHeight; + var requiredHeight = d.cellHeightMayIncrease ? element.parentNode.getBoundingClientRect().height + 2 * _$constants_1016.cellPad : declaredRowHeight; var finalHeight = Math.max(requiredHeight, declaredRowHeight); var increase = finalHeight - l.rows[rowIndex].rowHeight; @@ -183292,7 +187160,7 @@ function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { l.rows[rowIndex].rowHeight = finalHeight; columnBlock - .selectAll('.' + _$constants_945.cn.columnCell) + .selectAll('.' + _$constants_1016.cn.columnCell) .call(setCellHeightAndPositionY); updateBlockYPosition(null, columnBlock.filter(cellsBlock), 0); @@ -183309,10 +187177,10 @@ function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { var element = this; var columnCellElement = element.parentNode; var box = columnCellElement.getBoundingClientRect(); - var rectBox = _$d3_127.select(element.parentNode).select('.' + _$constants_945.cn.cellRect).node().getBoundingClientRect(); + var rectBox = _$d3_130.select(element.parentNode).select('.' + _$constants_1016.cn.cellRect).node().getBoundingClientRect(); var currentTransform = element.transform.baseVal.consolidate(); - var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : _$constants_945.cellPad); - return 'translate(' + xPosition(d, _$d3_127.select(element.parentNode).select('.' + _$constants_945.cn.cellTextHolder).node().getBoundingClientRect().width) + ' ' + yPosition + ')'; + var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : _$constants_1016.cellPad); + return 'translate(' + xPosition(d, _$d3_130.select(element.parentNode).select('.' + _$constants_1016.cn.cellTextHolder).node().getBoundingClientRect().width) + ' ' + yPosition + ')'; }); d.settledY = true; @@ -183321,10 +187189,10 @@ function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { function xPosition(d, optionalWidth) { switch(d.align) { - case 'left': return _$constants_945.cellPad; - case 'right': return d.column.columnWidth - (optionalWidth || 0) - _$constants_945.cellPad; + case 'left': return _$constants_1016.cellPad; + case 'right': return d.column.columnWidth - (optionalWidth || 0) - _$constants_1016.cellPad; case 'center': return (d.column.columnWidth - (optionalWidth || 0)) / 2; - default: return _$constants_945.cellPad; + default: return _$constants_1016.cellPad; } } @@ -183337,7 +187205,7 @@ function setCellHeightAndPositionY(columnCell) { var yOffset = rowAnchor + headerHeight; return 'translate(0 ' + yOffset + ')'; }) - .selectAll('.' + _$constants_945.cn.cellRect) + .selectAll('.' + _$constants_1016.cn.cellRect) .attr('height', function(d) {return getRow(getBlock(d), d.key).rowHeight;}); } @@ -183376,7 +187244,7 @@ function allRowsHeight(rowBlock) { function getBlock(d) {return d.rowBlocks[d.page];} function getRow(l, i) {return l.rows[i - l.firstRowIndex];} -var _$base_plot_943 = {}; +var _$base_plot_1014 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -183387,19 +187255,19 @@ var _$base_plot_943 = {}; 'use strict'; -var __getModuleCalcData_943 = _$get_data_621.getModuleCalcData; -/* removed: var _$plot_950 = require('./plot'); */; +var __getModuleCalcData_1014 = _$get_data_683.getModuleCalcData; +/* removed: var _$plot_1021 = require('./plot'); */; var TABLE = 'table'; -_$base_plot_943.name = TABLE; +_$base_plot_1014.name = TABLE; -_$base_plot_943.plot = function(gd) { - var calcData = __getModuleCalcData_943(gd.calcdata, TABLE); - if(calcData.length) _$plot_950(gd, calcData); +_$base_plot_1014.plot = function(gd) { + var calcData = __getModuleCalcData_1014(gd.calcdata, TABLE)[0]; + if(calcData.length) _$plot_1021(gd, calcData); }; -_$base_plot_943.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_1014.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadTable = (oldFullLayout._has && oldFullLayout._has(TABLE)); var hasTable = (newFullLayout._has && newFullLayout._has(TABLE)); @@ -183418,10 +187286,12 @@ _$base_plot_943.clean = function(newFullData, newFullLayout, oldFullData, oldFul 'use strict'; -var __wrap_944 = _$gup_536.wrap; +var __wrap_1015 = _$gup_598.wrap; -var _$calc_944 = function calc(gd, trace) { - return __wrap_944(trace); +var _$calc_1015 = 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_1015({}); }; /** @@ -183434,9 +187304,9 @@ var _$calc_944 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_942 = require('./attributes'); */; -var __handleDomainDefaults_948 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_1013 = require('./attributes'); */; +var __handleDomainDefaults_1019 = _$domain_672.defaults; function defaultColumnOrder(traceOut, coerce) { var specifiedColumnOrder = traceOut.columnorder || []; @@ -183450,12 +187320,12 @@ function defaultColumnOrder(traceOut, coerce) { coerce('columnorder', oneStepped); } -var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_1019 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_942, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_1013, attr, dflt); } - __handleDomainDefaults_948(traceOut, layout, coerce); + __handleDomainDefaults_1019(traceOut, layout, coerce); coerce('columnwidth'); @@ -183469,7 +187339,7 @@ var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('header.line.width'); coerce('header.line.color'); coerce('header.fill.color'); - _$lib_539.coerceFont(coerce, 'header.font', _$lib_539.extendFlat({}, layout.font)); + _$lib_601.coerceFont(coerce, 'header.font', _$lib_601.extendFlat({}, layout.font)); defaultColumnOrder(traceOut, coerce); @@ -183482,7 +187352,7 @@ var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('cells.line.width'); coerce('cells.line.color'); coerce('cells.fill.color'); - _$lib_539.coerceFont(coerce, 'cells.font', _$lib_539.extendFlat({}, layout.font)); + _$lib_601.coerceFont(coerce, 'cells.font', _$lib_601.extendFlat({}, layout.font)); }; /** @@ -183497,14 +187367,14 @@ var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultCol var Table = {}; -Table.attributes = _$attributes_942; -Table.supplyDefaults = _$supplyDefaults_948; -Table.calc = _$calc_944; -Table.plot = _$plot_950; +Table.attributes = _$attributes_1013; +Table.supplyDefaults = _$supplyDefaults_1019; +Table.calc = _$calc_1015; +Table.plot = _$plot_1021; Table.moduleType = 'trace'; Table.name = 'table'; -Table.basePlotModule = _$base_plot_943; +Table.basePlotModule = _$base_plot_1014; Table.categories = ['noOpacity']; Table.meta = { description: [ @@ -183515,7 +187385,7 @@ Table.meta = { ].join(' ') }; -var _$Table_949 = Table; +var _$Table_1020 = Table; /** * Copyright 2012-2018, Plotly, Inc. @@ -183527,7 +187397,7 @@ var _$Table_949 = Table; 'use strict'; -var _$table_37 = _$Table_949; +var _$table_38 = _$Table_1020; /** * Copyright 2012-2018, Plotly, Inc. @@ -183539,16 +187409,16 @@ var _$table_37 = _$Table_949; 'use strict'; -/* removed: var _$attributes_691 = require('../box/attributes'); */; -var __extendFlat_951 = _$extend_528.extendFlat; +/* removed: var _$attributes_754 = require('../box/attributes'); */; +var __extendFlat_1022 = _$extend_590.extendFlat; -var _$attributes_951 = { - y: _$attributes_691.y, - x: _$attributes_691.x, - x0: _$attributes_691.x0, - y0: _$attributes_691.y0, - name: _$attributes_691.name, - orientation: __extendFlat_951({}, _$attributes_691.orientation, { +var _$attributes_1022 = { + y: _$attributes_754.y, + x: _$attributes_754.x, + x0: _$attributes_754.x0, + y0: _$attributes_754.y0, + name: _$attributes_754.name, + orientation: __extendFlat_1022({}, _$attributes_754.orientation, { description: [ 'Sets the orientation of the violin(s).', 'If *v* (*h*), the distribution is visualized along', @@ -183637,9 +187507,9 @@ var _$attributes_951 = { }, editType: 'plot' }, - fillcolor: _$attributes_691.fillcolor, + fillcolor: _$attributes_754.fillcolor, - points: __extendFlat_951({}, _$attributes_691.boxpoints, { + points: __extendFlat_1022({}, _$attributes_754.boxpoints, { description: [ 'If *outliers*, only the sample points lying outside the whiskers', 'are shown', @@ -183650,7 +187520,7 @@ var _$attributes_951 = { 'If *false*, only the violins are shown with no sample points' ].join(' ') }), - jitter: __extendFlat_951({}, _$attributes_691.jitter, { + jitter: __extendFlat_1022({}, _$attributes_754.jitter, { description: [ 'Sets the amount of jitter in the sample points drawn.', 'If *0*, the sample points align along the distribution axis.', @@ -183658,7 +187528,7 @@ var _$attributes_951 = { 'equal to the width of the violins.' ].join(' ') }), - pointpos: __extendFlat_951({}, _$attributes_691.pointpos, { + pointpos: __extendFlat_1022({}, _$attributes_754.pointpos, { description: [ 'Sets the position of the sample points in relation to the violins.', 'If *0*, the sample points are places over the center of the violins.', @@ -183666,8 +187536,8 @@ var _$attributes_951 = { 'right (left) for vertical violins and above (below) for horizontal violins.' ].join(' ') }), - marker: _$attributes_691.marker, - text: _$attributes_691.text, + marker: _$attributes_754.marker, + text: _$attributes_754.text, box: { visible: { @@ -183760,8 +187630,8 @@ var _$attributes_951 = { ].join(' ') }, - selected: _$attributes_691.selected, - unselected: _$attributes_691.unselected, + selected: _$attributes_754.selected, + unselected: _$attributes_754.unselected, hoveron: { valType: 'flaglist', @@ -183777,7 +187647,7 @@ var _$attributes_951 = { } }; -var _$helpers_954 = {}; +var _$helpers_1025 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -183788,7 +187658,7 @@ var _$helpers_954 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; // Maybe add kernels more down the road, // but note that the default `spanmode: 'soft'` bounds might have @@ -183799,7 +187669,7 @@ var kernels = { } }; -_$helpers_954.makeKDE = function(calcItem, trace, vals) { +_$helpers_1025.makeKDE = function(calcItem, trace, vals) { var len = vals.length; var kernel = kernels.gaussian; var bandwidth = calcItem.bandwidth; @@ -183815,7 +187685,7 @@ _$helpers_954.makeKDE = function(calcItem, trace, vals) { }; }; -_$helpers_954.getPositionOnKdePath = function(calcItem, trace, valuePx) { +_$helpers_1025.getPositionOnKdePath = function(calcItem, trace, valuePx) { var posLetter, valLetter; if(trace.orientation === 'h') { @@ -183826,7 +187696,7 @@ _$helpers_954.getPositionOnKdePath = function(calcItem, trace, valuePx) { valLetter = 'y'; } - var pointOnPath = _$lib_539.findPointOnPath( + var pointOnPath = _$lib_601.findPointOnPath( calcItem.path, valuePx, valLetter, @@ -183842,13 +187712,13 @@ _$helpers_954.getPositionOnKdePath = function(calcItem, trace, valuePx) { return [posOnPath0, posOnPath1]; }; -_$helpers_954.getKdeValue = function(calcItem, trace, valueDist) { - var vals = calcItem.pts.map(_$helpers_954.extractVal); - var kde = _$helpers_954.makeKDE(calcItem, trace, vals); +_$helpers_1025.getKdeValue = function(calcItem, trace, valueDist) { + var vals = calcItem.pts.map(_$helpers_1025.extractVal); + var kde = _$helpers_1025.makeKDE(calcItem, trace, vals); return kde(valueDist) / calcItem.posDensityScale; }; -_$helpers_954.extractVal = function(o) { return o.v; }; +_$helpers_1025.extractVal = function(o) { return o.v; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -183860,19 +187730,19 @@ _$helpers_954.extractVal = function(o) { return o.v; }; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calc_692 = require('../box/calc'); */; -/* removed: var _$helpers_954 = require('./helpers'); */; -var __BADNUM_952 = _$numerical_517.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$calc_755 = require('../box/calc'); */; +/* removed: var _$helpers_1025 = require('./helpers'); */; +var __BADNUM_1023 = _$numerical_578.BADNUM; -var _$calc_952 = function calc(gd, trace) { - var cd = _$calc_692(gd, trace); +var _$calc_1023 = function calc(gd, trace) { + var cd = _$calc_755(gd, trace); if(cd[0].t.empty) return cd; var fullLayout = gd._fullLayout; - var valAxis = _$axes_584.getFromId( + var valAxis = _$axes_647.getFromId( gd, trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis'] ); @@ -183889,11 +187759,11 @@ var _$calc_952 = function calc(gd, trace) { for(var i = 0; i < cd.length; i++) { var cdi = cd[i]; - var vals = cdi.pts.map(_$helpers_954.extractVal); + var vals = cdi.pts.map(_$helpers_1025.extractVal); var len = vals.length; // sample standard deviation - var ssd = _$lib_539.stdev(vals, len - 1, cdi.mean); + var ssd = _$lib_601.stdev(vals, len - 1, cdi.mean); var bandwidthDflt = ruleOfThumbBandwidth(vals, ssd, cdi.q3 - cdi.q1); var bandwidth = cdi.bandwidth = trace.bandwidth || bandwidthDflt; var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth); @@ -183904,12 +187774,12 @@ var _$calc_952 = function calc(gd, trace) { var step = dist / n; if(!isFinite(step) || !isFinite(n)) { - _$lib_539.error('Something went wrong with computing the violin span'); + _$lib_601.error('Something went wrong with computing the violin span'); cd[0].t.empty = true; return cd; } - var kde = _$helpers_954.makeKDE(cdi, trace, vals); + var kde = _$helpers_1025.makeKDE(cdi, trace, vals); cdi.density = new Array(n); for(var k = 0, t = span[0]; t < (span[1] + step / 2); k++, t += step) { @@ -183918,11 +187788,11 @@ var _$calc_952 = function calc(gd, trace) { cdi.density[k] = {v: v, t: t}; } - _$axes_584.expand(valAxis, span, {padded: true}); + _$axes_647.expand(valAxis, span, {padded: true}); groupStats.maxCount = Math.max(groupStats.maxCount, vals.length); } - cd[0].t.labels.kde = _$lib_539._(gd, 'kde:'); + cd[0].t.labels.kde = _$lib_601._(gd, 'kde:'); return cd; }; @@ -183946,7 +187816,7 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { function calcSpanItem(index) { var s = spanIn[index]; var sc = valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']); - return sc === __BADNUM_952 ? spanLoose[index] : sc; + return sc === __BADNUM_1023 ? spanLoose[index] : sc; } if(spanmode === 'soft') { @@ -183962,7 +187832,7 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { type: 'linear', range: spanOut }; - _$axes_584.setConvert(dummyAx); + _$axes_647.setConvert(dummyAx); dummyAx.cleanRange(); return spanOut; @@ -183978,21 +187848,21 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$defaults_693 = require('../box/defaults'); */; -/* removed: var _$attributes_951 = require('./attributes'); */; +/* removed: var _$defaults_756 = require('../box/defaults'); */; +/* removed: var _$attributes_1022 = require('./attributes'); */; -var _$supplyDefaults_953 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_1024 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_951, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_1022, attr, dflt); } function coerce2(attr, dflt) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_951, attr, dflt); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_1022, attr, dflt); } - _$defaults_693.handleSampleDefaults(traceIn, traceOut, coerce, layout); + _$defaults_756.handleSampleDefaults(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; coerce('bandwidth'); @@ -184007,9 +187877,9 @@ var _$supplyDefaults_953 = function supplyDefaults(traceIn, traceOut, defaultCol var lineColor = coerce('line.color', (traceIn.marker || {}).color || defaultColor); var lineWidth = coerce('line.width'); - var fillColor = coerce('fillcolor', _$color_411.addOpacity(traceOut.line.color, 0.5)); + var fillColor = coerce('fillcolor', _$color_473.addOpacity(traceOut.line.color, 0.5)); - _$defaults_693.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''}); + _$defaults_756.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''}); var boxWidth = coerce2('box.width'); var boxFillColor = coerce2('box.fillcolor', fillColor); @@ -184034,12 +187904,12 @@ var _$supplyDefaults_953 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hover_694 = require('../box/hover'); */; -/* removed: var _$helpers_954 = require('./helpers'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hover_757 = require('../box/hover'); */; +/* removed: var _$helpers_1025 = require('./helpers'); */; -var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { +var _$hoverPoints_1026 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { var cd = pointData.cd; var trace = cd[0].trace; var hoveron = trace.hoveron; @@ -184050,7 +187920,7 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h var violinLineAttrs; if(hasHoveronViolins || hasHoveronKDE) { - var closeBoxData = _$hover_694.hoverOnBoxes(pointData, xval, yval, hovermode); + var closeBoxData = _$hover_757.hoverOnBoxes(pointData, xval, yval, hovermode); if(hasHoveronViolins) { closeData = closeData.concat(closeBoxData); @@ -184078,17 +187948,17 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h var di = cd[pointData.index]; if(vVal >= di.span[0] && vVal <= di.span[1]) { - var kdePointData = _$lib_539.extendFlat({}, pointData); + var kdePointData = _$lib_601.extendFlat({}, pointData); var vValPx = vAxis.c2p(vVal, true); - var kdeVal = _$helpers_954.getKdeValue(di, trace, vVal); - var pOnPath = _$helpers_954.getPositionOnKdePath(di, trace, vValPx); + var kdeVal = _$helpers_1025.getKdeValue(di, trace, vVal); + var pOnPath = _$helpers_1025.getPositionOnKdePath(di, trace, vValPx); var paOffset = pAxis._offset; var paLength = pAxis._length; kdePointData[pLetter + '0'] = pOnPath[0]; kdePointData[pLetter + '1'] = pOnPath[1]; kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx; - kdePointData[vLetter + 'Label'] = vLetter + ': ' + _$axes_584.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3); + kdePointData[vLetter + 'Label'] = vLetter + ': ' + _$axes_647.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3); // move the spike to the KDE point kdePointData.spikeDistance = closeBoxData[0].spikeDistance; @@ -184100,15 +187970,15 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h closeData.push(kdePointData); violinLineAttrs = {stroke: pointData.color}; - violinLineAttrs[pLetter + '1'] = _$lib_539.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength); - violinLineAttrs[pLetter + '2'] = _$lib_539.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength); + violinLineAttrs[pLetter + '1'] = _$lib_601.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength); + violinLineAttrs[pLetter + '2'] = _$lib_601.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength); violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx; } } } if(hoveron.indexOf('points') !== -1) { - closePtData = _$hover_694.hoverOnPoints(pointData, xval, yval); + closePtData = _$hover_757.hoverOnPoints(pointData, xval, yval); } // update violin line (if any) @@ -184142,11 +188012,11 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -/* removed: var _$layout_attributes_696 = require('../box/layout_attributes'); */; -var __extendFlat_957 = _$lib_539.extendFlat; +/* removed: var _$layout_attributes_759 = require('../box/layout_attributes'); */; +var __extendFlat_1028 = _$lib_601.extendFlat; -var _$layout_attributes_957 = { - violinmode: __extendFlat_957({}, _$layout_attributes_696.boxmode, { +var _$layout_attributes_1028 = { + violinmode: __extendFlat_1028({}, _$layout_attributes_759.boxmode, { description: [ 'Determines how violins at the same location coordinate', 'are displayed on the graph.', @@ -184156,13 +188026,13 @@ var _$layout_attributes_957 = { 'you might need to set *opacity* to see them multiple violins.' ].join(' ') }), - violingap: __extendFlat_957({}, _$layout_attributes_696.boxgap, { + violingap: __extendFlat_1028({}, _$layout_attributes_759.boxgap, { description: [ 'Sets the gap (in plot fraction) between violins of', 'adjacent location coordinates.' ].join(' ') }), - violingroupgap: __extendFlat_957({}, _$layout_attributes_696.boxgroupgap, { + violingroupgap: __extendFlat_1028({}, _$layout_attributes_759.boxgroupgap, { description: [ 'Sets the gap (in plot fraction) between violins of', 'the same location coordinate.' @@ -184180,15 +188050,15 @@ var _$layout_attributes_957 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_957 = require('./layout_attributes'); */; -/* removed: var _$layout_defaults_697 = require('../box/layout_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_1028 = require('./layout_attributes'); */; +/* removed: var _$layout_defaults_760 = require('../box/layout_defaults'); */; -var _$supplyLayoutDefaults_958 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { +var _$supplyLayoutDefaults_1029 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_957, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_1028, attr, dflt); } - _$layout_defaults_697._supply(layoutIn, layoutOut, fullData, coerce, 'violin'); + _$layout_defaults_760._supply(layoutIn, layoutOut, fullData, coerce, 'violin'); }; /** @@ -184201,20 +188071,20 @@ var _$supplyLayoutDefaults_958 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$plot_698 = require('../box/plot'); */; -/* removed: var _$linePoints_876 = require('../scatter/line_points'); */; -/* removed: var _$helpers_954 = require('./helpers'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$plot_761 = require('../box/plot'); */; +/* removed: var _$linePoints_941 = require('../scatter/line_points'); */; +/* removed: var _$helpers_1025 = require('./helpers'); */; -var _$plot_959 = function plot(gd, plotinfo, cd) { +var _$plot_1030 = function plot(gd, plotinfo, cd) { var fullLayout = gd._fullLayout; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; function makePath(pts) { - var segments = _$linePoints_876(pts, { + var segments = _$linePoints_941(pts, { xaxis: xa, yaxis: ya, connectGaps: true, @@ -184222,7 +188092,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { shape: 'spline', simplify: true }); - return _$drawing_436.smoothopen(segments[0], 1); + return _$drawing_498.smoothopen(segments[0], 1); } var traces = plotinfo.plot.select('.violinlayer') @@ -184235,16 +188105,21 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { var cd0 = d[0]; var t = cd0.t; var trace = cd0.trace; - var sel = cd0.node3 = _$d3_127.select(this); + var sel = _$d3_130.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; var numViolins = fullLayout._numViolins; var group = (fullLayout.violinmode === 'group' && numViolins > 1); + var groupFraction = 1 - fullLayout.violingap; // violin max half width - var bdPos = t.bdPos = t.dPos * (1 - fullLayout.violingap) * (1 - fullLayout.violingroupgap) / (group ? numViolins : 1); + var bdPos = t.bdPos = t.dPos * groupFraction * (1 - fullLayout.violingroupgap) / (group ? numViolins : 1); // violin center offset - var bPos = t.bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numViolins) * (1 - fullLayout.violingap) : 0; + var bPos = t.bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numViolins) * groupFraction : 0; + // half-width within which to accept hover for this violin + // always split the distance to the closest violin + t.wHover = t.dPos * (group ? groupFraction / numViolins : 1); if(trace.visible !== true || t.empty) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); return; } @@ -184258,12 +188133,12 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup]; sel.selectAll('path.violin') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .style('vector-effect', 'non-scaling-stroke') .attr('class', 'violin') .each(function(d) { - var pathSel = _$d3_127.select(this); + var pathSel = _$d3_130.select(this); var density = d.density; var len = density.length; var posCenter = d.pos + bPos; @@ -184350,7 +188225,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { // do not draw whiskers on inner boxes trace.whiskerwidth = 0; - _$plot_698.plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, { + _$plot_761.plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, { bPos: bPos, bdPos: bdPosScaled, bPosPxOffset: bPosPxOffset @@ -184358,7 +188233,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { // if both box and meanline are visible, show mean line inside box if(hasMeanLine) { - _$plot_698.plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, { + _$plot_761.plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, { bPos: bPos, bdPos: bdPosScaled, bPosPxOffset: bPosPxOffset @@ -184368,7 +188243,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { else { if(hasMeanLine) { sel.selectAll('path.mean') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .attr('class', 'mean') .style({ @@ -184377,9 +188252,9 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { }) .each(function(d) { var v = valAxis.c2p(d.mean, true); - var p = _$helpers_954.getPositionOnKdePath(d, trace, v); + var p = _$helpers_1025.getPositionOnKdePath(d, trace, v); - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', trace.orientation === 'h' ? 'M' + v + ',' + p[0] + 'V' + p[1] : 'M' + p[0] + ',' + v + 'H' + p[1] @@ -184389,7 +188264,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { } if(trace.points) { - _$plot_698.plotPoints(sel, {x: xa, y: ya}, trace, t); + _$plot_761.plotPoints(sel, {x: xa, y: ya}, trace, t); } }); }; @@ -184404,16 +188279,16 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { 'use strict'; -var __setPositionOffset_960 = _$set_positions_700.setPositionOffset; -var __orientations_960 = ['v', 'h']; +var __setPositionOffset_1031 = _$set_positions_763.setPositionOffset; +var __orientations_1031 = ['v', 'h']; -var _$setPositions_960 = function setPositions(gd, plotinfo) { +var _$setPositions_1031 = function setPositions(gd, plotinfo) { var calcdata = gd.calcdata; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; - for(var i = 0; i < __orientations_960.length; i++) { - var orientation = __orientations_960[i]; + for(var i = 0; i < __orientations_1031.length; i++) { + var orientation = __orientations_1031[i]; var posAxis = orientation === 'h' ? ya : xa; var violinList = []; var minPad = 0; @@ -184439,7 +188314,7 @@ var _$setPositions_960 = function setPositions(gd, plotinfo) { } } - __setPositionOffset_960('violin', gd, violinList, posAxis, [minPad, maxPad]); + __setPositionOffset_1031('violin', gd, violinList, posAxis, [minPad, maxPad]); } }; @@ -184453,18 +188328,18 @@ var _$setPositions_960 = function setPositions(gd, plotinfo) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -var __stylePoints_961 = _$style_883.stylePoints; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +var __stylePoints_1032 = _$style_948.stylePoints; -var _$style_961 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.violins'); +var _$style_1032 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.trace.violins'); s.style('opacity', function(d) { return d[0].trace.opacity; }); s.each(function(d) { var trace = d[0].trace; - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var box = trace.box || {}; var boxLine = box.line || {}; var meanline = trace.meanline || {}; @@ -184472,22 +188347,22 @@ var _$style_961 = function style(gd, cd) { sel.selectAll('path.violin') .style('stroke-width', trace.line.width + 'px') - .call(_$color_411.stroke, trace.line.color) - .call(_$color_411.fill, trace.fillcolor); + .call(_$color_473.stroke, trace.line.color) + .call(_$color_473.fill, trace.fillcolor); sel.selectAll('path.box') .style('stroke-width', boxLine.width + 'px') - .call(_$color_411.stroke, boxLine.color) - .call(_$color_411.fill, box.fillcolor); + .call(_$color_473.stroke, boxLine.color) + .call(_$color_473.fill, box.fillcolor); sel.selectAll('path.mean') .style({ 'stroke-width': meanLineWidth + 'px', 'stroke-dasharray': (2 * meanLineWidth) + 'px,' + meanLineWidth + 'px' }) - .call(_$color_411.stroke, meanline.color); + .call(_$color_473.stroke, meanline.color); - __stylePoints_961(sel, trace, gd); + __stylePoints_1032(sel, trace, gd); }); }; @@ -184501,22 +188376,22 @@ var _$style_961 = function style(gd, cd) { 'use strict'; -var _$violin_956 = { - attributes: _$attributes_951, - layoutAttributes: _$layout_attributes_957, - supplyDefaults: _$supplyDefaults_953, - supplyLayoutDefaults: _$supplyLayoutDefaults_958, - calc: _$calc_952, - setPositions: _$setPositions_960, - plot: _$plot_959, - style: _$style_961, - hoverPoints: _$hoverPoints_955, - selectPoints: _$selectPoints_699, +var _$violin_1027 = { + attributes: _$attributes_1022, + layoutAttributes: _$layout_attributes_1028, + supplyDefaults: _$supplyDefaults_1024, + supplyLayoutDefaults: _$supplyLayoutDefaults_1029, + calc: _$calc_1023, + setPositions: _$setPositions_1031, + plot: _$plot_1030, + style: _$style_1032, + hoverPoints: _$hoverPoints_1026, + selectPoints: _$selectPoints_762, moduleType: 'trace', name: 'violin', - basePlotModule: _$cartesian_595, - categories: ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend'], + basePlotModule: _$cartesian_658, + categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'draggedPts', 'violinLayout'], meta: { description: [ 'In vertical (horizontal) violin plots,', @@ -184540,7 +188415,7 @@ var _$violin_956 = { 'use strict'; -var _$violin_38 = _$violin_956; +var _$violin_39 = _$violin_1027; /** * Copyright 2012-2018, Plotly, Inc. @@ -184565,16 +188440,18 @@ _$core_12.register([ _$pie_24, _$contour_10, _$scatterternary_34, - _$violin_38, + _$violin_39, _$scatter3d_27, - _$surface_36, + _$surface_37, _$mesh3d_21, _$scattergeo_29, _$choropleth_9, _$scattergl_30, + _$splom_36, + _$pointcloud_25, _$heatmapgl_16, _$parcoords_23, @@ -184583,7 +188460,7 @@ _$core_12.register([ _$sankey_26, - _$table_37, + _$table_38, _$carpet_8, _$scattercarpet_28, diff --git a/dist/plotly.js b/dist/plotly.js index 90edf1a7a5c..cd1eee844e6 100644 --- a/dist/plotly.js +++ b/dist/plotly.js @@ -1,10 +1,160 @@ /** -* plotly.js v1.35.2 +* plotly.js v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Plotly = f()}})(function(){var define,module,exports; +var createModuleFactory = function createModuleFactory(factory) { + var module + return function (parent) { + if (!module) { + module = { exports: {}, parent: parent } + factory(module, module.exports) + } + return module.exports + } +}; +var _$shim_168 = createModuleFactory(function (module, exports) { +/* eslint no-proto: "off" */ + +// Big thanks to @WebReflection for sorting this out +// https://gist.github.com/WebReflection/5593554 + +"use strict"; + +var __dummy_168$0 = 0 + , __dummy_168$1 = 0 + , objIsPrototypeOf = Object.prototype.isPrototypeOf + , defineProperty = Object.defineProperty + , nullDesc = { + configurable: true, + enumerable: false, + writable: true, + value: undefined +} + , validate; + +validate = function (obj, prototype) { + _$validValue_171(obj); + if (prototype === null || _$isObject_159(prototype)) return obj; + throw new TypeError("Prototype must be null or an object"); +}; + +module.exports = (function (status) { + var fn, set; + if (!status) return null; + if (status.level === 2) { + if (status.set) { + set = status.set; + fn = function (obj, prototype) { + set.call(validate(obj, prototype), prototype); + return obj; + }; + } else { + fn = function (obj, prototype) { + validate(obj, prototype).__proto__ = prototype; + return obj; + }; + } + } else { + fn = function self(obj, prototype) { + var isNullBase; + validate(obj, prototype); + isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj); + if (isNullBase) delete self.nullPolyfill.__proto__; + if (prototype === null) prototype = self.nullPolyfill; + obj.__proto__ = prototype; + if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc); + return obj; + }; + } + return Object.defineProperty(fn, "level", { + configurable: false, + enumerable: false, + writable: false, + value: status.level + }); +}( + (function () { + var tmpObj1 = Object.create(null) + , tmpObj2 = {} + , set + , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"); + + if (desc) { + try { + set = desc.set; // Opera crashes at this point + set.call(tmpObj1, tmpObj2); + } catch (ignore) {} + if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 }; + } + + tmpObj1.__proto__ = tmpObj2; + if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 }; + + tmpObj1 = {}; + tmpObj1.__proto__ = tmpObj2; + if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 }; + + return false; + })() +)); + +_$create_156({}); + +}); +var _$create_156 = createModuleFactory(function (module, exports) { +// Workaround for http://code.google.com/p/v8/issues/detail?id=2804 + +"use strict"; + +var create = Object.create, shim; + +if (!_$isImplemented_167()) { + shim = _$shim_168({}); +} + +module.exports = (function () { + var nullObject, polyProps, desc; + if (!shim) return create; + if (shim.level !== 1) return create; + + nullObject = {}; + polyProps = {}; + desc = { + configurable: false, + enumerable: false, + writable: true, + value: undefined + }; + Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { + if (name === "__proto__") { + polyProps[name] = { + configurable: true, + enumerable: false, + writable: true, + value: undefined + }; + return; + } + polyProps[name] = desc; + }); + Object.defineProperties(nullObject, polyProps); + + Object.defineProperty(shim, "nullPolyfill", { + configurable: false, + enumerable: false, + writable: false, + value: nullObject + }); + + return function (prototype, props) { + return create(prototype === null ? nullObject : prototype, props); + }; +}()); + +}); /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16,7 +166,7 @@ 'use strict'; -var _$numerical_517 = { +var _$numerical_578 = { /** * Standardize all missing data in calcdata to use undefined * never null or NaN. @@ -63,7 +213,7 @@ var _$numerical_517 = { MINUS_SIGN: '\u2212' }; -var _$d3_127 = { exports: {} }; +var _$d3_130 = { exports: {} }; !function() { var d3 = { version: "3.5.17" @@ -9616,9 +9766,9 @@ var _$d3_127 = { exports: {} }; d3.xml = d3_xhrType(function(request) { return request.responseXML; }); - if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if ("object" === "object" && _$d3_127.exports) _$d3_127.exports = d3; else this.d3 = d3; + if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if ("object" === "object" && _$d3_130.exports) _$d3_130.exports = d3; else this.d3 = d3; }(); -_$d3_127 = _$d3_127.exports +_$d3_130 = _$d3_130.exports /** * inspired by is-number * but significantly simplified and sped up by ignoring number and string constructors @@ -9662,7 +9812,7 @@ function allBlankCharCodes(str){ return true; } -var _$fastIsnumeric_139 = function(n) { +var _$fastIsnumeric_196 = function(n) { var type = typeof n; if(type === 'string') { var original = n; @@ -9675,7 +9825,7 @@ var _$fastIsnumeric_139 = function(n) { return n - n < 1; }; -var _$angles_522 = {}; +var _$angles_583 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -9688,20 +9838,20 @@ var _$angles_522 = {}; var PI = Math.PI; -_$angles_522.deg2rad = function(deg) { +_$angles_583.deg2rad = function(deg) { return deg / 180 * PI; }; -_$angles_522.rad2deg = function(rad) { +_$angles_583.rad2deg = function(rad) { return rad / PI * 180; }; -_$angles_522.wrap360 = function(deg) { +_$angles_583.wrap360 = function(deg) { var out = deg % 360; return out < 0 ? out + 360 : out; }; -_$angles_522.wrap180 = function(deg) { +_$angles_583.wrap180 = function(deg) { if(Math.abs(deg) > 180) deg -= Math.round(deg / 360) * 360; return deg; }; @@ -9717,9 +9867,9 @@ _$angles_522.wrap180 = function(deg) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -var BADNUM = _$numerical_517.BADNUM; +var BADNUM = _$numerical_578.BADNUM; // precompile for speed var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; @@ -9728,17 +9878,17 @@ var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; * cleanNumber: remove common leading and trailing cruft * Always returns either a number or BADNUM. */ -var _$cleanNumber_523 = function cleanNumber(v) { +var _$cleanNumber_584 = function cleanNumber(v) { if(typeof v === 'string') { v = v.replace(JUNK, ''); } - if(_$fastIsnumeric_139(v)) return Number(v); + if(_$fastIsnumeric_196(v)) return Number(v); return BADNUM; }; -var _$tinycolor_352 = { exports: {} }; +var _$tinycolor_414 = { exports: {} }; // TinyColor v1.4.1 // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License @@ -10921,8 +11071,8 @@ function validateWCAG2Parms(parms) { } // Node: Export function -if ("object" !== "undefined" && _$tinycolor_352.exports) { - _$tinycolor_352.exports = tinycolor; +if ("object" !== "undefined" && _$tinycolor_414.exports) { + _$tinycolor_414.exports = tinycolor; } // AMD/requirejs: Define the module else if (typeof define === 'function' && define.amd) { @@ -10935,7 +11085,7 @@ else { })(Math); -_$tinycolor_352 = _$tinycolor_352.exports +_$tinycolor_414 = _$tinycolor_414.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -10947,7 +11097,7 @@ _$tinycolor_352 = _$tinycolor_352.exports 'use strict'; -var _$scales_430 = { +var _$scales_492 = { 'Greys': [ [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)'] ], @@ -11088,10 +11238,10 @@ var _$scales_430 = { 'use strict'; -/* removed: var _$scales_430 = require('./scales'); */; +/* removed: var _$scales_492 = require('./scales'); */; -var _$default_scale_420 = _$scales_430.RdBu; +var _$default_scale_482 = _$scales_492.RdBu; /** * Copyright 2012-2018, Plotly, Inc. @@ -11104,10 +11254,10 @@ var _$default_scale_420 = _$scales_430.RdBu; 'use strict'; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -var _$isValidScaleArray_428 = function isValidScaleArray(scl) { +var _$isValidScaleArray_490 = function isValidScaleArray(scl) { var highestVal = 0; if(!Array.isArray(scl) || scl.length < 2) return false; @@ -11119,7 +11269,7 @@ var _$isValidScaleArray_428 = function isValidScaleArray(scl) { for(var i = 0; i < scl.length; i++) { var si = scl[i]; - if(si.length !== 2 || +si[0] < highestVal || !_$tinycolor_352(si[1]).isValid()) { + if(si.length !== 2 || +si[0] < highestVal || !_$tinycolor_414(si[1]).isValid()) { return false; } @@ -11140,18 +11290,18 @@ var _$isValidScaleArray_428 = function isValidScaleArray(scl) { 'use strict'; -/* removed: var _$scales_430 = require('./scales'); */; -/* removed: var _$default_scale_420 = require('./default_scale'); */; -/* removed: var _$isValidScaleArray_428 = require('./is_valid_scale_array'); */; +/* removed: var _$scales_492 = require('./scales'); */; +/* removed: var _$default_scale_482 = require('./default_scale'); */; +/* removed: var _$isValidScaleArray_490 = require('./is_valid_scale_array'); */; -var _$getScale_424 = function getScale(scl, dflt) { - if(!dflt) dflt = _$default_scale_420; +var _$getScale_486 = function getScale(scl, dflt) { + if(!dflt) dflt = _$default_scale_482; if(!scl) return dflt; function parseScale() { try { - scl = _$scales_430[scl] || JSON.parse(scl); + scl = _$scales_492[scl] || JSON.parse(scl); } catch(e) { scl = dflt; @@ -11164,7 +11314,7 @@ var _$getScale_424 = function getScale(scl, dflt) { if(typeof scl === 'string') parseScale(); } - if(!_$isValidScaleArray_428(scl)) return dflt; + if(!_$isValidScaleArray_490(scl)) return dflt; return scl; }; @@ -11179,7 +11329,7 @@ var _$getScale_424 = function getScale(scl, dflt) { 'use strict'; -var _$interactions_516 = { +var _$interactions_577 = { /** * Timing information for interactive elements */ @@ -11194,7 +11344,7 @@ var _$interactions_516 = { DESELECTDIM: 0.2 }; -var _$is_array_540 = {}; +var _$is_array_602 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11215,12 +11365,12 @@ var dv = (typeof DataView === 'undefined') ? function() {} : DataView; -_$is_array_540.isTypedArray = function(a) { +_$is_array_602.isTypedArray = function(a) { return ab.isView(a) && !(a instanceof dv); }; -_$is_array_540.isArrayOrTypedArray = function(a) { - return Array.isArray(a) || _$is_array_540.isTypedArray(a); +_$is_array_602.isArrayOrTypedArray = function(a) { + return Array.isArray(a) || _$is_array_602.isTypedArray(a); }; /** @@ -11235,7 +11385,7 @@ _$is_array_540.isArrayOrTypedArray = function(a) { 'use strict'; // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing -var _$isPlainObject_541 = function isPlainObject(obj) { +var _$isPlainObject_603 = function isPlainObject(obj) { // We need to be a little less strict in the `imagetest` container because // of how async image requests are handled. @@ -11251,7 +11401,7 @@ var _$isPlainObject_541 = function isPlainObject(obj) { ); }; -var _$extend_528 = {}; +var _$extend_590 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11263,7 +11413,7 @@ var _$extend_528 = {}; 'use strict'; -/* removed: var _$isPlainObject_541 = require('./is_plain_object.js'); */; +/* removed: var _$isPlainObject_603 = require('./is_plain_object.js'); */; var isArray = Array.isArray; function primitivesLoopSplice(source, target) { @@ -11280,19 +11430,19 @@ function primitivesLoopSplice(source, target) { return true; } -_$extend_528.extendFlat = function() { +_$extend_590.extendFlat = function() { return _extend(arguments, false, false, false); }; -_$extend_528.extendDeep = function() { +_$extend_590.extendDeep = function() { return _extend(arguments, true, false, false); }; -_$extend_528.extendDeepAll = function() { +_$extend_590.extendDeepAll = function() { return _extend(arguments, true, true, false); }; -_$extend_528.extendDeepNoArrays = function() { +_$extend_590.extendDeepNoArrays = function() { return _extend(arguments, true, false, true); }; @@ -11345,12 +11495,12 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { } // recurse if we're merging plain objects or arrays - else if(isDeep && copy && (_$isPlainObject_541(copy) || (copyIsArray = isArray(copy)))) { + else if(isDeep && copy && (_$isPlainObject_603(copy) || (copyIsArray = isArray(copy)))) { if(copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { - clone = src && _$isPlainObject_541(src) ? src : {}; + clone = src && _$isPlainObject_603(src) ? src : {}; } // never move original objects, clone them @@ -11385,7 +11535,7 @@ function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { * so we get the right experience without any config argument. */ -var _$plot_config_574 = { +var _$plot_config_637 = { // no interactivity, for export or image generation staticPlot: false, @@ -11553,7 +11703,7 @@ var _$plot_config_574 = { locales: {} }; -var _$loggers_544 = {}; +var _$loggers_606 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11566,9 +11716,9 @@ var _$loggers_544 = {}; /* eslint-disable no-console */ -/* removed: var _$plot_config_574 = require('../plot_api/plot_config'); */; +/* removed: var _$plot_config_637 = require('../plot_api/plot_config'); */; -var loggers = _$loggers_544 = {}; +var loggers = _$loggers_606 = {}; /** * ------------------------------------------ @@ -11577,7 +11727,7 @@ var loggers = _$loggers_544 = {}; */ loggers.log = function() { - if(_$plot_config_574.logging > 1) { + if(_$plot_config_637.logging > 1) { var messages = ['LOG:']; for(var i = 0; i < arguments.length; i++) { @@ -11589,7 +11739,7 @@ loggers.log = function() { }; loggers.warn = function() { - if(_$plot_config_574.logging > 0) { + if(_$plot_config_637.logging > 0) { var messages = ['WARN:']; for(var i = 0; i < arguments.length; i++) { @@ -11601,7 +11751,7 @@ loggers.warn = function() { }; loggers.error = function() { - if(_$plot_config_574.logging > 0) { + if(_$plot_config_637.logging > 0) { var messages = ['ERROR:']; for(var i = 0; i < arguments.length; i++) { @@ -11640,7 +11790,7 @@ function apply(f, args) { // Simple helper functions // none of these need any external deps -var _$noop_548 = function noop() {}; +var _$noop_610 = function noop() {}; /** * Copyright 2012-2018, Plotly, Inc. @@ -11665,7 +11815,7 @@ var _$noop_548 = function noop() {}; * ref to array (now possibly containing one more item) * */ -var _$pushUnique_552 = function pushUnique(array, item) { +var _$pushUnique_615 = function pushUnique(array, item) { if(item instanceof RegExp) { var itemStr = item.toString(), i; @@ -11706,7 +11856,7 @@ var _$pushUnique_552 = function pushUnique(array, item) { * * @return {object} attributes object containing {family, size, color} as specified */ -var _$font_attributes_611 = function(opts) { +var _$font_attributes_673 = function(opts) { var editType = opts.editType; var colorEditType = opts.colorEditType; if(colorEditType === undefined) colorEditType = editType; @@ -11755,9 +11905,9 @@ var _$font_attributes_611 = function(opts) { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; -var _$attributes_445 = { +var _$attributes_507 = { hoverlabel: { bgcolor: { valType: 'color', @@ -11773,7 +11923,7 @@ var _$attributes_445 = { editType: 'none', }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ arrayOk: true, editType: 'none', @@ -11800,9 +11950,9 @@ var _$attributes_445 = { 'use strict'; -/* removed: var _$attributes_445 = require('../components/fx/attributes'); */; +/* removed: var _$attributes_507 = require('../components/fx/attributes'); */; -var _$attributes_581 = { +var _$attributes_644 = { type: { valType: 'enumerated', @@ -11886,7 +12036,7 @@ var _$attributes_581 = { editType: 'none', }, - hoverlabel: _$attributes_445.hoverlabel, + hoverlabel: _$attributes_507.hoverlabel, stream: { token: { valType: 'string', @@ -11909,7 +12059,7 @@ var _$attributes_581 = { } }; -var _$attributes_410 = {}; +var _$attributes_472 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -11922,7 +12072,7 @@ var _$attributes_410 = {}; // IMPORTANT - default colors should be in hex for compatibility -_$attributes_410.defaults = [ +_$attributes_472.defaults = [ '#1f77b4', // muted blue '#ff7f0e', // safety orange '#2ca02c', // cooked asparagus green @@ -11935,19 +12085,19 @@ _$attributes_410.defaults = [ '#17becf' // blue-teal ]; -_$attributes_410.defaultLine = '#444'; +_$attributes_472.defaultLine = '#444'; -_$attributes_410.lightLine = '#eee'; +_$attributes_472.lightLine = '#eee'; -_$attributes_410.background = '#fff'; +_$attributes_472.background = '#fff'; -_$attributes_410.borderLine = '#BEC8D9'; +_$attributes_472.borderLine = '#BEC8D9'; // with axis.color and Color.interp we aren't using lightLine // itself anymore, instead interpolating between axis.color // and the background color using tinycolor.mix. lightFraction // gives back exactly lightLine if the other colors are defaults. -_$attributes_410.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); +_$attributes_472.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); /** * Copyright 2012-2018, Plotly, Inc. @@ -11959,18 +12109,18 @@ _$attributes_410.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); 'use strict'; -/* removed: var _$font_attributes_611 = require('./font_attributes'); */; -/* removed: var _$attributes_410 = require('../components/color/attributes'); */; +/* removed: var _$font_attributes_673 = require('./font_attributes'); */; +/* removed: var _$attributes_472 = require('../components/color/attributes'); */; -var globalFont = _$font_attributes_611({ +var globalFont = _$font_attributes_673({ editType: 'calc', }); globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; globalFont.size.dflt = 12; -globalFont.color.dflt = _$attributes_410.defaultLine; +globalFont.color.dflt = _$attributes_472.defaultLine; -var _$layout_attributes_638 = { +var _$layout_attributes_700 = { font: globalFont, title: { valType: 'string', @@ -11978,7 +12128,7 @@ var _$layout_attributes_638 = { editType: 'layoutstyle', }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ editType: 'layoutstyle', }), @@ -12059,7 +12209,7 @@ var _$layout_attributes_638 = { paper_bgcolor: { valType: 'color', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, editType: 'plot', }, @@ -12068,7 +12218,7 @@ var _$layout_attributes_638 = { // because it needs to know if there are (2D) axes or not valType: 'color', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, editType: 'layoutstyle', }, @@ -12095,7 +12245,7 @@ var _$layout_attributes_638 = { }, colorway: { valType: 'colorlist', - dflt: _$attributes_410.defaults, + dflt: _$attributes_472.defaults, editType: 'calc', @@ -12108,7 +12258,7 @@ var _$layout_attributes_638 = { } }; -var _$registry_668 = {}; +var _$registry_731 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12119,29 +12269,29 @@ var _$registry_668 = {}; 'use strict'; -/* removed: var _$loggers_544 = require('./lib/loggers'); */; -/* removed: var _$noop_548 = require('./lib/noop'); */; -/* removed: var _$pushUnique_552 = require('./lib/push_unique'); */; -/* removed: var _$isPlainObject_541 = require('./lib/is_plain_object'); */; -/* removed: var _$extend_528 = require('./lib/extend'); */; +/* removed: var _$loggers_606 = require('./lib/loggers'); */; +/* removed: var _$noop_610 = require('./lib/noop'); */; +/* removed: var _$pushUnique_615 = require('./lib/push_unique'); */; +/* removed: var _$isPlainObject_603 = require('./lib/is_plain_object'); */; +/* removed: var _$extend_590 = require('./lib/extend'); */; -/* removed: var _$attributes_581 = require('./plots/attributes'); */; -/* removed: var _$layout_attributes_638 = require('./plots/layout_attributes'); */; +/* removed: var _$attributes_644 = require('./plots/attributes'); */; +/* removed: var _$layout_attributes_700 = require('./plots/layout_attributes'); */; -var extendFlat = _$extend_528.extendFlat; -var extendDeepAll = _$extend_528.extendDeepAll; +var extendFlat = _$extend_590.extendFlat; +var extendDeepAll = _$extend_590.extendDeepAll; -_$registry_668.modules = {}; -_$registry_668.allCategories = {}; -_$registry_668.allTypes = []; -_$registry_668.subplotsRegistry = {}; -_$registry_668.transformsRegistry = {}; -_$registry_668.componentsRegistry = {}; -_$registry_668.layoutArrayContainers = []; -_$registry_668.layoutArrayRegexes = []; -_$registry_668.traceLayoutAttributes = {}; -_$registry_668.localeRegistry = {}; -_$registry_668.apiMethodRegistry = {}; +_$registry_731.modules = {}; +_$registry_731.allCategories = {}; +_$registry_731.allTypes = []; +_$registry_731.subplotsRegistry = {}; +_$registry_731.transformsRegistry = {}; +_$registry_731.componentsRegistry = {}; +_$registry_731.layoutArrayContainers = []; +_$registry_731.layoutArrayRegexes = []; +_$registry_731.traceLayoutAttributes = {}; +_$registry_731.localeRegistry = {}; +_$registry_731.apiMethodRegistry = {}; /** * Top-level register routine, exported as Plotly.register @@ -12182,7 +12332,7 @@ _$registry_668.apiMethodRegistry = {}; * - fn {function} : the api method called with Register.call(); * */ -_$registry_668.register = function register(_modules) { +_$registry_731.register = function register(_modules) { if(!_modules) { throw new Error('No argument passed to Plotly.register.'); } else if(_modules && !Array.isArray(_modules)) { @@ -12211,7 +12361,7 @@ _$registry_668.register = function register(_modules) { break; case 'apiMethod': var name = newModule.name; - _$registry_668.apiMethodRegistry[name] = newModule.fn; + _$registry_731.apiMethodRegistry[name] = newModule.fn; break; default: throw new Error('Invalid module was attempted to be registered!'); @@ -12227,8 +12377,8 @@ _$registry_668.register = function register(_modules) { * @return {object} * module object corresponding to trace type */ -_$registry_668.getModule = function(trace) { - var _module = _$registry_668.modules[getTraceType(trace)]; +_$registry_731.getModule = function(trace) { + var _module = _$registry_731.modules[getTraceType(trace)]; if(!_module) return false; return _module._module; }; @@ -12242,20 +12392,20 @@ _$registry_668.getModule = function(trace) { * category in question * @return {boolean} */ -_$registry_668.traceIs = function(traceType, category) { +_$registry_731.traceIs = function(traceType, category) { traceType = getTraceType(traceType); // old plot.ly workspace hack, nothing to see here if(traceType === 'various') return false; - var _module = _$registry_668.modules[traceType]; + var _module = _$registry_731.modules[traceType]; if(!_module) { if(traceType && traceType !== 'area') { - _$loggers_544.log('Unrecognized trace type ' + traceType + '.'); + _$loggers_606.log('Unrecognized trace type ' + traceType + '.'); } - _module = _$registry_668.modules[_$attributes_581.type.dflt]; + _module = _$registry_731.modules[_$attributes_644.type.dflt]; } return !!_module.categories[category]; @@ -12272,7 +12422,7 @@ _$registry_668.traceIs = function(traceType, category) { * @return {array} * array of matching indices. If none found, returns [] */ -_$registry_668.getTransformIndices = function(data, type) { +_$registry_731.getTransformIndices = function(data, type) { var indices = []; var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { @@ -12292,7 +12442,7 @@ _$registry_668.getTransformIndices = function(data, type) { * type of trace to test * @return {boolean} */ -_$registry_668.hasTransform = function(data, type) { +_$registry_731.hasTransform = function(data, type) { var transforms = data.transforms || []; for(var i = 0; i < transforms.length; i++) { if(transforms[i].type === type) { @@ -12312,11 +12462,11 @@ _$registry_668.hasTransform = function(data, type) { * name of component module method * @return {function} */ -_$registry_668.getComponentMethod = function(name, method) { - var _module = _$registry_668.componentsRegistry[name]; +_$registry_731.getComponentMethod = function(name, method) { + var _module = _$registry_731.componentsRegistry[name]; - if(!_module) return _$noop_548; - return _module[method] || _$noop_548; + if(!_module) return _$noop_610; + return _module[method] || _$noop_610; }; /** @@ -12326,10 +12476,10 @@ _$registry_668.getComponentMethod = function(name, method) { * @param {...array} args : arguments passed to api method * @return {any} : returns api method output */ -_$registry_668.call = function() { +_$registry_731.call = function() { var name = arguments[0]; var args = [].slice.call(arguments, 1); - return _$registry_668.apiMethodRegistry[name].apply(null, args); + return _$registry_731.apiMethodRegistry[name].apply(null, args); }; function registerTraceModule(_module) { @@ -12337,33 +12487,33 @@ function registerTraceModule(_module) { var categoriesIn = _module.categories; var meta = _module.meta; - if(_$registry_668.modules[thisType]) { - _$loggers_544.log('Type ' + thisType + ' already registered'); + if(_$registry_731.modules[thisType]) { + _$loggers_606.log('Type ' + thisType + ' already registered'); return; } - if(!_$registry_668.subplotsRegistry[_module.basePlotModule.name]) { + if(!_$registry_731.subplotsRegistry[_module.basePlotModule.name]) { registerSubplot(_module.basePlotModule); } var categoryObj = {}; for(var i = 0; i < categoriesIn.length; i++) { categoryObj[categoriesIn[i]] = true; - _$registry_668.allCategories[categoriesIn[i]] = true; + _$registry_731.allCategories[categoriesIn[i]] = true; } - _$registry_668.modules[thisType] = { + _$registry_731.modules[thisType] = { _module: _module, categories: categoryObj }; if(meta && Object.keys(meta).length) { - _$registry_668.modules[thisType].meta = meta; + _$registry_731.modules[thisType].meta = meta; } - _$registry_668.allTypes.push(thisType); + _$registry_731.allTypes.push(thisType); - for(var componentName in _$registry_668.componentsRegistry) { + for(var componentName in _$registry_731.componentsRegistry) { mergeComponentAttrsToTrace(componentName, thisType); } @@ -12373,15 +12523,15 @@ function registerTraceModule(_module) { * (at least after https://github.com/plotly/documentation/issues/202 gets done!) */ if(_module.layoutAttributes) { - extendFlat(_$registry_668.traceLayoutAttributes, _module.layoutAttributes); + extendFlat(_$registry_731.traceLayoutAttributes, _module.layoutAttributes); } } function registerSubplot(_module) { var plotType = _module.name; - if(_$registry_668.subplotsRegistry[plotType]) { - _$loggers_544.log('Plot type ' + plotType + ' already registered.'); + if(_$registry_731.subplotsRegistry[plotType]) { + _$loggers_606.log('Plot type ' + plotType + ' already registered.'); return; } @@ -12391,9 +12541,9 @@ function registerSubplot(_module) { findArrayRegexps(_module); // not sure what's best for the 'cartesian' type at this point - _$registry_668.subplotsRegistry[plotType] = _module; + _$registry_731.subplotsRegistry[plotType] = _module; - for(var componentName in _$registry_668.componentsRegistry) { + for(var componentName in _$registry_731.componentsRegistry) { mergeComponentAttrsToSubplot(componentName, _module.name); } } @@ -12404,29 +12554,29 @@ function registerComponentModule(_module) { } var name = _module.name; - _$registry_668.componentsRegistry[name] = _module; + _$registry_731.componentsRegistry[name] = _module; if(_module.layoutAttributes) { if(_module.layoutAttributes._isLinkedToArray) { - _$pushUnique_552(_$registry_668.layoutArrayContainers, name); + _$pushUnique_615(_$registry_731.layoutArrayContainers, name); } findArrayRegexps(_module); } - for(var traceType in _$registry_668.modules) { + for(var traceType in _$registry_731.modules) { mergeComponentAttrsToTrace(name, traceType); } - for(var subplotName in _$registry_668.subplotsRegistry) { + for(var subplotName in _$registry_731.subplotsRegistry) { mergeComponentAttrsToSubplot(name, subplotName); } - for(var transformType in _$registry_668.transformsRegistry) { + for(var transformType in _$registry_731.transformsRegistry) { mergeComponentAttrsToTransform(name, transformType); } if(_module.schema && _module.schema.layout) { - extendDeepAll(_$layout_attributes_638, _module.schema.layout); + extendDeepAll(_$layout_attributes_700, _module.schema.layout); } } @@ -12443,22 +12593,22 @@ function registerTransformModule(_module) { throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.'); } if(hasTransform && hasCalcTransform) { - _$loggers_544.log([ + _$loggers_606.log([ prefix + ' has both a *transform* and *calcTransform* methods.', 'Please note that all *transform* methods are executed', 'before all *calcTransform* methods.' ].join(' ')); } - if(!_$isPlainObject_541(_module.attributes)) { - _$loggers_544.log(prefix + ' registered without an *attributes* object.'); + if(!_$isPlainObject_603(_module.attributes)) { + _$loggers_606.log(prefix + ' registered without an *attributes* object.'); } if(typeof _module.supplyDefaults !== 'function') { - _$loggers_544.log(prefix + ' registered without a *supplyDefaults* method.'); + _$loggers_606.log(prefix + ' registered without a *supplyDefaults* method.'); } - _$registry_668.transformsRegistry[_module.name] = _module; + _$registry_731.transformsRegistry[_module.name] = _module; - for(var componentName in _$registry_668.componentsRegistry) { + for(var componentName in _$registry_731.componentsRegistry) { mergeComponentAttrsToTransform(componentName, _module.name); } } @@ -12472,7 +12622,7 @@ function registerLocale(_module) { var hasDict = newDict && Object.keys(newDict).length; var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = _$registry_668.localeRegistry; + var locales = _$registry_731.localeRegistry; var localeObj = locales[locale]; if(!localeObj) locales[locale] = localeObj = {}; @@ -12504,37 +12654,37 @@ function findArrayRegexps(_module) { var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; if(arrayAttrRegexps) { for(var i = 0; i < arrayAttrRegexps.length; i++) { - _$pushUnique_552(_$registry_668.layoutArrayRegexes, arrayAttrRegexps[i]); + _$pushUnique_615(_$registry_731.layoutArrayRegexes, arrayAttrRegexps[i]); } } } } function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = _$registry_668.componentsRegistry[componentName].schema; + var componentSchema = _$registry_731.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.traces) return; var traceAttrs = componentSchema.traces[traceType]; if(traceAttrs) { - extendDeepAll(_$registry_668.modules[traceType]._module.attributes, traceAttrs); + extendDeepAll(_$registry_731.modules[traceType]._module.attributes, traceAttrs); } } function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = _$registry_668.componentsRegistry[componentName].schema; + var componentSchema = _$registry_731.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.transforms) return; var transformAttrs = componentSchema.transforms[transformType]; if(transformAttrs) { - extendDeepAll(_$registry_668.transformsRegistry[transformType].attributes, transformAttrs); + extendDeepAll(_$registry_731.transformsRegistry[transformType].attributes, transformAttrs); } } function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = _$registry_668.componentsRegistry[componentName].schema; + var componentSchema = _$registry_731.componentsRegistry[componentName].schema; if(!componentSchema || !componentSchema.subplots) return; - var subplotModule = _$registry_668.subplotsRegistry[subplotName]; + var subplotModule = _$registry_731.subplotsRegistry[subplotName]; var subplotAttrs = subplotModule.layoutAttributes; var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr; if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; @@ -12561,7 +12711,7 @@ function getTraceType(traceType) { 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$registry_731 = require('../registry'); */; /* * containerArrayMatch: does this attribute string point into a @@ -12576,9 +12726,9 @@ function getTraceType(traceType) { * if the whole array) and the property within that (or '' if the whole array * or the whole object) */ -var _$containerArrayMatch_568 = function containerArrayMatch(astr) { - var rootContainers = _$registry_668.layoutArrayContainers, - regexpContainers = _$registry_668.layoutArrayRegexes, +var _$containerArrayMatch_631 = function containerArrayMatch(astr) { + var rootContainers = _$registry_731.layoutArrayContainers, + regexpContainers = _$registry_731.layoutArrayRegexes, rootPart = astr.split('[')[0], arrayStr, match; @@ -12618,10 +12768,10 @@ var _$containerArrayMatch_568 = function containerArrayMatch(astr) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var isArrayOrTypedArray = _$is_array_540.isArrayOrTypedArray; -/* removed: var _$isPlainObject_541 = require('./is_plain_object'); */; -/* removed: var _$containerArrayMatch_568 = require('../plot_api/container_array_match'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var isArrayOrTypedArray = _$is_array_602.isArrayOrTypedArray; +/* removed: var _$isPlainObject_603 = require('./is_plain_object'); */; +/* removed: var _$containerArrayMatch_631 = require('../plot_api/container_array_match'); */; /** * convert a string s (such as 'xaxis.range[0]') @@ -12637,8 +12787,8 @@ var isArrayOrTypedArray = _$is_array_540.isArrayOrTypedArray; * you can't do nestedProperty(obj, 'arr[-1]').set(5) * but you can do nestedProperty(obj, 'arr').set([5, 5, 5]) */ -var _$nestedProperty_547 = function nestedProperty(container, propStr) { - if(_$fastIsnumeric_139(propStr)) propStr = String(propStr); +var _$nestedProperty_609 = function nestedProperty(container, propStr) { + if(_$fastIsnumeric_196(propStr)) propStr = String(propStr); else if(typeof propStr !== 'string' || propStr.substr(propStr.length - 4) === '[-1]') { throw 'bad property string'; @@ -12748,7 +12898,7 @@ var INFO_PATTERNS = /(^|\.)((domain|range)(\.[xy])?|args|parallels)$/; var ARGS_PATTERN = /(^|\.)args\[/; function isDeletable(val, propStr) { if(!emptyObj(val) || - (_$isPlainObject_541(val) && propStr.charAt(propStr.length - 1) === ']') || + (_$isPlainObject_603(val) && propStr.charAt(propStr.length - 1) === ']') || (propStr.match(ARGS_PATTERN) && val !== undefined) ) { return false; @@ -12757,7 +12907,7 @@ function isDeletable(val, propStr) { if(propStr.match(INFO_PATTERNS)) return true; - var match = _$containerArrayMatch_568(propStr); + var match = _$containerArrayMatch_631(propStr); // if propStr matches the container array itself, index is an empty string // otherwise we've matched something inside the container array, which may // still be a data array. @@ -12812,7 +12962,7 @@ function npSet(cont, parts, propStr) { function joinPropStr(propStr, newPart) { var toAdd = newPart; - if(_$fastIsnumeric_139(newPart)) toAdd = '[' + newPart + ']'; + if(_$fastIsnumeric_196(newPart)) toAdd = '[' + newPart + ']'; else if(propStr) toAdd = '.' + newPart; return propStr + toAdd; @@ -12910,7 +13060,7 @@ function badContainer(container, propStr, propParts) { }; } -var _$regex_554 = {}; +var _$regex_617 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12930,7 +13080,7 @@ var _$regex_554 = {}; * eg counterRegex('scene', '.annotations') for scene2.annotations etc. * @param {boolean} openEnded: if true, the string may continue past the match. */ -_$regex_554.counter = function(head, tail, openEnded) { +_$regex_617.counter = function(head, tail, openEnded) { var fullTail = (tail || '') + (openEnded ? '' : '$'); if(head === 'xy') { return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail); @@ -12938,7 +13088,7 @@ _$regex_554.counter = function(head, tail, openEnded) { return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail); }; -var _$coerce_524 = {}; +var _$coerce_586 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -12950,19 +13100,19 @@ var _$coerce_524 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$attributes_581 = require('../plots/attributes'); */; -/* removed: var _$getScale_424 = require('../components/colorscale/get_scale'); */; -var colorscaleNames = Object.keys(_$scales_430); -/* removed: var _$nestedProperty_547 = require('./nested_property'); */; -var counterRegex = _$regex_554.counter; -var DESELECTDIM = _$interactions_516.DESELECTDIM; -var wrap180 = _$angles_522.wrap180; -var __isArrayOrTypedArray_524 = _$is_array_540.isArrayOrTypedArray; +/* removed: var _$attributes_644 = require('../plots/attributes'); */; +/* removed: var _$getScale_486 = require('../components/colorscale/get_scale'); */; +var colorscaleNames = Object.keys(_$scales_492); +/* removed: var _$nestedProperty_609 = require('./nested_property'); */; +var counterRegex = _$regex_617.counter; +var DESELECTDIM = _$interactions_577.DESELECTDIM; +var wrap180 = _$angles_583.wrap180; +var __isArrayOrTypedArray_586 = _$is_array_602.isArrayOrTypedArray; -_$coerce_524.valObjectMeta = { +_$coerce_586.valObjectMeta = { data_array: { // You can use *dflt=[] to force said array to exist though. @@ -12970,7 +13120,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also - if(__isArrayOrTypedArray_524(v)) propOut.set(v); + if(__isArrayOrTypedArray_586(v)) propOut.set(v); else if(dflt !== undefined) propOut.set(dflt); } }, @@ -13012,7 +13162,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt, opts) { - if(!_$fastIsnumeric_139(v) || + if(!_$fastIsnumeric_196(v) || (opts.min !== undefined && v < opts.min) || (opts.max !== undefined && v > opts.max)) { propOut.set(dflt); @@ -13025,7 +13175,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt, opts) { - if(v % 1 || !_$fastIsnumeric_139(v) || + if(v % 1 || !_$fastIsnumeric_196(v) || (opts.min !== undefined && v < opts.min) || (opts.max !== undefined && v > opts.max)) { propOut.set(dflt); @@ -13054,7 +13204,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { - if(_$tinycolor_352(v).isValid()) propOut.set(v); + if(_$tinycolor_414(v).isValid()) propOut.set(v); else propOut.set(dflt); } }, @@ -13064,7 +13214,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { function isColor(color) { - return _$tinycolor_352(color).isValid(); + return _$tinycolor_414(color).isValid(); } if(!Array.isArray(v) || !v.length) propOut.set(dflt); else if(v.every(isColor)) propOut.set(v); @@ -13076,7 +13226,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { - propOut.set(_$getScale_424(v, dflt)); + propOut.set(_$getScale_486(v, dflt)); } }, angle: { @@ -13085,7 +13235,7 @@ _$coerce_524.valObjectMeta = { coerceFunction: function(v, propOut, dflt) { if(v === 'auto') propOut.set('auto'); - else if(!_$fastIsnumeric_139(v)) propOut.set(dflt); + else if(!_$fastIsnumeric_196(v)) propOut.set(dflt); else propOut.set(wrap180(+v)); } }, @@ -13093,8 +13243,9 @@ _$coerce_524.valObjectMeta = { - coerceFunction: function(v, propOut, dflt) { - if(typeof v === 'string' && counterRegex(dflt).test(v)) { + coerceFunction: function(v, propOut, dflt, opts) { + var regex = opts.regex || counterRegex(dflt); + if(typeof v === 'string' && regex.test(v)) { propOut.set(v); return; } @@ -13148,9 +13299,11 @@ _$coerce_524.valObjectMeta = { info_array: { - // set dimensions=2 for a 2D 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) { @@ -13161,12 +13314,12 @@ _$coerce_524.valObjectMeta = { if(dflt === undefined) dflt = opts.dflt; - _$coerce_524.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); + _$coerce_586.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts); return out; } - var twoD = opts.dimensions === 2; + var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0])); if(!Array.isArray(v)) { propOut.set(dflt); @@ -13176,19 +13329,28 @@ _$coerce_524.valObjectMeta = { var items = opts.items; var vOut = []; var arrayItems = Array.isArray(items); - var len = arrayItems ? items.length : v.length; + var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = (arrayItems && !innerItemsOnly) ? items.length : v.length; - var i, j, len2, vNew; + var i, j, row, item, len2, vNew; dflt = Array.isArray(dflt) ? dflt : []; if(twoD) { for(i = 0; i < len; i++) { vOut[i] = []; - var row = Array.isArray(v[i]) ? v[i] : []; - len2 = arrayItems ? items[i].length : row.length; + 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++) { - vNew = coercePart(row[j], arrayItems ? items[i][j] : items, (dflt[i] || [])[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; } } @@ -13219,12 +13381,12 @@ _$coerce_524.valObjectMeta = { return false; } for(var j = 0; j < v[i].length; j++) { - if(!_$coerce_524.validate(v[i][j], arrayItems ? items[i][j] : items)) { + if(!_$coerce_586.validate(v[i][j], arrayItems ? items[i][j] : items)) { return false; } } } - else if(!_$coerce_524.validate(v[i], arrayItems ? items[i] : items)) return false; + else if(!_$coerce_586.validate(v[i], arrayItems ? items[i] : items)) return false; } return true; @@ -13244,10 +13406,10 @@ _$coerce_524.valObjectMeta = { * if dflt is provided as an argument to lib.coerce it takes precedence * as a convenience, returns the value it finally set */ -_$coerce_524.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { - var opts = _$nestedProperty_547(attributes, attribute).get(), - propIn = _$nestedProperty_547(containerIn, attribute), - propOut = _$nestedProperty_547(containerOut, attribute), +_$coerce_586.coerce = function(containerIn, containerOut, attributes, attribute, dflt) { + var opts = _$nestedProperty_609(attributes, attribute).get(), + propIn = _$nestedProperty_609(containerIn, attribute), + propOut = _$nestedProperty_609(containerOut, attribute), v = propIn.get(); if(dflt === undefined) dflt = opts.dflt; @@ -13258,12 +13420,12 @@ _$coerce_524.coerce = function(containerIn, containerOut, attributes, attribute, * individual form (eg. some array vals can be numbers, even if the * single values must be color strings) */ - if(opts.arrayOk && __isArrayOrTypedArray_524(v)) { + if(opts.arrayOk && __isArrayOrTypedArray_586(v)) { propOut.set(v); return v; } - _$coerce_524.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); + _$coerce_586.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts); return propOut.get(); }; @@ -13275,9 +13437,9 @@ _$coerce_524.coerce = function(containerIn, containerOut, attributes, attribute, * returns attribute default if user input it not valid or * returns false if there is no user input. */ -_$coerce_524.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { - var propIn = _$nestedProperty_547(containerIn, attribute), - propOut = _$coerce_524.coerce(containerIn, containerOut, attributes, attribute, dflt), +_$coerce_586.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) { + var propIn = _$nestedProperty_609(containerIn, attribute), + propOut = _$coerce_586.coerce(containerIn, containerOut, attributes, attribute, dflt), valIn = propIn.get(); return (valIn !== undefined && valIn !== null) ? propOut : false; @@ -13288,7 +13450,7 @@ _$coerce_524.coerce2 = function(containerIn, containerOut, attributes, attribute * * 'coerce' is a lib.coerce wrapper with implied first three arguments */ -_$coerce_524.coerceFont = function(coerce, attr, dfltObj) { +_$coerce_586.coerceFont = function(coerce, attr, dfltObj) { var out = {}; dfltObj = dfltObj || {}; @@ -13308,11 +13470,9 @@ _$coerce_524.coerceFont = function(coerce, attr, dfltObj) { * @param {object} layoutOut : full layout object (require _dataLength ref) * @return {any} : the coerced value */ -_$coerce_524.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { +_$coerce_586.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { var moduleAttrs = traceOut._module.attributes; - var attrs = moduleAttrs.hoverinfo ? - {hoverinfo: moduleAttrs.hoverinfo} : - _$attributes_581; + var attrs = moduleAttrs.hoverinfo ? moduleAttrs : _$attributes_644; var valObj = attrs.hoverinfo; var dflt; @@ -13326,7 +13486,7 @@ _$coerce_524.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { dflt = flags.join('+'); } - return _$coerce_524.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); + return _$coerce_586.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt); }; /** Coerce shortcut for [un]selected.marker.opacity, @@ -13340,7 +13500,7 @@ _$coerce_524.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { * @param {object} traceOut : fullData item * @param {function} coerce : lib.coerce wrapper with implied first three arguments */ -_$coerce_524.coerceSelectionMarkerOpacity = function(traceOut, coerce) { +_$coerce_586.coerceSelectionMarkerOpacity = function(traceOut, coerce) { if(!traceOut.marker) return; var mo = traceOut.marker.opacity; @@ -13355,7 +13515,7 @@ _$coerce_524.coerceSelectionMarkerOpacity = function(traceOut, coerce) { // // Only give [un]selected.marker.opacity a default value if you don't // set any other [un]selected attributes. - if(!__isArrayOrTypedArray_524(mo) && !traceOut.selected && !traceOut.unselected) { + if(!__isArrayOrTypedArray_586(mo) && !traceOut.selected && !traceOut.unselected) { smoDflt = mo; usmoDflt = DESELECTDIM * mo; } @@ -13364,10 +13524,10 @@ _$coerce_524.coerceSelectionMarkerOpacity = function(traceOut, coerce) { coerce('unselected.marker.opacity', usmoDflt); }; -_$coerce_524.validate = function(value, opts) { - var valObjectDef = _$coerce_524.valObjectMeta[opts.valType]; +_$coerce_586.validate = function(value, opts) { + var valObjectDef = _$coerce_586.valObjectMeta[opts.valType]; - if(opts.arrayOk && __isArrayOrTypedArray_524(value)) return true; + if(opts.arrayOk && __isArrayOrTypedArray_586(value)) return true; if(valObjectDef.validateFunction) { return valObjectDef.validateFunction(value, opts); @@ -13397,12 +13557,12 @@ _$coerce_524.validate = function(value, opts) { * sanitized modulus function that always returns in the range [0, d) * rather than (-d, 0] if v is negative */ -var _$mod_546 = function mod(v, d) { +var _$mod_608 = function mod(v, d) { var out = v % d; return out < 0 ? out + d : out; }; -var _$dates_525 = {}; +var _$dates_587 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -13414,23 +13574,23 @@ var _$dates_525 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$loggers_544 = require('./loggers'); */; -/* removed: var _$mod_546 = require('./mod'); */; +/* removed: var _$loggers_606 = require('./loggers'); */; +/* removed: var _$mod_608 = require('./mod'); */; -/* removed: var _$numerical_517 = require('../constants/numerical'); */; -var __BADNUM_525 = _$numerical_517.BADNUM; -var ONEDAY = _$numerical_517.ONEDAY; -var ONEHOUR = _$numerical_517.ONEHOUR; -var ONEMIN = _$numerical_517.ONEMIN; -var ONESEC = _$numerical_517.ONESEC; -var EPOCHJD = _$numerical_517.EPOCHJD; +/* removed: var _$numerical_578 = require('../constants/numerical'); */; +var __BADNUM_587 = _$numerical_578.BADNUM; +var ONEDAY = _$numerical_578.ONEDAY; +var ONEHOUR = _$numerical_578.ONEHOUR; +var ONEMIN = _$numerical_578.ONEMIN; +var ONESEC = _$numerical_578.ONESEC; +var EPOCHJD = _$numerical_578.EPOCHJD; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$registry_731 = require('../registry'); */; -var utcFormat = _$d3_127.time.format.utc; +var utcFormat = _$d3_130.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 @@ -13442,7 +13602,7 @@ var YFIRST = new Date().getFullYear() - 70; function isWorldCalendar(calendar) { return ( calendar && - _$registry_668.componentsRegistry.calendars && + _$registry_731.componentsRegistry.calendars && typeof calendar === 'string' && calendar !== 'gregorian' ); } @@ -13452,11 +13612,11 @@ function isWorldCalendar(calendar) { * * bool sunday is for week ticks, shift it to a Sunday. */ -_$dates_525.dateTick0 = function(calendar, sunday) { +_$dates_587.dateTick0 = function(calendar, sunday) { if(isWorldCalendar(calendar)) { return sunday ? - _$registry_668.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : - _$registry_668.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; + _$registry_731.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] : + _$registry_731.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar]; } else { return sunday ? '2000-01-02' : '2000-01-01'; @@ -13466,9 +13626,9 @@ _$dates_525.dateTick0 = function(calendar, sunday) { /* * dfltRange: for each calendar, give a valid default range */ -_$dates_525.dfltRange = function(calendar) { +_$dates_587.dfltRange = function(calendar) { if(isWorldCalendar(calendar)) { - return _$registry_668.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; + return _$registry_731.getComponentMethod('calendars', 'DFLTRANGE')[calendar]; } else { return ['2000-01-01', '2001-01-01']; @@ -13476,7 +13636,7 @@ _$dates_525.dfltRange = function(calendar) { }; // is an object a javascript date? -_$dates_525.isJSDate = function(v) { +_$dates_587.isJSDate = function(v) { return typeof v === 'object' && v !== null && typeof v.getTime === 'function'; }; @@ -13538,17 +13698,17 @@ var MIN_MS, MAX_MS; * currently (2016) this range is: * 1946-2045 */ -_$dates_525.dateTime2ms = function(s, calendar) { +_$dates_587.dateTime2ms = function(s, calendar) { // first check if s is a date object - if(_$dates_525.isJSDate(s)) { + if(_$dates_587.isJSDate(s)) { // Convert to the UTC milliseconds that give the same // hours as this date has in the local timezone s = Number(s) - s.getTimezoneOffset() * ONEMIN; if(s >= MIN_MS && s <= MAX_MS) return s; - return __BADNUM_525; + return __BADNUM_587; } // otherwise only accept strings and numbers - if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_525; + if(typeof s !== 'string' && typeof s !== 'number') return __BADNUM_587; s = String(s); @@ -13565,7 +13725,7 @@ _$dates_525.dateTime2ms = function(s, calendar) { var isChinese = isWorld && calendar.substr(0, 7) === 'chinese'; var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if(!match) return __BADNUM_525; + if(!match) return __BADNUM_587; var y = match[1], m = match[3] || '1', d = Number(match[5] || 1), @@ -13575,12 +13735,12 @@ _$dates_525.dateTime2ms = function(s, calendar) { if(isWorld) { // disallow 2-digit years for world calendars - if(y.length === 2) return __BADNUM_525; + if(y.length === 2) return __BADNUM_587; y = Number(y); var cDate; try { - var calInstance = _$registry_668.getComponentMethod('calendars', 'getCal')(calendar); + var calInstance = _$registry_731.getComponentMethod('calendars', 'getCal')(calendar); if(isChinese) { var isIntercalary = m.charAt(m.length - 1) === 'i'; m = parseInt(m, 10); @@ -13590,9 +13750,9 @@ _$dates_525.dateTime2ms = function(s, calendar) { cDate = calInstance.newDate(y, Number(m), d); } } - catch(e) { return __BADNUM_525; } // Invalid ... date + catch(e) { return __BADNUM_587; } // Invalid ... date - if(!cDate) return __BADNUM_525; + if(!cDate) return __BADNUM_587; return ((cDate.toJD() - EPOCHJD) * ONEDAY) + (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC); @@ -13613,18 +13773,18 @@ _$dates_525.dateTime2ms = function(s, calendar) { var date = new Date(Date.UTC(2000, m, d, H, M)); date.setUTCFullYear(y); - if(date.getUTCMonth() !== m) return __BADNUM_525; - if(date.getUTCDate() !== d) return __BADNUM_525; + if(date.getUTCMonth() !== m) return __BADNUM_587; + if(date.getUTCDate() !== d) return __BADNUM_587; return date.getTime() + S * ONESEC; }; -MIN_MS = _$dates_525.MIN_MS = _$dates_525.dateTime2ms('-9999'); -MAX_MS = _$dates_525.MAX_MS = _$dates_525.dateTime2ms('9999-12-31 23:59:59.9999'); +MIN_MS = _$dates_587.MIN_MS = _$dates_587.dateTime2ms('-9999'); +MAX_MS = _$dates_587.MAX_MS = _$dates_587.dateTime2ms('9999-12-31 23:59:59.9999'); // is string s a date? (see above) -_$dates_525.isDateTime = function(s, calendar) { - return (_$dates_525.dateTime2ms(s, calendar) !== __BADNUM_525); +_$dates_587.isDateTime = function(s, calendar) { + return (_$dates_587.dateTime2ms(s, calendar) !== __BADNUM_587); }; // pad a number with zeroes, to given # of digits before the decimal point @@ -13643,20 +13803,20 @@ function lpad(val, digits) { var NINETYDAYS = 90 * ONEDAY; var THREEHOURS = 3 * ONEHOUR; var FIVEMIN = 5 * ONEMIN; -_$dates_525.ms2DateTime = function(ms, r, calendar) { - if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_525; +_$dates_587.ms2DateTime = function(ms, r, calendar) { + if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return __BADNUM_587; if(!r) r = 0; - var msecTenths = Math.floor(_$mod_546(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_608(ms + 0.05, 1) * 10), msRounded = Math.round(ms - msecTenths / 10), dateStr, h, m, s, msec10, d; if(isWorldCalendar(calendar)) { var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD, - timeMs = Math.floor(_$mod_546(ms, ONEDAY)); + timeMs = Math.floor(_$mod_608(ms, ONEDAY)); try { - dateStr = _$registry_668.getComponentMethod('calendars', 'getCal')(calendar) + dateStr = _$registry_731.getComponentMethod('calendars', 'getCal')(calendar) .fromJD(dateJD).formatDate('yyyy-mm-dd'); } catch(e) { @@ -13704,12 +13864,12 @@ _$dates_525.ms2DateTime = function(ms, r, calendar) { // 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. -_$dates_525.ms2DateTimeLocal = function(ms) { - if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_525; +_$dates_587.ms2DateTimeLocal = function(ms) { + if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return __BADNUM_587; - var msecTenths = Math.floor(_$mod_546(ms + 0.05, 1) * 10), + var msecTenths = Math.floor(_$mod_608(ms + 0.05, 1) * 10), d = new Date(Math.round(ms - msecTenths / 10)), - dateStr = _$d3_127.time.format('%Y-%m-%d')(d), + dateStr = _$d3_130.time.format('%Y-%m-%d')(d), h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), @@ -13740,23 +13900,23 @@ function includeTime(dateStr, h, m, s, msec10) { // 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 -_$dates_525.cleanDate = function(v, dflt, calendar) { - if(_$dates_525.isJSDate(v) || typeof v === 'number') { +_$dates_587.cleanDate = function(v, dflt, calendar) { + if(_$dates_587.isJSDate(v) || typeof v === 'number') { // do not allow milliseconds (old) or jsdate objects (inherently // described as gregorian dates) with world calendars if(isWorldCalendar(calendar)) { - _$loggers_544.error('JS Dates and milliseconds are incompatible with world calendars', v); + _$loggers_606.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 = _$dates_525.ms2DateTimeLocal(+v); + v = _$dates_587.ms2DateTimeLocal(+v); if(!v && dflt !== undefined) return dflt; } - else if(!_$dates_525.isDateTime(v, calendar)) { - _$loggers_544.error('unrecognized date', v); + else if(!_$dates_587.isDateTime(v, calendar)) { + _$loggers_606.error('unrecognized date', v); return dflt; } return v; @@ -13786,7 +13946,7 @@ function modDateFormat(fmt, x, formatter, calendar) { if(isWorldCalendar(calendar)) { try { - fmt = _$registry_668.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); + fmt = _$registry_731.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar); } catch(e) { return 'Invalid'; @@ -13803,13 +13963,13 @@ function modDateFormat(fmt, x, formatter, calendar) { */ var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; function formatTime(x, tr) { - var timePart = _$mod_546(x + 0.05, ONEDAY); + var timePart = _$mod_608(x + 0.05, ONEDAY); var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' + - lpad(_$mod_546(Math.floor(timePart / ONEMIN), 60), 2); + lpad(_$mod_608(Math.floor(timePart / ONEMIN), 60), 2); if(tr !== 'M') { - if(!_$fastIsnumeric_139(tr)) tr = 0; // should only be 'S' + if(!_$fastIsnumeric_196(tr)) tr = 0; // should only be 'S' /* * this is a weird one - and shouldn't come up unless people @@ -13826,7 +13986,7 @@ function formatTime(x, tr) { * 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_546(x / ONESEC, 60), MAXSECONDS[tr]); + var sec = Math.min(_$mod_608(x / ONESEC, 60), MAXSECONDS[tr]); var secStr = (100 + sec).toFixed(tr).substr(1); if(tr > 0) { @@ -13855,7 +14015,7 @@ function formatTime(x, tr) { * 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) */ -_$dates_525.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { +_$dates_587.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { calendar = isWorldCalendar(calendar) && calendar; if(!fmt) { @@ -13899,19 +14059,19 @@ _$dates_525.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) * and ticks on these days incrementing by month would be very unusual */ var THREEDAYS = 3 * ONEDAY; -_$dates_525.incrementMonth = function(ms, dMonth, calendar) { +_$dates_587.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_546(ms, ONEDAY); + var timeMs = _$mod_608(ms, ONEDAY); ms = Math.round(ms - timeMs); if(calendar) { try { var dateJD = Math.round(ms / ONEDAY) + EPOCHJD, - calInstance = _$registry_668.getComponentMethod('calendars', 'getCal')(calendar), + calInstance = _$registry_731.getComponentMethod('calendars', 'getCal')(calendar), cDate = calInstance.fromJD(dateJD); if(dMonth % 12) calInstance.add(cDate, dMonth, 'm'); @@ -13920,7 +14080,7 @@ _$dates_525.incrementMonth = function(ms, dMonth, calendar) { return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs; } catch(e) { - _$loggers_544.error('invalid ms ' + ms + ' in calendar ' + calendar); + _$loggers_606.error('invalid ms ' + ms + ' in calendar ' + calendar); // then keep going in gregorian even though the result will be 'Invalid' } } @@ -13935,7 +14095,7 @@ _$dates_525.incrementMonth = function(ms, dMonth, calendar) { * data: array of millisecond values * calendar (string) the calendar to test against */ -_$dates_525.findExactDates = function(data, calendar) { +_$dates_587.findExactDates = function(data, calendar) { var exactYears = 0, exactMonths = 0, exactDays = 0, @@ -13945,14 +14105,14 @@ _$dates_525.findExactDates = function(data, calendar) { var calInstance = ( isWorldCalendar(calendar) && - _$registry_668.getComponentMethod('calendars', 'getCal')(calendar) + _$registry_731.getComponentMethod('calendars', 'getCal')(calendar) ); for(var i = 0; i < data.length; i++) { di = data[i]; // not date data at all - if(!_$fastIsnumeric_139(di)) { + if(!_$fastIsnumeric_196(di)) { blankCount ++; continue; } @@ -14012,7 +14172,7 @@ _$dates_525.findExactDates = function(data, calendar) { * The goal is to just reuse memory to avoid a bit of excessive garbage * collection. */ -var _$ensureArray_526 = function ensureArray(out, n) { +var _$ensureArray_588 = function ensureArray(out, n) { if(!Array.isArray(out)) out = []; // If too long, truncate. (If too short, it will grow @@ -14055,7 +14215,7 @@ var _$ensureArray_526 = function ensureArray(out, n) { * @param {array} array base array * @return {array} new filtered array */ -var _$filterUnique_529 = function filterUnique(array) { +var _$filterUnique_591 = function filterUnique(array) { var seen = {}, out = [], j = 0; @@ -14089,7 +14249,7 @@ var _$filterUnique_529 = function filterUnique(array) { * @return {array of objects} of length <= container * */ -var _$filterVisible_530 = function filterVisible(container) { +var _$filterVisible_592 = function filterVisible(container) { var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; var out = []; @@ -14118,7 +14278,7 @@ function isCalcData(cont) { ); } -var _$geometry2d_533 = {}; +var _$geometry2d_595 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14129,13 +14289,13 @@ var _$geometry2d_533 = {}; 'use strict'; -/* removed: var _$mod_546 = require('./mod'); */; +/* removed: var _$mod_608 = require('./mod'); */; /* * look for intersection of two line segments * (1->2 and 3->4) - returns array [x,y] if they do, null if not */ -_$geometry2d_533.segmentsIntersect = segmentsIntersect; +_$geometry2d_595.segmentsIntersect = segmentsIntersect; function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { var a = x2 - x1, b = x3 - x1, @@ -14158,7 +14318,7 @@ function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { /* * find the minimum distance between two line segments (1->2 and 3->4) */ -_$geometry2d_533.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { +_$geometry2d_595.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 @@ -14211,7 +14371,7 @@ function perpDistance2(xab, yab, l2_ab, xac, yac) { var locationCache, workingPath, workingTextWidth; // turn a path and position along it into x, y, and angle for the given text -_$geometry2d_533.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { +_$geometry2d_595.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { if(path !== workingPath || textWidth !== workingTextWidth) { locationCache = {}; workingPath = path; @@ -14223,13 +14383,13 @@ _$geometry2d_533.getTextLocation = function getTextLocation(path, totalPathLen, // 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_546(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(_$mod_546(positionOnPath + textWidth / 2, totalPathLen)); + var p0 = path.getPointAtLength(_$mod_608(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(_$mod_608(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_546(positionOnPath, totalPathLen)); + var pCenter = path.getPointAtLength(_$mod_608(positionOnPath, totalPathLen)); var x = (pCenter.x * 4 + p0.x + p1.x) / 6; var y = (pCenter.y * 4 + p0.y + p1.y) / 6; @@ -14238,7 +14398,7 @@ _$geometry2d_533.getTextLocation = function getTextLocation(path, totalPathLen, return out; }; -_$geometry2d_533.clearLocationCache = function() { +_$geometry2d_595.clearLocationCache = function() { workingPath = null; }; @@ -14266,7 +14426,7 @@ _$geometry2d_533.clearLocationCache = function() { * the path). Note that if a path enters, exits, and re-enters the plot, we * will not capture this behavior. */ -_$geometry2d_533.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { +_$geometry2d_595.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) { var left = bounds.left; var right = bounds.right; var top = bounds.top; @@ -14327,7 +14487,7 @@ _$geometry2d_533.getVisibleSegment = function getVisibleSegment(path, bounds, bu * - {Number} iterationLimit * @return {SVGPoint} */ -_$geometry2d_533.findPointOnPath = function findPointOnPath(path, val, coord, opts) { +_$geometry2d_595.findPointOnPath = function findPointOnPath(path, val, coord, opts) { opts = opts || {}; var pathLength = opts.pathLength || path.getTotalLength(); @@ -14382,7 +14542,7 @@ _$geometry2d_533.findPointOnPath = function findPointOnPath(path, val, coord, op * * @returns {HTMLDivElement} the DOM element of the graph */ -var _$get_graph_div_534 = function(gd) { +var _$get_graph_div_596 = function(gd) { var gdElement; if(typeof gd === 'string') { @@ -14414,7 +14574,7 @@ var _$get_graph_div_534 = function(gd) { // Simple helper functions // none of these need any external deps -var _$identity_538 = function identity(d) { return d; }; +var _$identity_600 = function identity(d) { return d; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -14426,7 +14586,7 @@ var _$identity_538 = function identity(d) { return d; }; 'use strict'; -/* removed: var _$nestedProperty_547 = require('./nested_property'); */; +/* removed: var _$nestedProperty_609 = require('./nested_property'); */; var SIMPLE_PROPERTY_REGEX = /^\w*$/; @@ -14448,13 +14608,13 @@ var VALUE = 2; var BOTH = 3; var UNSET = 4; -var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, valueName) { +var _$keyedContainer_604 = function keyedContainer(baseObj, path, keyName, valueName) { keyName = keyName || 'name'; valueName = valueName || 'value'; var i, arr; var changeTypes = {}; - if(path && path.length) { arr = _$nestedProperty_547(baseObj, path).get(); + if(path && path.length) { arr = _$nestedProperty_609(baseObj, path).get(); } else { arr = baseObj; } @@ -14480,7 +14640,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value changeType = changeType | BOTH; idx = arr.length; indexLookup[name] = idx; - } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_547(arr[idx], valueName).get())) { + } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : _$nestedProperty_609(arr[idx], valueName).get())) { changeType = changeType | VALUE; } @@ -14490,7 +14650,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { newValue[valueName] = value; } else { - _$nestedProperty_547(newValue, valueName).set(value); + _$nestedProperty_609(newValue, valueName).set(value); } // If it's not an unset, force that bit to be unset. This is all related to the fact @@ -14511,7 +14671,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value } else if(isSimpleValueProp) { return arr[idx][valueName]; } else { - return _$nestedProperty_547(arr[idx], valueName).get(); + return _$nestedProperty_609(arr[idx], valueName).get(); } }, rename: function(name, newName) { @@ -14552,7 +14712,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value } 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_547(object, valueName).set(null); + _$nestedProperty_609(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, @@ -14579,7 +14739,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value if(isSimpleValueProp) { update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName]; } else { - update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_547(arr[idx], valueName).get(); + update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : _$nestedProperty_609(arr[idx], valueName).get(); } } } else { @@ -14605,7 +14765,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$registry_731 = require('../registry'); */; /** * localize: translate a string for the current locale @@ -14616,7 +14776,7 @@ var _$keyedContainer_542 = function keyedContainer(baseObj, path, keyName, value * gd._context.locales or globally via Plotly.register * @param {string} s: the string to translate */ -var _$localize_543 = function localize(gd, s) { +var _$localize_605 = function localize(gd, s) { var locale = gd._context.locale; /* @@ -14638,7 +14798,7 @@ var _$localize_543 = function localize(gd, s) { var out = dict[s]; if(out) return out; } - locales = _$registry_668.localeRegistry; + locales = _$registry_731.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -14649,7 +14809,7 @@ var _$localize_543 = function localize(gd, s) { return s; }; -var _$matrix_545 = {}; +var _$matrix_607 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14662,7 +14822,7 @@ var _$matrix_545 = {}; 'use strict'; -_$matrix_545.init2dArray = function(rowLength, colLength) { +_$matrix_607.init2dArray = function(rowLength, colLength) { var array = new Array(rowLength); for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength); return array; @@ -14673,7 +14833,7 @@ _$matrix_545.init2dArray = function(rowLength, colLength) { * http://stackoverflow.com/questions/17428587/ * transposing-a-2d-array-in-javascript */ -_$matrix_545.transposeRagged = function(z) { +_$matrix_607.transposeRagged = function(z) { var maxlen = 0, zlen = z.length, i, @@ -14691,7 +14851,7 @@ _$matrix_545.transposeRagged = function(z) { }; // our own dot function so that we don't need to include numeric -_$matrix_545.dot = function(x, y) { +_$matrix_607.dot = function(x, y) { if(!(x.length && y.length) || x.length !== y.length) return null; var len = x.length, @@ -14701,13 +14861,13 @@ _$matrix_545.dot = function(x, y) { if(x[0].length) { // mat-vec or mat-mat out = new Array(len); - for(i = 0; i < len; i++) out[i] = _$matrix_545.dot(x[i], y); + for(i = 0; i < len; i++) out[i] = _$matrix_607.dot(x[i], y); } else if(y[0].length) { // vec-mat - var yTranspose = _$matrix_545.transposeRagged(y); + var yTranspose = _$matrix_607.transposeRagged(y); out = new Array(yTranspose.length); - for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_545.dot(x, yTranspose[i]); + for(i = 0; i < yTranspose.length; i++) out[i] = _$matrix_607.dot(x, yTranspose[i]); } else { // vec-vec @@ -14719,12 +14879,12 @@ _$matrix_545.dot = function(x, y) { }; // translate by (x,y) -_$matrix_545.translationMatrix = function(x, y) { +_$matrix_607.translationMatrix = function(x, y) { return [[1, 0, x], [0, 1, y], [0, 0, 1]]; }; // rotate by alpha around (0,0) -_$matrix_545.rotationMatrix = function(alpha) { +_$matrix_607.rotationMatrix = function(alpha) { var a = alpha * Math.PI / 180; return [[Math.cos(a), -Math.sin(a), 0], [Math.sin(a), Math.cos(a), 0], @@ -14732,28 +14892,28 @@ _$matrix_545.rotationMatrix = function(alpha) { }; // rotate by alpha around (x,y) -_$matrix_545.rotationXYMatrix = function(a, x, y) { - return _$matrix_545.dot( - _$matrix_545.dot(_$matrix_545.translationMatrix(x, y), - _$matrix_545.rotationMatrix(a)), - _$matrix_545.translationMatrix(-x, -y)); +_$matrix_607.rotationXYMatrix = function(a, x, y) { + return _$matrix_607.dot( + _$matrix_607.dot(_$matrix_607.translationMatrix(x, y), + _$matrix_607.rotationMatrix(a)), + _$matrix_607.translationMatrix(-x, -y)); }; // applies a 2D transformation matrix to either x and y params or an [x,y] array -_$matrix_545.apply2DTransform = function(transform) { +_$matrix_607.apply2DTransform = function(transform) { return function() { var args = arguments; if(args.length === 3) { args = args[0]; }// from map var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return _$matrix_545.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + return _$matrix_607.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); }; }; // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment) -_$matrix_545.apply2DTransform2 = function(transform) { - var at = _$matrix_545.apply2DTransform(transform); +_$matrix_607.apply2DTransform2 = function(transform) { + var at = _$matrix_607.apply2DTransform(transform); return function(xys) { return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); }; @@ -14770,8 +14930,8 @@ _$matrix_545.apply2DTransform2 = function(transform) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; var NOTEDATA = []; @@ -14782,16 +14942,16 @@ var NOTEDATA = []; * or 'long' which provides 2000 ms delay time. * @return {undefined} this function does not return a value */ -var _$notifier_549 = function(text, displayLength) { +var _$notifier_611 = function(text, displayLength) { if(NOTEDATA.indexOf(text) !== -1) return; NOTEDATA.push(text); var ts = 1000; - if(_$fastIsnumeric_139(displayLength)) ts = displayLength; + if(_$fastIsnumeric_196(displayLength)) ts = displayLength; else if(displayLength === 'long') ts = 3000; - var notifierContainer = _$d3_127.select('body') + var notifierContainer = _$d3_130.select('body') .selectAll('.plotly-notifier') .data([0]); notifierContainer.enter() @@ -14807,7 +14967,7 @@ var _$notifier_549 = function(text, displayLength) { .each('end', function(thisText) { var thisIndex = NOTEDATA.indexOf(thisText); if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1); - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); }); } @@ -14815,7 +14975,7 @@ var _$notifier_549 = function(text, displayLength) { .classed('notifier-note', true) .style('opacity', 0) .each(function(thisText) { - var note = _$d3_127.select(this); + var note = _$d3_130.select(this); note.append('button') .classed('notifier-close', true) @@ -14874,7 +15034,7 @@ var SIMPLEATTR = /^[^\.\[\]]+$/; * relativeAttr('annotations[3].x', '^^margin') = 'margin' * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r' */ -var _$relative_attr_555 = function(baseAttr, relativeAttr) { +var _$relative_attr_618 = function(baseAttr, relativeAttr) { while(relativeAttr) { var match = baseAttr.match(ASCEND); @@ -14903,8 +15063,8 @@ var _$relative_attr_555 = function(baseAttr, relativeAttr) { 'use strict'; -var __isArrayOrTypedArray_556 = _$is_array_540.isArrayOrTypedArray; -/* removed: var _$isPlainObject_541 = require('./is_plain_object'); */; +var __isArrayOrTypedArray_619 = _$is_array_602.isArrayOrTypedArray; +/* removed: var _$isPlainObject_603 = require('./is_plain_object'); */; /** * Relink private _keys and keys with a function value from one container @@ -14913,7 +15073,7 @@ var __isArrayOrTypedArray_556 = _$is_array_540.isArrayOrTypedArray; * if object is pass-by-ref. * This prevents deepCopying massive structures like a webgl context. */ -var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContainer) { +var _$relinkPrivateKeys_619 = function relinkPrivateKeys(toContainer, fromContainer) { for(var k in fromContainer) { var fromVal = fromContainer[k]; var toVal = toContainer[k]; @@ -14929,7 +15089,7 @@ var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContai toContainer[k] = fromVal; } - else if(__isArrayOrTypedArray_556(fromVal) && __isArrayOrTypedArray_556(toVal) && _$isPlainObject_541(fromVal[0])) { + else if(__isArrayOrTypedArray_619(fromVal) && __isArrayOrTypedArray_619(toVal) && _$isPlainObject_603(fromVal[0])) { // filter out data_array items that can contain user objects // most of the time the toVal === fromVal check will catch these early @@ -14939,12 +15099,12 @@ var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContai // 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_541(fromVal[j]) && _$isPlainObject_541(toVal[j])) { + if((toVal[j] !== fromVal[j]) && _$isPlainObject_603(fromVal[j]) && _$isPlainObject_603(toVal[j])) { relinkPrivateKeys(toVal[j], fromVal[j]); } } } - else if(_$isPlainObject_541(fromVal) && _$isPlainObject_541(toVal)) { + else if(_$isPlainObject_603(fromVal) && _$isPlainObject_603(toVal)) { // recurse into objects, but only if they still exist relinkPrivateKeys(toVal, fromVal); @@ -14954,7 +15114,7 @@ var _$relinkPrivateKeys_556 = function relinkPrivateKeys(toContainer, fromContai } }; -var _$search_557 = {}; +var _$search_620 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -14966,8 +15126,8 @@ var _$search_557 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$loggers_544 = require('./loggers'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$loggers_606 = require('./loggers'); */; // don't trust floating point equality - fraction of bin size to call // "on the line" and ensure that they go the right way specified by @@ -14985,8 +15145,8 @@ var roundingError = 1e-9; * search linelow (truthy) says the bin boundary should be attributed to * the lower bin rather than the default upper bin */ -_$search_557.findBin = function(val, bins, linelow) { - if(_$fastIsnumeric_139(bins.start)) { +_$search_620.findBin = function(val, bins, linelow) { + if(_$fastIsnumeric_196(bins.start)) { return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError); @@ -15009,7 +15169,7 @@ _$search_557.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) _$loggers_544.log('Long binary search...'); + if(c > 90) _$loggers_606.log('Long binary search...'); return n1 - 1; } }; @@ -15019,17 +15179,17 @@ function lessOrEqual(a, b) { return a <= b; } function greaterThan(a, b) { return a > b; } function greaterOrEqual(a, b) { return a >= b; } -_$search_557.sorterAsc = function(a, b) { return a - b; }; -_$search_557.sorterDes = function(a, b) { return b - a; }; +_$search_620.sorterAsc = function(a, b) { return a - b; }; +_$search_620.sorterDes = function(a, b) { return b - a; }; /** * find distinct values in an array, lumping together ones that appear to * just be off by a rounding error * return the distinct values and the minimum difference between any two */ -_$search_557.distinctVals = function(valsIn) { +_$search_620.distinctVals = function(valsIn) { var vals = valsIn.slice(); // otherwise we sort the original array... - vals.sort(_$search_557.sorterAsc); + vals.sort(_$search_620.sorterAsc); var l = vals.length - 1, minDiff = (vals[l] - vals[0]) || 1, @@ -15054,7 +15214,7 @@ _$search_557.distinctVals = function(valsIn) { * particularly useful for date/time where things are not powers of 10 * binary search is probably overkill here... */ -_$search_557.roundUp = function(val, arrayIn, reverse) { +_$search_620.roundUp = function(val, arrayIn, reverse) { var low = 0, high = arrayIn.length - 1, mid, @@ -15071,7 +15231,7 @@ _$search_557.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -var _$stats_560 = {}; +var _$stats_623 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15083,8 +15243,8 @@ var _$stats_560 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_560 = _$is_array_540.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_623 = _$is_array_602.isArrayOrTypedArray; /** * aggNums() returns the result of an aggregate function applied to an array of @@ -15099,20 +15259,20 @@ var __isArrayOrTypedArray_560 = _$is_array_540.isArrayOrTypedArray; * @param {Number} len - maximum length of a to aggregate * @return {Number} - result of f applied to a starting from v */ -_$stats_560.aggNums = function(f, v, a, len) { +_$stats_623.aggNums = function(f, v, a, len) { var i, b; if(!len || len > a.length) len = a.length; - if(!_$fastIsnumeric_139(v)) v = false; - if(__isArrayOrTypedArray_560(a[0])) { + if(!_$fastIsnumeric_196(v)) v = false; + if(__isArrayOrTypedArray_623(a[0])) { b = new Array(len); - for(i = 0; i < len; i++) b[i] = _$stats_560.aggNums(f, v, a[i]); + for(i = 0; i < len; i++) b[i] = _$stats_623.aggNums(f, v, a[i]); a = b; } for(i = 0; i < len; i++) { - if(!_$fastIsnumeric_139(v)) v = a[i]; - else if(_$fastIsnumeric_139(a[i])) v = f(+v, +a[i]); + if(!_$fastIsnumeric_196(v)) v = a[i]; + else if(_$fastIsnumeric_196(a[i])) v = f(+v, +a[i]); } return v; }; @@ -15121,26 +15281,26 @@ _$stats_560.aggNums = function(f, v, a, len) { * mean & std dev functions using aggNums, so it handles non-numerics nicely * even need to use aggNums instead of .length, to toss out non-numerics */ -_$stats_560.len = function(data) { - return _$stats_560.aggNums(function(a) { return a + 1; }, 0, data); +_$stats_623.len = function(data) { + return _$stats_623.aggNums(function(a) { return a + 1; }, 0, data); }; -_$stats_560.mean = function(data, len) { - if(!len) len = _$stats_560.len(data); - return _$stats_560.aggNums(function(a, b) { return a + b; }, 0, data) / len; +_$stats_623.mean = function(data, len) { + if(!len) len = _$stats_623.len(data); + return _$stats_623.aggNums(function(a, b) { return a + b; }, 0, data) / len; }; -_$stats_560.variance = function(data, len, mean) { - if(!len) len = _$stats_560.len(data); - if(!_$fastIsnumeric_139(mean)) mean = _$stats_560.mean(data, len); +_$stats_623.variance = function(data, len, mean) { + if(!len) len = _$stats_623.len(data); + if(!_$fastIsnumeric_196(mean)) mean = _$stats_623.mean(data, len); - return _$stats_560.aggNums(function(a, b) { + return _$stats_623.aggNums(function(a, b) { return a + Math.pow(b - mean, 2); }, 0, data) / len; }; -_$stats_560.stdev = function(data, len, mean) { - return Math.sqrt(_$stats_560.variance(data, len, mean)); +_$stats_623.stdev = function(data, len, mean) { + return Math.sqrt(_$stats_623.variance(data, len, mean)); }; /** @@ -15158,8 +15318,8 @@ _$stats_560.stdev = function(data, len, mean) { * For example, the 50th percentile (or median) corresponds to n = 0.5 * @return {Number} - percentile */ -_$stats_560.interp = function(arr, n) { - if(!_$fastIsnumeric_139(n)) throw 'n should be a finite number'; +_$stats_623.interp = function(arr, n) { + if(!_$fastIsnumeric_196(n)) throw 'n should be a finite number'; n = n * arr.length - 0.5; if(n < 0) return arr[0]; if(n > arr.length - 1) return arr[arr.length - 1]; @@ -15167,7 +15327,7 @@ _$stats_560.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -var _$throttle_563 = {}; +var _$throttle_626 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -15194,7 +15354,7 @@ var timerCache = {}; * @param {function} callback: the function to throttle. `callback` itself * should be a purely synchronous function. */ -_$throttle_563.throttle = function throttle(id, minInterval, callback) { +_$throttle_626.throttle = function throttle(id, minInterval, callback) { var cache = timerCache[id]; var now = Date.now(); @@ -15234,7 +15394,7 @@ _$throttle_563.throttle = function throttle(id, minInterval, callback) { }, minInterval); }; -_$throttle_563.done = function(id) { +_$throttle_626.done = function(id) { var cache = timerCache[id]; if(!cache || !cache.timer) return Promise.resolve(); @@ -15254,13 +15414,13 @@ _$throttle_563.done = function(id) { * if provided, clear just this timer * if omitted, clear all timers (mainly useful for testing) */ -_$throttle_563.clear = function(id) { +_$throttle_626.clear = function(id) { if(id) { _clearTimeout(timerCache[id]); delete timerCache[id]; } else { - for(var idi in timerCache) _$throttle_563.clear(idi); + for(var idi in timerCache) _$throttle_626.clear(idi); } }; @@ -15281,160 +15441,160 @@ function _clearTimeout(cache) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; /** * convert a linear value into a logged value, folding negative numbers into * the given range */ -var _$toLogRange_564 = function toLogRange(val, range) { +var _$toLogRange_627 = function toLogRange(val, range) { if(val > 0) return Math.log(val) / Math.LN10; // move a negative value reference to a log axis - just put the // result at the lowest range value on the plot (or if the range also went negative, // one millionth of the top of the range) var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10; - if(!_$fastIsnumeric_139(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; + if(!_$fastIsnumeric_196(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; return newVal; }; -var _$lib_539 = {}; -/** +var _$lib_601 = {}; +/** * Copyright 2012-2018, Plotly, Inc. * All 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 source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. */ - + 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -/* removed: var _$numerical_517 = require('../constants/numerical'); */; -var FP_SAFE = _$numerical_517.FP_SAFE; -var __BADNUM_539 = _$numerical_517.BADNUM; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; + +/* removed: var _$numerical_578 = require('../constants/numerical'); */; +var FP_SAFE = _$numerical_578.FP_SAFE; +var __BADNUM_601 = _$numerical_578.BADNUM; -var lib = _$lib_539 = {}; +var lib = _$lib_601 = {}; -lib.nestedProperty = _$nestedProperty_547; -lib.keyedContainer = _$keyedContainer_542; -lib.relativeAttr = _$relative_attr_555; -lib.isPlainObject = _$isPlainObject_541; -lib.mod = _$mod_546; -lib.toLogRange = _$toLogRange_564; -lib.relinkPrivateKeys = _$relinkPrivateKeys_556; -lib.ensureArray = _$ensureArray_526; +lib.nestedProperty = _$nestedProperty_609; +lib.keyedContainer = _$keyedContainer_604; +lib.relativeAttr = _$relative_attr_618; +lib.isPlainObject = _$isPlainObject_603; +lib.mod = _$mod_608; +lib.toLogRange = _$toLogRange_627; +lib.relinkPrivateKeys = _$relinkPrivateKeys_619; +lib.ensureArray = _$ensureArray_588; -/* removed: var _$is_array_540 = require('./is_array'); */; -lib.isTypedArray = _$is_array_540.isTypedArray; -lib.isArrayOrTypedArray = _$is_array_540.isArrayOrTypedArray; +/* removed: var _$is_array_602 = require('./is_array'); */; +lib.isTypedArray = _$is_array_602.isTypedArray; +lib.isArrayOrTypedArray = _$is_array_602.isArrayOrTypedArray; -/* removed: var _$coerce_524 = require('./coerce'); */; -lib.valObjectMeta = _$coerce_524.valObjectMeta; -lib.coerce = _$coerce_524.coerce; -lib.coerce2 = _$coerce_524.coerce2; -lib.coerceFont = _$coerce_524.coerceFont; -lib.coerceHoverinfo = _$coerce_524.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = _$coerce_524.coerceSelectionMarkerOpacity; -lib.validate = _$coerce_524.validate; +/* removed: var _$coerce_586 = require('./coerce'); */; +lib.valObjectMeta = _$coerce_586.valObjectMeta; +lib.coerce = _$coerce_586.coerce; +lib.coerce2 = _$coerce_586.coerce2; +lib.coerceFont = _$coerce_586.coerceFont; +lib.coerceHoverinfo = _$coerce_586.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = _$coerce_586.coerceSelectionMarkerOpacity; +lib.validate = _$coerce_586.validate; -/* removed: var _$dates_525 = require('./dates'); */; -lib.dateTime2ms = _$dates_525.dateTime2ms; -lib.isDateTime = _$dates_525.isDateTime; -lib.ms2DateTime = _$dates_525.ms2DateTime; -lib.ms2DateTimeLocal = _$dates_525.ms2DateTimeLocal; -lib.cleanDate = _$dates_525.cleanDate; -lib.isJSDate = _$dates_525.isJSDate; -lib.formatDate = _$dates_525.formatDate; -lib.incrementMonth = _$dates_525.incrementMonth; -lib.dateTick0 = _$dates_525.dateTick0; -lib.dfltRange = _$dates_525.dfltRange; -lib.findExactDates = _$dates_525.findExactDates; -lib.MIN_MS = _$dates_525.MIN_MS; -lib.MAX_MS = _$dates_525.MAX_MS; +/* removed: var _$dates_587 = require('./dates'); */; +lib.dateTime2ms = _$dates_587.dateTime2ms; +lib.isDateTime = _$dates_587.isDateTime; +lib.ms2DateTime = _$dates_587.ms2DateTime; +lib.ms2DateTimeLocal = _$dates_587.ms2DateTimeLocal; +lib.cleanDate = _$dates_587.cleanDate; +lib.isJSDate = _$dates_587.isJSDate; +lib.formatDate = _$dates_587.formatDate; +lib.incrementMonth = _$dates_587.incrementMonth; +lib.dateTick0 = _$dates_587.dateTick0; +lib.dfltRange = _$dates_587.dfltRange; +lib.findExactDates = _$dates_587.findExactDates; +lib.MIN_MS = _$dates_587.MIN_MS; +lib.MAX_MS = _$dates_587.MAX_MS; -/* removed: var _$search_557 = require('./search'); */; -lib.findBin = _$search_557.findBin; -lib.sorterAsc = _$search_557.sorterAsc; -lib.sorterDes = _$search_557.sorterDes; -lib.distinctVals = _$search_557.distinctVals; -lib.roundUp = _$search_557.roundUp; +/* removed: var _$search_620 = require('./search'); */; +lib.findBin = _$search_620.findBin; +lib.sorterAsc = _$search_620.sorterAsc; +lib.sorterDes = _$search_620.sorterDes; +lib.distinctVals = _$search_620.distinctVals; +lib.roundUp = _$search_620.roundUp; -/* removed: var _$stats_560 = require('./stats'); */; -lib.aggNums = _$stats_560.aggNums; -lib.len = _$stats_560.len; -lib.mean = _$stats_560.mean; -lib.variance = _$stats_560.variance; -lib.stdev = _$stats_560.stdev; -lib.interp = _$stats_560.interp; +/* removed: var _$stats_623 = require('./stats'); */; +lib.aggNums = _$stats_623.aggNums; +lib.len = _$stats_623.len; +lib.mean = _$stats_623.mean; +lib.variance = _$stats_623.variance; +lib.stdev = _$stats_623.stdev; +lib.interp = _$stats_623.interp; -/* removed: var _$matrix_545 = require('./matrix'); */; -lib.init2dArray = _$matrix_545.init2dArray; -lib.transposeRagged = _$matrix_545.transposeRagged; -lib.dot = _$matrix_545.dot; -lib.translationMatrix = _$matrix_545.translationMatrix; -lib.rotationMatrix = _$matrix_545.rotationMatrix; -lib.rotationXYMatrix = _$matrix_545.rotationXYMatrix; -lib.apply2DTransform = _$matrix_545.apply2DTransform; -lib.apply2DTransform2 = _$matrix_545.apply2DTransform2; +/* removed: var _$matrix_607 = require('./matrix'); */; +lib.init2dArray = _$matrix_607.init2dArray; +lib.transposeRagged = _$matrix_607.transposeRagged; +lib.dot = _$matrix_607.dot; +lib.translationMatrix = _$matrix_607.translationMatrix; +lib.rotationMatrix = _$matrix_607.rotationMatrix; +lib.rotationXYMatrix = _$matrix_607.rotationXYMatrix; +lib.apply2DTransform = _$matrix_607.apply2DTransform; +lib.apply2DTransform2 = _$matrix_607.apply2DTransform2; -/* removed: var _$angles_522 = require('./angles'); */; -lib.deg2rad = _$angles_522.deg2rad; -lib.rad2deg = _$angles_522.rad2deg; -lib.wrap360 = _$angles_522.wrap360; -lib.wrap180 = _$angles_522.wrap180; +/* removed: var _$angles_583 = require('./angles'); */; +lib.deg2rad = _$angles_583.deg2rad; +lib.rad2deg = _$angles_583.rad2deg; +lib.wrap360 = _$angles_583.wrap360; +lib.wrap180 = _$angles_583.wrap180; -/* removed: var _$geometry2d_533 = require('./geometry2d'); */; -lib.segmentsIntersect = _$geometry2d_533.segmentsIntersect; -lib.segmentDistance = _$geometry2d_533.segmentDistance; -lib.getTextLocation = _$geometry2d_533.getTextLocation; -lib.clearLocationCache = _$geometry2d_533.clearLocationCache; -lib.getVisibleSegment = _$geometry2d_533.getVisibleSegment; -lib.findPointOnPath = _$geometry2d_533.findPointOnPath; +/* removed: var _$geometry2d_595 = require('./geometry2d'); */; +lib.segmentsIntersect = _$geometry2d_595.segmentsIntersect; +lib.segmentDistance = _$geometry2d_595.segmentDistance; +lib.getTextLocation = _$geometry2d_595.getTextLocation; +lib.clearLocationCache = _$geometry2d_595.clearLocationCache; +lib.getVisibleSegment = _$geometry2d_595.getVisibleSegment; +lib.findPointOnPath = _$geometry2d_595.findPointOnPath; -/* removed: var _$extend_528 = require('./extend'); */; -lib.extendFlat = _$extend_528.extendFlat; -lib.extendDeep = _$extend_528.extendDeep; -lib.extendDeepAll = _$extend_528.extendDeepAll; -lib.extendDeepNoArrays = _$extend_528.extendDeepNoArrays; +/* removed: var _$extend_590 = require('./extend'); */; +lib.extendFlat = _$extend_590.extendFlat; +lib.extendDeep = _$extend_590.extendDeep; +lib.extendDeepAll = _$extend_590.extendDeepAll; +lib.extendDeepNoArrays = _$extend_590.extendDeepNoArrays; -/* removed: var _$loggers_544 = require('./loggers'); */; -lib.log = _$loggers_544.log; -lib.warn = _$loggers_544.warn; -lib.error = _$loggers_544.error; - -/* removed: var _$regex_554 = require('./regex'); */; -lib.counterRegex = _$regex_554.counter; - -/* removed: var _$throttle_563 = require('./throttle'); */; -lib.throttle = _$throttle_563.throttle; -lib.throttleDone = _$throttle_563.done; -lib.clearThrottle = _$throttle_563.clear; - -lib.getGraphDiv = _$get_graph_div_534; - -lib._ = _$localize_543; - -lib.notifier = _$notifier_549; - -lib.filterUnique = _$filterUnique_529; -lib.filterVisible = _$filterVisible_530; -lib.pushUnique = _$pushUnique_552; - -lib.cleanNumber = _$cleanNumber_523; +/* removed: var _$loggers_606 = require('./loggers'); */; +lib.log = _$loggers_606.log; +lib.warn = _$loggers_606.warn; +lib.error = _$loggers_606.error; + +/* removed: var _$regex_617 = require('./regex'); */; +lib.counterRegex = _$regex_617.counter; + +/* removed: var _$throttle_626 = require('./throttle'); */; +lib.throttle = _$throttle_626.throttle; +lib.throttleDone = _$throttle_626.done; +lib.clearThrottle = _$throttle_626.clear; + +lib.getGraphDiv = _$get_graph_div_596; + +lib._ = _$localize_605; + +lib.notifier = _$notifier_611; + +lib.filterUnique = _$filterUnique_591; +lib.filterVisible = _$filterVisible_592; +lib.pushUnique = _$pushUnique_615; + +lib.cleanNumber = _$cleanNumber_584; lib.ensureNumber = function num(v) { - if(!_$fastIsnumeric_139(v)) return __BADNUM_539; + if(!_$fastIsnumeric_196(v)) return __BADNUM_601; v = Number(v); - if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_539; - return _$fastIsnumeric_139(v) ? Number(v) : __BADNUM_539; + if(v < -FP_SAFE || v > FP_SAFE) return __BADNUM_601; + return _$fastIsnumeric_196(v) ? Number(v) : __BADNUM_601; }; -lib.noop = _$noop_548; -lib.identity = _$identity_538; +lib.noop = _$noop_610; +lib.identity = _$identity_600; /** * swap x and y of the same attribute in container cont @@ -15794,7 +15954,7 @@ lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) { } function isPtIndexValid(v) { - return _$fastIsnumeric_139(v) && v >= 0 && v % 1 === 0; + return _$fastIsnumeric_196(v) && v >= 0 && v % 1 === 0; } function isCdIndexValid(v) { @@ -15886,7 +16046,7 @@ lib.containsAny = function(s, fragments) { }; lib.isPlotDiv = function(el) { - var el3 = _$d3_127.select(el); + var el3 = _$d3_130.select(el); return el3.node() instanceof HTMLElement && el3.size() && el3.classed('js-plotly-plot'); @@ -15933,6 +16093,63 @@ lib.isD3Selection = function(obj) { return obj && (typeof obj.classed === 'function'); }; +/** + * Append element to DOM only if not present. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} className : class name of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + * + * Previously, we were using the following pattern: + * + * ``` + * var sel = parent.selectAll('.' + className) + * .data([0]); + * + * sel.enter().append(nodeType) + * .classed(className, true); + * + * return sel; + * ``` + * + * in numerous places in our codebase to achieve the same behavior. + * + * The logic below performs much better, mostly as we are using + * `.select` instead `.selectAll` that is `querySelector` instead of + * `querySelectorAll`. + * + */ +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? '.' + className : '')); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).classed(className, true); + if(enterFn) layer.call(enterFn); + + return layer; +}; + +/** + * Same as Lib.ensureSingle, but using id as selector. + * This version is mostly used for clipPath nodes. + * + * @param {d3 selection} parent : parent selection of the element in question + * @param {string} nodeType : node type of element to append + * @param {string} id : id of element in question + * @param {fn} enterFn (optional) : optional fn applied to entering elements only + * @return {d3 selection} selection of new layer + */ +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + '#' + id); + if(sel.size()) return sel; + + var layer = parent.append(nodeType).attr('id', id); + if(enterFn) layer.call(enterFn); + + return layer; +}; /** * Converts a string path to an object. @@ -16126,7 +16343,7 @@ lib.numSeparate = function(value, separators, separatethousands) { }; var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g; -var __SIMPLE_PROPERTY_REGEX_539 = /^\w*$/; +var __SIMPLE_PROPERTY_REGEX_601 = /^\w*$/; /* * Substitute values from an object into a string @@ -16147,7 +16364,7 @@ lib.templateString = function(string, obj) { var getterCache = {}; return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) { - if(__SIMPLE_PROPERTY_REGEX_539.test(key)) { + if(__SIMPLE_PROPERTY_REGEX_601.test(key)) { return obj[key] || ''; } getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; @@ -16207,9 +16424,9 @@ lib.pseudoRandom = function() { 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -var __extendFlat_569 = _$lib_539.extendFlat; -var __isPlainObject_569 = _$lib_539.isPlainObject; +/* removed: var _$lib_601 = require('../lib'); */; +var __extendFlat_632 = _$lib_601.extendFlat; +var __isPlainObject_632 = _$lib_601.isPlainObject; var traceOpts = { valType: 'flaglist', @@ -16222,7 +16439,7 @@ var layoutOpts = { valType: 'flaglist', extras: ['none'], flags: [ - 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'margins', + 'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins', 'layoutstyle', 'modebar', 'camera', 'arraydraw' ], @@ -16237,7 +16454,7 @@ var traceEditTypeFlags = traceOpts.flags.slice() var layoutEditTypeFlags = layoutOpts.flags.slice() .concat('layoutReplot'); -var _$edit_types_569 = { +var _$edit_types_632 = { traces: traceOpts, layout: layoutOpts, /* @@ -16290,10 +16507,10 @@ function falseObj(keys) { * @return {object} a new attributes object with `editType` modified as directed */ function overrideAll(attrs, editTypeOverride, overrideContainers) { - var out = __extendFlat_569({}, attrs); + var out = __extendFlat_632({}, attrs); for(var key in out) { var attr = out[key]; - if(__isPlainObject_569(attr)) { + if(__isPlainObject_632(attr)) { out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); } } @@ -16304,7 +16521,7 @@ function overrideAll(attrs, editTypeOverride, overrideContainers) { function overrideOne(attr, editTypeOverride, overrideContainers, key) { if(attr.valType) { - var out = __extendFlat_569({}, attr); + var out = __extendFlat_632({}, attr); out.editType = editTypeOverride; if(Array.isArray(attr.items)) { @@ -16332,7 +16549,7 @@ function overrideOne(attr, editTypeOverride, overrideContainers, key) { 'use strict'; -var _$animation_attributes_579 = { +var _$animation_attributes_642 = { mode: { valType: 'enumerated', dflt: 'afterall', @@ -16433,7 +16650,7 @@ var _$animation_attributes_579 = { 'use strict'; -var _$frame_attributes_612 = { +var _$frame_attributes_674 = { _isLinkedToArray: 'frames_entry', group: { @@ -16468,7 +16685,7 @@ var _$frame_attributes_612 = { } }; -var _$attributes_435 = {}; +var _$attributes_497 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -16480,7 +16697,7 @@ var _$attributes_435 = {}; 'use strict'; -_$attributes_435.dash = { +_$attributes_497.dash = { valType: 'string', // string type usually doesn't take values... this one should really be // a special type or at least a special coercion function, from the GUI @@ -16502,21 +16719,21 @@ _$attributes_435.dash = { */ 'use strict'; -var __counterRegex_589 = _$regex_554.counter; +var __counterRegex_652 = _$regex_617.counter; -var _$constants_589 = { +var _$constants_652 = { idRegex: { - x: __counterRegex_589('x'), - y: __counterRegex_589('y') + x: __counterRegex_652('x'), + y: __counterRegex_652('y') }, - attrRegex: __counterRegex_589('[xy]axis'), + attrRegex: __counterRegex_652('[xy]axis'), // axis match regular expression - xAxisMatch: __counterRegex_589('xaxis'), - yAxisMatch: __counterRegex_589('yaxis'), + xAxisMatch: __counterRegex_652('xaxis'), + yAxisMatch: __counterRegex_652('yaxis'), // pattern matching axis ids and names // note that this is more permissive than counterRegex, as @@ -16563,6 +16780,7 @@ var _$constants_589 = { 'carpetlayer', 'violinlayer', 'boxlayer', + 'ohlclayer', 'scatterlayer' ], @@ -16582,15 +16800,15 @@ var _$constants_589 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../font_attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -var dash = _$attributes_435.dash; -var __extendFlat_596 = _$extend_528.extendFlat; +/* removed: var _$font_attributes_673 = require('../font_attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +var dash = _$attributes_497.dash; +var __extendFlat_659 = _$extend_590.extendFlat; -/* removed: var _$constants_589 = require('./constants'); */; +/* removed: var _$constants_652 = require('./constants'); */; -var _$layout_attributes_596 = { +var _$layout_attributes_659 = { visible: { valType: 'boolean', @@ -16599,7 +16817,7 @@ var _$layout_attributes_596 = { }, color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'ticks', @@ -16610,7 +16828,7 @@ var _$layout_attributes_596 = { editType: 'ticks+margins', }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ editType: 'ticks+margins', }), @@ -16646,10 +16864,10 @@ var _$layout_attributes_596 = { valType: 'info_array', items: [ - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}}, - {valType: 'any', editType: 'plot+margins', impliedEdits: {'^autorange': false}} + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}, + {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}} ], - editType: 'plot+margins', + editType: 'axrange+margins', impliedEdits: {'autorange': false}, }, @@ -16665,8 +16883,8 @@ var _$layout_attributes_596 = { scaleanchor: { valType: 'enumerated', values: [ - _$constants_589.idRegex.x.toString(), - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.x.toString(), + _$constants_652.idRegex.y.toString() ], editType: 'plot', @@ -16770,7 +16988,7 @@ var _$layout_attributes_596 = { }, tickcolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'ticks', @@ -16810,7 +17028,7 @@ var _$layout_attributes_596 = { editType: 'none', }, - spikedash: __extendFlat_596({}, dash, {dflt: 'dash', editType: 'none'}), + spikedash: __extendFlat_659({}, dash, {dflt: 'dash', editType: 'none'}), spikemode: { valType: 'flaglist', flags: ['toaxis', 'across', 'marker'], @@ -16827,7 +17045,7 @@ var _$layout_attributes_596 = { editType: 'none', }, - tickfont: _$font_attributes_611({ + tickfont: _$font_attributes_673({ editType: 'ticks+margins', }), @@ -16937,7 +17155,7 @@ var _$layout_attributes_596 = { }, linecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'layoutstyle', @@ -16958,7 +17176,7 @@ var _$layout_attributes_596 = { }, gridcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, editType: 'ticks', @@ -16979,7 +17197,7 @@ var _$layout_attributes_596 = { }, zerolinecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'ticks', @@ -16998,8 +17216,8 @@ var _$layout_attributes_596 = { valType: 'enumerated', values: [ 'free', - _$constants_589.idRegex.x.toString(), - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.x.toString(), + _$constants_652.idRegex.y.toString() ], editType: 'plot+margins', @@ -17021,8 +17239,8 @@ var _$layout_attributes_596 = { valType: 'enumerated', values: [ 'free', - _$constants_589.idRegex.x.toString(), - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.x.toString(), + _$constants_652.idRegex.y.toString() ], editType: 'plot', @@ -17095,13 +17313,13 @@ var _$layout_attributes_596 = { 'use strict'; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __extendFlat_412 = _$extend_528.extendFlat; -var __overrideAll_412 = _$edit_types_569.overrideAll; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __extendFlat_474 = _$extend_590.extendFlat; +var __overrideAll_474 = _$edit_types_632.overrideAll; -var _$attributes_412 = __overrideAll_412({ +var _$attributes_474 = __overrideAll_474({ // TODO: only right is supported currently // orient: { // valType: 'enumerated', @@ -17183,11 +17401,11 @@ var _$attributes_412 = __overrideAll_412({ }, // a possible line around the bar itself - outlinecolor: _$layout_attributes_596.linecolor, - outlinewidth: _$layout_attributes_596.linewidth, + outlinecolor: _$layout_attributes_659.linecolor, + outlinewidth: _$layout_attributes_659.linewidth, // Should outlinewidth have {dflt: 0} ? // another possible line outside the padding and tick labels - bordercolor: _$layout_attributes_596.linecolor, + bordercolor: _$layout_attributes_659.linecolor, borderwidth: { valType: 'number', @@ -17202,36 +17420,36 @@ var _$attributes_412 = __overrideAll_412({ }, // tick and title properties named and function exactly as in axes - tickmode: _$layout_attributes_596.tickmode, - nticks: _$layout_attributes_596.nticks, - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: __extendFlat_412({}, _$layout_attributes_596.ticks, {dflt: ''}), - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - tickfont: _$font_attributes_611({ + tickmode: _$layout_attributes_659.tickmode, + nticks: _$layout_attributes_659.nticks, + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: __extendFlat_474({}, _$layout_attributes_659.ticks, {dflt: ''}), + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + tickfont: _$font_attributes_673({ }), - tickangle: _$layout_attributes_596.tickangle, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - tickprefix: _$layout_attributes_596.tickprefix, - showtickprefix: _$layout_attributes_596.showtickprefix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showticksuffix: _$layout_attributes_596.showticksuffix, - separatethousands: _$layout_attributes_596.separatethousands, - exponentformat: _$layout_attributes_596.exponentformat, - showexponent: _$layout_attributes_596.showexponent, + tickangle: _$layout_attributes_659.tickangle, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + tickprefix: _$layout_attributes_659.tickprefix, + showtickprefix: _$layout_attributes_659.showtickprefix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showticksuffix: _$layout_attributes_659.showticksuffix, + separatethousands: _$layout_attributes_659.separatethousands, + exponentformat: _$layout_attributes_659.exponentformat, + showexponent: _$layout_attributes_659.showexponent, title: { valType: 'string', }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ }), titleside: { @@ -17253,7 +17471,7 @@ var _$attributes_412 = __overrideAll_412({ 'use strict'; -var _$attributes_417 = { +var _$attributes_479 = { zauto: { valType: 'boolean', @@ -17319,9 +17537,9 @@ var _$attributes_417 = { 'use strict'; -/* removed: var _$attributes_417 = require('./attributes'); */; -var __extendFlat_419 = _$extend_528.extendFlat; -/* removed: var _$scales_430 = require('./scales.js'); */; +/* removed: var _$attributes_479 = require('./attributes'); */; +var __extendFlat_481 = _$extend_590.extendFlat; +/* removed: var _$scales_492 = require('./scales.js'); */; /* * Make all the attributes for a regular colorscale: @@ -17337,7 +17555,7 @@ var __extendFlat_419 = _$extend_528.extendFlat; * * @return {object} the finished attributes object */ -var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) { +var _$makeColorScaleAttributes_481 = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) { var contextHead = context ? (context + '.') : ''; return { @@ -17348,34 +17566,34 @@ var _$makeColorScaleAttributes_419 = function makeColorScaleAttributes(context, editType: editTypeOverride || 'style', }, - colorscale: __extendFlat_419({}, _$attributes_417.colorscale, { + colorscale: __extendFlat_481({}, _$attributes_479.colorscale, { }), - cauto: __extendFlat_419({}, _$attributes_417.zauto, { + cauto: __extendFlat_481({}, _$attributes_479.zauto, { impliedEdits: {cmin: undefined, cmax: undefined}, }), - cmax: __extendFlat_419({}, _$attributes_417.zmax, { - editType: editTypeOverride || _$attributes_417.zmax.editType, + cmax: __extendFlat_481({}, _$attributes_479.zmax, { + editType: editTypeOverride || _$attributes_479.zmax.editType, impliedEdits: {cauto: false}, }), - cmin: __extendFlat_419({}, _$attributes_417.zmin, { - editType: editTypeOverride || _$attributes_417.zmin.editType, + cmin: __extendFlat_481({}, _$attributes_479.zmin, { + editType: editTypeOverride || _$attributes_479.zmin.editType, impliedEdits: {cauto: false}, }), - autocolorscale: __extendFlat_419({}, _$attributes_417.autocolorscale, { + autocolorscale: __extendFlat_481({}, _$attributes_479.autocolorscale, { - dflt: autoColorDflt === false ? autoColorDflt : _$attributes_417.autocolorscale.dflt + dflt: autoColorDflt === false ? autoColorDflt : _$attributes_479.autocolorscale.dflt }), - reversescale: __extendFlat_419({}, _$attributes_417.reversescale, { + reversescale: __extendFlat_481({}, _$attributes_479.reversescale, { }) }; }; -var _$color_411 = {}; +var _$color_473 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -17387,16 +17605,16 @@ var _$color_411 = {}; 'use strict'; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -var color = _$color_411 = {}; +var color = _$color_473 = {}; -/* removed: var _$attributes_410 = require('./attributes'); */; -color.defaults = _$attributes_410.defaults; -var defaultLine = color.defaultLine = _$attributes_410.defaultLine; -color.lightLine = _$attributes_410.lightLine; -var background = color.background = _$attributes_410.background; +/* removed: var _$attributes_472 = require('./attributes'); */; +color.defaults = _$attributes_472.defaults; +var defaultLine = color.defaultLine = _$attributes_472.defaultLine; +color.lightLine = _$attributes_472.lightLine; +var background = color.background = _$attributes_472.background; /* * tinyRGB: turn a tinycolor into an rgb string, but @@ -17408,12 +17626,12 @@ color.tinyRGB = function(tc) { Math.round(c.g) + ', ' + Math.round(c.b) + ')'; }; -color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_352(cstr)); }; +color.rgb = function(cstr) { return color.tinyRGB(_$tinycolor_414(cstr)); }; -color.opacity = function(cstr) { return cstr ? _$tinycolor_352(cstr).getAlpha() : 0; }; +color.opacity = function(cstr) { return cstr ? _$tinycolor_414(cstr).getAlpha() : 0; }; color.addOpacity = function(cstr, op) { - var c = _$tinycolor_352(cstr).toRgb(); + var c = _$tinycolor_414(cstr).toRgb(); return 'rgba(' + Math.round(c.r) + ', ' + Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')'; }; @@ -17422,10 +17640,10 @@ color.addOpacity = function(cstr, op) { // if back has transparency or is missing, // color.background is assumed behind it color.combine = function(front, back) { - var fc = _$tinycolor_352(front).toRgb(); - if(fc.a === 1) return _$tinycolor_352(front).toRgbString(); + var fc = _$tinycolor_414(front).toRgb(); + if(fc.a === 1) return _$tinycolor_414(front).toRgbString(); - var bc = _$tinycolor_352(back || background).toRgb(), + var bc = _$tinycolor_414(back || background).toRgb(), bcflat = bc.a === 1 ? bc : { r: 255 * (1 - bc.a) + bc.r * bc.a, g: 255 * (1 - bc.a) + bc.g * bc.a, @@ -17436,7 +17654,7 @@ color.combine = function(front, back) { g: bcflat.g * (1 - fc.a) + fc.g * fc.a, b: bcflat.b * (1 - fc.a) + fc.b * fc.a }; - return _$tinycolor_352(fcflat).toRgbString(); + return _$tinycolor_414(fcflat).toRgbString(); }; /* @@ -17448,9 +17666,9 @@ color.combine = function(front, back) { * otherwise we go all the way to white or black. */ color.contrast = function(cstr, lightAmount, darkAmount) { - var tc = _$tinycolor_352(cstr); + var tc = _$tinycolor_414(cstr); - if(tc.getAlpha() !== 1) tc = _$tinycolor_352(color.combine(cstr, background)); + if(tc.getAlpha() !== 1) tc = _$tinycolor_414(color.combine(cstr, background)); var newColor = tc.isDark() ? (lightAmount ? tc.lighten(lightAmount) : background) : @@ -17460,12 +17678,12 @@ color.contrast = function(cstr, lightAmount, darkAmount) { }; color.stroke = function(s, c) { - var tc = _$tinycolor_352(c); + var tc = _$tinycolor_414(c); s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()}); }; color.fill = function(s, c) { - var tc = _$tinycolor_352(c); + var tc = _$tinycolor_414(c); s.style({ 'fill': color.tinyRGB(tc), 'fill-opacity': tc.getAlpha() @@ -17512,7 +17730,7 @@ color.clean = function(container) { }; function cleanOne(val) { - if(_$fastIsnumeric_139(val) || typeof val !== 'string') return val; + if(_$fastIsnumeric_196(val) || typeof val !== 'string') return val; var valTrim = val.trim(); if(valTrim.substr(0, 3) !== 'rgb') return val; @@ -17557,7 +17775,7 @@ function cleanOne(val) { 'use strict'; -var _$flipScale_423 = function flipScale(scl) { +var _$flipScale_485 = function flipScale(scl) { var N = scl.length, sclNew = new Array(N), si; @@ -17581,18 +17799,18 @@ var _$flipScale_423 = function flipScale(scl) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$scales_430 = require('./scales'); */; -/* removed: var _$flipScale_423 = require('./flip_scale'); */; +/* removed: var _$scales_492 = require('./scales'); */; +/* removed: var _$flipScale_485 = require('./flip_scale'); */; -var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { +var _$calc_480 = function calc(trace, vals, containerStr, cLetter) { var container, inputContainer; if(containerStr) { - container = _$lib_539.nestedProperty(trace, containerStr).get(); - inputContainer = _$lib_539.nestedProperty(trace._input, containerStr).get(); + container = _$lib_601.nestedProperty(trace, containerStr).get(); + inputContainer = _$lib_601.nestedProperty(trace._input, containerStr).get(); } else { container = trace; @@ -17608,11 +17826,11 @@ var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { scl = container.colorscale; if(auto !== false || min === undefined) { - min = _$lib_539.aggNums(Math.min, null, vals); + min = _$lib_601.aggNums(Math.min, null, vals); } if(auto !== false || max === undefined) { - max = _$lib_539.aggNums(Math.max, null, vals); + max = _$lib_601.aggNums(Math.max, null, vals); } if(min === max) { @@ -17637,13 +17855,13 @@ var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { (min === undefined && max === undefined)); if(container.autocolorscale) { - if(min * max < 0) scl = _$scales_430.RdBu; - else if(min >= 0) scl = _$scales_430.Reds; - else scl = _$scales_430.Blues; + if(min * max < 0) scl = _$scales_492.RdBu; + else if(min >= 0) scl = _$scales_492.Reds; + else scl = _$scales_492.Blues; // reversescale is handled at the containerOut level inputContainer.colorscale = scl; - if(container.reversescale) scl = _$flipScale_423(scl); + if(container.reversescale) scl = _$flipScale_485(scl); container.colorscale = scl; } }; @@ -17659,10 +17877,10 @@ var _$calc_418 = function calc(trace, vals, containerStr, cLetter) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; -var _$handleTickLabelDefaults_604 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { +var _$handleTickLabelDefaults_666 = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) { var showAttrDflt = getShowAttrDflt(containerIn); var tickPrefix = coerce('tickprefix'); @@ -17678,7 +17896,7 @@ var _$handleTickLabelDefaults_604 = function handleTickLabelDefaults(containerIn // explicitly provided var dfltFontColor = (containerOut.color === containerIn.color) ? containerOut.color : font.color; - _$lib_539.coerceFont(coerce, 'tickfont', { + _$lib_601.coerceFont(coerce, 'tickfont', { family: font.family, size: font.size, color: dfltFontColor @@ -17736,7 +17954,7 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_539.coerce(valueIn, valueOut, _$layout_attributes_596.tickformatstops, attr, dflt); + return _$lib_601.coerce(valueIn, valueOut, _$layout_attributes_659.tickformatstops, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -17761,18 +17979,18 @@ function tickformatstopsDefaults(tickformatIn, tickformatOut) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; /** * options: inherits outerTicks from axes.handleAxisDefaults */ -var _$handleTickDefaults_605 = function handleTickDefaults(containerIn, containerOut, coerce, options) { - var tickLen = _$lib_539.coerce2(containerIn, containerOut, _$layout_attributes_596, 'ticklen'), - tickWidth = _$lib_539.coerce2(containerIn, containerOut, _$layout_attributes_596, 'tickwidth'), - tickColor = _$lib_539.coerce2(containerIn, containerOut, _$layout_attributes_596, 'tickcolor', containerOut.color), +var _$handleTickDefaults_667 = function handleTickDefaults(containerIn, containerOut, coerce, options) { + var tickLen = _$lib_601.coerce2(containerIn, containerOut, _$layout_attributes_659, 'ticklen'), + tickWidth = _$lib_601.coerce2(containerIn, containerOut, _$layout_attributes_659, 'tickwidth'), + tickColor = _$lib_601.coerce2(containerIn, containerOut, _$layout_attributes_659, 'tickcolor', containerOut.color), showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : ''); if(!showTicks) { @@ -17793,12 +18011,12 @@ var _$handleTickDefaults_605 = function handleTickDefaults(containerIn, containe 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __ONEDAY_606 = _$numerical_517.ONEDAY; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __ONEDAY_668 = _$numerical_578.ONEDAY; -var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { +var _$handleTickValueDefaults_668 = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) { var tickmodeDefault = 'auto'; if(containerIn.tickmode === 'array' && @@ -17817,9 +18035,9 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn // dtick is usually a positive number, but there are some // special strings available for log or date axes // default is 1 day for dates, otherwise 1 - var dtickDflt = (axType === 'date') ? __ONEDAY_606 : 1; + var dtickDflt = (axType === 'date') ? __ONEDAY_668 : 1; var dtick = coerce('dtick', dtickDflt); - if(_$fastIsnumeric_139(dtick)) { + if(_$fastIsnumeric_196(dtick)) { containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt; } else if(typeof dtick !== 'string') { @@ -17830,7 +18048,7 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn var prefix = dtick.charAt(0), dtickNum = dtick.substr(1); - dtickNum = _$fastIsnumeric_139(dtickNum) ? Number(dtickNum) : 0; + dtickNum = _$fastIsnumeric_196(dtickNum) ? Number(dtickNum) : 0; if((dtickNum <= 0) || !( // "M" gives ticks every (integer) n months (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) || @@ -17845,13 +18063,13 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn // tick0 can have different valType for different axis types, so // validate that now. Also for dates, change milliseconds to date strings - var tick0Dflt = (axType === 'date') ? _$lib_539.dateTick0(containerOut.calendar) : 0; + var tick0Dflt = (axType === 'date') ? _$lib_601.dateTick0(containerOut.calendar) : 0; var tick0 = coerce('tick0', tick0Dflt); if(axType === 'date') { - containerOut.tick0 = _$lib_539.cleanDate(tick0, tick0Dflt); + containerOut.tick0 = _$lib_601.cleanDate(tick0, tick0Dflt); } // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely - else if(_$fastIsnumeric_139(tick0) && dtick !== 'D1' && dtick !== 'D2') { + else if(_$fastIsnumeric_196(tick0) && dtick !== 'D1' && dtick !== 'D2') { containerOut.tick0 = Number(tick0); } else { @@ -17876,20 +18094,20 @@ var _$handleTickValueDefaults_606 = function handleTickValueDefaults(containerIn 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_606 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('../../plots/cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../../plots/cartesian/tick_label_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('../../plots/cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../../plots/cartesian/tick_label_defaults'); */; -/* removed: var _$attributes_412 = require('./attributes'); */; +/* removed: var _$attributes_474 = require('./attributes'); */; -var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut, layout) { +var _$colorbarDefaults_476 = function colorbarDefaults(containerIn, containerOut, layout) { var colorbarOut = containerOut.colorbar = {}, colorbarIn = containerIn.colorbar || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(colorbarIn, colorbarOut, _$attributes_412, attr, dflt); + return _$lib_601.coerce(colorbarIn, colorbarOut, _$attributes_474, attr, dflt); } var thicknessmode = coerce('thicknessmode'); @@ -17910,7 +18128,7 @@ var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut coerce('y'); coerce('yanchor'); coerce('ypad'); - _$lib_539.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); + _$lib_601.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']); coerce('outlinecolor'); coerce('outlinewidth'); @@ -17918,14 +18136,14 @@ var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut coerce('borderwidth'); coerce('bgcolor'); - _$handleTickValueDefaults_606(colorbarIn, colorbarOut, coerce, 'linear'); + _$handleTickValueDefaults_668(colorbarIn, colorbarOut, coerce, 'linear'); var opts = {outerTicks: false, font: layout.font}; - _$handleTickLabelDefaults_604(colorbarIn, colorbarOut, coerce, 'linear', opts); - _$handleTickDefaults_605(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickLabelDefaults_666(colorbarIn, colorbarOut, coerce, 'linear', opts); + _$handleTickDefaults_667(colorbarIn, colorbarOut, coerce, 'linear', opts); coerce('title', layout._dfltTitle.colorbar); - _$lib_539.coerceFont(coerce, 'titlefont', layout.font); + _$lib_601.coerceFont(coerce, 'titlefont', layout.font); coerce('titleside'); }; @@ -17940,11 +18158,11 @@ var _$colorbarDefaults_414 = function colorbarDefaults(containerIn, containerOut 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$hasColorbar_416 = function hasColorbar(container) { - return _$lib_539.isPlainObject(container.colorbar); +var _$hasColorbar_478 = function hasColorbar(container) { + return _$lib_601.isPlainObject(container.colorbar); }; /** @@ -17958,13 +18176,13 @@ var _$hasColorbar_416 = function hasColorbar(container) { 'use strict'; -/* removed: var _$scales_430 = require('./scales'); */; -/* removed: var _$isValidScaleArray_428 = require('./is_valid_scale_array'); */; +/* removed: var _$scales_492 = require('./scales'); */; +/* removed: var _$isValidScaleArray_490 = require('./is_valid_scale_array'); */; -var _$isValidScale_427 = function isValidScale(scl) { - if(_$scales_430[scl] !== undefined) return true; - else return _$isValidScaleArray_428(scl); +var _$isValidScale_489 = function isValidScale(scl) { + if(_$scales_492[scl] !== undefined) return true; + else return _$isValidScaleArray_490(scl); }; /** @@ -17978,31 +18196,31 @@ var _$isValidScale_427 = function isValidScale(scl) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$hasColorbar_416 = require('../colorbar/has_colorbar'); */; -/* removed: var _$colorbarDefaults_414 = require('../colorbar/defaults'); */; -/* removed: var _$isValidScale_427 = require('./is_valid_scale'); */; -/* removed: var _$flipScale_423 = require('./flip_scale'); */; +/* removed: var _$hasColorbar_478 = require('../colorbar/has_colorbar'); */; +/* removed: var _$colorbarDefaults_476 = require('../colorbar/defaults'); */; +/* removed: var _$isValidScale_489 = require('./is_valid_scale'); */; +/* removed: var _$flipScale_485 = require('./flip_scale'); */; -var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { +var _$colorScaleDefaults_483 = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) { var prefix = opts.prefix, cLetter = opts.cLetter, containerStr = prefix.slice(0, prefix.length - 1), containerIn = prefix ? - _$lib_539.nestedProperty(traceIn, containerStr).get() || {} : + _$lib_601.nestedProperty(traceIn, containerStr).get() || {} : traceIn, containerOut = prefix ? - _$lib_539.nestedProperty(traceOut, containerStr).get() || {} : + _$lib_601.nestedProperty(traceOut, containerStr).get() || {} : traceOut, minIn = containerIn[cLetter + 'min'], maxIn = containerIn[cLetter + 'max'], sclIn = containerIn.colorscale; - var validMinMax = _$fastIsnumeric_139(minIn) && _$fastIsnumeric_139(maxIn) && (minIn < maxIn); + var validMinMax = _$fastIsnumeric_196(minIn) && _$fastIsnumeric_196(maxIn) && (minIn < maxIn); coerce(prefix + cLetter + 'auto', !validMinMax); coerce(prefix + cLetter + 'min'); coerce(prefix + cLetter + 'max'); @@ -18010,13 +18228,13 @@ var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, la // handles both the trace case (autocolorscale is false by default) and // the marker and marker.line case (autocolorscale is true by default) var autoColorscaleDftl; - if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_427(sclIn); + if(sclIn !== undefined) autoColorscaleDftl = !_$isValidScale_489(sclIn); coerce(prefix + 'autocolorscale', autoColorscaleDftl); var sclOut = coerce(prefix + 'colorscale'); // reversescale is handled at the containerOut level var reverseScale = coerce(prefix + 'reversescale'); - if(reverseScale) containerOut.colorscale = _$flipScale_423(sclOut); + if(reverseScale) containerOut.colorscale = _$flipScale_485(sclOut); // ... until Scatter.colorbar can handle marker line colorbars if(prefix === 'marker.line.') return; @@ -18024,10 +18242,10 @@ var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, la // handle both the trace case where the dflt is listed in attributes and // the marker case where the dflt is determined by hasColorbar var showScaleDftl; - if(prefix) showScaleDftl = _$hasColorbar_416(containerIn); + if(prefix) showScaleDftl = _$hasColorbar_478(containerIn); var showScale = coerce(prefix + 'showscale', showScaleDftl); - if(showScale) _$colorbarDefaults_414(containerIn, containerOut, layout); + if(showScale) _$colorbarDefaults_476(containerIn, containerOut, layout); }; /** @@ -18048,7 +18266,7 @@ var _$colorScaleDefaults_421 = function colorScaleDefaults(traceIn, traceOut, la * @param {number} cmin minimum color value (used to clamp scale) * @param {number} cmax maximum color value (used to clamp scale) */ -var _$extractScale_422 = function extractScale(scl, cmin, cmax) { +var _$extractScale_484 = function extractScale(scl, cmin, cmax) { var N = scl.length, domain = new Array(N), range = new Array(N); @@ -18076,20 +18294,20 @@ var _$extractScale_422 = function extractScale(scl, cmin, cmax) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$isValidScale_427 = require('./is_valid_scale'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$isValidScale_489 = require('./is_valid_scale'); */; -var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { +var _$hasColorscale_487 = function hasColorscale(trace, containerStr) { var container = containerStr ? - _$lib_539.nestedProperty(trace, containerStr).get() || {} : + _$lib_601.nestedProperty(trace, containerStr).get() || {} : trace; var color = container.color; var isArrayWithOneNumber = false; - if(_$lib_539.isArrayOrTypedArray(color)) { + if(_$lib_601.isArrayOrTypedArray(color)) { for(var i = 0; i < color.length; i++) { - if(_$fastIsnumeric_139(color[i])) { + if(_$fastIsnumeric_196(color[i])) { isArrayWithOneNumber = true; break; } @@ -18097,12 +18315,12 @@ var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { } return ( - _$lib_539.isPlainObject(container) && ( + _$lib_601.isPlainObject(container) && ( isArrayWithOneNumber || container.showscale === true || - (_$fastIsnumeric_139(container.cmin) && _$fastIsnumeric_139(container.cmax)) || - _$isValidScale_427(container.colorscale) || - _$lib_539.isPlainObject(container.colorbar) + (_$fastIsnumeric_196(container.cmin) && _$fastIsnumeric_196(container.cmax)) || + _$isValidScale_489(container.colorscale) || + _$lib_601.isPlainObject(container.colorbar) ) ); }; @@ -18118,11 +18336,11 @@ var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$color_473 = require('../color'); */; /** * General colorscale function generator. @@ -18137,7 +18355,7 @@ var _$hasColorscale_425 = function hasColorscale(trace, containerStr) { * * @return {function} */ -var _$makeColorScaleFunc_429 = function makeColorScaleFunc(specs, opts) { +var _$makeColorScaleFunc_491 = function makeColorScaleFunc(specs, opts) { opts = opts || {}; var domain = specs.domain, @@ -18146,11 +18364,11 @@ var _$makeColorScaleFunc_429 = function makeColorScaleFunc(specs, opts) { _range = new Array(N); for(var i = 0; i < N; i++) { - var rgba = _$tinycolor_352(range[i]).toRgb(); + var rgba = _$tinycolor_414(range[i]).toRgb(); _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a]; } - var _sclFunc = _$d3_127.scale.linear() + var _sclFunc = _$d3_130.scale.linear() .domain(domain) .range(_range) .clamp(true); @@ -18169,16 +18387,16 @@ var _$makeColorScaleFunc_429 = function makeColorScaleFunc(specs, opts) { } else if(returnArray) { sclFunc = function(v) { - if(_$fastIsnumeric_139(v)) return _sclFunc(v); - else if(_$tinycolor_352(v).isValid()) return v; - else return _$color_411.defaultLine; + if(_$fastIsnumeric_196(v)) return _sclFunc(v); + else if(_$tinycolor_414(v).isValid()) return v; + else return _$color_473.defaultLine; }; } else { sclFunc = function(v) { - if(_$fastIsnumeric_139(v)) return colorArray2rbga(_sclFunc(v)); - else if(_$tinycolor_352(v).isValid()) return v; - else return _$color_411.defaultLine; + if(_$fastIsnumeric_196(v)) return colorArray2rbga(_sclFunc(v)); + else if(_$tinycolor_414(v).isValid()) return v; + else return _$color_473.defaultLine; }; } @@ -18199,10 +18417,10 @@ function colorArray2rbga(colorArray) { a: colorArray[3] }; - return _$tinycolor_352(colorObj).toRgbString(); + return _$tinycolor_414(colorObj).toRgbString(); } -var _$colorscale_426 = {}; +var _$colorscale_488 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18214,27 +18432,27 @@ var _$colorscale_426 = {}; 'use strict'; -_$colorscale_426.scales = _$scales_430; +_$colorscale_488.scales = _$scales_492; -_$colorscale_426.defaultScale = _$default_scale_420; +_$colorscale_488.defaultScale = _$default_scale_482; -_$colorscale_426.attributes = _$attributes_417; +_$colorscale_488.attributes = _$attributes_479; -_$colorscale_426.handleDefaults = _$colorScaleDefaults_421; +_$colorscale_488.handleDefaults = _$colorScaleDefaults_483; -_$colorscale_426.calc = _$calc_418; +_$colorscale_488.calc = _$calc_480; -_$colorscale_426.hasColorscale = _$hasColorscale_425; +_$colorscale_488.hasColorscale = _$hasColorscale_487; -_$colorscale_426.isValidScale = _$isValidScale_427; +_$colorscale_488.isValidScale = _$isValidScale_489; -_$colorscale_426.getScale = _$getScale_424; +_$colorscale_488.getScale = _$getScale_486; -_$colorscale_426.flipScale = _$flipScale_423; +_$colorscale_488.flipScale = _$flipScale_485; -_$colorscale_426.extractScale = _$extractScale_422; +_$colorscale_488.extractScale = _$extractScale_484; -_$colorscale_426.makeColorScaleFunc = _$makeColorScaleFunc_429; +_$colorscale_488.makeColorScaleFunc = _$makeColorScaleFunc_491; /** * Copyright 2012-2018, Plotly, Inc. @@ -18247,7 +18465,7 @@ _$colorscale_426.makeColorScaleFunc = _$makeColorScaleFunc_429; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; /** Marker symbol definitions * users can specify markers either by number or name @@ -18257,11 +18475,11 @@ _$colorscale_426.makeColorScaleFunc = _$makeColorScaleFunc_429; * add both and you get both */ -var _$symbol_defs_437 = { +var _$symbol_defs_499 = { circle: { n: 0, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; } @@ -18269,22 +18487,22 @@ var _$symbol_defs_437 = { square: { n: 1, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; } }, diamond: { n: 2, f: function(r) { - var rd = _$d3_127.round(r * 1.3, 2); + var rd = _$d3_130.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z'; } }, cross: { n: 3, f: function(r) { - var rc = _$d3_127.round(r * 0.4, 2), - rc2 = _$d3_127.round(r * 1.2, 2); + var rc = _$d3_130.round(r * 0.4, 2), + rc2 = _$d3_130.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'; @@ -18293,7 +18511,7 @@ var _$symbol_defs_437 = { x: { n: 4, f: function(r) { - var rx = _$d3_127.round(r * 0.8 / Math.sqrt(2), 2), + var rx = _$d3_130.round(r * 0.8 / Math.sqrt(2), 2), ne = 'l' + rx + ',' + rx, se = 'l' + rx + ',-' + rx, sw = 'l-' + rx + ',-' + rx, @@ -18304,79 +18522,79 @@ var _$symbol_defs_437 = { 'triangle-up': { n: 5, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z'; } }, 'triangle-down': { n: 6, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z'; } }, 'triangle-left': { n: 7, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z'; } }, 'triangle-right': { n: 8, f: function(r) { - var rt = _$d3_127.round(r * 2 / Math.sqrt(3), 2), - r2 = _$d3_127.round(r / 2, 2), - rs = _$d3_127.round(r, 2); + var rt = _$d3_130.round(r * 2 / Math.sqrt(3), 2), + r2 = _$d3_130.round(r / 2, 2), + rs = _$d3_130.round(r, 2); return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z'; } }, 'triangle-ne': { n: 9, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z'; } }, 'triangle-se': { n: 10, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z'; } }, 'triangle-sw': { n: 11, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z'; } }, 'triangle-nw': { n: 12, f: function(r) { - var r1 = _$d3_127.round(r * 0.6, 2), - r2 = _$d3_127.round(r * 1.2, 2); + var r1 = _$d3_130.round(r * 0.6, 2), + r2 = _$d3_130.round(r * 1.2, 2); return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z'; } }, pentagon: { n: 13, f: function(r) { - var x1 = _$d3_127.round(r * 0.951, 2), - x2 = _$d3_127.round(r * 0.588, 2), - y0 = _$d3_127.round(-r, 2), - y1 = _$d3_127.round(r * -0.309, 2), - y2 = _$d3_127.round(r * 0.809, 2); + var x1 = _$d3_130.round(r * 0.951, 2), + x2 = _$d3_130.round(r * 0.588, 2), + y0 = _$d3_130.round(-r, 2), + y1 = _$d3_130.round(r * -0.309, 2), + y2 = _$d3_130.round(r * 0.809, 2); return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 + 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z'; } @@ -18384,9 +18602,9 @@ var _$symbol_defs_437 = { hexagon: { n: 14, f: function(r) { - var y0 = _$d3_127.round(r, 2), - y1 = _$d3_127.round(r / 2, 2), - x = _$d3_127.round(r * Math.sqrt(3) / 2, 2); + var y0 = _$d3_130.round(r, 2), + y1 = _$d3_130.round(r / 2, 2), + x = _$d3_130.round(r * Math.sqrt(3) / 2, 2); return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 + 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z'; } @@ -18394,9 +18612,9 @@ var _$symbol_defs_437 = { hexagon2: { n: 15, f: function(r) { - var x0 = _$d3_127.round(r, 2), - x1 = _$d3_127.round(r / 2, 2), - y = _$d3_127.round(r * Math.sqrt(3) / 2, 2); + var x0 = _$d3_130.round(r, 2), + x1 = _$d3_130.round(r / 2, 2), + y = _$d3_130.round(r * Math.sqrt(3) / 2, 2); return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 + ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z'; } @@ -18404,8 +18622,8 @@ var _$symbol_defs_437 = { octagon: { n: 16, f: function(r) { - var a = _$d3_127.round(r * 0.924, 2), - b = _$d3_127.round(r * 0.383, 2); + var a = _$d3_130.round(r * 0.924, 2), + b = _$d3_130.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'; } @@ -18414,15 +18632,15 @@ var _$symbol_defs_437 = { n: 17, f: function(r) { var rs = r * 1.4, - x1 = _$d3_127.round(rs * 0.225, 2), - x2 = _$d3_127.round(rs * 0.951, 2), - x3 = _$d3_127.round(rs * 0.363, 2), - x4 = _$d3_127.round(rs * 0.588, 2), - y0 = _$d3_127.round(-rs, 2), - y1 = _$d3_127.round(rs * -0.309, 2), - y3 = _$d3_127.round(rs * 0.118, 2), - y4 = _$d3_127.round(rs * 0.809, 2), - y5 = _$d3_127.round(rs * 0.382, 2); + x1 = _$d3_130.round(rs * 0.225, 2), + x2 = _$d3_130.round(rs * 0.951, 2), + x3 = _$d3_130.round(rs * 0.363, 2), + x4 = _$d3_130.round(rs * 0.588, 2), + y0 = _$d3_130.round(-rs, 2), + y1 = _$d3_130.round(rs * -0.309, 2), + y3 = _$d3_130.round(rs * 0.118, 2), + y4 = _$d3_130.round(rs * 0.809, 2), + y5 = _$d3_130.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 + @@ -18432,9 +18650,9 @@ var _$symbol_defs_437 = { hexagram: { n: 18, f: function(r) { - var y = _$d3_127.round(r * 0.66, 2), - x1 = _$d3_127.round(r * 0.38, 2), - x2 = _$d3_127.round(r * 0.76, 2); + var y = _$d3_130.round(r * 0.66, 2), + x1 = _$d3_130.round(r * 0.38, 2), + x2 = _$d3_130.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 + @@ -18444,10 +18662,10 @@ var _$symbol_defs_437 = { 'star-triangle-up': { n: 19, f: function(r) { - var x = _$d3_127.round(r * Math.sqrt(3) * 0.8, 2), - y1 = _$d3_127.round(r * 0.8, 2), - y2 = _$d3_127.round(r * 1.6, 2), - rc = _$d3_127.round(r * 4, 2), + var x = _$d3_130.round(r * Math.sqrt(3) * 0.8, 2), + y1 = _$d3_130.round(r * 0.8, 2), + y2 = _$d3_130.round(r * 1.6, 2), + rc = _$d3_130.round(r * 4, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 + aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z'; @@ -18456,10 +18674,10 @@ var _$symbol_defs_437 = { 'star-triangle-down': { n: 20, f: function(r) { - var x = _$d3_127.round(r * Math.sqrt(3) * 0.8, 2), - y1 = _$d3_127.round(r * 0.8, 2), - y2 = _$d3_127.round(r * 1.6, 2), - rc = _$d3_127.round(r * 4, 2), + var x = _$d3_130.round(r * Math.sqrt(3) * 0.8, 2), + y1 = _$d3_130.round(r * 0.8, 2), + y2 = _$d3_130.round(r * 1.6, 2), + rc = _$d3_130.round(r * 4, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 + aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z'; @@ -18468,8 +18686,8 @@ var _$symbol_defs_437 = { 'star-square': { n: 21, f: function(r) { - var rp = _$d3_127.round(r * 1.1, 2), - rc = _$d3_127.round(r * 2, 2), + var rp = _$d3_130.round(r * 1.1, 2), + rc = _$d3_130.round(r * 2, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp + aPart + rp + ',' + rp + aPart + rp + ',-' + rp + @@ -18479,8 +18697,8 @@ var _$symbol_defs_437 = { 'star-diamond': { n: 22, f: function(r) { - var rp = _$d3_127.round(r * 1.4, 2), - rc = _$d3_127.round(r * 1.9, 2), + var rp = _$d3_130.round(r * 1.4, 2), + rc = _$d3_130.round(r * 1.9, 2), aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; return 'M-' + rp + ',0' + aPart + '0,' + rp + aPart + rp + ',0' + aPart + '0,-' + rp + @@ -18490,23 +18708,23 @@ var _$symbol_defs_437 = { 'diamond-tall': { n: 23, f: function(r) { - var x = _$d3_127.round(r * 0.7, 2), - y = _$d3_127.round(r * 1.4, 2); + var x = _$d3_130.round(r * 0.7, 2), + y = _$d3_130.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_127.round(r * 1.4, 2), - y = _$d3_127.round(r * 0.7, 2); + var x = _$d3_130.round(r * 1.4, 2), + y = _$d3_130.round(r * 0.7, 2); return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; } }, hourglass: { n: 25, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z'; }, noDot: true @@ -18514,7 +18732,7 @@ var _$symbol_defs_437 = { bowtie: { n: 26, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z'; }, noDot: true @@ -18522,7 +18740,7 @@ var _$symbol_defs_437 = { 'circle-cross': { n: 27, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.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'; @@ -18533,8 +18751,8 @@ var _$symbol_defs_437 = { 'circle-x': { n: 28, f: function(r) { - var rs = _$d3_127.round(r, 2), - rc = _$d3_127.round(r / Math.sqrt(2), 2); + var rs = _$d3_130.round(r, 2), + rc = _$d3_130.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 + @@ -18546,7 +18764,7 @@ var _$symbol_defs_437 = { 'square-cross': { n: 29, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.round(r, 2); return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; }, @@ -18556,7 +18774,7 @@ var _$symbol_defs_437 = { 'square-x': { n: 30, f: function(r) { - var rs = _$d3_127.round(r, 2); + var rs = _$d3_130.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'; @@ -18567,7 +18785,7 @@ var _$symbol_defs_437 = { 'diamond-cross': { n: 31, f: function(r) { - var rd = _$d3_127.round(r * 1.3, 2); + var rd = _$d3_130.round(r * 1.3, 2); return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + 'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd; }, @@ -18577,8 +18795,8 @@ var _$symbol_defs_437 = { 'diamond-x': { n: 32, f: function(r) { - var rd = _$d3_127.round(r * 1.3, 2), - r2 = _$d3_127.round(r * 0.65, 2); + var rd = _$d3_130.round(r * 1.3, 2), + r2 = _$d3_130.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; @@ -18589,7 +18807,7 @@ var _$symbol_defs_437 = { 'cross-thin': { n: 33, f: function(r) { - var rc = _$d3_127.round(r * 1.4, 2); + var rc = _$d3_130.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc; }, needLine: true, @@ -18599,7 +18817,7 @@ var _$symbol_defs_437 = { 'x-thin': { n: 34, f: function(r) { - var rx = _$d3_127.round(r, 2); + var rx = _$d3_130.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx + 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, @@ -18610,8 +18828,8 @@ var _$symbol_defs_437 = { asterisk: { n: 35, f: function(r) { - var rc = _$d3_127.round(r * 1.2, 2); - var rs = _$d3_127.round(r * 0.85, 2); + var rc = _$d3_130.round(r * 1.2, 2); + var rs = _$d3_130.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; @@ -18623,8 +18841,8 @@ var _$symbol_defs_437 = { hash: { n: 36, f: function(r) { - var r1 = _$d3_127.round(r / 2, 2), - r2 = _$d3_127.round(r, 2); + var r1 = _$d3_130.round(r / 2, 2), + r2 = _$d3_130.round(r, 2); return 'M' + r1 + ',' + r2 + 'V-' + r2 + 'm-' + r2 + ',0V' + r2 + 'M' + r2 + ',' + r1 + 'H-' + r2 + @@ -18636,9 +18854,9 @@ var _$symbol_defs_437 = { 'y-up': { n: 37, f: function(r) { - var x = _$d3_127.round(r * 1.2, 2), - y0 = _$d3_127.round(r * 1.6, 2), - y1 = _$d3_127.round(r * 0.8, 2); + var x = _$d3_130.round(r * 1.2, 2), + y0 = _$d3_130.round(r * 1.6, 2), + y1 = _$d3_130.round(r * 0.8, 2); return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0'; }, needLine: true, @@ -18648,9 +18866,9 @@ var _$symbol_defs_437 = { 'y-down': { n: 38, f: function(r) { - var x = _$d3_127.round(r * 1.2, 2), - y0 = _$d3_127.round(r * 1.6, 2), - y1 = _$d3_127.round(r * 0.8, 2); + var x = _$d3_130.round(r * 1.2, 2), + y0 = _$d3_130.round(r * 1.6, 2), + y1 = _$d3_130.round(r * 0.8, 2); return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0'; }, needLine: true, @@ -18660,9 +18878,9 @@ var _$symbol_defs_437 = { 'y-left': { n: 39, f: function(r) { - var y = _$d3_127.round(r * 1.2, 2), - x0 = _$d3_127.round(r * 1.6, 2), - x1 = _$d3_127.round(r * 0.8, 2); + var y = _$d3_130.round(r * 1.2, 2), + x0 = _$d3_130.round(r * 1.6, 2), + x1 = _$d3_130.round(r * 0.8, 2); return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0'; }, needLine: true, @@ -18672,9 +18890,9 @@ var _$symbol_defs_437 = { 'y-right': { n: 40, f: function(r) { - var y = _$d3_127.round(r * 1.2, 2), - x0 = _$d3_127.round(r * 1.6, 2), - x1 = _$d3_127.round(r * 0.8, 2); + var y = _$d3_130.round(r * 1.2, 2), + x0 = _$d3_130.round(r * 1.6, 2), + x1 = _$d3_130.round(r * 0.8, 2); return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0'; }, needLine: true, @@ -18684,7 +18902,7 @@ var _$symbol_defs_437 = { 'line-ew': { n: 41, f: function(r) { - var rc = _$d3_127.round(r * 1.4, 2); + var rc = _$d3_130.round(r * 1.4, 2); return 'M' + rc + ',0H-' + rc; }, needLine: true, @@ -18694,7 +18912,7 @@ var _$symbol_defs_437 = { 'line-ns': { n: 42, f: function(r) { - var rc = _$d3_127.round(r * 1.4, 2); + var rc = _$d3_130.round(r * 1.4, 2); return 'M0,' + rc + 'V-' + rc; }, needLine: true, @@ -18704,7 +18922,7 @@ var _$symbol_defs_437 = { 'line-ne': { n: 43, f: function(r) { - var rx = _$d3_127.round(r, 2); + var rx = _$d3_130.round(r, 2); return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; }, needLine: true, @@ -18714,7 +18932,7 @@ var _$symbol_defs_437 = { 'line-nw': { n: 44, f: function(r) { - var rx = _$d3_127.round(r, 2); + var rx = _$d3_130.round(r, 2); return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx; }, needLine: true, @@ -18734,7 +18952,7 @@ var _$symbol_defs_437 = { 'use strict'; // fraction of some size to get to a named position -var _$alignment_511 = { +var _$alignment_573 = { // from bottom left: this is the origin of our paper-reference // positioning system FROM_BL: { @@ -18782,7 +19000,7 @@ var _$alignment_511 = { } }; -var _$xmlns_namespaces_519 = {}; +var _$xmlns_namespaces_580 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18795,15 +19013,15 @@ var _$xmlns_namespaces_519 = {}; 'use strict'; -_$xmlns_namespaces_519.xmlns = 'http://www.w3.org/2000/xmlns/'; -_$xmlns_namespaces_519.svg = 'http://www.w3.org/2000/svg'; -_$xmlns_namespaces_519.xlink = 'http://www.w3.org/1999/xlink'; +_$xmlns_namespaces_580.xmlns = 'http://www.w3.org/2000/xmlns/'; +_$xmlns_namespaces_580.svg = 'http://www.w3.org/2000/svg'; +_$xmlns_namespaces_580.xlink = 'http://www.w3.org/1999/xlink'; // the 'old' d3 quirk got fix in v3.5.7 // https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed -_$xmlns_namespaces_519.svgAttrs = { - xmlns: _$xmlns_namespaces_519.svg, - 'xmlns:xlink': _$xmlns_namespaces_519.xlink +_$xmlns_namespaces_580.svgAttrs = { + xmlns: _$xmlns_namespaces_580.svg, + 'xmlns:xlink': _$xmlns_namespaces_580.xlink }; /** @@ -18820,7 +19038,7 @@ _$xmlns_namespaces_519.svgAttrs = { // N.B. HTML entities are listed without the leading '&' and trailing ';' // https://www.freeformatter.com/html-entities.html -var _$string_mappings_518 = { +var _$string_mappings_579 = { entityToUnicode: { 'mu': 'μ', '#956': 'μ', @@ -18848,7 +19066,7 @@ var _$string_mappings_518 = { } }; -var _$svg_text_utils_562 = {}; +var _$svg_text_utils_625 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -18862,12 +19080,12 @@ var _$svg_text_utils_562 = {}; /* global MathJax:false */ -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$xmlns_namespaces_519 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$string_mappings_518 = require('../constants/string_mappings'); */; -var LINE_SPACING = _$alignment_511.LINE_SPACING; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$xmlns_namespaces_580 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$string_mappings_579 = require('../constants/string_mappings'); */; +var LINE_SPACING = _$alignment_573.LINE_SPACING; // text converter @@ -18877,7 +19095,7 @@ function getSize(_selection, _dimension) { var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; -_$svg_text_utils_562.convertToTspans = function(_context, gd, _callback) { +_$svg_text_utils_625.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) @@ -18886,7 +19104,7 @@ _$svg_text_utils_562.convertToTspans = function(_context, gd, _callback) { (typeof MathJax !== 'undefined') && str.match(FIND_TEX); - var parent = _$d3_127.select(_context.node().parentNode); + var parent = _$d3_130.select(_context.node().parentNode); if(parent.empty()) return; var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text'; svgClass += '-math'; @@ -18920,7 +19138,7 @@ _$svg_text_utils_562.convertToTspans = function(_context, gd, _callback) { _context.style('pointer-events', 'all'); } - _$svg_text_utils_562.positionText(_context); + _$svg_text_utils_625.positionText(_context); if(_callback) _callback.call(_context); } @@ -19015,18 +19233,18 @@ function cleanEscapesForTex(s) { } function texToSVG(_texString, _config, _callback) { - var randomID = 'math-output-' + _$lib_539.randstr([], 64); - var tmpDiv = _$d3_127.select('body').append('div') + var randomID = 'math-output-' + _$lib_601.randstr([], 64); + var tmpDiv = _$d3_130.select('body').append('div') .attr({id: randomID}) .style({visibility: 'hidden', position: 'absolute'}) .style({'font-size': _config.fontSize + 'px'}) .text(cleanEscapesForTex(_texString)); MathJax.Hub.Queue(['Typeset', MathJax.Hub, tmpDiv.node()], function() { - var glyphDefs = _$d3_127.select('body').select('#MathJax_SVG_glyphs'); + var glyphDefs = _$d3_130.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - _$lib_539.log('There was an error in the tex syntax.', _texString); + _$lib_601.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -19074,10 +19292,10 @@ var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':']; var STRIP_TAGS = new RegExp(']*)?/?>', 'g'); -var ENTITY_TO_UNICODE = Object.keys(_$string_mappings_518.entityToUnicode).map(function(k) { +var ENTITY_TO_UNICODE = Object.keys(_$string_mappings_579.entityToUnicode).map(function(k) { return { regExp: new RegExp('&' + k + ';', 'g'), - sub: _$string_mappings_518.entityToUnicode[k] + sub: _$string_mappings_579.entityToUnicode[k] }; }); @@ -19121,7 +19339,7 @@ function getQuotedMatch(_str, re) { var COLORMATCH = /(^|;)\s*color:/; -_$svg_text_utils_562.plainText = function(_str) { +_$svg_text_utils_625.plainText = function(_str) { // strip out our pseudo-html so we have a readable // version to put into text fields return (_str || '').replace(STRIP_TAGS, ' '); @@ -19175,8 +19393,8 @@ function buildSVGText(containerNode, str) { function newLine() { currentLine++; - var lineNode = document.createElementNS(_$xmlns_namespaces_519.svg, 'tspan'); - _$d3_127.select(lineNode).attr({ + var lineNode = document.createElementNS(_$xmlns_namespaces_580.svg, 'tspan'); + _$d3_130.select(lineNode).attr({ class: 'line', dy: (currentLine * LINE_SPACING) + 'em' }); @@ -19222,15 +19440,15 @@ function buildSVGText(containerNode, str) { if(nodeSpec.style) nodeAttrs.style = nodeSpec.style; - var newNode = document.createElementNS(_$xmlns_namespaces_519.svg, nodeType); + var newNode = document.createElementNS(_$xmlns_namespaces_580.svg, nodeType); if(type === 'sup' || type === 'sub') { addTextNode(currentNode, ZERO_WIDTH_SPACE); currentNode.appendChild(newNode); - var resetter = document.createElementNS(_$xmlns_namespaces_519.svg, 'tspan'); + var resetter = document.createElementNS(_$xmlns_namespaces_580.svg, 'tspan'); addTextNode(resetter, ZERO_WIDTH_SPACE); - _$d3_127.select(resetter).attr('dy', RESET_DY[type]); + _$d3_130.select(resetter).attr('dy', RESET_DY[type]); nodeAttrs.dy = SHIFT_DY[type]; currentNode.appendChild(newNode); @@ -19240,7 +19458,7 @@ function buildSVGText(containerNode, str) { currentNode.appendChild(newNode); } - _$d3_127.select(newNode).attr(nodeAttrs); + _$d3_130.select(newNode).attr(nodeAttrs); currentNode = nodeSpec.node = newNode; nodeStack.push(nodeSpec); @@ -19254,14 +19472,14 @@ function buildSVGText(containerNode, str) { // 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_539.log('Ignoring unexpected end tag .', str); + _$lib_601.log('Ignoring unexpected end tag .', str); return; } var innerNode = nodeStack.pop(); if(type !== innerNode.type) { - _$lib_539.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + + _$lib_601.log('Start tag <' + innerNode.type + '> doesnt match end tag <' + type + '>. Pretending it did match.', str); } currentNode = nodeStack[nodeStack.length - 1].node; @@ -19320,7 +19538,10 @@ function buildSVGText(containerNode, str) { var dummyAnchor = document.createElement('a'); dummyAnchor.href = href; if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) { - nodeSpec.href = encodeURI(href); + // 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); } @@ -19335,13 +19556,13 @@ function buildSVGText(containerNode, str) { return hasLink; } -_$svg_text_utils_562.lineCount = function lineCount(s) { +_$svg_text_utils_625.lineCount = function lineCount(s) { return s.selectAll('tspan.line').size() || 1; }; -_$svg_text_utils_562.positionText = function positionText(s, x, y) { +_$svg_text_utils_625.positionText = function positionText(s, x, y) { return s.each(function() { - var text = _$d3_127.select(this); + var text = _$d3_130.select(this); function setOrGet(attr, val) { if(val === undefined) { @@ -19415,10 +19636,10 @@ function alignHTMLWith(_base, container, options) { * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element */ -_$svg_text_utils_562.makeEditable = function(context, options) { +_$svg_text_utils_625.makeEditable = function(context, options) { var gd = options.gd; var _delegate = options.delegate; - var dispatch = _$d3_127.dispatch('edit', 'input', 'cancel'); + var dispatch = _$d3_130.dispatch('edit', 'input', 'cancel'); var handlerElement = _delegate || context; context.style({'pointer-events': _delegate ? 'none' : 'all'}); @@ -19434,7 +19655,7 @@ _$svg_text_utils_562.makeEditable = function(context, options) { if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group'; else mathjaxClass = '[class*=-math-group]'; if(mathjaxClass) { - _$d3_127.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); + _$d3_130.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); } } @@ -19449,7 +19670,7 @@ _$svg_text_utils_562.makeEditable = function(context, options) { } function appendEditable() { - var plotDiv = _$d3_127.select(gd); + var plotDiv = _$d3_130.select(gd); var container = plotDiv.select('.svg-container'); var div = container.append('div'); var cStyle = context.node().style; @@ -19475,31 +19696,31 @@ _$svg_text_utils_562.makeEditable = function(context, options) { gd._editing = false; context.text(this.textContent) .style({opacity: 1}); - var svgClass = _$d3_127.select(this).attr('class'), + var svgClass = _$d3_130.select(this).attr('class'), mathjaxClass; if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group'; else mathjaxClass = '[class*=-math-group]'; if(mathjaxClass) { - _$d3_127.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); + _$d3_130.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0}); } var text = this.textContent; - _$d3_127.select(this).transition().duration(0).remove(); - _$d3_127.select(document).on('mouseup', null); + _$d3_130.select(this).transition().duration(0).remove(); + _$d3_130.select(document).on('mouseup', null); dispatch.edit.call(context, text); }) .on('focus', function() { var editDiv = this; gd._editing = true; - _$d3_127.select(document).on('mouseup', function() { - if(_$d3_127.event.target === editDiv) return false; + _$d3_130.select(document).on('mouseup', function() { + if(_$d3_130.event.target === editDiv) return false; if(document.activeElement === div.node()) div.node().blur(); }); }) .on('keyup', function() { - if(_$d3_127.event.which === 27) { + if(_$d3_130.event.which === 27) { gd._editing = false; context.style({opacity: 1}); - _$d3_127.select(this) + _$d3_130.select(this) .style({opacity: 0}) .on('blur', function() { return false; }) .transition().remove(); @@ -19507,11 +19728,11 @@ _$svg_text_utils_562.makeEditable = function(context, options) { } else { dispatch.input.call(context, this.textContent); - _$d3_127.select(this).call(alignHTMLWith(context, container, options)); + _$d3_130.select(this).call(alignHTMLWith(context, container, options)); } }) .on('keydown', function() { - if(_$d3_127.event.which === 13) this.blur(); + if(_$d3_130.event.which === 13) this.blur(); }) .call(selectElementContents); } @@ -19519,7 +19740,7 @@ _$svg_text_utils_562.makeEditable = function(context, options) { if(options.immediate) handleClick(); else handlerElement.on('click', handleClick); - return _$d3_127.rebind(context, dispatch, 'on'); + return _$d3_130.rebind(context, dispatch, 'on'); }; /** @@ -19533,12 +19754,12 @@ _$svg_text_utils_562.makeEditable = function(context, options) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' -var _$makeBubbleSizeFn_879 = function makeBubbleSizeFn(trace) { +var _$makeBubbleSizeFn_944 = function makeBubbleSizeFn(trace) { var marker = trace.marker, sizeRef = marker.sizeref || 1, sizeMin = marker.sizemin || 0; @@ -19557,7 +19778,7 @@ var _$makeBubbleSizeFn_879 = function makeBubbleSizeFn(trace) { var baseSize = baseFn(v / 2); // don't show non-numeric and negative sizes - return (_$fastIsnumeric_139(baseSize) && (baseSize > 0)) ? + return (_$fastIsnumeric_196(baseSize) && (baseSize > 0)) ? Math.max(baseSize, sizeMin) : 0; }; @@ -19574,17 +19795,20 @@ var _$makeBubbleSizeFn_879 = function makeBubbleSizeFn(trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$subtypes_884 = { +var _$subtypes_949 = { hasLines: function(trace) { return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1; }, hasMarkers: function(trace) { - return trace.visible && trace.mode && - trace.mode.indexOf('markers') !== -1; + return trace.visible && ( + (trace.mode && trace.mode.indexOf('markers') !== -1) || + // until splom implements 'mode' + trace.type === 'splom' + ); }, hasText: function(trace) { @@ -19593,12 +19817,12 @@ var _$subtypes_884 = { }, isBubble: function(trace) { - return _$lib_539.isPlainObject(trace.marker) && - _$lib_539.isArrayOrTypedArray(trace.marker.size); + return _$lib_601.isPlainObject(trace.marker) && + _$lib_601.isArrayOrTypedArray(trace.marker.size); } }; -var _$drawing_436 = {}; +var _$drawing_498 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -19610,25 +19834,25 @@ var _$drawing_436 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$colorscale_426 = require('../colorscale'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$colorscale_488 = require('../colorscale'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_436 = _$alignment_511.LINE_SPACING; -var __DESELECTDIM_436 = _$interactions_516.DESELECTDIM; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_498 = _$alignment_573.LINE_SPACING; +var __DESELECTDIM_498 = _$interactions_577.DESELECTDIM; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../../traces/scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../../traces/scatter/make_bubble_size_func'); */; -var drawing = _$drawing_436 = {}; +var drawing = _$drawing_498 = {}; // ----------------------------------------------------- // styling functions for plot elements @@ -19636,14 +19860,14 @@ var drawing = _$drawing_436 = {}; drawing.font = function(s, family, size, color) { // also allow the form font(s, {family, size, color}) - if(_$lib_539.isPlainObject(family)) { + if(_$lib_601.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_411.fill, color); + if(color) s.call(_$color_473.fill, color); }; /* @@ -19673,7 +19897,7 @@ drawing.translatePoint = function(d, sel, xa, ya) { var x = xa.c2p(d.x); var y = ya.c2p(d.y); - if(_$fastIsnumeric_139(x) && _$fastIsnumeric_139(y) && sel.node()) { + if(_$fastIsnumeric_196(x) && _$fastIsnumeric_196(y) && sel.node()) { // for multiline text this works better if(sel.node().nodeName === 'text') { sel.attr('x', x).attr('y', y); @@ -19689,7 +19913,7 @@ drawing.translatePoint = function(d, sel, xa, ya) { drawing.translatePoints = function(s, xa, ya) { s.each(function(d) { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); drawing.translatePoint(d, sel, xa, ya); }); }; @@ -19715,7 +19939,7 @@ drawing.hideOutsideRangePoints = function(traceGroups, subplot, selector) { var ycalendar = trace.ycalendar; traceGroups.selectAll(selector).each(function(d) { - drawing.hideOutsideRangePoint(d, _$d3_127.select(this), xa, ya, xcalendar, ycalendar); + drawing.hideOutsideRangePoint(d, _$d3_130.select(this), xa, ya, xcalendar, ycalendar); }); }); }; @@ -19724,7 +19948,7 @@ 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 || !_$fastIsnumeric_139(lineWidth)) return dflt || 0; + if(!lineWidth || !_$fastIsnumeric_196(lineWidth)) return dflt || 0; // but not for static plots - these don't get antialiased anyway. if(gd._context.staticPlot) return lineWidth; @@ -19739,7 +19963,7 @@ drawing.singleLineStyle = function(d, s, lw, lc, ld) { lw1 = lw || line.width||0, dash = ld || line.dash || ''; - _$color_411.stroke(s, lc || line.color); + _$color_473.stroke(s, lc || line.color); drawing.dashLine(s, dash, lw1); }; @@ -19750,8 +19974,8 @@ drawing.lineGroupStyle = function(s, lw, lc, ld) { lw1 = lw || line.width||0, dash = ld || line.dash || ''; - _$d3_127.select(this) - .call(_$color_411.stroke, lc || line.color) + _$d3_130.select(this) + .call(_$color_473.stroke, lc || line.color) .call(drawing.dashLine, dash, lw1); }); }; @@ -19788,29 +20012,29 @@ drawing.dashStyle = function(dash, lineWidth) { // Same as fillGroupStyle, except in this case the selection may be a transition drawing.singleFillStyle = function(sel) { - var node = _$d3_127.select(sel.node()); + var node = _$d3_130.select(sel.node()); var data = node.data(); var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor; if(fillcolor) { - sel.call(_$color_411.fill, fillcolor); + sel.call(_$color_473.fill, fillcolor); } }; drawing.fillGroupStyle = function(s) { s.style('stroke-width', 0) .each(function(d) { - var shape = _$d3_127.select(this); + var shape = _$d3_130.select(this); try { - shape.call(_$color_411.fill, d[0].trace.fillcolor); + shape.call(_$color_473.fill, d[0].trace.fillcolor); } catch(e) { - _$lib_539.error(e, s); + _$lib_601.error(e, s); shape.remove(); } }); }; -/* removed: var _$symbol_defs_437 = require('./symbol_defs'); */; +/* removed: var _$symbol_defs_499 = require('./symbol_defs'); */; drawing.symbolNames = []; drawing.symbolFuncs = []; @@ -19819,8 +20043,8 @@ drawing.symbolNoDot = {}; drawing.symbolNoFill = {}; drawing.symbolList = []; -Object.keys(_$symbol_defs_437).forEach(function(k) { - var symDef = _$symbol_defs_437[k]; +Object.keys(_$symbol_defs_499).forEach(function(k) { + var symDef = _$symbol_defs_499[k]; drawing.symbolList = drawing.symbolList.concat( [symDef.n, k, symDef.n + 100, k + '-open']); drawing.symbolNames[symDef.n] = k; @@ -19867,8 +20091,8 @@ function makePointPath(symbolNumber, r) { } function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerLine, gd) { - if(_$registry_668.traceIs(trace, 'symbols')) { - var sizeFn = _$makeBubbleSizeFn_879(trace); + if(_$registry_731.traceIs(trace, 'symbols')) { + var sizeFn = _$makeBubbleSizeFn_944(trace); sel.attr('d', function(d) { var r; @@ -19877,7 +20101,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.ms === 'various' || marker.size === 'various') { r = 3; } else { - r = _$subtypes_884.isBubble(trace) ? + r = _$subtypes_949.isBubble(trace) ? sizeFn(d.ms) : (marker.size || 6) / 2; } @@ -19917,11 +20141,11 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(_$lib_539.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_411.defaultLine; + else if(_$lib_601.isArrayOrTypedArray(markerLine.color)) lineColor = _$color_473.defaultLine; else lineColor = markerLine.color; - if(_$lib_539.isArrayOrTypedArray(marker.color)) { - fillColor = _$color_411.defaultLine; + if(_$lib_601.isArrayOrTypedArray(marker.color)) { + fillColor = _$color_473.defaultLine; perPointGradient = true; } @@ -19932,7 +20156,7 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL if(d.om) { // open markers can't have zero linewidth, default to 1px, // and use fill color as stroke color - sel.call(_$color_411.stroke, fillColor) + sel.call(_$color_473.stroke, fillColor) .style({ 'stroke-width': (lineWidth || 1) + 'px', fill: 'none' @@ -19958,11 +20182,11 @@ function singlePointStyle(d, sel, trace, markerScale, lineScale, marker, markerL sel.call(drawing.gradient, gd, gradientID, gradientType, fillColor, gradientColor); } else { - sel.call(_$color_411.fill, fillColor); + sel.call(_$color_473.fill, fillColor); } if(lineWidth) { - sel.call(_$color_411.stroke, lineColor); + sel.call(_$color_473.stroke, lineColor); } } } @@ -19973,31 +20197,31 @@ var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0}; drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { var gradient = gd._fullLayout._defs.select('.gradients') .selectAll('#' + gradientID) - .data([type + color1 + color2], _$lib_539.identity); + .data([type + color1 + color2], _$lib_601.identity); gradient.exit().remove(); gradient.enter() .append(type === 'radial' ? 'radialGradient' : 'linearGradient') .each(function() { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); if(type === 'horizontal') el.attr(HORZGRADIENT); else if(type === 'vertical') el.attr(VERTGRADIENT); el.attr('id', gradientID); - var tc1 = _$tinycolor_352(color1); - var tc2 = _$tinycolor_352(color2); + var tc1 = _$tinycolor_414(color1); + var tc2 = _$tinycolor_414(color2); el.append('stop').attr({ offset: '0%', - 'stop-color': _$color_411.tinyRGB(tc2), + 'stop-color': _$color_473.tinyRGB(tc2), 'stop-opacity': tc2.getAlpha() }); el.append('stop').attr({ offset: '100%', - 'stop-color': _$color_411.tinyRGB(tc1), + 'stop-color': _$color_473.tinyRGB(tc1), 'stop-opacity': tc1.getAlpha() }); }); @@ -20016,9 +20240,7 @@ drawing.gradient = function(sel, gd, gradientID, type, color1, color2) { * The upside of this is arbitrary points can share gradient defs */ drawing.initGradients = function(gd) { - var gradientsGroup = gd._fullLayout._defs.selectAll('.gradients').data([0]); - gradientsGroup.enter().append('g').classed('gradients', true); - + var gradientsGroup = _$lib_601.ensureSingle(gd._fullLayout._defs, 'g', 'gradients'); gradientsGroup.selectAll('linearGradient,radialGradient').remove(); }; @@ -20038,7 +20260,7 @@ drawing.pointStyle = function(s, trace, gd) { var lineScale = drawing.tryColorscale(marker, 'line'); s.each(function(d) { - drawing.singlePointStyle(d, _$d3_127.select(this), trace, markerScale, lineScale, gd); + drawing.singlePointStyle(d, _$d3_130.select(this), trace, markerScale, lineScale, gd); }); }; @@ -20067,7 +20289,7 @@ drawing.makeSelectedPointStyleFns = function(trace) { if(smoIsDefined) return smo; } else { if(usmoIsDefined) return usmo; - return __DESELECTDIM_436 * (dmoIsDefined ? dmo : mo); + return __DESELECTDIM_498 * (dmoIsDefined ? dmo : mo); } } }; @@ -20111,22 +20333,22 @@ drawing.selectedPointStyle = function(s, trace) { var marker = trace.marker || {}; s.each(function(d) { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var mo2 = fns.opacityFn(d); if(mo2 !== undefined) pt.style('opacity', mo2); }); if(fns.colorFn) { s.each(function(d) { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var mc2 = fns.colorFn(d); - if(mc2) _$color_411.fill(pt, mc2); + if(mc2) _$color_473.fill(pt, mc2); }); } - if(_$registry_668.traceIs(trace, 'symbols') && fns.sizeFn) { + if(_$registry_731.traceIs(trace, 'symbols') && fns.sizeFn) { s.each(function(d) { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var mx = d.mx || marker.symbol || 0; var mrc2 = fns.sizeFn(d); @@ -20139,22 +20361,22 @@ drawing.selectedPointStyle = function(s, trace) { }; drawing.tryColorscale = function(marker, prefix) { - var cont = prefix ? _$lib_539.nestedProperty(marker, prefix).get() : marker, + var cont = prefix ? _$lib_601.nestedProperty(marker, prefix).get() : marker, scl = cont.colorscale, colorArray = cont.color; - if(scl && _$lib_539.isArrayOrTypedArray(colorArray)) { - return _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale(scl, cont.cmin, cont.cmax) + if(scl && _$lib_601.isArrayOrTypedArray(colorArray)) { + return _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale(scl, cont.cmin, cont.cmax) ); } - else return _$lib_539.identity; + else return _$lib_601.identity; }; var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1}; function textPointPosition(s, textPosition, fontSize, markerRadius) { - var group = _$d3_127.select(s.node().parentNode); + var group = _$d3_130.select(s.node().parentNode); var v = textPosition.indexOf('top') !== -1 ? 'top' : @@ -20168,7 +20390,7 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { // ie 2/1.6 * nominal, bcs some markers are a bit bigger var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (_$svg_text_utils_562.lineCount(s) - 1) * __LINE_SPACING_436 + 1; + var numLines = (_$svg_text_utils_625.lineCount(s) - 1) * __LINE_SPACING_498 + 1; var dx = TEXTOFFSETSIGN[h] * r; var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r + (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2; @@ -20180,14 +20402,14 @@ function textPointPosition(s, textPosition, fontSize, markerRadius) { function extracTextFontSize(d, trace) { var fontSize = d.ts || trace.textfont.size; - return (_$fastIsnumeric_139(fontSize) && fontSize > 0) ? fontSize : 0; + return (_$fastIsnumeric_196(fontSize) && fontSize > 0) ? fontSize : 0; } // draw text at points drawing.textPointStyle = function(s, trace, gd) { s.each(function(d) { - var p = _$d3_127.select(this); - var text = _$lib_539.extractOption(d, trace, 'tx', 'text'); + var p = _$d3_130.select(this); + var text = _$lib_601.extractOption(d, trace, 'tx', 'text'); if(!text) { p.remove(); @@ -20202,7 +20424,7 @@ drawing.textPointStyle = function(s, trace, gd) { fontSize, d.tc || trace.textfont.color) .text(text) - .call(_$svg_text_utils_562.convertToTspans, gd) + .call(_$svg_text_utils_625.convertToTspans, gd) .call(textPointPosition, pos, fontSize, d.mrc); }); }; @@ -20214,7 +20436,7 @@ drawing.selectedTextStyle = function(s, trace) { var unselectedAttrs = trace.unselected || {}; s.each(function(d) { - var tx = _$d3_127.select(this); + var tx = _$d3_130.select(this); var tc = d.tc || trace.textfont.color; var tp = d.tp || trace.textposition; var fontSize = extracTextFontSize(d, trace); @@ -20226,10 +20448,10 @@ drawing.selectedTextStyle = function(s, trace) { if(stc) tc2 = stc; } else { if(utc) tc2 = utc; - else if(!stc) tc2 = _$color_411.addOpacity(tc, __DESELECTDIM_436); + else if(!stc) tc2 = _$color_473.addOpacity(tc, __DESELECTDIM_498); } - if(tc2) _$color_411.fill(tx, tc2); + if(tc2) _$color_473.fill(tx, tc2); textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc); }); }; @@ -20286,11 +20508,11 @@ function makeTangent(prevpt, thispt, nextpt, smoothness) { denom2 = 3 * d1a * (d1a + d2a); return [ [ - _$d3_127.round(thispt[0] + (denom1 && numx / denom1), 2), - _$d3_127.round(thispt[1] + (denom1 && numy / denom1), 2) + _$d3_130.round(thispt[0] + (denom1 && numx / denom1), 2), + _$d3_130.round(thispt[1] + (denom1 && numy / denom1), 2) ], [ - _$d3_127.round(thispt[0] - (denom2 && numx / denom2), 2), - _$d3_127.round(thispt[1] - (denom2 && numy / denom2), 2) + _$d3_130.round(thispt[0] - (denom2 && numx / denom2), 2), + _$d3_130.round(thispt[1] - (denom2 && numy / denom2), 2) ] ]; } @@ -20299,27 +20521,27 @@ function makeTangent(prevpt, thispt, nextpt, smoothness) { // with the given step shape var STEPPATH = { hv: function(p0, p1) { - return 'H' + _$d3_127.round(p1[0], 2) + 'V' + _$d3_127.round(p1[1], 2); + return 'H' + _$d3_130.round(p1[0], 2) + 'V' + _$d3_130.round(p1[1], 2); }, vh: function(p0, p1) { - return 'V' + _$d3_127.round(p1[1], 2) + 'H' + _$d3_127.round(p1[0], 2); + return 'V' + _$d3_130.round(p1[1], 2) + 'H' + _$d3_130.round(p1[0], 2); }, hvh: function(p0, p1) { - return 'H' + _$d3_127.round((p0[0] + p1[0]) / 2, 2) + 'V' + - _$d3_127.round(p1[1], 2) + 'H' + _$d3_127.round(p1[0], 2); + return 'H' + _$d3_130.round((p0[0] + p1[0]) / 2, 2) + 'V' + + _$d3_130.round(p1[1], 2) + 'H' + _$d3_130.round(p1[0], 2); }, vhv: function(p0, p1) { - return 'V' + _$d3_127.round((p0[1] + p1[1]) / 2, 2) + 'H' + - _$d3_127.round(p1[0], 2) + 'V' + _$d3_127.round(p1[1], 2); + return 'V' + _$d3_130.round((p0[1] + p1[1]) / 2, 2) + 'H' + + _$d3_130.round(p1[0], 2) + 'V' + _$d3_130.round(p1[1], 2); } }; var STEPLINEAR = function(p0, p1) { - return 'L' + _$d3_127.round(p1[0], 2) + ',' + _$d3_127.round(p1[1], 2); + return 'L' + _$d3_130.round(p1[0], 2) + ',' + _$d3_130.round(p1[1], 2); }; drawing.steps = function(shape) { var onestep = STEPPATH[shape] || STEPLINEAR; return function(pts) { - var path = 'M' + _$d3_127.round(pts[0][0], 2) + ',' + _$d3_127.round(pts[0][1], 2); + var path = 'M' + _$d3_130.round(pts[0][0], 2) + ',' + _$d3_130.round(pts[0][1], 2); for(var i = 1; i < pts.length; i++) { path += onestep(pts[i - 1], pts[i]); } @@ -20330,33 +20552,28 @@ drawing.steps = function(shape) { // 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 = _$d3_127.select('body') - .selectAll('#js-plotly-tester') - .data([0]); - - tester.enter().append('svg') - .attr('id', 'js-plotly-tester') - .attr(_$xmlns_namespaces_519.svgAttrs) - .style({ - position: 'absolute', - left: '-10000px', - top: '-10000px', - width: '9000px', - height: '9000px', - 'z-index': '1' - }); + var tester = _$lib_601.ensureSingleById(_$d3_130.select('body'), 'svg', 'js-plotly-tester', function(s) { + s.attr(_$xmlns_namespaces_580.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 = tester.selectAll('.js-reference-point').data([0]); - testref.enter().append('path') - .classed('js-reference-point', true) - .attr('d', 'M0,0H1V1H0Z') - .style({ - 'stroke-width': 0, - fill: 'black' - }); + var testref = _$lib_601.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; @@ -20401,7 +20618,7 @@ drawing.bBox = function(node, inTester, hash) { var out; if(hash) { out = drawing.savedBBoxes[hash]; - if(out) return _$lib_539.extendFlat({}, out); + if(out) return _$lib_601.extendFlat({}, out); } else if(node.childNodes.length === 1) { /* @@ -20445,7 +20662,7 @@ drawing.bBox = function(node, inTester, hash) { hash += '~' + x + '~' + y + '~' + transform; out = drawing.savedBBoxes[hash]; - if(out) return _$lib_539.extendFlat({}, out); + if(out) return _$lib_601.extendFlat({}, out); } } var testNode, tester; @@ -20461,9 +20678,9 @@ drawing.bBox = function(node, inTester, hash) { } // standardize its position (and newline tspans if any) - _$d3_127.select(testNode) + _$d3_130.select(testNode) .attr('transform', null) - .call(_$svg_text_utils_562.positionText, 0, 0); + .call(_$svg_text_utils_625.positionText, 0, 0); var testRect = testNode.getBoundingClientRect(); var refRect = drawing.testref @@ -20493,7 +20710,7 @@ drawing.bBox = function(node, inTester, hash) { if(hash) drawing.savedBBoxes[hash] = bb; savedBBoxesCount++; - return _$lib_539.extendFlat({}, bb); + return _$lib_601.extendFlat({}, bb); }; // capture everything about a node (at least in our usage) that @@ -20518,15 +20735,21 @@ drawing.setClipUrl = function(s, localId) { return; } - var url = '#' + localId, - base = _$d3_127.select('base'); + if(drawing.baseUrl === undefined) { + var base = _$d3_130.select('base'); - // add id to location href w/o hashes if any) - if(base.size() && base.attr('href')) { - url = window.location.href.split('#')[0] + url; + // Stash base url once and for all! + // We may have to stash this elsewhere when + // we'll try to support for child windows + // more info -> https://github.com/plotly/plotly.js/issues/702 + if(base.size() && base.attr('href')) { + drawing.baseUrl = window.location.href.split('#')[0]; + } else { + drawing.baseUrl = ''; + } } - s.attr('clip-path', 'url(' + url + ')'); + s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')'); }; drawing.getTranslate = function(element) { @@ -20636,7 +20859,7 @@ var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/; drawing.setTextPointsScale = function(selection, xScale, yScale) { selection.each(function() { var transforms; - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var text = el.select('text'); if(!text.node()) return; @@ -20675,7 +20898,7 @@ drawing.setTextPointsScale = function(selection, xScale, yScale) { 'use strict'; -var _$constants_868 = { +var _$constants_933 = { PTS_LINESONLY: 20, // fixed parameters of clustering and clipping algorithms @@ -20700,16 +20923,16 @@ var _$constants_868 = { 'use strict'; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __dash_862 = _$attributes_435.dash; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __dash_927 = _$attributes_497.dash; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$constants_868 = require('./constants'); */; -var __extendFlat_862 = _$extend_528.extendFlat; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$constants_933 = require('./constants'); */; +var __extendFlat_927 = _$extend_590.extendFlat; -var _$attributes_862 = { +var _$attributes_927 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -20811,7 +21034,7 @@ var _$attributes_862 = { editType: 'plot', }, - dash: __extendFlat_862({}, __dash_862, {editType: 'style'}), + dash: __extendFlat_927({}, __dash_927, {editType: 'style'}), simplify: { valType: 'boolean', dflt: true, @@ -20851,10 +21074,10 @@ var _$attributes_862 = { editType: 'style', }, - marker: __extendFlat_862({ + marker: __extendFlat_927({ symbol: { valType: 'enumerated', - values: _$drawing_436.symbolList, + values: _$drawing_498.symbolList, dflt: 'circle', arrayOk: true, @@ -20918,9 +21141,9 @@ var _$attributes_862 = { editType: 'calc', }, - colorbar: _$attributes_412, + colorbar: _$attributes_474, - line: __extendFlat_862({ + line: __extendFlat_927({ width: { valType: 'number', min: 0, @@ -20931,7 +21154,7 @@ var _$attributes_862 = { }, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ), gradient: { type: { @@ -20954,7 +21177,7 @@ var _$attributes_862 = { }, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker') + _$makeColorScaleAttributes_481('marker') ), selected: { marker: { @@ -21042,7 +21265,7 @@ var _$attributes_862 = { editType: 'calc', }, - textfont: _$font_attributes_611({ + textfont: _$font_attributes_673({ editType: 'calc', colorEditType: 'style', arrayOk: true, @@ -21071,12 +21294,12 @@ var _$attributes_862 = { 'use strict'; -/* removed: var _$attributes_862 = require('../../../traces/scatter/attributes'); */; -var scatterMarkerAttrs = _$attributes_862.marker; +/* removed: var _$attributes_927 = require('../../../traces/scatter/attributes'); */; +var scatterMarkerAttrs = _$attributes_927.marker; -var _$area_attributes_653 = { - r: _$attributes_862.r, - t: _$attributes_862.t, +var _$area_attributes_715 = { + r: _$attributes_927.r, + t: _$attributes_927.t, marker: { color: scatterMarkerAttrs.color, size: scatterMarkerAttrs.size, @@ -21097,11 +21320,11 @@ var _$area_attributes_653 = { 'use strict'; -/* removed: var _$layout_attributes_596 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_654 = _$extend_528.extendFlat; -var __overrideAll_654 = _$edit_types_569.overrideAll; +/* removed: var _$layout_attributes_659 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_716 = _$extend_590.extendFlat; +var __overrideAll_716 = _$edit_types_632.overrideAll; -var domainAttr = __extendFlat_654({}, _$layout_attributes_596.domain, { +var domainAttr = __extendFlat_716({}, _$layout_attributes_659.domain, { }); @@ -21150,10 +21373,10 @@ function mergeAttrs(axisName, nonCommonAttrs) { } }; - return __extendFlat_654({}, nonCommonAttrs, commonAttrs); + return __extendFlat_716({}, nonCommonAttrs, commonAttrs); } -var _$axis_attributes_654 = __overrideAll_654({ +var _$axis_attributes_716 = __overrideAll_716({ radialaxis: mergeAttrs('radial', { range: { valType: 'info_array', @@ -21201,7 +21424,7 @@ var _$axis_attributes_654 = __overrideAll_654({ } }, 'plot', 'nested'); -var _$plot_schema_575 = {}; +var _$plot_schema_638 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21213,22 +21436,23 @@ var _$plot_schema_575 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; -/* removed: var _$attributes_581 = require('../plots/attributes'); */; -/* removed: var _$layout_attributes_638 = require('../plots/layout_attributes'); */; -/* removed: var _$frame_attributes_612 = require('../plots/frame_attributes'); */; -/* removed: var _$animation_attributes_579 = require('../plots/animation_attributes'); */; +/* removed: var _$attributes_644 = require('../plots/attributes'); */; +/* removed: var _$layout_attributes_700 = require('../plots/layout_attributes'); */; +/* removed: var _$frame_attributes_674 = require('../plots/frame_attributes'); */; +/* removed: var _$animation_attributes_642 = require('../plots/animation_attributes'); */; // polar attributes are not part of the Registry yet -/* removed: var _$area_attributes_653 = require('../plots/polar/legacy/area_attributes'); */; -/* removed: var _$axis_attributes_654 = require('../plots/polar/legacy/axis_attributes'); */; +/* removed: var _$area_attributes_715 = require('../plots/polar/legacy/area_attributes'); */; +/* removed: var _$axis_attributes_716 = require('../plots/polar/legacy/axis_attributes'); */; -/* removed: var _$edit_types_569 = require('./edit_types'); */; +/* removed: var _$edit_types_632 = require('./edit_types'); */; -var __extendFlat_575 = _$lib_539.extendFlat; -var __extendDeepAll_575 = _$lib_539.extendDeepAll; +var __extendFlat_638 = _$lib_601.extendFlat; +var __extendDeepAll_638 = _$lib_601.extendDeepAll; +var __isPlainObject_638 = _$lib_601.isPlainObject; var IS_SUBPLOT_OBJ = '_isSubplotObj'; var IS_LINKED_TO_ARRAY = '_isLinkedToArray'; @@ -21236,10 +21460,10 @@ var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps'; var DEPRECATED = '_deprecated'; var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; -_$plot_schema_575.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; -_$plot_schema_575.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; -_$plot_schema_575.DEPRECATED = DEPRECATED; -_$plot_schema_575.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; +_$plot_schema_638.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; +_$plot_schema_638.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; +_$plot_schema_638.DEPRECATED = DEPRECATED; +_$plot_schema_638.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; /** Outputs the full plotly.js plot schema * @@ -21252,26 +21476,26 @@ _$plot_schema_575.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; * - animations * - config (coming soon ...) */ -_$plot_schema_575.get = function() { +_$plot_schema_638.get = function() { var traces = {}; - _$registry_668.allTypes.concat('area').forEach(function(type) { + _$registry_731.allTypes.concat('area').forEach(function(type) { traces[type] = getTraceAttributes(type); }); var transforms = {}; - Object.keys(_$registry_668.transformsRegistry).forEach(function(type) { + Object.keys(_$registry_731.transformsRegistry).forEach(function(type) { transforms[type] = getTransformAttributes(type); }); return { defs: { - valObjects: _$lib_539.valObjectMeta, + valObjects: _$lib_601.valObjectMeta, metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']), editType: { - traces: _$edit_types_569.traces, - layout: _$edit_types_569.layout + traces: _$edit_types_632.traces, + layout: _$edit_types_632.layout }, impliedEdits: { @@ -21284,7 +21508,7 @@ _$plot_schema_575.get = function() { transforms: transforms, frames: getFramesAttributes(), - animation: formatAttributes(_$animation_attributes_579) + animation: formatAttributes(_$animation_attributes_642) }; }; @@ -21315,7 +21539,7 @@ _$plot_schema_575.get = function() { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$plot_schema_575.crawl = function(attrs, callback, specifiedLevel, attrString) { +_$plot_schema_638.crawl = function(attrs, callback, specifiedLevel, attrString) { var level = specifiedLevel || 0; attrString = attrString || ''; @@ -21327,10 +21551,10 @@ _$plot_schema_575.crawl = function(attrs, callback, specifiedLevel, attrString) var fullAttrString = (attrString ? attrString + '.' : '') + attrName; callback(attr, attrName, attrs, level, fullAttrString); - if(_$plot_schema_575.isValObject(attr)) return; + if(_$plot_schema_638.isValObject(attr)) return; - if(_$lib_539.isPlainObject(attr) && attrName !== 'impliedEdits') { - _$plot_schema_575.crawl(attr, callback, level + 1, fullAttrString); + if(__isPlainObject_638(attr) && attrName !== 'impliedEdits') { + _$plot_schema_638.crawl(attr, callback, level + 1, fullAttrString); } }); }; @@ -21342,7 +21566,7 @@ _$plot_schema_575.crawl = function(attrs, callback, specifiedLevel, attrString) * returns true for a valid value object and * false for tree nodes in the attribute hierarchy */ -_$plot_schema_575.isValObject = function(obj) { +_$plot_schema_638.isValObject = function(obj) { return obj && obj.valType !== undefined; }; @@ -21356,7 +21580,7 @@ _$plot_schema_575.isValObject = function(obj) { * @return {array} arrayAttributes * list of array attributes for the given trace */ -_$plot_schema_575.findArrayAttributes = function(trace) { +_$plot_schema_638.findArrayAttributes = function(trace) { var arrayAttributes = []; var stack = []; @@ -21379,8 +21603,8 @@ _$plot_schema_575.findArrayAttributes = function(trace) { if(!splittableAttr) return; var astr = toAttrString(stack); - var val = _$lib_539.nestedProperty(trace, astr).get(); - if(!_$lib_539.isArrayOrTypedArray(val)) return; + var val = _$lib_601.nestedProperty(trace, astr).get(); + if(!_$lib_601.isArrayOrTypedArray(val)) return; arrayAttributes.push(astr); } @@ -21389,9 +21613,9 @@ _$plot_schema_575.findArrayAttributes = function(trace) { return stack.join('.'); } - _$plot_schema_575.crawl(_$attributes_581, callback); + _$plot_schema_638.crawl(_$attributes_644, callback); if(trace._module && trace._module.attributes) { - _$plot_schema_575.crawl(trace._module.attributes, callback); + _$plot_schema_638.crawl(trace._module.attributes, callback); } if(trace.transforms) { @@ -21404,7 +21628,7 @@ _$plot_schema_575.findArrayAttributes = function(trace) { if(module) { stack = ['transforms[' + i + ']']; - _$plot_schema_575.crawl(module.attributes, callback, 1); + _$plot_schema_638.crawl(module.attributes, callback, 1); } } } @@ -21416,8 +21640,8 @@ _$plot_schema_575.findArrayAttributes = function(trace) { // ohlc and candlestick 'open', 'high', 'low', 'close' can be // used with filter and groupby transforms. if(trace._fullInput && trace._fullInput._module && trace._fullInput._module.attributes) { - _$plot_schema_575.crawl(trace._fullInput._module.attributes, callback); - arrayAttributes = _$lib_539.filterUnique(arrayAttributes); + _$plot_schema_638.crawl(trace._fullInput._module.attributes, callback); + arrayAttributes = _$lib_601.filterUnique(arrayAttributes); } return arrayAttributes; @@ -21438,29 +21662,30 @@ _$plot_schema_575.findArrayAttributes = function(trace) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_575.getTraceValObject = function(trace, parts) { +_$plot_schema_638.getTraceValObject = function(trace, parts) { var head = parts[0]; var i = 1; // index to start recursing from var moduleAttrs, valObject; if(head === 'transforms') { - if(!Array.isArray(trace.transforms)) return false; + var transforms = trace.transforms; + if(!Array.isArray(transforms) || !transforms.length) return false; var tNum = parts[1]; - if(!isIndex(tNum) || tNum >= trace.transforms.length) { + if(!isIndex(tNum) || tNum >= transforms.length) { return false; } - moduleAttrs = (_$registry_668.transformsRegistry[trace.transforms[tNum].type] || {}).attributes; + moduleAttrs = (_$registry_731.transformsRegistry[transforms[tNum].type] || {}).attributes; valObject = moduleAttrs && moduleAttrs[parts[2]]; i = 3; // start recursing only inside the transform } else if(trace.type === 'area') { - valObject = _$area_attributes_653[head]; + valObject = _$area_attributes_715[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_668.modules[trace.type || _$attributes_581.type.dflt] || {})._module; + if(!_module) _module = (_$registry_731.modules[trace.type || _$attributes_644.type.dflt] || {})._module; if(!_module) return false; moduleAttrs = _module.attributes; @@ -21475,7 +21700,7 @@ _$plot_schema_575.getTraceValObject = function(trace, parts) { } // finally look in the global attributes - if(!valObject) valObject = _$attributes_581[head]; + if(!valObject) valObject = _$attributes_644[head]; } return recurseIntoValObject(valObject, parts, i); @@ -21494,7 +21719,7 @@ _$plot_schema_575.getTraceValObject = function(trace, parts) { * `valType: 'any'` attributes where we might set a part of the attribute. * In that case, stop at the deepest valObject we *do* find. */ -_$plot_schema_575.getLayoutValObject = function(fullLayout, parts) { +_$plot_schema_638.getLayoutValObject = function(fullLayout, parts) { var valObject = layoutHeadAttr(fullLayout, parts[0]); return recurseIntoValObject(valObject, parts, 1); @@ -21545,21 +21770,21 @@ function layoutHeadAttr(fullLayout, head) { * inside a container matching the module `name` * eg `attributes` (array) or `legend` (object) */ - for(key in _$registry_668.componentsRegistry) { - _module = _$registry_668.componentsRegistry[key]; + for(key in _$registry_731.componentsRegistry) { + _module = _$registry_731.componentsRegistry[key]; if(!_module.schema && (head === _module.name)) { return _module.layoutAttributes; } } - if(head in _$layout_attributes_638) return _$layout_attributes_638[head]; + if(head in _$layout_attributes_700) return _$layout_attributes_700[head]; // Polar doesn't populate _modules or _basePlotModules // just fall back on these when the others fail if(head === 'radialaxis' || head === 'angularaxis') { - return _$axis_attributes_654[head]; + return _$axis_attributes_716[head]; } - return _$axis_attributes_654.layout[head] || false; + return _$axis_attributes_716.layout[head] || false; } function recurseIntoValObject(valObject, parts, i) { @@ -21576,7 +21801,7 @@ function recurseIntoValObject(valObject, parts, i) { // the innermost schema item we find. for(; i < parts.length; i++) { var newValObject = valObject[parts[i]]; - if(_$lib_539.isPlainObject(newValObject)) valObject = newValObject; + if(__isPlainObject_638(newValObject)) valObject = newValObject; else break; if(i === parts.length - 1) break; @@ -21619,11 +21844,11 @@ function getTraceAttributes(type) { var _module, basePlotModule; if(type === 'area') { - _module = { attributes: _$area_attributes_653 }; + _module = { attributes: _$area_attributes_715 }; basePlotModule = {}; } else { - _module = _$registry_668.modules[type]._module, + _module = _$registry_731.modules[type]._module, basePlotModule = _module.basePlotModule; } @@ -21633,14 +21858,14 @@ function getTraceAttributes(type) { attributes.type = null; // base attributes (same for all trace types) - __extendDeepAll_575(attributes, _$attributes_581); + __extendDeepAll_638(attributes, _$attributes_644); // module attributes - __extendDeepAll_575(attributes, _module.attributes); + __extendDeepAll_638(attributes, _module.attributes); // subplot attributes if(basePlotModule.attributes) { - __extendDeepAll_575(attributes, basePlotModule.attributes); + __extendDeepAll_638(attributes, basePlotModule.attributes); } // 'type' gets overwritten by baseAttributes; reset it here @@ -21655,7 +21880,7 @@ function getTraceAttributes(type) { if(_module.layoutAttributes) { var layoutAttributes = {}; - __extendDeepAll_575(layoutAttributes, _module.layoutAttributes); + __extendDeepAll_638(layoutAttributes, _module.layoutAttributes); out.layoutAttributes = formatAttributes(layoutAttributes); } @@ -21667,21 +21892,20 @@ function getLayoutAttributes() { var key, _module; // global layout attributes - __extendDeepAll_575(layoutAttributes, _$layout_attributes_638); + __extendDeepAll_638(layoutAttributes, _$layout_attributes_700); // add base plot module layout attributes - for(key in _$registry_668.subplotsRegistry) { - _module = _$registry_668.subplotsRegistry[key]; + for(key in _$registry_731.subplotsRegistry) { + _module = _$registry_731.subplotsRegistry[key]; if(!_module.layoutAttributes) continue; - if(_module.name === 'cartesian') { - handleBasePlotModule(layoutAttributes, _module, 'xaxis'); - handleBasePlotModule(layoutAttributes, _module, 'yaxis'); - } - else { + 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); } } @@ -21690,8 +21914,8 @@ function getLayoutAttributes() { layoutAttributes = assignPolarLayoutAttrs(layoutAttributes); // add registered components layout attributes - for(key in _$registry_668.componentsRegistry) { - _module = _$registry_668.componentsRegistry[key]; + for(key in _$registry_731.componentsRegistry) { + _module = _$registry_731.componentsRegistry[key]; var schema = _module.schema; /* @@ -21722,12 +21946,12 @@ function getLayoutAttributes() { } function getTransformAttributes(type) { - var _module = _$registry_668.transformsRegistry[type]; - var attributes = __extendDeepAll_575({}, _module.attributes); + var _module = _$registry_731.transformsRegistry[type]; + var attributes = __extendDeepAll_638({}, _module.attributes); // add registered components transform attributes - Object.keys(_$registry_668.componentsRegistry).forEach(function(k) { - var _module = _$registry_668.componentsRegistry[k]; + Object.keys(_$registry_731.componentsRegistry).forEach(function(k) { + var _module = _$registry_731.componentsRegistry[k]; if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) { Object.keys(_module.schema.transforms[type]).forEach(function(v) { @@ -21743,7 +21967,7 @@ function getTransformAttributes(type) { function getFramesAttributes() { var attrs = { - frames: _$lib_539.extendDeepAll({}, _$frame_attributes_612) + frames: _$lib_601.extendDeepAll({}, _$frame_attributes_674) }; formatAttributes(attrs); @@ -21754,6 +21978,7 @@ function getFramesAttributes() { function formatAttributes(attrs) { mergeValTypeAndRole(attrs); formatArrayContainers(attrs); + stringify(attrs); return attrs; } @@ -21770,7 +21995,7 @@ function mergeValTypeAndRole(attrs) { } function callback(attr, attrName, attrs) { - if(_$plot_schema_575.isValObject(attr)) { + if(_$plot_schema_638.isValObject(attr)) { if(attr.valType === 'data_array') { // all 'data_array' attrs have role 'data' attr.role = 'data'; @@ -21782,13 +22007,13 @@ function mergeValTypeAndRole(attrs) { attrs[attrName + 'src'] = makeSrcAttr(attrName); } } - else if(_$lib_539.isPlainObject(attr)) { + else if(__isPlainObject_638(attr)) { // all attrs container objects get role 'object' attr.role = 'object'; } } - _$plot_schema_575.crawl(attrs, callback); + _$plot_schema_638.crawl(attrs, callback); } function formatArrayContainers(attrs) { @@ -21807,35 +22032,58 @@ function formatArrayContainers(attrs) { attrs[attrName].role = 'object'; } - _$plot_schema_575.crawl(attrs, callback); + _$plot_schema_638.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_638(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_575(layoutAttributes, { - radialaxis: _$axis_attributes_654.radialaxis, - angularaxis: _$axis_attributes_654.angularaxis + __extendFlat_638(layoutAttributes, { + radialaxis: _$axis_attributes_716.radialaxis, + angularaxis: _$axis_attributes_716.angularaxis }); - __extendFlat_575(layoutAttributes, _$axis_attributes_654.layout); + __extendFlat_638(layoutAttributes, _$axis_attributes_716.layout); return layoutAttributes; } function handleBasePlotModule(layoutAttributes, _module, astr) { - var np = _$lib_539.nestedProperty(layoutAttributes, astr), - attrs = __extendDeepAll_575({}, _module.layoutAttributes); + var np = _$lib_601.nestedProperty(layoutAttributes, astr), + attrs = __extendDeepAll_638({}, _module.layoutAttributes); attrs[IS_SUBPLOT_OBJ] = true; np.set(attrs); } function insertAttrs(baseAttrs, newAttrs, astr) { - var np = _$lib_539.nestedProperty(baseAttrs, astr); + var np = _$lib_601.nestedProperty(baseAttrs, astr); - np.set(__extendDeepAll_575(np.get() || {}, newAttrs)); + np.set(__extendDeepAll_638(np.get() || {}, newAttrs)); } -var _$axis_ids_587 = {}; +var _$axis_ids_650 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21846,30 +22094,30 @@ var _$axis_ids_587 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -/* removed: var _$constants_589 = require('./constants'); */; +/* removed: var _$constants_652 = require('./constants'); */; // 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. -_$axis_ids_587.id2name = function id2name(id) { - if(typeof id !== 'string' || !id.match(_$constants_589.AX_ID_PATTERN)) return; +_$axis_ids_650.id2name = function id2name(id) { + if(typeof id !== 'string' || !id.match(_$constants_652.AX_ID_PATTERN)) return; var axNum = id.substr(1); if(axNum === '1') axNum = ''; return id.charAt(0) + 'axis' + axNum; }; -_$axis_ids_587.name2id = function name2id(name) { - if(!name.match(_$constants_589.AX_NAME_PATTERN)) return; +_$axis_ids_650.name2id = function name2id(name) { + if(!name.match(_$constants_652.AX_NAME_PATTERN)) return; var axNum = name.substr(5); if(axNum === '1') axNum = ''; return name.charAt(0) + axNum; }; -_$axis_ids_587.cleanId = function cleanId(id, axLetter) { - if(!id.match(_$constants_589.AX_ID_PATTERN)) return; +_$axis_ids_650.cleanId = function cleanId(id, axLetter) { + if(!id.match(_$constants_652.AX_ID_PATTERN)) return; if(axLetter && id.charAt(0) !== axLetter) return; var axNum = id.substr(1).replace(/^0+/, ''); @@ -21878,11 +22126,11 @@ _$axis_ids_587.cleanId = function cleanId(id, axLetter) { }; // get all axis objects, as restricted in listNames -_$axis_ids_587.list = function(gd, axLetter, only2d) { +_$axis_ids_650.list = function(gd, axLetter, only2d) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; - var idList = _$axis_ids_587.listIds(gd, axLetter); + var idList = _$axis_ids_650.listIds(gd, axLetter); var out = new Array(idList.length); var i; @@ -21907,7 +22155,7 @@ _$axis_ids_587.list = function(gd, axLetter, only2d) { // get all axis ids, optionally restricted by letter // this only makes sense for 2d axes -_$axis_ids_587.listIds = function(gd, axLetter) { +_$axis_ids_650.listIds = function(gd, axLetter) { var fullLayout = gd._fullLayout; if(!fullLayout) return []; @@ -21918,42 +22166,42 @@ _$axis_ids_587.listIds = function(gd, axLetter) { // 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 -_$axis_ids_587.getFromId = function(gd, id, type) { +_$axis_ids_650.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[_$axis_ids_587.id2name(id)]; + return fullLayout[_$axis_ids_650.id2name(id)]; }; // get an axis object of specified type from the containing trace -_$axis_ids_587.getFromTrace = function(gd, fullTrace, type) { +_$axis_ids_650.getFromTrace = function(gd, fullTrace, type) { var fullLayout = gd._fullLayout; var ax = null; - if(_$registry_668.traceIs(fullTrace, 'gl3d')) { + if(_$registry_731.traceIs(fullTrace, 'gl3d')) { var scene = fullTrace.scene; if(scene.substr(0, 5) === 'scene') { ax = fullLayout[scene][type + 'axis']; } } else { - ax = _$axis_ids_587.getFromId(gd, fullTrace[type + 'axis'] || type); + ax = _$axis_ids_650.getFromId(gd, fullTrace[type + 'axis'] || type); } return ax; }; // sort x, x2, x10, y, y2, y10... -_$axis_ids_587.idSort = function(id1, id2) { +_$axis_ids_650.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); }; -var _$command_609 = {}; +var _$command_671 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -21964,8 +22212,8 @@ var _$command_609 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; /* * Create or update an observer. This function is designed to be @@ -21983,7 +22231,7 @@ var _$command_609 = {}; * A listener called when the value is changed. Receives data object * with information about the new state. */ -_$command_609.manageCommandObserver = function(gd, container, commandList, onchange) { +_$command_671.manageCommandObserver = function(gd, container, commandList, onchange) { var ret = {}; var enabled = true; @@ -21998,7 +22246,7 @@ _$command_609.manageCommandObserver = function(gd, container, commandList, oncha // Either create or just recompute this: ret.lookupTable = {}; - var binding = _$command_609.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); + var binding = _$command_671.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); if(container && container._commandObserver) { if(!binding) { @@ -22069,7 +22317,7 @@ _$command_609.manageCommandObserver = function(gd, container, commandList, oncha } else { // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning // is a start - _$lib_539.log('Unable to automatically bind plot updates to API command'); + _$lib_601.log('Unable to automatically bind plot updates to API command'); ret.lookupTable = {}; ret.remove = function() {}; @@ -22099,7 +22347,7 @@ _$command_609.manageCommandObserver = function(gd, container, commandList, oncha * 2. only one property may be affected * 3. the same property must be affected by all commands */ -_$command_609.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { +_$command_671.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { var i; var n = commandList.length; @@ -22117,7 +22365,7 @@ _$command_609.hasSimpleAPICommandBindings = function(gd, commandList, bindingsBy if(!method) { return false; } - var bindings = _$command_609.computeAPICommandBindings(gd, method, args); + var bindings = _$command_671.computeAPICommandBindings(gd, method, args); // Right now, handle one and *only* one property being set: if(bindings.length !== 1) { @@ -22187,7 +22435,7 @@ function bindingValueHasChanged(gd, binding, cache) { return false; } - value = _$lib_539.nestedProperty(container, binding.prop).get(); + value = _$lib_601.nestedProperty(container, binding.prop).get(); obj = cache[binding.type] = cache[binding.type] || {}; @@ -22216,10 +22464,10 @@ function bindingValueHasChanged(gd, binding, cache) { * @param {array} args * A list of arguments passed to the API command */ -_$command_609.executeAPICommand = function(gd, method, args) { +_$command_671.executeAPICommand = function(gd, method, args) { if(method === 'skip') return Promise.resolve(); - var _method = _$registry_668.apiMethodRegistry[method]; + var _method = _$registry_731.apiMethodRegistry[method]; var allArgs = [gd]; if(!Array.isArray(args)) args = []; @@ -22228,12 +22476,12 @@ _$command_609.executeAPICommand = function(gd, method, args) { } return _method.apply(null, allArgs).catch(function(err) { - _$lib_539.warn('API call to Plotly.' + method + ' rejected.', err); + _$lib_601.warn('API call to Plotly.' + method + ' rejected.', err); return Promise.reject(err); }); }; -_$command_609.computeAPICommandBindings = function(gd, method, args) { +_$command_671.computeAPICommandBindings = function(gd, method, args) { var bindings; if(!Array.isArray(args)) args = []; @@ -22278,7 +22526,7 @@ function computeLayoutBindings(gd, args) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = args[1]; - } else if(_$lib_539.isPlainObject(astr)) { + } else if(_$lib_601.isPlainObject(astr)) { aobj = astr; } else { return bindings; @@ -22302,7 +22550,7 @@ function computeDataBindings(gd, args) { aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_539.isPlainObject(astr)) { + } else if(_$lib_601.isPlainObject(astr)) { // the 3-arg form aobj = astr; @@ -22368,7 +22616,7 @@ function crawl(attrs, callback, path, depth) { var thisPath = path + (depth > 0 ? '.' : '') + attrName; - if(_$lib_539.isPlainObject(attr)) { + if(_$lib_601.isPlainObject(attr)) { crawl(attr, callback, thisPath, depth + 1); } else { // Only execute the callback on leaf nodes: @@ -22377,7 +22625,33 @@ function crawl(attrs, callback, path, depth) { }); } -var _$plots_647 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +// always plot splom before cartesian (i.e. scattergl traces) +function sortModules(a, b) { + if(a === 'splom') return -1; + if(b === 'splom') return 1; + return 0; +} + +function sortBasePlotModules(a, b) { + return sortModules(a.name, b.name); +} + +var _$sort_modules_722 = { + sortBasePlotModules: sortBasePlotModules, + sortModules: sortModules +}; + +var _$plots_709 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -22389,56 +22663,58 @@ var _$plots_647 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$plot_schema_575 = require('../plot_api/plot_schema'); */; -/* removed: var _$axis_ids_587 = require('../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_539 = require('../lib'); */; -var _ = _$lib_539._; -/* removed: var _$color_411 = require('../components/color'); */; -var __BADNUM_647 = _$numerical_517.BADNUM; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$plot_schema_638 = require('../plot_api/plot_schema'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$color_473 = require('../components/color'); */; +var __BADNUM_709 = _$numerical_578.BADNUM; -var plots = _$plots_647 = {}; +/* removed: var _$axis_ids_650 = require('../plots/cartesian/axis_ids'); */; +var __sortBasePlotModules_709 = _$sort_modules_722.sortBasePlotModules; -/* removed: var _$animation_attributes_579 = require('./animation_attributes'); */; -/* removed: var _$frame_attributes_612 = require('./frame_attributes'); */; +/* removed: var _$animation_attributes_642 = require('./animation_attributes'); */; +/* removed: var _$frame_attributes_674 = require('./frame_attributes'); */; -var relinkPrivateKeys = _$lib_539.relinkPrivateKeys; +var relinkPrivateKeys = _$lib_601.relinkPrivateKeys; +var _ = _$lib_601._; + +var plots = _$plots_709 = {}; // Expose registry methods on Plots for backward-compatibility -_$lib_539.extendFlat(plots, _$registry_668); +_$lib_601.extendFlat(plots, _$registry_731); -plots.attributes = _$attributes_581; +plots.attributes = _$attributes_644; plots.attributes.type.values = plots.allTypes; -plots.fontAttrs = _$font_attributes_611; -plots.layoutAttributes = _$layout_attributes_638; +plots.fontAttrs = _$font_attributes_673; +plots.layoutAttributes = _$layout_attributes_700; // TODO make this a plot attribute? plots.fontWeight = 'normal'; var transformsRegistry = plots.transformsRegistry; -/* removed: var _$command_609 = require('./command'); */; -plots.executeAPICommand = _$command_609.executeAPICommand; -plots.computeAPICommandBindings = _$command_609.computeAPICommandBindings; -plots.manageCommandObserver = _$command_609.manageCommandObserver; -plots.hasSimpleAPICommandBindings = _$command_609.hasSimpleAPICommandBindings; +/* removed: var _$command_671 = require('./command'); */; +plots.executeAPICommand = _$command_671.executeAPICommand; +plots.computeAPICommandBindings = _$command_671.computeAPICommandBindings; +plots.manageCommandObserver = _$command_671.manageCommandObserver; +plots.hasSimpleAPICommandBindings = _$command_671.hasSimpleAPICommandBindings; // in some cases the browser doesn't seem to know how big // the text is at first, so it needs to draw it, // then wait a little, then draw it again plots.redrawText = function(gd) { - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); // do not work if polar is present if((gd.data && gd.data[0] && gd.data[0].r)) return; return new Promise(function(resolve) { setTimeout(function() { - _$registry_668.getComponentMethod('annotations', 'draw')(gd); - _$registry_668.getComponentMethod('legend', 'draw')(gd); + _$registry_731.getComponentMethod('annotations', 'draw')(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); (gd.calcdata || []).forEach(function(d) { if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb(); @@ -22451,7 +22727,7 @@ plots.redrawText = function(gd) { // resize plot about the container size plots.resize = function(gd) { - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); return new Promise(function(resolve, reject) { @@ -22482,7 +22758,7 @@ plots.resize = function(gd) { // nor should it be included in the undo queue gd.autoplay = true; - _$registry_668.call('relayout', gd, {autosize: true}).then(function() { + _$registry_731.call('relayout', gd, {autosize: true}).then(function() { gd.changed = oldchanged; resolve(gd); }); @@ -22512,29 +22788,24 @@ plots.addLinks = function(gd) { var fullLayout = gd._fullLayout; - var linkContainer = fullLayout._paper - .selectAll('text.js-plot-link-container').data([0]); - - linkContainer.enter().append('text') - .classed('js-plot-link-container', true) - .style({ + var linkContainer = _$lib_601.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) { + s.style({ 'font-family': '"Open Sans", Arial, sans-serif', 'font-size': '12px', - 'fill': _$color_411.defaultLine, + 'fill': _$color_473.defaultLine, 'pointer-events': 'all' }) .each(function() { - var links = _$d3_127.select(this); + var links = _$d3_130.select(this); links.append('tspan').classed('js-link-to-tool', true); links.append('tspan').classed('js-link-spacer', true); links.append('tspan').classed('js-sourcelinks', true); }); + }); // The text node inside svg - var text = linkContainer.node(), - attrs = { - y: fullLayout._paper.attr('height') - 9 - }; + var text = linkContainer.node(); + var attrs = {y: fullLayout._paper.attr('height') - 9}; // If text's width is bigger than the layout // Check that text is a child node or document.body @@ -22599,7 +22870,7 @@ plots.sendDataToCloud = function(gd) { var baseUrl = (window.PLOTLYENV && window.PLOTLYENV.BASE_URL) || 'https://plot.ly'; - var hiddenformDiv = _$d3_127.select(gd) + var hiddenformDiv = _$d3_130.select(gd) .append('div') .attr('id', 'hiddenform') .style('display', 'none'); @@ -22672,6 +22943,8 @@ plots.supplyDefaults = function(gd) { var newFullData = gd._fullData = []; var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context = gd._context || {}; var i; @@ -22706,7 +22979,6 @@ plots.supplyDefaults = function(gd) { // first fill in what we can of layout without looking at data // because fullData needs a few things from layout - if(oldFullLayout._initialAutoSizeIsDone) { // coerce the updated layout while preserving width and height @@ -22749,12 +23021,38 @@ plots.supplyDefaults = function(gd) { // clear the lists of trace and baseplot modules, and subplots newFullLayout._modules = []; newFullLayout._basePlotModules = []; - newFullLayout._subplots = emptySubplotLists(); + var subplots = newFullLayout._subplots = emptySubplotLists(); + + // initialize axis and subplot hash objects for splom-generated grids + var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}}; + var splomSubplots = newFullLayout._splomSubplots = {}; + + // for traces to request a default rangeslider on their x axes + // eg set `_requestRangeslider.x2 = true` for xaxis2 + newFullLayout._requestRangeslider = {}; // then do the data newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + // redo grid size defaults with info about splom x/y axes, + // and fill in generated cartesian axes and subplots + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if(splomXa.length > 1 && splomYa.length > 1) { + _$registry_731.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout); + + for(i = 0; i < splomXa.length; i++) { + _$lib_601.pushUnique(subplots.xaxis, splomXa[i]); + } + for(i = 0; i < splomYa.length; i++) { + _$lib_601.pushUnique(subplots.yaxis, splomYa[i]); + } + for(var k in splomSubplots) { + _$lib_601.pushUnique(subplots.cartesian, k); + } + } + // attach helper method to check whether a plot type is present on graph newFullLayout._has = plots._hasPlotType.bind(newFullLayout); @@ -22765,7 +23063,7 @@ plots.supplyDefaults = function(gd) { if(_module.cleanData) _module.cleanData(newFullData); } - if(oldFullData.length === newData.length) { + if(oldFullData.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { relinkPrivateKeys(newFullData[i], oldFullData[i]); } @@ -22774,6 +23072,17 @@ plots.supplyDefaults = function(gd) { // finally, fill in the pieces of layout that may need to look at data plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + // turn on flag to optimize large splom-only graphs + // mostly by omitting SVG layers during Cartesian.drawFramework + newFullLayout._hasOnlyLargeSploms = ( + newFullLayout._basePlotModules.length === 1 && + newFullLayout._basePlotModules[0].name === 'splom' && + splomXa.length > 15 && + splomYa.length > 15 && + newFullLayout.shapes.length === 0 && + newFullLayout.images.length === 0 + ); + // TODO remove in v2.0.0 // add has-plot-type refs to fullLayout for backward compatibility newFullLayout._hasCartesian = newFullLayout._has('cartesian'); @@ -22784,7 +23093,7 @@ plots.supplyDefaults = function(gd) { newFullLayout._hasPie = newFullLayout._has('pie'); // clean subplots and other artifacts from previous plot calls - plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); // relink / initialize subplot axis objects plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); @@ -22796,17 +23105,17 @@ plots.supplyDefaults = function(gd) { plots.doAutoMargin(gd); // set scale after auto margin routine - var axList = _$axis_ids_587.list(gd); + var axList = _$axis_ids_650.list(gd); for(i = 0; i < axList.length; i++) { var ax = axList[i]; ax.setScale(); } // update object references in calcdata - if((gd.calcdata || []).length === newFullData.length) { + if(oldCalcdata.length === newFullData.length) { for(i = 0; i < newFullData.length; i++) { var newTrace = newFullData[i]; - var cd0 = gd.calcdata[i][0]; + var cd0 = oldCalcdata[i][0]; if(cd0 && cd0.trace) { if(cd0.trace._hasCalcTransform) { remapTransformedArrays(cd0, newTrace); @@ -22816,6 +23125,9 @@ plots.supplyDefaults = function(gd) { } } } + + // sort base plot modules for consistent ordering + newFullLayout._basePlotModules.sort(__sortBasePlotModules_709); }; /** @@ -22834,7 +23146,7 @@ function emptySubplotLists() { if(!collectableSubplotTypes) { collectableSubplotTypes = []; - var subplotsRegistry = _$registry_668.subplotsRegistry; + var subplotsRegistry = _$registry_731.subplotsRegistry; for(var subplotType in subplotsRegistry) { var subplotModule = subplotsRegistry[subplotType]; @@ -22847,7 +23159,7 @@ function emptySubplotLists() { // we need to enumerate axes, not just subplots if(Array.isArray(subplotAttr)) { for(j = 0; j < subplotAttr.length; j++) { - _$lib_539.pushUnique(collectableSubplotTypes, subplotAttr[j]); + _$lib_601.pushUnique(collectableSubplotTypes, subplotAttr[j]); } } } @@ -22868,14 +23180,14 @@ function remapTransformedArrays(cd0, newTrace) { for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - transformedArrayHash[astr] = _$lib_539.nestedProperty(oldTrace, astr).get().slice(); + transformedArrayHash[astr] = _$lib_601.nestedProperty(oldTrace, astr).get().slice(); } cd0.trace = newTrace; for(i = 0; i < arrayAttrs.length; i++) { astr = arrayAttrs[i]; - _$lib_539.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); + _$lib_601.nestedProperty(cd0.trace, astr).set(transformedArrayHash[astr]); } } @@ -22920,7 +23232,7 @@ function getFormatObj(gd, formatKeys) { includeFormat(formatj); if(formatDone) break; } - locales = _$registry_668.localeRegistry; + locales = _$registry_731.localeRegistry; } var baseLocale = locale.split('-')[0]; @@ -22929,7 +23241,7 @@ function getFormatObj(gd, formatKeys) { } // lastly pick out defaults from english (non-US, as DMY is so much more common) - if(!formatDone) includeFormat(_$registry_668.localeRegistry.en.format); + if(!formatDone) includeFormat(_$registry_731.localeRegistry.en.format); return formatObj; } @@ -22950,7 +23262,7 @@ function getFormatter(formatObj, separators) { formatObj.decimal = separators.charAt(0); formatObj.thousands = separators.charAt(1); - return _$d3_127.locale(formatObj); + return _$d3_130.locale(formatObj); } // Create storage for all of the data related to frames and transitions: @@ -22981,30 +23293,28 @@ plots.createTransitionData = function(gd) { // whether a certain plot type is present on plot // or trace has a category plots._hasPlotType = function(category) { - // check plot - var basePlotModules = this._basePlotModules || []; var i; + // check base plot modules + var basePlotModules = this._basePlotModules || []; for(i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - - if(_module.name === category) return true; + if(basePlotModules[i].name === category) return true; } - // check trace + // check trace modules var modules = this._modules || []; - for(i = 0; i < modules.length; i++) { - var modulei = modules[i]; - if(modulei.categories && modulei.categories.indexOf(category) >= 0) { - return true; - } + var name = modules[i].name; + if(name === category) return true; + // N.B. this is modules[i] along with 'categories' as a hash object + var _module = _$registry_731.modules[name]; + if(_module && _module.categories[category]) return true; } return false; }; -plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { var i, j; var basePlotModules = oldFullLayout._basePlotModules || []; @@ -23012,7 +23322,7 @@ plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayou var _module = basePlotModules[i]; if(_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata); } } @@ -23084,8 +23394,8 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa for(i = 0; i < ids.length; i++) { id = ids[i]; var oldSubplot = oldSubplots[id]; - var xaxis = _$axis_ids_587.getFromId(mockGd, id, 'x'); - var yaxis = _$axis_ids_587.getFromId(mockGd, id, 'y'); + var xaxis = _$axis_ids_650.getFromId(mockGd, id, 'x'); + var yaxis = _$axis_ids_650.getFromId(mockGd, id, 'y'); var plotinfo; if(oldSubplot) { @@ -23130,13 +23440,13 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa // while we're at it, link overlaying axes to their main axes and // anchored axes to the axes they're anchored to - var axList = _$axis_ids_587.list(mockGd, null, true); + var axList = _$axis_ids_650.list(mockGd, null, true); for(i = 0; i < axList.length; i++) { ax = axList[i]; var mainAx = null; if(ax.overlaying) { - mainAx = _$axis_ids_587.getFromId(mockGd, ax.overlaying); + mainAx = _$axis_ids_650.getFromId(mockGd, ax.overlaying); // you cannot overlay an axis that's already overlaying another if(mainAx && mainAx.overlaying) { @@ -23158,7 +23468,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa ax._anchorAxis = ax.anchor === 'free' ? null : - _$axis_ids_587.getFromId(mockGd, ax.anchor); + _$axis_ids_650.getFromId(mockGd, ax.anchor); } for(i = 0; i < axList.length; i++) { @@ -23187,7 +23497,7 @@ plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLa var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex); if(idPart === ax._id) { if(!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = _$axis_ids_587.getFromId(mockGd, counterPart); + var counterAx = _$axis_ids_650.getFromId(mockGd, counterPart); if(anchorID && counterAx.overlaying === anchorID) { mainSubplotID = id; break; @@ -23228,17 +23538,17 @@ plots.clearExpandedTraceDefaultColors = function(trace) { // Or else compute and cache the colorAttrs on the module: if(!colorAttrs) { trace._module._colorAttrs = colorAttrs = []; - _$plot_schema_575.crawl( + _$plot_schema_638.crawl( trace._module.attributes, locateColorAttrs ); } for(i = 0; i < colorAttrs.length; i++) { - var origprop = _$lib_539.nestedProperty(trace, '_input.' + colorAttrs[i]); + var origprop = _$lib_601.nestedProperty(trace, '_input.' + colorAttrs[i]); if(!origprop.get()) { - _$lib_539.nestedProperty(trace, colorAttrs[i]).set(null); + _$lib_601.nestedProperty(trace, colorAttrs[i]).set(null); } } }; @@ -23260,8 +23570,8 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { var _module = fullTrace._module; if(!_module) return; - if(fullTrace.visible === true) _$lib_539.pushUnique(modules, _module); - _$lib_539.pushUnique(basePlotModules, fullTrace._module.basePlotModule); + if(fullTrace.visible === true) _$lib_601.pushUnique(modules, _module); + _$lib_601.pushUnique(basePlotModules, fullTrace._module.basePlotModule); cnt++; @@ -23321,11 +23631,11 @@ plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { pushModule(fullTrace); } - if(_$registry_668.traceIs(fullTrace, 'carpetAxis')) { + if(_$registry_731.traceIs(fullTrace, 'carpetAxis')) { carpetIndex[fullTrace.carpet] = fullTrace; } - if(_$registry_668.traceIs(fullTrace, 'carpetDependent')) { + if(_$registry_731.traceIs(fullTrace, 'carpetDependent')) { carpetDependents.push(i); } } @@ -23354,7 +23664,7 @@ plots.supplyAnimationDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts || {}, optsOut, _$animation_attributes_579, attr, dflt); + return _$lib_601.coerce(opts || {}, optsOut, _$animation_attributes_642, attr, dflt); } coerce('mode'); @@ -23386,7 +23696,7 @@ plots.supplyAnimationFrameDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts || {}, optsOut, _$animation_attributes_579.frame, attr, dflt); + return _$lib_601.coerce(opts || {}, optsOut, _$animation_attributes_642.frame, attr, dflt); } coerce('duration'); @@ -23399,7 +23709,7 @@ plots.supplyAnimationTransitionDefaults = function(opts) { var optsOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts || {}, optsOut, _$animation_attributes_579.transition, attr, dflt); + return _$lib_601.coerce(opts || {}, optsOut, _$animation_attributes_642.transition, attr, dflt); } coerce('duration'); @@ -23412,7 +23722,7 @@ plots.supplyFrameDefaults = function(frameIn) { var frameOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(frameIn, frameOut, _$frame_attributes_612, attr, dflt); + return _$lib_601.coerce(frameIn, frameOut, _$frame_attributes_674, attr, dflt); } coerce('group'); @@ -23426,14 +23736,14 @@ plots.supplyFrameDefaults = function(frameIn) { }; plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) { - var colorway = layout.colorway || _$color_411.defaults; + var colorway = layout.colorway || _$color_473.defaults; var traceOut = {}, defaultColor = colorway[colorIndex % colorway.length]; var i; function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, plots.attributes, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, plots.attributes, attr, dflt); } var visible = coerce('visible'); @@ -23449,9 +23759,9 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { var basePlotModule = _module.basePlotModule; var subplotAttr = basePlotModule.attr; - if(subplotAttr) { + var subplotAttrs = basePlotModule.attributes; + if(subplotAttr && subplotAttrs) { var subplots = layout._subplots; - var subplotAttrs = basePlotModule.attributes; var subplotId = ''; // TODO - currently if we draw an empty gl2d subplot, it draws @@ -23461,18 +23771,18 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(Array.isArray(subplotAttr)) { for(i = 0; i < subplotAttr.length; i++) { var attri = subplotAttr[i]; - var vali = _$lib_539.coerce(traceIn, traceOut, subplotAttrs, attri); + var vali = _$lib_601.coerce(traceIn, traceOut, subplotAttrs, attri); - if(subplots[attri]) _$lib_539.pushUnique(subplots[attri], vali); + if(subplots[attri]) _$lib_601.pushUnique(subplots[attri], vali); subplotId += vali; } } else { - subplotId = _$lib_539.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + subplotId = _$lib_601.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); } if(subplots[basePlotModule.name]) { - _$lib_539.pushUnique(subplots[basePlotModule.name], subplotId); + _$lib_601.pushUnique(subplots[basePlotModule.name], subplotId); } } } @@ -23482,12 +23792,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) coerce('customdata'); coerce('ids'); - if(_$registry_668.traceIs(traceOut, 'showLegend')) { + if(_$registry_731.traceIs(traceOut, 'showLegend')) { coerce('showlegend'); coerce('legendgroup'); } - _$registry_668.getComponentMethod( + _$registry_731.getComponentMethod( 'fx', 'supplyDefaults' )(traceIn, traceOut, defaultColor, layout); @@ -23496,12 +23806,12 @@ plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) if(_module) { _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - _$lib_539.coerceHoverinfo(traceIn, traceOut, layout); + _$lib_601.coerceHoverinfo(traceIn, traceOut, layout); } - if(!_$registry_668.traceIs(traceOut, 'noOpacity')) coerce('opacity'); + if(!_$registry_731.traceIs(traceOut, 'noOpacity')) coerce('opacity'); - if(_$registry_668.traceIs(traceOut, 'notLegendIsolatable')) { + if(_$registry_731.traceIs(traceOut, 'notLegendIsolatable')) { // This clears out the legendonly state for traces like carpet that // cannot be isolated in the legend traceOut.visible = !!traceOut.visible; @@ -23545,17 +23855,17 @@ plots.supplyTransformDefaults = function(traceIn, traceOut, layout) { var isFirstStage = !(transformIn._module && transformIn._module === _module), doLaterStages = _module && typeof _module.transform === 'function'; - if(!_module) _$lib_539.warn('Unrecognized transform type ' + type + '.'); + if(!_module) _$lib_601.warn('Unrecognized transform type ' + type + '.'); if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); transformOut.type = type; transformOut._module = _module; - _$lib_539.pushUnique(transformModules, _module); + _$lib_601.pushUnique(transformModules, _module); } else { - transformOut = _$lib_539.extendFlat({}, transformIn); + transformOut = _$lib_601.extendFlat({}, transformIn); } containerOut.push(transformOut); @@ -23587,14 +23897,14 @@ function applyTransforms(fullTrace, fullData, layout, fullLayout) { plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt); } - var globalFont = _$lib_539.coerceFont(coerce, 'font'); + var globalFont = _$lib_601.coerceFont(coerce, 'font'); coerce('title', layoutOut._dfltTitle.plot); - _$lib_539.coerceFont(coerce, 'titlefont', { + _$lib_601.coerceFont(coerce, 'titlefont', { family: globalFont.family, size: Math.round(globalFont.size * 1.4), color: globalFont.color @@ -23622,7 +23932,7 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut); - _$registry_668.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); + _$registry_731.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut); coerce('paper_bgcolor'); @@ -23633,12 +23943,12 @@ plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { coerce('datarevision'); - _$registry_668.getComponentMethod( + _$registry_731.getComponentMethod( 'calendars', 'handleDefaults' )(layoutIn, layoutOut, 'calendar'); - _$registry_668.getComponentMethod( + _$registry_731.getComponentMethod( 'fx', 'supplyLayoutGlobalDefaults' )(layoutIn, layoutOut, coerce); @@ -23650,7 +23960,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { newWidth, newHeight; - var isPlotDiv = _$lib_539.isPlotDiv(gd); + var isPlotDiv = _$lib_601.isPlotDiv(gd); if(isPlotDiv) gd.emit('plotly_autosize'); @@ -23664,7 +23974,7 @@ plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { // just hide it document.body.style.overflow = 'hidden'; } - else if(_$fastIsnumeric_139(frameMargins) && frameMargins > 0) { + else if(_$fastIsnumeric_196(frameMargins) && frameMargins > 0) { var reservedMargins = calculateReservedMargins(gd._boundingBoxMargins), reservedWidth = reservedMargins.left + reservedMargins.right, reservedHeight = reservedMargins.bottom + reservedMargins.top, @@ -23738,11 +24048,11 @@ function calculateReservedMargins(margins) { } plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = _$registry_668.componentsRegistry; + var componentsRegistry = _$registry_731.componentsRegistry; var basePlotModules = layoutOut._basePlotModules; var component, i, _module; - var Cartesian = _$registry_668.subplotsRegistry.cartesian; + var Cartesian = _$registry_731.subplotsRegistry.cartesian; // check if any components need to add more base plot modules // that weren't captured by traces @@ -23761,13 +24071,13 @@ plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, trans // ensure all cartesian axes have at least one subplot if(layoutOut._has('cartesian')) { - _$registry_668.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); + _$registry_731.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut); Cartesian.finalizeSubplots(layoutIn, layoutOut); } // sort subplot lists for(var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(_$lib_539.subplotSort); + layoutOut._subplots[subplotType].sort(_$lib_601.subplotSort); } // base plot module layout defaults @@ -23839,7 +24149,7 @@ plots.purge = function(gd) { } // remove any planned throttles - _$lib_539.clearThrottle(); + _$lib_601.clearThrottle(); // data and layout delete gd.data; @@ -23895,7 +24205,7 @@ plots.style = function(gd) { for(i = 0; i < _modules.length; i++) { var _module = _modules[i]; if(_module.style) { - _$lib_539.pushUnique(styleModules, _module.style); + _$lib_601.pushUnique(styleModules, _module.style); } } @@ -24004,7 +24314,7 @@ plots.doAutoMargin = function(gd) { pb = pushbottom.size; for(var k2 in pm) { - if(_$fastIsnumeric_139(pl) && pm[k2].r) { + if(_$fastIsnumeric_196(pl) && pm[k2].r) { var fr = pm[k2].r.val, pr = pm[k2].r.size; @@ -24020,7 +24330,7 @@ plots.doAutoMargin = function(gd) { } } - if(_$fastIsnumeric_139(pb) && pm[k2].t) { + if(_$fastIsnumeric_196(pb) && pm[k2].t) { var ft = pm[k2].t.val, pt = pm[k2].t.size; @@ -24050,7 +24360,7 @@ plots.doAutoMargin = function(gd) { // if things changed and we're not already redrawing, trigger a redraw if(!fullLayout._replotting && oldmargins !== '{}' && oldmargins !== JSON.stringify(fullLayout._size)) { - return _$registry_668.call('plot', gd); + return _$registry_731.call('plot', gd); } }; @@ -24091,7 +24401,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { if(typeof d === 'function') { return null; } - if(_$lib_539.isPlainObject(d)) { + if(_$lib_601.isPlainObject(d)) { var o = {}, v, src; for(v in d) { // remove private elements and functions @@ -24114,7 +24424,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // in a trace, we will keep the data array. src = d[v + 'src']; if(typeof src === 'string' && src.indexOf(':') > 0) { - if(!_$lib_539.isPlainObject(d.stream)) { + if(!_$lib_601.isPlainObject(d.stream)) { continue; } } @@ -24140,7 +24450,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { // convert native dates to date strings... // mostly for external users exporting to plotly - if(_$lib_539.isJSDate(d)) return _$lib_539.ms2DateTimeLocal(+d); + if(_$lib_601.isJSDate(d)) return _$lib_601.ms2DateTimeLocal(+d); return d; } @@ -24337,8 +24647,8 @@ plots.recomputeFrameHash = function(gd) { */ plots.extendObjectWithContainers = function(dest, src, containerPaths) { var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy = _$lib_539.extendDeepNoArrays({}, src || {}); - var expandedObj = _$lib_539.expandObjectPaths(copy); + var copy = _$lib_601.extendDeepNoArrays({}, src || {}); + var expandedObj = _$lib_601.expandObjectPaths(copy); var containerObj = {}; // Step through and extract any container properties. Otherwise extendDeepNoArrays @@ -24346,29 +24656,29 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { // will reset everything to defaults. if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - containerProp = _$lib_539.nestedProperty(expandedObj, containerPaths[i]); + containerProp = _$lib_601.nestedProperty(expandedObj, containerPaths[i]); containerVal = containerProp.get(); if(containerVal === undefined) { - _$lib_539.nestedProperty(containerObj, containerPaths[i]).set(null); + _$lib_601.nestedProperty(containerObj, containerPaths[i]).set(null); } else { containerProp.set(null); - _$lib_539.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + _$lib_601.nestedProperty(containerObj, containerPaths[i]).set(containerVal); } } } - dest = _$lib_539.extendDeepNoArrays(dest || {}, expandedObj); + dest = _$lib_601.extendDeepNoArrays(dest || {}, expandedObj); if(containerPaths && containerPaths.length) { for(i = 0; i < containerPaths.length; i++) { - srcProp = _$lib_539.nestedProperty(containerObj, containerPaths[i]); + srcProp = _$lib_601.nestedProperty(containerObj, containerPaths[i]); srcContainer = srcProp.get(); if(!srcContainer) continue; - destProp = _$lib_539.nestedProperty(dest, containerPaths[i]); + destProp = _$lib_601.nestedProperty(dest, containerPaths[i]); destContainer = destProp.get(); if(!Array.isArray(destContainer)) { @@ -24393,7 +24703,7 @@ plots.extendObjectWithContainers = function(dest, src, containerPaths) { }; plots.dataArrayContainers = ['transforms', 'dimensions']; -plots.layoutArrayContainers = _$registry_668.layoutArrayContainers; +plots.layoutArrayContainers = _$registry_731.layoutArrayContainers; /* * Extend a trace definition. This method: @@ -24467,7 +24777,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // Follow the same procedure. Clone it so we don't mangle the input, then // expand any object paths so we can merge deep into gd.layout: - var layoutUpdate = _$lib_539.expandObjectPaths(_$lib_539.extendDeepNoArrays({}, layout)); + var layoutUpdate = _$lib_601.expandObjectPaths(_$lib_601.extendDeepNoArrays({}, layout)); // Before merging though, we need to modify the incoming layout. We only // know how to *transition* layout ranges, so it's imperative that a new @@ -24494,7 +24804,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) plots.doCalcdata(gd); - _$registry_668.getComponentMethod('errorbars', 'calc')(gd); + _$registry_731.getComponentMethod('errorbars', 'calc')(gd); return Promise.resolve(); } @@ -24542,7 +24852,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(frameOpts.redraw) { gd._transitionData._interruptCallbacks.push(function() { - return _$registry_668.call('redraw', gd); + return _$registry_731.call('redraw', gd); }); } @@ -24574,7 +24884,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) if(layout) { for(j = 0; j < basePlotModules.length; j++) { if(basePlotModules[j].transitionAxes) { - var newLayout = _$lib_539.expandObjectPaths(layout); + var newLayout = _$lib_601.expandObjectPaths(layout); hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition; } } @@ -24584,7 +24894,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) // time. In other words, if there's an axis transition, then set the data transition // to instantaneous. if(hasAxisTransition) { - traceTransitionOpts = _$lib_539.extendFlat({}, transitionOpts); + traceTransitionOpts = _$lib_601.extendFlat({}, transitionOpts); traceTransitionOpts.duration = 0; } else { traceTransitionOpts = transitionOpts; @@ -24614,7 +24924,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) return Promise.resolve().then(function() { if(frameOpts.redraw) { - return _$registry_668.call('redraw', gd); + return _$registry_731.call('redraw', gd); } }).then(function() { // Set transitioning false again once the redraw has occurred. This is used, for example, @@ -24649,7 +24959,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions]; - var transitionStarting = _$lib_539.syncOrAsync(seq, gd); + var transitionStarting = _$lib_601.syncOrAsync(seq, gd); if(!transitionStarting || !transitionStarting.then) { transitionStarting = Promise.resolve(); @@ -24661,7 +24971,7 @@ plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) }; plots.doCalcdata = function(gd, traces) { - var axList = _$axis_ids_587.list(gd), + var axList = _$axis_ids_650.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; @@ -24705,7 +25015,7 @@ plots.doCalcdata = function(gd, traces) { // find array attributes in trace for(i = 0; i < fullData.length; i++) { trace = fullData[i]; - trace._arrayAttrs = _$plot_schema_575.findArrayAttributes(trace); + trace._arrayAttrs = _$plot_schema_638.findArrayAttributes(trace); } // add polar axes to axis list @@ -24749,14 +25059,15 @@ plots.doCalcdata = function(gd, traces) { // clear stuff that should recomputed in 'regular' loop if(hasCalcTransform) clearAxesCalc(axList); - // 'regular' loop - for(i = 0; i < fullData.length; i++) { - var cd = []; - + function calci(i, isContainer) { trace = fullData[i]; + _module = trace._module; + + if(!!_module.isContainer !== isContainer) return; + + var cd = []; if(trace.visible === true) { - _module = trace._module; // keep ref of index-to-points map object of the *last* enabled transform, // this index-to-points map object is required to determine the calcdata indices @@ -24779,7 +25090,7 @@ plots.doCalcdata = function(gd, traces) { // This ensures there is a calcdata item for every trace, // even if cartesian logic doesn't handle it (for things like legends). if(!Array.isArray(cd) || !cd[0]) { - cd = [{x: __BADNUM_647, y: __BADNUM_647}]; + cd = [{x: __BADNUM_709, y: __BADNUM_709}]; } // add the trace-wide properties to the first point, @@ -24791,7 +25102,12 @@ plots.doCalcdata = function(gd, traces) { calcdata[i] = cd; } - _$registry_668.getComponentMethod('fx', 'calc')(gd); + // 'regular' loop - make sure container traces (eg carpet) calc before + // contained traces (eg contourcarpet) + for(i = 0; i < fullData.length; i++) calci(i, true); + for(i = 0; i < fullData.length; i++) calci(i, false); + + _$registry_731.getComponentMethod('fx', 'calc')(gd); }; function clearAxesCalc(axList) { @@ -24842,7 +25158,7 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl var moduleCalcData = traceHash[moduleName]; var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, _$lib_539.filterVisible(moduleCalcData), subplotLayout); + _module.plot(gd, subplot, _$lib_601.filterVisible(moduleCalcData), subplotLayout); } // update moduleName -> calcData hash @@ -24860,18 +25176,18 @@ plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subpl 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$interactions_516 = require('../../constants/interactions'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$interactions_577 = require('../../constants/interactions'); */; -var _$titles_504 = { +var _$titles_566 = { draw: draw }; @@ -24949,10 +25265,7 @@ function draw(gd, titleClass, options) { var elShouldExist = txt || editable; if(!group) { - group = fullLayout._infolayer.selectAll('.g-' + titleClass) - .data([0]); - group.enter().append('g') - .classed('g-' + titleClass, true); + group = _$lib_601.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass); } var el = group.selectAll('text') @@ -24970,7 +25283,7 @@ function draw(gd, titleClass, options) { if(!elShouldExist) return group; function titleLayout(titleEl) { - _$lib_539.syncOrAsync([drawTitle, scootTitle], titleEl); + _$lib_601.syncOrAsync([drawTitle, scootTitle], titleEl); } function drawTitle(titleEl) { @@ -24992,19 +25305,19 @@ function draw(gd, titleClass, options) { titleEl.style({ 'font-family': font, - 'font-size': _$d3_127.round(fontSize, 2) + 'px', - fill: _$color_411.rgb(fontColor), - opacity: opacity * _$color_411.opacity(fontColor), - 'font-weight': _$plots_647.fontWeight + 'font-size': _$d3_130.round(fontSize, 2) + 'px', + fill: _$color_473.rgb(fontColor), + opacity: opacity * _$color_473.opacity(fontColor), + 'font-weight': _$plots_709.fontWeight }) .attr(attributes) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); } function scootTitle(titleElIn) { - var titleGroup = _$d3_127.select(titleElIn.node().parentNode); + var titleGroup = _$d3_130.select(titleElIn.node().parentNode); if(avoid && avoid.selection && avoid.side && txt) { titleGroup.attr('transform', null); @@ -25020,8 +25333,8 @@ function draw(gd, titleClass, options) { }[avoid.side]; var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ? -1 : 1; - var pad = _$fastIsnumeric_139(avoid.pad) ? avoid.pad : 2; - var titlebb = _$drawing_436.bBox(titleGroup.node()); + var pad = _$fastIsnumeric_196(avoid.pad) ? avoid.pad : 2; + var titlebb = _$drawing_498.bBox(titleGroup.node()); var paperbb = { left: 0, top: 0, @@ -25046,9 +25359,9 @@ function draw(gd, titleClass, options) { // iterate over a set of elements (avoid.selection) // to avoid collisions with avoid.selection.each(function() { - var avoidbb = _$drawing_436.bBox(this); + var avoidbb = _$drawing_498.bBox(this); - if(_$lib_539.bBoxIntersect(titlebb, avoidbb, pad)) { + if(_$lib_601.bBoxIntersect(titlebb, avoidbb, pad)) { shift = Math.max(shift, shiftSign * ( avoidbb[avoid.side] - titlebb[backside]) + pad); } @@ -25075,12 +25388,12 @@ function draw(gd, titleClass, options) { isplaceholder = true; el.text(placeholder) .on('mouseover.opacity', function() { - _$d3_127.select(this).transition() - .duration(_$interactions_516.SHOW_PLACEHOLDER).style('opacity', 1); + _$d3_130.select(this).transition() + .duration(_$interactions_577.SHOW_PLACEHOLDER).style('opacity', 1); }) .on('mouseout.opacity', function() { - _$d3_127.select(this).transition() - .duration(_$interactions_516.HIDE_PLACEHOLDER).style('opacity', 0); + _$d3_130.select(this).transition() + .duration(_$interactions_577.HIDE_PLACEHOLDER).style('opacity', 0); }); } @@ -25088,12 +25401,12 @@ function draw(gd, titleClass, options) { if(!txt) setPlaceholder(); else el.on('.opacity', null); - el.call(_$svg_text_utils_562.makeEditable, {gd: gd}) + el.call(_$svg_text_utils_625.makeEditable, {gd: gd}) .on('edit', function(text) { if(traceIndex !== undefined) { - _$registry_668.call('restyle', gd, prop, text, traceIndex); + _$registry_731.call('restyle', gd, prop, text, traceIndex); } else { - _$registry_668.call('relayout', gd, prop, text); + _$registry_731.call('relayout', gd, prop, text); } }) .on('cancel', function() { @@ -25102,7 +25415,7 @@ function draw(gd, titleClass, options) { }) .on('input', function(d) { this.text(d || ' ') - .call(_$svg_text_utils_562.positionText, attributes.x, attributes.y); + .call(_$svg_text_utils_625.positionText, attributes.x, attributes.y); }); } el.classed('js-placeholder', isplaceholder); @@ -25121,12 +25434,12 @@ function draw(gd, titleClass, options) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __FP_SAFE_583 = _$numerical_517.FP_SAFE; +/* removed: var _$lib_601 = require('../../lib'); */; +var __FP_SAFE_646 = _$numerical_578.FP_SAFE; -var _$autorange_583 = { +var _$autorange_646 = { getAutoRange: getAutoRange, makePadFn: makePadFn, doAutoRange: doAutoRange, @@ -25171,7 +25484,7 @@ function getAutoRange(ax) { } if(ax.range) { - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); axReverse = rng[1] < rng[0]; } @@ -25264,7 +25577,7 @@ function getAutoRange(ax) { // maintain reversal if(axReverse) newRange.reverse(); - return _$lib_539.simpleMap(newRange, ax.l2r || Number); + return _$lib_601.simpleMap(newRange, ax.l2r || Number); } /* @@ -25296,7 +25609,7 @@ function doAutoRange(ax) { ax.range = getAutoRange(ax); ax._r = ax.range.slice(); - ax._rl = _$lib_539.simpleMap(ax._r, ax.r2l); + ax._rl = _$lib_601.simpleMap(ax._r, ax.r2l); // doAutoRange will get called on fullLayout, // but we want to report its results back to layout @@ -25318,7 +25631,7 @@ function doAutoRange(ax) { } } axIn = ax._anchorAxis._input; - axIn.rangeslider[ax._name] = _$lib_539.extendFlat({}, axeRangeOpts); + axIn.rangeslider[ax._name] = _$lib_601.extendFlat({}, axeRangeOpts); } } @@ -25331,6 +25644,8 @@ function needsAutorange(ax) { * Note that `expand` is called during `calc`, when we don't yet know the axis * length; all the inputs should be based solely on the trace data, nothing * about the axis layout. + * Note that `ppad` and `vpad` as well as their asymmetric variants refer to + * the before and after padding of the passed `data` array, not to the whole axis. * * @param {object} ax: the axis being expanded. The result will be more entries * in ax._min and ax._max if necessary to include the new data @@ -25391,14 +25706,14 @@ function expand(ax, data, options) { v = data[i]; // data is not linearized yet so we still have to filter out negative logs if(v < vmin && v > 0) vmin = v; - if(v > vmax && v < __FP_SAFE_583) vmax = v; + if(v > vmax && v < __FP_SAFE_646) vmax = v; } } else { for(i = 0; i < len; i++) { v = data[i]; - if(v < vmin && v > -__FP_SAFE_583) vmin = v; - if(v > vmax && v < __FP_SAFE_583) vmax = v; + if(v < vmin && v > -__FP_SAFE_646) vmin = v; + if(v > vmax && v < __FP_SAFE_646) vmax = v; } } @@ -25408,7 +25723,7 @@ function expand(ax, data, options) { function addItem(i) { di = data[i]; - if(!_$fastIsnumeric_139(di)) return; + if(!_$fastIsnumeric_196(di)) return; ppadiplus = ppadplus(i); ppadiminus = ppadminus(i); vmin = di - vpadminus(i); @@ -25432,7 +25747,7 @@ function expand(ax, data, options) { if(goodNumber(newVal)) { var extremes = k ? ax._max : ax._min; var newPad = k ? ppadiplus : ppadiminus; - var atLeastAsExtreme = k ? __greaterOrEqual_583 : __lessOrEqual_583; + var atLeastAsExtreme = k ? __greaterOrEqual_646 : __lessOrEqual_646; includeThis = true; /* @@ -25483,11 +25798,11 @@ function expand(ax, data, options) { // In order to stop overflow errors, don't consider points // too close to the limits of js floating point function goodNumber(v) { - return _$fastIsnumeric_139(v) && Math.abs(v) < __FP_SAFE_583; + return _$fastIsnumeric_196(v) && Math.abs(v) < __FP_SAFE_646; } -function __lessOrEqual_583(v0, v1) { return v0 <= v1; } -function __greaterOrEqual_583(v0, v1) { return v0 >= v1; } +function __lessOrEqual_646(v0, v1) { return v0 <= v1; } +function __greaterOrEqual_646(v0, v1) { return v0 >= v1; } /** * Copyright 2012-2018, Plotly, Inc. @@ -25500,12 +25815,12 @@ function __greaterOrEqual_583(v0, v1) { return v0 >= v1; } 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_585 = _$numerical_517.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_648 = _$numerical_578.BADNUM; -var _$autoType_585 = function autoType(array, calendar) { +var _$autoType_648 = function autoType(array, calendar) { if(moreDates(array, calendar)) return 'date'; if(category(array)) return 'category'; if(linearOK(array)) return 'linear'; @@ -25518,7 +25833,7 @@ function linearOK(array) { if(!array) return false; for(var i = 0; i < array.length; i++) { - if(_$fastIsnumeric_139(array[i])) return true; + if(_$fastIsnumeric_196(array[i])) return true; } return false; @@ -25538,8 +25853,8 @@ function moreDates(a, calendar) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_539.isDateTime(ai, calendar)) dcnt += 1; - if(_$fastIsnumeric_139(ai)) ncnt += 1; + if(_$lib_601.isDateTime(ai, calendar)) dcnt += 1; + if(_$fastIsnumeric_196(ai)) ncnt += 1; } return (dcnt > ncnt * 2); @@ -25556,7 +25871,7 @@ function category(a) { for(var i = 0; i < a.length; i += inc) { ai = a[Math.round(i)]; - if(_$lib_539.cleanNumber(ai) !== __BADNUM_585) curvenums++; + if(_$lib_601.cleanNumber(ai) !== __BADNUM_648) curvenums++; else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++; } @@ -25574,21 +25889,21 @@ function category(a) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var cleanNumber = _$lib_539.cleanNumber; -var ms2DateTime = _$lib_539.ms2DateTime; -var dateTime2ms = _$lib_539.dateTime2ms; -var ensureNumber = _$lib_539.ensureNumber; +/* removed: var _$lib_601 = require('../../lib'); */; +var cleanNumber = _$lib_601.cleanNumber; +var ms2DateTime = _$lib_601.ms2DateTime; +var dateTime2ms = _$lib_601.dateTime2ms; +var ensureNumber = _$lib_601.ensureNumber; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var __FP_SAFE_603 = _$numerical_517.FP_SAFE; -var __BADNUM_603 = _$numerical_517.BADNUM; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var __FP_SAFE_665 = _$numerical_578.FP_SAFE; +var __BADNUM_665 = _$numerical_578.BADNUM; -/* removed: var _$constants_589 = require('./constants'); */; -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; +/* removed: var _$constants_652 = require('./constants'); */; +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; function fromLog(v) { return Math.pow(10, v); @@ -25620,7 +25935,7 @@ function fromLog(v) { * also clears the autorange bounds ._min and ._max * and the autotick constraints ._minDtick, ._forceTick0 */ -var _$setConvert_603 = function setConvert(ax, fullLayout) { +var _$setConvert_665 = function setConvert(ax, fullLayout) { fullLayout = fullLayout || {}; var axLetter = (ax._id || 'x').charAt(0); @@ -25641,7 +25956,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1)); } - else return __BADNUM_603; + else return __BADNUM_665; } /* @@ -25656,9 +25971,9 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { // 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_603) { - if(_$fastIsnumeric_139(v)) ms = dateTime2ms(new Date(+v)); - else return __BADNUM_603; + if(ms === __BADNUM_665) { + if(_$fastIsnumeric_196(v)) ms = dateTime2ms(new Date(+v)); + else return __BADNUM_665; } return ms; } @@ -25702,7 +26017,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { return curLength; } } - return __BADNUM_603; + return __BADNUM_665; } function getCategoryIndex(v) { @@ -25713,14 +26028,14 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { if(index !== undefined) return index; } - if(_$fastIsnumeric_139(v)) return +v; + if(_$fastIsnumeric_196(v)) return +v; } function l2p(v) { - if(!_$fastIsnumeric_139(v)) return __BADNUM_603; + if(!_$fastIsnumeric_196(v)) return __BADNUM_665; // include 2 fractional digits on pixel, for PDF zooming etc - return _$d3_127.round(ax._b + ax._m * v, 2); + return _$d3_130.round(ax._b + ax._m * v, 2); } function p2l(px) { return (px - ax._b) / ax._m; } @@ -25780,7 +26095,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { * 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_539.identity; + ax.d2r = ax.r2d = _$lib_601.identity; ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; @@ -25788,7 +26103,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { 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_539.cleanDate(v, __BADNUM_603, ax.calendar); }; + ax.cleanPos = function(v) { return _$lib_601.cleanDate(v, __BADNUM_665, ax.calendar); }; } else if(ax.type === 'category') { // d is categories (string) @@ -25845,47 +26160,47 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { if(!opts) opts = {}; if(!rangeAttr) rangeAttr = 'range'; - var range = _$lib_539.nestedProperty(ax, rangeAttr).get(); + var range = _$lib_601.nestedProperty(ax, rangeAttr).get(); var i, dflt; - if(ax.type === 'date') dflt = _$lib_539.dfltRange(ax.calendar); - else if(axLetter === 'y') dflt = _$constants_589.DFLTRANGEY; - else dflt = opts.dfltRange || _$constants_589.DFLTRANGEX; + if(ax.type === 'date') dflt = _$lib_601.dfltRange(ax.calendar); + else if(axLetter === 'y') dflt = _$constants_652.DFLTRANGEY; + else dflt = opts.dfltRange || _$constants_652.DFLTRANGEX; // make sure we don't later mutate the defaults dflt = dflt.slice(); if(!range || range.length !== 2) { - _$lib_539.nestedProperty(ax, rangeAttr).set(dflt); + _$lib_601.nestedProperty(ax, rangeAttr).set(dflt); return; } if(ax.type === 'date') { // check if milliseconds or js date objects are provided for range // and convert to date strings - range[0] = _$lib_539.cleanDate(range[0], __BADNUM_603, ax.calendar); - range[1] = _$lib_539.cleanDate(range[1], __BADNUM_603, ax.calendar); + range[0] = _$lib_601.cleanDate(range[0], __BADNUM_665, ax.calendar); + range[1] = _$lib_601.cleanDate(range[1], __BADNUM_665, ax.calendar); } for(i = 0; i < 2; i++) { if(ax.type === 'date') { - if(!_$lib_539.isDateTime(range[i], ax.calendar)) { + if(!_$lib_601.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_539.constrain(ax.r2l(range[0]), - _$lib_539.MIN_MS + 1000, _$lib_539.MAX_MS - 1000); + var linCenter = _$lib_601.constrain(ax.r2l(range[0]), + _$lib_601.MIN_MS + 1000, _$lib_601.MAX_MS - 1000); range[0] = ax.l2r(linCenter - 1000); range[1] = ax.l2r(linCenter + 1000); break; } } else { - if(!_$fastIsnumeric_139(range[i])) { - if(_$fastIsnumeric_139(range[1 - i])) { + if(!_$fastIsnumeric_196(range[i])) { + if(_$fastIsnumeric_196(range[1 - i])) { range[i] = range[1 - i] * (i ? 10 : 0.1); } else { @@ -25894,8 +26209,8 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { } } - if(range[i] < -__FP_SAFE_603) range[i] = -__FP_SAFE_603; - else if(range[i] > __FP_SAFE_603) range[i] = __FP_SAFE_603; + if(range[i] < -__FP_SAFE_665) range[i] = -__FP_SAFE_665; + else if(range[i] > __FP_SAFE_665) range[i] = __FP_SAFE_665; if(range[0] === range[1]) { // somewhat arbitrary: split by 1 or 1ppm, whichever is bigger @@ -25919,7 +26234,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { // make sure we have a domain (pull it in from the axis // this one is overlaying if necessary) if(ax.overlaying) { - var ax2 = _$axis_ids_587.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + var ax2 = _$axis_ids_650.getFromId({ _fullLayout: fullLayout }, ax.overlaying); ax.domain = ax2.domain; } @@ -25972,7 +26287,7 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { arrayIn = trace[axLetter]; len = trace._length || arrayIn.length; - if(_$lib_539.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { + if(_$lib_601.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) { if(len === arrayIn.length) { return arrayIn; } else if(arrayIn.subarray) { @@ -26006,18 +26321,22 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { return ( Array.isArray(range) && range.length === 2 && - _$fastIsnumeric_139(ax.r2l(range[0])) && - _$fastIsnumeric_139(ax.r2l(range[1])) + _$fastIsnumeric_196(ax.r2l(range[0])) && + _$fastIsnumeric_196(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]); - return ( - coord >= ax.r2l(ax.range[0]) && - coord <= ax.r2l(ax.range[1]) - ); + if(r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + // Reversed axis case. + return r1 <= coord && coord <= r0; + } }; ax.clearCalc = function() { @@ -26048,20 +26367,20 @@ var _$setConvert_603 = function setConvert(ax, fullLayout) { // 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_127.time.format.utc; + ax._dateFormat = locale ? locale.timeFormat.utc : _$d3_130.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_127.format; + ax._numFormat = locale ? locale.numberFormat : _$d3_130.format; // and for bar charts and box plots: reset forced minimum tick spacing delete ax._minDtick; delete ax._forceTick0; }; -var _$axes_584 = {}; +var _$axes_647 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -26073,47 +26392,47 @@ var _$axes_584 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$titles_504 = require('../../components/titles'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$titles_566 = require('../../components/titles'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var ONEAVGYEAR = _$numerical_517.ONEAVGYEAR; -var ONEAVGMONTH = _$numerical_517.ONEAVGMONTH; -var __ONEDAY_584 = _$numerical_517.ONEDAY; -var __ONEHOUR_584 = _$numerical_517.ONEHOUR; -var __ONEMIN_584 = _$numerical_517.ONEMIN; -var __ONESEC_584 = _$numerical_517.ONESEC; -var MINUS_SIGN = _$numerical_517.MINUS_SIGN; -var __BADNUM_584 = _$numerical_517.BADNUM; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var ONEAVGYEAR = _$numerical_578.ONEAVGYEAR; +var ONEAVGMONTH = _$numerical_578.ONEAVGMONTH; +var __ONEDAY_647 = _$numerical_578.ONEDAY; +var __ONEHOUR_647 = _$numerical_578.ONEHOUR; +var __ONEMIN_647 = _$numerical_578.ONEMIN; +var __ONESEC_647 = _$numerical_578.ONESEC; +var MINUS_SIGN = _$numerical_578.MINUS_SIGN; +var __BADNUM_647 = _$numerical_578.BADNUM; -var MID_SHIFT = _$alignment_511.MID_SHIFT; -var __LINE_SPACING_584 = _$alignment_511.LINE_SPACING; +var MID_SHIFT = _$alignment_573.MID_SHIFT; +var __LINE_SPACING_647 = _$alignment_573.LINE_SPACING; -var axes = _$axes_584 = {}; +var axes = _$axes_647 = {}; -axes.setConvert = _$setConvert_603; -/* removed: var _$autoType_585 = require('./axis_autotype'); */; +axes.setConvert = _$setConvert_665; +/* removed: var _$autoType_648 = require('./axis_autotype'); */; -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; -axes.id2name = _$axis_ids_587.id2name; -axes.name2id = _$axis_ids_587.name2id; -axes.cleanId = _$axis_ids_587.cleanId; -axes.list = _$axis_ids_587.list; -axes.listIds = _$axis_ids_587.listIds; -axes.getFromId = _$axis_ids_587.getFromId; -axes.getFromTrace = _$axis_ids_587.getFromTrace; +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; +axes.id2name = _$axis_ids_650.id2name; +axes.name2id = _$axis_ids_650.name2id; +axes.cleanId = _$axis_ids_650.cleanId; +axes.list = _$axis_ids_650.list; +axes.listIds = _$axis_ids_650.listIds; +axes.getFromId = _$axis_ids_650.getFromId; +axes.getFromTrace = _$axis_ids_650.getFromTrace; -/* removed: var _$autorange_583 = require('./autorange'); */; -axes.expand = _$autorange_583.expand; -axes.getAutoRange = _$autorange_583.getAutoRange; +/* removed: var _$autorange_646 = require('./autorange'); */; +axes.expand = _$autorange_646.expand; +axes.getAutoRange = _$autorange_646.getAutoRange; /* * find the list of possible axes to reference with an xref or yref attribute @@ -26144,7 +26463,7 @@ axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption }; // xref, yref - return _$lib_539.coerce(containerIn, containerOut, attrDef, refAttr); + return _$lib_601.coerce(containerIn, containerOut, attrDef, refAttr); }; /* @@ -26173,7 +26492,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { var cleanPos, pos; if(axRef === 'paper' || axRef === 'pixel') { - cleanPos = _$lib_539.ensureNumber; + cleanPos = _$lib_601.ensureNumber; pos = coerce(attr, dflt); } else { var ax = axes.getFromId(gd, axRef); @@ -26187,7 +26506,7 @@ axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) { axes.cleanPosition = function(pos, gd, axRef) { var cleanPos = (axRef === 'paper' || axRef === 'pixel') ? - _$lib_539.ensureNumber : + _$lib_601.ensureNumber : axes.getFromId(gd, axRef).cleanPos; return cleanPos(pos); @@ -26207,7 +26526,7 @@ var getDataConversions = axes.getDataConversions = function(gd, trace, target, t // setup the data-to-calc method. if(Array.isArray(d2cTarget)) { ax = { - type: _$autoType_585(targetArray), + type: _$autoType_648(targetArray), _categories: [] }; axes.setConvert(ax); @@ -26343,8 +26662,8 @@ axes.saveShowSpikeInitial = function(gd, overwrite) { }; axes.autoBin = function(data, ax, nbins, is2d, calendar) { - var dataMin = _$lib_539.aggNums(Math.min, null, data), - dataMax = _$lib_539.aggNums(Math.max, null, data); + var dataMin = _$lib_601.aggNums(Math.min, null, data), + dataMax = _$lib_601.aggNums(Math.max, null, data); if(!calendar) calendar = ax.calendar; @@ -26364,18 +26683,18 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { // 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_539.distinctVals(data), + var distinctData = _$lib_601.distinctVals(data), msexp = Math.pow(10, Math.floor( Math.log(distinctData.minDiff) / Math.LN10)), - minSize = msexp * _$lib_539.roundUp( + minSize = msexp * _$lib_601.roundUp( distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true); - size0 = Math.max(minSize, 2 * _$lib_539.stdev(data) / + size0 = Math.max(minSize, 2 * _$lib_601.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(!_$fastIsnumeric_139(size0)) size0 = 1; + if(!_$fastIsnumeric_196(size0)) size0 = 1; } // piggyback off autotick code to make "nice" bin sizes @@ -26389,7 +26708,7 @@ axes.autoBin = function(data, ax, nbins, is2d, calendar) { else { dummyAx = { type: ax.type, - range: _$lib_539.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + range: _$lib_601.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), calendar: calendar }; } @@ -26451,7 +26770,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { for(var i = 0; i < data.length; i++) { if(data[i] % 1 === 0) intcount++; - else if(!_$fastIsnumeric_139(data[i])) blankCount++; + else if(!_$fastIsnumeric_196(data[i])) blankCount++; if(nearEdge(data[i])) edgecount++; if(nearEdge(data[i] + ax.dtick / 2)) midcount++; @@ -26488,7 +26807,7 @@ function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { - var stats = _$lib_539.findExactDates(data, calendar); + var stats = _$lib_601.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; @@ -26500,21 +26819,21 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // 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_584 * 1.5; + binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + __ONEDAY_647 * 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_584 * 15.5; + binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + __ONEDAY_647 * 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_584 / 2; + binStart -= __ONEDAY_647 / 2; } var nextBinStart = axes.tickIncrement(binStart, dtick); @@ -26529,7 +26848,7 @@ function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) { // ensure we have tick0, dtick, and tick rounding calculated axes.prepTicks = function(ax) { - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); // calculate max number of (auto) ticks to display based on plot size if(ax.tickmode === 'auto' || !ax.dtick) { @@ -26542,7 +26861,7 @@ axes.prepTicks = function(ax) { } else { minPx = ax._id.charAt(0) === 'y' ? 40 : 80; - nt = _$lib_539.constrain(ax._length / minPx, 4, 9) + 1; + nt = _$lib_601.constrain(ax._length / minPx, 4, 9) + 1; } // radial axes span half their domain, @@ -26577,7 +26896,7 @@ axes.prepTicks = function(ax) { // or codes to this effect for log and date scales axes.calcTicks = function calcTicks(ax) { axes.prepTicks(ax); - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.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 @@ -26645,7 +26964,7 @@ function arrayTicks(ax) { var vals = ax.tickvals, text = ax.ticktext, ticksOut = new Array(vals.length), - rng = _$lib_539.simpleMap(ax.range, ax.r2l), + rng = _$lib_601.simpleMap(ax.range, ax.r2l), r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001, r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001, tickMin = Math.min(r0expanded, r1expanded), @@ -26694,7 +27013,7 @@ var roundBase10 = [2, 5, 10], roundAngles = [15, 30, 45, 90, 180]; function roundDTick(roughDTick, base, roundingSet) { - return base * _$lib_539.roundUp(roughDTick / base, roundingSet); + return base * _$lib_601.roundUp(roughDTick / base, roundingSet); } // autoTicks: calculate best guess at pleasant ticks for this axis @@ -26721,7 +27040,7 @@ axes.autoTicks = function(ax, roughDTick) { } if(ax.type === 'date') { - ax.tick0 = _$lib_539.dateTick0(ax.calendar); + ax.tick0 = _$lib_601.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; @@ -26735,21 +27054,21 @@ axes.autoTicks = function(ax, roughDTick) { roughDTick /= ONEAVGMONTH; ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24); } - else if(roughX2 > __ONEDAY_584) { - ax.dtick = roundDTick(roughDTick, __ONEDAY_584, roundDays); + else if(roughX2 > __ONEDAY_647) { + ax.dtick = roundDTick(roughDTick, __ONEDAY_647, 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_539.dateTick0(ax.calendar, true); + ax.tick0 = _$lib_601.dateTick0(ax.calendar, true); } - else if(roughX2 > __ONEHOUR_584) { - ax.dtick = roundDTick(roughDTick, __ONEHOUR_584, roundBase24); + else if(roughX2 > __ONEHOUR_647) { + ax.dtick = roundDTick(roughDTick, __ONEHOUR_647, roundBase24); } - else if(roughX2 > __ONEMIN_584) { - ax.dtick = roundDTick(roughDTick, __ONEMIN_584, roundBase60); + else if(roughX2 > __ONEMIN_647) { + ax.dtick = roundDTick(roughDTick, __ONEMIN_647, roundBase60); } - else if(roughX2 > __ONESEC_584) { - ax.dtick = roundDTick(roughDTick, __ONESEC_584, roundBase60); + else if(roughX2 > __ONESEC_647) { + ax.dtick = roundDTick(roughDTick, __ONESEC_647, roundBase60); } else { // milliseconds @@ -26759,7 +27078,7 @@ axes.autoTicks = function(ax, roughDTick) { } else if(ax.type === 'log') { ax.tick0 = 0; - var rng = _$lib_539.simpleMap(ax.range, ax.r2l); + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); if(roughDTick > 0.7) { // only show powers of 10 @@ -26802,7 +27121,7 @@ axes.autoTicks = function(ax, roughDTick) { if(ax.dtick === 0) ax.dtick = 1; // TODO: this is from log axis histograms with autorange off - if(!_$fastIsnumeric_139(ax.dtick) && typeof ax.dtick !== 'string') { + if(!_$fastIsnumeric_196(ax.dtick) && typeof ax.dtick !== 'string') { var olddtick = ax.dtick; ax.dtick = 1; throw 'ax.dtick error: ' + String(olddtick); @@ -26818,7 +27137,7 @@ function autoTickRound(ax) { var dtick = ax.dtick; ax._tickexponent = 0; - if(!_$fastIsnumeric_139(dtick) && typeof dtick !== 'string') { + if(!_$fastIsnumeric_196(dtick) && typeof dtick !== 'string') { dtick = 1; } @@ -26840,9 +27159,9 @@ function autoTickRound(ax) { // 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_584 && tick0len <= 10) || (dtick >= __ONEDAY_584 * 15)) ax._tickround = 'd'; - else if((dtick >= __ONEMIN_584 && tick0len <= 16) || (dtick >= __ONEHOUR_584)) ax._tickround = 'M'; - else if((dtick >= __ONESEC_584 && tick0len <= 19) || (dtick >= __ONEMIN_584)) ax._tickround = 'S'; + else if((dtick >= __ONEDAY_647 && tick0len <= 10) || (dtick >= __ONEDAY_647 * 15)) ax._tickround = 'd'; + else if((dtick >= __ONEMIN_647 && tick0len <= 16) || (dtick >= __ONEHOUR_647)) ax._tickround = 'M'; + else if((dtick >= __ONESEC_647 && tick0len <= 19) || (dtick >= __ONEMIN_647)) 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 @@ -26851,10 +27170,10 @@ function autoTickRound(ax) { ax._tickround = Math.max(tick0len, tick1len) - 20; } } - else if(_$fastIsnumeric_139(dtick) || dtick.charAt(0) === 'L') { + else if(_$fastIsnumeric_196(dtick) || dtick.charAt(0) === 'L') { // linear or log (except D1, D2) var rng = ax.range.map(ax.r2d || Number); - if(!_$fastIsnumeric_139(dtick)) dtick = Number(dtick.substr(1)); + if(!_$fastIsnumeric_196(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); @@ -26882,14 +27201,14 @@ 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(_$fastIsnumeric_139(dtick)) return x + axSign * dtick; + if(_$fastIsnumeric_196(dtick)) return x + axSign * dtick; // everything else is a string, one character plus a number var tType = dtick.charAt(0), dtSigned = axSign * Number(dtick.substr(1)); // Dates: months (or years - see Lib.incrementMonth) - if(tType === 'M') return _$lib_539.incrementMonth(x, dtSigned, calendar); + if(tType === 'M') return _$lib_601.incrementMonth(x, dtSigned, calendar); // Log scales: Linear, Digits else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; @@ -26899,10 +27218,10 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, x2 = x + axSign * 0.01, - frac = _$lib_539.roundUp(_$lib_539.mod(x2, 1), tickset, axrev); + frac = _$lib_601.roundUp(_$lib_601.mod(x2, 1), tickset, axrev); return Math.floor(x2) + - Math.log(_$d3_127.round(Math.pow(10, frac), 1)) / Math.LN10; + Math.log(_$d3_130.round(Math.pow(10, frac), 1)) / Math.LN10; } else throw 'unrecognized dtick ' + String(dtick); }; @@ -26910,7 +27229,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) { // calculate the first tick on an axis axes.tickFirst = function(ax) { var r2l = ax.r2l || Number, - rng = _$lib_539.simpleMap(ax.range, r2l), + rng = _$lib_601.simpleMap(ax.range, r2l), axrev = rng[1] < rng[0], sRound = axrev ? Math.floor : Math.ceil, // add a tiny extra bit to make sure we get ticks @@ -26919,12 +27238,12 @@ axes.tickFirst = function(ax) { dtick = ax.dtick, tick0 = r2l(ax.tick0); - if(_$fastIsnumeric_139(dtick)) { + if(_$fastIsnumeric_196(dtick)) { var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0; // make sure no ticks outside the category list if(ax.type === 'category') { - tmin = _$lib_539.constrain(tmin, 0, ax._categories.length - 1); + tmin = _$lib_601.constrain(tmin, 0, ax._categories.length - 1); } return tmin; } @@ -26954,7 +27273,7 @@ axes.tickFirst = function(ax) { t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); cnt++; } - _$lib_539.error('tickFirst did not converge', ax); + _$lib_601.error('tickFirst did not converge', ax); return t0; } @@ -26965,10 +27284,10 @@ axes.tickFirst = function(ax) { } else if(tType === 'D') { var tickset = (dtick === 'D2') ? roundLog2 : roundLog1, - frac = _$lib_539.roundUp(_$lib_539.mod(r0, 1), tickset, axrev); + frac = _$lib_601.roundUp(_$lib_601.mod(r0, 1), tickset, axrev); return Math.floor(r0) + - Math.log(_$d3_127.round(Math.pow(10, frac), 1)) / Math.LN10; + Math.log(_$d3_130.round(Math.pow(10, frac), 1)) / Math.LN10; } else throw 'unrecognized dtick ' + String(dtick); }; @@ -26988,7 +27307,7 @@ axes.tickText = function(ax, x, hover) { tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l; if(arrayMode && Array.isArray(ax.ticktext)) { - var rng = _$lib_539.simpleMap(ax.range, ax.r2l), + var rng = _$lib_601.simpleMap(ax.range, ax.r2l), 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; @@ -27045,7 +27364,7 @@ axes.tickText = function(ax, x, hover) { * it's different from `val`. */ axes.hoverLabelText = function(ax, val, val2) { - if(val2 !== __BADNUM_584 && val2 !== val) { + if(val2 !== __BADNUM_647 && val2 !== val) { return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2); } @@ -27084,11 +27403,11 @@ function formatDate(ax, out, hover, extraPrecision) { if(extraPrecision) { // second or sub-second precision: extra always shows max digits. // for other fields, extra precision just adds one field. - if(_$fastIsnumeric_139(tr)) tr = 4; + if(_$fastIsnumeric_196(tr)) tr = 4; else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr]; } - var dateStr = _$lib_539.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), + var dateStr = _$lib_601.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat), headStr; var splitIndex = dateStr.indexOf('\n'); @@ -27153,7 +27472,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) { out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); } - else if(_$fastIsnumeric_139(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_539.mod(x + 0.01, 1) < 0.1))) { + else if(_$fastIsnumeric_196(dtick) || ((dtick.charAt(0) === 'D') && (_$lib_601.mod(x + 0.01, 1) < 0.1))) { var p = Math.round(x); if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 || (isSIFormat(ax.exponentformat) && beyondSI(p))) { @@ -27172,7 +27491,7 @@ function formatLog(ax, out, hover, extraPrecision, hideexp) { } } else if(dtick.charAt(0) === 'D') { - out.text = String(Math.round(Math.pow(10, _$lib_539.mod(x, 1)))); + out.text = String(Math.round(Math.pow(10, _$lib_601.mod(x, 1)))); out.fontSize *= 0.75; } else throw 'unrecognized dtick ' + String(dtick); @@ -27227,7 +27546,7 @@ function formatAngle(ax, out, hover, extraPrecision, hideexp) { var frac = num2frac(num); if(frac[1] >= 100) { - out.text = numFormat(_$lib_539.deg2rad(out.x), ax, hideexp, extraPrecision); + out.text = numFormat(_$lib_601.deg2rad(out.x), ax, hideexp, extraPrecision); } else { var isNeg = out.x < 0; @@ -27320,7 +27639,7 @@ function numFormat(v, ax, fmtoverride, hover) { var ah = { exponentformat: exponentFormat, dtick: ax.showexponent === 'none' ? ax.dtick : - (_$fastIsnumeric_139(v) ? Math.abs(v) || 1 : 1), + (_$fastIsnumeric_196(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] @@ -27375,7 +27694,7 @@ function numFormat(v, ax, fmtoverride, hover) { if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ''); } // insert appropriate decimal point and thousands separator - v = _$lib_539.numSeparate(v, ax._separators, separatethousands); + v = _$lib_601.numSeparate(v, ax._separators, separatethousands); } // add exponent @@ -27549,7 +27868,7 @@ axes.makeClipPaths = function(gd) { axClips.exit().remove(); axClips.each(function(d) { - _$d3_127.select(this).select('rect').attr({ + _$d3_130.select(this).select('rect').attr({ x: d.x._offset || 0, y: d.y._offset || 0, width: d.x._length || 1, @@ -27566,9 +27885,9 @@ axes.makeClipPaths = function(gd) { // ax._rl (stored linearized range for use by zoom/pan) // or can pass in an axis object directly axes.doTicks = function(gd, axid, skipTitle) { - var fullLayout = gd._fullLayout, - ax, - independent = false; + var fullLayout = gd._fullLayout; + var ax; + var independent = false; // allow passing an independent axis object instead of id if(typeof axid === 'object') { @@ -27581,32 +27900,26 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'redraw') { fullLayout._paper.selectAll('g.subplot').each(function(subplot) { - var plotinfo = fullLayout._plots[subplot], - xa = plotinfo.xaxis, - ya = plotinfo.yaxis; - - plotinfo.xaxislayer - .selectAll('.' + xa._id + 'tick').remove(); - plotinfo.yaxislayer - .selectAll('.' + ya._id + 'tick').remove(); - plotinfo.gridlayer - .selectAll('path').remove(); - plotinfo.zerolinelayer - .selectAll('path').remove(); + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + + plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove(); + plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').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(); }); } if(!axid || axid === 'redraw') { - return _$lib_539.syncOrAsync(axes.list(gd, '', true).map(function(ax) { + return _$lib_601.syncOrAsync(axes.list(gd, '', true).map(function(ax) { return function() { if(!ax._id) return; var axDone = axes.doTicks(gd, ax._id); - if(axid === 'redraw') { - ax._r = ax.range.slice(); - ax._rl = _$lib_539.simpleMap(ax._r, ax.r2l); - } + ax._r = ax.range.slice(); + ax._rl = _$lib_601.simpleMap(ax._r, ax.r2l); return axDone; }; })); @@ -27616,21 +27929,22 @@ axes.doTicks = function(gd, axid, skipTitle) { // set scaling to pixels ax.setScale(); - var axLetter = axid.charAt(0), - counterLetter = axes.counterLetter(axid), - vals = axes.calcTicks(ax), - datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }, - tcls = axid + 'tick', - gcls = axid + 'grid', - zcls = axid + 'zl', - pad = (ax.linewidth || 1) / 2, - labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0), - labelShift = 0, - gridWidth = _$drawing_436.crispRound(gd, ax.gridwidth, 1), - zeroLineWidth = _$drawing_436.crispRound(gd, ax.zerolinewidth, gridWidth), - tickWidth = _$drawing_436.crispRound(gd, ax.tickwidth, 1), - sides, transfn, tickpathfn, subplots, - i; + var axLetter = axid.charAt(0); + var counterLetter = axes.counterLetter(axid); + var vals = ax._vals = axes.calcTicks(ax); + var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); }; + var tcls = axid + 'tick'; + var gcls = axid + 'grid'; + var zcls = axid + 'zl'; + var pad = (ax.linewidth || 1) / 2; + var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0); + var labelShift = 0; + var gridWidth = _$drawing_498.crispRound(gd, ax.gridwidth, 1); + var zeroLineWidth = _$drawing_498.crispRound(gd, ax.zerolinewidth, gridWidth); + var tickWidth = _$drawing_498.crispRound(gd, ax.tickwidth, 1); + var sides, transfn, tickpathfn, subplots; + var tickLabels; + var i; if(ax._counterangle && ax.ticks === 'outside') { var caRad = ax._counterangle * Math.PI / 180; @@ -27677,13 +27991,14 @@ axes.doTicks = function(gd, axid, skipTitle) { }; } else { - _$lib_539.warn('Unrecognized doTicks axis:', axid); + _$lib_601.warn('Unrecognized doTicks axis:', axid); return; } - var axside = ax.side || sides[0], + + var axside = ax.side || sides[0]; // which direction do the side[0], side[1], and free ticks go? // then we flip if outside XOR y axis - ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; + var ticksign = [-1, 1, axside === sides[1] ? 1 : -1]; if((ax.ticks !== 'inside') === (axLetter === 'x')) { ticksign = ticksign.map(function(v) { return -v; }); } @@ -27711,10 +28026,11 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawTicks(container, tickpath) { var ticks = container.selectAll('path.' + tcls) .data(ax.ticks === 'inside' ? valsClipped : vals, datafn); + if(tickpath && ax.ticks) { ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1) .classed('crisp', 1) - .call(_$color_411.stroke, ax.tickcolor) + .call(_$color_473.stroke, ax.tickcolor) .style('stroke-width', tickWidth + 'px') .attr('d', tickpath); ticks.attr('transform', transfn); @@ -27726,9 +28042,9 @@ axes.doTicks = function(gd, axid, skipTitle) { function drawLabels(container, position) { // tick labels - for now just the main labels. // TODO: mirror labels, esp for subplots - var tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); + tickLabels = container.selectAll('g.' + tcls).data(vals, datafn); - if(!_$fastIsnumeric_139(position)) { + if(!_$fastIsnumeric_196(position)) { tickLabels.remove(); drawAxTitle(); return; @@ -27750,7 +28066,7 @@ axes.doTicks = function(gd, axid, skipTitle) { ((axside === 'bottom') ? 1 : -0.2); }; labelanchor = function(angle) { - if(!_$fastIsnumeric_139(angle) || angle === 0 || angle === 180) { + if(!_$fastIsnumeric_196(angle) || angle === 0 || angle === 180) { return 'middle'; } return (angle * flipit < 0) ? 'end' : 'start'; @@ -27766,7 +28082,7 @@ axes.doTicks = function(gd, axid, skipTitle) { ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit; }; labelanchor = function(angle) { - if(_$fastIsnumeric_139(angle) && Math.abs(angle) === 90) { + if(_$fastIsnumeric_196(angle) && Math.abs(angle) === 90) { return 'middle'; } return axside === 'right' ? 'start' : 'end'; @@ -27791,13 +28107,13 @@ axes.doTicks = function(gd, axid, skipTitle) { // alter later .attr('text-anchor', 'middle') .each(function(d) { - var thisLabel = _$d3_127.select(this), + var thisLabel = _$d3_130.select(this), newPromise = gd._promises.length; thisLabel - .call(_$svg_text_utils_562.positionText, labelx(d), labely(d)) - .call(_$drawing_436.font, d.font, d.fontSize, d.fontColor) + .call(_$svg_text_utils_625.positionText, labelx(d), labely(d)) + .call(_$drawing_498.font, d.font, d.fontSize, d.fontColor) .text(d.text) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); newPromise = gd._promises[newPromise]; if(newPromise) { // if we have an async label, we'll deal with that @@ -27821,8 +28137,8 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axid === 'angular') { tickLabels.each(function(d) { - _$d3_127.select(this).select('text') - .call(_$svg_text_utils_562.positionText, labelx(d), labely(d)); + _$d3_130.select(this).select('text') + .call(_$svg_text_utils_625.positionText, labelx(d), labely(d)); }); } @@ -27849,17 +28165,17 @@ axes.doTicks = function(gd, axid, skipTitle) { function positionLabels(s, angle) { s.each(function(d) { var anchor = labelanchor(angle, d); - var thisLabel = _$d3_127.select(this), + var thisLabel = _$d3_130.select(this), mathjaxGroup = thisLabel.select('.text-math-group'), transform = transfn.call(thisLabel.node(), d) + - ((_$fastIsnumeric_139(angle) && +angle !== 0) ? + ((_$fastIsnumeric_196(angle) && +angle !== 0) ? (' rotate(' + angle + ',' + labelx(d) + ',' + (labely(d) - d.fontSize / 2) + ')') : ''); var anchorHeight = getAnchorHeight( - _$svg_text_utils_562.lineCount(thisLabel), - __LINE_SPACING_584 * d.fontSize, - _$fastIsnumeric_139(angle) ? +angle : 0); + _$svg_text_utils_625.lineCount(thisLabel), + __LINE_SPACING_647 * d.fontSize, + _$fastIsnumeric_196(angle) ? +angle : 0); if(anchorHeight) { transform += ' translate(0, ' + anchorHeight + ')'; } @@ -27871,7 +28187,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } else { var mjShift = - _$drawing_436.bBox(mathjaxGroup.node()).width * + _$drawing_498.bBox(mathjaxGroup.node()).width * {end: -0.5, start: 0.5}[anchor]; mathjaxGroup.attr('transform', transform + (mjShift ? 'translate(' + mjShift + ',0)' : '')); @@ -27896,16 +28212,16 @@ axes.doTicks = function(gd, axid, skipTitle) { // check for auto-angling if x labels overlap // don't auto-angle at all for log axes with // base and digit format - if(axLetter === 'x' && !_$fastIsnumeric_139(ax.tickangle) && + if(axLetter === 'x' && !_$fastIsnumeric_196(ax.tickangle) && (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) { var lbbArray = []; tickLabels.each(function(d) { - var s = _$d3_127.select(this), + var s = _$d3_130.select(this), thisLabel = s.select('.text-math-group'), x = ax.l2p(d.x); if(thisLabel.empty()) thisLabel = s.select('text'); - var bb = _$drawing_436.bBox(thisLabel.node()); + var bb = _$drawing_498.bBox(thisLabel.node()); lbbArray.push({ // ignore about y, just deal with x overlaps @@ -27919,7 +28235,7 @@ axes.doTicks = function(gd, axid, skipTitle) { }); }); for(i = 0; i < lbbArray.length - 1; i++) { - if(_$lib_539.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { + if(_$lib_601.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) { // any overlap at all - set 30 degrees autoangle = 30; break; @@ -28057,11 +28373,11 @@ axes.doTicks = function(gd, axid, skipTitle) { var pushKey = ax._name + '.automargin'; var prevPush = fullLayout._pushmargin[pushKey]; if(!prevPush || prevPush[s].size < push[s]) { - _$plots_647.autoMargin(gd, pushKey, push); + _$plots_709.autoMargin(gd, pushKey, push); } } - var done = _$lib_539.syncOrAsync([ + var done = _$lib_601.syncOrAsync([ allLabelsReady, fixLabelOverlaps, calcBoundingBox, @@ -28077,14 +28393,12 @@ axes.doTicks = function(gd, axid, skipTitle) { // now this only applies to regular cartesian axes; colorbars and // others ALWAYS call doTicks with skipTitle=true so they can // configure their own titles. - var ax = _$axis_ids_587.getFromId(gd, axid); // rangeslider takes over a bottom title so drop it here if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return; - var avoidSelection = _$d3_127.select(gd).selectAll('g.' + axid + 'tick'); var avoid = { - selection: avoidSelection, + selection: tickLabels, side: ax.side }; var axLetter = axid.charAt(0); @@ -28094,8 +28408,8 @@ axes.doTicks = function(gd, axid, skipTitle) { var transform, counterAxis, x, y; - if(avoidSelection.size()) { - var translation = _$drawing_436.getTranslate(avoidSelection.node().parentNode); + if(tickLabels.size()) { + var translation = _$drawing_498.getTranslate(tickLabels.node().parentNode); avoid.offsetLeft = translation.x; avoid.offsetTop = translation.y; } @@ -28106,7 +28420,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(axLetter === 'x') { counterAxis = (ax.anchor === 'free') ? {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} : - _$axis_ids_587.getFromId(gd, ax.anchor); + _$axis_ids_650.getFromId(gd, ax.anchor); x = ax._offset + ax._length / 2; @@ -28124,7 +28438,7 @@ axes.doTicks = function(gd, axid, skipTitle) { else { counterAxis = (ax.anchor === 'free') ? {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} : - _$axis_ids_587.getFromId(gd, ax.anchor); + _$axis_ids_650.getFromId(gd, ax.anchor); y = ax._offset + ax._length / 2; if(ax.side === 'right') { @@ -28140,7 +28454,7 @@ axes.doTicks = function(gd, axid, skipTitle) { if(!avoid.side) avoid.side = 'left'; } - _$titles_504.draw(gd, axid + 'title', { + _$titles_566.draw(gd, axid + 'title', { propContainer: ax, propName: ax._name + '.title', placeholder: fullLayout._dfltTitle[axLetter], @@ -28152,11 +28466,13 @@ axes.doTicks = function(gd, axid, skipTitle) { function traceHasBarsOrFill(trace, subplot) { if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false; - if(_$registry_668.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; + if(_$registry_731.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true; return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter; } function drawGrid(plotinfo, counteraxis, subplot) { + if(fullLayout._hasOnlyLargeSploms) return; + var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid); var zlcontainer = plotinfo.zerolinelayer; var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped; @@ -28172,11 +28488,11 @@ axes.doTicks = function(gd, axid, skipTitle) { .each(function(d) { if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') && Math.abs(d.x) < ax.dtick / 100) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); } }); grid.attr('transform', transfn) - .call(_$color_411.stroke, ax.gridcolor || '#ddd') + .call(_$color_473.stroke, ax.gridcolor || '#ddd') .style('stroke-width', gridWidth + 'px'); if(typeof gridpath === 'function') grid.attr('d', gridpath); grid.exit().remove(); @@ -28190,7 +28506,7 @@ axes.doTicks = function(gd, axid, skipTitle) { break; } } - var rng = _$lib_539.simpleMap(ax.range, ax.r2l), + var rng = _$lib_601.simpleMap(ax.range, ax.r2l), showZl = (rng[0] * rng[1] <= 0) && ax.zeroline && (ax.type === 'linear' || ax.type === '-') && gridvals.length && (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline); @@ -28204,11 +28520,11 @@ axes.doTicks = function(gd, axid, skipTitle) { // If several zerolines enter at the same time we will sort once per, // but generally this should be a minimal overhead. zlcontainer.selectAll('path').sort(function(da, db) { - return _$axis_ids_587.idSort(da.id, db.id); + return _$axis_ids_650.idSort(da.id, db.id); }); }); zl.attr('transform', transfn) - .call(_$color_411.stroke, ax.zerolinecolor || _$color_411.defaultLine) + .call(_$color_473.stroke, ax.zerolinecolor || _$color_473.defaultLine) .style('stroke-width', zeroLineWidth + 'px'); zl.exit().remove(); } @@ -28255,7 +28571,7 @@ axes.doTicks = function(gd, axid, skipTitle) { } drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath); - tickSubplots = Object.keys(ax._linepositions); + tickSubplots = Object.keys(ax._linepositions || {}); } tickSubplots.map(function(subplot) { @@ -28394,7 +28710,7 @@ function swapAxisGroup(gd, xIds, yIds) { var ann = gd._fullLayout.annotations[i]; if(xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { - _$lib_539.swapAttrs(layout.annotations[i], ['?']); + _$lib_601.swapAttrs(layout.annotations[i], ['?']); } } } @@ -28403,7 +28719,7 @@ 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_539.nestedProperty, + var np = _$lib_601.nestedProperty, xVal = np(layout[xFullAxes[0]._name], key).get(), yVal = np(layout[yFullAxes[0]._name], key).get(), i; @@ -28425,7 +28741,7 @@ function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) { } } -var _$helpers_965 = {}; +var _$helpers_1036 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -28436,7 +28752,7 @@ var _$helpers_965 = {}; 'use strict'; -_$helpers_965.pointsAccessorFunction = function(transforms, opts) { +_$helpers_1036.pointsAccessorFunction = function(transforms, opts) { var tr; var prevIndexToPoints; for(var i = 0; i < transforms.length; i++) { @@ -28451,7 +28767,7 @@ _$helpers_965.pointsAccessorFunction = function(transforms, opts) { return originalPointsAccessor; }; -var _$aggregate_962 = {}; +var _$aggregate_1033 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -28462,17 +28778,17 @@ var _$aggregate_962 = {}; 'use strict'; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plot_schema_575 = require('../plot_api/plot_schema'); */; -var pointsAccessorFunction = _$helpers_965.pointsAccessorFunction; -var __BADNUM_962 = _$numerical_517.BADNUM; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plot_schema_638 = require('../plot_api/plot_schema'); */; +var pointsAccessorFunction = _$helpers_1036.pointsAccessorFunction; +var __BADNUM_1033 = _$numerical_578.BADNUM; -_$aggregate_962.moduleType = 'transform'; +_$aggregate_1033.moduleType = 'transform'; -_$aggregate_962.name = 'aggregate'; +_$aggregate_1033.name = 'aggregate'; -var attrs = _$aggregate_962.attributes = { +var attrs = _$aggregate_1033.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -28545,12 +28861,12 @@ var aggAttrs = attrs.aggregations; * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$aggregate_962.supplyDefaults = function(transformIn, traceOut) { +_$aggregate_1033.supplyDefaults = function(transformIn, traceOut) { var transformOut = {}; var i; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, attrs, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, attrs, attr, dflt); } var enabled = coerce('enabled'); @@ -28567,7 +28883,7 @@ _$aggregate_962.supplyDefaults = function(transformIn, traceOut) { * as distinct from undefined which means this array isn't present in the input * missing arrays can still be aggregate outputs for *count* aggregations. */ - var arrayAttrArray = _$plot_schema_575.findArrayAttributes(traceOut); + var arrayAttrArray = _$plot_schema_638.findArrayAttributes(traceOut); var arrayAttrs = {}; for(i = 0; i < arrayAttrArray.length; i++) arrayAttrs[arrayAttrArray[i]] = 1; @@ -28586,7 +28902,7 @@ _$aggregate_962.supplyDefaults = function(transformIn, traceOut) { var aggregationOut; function coercei(attr, dflt) { - return _$lib_539.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt); + return _$lib_601.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt); } for(i = 0; i < aggregationsIn.length; i++) { @@ -28622,12 +28938,12 @@ _$aggregate_962.supplyDefaults = function(transformIn, traceOut) { }; -_$aggregate_962.calcTransform = function(gd, trace, opts) { +_$aggregate_1033.calcTransform = function(gd, trace, opts) { if(!opts.enabled) return; var groups = opts.groups; - var groupArray = _$lib_539.getTargetArray(trace, {target: groups}); + var groupArray = _$lib_601.getTargetArray(trace, {target: groups}); if(!groupArray) return; var i, vi, groupIndex, newGrouping; @@ -28674,9 +28990,9 @@ function aggregateOneArray(gd, trace, groupings, aggregation) { if(!aggregation.enabled) return; var attr = aggregation.target; - var targetNP = _$lib_539.nestedProperty(trace, attr); + var targetNP = _$lib_601.nestedProperty(trace, attr); var arrayIn = targetNP.get(); - var conversions = _$axes_584.getDataConversions(gd, trace, attr, arrayIn); + var conversions = _$axes_647.getDataConversions(gd, trace, attr, arrayIn); var func = getAggregateFunction(aggregation, conversions); var arrayOut = new Array(groupings.length); @@ -28708,7 +29024,7 @@ function getAggregateFunction(opts, conversions) { var total = 0; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) total += vi; + if(vi !== __BADNUM_1033) total += vi; } return c2d(total); }; @@ -28720,12 +29036,12 @@ function getAggregateFunction(opts, conversions) { var cnt = 0; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { total += vi; cnt++; } } - return cnt ? c2d(total / cnt) : __BADNUM_962; + return cnt ? c2d(total / cnt) : __BADNUM_1033; }; case 'min': @@ -28733,9 +29049,9 @@ function getAggregateFunction(opts, conversions) { var out = Infinity; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) out = Math.min(out, vi); + if(vi !== __BADNUM_1033) out = Math.min(out, vi); } - return (out === Infinity) ? __BADNUM_962 : c2d(out); + return (out === Infinity) ? __BADNUM_1033 : c2d(out); }; case 'max': @@ -28743,9 +29059,9 @@ function getAggregateFunction(opts, conversions) { var out = -Infinity; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) out = Math.max(out, vi); + if(vi !== __BADNUM_1033) out = Math.max(out, vi); } - return (out === -Infinity) ? __BADNUM_962 : c2d(out); + return (out === -Infinity) ? __BADNUM_1033 : c2d(out); }; case 'median': @@ -28753,9 +29069,9 @@ function getAggregateFunction(opts, conversions) { var sortCalc = []; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) sortCalc.push(vi); + if(vi !== __BADNUM_1033) sortCalc.push(vi); } - if(!sortCalc.length) return __BADNUM_962; + if(!sortCalc.length) return __BADNUM_1033; sortCalc.sort(); var mid = (sortCalc.length - 1) / 2; return c2d((sortCalc[Math.floor(mid)] + sortCalc[Math.ceil(mid)]) / 2); @@ -28765,10 +29081,10 @@ function getAggregateFunction(opts, conversions) { return function(array, indices) { var counts = {}; var maxCnt = 0; - var out = __BADNUM_962; + var out = __BADNUM_1033; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { var counti = counts[vi] = (counts[vi] || 0) + 1; if(counti > maxCnt) { maxCnt = counti; @@ -28776,7 +29092,7 @@ function getAggregateFunction(opts, conversions) { } } } - return maxCnt ? c2d(out) : __BADNUM_962; + return maxCnt ? c2d(out) : __BADNUM_1033; }; case 'rms': @@ -28785,12 +29101,12 @@ function getAggregateFunction(opts, conversions) { var cnt = 0; for(var i = 0; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { total += vi * vi; cnt++; } } - return cnt ? c2d(Math.sqrt(total / cnt)) : __BADNUM_962; + return cnt ? c2d(Math.sqrt(total / cnt)) : __BADNUM_1033; }; case 'stddev': @@ -28801,16 +29117,16 @@ function getAggregateFunction(opts, conversions) { var total = 0; var total2 = 0; var cnt = 1; - var v0 = __BADNUM_962; + var v0 = __BADNUM_1033; var i; - for(i = 0; i < indices.length && v0 === __BADNUM_962; i++) { + for(i = 0; i < indices.length && v0 === __BADNUM_1033; i++) { v0 = d2c(array[indices[i]]); } - if(v0 === __BADNUM_962) return __BADNUM_962; + if(v0 === __BADNUM_1033) return __BADNUM_1033; for(; i < indices.length; i++) { var vi = d2c(array[indices[i]]); - if(vi !== __BADNUM_962) { + if(vi !== __BADNUM_1033) { var dv = vi - v0; total += dv; total2 += dv * dv; @@ -28855,7 +29171,7 @@ function last(array, indices) { 'use strict'; -var _$aggregate_3 = _$aggregate_962; +var _$aggregate_3 = _$aggregate_1033; /** * Copyright 2012-2018, Plotly, Inc. @@ -28868,7 +29184,7 @@ var _$aggregate_3 = _$aggregate_962; 'use strict'; -var _$attributes_582 = { +var _$attributes_645 = { xaxis: { valType: 'subplotid', @@ -28885,6 +29201,75 @@ var _$attributes_582 = { } }; +var _$client_303 = true; +var _$hasHover_296 = {}; +(function (global){ +'use strict' + +/* removed: var _$client_303 = require('is-browser') */; +var hasHover + +if (typeof global.matchMedia === 'function') { + hasHover = !global.matchMedia('(hover: none)').matches +} +else { + hasHover = _$client_303 +} + +_$hasHover_296 = hasHover + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + +/* removed: var _$client_303 = require('is-browser') */; + +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 +} + +var _$hasPassiveEvents_297 = _$client_303 && detect() + +var rootPosition = { left: 0, top: 0 } + +var _$mouseEventOffset_321 = mouseEventOffset +function mouseEventOffset (ev, target, out) { + target = target || ev.currentTarget || ev.srcElement + if (!Array.isArray(out)) { + out = [ 0, 0 ] + } + var cx = ev.clientX || 0 + var cy = ev.clientY || 0 + var rect = getBoundingClientOffset(target) + out[0] = cx - rect.left + out[1] = cy - rect.top + return out +} + +function getBoundingClientOffset (element) { + if (element === window || + element === document || + element === document.body) { + return rootPosition + } else { + return element.getBoundingClientRect() + } +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -28893,29 +29278,28 @@ var _$attributes_582 = { * LICENSE file in the root directory of this source tree. */ -'use strict'; - - -var _$handleCategoryOrderDefaults_588 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce) { - if(containerOut.type !== 'category') return; - - var arrayIn = containerIn.categoryarray, - orderDefault; - var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); +'use strict'; - // override default 'categoryorder' value when non-empty array is supplied - if(isValidArray) orderDefault = 'array'; - var order = coerce('categoryorder', orderDefault); +// 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 +var _$align_493 = function align(v, dv, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0), + vmax = vmin + dv / (v1 - v0), + vc = (vmin + vmax) / 2; - // coerce 'categoryarray' only in array order case - if(order === 'array') coerce('categoryarray'); + // explicitly specified anchor + if(anchor === 'left' || anchor === 'bottom') return vmin; + if(anchor === 'center' || anchor === 'middle') return vc; + if(anchor === 'right' || anchor === 'top') return vmax; - // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' - if(!isValidArray && order === 'array') { - containerOut.categoryorder = 'trace'; - } + // automatic based on position + if(vmin < (2 / 3) - vc) return vmin; + if(vmax > (4 / 3) - vc) return vmax; + return vc; }; /** @@ -28926,60 +29310,33 @@ var _$handleCategoryOrderDefaults_588 = function handleCategoryOrderDefaults(con * LICENSE file in the root directory of this source tree. */ -'use strict'; - -var colorMix = _$tinycolor_352.mix; -var lightFraction = _$attributes_410.lightFraction; -/* removed: var _$lib_539 = require('../../lib'); */; - -/** - * @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 - */ -var _$handleLineGridDefaults_598 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { - opts = opts || {}; - - var dfltColor = opts.dfltColor; - function coerce2(attr, dflt) { - return _$lib_539.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); - } +'use strict'; - var lineColor = coerce2('linecolor', dfltColor); - var lineWidth = coerce2('linewidth'); - var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth); +/* removed: var _$lib_601 = require('../../lib'); */; - 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); +// 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'] +]; - if(!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } +var _$getCursor_494 = 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_601.constrain(Math.floor(x * 3), 0, 2); - if(!opts.noZeroLine) { - var zeroLineColor = coerce2('zerolinecolor', dfltColor); - var zeroLineWidth = coerce2('zerolinewidth'); - var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth); + if(yanchor === 'bottom') y = 0; + else if(yanchor === 'middle') y = 1; + else if(yanchor === 'top') y = 2; + else y = _$lib_601.constrain(Math.floor(y * 3), 0, 2); - if(!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } + return cursorset[y][x]; }; /** @@ -28990,177 +29347,332 @@ var _$handleLineGridDefaults_598 = function handleLineGridDefaults(containerIn, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +var _$constants_510 = { + // 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', -// flattenUniqueSort :: String -> Function -> [[String]] -> [String] -function flattenUniqueSort(axisLetter, sortFunction, data) { + // minimum time (msec) between hover calls + HOVERMINTIME: 50, - // Bisection based insertion sort of distinct values for logarithmic time complexity. - // Can't use a hashmap, which is O(1), because ES5 maps coerce keys to strings. If it ever becomes a bottleneck, - // code can be separated: a hashmap (JS object) based version if all values encountered are strings; and - // downgrading to this O(log(n)) array on the first encounter of a non-string value. + // ID suffix (with fullLayout._uid) for hover events in the throttle cache + HOVERID: '-hover' +}; - var categoryArray = []; +// 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 traceLines = data.map(function(d) {return d[axisLetter];}); +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +var _$EventEmitter_194 = EventEmitter; - var i, j, tracePoints, category, insertionIndex; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - var bisector = _$d3_127.bisector(sortFunction).left; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - for(i = 0; i < traceLines.length; i++) { +// 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. +EventEmitter.defaultMaxListeners = 10; - tracePoints = traceLines[i]; +// 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(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; - for(j = 0; j < tracePoints.length; j++) { +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; - category = tracePoints[j]; + if (!this._events) + this._events = {}; - // skip loop: ignore null and undefined categories - if(category === null || category === undefined) continue; + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + } + } - insertionIndex = bisector(categoryArray, category); + handler = this._events[type]; - // skip loop on already encountered values - if(insertionIndex < categoryArray.length && categoryArray[insertionIndex] === category) continue; + if (isUndefined(handler)) + return false; - // insert value - categoryArray.splice(insertionIndex, 0, category); - } + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } - return categoryArray; -} + return true; +}; +EventEmitter.prototype.addListener = function(type, listener) { + var m; -/** - * This pure function returns the ordered categories for specified axisLetter, categoryorder, categoryarray and data. - * - * If categoryorder is 'array', the result is a fresh copy of categoryarray, or if unspecified, an empty array. - * - * If categoryorder is 'category ascending' or 'category descending', the result is an array of ascending or descending - * order of the unique categories encountered in the data for specified axisLetter. - * - * See cartesian/layout_attributes.js for the definition of categoryorder and categoryarray - * - */ + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; -// orderedCategories :: String -> String -> [String] -> [[String]] -> [String] -var _$orderedCategories_599 = function orderedCategories(axisLetter, categoryorder, categoryarray, data) { + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } - switch(categoryorder) { - case 'array': return Array.isArray(categoryarray) ? categoryarray.slice() : []; - case 'category ascending': return flattenUniqueSort(axisLetter, _$d3_127.ascending, data); - case 'category descending': return flattenUniqueSort(axisLetter, _$d3_127.descending, data); - case 'trace': return []; - default: return []; + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } } + } + + return this; }; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +EventEmitter.prototype.on = EventEmitter.prototype.addListener; -'use strict'; +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; + var fired = false; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; -/* removed: var _$handleTickValueDefaults_606 = require('./tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('./tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('./tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_588 = require('./category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_598 = require('./line_grid_defaults'); */; -/* removed: var _$setConvert_603 = require('./set_convert'); */; -/* removed: var _$orderedCategories_599 = require('./ordered_categories'); */; + function g() { + this.removeListener(type, g); -/** - * 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? - * data: the plot data, used to manage categories - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_586 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { - var letter = options.letter; - var font = options.font || {}; + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } - var visible = coerce('visible', !options.cheateronly); + g.listener = listener; + this.on(type, g); - var axType = containerOut.type; + return this; +}; - if(axType === 'date') { - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - _$setConvert_603(containerOut, layoutOut); + if (position < 0) + return this; - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } - // both x and y axes may need autorange done just for the range slider's purposes - // the logic is complicated to figure this out later, particularly for y axes since - // the settings can be spread out in the x axes... so instead we'll collect them - // during supplyDefaults - containerOut._rangesliderAutorange = false; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } - if(autoRange) coerce('rangemode'); + return this; +}; - coerce('range'); - containerOut.cleanRange(); +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - _$handleCategoryOrderDefaults_588(containerIn, containerOut, coerce); - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_599(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; + if (!this._events) + return this; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } - if(axType !== 'category' && !options.noHover) coerce('hoverformat'); + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } - if(!visible) return containerOut; + listeners = this._events[type]; - var dfltColor = coerce('color'); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - coerce('title', layoutOut._dfltTitle[letter]); - _$lib_539.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); + return this; +}; - _$handleTickValueDefaults_606(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_604(containerIn, containerOut, coerce, axType, options); - _$handleTickDefaults_605(containerIn, containerOut, coerce, options); - _$handleLineGridDefaults_598(containerIn, containerOut, coerce, { - dfltColor: dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - attributes: _$layout_attributes_596 - }); +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; - if(containerOut.showline || containerOut.ticks) coerce('mirror'); +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; - if(options.automargin) coerce('automargin'); + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; - return containerOut; +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); }; +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29172,148 +29684,161 @@ var _$handleAxisDefaults_586 = function handleAxisDefaults(containerIn, containe 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var id2name = _$axis_ids_587.id2name; +/* global jQuery:false */ +var __EventEmitter_589 = _$EventEmitter_194.EventEmitter; -var _$handleConstraintDefaults_590 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { - var constraintGroups = layoutOut._axisConstraintGroups; - var thisID = containerOut._id; - var letter = thisID.charAt(0); +var Events = { - if(containerOut.fixedrange) return; + init: function(plotObj) { - // coerce the constraint mechanics even if this axis has no scaleanchor - // because it may be the anchor of another axis. - coerce('constrain'); - _$lib_539.coerce(containerIn, containerOut, { - constraintoward: { - valType: 'enumerated', - values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], - dflt: letter === 'x' ? 'center' : 'middle' - } - }, 'constraintoward'); + /* + * If we have already instantiated an emitter for this plot + * return early. + */ + if(plotObj._ev instanceof __EventEmitter_589) return plotObj; - if(!containerIn.scaleanchor) return; + var ev = new __EventEmitter_589(); + var internalEv = new __EventEmitter_589(); - var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + /* + * Assign to plot._ev while we still live in a land + * where plot is a DOM element with stuff attached to it. + * In the future we can make plot the event emitter itself. + */ + plotObj._ev = ev; - var scaleanchor = _$lib_539.coerce(containerIn, containerOut, { - scaleanchor: { - valType: 'enumerated', - values: constraintOpts.linkableAxes - } - }, 'scaleanchor'); + /* + * Create a second event handler that will manage events *internally*. + * This allows parts of plotly to respond to thing like relayout without + * having to use the user-facing event handler. They cannot peacefully + * coexist on the same handler because a user invoking + * plotObj.removeAllListeners() would detach internal events, breaking + * plotly. + */ + plotObj._internalEv = internalEv; - 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; + /* + * Assign bound methods from the ev to the plot object. These methods + * will reference the 'this' of plot._ev even though they are methods + * of plot. This will keep the event machinery away from the plot object + * which currently is often a DOM element but presents an API that will + * continue to function when plot becomes an emitter. Not all EventEmitter + * methods have been bound to `plot` as some do not currently add value to + * the Plotly event API. + */ + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - updateConstraintGroups(constraintGroups, constraintOpts.thisGroup, - thisID, scaleanchor, scaleratio); - } - else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { - _$lib_539.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.'); - } -}; + /* + * Create funtions for managing internal events. These are *only* triggered + * by the mirroring of external events via the emit function. + */ + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); -function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { - // 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. + /* + * We must wrap emit to continue to support JQuery events. The idea + * is to check to see if the user is using JQuery events, if they are + * we emit JQuery events to trigger user handlers as well as the EventEmitter + * events. + */ + plotObj.emit = function(event, data) { + if(typeof jQuery !== 'undefined') { + jQuery(plotObj).trigger(event, data); + } - var thisType = layoutOut[id2name(thisID)].type; + ev.emit(event, data); + internalEv.emit(event, data); + }; - var i, j, idj, axj; + return plotObj; + }, - var linkableAxes = []; - for(j = 0; j < allAxisIds.length; j++) { - idj = allAxisIds[j]; - if(idj === thisID) continue; + /* + * This function behaves like jQueries triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. + * + * Note: triggerHandler has been recommended for deprecation in v2.0.0, + * so the additional behavior of triggerHandler triggering internal events + * is deliberate excluded in order to avoid reinforcing more usage. + */ + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + /* + * If Jquery exists run all its handlers for this event and + * collect the return value of the LAST handler function + */ + if(typeof jQuery !== 'undefined') { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } - axj = layoutOut[id2name(idj)]; - if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); - } + /* + * Now run all the node style event handlers + */ + var ev = plotObj._ev; + if(!ev) return jQueryHandlerValue; - for(i = 0; i < constraintGroups.length; i++) { - if(constraintGroups[i][thisID]) { - var thisGroup = constraintGroups[i]; + var handlers = ev._events[event]; + if(!handlers) return jQueryHandlerValue; - var linkableAxesNoLoops = []; - for(j = 0; j < linkableAxes.length; j++) { - idj = linkableAxes[j]; - if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); - } - return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; - } - } + /* + * handlers can be function or an array of functions + */ + if(typeof handlers === 'function') handlers = [handlers]; + var lastHandler = handlers.pop(); - return {linkableAxes: linkableAxes, thisGroup: null}; -} + /* + * Call all the handlers except the last one. + */ + for(var i = 0; i < handlers.length; i++) { + handlers[i](data); + } + /* + * Now call the final handler and collect its value + */ + nodeEventHandlerValue = lastHandler(data); -/* - * 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; + /* + * Return either the jquery handler value if it exists or the + * nodeEventHandler value. Jquery event value superceeds nodejs + * events for backwards compatability reasons. + */ + return jQueryHandlerValue !== undefined ? jQueryHandlerValue : + nodeEventHandlerValue; + }, - if(thisGroup === null) { - thisGroup = {}; - thisGroup[thisID] = 1; - thisGroupIndex = constraintGroups.length; - constraintGroups.push(thisGroup); - } - else { - thisGroupIndex = constraintGroups.indexOf(thisGroup); - } + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; - var thisGroupKeys = Object.keys(thisGroup); + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; - // 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; - } + return plotObj; } - // 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; -} +}; +var _$Events_589 = Events; + +var _$unhover_496 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29325,78 +29850,53 @@ function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$Events_589 = require('../../lib/events'); */; +/* removed: var _$throttle_626 = require('../../lib/throttle'); */; +/* removed: var _$get_graph_div_596 = require('../../lib/get_graph_div'); */; -var _$handlePositionDefaults_600 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid = options.grid; +/* removed: var _$constants_510 = require('../fx/constants'); */; - var dfltAnchor, dfltDomain, dfltSide, dfltPosition; +var unhover = _$unhover_496 = {}; - if(grid) { - dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; - dfltAnchor = grid._anchors[containerOut._id]; - if(dfltDomain) { - dfltSide = grid[letter + 'side'].split(' ')[0]; - dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; - } - } - // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (_$fastIsnumeric_139(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); - dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); - dfltPosition = dfltPosition || 0; +unhover.wrapped = function(gd, evt, subplot) { + gd = _$get_graph_div_596(gd); - var anchor = _$lib_539.coerce(containerIn, containerOut, { - anchor: { - valType: 'enumerated', - values: ['free'].concat(counterAxes), - dflt: dfltAnchor - } - }, 'anchor'); + // Important, clear any queued hovers + if(gd._fullLayout) { + _$throttle_626.clear(gd._fullLayout._uid + _$constants_510.HOVERID); + } - if(anchor === 'free') coerce('position', dfltPosition); + unhover.raw(gd, evt, subplot); +}; - _$lib_539.coerce(containerIn, containerOut, { - side: { - valType: 'enumerated', - values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], - dflt: dfltSide - } - }, 'side'); - var overlaying = false; - if(overlayableAxes.length) { - overlaying = _$lib_539.coerce(containerIn, containerOut, { - overlaying: { - valType: 'enumerated', - values: [false].concat(overlayableAxes), - dflt: false - } - }, 'overlaying'); - } +// remove hover effects on mouse out, and emit unhover event +unhover.raw = function unhoverRaw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; - if(!overlaying) { - // TODO: right now I'm copying this domain over to overlaying axes - // in ax.setscale()... but this means we still need (imperfect) logic - // in the axes popover to hide domain for the overlaying axis. - // perhaps I should make a private version _domain that all axes get??? - var domain = coerce('domain', dfltDomain); - if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; - _$lib_539.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + if(!evt) evt = {}; + if(evt.target && + _$Events_589.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; } - coerce('layer'); + fullLayout._hoverlayer.selectAll('g').remove(); + fullLayout._hoverlayer.selectAll('line').remove(); + fullLayout._hoverlayer.selectAll('circle').remove(); + gd._hoverdata = undefined; - return containerOut; + if(evt.target && oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); + } }; +var _$dragelement_495 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -29408,354 +29908,284 @@ var _$handlePositionDefaults_600 = function handlePositionDefaults(containerIn, 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$autoType_585 = require('./axis_autotype'); */; -var name2id = _$axis_ids_587.name2id; - -/* - * data: the plot data to use in choosing auto type - * name: axis object name (ie 'xaxis') if one should be stored - */ -var _$handleTypeDefaults_608 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { - // set up some private properties - if(name) { - containerOut._name = name; - containerOut._id = name2id(name); - } - - var axType = coerce('type'); - if(axType === '-') { - setAutoType(containerOut, data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - containerIn.type = containerOut.type; - } - } -}; - -function setAutoType(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; - - var id = ax._id, - axLetter = id.charAt(0); - - // support 3d - if(id.indexOf('scene') !== -1) id = axLetter; - - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if(!d0) return; +/* removed: var _$mouseEventOffset_321 = require('mouse-event-offset'); */; +/* removed: var _$hasHover_296 = require('has-hover'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; - // first check for histograms, as the count direction - // should always default to a linear axis - if(d0.type === 'histogram' && - axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { - ax.type = 'linear'; - return; - } +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; - var calAttr = axLetter + 'calendar', - calendar = d0[calAttr]; +/* removed: var _$constants_652 = require('../../plots/cartesian/constants'); */; +/* removed: var _$interactions_577 = require('../../constants/interactions'); */; - // check all boxes on this x axis to see - // if they're dates, numbers, or categories - if(isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0), - boxPositions = [], - trace; +var dragElement = _$dragelement_495 = {}; - for(var i = 0; i < data.length; i++) { - trace = data[i]; - if(!_$registry_668.traceIs(trace, 'box-violin') || - (trace[axLetter + 'axis'] || axLetter) !== id) continue; +dragElement.align = _$align_493; +dragElement.getCursor = _$getCursor_494; - if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); - else if(trace.name !== undefined) boxPositions.push(trace.name); - else boxPositions.push('text'); +/* removed: var _$unhover_496 = require('./unhover'); */; +dragElement.unhover = _$unhover_496.wrapped; +dragElement.unhoverRaw = _$unhover_496.raw; - if(trace[calAttr] !== calendar) calendar = undefined; - } - - ax.type = _$autoType_585(boxPositions, calendar); - } - else { - ax.type = _$autoType_585(d0[axLetter] || [d0[axLetter + '0']], calendar); - } -} - -function getFirstNonEmptyTrace(data, id, axLetter) { - for(var i = 0; i < data.length; i++) { - var trace = data[i]; - - if((trace[axLetter + 'axis'] || axLetter) === id) { - if(isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } - else if((trace[axLetter] || []).length || trace[axLetter + '0']) { - return trace; - } - } - } -} - -function getBoxPosLetter(trace) { - return {v: 'x', h: 'y'}[trace.orientation || 'v']; -} - -function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace), - isBox = _$registry_668.traceIs(trace, 'box-violin'), - isCandlestick = _$registry_668.traceIs(trace._fullInput || {}, 'candlestick'); - - return ( - isBox && - !isCandlestick && - axLetter === posLetter && - trace[posLetter] === undefined && - trace[posLetter + '0'] === undefined - ); -} /** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + * 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 DBLCLICKDELAY = _$interactions_577.DBLCLICKDELAY; + var element = options.element; + var startX, + startY, + newMouseDownTime, + cursor, + dragCover, + initialEvent, + initialTarget, + rightClick; -'use strict'; + if(!gd._mouseDownTime) gd._mouseDownTime = 0; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$layout_attributes_638 = require('../layout_attributes'); */; + element.style.pointerEvents = 'all'; -/* removed: var _$layout_attributes_596 = require('./layout_attributes'); */; -/* removed: var _$handleTypeDefaults_608 = require('./type_defaults'); */; -/* removed: var _$handleAxisDefaults_586 = require('./axis_defaults'); */; -/* removed: var _$handleConstraintDefaults_590 = require('./constraint_defaults'); */; -/* removed: var _$handlePositionDefaults_600 = require('./position_defaults'); */; -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; + element.onmousedown = onStart; + if(!_$hasPassiveEvents_297) { + element.ontouchstart = onStart; + } + else { + if(element._ontouchstart) { + element.removeEventListener('touchstart', element._ontouchstart); + } + element._ontouchstart = onStart; + element.addEventListener('touchstart', onStart, {passive: false}); + } -var _$supplyLayoutDefaults_597 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - var xaCheater = {}; - var xaNonCheater = {}; - var outerTicks = {}; - var noGrids = {}; - var i; + function _clampFn(dx, dy, minDrag) { + if(Math.abs(dx) < minDrag) dx = 0; + if(Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } - // look for axes in the data - for(i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + var clampFn = options.clampFn || _clampFn; - if(!_$registry_668.traceIs(trace, 'cartesian') && !_$registry_668.traceIs(trace, 'gl2d')) { - continue; - } + function onStart(e) { + e.preventDefault(); - var xaName = _$axis_ids_587.id2name(trace.xaxis); - var yaName = _$axis_ids_587.id2name(trace.yaxis); + // 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; - // Two things trigger axis visibility: - // 1. is not carpet - // 2. carpet that's not cheater - if(!_$registry_668.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { - if(xaName) xaNonCheater[xaName] = 1; + newMouseDownTime = (new Date()).getTime(); + if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { + // in a click train + numClicks += 1; } - - // 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) xaCheater[xaName] = 1; + else { + // new click train + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; } - // check for default formatting tweaks - if(_$registry_668.traceIs(trace, '2dMap')) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } + if(options.prepFn) options.prepFn(e, startX, startY); - if(_$registry_668.traceIs(trace, 'oriented')) { - var positionAxis = trace.orientation === 'h' ? yaName : xaName; - noGrids[positionAxis] = true; + if(_$hasHover_296 && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } + else if(!_$hasHover_296) { + // 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; } - } - var subplots = layoutOut._subplots; - var xIds = subplots.xaxis; - var yIds = subplots.yaxis; - var xNames = _$lib_539.simpleMap(xIds, _$axis_ids_587.id2name); - var yNames = _$lib_539.simpleMap(yIds, _$axis_ids_587.id2name); - var axNames = xNames.concat(yNames); + document.addEventListener('mousemove', onMove); + document.addEventListener('mouseup', onDone); + document.addEventListener('touchmove', onMove); + document.addEventListener('touchend', onDone); - // plot_bgcolor only makes sense if there's a (2D) plot! - // TODO: bgcolor for each subplot, to inherit from the main one - var plot_bgcolor = _$color_411.background; - if(xIds.length && yIds.length) { - plot_bgcolor = _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_638, 'plot_bgcolor'); + return; } - var bgColor = _$color_411.combine(plot_bgcolor, layoutOut.paper_bgcolor); + function onMove(e) { + e.preventDefault(); - var axName, axLetter, axLayoutIn, axLayoutOut; + var offset = pointerOffset(e); + var minDrag = options.minDrag || _$constants_652.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; - function coerce(attr, dflt) { - return _$lib_539.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_596, attr, dflt); - } + if(dx || dy) { + gd._dragged = true; + dragElement.unhover(gd); + } - function coerce2(attr, dflt) { - return _$lib_539.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_596, attr, dflt); - } + if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); - function getCounterAxes(axLetter) { - return (axLetter === 'x') ? yIds : xIds; + return; } - var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')}; - - function getOverlayableAxes(axLetter, axName) { - var list = (axLetter === 'x') ? xNames : yNames; - var out = []; + function onDone(e) { + document.removeEventListener('mousemove', onMove); + document.removeEventListener('mouseup', onDone); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onDone); - for(var j = 0; j < list.length; j++) { - var axName2 = list[j]; + e.preventDefault(); - if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) { - out.push(_$axis_ids_587.name2id(axName2)); - } + if(_$hasHover_296) { + _$lib_601.removeElement(dragCover); } - - 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]; - - if(!_$lib_539.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; + else if(cursor) { + dragCover.documentElement.style.cursor = cursor; + cursor = null; } - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName] = {}; - - _$handleTypeDefaults_608(axLayoutIn, axLayoutOut, coerce, fullData, axName); - - axLetter = axName.charAt(0); - var overlayableAxes = getOverlayableAxes(axLetter, axName); - - var defaultOptions = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: fullData, - bgColor: bgColor, - calendar: layoutOut.calendar, - automargin: true, - cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] - }; - - _$handleAxisDefaults_586(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); - - var spikecolor = coerce2('spikecolor'), - spikethickness = coerce2('spikethickness'), - spikedash = coerce2('spikedash'), - spikemode = coerce2('spikemode'), - spikesnap = coerce2('spikesnap'), - 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; + if(!gd._dragging) { + gd._dragged = false; + return; } + gd._dragging = false; - var positioningOptions = { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: overlayableAxes, - grid: layoutOut.grid - }; - - _$handlePositionDefaults_600(axLayoutIn, axLayoutOut, coerce, positioningOptions); - - axLayoutOut._input = axLayoutIn; - } + // don't count as a dblClick unless the mouseUp is also within + // the dblclick delay + if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { + numClicks = Math.max(numClicks - 1, 1); + } - // quick second pass for range slider and selector defaults - var rangeSliderDefaults = _$registry_668.getComponentMethod('rangeslider', 'handleDefaults'); - var rangeSelectorDefaults = _$registry_668.getComponentMethod('rangeselector', 'handleDefaults'); + if(gd._dragged) { + if(options.doneFn) options.doneFn(e); + } + else { + if(options.clickFn) options.clickFn(numClicks, initialEvent); - for(i = 0; i < xNames.length; i++) { - axName = xNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + // 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; - rangeSliderDefaults(layoutIn, layoutOut, axName); + 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); + } - if(axLayoutOut.type === 'date') { - rangeSelectorDefaults( - axLayoutIn, - axLayoutOut, - layoutOut, - yNames, - axLayoutOut.calendar - ); + initialTarget.dispatchEvent(e2); + } } - coerce('fixedrange'); - } + finishDrag(gd); - for(i = 0; i < yNames.length; i++) { - axName = yNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; + gd._dragged = false; - var anchoredAxis = layoutOut[_$axis_ids_587.id2name(axLayoutOut.anchor)]; + return; + } +}; - var fixedRangeDflt = ( - anchoredAxis && - anchoredAxis.rangeslider && - anchoredAxis.rangeslider.visible - ); +function coverSlip() { + var cover = document.createElement('div'); - coerce('fixedrange', fixedRangeDflt); - } + 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'; - // Finally, handle scale constraints. 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). + document.body.appendChild(cover); - // sets of axes linked by `scaleanchor` along with the scaleratios compounded - // together, populated in handleConstraintDefaults - layoutOut._axisConstraintGroups = []; - var allAxisIds = counterAxes.x.concat(counterAxes.y); + return cover; +} - for(i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axLetter = axName.charAt(0); +dragElement.coverSlip = coverSlip; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; +function finishDrag(gd) { + gd._dragging = false; + if(gd._replotPending) _$registry_731.call('plot', gd); +} - _$handleConstraintDefaults_590(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); - } -}; +function pointerOffset(e) { + return _$mouseEventOffset_321( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); +} /** * Copyright 2012-2018, Plotly, Inc. @@ -29767,328 +30197,294 @@ var _$supplyLayoutDefaults_597 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$axes_584 = require('./axes'); */; -var axisRegex = _$constants_589.attrRegex; - -var _$transitionAxes_607 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { +var _$calc_508 = function calc(gd) { + var calcdata = gd.calcdata; var fullLayout = gd._fullLayout; - var axes = []; - function computeUpdates(layout) { - var ai, attrList, match, axis, update; - var updates = {}; + function makeCoerceHoverInfo(trace) { + return function(val) { + return _$lib_601.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + }; + } - for(ai in layout) { - attrList = ai.split('.'); - match = attrList[0].match(axisRegex); - if(match) { - var axisLetter = ai.charAt(0); - var axisName = attrList[0]; - axis = fullLayout[axisName]; - update = {}; + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; - if(Array.isArray(layout[ai])) { - update.to = layout[ai].slice(0); - } else { - if(Array.isArray(layout[ai].range)) { - update.to = layout[ai].range.slice(0); - } - } - if(!update.to) continue; + // 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_731.traceIs(trace, 'pie')) continue; - update.axisName = axisName; - update.length = axis._length; + var fillFn = _$registry_731.traceIs(trace, '2dMap') ? paste : _$lib_601.fillArray; - axes.push(axisLetter); + fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); - updates[axisLetter] = update; - } - } + if(!trace.hoverlabel) continue; - return updates; + 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'); } +}; - function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { - var plotName; - var plotinfos = fullLayout._plots; - var affectedSubplots = []; - var toX, toY; - - for(plotName in plotinfos) { - var plotinfo = plotinfos[plotName]; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || _$lib_601.identity; - if(affectedSubplots.indexOf(plotinfo) !== -1) continue; + if(Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} - var x = plotinfo.xaxis._id; - var y = plotinfo.yaxis._id; - var fromX = plotinfo.xaxis.range; - var fromY = plotinfo.yaxis.range; +var _$helpers_512 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // Store the initial range at the beginning of this transition: - plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); - plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); +'use strict'; - if(updates[x]) { - toX = updates[x].to; - } else { - toX = fromX; - } - if(updates[y]) { - toY = updates[y].to; - } else { - toY = fromY; - } +/* removed: var _$lib_601 = require('../../lib'); */; - if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; +// look for either subplot or xaxis and yaxis attributes +// does not handle splom case +_$helpers_512.getSubplot = function getSubplot(trace) { + return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; +}; - if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { - affectedSubplots.push(plotinfo); +// is trace in given list of subplots? +// does handle splom case +_$helpers_512.isTraceInSubplots = function isTraceInSubplot(trace, subplots) { + if(trace.type === 'splom') { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for(var i = 0; i < xaxes.length; i++) { + for(var j = 0; j < yaxes.length; j++) { + if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } } } - - return affectedSubplots; + return false; } - var updates = computeUpdates(newLayout); - var updatedAxisIds = Object.keys(updates); - var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - - function updateLayoutObjs() { - function redrawObjs(objArray, method, shortCircuit) { - for(var i = 0; i < objArray.length; i++) { - method(gd, i); - - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } + return subplots.indexOf(_$helpers_512.getSubplot(trace)) !== -1; +}; - redrawObjs(fullLayout.annotations || [], _$registry_668.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_668.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_668.getComponentMethod('images', 'draw'), true); +// convenience functions for mapping all relevant axes +_$helpers_512.flat = function flat(subplots, v) { + var out = new Array(subplots.length); + for(var i = 0; i < subplots.length; i++) { + out[i] = v; } + return out; +}; - if(!affectedSubplots.length) { - updateLayoutObjs(); - return false; +_$helpers_512.p2c = function p2c(axArray, v) { + var out = new Array(axArray.length); + for(var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); } + return out; +}; - function ticksAndAnnotations(xa, ya) { - var activeAxIds = [], - i; - - activeAxIds = [xa._id, ya._id]; +_$helpers_512.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { + if(mode === 'closest') return dxy || _$helpers_512.quadrature(dx, dy); + return mode === 'x' ? dx : dy; +}; - for(i = 0; i < activeAxIds.length; i++) { - _$axes_584.doTicks(gd, activeAxIds[i], true); +_$helpers_512.getClosest = function getClosest(cd, distfn, pointData) { + // do we already have a point number? (array mode only) + if(pointData.index !== false) { + if(pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; } - - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; - - if((activeAxIds.indexOf(obji.xref) !== -1) || - (activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - } - - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; + else pointData.index = false; + } + else { + // apply the distance function to each data point + // this is the longest loop... if this bogs down, we may need + // to create pre-sorted data (by x or y), not sure how to + // do this for 'closest' + for(var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if(newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; } } - - redrawObjs(fullLayout.annotations || [], _$registry_668.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_668.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_668.getComponentMethod('images', 'draw'), true); - } - - function unsetSubplotTransform(subplot) { - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; - - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_436.setTranslate, 0, 0) - .call(_$drawing_436.setScale, 1, 1); - - subplot.plot - .call(_$drawing_436.setTranslate, xa2._offset, ya2._offset) - .call(_$drawing_436.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_436.setPointGroupScale, 1, 1); - traceGroups.selectAll('.textpoint') - .call(_$drawing_436.setTextPointsScale, 1, 1); - traceGroups - .call(_$drawing_436.hideOutsideRangePoints, subplot); } + return pointData; +}; - function updateSubplot(subplot, progress) { - var axis, r0, r1; - var xUpdate = updates[subplot.xaxis._id]; - var yUpdate = updates[subplot.yaxis._id]; - - var viewBox = []; - - if(xUpdate) { - axis = gd._fullLayout[xUpdate.axisName]; - r0 = axis._r; - r1 = xUpdate.to; - viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; - var dx1 = r0[1] - r0[0]; - var dx2 = r1[1] - r1[0]; +/* + * pseudo-distance function for hover effects on areas: inside the region + * distance is finite (`passVal`), outside it's Infinity. + * + * @param {number} v0: signed difference between the current position and the left edge + * @param {number} v1: signed difference between the current position and the right edge + * @param {number} passVal: the value to return on success + */ +_$helpers_512.inbox = function inbox(v0, v1, passVal) { + return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; +}; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; +_$helpers_512.quadrature = function quadrature(dx, dy) { + return function(di) { + var x = dx(di), + y = dy(di); + return Math.sqrt(x * x + y * y); + }; +}; - viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); - } else { - viewBox[0] = 0; - viewBox[2] = subplot.xaxis._length; - } +/** Fill event data point object for hover and selection. + * Invokes _module.eventData if present. + * + * N.B. note that point 'index' corresponds to input data array index + * whereas 'number' is its post-transform version. + * + * If the hovered/selected pt corresponds to an multiple input points + * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' + * are include in the event data. + * + * @param {object} pt + * @param {object} trace + * @param {object} cd + * @return {object} + */ +_$helpers_512.makeEventData = function makeEventData(pt, trace, cd) { + // hover uses 'index', select uses 'pointNumber' + var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; - if(yUpdate) { - axis = gd._fullLayout[yUpdate.axisName]; - r0 = axis._r; - r1 = yUpdate.to; - viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; - var dy1 = r0[1] - r0[0]; - var dy2 = r1[1] - r1[0]; + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber: pointNumber + }; - axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; - axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + if(trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; - viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + if(pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; } else { - viewBox[1] = 0; - viewBox[3] = subplot.yaxis._length; + out.pointIndices = pointIndices; } + } else { + out.pointIndex = pointNumber; + } - ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - - var xa2 = subplot.xaxis; - var ya2 = subplot.yaxis; - - var editX = !!xUpdate; - var editY = !!yUpdate; - - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; + if(trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if('xVal' in pt) out.x = pt.xVal; + else if('x' in pt) out.x = pt.x; - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + if('yVal' in pt) out.y = pt.yVal; + else if('y' in pt) out.y = pt.y; - var plotDx = xa2._offset - fracDx, - plotDy = ya2._offset - fracDy; + if(pt.xa) out.xaxis = pt.xa; + if(pt.ya) out.yaxis = pt.ya; + if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; + } - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_436.setTranslate, clipDx, clipDy) - .call(_$drawing_436.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + _$helpers_512.appendArrayPointValue(out, trace, pointNumber); - subplot.plot - .call(_$drawing_436.setTranslate, plotDx, plotDy) - .call(_$drawing_436.setScale, xScaleFactor, yScaleFactor) + return out; +}; - // This is specifically directed at scatter traces, applying an inverse - // scale to individual points to counteract the scale of the trace - // as a whole: - .selectAll('.points').selectAll('.point') - .call(_$drawing_436.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); +/** Appends values inside array attributes corresponding to given point number + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {number|Array(number)} pointNumber : point number. May be a length-2 array + * [row, col] to dig into 2D arrays + */ +_$helpers_512.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; - subplot.plot.selectAll('.points').selectAll('.textpoint') - .call(_$drawing_436.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); + if(!arrayAttrs) { + return; } - var onComplete; - if(makeOnCompleteCallback) { - // This module makes the choice whether or not it notifies Plotly.transition - // about completion: - onComplete = makeOnCompleteCallback(); - } + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); - function transitionComplete() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; - var to = updates[updatedAxisIds[i]].to; - aobj[axi._name + '.range[0]'] = to[0]; - aobj[axi._name + '.range[1]'] = to[1]; + if(pointData[key] === undefined) { + var val = _$lib_601.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); - axi.range = to.slice(); + if(pointVal !== undefined) pointData[key] = pointVal; } + } +}; - // Signal that this transition has completed: - onComplete && onComplete(); +/** + * Appends values inside array attributes corresponding to given point number array + * For use when pointData references a plot entity that arose (or potentially arose) + * from multiple points in the input data + * + * @param {object} pointData : point data object (gets mutated here) + * @param {object} trace : full trace object + * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. + * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays + */ +_$helpers_512.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; - return _$registry_668.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); - } - }); + if(!arrayAttrs) { + return; } - function transitionInterrupt() { - var aobj = {}; - for(var i = 0; i < updatedAxisIds.length; i++) { - var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; - aobj[axi._name + '.range[0]'] = axi.range[0]; - aobj[axi._name + '.range[1]'] = axi.range[1]; + for(var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); - axi.range = axi._r.slice(); - } + if(pointData[key] === undefined) { + var val = _$lib_601.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); - return _$registry_668.call('relayout', gd, aobj).then(function() { - for(var i = 0; i < affectedSubplots.length; i++) { - unsetSubplotTransform(affectedSubplots[i]); + for(var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); } - }); + pointData[key] = keyVal; + } } +}; - var t1, t2, raf; - var easeFn = _$d3_127.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); +var pointKeyMap = { + ids: 'id', + locations: 'location', + labels: 'label', + values: 'value', + 'marker.colors': 'color' +}; - for(var i = 0; i < affectedSubplots.length; i++) { - updateSubplot(affectedSubplots[i], progress); - } +function getPointKey(astr) { + return pointKeyMap[astr] || astr; +} - if(t2 - t1 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); +function getPointData(val, pointNumber) { + if(Array.isArray(pointNumber)) { + if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; } + } else { + return val[pointNumber]; } +} - t1 = Date.now(); - raf = window.requestAnimationFrame(doFrame); - - return Promise.resolve(); -}; - -var _$get_data_621 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -30097,92 +30493,69 @@ var _$get_data_621 = {}; * LICENSE file in the root directory of this source tree. */ -'use strict'; - -/* removed: var _$registry_668 = require('../registry'); */; -var SUBPLOT_PATTERN = _$constants_589.SUBPLOT_PATTERN; - -/** - * Get calcdata traces(s) associated with a given subplot - * - * @param {array} calcData (as in gd.calcdata) - * @param {string} type subplot type - * @param {string} subplotId subplot id to look for - * - * @return {array} array of calcdata traces - */ -_$get_data_621.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = _$registry_668.subplotsRegistry[type]; - if(!basePlotModule) return []; - - var attr = basePlotModule.attr; - var subplotCalcData = []; - - for(var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; - if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); - } - - return subplotCalcData; -}; - -_$get_data_621.getModuleCalcData = function(calcdata, typeOrModule) { - var moduleCalcData = []; - var _module = typeof typeOrModule === 'string' ? _$registry_668.getModule(typeOrModule) : typeOrModule; - if(!_module) return moduleCalcData; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; +'use strict'; - if((trace._module === _module) && (trace.visible === true)) moduleCalcData.push(cd); - } +// works with our CSS cursor classes (see css/_cursor.scss) +// to apply cursors to d3 single-element selections. +// omit cursor to revert to the default. +var _$setCursor_621 = function setCursor(el3, csr) { + (el3.attr('class') || '').split(' ').forEach(function(cls) { + if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); + }); - return moduleCalcData; + if(csr) el3.classed('cursor-' + csr, true); }; /** - * Get the data trace(s) associated with a given subplot. - * - * @param {array} data plotly full data array. - * @param {string} type subplot type to look for. - * @param {string} subplotId subplot id to look for. - * - * @return {array} list of trace objects. - * - */ -_$get_data_621.getSubplotData = function getSubplotData(data, type, subplotId) { - if(!_$registry_668.subplotsRegistry[type]) return []; +* Copyright 2012-2018, Plotly, Inc. +* All 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 attr = _$registry_668.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; - if(type === 'gl2d') { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = 'x' + spmatch[1]; - subplotY = 'y' + spmatch[2]; - } +'use strict'; - for(var i = 0; i < data.length; i++) { - trace = data[i]; +/* removed: var _$setCursor_621 = require('./setcursor'); */; - if(type === 'gl2d' && _$registry_668.traceIs(trace, 'gl2d')) { - if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); +var STASHATTR = 'data-savedcursor'; +var NO_CURSOR = '!!'; + +/* + * works with our CSS cursor classes (see css/_cursor.scss) + * to override a previous cursor set on d3 single-element selections, + * by moving the name of the original cursor to the data-savedcursor attr. + * omit cursor to revert to the previously set value. + */ +var _$overrideCursor_612 = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if(csr) { + if(!savedCursor) { + var classes = (el3.attr('class') || '').split(' '); + for(var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if(cls.indexOf('cursor-') === 0) { + el3.attr(STASHATTR, cls.substr(7)) + .classed(cls, false); + } + } + if(!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); } } - else { - if(trace[attr] === subplotId) subplotData.push(trace); - } + _$setCursor_621(el3, csr); } + else if(savedCursor) { + el3.attr(STASHATTR, null); - return subplotData; + if(savedCursor === NO_CURSOR) _$setCursor_621(el3); + else _$setCursor_621(el3, savedCursor); + } }; -var _$cartesian_595 = {}; +var _$hover_513 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -30191,870 +30564,1454 @@ var _$cartesian_595 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../plots'); */; -var getModuleCalcData = _$get_data_621.getModuleCalcData; - -/* removed: var _$axis_ids_587 = require('./axis_ids'); */; -/* removed: var _$constants_589 = require('./constants'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -_$cartesian_595.name = 'cartesian'; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$Events_589 = require('../../lib/events'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$overrideCursor_612 = require('../../lib/override_cursor'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -_$cartesian_595.attr = ['xaxis', 'yaxis']; +/* removed: var _$helpers_512 = require('./helpers'); */; +/* removed: var _$constants_510 = require('./constants'); */; -_$cartesian_595.idRoot = ['x', 'y']; +// hover labels for multiple horizontal bars get tilted by some angle, +// then need to be offset differently if they overlap +var YANGLE = _$constants_510.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; -_$cartesian_595.idRegex = _$constants_589.idRegex; +// expansion of projected height +var YFACTOR = 1 / Math.sin(YA_RADIANS); -_$cartesian_595.attrRegex = _$constants_589.attrRegex; +// to make the appropriate post-rotation x offset, +// you need both x and y offsets +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); -_$cartesian_595.attributes = _$attributes_582; +// size and display constants for hover text +var HOVERARROWSIZE = _$constants_510.HOVERARROWSIZE; +var HOVERTEXTPAD = _$constants_510.HOVERTEXTPAD; -_$cartesian_595.layoutAttributes = _$layout_attributes_596; +// fx.hover: highlight data on hover +// evt can be a mousemove event, or an object with data about what points +// to hover on +// {xpx,ypx[,hovermode]} - pixel locations from top left +// (with optional overriding hovermode) +// {xval,yval[,hovermode]} - data values +// [{curveNumber,(pointNumber|xval and/or yval)}] - +// array of specific points to highlight +// pointNumber is a single integer if gd.data[curveNumber] is 1D, +// or a two-element array if it's 2D +// xval and yval are data values, +// 1D data may specify either or both, +// 2D data must specify both +// subplot is an id string (default "xy") +// makes use of gl.hovermode, which can be: +// x (find the points with the closest x values, ie a column), +// closest (find the single closest point) +// internally there are two more that occasionally get used: +// y (pick out a row - only used for multiple horizontal bar charts) +// array (used when the user specifies an explicit +// array of points to hover on) +// +// We wrap the hovers in a timer, to limit their frequency. +// The actual rendering is done by private function _hover. +_$hover_513.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = _$lib_601.getGraphDiv(gd); -_$cartesian_595.supplyLayoutDefaults = _$supplyLayoutDefaults_597; + _$lib_601.throttle( + gd._fullLayout._uid + _$constants_510.HOVERID, + _$constants_510.HOVERMINTIME, + function() { _hover(gd, evt, subplot, noHoverEvent); } + ); +}; -_$cartesian_595.transitionAxes = _$transitionAxes_607; +/* + * Draw a single hover item in a pre-existing svg container somewhere + * hoverItem should have keys: + * - x and y (or x0, x1, y0, and y1): + * the pixel position to mark, relative to opts.container + * - xLabel, yLabel, zLabel, text, and name: + * info to go in the label + * - color: + * the background color for the label. + * - idealAlign (optional): + * 'left' or 'right' for which side of the x/y box to try to put this on first + * - borderColor (optional): + * color for the border, defaults to strongest contrast with color + * - fontFamily (optional): + * string, the font for this label, defaults to constants.HOVERFONT + * - fontSize (optional): + * the label font size, defaults to constants.HOVERFONTSIZE + * - fontColor (optional): + * defaults to borderColor + * opts should have keys: + * - bgColor: + * the background color this is against, used if the trace is + * non-opaque, and for the name, which goes outside the box + * - container: + * a or element to add the hover label to + * - outerContainer: + * normally a parent of `container`, sets the bounding box to use to + * constrain the hover label and determine whether to show it on the left or right + */ +_$hover_513.loneHover = function loneHover(hoverItem, opts) { + var pointData = { + color: hoverItem.color || _$color_473.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, -_$cartesian_595.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; + // optional extra bits of styling + borderColor: hoverItem.borderColor, + fontFamily: hoverItem.fontFamily, + fontSize: hoverItem.fontSize, + fontColor: hoverItem.fontColor, - for(i = 0; i < spAll.length; i++) { - var parts = spAll[i].split('y'); - allX[parts[0]] = 1; - allY['y' + parts[1]] = 1; - } + // filler to make createHoverText happy + trace: { + index: 0, + hoverinfo: '' + }, + xa: {_offset: 0}, + ya: {_offset: 0}, + index: 0 + }; - // check for x axes with no subplot, and make one from the anchor of that x axis - for(i = 0; i < xList.length; i++) { - xi = xList[i]; - if(!allX[xi]) { - yi = (layoutIn[_$axis_ids_587.id2name(xi)] || {}).anchor; - if(!_$constants_589.idRegex.y.test(yi)) yi = 'y'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var container3 = _$d3_130.select(opts.container), + outerContainer3 = opts.outerContainer ? + _$d3_130.select(opts.outerContainer) : container3; - if(!allY[yi]) { - allY[yi] = 1; - _$lib_539.pushUnique(yList, yi); - } - } - } + var fullOpts = { + hovermode: 'closest', + rotateLabels: false, + bgColor: opts.bgColor || _$color_473.background, + container: container3, + outerContainer: outerContainer3 + }; - // same for y axes with no subplot - for(i = 0; i < yList.length; i++) { - yi = yList[i]; - if(!allY[yi]) { - xi = (layoutIn[_$axis_ids_587.id2name(yi)] || {}).anchor; - if(!_$constants_589.idRegex.x.test(xi)) xi = 'x'; - spSVG.push(xi + yi); - spAll.push(xi + yi); + var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); + alignHoverText(hoverLabel, fullOpts.rotateLabels); - if(!allX[xi]) { - allX[xi] = 1; - _$lib_539.pushUnique(xList, xi); - } - } - } - - // finally, if we've gotten here we're supposed to show cartesian... - // so if there are NO subplots at all, make one from the first - // x & y axes in the input layout - if(!spAll.length) { - xi = ''; - yi = ''; - for(var ki in layoutIn) { - if(_$constants_589.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if(axLetter === 'x') { - if(!xi || (+ki.substr(5) < +xi.substr(5))) { - xi = ki; - } - } - else if(!yi || (+ki.substr(5) < +yi.substr(5))) { - yi = ki; - } - } - } - xi = xi ? _$axis_ids_587.name2id(xi) : 'x'; - yi = yi ? _$axis_ids_587.name2id(yi) : 'y'; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } + return hoverLabel.node(); }; -_$cartesian_595.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; +// The actual implementation is here: +function _hover(gd, evt, subplot, noHoverEvent) { + if(!subplot) subplot = 'xy'; - // If traces is not provided, then it's a complete replot and missing - // traces are removed - if(!Array.isArray(traces)) { - traces = []; + // if the user passed in an array of subplots, + // use those instead of finding overlayed plots + var subplots = Array.isArray(subplot) ? subplot : [subplot]; - for(i = 0; i < calcdata.length; i++) { - traces.push(i); - } - } + var fullLayout = gd._fullLayout; + var plots = fullLayout._plots || []; + var plotinfo = plots[subplot]; + var hasCartesian = fullLayout._has('cartesian'); - // clear gl frame, if any, since we preserve drawing buffer - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } + // list of all overlaid subplots to look at + if(plotinfo) { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; }); - } - for(i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - subplotInfo = fullLayout._plots[subplot]; + subplots = subplots.concat(overlayedSubplots); + } - // Get all calcdata for this subplot: - var cdSubplot = []; - var pcd; + var len = subplots.length; + var xaArray = new Array(len); + var yaArray = new Array(len); + var supportsCompare = false; - for(var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j], - trace = cd[0].trace; + for(var i = 0; i < len; i++) { + var spId = subplots[i]; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { - // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet - // axis has actually changed: - // - // If this trace is specifically requested, add it to the list: - if(traces.indexOf(trace.index) !== -1 || trace.carpet) { - // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate - // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill - // is outdated. So this retroactively adds the previous trace if the - // traces are interdependent. - if( - pcd && - pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && - ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && - cdSubplot.indexOf(pcd) === -1 - ) { - cdSubplot.push(pcd); - } + // 'cartesian' case + var plotObj = plots[spId]; + if(plotObj) { + supportsCompare = true; - cdSubplot.push(cd); - } + // TODO make sure that fullLayout_plots axis refs + // get updated properly so that we don't have + // to use Axes.getFromId in general. - // Track the previous trace on this subplot for the retroactive-add step - // above: - pcd = cd; - } + xaArray[i] = _$axes_647.getFromId(gd, plotObj.xaxis._id); + yaArray[i] = _$axes_647.getFromId(gd, plotObj.yaxis._id); + continue; } - plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } -}; - -function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout, - modules = fullLayout._modules; - - // remove old traces, then redraw everything - // - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(plotinfo.plot) { - plotinfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + // other subplot types + var _subplot = fullLayout[spId]._subplot; + xaArray[i] = _subplot.xaxis; + yaArray[i] = _subplot.yaxis; } - // plot all traces for each module at once - for(var j = 0; j < modules.length; j++) { - var _module = modules[j]; - - // skip over non-cartesian trace modules - if(_module.basePlotModule.name !== 'cartesian') continue; + var hovermode = evt.hovermode || fullLayout.hovermode; - // plot all traces of this type on this subplot at once - var cdModule = getModuleCalcData(cdSubplot, _module); + if(hovermode && !supportsCompare) hovermode = 'closest'; - if(_module.plot) _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || + gd.querySelector('.zoombox') || gd._dragging) { + return _$dragelement_495.unhoverRaw(gd, evt); } -} -_$cartesian_595.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldModules = oldFullLayout._modules || [], - newModules = newFullLayout._modules || []; + var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; + var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; - var hadScatter, hasScatter, hadGl, hasGl, i, oldPlots, ids, subplotInfo, moduleName; + // hoverData: the set of candidate points we've found to highlight + var hoverData = [], + // searchData: the data to search in. Mostly this is just a copy of + // gd.calcdata, filtered to the subplot and overlays we're on + // but if a point array is supplied it will be a mapping + // of indicated curves + searchData = [], - for(i = 0; i < oldModules.length; i++) { - moduleName = oldModules[i].name; - if(moduleName === 'scatter') hadScatter = true; - else if(moduleName === 'scattergl') hadGl = true; - } + // [x|y]valArray: the axis values of the hover event + // mapped onto each of the currently selected overlaid subplots + xvalArray, + yvalArray, - for(i = 0; i < newModules.length; i++) { - moduleName = newModules[i].name; - if(moduleName === 'scatter') hasScatter = true; - else if(moduleName === 'scattergl') hasGl = true; - } + // used in loops + itemnum, + curvenum, + cd, + trace, + subplotId, + subploti, + mode, + xval, + yval, + pointData, + closedataPreviousLength, - if(hadScatter && !hasScatter) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // spikePoints: the set of candidate points we've found to draw spikes to + spikePoints = { + hLinePoint: null, + vLinePoint: null + }; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + // Figure out what we're hovering on: + // mouse location or user-supplied data - if(subplotInfo.plot) { - subplotInfo.plot.select('g.scatterlayer') - .selectAll('g.trace') - .remove(); + if(Array.isArray(evt)) { + // user specified an array of points to highlight + hovermode = 'array'; + for(itemnum = 0; itemnum < evt.length; itemnum++) { + cd = gd.calcdata[evt[itemnum].curveNumber||0]; + if(cd[0].trace.hoverinfo !== 'skip') { + searchData.push(cd); } } - - oldFullLayout._infolayer.selectAll('g.rangeslider-container') - .select('g.scatterlayer') - .selectAll('g.trace') - .remove(); } + else { + for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { + cd = gd.calcdata[curvenum]; + trace = cd[0].trace; + if(trace.hoverinfo !== 'skip' && _$helpers_512.isTraceInSubplots(trace, subplots)) { + searchData.push(cd); + } + } - if(hadGl && !hasGl) { - oldPlots = oldFullLayout._plots; - ids = Object.keys(oldPlots || {}); + // [x|y]px: the pixels (from top left) of the mouse location + // on the currently selected plot area + // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation + var hasUserCalledHover = !evt.target, + xpx, ypx; - for(i = 0; i < ids.length; i++) { - subplotInfo = oldPlots[ids[i]]; + if(hasUserCalledHover) { + if('xpx' in evt) xpx = evt.xpx; + else xpx = xaArray[0]._length / 2; + evt.pointerX = xpx + xaArray[0]._offset; - if(subplotInfo._scene) { - subplotInfo._scene.destroy(); - } + if('ypx' in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + evt.pointerY = ypx + yaArray[0]._offset; } - } + else { + // fire the beforehover event and quit if it returns false + // note that we're only calling this on real mouse events, so + // manual calls to fx.hover will always run. + if(_$Events_589.triggerHandler(gd, 'plotly_beforehover', evt) === false) { + return; + } - var oldSubplotList = oldFullLayout._subplots || {}; - var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + var dbb = evt.target.getBoundingClientRect(); - // delete any titles we don't need anymore - // check if axis list has changed, and if so clear old titles - if(oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); - var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; - for(i = 0; i < oldAxIDs.length; i++) { - if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { - oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); + // in case hover was called from mouseout into hovertext, + // it's possible you're not actually over the plot anymore + if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { + return _$dragelement_495.unhoverRaw(gd, evt); } + evt.pointerX = evt.offsetX; + evt.pointerY = evt.offsetY; } - } - // if we've gotten rid of all cartesian traces, remove all the subplot svg items - var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); - var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); + if('xval' in evt) xvalArray = _$helpers_512.flat(subplots, evt.xval); + else xvalArray = _$helpers_512.p2c(xaArray, xpx); - if(hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); - oldFullLayout._defs.selectAll('.axesclip').remove(); - delete oldFullLayout._axisConstraintGroups; - } - // otherwise look for subplots we need to remove - else if(oldSubplotList.cartesian) { - for(i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { - var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } + if('yval' in evt) yvalArray = _$helpers_512.flat(subplots, evt.yval); + else yvalArray = _$helpers_512.p2c(yaArray, ypx); + + if(!_$fastIsnumeric_196(xvalArray[0]) || !_$fastIsnumeric_196(yvalArray[0])) { + _$lib_601.warn('Fx.hover failed', evt, gd); + return _$dragelement_495.unhoverRaw(gd, evt); } } -}; -_$cartesian_595.drawFramework = function(gd) { - var fullLayout = gd._fullLayout, - subplotData = makeSubplotData(gd); + // the pixel distance to beat as a matching point + // in 'x' or 'y' mode this resets for each trace + var distance = Infinity; - var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') - .data(subplotData, _$lib_539.identity); + // find the closest point in each trace + // this is minimum dx and/or dy, depending on mode + // and the pixel position for the label (labelXpx, labelYpx) + for(curvenum = 0; curvenum < searchData.length; curvenum++) { + cd = searchData[curvenum]; - subplotLayers.enter().append('g') - .attr('class', function(name) { return 'subplot ' + name; }); + // filter out invisible or broken data + if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; - subplotLayers.order(); + trace = cd[0].trace; - subplotLayers.exit() - .call(purgeSubplotLayers, fullLayout); + // Explicitly bail out for these two. I don't know how to otherwise prevent + // the rest of this function from running and failing + if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; - subplotLayers.each(function(name) { - var plotinfo = fullLayout._plots[name]; + if(trace.type === 'splom') { + // splom traces do not generate overlay subplots, + // it is safe to assume here splom traces correspond to the 0th subplot + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = _$helpers_512.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } - // keep ref to plot group - plotinfo.plotgroup = _$d3_127.select(this); + // within one trace mode can sometimes be overridden + mode = hovermode; - // initialize list of overlay subplots - plotinfo.overlays = []; + // container for new point, also used to pass info into module.hoverPoints + pointData = { + // trace properties + cd: cd, + trace: trace, + xa: xaArray[subploti], + ya: yaArray[subploti], - makeSubplotLayer(plotinfo); - // fill in list of overlay subplots - if(plotinfo.mainplot) { - var mainplot = fullLayout._plots[plotinfo.mainplot]; - mainplot.overlays.push(plotinfo); - } + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, - // make separate drag layers for each subplot, - // but append them to paper rather than the plot groups, - // so they end up on top of the rest - plotinfo.draglayer = joinLayer(fullLayout._draggers, 'g', name); - }); -}; + // point properties - override all of these + index: false, // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance -_$cartesian_595.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(plotinfo); - plotOne(gd, plotinfo, cdSubplot); - _$plots_647.style(gd); -}; + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout, - subplots = Object.keys(fullLayout._plots); + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: undefined, + ySpike: undefined, - var subplotData = [], - overlays = []; + // where and how to display the hover label + color: _$color_473.defaultLine, // trace color + name: trace.name, + x0: undefined, + x1: undefined, + y0: undefined, + y1: undefined, + xLabelVal: undefined, + yLabelVal: undefined, + zLabelVal: undefined, + text: undefined + }; - for(var i = 0; i < subplots.length; i++) { - var subplot = subplots[i], - plotinfo = fullLayout._plots[subplot]; + // add ref to subplot object (non-cartesian case) + if(fullLayout[subplotId]) { + pointData.subplot = fullLayout[subplotId]._subplot; + } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; + closedataPreviousLength = hoverData.length; - var mainplot = xa2._id + ya2._id; - if(mainplot !== subplot && subplots.indexOf(mainplot) !== -1) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = fullLayout._plots[mainplot]; - overlays.push(subplot); + // for a highlighting array, figure out what + // we're searching for with this element + if(mode === 'array') { + var selection = evt[curvenum]; + if('pointNumber' in selection) { + pointData.index = selection.pointNumber; + mode = 'closest'; + } + else { + mode = ''; + if('xval' in selection) { + xval = selection.xval; + mode = 'x'; + } + if('yval' in selection) { + yval = selection.yval; + mode = mode ? 'closest' : 'y'; + } + } } else { - subplotData.push(subplot); + xval = xvalArray[subploti]; + yval = yvalArray[subploti]; } - } - - // main subplots before overlays - subplotData = subplotData.concat(overlays); - - return subplotData; -} - -function makeSubplotLayer(plotinfo) { - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var xLayer = _$constants_589.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = _$constants_589.layerValue2layerClass[plotinfo.yaxis.layer]; - if(!plotinfo.mainplot) { - var backLayer = joinLayer(plotgroup, 'g', 'layer-subplot'); - plotinfo.shapelayer = joinLayer(backLayer, 'g', 'shapelayer'); - plotinfo.imagelayer = joinLayer(backLayer, 'g', 'imagelayer'); + // Now if there is range to look in, find the points to hover. + if(hoverdistance !== 0) { + if(trace._module && trace._module.hoverPoints) { + var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); + if(newPoints) { + var newPoint; + for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { + newPoint = newPoints[newPointNum]; + if(_$fastIsnumeric_196(newPoint.x0) && _$fastIsnumeric_196(newPoint.y0)) { + hoverData.push(cleanPoint(newPoint, hovermode)); + } + } + } + } + else { + _$lib_601.log('Unrecognized trace type in hover:', trace); + } + } - plotinfo.gridlayer = joinLayer(plotgroup, 'g', 'gridlayer'); + // in closest mode, remove any existing (farther) points + // and don't look any farther than this latest point (or points, some + // traces like box & violin make multiple hover labels at once) + if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } - plotinfo.zerolinelayer = joinLayer(plotgroup, 'g', 'zerolinelayer'); + // Now if there is range to look in, find the points to draw the spikelines + // Do it only if there is no hoverData + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); + if(closestPoints) { + closestPoints = closestPoints.filter(function(point) { + // some hover points, like scatter fills, do not allow spikes, + // so will generate a hover point but without a valid spikeDistance + return point.spikeDistance <= spikedistance; + }); + } + if(closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes; + }); + if(closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if(_$fastIsnumeric_196(closestVPt.x0) && _$fastIsnumeric_196(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.vLinePoint = tmpPoint; + } + } + } - joinLayer(plotgroup, 'path', 'xlines-below'); - joinLayer(plotgroup, 'path', 'ylines-below'); - plotinfo.overlinesBelow = joinLayer(plotgroup, 'g', 'overlines-below'); + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes; + }); + if(closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if(_$fastIsnumeric_196(closestHPt.x0) && _$fastIsnumeric_196(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } + } - joinLayer(plotgroup, 'g', 'xaxislayer-below'); - joinLayer(plotgroup, 'g', 'yaxislayer-below'); - plotinfo.overaxesBelow = joinLayer(plotgroup, 'g', 'overaxes-below'); + function selectClosestPoint(pointsData, spikedistance) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for(var i = 0; i < pointsData.length; i++) { + thisSpikeDistance = pointsData[i].spikeDistance; + if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { + resultPoint = pointsData[i]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } - plotinfo.plot = joinLayer(plotgroup, 'g', 'plot'); - plotinfo.overplot = joinLayer(plotgroup, 'g', 'overplot'); + function fillSpikePoint(point) { + if(!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } - joinLayer(plotgroup, 'path', 'xlines-above'); - joinLayer(plotgroup, 'path', 'ylines-above'); - plotinfo.overlinesAbove = joinLayer(plotgroup, 'g', 'overlines-above'); + var spikelineOpts = { + fullLayout: fullLayout, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + event: evt + }; + var oldspikepoints = gd._spikepoints, + newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; - joinLayer(plotgroup, 'g', 'xaxislayer-above'); - joinLayer(plotgroup, 'g', 'yaxislayer-above'); - plotinfo.overaxesAbove = joinLayer(plotgroup, 'g', 'overaxes-above'); + // Now if it is not restricted by spikedistance option, set the points to draw the spikelines + if(hasCartesian && (spikedistance !== 0)) { + if(hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); - // set refs to correct layers as determined by 'axis.layer' - plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); - plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); - plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); - plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } } - else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + '-x'; - var yId = id + '-y'; - - // now make the components of overlaid subplots - // overlays don't have backgrounds, and append all - // their other components to the corresponding - // extra groups of their main plots. - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + // if hoverData is empty check for the spikes to draw and quit if there are none + if(hoverData.length === 0) { + var result = _$dragelement_495.unhoverRaw(gd, evt); + if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } + return result; + } - joinLayer(mainplotinfo.overlinesBelow, 'path', xId); - joinLayer(mainplotinfo.overlinesBelow, 'path', yId); - joinLayer(mainplotinfo.overaxesBelow, 'g', xId); - joinLayer(mainplotinfo.overaxesBelow, 'g', yId); + if(hasCartesian) { + if(spikesChanged(oldspikepoints)) { + createSpikelines(spikePoints, spikelineOpts); + } + } - plotinfo.plot = joinLayer(mainplotinfo.overplot, 'g', id); + hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); - joinLayer(mainplotinfo.overlinesAbove, 'path', xId); - joinLayer(mainplotinfo.overlinesAbove, 'path', yId); - joinLayer(mainplotinfo.overaxesAbove, 'g', xId); - joinLayer(mainplotinfo.overaxesAbove, 'g', yId); + // lastly, emit custom hover/unhover events + var oldhoverdata = gd._hoverdata, + newhoverdata = []; - // set refs to correct layers as determined by 'abovetraces' - plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); - plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); - plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); - plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + // pull out just the data that's useful to + // other people and send it to the event + for(itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + newhoverdata.push(_$helpers_512.makeEventData(pt, pt.trace, pt.cd)); } - joinLayer(plotinfo.gridlayer, 'g', plotinfo.xaxis._id, plotinfo.xaxis._id); - joinLayer(plotinfo.gridlayer, 'g', plotinfo.yaxis._id, plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_587.idSort); + gd._hoverdata = newhoverdata; - // common attributes for all subplots, overlays or not + // if there's more than one horz bar trace, + // rotate the labels so they don't overlap + var rotateLabels = hovermode === 'y' && searchData.length > 1; - for(var i = 0; i < _$constants_589.traceLayerClasses.length; i++) { - joinLayer(plotinfo.plot, 'g', _$constants_589.traceLayerClasses[i]); - } + var bgColor = _$color_473.combine( + fullLayout.plot_bgcolor || _$color_473.background, + fullLayout.paper_bgcolor + ); - plotinfo.xlines - .style('fill', 'none') - .classed('crisp', true); + var labelOpts = { + hovermode: hovermode, + rotateLabels: rotateLabels, + bgColor: bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paperdiv, + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }; - plotinfo.ylines - .style('fill', 'none') - .classed('crisp', true); -} + var hoverLabels = createHoverText(hoverData, labelOpts, gd); -function purgeSubplotLayers(layers, fullLayout) { - if(!layers) return; + hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); - var overlayIdsToRemove = {}; + alignHoverText(hoverLabels, rotateLabels); - layers.each(function(subplotId) { - var plotgroup = _$d3_127.select(this); + // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true + // we should improve the "fx" API so other plots can use it without these hack. + if(evt.target && evt.target.tagName) { + var hasClickToShow = _$registry_731.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); + _$overrideCursor_612(_$d3_130.select(evt.target), hasClickToShow ? 'pointer' : ''); + } - plotgroup.remove(); - removeSubplotExtras(subplotId, fullLayout); + // don't emit events if called manually + if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; - overlayIdsToRemove[subplotId] = true; + if(oldhoverdata) { + gd.emit('plotly_unhover', { + event: evt, + points: oldhoverdata + }); + } - // do not remove individual axis s here - // as other subplots may need them + gd.emit('plotly_hover', { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray }); +} - // must remove overlaid subplot trace layers 'manually' +function createHoverText(hoverData, opts, gd) { + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; - var subplots = fullLayout._plots; - var subplotIds = Object.keys(subplots); + // opts.fontFamily/Size are used for the common label + // and as defaults for each hover label, though the individual labels + // can override this. + var fontFamily = opts.fontFamily || _$constants_510.HOVERFONT; + var fontSize = opts.fontSize || _$constants_510.HOVERFONTSIZE; - for(var i = 0; i < subplotIds.length; i++) { - var subplotInfo = subplots[subplotIds[i]]; - var overlays = subplotInfo.overlays || []; + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; + var t0 = c0[commonAttr]; + var t00 = (String(t0) || '').split(' ')[0]; + var outerContainerBB = outerContainer.node().getBoundingClientRect(); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; - for(var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; + // show the common label, if any, on the axis + // never show a common label in array mode, + // even if sometimes there could be one + var showCommonLabel = ( + (t0 !== undefined) && + (c0.distance <= opts.hoverdistance) && + (hovermode === 'x' || hovermode === 'y') + ); - if(overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll('.trace').remove(); + // all hover traces hoverinfo must contain the hovermode + // to have common labels + if(showCommonLabel) { + var i, traceHoverinfo; + var allHaveZ = true; + for(i = 0; i < hoverData.length; i++) { + if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + + traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; + var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); + if(parts.indexOf('all') === -1 && + parts.indexOf(hovermode) === -1) { + showCommonLabel = false; + break; } } + + // xyz labels put all info in their main label, so have no need of a common label + if(allHaveZ) showCommonLabel = false; } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); - fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); -} + var commonLabel = container.selectAll('g.axistext') + .data(showCommonLabel ? [0] : []); + commonLabel.enter().append('g') + .classed('axistext', true); + commonLabel.exit().remove(); -function joinLayer(parent, nodeType, className, dataVal) { - var layer = parent.selectAll('.' + className) - .data([dataVal || 0]); + commonLabel.each(function() { + var label = _$d3_130.select(this); + var lpath = _$lib_601.ensureSingle(label, 'path', '', function(s) { + s.style({'stroke-width': '1px'}); + }); + var ltext = _$lib_601.ensureSingle(label, 'text', '', function(s) { + // prohibit tex interpretation until we can handle + // tex and regular text together + s.attr('data-notex', 1); + }); - layer.enter().append(nodeType) - .classed(className, true); + lpath.style({ + fill: commonLabelOpts.bgcolor || _$color_473.defaultLine, + stroke: commonLabelOpts.bordercolor || _$color_473.background, + }); - return layer; -} + ltext.text(t0) + .call(_$drawing_498.font, + commonLabelOpts.font.family || fontFamily, + commonLabelOpts.font.size || fontSize, + commonLabelOpts.font.color || _$color_473.background + ) + .call(_$svg_text_utils_625.positionText, 0, 0) + .call(_$svg_text_utils_625.convertToTspans, gd); -_$cartesian_595.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = _$d3_127.select(gd).selectAll('.svg-container'); - var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) - .selectAll('.gl-canvas-context, .gl-canvas-focus'); + label.attr('transform', ''); - function canvasToImage() { - var canvas = this; - var imageData = canvas.toDataURL('image/png'); - var image = imageRoot.append('svg:image'); + var tbb = ltext.node().getBoundingClientRect(); + if(hovermode === 'x') { + ltext.attr('text-anchor', 'middle') + .call(_$svg_text_utils_625.positionText, 0, (xa.side === 'top' ? + (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : + (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); - image.attr({ - xmlns: _$xmlns_namespaces_519.svg, - 'xlink:href': imageData, - preserveAspectRatio: 'none', - x: 0, - y: 0, - width: canvas.width, - height: canvas.height + var topsign = xa.side === 'top' ? '-' : ''; + lpath.attr('d', 'M0,0' + + 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + + 'H' + (HOVERTEXTPAD + tbb.width / 2) + + 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + + 'H-' + (HOVERTEXTPAD + tbb.width / 2) + + 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); + + label.attr('transform', 'translate(' + + (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + + (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); + } + else { + ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') + .call(_$svg_text_utils_625.positionText, + (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), + outerTop - tbb.top - tbb.height / 2); + + var leftsign = ya.side === 'right' ? '' : '-'; + lpath.attr('d', 'M0,0' + + 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + + 'V' + (HOVERTEXTPAD + tbb.height / 2) + + 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + + 'V-' + (HOVERTEXTPAD + tbb.height / 2) + + 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); + + label.attr('transform', 'translate(' + + (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + + (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); + } + // remove the "close but not quite" points + // because of error bars, only take up to a space + hoverData = hoverData.filter(function(d) { + return (d.zLabelVal !== undefined) || + (d[commonAttr] || '').split(' ')[0] === t00; }); - } + }); - canvases.each(canvasToImage); -}; + // show all the individual labels -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // first create the objects + var hoverLabels = container.selectAll('g.hovertext') + .data(hoverData, function(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); + }); + hoverLabels.enter().append('g') + .classed('hovertext', true) + .each(function() { + var g = _$d3_130.select(this); + // trace name label (rect and text.name) + g.append('rect') + .call(_$color_473.fill, _$color_473.addOpacity(bgColor, 0.8)); + g.append('text').classed('name', true); + // trace data label (path and text.nums) + g.append('path') + .style('stroke-width', '1px'); + g.append('text').classed('nums', true) + .call(_$drawing_498.font, fontFamily, fontSize); + }); + hoverLabels.exit().remove(); + // then put the text in, position the pointer to the data, + // and figure out sizes + hoverLabels.each(function(d) { + var g = _$d3_130.select(this).attr('transform', ''), + name = '', + text = ''; -'use strict'; + // combine possible non-opaque trace color with bgColor + var baseColor = _$color_473.opacity(d.color) ? d.color : _$color_473.defaultLine; + var traceColor = _$color_473.combine(baseColor, bgColor); -var mergeArray = _$lib_539.mergeArray; + // find a contrasting color for border and text + var contrastColor = d.borderColor || _$color_473.contrast(traceColor); + // to get custom 'name' labels pass cleanPoint + if(d.nameOverride !== undefined) d.name = d.nameOverride; -// arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_677 = function arraysToCalcdata(cd, trace) { - for(var i = 0; i < cd.length; i++) cd[i].i = i; + if(d.name) { + // strip out our pseudo-html elements from d.name (if it exists at all) + name = _$svg_text_utils_625.plainText(d.name || ''); - mergeArray(trace.text, cd, 'tx'); - mergeArray(trace.hovertext, cd, 'htx'); + var nameLength = Math.round(d.nameLength); - var marker = trace.marker; - if(marker) { - mergeArray(marker.opacity, cd, 'mo'); - mergeArray(marker.color, cd, 'mc'); + if(nameLength > -1 && name.length > nameLength) { + if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; + else name = name.substr(0, nameLength); + } + } - var markerLine = marker.line; - if(markerLine) { - mergeArray(markerLine.color, cd, 'mlc'); - mergeArray(markerLine.width, cd, 'mlw'); + if(d.zLabel !== undefined) { + if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; + if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; + text += (text ? 'z: ' : '') + d.zLabel; } - } -}; + else if(showCommonLabel && d[hovermode + 'Label'] === t0) { + text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; + } + else if(d.xLabel === undefined) { + if(d.yLabel !== undefined) text = d.yLabel; + } + else if(d.yLabel === undefined) text = d.xLabel; + else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + if(d.text && !Array.isArray(d.text)) { + text += (text ? '
' : '') + d.text; + } -'use strict'; + // used by other modules (initially just ternary) that + // manage their own hoverinfo independent of cleanPoint + // the rest of this will still apply, so such modules + // can still put things in (x|y|z)Label, text, and name + // and hoverinfo will still determine their visibility + if(d.extraText !== undefined) text += (text ? '
' : '') + d.extraText; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; + // if 'text' is empty at this point, + // put 'name' in main label and don't show secondary label + if(text === '') { + // if 'name' is also empty, remove entire label + if(name === '') g.remove(); + text = name; + } -var __extendFlat_678 = _$extend_528.extendFlat; + // main label + var tx = g.select('text.nums') + .call(_$drawing_498.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + d.fontColor || contrastColor) + .text(text) + .attr('data-notex', 1) + .call(_$svg_text_utils_625.positionText, 0, 0) + .call(_$svg_text_utils_625.convertToTspans, gd); -var textFontAttrs = _$font_attributes_611({ - editType: 'calc', - arrayOk: true, - -}); + var tx2 = g.select('text.name'), + tx2width = 0; -var __scatterMarkerAttrs_678 = _$attributes_862.marker; -var scatterMarkerLineAttrs = __scatterMarkerAttrs_678.line; + // secondary label for non-empty 'name' + if(name && name !== text) { + tx2.call(_$drawing_498.font, + d.fontFamily || fontFamily, + d.fontSize || fontSize, + traceColor) + .text(name) + .attr('data-notex', 1) + .call(_$svg_text_utils_625.positionText, 0, 0) + .call(_$svg_text_utils_625.convertToTspans, gd); + tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; + } + else { + tx2.remove(); + g.select('rect').remove(); + } -var markerLineWidth = __extendFlat_678({}, - scatterMarkerLineAttrs.width, { dflt: 0 }); + g.select('path') + .style({ + fill: traceColor, + stroke: contrastColor + }); + var tbb = tx.node().getBoundingClientRect(), + htx = d.xa._offset + (d.x0 + d.x1) / 2, + hty = d.ya._offset + (d.y0 + d.y1) / 2, + dx = Math.abs(d.x1 - d.x0), + dy = Math.abs(d.y1 - d.y0), + txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, + anchorStartOK, + anchorEndOK; -var markerLine = __extendFlat_678({ - width: markerLineWidth, - editType: 'calc' -}, _$makeColorScaleAttributes_419('marker.line')); + d.ty0 = outerTop - tbb.top; + d.bx = tbb.width + 2 * HOVERTEXTPAD; + d.by = tbb.height + 2 * HOVERTEXTPAD; + d.anchor = 'start'; + d.txwidth = tbb.width; + d.tx2width = tx2width; + d.offset = 0; -var marker = __extendFlat_678({ - line: markerLine, - editType: 'calc' -}, _$makeColorScaleAttributes_419('marker'), { - showscale: __scatterMarkerAttrs_678.showscale, - colorbar: _$attributes_412, - opacity: { - valType: 'number', - arrayOk: true, - dflt: 1, - min: 0, - max: 1, - - editType: 'style', - - } -}); + if(rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + hty += dy / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } + else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = 'end'; + } else if(anchorStartOK) { + htx += dx / 2; + d.anchor = 'start'; + } else d.anchor = 'middle'; + } -var _$attributes_678 = { - x: _$attributes_862.x, - x0: _$attributes_862.x0, - dx: _$attributes_862.dx, - y: _$attributes_862.y, - y0: _$attributes_862.y0, - dy: _$attributes_862.dy, + tx.attr('text-anchor', d.anchor); + if(tx2width) tx2.attr('text-anchor', d.anchor); + g.attr('transform', 'translate(' + htx + ',' + hty + ')' + + (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); + }); - text: _$attributes_862.text, - hovertext: _$attributes_862.hovertext, + return hoverLabels; +} - textposition: { - valType: 'enumerated', - - values: ['inside', 'outside', 'auto', 'none'], - dflt: 'none', - arrayOk: true, - editType: 'calc', - - }, +// Make groups of touching points, and within each group +// move each point so that no labels overlap, but the average +// label position is the same as it was before moving. Indicentally, +// this is equivalent to saying all the labels are on equal linear +// springs about their initial position. Initially, each point is +// its own group, but as we find overlaps we will clump the points. +// +// Also, there are hard constraints at the edges of the graphs, +// that push all groups to the middle so they are visible. I don't +// know what happens if the group spans all the way from one edge to +// the other, though it hardly matters - there's just too much +// information then. +function hoverAvoidOverlaps(hoverData, ax, fullLayout) { + var nummoves = 0, - textfont: __extendFlat_678({}, textFontAttrs, { - - }), + // make groups of touching points + pointgroups = hoverData + .map(function(d, i) { + var axis = d[ax]; + return [{ + i: i, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, + pmin: 0, + pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) + }]; + }) + .sort(function(a, b) { return a[0].posref - b[0].posref; }), + donepositioning, + topOverlap, + bottomOverlap, + i, j, + pti, + sumdp; - insidetextfont: __extendFlat_678({}, textFontAttrs, { - - }), + function constrainGroup(grp) { + var minPt = grp[0], + maxPt = grp[grp.length - 1]; - outsidetextfont: __extendFlat_678({}, textFontAttrs, { - - }), + // overlap with the top - positive vals are overlaps + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; - constraintext: { - valType: 'enumerated', - values: ['inside', 'outside', 'both', 'none'], - - dflt: 'both', - editType: 'calc', - - }, + // overlap with the bottom - positive vals are overlaps + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; - cliponaxis: __extendFlat_678({}, _$attributes_862.cliponaxis, { - - }), + // check for min overlap first, so that we always + // see the largest labels + // allow for .01px overlap, so we don't get an + // infinite loop from rounding errors + if(topOverlap > 0.01) { + for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; + donepositioning = false; + } + if(bottomOverlap < 0.01) return; + if(topOverlap < -0.01) { + // make sure we're not pushing back and forth + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + donepositioning = false; + } + if(!donepositioning) return; - orientation: { - valType: 'enumerated', - - values: ['v', 'h'], - editType: 'calc+clearAxisTypes', - - }, + // no room to fix positioning, delete off-screen points - base: { - valType: 'any', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, + // first see how many points we need to delete + var deleteCount = 0; + for(i = 0; i < grp.length; i++) { + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } - offset: { - valType: 'number', - dflt: null, - arrayOk: true, - - editType: 'calc', - - }, - - width: { - valType: 'number', - dflt: null, - min: 0, - arrayOk: true, - - editType: 'calc', - - }, - - marker: marker, + // start by deleting points whose data is off screen + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; - selected: { - marker: { - opacity: _$attributes_862.selected.marker.opacity, - color: _$attributes_862.selected.marker.color, - editType: 'style' - }, - textfont: _$attributes_862.selected.textfont, - editType: 'style' - }, - unselected: { - marker: { - opacity: _$attributes_862.unselected.marker.opacity, - color: _$attributes_862.unselected.marker.color, - editType: 'style' - }, - textfont: _$attributes_862.unselected.textfont, - editType: 'style' - }, + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } + } + for(i = 0; i < grp.length; i++) { + if(deleteCount <= 0) break; + pti = grp[i]; - r: _$attributes_862.r, - t: _$attributes_862.t, + // pos has already been constrained to [pmin,pmax] + // so look for points close to that to delete + if(pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; - _deprecated: { - bardir: { - valType: 'enumerated', - - editType: 'calc', - values: ['v', 'h'], - + // shift the whole group minus into this new space + bottomOverlap = pti.size * 2; + for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + } + } + // then delete points that go off the bottom + for(i = grp.length - 1; i >= 0; i--) { + if(deleteCount <= 0) break; + pti = grp[i]; + if(pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } } } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // loop through groups, combining them if they overlap, + // until nothing moves + while(!donepositioning && nummoves <= hoverData.length) { + // to avoid infinite loops, don't move more times + // than there are traces + nummoves++; -'use strict'; + // assume nothing will move in this iteration, + // reverse this if it does + donepositioning = true; + i = 0; + while(i < pointgroups.length - 1) { + // the higher (g0) and lower (g1) point group + var g0 = pointgroups[i], + g1 = pointgroups[i + 1], + + // the lowest point in the higher group (p0) + // the highest point in the lower group (p1) + p0 = g0[g0.length - 1], + p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; + + // Only group points that lie on the same axes + if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { + // push the new point(s) added to this group out of the way + for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; + + // add them to the group + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); -/* removed: var _$lib_539 = require('../../lib'); */; + // adjust for minimum average movement + sumdp = 0; + for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } + else i++; + } -var _$calcSelection_864 = function calcSelection(cd, trace) { - if(_$lib_539.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_539.tagSelected(cd, trace); + // check if we're going off the plot on either side and fix + pointgroups.forEach(constrainGroup); } -}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // now put these offsets into hoverData + for(i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for(j = grp.length - 1; j >= 0; j--) { + var pt = grp[j], + hoverPt = hoverData[pt.i]; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } + } +} +function alignHoverText(hoverLabels, rotateLabels) { + // finally set the text positioning relative to the data and draw the + // box around it + hoverLabels.each(function(d) { + var g = _$d3_130.select(this); + if(d.del) { + g.remove(); + return; + } + var horzSign = d.anchor === 'end' ? -1 : 1, + tx = g.select('text.nums'), + alignShift = {start: 1, end: -1, middle: 0}[d.anchor], + txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), + tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), + offsetX = 0, + offsetY = d.offset; + if(d.anchor === 'middle') { + txx -= d.tx2width / 2; + tx2x += d.txwidth / 2 + HOVERTEXTPAD; + } + if(rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = d.offset * YSHIFTX; + } -'use strict'; + g.select('path').attr('d', d.anchor === 'middle' ? + // middle aligned: rect centered on data + ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + + 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : + // left or right aligned: side rect with arrow to data + ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + + 'v' + (d.by / 2 - HOVERARROWSIZE) + + 'h' + (horzSign * d.bx) + + 'v-' + d.by + + 'H' + (horzSign * HOVERARROWSIZE + offsetX) + + 'V' + (offsetY - HOVERARROWSIZE) + + 'Z')); -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_679 = _$lib_539.isArrayOrTypedArray; + tx.call(_$svg_text_utils_625.positionText, + txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_677 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; + if(d.tx2width) { + g.select('text.name') + .call(_$svg_text_utils_625.positionText, + tx2x + alignShift * HOVERTEXTPAD + offsetX, + offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + g.select('rect') + .call(_$drawing_498.setRect, + tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, + offsetY - d.by / 2 - 1, + d.tx2width, d.by + 2); + } + }); +} -var _$calc_679 = function calc(gd, trace) { - // depending on bar direction, set position and size axes - // and data ranges - // note: this logic for choosing orientation is - // duplicated in graph_obj->setstyles +function cleanPoint(d, hovermode) { + var index = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index] || {}; - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'), - orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), - sa, pos, size, i, scalendar; + var getVal = Array.isArray(index) ? + function(calcKey, traceKey) { + return _$lib_601.castOption(cd0, index, calcKey) || + _$lib_601.extractOption({}, trace, '', traceKey); + } : + function(calcKey, traceKey) { + return _$lib_601.extractOption(cd, trace, calcKey, traceKey); + }; - if(orientation === 'h') { - sa = xa; - size = xa.makeCalcdata(trace, 'x'); - pos = ya.makeCalcdata(trace, 'y'); + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if(val) d[key] = val; + } - // 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. - scalendar = trace.xcalendar; + fill('hoverinfo', 'hi', 'hoverinfo'); + fill('color', 'hbg', 'hoverlabel.bgcolor'); + fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); + fill('fontFamily', 'htf', 'hoverlabel.font.family'); + fill('fontSize', 'hts', 'hoverlabel.font.size'); + fill('fontColor', 'htc', 'hoverlabel.font.color'); + fill('nameLength', 'hnl', 'hoverlabel.namelength'); + + d.posref = hovermode === 'y' ? + (d.xa._offset + (d.x0 + d.x1) / 2) : + (d.ya._offset + (d.y0 + d.y1) / 2); + + // then constrain all the positions to be on the plot + d.x0 = _$lib_601.constrain(d.x0, 0, d.xa._length); + d.x1 = _$lib_601.constrain(d.x1, 0, d.xa._length); + d.y0 = _$lib_601.constrain(d.y0, 0, d.ya._length); + d.y1 = _$lib_601.constrain(d.y1, 0, d.ya._length); + + // and convert the x and y label values into formatted text + if(d.xLabelVal !== undefined) { + d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_647.hoverLabelText(d.xa, d.xLabelVal); + d.xVal = d.xa.c2d(d.xLabelVal); } - else { - sa = ya; - size = ya.makeCalcdata(trace, 'y'); - pos = xa.makeCalcdata(trace, 'x'); - scalendar = trace.ycalendar; + if(d.yLabelVal !== undefined) { + d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_647.hoverLabelText(d.ya, d.yLabelVal); + d.yVal = d.ya.c2d(d.yLabelVal); } - // create the "calculated data" to plot - var serieslen = Math.min(pos.length, size.length); - var cd = new Array(serieslen); + // Traces like heatmaps generate the zLabel in their hoverPoints function + if(d.zLabelVal !== undefined && d.zLabel === undefined) { + d.zLabel = String(d.zLabelVal); + } - // set position and size - for(i = 0; i < serieslen; i++) { - cd[i] = { p: pos[i], s: size[i] }; + // for box means and error bars, add the range to the label + if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { + var xeText = _$axes_647.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; + if(d.xerrneg !== undefined) { + d.xLabel += ' +' + xeText + ' / -' + + _$axes_647.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; + } + else d.xLabel += ' ± ' + xeText; - if(trace.ids) { - cd[i].id = String(trace.ids[i]); + // small distance penalty for error bars, so that if there are + // traces with errors and some without, the error bar label will + // hoist up to the point + if(hovermode === 'x') d.distance += 1; + } + if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { + var yeText = _$axes_647.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; + if(d.yerrneg !== undefined) { + d.yLabel += ' +' + yeText + ' / -' + + _$axes_647.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; } + else d.yLabel += ' ± ' + yeText; + + if(hovermode === 'y') d.distance += 1; } - // set base - var base = trace.base, - b; + var infomode = d.hoverinfo || d.trace.hoverinfo; - if(__isArrayOrTypedArray_679(base)) { - for(i = 0; i < Math.min(base.length, cd.length); i++) { - b = sa.d2c(base[i], 0, scalendar); - if(_$fastIsnumeric_139(b)) { - cd[i].b = +b; - cd[i].hasB = 1; + if(infomode !== 'all') { + infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); + if(infomode.indexOf('x') === -1) d.xLabel = undefined; + if(infomode.indexOf('y') === -1) d.yLabel = undefined; + if(infomode.indexOf('z') === -1) d.zLabel = undefined; + if(infomode.indexOf('text') === -1) d.text = undefined; + if(infomode.indexOf('name') === -1) d.name = undefined; + } + + return d; +} + +function createSpikelines(closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var evt = opts.event; + var xa, + ya; + + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; + + // Remove old spikeline items + container.selectAll('.spikeline').remove(); + + if(!(showX || showY)) return; + + var contrastColor = _$color_473.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + + // Horizontal line (to y-axis) + if(showY) { + var hLinePoint = closestPoints.hLinePoint, + hLinePointX, + hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; + + if(ySnap === 'cursor') { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = _$tinycolor_414.readability(hLinePoint.color, contrastColor) < 1.5 ? + _$color_473.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode, + yThickness = ya.spikethickness, + yColor = ya.spikecolor || dfltHLineColor, + yBB = ya._boundingBox, + xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, + xBase, + xEndSpike; + + if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { + if(yMode.indexOf('toaxis') !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; } - else cd[i].b = 0; + if(yMode.indexOf('across') !== -1) { + xBase = ya._counterSpan[0]; + xEndSpike = ya._counterSpan[1]; + } + + // Foreground horizontal line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness, + 'stroke': yColor, + 'stroke-dasharray': _$drawing_498.dashStyle(ya.spikedash, yThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background horizontal Line (to y-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': xBase, + 'x2': xEndSpike, + 'y1': hLinePointY, + 'y2': hLinePointY, + 'stroke-width': yThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); } - for(; i < cd.length; i++) { - cd[i].b = 0; + // Y axis marker + if(yMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), + 'cy': hLinePointY, + 'r': yThickness, + 'fill': yColor + }) + .classed('spikeline', true); } } - else { - b = sa.d2c(base, 0, scalendar); - var hasBase = _$fastIsnumeric_139(b); - b = hasBase ? b : 0; - for(i = 0; i < cd.length; i++) { - cd[i].b = b; - if(hasBase) cd[i].hasB = 1; + + if(showX) { + var vLinePoint = closestPoints.vLinePoint, + vLinePointX, + vLinePointY; + + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; + + if(xSnap === 'cursor') { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; } - } + var dfltVLineColor = _$tinycolor_414.readability(vLinePoint.color, contrastColor) < 1.5 ? + _$color_473.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode, + xThickness = xa.spikethickness, + xColor = xa.spikecolor || dfltVLineColor, + xBB = xa._boundingBox, + yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, + yBase, + yEndSpike; - // auto-z and autocolorscale if applicable - if(_$hasColorscale_425(trace, 'marker')) { - _$calc_418(trace, trace.marker.color, 'marker', 'c'); - } - if(_$hasColorscale_425(trace, 'marker.line')) { - _$calc_418(trace, trace.marker.line.color, 'marker.line', 'c'); + if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { + if(xMode.indexOf('toaxis') !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if(xMode.indexOf('across') !== -1) { + yBase = xa._counterSpan[0]; + yEndSpike = xa._counterSpan[1]; + } + + // Foreground vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness, + 'stroke': xColor, + 'stroke-dasharray': _$drawing_498.dashStyle(xa.spikedash, xThickness) + }) + .classed('spikeline', true) + .classed('crisp', true); + + // Background vertical line (to x-axis) + container.insert('line', ':first-child') + .attr({ + 'x1': vLinePointX, + 'x2': vLinePointX, + 'y1': yBase, + 'y2': yEndSpike, + 'stroke-width': xThickness + 2, + 'stroke': contrastColor + }) + .classed('spikeline', true) + .classed('crisp', true); + } + + // X axis marker + if(xMode.indexOf('marker') !== -1) { + container.insert('circle', ':first-child') + .attr({ + 'cx': vLinePointX, + 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), + 'r': xThickness, + 'fill': xColor + }) + .classed('spikeline', true); + } } +} - _$arraysToCalcdata_677(cd, trace); - _$calcSelection_864(cd, trace); +function hoverChanged(gd, evt, oldhoverdata) { + // don't emit any events if nothing changed + if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; - return cd; -}; + for(var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i], + newPt = gd._hoverdata[i]; + if(oldPt.curveNumber !== newPt.curveNumber || + String(oldPt.pointNumber) !== String(newPt.pointNumber)) { + return true; + } + } + return false; +} + +function spikesChanged(gd, oldspikepoints) { + // don't relayout the plot because of new spikelines if spikelines points didn't change + if(!oldspikepoints) return true; + if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || + oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint + ) return true; + return false; +} /** * Copyright 2012-2018, Plotly, Inc. @@ -31064,34 +32021,33 @@ var _$calc_679 = function calc(gd, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +var hover = _$hover_513.hover; -var _$handleStyleDefaults_690 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { - coerce('marker.color', defaultColor); +var _$click_509 = function click(gd, evt, subplot) { + var annotationsDone = _$registry_731.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata); - if(_$hasColorscale_425(traceIn, 'marker')) { - _$colorScaleDefaults_421( - traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} - ); + // 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); } - coerce('marker.line.color', _$color_411.defaultLine); + function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } - if(_$hasColorscale_425(traceIn, 'marker.line')) { - _$colorScaleDefaults_421( - traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} - ); - } + if(gd._hoverdata && evt && evt.target) { + if(annotationsDone && annotationsDone.then) { + annotationsDone.then(emitClick); + } + else emitClick(); - coerce('marker.line.width'); - coerce('marker.opacity'); - coerce('selected.marker.color'); - coerce('unselected.marker.color'); + // why do we get a double event without this??? + if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); + } }; /** @@ -31102,41 +32058,17 @@ var _$handleStyleDefaults_690 = function handleStyleDefaults(traceIn, traceOut, * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - - -var _$handleXYDefaults_886 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { - var len, - x = coerce('x'), - y = coerce('y'); - - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); - handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); - - if(x) { - if(y) { - len = Math.min(x.length, y.length); - } - else { - len = x.length; - coerce('y0'); - coerce('dy'); - } - } - else { - if(!y) return 0; - - len = traceOut.y.length; - coerce('x0'); - coerce('dx'); - } +/* removed: var _$lib_601 = require('../../lib'); */; - traceOut._length = len; +var _$handleHoverLabelDefaults_514 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { + opts = opts || {}; - return len; + coerce('hoverlabel.bgcolor', opts.bgcolor); + coerce('hoverlabel.bordercolor', opts.bordercolor); + coerce('hoverlabel.namelength', opts.namelength); + _$lib_601.coerceFont(coerce, 'hoverlabel.font', opts.font); }; /** @@ -31147,133 +32079,105 @@ var _$handleXYDefaults_886 = function handleXYDefaults(traceIn, traceOut, layout * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_507 = require('./attributes'); */; +/* removed: var _$handleHoverLabelDefaults_514 = require('./hoverlabel_defaults'); */; -/* removed: var _$handleXYDefaults_886 = require('../scatter/xy_defaults'); */; -/* removed: var _$handleStyleDefaults_690 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_678 = require('./attributes'); */; - -var _$supplyDefaults_680 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_511 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_678, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_507, attr, dflt); } - var coerceFont = _$lib_539.coerceFont; - - var len = _$handleXYDefaults_886(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; - } + _$handleHoverLabelDefaults_514(traceIn, traceOut, coerce, layout.hoverlabel); +}; - coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); - coerce('base'); - coerce('offset'); - coerce('width'); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('text'); - coerce('hovertext'); +'use strict'; - var textPosition = coerce('textposition'); +/* removed: var _$constants_510 = require('./constants'); */; - var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', - hasInside = hasBoth || textPosition === 'inside', - hasOutside = hasBoth || textPosition === 'outside'; +var __fontAttrs_516 = _$font_attributes_673({ + editType: 'none', + +}); +__fontAttrs_516.family.dflt = _$constants_510.HOVERFONT; +__fontAttrs_516.size.dflt = _$constants_510.HOVERFONTSIZE; - if(hasInside || hasOutside) { - var textFont = coerceFont(coerce, 'textfont', layout.font); - if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); - if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); - coerce('constraintext'); - coerce('selected.textfont.color'); - coerce('unselected.textfont.color'); - coerce('cliponaxis'); +var _$layout_attributes_516 = { + dragmode: { + valType: 'enumerated', + + values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], + dflt: 'zoom', + editType: 'modebar', + + }, + hovermode: { + valType: 'enumerated', + + values: ['x', 'y', 'closest', false], + editType: 'modebar', + + }, + hoverdistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + spikedistance: { + valType: 'integer', + min: -1, + dflt: 20, + + editType: 'none', + + }, + hoverlabel: { + bgcolor: { + valType: 'color', + + editType: 'none', + + }, + bordercolor: { + valType: 'color', + + editType: 'none', + + }, + font: __fontAttrs_516, + namelength: { + valType: 'integer', + min: -1, + dflt: 15, + + editType: 'none', + + }, + editType: 'none' + }, + selectdirection: { + valType: 'enumerated', + + values: ['h', 'v', 'd', 'any'], + dflt: 'any', + + editType: 'none' } - - _$handleStyleDefaults_690(traceIn, traceOut, coerce, defaultColor, layout); - - // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'x', inherit: 'y'}); - - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); }; -var _$client_246 = true; -var _$hasHover_239 = {}; -(function (global){ -'use strict' - -/* removed: var _$client_246 = require('is-browser') */; -var hasHover - -if (typeof global.matchMedia === 'function') { - hasHover = !global.matchMedia('(hover: none)').matches -} -else { - hasHover = _$client_246 -} - -_$hasHover_239 = hasHover - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -'use strict' - -/* removed: var _$client_246 = require('is-browser') */; - -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 -} - -var _$hasPassiveEvents_240 = _$client_246 && detect() - -var rootPosition = { left: 0, top: 0 } - -var _$mouseEventOffset_263 = mouseEventOffset -function mouseEventOffset (ev, target, out) { - target = target || ev.currentTarget || ev.srcElement - if (!Array.isArray(out)) { - out = [ 0, 0 ] - } - var cx = ev.clientX || 0 - var cy = ev.clientY || 0 - var rect = getBoundingClientOffset(target) - out[0] = cx - rect.left - out[1] = cy - rect.top - return out -} - -function getBoundingClientOffset (element) { - if (element === window || - element === document || - element === document.body) { - return rootPosition - } else { - return element.getBoundingClientRect() - } -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31282,30 +32186,64 @@ function getBoundingClientOffset (element) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_516 = require('./layout_attributes'); */; -// 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 -var _$align_431 = function align(v, dv, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0), - vmax = vmin + dv / (v1 - v0), - vc = (vmin + vmax) / 2; +var _$supplyLayoutDefaults_517 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + function coerce(attr, dflt) { + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_516, attr, dflt); + } - // explicitly specified anchor - if(anchor === 'left' || anchor === 'bottom') return vmin; - if(anchor === 'center' || anchor === 'middle') return vc; - if(anchor === 'right' || anchor === 'top') return vmax; + var dragMode = coerce('dragmode'); + if(dragMode === 'select') coerce('selectdirection'); - // automatic based on position - if(vmin < (2 / 3) - vc) return vmin; - if(vmax > (4 / 3) - vc) return vmax; - return vc; + var hovermodeDflt; + if(layoutOut._has('cartesian')) { + // flag for 'horizontal' plots: + // determines the state of the mode bar 'compare' hovermode button + layoutOut._isHoriz = isHoriz(fullData); + hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; + } + else hovermodeDflt = 'closest'; + + var hoverMode = coerce('hovermode', hovermodeDflt); + if(hoverMode) { + coerce('hoverdistance'); + coerce('spikedistance'); + } + + // if only mapbox or geo subplots is present on graph, + // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, + // so that the correct modebar button is active + var hasMapbox = layoutOut._has('mapbox'); + var hasGeo = layoutOut._has('geo'); + var len = layoutOut._basePlotModules.length; + + if(layoutOut.dragmode === 'zoom' && ( + ((hasMapbox || hasGeo) && len === 1) || + (hasMapbox && hasGeo && len === 2) + )) { + layoutOut.dragmode = 'pan'; + } }; +function isHoriz(fullData) { + var out = true; + + for(var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + + if(trace.orientation !== 'h') { + out = false; + break; + } + } + + return out; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -31314,33 +32252,18 @@ var _$align_431 = function align(v, dv, v0, v1, anchor) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; - - -// 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'] -]; - -var _$getCursor_432 = 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_539.constrain(Math.floor(x * 3), 0, 2); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleHoverLabelDefaults_514 = require('./hoverlabel_defaults'); */; +/* removed: var _$layout_attributes_516 = require('./layout_attributes'); */; - if(yanchor === 'bottom') y = 0; - else if(yanchor === 'middle') y = 1; - else if(yanchor === 'top') y = 2; - else y = _$lib_539.constrain(Math.floor(y * 3), 0, 2); +var _$supplyLayoutGlobalDefaults_518 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce(attr, dflt) { + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_516, attr, dflt); + } - return cursorset[y][x]; + _$handleHoverLabelDefaults_514(layoutIn, layoutOut, coerce); }; /** @@ -31353,843 +32276,3832 @@ var _$getCursor_432 = function getCursor(x, y, xanchor, yanchor) { 'use strict'; -var _$constants_448 = { - // hover labels for multiple horizontal bars get tilted by this angle - YANGLE: 60, +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$helpers_512 = require('./helpers'); */; +/* removed: var _$layout_attributes_516 = require('./layout_attributes'); */; - // size and display constants for hover text +var _$fx_515 = { + moduleType: 'component', + name: 'fx', - // pixel size of hover arrows - HOVERARROWSIZE: 6, - // pixels padding around text - HOVERTEXTPAD: 3, - // hover font - HOVERFONTSIZE: 13, - HOVERFONT: 'Arial, sans-serif', + constants: _$constants_510, + schema: { + layout: _$layout_attributes_516 + }, - // minimum time (msec) between hover calls - HOVERMINTIME: 50, + attributes: _$attributes_507, + layoutAttributes: _$layout_attributes_516, - // ID suffix (with fullLayout._uid) for hover events in the throttle cache - HOVERID: '-hover' -}; + supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_518, + supplyDefaults: _$supplyDefaults_511, + supplyLayoutDefaults: _$supplyLayoutDefaults_517, -// 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. + calc: _$calc_508, -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -var _$EventEmitter_137 = EventEmitter; + getDistanceFunction: _$helpers_512.getDistanceFunction, + getClosest: _$helpers_512.getClosest, + inbox: _$helpers_512.inbox, + quadrature: _$helpers_512.quadrature, + appendArrayPointValue: _$helpers_512.appendArrayPointValue, -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; + castHoverOption: castHoverOption, + castHoverinfo: castHoverinfo, -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; + hover: _$hover_513.hover, + unhover: _$dragelement_495.unhover, -// 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. -EventEmitter.defaultMaxListeners = 10; + loneHover: _$hover_513.loneHover, + loneUnhover: loneUnhover, -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; + click: _$click_509 }; -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; +function loneUnhover(containerOrSelection) { + // duck type whether the arg is a d3 selection because ie9 doesn't + // handle instanceof like modern browsers do. + var selection = _$lib_601.isD3Selection(containerOrSelection) ? + containerOrSelection : + _$d3_130.select(containerOrSelection); - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } + selection.selectAll('g.hovertext').remove(); + selection.selectAll('.spikeline').remove(); +} - handler = this._events[type]; +// helpers for traces that use Fx.loneHover - if (isUndefined(handler)) - return false; +function castHoverOption(trace, ptNumber, attr) { + return _$lib_601.castOption(trace, ptNumber, 'hoverlabel.' + attr); +} - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return _$lib_601.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - if (!this._events) - this._events = {}; + return _$lib_601.castOption(trace, ptNumber, 'hoverinfo', _coerce); +} - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; +'use strict'; - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } +/** + * 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 + */ +var _$clearGlCanvases_585 = function clearGlCanvases(gd) { + var fullLayout = gd._fullLayout; - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } + if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if(d.regl) d.regl.clear({color: true, depth: true}); + }); } - } - - return this; }; -EventEmitter.prototype.on = EventEmitter.prototype.addListener; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - var fired = false; +'use strict'; - function g() { - this.removeListener(type, g); +var FROM_BL = _$alignment_573.FROM_BL; - if (!fired) { - fired = true; - listener.apply(this, arguments); +var _$scaleZoom_663 = function scaleZoom(ax, factor, centerFraction) { + if(centerFraction === undefined) { + centerFraction = FROM_BL[ax.constraintoward || 'center']; } - } - g.listener = listener; - this.on(type, g); + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - return this; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; }; -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - if (!isFunction(listener)) - throw TypeError('listener must be a function'); +// +// used strictly for logging the processing of the algorithm... only useful if you intend on +// looking under the covers (for pretty UI's or debugging) +// - if (!this._events || !this._events[type]) - return this; +function BuildLog(){ + var my; + var nextSegmentId = 0; + var curVert = false; - list = this._events[type]; - length = list.length; - position = -1; + function push(type, data){ + my.list.push({ + type: type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; + my = { + list: [], + segmentId: function(){ + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2){ + return push('check', { seg1: seg1, seg2: seg2 }); + }, + segmentChop: function(seg, end){ + push('div_seg', { seg: seg, pt: end }); + return push('chop', { seg: seg, pt: end }); + }, + statusRemove: function(seg){ + return push('pop_seg', { seg: seg }); + }, + segmentUpdate: function(seg){ + return push('seg_update', { seg: seg }); + }, + segmentNew: function(seg, primary){ + return push('new_seg', { seg: seg, primary: primary }); + }, + segmentRemove: function(seg){ + return push('rem_seg', { seg: seg }); + }, + tempStatus: function(seg, above, below){ + return push('temp_status', { seg: seg, above: above, below: below }); + }, + rewind: function(seg){ + return push('rewind', { seg: seg }); + }, + status: function(seg, above, below){ + return push('status', { seg: seg, above: above, below: below }); + }, + vert: function(x){ + if (x === curVert) + return my; + curVert = x; + return push('vert', { x: x }); + }, + log: function(data){ + if (typeof data !== 'string') + data = JSON.stringify(data, false, ' '); + return push('log', { txt: data }); + }, + reset: function(){ + return push('reset'); + }, + selected: function(segs){ + return push('selected', { segs: segs }); + }, + chainStart: function(seg){ + return push('chain_start', { seg: seg }); + }, + chainRemoveHead: function(index, pt){ + return push('chain_rem_head', { index: index, pt: pt }); + }, + chainRemoveTail: function(index, pt){ + return push('chain_rem_tail', { index: index, pt: pt }); + }, + chainNew: function(pt1, pt2){ + return push('chain_new', { pt1: pt1, pt2: pt2 }); + }, + chainMatch: function(index){ + return push('chain_match', { index: index }); + }, + chainClose: function(index){ + return push('chain_close', { index: index }); + }, + chainAddHead: function(index, pt){ + return push('chain_add_head', { index: index, pt: pt }); + }, + chainAddTail: function(index, pt){ + return push('chain_add_tail', { index: index, pt: pt, }); + }, + chainConnect: function(index1, index2){ + return push('chain_con', { index1: index1, index2: index2 }); + }, + chainReverse: function(index){ + return push('chain_rev', { index: index }); + }, + chainJoin: function(index1, index2){ + return push('chain_join', { index1: index1, index2: index2 }); + }, + done: function(){ + return push('done'); + } + }; + return my; +} - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } +var _$BuildLog_358 = BuildLog; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs - return this; -}; +// +// provides the raw computation functions that takes epsilon into account +// +// zero is defined to be between (-epsilon, epsilon) exclusive +// -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; +function Epsilon(eps){ + if (typeof eps !== 'number') + eps = 0.0000000001; // sane default? sure why not + var my = { + epsilon: function(v){ + if (typeof v === 'number') + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right){ + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right){ + // p must be collinear with left->right + // returns false if p == left, p == right, or left == right + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; - if (!this._events) - return this; + var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) + // if `dot` is less than 0, then `p` is to the left of `left` (reject) + if (dot < eps) + return false; - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) + // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) + if (dot - sqlen > -eps) + return false; - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } + return true; + }, + pointsSameX: function(p1, p2){ + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2){ + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2){ + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2){ + // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3){ + // does pt1->pt2->pt3 make a straight line? + // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) + // if slopes are equal, then they must be collinear, because they share pt2 + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1){ + // returns false if the lines are coincident (e.g., parallel or on top of each other) + // + // returns an object if the lines intersect: + // { + // pt: [x, y], where the intersection point is at + // alongA: where intersection point is along A, + // alongB: where intersection point is along B + // } + // + // alongA and alongB will each be one of: -2, -1, 0, 1, 2 + // + // with the following meaning: + // + // -2 intersection point is before segment's first point + // -1 intersection point is directly on segment's first point + // 0 intersection point is between segment's first and second points (exclusive) + // 1 intersection point is directly on segment's second point + // 2 intersection point is after segment's second point + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; - listeners = this._events[type]; + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; // lines are coincident - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; - return this; -}; + var A = (bdx * dy - bdy * dx) / axb; + var B = (adx * dy - ady * dx) / axb; -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A * adx, + a0[1] + A * ady + ] + }; -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; + // categorize where intersection point is along A and B - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; + if (A <= -eps) + ret.alongA = -2; + else if (A < eps) + ret.alongA = -1; + else if (A - 1 <= -eps) + ret.alongA = 0; + else if (A - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; + if (B <= -eps) + ret.alongB = -2; + else if (B < eps) + ret.alongB = -1; + else if (B - 1 <= -eps) + ret.alongB = 0; + else if (B - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; -function isFunction(arg) { - return typeof arg === 'function'; -} + return ret; + }, + pointInsideRegion: function(pt, region){ + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++){ + var curr_x = region[i][0]; + var curr_y = region[i][1]; -function isNumber(arg) { - return typeof arg === 'number'; -} + // if y is between curr_y and last_y, and + // x is to the right of the boundary created by the line + if ((curr_y - y > eps) != (last_y - y > eps) && + (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside -function isObject(arg) { - return typeof arg === 'object' && arg !== null; + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; } -function isUndefined(arg) { - return arg === void 0; -} +var _$Epsilon_359 = Epsilon; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// (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) +// -'use strict'; +var GeoJSON = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool, geojson){ -/* global jQuery:false */ + // converts list of LineString's to segments + function GeoPoly(coords){ + // check for empty coords + if (coords.length <= 0) + return PolyBool.segments({ inverted: false, regions: [] }); -var __EventEmitter_527 = _$EventEmitter_137.EventEmitter; + // 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] }); + } -var Events = { + // the first LineString is considered the outside + var out = LineString(coords[0]); - init: function(plotObj) { + // 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]))); - /* - * If we have already instantiated an emitter for this plot - * return early. - */ - if(plotObj._ev instanceof __EventEmitter_527) return plotObj; + return out; + } - var ev = new __EventEmitter_527(); - var internalEv = new __EventEmitter_527(); + 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'); + }, - /* - * Assign to plot._ev while we still live in a land - * where plot is a DOM element with stuff attached to it. - * In the future we can make plot the event emitter itself. - */ - plotObj._ev = ev; + // 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)); - /* - * Create a second event handler that will manage events *internally*. - * This allows parts of plotly to respond to thing like relayout without - * having to use the user-facing event handler. They cannot peacefully - * coexist on the same handler because a user invoking - * plotObj.removeAllListeners() would detach internal events, breaking - * plotly. - */ - plotObj._internalEv = internalEv; + // 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); + } - /* - * Assign bound methods from the ev to the plot object. These methods - * will reference the 'this' of plot._ev even though they are methods - * of plot. This will keep the event machinery away from the plot object - * which currently is often a DOM element but presents an API that will - * continue to function when plot becomes an emitter. Not all EventEmitter - * methods have been bound to `plot` as some do not currently add value to - * the Plotly event API. - */ - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); + // calculate inside heirarchy + // + // _____________________ _______ roots -> A -> F + // | A | | F | | | + // | _______ _______ | | ___ | +-- B +-- G + // | | B | | C | | | | | | | | + // | | ___ | | ___ | | | | | | | +-- D + // | | | D | | | | E | | | | | G | | | + // | | |___| | | |___| | | | | | | +-- C + // | |_______| |_______| | | |___| | | + // |_____________________| |_______| +-- E - /* - * Create funtions for managing internal events. These are *only* triggered - * by the mirroring of external events via the emit function. - */ - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); + function newNode(region){ + return { + region: region, + children: [] + }; + } - /* - * We must wrap emit to continue to support JQuery events. The idea - * is to check to see if the user is using JQuery events, if they are - * we emit JQuery events to trigger user handlers as well as the EventEmitter - * events. - */ - plotObj.emit = function(event, data) { - if(typeof jQuery !== 'undefined') { - jQuery(plotObj).trigger(event, data); - } + var roots = newNode(null); - ev.emit(event, data); - internalEv.emit(event, data); - }; + 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; + } + } - return plotObj; - }, + // 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--; + } + } - /* - * This function behaves like jQueries triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - * - * Note: triggerHandler has been recommended for deprecation in v2.0.0, - * so the additional behavior of triggerHandler triggering internal events - * is deliberate excluded in order to avoid reinforcing more usage. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - /* - * If Jquery exists run all its handlers for this event and - * collect the return value of the LAST handler function - */ - if(typeof jQuery !== 'undefined') { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); - } + // now we can add ourselves + root.children.push(node); + } - /* - * Now run all the node style event handlers - */ - var ev = plotObj._ev; - if(!ev) return jQueryHandlerValue; + // 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); + } - var handlers = ev._events[event]; - if(!handlers) return jQueryHandlerValue; + // 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 - /* - * handlers can be function or an array of functions - */ - if(typeof handlers === 'function') handlers = [handlers]; - var lastHandler = handlers.pop(); + // while we're at it, exteriors are counter-clockwise, and interiors are clockwise - /* - * Call all the handlers except the last one. - */ - for(var i = 0; i < handlers.length; i++) { - handlers[i](data); - } + 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; + } - /* - * Now call the final handler and collect its value - */ - nodeEventHandlerValue = lastHandler(data); + var geopolys = []; - /* - * Return either the jquery handler value if it exists or the - * nodeEventHandler value. Jquery event value superceeds nodejs - * events for backwards compatability reasons. - */ - return jQueryHandlerValue !== undefined ? jQueryHandlerValue : - nodeEventHandlerValue; - }, + 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])); + } - purge: function(plotObj) { - delete plotObj._ev; - delete plotObj.on; - delete plotObj.once; - delete plotObj.removeListener; - delete plotObj.removeAllListeners; - delete plotObj.emit; + 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); + } - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; + // root nodes are exterior + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); - return plotObj; - } + // 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 + }; + } }; -var _$Events_527 = Events; +var _$GeoJSON_360 = GeoJSON; -var _$unhover_434 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs +// +// simple linked list implementation that allows you to traverse down nodes and save positions +// -'use strict'; +var LinkedList = { + create: function(){ + var my = { + root: { root: true, next: null }, + exists: function(node){ + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function(){ + return my.root.next === null; + }, + getHead: function(){ + return my.root.next; + }, + insertBefore: function(node, check){ + var last = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)){ + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check){ + var prev = my.root; + var here = my.root.next; + while (here !== null){ + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node){ + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data){ + data.prev = null; + data.next = null; + data.remove = function(){ + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } +}; +var _$LinkedList_362 = LinkedList; -/* removed: var _$Events_527 = require('../../lib/events'); */; -/* removed: var _$throttle_563 = require('../../lib/throttle'); */; -/* removed: var _$get_graph_div_534 = require('../../lib/get_graph_div'); */; +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs -/* removed: var _$constants_448 = require('../fx/constants'); */; +// +// this is the core work-horse +// -var unhover = _$unhover_434 = {}; +/* removed: var _$LinkedList_362 = require('./linked-list'); */; +function Intersecter(selfIntersection, eps, buildLog){ + // selfIntersection is true/false depending on the phase of the overall algorithm -unhover.wrapped = function(gd, evt, subplot) { - gd = _$get_graph_div_534(gd); + // + // segment creation + // - // Important, clear any queued hovers - if(gd._fullLayout) { - _$throttle_563.clear(gd._fullLayout._uid + _$constants_448.HOVERID); - } + function segmentNew(start, end){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: null, // is there fill above us? + below: null // is there fill below us? + }, + otherFill: null + }; + } - unhover.raw(gd, evt, subplot); -}; + function segmentCopy(start, end, seg){ + return { + id: buildLog ? buildLog.segmentId() : -1, + start: start, + end: end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } + // + // event logic + // -// remove hover effects on mouse out, and emit unhover event -unhover.raw = function unhoverRaw(gd, evt) { - var fullLayout = gd._fullLayout; - var oldhoverdata = gd._hoverdata; + var event_root = _$LinkedList_362.create(); - if(!evt) evt = {}; - if(evt.target && - _$Events_527.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ + // compare the selected points first + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + // the selected points are the same - fullLayout._hoverlayer.selectAll('g').remove(); - fullLayout._hoverlayer.selectAll('line').remove(); - fullLayout._hoverlayer.selectAll('circle').remove(); - gd._hoverdata = undefined; + if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... + return 0; // then the segments are equal - if(evt.target && oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } -}; + if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... + return p1_isStart ? 1 : -1; // favor the one that isn't the start -var _$dragelement_433 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + // otherwise, we'll have to calculate which one is below the other manually + return eps.pointAboveOrOnLine(p1_2, + p2_isStart ? p2_1 : p2_2, // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } + function eventAdd(ev, other_pt){ + event_root.insertBefore(ev, function(here){ + // should ev be inserted before here? + var comp = eventCompare( + ev .isStart, ev .pt, other_pt, + here.isStart, here.pt, here.other.pt + ); + return comp < 0; + }); + } -'use strict'; + function eventAddSegmentStart(seg, primary){ + var ev_start = _$LinkedList_362.node({ + isStart: true, + pt: seg.start, + seg: seg, + primary: primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } -/* removed: var _$mouseEventOffset_263 = require('mouse-event-offset'); */; -/* removed: var _$hasHover_239 = require('has-hover'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; + function eventAddSegmentEnd(ev_start, seg, primary){ + var ev_end = _$LinkedList_362.node({ + isStart: false, + pt: seg.end, + seg: seg, + primary: primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; + function eventAddSegment(seg, primary){ + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } -/* removed: var _$constants_589 = require('../../plots/cartesian/constants'); */; -/* removed: var _$interactions_516 = require('../../constants/interactions'); */; + function eventUpdateEnd(ev, end){ + // slides an end backwards + // (start)------------(end) to: + // (start)---(end) -var dragElement = _$dragelement_433 = {}; + if (buildLog) + buildLog.segmentChop(ev.seg, end); -dragElement.align = _$align_431; -dragElement.getCursor = _$getCursor_432; + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } -/* removed: var _$unhover_434 = require('./unhover'); */; -dragElement.unhover = _$unhover_434.wrapped; -dragElement.unhoverRaw = _$unhover_434.raw; + function eventDivide(ev, pt){ + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } + function calculate(primaryPolyInverted, secondaryPolyInverted){ + // if selfIntersection is true then there is no secondary polygon, so that isn't used -/** - * 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 DBLCLICKDELAY = _$interactions_516.DBLCLICKDELAY; - var element = options.element; + // + // status logic + // - var startX, - startY, - newMouseDownTime, - cursor, - dragCover, - initialEvent, - initialTarget, - rightClick; + var status_root = _$LinkedList_362.create(); - if(!gd._mouseDownTime) gd._mouseDownTime = 0; + function statusCompare(ev1, ev2){ + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; - element.style.pointerEvents = 'all'; + if (eps.pointsCollinear(a1, b1, b2)){ + if (eps.pointsCollinear(a2, b1, b2)) + return 1;//eventCompare(true, a1, a2, true, b1, b2); + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } - element.onmousedown = onStart; + function statusFindSurrounding(ev){ + return status_root.findTransition(function(here){ + var comp = statusCompare(ev, here.ev); + return comp > 0; + }); + } - if(!_$hasPassiveEvents_240) { - element.ontouchstart = onStart; - } - else { - if(element._ontouchstart) { - element.removeEventListener('touchstart', element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener('touchstart', onStart, {passive: false}); - } + function checkIntersection(ev1, ev2){ + // returns the segment equal to ev1, or false if nothing equal - function _clampFn(dx, dy, minDrag) { - if(Math.abs(dx) < minDrag) dx = 0; - if(Math.abs(dy) < minDrag) dy = 0; - return [dx, dy]; - } + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; - var clampFn = options.clampFn || _clampFn; + if (buildLog) + buildLog.checkIntersection(seg1, seg2); - function onStart(e) { - e.preventDefault(); + var i = eps.linesIntersect(a1, a2, b1, b2); - // 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; + if (i === false){ + // segments are parallel or coincident - newMouseDownTime = (new Date()).getTime(); - if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) { - // in a click train - numClicks += 1; - } - else { - // new click train - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } + // if points aren't collinear, then the segments are parallel, so no intersections + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + // otherwise, segments are on top of each other somehow (aka coincident) - if(options.prepFn) options.prepFn(e, startX, startY); + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; // segments touch at endpoints... no intersection - if(_$hasHover_239 && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } - else if(!_$hasHover_239) { - // 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; - } + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); - document.addEventListener('mousemove', onMove); - document.addEventListener('mouseup', onDone); - document.addEventListener('touchmove', onMove); - document.addEventListener('touchend', onDone); + if (a1_equ_b1 && a2_equ_b2) + return ev2; // segments are exactly equal - return; - } + var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - function onMove(e) { - e.preventDefault(); + // handy for debugging: + // buildLog.log({ + // a1_equ_b1: a1_equ_b1, + // a2_equ_b2: a2_equ_b2, + // a1_between: a1_between, + // a2_between: a2_between + // }); - var offset = pointerOffset(e); - var minDrag = options.minDrag || _$constants_589.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; + if (a1_equ_b1){ + if (a2_between){ + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)---(b2) + eventDivide(ev1, b2); + } + return ev2; + } + else if (a1_between){ + if (!a2_equ_b2){ + // make a2 equal to b2 + if (a2_between){ + // (a1)---(a2) + // (b1)-----------------(b2) + eventDivide(ev2, a2); + } + else{ + // (a1)----------(a2) + // (b1)----------(b2) + eventDivide(ev1, b2); + } + } + + // (a1)---(a2) + // (b1)----------(b2) + eventDivide(ev2, a1); + } + } + else{ + // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + + // is A divided between its endpoints? (exclusive) + if (i.alongA === 0){ + if (i.alongB === -1) // yes, at exactly b1 + eventDivide(ev1, b1); + else if (i.alongB === 0) // yes, somewhere between B's endpoints + eventDivide(ev1, i.pt); + else if (i.alongB === 1) // yes, at exactly b2 + eventDivide(ev1, b2); + } + + // is B divided between its endpoints? (exclusive) + if (i.alongB === 0){ + if (i.alongA === -1) // yes, at exactly a1 + eventDivide(ev2, a1); + else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) // yes, at exactly a2 + eventDivide(ev2, a2); + } + } + return false; + } + + // + // main event loop + // + var segments = []; + while (!event_root.isEmpty()){ + var ev = event_root.getHead(); + + if (buildLog) + buildLog.vert(ev.pt[0]); + + if (ev.isStart){ + + if (buildLog) + buildLog.segmentNew(ev.seg, ev.primary); + + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; + + if (buildLog){ + buildLog.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } + + function checkBothIntersections(){ + if (above){ + var eve = checkIntersection(ev, above); + if (eve) + return eve; + } + if (below) + return checkIntersection(ev, below); + return false; + } + + var eve = checkBothIntersections(); + if (eve){ + // ev and eve are equal + // we'll keep eve and throw away ev + + // merge ev.seg's fill information into eve.seg + + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + + // merge two segments that belong to the same polygon + // think of this as sandwiching two segments together, where `eve.seg` is + // the bottom -- this will cause the above fill flag to toggle + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } + else{ + // merge two segments that belong to different polygons + // each segment has distinct knowledge, so no special logic is needed + // note that this can only happen once per segment in this phase, because we + // are guaranteed that all self-intersections are gone + eve.seg.otherFill = ev.seg.myFill; + } + + if (buildLog) + buildLog.segmentUpdate(eve.seg); + + ev.other.remove(); + ev.remove(); + } + + if (event_root.getHead() !== ev){ + // something was inserted before us in the event queue, so loop back around and + // process it before continuing + if (buildLog) + buildLog.rewind(ev.seg); + continue; + } + + // + // calculate fill flags + // + if (selfIntersection){ + var toggle; // are we a toggling edge? + if (ev.seg.myFill.below === null) // if we are a new segment... + toggle = true; // then we toggle + else // we are a segment that has previous knowledge from a division + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle + + // next, calculate whether we are filled below us + if (!below){ // if nothing is below us... + // we are filled below us if the polygon is inverted + ev.seg.myFill.below = primaryPolyInverted; + } + else{ + // otherwise, we know the answer -- it's the same if whatever is below + // us is filled above it + ev.seg.myFill.below = below.seg.myFill.above; + } + + // since now we know if we're filled below us, we can calculate whether + // we're filled above us by applying toggle to whatever is below us + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } + else{ + // now we fill in any missing transition information, since we are all-knowing + // at this point + + if (ev.seg.otherFill === null){ + // if we don't have other information, then we need to figure out if we're + // inside the other polygon + var inside; + if (!below){ + // if nothing is below us, then we're inside if the other polygon is + // inverted + inside = + ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } + else{ // otherwise, something is below us + // so copy the below segment's other polygon's above + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } + + if (buildLog){ + buildLog.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } + + // insert the status and remember it for later removal + ev.other.status = surrounding.insert(_$LinkedList_362.node({ ev: ev })); + } + else{ + var st = ev.status; + + if (st === null){ + throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + } + + // removing the status will create two new adjacent edges, so we'll need to check + // for those + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); + + if (buildLog) + buildLog.statusRemove(st.ev.seg); + + // remove the status + st.remove(); + + // if we've reached this point, we've calculated everything there is to know, so + // save the segment for reporting + if (!ev.primary){ + // make sure `seg.myFill` actually points to the primary polygon though + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } + + // remove the event and continue + event_root.getHead().remove(); + } + + if (buildLog) + buildLog.done(); + + return segments; + } + + // return the appropriate API depending on what we're doing + if (!selfIntersection){ + // performing combination of polygons, so only deal with already-processed segments + return { + calculate: function(segments1, inverted1, segments2, inverted2){ + // segmentsX come from the self-intersection API, or this API + // invertedX is whether we treat that list of segments as an inverted polygon or not + // returns segments that can be used for further operations + segments1.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg){ + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } + + // otherwise, performing self-intersection, so deal with regions + return { + addRegion: function(region){ + // regions are a list of points: + // [ [0, 0], [100, 0], [50, 100] ] + // you can add multiple regions before running calculate + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++){ + pt1 = pt2; + pt2 = region[i]; + + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) // points are equal, so we have a zero-length segment + continue; // just skip it + + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted){ + // is the polygon inverted? + // returns segments + return calculate(inverted, false); + } + }; +} + +var _$Intersecter_361 = Intersecter; + +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs + +// +// converts a list of segments into a list of regions, while also removing unnecessary verticies +// + +function SegmentChainer(segments, eps, buildLog){ + var chains = []; + var regions = []; + + segments.forEach(function(seg){ + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)){ + console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + + 'probably too small or too large'); + return; + } + + if (buildLog) + buildLog.chainStart(seg); + + // search for two chains that this segment matches + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index, matches_head, matches_pt1){ + // return true if we've matched twice + next_match.index = index; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match){ + next_match = second_match; + return false; + } + next_match = null; + return true; // we've matched twice, we're done here + } + for (var i = 0; i < chains.length; i++){ + var chain = chains[i]; + var head = chain[0]; + var head2 = chain[1]; + var tail = chain[chain.length - 1]; + var tail2 = chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)){ + if (setMatch(i, true, true)) + break; + } + else if (eps.pointsSame(head, pt2)){ + if (setMatch(i, true, false)) + break; + } + else if (eps.pointsSame(tail, pt1)){ + if (setMatch(i, false, true)) + break; + } + else if (eps.pointsSame(tail, pt2)){ + if (setMatch(i, false, false)) + break; + } + } + + if (next_match === first_match){ + // we didn't match anything, so create a new chain + chains.push([ pt1, pt2 ]); + if (buildLog) + buildLog.chainNew(pt1, pt2); + return; + } + + if (next_match === second_match){ + // we matched a single chain + + if (buildLog) + buildLog.chainMatch(first_match.index); + + // add the other point to the apporpriate end, and check to see if we've closed the + // chain into a loop + + var index = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc + var addToHead = first_match.matches_head; // if we matched at head, then add to the head + + var chain = chains[index]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + + if (eps.pointsCollinear(grow2, grow, pt)){ + // grow isn't needed because it's directly between grow2 and pt: + // grow2 ---grow---> pt + if (addToHead){ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, pt); + chain.shift(); + } + else{ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; // old grow is gone... new grow is what grow2 was + } + + if (eps.pointsSame(oppo, pt)){ + // we're closing the loop, so remove chain from chains + chains.splice(index, 1); + + if (eps.pointsCollinear(oppo2, oppo, grow)){ + // oppo isn't needed because it's directly between oppo2 and grow: + // oppo2 ---oppo--->grow + if (addToHead){ + if (buildLog) + buildLog.chainRemoveTail(first_match.index, grow); + chain.pop(); + } + else{ + if (buildLog) + buildLog.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } + + if (buildLog) + buildLog.chainClose(first_match.index); + + // we have a closed chain! + regions.push(chain); + return; + } + + // not closing a loop, so just add it to the apporpriate side + if (addToHead){ + if (buildLog) + buildLog.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } + else{ + if (buildLog) + buildLog.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } + + // otherwise, we matched two chains, so we need to combine those chains together + + function reverseChain(index){ + if (buildLog) + buildLog.chainReverse(index); + chains[index].reverse(); // gee, that's easy + } + + function appendChain(index1, index2){ + // index1 gets index2 appended to it, and index2 is removed + var chain1 = chains[index1]; + var chain2 = chains[index2]; + var tail = chain1[chain1.length - 1]; + var tail2 = chain1[chain1.length - 2]; + var head = chain2[0]; + var head2 = chain2[1]; + + if (eps.pointsCollinear(tail2, tail, head)){ + // tail isn't needed because it's directly between tail2 and head + // tail2 ---tail---> head + if (buildLog) + buildLog.chainRemoveTail(index1, tail); + chain1.pop(); + tail = tail2; // old tail is gone... new tail is what tail2 was + } + + if (eps.pointsCollinear(tail, head, head2)){ + // head isn't needed because it's directly between tail and head2 + // tail ---head---> head2 + if (buildLog) + buildLog.chainRemoveHead(index2, head); + chain2.shift(); + } + + if (buildLog) + buildLog.chainJoin(index1, index2); + chains[index1] = chain1.concat(chain2); + chains.splice(index2, 1); + } + + var F = first_match.index; + var S = second_match.index; + + if (buildLog) + buildLog.chainConnect(F, S); + + var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed + if (first_match.matches_head){ + if (second_match.matches_head){ + if (reverseF){ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(F); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + // <<<< F <<<< --- >>>> S >>>> + reverseChain(S); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + } + else{ + if (second_match.matches_head){ + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + else{ + if (reverseF){ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(F); + // <<<< F <<<< --- <<<< S <<<< logically same as: + // >>>> S >>>> --- >>>> F >>>> + appendChain(S, F); + } + else{ + // >>>> F >>>> --- <<<< S <<<< + reverseChain(S); + // >>>> F >>>> --- >>>> S >>>> + appendChain(F, S); + } + } + } + }); + + return regions; +} + +var _$SegmentChainer_363 = SegmentChainer; + +// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc +// MIT License +// Project Home: https://github.com/voidqk/polybooljs + +// +// filter a list of segments based on boolean operations +// + +function select(segments, selection, buildLog){ + var result = []; + segments.forEach(function(seg){ + var index = + (seg.myFill.above ? 8 : 0) + + (seg.myFill.below ? 4 : 0) + + ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + + ((seg.otherFill && seg.otherFill.below) ? 1 : 0); + if (selection[index] !== 0){ + // copy the segment to the results, while also calculating the fill status + result.push({ + id: buildLog ? buildLog.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index] === 1, // 1 if filled above + below: selection[index] === 2 // 2 if filled below + }, + otherFill: null + }); + } + }); + + if (buildLog) + buildLog.selected(result); + + return result; +} + +var SegmentSelector = { + union: function(segments, buildLog){ // primary | secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 2, 0, 0, + 1, 0, 1, 0, + 0, 0, 0, 0 + ], buildLog); + }, + intersect: function(segments, buildLog){ // primary & secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => yes filled below 2 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled below 2 + // 1 0 0 0 => no 0 + // 1 0 0 1 => no 0 + // 1 0 1 0 => yes filled above 1 + // 1 0 1 1 => yes filled above 1 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled below 2 + // 1 1 1 0 => yes filled above 1 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 0, 2, 0, 2, + 0, 0, 1, 1, + 0, 2, 1, 0 + ], buildLog); + }, + difference: function(segments, buildLog){ // primary - secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => no 0 + // 0 0 1 0 => no 0 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled below 2 + // 0 1 1 1 => no 0 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => yes filled above 1 + // 1 0 1 0 => no 0 + // 1 0 1 1 => no 0 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 0, 0, 0, + 2, 0, 2, 0, + 1, 1, 0, 0, + 0, 1, 2, 0 + ], buildLog); + }, + differenceRev: function(segments, buildLog){ // secondary - primary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => no 0 + // 0 1 0 1 => no 0 + // 0 1 1 0 => yes filled above 1 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => no 0 + // 1 0 0 1 => yes filled below 2 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => no 0 + // 1 1 1 0 => no 0 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 0, 0, 1, 1, + 0, 2, 0, 2, + 0, 0, 0, 0 + ], buildLog); + }, + xor: function(segments, buildLog){ // primary ^ secondary + // above1 below1 above2 below2 Keep? Value + // 0 0 0 0 => no 0 + // 0 0 0 1 => yes filled below 2 + // 0 0 1 0 => yes filled above 1 + // 0 0 1 1 => no 0 + // 0 1 0 0 => yes filled below 2 + // 0 1 0 1 => no 0 + // 0 1 1 0 => no 0 + // 0 1 1 1 => yes filled above 1 + // 1 0 0 0 => yes filled above 1 + // 1 0 0 1 => no 0 + // 1 0 1 0 => no 0 + // 1 0 1 1 => yes filled below 2 + // 1 1 0 0 => no 0 + // 1 1 0 1 => yes filled above 1 + // 1 1 1 0 => yes filled below 2 + // 1 1 1 1 => no 0 + return select(segments, [ + 0, 2, 1, 0, + 2, 0, 0, 1, + 1, 0, 0, 2, + 0, 1, 2, 0 + ], buildLog); + } +}; + +var _$SegmentSelector_364 = SegmentSelector; + +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ + +/* removed: var _$BuildLog_358 = require('./lib/build-log'); */; +/* removed: var _$Epsilon_359 = require('./lib/epsilon'); */; +/* removed: var _$Intersecter_361 = require('./lib/intersecter'); */; +/* removed: var _$SegmentChainer_363 = require('./lib/segment-chainer'); */; +/* removed: var _$SegmentSelector_364 = require('./lib/segment-selector'); */; +/* removed: var _$GeoJSON_360 = require('./lib/geojson'); */; + +var buildLog = false; +var epsilon = _$Epsilon_359(); + +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl){ + if (bl === true) + buildLog = _$BuildLog_358(); + 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_361(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2){ + var i3 = _$Intersecter_361(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_364.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + } + }, + selectIntersect: function(combined){ + return { + segments: _$SegmentSelector_364.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + } + }, + selectDifference: function(combined){ + return { + segments: _$SegmentSelector_364.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + } + }, + selectDifferenceRev: function(combined){ + return { + segments: _$SegmentSelector_364.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + } + }, + selectXor: function(combined){ + return { + segments: _$SegmentSelector_364.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + } + }, + polygon: function(segments){ + return { + regions: _$SegmentChainer_363(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, + + // GeoJSON converters + polygonFromGeoJSON: function(geojson){ + return _$GeoJSON_360.toPolygon(PolyBool, geojson); + }, + polygonToGeoJSON: function(poly){ + return _$GeoJSON_360.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; + +var _$PolyBool_357 = PolyBool; + +var _$polygon_613 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +var dot = _$matrix_607.dot; +var __BADNUM_613 = _$numerical_578.BADNUM; + +var polygon = _$polygon_613 = {}; + +/** + * Turn an array of [x, y] pairs into a polygon object + * that can test if points are inside it + * + * @param ptsIn Array of [x, y] pairs + * + * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} + * (x|y)(min|max) are the bounding rect of the polygon + * pts is the original array, with the first pair repeated at the end + * contains is a function: (pt, omitFirstEdge) + * pt is the [x, y] pair to test + * omitFirstEdge truthy means points exactly on the first edge don't + * count. This is for use adding one polygon to another so we + * don't double-count the edge where they meet. + * returns boolean: is pt inside the polygon (including on its edges) + */ +polygon.tester = function tester(ptsIn) { + if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); + + var pts = ptsIn.slice(), + xmin = pts[0][0], + xmax = xmin, + ymin = pts[0][1], + ymax = ymin, + i; + + pts.push(pts[0]); + for(i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); + } + + // do we have a rectangle? Handle this here, so we can use the same + // tester for the rectangular case without sacrificing speed + + var isRect = false, + rectFirstEdgeTest; + + if(pts.length === 5) { + if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz + if(pts[2][0] === pts[3][0] && + pts[0][1] === pts[3][1] && + pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; + } + } + else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert + if(pts[2][1] === pts[3][1] && + pts[0][0] === pts[3][0] && + pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; + } + } + } + + function rectContains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; + + if(x === __BADNUM_613 || x < xmin || x > xmax || y === __BADNUM_613 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; + + return true; + } + + function contains(pt, omitFirstEdge) { + var x = pt[0], + y = pt[1]; + + if(x === __BADNUM_613 || x < xmin || x > xmax || y === __BADNUM_613 || y < ymin || y > ymax) { + // pt is outside the bounding box of polygon + return false; + } + + var imax = pts.length, + x1 = pts[0][0], + y1 = pts[0][1], + crossings = 0, + i, + x0, + y0, + xmini, + ycross; + + for(i = 1; i < imax; i++) { + // find all crossings of a vertical line upward from pt with + // polygon segments + // crossings exactly at xmax don't count, unless the point is + // exactly on the segment, then it counts as inside. + x0 = x1; + y0 = y1; + x1 = pts[i][0]; + y1 = pts[i][1]; + xmini = Math.min(x0, x1); + + // outside the bounding box of this segment, it's only a crossing + // if it's below the box. + if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } + else if(y < Math.min(y0, y1)) { + // don't count the left-most point of the segment as a crossing + // because we don't want to double-count adjacent crossings + // UNLESS the polygon turns past vertical at exactly this x + // Note that this is repeated below, but we can't factor it out + // because + if(x !== xmini) crossings++; + } + // inside the bounding box, check the actual line intercept + else { + // vertical segment - we know already that the point is exactly + // on the segment, so mark the crossing as exactly at the point. + if(x1 === x0) ycross = y; + // any other angle + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); + + // exactly on the edge: counts as inside the polygon, unless it's the + // first edge and we're omitting it. + if(y === ycross) { + if(i === 1 && omitFirstEdge) return false; + return true; + } + + if(y <= ycross && x !== xmini) crossings++; + } + } + + // if we've gotten this far, odd crossings means inside, even is outside + return crossings % 2 === 1; + } + + // detect if poly is degenerate + var degenerate = true; + var lastPt = pts[0]; + for(i = 1; i < pts.length; i++) { + if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; + } + } + + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: pts, + contains: isRect ? rectContains : contains, + isRect: isRect, + degenerate: degenerate + }; +}; + +/** + * Test multiple polygons + */ +polygon.multitester = function multitester(list) { + var testers = [], + xmin = list[0][0][0], + xmax = xmin, + ymin = list[0][0][1], + ymax = ymin; + + for(var i = 0; i < list.length; i++) { + 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); + } + + function contains(pt, arg) { + var yes = false; + for(var i = 0; i < testers.length; i++) { + if(testers[i].contains(pt, arg)) { + // if contained by subtract polygon - exclude the point + yes = testers[i].subtract === false; + } + } + + return yes; + } + + return { + xmin: xmin, + xmax: xmax, + ymin: ymin, + ymax: ymax, + pts: [], + contains: contains, + isRect: false, + degenerate: false + }; +}; + +/** + * Test if a segment of a points array is bent or straight + * + * @param pts Array of [x, y] pairs + * @param start the index of the proposed start of the straight section + * @param end the index of the proposed end point + * @param tolerance the max distance off the line connecting start and end + * before the line counts as bent + * @returns boolean: true means this segment is bent, false means straight + */ +var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { + var startPt = pts[start], + segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], + segmentSquared = dot(segment, segment), + segmentLen = Math.sqrt(segmentSquared), + unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], + i, + part, + partParallel; + + for(i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment); + + if(partParallel < 0 || partParallel > segmentSquared || + Math.abs(dot(part, unitPerp)) > tolerance) return true; + } + return false; +}; + +/** + * Make a filtering polygon, to minimize the number of segments + * + * @param pts Array of [x, y] pairs (must start with at least 1 pair) + * @param tolerance the maximum deviation from straight allowed for + * removing points to simplify the polygon + * + * @returns Object {addPt, raw, filtered} + * addPt is a function(pt: [x, y] pair) to add a raw point and + * continue filtering + * raw is all the input points + * filtered is the resulting filtered Array of [x, y] pairs + */ +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]], + doneRawIndex = 0, + doneFilteredIndex = 0; + + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length, + iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); + + for(var i = iLast + 1; i < pts.length; i++) { + if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if(ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } + } + } + + if(pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } + + return { + addPt: addPt, + raw: pts, + filtered: ptsFiltered + }; +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$PolyBool_357 = require('polybooljs'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; + +/* removed: var _$polygon_613 = require('../../lib/polygon'); */; +/* removed: var _$throttle_626 = require('../../lib/throttle'); */; +var makeEventData = _$helpers_512.makeEventData; +var getFromId = _$axis_ids_650.getFromId; +var __sortModules_664 = _$sort_modules_722.sortModules; + +/* removed: var _$constants_652 = require('./constants'); */; +var MINSELECT = _$constants_652.MINSELECT; + +var filteredPolygon = _$polygon_613.filter; +var polygonTester = _$polygon_613.tester; +var multipolygonTester = _$polygon_613.multitester; + +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 xAxisIds = dragOptions.xaxes.map(getAxId); + var yAxisIds = dragOptions.yaxes.map(getAxId); + var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes); + var subtract = e.altKey; + + var filterPoly, testPoly, mergedPolygons, currentPolygon; + var i, cd, trace, searchInfo, eventData; + + var selectingOnSameSubplot = ( + fullLayout._lastSelectedSubplot && + fullLayout._lastSelectedSubplot === plotinfo.id + ); + + if( + selectingOnSameSubplot && + (e.shiftKey || e.altKey) && + (plotinfo.selection && plotinfo.selection.polygons) && + !dragOptions.polygons + ) { + // take over selection polygons from prev mode, if any + dragOptions.polygons = plotinfo.selection.polygons; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if( + (!e.shiftKey && !e.altKey) || + ((e.shiftKey || e.altKey) && !plotinfo.selection) + ) { + // create new polygons, if shift mode or selecting across different subplots + plotinfo.selection = {}; + plotinfo.selection.polygons = dragOptions.polygons = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; + } + + // clear selection outline when selecting a different subplot + if(!selectingOnSameSubplot) { + clearSelect(zoomLayer); + fullLayout._lastSelectedSubplot = plotinfo.id; + } + + if(mode === 'lasso') { + filterPoly = filteredPolygon([[x0, y0]], _$constants_652.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_473.background, + stroke: _$color_473.defaultLine, + 'stroke-width': 1 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); + + + // find the traces to search for selection points + var searchTraces = []; + var throttleID = fullLayout._uid + _$constants_652.SELECTID; + var selection = []; + + 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(dragOptions.subplot) { + if( + trace.subplot === dragOptions.subplot || + trace.geo === dragOptions.subplot + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.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]] + ) { + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: dragOptions.xaxes[0], + yaxis: dragOptions.yaxes[0] + }); + } else { + if(xAxisIds.indexOf(trace.xaxis) === -1) continue; + if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + + searchTraces.push({ + _module: trace._module, + cd: cd, + xaxis: getFromId(gd, trace.xaxis), + yaxis: getFromId(gd, trace.yaxis) + }); + } + } + + function axValue(ax) { + var index = (ax._id.charAt(0) === 'y') ? 1 : 0; + return function(v) { return ax.p2d(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] = [ + ax.p2d(poly[axLetter + 'min']), + ax.p2d(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), + 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.polygons && dragOptions.polygons.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); + } + else { + mergedPolygons = [currentPolygon]; + testPoly = polygonTester(currentPolygon); + } + + // draw selection + var paths = []; + for(i = 0; i < mergedPolygons.length; i++) { + var ppts = mergedPolygons[i]; + paths.push(ppts.join('L') + 'L' + ppts[0]); + } + outlines + .attr('d', 'M' + paths.join('M') + 'Z'); + + _$throttle_626.throttle( + throttleID, + _$constants_652.SELECTDELAY, + function() { + selection = []; + + var thisSelection, traceSelections = [], traceSelection; + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + + traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly); + 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) { + corners.remove(); + + _$throttle_626.done(throttleID).then(function() { + _$throttle_626.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); + gd.emit('plotly_deselect', null); + } + else { + // 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. + gd.emit('plotly_selected', undefined); + } + + _$fx_515.click(gd, evt); + }); + }; + + dragOptions.doneFn = function() { + corners.remove(); + + _$throttle_626.done(throttleID).then(function() { + _$throttle_626.clear(throttleID); + dragOptions.gd.emit('plotly_selected', eventData); + + if(currentPolygon && dragOptions.polygons) { + // save last polygons + currentPolygon.subtract = subtract; + dragOptions.polygons.push(currentPolygon); + + // we have to keep reference to arrays container + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + }); + }; +} + +function updateSelectedState(gd, searchTraces, eventData) { + var i, j, searchInfo, trace; + + if(eventData) { + var pts = eventData.points || []; + + for(i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace.selectedpoints = []; + trace._input.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); + [].push.apply(fullData.selectedpoints, pt.pointIndices); + } else { + data.selectedpoints.push(pt.pointIndex); + 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; + } + } + + // group searchInfo traces by trace modules + var lookup = {}; + + for(i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + + var name = searchInfo._module.name; + if(lookup[name]) { + lookup[name].push(searchInfo); + } else { + lookup[name] = [searchInfo]; + } + } + + var keys = Object.keys(lookup).sort(__sortModules_664); + + for(i = 0; i < keys.length; i++) { + var items = lookup[keys[i]]; + var len = items.length; + var item0 = items[0]; + var trace0 = item0.cd[0].trace; + + if(_$registry_731.traceIs(trace0, 'regl')) { + // plot regl traces per module + var cds = new Array(len); + for(j = 0; j < len; j++) { + cds[j] = items[j].cd; + } + item0._module.style(gd, cds); + } else { + // plot svg trace per trace + for(j = 0; j < len; j++) { + item0._module.style(gd, items[j].cd); + } + } + } +} + +function mergePolygons(list, poly, subtract) { + var res; + + if(subtract) { + res = _$PolyBool_357.difference({ + regions: list, + inverted: false + }, { + regions: [poly], + inverted: false + }); + + return res.regions; + } + + res = _$PolyBool_357.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; +} + +function clearSelect(zoomlayer) { + // until we get around to persistent selections, remove the outline + // here. The selection itself will be removed when the plot redraws + // at the end. + zoomlayer.selectAll('.select-outline').remove(); +} + +var _$select_664 = { + prepSelect: prepSelect, + clearSelect: clearSelect +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$clearGlCanvases_585 = require('../../lib/clear_gl_canvases'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +var FROM_TL = _$alignment_573.FROM_TL; + +/* removed: var _$plots_709 = require('../plots'); */; + +var doTicks = _$axes_647.doTicks; +var __getFromId_655 = _$axis_ids_650.getFromId; +var __prepSelect_655 = _$select_664.prepSelect; +var __clearSelect_655 = _$select_664.clearSelect; +/* removed: var _$scaleZoom_663 = require('./scale_zoom'); */; + +/* removed: var _$constants_652 = require('./constants'); */; +var MINDRAG = _$constants_652.MINDRAG; +var MINZOOM = _$constants_652.MINZOOM; + + +// flag for showing "doubleclick to zoom out" only at the beginning +var SHOWZOOMOUTTIP = true; + +// dragBox: create an element to drag one or more axis ends +// inputs: +// plotinfo - which subplot are we making dragboxes on? +// x,y,w,h - left, top, width, height of the box +// ns - how does this drag the vertical axis? +// 'n' - top only +// 's' - bottom only +// 'ns' - top and bottom together, difference unchanged +// ew - same for horizontal axis +function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + // mouseDown stores ms of first mousedown event in the last + // DBLCLICKDELAY ms on the drag bars + // numClicks stores how many mousedowns have been seen + // within DBLCLICKDELAY so we can check for click or doubleclick events + // dragged stores whether a drag has occurred, so we don't have to + // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = (ns + ew === 'nsew'); + var singleEnd = (ns + ew).length === 1; + + // main subplot x and y (i.e. found in plotinfo - the main ones) + var xa0, ya0; + // {ax._id: ax} hash objects + var xaHash, yaHash; + // xaHash/yaHash values (arrays) + var xaxes, yaxes; + // main axis offsets + var xs, ys; + // main axis lengths + var pw, ph; + // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes' + // which are the x/y {ax._id: ax} hash objects and their values + // for linked axis relative to this subplot + var links; + // set to ew/ns val when active, set to '' when inactive + var xActive, yActive; + // are all axes in this subplot are fixed? + var allFixedRanges; + // is subplot constrained? + var isSubplotConstrained; + // do we need to edit x/y ranges? + var editX, editY; + + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; + + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; + + // if we're dragging two axes at once, also drag overlays + if(ns && ew) { + var overlays = plotinfo.overlays; + for(var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } + + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; + + links = calcLinks(gd, xaHash, yaHash); + isSubplotConstrained = links.isSubplotConstrained; + editX = ew || isSubplotConstrained; + editY = ns || isSubplotConstrained; + } + + recomputeAxisLists(); + + var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); + + // still need to make the element if the axes are disabled + // but nuke its events (except for maindrag which needs them for hover) + // and stop there + if(allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = 'none'; + return dragger; + } + + var dragOptions = { + element: dragger, + gd: gd, + plotinfo: plotinfo, + prepFn: function(e, startX, startY) { + var dragModeNow = gd._fullLayout.dragmode; + + recomputeAxisLists(); + + if(!allFixedRanges) { + if(isMainDrag) { + // main dragger handles all drag modes, and changes + // to pan (or to zoom if it already is pan) on shift + if(e.shiftKey) { + if(dragModeNow === 'pan') dragModeNow = 'zoom'; + else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; + } + else if(e.ctrlKey) { + dragModeNow = 'pan'; + } + } + // all other draggers just pan + else dragModeNow = 'pan'; + } + + if(dragModeNow === 'lasso') dragOptions.minDrag = 1; + else dragOptions.minDrag = undefined; + + if(isSelectOrLasso(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + __prepSelect_655(e, startX, startY, dragOptions, dragModeNow); + } + else if(allFixedRanges) { + __clearSelect_655(zoomlayer); + } + else if(dragModeNow === 'zoom') { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; + + // zoomMove takes care of the threshold, but we need to + // minimize this so that constrained zoom boxes will flip + // orientation at the right place + dragOptions.minDrag = 1; + + zoomPrep(e, startX, startY); + } + else if(dragModeNow === 'pan') { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + __clearSelect_655(zoomlayer); + } + }, + clickFn: function(numClicks, evt) { + removeZoombox(gd); + + if(numClicks === 2 && !singleEnd) doubleClick(); + + if(isMainDrag) { + _$fx_515.click(gd, evt, plotinfo.id); + } + else if(numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0, + end = (ns === 's' || ew === 'w') ? 0 : 1, + attrStr = ax._name + '.range[' + end + ']', + initialText = getEndText(ax, end), + hAlign = 'left', + vAlign = 'middle'; + + if(ax.fixedrange) return; + + if(ns) { + vAlign = (ns === 'n') ? 'top' : 'bottom'; + if(ax.side === 'right') hAlign = 'right'; + } + else if(ew === 'e') hAlign = 'right'; + + if(gd._context.showAxisRangeEntryBoxes) { + _$d3_130.select(dragger) + .call(_$svg_text_utils_625.makeEditable, { + gd: gd, + immediate: true, + background: gd._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : '#444', + horizontalAlign: hAlign, + verticalAlign: vAlign + }) + .on('edit', function(text) { + var v = ax.d2r(text); + if(v !== undefined) { + _$registry_731.call('relayout', gd, attrStr, v); + } + }); + } + } + } + }; + + _$dragelement_495.init(dragOptions); + + var x0, + y0, + box, + lum, + path0, + dimmed, + zoomMode, + zb, + corners; + + // collected changes to be made to the plot by relayout at the end + var updates = {}; + + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; + lum = gd._hmpixcount ? + (gd._hmlumcount / gd._hmpixcount) : + _$tinycolor_414(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; + dimmed = false; + zoomMode = 'xy'; + + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); + + corners = makeCorners(zoomlayer, xs, ys); + + __clearSelect_655(zoomlayer); + } + + function zoomMove(dx0, dy0) { + if(gd._transitioningWithDuration) { + return false; + } + + var x1 = Math.max(0, Math.min(pw, dx0 + x0)), + y1 = Math.max(0, Math.min(ph, dy0 + y0)), + dx = Math.abs(x1 - x0), + dy = Math.abs(y1 - y0); + + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); + + function noZoom() { + zoomMode = ''; + box.r = box.l; + box.t = box.b; + corners.attr('d', 'M0,0Z'); + } + + if(isSubplotConstrained) { + if(dx > MINZOOM || dy > MINZOOM) { + zoomMode = 'xy'; + if(dx / pw > dy / ph) { + dy = dx * ph / pw; + if(y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } + else { + dx = dy * pw / ph; + if(x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr('d', xyCorners(box)); + } + else { + noZoom(); + } + } + // look for small drags in one direction or the other, + // and only drag the other axis + else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if(dx < MINDRAG) { + noZoom(); + } + else { + box.t = 0; + box.b = ph; + zoomMode = 'x'; + corners.attr('d', xCorners(box, y0)); + } + } + else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = 'y'; + corners.attr('d', yCorners(box, x0)); + } + else { + zoomMode = 'xy'; + corners.attr('d', xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; + + updateZoombox(zb, corners, box, path0, dimmed, lum); + dimmed = true; + } + + function zoomDone() { + // more strict than dragged, which allows you to come back to where you started + // and still count as dragged + if(Math.min(box.h, box.w) < MINDRAG * 2) { + return removeZoombox(gd); + } + + // TODO: edit linked axes in zoomAxRanges and in dragTail + if(zoomMode === 'xy' || zoomMode === 'x') { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + } + if(zoomMode === 'xy' || zoomMode === 'y') { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + } + + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } + + // scroll zoom, on all draggers except corners + var scrollViewBox = [0, 0, pw, ph]; + // wait a little after scrolling before redrawing + var redrawTimer = null; + var REDRAWDELAY = _$constants_652.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; + + function zoomWheel(e) { + // deactivate mousewheel scrolling on embedded graphs + // devs can override this with layout._enablescrollzoom, + // but _ ensures this setting won't leave their page + if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) { + return; + } + + if(redrawTimer === null) { + __clearSelect_655(zoomlayer); + } + + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } + + var pc = gd.querySelector('.plotly'); + + recomputeAxisLists(); + + // if the plot has scrollbars (more than a tiny excess) + // disable scrollzoom too. + if(pc.scrollHeight - pc.clientHeight > 10 || + pc.scrollWidth - pc.clientWidth > 10) { + return; + } + + clearTimeout(redrawTimer); + + var wheelDelta = -e.deltaY; + if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if(!isFinite(wheelDelta)) { + _$lib_601.log('Did not find wheel motion attributes: ', e); + return; + } + + var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), + gbb = mainplot.draglayer.select('.nsewdrag') + .node().getBoundingClientRect(), + xfrac = (e.clientX - gbb.left) / gbb.width, + yfrac = (gbb.bottom - e.clientY) / gbb.height, + i; + + function zoomWheelOneAxis(ax, centerFraction, zoom) { + if(ax.fixedrange) return; + + var axRange = _$lib_601.simpleMap(ax.range, ax.r2l), + v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } + ax.range = axRange.map(doZoom); + } + + if(editX) { + // if we're only zooming this axis because of constraints, + // zoom it about the center + if(!ew) xfrac = 0.5; + + for(i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom); + } + + scrollViewBox[2] *= zoom; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); + } + if(editY) { + if(!ns) yfrac = 0.5; + + for(i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom); + } + + scrollViewBox[3] *= zoom; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); + } + + // viewbox redraw at first + updateSubplots(scrollViewBox); + ticksAndAnnotations(ns, ew); + + // then replot after a delay to make sure + // no more scrolling is coming + redrawTimer = setTimeout(function() { + scrollViewBox = [0, 0, pw, ph]; + + var zoomMode; + if(isSubplotConstrained) zoomMode = 'xy'; + else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + + dragTail(zoomMode); + }, REDRAWDELAY); + + e.preventDefault(); + return; + } + + // everything but the corners gets wheel zoom + if(ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); + } + + // plotDrag: move the plot in response to a drag + function plotDrag(dx, dy) { + // If a transition is in progress, then disable any behavior: + if(gd._transitioningWithDuration) { + return; + } + + if(xActive === 'ew' || yActive === 'ns') { + if(xActive) dragAxList(xaxes, dx); + if(yActive) dragAxList(yaxes, dy); + updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); + ticksAndAnnotations(yActive, xActive); + return; + } + + // dz: set a new value for one end (0 or 1) of an axis array axArray, + // and return a pixel shift for that end for the viewbox + // based on pixel drag distance d + // TODO: this makes (generally non-fatal) errors when you get + // near floating point limits + function dz(axArray, end, d) { + var otherEnd = 1 - end, + movedAx, + newLinearizedEnd; + for(var i = 0; i < axArray.length; i++) { + var axi = axArray[i]; + if(axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); + + // if l2r comes back false or undefined, it means we've dragged off + // the end of valid ranges - so stop. + if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / + (movedAx._rl[end] - movedAx._rl[otherEnd]); + } + + if(isSubplotConstrained && xActive && yActive) { + // dragging a corner of a constrained subplot: + // respect the fixed corner, but harmonize dx and dy + var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } + + if(xActive === 'w') dx = dz(xaxes, 0, dx); + else if(xActive === 'e') dx = dz(xaxes, 1, -dx); + else if(!xActive) dx = 0; + + if(yActive === 'n') dy = dz(yaxes, 1, dy); + else if(yActive === 's') dy = dz(yaxes, 0, -dy); + else if(!yActive) dy = 0; + + var x0 = (xActive === 'w') ? dx : 0; + var y0 = (yActive === 'n') ? dy : 0; + + if(isSubplotConstrained) { + var i; + if(!xActive && yActive.length === 1) { + // dragging one end of the y axis of a constrained subplot + // scale the other axis the same about its middle + for(i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + _$scaleZoom_663(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + x0 = dx / 2; + } + if(!yActive && xActive.length === 1) { + for(i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + _$scaleZoom_663(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + y0 = dy / 2; + } + } + + updateSubplots([x0, y0, pw - dx, ph - dy]); + ticksAndAnnotations(yActive, xActive); + } + + // Draw ticks and annotations (and other components) when ranges change. + // Also records the ranges that have changed for use by update at the end. + function ticksAndAnnotations(ns, ew) { + var activeAxIds = [], + i; + + function pushActiveAxIds(axList) { + for(i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } + + if(editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + } + if(editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + } + + updates = {}; + for(i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + doTicks(gd, axId, true); + var ax = __getFromId_655(gd, axId); + updates[ax._name + '.range[0]'] = ax.range[0]; + updates[ax._name + '.range[1]'] = ax.range[1]; + } + + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; + + if((ew && activeAxIds.indexOf(obji.xref) !== -1) || + (ns && activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + // 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 + + redrawObjs(gd._fullLayout.annotations || [], _$registry_731.getComponentMethod('annotations', 'drawOne')); + redrawObjs(gd._fullLayout.shapes || [], _$registry_731.getComponentMethod('shapes', 'drawOne')); + redrawObjs(gd._fullLayout.images || [], _$registry_731.getComponentMethod('images', 'draw'), true); + } + + function doubleClick() { + if(gd._transitioningWithDuration) return; + + var doubleClickConfig = gd._context.doubleClick, + axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []), + attrs = {}; + + var ax, i, rangeInitial; + + // For reset+autosize mode: + // If *any* of the main axes is not at its initial range + // (or autoranged, if we have no initial range, to match the logic in + // doubleClickConfig === 'reset' below), we reset. + // If they are *all* at their initial ranges, then we autosize. + if(doubleClickConfig === 'reset+autosize') { + + doubleClickConfig = 'autosize'; + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if((ax._rangeInitial && ( + ax.range[0] !== ax._rangeInitial[0] || + ax.range[1] !== ax._rangeInitial[1] + )) || + (!ax._rangeInitial && !ax.autorange) + ) { + doubleClickConfig = 'reset'; + break; + } + } + } + + if(doubleClickConfig === 'autosize') { + // don't set the linked axes here, so relayout marks them as shrinkable + // and we autosize just to the requested axis/axes + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; + } + } + else if(doubleClickConfig === 'reset') { + // when we're resetting, reset all linked axes too, so we get back + // to the fully-auto-with-constraints situation + if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes); + if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes); + + if(isSubplotConstrained) { + if(!xActive) axList = axList.concat(xaxes); + else if(!yActive) axList = axList.concat(yaxes); + } + + for(i = 0; i < axList.length; i++) { + ax = axList[i]; + + if(!ax._rangeInitial) { + attrs[ax._name + '.autorange'] = true; + } + else { + rangeInitial = ax._rangeInitial; + attrs[ax._name + '.range[0]'] = rangeInitial[0]; + attrs[ax._name + '.range[1]'] = rangeInitial[1]; + } + } + } + + gd.emit('plotly_doubleclick', null); + _$registry_731.call('relayout', gd, attrs); + } + + // dragTail - finish a drag event with a redraw + function dragTail() { + // put the subplot viewboxes back to default (Because we're going to) + // be repositioning the data in the relayout. But DON'T call + // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` + updateSubplots([0, 0, pw, ph]); + + // since we may have been redrawing some things during the drag, we may have + // accumulated MathJax promises - wait for them before we relayout. + _$lib_601.syncOrAsync([ + _$plots_709.previousPromises, + function() { _$registry_731.call('relayout', gd, updates); } + ], gd); + } + + // updateSubplots - find all plot viewboxes that should be + // affected by this drag, and update them. look for all plots + // sharing an affected axis (including the one being dragged), + // includes also scattergl and splom logic. + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; + + // TODO can we move these to outer scope? + var hasScatterGl = fullLayout._has('scattergl'); + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom'); + var hasSVG = fullLayout._has('svg'); + var hasDraggedPts = fullLayout._has('draggedPts'); + + var i, sp, xa, ya; + + if(hasSplom || hasScatterGl) { + _$clearGlCanvases_585(gd); + } + + if(hasSplom) { + _$registry_731.subplotsRegistry.splom.drag(gd); + if(hasOnlyLargeSploms) return; + } + + if(hasScatterGl) { + // loop over all subplots (w/o exceptions) here, + // as we cleared the gl canvases above + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var scene = sp._scene; + if(scene) { + // FIXME: possibly we could update axis internal _r and _rl here + var xrng = _$lib_601.simpleMap(xa.range, xa.r2l); + var yrng = _$lib_601.simpleMap(ya.range, ya.r2l); + scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]}); + } + } + } + + if(hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; + + for(i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + + var editX2 = editX && !xa.fixedrange && xaHash[xa._id]; + var editY2 = editY && !ya.fixedrange && yaHash[ya._id]; + + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; + + if(editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } + + if(editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } + + // don't scale at all if neither axis is scalable here + if(!xScaleFactor2 && !yScaleFactor2) { + continue; + } + + // but if only one is, reset the other axis scaling + if(!xScaleFactor2) xScaleFactor2 = 1; + if(!yScaleFactor2) yScaleFactor2 = 1; + + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + + // TODO could be more efficient here: + // setTranslate and setScale do a lot of extra work + // when working independently, should perhaps combine + // them into a single routine. + sp.clipRect + .call(_$drawing_498.setTranslate, clipDx, clipDy) + .call(_$drawing_498.setScale, xScaleFactor2, yScaleFactor2); + + sp.plot + .call(_$drawing_498.setTranslate, plotDx, plotDy) + .call(_$drawing_498.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + + // TODO move these selectAll calls out of here + // and stash them somewhere nice, see: + // https://github.com/plotly/plotly.js/issues/2548 + if(hasDraggedPts) { + var traceGroups = sp.plot + .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + + // This is specifically directed at marker points in scatter, box and violin traces, + // applying an inverse scale to individual points to counteract + // the scale of the trace as a whole: + traceGroups.selectAll('.point') + .call(_$drawing_498.setPointGroupScale, xScaleFactor2, yScaleFactor2); + traceGroups.selectAll('.textpoint') + .call(_$drawing_498.setTextPointsScale, xScaleFactor2, yScaleFactor2); + traceGroups + .call(_$drawing_498.hideOutsideRangePoints, sp); + + sp.plot.selectAll('.barlayer .trace') + .call(_$drawing_498.hideOutsideRangePoints, sp, '.bartext'); + } + } + } + } + + // Find the appropriate scaling for this axis, if it's linked to the + // dragged axes by constraints. 0 is special, it means this axis shouldn't + // ever be scaled (will be converted to 1 if the other axis is scaled) + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if(ax.fixedrange) return 0; + + if(editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } + + function scaleAndGetShift(ax, scaleFactor) { + if(scaleFactor) { + ax.range = ax._r.slice(); + _$scaleZoom_663(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } + + function getShift(ax, scaleFactor) { + return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle']; + } + + return dragger; +} + +function makeDragger(plotinfo, nodeName, dragClass, cursor) { + var dragger3 = _$lib_601.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed('drag', true) + .style({fill: 'transparent', 'stroke-width': 0}) + .attr('data-subplot', plotinfo.id); + }); + + dragger3.call(_$setCursor_621, cursor); + + return dragger3.node(); +} + +function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { + var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); + _$d3_130.select(dragger).call(_$drawing_498.setRect, x, y, w, h); + return dragger; +} + +function isDirectionActive(axList, activeVal) { + for(var i = 0; i < axList.length; i++) { + if(!axList[i].fixedrange) return activeVal; + } + return ''; +} + +function getEndText(ax, end) { + var initialVal = ax.range[end], + diff = Math.abs(initialVal - ax.range[1 - end]), + dig; + + // TODO: this should basically be ax.r2d but we're doing extra + // rounding here... can we clean up at all? + if(ax.type === 'date') { + return initialVal; + } + else if(ax.type === 'log') { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return _$d3_130.format('.' + dig + 'g')(Math.pow(10, initialVal)); + } + else { // linear numeric (or category... but just show numbers here) + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - + Math.floor(Math.log(diff) / Math.LN10) + 4; + return _$d3_130.format('.' + String(dig) + 'g')(initialVal); + } +} + +function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + var i, + axi, + axRangeLinear0, + axRangeLinearSpan; + + for(i = 0; i < axList.length; i++) { + axi = axList[i]; + if(axi.fixedrange) continue; + + axRangeLinear0 = axi._rl[0]; + axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + axi.range = [ + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), + axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) + ]; + updates[axi._name + '.range[0]'] = axi.range[0]; + updates[axi._name + '.range[1]'] = axi.range[1]; + } + + // zoom linked axes about their centers + if(linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); + } +} + +function dragAxList(axList, pix) { + for(var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if(!axi.fixedrange) { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + } +} + +// common transform for dragging one end of an axis +// d>0 is compressing scale (cursor is over the plot, +// the axis end should move with the cursor) +// d<0 is expanding (cursor is off the plot, axis end moves +// nonlinearly so you can expand far) +function dZoom(d) { + return 1 - ((d >= 0) ? Math.min(d, 0.9) : + 1 / (1 / Math.max(d, -0.3) + 3.222)); +} + +function getDragCursor(nsew, dragmode, isMainDrag) { + if(!nsew) return 'pointer'; + if(nsew === 'nsew') { + // in this case here, clear cursor and + // use the cursor style set on + if(isMainDrag) return ''; + if(dragmode === 'pan') return 'move'; + return 'crosshair'; + } + return nsew.toLowerCase() + '-resize'; +} + +function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append('path') + .attr('class', 'zoombox') + .style({ + 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', + 'stroke-width': 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', path0 + 'Z'); +} + +function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append('path') + .attr('class', 'zoombox-corners') + .style({ + fill: _$color_473.background, + stroke: _$color_473.defaultLine, + 'stroke-width': 1, + opacity: 0 + }) + .attr('transform', 'translate(' + xs + ', ' + ys + ')') + .attr('d', 'M0,0Z'); +} + +function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr('d', + path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + + 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); + transitionZoombox(zb, corners, dimmed, lum); +} + +function transitionZoombox(zb, corners, dimmed, lum) { + if(!dimmed) { + zb.transition() + .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : + 'rgba(255,255,255,0.3)') + .duration(200); + corners.transition() + .style('opacity', 1) + .duration(200); + } +} + +function removeZoombox(gd) { + _$d3_130.select(gd) + .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') + .remove(); +} + +function showDoubleClickNotifier(gd) { + if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + _$lib_601.notifier(_$lib_601._(gd, 'Double-click to zoom back out'), 'long'); + SHOWZOOMOUTTIP = false; + } +} + +function isSelectOrLasso(dragmode) { + return dragmode === 'lasso' || dragmode === 'select'; +} + +function xCorners(box, y0) { + return 'M' + + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + + (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + + 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; +} + +function yCorners(box, x0) { + return 'M' + + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + + 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + + (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + + 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; +} + +function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return 'M' + + (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + + 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + + 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + + (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + + 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + + (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + + 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; +} + +function calcLinks(gd, xaHash, yaHash) { + var constraintGroups = gd._fullLayout._axisConstraintGroups; + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; + + for(var i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + // check if any of the x axes we're dragging is in this constraint group + for(xID in xaHash) { + if(group[xID]) { + // put the rest of these axes into xLinks, if we're not already + // dragging them, so we know to scale these axes automatically too + // to match the changes in the dragged x axes + for(xLinkID in group) { + if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = 1; + } + } + + // check if the x and y axes of THIS drag are linked + for(yID in yaHash) { + if(group[yID]) isSubplotConstrained = true; + } + } + } + + // now check if any of the y axes we're dragging is in this constraint group + // only look for outside links, as we've already checked for links within the dragger + for(yID in yaHash) { + if(group[yID]) { + for(yLinkID in group) { + if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = 1; + } + } + } + } + } + + if(isSubplotConstrained) { + // merge xLinks and yLinks if the subplot is constrained, + // since we'll always apply both anyway and the two will contain + // duplicates + _$lib_601.extendFlat(xLinks, yLinks); + yLinks = {}; + } + + var xaHashLinked = {}; + var xaxesLinked = []; + for(xLinkID in xLinks) { + var xa = __getFromId_655(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; + } + + var yaHashLinked = {}; + var yaxesLinked = []; + for(yLinkID in yLinks) { + var ya = __getFromId_655(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; + } + + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + isSubplotConstrained: isSubplotConstrained + }; +} + +// still seems to be some confusion about onwheel vs onmousewheel... +function attachWheelEventHandler(element, handler) { + if(!_$hasPassiveEvents_297) { + if(element.onwheel !== undefined) element.onwheel = handler; + else if(element.onmousewheel !== undefined) element.onmousewheel = handler; + } + else { + var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; + + if(element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); + } + element._onwheel = handler; + + element.addEventListener(wheelEventName, handler, {passive: false}); + } +} + +function hashValues(hash) { + var out = []; + for(var k in hash) out.push(hash[k]); + return out; +} + +var _$dragbox_655 = { + makeDragBox: makeDragBox, + + makeDragger: makeDragger, + makeRectDragger: makeRectDragger, + makeZoombox: makeZoombox, + makeCorners: makeCorners, + + updateZoombox: updateZoombox, + xyCorners: xyCorners, + transitionZoombox: transitionZoombox, + removeZoombox: removeZoombox, + showDoubleClickNotifier: showDoubleClickNotifier, + + attachWheelEventHandler: attachWheelEventHandler +}; + +var _$graph_interact_656 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(dx || dy) { - gd._dragged = true; - dragElement.unhover(gd); - } - if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy); +'use strict'; - return; - } +/* removed: var _$d3_130 = require('d3'); */; - function onDone(e) { - document.removeEventListener('mousemove', onMove); - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchmove', onMove); - document.removeEventListener('touchend', onDone); +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; - e.preventDefault(); +var __makeDragBox_656 = _$dragbox_655.makeDragBox; +var DRAGGERSIZE = _$constants_652.DRAGGERSIZE; - if(_$hasHover_239) { - _$lib_539.removeElement(dragCover); - } - else if(cursor) { - dragCover.documentElement.style.cursor = cursor; - cursor = null; - } +_$graph_interact_656.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; - if(!gd._dragging) { - gd._dragged = false; - return; - } - gd._dragging = false; + if(gd._context.staticPlot) { + // this sweeps up more than just cartesian drag elements... + _$d3_130.select(gd).selectAll('.drag').remove(); + return; + } - // don't count as a dblClick unless the mouseUp is also within - // the dblclick delay - if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) { - numClicks = Math.max(numClicks - 1, 1); - } + if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return; - if(gd._dragged) { - if(options.doneFn) options.doneFn(e); + 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'), + 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)); } - else { - if(options.clickFn) options.clickFn(numClicks, initialEvent); + return fullLayout._plots[a].mainplot ? 1 : -1; + }); - // 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; + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; - 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); - } + // 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_656(gd, plotinfo, xa._offset, ya._offset, + xa._length, ya._length, 'ns', 'ew'); - initialTarget.dispatchEvent(e2); - } - } + 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) { + _$fx_515.hover(gd, evt, subplot); + } + }; - finishDrag(gd); + _$fx_515.hover(gd, evt, subplot); - gd._dragged = false; + // 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; + }; - return; - } -}; + /* + * 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; -function coverSlip() { - var cover = document.createElement('div'); + // 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; - 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'; + _$dragelement_495.unhover(gd, evt); + }; - document.body.appendChild(cover); + // corner draggers + if(gd._context.showAxisDragHandles) { + __makeDragBox_656(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); + __makeDragBox_656(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, + DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); + __makeDragBox_656(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, + DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); + __makeDragBox_656(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_656(gd, plotinfo, xa._offset + xa._length * 0.1, y0, + xa._length * 0.8, DRAGGERSIZE, '', 'ew'); + __makeDragBox_656(gd, plotinfo, xa._offset, y0, + xa._length * 0.1, DRAGGERSIZE, '', 'w'); + __makeDragBox_656(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_656(gd, plotinfo, x0, ya._offset + ya._length * 0.1, + DRAGGERSIZE, ya._length * 0.8, 'ns', ''); + __makeDragBox_656(gd, plotinfo, x0, ya._offset + ya._length * 0.9, + DRAGGERSIZE, ya._length * 0.1, 's', ''); + __makeDragBox_656(gd, plotinfo, x0, ya._offset, + DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } + } + }); - return cover; -} + // 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(); -dragElement.coverSlip = coverSlip; + hoverLayer.onmousemove = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_515.hover(gd, evt, fullLayout._hoversubplot); + }; -function finishDrag(gd) { - gd._dragging = false; - if(gd._replotPending) _$registry_668.call('plot', gd); -} + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + _$fx_515.click(gd, evt); + }; -function pointerOffset(e) { - return _$mouseEventOffset_263( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); -} + // also delegate mousedowns... TODO: does this actually work? + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; + + _$graph_interact_656.updateFx(fullLayout); +}; + +// 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. +_$graph_interact_656.updateFx = function(fullLayout) { + var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair'; + _$setCursor_621(fullLayout._draggers, cursor); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -32201,52 +36113,89 @@ function pointerOffset(e) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup = {}; + var axData; + var i, j; -var _$calc_446 = function calc(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; + if(opts.axData) { + // non-x/y case + axData = opts.axData; + } else { + // x/y case + axData = []; + for(i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if(trace[dataAttr + 'axis'] === ax._id) { + axData.push(trace); + } + } + } - function makeCoerceHoverInfo(trace) { - return function(val) { - return _$lib_539.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); - }; + for(i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for(j = 0; j < vals.length; j++) { + var v = vals[j]; + if(v !== null && v !== undefined) { + lookup[v] = 1; + } + } } - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; + return Object.keys(lookup); +} - // 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_668.traceIs(trace, 'pie')) continue; +/** + * Fills in category* default and initial categories. + * + * @param {object} containerIn : input axis object + * @param {object} containerOut : full axis object + * @param {function} coerce : Lib.coerce fn wrapper + * @param {object} opts : + * - data {array} : (full) data trace + * OR + * - axData {array} : (full) data associated with axis being coerced here + * - dataAttr {string} : attribute name corresponding to coordinate array + */ +var _$handleCategoryOrderDefaults_651 = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) { + if(containerOut.type !== 'category') return; - var fillFn = _$registry_668.traceIs(trace, '2dMap') ? paste : _$lib_539.fillArray; + var arrayIn = containerIn.categoryarray; + var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0); - fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace)); + // override default 'categoryorder' value when non-empty array is supplied + var orderDefault; + if(isValidArray) orderDefault = 'array'; - if(!trace.hoverlabel) continue; + var order = coerce('categoryorder', orderDefault); + var array; - 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'); + // coerce 'categoryarray' only in array order case + if(order === 'array') { + array = coerce('categoryarray'); } -}; -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || _$lib_539.identity; + // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray' + if(!isValidArray && order === 'array') { + order = containerOut.categoryorder = 'trace'; + } - if(Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); + // set up things for makeCalcdata + if(order === 'trace') { + containerOut._initialCategories = []; + } else if(order === 'array') { + containerOut._initialCategories = array.slice(); + } else { + array = findCategories(containerOut, opts).sort(); + if(order === 'category ascending') { + containerOut._initialCategories = array; + } else if(order === 'category descending') { + containerOut._initialCategories = array.reverse(); + } } -} +}; -var _$helpers_450 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -32257,216 +36206,310 @@ var _$helpers_450 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +var colorMix = _$tinycolor_414.mix; +var lightFraction = _$attributes_472.lightFraction; +/* removed: var _$lib_601 = require('../../lib'); */; -// look for either subplot or xaxis and yaxis attributes -_$helpers_450.getSubplot = function getSubplot(trace) { - return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo; -}; +/** + * @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 + */ +var _$handleLineGridDefaults_661 = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) { + opts = opts || {}; -// convenience functions for mapping all relevant axes -_$helpers_450.flat = function flat(subplots, v) { - var out = new Array(subplots.length); - for(var i = 0; i < subplots.length; i++) { - out[i] = v; + var dfltColor = opts.dfltColor; + + function coerce2(attr, dflt) { + return _$lib_601.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); } - return out; -}; -_$helpers_450.p2c = function p2c(axArray, v) { - var out = new Array(axArray.length); - for(var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); + 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; } - return out; -}; -_$helpers_450.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) { - if(mode === 'closest') return dxy || _$helpers_450.quadrature(dx, dy); - return mode === 'x' ? dx : dy; -}; + 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); -_$helpers_450.getClosest = function getClosest(cd, distfn, pointData) { - // do we already have a point number? (array mode only) - if(pointData.index !== false) { - if(pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } - else pointData.index = false; + if(!showGridLines) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; } - else { - // apply the distance function to each data point - // this is the longest loop... if this bogs down, we may need - // to create pre-sorted data (by x or y), not sure how to - // do this for 'closest' - for(var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if(newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } + + 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; } } - return pointData; }; -/* - * pseudo-distance function for hover effects on areas: inside the region - * distance is finite (`passVal`), outside it's Infinity. - * - * @param {number} v0: signed difference between the current position and the left edge - * @param {number} v1: signed difference between the current position and the right edge - * @param {number} passVal: the value to return on success - */ -_$helpers_450.inbox = function inbox(v0, v1, passVal) { - return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity; -}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ -_$helpers_450.quadrature = function quadrature(dx, dy) { - return function(di) { - var x = dx(di), - y = dy(di); - return Math.sqrt(x * x + y * y); - }; -}; +'use strict'; -/** Fill event data point object for hover and selection. - * Invokes _module.eventData if present. - * - * N.B. note that point 'index' corresponds to input data array index - * whereas 'number' is its post-transform version. - * - * If the hovered/selected pt corresponds to an multiple input points - * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices' - * are include in the event data. +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; + +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; +/* removed: var _$handleTickValueDefaults_668 = require('./tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('./tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('./tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_651 = require('./category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_661 = require('./line_grid_defaults'); */; +/* removed: var _$setConvert_665 = require('./set_convert'); */; + +/** + * options: object containing: * - * @param {object} pt - * @param {object} trace - * @param {object} cd - * @return {object} + * 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? + * data: the plot data, used to manage categories + * bgColor: the plot background color, to calculate default gridline colors */ -_$helpers_450.makeEventData = function makeEventData(pt, trace, cd) { - // hover uses 'index', select uses 'pointNumber' - var pointNumber = 'index' in pt ? pt.index : pt.pointNumber; +var _$handleAxisDefaults_649 = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) { + var letter = options.letter; + var id = containerOut._id; + var font = options.font || {}; - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber: pointNumber - }; + var visible = coerce('visible', !options.cheateronly); - if(trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; + var axType = containerOut.type; - if(pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; + if(axType === 'date') { + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); } - if(trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if('xVal' in pt) out.x = pt.xVal; - else if('x' in pt) out.x = pt.x; + _$setConvert_665(containerOut, layoutOut); - if('yVal' in pt) out.y = pt.yVal; - else if('y' in pt) out.y = pt.y; + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - if(pt.xa) out.xaxis = pt.xa; - if(pt.ya) out.yaxis = pt.ya; - if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal; - } + // both x and y axes may need autorange done just for the range slider's purposes + // the logic is complicated to figure this out later, particularly for y axes since + // the settings can be spread out in the x axes... so instead we'll collect them + // during supplyDefaults + containerOut._rangesliderAutorange = false; - _$helpers_450.appendArrayPointValue(out, trace, pointNumber); + if(autoRange) coerce('rangemode'); - return out; + coerce('range'); + containerOut.cleanRange(); + + _$handleCategoryOrderDefaults_651(containerIn, containerOut, coerce, options); + + if(axType !== 'category' && !options.noHover) coerce('hoverformat'); + + if(!visible) return containerOut; + + var dfltColor = coerce('color'); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; + // try to get default title from splom trace, fallback to graph-wide value + var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter]; + + coerce('title', dfltTitle); + _$lib_601.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); + + _$handleTickValueDefaults_668(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_666(containerIn, containerOut, coerce, axType, options); + _$handleTickDefaults_667(containerIn, containerOut, coerce, options); + _$handleLineGridDefaults_661(containerIn, containerOut, coerce, { + dfltColor: dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + attributes: _$layout_attributes_659 + }); + + if(containerOut.showline || containerOut.ticks) coerce('mirror'); + + if(options.automargin) coerce('automargin'); + + return containerOut; }; -/** Appends values inside array attributes corresponding to given point number - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {number|Array(number)} pointNumber : point number. May be a length-2 array - * [row, col] to dig into 2D arrays - */ -_$helpers_450.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(!arrayAttrs) { - return; - } - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); +'use strict'; - if(pointData[key] === undefined) { - var val = _$lib_539.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); +/* removed: var _$lib_601 = require('../../lib'); */; +var id2name = _$axis_ids_650.id2name; - if(pointVal !== undefined) pointData[key] = pointVal; + +var _$handleConstraintDefaults_653 = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) { + var constraintGroups = layoutOut._axisConstraintGroups; + var thisID = containerOut._id; + var letter = thisID.charAt(0); + + if(containerOut.fixedrange) return; + + // coerce the constraint mechanics even if this axis has no scaleanchor + // because it may be the anchor of another axis. + coerce('constrain'); + _$lib_601.coerce(containerIn, containerOut, { + constraintoward: { + valType: 'enumerated', + values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'], + dflt: letter === 'x' ? 'center' : 'middle' + } + }, 'constraintoward'); + + if(!containerIn.scaleanchor) return; + + var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut); + + var scaleanchor = _$lib_601.coerce(containerIn, containerOut, { + scaleanchor: { + valType: 'enumerated', + values: constraintOpts.linkableAxes } + }, 'scaleanchor'); + + 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, constraintOpts.thisGroup, + thisID, scaleanchor, scaleratio); + } + else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) { + _$lib_601.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.'); } }; -/** - * Appends values inside array attributes corresponding to given point number array - * For use when pointData references a plot entity that arose (or potentially arose) - * from multiple points in the input data - * - * @param {object} pointData : point data object (gets mutated here) - * @param {object} trace : full trace object - * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers. - * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays - */ -_$helpers_450.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; +function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) { + // 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. - if(!arrayAttrs) { - return; - } + var thisType = layoutOut[id2name(thisID)].type; - for(var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); + var i, j, idj, axj; - if(pointData[key] === undefined) { - var val = _$lib_539.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); + var linkableAxes = []; + for(j = 0; j < allAxisIds.length; j++) { + idj = allAxisIds[j]; + if(idj === thisID) continue; - for(var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); + axj = layoutOut[id2name(idj)]; + if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj); + } + + for(i = 0; i < constraintGroups.length; i++) { + if(constraintGroups[i][thisID]) { + var thisGroup = constraintGroups[i]; + + var linkableAxesNoLoops = []; + for(j = 0; j < linkableAxes.length; j++) { + idj = linkableAxes[j]; + if(!thisGroup[idj]) linkableAxesNoLoops.push(idj); } - pointData[key] = keyVal; + return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup}; } } -}; - -var pointKeyMap = { - ids: 'id', - locations: 'location', - labels: 'label', - values: 'value', - 'marker.colors': 'color' -}; -function getPointKey(astr) { - return pointKeyMap[astr] || astr; + return {linkableAxes: linkableAxes, thisGroup: null}; } -function getPointData(val, pointNumber) { - if(Array.isArray(pointNumber)) { - if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; + +/* + * 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; } - } else { - return val[pointNumber]; } + thisGroup[scaleanchor] = 1; } /** @@ -32480,15 +36523,76 @@ function getPointData(val, pointNumber) { 'use strict'; -// works with our CSS cursor classes (see css/_cursor.scss) -// to apply cursors to d3 single-element selections. -// omit cursor to revert to the default. -var _$setCursor_558 = function setCursor(el3, csr) { - (el3.attr('class') || '').split(' ').forEach(function(cls) { - if(cls.indexOf('cursor-') === 0) el3.classed(cls, false); - }); +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; - if(csr) el3.classed('cursor-' + csr, true); +/* removed: var _$lib_601 = require('../../lib'); */; + + +var _$handlePositionDefaults_662 = function handlePositionDefaults(containerIn, containerOut, coerce, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid = options.grid; + + var dfltAnchor, dfltDomain, dfltSide, dfltPosition; + + if(grid) { + dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]]; + dfltAnchor = grid._anchors[containerOut._id]; + if(dfltDomain) { + dfltSide = grid[letter + 'side'].split(' ')[0]; + dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0]; + } + } + + // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (_$fastIsnumeric_196(containerIn.position) ? 'free' : (counterAxes[0] || 'free')); + dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left'); + dfltPosition = dfltPosition || 0; + + var anchor = _$lib_601.coerce(containerIn, containerOut, { + anchor: { + valType: 'enumerated', + values: ['free'].concat(counterAxes), + dflt: dfltAnchor + } + }, 'anchor'); + + if(anchor === 'free') coerce('position', dfltPosition); + + _$lib_601.coerce(containerIn, containerOut, { + side: { + valType: 'enumerated', + values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'], + dflt: dfltSide + } + }, 'side'); + + var overlaying = false; + if(overlayableAxes.length) { + overlaying = _$lib_601.coerce(containerIn, containerOut, { + overlaying: { + valType: 'enumerated', + values: [false].concat(overlayableAxes), + dflt: false + } + }, 'overlaying'); + } + + if(!overlaying) { + // TODO: right now I'm copying this domain over to overlaying axes + // in ax.setscale()... but this means we still need (imperfect) logic + // in the axes popover to hide domain for the overlaying axis. + // perhaps I should make a private version _domain that all axes get??? + var domain = coerce('domain', dfltDomain); + if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain; + _$lib_601.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + } + + coerce('layer'); + + return containerOut; }; /** @@ -32502,44 +36606,139 @@ var _$setCursor_558 = function setCursor(el3, csr) { 'use strict'; -/* removed: var _$setCursor_558 = require('./setcursor'); */; - -var STASHATTR = 'data-savedcursor'; -var NO_CURSOR = '!!'; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$autoType_648 = require('./axis_autotype'); */; +var name2id = _$axis_ids_650.name2id; /* - * works with our CSS cursor classes (see css/_cursor.scss) - * to override a previous cursor set on d3 single-element selections, - * by moving the name of the original cursor to the data-savedcursor attr. - * omit cursor to revert to the previously set value. + * data: the plot data to use in choosing auto type + * name: axis object name (ie 'xaxis') if one should be stored */ -var _$overrideCursor_550 = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if(csr) { - if(!savedCursor) { - var classes = (el3.attr('class') || '').split(' '); - for(var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if(cls.indexOf('cursor-') === 0) { - el3.attr(STASHATTR, cls.substr(7)) - .classed(cls, false); - } - } - if(!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); +var _$handleTypeDefaults_670 = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) { + // set up some private properties + if(name) { + containerOut._name = name; + containerOut._id = name2id(name); + } + + var axType = coerce('type'); + if(axType === '-') { + setAutoType(containerOut, data); + + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + containerIn.type = containerOut.type; + } + } +}; + +function setAutoType(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; + + var id = ax._id; + var axLetter = id.charAt(0); + + // support 3d + if(id.indexOf('scene') !== -1) id = axLetter; + + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if(!d0) return; + + // first check for histograms, as the count direction + // should always default to a linear axis + if(d0.type === 'histogram' && + axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) { + ax.type = 'linear'; + return; + } + + var calAttr = axLetter + 'calendar'; + var calendar = d0[calAttr]; + var i; + + // check all boxes on this x axis to see + // if they're dates, numbers, or categories + if(isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; + + for(i = 0; i < data.length; i++) { + var trace = data[i]; + if(!_$registry_731.traceIs(trace, 'box-violin') || + (trace[axLetter + 'axis'] || axLetter) !== id) continue; + + if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]); + else if(trace.name !== undefined) boxPositions.push(trace.name); + else boxPositions.push('text'); + + if(trace[calAttr] !== calendar) calendar = undefined; + } + + ax.type = _$autoType_648(boxPositions, calendar); + } + else if(d0.type === 'splom') { + var dimensions = d0.dimensions; + for(i = 0; i < dimensions.length; i++) { + var dim = dimensions[i]; + if(dim.visible) { + ax.type = _$autoType_648(dim.values, calendar); + break; } } - _$setCursor_558(el3, csr); } - else if(savedCursor) { - el3.attr(STASHATTR, null); + else { + ax.type = _$autoType_648(d0[axLetter] || [d0[axLetter + '0']], calendar); + } +} + +function getFirstNonEmptyTrace(data, id, axLetter) { + for(var i = 0; i < data.length; i++) { + var trace = data[i]; + + if(trace.type === 'splom' && + trace._commonLength > 0 && + trace['_' + axLetter + 'axes'][id] + ) { + return trace; + } - if(savedCursor === NO_CURSOR) _$setCursor_558(el3); - else _$setCursor_558(el3, savedCursor); + if((trace[axLetter + 'axis'] || axLetter) === id) { + if(isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } + else if((trace[axLetter] || []).length || trace[axLetter + '0']) { + return trace; + } + } } -}; +} + +function getBoxPosLetter(trace) { + return {v: 'x', h: 'y'}[trace.orientation || 'v']; +} + +function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace), + isBox = _$registry_731.traceIs(trace, 'box-violin'), + isCandlestick = _$registry_731.traceIs(trace._fullInput || {}, 'candlestick'); + + return ( + isBox && + !isCandlestick && + axLetter === posLetter && + trace[posLetter] === undefined && + trace[posLetter + '0'] === undefined + ); +} -var _$hover_451 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -32548,1450 +36747,1244 @@ var _$hover_451 = {}; * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$layout_attributes_700 = require('../layout_attributes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$Events_527 = require('../../lib/events'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$overrideCursor_550 = require('../../lib/override_cursor'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$layout_attributes_659 = require('./layout_attributes'); */; +/* removed: var _$handleTypeDefaults_670 = require('./type_defaults'); */; +/* removed: var _$handleAxisDefaults_649 = require('./axis_defaults'); */; +/* removed: var _$handleConstraintDefaults_653 = require('./constraint_defaults'); */; +/* removed: var _$handlePositionDefaults_662 = require('./position_defaults'); */; +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; -/* removed: var _$helpers_450 = require('./helpers'); */; -/* removed: var _$constants_448 = require('./constants'); */; -// hover labels for multiple horizontal bars get tilted by some angle, -// then need to be offset differently if they overlap -var YANGLE = _$constants_448.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; +var _$supplyLayoutDefaults_660 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + var xaCheater = {}; + var xaNonCheater = {}; + var outerTicks = {}; + var noGrids = {}; + var i; -// expansion of projected height -var YFACTOR = 1 / Math.sin(YA_RADIANS); + // look for axes in the data + for(i = 0; i < fullData.length; i++) { + var trace = fullData[i]; -// to make the appropriate post-rotation x offset, -// you need both x and y offsets -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); + if(!_$registry_731.traceIs(trace, 'cartesian') && !_$registry_731.traceIs(trace, 'gl2d')) { + continue; + } -// size and display constants for hover text -var HOVERARROWSIZE = _$constants_448.HOVERARROWSIZE; -var HOVERTEXTPAD = _$constants_448.HOVERTEXTPAD; + var xaName = _$axis_ids_650.id2name(trace.xaxis); + var yaName = _$axis_ids_650.id2name(trace.yaxis); -// fx.hover: highlight data on hover -// evt can be a mousemove event, or an object with data about what points -// to hover on -// {xpx,ypx[,hovermode]} - pixel locations from top left -// (with optional overriding hovermode) -// {xval,yval[,hovermode]} - data values -// [{curveNumber,(pointNumber|xval and/or yval)}] - -// array of specific points to highlight -// pointNumber is a single integer if gd.data[curveNumber] is 1D, -// or a two-element array if it's 2D -// xval and yval are data values, -// 1D data may specify either or both, -// 2D data must specify both -// subplot is an id string (default "xy") -// makes use of gl.hovermode, which can be: -// x (find the points with the closest x values, ie a column), -// closest (find the single closest point) -// internally there are two more that occasionally get used: -// y (pick out a row - only used for multiple horizontal bar charts) -// array (used when the user specifies an explicit -// array of points to hover on) -// -// We wrap the hovers in a timer, to limit their frequency. -// The actual rendering is done by private function _hover. -_$hover_451.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = _$lib_539.getGraphDiv(gd); + // Two things trigger axis visibility: + // 1. is not carpet + // 2. carpet that's not cheater + if(!_$registry_731.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) { + if(xaName) xaNonCheater[xaName] = 1; + } - _$lib_539.throttle( - gd._fullLayout._uid + _$constants_448.HOVERID, - _$constants_448.HOVERMINTIME, - function() { _hover(gd, evt, subplot, noHoverEvent); } - ); -}; + // 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) xaCheater[xaName] = 1; + } -/* - * Draw a single hover item in a pre-existing svg container somewhere - * hoverItem should have keys: - * - x and y (or x0, x1, y0, and y1): - * the pixel position to mark, relative to opts.container - * - xLabel, yLabel, zLabel, text, and name: - * info to go in the label - * - color: - * the background color for the label. - * - idealAlign (optional): - * 'left' or 'right' for which side of the x/y box to try to put this on first - * - borderColor (optional): - * color for the border, defaults to strongest contrast with color - * - fontFamily (optional): - * string, the font for this label, defaults to constants.HOVERFONT - * - fontSize (optional): - * the label font size, defaults to constants.HOVERFONTSIZE - * - fontColor (optional): - * defaults to borderColor - * opts should have keys: - * - bgColor: - * the background color this is against, used if the trace is - * non-opaque, and for the name, which goes outside the box - * - container: - * a or element to add the hover label to - * - outerContainer: - * normally a parent of `container`, sets the bounding box to use to - * constrain the hover label and determine whether to show it on the left or right - */ -_$hover_451.loneHover = function loneHover(hoverItem, opts) { - var pointData = { - color: hoverItem.color || _$color_411.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, + // check for default formatting tweaks + if(_$registry_731.traceIs(trace, '2dMap')) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } + + if(_$registry_731.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_601.simpleMap(xIds, _$axis_ids_650.id2name); + var yNames = _$lib_601.simpleMap(yIds, _$axis_ids_650.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 plot_bgcolor = _$color_473.background; + if(xIds.length && yIds.length) { + plot_bgcolor = _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_700, 'plot_bgcolor'); + } + + var bgColor = _$color_473.combine(plot_bgcolor, layoutOut.paper_bgcolor); + + var axName, axLetter, axLayoutIn, axLayoutOut; + + function coerce(attr, dflt) { + return _$lib_601.coerce(axLayoutIn, axLayoutOut, _$layout_attributes_659, attr, dflt); + } + + function coerce2(attr, dflt) { + return _$lib_601.coerce2(axLayoutIn, axLayoutOut, _$layout_attributes_659, attr, dflt); + } + + function getCounterAxes(axLetter) { + return (axLetter === 'x') ? yIds : xIds; + } + + var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('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(_$axis_ids_650.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]; + + if(!_$lib_601.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } + + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName] = {}; + + _$handleTypeDefaults_670(axLayoutIn, axLayoutOut, coerce, fullData, axName); + + axLetter = axName.charAt(0); + var overlayableAxes = getOverlayableAxes(axLetter, axName); + + var defaultOptions = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: fullData, + bgColor: bgColor, + calendar: layoutOut.calendar, + automargin: true, + cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName] + }; + + _$handleAxisDefaults_649(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut); + + var spikecolor = coerce2('spikecolor'), + spikethickness = coerce2('spikethickness'), + spikedash = coerce2('spikedash'), + spikemode = coerce2('spikemode'), + spikesnap = coerce2('spikesnap'), + 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; + } + + var positioningOptions = { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: overlayableAxes, + grid: layoutOut.grid + }; + + _$handlePositionDefaults_662(axLayoutIn, axLayoutOut, coerce, positioningOptions); + + axLayoutOut._input = axLayoutIn; + } + + // quick second pass for range slider and selector defaults + var rangeSliderDefaults = _$registry_731.getComponentMethod('rangeslider', 'handleDefaults'); + var rangeSelectorDefaults = _$registry_731.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[_$axis_ids_650.id2name(axLayoutOut.anchor)]; + + var fixedRangeDflt = ( + anchoredAxis && + anchoredAxis.rangeslider && + anchoredAxis.rangeslider.visible + ); - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, + coerce('fixedrange', fixedRangeDflt); + } - // filler to make createHoverText happy - trace: { - index: 0, - hoverinfo: '' - }, - xa: {_offset: 0}, - ya: {_offset: 0}, - index: 0 - }; + // Finally, handle scale constraints. 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). - var container3 = _$d3_127.select(opts.container), - outerContainer3 = opts.outerContainer ? - _$d3_127.select(opts.outerContainer) : container3; + // sets of axes linked by `scaleanchor` along with the scaleratios compounded + // together, populated in handleConstraintDefaults + layoutOut._axisConstraintGroups = []; + var allAxisIds = counterAxes.x.concat(counterAxes.y); - var fullOpts = { - hovermode: 'closest', - rotateLabels: false, - bgColor: opts.bgColor || _$color_411.background, - container: container3, - outerContainer: outerContainer3 - }; + for(i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axLetter = axName.charAt(0); - var hoverLabel = createHoverText([pointData], fullOpts, opts.gd); - alignHoverText(hoverLabel, fullOpts.rotateLabels); + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; - return hoverLabel.node(); + _$handleConstraintDefaults_653(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut); + } }; -// The actual implementation is here: -function _hover(gd, evt, subplot, noHoverEvent) { - if(!subplot) subplot = 'xy'; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; +'use strict'; - var fullLayout = gd._fullLayout; - var plots = fullLayout._plots || []; - var plotinfo = plots[subplot]; - var hasCartesian = fullLayout._has('cartesian'); +/* removed: var _$d3_130 = require('d3'); */; - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$axes_647 = require('./axes'); */; +var axisRegex = _$constants_652.attrRegex; - subplots = subplots.concat(overlayedSubplots); - } +var _$transitionAxes_669 = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var axes = []; - var len = subplots.length; - var xaArray = new Array(len); - var yaArray = new Array(len); - var supportsCompare = false; + function computeUpdates(layout) { + var ai, attrList, match, axis, update; + var updates = {}; - for(var i = 0; i < len; i++) { - var spId = subplots[i]; + for(ai in layout) { + attrList = ai.split('.'); + match = attrList[0].match(axisRegex); + if(match) { + var axisLetter = ai.charAt(0); + var axisName = attrList[0]; + axis = fullLayout[axisName]; + update = {}; - // 'cartesian' case - var plotObj = plots[spId]; - if(plotObj) { - supportsCompare = true; + if(Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if(Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if(!update.to) continue; - // TODO make sure that fullLayout_plots axis refs - // get updated properly so that we don't have - // to use Axes.getFromId in general. + update.axisName = axisName; + update.length = axis._length; - xaArray[i] = _$axes_584.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = _$axes_584.getFromId(gd, plotObj.yaxis._id); - continue; + axes.push(axisLetter); + + updates[axisLetter] = update; + } } - // other subplot types - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; + return updates; } - var hovermode = evt.hovermode || fullLayout.hovermode; + function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + var toX, toY; - if(hovermode && !supportsCompare) hovermode = 'closest'; + for(plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; - if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || - gd.querySelector('.zoombox') || gd._dragging) { - return _$dragelement_433.unhoverRaw(gd, evt); - } + if(affectedSubplots.indexOf(plotinfo) !== -1) continue; - var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance; - var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance; + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + var fromX = plotinfo.xaxis.range; + var fromY = plotinfo.yaxis.range; - // hoverData: the set of candidate points we've found to highlight - var hoverData = [], + // Store the initial range at the beginning of this transition: + plotinfo.xaxis._r = plotinfo.xaxis.range.slice(); + plotinfo.yaxis._r = plotinfo.yaxis.range.slice(); - // searchData: the data to search in. Mostly this is just a copy of - // gd.calcdata, filtered to the subplot and overlays we're on - // but if a point array is supplied it will be a mapping - // of indicated curves - searchData = [], + if(updates[x]) { + toX = updates[x].to; + } else { + toX = fromX; + } + if(updates[y]) { + toY = updates[y].to; + } else { + toY = fromY; + } - // [x|y]valArray: the axis values of the hover event - // mapped onto each of the currently selected overlaid subplots - xvalArray, - yvalArray, + if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue; - // used in loops - itemnum, - curvenum, - cd, - trace, - subplotId, - subploti, - mode, - xval, - yval, - pointData, - closedataPreviousLength, + if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } + } - // spikePoints: the set of candidate points we've found to draw spikes to - spikePoints = { - hLinePoint: null, - vLinePoint: null - }; + return affectedSubplots; + } - // Figure out what we're hovering on: - // mouse location or user-supplied data + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates); - if(Array.isArray(evt)) { - // user specified an array of points to highlight - hovermode = 'array'; - for(itemnum = 0; itemnum < evt.length; itemnum++) { - cd = gd.calcdata[evt[itemnum].curveNumber||0]; - if(cd[0].trace.hoverinfo !== 'skip') { - searchData.push(cd); + function updateLayoutObjs() { + function redrawObjs(objArray, method, shortCircuit) { + for(var i = 0; i < objArray.length; i++) { + method(gd, i); + + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; } } + + redrawObjs(fullLayout.annotations || [], _$registry_731.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_731.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_731.getComponentMethod('images', 'draw'), true); } - else { - for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) { - cd = gd.calcdata[curvenum]; - trace = cd[0].trace; - if(trace.hoverinfo !== 'skip' && subplots.indexOf(_$helpers_450.getSubplot(trace)) !== -1) { - searchData.push(cd); - } - } - // [x|y]px: the pixels (from top left) of the mouse location - // on the currently selected plot area - // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation - var hasUserCalledHover = !evt.target, - xpx, ypx; + if(!affectedSubplots.length) { + updateLayoutObjs(); + return false; + } - if(hasUserCalledHover) { - if('xpx' in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - evt.pointerX = xpx + xaArray[0]._offset; + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; - if('ypx' in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - evt.pointerY = ypx + yaArray[0]._offset; + activeAxIds = [xa._id, ya._id]; + + for(i = 0; i < activeAxIds.length; i++) { + _$axes_647.doTicks(gd, activeAxIds[i], true); } - else { - // fire the beforehover event and quit if it returns false - // note that we're only calling this on real mouse events, so - // manual calls to fx.hover will always run. - if(_$Events_527.triggerHandler(gd, 'plotly_beforehover', evt) === false) { - return; - } - var dbb = evt.target.getBoundingClientRect(); + function redrawObjs(objArray, method, shortCircuit) { + for(i = 0; i < objArray.length; i++) { + var obji = objArray[i]; - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + method(gd, i); + } - // in case hover was called from mouseout into hovertext, - // it's possible you're not actually over the plot anymore - if(xpx < 0 || xpx > dbb.width || ypx < 0 || ypx > dbb.height) { - return _$dragelement_433.unhoverRaw(gd, evt); + // once is enough for images (which doesn't use the `i` arg anyway) + if(shortCircuit) return; } - evt.pointerX = evt.offsetX; - evt.pointerY = evt.offsetY; } - if('xval' in evt) xvalArray = _$helpers_450.flat(subplots, evt.xval); - else xvalArray = _$helpers_450.p2c(xaArray, xpx); + redrawObjs(fullLayout.annotations || [], _$registry_731.getComponentMethod('annotations', 'drawOne')); + redrawObjs(fullLayout.shapes || [], _$registry_731.getComponentMethod('shapes', 'drawOne')); + redrawObjs(fullLayout.images || [], _$registry_731.getComponentMethod('images', 'draw'), true); + } - if('yval' in evt) yvalArray = _$helpers_450.flat(subplots, evt.yval); - else yvalArray = _$helpers_450.p2c(yaArray, ypx); + function unsetSubplotTransform(subplot) { + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - if(!_$fastIsnumeric_139(xvalArray[0]) || !_$fastIsnumeric_139(yvalArray[0])) { - _$lib_539.warn('Fx.hover failed', evt, gd); - return _$dragelement_433.unhoverRaw(gd, evt); - } - } + fullLayout._defs.select('#' + subplot.clipId + '> rect') + .call(_$drawing_498.setTranslate, 0, 0) + .call(_$drawing_498.setScale, 1, 1); - // the pixel distance to beat as a matching point - // in 'x' or 'y' mode this resets for each trace - var distance = Infinity; + subplot.plot + .call(_$drawing_498.setTranslate, xa2._offset, ya2._offset) + .call(_$drawing_498.setScale, 1, 1); - // find the closest point in each trace - // this is minimum dx and/or dy, depending on mode - // and the pixel position for the label (labelXpx, labelYpx) - for(curvenum = 0; curvenum < searchData.length; curvenum++) { - cd = searchData[curvenum]; + var traceGroups = subplot.plot.selectAll('.scatterlayer .trace'); - // filter out invisible or broken data - if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue; + // 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_498.setPointGroupScale, 1, 1); + traceGroups.selectAll('.textpoint') + .call(_$drawing_498.setTextPointsScale, 1, 1); + traceGroups + .call(_$drawing_498.hideOutsideRangePoints, subplot); + } - trace = cd[0].trace; + function updateSubplot(subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; - // Explicitly bail out for these two. I don't know how to otherwise prevent - // the rest of this function from running and failing - if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue; + var viewBox = []; - subplotId = _$helpers_450.getSubplot(trace); - subploti = subplots.indexOf(subplotId); + if(xUpdate) { + axis = gd._fullLayout[xUpdate.axisName]; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; - // within one trace mode can sometimes be overridden - mode = hovermode; + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - // container for new point, also used to pass info into module.hoverPoints - pointData = { - // trace properties - cd: cd, - trace: trace, - xa: xaArray[subploti], - ya: yaArray[subploti], + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; + } - // max distances for hover and spikes - for points that want to show but do not - // want to override other points, set distance/spikeDistance equal to max*Distance - // and it will not get filtered out but it will be guaranteed to have a greater - // distance than any point that calculated a real distance. - maxHoverDistance: hoverdistance, - maxSpikeDistance: spikedistance, + if(yUpdate) { + axis = gd._fullLayout[yUpdate.axisName]; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; - // point properties - override all of these - index: false, // point index in trace - only used by plotly.js hoverdata consumers - distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; - // distance/pseudo-distance for spikes. This distance should always be calculated - // as if in "closest" mode, and should only be set if this point should - // generate a spike. - spikeDistance: Infinity, + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; + } - // in some cases the spikes have different positioning from the hover label - // they don't need x0/x1, just one position - xSpike: undefined, - ySpike: undefined, + ticksAndAnnotations(subplot.xaxis, subplot.yaxis); - // where and how to display the hover label - color: _$color_411.defaultLine, // trace color - name: trace.name, - x0: undefined, - x1: undefined, - y0: undefined, - y1: undefined, - xLabelVal: undefined, - yLabelVal: undefined, - zLabelVal: undefined, - text: undefined - }; + var xa2 = subplot.xaxis; + var ya2 = subplot.yaxis; - // add ref to subplot object (non-cartesian case) - if(fullLayout[subplotId]) { - pointData.subplot = fullLayout[subplotId]._subplot; - } + var editX = !!xUpdate; + var editY = !!yUpdate; - closedataPreviousLength = hoverData.length; + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; - // for a highlighting array, figure out what - // we're searching for with this element - if(mode === 'array') { - var selection = evt[curvenum]; - if('pointNumber' in selection) { - pointData.index = selection.pointNumber; - mode = 'closest'; - } - else { - mode = ''; - if('xval' in selection) { - xval = selection.xval; - mode = 'x'; - } - if('yval' in selection) { - yval = selection.yval; - mode = mode ? 'closest' : 'y'; - } - } - } - else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; - } + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; - // Now if there is range to look in, find the points to hover. - if(hoverdistance !== 0) { - if(trace._module && trace._module.hoverPoints) { - var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer); - if(newPoints) { - var newPoint; - for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { - newPoint = newPoints[newPointNum]; - if(_$fastIsnumeric_139(newPoint.x0) && _$fastIsnumeric_139(newPoint.y0)) { - hoverData.push(cleanPoint(newPoint, hovermode)); - } - } - } - } - else { - _$lib_539.log('Unrecognized trace type in hover:', trace); - } - } + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; - // in closest mode, remove any existing (farther) points - // and don't look any farther than this latest point (or points, some - // traces like box & violin make multiple hover labels at once) - if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; - } + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; - // Now if there is range to look in, find the points to draw the spikelines - // Do it only if there is no hoverData - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length === 0) { - pointData.distance = spikedistance; - pointData.index = false; - var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer); - if(closestPoints) { - closestPoints = closestPoints.filter(function(point) { - // some hover points, like scatter fills, do not allow spikes, - // so will generate a hover point but without a valid spikeDistance - return point.spikeDistance <= spikedistance; - }); - } - if(closestPoints && closestPoints.length) { - var tmpPoint; - var closestVPoints = closestPoints.filter(function(point) { - return point.xa.showspikes; - }); - if(closestVPoints.length) { - var closestVPt = closestVPoints[0]; - if(_$fastIsnumeric_139(closestVPt.x0) && _$fastIsnumeric_139(closestVPt.y0)) { - tmpPoint = fillSpikePoint(closestVPt); - if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.vLinePoint = tmpPoint; - } - } - } + subplot.clipRect + .call(_$drawing_498.setTranslate, clipDx, clipDy) + .call(_$drawing_498.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - var closestHPoints = closestPoints.filter(function(point) { - return point.ya.showspikes; - }); - if(closestHPoints.length) { - var closestHPt = closestHPoints[0]; - if(_$fastIsnumeric_139(closestHPt.x0) && _$fastIsnumeric_139(closestHPt.y0)) { - tmpPoint = fillSpikePoint(closestHPt); - if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } - } - } - } + subplot.plot + .call(_$drawing_498.setTranslate, plotDx, plotDy) + .call(_$drawing_498.setScale, xScaleFactor, yScaleFactor) - function selectClosestPoint(pointsData, spikedistance) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for(var i = 0; i < pointsData.length; i++) { - thisSpikeDistance = pointsData[i].spikeDistance; - if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) { - resultPoint = pointsData[i]; - minDistance = thisSpikeDistance; - } - } - return resultPoint; - } + // This is specifically directed at scatter traces, applying an inverse + // scale to individual points to counteract the scale of the trace + // as a whole: + .selectAll('.points').selectAll('.point') + .call(_$drawing_498.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor); - function fillSpikePoint(point) { - if(!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; + subplot.plot.selectAll('.points').selectAll('.textpoint') + .call(_$drawing_498.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor); } - var spikelineOpts = { - fullLayout: fullLayout, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - event: evt - }; - var oldspikepoints = gd._spikepoints, - newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; + var onComplete; + if(makeOnCompleteCallback) { + // This module makes the choice whether or not it notifies Plotly.transition + // about completion: + onComplete = makeOnCompleteCallback(); + } - // Now if it is not restricted by spikedistance option, set the points to draw the spikelines - if(hasCartesian && (spikedistance !== 0)) { - if(hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); + function transitionComplete() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName]; + var to = updates[updatedAxisIds[i]].to; + aobj[axi._name + '.range[0]'] = to[0]; + aobj[axi._name + '.range[1]'] = to[1]; - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + axi.range = to.slice(); } - } - // if hoverData is empty check for the spikes to draw and quit if there are none - if(hoverData.length === 0) { - var result = _$dragelement_433.unhoverRaw(gd, evt); - if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); + // Signal that this transition has completed: + onComplete && onComplete(); + + return _$registry_731.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); } - } - return result; + }); } - if(hasCartesian) { - if(spikesChanged(oldspikepoints)) { - createSpikelines(spikePoints, spikelineOpts); + function transitionInterrupt() { + var aobj = {}; + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = gd._fullLayout[updatedAxisIds[i] + 'axis']; + aobj[axi._name + '.range[0]'] = axi.range[0]; + aobj[axi._name + '.range[1]'] = axi.range[1]; + + axi.range = axi._r.slice(); } + + return _$registry_731.call('relayout', gd, aobj).then(function() { + for(var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + }); } - hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; }); + var t1, t2, raf; + var easeFn = _$d3_130.ease(transitionOpts.easing); - // lastly, emit custom hover/unhover events - var oldhoverdata = gd._hoverdata, - newhoverdata = []; + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); - // pull out just the data that's useful to - // other people and send it to the event - for(itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - newhoverdata.push(_$helpers_450.makeEventData(pt, pt.trace, pt.cd)); + function doFrame() { + t2 = Date.now(); + + var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration); + var progress = easeFn(tInterp); + + for(var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } + + if(t2 - t1 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); + } } - gd._hoverdata = newhoverdata; + t1 = Date.now(); + raf = window.requestAnimationFrame(doFrame); - // if there's more than one horz bar trace, - // rotate the labels so they don't overlap - var rotateLabels = hovermode === 'y' && searchData.length > 1; + return Promise.resolve(); +}; - var bgColor = _$color_411.combine( - fullLayout.plot_bgcolor || _$color_411.background, - fullLayout.paper_bgcolor - ); +var _$get_data_683 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 labelOpts = { - hovermode: hovermode, - rotateLabels: rotateLabels, - bgColor: bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paperdiv, - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }; +'use strict'; - var hoverLabels = createHoverText(hoverData, labelOpts, gd); +/* removed: var _$registry_731 = require('../registry'); */; +var SUBPLOT_PATTERN = _$constants_652.SUBPLOT_PATTERN; - hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout); +/** + * Get calcdata trace(s) associated with a given subplot + * + * @param {array} calcData: as in gd.calcdata + * @param {string} type: subplot type + * @param {string} subplotId: subplot id to look for + * + * @return {array} array of calcdata traces + */ +_$get_data_683.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = _$registry_731.subplotsRegistry[type]; + if(!basePlotModule) return []; - alignHoverText(hoverLabels, rotateLabels); + var attr = basePlotModule.attr; + var subplotCalcData = []; - // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true - // we should improve the "fx" API so other plots can use it without these hack. - if(evt.target && evt.target.tagName) { - var hasClickToShow = _$registry_668.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata); - _$overrideCursor_550(_$d3_127.select(evt.target), hasClickToShow ? 'pointer' : ''); + for(var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; + + if(trace[attr] === subplotId) subplotCalcData.push(calcTrace); } - // don't emit events if called manually - if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; + return subplotCalcData; +}; +/** + * Get calcdata trace(s) that can be plotted with a given module + * NOTE: this isn't necessarily just exactly matching trace type, + * if multiple trace types use the same plotting routine, they will be + * collected here. + * In order to not plot the same thing multiple times, we return two arrays, + * the calcdata we *will* plot with this module, and the ones we *won't* + * + * @param {array} calcdata: as in gd.calcdata + * @param {object|string} typeOrModule: the plotting module, or its name + * + * @return {array[array]} [foundCalcdata, remainingCalcdata] + */ +_$get_data_683.getModuleCalcData = function(calcdata, typeOrModule) { + var moduleCalcData = []; + var remainingCalcData = []; + var _module = typeof typeOrModule === 'string' ? _$registry_731.getModule(typeOrModule) : typeOrModule; + if(!_module) return [moduleCalcData, calcdata]; - if(oldhoverdata) { - gd.emit('plotly_unhover', { - event: evt, - points: oldhoverdata - }); - } + for(var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if(trace.visible !== true) continue; - gd.emit('plotly_hover', { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); -} + // we use this to find data to plot - so if there's a .plot + if(trace._module.plot === _module.plot) { + moduleCalcData.push(cd); + } + else { + remainingCalcData.push(cd); + } + } -function createHoverText(hoverData, opts, gd) { - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; + return [moduleCalcData, remainingCalcData]; +}; - // opts.fontFamily/Size are used for the common label - // and as defaults for each hover label, though the individual labels - // can override this. - var fontFamily = opts.fontFamily || _$constants_448.HOVERFONT; - var fontSize = opts.fontSize || _$constants_448.HOVERFONTSIZE; +/** + * Get the data trace(s) associated with a given subplot. + * + * @param {array} data plotly full data array. + * @param {string} type subplot type to look for. + * @param {string} subplotId subplot id to look for. + * + * @return {array} list of trace objects. + * + */ +_$get_data_683.getSubplotData = function getSubplotData(data, type, subplotId) { + if(!_$registry_731.subplotsRegistry[type]) return []; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel'; - var t0 = c0[commonAttr]; - var t00 = (String(t0) || '').split(' ')[0]; - var outerContainerBB = outerContainer.node().getBoundingClientRect(); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; + var attr = _$registry_731.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; - // show the common label, if any, on the axis - // never show a common label in array mode, - // even if sometimes there could be one - var showCommonLabel = ( - (t0 !== undefined) && - (c0.distance <= opts.hoverdistance) && - (hovermode === 'x' || hovermode === 'y') - ); + if(type === 'gl2d') { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = 'x' + spmatch[1]; + subplotY = 'y' + spmatch[2]; + } - // all hover traces hoverinfo must contain the hovermode - // to have common labels - if(showCommonLabel) { - var i, traceHoverinfo; - var allHaveZ = true; - for(i = 0; i < hoverData.length; i++) { - if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false; + for(var i = 0; i < data.length; i++) { + trace = data[i]; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+'); - if(parts.indexOf('all') === -1 && - parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; + if(type === 'gl2d' && _$registry_731.traceIs(trace, 'gl2d')) { + if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); } } - - // xyz labels put all info in their main label, so have no need of a common label - if(allHaveZ) showCommonLabel = false; + else { + if(trace[attr] === subplotId) subplotData.push(trace); + } } - var commonLabel = container.selectAll('g.axistext') - .data(showCommonLabel ? [0] : []); - commonLabel.enter().append('g') - .classed('axistext', true); - commonLabel.exit().remove(); + return subplotData; +}; - commonLabel.each(function() { - var label = _$d3_127.select(this), - lpath = label.selectAll('path').data([0]), - ltext = label.selectAll('text').data([0]); +var _$cartesian_658 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - lpath.enter().append('path') - .style({'stroke-width': '1px'}); - lpath.style({ - fill: commonLabelOpts.bgcolor || _$color_411.defaultLine, - stroke: commonLabelOpts.bordercolor || _$color_411.background, - }); +'use strict'; - ltext.enter().append('text') - // prohibit tex interpretation until we can handle - // tex and regular text together - .attr('data-notex', 1); +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../plots'); */; +var getModuleCalcData = _$get_data_683.getModuleCalcData; - ltext.text(t0) - .call(_$drawing_436.font, - commonLabelOpts.font.family || fontFamily, - commonLabelOpts.font.size || fontSize, - commonLabelOpts.font.color || _$color_411.background - ) - .call(_$svg_text_utils_562.positionText, 0, 0) - .call(_$svg_text_utils_562.convertToTspans, gd); +/* removed: var _$axis_ids_650 = require('./axis_ids'); */; +/* removed: var _$constants_652 = require('./constants'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; - label.attr('transform', ''); +var ensureSingle = _$lib_601.ensureSingle; - var tbb = ltext.node().getBoundingClientRect(); - if(hovermode === 'x') { - ltext.attr('text-anchor', 'middle') - .call(_$svg_text_utils_562.positionText, 0, (xa.side === 'top' ? - (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) : - (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD))); +function ensureSingleAndAddDatum(parent, nodeType, className) { + return _$lib_601.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} - var topsign = xa.side === 'top' ? '-' : ''; - lpath.attr('d', 'M0,0' + - 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE + - 'H' + (HOVERTEXTPAD + tbb.width / 2) + - 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) + - 'H-' + (HOVERTEXTPAD + tbb.width / 2) + - 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z'); +_$cartesian_658.name = 'cartesian'; - label.attr('transform', 'translate(' + - (xa._offset + (c0.x0 + c0.x1) / 2) + ',' + - (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')'); - } - else { - ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end') - .call(_$svg_text_utils_562.positionText, - (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE), - outerTop - tbb.top - tbb.height / 2); +_$cartesian_658.attr = ['xaxis', 'yaxis']; - var leftsign = ya.side === 'right' ? '' : '-'; - lpath.attr('d', 'M0,0' + - 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE + - 'V' + (HOVERTEXTPAD + tbb.height / 2) + - 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) + - 'V-' + (HOVERTEXTPAD + tbb.height / 2) + - 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z'); +_$cartesian_658.idRoot = ['x', 'y']; - label.attr('transform', 'translate(' + - (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' + - (ya._offset + (c0.y0 + c0.y1) / 2) + ')'); - } - // remove the "close but not quite" points - // because of error bars, only take up to a space - hoverData = hoverData.filter(function(d) { - return (d.zLabelVal !== undefined) || - (d[commonAttr] || '').split(' ')[0] === t00; - }); - }); +_$cartesian_658.idRegex = _$constants_652.idRegex; - // show all the individual labels +_$cartesian_658.attrRegex = _$constants_652.attrRegex; - // first create the objects - var hoverLabels = container.selectAll('g.hovertext') - .data(hoverData, function(d) { - return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(','); - }); - hoverLabels.enter().append('g') - .classed('hovertext', true) - .each(function() { - var g = _$d3_127.select(this); - // trace name label (rect and text.name) - g.append('rect') - .call(_$color_411.fill, _$color_411.addOpacity(bgColor, 0.8)); - g.append('text').classed('name', true); - // trace data label (path and text.nums) - g.append('path') - .style('stroke-width', '1px'); - g.append('text').classed('nums', true) - .call(_$drawing_436.font, fontFamily, fontSize); - }); - hoverLabels.exit().remove(); +_$cartesian_658.attributes = _$attributes_645; - // then put the text in, position the pointer to the data, - // and figure out sizes - hoverLabels.each(function(d) { - var g = _$d3_127.select(this).attr('transform', ''), - name = '', - text = ''; +_$cartesian_658.layoutAttributes = _$layout_attributes_659; - // combine possible non-opaque trace color with bgColor - var baseColor = _$color_411.opacity(d.color) ? d.color : _$color_411.defaultLine; - var traceColor = _$color_411.combine(baseColor, bgColor); +_$cartesian_658.supplyLayoutDefaults = _$supplyLayoutDefaults_660; - // find a contrasting color for border and text - var contrastColor = d.borderColor || _$color_411.contrast(traceColor); +_$cartesian_658.transitionAxes = _$transitionAxes_669; - // to get custom 'name' labels pass cleanPoint - if(d.nameOverride !== undefined) d.name = d.nameOverride; +_$cartesian_658.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; - if(d.name) { - // strip out our pseudo-html elements from d.name (if it exists at all) - name = _$svg_text_utils_562.plainText(d.name || ''); + for(i = 0; i < spAll.length; i++) { + var parts = spAll[i].split('y'); + allX[parts[0]] = 1; + allY['y' + parts[1]] = 1; + } - var nameLength = Math.round(d.nameLength); + // check for x axes with no subplot, and make one from the anchor of that x axis + for(i = 0; i < xList.length; i++) { + xi = xList[i]; + if(!allX[xi]) { + yi = (layoutIn[_$axis_ids_650.id2name(xi)] || {}).anchor; + if(!_$constants_652.idRegex.y.test(yi)) yi = 'y'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - if(nameLength > -1 && name.length > nameLength) { - if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...'; - else name = name.substr(0, nameLength); + if(!allY[yi]) { + allY[yi] = 1; + _$lib_601.pushUnique(yList, yi); } } + } - // used by other modules (initially just ternary) that - // manage their own hoverinfo independent of cleanPoint - // the rest of this will still apply, so such modules - // can still put things in (x|y|z)Label, text, and name - // and hoverinfo will still determine their visibility - if(d.extraText !== undefined) text += d.extraText; + // same for y axes with no subplot + for(i = 0; i < yList.length; i++) { + yi = yList[i]; + if(!allY[yi]) { + xi = (layoutIn[_$axis_ids_650.id2name(yi)] || {}).anchor; + if(!_$constants_652.idRegex.x.test(xi)) xi = 'x'; + spSVG.push(xi + yi); + spAll.push(xi + yi); - if(d.zLabel !== undefined) { - if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '
'; - if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '
'; - text += (text ? 'z: ' : '') + d.zLabel; - } - else if(showCommonLabel && d[hovermode + 'Label'] === t0) { - text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || ''; - } - else if(d.xLabel === undefined) { - if(d.yLabel !== undefined) text = d.yLabel; + if(!allX[xi]) { + allX[xi] = 1; + _$lib_601.pushUnique(xList, xi); + } } - else if(d.yLabel === undefined) text = d.xLabel; - else text = '(' + d.xLabel + ', ' + d.yLabel + ')'; + } - if(d.text && !Array.isArray(d.text)) { - text += (text ? '
' : '') + d.text; + // finally, if we've gotten here we're supposed to show cartesian... + // so if there are NO subplots at all, make one from the first + // x & y axes in the input layout + if(!spAll.length) { + xi = ''; + yi = ''; + for(var ki in layoutIn) { + if(_$constants_652.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if(axLetter === 'x') { + if(!xi || (+ki.substr(5) < +xi.substr(5))) { + xi = ki; + } + } + else if(!yi || (+ki.substr(5) < +yi.substr(5))) { + yi = ki; + } + } } + xi = xi ? _$axis_ids_650.name2id(xi) : 'x'; + yi = yi ? _$axis_ids_650.name2id(yi) : 'y'; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; - // if 'text' is empty at this point, - // put 'name' in main label and don't show secondary label - if(text === '') { - // if 'name' is also empty, remove entire label - if(name === '') g.remove(); - text = name; +_$cartesian_658.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; + + // If traces is not provided, then it's a complete replot and missing + // traces are removed + if(!Array.isArray(traces)) { + traces = []; + + for(i = 0; i < calcdata.length; i++) { + traces.push(i); } + } - // main label - var tx = g.select('text.nums') - .call(_$drawing_436.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - d.fontColor || contrastColor) - .text(text) - .attr('data-notex', 1) - .call(_$svg_text_utils_562.positionText, 0, 0) - .call(_$svg_text_utils_562.convertToTspans, gd); + for(i = 0; i < subplots.length; i++) { + var subplot = subplots[i], + subplotInfo = fullLayout._plots[subplot]; - var tx2 = g.select('text.name'), - tx2width = 0; + // Get all calcdata for this subplot: + var cdSubplot = []; + var pcd; - // secondary label for non-empty 'name' - if(name && name !== text) { - tx2.call(_$drawing_436.font, - d.fontFamily || fontFamily, - d.fontSize || fontSize, - traceColor) - .text(name) - .attr('data-notex', 1) - .call(_$svg_text_utils_562.positionText, 0, 0) - .call(_$svg_text_utils_562.convertToTspans, gd); - tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD; - } - else { - tx2.remove(); - g.select('rect').remove(); - } + for(var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j], + trace = cd[0].trace; - g.select('path') - .style({ - fill: traceColor, - stroke: contrastColor - }); - var tbb = tx.node().getBoundingClientRect(), - htx = d.xa._offset + (d.x0 + d.x1) / 2, - hty = d.ya._offset + (d.y0 + d.y1) / 2, - dx = Math.abs(d.x1 - d.x0), - dy = Math.abs(d.y1 - d.y0), - txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width, - anchorStartOK, - anchorEndOK; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { + // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet + // axis has actually changed: + // + // If this trace is specifically requested, add it to the list: + if(traces.indexOf(trace.index) !== -1 || trace.carpet) { + // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate + // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill + // is outdated. So this retroactively adds the previous trace if the + // traces are interdependent. + if( + pcd && + pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && + ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 && + cdSubplot.indexOf(pcd) === -1 + ) { + cdSubplot.push(pcd); + } - d.ty0 = outerTop - tbb.top; - d.bx = tbb.width + 2 * HOVERTEXTPAD; - d.by = tbb.height + 2 * HOVERTEXTPAD; - d.anchor = 'start'; - d.txwidth = tbb.width; - d.tx2width = tx2width; - d.offset = 0; + cdSubplot.push(cd); + } - if(rotateLabels) { - d.pos = htx; - anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; - anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - hty += dy / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; - } - else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = 'end'; - } else if(anchorStartOK) { - htx += dx / 2; - d.anchor = 'start'; - } else d.anchor = 'middle'; + // Track the previous trace on this subplot for the retroactive-add step + // above: + pcd = cd; + } } - tx.attr('text-anchor', d.anchor); - if(tx2width) tx2.attr('text-anchor', d.anchor); - g.attr('transform', 'translate(' + htx + ',' + hty + ')' + - (rotateLabels ? 'rotate(' + YANGLE + ')' : '')); - }); + plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + } +}; - return hoverLabels; -} +function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout, + modules = fullLayout._modules; -// Make groups of touching points, and within each group -// move each point so that no labels overlap, but the average -// label position is the same as it was before moving. Indicentally, -// this is equivalent to saying all the labels are on equal linear -// springs about their initial position. Initially, each point is -// its own group, but as we find overlaps we will clump the points. -// -// Also, there are hard constraints at the edges of the graphs, -// that push all groups to the middle so they are visible. I don't -// know what happens if the group spans all the way from one edge to -// the other, though it hardly matters - there's just too much -// information then. -function hoverAvoidOverlaps(hoverData, ax, fullLayout) { - var nummoves = 0, + // remove old traces, then redraw everything + // + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(plotinfo.plot) { + plotinfo.plot.selectAll('g:not(.scatterlayer):not(.ohlclayer)').selectAll('g.trace').remove(); + } - // make groups of touching points - pointgroups = hoverData - .map(function(d, i) { - var axis = d[ax]; - return [{ - i: i, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2, - pmin: 0, - pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height) - }]; - }) - .sort(function(a, b) { return a[0].posref - b[0].posref; }), - donepositioning, - topOverlap, - bottomOverlap, - i, j, - pti, - sumdp; + // plot all traces for each module at once + for(var j = 0; j < modules.length; j++) { + var _module = modules[j]; - function constrainGroup(grp) { - var minPt = grp[0], - maxPt = grp[grp.length - 1]; + // skip over non-cartesian trace modules + if(!_module.plot || _module.basePlotModule.name !== 'cartesian') continue; - // overlap with the top - positive vals are overlaps - topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; + // plot all traces of this type on this subplot at once + var cdModuleAndOthers = getModuleCalcData(cdSubplot, _module); + var cdModule = cdModuleAndOthers[0]; + // don't need to search the found traces again - in fact we need to NOT + // so that if two modules share the same plotter we don't double-plot + cdSubplot = cdModuleAndOthers[1]; - // overlap with the bottom - positive vals are overlaps - bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; + _module.plot(gd, plotinfo, cdModule, transitionOpts, makeOnCompleteCallback); + } +} - // check for min overlap first, so that we always - // see the largest labels - // allow for .01px overlap, so we don't get an - // infinite loop from rounding errors - if(topOverlap > 0.01) { - for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap; - donepositioning = false; - } - if(bottomOverlap < 0.01) return; - if(topOverlap < -0.01) { - // make sure we're not pushing back and forth - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; - donepositioning = false; - } - if(!donepositioning) return; +_$cartesian_658.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + var oldPlots = oldFullLayout._plots || {}; - // no room to fix positioning, delete off-screen points + var hadScatter, hasScatter; + var hadOHLC, hasOHLC; + var hadGl, hasGl; + var i, k, subplotInfo, moduleName; - // first see how many points we need to delete - var deleteCount = 0; - for(i = 0; i < grp.length; i++) { - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + // when going from a large splom graph to something else, + // we need to clear so that the new cartesian subplot + // can have the correct layer ordering + if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plotgroup) subplotInfo.plotgroup.remove(); } + } - // start by deleting points whose data is off screen - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; + for(i = 0; i < oldModules.length; i++) { + moduleName = oldModules[i].name; + if(moduleName === 'scatter') hadScatter = true; + else if(moduleName === 'scattergl') hadGl = true; + else if(moduleName === 'ohlc') hadOHLC = true; + } - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; + for(i = 0; i < newModules.length; i++) { + moduleName = newModules[i].name; + if(moduleName === 'scatter') hasScatter = true; + else if(moduleName === 'scattergl') hasGl = true; + else if(moduleName === 'ohlc') hasOHLC = true; + } + + var layersToEmpty = []; + if(hadScatter && !hasScatter) layersToEmpty.push('g.scatterlayer'); + if(hadOHLC && !hasOHLC) layersToEmpty.push('g.ohlclayer'); + + if(layersToEmpty.length) { + for(var layeri = 0; layeri < layersToEmpty.length; layeri++) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; + if(subplotInfo.plot) { + subplotInfo.plot.select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); + } } + + oldFullLayout._infolayer.selectAll('g.rangeslider-container') + .select(layersToEmpty[layeri]) + .selectAll('g.trace') + .remove(); } - for(i = 0; i < grp.length; i++) { - if(deleteCount <= 0) break; - pti = grp[i]; + } - // pos has already been constrained to [pmin,pmax] - // so look for points close to that to delete - if(pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; + if(hadGl && !hasGl) { + for(k in oldPlots) { + subplotInfo = oldPlots[k]; - // shift the whole group minus into this new space - bottomOverlap = pti.size * 2; - for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap; + if(subplotInfo._scene) { + subplotInfo._scene.destroy(); } } - // then delete points that go off the bottom - for(i = grp.length - 1; i >= 0; i--) { - if(deleteCount <= 0) break; - pti = grp[i]; - if(pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; + } + + var oldSubplotList = oldFullLayout._subplots || {}; + var newSubplotList = newFullLayout._subplots || {xaxis: [], yaxis: []}; + + // delete any titles we don't need anymore + // check if axis list has changed, and if so clear old titles + if(oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = oldSubplotList.xaxis.concat(oldSubplotList.yaxis); + var newAxIDs = newSubplotList.xaxis.concat(newSubplotList.yaxis); + + for(i = 0; i < oldAxIDs.length; i++) { + if(newAxIDs.indexOf(oldAxIDs[i]) === -1) { + oldFullLayout._infolayer.selectAll('.g-' + oldAxIDs[i] + 'title').remove(); } } } - // loop through groups, combining them if they overlap, - // until nothing moves - while(!donepositioning && nummoves <= hoverData.length) { - // to avoid infinite loops, don't move more times - // than there are traces - nummoves++; + // if we've gotten rid of all cartesian traces, remove all the subplot svg items + var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian')); + var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian')); - // assume nothing will move in this iteration, - // reverse this if it does - donepositioning = true; - i = 0; - while(i < pointgroups.length - 1) { - // the higher (g0) and lower (g1) point group - var g0 = pointgroups[i], - g1 = pointgroups[i + 1], + if(hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout); + oldFullLayout._defs.selectAll('.axesclip').remove(); + delete oldFullLayout._axisConstraintGroups; + } + // otherwise look for subplots we need to remove + else if(oldSubplotList.cartesian) { + for(i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if(newSubplotList.cartesian.indexOf(oldSubplotId) === -1) { + var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y'; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } + } +}; - // the lowest point in the higher group (p0) - // the highest point in the lower group (p1) - p0 = g0[g0.length - 1], - p1 = g1[0]; - topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; +_$cartesian_658.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var subplotData = makeSubplotData(gd); - // Only group points that lie on the same axes - if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) { - // push the new point(s) added to this group out of the way - for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; + var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot') + .data(subplotData, _$lib_601.identity); - // add them to the group - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); + subplotLayers.enter().append('g') + .attr('class', function(name) { return 'subplot ' + name; }); - // adjust for minimum average movement - sumdp = 0; - for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; - } - else i++; - } + subplotLayers.order(); - // check if we're going off the plot on either side and fix - pointgroups.forEach(constrainGroup); - } + subplotLayers.exit() + .call(purgeSubplotLayers, fullLayout); - // now put these offsets into hoverData - for(i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for(j = grp.length - 1; j >= 0; j--) { - var pt = grp[j], - hoverPt = hoverData[pt.i]; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; - } - } -} + subplotLayers.each(function(name) { + var plotinfo = fullLayout._plots[name]; -function alignHoverText(hoverLabels, rotateLabels) { - // finally set the text positioning relative to the data and draw the - // box around it - hoverLabels.each(function(d) { - var g = _$d3_127.select(this); - if(d.del) { - g.remove(); - return; - } - var horzSign = d.anchor === 'end' ? -1 : 1, - tx = g.select('text.nums'), - alignShift = {start: 1, end: -1, middle: 0}[d.anchor], - txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD), - tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD), - offsetX = 0, - offsetY = d.offset; - if(d.anchor === 'middle') { - txx -= d.tx2width / 2; - tx2x += d.txwidth / 2 + HOVERTEXTPAD; - } - if(rotateLabels) { - offsetY *= -YSHIFTY; - offsetX = d.offset * YSHIFTX; - } + // keep ref to plot group + plotinfo.plotgroup = _$d3_130.select(this); - g.select('path').attr('d', d.anchor === 'middle' ? - // middle aligned: rect centered on data - ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) + - 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') : - // left or right aligned: side rect with arrow to data - ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) + - 'v' + (d.by / 2 - HOVERARROWSIZE) + - 'h' + (horzSign * d.bx) + - 'v-' + d.by + - 'H' + (horzSign * HOVERARROWSIZE + offsetX) + - 'V' + (offsetY - HOVERARROWSIZE) + - 'Z')); + // initialize list of overlay subplots + plotinfo.overlays = []; - tx.call(_$svg_text_utils_562.positionText, - txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); + makeSubplotLayer(gd, plotinfo); - if(d.tx2width) { - g.select('text.name') - .call(_$svg_text_utils_562.positionText, - tx2x + alignShift * HOVERTEXTPAD + offsetX, - offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD); - g.select('rect') - .call(_$drawing_436.setRect, - tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX, - offsetY - d.by / 2 - 1, - d.tx2width, d.by + 2); + // fill in list of overlay subplots + if(plotinfo.mainplot) { + var mainplot = fullLayout._plots[plotinfo.mainplot]; + mainplot.overlays.push(plotinfo); } + + // make separate drag layers for each subplot, + // but append them to paper rather than the plot groups, + // so they end up on top of the rest + plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name); }); -} +}; -function cleanPoint(d, hovermode) { - var index = d.index; - var trace = d.trace || {}; - var cd0 = d.cd[0]; - var cd = d.cd[index] || {}; +_$cartesian_658.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne(gd, plotinfo, cdSubplot); + _$plots_709.style(gd); +}; - var getVal = Array.isArray(index) ? - function(calcKey, traceKey) { - return _$lib_539.castOption(cd0, index, calcKey) || - _$lib_539.extractOption({}, trace, '', traceKey); - } : - function(calcKey, traceKey) { - return _$lib_539.extractOption(cd, trace, calcKey, traceKey); - }; +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var subplotData = []; + var overlays = []; - function fill(key, calcKey, traceKey) { - var val = getVal(calcKey, traceKey); - if(val) d[key] = val; + for(var k in fullLayout._plots) { + var plotinfo = fullLayout._plots[k]; + var xa2 = plotinfo.xaxis._mainAxis; + var ya2 = plotinfo.yaxis._mainAxis; + var mainplot = xa2._id + ya2._id; + + if(mainplot !== k && fullLayout._plots[mainplot]) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = fullLayout._plots[mainplot]; + overlays.push(k); + } else { + subplotData.push(k); + plotinfo.mainplot = undefined; + } } - fill('hoverinfo', 'hi', 'hoverinfo'); - fill('color', 'hbg', 'hoverlabel.bgcolor'); - fill('borderColor', 'hbc', 'hoverlabel.bordercolor'); - fill('fontFamily', 'htf', 'hoverlabel.font.family'); - fill('fontSize', 'hts', 'hoverlabel.font.size'); - fill('fontColor', 'htc', 'hoverlabel.font.color'); - fill('nameLength', 'hnl', 'hoverlabel.namelength'); + // main subplots before overlays + subplotData = subplotData.concat(overlays); - d.posref = hovermode === 'y' ? - (d.xa._offset + (d.x0 + d.x1) / 2) : - (d.ya._offset + (d.y0 + d.y1) / 2); + return subplotData; +} - // then constrain all the positions to be on the plot - d.x0 = _$lib_539.constrain(d.x0, 0, d.xa._length); - d.x1 = _$lib_539.constrain(d.x1, 0, d.xa._length); - d.y0 = _$lib_539.constrain(d.y0, 0, d.ya._length); - d.y1 = _$lib_539.constrain(d.y1, 0, d.ya._length); +function makeSubplotLayer(gd, plotinfo) { + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var xLayer = _$constants_652.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = _$constants_652.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms; - // and convert the x and y label values into formatted text - if(d.xLabelVal !== undefined) { - d.xLabel = ('xLabel' in d) ? d.xLabel : _$axes_584.hoverLabelText(d.xa, d.xLabelVal); - d.xVal = d.xa.c2d(d.xLabelVal); - } - if(d.yLabelVal !== undefined) { - d.yLabel = ('yLabel' in d) ? d.yLabel : _$axes_584.hoverLabelText(d.ya, d.yLabelVal); - d.yVal = d.ya.c2d(d.yLabelVal); - } + if(!plotinfo.mainplot) { + if(hasOnlyLargeSploms) { + // TODO could do even better + // - we don't need plot (but we would have to mock it in lsInner + // and other places + // - we don't (x|y)lines and (x|y)axislayer for most subplots + // usually just the bottom x and left y axes. + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + } + else { + var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot'); + plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer'); + plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer'); - // Traces like heatmaps generate the zLabel in their hoverPoints function - if(d.zLabelVal !== undefined && d.zLabel === undefined) { - d.zLabel = String(d.zLabelVal); - } + plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer'); + plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer'); - // for box means and error bars, add the range to the label - if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) { - var xeText = _$axes_584.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text; - if(d.xerrneg !== undefined) { - d.xLabel += ' +' + xeText + ' / -' + - _$axes_584.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text; - } - else d.xLabel += ' ± ' + xeText; + ensureSingle(plotgroup, 'path', 'xlines-below'); + ensureSingle(plotgroup, 'path', 'ylines-below'); + plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below'); - // small distance penalty for error bars, so that if there are - // traces with errors and some without, the error bar label will - // hoist up to the point - if(hovermode === 'x') d.distance += 1; - } - if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) { - var yeText = _$axes_584.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text; - if(d.yerrneg !== undefined) { - d.yLabel += ' +' + yeText + ' / -' + - _$axes_584.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text; - } - else d.yLabel += ' ± ' + yeText; + ensureSingle(plotgroup, 'g', 'xaxislayer-below'); + ensureSingle(plotgroup, 'g', 'yaxislayer-below'); + plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below'); - if(hovermode === 'y') d.distance += 1; - } + plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot'); + plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot'); - var infomode = d.hoverinfo || d.trace.hoverinfo; + plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above'); + plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above'); + plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above'); - if(infomode !== 'all') { - infomode = Array.isArray(infomode) ? infomode : infomode.split('+'); - if(infomode.indexOf('x') === -1) d.xLabel = undefined; - if(infomode.indexOf('y') === -1) d.yLabel = undefined; - if(infomode.indexOf('z') === -1) d.zLabel = undefined; - if(infomode.indexOf('text') === -1) d.text = undefined; - if(infomode.indexOf('name') === -1) d.name = undefined; + ensureSingle(plotgroup, 'g', 'xaxislayer-above'); + ensureSingle(plotgroup, 'g', 'yaxislayer-above'); + plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above'); + + // set refs to correct layers as determined by 'axis.layer' + plotinfo.xlines = plotgroup.select('.xlines-' + xLayer); + plotinfo.ylines = plotgroup.select('.ylines-' + yLayer); + plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer); + plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer); + } } + else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + '-x'; + var yId = id + '-y'; - return d; -} + // now make the components of overlaid subplots + // overlays don't have backgrounds, and append all + // their other components to the corresponding + // extra groups of their main plots. -function createSpikelines(closestPoints, opts) { - var container = opts.container; - var fullLayout = opts.fullLayout; - var evt = opts.event; - var xa, - ya; + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - var showY = !!closestPoints.hLinePoint; - var showX = !!closestPoints.vLinePoint; + ensureSingle(mainplotinfo.overlinesBelow, 'path', xId); + ensureSingle(mainplotinfo.overlinesBelow, 'path', yId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', xId); + ensureSingle(mainplotinfo.overaxesBelow, 'g', yId); - // Remove old spikeline items - container.selectAll('.spikeline').remove(); + plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id); - if(!(showX || showY)) return; + ensureSingle(mainplotinfo.overlinesAbove, 'path', xId); + ensureSingle(mainplotinfo.overlinesAbove, 'path', yId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', xId); + ensureSingle(mainplotinfo.overaxesAbove, 'g', yId); - var contrastColor = _$color_411.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + // set refs to correct layers as determined by 'abovetraces' + plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId); + plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId); + plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId); + plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId); + } - // Horizontal line (to y-axis) - if(showY) { - var hLinePoint = closestPoints.hLinePoint, - hLinePointX, - hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; + // common attributes for all subplots, overlays or not - if(ySnap === 'cursor') { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; + if(!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll('g').sort(_$axis_ids_650.idSort); + + for(var i = 0; i < _$constants_652.traceLayerClasses.length; i++) { + ensureSingle(plotinfo.plot, 'g', _$constants_652.traceLayerClasses[i]); } - var dfltHLineColor = _$tinycolor_352.readability(hLinePoint.color, contrastColor) < 1.5 ? - _$color_411.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode, - yThickness = ya.spikethickness, - yColor = ya.spikecolor || dfltHLineColor, - yBB = ya._boundingBox, - xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left, - xBase, - xEndSpike; + } - if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) { - if(yMode.indexOf('toaxis') !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; - } - if(yMode.indexOf('across') !== -1) { - xBase = ya._counterSpan[0]; - xEndSpike = ya._counterSpan[1]; - } + plotinfo.xlines + .style('fill', 'none') + .classed('crisp', true); - // Foreground horizontal line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness, - 'stroke': yColor, - 'stroke-dasharray': _$drawing_436.dashStyle(ya.spikedash, yThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + plotinfo.ylines + .style('fill', 'none') + .classed('crisp', true); +} - // Background horizontal Line (to y-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': xBase, - 'x2': xEndSpike, - 'y1': hLinePointY, - 'y2': hLinePointY, - 'stroke-width': yThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } - // Y axis marker - if(yMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness), - 'cy': hLinePointY, - 'r': yThickness, - 'fill': yColor - }) - .classed('spikeline', true); - } - } +function purgeSubplotLayers(layers, fullLayout) { + if(!layers) return; - if(showX) { - var vLinePoint = closestPoints.vLinePoint, - vLinePointX, - vLinePointY; + var overlayIdsToRemove = {}; - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; + layers.each(function(subplotId) { + var plotgroup = _$d3_130.select(this); - if(xSnap === 'cursor') { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; - } - var dfltVLineColor = _$tinycolor_352.readability(vLinePoint.color, contrastColor) < 1.5 ? - _$color_411.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode, - xThickness = xa.spikethickness, - xColor = xa.spikecolor || dfltVLineColor, - xBB = xa._boundingBox, - yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top, - yBase, - yEndSpike; + plotgroup.remove(); + removeSubplotExtras(subplotId, fullLayout); - if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) { - if(xMode.indexOf('toaxis') !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if(xMode.indexOf('across') !== -1) { - yBase = xa._counterSpan[0]; - yEndSpike = xa._counterSpan[1]; - } + overlayIdsToRemove[subplotId] = true; - // Foreground vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness, - 'stroke': xColor, - 'stroke-dasharray': _$drawing_436.dashStyle(xa.spikedash, xThickness) - }) - .classed('spikeline', true) - .classed('crisp', true); + // do not remove individual axis s here + // as other subplots may need them + }); - // Background vertical line (to x-axis) - container.insert('line', ':first-child') - .attr({ - 'x1': vLinePointX, - 'x2': vLinePointX, - 'y1': yBase, - 'y2': yEndSpike, - 'stroke-width': xThickness + 2, - 'stroke': contrastColor - }) - .classed('spikeline', true) - .classed('crisp', true); - } + // must remove overlaid subplot trace layers 'manually' - // X axis marker - if(xMode.indexOf('marker') !== -1) { - container.insert('circle', ':first-child') - .attr({ - 'cx': vLinePointX, - 'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness), - 'r': xThickness, - 'fill': xColor - }) - .classed('spikeline', true); - } - } -} + var subplots = fullLayout._plots; + var subplotIds = Object.keys(subplots); -function hoverChanged(gd, evt, oldhoverdata) { - // don't emit any events if nothing changed - if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + for(var i = 0; i < subplotIds.length; i++) { + var subplotInfo = subplots[subplotIds[i]]; + var overlays = subplotInfo.overlays || []; - for(var i = oldhoverdata.length - 1; i >= 0; i--) { - var oldPt = oldhoverdata[i], - newPt = gd._hoverdata[i]; - if(oldPt.curveNumber !== newPt.curveNumber || - String(oldPt.pointNumber) !== String(newPt.pointNumber)) { - return true; + for(var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; + + if(overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll('.trace').remove(); + } } } - return false; } -function spikesChanged(gd, oldspikepoints) { - // don't relayout the plot because of new spikelines if spikelines points didn't change - if(!oldspikepoints) return true; - if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint || - oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint - ) return true; - return false; +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll('g.' + subplotId).remove(); + fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); } +_$cartesian_658.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = _$d3_130.select(gd).selectAll('.svg-container'); + var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) + .selectAll('.gl-canvas-context, .gl-canvas-focus'); + + function canvasToImage() { + var canvas = this; + var imageData = canvas.toDataURL('image/png'); + var image = imageRoot.append('svg:image'); + + image.attr({ + xmlns: _$xmlns_namespaces_580.svg, + 'xlink:href': imageData, + preserveAspectRatio: 'none', + x: 0, + y: 0, + width: canvas.width, + height: canvas.height + }); + } + + canvases.each(canvasToImage); +}; + +_$cartesian_658.updateFx = _$graph_interact_656.updateFx; + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -34000,32 +37993,29 @@ function spikesChanged(gd, oldspikepoints) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -var hover = _$hover_451.hover; +var mergeArray = _$lib_601.mergeArray; -var _$click_447 = function click(gd, evt, subplot) { - var annotationsDone = _$registry_668.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); - } +// arrayOk attributes, merge them into calcdata array +var _$arraysToCalcdata_740 = function arraysToCalcdata(cd, trace) { + for(var i = 0; i < cd.length; i++) cd[i].i = i; - function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); } + mergeArray(trace.text, cd, 'tx'); + mergeArray(trace.hovertext, cd, 'htx'); - if(gd._hoverdata && evt && evt.target) { - if(annotationsDone && annotationsDone.then) { - annotationsDone.then(emitClick); - } - else emitClick(); + var marker = trace.marker; + if(marker) { + mergeArray(marker.opacity, cd, 'mo'); + mergeArray(marker.color, cd, 'mc'); - // why do we get a double event without this??? - if(evt.stopImmediatePropagation) evt.stopImmediatePropagation(); + var markerLine = marker.line; + if(markerLine) { + mergeArray(markerLine.color, cd, 'mlc'); + mergeArray(markerLine.width, cd, 'mlw'); + } } }; @@ -34039,113 +38029,162 @@ var _$click_447 = function click(gd, evt, subplot) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; -var _$handleHoverLabelDefaults_452 = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) { - opts = opts || {}; +var __extendFlat_741 = _$extend_590.extendFlat; - coerce('hoverlabel.bgcolor', opts.bgcolor); - coerce('hoverlabel.bordercolor', opts.bordercolor); - coerce('hoverlabel.namelength', opts.namelength); - _$lib_539.coerceFont(coerce, 'hoverlabel.font', opts.font); -}; +var textFontAttrs = _$font_attributes_673({ + editType: 'calc', + arrayOk: true, + +}); -/** -* Copyright 2012-2018, Plotly, Inc. -* All 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 __scatterMarkerAttrs_741 = _$attributes_927.marker; +var scatterMarkerLineAttrs = __scatterMarkerAttrs_741.line; -'use strict'; +var markerLineWidth = __extendFlat_741({}, + scatterMarkerLineAttrs.width, { dflt: 0 }); -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_445 = require('./attributes'); */; -/* removed: var _$handleHoverLabelDefaults_452 = require('./hoverlabel_defaults'); */; +var markerLine = __extendFlat_741({ + width: markerLineWidth, + editType: 'calc' +}, _$makeColorScaleAttributes_481('marker.line')); -var _$supplyDefaults_449 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_445, attr, dflt); +var marker = __extendFlat_741({ + line: markerLine, + editType: 'calc' +}, _$makeColorScaleAttributes_481('marker'), { + showscale: __scatterMarkerAttrs_741.showscale, + colorbar: _$attributes_474, + opacity: { + valType: 'number', + arrayOk: true, + dflt: 1, + min: 0, + max: 1, + + editType: 'style', + } +}); - _$handleHoverLabelDefaults_452(traceIn, traceOut, coerce, layout.hoverlabel); -}; +var _$attributes_741 = { + x: _$attributes_927.x, + x0: _$attributes_927.x0, + dx: _$attributes_927.dx, + y: _$attributes_927.y, + y0: _$attributes_927.y0, + dy: _$attributes_927.dy, -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + text: _$attributes_927.text, + hovertext: _$attributes_927.hovertext, -'use strict'; + textposition: { + valType: 'enumerated', + + values: ['inside', 'outside', 'auto', 'none'], + dflt: 'none', + arrayOk: true, + editType: 'calc', + + }, -/* removed: var _$constants_448 = require('./constants'); */; + textfont: __extendFlat_741({}, textFontAttrs, { + + }), -var __fontAttrs_454 = _$font_attributes_611({ - editType: 'none', - -}); -__fontAttrs_454.family.dflt = _$constants_448.HOVERFONT; -__fontAttrs_454.size.dflt = _$constants_448.HOVERFONTSIZE; + insidetextfont: __extendFlat_741({}, textFontAttrs, { + + }), -var _$layout_attributes_454 = { - dragmode: { + outsidetextfont: __extendFlat_741({}, textFontAttrs, { + + }), + + constraintext: { valType: 'enumerated', + values: ['inside', 'outside', 'both', 'none'], - values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'], - dflt: 'zoom', - editType: 'modebar', + dflt: 'both', + editType: 'calc', }, - hovermode: { + + cliponaxis: __extendFlat_741({}, _$attributes_927.cliponaxis, { + + }), + + orientation: { valType: 'enumerated', - values: ['x', 'y', 'closest', false], - editType: 'modebar', + values: ['v', 'h'], + editType: 'calc+clearAxisTypes', }, - hoverdistance: { - valType: 'integer', - min: -1, - dflt: 20, + + base: { + valType: 'any', + dflt: null, + arrayOk: true, - editType: 'none', + editType: 'calc', }, - spikedistance: { - valType: 'integer', - min: -1, - dflt: 20, + + offset: { + valType: 'number', + dflt: null, + arrayOk: true, - editType: 'none', + editType: 'calc', }, - hoverlabel: { - bgcolor: { - valType: 'color', - - editType: 'none', - + + width: { + valType: 'number', + dflt: null, + min: 0, + arrayOk: true, + + editType: 'calc', + + }, + + marker: marker, + + selected: { + marker: { + opacity: _$attributes_927.selected.marker.opacity, + color: _$attributes_927.selected.marker.color, + editType: 'style' }, - bordercolor: { - valType: 'color', - - editType: 'none', - + textfont: _$attributes_927.selected.textfont, + editType: 'style' + }, + unselected: { + marker: { + opacity: _$attributes_927.unselected.marker.opacity, + color: _$attributes_927.unselected.marker.color, + editType: 'style' }, - font: __fontAttrs_454, - namelength: { - valType: 'integer', - min: -1, - dflt: 15, + textfont: _$attributes_927.unselected.textfont, + editType: 'style' + }, + + r: _$attributes_927.r, + t: _$attributes_927.t, + + _deprecated: { + bardir: { + valType: 'enumerated', - editType: 'none', + editType: 'calc', + values: ['v', 'h'], - }, - editType: 'none' + } } }; @@ -34159,60 +38198,116 @@ var _$layout_attributes_454 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_454 = require('./layout_attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$supplyLayoutDefaults_455 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_454, attr, dflt); +var _$calcSelection_929 = function calcSelection(cd, trace) { + if(_$lib_601.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_601.tagSelected(cd, trace); } +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - coerce('dragmode'); - var hovermodeDflt; - if(layoutOut._has('cartesian')) { - // flag for 'horizontal' plots: - // determines the state of the mode bar 'compare' hovermode button - layoutOut._isHoriz = isHoriz(fullData); - hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x'; - } - else hovermodeDflt = 'closest'; +'use strict'; - var hoverMode = coerce('hovermode', hovermodeDflt); - if(hoverMode) { - coerce('hoverdistance'); - coerce('spikedistance'); - } +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_742 = _$lib_601.isArrayOrTypedArray; - // if only mapbox or geo subplots is present on graph, - // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented, - // so that the correct modebar button is active - var hasMapbox = layoutOut._has('mapbox'); - var hasGeo = layoutOut._has('geo'); - var len = layoutOut._basePlotModules.length; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_740 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; - if(layoutOut.dragmode === 'zoom' && ( - ((hasMapbox || hasGeo) && len === 1) || - (hasMapbox && hasGeo && len === 2) - )) { - layoutOut.dragmode = 'pan'; +var _$calc_742 = function calc(gd, trace) { + // depending on bar direction, set position and size axes + // and data ranges + // note: this logic for choosing orientation is + // duplicated in graph_obj->setstyles + + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'), + orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'), + sa, pos, size, i, scalendar; + + if(orientation === 'h') { + sa = xa; + size = xa.makeCalcdata(trace, 'x'); + pos = ya.makeCalcdata(trace, 'y'); + + // 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. + scalendar = trace.xcalendar; + } + else { + sa = ya; + size = ya.makeCalcdata(trace, 'y'); + pos = xa.makeCalcdata(trace, 'x'); + scalendar = trace.ycalendar; } -}; -function isHoriz(fullData) { - var out = true; + // create the "calculated data" to plot + var serieslen = Math.min(pos.length, size.length); + var cd = new Array(serieslen); - for(var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; + // set position and size + for(i = 0; i < serieslen; i++) { + cd[i] = { p: pos[i], s: size[i] }; - if(trace.orientation !== 'h') { - out = false; - break; + if(trace.ids) { + cd[i].id = String(trace.ids[i]); } } - return out; -} + // set base + var base = trace.base, + b; + + if(__isArrayOrTypedArray_742(base)) { + for(i = 0; i < Math.min(base.length, cd.length); i++) { + b = sa.d2c(base[i], 0, scalendar); + if(_$fastIsnumeric_196(b)) { + cd[i].b = +b; + cd[i].hasB = 1; + } + else cd[i].b = 0; + } + for(; i < cd.length; i++) { + cd[i].b = 0; + } + } + else { + b = sa.d2c(base, 0, scalendar); + var hasBase = _$fastIsnumeric_196(b); + b = hasBase ? b : 0; + for(i = 0; i < cd.length; i++) { + cd[i].b = b; + if(hasBase) cd[i].hasB = 1; + } + } + + // auto-z and autocolorscale if applicable + if(_$hasColorscale_487(trace, 'marker')) { + _$calc_480(trace, trace.marker.color, 'marker', 'c'); + } + if(_$hasColorscale_487(trace, 'marker.line')) { + _$calc_480(trace, trace.marker.line.color, 'marker.line', 'c'); + } + + _$arraysToCalcdata_740(cd, trace); + _$calcSelection_929(cd, trace); + + return cd; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -34222,18 +38317,34 @@ function isHoriz(fullData) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleHoverLabelDefaults_452 = require('./hoverlabel_defaults'); */; -/* removed: var _$layout_attributes_454 = require('./layout_attributes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; -var _$supplyLayoutGlobalDefaults_456 = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { - function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_454, attr, dflt); +var _$handleStyleDefaults_753 = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) { + coerce('marker.color', defaultColor); + + if(_$hasColorscale_487(traceIn, 'marker')) { + _$colorScaleDefaults_483( + traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'} + ); + } + + coerce('marker.line.color', _$color_473.defaultLine); + + if(_$hasColorscale_487(traceIn, 'marker.line')) { + _$colorScaleDefaults_483( + traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'} + ); } - _$handleHoverLabelDefaults_452(layoutIn, layoutOut, coerce); + coerce('marker.line.width'); + coerce('marker.opacity'); + coerce('selected.marker.color'); + coerce('unselected.marker.color'); }; /** @@ -34244,74 +38355,108 @@ var _$supplyLayoutGlobalDefaults_456 = function supplyLayoutGlobalDefaults(layou * LICENSE file in the root directory of this source tree. */ + 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$helpers_450 = require('./helpers'); */; -/* removed: var _$layout_attributes_454 = require('./layout_attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$fx_453 = { - moduleType: 'component', - name: 'fx', - constants: _$constants_448, - schema: { - layout: _$layout_attributes_454 - }, +var _$handleXYDefaults_951 = function handleXYDefaults(traceIn, traceOut, layout, coerce) { + var len, + x = coerce('x'), + y = coerce('y'); - attributes: _$attributes_445, - layoutAttributes: _$layout_attributes_454, + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); + handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); - supplyLayoutGlobalDefaults: _$supplyLayoutGlobalDefaults_456, - supplyDefaults: _$supplyDefaults_449, - supplyLayoutDefaults: _$supplyLayoutDefaults_455, + if(x) { + if(y) { + len = Math.min(x.length, y.length); + } + else { + len = x.length; + coerce('y0'); + coerce('dy'); + } + } + else { + if(!y) return 0; - calc: _$calc_446, + len = traceOut.y.length; + coerce('x0'); + coerce('dx'); + } - getDistanceFunction: _$helpers_450.getDistanceFunction, - getClosest: _$helpers_450.getClosest, - inbox: _$helpers_450.inbox, - quadrature: _$helpers_450.quadrature, - appendArrayPointValue: _$helpers_450.appendArrayPointValue, + traceOut._length = len; - castHoverOption: castHoverOption, - castHoverinfo: castHoverinfo, + return len; +}; - hover: _$hover_451.hover, - unhover: _$dragelement_433.unhover, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - loneHover: _$hover_451.loneHover, - loneUnhover: loneUnhover, - click: _$click_447 -}; +'use strict'; -function loneUnhover(containerOrSelection) { - // duck type whether the arg is a d3 selection because ie9 doesn't - // handle instanceof like modern browsers do. - var selection = _$lib_539.isD3Selection(containerOrSelection) ? - containerOrSelection : - _$d3_127.select(containerOrSelection); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$registry_731 = require('../../registry'); */; - selection.selectAll('g.hovertext').remove(); - selection.selectAll('.spikeline').remove(); -} +/* removed: var _$handleXYDefaults_951 = require('../scatter/xy_defaults'); */; +/* removed: var _$handleStyleDefaults_753 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_741 = require('./attributes'); */; -// helpers for traces that use Fx.loneHover +var _$supplyDefaults_743 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_741, attr, dflt); + } -function castHoverOption(trace, ptNumber, attr) { - return _$lib_539.castOption(trace, ptNumber, 'hoverlabel.' + attr); -} + var coerceFont = _$lib_601.coerceFont; -function castHoverinfo(trace, fullLayout, ptNumber) { - function _coerce(val) { - return _$lib_539.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout); + var len = _$handleXYDefaults_951(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; } - return _$lib_539.castOption(trace, ptNumber, 'hoverinfo', _coerce); -} + coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v'); + coerce('base'); + coerce('offset'); + coerce('width'); + + coerce('text'); + coerce('hovertext'); + + var textPosition = coerce('textposition'); + + var hasBoth = Array.isArray(textPosition) || textPosition === 'auto', + hasInside = hasBoth || textPosition === 'inside', + hasOutside = hasBoth || textPosition === 'outside'; + + if(hasInside || hasOutside) { + var textFont = coerceFont(coerce, 'textfont', layout.font); + if(hasInside) coerceFont(coerce, 'insidetextfont', textFont); + if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont); + coerce('constraintext'); + coerce('selected.textfont.color'); + coerce('unselected.textfont.color'); + coerce('cliponaxis'); + } + + _$handleStyleDefaults_753(traceIn, traceOut, coerce, defaultColor, layout); + + // override defaultColor for error bars with defaultLine + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'x', inherit: 'y'}); + + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -34323,7 +38468,7 @@ function castHoverinfo(trace, fullLayout, ptNumber) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** Fill hover 'pointData' container with 'correct' hover text value * @@ -34338,15 +38483,15 @@ function castHoverinfo(trace, fullLayout, ptNumber) { * @param {object} trace * @param {object || array} contOut (mutated here) */ -var _$fillHoverText_870 = function fillHoverText(calcPt, trace, contOut) { +var _$fillHoverText_935 = function fillHoverText(calcPt, trace, contOut) { var fill = Array.isArray(contOut) ? function(v) { contOut.push(v); } : function(v) { contOut.text = v; }; - var htx = _$lib_539.extractOption(calcPt, trace, 'htx', 'hovertext'); + var htx = _$lib_601.extractOption(calcPt, trace, 'htx', 'hovertext'); if(isValid(htx)) return fill(htx); - var tx = _$lib_539.extractOption(calcPt, trace, 'tx', 'text'); + var tx = _$lib_601.extractOption(calcPt, trace, 'tx', 'text'); if(isValid(tx)) return fill(tx); }; @@ -34366,12 +38511,12 @@ function isValid(v) { 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; -var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_744 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var t = cd[0].t; @@ -34411,7 +38556,7 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { function _positionFn(_minPos, _maxPos) { // add a little to the pseudo-distance for wider bars, so that like scatter, // if you are over two overlapping bars, the narrower one wins. - return _$fx_453.inbox(_minPos - posVal, _maxPos - posVal, + return _$fx_515.inbox(_minPos - posVal, _maxPos - posVal, maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1); } @@ -34426,7 +38571,7 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { function sizeFn(di) { // add a gradient so hovering near the end of a // bar makes it a little closer match - return _$fx_453.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, + return _$fx_515.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal, maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1); } @@ -34453,8 +38598,8 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_453.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_453.getClosest(cd, distfn, pointData); + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_515.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index === false) return; @@ -34478,8 +38623,8 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { var mlc = di.mlcc || trace.marker.line.color; var mlw = di.mlw || trace.marker.line.width; - if(_$color_411.opacity(mc)) pointData.color = mc; - else if(_$color_411.opacity(mlc) && mlw) pointData.color = mlc; + if(_$color_473.opacity(mc)) pointData.color = mc; + else if(_$color_473.opacity(mlc) && mlw) pointData.color = mlc; var size = (trace.base) ? di.b + di.s : di.s; pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true); @@ -34496,8 +38641,8 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { // in case of bars shifted within groups pointData[posLetter + 'Spike'] = pa.c2p(di.p, true); - _$fillHoverText_870(di, trace, pointData); - _$registry_668.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_935(di, trace, pointData); + _$registry_731.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; }; @@ -34513,7 +38658,7 @@ var _$hoverPoints_681 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var _$layout_attributes_683 = { +var _$layout_attributes_746 = { barmode: { valType: 'enumerated', values: ['stack', 'group', 'overlay', 'relative'], @@ -34560,16 +38705,16 @@ var _$layout_attributes_683 = { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$layout_attributes_683 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_746 = require('./layout_attributes'); */; -var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { +var _$layout_defaults_747 = function(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_683, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_746, attr, dflt); } var hasBars = false, @@ -34579,7 +38724,7 @@ var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { for(var i = 0; i < fullData.length; i++) { var trace = fullData[i]; - if(_$registry_668.traceIs(trace, 'bar')) hasBars = true; + if(_$registry_731.traceIs(trace, 'bar')) hasBars = true; else continue; // if we have at least 2 grouped bar traces on the same subplot, @@ -34591,7 +38736,7 @@ var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { } if(trace.visible && trace.type === 'histogram') { - var pa = _$axes_584.getFromId({_fullLayout: layoutOut}, + var pa = _$axes_647.getFromId({_fullLayout: layoutOut}, trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']); if(pa.type !== 'category') shouldBeGapless = true; } @@ -34617,28 +38762,28 @@ var _$layout_defaults_684 = function(layoutIn, layoutOut, fullData) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var __dummy_685$0 = 0, - attributeText = _$attributes_678.text, - attributeTextPosition = _$attributes_678.textposition, - attributeTextFont = _$attributes_678.textfont, - attributeInsideTextFont = _$attributes_678.insidetextfont, - attributeOutsideTextFont = _$attributes_678.outsidetextfont; +var __dummy_748$0 = 0, + attributeText = _$attributes_741.text, + attributeTextPosition = _$attributes_741.textposition, + attributeTextFont = _$attributes_741.textfont, + attributeInsideTextFont = _$attributes_741.insidetextfont, + attributeOutsideTextFont = _$attributes_741.outsidetextfont; // padding in pixels around text var TEXTPAD = 3; -var _$plot_685 = function plot(gd, plotinfo, cdbar) { +var _$plot_748 = function plot(gd, plotinfo, cdbar) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, fullLayout = gd._fullLayout; @@ -34650,21 +38795,23 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { bartraces.enter().append('g') .attr('class', 'trace bars'); - bartraces.each(function(d) { - d[0].node3 = _$d3_127.select(this); - }); + if(!plotinfo.isRangePlot) { + bartraces.each(function(d) { + d[0].node3 = _$d3_130.select(this); + }); + } bartraces.append('g') .attr('class', 'points') .each(function(d) { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var t = d[0].t; var trace = d[0].trace; var poffset = t.poffset; var poffsetIsArray = Array.isArray(poffset); sel.selectAll('g.point') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('g').classed('point', true) .each(function(di, i) { // now display the bar @@ -34696,22 +38843,22 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { di.ct = [(x0 + x1) / 2, y1]; } - if(!_$fastIsnumeric_139(x0) || !_$fastIsnumeric_139(x1) || - !_$fastIsnumeric_139(y0) || !_$fastIsnumeric_139(y1) || + if(!_$fastIsnumeric_196(x0) || !_$fastIsnumeric_196(x1) || + !_$fastIsnumeric_196(y0) || !_$fastIsnumeric_196(y1) || x0 === x1 || y0 === y1) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); return; } var lw = (di.mlw + 1 || trace.marker.line.width + 1 || (di.trace ? di.trace.marker.line.width : 0) + 1) - 1, - offset = _$d3_127.round((lw / 2) % 1, 2); + offset = _$d3_130.round((lw / 2) % 1, 2); function roundWithLine(v) { // if there are explicit gaps, don't round, // it can make the gaps look crappy return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ? - _$d3_127.round(Math.round(v) - offset, 2) : v; + _$d3_130.round(Math.round(v) - offset, 2) : v; } function expandToVisible(v, vc) { @@ -34731,7 +38878,7 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { // pixelation. if the bars ARE fully opaque and have // no line, expand to a full pixel to make sure we // can see them - var op = _$color_411.opacity(di.mc || trace.marker.color), + var op = _$color_473.opacity(di.mc || trace.marker.color), fixpx = (op < 1 || lw > 0.01) ? roundWithLine : expandToVisible; x0 = fixpx(x0, x1); @@ -34741,30 +38888,30 @@ var _$plot_685 = function plot(gd, plotinfo, cdbar) { } // append bar path and text - var bar = _$d3_127.select(this); + var bar = _$d3_130.select(this); bar.append('path') .style('vector-effect', 'non-scaling-stroke') .attr('d', 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z') - .call(_$drawing_436.setClipUrl, plotinfo.layerClipId); + .call(_$drawing_498.setClipUrl, plotinfo.layerClipId); appendBarText(gd, bar, d, i, x0, x1, y0, y1); if(plotinfo.layerClipId) { - _$drawing_436.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_498.hideOutsideRangePoint(d[i], bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar); } }); }); // error bars are on the top - _$registry_668.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); + _$registry_731.getComponentMethod('errorbars', 'plot')(bartraces, plotinfo); // lastly, clip points groups of `cliponaxis !== false` traces // on `plotinfo._hasClipOnAxisFalse === true` subplots bartraces.each(function(d) { var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_436.setClipUrl(_$d3_127.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + _$drawing_498.setClipUrl(_$d3_130.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); }); }; @@ -34782,8 +38929,8 @@ function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { // tex and regular text together 'data-notex': 1 }) - .call(_$drawing_436.font, textFont) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$drawing_498.font, textFont) + .call(_$svg_text_utils_625.convertToTspans, gd); return textSelection; } @@ -34829,7 +38976,7 @@ function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { textPosition = 'inside'; textSelection = appendTextNode(bar, text, insideTextFont); - textBB = _$drawing_436.bBox(textSelection.node()), + textBB = _$drawing_498.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height; @@ -34859,7 +39006,7 @@ function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) { (textPosition === 'outside') ? outsideTextFont : insideTextFont); - textBB = _$drawing_436.bBox(textSelection.node()), + textBB = _$drawing_498.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height; @@ -35122,7 +39269,7 @@ function coerceEnumerated(attributeDefinition, value, defaultValue) { } function coerceNumber(attributeDefinition, value, defaultValue) { - if(_$fastIsnumeric_139(value)) { + if(_$fastIsnumeric_196(value)) { value = +value; var min = attributeDefinition.min, @@ -35139,7 +39286,7 @@ function coerceNumber(attributeDefinition, value, defaultValue) { } function coerceColor(attributeDefinition, value, defaultValue) { - if(_$tinycolor_352(value).isValid()) return value; + if(_$tinycolor_414(value).isValid()) return value; return (defaultValue !== undefined) ? defaultValue : @@ -35156,7 +39303,7 @@ function coerceColor(attributeDefinition, value, defaultValue) { 'use strict'; -var _$selectPoints_686 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_749 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -35198,10 +39345,10 @@ var _$selectPoints_686 = function selectPoints(searchInfo, polygon) { 'use strict'; -var _$Sieve_688 = Sieve; +var _$Sieve_751 = Sieve; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_688 = _$numerical_517.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_751 = _$numerical_578.BADNUM; /** * Helper class to sieve data from traces into bins @@ -35228,7 +39375,7 @@ function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { var trace = traces[i]; for(var j = 0; j < trace.length; j++) { var bar = trace[j]; - if(bar.p !== __BADNUM_688) positions.push(bar.p); + if(bar.p !== __BADNUM_751) positions.push(bar.p); } if(trace[0] && trace[0].width1) { width1 = Math.min(trace[0].width1, width1); @@ -35236,7 +39383,7 @@ function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) { } this.positions = positions; - var dv = _$lib_539.distinctVals(positions); + var dv = _$lib_601.distinctVals(positions); this.distinctPositions = dv.vals; if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; else this.minDiff = Math.min(dv.minDiff, width1); @@ -35307,13 +39454,13 @@ Sieve.prototype.getLabel = function getLabel(position, value) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_687 = _$lib_539.isArrayOrTypedArray; -var __BADNUM_687 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_750 = _$lib_601.isArrayOrTypedArray; +var __BADNUM_750 = _$numerical_578.BADNUM; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$Sieve_688 = require('./sieve.js'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$Sieve_751 = require('./sieve.js'); */; /* * Bar chart stacking/grouping positioning and autoscaling calculations @@ -35322,7 +39469,7 @@ var __BADNUM_687 = _$numerical_517.BADNUM; * now doing this one subplot at a time */ -var _$setPositions_687 = function setPositions(gd, plotinfo) { +var _$setPositions_750 = function setPositions(gd, plotinfo) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis; @@ -35335,7 +39482,7 @@ var _$setPositions_687 = function setPositions(gd, plotinfo) { var fullTrace = fullTraces[i]; if( fullTrace.visible === true && - _$registry_668.traceIs(fullTrace, 'bar') && + _$registry_731.traceIs(fullTrace, 'bar') && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id ) { @@ -35418,7 +39565,7 @@ function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) { for(var i = 0; i < calcTraces.length; i++) { var calcTrace = calcTraces[i]; - var sieve = new _$Sieve_688( + var sieve = new _$Sieve_751( [calcTrace], separateNegativeValues, dontMergeOverlappingData ); @@ -35446,7 +39593,7 @@ function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) { barnorm = fullLayout.barnorm, separateNegativeValues = false, dontMergeOverlappingData = !barnorm, - sieve = new _$Sieve_688( + sieve = new _$Sieve_751( calcTraces, separateNegativeValues, dontMergeOverlappingData ); @@ -35472,7 +39619,7 @@ function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { barnorm = gd._fullLayout.barnorm, separateNegativeValues = relative, dontMergeOverlappingData = !(barnorm || stack || relative), - sieve = new _$Sieve_688( + sieve = new _$Sieve_751( calcTraces, separateNegativeValues, dontMergeOverlappingData ); @@ -35489,7 +39636,7 @@ function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) { for(var j = 0; j < calcTrace.length; j++) { var bar = calcTrace[j]; - if(bar.s === __BADNUM_687) continue; + if(bar.s === __BADNUM_750) continue; var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s)); if(isOutmostBar) bar._outmost = true; @@ -35612,13 +39759,13 @@ function applyAttributes(sieve) { initialPoffset = t.poffset, newPoffset; - if(__isArrayOrTypedArray_687(offset)) { + if(__isArrayOrTypedArray_750(offset)) { // if offset is an array, then clone it into t.poffset. newPoffset = offset.slice(0, calcTrace.length); // guard against non-numeric items for(j = 0; j < newPoffset.length; j++) { - if(!_$fastIsnumeric_139(newPoffset[j])) { + if(!_$fastIsnumeric_196(newPoffset[j])) { newPoffset[j] = initialPoffset; } } @@ -35638,13 +39785,13 @@ function applyAttributes(sieve) { var width = fullTrace.width, initialBarwidth = t.barwidth; - if(__isArrayOrTypedArray_687(width)) { + if(__isArrayOrTypedArray_750(width)) { // if width is an array, then clone it into t.barwidth. var newBarwidth = width.slice(0, calcTrace.length); // guard against non-numeric items for(j = 0; j < newBarwidth.length; j++) { - if(!_$fastIsnumeric_139(newBarwidth[j])) newBarwidth[j] = initialBarwidth; + if(!_$fastIsnumeric_196(newBarwidth[j])) newBarwidth[j] = initialBarwidth; } // if the length of the array is too short, @@ -35714,7 +39861,7 @@ function updatePositionAxis(gd, pa, sieve, allowMinDtick) { minDiff = sieve.minDiff, vpad = minDiff / 2; - _$axes_584.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); + _$axes_647.minDtick(pa, minDiff, distinctPositions0, allowMinDtick); // If the user set the bar width or the offset, // then bars can be shifted away from their positions @@ -35753,14 +39900,14 @@ function updatePositionAxis(gd, pa, sieve, allowMinDtick) { } } - _$axes_584.expand(pa, [pMin, pMax], {padded: false}); + _$axes_647.expand(pa, [pMin, pMax], {padded: false}); } function expandRange(range, newValue) { - if(_$fastIsnumeric_139(range[0])) range[0] = Math.min(range[0], newValue); + if(_$fastIsnumeric_196(range[0])) range[0] = Math.min(range[0], newValue); else range[0] = newValue; - if(_$fastIsnumeric_139(range[1])) range[1] = Math.max(range[1], newValue); + if(_$fastIsnumeric_196(range[1])) range[1] = Math.max(range[1], newValue); else range[1] = newValue; } @@ -35782,12 +39929,12 @@ function setBaseAndTop(gd, sa, sieve) { bar[sLetter] = barTop; - if(_$fastIsnumeric_139(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_139(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$fastIsnumeric_196(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_196(sa.c2l(barBase))) expandRange(sRange, barBase); } } - _$axes_584.expand(sa, sRange, {tozero: true, padded: true}); + _$axes_647.expand(sa, sRange, {tozero: true, padded: true}); } @@ -35807,7 +39954,7 @@ function stackBars(gd, sa, sieve) { for(j = 0; j < trace.length; j++) { bar = trace[j]; - if(bar.s === __BADNUM_687) continue; + if(bar.s === __BADNUM_750) continue; // stack current bar and get previous sum var barBase = sieve.put(bar.p, bar.b + bar.s), @@ -35818,14 +39965,14 @@ function stackBars(gd, sa, sieve) { bar[sLetter] = barTop; if(!barnorm) { - if(_$fastIsnumeric_139(sa.c2l(barTop))) expandRange(sRange, barTop); - if(bar.hasB && _$fastIsnumeric_139(sa.c2l(barBase))) expandRange(sRange, barBase); + if(_$fastIsnumeric_196(sa.c2l(barTop))) expandRange(sRange, barTop); + if(bar.hasB && _$fastIsnumeric_196(sa.c2l(barBase))) expandRange(sRange, barBase); } } } // if barnorm is set, let normalizeBars update the axis range - if(!barnorm) _$axes_584.expand(sa, sRange, {tozero: true, padded: true}); + if(!barnorm) _$axes_647.expand(sa, sRange, {tozero: true, padded: true}); } @@ -35838,7 +39985,7 @@ function sieveBars(gd, sa, sieve) { for(var j = 0; j < trace.length; j++) { var bar = trace[j]; - if(bar.s !== __BADNUM_687) sieve.put(bar.p, bar.b + bar.s); + if(bar.s !== __BADNUM_750) sieve.put(bar.p, bar.b + bar.s); } } } @@ -35860,8 +40007,8 @@ function normalizeBars(gd, sa, sieve) { padded = false; function maybeExpand(newValue) { - if(_$fastIsnumeric_139(sa.c2l(newValue)) && - ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_139(sMin)) + if(_$fastIsnumeric_196(sa.c2l(newValue)) && + ((newValue < sMin - sTiny) || (newValue > sMax + sTiny) || !_$fastIsnumeric_196(sMin)) ) { padded = true; expandRange(sRange, newValue); @@ -35874,7 +40021,7 @@ function normalizeBars(gd, sa, sieve) { for(var j = 0; j < trace.length; j++) { var bar = trace[j]; - if(bar.s === __BADNUM_687) continue; + if(bar.s === __BADNUM_750) continue; var scale = Math.abs(sTop / sieve.get(bar.p, bar.s)); bar.b *= scale; @@ -35890,7 +40037,7 @@ function normalizeBars(gd, sa, sieve) { } // update range of size axis - _$axes_584.expand(sa, sRange, {tozero: true, padded: padded}); + _$axes_647.expand(sa, sRange, {tozero: true, padded: padded}); } @@ -35914,7 +40061,7 @@ function collectExtents(calcTraces, pa) { cd = calcTraces[i]; for(j = 0; j < cd.length; j++) { var p = cd[j].p; - if(_$fastIsnumeric_139(p)) { + if(_$fastIsnumeric_196(p)) { pMin = Math.min(pMin, p); pMax = Math.max(pMax, p); } @@ -35935,7 +40082,7 @@ function collectExtents(calcTraces, pa) { for(j = 0; j < cd.length; j++) { var di = cd[j]; var p0 = di[posLetter] - di.w / 2; - if(_$fastIsnumeric_139(p0)) { + if(_$fastIsnumeric_196(p0)) { var p1 = di[posLetter] + di.w / 2; var pVal = round(di.p); if(extents[pVal]) { @@ -35960,12 +40107,12 @@ function collectExtents(calcTraces, pa) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$style_689 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.bars'); +var _$style_752 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.trace.bars'); var barcount = s.size(); var fullLayout = gd._fullLayout; @@ -35980,21 +40127,21 @@ var _$style_689 = function style(gd, cd) { (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width)) { - _$d3_127.select(this).attr('shape-rendering', 'crispEdges'); + _$d3_130.select(this).attr('shape-rendering', 'crispEdges'); } }); s.selectAll('g.points').each(function(d) { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var pts = sel.selectAll('path'); var txs = sel.selectAll('text'); var trace = d[0].trace; - _$drawing_436.pointStyle(pts, trace, gd); - _$drawing_436.selectedPointStyle(pts, trace); + _$drawing_498.pointStyle(pts, trace, gd); + _$drawing_498.selectedPointStyle(pts, trace); txs.each(function(d) { - var tx = _$d3_127.select(this); + var tx = _$d3_130.select(this); var textFont; if(tx.classed('bartext-inside')) { @@ -36009,13 +40156,13 @@ var _$style_689 = function style(gd, cd) { return Array.isArray(cont) ? cont[d.i] : cont; } - _$drawing_436.font(tx, cast('family'), cast('size'), cast('color')); + _$drawing_498.font(tx, cast('family'), cast('size'), cast('color')); }); - _$drawing_436.selectedTextStyle(txs, trace); + _$drawing_498.selectedTextStyle(txs, trace); }); - _$registry_668.getComponentMethod('errorbars', 'style')(s); + _$registry_731.getComponentMethod('errorbars', 'style')(s); }; /** @@ -36028,7 +40175,7 @@ var _$style_689 = function style(gd, cd) { 'use strict'; -var _$constants_413 = { +var _$constants_475 = { cn: { colorbar: 'colorbar', cbbg: 'cbbg', @@ -36056,34 +40203,34 @@ var _$constants_413 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __extendFlat_415 = _$extend_528.extendFlat; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$titles_504 = require('../titles'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -var __LINE_SPACING_415 = _$alignment_511.LINE_SPACING; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __extendFlat_477 = _$extend_590.extendFlat; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$titles_566 = require('../titles'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +var __LINE_SPACING_477 = _$alignment_573.LINE_SPACING; -/* removed: var _$handleAxisDefaults_586 = require('../../plots/cartesian/axis_defaults'); */; -/* removed: var _$handlePositionDefaults_600 = require('../../plots/cartesian/position_defaults'); */; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$handleAxisDefaults_649 = require('../../plots/cartesian/axis_defaults'); */; +/* removed: var _$handlePositionDefaults_662 = require('../../plots/cartesian/position_defaults'); */; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$attributes_412 = require('./attributes'); */; -var cn = _$constants_413.cn; +/* removed: var _$attributes_474 = require('./attributes'); */; +var cn = _$constants_475.cn; -var _$draw_415 = function draw(gd, id) { +var _$draw_477 = function draw(gd, id) { // opts: options object, containing everything from attributes // plus a few others that are the equivalent of the colorbar "data" var opts = {}; - Object.keys(_$attributes_412).forEach(function(k) { + Object.keys(_$attributes_474).forEach(function(k) { opts[k] = null; }); // fillcolor can be a d3 scale, domain is z values, range is colors @@ -36110,7 +40257,7 @@ var _$draw_415 = function draw(gd, id) { fullLayout._infolayer.selectAll('g.' + id).remove(); return; } - var zrange = _$d3_127.extent(((typeof opts.fillcolor === 'function') ? + var zrange = _$d3_130.extent(((typeof opts.fillcolor === 'function') ? opts.fillcolor : opts.line.color).domain()); var linelevels = []; var filllevels = []; @@ -36238,12 +40385,12 @@ var _$draw_415 = function draw(gd, id) { // Coerce w.r.t. Axes layoutAttributes: // re-use axes.js logic without updating _fullData function coerce(attr, dflt) { - return _$lib_539.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_596, attr, dflt); + return _$lib_601.coerce(cbAxisIn, cbAxisOut, _$layout_attributes_659, attr, dflt); } // Prepare the Plotly axis object - _$handleAxisDefaults_586(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); - _$handlePositionDefaults_600(cbAxisIn, cbAxisOut, coerce, axisOptions); + _$handleAxisDefaults_649(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout); + _$handlePositionDefaults_662(cbAxisIn, cbAxisOut, coerce, axisOptions); // position can't go in through supplyDefaults // because that restricts it to [0,1] @@ -36264,14 +40411,14 @@ var _$draw_415 = function draw(gd, id) { cbAxisOut.tick0 = opts.levels.start; var dtick = opts.levels.size; // expand if too many contours, so we don't get too many ticks - var autoNtick = _$lib_539.constrain( + var autoNtick = _$lib_601.constrain( (yBottomPx - yTopPx) / 50, 4, 15) + 1, dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick); if(dtFactor > 1) { var dtexp = Math.pow(10, Math.floor( Math.log(dtFactor) / Math.LN10)); - dtick *= dtexp * _$lib_539.roundUp(dtFactor / dtexp, [2, 5, 10]); + dtick *= dtexp * _$lib_601.roundUp(dtFactor / dtexp, [2, 5, 10]); // if the contours are at round multiples, reset tick0 // so they're still at round multiples. Otherwise, // keep the first label on the first contour level @@ -36292,20 +40439,21 @@ var _$draw_415 = function draw(gd, id) { cbAxisOut.setScale(); // now draw the elements - var container = fullLayout._infolayer.selectAll('g.' + id).data([0]); - container.enter().append('g').classed(id, true) - .classed(cn.colorbar, true) - .each(function() { - var s = _$d3_127.select(this); - s.append('rect').classed(cn.cbbg, true); - s.append('g').classed(cn.cbfills, true); - s.append('g').classed(cn.cblines, true); - s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); - s.append('g').classed(cn.cbtitleunshift, true) - .append('g').classed(cn.cbtitle, true); - s.append('rect').classed(cn.cboutline, true); - s.select('.cbtitle').datum(0); - }); + var container = _$lib_601.ensureSingle(fullLayout._infolayer, 'g', id, function(s) { + s.classed(cn.colorbar, true) + .each(function() { + var s = _$d3_130.select(this); + s.append('rect').classed(cn.cbbg, true); + s.append('g').classed(cn.cbfills, true); + s.append('g').classed(cn.cblines, true); + s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true); + s.append('g').classed(cn.cbtitleunshift, true) + .append('g').classed(cn.cbtitle, true); + s.append('rect').classed(cn.cboutline, true); + s.select('.cbtitle').datum(0); + }); + }); + container.attr('transform', 'translate(' + Math.round(gs.l) + ',' + Math.round(gs.t) + ')'); // TODO: this opposite transform is a hack until we make it @@ -36351,10 +40499,10 @@ var _$draw_415 = function draw(gd, id) { lineSize = 15.6; if(titleText.node()) { lineSize = - parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_415; + parseInt(titleText.node().style.fontSize, 10) * __LINE_SPACING_477; } if(mathJaxNode) { - titleHeight = _$drawing_436.bBox(mathJaxNode).height; + titleHeight = _$drawing_498.bBox(mathJaxNode).height; if(titleHeight > lineSize) { // not entirely sure how mathjax is doing // vertical alignment, but this seems to work. @@ -36363,7 +40511,7 @@ var _$draw_415 = function draw(gd, id) { } else if(titleText.node() && !titleText.classed(cn.jsPlaceholder)) { - titleHeight = _$drawing_436.bBox(titleText.node()).height; + titleHeight = _$drawing_498.bBox(titleText.node()).height; } if(titleHeight) { // buffer btwn colorbar and title @@ -36376,7 +40524,7 @@ var _$draw_415 = function draw(gd, id) { } else { cbAxisOut.domain[0] += titleHeight / gs.h; - var nlines = _$svg_text_utils_562.lineCount(titleText); + var nlines = _$svg_text_utils_625.lineCount(titleText); titleTrans[1] += (1 - nlines) * lineSize; } @@ -36421,15 +40569,15 @@ var _$draw_415 = function draw(gd, id) { // Tinycolor can't handle exponents and // at this scale, removing it makes no difference. var colorString = fillcolormap(d).replace('e-', ''), - opaqueColor = _$tinycolor_352(colorString).toHexString(); + opaqueColor = _$tinycolor_414(colorString).toHexString(); // Colorbar cannot currently support opacities so we // use an opaque fill even when alpha channels present - _$d3_127.select(this).attr({ + _$d3_130.select(this).attr({ x: xLeft, width: Math.max(thickPx, 2), - y: _$d3_127.min(z), - height: Math.max(_$d3_127.max(z) - _$d3_127.min(z), 2), + y: _$d3_130.min(z), + height: Math.max(_$d3_130.max(z) - _$d3_130.min(z), 2), fill: opaqueColor }); }); @@ -36442,11 +40590,11 @@ var _$draw_415 = function draw(gd, id) { .classed(cn.cbline, true); lines.exit().remove(); lines.each(function(d) { - _$d3_127.select(this) + _$d3_130.select(this) .attr('d', 'M' + xLeft + ',' + (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) + 'h' + thickPx) - .call(_$drawing_436.lineGroupStyle, + .call(_$drawing_498.lineGroupStyle, opts.line.width, linecolormap(d), opts.line.dash); }); @@ -36462,9 +40610,9 @@ var _$draw_415 = function draw(gd, id) { // so we don't need such complicated logic in Titles.draw // if title is on the top or bottom, we've already drawn it // this title call only handles side=right - return _$lib_539.syncOrAsync([ + return _$lib_601.syncOrAsync([ function() { - return _$axes_584.doTicks(gd, cbAxisOut, true); + return _$axes_647.doTicks(gd, cbAxisOut, true); }, function() { if(['top', 'bottom'].indexOf(opts.titleside) === -1) { @@ -36479,7 +40627,7 @@ var _$draw_415 = function draw(gd, id) { // TODO: find a better way to control this. drawTitle('h' + cbAxisOut._id + 'title', { avoid: { - selection: _$d3_127.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), + selection: _$d3_130.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'), side: opts.titleside, offsetLeft: gs.l, offsetTop: 0, @@ -36495,7 +40643,7 @@ var _$draw_415 = function draw(gd, id) { function drawTitle(titleClass, titleOpts) { var trace = getTrace(), propName; - if(_$registry_668.traceIs(trace, 'markerColorscale')) { + if(_$registry_731.traceIs(trace, 'markerColorscale')) { propName = 'marker.colorbar.title'; } else propName = 'colorbar.title'; @@ -36517,8 +40665,8 @@ var _$draw_415 = function draw(gd, id) { container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group') .remove(); - _$titles_504.draw(gd, titleClass, - __extendFlat_415(dfltTitleOpts, titleOpts || {})); + _$titles_566.draw(gd, titleClass, + __extendFlat_477(dfltTitleOpts, titleOpts || {})); } function positionCB() { @@ -36527,7 +40675,7 @@ var _$draw_415 = function draw(gd, id) { // TODO: why are we redrawing multiple times now with this? // I guess autoMargin doesn't like being post-promise? var innerWidth = thickPx + opts.outlinewidth / 2 + - _$drawing_436.bBox(cbAxisOut._axislayer.node()).width; + _$drawing_498.bBox(cbAxisOut._axislayer.node()).width; titleEl = titleCont.select('text'); if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { var mathJaxNode = titleCont @@ -36536,7 +40684,7 @@ var _$draw_415 = function draw(gd, id) { titleWidth; if(mathJaxNode && ['top', 'bottom'].indexOf(opts.titleside) !== -1) { - titleWidth = _$drawing_436.bBox(mathJaxNode).width; + titleWidth = _$drawing_498.bBox(mathJaxNode).width; } else { // note: the formula below works for all titlesides, @@ -36544,7 +40692,7 @@ var _$draw_415 = function draw(gd, id) { // but the weird gs.l is because the titleunshift // transform gets removed by Drawing.bBox titleWidth = - _$drawing_436.bBox(titleCont.node()).right - + _$drawing_498.bBox(titleCont.node()).right - xLeft - gs.l; } innerWidth = Math.max(innerWidth, titleWidth); @@ -36561,8 +40709,8 @@ var _$draw_415 = function draw(gd, id) { width: Math.max(outerwidth, 2), height: Math.max(outerheight + 2 * yExtraPx, 2) }) - .call(_$color_411.fill, opts.bgcolor) - .call(_$color_411.stroke, opts.bordercolor) + .call(_$color_473.fill, opts.bgcolor) + .call(_$color_473.stroke, opts.bordercolor) .style({'stroke-width': opts.borderwidth}); container.selectAll('.cboutline').attr({ @@ -36572,7 +40720,7 @@ var _$draw_415 = function draw(gd, id) { width: Math.max(thickPx, 2), height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2) }) - .call(_$color_411.stroke, opts.outlinecolor) + .call(_$color_473.stroke, opts.outlinecolor) .style({ fill: 'None', 'stroke-width': opts.outlinewidth @@ -36585,7 +40733,7 @@ var _$draw_415 = function draw(gd, id) { 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')'); // auto margin adjustment - _$plots_647.autoMargin(gd, id, { + _$plots_709.autoMargin(gd, id, { x: opts.x, y: opts.y, l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0), @@ -36595,10 +40743,10 @@ var _$draw_415 = function draw(gd, id) { }); } - var cbDone = _$lib_539.syncOrAsync([ - _$plots_647.previousPromises, + var cbDone = _$lib_601.syncOrAsync([ + _$plots_709.previousPromises, drawAxis, - _$plots_647.previousPromises, + _$plots_709.previousPromises, positionCB ], gd); @@ -36610,31 +40758,31 @@ var _$draw_415 = function draw(gd, id) { xf, yf; - _$dragelement_433.init({ + _$dragelement_495.init({ element: container.node(), gd: gd, prepFn: function() { t0 = container.attr('transform'); - _$setCursor_558(container); + _$setCursor_621(container); }, moveFn: function(dx, dy) { container.attr('transform', t0 + ' ' + 'translate(' + dx + ',' + dy + ')'); - xf = _$dragelement_433.align(xLeftFrac + (dx / gs.w), thickFrac, + xf = _$dragelement_495.align(xLeftFrac + (dx / gs.w), thickFrac, 0, 1, opts.xanchor); - yf = _$dragelement_433.align(yBottomFrac - (dy / gs.h), lenFrac, + yf = _$dragelement_495.align(yBottomFrac - (dy / gs.h), lenFrac, 0, 1, opts.yanchor); - var csr = _$dragelement_433.getCursor(xf, yf, + var csr = _$dragelement_495.getCursor(xf, yf, opts.xanchor, opts.yanchor); - _$setCursor_558(container, csr); + _$setCursor_621(container, csr); }, doneFn: function() { - _$setCursor_558(container); + _$setCursor_621(container); if(xf !== undefined && yf !== undefined) { - _$registry_668.call('restyle', + _$registry_731.call('restyle', gd, {'colorbar.x': xf, 'colorbar.y': yf}, getTrace().index @@ -36664,8 +40812,8 @@ var _$draw_415 = function draw(gd, id) { // setter - for multi-part properties, // set only the parts that are provided - opts[name] = _$lib_539.isPlainObject(opts[name]) ? - _$lib_539.extendFlat(opts[name], v) : + opts[name] = _$lib_601.isPlainObject(opts[name]) ? + _$lib_601.extendFlat(opts[name], v) : v; return component; @@ -36700,15 +40848,15 @@ var _$draw_415 = function draw(gd, id) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_866 = function colorbar(gd, cd) { +var _$colorbar_931 = function colorbar(gd, cd) { var trace = cd[0].trace, marker = trace.marker, cbId = 'cb' + trace.uid; @@ -36718,7 +40866,7 @@ var _$colorbar_866 = function colorbar(gd, cd) { // TODO make Colorbar.draw support multiple colorbar per trace if((marker === undefined) || !marker.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } @@ -36726,12 +40874,12 @@ var _$colorbar_866 = function colorbar(gd, cd) { cmin = marker.cmin, cmax = marker.cmax; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( marker.colorscale, cmin, cmax @@ -36757,28 +40905,28 @@ var _$colorbar_866 = function colorbar(gd, cd) { var Bar = {}; -Bar.attributes = _$attributes_678; -Bar.layoutAttributes = _$layout_attributes_683; -Bar.supplyDefaults = _$supplyDefaults_680; -Bar.supplyLayoutDefaults = _$layout_defaults_684; -Bar.calc = _$calc_679; -Bar.setPositions = _$setPositions_687; -Bar.colorbar = _$colorbar_866; -Bar.arraysToCalcdata = _$arraysToCalcdata_677; -Bar.plot = _$plot_685; -Bar.style = _$style_689; -Bar.hoverPoints = _$hoverPoints_681; -Bar.selectPoints = _$selectPoints_686; +Bar.attributes = _$attributes_741; +Bar.layoutAttributes = _$layout_attributes_746; +Bar.supplyDefaults = _$supplyDefaults_743; +Bar.supplyLayoutDefaults = _$layout_defaults_747; +Bar.calc = _$calc_742; +Bar.setPositions = _$setPositions_750; +Bar.colorbar = _$colorbar_931; +Bar.arraysToCalcdata = _$arraysToCalcdata_740; +Bar.plot = _$plot_748; +Bar.style = _$style_752; +Bar.hoverPoints = _$hoverPoints_744; +Bar.selectPoints = _$selectPoints_749; Bar.moduleType = 'trace'; Bar.name = 'bar'; -Bar.basePlotModule = _$cartesian_595; -Bar.categories = ['cartesian', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend']; +Bar.basePlotModule = _$cartesian_658; +Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend', 'draggedPts']; Bar.meta = { }; -var _$Bar_682 = Bar; +var _$Bar_745 = Bar; /** * Copyright 2012-2018, Plotly, Inc. @@ -36790,7 +40938,7 @@ var _$Bar_682 = Bar; 'use strict'; -var _$bar_4 = _$Bar_682; +var _$bar_4 = _$Bar_745; /** * Copyright 2012-2018, Plotly, Inc. @@ -36802,14 +40950,14 @@ var _$bar_4 = _$Bar_682; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -var __extendFlat_691 = _$extend_528.extendFlat; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +var __extendFlat_754 = _$extend_590.extendFlat; -var __scatterMarkerAttrs_691 = _$attributes_862.marker; -var __scatterMarkerLineAttrs_691 = __scatterMarkerAttrs_691.line; +var __scatterMarkerAttrs_754 = _$attributes_927.marker; +var __scatterMarkerLineAttrs_754 = __scatterMarkerAttrs_754.line; -var _$attributes_691 = { +var _$attributes_754 = { y: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -36838,7 +40986,7 @@ var _$attributes_691 = { editType: 'calc+clearAxisTypes', }, - text: __extendFlat_691({}, _$attributes_862.text, { + text: __extendFlat_754({}, _$attributes_927.text, { }), whiskerwidth: { @@ -36912,19 +41060,19 @@ var _$attributes_691 = { editType: 'style', }, - symbol: __extendFlat_691({}, __scatterMarkerAttrs_691.symbol, + symbol: __extendFlat_754({}, __scatterMarkerAttrs_754.symbol, {arrayOk: false, editType: 'plot'}), - opacity: __extendFlat_691({}, __scatterMarkerAttrs_691.opacity, + opacity: __extendFlat_754({}, __scatterMarkerAttrs_754.opacity, {arrayOk: false, dflt: 1, editType: 'style'}), - size: __extendFlat_691({}, __scatterMarkerAttrs_691.size, + size: __extendFlat_754({}, __scatterMarkerAttrs_754.size, {arrayOk: false, editType: 'calcIfAutorange'}), - color: __extendFlat_691({}, __scatterMarkerAttrs_691.color, + color: __extendFlat_754({}, __scatterMarkerAttrs_754.color, {arrayOk: false, editType: 'style'}), line: { - color: __extendFlat_691({}, __scatterMarkerLineAttrs_691.color, - {arrayOk: false, dflt: _$attributes_410.defaultLine, editType: 'style'} + color: __extendFlat_754({}, __scatterMarkerLineAttrs_754.color, + {arrayOk: false, dflt: _$attributes_472.defaultLine, editType: 'style'} ), - width: __extendFlat_691({}, __scatterMarkerLineAttrs_691.width, + width: __extendFlat_754({}, __scatterMarkerLineAttrs_754.width, {arrayOk: false, dflt: 0, editType: 'style'} ), outliercolor: { @@ -36962,14 +41110,14 @@ var _$attributes_691 = { }, editType: 'plot' }, - fillcolor: _$attributes_862.fillcolor, + fillcolor: _$attributes_927.fillcolor, selected: { - marker: _$attributes_862.selected.marker, + marker: _$attributes_927.selected.marker, editType: 'style' }, unselected: { - marker: _$attributes_862.unselected.marker, + marker: _$attributes_927.unselected.marker, editType: 'style' }, @@ -36993,17 +41141,17 @@ var _$attributes_691 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var ____692 = _$lib_539._; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var ____755 = _$lib_601._; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; // outlier definition based on http://www.physics.csbsju.edu/stats/box2.html -var _$calc_692 = function calc(gd, trace) { +var _$calc_755 = function calc(gd, trace) { var fullLayout = gd._fullLayout; - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'); var cd = []; // N.B. violin reuses same Box.calc @@ -37028,7 +41176,7 @@ var _$calc_692 = function calc(gd, trace) { var val = valAxis.makeCalcdata(trace, valLetter); var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]); - var dv = _$lib_539.distinctVals(pos); + var dv = _$lib_601.distinctVals(pos); var posDistinct = dv.vals; var dPos = dv.minDiff / 2; var posBins = makeBins(posDistinct, dPos); @@ -37040,12 +41188,12 @@ var _$calc_692 = function calc(gd, trace) { // bin pts info per position bins for(i = 0; i < vLen; i++) { var v = val[i]; - if(!_$fastIsnumeric_139(v)) continue; + if(!_$fastIsnumeric_196(v)) continue; - var n = _$lib_539.findBin(pos[i], posBins); + var n = _$lib_601.findBin(pos[i], posBins); if(n >= 0 && n < pLen) { var pt = {v: v, i: i}; - __arraysToCalcdata_692(pt, trace, i); + __arraysToCalcdata_755(pt, trace, i); ptsPerBin[n].push(pt); } } @@ -37064,29 +41212,29 @@ var _$calc_692 = function calc(gd, trace) { cdi.min = boxVals[0]; cdi.max = boxVals[bvLen - 1]; - cdi.mean = _$lib_539.mean(boxVals, bvLen); - cdi.sd = _$lib_539.stdev(boxVals, bvLen, cdi.mean); + cdi.mean = _$lib_601.mean(boxVals, bvLen); + cdi.sd = _$lib_601.stdev(boxVals, bvLen, cdi.mean); // first quartile - cdi.q1 = _$lib_539.interp(boxVals, 0.25); + cdi.q1 = _$lib_601.interp(boxVals, 0.25); // median - cdi.med = _$lib_539.interp(boxVals, 0.5); + cdi.med = _$lib_601.interp(boxVals, 0.5); // third quartile - cdi.q3 = _$lib_539.interp(boxVals, 0.75); + cdi.q3 = _$lib_601.interp(boxVals, 0.75); // lower and upper fences - last point inside // 1.5 interquartile ranges from quartiles cdi.lf = Math.min( cdi.q1, boxVals[Math.min( - _$lib_539.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, + _$lib_601.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, bvLen - 1 )] ); cdi.uf = Math.max( cdi.q3, boxVals[Math.max( - _$lib_539.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), + _$lib_601.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), 0 )] ); @@ -37107,8 +41255,8 @@ var _$calc_692 = function calc(gd, trace) { } } - __calcSelection_692(cd, trace); - _$axes_584.expand(valAxis, val, {padded: true}); + __calcSelection_755(cd, trace); + _$axes_647.expand(valAxis, val, {padded: true}); if(cd.length > 0) { cd[0].t = { @@ -37117,22 +41265,17 @@ var _$calc_692 = function calc(gd, trace) { posLetter: posLetter, valLetter: valLetter, labels: { - med: ____692(gd, 'median:'), - min: ____692(gd, 'min:'), - q1: ____692(gd, 'q1:'), - q3: ____692(gd, 'q3:'), - max: ____692(gd, 'max:'), - mean: trace.boxmean === 'sd' ? ____692(gd, 'mean ± σ:') : ____692(gd, 'mean:'), - lf: ____692(gd, 'lower fence:'), - uf: ____692(gd, 'upper fence:') + med: ____755(gd, 'median:'), + min: ____755(gd, 'min:'), + q1: ____755(gd, 'q1:'), + q3: ____755(gd, 'q3:'), + max: ____755(gd, 'max:'), + mean: trace.boxmean === 'sd' ? ____755(gd, 'mean ± σ:') : ____755(gd, 'mean:'), + lf: ____755(gd, 'lower fence:'), + uf: ____755(gd, 'upper fence:') } }; - // don't show labels in candlestick hover labels - if(trace._fullInput && trace._fullInput.type === 'candlestick') { - delete cd[0].t.labels; - } - fullLayout[numKey]++; return cd; } else { @@ -37156,10 +41299,10 @@ function getPos(trace, posLetter, posAxis, val, num) { pos0 = trace[posLetter + '0']; } else if('name' in trace && ( posAxis.type === 'category' || ( - _$fastIsnumeric_139(trace.name) && + _$fastIsnumeric_196(trace.name) && ['linear', 'log'].indexOf(posAxis.type) !== -1 ) || ( - _$lib_539.isDateTime(trace.name) && + _$lib_601.isDateTime(trace.name) && posAxis.type === 'date' ) )) { @@ -37192,7 +41335,7 @@ function initNestedArray(len) { return arr; } -function __arraysToCalcdata_692(pt, trace, i) { +function __arraysToCalcdata_755(pt, trace, i) { var trace2calc = { text: 'tx' }; @@ -37204,8 +41347,8 @@ function __arraysToCalcdata_692(pt, trace, i) { } } -function __calcSelection_692(cd, trace) { - if(_$lib_539.isArrayOrTypedArray(trace.selectedpoints)) { +function __calcSelection_755(cd, trace) { + if(_$lib_601.isArrayOrTypedArray(trace.selectedpoints)) { for(var i = 0; i < cd.length; i++) { var pts = cd[i].pts || []; var ptNumber2cdIndex = {}; @@ -37214,7 +41357,7 @@ function __calcSelection_692(cd, trace) { ptNumber2cdIndex[pts[j].i] = j; } - _$lib_539.tagSelected(pts, trace, ptNumber2cdIndex); + _$lib_601.tagSelected(pts, trace, ptNumber2cdIndex); } } } @@ -37233,15 +41376,15 @@ function extractVal(o) { return o.v; } 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$attributes_691 = require('./attributes'); */; +/* removed: var _$attributes_754 = require('./attributes'); */; function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_691, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_754, attr, dflt); } handleSampleDefaults(traceIn, traceOut, coerce, layout); @@ -37249,7 +41392,7 @@ function supplyDefaults(traceIn, traceOut, defaultColor, layout) { coerce('line.color', (traceIn.marker || {}).color || defaultColor); coerce('line.width'); - coerce('fillcolor', _$color_411.addOpacity(traceOut.line.color, 0.5)); + coerce('fillcolor', _$color_473.addOpacity(traceOut.line.color, 0.5)); coerce('whiskerwidth'); coerce('boxmean'); @@ -37277,7 +41420,7 @@ function handleSampleDefaults(traceIn, traceOut, coerce, layout) { return; } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); coerce('orientation', defaultOrientation); @@ -37286,7 +41429,7 @@ function handleSampleDefaults(traceIn, traceOut, coerce, layout) { function handlePointsDefaults(traceIn, traceOut, coerce, opts) { var prefix = opts.prefix; - var outlierColorDflt = _$lib_539.coerce2(traceIn, traceOut, _$attributes_691, 'marker.outliercolor'); + var outlierColorDflt = _$lib_601.coerce2(traceIn, traceOut, _$attributes_754, 'marker.outliercolor'); var lineoutliercolor = coerce('marker.line.outliercolor'); var points = coerce( @@ -37322,10 +41465,10 @@ function handlePointsDefaults(traceIn, traceOut, coerce, opts) { coerce('hoveron'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); } -var _$defaults_693 = { +var _$defaults_756 = { supplyDefaults: supplyDefaults, handleSampleDefaults: handleSampleDefaults, handlePointsDefaults: handlePointsDefaults @@ -37341,11 +41484,11 @@ var _$defaults_693 = { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; @@ -37391,25 +41534,26 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { hoverPseudoDistance, spikePseudoDistance; var boxDelta = t.bdPos; + var posAcceptance = t.wHover; var shiftPos = function(di) { return di.pos + t.bPos - pVal; }; if(isViolin && trace.side !== 'both') { if(trace.side === 'positive') { dPos = function(di) { var pos = shiftPos(di); - return _$fx_453.inbox(pos, pos + boxDelta, hoverPseudoDistance); + return _$fx_515.inbox(pos, pos + posAcceptance, hoverPseudoDistance); }; } if(trace.side === 'negative') { dPos = function(di) { var pos = shiftPos(di); - return _$fx_453.inbox(pos - boxDelta, pos, hoverPseudoDistance); + return _$fx_515.inbox(pos - posAcceptance, pos, hoverPseudoDistance); }; } } else { dPos = function(di) { var pos = shiftPos(di); - return _$fx_453.inbox(pos - boxDelta, pos + boxDelta, hoverPseudoDistance); + return _$fx_515.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance); }; } @@ -37417,11 +41561,11 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { if(isViolin) { dVal = function(di) { - return _$fx_453.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); + return _$fx_515.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance); }; } else { dVal = function(di) { - return _$fx_453.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); + return _$fx_515.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance); }; } @@ -37451,8 +41595,8 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; function dxy(di) { return (dx(di) + dy(di)) / 2; } - var distfn = _$fx_453.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_453.getClosest(cd, distfn, pointData); + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_515.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point // and create the item(s) in closedata for this point @@ -37462,14 +41606,13 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { var lc = trace.line.color; var mc = (trace.marker || {}).color; - if(_$color_411.opacity(lc) && trace.line.width) pointData.color = lc; - else if(_$color_411.opacity(mc) && trace.boxpoints) pointData.color = mc; + if(_$color_473.opacity(lc) && trace.line.width) pointData.color = lc; + else if(_$color_473.opacity(mc) && trace.boxpoints) pointData.color = mc; else pointData.color = trace.fillcolor; - pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - t.bdPos, true); - pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + t.bdPos, true); + pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDelta, true); + pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDelta, true); - _$axes_584.tickText(pAxis, pAxis.c2l(di.pos), 'hover').text; pointData[pLetter + 'LabelVal'] = di.pos; var spikePosAttr = pLetter + 'Spike'; @@ -37496,11 +41639,11 @@ function hoverOnBoxes(pointData, xval, yval, hovermode) { // copy out to a new object for each value to label var val = di[attr]; var valPx = vAxis.c2p(val, true); - var pointData2 = _$lib_539.extendFlat({}, pointData); + var pointData2 = _$lib_601.extendFlat({}, pointData); pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx; pointData2[vLetter + 'LabelVal'] = val; - pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_584.hoverLabelText(vAxis, val); + pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + _$axes_647.hoverLabelText(vAxis, val); if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') { pointData2[vLetter + 'err'] = di.sd; @@ -37533,7 +41676,7 @@ function hoverOnPoints(pointData, xval, yval) { var rad = Math.max(3, di.mrc || 0); return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad); }; - var distfn = _$fx_453.quadrature(dx, dy); + var distfn = _$fx_515.quadrature(dx, dy); // show one point per trace var ijClosest = false; @@ -37562,7 +41705,7 @@ function hoverOnPoints(pointData, xval, yval) { var yc = ya.c2p(pt.y, true); var rad = pt.mrc || 1; - closePtData = _$lib_539.extendFlat({}, pointData, { + closePtData = _$lib_601.extendFlat({}, pointData, { // corresponds to index in x/y input data array index: pt.i, color: (trace.marker || {}).color, @@ -37578,12 +41721,12 @@ function hoverOnPoints(pointData, xval, yval) { var pLetter = trace.orientation === 'h' ? 'y' : 'x'; var pa = trace.orientation === 'h' ? ya : xa; closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true); - _$fillHoverText_870(pt, trace, closePtData); + _$fillHoverText_935(pt, trace, closePtData); return closePtData; } -var _$hover_694 = { +var _$hover_757 = { hoverPoints: hoverPoints, hoverOnBoxes: hoverOnBoxes, hoverOnPoints: hoverOnPoints @@ -37600,7 +41743,7 @@ var _$hover_694 = { 'use strict'; -var _$layout_attributes_696 = { +var _$layout_attributes_759 = { boxmode: { valType: 'enumerated', values: ['group', 'overlay'], @@ -37639,13 +41782,15 @@ var _$layout_attributes_696 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_696 = require('./layout_attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_759 = require('./layout_attributes'); */; function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { var hasTraceType; + var category = traceType + 'Layout'; for(var i = 0; i < fullData.length; i++) { - if(fullData[i].type === traceType) { + if(_$registry_731.traceIs(fullData[i], category)) { hasTraceType = true; break; } @@ -37659,12 +41804,12 @@ function _supply(layoutIn, layoutOut, fullData, coerce, traceType) { function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_696, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_759, attr, dflt); } _supply(layoutIn, layoutOut, fullData, coerce, 'box'); } -var _$layout_defaults_697 = { +var _$layout_defaults_760 = { supplyLayoutDefaults: supplyLayoutDefaults, _supply: _supply }; @@ -37679,10 +41824,10 @@ var _$layout_defaults_697 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; // constants for dynamic jitter (ie less jitter for sparser points) var JITTERCOUNT = 5; // points either side of this to include @@ -37703,19 +41848,22 @@ function plot(gd, plotinfo, cdbox) { var cd0 = d[0]; var t = cd0.t; var trace = cd0.trace; - var sel = cd0.node3 = _$d3_127.select(this); + var sel = _$d3_130.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; var numBoxes = fullLayout._numBoxes; + var groupFraction = (1 - fullLayout.boxgap); + var group = (fullLayout.boxmode === 'group' && numBoxes > 1); // box half width - var bdPos = t.dPos * (1 - fullLayout.boxgap) * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); + var bdPos = t.dPos * groupFraction * (1 - fullLayout.boxgroupgap) / (group ? numBoxes : 1); // box center offset - var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * (1 - fullLayout.boxgap) : 0; + var bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numBoxes) * groupFraction : 0; // whisker width var wdPos = bdPos * trace.whiskerwidth; if(trace.visible !== true || t.empty) { - _$d3_127.select(this).remove(); + sel.remove(); return; } @@ -37733,6 +41881,9 @@ function plot(gd, plotinfo, cdbox) { t.bPos = bPos; t.bdPos = bdPos; t.wdPos = wdPos; + // half-width within which to accept hover for this box + // always split the distance to the closest box + t.wHover = t.dPos * (group ? groupFraction / numBoxes : 1); // boxes and whiskers plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, t); @@ -37771,7 +41922,7 @@ function plotBoxAndWhiskers(sel, axes, trace, t) { } sel.selectAll('path.box') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .style('vector-effect', 'non-scaling-stroke') .attr('class', 'box') @@ -37788,17 +41939,25 @@ function plotBoxAndWhiskers(sel, axes, trace, t) { var q3 = valAxis.c2p(d.q3, true); // make sure median isn't identical to either of the // quartiles, so we can see it - var m = _$lib_539.constrain( + var m = _$lib_601.constrain( valAxis.c2p(d.med, true), Math.min(q1, q3) + 1, Math.max(q1, q3) - 1 ); - var lf = valAxis.c2p(trace.boxpoints === false ? d.min : d.lf, true); - var uf = valAxis.c2p(trace.boxpoints === false ? d.max : d.uf, true); + + // for compatibility with box, violin, and candlestick + // perhaps we should put this into cd0.t instead so it's more explicit, + // but what we have now is: + // - box always has d.lf, but boxpoints can be anything + // - violin has d.lf and should always use it (boxpoints is undefined) + // - candlestick has only min/max + var useExtremes = (d.lf === undefined) || (trace.boxpoints === false); + var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true); + var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true); var ln = valAxis.c2p(d.ln, true); var un = valAxis.c2p(d.un, true); if(trace.orientation === 'h') { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + m + ',' + posm0 + 'V' + posm1 + // median line 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge @@ -37810,7 +41969,7 @@ function plotBoxAndWhiskers(sel, axes, trace, t) { ((whiskerWidth === 0) ? '' : // whisker caps 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1)); } else { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + posm0 + ',' + m + 'H' + posm1 + // median line 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge @@ -37835,7 +41994,7 @@ function plotPoints(sel, axes, trace, t) { var mode = trace.boxpoints || trace.points; // repeatable pseudo-random number generator - _$lib_539.seedPseudoRandom(); + _$lib_601.seedPseudoRandom(); sel.selectAll('g.points') // since box plot points get an extra level of nesting, each @@ -37887,13 +42046,13 @@ function plotPoints(sel, axes, trace, t) { } var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0; - jitterFactor = _$lib_539.constrain(Math.abs(jitterFactor), 0, 1); + jitterFactor = _$lib_601.constrain(Math.abs(jitterFactor), 0, 1); jitterFactors.push(jitterFactor); maxJitterFactor = Math.max(jitterFactor, maxJitterFactor); } } - newJitter = trace.jitter * 2 / maxJitterFactor; + newJitter = trace.jitter * 2 / (maxJitterFactor || 1); } // fills in 'x' and 'y' in calcdata 'pts' item @@ -37902,7 +42061,7 @@ function plotPoints(sel, axes, trace, t) { var v = pt.v; var jitterOffset = trace.jitter ? - (newJitter * jitterFactors[i] * (_$lib_539.pseudoRandom() - 0.5)) : + (newJitter * jitterFactors[i] * (_$lib_601.pseudoRandom() - 0.5)) : 0; var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset); @@ -37925,7 +42084,7 @@ function plotPoints(sel, axes, trace, t) { }) .enter().append('path') .classed('point', true) - .call(_$drawing_436.translatePoints, xa, ya); + .call(_$drawing_498.translatePoints, xa, ya); } function plotBoxMean(sel, axes, trace, t) { @@ -37946,7 +42105,7 @@ function plotBoxMean(sel, axes, trace, t) { } sel.selectAll('path.mean') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .attr('class', 'mean') .style({ @@ -37962,14 +42121,14 @@ function plotBoxMean(sel, axes, trace, t) { var sh = valAxis.c2p(d.mean + d.sd, true); if(trace.orientation === 'h') { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + m + ',' + pos0 + 'V' + pos1 + (trace.boxmean === 'sd' ? 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : '') ); } else { - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', 'M' + pos0 + ',' + m + 'H' + pos1 + (trace.boxmean === 'sd' ? 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : @@ -37979,7 +42138,7 @@ function plotBoxMean(sel, axes, trace, t) { }); } -var _$plot_698 = { +var _$plot_761 = { plot: plot, plotBoxAndWhiskers: plotBoxAndWhiskers, plotPoints: plotPoints, @@ -37996,7 +42155,7 @@ var _$plot_698 = { 'use strict'; -var _$selectPoints_699 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_762 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -38044,8 +42203,8 @@ var _$selectPoints_699 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; var orientations = ['v', 'h']; @@ -38061,21 +42220,23 @@ function setPositions(gd, plotinfo) { var minPad = 0; var maxPad = 0; - // make list of boxes + // make list of boxes / candlesticks + // For backward compatibility, candlesticks are treated as if they *are* box traces here for(var j = 0; j < calcdata.length; j++) { var cd = calcdata[j]; var t = cd[0].t; var trace = cd[0].trace; - if(trace.visible === true && trace.type === 'box' && + if(trace.visible === true && + (trace.type === 'box' || trace.type === 'candlestick') && !t.empty && - trace.orientation === orientation && + (trace.orientation || 'v') === orientation && trace.xaxis === xa._id && trace.yaxis === ya._id ) { boxList.push(j); - if(trace.boxpoints !== false) { + if(trace.boxpoints) { minPad = Math.max(minPad, trace.jitter - trace.pointpos - 1); maxPad = Math.max(maxPad, trace.jitter + trace.pointpos - 1); } @@ -38108,7 +42269,7 @@ function setPositionOffset(traceType, gd, boxList, posAxis, pad) { // box plots - update dPos based on multiple traces // and then use for posAxis autorange - var boxdv = _$lib_539.distinctVals(pointList); + var boxdv = _$lib_601.distinctVals(pointList); var dPos = boxdv.minDiff / 2; // if there's no duplication of x points, @@ -38118,7 +42279,7 @@ function setPositionOffset(traceType, gd, boxList, posAxis, pad) { } // check for forced minimum dtick - _$axes_584.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); + _$axes_647.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true); // set the width of all boxes for(i = 0; i < boxList.length; i++) { @@ -38133,13 +42294,13 @@ function setPositionOffset(traceType, gd, boxList, posAxis, pad) { // autoscale the x axis - including space for points if they're off the side // TODO: this will overdo it if the outermost boxes don't have // their points as far out as the other boxes - _$axes_584.expand(posAxis, boxdv.vals, { + _$axes_647.expand(posAxis, boxdv.vals, { vpadminus: dPos + pad[0] * padfactor, vpadplus: dPos + pad[1] * padfactor }); } -var _$set_positions_700 = { +var _$set_positions_763 = { setPositions: setPositions, setPositionOffset: setPositionOffset }; @@ -38154,35 +42315,50 @@ var _$set_positions_700 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -var _$style_701 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.boxes'); +var _$style_764 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.trace.boxes'); s.style('opacity', function(d) { return d[0].trace.opacity; }); s.each(function(d) { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var trace = d[0].trace; var lineWidth = trace.line.width; - el.selectAll('path.box') - .style('stroke-width', lineWidth + 'px') - .call(_$color_411.stroke, trace.line.color) - .call(_$color_411.fill, trace.fillcolor); + function styleBox(boxSel, lineWidth, lineColor, fillColor) { + boxSel.style('stroke-width', lineWidth + 'px') + .call(_$color_473.stroke, lineColor) + .call(_$color_473.fill, fillColor); + } - el.selectAll('path.mean') - .style({ - 'stroke-width': lineWidth, - 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' - }) - .call(_$color_411.stroke, trace.line.color); + var allBoxes = el.selectAll('path.box'); + + if(trace.type === 'candlestick') { + allBoxes.each(function(boxData) { + var thisBox = _$d3_130.select(this); + var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing' + styleBox(thisBox, container.line.width, container.line.color, container.fillcolor); + // TODO: custom selection style for candlesticks + thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1); + }); + } + else { + styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor); + el.selectAll('path.mean') + .style({ + 'stroke-width': lineWidth, + 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px' + }) + .call(_$color_473.stroke, trace.line.color); - var pts = el.selectAll('path.point'); - _$drawing_436.pointStyle(pts, trace, gd); - _$drawing_436.selectedPointStyle(pts, trace); + var pts = el.selectAll('path.point'); + _$drawing_498.pointStyle(pts, trace, gd); + _$drawing_498.selectedPointStyle(pts, trace); + } }); }; @@ -38198,26 +42374,26 @@ var _$style_701 = function style(gd, cd) { var Box = {}; -Box.attributes = _$attributes_691; -Box.layoutAttributes = _$layout_attributes_696; -Box.supplyDefaults = _$defaults_693.supplyDefaults; -Box.supplyLayoutDefaults = _$layout_defaults_697.supplyLayoutDefaults; -Box.calc = _$calc_692; -Box.setPositions = _$set_positions_700.setPositions; -Box.plot = _$plot_698.plot; -Box.style = _$style_701; -Box.hoverPoints = _$hover_694.hoverPoints; -Box.selectPoints = _$selectPoints_699; +Box.attributes = _$attributes_754; +Box.layoutAttributes = _$layout_attributes_759; +Box.supplyDefaults = _$defaults_756.supplyDefaults; +Box.supplyLayoutDefaults = _$layout_defaults_760.supplyLayoutDefaults; +Box.calc = _$calc_755; +Box.setPositions = _$set_positions_763.setPositions; +Box.plot = _$plot_761.plot; +Box.style = _$style_764; +Box.hoverPoints = _$hover_757.hoverPoints; +Box.selectPoints = _$selectPoints_762; Box.moduleType = 'trace'; Box.name = 'box'; -Box.basePlotModule = _$cartesian_595; -Box.categories = ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend']; +Box.basePlotModule = _$cartesian_658; +Box.categories = ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'draggedPts', 'boxLayout']; Box.meta = { }; -var _$Box_695 = Box; +var _$Box_758 = Box; /** * Copyright 2012-2018, Plotly, Inc. @@ -38229,7 +42405,7 @@ var _$Box_695 = Box; 'use strict'; -var _$box_5 = _$Box_695; +var _$box_5 = _$Box_758; /* object-assign @@ -38295,7 +42471,7 @@ function shouldUseNative() { } } -var _$objectAssign_281 = shouldUseNative() ? Object.assign : function (target, source) { +var _$objectAssign_339 = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; @@ -38322,7 +42498,7 @@ var _$objectAssign_281 = shouldUseNative() ? Object.assign : function (target, s return to; }; -var _$main_388 = {}; +var _$main_450 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -38340,7 +42516,7 @@ var _$main_388 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; function Calendars() { @@ -38361,7 +42537,7 @@ function Calendars() {

Provides support for various world calendars in a consistent manner.

@class Calendars @example _exports.instance('julian').newDate(2014, 12, 25) */ -_$objectAssign_281(Calendars.prototype, { +_$objectAssign_339(Calendars.prototype, { /** Obtain a calendar implementation and localisation. @memberof Calendars @@ -38464,7 +42640,7 @@ function pad(value, length) { return '000000'.substring(0, length - value.length) + value; } -_$objectAssign_281(CDate.prototype, { +_$objectAssign_339(CDate.prototype, { /** Create a new date. @memberof CDate @@ -38690,7 +42866,7 @@ function BaseCalendar() { this.shortYearCutoff = '+10'; } -_$objectAssign_281(BaseCalendar.prototype, { +_$objectAssign_339(BaseCalendar.prototype, { _validateLevel: 0, // "Stack" to turn validation on/off /** Create a new date within this calendar - today if no parameters given. @@ -39032,7 +43208,7 @@ function GregorianCalendar(language) { GregorianCalendar.prototype = new BaseCalendar; -_$objectAssign_281(GregorianCalendar.prototype, { +_$objectAssign_339(GregorianCalendar.prototype, { /** The calendar name. @memberof GregorianCalendar */ name: 'Gregorian', @@ -39215,7 +43391,7 @@ _$objectAssign_281(GregorianCalendar.prototype, { }); // Singleton manager -var _exports = _$main_388 = new Calendars(); +var _exports = _$main_450 = new Calendars(); // Date template _exports.cdate = CDate; @@ -39227,7 +43403,7 @@ _exports.baseCalendar = BaseCalendar; _exports.calendars.gregorian = GregorianCalendar; -var _$chinese_374 = {}; +var _$chinese_436 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -39245,11 +43421,11 @@ var _$chinese_374 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; -var gregorianCalendar = _$main_388.instance(); +var gregorianCalendar = _$main_450.instance(); /** Implementation of the traditional Chinese calendar. Source of calendar tables https://github.com/isee15/Lunar-Solar-Calendar-Converter . @@ -39259,9 +43435,9 @@ function ChineseCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -ChineseCalendar.prototype = new _$main_388.baseCalendar; +ChineseCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(ChineseCalendar.prototype, { +_$objectAssign_339(ChineseCalendar.prototype, { /** The calendar name. @memberof ChineseCalendar */ name: 'Chinese', @@ -39431,7 +43607,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { var invalidIntercalaryMonth = (isIntercalary && month !== intercalaryMonth); if (invalidIntercalaryMonth || month < 1 || month > 12) { - throw _$main_388.local.invalidMonth + throw _$main_450.local.invalidMonth .replace(/\{0\}/, this.local.name); } @@ -39467,7 +43643,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { // validate month var maxMonthIndex = (intercalaryMonth) ? 12 : 11; if (monthIndex < 0 || monthIndex > maxMonthIndex) { - throw _$main_388.local.invalidMonth + throw _$main_450.local.invalidMonth .replace(/\{0\}/, this.local.name); } @@ -39535,7 +43711,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { weekOfYear: function(year, monthIndex, day) { // compute Chinese new year var validatedYear = - this._validateYear(year, _$main_388.local.invalidyear); + this._validateYear(year, _$main_450.local.invalidyear); var packedDate = CHINESE_NEW_YEAR[validatedYear - CHINESE_NEW_YEAR[0]]; @@ -39582,7 +43758,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { var intercalaryMonth = monthDaysTable >> 13; var maxMonthIndex = (intercalaryMonth) ? 12 : 11; if (monthIndex > maxMonthIndex) { - throw _$main_388.local.invalidMonth + throw _$main_450.local.invalidMonth .replace(/\{0\}/, this.local.name); } @@ -39612,7 +43788,7 @@ _$objectAssign_281(ChineseCalendar.prototype, { @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(year, monthIndex, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = this._validateYear(date.year()); monthIndex = date.month(); day = date.day(); @@ -39704,7 +43880,7 @@ var MONTH_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?月/m; var MONTH_SHORT_NAME_REGEXP = /^闰?十?[一二三四五六七八九]?/m; // Chinese calendar implementation -_$main_388.calendars.chinese = ChineseCalendar; +_$main_450.calendars.chinese = ChineseCalendar; // Chinese calendar tables from year 1888 to 2111 // @@ -39960,7 +44136,7 @@ function toSolar(yearOrDate, monthOrResult, day, isIntercalaryOrResult, result) } -var _$coptic_375 = {}; +var _$coptic_437 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -39978,8 +44154,8 @@ var _$coptic_375 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Coptic calendar. @@ -39992,9 +44168,9 @@ function CopticCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -CopticCalendar.prototype = new _$main_388.baseCalendar; +CopticCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(CopticCalendar.prototype, { +_$objectAssign_339(CopticCalendar.prototype, { /** The calendar name. @memberof CopticCalendar */ name: 'Coptic', @@ -40056,7 +44232,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero return year % 4 === 3 || year % 4 === -1; }, @@ -40068,7 +44244,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ monthsInYear: function(year) { this._validate(year, this.minMonth, this.minDay, - _$main_388.local.invalidYear || _$main_388.regionalOptions[''].invalidYear); + _$main_450.local.invalidYear || _$main_450.regionalOptions[''].invalidYear); return 13; }, @@ -40093,7 +44269,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0); }, @@ -40118,7 +44294,7 @@ _$objectAssign_281(CopticCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); if (year < 0) { year++; } // No year zero return date.day() + (date.month() - 1) * 30 + @@ -40141,10 +44317,10 @@ _$objectAssign_281(CopticCalendar.prototype, { }); // Coptic calendar implementation -_$main_388.calendars.coptic = CopticCalendar; +_$main_450.calendars.coptic = CopticCalendar; -var _$discworld_376 = {}; +var _$discworld_438 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -40162,8 +44338,8 @@ var _$discworld_376 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Discworld calendar - Unseen University version. @@ -40175,9 +44351,9 @@ function DiscworldCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -DiscworldCalendar.prototype = new _$main_388.baseCalendar; +DiscworldCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(DiscworldCalendar.prototype, { +_$objectAssign_339(DiscworldCalendar.prototype, { /** The calendar name. @memberof DiscworldCalendar */ name: 'Discworld', @@ -40238,7 +44414,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return false; }, @@ -40248,7 +44424,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 13; }, @@ -40258,7 +44434,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function(year) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 400; }, @@ -40283,7 +44459,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1]; }, @@ -40302,7 +44478,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return (date.day() + 1) % 8; }, @@ -40326,7 +44502,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return {century: centuries[Math.floor((date.year() - 1) / 100) + 1] || ''}; }, @@ -40339,7 +44515,7 @@ _$objectAssign_281(DiscworldCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year() + (date.year() < 0 ? 1 : 0); month = date.month(); day = date.day(); @@ -40369,10 +44545,10 @@ var centuries = { }; // Discworld calendar implementation -_$main_388.calendars.discworld = DiscworldCalendar; +_$main_450.calendars.discworld = DiscworldCalendar; -var _$ethiopian_377 = {}; +var _$ethiopian_439 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -40390,8 +44566,8 @@ var _$ethiopian_377 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Ethiopian calendar. @@ -40404,9 +44580,9 @@ function EthiopianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -EthiopianCalendar.prototype = new _$main_388.baseCalendar; +EthiopianCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(EthiopianCalendar.prototype, { +_$objectAssign_339(EthiopianCalendar.prototype, { /** The calendar name. @memberof EthiopianCalendar */ name: 'Ethiopian', @@ -40468,7 +44644,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = date.year() + (date.year() < 0 ? 1 : 0); // No year zero return year % 4 === 3 || year % 4 === -1; }, @@ -40480,7 +44656,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ monthsInYear: function(year) { this._validate(year, this.minMonth, this.minDay, - _$main_388.local.invalidYear || _$main_388.regionalOptions[''].invalidYear); + _$main_450.local.invalidYear || _$main_450.regionalOptions[''].invalidYear); return 13; }, @@ -40505,7 +44681,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 13 && this.leapYear(date.year()) ? 1 : 0); }, @@ -40530,7 +44706,7 @@ _$objectAssign_281(EthiopianCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); if (year < 0) { year++; } // No year zero return date.day() + (date.month() - 1) * 30 + @@ -40553,10 +44729,10 @@ _$objectAssign_281(EthiopianCalendar.prototype, { }); // Ethiopian calendar implementation -_$main_388.calendars.ethiopian = EthiopianCalendar; +_$main_450.calendars.ethiopian = EthiopianCalendar; -var _$hebrew_378 = {}; +var _$hebrew_440 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -40574,8 +44750,8 @@ var _$hebrew_378 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Hebrew civil calendar. @@ -40587,9 +44763,9 @@ function HebrewCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -HebrewCalendar.prototype = new _$main_388.baseCalendar; +HebrewCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(HebrewCalendar.prototype, { +_$objectAssign_339(HebrewCalendar.prototype, { /** The calendar name. @memberof HebrewCalendar */ name: 'Hebrew', @@ -40650,7 +44826,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return this._leapYear(date.year()); }, @@ -40662,7 +44838,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ _leapYear: function(year) { year = (year < 0 ? year + 1 : year); - return __mod_378(year * 7 + 1, 19) < 7; + return __mod_440(year * 7 + 1, 19) < 7; }, /** Retrieve the number of months in a year. @@ -40671,7 +44847,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return this._leapYear(year.year ? year.year() : year) ? 13 : 12; }, @@ -40695,7 +44871,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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, _$main_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); year = date.year(); return this.toJD((year === -1 ? +1 : year + 1), 7, 1) - this.toJD(year, 7, 1); }, @@ -40711,10 +44887,10 @@ _$objectAssign_281(HebrewCalendar.prototype, { month = year.month(); year = year.year(); } - this._validate(year, month, this.minDay, _$main_388.local.invalidMonth); + this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return (month === 12 && this.leapYear(year) ? 30 : // Adar I - (month === 8 && __mod_378(this.daysInYear(year), 10) === 5 ? 30 : // Cheshvan in shlemah year - (month === 9 && __mod_378(this.daysInYear(year), 10) === 3 ? 29 : // Kislev in chaserah year + (month === 8 && __mod_440(this.daysInYear(year), 10) === 5 ? 30 : // Cheshvan in shlemah year + (month === 9 && __mod_440(this.daysInYear(year), 10) === 3 ? 29 : // Kislev in chaserah year this.daysPerMonth[month - 1]))); }, @@ -40737,7 +44913,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return {yearType: (this.leapYear(date) ? 'embolismic' : 'common') + ' ' + ['deficient', 'regular', 'complete'][this.daysInYear(date) % 10 - 3]}; }, @@ -40751,7 +44927,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); @@ -40784,7 +44960,7 @@ _$objectAssign_281(HebrewCalendar.prototype, { var months = Math.floor((235 * year - 234) / 19); var parts = 12084 + 13753 * months; var day = months * 29 + Math.floor(parts / 25920); - if (__mod_378(3 * (day + 1), 7) < 3) { + if (__mod_440(3 * (day + 1), 7) < 3) { day++; } return day; @@ -40822,15 +44998,15 @@ _$objectAssign_281(HebrewCalendar.prototype, { }); // Modulus function which works for non-integers. -function __mod_378(a, b) { +function __mod_440(a, b) { return a - (b * Math.floor(a / b)); } // Hebrew calendar implementation -_$main_388.calendars.hebrew = HebrewCalendar; +_$main_450.calendars.hebrew = HebrewCalendar; -var _$islamic_379 = {}; +var _$islamic_441 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -40848,8 +45024,8 @@ var _$islamic_379 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Islamic or '16 civil' calendar. @@ -40861,9 +45037,9 @@ function IslamicCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -IslamicCalendar.prototype = new _$main_388.baseCalendar; +IslamicCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(IslamicCalendar.prototype, { +_$objectAssign_339(IslamicCalendar.prototype, { /** The calendar name. @memberof IslamicCalendar */ name: 'Islamic', @@ -40925,7 +45101,7 @@ _$objectAssign_281(IslamicCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return (date.year() * 11 + 14) % 30 < 11; }, @@ -40959,7 +45135,7 @@ _$objectAssign_281(IslamicCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, @@ -40984,7 +45160,7 @@ _$objectAssign_281(IslamicCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); @@ -41008,10 +45184,10 @@ _$objectAssign_281(IslamicCalendar.prototype, { }); // Islamic (16 civil) calendar implementation -_$main_388.calendars.islamic = IslamicCalendar; +_$main_450.calendars.islamic = IslamicCalendar; -var _$julian_380 = {}; +var _$julian_442 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41029,8 +45205,8 @@ var _$julian_380 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Julian calendar. @@ -41043,9 +45219,9 @@ function JulianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -JulianCalendar.prototype = new _$main_388.baseCalendar; +JulianCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(JulianCalendar.prototype, { +_$objectAssign_339(JulianCalendar.prototype, { /** The calendar name. @memberof JulianCalendar */ name: 'Julian', @@ -41106,7 +45282,7 @@ _$objectAssign_281(JulianCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = (date.year() < 0 ? date.year() + 1 : date.year()); // No year zero return (year % 4) === 0; }, @@ -41132,7 +45308,7 @@ _$objectAssign_281(JulianCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, @@ -41157,7 +45333,7 @@ _$objectAssign_281(JulianCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); @@ -41191,10 +45367,10 @@ _$objectAssign_281(JulianCalendar.prototype, { }); // Julian calendar implementation -_$main_388.calendars.julian = JulianCalendar; +_$main_450.calendars.julian = JulianCalendar; -var _$mayan_381 = {}; +var _$mayan_443 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41212,8 +45388,8 @@ var _$mayan_381 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Mayan Long Count calendar. @@ -41224,9 +45400,9 @@ function MayanCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -MayanCalendar.prototype = new _$main_388.baseCalendar; +MayanCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(MayanCalendar.prototype, { +_$objectAssign_339(MayanCalendar.prototype, { /** The calendar name. @memberof MayanCalendar */ name: 'Mayan', @@ -41294,7 +45470,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return false; }, @@ -41304,7 +45480,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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, _$main_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; @@ -41340,7 +45516,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 18; }, @@ -41352,7 +45528,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {number} The week of the year. @throws Error if an invalid date or a different calendar used. */ weekOfYear: function(year, month, day) { - this._validate(year, month, day, _$main_388.local.invalidDate); + this._validate(year, month, day, _$main_450.local.invalidDate); return 0; }, @@ -41362,7 +45538,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {number} The number of days. @throws Error if an invalid year or a different calendar used. */ daysInYear: function(year) { - this._validate(year, this.minMonth, this.minDay, _$main_388.local.invalidYear); + this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return 360; }, @@ -41373,7 +45549,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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) { - this._validate(year, month, this.minDay, _$main_388.local.invalidMonth); + this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return 20; }, @@ -41392,7 +45568,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return date.day(); }, @@ -41404,7 +45580,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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) { - this._validate(year, month, day, _$main_388.local.invalidDate); + this._validate(year, month, day, _$main_450.local.invalidDate); return true; }, @@ -41416,7 +45592,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used. */ extraInfo: function(year, month, day) { - var date = this._validate(year, month, day, _$main_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); @@ -41433,8 +45609,8 @@ _$objectAssign_281(MayanCalendar.prototype, { @return {number[]} Corresponding Haab month and day. */ _toHaab: function(jd) { jd -= this.jdEpoch; - var day = __mod_381(jd + 8 + ((18 - 1) * 20), 365); - return [Math.floor(day / 20) + 1, __mod_381(day, 20)]; + var day = __mod_443(jd + 8 + ((18 - 1) * 20), 365); + return [Math.floor(day / 20) + 1, __mod_443(day, 20)]; }, /** Retrieve Tzolkin date from a Julian date. @@ -41456,7 +45632,7 @@ _$objectAssign_281(MayanCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); return date.day() + (date.month() * 20) + (date.year() * 360) + this.jdEpoch; }, @@ -41476,20 +45652,20 @@ _$objectAssign_281(MayanCalendar.prototype, { }); // Modulus function which works for non-integers. -function __mod_381(a, b) { +function __mod_443(a, b) { return a - (b * Math.floor(a / b)); } // Modulus function which returns numerator if modulus is zero. function amod(a, b) { - return __mod_381(a - 1, b) + 1; + return __mod_443(a - 1, b) + 1; } // Mayan calendar implementation -_$main_388.calendars.mayan = MayanCalendar; +_$main_450.calendars.mayan = MayanCalendar; -var _$nanakshahi_382 = {}; +var _$nanakshahi_444 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41507,8 +45683,8 @@ var _$nanakshahi_382 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Nanakshahi calendar. @@ -41519,11 +45695,11 @@ function NanakshahiCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -NanakshahiCalendar.prototype = new _$main_388.baseCalendar; +NanakshahiCalendar.prototype = new _$main_450.baseCalendar; -var gregorian = _$main_388.instance('gregorian'); +var gregorian = _$main_450.instance('gregorian'); -_$objectAssign_281(NanakshahiCalendar.prototype, { +_$objectAssign_339(NanakshahiCalendar.prototype, { /** The calendar name. @memberof NanakshahiCalendar */ name: 'Nanakshahi', @@ -41585,7 +45761,7 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { @throws Error if an invalid year or a different calendar used. */ leapYear: function(year) { var date = this._validate(year, this.minMonth, this.minDay, - _$main_388.local.invalidYear || _$main_388.regionalOptions[''].invalidYear); + _$main_450.local.invalidYear || _$main_450.regionalOptions[''].invalidYear); return gregorian.leapYear(date.year() + (date.year() < 1 ? 1 : 0) + 1469); }, @@ -41610,7 +45786,7 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, @@ -41635,7 +45811,7 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, day, _$main_450.local.invalidMonth); var year = date.year(); if (year < 0) { year++; } // No year zero var doy = date.day(); @@ -41666,10 +45842,10 @@ _$objectAssign_281(NanakshahiCalendar.prototype, { }); // Nanakshahi calendar implementation -_$main_388.calendars.nanakshahi = NanakshahiCalendar; +_$main_450.calendars.nanakshahi = NanakshahiCalendar; -var _$nepali_383 = {}; +var _$nepali_445 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -41687,8 +45863,8 @@ var _$nepali_383 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Nepali civil calendar. @@ -41703,9 +45879,9 @@ function NepaliCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -NepaliCalendar.prototype = new _$main_388.baseCalendar; +NepaliCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(NepaliCalendar.prototype, { +_$objectAssign_339(NepaliCalendar.prototype, { /** The calendar name. @memberof NepaliCalendar */ name: 'Nepali', @@ -41792,7 +45968,7 @@ _$objectAssign_281(NepaliCalendar.prototype, { @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, _$main_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); year = date.year(); if (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined') { return this.daysPerYear; @@ -41815,7 +45991,7 @@ _$objectAssign_281(NepaliCalendar.prototype, { month = year.month(); year = year.year(); } - this._validate(year, month, this.minDay, _$main_388.local.invalidMonth); + this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return (typeof this.NEPALI_CALENDAR_DATA[year] === 'undefined' ? this.daysPerMonth[month - 1] : this.NEPALI_CALENDAR_DATA[year][month]); }, @@ -41840,11 +46016,11 @@ _$objectAssign_281(NepaliCalendar.prototype, { @return {number} The equivalent Julian date. @throws Error if an invalid date or a different calendar used. */ toJD: function(nepaliYear, nepaliMonth, nepaliDay) { - var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, _$main_388.local.invalidDate); + var date = this._validate(nepaliYear, nepaliMonth, nepaliDay, _$main_450.local.invalidDate); nepaliYear = date.year(); nepaliMonth = date.month(); nepaliDay = date.day(); - var gregorianCalendar = _$main_388.instance(); + var gregorianCalendar = _$main_450.instance(); var gregorianDayOfYear = 0; // We will add all the days that went by since // the 1st. January and then we can get the Gregorian Date var nepaliMonthToCheck = nepaliMonth; @@ -41893,7 +46069,7 @@ _$objectAssign_281(NepaliCalendar.prototype, { @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { - var gregorianCalendar = _$main_388.instance(); + var gregorianCalendar = _$main_450.instance(); var gregorianDate = gregorianCalendar.fromJD(jd); var gregorianYear = gregorianDate.year(); var gregorianDayOfYear = gregorianDate.dayOfYear(); @@ -42089,10 +46265,10 @@ _$objectAssign_281(NepaliCalendar.prototype, { }); // Nepali calendar implementation -_$main_388.calendars.nepali = NepaliCalendar; +_$main_450.calendars.nepali = NepaliCalendar; -var _$persian_384 = {}; +var _$persian_446 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42110,8 +46286,8 @@ var _$persian_384 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the Persian or Jalali calendar. @@ -42123,9 +46299,9 @@ function PersianCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -PersianCalendar.prototype = new _$main_388.baseCalendar; +PersianCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(PersianCalendar.prototype, { +_$objectAssign_339(PersianCalendar.prototype, { /** The calendar name. @memberof PersianCalendar */ name: 'Persian', @@ -42186,7 +46362,7 @@ _$objectAssign_281(PersianCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return (((((date.year() - (date.year() > 0 ? 474 : 473)) % 2820) + 474 + 38) * 682) % 2816) < 682; }, @@ -42212,7 +46388,7 @@ _$objectAssign_281(PersianCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 12 && this.leapYear(date.year()) ? 1 : 0); }, @@ -42237,12 +46413,12 @@ _$objectAssign_281(PersianCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); year = date.year(); month = date.month(); day = date.day(); var epBase = year - (year >= 0 ? 474 : 473); - var epYear = 474 + __mod_384(epBase, 2820); + var epYear = 474 + __mod_446(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; @@ -42256,11 +46432,11 @@ _$objectAssign_281(PersianCalendar.prototype, { jd = Math.floor(jd) + 0.5; var depoch = jd - this.toJD(475, 1, 1); var cycle = Math.floor(depoch / 1029983); - var cyear = __mod_384(depoch, 1029983); + var cyear = __mod_446(depoch, 1029983); var ycycle = 2820; if (cyear !== 1029982) { var aux1 = Math.floor(cyear / 366); - var aux2 = __mod_384(cyear, 366); + var aux2 = __mod_446(cyear, 366); ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1; } var year = ycycle + (2820 * cycle) + 474; @@ -42273,16 +46449,16 @@ _$objectAssign_281(PersianCalendar.prototype, { }); // Modulus function which works for non-integers. -function __mod_384(a, b) { +function __mod_446(a, b) { return a - (b * Math.floor(a / b)); } // Persian (Jalali) calendar implementation -_$main_388.calendars.persian = PersianCalendar; -_$main_388.calendars.jalali = PersianCalendar; +_$main_450.calendars.persian = PersianCalendar; +_$main_450.calendars.jalali = PersianCalendar; -var _$taiwan_385 = {}; +var _$taiwan_447 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42300,11 +46476,11 @@ var _$taiwan_385 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; -var __gregorianCalendar_385 = _$main_388.instance(); +var __gregorianCalendar_447 = _$main_450.instance(); /** Implementation of the Taiwanese calendar. See http://en.wikipedia.org/wiki/Minguo_calendar. @@ -42314,9 +46490,9 @@ function TaiwanCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -TaiwanCalendar.prototype = new _$main_388.baseCalendar; +TaiwanCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(TaiwanCalendar.prototype, { +_$objectAssign_339(TaiwanCalendar.prototype, { /** The calendar name. @memberof TaiwanCalendar */ name: 'Taiwan', @@ -42380,9 +46556,9 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_385.leapYear(year); + return __gregorianCalendar_447.leapYear(year); }, /** Determine the week of the year for a date - ISO 8601. @@ -42393,9 +46569,9 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_385.weekOfYear(year, date.month(), date.day()); + return __gregorianCalendar_447.weekOfYear(year, date.month(), date.day()); }, /** Retrieve the number of days in a month. @@ -42405,7 +46581,7 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, @@ -42430,9 +46606,9 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); var year = this._t2gYear(date.year()); - return __gregorianCalendar_385.toJD(year, date.month(), date.day()); + return __gregorianCalendar_447.toJD(year, date.month(), date.day()); }, /** Create a new date from a Julian date. @@ -42440,7 +46616,7 @@ _$objectAssign_281(TaiwanCalendar.prototype, { @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { - var date = __gregorianCalendar_385.fromJD(jd); + var date = __gregorianCalendar_447.fromJD(jd); var year = this._g2tYear(date.year()); return this.newDate(year, date.month(), date.day()); }, @@ -42465,10 +46641,10 @@ _$objectAssign_281(TaiwanCalendar.prototype, { }); // Taiwan calendar implementation -_$main_388.calendars.taiwan = TaiwanCalendar; +_$main_450.calendars.taiwan = TaiwanCalendar; -var _$thai_386 = {}; +var _$thai_448 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42486,11 +46662,11 @@ var _$thai_386 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; -var __gregorianCalendar_386 = _$main_388.instance(); +var __gregorianCalendar_448 = _$main_450.instance(); /** Implementation of the Thai calendar. See http://en.wikipedia.org/wiki/Thai_calendar. @@ -42500,9 +46676,9 @@ function ThaiCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -ThaiCalendar.prototype = new _$main_388.baseCalendar; +ThaiCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(ThaiCalendar.prototype, { +_$objectAssign_339(ThaiCalendar.prototype, { /** The calendar name. @memberof ThaiCalendar */ name: 'Thai', @@ -42566,9 +46742,9 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_386.leapYear(year); + return __gregorianCalendar_448.leapYear(year); }, /** Determine the week of the year for a date - ISO 8601. @@ -42579,9 +46755,9 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); var year = this._t2gYear(date.year()); - return __gregorianCalendar_386.weekOfYear(year, date.month(), date.day()); + return __gregorianCalendar_448.weekOfYear(year, date.month(), date.day()); }, /** Retrieve the number of days in a month. @@ -42591,7 +46767,7 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.local.invalidMonth); return this.daysPerMonth[date.month() - 1] + (date.month() === 2 && this.leapYear(date.year()) ? 1 : 0); }, @@ -42616,9 +46792,9 @@ _$objectAssign_281(ThaiCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.local.invalidDate); var year = this._t2gYear(date.year()); - return __gregorianCalendar_386.toJD(year, date.month(), date.day()); + return __gregorianCalendar_448.toJD(year, date.month(), date.day()); }, /** Create a new date from a Julian date. @@ -42626,7 +46802,7 @@ _$objectAssign_281(ThaiCalendar.prototype, { @param jd {number} The Julian date to convert. @return {CDate} The equivalent date. */ fromJD: function(jd) { - var date = __gregorianCalendar_386.fromJD(jd); + var date = __gregorianCalendar_448.fromJD(jd); var year = this._g2tYear(date.year()); return this.newDate(year, date.month(), date.day()); }, @@ -42651,10 +46827,10 @@ _$objectAssign_281(ThaiCalendar.prototype, { }); // Thai calendar implementation -_$main_388.calendars.thai = ThaiCalendar; +_$main_450.calendars.thai = ThaiCalendar; -var _$ummalqura_387 = {}; +var _$ummalqura_449 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -42673,8 +46849,8 @@ var _$ummalqura_387 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$main_388 = require('../main'); */; -/* removed: var _$objectAssign_281 = require('object-assign'); */; +/* removed: var _$main_450 = require('../main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; /** Implementation of the UmmAlQura or 'saudi' calendar. @@ -42687,9 +46863,9 @@ function UmmAlQuraCalendar(language) { this.local = this.regionalOptions[language || ''] || this.regionalOptions['']; } -UmmAlQuraCalendar.prototype = new _$main_388.baseCalendar; +UmmAlQuraCalendar.prototype = new _$main_450.baseCalendar; -_$objectAssign_281(UmmAlQuraCalendar.prototype, { +_$objectAssign_339(UmmAlQuraCalendar.prototype, { /** The calendar name. @memberof UmmAlQuraCalendar */ name: 'UmmAlQura', @@ -42745,7 +46921,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.local.invalidYear); + var date = this._validate(year, this.minMonth, this.minDay, _$main_450.local.invalidYear); return (this.daysInYear(date.year()) === 355); }, @@ -42783,7 +46959,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.local.invalidMonth); + var date = this._validate(year, month, this.minDay, _$main_450.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; @@ -42816,7 +46992,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.local.invalidDate); + var date = this._validate(year, month, day, _$main_450.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) @@ -42850,7 +47026,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.baseCalendar.prototype.isValid.apply(this, arguments); + var valid = _$main_450.baseCalendar.prototype.isValid.apply(this, arguments); if (valid) { year = (year.year != null ? year.year : year); valid = (year >= 1276 && year <= 1500); @@ -42867,7 +47043,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { @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_388.baseCalendar.prototype._validate.apply(this, arguments); + var date = _$main_450.baseCalendar.prototype._validate.apply(this, arguments); if (date.year < 1276 || date.year > 1500) { throw error.replace(/\{0\}/, this.local.name); } @@ -42876,7 +47052,7 @@ _$objectAssign_281(UmmAlQuraCalendar.prototype, { }); // UmmAlQura calendar implementation -_$main_388.calendars.ummalqura = UmmAlQuraCalendar; +_$main_450.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, @@ -43019,7 +47195,7 @@ var ummalqura_dat = [ 79990]; -var _$plus_389 = {}; +var _$plus_451 = {}; /* * World Calendars * https://github.com/alexcjohnson/world-calendars @@ -43037,11 +47213,11 @@ var _$plus_389 = {}; Available under the MIT (http://keith-wood.name/licence.html) license. Please attribute the author if you use it. */ -/* removed: var _$objectAssign_281 = require('object-assign'); */; -/* removed: var _$main_388 = require('./main'); */; +/* removed: var _$objectAssign_339 = require('object-assign'); */; +/* removed: var _$main_450 = require('./main'); */; -_$objectAssign_281(_$main_388.regionalOptions[''], { +_$objectAssign_339(_$main_450.regionalOptions[''], { invalidArguments: 'Invalid arguments', invalidFormat: 'Cannot format a date from another calendar', missingNumberAt: 'Missing number at position {0}', @@ -43049,9 +47225,9 @@ _$objectAssign_281(_$main_388.regionalOptions[''], { unexpectedLiteralAt: 'Unexpected literal at position {0}', unexpectedText: 'Additional text found at end' }); -_$main_388.local = _$main_388.regionalOptions['']; +_$main_450.local = _$main_450.regionalOptions['']; -_$objectAssign_281(_$main_388.cdate.prototype, { +_$objectAssign_339(_$main_450.cdate.prototype, { /** Format this date. Found in the jquery.calendars.plus.js module. @@ -43068,11 +47244,11 @@ _$objectAssign_281(_$main_388.cdate.prototype, { } }); -_$objectAssign_281(_$main_388.baseCalendar.prototype, { +_$objectAssign_339(_$main_450.baseCalendar.prototype, { - UNIX_EPOCH: _$main_388.instance().newDate(1970, 1, 1).toJD(), + UNIX_EPOCH: _$main_450.instance().newDate(1970, 1, 1).toJD(), SECS_PER_DAY: 24 * 60 * 60, - TICKS_EPOCH: _$main_388.instance().jdEpoch, // 1 January 0001 CE + TICKS_EPOCH: _$main_450.instance().jdEpoch, // 1 January 0001 CE TICKS_PER_DAY: 24 * 60 * 60 * 10000000, /** Date form for ATOM (RFC 3339/ISO 8601). @@ -43180,7 +47356,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { return ''; } if (date.calendar() !== this) { - throw _$main_388.local.invalidFormat || _$main_388.regionalOptions[''].invalidFormat; + throw _$main_450.local.invalidFormat || _$main_450.regionalOptions[''].invalidFormat; } format = format || this.local.dateFormat; settings = settings || {}; @@ -43305,7 +47481,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { if the value doesn't match the format, or if the date is invalid. */ parseDate: function(format, value, settings) { if (value == null) { - throw _$main_388.local.invalidArguments || _$main_388.regionalOptions[''].invalidArguments; + throw _$main_450.local.invalidArguments || _$main_450.regionalOptions[''].invalidArguments; } value = (typeof value === 'object' ? value.toString() : value + ''); if (value === '') { @@ -43345,7 +47521,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { var digits = new RegExp('^-?\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) { - throw (_$main_388.local.missingNumberAt || _$main_388.regionalOptions[''].missingNumberAt). + throw (_$main_450.local.missingNumberAt || _$main_450.regionalOptions[''].missingNumberAt). replace(/\{0\}/, iValue); } iValue += num[0].length; @@ -43372,7 +47548,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { return i + calendar.minMonth; } } - throw (_$main_388.local.unknownNameAt || _$main_388.regionalOptions[''].unknownNameAt). + throw (_$main_450.local.unknownNameAt || _$main_450.regionalOptions[''].unknownNameAt). replace(/\{0\}/, iValue); }; // Extract a month number from the string value @@ -43390,8 +47566,8 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { // Confirm that a literal character matches the string value var checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { - throw (_$main_388.local.unexpectedLiteralAt || - _$main_388.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue); + throw (_$main_450.local.unexpectedLiteralAt || + _$main_450.regionalOptions[''].unexpectedLiteralAt).replace(/\{0\}/, iValue); } iValue++; }; @@ -43443,7 +47619,7 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { } } if (iValue < value.length) { - throw _$main_388.local.unexpectedText || _$main_388.regionalOptions[''].unexpectedText; + throw _$main_450.local.unexpectedText || _$main_450.regionalOptions[''].unexpectedText; } if (year === -1) { year = this.today().year(); @@ -43534,24 +47710,24 @@ _$objectAssign_281(_$main_388.baseCalendar.prototype, { // a trimmed down version of: // https://github.com/alexcjohnson/world-calendars/blob/master/dist/index.js -var _$calendars_408 = _$main_388; +var _$calendars_470 = _$main_450; -_$plus_389; +_$plus_451; -_$chinese_374; -_$coptic_375; -_$discworld_376; -_$ethiopian_377; -_$hebrew_378; -_$islamic_379; -_$julian_380; -_$mayan_381; -_$nanakshahi_382; -_$nepali_383; -_$persian_384; -_$taiwan_385; -_$thai_386; -_$ummalqura_387; +_$chinese_436; +_$coptic_437; +_$discworld_438; +_$ethiopian_439; +_$hebrew_440; +_$islamic_441; +_$julian_442; +_$mayan_443; +_$nanakshahi_444; +_$nepali_445; +_$persian_446; +_$taiwan_447; +_$thai_448; +_$ummalqura_449; /** * Copyright 2012-2018, Plotly, Inc. @@ -43563,17 +47739,17 @@ _$ummalqura_387; 'use strict'; -/* removed: var _$calendars_408 = require('./calendars'); */; +/* removed: var _$calendars_470 = require('./calendars'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; -var __EPOCHJD_409 = _$numerical_517.EPOCHJD; -var __ONEDAY_409 = _$numerical_517.ONEDAY; +var __EPOCHJD_471 = _$numerical_578.EPOCHJD; +var __ONEDAY_471 = _$numerical_578.ONEDAY; -var __attributes_409 = { +var __attributes_471 = { valType: 'enumerated', - values: Object.keys(_$calendars_408.calendars), + values: Object.keys(_$calendars_470.calendars), editType: 'calc', dflt: 'gregorian' @@ -43581,9 +47757,9 @@ var __attributes_409 = { var handleDefaults = function(contIn, contOut, attr, dflt) { var attrs = {}; - attrs[attr] = __attributes_409; + attrs[attr] = __attributes_471; - return _$lib_539.coerce(contIn, contOut, attrs, attr, dflt); + return _$lib_601.coerce(contIn, contOut, attrs, attr, dflt); }; var handleTraceDefaults = function(traceIn, traceOut, coords, layout) { @@ -43681,7 +47857,7 @@ var d3ToWorldCalendars = { }; function worldCalFmt(fmt, x, calendar) { - var dateJD = Math.floor((x + 0.05) / __ONEDAY_409) + __EPOCHJD_409, + var dateJD = Math.floor((x + 0.05) / __ONEDAY_471) + __EPOCHJD_471, cDate = getCal(calendar).fromJD(dateJD), i = 0, modifier, directive, directiveLen, directiveObj, replacementPart; @@ -43722,12 +47898,12 @@ function getCal(calendar) { var calendarObj = allCals[calendar]; if(calendarObj) return calendarObj; - calendarObj = allCals[calendar] = _$calendars_408.instance(calendar); + calendarObj = allCals[calendar] = _$calendars_470.instance(calendar); return calendarObj; } function makeAttrs(description) { - return _$lib_539.extendFlat({}, __attributes_409, { description: description }); + return _$lib_601.extendFlat({}, __attributes_471, { description: description }); } function makeTraceAttrsDescription(coord) { @@ -43738,11 +47914,11 @@ var xAttrs = { xcalendar: makeAttrs(makeTraceAttrsDescription('x')) }; -var xyAttrs = _$lib_539.extendFlat({}, xAttrs, { +var xyAttrs = _$lib_601.extendFlat({}, xAttrs, { ycalendar: makeAttrs(makeTraceAttrsDescription('y')) }); -var xyzAttrs = _$lib_539.extendFlat({}, xyAttrs, { +var xyzAttrs = _$lib_601.extendFlat({}, xyAttrs, { zcalendar: makeAttrs(makeTraceAttrsDescription('z')) }); @@ -43753,7 +47929,7 @@ var axisAttrs = makeAttrs([ 'or via the global `layout.calendar`' ].join(' ')); -var _$calendars_409 = { +var _$calendars_471 = { moduleType: 'component', name: 'calendars', @@ -43813,7 +47989,7 @@ var _$calendars_409 = { } }, - layoutAttributes: __attributes_409, + layoutAttributes: __attributes_471, handleDefaults: handleDefaults, handleTraceDefaults: handleTraceDefaults, @@ -43836,7 +48012,7 @@ var _$calendars_409 = { 'use strict'; -var _$calendars_6 = _$calendars_409; +var _$calendars_6 = _$calendars_471; /** * Copyright 2012-2018, Plotly, Inc. @@ -43849,43 +48025,28 @@ var _$calendars_6 = _$calendars_409; 'use strict'; -var __extendFlat_820 = _$lib_539.extendFlat; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -var __dash_820 = _$attributes_435.dash; +var __extendFlat_882 = _$lib_601.extendFlat; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +var __dash_882 = _$attributes_497.dash; var INCREASING_COLOR = '#3D9970'; var DECREASING_COLOR = '#FF4136'; -var lineAttrs = _$attributes_862.line; +var lineAttrs = _$attributes_927.line; function directionAttrs(lineColorDefault) { return { - name: { - valType: 'string', - - editType: 'style', - - }, - - showlegend: { - valType: 'boolean', - - dflt: true, - editType: 'style', - - }, - line: { - color: __extendFlat_820({}, lineAttrs.color, {dflt: lineColorDefault}), + color: __extendFlat_882({}, lineAttrs.color, {dflt: lineColorDefault}), width: lineAttrs.width, - dash: __dash_820, + dash: __dash_882, editType: 'style' }, editType: 'style' }; } -var _$attributes_820 = { +var _$attributes_882 = { x: { valType: 'data_array', @@ -43895,37 +48056,33 @@ var _$attributes_820 = { open: { valType: 'data_array', - dflt: [], editType: 'calc', }, high: { valType: 'data_array', - dflt: [], editType: 'calc', }, low: { valType: 'data_array', - dflt: [], editType: 'calc', }, close: { valType: 'data_array', - dflt: [], editType: 'calc', }, line: { - width: __extendFlat_820({}, lineAttrs.width, { + width: __extendFlat_882({}, lineAttrs.width, { }), - dash: __extendFlat_820({}, __dash_820, { + dash: __extendFlat_882({}, __dash_882, { }), editType: 'style' @@ -43966,46 +48123,43 @@ var _$attributes_820 = { 'use strict'; -var __extendFlat_702 = _$lib_539.extendFlat; -/* removed: var _$attributes_820 = require('../ohlc/attributes'); */; -/* removed: var _$attributes_691 = require('../box/attributes'); */; +var __extendFlat_765 = _$lib_601.extendFlat; +/* removed: var _$attributes_882 = require('../ohlc/attributes'); */; +/* removed: var _$attributes_754 = require('../box/attributes'); */; -function __directionAttrs_702(lineColorDefault) { +function __directionAttrs_765(lineColorDefault) { return { - name: _$attributes_820.increasing.name, - showlegend: _$attributes_820.increasing.showlegend, - line: { - color: __extendFlat_702({}, _$attributes_691.line.color, {dflt: lineColorDefault}), - width: _$attributes_691.line.width, + color: __extendFlat_765({}, _$attributes_754.line.color, {dflt: lineColorDefault}), + width: _$attributes_754.line.width, editType: 'style' }, - fillcolor: _$attributes_691.fillcolor, + fillcolor: _$attributes_754.fillcolor, editType: 'style' }; } -var _$attributes_702 = { - x: _$attributes_820.x, - open: _$attributes_820.open, - high: _$attributes_820.high, - low: _$attributes_820.low, - close: _$attributes_820.close, +var _$attributes_765 = { + x: _$attributes_882.x, + open: _$attributes_882.open, + high: _$attributes_882.high, + low: _$attributes_882.low, + close: _$attributes_882.close, line: { - width: __extendFlat_702({}, _$attributes_691.line.width, { + width: __extendFlat_765({}, _$attributes_754.line.width, { }), editType: 'style' }, - increasing: __directionAttrs_702(_$attributes_820.increasing.line.color.dflt), + increasing: __directionAttrs_765(_$attributes_882.increasing.line.color.dflt), - decreasing: __directionAttrs_702(_$attributes_820.decreasing.line.color.dflt), + decreasing: __directionAttrs_765(_$attributes_882.decreasing.line.color.dflt), - text: _$attributes_820.text, - whiskerwidth: __extendFlat_702({}, _$attributes_691.whiskerwidth, { dflt: 0 }) + text: _$attributes_882.text, + whiskerwidth: __extendFlat_765({}, _$attributes_754.whiskerwidth, { dflt: 0 }) }; /** @@ -44016,172 +48170,212 @@ var _$attributes_702 = { * LICENSE file in the root directory of this source tree. */ - 'use strict'; +/* removed: var _$lib_601 = require('../../lib'); */; +var ____883 = _$lib_601._; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __BADNUM_883 = _$numerical_578.BADNUM; + +function calc(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis); + var ya = _$axes_647.getFromId(gd, trace.yaxis); -var _$handleDirectionDefaults_822 = function handleDirectionDefaults(traceIn, traceOut, coerce, direction) { - coerce(direction + '.showlegend'); + var tickLen = convertTickWidth(gd, xa, trace); + var minDiff = trace._minDiff; + trace._minDiff = null; + var x = trace._xcalc; + trace._xcalc = null; - // trace-wide *showlegend* overrides direction *showlegend* - if(traceIn.showlegend === false) { - traceOut[direction].showlegend = false; + var cd = calcCommon(gd, trace, x, ya, ptFunc); + + _$axes_647.expand(xa, x, {vpad: minDiff / 2}); + + if(cd.length) { + _$lib_601.extendFlat(cd[0].t, { + wHover: minDiff / 2, + tickLen: tickLen + }); + return cd; + } else { + return [{t: {empty: true}}]; } +} - var nameDflt = traceOut.name + ' - ' + direction; +function ptFunc(o, h, l, c) { + return { + o: o, + h: h, + l: l, + c: c + }; +} - coerce(direction + '.name', nameDflt); -}; -var _$helpers_823 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ +// shared between OHLC and candlestick +// ptFunc makes a calcdata point specific to each trace type, from oi, hi, li, ci +function calcCommon(gd, trace, x, ya, ptFunc) { + var o = ya.makeCalcdata(trace, 'open'); + var h = ya.makeCalcdata(trace, 'high'); + var l = ya.makeCalcdata(trace, 'low'); + var c = ya.makeCalcdata(trace, 'close'); + var hasTextArray = Array.isArray(trace.text); -'use strict'; + // we're optimists - before we have any changing data, assume increasing + var increasing = true; + var cPrev = null; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; + var cd = []; + for(var i = 0; i < x.length; i++) { + var xi = x[i]; + var oi = o[i]; + var hi = h[i]; + var li = l[i]; + var ci = c[i]; -/* removed: var _$lib_539 = require('../../lib'); */; + if(xi !== __BADNUM_883 && oi !== __BADNUM_883 && hi !== __BADNUM_883 && li !== __BADNUM_883 && ci !== __BADNUM_883) { + if(ci === oi) { + // if open == close, look for a change from the previous close + if(cPrev !== null && ci !== cPrev) increasing = ci > cPrev; + // else (c === cPrev or cPrev is null) no change + } + else increasing = ci > oi; -// This routine gets called during the trace supply-defaults step. -// -// This is a hacky way to make 'ohlc' and 'candlestick' trace types -// go through the transform machinery. -// -// Note that, we must mutate user data (here traceIn) as opposed -// to full data (here traceOut) as - at the moment - transform -// defaults (which are called after trace defaults) start -// from a clear transforms container. The mutations inflicted are -// cleared in exports.clearEphemeralTransformOpts. -_$helpers_823.pushDummyTransformOpts = function(traceIn, traceOut) { - var transformOpts = { + cPrev = ci; - // give dummy transform the same type as trace - type: traceOut.type, + var pt = ptFunc(oi, hi, li, ci); - // track ephemeral transforms in user data - _ephemeral: true - }; + pt.pos = xi; + pt.yc = (oi + ci) / 2; + pt.i = i; + pt.dir = increasing ? 'increasing' : 'decreasing'; - if(Array.isArray(traceIn.transforms)) { - traceIn.transforms.push(transformOpts); - } - else { - traceIn.transforms = [transformOpts]; - } -}; + if(hasTextArray) pt.tx = trace.text[i]; -// This routine gets called during the transform supply-defaults step -// where it clears ephemeral transform opts in user data -// and effectively put back user date in its pre-supplyDefaults state. -_$helpers_823.clearEphemeralTransformOpts = function(traceIn) { - var transformsIn = traceIn.transforms; + cd.push(pt); + } + } - if(!Array.isArray(transformsIn)) return; + _$axes_647.expand(ya, l.concat(h), {padded: true}); - for(var i = 0; i < transformsIn.length; i++) { - if(transformsIn[i]._ephemeral) transformsIn.splice(i, 1); + if(cd.length) { + cd[0].t = { + labels: { + open: ____883(gd, 'open:') + ' ', + high: ____883(gd, 'high:') + ' ', + low: ____883(gd, 'low:') + ' ', + close: ____883(gd, 'close:') + ' ' + } + }; } - if(transformsIn.length === 0) delete traceIn.transforms; -}; + return cd; +} -// This routine gets called during the transform supply-defaults step -// where it passes 'ohlc' and 'candlestick' attributes -// (found the transform container via exports.makeTransform) -// to the traceOut container such that they can -// be compatible with filter and groupby transforms. -// -// Note that this routine only has an effect during the -// second round of transform defaults done on generated traces -_$helpers_823.copyOHLC = function(container, traceOut) { - if(container.open) traceOut.open = container.open; - if(container.high) traceOut.high = container.high; - if(container.low) traceOut.low = container.low; - if(container.close) traceOut.close = container.close; -}; +/* + * find min x-coordinates difference of all traces + * attached to this x-axis and stash the result in _minDiff + * in all traces; when a trace uses this in its + * calc step it deletes _minDiff, so that next calc this is + * done again in case the data changed. + * also since we need it here, stash _xcalc on the trace + */ +function convertTickWidth(gd, xa, trace) { + var minDiff = trace._minDiff; -// This routine gets called during the applyTransform step. -// -// We need to track trace attributes and which direction -// ('increasing' or 'decreasing') -// the generated correspond to for the calcTransform step. -// -// To make sure that the attributes reach the calcTransform, -// store it in the transform opts object. -_$helpers_823.makeTransform = function(traceIn, state, direction) { - var out = _$lib_539.extendFlat([], traceIn.transforms); + if(!minDiff) { + var fullData = gd._fullData, + ohlcTracesOnThisXaxis = []; - out[state.transformIndex] = { - type: traceIn.type, - direction: direction, + minDiff = Infinity; - // these are copied to traceOut during exports.copyOHLC - open: traceIn.open, - high: traceIn.high, - low: traceIn.low, - close: traceIn.close - }; + var i; - return out; -}; + for(i = 0; i < fullData.length; i++) { + var tracei = fullData[i]; -_$helpers_823.getFilterFn = function(direction) { - return new _getFilterFn(direction); -}; + if(tracei.type === 'ohlc' && + tracei.visible === true && + tracei.xaxis === xa._id + ) { + ohlcTracesOnThisXaxis.push(tracei); -function _getFilterFn(direction) { - // we're optimists - before we have any changing data, assume increasing - var isPrevIncreasing = true; - var cPrev = null; + var xcalc = xa.makeCalcdata(tracei, 'x'); + tracei._xcalc = xcalc; - function _isIncreasing(o, c) { - if(o === c) { - if(c > cPrev) { - isPrevIncreasing = true; // increasing - } else if(c < cPrev) { - isPrevIncreasing = false; // decreasing + var _minDiff = _$lib_601.distinctVals(xcalc).minDiff; + if(_minDiff && isFinite(_minDiff)) { + minDiff = Math.min(minDiff, _minDiff); + } } - // else isPrevIncreasing is not changed } - else isPrevIncreasing = (o < c); - cPrev = c; - return isPrevIncreasing; - } - function isIncreasing(o, c) { - return _$fastIsnumeric_139(o) && _$fastIsnumeric_139(c) && _isIncreasing(+o, +c); - } + // if minDiff is still Infinity here, set it to 1 + if(minDiff === Infinity) minDiff = 1; - function isDecreasing(o, c) { - return _$fastIsnumeric_139(o) && _$fastIsnumeric_139(c) && !_isIncreasing(+o, +c); + for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) { + ohlcTracesOnThisXaxis[i]._minDiff = minDiff; + } } - return direction === 'increasing' ? isIncreasing : isDecreasing; + return minDiff * trace.tickwidth; } -_$helpers_823.addRangeSlider = function(data, layout) { - var hasOneVisibleTrace = false; +var _$calc_883 = { + calc: calc, + calcCommon: calcCommon +}; - for(var i = 0; i < data.length; i++) { - if(data[i].visible === true) { - hasOneVisibleTrace = true; - break; - } - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; + +var __calcCommon_766 = _$calc_883.calcCommon; + +var _$calc_766 = function(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axes_647.getFromId(gd, trace.xaxis); + var ya = _$axes_647.getFromId(gd, trace.yaxis); + + var x = xa.makeCalcdata(trace, 'x'); + + var cd = __calcCommon_766(gd, trace, x, ya, __ptFunc_766); - if(hasOneVisibleTrace) { - if(!layout.xaxis) layout.xaxis = {}; - if(!layout.xaxis.rangeslider) layout.xaxis.rangeslider = {}; + if(cd.length) { + _$lib_601.extendFlat(cd[0].t, { + num: fullLayout._numBoxes, + dPos: _$lib_601.distinctVals(x).minDiff / 2, + posLetter: 'x', + valLetter: 'y', + }); + + fullLayout._numBoxes++; + return cd; + } else { + return [{t: {empty: true}}]; } }; +function __ptFunc_766(o, h, l, c) { + return { + min: l, + q1: Math.min(o, c), + med: c, + q3: Math.max(o, c), + max: h, + }; +} + /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44193,32 +48387,26 @@ _$helpers_823.addRangeSlider = function(data, layout) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$handleOHLC_825 = function handleOHLC(traceIn, traceOut, coerce, layout) { - var len; - - var x = coerce('x'), - open = coerce('open'), - high = coerce('high'), - low = coerce('low'), - close = coerce('close'); +var _$handleOHLC_887 = 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'); - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x'], layout); - len = Math.min(open.length, high.length, low.length, close.length); + if(!(open && high && low && close)) return; - if(x) { - len = Math.min(len, x.length); - if(len < x.length) traceOut.x = x.slice(0, len); - } + var len = Math.min(open.length, high.length, low.length, close.length); + + if(x) len = Math.min(len, x.length); - if(len < open.length) traceOut.open = open.slice(0, len); - if(len < high.length) traceOut.high = high.slice(0, len); - if(len < low.length) traceOut.low = low.slice(0, len); - if(len < close.length) traceOut.close = close.slice(0, len); + traceOut._length = len; return len; }; @@ -44234,21 +48422,18 @@ var _$handleOHLC_825 = function handleOHLC(traceIn, traceOut, coerce, layout) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleOHLC_825 = require('../ohlc/ohlc_defaults'); */; -/* removed: var _$handleDirectionDefaults_822 = require('../ohlc/direction_defaults'); */; -/* removed: var _$helpers_823 = require('../ohlc/helpers'); */; -/* removed: var _$attributes_702 = require('./attributes'); */; - -var _$supplyDefaults_703 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - _$helpers_823.pushDummyTransformOpts(traceIn, traceOut); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$handleOHLC_887 = require('../ohlc/ohlc_defaults'); */; +/* removed: var _$attributes_765 = require('./attributes'); */; +var _$supplyDefaults_767 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_702, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_765, attr, dflt); } - var len = _$handleOHLC_825(traceIn, traceOut, coerce, layout); - if(len === 0) { + var len = _$handleOHLC_887(traceIn, traceOut, coerce, layout); + if(!len) { traceOut.visible = false; return; } @@ -44260,17 +48445,16 @@ var _$supplyDefaults_703 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('whiskerwidth'); + + layout._requestRangeslider[traceOut.xaxis] = true; }; function handleDirection(traceIn, traceOut, coerce, direction) { - _$handleDirectionDefaults_822(traceIn, traceOut, coerce, direction); - - coerce(direction + '.line.color'); + var lineColor = coerce(direction + '.line.color'); coerce(direction + '.line.width', traceOut.line.width); - coerce(direction + '.fillcolor'); + coerce(direction + '.fillcolor', _$color_473.addOpacity(lineColor, 0.5)); } -var _$transform_705 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44279,125 +48463,150 @@ var _$transform_705 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$helpers_823 = require('../ohlc/helpers'); */; - -_$transform_705.moduleType = 'transform'; - -_$transform_705.name = 'candlestick'; - -_$transform_705.attributes = {}; - -_$transform_705.supplyDefaults = function(transformIn, traceOut, layout, traceIn) { - _$helpers_823.clearEphemeralTransformOpts(traceIn); - _$helpers_823.copyOHLC(transformIn, traceOut); - - return transformIn; +var DIRSYMBOL = { + increasing: '▲', + decreasing: '▼' }; -_$transform_705.transform = function transform(dataIn, state) { - var dataOut = []; +var _$hoverPoints_885 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var xa = pointData.xa; + var ya = pointData.ya; + var trace = cd[0].trace; + var t = cd[0].t; - for(var i = 0; i < dataIn.length; i++) { - var traceIn = dataIn[i]; + var type = trace.type; + var minAttr = type === 'ohlc' ? 'l' : 'min'; + var maxAttr = type === 'ohlc' ? 'h' : 'max'; - if(traceIn.type !== 'candlestick') { - dataOut.push(traceIn); - continue; - } + // potentially shift xval for grouped candlesticks + var centerShift = t.bPos || 0; + var x0 = xval - centerShift; - dataOut.push( - makeTrace(traceIn, state, 'increasing'), - makeTrace(traceIn, state, 'decreasing') - ); - } + // ohlc and candlestick call displayHalfWidth different things... + var displayHalfWidth = t.bdPos || t.tickLen; + var hoverHalfWidth = t.wHover; - _$helpers_823.addRangeSlider(dataOut, state.layout); + // if two items are overlaying, let the narrowest one win + var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0]))); + var hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; + var spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; - return dataOut; -}; + function dx(di) { + var pos = di.pos - x0; + return _$fx_515.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance); + } -function makeTrace(traceIn, state, direction) { - var traceOut = { - type: 'box', - boxpoints: false, + function dy(di) { + return _$fx_515.inbox(di[minAttr] - yval, di[maxAttr] - yval, hoverPseudoDistance); + } - visible: traceIn.visible, - hoverinfo: traceIn.hoverinfo, - opacity: traceIn.opacity, - xaxis: traceIn.xaxis, - yaxis: traceIn.yaxis, + function dxy(di) { return (dx(di) + dy(di)) / 2; } + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); + _$fx_515.getClosest(cd, distfn, pointData); - transforms: _$helpers_823.makeTransform(traceIn, state, direction) - }; + // skip the rest (for this trace) if we didn't find a close point + if(pointData.index === false) return []; - // the rest of below may not have been coerced + // we don't make a calcdata point if we're missing any piece (x/o/h/l/c) + // so we need to fix the index here to point to the data arrays + var cdIndex = pointData.index; + var di = cd[cdIndex]; + var i = pointData.index = di.i; - var directionOpts = traceIn[direction]; + var dir = di.dir; + var container = trace[dir]; + var lc = container.line.color; - if(directionOpts) { - _$lib_539.extendFlat(traceOut, { + if(_$color_473.opacity(lc) && container.line.width) pointData.color = lc; + else pointData.color = container.fillcolor; - // to make autotype catch date axes soon!! - x: traceIn.x || [0], - xcalendar: traceIn.xcalendar, + pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true); + pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true); - // concat low and high to get correct autorange - y: [].concat(traceIn.low).concat(traceIn.high), + pointData.xLabelVal = di.pos; - whiskerwidth: traceIn.whiskerwidth, - text: traceIn.text, + pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; + pointData.xSpike = xa.c2p(di.pos, true); - name: directionOpts.name, - showlegend: directionOpts.showlegend, - line: directionOpts.line, - fillcolor: directionOpts.fillcolor - }); + function getLabelLine(attr) { + return t.labels[attr] + _$axes_647.hoverLabelText(ya, trace[attr][i]); } - return traceOut; -} + var hoverinfo = trace.hoverinfo; + var hoverParts = hoverinfo.split('+'); + var isAll = hoverinfo === 'all'; + var hasY = isAll || hoverParts.indexOf('y') !== -1; + var hasText = isAll || hoverParts.indexOf('text') !== -1; + + var textParts = hasY ? [ + getLabelLine('open'), + getLabelLine('high'), + getLabelLine('low'), + getLabelLine('close') + ' ' + DIRSYMBOL[dir] + ] : []; + if(hasText) _$fillHoverText_935(di, trace, textParts); + + // don't make .yLabelVal or .text, since we're managing hoverinfo + // put it all in .extraText + pointData.extraText = textParts.join('
'); + + // this puts the label *and the spike* at the midpoint of the box, ie + // halfway between open and close, not between high and low. + pointData.y0 = pointData.y1 = ya.c2p(di.yc, true); -_$transform_705.calcTransform = function calcTransform(gd, trace, opts) { - var direction = opts.direction, - filterFn = _$helpers_823.getFilterFn(direction); + return [pointData]; +}; - var open = trace.open, - high = trace.high, - low = trace.low, - close = trace.close; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 len = open.length, - x = [], - y = []; +'use strict'; - var appendX = trace._fullInput.x ? - function(i) { - var v = trace.x[i]; - x.push(v, v, v, v, v, v); - } : - function(i) { - x.push(i, i, i, i, i, i); - }; +var _$selectPoints_889 = function selectPoints(searchInfo, polygon) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + // for (potentially grouped) candlesticks + var posOffset = cd[0].t.bPos || 0; - var appendY = function(o, h, l, c) { - y.push(l, o, c, c, c, h); - }; + if(polygon === 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]; - for(var i = 0; i < len; i++) { - if(filterFn(open[i], close[i]) && _$fastIsnumeric_139(high[i]) && _$fastIsnumeric_139(low[i])) { - appendX(i); - appendY(open[i], high[i], low[i], close[i]); + if(polygon.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)])) { + selection.push({ + pointNumber: di.i, + x: xa.c2d(di.pos), + y: ya.c2d(di.yc) + }); + di.selected = 1; + } else { + di.selected = 0; + } } } - trace.x = x; - trace.y = y; + return selection; }; /** @@ -44410,24 +48619,27 @@ _$transform_705.calcTransform = function calcTransform(gd, trace, opts) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - -var _$candlestick_704 = { +var _$candlestick_768 = { moduleType: 'trace', name: 'candlestick', - basePlotModule: _$cartesian_595, - categories: ['cartesian', 'showLegend', 'candlestick'], + basePlotModule: _$cartesian_658, + categories: ['cartesian', 'svg', 'showLegend', 'candlestick', 'boxLayout'], meta: { }, - attributes: _$attributes_702, - supplyDefaults: _$supplyDefaults_703, + attributes: _$attributes_765, + layoutAttributes: _$layout_attributes_759, + supplyLayoutDefaults: _$layout_defaults_760.supplyLayoutDefaults, + setPositions: _$set_positions_763.setPositions, + supplyDefaults: _$supplyDefaults_767, + calc: _$calc_766, + plot: _$plot_761.plot, + style: _$style_764, + hoverPoints: _$hoverPoints_885, + selectPoints: _$selectPoints_889 }; -_$registry_668.register(_$Box_695); -_$registry_668.register(_$transform_705); - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -44438,7 +48650,7 @@ _$registry_668.register(_$transform_705); 'use strict'; -var _$candlestick_7 = _$candlestick_704; +var _$candlestick_7 = _$candlestick_768; /** * Copyright 2012-2018, Plotly, Inc. @@ -44450,12 +48662,12 @@ var _$candlestick_7 = _$candlestick_704; 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; -var __overrideAll_710 = _$edit_types_569.overrideAll; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; +var __overrideAll_773 = _$edit_types_632.overrideAll; -var _$axis_attributes_710 = { +var _$axis_attributes_773 = { color: { valType: 'color', @@ -44476,7 +48688,7 @@ var _$axis_attributes_710 = { editType: 'calc', }, - titlefont: _$font_attributes_611({ + titlefont: _$font_attributes_673({ editType: 'calc', }), @@ -44572,7 +48784,7 @@ var _$axis_attributes_710 = { editType: 'calc', }, - tickfont: _$font_attributes_611({ + tickfont: _$font_attributes_673({ editType: 'calc', }), @@ -44643,7 +48855,7 @@ var _$axis_attributes_710 = { editType: 'calc', }, - tickformatstops: __overrideAll_710(_$layout_attributes_596.tickformatstops, 'calc', 'from-root'), + tickformatstops: __overrideAll_773(_$layout_attributes_659.tickformatstops, 'calc', 'from-root'), categoryorder: { valType: 'enumerated', values: [ @@ -44691,7 +48903,7 @@ var _$axis_attributes_710 = { }, linecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'calc', @@ -44743,7 +48955,7 @@ var _$axis_attributes_710 = { }, minorgridcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, editType: 'calc', @@ -44831,20 +49043,20 @@ var _$axis_attributes_710 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$axis_attributes_710 = require('./axis_attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$axis_attributes_773 = require('./axis_attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; -var carpetFont = _$font_attributes_611({ +var carpetFont = _$font_attributes_673({ editType: 'calc', }); // TODO: inherit from global font carpetFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; carpetFont.size.dflt = 12; -carpetFont.color.dflt = _$attributes_410.defaultLine; +carpetFont.color.dflt = _$attributes_472.defaultLine; -var _$attributes_708 = { +var _$attributes_771 = { carpet: { valType: 'string', @@ -44906,12 +49118,12 @@ var _$attributes_708 = { editType: 'calc', }, - aaxis: _$axis_attributes_710, - baxis: _$axis_attributes_710, + aaxis: _$axis_attributes_773, + baxis: _$axis_attributes_773, font: carpetFont, color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'plot', @@ -44928,9 +49140,9 @@ var _$attributes_708 = { 'use strict'; -var __isArrayOrTypedArray_707 = _$lib_539.isArrayOrTypedArray; +var __isArrayOrTypedArray_770 = _$lib_601.isArrayOrTypedArray; -var _$array_minmax_707 = function(a) { +var _$array_minmax_770 = function(a) { return minMax(a, 0); }; @@ -44938,7 +49150,7 @@ 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_707(a) || depth >= 10) { + if(!__isArrayOrTypedArray_770(a) || depth >= 10) { return null; } @@ -44948,7 +49160,7 @@ function minMax(a, depth) { for(var i = 0; i < n; i++) { var datum = a[i]; - if(__isArrayOrTypedArray_707(datum)) { + if(__isArrayOrTypedArray_770(datum)) { var result = minMax(datum, depth + 1); if(result) { @@ -44975,7 +49187,7 @@ function minMax(a, depth) { 'use strict'; -var _$makeClipPath_713 = function makeClipPath(xctrl, yctrl, aax, bax) { +var _$makeClipPath_776 = function makeClipPath(xctrl, yctrl, aax, bax) { var i, x, y; var segments = []; @@ -45025,36 +49237,36 @@ var _$makeClipPath_713 = function makeClipPath(xctrl, yctrl, aax, bax) { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __extendFlat_714 = _$extend_528.extendFlat; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __extendFlat_777 = _$extend_590.extendFlat; -var _$calcGridlines_714 = function calcGridlines(trace, cd, axisLetter, crossAxisLetter) { +var _$calcGridlines_777 = 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 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 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 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; + var na = trace._a.length; + var nb = trace._b.length; - _$axes_584.prepTicks(axis); + _$axes_647.prepTicks(axis); // don't leave tickvals in axis looking like an attribute if(axis.tickmode === 'array') delete axis.tickvals; @@ -45248,7 +49460,7 @@ var _$calcGridlines_714 = function calcGridlines(trace, cd, axisLetter, crossAxi for(n = n1; n < n2; n++) { j = axis.arraytick0 + axis.arraydtick * n; if(j < 0 || j > data.length - 1) continue; - gridlines.push(__extendFlat_714(constructArrayGridline(j), { + gridlines.push(__extendFlat_777(constructArrayGridline(j), { color: axis.gridcolor, width: axis.gridwidth })); @@ -45267,861 +49479,155 @@ var _$calcGridlines_714 = function calcGridlines(trace, cd, axisLetter, crossAxi 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_714(constructValueGridline(v), { - color: axis.minorgridcolor, - width: axis.minorgridwidth - })); - } - } - - if(axis.startline) { - boundarylines.push(__extendFlat_714(constructArrayGridline(0), { - color: axis.startlinecolor, - width: axis.startlinewidth - })); - } - - if(axis.endline) { - boundarylines.push(__extendFlat_714(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_714(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_714(constructValueGridline(v), { - color: axis.minorgridcolor, - width: axis.minorgridwidth - })); - } - } - - if(axis.startline) { - boundarylines.push(__extendFlat_714(constructValueGridline(data[0]), { - color: axis.startlinecolor, - width: axis.startlinewidth - })); - } - - if(axis.endline) { - boundarylines.push(__extendFlat_714(constructValueGridline(data[data.length - 1]), { - color: axis.endlinecolor, - width: axis.endlinewidth - })); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __extendFlat_715 = _$extend_528.extendFlat; - -var _$calcLabels_715 = function calcLabels(trace, axis) { - var i, tobj, prefix, suffix, gridline; - - var labels = axis._labels = []; - var gridlines = axis._gridlines; - - for(i = 0; i < gridlines.length; i++) { - gridline = gridlines[i]; - - if(['start', 'both'].indexOf(axis.showticklabels) !== -1) { - tobj = _$axes_584.tickText(axis, gridline.value); - - __extendFlat_715(tobj, { - prefix: prefix, - suffix: suffix, - endAnchor: true, - xy: gridline.xy(0), - dxy: gridline.dxy(0, 0), - axis: gridline.axis, - length: gridline.crossAxis.length, - font: gridline.axis.tickfont, - isFirst: i === 0, - isLast: i === gridlines.length - 1 - }); - - labels.push(tobj); - } - - if(['end', 'both'].indexOf(axis.showticklabels) !== -1) { - tobj = _$axes_584.tickText(axis, gridline.value); - - __extendFlat_715(tobj, { - endAnchor: false, - xy: gridline.xy(gridline.crossLength - 1), - dxy: gridline.dxy(gridline.crossLength - 2, 1), - axis: gridline.axis, - length: gridline.crossAxis.length, - font: gridline.axis.tickfont, - isFirst: i === 0, - isLast: i === gridlines.length - 1 - }); - - labels.push(tobj); - } - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_717 = _$lib_539.isArrayOrTypedArray; - -/* - * Construct a 2D array of cheater values given a, b, and a slope. - * If - */ -var _$cheater_basis_717 = function(a, b, cheaterslope) { - var i, j, ascal, bscal, aval, bval; - var data = []; - - var na = __isArrayOrTypedArray_717(a) ? a.length : a; - var nb = __isArrayOrTypedArray_717(b) ? b.length : b; - var adata = __isArrayOrTypedArray_717(a) ? a : null; - var bdata = __isArrayOrTypedArray_717(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; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_729 = _$lib_539.isArrayOrTypedArray; - -/* - * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p). - * The output array is optional, but if provided, it will be reused without - * reallocation to the extent possible. - */ -var _$mapArray_729 = function mapArray(out, data, func) { - var i, j; - - if(!Array.isArray(out)) { - // If not an array, make it an array: - out = []; - } else if(out.length > data.length) { - // If too long, truncate. (If too short, it will grow - // automatically so we don't care about that case) - out = out.slice(0, data.length); - } - - for(i = 0; i < data.length; i++) { - if(!__isArrayOrTypedArray_729(out[i])) { - // If not an array, make it an array: - out[i] = []; - } else if(out[i].length > data.length) { - // If too long, truncate. (If too short, it will grow - // automatically so we don't care about[i] that case) - out[i] = out[i].slice(0, data.length); - } - - for(j = 0; j < data[0].length; j++) { - out[i][j] = func(data[i][j]); - } - } - return out; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; - -/* - * 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 - */ -var _$smoothFill2dArray_733 = 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_539.log('Smoother converged to', resid, 'after', iter, 'iterations'); - - return data; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; - -var _$clean2dArray_775 = function clean2dArray(zOld, transpose) { - var rowlen, collen, getCollen, old2new, i, j; - - function cleanZvalue(v) { - if(!_$fastIsnumeric_139(v)) return undefined; - return +v; - } - - if(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 zNew = new Array(rowlen); - - for(i = 0; i < rowlen; i++) { - collen = getCollen(zOld, i); - zNew[i] = new Array(collen); - for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); - } - - return zNew; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$cheater_basis_717 = require('./cheater_basis'); */; -/* removed: var _$array_minmax_707 = require('./array_minmax'); */; -/* removed: var _$mapArray_729 = require('./map_2d_array'); */; -/* removed: var _$calcGridlines_714 = require('./calc_gridlines'); */; -/* removed: var _$calcLabels_715 = require('./calc_labels'); */; -/* removed: var _$makeClipPath_713 = require('./calc_clippath'); */; -/* removed: var _$clean2dArray_775 = require('../heatmap/clean_2d_array'); */; -/* removed: var _$smoothFill2dArray_733 = require('./smooth_fill_2d_array'); */; - -var _$calc_712 = function calc(gd, trace) { - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); - var aax = trace.aaxis; - var bax = trace.baxis; - var a = trace._a = trace.a; - var b = trace._b = trace.b; - - var t = {}; - var x; - var y = trace.y; - - if(trace._cheater) { - var avals = aax.cheatertype === 'index' ? a.length : a; - var bvals = bax.cheatertype === 'index' ? b.length : b; - x = _$cheater_basis_717(avals, bvals, trace.cheaterslope); - } else { - x = trace.x; - } - - trace._x = x = _$clean2dArray_775(x); - trace._y = y = _$clean2dArray_775(y); - - // Fill in any undefined values with elliptic smoothing. This doesn't take - // into account the spacing of the values. That is, the derivatives should - // be modified to use a and b values. It's not that hard, but this is already - // moderate overkill for just filling in missing values. - _$smoothFill2dArray_733(x, a, b); - _$smoothFill2dArray_733(y, a, b); - - // create conversion functions that depend on the data - trace.setScale(); - - // Convert cartesian-space x/y coordinates to screen space pixel coordinates: - t.xp = trace.xp = _$mapArray_729(trace.xp, x, xa.c2p); - t.yp = trace.yp = _$mapArray_729(trace.yp, y, ya.c2p); - - // This is a rather expensive scan. Nothing guarantees monotonicity, - // so we need to scan through all data to get proper ranges: - var xrange = _$array_minmax_707(x); - var yrange = _$array_minmax_707(y); - - var dx = 0.5 * (xrange[1] - xrange[0]); - var xc = 0.5 * (xrange[1] + xrange[0]); - - var dy = 0.5 * (yrange[1] - yrange[0]); - var yc = 0.5 * (yrange[1] + yrange[0]); - - // Expand the axes to fit the plot, except just grow it by a factor of 1.3 - // because the labels should be taken into account except that's difficult - // hence 1.3. - var grow = 1.3; - xrange = [xc - dx * grow, xc + dx * grow]; - yrange = [yc - dy * grow, yc + dy * grow]; - - _$axes_584.expand(xa, xrange, {padded: true}); - _$axes_584.expand(ya, yrange, {padded: true}); - - // Enumerate the gridlines, both major and minor, and store them on the trace - // object: - _$calcGridlines_714(trace, t, 'a', 'b'); - _$calcGridlines_714(trace, t, 'b', 'a'); - - // Calculate the text labels for each major gridline and store them on the - // trace object: - _$calcLabels_715(trace, aax); - _$calcLabels_715(trace, bax); - - // Tabulate points for the four segments that bound the axes so that we can - // map to pixel coordinates in the plot function and create a clip rect: - t.clipsegments = _$makeClipPath_713(trace.xctrl, trace.yctrl, aax, bax); - - t.x = x; - t.y = y; - t.a = a; - t.b = b; - - return [t]; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_708 = require('./attributes'); */; - -var addOpacity = _$color_411.addOpacity; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleTickValueDefaults_606 = require('../../plots/cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../../plots/cartesian/tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_588 = require('../../plots/cartesian/category_order_defaults'); */; -/* removed: var _$setConvert_603 = require('../../plots/cartesian/set_convert'); */; -/* removed: var _$orderedCategories_599 = require('../../plots/cartesian/ordered_categories'); */; -/* removed: var _$autoType_585 = require('../../plots/cartesian/axis_autotype'); */; - -/** - * options: object containing: - * - * letter: 'x' or 'y' - * title: name of the axis (ie 'Colorbar') to go in default title - * name: axis object name (ie 'xaxis') if one should be stored - * font: the default font to inherit - * outerTicks: boolean, should ticks default to outside? - * showGrid: boolean, should gridlines be shown by default? - * data: the plot data to use in choosing auto type - * bgColor: the plot background color, to calculate default gridline colors - */ -var _$handleAxisDefaults_711 = function handleAxisDefaults(containerIn, containerOut, options) { - var letter = options.letter, - font = options.font || {}, - attributes = _$attributes_708[letter + 'axis']; - - function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, attributes, attr, dflt); - } - - function coerce2(attr, dflt) { - return _$lib_539.coerce2(containerIn, containerOut, attributes, attr, dflt); - } - - // set up some private properties - if(options.name) { - containerOut._name = options.name; - containerOut._id = options.name; - } - - // now figure out type and do some more initialization - var axType = coerce('type'); - if(axType === '-') { - if(options.data) __setAutoType_711(containerOut, options.data); - - if(containerOut.type === '-') { - containerOut.type = 'linear'; - } - else { - // copy autoType back to input axis - // note that if this object didn't exist - // in the input layout, we have to put it in - // this happens in the main supplyDefaults function - axType = containerIn.type = containerOut.type; - } - } - - coerce('smoothing'); - coerce('cheatertype'); - - coerce('showticklabels'); - coerce('labelprefix', letter + ' = '); - coerce('labelsuffix'); - coerce('showtickprefix'); - coerce('showticksuffix'); - - coerce('separatethousands'); - coerce('tickformat'); - coerce('exponentformat'); - coerce('showexponent'); - coerce('categoryorder'); - - coerce('tickmode'); - coerce('tickvals'); - coerce('ticktext'); - coerce('tick0'); - coerce('dtick'); - - if(containerOut.tickmode === 'array') { - coerce('arraytick0'); - coerce('arraydtick'); - } - - coerce('labelpadding'); - - containerOut._hovertitle = letter; - - - if(axType === 'date') { - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleDefaults'); - handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); - } - - _$setConvert_603(containerOut, options.fullLayout); - - var dfltColor = coerce('color', options.dfltColor); - // if axis.color was provided, use it for fonts too; otherwise, - // inherit from global font color in case that was provided. - var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; - - coerce('title'); - _$lib_539.coerceFont(coerce, 'titlefont', { - family: font.family, - size: Math.round(font.size * 1.2), - color: dfltFontColor - }); - - coerce('titleoffset'); - - coerce('tickangle'); + d = j1 - j0; - var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); + // 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; - if(autoRange) coerce('rangemode'); + // XXX: This calculation isn't quite right. Off by one somewhere? + v = v0 + (v1 - v0) * (i + 1) / (axis.minorgridcount + 1) * (axis.arraydtick / d); - coerce('range'); - containerOut.cleanRange(); + // 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_777(constructValueGridline(v), { + color: axis.minorgridcolor, + width: axis.minorgridwidth + })); + } + } - coerce('fixedrange'); + if(axis.startline) { + boundarylines.push(__extendFlat_777(constructArrayGridline(0), { + color: axis.startlinecolor, + width: axis.startlinewidth + })); + } - _$handleTickValueDefaults_606(containerIn, containerOut, coerce, axType); - _$handleTickLabelDefaults_604(containerIn, containerOut, coerce, axType, options); - _$handleCategoryOrderDefaults_588(containerIn, containerOut, coerce); + if(axis.endline) { + boundarylines.push(__extendFlat_777(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. - var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3)); - var gridWidth = coerce2('gridwidth'); - var showGrid = coerce('showgrid'); + // 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;}); - if(!showGrid) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - } + // Unpack sorted values so we can be sure to avoid infinite loops if something + // is backwards: + n1 = bounds[0]; + n2 = bounds[1]; - var startLineColor = coerce2('startlinecolor', dfltColor); - var startLineWidth = coerce2('startlinewidth', gridWidth); - var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth); + for(n = n1; n <= n2; n++) { + value = axis.tick0 + axis.dtick * n; - if(!showStartLine) { - delete containerOut.startlinecolor; - delete containerOut.startlinewidth; - } + gridlines.push(__extendFlat_777(constructValueGridline(value), { + color: axis.gridcolor, + width: axis.gridwidth + })); + } - var endLineColor = coerce2('endlinecolor', dfltColor); - var endLineWidth = coerce2('endlinewidth', gridWidth); - var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth); + for(n = n1 - 1; n < n2 + 1; n++) { + value = axis.tick0 + axis.dtick * n; - if(!showEndLine) { - delete containerOut.endlinecolor; - delete containerOut.endlinewidth; - } + 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_777(constructValueGridline(v), { + color: axis.minorgridcolor, + width: axis.minorgridwidth + })); + } + } - if(!showGrid) { - delete containerOut.gridcolor; - delete containerOut.gridWidth; - } else { - coerce('minorgridcount'); - coerce('minorgridwidth', gridWidth); - coerce('minorgridcolor', addOpacity(gridColor, 0.06)); + if(axis.startline) { + boundarylines.push(__extendFlat_777(constructValueGridline(data[0]), { + color: axis.startlinecolor, + width: axis.startlinewidth + })); + } - if(!containerOut.minorgridcount) { - delete containerOut.minorgridwidth; - delete containerOut.minorgridcolor; + if(axis.endline) { + boundarylines.push(__extendFlat_777(constructValueGridline(data[data.length - 1]), { + color: axis.endlinecolor, + width: axis.endlinewidth + })); } } +}; - // fill in categories - containerOut._initialCategories = axType === 'category' ? - _$orderedCategories_599(letter, containerOut.categoryorder, containerOut.categoryarray, options.data) : - []; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(containerOut.showticklabels === 'none') { - delete containerOut.tickfont; - delete containerOut.tickangle; - delete containerOut.showexponent; - delete containerOut.exponentformat; - delete containerOut.tickformat; - delete containerOut.showticksuffix; - delete containerOut.showtickprefix; - } +'use strict'; - if(!containerOut.showticksuffix) { - delete containerOut.ticksuffix; - } +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __extendFlat_778 = _$extend_590.extendFlat; - if(!containerOut.showtickprefix) { - delete containerOut.tickprefix; - } +var _$calcLabels_778 = function calcLabels(trace, axis) { + var i, tobj, prefix, suffix, gridline; - // It needs to be coerced, then something above overrides this deep in the axis code, - // but no, we *actually* want to coerce this. - coerce('tickmode'); + var labels = axis._labels = []; + var gridlines = axis._gridlines; - if(!containerOut.title || (containerOut.title && containerOut.title.length === 0)) { - delete containerOut.titlefont; - delete containerOut.titleoffset; - } + for(i = 0; i < gridlines.length; i++) { + gridline = gridlines[i]; - return containerOut; -}; + if(['start', 'both'].indexOf(axis.showticklabels) !== -1) { + tobj = _$axes_647.tickText(axis, gridline.value); -function __setAutoType_711(ax, data) { - // new logic: let people specify any type they want, - // only autotype if type is '-' - if(ax.type !== '-') return; + __extendFlat_778(tobj, { + prefix: prefix, + suffix: suffix, + endAnchor: true, + xy: gridline.xy(0), + dxy: gridline.dxy(0, 0), + axis: gridline.axis, + length: gridline.crossAxis.length, + font: gridline.axis.tickfont, + isFirst: i === 0, + isLast: i === gridlines.length - 1 + }); - var id = ax._id, - axLetter = id.charAt(0); + labels.push(tobj); + } - var calAttr = axLetter + 'calendar', - calendar = ax[calAttr]; + if(['end', 'both'].indexOf(axis.showticklabels) !== -1) { + tobj = _$axes_647.tickText(axis, gridline.value); - ax.type = _$autoType_585(data, calendar); -} + __extendFlat_778(tobj, { + endAnchor: false, + xy: gridline.xy(gridline.crossLength - 1), + dxy: gridline.dxy(gridline.crossLength - 2, 1), + axis: gridline.axis, + length: gridline.crossAxis.length, + font: gridline.axis.tickfont, + isFirst: i === 0, + isLast: i === gridlines.length - 1 + }); + + labels.push(tobj); + } + } +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -46133,62 +49639,78 @@ function __setAutoType_711(ax, data) { 'use strict'; -/* removed: var _$handleAxisDefaults_711 = require('./axis_defaults'); */; +var __isArrayOrTypedArray_780 = _$lib_601.isArrayOrTypedArray; -var _$handleABDefaults_706 = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) { - var a = coerce('a'); +/* + * Construct a 2D array of cheater values given a, b, and a slope. + * If + */ +var _$cheater_basis_780 = function(a, b, cheaterslope) { + var i, j, ascal, bscal, aval, bval; + var data = []; - if(!a) { - coerce('da'); - coerce('a0'); + var na = __isArrayOrTypedArray_780(a) ? a.length : a; + var nb = __isArrayOrTypedArray_780(b) ? b.length : b; + var adata = __isArrayOrTypedArray_780(a) ? a : null; + var bdata = __isArrayOrTypedArray_780(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); } - var b = coerce('b'); + if(bdata) { + bscal = (bdata.length - 1) / (bdata[bdata.length - 1] - bdata[0]) / (nb - 1); + } - if(!b) { - coerce('db'); - coerce('b0'); + 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; + } } - mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor); + // 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; + return data; }; -function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) { - var axesList = ['aaxis', 'baxis']; - - axesList.forEach(function(axName) { - var axLetter = axName.charAt(0); - var axIn = traceIn[axName] || {}; - var axOut = {}; - - var defaultOptions = { - tickfont: 'x', - id: axLetter + 'axis', - letter: axLetter, - font: traceOut.font, - name: axName, - data: traceIn[axLetter], - calendar: traceOut.calendar, - dfltColor: dfltColor, - bgColor: fullLayout.paper_bgcolor, - fullLayout: fullLayout - }; - - _$handleAxisDefaults_711(axIn, axOut, defaultOptions); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - axOut._categories = axOut._categories || []; +'use strict'; - traceOut[axName] = axOut; +var __isArrayOrTypedArray_787 = _$lib_601.isArrayOrTypedArray; - // so we don't have to repeat autotype unnecessarily, - // copy an autotype back to traceIn - if(!traceIn[axName] && axIn.type !== '-') { - traceIn[axName] = {type: axIn.type}; - } - }); -} +var _$has_columns_787 = function(data) { + return __isArrayOrTypedArray_787(data[0]); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -46210,14 +49732,14 @@ function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) { * to make a nice grid, we'll need to divide the tangent by 2 instead of 3. (The * math works out this way if you work through the bezier derivatives) */ -var __CatmullRomExp_716 = 0.5; -var _$makeControlPoints_716 = function makeControlPoints(p0, p1, p2, smoothness) { +var __CatmullRomExp_779 = 0.5; +var _$makeControlPoints_779 = function makeControlPoints(p0, p1, p2, smoothness) { var d1x = p0[0] - p1[0], d1y = p0[1] - p1[1], d2x = p2[0] - p1[0], d2y = p2[1] - p1[1], - d1a = Math.pow(d1x * d1x + d1y * d1y, __CatmullRomExp_716 / 2), - d2a = Math.pow(d2x * d2x + d2y * d2y, __CatmullRomExp_716 / 2), + d1a = Math.pow(d1x * d1x + d1y * d1y, __CatmullRomExp_779 / 2), + d2a = Math.pow(d2x * d2x + d2y * d2y, __CatmullRomExp_779 / 2), numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness, numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness, denom1 = d2a * (d1a + d2a) * 3, @@ -46241,8 +49763,8 @@ var _$makeControlPoints_716 = function makeControlPoints(p0, p1, p2, smoothness) 'use strict'; -/* removed: var _$makeControlPoints_716 = require('./catmull_rom'); */; -var ensureArray = _$lib_539.ensureArray; +/* removed: var _$makeControlPoints_779 = require('./catmull_rom'); */; +var ensureArray = _$lib_601.ensureArray; /* * Turns a coarse grid into a fine grid with control points. @@ -46360,7 +49882,7 @@ function inferCubicControlPoint(p0, p2, p3) { ]; } -var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) { +var _$computeControlPoints_781 = function computeControlPoints(xe, ye, x, y, asmoothing, bsmoothing) { var i, j, ie, je, xej, yej, xj, yj, cp, p1; // At this point, we know these dimensions are correct and representative of // the whole 2D arrays: @@ -46428,7 +49950,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm for(j = 0, je = 0; j < nb; j++, je += bsmoothing ? 3 : 1) { // Fill in the points marked X for this a-row: for(i = 1, ie = 3; i < na - 1; i++, ie += 3) { - cp = _$makeControlPoints_716( + cp = _$makeControlPoints_779( [x[j][i - 1], y[j][i - 1]], [x[j][i ], y[j][i]], [x[j][i + 1], y[j][i + 1]], @@ -46487,7 +50009,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm // for(ie = 0; ie < nea; ie++) { for(je = 3; je < neb - 3; je += 3) { - cp = _$makeControlPoints_716( + cp = _$makeControlPoints_779( [xe[je - 3][ie], ye[je - 3][ie]], [xe[je][ie], ye[je][ie]], [xe[je + 3][ie], ye[je + 3][ie]], @@ -46546,7 +50068,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm for(je = 1; je < neb; je += (je + 1) % 3 === 0 ? 2 : 1) { // Fill in the points marked X for this a-row: for(ie = 3; ie < nea - 3; ie += 3) { - cp = _$makeControlPoints_716( + cp = _$makeControlPoints_779( [xe[je][ie - 3], ye[je][ie - 3]], [xe[je][ie], ye[je][ie]], [xe[je][ie + 3], ye[je][ie + 3]], @@ -46593,7 +50115,7 @@ var _$computeControlPoints_718 = function computeControlPoints(xe, ye, x, y, asm 'use strict'; -var _$constants_719 = { +var _$constants_782 = { RELATIVE_CULL_TOLERANCE: 1e-6 }; @@ -46637,7 +50159,7 @@ var _$constants_719 = { * NB: It's presumed that at this point all data has been sanitized and is valid numerical data arrays * of the correct dimension. */ -var _$create_i_derivative_evaluator_720 = function(arrays, asmoothing, bsmoothing) { +var _$create_i_derivative_evaluator_783 = function(arrays, asmoothing, bsmoothing) { if(asmoothing && bsmoothing) { return function(out, i0, j0, u, v) { if(!out) out = []; @@ -46758,7 +50280,7 @@ var _$create_i_derivative_evaluator_720 = function(arrays, asmoothing, bsmoothin 'use strict'; -var _$create_j_derivative_evaluator_721 = function(arrays, asmoothing, bsmoothing) { +var _$create_j_derivative_evaluator_784 = function(arrays, asmoothing, bsmoothing) { if(asmoothing && bsmoothing) { return function(out, i0, j0, u, v) { if(!out) out = []; @@ -46898,7 +50420,7 @@ var _$create_j_derivative_evaluator_721 = function(arrays, asmoothing, bsmoothin * to be able control whether the derivative at a cell boundary is approached * from one side or the other. */ -var _$create_spline_evaluator_722 = function(arrays, na, nb, asmoothing, bsmoothing) { +var _$create_spline_evaluator_785 = function(arrays, na, nb, asmoothing, bsmoothing) { var imax = na - 2; var jmax = nb - 2; @@ -47035,12 +50557,12 @@ var _$create_spline_evaluator_722 = function(arrays, na, nb, asmoothing, bsmooth 'use strict'; -/* removed: var _$constants_719 = require('./constants'); */; -var search = _$search_557.findBin; -/* removed: var _$computeControlPoints_718 = require('./compute_control_points'); */; -/* removed: var _$create_spline_evaluator_722 = require('./create_spline_evaluator'); */; -/* removed: var _$create_i_derivative_evaluator_720 = require('./create_i_derivative_evaluator'); */; -/* removed: var _$create_j_derivative_evaluator_721 = require('./create_j_derivative_evaluator'); */; +/* removed: var _$constants_782 = require('./constants'); */; +var search = _$search_620.findBin; +/* removed: var _$computeControlPoints_781 = require('./compute_control_points'); */; +/* removed: var _$create_spline_evaluator_785 = require('./create_spline_evaluator'); */; +/* removed: var _$create_i_derivative_evaluator_783 = require('./create_i_derivative_evaluator'); */; +/* removed: var _$create_j_derivative_evaluator_784 = require('./create_j_derivative_evaluator'); */; /* * Create conversion functions to go from one basis to another. In particular the letter @@ -47051,11 +50573,11 @@ var search = _$search_557.findBin; * c: cartesian x-y coordinates * p: screen-space pixel coordinates */ -var _$setConvert_732 = function setConvert(trace) { - var a = trace.a; - var b = trace.b; - var na = trace.a.length; - var nb = trace.b.length; +var _$setConvert_794 = function setConvert(trace) { + var a = trace._a; + var b = trace._b; + var na = a.length; + var nb = b.length; var aax = trace.aaxis; var bax = trace.baxis; @@ -47070,1371 +50592,509 @@ var _$setConvert_732 = function setConvert(trace) { // Compute the tolerance so that points are visible slightly outside the // defined carpet axis: - var atol = arange * _$constants_719.RELATIVE_CULL_TOLERANCE; - var btol = brange * _$constants_719.RELATIVE_CULL_TOLERANCE; - - // Expand the limits to include the relative tolerance: - amin -= atol; - amax += atol; - bmin -= btol; - bmax += btol; - - trace.isVisible = function(a, b) { - return a > amin && a < amax && b > bmin && b < bmax; - }; - - trace.isOccluded = function(a, b) { - return a < amin || a > amax || b < bmin || b > bmax; - }; - - // XXX: ONLY PASSTHRU. ONLY. No, ONLY. - aax.c2p = function(v) { return v; }; - bax.c2p = function(v) { return v; }; - - trace.setScale = function() { - var x = trace._x; - var y = trace._y; - - // This is potentially a very expensive step! It does the bulk of the work of constructing - // an expanded basis of control points. Note in particular that it overwrites the existing - // basis without creating a new array since that would potentially thrash the garbage - // collector. - var result = _$computeControlPoints_718(trace.xctrl, trace.yctrl, x, y, aax.smoothing, bax.smoothing); - trace.xctrl = result[0]; - trace.yctrl = result[1]; - - // This step is the second step in the process, but it's somewhat simpler. It just unrolls - // some logic since it would be unnecessarily expensive to compute both interpolations - // nearly identically but separately and to include a bunch of linear vs. bicubic logic in - // every single call. - trace.evalxy = _$create_spline_evaluator_722([trace.xctrl, trace.yctrl], na, nb, aax.smoothing, bax.smoothing); - - trace.dxydi = _$create_i_derivative_evaluator_720([trace.xctrl, trace.yctrl], aax.smoothing, bax.smoothing); - trace.dxydj = _$create_j_derivative_evaluator_721([trace.xctrl, trace.yctrl], aax.smoothing, bax.smoothing); - }; - - /* - * Convert from i/j data grid coordinates to a/b values. Note in particular that this - * is *linear* interpolation, even if the data is interpolated bicubically. - */ - trace.i2a = function(i) { - var i0 = Math.max(0, Math.floor(i[0]), na - 2); - var ti = i[0] - i0; - return (1 - ti) * a[i0] + ti * a[i0 + 1]; - }; - - trace.j2b = function(j) { - var j0 = Math.max(0, Math.floor(j[1]), na - 2); - var tj = j[1] - j0; - return (1 - tj) * b[j0] + tj * b[j0 + 1]; - }; - - trace.ij2ab = function(ij) { - return [trace.i2a(ij[0]), trace.j2b(ij[1])]; - }; - - /* - * Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching - * through the a/b data arrays and assumes they are monotonic, which is presumed to have - * been enforced already. - */ - trace.a2i = function(aval) { - var i0 = Math.max(0, Math.min(search(aval, a), na - 2)); - var a0 = a[i0]; - var a1 = a[i0 + 1]; - return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0))); - }; - - trace.b2j = function(bval) { - var j0 = Math.max(0, Math.min(search(bval, b), nb - 2)); - var b0 = b[j0]; - var b1 = b[j0 + 1]; - return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0))); - }; - - trace.ab2ij = function(ab) { - return [trace.a2i(ab[0]), trace.b2j(ab[1])]; - }; - - /* - * Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear - * or bicubic spline evaluation, but the hard part is already done at this point. - */ - trace.i2c = function(i, j) { - return trace.evalxy([], i, j); - }; - - trace.ab2xy = function(aval, bval, extrapolate) { - if(!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) { - return [false, false]; - } - var i = trace.a2i(aval); - var j = trace.b2j(bval); - - var pt = trace.evalxy([], i, j); - - if(extrapolate) { - // This section uses the boundary derivatives to extrapolate linearly outside - // the defined range. Consider a scatter line with one point inside the carpet - // axis and one point outside. If we don't extrapolate, we can't draw the line - // at all. - var iex = 0; - var jex = 0; - var der = []; - - var i0, ti, j0, tj; - if(aval < a[0]) { - i0 = 0; - ti = 0; - iex = (aval - a[0]) / (a[1] - a[0]); - } else if(aval > a[na - 1]) { - i0 = na - 2; - ti = 1; - iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]); - } else { - i0 = Math.max(0, Math.min(na - 2, Math.floor(i))); - ti = i - i0; - } - - if(bval < b[0]) { - j0 = 0; - tj = 0; - jex = (bval - b[0]) / (b[1] - b[0]); - } else if(bval > b[nb - 1]) { - j0 = nb - 2; - tj = 1; - jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]); - } else { - j0 = Math.max(0, Math.min(nb - 2, Math.floor(j))); - tj = j - j0; - } - - if(iex) { - trace.dxydi(der, i0, j0, ti, tj); - pt[0] += der[0] * iex; - pt[1] += der[1] * iex; - } - - if(jex) { - trace.dxydj(der, i0, j0, ti, tj); - pt[0] += der[0] * jex; - pt[1] += der[1] * jex; - } - } - - return pt; - }; - - - trace.c2p = function(xy, xa, ya) { - return [xa.c2p(xy[0]), ya.c2p(xy[1])]; - }; - - trace.p2x = function(p, xa, ya) { - return [xa.p2c(p[0]), ya.p2c(p[1])]; - }; - - trace.dadi = function(i /* , u*/) { - // Right now only a piecewise linear a or b basis is permitted since smoother interpolation - // would cause monotonicity problems. As a retult, u is entirely disregarded in this - // computation, though we'll specify it as a parameter for the sake of completeness and - // future-proofing. It would be possible to use monotonic cubic interpolation, for example. - // - // See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation - - // u = u || 0; - - var i0 = Math.max(0, Math.min(a.length - 2, i)); - - // The step (demoninator) is implicitly 1 since that's the grid spacing. - return a[i0 + 1] - a[i0]; - }; - - trace.dbdj = function(j /* , v*/) { - // See above caveats for dadi which also apply here - var j0 = Math.max(0, Math.min(b.length - 2, j)); - - // The step (demoninator) is implicitly 1 since that's the grid spacing. - return b[j0 + 1] - b[j0]; - }; - - // Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v) - // Returns: (dx/da, dy/db) - // - // NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous - // derivative, as described better in create_i_derivative_evaluator.js - trace.dxyda = function(i0, j0, u, v) { - var dxydi = trace.dxydi(null, i0, j0, u, v); - var dadi = trace.dadi(i0, u); - - return [dxydi[0] / dadi, dxydi[1] / dadi]; - }; - - trace.dxydb = function(i0, j0, u, v) { - var dxydj = trace.dxydj(null, i0, j0, u, v); - var dbdj = trace.dbdj(j0, v); - - return [dxydj[0] / dbdj, dxydj[1] / dbdj]; - }; - - // Sometimes we don't care about precision and all we really want is decent rough - // directions (as is the case with labels). In that case, we can do a very rough finite - // difference and spare having to worry about precise grid coordinates: - trace.dxyda_rough = function(a, b, reldiff) { - var h = arange * (reldiff || 0.1); - var plus = trace.ab2xy(a + h, b, true); - var minus = trace.ab2xy(a - h, b, true); - - return [ - (plus[0] - minus[0]) * 0.5 / h, - (plus[1] - minus[1]) * 0.5 / h - ]; - }; - - trace.dxydb_rough = function(a, b, reldiff) { - var h = brange * (reldiff || 0.1); - var plus = trace.ab2xy(a, b + h, true); - var minus = trace.ab2xy(a, b - h, true); - - return [ - (plus[0] - minus[0]) * 0.5 / h, - (plus[1] - minus[1]) * 0.5 / h - ]; - }; - - trace.dpdx = function(xa) { - return xa._m; - }; - - trace.dpdy = function(ya) { - return ya._m; - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_724 = _$lib_539.isArrayOrTypedArray; - -var _$has_columns_724 = function(data) { - return __isArrayOrTypedArray_724(data[0]); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_777 = _$numerical_517.BADNUM; - -var _$convertColumnData_777 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { - var1Name = var1Name || 'x'; - var2Name = var2Name || 'y'; - arrayVarNames = arrayVarNames || ['z']; - - var col1 = trace[var1Name].slice(), - col2 = trace[var2Name].slice(), - textCol = trace.text, - colLen = Math.min(col1.length, col2.length), - hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), - col1Calendar = trace[var1Name + 'calendar'], - col2Calendar = trace[var2Name + 'calendar']; - - var i, j, arrayVar, newArray, arrayVarName; - - for(i = 0; i < arrayVarNames.length; i++) { - arrayVar = trace[arrayVarNames[i]]; - if(arrayVar) colLen = Math.min(colLen, arrayVar.length); - } - - if(colLen < col1.length) col1 = col1.slice(0, colLen); - if(colLen < col2.length) col2 = col2.slice(0, colLen); - - for(i = 0; i < colLen; i++) { - col1[i] = ax1.d2c(col1[i], 0, col1Calendar); - col2[i] = ax2.d2c(col2[i], 0, col2Calendar); - } - - var col1dv = _$lib_539.distinctVals(col1), - col1vals = col1dv.vals, - col2dv = _$lib_539.distinctVals(col2), - col2vals = col2dv.vals, - newArrays = []; - - for(i = 0; i < arrayVarNames.length; i++) { - newArrays[i] = _$lib_539.init2dArray(col2vals.length, col1vals.length); - } - - var i1, i2, text; - - if(hasColumnText) text = _$lib_539.init2dArray(col2vals.length, col1vals.length); - - for(i = 0; i < colLen; i++) { - if(col1[i] !== __BADNUM_777 && col2[i] !== __BADNUM_777) { - i1 = _$lib_539.findBin(col1[i] + col1dv.minDiff / 2, col1vals); - i2 = _$lib_539.findBin(col2[i] + col2dv.minDiff / 2, col2vals); - - for(j = 0; j < arrayVarNames.length; j++) { - arrayVarName = arrayVarNames[j]; - arrayVar = trace[arrayVarName]; - newArray = newArrays[j]; - newArray[i2][i1] = arrayVar[i]; - } - - if(hasColumnText) text[i2][i1] = textCol[i]; - } - } - - // hack for Plotly.react - save the input arrays for diffing purposes - trace['_input_' + var1Name] = trace[var1Name]; - trace['_input_' + var2Name] = trace[var2Name]; - trace[var1Name] = col1vals; - trace[var2Name] = col2vals; - for(j = 0; j < arrayVarNames.length; j++) { - trace['_input_' + arrayVarNames[j]] = trace[arrayVarNames[j]]; - trace[arrayVarNames[j]] = newArrays[j]; - } - if(hasColumnText) trace.text = text; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$has_columns_724 = require('./has_columns'); */; -/* removed: var _$convertColumnData_777 = require('../heatmap/convert_column_xyz'); */; - -var _$handleXYDefaults_734 = function handleXYDefaults(traceIn, traceOut, coerce) { - var cols = []; - var x = coerce('x'); - - var needsXTransform = x && !_$has_columns_724(x); - if(needsXTransform) cols.push('x'); - - traceOut._cheater = !x; - - var y = coerce('y'); - - var needsYTransform = y && !_$has_columns_724(y); - if(needsYTransform) cols.push('y'); - - if(!x && !y) return; - - if(cols.length) { - _$convertColumnData_777(traceOut, traceOut.aaxis, traceOut.baxis, 'a', 'b', cols); - } - - return true; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleXYDefaults_734 = require('./xy_defaults'); */; -/* removed: var _$handleABDefaults_706 = require('./ab_defaults'); */; -/* removed: var _$setConvert_732 = require('./set_convert'); */; -/* removed: var _$attributes_708 = require('./attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; - -var _$supplyDefaults_723 = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_708, attr, dflt); - } - - traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet'; - - var defaultColor = coerce('color', _$attributes_410.defaultLine); - _$lib_539.coerceFont(coerce, 'font'); - - coerce('carpet'); - - _$handleABDefaults_706(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 len = _$handleXYDefaults_734(traceIn, traceOut, coerce); - - _$setConvert_732(traceOut); - - if(traceOut._cheater) { - coerce('cheaterslope'); - } - - if(!len) { - traceOut.visible = false; - } -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$makePath_727 = function makePath(xp, yp, isBicubic) { - // Prevent d3 errors that would result otherwise: - if(xp.length === 0) return ''; - - var i, path = []; - var stride = isBicubic ? 3 : 1; - for(i = 0; i < xp.length; i += stride) { - path.push(xp[i] + ',' + yp[i]); - - if(isBicubic && i < xp.length - stride) { - path.push('C'); - path.push([ - xp[i + 1] + ',' + yp[i + 1], - xp[i + 2] + ',' + yp[i + 2] + ' ', - ].join(' ')); - } - } - return path.join(isBicubic ? '' : 'L'); -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var __isArrayOrTypedArray_728 = _$lib_539.isArrayOrTypedArray; - -/* - * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p). - * The output array is optional, but if provided, it will be reused without - * reallocation to the extent possible. - */ -var _$mapArray_728 = function mapArray(out, data, func) { - var i; - - if(!__isArrayOrTypedArray_728(out)) { - // If not an array, make it an array: - out = []; - } else if(out.length > data.length) { - // If too long, truncate. (If too short, it will grow - // automatically so we don't care about that case) - out = out.slice(0, data.length); - } - - for(i = 0; i < data.length; i++) { - out[i] = func(data[i]); - } - - return out; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var _$orientText_730 = 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 - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$mapArray_728 = require('./map_1d_array'); */; -/* removed: var _$makePath_727 = require('./makepath'); */; -/* removed: var _$orientText_730 = require('./orient_text'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; - -var _$plot_731 = function plot(gd, plotinfo, cdcarpet) { - for(var i = 0; i < cdcarpet.length; i++) { - __plotOne_731(gd, plotinfo, cdcarpet[i]); - } -}; - -function makeg(el, type, klass) { - var join = el.selectAll(type + '.' + klass).data([0]); - join.enter().append(type).classed(klass, true); - return join; -} - -function __plotOne_731(gd, plotinfo, cd) { - var t = cd[0]; - var trace = cd[0].trace, - xa = plotinfo.xaxis, - ya = plotinfo.yaxis, - aax = trace.aaxis, - bax = trace.baxis, - fullLayout = gd._fullLayout; - - var gridLayer = plotinfo.plot.selectAll('.carpetlayer'); - var clipLayer = fullLayout._clips; - - var axisLayer = makeg(gridLayer, 'g', 'carpet' + trace.uid).classed('trace', true); - var minorLayer = makeg(axisLayer, 'g', 'minorlayer'); - var majorLayer = makeg(axisLayer, 'g', 'majorlayer'); - var boundaryLayer = makeg(axisLayer, 'g', 'boundarylayer'); - var labelLayer = makeg(axisLayer, 'g', 'labellayer'); - - axisLayer.style('opacity', trace.opacity); - - drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true); - drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true); - drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true); - drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true); - - // NB: These are not ommitted if the lines are not active. The joins must be executed - // in order for them to get cleaned up without a full redraw - drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines); - drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines); - - var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, aax._labels, 'a-label'); - var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, bax._labels, 'b-label'); - - drawAxisTitles(gd, labelLayer, trace, t, xa, ya, labelOrientationA, labelOrientationB); - - drawClipPath(trace, t, clipLayer, xa, ya); -} - -function drawClipPath(trace, t, layer, xaxis, yaxis) { - var seg, xp, yp, i; - - var clip = layer.select('#' + trace._clipPathId); - - if(!clip.size()) { - clip = layer.append('clipPath') - .classed('carpetclip', true); - } - - var path = makeg(clip, 'path', 'carpetboundary'); - var segments = t.clipsegments; - var segs = []; - - for(i = 0; i < segments.length; i++) { - seg = segments[i]; - xp = _$mapArray_728([], seg.x, xaxis.c2p); - yp = _$mapArray_728([], seg.y, yaxis.c2p); - segs.push(_$makePath_727(xp, yp, seg.bicubic)); - } - - // This could be optimized ever so slightly to avoid no-op L segments - // at the corners, but it's so negligible that I don't think it's worth - // the extra complexity - var clipPathData = 'M' + segs.join('L') + 'Z'; - clip.attr('id', trace._clipPathId); - path.attr('d', clipPathData); -} - -function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines) { - var lineClass = 'const-' + axisLetter + '-lines'; - var gridJoin = layer.selectAll('.' + lineClass).data(gridlines); - - gridJoin.enter().append('path') - .classed(lineClass, true) - .style('vector-effect', 'non-scaling-stroke'); - - gridJoin.each(function(d) { - var gridline = d; - var x = gridline.x; - var y = gridline.y; - - var xp = _$mapArray_728([], x, xaxis.c2p); - var yp = _$mapArray_728([], y, yaxis.c2p); - - var path = 'M' + _$makePath_727(xp, yp, gridline.smoothing); - - var el = _$d3_127.select(this); - - el.attr('d', path) - .style('stroke-width', gridline.width) - .style('stroke', gridline.color) - .style('fill', 'none'); - }); - - gridJoin.exit().remove(); -} - -function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) { - var labelJoin = layer.selectAll('text.' + labelClass).data(labels); - - labelJoin.enter().append('text') - .classed(labelClass, true); - - var maxExtent = 0; - var labelOrientation = {}; - - labelJoin.each(function(label, i) { - // Most of the positioning is done in calc_labels. Only the parts that depend upon - // the screen space representation of the x and y axes are here: - var orientation; - if(label.axis.tickangle === 'auto') { - orientation = _$orientText_730(trace, xaxis, yaxis, label.xy, label.dxy); - } else { - var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0; - orientation = _$orientText_730(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]); - } - - if(!i) { - // TODO: offsetMultiplier? Not currently used anywhere... - labelOrientation = {angle: orientation.angle, flip: orientation.flip}; - } - var direction = (label.endAnchor ? -1 : 1) * orientation.flip; - - var labelEl = _$d3_127.select(this) - .attr({ - 'text-anchor': direction > 0 ? 'start' : 'end', - 'data-notex': 1 - }) - .call(_$drawing_436.font, label.font) - .text(label.text) - .call(_$svg_text_utils_562.convertToTspans, gd); - - var bbox = _$drawing_436.bBox(this); - - labelEl.attr('transform', - // Translate to the correct point: - 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + - // Rotate to line up with grid line tangent: - 'rotate(' + orientation.angle + ')' + - // Adjust the baseline and indentation: - 'translate(' + label.axis.labelpadding * direction + ',' + bbox.height * 0.3 + ')' - ); - - maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding); - }); - - labelJoin.exit().remove(); - - labelOrientation.maxExtent = maxExtent; - return labelOrientation; -} - -function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) { - var a, b, xy, dxy; - - a = 0.5 * (trace.a[0] + trace.a[trace.a.length - 1]); - b = trace.b[0]; - xy = trace.ab2xy(a, b, true); - dxy = trace.dxyda_rough(a, b); - if(labelOrientationA.angle === undefined) { - _$lib_539.extendFlat(labelOrientationA, _$orientText_730(trace, xa, ya, xy, trace.dxydb_rough(a, b))); - } - drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title'); - - a = trace.a[0]; - b = 0.5 * (trace.b[0] + trace.b[trace.b.length - 1]); - xy = trace.ab2xy(a, b, true); - dxy = trace.dxydb_rough(a, b); - if(labelOrientationB.angle === undefined) { - _$lib_539.extendFlat(labelOrientationB, _$orientText_730(trace, xa, ya, xy, trace.dxyda_rough(a, b))); - } - drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title'); -} - -var lineSpacing = _$alignment_511.LINE_SPACING; -var midShift = ((1 - _$alignment_511.MID_SHIFT) / lineSpacing) + 1; - -function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) { - var data = []; - if(axis.title) data.push(axis.title); - var titleJoin = layer.selectAll('text.' + labelClass).data(data); - var offset = labelOrientation.maxExtent; - - titleJoin.enter().append('text') - .classed(labelClass, true); - - // There's only one, but we'll do it as a join so it's updated nicely: - titleJoin.each(function() { - var orientation = _$orientText_730(trace, xa, ya, xy, dxy); - - if(['start', 'both'].indexOf(axis.showticklabels) === -1) { - offset = 0; - } - - // In addition to the size of the labels, add on some extra padding: - var titleSize = axis.titlefont.size; - offset += titleSize + axis.titleoffset; - - var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0); - var angleDiff = (labelNorm - orientation.angle + 450) % 360; - var reverseTitle = angleDiff > 90 && angleDiff < 270; - - var el = _$d3_127.select(this); - - el.text(axis.title || '') - .call(_$svg_text_utils_562.convertToTspans, gd); - - if(reverseTitle) { - offset = (-_$svg_text_utils_562.lineCount(el) + midShift) * lineSpacing * titleSize - offset; - } - - el.attr('transform', - 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + - 'rotate(' + orientation.angle + ') ' + - 'translate(0,' + offset + ')' - ) - .classed('user-select-none', true) - .attr('text-anchor', 'middle') - .call(_$drawing_436.font, axis.titlefont); - }); - - titleJoin.exit().remove(); -} - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var Carpet = {}; - -Carpet.attributes = _$attributes_708; -Carpet.supplyDefaults = _$supplyDefaults_723; -Carpet.plot = _$plot_731; -Carpet.calc = _$calc_712; -Carpet.animatable = true; - -Carpet.moduleType = 'trace'; -Carpet.name = 'carpet'; -Carpet.basePlotModule = _$cartesian_595; -Carpet.categories = ['cartesian', 'carpet', 'carpetAxis', 'notLegendIsolatable']; -Carpet.meta = { - -}; - -var _$Carpet_725 = Carpet; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var _$carpet_8 = _$Carpet_725; - -var _$topojsonClient_355 = { exports: {} }; -// https://github.com/topojson/topojson-client Version 2.1.0. Copyright 2016 Mike Bostock. -(function (global, factory) { - typeof _$topojsonClient_355.exports === 'object' && "object" !== 'undefined' ? factory(_$topojsonClient_355.exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.topojson = global.topojson || {}))); -}(this, (function (exports) { 'use strict'; - -var identity = function(x) { - return x; -}; - -var transform = function(topology) { - if ((transform = topology.transform) == null) return identity; - var transform, - x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - point[0] = (x0 += point[0]) * kx + dx; - point[1] = (y0 += point[1]) * ky + dy; - return point; - }; -}; + var atol = arange * _$constants_782.RELATIVE_CULL_TOLERANCE; + var btol = brange * _$constants_782.RELATIVE_CULL_TOLERANCE; -var bbox = function(topology) { - var bbox = topology.bbox; + // Expand the limits to include the relative tolerance: + amin -= atol; + amax += atol; + bmin -= btol; + bmax += btol; - function bboxPoint(p0) { - p1[0] = p0[0], p1[1] = p0[1], t(p1); - if (p1[0] < x0) x0 = p1[0]; - if (p1[0] > x1) x1 = p1[0]; - if (p1[1] < y0) y0 = p1[1]; - if (p1[1] > y1) y1 = p1[1]; - } + trace.isVisible = function(a, b) { + return a > amin && a < amax && b > bmin && b < bmax; + }; - function bboxGeometry(o) { - switch (o.type) { - case "GeometryCollection": o.geometries.forEach(bboxGeometry); break; - case "Point": bboxPoint(o.coordinates); break; - case "MultiPoint": o.coordinates.forEach(bboxPoint); break; - } - } + trace.isOccluded = function(a, b) { + return a < amin || a > amax || b < bmin || b > bmax; + }; - if (!bbox) { - var t = transform(topology), p0, p1 = new Array(2), name, - x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0; + trace.setScale = function() { + var x = trace._x; + var y = trace._y; - topology.arcs.forEach(function(arc) { - var i = -1, n = arc.length; - while (++i < n) { - p0 = arc[i], p1[0] = p0[0], p1[1] = p0[1], t(p1, i); - if (p1[0] < x0) x0 = p1[0]; - if (p1[0] > x1) x1 = p1[0]; - if (p1[1] < y0) y0 = p1[1]; - if (p1[1] > y1) y1 = p1[1]; - } - }); + // This is potentially a very expensive step! It does the bulk of the work of constructing + // an expanded basis of control points. Note in particular that it overwrites the existing + // basis without creating a new array since that would potentially thrash the garbage + // collector. + var result = _$computeControlPoints_781(trace._xctrl, trace._yctrl, x, y, aax.smoothing, bax.smoothing); + trace._xctrl = result[0]; + trace._yctrl = result[1]; - for (name in topology.objects) { - bboxGeometry(topology.objects[name]); - } + // This step is the second step in the process, but it's somewhat simpler. It just unrolls + // some logic since it would be unnecessarily expensive to compute both interpolations + // nearly identically but separately and to include a bunch of linear vs. bicubic logic in + // every single call. + trace.evalxy = _$create_spline_evaluator_785([trace._xctrl, trace._yctrl], na, nb, aax.smoothing, bax.smoothing); - bbox = topology.bbox = [x0, y0, x1, y1]; - } + trace.dxydi = _$create_i_derivative_evaluator_783([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing); + trace.dxydj = _$create_j_derivative_evaluator_784([trace._xctrl, trace._yctrl], aax.smoothing, bax.smoothing); + }; - return bbox; -}; + /* + * Convert from i/j data grid coordinates to a/b values. Note in particular that this + * is *linear* interpolation, even if the data is interpolated bicubically. + */ + trace.i2a = function(i) { + var i0 = Math.max(0, Math.floor(i[0]), na - 2); + var ti = i[0] - i0; + return (1 - ti) * a[i0] + ti * a[i0 + 1]; + }; -var reverse = function(array, n) { - var t, j = array.length, i = j - n; - while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; -}; + trace.j2b = function(j) { + var j0 = Math.max(0, Math.floor(j[1]), na - 2); + var tj = j[1] - j0; + return (1 - tj) * b[j0] + tj * b[j0 + 1]; + }; -var feature = function(topology, o) { - return o.type === "GeometryCollection" - ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })} - : feature$1(topology, o); -}; + trace.ij2ab = function(ij) { + return [trace.i2a(ij[0]), trace.j2b(ij[1])]; + }; -function feature$1(topology, o) { - var id = o.id, - bbox = o.bbox, - properties = o.properties == null ? {} : o.properties, - geometry = object(topology, o); - return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} - : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} - : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; -} + /* + * Convert from a/b coordinates to i/j grid-numbered coordinates. This requires searching + * through the a/b data arrays and assumes they are monotonic, which is presumed to have + * been enforced already. + */ + trace.a2i = function(aval) { + var i0 = Math.max(0, Math.min(search(aval, a), na - 2)); + var a0 = a[i0]; + var a1 = a[i0 + 1]; + return Math.max(0, Math.min(na - 1, i0 + (aval - a0) / (a1 - a0))); + }; -function object(topology, o) { - var transformPoint = transform(topology), - arcs = topology.arcs; + trace.b2j = function(bval) { + var j0 = Math.max(0, Math.min(search(bval, b), nb - 2)); + var b0 = b[j0]; + var b1 = b[j0 + 1]; + return Math.max(0, Math.min(nb - 1, j0 + (bval - b0) / (b1 - b0))); + }; - function arc(i, points) { - if (points.length) points.pop(); - for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { - points.push(transformPoint(a[k].slice(), k)); - } - if (i < 0) reverse(points, n); - } + trace.ab2ij = function(ab) { + return [trace.a2i(ab[0]), trace.b2j(ab[1])]; + }; - function point(p) { - return transformPoint(p.slice()); - } + /* + * Convert from i/j coordinates to x/y caretesian coordinates. This means either bilinear + * or bicubic spline evaluation, but the hard part is already done at this point. + */ + trace.i2c = function(i, j) { + return trace.evalxy([], i, j); + }; - function line(arcs) { - var points = []; - for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); - if (points.length < 2) points.push(points[0].slice()); - return points; - } + trace.ab2xy = function(aval, bval, extrapolate) { + if(!extrapolate && (aval < a[0] || aval > a[na - 1] | bval < b[0] || bval > b[nb - 1])) { + return [false, false]; + } + var i = trace.a2i(aval); + var j = trace.b2j(bval); - function ring(arcs) { - var points = line(arcs); - while (points.length < 4) points.push(points[0].slice()); - return points; - } + var pt = trace.evalxy([], i, j); - function polygon(arcs) { - return arcs.map(ring); - } + if(extrapolate) { + // This section uses the boundary derivatives to extrapolate linearly outside + // the defined range. Consider a scatter line with one point inside the carpet + // axis and one point outside. If we don't extrapolate, we can't draw the line + // at all. + var iex = 0; + var jex = 0; + var der = []; - function geometry(o) { - var type = o.type, coordinates; - switch (type) { - case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; - case "Point": coordinates = point(o.coordinates); break; - case "MultiPoint": coordinates = o.coordinates.map(point); break; - case "LineString": coordinates = line(o.arcs); break; - case "MultiLineString": coordinates = o.arcs.map(line); break; - case "Polygon": coordinates = polygon(o.arcs); break; - case "MultiPolygon": coordinates = o.arcs.map(polygon); break; - default: return null; - } - return {type: type, coordinates: coordinates}; - } + var i0, ti, j0, tj; + if(aval < a[0]) { + i0 = 0; + ti = 0; + iex = (aval - a[0]) / (a[1] - a[0]); + } else if(aval > a[na - 1]) { + i0 = na - 2; + ti = 1; + iex = (aval - a[na - 1]) / (a[na - 1] - a[na - 2]); + } else { + i0 = Math.max(0, Math.min(na - 2, Math.floor(i))); + ti = i - i0; + } - return geometry(o); -} + if(bval < b[0]) { + j0 = 0; + tj = 0; + jex = (bval - b[0]) / (b[1] - b[0]); + } else if(bval > b[nb - 1]) { + j0 = nb - 2; + tj = 1; + jex = (bval - b[nb - 1]) / (b[nb - 1] - b[nb - 2]); + } else { + j0 = Math.max(0, Math.min(nb - 2, Math.floor(j))); + tj = j - j0; + } -var stitch = function(topology, arcs) { - var stitchedArcs = {}, - fragmentByStart = {}, - fragmentByEnd = {}, - fragments = [], - emptyIndex = -1; + if(iex) { + trace.dxydi(der, i0, j0, ti, tj); + pt[0] += der[0] * iex; + pt[1] += der[1] * iex; + } - // Stitch empty arcs first, since they may be subsumed by other arcs. - arcs.forEach(function(i, j) { - var arc = topology.arcs[i < 0 ? ~i : i], t; - if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { - t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; - } - }); + if(jex) { + trace.dxydj(der, i0, j0, ti, tj); + pt[0] += der[0] * jex; + pt[1] += der[1] * jex; + } + } - arcs.forEach(function(i) { - var e = ends(i), - start = e[0], - end = e[1], - f, g; + return pt; + }; - if (f = fragmentByEnd[start]) { - delete fragmentByEnd[f.end]; - f.push(i); - f.end = end; - if (g = fragmentByStart[end]) { - delete fragmentByStart[g.start]; - var fg = g === f ? f : f.concat(g); - fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else if (f = fragmentByStart[end]) { - delete fragmentByStart[f.start]; - f.unshift(i); - f.start = start; - if (g = fragmentByEnd[start]) { - delete fragmentByEnd[g.end]; - var gf = g === f ? f : g.concat(f); - fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else { - f = [i]; - fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; - } - }); - function ends(i) { - var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; - if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); - else p1 = arc[arc.length - 1]; - return i < 0 ? [p1, p0] : [p0, p1]; - } + trace.c2p = function(xy, xa, ya) { + return [xa.c2p(xy[0]), ya.c2p(xy[1])]; + }; - function flush(fragmentByEnd, fragmentByStart) { - for (var k in fragmentByEnd) { - var f = fragmentByEnd[k]; - delete fragmentByStart[f.start]; - delete f.start; - delete f.end; - f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); - fragments.push(f); - } - } + trace.p2x = function(p, xa, ya) { + return [xa.p2c(p[0]), ya.p2c(p[1])]; + }; - flush(fragmentByEnd, fragmentByStart); - flush(fragmentByStart, fragmentByEnd); - arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); + trace.dadi = function(i /* , u*/) { + // Right now only a piecewise linear a or b basis is permitted since smoother interpolation + // would cause monotonicity problems. As a retult, u is entirely disregarded in this + // computation, though we'll specify it as a parameter for the sake of completeness and + // future-proofing. It would be possible to use monotonic cubic interpolation, for example. + // + // See: https://en.wikipedia.org/wiki/Monotone_cubic_interpolation - return fragments; -}; + // u = u || 0; -var mesh = function(topology) { - return object(topology, meshArcs.apply(this, arguments)); -}; + var i0 = Math.max(0, Math.min(a.length - 2, i)); -function meshArcs(topology, object$$1, filter) { - var arcs, i, n; - if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter); - else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i; - return {type: "MultiLineString", arcs: stitch(topology, arcs)}; -} + // The step (demoninator) is implicitly 1 since that's the grid spacing. + return a[i0 + 1] - a[i0]; + }; -function extractArcs(topology, object$$1, filter) { - var arcs = [], - geomsByArc = [], - geom; + trace.dbdj = function(j /* , v*/) { + // See above caveats for dadi which also apply here + var j0 = Math.max(0, Math.min(b.length - 2, j)); - function extract0(i) { - var j = i < 0 ? ~i : i; - (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); - } + // The step (demoninator) is implicitly 1 since that's the grid spacing. + return b[j0 + 1] - b[j0]; + }; - function extract1(arcs) { - arcs.forEach(extract0); - } + // Takes: grid cell coordinate (i, j) and fractional grid cell coordinates (u, v) + // Returns: (dx/da, dy/db) + // + // NB: separate grid cell + fractional grid cell coordinate format is due to the discontinuous + // derivative, as described better in create_i_derivative_evaluator.js + trace.dxyda = function(i0, j0, u, v) { + var dxydi = trace.dxydi(null, i0, j0, u, v); + var dadi = trace.dadi(i0, u); - function extract2(arcs) { - arcs.forEach(extract1); - } + return [dxydi[0] / dadi, dxydi[1] / dadi]; + }; - function extract3(arcs) { - arcs.forEach(extract2); - } + trace.dxydb = function(i0, j0, u, v) { + var dxydj = trace.dxydj(null, i0, j0, u, v); + var dbdj = trace.dbdj(j0, v); - function geometry(o) { - switch (geom = o, o.type) { - case "GeometryCollection": o.geometries.forEach(geometry); break; - case "LineString": extract1(o.arcs); break; - case "MultiLineString": case "Polygon": extract2(o.arcs); break; - case "MultiPolygon": extract3(o.arcs); break; - } - } + return [dxydj[0] / dbdj, dxydj[1] / dbdj]; + }; - geometry(object$$1); + // Sometimes we don't care about precision and all we really want is decent rough + // directions (as is the case with labels). In that case, we can do a very rough finite + // difference and spare having to worry about precise grid coordinates: + trace.dxyda_rough = function(a, b, reldiff) { + var h = arange * (reldiff || 0.1); + var plus = trace.ab2xy(a + h, b, true); + var minus = trace.ab2xy(a - h, b, true); - geomsByArc.forEach(filter == null - ? function(geoms) { arcs.push(geoms[0].i); } - : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); + return [ + (plus[0] - minus[0]) * 0.5 / h, + (plus[1] - minus[1]) * 0.5 / h + ]; + }; - return arcs; -} + trace.dxydb_rough = function(a, b, reldiff) { + var h = brange * (reldiff || 0.1); + var plus = trace.ab2xy(a, b + h, true); + var minus = trace.ab2xy(a, b - h, true); -function planarRingArea(ring) { - var i = -1, n = ring.length, a, b = ring[n - 1], area = 0; - while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0]; - return Math.abs(area); // Note: doubled area! -} + return [ + (plus[0] - minus[0]) * 0.5 / h, + (plus[1] - minus[1]) * 0.5 / h + ]; + }; -var merge = function(topology) { - return object(topology, mergeArcs.apply(this, arguments)); + trace.dpdx = function(xa) { + return xa._m; + }; + + trace.dpdy = function(ya) { + return ya._m; + }; }; -function mergeArcs(topology, objects) { - var polygonsByArc = {}, - polygons = [], - groups = []; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - objects.forEach(geometry); +'use strict'; - function geometry(o) { - switch (o.type) { - case "GeometryCollection": o.geometries.forEach(geometry); break; - case "Polygon": extract(o.arcs); break; - case "MultiPolygon": o.arcs.forEach(extract); break; - } - } +/* removed: var _$lib_601 = require('../../lib'); */; - function extract(polygon) { - polygon.forEach(function(ring) { - ring.forEach(function(arc) { - (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); - }); - }); - polygons.push(polygon); - } +/* + * 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 + */ +var _$smoothFill2dArray_795 = function smoothFill2dArray(data, a, b) { + var i, j, k; + var ip = []; + var jp = []; + // var neighborCnts = []; - function area(ring) { - return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]); - } + var ni = data[0].length; + var nj = data.length; - polygons.forEach(function(polygon) { - if (!polygon._) { - var group = [], - neighbors = [polygon]; - polygon._ = 1; - groups.push(group); - while (polygon = neighbors.pop()) { - group.push(polygon); - polygon.forEach(function(ring) { - ring.forEach(function(arc) { - polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { - if (!polygon._) { - polygon._ = 1; - neighbors.push(polygon); - } - }); - }); - }); - } - } - }); + 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); - polygons.forEach(function(polygon) { - delete polygon._; - }); + } - return { - type: "MultiPolygon", - arcs: groups.map(function(polygons) { - var arcs = [], n; + // 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); - // Extract the exterior (unique) arcs. - polygons.forEach(function(polygon) { - polygon.forEach(function(ring) { - ring.forEach(function(arc) { - if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { - arcs.push(arc); + data[j][i] = avgSurrounding(i, j); + // neighborCnts.push(result.neighbors); } - }); - }); - }); + dmax = Math.max(dmax, Math.abs(data[j][i])); + } + } - // Stitch the arcs into one or more rings. - arcs = stitch(topology, arcs); + if(!ip.length) return data; - // If more than one ring is returned, - // at most one of these rings can be the exterior; - // choose the one with the greatest absolute area. - if ((n = arcs.length) > 1) { - for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { - if ((ki = area(arcs[i])) > k) { - t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; - } - } - } + // 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]; - return arcs; - }) - }; -} + // 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 bisect = function(a, x) { - var lo = 0, hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (a[mid] < x) lo = mid + 1; - else hi = mid; - } - return lo; -}; + 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++; + } -var neighbors = function(objects) { - var indexesByArc = {}, // arc index -> array of object indexes - neighbors = objects.map(function() { return []; }); + 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++; + } - function line(arcs, i) { - arcs.forEach(function(a) { - if (a < 0) a = ~a; - var o = indexesByArc[a]; - if (o) o.push(i); - else indexesByArc[a] = [i]; - }); - } + 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++; + } - function polygon(arcs, i) { - arcs.forEach(function(arc) { line(arc, i); }); - } + 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++; + } - function geometry(o, i) { - if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); - else if (o.type in geometryType) geometryType[o.type](o.arcs, i); - } + 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]; - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } - }; + // 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); - objects.forEach(geometry); + 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; + } - for (var i in indexesByArc) { - for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { - for (var k = j + 1; k < m; ++k) { - var ij = indexes[j], ik = indexes[k], n; - if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); - if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); - } - } - } + // 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; - return neighbors; -}; + // 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; -var quantize = function(topology, n) { - if (!((n = Math.floor(n)) >= 2)) throw new Error("n must be ≥2"); - if (topology.transform) throw new Error("already quantized"); - var bb = bbox(topology), name, - dx = bb[0], kx = (bb[2] - dx) / (n - 1) || 1, - dy = bb[1], ky = (bb[3] - dy) / (n - 1) || 1; + // 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; - function quantizePoint(p) { - p[0] = Math.round((p[0] - dx) / kx); - p[1] = Math.round((p[1] - dy) / ky); - } + data[j][i] += diff * (1 + overrelaxation); + } - function quantizeGeometry(o) { - switch (o.type) { - case "GeometryCollection": o.geometries.forEach(quantizeGeometry); break; - case "Point": quantizePoint(o.coordinates); break; - case "MultiPoint": o.coordinates.forEach(quantizePoint); break; - } - } + resid = Math.sqrt(resid); + } while(iter++ < itermax && resid > tol); - topology.arcs.forEach(function(arc) { - var i = 1, - j = 1, - n = arc.length, - pi = arc[0], - x0 = pi[0] = Math.round((pi[0] - dx) / kx), - y0 = pi[1] = Math.round((pi[1] - dy) / ky), - pj, - x1, - y1; + _$lib_601.log('Smoother converged to', resid, 'after', iter, 'iterations'); - for (; i < n; ++i) { - pi = arc[i]; - x1 = Math.round((pi[0] - dx) / kx); - y1 = Math.round((pi[1] - dy) / ky); - if (x1 !== x0 || y1 !== y0) { - pj = arc[j++]; - pj[0] = x1 - x0, x0 = x1; - pj[1] = y1 - y0, y0 = y1; - } - } + return data; +}; - if (j < 2) { - pj = arc[j++]; - pj[0] = 0; - pj[1] = 0; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - arc.length = j; - }); +'use strict'; - for (name in topology.objects) { - quantizeGeometry(topology.objects[name]); - } +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; - topology.transform = { - scale: [kx, ky], - translate: [dx, dy] - }; +var _$clean2dArray_837 = function clean2dArray(zOld, transpose) { + var rowlen, collen, getCollen, old2new, i, j; - return topology; -}; + function cleanZvalue(v) { + if(!_$fastIsnumeric_196(v)) return undefined; + return +v; + } -var untransform = function(topology) { - if ((transform = topology.transform) == null) return identity; - var transform, - x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - var x1 = Math.round((point[0] - dx) / kx), - y1 = Math.round((point[1] - dy) / ky); - point[0] = x1 - x0, x0 = x1; - point[1] = y1 - y0, y0 = y1; - return point; - }; -}; + if(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]; }; + } -exports.bbox = bbox; -exports.feature = feature; -exports.mesh = mesh; -exports.meshArcs = meshArcs; -exports.merge = merge; -exports.mergeArcs = mergeArcs; -exports.neighbors = neighbors; -exports.quantize = quantize; -exports.transform = transform; -exports.untransform = untransform; + var zNew = new Array(rowlen); -Object.defineProperty(exports, '__esModule', { value: true }); + for(i = 0; i < rowlen; i++) { + collen = getCollen(zOld, i); + zNew[i] = new Array(collen); + for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j)); + } -}))); + return zNew; +}; -_$topojsonClient_355 = _$topojsonClient_355.exports -var _$constants_613 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48443,173 +51103,74 @@ var _$constants_613 = {}; * LICENSE file in the root directory of this source tree. */ -'use strict'; -// projection names to d3 function name -_$constants_613.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' -}; +'use strict'; -// name of the axes -_$constants_613.axesNames = ['lonaxis', 'lataxis']; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_839 = _$numerical_578.BADNUM; -// max longitudinal angular span (EXPERIMENTAL) -_$constants_613.lonaxisSpan = { - 'orthographic': 180, - 'azimuthal equal area': 360, - 'azimuthal equidistant': 360, - 'conic conformal': 180, - 'gnomonic': 160, - 'stereographic': 180, - 'transverse mercator': 180, - '*': 360 -}; +var _$convertColumnData_839 = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) { + var col1 = trace[var1Name].slice(), + col2 = trace[var2Name].slice(), + textCol = trace.text, + colLen = Math.min(col1.length, col2.length), + hasColumnText = (textCol !== undefined && !Array.isArray(textCol[0])), + col1Calendar = trace[var1Name + 'calendar'], + col2Calendar = trace[var2Name + 'calendar']; -// max latitudinal angular span (EXPERIMENTAL) -_$constants_613.lataxisSpan = { - 'conic conformal': 150, - 'stereographic': 179.5, - '*': 180 -}; + var i, j, arrayVar, newArray, arrayVarName; -// defaults for each scope -_$constants_613.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] + for(i = 0; i < arrayVarNames.length; i++) { + arrayVar = trace[arrayVarNames[i]]; + if(arrayVar) colLen = Math.min(colLen, arrayVar.length); } -}; - -// angular pad to avoid rounding error around clip angles -_$constants_613.clipPad = 1e-3; -// map projection precision -_$constants_613.precision = 0.1; + if(colLen < col1.length) col1 = col1.slice(0, colLen); + if(colLen < col2.length) col2 = col2.slice(0, colLen); -// default land and water fill colors -_$constants_613.landColor = '#F0DC82'; -_$constants_613.waterColor = '#3399FF'; + for(i = 0; i < colLen; i++) { + col1[i] = ax1.d2c(col1[i], 0, col1Calendar); + col2[i] = ax2.d2c(col2[i], 0, col2Calendar); + } -// locationmode to layer name -_$constants_613.locationmodeToLayer = { - 'ISO-3': 'countries', - 'USA-states': 'subunits', - 'country names': 'countries' -}; + var col1dv = _$lib_601.distinctVals(col1), + col1vals = col1dv.vals, + col2dv = _$lib_601.distinctVals(col2), + col2vals = col2dv.vals, + newArrays = []; -// SVG element for a sphere (use to frame maps) -_$constants_613.sphereSVG = {type: 'Sphere'}; + for(i = 0; i < arrayVarNames.length; i++) { + newArrays[i] = _$lib_601.init2dArray(col2vals.length, col1vals.length); + } -// N.B. base layer names must be the same as in the topojson files + var i1, i2, text; -// base layer with a fill color -_$constants_613.fillLayers = { - ocean: 1, - land: 1, - lakes: 1 -}; + if(hasColumnText) text = _$lib_601.init2dArray(col2vals.length, col1vals.length); -// base layer with a only a line color -_$constants_613.lineLayers = { - subunits: 1, - countries: 1, - coastlines: 1, - rivers: 1, - frame: 1 -}; + for(i = 0; i < colLen; i++) { + if(col1[i] !== __BADNUM_839 && col2[i] !== __BADNUM_839) { + i1 = _$lib_601.findBin(col1[i] + col1dv.minDiff / 2, col1vals); + i2 = _$lib_601.findBin(col2[i] + col2dv.minDiff / 2, col2vals); -_$constants_613.layers = [ - 'bg', - 'ocean', 'land', 'lakes', - 'subunits', 'countries', 'coastlines', 'rivers', - 'lataxis', 'lonaxis', 'frame', - 'backplot', - 'frontplot' -]; + for(j = 0; j < arrayVarNames.length; j++) { + arrayVarName = arrayVarNames[j]; + arrayVar = trace[arrayVarName]; + newArray = newArrays[j]; + newArray[i2][i1] = arrayVar[i]; + } -_$constants_613.layersForChoropleth = [ - 'bg', - 'ocean', 'land', - 'subunits', 'countries', 'coastlines', - 'lataxis', 'lonaxis', 'frame', - 'backplot', - 'rivers', 'lakes', - 'frontplot' -]; + if(hasColumnText) text[i2][i1] = textCol[i]; + } + } -_$constants_613.layerNameToAdjective = { - ocean: 'ocean', - land: 'land', - lakes: 'lake', - subunits: 'subunit', - countries: 'country', - coastlines: 'coastline', - rivers: 'river', - frame: 'frame' + trace['_' + var1Name] = col1vals; + trace['_' + var2Name] = col2vals; + for(j = 0; j < arrayVarNames.length; j++) { + trace['_' + arrayVarNames[j]] = newArrays[j]; + } + if(hasColumnText) trace._text = text; }; -var _$topojson_utils_565 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -48618,1643 +51179,866 @@ var _$topojson_utils_565 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var topojsonUtils = _$topojson_utils_565 = {}; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$cheater_basis_780 = require('./cheater_basis'); */; +/* removed: var _$array_minmax_770 = require('./array_minmax'); */; +/* removed: var _$calcGridlines_777 = require('./calc_gridlines'); */; +/* removed: var _$calcLabels_778 = require('./calc_labels'); */; +/* removed: var _$makeClipPath_776 = require('./calc_clippath'); */; +/* removed: var _$clean2dArray_837 = require('../heatmap/clean_2d_array'); */; +/* removed: var _$smoothFill2dArray_795 = require('./smooth_fill_2d_array'); */; +/* removed: var _$has_columns_787 = require('./has_columns'); */; +/* removed: var _$convertColumnData_839 = require('../heatmap/convert_column_xyz'); */; +/* removed: var _$setConvert_794 = require('./set_convert'); */; -var locationmodeToLayer = _$constants_613.locationmodeToLayer; -var topojsonFeature = _$topojsonClient_355.feature; +var _$calc_775 = function calc(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis); + var ya = _$axes_647.getFromId(gd, trace.yaxis); + var aax = trace.aaxis; + var bax = trace.baxis; + var x = trace.x; + var y = trace.y; + var cols = []; + if(x && !_$has_columns_787(x)) cols.push('x'); + if(y && !_$has_columns_787(y)) cols.push('y'); -topojsonUtils.getTopojsonName = function(geoLayout) { - return [ - geoLayout.scope.replace(/ /g, '-'), '_', - geoLayout.resolution.toString(), 'm' - ].join(''); -}; + if(cols.length) { + _$convertColumnData_839(trace, aax, bax, 'a', 'b', cols); + } -topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) { - return topojsonURL + topojsonName + '.json'; -}; + var a = trace._a = trace._a || trace.a; + var b = trace._b = trace._b || trace.b; + x = trace._x || trace.x; + y = trace._y || trace.y; -topojsonUtils.getTopojsonFeatures = function(trace, topojson) { - var layer = locationmodeToLayer[trace.locationmode], - obj = topojson.objects[layer]; + var t = {}; + + if(trace._cheater) { + var avals = aax.cheatertype === 'index' ? a.length : a; + var bvals = bax.cheatertype === 'index' ? b.length : b; + x = _$cheater_basis_780(avals, bvals, trace.cheaterslope); + } + + trace._x = x = _$clean2dArray_837(x); + trace._y = y = _$clean2dArray_837(y); + + // Fill in any undefined values with elliptic smoothing. This doesn't take + // into account the spacing of the values. That is, the derivatives should + // be modified to use a and b values. It's not that hard, but this is already + // moderate overkill for just filling in missing values. + _$smoothFill2dArray_795(x, a, b); + _$smoothFill2dArray_795(y, a, b); - return topojsonFeature(topojson, obj).features; -}; + _$setConvert_794(trace); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // create conversion functions that depend on the data + trace.setScale(); -// -// used strictly for logging the processing of the algorithm... only useful if you intend on -// looking under the covers (for pretty UI's or debugging) -// + // This is a rather expensive scan. Nothing guarantees monotonicity, + // so we need to scan through all data to get proper ranges: + var xrange = _$array_minmax_770(x); + var yrange = _$array_minmax_770(y); -function BuildLog(){ - var my; - var nextSegmentId = 0; - var curVert = false; + var dx = 0.5 * (xrange[1] - xrange[0]); + var xc = 0.5 * (xrange[1] + xrange[0]); - function push(type, data){ - my.list.push({ - type: type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } + var dy = 0.5 * (yrange[1] - yrange[0]); + var yc = 0.5 * (yrange[1] + yrange[0]); - my = { - list: [], - segmentId: function(){ - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2){ - return push('check', { seg1: seg1, seg2: seg2 }); - }, - segmentChop: function(seg, end){ - push('div_seg', { seg: seg, pt: end }); - return push('chop', { seg: seg, pt: end }); - }, - statusRemove: function(seg){ - return push('pop_seg', { seg: seg }); - }, - segmentUpdate: function(seg){ - return push('seg_update', { seg: seg }); - }, - segmentNew: function(seg, primary){ - return push('new_seg', { seg: seg, primary: primary }); - }, - segmentRemove: function(seg){ - return push('rem_seg', { seg: seg }); - }, - tempStatus: function(seg, above, below){ - return push('temp_status', { seg: seg, above: above, below: below }); - }, - rewind: function(seg){ - return push('rewind', { seg: seg }); - }, - status: function(seg, above, below){ - return push('status', { seg: seg, above: above, below: below }); - }, - vert: function(x){ - if (x === curVert) - return my; - curVert = x; - return push('vert', { x: x }); - }, - log: function(data){ - if (typeof data !== 'string') - data = JSON.stringify(data, false, ' '); - return push('log', { txt: data }); - }, - reset: function(){ - return push('reset'); - }, - selected: function(segs){ - return push('selected', { segs: segs }); - }, - chainStart: function(seg){ - return push('chain_start', { seg: seg }); - }, - chainRemoveHead: function(index, pt){ - return push('chain_rem_head', { index: index, pt: pt }); - }, - chainRemoveTail: function(index, pt){ - return push('chain_rem_tail', { index: index, pt: pt }); - }, - chainNew: function(pt1, pt2){ - return push('chain_new', { pt1: pt1, pt2: pt2 }); - }, - chainMatch: function(index){ - return push('chain_match', { index: index }); - }, - chainClose: function(index){ - return push('chain_close', { index: index }); - }, - chainAddHead: function(index, pt){ - return push('chain_add_head', { index: index, pt: pt }); - }, - chainAddTail: function(index, pt){ - return push('chain_add_tail', { index: index, pt: pt, }); - }, - chainConnect: function(index1, index2){ - return push('chain_con', { index1: index1, index2: index2 }); - }, - chainReverse: function(index){ - return push('chain_rev', { index: index }); - }, - chainJoin: function(index1, index2){ - return push('chain_join', { index1: index1, index2: index2 }); - }, - done: function(){ - return push('done'); - } - }; - return my; -} + // Expand the axes to fit the plot, except just grow it by a factor of 1.3 + // because the labels should be taken into account except that's difficult + // hence 1.3. + var grow = 1.3; + xrange = [xc - dx * grow, xc + dx * grow]; + yrange = [yc - dy * grow, yc + dy * grow]; -var _$BuildLog_296 = BuildLog; + _$axes_647.expand(xa, xrange, {padded: true}); + _$axes_647.expand(ya, yrange, {padded: true}); -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // Enumerate the gridlines, both major and minor, and store them on the trace + // object: + _$calcGridlines_777(trace, 'a', 'b'); + _$calcGridlines_777(trace, 'b', 'a'); -// -// provides the raw computation functions that takes epsilon into account -// -// zero is defined to be between (-epsilon, epsilon) exclusive -// + // Calculate the text labels for each major gridline and store them on the + // trace object: + _$calcLabels_778(trace, aax); + _$calcLabels_778(trace, bax); -function Epsilon(eps){ - if (typeof eps !== 'number') - eps = 0.0000000001; // sane default? sure why not - var my = { - epsilon: function(v){ - if (typeof v === 'number') - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right){ - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right){ - // p must be collinear with left->right - // returns false if p == left, p == right, or left == right - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; + // Tabulate points for the four segments that bound the axes so that we can + // map to pixel coordinates in the plot function and create a clip rect: + t.clipsegments = _$makeClipPath_776(trace._xctrl, trace._yctrl, aax, bax); - var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - // if `dot` is 0, then `p` == `left` or `left` == `right` (reject) - // if `dot` is less than 0, then `p` is to the left of `left` (reject) - if (dot < eps) - return false; + t.x = x; + t.y = y; + t.a = a; + t.b = b; - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - // if `dot` > `sqlen`, then `p` is to the right of `right` (reject) - // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject) - if (dot - sqlen > -eps) - return false; + return [t]; +}; - return true; - }, - pointsSameX: function(p1, p2){ - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2){ - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2){ - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2){ - // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1); - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3){ - // does pt1->pt2->pt3 make a straight line? - // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3) - // if slopes are equal, then they must be collinear, because they share pt2 - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1){ - // returns false if the lines are coincident (e.g., parallel or on top of each other) - // - // returns an object if the lines intersect: - // { - // pt: [x, y], where the intersection point is at - // alongA: where intersection point is along A, - // alongB: where intersection point is along B - // } - // - // alongA and alongB will each be one of: -2, -1, 0, 1, 2 - // - // with the following meaning: - // - // -2 intersection point is before segment's first point - // -1 intersection point is directly on segment's first point - // 0 intersection point is between segment's first and second points (exclusive) - // 1 intersection point is directly on segment's second point - // 2 intersection point is after segment's second point - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; // lines are coincident +'use strict'; - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; +/* removed: var _$attributes_771 = require('./attributes'); */; - var A = (bdx * dy - bdy * dx) / axb; - var B = (adx * dy - ady * dx) / axb; +var addOpacity = _$color_473.addOpacity; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../../plots/cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../../plots/cartesian/tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_651 = require('../../plots/cartesian/category_order_defaults'); */; +/* removed: var _$setConvert_665 = require('../../plots/cartesian/set_convert'); */; +/* removed: var _$autoType_648 = require('../../plots/cartesian/axis_autotype'); */; - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A * adx, - a0[1] + A * ady - ] - }; +/** + * options: object containing: + * + * letter: 'a' or 'b' + * title: name of the axis (ie 'Colorbar') to go in default title + * name: axis object name (ie 'xaxis') if one should be stored + * font: the default font to inherit + * outerTicks: boolean, should ticks default to outside? + * showGrid: boolean, should gridlines be shown by default? + * data: the plot data to use in choosing auto type + * bgColor: the plot background color, to calculate default gridline colors + */ +var _$handleAxisDefaults_774 = function handleAxisDefaults(containerIn, containerOut, options) { + var letter = options.letter, + font = options.font || {}, + attributes = _$attributes_771[letter + 'axis']; - // categorize where intersection point is along A and B + function coerce(attr, dflt) { + return _$lib_601.coerce(containerIn, containerOut, attributes, attr, dflt); + } - if (A <= -eps) - ret.alongA = -2; - else if (A < eps) - ret.alongA = -1; - else if (A - 1 <= -eps) - ret.alongA = 0; - else if (A - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; + function coerce2(attr, dflt) { + return _$lib_601.coerce2(containerIn, containerOut, attributes, attr, dflt); + } - if (B <= -eps) - ret.alongB = -2; - else if (B < eps) - ret.alongB = -1; - else if (B - 1 <= -eps) - ret.alongB = 0; - else if (B - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; + // set up some private properties + if(options.name) { + containerOut._name = options.name; + containerOut._id = options.name; + } - return ret; - }, - pointInsideRegion: function(pt, region){ - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++){ - var curr_x = region[i][0]; - var curr_y = region[i][1]; + // now figure out type and do some more initialization + var axType = coerce('type'); + if(axType === '-') { + if(options.data) __setAutoType_774(containerOut, options.data); - // if y is between curr_y and last_y, and - // x is to the right of the boundary created by the line - if ((curr_y - y > eps) != (last_y - y > eps) && - (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside + if(containerOut.type === '-') { + containerOut.type = 'linear'; + } + else { + // copy autoType back to input axis + // note that if this object didn't exist + // in the input layout, we have to put it in + // this happens in the main supplyDefaults function + axType = containerIn.type = containerOut.type; + } + } - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; -} + coerce('smoothing'); + coerce('cheatertype'); -var _$Epsilon_297 = Epsilon; + coerce('showticklabels'); + coerce('labelprefix', letter + ' = '); + coerce('labelsuffix'); + coerce('showtickprefix'); + coerce('showticksuffix'); -// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + coerce('separatethousands'); + coerce('tickformat'); + coerce('exponentformat'); + coerce('showexponent'); + coerce('categoryorder'); -// -// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon) -// + coerce('tickmode'); + coerce('tickvals'); + coerce('ticktext'); + coerce('tick0'); + coerce('dtick'); -var GeoJSON = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool, geojson){ + if(containerOut.tickmode === 'array') { + coerce('arraytick0'); + coerce('arraydtick'); + } - // converts list of LineString's to segments - function GeoPoly(coords){ - // check for empty coords - if (coords.length <= 0) - return PolyBool.segments({ inverted: false, regions: [] }); + coerce('labelpadding'); - // 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] }); - } + containerOut._hovertitle = letter; - // 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]))); + if(axType === 'date') { + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleDefaults'); + handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar); + } - return out; - } + // we need some of the other functions setConvert attaches, but for + // path finding, override pixel scaling to simple passthrough (identity) + _$setConvert_665(containerOut, options.fullLayout); + containerOut.c2p = _$lib_601.identity; - 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'); - }, + var dfltColor = coerce('color', options.dfltColor); + // if axis.color was provided, use it for fonts too; otherwise, + // inherit from global font color in case that was provided. + var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color; - // 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)); + coerce('title'); + _$lib_601.coerceFont(coerce, 'titlefont', { + family: font.family, + size: Math.round(font.size * 1.2), + color: dfltFontColor + }); - // 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); - } + coerce('titleoffset'); - // calculate inside heirarchy - // - // _____________________ _______ roots -> A -> F - // | A | | F | | | - // | _______ _______ | | ___ | +-- B +-- G - // | | B | | C | | | | | | | | - // | | ___ | | ___ | | | | | | | +-- D - // | | | D | | | | E | | | | | G | | | - // | | |___| | | |___| | | | | | | +-- C - // | |_______| |_______| | | |___| | | - // |_____________________| |_______| +-- E + coerce('tickangle'); - function newNode(region){ - return { - region: region, - children: [] - }; - } + var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range)); - var roots = newNode(null); + if(autoRange) coerce('rangemode'); - 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; - } - } + coerce('range'); + containerOut.cleanRange(); - // 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--; - } - } + coerce('fixedrange'); - // now we can add ourselves - root.children.push(node); - } + _$handleTickValueDefaults_668(containerIn, containerOut, coerce, axType); + _$handleTickLabelDefaults_666(containerIn, containerOut, coerce, axType, options); + _$handleCategoryOrderDefaults_651(containerIn, containerOut, coerce, { + data: options.data, + dataAttr: letter + }); - // 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); - } + var gridColor = coerce2('gridcolor', addOpacity(dfltColor, 0.3)); + var gridWidth = coerce2('gridwidth'); + var showGrid = coerce('showgrid'); - // 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 + if(!showGrid) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; + } - // while we're at it, exteriors are counter-clockwise, and interiors are clockwise + var startLineColor = coerce2('startlinecolor', dfltColor); + var startLineWidth = coerce2('startlinewidth', gridWidth); + var showStartLine = coerce('startline', containerOut.showgrid || !!startLineColor || !!startLineWidth); - 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; - } + if(!showStartLine) { + delete containerOut.startlinecolor; + delete containerOut.startlinewidth; + } - var geopolys = []; + var endLineColor = coerce2('endlinecolor', dfltColor); + var endLineWidth = coerce2('endlinewidth', gridWidth); + var showEndLine = coerce('endline', containerOut.showgrid || !!endLineColor || !!endLineWidth); - 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])); - } + if(!showEndLine) { + delete containerOut.endlinecolor; + delete containerOut.endlinewidth; + } - 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); - } + if(!showGrid) { + delete containerOut.gridcolor; + delete containerOut.gridWidth; + } else { + coerce('minorgridcount'); + coerce('minorgridwidth', gridWidth); + coerce('minorgridcolor', addOpacity(gridColor, 0.06)); - // root nodes are exterior - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); + if(!containerOut.minorgridcount) { + delete containerOut.minorgridwidth; + delete containerOut.minorgridcolor; + } + } - // lastly, construct the approrpriate GeoJSON object + if(containerOut.showticklabels === 'none') { + delete containerOut.tickfont; + delete containerOut.tickangle; + delete containerOut.showexponent; + delete containerOut.exponentformat; + delete containerOut.tickformat; + delete containerOut.showticksuffix; + delete containerOut.showtickprefix; + } - 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 - }; - } -}; + if(!containerOut.showticksuffix) { + delete containerOut.ticksuffix; + } -var _$GeoJSON_298 = GeoJSON; + if(!containerOut.showtickprefix) { + delete containerOut.tickprefix; + } -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs + // It needs to be coerced, then something above overrides this deep in the axis code, + // but no, we *actually* want to coerce this. + coerce('tickmode'); -// -// simple linked list implementation that allows you to traverse down nodes and save positions -// + if(!containerOut.title || (containerOut.title && containerOut.title.length === 0)) { + delete containerOut.titlefont; + delete containerOut.titleoffset; + } -var LinkedList = { - create: function(){ - var my = { - root: { root: true, next: null }, - exists: function(node){ - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function(){ - return my.root.next === null; - }, - getHead: function(){ - return my.root.next; - }, - insertBefore: function(node, check){ - var last = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)){ - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check){ - var prev = my.root; - var here = my.root.next; - while (here !== null){ - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node){ - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data){ - data.prev = null; - data.next = null; - data.remove = function(){ - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } + return containerOut; }; -var _$LinkedList_300 = LinkedList; - -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs - -// -// this is the core work-horse -// +function __setAutoType_774(ax, data) { + // new logic: let people specify any type they want, + // only autotype if type is '-' + if(ax.type !== '-') return; -/* removed: var _$LinkedList_300 = require('./linked-list'); */; + var id = ax._id, + axLetter = id.charAt(0); -function Intersecter(selfIntersection, eps, buildLog){ - // selfIntersection is true/false depending on the phase of the overall algorithm + var calAttr = axLetter + 'calendar', + calendar = ax[calAttr]; - // - // segment creation - // + ax.type = _$autoType_648(data, calendar); +} - function segmentNew(start, end){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: null, // is there fill above us? - below: null // is there fill below us? - }, - otherFill: null - }; - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function segmentCopy(start, end, seg){ - return { - id: buildLog ? buildLog.segmentId() : -1, - start: start, - end: end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } +'use strict'; - // - // event logic - // +/* removed: var _$handleAxisDefaults_774 = require('./axis_defaults'); */; - var event_root = _$LinkedList_300.create(); +var _$handleABDefaults_769 = function handleABDefaults(traceIn, traceOut, fullLayout, coerce, dfltColor) { + var a = coerce('a'); - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){ - // compare the selected points first - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - // the selected points are the same + if(!a) { + coerce('da'); + coerce('a0'); + } - if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too... - return 0; // then the segments are equal + var b = coerce('b'); - if (p1_isStart !== p2_isStart) // if one is a start and the other isn't... - return p1_isStart ? 1 : -1; // favor the one that isn't the start + if(!b) { + coerce('db'); + coerce('b0'); + } - // otherwise, we'll have to calculate which one is below the other manually - return eps.pointAboveOrOnLine(p1_2, - p2_isStart ? p2_1 : p2_2, // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } + mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor); - function eventAdd(ev, other_pt){ - event_root.insertBefore(ev, function(here){ - // should ev be inserted before here? - var comp = eventCompare( - ev .isStart, ev .pt, other_pt, - here.isStart, here.pt, here.other.pt - ); - return comp < 0; - }); - } + return; +}; - function eventAddSegmentStart(seg, primary){ - var ev_start = _$LinkedList_300.node({ - isStart: true, - pt: seg.start, - seg: seg, - primary: primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } +function mimickAxisDefaults(traceIn, traceOut, fullLayout, dfltColor) { + var axesList = ['aaxis', 'baxis']; - function eventAddSegmentEnd(ev_start, seg, primary){ - var ev_end = _$LinkedList_300.node({ - isStart: false, - pt: seg.end, - seg: seg, - primary: primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } + axesList.forEach(function(axName) { + var axLetter = axName.charAt(0); + var axIn = traceIn[axName] || {}; + var axOut = {}; - function eventAddSegment(seg, primary){ - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } + var defaultOptions = { + tickfont: 'x', + id: axLetter + 'axis', + letter: axLetter, + font: traceOut.font, + name: axName, + data: traceIn[axLetter], + calendar: traceOut.calendar, + dfltColor: dfltColor, + bgColor: fullLayout.paper_bgcolor, + fullLayout: fullLayout + }; - function eventUpdateEnd(ev, end){ - // slides an end backwards - // (start)------------(end) to: - // (start)---(end) + _$handleAxisDefaults_774(axIn, axOut, defaultOptions); - if (buildLog) - buildLog.segmentChop(ev.seg, end); + axOut._categories = axOut._categories || []; - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } + traceOut[axName] = axOut; - function eventDivide(ev, pt){ - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } + // so we don't have to repeat autotype unnecessarily, + // copy an autotype back to traceIn + if(!traceIn[axName] && axIn.type !== '-') { + traceIn[axName] = {type: axIn.type}; + } + }); +} - function calculate(primaryPolyInverted, secondaryPolyInverted){ - // if selfIntersection is true then there is no secondary polygon, so that isn't used +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // - // status logic - // - var status_root = _$LinkedList_300.create(); +'use strict'; - function statusCompare(ev1, ev2){ - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; +var _$handleXYDefaults_796 = function handleXYDefaults(traceIn, traceOut, coerce) { + var x = coerce('x'); + var y = coerce('y'); - if (eps.pointsCollinear(a1, b1, b2)){ - if (eps.pointsCollinear(a2, b1, b2)) - return 1;//eventCompare(true, a1, a2, true, b1, b2); - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } + traceOut._cheater = !x; - function statusFindSurrounding(ev){ - return status_root.findTransition(function(here){ - var comp = statusCompare(ev, here.ev); - return comp > 0; - }); - } + return !!x || !!y; +}; - function checkIntersection(ev1, ev2){ - // returns the segment equal to ev1, or false if nothing equal +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; - if (buildLog) - buildLog.checkIntersection(seg1, seg2); +'use strict'; - var i = eps.linesIntersect(a1, a2, b1, b2); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleXYDefaults_796 = require('./xy_defaults'); */; +/* removed: var _$handleABDefaults_769 = require('./ab_defaults'); */; +/* removed: var _$attributes_771 = require('./attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; - if (i === false){ - // segments are parallel or coincident +var _$supplyDefaults_786 = function supplyDefaults(traceIn, traceOut, dfltColor, fullLayout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_771, attr, dflt); + } - // if points aren't collinear, then the segments are parallel, so no intersections - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - // otherwise, segments are on top of each other somehow (aka coincident) + traceOut._clipPathId = 'clip' + traceOut.uid + 'carpet'; - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; // segments touch at endpoints... no intersection + var defaultColor = coerce('color', _$attributes_472.defaultLine); + _$lib_601.coerceFont(coerce, 'font'); - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); + coerce('carpet'); - if (a1_equ_b1 && a2_equ_b2) - return ev2; // segments are exactly equal + _$handleABDefaults_769(traceIn, traceOut, fullLayout, coerce, defaultColor); - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); + if(!traceOut.a || !traceOut.b) { + traceOut.visible = false; + return; + } - // handy for debugging: - // buildLog.log({ - // a1_equ_b1: a1_equ_b1, - // a2_equ_b2: a2_equ_b2, - // a1_between: a1_between, - // a2_between: a2_between - // }); + if(traceOut.a.length < 3) { + traceOut.aaxis.smoothing = 0; + } - if (a1_equ_b1){ - if (a2_between){ - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)---(b2) - eventDivide(ev1, b2); - } - return ev2; - } - else if (a1_between){ - if (!a2_equ_b2){ - // make a2 equal to b2 - if (a2_between){ - // (a1)---(a2) - // (b1)-----------------(b2) - eventDivide(ev2, a2); - } - else{ - // (a1)----------(a2) - // (b1)----------(b2) - eventDivide(ev1, b2); - } - } + if(traceOut.b.length < 3) { + traceOut.baxis.smoothing = 0; + } - // (a1)---(a2) - // (b1)----------(b2) - eventDivide(ev2, a1); - } - } - else{ - // otherwise, lines intersect at i.pt, which may or may not be between the endpoints + // 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 len = _$handleXYDefaults_796(traceIn, traceOut, coerce); - // is A divided between its endpoints? (exclusive) - if (i.alongA === 0){ - if (i.alongB === -1) // yes, at exactly b1 - eventDivide(ev1, b1); - else if (i.alongB === 0) // yes, somewhere between B's endpoints - eventDivide(ev1, i.pt); - else if (i.alongB === 1) // yes, at exactly b2 - eventDivide(ev1, b2); - } + if(traceOut._cheater) { + coerce('cheaterslope'); + } - // is B divided between its endpoints? (exclusive) - if (i.alongB === 0){ - if (i.alongA === -1) // yes, at exactly a1 - eventDivide(ev2, a1); - else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) // yes, at exactly a2 - eventDivide(ev2, a2); - } - } - return false; - } + if(!len) { + traceOut.visible = false; + } +}; - // - // main event loop - // - var segments = []; - while (!event_root.isEmpty()){ - var ev = event_root.getHead(); +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (buildLog) - buildLog.vert(ev.pt[0]); +'use strict'; - if (ev.isStart){ +var _$makePath_790 = function makePath(xp, yp, isBicubic) { + // Prevent d3 errors that would result otherwise: + if(xp.length === 0) return ''; - if (buildLog) - buildLog.segmentNew(ev.seg, ev.primary); + var i, path = []; + var stride = isBicubic ? 3 : 1; + for(i = 0; i < xp.length; i += stride) { + path.push(xp[i] + ',' + yp[i]); - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; + if(isBicubic && i < xp.length - stride) { + path.push('C'); + path.push([ + xp[i + 1] + ',' + yp[i + 1], + xp[i + 2] + ',' + yp[i + 2] + ' ', + ].join(' ')); + } + } + return path.join(isBicubic ? '' : 'L'); +}; - if (buildLog){ - buildLog.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - function checkBothIntersections(){ - if (above){ - var eve = checkIntersection(ev, above); - if (eve) - return eve; - } - if (below) - return checkIntersection(ev, below); - return false; - } +'use strict'; - var eve = checkBothIntersections(); - if (eve){ - // ev and eve are equal - // we'll keep eve and throw away ev +var __isArrayOrTypedArray_791 = _$lib_601.isArrayOrTypedArray; - // merge ev.seg's fill information into eve.seg +/* + * Map an array of x or y coordinates (c) to screen-space pixel coordinates (p). + * The output array is optional, but if provided, it will be reused without + * reallocation to the extent possible. + */ +var _$mapArray_791 = function mapArray(out, data, func) { + var i; - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + if(!__isArrayOrTypedArray_791(out)) { + // If not an array, make it an array: + out = []; + } else if(out.length > data.length) { + // If too long, truncate. (If too short, it will grow + // automatically so we don't care about that case) + out = out.slice(0, data.length); + } - // merge two segments that belong to the same polygon - // think of this as sandwiching two segments together, where `eve.seg` is - // the bottom -- this will cause the above fill flag to toggle - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } - else{ - // merge two segments that belong to different polygons - // each segment has distinct knowledge, so no special logic is needed - // note that this can only happen once per segment in this phase, because we - // are guaranteed that all self-intersections are gone - eve.seg.otherFill = ev.seg.myFill; - } + for(i = 0; i < data.length; i++) { + out[i] = func(data[i]); + } - if (buildLog) - buildLog.segmentUpdate(eve.seg); + return out; +}; - ev.other.remove(); - ev.remove(); - } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (event_root.getHead() !== ev){ - // something was inserted before us in the event queue, so loop back around and - // process it before continuing - if (buildLog) - buildLog.rewind(ev.seg); - continue; - } - // - // calculate fill flags - // - if (selfIntersection){ - var toggle; // are we a toggling edge? - if (ev.seg.myFill.below === null) // if we are a new segment... - toggle = true; // then we toggle - else // we are a segment that has previous knowledge from a division - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle +'use strict'; - // next, calculate whether we are filled below us - if (!below){ // if nothing is below us... - // we are filled below us if the polygon is inverted - ev.seg.myFill.below = primaryPolyInverted; - } - else{ - // otherwise, we know the answer -- it's the same if whatever is below - // us is filled above it - ev.seg.myFill.below = below.seg.myFill.above; - } +var _$orientText_792 = 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; - // since now we know if we're filled below us, we can calculate whether - // we're filled above us by applying toggle to whatever is below us - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } - else{ - // now we fill in any missing transition information, since we are all-knowing - // at this point + 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); + } - if (ev.seg.otherFill === null){ - // if we don't have other information, then we need to figure out if we're - // inside the other polygon - var inside; - if (!below){ - // if nothing is below us, then we're inside if the other polygon is - // inverted - inside = - ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } - else{ // otherwise, something is below us - // so copy the below segment's other polygon's above - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } + var angle = Math.atan2(dy, dx) * 180 / Math.PI; + if(angle < -90) { + angle += 180; + flip = -flip; + } else if(angle > 90) { + angle -= 180; + flip = -flip; + } - if (buildLog){ - buildLog.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } + return { + angle: angle, + flip: flip, + p: trace.c2p(xy, xaxis, yaxis), + offsetMultplier: offsetMultiplier + }; +}; - // insert the status and remember it for later removal - ev.other.status = surrounding.insert(_$LinkedList_300.node({ ev: ev })); - } - else{ - var st = ev.status; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if (st === null){ - throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - } - // removing the status will create two new adjacent edges, so we'll need to check - // for those - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); +'use strict'; - if (buildLog) - buildLog.statusRemove(st.ev.seg); +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$mapArray_791 = require('./map_1d_array'); */; +/* removed: var _$makePath_790 = require('./makepath'); */; +/* removed: var _$orientText_792 = require('./orient_text'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; - // remove the status - st.remove(); +var _$plot_793 = function plot(gd, plotinfo, cdcarpet) { + for(var i = 0; i < cdcarpet.length; i++) { + __plotOne_793(gd, plotinfo, cdcarpet[i]); + } +}; - // if we've reached this point, we've calculated everything there is to know, so - // save the segment for reporting - if (!ev.primary){ - // make sure `seg.myFill` actually points to the primary polygon though - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } +function __plotOne_793(gd, plotinfo, cd) { + var t = cd[0]; + var trace = cd[0].trace, + xa = plotinfo.xaxis, + ya = plotinfo.yaxis, + aax = trace.aaxis, + bax = trace.baxis, + fullLayout = gd._fullLayout; - // remove the event and continue - event_root.getHead().remove(); - } + var gridLayer = plotinfo.plot.selectAll('.carpetlayer'); + var clipLayer = fullLayout._clips; - if (buildLog) - buildLog.done(); + var axisLayer = _$lib_601.ensureSingle(gridLayer, 'g', 'carpet' + trace.uid).classed('trace', true); + var minorLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'minorlayer'); + var majorLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'majorlayer'); + var boundaryLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'boundarylayer'); + var labelLayer = _$lib_601.ensureSingle(axisLayer, 'g', 'labellayer'); - return segments; - } + axisLayer.style('opacity', trace.opacity); - // return the appropriate API depending on what we're doing - if (!selfIntersection){ - // performing combination of polygons, so only deal with already-processed segments - return { - calculate: function(segments1, inverted1, segments2, inverted2){ - // segmentsX come from the self-intersection API, or this API - // invertedX is whether we treat that list of segments as an inverted polygon or not - // returns segments that can be used for further operations - segments1.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg){ - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } + drawGridLines(xa, ya, majorLayer, aax, 'a', aax._gridlines, true); + drawGridLines(xa, ya, majorLayer, bax, 'b', bax._gridlines, true); + drawGridLines(xa, ya, minorLayer, aax, 'a', aax._minorgridlines, true); + drawGridLines(xa, ya, minorLayer, bax, 'b', bax._minorgridlines, true); - // otherwise, performing self-intersection, so deal with regions - return { - addRegion: function(region){ - // regions are a list of points: - // [ [0, 0], [100, 0], [50, 100] ] - // you can add multiple regions before running calculate - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++){ - pt1 = pt2; - pt2 = region[i]; + // NB: These are not ommitted if the lines are not active. The joins must be executed + // in order for them to get cleaned up without a full redraw + drawGridLines(xa, ya, boundaryLayer, aax, 'a-boundary', aax._boundarylines); + drawGridLines(xa, ya, boundaryLayer, bax, 'b-boundary', bax._boundarylines); - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) // points are equal, so we have a zero-length segment - continue; // just skip it + var labelOrientationA = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, aax._labels, 'a-label'); + var labelOrientationB = drawAxisLabels(gd, xa, ya, trace, t, labelLayer, bax._labels, 'b-label'); - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted){ - // is the polygon inverted? - // returns segments - return calculate(inverted, false); - } - }; -} + drawAxisTitles(gd, labelLayer, trace, t, xa, ya, labelOrientationA, labelOrientationB); -var _$Intersecter_299 = Intersecter; + drawClipPath(trace, t, clipLayer, xa, ya); +} -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +function drawClipPath(trace, t, layer, xaxis, yaxis) { + var seg, xp, yp, i; -// -// converts a list of segments into a list of regions, while also removing unnecessary verticies -// + var clip = layer.select('#' + trace._clipPathId); -function SegmentChainer(segments, eps, buildLog){ - var chains = []; - var regions = []; + if(!clip.size()) { + clip = layer.append('clipPath') + .classed('carpetclip', true); + } - segments.forEach(function(seg){ - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)){ - console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' + - 'probably too small or too large'); - return; - } + var path = _$lib_601.ensureSingle(clip, 'path', 'carpetboundary'); + var segments = t.clipsegments; + var segs = []; - if (buildLog) - buildLog.chainStart(seg); + for(i = 0; i < segments.length; i++) { + seg = segments[i]; + xp = _$mapArray_791([], seg.x, xaxis.c2p); + yp = _$mapArray_791([], seg.y, yaxis.c2p); + segs.push(_$makePath_790(xp, yp, seg.bicubic)); + } - // search for two chains that this segment matches - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index, matches_head, matches_pt1){ - // return true if we've matched twice - next_match.index = index; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match){ - next_match = second_match; - return false; - } - next_match = null; - return true; // we've matched twice, we're done here - } - for (var i = 0; i < chains.length; i++){ - var chain = chains[i]; - var head = chain[0]; - var head2 = chain[1]; - var tail = chain[chain.length - 1]; - var tail2 = chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)){ - if (setMatch(i, true, true)) - break; - } - else if (eps.pointsSame(head, pt2)){ - if (setMatch(i, true, false)) - break; - } - else if (eps.pointsSame(tail, pt1)){ - if (setMatch(i, false, true)) - break; - } - else if (eps.pointsSame(tail, pt2)){ - if (setMatch(i, false, false)) - break; - } - } + // This could be optimized ever so slightly to avoid no-op L segments + // at the corners, but it's so negligible that I don't think it's worth + // the extra complexity + var clipPathData = 'M' + segs.join('L') + 'Z'; + clip.attr('id', trace._clipPathId); + path.attr('d', clipPathData); +} - if (next_match === first_match){ - // we didn't match anything, so create a new chain - chains.push([ pt1, pt2 ]); - if (buildLog) - buildLog.chainNew(pt1, pt2); - return; - } +function drawGridLines(xaxis, yaxis, layer, axis, axisLetter, gridlines) { + var lineClass = 'const-' + axisLetter + '-lines'; + var gridJoin = layer.selectAll('.' + lineClass).data(gridlines); - if (next_match === second_match){ - // we matched a single chain + gridJoin.enter().append('path') + .classed(lineClass, true) + .style('vector-effect', 'non-scaling-stroke'); - if (buildLog) - buildLog.chainMatch(first_match.index); + gridJoin.each(function(d) { + var gridline = d; + var x = gridline.x; + var y = gridline.y; - // add the other point to the apporpriate end, and check to see if we've closed the - // chain into a loop + var xp = _$mapArray_791([], x, xaxis.c2p); + var yp = _$mapArray_791([], y, yaxis.c2p); - var index = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc - var addToHead = first_match.matches_head; // if we matched at head, then add to the head + var path = 'M' + _$makePath_790(xp, yp, gridline.smoothing); - var chain = chains[index]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + var el = _$d3_130.select(this); - if (eps.pointsCollinear(grow2, grow, pt)){ - // grow isn't needed because it's directly between grow2 and pt: - // grow2 ---grow---> pt - if (addToHead){ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, pt); - chain.shift(); - } - else{ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; // old grow is gone... new grow is what grow2 was - } + el.attr('d', path) + .style('stroke-width', gridline.width) + .style('stroke', gridline.color) + .style('fill', 'none'); + }); - if (eps.pointsSame(oppo, pt)){ - // we're closing the loop, so remove chain from chains - chains.splice(index, 1); + gridJoin.exit().remove(); +} - if (eps.pointsCollinear(oppo2, oppo, grow)){ - // oppo isn't needed because it's directly between oppo2 and grow: - // oppo2 ---oppo--->grow - if (addToHead){ - if (buildLog) - buildLog.chainRemoveTail(first_match.index, grow); - chain.pop(); - } - else{ - if (buildLog) - buildLog.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } +function drawAxisLabels(gd, xaxis, yaxis, trace, t, layer, labels, labelClass) { + var labelJoin = layer.selectAll('text.' + labelClass).data(labels); - if (buildLog) - buildLog.chainClose(first_match.index); + labelJoin.enter().append('text') + .classed(labelClass, true); - // we have a closed chain! - regions.push(chain); - return; - } + var maxExtent = 0; + var labelOrientation = {}; - // not closing a loop, so just add it to the apporpriate side - if (addToHead){ - if (buildLog) - buildLog.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } - else{ - if (buildLog) - buildLog.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } + labelJoin.each(function(label, i) { + // Most of the positioning is done in calc_labels. Only the parts that depend upon + // the screen space representation of the x and y axes are here: + var orientation; + if(label.axis.tickangle === 'auto') { + orientation = _$orientText_792(trace, xaxis, yaxis, label.xy, label.dxy); + } else { + var angle = (label.axis.tickangle + 180.0) * Math.PI / 180.0; + orientation = _$orientText_792(trace, xaxis, yaxis, label.xy, [Math.cos(angle), Math.sin(angle)]); + } - // otherwise, we matched two chains, so we need to combine those chains together + if(!i) { + // TODO: offsetMultiplier? Not currently used anywhere... + labelOrientation = {angle: orientation.angle, flip: orientation.flip}; + } + var direction = (label.endAnchor ? -1 : 1) * orientation.flip; - function reverseChain(index){ - if (buildLog) - buildLog.chainReverse(index); - chains[index].reverse(); // gee, that's easy - } + var labelEl = _$d3_130.select(this) + .attr({ + 'text-anchor': direction > 0 ? 'start' : 'end', + 'data-notex': 1 + }) + .call(_$drawing_498.font, label.font) + .text(label.text) + .call(_$svg_text_utils_625.convertToTspans, gd); - function appendChain(index1, index2){ - // index1 gets index2 appended to it, and index2 is removed - var chain1 = chains[index1]; - var chain2 = chains[index2]; - var tail = chain1[chain1.length - 1]; - var tail2 = chain1[chain1.length - 2]; - var head = chain2[0]; - var head2 = chain2[1]; + var bbox = _$drawing_498.bBox(this); - if (eps.pointsCollinear(tail2, tail, head)){ - // tail isn't needed because it's directly between tail2 and head - // tail2 ---tail---> head - if (buildLog) - buildLog.chainRemoveTail(index1, tail); - chain1.pop(); - tail = tail2; // old tail is gone... new tail is what tail2 was - } + labelEl.attr('transform', + // Translate to the correct point: + 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + + // Rotate to line up with grid line tangent: + 'rotate(' + orientation.angle + ')' + + // Adjust the baseline and indentation: + 'translate(' + label.axis.labelpadding * direction + ',' + bbox.height * 0.3 + ')' + ); - if (eps.pointsCollinear(tail, head, head2)){ - // head isn't needed because it's directly between tail and head2 - // tail ---head---> head2 - if (buildLog) - buildLog.chainRemoveHead(index2, head); - chain2.shift(); - } + maxExtent = Math.max(maxExtent, bbox.width + label.axis.labelpadding); + }); - if (buildLog) - buildLog.chainJoin(index1, index2); - chains[index1] = chain1.concat(chain2); - chains.splice(index2, 1); - } + labelJoin.exit().remove(); - var F = first_match.index; - var S = second_match.index; + labelOrientation.maxExtent = maxExtent; + return labelOrientation; +} - if (buildLog) - buildLog.chainConnect(F, S); +function drawAxisTitles(gd, layer, trace, t, xa, ya, labelOrientationA, labelOrientationB) { + var a, b, xy, dxy; - var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed - if (first_match.matches_head){ - if (second_match.matches_head){ - if (reverseF){ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(F); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - // <<<< F <<<< --- >>>> S >>>> - reverseChain(S); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - } - else{ - if (second_match.matches_head){ - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - else{ - if (reverseF){ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(F); - // <<<< F <<<< --- <<<< S <<<< logically same as: - // >>>> S >>>> --- >>>> F >>>> - appendChain(S, F); - } - else{ - // >>>> F >>>> --- <<<< S <<<< - reverseChain(S); - // >>>> F >>>> --- >>>> S >>>> - appendChain(F, S); - } - } - } - }); + a = 0.5 * (trace.a[0] + trace.a[trace.a.length - 1]); + b = trace.b[0]; + xy = trace.ab2xy(a, b, true); + dxy = trace.dxyda_rough(a, b); + if(labelOrientationA.angle === undefined) { + _$lib_601.extendFlat(labelOrientationA, _$orientText_792(trace, xa, ya, xy, trace.dxydb_rough(a, b))); + } + drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.aaxis, xa, ya, labelOrientationA, 'a-title'); - return regions; + a = trace.a[0]; + b = 0.5 * (trace.b[0] + trace.b[trace.b.length - 1]); + xy = trace.ab2xy(a, b, true); + dxy = trace.dxydb_rough(a, b); + if(labelOrientationB.angle === undefined) { + _$lib_601.extendFlat(labelOrientationB, _$orientText_792(trace, xa, ya, xy, trace.dxyda_rough(a, b))); + } + drawAxisTitle(gd, layer, trace, t, xy, dxy, trace.baxis, xa, ya, labelOrientationB, 'b-title'); } -var _$SegmentChainer_301 = SegmentChainer; +var lineSpacing = _$alignment_573.LINE_SPACING; +var midShift = ((1 - _$alignment_573.MID_SHIFT) / lineSpacing) + 1; -// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc -// MIT License -// Project Home: https://github.com/voidqk/polybooljs +function drawAxisTitle(gd, layer, trace, t, xy, dxy, axis, xa, ya, labelOrientation, labelClass) { + var data = []; + if(axis.title) data.push(axis.title); + var titleJoin = layer.selectAll('text.' + labelClass).data(data); + var offset = labelOrientation.maxExtent; -// -// filter a list of segments based on boolean operations -// + titleJoin.enter().append('text') + .classed(labelClass, true); -function select(segments, selection, buildLog){ - var result = []; - segments.forEach(function(seg){ - var index = - (seg.myFill.above ? 8 : 0) + - (seg.myFill.below ? 4 : 0) + - ((seg.otherFill && seg.otherFill.above) ? 2 : 0) + - ((seg.otherFill && seg.otherFill.below) ? 1 : 0); - if (selection[index] !== 0){ - // copy the segment to the results, while also calculating the fill status - result.push({ - id: buildLog ? buildLog.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index] === 1, // 1 if filled above - below: selection[index] === 2 // 2 if filled below - }, - otherFill: null - }); - } - }); + // There's only one, but we'll do it as a join so it's updated nicely: + titleJoin.each(function() { + var orientation = _$orientText_792(trace, xa, ya, xy, dxy); - if (buildLog) - buildLog.selected(result); + if(['start', 'both'].indexOf(axis.showticklabels) === -1) { + offset = 0; + } - return result; -} + // In addition to the size of the labels, add on some extra padding: + var titleSize = axis.titlefont.size; + offset += titleSize + axis.titleoffset; -var SegmentSelector = { - union: function(segments, buildLog){ // primary | secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 2, 0, 0, - 1, 0, 1, 0, - 0, 0, 0, 0 - ], buildLog); - }, - intersect: function(segments, buildLog){ // primary & secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => yes filled below 2 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled below 2 - // 1 0 0 0 => no 0 - // 1 0 0 1 => no 0 - // 1 0 1 0 => yes filled above 1 - // 1 0 1 1 => yes filled above 1 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled below 2 - // 1 1 1 0 => yes filled above 1 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 0, 2, 0, 2, - 0, 0, 1, 1, - 0, 2, 1, 0 - ], buildLog); - }, - difference: function(segments, buildLog){ // primary - secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => no 0 - // 0 0 1 0 => no 0 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled below 2 - // 0 1 1 1 => no 0 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => yes filled above 1 - // 1 0 1 0 => no 0 - // 1 0 1 1 => no 0 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 0, 0, 0, - 2, 0, 2, 0, - 1, 1, 0, 0, - 0, 1, 2, 0 - ], buildLog); - }, - differenceRev: function(segments, buildLog){ // secondary - primary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => no 0 - // 0 1 0 1 => no 0 - // 0 1 1 0 => yes filled above 1 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => no 0 - // 1 0 0 1 => yes filled below 2 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => no 0 - // 1 1 1 0 => no 0 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 0, 0, 1, 1, - 0, 2, 0, 2, - 0, 0, 0, 0 - ], buildLog); - }, - xor: function(segments, buildLog){ // primary ^ secondary - // above1 below1 above2 below2 Keep? Value - // 0 0 0 0 => no 0 - // 0 0 0 1 => yes filled below 2 - // 0 0 1 0 => yes filled above 1 - // 0 0 1 1 => no 0 - // 0 1 0 0 => yes filled below 2 - // 0 1 0 1 => no 0 - // 0 1 1 0 => no 0 - // 0 1 1 1 => yes filled above 1 - // 1 0 0 0 => yes filled above 1 - // 1 0 0 1 => no 0 - // 1 0 1 0 => no 0 - // 1 0 1 1 => yes filled below 2 - // 1 1 0 0 => no 0 - // 1 1 0 1 => yes filled above 1 - // 1 1 1 0 => yes filled below 2 - // 1 1 1 1 => no 0 - return select(segments, [ - 0, 2, 1, 0, - 2, 0, 0, 1, - 1, 0, 0, 2, - 0, 1, 2, 0 - ], buildLog); - } -}; + var labelNorm = labelOrientation.angle + (labelOrientation.flip < 0 ? 180 : 0); + var angleDiff = (labelNorm - orientation.angle + 450) % 360; + var reverseTitle = angleDiff > 90 && angleDiff < 270; -var _$SegmentSelector_302 = SegmentSelector; + var el = _$d3_130.select(this); -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs - */ + el.text(axis.title || '') + .call(_$svg_text_utils_625.convertToTspans, gd); -/* removed: var _$BuildLog_296 = require('./lib/build-log'); */; -/* removed: var _$Epsilon_297 = require('./lib/epsilon'); */; -/* removed: var _$Intersecter_299 = require('./lib/intersecter'); */; -/* removed: var _$SegmentChainer_301 = require('./lib/segment-chainer'); */; -/* removed: var _$SegmentSelector_302 = require('./lib/segment-selector'); */; -/* removed: var _$GeoJSON_298 = require('./lib/geojson'); */; + if(reverseTitle) { + offset = (-_$svg_text_utils_625.lineCount(el) + midShift) * lineSpacing * titleSize - offset; + } -var buildLog = false; -var epsilon = _$Epsilon_297(); + el.attr('transform', + 'translate(' + orientation.p[0] + ',' + orientation.p[1] + ') ' + + 'rotate(' + orientation.angle + ') ' + + 'translate(0,' + offset + ')' + ) + .classed('user-select-none', true) + .attr('text-anchor', 'middle') + .call(_$drawing_498.font, axis.titlefont); + }); -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl){ - if (bl === true) - buildLog = _$BuildLog_296(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v){ - return epsilon.epsilon(v); - }, + titleJoin.exit().remove(); +} - // core API - segments: function(poly){ - var i = _$Intersecter_299(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2){ - var i3 = _$Intersecter_299(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_302.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - } - }, - selectIntersect: function(combined){ - return { - segments: _$SegmentSelector_302.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - } - }, - selectDifference: function(combined){ - return { - segments: _$SegmentSelector_302.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - } - }, - selectDifferenceRev: function(combined){ - return { - segments: _$SegmentSelector_302.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - } - }, - selectXor: function(combined){ - return { - segments: _$SegmentSelector_302.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - } - }, - polygon: function(segments){ - return { - regions: _$SegmentChainer_301(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - // GeoJSON converters - polygonFromGeoJSON: function(geojson){ - return _$GeoJSON_298.toPolygon(PolyBool, geojson); - }, - polygonToGeoJSON: function(poly){ - return _$GeoJSON_298.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); - } -}; +'use strict'; -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); -} +var Carpet = {}; -if (typeof window === 'object') - window.PolyBool = PolyBool; +Carpet.attributes = _$attributes_771; +Carpet.supplyDefaults = _$supplyDefaults_786; +Carpet.plot = _$plot_793; +Carpet.calc = _$calc_775; +Carpet.animatable = true; +Carpet.isContainer = true; // so carpet traces get `calc` before other traces + +Carpet.moduleType = 'trace'; +Carpet.name = 'carpet'; +Carpet.basePlotModule = _$cartesian_658; +Carpet.categories = ['cartesian', 'svg', 'carpet', 'carpetAxis', 'notLegendIsolatable']; +Carpet.meta = { + +}; -var _$PolyBool_295 = PolyBool; +var _$Carpet_788 = Carpet; -var _$polygon_551 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -50263,686 +52047,741 @@ var _$polygon_551 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var dot = _$matrix_545.dot; -var __BADNUM_551 = _$numerical_517.BADNUM; +var _$carpet_8 = _$Carpet_788; -var polygon = _$polygon_551 = {}; +var _$topojsonClient_417 = { exports: {} }; +// https://github.com/topojson/topojson-client Version 2.1.0. Copyright 2016 Mike Bostock. +(function (global, factory) { + typeof _$topojsonClient_417.exports === 'object' && "object" !== 'undefined' ? factory(_$topojsonClient_417.exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.topojson = global.topojson || {}))); +}(this, (function (exports) { 'use strict'; -/** - * Turn an array of [x, y] pairs into a polygon object - * that can test if points are inside it - * - * @param ptsIn Array of [x, y] pairs - * - * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains} - * (x|y)(min|max) are the bounding rect of the polygon - * pts is the original array, with the first pair repeated at the end - * contains is a function: (pt, omitFirstEdge) - * pt is the [x, y] pair to test - * omitFirstEdge truthy means points exactly on the first edge don't - * count. This is for use adding one polygon to another so we - * don't double-count the edge where they meet. - * returns boolean: is pt inside the polygon (including on its edges) - */ -polygon.tester = function tester(ptsIn) { - if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn); +var identity = function(x) { + return x; +}; + +var transform = function(topology) { + if ((transform = topology.transform) == null) return identity; + var transform, + x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + point[0] = (x0 += point[0]) * kx + dx; + point[1] = (y0 += point[1]) * ky + dy; + return point; + }; +}; + +var bbox = function(topology) { + var bbox = topology.bbox; + + function bboxPoint(p0) { + p1[0] = p0[0], p1[1] = p0[1], t(p1); + if (p1[0] < x0) x0 = p1[0]; + if (p1[0] > x1) x1 = p1[0]; + if (p1[1] < y0) y0 = p1[1]; + if (p1[1] > y1) y1 = p1[1]; + } + + function bboxGeometry(o) { + switch (o.type) { + case "GeometryCollection": o.geometries.forEach(bboxGeometry); break; + case "Point": bboxPoint(o.coordinates); break; + case "MultiPoint": o.coordinates.forEach(bboxPoint); break; + } + } + + if (!bbox) { + var t = transform(topology), p0, p1 = new Array(2), name, + x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0; + + topology.arcs.forEach(function(arc) { + var i = -1, n = arc.length; + while (++i < n) { + p0 = arc[i], p1[0] = p0[0], p1[1] = p0[1], t(p1, i); + if (p1[0] < x0) x0 = p1[0]; + if (p1[0] > x1) x1 = p1[0]; + if (p1[1] < y0) y0 = p1[1]; + if (p1[1] > y1) y1 = p1[1]; + } + }); + + for (name in topology.objects) { + bboxGeometry(topology.objects[name]); + } + + bbox = topology.bbox = [x0, y0, x1, y1]; + } + + return bbox; +}; + +var reverse = function(array, n) { + var t, j = array.length, i = j - n; + while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; +}; + +var feature = function(topology, o) { + return o.type === "GeometryCollection" + ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })} + : feature$1(topology, o); +}; + +function feature$1(topology, o) { + var id = o.id, + bbox = o.bbox, + properties = o.properties == null ? {} : o.properties, + geometry = object(topology, o); + return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} + : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} + : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; +} + +function object(topology, o) { + var transformPoint = transform(topology), + arcs = topology.arcs; + + function arc(i, points) { + if (points.length) points.pop(); + for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { + points.push(transformPoint(a[k].slice(), k)); + } + if (i < 0) reverse(points, n); + } - var pts = ptsIn.slice(), - xmin = pts[0][0], - xmax = xmin, - ymin = pts[0][1], - ymax = ymin, - i; + function point(p) { + return transformPoint(p.slice()); + } - pts.push(pts[0]); - for(i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } + function line(arcs) { + var points = []; + for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); + if (points.length < 2) points.push(points[0].slice()); + return points; + } - // do we have a rectangle? Handle this here, so we can use the same - // tester for the rectangular case without sacrificing speed + function ring(arcs) { + var points = line(arcs); + while (points.length < 4) points.push(points[0].slice()); + return points; + } - var isRect = false, - rectFirstEdgeTest; + function polygon(arcs) { + return arcs.map(ring); + } - if(pts.length === 5) { - if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz - if(pts[2][0] === pts[3][0] && - pts[0][1] === pts[3][1] && - pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; }; - } - } - else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert - if(pts[2][1] === pts[3][1] && - pts[0][0] === pts[3][0] && - pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; }; - } - } + function geometry(o) { + var type = o.type, coordinates; + switch (type) { + case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; + case "Point": coordinates = point(o.coordinates); break; + case "MultiPoint": coordinates = o.coordinates.map(point); break; + case "LineString": coordinates = line(o.arcs); break; + case "MultiLineString": coordinates = o.arcs.map(line); break; + case "Polygon": coordinates = polygon(o.arcs); break; + case "MultiPolygon": coordinates = o.arcs.map(polygon); break; + default: return null; } + return {type: type, coordinates: coordinates}; + } - function rectContains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + return geometry(o); +} - if(x === __BADNUM_551 || x < xmin || x > xmax || y === __BADNUM_551 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } - if(omitFirstEdge && rectFirstEdgeTest(pt)) return false; +var stitch = function(topology, arcs) { + var stitchedArcs = {}, + fragmentByStart = {}, + fragmentByEnd = {}, + fragments = [], + emptyIndex = -1; - return true; + // Stitch empty arcs first, since they may be subsumed by other arcs. + arcs.forEach(function(i, j) { + var arc = topology.arcs[i < 0 ? ~i : i], t; + if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { + t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; } + }); - function contains(pt, omitFirstEdge) { - var x = pt[0], - y = pt[1]; + arcs.forEach(function(i) { + var e = ends(i), + start = e[0], + end = e[1], + f, g; - if(x === __BADNUM_551 || x < xmin || x > xmax || y === __BADNUM_551 || y < ymin || y > ymax) { - // pt is outside the bounding box of polygon - return false; - } + if (f = fragmentByEnd[start]) { + delete fragmentByEnd[f.end]; + f.push(i); + f.end = end; + if (g = fragmentByStart[end]) { + delete fragmentByStart[g.start]; + var fg = g === f ? f : f.concat(g); + fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else if (f = fragmentByStart[end]) { + delete fragmentByStart[f.start]; + f.unshift(i); + f.start = start; + if (g = fragmentByEnd[start]) { + delete fragmentByEnd[g.end]; + var gf = g === f ? f : g.concat(f); + fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else { + f = [i]; + fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; + } + }); - var imax = pts.length, - x1 = pts[0][0], - y1 = pts[0][1], - crossings = 0, - i, - x0, - y0, - xmini, - ycross; + function ends(i) { + var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; + if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); + else p1 = arc[arc.length - 1]; + return i < 0 ? [p1, p0] : [p0, p1]; + } - for(i = 1; i < imax; i++) { - // find all crossings of a vertical line upward from pt with - // polygon segments - // crossings exactly at xmax don't count, unless the point is - // exactly on the segment, then it counts as inside. - x0 = x1; - y0 = y1; - x1 = pts[i][0]; - y1 = pts[i][1]; - xmini = Math.min(x0, x1); + function flush(fragmentByEnd, fragmentByStart) { + for (var k in fragmentByEnd) { + var f = fragmentByEnd[k]; + delete fragmentByStart[f.start]; + delete f.start; + delete f.end; + f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); + fragments.push(f); + } + } - // outside the bounding box of this segment, it's only a crossing - // if it's below the box. - if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; - } - else if(y < Math.min(y0, y1)) { - // don't count the left-most point of the segment as a crossing - // because we don't want to double-count adjacent crossings - // UNLESS the polygon turns past vertical at exactly this x - // Note that this is repeated below, but we can't factor it out - // because - if(x !== xmini) crossings++; - } - // inside the bounding box, check the actual line intercept - else { - // vertical segment - we know already that the point is exactly - // on the segment, so mark the crossing as exactly at the point. - if(x1 === x0) ycross = y; - // any other angle - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); + flush(fragmentByEnd, fragmentByStart); + flush(fragmentByStart, fragmentByEnd); + arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); - // exactly on the edge: counts as inside the polygon, unless it's the - // first edge and we're omitting it. - if(y === ycross) { - if(i === 1 && omitFirstEdge) return false; - return true; - } + return fragments; +}; - if(y <= ycross && x !== xmini) crossings++; - } - } +var mesh = function(topology) { + return object(topology, meshArcs.apply(this, arguments)); +}; - // if we've gotten this far, odd crossings means inside, even is outside - return crossings % 2 === 1; - } +function meshArcs(topology, object$$1, filter) { + var arcs, i, n; + if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter); + else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i; + return {type: "MultiLineString", arcs: stitch(topology, arcs)}; +} - // detect if poly is degenerate - var degenerate = true; - var lastPt = pts[0]; - for(i = 1; i < pts.length; i++) { - if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; - } - } +function extractArcs(topology, object$$1, filter) { + var arcs = [], + geomsByArc = [], + geom; - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: pts, - contains: isRect ? rectContains : contains, - isRect: isRect, - degenerate: degenerate - }; -}; + function extract0(i) { + var j = i < 0 ? ~i : i; + (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); + } -/** - * Test multiple polygons - */ -polygon.multitester = function multitester(list) { - var testers = [], - xmin = list[0][0][0], - xmax = xmin, - ymin = list[0][0][1], - ymax = ymin; + function extract1(arcs) { + arcs.forEach(extract0); + } - for(var i = 0; i < list.length; i++) { - 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); - } + function extract2(arcs) { + arcs.forEach(extract1); + } - function contains(pt, arg) { - var yes = false; - for(var i = 0; i < testers.length; i++) { - if(testers[i].contains(pt, arg)) { - // if contained by subtract polygon - exclude the point - yes = testers[i].subtract === false; - } - } + function extract3(arcs) { + arcs.forEach(extract2); + } - return yes; + function geometry(o) { + switch (geom = o, o.type) { + case "GeometryCollection": o.geometries.forEach(geometry); break; + case "LineString": extract1(o.arcs); break; + case "MultiLineString": case "Polygon": extract2(o.arcs); break; + case "MultiPolygon": extract3(o.arcs); break; } + } - return { - xmin: xmin, - xmax: xmax, - ymin: ymin, - ymax: ymax, - pts: [], - contains: contains, - isRect: false, - degenerate: false - }; -}; + geometry(object$$1); -/** - * Test if a segment of a points array is bent or straight - * - * @param pts Array of [x, y] pairs - * @param start the index of the proposed start of the straight section - * @param end the index of the proposed end point - * @param tolerance the max distance off the line connecting start and end - * before the line counts as bent - * @returns boolean: true means this segment is bent, false means straight - */ -var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) { - var startPt = pts[start], - segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]], - segmentSquared = dot(segment, segment), - segmentLen = Math.sqrt(segmentSquared), - unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen], - i, - part, - partParallel; + geomsByArc.forEach(filter == null + ? function(geoms) { arcs.push(geoms[0].i); } + : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); - for(i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment); + return arcs; +} - if(partParallel < 0 || partParallel > segmentSquared || - Math.abs(dot(part, unitPerp)) > tolerance) return true; - } - return false; -}; +function planarRingArea(ring) { + var i = -1, n = ring.length, a, b = ring[n - 1], area = 0; + while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0]; + return Math.abs(area); // Note: doubled area! +} -/** - * Make a filtering polygon, to minimize the number of segments - * - * @param pts Array of [x, y] pairs (must start with at least 1 pair) - * @param tolerance the maximum deviation from straight allowed for - * removing points to simplify the polygon - * - * @returns Object {addPt, raw, filtered} - * addPt is a function(pt: [x, y] pair) to add a raw point and - * continue filtering - * raw is all the input points - * filtered is the resulting filtered Array of [x, y] pairs - */ -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]], - doneRawIndex = 0, - doneFilteredIndex = 0; +var merge = function(topology) { + return object(topology, mergeArcs.apply(this, arguments)); +}; - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length, - iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); +function mergeArcs(topology, objects) { + var polygonsByArc = {}, + polygons = [], + groups = []; - for(var i = iLast + 1; i < pts.length; i++) { - if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if(ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; - } - } - } + objects.forEach(geometry); - if(pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); + function geometry(o) { + switch (o.type) { + case "GeometryCollection": o.geometries.forEach(geometry); break; + case "Polygon": extract(o.arcs); break; + case "MultiPolygon": o.arcs.forEach(extract); break; } + } - return { - addPt: addPt, - raw: pts, - filtered: ptsFiltered - }; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ + function extract(polygon) { + polygon.forEach(function(ring) { + ring.forEach(function(arc) { + (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); + }); + }); + polygons.push(polygon); + } + function area(ring) { + return planarRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]); + } -'use strict'; + polygons.forEach(function(polygon) { + if (!polygon._) { + var group = [], + neighbors = [polygon]; + polygon._ = 1; + groups.push(group); + while (polygon = neighbors.pop()) { + group.push(polygon); + polygon.forEach(function(ring) { + ring.forEach(function(arc) { + polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { + if (!polygon._) { + polygon._ = 1; + neighbors.push(polygon); + } + }); + }); + }); + } + } + }); -/* removed: var _$PolyBool_295 = require('polybooljs'); */; -/* removed: var _$polygon_551 = require('../../lib/polygon'); */; -/* removed: var _$throttle_563 = require('../../lib/throttle'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -var makeEventData = _$helpers_450.makeEventData; -/* removed: var _$fx_453 = require('../../components/fx'); */; + polygons.forEach(function(polygon) { + delete polygon._; + }); -/* removed: var _$axes_584 = require('./axes'); */; -/* removed: var _$constants_589 = require('./constants'); */; + return { + type: "MultiPolygon", + arcs: groups.map(function(polygons) { + var arcs = [], n; -var filteredPolygon = _$polygon_551.filter; -var polygonTester = _$polygon_551.tester; -var multipolygonTester = _$polygon_551.multitester; -var MINSELECT = _$constants_589.MINSELECT; + // Extract the exterior (unique) arcs. + polygons.forEach(function(polygon) { + polygon.forEach(function(ring) { + ring.forEach(function(arc) { + if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { + arcs.push(arc); + } + }); + }); + }); -function getAxId(ax) { return ax._id; } + // Stitch the arcs into one or more rings. + arcs = stitch(topology, arcs); -var _$prepSelect_602 = function prepSelect(e, startX, startY, dragOptions, mode) { - var gd = dragOptions.gd, - fullLayout = gd._fullLayout, - zoomLayer = fullLayout._zoomlayer, - dragBBox = dragOptions.element.getBoundingClientRect(), - plotinfo = dragOptions.plotinfo, - xs = plotinfo.xaxis._offset, - ys = plotinfo.yaxis._offset, - x0 = startX - dragBBox.left, - y0 = startY - dragBBox.top, - x1 = x0, - y1 = y0, - path0 = 'M' + x0 + ',' + y0, - pw = dragOptions.xaxes[0]._length, - ph = dragOptions.yaxes[0]._length, - xAxisIds = dragOptions.xaxes.map(getAxId), - yAxisIds = dragOptions.yaxes.map(getAxId), - allAxes = dragOptions.xaxes.concat(dragOptions.yaxes), - filterPoly, testPoly, mergedPolygons, currentPolygon, - subtract = e.altKey; - - - // take over selection polygons from prev mode, if any - if((e.shiftKey || e.altKey) && (plotinfo.selection && plotinfo.selection.polygons) && !dragOptions.polygons) { - dragOptions.polygons = plotinfo.selection.polygons; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } - // create new polygons, if shift mode - else if((!e.shiftKey && !e.altKey) || ((e.shiftKey || e.altKey) && !plotinfo.selection)) { - plotinfo.selection = {}; - plotinfo.selection.polygons = dragOptions.polygons = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; - } + // If more than one ring is returned, + // at most one of these rings can be the exterior; + // choose the one with the greatest absolute area. + if ((n = arcs.length) > 1) { + for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { + if ((ki = area(arcs[i])) > k) { + t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; + } + } + } - if(mode === 'lasso') { - filterPoly = filteredPolygon([[x0, y0]], _$constants_589.BENDPX); - } - var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]); + return arcs; + }) + }; +} - 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 bisect = function(a, x) { + var lo = 0, hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; + } + return lo; +}; - var corners = zoomLayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_411.background, - stroke: _$color_411.defaultLine, - 'stroke-width': 1 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); +var neighbors = function(objects) { + var indexesByArc = {}, // arc index -> array of object indexes + neighbors = objects.map(function() { return []; }); + function line(arcs, i) { + arcs.forEach(function(a) { + if (a < 0) a = ~a; + var o = indexesByArc[a]; + if (o) o.push(i); + else indexesByArc[a] = [i]; + }); + } - // find the traces to search for selection points - var searchTraces = []; - var throttleID = fullLayout._uid + _$constants_589.SELECTID; - var selection = []; - var i, cd, trace, searchInfo, eventData; + function polygon(arcs, i) { + arcs.forEach(function(arc) { line(arc, 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; + function geometry(o, i) { + if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); + else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + } - if(dragOptions.subplot) { - if( - trace.subplot === dragOptions.subplot || - trace.geo === dragOptions.subplot - ) { - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: dragOptions.xaxes[0], - yaxis: dragOptions.yaxes[0] - }); - } - } else { - if(xAxisIds.indexOf(trace.xaxis) === -1) continue; - if(yAxisIds.indexOf(trace.yaxis) === -1) continue; + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } + }; - searchTraces.push({ - selectPoints: trace._module.selectPoints, - style: trace._module.style, - cd: cd, - xaxis: _$axes_584.getFromId(gd, trace.xaxis), - yaxis: _$axes_584.getFromId(gd, trace.yaxis) - }); - } - } + objects.forEach(geometry); - function axValue(ax) { - var index = (ax._id.charAt(0) === 'y') ? 1 : 0; - return function(v) { return ax.p2d(v[index]); }; + for (var i in indexesByArc) { + for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { + for (var k = j + 1; k < m; ++k) { + var ij = indexes[j], ik = indexes[k], n; + if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); + if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); + } } + } - function ascending(a, b) { return a - b; } + return neighbors; +}; - // allow subplots to override fillRangeItems routine - var fillRangeItems; +var quantize = function(topology, n) { + if (!((n = Math.floor(n)) >= 2)) throw new Error("n must be ≥2"); + if (topology.transform) throw new Error("already quantized"); + var bb = bbox(topology), name, + dx = bb[0], kx = (bb[2] - dx) / (n - 1) || 1, + dy = bb[1], ky = (bb[3] - dy) / (n - 1) || 1; - if(plotinfo.fillRangeItems) { - fillRangeItems = plotinfo.fillRangeItems; - } else { - if(mode === 'select') { - fillRangeItems = function(eventData, poly) { - var ranges = eventData.range = {}; + function quantizePoint(p) { + p[0] = Math.round((p[0] - dx) / kx); + p[1] = Math.round((p[1] - dy) / ky); + } - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var axLetter = ax._id.charAt(0); + function quantizeGeometry(o) { + switch (o.type) { + case "GeometryCollection": o.geometries.forEach(quantizeGeometry); break; + case "Point": quantizePoint(o.coordinates); break; + case "MultiPoint": o.coordinates.forEach(quantizePoint); break; + } + } - ranges[ax._id] = [ - ax.p2d(poly[axLetter + 'min']), - ax.p2d(poly[axLetter + 'max']) - ].sort(ascending); - } - }; - } else { - fillRangeItems = function(eventData, poly, filterPoly) { - var dataPts = eventData.lassoPoints = {}; + topology.arcs.forEach(function(arc) { + var i = 1, + j = 1, + n = arc.length, + pi = arc[0], + x0 = pi[0] = Math.round((pi[0] - dx) / kx), + y0 = pi[1] = Math.round((pi[1] - dy) / ky), + pj, + x1, + y1; - for(i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - dataPts[ax._id] = filterPoly.filtered.map(axValue(ax)); - } - }; - } + for (; i < n; ++i) { + pi = arc[i]; + x1 = Math.round((pi[0] - dx) / kx); + y1 = Math.round((pi[1] - dy) / ky); + if (x1 !== x0 || y1 !== y0) { + pj = arc[j++]; + pj[0] = x1 - x0, x0 = x1; + pj[1] = y1 - y0, y0 = y1; + } } - dragOptions.moveFn = function(dx0, dy0) { - x1 = Math.max(0, Math.min(pw, dx0 + x0)); - y1 = Math.max(0, Math.min(ph, dy0 + y0)); + if (j < 2) { + pj = arc[j++]; + pj[0] = 0; + pj[1] = 0; + } - var dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); + arc.length = j; + }); - if(mode === 'select') { - if(dy < Math.min(dx * 0.6, MINSELECT)) { - // 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'); + for (name in topology.objects) { + quantizeGeometry(topology.objects[name]); + } - } - else if(dx < Math.min(dy * 0.6, MINSELECT)) { - // 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 { - // 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; - } + topology.transform = { + scale: [kx, ky], + translate: [dx, dy] + }; - // create outline & tester - if(dragOptions.polygons && dragOptions.polygons.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon])); - } - else { - mergedPolygons = [currentPolygon]; - testPoly = polygonTester(currentPolygon); - } + return topology; +}; - // draw selection - var paths = []; - for(i = 0; i < mergedPolygons.length; i++) { - var ppts = mergedPolygons[i]; - paths.push(ppts.join('L') + 'L' + ppts[0]); - } - outlines - .attr('d', 'M' + paths.join('M') + 'Z'); +var untransform = function(topology) { + if ((transform = topology.transform) == null) return identity; + var transform, + x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + var x1 = Math.round((point[0] - dx) / kx), + y1 = Math.round((point[1] - dy) / ky); + point[0] = x1 - x0, x0 = x1; + point[1] = y1 - y0, y0 = y1; + return point; + }; +}; - _$throttle_563.throttle( - throttleID, - _$constants_589.SELECTDELAY, - function() { - selection = []; +exports.bbox = bbox; +exports.feature = feature; +exports.mesh = mesh; +exports.meshArcs = meshArcs; +exports.merge = merge; +exports.mergeArcs = mergeArcs; +exports.neighbors = neighbors; +exports.quantize = quantize; +exports.transform = transform; +exports.untransform = untransform; - var thisSelection, traceSelections = [], traceSelection; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; +Object.defineProperty(exports, '__esModule', { value: true }); - traceSelection = searchInfo.selectPoints(searchInfo, testPoly); - traceSelections.push(traceSelection); +}))); - thisSelection = fillSelectionItem(traceSelection, searchInfo); +_$topojsonClient_417 = _$topojsonClient_417.exports +var _$constants_675 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(selection.length) { - for(var j = 0; j < thisSelection.length; j++) { - selection.push(thisSelection[j]); - } - } - else selection = thisSelection; - } +'use strict'; - eventData = {points: selection}; - updateSelectedState(gd, searchTraces, eventData); - fillRangeItems(eventData, currentPolygon, filterPoly); - dragOptions.gd.emit('plotly_selecting', eventData); - } - ); - }; +// projection names to d3 function name +_$constants_675.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' +}; - dragOptions.clickFn = function(numClicks, evt) { - corners.remove(); +// name of the axes +_$constants_675.axesNames = ['lonaxis', 'lataxis']; - _$throttle_563.done(throttleID).then(function() { - _$throttle_563.clear(throttleID); - if(numClicks === 2) { - // clear selection on doubleclick - outlines.remove(); - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo.selectPoints(searchInfo, false); - } +// max longitudinal angular span (EXPERIMENTAL) +_$constants_675.lonaxisSpan = { + 'orthographic': 180, + 'azimuthal equal area': 360, + 'azimuthal equidistant': 360, + 'conic conformal': 180, + 'gnomonic': 160, + 'stereographic': 180, + 'transverse mercator': 180, + '*': 360 +}; - updateSelectedState(gd, searchTraces); - gd.emit('plotly_deselect', null); - } - else { - // 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. - gd.emit('plotly_selected', undefined); - } +// max latitudinal angular span (EXPERIMENTAL) +_$constants_675.lataxisSpan = { + 'conic conformal': 150, + 'stereographic': 179.5, + '*': 180 +}; - _$fx_453.click(gd, evt); - }); - }; +// defaults for each scope +_$constants_675.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] + } +}; - dragOptions.doneFn = function() { - corners.remove(); +// angular pad to avoid rounding error around clip angles +_$constants_675.clipPad = 1e-3; - _$throttle_563.done(throttleID).then(function() { - _$throttle_563.clear(throttleID); - dragOptions.gd.emit('plotly_selected', eventData); +// map projection precision +_$constants_675.precision = 0.1; - if(currentPolygon && dragOptions.polygons) { - // save last polygons - currentPolygon.subtract = subtract; - dragOptions.polygons.push(currentPolygon); +// default land and water fill colors +_$constants_675.landColor = '#F0DC82'; +_$constants_675.waterColor = '#3399FF'; - // we have to keep reference to arrays container - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - }); - }; +// locationmode to layer name +_$constants_675.locationmodeToLayer = { + 'ISO-3': 'countries', + 'USA-states': 'subunits', + 'country names': 'countries' }; -function updateSelectedState(gd, searchTraces, eventData) { - var i, searchInfo, trace; +// SVG element for a sphere (use to frame maps) +_$constants_675.sphereSVG = {type: 'Sphere'}; - if(eventData) { - var pts = eventData.points || []; +// N.B. base layer names must be the same as in the topojson files - for(i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace.selectedpoints = []; - trace._input.selectedpoints = []; - } +// base layer with a fill color +_$constants_675.fillLayers = { + ocean: 1, + land: 1, + lakes: 1 +}; - for(i = 0; i < pts.length; i++) { - var pt = pts[i]; - var data = pt.data; - var fullData = pt.fullData; +// base layer with a only a line color +_$constants_675.lineLayers = { + subunits: 1, + countries: 1, + coastlines: 1, + rivers: 1, + frame: 1 +}; - if(pt.pointIndices) { - [].push.apply(data.selectedpoints, pt.pointIndices); - [].push.apply(fullData.selectedpoints, pt.pointIndices); - } else { - data.selectedpoints.push(pt.pointIndex); - 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; +_$constants_675.layers = [ + 'bg', + 'ocean', 'land', 'lakes', + 'subunits', 'countries', 'coastlines', 'rivers', + 'lataxis', 'lonaxis', 'frame', + 'backplot', + 'frontplot' +]; - // delete scattergl selection - if(searchTraces[i].cd[0].t && searchTraces[i].cd[0].t.scene) { - searchTraces[i].cd[0].t.scene.clearSelect(); - } - } - } +_$constants_675.layersForChoropleth = [ + 'bg', + 'ocean', 'land', + 'subunits', 'countries', 'coastlines', + 'lataxis', 'lonaxis', 'frame', + 'backplot', + 'rivers', 'lakes', + 'frontplot' +]; - for(i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if(searchInfo.style) searchInfo.style(gd, searchInfo.cd); - } -} +_$constants_675.layerNameToAdjective = { + ocean: 'ocean', + land: 'land', + lakes: 'lake', + subunits: 'subunit', + countries: 'country', + coastlines: 'coastline', + rivers: 'river', + frame: 'frame' +}; -function mergePolygons(list, poly, subtract) { - var res; +var _$topojson_utils_628 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(subtract) { - res = _$PolyBool_295.difference({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); - return res.regions; - } +'use strict'; - res = _$PolyBool_295.union({ - regions: list, - inverted: false - }, { - regions: [poly], - inverted: false - }); +var topojsonUtils = _$topojson_utils_628 = {}; - return res.regions; -} +var locationmodeToLayer = _$constants_675.locationmodeToLayer; +var topojsonFeature = _$topojsonClient_417.feature; -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); - } - } +topojsonUtils.getTopojsonName = function(geoLayout) { + return [ + geoLayout.scope.replace(/ /g, '-'), '_', + geoLayout.resolution.toString(), 'm' + ].join(''); +}; - return selection; -} +topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) { + return topojsonURL + topojsonName + '.json'; +}; + +topojsonUtils.getTopojsonFeatures = function(trace, topojson) { + var layer = locationmodeToLayer[trace.locationmode], + obj = topojson.objects[layer]; + + return topojsonFeature(topojson, obj).features; +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -51387,7 +53226,7 @@ function addProjectionsToD3(d3) { }).raw = winkel3; } -var _$addProjectionsToD3_619 = addProjectionsToD3; +var _$addProjectionsToD3_681 = addProjectionsToD3; /** * Copyright 2012-2018, Plotly, Inc. @@ -51400,8 +53239,8 @@ var _$addProjectionsToD3_619 = addProjectionsToD3; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; var radians = Math.PI / 180; var degrees = 180 / Math.PI; @@ -51425,11 +53264,11 @@ function createGeoZoom(geo, geoLayout) { return zoomConstructor(geo, projection); } -var _$createGeoZoom_620 = createGeoZoom; +var _$createGeoZoom_682 = createGeoZoom; // common to all zoom types function initZoom(geo, projection) { - return _$d3_127.behavior.zoom() + return _$d3_130.behavior.zoom() .translate(projection.translate()) .scale(projection.scale()); } @@ -51444,11 +53283,11 @@ function sync(geo, projection, cb) { var eventData = {}; function set(propStr, val) { - var fullNp = _$lib_539.nestedProperty(fullOpts, propStr); + var fullNp = _$lib_601.nestedProperty(fullOpts, propStr); if(fullNp.get() !== val) { fullNp.set(val); - _$lib_539.nestedProperty(userOpts, propStr).set(val); + _$lib_601.nestedProperty(userOpts, propStr).set(val); eventData[id + '.' + propStr] = val; } } @@ -51463,13 +53302,13 @@ function zoomScoped(geo, projection) { var zoom = initZoom(geo, projection); function handleZoomstart() { - _$d3_127.select(this).style(zoomstartStyle); + _$d3_130.select(this).style(zoomstartStyle); } function handleZoom() { projection - .scale(_$d3_127.event.scale) - .translate(_$d3_127.event.translate); + .scale(_$d3_130.event.scale) + .translate(_$d3_130.event.translate); geo.render(); } @@ -51481,7 +53320,7 @@ function zoomScoped(geo, projection) { } function handleZoomend() { - _$d3_127.select(this).style(zoomendStyle); + _$d3_130.select(this).style(zoomendStyle); sync(geo, projection, syncCb); } @@ -51511,9 +53350,9 @@ function zoomNonClipped(geo, projection) { } function handleZoomstart() { - _$d3_127.select(this).style(zoomstartStyle); + _$d3_130.select(this).style(zoomstartStyle); - mouse0 = _$d3_127.mouse(this); + mouse0 = _$d3_130.mouse(this); rotate0 = projection.rotate(); translate0 = projection.translate(); lastRotate = rotate0; @@ -51521,7 +53360,7 @@ function zoomNonClipped(geo, projection) { } function handleZoom() { - mouse1 = _$d3_127.mouse(this); + mouse1 = _$d3_130.mouse(this); if(outside(mouse0)) { zoom.scale(projection.scale()); @@ -51529,8 +53368,8 @@ function zoomNonClipped(geo, projection) { return; } - projection.scale(_$d3_127.event.scale); - projection.translate([translate0[0], _$d3_127.event.translate[1]]); + projection.scale(_$d3_130.event.scale); + projection.translate([translate0[0], _$d3_130.event.translate[1]]); if(!zoomPoint) { mouse0 = mouse1; @@ -51547,7 +53386,7 @@ function zoomNonClipped(geo, projection) { } function handleZoomend() { - _$d3_127.select(this).style(zoomendStyle); + _$d3_130.select(this).style(zoomendStyle); sync(geo, projection, syncCb); } @@ -51580,9 +53419,9 @@ function zoomClipped(geo, projection) { var zoomPoint; zoom.on('zoomstart', function() { - _$d3_127.select(this).style(zoomstartStyle); + _$d3_130.select(this).style(zoomstartStyle); - var mouse0 = _$d3_127.mouse(this), + var mouse0 = _$d3_130.mouse(this), rotate0 = projection.rotate(), lastRotate = rotate0, translate0 = projection.translate(), @@ -51591,9 +53430,9 @@ function zoomClipped(geo, projection) { zoomPoint = position(projection, mouse0); zoomOn.call(zoom, 'zoom', function() { - var mouse1 = _$d3_127.mouse(this); + var mouse1 = _$d3_130.mouse(this); - projection.scale(view.k = _$d3_127.event.scale); + projection.scale(view.k = _$d3_130.event.scale); if(!zoomPoint) { // if no zoomPoint, the mouse wasn't over the actual geography yet @@ -51634,7 +53473,7 @@ function zoomClipped(geo, projection) { zoomstarted(event.of(this, arguments)); }) .on('zoomend', function() { - _$d3_127.select(this).style(zoomendStyle); + _$d3_130.select(this).style(zoomendStyle); zoomOn.call(zoom, 'zoom', null); zoomended(event.of(this, arguments)); sync(geo, projection, syncCb); @@ -51661,7 +53500,7 @@ function zoomClipped(geo, projection) { set('projection.rotation.lat', -_rotate[1]); } - return _$d3_127.rebind(zoom, event, 'on'); + return _$d3_130.rebind(zoom, event, 'on'); } // -- helper functions for zoomClipped @@ -51700,8 +53539,8 @@ function multiply(a, b) { function rotateBetween(a, b) { if(!a || !b) return; var axis = cross(a, b), - norm = Math.sqrt(__dot_620(axis, axis)), - halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, __dot_620(a, b)))), + norm = Math.sqrt(__dot_682(axis, axis)), + halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, __dot_682(a, b)))), k = Math.sin(halfgamma) / norm; return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k]; } @@ -51803,7 +53642,7 @@ function cartesian(spherical) { ]; } -function __dot_620(a, b) { +function __dot_682(a, b) { var s = 0; for(var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i]; return s; @@ -51828,7 +53667,7 @@ function d3_eventDispatch(target) { while(++i < n) argumentz.push(arguments[i]); - var dispatch = _$d3_127.dispatch.apply(null, argumentz); + var dispatch = _$d3_130.dispatch.apply(null, argumentz); // Creates a dispatch context for the specified `thiz` (typically, the target // DOM element that received the source event) and `argumentz` (typically, the @@ -51843,12 +53682,12 @@ function d3_eventDispatch(target) { return function(e1) { var e0; try { - e0 = e1.sourceEvent = _$d3_127.event; + e0 = e1.sourceEvent = _$d3_130.event; e1.target = target; - _$d3_127.event = e1; + _$d3_130.event = e1; dispatch[e1.type].apply(thiz, argumentz); } finally { - _$d3_127.event = e0; + _$d3_130.event = e0; } }; }; @@ -51868,25 +53707,25 @@ function d3_eventDispatch(target) { /* global PlotlyGeoAssets:false */ -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$plots_647 = require('../plots'); */; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$plots_709 = require('../plots'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +var __prepSelect_676 = _$select_664.prepSelect; -/* removed: var _$createGeoZoom_620 = require('./zoom'); */; -/* removed: var _$constants_613 = require('./constants'); */; +/* removed: var _$createGeoZoom_682 = require('./zoom'); */; +/* removed: var _$constants_675 = require('./constants'); */; -/* removed: var _$topojson_utils_565 = require('../../lib/topojson_utils'); */; -var __topojsonFeature_614 = _$topojsonClient_355.feature; +/* removed: var _$topojson_utils_628 = require('../../lib/topojson_utils'); */; +var __topojsonFeature_676 = _$topojsonClient_417.feature; -_$addProjectionsToD3_619(_$d3_127); +_$addProjectionsToD3_681(_$d3_130); function Geo(opts) { this.id = opts.id; @@ -51921,14 +53760,14 @@ function Geo(opts) { var proto = Geo.prototype; -var _$createGeo_614 = function createGeo(opts) { +var _$createGeo_676 = function createGeo(opts) { return new Geo(opts); }; proto.plot = function(geoCalcData, fullLayout, promises) { var _this = this; var geoLayout = fullLayout[this.id]; - var topojsonNameNew = _$topojson_utils_565.getTopojsonName(geoLayout); + var topojsonNameNew = _$topojson_utils_628.getTopojsonName(geoLayout); if(_this.topojson === null || topojsonNameNew !== _this.topojsonName) { _this.topojsonName = topojsonNameNew; @@ -51949,12 +53788,12 @@ proto.plot = function(geoCalcData, fullLayout, promises) { }; proto.fetchTopojson = function() { - var topojsonPath = _$topojson_utils_565.getTopojsonPath( + var topojsonPath = _$topojson_utils_628.getTopojsonPath( this.topojsonURL, this.topojsonName ); return new Promise(function(resolve, reject) { - _$d3_127.json(topojsonPath, function(err, topojson) { + _$d3_130.json(topojsonPath, function(err, topojson) { if(err) { if(err.status === 404) { return reject(new Error([ @@ -51998,7 +53837,7 @@ proto.update = function(geoCalcData, fullLayout) { this.updateDims(fullLayout, geoLayout); this.updateFx(fullLayout, geoLayout); - _$plots_647.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout); + _$plots_709.generalUpdatePerTraceModule(this.graphDiv, this, geoCalcData, geoLayout); var scatterLayer = this.layers.frontplot.select('.scatterlayer'); this.dataPoints.point = scatterLayer.selectAll('.point'); @@ -52065,8 +53904,8 @@ proto.updateProjection = function(fullLayout, geoLayout) { this.viewInitial = null; - _$lib_539.warn(msg); - gd._promises.push(_$registry_668.call('relayout', gd, updateObj)); + _$lib_601.warn(msg); + gd._promises.push(_$registry_731.call('relayout', gd, updateObj)); return msg; } @@ -52107,16 +53946,16 @@ proto.updateBaseLayers = function(fullLayout, geoLayout) { } function isLineLayer(d) { - return Boolean(_$constants_613.lineLayers[d]); + return Boolean(_$constants_675.lineLayers[d]); } function isFillLayer(d) { - return Boolean(_$constants_613.fillLayers[d]); + return Boolean(_$constants_675.fillLayers[d]); } var allLayers = this.hasChoropleth ? - _$constants_613.layersForChoropleth : - _$constants_613.layers; + _$constants_675.layersForChoropleth : + _$constants_675.layers; var layerData = allLayers.filter(function(d) { return (isLineLayer(d) || isFillLayer(d)) ? geoLayout['show' + d] : @@ -52130,13 +53969,13 @@ proto.updateBaseLayers = function(fullLayout, geoLayout) { join.exit().each(function(d) { delete layers[d]; delete basePaths[d]; - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); }); join.enter().append('g') .attr('class', function(d) { return 'layer ' + d; }) .each(function(d) { - var layer = layers[d] = _$d3_127.select(this); + var layer = layers[d] = _$d3_130.select(this); if(d === 'bg') { _this.bgRect = layer.append('rect') @@ -52164,23 +54003,23 @@ proto.updateBaseLayers = function(fullLayout, geoLayout) { join.each(function(d) { var path = basePaths[d]; - var adj = _$constants_613.layerNameToAdjective[d]; + var adj = _$constants_675.layerNameToAdjective[d]; if(d === 'frame') { - path.datum(_$constants_613.sphereSVG); + path.datum(_$constants_675.sphereSVG); } else if(isLineLayer(d) || isFillLayer(d)) { - path.datum(__topojsonFeature_614(topojson, topojson.objects[d])); + path.datum(__topojsonFeature_676(topojson, topojson.objects[d])); } else if(isAxisLayer(d)) { path.datum(makeGraticule(d, geoLayout)) - .call(_$color_411.stroke, geoLayout[d].gridcolor) - .call(_$drawing_436.dashLine, '', geoLayout[d].gridwidth); + .call(_$color_473.stroke, geoLayout[d].gridcolor) + .call(_$drawing_498.dashLine, '', geoLayout[d].gridwidth); } if(isLineLayer(d)) { - path.call(_$color_411.stroke, geoLayout[adj + 'color']) - .call(_$drawing_436.dashLine, '', geoLayout[adj + 'width']); + path.call(_$color_473.stroke, geoLayout[adj + 'color']) + .call(_$drawing_498.dashLine, '', geoLayout[adj + 'width']); } else if(isFillLayer(d)) { - path.call(_$color_411.fill, geoLayout[adj + 'color']); + path.call(_$color_473.fill, geoLayout[adj + 'color']); } }); }; @@ -52194,11 +54033,11 @@ proto.updateDims = function(fullLayout, geoLayout) { var w = b[1][0] - l + hFrameWidth; var h = b[1][1] - t + hFrameWidth; - _$drawing_436.setRect(this.clipRect, l, t, w, h); + _$drawing_498.setRect(this.clipRect, l, t, w, h); this.bgRect - .call(_$drawing_436.setRect, l, t, w, h) - .call(_$color_411.fill, geoLayout.bgcolor); + .call(_$drawing_498.setRect, l, t, w, h) + .call(_$color_473.fill, geoLayout.bgcolor); this.xaxis._offset = l; this.xaxis._length = w; @@ -52223,7 +54062,7 @@ proto.updateFx = function(fullLayout, geoLayout) { updateObj[_this.id + '.' + k] = viewInitial[k]; } - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); gd.emit('plotly_doubleclick', null); } @@ -52236,7 +54075,7 @@ proto.updateFx = function(fullLayout, geoLayout) { if(dragMode === 'pan') { bgRect.node().onmousedown = null; - bgRect.call(_$createGeoZoom_620(_this, geoLayout)); + bgRect.call(_$createGeoZoom_682(_this, geoLayout)); bgRect.on('dblclick.zoom', zoomReset); } else if(dragMode === 'select' || dragMode === 'lasso') { @@ -52278,27 +54117,27 @@ proto.updateFx = function(fullLayout, geoLayout) { }; dragOptions.prepFn = function(e, startX, startY) { - _$prepSelect_602(e, startX, startY, dragOptions, dragMode); + __prepSelect_676(e, startX, startY, dragOptions, dragMode); }; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); } bgRect.on('mousemove', function() { - var lonlat = _this.projection.invert(_$d3_127.mouse(this)); + var lonlat = _this.projection.invert(_$d3_130.mouse(this)); if(!lonlat || isNaN(lonlat[0]) || isNaN(lonlat[1])) { - return _$dragelement_433.unhover(gd, _$d3_127.event); + return _$dragelement_495.unhover(gd, _$d3_130.event); } _this.xaxis.p2c = function() { return lonlat[0]; }; _this.yaxis.p2c = function() { return lonlat[1]; }; - _$fx_453.hover(gd, _$d3_127.event, _this.id); + _$fx_515.hover(gd, _$d3_130.event, _this.id); }); bgRect.on('mouseout', function() { - _$dragelement_433.unhover(gd, _$d3_127.event); + _$dragelement_495.unhover(gd, _$d3_130.event); }); bgRect.on('click', function() { @@ -52306,7 +54145,7 @@ proto.updateFx = function(fullLayout, geoLayout) { // actually this one is worse, as right-click starts a pan, or leaves // select in a weird state. // Also, only tangentially related, we should cancel hover during pan - _$fx_453.click(gd, _$d3_127.event); + _$fx_515.click(gd, _$d3_130.event); }); }; @@ -52320,9 +54159,9 @@ proto.makeFramework = function() { _this.clipRect = _this.clipDef.append('rect'); - _this.framework = _$d3_127.select(_this.container).append('g') + _this.framework = _$d3_130.select(_this.container).append('g') .attr('class', 'geo ' + _this.id) - .call(_$drawing_436.setClipUrl, clipId); + .call(_$drawing_498.setClipUrl, clipId); // sane lonlat to px _this.project = function(v) { @@ -52348,7 +54187,7 @@ proto.makeFramework = function() { showexponent: 'all', exponentformat: 'B' }; - _$axes_584.setConvert(_this.mockAxis, fullLayout); + _$axes_647.setConvert(_this.mockAxis, fullLayout); }; proto.saveViewInitial = function(geoLayout) { @@ -52425,10 +54264,10 @@ function getProjection(geoLayout) { var projLayout = geoLayout.projection; var projType = projLayout.type; - var projection = _$d3_127.geo[_$constants_613.projNames[projType]](); + var projection = _$d3_130.geo[_$constants_675.projNames[projType]](); var clipAngle = geoLayout._isClipped ? - _$constants_613.lonaxisSpan[projType] / 2 : + _$constants_675.lonaxisSpan[projType] / 2 : null; var methods = ['center', 'rotate', 'parallels', 'clipExtent']; @@ -52448,7 +54287,7 @@ function getProjection(geoLayout) { if(clipAngle) { var r = projection.rotate(); - var angle = _$d3_127.geo.distance(lonlat, [-r[0], -r[1]]); + var angle = _$d3_130.geo.distance(lonlat, [-r[0], -r[1]]); var maxAngle = clipAngle * Math.PI / 180; return angle > maxAngle; } else { @@ -52457,7 +54296,7 @@ function getProjection(geoLayout) { }; projection.getPath = function() { - return _$d3_127.geo.path().projection(projection); + return _$d3_130.geo.path().projection(projection); }; projection.getBounds = function(object) { @@ -52489,10 +54328,10 @@ function getProjection(geoLayout) { .translate([x, y]); }; - projection.precision(_$constants_613.precision); + projection.precision(_$constants_675.precision); if(clipAngle) { - projection.clipAngle(clipAngle - _$constants_613.clipPad); + projection.clipAngle(clipAngle - _$constants_675.clipPad); } return projection; @@ -52501,12 +54340,12 @@ function getProjection(geoLayout) { function makeGraticule(axisName, geoLayout) { var axisLayout = geoLayout[axisName]; var dtick = axisLayout.dtick; - var scopeDefaults = _$constants_613.scopeDefaults[geoLayout.scope]; + var scopeDefaults = _$constants_675.scopeDefaults[geoLayout.scope]; var lonaxisRange = scopeDefaults.lonaxisRange; var lataxisRange = scopeDefaults.lataxisRange; var step = axisName === 'lonaxis' ? [dtick] : [0, dtick]; - return _$d3_127.geo.graticule() + return _$d3_130.geo.graticule() .extent([ [lonaxisRange[0], lataxisRange[0]], [lonaxisRange[1], lataxisRange[1]] @@ -52519,7 +54358,7 @@ function makeGraticule(axisName, geoLayout) { // // Note that clipPad padding is added around range to avoid aliasing. function makeRangeBox(lon, lat) { - var clipPad = _$constants_613.clipPad; + var clipPad = _$constants_675.clipPad; var lon0 = lon[0] + clipPad; var lon1 = lon[1] - clipPad; var lat0 = lat[0] + clipPad; @@ -52559,7 +54398,7 @@ function makeRangeBox(lon, lat) { 'use strict'; -var _$attributes_616 = { +var _$attributes_678 = { geo: { valType: 'subplotid', @@ -52569,7 +54408,7 @@ var _$attributes_616 = { } }; -var _$domain_610 = {}; +var _$domain_672 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -52580,7 +54419,7 @@ var _$domain_610 = {}; 'use strict'; -var __extendFlat_610 = _$extend_528.extendFlat; +var __extendFlat_672 = _$extend_590.extendFlat; /** * Make a xy domain attribute group @@ -52603,7 +54442,7 @@ var __extendFlat_610 = _$extend_528.extendFlat; * * @return {object} attributes object containing {x,y} as specified */ -_$domain_610.attributes = function(opts, extra) { +_$domain_672.attributes = function(opts, extra) { opts = opts || {}; extra = extra || {}; @@ -52623,10 +54462,10 @@ _$domain_610.attributes = function(opts, extra) { var descPart = extra.description ? ' ' + extra.description : ''; var out = { - x: __extendFlat_610({}, base, { + x: __extendFlat_672({}, base, { }), - y: __extendFlat_610({}, base, { + y: __extendFlat_672({}, base, { }), editType: opts.editType @@ -52654,7 +54493,7 @@ _$domain_610.attributes = function(opts, extra) { return out; }; -_$domain_610.defaults = function(containerOut, layout, coerce, dfltDomains) { +_$domain_672.defaults = function(containerOut, layout, coerce, dfltDomains) { var dfltX = (dfltDomains && dfltDomains.x) || [0, 1]; var dfltY = (dfltDomains && dfltDomains.y) || [0, 1]; @@ -52687,10 +54526,10 @@ _$domain_610.defaults = function(containerOut, layout, coerce, dfltDomains) { 'use strict'; -/* removed: var _$attributes_410 = require('../../../components/color/attributes'); */; -var domainAttrs = _$domain_610.attributes; -/* removed: var _$constants_613 = require('../constants'); */; -var __overrideAll_618 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_472 = require('../../../components/color/attributes'); */; +var domainAttrs = _$domain_672.attributes; +/* removed: var _$constants_675 = require('../constants'); */; +var __overrideAll_680 = _$edit_types_632.overrideAll; var geoAxesAttrs = { range: { @@ -52721,7 +54560,7 @@ var geoAxesAttrs = { gridcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, }, gridwidth: { @@ -52733,7 +54572,7 @@ var geoAxesAttrs = { } }; -var _$layout_attributes_618 = __overrideAll_618({ +var _$layout_attributes_680 = __overrideAll_680({ domain: domainAttrs({name: 'geo'}, { }), @@ -52749,7 +54588,7 @@ var _$layout_attributes_618 = __overrideAll_618({ scope: { valType: 'enumerated', - values: Object.keys(_$constants_613.scopeDefaults), + values: Object.keys(_$constants_675.scopeDefaults), dflt: 'world', }, @@ -52757,7 +54596,7 @@ var _$layout_attributes_618 = __overrideAll_618({ type: { valType: 'enumerated', - values: Object.keys(_$constants_613.projNames), + values: Object.keys(_$constants_675.projNames), }, rotation: { @@ -52814,7 +54653,7 @@ var _$layout_attributes_618 = __overrideAll_618({ coastlinecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, }, coastlinewidth: { @@ -52833,7 +54672,7 @@ var _$layout_attributes_618 = __overrideAll_618({ landcolor: { valType: 'color', - dflt: _$constants_613.landColor, + dflt: _$constants_675.landColor, }, showocean: { @@ -52845,7 +54684,7 @@ var _$layout_attributes_618 = __overrideAll_618({ oceancolor: { valType: 'color', - dflt: _$constants_613.waterColor, + dflt: _$constants_675.waterColor, }, showlakes: { @@ -52857,7 +54696,7 @@ var _$layout_attributes_618 = __overrideAll_618({ lakecolor: { valType: 'color', - dflt: _$constants_613.waterColor, + dflt: _$constants_675.waterColor, }, showrivers: { @@ -52869,7 +54708,7 @@ var _$layout_attributes_618 = __overrideAll_618({ rivercolor: { valType: 'color', - dflt: _$constants_613.waterColor, + dflt: _$constants_675.waterColor, }, riverwidth: { @@ -52887,7 +54726,7 @@ var _$layout_attributes_618 = __overrideAll_618({ countrycolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, }, countrywidth: { @@ -52905,7 +54744,7 @@ var _$layout_attributes_618 = __overrideAll_618({ subunitcolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, }, subunitwidth: { @@ -52923,7 +54762,7 @@ var _$layout_attributes_618 = __overrideAll_618({ framecolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, }, framewidth: { @@ -52936,7 +54775,7 @@ var _$layout_attributes_618 = __overrideAll_618({ bgcolor: { valType: 'color', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, }, lonaxis: geoAxesAttrs, @@ -52954,8 +54793,8 @@ var _$layout_attributes_618 = __overrideAll_618({ 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -var handleDomainDefaults = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../lib'); */; +var handleDomainDefaults = _$domain_672.defaults; /** @@ -52985,7 +54824,7 @@ var handleDomainDefaults = _$domain_610.defaults; * additional items needed by this function here as well * } */ -var _$handleSubplotDefaults_660 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { +var _$handleSubplotDefaults_723 = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) { var subplotType = opts.type; var subplotAttributes = opts.attributes; var handleDefaults = opts.handleDefaults; @@ -52997,7 +54836,7 @@ var _$handleSubplotDefaults_660 = function handleSubplotDefaults(layoutIn, layou var subplotLayoutIn, subplotLayoutOut; function coerce(attr, dflt) { - return _$lib_539.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); + return _$lib_601.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt); } for(var i = 0; i < idsLength; i++) { @@ -53029,16 +54868,16 @@ var _$handleSubplotDefaults_660 = function handleSubplotDefaults(layoutIn, layou 'use strict'; -/* removed: var _$handleSubplotDefaults_660 = require('../../subplot_defaults'); */; -/* removed: var _$constants_613 = require('../constants'); */; -/* removed: var _$layout_attributes_618 = require('./layout_attributes'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../../subplot_defaults'); */; +/* removed: var _$constants_675 = require('../constants'); */; +/* removed: var _$layout_attributes_680 = require('./layout_attributes'); */; -var axesNames = _$constants_613.axesNames; +var axesNames = _$constants_675.axesNames; -var _$supplyLayoutDefaults_617 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_679 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'geo', - attributes: _$layout_attributes_618, + attributes: _$layout_attributes_680, handleDefaults: handleGeoDefaults, partition: 'y' }); @@ -53049,7 +54888,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { var resolution = coerce('resolution'); var scope = coerce('scope'); - var scopeParams = _$constants_613.scopeDefaults[scope]; + var scopeParams = _$constants_675.scopeDefaults[scope]; var projType = coerce('projection.type', scopeParams.projType); var isAlbersUsa = geoLayoutOut._isAlbersUsa = projType === 'albers usa'; @@ -53059,7 +54898,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { var isScoped = geoLayoutOut._isScoped = (scope !== 'world'); var isConic = geoLayoutOut._isConic = projType.indexOf('conic') !== -1; - geoLayoutOut._isClipped = !!_$constants_613.lonaxisSpan[projType]; + geoLayoutOut._isClipped = !!_$constants_675.lonaxisSpan[projType]; for(var i = 0; i < axesNames.length; i++) { var axisName = axesNames[i]; @@ -53069,7 +54908,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { if(isScoped) { rangeDflt = scopeParams[axisName + 'Range']; } else { - var dfltSpans = _$constants_613[axisName + 'Span']; + var dfltSpans = _$constants_675[axisName + 'Span']; var hSpan = (dfltSpans[projType] || dfltSpans['*']) / 2; var rot = coerce( 'projection.rotation.' + axisName.substr(0, 3), @@ -53181,7 +55020,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { coerce('bgcolor'); } -var _$geo_615 = {}; +var _$geo_677 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53193,27 +55032,27 @@ var _$geo_615 = {}; 'use strict'; -/* removed: var _$createGeo_614 = require('./geo'); */; -var getSubplotCalcData = _$get_data_621.getSubplotCalcData; -var __counterRegex_615 = _$lib_539.counterRegex; +/* removed: var _$createGeo_676 = require('./geo'); */; +var getSubplotCalcData = _$get_data_683.getSubplotCalcData; +var __counterRegex_677 = _$lib_601.counterRegex; var GEO = 'geo'; -_$geo_615.name = GEO; +_$geo_677.name = GEO; -_$geo_615.attr = GEO; +_$geo_677.attr = GEO; -_$geo_615.idRoot = GEO; +_$geo_677.idRoot = GEO; -_$geo_615.idRegex = _$geo_615.attrRegex = __counterRegex_615(GEO); +_$geo_677.idRegex = _$geo_677.attrRegex = __counterRegex_677(GEO); -_$geo_615.attributes = _$attributes_616; +_$geo_677.attributes = _$attributes_678; -_$geo_615.layoutAttributes = _$layout_attributes_618; +_$geo_677.layoutAttributes = _$layout_attributes_680; -_$geo_615.supplyLayoutDefaults = _$supplyLayoutDefaults_617; +_$geo_677.supplyLayoutDefaults = _$supplyLayoutDefaults_679; -_$geo_615.plot = function plotGeo(gd) { +_$geo_677.plot = function plotGeo(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var geoIds = fullLayout._subplots[GEO]; @@ -53233,7 +55072,7 @@ _$geo_615.plot = function plotGeo(gd) { var geo = geoLayout._subplot; if(!geo) { - geo = _$createGeo_614({ + geo = _$createGeo_676({ id: geoId, graphDiv: gd, container: fullLayout._geolayer.node(), @@ -53248,7 +55087,7 @@ _$geo_615.plot = function plotGeo(gd) { } }; -_$geo_615.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$geo_677.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldGeoKeys = oldFullLayout._subplots[GEO] || []; for(var i = 0; i < oldGeoKeys.length; i++) { @@ -53262,7 +55101,7 @@ _$geo_615.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayou } }; -_$geo_615.updateFx = function(fullLayout) { +_$geo_677.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots[GEO]; for(var i = 0; i < subplotIds.length; i++) { @@ -53282,19 +55121,19 @@ _$geo_615.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -var __dash_900 = _$attributes_435.dash; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +var __dash_965 = _$attributes_497.dash; -var __extendFlat_900 = _$extend_528.extendFlat; -var __overrideAll_900 = _$edit_types_569.overrideAll; +var __extendFlat_965 = _$extend_590.extendFlat; +var __overrideAll_965 = _$edit_types_632.overrideAll; -var __scatterMarkerAttrs_900 = _$attributes_862.marker, - scatterLineAttrs = _$attributes_862.line, - __scatterMarkerLineAttrs_900 = __scatterMarkerAttrs_900.line; +var __scatterMarkerAttrs_965 = _$attributes_927.marker, + scatterLineAttrs = _$attributes_927.line, + __scatterMarkerLineAttrs_965 = __scatterMarkerAttrs_965.line; -var _$attributes_900 = __overrideAll_900({ +var _$attributes_965 = __overrideAll_965({ lon: { valType: 'data_array', @@ -53316,42 +55155,42 @@ var _$attributes_900 = __overrideAll_900({ }, - mode: __extendFlat_900({}, _$attributes_862.mode, {dflt: 'markers'}), + mode: __extendFlat_965({}, _$attributes_927.mode, {dflt: 'markers'}), - text: __extendFlat_900({}, _$attributes_862.text, { + text: __extendFlat_965({}, _$attributes_927.text, { }), - hovertext: __extendFlat_900({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_965({}, _$attributes_927.hovertext, { }), - textfont: _$attributes_862.textfont, - textposition: _$attributes_862.textposition, + textfont: _$attributes_927.textfont, + textposition: _$attributes_927.textposition, line: { color: scatterLineAttrs.color, width: scatterLineAttrs.width, - dash: __dash_900 - }, - connectgaps: _$attributes_862.connectgaps, - - marker: __extendFlat_900({ - symbol: __scatterMarkerAttrs_900.symbol, - opacity: __scatterMarkerAttrs_900.opacity, - size: __scatterMarkerAttrs_900.size, - sizeref: __scatterMarkerAttrs_900.sizeref, - sizemin: __scatterMarkerAttrs_900.sizemin, - sizemode: __scatterMarkerAttrs_900.sizemode, - showscale: __scatterMarkerAttrs_900.showscale, - colorbar: __scatterMarkerAttrs_900.colorbar, - line: __extendFlat_900({ - width: __scatterMarkerLineAttrs_900.width + dash: __dash_965 + }, + connectgaps: _$attributes_927.connectgaps, + + marker: __extendFlat_965({ + symbol: __scatterMarkerAttrs_965.symbol, + opacity: __scatterMarkerAttrs_965.opacity, + size: __scatterMarkerAttrs_965.size, + sizeref: __scatterMarkerAttrs_965.sizeref, + sizemin: __scatterMarkerAttrs_965.sizemin, + sizemode: __scatterMarkerAttrs_965.sizemode, + showscale: __scatterMarkerAttrs_965.showscale, + colorbar: __scatterMarkerAttrs_965.colorbar, + line: __extendFlat_965({ + width: __scatterMarkerLineAttrs_965.width }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ), - gradient: __scatterMarkerAttrs_900.gradient + gradient: __scatterMarkerAttrs_965.gradient }, - _$makeColorScaleAttributes_419('marker') + _$makeColorScaleAttributes_481('marker') ), fill: { @@ -53361,12 +55200,12 @@ var _$attributes_900 = __overrideAll_900({ }, - fillcolor: _$attributes_862.fillcolor, + fillcolor: _$attributes_927.fillcolor, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected, + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected, - hoverinfo: __extendFlat_900({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_965({}, _$attributes_644.hoverinfo, { flags: ['lon', 'lat', 'location', 'text', 'name'] }) }, 'calc', 'nested'); @@ -53381,36 +55220,36 @@ var _$attributes_900 = __overrideAll_900({ 'use strict'; -/* removed: var _$attributes_900 = require('../scattergeo/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; +/* removed: var _$attributes_965 = require('../scattergeo/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; -/* removed: var _$extend_528 = require('../../lib/extend'); */; -var __extendFlat_735 = _$extend_528.extendFlat; -var __extendDeepAll_735 = _$extend_528.extendDeepAll; +/* removed: var _$extend_590 = require('../../lib/extend'); */; +var __extendFlat_797 = _$extend_590.extendFlat; +var __extendDeepAll_797 = _$extend_590.extendDeepAll; -var scatterGeoMarkerLineAttrs = _$attributes_900.marker.line; +var scatterGeoMarkerLineAttrs = _$attributes_965.marker.line; -var _$attributes_735 = __extendFlat_735({ +var _$attributes_797 = __extendFlat_797({ locations: { valType: 'data_array', editType: 'calc', }, - locationmode: _$attributes_900.locationmode, + locationmode: _$attributes_965.locationmode, z: { valType: 'data_array', editType: 'calc', }, - text: __extendFlat_735({}, _$attributes_900.text, { + text: __extendFlat_797({}, _$attributes_965.text, { }), marker: { line: { color: scatterGeoMarkerLineAttrs.color, - width: __extendFlat_735({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}), + width: __extendFlat_797({}, scatterGeoMarkerLineAttrs.width, {dflt: 1}), editType: 'calc' }, opacity: { @@ -53428,29 +55267,29 @@ var _$attributes_735 = __extendFlat_735({ selected: { marker: { - opacity: _$attributes_900.selected.marker.opacity, + opacity: _$attributes_965.selected.marker.opacity, editType: 'plot' }, editType: 'plot' }, unselected: { marker: { - opacity: _$attributes_900.unselected.marker.opacity, + opacity: _$attributes_965.unselected.marker.opacity, editType: 'plot' }, editType: 'plot' }, - hoverinfo: __extendFlat_735({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_797({}, _$attributes_644.hoverinfo, { editType: 'calc', flags: ['location', 'z', 'text', 'name'] }) }, - __extendDeepAll_735({}, _$attributes_417, { + __extendDeepAll_797({}, _$attributes_479, { zmax: {editType: 'calc'}, zmin: {editType: 'calc'} }), - { colorbar: _$attributes_412 } + { colorbar: _$attributes_474 } ); /** @@ -53464,42 +55303,42 @@ var _$attributes_735 = __extendFlat_735({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; // arrayOk attributes, merge them into calcdata array -var _$arraysToCalcdata_861 = function arraysToCalcdata(cd, trace) { +var _$arraysToCalcdata_926 = function arraysToCalcdata(cd, trace) { // so each point knows which index it originally came from for(var i = 0; i < cd.length; i++) cd[i].i = i; - _$lib_539.mergeArray(trace.text, cd, 'tx'); - _$lib_539.mergeArray(trace.hovertext, cd, 'htx'); - _$lib_539.mergeArray(trace.customdata, cd, 'data'); - _$lib_539.mergeArray(trace.textposition, cd, 'tp'); + _$lib_601.mergeArray(trace.text, cd, 'tx'); + _$lib_601.mergeArray(trace.hovertext, cd, 'htx'); + _$lib_601.mergeArray(trace.customdata, cd, 'data'); + _$lib_601.mergeArray(trace.textposition, cd, 'tp'); if(trace.textfont) { - _$lib_539.mergeArray(trace.textfont.size, cd, 'ts'); - _$lib_539.mergeArray(trace.textfont.color, cd, 'tc'); - _$lib_539.mergeArray(trace.textfont.family, cd, 'tf'); + _$lib_601.mergeArray(trace.textfont.size, cd, 'ts'); + _$lib_601.mergeArray(trace.textfont.color, cd, 'tc'); + _$lib_601.mergeArray(trace.textfont.family, cd, 'tf'); } var marker = trace.marker; if(marker) { - _$lib_539.mergeArray(marker.size, cd, 'ms'); - _$lib_539.mergeArray(marker.opacity, cd, 'mo'); - _$lib_539.mergeArray(marker.symbol, cd, 'mx'); - _$lib_539.mergeArray(marker.color, cd, 'mc'); + _$lib_601.mergeArray(marker.size, cd, 'ms'); + _$lib_601.mergeArray(marker.opacity, cd, 'mo'); + _$lib_601.mergeArray(marker.symbol, cd, 'mx'); + _$lib_601.mergeArray(marker.color, cd, 'mc'); var markerLine = marker.line; if(marker.line) { - _$lib_539.mergeArray(markerLine.color, cd, 'mlc'); - _$lib_539.mergeArray(markerLine.width, cd, 'mlw'); + _$lib_601.mergeArray(markerLine.color, cd, 'mlc'); + _$lib_601.mergeArray(markerLine.width, cd, 'mlw'); } var markerGradient = marker.gradient; if(markerGradient && markerGradient.type !== 'none') { - _$lib_539.mergeArray(markerGradient.type, cd, 'mgt'); - _$lib_539.mergeArray(markerGradient.color, cd, 'mgc'); + _$lib_601.mergeArray(markerGradient.type, cd, 'mgt'); + _$lib_601.mergeArray(markerGradient.color, cd, 'mgc'); } } }; @@ -53515,14 +55354,14 @@ var _$arraysToCalcdata_861 = function arraysToCalcdata(cd, trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __BADNUM_736 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __BADNUM_798 = _$numerical_578.BADNUM; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; -var _$calc_736 = function calc(gd, trace) { +var _$calc_798 = function calc(gd, trace) { var len = trace.locations.length; var calcTrace = new Array(len); @@ -53532,12 +55371,12 @@ var _$calc_736 = function calc(gd, trace) { var z = trace.z[i]; calcPt.loc = typeof loc === 'string' ? loc : null; - calcPt.z = _$fastIsnumeric_139(z) ? z : __BADNUM_736; + calcPt.z = _$fastIsnumeric_196(z) ? z : __BADNUM_798; } - _$arraysToCalcdata_861(calcTrace, trace); - _$calc_418(trace, trace.z, '', 'z'); - _$calcSelection_864(calcTrace, trace); + _$arraysToCalcdata_926(calcTrace, trace); + _$calc_480(trace, trace.z, '', 'z'); + _$calcSelection_929(calcTrace, trace); return calcTrace; }; @@ -53553,13 +55392,13 @@ var _$calc_736 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_735 = require('./attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_797 = require('./attributes'); */; -var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_799 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_735, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_797, attr, dflt); } var locations = coerce('locations'); @@ -53573,7 +55412,7 @@ var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultCol } var z = coerce('z'); - if(!_$lib_539.isArrayOrTypedArray(z)) { + if(!_$lib_601.isArrayOrTypedArray(z)) { traceOut.visible = false; return; } @@ -53588,11 +55427,11 @@ var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('marker.line.width'); coerce('marker.opacity'); - _$colorScaleDefaults_421( + _$colorScaleDefaults_483( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -53606,7 +55445,7 @@ var _$supplyDefaults_737 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_738 = function eventData(out, pt) { +var _$eventData_800 = function eventData(out, pt) { out.location = pt.location; out.z = pt.z; @@ -53624,11 +55463,11 @@ var _$eventData_738 = function eventData(out, pt) { 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$attributes_735 = require('./attributes'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$attributes_797 = require('./attributes'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; -var _$hoverPoints_739 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_801 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var geo = pointData.subplot; @@ -53672,7 +55511,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { var hoverinfo = pt.hi || trace.hoverinfo; var parts = (hoverinfo === 'all') ? - _$attributes_735.hoverinfo.flags : + _$attributes_797.hoverinfo.flags : hoverinfo.split('+'); var hasName = (parts.indexOf('name') !== -1); @@ -53684,7 +55523,7 @@ function makeHoverInfo(pointData, trace, pt, axis) { var text = []; function formatter(val) { - return _$axes_584.tickText(axis, axis.c2l(val), 'hover').text; + return _$axes_647.tickText(axis, axis.c2l(val), 'hover').text; } if(hasIdAsNameLabel) { @@ -53696,13 +55535,13 @@ function makeHoverInfo(pointData, trace, pt, axis) { if(hasZ) text.push(formatter(pt.z)); if(hasText) { - _$fillHoverText_870(pt, trace, text); + _$fillHoverText_935(pt, trace, text); } pointData.extraText = text.join('
'); } -var _$countryRegex_113 = { +var _$countryRegex_114 = { AFG: 'afghan', ALA: '\\b\\wland', ALB: 'albania', @@ -53960,7 +55799,7 @@ var _$countryRegex_113 = { ZWE: 'zimbabwe|^(?!.*northern).*rhodesia' } -var _$geo_location_utils_531 = {}; +var _$geo_location_utils_593 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -53972,20 +55811,20 @@ var _$geo_location_utils_531 = {}; 'use strict'; -/* removed: var _$countryRegex_113 = require('country-regex'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$countryRegex_114 = require('country-regex'); */; +/* removed: var _$lib_601 = require('../lib'); */; // make list of all country iso3 ids from at runtime -var countryIds = Object.keys(_$countryRegex_113); +var countryIds = Object.keys(_$countryRegex_114); var locationmodeToIdFinder = { - 'ISO-3': _$lib_539.identity, - 'USA-states': _$lib_539.identity, + 'ISO-3': _$lib_601.identity, + 'USA-states': _$lib_601.identity, 'country names': countryNameToISO3 }; -_$geo_location_utils_531.locationToFeature = function(locationmode, location, features) { +_$geo_location_utils_593.locationToFeature = function(locationmode, location, features) { if(!location || typeof location !== 'string') return false; var locationId = getLocationId(locationmode, location); @@ -53997,7 +55836,7 @@ _$geo_location_utils_531.locationToFeature = function(locationmode, location, fe if(feature.id === locationId) return feature; } - _$lib_539.log([ + _$lib_601.log([ 'Location with id', locationId, 'does not have a matching topojson feature at this resolution.' ].join(' ')); @@ -54014,12 +55853,12 @@ function getLocationId(locationmode, location) { function countryNameToISO3(countryName) { for(var i = 0; i < countryIds.length; i++) { var iso3 = countryIds[i], - regex = new RegExp(_$countryRegex_113[iso3]); + regex = new RegExp(_$countryRegex_114[iso3]); if(regex.test(countryName.trim().toLowerCase())) return iso3; } - _$lib_539.log('Unrecognized country name: ' + countryName + '.'); + _$lib_601.log('Unrecognized country name: ' + countryName + '.'); return false; } @@ -54034,12 +55873,12 @@ function countryNameToISO3(countryName) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; -var _$style_743 = function style(gd, calcTrace) { +var _$style_805 = function style(gd, calcTrace) { if(calcTrace) styleTrace(gd, calcTrace); }; @@ -54050,8 +55889,8 @@ function styleTrace(gd, calcTrace) { var marker = trace.marker || {}; var markerLine = marker.line || {}; - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, trace.zmin, trace.zmax @@ -54059,14 +55898,14 @@ function styleTrace(gd, calcTrace) { ); locs.each(function(d) { - _$d3_127.select(this) + _$d3_130.select(this) .attr('fill', sclFunc(d.z)) - .call(_$color_411.stroke, d.mlc || markerLine.color) - .call(_$drawing_436.dashLine, '', d.mlw || markerLine.width || 0) + .call(_$color_473.stroke, d.mlc || markerLine.color) + .call(_$drawing_498.dashLine, '', d.mlw || markerLine.width || 0) .style('opacity', marker.opacity); }); - _$drawing_436.selectedPointStyle(locs, trace); + _$drawing_498.selectedPointStyle(locs, trace); } /** @@ -54079,16 +55918,16 @@ function styleTrace(gd, calcTrace) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$polygon_551 = require('../../lib/polygon'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$polygon_613 = require('../../lib/polygon'); */; -var getTopojsonFeatures = _$topojson_utils_565.getTopojsonFeatures; -var locationToFeature = _$geo_location_utils_531.locationToFeature; -/* removed: var _$style_743 = require('./style'); */; +var getTopojsonFeatures = _$topojson_utils_628.getTopojsonFeatures; +var locationToFeature = _$geo_location_utils_593.locationToFeature; +/* removed: var _$style_805 = require('./style'); */; -var _$plot_741 = function plot(gd, geo, calcData) { +var _$plot_803 = function plot(gd, geo, calcData) { for(var i = 0; i < calcData.length; i++) { calcGeoJSON(calcData[i], geo.topojson); } @@ -54105,10 +55944,10 @@ var _$plot_741 = function plot(gd, geo, calcData) { gTraces.exit().remove(); gTraces.each(function(calcTrace) { - var sel = calcTrace[0].node3 = _$d3_127.select(this); + var sel = calcTrace[0].node3 = _$d3_130.select(this); var paths = sel.selectAll('path.choroplethlocation') - .data(_$lib_539.identity); + .data(_$lib_601.identity); paths.enter().append('path') .classed('choroplethlocation', true); @@ -54116,7 +55955,7 @@ var _$plot_741 = function plot(gd, geo, calcData) { paths.exit().remove(); // call style here within topojson request callback - _$style_743(gd, calcTrace); + _$style_805(gd, calcTrace); }); }; @@ -54181,7 +56020,7 @@ function feature2polygons(feature) { } } - polygons.push(_$polygon_551.tester(pts)); + polygons.push(_$polygon_613.tester(pts)); }; } else if(loc === 'ATA') { // Antarctica has a landmass that wraps around every longitudes which @@ -54191,7 +56030,7 @@ function feature2polygons(feature) { // polygon that do not cross anti-meridian need no special handling if(crossAntiMeridianIndex === null) { - return polygons.push(_$polygon_551.tester(pts)); + return polygons.push(_$polygon_613.tester(pts)); } // stitch polygon by adding pt over South Pole, @@ -54217,14 +56056,14 @@ function feature2polygons(feature) { // 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_551.tester(stitch); + var tester = _$polygon_613.tester(stitch); tester.pts.pop(); polygons.push(tester); }; } else { // otherwise using same array ref is fine appendPolygon = function(pts) { - polygons.push(_$polygon_551.tester(pts)); + polygons.push(_$polygon_613.tester(pts)); }; } @@ -54256,7 +56095,7 @@ function feature2polygons(feature) { 'use strict'; -var _$selectPoints_742 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_804 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -54305,33 +56144,33 @@ var _$selectPoints_742 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_776 = function colorbar(gd, cd) { +var _$colorbar_838 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, zmin = trace.zmin, zmax = trace.zmax; - if(!_$fastIsnumeric_139(zmin)) zmin = _$lib_539.aggNums(Math.min, null, trace.z); - if(!_$fastIsnumeric_139(zmax)) zmax = _$lib_539.aggNums(Math.max, null, trace.z); + if(!_$fastIsnumeric_196(zmin)) zmin = _$lib_601.aggNums(Math.min, null, trace.z); + if(!_$fastIsnumeric_196(zmax)) zmax = _$lib_601.aggNums(Math.max, null, trace.z); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, zmin, zmax @@ -54357,25 +56196,25 @@ var _$colorbar_776 = function colorbar(gd, cd) { var Choropleth = {}; -Choropleth.attributes = _$attributes_735; -Choropleth.supplyDefaults = _$supplyDefaults_737; -Choropleth.colorbar = _$colorbar_776; -Choropleth.calc = _$calc_736; -Choropleth.plot = _$plot_741; -Choropleth.style = _$style_743; -Choropleth.hoverPoints = _$hoverPoints_739; -Choropleth.eventData = _$eventData_738; -Choropleth.selectPoints = _$selectPoints_742; +Choropleth.attributes = _$attributes_797; +Choropleth.supplyDefaults = _$supplyDefaults_799; +Choropleth.colorbar = _$colorbar_838; +Choropleth.calc = _$calc_798; +Choropleth.plot = _$plot_803; +Choropleth.style = _$style_805; +Choropleth.hoverPoints = _$hoverPoints_801; +Choropleth.eventData = _$eventData_800; +Choropleth.selectPoints = _$selectPoints_804; Choropleth.moduleType = 'trace'; Choropleth.name = 'choropleth'; -Choropleth.basePlotModule = _$geo_615; +Choropleth.basePlotModule = _$geo_677; Choropleth.categories = ['geo', 'noOpacity']; Choropleth.meta = { }; -var _$Choropleth_740 = Choropleth; +var _$Choropleth_802 = Choropleth; /** * Copyright 2012-2018, Plotly, Inc. @@ -54387,7 +56226,7 @@ var _$Choropleth_740 = Choropleth; 'use strict'; -var _$choropleth_9 = _$Choropleth_740; +var _$choropleth_9 = _$Choropleth_802; /** * Copyright 2012-2018, Plotly, Inc. @@ -54399,7 +56238,7 @@ var _$choropleth_9 = _$Choropleth_740; 'use strict'; -var _$filter_ops_512 = { +var _$filter_ops_574 = { COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='], COMPARISON_OPS2: ['=', '<', '>=', '>', '<='], INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['], @@ -54436,24 +56275,24 @@ var _$filter_ops_512 = { 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_773 = _$extend_528.extendFlat; +var __extendFlat_835 = _$extend_590.extendFlat; -var _$attributes_773 = __extendFlat_773({}, { +var _$attributes_835 = __extendFlat_835({}, { z: { valType: 'data_array', editType: 'calc', }, - x: __extendFlat_773({}, _$attributes_862.x, {impliedEdits: {xtype: 'array'}}), - x0: __extendFlat_773({}, _$attributes_862.x0, {impliedEdits: {xtype: 'scaled'}}), - dx: __extendFlat_773({}, _$attributes_862.dx, {impliedEdits: {xtype: 'scaled'}}), - y: __extendFlat_773({}, _$attributes_862.y, {impliedEdits: {ytype: 'array'}}), - y0: __extendFlat_773({}, _$attributes_862.y0, {impliedEdits: {ytype: 'scaled'}}), - dy: __extendFlat_773({}, _$attributes_862.dy, {impliedEdits: {ytype: 'scaled'}}), + x: __extendFlat_835({}, _$attributes_927.x, {impliedEdits: {xtype: 'array'}}), + x0: __extendFlat_835({}, _$attributes_927.x0, {impliedEdits: {xtype: 'scaled'}}), + dx: __extendFlat_835({}, _$attributes_927.dx, {impliedEdits: {xtype: 'scaled'}}), + y: __extendFlat_835({}, _$attributes_927.y, {impliedEdits: {ytype: 'array'}}), + y0: __extendFlat_835({}, _$attributes_927.y0, {impliedEdits: {ytype: 'scaled'}}), + dy: __extendFlat_835({}, _$attributes_927.dy, {impliedEdits: {ytype: 'scaled'}}), text: { valType: 'data_array', @@ -54520,9 +56359,9 @@ var _$attributes_773 = __extendFlat_773({}, { }, }, - _$attributes_417, - { autocolorscale: __extendFlat_773({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } + _$attributes_479, + { autocolorscale: __extendFlat_835({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); /** @@ -54535,35 +56374,35 @@ var _$attributes_773 = __extendFlat_773({}, { 'use strict'; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -var __dash_744 = _$attributes_435.dash; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __extendFlat_744 = _$extend_528.extendFlat; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +var __dash_806 = _$attributes_497.dash; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __extendFlat_806 = _$extend_590.extendFlat; -/* removed: var _$filter_ops_512 = require('../../constants/filter_ops'); */; -var COMPARISON_OPS2 = _$filter_ops_512.COMPARISON_OPS2; -var INTERVAL_OPS = _$filter_ops_512.INTERVAL_OPS; +/* removed: var _$filter_ops_574 = require('../../constants/filter_ops'); */; +var COMPARISON_OPS2 = _$filter_ops_574.COMPARISON_OPS2; +var INTERVAL_OPS = _$filter_ops_574.INTERVAL_OPS; -var __scatterLineAttrs_744 = _$attributes_862.line; +var __scatterLineAttrs_806 = _$attributes_927.line; -var _$attributes_744 = __extendFlat_744({ - z: _$attributes_773.z, - x: _$attributes_773.x, - x0: _$attributes_773.x0, - dx: _$attributes_773.dx, - y: _$attributes_773.y, - y0: _$attributes_773.y0, - dy: _$attributes_773.dy, - text: _$attributes_773.text, - transpose: _$attributes_773.transpose, - xtype: _$attributes_773.xtype, - ytype: _$attributes_773.ytype, - zhoverformat: _$attributes_773.zhoverformat, +var _$attributes_806 = __extendFlat_806({ + z: _$attributes_835.z, + x: _$attributes_835.x, + x0: _$attributes_835.x0, + dx: _$attributes_835.dx, + y: _$attributes_835.y, + y0: _$attributes_835.y0, + dy: _$attributes_835.dy, + text: _$attributes_835.text, + transpose: _$attributes_835.transpose, + xtype: _$attributes_835.xtype, + ytype: _$attributes_835.ytype, + zhoverformat: _$attributes_835.zhoverformat, - connectgaps: _$attributes_773.connectgaps, + connectgaps: _$attributes_835.connectgaps, fillcolor: { valType: 'color', @@ -54649,7 +56488,7 @@ var _$attributes_744 = __extendFlat_744({ editType: 'plot', }, - labelfont: _$font_attributes_611({ + labelfont: _$font_attributes_673({ editType: 'plot', colorEditType: 'style', @@ -54681,26 +56520,26 @@ var _$attributes_744 = __extendFlat_744({ }, line: { - color: __extendFlat_744({}, __scatterLineAttrs_744.color, { + color: __extendFlat_806({}, __scatterLineAttrs_806.color, { editType: 'style+colorbars', }), - width: __extendFlat_744({}, __scatterLineAttrs_744.width, { + width: __extendFlat_806({}, __scatterLineAttrs_806.width, { editType: 'style+colorbars' }), - dash: __dash_744, - smoothing: __extendFlat_744({}, __scatterLineAttrs_744.smoothing, { + dash: __dash_806, + smoothing: __extendFlat_806({}, __scatterLineAttrs_806.smoothing, { }), editType: 'plot' } }, - _$attributes_417, { - autocolorscale: __extendFlat_744({}, _$attributes_417.autocolorscale, {dflt: false}), - zmin: __extendFlat_744({}, _$attributes_417.zmin, {editType: 'calc'}), - zmax: __extendFlat_744({}, _$attributes_417.zmax, {editType: 'calc'}) + _$attributes_479, { + autocolorscale: __extendFlat_806({}, _$attributes_479.autocolorscale, {dflt: false}), + zmin: __extendFlat_806({}, _$attributes_479.zmin, {editType: 'calc'}), + zmax: __extendFlat_806({}, _$attributes_479.zmax, {editType: 'calc'}) }, - { colorbar: _$attributes_412 } + { colorbar: _$attributes_474 } ); /** @@ -54714,11 +56553,11 @@ var _$attributes_744 = __extendFlat_744({ 'use strict'; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __extendFlat_763 = _$lib_539.extendFlat; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __extendFlat_825 = _$lib_601.extendFlat; -var _$setContours_763 = function setContours(trace) { +var _$setContours_825 = function setContours(trace) { var contours = trace.contours; // check if we need to auto-choose contour levels @@ -54727,9 +56566,9 @@ var _$setContours_763 = function setContours(trace) { contours.size = dummyAx.dtick; - contours.start = _$axes_584.tickFirst(dummyAx); + contours.start = _$axes_647.tickFirst(dummyAx); dummyAx.range.reverse(); - contours.end = _$axes_584.tickFirst(dummyAx); + contours.end = _$axes_647.tickFirst(dummyAx); if(contours.start === trace.zmin) contours.start += contours.size; if(contours.end === trace.zmax) contours.end -= contours.size; @@ -54745,7 +56584,7 @@ var _$setContours_763 = function setContours(trace) { // previously we copied the whole contours object back, but that had // other info (coloring, showlines) that should be left to supplyDefaults if(!trace._input.contours) trace._input.contours = {}; - __extendFlat_763(trace._input.contours, { + __extendFlat_825(trace._input.contours, { start: contours.start, end: contours.end, size: contours.size @@ -54792,7 +56631,7 @@ function autoContours(start, end, ncontours) { range: [start, end] }; - _$axes_584.autoTicks( + _$axes_647.autoTicks( dummyAx, (end - start) / (ncontours || 15) ); @@ -54811,7 +56650,7 @@ function autoContours(start, end, ncontours) { 'use strict'; -var _$maxRowLength_785 = function maxRowLength(z) { +var _$maxRowLength_847 = function maxRowLength(z) { var len = 0; for(var i = 0; i < z.length; i++) { @@ -54831,7 +56670,7 @@ var _$maxRowLength_785 = function maxRowLength(z) { 'use strict'; -/* removed: var _$maxRowLength_785 = require('./max_row_length'); */; +/* removed: var _$maxRowLength_847 = require('./max_row_length'); */; /* Return a list of empty points in 2D array z * each empty point z[i][j] gives an array [i, j, neighborCount] @@ -54840,14 +56679,14 @@ var _$maxRowLength_785 = function maxRowLength(z) { * if no neighbors exist, we iteratively look for neighbors that HAVE * neighbors, and add a fractional neighborCount */ -var _$findEmpties_779 = function findEmpties(z) { +var _$findEmpties_841 = function findEmpties(z) { var empties = [], neighborHash = {}, noNeighborList = [], nextRow = z[0], row = [], blank = [0, 0, 0], - rowLength = _$maxRowLength_785(z), + rowLength = _$maxRowLength_847(z), prevRow, i, j, @@ -54936,10 +56775,10 @@ var _$findEmpties_779 = function findEmpties(z) { 'use strict'; -var __isArrayOrTypedArray_780 = _$lib_539.isArrayOrTypedArray; +var __isArrayOrTypedArray_842 = _$lib_601.isArrayOrTypedArray; -var _$has_columns_780 = function(trace) { - return !__isArrayOrTypedArray_780(trace.z[0]); +var _$has_columns_842 = function(trace) { + return !__isArrayOrTypedArray_842(trace.z[0]); }; /** @@ -54952,7 +56791,7 @@ var _$has_columns_780 = function(trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; var INTERPTHRESHOLD = 1e-2, NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; @@ -54963,7 +56802,7 @@ function correctionOvershoot(maxFractionalChange) { return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5); } -var _$interp2d_783 = function interp2d(z, emptyPoints, savedInterpZ) { +var _$interp2d_845 = function interp2d(z, emptyPoints, savedInterpZ) { // fill in any missing data in 2D array z using an iterative // poisson equation solver with zero-derivative BC at edges // amazingly, this just amounts to repeatedly averaging all the existing @@ -54996,7 +56835,7 @@ var _$interp2d_783 = function interp2d(z, emptyPoints, savedInterpZ) { correctionOvershoot(maxFractionalChange)); } if(maxFractionalChange > INTERPTHRESHOLD) { - _$lib_539.log('interp2d didn\'t converge quickly', maxFractionalChange); + _$lib_601.log('interp2d didn\'t converge quickly', maxFractionalChange); } return z; @@ -55083,19 +56922,19 @@ function iterateInterp2d(z, emptyPoints, overshoot) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -var __isArrayOrTypedArray_784 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$registry_731 = require('../../registry'); */; +var __isArrayOrTypedArray_846 = _$lib_601.isArrayOrTypedArray; -var _$makeBoundArray_784 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { +var _$makeBoundArray_846 = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) { var arrayOut = [], - isContour = _$registry_668.traceIs(trace, 'contour'), - isHist = _$registry_668.traceIs(trace, 'histogram'), - isGL2D = _$registry_668.traceIs(trace, 'gl2d'), + isContour = _$registry_731.traceIs(trace, 'contour'), + isHist = _$registry_731.traceIs(trace, 'histogram'), + isGL2D = _$registry_731.traceIs(trace, 'gl2d'), v0, dv, i; - var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_784(arrayIn) && arrayIn.length > 1; + var isArrayOfTwoItemsOrMore = __isArrayOrTypedArray_846(arrayIn) && arrayIn.length > 1; if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) { var len = arrayIn.length; @@ -55143,7 +56982,7 @@ var _$makeBoundArray_784 = function makeBoundArray(trace, arrayIn, v0In, dvIn, n var calendar = trace[ax._id.charAt(0) + 'calendar']; if(isHist || ax.type === 'category') v0 = ax.r2c(v0In, 0, calendar) || 0; - else if(__isArrayOrTypedArray_784(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; + else if(__isArrayOrTypedArray_846(arrayIn) && arrayIn.length === 1) v0 = arrayIn[0]; else if(v0In === undefined) v0 = 0; else v0 = ax.d2c(v0In, 0, calendar); @@ -55167,7 +57006,7 @@ var _$makeBoundArray_784 = function makeBoundArray(trace, arrayIn, v0In, dvIn, n 'use strict'; -var _$doAvg_794 = function doAvg(size, counts) { +var _$doAvg_856 = function doAvg(size, counts) { var nMax = size.length, total = 0; for(var i = 0; i < nMax; i++) { @@ -55191,10 +57030,10 @@ var _$doAvg_794 = function doAvg(size, counts) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -var _$bin_functions_796 = { +var _$bin_functions_858 = { count: function(n, i, size) { size[n]++; return 1; @@ -55202,7 +57041,7 @@ var _$bin_functions_796 = { sum: function(n, i, size, counterData) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); size[n] += v; return v; @@ -55212,7 +57051,7 @@ var _$bin_functions_796 = { avg: function(n, i, size, counterData, counts) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); size[n] += v; counts[n]++; @@ -55222,9 +57061,9 @@ var _$bin_functions_796 = { min: function(n, i, size, counterData) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); - if(!_$fastIsnumeric_139(size[n])) { + if(!_$fastIsnumeric_196(size[n])) { size[n] = v; return v; } @@ -55239,9 +57078,9 @@ var _$bin_functions_796 = { max: function(n, i, size, counterData) { var v = counterData[i]; - if(_$fastIsnumeric_139(v)) { + if(_$fastIsnumeric_196(v)) { v = Number(v); - if(!_$fastIsnumeric_139(size[n])) { + if(!_$fastIsnumeric_196(size[n])) { size[n] = v; return v; } @@ -55266,14 +57105,14 @@ var _$bin_functions_796 = { 'use strict'; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var oneYear = _$numerical_517.ONEAVGYEAR; -var oneMonth = _$numerical_517.ONEAVGMONTH; -var oneDay = _$numerical_517.ONEDAY; -var oneHour = _$numerical_517.ONEHOUR; -var oneMin = _$numerical_517.ONEMIN; -var oneSec = _$numerical_517.ONESEC; -var tickIncrement = _$axes_584.tickIncrement; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var oneYear = _$numerical_578.ONEAVGYEAR; +var oneMonth = _$numerical_578.ONEAVGMONTH; +var oneDay = _$numerical_578.ONEDAY; +var oneHour = _$numerical_578.ONEHOUR; +var oneMin = _$numerical_578.ONEMIN; +var oneSec = _$numerical_578.ONESEC; +var tickIncrement = _$axes_647.tickIncrement; /* @@ -55287,7 +57126,7 @@ var tickIncrement = _$axes_584.tickIncrement; * @return {function(v, isRightEdge)}: * find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v` */ -var _$getBinSpanLabelRound_797 = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) { +var _$getBinSpanLabelRound_859 = 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) @@ -55442,11 +57281,11 @@ function dateParts(v, pa, calendar) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var cleanDate = _$lib_539.cleanDate; -/* removed: var _$numerical_517 = require('../../constants/numerical'); */; -var __ONEDAY_799 = _$numerical_517.ONEDAY; -var __BADNUM_799 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var cleanDate = _$lib_601.cleanDate; +/* removed: var _$numerical_578 = require('../../constants/numerical'); */; +var __ONEDAY_861 = _$numerical_578.ONEDAY; +var __BADNUM_861 = _$numerical_578.BADNUM; /* * cleanBins: validate attributes autobin[xy] and [xy]bins.(start, end, size) @@ -55457,7 +57296,7 @@ var __BADNUM_799 = _$numerical_517.BADNUM; * after trace supplyDefaults are completed. So this gets called during the * calc step, when data are inserted into bins. */ -var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { +var _$cleanBins_861 = function cleanBins(trace, ax, binDirection) { var axType = ax.type, binAttr = binDirection + 'bins', bins = trace[binAttr]; @@ -55465,8 +57304,8 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { if(!bins) bins = trace[binAttr] = {}; var cleanBound = (axType === 'date') ? - function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_799, bins.calendar) : null; } : - function(v) { return _$fastIsnumeric_139(v) ? Number(v) : null; }; + function(v) { return (v || v === 0) ? cleanDate(v, __BADNUM_861, bins.calendar) : null; } : + function(v) { return _$fastIsnumeric_196(v) ? Number(v) : null; }; bins.start = cleanBound(bins.start); bins.end = cleanBound(bins.end); @@ -55474,10 +57313,10 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { // logic for bin size is very similar to dtick (cartesian/tick_value_defaults) // but without the extra string options for log axes // ie the only strings we accept are M for months - var sizeDflt = (axType === 'date') ? __ONEDAY_799 : 1, + var sizeDflt = (axType === 'date') ? __ONEDAY_861 : 1, binSize = bins.size; - if(_$fastIsnumeric_139(binSize)) { + if(_$fastIsnumeric_196(binSize)) { bins.size = (binSize > 0) ? Number(binSize) : sizeDflt; } else if(typeof binSize !== 'string') { @@ -55488,7 +57327,7 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { var prefix = binSize.charAt(0), sizeNum = binSize.substr(1); - sizeNum = _$fastIsnumeric_139(sizeNum) ? Number(sizeNum) : 0; + sizeNum = _$fastIsnumeric_196(sizeNum) ? Number(sizeNum) : 0; if((sizeNum <= 0) || !( axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum) )) { @@ -55523,7 +57362,7 @@ var _$cleanBins_799 = function cleanBins(trace, ax, binDirection) { 'use strict'; -var _$norm_functions_804 = { +var _$norm_functions_866 = { percent: function(size, total) { var nMax = size.length, norm = 100 / total; @@ -55556,20 +57395,20 @@ var _$norm_functions_804 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$bin_functions_796 = require('../histogram/bin_functions'); */; -/* removed: var _$norm_functions_804 = require('../histogram/norm_functions'); */; -/* removed: var _$doAvg_794 = require('../histogram/average'); */; -/* removed: var _$cleanBins_799 = require('../histogram/clean_bins'); */; -/* removed: var _$getBinSpanLabelRound_797 = require('../histogram/bin_label_vals'); */; +/* removed: var _$bin_functions_858 = require('../histogram/bin_functions'); */; +/* removed: var _$norm_functions_866 = require('../histogram/norm_functions'); */; +/* removed: var _$doAvg_856 = require('../histogram/average'); */; +/* removed: var _$cleanBins_861 = require('../histogram/clean_bins'); */; +/* removed: var _$getBinSpanLabelRound_859 = require('../histogram/bin_label_vals'); */; -var _$calc_806 = function calc(gd, trace) { - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); +var _$calc_868 = function calc(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'); var x = trace.x ? xa.makeCalcdata(trace, 'x') : []; - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); + var ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'); var y = trace.y ? ya.makeCalcdata(trace, 'y') : []; var xcalendar = trace.xcalendar; var ycalendar = trace.ycalendar; @@ -55606,8 +57445,8 @@ var _$calc_806 = function calc(gd, trace) { var densitynorm = (norm.indexOf('density') !== -1); var extremefunc = (func === 'max' || func === 'min'); var sizeinit = (extremefunc ? null : 0); - var binfunc = _$bin_functions_796.count; - var normfunc = _$norm_functions_804[norm]; + var binfunc = _$bin_functions_858.count; + var normfunc = _$norm_functions_866[norm]; var doavg = false; var xinc = []; var yinc = []; @@ -55623,16 +57462,16 @@ var _$calc_806 = function calc(gd, trace) { trace.marker.color : ''); if(rawCounterData && func !== 'count') { doavg = func === 'avg'; - binfunc = _$bin_functions_796[func]; + binfunc = _$bin_functions_858[func]; } // decrease end a little in case of rounding errors var binSpec = trace.xbins, binStart = xr2c(binSpec.start), binEnd = xr2c(binSpec.end) + - (binStart - _$axes_584.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; + (binStart - _$axes_647.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6; - for(i = binStart; i < binEnd; i = _$axes_584.tickIncrement(i, binSpec.size, false, xcalendar)) { + for(i = binStart; i < binEnd; i = _$axes_647.tickIncrement(i, binSpec.size, false, xcalendar)) { onecol.push(sizeinit); xEdges.push(i); if(doavg) zerocol.push(0); @@ -55647,9 +57486,9 @@ var _$calc_806 = function calc(gd, trace) { binSpec = trace.ybins; binStart = yr2c(binSpec.start); binEnd = yr2c(binSpec.end) + - (binStart - _$axes_584.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; + (binStart - _$axes_647.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6; - for(i = binStart; i < binEnd; i = _$axes_584.tickIncrement(i, binSpec.size, false, ycalendar)) { + for(i = binStart; i < binEnd; i = _$axes_647.tickIncrement(i, binSpec.size, false, ycalendar)) { z.push(onecol.slice()); yEdges.push(i); var ipCol = new Array(nx); @@ -55686,8 +57525,8 @@ var _$calc_806 = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { var xi = x[i]; var yi = y[i]; - n = _$lib_539.findBin(xi, xbins); - m = _$lib_539.findBin(yi, ybins); + n = _$lib_601.findBin(xi, xbins); + m = _$lib_601.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); @@ -55709,7 +57548,7 @@ var _$calc_806 = function calc(gd, trace) { } // normalize, if needed if(doavg) { - for(m = 0; m < ny; m++) total += _$doAvg_794(z[m], counts[m]); + for(m = 0; m < ny; m++) total += _$doAvg_856(z[m], counts[m]); } if(normfunc) { for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); @@ -55734,16 +57573,16 @@ function cleanAndAutobin(trace, axLetter, data, ax, r2c, c2r, calendar) { var autoBinAttr = 'autobin' + axLetter; var binSpec = trace[binSpecAttr]; - _$cleanBins_799(trace, ax, axLetter); + _$cleanBins_861(trace, ax, axLetter); if(trace[autoBinAttr] || !binSpec || binSpec.start === null || binSpec.end === null) { - binSpec = _$axes_584.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); + binSpec = _$axes_647.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar); if(trace.type === 'histogram2dcontour') { // the "true" last argument reverses the tick direction (which we can't // just do with a minus sign because of month bins) - binSpec.start = c2r(_$axes_584.tickIncrement( + binSpec.start = c2r(_$axes_647.tickIncrement( r2c(binSpec.start), binSpec.size, true, calendar)); - binSpec.end = c2r(_$axes_584.tickIncrement( + binSpec.end = c2r(_$axes_647.tickIncrement( r2c(binSpec.end), binSpec.size, false, calendar)); } @@ -55786,7 +57625,7 @@ function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]]; } else { - var roundFn = _$getBinSpanLabelRound_797(gapLow, gapHigh, edges, ax, calendar); + var roundFn = _$getBinSpanLabelRound_859(gapLow, gapHigh, edges, ax, calendar); for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)]; } return out; @@ -55803,29 +57642,29 @@ function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calc_806 = require('../histogram2d/calc'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$has_columns_780 = require('./has_columns'); */; -/* removed: var _$convertColumnData_777 = require('./convert_column_xyz'); */; -/* removed: var _$maxRowLength_785 = require('./max_row_length'); */; -/* removed: var _$clean2dArray_775 = require('./clean_2d_array'); */; -/* removed: var _$interp2d_783 = require('./interp2d'); */; -/* removed: var _$findEmpties_779 = require('./find_empties'); */; -/* removed: var _$makeBoundArray_784 = require('./make_bound_array'); */; +/* removed: var _$calc_868 = require('../histogram2d/calc'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$has_columns_842 = require('./has_columns'); */; +/* removed: var _$convertColumnData_839 = require('./convert_column_xyz'); */; +/* removed: var _$maxRowLength_847 = require('./max_row_length'); */; +/* removed: var _$clean2dArray_837 = require('./clean_2d_array'); */; +/* removed: var _$interp2d_845 = require('./interp2d'); */; +/* removed: var _$findEmpties_841 = require('./find_empties'); */; +/* removed: var _$makeBoundArray_846 = require('./make_bound_array'); */; -var _$calc_774 = function calc(gd, trace) { +var _$calc_836 = 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_584.getFromId(gd, trace.xaxis || 'x'), - ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'), - isContour = _$registry_668.traceIs(trace, 'contour'), - isHist = _$registry_668.traceIs(trace, 'histogram'), - isGL2D = _$registry_668.traceIs(trace, 'gl2d'), + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'), + ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'), + isContour = _$registry_731.traceIs(trace, 'contour'), + isHist = _$registry_731.traceIs(trace, 'histogram'), + isGL2D = _$registry_731.traceIs(trace, 'gl2d'), zsmooth = isContour ? 'best' : trace.zsmooth, x, x0, @@ -55842,7 +57681,7 @@ var _$calc_774 = function calc(gd, trace) { ya._minDtick = 0; if(isHist) { - binned = _$calc_806(gd, trace); + binned = _$calc_868(gd, trace); x = binned.x; x0 = binned.x0; dx = binned.dx; @@ -55852,10 +57691,12 @@ var _$calc_774 = function calc(gd, trace) { z = binned.z; } else { - if(_$has_columns_780(trace)) { - _$convertColumnData_777(trace, xa, ya, 'x', 'y', ['z']); - x = trace.x; - y = trace.y; + var zIn = trace.z; + if(_$has_columns_842(trace)) { + _$convertColumnData_839(trace, xa, ya, 'x', 'y', ['z']); + x = trace._x; + y = trace._y; + zIn = trace._z; } else { x = trace.x ? xa.makeCalcdata(trace, 'x') : []; y = trace.y ? ya.makeCalcdata(trace, 'y') : []; @@ -55866,17 +57707,17 @@ var _$calc_774 = function calc(gd, trace) { y0 = trace.y0 || 0; dy = trace.dy || 1; - z = _$clean2dArray_775(trace.z, trace.transpose); + z = _$clean2dArray_837(zIn, trace.transpose); if(isContour || trace.connectgaps) { - trace._emptypoints = _$findEmpties_779(z); - trace._interpz = _$interp2d_783(z, trace._emptypoints, trace._interpz); + trace._emptypoints = _$findEmpties_841(z); + trace._interpz = _$interp2d_845(z, trace._emptypoints, trace._interpz); } } function noZsmooth(msg) { zsmooth = trace._input.zsmooth = trace.zsmooth = false; - _$lib_539.warn('cannot use zsmooth: "fast": ' + msg); + _$lib_601.warn('cannot use zsmooth: "fast": ' + msg); } // check whether we really can smooth (ie all boxes are about the same size) @@ -55909,23 +57750,23 @@ var _$calc_774 = function calc(gd, trace) { } // create arrays of brick boundaries, to be used by autorange and heatmap.plot - var xlen = _$maxRowLength_785(z); + var xlen = _$maxRowLength_847(z); var xIn = trace.xtype === 'scaled' ? '' : x; - var xArray = _$makeBoundArray_784(trace, xIn, x0, dx, xlen, xa); + var xArray = _$makeBoundArray_846(trace, xIn, x0, dx, xlen, xa); var yIn = trace.ytype === 'scaled' ? '' : y; - var yArray = _$makeBoundArray_784(trace, yIn, y0, dy, z.length, ya); + var yArray = _$makeBoundArray_846(trace, yIn, y0, dy, z.length, ya); // handled in gl2d convert step if(!isGL2D) { - _$axes_584.expand(xa, xArray); - _$axes_584.expand(ya, yArray); + _$axes_647.expand(xa, xArray); + _$axes_647.expand(ya, yArray); } var cd0 = { x: xArray, y: yArray, z: z, - text: trace.text + text: trace._text || trace.text }; if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn; @@ -55939,7 +57780,7 @@ var _$calc_774 = function calc(gd, trace) { // auto-z and autocolorscale if applicable if(!isContour || trace.contours.type !== 'constraint') { - _$calc_418(trace, z, '', 'z'); + _$calc_480(trace, z, '', 'z'); } if(isContour && trace.contours && trace.contours.coloring === 'heatmap') { @@ -55948,8 +57789,8 @@ var _$calc_774 = function calc(gd, trace) { xcalendar: trace.xcalendar, ycalendar: trace.ycalendar }; - cd0.xfill = _$makeBoundArray_784(dummyTrace, xIn, x0, dx, xlen, xa); - cd0.yfill = _$makeBoundArray_784(dummyTrace, yIn, y0, dy, z.length, ya); + cd0.xfill = _$makeBoundArray_846(dummyTrace, xIn, x0, dx, xlen, xa); + cd0.yfill = _$makeBoundArray_846(dummyTrace, yIn, y0, dy, z.length, ya); } return [cd0]; @@ -55966,15 +57807,15 @@ var _$calc_774 = function calc(gd, trace) { 'use strict'; -/* removed: var _$calc_774 = require('../heatmap/calc'); */; -/* removed: var _$setContours_763 = require('./set_contours'); */; +/* removed: var _$calc_836 = require('../heatmap/calc'); */; +/* removed: var _$setContours_825 = require('./set_contours'); */; // 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 -var _$calc_745 = function calc(gd, trace) { - var cd = _$calc_774(gd, trace); - _$setContours_763(trace); +var _$calc_807 = function calc(gd, trace) { + var cd = _$calc_836(gd, trace); + _$setContours_825(trace); return cd; }; @@ -55993,7 +57834,7 @@ var _$calc_745 = function calc(gd, trace) { * tiny helper to move the end of the contours a little to prevent * losing the last contour to rounding errors */ -var _$endPlus_755 = function endPlus(contours) { +var _$endPlus_817 = function endPlus(contours) { return contours.end + contours.size / 1e6; }; @@ -56008,14 +57849,14 @@ var _$endPlus_755 = function endPlus(contours) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$endPlus_755 = require('./end_plus'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$endPlus_817 = require('./end_plus'); */; -var _$makeColorMap_760 = function makeColorMap(trace) { +var _$makeColorMap_822 = function makeColorMap(trace) { var contours = trace.contours, start = contours.start, - end = _$endPlus_755(contours), + end = _$endPlus_817(contours), cs = contours.size || 1, nc = Math.floor((end - start) / cs) + 1, extra = contours.coloring === 'lines' ? 0 : 1; @@ -56048,7 +57889,7 @@ var _$makeColorMap_760 = function makeColorMap(trace) { // do the contours extend beyond the colorscale? // if so, extend the colorscale with constants - var zRange = _$d3_127.extent([trace.zmin, trace.zmax, contours.start, + var zRange = _$d3_130.extent([trace.zmin, trace.zmax, contours.start, contours.start + cs * (nc - 1)]), zmin = zRange[trace.zmin < trace.zmax ? 0 : 1], zmax = zRange[trace.zmin < trace.zmax ? 1 : 0]; @@ -56072,7 +57913,7 @@ var _$makeColorMap_760 = function makeColorMap(trace) { } } - return _$colorscale_426.makeColorScaleFunc({ + return _$colorscale_488.makeColorScaleFunc({ domain: domain, range: range, }, { @@ -56091,25 +57932,25 @@ var _$makeColorMap_760 = function makeColorMap(trace) { 'use strict'; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -/* removed: var _$makeColorMap_760 = require('./make_color_map'); */; -/* removed: var _$endPlus_755 = require('./end_plus'); */; +/* removed: var _$makeColorMap_822 = require('./make_color_map'); */; +/* removed: var _$endPlus_817 = require('./end_plus'); */; -var _$colorbar_747 = function colorbar(gd, cd) { +var _$colorbar_809 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid; gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = _$draw_415(gd, cbId); + var cb = _$draw_477(gd, cbId); cd[0].t.cb = cb; var contours = trace.contours, @@ -56117,7 +57958,7 @@ var _$colorbar_747 = function colorbar(gd, cd) { cs = contours.size || 1, coloring = contours.coloring; - var colorMap = _$makeColorMap_760(trace, {isColorbar: true}); + var colorMap = _$makeColorMap_822(trace, {isColorbar: true}); if(coloring === 'heatmap') { cb.filllevels({ @@ -56135,7 +57976,7 @@ var _$colorbar_747 = function colorbar(gd, cd) { }) .levels({ start: contours.start, - end: _$endPlus_755(contours), + end: _$endPlus_817(contours), size: cs }) .options(trace.colorbar)(); @@ -56152,14 +57993,14 @@ var _$colorbar_747 = function colorbar(gd, cd) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$handleLabelDefaults_759 = function handleLabelDefaults(coerce, layout, lineColor, opts) { +var _$handleLabelDefaults_821 = function handleLabelDefaults(coerce, layout, lineColor, opts) { if(!opts) opts = {}; var showLabels = coerce('contours.showlabels'); if(showLabels) { var globalFont = layout.font; - _$lib_539.coerceFont(coerce, 'contours.labelfont', { + _$lib_601.coerceFont(coerce, 'contours.labelfont', { family: globalFont.family, size: globalFont.size, color: lineColor @@ -56180,19 +58021,19 @@ var _$handleLabelDefaults_759 = function handleLabelDefaults(coerce, layout, lin 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$handleLabelDefaults_759 = require('./label_defaults'); */; +/* removed: var _$handleLabelDefaults_821 = require('./label_defaults'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -var __addOpacity_749 = _$color_411.addOpacity; -var opacity = _$color_411.opacity; +/* removed: var _$color_473 = require('../../components/color'); */; +var __addOpacity_811 = _$color_473.addOpacity; +var opacity = _$color_473.opacity; -/* removed: var _$filter_ops_512 = require('../../constants/filter_ops'); */; -var CONSTRAINT_REDUCTION = _$filter_ops_512.CONSTRAINT_REDUCTION; -var __COMPARISON_OPS2_749 = _$filter_ops_512.COMPARISON_OPS2; +/* removed: var _$filter_ops_574 = require('../../constants/filter_ops'); */; +var CONSTRAINT_REDUCTION = _$filter_ops_574.CONSTRAINT_REDUCTION; +var __COMPARISON_OPS2_811 = _$filter_ops_574.COMPARISON_OPS2; -var _$handleConstraintDefaults_749 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { +var _$handleConstraintDefaults_811 = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) { var contours = traceOut.contours; var showLines, lineColor, fillColor; @@ -56206,14 +58047,14 @@ var _$handleConstraintDefaults_749 = function handleConstraintDefaults(traceIn, } else { showLines = coerce('contours.showlines'); - fillColor = coerce('fillcolor', __addOpacity_749( + fillColor = coerce('fillcolor', __addOpacity_811( (traceIn.line || {}).color || defaultColor, 0.5 )); } if(showLines) { var lineDfltColor = fillColor && opacity(fillColor) ? - __addOpacity_749(traceOut.fillcolor, 1) : + __addOpacity_811(traceOut.fillcolor, 1) : defaultColor; lineColor = coerce('line.color', lineDfltColor); coerce('line.width', 2); @@ -56222,18 +58063,18 @@ var _$handleConstraintDefaults_749 = function handleConstraintDefaults(traceIn, coerce('line.smoothing'); - _$handleLabelDefaults_759(coerce, layout, lineColor, opts); + _$handleLabelDefaults_821(coerce, layout, lineColor, opts); }; function handleConstraintValueDefaults(coerce, contours) { var zvalue; - if(__COMPARISON_OPS2_749.indexOf(contours.operation) === -1) { + if(__COMPARISON_OPS2_811.indexOf(contours.operation) === -1) { // Requires an array of two numbers: coerce('contours.value', [0, 1]); if(!Array.isArray(contours.value)) { - if(_$fastIsnumeric_139(contours.value)) { + if(_$fastIsnumeric_196(contours.value)) { zvalue = parseFloat(contours.value); contours.value = [zvalue, zvalue + 1]; } @@ -56254,7 +58095,7 @@ function handleConstraintValueDefaults(coerce, contours) { // Requires a single scalar: coerce('contours.value', 0); - if(!_$fastIsnumeric_139(contours.value)) { + if(!_$fastIsnumeric_196(contours.value)) { if(Array.isArray(contours.value)) { contours.value = parseFloat(contours.value[0]); } else { @@ -56274,7 +58115,7 @@ function handleConstraintValueDefaults(coerce, contours) { 'use strict'; -var _$handleContourDefaults_751 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { +var _$handleContourDefaults_813 = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) { var contourStart = coerce2('contours.start'); var contourEnd = coerce2('contours.end'); var missingEnd = (contourStart === false) || (contourEnd === false); @@ -56303,11 +58144,11 @@ var _$handleContourDefaults_751 = function handleContourDefaults(traceIn, traceO 'use strict'; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$handleLabelDefaults_759 = require('./label_defaults'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$handleLabelDefaults_821 = require('./label_defaults'); */; -var _$handleStyleDefaults_765 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { +var _$handleStyleDefaults_827 = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) { var coloring = coerce('contours.coloring'); var showLines; @@ -56321,14 +58162,14 @@ var _$handleStyleDefaults_765 = function handleStyleDefaults(traceIn, traceOut, } if(coloring !== 'none') { - _$colorScaleDefaults_421( + _$colorScaleDefaults_483( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); } coerce('line.smoothing'); - _$handleLabelDefaults_759(coerce, layout, lineColor, opts); + _$handleLabelDefaults_821(coerce, layout, lineColor, opts); }; /** @@ -56342,13 +58183,13 @@ var _$handleStyleDefaults_765 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_789 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_851 = _$lib_601.isArrayOrTypedArray; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$has_columns_780 = require('./has_columns'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$has_columns_842 = require('./has_columns'); */; -var _$handleXYZDefaults_789 = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) { +var _$handleXYZDefaults_851 = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) { var z = coerce('z'); xName = xName || 'x'; yName = yName || 'y'; @@ -56356,7 +58197,7 @@ var _$handleXYZDefaults_789 = function handleXYZDefaults(traceIn, traceOut, coer if(z === undefined || !z.length) return 0; - if(_$has_columns_780(traceIn)) { + if(_$has_columns_842(traceIn)) { x = coerce(xName); y = coerce(yName); @@ -56373,7 +58214,7 @@ var _$handleXYZDefaults_789 = function handleXYZDefaults(traceIn, traceOut, coer coerce('transpose'); } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout); return traceOut.z.length; @@ -56409,13 +58250,13 @@ function isValidZ(z) { for(var i = 0; i < z.length; i++) { zi = z[i]; - if(!__isArrayOrTypedArray_789(zi)) { + if(!__isArrayOrTypedArray_851(zi)) { allRowsAreArrays = false; break; } if(zi.length > 0) oneRowIsFilled = true; for(var j = 0; j < zi.length; j++) { - if(_$fastIsnumeric_139(zi[j])) { + if(_$fastIsnumeric_196(zi[j])) { hasOneNumber = true; break; } @@ -56436,26 +58277,26 @@ function isValidZ(z) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$has_columns_780 = require('../heatmap/has_columns'); */; -/* removed: var _$handleXYZDefaults_789 = require('../heatmap/xyz_defaults'); */; -/* removed: var _$handleConstraintDefaults_749 = require('./constraint_defaults'); */; -/* removed: var _$handleContourDefaults_751 = require('./contours_defaults'); */; -/* removed: var _$handleStyleDefaults_765 = require('./style_defaults'); */; -/* removed: var _$attributes_744 = require('./attributes'); */; +/* removed: var _$has_columns_842 = require('../heatmap/has_columns'); */; +/* removed: var _$handleXYZDefaults_851 = require('../heatmap/xyz_defaults'); */; +/* removed: var _$handleConstraintDefaults_811 = require('./constraint_defaults'); */; +/* removed: var _$handleContourDefaults_813 = require('./contours_defaults'); */; +/* removed: var _$handleStyleDefaults_827 = require('./style_defaults'); */; +/* removed: var _$attributes_806 = require('./attributes'); */; -var _$supplyDefaults_753 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_815 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_744, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_806, attr, dflt); } function coerce2(attr) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_744, attr); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_806, attr); } - var len = _$handleXYZDefaults_789(traceIn, traceOut, coerce, layout); + var len = _$handleXYZDefaults_851(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -56463,17 +58304,17 @@ var _$supplyDefaults_753 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); var isConstraint = (coerce('contours.type') === 'constraint'); - coerce('connectgaps', _$has_columns_780(traceOut)); + coerce('connectgaps', _$has_columns_842(traceOut)); // trace-level showlegend has already been set, but is only allowed if this is a constraint if(!isConstraint) delete traceOut.showlegend; if(isConstraint) { - _$handleConstraintDefaults_749(traceIn, traceOut, coerce, layout, defaultColor); + _$handleConstraintDefaults_811(traceIn, traceOut, coerce, layout, defaultColor); } else { - _$handleContourDefaults_751(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_765(traceIn, traceOut, coerce, layout); + _$handleContourDefaults_813(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_827(traceIn, traceOut, coerce, layout); } }; @@ -56488,11 +58329,11 @@ var _$supplyDefaults_753 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { +var _$hoverPoints_843 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { var cd0 = pointData.cd[0]; var trace = cd0.trace; var xa = pointData.xa; @@ -56516,7 +58357,7 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h ny = Math.round(pointData.index[0]); } catch(e) { - _$lib_539.error('Error hovering on heatmap, ' + + _$lib_601.error('Error hovering on heatmap, ' + 'pointNumber must be [row,col], found:', pointData.index); return; } @@ -56524,8 +58365,8 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h return; } } - else if(_$fx_453.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || - _$fx_453.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) { + else if(_$fx_515.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || + _$fx_515.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) { return; } else { @@ -56544,8 +58385,8 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h } y2.push([2 * y[y.length - 1] - y[y.length - 2]]); } - nx = Math.max(0, Math.min(x2.length - 2, _$lib_539.findBin(xval, x2))); - ny = Math.max(0, Math.min(y2.length - 2, _$lib_539.findBin(yval, y2))); + nx = Math.max(0, Math.min(x2.length - 2, _$lib_601.findBin(xval, x2))); + ny = Math.max(0, Math.min(y2.length - 2, _$lib_601.findBin(yval, y2))); } var x0 = xa.c2p(x[nx]), @@ -56585,10 +58426,10 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h _separators: xa._separators, _numFormat: xa._numFormat }; - var zLabelObj = _$axes_584.tickText(dummyAx, zVal, 'hover'); + var zLabelObj = _$axes_647.tickText(dummyAx, zVal, 'hover'); zLabel = zLabelObj.text; - return [_$lib_539.extendFlat(pointData, { + return [_$lib_601.extendFlat(pointData, { index: [ny, nx], // never let a 2D override 1D type as closest point distance: pointData.maxHoverDistance, @@ -56616,22 +58457,22 @@ var _$hoverPoints_781 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$hoverPoints_781 = require('../heatmap/hover'); */; +/* removed: var _$hoverPoints_843 = require('../heatmap/hover'); */; -var _$hoverPoints_757 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { - var hoverData = _$hoverPoints_781(pointData, xval, yval, hovermode, hoverLayer, true); +var _$hoverPoints_819 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { + var hoverData = _$hoverPoints_843(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_411.opacity(trace.fillcolor)) { - hoverPt.color = _$color_411.addOpacity(trace.fillcolor, 1); + if(trace.fillcolor && _$color_473.opacity(trace.fillcolor)) { + hoverPt.color = _$color_473.addOpacity(trace.fillcolor, 1); } - else if(trace.contours.showlines && _$color_411.opacity(trace.line.color)) { - hoverPt.color = _$color_411.addOpacity(trace.line.color, 1); + else if(trace.contours.showlines && _$color_473.opacity(trace.line.color)) { + hoverPt.color = _$color_473.addOpacity(trace.line.color, 1); } } }); @@ -56650,7 +58491,7 @@ var _$hoverPoints_757 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -var _$close_boundaries_746 = function(pathinfo, operation, perimeter, trace) { +var _$close_boundaries_808 = function(pathinfo, operation, perimeter, trace) { // Abandon all hope, ye who enter here. var i, v1, v2; var pi0 = pathinfo[0]; @@ -56715,7 +58556,7 @@ var _$close_boundaries_746 = function(pathinfo, operation, perimeter, trace) { */ 'use strict'; -var _$constants_748 = { +var _$constants_810 = { // some constants to help with marching squares algorithm // where does the path start for each index? BOTTOMSTART: [1, 9, 13, 104, 713], @@ -56793,13 +58634,13 @@ var _$constants_748 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; // 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. -var _$convert_to_constraints_752 = function(pathinfo, operation) { +var _$convert_to_constraints_814 = function(pathinfo, operation) { var i, pi0, pi1; var op0 = function(arr) { return arr.reverse(); }; @@ -56811,7 +58652,7 @@ var _$convert_to_constraints_752 = function(pathinfo, operation) { return pathinfo; case '>': if(pathinfo.length !== 1) { - _$lib_539.warn('Contour data invalid for the specified inequality operation.'); + _$lib_601.warn('Contour data invalid for the specified inequality operation.'); } // In this case there should be exactly two contour levels in pathinfo. We @@ -56836,7 +58677,7 @@ var _$convert_to_constraints_752 = function(pathinfo, operation) { case '[]': /* eslint-enable: no-fallthrough */ if(pathinfo.length !== 2) { - _$lib_539.warn('Contour data invalid for the specified inequality range operation.'); + _$lib_601.warn('Contour data invalid for the specified inequality range operation.'); } // In this case there should be exactly two contour levels in pathinfo. We @@ -56864,9 +58705,9 @@ var _$convert_to_constraints_752 = function(pathinfo, operation) { }; function copyPathinfo(pi) { - return _$lib_539.extendFlat({}, pi, { - edgepaths: _$lib_539.extendDeep([], pi.edgepaths), - paths: _$lib_539.extendDeep([], pi.paths) + return _$lib_601.extendFlat({}, pi, { + edgepaths: _$lib_601.extendDeep([], pi.edgepaths), + paths: _$lib_601.extendDeep([], pi.paths) }); } @@ -56880,12 +58721,12 @@ function copyPathinfo(pi) { 'use strict'; -/* removed: var _$filter_ops_512 = require('../../constants/filter_ops'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$filter_ops_574 = require('../../constants/filter_ops'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; // This syntax conforms to the existing filter transform syntax, but we don't care // about open vs. closed intervals for simply drawing contours constraints: -var _$constraint_mapping_750 = { +var _$constraint_mapping_812 = { '[]': makeRangeSettings('[]'), '][': makeRangeSettings(']['), '>': makeInequalitySettings('>'), @@ -56901,16 +58742,16 @@ function coerceValue(operation, value) { var coercedValue; function coerce(value) { - return _$fastIsnumeric_139(value) ? (+value) : null; + return _$fastIsnumeric_196(value) ? (+value) : null; } - if(_$filter_ops_512.COMPARISON_OPS2.indexOf(operation) !== -1) { + if(_$filter_ops_574.COMPARISON_OPS2.indexOf(operation) !== -1) { coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value); - } else if(_$filter_ops_512.INTERVAL_OPS.indexOf(operation) !== -1) { + } else if(_$filter_ops_574.INTERVAL_OPS.indexOf(operation) !== -1) { coercedValue = hasArrayValue ? [coerce(value[0]), coerce(value[1])] : [coerce(value), coerce(value)]; - } else if(_$filter_ops_512.SET_OPS.indexOf(operation) !== -1) { + } else if(_$filter_ops_574.SET_OPS.indexOf(operation) !== -1) { coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)]; } @@ -56958,20 +58799,20 @@ function makeInequalitySettings(operation) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$constraint_mapping_750 = require('./constraint_mapping'); */; -/* removed: var _$endPlus_755 = require('./end_plus'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$constraint_mapping_812 = require('./constraint_mapping'); */; +/* removed: var _$endPlus_817 = require('./end_plus'); */; -var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { +var _$emptyPathinfo_816 = function emptyPathinfo(contours, plotinfo, cd0) { var contoursFinal = (contours.type === 'constraint') ? - _$constraint_mapping_750[contours._operation](contours.value) : + _$constraint_mapping_812[contours._operation](contours.value) : contours; var cs = contoursFinal.size; var pathinfo = []; - var end = _$endPlus_755(contoursFinal); + var end = _$endPlus_817(contoursFinal); - var carpet = cd0.trace.carpetTrace; + var carpet = cd0.trace._carpetTrace; var basePathinfo = carpet ? { // store axes so we can convert to px @@ -56988,7 +58829,7 @@ var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { }; for(var ci = contoursFinal.start; ci < end; ci += cs) { - pathinfo.push(_$lib_539.extendFlat({ + pathinfo.push(_$lib_601.extendFlat({ level: ci, // all the cells with nontrivial marching index crossings: {}, @@ -57004,7 +58845,7 @@ var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { }, basePathinfo)); if(pathinfo.length > 1000) { - _$lib_539.warn('Too many contours, clipping at 1000', contours); + _$lib_601.warn('Too many contours, clipping at 1000', contours); break; } } @@ -57021,10 +58862,10 @@ var _$emptyPathinfo_754 = function emptyPathinfo(contours, plotinfo, cd0) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$constants_748 = require('./constants'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$constants_810 = require('./constants'); */; -var _$findAllPaths_756 = function findAllPaths(pathinfo, xtol, ytol) { +var _$findAllPaths_818 = function findAllPaths(pathinfo, xtol, ytol) { var cnt, startLoc, i, @@ -57049,7 +58890,7 @@ var _$findAllPaths_756 = function findAllPaths(pathinfo, xtol, ytol) { startLoc = Object.keys(pi.crossings)[0].split(',').map(Number); makePath(pi, startLoc, undefined, xtol, ytol); } - if(cnt === 10000) _$lib_539.log('Infinite loop in contour?'); + if(cnt === 10000) _$lib_601.log('Infinite loop in contour?'); } }; @@ -57080,16 +58921,16 @@ function makePath(pi, loc, edgeflag, xtol, ytol) { // now follow the path for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops if(mi > 20) { - mi = _$constants_748.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1]; - pi.crossings[locStr] = _$constants_748.SADDLEREMAINDER[mi]; + mi = _$constants_810.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1]; + pi.crossings[locStr] = _$constants_810.SADDLEREMAINDER[mi]; } else { delete pi.crossings[locStr]; } - marchStep = _$constants_748.NEWDELTA[mi]; + marchStep = _$constants_810.NEWDELTA[mi]; if(!marchStep) { - _$lib_539.log('Found bad marching index:', mi, loc, pi.level); + _$lib_601.log('Found bad marching index:', mi, loc, pi.level); break; } @@ -57113,7 +58954,7 @@ function makePath(pi, loc, edgeflag, xtol, ytol) { } if(cnt === 10000) { - _$lib_539.log('Infinite loop in contour?'); + _$lib_601.log('Infinite loop in contour?'); } var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol); var totaldist = 0; @@ -57200,7 +59041,7 @@ function makePath(pi, loc, edgeflag, xtol, ytol) { } else { if(!edgeflag) { - _$lib_539.log('Unclosed interior contour?', + _$lib_601.log('Unclosed interior contour?', pi.level, startLocStr, pts.join('L')); } @@ -57266,9 +59107,9 @@ function startStep(mi, edgeflag, loc) { dy = loc[1] === 0 ? 1 : -1; } } - else if(_$constants_748.BOTTOMSTART.indexOf(mi) !== -1) dy = 1; - else if(_$constants_748.LEFTSTART.indexOf(mi) !== -1) dx = 1; - else if(_$constants_748.TOPSTART.indexOf(mi) !== -1) dy = -1; + else if(_$constants_810.BOTTOMSTART.indexOf(mi) !== -1) dy = 1; + else if(_$constants_810.LEFTSTART.indexOf(mi) !== -1) dx = 1; + else if(_$constants_810.TOPSTART.indexOf(mi) !== -1) dy = -1; else dx = -1; return [dx, dy]; } @@ -57320,13 +59161,13 @@ function getInterpPx(pi, loc, step) { 'use strict'; -/* removed: var _$constants_748 = require('./constants'); */; +/* removed: var _$constants_810 = require('./constants'); */; // Calculate all the marching indices, for ALL levels at once. // since we want to be exhaustive we'll check for contour crossings // at every intersection, rather than just following a path // TODO: shorten the inner loop to only the relevant levels -var _$makeCrossings_761 = function makeCrossings(pathinfo) { +var _$makeCrossings_823 = function makeCrossings(pathinfo) { var z = pathinfo[0].z, m = z.length, n = z[0].length, // we already made sure z isn't ragged in interp2d @@ -57343,13 +59184,13 @@ var _$makeCrossings_761 = function makeCrossings(pathinfo) { for(yi = 0; yi < m - 1; yi++) { ystartIndices = []; - if(yi === 0) ystartIndices = ystartIndices.concat(_$constants_748.BOTTOMSTART); - if(yi === m - 2) ystartIndices = ystartIndices.concat(_$constants_748.TOPSTART); + if(yi === 0) ystartIndices = ystartIndices.concat(_$constants_810.BOTTOMSTART); + if(yi === m - 2) ystartIndices = ystartIndices.concat(_$constants_810.TOPSTART); for(xi = 0; xi < n - 1; xi++) { startIndices = ystartIndices.slice(); - if(xi === 0) startIndices = startIndices.concat(_$constants_748.LEFTSTART); - if(xi === n - 2) startIndices = startIndices.concat(_$constants_748.RIGHTSTART); + if(xi === 0) startIndices = startIndices.concat(_$constants_810.LEFTSTART); + if(xi === n - 2) startIndices = startIndices.concat(_$constants_810.RIGHTSTART); label = xi + ',' + yi; corners = [[z[yi][xi], z[yi][xi + 1]], @@ -57412,23 +59253,23 @@ function getMarchingIndex(val, corners) { 'use strict'; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$maxRowLength_785 = require('./max_row_length'); */; +/* removed: var _$maxRowLength_847 = require('./max_row_length'); */; -var _$plot_786 = function(gd, plotinfo, cdheatmaps) { +var _$plot_848 = function(gd, plotinfo, cdheatmaps) { for(var i = 0; i < cdheatmaps.length; i++) { - __plotOne_786(gd, plotinfo, cdheatmaps[i]); + __plotOne_848(gd, plotinfo, cdheatmaps[i]); } }; -function __plotOne_786(gd, plotinfo, cd) { +function __plotOne_848(gd, plotinfo, cd) { var cd0 = cd[0]; var trace = cd0.trace; var uid = trace.uid; @@ -57453,12 +59294,12 @@ function __plotOne_786(gd, plotinfo, cd) { var y = cd0.y; var xc = cd0.xCenter; var yc = cd0.yCenter; - var isContour = _$registry_668.traceIs(trace, 'contour'); + var isContour = _$registry_731.traceIs(trace, 'contour'); var zsmooth = isContour ? 'best' : trace.zsmooth; // get z dims var m = z.length; - var n = _$maxRowLength_785(z); + var n = _$maxRowLength_847(z); var xrev = false; var yrev = false; @@ -57568,8 +59409,8 @@ function __plotOne_786(gd, plotinfo, cd) { canvas.height = canvasH; var context = canvas.getContext('2d'); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, trace.zmin, trace.zmax @@ -57583,18 +59424,18 @@ function __plotOne_786(gd, plotinfo, cd) { if(zsmooth === 'fast') { xpx = xrev ? function(index) { return n - 1 - index; } : - _$lib_539.identity; + _$lib_601.identity; ypx = yrev ? function(index) { return m - 1 - index; } : - _$lib_539.identity; + _$lib_601.identity; } else { xpx = function(index) { - return _$lib_539.constrain(Math.round(xa.c2p(x[index]) - left), + return _$lib_601.constrain(Math.round(xa.c2p(x[index]) - left), 0, imageWidth); }; ypx = function(index) { - return _$lib_539.constrain(Math.round(ya.c2p(y[index]) - top), + return _$lib_601.constrain(Math.round(ya.c2p(y[index]) - top), 0, imageHeight); }; } @@ -57763,7 +59604,7 @@ function __plotOne_786(gd, plotinfo, cd) { rcount = Math.round(rcount / pixcount); gcount = Math.round(gcount / pixcount); bcount = Math.round(bcount / pixcount); - var avgColor = _$tinycolor_352('rgb(' + rcount + ',' + gcount + ',' + bcount + ')'); + var avgColor = _$tinycolor_414('rgb(' + rcount + ',' + gcount + ',' + bcount + ')'); gd._hmpixcount = (gd._hmpixcount||0) + pixcount; gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance(); @@ -57772,7 +59613,7 @@ function __plotOne_786(gd, plotinfo, cd) { .data(cd); image3.enter().append('svg:image').attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, preserveAspectRatio: 'none' }); @@ -57790,10 +59631,10 @@ function __plotOne_786(gd, plotinfo, cd) { // get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin} function findInterp(pixel, pixArray) { var maxBin = pixArray.length - 2; - var bin = _$lib_539.constrain(_$lib_539.findBin(pixel, pixArray), 0, maxBin); + var bin = _$lib_601.constrain(_$lib_601.findBin(pixel, pixArray), 0, maxBin); var pix0 = pixArray[bin]; var pix1 = pixArray[bin + 1]; - var interp = _$lib_539.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin); + var interp = _$lib_601.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin); var bin0 = Math.round(interp); var frac = Math.abs(interp - bin0); @@ -57813,7 +59654,7 @@ function findInterp(pixel, pixArray) { function findInterpFromCenters(pixel, centerPixArray) { var maxBin = centerPixArray.length - 1; - var bin = _$lib_539.constrain(_$lib_539.findBin(pixel, centerPixArray), 0, maxBin); + var bin = _$lib_601.constrain(_$lib_601.findBin(pixel, centerPixArray), 0, maxBin); var pix0 = centerPixArray[bin]; var pix1 = centerPixArray[bin + 1]; var frac = ((pixel - pix0) / (pix1 - pix0)) || 0; @@ -57845,7 +59686,7 @@ function putColor(pixels, pxIndex, c) { pixels[pxIndex + 3] = Math.round(c[3] * 255); } -var _$plot_762 = {}; +var _$plot_824 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -57857,31 +59698,31 @@ var _$plot_762 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$setConvert_603 = require('../../plots/cartesian/set_convert'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$setConvert_665 = require('../../plots/cartesian/set_convert'); */; -/* removed: var _$plot_786 = require('../heatmap/plot'); */; -/* removed: var _$makeCrossings_761 = require('./make_crossings'); */; -/* removed: var _$findAllPaths_756 = require('./find_all_paths'); */; -/* removed: var _$emptyPathinfo_754 = require('./empty_pathinfo'); */; -/* removed: var _$convert_to_constraints_752 = require('./convert_to_constraints'); */; -/* removed: var _$close_boundaries_746 = require('./close_boundaries'); */; -/* removed: var _$constants_748 = require('./constants'); */; -var costConstants = _$constants_748.LABELOPTIMIZER; +/* removed: var _$plot_848 = require('../heatmap/plot'); */; +/* removed: var _$makeCrossings_823 = require('./make_crossings'); */; +/* removed: var _$findAllPaths_818 = require('./find_all_paths'); */; +/* removed: var _$emptyPathinfo_816 = require('./empty_pathinfo'); */; +/* removed: var _$convert_to_constraints_814 = require('./convert_to_constraints'); */; +/* removed: var _$close_boundaries_808 = require('./close_boundaries'); */; +/* removed: var _$constants_810 = require('./constants'); */; +var costConstants = _$constants_810.LABELOPTIMIZER; -_$plot_762.plot = function plot(gd, plotinfo, cdcontours) { +_$plot_824.plot = function plot(gd, plotinfo, cdcontours) { for(var i = 0; i < cdcontours.length; i++) { - __plotOne_762(gd, plotinfo, cdcontours[i]); + __plotOne_824(gd, plotinfo, cdcontours[i]); } }; -function __plotOne_762(gd, plotinfo, cd) { +function __plotOne_824(gd, plotinfo, cd) { var trace = cd[0].trace, x = cd[0].x, y = cd[0].y, @@ -57891,7 +59732,7 @@ function __plotOne_762(gd, plotinfo, cd) { ya = plotinfo.yaxis, fullLayout = gd._fullLayout, id = 'contour' + uid, - pathinfo = _$emptyPathinfo_754(contours, plotinfo, cd[0]); + pathinfo = _$emptyPathinfo_816(contours, plotinfo, cd[0]); if(trace.visible !== true) { fullLayout._paper.selectAll('.' + id + ',.hm' + uid).remove(); @@ -57908,7 +59749,7 @@ function __plotOne_762(gd, plotinfo, cd) { trace.zmin + pathinfo.length * contours.size; } - _$plot_786(gd, plotinfo, [cd]); + _$plot_848(gd, plotinfo, [cd]); } // in case this used to be a heatmap (or have heatmap fill) else { @@ -57917,8 +59758,8 @@ function __plotOne_762(gd, plotinfo, cd) { .selectAll('.hm' + uid).remove(); } - _$makeCrossings_761(pathinfo); - _$findAllPaths_756(pathinfo); + _$makeCrossings_823(pathinfo); + _$findAllPaths_818(pathinfo); var leftedge = xa.c2p(x[0], true), rightedge = xa.c2p(x[x.length - 1], true), @@ -57933,19 +59774,19 @@ function __plotOne_762(gd, plotinfo, cd) { var fillPathinfo = pathinfo; if(contours.type === 'constraint') { - fillPathinfo = _$convert_to_constraints_752(pathinfo, contours._operation); - _$close_boundaries_746(fillPathinfo, contours._operation, perimeter, trace); + fillPathinfo = _$convert_to_constraints_814(pathinfo, contours._operation); + _$close_boundaries_808(fillPathinfo, contours._operation, perimeter, trace); } // draw everything - var plotGroup = _$plot_762.makeContourGroup(plotinfo, cd, id); + var plotGroup = _$plot_824.makeContourGroup(plotinfo, cd, id); makeBackground(plotGroup, perimeter, contours); makeFills(plotGroup, fillPathinfo, perimeter, contours); makeLinesAndLabels(plotGroup, pathinfo, gd, cd[0], contours, perimeter); clipGaps(plotGroup, plotinfo, fullLayout._clips, cd[0], perimeter); } -_$plot_762.makeContourGroup = function(plotinfo, cd, id) { +_$plot_824.makeContourGroup = function(plotinfo, cd, id) { var plotgroup = plotinfo.plot.select('.maplayer') .selectAll('g.contour.' + id) .data(cd); @@ -57960,8 +59801,7 @@ _$plot_762.makeContourGroup = function(plotinfo, cd, id) { }; function makeBackground(plotgroup, perimeter, contours) { - var bggroup = plotgroup.selectAll('g.contourbg').data([0]); - bggroup.enter().append('g').classed('contourbg', true); + var bggroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourbg'); var bgfill = bggroup.selectAll('path') .data(contours.coloring === 'fill' ? [0] : []); @@ -57973,10 +59813,7 @@ function makeBackground(plotgroup, perimeter, contours) { } function makeFills(plotgroup, pathinfo, perimeter, contours) { - var fillgroup = plotgroup.selectAll('g.contourfill') - .data([0]); - fillgroup.enter().append('g') - .classed('contourfill', true); + var fillgroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourfill'); var fillitems = fillgroup.selectAll('path') .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? pathinfo : []); @@ -57990,8 +59827,8 @@ function makeFills(plotgroup, pathinfo, perimeter, contours) { // that we always fill everything above the contour, nothing below var fullpath = joinAllPaths(pi, perimeter); - if(!fullpath) _$d3_127.select(this).remove(); - else _$d3_127.select(this).attr('d', fullpath).style('stroke', 'none'); + if(!fullpath) _$d3_130.select(this).remove(); + else _$d3_130.select(this).attr('d', fullpath).style('stroke', 'none'); }); } @@ -58028,7 +59865,7 @@ function joinAllPaths(pi, perimeter) { function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < 0.01; } while(startsleft.length) { - addpath = _$drawing_436.smoothopen(pi.edgepaths[i], pi.smoothing); + addpath = _$drawing_498.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]; @@ -58037,7 +59874,7 @@ function joinAllPaths(pi, perimeter) { // 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_539.log('Missing end?', i, pi); + _$lib_601.log('Missing end?', i, pi); break; } @@ -58064,7 +59901,7 @@ function joinAllPaths(pi, perimeter) { } } else { - _$lib_539.log('endpt to newendpt is not vert. or horz.', + _$lib_601.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); } } @@ -58076,7 +59913,7 @@ function joinAllPaths(pi, perimeter) { } if(nexti === pi.edgepaths.length) { - _$lib_539.log('unclosed perimeter path'); + _$lib_601.log('unclosed perimeter path'); break; } @@ -58093,18 +59930,14 @@ function joinAllPaths(pi, perimeter) { // finally add the interior paths for(i = 0; i < pi.paths.length; i++) { - fullpath += _$drawing_436.smoothclosed(pi.paths[i], pi.smoothing); + fullpath += _$drawing_498.smoothclosed(pi.paths[i], pi.smoothing); } return fullpath; } function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { - var lineContainer = plotgroup.selectAll('g.contourlines').data([0]); - - lineContainer.enter().append('g') - .classed('contourlines', true); - + var lineContainer = _$lib_601.ensureSingle(plotgroup, 'g', 'contourlines'); var showLines = contours.showlines !== false; var showLabels = contours.showlabels; var clipLinesForLabels = showLines && showLabels; @@ -58113,9 +59946,9 @@ function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { // 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 = _$plot_762.createLines(lineContainer, showLines || showLabels, pathinfo); + var linegroup = _$plot_824.createLines(lineContainer, showLines || showLabels, pathinfo); - var lineClip = _$plot_762.createLineClip(lineContainer, clipLinesForLabels, + var lineClip = _$plot_824.createLineClip(lineContainer, clipLinesForLabels, gd._fullLayout._clips, cd0.trace.uid); var labelGroup = plotgroup.selectAll('g.contourlabels') @@ -58132,13 +59965,13 @@ function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { var labelData = []; // invalidate the getTextLocation cache in case paths changed - _$lib_539.clearLocationCache(); + _$lib_601.clearLocationCache(); - var contourFormat = _$plot_762.labelFormatter(contours, cd0.t.cb, gd._fullLayout); + var contourFormat = _$plot_824.labelFormatter(contours, cd0.t.cb, gd._fullLayout); - var dummyText = _$drawing_436.tester.append('text') + var dummyText = _$drawing_498.tester.append('text') .attr('data-notex', 1) - .call(_$drawing_436.font, contours.labelfont); + .call(_$drawing_498.font, contours.labelfont); var xLen = pathinfo[0].xaxis._length; var yLen = pathinfo[0].yaxis._length; @@ -58157,43 +59990,43 @@ function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) { var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen); // the path length to use to scale the number of labels to draw: - var normLength = _$constants_748.LABELDISTANCE * plotDiagonal / - Math.max(1, pathinfo.length / _$constants_748.LABELINCREASE); + var normLength = _$constants_810.LABELDISTANCE * plotDiagonal / + Math.max(1, pathinfo.length / _$constants_810.LABELINCREASE); linegroup.each(function(d) { - var textOpts = _$plot_762.calcTextOpts(d.level, contourFormat, dummyText, gd); + var textOpts = _$plot_824.calcTextOpts(d.level, contourFormat, dummyText, gd); - _$d3_127.select(this).selectAll('path').each(function() { + _$d3_130.select(this).selectAll('path').each(function() { var path = this; - var pathBounds = _$lib_539.getVisibleSegment(path, bounds, textOpts.height / 2); + var pathBounds = _$lib_601.getVisibleSegment(path, bounds, textOpts.height / 2); if(!pathBounds) return; - if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_748.LABELMIN) return; + if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_810.LABELMIN) return; var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), - _$constants_748.LABELMAX); + _$constants_810.LABELMAX); for(var i = 0; i < maxLabels; i++) { - var loc = _$plot_762.findBestTextLocation(path, pathBounds, textOpts, + var loc = _$plot_824.findBestTextLocation(path, pathBounds, textOpts, labelData, bounds); if(!loc) break; - _$plot_762.addLabelData(loc, textOpts, labelData, labelClipPathData); + _$plot_824.addLabelData(loc, textOpts, labelData, labelClipPathData); } }); }); dummyText.remove(); - _$plot_762.drawLabels(labelGroup, labelData, gd, lineClip, + _$plot_824.drawLabels(labelGroup, labelData, gd, lineClip, clipLinesForLabels ? labelClipPathData : null); } if(showLabels && !showLines) linegroup.remove(); } -_$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { +_$plot_824.createLines = function(lineContainer, makeLines, pathinfo) { var smoothing = pathinfo[0].smoothing; var linegroup = lineContainer.selectAll('g.contourlevel') @@ -58215,7 +60048,7 @@ _$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { opencontourlines .attr('d', function(d) { - return _$drawing_436.smoothopen(d, smoothing); + return _$drawing_498.smoothopen(d, smoothing); }) .style('stroke-miterlimit', 1) .style('vector-effect', 'non-scaling-stroke'); @@ -58229,7 +60062,7 @@ _$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { closedcontourlines .attr('d', function(d) { - return _$drawing_436.smoothclosed(d, smoothing); + return _$drawing_498.smoothclosed(d, smoothing); }) .style('stroke-miterlimit', 1) .style('vector-effect', 'non-scaling-stroke'); @@ -58238,7 +60071,7 @@ _$plot_762.createLines = function(lineContainer, makeLines, pathinfo) { return linegroup; }; -_$plot_762.createLineClip = function(lineContainer, clipLinesForLabels, clips, uid) { +_$plot_824.createLineClip = function(lineContainer, clipLinesForLabels, clips, uid) { var clipId = clipLinesForLabels ? ('clipline' + uid) : null; var lineClip = clips.selectAll('#' + clipId) @@ -58249,12 +60082,12 @@ _$plot_762.createLineClip = function(lineContainer, clipLinesForLabels, clips, u .classed('contourlineclip', true) .attr('id', clipId); - _$drawing_436.setClipUrl(lineContainer, clipId); + _$drawing_498.setClipUrl(lineContainer, clipId); return lineClip; }; -_$plot_762.labelFormatter = function(contours, colorbar, fullLayout) { +_$plot_824.labelFormatter = function(contours, colorbar, fullLayout) { if(contours.labelformat) { return fullLayout._d3locale.numberFormat(contours.labelformat); } @@ -58287,22 +60120,22 @@ _$plot_762.labelFormatter = function(contours, colorbar, fullLayout) { } if(!formatAxis.nticks) formatAxis.nticks = 1000; - _$setConvert_603(formatAxis, fullLayout); - _$axes_584.prepTicks(formatAxis); + _$setConvert_665(formatAxis, fullLayout); + _$axes_647.prepTicks(formatAxis); formatAxis._tmin = null; formatAxis._tmax = null; } return function(v) { - return _$axes_584.tickText(formatAxis, v).text; + return _$axes_647.tickText(formatAxis, v).text; }; } }; -_$plot_762.calcTextOpts = function(level, contourFormat, dummyText, gd) { +_$plot_824.calcTextOpts = function(level, contourFormat, dummyText, gd) { var text = contourFormat(level); dummyText.text(text) - .call(_$svg_text_utils_562.convertToTspans, gd); - var bBox = _$drawing_436.bBox(dummyText.node(), true); + .call(_$svg_text_utils_625.convertToTspans, gd); + var bBox = _$drawing_498.bBox(dummyText.node(), true); return { text: text, @@ -58313,7 +60146,7 @@ _$plot_762.calcTextOpts = function(level, contourFormat, dummyText, gd) { }; }; -_$plot_762.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) { +_$plot_824.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) { var textWidth = textOpts.width; var p0, dp, pMax, pMin, loc; @@ -58331,7 +60164,7 @@ _$plot_762.findBestTextLocation = function(path, pathBounds, textOpts, labelData var cost = Infinity; for(var j = 0; j < costConstants.ITERATIONS; j++) { for(var p = p0; p < pMax; p += dp) { - var newLocation = _$lib_539.getTextLocation(path, pathBounds.total, p, textWidth); + var newLocation = _$lib_601.getTextLocation(path, pathBounds.total, p, textWidth); var newCost = locationCost(newLocation, textOpts, labelData, plotBounds); if(newCost < cost) { cost = newCost; @@ -58386,7 +60219,7 @@ function locationCost(loc, textOpts, labelData, bounds) { 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_539.segmentDistance( + var dist = _$lib_601.segmentDistance( x1, y1, x2, y2, labeli.x - dxd, labeli.y - dyd, @@ -58407,7 +60240,7 @@ function locationCost(loc, textOpts, labelData, bounds) { return cost; } -_$plot_762.addLabelData = function(loc, textOpts, labelData, labelClipPathData) { +_$plot_824.addLabelData = function(loc, textOpts, labelData, labelClipPathData) { var halfWidth = textOpts.width / 2; var halfHeight = textOpts.height / 2; @@ -58442,7 +60275,7 @@ _$plot_762.addLabelData = function(loc, textOpts, labelData, labelClipPathData) labelClipPathData.push(bBoxPts); }; -_$plot_762.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipPathData) { +_$plot_824.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; @@ -58458,14 +60291,14 @@ _$plot_762.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipP .each(function(d) { var x = d.x + Math.sin(d.theta) * d.dy; var y = d.y - Math.cos(d.theta) * d.dy; - _$d3_127.select(this) + _$d3_130.select(this) .text(d.text) .attr({ x: x, y: y, transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')' }) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); }); if(labelClipPathData) { @@ -58474,8 +60307,7 @@ _$plot_762.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipP clipPath += 'M' + labelClipPathData[i].join('L') + 'Z'; } - var lineClipPath = lineClip.selectAll('path').data([0]); - lineClipPath.enter().append('path'); + var lineClipPath = _$lib_601.ensureSingle(lineClip, 'path', ''); lineClipPath.attr('d', clipPath); } }; @@ -58510,20 +60342,18 @@ function clipGaps(plotGroup, plotinfo, clips, cd0, perimeter) { smoothing: 0 }; - _$makeCrossings_761([clipPathInfo]); - _$findAllPaths_756([clipPathInfo]); + _$makeCrossings_823([clipPathInfo]); + _$findAllPaths_818([clipPathInfo]); var fullpath = joinAllPaths(clipPathInfo, perimeter); - var path = clipPath.selectAll('path') - .data([0]); - path.enter().append('path'); + var path = _$lib_601.ensureSingle(clipPath, 'path', ''); path.attr('d', fullpath); } else clipId = null; - plotGroup.call(_$drawing_436.setClipUrl, clipId); + plotGroup.call(_$drawing_498.setClipUrl, clipId); plotinfo.plot.selectAll('.hm' + cd0.trace.uid) - .call(_$drawing_436.setClipUrl, clipId); + .call(_$drawing_498.setClipUrl, clipId); } function makeClipMask(cd0) { @@ -58557,10 +60387,10 @@ function makeClipMask(cd0) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -var _$style_787 = function style(gd) { - _$d3_127.select(gd).selectAll('.hm image') +var _$style_849 = function style(gd) { + _$d3_130.select(gd).selectAll('.hm image') .style('opacity', function(d) { return d.trace.opacity; }); @@ -58577,23 +60407,23 @@ var _$style_787 = function style(gd) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$style_787 = require('../heatmap/style'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$style_849 = require('../heatmap/style'); */; -/* removed: var _$makeColorMap_760 = require('./make_color_map'); */; +/* removed: var _$makeColorMap_822 = require('./make_color_map'); */; -var _$style_764 = function style(gd) { - var contours = _$d3_127.select(gd).selectAll('g.contour'); +var _$style_826 = function style(gd) { + var contours = _$d3_130.select(gd).selectAll('g.contour'); contours.style('opacity', function(d) { return d.trace.opacity; }); contours.each(function(d) { - var c = _$d3_127.select(this); + var c = _$d3_130.select(this); var trace = d.trace; var contours = trace.contours; var line = trace.line; @@ -58605,11 +60435,11 @@ var _$style_764 = function style(gd) { var colorLines = !isConstraintType && contours.coloring === 'lines'; var colorFills = !isConstraintType && contours.coloring === 'fill'; - var colorMap = (colorLines || colorFills) ? _$makeColorMap_760(trace) : null; + var colorMap = (colorLines || colorFills) ? _$makeColorMap_822(trace) : null; c.selectAll('g.contourlevel').each(function(d) { - _$d3_127.select(this).selectAll('path') - .call(_$drawing_436.lineGroupStyle, + _$d3_130.select(this).selectAll('path') + .call(_$drawing_498.lineGroupStyle, line.width, colorLines ? colorMap(d.level) : line.color, line.dash); @@ -58617,7 +60447,7 @@ var _$style_764 = function style(gd) { var labelFont = contours.labelfont; c.selectAll('g.contourlabels text').each(function(d) { - _$drawing_436.font(_$d3_127.select(this), { + _$drawing_498.font(_$d3_130.select(this), { family: labelFont.family, size: labelFont.size, color: labelFont.color || (colorLines ? colorMap(d.level) : line.color) @@ -58644,7 +60474,7 @@ var _$style_764 = function style(gd) { } }); - _$style_787(gd); + _$style_849(gd); }; /** @@ -58660,23 +60490,23 @@ var _$style_764 = function style(gd) { var Contour = {}; -Contour.attributes = _$attributes_744; -Contour.supplyDefaults = _$supplyDefaults_753; -Contour.calc = _$calc_745; -Contour.plot = _$plot_762.plot; -Contour.style = _$style_764; -Contour.colorbar = _$colorbar_747; -Contour.hoverPoints = _$hoverPoints_757; +Contour.attributes = _$attributes_806; +Contour.supplyDefaults = _$supplyDefaults_815; +Contour.calc = _$calc_807; +Contour.plot = _$plot_824.plot; +Contour.style = _$style_826; +Contour.colorbar = _$colorbar_809; +Contour.hoverPoints = _$hoverPoints_819; Contour.moduleType = 'trace'; Contour.name = 'contour'; -Contour.basePlotModule = _$cartesian_595; -Contour.categories = ['cartesian', '2dMap', 'contour', 'showLegend']; +Contour.basePlotModule = _$cartesian_658; +Contour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'showLegend']; Contour.meta = { }; -var _$Contour_758 = Contour; +var _$Contour_820 = Contour; /** * Copyright 2012-2018, Plotly, Inc. @@ -58688,7 +60518,7 @@ var _$Contour_758 = Contour; 'use strict'; -var _$contour_10 = _$Contour_758; +var _$contour_10 = _$Contour_820; /** * Copyright 2012-2018, Plotly, Inc. @@ -58700,43 +60530,43 @@ var _$contour_10 = _$Contour_758; 'use strict'; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_744 = require('../contour/attributes'); */; -var contourContourAttrs = _$attributes_744.contours; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_806 = require('../contour/attributes'); */; +var contourContourAttrs = _$attributes_806.contours; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_766 = _$extend_528.extendFlat; +var __extendFlat_828 = _$extend_590.extendFlat; -var __scatterLineAttrs_766 = _$attributes_862.line; +var __scatterLineAttrs_828 = _$attributes_927.line; -var _$attributes_766 = __extendFlat_766({}, { +var _$attributes_828 = __extendFlat_828({}, { carpet: { valType: 'string', editType: 'calc', }, - z: _$attributes_773.z, - a: _$attributes_773.x, - a0: _$attributes_773.x0, - da: _$attributes_773.dx, - b: _$attributes_773.y, - b0: _$attributes_773.y0, - db: _$attributes_773.dy, - text: _$attributes_773.text, - transpose: _$attributes_773.transpose, - atype: _$attributes_773.xtype, - btype: _$attributes_773.ytype, + z: _$attributes_835.z, + a: _$attributes_835.x, + a0: _$attributes_835.x0, + da: _$attributes_835.dx, + b: _$attributes_835.y, + b0: _$attributes_835.y0, + db: _$attributes_835.dy, + text: _$attributes_835.text, + transpose: _$attributes_835.transpose, + atype: _$attributes_835.xtype, + btype: _$attributes_835.ytype, // unimplemented - looks like connectgaps is implied true // connectgaps: heatmapAttrs.connectgaps, - fillcolor: _$attributes_744.fillcolor, + fillcolor: _$attributes_806.fillcolor, - autocontour: _$attributes_744.autocontour, - ncontours: _$attributes_744.ncontours, + autocontour: _$attributes_806.autocontour, + ncontours: _$attributes_806.ncontours, contours: { type: contourContourAttrs.type, @@ -58763,20 +60593,20 @@ var _$attributes_766 = __extendFlat_766({}, { }, line: { - color: __extendFlat_766({}, __scatterLineAttrs_766.color, { + color: __extendFlat_828({}, __scatterLineAttrs_828.color, { }), - width: __scatterLineAttrs_766.width, - dash: __scatterLineAttrs_766.dash, - smoothing: __extendFlat_766({}, __scatterLineAttrs_766.smoothing, { + width: __scatterLineAttrs_828.width, + dash: __scatterLineAttrs_828.dash, + smoothing: __extendFlat_828({}, __scatterLineAttrs_828.smoothing, { }), editType: 'plot' } }, - _$attributes_417, - { autocolorscale: __extendFlat_766({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } + _$attributes_479, + { autocolorscale: __extendFlat_828({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); /** @@ -58792,7 +60622,7 @@ var _$attributes_766 = __extendFlat_766({}, { /* * Given a trace, look up the carpet axis by carpet. */ -var _$lookup_carpetid_726 = function(gd, trace) { +var _$lookup_carpetid_789 = function(gd, trace) { var n = gd._fullData.length; var firstAxis; for(var i = 0; i < n; i++) { @@ -58825,21 +60655,21 @@ var _$lookup_carpetid_726 = function(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleXYZDefaults_789 = require('../heatmap/xyz_defaults'); */; -/* removed: var _$attributes_766 = require('./attributes'); */; -/* removed: var _$handleConstraintDefaults_749 = require('../contour/constraint_defaults'); */; -/* removed: var _$handleContourDefaults_751 = require('../contour/contours_defaults'); */; -/* removed: var _$handleStyleDefaults_765 = require('../contour/style_defaults'); */; +/* removed: var _$handleXYZDefaults_851 = require('../heatmap/xyz_defaults'); */; +/* removed: var _$attributes_828 = require('./attributes'); */; +/* removed: var _$handleConstraintDefaults_811 = require('../contour/constraint_defaults'); */; +/* removed: var _$handleContourDefaults_813 = require('../contour/contours_defaults'); */; +/* removed: var _$handleStyleDefaults_827 = require('../contour/style_defaults'); */; -var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_830 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_766, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_828, attr, dflt); } function coerce2(attr) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_766, attr); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_828, attr); } coerce('carpet'); @@ -58861,7 +60691,7 @@ var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultCol // straightforward. if(traceIn.a && traceIn.b) { - var len = _$handleXYZDefaults_789(traceIn, traceOut, coerce, layout, 'a', 'b'); + var len = _$handleXYZDefaults_851(traceIn, traceOut, coerce, layout, 'a', 'b'); if(!len) { traceOut.visible = false; @@ -58878,10 +60708,10 @@ var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultCol if(!isConstraint) delete traceOut.showlegend; if(isConstraint) { - _$handleConstraintDefaults_749(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false}); + _$handleConstraintDefaults_811(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false}); } else { - _$handleContourDefaults_751(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_765(traceIn, traceOut, coerce, layout, {hasHover: false}); + _$handleContourDefaults_813(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_827(traceIn, traceOut, coerce, layout, {hasHover: false}); } } else { traceOut._defaultColor = defaultColor; @@ -58898,23 +60728,23 @@ var _$supplyDefaults_768 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$has_columns_780 = require('../heatmap/has_columns'); */; -/* removed: var _$convertColumnData_777 = require('../heatmap/convert_column_xyz'); */; -/* removed: var _$clean2dArray_775 = require('../heatmap/clean_2d_array'); */; -/* removed: var _$maxRowLength_785 = require('../heatmap/max_row_length'); */; -/* removed: var _$interp2d_783 = require('../heatmap/interp2d'); */; -/* removed: var _$findEmpties_779 = require('../heatmap/find_empties'); */; -/* removed: var _$makeBoundArray_784 = require('../heatmap/make_bound_array'); */; -/* removed: var _$supplyDefaults_768 = require('./defaults'); */; -/* removed: var _$lookup_carpetid_726 = require('../carpet/lookup_carpetid'); */; -/* removed: var _$setContours_763 = require('../contour/set_contours'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$has_columns_842 = require('../heatmap/has_columns'); */; +/* removed: var _$convertColumnData_839 = require('../heatmap/convert_column_xyz'); */; +/* removed: var _$clean2dArray_837 = require('../heatmap/clean_2d_array'); */; +/* removed: var _$maxRowLength_847 = require('../heatmap/max_row_length'); */; +/* removed: var _$interp2d_845 = require('../heatmap/interp2d'); */; +/* removed: var _$findEmpties_841 = require('../heatmap/find_empties'); */; +/* removed: var _$makeBoundArray_846 = require('../heatmap/make_bound_array'); */; +/* removed: var _$supplyDefaults_830 = require('./defaults'); */; +/* removed: var _$lookup_carpetid_789 = require('../carpet/lookup_carpetid'); */; +/* removed: var _$setContours_825 = require('../contour/set_contours'); */; // 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 -var _$calc_767 = function calc(gd, trace) { - var carpet = trace.carpetTrace = _$lookup_carpetid_726(gd, trace); +var _$calc_829 = function calc(gd, trace) { + var carpet = trace._carpetTrace = _$lookup_carpetid_789(gd, trace); if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return; if(!trace.a || !trace.b) { @@ -58931,12 +60761,12 @@ var _$calc_767 = function calc(gd, trace) { if(!tracedata.a) tracedata.a = carpetdata.a; if(!tracedata.b) tracedata.b = carpetdata.b; - _$supplyDefaults_768(tracedata, trace, trace._defaultColor, gd._fullLayout); + _$supplyDefaults_830(tracedata, trace, trace._defaultColor, gd._fullLayout); } var cd = heatmappishCalc(gd, trace); - _$setContours_763(trace); + _$setContours_825(trace); return cd; }; @@ -58944,7 +60774,7 @@ var _$calc_767 = function calc(gd, trace) { 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 carpet = trace._carpetTrace; var aax = carpet.aaxis; var bax = carpet.baxis; var a, @@ -58959,26 +60789,28 @@ function heatmappishCalc(gd, trace) { aax._minDtick = 0; bax._minDtick = 0; - if(_$has_columns_780(trace)) _$convertColumnData_777(trace, aax, bax, 'a', 'b', ['z']); + if(_$has_columns_842(trace)) _$convertColumnData_839(trace, aax, bax, 'a', 'b', ['z']); + a = trace._a = trace._a || trace.a; + b = trace._b = trace._b || trace.b; - a = trace.a ? aax.makeCalcdata(trace, 'a') : []; - b = trace.b ? bax.makeCalcdata(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 = _$clean2dArray_775(trace.z, trace.transpose); + z = trace._z = _$clean2dArray_837(trace._z || trace.z, trace.transpose); - trace._emptypoints = _$findEmpties_779(z); - trace._interpz = _$interp2d_783(z, trace._emptypoints, trace._interpz); + trace._emptypoints = _$findEmpties_841(z); + trace._interpz = _$interp2d_845(z, trace._emptypoints, trace._interpz); // create arrays of brick boundaries, to be used by autorange and heatmap.plot - var xlen = _$maxRowLength_785(z), + var xlen = _$maxRowLength_847(z), xIn = trace.xtype === 'scaled' ? '' : a, - xArray = _$makeBoundArray_784(trace, xIn, a0, da, xlen, aax), + xArray = _$makeBoundArray_846(trace, xIn, a0, da, xlen, aax), yIn = trace.ytype === 'scaled' ? '' : b, - yArray = _$makeBoundArray_784(trace, yIn, b0, db, z.length, bax); + yArray = _$makeBoundArray_846(trace, yIn, b0, db, z.length, bax); var cd0 = { a: xArray, @@ -58988,7 +60820,7 @@ function heatmappishCalc(gd, trace) { if(trace.contours.type === 'levels') { // auto-z and autocolorscale if applicable - _$calc_418(trace, z, '', 'z'); + _$calc_480(trace, z, '', 'z'); } return [cd0]; @@ -59004,7 +60836,7 @@ function heatmappishCalc(gd, trace) { 'use strict'; -var __isArrayOrTypedArray_709 = _$lib_539.isArrayOrTypedArray; +var __isArrayOrTypedArray_772 = _$lib_601.isArrayOrTypedArray; /* This function retrns a set of control points that define a curve aligned along * either the a or b axis. Exactly one of a or b must be an array defining the range @@ -59013,11 +60845,11 @@ var __isArrayOrTypedArray_709 = _$lib_539.isArrayOrTypedArray; * Honestly this is the most complicated function I've implemente here so far because * of the way it handles knot insertion and direction/axis-agnostic slices. */ -var _$axis_aligned_line_709 = function(carpet, carpetcd, a, b) { +var _$axis_aligned_line_772 = function(carpet, carpetcd, a, b) { var idx, tangent, tanIsoIdx, tanIsoPar, segment, refidx; var p0, p1, v0, v1, start, end, range; - var axis = __isArrayOrTypedArray_709(a) ? 'a' : 'b'; + var axis = __isArrayOrTypedArray_772(a) ? 'a' : 'b'; var ax = axis === 'a' ? carpet.aaxis : carpet.baxis; var smoothing = ax.smoothing; var toIdx = axis === 'a' ? carpet.a2i : carpet.b2j; @@ -59110,11 +60942,11 @@ var _$axis_aligned_line_709 = function(carpet, carpetcd, a, b) { 'use strict'; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$axis_aligned_line_709 = require('../carpet/axis_aligned_line'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$axis_aligned_line_772 = require('../carpet/axis_aligned_line'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) { +var _$joinAllPaths_832 = function joinAllPaths(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya) { var i; var fullpath = ''; @@ -59136,10 +60968,10 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe if((istop(pt0) && !isright(pt0)) || (isbottom(pt0) && !isleft(pt0))) { axis = carpet.aaxis; - segments = _$axis_aligned_line_709(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1])); + segments = _$axis_aligned_line_772(carpet, carpetcd, [pt0[0], pt1[0]], 0.5 * (pt0[1] + pt1[1])); } else { axis = carpet.baxis; - segments = _$axis_aligned_line_709(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]); + segments = _$axis_aligned_line_772(carpet, carpetcd, 0.5 * (pt0[0] + pt1[0]), [pt0[1], pt1[1]]); } for(i = 1; i < segments.length; i++) { @@ -59162,7 +60994,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe fullpath += pathto(endpt, startpt); } - addpath = _$drawing_436.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing); + addpath = _$drawing_498.smoothopen(pi.edgepaths[i].map(ab2p), pi.smoothing); fullpath += newloop ? addpath : addpath.replace(/^M/, 'L'); startsleft.splice(startsleft.indexOf(i), 1); endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1]; @@ -59171,7 +61003,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe // 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_539.log('Missing end?', i, pi); + _$lib_601.log('Missing end?', i, pi); break; } @@ -59199,7 +61031,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe nexti = possiblei; } } else { - _$lib_539.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); + _$lib_601.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); } } @@ -59209,7 +61041,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe } if(nexti === pi.edgepaths.length) { - _$lib_539.log('unclosed perimeter path'); + _$lib_601.log('unclosed perimeter path'); break; } @@ -59227,7 +61059,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe // finally add the interior paths for(i = 0; i < pi.paths.length; i++) { - fullpath += _$drawing_436.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing); + fullpath += _$drawing_498.smoothclosed(pi.paths[i].map(ab2p), pi.smoothing); } return fullpath; @@ -59243,7 +61075,7 @@ var _$joinAllPaths_770 = function joinAllPaths(trace, pi, perimeter, ab2p, carpe 'use strict'; -var _$mapPathinfo_771 = function mapPathinfo(pathinfo, map) { +var _$mapPathinfo_833 = function mapPathinfo(pathinfo, map) { var i, j, k, pi, pedgepaths, ppaths, pedgepath, ppath, path; for(i = 0; i < pathinfo.length; i++) { @@ -59279,34 +61111,34 @@ var _$mapPathinfo_771 = function mapPathinfo(pathinfo, map) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$mapArray_728 = require('../carpet/map_1d_array'); */; -/* removed: var _$makePath_727 = require('../carpet/makepath'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$mapArray_791 = require('../carpet/map_1d_array'); */; +/* removed: var _$makePath_790 = require('../carpet/makepath'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$makeCrossings_761 = require('../contour/make_crossings'); */; -/* removed: var _$findAllPaths_756 = require('../contour/find_all_paths'); */; -/* removed: var _$plot_762 = require('../contour/plot'); */; -/* removed: var _$constants_748 = require('../contour/constants'); */; -/* removed: var _$convert_to_constraints_752 = require('../contour/convert_to_constraints'); */; -/* removed: var _$joinAllPaths_770 = require('./join_all_paths'); */; -/* removed: var _$emptyPathinfo_754 = require('../contour/empty_pathinfo'); */; -/* removed: var _$mapPathinfo_771 = require('./map_pathinfo'); */; -/* removed: var _$lookup_carpetid_726 = require('../carpet/lookup_carpetid'); */; -/* removed: var _$close_boundaries_746 = require('../contour/close_boundaries'); */; +/* removed: var _$makeCrossings_823 = require('../contour/make_crossings'); */; +/* removed: var _$findAllPaths_818 = require('../contour/find_all_paths'); */; +/* removed: var _$plot_824 = require('../contour/plot'); */; +/* removed: var _$constants_810 = require('../contour/constants'); */; +/* removed: var _$convert_to_constraints_814 = require('../contour/convert_to_constraints'); */; +/* removed: var _$joinAllPaths_832 = require('./join_all_paths'); */; +/* removed: var _$emptyPathinfo_816 = require('../contour/empty_pathinfo'); */; +/* removed: var _$mapPathinfo_833 = require('./map_pathinfo'); */; +/* removed: var _$lookup_carpetid_789 = require('../carpet/lookup_carpetid'); */; +/* removed: var _$close_boundaries_808 = require('../contour/close_boundaries'); */; -var _$plot_772 = function plot(gd, plotinfo, cdcontours) { +var _$plot_834 = function plot(gd, plotinfo, cdcontours) { for(var i = 0; i < cdcontours.length; i++) { - __plotOne_772(gd, plotinfo, cdcontours[i]); + __plotOne_834(gd, plotinfo, cdcontours[i]); } }; -function __plotOne_772(gd, plotinfo, cd) { +function __plotOne_834(gd, plotinfo, cd) { var trace = cd[0].trace; - var carpet = trace.carpetTrace = _$lookup_carpetid_726(gd, trace); + var carpet = trace._carpetTrace = _$lookup_carpetid_789(gd, trace); var carpetcd = gd.calcdata[carpet.index][0]; if(!carpet.visible || carpet.visible === 'legendonly') return; @@ -59319,7 +61151,7 @@ function __plotOne_772(gd, plotinfo, cd) { var ya = plotinfo.yaxis; var fullLayout = gd._fullLayout; var id = 'contour' + uid; - var pathinfo = _$emptyPathinfo_754(contours, plotinfo, cd[0]); + var pathinfo = _$emptyPathinfo_816(contours, plotinfo, cd[0]); var isConstraint = contours.type === 'constraint'; var operation = contours._operation; var coloring = isConstraint ? (operation === '=' ? 'lines' : 'fill') : contours.coloring; @@ -59344,10 +61176,10 @@ function __plotOne_772(gd, plotinfo, cd) { ]; // Extract the contour levels: - _$makeCrossings_761(pathinfo); + _$makeCrossings_823(pathinfo); var atol = (a[a.length - 1] - a[0]) * 1e-8; var btol = (b[b.length - 1] - b[0]) * 1e-8; - _$findAllPaths_756(pathinfo, atol, btol); + _$findAllPaths_818(pathinfo, atol, btol); // Constraints might need to be draw inverted, which is not something contours // handle by default since they're assumed fully opaque so that they can be @@ -59359,52 +61191,48 @@ function __plotOne_772(gd, plotinfo, cd) { // See: https://github.com/plotly/plotly.js/issues/1356 var fillPathinfo = pathinfo; if(contours.type === 'constraint') { - fillPathinfo = _$convert_to_constraints_752(pathinfo, operation); - _$close_boundaries_746(fillPathinfo, operation, perimeter, trace); + fillPathinfo = _$convert_to_constraints_814(pathinfo, operation); + _$close_boundaries_808(fillPathinfo, operation, perimeter, trace); } // Map the paths in a/b coordinates to pixel coordinates: - _$mapPathinfo_771(pathinfo, ab2p); + _$mapPathinfo_833(pathinfo, ab2p); // draw everything - var plotGroup = _$plot_762.makeContourGroup(plotinfo, cd, id); + var plotGroup = _$plot_824.makeContourGroup(plotinfo, cd, id); // Compute the boundary path var seg, xp, yp, i; var segs = []; for(i = carpetcd.clipsegments.length - 1; i >= 0; i--) { seg = carpetcd.clipsegments[i]; - xp = _$mapArray_728([], seg.x, xa.c2p); - yp = _$mapArray_728([], seg.y, ya.c2p); + xp = _$mapArray_791([], seg.x, xa.c2p); + yp = _$mapArray_791([], seg.y, ya.c2p); xp.reverse(); yp.reverse(); - segs.push(_$makePath_727(xp, yp, seg.bicubic)); + segs.push(_$makePath_790(xp, yp, seg.bicubic)); } var boundaryPath = 'M' + segs.join('L') + 'Z'; // Draw the baseline background fill that fills in the space behind any other // contour levels: - __makeBackground_772(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring); + __makeBackground_834(plotGroup, carpetcd.clipsegments, xa, ya, isConstraint, coloring); // Draw the specific contour fills. As a simplification, they're assumed to be // fully opaque so that it's easy to draw them simply overlapping. The alternative // would be to flip adjacent paths and draw closed paths for each level instead. - __makeFills_772(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath); + __makeFills_834(trace, plotGroup, xa, ya, fillPathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath); // Draw contour lines: - __makeLinesAndLabels_772(plotGroup, pathinfo, gd, cd[0], contours, plotinfo, carpet); + __makeLinesAndLabels_834(plotGroup, pathinfo, gd, cd[0], contours, plotinfo, carpet); // Clip the boundary of the plot - _$drawing_436.setClipUrl(plotGroup, carpet._clipPathId); + _$drawing_498.setClipUrl(plotGroup, carpet._clipPathId); } -function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) { - var lineContainer = plotgroup.selectAll('g.contourlines').data([0]); - - lineContainer.enter().append('g') - .classed('contourlines', true); - +function __makeLinesAndLabels_834(plotgroup, pathinfo, gd, cd0, contours, plotinfo, carpet) { + var lineContainer = _$lib_601.ensureSingle(plotgroup, 'g', 'contourlines'); var showLines = contours.showlines !== false; var showLabels = contours.showlabels; var clipLinesForLabels = showLines && showLabels; @@ -59413,9 +61241,9 @@ function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotin // 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 = _$plot_762.createLines(lineContainer, showLines || showLabels, pathinfo); + var linegroup = _$plot_824.createLines(lineContainer, showLines || showLabels, pathinfo); - var lineClip = _$plot_762.createLineClip(lineContainer, clipLinesForLabels, + var lineClip = _$plot_824.createLineClip(lineContainer, clipLinesForLabels, gd._fullLayout._defs, cd0.trace.uid); var labelGroup = plotgroup.selectAll('g.contourlabels') @@ -59443,13 +61271,13 @@ function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotin var labelData = []; // invalidate the getTextLocation cache in case paths changed - _$lib_539.clearLocationCache(); + _$lib_601.clearLocationCache(); - var contourFormat = _$plot_762.labelFormatter(contours, cd0.t.cb, gd._fullLayout); + var contourFormat = _$plot_824.labelFormatter(contours, cd0.t.cb, gd._fullLayout); - var dummyText = _$drawing_436.tester.append('text') + var dummyText = _$drawing_498.tester.append('text') .attr('data-notex', 1) - .call(_$drawing_436.font, contours.labelfont); + .call(_$drawing_498.font, contours.labelfont); // use `bounds` only to keep labels away from the x/y boundaries // `constrainToCarpet` below ensures labels don't go off the @@ -59466,38 +61294,38 @@ function __makeLinesAndLabels_772(plotgroup, pathinfo, gd, cd0, contours, plotin var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen); // the path length to use to scale the number of labels to draw: - var normLength = _$constants_748.LABELDISTANCE * plotDiagonal / - Math.max(1, pathinfo.length / _$constants_748.LABELINCREASE); + var normLength = _$constants_810.LABELDISTANCE * plotDiagonal / + Math.max(1, pathinfo.length / _$constants_810.LABELINCREASE); linegroup.each(function(d) { - var textOpts = _$plot_762.calcTextOpts(d.level, contourFormat, dummyText, gd); + var textOpts = _$plot_824.calcTextOpts(d.level, contourFormat, dummyText, gd); - _$d3_127.select(this).selectAll('path').each(function(pathData) { + _$d3_130.select(this).selectAll('path').each(function(pathData) { var path = this; - var pathBounds = _$lib_539.getVisibleSegment(path, bounds, textOpts.height / 2); + var pathBounds = _$lib_601.getVisibleSegment(path, bounds, textOpts.height / 2); if(!pathBounds) return; constrainToCarpet(path, pathData, d, pathBounds, carpet, textOpts.height); - if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_748.LABELMIN) return; + if(pathBounds.len < (textOpts.width + textOpts.height) * _$constants_810.LABELMIN) return; var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), - _$constants_748.LABELMAX); + _$constants_810.LABELMAX); for(var i = 0; i < maxLabels; i++) { - var loc = _$plot_762.findBestTextLocation(path, pathBounds, textOpts, + var loc = _$plot_824.findBestTextLocation(path, pathBounds, textOpts, labelData, bounds); if(!loc) break; - _$plot_762.addLabelData(loc, textOpts, labelData, labelClipPathData); + _$plot_824.addLabelData(loc, textOpts, labelData, labelClipPathData); } }); }); dummyText.remove(); - _$plot_762.drawLabels(labelGroup, labelData, gd, lineClip, + _$plot_824.drawLabels(labelGroup, labelData, gd, lineClip, clipLinesForLabels ? labelClipPathData : null); } @@ -59567,10 +61395,9 @@ function vectorTan(v0, v1) { return sin / cos; } -function __makeBackground_772(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) { +function __makeBackground_834(plotgroup, clipsegments, xaxis, yaxis, isConstraint, coloring) { var seg, xp, yp, i; - var bggroup = plotgroup.selectAll('g.contourbg').data([0]); - bggroup.enter().append('g').classed('contourbg', true); + var bggroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourbg'); var bgfill = bggroup.selectAll('path') .data((coloring === 'fill' && !isConstraint) ? [0] : []); @@ -59580,9 +61407,9 @@ function __makeBackground_772(plotgroup, clipsegments, xaxis, yaxis, isConstrain var segs = []; for(i = 0; i < clipsegments.length; i++) { seg = clipsegments[i]; - xp = _$mapArray_728([], seg.x, xaxis.c2p); - yp = _$mapArray_728([], seg.y, yaxis.c2p); - segs.push(_$makePath_727(xp, yp, seg.bicubic)); + xp = _$mapArray_791([], seg.x, xaxis.c2p); + yp = _$mapArray_791([], seg.y, yaxis.c2p); + segs.push(_$makePath_790(xp, yp, seg.bicubic)); } bgfill @@ -59590,11 +61417,8 @@ function __makeBackground_772(plotgroup, clipsegments, xaxis, yaxis, isConstrain .style('stroke', 'none'); } -function __makeFills_772(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) { - var fillgroup = plotgroup.selectAll('g.contourfill') - .data([0]); - fillgroup.enter().append('g') - .classed('contourfill', true); +function __makeFills_834(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, carpet, carpetcd, coloring, boundaryPath) { + var fillgroup = _$lib_601.ensureSingle(plotgroup, 'g', 'contourfill'); var fillitems = fillgroup.selectAll('path') .data(coloring === 'fill' ? pathinfo : []); @@ -59606,16 +61430,16 @@ function __makeFills_772(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, ca // 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 = _$joinAllPaths_770(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya); + var fullpath = _$joinAllPaths_832(trace, pi, perimeter, ab2p, carpet, carpetcd, xa, ya); if(pi.prefixBoundary) { fullpath = boundaryPath + fullpath; } if(!fullpath) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); } else { - _$d3_127.select(this) + _$d3_130.select(this) .attr('d', fullpath) .style('stroke', 'none'); } @@ -59634,23 +61458,23 @@ function __makeFills_772(trace, plotgroup, xa, ya, pathinfo, perimeter, ab2p, ca var ContourCarpet = {}; -ContourCarpet.attributes = _$attributes_766; -ContourCarpet.supplyDefaults = _$supplyDefaults_768; -ContourCarpet.colorbar = _$colorbar_747; -ContourCarpet.calc = _$calc_767; -ContourCarpet.plot = _$plot_772; -ContourCarpet.style = _$style_764; +ContourCarpet.attributes = _$attributes_828; +ContourCarpet.supplyDefaults = _$supplyDefaults_830; +ContourCarpet.colorbar = _$colorbar_809; +ContourCarpet.calc = _$calc_829; +ContourCarpet.plot = _$plot_834; +ContourCarpet.style = _$style_826; ContourCarpet.moduleType = 'trace'; ContourCarpet.name = 'contourcarpet'; -ContourCarpet.basePlotModule = _$cartesian_595; -ContourCarpet.categories = ['cartesian', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent']; +ContourCarpet.basePlotModule = _$cartesian_658; +ContourCarpet.categories = ['cartesian', 'svg', 'carpet', 'contour', 'symbols', 'showLegend', 'hasLines', 'carpetDependent']; ContourCarpet.meta = { }; -var _$ContourCarpet_769 = ContourCarpet; +var _$ContourCarpet_831 = ContourCarpet; /** * Copyright 2012-2018, Plotly, Inc. @@ -59662,12 +61486,12 @@ var _$ContourCarpet_769 = ContourCarpet; 'use strict'; -var _$contourcarpet_11 = _$ContourCarpet_769; +var _$contourcarpet_11 = _$ContourCarpet_831; var _$plotcss_1 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../src/lib'); */; +/* removed: var _$lib_601 = require('../src/lib'); */; var rules = { "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;", "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;", @@ -59726,7 +61550,7 @@ for(var selector in rules) { var fullSelector = selector.replace(/^,/,' ,') .replace(/X/g, '.js-plotly-plot .plotly') .replace(/Y/g, '.plotly-notifier'); - _$lib_539.addStyleRule(fullSelector, rules[selector]); + _$lib_601.addStyleRule(fullSelector, rules[selector]); } 'use strict'; @@ -59854,9 +61678,9 @@ var _$ploticon_2 = { } }; -var _$browser_304 = {}; +var _$browser_366 = {}; // shim for using process in browser -var process = _$browser_304 = {}; +var process = _$browser_366 = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is @@ -60016,17 +61840,17 @@ process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; -function __noop_304() {} +function __noop_366() {} -process.on = __noop_304; -process.addListener = __noop_304; -process.once = __noop_304; -process.off = __noop_304; -process.removeListener = __noop_304; -process.removeAllListeners = __noop_304; -process.emit = __noop_304; -process.prependListener = __noop_304; -process.prependOnceListener = __noop_304; +process.on = __noop_366; +process.addListener = __noop_366; +process.once = __noop_366; +process.off = __noop_366; +process.removeListener = __noop_366; +process.removeAllListeners = __noop_366; +process.emit = __noop_366; +process.prependListener = __noop_366; +process.prependOnceListener = __noop_366; process.listeners = function (name) { return [] } @@ -60040,7 +61864,7 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -var _$es6Promise_136 = { exports: {} }; +var _$es6Promise_184 = { exports: {} }; (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. @@ -60051,7 +61875,7 @@ var _$es6Promise_136 = { exports: {} }; */ (function (global, factory) { - typeof _$es6Promise_136.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_136.exports = factory() : + typeof _$es6Promise_184.exports === 'object' && "object" !== 'undefined' ? _$es6Promise_184.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; @@ -61196,8 +63020,8 @@ return Promise; }))); //# sourceMappingURL=es6-promise.map -}).call(this,_$browser_304,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$es6Promise_136 = _$es6Promise_136.exports +}).call(this,_$browser_366,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +_$es6Promise_184 = _$es6Promise_184.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -61223,7 +63047,7 @@ _$es6Promise_136 = _$es6Promise_136.exports * circles, for which it's irrelevant. */ -var _$arrow_paths_393 = [ +var _$arrow_paths_455 = [ // no arrow { path: '', @@ -61278,12 +63102,12 @@ var _$arrow_paths_393 = [ 'use strict'; -/* removed: var _$arrow_paths_393 = require('./arrow_paths'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$constants_589 = require('../../plots/cartesian/constants'); */; +/* removed: var _$arrow_paths_455 = require('./arrow_paths'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$constants_652 = require('../../plots/cartesian/constants'); */; -var _$attributes_394 = { +var _$attributes_456 = { _isLinkedToArray: 'annotation', visible: { @@ -61307,7 +63131,7 @@ var _$attributes_394 = { editType: 'calcIfAutorange+arraydraw', }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'calcIfAutorange+arraydraw', colorEditType: 'arraydraw', @@ -61400,7 +63224,7 @@ var _$attributes_394 = { arrowhead: { valType: 'integer', min: 0, - max: _$arrow_paths_393.length, + max: _$arrow_paths_455.length, dflt: 1, editType: 'arraydraw', @@ -61409,7 +63233,7 @@ var _$attributes_394 = { startarrowhead: { valType: 'integer', min: 0, - max: _$arrow_paths_393.length, + max: _$arrow_paths_455.length, dflt: 1, editType: 'arraydraw', @@ -61480,7 +63304,7 @@ var _$attributes_394 = { dflt: 'pixel', values: [ 'pixel', - _$constants_589.idRegex.x.toString() + _$constants_652.idRegex.x.toString() ], editType: 'calc', @@ -61491,7 +63315,7 @@ var _$attributes_394 = { dflt: 'pixel', values: [ 'pixel', - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.y.toString() ], editType: 'calc', @@ -61502,7 +63326,7 @@ var _$attributes_394 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.x.toString() + _$constants_652.idRegex.x.toString() ], editType: 'calc', @@ -61533,7 +63357,7 @@ var _$attributes_394 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.y.toString() ], editType: 'calc', @@ -61599,7 +63423,7 @@ var _$attributes_394 = { editType: 'arraydraw', }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'arraydraw', }), @@ -61634,11 +63458,11 @@ var _$attributes_394 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$color_473 = require('../color'); */; -/* removed: var _$arrow_paths_393 = require('./arrow_paths'); */; +/* removed: var _$arrow_paths_455 = require('./arrow_paths'); */; /** * Add arrowhead(s) to a path or line element @@ -61660,10 +63484,10 @@ var _$attributes_394 = { * of both the line and head has opacity applied to it so there isn't greater opacity * where they overlap. */ -var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { +var _$drawArrowHead_463 = function drawArrowHead(el3, ends, options) { var el = el3.node(); - var headStyle = _$arrow_paths_393[options.arrowhead || 0]; - var startHeadStyle = _$arrow_paths_393[options.startarrowhead || 0]; + var headStyle = _$arrow_paths_455[options.arrowhead || 0]; + var startHeadStyle = _$arrow_paths_455[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; @@ -61757,7 +63581,7 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { if(!arrowHeadStyle.path) return; if(arrowHeadStyle.noRotate) rot = 0; - _$d3_127.select(el.parentNode).append('path') + _$d3_130.select(el.parentNode).append('path') .attr({ 'class': el3.attr('class'), d: arrowHeadStyle.path, @@ -61767,7 +63591,7 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { 'scale(' + arrowScale + ')' }) .style({ - fill: _$color_411.rgb(options.arrowcolor), + fill: _$color_473.rgb(options.arrowcolor), 'stroke-width': 0 }); } @@ -61786,19 +63610,19 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$fx_453 = require('../fx'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$drawArrowHead_401 = require('./draw_arrow_head'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$fx_515 = require('../fx'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$drawArrowHead_463 = require('./draw_arrow_head'); */; // Annotations are stored in gd.layout.annotations, an array of objects // index can point to one item in this array, @@ -61809,8 +63633,8 @@ var _$drawArrowHead_401 = function drawArrowHead(el3, ends, options) { // if opt is blank, val can be 'add' or a full options object to add a new // annotation at that point in the array, or 'remove' to delete this one -var _$draw_400 = { - draw: __draw_400, +var _$draw_462 = { + draw: __draw_462, drawOne: drawOne, drawRaw: drawRaw }; @@ -61818,7 +63642,7 @@ var _$draw_400 = { /* * draw: draw all annotations without any new modifications */ -function __draw_400(gd) { +function __draw_462(gd) { var fullLayout = gd._fullLayout; fullLayout._infolayer.selectAll('.annotation').remove(); @@ -61829,7 +63653,7 @@ function __draw_400(gd) { } } - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); } /* @@ -61840,8 +63664,8 @@ function __draw_400(gd) { function drawOne(gd, index) { var fullLayout = gd._fullLayout; var options = fullLayout.annotations[index] || {}; - var xa = _$axes_584.getFromId(gd, options.xref); - var ya = _$axes_584.getFromId(gd, options.yref); + var xa = _$axes_647.getFromId(gd, options.xref); + var ya = _$axes_647.getFromId(gd, options.yref); drawRaw(gd, options, index, false, xa, ya); } @@ -61883,7 +63707,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // this annotation is gone - quit now after deleting it // TODO: use d3 idioms instead of deleting and redrawing every time if(!options._input || options.visible === false) { - _$d3_127.selectAll('#' + annClipID).remove(); + _$d3_130.selectAll('#' + annClipID).remove(); return; } @@ -61910,7 +63734,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextGroupInner = annTextGroup.append('g') .style('pointer-events', textEvents ? 'all' : null) - .call(_$setCursor_558, 'default') + .call(_$setCursor_621, 'default') .on('click', function() { gd._dragging = false; @@ -61918,7 +63742,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { index: index, annotation: options._input, fullAnnotation: options, - event: _$d3_127.event + event: _$d3_130.event }; if(subplotId) { @@ -61936,7 +63760,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var bBox = this.getBoundingClientRect(); var bBoxRef = gd.getBoundingClientRect(); - _$fx_453.loneHover({ + _$fx_515.loneHover({ x0: bBox.left - bBoxRef.left, x1: bBox.right - bBoxRef.left, y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, @@ -61953,7 +63777,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }) .on('mouseout', function() { - _$fx_453.loneUnhover(fullLayout._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout._hoverlayer.node()); }); } @@ -61964,8 +63788,8 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annTextBG = annTextGroupInner.append('rect') .attr('class', 'bg') .style('stroke-width', borderwidth + 'px') - .call(_$color_411.stroke, options.bordercolor) - .call(_$color_411.fill, options.bgcolor); + .call(_$color_473.stroke, options.bordercolor) + .call(_$color_473.fill, options.bgcolor); var isSizeConstrained = options.width || options.height; @@ -61986,7 +63810,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { .text(options.text); function textLayout(s) { - s.call(_$drawing_436.font, font) + s.call(_$drawing_498.font, font) .attr({ 'text-anchor': { left: 'start', @@ -61994,7 +63818,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }[options.align] || 'middle' }); - _$svg_text_utils_562.convertToTspans(s, gd, drawGraphicalElements); + _$svg_text_utils_625.convertToTspans(s, gd, drawGraphicalElements); return s; } @@ -62013,7 +63837,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group'); var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = _$drawing_436.bBox( + var anntextBB = _$drawing_498.bBox( (hasMathjax ? mathjaxGroup : annText).node()); var textWidth = anntextBB.width; var textHeight = anntextBB.height; @@ -62135,7 +63959,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // partially visible var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height']; if(axRef === 'paper') { - posPx.head = _$lib_539.constrain(posPx.head, 1, maxPx - 1); + posPx.head = _$lib_601.constrain(posPx.head, 1, maxPx - 1); } if(tailRef === 'pixel') { var shiftPlus = -Math.max(posPx.tail - 3, posPx.text), @@ -62194,23 +64018,23 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { x: borderfull + xShift - 1, y: borderfull + yShift }) - .call(_$drawing_436.setClipUrl, isSizeConstrained ? annClipID : null); + .call(_$drawing_498.setClipUrl, isSizeConstrained ? annClipID : null); } else { var texty = borderfull + yShift - anntextBB.top; var textx = borderfull + xShift - anntextBB.left; - annText.call(_$svg_text_utils_562.positionText, textx, texty) - .call(_$drawing_436.setClipUrl, isSizeConstrained ? annClipID : null); + annText.call(_$svg_text_utils_625.positionText, textx, texty) + .call(_$drawing_498.setClipUrl, isSizeConstrained ? annClipID : null); } - annTextClip.select('rect').call(_$drawing_436.setRect, borderfull, borderfull, + annTextClip.select('rect').call(_$drawing_498.setRect, borderfull, borderfull, annWidth, annHeight); - annTextBG.call(_$drawing_436.setRect, borderwidth / 2, borderwidth / 2, + annTextBG.call(_$drawing_498.setRect, borderwidth / 2, borderwidth / 2, outerWidth - borderwidth, outerHeight - borderwidth); - annTextGroupInner.call(_$drawing_436.setTranslate, + annTextGroupInner.call(_$drawing_498.setTranslate, Math.round(annPosPx.x.text - outerWidth / 2), Math.round(annPosPx.y.text - outerHeight / 2)); @@ -62243,9 +64067,9 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // find the edge of the text box, where we'll start the arrow: // create transform matrix to rotate the text box corners - transform = _$lib_539.rotationXYMatrix(textangle, textX, textY), - applyTransform = _$lib_539.apply2DTransform(transform), - applyTransform2 = _$lib_539.apply2DTransform2(transform), + transform = _$lib_601.rotationXYMatrix(textangle, textX, textY), + applyTransform = _$lib_601.apply2DTransform(transform), + applyTransform2 = _$lib_601.apply2DTransform2(transform), // calculate and transform bounding box width = +annTextBG.attr('width'), @@ -62267,7 +64091,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // to get the parity of the number of intersections. if(edges.reduce(function(a, x) { return a ^ - !!_$lib_539.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, + !!_$lib_601.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6, x[0], x[1], x[2], x[3]); }, false)) { // no line or arrow - so quit drawArrow now @@ -62275,7 +64099,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } edges.forEach(function(x) { - var p = _$lib_539.segmentsIntersect(tailX, tailY, headX, headY, + var p = _$lib_601.segmentsIntersect(tailX, tailY, headX, headY, x[0], x[1], x[2], x[3]); if(p) { tailX = p.x; @@ -62288,15 +64112,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { arrowSide = options.arrowside; var arrowGroup = annGroup.append('g') - .style({opacity: _$color_411.opacity(arrowColor)}) + .style({opacity: _$color_473.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_411.stroke, _$color_411.rgb(arrowColor)); + .call(_$color_473.stroke, _$color_473.rgb(arrowColor)); - _$drawArrowHead_401(arrow, arrowSide, options); + _$drawArrowHead_463(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 @@ -62316,8 +64140,8 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')' }) .style('stroke-width', (strokewidth + 6) + 'px') - .call(_$color_411.stroke, 'rgba(0,0,0,0)') - .call(_$color_411.fill, 'rgba(0,0,0,0)'); + .call(_$color_473.stroke, 'rgba(0,0,0,0)') + .call(_$color_473.fill, 'rgba(0,0,0,0)'); var update, annx0, @@ -62325,11 +64149,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // dragger for the arrow & head: translates the whole thing // (head/tail/text) all together - _$dragelement_433.init({ + _$dragelement_495.init({ element: arrowDrag.node(), gd: gd, prepFn: function() { - var pos = _$drawing_436.getTranslate(annTextGroupInner); + var pos = _$drawing_498.getTranslate(annTextGroupInner); annx0 = pos.x; anny0 = pos.y; @@ -62345,7 +64169,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { var annxy0 = applyTransform(annx0, anny0), xcenter = annxy0[0] + dx, ycenter = annxy0[1] + dy; - annTextGroupInner.call(_$drawing_436.setTranslate, xcenter, ycenter); + annTextGroupInner.call(_$drawing_498.setTranslate, xcenter, ycenter); update[annbase + '.x'] = xa ? xa.p2r(xa.r2p(options.x) + dx) : @@ -62369,7 +64193,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { }); }, doneFn: function() { - _$registry_668.call('relayout', gd, update); + _$registry_731.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -62386,7 +64210,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { // dragger for the textbox: if there's an arrow, just drag the // textbox and tail, leave the head untouched - _$dragelement_433.init({ + _$dragelement_495.init({ element: annTextGroupInner.node(), gd: gd, prepFn: function() { @@ -62419,7 +64243,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2; - update[annbase + '.x'] = _$dragelement_433.align(xLeft + dx / gs.w, + update[annbase + '.x'] = _$dragelement_495.align(xLeft + dx / gs.w, widthFraction, 0, 1, options.xanchor); } @@ -62430,11 +64254,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2; - update[annbase + '.y'] = _$dragelement_433.align(yBottom - dy / gs.h, + update[annbase + '.y'] = _$dragelement_495.align(yBottom - dy / gs.h, heightFraction, 0, 1, options.yanchor); } if(!xa || !ya) { - csr = _$dragelement_433.getCursor( + csr = _$dragelement_495.getCursor( xa ? 0.5 : update[annbase + '.x'], ya ? 0.5 : update[annbase + '.y'], options.xanchor, options.yanchor @@ -62447,11 +64271,11 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform }); - _$setCursor_558(annTextGroupInner, csr); + _$setCursor_621(annTextGroupInner, csr); }, doneFn: function() { - _$setCursor_558(annTextGroupInner); - _$registry_668.call('relayout', gd, update); + _$setCursor_621(annTextGroupInner); + _$registry_731.call('relayout', gd, update); var notesBox = document.querySelector('.js-notes-box-panel'); if(notesBox) notesBox.redraw(notesBox.selectedObj); } @@ -62460,7 +64284,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { } if(edits.annotationText) { - annText.call(_$svg_text_utils_562.makeEditable, {delegate: annTextGroupInner, gd: gd}) + annText.call(_$svg_text_utils_625.makeEditable, {delegate: annTextGroupInner, gd: gd}) .call(textLayout) .on('edit', function(_text) { options.text = _text; @@ -62476,7 +64300,7 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { update[ya._name + '.autorange'] = true; } - _$registry_668.call('relayout', gd, update); + _$registry_731.call('relayout', gd, update); }); } else annText.call(textLayout); @@ -62493,15 +64317,15 @@ function drawRaw(gd, options, index, subplotId, xa, ya) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var __draw_395 = _$draw_400.draw; +var __draw_457 = _$draw_462.draw; -var _$calcAutorange_395 = function calcAutorange(gd) { +var _$calcAutorange_457 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - annotationList = _$lib_539.filterVisible(fullLayout.annotations); + annotationList = _$lib_601.filterVisible(fullLayout.annotations); if(!annotationList.length || !gd._fullData.length) return; @@ -62512,10 +64336,10 @@ var _$calcAutorange_395 = function calcAutorange(gd) { }); for(var axId in annotationAxes) { - var ax = _$axes_584.getFromId(gd, axId); + var ax = _$axes_647.getFromId(gd, axId); if(ax && ax.autorange) { - return _$lib_539.syncOrAsync([ - __draw_395, + return _$lib_601.syncOrAsync([ + __draw_457, annAutorange ], gd); } @@ -62529,9 +64353,9 @@ function annAutorange(gd) { // relative to their anchor points // use the arrow and the text bg rectangle, // as the whole anno may include hidden text in its bbox - _$lib_539.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = _$axes_584.getFromId(gd, ann.xref), - ya = _$axes_584.getFromId(gd, ann.yref), + _$lib_601.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = _$axes_647.getFromId(gd, ann.xref), + ya = _$axes_647.getFromId(gd, ann.yref), headSize = 3 * ann.arrowsize * ann.arrowwidth || 0, startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; @@ -62545,12 +64369,12 @@ function annAutorange(gd) { if(ann.axref === ann.xref) { // expand for the arrowhead (padded by arrowhead) - _$axes_584.expand(xa, [xa.r2c(ann.x)], { + _$axes_647.expand(xa, [xa.r2c(ann.x)], { ppadplus: headPlus, ppadminus: headMinus }); // again for the textbox (padded by textbox) - _$axes_584.expand(xa, [xa.r2c(ann.ax)], { + _$axes_647.expand(xa, [xa.r2c(ann.ax)], { ppadplus: Math.max(ann._xpadplus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, startHeadMinus) }); @@ -62558,7 +64382,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus; startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus; - _$axes_584.expand(xa, [xa.r2c(ann.x)], { + _$axes_647.expand(xa, [xa.r2c(ann.x)], { ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus) }); @@ -62572,11 +64396,11 @@ function annAutorange(gd) { startHeadMinus = startHeadSize + ann.yshift; if(ann.ayref === ann.yref) { - _$axes_584.expand(ya, [ya.r2c(ann.y)], { + _$axes_647.expand(ya, [ya.r2c(ann.y)], { ppadplus: headPlus, ppadminus: headMinus }); - _$axes_584.expand(ya, [ya.r2c(ann.ay)], { + _$axes_647.expand(ya, [ya.r2c(ann.ay)], { ppadplus: Math.max(ann._ypadplus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, startHeadMinus) }); @@ -62584,7 +64408,7 @@ function annAutorange(gd) { else { startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus; startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus; - _$axes_584.expand(ya, [ya.r2c(ann.y)], { + _$axes_647.expand(ya, [ya.r2c(ann.y)], { ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus), ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus) }); @@ -62603,9 +64427,9 @@ function annAutorange(gd) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -var _$click_396 = { +var _$click_458 = { hasClickToShow: hasClickToShow, onClick: onClick }; @@ -62652,7 +64476,7 @@ function onClick(gd, hoverData) { update['annotations[' + offSet[i] + '].visible'] = false; } - return _$registry_668.call('update', gd, {}, update); + return _$registry_731.call('update', gd, {}, update); } /* @@ -62735,8 +64559,8 @@ function clickData2r(d, ax) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_564 = require('../../lib/to_log_range'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_627 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -62751,7 +64575,7 @@ function clickData2r(d, ax) { * Use this to make the changes as it's aware if any other changes in the * same relayout call should override this conversion. */ -var _$convertCoords_398 = function convertCoords(gd, ax, newType, doExtra) { +var _$convertCoords_460 = function convertCoords(gd, ax, newType, doExtra) { ax = ax || {}; var toLog = (newType === 'log') && (ax.type === 'linear'), @@ -62768,11 +64592,11 @@ var _$convertCoords_398 = function convertCoords(gd, ax, newType, doExtra) { var currentVal = ann[attr], newVal = null; - if(toLog) newVal = _$toLogRange_564(currentVal, ax.range); + if(toLog) newVal = _$toLogRange_627(currentVal, ax.range); else newVal = Math.pow(10, currentVal); // if conversion failed, delete the value so it gets a default value - if(!_$fastIsnumeric_139(newVal)) newVal = null; + if(!_$fastIsnumeric_196(newVal)) newVal = null; doExtra(attrPrefix + attr, newVal); } @@ -62796,16 +64620,16 @@ var _$convertCoords_398 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../color'); */; // defaults common to 'annotations' and 'annotations3d' -var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { +var _$handleAnnotationCommonDefaults_459 = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) { coerce('opacity'); var bgColor = coerce('bgcolor'); var borderColor = coerce('bordercolor'); - var borderOpacity = _$color_411.opacity(borderColor); + var borderOpacity = _$color_473.opacity(borderColor); coerce('borderpad'); @@ -62814,7 +64638,7 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation); coerce('textangle'); - _$lib_539.coerceFont(coerce, 'font', fullLayout.font); + _$lib_601.coerceFont(coerce, 'font', fullLayout.font); coerce('width'); coerce('align'); @@ -62836,7 +64660,7 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul coerce('startarrowhead', arrowhead); coerce('startarrowsize', arrowsize); } - coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_411.defaultLine); + coerce('arrowcolor', borderOpacity ? annOut.bordercolor : _$color_473.defaultLine); coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2); coerce('standoff'); coerce('startstandoff'); @@ -62848,14 +64672,14 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul if(hoverText) { var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor || - (_$color_411.opacity(bgColor) ? _$color_411.rgb(bgColor) : _$color_411.defaultLine) + (_$color_473.opacity(bgColor) ? _$color_473.rgb(bgColor) : _$color_473.defaultLine) ); var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor || - _$color_411.contrast(hoverBG) + _$color_473.contrast(hoverBG) ); - _$lib_539.coerceFont(coerce, 'hoverlabel.font', { + _$lib_601.coerceFont(coerce, 'hoverlabel.font', { family: globalHoverLabel.font.family, size: globalHoverLabel.font.size, color: globalHoverLabel.font.color || hoverBorder @@ -62876,18 +64700,18 @@ var _$handleAnnotationCommonDefaults_397 = function handleAnnotationCommonDefaul 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleAnnotationCommonDefaults_397 = require('./common_defaults'); */; -/* removed: var _$attributes_394 = require('./attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleAnnotationCommonDefaults_459 = require('./common_defaults'); */; +/* removed: var _$attributes_456 = require('./attributes'); */; -var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { +var _$handleAnnotationDefaults_454 = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) { opts = opts || {}; itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(annIn, annOut, _$attributes_394, attr, dflt); + return _$lib_601.coerce(annIn, annOut, _$attributes_456, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -62895,7 +64719,7 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an if(!(visible || clickToShow)) return annOut; - _$handleAnnotationCommonDefaults_397(annIn, annOut, fullLayout, coerce); + _$handleAnnotationCommonDefaults_459(annIn, annOut, fullLayout, coerce); var showArrow = annOut.showarrow; @@ -62907,15 +64731,15 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an var axLetter = axLetters[i]; // xref, yref - var axRef = _$axes_584.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_647.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper'); // x, y - _$axes_584.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); + _$axes_647.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5); if(showArrow) { var arrowPosAttr = 'a' + axLetter, // axref, ayref - aaxRef = _$axes_584.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); + aaxRef = _$axes_647.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel'); // for now the arrow can only be on the same axis or specified as pixels // TODO: sometime it might be interesting to allow it to be on *any* axis @@ -62926,7 +64750,7 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an // ax, ay var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4; - _$axes_584.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); + _$axes_647.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt); } // xanchor, yanchor @@ -62937,11 +64761,11 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an } // if you have one coordinate you should have both - _$lib_539.noneOrAll(annIn, annOut, ['x', 'y']); + _$lib_601.noneOrAll(annIn, annOut, ['x', 'y']); // if you have one part of arrow length you should have both if(showArrow) { - _$lib_539.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_601.noneOrAll(annIn, annOut, ['ax', 'ay']); } if(clickToShow) { @@ -62952,10 +64776,10 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an // so we don't have to do this little bit of logic on every hover event annOut._xclick = (xClick === undefined) ? annOut.x : - _$axes_584.cleanPosition(xClick, gdMock, annOut.xref); + _$axes_647.cleanPosition(xClick, gdMock, annOut.xref); annOut._yclick = (yClick === undefined) ? annOut.y : - _$axes_584.cleanPosition(yClick, gdMock, annOut.yref); + _$axes_647.cleanPosition(yClick, gdMock, annOut.yref); } return annOut; @@ -62971,7 +64795,7 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$lib_601 = require('../lib'); */; /** Convenience wrapper for making array container logic DRY and consistent * @@ -63003,12 +64827,12 @@ var _$handleAnnotationDefaults_392 = function handleAnnotationDefaults(annIn, an * links to supplementary data (e.g. fullData for layout components) * */ -var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { +var _$handleArrayContainerDefaults_643 = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { var name = opts.name; var previousContOut = parentObjOut[name]; - var contIn = _$lib_539.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], + var contIn = _$lib_601.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [], contOut = parentObjOut[name] = [], i; @@ -63017,7 +64841,7 @@ var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(p itemOut = {}, itemOpts = {}; - if(!_$lib_539.isPlainObject(itemIn)) { + if(!_$lib_601.isPlainObject(itemIn)) { itemOpts.itemIsNotPlainObject = true; itemIn = {}; } @@ -63032,10 +64856,10 @@ var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(p // in case this array gets its defaults rebuilt independent of the whole layout, // relink the private keys just for this array. - if(_$lib_539.isArrayOrTypedArray(previousContOut)) { + if(_$lib_601.isArrayOrTypedArray(previousContOut)) { var len = Math.min(previousContOut.length, contOut.length); for(i = 0; i < len; i++) { - _$lib_539.relinkPrivateKeys(contOut[i], previousContOut[i]); + _$lib_601.relinkPrivateKeys(contOut[i], previousContOut[i]); } } }; @@ -63051,17 +64875,17 @@ var _$handleArrayContainerDefaults_580 = function handleArrayContainerDefaults(p 'use strict'; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationDefaults_392 = require('./annotation_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationDefaults_454 = require('./annotation_defaults'); */; -var _$supplyLayoutDefaults_399 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_461 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { name: 'annotations', - handleItemDefaults: _$handleAnnotationDefaults_392 + handleItemDefaults: _$handleAnnotationDefaults_454 }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; /** @@ -63075,8 +64899,8 @@ var _$supplyLayoutDefaults_399 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** * Factory function for checking component arrays for subplot references. @@ -63089,12 +64913,12 @@ var _$supplyLayoutDefaults_399 = function supplyLayoutDefaults(layoutIn, layoutO * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout) * as expected of a component includeBasePlot method */ -var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayName) { +var _$makeIncludeComponents_657 = function makeIncludeComponents(containerArrayName) { return function includeComponents(layoutIn, layoutOut) { var array = layoutIn[containerArrayName]; if(!Array.isArray(array)) return; - var Cartesian = _$registry_668.subplotsRegistry.cartesian; + var Cartesian = _$registry_731.subplotsRegistry.cartesian; var idRegex = Cartesian.idRegex; var subplots = layoutOut._subplots; var xaList = subplots.xaxis; @@ -63104,7 +64928,7 @@ var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayN for(var i = 0; i < array.length; i++) { var itemi = array[i]; - if(!_$lib_539.isPlainObject(itemi)) continue; + if(!_$lib_601.isPlainObject(itemi)) continue; var xref = itemi.xref; var yref = itemi.yref; @@ -63112,7 +64936,7 @@ var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayN var hasXref = idRegex.x.test(xref); var hasYref = idRegex.y.test(yref); if(hasXref || hasYref) { - if(!hasCartesianOrGL2D) _$lib_539.pushUnique(layoutOut._basePlotModules, Cartesian); + if(!hasCartesianOrGL2D) _$lib_601.pushUnique(layoutOut._basePlotModules, Cartesian); var newAxis = false; if(hasXref && xaList.indexOf(xref) === -1) { @@ -63149,26 +64973,26 @@ var _$makeIncludeComponents_594 = function makeIncludeComponents(containerArrayN 'use strict'; -/* removed: var _$draw_400 = require('./draw'); */; -/* removed: var _$click_396 = require('./click'); */; +/* removed: var _$draw_462 = require('./draw'); */; +/* removed: var _$click_458 = require('./click'); */; -var _$annotations_402 = { +var _$annotations_464 = { moduleType: 'component', name: 'annotations', - layoutAttributes: _$attributes_394, - supplyLayoutDefaults: _$supplyLayoutDefaults_399, - includeBasePlot: _$makeIncludeComponents_594('annotations'), + layoutAttributes: _$attributes_456, + supplyLayoutDefaults: _$supplyLayoutDefaults_461, + includeBasePlot: _$makeIncludeComponents_657('annotations'), - calcAutorange: _$calcAutorange_395, - draw: _$draw_400.draw, - drawOne: _$draw_400.drawOne, - drawRaw: _$draw_400.drawRaw, + calcAutorange: _$calcAutorange_457, + draw: _$draw_462.draw, + drawOne: _$draw_462.drawOne, + drawRaw: _$draw_462.drawRaw, - hasClickToShow: _$click_396.hasClickToShow, - onClick: _$click_396.onClick, + hasClickToShow: _$click_458.hasClickToShow, + onClick: _$click_458.onClick, - convertCoords: _$convertCoords_398 + convertCoords: _$convertCoords_460 }; /** @@ -63182,13 +65006,13 @@ var _$annotations_402 = { 'use strict'; -/* removed: var _$attributes_394 = require('../annotations/attributes'); */; -var __overrideAll_403 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_456 = require('../annotations/attributes'); */; +var __overrideAll_465 = _$edit_types_632.overrideAll; -var _$attributes_403 = __overrideAll_403({ +var _$attributes_465 = __overrideAll_465({ _isLinkedToArray: 'annotation', - visible: _$attributes_394.visible, + visible: _$attributes_456.visible, x: { valType: 'any', @@ -63215,36 +65039,36 @@ var _$attributes_403 = __overrideAll_403({ }, - xanchor: _$attributes_394.xanchor, - xshift: _$attributes_394.xshift, - yanchor: _$attributes_394.yanchor, - yshift: _$attributes_394.yshift, - - text: _$attributes_394.text, - textangle: _$attributes_394.textangle, - font: _$attributes_394.font, - width: _$attributes_394.width, - height: _$attributes_394.height, - opacity: _$attributes_394.opacity, - align: _$attributes_394.align, - valign: _$attributes_394.valign, - bgcolor: _$attributes_394.bgcolor, - bordercolor: _$attributes_394.bordercolor, - borderpad: _$attributes_394.borderpad, - borderwidth: _$attributes_394.borderwidth, - showarrow: _$attributes_394.showarrow, - arrowcolor: _$attributes_394.arrowcolor, - arrowhead: _$attributes_394.arrowhead, - startarrowhead: _$attributes_394.startarrowhead, - arrowside: _$attributes_394.arrowside, - arrowsize: _$attributes_394.arrowsize, - startarrowsize: _$attributes_394.startarrowsize, - arrowwidth: _$attributes_394.arrowwidth, - standoff: _$attributes_394.standoff, - startstandoff: _$attributes_394.startstandoff, - hovertext: _$attributes_394.hovertext, - hoverlabel: _$attributes_394.hoverlabel, - captureevents: _$attributes_394.captureevents, + xanchor: _$attributes_456.xanchor, + xshift: _$attributes_456.xshift, + yanchor: _$attributes_456.yanchor, + yshift: _$attributes_456.yshift, + + text: _$attributes_456.text, + textangle: _$attributes_456.textangle, + font: _$attributes_456.font, + width: _$attributes_456.width, + height: _$attributes_456.height, + opacity: _$attributes_456.opacity, + align: _$attributes_456.align, + valign: _$attributes_456.valign, + bgcolor: _$attributes_456.bgcolor, + bordercolor: _$attributes_456.bordercolor, + borderpad: _$attributes_456.borderpad, + borderwidth: _$attributes_456.borderwidth, + showarrow: _$attributes_456.showarrow, + arrowcolor: _$attributes_456.arrowcolor, + arrowhead: _$attributes_456.arrowhead, + startarrowhead: _$attributes_456.startarrowhead, + arrowside: _$attributes_456.arrowside, + arrowsize: _$attributes_456.arrowsize, + startarrowsize: _$attributes_456.startarrowsize, + arrowwidth: _$attributes_456.arrowwidth, + standoff: _$attributes_456.standoff, + startstandoff: _$attributes_456.startstandoff, + hovertext: _$attributes_456.hovertext, + hoverlabel: _$attributes_456.hoverlabel, + captureevents: _$attributes_456.captureevents, // maybes later? // clicktoshow: annAtts.clicktoshow, @@ -63269,10 +65093,10 @@ var _$attributes_403 = __overrideAll_403({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var _$convert_404 = function convert(scene) { +var _$convert_466 = function convert(scene) { var fullSceneLayout = scene.fullSceneLayout; var anns = fullSceneLayout.annotations; @@ -63307,16 +65131,16 @@ function mockAnnAxes(ann, scene) { }; ann._xa = {}; - _$lib_539.extendFlat(ann._xa, base); - _$axes_584.setConvert(ann._xa); + _$lib_601.extendFlat(ann._xa, base); + _$axes_647.setConvert(ann._xa); ann._xa._offset = size.l + domain.x[0] * size.w; ann._xa.l2p = function() { return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]); }; ann._ya = {}; - _$lib_539.extendFlat(ann._ya, base); - _$axes_584.setConvert(ann._ya); + _$lib_601.extendFlat(ann._ya, base); + _$axes_647.setConvert(ann._ya); ann._ya._offset = size.t + (1 - domain.y[1]) * size.h; ann._ya.l2p = function() { return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]); @@ -63333,23 +65157,23 @@ function mockAnnAxes(ann, scene) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleAnnotationCommonDefaults_397 = require('../annotations/common_defaults'); */; -/* removed: var _$attributes_403 = require('./attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleAnnotationCommonDefaults_459 = require('../annotations/common_defaults'); */; +/* removed: var _$attributes_465 = require('./attributes'); */; -var _$handleDefaults_405 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - _$handleArrayContainerDefaults_580(sceneLayoutIn, sceneLayoutOut, { +var _$handleDefaults_467 = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + _$handleArrayContainerDefaults_643(sceneLayoutIn, sceneLayoutOut, { name: 'annotations', - handleItemDefaults: __handleAnnotationDefaults_405, + handleItemDefaults: __handleAnnotationDefaults_467, fullLayout: opts.fullLayout }); }; -function __handleAnnotationDefaults_405(annIn, annOut, sceneLayout, opts, itemOpts) { +function __handleAnnotationDefaults_467(annIn, annOut, sceneLayout, opts, itemOpts) { function coerce(attr, dflt) { - return _$lib_539.coerce(annIn, annOut, _$attributes_403, attr, dflt); + return _$lib_601.coerce(annIn, annOut, _$attributes_465, attr, dflt); } function coercePosition(axLetter) { @@ -63359,21 +65183,21 @@ function __handleAnnotationDefaults_405(annIn, annOut, sceneLayout, opts, itemOp var gdMock = { _fullLayout: {} }; gdMock._fullLayout[axName] = sceneLayout[axName]; - return _$axes_584.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); + return _$axes_647.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); if(!visible) return annOut; - _$handleAnnotationCommonDefaults_397(annIn, annOut, opts.fullLayout, coerce); + _$handleAnnotationCommonDefaults_459(annIn, annOut, opts.fullLayout, coerce); coercePosition('x'); coercePosition('y'); coercePosition('z'); // if you have one coordinate you should all three - _$lib_539.noneOrAll(annIn, annOut, ['x', 'y', 'z']); + _$lib_601.noneOrAll(annIn, annOut, ['x', 'y', 'z']); // hard-set here for completeness annOut.xref = 'x'; @@ -63394,7 +65218,7 @@ function __handleAnnotationDefaults_405(annIn, annOut, sceneLayout, opts, itemOp coerce('ay', -30); // if you have one part of arrow length you should have both - _$lib_539.noneOrAll(annIn, annOut, ['ax', 'ay']); + _$lib_601.noneOrAll(annIn, annOut, ['ax', 'ay']); } return annOut; @@ -63431,7 +65255,7 @@ function project(camera, v) { return p; } -var _$project_636 = project; +var _$project_698 = project; /** * Copyright 2012-2018, Plotly, Inc. @@ -63443,11 +65267,11 @@ var _$project_636 = project; 'use strict'; -var __drawRaw_406 = _$draw_400.drawRaw; -/* removed: var _$project_636 = require('../../plots/gl3d/project'); */; +var __drawRaw_468 = _$draw_462.drawRaw; +/* removed: var _$project_698 = require('../../plots/gl3d/project'); */; var axLetters = ['x', 'y', 'z']; -var _$draw_406 = function draw(scene) { +var _$draw_468 = function draw(scene) { var fullSceneLayout = scene.fullSceneLayout; var dataScale = scene.dataScale; var anns = fullSceneLayout.annotations; @@ -63473,13 +65297,13 @@ var _$draw_406 = function draw(scene) { .select('.annotation-' + scene.id + '[data-index="' + i + '"]') .remove(); } else { - ann._pdata = _$project_636(scene.glplot.cameraParams, [ + ann._pdata = _$project_698(scene.glplot.cameraParams, [ fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] ]); - __drawRaw_406(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + __drawRaw_468(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); } } }; @@ -63494,29 +65318,29 @@ var _$draw_406 = function draw(scene) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -var _$annotations3d_407 = { +var _$annotations3d_469 = { moduleType: 'component', name: 'annotations3d', schema: { subplots: { - scene: {annotations: _$attributes_403} + scene: {annotations: _$attributes_465} } }, - layoutAttributes: _$attributes_403, - handleDefaults: _$handleDefaults_405, + layoutAttributes: _$attributes_465, + handleDefaults: _$handleDefaults_467, includeBasePlot: includeGL3D, - convert: _$convert_404, - draw: _$draw_406 + convert: _$convert_466, + draw: _$draw_468 }; function includeGL3D(layoutIn, layoutOut) { - var GL3D = _$registry_668.subplotsRegistry.gl3d; + var GL3D = _$registry_731.subplotsRegistry.gl3d; if(!GL3D) return; var attrRegex = GL3D.attrRegex; @@ -63525,8 +65349,8 @@ function includeGL3D(layoutIn, layoutOut) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - _$lib_539.pushUnique(layoutOut._basePlotModules, GL3D); - _$lib_539.pushUnique(layoutOut._subplots.gl3d, k); + _$lib_601.pushUnique(layoutOut._basePlotModules, GL3D); + _$lib_601.pushUnique(layoutOut._subplots.gl3d, k); } } } @@ -63542,7 +65366,7 @@ function includeGL3D(layoutIn, layoutOut) { 'use strict'; -var _$attributes_438 = { +var _$attributes_500 = { visible: { valType: 'boolean', @@ -63672,7 +65496,7 @@ var _$attributes_438 = { * - error[0] : error magnitude in the negative direction * - error[1] : " " " " positive " */ -var _$makeComputeError_440 = function makeComputeError(opts) { +var _$makeComputeError_502 = function makeComputeError(opts) { var type = opts.type, symmetric = opts.symmetric; @@ -63759,25 +65583,25 @@ function makeComputeErrorValue(type, value) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$makeComputeError_440 = require('./compute_error'); */; +/* removed: var _$makeComputeError_502 = require('./compute_error'); */; -var _$calc_439 = function calc(gd) { +var _$calc_501 = function calc(gd) { var calcdata = gd.calcdata; for(var i = 0; i < calcdata.length; i++) { var calcTrace = calcdata[i], trace = calcTrace[0].trace; - if(!_$registry_668.traceIs(trace, 'errorBarsOK')) continue; + if(!_$registry_731.traceIs(trace, 'errorBarsOK')) continue; - var xa = _$axes_584.getFromId(gd, trace.xaxis), - ya = _$axes_584.getFromId(gd, trace.yaxis); + var xa = _$axes_647.getFromId(gd, trace.xaxis), + ya = _$axes_647.getFromId(gd, trace.yaxis); calcOneAxis(calcTrace, trace, xa, 'x'); calcOneAxis(calcTrace, trace, ya, 'y'); @@ -63791,23 +65615,23 @@ function calcOneAxis(calcTrace, trace, axis, coord) { if(!isVisible) return; - var computeError = _$makeComputeError_440(opts); + var computeError = _$makeComputeError_502(opts); for(var i = 0; i < calcTrace.length; i++) { var calcPt = calcTrace[i], calcCoord = calcPt[coord]; - if(!_$fastIsnumeric_139(axis.c2l(calcCoord))) continue; + if(!_$fastIsnumeric_196(axis.c2l(calcCoord))) continue; var errors = computeError(calcCoord, i); - if(_$fastIsnumeric_139(errors[0]) && _$fastIsnumeric_139(errors[1])) { + if(_$fastIsnumeric_196(errors[0]) && _$fastIsnumeric_196(errors[1])) { var shoe = calcPt[coord + 's'] = calcCoord - errors[0], hat = calcPt[coord + 'h'] = calcCoord + errors[1]; vals.push(shoe, hat); } } - _$axes_584.expand(axis, vals, {padded: true}); + _$axes_647.expand(axis, vals, {padded: true}); } /** @@ -63820,21 +65644,21 @@ function calcOneAxis(calcTrace, trace, axis, coord) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$attributes_438 = require('./attributes'); */; +/* removed: var _$attributes_500 = require('./attributes'); */; -var _$defaults_441 = function(traceIn, traceOut, defaultColor, opts) { +var _$defaults_503 = function(traceIn, traceOut, defaultColor, opts) { var objName = 'error_' + opts.axis, containerOut = traceOut[objName] = {}, containerIn = traceIn[objName] || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$attributes_438, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$attributes_500, attr, dflt); } var hasErrorBars = ( @@ -63873,14 +65697,14 @@ var _$defaults_441 = function(traceIn, traceOut, defaultColor, opts) { var inheritObj = traceOut['error_' + opts.inherit]; if((inheritObj || {}).visible) { coerce(copyAttr, !(containerIn.color || - _$fastIsnumeric_139(containerIn.thickness) || - _$fastIsnumeric_139(containerIn.width))); + _$fastIsnumeric_196(containerIn.thickness) || + _$fastIsnumeric_196(containerIn.width))); } } if(!opts.inherit || !containerOut[copyAttr]) { coerce('color', defaultColor); coerce('thickness'); - coerce('width', _$registry_668.traceIs(traceOut, 'gl3d') ? 0 : 4); + coerce('width', _$registry_731.traceIs(traceOut, 'gl3d') ? 0 : 4); } }; @@ -63895,13 +65719,13 @@ var _$defaults_441 = function(traceIn, traceOut, defaultColor, opts) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; -var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { +var _$plot_505 = function plot(traces, plotinfo, transitionOpts) { var isNew; var xa = plotinfo.xaxis; @@ -63925,13 +65749,13 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { } var sparse = ( - _$subtypes_884.hasMarkers(trace) && + _$subtypes_949.hasMarkers(trace) && trace.marker.maxdisplayed > 0 ); if(!yObj.visible && !xObj.visible) d = []; - var errorbars = _$d3_127.select(this).selectAll('g.errorbar') + var errorbars = _$d3_130.select(this).selectAll('g.errorbar') .data(d, keyFunc); errorbars.exit().remove(); @@ -63952,10 +65776,10 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { .style('opacity', 1); } - _$drawing_436.setClipUrl(errorbars, plotinfo.layerClipId); + _$drawing_498.setClipUrl(errorbars, plotinfo.layerClipId); errorbars.each(function(d) { - var errorbar = _$d3_127.select(this); + var errorbar = _$d3_130.select(this); var coords = errorCoords(d, xa, ya); if(sparse && !d.vis) return; @@ -63963,9 +65787,9 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { var path; var yerror = errorbar.select('path.yerror'); - if(yObj.visible && _$fastIsnumeric_139(coords.x) && - _$fastIsnumeric_139(coords.yh) && - _$fastIsnumeric_139(coords.ys)) { + if(yObj.visible && _$fastIsnumeric_196(coords.x) && + _$fastIsnumeric_196(coords.yh) && + _$fastIsnumeric_196(coords.ys)) { var yw = yObj.width; path = 'M' + (coords.x - yw) + ',' + @@ -63993,9 +65817,9 @@ var _$plot_443 = function plot(traces, plotinfo, transitionOpts) { else yerror.remove(); var xerror = errorbar.select('path.xerror'); - if(xObj.visible && _$fastIsnumeric_139(coords.y) && - _$fastIsnumeric_139(coords.xh) && - _$fastIsnumeric_139(coords.xs)) { + if(xObj.visible && _$fastIsnumeric_196(coords.y) && + _$fastIsnumeric_196(coords.xh) && + _$fastIsnumeric_196(coords.xs)) { var xw = (xObj.copy_ystyle ? yObj : xObj).width; path = 'M' + coords.xh + ',' + @@ -64038,7 +65862,7 @@ function errorCoords(d, xa, ya) { // if the shoes go off-scale (ie log scale, error bars past zero) // clip the bar and hide the shoes - if(!_$fastIsnumeric_139(out.ys)) { + if(!_$fastIsnumeric_196(out.ys)) { out.noYS = true; out.ys = ya.c2p(d.ys, true); } @@ -64048,7 +65872,7 @@ function errorCoords(d, xa, ya) { out.xh = xa.c2p(d.xh); out.xs = xa.c2p(d.xs); - if(!_$fastIsnumeric_139(out.xs)) { + if(!_$fastIsnumeric_196(out.xs)) { out.noXS = true; out.xs = xa.c2p(d.xs, true); } @@ -64068,28 +65892,28 @@ function errorCoords(d, xa, ya) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$color_473 = require('../color'); */; -var _$style_444 = function style(traces) { +var _$style_506 = function style(traces) { traces.each(function(d) { var trace = d[0].trace, yObj = trace.error_y || {}, xObj = trace.error_x || {}; - var s = _$d3_127.select(this); + var s = _$d3_130.select(this); s.selectAll('path.yerror') .style('stroke-width', yObj.thickness + 'px') - .call(_$color_411.stroke, yObj.color); + .call(_$color_473.stroke, yObj.color); if(xObj.copy_ystyle) xObj = yObj; s.selectAll('path.xerror') .style('stroke-width', xObj.thickness + 'px') - .call(_$color_411.stroke, xObj.color); + .call(_$color_473.stroke, xObj.color); }); }; @@ -64103,51 +65927,51 @@ var _$style_444 = function style(traces) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var __overrideAll_442 = _$edit_types_569.overrideAll; +/* removed: var _$lib_601 = require('../../lib'); */; +var __overrideAll_504 = _$edit_types_632.overrideAll; -/* removed: var _$attributes_438 = require('./attributes'); */; -/* removed: var _$calc_439 = require('./calc'); */; +/* removed: var _$attributes_500 = require('./attributes'); */; +/* removed: var _$calc_501 = require('./calc'); */; -var __xyAttrs_442 = { - error_x: _$lib_539.extendFlat({}, _$attributes_438), - error_y: _$lib_539.extendFlat({}, _$attributes_438) +var __xyAttrs_504 = { + error_x: _$lib_601.extendFlat({}, _$attributes_500), + error_y: _$lib_601.extendFlat({}, _$attributes_500) }; -delete __xyAttrs_442.error_x.copy_zstyle; -delete __xyAttrs_442.error_y.copy_zstyle; -delete __xyAttrs_442.error_y.copy_ystyle; +delete __xyAttrs_504.error_x.copy_zstyle; +delete __xyAttrs_504.error_y.copy_zstyle; +delete __xyAttrs_504.error_y.copy_ystyle; -var __xyzAttrs_442 = { - error_x: _$lib_539.extendFlat({}, _$attributes_438), - error_y: _$lib_539.extendFlat({}, _$attributes_438), - error_z: _$lib_539.extendFlat({}, _$attributes_438) +var __xyzAttrs_504 = { + error_x: _$lib_601.extendFlat({}, _$attributes_500), + error_y: _$lib_601.extendFlat({}, _$attributes_500), + error_z: _$lib_601.extendFlat({}, _$attributes_500) }; -delete __xyzAttrs_442.error_x.copy_ystyle; -delete __xyzAttrs_442.error_y.copy_ystyle; -delete __xyzAttrs_442.error_z.copy_ystyle; -delete __xyzAttrs_442.error_z.copy_zstyle; +delete __xyzAttrs_504.error_x.copy_ystyle; +delete __xyzAttrs_504.error_y.copy_ystyle; +delete __xyzAttrs_504.error_z.copy_ystyle; +delete __xyzAttrs_504.error_z.copy_zstyle; -var _$errorbars_442 = { +var _$errorbars_504 = { moduleType: 'component', name: 'errorbars', schema: { traces: { - scatter: __xyAttrs_442, - bar: __xyAttrs_442, - histogram: __xyAttrs_442, - scatter3d: __overrideAll_442(__xyzAttrs_442, 'calc', 'nested'), - scattergl: __overrideAll_442(__xyAttrs_442, 'calc', 'nested') + scatter: __xyAttrs_504, + bar: __xyAttrs_504, + histogram: __xyAttrs_504, + scatter3d: __overrideAll_504(__xyzAttrs_504, 'calc', 'nested'), + scattergl: __overrideAll_504(__xyAttrs_504, 'calc', 'nested') } }, - supplyDefaults: _$defaults_441, + supplyDefaults: _$defaults_503, - calc: _$calc_439, + calc: _$calc_501, calcFromTrace: calcFromTrace, - plot: _$plot_443, - style: _$style_444, + plot: _$plot_505, + style: _$style_506, hoverInfo: hoverInfo }; @@ -64167,7 +65991,7 @@ function calcFromTrace(trace, layout) { calcdataMock[0].trace = trace; - _$calc_439({ + _$calc_501({ calcdata: [calcdataMock], _fullLayout: layout }); @@ -64196,10 +66020,10 @@ function hoverInfo(calcPoint, trace, hoverPoint) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var __counterRegex_457 = _$regex_554.counter; -var __domainAttrs_457 = _$domain_610.attributes; -var cartesianIdRegex = _$constants_589.idRegex; +/* removed: var _$lib_601 = require('../../lib'); */; +var __counterRegex_519 = _$regex_617.counter; +var __domainAttrs_519 = _$domain_672.attributes; +var cartesianIdRegex = _$constants_652.idRegex; var gridAttrs = { rows: { @@ -64228,7 +66052,7 @@ var gridAttrs = { valType: 'info_array', freeLength: true, dimensions: 2, - items: {valType: 'enumerated', values: [__counterRegex_457('xy').toString(), ''], editType: 'plot'}, + items: {valType: 'enumerated', values: [__counterRegex_519('xy').toString(), ''], editType: 'plot'}, editType: 'plot', @@ -64273,7 +66097,7 @@ var gridAttrs = { editType: 'plot', }, - domain: __domainAttrs_457({name: 'grid', editType: 'plot', noGridCell: true}, { + domain: __domainAttrs_519({name: 'grid', editType: 'plot', noGridCell: true}, { }), xside: { @@ -64281,7 +66105,7 @@ var gridAttrs = { values: ['bottom', 'bottom plot', 'top plot', 'top'], dflt: 'bottom plot', - editType: 'ticks', + editType: 'plot', }, yside: { @@ -64289,21 +66113,36 @@ var gridAttrs = { values: ['left', 'left plot', 'right plot', 'right'], dflt: 'left plot', - editType: 'ticks', + 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; - if(!gridIn) return; + 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(gridIn.xaxes); - var hasYaxes = Array.isArray(gridIn.yaxes); + var hasXaxes = Array.isArray(xAxes); + var hasYaxes = Array.isArray(yAxes); + var isSplomGenerated = ( + hasXaxes && xAxes !== gridIn.xaxes && + hasYaxes && yAxes !== gridIn.yaxes + ); var dfltRows, dfltColumns; @@ -64312,14 +66151,14 @@ function sizeDefaults(layoutIn, layoutOut) { dfltColumns = gridIn.subplots[0].length; } else { - if(hasYaxes) dfltRows = gridIn.yaxes.length; - if(hasXaxes) dfltColumns = gridIn.xaxes.length; + if(hasYaxes) dfltRows = yAxes.length; + if(hasXaxes) dfltColumns = xAxes.length; } var gridOut = layoutOut.grid = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + return _$lib_601.coerce(gridIn, gridOut, gridAttrs, attr, dflt); } var rows = coerce('rows', dfltRows); @@ -64336,17 +66175,26 @@ function sizeDefaults(layoutIn, layoutOut) { 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) { + dfltSideX = 'bottom'; + dfltSideY = 'left'; + } + gridOut._domains = { - x: fillGridPositions('x', coerce, hasSubplotGrid ? 0.2 : 0.1, columns), - y: fillGridPositions('y', coerce, hasSubplotGrid ? 0.3 : 0.1, rows, reversed) + 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, len, reversed) { +function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) { var dirGap = coerce(axLetter + 'gap', dfltGap); var domain = coerce('domain.' + axLetter); - coerce(axLetter + 'side'); + coerce(axLetter + 'side', dfltSide); var out = new Array(len); var start = domain[0]; @@ -64366,7 +66214,7 @@ function contentDefaults(layoutIn, layoutOut) { // make sure we got to the end of handleGridSizing if(!gridOut || !gridOut._domains) return; - var gridIn = layoutIn.grid; + var gridIn = layoutIn.grid || {}; var subplots = layoutOut._subplots; var hasSubplotGrid = gridOut._hasSubplotGrid; var rows = gridOut.rows; @@ -64412,8 +66260,10 @@ function contentDefaults(layoutIn, layoutOut) { } } else { - gridOut.xaxes = fillGridAxes(gridIn.xaxes, subplots.xaxis, columns, axisMap, 'x'); - gridOut.yaxes = fillGridAxes(gridIn.yaxes, subplots.yaxis, rows, axisMap, 'y'); + 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 = {}; @@ -64527,7 +66377,7 @@ function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { return out; } -var _$grid_457 = { +var _$grid_519 = { moduleType: 'component', name: 'grid', @@ -64550,10 +66400,10 @@ var _$grid_457 = { 'use strict'; -/* removed: var _$constants_589 = require('../../plots/cartesian/constants'); */; +/* removed: var _$constants_652 = require('../../plots/cartesian/constants'); */; -var _$attributes_458 = { +var _$attributes_520 = { _isLinkedToArray: 'image', visible: { @@ -64653,7 +66503,7 @@ var _$attributes_458 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.x.toString() + _$constants_652.idRegex.x.toString() ], dflt: 'paper', @@ -64665,7 +66515,7 @@ var _$attributes_458 = { valType: 'enumerated', values: [ 'paper', - _$constants_589.idRegex.y.toString() + _$constants_652.idRegex.y.toString() ], dflt: 'paper', @@ -64686,8 +66536,8 @@ var _$attributes_458 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$toLogRange_564 = require('../../lib/to_log_range'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$toLogRange_627 = require('../../lib/to_log_range'); */; /* * convertCoords: when converting an axis between log and linear @@ -64707,7 +66557,7 @@ var _$attributes_458 = { * Use this to make the changes as it's aware if any other changes in the * same relayout call should override this conversion. */ -var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { +var _$convertCoords_521 = function convertCoords(gd, ax, newType, doExtra) { ax = ax || {}; var toLog = (newType === 'log') && (ax.type === 'linear'), @@ -64731,7 +66581,7 @@ var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { newSize = null; if(toLog) { - newPos = _$toLogRange_564(currentPos, ax.range); + newPos = _$toLogRange_627(currentPos, ax.range); // this is the inverse of the conversion we do in fromLog below // so that the conversion is reversible (notice the fromLog conversion @@ -64745,11 +66595,11 @@ var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { } // if conversion failed, delete the value so it can get a default later on - if(!_$fastIsnumeric_139(newPos)) { + if(!_$fastIsnumeric_196(newPos)) { newPos = null; newSize = null; } - else if(!_$fastIsnumeric_139(newSize)) newSize = null; + else if(!_$fastIsnumeric_196(newSize)) newSize = null; doExtra(attrPrefix + axLetter, newPos); doExtra(attrPrefix + 'size' + axLetter, newSize); @@ -64767,27 +66617,27 @@ var _$convertCoords_459 = function convertCoords(gd, ax, newType, doExtra) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_458 = require('./attributes'); */; +/* removed: var _$attributes_520 = require('./attributes'); */; var name = 'images'; -var _$supplyLayoutDefaults_460 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_522 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { name: name, handleItemDefaults: imageDefaults }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; function imageDefaults(imageIn, imageOut, fullLayout) { function coerce(attr, dflt) { - return _$lib_539.coerce(imageIn, imageOut, _$attributes_458, attr, dflt); + return _$lib_601.coerce(imageIn, imageOut, _$attributes_520, attr, dflt); } var source = coerce('source'); @@ -64809,9 +66659,9 @@ function imageDefaults(imageIn, imageOut, fullLayout) { for(var i = 0; i < 2; i++) { // 'paper' is the fallback axref var axLetter = axLetters[i], - axRef = _$axes_584.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); + axRef = _$axes_647.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper'); - _$axes_584.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); + _$axes_647.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0); } return imageOut; @@ -64827,12 +66677,12 @@ function imageDefaults(imageIn, imageOut, fullLayout) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; -var _$draw_461 = function draw(gd) { +var _$draw_523 = function draw(gd) { var fullLayout = gd._fullLayout, imageDataAbove = [], imageDataSubplot = {}, @@ -64891,13 +66741,13 @@ var _$draw_461 = function draw(gd) { // Images must be converted to dataURL's for exporting. function setImage(d) { - var thisImage = _$d3_127.select(this); + var thisImage = _$d3_130.select(this); if(this.img && this.img.src === d.source) { return; } - thisImage.attr('xmlns', _$xmlns_namespaces_519.svg); + thisImage.attr('xmlns', _$xmlns_namespaces_580.svg); var imagePromise = new Promise(function(resolve) { @@ -64940,11 +66790,11 @@ var _$draw_461 = function draw(gd) { } function applyAttributes(d) { - var thisImage = _$d3_127.select(this); + var thisImage = _$d3_130.select(this); // Axes if specified - var xa = _$axes_584.getFromId(gd, d.xref), - ya = _$axes_584.getFromId(gd, d.yref); + var xa = _$axes_647.getFromId(gd, d.xref), + ya = _$axes_647.getFromId(gd, d.yref); var size = fullLayout._size, width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w, @@ -64987,7 +66837,7 @@ var _$draw_461 = function draw(gd) { yId = ya ? ya._id : '', clipAxes = xId + yId; - thisImage.call(_$drawing_436.setClipUrl, clipAxes ? + thisImage.call(_$drawing_498.setClipUrl, clipAxes ? ('clip' + fullLayout._uid + clipAxes) : null ); @@ -65047,17 +66897,17 @@ var _$draw_461 = function draw(gd) { 'use strict'; -var _$images_462 = { +var _$images_524 = { moduleType: 'component', name: 'images', - layoutAttributes: _$attributes_458, - supplyLayoutDefaults: _$supplyLayoutDefaults_460, - includeBasePlot: _$makeIncludeComponents_594('images'), + layoutAttributes: _$attributes_520, + supplyLayoutDefaults: _$supplyLayoutDefaults_522, + includeBasePlot: _$makeIncludeComponents_657('images'), - draw: _$draw_461, + draw: _$draw_523, - convertCoords: _$convertCoords_459 + convertCoords: _$convertCoords_521 }; /** @@ -65070,11 +66920,11 @@ var _$images_462 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../color/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; -var _$attributes_464 = { +var _$attributes_526 = { bgcolor: { valType: 'color', @@ -65083,7 +66933,7 @@ var _$attributes_464 = { }, bordercolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'legend', @@ -65096,7 +66946,7 @@ var _$attributes_464 = { editType: 'legend', }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'legend', }), @@ -65161,7 +67011,7 @@ var _$attributes_464 = { editType: 'legend' }; -var _$helpers_470 = {}; +var _$helpers_532 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -65173,7 +67023,7 @@ var _$helpers_470 = {}; 'use strict'; -_$helpers_470.legendGetsTrace = function legendGetsTrace(trace) { +_$helpers_532.legendGetsTrace = function legendGetsTrace(trace) { // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)? // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted. @@ -65183,15 +67033,15 @@ _$helpers_470.legendGetsTrace = function legendGetsTrace(trace) { return trace.visible && (trace.showlegend !== undefined); }; -_$helpers_470.isGrouped = function isGrouped(legendLayout) { +_$helpers_532.isGrouped = function isGrouped(legendLayout) { return (legendLayout.traceorder || '').indexOf('grouped') !== -1; }; -_$helpers_470.isVertical = function isVertical(legendLayout) { +_$helpers_532.isVertical = function isVertical(legendLayout) { return legendLayout.orientation !== 'h'; }; -_$helpers_470.isReversed = function isReversed(legendLayout) { +_$helpers_532.isReversed = function isReversed(legendLayout) { return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; @@ -65206,15 +67056,15 @@ _$helpers_470.isReversed = function isReversed(legendLayout) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$attributes_464 = require('./attributes'); */; -/* removed: var _$layout_attributes_638 = require('../../plots/layout_attributes'); */; -/* removed: var _$helpers_470 = require('./helpers'); */; +/* removed: var _$attributes_526 = require('./attributes'); */; +/* removed: var _$layout_attributes_700 = require('../../plots/layout_attributes'); */; +/* removed: var _$helpers_532 = require('./helpers'); */; -var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData) { +var _$legendDefaults_528 = function legendDefaults(layoutIn, layoutOut, fullData) { var containerIn = layoutIn.legend || {}; var containerOut = {}; @@ -65226,30 +67076,30 @@ var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData for(var i = 0; i < fullData.length; i++) { var trace = fullData[i]; - if(_$helpers_470.legendGetsTrace(trace)) { + if(_$helpers_532.legendGetsTrace(trace)) { visibleTraces++; // always show the legend by default if there's a pie - if(_$registry_668.traceIs(trace, 'pie')) visibleTraces++; + if(_$registry_731.traceIs(trace, 'pie')) visibleTraces++; } - if((_$registry_668.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || + if((_$registry_731.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') || ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) { - defaultOrder = _$helpers_470.isGrouped({traceorder: defaultOrder}) ? + defaultOrder = _$helpers_532.isGrouped({traceorder: defaultOrder}) ? 'grouped+reversed' : 'reversed'; } if(trace.legendgroup !== undefined && trace.legendgroup !== '') { - defaultOrder = _$helpers_470.isReversed({traceorder: defaultOrder}) ? + defaultOrder = _$helpers_532.isReversed({traceorder: defaultOrder}) ? 'reversed+grouped' : 'grouped'; } } function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$attributes_464, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$attributes_526, attr, dflt); } - var showLegend = _$lib_539.coerce(layoutIn, layoutOut, - _$layout_attributes_638, 'showlegend', visibleTraces > 1); + var showLegend = _$lib_601.coerce(layoutIn, layoutOut, + _$layout_attributes_700, 'showlegend', visibleTraces > 1); if(showLegend === false) return; @@ -65258,7 +67108,7 @@ var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); - _$lib_539.coerceFont(coerce, 'font', layoutOut.font); + _$lib_601.coerceFont(coerce, 'font', layoutOut.font); coerce('orientation'); if(containerOut.orientation === 'h') { @@ -65278,16 +67128,16 @@ var _$legendDefaults_466 = function legendDefaults(layoutIn, layoutOut, fullData } coerce('traceorder', defaultOrder); - if(_$helpers_470.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); + if(_$helpers_532.isGrouped(layoutOut.legend)) coerce('tracegroupgap'); coerce('x', defaultX); coerce('xanchor', defaultXAnchor); coerce('y', defaultY); coerce('yanchor', defaultYAnchor); - _$lib_539.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_601.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -var _$anchor_utils_463 = {}; +var _$anchor_utils_525 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -65308,28 +67158,28 @@ var _$anchor_utils_463 = {}; * - values > 2/3 align the right at that fraction. */ -_$anchor_utils_463.isRightAnchor = function isRightAnchor(opts) { +_$anchor_utils_525.isRightAnchor = function isRightAnchor(opts) { return ( opts.xanchor === 'right' || (opts.xanchor === 'auto' && opts.x >= 2 / 3) ); }; -_$anchor_utils_463.isCenterAnchor = function isCenterAnchor(opts) { +_$anchor_utils_525.isCenterAnchor = function isCenterAnchor(opts) { return ( opts.xanchor === 'center' || (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3) ); }; -_$anchor_utils_463.isBottomAnchor = function isBottomAnchor(opts) { +_$anchor_utils_525.isBottomAnchor = function isBottomAnchor(opts) { return ( opts.yanchor === 'bottom' || (opts.yanchor === 'auto' && opts.y <= 1 / 3) ); }; -_$anchor_utils_463.isMiddleAnchor = function isMiddleAnchor(opts) { +_$anchor_utils_525.isMiddleAnchor = function isMiddleAnchor(opts) { return ( opts.yanchor === 'middle' || (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3) @@ -65346,7 +67196,7 @@ _$anchor_utils_463.isMiddleAnchor = function isMiddleAnchor(opts) { 'use strict'; -var _$constants_465 = { +var _$constants_527 = { scrollBarWidth: 6, scrollBarMinHeight: 20, scrollBarColor: '#808BA4', @@ -65364,11 +67214,11 @@ var _$constants_465 = { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$helpers_470 = require('./helpers'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$helpers_532 = require('./helpers'); */; -var _$getLegendData_468 = function getLegendData(calcdata, opts) { +var _$getLegendData_530 = function getLegendData(calcdata, opts) { var lgroupToTraces = {}, lgroups = [], hasOneNonBlankGroup = false, @@ -65379,7 +67229,7 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { function addOneItem(legendGroup, legendItem) { // each '' legend group is treated as a separate group - if(legendGroup === '' || !_$helpers_470.isGrouped(opts)) { + if(legendGroup === '' || !_$helpers_532.isGrouped(opts)) { var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups? lgroups.push(uniqueGroup); @@ -65401,9 +67251,9 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { trace = cd0.trace, lgroup = trace.legendgroup; - if(!_$helpers_470.legendGetsTrace(trace) || !trace.showlegend) continue; + if(!_$helpers_532.legendGetsTrace(trace) || !trace.showlegend) continue; - if(_$registry_668.traceIs(trace, 'pie')) { + if(_$registry_731.traceIs(trace, 'pie')) { if(!slicesShown[lgroup]) slicesShown[lgroup] = {}; for(j = 0; j < cd.length; j++) { @@ -65433,12 +67283,12 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { ltraces, legendData; - if(hasOneNonBlankGroup && _$helpers_470.isGrouped(opts)) { + if(hasOneNonBlankGroup && _$helpers_532.isGrouped(opts)) { legendData = new Array(lgroupsLength); for(i = 0; i < lgroupsLength; i++) { ltraces = lgroupToTraces[lgroups[i]]; - legendData[i] = _$helpers_470.isReversed(opts) ? ltraces.reverse() : ltraces; + legendData[i] = _$helpers_532.isReversed(opts) ? ltraces.reverse() : ltraces; } } else { @@ -65447,7 +67297,7 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { for(i = 0; i < lgroupsLength; i++) { ltraces = lgroupToTraces[lgroups[i]][0]; - legendData[0][_$helpers_470.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; + legendData[0][_$helpers_532.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces; } lgroupsLength = 1; } @@ -65467,12 +67317,12 @@ var _$getLegendData_468 = function getLegendData(calcdata, opts) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; var SHOWISOLATETIP = true; -var _$handleClick_469 = function handleClick(g, gd, numClicks) { +var _$handleClick_531 = function handleClick(g, gd, numClicks) { if(gd._dragged || gd._editing) return; var hiddenSlices = gd._fullLayout.hiddenlabels ? @@ -65509,12 +67359,12 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { function setVisibility(fullTrace, visibility) { var fullInput = fullTrace._fullInput; - if(_$registry_668.hasTransform(fullInput, 'groupby')) { + if(_$registry_731.hasTransform(fullInput, 'groupby')) { var kcont = carrs[fullInput.index]; if(!kcont) { - var groupbyIndices = _$registry_668.getTransformIndices(fullInput, 'groupby'); + var groupbyIndices = _$registry_731.getTransformIndices(fullInput, 'groupby'); var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont = _$lib_539.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); + kcont = _$lib_601.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible'); carrs[fullInput.index] = kcont; } @@ -65545,13 +67395,13 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { } if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) { - _$lib_539.notifier(_$lib_539._(gd, 'Double-click on legend to isolate one trace'), 'long'); + _$lib_601.notifier(_$lib_601._(gd, 'Double-click on legend to isolate one trace'), 'long'); SHOWISOLATETIP = false; } else { SHOWISOLATETIP = false; } - if(_$registry_668.traceIs(fullTrace, 'pie')) { + if(_$registry_731.traceIs(fullTrace, 'pie')) { var thisLabel = legendItem.label, thisLabelIndex = hiddenSlices.indexOf(thisLabel); @@ -65570,7 +67420,7 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { } } - _$registry_668.call('relayout', gd, 'hiddenlabels', hiddenSlices); + _$registry_731.call('relayout', gd, 'hiddenlabels', hiddenSlices); } else { var hasLegendgroup = legendgroup && legendgroup.length; var traceIndicesInGroup = []; @@ -65620,7 +67470,7 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup); - if(!isInGroup && fullData[i].visible === true && !_$registry_668.traceIs(fullData[i], 'notLegendIsolatable')) { + if(!isInGroup && fullData[i].visible === true && !_$registry_731.traceIs(fullData[i], 'notLegendIsolatable')) { isIsolated = false; break; } @@ -65630,7 +67480,7 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { // False is sticky; we don't change it. if(fullData[i].visible === false) continue; - if(_$registry_668.traceIs(fullData[i], 'notLegendIsolatable')) { + if(_$registry_731.traceIs(fullData[i], 'notLegendIsolatable')) { continue; } @@ -65676,11 +67526,11 @@ var _$handleClick_469 = function handleClick(g, gd, numClicks) { } } - _$registry_668.call('restyle', gd, attrUpdate, attrIndices); + _$registry_731.call('restyle', gd, attrUpdate, attrIndices); } }; -var _$helpers_842 = {}; +var _$helpers_907 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -65691,25 +67541,25 @@ var _$helpers_842 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -_$helpers_842.formatPiePercent = function formatPiePercent(v, separators) { +_$helpers_907.formatPiePercent = function formatPiePercent(v, separators) { var vRounded = (v * 100).toPrecision(3); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_539.numSeparate(vRounded, separators) + '%'; + return _$lib_601.numSeparate(vRounded, separators) + '%'; }; -_$helpers_842.formatPieValue = function formatPieValue(v, separators) { +_$helpers_907.formatPieValue = function formatPieValue(v, separators) { var vRounded = v.toPrecision(10); if(vRounded.lastIndexOf('.') !== -1) { vRounded = vRounded.replace(/[.]?0+$/, ''); } - return _$lib_539.numSeparate(vRounded, separators); + return _$lib_601.numSeparate(vRounded, separators); }; -_$helpers_842.getFirstFilled = function getFirstFilled(array, indices) { +_$helpers_907.getFirstFilled = function getFirstFilled(array, indices) { if(!Array.isArray(array)) return; for(var i = 0; i < indices.length; i++) { var v = array[indices[i]]; @@ -65717,8 +67567,8 @@ _$helpers_842.getFirstFilled = function getFirstFilled(array, indices) { } }; -_$helpers_842.castOption = function castOption(item, indices) { - if(Array.isArray(item)) return _$helpers_842.getFirstFilled(item, indices); +_$helpers_907.castOption = function castOption(item, indices) { + if(Array.isArray(item)) return _$helpers_907.getFirstFilled(item, indices); else if(item) return item; }; @@ -65732,17 +67582,17 @@ _$helpers_842.castOption = function castOption(item, indices) { 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -var castOption = _$helpers_842.castOption; +/* removed: var _$color_473 = require('../../components/color'); */; +var castOption = _$helpers_907.castOption; -var _$styleOne_848 = function styleOne(s, pt, trace) { +var _$styleOne_913 = function styleOne(s, pt, trace) { var line = trace.marker.line; - var lineColor = castOption(line.color, pt.pts) || _$color_411.defaultLine; + var lineColor = castOption(line.color, pt.pts) || _$color_473.defaultLine; var lineWidth = castOption(line.width, pt.pts) || 0; s.style({'stroke-width': lineWidth}) - .call(_$color_411.fill, pt.color) - .call(_$color_411.stroke, lineColor); + .call(_$color_473.fill, pt.color) + .call(_$color_473.stroke, lineColor); }; /** @@ -65753,28 +67603,23 @@ var _$styleOne_848 = function styleOne(s, pt, trace) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; - -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$styleOne_848 = require('../../traces/pie/style_one'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$styleOne_913 = require('../../traces/pie/style_one'); */; -var _$style_472 = function style(s, gd) { +var _$style_534 = function style(s, gd) { s.each(function(d) { - var traceGroup = _$d3_127.select(this); + var traceGroup = _$d3_130.select(this); - var layers = traceGroup.selectAll('g.layers') - .data([0]); - layers.enter().append('g') - .classed('layers', true); + var layers = _$lib_601.ensureSingle(traceGroup, 'g', 'layers'); layers.style('opacity', d[0].trace.opacity); var fill = layers @@ -65804,12 +67649,14 @@ var _$style_472 = function style(s, gd) { .each(styleBoxes) .each(stylePies) .each(styleLines) - .each(stylePoints); + .each(stylePoints) + .each(styleCandles) + .each(styleOHLC); function styleLines(d) { var trace = d[0].trace; var showFill = trace.visible && trace.fill && trace.fill !== 'none'; - var showLine = _$subtypes_884.hasLines(trace); + var showLine = _$subtypes_949.hasLines(trace); var contours = trace.contours; if(contours && contours.type === 'constraint') { @@ -65817,27 +67664,27 @@ var _$style_472 = function style(s, gd) { showFill = contours._operation !== '='; } - var fill = _$d3_127.select(this).select('.legendfill').selectAll('path') + var fill = _$d3_130.select(this).select('.legendfill').selectAll('path') .data(showFill ? [d] : []); fill.enter().append('path').classed('js-fill', true); fill.exit().remove(); fill.attr('d', 'M5,0h30v6h-30z') - .call(_$drawing_436.fillGroupStyle); + .call(_$drawing_498.fillGroupStyle); - var line = _$d3_127.select(this).select('.legendlines').selectAll('path') + var line = _$d3_130.select(this).select('.legendlines').selectAll('path') .data(showLine ? [d] : []); line.enter().append('path').classed('js-line', true) .attr('d', 'M5,0h30'); line.exit().remove(); - line.call(_$drawing_436.lineGroupStyle); + line.call(_$drawing_498.lineGroupStyle); } function stylePoints(d) { var d0 = d[0], trace = d0.trace, - showMarkers = _$subtypes_884.hasMarkers(trace), - showText = _$subtypes_884.hasText(trace), - showLines = _$subtypes_884.hasLines(trace); + showMarkers = _$subtypes_949.hasMarkers(trace), + showText = _$subtypes_949.hasText(trace), + showLines = _$subtypes_949.hasLines(trace); var dMod, tMod; @@ -65845,7 +67692,7 @@ var _$style_472 = function style(s, gd) { // use d0.trace to infer arrayOk attributes function boundVal(attrIn, arrayToValFn, bounds) { - var valIn = _$lib_539.nestedProperty(trace, attrIn).get(), + var valIn = _$lib_601.nestedProperty(trace, attrIn).get(), valToBound = (Array.isArray(valIn) && arrayToValFn) ? arrayToValFn(valIn) : valIn; @@ -65865,10 +67712,10 @@ var _$style_472 = function style(s, gd) { if(showMarkers) { dEdit.mc = boundVal('marker.color', pickFirst); - dEdit.mo = boundVal('marker.opacity', _$lib_539.mean, [0.2, 1]); - dEdit.ms = boundVal('marker.size', _$lib_539.mean, [2, 16]); + dEdit.mo = boundVal('marker.opacity', _$lib_601.mean, [0.2, 1]); + dEdit.ms = boundVal('marker.size', _$lib_601.mean, [2, 16]); dEdit.mlc = boundVal('marker.line.color', pickFirst); - dEdit.mlw = boundVal('marker.line.width', _$lib_539.mean, [0, 5]); + dEdit.mlw = boundVal('marker.line.width', _$lib_601.mean, [0, 5]); tEdit.marker = { sizeref: 1, sizemin: 1, @@ -65890,18 +67737,18 @@ var _$style_472 = function style(s, gd) { dEdit.tf = boundVal('textfont.family', pickFirst); } - dMod = [_$lib_539.minExtend(d0, dEdit)]; - tMod = _$lib_539.minExtend(trace, tEdit); + dMod = [_$lib_601.minExtend(d0, dEdit)]; + tMod = _$lib_601.minExtend(trace, tEdit); } - var ptgroup = _$d3_127.select(this).select('g.legendpoints'); + var ptgroup = _$d3_130.select(this).select('g.legendpoints'); var pts = ptgroup.selectAll('path.scatterpts') .data(showMarkers ? dMod : []); pts.enter().append('path').classed('scatterpts', true) .attr('transform', 'translate(20,0)'); pts.exit().remove(); - pts.call(_$drawing_436.pointStyle, tMod, gd); + pts.call(_$drawing_498.pointStyle, tMod, gd); // 'mrc' is set in pointStyle and used in textPointStyle: // constrain it here @@ -65913,39 +67760,39 @@ var _$style_472 = function style(s, gd) { .append('g').classed('pointtext', true) .append('text').attr('transform', 'translate(20,0)'); txt.exit().remove(); - txt.selectAll('text').call(_$drawing_436.textPointStyle, tMod, gd); + txt.selectAll('text').call(_$drawing_498.textPointStyle, tMod, gd); } function styleBars(d) { var trace = d[0].trace, marker = trace.marker || {}, markerLine = marker.line || {}, - barpath = _$d3_127.select(this).select('g.legendpoints') + barpath = _$d3_130.select(this).select('g.legendpoints') .selectAll('path.legendbar') - .data(_$registry_668.traceIs(trace, 'bar') ? [d] : []); + .data(_$registry_731.traceIs(trace, 'bar') ? [d] : []); barpath.enter().append('path').classed('legendbar', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); barpath.exit().remove(); barpath.each(function(d) { - var p = _$d3_127.select(this), + var p = _$d3_130.select(this), d0 = d[0], w = (d0.mlw + 1 || markerLine.width + 1) - 1; p.style('stroke-width', w + 'px') - .call(_$color_411.fill, d0.mc || marker.color); + .call(_$color_473.fill, d0.mc || marker.color); if(w) { - p.call(_$color_411.stroke, d0.mlc || markerLine.color); + p.call(_$color_473.stroke, d0.mlc || markerLine.color); } }); } function styleBoxes(d) { var trace = d[0].trace, - pts = _$d3_127.select(this).select('g.legendpoints') + pts = _$d3_130.select(this).select('g.legendpoints') .selectAll('path.legendbox') - .data(_$registry_668.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); + .data(_$registry_731.traceIs(trace, 'box-violin') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendbox', true) // if we want the median bar, prepend M6,0H-6 .attr('d', 'M6,6H-6V-6H6Z') @@ -65953,28 +67800,82 @@ var _$style_472 = function style(s, gd) { pts.exit().remove(); pts.each(function() { var w = trace.line.width, - p = _$d3_127.select(this); + p = _$d3_130.select(this); p.style('stroke-width', w + 'px') - .call(_$color_411.fill, trace.fillcolor); + .call(_$color_473.fill, trace.fillcolor); if(w) { - p.call(_$color_411.stroke, trace.line.color); + _$color_473.stroke(p, trace.line.color); + } + }); + } + + function styleCandles(d) { + var trace = d[0].trace, + pts = _$d3_130.select(this).select('g.legendpoints') + .selectAll('path.legendcandle') + .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendcandle', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing + return 'M15,0H8M8,-6V6H-8Z'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_130.select(this); + + p.style('stroke-width', w + 'px') + .call(_$color_473.fill, container.fillcolor); + + if(w) { + _$color_473.stroke(p, container.line.color); + } + }); + } + + function styleOHLC(d) { + var trace = d[0].trace, + pts = _$d3_130.select(this).select('g.legendpoints') + .selectAll('path.legendohlc') + .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []); + pts.enter().append('path').classed('legendohlc', true) + .attr('d', function(_, i) { + if(i) return 'M-15,0H0M-8,-6V0'; // increasing + return 'M15,0H0M8,6V0'; // decreasing + }) + .attr('transform', 'translate(20,0)') + .style('stroke-miterlimit', 1); + pts.exit().remove(); + pts.each(function(_, i) { + var container = trace[i ? 'increasing' : 'decreasing']; + var w = container.line.width, + p = _$d3_130.select(this); + + p.style('fill', 'none') + .call(_$drawing_498.dashLine, container.line.dash, w); + + if(w) { + _$color_473.stroke(p, container.line.color); } }); } function stylePies(d) { var trace = d[0].trace, - pts = _$d3_127.select(this).select('g.legendpoints') + pts = _$d3_130.select(this).select('g.legendpoints') .selectAll('path.legendpie') - .data(_$registry_668.traceIs(trace, 'pie') && trace.visible ? [d] : []); + .data(_$registry_731.traceIs(trace, 'pie') && trace.visible ? [d] : []); pts.enter().append('path').classed('legendpie', true) .attr('d', 'M6,6H-6V-6H6Z') .attr('transform', 'translate(20,0)'); pts.exit().remove(); - if(pts.size()) pts.call(_$styleOne_848, d[0], trace); + if(pts.size()) pts.call(_$styleOne_913, d[0], trace); } }; @@ -65988,32 +67889,32 @@ var _$style_472 = function style(s, gd) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$handleClick_469 = require('./handle_click'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$handleClick_531 = require('./handle_click'); */; -/* removed: var _$constants_465 = require('./constants'); */; -/* removed: var _$interactions_516 = require('../../constants/interactions'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_467 = _$alignment_511.LINE_SPACING; -var FROM_TL = _$alignment_511.FROM_TL; -var FROM_BR = _$alignment_511.FROM_BR; +/* removed: var _$constants_527 = require('./constants'); */; +/* removed: var _$interactions_577 = require('../../constants/interactions'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_529 = _$alignment_573.LINE_SPACING; +var __FROM_TL_529 = _$alignment_573.FROM_TL; +var FROM_BR = _$alignment_573.FROM_BR; -/* removed: var _$getLegendData_468 = require('./get_legend_data'); */; -/* removed: var _$style_472 = require('./style'); */; -/* removed: var _$helpers_470 = require('./helpers'); */; -/* removed: var _$anchor_utils_463 = require('./anchor_utils'); */; +/* removed: var _$getLegendData_530 = require('./get_legend_data'); */; +/* removed: var _$style_534 = require('./style'); */; +/* removed: var _$helpers_532 = require('./helpers'); */; +/* removed: var _$anchor_utils_525 = require('./anchor_utils'); */; -var DBLCLICKDELAY = _$interactions_516.DBLCLICKDELAY; +var DBLCLICKDELAY = _$interactions_577.DBLCLICKDELAY; -var _$draw_467 = function draw(gd) { +var _$draw_529 = function draw(gd) { var fullLayout = gd._fullLayout; var clipId = 'legend' + fullLayout._uid; @@ -66022,63 +67923,46 @@ var _$draw_467 = function draw(gd) { if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; var opts = fullLayout.legend, - legendData = fullLayout.showlegend && _$getLegendData_468(gd.calcdata, opts), + legendData = fullLayout.showlegend && _$getLegendData_530(gd.calcdata, opts), hiddenSlices = fullLayout.hiddenlabels || []; if(!fullLayout.showlegend || !legendData.length) { fullLayout._infolayer.selectAll('.legend').remove(); fullLayout._topdefs.select('#' + clipId).remove(); - _$plots_647.autoMargin(gd, 'legend'); + _$plots_709.autoMargin(gd, 'legend'); return; } - var legend = fullLayout._infolayer.selectAll('g.legend') - .data([0]); - - legend.enter().append('g') - .attr({ - 'class': 'legend', - 'pointer-events': 'all' - }); - - var clipPath = fullLayout._topdefs.selectAll('#' + clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', clipId) - .append('rect'); + var firstRender = false; + var legend = _$lib_601.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) { + s.attr('pointer-events', 'all'); + firstRender = true; + }); - var bg = legend.selectAll('rect.bg') - .data([0]); + var clipPath = _$lib_601.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) { + s.append('rect'); + }); - bg.enter().append('rect').attr({ - 'class': 'bg', - 'shape-rendering': 'crispEdges' + var bg = _$lib_601.ensureSingle(legend, 'rect', 'bg', function(s) { + s.attr('shape-rendering', 'crispEdges'); }); - bg.call(_$color_411.stroke, opts.bordercolor) - .call(_$color_411.fill, opts.bgcolor) + bg.call(_$color_473.stroke, opts.bordercolor) + .call(_$color_473.fill, opts.bgcolor) .style('stroke-width', opts.borderwidth + 'px'); - var scrollBox = legend.selectAll('g.scrollbox') - .data([0]); + var scrollBox = _$lib_601.ensureSingle(legend, 'g', 'scrollbox'); - scrollBox.enter().append('g') - .attr('class', 'scrollbox'); - - var scrollBar = legend.selectAll('rect.scrollbar') - .data([0]); - - scrollBar.enter().append('rect') - .attr({ - 'class': 'scrollbar', + var scrollBar = _$lib_601.ensureSingle(legend, 'rect', 'scrollbar', function(s) { + s.attr({ rx: 20, ry: 3, width: 0, height: 0 }) - .call(_$color_411.fill, '#808BA4'); + .call(_$color_473.fill, '#808BA4'); + }); var groups = scrollBox.selectAll('g.groups') .data(legendData); @@ -66089,27 +67973,26 @@ var _$draw_467 = function draw(gd) { groups.exit().remove(); var traces = groups.selectAll('g.traces') - .data(_$lib_539.identity); + .data(_$lib_601.identity); traces.enter().append('g').attr('class', 'traces'); traces.exit().remove(); - traces.call(_$style_472, gd) + traces.call(_$style_534, gd) .style('opacity', function(d) { var trace = d[0].trace; - if(_$registry_668.traceIs(trace, 'pie')) { + if(_$registry_731.traceIs(trace, 'pie')) { return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; } else { return trace.visible === 'legendonly' ? 0.5 : 1; } }) .each(function() { - _$d3_127.select(this) + _$d3_130.select(this) .call(drawTexts, gd) .call(setupTraceToggle, gd); }); - var firstRender = legend.enter().size() !== 0; if(firstRender) { computeLegendDimensions(gd, groups, traces); expandMargin(gd); @@ -66138,17 +68021,17 @@ var _$draw_467 = function draw(gd) { lx = gs.l + gs.w * opts.x, ly = gs.t + gs.h * (1 - opts.y); - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { lx -= opts._width; } - else if(_$anchor_utils_463.isCenterAnchor(opts)) { + else if(_$anchor_utils_525.isCenterAnchor(opts)) { lx -= opts._width / 2; } - if(_$anchor_utils_463.isBottomAnchor(opts)) { + if(_$anchor_utils_525.isBottomAnchor(opts)) { ly -= opts._height; } - else if(_$anchor_utils_463.isMiddleAnchor(opts)) { + else if(_$anchor_utils_525.isMiddleAnchor(opts)) { ly -= opts._height / 2; } @@ -66184,7 +68067,7 @@ var _$draw_467 = function draw(gd) { // Set size and position of all the elements that make up a legend: // legend, background and border, scroll box and scroll bar - _$drawing_436.setTranslate(legend, lx, ly); + _$drawing_498.setTranslate(legend, lx, ly); // to be safe, remove previous listeners scrollBar.on('.drag', null); @@ -66199,7 +68082,7 @@ var _$draw_467 = function draw(gd) { y: opts.borderwidth / 2 }); - _$drawing_436.setTranslate(scrollBox, 0, 0); + _$drawing_498.setTranslate(scrollBox, 0, 0); clipPath.select('rect').attr({ width: legendWidth - 2 * opts.borderwidth, @@ -66208,17 +68091,17 @@ var _$draw_467 = function draw(gd) { y: opts.borderwidth }); - _$drawing_436.setClipUrl(scrollBox, clipId); + _$drawing_498.setClipUrl(scrollBox, clipId); - _$drawing_436.setRect(scrollBar, 0, 0, 0, 0); + _$drawing_498.setRect(scrollBar, 0, 0, 0, 0); delete opts._scrollY; } else { - var scrollBarHeight = Math.max(_$constants_465.scrollBarMinHeight, + var scrollBarHeight = Math.max(_$constants_527.scrollBarMinHeight, legendHeight * legendHeight / opts._height); var scrollBarYMax = legendHeight - scrollBarHeight - - 2 * _$constants_465.scrollBarMargin; + 2 * _$constants_527.scrollBarMargin; var scrollBoxYMax = opts._height - legendHeight; var scrollRatio = scrollBarYMax / scrollBoxYMax; @@ -66229,8 +68112,8 @@ var _$draw_467 = function draw(gd) { bg.attr({ width: legendWidth - 2 * opts.borderwidth + - _$constants_465.scrollBarWidth + - _$constants_465.scrollBarMargin, + _$constants_527.scrollBarWidth + + _$constants_527.scrollBarMargin, height: legendHeight - opts.borderwidth, x: opts.borderwidth / 2, y: opts.borderwidth / 2 @@ -66239,40 +68122,40 @@ var _$draw_467 = function draw(gd) { clipPath.select('rect').attr({ width: legendWidth - 2 * opts.borderwidth + - _$constants_465.scrollBarWidth + - _$constants_465.scrollBarMargin, + _$constants_527.scrollBarWidth + + _$constants_527.scrollBarMargin, height: legendHeight - 2 * opts.borderwidth, x: opts.borderwidth, y: opts.borderwidth + scrollBoxY }); - _$drawing_436.setClipUrl(scrollBox, clipId); + _$drawing_498.setClipUrl(scrollBox, clipId); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); legend.on('wheel', function() { - scrollBoxY = _$lib_539.constrain( + scrollBoxY = _$lib_601.constrain( opts._scrollY + - _$d3_127.event.deltaY / scrollBarYMax * scrollBoxYMax, + _$d3_130.event.deltaY / scrollBarYMax * scrollBoxYMax, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - _$d3_127.event.preventDefault(); + _$d3_130.event.preventDefault(); } }); var eventY0, scrollBoxY0; - var drag = _$d3_127.behavior.drag() + var drag = _$d3_130.behavior.drag() .on('dragstart', function() { - eventY0 = _$d3_127.event.sourceEvent.clientY; + eventY0 = _$d3_130.event.sourceEvent.clientY; scrollBoxY0 = scrollBoxY; }) .on('drag', function() { - var e = _$d3_127.event.sourceEvent; + var e = _$d3_130.event.sourceEvent; if(e.buttons === 2 || e.ctrlKey) return; - scrollBoxY = _$lib_539.constrain( + scrollBoxY = _$lib_601.constrain( (e.clientY - eventY0) / scrollRatio + scrollBoxY0, 0, scrollBoxYMax); scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); @@ -66284,13 +68167,13 @@ var _$draw_467 = function draw(gd) { function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) { opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY; - _$drawing_436.setTranslate(scrollBox, 0, -scrollBoxY); + _$drawing_498.setTranslate(scrollBox, 0, -scrollBoxY); - _$drawing_436.setRect( + _$drawing_498.setRect( scrollBar, legendWidth, - _$constants_465.scrollBarMargin + scrollBoxY * scrollRatio, - _$constants_465.scrollBarWidth, + _$constants_527.scrollBarMargin + scrollBoxY * scrollRatio, + _$constants_527.scrollBarWidth, scrollBarHeight ); clipPath.select('rect').attr({ @@ -66303,11 +68186,11 @@ var _$draw_467 = function draw(gd) { legend.classed('cursor-move', true); - _$dragelement_433.init({ + _$dragelement_495.init({ element: legend.node(), gd: gd, prepFn: function() { - var transform = _$drawing_436.getTranslate(legend); + var transform = _$drawing_498.getTranslate(legend); x0 = transform.x; y0 = transform.y; @@ -66316,14 +68199,14 @@ var _$draw_467 = function draw(gd) { var newX = x0 + dx, newY = y0 + dy; - _$drawing_436.setTranslate(legend, newX, newY); + _$drawing_498.setTranslate(legend, newX, newY); - xf = _$dragelement_433.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); - yf = _$dragelement_433.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); + xf = _$dragelement_495.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor); + yf = _$dragelement_495.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor); }, doneFn: function() { if(xf !== undefined && yf !== undefined) { - _$registry_668.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); + _$registry_731.call('relayout', gd, {'legend.x': xf, 'legend.y': yf}); } }, clickFn: function(numClicks, e) { @@ -66336,13 +68219,13 @@ var _$draw_467 = function draw(gd) { if(clickedTrace.size() > 0) { if(numClicks === 1) { legend._clickTimeout = setTimeout(function() { - _$handleClick_469(clickedTrace, gd, numClicks); + _$handleClick_531(clickedTrace, gd, numClicks); }, DBLCLICKDELAY); } else if(numClicks === 2) { if(legend._clickTimeout) { clearTimeout(legend._clickTimeout); } - _$handleClick_469(clickedTrace, gd, numClicks); + _$handleClick_531(clickedTrace, gd, numClicks); } } } @@ -66354,28 +68237,25 @@ function drawTexts(g, gd) { var legendItem = g.data()[0][0], fullLayout = gd._fullLayout, trace = legendItem.trace, - isPie = _$registry_668.traceIs(trace, 'pie'), + isPie = _$registry_731.traceIs(trace, 'pie'), traceIndex = trace.index, name = isPie ? legendItem.label : trace.name; - var text = g.selectAll('text.legendtext') - .data([0]); - - text.enter().append('text').classed('legendtext', true); + var text = _$lib_601.ensureSingle(g, 'text', 'legendtext'); text.attr('text-anchor', 'start') .classed('user-select-none', true) - .call(_$drawing_436.font, fullLayout.legend.font) + .call(_$drawing_498.font, fullLayout.legend.font) .text(name); function textLayout(s) { - _$svg_text_utils_562.convertToTspans(s, gd, function() { + _$svg_text_utils_625.convertToTspans(s, gd, function() { computeTextDimensions(g, gd); }); } if(gd._context.edits.legendText && !isPie) { - text.call(_$svg_text_utils_562.makeEditable, {gd: gd}) + text.call(_$svg_text_utils_625.makeEditable, {gd: gd}) .call(textLayout) .on('edit', function(text) { this.text(text) @@ -66385,24 +68265,14 @@ function drawTexts(g, gd) { if(!this.text()) text = ' \u0020\u0020 '; - var transforms, direction; var fullInput = legendItem.trace._fullInput || {}; var update = {}; - // N.B. this block isn't super clean, - // is unfortunately untested at the moment, - // and only works for for 'ohlc' and 'candlestick', - // but should be generalized for other one-to-many transforms - if(['ohlc', 'candlestick'].indexOf(fullInput.type) !== -1) { - transforms = legendItem.trace.transforms; - direction = transforms[transforms.length - 1].direction; - - update[direction + '.name'] = text; - } else if(_$registry_668.hasTransform(fullInput, 'groupby')) { - var groupbyIndices = _$registry_668.getTransformIndices(fullInput, 'groupby'); + if(_$registry_731.hasTransform(fullInput, 'groupby')) { + var groupbyIndices = _$registry_731.getTransformIndices(fullInput, 'groupby'); var index = groupbyIndices[groupbyIndices.length - 1]; - var kcont = _$lib_539.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); + var kcont = _$lib_601.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name'); if(origText === '') { kcont.remove(legendItem.trace._group); @@ -66415,7 +68285,7 @@ function drawTexts(g, gd) { update.name = text; } - return _$registry_668.call('restyle', gd, update, traceIndex); + return _$registry_731.call('restyle', gd, update, traceIndex); }); } else { textLayout(text); @@ -66426,15 +68296,11 @@ function setupTraceToggle(g, gd) { var newMouseDownTime, numClicks = 1; - var traceToggle = g.selectAll('rect') - .data([0]); - - traceToggle.enter().append('rect') - .classed('legendtoggle', true) - .style('cursor', 'pointer') - .attr('pointer-events', 'all') - .call(_$color_411.fill, 'rgba(0,0,0,0)'); - + var traceToggle = _$lib_601.ensureSingle(g, 'rect', 'legendtoggle', function(s) { + s.style('cursor', 'pointer') + .attr('pointer-events', 'all') + .call(_$color_473.fill, 'rgba(0,0,0,0)'); + }); traceToggle.on('mousedown', function() { newMouseDownTime = (new Date()).getTime(); @@ -66457,13 +68323,13 @@ function setupTraceToggle(g, gd) { } if(numClicks === 1) { - legend._clickTimeout = setTimeout(function() { _$handleClick_469(g, gd, numClicks); }, DBLCLICKDELAY); + legend._clickTimeout = setTimeout(function() { _$handleClick_531(g, gd, numClicks); }, DBLCLICKDELAY); } else if(numClicks === 2) { if(legend._clickTimeout) { clearTimeout(legend._clickTimeout); } gd._legendMouseDownTime = 0; - _$handleClick_469(g, gd, numClicks); + _$handleClick_531(g, gd, numClicks); } }); } @@ -66479,31 +68345,31 @@ function computeTextDimensions(g, gd) { var mathjaxGroup = g.select('g[class*=math-group]'); var mathjaxNode = mathjaxGroup.node(); var opts = gd._fullLayout.legend; - var lineHeight = opts.font.size * __LINE_SPACING_467; + var lineHeight = opts.font.size * __LINE_SPACING_529; var height, width; if(mathjaxNode) { - var mathjaxBB = _$drawing_436.bBox(mathjaxNode); + var mathjaxBB = _$drawing_498.bBox(mathjaxNode); height = mathjaxBB.height; width = mathjaxBB.width; - _$drawing_436.setTranslate(mathjaxGroup, 0, (height / 4)); + _$drawing_498.setTranslate(mathjaxGroup, 0, (height / 4)); } else { var text = g.select('.legendtext'); - var textLines = _$svg_text_utils_562.lineCount(text); + var textLines = _$svg_text_utils_625.lineCount(text); var textNode = text.node(); height = lineHeight * textLines; - width = textNode ? _$drawing_436.bBox(textNode).width : 0; + width = textNode ? _$drawing_498.bBox(textNode).width : 0; // approximation to height offset to center the font // to avoid getBoundingClientRect var textY = lineHeight * (0.3 + (1 - textLines) / 2); // TODO: this 40 should go in a constants file (along with other // values related to the legend symbol size) - _$svg_text_utils_562.positionText(text, 40, textY); + _$svg_text_utils_625.positionText(text, 40, textY); } height = Math.max(height, 16) + 3; @@ -66516,17 +68382,17 @@ function computeLegendDimensions(gd, groups, traces) { var fullLayout = gd._fullLayout; var opts = fullLayout.legend; var borderwidth = opts.borderwidth; - var isGrouped = _$helpers_470.isGrouped(opts); + var isGrouped = _$helpers_532.isGrouped(opts); var extraWidth = 0; opts._width = 0; opts._height = 0; - if(_$helpers_470.isVertical(opts)) { + if(_$helpers_532.isVertical(opts)) { if(isGrouped) { groups.each(function(d, i) { - _$drawing_436.setTranslate(this, 0, i * opts.tracegroupgap); + _$drawing_498.setTranslate(this, 0, i * opts.tracegroupgap); }); } @@ -66535,7 +68401,7 @@ function computeLegendDimensions(gd, groups, traces) { textHeight = legendItem.height, textWidth = legendItem.width; - _$drawing_436.setTranslate(this, + _$drawing_498.setTranslate(this, borderwidth, (5 + borderwidth + opts._height + textHeight / 2)); @@ -66569,11 +68435,11 @@ function computeLegendDimensions(gd, groups, traces) { } groups.each(function(d, i) { - _$drawing_436.setTranslate(this, groupXOffsets[i], 0); + _$drawing_498.setTranslate(this, groupXOffsets[i], 0); }); groups.each(function() { - var group = _$d3_127.select(this), + var group = _$d3_130.select(this), groupTraces = group.selectAll('g.traces'), groupHeight = 0; @@ -66581,7 +68447,7 @@ function computeLegendDimensions(gd, groups, traces) { var legendItem = d[0], textHeight = legendItem.height; - _$drawing_436.setTranslate(this, + _$drawing_498.setTranslate(this, 0, (5 + borderwidth + groupHeight + textHeight / 2)); @@ -66623,7 +68489,7 @@ function computeLegendDimensions(gd, groups, traces) { maxTraceHeight = 0; } - _$drawing_436.setTranslate(this, + _$drawing_498.setTranslate(this, (borderwidth + offsetX), (5 + borderwidth + legendItem.height / 2) + rowHeight); @@ -66646,9 +68512,9 @@ function computeLegendDimensions(gd, groups, traces) { traces.each(function(d) { var legendItem = d[0], - bg = _$d3_127.select(this).select('.legendtoggle'); + bg = _$d3_130.select(this).select('.legendtoggle'); - _$drawing_436.setRect(bg, + _$drawing_498.setRect(bg, 0, -legendItem.height / 2, (gd._context.edits.legendText ? 0 : opts._width) + extraWidth, @@ -66662,29 +68528,29 @@ function expandMargin(gd) { opts = fullLayout.legend; var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { xanchor = 'right'; } - else if(_$anchor_utils_463.isCenterAnchor(opts)) { + else if(_$anchor_utils_525.isCenterAnchor(opts)) { xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(opts)) { + if(_$anchor_utils_525.isBottomAnchor(opts)) { yanchor = 'bottom'; } - else if(_$anchor_utils_463.isMiddleAnchor(opts)) { + else if(_$anchor_utils_525.isMiddleAnchor(opts)) { yanchor = 'middle'; } // lastly check if the margin auto-expand has changed - _$plots_647.autoMargin(gd, 'legend', { + _$plots_709.autoMargin(gd, 'legend', { x: opts.x, y: opts.y, - l: opts._width * (FROM_TL[xanchor]), + l: opts._width * (__FROM_TL_529[xanchor]), r: opts._width * (FROM_BR[xanchor]), b: opts._height * (FROM_BR[yanchor]), - t: opts._height * (FROM_TL[yanchor]) + t: opts._height * (__FROM_TL_529[yanchor]) }); } @@ -66693,18 +68559,18 @@ function expandHorizontalMargin(gd) { opts = fullLayout.legend; var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { xanchor = 'right'; } - else if(_$anchor_utils_463.isCenterAnchor(opts)) { + else if(_$anchor_utils_525.isCenterAnchor(opts)) { xanchor = 'center'; } // lastly check if the margin auto-expand has changed - _$plots_647.autoMargin(gd, 'legend', { + _$plots_709.autoMargin(gd, 'legend', { x: opts.x, y: 0.5, - l: opts._width * (FROM_TL[xanchor]), + l: opts._width * (__FROM_TL_529[xanchor]), r: opts._width * (FROM_BR[xanchor]), b: 0, t: 0 @@ -66723,15 +68589,15 @@ function expandHorizontalMargin(gd) { 'use strict'; -var _$legend_471 = { +var _$legend_533 = { moduleType: 'component', name: 'legend', - layoutAttributes: _$attributes_464, - supplyLayoutDefaults: _$legendDefaults_466, + layoutAttributes: _$attributes_526, + supplyLayoutDefaults: _$legendDefaults_528, - draw: _$draw_467, - style: _$style_472 + draw: _$draw_529, + style: _$style_534 }; /** @@ -66745,7 +68611,7 @@ var _$legend_471 = { 'use strict'; -var _$button_attributes_478 = { +var _$button_attributes_540 = { step: { valType: 'enumerated', @@ -66789,18 +68655,18 @@ var _$button_attributes_478 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../color/attributes'); */; -var __extendFlat_477 = _$extend_528.extendFlat; -/* removed: var _$button_attributes_478 = require('./button_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; +var __extendFlat_539 = _$extend_590.extendFlat; +/* removed: var _$button_attributes_540 = require('./button_attributes'); */; -_$button_attributes_478 = __extendFlat_477(_$button_attributes_478, { +_$button_attributes_540 = __extendFlat_539(_$button_attributes_540, { _isLinkedToArray: 'button', }); -var _$attributes_477 = { +var _$attributes_539 = { visible: { valType: 'boolean', @@ -66808,7 +68674,7 @@ var _$attributes_477 = { }, - buttons: _$button_attributes_478, + buttons: _$button_attributes_540, x: { valType: 'number', @@ -66843,14 +68709,14 @@ var _$attributes_477 = { }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ editType: 'plot', }), bgcolor: { valType: 'color', - dflt: _$attributes_410.lightLine, + dflt: _$attributes_472.lightLine, editType: 'plot', @@ -66863,7 +68729,7 @@ var _$attributes_477 = { }, bordercolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'plot', @@ -66890,7 +68756,7 @@ var _$attributes_477 = { 'use strict'; -var _$constants_479 = { +var _$constants_541 = { // 'y' position pad above counter axis domain yPad: 0.02, @@ -66917,20 +68783,20 @@ var _$constants_479 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../color'); */; -/* removed: var _$attributes_477 = require('./attributes'); */; -/* removed: var _$button_attributes_478 = require('./button_attributes'); */; -/* removed: var _$constants_479 = require('./constants'); */; +/* removed: var _$attributes_539 = require('./attributes'); */; +/* removed: var _$button_attributes_540 = require('./button_attributes'); */; +/* removed: var _$constants_541 = require('./constants'); */; -var _$handleDefaults_480 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { +var _$handleDefaults_542 = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) { var selectorIn = containerIn.rangeselector || {}, selectorOut = containerOut.rangeselector = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(selectorIn, selectorOut, _$attributes_477, attr, dflt); + return _$lib_601.coerce(selectorIn, selectorOut, _$attributes_539, attr, dflt); } var buttons = buttonsDefaults(selectorIn, selectorOut, calendar); @@ -66941,15 +68807,15 @@ var _$handleDefaults_480 = function handleDefaults(containerIn, containerOut, la var posDflt = getPosDflt(containerOut, layout, counterAxes); coerce('x', posDflt[0]); coerce('y', posDflt[1]); - _$lib_539.noneOrAll(containerIn, containerOut, ['x', 'y']); + _$lib_601.noneOrAll(containerIn, containerOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); - _$lib_539.coerceFont(coerce, 'font', layout.font); + _$lib_601.coerceFont(coerce, 'font', layout.font); var bgColor = coerce('bgcolor'); - coerce('activecolor', _$color_411.contrast(bgColor, _$constants_479.lightAmount, _$constants_479.darkAmount)); + coerce('activecolor', _$color_473.contrast(bgColor, _$constants_541.lightAmount, _$constants_541.darkAmount)); coerce('bordercolor'); coerce('borderwidth'); }; @@ -66961,14 +68827,14 @@ function buttonsDefaults(containerIn, containerOut, calendar) { var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_539.coerce(buttonIn, buttonOut, _$button_attributes_478, attr, dflt); + return _$lib_601.coerce(buttonIn, buttonOut, _$button_attributes_540, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { buttonIn = buttonsIn[i]; buttonOut = {}; - if(!_$lib_539.isPlainObject(buttonIn)) continue; + if(!_$lib_601.isPlainObject(buttonIn)) continue; var step = coerce('step'); if(step !== 'all') { @@ -67002,7 +68868,7 @@ function getPosDflt(containerOut, layout, counterAxes) { if(domain) posY = Math.max(domain[1], posY); } - return [containerOut.domain[0], posY + _$constants_479.yPad]; + return [containerOut.domain[0], posY + _$constants_541.yPad]; } /** @@ -67016,9 +68882,9 @@ function getPosDflt(containerOut, layout, counterAxes) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -var _$getUpdateObject_482 = function getUpdateObject(axisLayout, buttonLayout) { +var _$getUpdateObject_544 = function getUpdateObject(axisLayout, buttonLayout) { var axName = axisLayout._name; var update = {}; @@ -67046,13 +68912,13 @@ function getXRange(axisLayout, buttonLayout) { switch(buttonLayout.stepmode) { case 'backward': - range0 = axisLayout.l2r(+_$d3_127.time[step].utc.offset(base, -count)); + range0 = axisLayout.l2r(+_$d3_130.time[step].utc.offset(base, -count)); break; case 'todate': - var base2 = _$d3_127.time[step].utc.offset(base, -count); + var base2 = _$d3_130.time[step].utc.offset(base, -count); - range0 = axisLayout.l2r(+_$d3_127.time[step].utc.ceil(base2)); + range0 = axisLayout.l2r(+_$d3_130.time[step].utc.ceil(base2)); break; } @@ -67071,26 +68937,27 @@ function getXRange(axisLayout, buttonLayout) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$anchor_utils_463 = require('../legend/anchor_utils'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$anchor_utils_525 = require('../legend/anchor_utils'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_481 = _$alignment_511.LINE_SPACING; -var __FROM_TL_481 = _$alignment_511.FROM_TL; -var __FROM_BR_481 = _$alignment_511.FROM_BR; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_543 = _$alignment_573.LINE_SPACING; +var __FROM_TL_543 = _$alignment_573.FROM_TL; +var __FROM_BR_543 = _$alignment_573.FROM_BR; -/* removed: var _$constants_479 = require('./constants'); */; -/* removed: var _$getUpdateObject_482 = require('./get_update_object'); */; +/* removed: var _$constants_541 = require('./constants'); */; +/* removed: var _$getUpdateObject_544 = require('./get_update_object'); */; -var _$draw_481 = function draw(gd) { +var _$draw_543 = function draw(gd) { var fullLayout = gd._fullLayout; var selectors = fullLayout._infolayer.selectAll('.rangeselector') @@ -67107,7 +68974,7 @@ var _$draw_481 = function draw(gd) { }); selectors.each(function(d) { - var selector = _$d3_127.select(this), + var selector = _$d3_130.select(this), axisLayout = d, selectorLayout = axisLayout.rangeselector; @@ -67120,8 +68987,8 @@ var _$draw_481 = function draw(gd) { buttons.exit().remove(); buttons.each(function(d) { - var button = _$d3_127.select(this); - var update = _$getUpdateObject_482(axisLayout, d); + var button = _$d3_130.select(this); + var update = _$getUpdateObject_544(axisLayout, d); d._isActive = isActive(axisLayout, d, update); @@ -67131,7 +68998,7 @@ var _$draw_481 = function draw(gd) { button.on('click', function() { if(gd._dragged) return; - _$registry_668.call('relayout', gd, update); + _$registry_731.call('relayout', gd, update); }); button.on('mouseover', function() { @@ -67151,7 +69018,7 @@ var _$draw_481 = function draw(gd) { }; function makeSelectorData(gd) { - var axes = _$axis_ids_587.list(gd, 'x', true); + var axes = _$axis_ids_650.list(gd, 'x', true); var data = []; for(var i = 0; i < axes.length; i++) { @@ -67184,21 +69051,17 @@ function isActive(axisLayout, opts, update) { } function drawButtonRect(button, selectorLayout, d) { - var rect = button.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed('selector-rect', true); - - rect.attr('shape-rendering', 'crispEdges'); + var rect = _$lib_601.ensureSingle(button, 'rect', 'selector-rect', function(s) { + s.attr('shape-rendering', 'crispEdges'); + }); rect.attr({ - 'rx': _$constants_479.rx, - 'ry': _$constants_479.ry + 'rx': _$constants_541.rx, + 'ry': _$constants_541.ry }); - rect.call(_$color_411.stroke, selectorLayout.bordercolor) - .call(_$color_411.fill, getFillColor(selectorLayout, d)) + rect.call(_$color_473.stroke, selectorLayout.bordercolor) + .call(_$color_473.fill, getFillColor(selectorLayout, d)) .style('stroke-width', selectorLayout.borderwidth + 'px'); } @@ -67210,19 +69073,15 @@ function getFillColor(selectorLayout, d) { function drawButtonText(button, selectorLayout, d, gd) { function textLayout(s) { - _$svg_text_utils_562.convertToTspans(s, gd); + _$svg_text_utils_625.convertToTspans(s, gd); } - var text = button.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed('selector-text', true) - .classed('user-select-none', true); - - text.attr('text-anchor', 'middle'); + var text = _$lib_601.ensureSingle(button, 'text', 'selector-text', function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'middle'); + }); - text.call(_$drawing_436.font, selectorLayout.font) + text.call(_$drawing_498.font, selectorLayout.font) .text(getLabel(d)) .call(textLayout); } @@ -67242,25 +69101,25 @@ function reposition(gd, buttons, opts, axName, selector) { var borderWidth = opts.borderwidth; buttons.each(function() { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); var text = button.select('.selector-text'); - var tHeight = opts.font.size * __LINE_SPACING_481; - var hEff = Math.max(tHeight * _$svg_text_utils_562.lineCount(text), 16) + 3; + var tHeight = opts.font.size * __LINE_SPACING_543; + var hEff = Math.max(tHeight * _$svg_text_utils_625.lineCount(text), 16) + 3; height = Math.max(height, hEff); }); buttons.each(function() { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); var rect = button.select('.selector-rect'); var text = button.select('.selector-text'); - var tWidth = text.node() && _$drawing_436.bBox(text.node()).width; - var tHeight = opts.font.size * __LINE_SPACING_481; - var tLines = _$svg_text_utils_562.lineCount(text); + var tWidth = text.node() && _$drawing_498.bBox(text.node()).width; + var tHeight = opts.font.size * __LINE_SPACING_543; + var tLines = _$svg_text_utils_625.lineCount(text); - var wEff = Math.max(tWidth + 10, _$constants_479.minButtonWidth); + var wEff = Math.max(tWidth + 10, _$constants_541.minButtonWidth); // TODO add MathJax support @@ -67277,7 +69136,7 @@ function reposition(gd, buttons, opts, axName, selector) { height: height }); - _$svg_text_utils_562.positionText(text, wEff / 2, + _$svg_text_utils_625.positionText(text, wEff / 2, height / 2 - ((tLines - 1) * tHeight / 2) + 3); width += wEff + 5; @@ -67288,21 +69147,21 @@ function reposition(gd, buttons, opts, axName, selector) { var ly = graphSize.t + graphSize.h * (1 - opts.y); var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(opts)) { + if(_$anchor_utils_525.isRightAnchor(opts)) { lx -= width; xanchor = 'right'; } - if(_$anchor_utils_463.isCenterAnchor(opts)) { + if(_$anchor_utils_525.isCenterAnchor(opts)) { lx -= width / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(opts)) { + if(_$anchor_utils_525.isBottomAnchor(opts)) { ly -= height; yanchor = 'bottom'; } - if(_$anchor_utils_463.isMiddleAnchor(opts)) { + if(_$anchor_utils_525.isMiddleAnchor(opts)) { ly -= height / 2; yanchor = 'middle'; } @@ -67312,13 +69171,13 @@ function reposition(gd, buttons, opts, axName, selector) { lx = Math.round(lx); ly = Math.round(ly); - _$plots_647.autoMargin(gd, axName + '-range-selector', { + _$plots_709.autoMargin(gd, axName + '-range-selector', { x: opts.x, y: opts.y, - l: width * __FROM_TL_481[xanchor], - r: width * __FROM_BR_481[xanchor], - b: height * __FROM_BR_481[yanchor], - t: height * __FROM_TL_481[yanchor] + l: width * __FROM_TL_543[xanchor], + r: width * __FROM_BR_543[xanchor], + b: height * __FROM_BR_543[yanchor], + t: height * __FROM_TL_543[yanchor] }); selector.attr('transform', 'translate(' + lx + ',' + ly + ')'); @@ -67334,20 +69193,20 @@ function reposition(gd, buttons, opts, axName, selector) { 'use strict'; -var _$rangeselector_483 = { +var _$rangeselector_545 = { moduleType: 'component', name: 'rangeselector', schema: { subplots: { - xaxis: {rangeselector: _$attributes_477} + xaxis: {rangeselector: _$attributes_539} } }, - layoutAttributes: _$attributes_477, - handleDefaults: _$handleDefaults_480, + layoutAttributes: _$attributes_539, + handleDefaults: _$handleDefaults_542, - draw: _$draw_481 + draw: _$draw_543 }; /** @@ -67360,19 +69219,19 @@ var _$rangeselector_483 = { 'use strict'; -/* removed: var _$attributes_410 = require('../color/attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; -var _$attributes_484 = { +var _$attributes_546 = { bgcolor: { valType: 'color', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, editType: 'plot', }, bordercolor: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, editType: 'plot', @@ -67433,7 +69292,7 @@ var _$attributes_484 = { 'use strict'; -var _$constants_486 = { +var _$constants_548 = { // attribute container name name: 'rangeslider', @@ -67488,11 +69347,11 @@ var _$constants_486 = { 'use strict'; -var listAxes = _$axis_ids_587.list; -var __getAutoRange_485 = _$autorange_583.getAutoRange; -/* removed: var _$constants_486 = require('./constants'); */; +var listAxes = _$axis_ids_650.list; +var __getAutoRange_547 = _$autorange_646.getAutoRange; +/* removed: var _$constants_548 = require('./constants'); */; -var _$calcAutorange_485 = function calcAutorange(gd) { +var _$calcAutorange_547 = function calcAutorange(gd) { var axes = listAxes(gd, 'x', true); // Compute new slider range using axis autorange if necessary. @@ -67502,14 +69361,14 @@ var _$calcAutorange_485 = function calcAutorange(gd) { for(var i = 0; i < axes.length; i++) { var ax = axes[i], - opts = ax[_$constants_486.name]; + opts = ax[_$constants_548.name]; // Don't try calling getAutoRange if _min and _max are filled in. // This happens on updates where the calc step is skipped. if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) { opts._input.autorange = true; - opts._input.range = opts.range = __getAutoRange_485(ax); + opts._input.range = opts.range = __getAutoRange_547(ax); } } }; @@ -67524,7 +69383,7 @@ var _$calcAutorange_485 = function calcAutorange(gd) { 'use strict'; -var _$oppaxis_attributes_490 = { +var _$oppaxis_attributes_552 = { // not really a 'subplot' attribute container, // but this is the flag we use to denote attributes that // support yaxis, yaxis2, yaxis3, ... counters @@ -67561,29 +69420,31 @@ var _$oppaxis_attributes_490 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_484 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_490 = require('./oppaxis_attributes'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_546 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_552 = require('./oppaxis_attributes'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; -var _$handleDefaults_487 = function handleDefaults(layoutIn, layoutOut, axName) { - if(!layoutIn[axName].rangeslider) return; +var _$handleDefaults_549 = 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_539.isPlainObject(layoutIn[axName].rangeslider)) { - layoutIn[axName].rangeslider = {}; + if(!_$lib_601.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; } - var containerIn = layoutIn[axName].rangeslider, - axOut = layoutOut[axName], - containerOut = axOut.rangeslider = {}; + var containerIn = axIn.rangeslider; + var containerOut = axOut.rangeslider = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$attributes_484, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$attributes_546, attr, dflt); } function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) { - return _$lib_539.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_490, attr, dflt); + return _$lib_601.coerce(rangeContainerIn, rangeContainerOut, _$oppaxis_attributes_552, attr, dflt); } var visible = coerce('visible'); @@ -67601,12 +69462,12 @@ var _$handleDefaults_487 = function handleDefaults(layoutIn, layoutOut, axName) if(subplots) { var yIds = subplots.cartesian .filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_587.name2id(axName); + return subplotId.substr(0, subplotId.indexOf('y')) === _$axis_ids_650.name2id(axName); }) .map(function(subplotId) { return subplotId.substr(subplotId.indexOf('y'), subplotId.length); }); - var yNames = _$lib_539.simpleMap(yIds, _$axis_ids_587.id2name); + var yNames = _$lib_601.simpleMap(yIds, _$axis_ids_650.id2name); for(var i = 0; i < yNames.length; i++) { var yName = yNames[i]; @@ -67642,25 +69503,25 @@ var _$handleDefaults_487 = function handleDefaults(layoutIn, layoutOut, axName) 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$titles_504 = require('../titles'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$titles_566 = require('../titles'); */; -/* removed: var _$cartesian_595 = require('../../plots/cartesian'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$cartesian_658 = require('../../plots/cartesian'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; -/* removed: var _$constants_486 = require('./constants'); */; +/* removed: var _$constants_548 = require('./constants'); */; -var _$draw_488 = function(gd) { +var _$draw_550 = function(gd) { var fullLayout = gd._fullLayout, rangeSliderData = makeRangeSliderData(fullLayout); @@ -67686,17 +69547,17 @@ var _$draw_488 = function(gd) { } var rangeSliders = fullLayout._infolayer - .selectAll('g.' + _$constants_486.containerClassName) + .selectAll('g.' + _$constants_548.containerClassName) .data(rangeSliderData, keyFunction); rangeSliders.enter().append('g') - .classed(_$constants_486.containerClassName, true) + .classed(_$constants_548.containerClassName, true) .attr('pointer-events', 'all'); // remove exiting sliders and their corresponding clip paths rangeSliders.exit().each(function(axisOpts) { - var rangeSlider = _$d3_127.select(this), - opts = axisOpts[_$constants_486.name]; + var rangeSlider = _$d3_130.select(this), + opts = axisOpts[_$constants_548.name]; rangeSlider.remove(); fullLayout._topdefs.select('#' + opts._clipId).remove(); @@ -67710,10 +69571,10 @@ var _$draw_488 = function(gd) { // for all present range sliders rangeSliders.each(function(axisOpts) { - var rangeSlider = _$d3_127.select(this), - opts = axisOpts[_$constants_486.name], - oppAxisOpts = fullLayout[_$axes_584.id2name(axisOpts.anchor)], - oppAxisRangeOpts = opts[_$axes_584.id2name(axisOpts.anchor)]; + var rangeSlider = _$d3_130.select(this), + opts = axisOpts[_$constants_548.name], + oppAxisOpts = fullLayout[_$axes_647.id2name(axisOpts.anchor)], + oppAxisRangeOpts = opts[_$axes_647.id2name(axisOpts.anchor)]; // update range // Expand slider range to the axis range @@ -67738,13 +69599,13 @@ var _$draw_488 = function(gd) { var tickHeight = (axisOpts._boundingBox || {}).height || 0; var oppBottom = Infinity; - var subplotData = _$axes_584.getSubplots(gd, axisOpts); + var subplotData = _$axes_647.getSubplots(gd, axisOpts); for(var i = 0; i < subplotData.length; i++) { - var oppAxis = _$axes_584.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); + var oppAxis = _$axes_647.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y'))); oppBottom = Math.min(oppBottom, oppAxis.domain[0]); } - opts._id = _$constants_486.name + axisOpts._id; + opts._id = _$constants_548.name + axisOpts._id; opts._clipId = opts._id + '-' + fullLayout._uid; opts._width = graphSize.w * (domain[1] - domain[0]); @@ -67756,7 +69617,7 @@ var _$draw_488 = function(gd) { var y = Math.round( graphSize.t + graphSize.h * (1 - oppBottom) + tickHeight + - opts._offsetShift + _$constants_486.extraPad + opts._offsetShift + _$constants_548.extraPad ); rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')'); @@ -67806,7 +69667,7 @@ var _$draw_488 = function(gd) { // title goes next to range slider instead of tick labels, so // just take it over and draw it from here if(axisOpts.side === 'bottom') { - _$titles_504.draw(gd, axisOpts._id + 'title', { + _$titles_566.draw(gd, axisOpts._id + 'title', { propContainer: axisOpts, propName: axisOpts._name + '.title', placeholder: fullLayout._dfltTitle.x, @@ -67819,21 +69680,21 @@ var _$draw_488 = function(gd) { } // update margins - _$plots_647.autoMargin(gd, opts._id, { + _$plots_709.autoMargin(gd, opts._id, { x: domain[0], y: oppBottom, l: 0, r: 0, t: 0, b: opts._height + margin.b + tickHeight, - pad: _$constants_486.extraPad + opts._offsetShift * 2 + pad: _$constants_548.extraPad + opts._offsetShift * 2 }); }); }; function makeRangeSliderData(fullLayout) { - var axes = _$axes_584.list({ _fullLayout: fullLayout }, 'x', true), - name = _$constants_486.name, + var axes = _$axes_647.list({ _fullLayout: fullLayout }, 'x', true), + name = _$constants_548.name, out = []; if(fullLayout._has('gl2d')) return out; @@ -67848,19 +69709,19 @@ function makeRangeSliderData(fullLayout) { } function setupDragElement(rangeSlider, gd, axisOpts, opts) { - var slideBox = rangeSlider.select('rect.' + _$constants_486.slideBoxClassName).node(), - grabAreaMin = rangeSlider.select('rect.' + _$constants_486.grabAreaMinClassName).node(), - grabAreaMax = rangeSlider.select('rect.' + _$constants_486.grabAreaMaxClassName).node(); + var slideBox = rangeSlider.select('rect.' + _$constants_548.slideBoxClassName).node(), + grabAreaMin = rangeSlider.select('rect.' + _$constants_548.grabAreaMinClassName).node(), + grabAreaMax = rangeSlider.select('rect.' + _$constants_548.grabAreaMaxClassName).node(); rangeSlider.on('mousedown', function() { - var event = _$d3_127.event, + var event = _$d3_130.event, target = event.target, startX = event.clientX, offsetX = startX - rangeSlider.node().getBoundingClientRect().left, minVal = opts.d2p(axisOpts._rl[0]), maxVal = opts.d2p(axisOpts._rl[1]); - var dragCover = _$dragelement_433.coverSlip(); + var dragCover = _$dragelement_495.coverSlip(); dragCover.addEventListener('mousemove', mouseMove); dragCover.addEventListener('mouseup', mouseUp); @@ -67904,14 +69765,14 @@ function setupDragElement(rangeSlider, gd, axisOpts, opts) { opts._pixelMin = pixelMin; opts._pixelMax = pixelMax; - _$setCursor_558(_$d3_127.select(dragCover), cursor); + _$setCursor_621(_$d3_130.select(dragCover), cursor); setDataRange(rangeSlider, gd, axisOpts, opts); } function mouseUp() { dragCover.removeEventListener('mousemove', mouseMove); dragCover.removeEventListener('mouseup', mouseUp); - _$lib_539.removeElement(dragCover); + _$lib_601.removeElement(dragCover); } }); } @@ -67919,43 +69780,43 @@ function setupDragElement(rangeSlider, gd, axisOpts, opts) { function setDataRange(rangeSlider, gd, axisOpts, opts) { function clamp(v) { - return axisOpts.l2r(_$lib_539.constrain(v, opts._rl[0], opts._rl[1])); + return axisOpts.l2r(_$lib_601.constrain(v, opts._rl[0], opts._rl[1])); } var dataMin = clamp(opts.p2d(opts._pixelMin)), dataMax = clamp(opts.p2d(opts._pixelMax)); window.requestAnimationFrame(function() { - _$registry_668.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); + _$registry_731.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]); }); } function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = _$constants_486.handleWidth / 2; + var hw2 = _$constants_548.handleWidth / 2; function clamp(v) { - return _$lib_539.constrain(v, 0, opts._width); + return _$lib_601.constrain(v, 0, opts._width); } function clampOppAxis(v) { - return _$lib_539.constrain(v, 0, opts._height); + return _$lib_601.constrain(v, 0, opts._height); } function clampHandle(v) { - return _$lib_539.constrain(v, -hw2, opts._width + hw2); + return _$lib_601.constrain(v, -hw2, opts._width + hw2); } var pixelMin = clamp(opts.d2p(axisOpts._rl[0])), pixelMax = clamp(opts.d2p(axisOpts._rl[1])); - rangeSlider.select('rect.' + _$constants_486.slideBoxClassName) + rangeSlider.select('rect.' + _$constants_548.slideBoxClassName) .attr('x', pixelMin) .attr('width', pixelMax - pixelMin); - rangeSlider.select('rect.' + _$constants_486.maskMinClassName) + rangeSlider.select('rect.' + _$constants_548.maskMinClassName) .attr('width', pixelMin); - rangeSlider.select('rect.' + _$constants_486.maskMaxClassName) + rangeSlider.select('rect.' + _$constants_548.maskMaxClassName) .attr('x', pixelMax) .attr('width', opts._width - pixelMax); @@ -67963,18 +69824,18 @@ function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRang var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])), pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - rangeSlider.select('rect.' + _$constants_486.maskMinOppAxisClassName) + rangeSlider.select('rect.' + _$constants_548.maskMinOppAxisClassName) .attr('x', pixelMin) .attr('height', pixelMinOppAxis) .attr('width', pixelMax - pixelMin); - rangeSlider.select('rect.' + _$constants_486.maskMaxOppAxisClassName) + rangeSlider.select('rect.' + _$constants_548.maskMaxOppAxisClassName) .attr('x', pixelMin) .attr('y', pixelMaxOppAxis) .attr('height', opts._height - pixelMaxOppAxis) .attr('width', pixelMax - pixelMin); - rangeSlider.select('rect.' + _$constants_486.slideBoxClassName) + rangeSlider.select('rect.' + _$constants_548.slideBoxClassName) .attr('y', pixelMinOppAxis) .attr('height', pixelMaxOppAxis - pixelMinOppAxis); } @@ -67986,31 +69847,28 @@ function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRang var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset, xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - rangeSlider.select('g.' + _$constants_486.grabberMinClassName) + rangeSlider.select('g.' + _$constants_548.grabberMinClassName) .attr('transform', 'translate(' + xMin + ',' + offset + ')'); - rangeSlider.select('g.' + _$constants_486.grabberMaxClassName) + rangeSlider.select('g.' + _$constants_548.grabberMaxClassName) .attr('transform', 'translate(' + xMax + ',' + offset + ')'); } function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = rangeSlider.selectAll('rect.' + _$constants_486.bgClassName) - .data([0]); - - bg.enter().append('rect') - .classed(_$constants_486.bgClassName, true) - .attr({ + var bg = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.bgClassName, function(s) { + s.attr({ x: 0, y: 0, 'shape-rendering': 'crispEdges' }); + }); var borderCorrect = (opts.borderwidth % 2) === 0 ? opts.borderwidth : opts.borderwidth - 1; var offsetShift = -opts._offsetShift; - var lw = _$drawing_436.crispRound(gd, opts.borderwidth); + var lw = _$drawing_498.crispRound(gd, opts.borderwidth); bg.attr({ width: opts._width + borderCorrect, @@ -68025,13 +69883,9 @@ function drawBg(rangeSlider, gd, axisOpts, opts) { function addClipPath(rangeSlider, gd, axisOpts, opts) { var fullLayout = gd._fullLayout; - var clipPath = fullLayout._topdefs.selectAll('#' + opts._clipId) - .data([0]); - - clipPath.enter().append('clipPath') - .attr('id', opts._clipId) - .append('rect') - .attr({ x: 0, y: 0 }); + var clipPath = _$lib_601.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) { + s.append('rect').attr({ x: 0, y: 0 }); + }); clipPath.select('rect').attr({ width: opts._width, @@ -68040,15 +69894,15 @@ function addClipPath(rangeSlider, gd, axisOpts, opts) { } function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var subplotData = _$axes_584.getSubplots(gd, axisOpts), + var subplotData = _$axes_647.getSubplots(gd, axisOpts), calcData = gd.calcdata; - var rangePlots = rangeSlider.selectAll('g.' + _$constants_486.rangePlotClassName) - .data(subplotData, _$lib_539.identity); + var rangePlots = rangeSlider.selectAll('g.' + _$constants_548.rangePlotClassName) + .data(subplotData, _$lib_601.identity); rangePlots.enter().append('g') - .attr('class', function(id) { return _$constants_486.rangePlotClassName + ' ' + id; }) - .call(_$drawing_436.setClipUrl, opts._clipId); + .attr('class', function(id) { return _$constants_548.rangePlotClassName + ' ' + id; }) + .call(_$drawing_498.setClipUrl, opts._clipId); rangePlots.order(); @@ -68057,10 +69911,10 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { var mainplotinfo; rangePlots.each(function(id, i) { - var plotgroup = _$d3_127.select(this), + var plotgroup = _$d3_130.select(this), isMainPlot = (i === 0); - var oppAxisOpts = _$axes_584.getFromId(gd, id, 'y'), + var oppAxisOpts = _$axes_647.getFromId(gd, id, 'y'), oppAxisName = oppAxisOpts._name, oppAxisRangeOpts = opts[oppAxisName]; @@ -68087,7 +69941,7 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { calendar: oppAxisOpts.calendar }; - _$plots_647.supplyDefaults(mockFigure); + _$plots_709.supplyDefaults(mockFigure); var xa = mockFigure._fullLayout.xaxis, ya = mockFigure._fullLayout[oppAxisName]; @@ -68096,7 +69950,8 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { id: id, plotgroup: plotgroup, xaxis: xa, - yaxis: ya + yaxis: ya, + isRangePlot: true }; if(isMainPlot) mainplotinfo = plotinfo; @@ -68105,7 +69960,7 @@ function drawRangePlot(rangeSlider, gd, axisOpts, opts) { plotinfo.mainplotinfo = mainplotinfo; } - _$cartesian_595.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + _$cartesian_658.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); }); } @@ -68125,146 +69980,121 @@ function filterRangePlotCalcData(calcData, subplotId) { } function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = rangeSlider.selectAll('rect.' + _$constants_486.maskMinClassName) - .data([0]); - - maskMin.enter().append('rect') - .classed(_$constants_486.maskMinClassName, true) - .attr({ x: 0, y: 0 }) - .attr('shape-rendering', 'crispEdges'); + var maskMin = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMin .attr('height', opts._height) - .call(_$color_411.fill, _$constants_486.maskColor); - - var maskMax = rangeSlider.selectAll('rect.' + _$constants_486.maskMaxClassName) - .data([0]); + .call(_$color_473.fill, _$constants_548.maskColor); - maskMax.enter().append('rect') - .classed(_$constants_486.maskMaxClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var maskMax = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMaxClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMax .attr('height', opts._height) - .call(_$color_411.fill, _$constants_486.maskColor); + .call(_$color_473.fill, _$constants_548.maskColor); // masks used for oppAxis zoom if(oppAxisRangeOpts.rangemode !== 'match') { - var maskMinOppAxis = rangeSlider.selectAll('rect.' + _$constants_486.maskMinOppAxisClassName) - .data([0]); - - maskMinOppAxis.enter().append('rect') - .classed(_$constants_486.maskMinOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var maskMinOppAxis = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMinOppAxis .attr('width', opts._width) - .call(_$color_411.fill, _$constants_486.maskOppAxisColor); + .call(_$color_473.fill, _$constants_548.maskOppAxisColor); - var maskMaxOppAxis = rangeSlider.selectAll('rect.' + _$constants_486.maskMaxOppAxisClassName) - .data([0]); - - maskMaxOppAxis.enter().append('rect') - .classed(_$constants_486.maskMaxOppAxisClassName, true) - .attr('y', 0) - .attr('shape-rendering', 'crispEdges'); + var maskMaxOppAxis = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + 'shape-rendering': 'crispEdges' + }); + }); maskMaxOppAxis .attr('width', opts._width) - .style('border-top', _$constants_486.maskOppBorder) - .call(_$color_411.fill, _$constants_486.maskOppAxisColor); + .style('border-top', _$constants_548.maskOppBorder) + .call(_$color_473.fill, _$constants_548.maskOppAxisColor); } } function drawSlideBox(rangeSlider, gd, axisOpts, opts) { if(gd._context.staticPlot) return; - var slideBox = rangeSlider.selectAll('rect.' + _$constants_486.slideBoxClassName) - .data([0]); - - slideBox.enter().append('rect') - .classed(_$constants_486.slideBoxClassName, true) - .attr('y', 0) - .attr('cursor', _$constants_486.slideBoxCursor) - .attr('shape-rendering', 'crispEdges'); + var slideBox = _$lib_601.ensureSingle(rangeSlider, 'rect', _$constants_548.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: _$constants_548.slideBoxCursor, + 'shape-rendering': 'crispEdges' + }); + }); slideBox.attr({ height: opts._height, - fill: _$constants_486.slideBoxFill + fill: _$constants_548.slideBoxFill }); } function drawGrabbers(rangeSlider, gd, axisOpts, opts) { - // - - var grabberMin = rangeSlider.selectAll('g.' + _$constants_486.grabberMinClassName) - .data([0]); - grabberMin.enter().append('g') - .classed(_$constants_486.grabberMinClassName, true); - - var grabberMax = rangeSlider.selectAll('g.' + _$constants_486.grabberMaxClassName) - .data([0]); - grabberMax.enter().append('g') - .classed(_$constants_486.grabberMaxClassName, true); + var grabberMin = _$lib_601.ensureSingle(rangeSlider, 'g', _$constants_548.grabberMinClassName); + var grabberMax = _$lib_601.ensureSingle(rangeSlider, 'g', _$constants_548.grabberMaxClassName); // - var handleFixAttrs = { x: 0, - width: _$constants_486.handleWidth, - rx: _$constants_486.handleRadius, - fill: _$color_411.background, - stroke: _$color_411.defaultLine, - 'stroke-width': _$constants_486.handleStrokeWidth, + width: _$constants_548.handleWidth, + rx: _$constants_548.handleRadius, + fill: _$color_473.background, + stroke: _$color_473.defaultLine, + 'stroke-width': _$constants_548.handleStrokeWidth, 'shape-rendering': 'crispEdges' }; - var handleDynamicAttrs = { y: Math.round(opts._height / 4), height: Math.round(opts._height / 2), }; - - var handleMin = grabberMin.selectAll('rect.' + _$constants_486.handleMinClassName) - .data([0]); - handleMin.enter().append('rect') - .classed(_$constants_486.handleMinClassName, true) - .attr(handleFixAttrs); + var handleMin = _$lib_601.ensureSingle(grabberMin, 'rect', _$constants_548.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); handleMin.attr(handleDynamicAttrs); - var handleMax = grabberMax.selectAll('rect.' + _$constants_486.handleMaxClassName) - .data([0]); - handleMax.enter().append('rect') - .classed(_$constants_486.handleMaxClassName, true) - .attr(handleFixAttrs); + var handleMax = _$lib_601.ensureSingle(grabberMax, 'rect', _$constants_548.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); handleMax.attr(handleDynamicAttrs); // - if(gd._context.staticPlot) return; var grabAreaFixAttrs = { - width: _$constants_486.grabAreaWidth, + width: _$constants_548.grabAreaWidth, x: 0, y: 0, - fill: _$constants_486.grabAreaFill, - cursor: _$constants_486.grabAreaCursor + fill: _$constants_548.grabAreaFill, + cursor: _$constants_548.grabAreaCursor }; - var grabAreaMin = grabberMin.selectAll('rect.' + _$constants_486.grabAreaMinClassName) - .data([0]); - grabAreaMin.enter().append('rect') - .classed(_$constants_486.grabAreaMinClassName, true) - .attr(grabAreaFixAttrs); + var grabAreaMin = _$lib_601.ensureSingle(grabberMin, 'rect', _$constants_548.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); grabAreaMin.attr('height', opts._height); - var grabAreaMax = grabberMax.selectAll('rect.' + _$constants_486.grabAreaMaxClassName) - .data([0]); - grabAreaMax.enter().append('rect') - .classed(_$constants_486.grabAreaMaxClassName, true) - .attr(grabAreaFixAttrs); + var grabAreaMax = _$lib_601.ensureSingle(grabberMax, 'rect', _$constants_548.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); grabAreaMax.attr('height', opts._height); } @@ -68275,8 +70105,8 @@ function clearPushMargins(gd) { for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_486.name) !== -1) { - _$plots_647.autoMargin(gd, k); + if(k.indexOf(_$constants_548.name) !== -1) { + _$plots_709.autoMargin(gd, k); } } } @@ -68291,28 +70121,28 @@ function clearPushMargins(gd) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_484 = require('./attributes'); */; -/* removed: var _$oppaxis_attributes_490 = require('./oppaxis_attributes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_546 = require('./attributes'); */; +/* removed: var _$oppaxis_attributes_552 = require('./oppaxis_attributes'); */; -var _$rangeslider_489 = { +var _$rangeslider_551 = { moduleType: 'component', name: 'rangeslider', schema: { subplots: { xaxis: { - rangeslider: _$lib_539.extendFlat({}, _$attributes_484, { - yaxis: _$oppaxis_attributes_490 + rangeslider: _$lib_601.extendFlat({}, _$attributes_546, { + yaxis: _$oppaxis_attributes_552 }) } } }, - layoutAttributes: _$attributes_484, - handleDefaults: _$handleDefaults_487, - calcAutorange: _$calcAutorange_485, - draw: _$draw_488 + layoutAttributes: _$attributes_546, + handleDefaults: _$handleDefaults_549, + calcAutorange: _$calcAutorange_547, + draw: _$draw_550 }; /** @@ -68325,12 +70155,12 @@ var _$rangeslider_489 = { 'use strict'; -/* removed: var _$attributes_394 = require('../annotations/attributes'); */; -var __scatterLineAttrs_491 = _$attributes_862.line; -var __dash_491 = _$attributes_435.dash; -var __extendFlat_491 = _$extend_528.extendFlat; +/* removed: var _$attributes_456 = require('../annotations/attributes'); */; +var __scatterLineAttrs_553 = _$attributes_927.line; +var __dash_553 = _$attributes_497.dash; +var __extendFlat_553 = _$extend_590.extendFlat; -var _$attributes_491 = { +var _$attributes_553 = { _isLinkedToArray: 'shape', visible: { @@ -68358,9 +70188,23 @@ var _$attributes_491 = { }, - xref: __extendFlat_491({}, _$attributes_394.xref, { + xref: __extendFlat_553({}, _$attributes_456.xref, { }), + xsizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + xanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, x0: { valType: 'any', @@ -68374,9 +70218,23 @@ var _$attributes_491 = { }, - yref: __extendFlat_491({}, _$attributes_394.yref, { + yref: __extendFlat_553({}, _$attributes_456.yref, { }), + ysizemode: { + valType: 'enumerated', + values: ['scaled', 'pixel'], + dflt: 'scaled', + + editType: 'calcIfAutorange+arraydraw', + + }, + yanchor: { + valType: 'any', + + editType: 'calcIfAutorange+arraydraw', + + }, y0: { valType: 'any', @@ -68407,9 +70265,9 @@ var _$attributes_491 = { }, line: { - color: __extendFlat_491({}, __scatterLineAttrs_491.color, {editType: 'arraydraw'}), - width: __extendFlat_491({}, __scatterLineAttrs_491.width, {editType: 'calcIfAutorange+arraydraw'}), - dash: __extendFlat_491({}, __dash_491, {editType: 'arraydraw'}), + color: __extendFlat_553({}, __scatterLineAttrs_553.color, {editType: 'arraydraw'}), + width: __extendFlat_553({}, __scatterLineAttrs_553.width, {editType: 'calcIfAutorange+arraydraw'}), + dash: __extendFlat_553({}, __dash_553, {editType: 'arraydraw'}), editType: 'calcIfAutorange+arraydraw' }, @@ -68435,7 +70293,7 @@ var _$attributes_491 = { 'use strict'; -var _$constants_493 = { +var _$constants_555 = { segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, paramRE: /[^\s,]+/g, @@ -68486,7 +70344,7 @@ var _$constants_493 = { } }; -var _$helpers_496 = {}; +var _$helpers_558 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -68507,37 +70365,37 @@ var _$helpers_496 = {}; // will be identical, so rangeToShapePosition and shapePositionToRange can be // removed entirely. -_$helpers_496.rangeToShapePosition = function(ax) { +_$helpers_558.rangeToShapePosition = function(ax) { return (ax.type === 'log') ? ax.r2d : function(v) { return v; }; }; -_$helpers_496.shapePositionToRange = function(ax) { +_$helpers_558.shapePositionToRange = function(ax) { return (ax.type === 'log') ? ax.d2r : function(v) { return v; }; }; -_$helpers_496.decodeDate = function(convertToPx) { +_$helpers_558.decodeDate = function(convertToPx) { return function(v) { if(v.replace) v = v.replace('_', ' '); return convertToPx(v); }; }; -_$helpers_496.encodeDate = function(convertToDate) { +_$helpers_558.encodeDate = function(convertToDate) { return function(v) { return convertToDate(v).replace(' ', '_'); }; }; -_$helpers_496.getDataToPixel = function(gd, axis, isVertical) { +_$helpers_558.getDataToPixel = function(gd, axis, isVertical) { var gs = gd._fullLayout._size, dataToPixel; if(axis) { - var d2r = _$helpers_496.shapePositionToRange(axis); + var d2r = _$helpers_558.shapePositionToRange(axis); dataToPixel = function(v) { return axis._offset + axis.r2p(d2r(v, true)); }; - if(axis.type === 'date') dataToPixel = _$helpers_496.decodeDate(dataToPixel); + if(axis.type === 'date') dataToPixel = _$helpers_558.decodeDate(dataToPixel); } else if(isVertical) { dataToPixel = function(v) { return gs.t + gs.h * (1 - v); }; @@ -68549,12 +70407,12 @@ _$helpers_496.getDataToPixel = function(gd, axis, isVertical) { return dataToPixel; }; -_$helpers_496.getPixelToData = function(gd, axis, isVertical) { +_$helpers_558.getPixelToData = function(gd, axis, isVertical) { var gs = gd._fullLayout._size, pixelToData; if(axis) { - var r2d = _$helpers_496.rangeToShapePosition(axis); + var r2d = _$helpers_558.rangeToShapePosition(axis); pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); }; } else if(isVertical) { @@ -68578,39 +70436,93 @@ _$helpers_496.getPixelToData = function(gd, axis, isVertical) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$constants_493 = require('./constants'); */; -/* removed: var _$helpers_496 = require('./helpers'); */; +/* removed: var _$constants_555 = require('./constants'); */; +/* removed: var _$helpers_558 = require('./helpers'); */; -var _$calcAutorange_492 = function calcAutorange(gd) { +var _$calcAutorange_554 = function calcAutorange(gd) { var fullLayout = gd._fullLayout, - shapeList = _$lib_539.filterVisible(fullLayout.shapes); + shapeList = _$lib_601.filterVisible(fullLayout.shapes); if(!shapeList.length || !gd._fullData.length) return; for(var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i], - ppad = shape.line.width / 2; + var shape = shapeList[i]; var ax, bounds; if(shape.xref !== 'paper') { - ax = _$axes_584.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, _$constants_493.paramIsX); - if(bounds) _$axes_584.expand(ax, bounds, {ppad: ppad}); + var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0, + vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1; + ax = _$axes_647.getFromId(gd, shape.xref); + + bounds = shapeBounds(ax, vx0, vx1, shape.path, _$constants_555.paramIsX); + + if(bounds) _$axes_647.expand(ax, bounds, calcXPaddingOptions(shape)); } if(shape.yref !== 'paper') { - ax = _$axes_584.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, _$constants_493.paramIsY); - if(bounds) _$axes_584.expand(ax, bounds, {ppad: ppad}); + var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0, + vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1; + ax = _$axes_647.getFromId(gd, shape.yref); + + bounds = shapeBounds(ax, vy0, vy1, shape.path, _$constants_555.paramIsY); + if(bounds) _$axes_647.expand(ax, bounds, calcYPaddingOptions(shape)); } } }; +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} + +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} + +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2, + axisDirectionReverted = isYAxis; + + if(sizeMode === 'pixel') { + var coords = path ? + extractPathCoords(path, isYAxis ? _$constants_555.paramIsY : _$constants_555.paramIsX) : + [v0, v1]; + var maxValue = _$lib_601.aggNums(Math.max, null, coords), + minValue = _$lib_601.aggNums(Math.min, null, coords), + beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad, + afterPad = maxValue > 0 ? maxValue + ppad : ppad; + + return { + ppad: ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return {ppad: ppad}; + } +} + +function extractPathCoords(path, paramsToUse) { + var extractedCoordinates = []; + + var segments = path.match(_$constants_555.segmentRE); + segments.forEach(function(segment) { + var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn; + if(relevantParamIdx === undefined) return; + + var params = segment.substr(1).match(_$constants_555.paramRE); + if(!params || params.length < relevantParamIdx) return; + + extractedCoordinates.push(params[relevantParamIdx]); + }); + + return extractedCoordinates; +} + function shapeBounds(ax, v0, v1, path, paramsToUse) { var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c; @@ -68619,21 +70531,21 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { var min = Infinity, max = -Infinity, - segments = path.match(_$constants_493.segmentRE), + segments = path.match(_$constants_555.segmentRE), i, segment, drawnParam, params, val; - if(ax.type === 'date') convertVal = _$helpers_496.decodeDate(convertVal); + if(ax.type === 'date') convertVal = _$helpers_558.decodeDate(convertVal); for(i = 0; i < segments.length; i++) { segment = segments[i]; drawnParam = paramsToUse[segment.charAt(0)].drawn; if(drawnParam === undefined) continue; - params = segments[i].substr(1).match(_$constants_493.paramRE); + params = segments[i].substr(1).match(_$constants_555.paramRE); if(!params || params.length < drawnParam) continue; val = convertVal(params[drawnParam]); @@ -68654,19 +70566,19 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$attributes_491 = require('./attributes'); */; -/* removed: var _$helpers_496 = require('./helpers'); */; +/* removed: var _$attributes_553 = require('./attributes'); */; +/* removed: var _$helpers_558 = require('./helpers'); */; -var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { +var _$handleShapeDefaults_560 = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) { opts = opts || {}; itemOpts = itemOpts || {}; function coerce(attr, dflt) { - return _$lib_539.coerce(shapeIn, shapeOut, _$attributes_491, attr, dflt); + return _$lib_601.coerce(shapeIn, shapeOut, _$attributes_553, attr, dflt); } var visible = coerce('visible', !itemOpts.itemIsNotPlainObject); @@ -68681,32 +70593,37 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, coerce('line.dash'); var dfltType = shapeIn.path ? 'path' : 'rect', - shapeType = coerce('type', dfltType); + shapeType = coerce('type', dfltType), + xSizeMode = coerce('xsizemode'), + ySizeMode = coerce('ysizemode'); // positioning var axLetters = ['x', 'y']; for(var i = 0; i < 2; i++) { var axLetter = axLetters[i], - gdMock = {_fullLayout: fullLayout}; + attrAnchor = axLetter + 'anchor', + sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode, + gdMock = {_fullLayout: fullLayout}, + ax, + pos2r, + r2pos; // xref, yref - var axRef = _$axes_584.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + var axRef = _$axes_647.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper'); + + if(axRef !== 'paper') { + ax = _$axes_647.getFromId(gdMock, axRef); + r2pos = _$helpers_558.rangeToShapePosition(ax); + pos2r = _$helpers_558.shapePositionToRange(ax); + } + else { + pos2r = r2pos = _$lib_601.identity; + } + // Coerce x0, x1, y0, y1 if(shapeType !== 'path') { var dflt0 = 0.25, - dflt1 = 0.75, - ax, - pos2r, - r2pos; - - if(axRef !== 'paper') { - ax = _$axes_584.getFromId(gdMock, axRef); - r2pos = _$helpers_496.rangeToShapePosition(ax); - pos2r = _$helpers_496.shapePositionToRange(ax); - } - else { - pos2r = r2pos = _$lib_539.identity; - } + 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 @@ -68719,9 +70636,13 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, shapeIn[attr0] = pos2r(shapeIn[attr0], true); shapeIn[attr1] = pos2r(shapeIn[attr1], true); - // x0, x1 (and y0, y1) - _$axes_584.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); - _$axes_584.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + if(sizeMode === 'pixel') { + coerce(attr0, 0); + coerce(attr1, 10); + } else { + _$axes_647.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0); + _$axes_647.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1); + } // hack part 2 shapeOut[attr0] = r2pos(shapeOut[attr0]); @@ -68729,13 +70650,26 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, 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_647.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_539.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); + _$lib_601.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']); } return shapeOut; @@ -68752,17 +70686,17 @@ var _$handleShapeDefaults_498 = function handleShapeDefaults(shapeIn, shapeOut, 'use strict'; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; -/* removed: var _$handleShapeDefaults_498 = require('./shape_defaults'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; +/* removed: var _$handleShapeDefaults_560 = require('./shape_defaults'); */; -var _$supplyLayoutDefaults_494 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_556 = function supplyLayoutDefaults(layoutIn, layoutOut) { var opts = { name: 'shapes', - handleItemDefaults: _$handleShapeDefaults_498 + handleItemDefaults: _$handleShapeDefaults_560 }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; /** @@ -68776,17 +70710,17 @@ var _$supplyLayoutDefaults_494 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; -/* removed: var _$dragelement_433 = require('../dragelement'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; +/* removed: var _$dragelement_495 = require('../dragelement'); */; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; -/* removed: var _$constants_493 = require('./constants'); */; -/* removed: var _$helpers_496 = require('./helpers'); */; +/* removed: var _$constants_555 = require('./constants'); */; +/* removed: var _$helpers_558 = require('./helpers'); */; // Shapes are stored in gd.layout.shapes, an array of objects @@ -68798,22 +70732,26 @@ var _$supplyLayoutDefaults_494 = function supplyLayoutDefaults(layoutIn, layoutO // if opt is blank, val can be 'add' or a full options object to add a new // annotation at that point in the array, or 'remove' to delete this one -var _$draw_495 = { - draw: __draw_495, - drawOne: __drawOne_495 +var _$draw_557 = { + draw: __draw_557, + drawOne: __drawOne_557 }; -function __draw_495(gd) { +function __draw_557(gd) { var fullLayout = gd._fullLayout; // Remove previous shapes before drawing new in shapes in fullLayout.shapes fullLayout._shapeUpperLayer.selectAll('path').remove(); fullLayout._shapeLowerLayer.selectAll('path').remove(); - fullLayout._shapeSubplotLayers.selectAll('path').remove(); + + for(var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if(shapelayer) shapelayer.selectAll('path').remove(); + } for(var i = 0; i < fullLayout.shapes.length; i++) { if(fullLayout.shapes[i].visible) { - __drawOne_495(gd, i); + __drawOne_557(gd, i); } } @@ -68821,7 +70759,7 @@ function __draw_495(gd) { // return Plots.previousPromises(gd); } -function __drawOne_495(gd, index) { +function __drawOne_557(gd, index) { // remove the existing shape if there is one. // because indices can change, we need to look in all shape layers gd._fullLayout._paperdiv @@ -68867,30 +70805,33 @@ function __drawOne_495(gd, index) { var path = shapeLayer.append('path') .attr(attrs) .style('opacity', options.opacity) - .call(_$color_411.stroke, lineColor) - .call(_$color_411.fill, options.fillcolor) - .call(_$drawing_436.dashLine, options.line.dash, options.line.width); + .call(_$color_473.stroke, lineColor) + .call(_$color_473.fill, options.fillcolor) + .call(_$drawing_498.dashLine, options.line.dash, options.line.width); // note that for layer="below" the clipAxes can be different from the // subplot we're drawing this in. This could cause problems if the shape // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452 var clipAxes = (options.xref + options.yref).replace(/paper/g, ''); - path.call(_$drawing_436.setClipUrl, clipAxes ? + path.call(_$drawing_498.setClipUrl, clipAxes ? ('clip' + gd._fullLayout._uid + clipAxes) : null ); - if(gd._context.edits.shapePosition) __setupDragElement_495(gd, path, options, index); + if(gd._context.edits.shapePosition) __setupDragElement_557(gd, path, options, index); } } -function __setupDragElement_495(gd, shapePath, shapeOptions, index) { +function __setupDragElement_557(gd, shapePath, shapeOptions, index) { var MINWIDTH = 10, MINHEIGHT = 10; + var xPixelSized = shapeOptions.xsizemode === 'pixel', + yPixelSized = shapeOptions.ysizemode === 'pixel'; + var update; - var x0, y0, x1, y1, astrX0, astrY0, astrX1, astrY1; + var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor; var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE; var pathIn, astrPath; @@ -68902,14 +70843,17 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { prepFn: startDrag, doneFn: endDrag }, - dragBBox = dragOptions.element.getBoundingClientRect(), dragMode; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); shapePath.node().onmousemove = updateDragMode; function updateDragMode(evt) { + // 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, @@ -68917,10 +70861,10 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { x = evt.clientX - dragBBox.left, y = evt.clientY - dragBBox.top, cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ? - _$dragelement_433.getCursor(x / w, 1 - y / h) : + _$dragelement_495.getCursor(x / w, 1 - y / h) : 'move'; - _$setCursor_558(shapePath, cursor); + _$setCursor_621(shapePath, cursor); // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w' dragMode = cursor.split('-')[0]; @@ -68928,25 +70872,35 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { function startDrag(evt) { // setup conversion functions - xa = _$axes_584.getFromId(gd, shapeOptions.xref); - ya = _$axes_584.getFromId(gd, shapeOptions.yref); + xa = _$axes_647.getFromId(gd, shapeOptions.xref); + ya = _$axes_647.getFromId(gd, shapeOptions.yref); - x2p = _$helpers_496.getDataToPixel(gd, xa); - y2p = _$helpers_496.getDataToPixel(gd, ya, true); - p2x = _$helpers_496.getPixelToData(gd, xa); - p2y = _$helpers_496.getPixelToData(gd, ya, true); + x2p = _$helpers_558.getDataToPixel(gd, xa); + y2p = _$helpers_558.getDataToPixel(gd, ya, true); + p2x = _$helpers_558.getPixelToData(gd, xa); + p2y = _$helpers_558.getPixelToData(gd, ya, true); // setup update strings and initial values var astr = 'shapes[' + index + ']'; + + if(xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + astrXAnchor = astr + '.xanchor'; + } + if(yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + astrYAnchor = astr + '.yanchor'; + } + if(shapeOptions.type === 'path') { pathIn = shapeOptions.path; astrPath = astr + '.path'; } else { - x0 = x2p(shapeOptions.x0); - y0 = y2p(shapeOptions.y0); - x1 = x2p(shapeOptions.x1); - y1 = y2p(shapeOptions.y1); + 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); astrX0 = astr + '.x0'; astrY0 = astr + '.y0'; @@ -68962,7 +70916,10 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { w0 = x1; astrW = astr + '.x1'; optW = 'x1'; e0 = x0; astrE = astr + '.x0'; optE = 'x0'; } - if(y0 < y1) { + + // 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; astrN = astr + '.y0'; optN = 'y0'; s0 = y1; astrS = astr + '.y1'; optS = 'y1'; } @@ -68979,26 +70936,47 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { } function endDrag() { - _$setCursor_558(shapePath); - _$registry_668.call('relayout', gd, update); + _$setCursor_621(shapePath); + _$registry_731.call('relayout', gd, update); } function moveShape(dx, dy) { if(shapeOptions.type === 'path') { - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_496.encodeDate(moveX); + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_496.encodeDate(moveY); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_558.encodeDate(moveX); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_558.encodeDate(moveY); + } shapeOptions.path = movePath(pathIn, moveX, moveY); update[astrPath] = shapeOptions.path; } else { - update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); - update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); - update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); - update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + update[astrX0] = shapeOptions.x0 = p2x(x0 + dx); + update[astrX1] = shapeOptions.x1 = p2x(x1 + dx); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + update[astrY0] = shapeOptions.y0 = p2y(y0 + dy); + update[astrY1] = shapeOptions.y1 = p2y(y1 + dy); + } } shapePath.attr('d', getPathString(gd, shapeOptions)); @@ -69007,11 +70985,23 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { function resizeShape(dx, dy) { if(shapeOptions.type === 'path') { // TODO: implement path resize - var moveX = function moveX(x) { return p2x(x2p(x) + dx); }; - if(xa && xa.type === 'date') moveX = _$helpers_496.encodeDate(moveX); + var noOp = function(coord) { return coord; }, + moveX = noOp, + moveY = noOp; - var moveY = function moveY(y) { return p2y(y2p(y) + dy); }; - if(ya && ya.type === 'date') moveY = _$helpers_496.encodeDate(moveY); + if(xPixelSized) { + update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx); + } else { + moveX = function moveX(x) { return p2x(x2p(x) + dx); }; + if(xa && xa.type === 'date') moveX = _$helpers_558.encodeDate(moveX); + } + + if(yPixelSized) { + update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy); + } else { + moveY = function moveY(y) { return p2y(y2p(y) + dy); }; + if(ya && ya.type === 'date') moveY = _$helpers_558.encodeDate(moveY); + } shapeOptions.path = movePath(pathIn, moveX, moveY); update[astrPath] = shapeOptions.path; @@ -69022,14 +71012,21 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { newW = (~dragMode.indexOf('w')) ? w0 + dx : w0, newE = (~dragMode.indexOf('e')) ? e0 + dx : e0; - if(newS - newN > MINHEIGHT) { - update[astrN] = shapeOptions[optN] = p2y(newN); - update[astrS] = shapeOptions[optS] = p2y(newS); - } + // 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)) { + update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN); + update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS); + } if(newE - newW > MINWIDTH) { - update[astrW] = shapeOptions[optW] = p2x(newW); - update[astrE] = shapeOptions[optE] = p2x(newE); + update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW); + update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE); } } @@ -69039,16 +71036,14 @@ function __setupDragElement_495(gd, shapePath, shapeOptions, index) { function getPathString(gd, options) { var type = options.type, - xa = _$axes_584.getFromId(gd, options.xref), - ya = _$axes_584.getFromId(gd, options.yref), + xa = _$axes_647.getFromId(gd, options.xref), + ya = _$axes_647.getFromId(gd, options.yref), gs = gd._fullLayout._size, - x2r, - x2p, - y2r, - y2p; + x2r, x2p, y2r, y2p, + x0, x1, y0, y1; if(xa) { - x2r = _$helpers_496.shapePositionToRange(xa); + x2r = _$helpers_558.shapePositionToRange(xa); x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); }; } else { @@ -69056,7 +71051,7 @@ function getPathString(gd, options) { } if(ya) { - y2r = _$helpers_496.shapePositionToRange(ya); + y2r = _$helpers_558.shapePositionToRange(ya); y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); }; } else { @@ -69064,15 +71059,30 @@ function getPathString(gd, options) { } if(type === 'path') { - if(xa && xa.type === 'date') x2p = _$helpers_496.decodeDate(x2p); - if(ya && ya.type === 'date') y2p = _$helpers_496.decodeDate(y2p); - return convertPath(options.path, x2p, y2p); + if(xa && xa.type === 'date') x2p = _$helpers_558.decodeDate(x2p); + if(ya && ya.type === 'date') y2p = _$helpers_558.decodeDate(y2p); + return convertPath(options, x2p, y2p); } - var x0 = x2p(options.x0), - x1 = x2p(options.x1), - y0 = y2p(options.y0), + 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'; @@ -69089,18 +71099,30 @@ function getPathString(gd, options) { } -function convertPath(pathIn, x2p, y2p) { - // convert an SVG path string from data units to pixels - return pathIn.replace(_$constants_493.segmentRE, function(segment) { +function convertPath(options, x2p, y2p) { + var pathIn = options.path, + xSizemode = options.xsizemode, + ySizemode = options.ysizemode, + xAnchor = options.xanchor, + yAnchor = options.yanchor; + + + return pathIn.replace(_$constants_555.segmentRE, function(segment) { var paramNumber = 0, segmentType = segment.charAt(0), - xParams = _$constants_493.paramIsX[segmentType], - yParams = _$constants_493.paramIsY[segmentType], - nParams = _$constants_493.numParams[segmentType]; + xParams = _$constants_555.paramIsX[segmentType], + yParams = _$constants_555.paramIsY[segmentType], + nParams = _$constants_555.numParams[segmentType]; - var paramString = segment.substr(1).replace(_$constants_493.paramRE, function(param) { - if(xParams[paramNumber]) param = x2p(param); - else if(yParams[paramNumber]) param = y2p(param); + var paramString = segment.substr(1).replace(_$constants_555.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'; @@ -69109,7 +71131,7 @@ function convertPath(pathIn, x2p, y2p) { if(paramNumber > nParams) { paramString = paramString.replace(/[\s,]*X.*/, ''); - _$lib_539.log('Ignoring extra params in segment ' + segment); + _$lib_601.log('Ignoring extra params in segment ' + segment); } return segmentType + paramString; @@ -69117,14 +71139,14 @@ function convertPath(pathIn, x2p, y2p) { } function movePath(pathIn, moveX, moveY) { - return pathIn.replace(_$constants_493.segmentRE, function(segment) { + return pathIn.replace(_$constants_555.segmentRE, function(segment) { var paramNumber = 0, segmentType = segment.charAt(0), - xParams = _$constants_493.paramIsX[segmentType], - yParams = _$constants_493.paramIsY[segmentType], - nParams = _$constants_493.numParams[segmentType]; + xParams = _$constants_555.paramIsX[segmentType], + yParams = _$constants_555.paramIsY[segmentType], + nParams = _$constants_555.numParams[segmentType]; - var paramString = segment.substr(1).replace(_$constants_493.paramRE, function(param) { + var paramString = segment.substr(1).replace(_$constants_555.paramRE, function(param) { if(paramNumber >= nParams) return param; if(xParams[paramNumber]) param = moveX(param); @@ -69150,19 +71172,19 @@ function movePath(pathIn, moveX, moveY) { 'use strict'; -/* removed: var _$draw_495 = require('./draw'); */; +/* removed: var _$draw_557 = require('./draw'); */; -var _$shapes_497 = { +var _$shapes_559 = { moduleType: 'component', name: 'shapes', - layoutAttributes: _$attributes_491, - supplyLayoutDefaults: _$supplyLayoutDefaults_494, - includeBasePlot: _$makeIncludeComponents_594('shapes'), + layoutAttributes: _$attributes_553, + supplyLayoutDefaults: _$supplyLayoutDefaults_556, + includeBasePlot: _$makeIncludeComponents_657('shapes'), - calcAutorange: _$calcAutorange_492, - draw: _$draw_495.draw, - drawOne: _$draw_495.drawOne + calcAutorange: _$calcAutorange_554, + draw: _$draw_557.draw, + drawOne: _$draw_557.drawOne }; /** @@ -69177,7 +71199,7 @@ var _$shapes_497 = { 'use strict'; -var _$constants_500 = { +var _$constants_562 = { // layout attribute name name: 'sliders', @@ -69271,7 +71293,7 @@ var _$constants_500 = { // This is used exclusively by components inside component arrays, // hence the 'arraydraw' editType. If this ever gets used elsewhere // we could generalize it as a function ala font_attributes -var _$pad_attributes_646 = { +var _$pad_attributes_708 = { t: { valType: 'number', dflt: 0, @@ -69313,12 +71335,12 @@ var _$pad_attributes_646 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$pad_attributes_646 = require('../../plots/pad_attributes'); */; -var __extendDeepAll_499 = _$extend_528.extendDeepAll; -var __overrideAll_499 = _$edit_types_569.overrideAll; -/* removed: var _$animation_attributes_579 = require('../../plots/animation_attributes'); */; -/* removed: var _$constants_500 = require('./constants'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$pad_attributes_708 = require('../../plots/pad_attributes'); */; +var __extendDeepAll_561 = _$extend_590.extendDeepAll; +var __overrideAll_561 = _$edit_types_632.overrideAll; +/* removed: var _$animation_attributes_642 = require('../../plots/animation_attributes'); */; +/* removed: var _$constants_562 = require('./constants'); */; var stepsAttrs = { _isLinkedToArray: 'step', @@ -69359,7 +71381,7 @@ var stepsAttrs = { } }; -var _$attributes_499 = __overrideAll_499({ +var _$attributes_561 = __overrideAll_561({ _isLinkedToArray: 'slider', visible: { @@ -69401,7 +71423,7 @@ var _$attributes_499 = __overrideAll_499({ }, - pad: __extendDeepAll_499({}, _$pad_attributes_646, { + pad: __extendDeepAll_561({}, _$pad_attributes_708, { }, {t: {dflt: 20}}), xanchor: { @@ -69437,7 +71459,7 @@ var _$attributes_499 = __overrideAll_499({ }, easing: { valType: 'enumerated', - values: _$animation_attributes_579.transition.easing.values, + values: _$animation_attributes_642.transition.easing.values, dflt: 'cubic-in-out', @@ -69479,50 +71501,50 @@ var _$attributes_499 = __overrideAll_499({ }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ }) }, - font: _$font_attributes_611({ + font: _$font_attributes_673({ }), activebgcolor: { valType: 'color', - dflt: _$constants_500.gripBgActiveColor, + dflt: _$constants_562.gripBgActiveColor, }, bgcolor: { valType: 'color', - dflt: _$constants_500.railBgColor, + dflt: _$constants_562.railBgColor, }, bordercolor: { valType: 'color', - dflt: _$constants_500.railBorderColor, + dflt: _$constants_562.railBorderColor, }, borderwidth: { valType: 'number', min: 0, - dflt: _$constants_500.railBorderWidth, + dflt: _$constants_562.railBorderWidth, }, ticklen: { valType: 'number', min: 0, - dflt: _$constants_500.tickLength, + dflt: _$constants_562.tickLength, }, tickcolor: { valType: 'color', - dflt: _$constants_500.tickColor, + dflt: _$constants_562.tickColor, }, @@ -69536,7 +71558,7 @@ var _$attributes_499 = __overrideAll_499({ minorticklen: { valType: 'number', min: 0, - dflt: _$constants_500.minorTickLength, + dflt: _$constants_562.minorTickLength, } @@ -69552,29 +71574,29 @@ var _$attributes_499 = __overrideAll_499({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_499 = require('./attributes'); */; -/* removed: var _$constants_500 = require('./constants'); */; +/* removed: var _$attributes_561 = require('./attributes'); */; +/* removed: var _$constants_562 = require('./constants'); */; -var __name_501 = _$constants_500.name; -var stepAttrs = _$attributes_499.steps; +var __name_563 = _$constants_562.name; +var stepAttrs = _$attributes_561.steps; -var _$slidersDefaults_501 = function slidersDefaults(layoutIn, layoutOut) { +var _$slidersDefaults_563 = function slidersDefaults(layoutIn, layoutOut) { var opts = { - name: __name_501, + name: __name_563, handleItemDefaults: sliderDefaults }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; function sliderDefaults(sliderIn, sliderOut, layoutOut) { function coerce(attr, dflt) { - return _$lib_539.coerce(sliderIn, sliderOut, _$attributes_499, attr, dflt); + return _$lib_601.coerce(sliderIn, sliderOut, _$attributes_561, attr, dflt); } var steps = stepsDefaults(sliderIn, sliderOut); @@ -69586,7 +71608,7 @@ function sliderDefaults(sliderIn, sliderOut, layoutOut) { coerce('x'); coerce('y'); - _$lib_539.noneOrAll(sliderIn, sliderOut, ['x', 'y']); + _$lib_601.noneOrAll(sliderIn, sliderOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); @@ -69599,7 +71621,7 @@ function sliderDefaults(sliderIn, sliderOut, layoutOut) { coerce('pad.b'); coerce('pad.l'); - _$lib_539.coerceFont(coerce, 'font', layoutOut.font); + _$lib_601.coerceFont(coerce, 'font', layoutOut.font); var currentValueIsVisible = coerce('currentvalue.visible'); @@ -69609,7 +71631,7 @@ function sliderDefaults(sliderIn, sliderOut, layoutOut) { coerce('currentvalue.suffix'); coerce('currentvalue.offset'); - _$lib_539.coerceFont(coerce, 'currentvalue.font', sliderOut.font); + _$lib_601.coerceFont(coerce, 'currentvalue.font', sliderOut.font); } coerce('transition.duration'); @@ -69632,7 +71654,7 @@ function stepsDefaults(sliderIn, sliderOut) { var valueIn, valueOut; function coerce(attr, dflt) { - return _$lib_539.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + return _$lib_601.coerce(valueIn, valueOut, stepAttrs, attr, dflt); } for(var i = 0; i < valuesIn.length; i++) { @@ -69641,7 +71663,7 @@ function stepsDefaults(sliderIn, sliderOut) { coerce('method'); - if(!_$lib_539.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { + if(!_$lib_601.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) { continue; } @@ -69664,58 +71686,57 @@ function stepsDefaults(sliderIn, sliderOut) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; - -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_463 = require('../legend/anchor_utils'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$constants_500 = require('./constants'); */; -/* removed: var _$alignment_511 = require('../../constants/alignment'); */; -var __LINE_SPACING_502 = _$alignment_511.LINE_SPACING; -var __FROM_TL_502 = _$alignment_511.FROM_TL; -var __FROM_BR_502 = _$alignment_511.FROM_BR; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_525 = require('../legend/anchor_utils'); */; +/* removed: var _$constants_562 = require('./constants'); */; +/* removed: var _$alignment_573 = require('../../constants/alignment'); */; +var __LINE_SPACING_564 = _$alignment_573.LINE_SPACING; +var __FROM_TL_564 = _$alignment_573.FROM_TL; +var __FROM_BR_564 = _$alignment_573.FROM_BR; -var _$draw_502 = function draw(gd) { +var _$draw_564 = function draw(gd) { var fullLayout = gd._fullLayout, sliderData = makeSliderData(fullLayout, gd); // draw a container for *all* sliders: var sliders = fullLayout._infolayer - .selectAll('g.' + _$constants_500.containerClassName) + .selectAll('g.' + _$constants_562.containerClassName) .data(sliderData.length > 0 ? [0] : []); sliders.enter().append('g') - .classed(_$constants_500.containerClassName, true) + .classed(_$constants_562.containerClassName, true) .style('cursor', 'ew-resize'); sliders.exit().remove(); // If no more sliders, clear the margisn: - if(sliders.exit().size()) __clearPushMargins_502(gd); + if(sliders.exit().size()) __clearPushMargins_564(gd); // Return early if no menus visible: if(sliderData.length === 0) return; - var sliderGroups = sliders.selectAll('g.' + _$constants_500.groupClassName) + var sliderGroups = sliders.selectAll('g.' + _$constants_562.groupClassName) .data(sliderData, keyFunction); sliderGroups.enter().append('g') - .classed(_$constants_500.groupClassName, true); + .classed(_$constants_562.groupClassName, true); sliderGroups.exit().each(function(sliderOpts) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); sliderOpts._commandObserver.remove(); delete sliderOpts._commandObserver; - _$plots_647.autoMargin(gd, _$constants_500.autoMarginIdRoot + sliderOpts._index); + _$plots_709.autoMargin(gd, _$constants_562.autoMarginIdRoot + sliderOpts._index); }); // Find the dimensions of the sliders: @@ -69728,11 +71749,11 @@ var _$draw_502 = function draw(gd) { // If it has fewer than two options, it's not really a slider: if(sliderOpts.steps.length < 2) return; - var gSlider = _$d3_127.select(this); + var gSlider = _$d3_130.select(this); computeLabelSteps(sliderOpts); - _$plots_647.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { + _$plots_709.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) { // NB: Same as below. This is *not* always the same as sliderOpts since // if a new set of steps comes in, the reference in this callback would // be invalid. We need to refetch it from the slider group, which is @@ -69747,13 +71768,13 @@ var _$draw_502 = function draw(gd) { setActive(gd, gSlider, opts, data.index, false, true); }); - drawSlider(gd, _$d3_127.select(this), sliderOpts); + drawSlider(gd, _$d3_130.select(this), sliderOpts); }); }; // This really only just filters by visibility: function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[_$constants_500.name], + var contOpts = fullLayout[_$constants_562.name], sliderData = []; for(var i = 0; i < contOpts.length; i++) { @@ -69773,23 +71794,23 @@ function keyFunction(opts) { // Compute the dimensions (mutates sliderOpts): function findDimensions(gd, sliderOpts) { - var sliderLabels = _$drawing_436.tester.selectAll('g.' + _$constants_500.labelGroupClass) + var sliderLabels = _$drawing_498.tester.selectAll('g.' + _$constants_562.labelGroupClass) .data(sliderOpts.steps); sliderLabels.enter().append('g') - .classed(_$constants_500.labelGroupClass, true); + .classed(_$constants_562.labelGroupClass, true); // loop over fake buttons to find width / height var maxLabelWidth = 0; var labelHeight = 0; sliderLabels.each(function(stepOpts) { - var labelGroup = _$d3_127.select(this); + var labelGroup = _$d3_130.select(this); var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts); var textNode = text.node(); if(textNode) { - var bBox = _$drawing_436.bBox(textNode); + var bBox = _$drawing_498.bBox(textNode); labelHeight = Math.max(labelHeight, bBox.height); maxLabelWidth = Math.max(maxLabelWidth, bBox.width); } @@ -69800,8 +71821,8 @@ function findDimensions(gd, sliderOpts) { var dims = sliderOpts._dims = {}; dims.inputAreaWidth = Math.max( - _$constants_500.railWidth, - _$constants_500.gripHeight + _$constants_562.railWidth, + _$constants_562.gripHeight ); // calculate some overall dimensions - some of these are needed for @@ -69822,9 +71843,9 @@ function findDimensions(gd, sliderOpts) { dims.inputAreaStart = 0; dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - var textableInputLength = dims.inputAreaLength - 2 * _$constants_500.stepInset; + var textableInputLength = dims.inputAreaLength - 2 * _$constants_562.stepInset; var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1); - var computedSpacePerLabel = maxLabelWidth + _$constants_500.labelPadding; + var computedSpacePerLabel = maxLabelWidth + _$constants_562.labelPadding; dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); dims.labelHeight = labelHeight; @@ -69837,12 +71858,12 @@ function findDimensions(gd, sliderOpts) { if(sliderOpts.currentvalue.visible) { // Get the dimensions of the current value label: - var dummyGroup = _$drawing_436.tester.append('g'); + var dummyGroup = _$drawing_498.tester.append('g'); sliderLabels.each(function(stepOpts) { var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = (curValPrefix.node() && _$drawing_436.bBox(curValPrefix.node())) || {width: 0, height: 0}; - var lines = _$svg_text_utils_562.lineCount(curValPrefix); + var curValSize = (curValPrefix.node() && _$drawing_498.bBox(curValPrefix.node())) || {width: 0, height: 0}; + var lines = _$svg_text_utils_625.lineCount(curValPrefix); dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); @@ -69853,24 +71874,24 @@ function findDimensions(gd, sliderOpts) { dummyGroup.remove(); } - dims.height = dims.currentValueTotalHeight + _$constants_500.tickOffset + sliderOpts.ticklen + _$constants_500.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + dims.height = dims.currentValueTotalHeight + _$constants_562.tickOffset + sliderOpts.ticklen + _$constants_562.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(sliderOpts)) { + if(_$anchor_utils_525.isRightAnchor(sliderOpts)) { dims.lx -= dims.outerLength; xanchor = 'right'; } - if(_$anchor_utils_463.isCenterAnchor(sliderOpts)) { + if(_$anchor_utils_525.isCenterAnchor(sliderOpts)) { dims.lx -= dims.outerLength / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(sliderOpts)) { + if(_$anchor_utils_525.isBottomAnchor(sliderOpts)) { dims.ly -= dims.height; yanchor = 'bottom'; } - if(_$anchor_utils_463.isMiddleAnchor(sliderOpts)) { + if(_$anchor_utils_525.isMiddleAnchor(sliderOpts)) { dims.ly -= dims.height / 2; yanchor = 'middle'; } @@ -69880,13 +71901,13 @@ function findDimensions(gd, sliderOpts) { dims.lx = Math.round(dims.lx); dims.ly = Math.round(dims.ly); - _$plots_647.autoMargin(gd, _$constants_500.autoMarginIdRoot + sliderOpts._index, { + _$plots_709.autoMargin(gd, _$constants_562.autoMarginIdRoot + sliderOpts._index, { x: sliderOpts.x, y: sliderOpts.y, - l: dims.outerLength * __FROM_TL_502[xanchor], - r: dims.outerLength * __FROM_BR_502[xanchor], - b: dims.height * __FROM_BR_502[yanchor], - t: dims.height * __FROM_TL_502[yanchor] + l: dims.outerLength * __FROM_TL_564[xanchor], + r: dims.outerLength * __FROM_BR_564[xanchor], + b: dims.height * __FROM_BR_564[yanchor], + t: dims.height * __FROM_TL_564[yanchor] }); } @@ -69912,7 +71933,7 @@ function drawSlider(gd, sliderGroup, sliderOpts) { var dims = sliderOpts._dims; // Position the rectangle: - _$drawing_436.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + _$drawing_498.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false); sliderGroup.call(drawCurrentValue, sliderOpts); @@ -69922,17 +71943,15 @@ function drawSlider(gd, sliderGroup, sliderOpts) { function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { if(!sliderOpts.currentvalue.visible) return; - var x0, textAnchor; - var text = sliderGroup.selectAll('text') - .data([0]); var dims = sliderOpts._dims; + var x0, textAnchor; switch(sliderOpts.currentvalue.xanchor) { case 'right': // This is anchored left and adjusted by the width of the longest label // so that the prefix doesn't move. The goal of this is to emphasize // what's actually changing and make the update less distracting. - x0 = dims.inputAreaLength - _$constants_500.currentValueInset - dims.currentValueMaxWidth; + x0 = dims.inputAreaLength - _$constants_562.currentValueInset - dims.currentValueMaxWidth; textAnchor = 'left'; break; case 'center': @@ -69940,17 +71959,17 @@ function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { textAnchor = 'middle'; break; default: - x0 = _$constants_500.currentValueInset; + x0 = _$constants_562.currentValueInset; textAnchor = 'left'; } - text.enter().append('text') - .classed(_$constants_500.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': textAnchor, - 'data-notex': 1 - }); + var text = _$lib_601.ensureSingle(sliderGroup, 'text', _$constants_562.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': textAnchor, + 'data-notex': 1 + }); + }); var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ''; @@ -69965,88 +71984,78 @@ function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { str += sliderOpts.currentvalue.suffix; } - text.call(_$drawing_436.font, sliderOpts.currentvalue.font) + text.call(_$drawing_498.font, sliderOpts.currentvalue.font) .text(str) - .call(_$svg_text_utils_562.convertToTspans, sliderOpts._gd); + .call(_$svg_text_utils_625.convertToTspans, sliderOpts._gd); - var lines = _$svg_text_utils_562.lineCount(text); + var lines = _$svg_text_utils_625.lineCount(text); var y0 = (dims.currentValueMaxLines + 1 - lines) * - sliderOpts.currentvalue.font.size * __LINE_SPACING_502; + sliderOpts.currentvalue.font.size * __LINE_SPACING_564; - _$svg_text_utils_562.positionText(text, x0, y0); + _$svg_text_utils_625.positionText(text, x0, y0); return text; } function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = sliderGroup.selectAll('rect.' + _$constants_500.gripRectClass) - .data([0]); - - grip.enter().append('rect') - .classed(_$constants_500.gripRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + var grip = _$lib_601.ensureSingle(sliderGroup, 'rect', _$constants_562.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); grip.attr({ - width: _$constants_500.gripWidth, - height: _$constants_500.gripHeight, - rx: _$constants_500.gripRadius, - ry: _$constants_500.gripRadius, + width: _$constants_562.gripWidth, + height: _$constants_562.gripHeight, + rx: _$constants_562.gripRadius, + ry: _$constants_562.gripRadius, }) - .call(_$color_411.stroke, sliderOpts.bordercolor) - .call(_$color_411.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + .call(_$color_473.stroke, sliderOpts.bordercolor) + .call(_$color_473.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); } function drawLabel(item, data, sliderOpts) { - var text = item.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed(_$constants_500.labelClass, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'middle', - 'data-notex': 1 - }); + var text = _$lib_601.ensureSingle(item, 'text', _$constants_562.labelClass, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'middle', + 'data-notex': 1 + }); + }); - text.call(_$drawing_436.font, sliderOpts.font) + text.call(_$drawing_498.font, sliderOpts.font) .text(data.step.label) - .call(_$svg_text_utils_562.convertToTspans, sliderOpts._gd); + .call(_$svg_text_utils_625.convertToTspans, sliderOpts._gd); return text; } function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = sliderGroup.selectAll('g.' + _$constants_500.labelsClass) - .data([0]); + var labels = _$lib_601.ensureSingle(sliderGroup, 'g', _$constants_562.labelsClass); var dims = sliderOpts._dims; - labels.enter().append('g') - .classed(_$constants_500.labelsClass, true); - - var labelItems = labels.selectAll('g.' + _$constants_500.labelGroupClass) + var labelItems = labels.selectAll('g.' + _$constants_562.labelGroupClass) .data(dims.labelSteps); labelItems.enter().append('g') - .classed(_$constants_500.labelGroupClass, true); + .classed(_$constants_562.labelGroupClass, true); labelItems.exit().remove(); labelItems.each(function(d) { - var item = _$d3_127.select(this); + var item = _$d3_130.select(this); item.call(drawLabel, d, sliderOpts); - _$drawing_436.setTranslate(item, + _$drawing_498.setTranslate(item, normalizedValueToPosition(sliderOpts, d.fraction), - _$constants_500.tickOffset + + _$constants_562.tickOffset + sliderOpts.ticklen + // position is the baseline of the top line of text only, even // if the label spans multiple lines - sliderOpts.font.size * __LINE_SPACING_502 + - _$constants_500.labelOffset + + sliderOpts.font.size * __LINE_SPACING_564 + + _$constants_562.labelOffset + dims.currentValueTotalHeight ); }); @@ -70090,7 +72099,7 @@ function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) if(!_step.method) return; if(_step.execute) { - _$plots_647.executeAPICommand(gd, _step.method, _step.args); + _$plots_709.executeAPICommand(gd, _step.method, _step.args); } sliderGroup._nextMethod = null; @@ -70102,7 +72111,7 @@ function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) function attachGripEvents(item, gd, sliderGroup) { var node = sliderGroup.node(); - var $gd = _$d3_127.select(gd); + var $gd = _$d3_130.select(gd); // NB: This is *not* the same as sliderOpts itself! These callbacks // are in a closure so this array won't actually be correct if the @@ -70117,26 +72126,26 @@ function attachGripEvents(item, gd, sliderGroup) { var sliderOpts = getSliderOpts(); gd.emit('plotly_sliderstart', {slider: sliderOpts}); - var grip = sliderGroup.select('.' + _$constants_500.gripRectClass); + var grip = sliderGroup.select('.' + _$constants_562.gripRectClass); - _$d3_127.event.stopPropagation(); - _$d3_127.event.preventDefault(); - grip.call(_$color_411.fill, sliderOpts.activebgcolor); + _$d3_130.event.stopPropagation(); + _$d3_130.event.preventDefault(); + grip.call(_$color_473.fill, sliderOpts.activebgcolor); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_127.mouse(node)[0]); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_130.mouse(node)[0]); handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); sliderOpts._dragging = true; $gd.on('mousemove', function() { var sliderOpts = getSliderOpts(); - var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_127.mouse(node)[0]); + var normalizedPosition = positionToNormalizedValue(sliderOpts, _$d3_130.mouse(node)[0]); handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false); }); $gd.on('mouseup', function() { var sliderOpts = getSliderOpts(); sliderOpts._dragging = false; - grip.call(_$color_411.fill, sliderOpts.bgcolor); + grip.call(_$color_473.fill, sliderOpts.bgcolor); $gd.on('mouseup', null); $gd.on('mousemove', null); @@ -70149,12 +72158,12 @@ function attachGripEvents(item, gd, sliderGroup) { } function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll('rect.' + _$constants_500.tickRectClass) + var tick = sliderGroup.selectAll('rect.' + _$constants_562.tickRectClass) .data(sliderOpts.steps); var dims = sliderOpts._dims; tick.enter().append('rect') - .classed(_$constants_500.tickRectClass, true); + .classed(_$constants_562.tickRectClass, true); tick.exit().remove(); @@ -70165,15 +72174,15 @@ function drawTicks(sliderGroup, sliderOpts) { tick.each(function(d, i) { var isMajor = i % dims.labelStride === 0; - var item = _$d3_127.select(this); + var item = _$d3_130.select(this); item .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen}) - .call(_$color_411.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + .call(_$color_473.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - _$drawing_436.setTranslate(item, + _$drawing_498.setTranslate(item, normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? _$constants_500.tickOffset : _$constants_500.minorTickOffset) + dims.currentValueTotalHeight + (isMajor ? _$constants_562.tickOffset : _$constants_562.minorTickOffset) + dims.currentValueTotalHeight ); }); @@ -70194,7 +72203,7 @@ function computeLabelSteps(sliderOpts) { } function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { - var grip = sliderGroup.select('rect.' + _$constants_500.gripRectClass); + var grip = sliderGroup.select('rect.' + _$constants_562.gripRectClass); var x = normalizedValueToPosition(sliderOpts, position); @@ -70211,78 +72220,70 @@ function setGripPosition(sliderGroup, sliderOpts, position, doTransition) { // Drawing.setTranslate doesn't work here becasue of the transition duck-typing. // It's also not necessary because there are no other transitions to preserve. - el.attr('transform', 'translate(' + (x - _$constants_500.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); + el.attr('transform', 'translate(' + (x - _$constants_562.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')'); } // Convert a number from [0-1] to a pixel position relative to the slider group container: function normalizedValueToPosition(sliderOpts, normalizedPosition) { var dims = sliderOpts._dims; - return dims.inputAreaStart + _$constants_500.stepInset + - (dims.inputAreaLength - 2 * _$constants_500.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); + return dims.inputAreaStart + _$constants_562.stepInset + + (dims.inputAreaLength - 2 * _$constants_562.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); } // Convert a position relative to the slider group to a nubmer in [0, 1] function positionToNormalizedValue(sliderOpts, position) { var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - _$constants_500.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_500.stepInset - 2 * dims.inputAreaStart))); + return Math.min(1, Math.max(0, (position - _$constants_562.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * _$constants_562.stepInset - 2 * dims.inputAreaStart))); } function drawTouchRect(sliderGroup, gd, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_500.railTouchRectClass) - .data([0]); var dims = sliderOpts._dims; - - rect.enter().append('rect') - .classed(_$constants_500.railTouchRectClass, true) - .call(attachGripEvents, gd, sliderGroup, sliderOpts) - .style('pointer-events', 'all'); + var rect = _$lib_601.ensureSingle(sliderGroup, 'rect', _$constants_562.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts) + .style('pointer-events', 'all'); + }); rect.attr({ width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, _$constants_500.tickOffset + sliderOpts.ticklen + dims.labelHeight) + height: Math.max(dims.inputAreaWidth, _$constants_562.tickOffset + sliderOpts.ticklen + dims.labelHeight) }) - .call(_$color_411.fill, sliderOpts.bgcolor) + .call(_$color_473.fill, sliderOpts.bgcolor) .attr('opacity', 0); - _$drawing_436.setTranslate(rect, 0, dims.currentValueTotalHeight); + _$drawing_498.setTranslate(rect, 0, dims.currentValueTotalHeight); } function drawRail(sliderGroup, sliderOpts) { - var rect = sliderGroup.selectAll('rect.' + _$constants_500.railRectClass) - .data([0]); var dims = sliderOpts._dims; - - rect.enter().append('rect') - .classed(_$constants_500.railRectClass, true); - - var computedLength = dims.inputAreaLength - _$constants_500.railInset * 2; + var computedLength = dims.inputAreaLength - _$constants_562.railInset * 2; + var rect = _$lib_601.ensureSingle(sliderGroup, 'rect', _$constants_562.railRectClass); rect.attr({ width: computedLength, - height: _$constants_500.railWidth, - rx: _$constants_500.railRadius, - ry: _$constants_500.railRadius, + height: _$constants_562.railWidth, + rx: _$constants_562.railRadius, + ry: _$constants_562.railRadius, 'shape-rendering': 'crispEdges' }) - .call(_$color_411.stroke, sliderOpts.bordercolor) - .call(_$color_411.fill, sliderOpts.bgcolor) - .style('stroke-width', sliderOpts.borderwidth + 'px'); + .call(_$color_473.stroke, sliderOpts.bordercolor) + .call(_$color_473.fill, sliderOpts.bgcolor) + .style('stroke-width', sliderOpts.borderwidth + 'px'); - _$drawing_436.setTranslate(rect, - _$constants_500.railInset, - (dims.inputAreaWidth - _$constants_500.railWidth) * 0.5 + dims.currentValueTotalHeight + _$drawing_498.setTranslate(rect, + _$constants_562.railInset, + (dims.inputAreaWidth - _$constants_562.railWidth) * 0.5 + dims.currentValueTotalHeight ); } -function __clearPushMargins_502(gd) { +function __clearPushMargins_564(gd) { var pushMargins = gd._fullLayout._pushmargin || {}, keys = Object.keys(pushMargins); for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_500.autoMarginIdRoot) !== -1) { - _$plots_647.autoMargin(gd, k); + if(k.indexOf(_$constants_562.autoMarginIdRoot) !== -1) { + _$plots_709.autoMargin(gd, k); } } } @@ -70297,16 +72298,16 @@ function __clearPushMargins_502(gd) { 'use strict'; -/* removed: var _$constants_500 = require('./constants'); */; +/* removed: var _$constants_562 = require('./constants'); */; -var _$sliders_503 = { +var _$sliders_565 = { moduleType: 'component', - name: _$constants_500.name, + name: _$constants_562.name, - layoutAttributes: _$attributes_499, - supplyLayoutDefaults: _$slidersDefaults_501, + layoutAttributes: _$attributes_561, + supplyLayoutDefaults: _$slidersDefaults_563, - draw: _$draw_502 + draw: _$draw_564 }; /** @@ -70319,11 +72320,11 @@ var _$sliders_503 = { 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_410 = require('../color/attributes'); */; -var __extendFlat_505 = _$extend_528.extendFlat; -var __overrideAll_505 = _$edit_types_569.overrideAll; -/* removed: var _$pad_attributes_646 = require('../../plots/pad_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_472 = require('../color/attributes'); */; +var __extendFlat_567 = _$extend_590.extendFlat; +var __overrideAll_567 = _$edit_types_632.overrideAll; +/* removed: var _$pad_attributes_708 = require('../../plots/pad_attributes'); */; var buttonsAttrs = { _isLinkedToArray: 'button', @@ -70360,7 +72361,7 @@ var buttonsAttrs = { } }; -var _$attributes_505 = __overrideAll_505({ +var _$attributes_567 = __overrideAll_567({ _isLinkedToArray: 'updatemenu', _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], @@ -70434,11 +72435,11 @@ var _$attributes_505 = __overrideAll_505({ }, - pad: __extendFlat_505({}, _$pad_attributes_646, { + pad: __extendFlat_567({}, _$pad_attributes_708, { }), - font: _$font_attributes_611({ + font: _$font_attributes_673({ }), @@ -70449,7 +72450,7 @@ var _$attributes_505 = __overrideAll_505({ }, bordercolor: { valType: 'color', - dflt: _$attributes_410.borderLine, + dflt: _$attributes_472.borderLine, }, @@ -70475,7 +72476,7 @@ var _$attributes_505 = __overrideAll_505({ 'use strict'; -var _$constants_506 = { +var _$constants_568 = { // layout attribute name name: 'updatemenus', @@ -70553,32 +72554,32 @@ var _$constants_506 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleArrayContainerDefaults_580 = require('../../plots/array_container_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleArrayContainerDefaults_643 = require('../../plots/array_container_defaults'); */; -/* removed: var _$attributes_505 = require('./attributes'); */; -/* removed: var _$constants_506 = require('./constants'); */; +/* removed: var _$attributes_567 = require('./attributes'); */; +/* removed: var _$constants_568 = require('./constants'); */; -var __name_507 = _$constants_506.name; -var __buttonAttrs_507 = _$attributes_505.buttons; +var __name_569 = _$constants_568.name; +var __buttonAttrs_569 = _$attributes_567.buttons; -var _$updateMenusDefaults_507 = function updateMenusDefaults(layoutIn, layoutOut) { +var _$updateMenusDefaults_569 = function updateMenusDefaults(layoutIn, layoutOut) { var opts = { - name: __name_507, + name: __name_569, handleItemDefaults: menuDefaults }; - _$handleArrayContainerDefaults_580(layoutIn, layoutOut, opts); + _$handleArrayContainerDefaults_643(layoutIn, layoutOut, opts); }; function menuDefaults(menuIn, menuOut, layoutOut) { function coerce(attr, dflt) { - return _$lib_539.coerce(menuIn, menuOut, _$attributes_505, attr, dflt); + return _$lib_601.coerce(menuIn, menuOut, _$attributes_567, attr, dflt); } - var buttons = __buttonsDefaults_507(menuIn, menuOut); + var buttons = __buttonsDefaults_569(menuIn, menuOut); var visible = coerce('visible', buttons.length > 0); if(!visible) return; @@ -70590,7 +72591,7 @@ function menuDefaults(menuIn, menuOut, layoutOut) { coerce('x'); coerce('y'); - _$lib_539.noneOrAll(menuIn, menuOut, ['x', 'y']); + _$lib_601.noneOrAll(menuIn, menuOut, ['x', 'y']); coerce('xanchor'); coerce('yanchor'); @@ -70600,21 +72601,21 @@ function menuDefaults(menuIn, menuOut, layoutOut) { coerce('pad.b'); coerce('pad.l'); - _$lib_539.coerceFont(coerce, 'font', layoutOut.font); + _$lib_601.coerceFont(coerce, 'font', layoutOut.font); coerce('bgcolor', layoutOut.paper_bgcolor); coerce('bordercolor'); coerce('borderwidth'); } -function __buttonsDefaults_507(menuIn, menuOut) { +function __buttonsDefaults_569(menuIn, menuOut) { var buttonsIn = menuIn.buttons || [], buttonsOut = menuOut.buttons = []; var buttonIn, buttonOut; function coerce(attr, dflt) { - return _$lib_539.coerce(buttonIn, buttonOut, __buttonAttrs_507, attr, dflt); + return _$lib_601.coerce(buttonIn, buttonOut, __buttonAttrs_569, attr, dflt); } for(var i = 0; i < buttonsIn.length; i++) { @@ -70623,7 +72624,7 @@ function __buttonsDefaults_507(menuIn, menuOut) { coerce('method'); - if(!_$lib_539.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { + if(!_$lib_601.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) { continue; } @@ -70648,14 +72649,14 @@ function __buttonsDefaults_507(menuIn, menuOut) { 'use strict'; -var _$ScrollBox_510 = ScrollBox; +var _$ScrollBox_572 = ScrollBox; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** * Helper class to setup a scroll box @@ -70807,7 +72808,7 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { hbar.enter().append('rect') .classed('scrollbar-horizontal', true) - .call(_$color_411.fill, ScrollBox.barColor); + .call(_$color_473.fill, ScrollBox.barColor); if(needsHorizontalScrollBar) { this.hbar = hbar.attr({ @@ -70848,7 +72849,7 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { vbar.enter().append('rect') .classed('scrollbar-vertical', true) - .call(_$color_411.fill, ScrollBox.barColor); + .call(_$color_473.fill, ScrollBox.barColor); if(needsVerticalScrollBar) { this.vbar = vbar.attr({ @@ -70894,7 +72895,7 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { height: Math.ceil(clipB) - Math.floor(clipT) }); - this.container.call(_$drawing_436.setClipUrl, clipId); + this.container.call(_$drawing_498.setClipUrl, clipId); this.bg.attr({ x: l, @@ -70911,15 +72912,15 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { this.container .on('wheel', null) .on('.drag', null) - .call(_$drawing_436.setClipUrl, null); + .call(_$drawing_498.setClipUrl, null); delete this._clipRect; } // set up drag listeners (if scroll bars are needed) if(needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = _$d3_127.behavior.drag() + var onBoxDrag = _$d3_130.behavior.drag() .on('dragstart', function() { - _$d3_127.event.sourceEvent.preventDefault(); + _$d3_130.event.sourceEvent.preventDefault(); }) .on('drag', this._onBoxDrag.bind(this)); @@ -70929,10 +72930,10 @@ ScrollBox.prototype.enable = function enable(position, translateX, translateY) { .on('.drag', null) .call(onBoxDrag); - var onBarDrag = _$d3_127.behavior.drag() + var onBarDrag = _$d3_130.behavior.drag() .on('dragstart', function() { - _$d3_127.event.sourceEvent.preventDefault(); - _$d3_127.event.sourceEvent.stopPropagation(); + _$d3_130.event.sourceEvent.preventDefault(); + _$d3_130.event.sourceEvent.stopPropagation(); }) .on('drag', this._onBarDrag.bind(this)); @@ -70967,7 +72968,7 @@ ScrollBox.prototype.disable = function disable() { this.container .on('wheel', null) .on('.drag', null) - .call(_$drawing_436.setClipUrl, null); + .call(_$drawing_498.setClipUrl, null); delete this._clipRect; } @@ -70998,11 +72999,11 @@ ScrollBox.prototype._onBoxDrag = function onBarDrag() { translateY = this.translateY; if(this.hbar) { - translateX -= _$d3_127.event.dx; + translateX -= _$d3_130.event.dx; } if(this.vbar) { - translateY -= _$d3_127.event.dy; + translateY -= _$d3_130.event.dy; } this.setTranslate(translateX, translateY); @@ -71018,11 +73019,11 @@ ScrollBox.prototype._onBoxWheel = function onBarWheel() { translateY = this.translateY; if(this.hbar) { - translateX += _$d3_127.event.deltaY; + translateX += _$d3_130.event.deltaY; } if(this.vbar) { - translateY += _$d3_127.event.deltaY; + translateY += _$d3_130.event.deltaY; } this.setTranslate(translateX, translateY); @@ -71040,7 +73041,7 @@ ScrollBox.prototype._onBarDrag = function onBarDrag() { if(this.hbar) { var xMin = translateX + this._hbarXMin, xMax = xMin + this._hbarTranslateMax, - x = _$lib_539.constrain(_$d3_127.event.x, xMin, xMax), + x = _$lib_601.constrain(_$d3_130.event.x, xMin, xMax), xf = (x - xMin) / (xMax - xMin); var translateXMax = this.position.w - this._box.w; @@ -71051,7 +73052,7 @@ ScrollBox.prototype._onBarDrag = function onBarDrag() { if(this.vbar) { var yMin = translateY + this._vbarYMin, yMax = yMin + this._vbarTranslateMax, - y = _$lib_539.constrain(_$d3_127.event.y, yMin, yMax), + y = _$lib_601.constrain(_$d3_130.event.y, yMin, yMax), yf = (y - yMin) / (yMax - yMin); var translateYMax = this.position.h - this._box.h; @@ -71074,13 +73075,13 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) var translateXMax = this.position.w - this._box.w, translateYMax = this.position.h - this._box.h; - translateX = _$lib_539.constrain(translateX || 0, 0, translateXMax); - translateY = _$lib_539.constrain(translateY || 0, 0, translateYMax); + translateX = _$lib_601.constrain(translateX || 0, 0, translateXMax); + translateY = _$lib_601.constrain(translateY || 0, 0, translateYMax); this.translateX = translateX; this.translateY = translateY; - this.container.call(_$drawing_436.setTranslate, + this.container.call(_$drawing_498.setTranslate, this._box.l - this.position.l - translateX, this._box.t - this.position.t - translateY); @@ -71094,7 +73095,7 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) if(this.hbar) { var xf = translateX / translateXMax; - this.hbar.call(_$drawing_436.setTranslate, + this.hbar.call(_$drawing_498.setTranslate, translateX + xf * this._hbarTranslateMax, translateY); } @@ -71102,7 +73103,7 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) if(this.vbar) { var yf = translateY / translateYMax; - this.vbar.call(_$drawing_436.setTranslate, + this.vbar.call(_$drawing_498.setTranslate, translateX, translateY + yf * this._vbarTranslateMax); } @@ -71119,20 +73120,21 @@ ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$color_411 = require('../color'); */; -/* removed: var _$drawing_436 = require('../drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$anchor_utils_463 = require('../legend/anchor_utils'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$color_473 = require('../color'); */; +/* removed: var _$drawing_498 = require('../drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; +/* removed: var _$anchor_utils_525 = require('../legend/anchor_utils'); */; -var __LINE_SPACING_508 = _$alignment_511.LINE_SPACING; +var __LINE_SPACING_570 = _$alignment_573.LINE_SPACING; -/* removed: var _$constants_506 = require('./constants'); */; -/* removed: var _$ScrollBox_510 = require('./scrollbox'); */; +/* removed: var _$constants_568 = require('./constants'); */; +/* removed: var _$ScrollBox_572 = require('./scrollbox'); */; -var _$draw_508 = function draw(gd) { +var _$draw_570 = function draw(gd) { var fullLayout = gd._fullLayout, menuData = makeMenuData(fullLayout); @@ -71165,45 +73167,42 @@ var _$draw_508 = function draw(gd) { // draw update menu container var menus = fullLayout._menulayer - .selectAll('g.' + _$constants_506.containerClassName) + .selectAll('g.' + _$constants_568.containerClassName) .data(menuData.length > 0 ? [0] : []); menus.enter().append('g') - .classed(_$constants_506.containerClassName, true) + .classed(_$constants_568.containerClassName, true) .style('cursor', 'pointer'); menus.exit().remove(); // remove push margin object(s) - if(menus.exit().size()) __clearPushMargins_508(gd); + if(menus.exit().size()) __clearPushMargins_570(gd); // return early if no update menus are visible if(menuData.length === 0) return; // join header group - var headerGroups = menus.selectAll('g.' + _$constants_506.headerGroupClassName) - .data(menuData, __keyFunction_508); + var headerGroups = menus.selectAll('g.' + _$constants_568.headerGroupClassName) + .data(menuData, __keyFunction_570); headerGroups.enter().append('g') - .classed(_$constants_506.headerGroupClassName, true); + .classed(_$constants_568.headerGroupClassName, true); // draw dropdown button container - var gButton = menus.selectAll('g.' + _$constants_506.dropdownButtonGroupClassName) - .data([0]); - - gButton.enter().append('g') - .classed(_$constants_506.dropdownButtonGroupClassName, true) - .style('pointer-events', 'all'); + var gButton = _$lib_601.ensureSingle(menus, 'g', _$constants_568.dropdownButtonGroupClassName, function(s) { + s.style('pointer-events', 'all'); + }); // find dimensions before plotting anything (this mutates menuOpts) for(var i = 0; i < menuData.length; i++) { var menuOpts = menuData[i]; - __findDimensions_508(gd, menuOpts); + __findDimensions_570(gd, menuOpts); } // setup scrollbox var scrollBoxId = 'updatemenus' + fullLayout._uid, - scrollBox = new _$ScrollBox_510(gd, gButton, scrollBoxId); + scrollBox = new _$ScrollBox_572(gd, gButton, scrollBoxId); // remove exiting header, remove dropped buttons and reset margins if(headerGroups.enter().size()) { @@ -71212,33 +73211,33 @@ var _$draw_508 = function draw(gd) { gButton .call(removeAllButtons) - .attr(_$constants_506.menuIndexAttrName, '-1'); + .attr(_$constants_568.menuIndexAttrName, '-1'); } headerGroups.exit().each(function(menuOpts) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); gButton .call(removeAllButtons) - .attr(_$constants_506.menuIndexAttrName, '-1'); + .attr(_$constants_568.menuIndexAttrName, '-1'); - _$plots_647.autoMargin(gd, _$constants_506.autoMarginIdRoot + menuOpts._index); + _$plots_709.autoMargin(gd, _$constants_568.autoMarginIdRoot + menuOpts._index); }); // draw headers! headerGroups.each(function(menuOpts) { - var gHeader = _$d3_127.select(this); + var gHeader = _$d3_130.select(this); var _gButton = menuOpts.type === 'dropdown' ? gButton : null; - _$plots_647.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { - __setActive_508(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + _$plots_709.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) { + __setActive_570(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); }); if(menuOpts.type === 'dropdown') { drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); // if this menu is active, update the dropdown container - if(__isActive_508(gButton, menuOpts)) { + if(__isActive_570(gButton, menuOpts)) { drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); } } else { @@ -71252,7 +73251,7 @@ var _$draw_508 = function draw(gd) { * get only visible menus for display */ function makeMenuData(fullLayout) { - var contOpts = fullLayout[_$constants_506.name]; + var contOpts = fullLayout[_$constants_568.name]; var menuData = []; for(var i = 0; i < contOpts.length; i++) { @@ -71268,19 +73267,19 @@ function makeMenuData(fullLayout) { // it corresponds to the menu index in the user layout update menu container. // Because a menu can be set invisible, // this is a more 'consistent' field than the index in the menuData. -function __keyFunction_508(menuOpts) { +function __keyFunction_570(menuOpts) { return menuOpts._index; } function isFolded(gButton) { - return +gButton.attr(_$constants_506.menuIndexAttrName) === -1; + return +gButton.attr(_$constants_568.menuIndexAttrName) === -1; } -function __isActive_508(gButton, menuOpts) { - return +gButton.attr(_$constants_506.menuIndexAttrName) === menuOpts._index; +function __isActive_570(gButton, menuOpts) { + return +gButton.attr(_$constants_568.menuIndexAttrName) === menuOpts._index; } -function __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { +function __setActive_570(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { // update 'active' attribute in menuOpts menuOpts._input.active = menuOpts.active = buttonIndex; @@ -71289,7 +73288,7 @@ function __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, } else if(menuOpts.type === 'dropdown') { // fold up buttons and redraw header - gButton.attr(_$constants_506.menuIndexAttrName, '-1'); + gButton.attr(_$constants_568.menuIndexAttrName, '-1'); drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); @@ -71300,40 +73299,34 @@ function __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, } function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = gHeader.selectAll('g.' + _$constants_506.headerClassName) - .data([0]); - var dims = menuOpts._dims; - - header.enter().append('g') - .classed(_$constants_506.headerClassName, true) - .style('pointer-events', 'all'); + var header = _$lib_601.ensureSingle(gHeader, 'g', _$constants_568.headerClassName, function(s) { + s.style('pointer-events', 'all'); + }); - var active = menuOpts.active, - headerOpts = menuOpts.buttons[active] || _$constants_506.blankHeaderOpts, - posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }, - positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || _$constants_568.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; header .call(drawItem, menuOpts, headerOpts, gd) .call(setItemPosition, menuOpts, posOpts, positionOverrides); // draw drop arrow at the right edge - var arrow = gHeader.selectAll('text.' + _$constants_506.headerArrowClassName) - .data([0]); - - arrow.enter().append('text') - .classed(_$constants_506.headerArrowClassName, true) - .classed('user-select-none', true) - .attr('text-anchor', 'end') - .call(_$drawing_436.font, menuOpts.font) - .text(_$constants_506.arrowSymbol[menuOpts.direction]); + var arrow = _$lib_601.ensureSingle(gHeader, 'text', _$constants_568.headerArrowClassName, function(s) { + s.classed('user-select-none', true) + .attr('text-anchor', 'end') + .call(_$drawing_498.font, menuOpts.font) + .text(_$constants_568.arrowSymbol[menuOpts.direction]); + }); arrow.attr({ - x: dims.headerWidth - _$constants_506.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + _$constants_506.textOffsetY + menuOpts.pad.t + x: dims.headerWidth - _$constants_568.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + _$constants_568.textOffsetY + menuOpts.pad.t }); header.on('click', function() { @@ -71343,8 +73336,8 @@ function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { // if this menu is active, fold the dropdown container // otherwise, make this menu active gButton.attr( - _$constants_506.menuIndexAttrName, - __isActive_508(gButton, menuOpts) ? + _$constants_568.menuIndexAttrName, + __isActive_570(gButton, menuOpts) ? -1 : String(menuOpts._index) ); @@ -71361,7 +73354,7 @@ function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { }); // translate header group - _$drawing_436.setTranslate(gHeader, dims.lx, dims.ly); + _$drawing_498.setTranslate(gHeader, dims.lx, dims.ly); } function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { @@ -71377,7 +73370,7 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { menuOpts.buttons : []; - var klass = menuOpts.type === 'dropdown' ? _$constants_506.dropdownButtonClassName : _$constants_506.buttonClassName; + var klass = menuOpts.type === 'dropdown' ? _$constants_568.dropdownButtonClassName : _$constants_568.buttonClassName; var buttons = gButton.selectAll('g.' + klass) .data(buttonData); @@ -71407,25 +73400,25 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { if(menuOpts.type === 'dropdown') { if(isVertical) { - y0 = dims.headerHeight + _$constants_506.gapButtonHeader; + y0 = dims.headerHeight + _$constants_568.gapButtonHeader; } else { - x0 = dims.headerWidth + _$constants_506.gapButtonHeader; + x0 = dims.headerWidth + _$constants_568.gapButtonHeader; } } if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') { - y0 = -_$constants_506.gapButtonHeader + _$constants_506.gapButton - dims.openHeight; + y0 = -_$constants_568.gapButtonHeader + _$constants_568.gapButton - dims.openHeight; } if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') { - x0 = -_$constants_506.gapButtonHeader + _$constants_506.gapButton - dims.openWidth; + x0 = -_$constants_568.gapButtonHeader + _$constants_568.gapButton - dims.openWidth; } var posOpts = { x: dims.lx + x0 + menuOpts.pad.l, y: dims.ly + y0 + menuOpts.pad.t, - yPad: _$constants_506.gapButton, - xPad: _$constants_506.gapButton, + yPad: _$constants_568.gapButton, + xPad: _$constants_568.gapButton, index: 0, }; @@ -71435,7 +73428,7 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { }; buttons.each(function(buttonOpts, buttonIndex) { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); button .call(drawItem, menuOpts, buttonOpts, gd) @@ -71443,12 +73436,12 @@ function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { button.on('click', function() { // skip `dragend` events - if(_$d3_127.event.defaultPrevented) return; + if(_$d3_130.event.defaultPrevented) return; - __setActive_508(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + __setActive_570(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); if(buttonOpts.execute) { - _$plots_647.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + _$plots_709.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); } gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active}); @@ -71499,13 +73492,13 @@ function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { if(isVertical) { translateY = 0; for(i = 0; i < active; i++) { - translateY += dims.heights[i] + _$constants_506.gapButton; + translateY += dims.heights[i] + _$constants_568.gapButton; } } else { translateX = 0; for(i = 0; i < active; i++) { - translateX += dims.widths[i] + _$constants_506.gapButton; + translateX += dims.widths[i] + _$constants_568.gapButton; } } @@ -71557,64 +73550,58 @@ function drawItem(item, menuOpts, itemOpts, gd) { } function drawItemRect(item, menuOpts) { - var rect = item.selectAll('rect') - .data([0]); - - rect.enter().append('rect') - .classed(_$constants_506.itemRectClassName, true) - .attr({ - rx: _$constants_506.rx, - ry: _$constants_506.ry, + var rect = _$lib_601.ensureSingle(item, 'rect', _$constants_568.itemRectClassName, function(s) { + s.attr({ + rx: _$constants_568.rx, + ry: _$constants_568.ry, 'shape-rendering': 'crispEdges' }); + }); - rect.call(_$color_411.stroke, menuOpts.bordercolor) - .call(_$color_411.fill, menuOpts.bgcolor) + rect.call(_$color_473.stroke, menuOpts.bordercolor) + .call(_$color_473.fill, menuOpts.bgcolor) .style('stroke-width', menuOpts.borderwidth + 'px'); } function drawItemText(item, menuOpts, itemOpts, gd) { - var text = item.selectAll('text') - .data([0]); - - text.enter().append('text') - .classed(_$constants_506.itemTextClassName, true) - .classed('user-select-none', true) - .attr({ - 'text-anchor': 'start', - 'data-notex': 1 - }); + var text = _$lib_601.ensureSingle(item, 'text', _$constants_568.itemTextClassName, function(s) { + s.classed('user-select-none', true) + .attr({ + 'text-anchor': 'start', + 'data-notex': 1 + }); + }); - text.call(_$drawing_436.font, menuOpts.font) + text.call(_$drawing_498.font, menuOpts.font) .text(itemOpts.label) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); } function styleButtons(buttons, menuOpts) { var active = menuOpts.active; buttons.each(function(buttonOpts, i) { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); if(i === active && menuOpts.showactive) { - button.select('rect.' + _$constants_506.itemRectClassName) - .call(_$color_411.fill, _$constants_506.activeColor); + button.select('rect.' + _$constants_568.itemRectClassName) + .call(_$color_473.fill, _$constants_568.activeColor); } }); } function styleOnMouseOver(item) { - item.select('rect.' + _$constants_506.itemRectClassName) - .call(_$color_411.fill, _$constants_506.hoverColor); + item.select('rect.' + _$constants_568.itemRectClassName) + .call(_$color_473.fill, _$constants_568.hoverColor); } function styleOnMouseOut(item, menuOpts) { - item.select('rect.' + _$constants_506.itemRectClassName) - .call(_$color_411.fill, menuOpts.bgcolor); + item.select('rect.' + _$constants_568.itemRectClassName) + .call(_$color_473.fill, menuOpts.bgcolor); } // find item dimensions (this mutates menuOpts) -function __findDimensions_508(gd, menuOpts) { +function __findDimensions_570(gd, menuOpts) { var dims = menuOpts._dims = { width1: 0, height1: 0, @@ -71628,30 +73615,30 @@ function __findDimensions_508(gd, menuOpts) { ly: 0 }; - var fakeButtons = _$drawing_436.tester.selectAll('g.' + _$constants_506.dropdownButtonClassName) + var fakeButtons = _$drawing_498.tester.selectAll('g.' + _$constants_568.dropdownButtonClassName) .data(menuOpts.buttons); fakeButtons.enter().append('g') - .classed(_$constants_506.dropdownButtonClassName, true); + .classed(_$constants_568.dropdownButtonClassName, true); var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; // loop over fake buttons to find width / height fakeButtons.each(function(buttonOpts, i) { - var button = _$d3_127.select(this); + var button = _$d3_130.select(this); button.call(drawItem, menuOpts, buttonOpts, gd); - var text = button.select('.' + _$constants_506.itemTextClassName); + var text = button.select('.' + _$constants_568.itemTextClassName); // width is given by max width of all buttons - var tWidth = text.node() && _$drawing_436.bBox(text.node()).width; - var wEff = Math.max(tWidth + _$constants_506.textPadX, _$constants_506.minWidth); + var tWidth = text.node() && _$drawing_498.bBox(text.node()).width; + var wEff = Math.max(tWidth + _$constants_568.textPadX, _$constants_568.minWidth); // height is determined by item text - var tHeight = menuOpts.font.size * __LINE_SPACING_508; - var tLines = _$svg_text_utils_562.lineCount(text); - var hEff = Math.max(tHeight * tLines, _$constants_506.minHeight) + _$constants_506.textOffsetY; + var tHeight = menuOpts.font.size * __LINE_SPACING_570; + var tLines = _$svg_text_utils_625.lineCount(text); + var hEff = Math.max(tHeight * tLines, _$constants_568.minHeight) + _$constants_568.textOffsetY; hEff = Math.ceil(hEff); wEff = Math.ceil(wEff); @@ -71668,34 +73655,34 @@ function __findDimensions_508(gd, menuOpts) { if(isVertical) { dims.totalWidth = Math.max(dims.totalWidth, wEff); dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + _$constants_506.gapButton; - dims.openHeight += hEff + _$constants_506.gapButton; + dims.totalHeight += hEff + _$constants_568.gapButton; + dims.openHeight += hEff + _$constants_568.gapButton; } else { - dims.totalWidth += wEff + _$constants_506.gapButton; - dims.openWidth += wEff + _$constants_506.gapButton; + dims.totalWidth += wEff + _$constants_568.gapButton; + dims.openWidth += wEff + _$constants_568.gapButton; dims.totalHeight = Math.max(dims.totalHeight, hEff); dims.openHeight = dims.totalHeight; } }); if(isVertical) { - dims.totalHeight -= _$constants_506.gapButton; + dims.totalHeight -= _$constants_568.gapButton; } else { - dims.totalWidth -= _$constants_506.gapButton; + dims.totalWidth -= _$constants_568.gapButton; } - dims.headerWidth = dims.width1 + _$constants_506.arrowPadX; + dims.headerWidth = dims.width1 + _$constants_568.arrowPadX; dims.headerHeight = dims.height1; if(menuOpts.type === 'dropdown') { if(isVertical) { - dims.width1 += _$constants_506.arrowPadX; + dims.width1 += _$constants_568.arrowPadX; dims.totalHeight = dims.height1; } else { dims.totalWidth = dims.width1; } - dims.totalWidth += _$constants_506.arrowPadX; + dims.totalWidth += _$constants_568.arrowPadX; } fakeButtons.remove(); @@ -71708,21 +73695,21 @@ function __findDimensions_508(gd, menuOpts) { dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); var xanchor = 'left'; - if(_$anchor_utils_463.isRightAnchor(menuOpts)) { + if(_$anchor_utils_525.isRightAnchor(menuOpts)) { dims.lx -= paddedWidth; xanchor = 'right'; } - if(_$anchor_utils_463.isCenterAnchor(menuOpts)) { + if(_$anchor_utils_525.isCenterAnchor(menuOpts)) { dims.lx -= paddedWidth / 2; xanchor = 'center'; } var yanchor = 'top'; - if(_$anchor_utils_463.isBottomAnchor(menuOpts)) { + if(_$anchor_utils_525.isBottomAnchor(menuOpts)) { dims.ly -= paddedHeight; yanchor = 'bottom'; } - if(_$anchor_utils_463.isMiddleAnchor(menuOpts)) { + if(_$anchor_utils_525.isMiddleAnchor(menuOpts)) { dims.ly -= paddedHeight / 2; yanchor = 'middle'; } @@ -71732,7 +73719,7 @@ function __findDimensions_508(gd, menuOpts) { dims.lx = Math.round(dims.lx); dims.ly = Math.round(dims.ly); - _$plots_647.autoMargin(gd, _$constants_506.autoMarginIdRoot + menuOpts._index, { + _$plots_709.autoMargin(gd, _$constants_568.autoMarginIdRoot + menuOpts._index, { x: menuOpts.x, y: menuOpts.y, l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0), @@ -71745,13 +73732,13 @@ function __findDimensions_508(gd, menuOpts) { // set item positions (mutates posOpts) function setItemPosition(item, menuOpts, posOpts, overrideOpts) { overrideOpts = overrideOpts || {}; - var rect = item.select('.' + _$constants_506.itemRectClassName); - var text = item.select('.' + _$constants_506.itemTextClassName); + var rect = item.select('.' + _$constants_568.itemRectClassName); + var text = item.select('.' + _$constants_568.itemTextClassName); var borderWidth = menuOpts.borderwidth; var index = posOpts.index; var dims = menuOpts._dims; - _$drawing_436.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + _$drawing_498.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1; var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1); @@ -71763,12 +73750,12 @@ function setItemPosition(item, menuOpts, posOpts, overrideOpts) { height: finalHeight }); - var tHeight = menuOpts.font.size * __LINE_SPACING_508; - var tLines = _$svg_text_utils_562.lineCount(text); + var tHeight = menuOpts.font.size * __LINE_SPACING_570; + var tLines = _$svg_text_utils_625.lineCount(text); var spanOffset = ((tLines - 1) * tHeight / 2); - _$svg_text_utils_562.positionText(text, _$constants_506.textOffsetX, - finalHeight / 2 - spanOffset + _$constants_506.textOffsetY); + _$svg_text_utils_625.positionText(text, _$constants_568.textOffsetX, + finalHeight / 2 - spanOffset + _$constants_568.textOffsetY); if(isVertical) { posOpts.y += dims.heights[index] + posOpts.yPad; @@ -71780,18 +73767,18 @@ function setItemPosition(item, menuOpts, posOpts, overrideOpts) { } function removeAllButtons(gButton) { - gButton.selectAll('g.' + _$constants_506.dropdownButtonClassName).remove(); + gButton.selectAll('g.' + _$constants_568.dropdownButtonClassName).remove(); } -function __clearPushMargins_508(gd) { +function __clearPushMargins_570(gd) { var pushMargins = gd._fullLayout._pushmargin || {}; var keys = Object.keys(pushMargins); for(var i = 0; i < keys.length; i++) { var k = keys[i]; - if(k.indexOf(_$constants_506.autoMarginIdRoot) !== -1) { - _$plots_647.autoMargin(gd, k); + if(k.indexOf(_$constants_568.autoMarginIdRoot) !== -1) { + _$plots_709.autoMargin(gd, k); } } } @@ -71806,19 +73793,19 @@ function __clearPushMargins_508(gd) { 'use strict'; -/* removed: var _$constants_506 = require('./constants'); */; +/* removed: var _$constants_568 = require('./constants'); */; -var _$updatemenus_509 = { +var _$updatemenus_571 = { moduleType: 'component', - name: _$constants_506.name, + name: _$constants_568.name, - layoutAttributes: _$attributes_505, - supplyLayoutDefaults: _$updateMenusDefaults_507, + layoutAttributes: _$attributes_567, + supplyLayoutDefaults: _$updateMenusDefaults_569, - draw: _$draw_508 + draw: _$draw_570 }; -var _$mathjax_config_521 = {}; +var _$mathjax_config_582 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -71835,7 +73822,7 @@ var _$mathjax_config_521 = {}; * Check and configure MathJax */ if(typeof MathJax !== 'undefined') { - _$mathjax_config_521.MathJax = true; + _$mathjax_config_582.MathJax = true; MathJax.Hub.Config({ messageStyle: 'none', @@ -71848,7 +73835,7 @@ if(typeof MathJax !== 'undefined') { MathJax.Hub.Configured(); } else { - _$mathjax_config_521.MathJax = false; + _$mathjax_config_582.MathJax = false; } /** @@ -71862,8 +73849,8 @@ if(typeof MathJax !== 'undefined') { 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plot_config_574 = require('../plot_api/plot_config'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plot_config_637 = require('../plot_api/plot_config'); */; /** @@ -71883,8 +73870,8 @@ function copyArgArray(gd, args) { if(arg === gd) copy[i] = arg; else if(typeof arg === 'object') { copy[i] = Array.isArray(arg) ? - _$lib_539.extendDeep([], arg) : - _$lib_539.extendDeepAll({}, arg); + _$lib_601.extendDeep([], arg) : + _$lib_601.extendDeepAll({}, arg); } else copy[i] = arg; } @@ -71898,7 +73885,7 @@ function copyArgArray(gd, args) { // ----------------------------------------------------- -var __queue_553 = {}; +var __queue_616 = {}; // TODO: disable/enable undo and redo buttons appropriately @@ -71911,7 +73898,7 @@ var __queue_553 = {}; * @param redoFunc Function to redo this operation * @param redoArgs Args to supply redoFunc with */ -__queue_553.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { +__queue_616.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { var queueObj, queueIndex; @@ -71944,7 +73931,7 @@ __queue_553.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { queueObj.redo.args.push(redoArgs); } - if(gd.undoQueue.queue.length > _$plot_config_574.queueLength) { + if(gd.undoQueue.queue.length > _$plot_config_637.queueLength) { gd.undoQueue.queue.shift(); gd.undoQueue.index--; } @@ -71955,7 +73942,7 @@ __queue_553.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { * * @param gd */ -__queue_553.startSequence = function(gd) { +__queue_616.startSequence = function(gd) { gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; gd.undoQueue.sequence = true; gd.undoQueue.beginSequence = true; @@ -71968,7 +73955,7 @@ __queue_553.startSequence = function(gd) { * * @param gd */ -__queue_553.stopSequence = function(gd) { +__queue_616.stopSequence = function(gd) { gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false}; gd.undoQueue.sequence = false; gd.undoQueue.beginSequence = false; @@ -71979,7 +73966,7 @@ __queue_553.stopSequence = function(gd) { * * @param gd */ -__queue_553.undo = function undo(gd) { +__queue_616.undo = function undo(gd) { var queueObj, i; if(gd.framework && gd.framework.isPolar) { @@ -72001,7 +73988,7 @@ __queue_553.undo = function undo(gd) { // this sequence keeps things from adding to the queue during undo/redo gd.undoQueue.inSequence = true; for(i = 0; i < queueObj.undo.calls.length; i++) { - __queue_553.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + __queue_616.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); } gd.undoQueue.inSequence = false; gd.autoplay = false; @@ -72012,7 +73999,7 @@ __queue_553.undo = function undo(gd) { * * @param gd */ -__queue_553.redo = function redo(gd) { +__queue_616.redo = function redo(gd) { var queueObj, i; if(gd.framework && gd.framework.isPolar) { @@ -72031,7 +74018,7 @@ __queue_553.redo = function redo(gd) { // this sequence keeps things from adding to the queue during undo/redo gd.undoQueue.inSequence = true; for(i = 0; i < queueObj.redo.calls.length; i++) { - __queue_553.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + __queue_616.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); } gd.undoQueue.inSequence = false; gd.autoplay = false; @@ -72049,7 +74036,7 @@ __queue_553.redo = function redo(gd) { * @param func * @param args */ -__queue_553.plotDo = function(gd, func, args) { +__queue_616.plotDo = function(gd, func, args) { gd.autoplay = true; // this *won't* copy gd and it preserves `undefined` properties! @@ -72059,7 +74046,7 @@ __queue_553.plotDo = function(gd, func, args) { func.apply(null, args); }; -var _$queue_553 = __queue_553; +var _$queue_616 = __queue_616; /** * Copyright 2012-2018, Plotly, Inc. @@ -72071,7 +74058,7 @@ var _$queue_553 = __queue_553; 'use strict'; -var _$localeEnUs_566 = { +var _$localeEnUs_629 = { moduleType: 'locale', name: 'en-US', dictionary: { @@ -72092,14 +74079,14 @@ var _$localeEnUs_566 = { 'use strict'; -var _$localeEn_567 = { +var _$localeEn_630 = { moduleType: 'locale', name: 'en', dictionary: { 'Click to enter Colorscale title': 'Click to enter Colourscale title' }, format: { - days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], + days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], months: [ 'January', 'February', 'March', 'April', 'May', 'June', @@ -72124,7 +74111,7 @@ var _$localeEn_567 = { } }; -var _$fromQuat_170 = fromQuat; +var _$fromQuat_227 = fromQuat; /** * Creates a matrix from a quaternion rotation. @@ -72171,7 +74158,7 @@ function fromQuat(out, q) { return out; }; -var _$helpers_570 = {}; +var _$helpers_633 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -72183,22 +74170,22 @@ var _$helpers_570 = {}; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$fromQuat_170 = require('gl-mat4/fromQuat'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$fromQuat_227 = require('gl-mat4/fromQuat'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$axis_ids_587 = require('../plots/cartesian/axis_ids'); */; -var cleanId = _$axis_ids_587.cleanId; -var getFromTrace = _$axis_ids_587.getFromTrace; -/* removed: var _$color_411 = require('../components/color'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +/* removed: var _$axis_ids_650 = require('../plots/cartesian/axis_ids'); */; +var cleanId = _$axis_ids_650.cleanId; +var getFromTrace = _$axis_ids_650.getFromTrace; +/* removed: var _$color_473 = require('../components/color'); */; // clear the promise queue if one of them got rejected -_$helpers_570.clearPromiseQueue = function(gd) { +_$helpers_633.clearPromiseQueue = function(gd) { if(Array.isArray(gd._promises) && gd._promises.length > 0) { - _$lib_539.log('Clearing previous rejected promises from queue.'); + _$lib_601.log('Clearing previous rejected promises from queue.'); } gd._promises = []; @@ -72207,7 +74194,7 @@ _$helpers_570.clearPromiseQueue = function(gd) { // make a few changes to the layout right away // before it gets used for anything // backward compatibility and cleanup of nonstandard options -_$helpers_570.cleanLayout = function(layout) { +_$helpers_633.cleanLayout = function(layout) { var i, j; if(!layout) layout = {}; @@ -72226,8 +74213,8 @@ _$helpers_570.cleanLayout = function(layout) { delete layout.scene1; } - var axisAttrRegex = (_$plots_647.subplotsRegistry.cartesian || {}).attrRegex; - var sceneAttrRegex = (_$plots_647.subplotsRegistry.gl3d || {}).attrRegex; + var axisAttrRegex = (_$plots_709.subplotsRegistry.cartesian || {}).attrRegex; + var sceneAttrRegex = (_$plots_709.subplotsRegistry.gl3d || {}).attrRegex; var keys = Object.keys(layout); for(i = 0; i < keys.length; i++) { @@ -72278,7 +74265,7 @@ _$helpers_570.cleanLayout = function(layout) { var rotation = cameraposition[0], center = cameraposition[1], radius = cameraposition[2], - mat = _$fromQuat_170([], rotation), + mat = _$fromQuat_227([], rotation), eye = []; for(j = 0; j < 3; ++j) { @@ -72300,7 +74287,7 @@ _$helpers_570.cleanLayout = function(layout) { for(i = 0; i < annotationsLen; i++) { var ann = layout.annotations[i]; - if(!_$lib_539.isPlainObject(ann)) continue; + if(!_$lib_601.isPlainObject(ann)) continue; if(ann.ref) { if(ann.ref === 'paper') { @@ -72322,7 +74309,7 @@ _$helpers_570.cleanLayout = function(layout) { for(i = 0; i < shapesLen; i++) { var shape = layout.shapes[i]; - if(!_$lib_539.isPlainObject(shape)) continue; + if(!_$lib_601.isPlainObject(shape)) continue; cleanAxRef(shape, 'xref'); cleanAxRef(shape, 'yref'); @@ -72357,7 +74344,7 @@ _$helpers_570.cleanLayout = function(layout) { // sanitize rgb(fractions) and rgba(fractions) that old tinycolor // supported, but new tinycolor does not because they're not valid css - _$color_411.clean(layout); + _$color_473.clean(layout); return layout; }; @@ -72378,7 +74365,7 @@ function cleanAxRef(container, attr) { * Important: if you're going to add something here that modifies a data array, * update it in place so the new array === the old one. */ -_$helpers_570.cleanData = function(data, existingData) { +_$helpers_633.cleanData = function(data, existingData) { // Enforce unique IDs var suids = [], // seen uids --- so we can weed out incoming repeats uids = data.concat(Array.isArray(existingData) ? existingData : []) @@ -72394,10 +74381,10 @@ _$helpers_570.cleanData = function(data, existingData) { var newUid; for(i = 0; i < 100; i++) { - newUid = _$lib_539.randstr(uids); + newUid = _$lib_601.randstr(uids); if(suids.indexOf(newUid) === -1) break; } - trace.uid = _$lib_539.randstr(uids); + trace.uid = _$lib_601.randstr(uids); uids.push(trace.uid); } // keep track of already seen uids, so that if there are @@ -72415,29 +74402,29 @@ _$helpers_570.cleanData = function(data, existingData) { // error_y.opacity is obsolete - merge into color if(trace.error_y && 'opacity' in trace.error_y) { - var dc = _$color_411.defaults, + var dc = _$color_473.defaults, yeColor = trace.error_y.color || - (_$registry_668.traceIs(trace, 'bar') ? _$color_411.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = _$color_411.addOpacity( - _$color_411.rgb(yeColor), - _$color_411.opacity(yeColor) * trace.error_y.opacity); + (_$registry_731.traceIs(trace, 'bar') ? _$color_473.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = _$color_473.addOpacity( + _$color_473.rgb(yeColor), + _$color_473.opacity(yeColor) * trace.error_y.opacity); delete trace.error_y.opacity; } // convert bardir to orientation, and put the data into // the axes it's eventually going to be used with if('bardir' in trace) { - if(trace.bardir === 'h' && (_$registry_668.traceIs(trace, 'bar') || + if(trace.bardir === 'h' && (_$registry_731.traceIs(trace, 'bar') || trace.type.substr(0, 9) === 'histogram')) { trace.orientation = 'h'; - _$helpers_570.swapXYData(trace); + _$helpers_633.swapXYData(trace); } delete trace.bardir; } // now we have only one 1D histogram type, and whether // it uses x or y data depends on trace.orientation - if(trace.type === 'histogramy') _$helpers_570.swapXYData(trace); + if(trace.type === 'histogramy') _$helpers_633.swapXYData(trace); if(trace.type === 'histogramx' || trace.type === 'histogramy') { trace.type = 'histogram'; } @@ -72457,11 +74444,11 @@ _$helpers_570.cleanData = function(data, existingData) { if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y'); // scene ids scene1 -> scene - if(_$registry_668.traceIs(trace, 'gl3d') && trace.scene) { - trace.scene = _$plots_647.subplotsRegistry.gl3d.cleanId(trace.scene); + if(_$registry_731.traceIs(trace, 'gl3d') && trace.scene) { + trace.scene = _$plots_709.subplotsRegistry.gl3d.cleanId(trace.scene); } - if(!_$registry_668.traceIs(trace, 'pie') && !_$registry_668.traceIs(trace, 'bar')) { + if(!_$registry_731.traceIs(trace, 'pie') && !_$registry_731.traceIs(trace, 'bar')) { if(Array.isArray(trace.textposition)) { for(i = 0; i < trace.textposition.length; i++) { trace.textposition[i] = cleanTextPosition(trace.textposition[i]); @@ -72473,24 +74460,24 @@ _$helpers_570.cleanData = function(data, existingData) { } // fix typo in colorscale definition - if(_$registry_668.traceIs(trace, '2dMap')) { + if(_$registry_731.traceIs(trace, '2dMap')) { if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu'; if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd'; } - if(_$registry_668.traceIs(trace, 'markerColorscale') && trace.marker) { + if(_$registry_731.traceIs(trace, 'markerColorscale') && trace.marker) { var cont = trace.marker; if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu'; if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd'; } // fix typo in surface 'highlight*' definitions - if(trace.type === 'surface' && _$lib_539.isPlainObject(trace.contours)) { + if(trace.type === 'surface' && _$lib_601.isPlainObject(trace.contours)) { var dims = ['x', 'y', 'z']; for(i = 0; i < dims.length; i++) { var opts = trace.contours[dims[i]]; - if(!_$lib_539.isPlainObject(opts)) continue; + if(!_$lib_601.isPlainObject(opts)) continue; if(opts.highlightColor) { opts.highlightcolor = opts.highlightColor; @@ -72504,6 +74491,32 @@ _$helpers_570.cleanData = function(data, existingData) { } } + // fixes from converting finance from transforms to real trace types + if(trace.type === 'candlestick' || trace.type === 'ohlc') { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); + + // now figure out something smart to do with the separate direction + // names we removed + if((increasingName !== false) && (decreasingName !== false)) { + // both sub-names existed: base name previously had no effect + // so ignore it and try to find a shared part of the sub-names + + var newName = commonPrefix( + increasingName, decreasingName, + increasingShowlegend, decreasingShowlegend + ); + // if no common part, leave whatever name was (or wasn't) there + if(newName) trace.name = newName; + } + else if((increasingName || decreasingName) && !trace.name) { + // one sub-name existed but not the base name - just use the sub-name + trace.name = increasingName || decreasingName; + } + } + // transforms backward compatibility fixes if(Array.isArray(trace.transforms)) { var transforms = trace.transforms; @@ -72511,7 +74524,7 @@ _$helpers_570.cleanData = function(data, existingData) { for(i = 0; i < transforms.length; i++) { var transform = transforms[i]; - if(!_$lib_539.isPlainObject(transform)) continue; + if(!_$lib_601.isPlainObject(transform)) continue; switch(transform.type) { case 'filter': @@ -72558,10 +74571,42 @@ _$helpers_570.cleanData = function(data, existingData) { // sanitize rgb(fractions) and rgba(fractions) that old tinycolor // supported, but new tinycolor does not because they're not valid css - _$color_411.clean(trace); + _$color_473.clean(trace); } }; +function cleanFinanceDir(dirContainer) { + if(!_$lib_601.isPlainObject(dirContainer)) return false; + + var dirName = dirContainer.name; + + delete dirContainer.name; + delete dirContainer.showlegend; + + return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName); +} + +function commonPrefix(name1, name2, show1, show2) { + // if only one is shown in the legend, use that + if(show1 && !show2) return name1; + if(show2 && !show1) return name2; + + // if both or neither are in the legend, check if one is blank (or whitespace) + // and use the other one + // note that hover labels can still use the name even if the legend doesn't + if(!name1.trim()) return name2; + if(!name2.trim()) return name1; + + var minLen = Math.min(name1.length, name2.length); + var i; + for(i = 0; i < minLen; i++) { + if(name1.charAt(i) !== name2.charAt(i)) break; + } + + var out = name1.substr(0, i); + return out.trim(); +} + // textposition - support partial attributes (ie just 'top') // and incorrect use of middle / center etc. function cleanTextPosition(textposition) { @@ -72584,9 +74629,9 @@ function emptyContainer(outer, innerStr) { // swap all the data and data attributes associated with x and y -_$helpers_570.swapXYData = function(trace) { +_$helpers_633.swapXYData = function(trace) { var i; - _$lib_539.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); + _$lib_601.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']); if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) { if(trace.transpose) delete trace.transpose; else trace.transpose = true; @@ -72595,9 +74640,9 @@ _$helpers_570.swapXYData = function(trace) { var errorY = trace.error_y, copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle : !(errorY.color || errorY.thickness || errorY.width); - _$lib_539.swapAttrs(trace, ['error_?.copy_ystyle']); + _$lib_601.swapAttrs(trace, ['error_?.copy_ystyle']); if(copyYstyle) { - _$lib_539.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); + _$lib_601.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']); } } if(typeof trace.hoverinfo === 'string') { @@ -72611,8 +74656,8 @@ _$helpers_570.swapXYData = function(trace) { }; // coerce traceIndices input to array of trace indices -_$helpers_570.coerceTraceIndices = function(gd, traceIndices) { - if(_$fastIsnumeric_139(traceIndices)) { +_$helpers_633.coerceTraceIndices = function(gd, traceIndices) { + if(_$fastIsnumeric_196(traceIndices)) { return [traceIndices]; } else if(!Array.isArray(traceIndices) || !traceIndices.length) { @@ -72634,20 +74679,20 @@ _$helpers_570.coerceTraceIndices = function(gd, traceIndices) { * undo hash (N.B. undoit may be mutated here). * */ -_$helpers_570.manageArrayContainers = function(np, newVal, undoit) { +_$helpers_633.manageArrayContainers = function(np, newVal, undoit) { var obj = np.obj, parts = np.parts, pLength = parts.length, pLast = parts[pLength - 1]; - var pLastIsNumber = _$fastIsnumeric_139(pLast); + var pLastIsNumber = _$fastIsnumeric_196(pLast); // delete item if(pLastIsNumber && newVal === null) { // Clear item in array container when new value is null var contPath = parts.slice(0, pLength - 1).join('.'), - cont = _$lib_539.nestedProperty(obj, contPath).get(); + cont = _$lib_601.nestedProperty(obj, contPath).get(); cont.splice(pLast, 1); // Note that nested property clears null / undefined at end of @@ -72694,7 +74739,7 @@ function getParent(attr) { * @returns {Boolean} * is a parent of attr present in aobj? */ -_$helpers_570.hasParent = function(aobj, attr) { +_$helpers_633.hasParent = function(aobj, attr) { var attrParent = getParent(attr); while(attrParent) { if(attrParent in aobj) return true; @@ -72711,12 +74756,12 @@ _$helpers_570.hasParent = function(aobj, attr) { * @param {object} layoutUpdate: any update being done concurrently to the layout, * which may supercede clearing the axis types */ -var __axLetters_570 = ['x', 'y', 'z']; -_$helpers_570.clearAxisTypes = function(gd, traces, layoutUpdate) { +var __axLetters_633 = ['x', 'y', 'z']; +_$helpers_633.clearAxisTypes = function(gd, traces, layoutUpdate) { for(var i = 0; i < traces.length; i++) { var trace = gd._fullData[i]; for(var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, __axLetters_570[j]); + var ax = getFromTrace(gd, trace, __axLetters_633[j]); // do not clear log type - that's never an auto result so must have been intentional if(ax && ax.type !== 'log') { @@ -72729,14 +74774,14 @@ _$helpers_570.clearAxisTypes = function(gd, traces, layoutUpdate) { var typeAttr = axAttr + '.type'; if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) { - _$lib_539.nestedProperty(gd.layout, typeAttr).set(null); + _$lib_601.nestedProperty(gd.layout, typeAttr).set(null); } } } } }; -_$helpers_570.clearAxisAutomargins = function(gd) { +_$helpers_633.clearAxisAutomargins = function(gd) { var keys = Object.keys(gd._fullLayout._pushmargin); for(var i = 0; i < keys.length; i++) { if(keys[i].indexOf('automargin') !== -1) { @@ -72745,7 +74790,7 @@ _$helpers_570.clearAxisAutomargins = function(gd) { } }; -var _$manage_arrays_572 = {}; +var _$manage_arrays_635 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -72757,21 +74802,21 @@ var _$manage_arrays_572 = {}; 'use strict'; -/* removed: var _$nestedProperty_547 = require('../lib/nested_property'); */; -/* removed: var _$isPlainObject_541 = require('../lib/is_plain_object'); */; -/* removed: var _$noop_548 = require('../lib/noop'); */; -/* removed: var _$loggers_544 = require('../lib/loggers'); */; -var sorterAsc = _$search_557.sorterAsc; -/* removed: var _$registry_668 = require('../registry'); */; +/* removed: var _$nestedProperty_609 = require('../lib/nested_property'); */; +/* removed: var _$isPlainObject_603 = require('../lib/is_plain_object'); */; +/* removed: var _$noop_610 = require('../lib/noop'); */; +/* removed: var _$loggers_606 = require('../lib/loggers'); */; +var sorterAsc = _$search_620.sorterAsc; +/* removed: var _$registry_731 = require('../registry'); */; -_$manage_arrays_572.containerArrayMatch = _$containerArrayMatch_568; +_$manage_arrays_635.containerArrayMatch = _$containerArrayMatch_631; -var isAddVal = _$manage_arrays_572.isAddVal = function isAddVal(val) { - return val === 'add' || _$isPlainObject_541(val); +var isAddVal = _$manage_arrays_635.isAddVal = function isAddVal(val) { + return val === 'add' || _$isPlainObject_603(val); }; -var isRemoveVal = _$manage_arrays_572.isRemoveVal = function isRemoveVal(val) { +var isRemoveVal = _$manage_arrays_635.isRemoveVal = function isRemoveVal(val) { return val === null || val === 'remove'; }; @@ -72818,19 +74863,19 @@ var isRemoveVal = _$manage_arrays_572.isRemoveVal = function isRemoveVal(val) { * @returns {bool} `true` if it managed to complete drawing of the changes * `false` would mean the parent should replot. */ -_$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { +_$manage_arrays_635.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) { var componentType = np.astr, - supplyComponentDefaults = _$registry_668.getComponentMethod(componentType, 'supplyLayoutDefaults'), - draw = _$registry_668.getComponentMethod(componentType, 'draw'), - drawOne = _$registry_668.getComponentMethod(componentType, 'drawOne'), - replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_548) || - (draw === _$noop_548), + supplyComponentDefaults = _$registry_731.getComponentMethod(componentType, 'supplyLayoutDefaults'), + draw = _$registry_731.getComponentMethod(componentType, 'draw'), + drawOne = _$registry_731.getComponentMethod(componentType, 'drawOne'), + replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === _$noop_610) || + (draw === _$noop_610), layout = gd.layout, fullLayout = gd._fullLayout; if(edits['']) { if(Object.keys(edits).length > 1) { - _$loggers_544.warn('Full array edits are incompatible with other edits', + _$loggers_606.warn('Full array edits are incompatible with other edits', componentType); } @@ -72839,7 +74884,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha if(isRemoveVal(fullVal)) np.set(null); else if(Array.isArray(fullVal)) np.set(fullVal); else { - _$loggers_544.warn('Unrecognized full array edit value', componentType, fullVal); + _$loggers_606.warn('Unrecognized full array edit value', componentType, fullVal); return true; } @@ -72858,7 +74903,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha // redoing supplyDefaults // TODO: this assumes componentArray is in gd.layout - which will not be // true after we extend this to restyle - componentArrayFull = _$nestedProperty_547(fullLayout, componentType).get(); + componentArrayFull = _$nestedProperty_609(fullLayout, componentType).get(); var deletes = [], firstIndexChange = -1, @@ -72880,13 +74925,13 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha adding = isAddVal(objVal); if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - _$loggers_544.warn('index out of range', componentType, componentNum); + _$loggers_606.warn('index out of range', componentType, componentNum); continue; } if(objVal !== undefined) { if(objKeys.length > 1) { - _$loggers_544.warn( + _$loggers_606.warn( 'Insertion & removal are incompatible with edits to the same index.', componentType, componentNum); } @@ -72900,7 +74945,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); } else { - _$loggers_544.warn('Unrecognized full object edit value', + _$loggers_606.warn('Unrecognized full object edit value', componentType, componentNum, objVal); } @@ -72908,7 +74953,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha } else { for(j = 0; j < objKeys.length; j++) { - _$nestedProperty_547(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); + _$nestedProperty_609(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]); } } } @@ -72930,7 +74975,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha // finally draw all the components we need to // if we added or removed any, redraw all after it - if(drawOne !== _$noop_548) { + if(drawOne !== _$noop_610) { var indicesToDraw; if(firstIndexChange === -1) { // there's no re-indexing to do, so only redraw components that changed @@ -72959,7 +75004,7 @@ _$manage_arrays_572.applyContainerArrayChanges = function applyContainerArrayCha return true; }; -var _$buttons_473 = {}; +var _$buttons_535 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -72971,15 +75016,15 @@ var _$buttons_473 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; -var ____473 = _$lib_539._; +var ____535 = _$lib_601._; -var modeBarButtons = _$buttons_473 = {}; +var modeBarButtons = _$buttons_535 = {}; /** * ModeBar buttons configuration @@ -73009,40 +75054,40 @@ var modeBarButtons = _$buttons_473 = {}; modeBarButtons.toImage = { name: 'toImage', - title: function(gd) { return ____473(gd, 'Download plot as a png'); }, + title: function(gd) { return ____535(gd, 'Download plot as a png'); }, icon: _$ploticon_2.camera, click: function(gd) { var format = 'png'; - _$lib_539.notifier(____473(gd, 'Taking snapshot - this may take a few seconds'), 'long'); + _$lib_601.notifier(____535(gd, 'Taking snapshot - this may take a few seconds'), 'long'); - if(_$lib_539.isIE()) { - _$lib_539.notifier(____473(gd, 'IE only supports svg. Changing format to svg.'), 'long'); + if(_$lib_601.isIE()) { + _$lib_601.notifier(____535(gd, 'IE only supports svg. Changing format to svg.'), 'long'); format = 'svg'; } - _$registry_668.call('downloadImage', gd, {'format': format}) + _$registry_731.call('downloadImage', gd, {'format': format}) .then(function(filename) { - _$lib_539.notifier(____473(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); + _$lib_601.notifier(____535(gd, 'Snapshot succeeded') + ' - ' + filename, 'long'); }) .catch(function() { - _$lib_539.notifier(____473(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); + _$lib_601.notifier(____535(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long'); }); } }; modeBarButtons.sendDataToCloud = { name: 'sendDataToCloud', - title: function(gd) { return ____473(gd, 'Edit in Chart Studio'); }, + title: function(gd) { return ____535(gd, 'Edit in Chart Studio'); }, icon: _$ploticon_2.disk, click: function(gd) { - _$plots_647.sendDataToCloud(gd); + _$plots_709.sendDataToCloud(gd); } }; modeBarButtons.zoom2d = { name: 'zoom2d', - title: function(gd) { return ____473(gd, 'Zoom'); }, + title: function(gd) { return ____535(gd, 'Zoom'); }, attr: 'dragmode', val: 'zoom', icon: _$ploticon_2.zoombox, @@ -73051,7 +75096,7 @@ modeBarButtons.zoom2d = { modeBarButtons.pan2d = { name: 'pan2d', - title: function(gd) { return ____473(gd, 'Pan'); }, + title: function(gd) { return ____535(gd, 'Pan'); }, attr: 'dragmode', val: 'pan', icon: _$ploticon_2.pan, @@ -73060,7 +75105,7 @@ modeBarButtons.pan2d = { modeBarButtons.select2d = { name: 'select2d', - title: function(gd) { return ____473(gd, 'Box Select'); }, + title: function(gd) { return ____535(gd, 'Box Select'); }, attr: 'dragmode', val: 'select', icon: _$ploticon_2.selectbox, @@ -73069,7 +75114,7 @@ modeBarButtons.select2d = { modeBarButtons.lasso2d = { name: 'lasso2d', - title: function(gd) { return ____473(gd, 'Lasso Select'); }, + title: function(gd) { return ____535(gd, 'Lasso Select'); }, attr: 'dragmode', val: 'lasso', icon: _$ploticon_2.lasso, @@ -73078,7 +75123,7 @@ modeBarButtons.lasso2d = { modeBarButtons.zoomIn2d = { name: 'zoomIn2d', - title: function(gd) { return ____473(gd, 'Zoom in'); }, + title: function(gd) { return ____535(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: _$ploticon_2.zoom_plus, @@ -73087,7 +75132,7 @@ modeBarButtons.zoomIn2d = { modeBarButtons.zoomOut2d = { name: 'zoomOut2d', - title: function(gd) { return ____473(gd, 'Zoom out'); }, + title: function(gd) { return ____535(gd, 'Zoom out'); }, attr: 'zoom', val: 'out', icon: _$ploticon_2.zoom_minus, @@ -73096,7 +75141,7 @@ modeBarButtons.zoomOut2d = { modeBarButtons.autoScale2d = { name: 'autoScale2d', - title: function(gd) { return ____473(gd, 'Autoscale'); }, + title: function(gd) { return ____535(gd, 'Autoscale'); }, attr: 'zoom', val: 'auto', icon: _$ploticon_2.autoscale, @@ -73105,7 +75150,7 @@ modeBarButtons.autoScale2d = { modeBarButtons.resetScale2d = { name: 'resetScale2d', - title: function(gd) { return ____473(gd, 'Reset axes'); }, + title: function(gd) { return ____535(gd, 'Reset axes'); }, attr: 'zoom', val: 'reset', icon: _$ploticon_2.home, @@ -73114,7 +75159,7 @@ modeBarButtons.resetScale2d = { modeBarButtons.hoverClosestCartesian = { name: 'hoverClosestCartesian', - title: function(gd) { return ____473(gd, 'Show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Show closest data on hover'); }, attr: 'hovermode', val: 'closest', icon: _$ploticon_2.tooltip_basic, @@ -73124,7 +75169,7 @@ modeBarButtons.hoverClosestCartesian = { modeBarButtons.hoverCompareCartesian = { name: 'hoverCompareCartesian', - title: function(gd) { return ____473(gd, 'Compare data on hover'); }, + title: function(gd) { return ____535(gd, 'Compare data on hover'); }, attr: 'hovermode', val: function(gd) { return gd._fullLayout._isHoriz ? 'y' : 'x'; @@ -73140,7 +75185,7 @@ function handleCartesian(gd, ev) { var val = button.getAttribute('data-val') || true; var fullLayout = gd._fullLayout; var aobj = {}; - var axList = _$axis_ids_587.list(gd, null, true); + var axList = _$axis_ids_650.list(gd, null, true); var allSpikesEnabled = 'on'; var ax, i; @@ -73210,12 +75255,12 @@ function handleCartesian(gd, ev) { aobj[astr] = val; } - _$registry_668.call('relayout', gd, aobj); + _$registry_731.call('relayout', gd, aobj); } modeBarButtons.zoom3d = { name: 'zoom3d', - title: function(gd) { return ____473(gd, 'Zoom'); }, + title: function(gd) { return ____535(gd, 'Zoom'); }, attr: 'scene.dragmode', val: 'zoom', icon: _$ploticon_2.zoombox, @@ -73224,7 +75269,7 @@ modeBarButtons.zoom3d = { modeBarButtons.pan3d = { name: 'pan3d', - title: function(gd) { return ____473(gd, 'Pan'); }, + title: function(gd) { return ____535(gd, 'Pan'); }, attr: 'scene.dragmode', val: 'pan', icon: _$ploticon_2.pan, @@ -73233,7 +75278,7 @@ modeBarButtons.pan3d = { modeBarButtons.orbitRotation = { name: 'orbitRotation', - title: function(gd) { return ____473(gd, 'Orbital rotation'); }, + title: function(gd) { return ____535(gd, 'Orbital rotation'); }, attr: 'scene.dragmode', val: 'orbit', icon: _$ploticon_2['3d_rotate'], @@ -73242,7 +75287,7 @@ modeBarButtons.orbitRotation = { modeBarButtons.tableRotation = { name: 'tableRotation', - title: function(gd) { return ____473(gd, 'Turntable rotation'); }, + title: function(gd) { return ____535(gd, 'Turntable rotation'); }, attr: 'scene.dragmode', val: 'turntable', icon: _$ploticon_2['z-axis'], @@ -73266,12 +75311,12 @@ function handleDrag3d(gd, ev) { var val2d = (val === 'pan') ? val : 'zoom'; layoutUpdate.dragmode = val2d; - _$registry_668.call('relayout', gd, layoutUpdate); + _$registry_731.call('relayout', gd, layoutUpdate); } modeBarButtons.resetCameraDefault3d = { name: 'resetCameraDefault3d', - title: function(gd) { return ____473(gd, 'Reset camera to default'); }, + title: function(gd) { return ____535(gd, 'Reset camera to default'); }, attr: 'resetDefault', icon: _$ploticon_2.home, click: handleCamera3d @@ -73279,7 +75324,7 @@ modeBarButtons.resetCameraDefault3d = { modeBarButtons.resetCameraLastSave3d = { name: 'resetCameraLastSave3d', - title: function(gd) { return ____473(gd, 'Reset camera to last save'); }, + title: function(gd) { return ____535(gd, 'Reset camera to last save'); }, attr: 'resetLastSave', icon: _$ploticon_2.movie, click: handleCamera3d @@ -73301,16 +75346,16 @@ function handleCamera3d(gd, ev) { aobj[key] = null; } else if(attr === 'resetLastSave') { - aobj[key] = _$lib_539.extendDeep({}, scene.cameraInitial); + aobj[key] = _$lib_601.extendDeep({}, scene.cameraInitial); } } - _$registry_668.call('relayout', gd, aobj); + _$registry_731.call('relayout', gd, aobj); } modeBarButtons.hoverClosest3d = { name: 'hoverClosest3d', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -73335,7 +75380,7 @@ function handleHover3d(gd, ev) { var layoutUpdate = {}; if(val) { - layoutUpdate = _$lib_539.extendDeep(layout, val); + layoutUpdate = _$lib_601.extendDeep(layout, val); button._previousVal = null; } else { @@ -73363,15 +75408,15 @@ function handleHover3d(gd, ev) { } } - button._previousVal = _$lib_539.extendDeep({}, currentSpikes); + button._previousVal = _$lib_601.extendDeep({}, currentSpikes); } - _$registry_668.call('relayout', gd, layoutUpdate); + _$registry_731.call('relayout', gd, layoutUpdate); } modeBarButtons.zoomInGeo = { name: 'zoomInGeo', - title: function(gd) { return ____473(gd, 'Zoom in'); }, + title: function(gd) { return ____535(gd, 'Zoom in'); }, attr: 'zoom', val: 'in', icon: _$ploticon_2.zoom_plus, @@ -73380,7 +75425,7 @@ modeBarButtons.zoomInGeo = { modeBarButtons.zoomOutGeo = { name: 'zoomOutGeo', - title: function(gd) { return ____473(gd, 'Zoom out'); }, + title: function(gd) { return ____535(gd, 'Zoom out'); }, attr: 'zoom', val: 'out', icon: _$ploticon_2.zoom_minus, @@ -73389,7 +75434,7 @@ modeBarButtons.zoomOutGeo = { modeBarButtons.resetGeo = { name: 'resetGeo', - title: function(gd) { return ____473(gd, 'Reset'); }, + title: function(gd) { return ____535(gd, 'Reset'); }, attr: 'reset', val: null, icon: _$ploticon_2.autoscale, @@ -73398,7 +75443,7 @@ modeBarButtons.resetGeo = { modeBarButtons.hoverClosestGeo = { name: 'hoverClosestGeo', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -73422,7 +75467,7 @@ function handleGeo(gd, ev) { var scale = geoLayout.projection.scale; var newScale = (val === 'in') ? 2 * scale : 0.5 * scale; - _$registry_668.call('relayout', gd, id + '.projection.scale', newScale); + _$registry_731.call('relayout', gd, id + '.projection.scale', newScale); } else if(attr === 'reset') { resetView(gd, 'geo'); } @@ -73431,7 +75476,7 @@ function handleGeo(gd, ev) { modeBarButtons.hoverClosestGl2d = { name: 'hoverClosestGl2d', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -73442,7 +75487,7 @@ modeBarButtons.hoverClosestGl2d = { modeBarButtons.hoverClosestPie = { name: 'hoverClosestPie', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: 'closest', icon: _$ploticon_2.tooltip_basic, @@ -73461,14 +75506,14 @@ function toggleHover(gd) { var newHover = gd._fullLayout.hovermode ? false : onHoverVal; - _$registry_668.call('relayout', gd, 'hovermode', newHover); + _$registry_731.call('relayout', gd, 'hovermode', newHover); } // buttons when more then one plot types are present modeBarButtons.toggleHover = { name: 'toggleHover', - title: function(gd) { return ____473(gd, 'Toggle show closest data on hover'); }, + title: function(gd) { return ____535(gd, 'Toggle show closest data on hover'); }, attr: 'hovermode', val: null, toggle: true, @@ -73486,7 +75531,7 @@ modeBarButtons.toggleHover = { modeBarButtons.resetViews = { name: 'resetViews', - title: function(gd) { return ____473(gd, 'Reset views'); }, + title: function(gd) { return ____535(gd, 'Reset views'); }, icon: _$ploticon_2.home, click: function(gd, ev) { var button = ev.currentTarget; @@ -73505,7 +75550,7 @@ modeBarButtons.resetViews = { modeBarButtons.toggleSpikelines = { name: 'toggleSpikelines', - title: function(gd) { return ____473(gd, 'Toggle Spike Lines'); }, + title: function(gd) { return ____535(gd, 'Toggle Spike Lines'); }, icon: _$ploticon_2.spikeline, attr: '_cartesianSpikesEnabled', val: 'on', @@ -73516,13 +75561,13 @@ modeBarButtons.toggleSpikelines = { var aobj = setSpikelineVisibility(gd); - _$registry_668.call('relayout', gd, aobj); + _$registry_731.call('relayout', gd, aobj); } }; function setSpikelineVisibility(gd) { var fullLayout = gd._fullLayout; - var axList = _$axis_ids_587.list(gd, null, true); + var axList = _$axis_ids_650.list(gd, null, true); var aobj = {}; var ax, axName; @@ -73538,7 +75583,7 @@ function setSpikelineVisibility(gd) { modeBarButtons.resetViewMapbox = { name: 'resetViewMapbox', - title: function(gd) { return ____473(gd, 'Reset view'); }, + title: function(gd) { return ____535(gd, 'Reset view'); }, attr: 'reset', icon: _$ploticon_2.home, click: function(gd) { @@ -73563,7 +75608,7 @@ function resetView(gd, subplotType) { } } - _$registry_668.call('relayout', gd, aObj); + _$registry_731.call('relayout', gd, aObj); } /** @@ -73577,9 +75622,9 @@ function resetView(gd, subplotType) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /* removed: var _$ploticon_2 = require('../../../build/ploticon'); */; @@ -73600,7 +75645,7 @@ function ModeBar(opts) { this.container.appendChild(this.element); } -var __proto_476 = ModeBar.prototype; +var __proto_538 = ModeBar.prototype; /** * Update modeBar (buttons and logo) @@ -73609,7 +75654,7 @@ var __proto_476 = ModeBar.prototype; * @param {array of arrays} buttons nested arrays of grouped buttons to initialize * */ -__proto_476.update = function(graphInfo, buttons) { +__proto_538.update = function(graphInfo, buttons) { this.graphInfo = graphInfo; var context = this.graphInfo._context; @@ -73637,7 +75682,7 @@ __proto_476.update = function(graphInfo, buttons) { this.updateActiveButton(); }; -__proto_476.updateButtons = function(buttons) { +__proto_538.updateButtons = function(buttons) { var _this = this; this.buttons = buttons; @@ -73653,1607 +75698,484 @@ __proto_476.updateButtons = function(buttons) { 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_476.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_476.createButton = function(config) { - var _this = this, - 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_127.select(button).classed('active', true); - - button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); - 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 - * @Return {HTMLelement} - */ -__proto_476.createIcon = function(thisIcon, name) { - var iconHeight = thisIcon.ascent - thisIcon.descent, - svgNS = 'http://www.w3.org/2000/svg', - icon = document.createElementNS(svgNS, 'svg'), - path = document.createElementNS(svgNS, 'path'); - - icon.setAttribute('height', '1em'); - icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); - icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - - var transform = name === 'toggleSpikelines' ? - 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : - 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - - path.setAttribute('d', thisIcon.path); - path.setAttribute('transform', transform); - icon.appendChild(path); - - return icon; -}; - -/** - * Updates active button with attribute specified in layout - * @Param {object} graphInfo plot object containing data and layout - * @Return {HTMLelement} - */ -__proto_476.updateActiveButton = function(buttonClicked) { - var fullLayout = this.graphInfo._fullLayout, - dataAttrClicked = (buttonClicked !== undefined) ? - buttonClicked.getAttribute('data-attr') : - null; - - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute('data-val') || true, - dataAttr = button.getAttribute('data-attr'), - isToggleButton = (button.getAttribute('data-toggle') === 'true'), - button3 = _$d3_127.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_539.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_476.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_476.getLogo = function() { - var group = this.createGroup(), - a = document.createElement('a'); - - a.href = 'https://plot.ly/'; - a.target = '_blank'; - a.setAttribute('data-title', _$lib_539._(this.graphInfo, 'Produced with Plotly')); - a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - - a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - - group.appendChild(a); - return group; -}; - -__proto_476.removeAllButtons = function() { - while(this.element.firstChild) { - this.element.removeChild(this.element.firstChild); - } - - this.hasLogo = false; -}; - -__proto_476.destroy = function() { - _$lib_539.removeElement(this.container.querySelector('.modebar')); -}; - -function createModeBar(gd, buttons) { - var fullLayout = gd._fullLayout; - - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._paperdiv.node(), - buttons: buttons - }); - - if(fullLayout._privateplot) { - _$d3_127.select(modeBar.element).append('span') - .classed('badge-private float--left', true) - .text('PRIVATE'); - } - - return modeBar; -} - -var _$createModeBar_476 = createModeBar; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$subtypes_884 = require('../../traces/scatter/subtypes'); */; -/* removed: var _$registry_668 = require('../../registry'); */; - -/* removed: var _$createModeBar_476 = require('./modebar'); */; -/* removed: var _$buttons_473 = require('./buttons'); */; - -/** - * ModeBar wrapper around 'create' and 'update', - * chooses buttons to pass to ModeBar constructor based on - * plot type and plot config. - * - * @param {object} gd main plot object - * - */ -var _$manageModeBar_475 = function manageModeBar(gd) { - var fullLayout = gd._fullLayout, - context = gd._context, - modeBar = fullLayout._modeBar; - - if(!context.displayModeBar) { - if(modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } - - if(!Array.isArray(context.modeBarButtonsToRemove)) { - throw new Error([ - '*modeBarButtonsToRemove* configuration options', - 'must be an array.' - ].join(' ')); - } - - if(!Array.isArray(context.modeBarButtonsToAdd)) { - throw new Error([ - '*modeBarButtonsToAdd* configuration options', - 'must be an array.' - ].join(' ')); - } - - var customButtons = context.modeBarButtons; - var buttonGroups; - - if(Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } - else { - buttonGroups = getButtonGroups( - gd, - context.modeBarButtonsToRemove, - context.modeBarButtonsToAdd - ); - } - - if(modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = _$createModeBar_476(gd, buttonGroups); -}; - -// logic behind which buttons are displayed by default -function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; - - var hasCartesian = fullLayout._has('cartesian'); - var hasGL3D = fullLayout._has('gl3d'); - var hasGeo = fullLayout._has('geo'); - var hasPie = fullLayout._has('pie'); - var hasGL2D = fullLayout._has('gl2d'); - var hasTernary = fullLayout._has('ternary'); - var hasMapbox = fullLayout._has('mapbox'); - var hasPolar = fullLayout._has('polar'); - var allAxesFixed = areAllAxesFixed(fullLayout); - - var groups = []; - - function addGroup(newGroup) { - if(!newGroup.length) return; - - var out = []; - - for(var i = 0; i < newGroup.length; i++) { - var button = newGroup[i]; - if(buttonsToRemove.indexOf(button) !== -1) continue; - out.push(_$buttons_473[button]); - } - - groups.push(out); - } - - // buttons common to all plot types - addGroup(['toImage', 'sendDataToCloud']); - - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; - - if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { - // graphs with more than one plot types get 'union buttons' - // which reset the view or toggle hover labels across all subplots. - hoverGroup = ['toggleHover']; - resetGroup = ['resetViews']; - } - else if(hasGeo) { - zoomGroup = ['zoomInGeo', 'zoomOutGeo']; - hoverGroup = ['hoverClosestGeo']; - resetGroup = ['resetGeo']; - } - else if(hasGL3D) { - hoverGroup = ['hoverClosest3d']; - resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; - } - else if(hasMapbox) { - hoverGroup = ['toggleHover']; - resetGroup = ['resetViewMapbox']; - } - else if(hasGL2D) { - hoverGroup = ['hoverClosestGl2d']; - } - else if(hasPie) { - hoverGroup = ['hoverClosestPie']; - } - else { // hasPolar, hasTernary - // always show at least one hover icon. - hoverGroup = ['toggleHover']; - } - // if we have cartesian, allow switching between closest and compare - // regardless of what other types are on the plot, since they'll all - // just treat any truthy hovermode as 'closest' - if(hasCartesian) { - hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; - } - - if((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; - if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; - } - - if(hasGL3D) { - dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; - } - else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { - dragModeGroup = ['zoom2d', 'pan2d']; - } - else if(hasMapbox || hasGeo) { - dragModeGroup = ['pan2d']; - } - else if(hasPolar) { - dragModeGroup = ['zoom2d']; - } - if(isSelectable(fullData)) { - dragModeGroup.push('select2d', 'lasso2d'); - } - - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(hoverGroup); - - return appendButtonsToGroups(groups, buttonsToAdd); -} - -function areAllAxesFixed(fullLayout) { - var axList = _$axis_ids_587.list({_fullLayout: fullLayout}, null, true); - - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) { - return false; - } - } - - return true; -} - -// look for traces that support selection -// to be updated as we add more selectPoints handlers -function isSelectable(fullData) { - var selectable = false; - - for(var i = 0; i < fullData.length; i++) { - if(selectable) break; - - var trace = fullData[i]; - - if(!trace._module || !trace._module.selectPoints) continue; - - if(_$registry_668.traceIs(trace, 'scatter-like')) { - if(_$subtypes_884.hasMarkers(trace) || _$subtypes_884.hasText(trace)) { - selectable = true; - } - } else if(_$registry_668.traceIs(trace, 'box-violin')) { - if(trace.boxpoints === 'all' || trace.points === 'all') { - selectable = true; - } - } - // assume that in general if the trace module has selectPoints, - // then it's selectable. Scatter is an exception to this because it must - // have markers or text, not just be a scatter type. - else selectable = true; - } - - return selectable; -} - -function appendButtonsToGroups(groups, buttons) { - if(buttons.length) { - if(Array.isArray(buttons[0])) { - for(var i = 0; i < buttons.length; i++) { - groups.push(buttons[i]); - } - } - else groups.push(buttons); - } - - return groups; -} - -// fill in custom buttons referring to default mode bar buttons -function fillCustomButton(customButtons) { - for(var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; - - for(var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; - - if(typeof button === 'string') { - if(_$buttons_473[button] !== undefined) { - customButtons[i][j] = _$buttons_473[button]; - } - else { - throw new Error([ - '*modeBarButtons* configuration options', - 'invalid button name' - ].join(' ')); - } - } - } - } - - return customButtons; -} - -var _$modebar_474 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -_$modebar_474.manage = _$manageModeBar_475; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var FROM_BL = _$alignment_511.FROM_BL; - -var _$scaleZoom_601 = function scaleZoom(ax, factor, centerFraction) { - if(centerFraction === undefined) { - centerFraction = FROM_BL[ax.constraintoward || 'center']; - } - - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; -}; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; - -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -var __FROM_TL_592 = _$alignment_511.FROM_TL; - -/* removed: var _$plots_647 = require('../plots'); */; - -var doTicks = _$axes_584.doTicks; -var getFromId = _$axis_ids_587.getFromId; -/* removed: var _$prepSelect_602 = require('./select'); */; -/* removed: var _$scaleZoom_601 = require('./scale_zoom'); */; - -/* removed: var _$constants_589 = require('./constants'); */; -var MINDRAG = _$constants_589.MINDRAG; -var MINZOOM = _$constants_589.MINZOOM; - - -// flag for showing "doubleclick to zoom out" only at the beginning -var SHOWZOOMOUTTIP = true; - -// dragBox: create an element to drag one or more axis ends -// inputs: -// plotinfo - which subplot are we making dragboxes on? -// x,y,w,h - left, top, width, height of the box -// ns - how does this drag the vertical axis? -// 'n' - top only -// 's' - bottom only -// 'ns' - top and bottom together, difference unchanged -// ew - same for horizontal axis -function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - // mouseDown stores ms of first mousedown event in the last - // DBLCLICKDELAY ms on the drag bars - // numClicks stores how many mousedowns have been seen - // within DBLCLICKDELAY so we can check for click or doubleclick events - // dragged stores whether a drag has occurred, so we don't have to - // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px - var fullLayout = gd._fullLayout; - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = (ns + ew === 'nsew'); - var singleEnd = (ns + ew).length === 1; - - var subplots, xa, ya, xs, ys, pw, ph, xActive, yActive, cursor, - isSubplotConstrained, xaLinked, yaLinked; - - function recomputeAxisLists() { - xa = [plotinfo.xaxis]; - ya = [plotinfo.yaxis]; - var xa0 = xa[0]; - var ya0 = ya[0]; - pw = xa0._length; - ph = ya0._length; - - var constraintGroups = fullLayout._axisConstraintGroups; - var xIDs = [xa0._id]; - var yIDs = [ya0._id]; - - // if we're dragging two axes at once, also drag overlays - subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []); - - for(var i = 1; i < subplots.length; i++) { - var subplotXa = subplots[i].xaxis, - subplotYa = subplots[i].yaxis; - - if(xa.indexOf(subplotXa) === -1) { - xa.push(subplotXa); - xIDs.push(subplotXa._id); - } - - if(ya.indexOf(subplotYa) === -1) { - ya.push(subplotYa); - yIDs.push(subplotYa._id); - } - } - - xActive = isDirectionActive(xa, ew); - yActive = isDirectionActive(ya, ns); - cursor = getDragCursor(yActive + xActive, fullLayout.dragmode); - xs = xa0._offset; - ys = ya0._offset; - - var links = calcLinks(constraintGroups, xIDs, yIDs); - isSubplotConstrained = links.xy; - - // finally make the list of axis objects to link - xaLinked = []; - for(var xLinkID in links.x) { xaLinked.push(getFromId(gd, xLinkID)); } - yaLinked = []; - for(var yLinkID in links.y) { yaLinked.push(getFromId(gd, yLinkID)); } - } - - recomputeAxisLists(); - - var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h); - - var allFixedRanges = !yActive && !xActive; - - // still need to make the element if the axes are disabled - // but nuke its events (except for maindrag which needs them for hover) - // and stop there - if(allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = 'none'; - return dragger; - } - - var dragOptions = { - element: dragger, - gd: gd, - plotinfo: plotinfo, - prepFn: function(e, startX, startY) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!allFixedRanges) { - if(isMainDrag) { - // main dragger handles all drag modes, and changes - // to pan (or to zoom if it already is pan) on shift - if(e.shiftKey) { - if(dragModeNow === 'pan') dragModeNow = 'zoom'; - else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan'; - } - else if(e.ctrlKey) { - dragModeNow = 'pan'; - } - } - // all other draggers just pan - else dragModeNow = 'pan'; - } - - if(dragModeNow === 'lasso') dragOptions.minDrag = 1; - else dragOptions.minDrag = undefined; - - if(isSelectOrLasso(dragModeNow)) { - dragOptions.xaxes = xa; - dragOptions.yaxes = ya; - _$prepSelect_602(e, startX, startY, dragOptions, dragModeNow); - } - else if(allFixedRanges) { - clearSelect(zoomlayer); - } - else if(dragModeNow === 'zoom') { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; - - // zoomMove takes care of the threshold, but we need to - // minimize this so that constrained zoom boxes will flip - // orientation at the right place - dragOptions.minDrag = 1; - - zoomPrep(e, startX, startY); - } - else if(dragModeNow === 'pan') { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - clearSelect(zoomlayer); - } - }, - clickFn: function(numClicks, evt) { - removeZoombox(gd); - - if(numClicks === 2 && !singleEnd) doubleClick(); - - if(isMainDrag) { - _$fx_453.click(gd, evt, plotinfo.id); - } - else if(numClicks === 1 && singleEnd) { - var ax = ns ? ya[0] : xa[0], - end = (ns === 's' || ew === 'w') ? 0 : 1, - attrStr = ax._name + '.range[' + end + ']', - initialText = getEndText(ax, end), - hAlign = 'left', - vAlign = 'middle'; - - if(ax.fixedrange) return; - - if(ns) { - vAlign = (ns === 'n') ? 'top' : 'bottom'; - if(ax.side === 'right') hAlign = 'right'; - } - else if(ew === 'e') hAlign = 'right'; - - if(gd._context.showAxisRangeEntryBoxes) { - _$d3_127.select(dragger) - .call(_$svg_text_utils_562.makeEditable, { - gd: gd, - immediate: true, - background: fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : '#444', - horizontalAlign: hAlign, - verticalAlign: vAlign - }) - .on('edit', function(text) { - var v = ax.d2r(text); - if(v !== undefined) { - _$registry_668.call('relayout', gd, attrStr, v); - } - }); - } - } - } - }; - - _$dragelement_433.init(dragOptions); - - var x0, - y0, - box, - lum, - path0, - dimmed, - zoomMode, - zb, - corners; - - // collected changes to be made to the plot by relayout at the end - var updates = {}; - - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0}; - lum = gd._hmpixcount ? - (gd._hmlumcount / gd._hmpixcount) : - _$tinycolor_352(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0'; - dimmed = false; - zoomMode = 'xy'; - - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - - corners = makeCorners(zoomlayer, xs, ys); - - clearSelect(zoomlayer); - } - - function zoomMove(dx0, dy0) { - if(gd._transitioningWithDuration) { - return false; - } - - var x1 = Math.max(0, Math.min(pw, dx0 + x0)), - y1 = Math.max(0, Math.min(ph, dy0 + y0)), - dx = Math.abs(x1 - x0), - dy = Math.abs(y1 - y0); - - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); - - function noZoom() { - zoomMode = ''; - box.r = box.l; - box.t = box.b; - corners.attr('d', 'M0,0Z'); - } - - if(isSubplotConstrained) { - if(dx > MINZOOM || dy > MINZOOM) { - zoomMode = 'xy'; - if(dx / pw > dy / ph) { - dy = dx * ph / pw; - if(y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } - else { - dx = dy * pw / ph; - if(x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr('d', xyCorners(box)); - } - else { - noZoom(); - } - } - // look for small drags in one direction or the other, - // and only drag the other axis - else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if(dx < MINDRAG) { - noZoom(); - } - else { - box.t = 0; - box.b = ph; - zoomMode = 'x'; - corners.attr('d', xCorners(box, y0)); - } - } - else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = 'y'; - corners.attr('d', yCorners(box, x0)); - } - else { - zoomMode = 'xy'; - corners.attr('d', xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; - - updateZoombox(zb, corners, box, path0, dimmed, lum); - dimmed = true; - } - - function zoomDone() { - // more strict than dragged, which allows you to come back to where you started - // and still count as dragged - if(Math.min(box.h, box.w) < MINDRAG * 2) { - return removeZoombox(gd); - } - - // TODO: edit linked axes in zoomAxRanges and in dragTail - if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw, updates, xaLinked); - if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph, updates, yaLinked); - - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); - } - - // scroll zoom, on all draggers except corners - var scrollViewBox = [0, 0, pw, ph]; - // wait a little after scrolling before redrawing - var redrawTimer = null; - var REDRAWDELAY = _$constants_589.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? - fullLayout._plots[plotinfo.mainplot] : plotinfo; - - function zoomWheel(e) { - // deactivate mousewheel scrolling on embedded graphs - // devs can override this with layout._enablescrollzoom, - // but _ ensures this setting won't leave their page - if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) { - return; - } - - if(redrawTimer === null) { - clearSelect(zoomlayer); - } - - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } - - var pc = gd.querySelector('.plotly'); - - recomputeAxisLists(); - - // if the plot has scrollbars (more than a tiny excess) - // disable scrollzoom too. - if(pc.scrollHeight - pc.clientHeight > 10 || - pc.scrollWidth - pc.clientWidth > 10) { - return; - } - - clearTimeout(redrawTimer); - - var wheelDelta = -e.deltaY; - if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if(!isFinite(wheelDelta)) { - _$lib_539.log('Did not find wheel motion attributes: ', e); - return; - } - - var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200), - gbb = mainplot.draglayer.select('.nsewdrag') - .node().getBoundingClientRect(), - xfrac = (e.clientX - gbb.left) / gbb.width, - yfrac = (gbb.bottom - e.clientY) / gbb.height, - i; - - function zoomWheelOneAxis(ax, centerFraction, zoom) { - if(ax.fixedrange) return; - - var axRange = _$lib_539.simpleMap(ax.range, ax.r2l), - v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); } - ax.range = axRange.map(doZoom); - } + throw new Error('button name \'' + buttonName + '\' is taken'); + } + _this.buttonsNames.push(buttonName); - if(ew || isSubplotConstrained) { - // if we're only zooming this axis because of constraints, - // zoom it about the center - if(!ew) xfrac = 0.5; + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); - for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom); + _this.element.appendChild(group); + }); +}; - scrollViewBox[2] *= zoom; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1); - } - if(ns || isSubplotConstrained) { - if(!ns) yfrac = 0.5; +/** + * Empty div for containing a group of buttons + * @Return {HTMLelement} + */ +__proto_538.createGroup = function() { + var group = document.createElement('div'); + group.className = 'modebar-group'; - for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom); + return group; +}; - scrollViewBox[3] *= zoom; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1); - } +/** + * Create a new button div and set constant and configurable attributes + * @Param {object} config (see ./buttons.js for more info) + * @Return {HTMLelement} + */ +__proto_538.createButton = function(config) { + var _this = this, + button = document.createElement('a'); - // viewbox redraw at first - updateSubplots(scrollViewBox); - ticksAndAnnotations(ns, ew); + button.setAttribute('rel', 'tooltip'); + button.className = 'modebar-btn'; - // then replot after a delay to make sure - // no more scrolling is coming - redrawTimer = setTimeout(function() { - scrollViewBox = [0, 0, pw, ph]; + 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); - var zoomMode; - if(isSubplotConstrained) zoomMode = 'xy'; - else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : ''); + if(title || title === 0) button.setAttribute('data-title', title); - dragTail(zoomMode); - }, REDRAWDELAY); + if(config.attr !== undefined) button.setAttribute('data-attr', config.attr); - e.preventDefault(); - return; + var val = config.val; + if(val !== undefined) { + if(typeof val === 'function') val = val(this.graphInfo); + button.setAttribute('data-val', val); } - // everything but the corners gets wheel zoom - if(ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); + 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); - // plotDrag: move the plot in response to a drag - function plotDrag(dx, dy) { - // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { - return; - } - - recomputeAxisLists(); - - if(xActive === 'ew' || yActive === 'ns') { - if(xActive) dragAxList(xa, dx); - if(yActive) dragAxList(ya, dy); - updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]); - ticksAndAnnotations(yActive, xActive); - return; - } + // only needed for 'hoverClosestGeo' which does not call relayout + _this.updateActiveButton(ev.currentTarget); + }); + } - // dz: set a new value for one end (0 or 1) of an axis array axArray, - // and return a pixel shift for that end for the viewbox - // based on pixel drag distance d - // TODO: this makes (generally non-fatal) errors when you get - // near floating point limits - function dz(axArray, end, d) { - var otherEnd = 1 - end, - movedAx, - newLinearizedEnd; - for(var i = 0; i < axArray.length; i++) { - var axi = axArray[i]; - if(axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + - (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); + button.setAttribute('data-toggle', config.toggle || false); + if(config.toggle) _$d3_130.select(button).classed('active', true); - // if l2r comes back false or undefined, it means we've dragged off - // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / - (movedAx._rl[end] - movedAx._rl[otherEnd]); - } + button.appendChild(this.createIcon(config.icon || _$ploticon_2.question, config.name)); + button.setAttribute('data-gravity', config.gravity || 'n'); - if(isSubplotConstrained && xActive && yActive) { - // dragging a corner of a constrained subplot: - // respect the fixed corner, but harmonize dx and dy - var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1; - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } + return button; +}; - if(xActive === 'w') dx = dz(xa, 0, dx); - else if(xActive === 'e') dx = dz(xa, 1, -dx); - else if(!xActive) dx = 0; +/** + * Add an icon to a button + * @Param {object} thisIcon + * @Param {number} thisIcon.width + * @Param {string} thisIcon.path + * @Return {HTMLelement} + */ +__proto_538.createIcon = function(thisIcon, name) { + var iconHeight = thisIcon.ascent - thisIcon.descent, + svgNS = 'http://www.w3.org/2000/svg', + icon = document.createElementNS(svgNS, 'svg'), + path = document.createElementNS(svgNS, 'path'); - if(yActive === 'n') dy = dz(ya, 1, dy); - else if(yActive === 's') dy = dz(ya, 0, -dy); - else if(!yActive) dy = 0; + icon.setAttribute('height', '1em'); + icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em'); + icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' ')); - var x0 = (xActive === 'w') ? dx : 0; - var y0 = (yActive === 'n') ? dy : 0; + var transform = name === 'toggleSpikelines' ? + 'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' : + 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')'; - if(isSubplotConstrained) { - var i; - if(!xActive && yActive.length === 1) { - // dragging one end of the y axis of a constrained subplot - // scale the other axis the same about its middle - for(i = 0; i < xa.length; i++) { - xa[i].range = xa[i]._r.slice(); - _$scaleZoom_601(xa[i], 1 - dy / ph); - } - dx = dy * pw / ph; - x0 = dx / 2; - } - if(!yActive && xActive.length === 1) { - for(i = 0; i < ya.length; i++) { - ya[i].range = ya[i]._r.slice(); - _$scaleZoom_601(ya[i], 1 - dx / pw); - } - dy = dx * ph / pw; - y0 = dy / 2; - } - } + path.setAttribute('d', thisIcon.path); + path.setAttribute('transform', transform); + icon.appendChild(path); - updateSubplots([x0, y0, pw - dx, ph - dy]); + return icon; +}; - ticksAndAnnotations(yActive, xActive); - } +/** + * Updates active button with attribute specified in layout + * @Param {object} graphInfo plot object containing data and layout + * @Return {HTMLelement} + */ +__proto_538.updateActiveButton = function(buttonClicked) { + var fullLayout = this.graphInfo._fullLayout, + dataAttrClicked = (buttonClicked !== undefined) ? + buttonClicked.getAttribute('data-attr') : + null; - // Draw ticks and annotations (and other components) when ranges change. - // Also records the ranges that have changed for use by update at the end. - function ticksAndAnnotations(ns, ew) { - var activeAxIds = [], - i; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute('data-val') || true, + dataAttr = button.getAttribute('data-attr'), + isToggleButton = (button.getAttribute('data-toggle') === 'true'), + button3 = _$d3_130.select(button); - function pushActiveAxIds(axList) { - for(i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + // 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_601.nestedProperty(fullLayout, dataAttr).get(); - if(ew || isSubplotConstrained) { - pushActiveAxIds(xa); - pushActiveAxIds(xaLinked); - } - if(ns || isSubplotConstrained) { - pushActiveAxIds(ya); - pushActiveAxIds(yaLinked); + button3.classed('active', val === thisval); } - updates = {}; - for(i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - doTicks(gd, axId, true); - var ax = getFromId(gd, axId); - updates[ax._name + '.range[0]'] = ax.range[0]; - updates[ax._name + '.range[1]'] = ax.range[1]; - } + }); +}; - function redrawObjs(objArray, method, shortCircuit) { - for(i = 0; i < objArray.length; i++) { - var obji = objArray[i]; +/** + * Check if modeBar is configured as button configuration argument + * + * @Param {object} buttons 2d array of grouped button config objects + * @Return {boolean} + */ +__proto_538.hasButtons = function(buttons) { + var currentButtons = this.buttons; - if((ew && activeAxIds.indexOf(obji.xref) !== -1) || - (ns && activeAxIds.indexOf(obji.yref) !== -1)) { - method(gd, i); - // once is enough for images (which doesn't use the `i` arg anyway) - if(shortCircuit) return; - } - } - } + if(!currentButtons) return false; - // annotations and shapes 'draw' method is slow, - // use the finer-grained 'drawOne' method instead + if(buttons.length !== currentButtons.length) return false; - redrawObjs(fullLayout.annotations || [], _$registry_668.getComponentMethod('annotations', 'drawOne')); - redrawObjs(fullLayout.shapes || [], _$registry_668.getComponentMethod('shapes', 'drawOne')); - redrawObjs(fullLayout.images || [], _$registry_668.getComponentMethod('images', 'draw'), true); + 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; + } } - function doubleClick() { - if(gd._transitioningWithDuration) return; + return true; +}; - var doubleClickConfig = gd._context.doubleClick, - axList = (xActive ? xa : []).concat(yActive ? ya : []), - attrs = {}; +/** + * @return {HTMLDivElement} The logo image wrapped in a group + */ +__proto_538.getLogo = function() { + var group = this.createGroup(), + a = document.createElement('a'); - var ax, i, rangeInitial; + a.href = 'https://plot.ly/'; + a.target = '_blank'; + a.setAttribute('data-title', _$lib_601._(this.graphInfo, 'Produced with Plotly')); + a.className = 'modebar-btn plotlyjsicon modebar-btn--logo'; - // For reset+autosize mode: - // If *any* of the main axes is not at its initial range - // (or autoranged, if we have no initial range, to match the logic in - // doubleClickConfig === 'reset' below), we reset. - // If they are *all* at their initial ranges, then we autosize. - if(doubleClickConfig === 'reset+autosize') { + a.appendChild(this.createIcon(_$ploticon_2.plotlylogo)); - doubleClickConfig = 'autosize'; + group.appendChild(a); + return group; +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if((ax._rangeInitial && ( - ax.range[0] !== ax._rangeInitial[0] || - ax.range[1] !== ax._rangeInitial[1] - )) || - (!ax._rangeInitial && !ax.autorange) - ) { - doubleClickConfig = 'reset'; - break; - } - } - } +__proto_538.removeAllButtons = function() { + while(this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } - if(doubleClickConfig === 'autosize') { - // don't set the linked axes here, so relayout marks them as shrinkable - // and we autosize just to the requested axis/axes - for(i = 0; i < axList.length; i++) { - ax = axList[i]; - if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true; - } - } - else if(doubleClickConfig === 'reset') { - // when we're resetting, reset all linked axes too, so we get back - // to the fully-auto-with-constraints situation - if(xActive || isSubplotConstrained) axList = axList.concat(xaLinked); - if(yActive && !isSubplotConstrained) axList = axList.concat(yaLinked); + this.hasLogo = false; +}; - if(isSubplotConstrained) { - if(!xActive) axList = axList.concat(xa); - else if(!yActive) axList = axList.concat(ya); - } +__proto_538.destroy = function() { + _$lib_601.removeElement(this.container.querySelector('.modebar')); +}; - for(i = 0; i < axList.length; i++) { - ax = axList[i]; +function createModeBar(gd, buttons) { + var fullLayout = gd._fullLayout; - if(!ax._rangeInitial) { - attrs[ax._name + '.autorange'] = true; - } - else { - rangeInitial = ax._rangeInitial; - attrs[ax._name + '.range[0]'] = rangeInitial[0]; - attrs[ax._name + '.range[1]'] = rangeInitial[1]; - } - } - } + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._paperdiv.node(), + buttons: buttons + }); - gd.emit('plotly_doubleclick', null); - _$registry_668.call('relayout', gd, attrs); + if(fullLayout._privateplot) { + _$d3_130.select(modeBar.element).append('span') + .classed('badge-private float--left', true) + .text('PRIVATE'); } - // dragTail - finish a drag event with a redraw - function dragTail() { - // put the subplot viewboxes back to default (Because we're going to) - // be repositioning the data in the relayout. But DON'T call - // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + return modeBar; +} - // since we may have been redrawing some things during the drag, we may have - // accumulated MathJax promises - wait for them before we relayout. - _$lib_539.syncOrAsync([ - _$plots_647.previousPromises, - function() { _$registry_668.call('relayout', gd, updates); } - ], gd); - } +var _$createModeBar_538 = createModeBar; - // updateSubplots - find all plot viewboxes that should be - // affected by this drag, and update them. look for all plots - // sharing an affected axis (including the one being dragged) - function updateSubplots(viewBox) { - var plotinfos = fullLayout._plots; - var subplots = Object.keys(plotinfos); - var xScaleFactor = viewBox[2] / xa[0]._length; - var yScaleFactor = viewBox[3] / ya[0]._length; - var editX = ew || isSubplotConstrained; - var editY = ns || isSubplotConstrained; +/** +* Copyright 2012-2018, Plotly, Inc. +* All 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 i, xScaleFactor2, yScaleFactor2, clipDx, clipDy; - // Find the appropriate scaling for this axis, if it's linked to the - // dragged axes by constraints. 0 is special, it means this axis shouldn't - // ever be scaled (will be converted to 1 if the other axis is scaled) - function getLinkedScaleFactor(ax) { - if(ax.fixedrange) return 0; +'use strict'; - if(editX && xaLinked.indexOf(ax) !== -1) { - return xScaleFactor; - } - if(editY && (isSubplotConstrained ? xaLinked : yaLinked).indexOf(ax) !== -1) { - return yScaleFactor; - } - return 0; - } +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$subtypes_949 = require('../../traces/scatter/subtypes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; - function scaleAndGetShift(ax, scaleFactor) { - if(scaleFactor) { - ax.range = ax._r.slice(); - _$scaleZoom_601(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } +/* removed: var _$createModeBar_538 = require('./modebar'); */; +/* removed: var _$buttons_535 = require('./buttons'); */; - function getShift(ax, scaleFactor) { - return ax._length * (1 - scaleFactor) * __FROM_TL_592[ax.constraintoward || 'middle']; - } +/** + * ModeBar wrapper around 'create' and 'update', + * chooses buttons to pass to ModeBar constructor based on + * plot type and plot config. + * + * @param {object} gd main plot object + * + */ +var _$manageModeBar_537 = function manageModeBar(gd) { + var fullLayout = gd._fullLayout, + context = gd._context, + modeBar = fullLayout._modeBar; - // clear gl frame, if any, since we preserve drawing buffer - // FIXME: code duplication with cartesian.plot - if(fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if(d.regl) { - d.regl.clear({ - color: true - }); - } - }); + if(!context.displayModeBar) { + if(modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; } + return; + } - for(i = 0; i < subplots.length; i++) { - var subplot = plotinfos[subplots[i]], - xa2 = subplot.xaxis, - ya2 = subplot.yaxis, - editX2 = editX && !xa2.fixedrange && (xa.indexOf(xa2) !== -1), - editY2 = editY && !ya2.fixedrange && (ya.indexOf(ya2) !== -1); - - // scattergl translate - if(subplot._scene && subplot._scene.update) { - // FIXME: possibly we could update axis internal _r and _rl here - var xaRange = _$lib_539.simpleMap(xa2.range, xa2.r2l), - yaRange = _$lib_539.simpleMap(ya2.range, ya2.r2l); - subplot._scene.update( - {range: [xaRange[0], yaRange[0], xaRange[1], yaRange[1]]} - ); - } + if(!Array.isArray(context.modeBarButtonsToRemove)) { + throw new Error([ + '*modeBarButtonsToRemove* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew ? viewBox[0] : getShift(xa2, xScaleFactor2); - } - else { - xScaleFactor2 = getLinkedScaleFactor(xa2); - clipDx = scaleAndGetShift(xa2, xScaleFactor2); - } + if(!Array.isArray(context.modeBarButtonsToAdd)) { + throw new Error([ + '*modeBarButtonsToAdd* configuration options', + 'must be an array.' + ].join(' ')); + } - if(editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns ? viewBox[1] : getShift(ya2, yScaleFactor2); - } - else { - yScaleFactor2 = getLinkedScaleFactor(ya2); - clipDy = scaleAndGetShift(ya2, yScaleFactor2); - } + var customButtons = context.modeBarButtons; + var buttonGroups; - // don't scale at all if neither axis is scalable here - if(!xScaleFactor2 && !yScaleFactor2) { - continue; - } + if(Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } + else { + buttonGroups = getButtonGroups( + gd, + context.modeBarButtonsToRemove, + context.modeBarButtonsToAdd + ); + } - // but if only one is, reset the other axis scaling - if(!xScaleFactor2) xScaleFactor2 = 1; - if(!yScaleFactor2) yScaleFactor2 = 1; + if(modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = _$createModeBar_538(gd, buttonGroups); +}; - var plotDx = xa2._offset - clipDx / xScaleFactor2, - plotDy = ya2._offset - clipDy / yScaleFactor2; +// logic behind which buttons are displayed by default +function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; - fullLayout._defs.select('#' + subplot.clipId + '> rect') - .call(_$drawing_436.setTranslate, clipDx, clipDy) - .call(_$drawing_436.setScale, xScaleFactor2, yScaleFactor2); + var hasCartesian = fullLayout._has('cartesian'); + var hasGL3D = fullLayout._has('gl3d'); + var hasGeo = fullLayout._has('geo'); + var hasPie = fullLayout._has('pie'); + var hasGL2D = fullLayout._has('gl2d'); + var hasTernary = fullLayout._has('ternary'); + var hasMapbox = fullLayout._has('mapbox'); + var hasPolar = fullLayout._has('polar'); + var allAxesFixed = areAllAxesFixed(fullLayout); - var traceGroups = subplot.plot - .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace'); + var groups = []; - subplot.plot - .call(_$drawing_436.setTranslate, plotDx, plotDy) - .call(_$drawing_436.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + function addGroup(newGroup) { + if(!newGroup.length) return; - // This is specifically directed at marker points in scatter, box and violin traces, - // applying an inverse scale to individual points to counteract - // the scale of the trace as a whole: - traceGroups.selectAll('.point') - .call(_$drawing_436.setPointGroupScale, xScaleFactor2, yScaleFactor2); - traceGroups.selectAll('.textpoint') - .call(_$drawing_436.setTextPointsScale, xScaleFactor2, yScaleFactor2); - traceGroups - .call(_$drawing_436.hideOutsideRangePoints, subplot); + var out = []; - subplot.plot.selectAll('.barlayer .trace') - .call(_$drawing_436.hideOutsideRangePoints, subplot, '.bartext'); + for(var i = 0; i < newGroup.length; i++) { + var button = newGroup[i]; + if(buttonsToRemove.indexOf(button) !== -1) continue; + out.push(_$buttons_535[button]); } - } - - return dragger; -} -function makeDragger(plotinfo, nodeName, dragClass, cursor) { - var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]); - - dragger3.enter().append(nodeName) - .classed('drag', true) - .classed(dragClass, true) - .style({fill: 'transparent', 'stroke-width': 0}) - .attr('data-subplot', plotinfo.id); - - dragger3.call(_$setCursor_558, cursor); + groups.push(out); + } - return dragger3.node(); -} + // buttons common to all plot types + addGroup(['toImage', 'sendDataToCloud']); -function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) { - var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor); - _$d3_127.select(dragger).call(_$drawing_436.setRect, x, y, w, h); - return dragger; -} + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; -function isDirectionActive(axList, activeVal) { - for(var i = 0; i < axList.length; i++) { - if(!axList[i].fixedrange) return activeVal; + if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) { + // graphs with more than one plot types get 'union buttons' + // which reset the view or toggle hover labels across all subplots. + hoverGroup = ['toggleHover']; + resetGroup = ['resetViews']; } - return ''; -} - -function getEndText(ax, end) { - var initialVal = ax.range[end], - diff = Math.abs(initialVal - ax.range[1 - end]), - dig; - - // TODO: this should basically be ax.r2d but we're doing extra - // rounding here... can we clean up at all? - if(ax.type === 'date') { - return initialVal; + else if(hasGeo) { + zoomGroup = ['zoomInGeo', 'zoomOutGeo']; + hoverGroup = ['hoverClosestGeo']; + resetGroup = ['resetGeo']; } - else if(ax.type === 'log') { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return _$d3_127.format('.' + dig + 'g')(Math.pow(10, initialVal)); + else if(hasGL3D) { + hoverGroup = ['hoverClosest3d']; + resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d']; } - else { // linear numeric (or category... but just show numbers here) - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - - Math.floor(Math.log(diff) / Math.LN10) + 4; - return _$d3_127.format('.' + String(dig) + 'g')(initialVal); + else if(hasMapbox) { + hoverGroup = ['toggleHover']; + resetGroup = ['resetViewMapbox']; + } + else if(hasGL2D) { + hoverGroup = ['hoverClosestGl2d']; + } + else if(hasPie) { + hoverGroup = ['hoverClosestPie']; + } + else { // hasPolar, hasTernary + // always show at least one hover icon. + hoverGroup = ['toggleHover']; + } + // if we have cartesian, allow switching between closest and compare + // regardless of what other types are on the plot, since they'll all + // just treat any truthy hovermode as 'closest' + if(hasCartesian) { + hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; } -} - -function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - var i, - axi, - axRangeLinear0, - axRangeLinearSpan; - for(i = 0; i < axList.length; i++) { - axi = axList[i]; - if(axi.fixedrange) continue; + if((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d']; + if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d']; + } - axRangeLinear0 = axi._rl[0]; - axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - axi.range = [ - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction), - axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction) - ]; - updates[axi._name + '.range[0]'] = axi.range[0]; - updates[axi._name + '.range[1]'] = axi.range[1]; + if(hasGL3D) { + dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']; + } + else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) { + dragModeGroup = ['zoom2d', 'pan2d']; + } + else if(hasMapbox || hasGeo) { + dragModeGroup = ['pan2d']; + } + else if(hasPolar) { + dragModeGroup = ['zoom2d']; + } + if(isSelectable(fullData)) { + dragModeGroup.push('select2d', 'lasso2d'); } - // zoom linked axes about their centers - if(linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(hoverGroup); - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates); - } + return appendButtonsToGroups(groups, buttonsToAdd); } -function dragAxList(axList, pix) { +function areAllAxesFixed(fullLayout) { + var axList = _$axis_ids_650.list({_fullLayout: fullLayout}, null, true); + for(var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if(!axi.fixedrange) { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; + if(!axList[i].fixedrange) { + return false; } } -} - -// common transform for dragging one end of an axis -// d>0 is compressing scale (cursor is over the plot, -// the axis end should move with the cursor) -// d<0 is expanding (cursor is off the plot, axis end moves -// nonlinearly so you can expand far) -function dZoom(d) { - return 1 - ((d >= 0) ? Math.min(d, 0.9) : - 1 / (1 / Math.max(d, -0.3) + 3.222)); -} -function getDragCursor(nsew, dragmode) { - if(!nsew) return 'pointer'; - if(nsew === 'nsew') { - if(dragmode === 'pan') return 'move'; - return 'crosshair'; - } - return nsew.toLowerCase() + '-resize'; + return true; } -function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append('path') - .attr('class', 'zoombox') - .style({ - 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)', - 'stroke-width': 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', path0 + 'Z'); -} +// look for traces that support selection +// to be updated as we add more selectPoints handlers +function isSelectable(fullData) { + var selectable = false; -function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append('path') - .attr('class', 'zoombox-corners') - .style({ - fill: _$color_411.background, - stroke: _$color_411.defaultLine, - 'stroke-width': 1, - opacity: 0 - }) - .attr('transform', 'translate(' + xs + ', ' + ys + ')') - .attr('d', 'M0,0Z'); -} + for(var i = 0; i < fullData.length; i++) { + if(selectable) break; -function clearSelect(zoomlayer) { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomlayer.selectAll('.select-outline').remove(); -} + var trace = fullData[i]; -function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr('d', - path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) + - 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z'); - transitionZoombox(zb, corners, dimmed, lum); -} + if(!trace._module || !trace._module.selectPoints) continue; -function transitionZoombox(zb, corners, dimmed, lum) { - if(!dimmed) { - zb.transition() - .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' : - 'rgba(255,255,255,0.3)') - .duration(200); - corners.transition() - .style('opacity', 1) - .duration(200); + if(_$registry_731.traceIs(trace, 'scatter-like')) { + if(_$subtypes_949.hasMarkers(trace) || _$subtypes_949.hasText(trace)) { + selectable = true; + } + } else if(_$registry_731.traceIs(trace, 'box-violin')) { + if(trace.boxpoints === 'all' || trace.points === 'all') { + selectable = true; + } + } + // assume that in general if the trace module has selectPoints, + // then it's selectable. Scatter is an exception to this because it must + // have markers or text, not just be a scatter type. + else selectable = true; } -} -function removeZoombox(gd) { - _$d3_127.select(gd) - .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') - .remove(); + return selectable; } -function showDoubleClickNotifier(gd) { - if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - _$lib_539.notifier(_$lib_539._(gd, 'Double-click to zoom back out'), 'long'); - SHOWZOOMOUTTIP = false; +function appendButtonsToGroups(groups, buttons) { + if(buttons.length) { + if(Array.isArray(buttons[0])) { + for(var i = 0; i < buttons.length; i++) { + groups.push(buttons[i]); + } + } + else groups.push(buttons); } -} - -function isSelectOrLasso(dragmode) { - return dragmode === 'lasso' || dragmode === 'select'; -} - -function xCorners(box, y0) { - return 'M' + - (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' + - (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) + - 'h3v' + (2 * MINZOOM + 1) + 'h-3Z'; -} - -function yCorners(box, x0) { - return 'M' + - (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) + - 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' + - (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) + - 'v3h' + (2 * MINZOOM + 1) + 'v-3Z'; -} -function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return 'M' + - (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) + - 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) + - 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' + - (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen + - 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' + - (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen + - 'h' + clen + 'v3h-' + (clen + 3) + 'Z'; + return groups; } -function calcLinks(constraintGroups, xIDs, yIDs) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var i, j, k; +// fill in custom buttons referring to default mode bar buttons +function fillCustomButton(customButtons) { + for(var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; - var group, xLinkID, yLinkID; - for(i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - // check if any of the x axes we're dragging is in this constraint group - for(j = 0; j < xIDs.length; j++) { - if(group[xIDs[j]]) { - // put the rest of these axes into xLinks, if we're not already - // dragging them, so we know to scale these axes automatically too - // to match the changes in the dragged x axes - for(xLinkID in group) { - if((xLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(xLinkID) === -1) { - xLinks[xLinkID] = 1; - } - } + for(var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; - // check if the x and y axes of THIS drag are linked - for(k = 0; k < yIDs.length; k++) { - if(group[yIDs[k]]) isSubplotConstrained = true; + if(typeof button === 'string') { + if(_$buttons_535[button] !== undefined) { + customButtons[i][j] = _$buttons_535[button]; } - } - } - - // now check if any of the y axes we're dragging is in this constraint group - // only look for outside links, as we've already checked for links within the dragger - for(j = 0; j < yIDs.length; j++) { - if(group[yIDs[j]]) { - for(yLinkID in group) { - if((yLinkID.charAt(0) === 'x' ? xIDs : yIDs).indexOf(yLinkID) === -1) { - yLinks[yLinkID] = 1; - } + else { + throw new Error([ + '*modeBarButtons* configuration options', + 'invalid button name' + ].join(' ')); } } } } - if(isSubplotConstrained) { - // merge xLinks and yLinks if the subplot is constrained, - // since we'll always apply both anyway and the two will contain - // duplicates - _$lib_539.extendFlat(xLinks, yLinks); - yLinks = {}; - } - return { - x: xLinks, - y: yLinks, - xy: isSubplotConstrained - }; -} - -// still seems to be some confusion about onwheel vs onmousewheel... -function attachWheelEventHandler(element, handler) { - if(!_$hasPassiveEvents_240) { - if(element.onwheel !== undefined) element.onwheel = handler; - else if(element.onmousewheel !== undefined) element.onmousewheel = handler; - } - else { - var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel'; - - if(element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - - element.addEventListener(wheelEventName, handler, {passive: false}); - } + return customButtons; } -var _$dragbox_592 = { - makeDragBox: makeDragBox, +var _$modebar_536 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - makeDragger: makeDragger, - makeRectDragger: makeRectDragger, - makeZoombox: makeZoombox, - makeCorners: makeCorners, - updateZoombox: updateZoombox, - xyCorners: xyCorners, - transitionZoombox: transitionZoombox, - removeZoombox: removeZoombox, - clearSelect: clearSelect, - showDoubleClickNotifier: showDoubleClickNotifier, +'use strict'; - attachWheelEventHandler: attachWheelEventHandler -}; +_$modebar_536.manage = _$manageModeBar_537; +var _$constraints_654 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -75265,152 +76187,202 @@ var _$dragbox_592 = { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +var __id2name_654 = _$axis_ids_650.id2name; +/* removed: var _$scaleZoom_663 = require('./scale_zoom'); */; +var __makePadFn_654 = _$autorange_646.makePadFn; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; +var ALMOST_EQUAL = _$numerical_578.ALMOST_EQUAL; -/* removed: var _$constants_589 = require('./constants'); */; -var __makeDragBox_593 = _$dragbox_592.makeDragBox; +var __FROM_BL_654 = _$alignment_573.FROM_BL; -var _$initInteractions_593 = function initInteractions(gd) { + +_$constraints_654.enforce = function enforceAxisConstraints(gd) { var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; - if(gd._context.staticPlot) { - // this sweeps up more than just cartesian drag elements... - _$d3_127.select(gd).selectAll('.drag').remove(); - return; - } + var i, j, axisID, ax, normScale, mode, factor; + + for(i = 0; i < constraintGroups.length; i++) { + var group = constraintGroups[i]; + var axisIDs = Object.keys(group); - if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d')) return; + 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; - 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'), - 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)); + // 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_654(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; } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; + // Do we have a constraint mismatch? Give a small buffer for rounding errors + if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; + // 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; - var DRAGGERSIZE = _$constants_589.DRAGGERSIZE; + if(mode === 'range') { + _$scaleZoom_663(ax, factor); + } + else { + // mode === 'domain' - // 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_593(gd, plotinfo, xa._offset, ya._offset, - xa._length, ya._length, 'ns', 'ew'); + 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])); - 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) { - _$fx_453.hover(gd, evt, subplot); + 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_663(ax, factor); + continue; } - }; - _$fx_453.hover(gd, evt, subplot); + 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; + } - // 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; - }; + if(ax.autorange && ax._min.length && ax._max.length) { + /* + * 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_654(ax); - /* - * 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; + updateDomain(ax, factor); + ax.setScale(); + var m = Math.abs(ax._m); + var newVal; + var k; - // 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; + for(k = 0; k < ax._min.length; k++) { + newVal = ax._min[k].val - getPad(ax._min[k]) / m; + if(newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } - _$dragelement_433.unhover(gd, evt); - }; + for(k = 0; k < ax._max.length; k++) { + newVal = ax._max[k].val + getPad(ax._max[k]) / m; + if(newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } - // corner draggers - if(gd._context.showAxisDragHandles) { - __makeDragBox_593(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'w'); - __makeDragBox_593(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE, - DRAGGERSIZE, DRAGGERSIZE, 'n', 'e'); - __makeDragBox_593(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'w'); - __makeDragBox_593(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length, - DRAGGERSIZE, DRAGGERSIZE, 's', 'e'); + 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); + } } } - 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_593(gd, plotinfo, xa._offset + xa._length * 0.1, y0, - xa._length * 0.8, DRAGGERSIZE, '', 'ew'); - __makeDragBox_593(gd, plotinfo, xa._offset, y0, - xa._length * 0.1, DRAGGERSIZE, '', 'w'); - __makeDragBox_593(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_593(gd, plotinfo, x0, ya._offset + ya._length * 0.1, - DRAGGERSIZE, ya._length * 0.8, 'ns', ''); - __makeDragBox_593(gd, plotinfo, x0, ya._offset + ya._length * 0.9, - DRAGGERSIZE, ya._length * 0.1, 's', ''); - __makeDragBox_593(gd, plotinfo, x0, ya._offset, - DRAGGERSIZE, ya._length * 0.1, 'n', ''); + } +}; + +// For use before autoranging, check if this axis was previously constrained +// by domain but no longer is +_$constraints_654.clean = function cleanConstraints(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; } } - }); - - // 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 = fullLayout._lasthover; - _$fx_453.hover(gd, evt, fullLayout._hoversubplot); - }; + if(!isConstrained || ax.constrain !== 'domain') { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; - hoverLayer.onclick = function(evt) { - evt.target = fullLayout._lasthover; - _$fx_453.click(gd, evt); - }; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = __FROM_BL_654[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - // also delegate mousedowns... TODO: does this actually work? - hoverLayer.onmousedown = function(evt) { - fullLayout._lasthover.onmousedown(evt); - }; -}; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; +} -var _$subroutines_576 = {}; +var _$subroutines_639 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -75421,22 +76393,28 @@ var _$subroutines_576 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; -/* removed: var _$color_411 = require('../components/color'); */; -/* removed: var _$drawing_436 = require('../components/drawing'); */; -/* removed: var _$titles_504 = require('../components/titles'); */; -/* removed: var _$modebar_474 = require('../components/modebar'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -/* removed: var _$initInteractions_593 = require('../plots/cartesian/graph_interact'); */; -/* removed: var _$constants_589 = require('../plots/cartesian/constants'); */; -/* removed: var _$alignment_511 = require('../constants/alignment'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$clearGlCanvases_585 = require('../lib/clear_gl_canvases'); */; -_$subroutines_576.layoutStyles = function(gd) { - return _$lib_539.syncOrAsync([_$plots_647.doAutoMargin, _$subroutines_576.lsInner], gd); +/* removed: var _$color_473 = require('../components/color'); */; +/* removed: var _$drawing_498 = require('../components/drawing'); */; +/* removed: var _$titles_566 = require('../components/titles'); */; +/* removed: var _$modebar_536 = require('../components/modebar'); */; + +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +/* removed: var _$constants_652 = require('../plots/cartesian/constants'); */; +/* removed: var _$alignment_573 = require('../constants/alignment'); */; +/* removed: var _$constraints_654 = require('../plots/cartesian/constraints'); */; +var enforceAxisConstraints = _$constraints_654.enforce; +var cleanAxisConstraints = _$constraints_654.clean; +var __doAutoRange_639 = _$autorange_646.doAutoRange; + +_$subroutines_639.layoutStyles = function(gd) { + return _$lib_601.syncOrAsync([_$plots_709.doAutoMargin, _$subroutines_639.lsInner], gd); }; function overlappingDomain(xDomain, yDomain, domains) { @@ -75454,11 +76432,11 @@ function overlappingDomain(xDomain, yDomain, domains) { return false; } -_$subroutines_576.lsInner = function(gd) { +_$subroutines_639.lsInner = function(gd) { var fullLayout = gd._fullLayout; var gs = fullLayout._size; var pad = gs.p; - var axList = _$axes_584.list(gd); + var axList = _$axes_647.list(gd); // _has('cartesian') means SVG specifically, not GL2D - but GL2D // can still get here because it makes some of the SVG structure @@ -75493,7 +76471,7 @@ _$subroutines_576.lsInner = function(gd) { ax._linepositions = {}; // stash crispRounded linewidth so we don't need to pass gd all over the place - ax._lw = _$drawing_436.crispRound(gd, ax.linewidth, 1); + ax._lw = _$drawing_498.crispRound(gd, ax.linewidth, 1); // figure out the main axis line and main mirror line position. // it's easier to follow the logic if we handle these separately from @@ -75502,7 +76480,7 @@ _$subroutines_576.lsInner = function(gd) { ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side); ax._mainMirrorPosition = (ax.mirror && counterAx) ? getLinePosition(ax, counterAx, - _$alignment_511.OPPOSITE_SIDE[ax.side]) : null; + _$alignment_573.OPPOSITE_SIDE[ax.side]) : null; } fullLayout._paperdiv @@ -75511,7 +76489,7 @@ _$subroutines_576.lsInner = function(gd) { height: fullLayout.height + 'px' }) .selectAll('.main-svg') - .call(_$drawing_436.setSize, fullLayout.width, fullLayout.height); + .call(_$drawing_498.setSize, fullLayout.width, fullLayout.height); gd._context.setBackground(gd, fullLayout.paper_bgcolor); @@ -75537,31 +76515,17 @@ _$subroutines_576.lsInner = function(gd) { var xDomain = plotinfo.xaxis.domain; var yDomain = plotinfo.yaxis.domain; - var plotgroupBgData = []; + var plotgroup = plotinfo.plotgroup; if(overlappingDomain(xDomain, yDomain, lowerDomains)) { - plotgroupBgData = [0]; - } - else { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = _$lib_601.ensureSingle(plotgroup, 'rect', 'bg'); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + } else { + plotgroup.select('rect.bg').remove(); lowerBackgroundIDs.push(subplot); lowerDomains.push([xDomain, yDomain]); } - - // create the plot group backgrounds now, since - // they're all independent selections - var plotgroupBg = plotinfo.plotgroup.selectAll('.bg') - .data(plotgroupBgData); - - plotgroupBg.enter().append('rect') - .classed('bg', true); - - plotgroupBg.exit().remove(); - - plotgroupBg.each(function() { - plotinfo.bg = plotgroupBg; - var pgNode = plotinfo.plotgroup.node(); - pgNode.insertBefore(this, pgNode.childNodes[0]); - }); }); // now create all the lower-layer backgrounds at once now that @@ -75575,7 +76539,7 @@ _$subroutines_576.lsInner = function(gd) { lowerBackgrounds.exit().remove(); lowerBackgrounds.each(function(subplot) { - fullLayout._plots[subplot].bg = _$d3_127.select(this); + fullLayout._plots[subplot].bg = _$d3_130.select(this); }); subplotSelection.each(function(subplot) { @@ -75585,51 +76549,45 @@ _$subroutines_576.lsInner = function(gd) { if(plotinfo.bg && hasSVGCartesian) { plotinfo.bg - .call(_$drawing_436.setRect, + .call(_$drawing_498.setRect, xa._offset - pad, ya._offset - pad, xa._length + 2 * pad, ya._length + 2 * pad) - .call(_$color_411.fill, fullLayout.plot_bgcolor) + .call(_$color_473.fill, fullLayout.plot_bgcolor) .style('stroke-width', 0); } // Clip so that data only shows up on the plot area. - plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; + var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot'; - var plotClip = fullLayout._clips.selectAll('#' + plotinfo.clipId) - .data([0]); - - plotClip.enter().append('clipPath') - .attr({ - 'class': 'plotclip', - 'id': plotinfo.clipId - }) - .append('rect'); + var plotClip = _$lib_601.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.classed('plotclip', true) + .append('rect'); + }); - plotClip.selectAll('rect') - .attr({ - 'width': xa._length, - 'height': ya._length - }); + plotinfo.clipRect = plotClip.select('rect').attr({ + width: xa._length, + height: ya._length + }); - _$drawing_436.setTranslate(plotinfo.plot, xa._offset, ya._offset); + _$drawing_498.setTranslate(plotinfo.plot, xa._offset, ya._offset); var plotClipId; var layerClipId; if(plotinfo._hasClipOnAxisFalse) { plotClipId = null; - layerClipId = plotinfo.clipId; + layerClipId = clipId; } else { - plotClipId = plotinfo.clipId; + plotClipId = clipId; layerClipId = null; } - _$drawing_436.setClipUrl(plotinfo.plot, plotClipId); + _$drawing_498.setClipUrl(plotinfo.plot, plotClipId); - for(i = 0; i < _$constants_589.traceLayerClasses.length; i++) { - var layer = _$constants_589.traceLayerClasses[i]; + for(i = 0; i < _$constants_652.traceLayerClasses.length; i++) { + var layer = _$constants_652.traceLayerClasses[i]; if(layer !== 'scatterlayer' && layer !== 'barlayer') { - plotinfo.plot.selectAll('g.' + layer).call(_$drawing_436.setClipUrl, layerClipId); + plotinfo.plot.selectAll('g.' + layer).call(_$drawing_498.setClipUrl, layerClipId); } } @@ -75708,7 +76666,7 @@ _$subroutines_576.lsInner = function(gd) { plotinfo.xlines .style('stroke-width', xa._lw + 'px') - .call(_$color_411.stroke, xa.showline ? + .call(_$color_473.stroke, xa.showline ? xa.linecolor : 'rgba(0,0,0,0)'); } plotinfo.xlines.attr('d', xPath); @@ -75745,15 +76703,15 @@ _$subroutines_576.lsInner = function(gd) { plotinfo.ylines .style('stroke-width', ya._lw + 'px') - .call(_$color_411.stroke, ya.showline ? + .call(_$color_473.stroke, ya.showline ? ya.linecolor : 'rgba(0,0,0,0)'); } plotinfo.ylines.attr('d', yPath); }); - _$axes_584.makeClipPaths(gd); - _$subroutines_576.drawMainTitle(gd); - _$modebar_474.manage(gd); + _$axes_647.makeClipPaths(gd); + _$subroutines_639.drawMainTitle(gd); + _$modebar_536.manage(gd); return gd._promises.length && Promise.all(gd._promises); }; @@ -75783,7 +76741,7 @@ function shouldShowLineThisSide(ax, side, counterAx) { // in order to handle cases where the user forgot to anchor this axis correctly // (because its default anchor has the same domain on the relevant end) // check whether the relevant position is the same. - var sideIndex = _$alignment_511.FROM_BL[side]; + var sideIndex = _$alignment_573.FROM_BL[side]; if(counterAx.side === side) { return anchorAx.domain[sideIndex] === ax.domain[sideIndex]; } @@ -75809,10 +76767,10 @@ function findCounterAxisLineWidth(ax, side, counterAx, axList) { return 0; } -_$subroutines_576.drawMainTitle = function(gd) { +_$subroutines_639.drawMainTitle = function(gd) { var fullLayout = gd._fullLayout; - _$titles_504.draw(gd, 'gtitle', { + _$titles_566.draw(gd, 'gtitle', { propContainer: fullLayout, propName: 'title', placeholder: fullLayout._dfltTitle.plot, @@ -75828,7 +76786,7 @@ _$subroutines_576.drawMainTitle = function(gd) { // call it regardless of what change we made, in case // supplyDefaults brought in an array that was already // in gd.data but not in gd._fullData previously -_$subroutines_576.doTraceStyle = function(gd) { +_$subroutines_639.doTraceStyle = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi = gd.calcdata[i], _module = ((cdi[0] || {}).trace || {})._module || {}, @@ -75837,13 +76795,13 @@ _$subroutines_576.doTraceStyle = function(gd) { if(arraysToCalcdata) arraysToCalcdata(cdi, cdi[0].trace); } - _$plots_647.style(gd); - _$registry_668.getComponentMethod('legend', 'draw')(gd); + _$plots_709.style(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doColorBars = function(gd) { +_$subroutines_639.doColorBars = function(gd) { for(var i = 0; i < gd.calcdata.length; i++) { var cdi0 = gd.calcdata[i][0]; @@ -75851,7 +76809,7 @@ _$subroutines_576.doColorBars = function(gd) { var trace = cdi0.trace, cb = cdi0.t.cb; - if(_$registry_668.traceIs(trace, 'contour')) { + if(_$registry_731.traceIs(trace, 'contour')) { cb.line({ width: trace.contours.showlines !== false ? trace.line.width : 0, @@ -75860,49 +76818,54 @@ _$subroutines_576.doColorBars = function(gd) { cb._opts.line.color : trace.line.color }); } - if(_$registry_668.traceIs(trace, 'markerColorscale')) { + if(_$registry_731.traceIs(trace, 'markerColorscale')) { cb.options(trace.marker.colorbar)(); } else cb.options(trace.colorbar)(); } } - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); }; // force plot() to redo the layout and replot with the modified layout -_$subroutines_576.layoutReplot = function(gd) { +_$subroutines_639.layoutReplot = function(gd) { var layout = gd.layout; gd.layout = undefined; - return _$registry_668.call('plot', gd, '', layout); + return _$registry_731.call('plot', gd, '', layout); }; -_$subroutines_576.doLegend = function(gd) { - _$registry_668.getComponentMethod('legend', 'draw')(gd); - return _$plots_647.previousPromises(gd); +_$subroutines_639.doLegend = function(gd) { + _$registry_731.getComponentMethod('legend', 'draw')(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doTicksRelayout = function(gd) { - _$axes_584.doTicks(gd, 'redraw'); - _$subroutines_576.drawMainTitle(gd); - return _$plots_647.previousPromises(gd); +_$subroutines_639.doTicksRelayout = function(gd) { + _$axes_647.doTicks(gd, 'redraw'); + + if(gd._fullLayout._hasOnlyLargeSploms) { + _$clearGlCanvases_585(gd); + _$registry_731.subplotsRegistry.splom.plot(gd); + } + + _$subroutines_639.drawMainTitle(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doModeBar = function(gd) { +_$subroutines_639.doModeBar = function(gd) { var fullLayout = gd._fullLayout; - _$modebar_474.manage(gd); - _$initInteractions_593(gd); + _$modebar_536.manage(gd); for(var i = 0; i < fullLayout._basePlotModules.length; i++) { var updateFx = fullLayout._basePlotModules[i].updateFx; if(updateFx) updateFx(fullLayout); } - return _$plots_647.previousPromises(gd); + return _$plots_709.previousPromises(gd); }; -_$subroutines_576.doCamera = function(gd) { +_$subroutines_639.doCamera = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots.gl3d; @@ -75914,214 +76877,88 @@ _$subroutines_576.doCamera = function(gd) { } }; -var _$constraints_591 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - - -'use strict'; - -var __id2name_591 = _$axis_ids_587.id2name; -/* removed: var _$scaleZoom_601 = require('./scale_zoom'); */; -var __makePadFn_591 = _$autorange_583.makePadFn; - -var ALMOST_EQUAL = _$numerical_517.ALMOST_EQUAL; - -var __FROM_BL_591 = _$alignment_511.FROM_BL; - - -_$constraints_591.enforce = function enforceAxisConstraints(gd) { +_$subroutines_639.drawData = function(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_591(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(); + var calcdata = gd.calcdata; + var rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); + var i; - // 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); - } + // in case of traces that were heatmaps or contour maps + // previously, remove them and their colorbars explicitly + for(i = 0; i < calcdata.length; i++) { + var trace = calcdata[i][0].trace; + var isVisible = (trace.visible === true); + var uid = trace.uid; + + if(!isVisible || !_$registry_731.traceIs(trace, '2dMap')) { + var query = ( + '.hm' + uid + + ',.contour' + uid + + ',#clip' + uid + ); - // this has served its purpose, so remove it - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); + fullLayout._paper + .selectAll(query) + .remove(); - if(ax.constrain === 'domain') hasAnyDomainConstraint = true; + rangesliderContainers + .selectAll(query) + .remove(); } - // 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_601(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_601(ax, factor); - continue; - } + if(!isVisible || !trace._module.colorbar) { + fullLayout._infolayer.selectAll('.cb' + uid).remove(); + } + } - 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; - } + _$clearGlCanvases_585(gd); - if(ax.autorange && ax._min.length && ax._max.length) { - /* - * 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_591(ax); + // loop over the base plot modules present on graph + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } - updateDomain(ax, factor); - ax.setScale(); - var m = Math.abs(ax._m); - var newVal; - var k; + // styling separate from drawing + _$plots_709.style(gd); - for(k = 0; k < ax._min.length; k++) { - newVal = ax._min[k].val - getPad(ax._min[k]) / m; - if(newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } + // show annotations and shapes + _$registry_731.getComponentMethod('shapes', 'draw')(gd); + _$registry_731.getComponentMethod('annotations', 'draw')(gd); - for(k = 0; k < ax._max.length; k++) { - newVal = ax._max[k].val + getPad(ax._max[k]) / m; - if(newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } + // Mark the first render as complete + fullLayout._replotting = false; - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; + return _$plots_709.previousPromises(gd); +}; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = (rl0 < rl1) ? - [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } +_$subroutines_639.doAutoRangeAndConstraints = function(gd) { + var axList = _$axes_647.list(gd, '', true); - updateDomain(ax, factor); - } - } - } + for(var i = 0; i < axList.length; i++) { + var ax = axList[i]; + cleanAxisConstraints(gd, ax); + __doAutoRange_639(ax); } -}; -// For use before autoranging, check if this axis was previously constrained -// by domain but no longer is -_$constraints_591.clean = function cleanConstraints(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; - } - } + enforceAxisConstraints(gd); }; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = __FROM_BL_591[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 - ]; -} +// An initial paint must be completed before these components can be +// correctly sized and the whole plot re-margined. fullLayout._replotting must +// be set to false before these will work properly. +_$subroutines_639.finalDraw = function(gd) { + _$registry_731.getComponentMethod('shapes', 'draw')(gd); + _$registry_731.getComponentMethod('images', 'draw')(gd); + _$registry_731.getComponentMethod('annotations', 'draw')(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); + _$registry_731.getComponentMethod('rangeslider', 'draw')(gd); + _$registry_731.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_731.getComponentMethod('sliders', 'draw')(gd); + _$registry_731.getComponentMethod('updatemenus', 'draw')(gd); +}; -var _$micropolar_656 = {}; +var _$micropolar_718 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -76130,25 +76967,25 @@ var _$micropolar_656 = {}; * LICENSE file in the root directory of this source tree. */ -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../../lib'); */; -var __extendDeepAll_656 = _$lib_539.extendDeepAll; -var __MID_SHIFT_656 = _$alignment_511.MID_SHIFT; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +var __extendDeepAll_718 = _$lib_601.extendDeepAll; +var __MID_SHIFT_718 = _$alignment_573.MID_SHIFT; -var µ = _$micropolar_656 = { version: '0.2.2' }; +var µ = _$micropolar_718 = { version: '0.2.2' }; µ.Axis = function module() { var config = { data: [], layout: {} }, inputConfig = {}, liveConfig = {}; - var svg, container, dispatch = _$d3_127.dispatch('hover'), radialScale, angularScale; + var svg, container, dispatch = _$d3_130.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_127.select(container); + if (typeof container == 'string' || container.nodeName) container = _$d3_130.select(container); container.datum(data).each(function(_data, _index) { var dataOriginal = _data.slice(); liveConfig = { @@ -76162,7 +76999,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length; } if (!d.strokeColor) { - d.strokeColor = d.geometry === 'LinePlot' ? d.color : _$d3_127.rgb(d.color).darker().toString(); + d.strokeColor = d.geometry === 'LinePlot' ? d.color : _$d3_130.rgb(d.color).darker().toString(); } liveConfig.data[i].color = d.color; liveConfig.data[i].strokeColor = d.strokeColor; @@ -76179,7 +77016,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return d; }); if (isStacked) { - var grouped = _$d3_127.nest().key(function(d, i) { + var grouped = _$d3_130.nest().key(function(d, i) { return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked'; }).entries(dataWithGroupId); var dataYStack = []; @@ -76196,7 +77033,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return d.values; } }); - data = _$d3_127.merge(stacked); + data = _$d3_130.merge(stacked); } data.forEach(function(d, i) { d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ]; @@ -76207,13 +77044,13 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ]; var extent; if (isStacked) { - var highestStackedValue = _$d3_127.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); + var highestStackedValue = _$d3_130.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack))); extent = [ 0, highestStackedValue ]; - } else extent = _$d3_127.extent(µ.util.flattenArray(data.map(function(d, i) { + } else extent = _$d3_130.extent(µ.util.flattenArray(data.map(function(d, i) { return d.r; }))); if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0; - radialScale = _$d3_127.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]); + radialScale = _$d3_130.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; @@ -76223,7 +77060,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; if (isOrdinal) { angularDataMerged = µ.util.deduplicate(angularDataMerged); ticks = angularDataMerged.slice(); - angularDataMerged = _$d3_127.range(angularDataMerged.length); + angularDataMerged = _$d3_130.range(angularDataMerged.length); data = data.map(function(d, i) { var result = d; d.t = [ angularDataMerged ]; @@ -76236,7 +77073,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }).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_127.extent(angularDataMerged); + var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : _$d3_130.extent(angularDataMerged); var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]); if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0; var angularDomainWithPadding = angularDomain.slice(); @@ -76249,19 +77086,19 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; 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_127.range.apply(this, angularDomainWithPadding); + var angularAxisRange = _$d3_130.range.apply(this, angularDomainWithPadding); angularAxisRange = angularAxisRange.map(function(d, i) { return parseFloat(d.toPrecision(12)); }); - angularScale = _$d3_127.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]); + angularScale = _$d3_130.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_127.select(this).select('svg.chart-root'); + svg = _$d3_130.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_127.select(newSvg); + svg = _$d3_130.select(newSvg); } svg.select('.guides-group').style({ 'pointer-events': 'none' @@ -76304,7 +77141,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; data: data.map(function(d, i) { return d.name || 'Element' + i; }), - legendConfig: __extendDeepAll_656({}, + legendConfig: __extendDeepAll_718({}, µ.Legend.defaultConfig().legendConfig, { container: legendContainer, @@ -76369,7 +77206,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return angularScale(d) % 360 + axisConfig.orientation; } if (axisConfig.radialAxis.visible) { - var axis = _$d3_127.svg.axis().scale(radialScale).ticks(5).tickSize(5); + var axis = _$d3_130.svg.axis().scale(radialScale).ticks(5).tickSize(5); radialAxis.call(axis).attr({ transform: 'rotate(' + axisConfig.radialAxis.orientation + ')' }); @@ -76420,7 +77257,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle); var ticksText = angularAxis.select('text.axis-text').attr({ x: radius + axisConfig.labelOffset, - dy: __MID_SHIFT_656 + 'em', + dy: __MID_SHIFT_718 + 'em', transform: function(d, i) { var angle = currentAngle(d, i); var rad = radius + axisConfig.labelOffset; @@ -76440,7 +77277,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; if (i % (axisConfig.minorTicks + 1) != 0) return ''; return axisConfig.angularAxis.rewriteTicks(this.textContent, i); }); - var rightmostTickEndX = _$d3_127.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { + var rightmostTickEndX = _$d3_130.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) { return d.getCTM().e + d.getBBox().width; })); legendContainer.attr({ @@ -76472,7 +77309,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; geometryConfig: geometryConfig }); }); - var geometryConfigsGrouped = _$d3_127.nest().key(function(d, i) { + var geometryConfigsGrouped = _$d3_130.nest().key(function(d, i) { return typeof d.data.groupId != 'undefined' || 'unstacked'; }).entries(geometryConfigs); var geometryConfigsGrouped2 = []; @@ -76485,7 +77322,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; 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_656(µ[geometry].defaultConfig(), dB); + return __extendDeepAll_718(µ[geometry].defaultConfig(), dB); }); µ[geometry]().config(finalGeometryConfig)(); }); @@ -76555,7 +77392,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; radialTooltip.hide(); }); svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var color = this.style.fill; var newColor = 'black'; var opacity = this.style.opacity || 1; @@ -76566,7 +77403,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; el.attr({ 'data-fill': color }); - newColor = _$d3_127.hsl(color).darker().toString(); + newColor = _$d3_130.hsl(color).darker().toString(); el.style({ fill: newColor, opacity: 1 @@ -76589,18 +77426,18 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; el.attr({ 'data-stroke': color }); - newColor = _$d3_127.hsl(color).darker().toString(); + newColor = _$d3_130.hsl(color).darker().toString(); el.style({ stroke: newColor, opacity: 1 }); } }).on('mousemove.tooltip', function(d, i) { - if (_$d3_127.event.which != 0) return false; - if (_$d3_127.select(this).attr('data-fill')) geometryTooltip.show(); + if (_$d3_130.event.which != 0) return false; + if (_$d3_130.select(this).attr('data-fill')) geometryTooltip.show(); }).on('mouseout.tooltip', function(d, i) { geometryTooltip.hide(); - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var fillColor = el.attr('data-fill'); if (fillColor) el.style({ fill: fillColor, @@ -76622,11 +77459,11 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var xClone = µ.util.cloneJson(_x); xClone.data.forEach(function(d, i) { if (!config.data[i]) config.data[i] = {}; - __extendDeepAll_656(config.data[i], µ.Axis.defaultConfig().data[0]); - __extendDeepAll_656(config.data[i], d); + __extendDeepAll_718(config.data[i], µ.Axis.defaultConfig().data[0]); + __extendDeepAll_718(config.data[i], d); }); - __extendDeepAll_656(config.layout, µ.Axis.defaultConfig().layout); - __extendDeepAll_656(config.layout, xClone.layout); + __extendDeepAll_718(config.layout, µ.Axis.defaultConfig().layout); + __extendDeepAll_718(config.layout, xClone.layout); return this; }; exports.getLiveConfig = function() { @@ -76644,7 +77481,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; exports.svg = function() { return svg; }; - _$d3_127.rebind(exports, dispatch, 'on'); + _$d3_130.rebind(exports, dispatch, 'on'); return exports; }; @@ -76663,7 +77500,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; opacity: 1 } ], layout: { - defaultColorRange: _$d3_127.scale.category10().range(), + defaultColorRange: _$d3_130.scale.category10().range(), title: null, height: 450, width: 500, @@ -76744,7 +77581,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.util.dataFromEquation2 = function(_equation, _step) { var step = _step || 6; - var data = _$d3_127.range(0, 360 + step, step).map(function(deg, index) { + var data = _$d3_130.range(0, 360 + step, step).map(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); return [ deg, radius ]; @@ -76755,7 +77592,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.util.dataFromEquation = function(_equation, _step, _name) { var step = _step || 6; var t = [], r = []; - _$d3_127.range(0, 360 + step, step).forEach(function(deg, index) { + _$d3_130.range(0, 360 + step, step).forEach(function(deg, index) { var theta = deg * Math.PI / 180; var radius = _equation(theta); t.push(deg); @@ -76772,7 +77609,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.util.ensureArray = function(_val, _count) { if (typeof _val === 'undefined') return null; var arr = [].concat(_val); - return _$d3_127.range(_count).map(function(d, i) { + return _$d3_130.range(_count).map(function(d, i) { return arr[i] || arr[0]; }); }; @@ -76795,8 +77632,8 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; µ.util.sumArrays = function(a, b) { - return _$d3_127.zip(a, b).map(function(d, i) { - return _$d3_127.sum(d); + return _$d3_130.zip(a, b).map(function(d, i) { + return _$d3_130.sum(d); }); }; @@ -76839,7 +77676,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; µ.util.getMousePos = function(_referenceElement) { - var mousePos = _$d3_127.mouse(_referenceElement.node()); + var mousePos = _$d3_130.mouse(_referenceElement.node()); var mouseX = mousePos[0]; var mouseY = mousePos[1]; var mouse = {}; @@ -76894,7 +77731,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.PolyChart = function module() { var config = [ µ.PolyChart.defaultConfig() ]; - var dispatch = _$d3_127.dispatch('hover'); + var dispatch = _$d3_130.dispatch('hover'); var dashArray = { solid: 'none', dash: [ 5, 2 ], @@ -76904,11 +77741,11 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; function exports() { var geometryConfig = config[0].geometryConfig; var container = geometryConfig.container; - if (typeof container == 'string') container = _$d3_127.select(container); + if (typeof container == 'string') container = _$d3_130.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_127.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return _$d3_127.zip(d.data.t[0], d.data.r[0]); + if (isStack) return _$d3_130.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return _$d3_130.zip(d.data.t[0], d.data.r[0]); }); var angularScale = geometryConfig.angularScale; var domainMin = geometryConfig.radialScale.domain()[0]; @@ -76918,7 +77755,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0); var stackTop = geometryConfig.radialScale(d[2] || 0); var w = dataConfig.barWidth; - _$d3_127.select(this).attr({ + _$d3_130.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) { @@ -76928,8 +77765,8 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; generator.dot = function(d, i, pI) { var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d; - var symbol = _$d3_127.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); - _$d3_127.select(this).attr({ + var symbol = _$d3_130.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i); + _$d3_130.select(this).attr({ 'class': 'mark dot', d: symbol, transform: function(d, i) { @@ -76938,7 +77775,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; } }); }; - var line = _$d3_127.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) { + var line = _$d3_130.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; @@ -76947,7 +77784,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var lineData = d[2] ? data[pI].map(function(d, i) { return [ d[0], d[1] + d[2] ]; }) : data[pI]; - _$d3_127.select(this).each(generator['dot']).style({ + _$d3_130.select(this).each(generator['dot']).style({ opacity: function(dB, iB) { return +_config[pI].data.dotVisible; }, @@ -76956,7 +77793,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; 'class': 'mark dot' }); if (i > 0) return; - var lineSelection = _$d3_127.select(this.parentNode).selectAll('path.line').data([ 0 ]); + var lineSelection = _$d3_130.select(this.parentNode).selectAll('path.line').data([ 0 ]); lineSelection.enter().insert('path'); lineSelection.attr({ 'class': 'line', @@ -76989,7 +77826,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }; var angularRange = geometryConfig.angularScale.range(); var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180; - var arc = _$d3_127.svg.arc().startAngle(function(d) { + var arc = _$d3_130.svg.arc().startAngle(function(d) { return -triangleAngle / 2; }).endAngle(function(d) { return triangleAngle / 2; @@ -76999,7 +77836,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]); }); generator.arc = function(d, i, pI) { - _$d3_127.select(this).attr({ + _$d3_130.select(this).attr({ 'class': 'mark arc', d: arc, transform: function(d, i) { @@ -77027,7 +77864,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none'; } }; - var geometryLayer = _$d3_127.select(this).selectAll('g.layer').data(data); + var geometryLayer = _$d3_130.select(this).selectAll('g.layer').data(data); geometryLayer.enter().append('g').attr({ 'class': 'layer' }); @@ -77062,15 +77899,15 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; if (!arguments.length) return config; _x.forEach(function(d, i) { if (!config[i]) config[i] = {}; - __extendDeepAll_656(config[i], µ.PolyChart.defaultConfig()); - __extendDeepAll_656(config[i], d); + __extendDeepAll_718(config[i], µ.PolyChart.defaultConfig()); + __extendDeepAll_718(config[i], d); }); return this; }; exports.getColorScale = function() { return colorScale; }; - _$d3_127.rebind(exports, dispatch, 'on'); + _$d3_130.rebind(exports, dispatch, 'on'); return exports; }; @@ -77101,7 +77938,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; container: 'body', radialScale: null, angularScale: null, - colorScale: _$d3_127.scale.category20() + colorScale: _$d3_130.scale.category20() } }; return config; @@ -77162,24 +77999,24 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; µ.Legend = function module() { var config = µ.Legend.defaultConfig(); - var dispatch = _$d3_127.dispatch('hover'); + var dispatch = _$d3_130.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_656({}, legendConfig.elements[i]); + var element = __extendDeepAll_718({}, legendConfig.elements[i]); element.name = dB; element.color = [].concat(legendConfig.elements[i].color)[iB]; return element; }); }); - var data = _$d3_127.merge(flattenData); + var data = _$d3_130.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_127.select(container); + if (typeof container == 'string' || container.nodeName) container = _$d3_130.select(container); var colors = data.map(function(d, i) { return d.color; }); @@ -77197,14 +78034,14 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }); svgEnter.append('g').classed('legend-axis', true); svgEnter.append('g').classed('legend-marks', true); - var dataNumbered = _$d3_127.range(data.length); - var colorScale = _$d3_127.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); - var dataScale = _$d3_127.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]); + var dataNumbered = _$d3_130.range(data.length); + var colorScale = _$d3_130.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors); + var dataScale = _$d3_130.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_127.svg.symbolTypes.indexOf(_type) != -1) return _$d3_127.svg.symbol().type(_type).size(squareSize)(); else return _$d3_127.svg.symbol().type('square').size(squareSize)(); + } else if (_$d3_130.svg.symbolTypes.indexOf(_type) != -1) return _$d3_130.svg.symbol().type(_type).size(squareSize)(); else return _$d3_130.svg.symbol().type('square').size(squareSize)(); }; if (isContinuous) { var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({ @@ -77246,7 +78083,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; }); legendElement.exit().remove(); } - var legendAxis = _$d3_127.svg.axis().scale(dataScale).orient('right'); + var legendAxis = _$d3_130.svg.axis().scale(dataScale).orient('right'); var axis = svg.select('g.legend-axis').attr({ transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')' }).call(legendAxis); @@ -77268,10 +78105,10 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; } exports.config = function(_x) { if (!arguments.length) return config; - __extendDeepAll_656(config, _x); + __extendDeepAll_718(config, _x); return this; }; - _$d3_127.rebind(exports, dispatch, 'on'); + _$d3_130.rebind(exports, dispatch, 'on'); return exports; }; @@ -77331,7 +78168,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return exports; }; exports.text = function(_text) { - var l = _$d3_127.hsl(config.color).l; + var l = _$d3_130.hsl(config.color).l; var strokeColor = l >= .5 ? '#aaa' : 'white'; var fillColor = l >= .5 ? 'black' : 'white'; var text = _text || ''; @@ -77383,7 +78220,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; return exports; }; exports.config = function(_x) { - __extendDeepAll_656(config, _x); + __extendDeepAll_718(config, _x); return exports; }; return exports; @@ -77399,7 +78236,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var outputConfig = {}; if (_inputConfig.data) { outputConfig.data = _inputConfig.data.map(function(d, i) { - var r = __extendDeepAll_656({}, d); + var r = __extendDeepAll_718({}, d); var toTranslate = [ [ r, [ 'marker', 'color' ], [ 'color' ] ], [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ], @@ -77453,7 +78290,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; } } if (_inputConfig.layout) { - var r = __extendDeepAll_656({}, _inputConfig.layout); + var r = __extendDeepAll_718({}, _inputConfig.layout); var toTranslate = [ [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ], [ r, [ 'showlegend' ], [ 'showLegend' ] ], @@ -77514,7 +78351,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; var source = [ 't', 'r', 'b', 'l', 'pad' ]; var target = [ 'top', 'right', 'bottom', 'left', 'pad' ]; var margin = {}; - _$d3_127.entries(r.margin).forEach(function(dB, iB) { + _$d3_130.entries(r.margin).forEach(function(dB, iB) { margin[target[source.indexOf(dB.key)]] = dB.value; }); r.margin = margin; @@ -77553,7 +78390,7 @@ var µ = _$micropolar_656 = { version: '0.2.2' }; // Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager // Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com -var _$UndoManager_658 = function UndoManager() { +var _$UndoManager_720 = function UndoManager() { var undoCommands = [], index = -1, isExecuting = false, @@ -77606,7 +78443,7 @@ var _$UndoManager_658 = function UndoManager() { }; }; -var _$micropolar_manager_657 = {}; +var _$micropolar_manager_719 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -77619,30 +78456,30 @@ var _$micropolar_manager_657 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$color_411 = require('../../../components/color'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$color_473 = require('../../../components/color'); */; -/* removed: var _$micropolar_656 = require('./micropolar'); */; -/* removed: var _$UndoManager_658 = require('./undo_manager'); */; -var __extendDeepAll_657 = _$lib_539.extendDeepAll; +/* removed: var _$micropolar_718 = require('./micropolar'); */; +/* removed: var _$UndoManager_720 = require('./undo_manager'); */; +var __extendDeepAll_719 = _$lib_601.extendDeepAll; -var manager = _$micropolar_manager_657 = {}; +var manager = _$micropolar_manager_719 = {}; manager.framework = function(_gd) { var config, previousConfigClone, plot, convertedInput, container; - var undoManager = new _$UndoManager_658(); + var undoManager = new _$UndoManager_720(); function exports(_inputConfig, _container) { if(_container) container = _container; - _$d3_127.select(_$d3_127.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); + _$d3_130.select(_$d3_130.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove(); config = (!config) ? _inputConfig : - __extendDeepAll_657(config, _inputConfig); + __extendDeepAll_719(config, _inputConfig); - if(!plot) plot = _$micropolar_656.Axis(); - convertedInput = _$micropolar_656.adapter.plotly().convert(config); + if(!plot) plot = _$micropolar_718.Axis(); + convertedInput = _$micropolar_718.adapter.plotly().convert(config); plot.config(convertedInput).render(container); _gd.data = config.data; _gd.layout = config.layout; @@ -77653,12 +78490,12 @@ manager.framework = function(_gd) { exports.svg = function() { return plot.svg(); }; exports.getConfig = function() { return config; }; exports.getLiveConfig = function() { - return _$micropolar_656.adapter.plotly().convert(plot.getLiveConfig(), true); + return _$micropolar_718.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_656.util.cloneJson(config); + var configClone = _$micropolar_718.util.cloneJson(config); (function(_configClone, _previousConfigClone) { undoManager.add({ undo: function() { @@ -77669,7 +78506,7 @@ manager.framework = function(_gd) { } }); })(configClone, previousConfigClone); - previousConfigClone = _$micropolar_656.util.cloneJson(configClone); + previousConfigClone = _$micropolar_718.util.cloneJson(configClone); }; exports.undo = function() { undoManager.undo(); }; exports.redo = function() { undoManager.redo(); }; @@ -77677,22 +78514,22 @@ manager.framework = function(_gd) { }; manager.fillLayout = function(_gd) { - var container = _$d3_127.select(_gd).selectAll('.plot-container'), + var container = _$d3_130.select(_gd).selectAll('.plot-container'), paperDiv = container.selectAll('.svg-container'), paper = _gd.framework && _gd.framework.svg && _gd.framework.svg(), dflts = { width: 800, height: 600, - paper_bgcolor: _$color_411.background, + paper_bgcolor: _$color_473.background, _container: container, _paperdiv: paperDiv, _paper: paper }; - _gd._fullLayout = __extendDeepAll_657(dflts, _gd.layout); + _gd._fullLayout = __extendDeepAll_719(dflts, _gd.layout); }; -var _$legacy_655 = {}; +var _$legacy_717 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -77703,11 +78540,11 @@ var _$legacy_655 = {}; 'use strict'; -var Polar = _$legacy_655 = _$micropolar_656; +var Polar = _$legacy_717 = _$micropolar_718; -Polar.manager = _$micropolar_manager_657; +Polar.manager = _$micropolar_manager_719; -var _$plot_api_573 = {}; +var _$plot_api_636 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -77720,37 +78557,33 @@ var _$plot_api_573 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$hasHover_239 = require('has-hover'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$hasHover_296 = require('has-hover'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$Events_527 = require('../lib/events'); */; -/* removed: var _$queue_553 = require('../lib/queue'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$Events_589 = require('../lib/events'); */; +/* removed: var _$queue_616 = require('../lib/queue'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$plot_schema_575 = require('./plot_schema'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$legacy_655 = require('../plots/polar/legacy'); */; -/* removed: var _$initInteractions_593 = require('../plots/cartesian/graph_interact'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$plot_schema_638 = require('./plot_schema'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +/* removed: var _$legacy_717 = require('../plots/polar/legacy'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -/* removed: var _$drawing_436 = require('../components/drawing'); */; -/* removed: var _$color_411 = require('../components/color'); */; -/* removed: var _$xmlns_namespaces_519 = require('../constants/xmlns_namespaces'); */; -/* removed: var _$svg_text_utils_562 = require('../lib/svg_text_utils'); */; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +/* removed: var _$drawing_498 = require('../components/drawing'); */; +/* removed: var _$color_473 = require('../components/color'); */; +var initInteractions = _$graph_interact_656.initInteractions; +/* removed: var _$xmlns_namespaces_580 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$svg_text_utils_625 = require('../lib/svg_text_utils'); */; -/* removed: var _$plot_config_574 = require('./plot_config'); */; -/* removed: var _$manage_arrays_572 = require('./manage_arrays'); */; -/* removed: var _$helpers_570 = require('./helpers'); */; -/* removed: var _$subroutines_576 = require('./subroutines'); */; -/* removed: var _$edit_types_569 = require('./edit_types'); */; +/* removed: var _$plot_config_637 = require('./plot_config'); */; +/* removed: var _$manage_arrays_635 = require('./manage_arrays'); */; +/* removed: var _$helpers_633 = require('./helpers'); */; +/* removed: var _$subroutines_639 = require('./subroutines'); */; +/* removed: var _$edit_types_632 = require('./edit_types'); */; -/* removed: var _$constants_589 = require('../plots/cartesian/constants'); */; -/* removed: var _$constraints_591 = require('../plots/cartesian/constraints'); */; -var enforceAxisConstraints = _$constraints_591.enforce; -var cleanAxisConstraints = _$constraints_591.clean; -var __doAutoRange_573 = _$autorange_583.doAutoRange; +var AX_NAME_PATTERN = _$constants_652.AX_NAME_PATTERN; var numericNameWarningCount = 0; var numericNameWarningCountLimit = 5; @@ -77776,15 +78609,15 @@ var numericNameWarningCountLimit = 5; * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_573.plot = function(gd, data, layout, config) { +_$plot_api_636.plot = function(gd, data, layout, config) { var frames; - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); // Events.init is idempotent and bails early if gd has already been init'd - _$Events_527.init(gd); + _$Events_589.init(gd); - if(_$lib_539.isPlainObject(data)) { + if(_$lib_601.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -77792,19 +78625,19 @@ _$plot_api_573.plot = function(gd, data, layout, config) { frames = obj.frames; } - var okToPlot = _$Events_527.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); + var okToPlot = _$Events_589.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]); if(okToPlot === false) return Promise.reject(); // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug - if(!data && !layout && !_$lib_539.isPlotDiv(gd)) { - _$lib_539.warn('Calling Plotly.plot as if redrawing ' + + if(!data && !layout && !_$lib_601.isPlotDiv(gd)) { + _$lib_601.warn('Calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } function addFrames() { if(frames) { - return _$plot_api_573.addFrames(gd, frames); + return _$plot_api_636.addFrames(gd, frames); } } @@ -77816,12 +78649,15 @@ _$plot_api_573.plot = function(gd, data, layout, config) { // hook class for plots main container (in case of plotly.js // this won't be #embedded-graph or .js-tab-contents) - _$d3_127.select(gd).classed('js-plotly-plot', true); + _$d3_130.select(gd).classed('js-plotly-plot', true); // off-screen getBoundingClientRect testing space, // in #js-plotly-tester (and stored as Drawing.tester) // so we can share cached text across tabs - _$drawing_436.makeTester(); + _$drawing_498.makeTester(); + + // clear stashed base url + delete _$drawing_498.baseUrl; // collect promises for any async actions during plotting // any part of the plotting code can push to gd._promises, then @@ -77834,7 +78670,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { // if there is already data on the graph, append the new data // if you only want to redraw, pass a non-array for data if(Array.isArray(data)) { - _$helpers_570.cleanData(data, gd.data); + _$helpers_633.cleanData(data, gd.data); if(graphWasEmpty) gd.data = data; else gd.data.push.apply(gd.data, data); @@ -77845,7 +78681,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { gd.empty = false; } - if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_570.cleanLayout(layout); + if(!gd.layout || graphWasEmpty) gd.layout = _$helpers_633.cleanLayout(layout); // if the user is trying to drag the axes, allow new data and layout // to come in but don't allow a replot. @@ -77859,7 +78695,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { gd._replotPending = false; } - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); var fullLayout = gd._fullLayout; @@ -77867,7 +78703,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { // Legacy polar plots if(!fullLayout._has('polar') && data && data[0] && data[0].r) { - _$lib_539.log('Legacy polar charts are deprecated!'); + _$lib_601.log('Legacy polar charts are deprecated!'); return plotPolar(gd, data, layout); } @@ -77885,17 +78721,17 @@ _$plot_api_573.plot = function(gd, data, layout, config) { } // clear gradient defs on each .plot call, because we know we'll loop through all traces - _$drawing_436.initGradients(gd); + _$drawing_498.initGradients(gd); // save initial show spikes once per graph - if(graphWasEmpty) _$axes_584.saveShowSpikeInitial(gd); + if(graphWasEmpty) _$axes_647.saveShowSpikeInitial(gd); // prepare the data and find the autorange // generate calcdata, if we need to // to force redoing calcdata, just delete it before calling Plotly.plot var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length; - if(recalc) _$plots_647.doCalcdata(gd); + if(recalc) _$plots_709.doCalcdata(gd); // in case it has changed, attach fullData traces to calcdata for(var i = 0; i < gd.calcdata.length; i++) { @@ -77955,9 +78791,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { .attr('height', fullLayout.height); } - return _$lib_539.syncOrAsync([ - _$subroutines_576.layoutStyles - ], gd); + return _$plots_709.previousPromises(gd); } // draw anything that can affect margins. @@ -77965,31 +78799,31 @@ _$plot_api_573.plot = function(gd, data, layout, config) { var calcdata = gd.calcdata; var i, cd, trace; - _$registry_668.getComponentMethod('legend', 'draw')(gd); - _$registry_668.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_668.getComponentMethod('sliders', 'draw')(gd); - _$registry_668.getComponentMethod('updatemenus', 'draw')(gd); + _$registry_731.getComponentMethod('legend', 'draw')(gd); + _$registry_731.getComponentMethod('rangeselector', 'draw')(gd); + _$registry_731.getComponentMethod('sliders', 'draw')(gd); + _$registry_731.getComponentMethod('updatemenus', 'draw')(gd); for(i = 0; i < calcdata.length; i++) { cd = calcdata[i]; trace = cd[0].trace; if(trace.visible !== true || !trace._module.colorbar) { - _$plots_647.autoMargin(gd, 'cb' + trace.uid); + _$plots_709.autoMargin(gd, 'cb' + trace.uid); } else trace._module.colorbar(gd, cd); } - _$plots_647.doAutoMargin(gd); - return _$plots_647.previousPromises(gd); + _$plots_709.doAutoMargin(gd); + return _$plots_709.previousPromises(gd); } // in case the margins changed, draw margin pushers again function marginPushersAgain() { if(JSON.stringify(fullLayout._size) === oldmargins) return; - return _$lib_539.syncOrAsync([ + return _$lib_601.syncOrAsync([ marginPushers, - _$subroutines_576.layoutStyles + _$subroutines_639.layoutStyles ], gd); } @@ -78010,7 +78844,7 @@ _$plot_api_573.plot = function(gd, data, layout, config) { var subplotInfo, i, j; for(j = 0; j < modules.length; j++) { - _$lib_539.pushUnique(setPositionsArray, modules[j].setPositions); + _$lib_601.pushUnique(setPositionsArray, modules[j].setPositions); } if(setPositionsArray.length) { @@ -78024,136 +78858,55 @@ _$plot_api_573.plot = function(gd, data, layout, config) { } // calc and autorange for errorbars - _$registry_668.getComponentMethod('errorbars', 'calc')(gd); + _$registry_731.getComponentMethod('errorbars', 'calc')(gd); // TODO: autosize extra for text markers and images // see https://github.com/plotly/plotly.js/issues/1111 - return _$lib_539.syncOrAsync([ - _$registry_668.getComponentMethod('shapes', 'calcAutorange'), - _$registry_668.getComponentMethod('annotations', 'calcAutorange'), + return _$lib_601.syncOrAsync([ + _$registry_731.getComponentMethod('shapes', 'calcAutorange'), + _$registry_731.getComponentMethod('annotations', 'calcAutorange'), doAutoRangeAndConstraints, - _$registry_668.getComponentMethod('rangeslider', 'calcAutorange') + _$registry_731.getComponentMethod('rangeslider', 'calcAutorange') ], gd); } function doAutoRangeAndConstraints() { if(gd._transitioning) return; - var axList = _$axes_584.list(gd, '', true); - for(var i = 0; i < axList.length; i++) { - var ax = axList[i]; - cleanAxisConstraints(gd, ax); - - __doAutoRange_573(ax); - } - - enforceAxisConstraints(gd); + _$subroutines_639.doAutoRangeAndConstraints(gd); // store initial ranges *after* enforcing constraints, otherwise // we will never look like we're at the initial ranges - if(graphWasEmpty) _$axes_584.saveRangeInitial(gd); + if(graphWasEmpty) _$axes_647.saveRangeInitial(gd); } // draw ticks, titles, and calculate axis scaling (._b, ._m) function drawAxes() { - return _$axes_584.doTicks(gd, 'redraw'); - } - - // Now plot the data - function drawData() { - var calcdata = gd.calcdata, - i, - rangesliderContainers = fullLayout._infolayer.selectAll('g.rangeslider-container'); - - // in case of traces that were heatmaps or contour maps - // previously, remove them and their colorbars explicitly - for(i = 0; i < calcdata.length; i++) { - var trace = calcdata[i][0].trace, - isVisible = (trace.visible === true), - uid = trace.uid; - - if(!isVisible || !_$registry_668.traceIs(trace, '2dMap')) { - var query = ( - '.hm' + uid + - ',.contour' + uid + - ',#clip' + uid - ); - - fullLayout._paper - .selectAll(query) - .remove(); - - rangesliderContainers - .selectAll(query) - .remove(); - } - - if(!isVisible || !trace._module.colorbar) { - fullLayout._infolayer.selectAll('.cb' + uid).remove(); - } - } - - // loop over the base plot modules present on graph - var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - - // keep reference to shape layers in subplots - var layerSubplot = fullLayout._paper.selectAll('.layer-subplot'); - fullLayout._shapeSubplotLayers = layerSubplot.selectAll('.shapelayer'); - - // styling separate from drawing - _$plots_647.style(gd); - - // show annotations and shapes - _$registry_668.getComponentMethod('shapes', 'draw')(gd); - _$registry_668.getComponentMethod('annotations', 'draw')(gd); - - // source links - _$plots_647.addLinks(gd); - - // Mark the first render as complete - fullLayout._replotting = false; - - return _$plots_647.previousPromises(gd); - } - - // An initial paint must be completed before these components can be - // correctly sized and the whole plot re-margined. fullLayout._replotting must - // be set to false before these will work properly. - function finalDraw() { - _$registry_668.getComponentMethod('shapes', 'draw')(gd); - _$registry_668.getComponentMethod('images', 'draw')(gd); - _$registry_668.getComponentMethod('annotations', 'draw')(gd); - _$registry_668.getComponentMethod('legend', 'draw')(gd); - _$registry_668.getComponentMethod('rangeslider', 'draw')(gd); - _$registry_668.getComponentMethod('rangeselector', 'draw')(gd); - _$registry_668.getComponentMethod('sliders', 'draw')(gd); - _$registry_668.getComponentMethod('updatemenus', 'draw')(gd); + return _$axes_647.doTicks(gd, graphWasEmpty ? '' : 'redraw'); } var seq = [ - _$plots_647.previousPromises, + _$plots_709.previousPromises, addFrames, drawFramework, marginPushers, marginPushersAgain ]; if(hasCartesian) seq.push(positionAndAutorange); - seq.push(_$subroutines_576.layoutStyles); + seq.push(_$subroutines_639.layoutStyles); if(hasCartesian) seq.push(drawAxes); seq.push( - drawData, - finalDraw, - _$initInteractions_593, - _$plots_647.rehover, - _$plots_647.previousPromises + _$subroutines_639.drawData, + _$subroutines_639.finalDraw, + initInteractions, + _$plots_709.addLinks, + _$plots_709.rehover, + _$plots_709.previousPromises ); // even if everything we did was synchronous, return a promise // so that the caller doesn't care which route we took - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -78162,25 +78915,25 @@ _$plot_api_573.plot = function(gd, data, layout, config) { }); }; -_$plot_api_573.setPlotConfig = function setPlotConfig(obj) { - return _$lib_539.extendFlat(_$plot_config_574, obj); +_$plot_api_636.setPlotConfig = function setPlotConfig(obj) { + return _$lib_601.extendFlat(_$plot_config_637, obj); }; function setBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } catch(e) { - _$lib_539.error(e); + _$lib_601.error(e); } } function opaqueSetBackground(gd, bgColor) { - var blend = _$color_411.combine(bgColor, 'white'); + var blend = _$color_473.combine(bgColor, 'white'); setBackground(gd, blend); } function setPlotContext(gd, config) { - if(!gd._context) gd._context = _$lib_539.extendDeep({}, _$plot_config_574); + if(!gd._context) gd._context = _$lib_601.extendDeep({}, _$plot_config_637); var context = gd._context; var i, keys, key; @@ -78241,7 +78994,7 @@ function setPlotContext(gd, config) { } // make sure hover-only devices have mode bar visible - if(context.displayModeBar === 'hover' && !_$hasHover_239) { + if(context.displayModeBar === 'hover' && !_$hasHover_296) { context.displayModeBar = true; } @@ -78253,7 +79006,7 @@ function setPlotContext(gd, config) { function plotPolar(gd, data, layout) { // build or reuse the container skeleton - var plotContainer = _$d3_127.select(gd).selectAll('.plot-container') + var plotContainer = _$d3_130.select(gd).selectAll('.plot-container') .data([0]); plotContainer.enter() .insert('div', ':first-child') @@ -78270,7 +79023,7 @@ function plotPolar(gd, data, layout) { // fulfill gd requirements if(data) gd.data = data; if(layout) gd.layout = layout; - _$legacy_655.manager.fillLayout(gd); + _$legacy_717.manager.fillLayout(gd); // resize canvas paperDiv.style({ @@ -78279,7 +79032,7 @@ function plotPolar(gd, data, layout) { }); // instantiate framework - gd.framework = _$legacy_655.manager.framework(gd); + gd.framework = _$legacy_717.manager.framework(gd); // plot gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node()); @@ -78296,7 +79049,7 @@ function plotPolar(gd, data, layout) { if(txt === '' || !txt) opacity = 0; var titleLayout = function() { - this.call(_$svg_text_utils_562.convertToTspans, gd); + this.call(_$svg_text_utils_625.convertToTspans, gd); // TODO: html/mathjax // TODO: center title }; @@ -78305,7 +79058,7 @@ function plotPolar(gd, data, layout) { .call(titleLayout); if(gd._context.edits.titleText) { - var placeholderText = _$lib_539._(gd, 'Click to enter Plot title'); + var placeholderText = _$lib_601._(gd, 'Click to enter Plot title'); if(!txt || txt === placeholderText) { opacity = 0.2; // placeholder is not going through convertToTspans @@ -78314,17 +79067,17 @@ function plotPolar(gd, data, layout) { .text(placeholderText) .style({opacity: opacity}) .on('mouseover.opacity', function() { - _$d3_127.select(this).transition().duration(100) + _$d3_130.select(this).transition().duration(100) .style('opacity', 1); }) .on('mouseout.opacity', function() { - _$d3_127.select(this).transition().duration(1000) + _$d3_130.select(this).transition().duration(1000) .style('opacity', 0); }); } var setContenteditable = function() { - this.call(_$svg_text_utils_562.makeEditable, {gd: gd}) + this.call(_$svg_text_utils_625.makeEditable, {gd: gd}) .on('edit', function(text) { gd.framework({layout: {title: text}}); this.text(text) @@ -78340,24 +79093,24 @@ function plotPolar(gd, data, layout) { } gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor); - _$plots_647.addLinks(gd); + _$plots_709.addLinks(gd); return Promise.resolve(); } // convenience function to force a full redraw, mostly for use by plotly.js -_$plot_api_573.redraw = function(gd) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.redraw = function(gd) { + gd = _$lib_601.getGraphDiv(gd); - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } - _$helpers_570.cleanData(gd.data, gd.data); - _$helpers_570.cleanLayout(gd.layout); + _$helpers_633.cleanData(gd.data, gd.data); + _$helpers_633.cleanLayout(gd.layout); gd.calcdata = undefined; - return _$plot_api_573.plot(gd).then(function() { + return _$plot_api_636.plot(gd).then(function() { gd.emit('plotly_redraw'); return gd; }); @@ -78371,14 +79124,14 @@ _$plot_api_573.redraw = function(gd) { * @param {Object} layout * @param {Object} config */ -_$plot_api_573.newPlot = function(gd, data, layout, config) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.newPlot = function(gd, data, layout, config) { + gd = _$lib_601.getGraphDiv(gd); // remove gl contexts - _$plots_647.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {}); + _$plots_709.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []); - _$plots_647.purge(gd); - return _$plot_api_573.plot(gd, data, layout, config); + _$plots_709.purge(gd); + return _$plot_api_636.plot(gd, data, layout, config); }; /** @@ -78531,12 +79284,12 @@ function checkAddTracesArgs(gd, traces, newIndices) { */ function assertExtendTracesArgs(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_539.isPlainObject(maxPoints); + var maxPointsIsObject = _$lib_601.isPlainObject(maxPoints); if(!Array.isArray(gd.data)) { throw new Error('gd.data must be an array'); } - if(!_$lib_539.isPlainObject(update)) { + if(!_$lib_601.isPlainObject(update)) { throw new Error('update must be a key:value object'); } @@ -78579,7 +79332,7 @@ function assertExtendTracesArgs(gd, update, indices, maxPoints) { */ function getExtendProperties(gd, update, indices, maxPoints) { - var maxPointsIsObject = _$lib_539.isPlainObject(maxPoints), + var maxPointsIsObject = _$lib_601.isPlainObject(maxPoints), updateProps = []; var trace, target, prop, insert, maxp; @@ -78599,7 +79352,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { * instance that references the key and value for this particular trace. */ trace = gd.data[indices[j]]; - prop = _$lib_539.nestedProperty(trace, key); + prop = _$lib_601.nestedProperty(trace, key); /* * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size" @@ -78608,10 +79361,10 @@ function getExtendProperties(gd, update, indices, maxPoints) { target = prop.get(); insert = update[key][j]; - if(!_$lib_539.isArrayOrTypedArray(insert)) { + if(!_$lib_601.isArrayOrTypedArray(insert)) { throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array'); } - if(!_$lib_539.isArrayOrTypedArray(target)) { + if(!_$lib_601.isArrayOrTypedArray(target)) { throw new Error('cannot extend missing or non-array attribute: ' + key); } if(target.constructor !== insert.constructor) { @@ -78625,7 +79378,7 @@ function getExtendProperties(gd, update, indices, maxPoints) { maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints; // could have chosen null here, -1 just tells us to not take a window - if(!_$fastIsnumeric_139(maxp)) maxp = -1; + if(!_$fastIsnumeric_196(maxp)) maxp = -1; /* * Wrap the nestedProperty in an object containing required data @@ -78706,13 +79459,13 @@ function concatTypedArray(arr0, arr1) { * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening. * */ -_$plot_api_573.extendTraces = function extendTraces(gd, update, indices, maxPoints) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.extendTraces = function extendTraces(gd, update, indices, maxPoints) { + gd = _$lib_601.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_539.isTypedArray(target)) { + if(_$lib_601.isTypedArray(target)) { if(maxp < 0) { var none = new target.constructor(0); var both = concatTypedArray(target, insert); @@ -78757,20 +79510,20 @@ _$plot_api_573.extendTraces = function extendTraces(gd, update, indices, maxPoin } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_573.redraw(gd); + var promise = _$plot_api_636.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_553.add(gd, _$plot_api_573.prependTraces, undoArgs, extendTraces, arguments); + _$queue_616.add(gd, _$plot_api_636.prependTraces, undoArgs, extendTraces, arguments); return promise; }; -_$plot_api_573.prependTraces = function prependTraces(gd, update, indices, maxPoints) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.prependTraces = function prependTraces(gd, update, indices, maxPoints) { + gd = _$lib_601.getGraphDiv(gd); function updateArray(target, insert, maxp) { var newArray, remainder; - if(_$lib_539.isTypedArray(target)) { + if(_$lib_601.isTypedArray(target)) { if(maxp <= 0) { var none = new target.constructor(0); var both = concatTypedArray(insert, target); @@ -78814,9 +79567,9 @@ _$plot_api_573.prependTraces = function prependTraces(gd, update, indices, maxPo } var undo = spliceTraces(gd, update, indices, maxPoints, updateArray); - var promise = _$plot_api_573.redraw(gd); + var promise = _$plot_api_636.redraw(gd); var undoArgs = [gd, undo.update, indices, undo.maxPoints]; - _$queue_553.add(gd, _$plot_api_573.extendTraces, undoArgs, prependTraces, arguments); + _$queue_616.add(gd, _$plot_api_636.extendTraces, undoArgs, prependTraces, arguments); return promise; }; @@ -78830,11 +79583,11 @@ _$plot_api_573.prependTraces = function prependTraces(gd, update, indices, maxPo * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces * */ -_$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.addTraces = function addTraces(gd, traces, newIndices) { + gd = _$lib_601.getGraphDiv(gd); var currentIndices = [], - undoFunc = _$plot_api_573.deleteTraces, + undoFunc = _$plot_api_636.deleteTraces, redoFunc = addTraces, undoArgs = [gd, currentIndices], redoArgs = [gd, traces], // no newIndices here @@ -78851,10 +79604,10 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { // make sure traces do not repeat existing ones traces = traces.map(function(trace) { - return _$lib_539.extendFlat({}, trace); + return _$lib_601.extendFlat({}, trace); }); - _$helpers_570.cleanData(traces, gd.data); + _$helpers_633.cleanData(traces, gd.data); // add the traces to gd.data (no redrawing yet!) for(i = 0; i < traces.length; i++) { @@ -78869,8 +79622,8 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { // if the user didn't define newIndices, they just want the traces appended // i.e., we can simply redraw and be done if(typeof newIndices === 'undefined') { - promise = _$plot_api_573.redraw(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_636.redraw(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; } @@ -78893,10 +79646,10 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { // if we're here, the user has defined specific places to place the new traces // this requires some extra work that moveTraces will do - _$queue_553.startSequence(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = _$plot_api_573.moveTraces(gd, currentIndices, newIndices); - _$queue_553.stopSequence(gd); + _$queue_616.startSequence(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = _$plot_api_636.moveTraces(gd, currentIndices, newIndices); + _$queue_616.stopSequence(gd); return promise; }; @@ -78907,11 +79660,11 @@ _$plot_api_573.addTraces = function addTraces(gd, traces, newIndices) { * @param {Object[]} gd.data The array of traces we're removing from * @param {Number|Number[]} indices The indices */ -_$plot_api_573.deleteTraces = function deleteTraces(gd, indices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.deleteTraces = function deleteTraces(gd, indices) { + gd = _$lib_601.getGraphDiv(gd); var traces = [], - undoFunc = _$plot_api_573.addTraces, + undoFunc = _$plot_api_636.addTraces, redoFunc = deleteTraces, undoArgs = [gd, traces, indices], redoArgs = [gd, indices], @@ -78930,14 +79683,14 @@ _$plot_api_573.deleteTraces = function deleteTraces(gd, indices) { indices = positivifyIndices(indices, gd.data.length - 1); // we want descending here so that splicing later doesn't affect indexing - indices.sort(_$lib_539.sorterDes); + indices.sort(_$lib_601.sorterDes); for(i = 0; i < indices.length; i += 1) { deletedTrace = gd.data.splice(indices[i], 1)[0]; traces.push(deletedTrace); } - var promise = _$plot_api_573.redraw(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_636.redraw(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -78973,8 +79726,8 @@ _$plot_api_573.deleteTraces = function deleteTraces(gd, indices) { * // reorder all traces (assume there are 5--a, b, c, d, e) * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end' */ -_$plot_api_573.moveTraces = function moveTraces(gd, currentIndices, newIndices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.moveTraces = function moveTraces(gd, currentIndices, newIndices) { + gd = _$lib_601.getGraphDiv(gd); var newData = [], movingTraceMap = [], @@ -79034,8 +79787,8 @@ _$plot_api_573.moveTraces = function moveTraces(gd, currentIndices, newIndices) gd.data = newData; - var promise = _$plot_api_573.redraw(gd); - _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + var promise = _$plot_api_636.redraw(gd); + _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); return promise; }; @@ -79070,55 +79823,55 @@ _$plot_api_573.moveTraces = function moveTraces(gd, currentIndices, newIndices) * If the array is too short, it will wrap around (useful for * style files that want to specify cyclical default values). */ -_$plot_api_573.restyle = function restyle(gd, astr, val, _traces) { - gd = _$lib_539.getGraphDiv(gd); - _$helpers_570.clearPromiseQueue(gd); +_$plot_api_636.restyle = function restyle(gd, astr, val, _traces) { + gd = _$lib_601.getGraphDiv(gd); + _$helpers_633.clearPromiseQueue(gd); var aobj = {}; if(typeof astr === 'string') aobj[astr] = val; - else if(_$lib_539.isPlainObject(astr)) { + else if(_$lib_601.isPlainObject(astr)) { // the 3-arg form - aobj = _$lib_539.extendFlat({}, astr); + aobj = _$lib_601.extendFlat({}, astr); if(_traces === undefined) _traces = val; } else { - _$lib_539.warn('Restyle fail.', astr, val, _traces); + _$lib_601.warn('Restyle fail.', astr, val, _traces); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var traces = _$helpers_570.coerceTraceIndices(gd, _traces); + var traces = _$helpers_633.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces), - flags = specs.flags; + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; // clear calcdata and/or axis types if required so they get regenerated if(flags.clearCalc) gd.calcdata = undefined; - if(flags.clearAxisTypes) _$helpers_570.clearAxisTypes(gd, traces, {}); + if(flags.clearAxisTypes) _$helpers_633.clearAxisTypes(gd, traces, {}); // fill in redraw sequence var seq = []; if(flags.fullReplot) { - seq.push(_$plot_api_573.plot); + seq.push(_$plot_api_636.plot); } else { - seq.push(_$plots_647.previousPromises); + seq.push(_$plots_709.previousPromises); - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); - if(flags.style) seq.push(_$subroutines_576.doTraceStyle); - if(flags.colorbars) seq.push(_$subroutines_576.doColorBars); + if(flags.style) seq.push(_$subroutines_639.doTraceStyle); + if(flags.colorbars) seq.push(_$subroutines_639.doColorBars); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - _$queue_553.add(gd, + _$queue_616.add(gd, restyle, [gd, specs.undoit, specs.traces], restyle, [gd, specs.redoit, specs.traces] ); - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { @@ -79141,7 +79894,7 @@ function _restyle(gd, aobj, traces) { i; // initialize flags - var flags = _$edit_types_569.traceFlags(); + var flags = _$edit_types_632.traceFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -79154,7 +79907,7 @@ function _restyle(gd, aobj, traces) { // for autoranging multiple axes function addToAxlist(axid) { - var axName = _$axes_584.id2name(axid); + var axName = _$axes_647.id2name(axid); if(axlist.indexOf(axName) === -1) axlist.push(axName); } @@ -79173,13 +79926,13 @@ function _restyle(gd, aobj, traces) { return; } // quit if explicitly setting this elsewhere - if(attr in aobj || _$helpers_570.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_633.hasParent(aobj, attr)) return; var extraparam; if(attr.substr(0, 6) === 'LAYOUT') { - extraparam = _$lib_539.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); + extraparam = _$lib_601.nestedProperty(gd.layout, attr.replace('LAYOUT', '')); } else { - extraparam = _$lib_539.nestedProperty(data[traces[i]], attr); + extraparam = _$lib_601.nestedProperty(data[traces[i]], attr); } if(!(attr in undoit)) { @@ -79196,7 +79949,7 @@ function _restyle(gd, aobj, traces) { // now make the changes to gd.data (and occasionally gd.layout) // and figure out what kind of graphics update we need to do for(var ai in aobj) { - if(_$helpers_570.hasParent(aobj, ai)) { + if(_$helpers_633.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } @@ -79211,7 +79964,7 @@ function _restyle(gd, aobj, traces) { redoit[ai] = vi; if(ai.substr(0, 6) === 'LAYOUT') { - param = _$lib_539.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); + param = _$lib_601.nestedProperty(gd.layout, ai.replace('LAYOUT', '')); undoit[ai] = [undefinedToNull(param.get())]; // since we're allowing val to be an array, allow it here too, // even though that's meaningless @@ -79227,17 +79980,17 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { cont = data[traces[i]]; contFull = fullData[traces[i]]; - param = _$lib_539.nestedProperty(cont, ai); + param = _$lib_601.nestedProperty(cont, ai); oldVal = param.get(); newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; if(newVal === undefined) continue; - valObject = _$plot_schema_575.getTraceValObject(contFull, param.parts); + valObject = _$plot_schema_638.getTraceValObject(contFull, param.parts); if(valObject && valObject.impliedEdits && newVal !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_539.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + doextra(_$lib_601.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); } } @@ -79277,19 +80030,19 @@ function _restyle(gd, aobj, traces) { labelsTo = 'y'; valuesTo = 'x'; } - _$lib_539.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); - _$lib_539.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); - _$lib_539.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); + _$lib_601.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo); + _$lib_601.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo); + _$lib_601.swapAttrs(cont, ['?', '?src'], 'values', valuesTo); if(oldVal === 'pie') { - _$lib_539.nestedProperty(cont, 'marker.color') - .set(_$lib_539.nestedProperty(cont, 'marker.colors').get()); + _$lib_601.nestedProperty(cont, 'marker.color') + .set(_$lib_601.nestedProperty(cont, 'marker.colors').get()); // super kludgy - but if all pies are gone we won't remove them otherwise fullLayout._pielayer.selectAll('g.trace').remove(); - } else if(_$registry_668.traceIs(cont, 'cartesian')) { - _$lib_539.nestedProperty(cont, 'marker.colors') - .set(_$lib_539.nestedProperty(cont, 'marker.color').get()); + } else if(_$registry_731.traceIs(cont, 'cartesian')) { + _$lib_601.nestedProperty(cont, 'marker.colors') + .set(_$lib_601.nestedProperty(cont, 'marker.color').get()); } } @@ -79318,23 +80071,23 @@ function _restyle(gd, aobj, traces) { cont.orientation = {v: 'h', h: 'v'}[contFull.orientation]; } - _$helpers_570.swapXYData(cont); + _$helpers_633.swapXYData(cont); flags.calc = flags.clearAxisTypes = true; } - else if(_$plots_647.dataArrayContainers.indexOf(param.parts[0]) !== -1) { + else if(_$plots_709.dataArrayContainers.indexOf(param.parts[0]) !== -1) { // TODO: use manageArrays.applyContainerArrayChanges here too - _$helpers_570.manageArrayContainers(param, newVal, undoit); + _$helpers_633.manageArrayContainers(param, newVal, undoit); flags.calc = true; } else { if(valObject) { // must redo calcdata when restyling array values of arrayOk attributes if(valObject.arrayOk && ( - _$lib_539.isArrayOrTypedArray(newVal) || _$lib_539.isArrayOrTypedArray(oldVal)) + _$lib_601.isArrayOrTypedArray(newVal) || _$lib_601.isArrayOrTypedArray(oldVal)) ) { flags.calc = true; } - else _$edit_types_569.update(flags, valObject); + else _$edit_types_632.update(flags, valObject); } else { /* @@ -79353,12 +80106,12 @@ function _restyle(gd, aobj, traces) { // swap the data attributes of the relevant x and y axes? if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) { - _$axes_584.swap(gd, traces); + _$axes_647.swap(gd, traces); } // swap hovermode if set to "compare x/y data" if(ai === 'orientationaxes') { - var hovermode = _$lib_539.nestedProperty(gd.layout, 'hovermode'); + var hovermode = _$lib_601.nestedProperty(gd.layout, 'hovermode'); if(hovermode.get() === 'x') { hovermode.set('y'); } else if(hovermode.get() === 'y') { @@ -79373,7 +80126,7 @@ function _restyle(gd, aobj, traces) { for(i = 0; i < traces.length; i++) { var trace = data[traces[i]]; - if(_$registry_668.traceIs(trace, 'cartesian')) { + if(_$registry_731.traceIs(trace, 'cartesian')) { addToAxlist(trace.xaxis || 'x'); addToAxlist(trace.yaxis || 'y'); @@ -79390,7 +80143,7 @@ function _restyle(gd, aobj, traces) { // do we need to force a recalc? var autorangeOn = false; - var axList = _$axes_584.list(gd); + var axList = _$axes_647.list(gd); for(i = 0; i < axList.length; i++) { if(axList[i].autorange) { autorangeOn = true; @@ -79411,7 +80164,7 @@ function _restyle(gd, aobj, traces) { undoit: undoit, redoit: redoit, traces: traces, - eventData: _$lib_539.extendDeepNoArrays([], [redoit, traces]) + eventData: _$lib_601.extendDeepNoArrays([], [redoit, traces]) }; } @@ -79435,9 +80188,9 @@ function _restyle(gd, aobj, traces) { * attribute object `{astr1: val1, astr2: val2 ...}` * allows setting multiple attributes simultaneously */ -_$plot_api_573.relayout = function relayout(gd, astr, val) { - gd = _$lib_539.getGraphDiv(gd); - _$helpers_570.clearPromiseQueue(gd); +_$plot_api_636.relayout = function relayout(gd, astr, val) { + gd = _$lib_601.getGraphDiv(gd); + _$helpers_633.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); @@ -79446,50 +80199,74 @@ _$plot_api_573.relayout = function relayout(gd, astr, val) { var aobj = {}; if(typeof astr === 'string') { aobj[astr] = val; - } else if(_$lib_539.isPlainObject(astr)) { - aobj = _$lib_539.extendFlat({}, astr); + } else if(_$lib_601.isPlainObject(astr)) { + aobj = _$lib_601.extendFlat({}, astr); } else { - _$lib_539.warn('Relayout fail.', astr, val); + _$lib_601.warn('Relayout fail.', astr, val); return Promise.reject(); } if(Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj), - flags = specs.flags; + var specs = _relayout(gd, aobj); + var flags = specs.flags; // clear calcdata if required if(flags.calc) gd.calcdata = undefined; - if(flags.margins) _$helpers_570.clearAxisAutomargins(gd); + if(flags.margins) _$helpers_633.clearAxisAutomargins(gd); // fill in redraw sequence // even if we don't have anything left in aobj, // something may have happened within relayout that we // need to wait for - var seq = [_$plots_647.previousPromises]; + var seq = [_$plots_709.previousPromises]; if(flags.layoutReplot) { - seq.push(_$subroutines_576.layoutReplot); + seq.push(_$subroutines_639.layoutReplot); } else if(Object.keys(aobj).length) { - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); + + if(flags.legend) seq.push(_$subroutines_639.doLegend); + if(flags.layoutstyle) seq.push(_$subroutines_639.layoutStyles); + + if(flags.axrange) { + // N.B. leave as sequence of subroutines (for now) instead of + // subroutine of its own so that finalDraw always gets + // executed after drawData + seq.push( + // TODO + // no test fail when commenting out doAutoRangeAndConstraints, + // but I think we do need this (maybe just the enforce part?) + // Am I right? + // More info in: + // https://github.com/plotly/plotly.js/issues/2540 + _$subroutines_639.doAutoRangeAndConstraints, + // TODO + // can target specific axes, + // do not have to redraw all axes here + // See: + // https://github.com/plotly/plotly.js/issues/2547 + _$subroutines_639.doTicksRelayout, + _$subroutines_639.drawData, + _$subroutines_639.finalDraw + ); + } - if(flags.legend) seq.push(_$subroutines_576.doLegend); - if(flags.layoutstyle) seq.push(_$subroutines_576.layoutStyles); - if(flags.ticks) seq.push(_$subroutines_576.doTicksRelayout); - if(flags.modebar) seq.push(_$subroutines_576.doModeBar); - if(flags.camera) seq.push(_$subroutines_576.doCamera); + if(flags.ticks) seq.push(_$subroutines_639.doTicksRelayout); + if(flags.modebar) seq.push(_$subroutines_639.doModeBar); + if(flags.camera) seq.push(_$subroutines_639.doCamera); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - _$queue_553.add(gd, + _$queue_616.add(gd, relayout, [gd, specs.undoit], relayout, [gd, specs.redoit] ); - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -79502,7 +80279,7 @@ function _relayout(gd, aobj) { var layout = gd.layout, fullLayout = gd._fullLayout, keys = Object.keys(aobj), - axes = _$axes_584.list(gd), + axes = _$axes_647.list(gd), arrayEdits = {}, arrayStr, i, @@ -79525,7 +80302,7 @@ function _relayout(gd, aobj) { } // initialize flags - var flags = _$edit_types_569.layoutFlags(); + var flags = _$edit_types_632.layoutFlags(); // copies of the change (and previous values of anything affected) // for the undo / redo queue @@ -79544,9 +80321,9 @@ function _relayout(gd, aobj) { // if we have another value for this attribute (explicitly or // via a parent) do not override with this auto-generated extra - if(attr in aobj || _$helpers_570.hasParent(aobj, attr)) return; + if(attr in aobj || _$helpers_633.hasParent(aobj, attr)) return; - var p = _$lib_539.nestedProperty(layout, attr); + var p = _$lib_601.nestedProperty(layout, attr); if(!(attr in undoit)) { undoit[attr] = undefinedToNull(p.get()); } @@ -79560,18 +80337,18 @@ function _relayout(gd, aobj) { var axId; function recordAlteredAxis(pleafPlus) { - var axId = _$axes_584.name2id(pleafPlus.split('.')[0]); + var axId = _$axes_647.name2id(pleafPlus.split('.')[0]); rangesAltered[axId] = 1; return axId; } // alter gd.layout for(var ai in aobj) { - if(_$helpers_570.hasParent(aobj, ai)) { + if(_$helpers_633.hasParent(aobj, ai)) { throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously'); } - var p = _$lib_539.nestedProperty(layout, ai); + var p = _$lib_601.nestedProperty(layout, ai); var vi = aobj[ai]; var plen = p.parts.length; // p.parts may end with an index integer if the property is an array @@ -79583,8 +80360,8 @@ function _relayout(gd, aobj) { var pleafPlus = p.parts[pend - 1] + '.' + pleaf; // trunk nodes (everything except the leaf) var ptrunk = p.parts.slice(0, pend).join('.'); - var parentIn = _$lib_539.nestedProperty(gd.layout, ptrunk).get(); - var parentFull = _$lib_539.nestedProperty(fullLayout, ptrunk).get(); + var parentIn = _$lib_601.nestedProperty(gd.layout, ptrunk).get(); + var parentFull = _$lib_601.nestedProperty(fullLayout, ptrunk).get(); var vOld = p.get(); if(vi === undefined) continue; @@ -79595,11 +80372,11 @@ function _relayout(gd, aobj) { // op and has no flag. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld); - var valObject = _$plot_schema_575.getLayoutValObject(fullLayout, p.parts); + var valObject = _$plot_schema_638.getLayoutValObject(fullLayout, p.parts); if(valObject && valObject.impliedEdits && vi !== null) { for(var impliedKey in valObject.impliedEdits) { - doextra(_$lib_539.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + doextra(_$lib_601.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); } } @@ -79613,12 +80390,12 @@ function _relayout(gd, aobj) { // check autorange vs range else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) { recordAlteredAxis(pleafPlus); - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) { recordAlteredAxis(pleafPlus); - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); - var axFull = _$lib_539.nestedProperty(fullLayout, ptrunk).get(); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + var axFull = _$lib_601.nestedProperty(fullLayout, ptrunk).get(); if(axFull._inputDomain) { // if we're autoranging and this axis has a constrained domain, // reset it so we don't get locked into a shrunken size @@ -79626,7 +80403,7 @@ function _relayout(gd, aobj) { } } else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) { - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null); } // toggling axis type between log and linear: we need to convert @@ -79686,8 +80463,8 @@ function _relayout(gd, aobj) { // Annotations and images also need to convert to/from linearized coords // Shapes do not need this :) - _$registry_668.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); - _$registry_668.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_731.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra); + _$registry_731.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra); } else { // any other type changes: the range from the previous type @@ -79695,18 +80472,18 @@ function _relayout(gd, aobj) { doextra(ptrunk + '.autorange', true); doextra(ptrunk + '.range', null); } - _$lib_539.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); + _$lib_601.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null); } - else if(pleaf.match(_$constants_589.AX_NAME_PATTERN)) { - var fullProp = _$lib_539.nestedProperty(fullLayout, ai).get(), + else if(pleaf.match(AX_NAME_PATTERN)) { + var fullProp = _$lib_601.nestedProperty(fullLayout, ai).get(), newType = (vi || {}).type; // This can potentially cause strange behavior if the autotype is not // numeric (linear, because we don't auto-log) but the previous type // was log. That's a very strange edge case though if(!newType || newType === '-') newType = 'linear'; - _$registry_668.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); - _$registry_668.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_731.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra); + _$registry_731.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra); } // alter gd.layout @@ -79715,12 +80492,12 @@ function _relayout(gd, aobj) { // so we can ensure consistent behavior adding/removing items // and order-independence for add/remove/edit all together in // one relayout call - var containerArrayMatch = _$manage_arrays_572.containerArrayMatch(ai); + var containerArrayMatch = _$manage_arrays_635.containerArrayMatch(ai); if(containerArrayMatch) { arrayStr = containerArrayMatch.array; i = containerArrayMatch.index; var propStr = containerArrayMatch.property; - var componentArray = _$lib_539.nestedProperty(layout, arrayStr); + var componentArray = _$lib_601.nestedProperty(layout, arrayStr); var obji = (componentArray || [])[i] || {}; var objToAutorange = obji; @@ -79730,28 +80507,29 @@ function _relayout(gd, aobj) { if(i === '') { // replacing the entire array - too many possibilities, just recalc if(checkForAutorange) flags.calc = true; - else _$edit_types_569.update(flags, updateValObject); + else _$edit_types_632.update(flags, updateValObject); checkForAutorange = false; // clear this, we're already doing a recalc } else if(propStr === '') { // special handling of undoit if we're adding or removing an element // ie 'annotations[2]' which can be {...} (add) or null (remove) objToAutorange = vi; - if(_$manage_arrays_572.isAddVal(vi)) { + if(_$manage_arrays_635.isAddVal(vi)) { undoit[ai] = null; } - else if(_$manage_arrays_572.isRemoveVal(vi)) { + else if(_$manage_arrays_635.isRemoveVal(vi)) { undoit[ai] = obji; objToAutorange = obji; } - else _$lib_539.warn('unrecognized full object value', aobj); + else _$lib_601.warn('unrecognized full object value', aobj); } if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) { flags.calc = true; } - else _$edit_types_569.update(flags, updateValObject); - + else { + _$edit_types_632.update(flags, updateValObject); + } // prepare the edits object we'll send to applyContainerArrayChanges if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; @@ -79780,7 +80558,7 @@ function _relayout(gd, aobj) { ) { flags.plot = true; } - else if(valObject) _$edit_types_569.update(flags, valObject); + else if(valObject) _$edit_types_632.update(flags, valObject); else flags.calc = true; p.set(vi); @@ -79789,8 +80567,8 @@ function _relayout(gd, aobj) { // now we've collected component edits - execute them all together for(arrayStr in arrayEdits) { - var finished = _$manage_arrays_572.applyContainerArrayChanges(gd, - _$lib_539.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); + var finished = _$manage_arrays_635.applyContainerArrayChanges(gd, + _$lib_601.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags); if(!finished) flags.plot = true; } @@ -79808,7 +80586,7 @@ function _relayout(gd, aobj) { flags.calc = true; for(var groupAxId in group) { if(!rangesAltered[groupAxId]) { - _$axes_584.getFromId(gd, groupAxId)._constraintShrinkable = true; + _$axes_647.getFromId(gd, groupAxId)._constraintShrinkable = true; } } } @@ -79832,7 +80610,7 @@ function _relayout(gd, aobj) { flags: flags, undoit: undoit, redoit: redoit, - eventData: _$lib_539.extendDeep({}, redoit) + eventData: _$lib_601.extendDeep({}, redoit) }; } @@ -79847,16 +80625,16 @@ function updateAutosize(gd) { var oldHeight = fullLayout.height; // calculate autosizing - if(gd.layout.autosize) _$plots_647.plotAutoSize(gd, gd.layout, fullLayout); + if(gd.layout.autosize) _$plots_709.plotAutoSize(gd, gd.layout, fullLayout); return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight); } // for editing annotations or shapes - is it on autoscaled axes? function refAutorange(gd, obj, axLetter) { - if(!_$lib_539.isPlainObject(obj)) return false; + if(!_$lib_601.isPlainObject(obj)) return false; var axRef = obj[axLetter + 'ref'] || axLetter, - ax = _$axes_584.getFromId(gd, axRef); + ax = _$axes_647.getFromId(gd, axRef); if(!ax && axRef.charAt(0) === axLetter) { // fall back on the primary axis in case we've referenced a @@ -79866,7 +80644,7 @@ function refAutorange(gd, obj, axLetter) { // The only thing this is used for is to determine whether to // do a full `recalc`, so the only ill effect of this error is // to waste some time. - ax = _$axes_584.getFromId(gd, axLetter); + ax = _$axes_647.getFromId(gd, axLetter); } return (ax || {}).autorange; } @@ -79886,32 +80664,32 @@ function refAutorange(gd, obj, axLetter) { * integer or array of integers for the traces to alter (all if omitted) * */ -_$plot_api_573.update = function update(gd, traceUpdate, layoutUpdate, _traces) { - gd = _$lib_539.getGraphDiv(gd); - _$helpers_570.clearPromiseQueue(gd); +_$plot_api_636.update = function update(gd, traceUpdate, layoutUpdate, _traces) { + gd = _$lib_601.getGraphDiv(gd); + _$helpers_633.clearPromiseQueue(gd); if(gd.framework && gd.framework.isPolar) { return Promise.resolve(gd); } - if(!_$lib_539.isPlainObject(traceUpdate)) traceUpdate = {}; - if(!_$lib_539.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if(!_$lib_601.isPlainObject(traceUpdate)) traceUpdate = {}; + if(!_$lib_601.isPlainObject(layoutUpdate)) layoutUpdate = {}; if(Object.keys(traceUpdate).length) gd.changed = true; if(Object.keys(layoutUpdate).length) gd.changed = true; - var traces = _$helpers_570.coerceTraceIndices(gd, _traces); + var traces = _$helpers_633.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, _$lib_539.extendFlat({}, traceUpdate), traces), - restyleFlags = restyleSpecs.flags; + var restyleSpecs = _restyle(gd, _$lib_601.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, _$lib_539.extendFlat({}, layoutUpdate)), - relayoutFlags = relayoutSpecs.flags; + var relayoutSpecs = _relayout(gd, _$lib_601.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; // clear calcdata and/or axis types if required if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined; - if(restyleFlags.clearAxisTypes) _$helpers_570.clearAxisTypes(gd, traces, layoutUpdate); - if(relayoutFlags.margins) _$helpers_570.clearAxisAutomargins(gd); + if(restyleFlags.clearAxisTypes) _$helpers_633.clearAxisTypes(gd, traces, layoutUpdate); + if(relayoutFlags.margins) _$helpers_633.clearAxisAutomargins(gd); // fill in redraw sequence var seq = []; @@ -79925,35 +80703,43 @@ _$plot_api_573.update = function update(gd, traceUpdate, layoutUpdate, _traces) gd.data = undefined; gd.layout = undefined; - seq.push(function() { return _$plot_api_573.plot(gd, data, layout); }); + seq.push(function() { return _$plot_api_636.plot(gd, data, layout); }); } else if(restyleFlags.fullReplot) { - seq.push(_$plot_api_573.plot); + seq.push(_$plot_api_636.plot); } else if(relayoutFlags.layoutReplot) { - seq.push(_$subroutines_576.layoutReplot); + seq.push(_$subroutines_639.layoutReplot); } else { - seq.push(_$plots_647.previousPromises); - _$plots_647.supplyDefaults(gd); - - if(restyleFlags.style) seq.push(_$subroutines_576.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_576.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_576.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_576.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_576.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_576.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_576.doCamera); + seq.push(_$plots_709.previousPromises); + _$plots_709.supplyDefaults(gd); + + if(restyleFlags.style) seq.push(_$subroutines_639.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_639.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_639.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_639.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_639.doAutoRangeAndConstraints, + _$subroutines_639.doTicksRelayout, + _$subroutines_639.drawData, + _$subroutines_639.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_639.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_639.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_639.doCamera); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - _$queue_553.add(gd, + _$queue_616.add(gd, update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] ); - var plotDone = _$lib_539.syncOrAsync(seq, gd); + var plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); return plotDone.then(function() { @@ -79989,23 +80775,23 @@ _$plot_api_573.update = function update(gd, traceUpdate, layoutUpdate, _traces) * object containing `data`, `layout`, `config`, and `frames` members * */ -_$plot_api_573.react = function(gd, data, layout, config) { +_$plot_api_636.react = function(gd, data, layout, config) { var frames, plotDone; - function addFrames() { return _$plot_api_573.addFrames(gd, frames); } + function addFrames() { return _$plot_api_636.addFrames(gd, frames); } - gd = _$lib_539.getGraphDiv(gd); + gd = _$lib_601.getGraphDiv(gd); var oldFullData = gd._fullData; var oldFullLayout = gd._fullLayout; // you can use this as the initial draw as well as to update - if(!_$lib_539.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = _$plot_api_573.newPlot(gd, data, layout, config); + if(!_$lib_601.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = _$plot_api_636.newPlot(gd, data, layout, config); } else { - if(_$lib_539.isPlainObject(data)) { + if(_$lib_601.isPlainObject(data)) { var obj = data; data = obj.data; layout = obj.layout; @@ -80017,18 +80803,18 @@ _$plot_api_573.react = function(gd, data, layout, config) { // assume that if there's a config at all, we're reacting to it too, // and completely replace the previous config if(config) { - var oldConfig = _$lib_539.extendDeep({}, gd._context); + var oldConfig = _$lib_601.extendDeep({}, gd._context); gd._context = undefined; setPlotContext(gd, config); configChanged = diffConfig(oldConfig, gd._context); } gd.data = data || []; - _$helpers_570.cleanData(gd.data, []); + _$helpers_633.cleanData(gd.data, []); gd.layout = layout || {}; - _$helpers_570.cleanLayout(gd.layout); + _$helpers_633.cleanLayout(gd.layout); - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); var newFullData = gd._fullData; var newFullLayout = gd._fullLayout; @@ -80050,7 +80836,7 @@ _$plot_api_573.react = function(gd, data, layout, config) { // clear calcdata if required if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined; - if(relayoutFlags.margins) _$helpers_570.clearAxisAutomargins(gd); + if(relayoutFlags.margins) _$helpers_633.clearAxisAutomargins(gd); // Note: what restyle/relayout use impliedEdits and clearAxisTypes for // must be handled by the user when using Plotly.react. @@ -80060,27 +80846,27 @@ _$plot_api_573.react = function(gd, data, layout, config) { if(frames) { gd._transitionData = {}; - _$plots_647.createTransitionData(gd); + _$plots_709.createTransitionData(gd); seq.push(addFrames); } if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { gd._fullLayout._skipDefaults = true; - seq.push(_$plot_api_573.plot); + seq.push(_$plot_api_636.plot); } else { for(var componentType in relayoutFlags.arrays) { var indices = relayoutFlags.arrays[componentType]; if(indices.length) { - var drawOne = _$registry_668.getComponentMethod(componentType, 'drawOne'); - if(drawOne !== _$lib_539.noop) { + var drawOne = _$registry_731.getComponentMethod(componentType, 'drawOne'); + if(drawOne !== _$lib_601.noop) { for(var i = 0; i < indices.length; i++) { drawOne(gd, indices[i]); } } else { - var draw = _$registry_668.getComponentMethod(componentType, 'draw'); - if(draw === _$lib_539.noop) { + var draw = _$registry_731.getComponentMethod(componentType, 'draw'); + if(draw === _$lib_601.noop) { throw new Error('cannot draw components: ' + componentType); } draw(gd); @@ -80088,19 +80874,27 @@ _$plot_api_573.react = function(gd, data, layout, config) { } } - seq.push(_$plots_647.previousPromises); - if(restyleFlags.style) seq.push(_$subroutines_576.doTraceStyle); - if(restyleFlags.colorbars) seq.push(_$subroutines_576.doColorBars); - if(relayoutFlags.legend) seq.push(_$subroutines_576.doLegend); - if(relayoutFlags.layoutstyle) seq.push(_$subroutines_576.layoutStyles); - if(relayoutFlags.ticks) seq.push(_$subroutines_576.doTicksRelayout); - if(relayoutFlags.modebar) seq.push(_$subroutines_576.doModeBar); - if(relayoutFlags.camera) seq.push(_$subroutines_576.doCamera); + seq.push(_$plots_709.previousPromises); + if(restyleFlags.style) seq.push(_$subroutines_639.doTraceStyle); + if(restyleFlags.colorbars) seq.push(_$subroutines_639.doColorBars); + if(relayoutFlags.legend) seq.push(_$subroutines_639.doLegend); + if(relayoutFlags.layoutstyle) seq.push(_$subroutines_639.layoutStyles); + if(relayoutFlags.axrange) { + seq.push( + _$subroutines_639.doAutoRangeAndConstraints, + _$subroutines_639.doTicksRelayout, + _$subroutines_639.drawData, + _$subroutines_639.finalDraw + ); + } + if(relayoutFlags.ticks) seq.push(_$subroutines_639.doTicksRelayout); + if(relayoutFlags.modebar) seq.push(_$subroutines_639.doModeBar); + if(relayoutFlags.camera) seq.push(_$subroutines_639.doCamera); } - seq.push(_$plots_647.rehover); + seq.push(_$plots_709.rehover); - plotDone = _$lib_539.syncOrAsync(seq, gd); + plotDone = _$lib_601.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); } @@ -80123,12 +80917,12 @@ function diffData(gd, oldFullData, newFullData, immutable) { }; } - var flags = _$edit_types_569.traceFlags(); + var flags = _$edit_types_632.traceFlags(); flags.arrays = {}; var i, trace; function getTraceValObject(parts) { - return _$plot_schema_575.getTraceValObject(trace, parts); + return _$plot_schema_638.getTraceValObject(trace, parts); } var diffOpts = { @@ -80138,11 +80932,17 @@ function diffData(gd, oldFullData, newFullData, immutable) { gd: gd }; + + var seenUIDs = {}; + for(i = 0; i < oldFullData.length; i++) { - trace = newFullData[i]; + trace = newFullData[i]._fullInput; + if(seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + diffOpts.autoranged = trace.xaxis ? ( - _$axes_584.getFromId(gd, trace.xaxis).autorange || - _$axes_584.getFromId(gd, trace.yaxis).autorange + _$axes_647.getFromId(gd, trace.xaxis).autorange || + _$axes_647.getFromId(gd, trace.yaxis).autorange ) : false; getDiffFlags(oldFullData[i], trace, [], diffOpts); } @@ -80155,11 +80955,11 @@ function diffData(gd, oldFullData, newFullData, immutable) { } function diffLayout(gd, oldFullLayout, newFullLayout, immutable) { - var flags = _$edit_types_569.layoutFlags(); + var flags = _$edit_types_632.layoutFlags(); flags.arrays = {}; function getLayoutValObject(parts) { - return _$plot_schema_575.getLayoutValObject(newFullLayout, parts); + return _$plot_schema_638.getLayoutValObject(newFullLayout, parts); } var diffOpts = { @@ -80198,10 +80998,10 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { return; } if(inArray && editType.indexOf('arraydraw') !== -1) { - _$lib_539.pushUnique(flags.arrays[inArray], arrayIndex); + _$lib_601.pushUnique(flags.arrays[inArray], arrayIndex); return; } - _$edit_types_569.update(flags, valObject); + _$edit_types_632.update(flags, valObject); } function valObjectCanBeDataArray(valObject) { @@ -80281,7 +81081,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { for(i = 0; i < minLen; i++) { getDiffFlags(oldVal[i], newVal[i], parts.concat(i), // add array indices, but not if we're already in an array - _$lib_539.extendFlat({inArray: key, arrayIndex: i}, opts)); + _$lib_601.extendFlat({inArray: key, arrayIndex: i}, opts)); } // put this at the end so that we know our collected array indices are sorted @@ -80293,7 +81093,7 @@ function getDiffFlags(oldContainer, newContainer, outerparts, opts) { } } } - else if(!valType && _$lib_539.isPlainObject(oldVal)) { + else if(!valType && _$lib_601.isPlainObject(oldVal)) { getDiffFlags(oldVal, newVal, parts, opts); } else if(canBeDataArray) { @@ -80347,7 +81147,7 @@ function diffConfig(oldConfig, newConfig) { var oldVal = oldConfig[key]; var newVal = newConfig[key]; if(oldVal !== newVal) { - if(_$lib_539.isPlainObject(oldVal) && _$lib_539.isPlainObject(newVal)) { + if(_$lib_601.isPlainObject(oldVal) && _$lib_601.isPlainObject(newVal)) { if(diffConfig(oldVal, newVal)) { return true; } @@ -80358,7 +81158,7 @@ function diffConfig(oldConfig, newConfig) { } for(var i = 0; i < oldVal.length; i++) { if(oldVal[i] !== newVal[i]) { - if(_$lib_539.isPlainObject(oldVal[i]) && _$lib_539.isPlainObject(newVal[i])) { + if(_$lib_601.isPlainObject(oldVal[i]) && _$lib_601.isPlainObject(newVal[i])) { if(diffConfig(oldVal[i], newVal[i])) { return true; } @@ -80403,10 +81203,10 @@ function diffConfig(oldConfig, newConfig) { * @param {object} animationOpts * configuration for the animation */ -_$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = _$lib_601.getGraphDiv(gd); - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before animating it. For more details, see ' + @@ -80422,7 +81222,7 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts trans._frameQueue = []; } - animationOpts = _$plots_647.supplyAnimationDefaults(animationOpts); + animationOpts = _$plots_709.supplyAnimationDefaults(animationOpts); var transitionOpts = animationOpts.transition; var frameOpts = animationOpts.frame; @@ -80496,7 +81296,7 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts if(frameList[i].type === 'byname') { // If it's a named frame, compute it: - computedFrame = _$plots_647.computeFrame(gd, frameList[i].name); + computedFrame = _$plots_709.computeFrame(gd, frameList[i].name); } else { // Otherwise we must have been given a simple object, so treat // the input itself as the computed frame. @@ -80577,10 +81377,10 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts // This is simply called and it's left to .transition to decide how to manage // interrupting current transitions. That means we don't need to worry about // how it resolves or what happens after this: - _$plots_647.transition(gd, + _$plots_709.transition(gd, newFrame.frame.data, newFrame.frame.layout, - _$helpers_570.coerceTraceIndices(gd, newFrame.frame.traces), + _$helpers_633.coerceTraceIndices(gd, newFrame.frame.traces), newFrame.frameOpts, newFrame.transitionOpts ).then(function() { @@ -80650,13 +81450,13 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts var frameList = []; var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null; var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && _$lib_539.isPlainObject(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && _$lib_601.isPlainObject(frameOrGroupNameOrFrameList); if(isSingleFrame) { // In this case, a simple object has been passed to animate. frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_539.extendFlat({}, frameOrGroupNameOrFrameList)) + data: setTransitionConfig(_$lib_601.extendFlat({}, frameOrGroupNameOrFrameList)) }); } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { // In this case, null or undefined has been passed so that we want to @@ -80685,10 +81485,10 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts name: frameOrName, data: setTransitionConfig({name: frameOrName}) }); - } else if(_$lib_539.isPlainObject(frameOrName)) { + } else if(_$lib_601.isPlainObject(frameOrName)) { frameList.push({ type: 'object', - data: setTransitionConfig(_$lib_539.extendFlat({}, frameOrName)) + data: setTransitionConfig(_$lib_601.extendFlat({}, frameOrName)) }); } } @@ -80698,7 +81498,7 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts for(i = 0; i < frameList.length; i++) { frame = frameList[i]; if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) { - _$lib_539.warn('animate failure: frame not found: "' + frame.data.name + '"'); + _$lib_601.warn('animate failure: frame not found: "' + frame.data.name + '"'); reject(); return; } @@ -80767,14 +81567,14 @@ _$plot_api_573.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts * provided, an index will be provided in serial order. If already used, the frame * will be overwritten. */ -_$plot_api_573.addFrames = function(gd, frameList, indices) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.addFrames = function(gd, frameList, indices) { + gd = _$lib_601.getGraphDiv(gd); if(frameList === null || frameList === undefined) { return Promise.resolve(); } - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error( 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' + 'to create a plot before adding frames. For more details, see ' + @@ -80801,7 +81601,7 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { var insertions = []; var _frameHashLocal = {}; for(i = frameList.length - 1; i >= 0; i--) { - if(!_$lib_539.isPlainObject(frameList[i])) continue; + if(!_$lib_601.isPlainObject(frameList[i])) continue; // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and // use a Map instead of an Object instance, as Map keys aren't converted to strings. @@ -80813,14 +81613,14 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { numericNameWarningCount++; - _$lib_539.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + + _$lib_601.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name + '" with a frame whose name of type "number" also equates to "' + name + '". This is valid but may potentially lead to unexpected ' + 'behavior since all plotly.js frame names are stored internally ' + 'as strings.'); if(numericNameWarningCount === numericNameWarningCountLimit) { - _$lib_539.warn('addFrames: This API call has yielded too many of these warnings. ' + + _$lib_601.warn('addFrames: This API call has yielded too many of these warnings. ' + 'For the rest of this call, further warnings about numeric frame ' + 'names will be suppressed.'); } @@ -80829,7 +81629,7 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { _frameHashLocal[lookupName] = {name: lookupName}; insertions.push({ - frame: _$plots_647.supplyFrameDefaults(frameList[i]), + frame: _$plots_709.supplyFrameDefaults(frameList[i]), index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i }); } @@ -80849,7 +81649,7 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { frame = insertions[i].frame; if(typeof frame.name === 'number') { - _$lib_539.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + + _$lib_601.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' + 'implicitly cast to strings'); } @@ -80877,14 +81677,14 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { } } - var undoFunc = _$plots_647.modifyFrames, - redoFunc = _$plots_647.modifyFrames, + var undoFunc = _$plots_709.modifyFrames, + redoFunc = _$plots_709.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_553) _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_616) _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return _$plots_647.modifyFrames(gd, ops); + return _$plots_709.modifyFrames(gd, ops); }; /** @@ -80896,10 +81696,10 @@ _$plot_api_573.addFrames = function(gd, frameList, indices) { * @param {array of integers} frameList * list of integer indices of frames to be deleted */ -_$plot_api_573.deleteFrames = function(gd, frameList) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.deleteFrames = function(gd, frameList) { + gd = _$lib_601.getGraphDiv(gd); - if(!_$lib_539.isPlotDiv(gd)) { + if(!_$lib_601.isPlotDiv(gd)) { throw new Error('This element is not a Plotly plot: ' + gd); } @@ -80924,14 +81724,14 @@ _$plot_api_573.deleteFrames = function(gd, frameList) { revops.unshift({type: 'insert', index: idx, value: _frames[idx]}); } - var undoFunc = _$plots_647.modifyFrames, - redoFunc = _$plots_647.modifyFrames, + var undoFunc = _$plots_709.modifyFrames, + redoFunc = _$plots_709.modifyFrames, undoArgs = [gd, revops], redoArgs = [gd, ops]; - if(_$queue_553) _$queue_553.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + if(_$queue_616) _$queue_616.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return _$plots_647.modifyFrames(gd, ops); + return _$plots_709.modifyFrames(gd, ops); }; /** @@ -80940,20 +81740,21 @@ _$plot_api_573.deleteFrames = function(gd, frameList) { * @param {string id or DOM element} gd * the id or DOM element of the graph container div */ -_$plot_api_573.purge = function purge(gd) { - gd = _$lib_539.getGraphDiv(gd); +_$plot_api_636.purge = function purge(gd) { + gd = _$lib_601.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}, - fullData = gd._fullData || []; + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + var calcdata = gd.calcdata || []; // remove gl contexts - _$plots_647.cleanPlot([], {}, fullData, fullLayout); + _$plots_709.cleanPlot([], {}, fullData, fullLayout, calcdata); // purge properties - _$plots_647.purge(gd); + _$plots_709.purge(gd); // purge event emitter methods - _$Events_527.purge(gd); + _$Events_589.purge(gd); // remove plot container if(fullLayout._container) fullLayout._container.remove(); @@ -80968,7 +81769,7 @@ _$plot_api_573.purge = function purge(gd) { // makePlotFramework: Create the plot container and axes // ------------------------------------------------------- function makePlotFramework(gd) { - var gd3 = _$d3_127.select(gd); + var gd3 = _$d3_130.select(gd); var fullLayout = gd._fullLayout; // Plot container @@ -81008,14 +81809,14 @@ function makePlotFramework(gd) { if(!fullLayout._uid) { var otherUids = []; - _$d3_127.selectAll('defs').each(function() { + _$d3_130.selectAll('defs').each(function() { if(this.id) otherUids.push(this.id.split('-')[1]); }); - fullLayout._uid = _$lib_539.randstr(otherUids); + fullLayout._uid = _$lib_601.randstr(otherUids); } fullLayout._paperdiv.selectAll('.main-svg') - .attr(_$xmlns_namespaces_519.svgAttrs); + .attr(_$xmlns_namespaces_580.svgAttrs); fullLayout._defs = fullLayout._paper.append('defs') .attr('id', 'defs-' + fullLayout._uid); @@ -81087,7 +81888,7 @@ function makePlotFramework(gd) { gd.emit('plotly_framework'); } -var _$helpers_672 = {}; +var _$helpers_735 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -81099,7 +81900,7 @@ var _$helpers_672 = {}; 'use strict'; -_$helpers_672.getDelay = function(fullLayout) { +_$helpers_735.getDelay = function(fullLayout) { if(!fullLayout._has) return 0; return ( @@ -81109,7 +81910,7 @@ _$helpers_672.getDelay = function(fullLayout) { ) ? 500 : 0; }; -_$helpers_672.getRedrawFunc = function(gd) { +_$helpers_735.getRedrawFunc = function(gd) { var fullLayout = gd._fullLayout || {}; var hasPolar = fullLayout._has && fullLayout._has('polar'); var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r; @@ -81134,11 +81935,11 @@ _$helpers_672.getRedrawFunc = function(gd) { 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -var __EventEmitter_674 = _$EventEmitter_137.EventEmitter; +/* removed: var _$lib_601 = require('../lib'); */; +var __EventEmitter_737 = _$EventEmitter_194.EventEmitter; function svgToImg(opts) { - var ev = opts.emitter || new __EventEmitter_674(); + var ev = opts.emitter || new __EventEmitter_737(); var promise = new Promise(function(resolve, reject) { var Image = window.Image; @@ -81146,7 +81947,7 @@ function svgToImg(opts) { var format = opts.format || 'png'; // IE only support svg - if(_$lib_539.isIE() && format !== 'svg') { + if(_$lib_601.isIE() && format !== 'svg') { var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'); reject(ieSvgError); // eventually remove the ev @@ -81237,7 +82038,7 @@ function svgToImg(opts) { return ev; } -var _$svgToImg_674 = svgToImg; +var _$svgToImg_737 = svgToImg; /** * Copyright 2012-2018, Plotly, Inc. @@ -81250,19 +82051,19 @@ var _$svgToImg_674 = svgToImg; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$drawing_436 = require('../components/drawing'); */; -/* removed: var _$color_411 = require('../components/color'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$drawing_498 = require('../components/drawing'); */; +/* removed: var _$color_473 = require('../components/color'); */; -/* removed: var _$xmlns_namespaces_519 = require('../constants/xmlns_namespaces'); */; +/* removed: var _$xmlns_namespaces_580 = require('../constants/xmlns_namespaces'); */; var DOUBLEQUOTE_REGEX = /"/g; var DUMMY_SUB = 'TOBESTRIPPED'; var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g'); function htmlEntityDecode(s) { - var hiddenDiv = _$d3_127.select('body').append('div').style({display: 'none'}).html(''); + var hiddenDiv = _$d3_130.select('body').append('div').style({display: 'none'}).html(''); var replaced = s.replace(/(&[^;]*;)/gi, function(d) { if(d === '<') { return '<'; } // special handling for brackets if(d === '&rt;') { return '>'; } @@ -81277,7 +82078,7 @@ function xmlEntityEncode(str) { return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&'); } -var _$toSVG_676 = function toSVG(gd, format, scale) { +var _$toSVG_739 = function toSVG(gd, format, scale) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var toppaper = fullLayout._toppaper; @@ -81291,8 +82092,8 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { // have to remove them, and providing the right namespaces in the svg to // begin with svg.insert('rect', ':first-child') - .call(_$drawing_436.setRect, 0, 0, width, height) - .call(_$color_411.fill, fullLayout.paper_bgcolor); + .call(_$drawing_498.setRect, 0, 0, width, height) + .call(_$color_473.fill, fullLayout.paper_bgcolor); // subplot-specific to-SVG methods // which notably add the contents of the gl-container @@ -81332,7 +82133,7 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { svg.selectAll('text') .attr({'data-unformatted': null, 'data-math': null}) .each(function() { - var txt = _$d3_127.select(this); + var txt = _$d3_130.select(this); // hidden text is pre-formatting mathjax, the browser ignores it // but in a static plot it's useless and it can confuse batik @@ -81358,7 +82159,7 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { }); svg.selectAll('.point,.scatterpts').each(function() { - var pt = _$d3_127.select(this); + var pt = _$d3_130.select(this); var fill = this.style.fill; // similar to font family styles above, @@ -81377,8 +82178,8 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { // fix for IE namespacing quirk? // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie - svg.node().setAttributeNS(_$xmlns_namespaces_519.xmlns, 'xmlns', _$xmlns_namespaces_519.svg); - svg.node().setAttributeNS(_$xmlns_namespaces_519.xmlns, 'xmlns:xlink', _$xmlns_namespaces_519.xlink); + svg.node().setAttributeNS(_$xmlns_namespaces_580.xmlns, 'xmlns', _$xmlns_namespaces_580.svg); + svg.node().setAttributeNS(_$xmlns_namespaces_580.xmlns, 'xmlns:xlink', _$xmlns_namespaces_580.xlink); if(format === 'svg' && scale) { svg.attr('width', scale * width); @@ -81400,7 +82201,7 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { // see https://github.com/kangax/fabric.js/issues/1957 // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10 // Leave here just in case the CORS/tainted IE issue gets resolved - if(_$lib_539.isIE()) { + if(_$lib_601.isIE()) { // replace double quote with single quote s = s.replace(/"/gi, '\''); // url in svg are single quoted @@ -81425,14 +82226,14 @@ var _$toSVG_676 = function toSVG(gd, format, scale) { 'use strict'; -/* removed: var _$plot_api_573 = require('./plot_api'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$plot_api_636 = require('./plot_api'); */; +/* removed: var _$lib_601 = require('../lib'); */; -/* removed: var _$helpers_672 = require('../snapshot/helpers'); */; -/* removed: var _$toSVG_676 = require('../snapshot/tosvg'); */; -/* removed: var _$svgToImg_674 = require('../snapshot/svgtoimg'); */; +/* removed: var _$helpers_735 = require('../snapshot/helpers'); */; +/* removed: var _$toSVG_739 = require('../snapshot/tosvg'); */; +/* removed: var _$svgToImg_737 = require('../snapshot/svgtoimg'); */; -var __attrs_577 = { +var __attrs_640 = { format: { valType: 'enumerated', values: ['png', 'jpeg', 'webp', 'svg'], @@ -81485,19 +82286,19 @@ function toImage(gd, opts) { var layout; var config; - if(_$lib_539.isPlainObject(gd)) { + if(_$lib_601.isPlainObject(gd)) { data = gd.data || []; layout = gd.layout || {}; config = gd.config || {}; } else { - gd = _$lib_539.getGraphDiv(gd); - data = _$lib_539.extendDeep([], gd.data); - layout = _$lib_539.extendDeep({}, gd.layout); + gd = _$lib_601.getGraphDiv(gd); + data = _$lib_601.extendDeep([], gd.data); + layout = _$lib_601.extendDeep({}, gd.layout); config = gd._context; } function isImpliedOrValid(attr) { - return !(attr in opts) || _$lib_539.validate(opts[attr], __attrs_577[attr]); + return !(attr in opts) || _$lib_601.validate(opts[attr], __attrs_640[attr]); } if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) { @@ -81511,7 +82312,7 @@ function toImage(gd, opts) { var fullOpts = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(opts, fullOpts, __attrs_577, attr, dflt); + return _$lib_601.coerce(opts, fullOpts, __attrs_640, attr, dflt); } var format = coerce('format'); @@ -81528,31 +82329,31 @@ function toImage(gd, opts) { document.body.appendChild(clonedGd); // extend layout with image options - var layoutImage = _$lib_539.extendFlat({}, layout); + var layoutImage = _$lib_601.extendFlat({}, layout); if(width) layoutImage.width = width; if(height) layoutImage.height = height; // extend config for static plot - var configImage = _$lib_539.extendFlat({}, config, { + var configImage = _$lib_601.extendFlat({}, config, { staticPlot: true, setBackground: setBackground }); - var redrawFunc = _$helpers_672.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_735.getRedrawFunc(clonedGd); function wait() { return new Promise(function(resolve) { - setTimeout(resolve, _$helpers_672.getDelay(clonedGd._fullLayout)); + setTimeout(resolve, _$helpers_735.getDelay(clonedGd._fullLayout)); }); } function convert() { return new Promise(function(resolve, reject) { - var svg = _$toSVG_676(clonedGd, format, scale); + var svg = _$toSVG_739(clonedGd, format, scale); var width = clonedGd._fullLayout.width; var height = clonedGd._fullLayout.height; - _$plot_api_573.purge(clonedGd); + _$plot_api_636.purge(clonedGd); document.body.removeChild(clonedGd); if(format === 'svg') { @@ -81564,9 +82365,9 @@ function toImage(gd, opts) { } var canvas = document.createElement('canvas'); - canvas.id = _$lib_539.randstr(); + canvas.id = _$lib_601.randstr(); - _$svgToImg_674({ + _$svgToImg_737({ format: format, width: width, height: height, @@ -81593,7 +82394,7 @@ function toImage(gd, opts) { } return new Promise(function(resolve, reject) { - _$plot_api_573.plot(clonedGd, data, layoutImage, configImage) + _$plot_api_636.plot(clonedGd, data, layoutImage, configImage) .then(redrawFunc) .then(wait) .then(convert) @@ -81602,7 +82403,7 @@ function toImage(gd, opts) { }); } -var _$toImage_577 = toImage; +var _$toImage_640 = toImage; /** * Copyright 2012-2018, Plotly, Inc. @@ -81614,14 +82415,14 @@ var _$toImage_577 = toImage; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -/* removed: var _$plot_schema_575 = require('./plot_schema'); */; -/* removed: var _$plot_config_574 = require('./plot_config'); */; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +/* removed: var _$plot_schema_638 = require('./plot_schema'); */; +/* removed: var _$plot_config_637 = require('./plot_config'); */; -var __isPlainObject_578 = _$lib_539.isPlainObject; -var __isArray_578 = Array.isArray; -var __isArrayOrTypedArray_578 = _$lib_539.isArrayOrTypedArray; +var __isPlainObject_641 = _$lib_601.isPlainObject; +var __isArray_641 = Array.isArray; +var __isArrayOrTypedArray_641 = _$lib_601.isArrayOrTypedArray; /** * Validate a data array and layout object. @@ -81644,15 +82445,15 @@ var __isArrayOrTypedArray_578 = _$lib_539.isArrayOrTypedArray; * - {string} msg * error message (shown in console in logger config argument is enable) */ -var _$valiate_578 = function valiate(data, layout) { - var schema = _$plot_schema_575.get(); +var _$valiate_641 = function valiate(data, layout) { + var schema = _$plot_schema_638.get(); var errorList = []; - var gd = {_context: _$lib_539.extendFlat({}, _$plot_config_574)}; + var gd = {_context: _$lib_601.extendFlat({}, _$plot_config_637)}; var dataIn, layoutIn; - if(__isArray_578(data)) { - gd.data = _$lib_539.extendDeep([], data); + if(__isArray_641(data)) { + gd.data = _$lib_601.extendDeep([], data); dataIn = data; } else { @@ -81661,8 +82462,8 @@ var _$valiate_578 = function valiate(data, layout) { errorList.push(format('array', 'data')); } - if(__isPlainObject_578(layout)) { - gd.layout = _$lib_539.extendDeep({}, layout); + if(__isPlainObject_641(layout)) { + gd.layout = _$lib_601.extendDeep({}, layout); layoutIn = layout; } else { @@ -81677,7 +82478,7 @@ var _$valiate_578 = function valiate(data, layout) { // gd.data and gd.layout after supplyDefaults as some attributes // in gd.data and gd.layout (still) get mutated during this step. - _$plots_647.supplyDefaults(gd); + _$plots_709.supplyDefaults(gd); var dataOut = gd._fullData, len = dataIn.length; @@ -81686,7 +82487,7 @@ var _$valiate_578 = function valiate(data, layout) { var traceIn = dataIn[i], base = ['data', i]; - if(!__isPlainObject_578(traceIn)) { + if(!__isPlainObject_641(traceIn)) { errorList.push(format('object', base)); continue; } @@ -81706,13 +82507,13 @@ var _$valiate_578 = function valiate(data, layout) { errorList.push(format('invisible', base)); } - __crawl_578(traceIn, traceOut, traceSchema, errorList, base); + __crawl_641(traceIn, traceOut, traceSchema, errorList, base); var transformsIn = traceIn.transforms, transformsOut = traceOut.transforms; if(transformsIn) { - if(!__isArray_578(transformsIn)) { + if(!__isArray_641(transformsIn)) { errorList.push(format('array', base, ['transforms'])); } @@ -81722,7 +82523,7 @@ var _$valiate_578 = function valiate(data, layout) { var path = ['transforms', j], transformType = transformsIn[j].type; - if(!__isPlainObject_578(transformsIn[j])) { + if(!__isPlainObject_641(transformsIn[j])) { errorList.push(format('object', base, path)); continue; } @@ -81737,7 +82538,7 @@ var _$valiate_578 = function valiate(data, layout) { values: Object.keys(schema.transforms) }; - __crawl_578(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + __crawl_641(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); } } } @@ -81745,13 +82546,13 @@ var _$valiate_578 = function valiate(data, layout) { var layoutOut = gd._fullLayout, layoutSchema = fillLayoutSchema(schema, dataOut); - __crawl_578(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); + __crawl_641(layoutIn, layoutOut, layoutSchema, errorList, 'layout'); // return undefined if no validation errors were found return (errorList.length === 0) ? void(0) : errorList; }; -function __crawl_578(objIn, objOut, schema, list, base, path) { +function __crawl_641(objIn, objOut, schema, list, base, path) { path = path || []; var keys = Object.keys(objIn); @@ -81776,10 +82577,10 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { if(!isInSchema(schema, k)) { list.push(format('schema', base, p)); } - else if(__isPlainObject_578(valIn) && __isPlainObject_578(valOut)) { - __crawl_578(valIn, valOut, nestedSchema, list, base, p); + else if(__isPlainObject_641(valIn) && __isPlainObject_641(valOut)) { + __crawl_641(valIn, valOut, nestedSchema, list, base, p); } - else if(isInfoArray && __isArray_578(valIn)) { + else if(isInfoArray && __isArray_641(valIn)) { if(valIn.length > valOut.length) { list.push(format('unused', base, p.concat(valOut.length))); } @@ -81789,7 +82590,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { var m, n, item, valInPart, valOutPart; if(nestedSchema.dimensions === 2) { for(n = 0; n < len; n++) { - if(__isArray_578(valIn[n])) { + if(__isArray_641(valIn[n])) { if(valIn[n].length > valOut[n].length) { list.push(format('unused', base, p.concat(n, valOut[n].length))); } @@ -81798,7 +82599,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n][m] : items; valInPart = valIn[n][m]; valOutPart = valOut[n][m]; - if(!_$lib_539.validate(valInPart, item)) { + if(!_$lib_601.validate(valInPart, item)) { list.push(format('value', base, p.concat(n, m), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -81816,7 +82617,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { item = arrayItems ? items[n] : items; valInPart = valIn[n]; valOutPart = valOut[n]; - if(!_$lib_539.validate(valInPart, item)) { + if(!_$lib_601.validate(valInPart, item)) { list.push(format('value', base, p.concat(n), valInPart)); } else if(valOutPart !== valInPart && valOutPart !== +valInPart) { @@ -81825,7 +82626,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { } } } - else if(nestedSchema.items && !isInfoArray && __isArray_578(valIn)) { + else if(nestedSchema.items && !isInfoArray && __isArray_641(valIn)) { var _nestedSchema = items[Object.keys(items)[0]], indexList = []; @@ -81839,9 +82640,9 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(_index); - if(__isPlainObject_578(valIn[_index]) && __isPlainObject_578(valOut[j])) { + if(__isPlainObject_641(valIn[_index]) && __isPlainObject_641(valOut[j])) { indexList.push(_index); - __crawl_578(valIn[_index], valOut[j], _nestedSchema, list, base, _p); + __crawl_641(valIn[_index], valOut[j], _nestedSchema, list, base, _p); } } @@ -81850,7 +82651,7 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { _p = p.slice(); _p.push(j); - if(!__isPlainObject_578(valIn[j])) { + if(!__isPlainObject_641(valIn[j])) { list.push(format('object', base, _p, valIn[j])); } else if(indexList.indexOf(j) === -1) { @@ -81858,16 +82659,16 @@ function __crawl_578(objIn, objOut, schema, list, base, path) { } } } - else if(!__isPlainObject_578(valIn) && __isPlainObject_578(valOut)) { + else if(!__isPlainObject_641(valIn) && __isPlainObject_641(valOut)) { list.push(format('object', base, p, valIn)); } - else if(!__isArrayOrTypedArray_578(valIn) && __isArrayOrTypedArray_578(valOut) && !isInfoArray && !isColorscale) { + else if(!__isArrayOrTypedArray_641(valIn) && __isArrayOrTypedArray_641(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_539.validate(valIn, nestedSchema)) { + else if(!_$lib_601.validate(valIn, nestedSchema)) { list.push(format('value', base, p, valIn)); } else if(nestedSchema.valType === 'enumerated' && @@ -81887,7 +82688,7 @@ function fillLayoutSchema(schema, dataOut) { traceLayoutAttr = schema.traces[traceType].layoutAttributes; if(traceLayoutAttr) { - _$lib_539.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); + _$lib_601.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr); } } @@ -81919,7 +82720,7 @@ var code2msgFunc = { return inBase(base) + 'key ' + astr + ' is not part of the schema'; }, unused: function(base, astr, valIn) { - var target = __isPlainObject_578(valIn) ? 'container' : 'key'; + var target = __isPlainObject_641(valIn) ? 'container' : 'key'; return inBase(base) + target + ' ' + astr + ' did not get coerced'; }, @@ -81945,7 +82746,7 @@ var code2msgFunc = { }; function inBase(base) { - if(__isArray_578(base)) return 'In data trace ' + base[1] + ', '; + if(__isArray_641(base)) return 'In data trace ' + base[1] + ', '; return 'In ' + base + ', '; } @@ -81958,7 +82759,7 @@ function format(code, base, path, valIn, valOut) { // container is either 'data' or 'layout // trace is the trace index if 'data', null otherwise - if(__isArray_578(base)) { + if(__isArray_641(base)) { container = base[0]; trace = base[1]; } @@ -81971,7 +82772,7 @@ function format(code, base, path, valIn, valOut) { var msg = code2msgFunc[code](base, astr, valIn, valOut); // log to console if logger config option is enabled - _$lib_539.log(msg); + _$lib_601.log(msg); return { code: code, @@ -82001,7 +82802,7 @@ function getNestedSchema(schema, key) { return schema[parts.keyMinusId]; } -var idRegex = _$lib_539.counterRegex('([a-z]+)'); +var idRegex = _$lib_601.counterRegex('([a-z]+)'); function splitKey(key) { var idMatch = key.match(idRegex); @@ -82013,7 +82814,7 @@ function splitKey(key) { } function convertPathToAttributeString(path) { - if(!__isArray_578(path)) return String(path); + if(!__isArray_641(path)) return String(path); var astr = ''; @@ -82102,7 +82903,7 @@ var fileSaver = function(url, name) { return promise; }; -var _$fileSaver_671 = fileSaver; +var _$fileSaver_734 = fileSaver; /** * Copyright 2012-2018, Plotly, Inc. @@ -82115,9 +82916,9 @@ var _$fileSaver_671 = fileSaver; 'use strict'; -/* removed: var _$toImage_577 = require('../plot_api/to_image'); */; -/* removed: var _$lib_539 = require('../lib'); */; // for isIE -/* removed: var _$fileSaver_671 = require('./filesaver'); */; +/* removed: var _$toImage_640 = require('../plot_api/to_image'); */; +/* removed: var _$lib_601 = require('../lib'); */; // for isIE +/* removed: var _$fileSaver_734 = require('./filesaver'); */; /** * @param {object} gd figure Object @@ -82145,19 +82946,19 @@ function downloadImage(gd, opts) { // can now draw to canvas, but CORS tainted canvas // does not allow toDataURL // svg format will work though - if(_$lib_539.isIE() && opts.format !== 'svg') { + if(_$lib_601.isIE() && opts.format !== 'svg') { reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.')); } gd._snapshotInProgress = true; - var promise = _$toImage_577(gd, opts); + var promise = _$toImage_640(gd, opts); var filename = opts.filename || gd.fn || 'newplot'; filename += '.' + opts.format; promise.then(function(result) { gd._snapshotInProgress = false; - return _$fileSaver_671(result, filename); + return _$fileSaver_734(result, filename); }).then(function(name) { resolve(name); }).catch(function(err) { @@ -82167,9 +82968,9 @@ function downloadImage(gd, opts) { }); } -var _$downloadImage_670 = downloadImage; +var _$downloadImage_733 = downloadImage; -var _$plot_api_571 = {}; +var _$plot_api_634 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -82180,29 +82981,29 @@ var _$plot_api_571 = {}; 'use strict'; -/* removed: var _$plot_api_573 = require('./plot_api'); */; +/* removed: var _$plot_api_636 = require('./plot_api'); */; -_$plot_api_571.plot = _$plot_api_573.plot; -_$plot_api_571.newPlot = _$plot_api_573.newPlot; -_$plot_api_571.restyle = _$plot_api_573.restyle; -_$plot_api_571.relayout = _$plot_api_573.relayout; -_$plot_api_571.redraw = _$plot_api_573.redraw; -_$plot_api_571.update = _$plot_api_573.update; -_$plot_api_571.react = _$plot_api_573.react; -_$plot_api_571.extendTraces = _$plot_api_573.extendTraces; -_$plot_api_571.prependTraces = _$plot_api_573.prependTraces; -_$plot_api_571.addTraces = _$plot_api_573.addTraces; -_$plot_api_571.deleteTraces = _$plot_api_573.deleteTraces; -_$plot_api_571.moveTraces = _$plot_api_573.moveTraces; -_$plot_api_571.purge = _$plot_api_573.purge; -_$plot_api_571.addFrames = _$plot_api_573.addFrames; -_$plot_api_571.deleteFrames = _$plot_api_573.deleteFrames; -_$plot_api_571.animate = _$plot_api_573.animate; -_$plot_api_571.setPlotConfig = _$plot_api_573.setPlotConfig; +_$plot_api_634.plot = _$plot_api_636.plot; +_$plot_api_634.newPlot = _$plot_api_636.newPlot; +_$plot_api_634.restyle = _$plot_api_636.restyle; +_$plot_api_634.relayout = _$plot_api_636.relayout; +_$plot_api_634.redraw = _$plot_api_636.redraw; +_$plot_api_634.update = _$plot_api_636.update; +_$plot_api_634.react = _$plot_api_636.react; +_$plot_api_634.extendTraces = _$plot_api_636.extendTraces; +_$plot_api_634.prependTraces = _$plot_api_636.prependTraces; +_$plot_api_634.addTraces = _$plot_api_636.addTraces; +_$plot_api_634.deleteTraces = _$plot_api_636.deleteTraces; +_$plot_api_634.moveTraces = _$plot_api_636.moveTraces; +_$plot_api_634.purge = _$plot_api_636.purge; +_$plot_api_634.addFrames = _$plot_api_636.addFrames; +_$plot_api_634.deleteFrames = _$plot_api_636.deleteFrames; +_$plot_api_634.animate = _$plot_api_636.animate; +_$plot_api_634.setPlotConfig = _$plot_api_636.setPlotConfig; -_$plot_api_571.toImage = _$toImage_577; -_$plot_api_571.validate = _$valiate_578; -_$plot_api_571.downloadImage = _$downloadImage_670; +_$plot_api_634.toImage = _$toImage_640; +_$plot_api_634.validate = _$valiate_641; +_$plot_api_634.downloadImage = _$downloadImage_733; /** * Copyright 2012-2018, Plotly, Inc. @@ -82215,10 +83016,10 @@ _$plot_api_571.downloadImage = _$downloadImage_670; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$lib_601 = require('../lib'); */; -var __extendFlat_669 = _$lib_539.extendFlat; -var extendDeep = _$lib_539.extendDeep; +var __extendFlat_732 = _$lib_601.extendFlat; +var extendDeep = _$lib_601.extendDeep; // Put default plotTile layouts here function cloneLayoutOverride(tileClass) { @@ -82263,7 +83064,7 @@ function keyIsAxis(keyName) { } -var _$clonePlot_669 = function clonePlot(graphObj, options) { +var _$clonePlot_732 = function clonePlot(graphObj, options) { // Polar plot compatibility if(graphObj.framework && graphObj.framework.isPolar) { @@ -82336,9 +83137,9 @@ var _$clonePlot_669 = function clonePlot(graphObj, options) { scene.zaxis = {}; } - __extendFlat_669(scene.xaxis, axesImageOverride); - __extendFlat_669(scene.yaxis, axesImageOverride); - __extendFlat_669(scene.zaxis, axesImageOverride); + __extendFlat_732(scene.xaxis, axesImageOverride); + __extendFlat_732(scene.yaxis, axesImageOverride); + __extendFlat_732(scene.zaxis, axesImageOverride); // TODO what does this do? scene._scene = null; @@ -82387,27 +83188,27 @@ var _$clonePlot_669 = function clonePlot(graphObj, options) { 'use strict'; -var __EventEmitter_675 = _$EventEmitter_137.EventEmitter; +var __EventEmitter_738 = _$EventEmitter_194.EventEmitter; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$lib_539 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$lib_601 = require('../lib'); */; -/* removed: var _$helpers_672 = require('./helpers'); */; -/* removed: var _$clonePlot_669 = require('./cloneplot'); */; -/* removed: var _$toSVG_676 = require('./tosvg'); */; -/* removed: var _$svgToImg_674 = require('./svgtoimg'); */; +/* removed: var _$helpers_735 = require('./helpers'); */; +/* removed: var _$clonePlot_732 = require('./cloneplot'); */; +/* removed: var _$toSVG_739 = require('./tosvg'); */; +/* removed: var _$svgToImg_737 = require('./svgtoimg'); */; /** * @param {object} gd figure Object * @param {object} opts option object * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg' */ -function __toImage_675(gd, opts) { +function __toImage_738(gd, opts) { // first clone the GD so we can operate in a clean environment - var ev = new __EventEmitter_675(); + var ev = new __EventEmitter_738(); - var clone = _$clonePlot_669(gd, {format: 'png'}); + var clone = _$clonePlot_732(gd, {format: 'png'}); var clonedGd = clone.gd; // put the cloned div somewhere off screen before attaching to DOM @@ -82416,15 +83217,15 @@ function __toImage_675(gd, opts) { document.body.appendChild(clonedGd); function wait() { - var delay = _$helpers_672.getDelay(clonedGd._fullLayout); + var delay = _$helpers_735.getDelay(clonedGd._fullLayout); setTimeout(function() { - var svg = _$toSVG_676(clonedGd); + var svg = _$toSVG_739(clonedGd); var canvas = document.createElement('canvas'); - canvas.id = _$lib_539.randstr(); + canvas.id = _$lib_601.randstr(); - ev = _$svgToImg_674({ + ev = _$svgToImg_737({ format: opts.format, width: clonedGd._fullLayout.width, height: clonedGd._fullLayout.height, @@ -82440,9 +83241,9 @@ function __toImage_675(gd, opts) { }, delay); } - var redrawFunc = _$helpers_672.getRedrawFunc(clonedGd); + var redrawFunc = _$helpers_735.getRedrawFunc(clonedGd); - _$registry_668.call('plot', clonedGd, clone.data, clone.layout, clone.config) + _$registry_731.call('plot', clonedGd, clone.data, clone.layout, clone.config) .then(redrawFunc) .then(wait) .catch(function(err) { @@ -82453,7 +83254,7 @@ function __toImage_675(gd, opts) { return ev; } -var _$toImage_675 = __toImage_675; +var _$toImage_738 = __toImage_738; /** * Copyright 2012-2018, Plotly, Inc. @@ -82466,19 +83267,19 @@ var _$toImage_675 = __toImage_675; 'use strict'; -/* removed: var _$helpers_672 = require('./helpers'); */; +/* removed: var _$helpers_735 = require('./helpers'); */; var Snapshot = { - getDelay: _$helpers_672.getDelay, - getRedrawFunc: _$helpers_672.getRedrawFunc, - clone: _$clonePlot_669, - toSVG: _$toSVG_676, - svgToImg: _$svgToImg_674, - toImage: _$toImage_675, - downloadImage: _$downloadImage_670 + getDelay: _$helpers_735.getDelay, + getRedrawFunc: _$helpers_735.getRedrawFunc, + clone: _$clonePlot_732, + toSVG: _$toSVG_739, + svgToImg: _$svgToImg_737, + toImage: _$toImage_738, + downloadImage: _$downloadImage_733 }; -var _$Snapshot_673 = Snapshot; +var _$Snapshot_736 = Snapshot; /** * Copyright 2012-2018, Plotly, Inc. @@ -82491,23 +83292,23 @@ var _$Snapshot_673 = Snapshot; 'use strict'; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; -var _$calcMarkerColorscale_867 = function calcMarkerColorscale(trace) { - if(_$subtypes_884.hasLines(trace) && _$hasColorscale_425(trace, 'line')) { - _$calc_418(trace, trace.line.color, 'line', 'c'); +var _$calcMarkerColorscale_932 = function calcMarkerColorscale(trace) { + if(_$subtypes_949.hasLines(trace) && _$hasColorscale_487(trace, 'line')) { + _$calc_480(trace, trace.line.color, 'line', 'c'); } - if(_$subtypes_884.hasMarkers(trace)) { - if(_$hasColorscale_425(trace, 'marker')) { - _$calc_418(trace, trace.marker.color, 'marker', 'c'); + if(_$subtypes_949.hasMarkers(trace)) { + if(_$hasColorscale_487(trace, 'marker')) { + _$calc_480(trace, trace.marker.color, 'marker', 'c'); } - if(_$hasColorscale_425(trace, 'marker.line')) { - _$calc_418(trace, trace.marker.line.color, 'marker.line', 'c'); + if(_$hasColorscale_487(trace, 'marker.line')) { + _$calc_480(trace, trace.marker.line.color, 'marker.line', 'c'); } } }; @@ -82522,20 +83323,20 @@ var _$calcMarkerColorscale_867 = function calcMarkerColorscale(trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_863 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_928 = _$lib_601.isArrayOrTypedArray; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __BADNUM_863 = _$numerical_517.BADNUM; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __BADNUM_928 = _$numerical_578.BADNUM; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -/* removed: var _$calcMarkerColorscale_867 = require('./colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('./arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('./calc_selection'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +/* removed: var _$calcMarkerColorscale_932 = require('./colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('./arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('./calc_selection'); */; -function __calc_863(gd, trace) { - var xa = _$axes_584.getFromId(gd, trace.xaxis || 'x'); - var ya = _$axes_584.getFromId(gd, trace.yaxis || 'y'); +function __calc_928(gd, trace) { + var xa = _$axes_647.getFromId(gd, trace.xaxis || 'x'); + var ya = _$axes_647.getFromId(gd, trace.yaxis || 'y'); var x = xa.makeCalcdata(trace, 'x'); var y = ya.makeCalcdata(trace, 'y'); var serieslen = trace._length; @@ -82545,18 +83346,18 @@ function __calc_863(gd, trace) { calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); for(var i = 0; i < serieslen; i++) { - cd[i] = (_$fastIsnumeric_139(x[i]) && _$fastIsnumeric_139(y[i])) ? + cd[i] = (_$fastIsnumeric_196(x[i]) && _$fastIsnumeric_196(y[i])) ? {x: x[i], y: y[i]} : - {x: __BADNUM_863, y: __BADNUM_863}; + {x: __BADNUM_928, y: __BADNUM_928}; if(trace.ids) { cd[i].id = String(trace.ids[i]); } } - _$arraysToCalcdata_861(cd, trace); - _$calcMarkerColorscale_867(trace); - _$calcSelection_864(cd, trace); + _$arraysToCalcdata_926(cd, trace); + _$calcMarkerColorscale_932(trace); + _$calcSelection_929(cd, trace); gd.firstscatter = false; return cd; @@ -82589,9 +83390,9 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { } // if no error bars, markers or text, or fill to y=0 remove x padding - else if(!trace.error_y.visible && ( + else if(!(trace.error_y || {}).visible && ( ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 || - (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)) + (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)) )) { xOptions.padded = false; xOptions.ppad = 0; @@ -82610,12 +83411,12 @@ function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) { yOptions.padded = false; } - _$axes_584.expand(xa, x, xOptions); - _$axes_584.expand(ya, y, yOptions); + _$axes_647.expand(xa, x, xOptions); + _$axes_647.expand(ya, y, yOptions); } function calcMarkerSize(trace, serieslen) { - if(!_$subtypes_884.hasMarkers(trace)) return; + if(!_$subtypes_949.hasMarkers(trace)) return; // Treat size like x or y arrays --- Run d2c // this needs to go before ppad computation @@ -82633,10 +83434,10 @@ function calcMarkerSize(trace, serieslen) { }; } - if(__isArrayOrTypedArray_863(marker.size)) { + if(__isArrayOrTypedArray_928(marker.size)) { // I tried auto-type but category and dates dont make much sense. var ax = {type: 'linear'}; - _$axes_584.setConvert(ax); + _$axes_647.setConvert(ax); var s = ax.makeCalcdata(trace.marker, 'size'); @@ -82651,8 +83452,8 @@ function calcMarkerSize(trace, serieslen) { } } -var _$calc_863 = { - calc: __calc_863, +var _$calc_928 = { + calc: __calc_928, calcMarkerSize: calcMarkerSize, calcAxisExpansion: calcAxisExpansion }; @@ -82670,7 +83471,7 @@ var _$calc_863 = { // remove opacity for any trace that has a fill or is filled to -var _$cleanData_865 = function cleanData(fullData) { +var _$cleanData_930 = function cleanData(fullData) { for(var i = 0; i < fullData.length; i++) { var tracei = fullData[i]; if(tracei.type !== 'scatter') continue; @@ -82706,10 +83507,10 @@ var _$cleanData_865 = function cleanData(fullData) { 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -var __isArrayOrTypedArray_871 = _$lib_539.isArrayOrTypedArray; +/* removed: var _$color_473 = require('../../components/color'); */; +var __isArrayOrTypedArray_936 = _$lib_601.isArrayOrTypedArray; -var _$fillColorDefaults_871 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { +var _$fillColorDefaults_936 = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) { var inheritColorFromMarker = false; if(traceOut.marker) { @@ -82717,15 +83518,15 @@ var _$fillColorDefaults_871 = function fillColorDefaults(traceIn, traceOut, defa var markerColor = traceOut.marker.color, markerLineColor = (traceOut.marker.line || {}).color; - if(markerColor && !__isArrayOrTypedArray_871(markerColor)) { + if(markerColor && !__isArrayOrTypedArray_936(markerColor)) { inheritColorFromMarker = markerColor; } - else if(markerLineColor && !__isArrayOrTypedArray_871(markerLineColor)) { + else if(markerLineColor && !__isArrayOrTypedArray_936(markerLineColor)) { inheritColorFromMarker = markerLineColor; } } - coerce('fillcolor', _$color_411.addOpacity( + coerce('fillcolor', _$color_473.addOpacity( (traceOut.line || {}).color || inheritColorFromMarker || defaultColor, 0.5 @@ -82742,20 +83543,20 @@ var _$fillColorDefaults_871 = function fillColorDefaults(traceIn, traceOut, defa 'use strict'; -var __isArrayOrTypedArray_875 = _$lib_539.isArrayOrTypedArray; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; +var __isArrayOrTypedArray_940 = _$lib_601.isArrayOrTypedArray; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; -var _$lineDefaults_875 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { +var _$lineDefaults_940 = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { var markerColor = (traceIn.marker || {}).color; coerce('line.color', defaultColor); - if(_$hasColorscale_425(traceIn, 'line')) { - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); + if(_$hasColorscale_487(traceIn, 'line')) { + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); } else { - var lineColorDflt = (__isArrayOrTypedArray_875(markerColor) ? false : markerColor) || defaultColor; + var lineColorDflt = (__isArrayOrTypedArray_940(markerColor) ? false : markerColor) || defaultColor; coerce('line.color', lineColorDflt); } @@ -82776,7 +83577,7 @@ var _$lineDefaults_875 = function lineDefaults(traceIn, traceOut, defaultColor, // common to 'scatter' and 'scatterternary' -var _$handleLineShapeDefaults_877 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { +var _$handleLineShapeDefaults_942 = function handleLineShapeDefaults(traceIn, traceOut, coerce) { var shape = coerce('line.shape'); if(shape === 'spline') coerce('line.smoothing'); }; @@ -82792,11 +83593,11 @@ var _$handleLineShapeDefaults_877 = function handleLineShapeDefaults(traceIn, tr 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; /* * opts: object of flags to control features not all marker users support @@ -82804,8 +83605,8 @@ var _$handleLineShapeDefaults_877 = function handleLineShapeDefaults(traceIn, tr * gradient: caller supports gradients * noSelect: caller does not support selected/unselected attribute containers */ -var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { - var isBubble = _$subtypes_884.isBubble(traceIn), +var _$markerDefaults_945 = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) { + var isBubble = _$subtypes_949.isBubble(traceIn), lineColor = (traceIn.line || {}).color, defaultMLC; @@ -82819,8 +83620,8 @@ var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultCol coerce('marker.size'); coerce('marker.color', defaultColor); - if(_$hasColorscale_425(traceIn, 'marker')) { - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); + if(_$hasColorscale_487(traceIn, 'marker')) { + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}); } if(!opts.noSelect) { @@ -82838,12 +83639,12 @@ var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultCol if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) { defaultMLC = lineColor; } - else if(isBubble) defaultMLC = _$color_411.background; - else defaultMLC = _$color_411.defaultLine; + else if(isBubble) defaultMLC = _$color_473.background; + else defaultMLC = _$color_473.defaultLine; coerce('marker.line.color', defaultMLC); - if(_$hasColorscale_425(traceIn, 'marker.line')) { - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}); + if(_$hasColorscale_487(traceIn, 'marker.line')) { + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}); } coerce('marker.line.width', isBubble ? 1 : 0); @@ -82874,17 +83675,17 @@ var _$markerDefaults_880 = function markerDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /* * opts: object of flags to control features not all text users support * noSelect: caller does not support selected/unselected attribute containers */ -var _$text_defaults_885 = function(traceIn, traceOut, layout, coerce, opts) { +var _$text_defaults_950 = function(traceIn, traceOut, layout, coerce, opts) { opts = opts || {}; coerce('textposition'); - _$lib_539.coerceFont(coerce, 'textfont', layout.font); + _$lib_601.coerceFont(coerce, 'textfont', layout.font); if(!opts.noSelect) { coerce('selected.textfont.color'); @@ -82902,27 +83703,27 @@ var _$text_defaults_885 = function(traceIn, traceOut, layout, coerce, opts) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -/* removed: var _$attributes_862 = require('./attributes'); */; -/* removed: var _$constants_868 = require('./constants'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -/* removed: var _$handleXYDefaults_886 = require('./xy_defaults'); */; -/* removed: var _$markerDefaults_880 = require('./marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('./line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('./line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('./text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('./fillcolor_defaults'); */; +/* removed: var _$attributes_927 = require('./attributes'); */; +/* removed: var _$constants_933 = require('./constants'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +/* removed: var _$handleXYDefaults_951 = require('./xy_defaults'); */; +/* removed: var _$markerDefaults_945 = require('./marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('./line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('./line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('./text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('./fillcolor_defaults'); */; -var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_934 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_862, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_927, attr, dflt); } - var len = _$handleXYDefaults_886(traceIn, traceOut, layout, coerce), + var len = _$handleXYDefaults_951(traceIn, traceOut, layout, coerce), // TODO: default mode by orphan points... - defaultMode = len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'; + defaultMode = len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'; if(!len) { traceOut.visible = false; return; @@ -82932,24 +83733,24 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode', defaultMode); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); coerce('line.simplify'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -82957,8 +83758,8 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -82966,11 +83767,11 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -82984,18 +83785,18 @@ var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; -var _$getTraceColor_872 = function getTraceColor(trace, di) { +var _$getTraceColor_937 = function getTraceColor(trace, di) { var lc, tc; // TODO: text modes if(trace.mode === 'lines') { lc = trace.line.color; - return (lc && _$color_411.opacity(lc)) ? + return (lc && _$color_473.opacity(lc)) ? lc : trace.fillcolor; } else if(trace.mode === 'none') { @@ -83005,21 +83806,21 @@ var _$getTraceColor_872 = function getTraceColor(trace, di) { var mc = di.mcc || (trace.marker || {}).color, mlc = di.mlcc || ((trace.marker || {}).line || {}).color; - tc = (mc && _$color_411.opacity(mc)) ? mc : - (mlc && _$color_411.opacity(mlc) && + tc = (mc && _$color_473.opacity(mc)) ? mc : + (mlc && _$color_473.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : ''; if(tc) { // make sure the points aren't TOO transparent - if(_$color_411.opacity(tc) < 0.3) { - return _$color_411.addOpacity(tc, 0.3); + if(_$color_473.opacity(tc) < 0.3) { + return _$color_473.addOpacity(tc, 0.3); } else return tc; } else { lc = (trace.line || {}).color; - return (lc && _$color_411.opacity(lc) && - _$subtypes_884.hasLines(trace) && trace.line.width) ? + return (lc && _$color_473.opacity(lc) && + _$subtypes_949.hasLines(trace) && trace.line.width) ? lc : trace.fillcolor; } } @@ -83035,14 +83836,14 @@ var _$getTraceColor_872 = function getTraceColor(trace, di) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$getTraceColor_872 = require('./get_trace_color'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$fillHoverText_870 = require('./fill_hover_text'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$getTraceColor_937 = require('./get_trace_color'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$fillHoverText_935 = require('./fill_hover_text'); */; -var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { +var _$hoverPoints_938 = function hoverPoints(pointData, xval, yval, hovermode) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -83082,9 +83883,9 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { var dy = ya.c2p(di.y) - ypx; return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad); }; - var distfn = _$fx_453.getDistanceFunction(hovermode, dx, dy, dxy); + var distfn = _$fx_515.getDistanceFunction(hovermode, dx, dy, dxy); - _$fx_453.getClosest(cd, distfn, pointData); + _$fx_515.getClosest(cd, distfn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index !== false) { @@ -83095,8 +83896,8 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { var yc = ya.c2p(di.y, true); var rad = di.mrc || 1; - _$lib_539.extendFlat(pointData, { - color: _$getTraceColor_872(trace, di), + _$lib_601.extendFlat(pointData, { + color: _$getTraceColor_937(trace, di), x0: xc - rad, x1: xc + rad, @@ -83109,8 +83910,8 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { spikeDistance: dxy(di) }); - _$fillHoverText_870(di, trace, pointData); - _$registry_668.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_935(di, trace, pointData); + _$registry_731.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); return [pointData]; } @@ -83176,13 +83977,13 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { xmax = Math.min(xmax, xa._length); // get only fill or line color for the hover color - var color = _$color_411.defaultLine; - if(_$color_411.opacity(trace.fillcolor)) color = trace.fillcolor; - else if(_$color_411.opacity((trace.line || {}).color)) { + var color = _$color_473.defaultLine; + if(_$color_473.opacity(trace.fillcolor)) color = trace.fillcolor; + else if(_$color_473.opacity((trace.line || {}).color)) { color = trace.line.color; } - _$lib_539.extendFlat(pointData, { + _$lib_601.extendFlat(pointData, { // never let a 2D override 1D type as closest point // also: no spikeDistance, it's not allowed for fills distance: pointData.maxHoverDistance, @@ -83216,14 +84017,14 @@ var _$hoverPoints_873 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -var __BADNUM_876 = _$numerical_517.BADNUM; -/* removed: var _$lib_539 = require('../../lib'); */; -var __segmentsIntersect_876 = _$lib_539.segmentsIntersect; -var constrain = _$lib_539.constrain; -/* removed: var _$constants_868 = require('./constants'); */; +var __BADNUM_941 = _$numerical_578.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +var __segmentsIntersect_941 = _$lib_601.segmentsIntersect; +var constrain = _$lib_601.constrain; +/* removed: var _$constants_933 = require('./constants'); */; -var _$linePoints_876 = function linePoints(d, opts) { +var _$linePoints_941 = function linePoints(d, opts) { var xa = opts.xaxis; var ya = opts.yaxis; var simplify = opts.simplify; @@ -83232,7 +84033,7 @@ var _$linePoints_876 = function linePoints(d, opts) { var shape = opts.shape; var linear = shape === 'linear'; var segments = []; - var minTolerance = _$constants_868.minTolerance; + var minTolerance = _$constants_933.minTolerance; var pts = new Array(d.length); var pti = 0; @@ -83270,7 +84071,7 @@ var _$linePoints_876 = function linePoints(d, opts) { var di = d[index]; var x = xa.c2p(di.x); var y = ya.c2p(di.y); - if(x === __BADNUM_876 || y === __BADNUM_876) return di.intoCenter || false; + if(x === __BADNUM_941 || y === __BADNUM_941) return di.intoCenter || false; return [x, y]; } @@ -83278,7 +84079,7 @@ var _$linePoints_876 = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length; var yFrac = pt[1] / ya._length; - return (1 + _$constants_868.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + _$constants_933.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -83290,7 +84091,7 @@ var _$linePoints_876 = function linePoints(d, opts) { // last bit of filtering: clip paths that are VERY far off-screen // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF) - var maxScreensAway = _$constants_868.maxScreensAway; + var maxScreensAway = _$constants_933.maxScreensAway; // find the intersections between the segment from pt1 to pt2 // and the large rectangle maxScreensAway around the viewport @@ -83319,7 +84120,7 @@ var _$linePoints_876 = function linePoints(d, opts) { var ptCount = 0; for(var i = 0; i < 4; i++) { var edge = edges[i]; - var ptInt = __segmentsIntersect_876(pt1[0], pt1[1], pt2[0], pt2[1], + var ptInt = __segmentsIntersect_941(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]); if(ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || @@ -83373,7 +84174,7 @@ var _$linePoints_876 = function linePoints(d, opts) { if(ptInt1) out.push(ptInt1); if(ptInt2) out.push(ptInt2); - var midShift = 2 * _$lib_539.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - + var midShift = 2 * _$lib_601.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); if(midShift) { var ptToAlter; @@ -83626,7 +84427,7 @@ var _$linePoints_876 = function linePoints(d, opts) { 'use strict'; -var _$linkTraces_878 = function linkTraces(gd, plotinfo, cdscatter) { +var _$linkTraces_943 = function linkTraces(gd, plotinfo, cdscatter) { var trace, i; var prevtrace = null; @@ -83666,19 +84467,19 @@ var _$linkTraces_878 = function linkTraces(gd, plotinfo, cdscatter) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -/* removed: var _$linePoints_876 = require('./line_points'); */; -/* removed: var _$linkTraces_878 = require('./link_traces'); */; -var __polygonTester_881 = _$polygon_551.tester; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +/* removed: var _$linePoints_941 = require('./line_points'); */; +/* removed: var _$linkTraces_943 = require('./link_traces'); */; +var __polygonTester_946 = _$polygon_613.tester; -var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { - var i, uids, selection, join, onComplete; +var _$plot_946 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCompleteCallback) { + var i, uids, join, onComplete; var scatterlayer = plotinfo.plot.select('g.scatterlayer'); @@ -83687,9 +84488,8 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo var isFullReplot = !transitionOpts; var hasTransition = !!transitionOpts && transitionOpts.duration > 0; - selection = scatterlayer.selectAll('g.trace'); - - join = selection.data(cdscatter, function(d) { return d[0].trace.uid; }); + join = scatterlayer.selectAll('g.trace') + .data(cdscatter, function(d) { return d[0].trace.uid; }); // Append new traces: join.enter().append('g') @@ -83701,7 +84501,7 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // After the elements are created but before they've been draw, we have to perform // this extra step of linking the traces. This allows appending of fill layers so that // the z-order of fill layers is correct. - _$linkTraces_878(gd, plotinfo, cdscatter); + _$linkTraces_943(gd, plotinfo, cdscatter); createFills(gd, scatterlayer, plotinfo); @@ -83726,7 +84526,7 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo onComplete = makeOnCompleteCallback(); } - var transition = _$d3_127.transition() + var transition = _$d3_130.transition() .duration(transitionOpts.duration) .ease(transitionOpts.easing) .each('end', function() { @@ -83740,12 +84540,12 @@ var _$plot_881 = function plot(gd, plotinfo, cdscatter, transitionOpts, makeOnCo // Must run the selection again since otherwise enters/updates get grouped together // and these get executed out of order. Except we need them in order! scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_881(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_946(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); }); } else { scatterlayer.selectAll('g.trace').each(function(d, i) { - __plotOne_881(gd, i, plotinfo, d, cdscatter, this, transitionOpts); + __plotOne_946(gd, i, plotinfo, d, cdscatter, this, transitionOpts); }); } @@ -83761,7 +84561,7 @@ function createFills(gd, scatterlayer, plotinfo) { var trace; scatterlayer.selectAll('g.trace').each(function(d) { - var tr = _$d3_127.select(this); + var tr = _$d3_130.select(this); // Loop only over the traces being redrawn: trace = d[0].trace; @@ -83796,11 +84596,11 @@ function createFills(gd, scatterlayer, plotinfo) { trace._ownFill = null; } - tr.selectAll('.js-fill').call(_$drawing_436.setClipUrl, plotinfo.layerClipId); + tr.selectAll('.js-fill').call(_$drawing_498.setClipUrl, plotinfo.layerClipId); }); } -function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { +function __plotOne_946(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { var join, i; // Since this has been reorganized and we're executing this on individual traces, @@ -83819,10 +84619,10 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var trace = cdscatter[0].trace, line = trace.line, - tr = _$d3_127.select(element); + tr = _$d3_130.select(element); // error bars are at the bottom - _$registry_668.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); + _$registry_731.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts); if(trace.visible !== true) return; @@ -83834,7 +84634,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; + if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr; var prevRevpath = ''; var prevPolygons = []; @@ -83860,11 +84660,11 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // initialize line join data / method var segments = [], - makeUpdate = _$lib_539.noop; + makeUpdate = _$lib_601.noop; ownFillEl3 = trace._ownFill; - if(_$subtypes_884.hasLines(trace) || trace.fill !== 'none') { + if(_$subtypes_949.hasLines(trace) || trace.fill !== 'none') { if(tonext) { // This tells .style which trace to use for fill information: @@ -83872,8 +84672,8 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran } if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = _$drawing_436.steps(line.shape); - revpathbase = _$drawing_436.steps( + pathfn = _$drawing_498.steps(line.shape); + revpathbase = _$drawing_498.steps( line.shape.split('').reverse().join('') ); } @@ -83883,10 +84683,10 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { // identical start and end points: treat it as a // closed curve so we don't get a kink - return _$drawing_436.smoothclosed(pts.slice(1), line.smoothing); + return _$drawing_498.smoothclosed(pts.slice(1), line.smoothing); } else { - return _$drawing_436.smoothopen(pts, line.smoothing); + return _$drawing_498.smoothopen(pts, line.smoothing); } }; } @@ -83901,7 +84701,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran return revpathbase(pts.reverse()); }; - segments = _$linePoints_876(cdscatter, { + segments = _$linePoints_941(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -83916,7 +84716,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // need to redraw when you change hoveron... thisPolygons = trace._polygons = new Array(segments.length); for(i = 0; i < segments.length; i++) { - trace._polygons[i] = __polygonTester_881(segments[i]); + trace._polygons[i] = __polygonTester_946(segments[i]); } if(segments.length) { @@ -83942,8 +84742,8 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran revpath = thisrevpath + 'Z' + revpath; } - if(_$subtypes_884.hasLines(trace) && pts.length > 1) { - var el = _$d3_127.select(this); + if(_$subtypes_949.hasLines(trace) && pts.length > 1) { + var el = _$d3_130.select(this); // This makes the coloring work correctly: el.datum(cdscatter); @@ -83951,12 +84751,12 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(isEnter) { transition(el.style('opacity', 0) .attr('d', thispath) - .call(_$drawing_436.lineGroupStyle)) + .call(_$drawing_498.lineGroupStyle)) .style('opacity', 1); } else { var sel = transition(el); sel.attr('d', thispath); - _$drawing_436.singleLineStyle(cdscatter, sel); + _$drawing_498.singleLineStyle(cdscatter, sel); } } }; @@ -83974,10 +84774,10 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran lineJoin.enter().append('path') .classed('js-line', true) .style('vector-effect', 'non-scaling-stroke') - .call(_$drawing_436.lineGroupStyle) + .call(_$drawing_498.lineGroupStyle) .each(makeUpdate(true)); - _$drawing_436.setClipUrl(lineJoin, plotinfo.layerClipId); + _$drawing_498.setClipUrl(lineJoin, plotinfo.layerClipId); function clearFill(selection) { transition(selection).attr('d', 'M0,0Z'); @@ -84000,11 +84800,11 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // the points on the axes are the first two points. Otherwise // animations get a little crazy if the number of points changes. transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1)) - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } else { // fill to self: just join the path to itself transition(ownFillEl3).attr('d', fullpath + 'Z') - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } } } @@ -84017,7 +84817,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z') - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -84026,7 +84826,7 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // things depending on whether the new endpoint projects onto the // existing curve or off the end of it transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z') - .call(_$drawing_436.singleFillStyle); + .call(_$drawing_498.singleFillStyle); } trace._polygons = trace._polygons.concat(prevPolygons); } @@ -84068,20 +84868,20 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran var join, selection, hasNode; var trace = d[0].trace, - s = _$d3_127.select(this), - showMarkers = _$subtypes_884.hasMarkers(trace), - showText = _$subtypes_884.hasText(trace); + s = _$d3_130.select(this), + showMarkers = _$subtypes_949.hasMarkers(trace), + showText = _$subtypes_949.hasText(trace); var keyFunc = getKeyFunc(trace), markerFilter = hideFilter, textFilter = hideFilter; if(showMarkers) { - markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_539.identity; + markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_601.identity; } if(showText) { - textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_539.identity; + textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : _$lib_601.identity; } // marker points @@ -84095,28 +84895,28 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran if(hasTransition) { enter - .call(_$drawing_436.pointStyle, trace, gd) - .call(_$drawing_436.translatePoints, xa, ya) + .call(_$drawing_498.pointStyle, trace, gd) + .call(_$drawing_498.translatePoints, xa, ya) .style('opacity', 0) .transition() .style('opacity', 1); } - var markerScale = showMarkers && _$drawing_436.tryColorscale(trace.marker, ''); - var lineScale = showMarkers && _$drawing_436.tryColorscale(trace.marker, 'line'); + var markerScale = showMarkers && _$drawing_498.tryColorscale(trace.marker, ''); + var lineScale = showMarkers && _$drawing_498.tryColorscale(trace.marker, 'line'); join.order(); join.each(function(d) { - var el = _$d3_127.select(this); + var el = _$d3_130.select(this); var sel = transition(el); - hasNode = _$drawing_436.translatePoint(d, sel, xa, ya); + hasNode = _$drawing_498.translatePoint(d, sel, xa, ya); if(hasNode) { - _$drawing_436.singlePointStyle(d, sel, trace, markerScale, lineScale, gd); + _$drawing_498.singlePointStyle(d, sel, trace, markerScale, lineScale, gd); if(plotinfo.layerClipId) { - _$drawing_436.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_498.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar); } if(trace.customdata) { @@ -84146,13 +84946,13 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran join.order(); join.each(function(d) { - var g = _$d3_127.select(this); + var g = _$d3_130.select(this); var sel = transition(g.select('text')); - hasNode = _$drawing_436.translatePoint(d, sel, xa, ya); + hasNode = _$drawing_498.translatePoint(d, sel, xa, ya); if(hasNode) { if(plotinfo.layerClipId) { - _$drawing_436.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar); + _$drawing_498.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar); } } else { g.remove(); @@ -84160,15 +84960,15 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran }); join.selectAll('text') - .call(_$drawing_436.textPointStyle, trace, gd) + .call(_$drawing_498.textPointStyle, trace, gd) .each(function(d) { // This just *has* to be totally custom becuase of SVG text positioning :( // It's obviously copied from translatePoint; we just can't use that var x = xa.c2p(d.x); var y = ya.c2p(d.y); - _$d3_127.select(this).selectAll('tspan.line').each(function() { - transition(_$d3_127.select(this)).attr({x: x, y: y}); + _$d3_130.select(this).selectAll('tspan.line').each(function() { + transition(_$d3_130.select(this)).attr({x: x, y: y}); }); }); @@ -84195,18 +84995,18 @@ function __plotOne_881(gd, idx, plotinfo, cdscatter, cdscatterAll, element, tran // on `plotinfo._hasClipOnAxisFalse === true` subplots join.each(function(d) { var hasClipOnAxisFalse = d[0].trace.cliponaxis === false; - _$drawing_436.setClipUrl(_$d3_127.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); + _$drawing_498.setClipUrl(_$d3_130.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId); }); } function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { var xa = plotinfo.xaxis, ya = plotinfo.yaxis, - xr = _$d3_127.extent(_$lib_539.simpleMap(xa.range, xa.r2c)), - yr = _$d3_127.extent(_$lib_539.simpleMap(ya.range, ya.r2c)); + xr = _$d3_130.extent(_$lib_601.simpleMap(xa.range, xa.r2c)), + yr = _$d3_130.extent(_$lib_601.simpleMap(ya.range, ya.r2c)); var trace = cdscatter[0].trace; - if(!_$subtypes_884.hasMarkers(trace)) return; + if(!_$subtypes_949.hasMarkers(trace)) return; // if marker.maxdisplayed is used, select a maximum of // mnum markers to show, from the set that are in the viewport var mnum = trace.marker.maxdisplayed; @@ -84221,7 +85021,7 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { tnum = 0; cdscatterAll.forEach(function(cdj, j) { var tracei = cdj[0].trace; - if(_$subtypes_884.hasMarkers(tracei) && + if(_$subtypes_949.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { tnum++; } @@ -84252,9 +85052,9 @@ function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { 'use strict'; -/* removed: var _$subtypes_884 = require('./subtypes'); */; +/* removed: var _$subtypes_949 = require('./subtypes'); */; -var _$selectPoints_882 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_947 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd, xa = searchInfo.xaxis, ya = searchInfo.yaxis, @@ -84265,7 +85065,7 @@ var _$selectPoints_882 = function selectPoints(searchInfo, polygon) { x, y; - var hasOnlyLines = (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)); + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { // clear selection @@ -84306,44 +85106,44 @@ var _$selectPoints_882 = function selectPoints(searchInfo, polygon) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$registry_668 = require('../../registry'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$registry_731 = require('../../registry'); */; -function __style_883(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.scatter'); +function __style_948(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.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_127.select(this); + var sel = _$d3_130.select(this); var trace = d.trace || d[0].trace; stylePoints(sel, trace, gd); }); s.selectAll('g.trace path.js-line') - .call(_$drawing_436.lineGroupStyle); + .call(_$drawing_498.lineGroupStyle); s.selectAll('g.trace path.js-fill') - .call(_$drawing_436.fillGroupStyle); + .call(_$drawing_498.fillGroupStyle); - _$registry_668.getComponentMethod('errorbars', 'style')(s); + _$registry_731.getComponentMethod('errorbars', 'style')(s); } function stylePoints(sel, trace, gd) { var pts = sel.selectAll('path.point'); var txs = sel.selectAll('text'); - _$drawing_436.pointStyle(pts, trace, gd); - _$drawing_436.textPointStyle(txs, trace, gd); - _$drawing_436.selectedPointStyle(pts, trace); - _$drawing_436.selectedTextStyle(txs, trace); + _$drawing_498.pointStyle(pts, trace, gd); + _$drawing_498.textPointStyle(txs, trace, gd); + _$drawing_498.selectedPointStyle(pts, trace); + _$drawing_498.selectedTextStyle(txs, trace); } -var _$style_883 = { - style: __style_883, +var _$style_948 = { + style: __style_948, stylePoints: stylePoints }; @@ -84360,37 +85160,37 @@ var _$style_883 = { var Scatter = {}; -/* removed: var _$subtypes_884 = require('./subtypes'); */; -Scatter.hasLines = _$subtypes_884.hasLines; -Scatter.hasMarkers = _$subtypes_884.hasMarkers; -Scatter.hasText = _$subtypes_884.hasText; -Scatter.isBubble = _$subtypes_884.isBubble; +/* removed: var _$subtypes_949 = require('./subtypes'); */; +Scatter.hasLines = _$subtypes_949.hasLines; +Scatter.hasMarkers = _$subtypes_949.hasMarkers; +Scatter.hasText = _$subtypes_949.hasText; +Scatter.isBubble = _$subtypes_949.isBubble; // traces with < this many points are by default shown // with points and lines, > just get lines -Scatter.attributes = _$attributes_862; -Scatter.supplyDefaults = _$supplyDefaults_869; -Scatter.cleanData = _$cleanData_865; -Scatter.calc = _$calc_863.calc; -Scatter.arraysToCalcdata = _$arraysToCalcdata_861; -Scatter.plot = _$plot_881; -Scatter.colorbar = _$colorbar_866; -Scatter.style = _$style_883.style; -Scatter.hoverPoints = _$hoverPoints_873; -Scatter.selectPoints = _$selectPoints_882; +Scatter.attributes = _$attributes_927; +Scatter.supplyDefaults = _$supplyDefaults_934; +Scatter.cleanData = _$cleanData_930; +Scatter.calc = _$calc_928.calc; +Scatter.arraysToCalcdata = _$arraysToCalcdata_926; +Scatter.plot = _$plot_946; +Scatter.colorbar = _$colorbar_931; +Scatter.style = _$style_948.style; +Scatter.hoverPoints = _$hoverPoints_938; +Scatter.selectPoints = _$selectPoints_947; Scatter.animatable = true; Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.basePlotModule = _$cartesian_595; -Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like']; +Scatter.basePlotModule = _$cartesian_658; +Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts']; Scatter.meta = { }; -var _$Scatter_874 = Scatter; +var _$Scatter_939 = Scatter; -var _$core_520 = {}; +var _$core_581 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -84402,71 +85202,71 @@ var _$core_520 = {}; 'use strict'; // package version injected by `npm run preprocess` -_$core_520.version = '1.35.2'; +_$core_581.version = '1.36.0'; // inject promise polyfill -_$es6Promise_136.polyfill(); +_$es6Promise_184.polyfill(); // inject plot css _$plotcss_1; // inject default MathJax config -_$mathjax_config_521; +_$mathjax_config_582; // include registry module and expose register method -/* removed: var _$registry_668 = require('./registry'); */; -var register = _$core_520.register = _$registry_668.register; +/* removed: var _$registry_731 = require('./registry'); */; +var register = _$core_581.register = _$registry_731.register; // expose plot api methods -/* removed: var _$plot_api_571 = require('./plot_api'); */; -var methodNames = Object.keys(_$plot_api_571); +/* removed: var _$plot_api_634 = require('./plot_api'); */; +var methodNames = Object.keys(_$plot_api_634); for(var i = 0; i < methodNames.length; i++) { - var __name_520 = methodNames[i]; - _$core_520[__name_520] = _$plot_api_571[__name_520]; + var __name_581 = methodNames[i]; + _$core_581[__name_581] = _$plot_api_634[__name_581]; register({ moduleType: 'apiMethod', - name: __name_520, - fn: _$plot_api_571[__name_520] + name: __name_581, + fn: _$plot_api_634[__name_581] }); } // scatter is the only trace included by default -register(_$Scatter_874); +register(_$Scatter_939); // register all registrable components modules register([ - _$fx_453, - _$legend_471, - _$annotations_402, - _$annotations3d_407, - _$shapes_497, - _$images_462, - _$updatemenus_509, - _$sliders_503, - _$rangeslider_489, - _$rangeselector_483, - _$grid_457, - _$errorbars_442 + _$fx_515, + _$legend_533, + _$annotations_464, + _$annotations3d_469, + _$shapes_559, + _$images_524, + _$updatemenus_571, + _$sliders_565, + _$rangeslider_551, + _$rangeselector_545, + _$grid_519, + _$errorbars_504 ]); // locales en and en-US are required for default behavior register([ - _$localeEn_567, - _$localeEnUs_566 + _$localeEn_630, + _$localeEnUs_629 ]); // plot icons -_$core_520.Icons = _$ploticon_2; +_$core_581.Icons = _$ploticon_2; // unofficial 'beta' plot methods, use at your own risk -_$core_520.Plots = _$plots_647; -_$core_520.Fx = _$fx_453; -_$core_520.Snapshot = _$Snapshot_673; -_$core_520.PlotSchema = _$plot_schema_575; -_$core_520.Queue = _$queue_553; +_$core_581.Plots = _$plots_709; +_$core_581.Fx = _$fx_515; +_$core_581.Snapshot = _$Snapshot_736; +_$core_581.PlotSchema = _$plot_schema_638; +_$core_581.Queue = _$queue_616; // export d3 used in the bundle -_$core_520.d3 = _$d3_127; +_$core_581.d3 = _$d3_130; /** * Copyright 2012-2018, Plotly, Inc. @@ -84478,9 +85278,9 @@ _$core_520.d3 = _$d3_127; 'use strict'; -var _$core_12 = _$core_520; +var _$core_12 = _$core_581; -var _$filter_963 = {}; +var _$filter_1034 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -84491,21 +85291,21 @@ var _$filter_963 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$registry_668 = require('../registry'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -var __pointsAccessorFunction_963 = _$helpers_965.pointsAccessorFunction; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$registry_731 = require('../registry'); */; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +var __pointsAccessorFunction_1034 = _$helpers_1036.pointsAccessorFunction; -/* removed: var _$filter_ops_512 = require('../constants/filter_ops'); */; -var COMPARISON_OPS = _$filter_ops_512.COMPARISON_OPS; -var __INTERVAL_OPS_963 = _$filter_ops_512.INTERVAL_OPS; -var SET_OPS = _$filter_ops_512.SET_OPS; +/* removed: var _$filter_ops_574 = require('../constants/filter_ops'); */; +var COMPARISON_OPS = _$filter_ops_574.COMPARISON_OPS; +var __INTERVAL_OPS_1034 = _$filter_ops_574.INTERVAL_OPS; +var SET_OPS = _$filter_ops_574.SET_OPS; -_$filter_963.moduleType = 'transform'; +_$filter_1034.moduleType = 'transform'; -_$filter_963.name = 'filter'; +_$filter_1034.name = 'filter'; -_$filter_963.attributes = { +_$filter_1034.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -84527,7 +85327,7 @@ _$filter_963.attributes = { valType: 'enumerated', values: [] .concat(COMPARISON_OPS) - .concat(__INTERVAL_OPS_963) + .concat(__INTERVAL_OPS_1034) .concat(SET_OPS), dflt: '=', @@ -84551,11 +85351,11 @@ _$filter_963.attributes = { editType: 'calc' }; -_$filter_963.supplyDefaults = function(transformIn) { +_$filter_1034.supplyDefaults = function(transformIn) { var transformOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, _$filter_963.attributes, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, _$filter_1034.attributes, attr, dflt); } var enabled = coerce('enabled'); @@ -84566,7 +85366,7 @@ _$filter_963.supplyDefaults = function(transformIn) { coerce('value'); coerce('target'); - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleDefaults'); handleCalendarDefaults(transformIn, transformOut, 'valuecalendar', null); handleCalendarDefaults(transformIn, transformOut, 'targetcalendar', null); } @@ -84574,10 +85374,10 @@ _$filter_963.supplyDefaults = function(transformIn) { return transformOut; }; -_$filter_963.calcTransform = function(gd, trace, opts) { +_$filter_1034.calcTransform = function(gd, trace, opts) { if(!opts.enabled) return; - var targetArray = _$lib_539.getTargetArray(trace, opts); + var targetArray = _$lib_601.getTargetArray(trace, opts); if(!targetArray) return; var target = opts.target; @@ -84588,11 +85388,11 @@ _$filter_963.calcTransform = function(gd, trace, opts) { // even if you provide targetcalendar, if target is a string and there // is a calendar attribute matching target it will get used instead. if(typeof target === 'string') { - var attrTargetCalendar = _$lib_539.nestedProperty(trace, target + 'calendar').get(); + var attrTargetCalendar = _$lib_601.nestedProperty(trace, target + 'calendar').get(); if(attrTargetCalendar) targetCalendar = attrTargetCalendar; } - var d2c = _$axes_584.getDataToCoordFunc(gd, trace, target, targetArray); + var d2c = _$axes_647.getDataToCoordFunc(gd, trace, target, targetArray); var filterFunc = getFilterFunc(opts, d2c, targetCalendar); var originalArrays = {}; var indexToPoints = {}; @@ -84600,7 +85400,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { function forAllAttrs(fn, index) { for(var j = 0; j < arrayAttrs.length; j++) { - var np = _$lib_539.nestedProperty(trace, arrayAttrs[j]); + var np = _$lib_601.nestedProperty(trace, arrayAttrs[j]); fn(np, index); } } @@ -84609,7 +85409,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { var fillFn; if(opts.preservegaps) { initFn = function(np) { - originalArrays[np.astr] = _$lib_539.extendDeep([], np.get()); + originalArrays[np.astr] = _$lib_601.extendDeep([], np.get()); np.set(new Array(len)); }; fillFn = function(np, index) { @@ -84618,7 +85418,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { }; } else { initFn = function(np) { - originalArrays[np.astr] = _$lib_539.extendDeep([], np.get()); + originalArrays[np.astr] = _$lib_601.extendDeep([], np.get()); np.set([]); }; fillFn = function(np, index) { @@ -84630,7 +85430,7 @@ _$filter_963.calcTransform = function(gd, trace, opts) { // copy all original array attribute values, and clear arrays in trace forAllAttrs(initFn); - var originalPointsAccessor = __pointsAccessorFunction_963(trace.transforms, opts); + var originalPointsAccessor = __pointsAccessorFunction_1034(trace.transforms, opts); // loop through filter array, fill trace arrays if passed for(var i = 0; i < len; i++) { @@ -84662,7 +85462,7 @@ function getFilterFunc(opts, d2c, targetCalendar) { if(isOperationIn(COMPARISON_OPS)) { coercedValue = hasArrayValue ? d2cValue(value[0]) : d2cValue(value); } - else if(isOperationIn(__INTERVAL_OPS_963)) { + else if(isOperationIn(__INTERVAL_OPS_1034)) { coercedValue = hasArrayValue ? [d2cValue(value[0]), d2cValue(value[1])] : [d2cValue(value), d2cValue(value)]; @@ -84761,9 +85561,9 @@ function getFilterFunc(opts, d2c, targetCalendar) { 'use strict'; -var _$filter_13 = _$filter_963; +var _$filter_13 = _$filter_1034; -var _$groupby_964 = {}; +var _$groupby_1035 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -84774,16 +85574,16 @@ var _$groupby_964 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$plot_schema_575 = require('../plot_api/plot_schema'); */; -/* removed: var _$plots_647 = require('../plots/plots'); */; -var __pointsAccessorFunction_964 = _$helpers_965.pointsAccessorFunction; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$plot_schema_638 = require('../plot_api/plot_schema'); */; +/* removed: var _$plots_709 = require('../plots/plots'); */; +var __pointsAccessorFunction_1035 = _$helpers_1036.pointsAccessorFunction; -_$groupby_964.moduleType = 'transform'; +_$groupby_1035.moduleType = 'transform'; -_$groupby_964.name = 'groupby'; +_$groupby_1035.name = 'groupby'; -_$groupby_964.attributes = { +_$groupby_1035.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -84839,12 +85639,12 @@ _$groupby_964.attributes = { * @return {object} transformOut * copy of transformIn that contains attribute defaults */ -_$groupby_964.supplyDefaults = function(transformIn, traceOut, layout) { +_$groupby_1035.supplyDefaults = function(transformIn, traceOut, layout) { var i; var transformOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, _$groupby_964.attributes, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, _$groupby_1035.attributes, attr, dflt); } var enabled = coerce('enabled'); @@ -84860,8 +85660,8 @@ _$groupby_964.supplyDefaults = function(transformIn, traceOut, layout) { if(styleIn) { for(i = 0; i < styleIn.length; i++) { styleOut[i] = {}; - _$lib_539.coerce(styleIn[i], styleOut[i], _$groupby_964.attributes.styles, 'target'); - _$lib_539.coerce(styleIn[i], styleOut[i], _$groupby_964.attributes.styles, 'value'); + _$lib_601.coerce(styleIn[i], styleOut[i], _$groupby_1035.attributes.styles, 'target'); + _$lib_601.coerce(styleIn[i], styleOut[i], _$groupby_1035.attributes.styles, 'value'); } } @@ -84885,7 +85685,7 @@ _$groupby_964.supplyDefaults = function(transformIn, traceOut, layout) { * @return {object} newData * array of transformed traces */ -_$groupby_964.transform = function(data, state) { +_$groupby_1035.transform = function(data, state) { var newTraces, i, j; var newData = []; @@ -84906,17 +85706,17 @@ function transformOne(trace, state) { var opts = state.transform; var groups = trace.transforms[state.transformIndex].groups; - var originalPointsAccessor = __pointsAccessorFunction_964(trace.transforms, opts); + var originalPointsAccessor = __pointsAccessorFunction_1035(trace.transforms, opts); if(!(Array.isArray(groups)) || groups.length === 0) { return [trace]; } - var groupNames = _$lib_539.filterUnique(groups), + var groupNames = _$lib_601.filterUnique(groups), newData = new Array(groupNames.length), len = groups.length; - var arrayAttrs = _$plot_schema_575.findArrayAttributes(trace); + var arrayAttrs = _$plot_schema_638.findArrayAttributes(trace); var styles = opts.styles || []; var styleLookup = {}; @@ -84925,7 +85725,7 @@ function transformOne(trace, state) { } if(opts.styles) { - groupNameObj = _$lib_539.keyedContainer(opts, 'styles', 'target', 'value.name'); + groupNameObj = _$lib_601.keyedContainer(opts, 'styles', 'target', 'value.name'); } // An index to map group name --> expanded trace index @@ -84938,7 +85738,7 @@ function transformOne(trace, state) { indexCnts[groupName] = 0; // Start with a deep extend that just copies array references. - newTrace = newData[i] = _$lib_539.extendDeepNoArrays({}, trace); + newTrace = newData[i] = _$lib_601.extendDeepNoArrays({}, trace); newTrace._group = groupName; newTrace.transforms[state.transformIndex]._indexToPoints = {}; @@ -84950,7 +85750,7 @@ function transformOne(trace, state) { if(suppliedName) { newTrace.name = suppliedName; } else { - newTrace.name = _$lib_539.templateString(opts.nameformat, { + newTrace.name = _$lib_601.templateString(opts.nameformat, { trace: trace.name, group: groupName }); @@ -84965,12 +85765,12 @@ function transformOne(trace, state) { transforms = newTrace.transforms; newTrace.transforms = []; for(j = 0; j < transforms.length; j++) { - newTrace.transforms[j] = _$lib_539.extendDeepNoArrays({}, transforms[j]); + newTrace.transforms[j] = _$lib_601.extendDeepNoArrays({}, transforms[j]); } // Initialize empty arrays for the arrayAttrs, to be split in the next step for(j = 0; j < arrayAttrs.length; j++) { - _$lib_539.nestedProperty(newTrace, arrayAttrs[j]).set([]); + _$lib_601.nestedProperty(newTrace, arrayAttrs[j]).set([]); } } @@ -84982,11 +85782,11 @@ function transformOne(trace, state) { // Cache all the arrays to which we'll push: for(j = 0, arrayLookup = []; j < groupNames.length; j++) { - arrayLookup[j] = _$lib_539.nestedProperty(newData[j], attr).get(); + arrayLookup[j] = _$lib_601.nestedProperty(newData[j], attr).get(); } // Get the input data: - srcArray = _$lib_539.nestedProperty(trace, attr).get(); + srcArray = _$lib_601.nestedProperty(trace, attr).get(); // Send each data point to the appropriate expanded trace: for(j = 0; j < len; j++) { @@ -85007,11 +85807,11 @@ function transformOne(trace, state) { groupName = groupNames[i]; newTrace = newData[i]; - _$plots_647.clearExpandedTraceDefaultColors(newTrace); + _$plots_709.clearExpandedTraceDefaultColors(newTrace); // there's no need to coerce styleLookup[groupName] here // as another round of supplyDefaults is done on the transformed traces - newTrace = _$lib_539.extendDeepNoArrays(newTrace, styleLookup[groupName] || {}); + newTrace = _$lib_601.extendDeepNoArrays(newTrace, styleLookup[groupName] || {}); } return newData; @@ -85027,7 +85827,7 @@ function transformOne(trace, state) { 'use strict'; -var _$groupby_14 = _$groupby_964; +var _$groupby_14 = _$groupby_1035; /** * Copyright 2012-2018, Plotly, Inc. @@ -85040,7 +85840,7 @@ var _$groupby_14 = _$groupby_964; 'use strict'; -var _$handleStyleDefaults_788 = function handleStyleDefaults(traceIn, traceOut, coerce) { +var _$handleStyleDefaults_850 = function handleStyleDefaults(traceIn, traceOut, coerce) { var zsmooth = coerce('zsmooth'); if(zsmooth === false) { // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect. @@ -85062,21 +85862,21 @@ var _$handleStyleDefaults_788 = function handleStyleDefaults(traceIn, traceOut, 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$has_columns_780 = require('./has_columns'); */; -/* removed: var _$handleXYZDefaults_789 = require('./xyz_defaults'); */; -/* removed: var _$handleStyleDefaults_788 = require('./style_defaults'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_773 = require('./attributes'); */; +/* removed: var _$has_columns_842 = require('./has_columns'); */; +/* removed: var _$handleXYZDefaults_851 = require('./xyz_defaults'); */; +/* removed: var _$handleStyleDefaults_850 = require('./style_defaults'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_835 = require('./attributes'); */; -var _$supplyDefaults_778 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_773, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_835, attr, dflt); } - var len = _$handleXYZDefaults_789(traceIn, traceOut, coerce, layout); + var len = _$handleXYZDefaults_851(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -85084,11 +85884,11 @@ var _$supplyDefaults_778 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); - _$handleStyleDefaults_788(traceIn, traceOut, coerce, layout); + _$handleStyleDefaults_850(traceIn, traceOut, coerce, layout); - coerce('connectgaps', _$has_columns_780(traceOut) && (traceOut.zsmooth !== false)); + coerce('connectgaps', _$has_columns_842(traceOut) && (traceOut.zsmooth !== false)); - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; /** @@ -85104,23 +85904,23 @@ var _$supplyDefaults_778 = function supplyDefaults(traceIn, traceOut, defaultCol var Heatmap = {}; -Heatmap.attributes = _$attributes_773; -Heatmap.supplyDefaults = _$supplyDefaults_778; -Heatmap.calc = _$calc_774; -Heatmap.plot = _$plot_786; -Heatmap.colorbar = _$colorbar_776; -Heatmap.style = _$style_787; -Heatmap.hoverPoints = _$hoverPoints_781; +Heatmap.attributes = _$attributes_835; +Heatmap.supplyDefaults = _$supplyDefaults_840; +Heatmap.calc = _$calc_836; +Heatmap.plot = _$plot_848; +Heatmap.colorbar = _$colorbar_838; +Heatmap.style = _$style_849; +Heatmap.hoverPoints = _$hoverPoints_843; Heatmap.moduleType = 'trace'; Heatmap.name = 'heatmap'; -Heatmap.basePlotModule = _$cartesian_595; -Heatmap.categories = ['cartesian', '2dMap']; +Heatmap.basePlotModule = _$cartesian_658; +Heatmap.categories = ['cartesian', 'svg', '2dMap']; Heatmap.meta = { }; -var _$Heatmap_782 = Heatmap; +var _$Heatmap_844 = Heatmap; /** * Copyright 2012-2018, Plotly, Inc. @@ -85132,7 +85932,7 @@ var _$Heatmap_782 = Heatmap; 'use strict'; -var _$heatmap_15 = _$Heatmap_782; +var _$heatmap_15 = _$Heatmap_844; "use strict" @@ -85190,11 +85990,11 @@ function unique(list, compare, sorted) { return unique_eq(list) } -var _$unique_362 = unique +var _$unique_424 = unique "use strict" -/* removed: var _$unique_362 = require("uniq") */; +/* removed: var _$unique_424 = require("uniq") */; // 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. @@ -85511,7 +86311,7 @@ function generateCWiseOp(proc, typesig) { } //Prepare this variables - var thisVars = _$unique_362([].concat(proc.pre.thisVars) + var thisVars = _$unique_424([].concat(proc.pre.thisVars) .concat(proc.body.thisVars) .concat(proc.post.thisVars)) vars = vars.concat(thisVars) @@ -85549,7 +86349,7 @@ function generateCWiseOp(proc, typesig) { var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) return f() } -var _$generateCWiseOp_116 = generateCWiseOp +var _$generateCWiseOp_117 = generateCWiseOp "use strict" @@ -85576,7 +86376,7 @@ var _$generateCWiseOp_116 = generateCWiseOp // return thunk(compile.bind1(proc)) // } -/* removed: var _$generateCWiseOp_116 = require("./compile.js") */; +/* removed: var _$generateCWiseOp_117 = require("./compile.js") */; function createThunk(proc) { var code = ["'use strict'", "var CACHED={}"] @@ -85633,14 +86433,14 @@ function createThunk(proc) { //Compile thunk var thunk = new Function("compile", code.join("\n")) - return thunk(_$generateCWiseOp_116.bind(undefined, proc)) + return thunk(_$generateCWiseOp_117.bind(undefined, proc)) } -var _$createThunk_117 = createThunk +var _$createThunk_118 = createThunk "use strict" -/* removed: var _$createThunk_117 = require("./lib/thunk.js") */; +/* removed: var _$createThunk_118 = require("./lib/thunk.js") */; function Procedure() { this.argTypes = [] @@ -85743,15 +86543,15 @@ function compileCwise(user_args) { //Read in block size proc.blockSize = user_args.blockSize || 64 - return _$createThunk_117(proc) + return _$createThunk_118(proc) } -var _$compileCwise_115 = compileCwise +var _$compileCwise_116 = compileCwise -var _$ndarrayOps_271 = {}; +var _$ndarrayOps_329 = {}; "use strict" -/* removed: var _$compileCwise_115 = require("cwise-compiler") */; +/* removed: var _$compileCwise_116 = require("cwise-compiler") */; var EmptyProc = { body: "", @@ -85782,7 +86582,7 @@ function fixup(x) { } function pcompile(user_args) { - return _$compileCwise_115({ + return _$compileCwise_116({ args: user_args.args, pre: fixup(user_args.pre), body: fixup(user_args.body), @@ -85818,26 +86618,26 @@ var assign_ops = { ;(function(){ for(var id in assign_ops) { var op = assign_ops[id] - _$ndarrayOps_271[id] = makeOp({ + _$ndarrayOps_329[id] = makeOp({ args: ["array","array","array"], body: {args:["a","b","c"], body: "a=b"+op+"c"}, funcName: id }) - _$ndarrayOps_271[id+"eq"] = makeOp({ + _$ndarrayOps_329[id+"eq"] = makeOp({ args: ["array","array"], body: {args:["a","b"], body:"a"+op+"=b"}, rvalue: true, funcName: id+"eq" }) - _$ndarrayOps_271[id+"s"] = makeOp({ + _$ndarrayOps_329[id+"s"] = makeOp({ args: ["array", "array", "scalar"], body: {args:["a","b","s"], body:"a=b"+op+"s"}, funcName: id+"s" }) - _$ndarrayOps_271[id+"seq"] = makeOp({ + _$ndarrayOps_329[id+"seq"] = makeOp({ args: ["array","scalar"], body: {args:["a","s"], body:"a"+op+"=s"}, @@ -85856,13 +86656,13 @@ var unary_ops = { ;(function(){ for(var id in unary_ops) { var op = unary_ops[id] - _$ndarrayOps_271[id] = makeOp({ + _$ndarrayOps_329[id] = makeOp({ args: ["array", "array"], body: {args:["a","b"], body:"a="+op+"b"}, funcName: id }) - _$ndarrayOps_271[id+"eq"] = makeOp({ + _$ndarrayOps_329[id+"eq"] = makeOp({ args: ["array"], body: {args:["a"], body:"a="+op+"a"}, @@ -85886,19 +86686,19 @@ var binary_ops = { ;(function() { for(var id in binary_ops) { var op = binary_ops[id] - _$ndarrayOps_271[id] = makeOp({ + _$ndarrayOps_329[id] = makeOp({ args: ["array","array","array"], body: {args:["a", "b", "c"], body:"a=b"+op+"c"}, funcName: id }) - _$ndarrayOps_271[id+"s"] = makeOp({ + _$ndarrayOps_329[id+"s"] = makeOp({ args: ["array","array","scalar"], body: {args:["a", "b", "s"], body:"a=b"+op+"s"}, funcName: id+"s" }) - _$ndarrayOps_271[id+"eq"] = makeOp({ + _$ndarrayOps_329[id+"eq"] = makeOp({ args: ["array", "array"], body: {args:["a", "b"], body:"a=a"+op+"b"}, @@ -85906,7 +86706,7 @@ var binary_ops = { count:2, funcName: id+"eq" }) - _$ndarrayOps_271[id+"seq"] = makeOp({ + _$ndarrayOps_329[id+"seq"] = makeOp({ args: ["array", "scalar"], body: {args:["a","s"], body:"a=a"+op+"s"}, @@ -85935,13 +86735,13 @@ var math_unary = [ ;(function() { for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, @@ -86083,7 +86883,7 @@ _$ndarrayOps_271.norminf = _$compileCwise_115({ funcName: "norminf" }) -_$ndarrayOps_271.norm1 = _$compileCwise_115({ +_$ndarrayOps_329.norm1 = _$compileCwise_116({ 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"]}, @@ -86091,7 +86891,7 @@ _$ndarrayOps_271.norm1 = _$compileCwise_115({ funcName: "norm1" }) -_$ndarrayOps_271.sup = _$compileCwise_115({ +_$ndarrayOps_329.sup = _$compileCwise_116({ args: [ "array" ], pre: { body: "this_h=-Infinity", @@ -86110,7 +86910,7 @@ _$ndarrayOps_271.sup = _$compileCwise_115({ localVars: [] } }) -_$ndarrayOps_271.inf = _$compileCwise_115({ +_$ndarrayOps_329.inf = _$compileCwise_116({ args: [ "array" ], pre: { body: "this_h=Infinity", @@ -86129,7 +86929,7 @@ _$ndarrayOps_271.inf = _$compileCwise_115({ localVars: [] } }) -_$ndarrayOps_271.argmin = _$compileCwise_115({ +_$ndarrayOps_329.argmin = _$compileCwise_116({ args:["index","array","shape"], pre:{ body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}", @@ -86154,7 +86954,7 @@ _$ndarrayOps_271.argmin = _$compileCwise_115({ localVars:[]} }) -_$ndarrayOps_271.argmax = _$compileCwise_115({ +_$ndarrayOps_329.argmax = _$compileCwise_116({ args:["index","array","shape"], pre:{ body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}", @@ -86179,25 +86979,25 @@ _$ndarrayOps_271.argmax = _$compileCwise_115({ localVars:[]} }) -_$ndarrayOps_271.random = makeOp({ +_$ndarrayOps_329.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" }) -_$ndarrayOps_271.assign = makeOp({ +_$ndarrayOps_329.assign = makeOp({ args:["array", "array"], body: {args:["a", "b"], body:"a=b"}, funcName: "assign" }) -_$ndarrayOps_271.assigns = makeOp({ +_$ndarrayOps_329.assigns = makeOp({ args:["array", "scalar"], body: {args:["a", "b"], body:"a=b"}, funcName: "assigns" }) -_$ndarrayOps_271.equals = _$compileCwise_115({ +_$ndarrayOps_329.equals = _$compileCwise_116({ args:["array", "array"], pre: EmptyProc, body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, @@ -86221,7 +87021,7 @@ function iota(n) { return result } -var _$iota_245 = iota +var _$iota_302 = iota /*! * Determine if an object is a Buffer * @@ -86231,7 +87031,7 @@ var _$iota_245 = iota // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually -var _$isBuffer_247 = function (obj) { +var _$isBuffer_304 = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } @@ -86244,8 +87044,8 @@ function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } -/* removed: var _$iota_245 = require("iota-array") */; -/* removed: var _$isBuffer_247 = require("is-buffer") */; +/* removed: var _$iota_302 = require("iota-array") */; +/* removed: var _$isBuffer_304 = require("is-buffer") */; var hasTypedArrays = ((typeof Float64Array) !== "undefined") @@ -86330,7 +87130,7 @@ return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" var code = ["'use strict'"] //Create constructor for view - var indices = _$iota_245(dimension) + var indices = _$iota_302(dimension) var args = indices.map(function(i) { return "i"+i }) var index_str = "this.offset+" + indices.map(function(i) { return "this.stride[" + i + "]*i" + i @@ -86499,7 +87299,7 @@ b"+i+"*=d\ } function arrayDType(data) { - if(_$isBuffer_247(data)) { + if(_$isBuffer_304(data)) { return "buffer" } if(hasTypedArrays) { @@ -86586,9 +87386,9 @@ function wrappedNDArrayCtor(data, shape, stride, offset) { return ctor(data, shape, stride, offset) } -var _$wrappedNDArrayCtor_277 = wrappedNDArrayCtor +var _$wrappedNDArrayCtor_335 = wrappedNDArrayCtor -var _$twiddle_72 = {}; +var _$twiddle_73 = {}; /** * Bit twiddling hacks for JavaScript. * @@ -86604,38 +87404,38 @@ var _$twiddle_72 = {}; var INT_BITS = 32; //Constants -_$twiddle_72.INT_BITS = INT_BITS; -_$twiddle_72.INT_MAX = 0x7fffffff; -_$twiddle_72.INT_MIN = -1<<(INT_BITS-1); +_$twiddle_73.INT_BITS = INT_BITS; +_$twiddle_73.INT_MAX = 0x7fffffff; +_$twiddle_73.INT_MIN = -1<<(INT_BITS-1); //Returns -1, 0, +1 depending on sign of x -_$twiddle_72.sign = function(v) { +_$twiddle_73.sign = function(v) { return (v > 0) - (v < 0); } //Computes absolute value of integer -_$twiddle_72.abs = function(v) { +_$twiddle_73.abs = function(v) { var mask = v >> (INT_BITS-1); return (v ^ mask) - mask; } //Computes minimum of integers x and y -_$twiddle_72.min = function(x, y) { +_$twiddle_73.min = function(x, y) { return y ^ ((x ^ y) & -(x < y)); } //Computes maximum of integers x and y -_$twiddle_72.max = function(x, y) { +_$twiddle_73.max = function(x, y) { return x ^ ((x ^ y) & -(x < y)); } //Checks if a number is a power of two -_$twiddle_72.isPow2 = function(v) { +_$twiddle_73.isPow2 = function(v) { return !(v & (v-1)) && (!!v); } //Computes log base 2 of v -_$twiddle_72.log2 = function(v) { +_$twiddle_73.log2 = function(v) { var r, shift; r = (v > 0xFFFF) << 4; v >>>= r; shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; @@ -86645,14 +87445,14 @@ _$twiddle_72.log2 = function(v) { } //Computes log base 10 of v -_$twiddle_72.log10 = function(v) { +_$twiddle_73.log10 = function(v) { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } //Counts number of bits -_$twiddle_72.popCount = function(v) { +_$twiddle_73.popCount = function(v) { v = v - ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; @@ -86670,10 +87470,10 @@ function countTrailingZeros(v) { if (v & 0x55555555) c -= 1; return c; } -_$twiddle_72.countTrailingZeros = countTrailingZeros; +_$twiddle_73.countTrailingZeros = countTrailingZeros; //Rounds to next power of 2 -_$twiddle_72.nextPow2 = function(v) { +_$twiddle_73.nextPow2 = function(v) { v += v === 0; --v; v |= v >>> 1; @@ -86685,7 +87485,7 @@ _$twiddle_72.nextPow2 = function(v) { } //Rounds down to previous power of 2 -_$twiddle_72.prevPow2 = function(v) { +_$twiddle_73.prevPow2 = function(v) { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; @@ -86695,7 +87495,7 @@ _$twiddle_72.prevPow2 = function(v) { } //Computes parity of word -_$twiddle_72.parity = function(v) { +_$twiddle_73.parity = function(v) { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; @@ -86718,7 +87518,7 @@ var REVERSE_TABLE = new Array(256); })(REVERSE_TABLE); //Reverse bits in a 32 bit word -_$twiddle_72.reverse = function(v) { +_$twiddle_73.reverse = function(v) { return (REVERSE_TABLE[ v & 0xff] << 24) | (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | @@ -86726,7 +87526,7 @@ _$twiddle_72.reverse = function(v) { } //Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -_$twiddle_72.interleave2 = function(x, y) { +_$twiddle_73.interleave2 = function(x, y) { x &= 0xFFFF; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; @@ -86743,7 +87543,7 @@ _$twiddle_72.interleave2 = function(x, y) { } //Extracts the nth interleaved component -_$twiddle_72.deinterleave2 = function(v, n) { +_$twiddle_73.deinterleave2 = function(v, n) { v = (v >>> n) & 0x55555555; v = (v | (v >>> 1)) & 0x33333333; v = (v | (v >>> 2)) & 0x0F0F0F0F; @@ -86754,7 +87554,7 @@ _$twiddle_72.deinterleave2 = function(v, n) { //Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -_$twiddle_72.interleave3 = function(x, y, z) { +_$twiddle_73.interleave3 = function(x, y, z) { x &= 0x3FF; x = (x | (x<<16)) & 4278190335; x = (x | (x<<8)) & 251719695; @@ -86778,7 +87578,7 @@ _$twiddle_72.interleave3 = function(x, y, z) { } //Extracts nth interleaved component of a 3-tuple -_$twiddle_72.deinterleave3 = function(v, n) { +_$twiddle_73.deinterleave3 = function(v, n) { v = (v >>> n) & 1227133513; v = (v | (v>>>2)) & 3272356035; v = (v | (v>>>4)) & 251719695; @@ -86788,27 +87588,27 @@ _$twiddle_72.deinterleave3 = function(v, n) { } //Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -_$twiddle_72.nextCombination = function(v) { +_$twiddle_73.nextCombination = function(v) { var t = v | (v - 1); return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } -var _$base64Js_54 = {}; +var _$base64Js_55 = {}; 'use strict' -_$base64Js_54.byteLength = byteLength -_$base64Js_54.toByteArray = toByteArray -_$base64Js_54.fromByteArray = fromByteArray +_$base64Js_55.byteLength = byteLength +_$base64Js_55.toByteArray = toByteArray +_$base64Js_55.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var __i_54 = 0, len = code.length; __i_54 < len; ++__i_54) { - lookup[__i_54] = code[__i_54] - revLookup[code.charCodeAt(__i_54)] = __i_54 +for (var __i_55 = 0, len = code.length; __i_55 < len; ++__i_55) { + lookup[__i_55] = code[__i_55] + revLookup[code.charCodeAt(__i_55)] = __i_55 } // Support decoding URL-safe base64 strings, as Node.js does. @@ -86912,8 +87712,8 @@ function fromByteArray (uint8) { return parts.join('') } -var _$ieee754_241 = {}; -_$ieee754_241.read = function (buffer, offset, isLE, mLen, nBytes) { +var _$ieee754_298 = {}; +_$ieee754_298.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 @@ -86946,7 +87746,7 @@ _$ieee754_241.read = function (buffer, offset, isLE, mLen, nBytes) { return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } -_$ieee754_241.write = function (buffer, value, offset, isLE, mLen, nBytes) { +_$ieee754_298.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 @@ -86998,7 +87798,7 @@ _$ieee754_241.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -var _$buffer_84 = {}; +var _$buffer_85 = {}; /*! * The buffer module from node.js, for the browser. * @@ -87009,15 +87809,15 @@ var _$buffer_84 = {}; 'use strict' -/* removed: var _$base64Js_54 = require('base64-js') */; -/* removed: var _$ieee754_241 = require('ieee754') */; +/* removed: var _$base64Js_55 = require('base64-js') */; +/* removed: var _$ieee754_298 = require('ieee754') */; -_$buffer_84.Buffer = Buffer -_$buffer_84.SlowBuffer = SlowBuffer -_$buffer_84.INSPECT_MAX_BYTES = 50 +_$buffer_85.Buffer = Buffer +_$buffer_85.SlowBuffer = SlowBuffer +_$buffer_85.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff -_$buffer_84.kMaxLength = K_MAX_LENGTH +_$buffer_85.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -87210,7 +88010,7 @@ function fromString (string, encoding) { throw new TypeError('Unknown encoding: ' + encoding) } - var length = __byteLength_84(string, encoding) | 0 + var length = __byteLength_85(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.write(string, encoding) @@ -87382,7 +88182,7 @@ Buffer.concat = function concat (list, length) { return buffer } -function __byteLength_84 (string, encoding) { +function __byteLength_85 (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } @@ -87424,7 +88224,7 @@ function __byteLength_84 (string, encoding) { } } } -Buffer.byteLength = __byteLength_84 +Buffer.byteLength = __byteLength_85 function slowToString (encoding, start, end) { var loweredCase = false @@ -87564,7 +88364,7 @@ Buffer.prototype.equals = function equals (b) { Buffer.prototype.inspect = function inspect () { var str = '' - var max = _$buffer_84.INSPECT_MAX_BYTES + var max = _$buffer_85.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' @@ -87889,9 +88689,9 @@ Buffer.prototype.toJSON = function toJSON () { function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { - return _$base64Js_54.fromByteArray(buf) + return _$base64Js_55.fromByteArray(buf) } else { - return _$base64Js_54.fromByteArray(buf.slice(start, end)) + return _$base64Js_55.fromByteArray(buf.slice(start, end)) } } @@ -88217,25 +89017,25 @@ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) - return _$ieee754_241.read(this, offset, true, 23, 4) + return _$ieee754_298.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) - return _$ieee754_241.read(this, offset, false, 23, 4) + return _$ieee754_298.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) - return _$ieee754_241.read(this, offset, true, 52, 8) + return _$ieee754_298.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) - return _$ieee754_241.read(this, offset, false, 52, 8) + return _$ieee754_298.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { @@ -88437,7 +89237,7 @@ function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } - _$ieee754_241.write(buf, value, offset, littleEndian, 23, 4) + _$ieee754_298.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } @@ -88455,7 +89255,7 @@ function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } - _$ieee754_241.write(buf, value, offset, littleEndian, 52, 8) + _$ieee754_298.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } @@ -88713,7 +89513,7 @@ function utf16leToBytes (str, units) { } function base64ToBytes (str) { - return _$base64Js_54.toByteArray(base64clean(str)) + return _$base64Js_55.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { @@ -88784,28 +89584,28 @@ function dupe(count, value) { return [] } -var _$dupe_133 = dupe -var _$pool_360 = {}; +var _$dupe_136 = dupe +var _$pool_422 = {}; (function (global,Buffer){ 'use strict' -/* removed: var _$twiddle_72 = require('bit-twiddle') */; -/* removed: var _$dupe_133 = require('dup') */; +/* removed: var _$twiddle_73 = require('bit-twiddle') */; +/* removed: var _$dupe_136 = require('dup') */; //Legacy pool support if(!global.__TYPEDARRAY_POOL) { global.__TYPEDARRAY_POOL = { - UINT8 : _$dupe_133([32, 0]) - , UINT16 : _$dupe_133([32, 0]) - , UINT32 : _$dupe_133([32, 0]) - , INT8 : _$dupe_133([32, 0]) - , INT16 : _$dupe_133([32, 0]) - , INT32 : _$dupe_133([32, 0]) - , FLOAT : _$dupe_133([32, 0]) - , DOUBLE : _$dupe_133([32, 0]) - , DATA : _$dupe_133([32, 0]) - , UINT8C : _$dupe_133([32, 0]) - , BUFFER : _$dupe_133([32, 0]) + UINT8 : _$dupe_136([32, 0]) + , UINT16 : _$dupe_136([32, 0]) + , UINT32 : _$dupe_136([32, 0]) + , INT8 : _$dupe_136([32, 0]) + , INT16 : _$dupe_136([32, 0]) + , INT32 : _$dupe_136([32, 0]) + , FLOAT : _$dupe_136([32, 0]) + , DOUBLE : _$dupe_136([32, 0]) + , DATA : _$dupe_136([32, 0]) + , UINT8C : _$dupe_136([32, 0]) + , BUFFER : _$dupe_136([32, 0]) } } @@ -88814,19 +89614,19 @@ var POOL = global.__TYPEDARRAY_POOL //Upgrade pool if(!POOL.UINT8C) { - POOL.UINT8C = _$dupe_133([32, 0]) + POOL.UINT8C = _$dupe_136([32, 0]) } if(!POOL.BUFFER) { - POOL.BUFFER = _$dupe_133([32, 0]) + POOL.BUFFER = _$dupe_136([32, 0]) } //New technique: Only allocate from ArrayBufferView and Buffer var DATA = POOL.DATA , BUFFER = POOL.BUFFER -_$pool_360.free = function free(array) { +_$pool_422.free = function free(array) { if(Buffer.isBuffer(array)) { - BUFFER[_$twiddle_72.log2(array.length)].push(array) + BUFFER[_$twiddle_73.log2(array.length)].push(array) } else { if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { array = array.buffer @@ -88835,7 +89635,7 @@ _$pool_360.free = function free(array) { return } var n = array.length || array.byteLength - var log_n = _$twiddle_72.log2(n)|0 + var log_n = _$twiddle_73.log2(n)|0 DATA[log_n].push(array) } } @@ -88845,7 +89645,7 @@ function freeArrayBuffer(buffer) { return } var n = buffer.length || buffer.byteLength - var log_n = _$twiddle_72.log2(n) + var log_n = _$twiddle_73.log2(n) DATA[log_n].push(buffer) } @@ -88853,26 +89653,26 @@ function freeTypedArray(array) { freeArrayBuffer(array.buffer) } -_$pool_360.freeUint8 = -_$pool_360.freeUint16 = -_$pool_360.freeUint32 = -_$pool_360.freeInt8 = -_$pool_360.freeInt16 = -_$pool_360.freeInt32 = -_$pool_360.freeFloat32 = -_$pool_360.freeFloat = -_$pool_360.freeFloat64 = -_$pool_360.freeDouble = -_$pool_360.freeUint8Clamped = -_$pool_360.freeDataView = freeTypedArray +_$pool_422.freeUint8 = +_$pool_422.freeUint16 = +_$pool_422.freeUint32 = +_$pool_422.freeInt8 = +_$pool_422.freeInt16 = +_$pool_422.freeInt32 = +_$pool_422.freeFloat32 = +_$pool_422.freeFloat = +_$pool_422.freeFloat64 = +_$pool_422.freeDouble = +_$pool_422.freeUint8Clamped = +_$pool_422.freeDataView = freeTypedArray -_$pool_360.freeArrayBuffer = freeArrayBuffer +_$pool_422.freeArrayBuffer = freeArrayBuffer -_$pool_360.freeBuffer = function freeBuffer(array) { - BUFFER[_$twiddle_72.log2(array.length)].push(array) +_$pool_422.freeBuffer = function freeBuffer(array) { + BUFFER[_$twiddle_73.log2(array.length)].push(array) } -_$pool_360.malloc = function malloc(n, dtype) { +_$pool_422.malloc = function malloc(n, dtype) { if(dtype === undefined || dtype === 'arraybuffer') { return mallocArrayBuffer(n) } else { @@ -88911,55 +89711,55 @@ _$pool_360.malloc = function malloc(n, dtype) { } function mallocArrayBuffer(n) { - var n = _$twiddle_72.nextPow2(n) - var log_n = _$twiddle_72.log2(n) + var n = _$twiddle_73.nextPow2(n) + var log_n = _$twiddle_73.log2(n) var d = DATA[log_n] if(d.length > 0) { return d.pop() } return new ArrayBuffer(n) } -_$pool_360.mallocArrayBuffer = mallocArrayBuffer +_$pool_422.mallocArrayBuffer = mallocArrayBuffer function mallocUint8(n) { return new Uint8Array(mallocArrayBuffer(n), 0, n) } -_$pool_360.mallocUint8 = mallocUint8 +_$pool_422.mallocUint8 = mallocUint8 function mallocUint16(n) { return new Uint16Array(mallocArrayBuffer(2*n), 0, n) } -_$pool_360.mallocUint16 = mallocUint16 +_$pool_422.mallocUint16 = mallocUint16 function mallocUint32(n) { return new Uint32Array(mallocArrayBuffer(4*n), 0, n) } -_$pool_360.mallocUint32 = mallocUint32 +_$pool_422.mallocUint32 = mallocUint32 function mallocInt8(n) { return new Int8Array(mallocArrayBuffer(n), 0, n) } -_$pool_360.mallocInt8 = mallocInt8 +_$pool_422.mallocInt8 = mallocInt8 function mallocInt16(n) { return new Int16Array(mallocArrayBuffer(2*n), 0, n) } -_$pool_360.mallocInt16 = mallocInt16 +_$pool_422.mallocInt16 = mallocInt16 function mallocInt32(n) { return new Int32Array(mallocArrayBuffer(4*n), 0, n) } -_$pool_360.mallocInt32 = mallocInt32 +_$pool_422.mallocInt32 = mallocInt32 function mallocFloat(n) { return new Float32Array(mallocArrayBuffer(4*n), 0, n) } -_$pool_360.mallocFloat32 = _$pool_360.mallocFloat = mallocFloat +_$pool_422.mallocFloat32 = _$pool_422.mallocFloat = mallocFloat function mallocDouble(n) { return new Float64Array(mallocArrayBuffer(8*n), 0, n) } -_$pool_360.mallocFloat64 = _$pool_360.mallocDouble = mallocDouble +_$pool_422.mallocFloat64 = _$pool_422.mallocDouble = mallocDouble function mallocUint8Clamped(n) { if(hasUint8C) { @@ -88968,25 +89768,25 @@ function mallocUint8Clamped(n) { return mallocUint8(n) } } -_$pool_360.mallocUint8Clamped = mallocUint8Clamped +_$pool_422.mallocUint8Clamped = mallocUint8Clamped function mallocDataView(n) { return new DataView(mallocArrayBuffer(n), 0, n) } -_$pool_360.mallocDataView = mallocDataView +_$pool_422.mallocDataView = mallocDataView function mallocBuffer(n) { - n = _$twiddle_72.nextPow2(n) - var log_n = _$twiddle_72.log2(n) + n = _$twiddle_73.nextPow2(n) + var log_n = _$twiddle_73.log2(n) var cache = BUFFER[log_n] if(cache.length > 0) { return cache.pop() } return new Buffer(n) } -_$pool_360.mallocBuffer = mallocBuffer +_$pool_422.mallocBuffer = mallocBuffer -_$pool_360.clearCache = function clearCache() { +_$pool_422.clearCache = function clearCache() { for(var i=0; i<32; ++i) { POOL.UINT8[i].length = 0 POOL.UINT16[i].length = 0 @@ -89001,12 +89801,12 @@ _$pool_360.clearCache = function clearCache() { BUFFER[i].length = 0 } } -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_$buffer_84.Buffer) +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},_$buffer_85.Buffer) "use strict" -/* removed: var _$pool_360 = require("typedarray-pool") */; -/* removed: var _$ndarrayOps_271 = require("ndarray-ops") */; -/* removed: var _$wrappedNDArrayCtor_277 = require("ndarray") */; +/* removed: var _$pool_422 = require("typedarray-pool") */; +/* removed: var _$ndarrayOps_329 = require("ndarray-ops") */; +/* removed: var _$wrappedNDArrayCtor_335 = require("ndarray") */; var SUPPORTED_TYPES = [ "uint8", @@ -89026,17 +89826,17 @@ function GLBuffer(gl, type, handle, length, usage) { this.usage = usage } -var __proto_153 = GLBuffer.prototype +var __proto_210 = GLBuffer.prototype -__proto_153.bind = function() { +__proto_210.bind = function() { this.gl.bindBuffer(this.type, this.handle) } -__proto_153.unbind = function() { +__proto_210.unbind = function() { this.gl.bindBuffer(this.type, null) } -__proto_153.dispose = function() { +__proto_210.dispose = function() { this.gl.deleteBuffer(this.handle) } @@ -89054,7 +89854,7 @@ function updateTypeArray(gl, type, len, usage, data, offset) { } function makeScratchTypeArray(array, dtype) { - var res = _$pool_360.malloc(array.length, dtype) + var res = _$pool_422.malloc(array.length, dtype) var n = array.length for(var i=0; i= 0) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type for attribute ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid data type for attribute ' + name + ': ' + type) } addVectorAttribute( gl @@ -89442,7 +90242,7 @@ function createAttributeWrapper( } else if(type.indexOf('mat') >= 0) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type for attribute ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid data type for attribute ' + name + ': ' + type) } addMatrixAttribute( gl @@ -89453,7 +90253,7 @@ function createAttributeWrapper( , obj , name) } else { - throw new _$GLError_207('', 'Unknown data type for attribute ' + name + ': ' + type) + throw new _$GLError_264('', 'Unknown data type for attribute ' + name + ': ' + type) } break } @@ -89463,7 +90263,7 @@ function createAttributeWrapper( 'use strict' -var _$makeReflectTypes_210 = makeReflectTypes +var _$makeReflectTypes_267 = makeReflectTypes //Construct type info for reflection. // @@ -89520,10 +90320,10 @@ function makeReflectTypes(uniforms, useIndex) { } 'use strict' -/* removed: var _$makeReflectTypes_210 = require('./reflect') */; -/* removed: var _$GLError_207 = require("./GLError") */; +/* removed: var _$makeReflectTypes_267 = require('./reflect') */; +/* removed: var _$GLError_264 = require("./GLError") */; -var _$createUniformWrapper_209 = createUniformWrapper +var _$createUniformWrapper_266 = createUniformWrapper //Binds a function and returns a value function identity(x) { @@ -89565,7 +90365,7 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type') + throw new _$GLError_264('', 'Invalid data type') } switch(type.charAt(0)) { case 'b': @@ -89574,16 +90374,16 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { case 'v': return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' default: - throw new _$GLError_207('', 'Unrecognized data type for vector ' + name + ': ' + type) + throw new _$GLError_264('', 'Unrecognized data type for vector ' + name + ': ' + type) } } else if(type.indexOf('mat') === 0 && type.length === 4) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' } else { - throw new _$GLError_207('', 'Unknown uniform data type for ' + name + ': ' + type) + throw new _$GLError_264('', 'Unknown uniform data type for ' + name + ': ' + type) } break } @@ -89642,7 +90442,7 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid data type') + throw new _$GLError_264('', 'Invalid data type') } if(type.charAt(0) === 'b') { return makeVector(d, false) @@ -89651,11 +90451,11 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { } else if(type.indexOf('mat') === 0 && type.length === 4) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { - throw new _$GLError_207('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + throw new _$GLError_264('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } return makeVector(d*d, 0) } else { - throw new _$GLError_207('', 'Unknown uniform data type for ' + name + ': ' + type) + throw new _$GLError_264('', 'Unknown uniform data type for ' + name + ': ' + type) } break } @@ -89701,7 +90501,7 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { } //Return data - var coallesced = _$makeReflectTypes_210(uniforms, true) + var coallesced = _$makeReflectTypes_267(uniforms, true) return { get: identity(processObject(coallesced)), set: makeSetter(coallesced), @@ -89710,11 +90510,11 @@ function createUniformWrapper(gl, wrapper, uniforms, locations) { } } -var _$runtimeReflect_211 = {}; +var _$runtimeReflect_268 = {}; 'use strict' -_$runtimeReflect_211.uniforms = runtimeUniforms -_$runtimeReflect_211.attributes = runtimeAttributes +_$runtimeReflect_268.uniforms = runtimeUniforms +_$runtimeReflect_268.attributes = runtimeAttributes var GL_TO_GLSL_TYPES = { 'FLOAT': 'float', @@ -89810,7 +90610,7 @@ var cache; * Expose `repeat` */ -var _$repeat_316 = repeat; +var _$repeat_380 = repeat; /** * Repeat the given `string` the specified `number` @@ -89870,15 +90670,15 @@ function repeat(str, num) { 'use strict'; -/* removed: var _$repeat_316 = require('repeat-string'); */; +/* removed: var _$repeat_380 = require('repeat-string'); */; -var _$padLeft_284 = function padLeft(str, num, ch) { +var _$padLeft_342 = function padLeft(str, num, ch) { ch = typeof ch !== 'undefined' ? (ch + '') : ' '; - return _$repeat_316(ch, num) + str; + return _$repeat_380(ch, num) + str; }; -/* removed: var _$padLeft_284 = require('pad-left') */; +/* removed: var _$padLeft_342 = require('pad-left') */; -var _$addLineNumbers_44 = addLineNumbers +var _$addLineNumbers_45 = addLineNumbers function addLineNumbers (string, start, delim) { start = typeof start === 'number' ? start : 1 delim = delim || ': ' @@ -89888,12 +90688,12 @@ function addLineNumbers (string, start, delim) { return lines.map(function (line, i) { var c = i + start var digits = String(c).length - var prefix = _$padLeft_284(c, totalDigits - digits) + var prefix = _$padLeft_342(c, totalDigits - digits) return prefix + delim + line }).join('\n') } -var _$numbers_154 = { +var _$numbers_211 = { 0: 'NONE', 1: 'ONE', 2: 'LINE_LOOP', @@ -90192,17 +90992,17 @@ var _$numbers_154 = { 37444: 'BROWSER_DEFAULT_WEBGL' } -/* removed: var _$numbers_154 = require('./1.0/numbers') */; +/* removed: var _$numbers_211 = require('./1.0/numbers') */; -var _$lookupConstant_155 = function lookupConstant (number) { - return _$numbers_154[number] +var _$lookupConstant_212 = function lookupConstant (number) { + return _$numbers_211[number] } -var _$_atob_52 = function _atob(str) { +var _$_atob_53 = function _atob(str) { return atob(str) } -var _$builtins_233 = [ +var _$builtins_290 = [ // Keep this list sorted 'abs' , 'acos' @@ -90354,15 +91154,15 @@ var _$builtins_233 = [ ] // 300es builtins/reserved words that were previously valid in v100 -/* removed: var _$builtins_233 = require('./builtins') */; +/* removed: var _$builtins_290 = require('./builtins') */; // The texture2D|Cube functions have been removed // And the gl_ features are updated -_$builtins_233 = _$builtins_233.slice().filter(function (b) { +_$builtins_290 = _$builtins_290.slice().filter(function (b) { return !/^(gl\_|texture)/.test(b) }) -var _$builtins300es_232 = _$builtins_233.concat([ +var _$builtins300es_289 = _$builtins_290.concat([ // the updated gl_ constants 'gl_VertexID' , 'gl_InstanceID' @@ -90423,7 +91223,7 @@ var _$builtins300es_232 = _$builtins_233.concat([ , 'textureProjGradOffset' ]) -var _$literals_235 = [ +var _$literals_292 = [ // current 'precision' , 'highp' @@ -90517,9 +91317,9 @@ var _$literals_235 = [ , 'using' ] -/* removed: var _$literals_235 = require('./literals') */; +/* removed: var _$literals_292 = require('./literals') */; -var _$literals300es_234 = _$literals_235.slice().concat([ +var _$literals300es_291 = _$literals_292.slice().concat([ 'layout' , 'centroid' , 'smooth' @@ -90606,7 +91406,7 @@ var _$literals300es_234 = _$literals_235.slice().concat([ , 'usampler2DMSArray' ]) -var _$operators_236 = [ +var _$operators_293 = [ '<<=' , '>>=' , '++' @@ -90654,13 +91454,13 @@ var _$operators_236 = [ , '}' ] -var _$tokenize_231 = tokenize +var _$tokenize_288 = tokenize -var __dummy_231$0 = 0 - , __dummy_231$1 = 0 - , __dummy_231$2 = 0 - , __dummy_231$3 = 0 - , __dummy_231$4 = 0 +var __dummy_288$0 = 0 + , __dummy_288$1 = 0 + , __dummy_288$2 = 0 + , __dummy_288$3 = 0 + , __dummy_288$4 = 0 var NORMAL = 999 // <-- never emitted , TOKEN = 9999 // <-- never emitted @@ -90711,11 +91511,11 @@ function tokenize(opt) { , len opt = opt || {} - var allBuiltins = _$builtins_233 - var allLiterals = _$literals_235 + var allBuiltins = _$builtins_290 + var allLiterals = _$literals_292 if (opt.version === '300 es') { - allBuiltins = _$builtins300es_232 - allLiterals = _$literals300es_234 + allBuiltins = _$builtins300es_289 + allLiterals = _$literals300es_291 } return function(data) { @@ -90906,8 +91706,8 @@ function tokenize(opt) { , res do { - idx = _$operators_236.indexOf(buf.slice(0, buf.length + j).join('')) - res = _$operators_236[idx] + idx = _$operators_293.indexOf(buf.slice(0, buf.length + j).join('')) + res = _$operators_293[idx] if(idx === -1) { if(j-- + buf.length > 0) continue @@ -91017,12 +91817,12 @@ function tokenize(opt) { } } -/* removed: var _$tokenize_231 = require('./index') */; +/* removed: var _$tokenize_288 = require('./index') */; -var _$tokenizeString_237 = tokenizeString +var _$tokenizeString_294 = tokenizeString function tokenizeString(str, opt) { - var generator = _$tokenize_231(opt) + var generator = _$tokenize_288(opt) var tokens = [] tokens = tokens.concat(generator(str)) @@ -91031,15 +91831,15 @@ function tokenizeString(str, opt) { return tokens } -/* removed: var _$tokenizeString_237 = require('glsl-tokenizer') */; -/* removed: var _$_atob_52 = require('atob-lite') */; +/* removed: var _$tokenizeString_294 = require('glsl-tokenizer') */; +/* removed: var _$_atob_53 = require('atob-lite') */; -var _$getName_230 = getName +var _$getName_287 = getName function getName(src) { var tokens = Array.isArray(src) ? src - : _$tokenizeString_237(src) + : _$tokenizeString_294(src) for (var i = 0; i < tokens.length; i++) { var token = tokens[i] @@ -91051,11 +91851,11 @@ function getName(src) { var b64 = match[1] var name = match[2] - return (b64 ? _$_atob_52(name) : name).trim() + return (b64 ? _$_atob_53(name) : name).trim() } } -var _$sprintf_343 = {}; +var _$sprintf_405 = {}; /* global window, exports, define */ !function() { @@ -91255,9 +92055,9 @@ var _$sprintf_343 = {}; * export to either browser or node.js */ /* eslint-disable quote-props */ - if (typeof _$sprintf_343 !== 'undefined') { - _$sprintf_343['sprintf'] = sprintf - _$sprintf_343['vsprintf'] = vsprintf + if (typeof _$sprintf_405 !== 'undefined') { + _$sprintf_405['sprintf'] = sprintf + _$sprintf_405['vsprintf'] = vsprintf } if (typeof window !== 'undefined') { window['sprintf'] = sprintf @@ -91276,21 +92076,21 @@ var _$sprintf_343 = {}; }() -var sprintf = _$sprintf_343.sprintf; -/* removed: var _$lookupConstant_155 = require('gl-constants/lookup'); */; -/* removed: var _$getName_230 = require('glsl-shader-name'); */; -/* removed: var _$addLineNumbers_44 = require('add-line-numbers'); */; +var sprintf = _$sprintf_405.sprintf; +/* removed: var _$lookupConstant_212 = require('gl-constants/lookup'); */; +/* removed: var _$getName_287 = require('glsl-shader-name'); */; +/* removed: var _$addLineNumbers_45 = require('add-line-numbers'); */; -var _$formatCompilerError_159 = formatCompilerError; +var _$formatCompilerError_216 = formatCompilerError; function formatCompilerError(errLog, src, type) { "use strict"; - var name = _$getName_230(src) || 'of unknown name (see npm glsl-shader-name)'; + var name = _$getName_287(src) || 'of unknown name (see npm glsl-shader-name)'; var typeName = 'unknown type'; if (type !== undefined) { - typeName = type === _$lookupConstant_155.FRAGMENT_SHADER ? 'fragment' : 'vertex' + typeName = type === _$lookupConstant_212.FRAGMENT_SHADER ? 'fragment' : 'vertex' } var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name); @@ -91309,7 +92109,7 @@ function formatCompilerError(errLog, src, type) { errors[lineNo] = errorString; } - var lines = _$addLineNumbers_44(src).split('\n'); + var lines = _$addLineNumbers_45(src).split('\n'); for (var i = 0; i < lines.length; i++) { if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue; @@ -91329,7 +92129,7 @@ function formatCompilerError(errLog, src, type) { } -var _$hiddenStore_371 = hiddenStore; +var _$hiddenStore_433 = hiddenStore; function hiddenStore(obj, key) { var store = { identity: key }; @@ -91346,9 +92146,9 @@ function hiddenStore(obj, key) { return store; } -/* removed: var _$hiddenStore_371 = require('./hidden-store.js'); */; +/* removed: var _$hiddenStore_433 = require('./hidden-store.js'); */; -var _$createStore_370 = createStore; +var _$createStore_432 = createStore; function createStore() { var key = {}; @@ -91362,7 +92162,7 @@ function createStore() { var store = obj.valueOf(key); return store && store.identity === key ? - store : _$hiddenStore_371(obj, key); + store : _$hiddenStore_433(obj, key); }; } @@ -91370,12 +92170,12 @@ function createStore() { // https://gist.github.com/Gozala/1269991 // This is a reimplemented version (with a few bug fixes). -/* removed: var _$createStore_370 = require('./create-store.js'); */; +/* removed: var _$createStore_432 = require('./create-store.js'); */; -var _$weakMap_372 = weakMap; +var _$weakMap_434 = weakMap; function weakMap() { - var privates = _$createStore_370(); + var privates = _$createStore_432(); return { 'get': function (key, fallback) { @@ -91396,17 +92196,17 @@ function weakMap() { } } -var _$shaderCache_212 = {}; +var _$shaderCache_269 = {}; 'use strict' -_$shaderCache_212.shader = getShaderReference -_$shaderCache_212.program = createProgram +_$shaderCache_269.shader = getShaderReference +_$shaderCache_269.program = createProgram -/* removed: var _$GLError_207 = require("./GLError") */; -/* removed: var _$formatCompilerError_159 = require('gl-format-compiler-error'); */; +/* removed: var _$GLError_264 = require("./GLError") */; +/* removed: var _$formatCompilerError_216 = require('gl-format-compiler-error'); */; -var __weakMap_212 = typeof WeakMap === 'undefined' ? _$weakMap_372 : WeakMap -var CACHE = new __weakMap_212() +var __weakMap_269 = typeof WeakMap === 'undefined' ? _$weakMap_434 : WeakMap +var CACHE = new __weakMap_269() var SHADER_COUNTER = 0 @@ -91447,7 +92247,7 @@ function ContextCache(gl) { this.programs = {} } -var __proto_212 = ContextCache.prototype +var __proto_269 = ContextCache.prototype function compileShader(gl, type, src) { var shader = gl.createShader(type) @@ -91456,17 +92256,17 @@ function compileShader(gl, type, src) { if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { var errLog = gl.getShaderInfoLog(shader) try { - var fmt = _$formatCompilerError_159(errLog, src, type); + var fmt = _$formatCompilerError_216(errLog, src, type); } catch (e){ console.warn('Failed to format compiler error: ' + e); - throw new _$GLError_207(errLog, 'Error compiling shader:\n' + errLog) + throw new _$GLError_264(errLog, 'Error compiling shader:\n' + errLog) } - throw new _$GLError_207(errLog, fmt.short, fmt.long) + throw new _$GLError_264(errLog, fmt.short, fmt.long) } return shader } -__proto_212.getShaderReference = function(type, src) { +__proto_269.getShaderReference = function(type, src) { var gl = this.gl var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0] var shader = shaders[src] @@ -91496,12 +92296,12 @@ function linkProgram(gl, vshader, fshader, attribs, locations) { gl.linkProgram(program) if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { var errLog = gl.getProgramInfoLog(program) - throw new _$GLError_207(errLog, 'Error linking program: ' + errLog) + throw new _$GLError_264(errLog, 'Error linking program: ' + errLog) } return program } -__proto_212.getProgram = function(vref, fref, attribs, locations) { +__proto_269.getProgram = function(vref, fref, attribs, locations) { var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') var prog = this.programs[token] if(!prog || !this.gl.isProgram(prog)) { @@ -91536,12 +92336,12 @@ function createProgram(gl, vref, fref, attribs, locations) { 'use strict' -/* removed: var _$createUniformWrapper_209 = require('./lib/create-uniforms') */; -/* removed: var _$createAttributeWrapper_208 = require('./lib/create-attributes') */; -/* removed: var _$makeReflectTypes_210 = require('./lib/reflect') */; -/* removed: var _$shaderCache_212 = require('./lib/shader-cache') */; -/* removed: var _$runtimeReflect_211 = require('./lib/runtime-reflect') */; -/* removed: var _$GLError_207 = require("./lib/GLError") */; +/* removed: var _$createUniformWrapper_266 = require('./lib/create-uniforms') */; +/* removed: var _$createAttributeWrapper_265 = require('./lib/create-attributes') */; +/* removed: var _$makeReflectTypes_267 = require('./lib/reflect') */; +/* removed: var _$shaderCache_269 = require('./lib/shader-cache') */; +/* removed: var _$runtimeReflect_268 = require('./lib/runtime-reflect') */; +/* removed: var _$GLError_264 = require("./lib/GLError") */; //Shader object function Shader(gl) { @@ -91560,9 +92360,9 @@ function Shader(gl) { this.types = null } -var __proto_206 = Shader.prototype +var __proto_263 = Shader.prototype -__proto_206.bind = function() { +__proto_263.bind = function() { if(!this.program) { this._relink() } @@ -91587,7 +92387,7 @@ __proto_206.bind = function() { this.gl.useProgram(this.program) } -__proto_206.dispose = function() { +__proto_263.dispose = function() { // disabling vertex attributes so new shader starts with zero // and it's also useful if all shaders are disposed but the @@ -91622,7 +92422,7 @@ function compareAttributes(a, b) { } //Update export hook for glslify-live -__proto_206.update = function( +__proto_263.update = function( vertSource , fragSource , uniforms @@ -91642,13 +92442,13 @@ __proto_206.update = function( //Compile vertex and fragment shaders var pvref = wrapper._vref - wrapper._vref = _$shaderCache_212.shader(gl, gl.VERTEX_SHADER, vertSource) + wrapper._vref = _$shaderCache_269.shader(gl, gl.VERTEX_SHADER, vertSource) if(pvref) { pvref.dispose() } wrapper.vertShader = wrapper._vref.shader var pfref = this._fref - wrapper._fref = _$shaderCache_212.shader(gl, gl.FRAGMENT_SHADER, fragSource) + wrapper._fref = _$shaderCache_269.shader(gl, gl.FRAGMENT_SHADER, fragSource) if(pfref) { pfref.dispose() } @@ -91664,12 +92464,12 @@ __proto_206.update = function( gl.linkProgram(testProgram) if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) { var errLog = gl.getProgramInfoLog(testProgram) - throw new _$GLError_207(errLog, 'Error linking program:' + errLog) + throw new _$GLError_264(errLog, 'Error linking program:' + errLog) } //Load data from runtime - uniforms = uniforms || _$runtimeReflect_211.uniforms(gl, testProgram) - attributes = attributes || _$runtimeReflect_211.attributes(gl, testProgram) + uniforms = uniforms || _$runtimeReflect_268.uniforms(gl, testProgram) + attributes = attributes || _$runtimeReflect_268.attributes(gl, testProgram) //Release test program gl.deleteProgram(testProgram) @@ -91737,7 +92537,7 @@ __proto_206.update = function( //Rebuild program and recompute all uniform locations var uniformLocations = new Array(uniforms.length) function relink() { - wrapper.program = _$shaderCache_212.program( + wrapper.program = _$shaderCache_269.program( gl , wrapper._vref , wrapper._fref @@ -91759,19 +92559,19 @@ __proto_206.update = function( //Generate type info wrapper.types = { - uniforms: _$makeReflectTypes_210(uniforms), - attributes: _$makeReflectTypes_210(attributes) + uniforms: _$makeReflectTypes_267(uniforms), + attributes: _$makeReflectTypes_267(attributes) } //Generate attribute wrappers - wrapper.attributes = _$createAttributeWrapper_208( + wrapper.attributes = _$createAttributeWrapper_265( gl , wrapper , attributeUnpacked , attributeLocations) //Generate uniform wrappers - Object.defineProperty(wrapper, 'uniforms', _$createUniformWrapper_209( + Object.defineProperty(wrapper, 'uniforms', _$createUniformWrapper_266( gl , wrapper , uniforms @@ -91797,16 +92597,16 @@ function createShader( return shader } -var _$createShader_206 = createShader +var _$createShader_263 = createShader 'use strict' -var _$createBoxes_188 = createBoxes +var _$createBoxes_245 = createBoxes -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -/* removed: var _$shaders_191 = require('./shaders') */; +/* removed: var _$shaders_248 = require('./shaders') */; function Boxes(plot, vbo, shader) { this.plot = plot @@ -91814,9 +92614,9 @@ function Boxes(plot, vbo, shader) { this.shader = shader } -var __proto_188 = Boxes.prototype +var __proto_245 = Boxes.prototype -__proto_188.bind = function() { +__proto_245.bind = function() { var shader = this.shader this.vbo.bind() this.shader.bind() @@ -91824,7 +92624,7 @@ __proto_188.bind = function() { shader.uniforms.screenBox = this.plot.screenBox } -__proto_188.drawBox = (function() { +__proto_245.drawBox = (function() { var lo = [0,0] var hi = [0,0] return function(loX, loY, hiX, hiY, color) { @@ -91845,19 +92645,19 @@ __proto_188.drawBox = (function() { } }()) -__proto_188.dispose = function() { +__proto_245.dispose = function() { this.vbo.dispose() this.shader.dispose() } function createBoxes(plot) { var gl = plot.gl - var vbo = _$createBuffer_153(gl, [ + var vbo = _$createBuffer_210(gl, [ 0,0, 0,1, 1,0, 1,1]) - var shader = _$createShader_206(gl, _$shaders_191.boxVert, _$shaders_191.lineFrag) + var shader = _$createShader_263(gl, _$shaders_248.boxVert, _$shaders_248.lineFrag) return new Boxes(plot, vbo, shader) } @@ -91905,7 +92705,7 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_90 = { +var _$searchBounds_91 = { ge: compileBoundsSearch(">=", false, "GE"), gt: compileBoundsSearch(">", false, "GT"), lt: compileBoundsSearch("<", true, "LT"), @@ -91915,7 +92715,7 @@ var _$searchBounds_90 = { "use strict" -function __compileSearch_193(funcName, predicate, reversed, extraArgs, earlyOut) { +function __compileSearch_250(funcName, predicate, reversed, extraArgs, earlyOut) { var code = [ "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), @@ -91943,10 +92743,10 @@ function __compileSearch_193(funcName, predicate, reversed, extraArgs, earlyOut) return code.join("") } -function __compileBoundsSearch_193(predicate, reversed, suffix, earlyOut) { +function __compileBoundsSearch_250(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_193("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_193("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), + __compileSearch_250("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_250("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), "function dispatchBsearch", suffix, "(a,y,c,l,h){\ if(typeof(c)==='function'){\ return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ @@ -91957,22 +92757,22 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_193 = { - ge: __compileBoundsSearch_193(">=", false, "GE"), - gt: __compileBoundsSearch_193(">", false, "GT"), - lt: __compileBoundsSearch_193("<", true, "LT"), - le: __compileBoundsSearch_193("<=", true, "LE"), - eq: __compileBoundsSearch_193("-", true, "EQ", true) +var _$searchBounds_250 = { + ge: __compileBoundsSearch_250(">=", false, "GE"), + gt: __compileBoundsSearch_250(">", false, "GT"), + lt: __compileBoundsSearch_250("<", true, "LT"), + le: __compileBoundsSearch_250("<=", true, "LE"), + eq: __compileBoundsSearch_250("-", true, "EQ", true) } 'use strict' -var _$createGrid_189 = createGrid +var _$createGrid_246 = createGrid -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$searchBounds_193 = require('binary-search-bounds') */; -/* removed: var _$shaders_191 = require('./shaders') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$searchBounds_250 = require('binary-search-bounds') */; +/* removed: var _$shaders_248 = require('./shaders') */; function Grid(plot, vbo, shader, tickShader) { this.plot = plot @@ -91986,9 +92786,9 @@ function compareTickNum(a, b) { return a - b } -var __proto_189 = Grid.prototype +var __proto_246 = Grid.prototype -__proto_189.draw = (function() { +__proto_246.draw = (function() { var DATA_SHIFT = [0,0] var DATA_SCALE = [0,0] @@ -92041,7 +92841,7 @@ __proto_189.draw = (function() { } })() -__proto_189.drawTickMarks = (function() { +__proto_246.drawTickMarks = (function() { var DATA_SHIFT = [0,0] var DATA_SCALE = [0,0] var X_AXIS = [1,0] @@ -92098,13 +92898,13 @@ __proto_189.drawTickMarks = (function() { var xTicksOffset = 0 var yTicksOffset = ticks[0].length * 6 - var xStart = Math.min(_$searchBounds_193.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xEnd = Math.min(_$searchBounds_193.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xStart = Math.min(_$searchBounds_250.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xEnd = Math.min(_$searchBounds_250.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) var xOffset = xTicksOffset + 6 * xStart var xCount = 6 * Math.max(0, xEnd - xStart) - var yStart = Math.min(_$searchBounds_193.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yEnd = Math.min(_$searchBounds_193.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yStart = Math.min(_$searchBounds_250.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yEnd = Math.min(_$searchBounds_250.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) var yOffset = yTicksOffset + 6 * yStart var yCount = 6 * Math.max(0, yEnd - yStart) @@ -92162,7 +92962,7 @@ __proto_189.drawTickMarks = (function() { } })() -__proto_189.update = (function() { +__proto_246.update = (function() { var OFFSET_X = [1, 1, -1, -1, 1, -1] var OFFSET_Y = [1, -1, 1, 1, -1, -1] @@ -92196,7 +92996,7 @@ __proto_189.update = (function() { } })() -__proto_189.dispose = function() { +__proto_246.dispose = function() { this.vbo.dispose() this.shader.dispose() this.tickShader.dispose() @@ -92204,21 +93004,21 @@ __proto_189.dispose = function() { function createGrid(plot) { var gl = plot.gl - var vbo = _$createBuffer_153(gl) - var shader = _$createShader_206(gl, _$shaders_191.gridVert, _$shaders_191.gridFrag) - var tickShader = _$createShader_206(gl, _$shaders_191.tickVert, _$shaders_191.gridFrag) + var vbo = _$createBuffer_210(gl) + var shader = _$createShader_263(gl, _$shaders_248.gridVert, _$shaders_248.gridFrag) + var tickShader = _$createShader_263(gl, _$shaders_248.tickVert, _$shaders_248.gridFrag) var grid = new Grid(plot, vbo, shader, tickShader) return grid } 'use strict' -var _$createLines_190 = createLines +var _$createLines_247 = createLines -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -/* removed: var _$shaders_191 = require('./shaders') */; +/* removed: var _$shaders_248 = require('./shaders') */; function Lines(plot, vbo, shader) { this.plot = plot @@ -92226,9 +93026,9 @@ function Lines(plot, vbo, shader) { this.shader = shader } -var __proto_190 = Lines.prototype +var __proto_247 = Lines.prototype -__proto_190.bind = function() { +__proto_247.bind = function() { var shader = this.shader this.vbo.bind() this.shader.bind() @@ -92236,7 +93036,7 @@ __proto_190.bind = function() { shader.uniforms.screenBox = this.plot.screenBox } -__proto_190.drawLine = (function() { +__proto_247.drawLine = (function() { var start = [0,0] var end = [0,0] return function(startX, startY, endX, endY, width, color) { @@ -92258,26 +93058,26 @@ __proto_190.drawLine = (function() { } }()) -__proto_190.dispose = function() { +__proto_247.dispose = function() { this.vbo.dispose() this.shader.dispose() } function createLines(plot) { var gl = plot.gl - var vbo = _$createBuffer_153(gl, [ + var vbo = _$createBuffer_210(gl, [ -1,-1, -1,1, 1,-1, 1,1]) - var shader = _$createShader_206(gl, _$shaders_191.lineVert, _$shaders_191.lineFrag) + var shader = _$createShader_263(gl, _$shaders_248.lineVert, _$shaders_248.lineFrag) var lines = new Lines(plot, vbo, shader) return lines } "use strict" -var _$twoProduct_358 = twoProduct +var _$twoProduct_420 = twoProduct var SPLITTER = +(Math.pow(2, 27) + 1.0) @@ -92310,7 +93110,7 @@ function twoProduct(a, b, result) { } "use strict" -var _$fastTwoSum_359 = fastTwoSum +var _$fastTwoSum_421 = fastTwoSum function fastTwoSum(a, b, result) { var x = a + b @@ -92327,15 +93127,15 @@ function fastTwoSum(a, b, result) { } "use strict" -/* removed: var _$twoProduct_358 = require("two-product") */; -/* removed: var _$fastTwoSum_359 = require("two-sum") */; +/* removed: var _$twoProduct_420 = require("two-product") */; +/* removed: var _$fastTwoSum_421 = require("two-sum") */; -var _$scaleLinearExpansion_325 = scaleLinearExpansion +var _$scaleLinearExpansion_389 = scaleLinearExpansion function scaleLinearExpansion(e, scale) { var n = e.length if(n === 1) { - var ts = _$twoProduct_358(e[0], scale) + var ts = _$twoProduct_420(e[0], scale) if(ts[0]) { return ts } @@ -92345,14 +93145,14 @@ function scaleLinearExpansion(e, scale) { var q = [0.1, 0.1] var t = [0.1, 0.1] var count = 0 - _$twoProduct_358(e[0], scale, q) + _$twoProduct_420(e[0], scale, q) if(q[0]) { g[count++] = q[0] } for(var i=1; i>1 - return ["sum(", __generateSum_323(expr.slice(0, m)), ",", __generateSum_323(expr.slice(m)), ")"].join("") + return ["sum(", __generateSum_387(expr.slice(0, m)), ",", __generateSum_387(expr.slice(m)), ")"].join("") } } -function __determinant_323(m) { +function __determinant_387(m) { if(m.length === 2) { return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] } else { var expr = [] for(var i=0; i= 0 + return _$searchBounds_91.eq(this.edges, e, compareLex) >= 0 } })() -__proto_89.removeTriangle = function(i, j, k) { +__proto_90.removeTriangle = function(i, j, k) { var stars = this.stars removePair(stars[i], j, k) removePair(stars[j], k, i) removePair(stars[k], i, j) } -__proto_89.addTriangle = function(i, j, k) { +__proto_90.addTriangle = function(i, j, k) { var stars = this.stars stars[i].push(j, k) stars[j].push(k, i) stars[k].push(i, j) } -__proto_89.opposite = function(j, i) { +__proto_90.opposite = function(j, i) { var list = this.stars[i] for(var k=1, n=list.length; k>> 31 +_$double_133.sign = function(n) { + return _$double_133.hi(n) >>> 31 } -_$double_130.exponent = function(n) { - var b = _$double_130.hi(n) +_$double_133.exponent = function(n) { + var b = _$double_133.hi(n) return ((b<<1) >>> 21) - 1023 } -_$double_130.fraction = function(n) { - var lo = _$double_130.lo(n) - var hi = _$double_130.hi(n) +_$double_133.fraction = function(n) { + var lo = _$double_133.lo(n) + var hi = _$double_133.hi(n) var b = hi & ((1<<20) - 1) if(hi & 0x7ff00000) { b += (1<<20) @@ -97268,42 +98068,42 @@ _$double_130.fraction = function(n) { return [lo, b] } -_$double_130.denormalized = function(n) { - var hi = _$double_130.hi(n) +_$double_133.denormalized = function(n) { + var hi = _$double_133.hi(n) return !(hi & 0x7ff00000) } -}).call(this,_$buffer_84.Buffer) +}).call(this,_$buffer_85.Buffer) 'use strict' -/* removed: var _$bn_74 = require('bn.js') */; -/* removed: var _$double_130 = require('double-bits') */; +/* removed: var _$bn_75 = require('bn.js') */; +/* removed: var _$double_133 = require('double-bits') */; -var _$num2bn_64 = num2bn +var _$num2bn_65 = num2bn function num2bn(x) { - var e = _$double_130.exponent(x) + var e = _$double_133.exponent(x) if(e < 52) { - return new _$bn_74(x) + return new _$bn_75(x) } else { - return (new _$bn_74(x * Math.pow(2, 52-e))).ushln(e-52) + return (new _$bn_75(x * Math.pow(2, 52-e))).ushln(e-52) } } 'use strict' -/* removed: var _$num2bn_64 = require('./num-to-bn') */; -/* removed: var _$sign_60 = require('./bn-sign') */; +/* removed: var _$num2bn_65 = require('./num-to-bn') */; +/* removed: var _$sign_61 = require('./bn-sign') */; -var _$rationalize_65 = rationalize +var _$rationalize_66 = rationalize function rationalize(numer, denom) { - var snumer = _$sign_60(numer) - var sdenom = _$sign_60(denom) + var snumer = _$sign_61(numer) + var sdenom = _$sign_61(denom) if(snumer === 0) { - return [_$num2bn_64(0), _$num2bn_64(1)] + return [_$num2bn_65(0), _$num2bn_65(1)] } if(sdenom === 0) { - return [_$num2bn_64(0), _$num2bn_64(0)] + return [_$num2bn_65(0), _$num2bn_65(0)] } if(sdenom < 0) { numer = numer.neg() @@ -97318,19 +98118,19 @@ function rationalize(numer, denom) { 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$div_57 = div +var _$div_58 = div function div(a, b) { - return _$rationalize_65(a[0].mul(b[1]), a[1].mul(b[0])) + return _$rationalize_66(a[0].mul(b[1]), a[1].mul(b[0])) } 'use strict' -/* removed: var _$bn_74 = require('bn.js') */; +/* removed: var _$bn_75 = require('bn.js') */; -var _$isBN_63 = isBN +var _$isBN_64 = isBN //Test if x is a bignumber //FIXME: obviously this is the wrong way to do it @@ -97340,90 +98140,90 @@ function isBN(x) { 'use strict' -/* removed: var _$isBN_63 = require('./lib/is-bn') */; +/* removed: var _$isBN_64 = require('./lib/is-bn') */; -var _$isRat_59 = isRat +var _$isRat_60 = isRat function isRat(x) { - return Array.isArray(x) && x.length === 2 && _$isBN_63(x[0]) && _$isBN_63(x[1]) + return Array.isArray(x) && x.length === 2 && _$isBN_64(x[0]) && _$isBN_64(x[1]) } 'use strict' -/* removed: var _$bn_74 = require('bn.js') */; +/* removed: var _$bn_75 = require('bn.js') */; -var _$str2BN_66 = str2BN +var _$str2BN_67 = str2BN function str2BN(x) { - return new _$bn_74(x) + return new _$bn_75(x) } 'use strict' -/* removed: var _$isRat_59 = require('./is-rat') */; -/* removed: var _$isBN_63 = require('./lib/is-bn') */; -/* removed: var _$num2bn_64 = require('./lib/num-to-bn') */; -/* removed: var _$str2BN_66 = require('./lib/str-to-bn') */; -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; -/* removed: var _$div_57 = require('./div') */; +/* removed: var _$isRat_60 = require('./is-rat') */; +/* removed: var _$isBN_64 = require('./lib/is-bn') */; +/* removed: var _$num2bn_65 = require('./lib/num-to-bn') */; +/* removed: var _$str2BN_67 = require('./lib/str-to-bn') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; +/* removed: var _$div_58 = require('./div') */; -var _$makeRational_58 = makeRational +var _$makeRational_59 = makeRational function makeRational(numer, denom) { - if(_$isRat_59(numer)) { + if(_$isRat_60(numer)) { if(denom) { - return _$div_57(numer, makeRational(denom)) + return _$div_58(numer, makeRational(denom)) } return [numer[0].clone(), numer[1].clone()] } var shift = 0 var a, b - if(_$isBN_63(numer)) { + if(_$isBN_64(numer)) { a = numer.clone() } else if(typeof numer === 'string') { - a = _$str2BN_66(numer) + a = _$str2BN_67(numer) } else if(numer === 0) { - return [_$num2bn_64(0), _$num2bn_64(1)] + return [_$num2bn_65(0), _$num2bn_65(1)] } else if(numer === Math.floor(numer)) { - a = _$num2bn_64(numer) + a = _$num2bn_65(numer) } else { while(numer !== Math.floor(numer)) { numer = numer * Math.pow(2, 256) shift -= 256 } - a = _$num2bn_64(numer) + a = _$num2bn_65(numer) } - if(_$isRat_59(denom)) { + if(_$isRat_60(denom)) { a.mul(denom[1]) b = denom[0].clone() - } else if(_$isBN_63(denom)) { + } else if(_$isBN_64(denom)) { b = denom.clone() } else if(typeof denom === 'string') { - b = _$str2BN_66(denom) + b = _$str2BN_67(denom) } else if(!denom) { - b = _$num2bn_64(1) + b = _$num2bn_65(1) } else if(denom === Math.floor(denom)) { - b = _$num2bn_64(denom) + b = _$num2bn_65(denom) } else { while(denom !== Math.floor(denom)) { denom = denom * Math.pow(2, 256) shift += 256 } - b = _$num2bn_64(denom) + b = _$num2bn_65(denom) } if(shift > 0) { a = a.ushln(shift) } else if(shift < 0) { b = b.ushln(-shift) } - return _$rationalize_65(a, b) + return _$rationalize_66(a, b) } 'use strict' -/* removed: var _$sign_60 = require('./bn-sign') */; +/* removed: var _$sign_61 = require('./bn-sign') */; -var _$bn2num_61 = bn2num +var _$bn2num_62 = bn2num //TODO: Make this better function bn2num(b) { @@ -97440,23 +98240,23 @@ function bn2num(b) { out += w * Math.pow(0x4000000, i) } } - return _$sign_60(b) * out + return _$sign_61(b) * out } 'use strict' -/* removed: var _$double_130 = require('double-bits') */; -var ctz = _$twiddle_72.countTrailingZeros +/* removed: var _$double_133 = require('double-bits') */; +var ctz = _$twiddle_73.countTrailingZeros -var _$ctzNumber_62 = ctzNumber +var _$ctzNumber_63 = ctzNumber //Counts the number of trailing zeros function ctzNumber(x) { - var l = ctz(_$double_130.lo(x)) + var l = ctz(_$double_133.lo(x)) if(l < 32) { return l } - var h = ctz(_$double_130.hi(x)) + var h = ctz(_$double_133.hi(x)) if(h > 20) { return 52 } @@ -97465,10 +98265,10 @@ function ctzNumber(x) { 'use strict' -/* removed: var _$bn2num_61 = require('./lib/bn-to-num') */; -/* removed: var _$ctzNumber_62 = require('./lib/ctz') */; +/* removed: var _$bn2num_62 = require('./lib/bn-to-num') */; +/* removed: var _$ctzNumber_63 = require('./lib/ctz') */; -var _$roundRat_70 = roundRat +var _$roundRat_71 = roundRat // Round a rational to the closest float function roundRat (f) { @@ -97479,19 +98279,19 @@ function roundRat (f) { } var h = a.abs().divmod(b.abs()) var iv = h.div - var x = _$bn2num_61(iv) + var x = _$bn2num_62(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 = _$ctzNumber_62(x) + 4 - var y = _$bn2num_61(ir.ushln(s).divRound(b)) + var s = _$ctzNumber_63(x) + 4 + var y = _$bn2num_62(ir.ushln(s).divRound(b)) return sgn * (x + y * Math.pow(2, -s)) } else { var ybits = b.bitLength() - ir.bitLength() + 53 - var y = _$bn2num_61(ir.ushln(ybits).divRound(b)) + var y = _$bn2num_62(ir.ushln(ybits).divRound(b)) if (ybits < 1023) { return sgn * y * Math.pow(2, -ybits) } @@ -97500,7 +98300,7 @@ function roundRat (f) { } } -var _$brute_77 = {}; +var _$brute_78 = {}; 'use strict' var DIMENSION = 'd' @@ -97643,13 +98443,13 @@ function bruteForcePlanner(full) { } -_$brute_77.partial = bruteForcePlanner(false) -_$brute_77.full = bruteForcePlanner(true) +_$brute_78.partial = bruteForcePlanner(false) +_$brute_78.full = bruteForcePlanner(true) 'use strict' -var _$genPartition_80 = genPartition +var _$genPartition_81 = genPartition -var __code_80 = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' +var __code_81 = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' function genPartition(predicate, args) { var fargs ='abcdef'.split('').concat(args) @@ -97661,17 +98461,17 @@ function genPartition(predicate, args) { reads.push('hi=e[k+o]') } fargs.push( - __code_80.replace('_', reads.join()) + __code_81.replace('_', reads.join()) .replace('$', predicate)) return Function.apply(void 0, fargs) } 'use strict' -var _$findMedian_79 = findMedian +var _$findMedian_80 = findMedian -/* removed: var _$genPartition_80 = require('./partition') */; +/* removed: var _$genPartition_81 = require('./partition') */; -var partitionStartLessThan = _$genPartition_80('loright var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 var blueActive = 0 @@ -98223,7 +99023,7 @@ function sweepComplete(d, visit, //process events from left->right var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 var blueActive = 0 @@ -98333,7 +99133,7 @@ function scanBipartite( //process events from left->right var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 for(var i=0; iright var n = ptr >>> 1 - _$wrapper_81(SWEEP_EVENTS, n) + _$wrapper_82(SWEEP_EVENTS, n) var redActive = 0 for(var i=0; i=p0)&&!(p1>=hi)', ['p0', 'p1']) -var partitionStartEqual = _$genPartition_80( +var partitionStartEqual = _$genPartition_81( 'lo===p0', ['p0']) -var __partitionStartLessThan_78 = _$genPartition_80( +var __partitionStartLessThan_79 = _$genPartition_81( 'lo mid point // - var blue0 = _$findMedian_79( + var blue0 = _$findMedian_80( d, axis, blueStart, blueEnd, blue, blueIndex) var mid = blue[elemSize * blue0 + axis] @@ -98881,7 +99681,7 @@ function boxIntersectIter( //Degenerate sweep intersection: // [red0, redX] with [blue0, blue1] if(red0 < redX) { - retval = _$sweep_82.sweepComplete( + retval = _$sweep_83.sweepComplete( d, visit, red0, redX, red, redIndex, blue0, blue1, blue, blueIndex) @@ -98893,7 +99693,7 @@ function boxIntersectIter( //Normal sweep intersection: // [redX, red1] with [blue0, blue1] if(redX < red1) { - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, redX, red1, red, redIndex, blue0, blue1, blue, blueIndex) @@ -98941,12 +99741,12 @@ function boxIntersectIter( if(red0 < red1) { if(axis === d-2) { if(flip) { - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, blue0, blue1, blue, blueIndex, red0, red1, red, redIndex) } else { - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, red0, red1, red, redIndex, blue0, blue1, blue, blueIndex) @@ -98973,11 +99773,11 @@ function boxIntersectIter( } 'use strict' -var _$boxIntersectWrapper_76 = boxIntersectWrapper +var _$boxIntersectWrapper_77 = boxIntersectWrapper -/* removed: var _$pool_360 = require('typedarray-pool') */; -/* removed: var _$sweep_82 = require('./lib/sweep') */; -/* removed: var _$boxIntersectIter_78 = require('./lib/intersect') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; +/* removed: var _$sweep_83 = require('./lib/sweep') */; +/* removed: var _$boxIntersectIter_79 = require('./lib/intersect') */; function boxEmpty(d, box) { for(var j=0; j 0) { if(d === 1 && full) { //Special case: 1d complete - _$sweep_82.init(n) - retval = _$sweep_82.sweepComplete( + _$sweep_83.init(n) + retval = _$sweep_83.sweepComplete( d, visit, 0, n, redList, redIds, 0, n, redList, redIds) } else { //Convert blue boxes - var blueList = _$pool_360.mallocDouble(2*d*m) - var blueIds = _$pool_360.mallocInt32(m) + var blueList = _$pool_422.mallocDouble(2*d*m) + var blueIds = _$pool_422.mallocInt32(m) m = convertBoxes(blue, d, blueList, blueIds) if(m > 0) { - _$sweep_82.init(n+m) + _$sweep_83.init(n+m) if(d === 1) { //Special case: 1d bipartite - retval = _$sweep_82.sweepBipartite( + retval = _$sweep_83.sweepBipartite( d, visit, 0, n, redList, redIds, 0, m, blueList, blueIds) } else { //General case: d>1 - retval = _$boxIntersectIter_78( + retval = _$boxIntersectIter_79( d, visit, full, n, redList, redIds, m, blueList, blueIds) } - _$pool_360.free(blueList) - _$pool_360.free(blueIds) + _$pool_422.free(blueList) + _$pool_422.free(blueIds) } } - _$pool_360.free(redList) - _$pool_360.free(redIds) + _$pool_422.free(redList) + _$pool_422.free(redIds) } return retval @@ -99111,107 +99911,107 @@ function boxIntersectWrapper(arg0, arg1, arg2) { } 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$mul_67 = mul +var _$mul_68 = mul function mul(a, b) { - return _$rationalize_65(a[0].mul(b[0]), a[1].mul(b[1])) + return _$rationalize_66(a[0].mul(b[0]), a[1].mul(b[1])) } 'use strict' -/* removed: var _$sign_60 = require('./lib/bn-sign') */; +/* removed: var _$sign_61 = require('./lib/bn-sign') */; -var _$sign_68 = __sign_68 +var _$sign_69 = __sign_69 -function __sign_68(x) { - return _$sign_60(x[0]) * _$sign_60(x[1]) +function __sign_69(x) { + return _$sign_61(x[0]) * _$sign_61(x[1]) } 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$sub_69 = sub +var _$sub_70 = sub function sub(a, b) { - return _$rationalize_65(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) + return _$rationalize_66(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) } 'use strict' -/* removed: var _$rationalize_65 = require('./lib/rationalize') */; +/* removed: var _$rationalize_66 = require('./lib/rationalize') */; -var _$add_55 = add +var _$add_56 = add function add(a, b) { - return _$rationalize_65( + return _$rationalize_66( a[0].mul(b[1]).add(b[0].mul(a[1])), a[1].mul(b[1])) } 'use strict' -/* removed: var _$add_55 = require('big-rat/add') */; +/* removed: var _$add_56 = require('big-rat/add') */; -var _$add_306 = __add_306 +var _$add_369 = __add_369 -function __add_306 (a, b) { +function __add_369 (a, b) { var n = a.length var r = new Array(n) for (var i=0; i>>0 -var _$nextafter_278 = nextafter +var _$nextafter_336 = nextafter function nextafter(x, y) { if(isNaN(x) || isNaN(y)) { @@ -99264,8 +100064,8 @@ function nextafter(x, y) { return SMALLEST_DENORM } } - var hi = _$double_130.hi(x) - var lo = _$double_130.lo(x) + var hi = _$double_133.hi(x) + var lo = _$double_133.lo(x) if((y > x) === (x > 0)) { if(lo === UINT_MAX) { hi += 1 @@ -99281,27 +100081,27 @@ function nextafter(x, y) { lo -= 1 } } - return _$double_130.pack(lo, hi) + return _$double_133.pack(lo, hi) } 'use strict' -var _$float2rat_307 = float2rat +var _$float2rat_370 = float2rat -/* removed: var _$makeRational_58 = require('big-rat') */; +/* removed: var _$makeRational_59 = require('big-rat') */; function float2rat(v) { var result = new Array(v.length) for(var i=0; i 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { return false } - var x1 = __orient_326(b0, a0, a1) - var y1 = __orient_326(b1, a0, a1) + var x1 = __orient_390(b0, a0, a1) + var y1 = __orient_390(b1, a0, a1) if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { return false } @@ -99346,7 +100146,7 @@ function __segmentsIntersect_326(a0, a1, b0, b1) { } "use strict"; "use restrict"; -var _$UnionFind_361 = UnionFind; +var _$UnionFind_423 = UnionFind; function UnionFind(count) { this.roots = new Array(count); @@ -99358,22 +100158,22 @@ function UnionFind(count) { } } -var __proto_361 = UnionFind.prototype +var __proto_423 = UnionFind.prototype -Object.defineProperty(__proto_361, "length", { +Object.defineProperty(__proto_423, "length", { "get": function() { return this.roots.length } }) -__proto_361.makeSet = function() { +__proto_423.makeSet = function() { var n = this.roots.length; this.roots.push(n); this.ranks.push(0); return n; } -__proto_361.find = function(x) { +__proto_423.find = function(x) { var x0 = x var roots = this.roots; while(roots[x] !== x) { @@ -99387,7 +100187,7 @@ __proto_361.find = function(x) { return x; } -__proto_361.link = function(x, y) { +__proto_423.link = function(x, y) { var xr = this.find(x) , yr = this.find(y); if(xr === yr) { @@ -99408,25 +100208,25 @@ __proto_361.link = function(x, y) { } 'use strict' -var _$cleanPSLG_95 = cleanPSLG +var _$cleanPSLG_96 = cleanPSLG -/* removed: var _$UnionFind_361 = require('union-find') */; -/* removed: var _$boxIntersectWrapper_76 = require('box-intersect') */; -/* removed: var _$segmentsIntersect_326 = require('robust-segment-intersect') */; -/* removed: var _$makeRational_58 = require('big-rat') */; -/* removed: var _$cmp_56 = require('big-rat/cmp') */; -/* removed: var _$roundRat_70 = require('big-rat/to-float') */; -/* removed: var _$float2rat_307 = require('rat-vec') */; -/* removed: var _$nextafter_278 = require('nextafter') */; +/* removed: var _$UnionFind_423 = require('union-find') */; +/* removed: var _$boxIntersectWrapper_77 = require('box-intersect') */; +/* removed: var _$segmentsIntersect_390 = require('robust-segment-intersect') */; +/* removed: var _$makeRational_59 = require('big-rat') */; +/* removed: var _$cmp_57 = require('big-rat/cmp') */; +/* removed: var _$roundRat_71 = require('big-rat/to-float') */; +/* removed: var _$float2rat_370 = require('rat-vec') */; +/* removed: var _$nextafter_336 = require('nextafter') */; -/* removed: var _$solveIntersection_96 = require('./lib/rat-seg-intersect') */; +/* removed: var _$solveIntersection_97 = require('./lib/rat-seg-intersect') */; // Bounds on a rational number when rounded to a float function boundRat (r) { - var f = _$roundRat_70(r) + var f = _$roundRat_71(r) return [ - _$nextafter_278(f, -Infinity), - _$nextafter_278(f, Infinity) + _$nextafter_336(f, -Infinity), + _$nextafter_336(f, Infinity) ] } @@ -99438,10 +100238,10 @@ function boundEdges (points, edges) { var a = points[e[0]] var b = points[e[1]] bounds[i] = [ - _$nextafter_278(Math.min(a[0], b[0]), -Infinity), - _$nextafter_278(Math.min(a[1], b[1]), -Infinity), - _$nextafter_278(Math.max(a[0], b[0]), Infinity), - _$nextafter_278(Math.max(a[1], b[1]), Infinity) + _$nextafter_336(Math.min(a[0], b[0]), -Infinity), + _$nextafter_336(Math.min(a[1], b[1]), -Infinity), + _$nextafter_336(Math.max(a[0], b[0]), Infinity), + _$nextafter_336(Math.max(a[1], b[1]), Infinity) ] } return bounds @@ -99453,10 +100253,10 @@ function boundPoints (points) { for (var i = 0; i < points.length; ++i) { var p = points[i] bounds[i] = [ - _$nextafter_278(p[0], -Infinity), - _$nextafter_278(p[1], -Infinity), - _$nextafter_278(p[0], Infinity), - _$nextafter_278(p[1], Infinity) + _$nextafter_336(p[0], -Infinity), + _$nextafter_336(p[1], -Infinity), + _$nextafter_336(p[0], Infinity), + _$nextafter_336(p[1], Infinity) ] } return bounds @@ -99465,7 +100265,7 @@ function boundPoints (points) { // Find all pairs of crossing edges in a pslg (given edge bounds) function getCrossings (points, edges, edgeBounds) { var result = [] - _$boxIntersectWrapper_76(edgeBounds, function (i, j) { + _$boxIntersectWrapper_77(edgeBounds, function (i, j) { var e = edges[i] var f = edges[j] if (e[0] === f[0] || e[0] === f[1] || @@ -99476,7 +100276,7 @@ function getCrossings (points, edges, edgeBounds) { var b = points[e[1]] var c = points[f[0]] var d = points[f[1]] - if (_$segmentsIntersect_326(a, b, c, d)) { + if (_$segmentsIntersect_390(a, b, c, d)) { result.push([i, j]) } }) @@ -99486,7 +100286,7 @@ function getCrossings (points, edges, edgeBounds) { // Find all pairs of crossing vertices in a pslg (given edge/vert bounds) function getTJunctions (points, edges, edgeBounds, vertBounds) { var result = [] - _$boxIntersectWrapper_76(edgeBounds, vertBounds, function (i, v) { + _$boxIntersectWrapper_77(edgeBounds, vertBounds, function (i, v) { var e = edges[i] if (e[0] === v || e[1] === v) { return @@ -99494,7 +100294,7 @@ function getTJunctions (points, edges, edgeBounds, vertBounds) { var p = points[v] var a = points[e[0]] var b = points[e[1]] - if (_$segmentsIntersect_326(a, b, p, p)) { + if (_$segmentsIntersect_390(a, b, p, p)) { result.push([i, v]) } }) @@ -99508,8 +100308,8 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { // Convert crossings into tjunctions by constructing rational points var ratPoints = floatPoints.map(function(p) { return [ - _$makeRational_58(p[0]), - _$makeRational_58(p[1]) + _$makeRational_59(p[0]), + _$makeRational_59(p[1]) ] }) for (i = 0; i < crossings.length; ++i) { @@ -99518,17 +100318,17 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { var f = crossing[1] var ee = edges[e] var ef = edges[f] - var x = _$solveIntersection_96( - _$float2rat_307(floatPoints[ee[0]]), - _$float2rat_307(floatPoints[ee[1]]), - _$float2rat_307(floatPoints[ef[0]]), - _$float2rat_307(floatPoints[ef[1]])) + var x = _$solveIntersection_97( + _$float2rat_370(floatPoints[ee[0]]), + _$float2rat_370(floatPoints[ee[1]]), + _$float2rat_370(floatPoints[ef[0]]), + _$float2rat_370(floatPoints[ef[1]])) if (!x) { // Segments are parallel, should already be handled by t-junctions continue } var idx = floatPoints.length - floatPoints.push([_$roundRat_70(x[0]), _$roundRat_70(x[1])]) + floatPoints.push([_$roundRat_71(x[0]), _$roundRat_71(x[1])]) ratPoints.push(x) junctions.push([e, idx], [f, idx]) } @@ -99540,7 +100340,7 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { } var u = ratPoints[a[1]] var v = ratPoints[b[1]] - return _$cmp_56(u[0], v[0]) || _$cmp_56(u[1], v[1]) + return _$cmp_57(u[0], v[0]) || _$cmp_57(u[1], v[1]) }) // Split edges along junctions @@ -99598,7 +100398,7 @@ function cutEdges (floatPoints, edges, crossings, junctions, useColor) { // Merge overlapping points function dedupPoints (floatPoints, ratPoints, floatBounds) { var numPoints = ratPoints.length - var uf = new _$UnionFind_361(numPoints) + var uf = new _$UnionFind_423(numPoints) // Compute rational bounds var bounds = [] @@ -99607,15 +100407,15 @@ function dedupPoints (floatPoints, ratPoints, floatBounds) { var xb = boundRat(p[0]) var yb = boundRat(p[1]) bounds.push([ - _$nextafter_278(xb[0], -Infinity), - _$nextafter_278(yb[0], -Infinity), - _$nextafter_278(xb[1], Infinity), - _$nextafter_278(yb[1], Infinity) + _$nextafter_336(xb[0], -Infinity), + _$nextafter_336(yb[0], -Infinity), + _$nextafter_336(xb[1], Infinity), + _$nextafter_336(yb[1], Infinity) ]) } // Link all points with over lapping boxes - _$boxIntersectWrapper_76(bounds, function (i, j) { + _$boxIntersectWrapper_77(bounds, function (i, j) { uf.link(i, j) }) @@ -99790,9 +100590,9 @@ function cleanPSLG (points, edges, colors) { "use strict" -var _$edgeToAdjacency_135 = edgeToAdjacency +var _$edgeToAdjacency_138 = edgeToAdjacency -/* removed: var _$unique_362 = require("uniq") */; +/* removed: var _$unique_424 = require("uniq") */; function edgeToAdjacency(edges, numVertices) { var numEdges = edges.length @@ -99815,7 +100615,7 @@ function edgeToAdjacency(edges, numVertices) { adj[e[1]].push(e[0]) } for(var j=0; j 0) { return 1 } return 0.0 } "use strict" -var _$compareAngle_106 = compareAngle +var _$compareAngle_107 = compareAngle -/* removed: var _$orientation_323 = require("robust-orientation") */; -/* removed: var _$signum_329 = require("signum") */; -/* removed: var _$fastTwoSum_359 = require("two-sum") */; -/* removed: var _$robustProduct_324 = require("robust-product") */; -/* removed: var _$linearExpansionSum_328 = require("robust-sum") */; +/* removed: var _$orientation_387 = require("robust-orientation") */; +/* removed: var _$signum_393 = require("signum") */; +/* removed: var _$fastTwoSum_421 = require("two-sum") */; +/* removed: var _$robustProduct_388 = require("robust-product") */; +/* removed: var _$linearExpansionSum_392 = require("robust-sum") */; function testInterior(a, b, c) { - var x0 = _$fastTwoSum_359(a[0], -b[0]) - var y0 = _$fastTwoSum_359(a[1], -b[1]) - var x1 = _$fastTwoSum_359(c[0], -b[0]) - var y1 = _$fastTwoSum_359(c[1], -b[1]) + var x0 = _$fastTwoSum_421(a[0], -b[0]) + var y0 = _$fastTwoSum_421(a[1], -b[1]) + var x1 = _$fastTwoSum_421(c[0], -b[0]) + var y1 = _$fastTwoSum_421(c[1], -b[1]) - var d = _$linearExpansionSum_328( - _$robustProduct_324(x0, x1), - _$robustProduct_324(y0, y1)) + var d = _$linearExpansionSum_392( + _$robustProduct_388(x0, x1), + _$robustProduct_388(y0, y1)) return d[d.length-1] >= 0 } function compareAngle(a, b, c, d) { - var bcd = _$orientation_323(b, c, d) + var bcd = _$orientation_387(b, c, d) if(bcd === 0) { //Handle degenerate cases - var sabc = _$signum_329(_$orientation_323(a, b, c)) - var sabd = _$signum_329(_$orientation_323(a, b, d)) + var sabc = _$signum_393(_$orientation_387(a, b, c)) + var sabd = _$signum_393(_$orientation_387(a, b, d)) if(sabc === sabd) { if(sabc === 0) { var ic = testInterior(a, b, c) @@ -99916,21 +100716,21 @@ function compareAngle(a, b, c, d) { return -1 } } - return _$signum_329(sabd - sabc) + return _$signum_393(sabd - sabc) } - var abc = _$orientation_323(a, b, c) + var abc = _$orientation_387(a, b, c) if(abc > 0) { - if(bcd > 0 && _$orientation_323(a, b, d) > 0) { + if(bcd > 0 && _$orientation_387(a, b, d) > 0) { return 1 } return -1 } else if(abc < 0) { - if(bcd > 0 || _$orientation_323(a, b, d) > 0) { + if(bcd > 0 || _$orientation_387(a, b, d) > 0) { return 1 } return -1 } else { - var abd = _$orientation_323(a, b, d) + var abd = _$orientation_387(a, b, d) if(abd > 0) { return 1 } else { @@ -99944,9 +100744,9 @@ function compareAngle(a, b, c, d) { } "use strict" -var _$planarDual_291 = planarDual +var _$planarDual_350 = planarDual -/* removed: var _$compareAngle_106 = require("compare-angle") */; +/* removed: var _$compareAngle_107 = require("compare-angle") */; function planarDual(cells, positions) { @@ -99995,7 +100795,7 @@ function planarDual(cells, positions) { for(var k=0; k>>1,x=a", useNdarray ? ".get(m)" : "[m]"] return code.join("") } -function __compileBoundsSearch_71(predicate, reversed, suffix, earlyOut) { +function __compileBoundsSearch_72(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_71("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), - __compileSearch_71("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), - __compileSearch_71("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), - __compileSearch_71("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut), + __compileSearch_72("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut), + __compileSearch_72("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut), + __compileSearch_72("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut), + __compileSearch_72("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'){\ @@ -100180,23 +100980,23 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_71 = { - ge: __compileBoundsSearch_71(">=", false, "GE"), - gt: __compileBoundsSearch_71(">", false, "GT"), - lt: __compileBoundsSearch_71("<", true, "LT"), - le: __compileBoundsSearch_71("<=", true, "LE"), - eq: __compileBoundsSearch_71("-", true, "EQ", true) +var _$searchBounds_72 = { + ge: __compileBoundsSearch_72(">=", false, "GE"), + gt: __compileBoundsSearch_72(">", false, "GT"), + lt: __compileBoundsSearch_72("<", true, "LT"), + le: __compileBoundsSearch_72("<=", true, "LE"), + eq: __compileBoundsSearch_72("-", true, "EQ", true) } "use strict" -/* removed: var _$searchBounds_71 = require("binary-search-bounds") */; +/* removed: var _$searchBounds_72 = require("binary-search-bounds") */; var NOT_FOUND = 0 var SUCCESS = 1 var EMPTY = 2 -var _$createWrapper_243 = createWrapper +var _$createWrapper_300 = createWrapper function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { this.mid = mid @@ -100207,7 +101007,7 @@ function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length } -var __proto_243 = IntervalTreeNode.prototype +var __proto_300 = IntervalTreeNode.prototype function copy(a, b) { a.mid = b.mid @@ -100245,7 +101045,7 @@ function rebuildWithoutInterval(node, interval) { return SUCCESS } -__proto_243.intervals = function(result) { +__proto_300.intervals = function(result) { result.push.apply(result, this.leftPoints) if(this.left) { this.left.intervals(result) @@ -100256,7 +101056,7 @@ __proto_243.intervals = function(result) { return result } -__proto_243.insert = function(interval) { +__proto_300.insert = function(interval) { var weight = this.count - this.leftPoints.length this.count += 1 if(interval[1] < this.mid) { @@ -100280,14 +101080,14 @@ __proto_243.insert = function(interval) { this.right = createIntervalTree([interval]) } } else { - var l = _$searchBounds_71.ge(this.leftPoints, interval, compareBegin) - var r = _$searchBounds_71.ge(this.rightPoints, interval, compareEnd) + var l = _$searchBounds_72.ge(this.leftPoints, interval, compareBegin) + var r = _$searchBounds_72.ge(this.rightPoints, interval, compareEnd) this.leftPoints.splice(l, 0, interval) this.rightPoints.splice(r, 0, interval) } } -__proto_243.remove = function(interval) { +__proto_300.remove = function(interval) { var weight = this.count - this.leftPoints if(interval[1] < this.mid) { if(!this.left) { @@ -100358,14 +101158,14 @@ __proto_243.remove = function(interval) { } return SUCCESS } - for(var l = _$searchBounds_71.ge(this.leftPoints, interval, compareBegin); l 0) { @@ -101707,8 +102507,8 @@ function searchBucket(root, p) { return lastNode } -__proto_339.castUp = function(p) { - var bucket = _$searchBounds_71.le(this.coordinates, p[0]) +__proto_403.castUp = function(p) { + var bucket = _$searchBounds_72.le(this.coordinates, p[0]) if(bucket < 0) { return -1 } @@ -101728,7 +102528,7 @@ __proto_339.castUp = function(p) { var otherHitNode = searchBucket(this.slabs[bucket-1], p) if(otherHitNode) { if(lastSegment) { - if(_$orderSegments_338(otherHitNode.key, lastSegment) > 0) { + if(_$orderSegments_402(otherHitNode.key, lastSegment) > 0) { lastSegment = otherHitNode.key lastHit = otherHitNode.value } @@ -101740,7 +102540,7 @@ __proto_339.castUp = function(p) { } var horiz = this.horizontal[bucket] if(horiz.length > 0) { - var hbucket = _$searchBounds_71.ge(horiz, p[1], compareHorizontal) + var hbucket = _$searchBounds_72.ge(horiz, p[1], compareHorizontal) if(hbucket < horiz.length) { var e = horiz[hbucket] if(p[1] === e.y) { @@ -101766,7 +102566,7 @@ __proto_339.castUp = function(p) { //Check if e is above/below last segment if(e.start) { if(lastSegment) { - var o = _$orientation_323(lastSegment[0], lastSegment[1], [p[0], e.y]) + var o = _$orientation_387(lastSegment[0], lastSegment[1], [p[0], e.y]) if(lastSegment[0][0] > lastSegment[1][0]) { o = -o } @@ -101792,7 +102592,7 @@ function IntervalSegment(y, index, start, closed) { this.closed = closed } -function __Event_339(x, segment, create, index) { +function __Event_403(x, segment, create, index) { this.x = x this.segment = segment this.create = create @@ -101807,8 +102607,8 @@ function createSlabDecomposition(segments) { for(var i=0; i 0 } @@ -102105,7 +102905,7 @@ function planarGraphToPolyline(edges, positions) { var loopVertices = faces[i].map(function(v) { return positions[v] }) - var pmc = _$preprocessPolygon_294([loopVertices]) + var pmc = _$preprocessPolygon_356([loopVertices]) var count = 0 outer: for(var j=0; j 0) { var top = toVisit.pop() var nbhd = fadj[top] - _$unique_362(nbhd, function(a,b) { + _$unique_424(nbhd, function(a,b) { return a-b }) var nnbhr = nbhd.length @@ -102230,11 +103030,11 @@ function planarGraphToPolyline(edges, positions) { return result } -var _$topology_333 = {}; +var _$topology_397 = {}; "use strict"; "use restrict"; -var __dummy_333$0 = 0 - , __dummy_333$1 = 0 +var __dummy_397$0 = 0 + , __dummy_397$1 = 0 //Returns the dimension of a cell complex function dimension(cells) { @@ -102245,7 +103045,7 @@ function dimension(cells) { } return d-1 } -_$topology_333.dimension = dimension +_$topology_397.dimension = dimension //Counts the number of vertices in faces function countVertices(cells) { @@ -102259,7 +103059,7 @@ function countVertices(cells) { } return vc+1 } -_$topology_333.countVertices = countVertices +_$topology_397.countVertices = countVertices //Returns a deep copy of cells function cloneCells(cells) { @@ -102269,7 +103069,7 @@ function cloneCells(cells) { } return ncells } -_$topology_333.cloneCells = cloneCells +_$topology_397.cloneCells = cloneCells //Ranks a pair of cells up to permutation function compareCells(a, b) { @@ -102321,7 +103121,7 @@ function compareCells(a, b) { return 0 } } -_$topology_333.compareCells = compareCells +_$topology_397.compareCells = compareCells function compareZipped(a, b) { return compareCells(a[0], b[0]) @@ -102346,10 +103146,10 @@ function normalize(cells, attr) { return cells } } -_$topology_333.normalize = normalize +_$topology_397.normalize = normalize //Removes all duplicate cells in the complex -function __unique_333(cells) { +function __unique_397(cells) { if(cells.length === 0) { return [] } @@ -102368,7 +103168,7 @@ function __unique_333(cells) { cells.length = ptr return cells } -_$topology_333.unique = __unique_333; +_$topology_397.unique = __unique_397; //Finds a cell in a normalized cell complex function findCell(cells, c) { @@ -102389,7 +103189,7 @@ function findCell(cells, c) { } return r } -_$topology_333.findCell = findCell; +_$topology_397.findCell = findCell; //Builds an index for an n-cell. This is more general than dual, but less efficient function incidence(from_cells, to_cells) { @@ -102402,7 +103202,7 @@ function incidence(from_cells, to_cells) { var c = to_cells[i] var cl = c.length for(var k=1, kn=(1< 0) - (v < 0); } //Computes absolute value of integer -_$twiddle_334.abs = function(v) { - var mask = v >> (__INT_BITS_334-1); +_$twiddle_398.abs = function(v) { + var mask = v >> (__INT_BITS_398-1); return (v ^ mask) - mask; } //Computes minimum of integers x and y -_$twiddle_334.min = function(x, y) { +_$twiddle_398.min = function(x, y) { return y ^ ((x ^ y) & -(x < y)); } //Computes maximum of integers x and y -_$twiddle_334.max = function(x, y) { +_$twiddle_398.max = function(x, y) { return x ^ ((x ^ y) & -(x < y)); } //Checks if a number is a power of two -_$twiddle_334.isPow2 = function(v) { +_$twiddle_398.isPow2 = function(v) { return !(v & (v-1)) && (!!v); } //Computes log base 2 of v -_$twiddle_334.log2 = function(v) { +_$twiddle_398.log2 = function(v) { var r, shift; r = (v > 0xFFFF) << 4; v >>>= r; shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; @@ -102631,21 +103431,21 @@ _$twiddle_334.log2 = function(v) { } //Computes log base 10 of v -_$twiddle_334.log10 = function(v) { +_$twiddle_398.log10 = function(v) { return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } //Counts number of bits -_$twiddle_334.popCount = function(v) { +_$twiddle_398.popCount = function(v) { v = v - ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; } //Counts number of trailing zeros -function __countTrailingZeros_334(v) { +function __countTrailingZeros_398(v) { var c = 32; v &= -v; if (v) c--; @@ -102656,10 +103456,10 @@ function __countTrailingZeros_334(v) { if (v & 0x55555555) c -= 1; return c; } -_$twiddle_334.countTrailingZeros = __countTrailingZeros_334; +_$twiddle_398.countTrailingZeros = __countTrailingZeros_398; //Rounds to next power of 2 -_$twiddle_334.nextPow2 = function(v) { +_$twiddle_398.nextPow2 = function(v) { v += v === 0; --v; v |= v >>> 1; @@ -102671,7 +103471,7 @@ _$twiddle_334.nextPow2 = function(v) { } //Rounds down to previous power of 2 -_$twiddle_334.prevPow2 = function(v) { +_$twiddle_398.prevPow2 = function(v) { v |= v >>> 1; v |= v >>> 2; v |= v >>> 4; @@ -102681,7 +103481,7 @@ _$twiddle_334.prevPow2 = function(v) { } //Computes parity of word -_$twiddle_334.parity = function(v) { +_$twiddle_398.parity = function(v) { v ^= v >>> 16; v ^= v >>> 8; v ^= v >>> 4; @@ -102689,7 +103489,7 @@ _$twiddle_334.parity = function(v) { return (0x6996 >>> v) & 1; } -var __REVERSE_TABLE_334 = new Array(256); +var __REVERSE_TABLE_398 = new Array(256); (function(tab) { for(var i=0; i<256; ++i) { @@ -102701,18 +103501,18 @@ var __REVERSE_TABLE_334 = new Array(256); } tab[i] = (r << s) & 0xff; } -})(__REVERSE_TABLE_334); +})(__REVERSE_TABLE_398); //Reverse bits in a 32 bit word -_$twiddle_334.reverse = function(v) { - return (__REVERSE_TABLE_334[ v & 0xff] << 24) | - (__REVERSE_TABLE_334[(v >>> 8) & 0xff] << 16) | - (__REVERSE_TABLE_334[(v >>> 16) & 0xff] << 8) | - __REVERSE_TABLE_334[(v >>> 24) & 0xff]; +_$twiddle_398.reverse = function(v) { + return (__REVERSE_TABLE_398[ v & 0xff] << 24) | + (__REVERSE_TABLE_398[(v >>> 8) & 0xff] << 16) | + (__REVERSE_TABLE_398[(v >>> 16) & 0xff] << 8) | + __REVERSE_TABLE_398[(v >>> 24) & 0xff]; } //Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -_$twiddle_334.interleave2 = function(x, y) { +_$twiddle_398.interleave2 = function(x, y) { x &= 0xFFFF; x = (x | (x << 8)) & 0x00FF00FF; x = (x | (x << 4)) & 0x0F0F0F0F; @@ -102729,7 +103529,7 @@ _$twiddle_334.interleave2 = function(x, y) { } //Extracts the nth interleaved component -_$twiddle_334.deinterleave2 = function(v, n) { +_$twiddle_398.deinterleave2 = function(v, n) { v = (v >>> n) & 0x55555555; v = (v | (v >>> 1)) & 0x33333333; v = (v | (v >>> 2)) & 0x0F0F0F0F; @@ -102740,7 +103540,7 @@ _$twiddle_334.deinterleave2 = function(v, n) { //Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes -_$twiddle_334.interleave3 = function(x, y, z) { +_$twiddle_398.interleave3 = function(x, y, z) { x &= 0x3FF; x = (x | (x<<16)) & 4278190335; x = (x | (x<<8)) & 251719695; @@ -102764,7 +103564,7 @@ _$twiddle_334.interleave3 = function(x, y, z) { } //Extracts nth interleaved component of a 3-tuple -_$twiddle_334.deinterleave3 = function(v, n) { +_$twiddle_398.deinterleave3 = function(v, n) { v = (v >>> n) & 1227133513; v = (v | (v>>>2)) & 3272356035; v = (v | (v>>>4)) & 251719695; @@ -102774,17 +103574,17 @@ _$twiddle_334.deinterleave3 = function(v, n) { } //Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -_$twiddle_334.nextCombination = function(v) { +_$twiddle_398.nextCombination = function(v) { var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (__countTrailingZeros_334(v) + 1)); + return (t + 1) | (((~t & -~t) - 1) >>> (__countTrailingZeros_398(v) + 1)); } "use strict"; "use restrict"; -var _$UnionFind_336 = __UnionFind_336; +var _$UnionFind_400 = __UnionFind_400; -function __UnionFind_336(count) { +function __UnionFind_400(count) { this.roots = new Array(count); this.ranks = new Array(count); @@ -102794,18 +103594,18 @@ function __UnionFind_336(count) { } } -__UnionFind_336.prototype.length = function() { +__UnionFind_400.prototype.length = function() { return this.roots.length; } -__UnionFind_336.prototype.makeSet = function() { +__UnionFind_400.prototype.makeSet = function() { var n = this.roots.length; this.roots.push(n); this.ranks.push(0); return n; } -__UnionFind_336.prototype.find = function(x) { +__UnionFind_400.prototype.find = function(x) { var roots = this.roots; while(roots[x] !== x) { var y = roots[x]; @@ -102815,7 +103615,7 @@ __UnionFind_336.prototype.find = function(x) { return x; } -__UnionFind_336.prototype.link = function(x, y) { +__UnionFind_400.prototype.link = function(x, y) { var xr = this.find(x) , yr = this.find(y); if(xr === yr) { @@ -102836,14 +103636,14 @@ __UnionFind_336.prototype.link = function(x, y) { } -var _$topology_335 = {}; +var _$topology_399 = {}; "use strict"; "use restrict"; -var __dummy_335$0 = 0 - , __dummy_335$1 = 0 +var __dummy_399$0 = 0 + , __dummy_399$1 = 0 //Returns the dimension of a cell complex -function __dimension_335(cells) { +function __dimension_399(cells) { var d = 0 , max = Math.max for(var i=0, il=cells.length; i> 1 - , s = __compareCells_335(cells[mid], c) + , s = __compareCells_399(cells[mid], c) if(s <= 0) { if(s === 0) { r = mid @@ -102995,10 +103795,10 @@ function __findCell_335(cells, c) { } return r } -_$topology_335.findCell = __findCell_335; +_$topology_399.findCell = __findCell_399; //Builds an index for an n-cell. This is more general than dual, but less efficient -function __incidence_335(from_cells, to_cells) { +function __incidence_399(from_cells, to_cells) { var index = new Array(from_cells.length) for(var i=0, il=index.length; i= from_cells.length || __compareCells_335(from_cells[idx], b) !== 0) { + if(idx >= from_cells.length || __compareCells_399(from_cells[idx], b) !== 0) { break } } @@ -103029,12 +103829,12 @@ function __incidence_335(from_cells, to_cells) { } return index } -_$topology_335.incidence = __incidence_335 +_$topology_399.incidence = __incidence_399 //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_335(cells, vertex_count) { +function __dual_399(cells, vertex_count) { if(!vertex_count) { - return __incidence_335(__unique_335(__skeleton_335(cells, 0)), cells, 0) + return __incidence_399(__unique_399(__skeleton_399(cells, 0)), cells, 0) } var res = new Array(vertex_count) for(var i=0; i maxSize || shape[1] < 0 || shape[1] > maxSize) { throw new Error('gl-texture2d: Invalid texture size') } - var packed = __isPacked_218(shape, array.stride.slice()) + var packed = __isPacked_275(shape, array.stride.slice()) var type = 0 if(dtype === 'float32') { type = gl.FLOAT @@ -105479,7 +106279,7 @@ function createTextureArray(gl, array) { if(shape.length === 2) { format = gl.LUMINANCE shape = [shape[0], shape[1], 1] - array = _$wrappedNDArrayCtor_277(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + array = _$wrappedNDArrayCtor_335(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) } else if(shape.length === 3) { if(shape[2] === 1) { format = gl.ALPHA @@ -105503,12 +106303,12 @@ function createTextureArray(gl, array) { var size = array.size if(!packed) { var stride = [shape[2], shape[2]*shape[0], 1] - buf_store = _$pool_360.malloc(size, dtype) - var buf_array = _$wrappedNDArrayCtor_277(buf_store, shape, stride, 0) + buf_store = _$pool_422.malloc(size, dtype) + var buf_array = _$wrappedNDArrayCtor_335(buf_store, shape, stride, 0) if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { convertFloatToUint8(buf_array, array) } else { - _$ndarrayOps_271.assign(buf_array, array) + _$ndarrayOps_329.assign(buf_array, array) } buffer = buf_store.subarray(0, size) } else if (array.offset === 0 && array.data.length === size) { @@ -105519,7 +106319,7 @@ function createTextureArray(gl, array) { var tex = initTexture(gl) gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) if(!packed) { - _$pool_360.free(buf_store) + _$pool_422.free(buf_store) } return new Texture2D(gl, tex, shape[0], shape[1], format, type) } @@ -105551,9 +106351,9 @@ function createTexture2D(gl) { 'use strict' -/* removed: var _$createTexture2D_218 = require('gl-texture2d') */; +/* removed: var _$createTexture2D_275 = require('gl-texture2d') */; -var _$createFBO_158 = createFBO +var _$createFBO_215 = createFBO var colorAttachmentArrays = null var FRAMEBUFFER_UNSUPPORTED @@ -105606,11 +106406,11 @@ function throwFBOError(status) { } //Initialize a texture object -function __initTexture_158(gl, width, height, type, format, attachment) { +function __initTexture_215(gl, width, height, type, format, attachment) { if(!type) { return null } - var result = _$createTexture2D_218(gl, width, height, format, type) + var result = _$createTexture2D_275(gl, width, height, format, type) result.magFilter = gl.NEAREST result.minFilter = gl.NEAREST result.mipSamples = 1 @@ -105649,7 +106449,7 @@ function rebuildFBO(fbo) { //Allocate color buffers for(var i=0; i this.buffer.length) { - _$pool_360.free(this.buffer) - var buffer = this.buffer = _$pool_360.mallocUint8(nextPow2(r*c*4)) + _$pool_422.free(this.buffer) + var buffer = this.buffer = _$pool_422.mallocUint8(nextPow2(r*c*4)) for(var i=0; i', idx); if(nidx < idx) break; - x = x.slice(0, idx) + _$toSuperScript_345(x.slice(idx + 5, nidx)) + x.slice(nidx + 6); + x = x.slice(0, idx) + _$toSuperScript_407(x.slice(idx + 5, nidx)) + x.slice(nidx + 6); } return x; @@ -107106,7 +107906,7 @@ function stripTags(x) { } function fixEntities(x) { - var entityToUnicode = _$string_mappings_518.entityToUnicode; + var entityToUnicode = _$string_mappings_579.entityToUnicode; var idx = 0; while((idx = x.indexOf('&', idx)) >= 0) { @@ -107136,7 +107936,7 @@ function convertHTMLToUnicode(html) { html)))); } -var _$convertHTMLToUnicode_537 = convertHTMLToUnicode; +var _$convertHTMLToUnicode_599 = convertHTMLToUnicode; /** * Copyright 2012-2018, Plotly, Inc. @@ -107149,9 +107949,9 @@ var _$convertHTMLToUnicode_537 = convertHTMLToUnicode; 'use strict'; -/* removed: var _$color_411 = require('../components/color'); */; +/* removed: var _$color_473 = require('../components/color'); */; -var __noop_559 = function() {}; +var __noop_622 = function() {}; /** @@ -107161,9 +107961,9 @@ var __noop_559 = function() {}; * Expects 'scene' to have property 'container' * */ -var _$showWebGlMsg_559 = function showWebGlMsg(scene) { +var _$showWebGlMsg_622 = function showWebGlMsg(scene) { for(var prop in scene) { - if(typeof scene[prop] === 'function') scene[prop] = __noop_559; + if(typeof scene[prop] === 'function') scene[prop] = __noop_622; } scene.destroy = function() { @@ -107174,7 +107974,7 @@ var _$showWebGlMsg_559 = function showWebGlMsg(scene) { div.textContent = 'Webgl is not supported by your browser - visit http://get.webgl.org for more info'; div.style.cursor = 'pointer'; div.style.fontSize = '24px'; - div.style.color = _$color_411.defaults[0]; + div.style.color = _$color_473.defaults[0]; scene.container.appendChild(div); scene.container.style.background = '#FFFFFF'; @@ -107186,7 +107986,7 @@ var _$showWebGlMsg_559 = function showWebGlMsg(scene) { return false; }; -var _$mouse_264 = {}; +var _$mouse_322 = {}; 'use strict' function mouseButtons(ev) { @@ -107215,12 +108015,12 @@ function mouseButtons(ev) { } return 0 } -_$mouse_264.buttons = mouseButtons +_$mouse_322.buttons = mouseButtons function mouseElement(ev) { return ev.target || ev.srcElement || window } -_$mouse_264.element = mouseElement +_$mouse_322.element = mouseElement function mouseRelativeX(ev) { if(typeof ev === 'object') { @@ -107233,7 +108033,7 @@ function mouseRelativeX(ev) { } return 0 } -_$mouse_264.x = mouseRelativeX +_$mouse_322.x = mouseRelativeX function mouseRelativeY(ev) { if(typeof ev === 'object') { @@ -107246,13 +108046,13 @@ function mouseRelativeY(ev) { } return 0 } -_$mouse_264.y = mouseRelativeY +_$mouse_322.y = mouseRelativeY 'use strict' -var _$mouseListen_262 = mouseListen +var _$mouseListen_320 = mouseListen -/* removed: var _$mouse_264 = require('mouse-event') */; +/* removed: var _$mouse_322 = require('mouse-event') */; function mouseListen (element, callback) { if (!callback) { @@ -107293,8 +108093,8 @@ function mouseListen (element, callback) { } function handleEvent (nextButtons, ev) { - var nextX = _$mouse_264.x(ev) - var nextY = _$mouse_264.y(ev) + var nextX = _$mouse_322.x(ev) + var nextY = _$mouse_322.y(ev) if ('buttons' in ev) { nextButtons = ev.buttons | 0 } @@ -107335,7 +108135,7 @@ function mouseListen (element, callback) { } function handleMouseMove (ev) { - if (_$mouse_264.buttons(ev) === 0) { + if (_$mouse_322.buttons(ev) === 0) { handleEvent(0, ev) } else { handleEvent(buttonState, ev) @@ -107343,11 +108143,11 @@ function mouseListen (element, callback) { } function handleMouseDown (ev) { - handleEvent(buttonState | _$mouse_264.buttons(ev), ev) + handleEvent(buttonState | _$mouse_322.buttons(ev), ev) } function handleMouseUp (ev) { - handleEvent(buttonState & ~_$mouse_264.buttons(ev), ev) + handleEvent(buttonState & ~_$mouse_322.buttons(ev), ev) } function attachListeners () { @@ -107454,7 +108254,7 @@ function mouseListen (element, callback) { return result } -var _$parseUnit_287 = function parseUnit(str, out) { +var _$parseUnit_345 = function parseUnit(str, out) { if (!out) out = [ 0, '' ] @@ -107466,14 +108266,14 @@ var _$parseUnit_287 = function parseUnit(str, out) { } 'use strict' -/* removed: var _$parseUnit_287 = require('parse-unit') */; +/* removed: var _$parseUnit_345 = require('parse-unit') */; -var _$toPX_354 = toPX +var _$toPX_416 = toPX var PIXELS_PER_INCH = 96 function getPropertyInPX(element, prop) { - var parts = _$parseUnit_287(getComputedStyle(element).getPropertyValue(prop)) + var parts = _$parseUnit_345(getComputedStyle(element).getPropertyValue(prop)) return parts[0] * toPX(parts[1], element) } @@ -107526,9 +108326,9 @@ function toPX(str, element) { } 'use strict' -/* removed: var _$toPX_354 = require('to-px') */; +/* removed: var _$toPX_416 = require('to-px') */; -var _$mouseWheelListen_265 = mouseWheelListen +var _$mouseWheelListen_323 = mouseWheelListen function mouseWheelListen(element, callback, noScroll) { if(typeof element === 'function') { @@ -107536,7 +108336,7 @@ function mouseWheelListen(element, callback, noScroll) { callback = element element = window } - var lineHeight = _$toPX_354('ex', element) + var lineHeight = _$toPX_416('ex', element) var listener = function(ev) { if(noScroll) { ev.preventDefault() @@ -107576,13 +108376,13 @@ function mouseWheelListen(element, callback, noScroll) { 'use strict'; -/* removed: var _$mouseListen_262 = require('mouse-change'); */; -/* removed: var _$mouseWheelListen_265 = require('mouse-wheel'); */; -/* removed: var _$mouseEventOffset_263 = require('mouse-event-offset'); */; -/* removed: var _$constants_589 = require('../cartesian/constants'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; +/* removed: var _$mouseListen_320 = require('mouse-change'); */; +/* removed: var _$mouseWheelListen_323 = require('mouse-wheel'); */; +/* removed: var _$mouseEventOffset_321 = require('mouse-event-offset'); */; +/* removed: var _$constants_652 = require('../cartesian/constants'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; -var _$createCamera_622 = createCamera; +var _$createCamera_684 = createCamera; function Camera2D(element, plot) { this.element = element; @@ -107624,28 +108424,28 @@ function createCamera(scene) { return false; } - result.mouseListener = _$mouseListen_262(element, handleInteraction); + result.mouseListener = _$mouseListen_320(element, handleInteraction); // enable simple touch interactions element.addEventListener('touchstart', function(ev) { - var xy = _$mouseEventOffset_263(ev.changedTouches[0], element); + var xy = _$mouseEventOffset_321(ev.changedTouches[0], element); handleInteraction(0, xy[0], xy[1]); handleInteraction(1, xy[0], xy[1]); ev.preventDefault(); - }, _$hasPassiveEvents_240 ? {passive: false} : false); + }, _$hasPassiveEvents_297 ? {passive: false} : false); element.addEventListener('touchmove', function(ev) { ev.preventDefault(); - var xy = _$mouseEventOffset_263(ev.changedTouches[0], element); + var xy = _$mouseEventOffset_321(ev.changedTouches[0], element); handleInteraction(1, xy[0], xy[1]); ev.preventDefault(); - }, _$hasPassiveEvents_240 ? {passive: false} : false); + }, _$hasPassiveEvents_297 ? {passive: false} : false); element.addEventListener('touchend', function(ev) { handleInteraction(0, result.lastPos[0], result.lastPos[1]); ev.preventDefault(); - }, _$hasPassiveEvents_240 ? {passive: false} : false); + }, _$hasPassiveEvents_297 ? {passive: false} : false); function handleInteraction(buttons, x, y) { var dataBox = scene.calcDataBox(), @@ -107654,8 +108454,8 @@ function createCamera(scene) { var lastX = result.lastPos[0], lastY = result.lastPos[1]; - var MINDRAG = _$constants_589.MINDRAG * plot.pixelRatio; - var MINZOOM = _$constants_589.MINZOOM * plot.pixelRatio; + var MINDRAG = _$constants_652.MINDRAG * plot.pixelRatio; + var MINZOOM = _$constants_652.MINZOOM * plot.pixelRatio; var dx, dy; @@ -107829,7 +108629,7 @@ function createCamera(scene) { result.lastPos[1] = y; } - result.wheelListener = _$mouseWheelListen_265(element, function(dx, dy) { + result.wheelListener = _$mouseWheelListen_323(element, function(dx, dy) { if(!scene.scrollZoom) return false; var dataBox = scene.calcDataBox(), @@ -107866,7 +108666,7 @@ function createCamera(scene) { return result; } -var _$clamp_94 = clamp +var _$clamp_95 = clamp function clamp(value, min, max) { return min < max @@ -107876,7 +108676,7 @@ function clamp(value, min, max) { 'use strict' -var _$colorName_98 = { +var _$colorName_99 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], @@ -108027,21 +108827,21 @@ var _$colorName_98 = { "yellowgreen": [154, 205, 50] }; -var _$defined_128 = function () { +var _$defined_131 = function () { for (var i = 0; i < arguments.length; i++) { if (arguments[i] !== undefined) return arguments[i]; } }; 'use strict'; -var __toString_250 = Object.prototype.toString; +var __toString_308 = Object.prototype.toString; -var _$isPlainObj_250 = function (x) { +var _$isPlainObj_308 = function (x) { var prototype; - return __toString_250.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); + return __toString_308.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); }; -var _$parse_100 = {}; +var _$parse_101 = {}; (function (global){ /** * @module color-parse @@ -108049,11 +108849,11 @@ var _$parse_100 = {}; 'use strict' -/* removed: var _$colorName_98 = require('color-name') */; -/* removed: var _$isPlainObj_250 = require('is-plain-obj') */; -/* removed: var _$defined_128 = require('defined') */; +/* removed: var _$colorName_99 = require('color-name') */; +/* removed: var _$isPlainObj_308 = require('is-plain-obj') */; +/* removed: var _$defined_131 = require('defined') */; -_$parse_100 = parse +_$parse_101 = parse /** * Base hues @@ -108079,8 +108879,8 @@ function parse (cstr) { if (typeof cstr === 'string') { //keyword - if (_$colorName_98[cstr]) { - parts = _$colorName_98[cstr].slice() + if (_$colorName_99[cstr]) { + parts = _$colorName_99[cstr].slice() space = 'rgb' } @@ -108179,27 +108979,27 @@ function parse (cstr) { } //object case - detects css cases of rgb and hsl - else if (_$isPlainObj_250(cstr)) { - var r = _$defined_128(cstr.r, cstr.red, cstr.R, null) + else if (_$isPlainObj_308(cstr)) { + var r = _$defined_131(cstr.r, cstr.red, cstr.R, null) if (r !== null) { space = 'rgb' parts = [ r, - _$defined_128(cstr.g, cstr.green, cstr.G), - _$defined_128(cstr.b, cstr.blue, cstr.B) + _$defined_131(cstr.g, cstr.green, cstr.G), + _$defined_131(cstr.b, cstr.blue, cstr.B) ] } else { space = 'hsl' parts = [ - _$defined_128(cstr.h, cstr.hue, cstr.H), - _$defined_128(cstr.s, cstr.saturation, cstr.S), - _$defined_128(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness) + _$defined_131(cstr.h, cstr.hue, cstr.H), + _$defined_131(cstr.s, cstr.saturation, cstr.S), + _$defined_131(cstr.l, cstr.lightness, cstr.L, cstr.b, cstr.brightness) ] } - alpha = _$defined_128(cstr.a, cstr.alpha, cstr.opacity, 1) + alpha = _$defined_131(cstr.a, cstr.alpha, cstr.opacity, 1) if (cstr.opacity != null) alpha /= 100 } @@ -108226,7 +109026,7 @@ function parse (cstr) { */ 'use strict' -var _$rgb_103 = { +var _$rgb_104 = { name: 'rgb', min: [0,0,0], max: [255,255,255], @@ -108239,9 +109039,9 @@ var _$rgb_103 = { */ 'use strict' -/* removed: var _$rgb_103 = require('./rgb'); */; +/* removed: var _$rgb_104 = require('./rgb'); */; -var _$hsl_102 = { +var _$hsl_103 = { name: 'hsl', min: [0,0,0], max: [360,100,100], @@ -108299,7 +109099,7 @@ var _$hsl_102 = { //extend rgb -_$rgb_103.hsl = function(rgb) { +_$rgb_104.hsl = function(rgb) { var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255, @@ -108346,35 +109146,35 @@ _$rgb_103.hsl = function(rgb) { 'use strict' -/* removed: var _$parse_100 = require('color-parse') */; -/* removed: var _$hsl_102 = require('color-space/hsl') */; -/* removed: var _$clamp_94 = require('clamp') */; +/* removed: var _$parse_101 = require('color-parse') */; +/* removed: var _$hsl_103 = require('color-space/hsl') */; +/* removed: var _$clamp_95 = require('clamp') */; -var _$rgba_101 = function rgba (color) { +var _$rgba_102 = function rgba (color) { var values, i, l if (typeof color !== 'string') throw Error('Argument should be a string') //attempt to parse non-array arguments - var parsed = _$parse_100(color) + var parsed = _$parse_101(color) if (!parsed.space) return [] values = Array(3) - values[0] = _$clamp_94(parsed.values[0], 0, 255) - values[1] = _$clamp_94(parsed.values[1], 0, 255) - values[2] = _$clamp_94(parsed.values[2], 0, 255) + values[0] = _$clamp_95(parsed.values[0], 0, 255) + values[1] = _$clamp_95(parsed.values[1], 0, 255) + values[2] = _$clamp_95(parsed.values[2], 0, 255) if (parsed.space[0] === 'h') { - values = _$hsl_102.rgb(values) + values = _$hsl_103.rgb(values) } - values.push(_$clamp_94(parsed.alpha, 0, 1)) + values.push(_$clamp_95(parsed.alpha, 0, 1)) return values } -var _$dtype_132 = function(dtype) { +var _$dtype_135 = function(dtype) { switch (dtype) { case 'int8': return Int8Array @@ -108403,15 +109203,15 @@ var _$dtype_132 = function(dtype) { 'use strict' -/* removed: var _$rgba_101 = require('color-rgba') */; -/* removed: var _$clamp_94 = require('clamp') */; -/* removed: var _$dtype_132 = require('dtype') */; +/* removed: var _$rgba_102 = require('color-rgba') */; +/* removed: var _$clamp_95 = require('clamp') */; +/* removed: var _$dtype_135 = require('dtype') */; -var _$normalize_99 = function normalize (color, type) { +var _$normalize_100 = 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_132(type) + var Ctor = _$dtype_135(type) var output = new Ctor(4) //same class does not change values @@ -108445,7 +109245,7 @@ var _$normalize_99 = function normalize (color, type) { //attempt to parse non-array arguments if (!color.length || typeof color === 'string') { - color = _$rgba_101(color) + color = _$rgba_102(color) color[0] /= 255 color[1] /= 255 color[2] /= 255 @@ -108453,10 +109253,10 @@ var _$normalize_99 = function normalize (color, type) { //consider every other array type as 0..1 float values if (!normalize) { - output[0] = _$clamp_94(Math.round(color[0] * 255), 0, 255) - output[1] = _$clamp_94(Math.round(color[1] * 255), 0, 255) - output[2] = _$clamp_94(Math.round(color[2] * 255), 0, 255) - output[3] = color[3] == null ? 255 : _$clamp_94(Math.floor(color[3] * 255), 0, 255) + output[0] = _$clamp_95(Math.round(color[0] * 255), 0, 255) + output[1] = _$clamp_95(Math.round(color[1] * 255), 0, 255) + output[2] = _$clamp_95(Math.round(color[2] * 255), 0, 255) + output[3] = color[3] == null ? 255 : _$clamp_95(Math.floor(color[3] * 255), 0, 255) } else { output[0] = color[0] output[1] = color[1] @@ -108478,14 +109278,14 @@ var _$normalize_99 = function normalize (color, type) { 'use strict'; -/* removed: var _$normalize_99 = require('color-normalize'); */; +/* removed: var _$normalize_100 = require('color-normalize'); */; function str2RgbaArray(color) { if(!color) return [0, 0, 0, 1]; - return _$normalize_99(color); + return _$normalize_100(color); } -var _$str2RgbaArray_561 = str2RgbaArray; +var _$str2RgbaArray_624 = str2RgbaArray; /** * Copyright 2012-2018, Plotly, Inc. @@ -108498,10 +109298,10 @@ var _$str2RgbaArray_561 = str2RgbaArray; 'use strict'; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; -/* removed: var _$convertHTMLToUnicode_537 = require('../../lib/html2unicode'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../lib/html2unicode'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; function Axes2DOptions(scene) { this.scene = scene; @@ -108581,15 +109381,15 @@ function Axes2DOptions(scene) { this.static = this.scene.staticPlot; } -var __proto_623 = Axes2DOptions.prototype; +var __proto_685 = Axes2DOptions.prototype; var AXES = ['xaxis', 'yaxis']; -__proto_623.merge = function(options) { +__proto_685.merge = function(options) { // titles are rendered in SVG this.titleEnable = false; - this.backgroundColor = _$str2RgbaArray_561(options.plot_bgcolor); + this.backgroundColor = _$str2RgbaArray_624(options.plot_bgcolor); var axisName, ax, axTitle, axMirror; var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks; @@ -108607,14 +109407,14 @@ __proto_623.merge = function(options) { for(j = 0; j <= 2; j += 2) { this.labelEnable[i + j] = false; - this.labels[i + j] = _$convertHTMLToUnicode_537(axTitle); - this.labelColor[i + j] = _$str2RgbaArray_561(ax.titlefont.color); + this.labels[i + j] = _$convertHTMLToUnicode_599(axTitle); + this.labelColor[i + j] = _$str2RgbaArray_624(ax.titlefont.color); this.labelFont[i + j] = ax.titlefont.family; this.labelSize[i + j] = ax.titlefont.size; this.labelPad[i + j] = this.getLabelPad(axisName, ax); this.tickEnable[i + j] = false; - this.tickColor[i + j] = _$str2RgbaArray_561((ax.tickfont || {}).color); + this.tickColor[i + j] = _$str2RgbaArray_624((ax.tickfont || {}).color); this.tickAngle[i + j] = (ax.tickangle === 'auto') ? 0 : Math.PI * -ax.tickangle / 180; @@ -108622,10 +109422,10 @@ __proto_623.merge = function(options) { this.tickMarkLength[i + j] = 0; this.tickMarkWidth[i + j] = ax.tickwidth || 0; - this.tickMarkColor[i + j] = _$str2RgbaArray_561(ax.tickcolor); + this.tickMarkColor[i + j] = _$str2RgbaArray_624(ax.tickcolor); this.borderLineEnable[i + j] = false; - this.borderLineColor[i + j] = _$str2RgbaArray_561(ax.linecolor); + this.borderLineColor[i + j] = _$str2RgbaArray_624(ax.linecolor); this.borderLineWidth[i + j] = ax.linewidth || 0; } @@ -108660,20 +109460,20 @@ __proto_623.merge = function(options) { if(hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i + 2] = this.getTickMarkLength(ax); this.gridLineEnable[i] = ax.showgrid; - this.gridLineColor[i] = _$str2RgbaArray_561(ax.gridcolor); + this.gridLineColor[i] = _$str2RgbaArray_624(ax.gridcolor); this.gridLineWidth[i] = ax.gridwidth; this.zeroLineEnable[i] = ax.zeroline; - this.zeroLineColor[i] = _$str2RgbaArray_561(ax.zerolinecolor); + this.zeroLineColor[i] = _$str2RgbaArray_624(ax.zerolinecolor); this.zeroLineWidth[i] = ax.zerolinewidth; } }; // is an axis shared with an already-drawn subplot ? -__proto_623.hasSharedAxis = function(ax) { +__proto_685.hasSharedAxis = function(ax) { var scene = this.scene; var subplotIds = scene.fullLayout._subplots.gl2d; - var list = _$axes_584.findSubplotsWithAxis(subplotIds, ax); + var list = _$axes_647.findSubplotsWithAxis(subplotIds, ax); // if index === 0, then the subplot is already drawn as subplots // are drawn in order. @@ -108681,7 +109481,7 @@ __proto_623.hasSharedAxis = function(ax) { }; // has an axis in default position (i.e. bottom/left) ? -__proto_623.hasAxisInDfltPos = function(axisName, ax) { +__proto_685.hasAxisInDfltPos = function(axisName, ax) { var axSide = ax.side; if(axisName === 'xaxis') return (axSide === 'bottom'); @@ -108689,14 +109489,14 @@ __proto_623.hasAxisInDfltPos = function(axisName, ax) { }; // has an axis in alternate position (i.e. top/right) ? -__proto_623.hasAxisInAltrPos = function(axisName, ax) { +__proto_685.hasAxisInAltrPos = function(axisName, ax) { var axSide = ax.side; if(axisName === 'xaxis') return (axSide === 'top'); else if(axisName === 'yaxis') return (axSide === 'right'); }; -__proto_623.getLabelPad = function(axisName, ax) { +__proto_685.getLabelPad = function(axisName, ax) { var offsetBase = 1.5, fontSize = ax.titlefont.size, showticklabels = ax.showticklabels; @@ -108713,11 +109513,11 @@ __proto_623.getLabelPad = function(axisName, ax) { } }; -__proto_623.getTickPad = function(ax) { +__proto_685.getTickPad = function(ax) { return (ax.ticks === 'outside') ? 10 + ax.ticklen : 15; }; -__proto_623.getTickMarkLength = function(ax) { +__proto_685.getTickMarkLength = function(ax) { if(!ax.ticks) return 0; var ticklen = ax.ticklen; @@ -108730,7 +109530,7 @@ function createAxes2D(scene) { return new Axes2DOptions(scene); } -var _$createAxes2D_623 = createAxes2D; +var _$createAxes2D_685 = createAxes2D; /** * Copyright 2012-2018, Plotly, Inc. @@ -108743,28 +109543,28 @@ var _$createAxes2D_623 = createAxes2D; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; -/* removed: var _$createGLPlot2D_194 = require('gl-plot2d'); */; -/* removed: var _$createSpikes2D_213 = require('gl-spikes2d'); */; -/* removed: var _$createSelectBox_204 = require('gl-select-box'); */; -/* removed: var _$getWebGLContext_373 = require('webgl-context'); */; +/* removed: var _$createGLPlot2D_251 = require('gl-plot2d'); */; +/* removed: var _$createSpikes2D_270 = require('gl-spikes2d'); */; +/* removed: var _$createSelectBox_261 = require('gl-select-box'); */; +/* removed: var _$getWebGLContext_435 = require('webgl-context'); */; -/* removed: var _$createAxes2D_623 = require('./convert'); */; -/* removed: var _$createCamera_622 = require('./camera'); */; -/* removed: var _$convertHTMLToUnicode_537 = require('../../lib/html2unicode'); */; -/* removed: var _$showWebGlMsg_559 = require('../../lib/show_no_webgl_msg'); */; -/* removed: var _$constraints_591 = require('../cartesian/constraints'); */; -var __enforceAxisConstraints_625 = _$constraints_591.enforce; -var __cleanAxisConstraints_625 = _$constraints_591.clean; -var __doAutoRange_625 = _$autorange_583.doAutoRange; +/* removed: var _$createAxes2D_685 = require('./convert'); */; +/* removed: var _$createCamera_684 = require('./camera'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../lib/html2unicode'); */; +/* removed: var _$showWebGlMsg_622 = require('../../lib/show_no_webgl_msg'); */; +/* removed: var _$constraints_654 = require('../cartesian/constraints'); */; +var __enforceAxisConstraints_687 = _$constraints_654.enforce; +var __cleanAxisConstraints_687 = _$constraints_654.clean; +var __doAutoRange_687 = _$autorange_646.doAutoRange; -var __AXES_625 = ['xaxis', 'yaxis']; +var __AXES_687 = ['xaxis', 'yaxis']; var STATIC_CANVAS, STATIC_CONTEXT; -var __SUBPLOT_PATTERN_625 = _$constants_589.SUBPLOT_PATTERN; +var __SUBPLOT_PATTERN_687 = _$constants_652.SUBPLOT_PATTERN; function Scene2D(options, fullLayout) { @@ -108781,22 +109581,22 @@ function Scene2D(options, fullLayout) { this.makeFramework(); // update options - this.glplotOptions = _$createAxes2D_623(this); + this.glplotOptions = _$createAxes2D_685(this); this.glplotOptions.merge(fullLayout); // create the plot - this.glplot = _$createGLPlot2D_194(this.glplotOptions); + this.glplot = _$createGLPlot2D_251(this.glplotOptions); // create camera - this.camera = _$createCamera_622(this); + this.camera = _$createCamera_684(this); // trace set this.traces = {}; // create axes spikes - this.spikes = _$createSpikes2D_213(this.glplot); + this.spikes = _$createSpikes2D_270(this.glplot); - this.selectBox = _$createSelectBox_204(this.glplot, { + this.selectBox = _$createSelectBox_261(this.glplot, { innerFill: false, outerFill: true }); @@ -108820,18 +109620,18 @@ function Scene2D(options, fullLayout) { this.redraw(); } -var _$Scene2D_625 = Scene2D; +var _$Scene2D_687 = Scene2D; -var __proto_625 = Scene2D.prototype; +var __proto_687 = Scene2D.prototype; -__proto_625.makeFramework = function() { +__proto_687.makeFramework = function() { // create canvas and gl context if(this.staticPlot) { if(!STATIC_CONTEXT) { STATIC_CANVAS = document.createElement('canvas'); - STATIC_CONTEXT = _$getWebGLContext_373({ + STATIC_CONTEXT = _$getWebGLContext_435({ canvas: STATIC_CANVAS, preserveDrawingBuffer: false, premultipliedAlpha: true, @@ -108849,13 +109649,13 @@ __proto_625.makeFramework = function() { else { var liveCanvas = this.container.querySelector('.gl-canvas-focus'); - var gl = _$getWebGLContext_373({ + var gl = _$getWebGLContext_435({ canvas: liveCanvas, preserveDrawingBuffer: true, premultipliedAlpha: true }); - if(!gl) _$showWebGlMsg_559(this); + if(!gl) _$showWebGlMsg_622(this); this.canvas = liveCanvas; this.gl = gl; @@ -108911,7 +109711,7 @@ __proto_625.makeFramework = function() { }); }; -__proto_625.toImage = function(format) { +__proto_687.toImage = function(format) { if(!format) format = 'png'; this.stopped = true; @@ -108976,7 +109776,7 @@ __proto_625.toImage = function(format) { return dataURL; }; -__proto_625.updateSize = function(canvas) { +__proto_687.updateSize = function(canvas) { if(!canvas) canvas = this.canvas; var pixelRatio = this.pixelRatio, @@ -108996,26 +109796,26 @@ __proto_625.updateSize = function(canvas) { return canvas; }; -__proto_625.computeTickMarks = function() { +__proto_687.computeTickMarks = function() { this.xaxis.setScale(); this.yaxis.setScale(); var nextTicks = [ - _$axes_584.calcTicks(this.xaxis), - _$axes_584.calcTicks(this.yaxis) + _$axes_647.calcTicks(this.xaxis), + _$axes_647.calcTicks(this.yaxis) ]; for(var j = 0; j < 2; ++j) { for(var i = 0; i < nextTicks[j].length; ++i) { // coercing tick value (may not be a string) to a string - nextTicks[j][i].text = _$convertHTMLToUnicode_537(nextTicks[j][i].text + ''); + nextTicks[j][i].text = _$convertHTMLToUnicode_599(nextTicks[j][i].text + ''); } } return nextTicks; }; -function __compareTicks_625(a, b) { +function __compareTicks_687(a, b) { for(var i = 0; i < 2; ++i) { var aticks = a[i], bticks = b[i]; @@ -109030,10 +109830,10 @@ function __compareTicks_625(a, b) { return false; } -__proto_625.updateRefs = function(newFullLayout) { +__proto_687.updateRefs = function(newFullLayout) { this.fullLayout = newFullLayout; - var spmatch = this.id.match(__SUBPLOT_PATTERN_625); + var spmatch = this.id.match(__SUBPLOT_PATTERN_687); var xaxisName = 'xaxis' + spmatch[1]; var yaxisName = 'yaxis' + spmatch[2]; @@ -109041,7 +109841,7 @@ __proto_625.updateRefs = function(newFullLayout) { this.yaxis = this.fullLayout[yaxisName]; }; -__proto_625.relayoutCallback = function() { +__proto_687.relayoutCallback = function() { var graphDiv = this.graphDiv, xaxis = this.xaxis, yaxis = this.yaxis, @@ -109066,7 +109866,7 @@ __proto_625.relayoutCallback = function() { graphDiv.emit('plotly_relayout', update); }; -__proto_625.cameraChanged = function() { +__proto_687.cameraChanged = function() { var camera = this.camera; this.glplot.setDataBox(this.calcDataBox()); @@ -109074,7 +109874,7 @@ __proto_625.cameraChanged = function() { var nextTicks = this.computeTickMarks(); var curTicks = this.glplotOptions.ticks; - if(__compareTicks_625(nextTicks, curTicks)) { + if(__compareTicks_687(nextTicks, curTicks)) { this.glplotOptions.ticks = nextTicks; this.glplotOptions.dataBox = camera.dataBox; this.glplot.update(this.glplotOptions); @@ -109082,7 +109882,7 @@ __proto_625.cameraChanged = function() { } }; -__proto_625.handleAnnotations = function() { +__proto_687.handleAnnotations = function() { var gd = this.graphDiv, annotations = this.fullLayout.annotations; @@ -109090,12 +109890,12 @@ __proto_625.handleAnnotations = function() { var ann = annotations[i]; if(ann.xref === this.xaxis._id && ann.yref === this.yaxis._id) { - _$registry_668.getComponentMethod('annotations', 'drawOne')(gd, i); + _$registry_731.getComponentMethod('annotations', 'drawOne')(gd, i); } } }; -__proto_625.destroy = function() { +__proto_687.destroy = function() { if(!this.glplot) return; var traces = this.traces; @@ -109120,7 +109920,7 @@ __proto_625.destroy = function() { this.camera = null; }; -__proto_625.plot = function(fullData, calcData, fullLayout) { +__proto_687.plot = function(fullData, calcData, fullLayout) { var glplot = this.glplot; this.updateRefs(fullLayout); @@ -109144,8 +109944,8 @@ __proto_625.plot = function(fullData, calcData, fullLayout) { yaxis: this.yaxis }}; - __cleanAxisConstraints_625(mockGraphDiv, this.xaxis); - __cleanAxisConstraints_625(mockGraphDiv, this.yaxis); + __cleanAxisConstraints_687(mockGraphDiv, this.xaxis); + __cleanAxisConstraints_687(mockGraphDiv, this.yaxis); var size = fullLayout._size, domainX = this.xaxis.domain, @@ -109167,14 +109967,14 @@ __proto_625.plot = function(fullData, calcData, fullLayout) { var ax, i; for(i = 0; i < 2; ++i) { - ax = this[__AXES_625[i]]; + ax = this[__AXES_687[i]]; ax._length = options.viewBox[i + 2] - options.viewBox[i]; - __doAutoRange_625(ax); + __doAutoRange_687(ax); ax.setScale(); } - __enforceAxisConstraints_625(mockGraphDiv); + __enforceAxisConstraints_687(mockGraphDiv); options.ticks = this.computeTickMarks(); @@ -109187,7 +109987,7 @@ __proto_625.plot = function(fullData, calcData, fullLayout) { this.glplot.draw(); }; -__proto_625.calcDataBox = function() { +__proto_687.calcDataBox = function() { var xaxis = this.xaxis, yaxis = this.yaxis, xrange = xaxis.range, @@ -109198,7 +109998,7 @@ __proto_625.calcDataBox = function() { return [xr2l(xrange[0]), yr2l(yrange[0]), xr2l(xrange[1]), yr2l(yrange[1])]; }; -__proto_625.setRanges = function(dataBox) { +__proto_687.setRanges = function(dataBox) { var xaxis = this.xaxis, yaxis = this.yaxis, xl2r = xaxis.l2r, @@ -109208,7 +110008,7 @@ __proto_625.setRanges = function(dataBox) { yaxis.range = [yl2r(dataBox[1]), yl2r(dataBox[3])]; }; -__proto_625.updateTraces = function(fullData, calcData) { +__proto_687.updateTraces = function(fullData, calcData) { var traceIds = Object.keys(this.traces); var i, j, fullTrace; @@ -109251,7 +110051,7 @@ __proto_625.updateTraces = function(fullData, calcData) { }); }; -__proto_625.updateFx = function(dragmode) { +__proto_687.updateFx = function(dragmode) { // switch to svg interactions in lasso/select mode if(dragmode === 'lasso' || dragmode === 'select') { this.pickCanvas.style['pointer-events'] = 'none'; @@ -109273,7 +110073,7 @@ __proto_625.updateFx = function(dragmode) { } }; -__proto_625.emitPointAction = function(nextSelection, eventType) { +__proto_687.emitPointAction = function(nextSelection, eventType) { var uid = nextSelection.trace.uid; var ptNumber = nextSelection.pointIndex; var trace; @@ -109295,12 +110095,12 @@ __proto_625.emitPointAction = function(nextSelection, eventType) { yaxis: this.yaxis }; - _$fx_453.appendArrayPointValue(pointData, trace, ptNumber); + _$fx_515.appendArrayPointValue(pointData, trace, ptNumber); this.graphDiv.emit(eventType, {points: [pointData]}); }; -__proto_625.draw = function() { +__proto_687.draw = function() { if(this.stopped) return; requestAnimationFrame(this.redraw); @@ -109391,7 +110191,7 @@ __proto_625.draw = function() { var trace = this.fullData[selection.trace.index] || {}; var ptNumber = selection.pointIndex; - var hoverinfo = _$fx_453.castHoverinfo(trace, fullLayout, ptNumber); + var hoverinfo = _$fx_515.castHoverinfo(trace, fullLayout, ptNumber); if(hoverinfo && hoverinfo !== 'all') { var parts = hoverinfo.split('+'); @@ -109402,7 +110202,7 @@ __proto_625.draw = function() { if(parts.indexOf('name') === -1) selection.name = undefined; } - _$fx_453.loneHover({ + _$fx_515.loneHover({ x: selection.screenCoord[0], y: selection.screenCoord[1], xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]), @@ -109410,11 +110210,11 @@ __proto_625.draw = function() { zLabel: selection.traceCoord[2], text: selection.textLabel, name: selection.name, - color: _$fx_453.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color, - borderColor: _$fx_453.castHoverOption(trace, ptNumber, 'bordercolor'), - fontFamily: _$fx_453.castHoverOption(trace, ptNumber, 'font.family'), - fontSize: _$fx_453.castHoverOption(trace, ptNumber, 'font.size'), - fontColor: _$fx_453.castHoverOption(trace, ptNumber, 'font.color') + color: _$fx_515.castHoverOption(trace, ptNumber, 'bgcolor') || selection.color, + borderColor: _$fx_515.castHoverOption(trace, ptNumber, 'bordercolor'), + fontFamily: _$fx_515.castHoverOption(trace, ptNumber, 'font.family'), + fontSize: _$fx_515.castHoverOption(trace, ptNumber, 'font.size'), + fontColor: _$fx_515.castHoverOption(trace, ptNumber, 'font.color') }, { container: this.svgContainer, gd: this.graphDiv @@ -109432,23 +110232,23 @@ __proto_625.draw = function() { glplot.draw(); }; -__proto_625.unhover = function() { +__proto_687.unhover = function() { if(this.lastPickResult) { this.spikes.update({}); this.lastPickResult = null; this.graphDiv.emit('plotly_unhover'); - _$fx_453.loneUnhover(this.svgContainer); + _$fx_515.loneUnhover(this.svgContainer); } }; -__proto_625.hoverFormatter = function(axisName, val) { +__proto_687.hoverFormatter = function(axisName, val) { if(val === undefined) return undefined; var axis = this[axisName]; - return _$axes_584.tickText(axis, axis.c2l(val), 'hover').text; + return _$axes_647.tickText(axis, axis.c2l(val), 'hover').text; }; -var _$gl2d_624 = {}; +var _$gl2d_686 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -109460,31 +110260,31 @@ var _$gl2d_624 = {}; 'use strict'; -var __overrideAll_624 = _$edit_types_569.overrideAll; +var __overrideAll_686 = _$edit_types_632.overrideAll; -/* removed: var _$Scene2D_625 = require('./scene2d'); */; -/* removed: var _$layout_attributes_638 = require('../layout_attributes'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$constants_589 = require('../cartesian/constants'); */; -/* removed: var _$cartesian_595 = require('../cartesian'); */; -/* removed: var _$layout_attributes_454 = require('../../components/fx/layout_attributes'); */; -var getSubplotData = _$get_data_621.getSubplotData; +/* removed: var _$Scene2D_687 = require('./scene2d'); */; +/* removed: var _$layout_attributes_700 = require('../layout_attributes'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$constants_652 = require('../cartesian/constants'); */; +/* removed: var _$cartesian_658 = require('../cartesian'); */; +/* removed: var _$layout_attributes_516 = require('../../components/fx/layout_attributes'); */; +var getSubplotData = _$get_data_683.getSubplotData; -_$gl2d_624.name = 'gl2d'; +_$gl2d_686.name = 'gl2d'; -_$gl2d_624.attr = ['xaxis', 'yaxis']; +_$gl2d_686.attr = ['xaxis', 'yaxis']; -_$gl2d_624.idRoot = ['x', 'y']; +_$gl2d_686.idRoot = ['x', 'y']; -_$gl2d_624.idRegex = _$constants_589.idRegex; +_$gl2d_686.idRegex = _$constants_652.idRegex; -_$gl2d_624.attrRegex = _$constants_589.attrRegex; +_$gl2d_686.attrRegex = _$constants_652.attrRegex; -_$gl2d_624.attributes = _$attributes_582; +_$gl2d_686.attributes = _$attributes_645; -_$gl2d_624.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { +_$gl2d_686.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { if(!layoutOut._has('cartesian')) { - _$cartesian_595.supplyLayoutDefaults(layoutIn, layoutOut, fullData); + _$cartesian_658.supplyLayoutDefaults(layoutIn, layoutOut, fullData); } }; @@ -109492,18 +110292,18 @@ _$gl2d_624.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) { // 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 -_$gl2d_624.layoutAttrOverrides = __overrideAll_624(_$cartesian_595.layoutAttributes, 'plot', 'from-root'); +_$gl2d_686.layoutAttrOverrides = __overrideAll_686(_$cartesian_658.layoutAttributes, 'plot', 'from-root'); // similar overrides for base plot attributes (and those added by components) -_$gl2d_624.baseLayoutAttrOverrides = __overrideAll_624({ - plot_bgcolor: _$layout_attributes_638.plot_bgcolor, - hoverlabel: _$layout_attributes_454.hoverlabel +_$gl2d_686.baseLayoutAttrOverrides = __overrideAll_686({ + plot_bgcolor: _$layout_attributes_700.plot_bgcolor, + hoverlabel: _$layout_attributes_516.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'); -_$gl2d_624.plot = function plotGl2d(gd) { +_$gl2d_686.plot = function plotGl2d(gd) { var fullLayout = gd._fullLayout; var fullData = gd._fullData; var subplotIds = fullLayout._subplots.gl2d; @@ -109518,7 +110318,7 @@ _$gl2d_624.plot = function plotGl2d(gd) { // If Scene is not instantiated, create one! if(scene === undefined) { - scene = new _$Scene2D_625({ + scene = new _$Scene2D_687({ id: subplotId, graphDiv: gd, container: gd.querySelector('.gl-container'), @@ -109536,7 +110336,7 @@ _$gl2d_624.plot = function plotGl2d(gd) { } }; -_$gl2d_624.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$gl2d_686.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldSceneKeys = oldFullLayout._subplots.gl2d || []; for(var i = 0; i < oldSceneKeys.length; i++) { @@ -109555,16 +110355,16 @@ _$gl2d_624.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayo } // since we use cartesian interactions, do cartesian clean - _$cartesian_595.clean.apply(this, arguments); + _$cartesian_658.clean.apply(this, arguments); }; -_$gl2d_624.drawFramework = function(gd) { +_$gl2d_686.drawFramework = function(gd) { if(!gd._context.staticPlot) { - _$cartesian_595.drawFramework(gd); + _$cartesian_658.drawFramework(gd); } }; -_$gl2d_624.toSVG = function(gd) { +_$gl2d_686.toSVG = function(gd) { var fullLayout = gd._fullLayout; var subplotIds = fullLayout._subplots.gl2d; @@ -109576,7 +110376,7 @@ _$gl2d_624.toSVG = function(gd) { var image = fullLayout._glimages.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, x: 0, y: 0, @@ -109589,7 +110389,7 @@ _$gl2d_624.toSVG = function(gd) { } }; -_$gl2d_624.updateFx = function(fullLayout) { +_$gl2d_686.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots.gl2d; for(var i = 0; i < subplotIds.length; i++) { @@ -109609,12 +110409,12 @@ _$gl2d_624.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_790 = _$extend_528.extendFlat; -var __overrideAll_790 = _$edit_types_569.overrideAll; +var __extendFlat_852 = _$extend_590.extendFlat; +var __overrideAll_852 = _$edit_types_632.overrideAll; var commonList = [ @@ -109625,36 +110425,36 @@ var commonList = [ 'xtype', 'ytype' ]; -var __attrs_790 = {}; +var __attrs_852 = {}; -for(var __i_790 = 0; __i_790 < commonList.length; __i_790++) { - var k = commonList[__i_790]; - __attrs_790[k] = _$attributes_773[k]; +for(var __i_852 = 0; __i_852 < commonList.length; __i_852++) { + var k = commonList[__i_852]; + __attrs_852[k] = _$attributes_835[k]; } -__extendFlat_790( - __attrs_790, - _$attributes_417, - { autocolorscale: __extendFlat_790({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } +__extendFlat_852( + __attrs_852, + _$attributes_479, + { autocolorscale: __extendFlat_852({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); -var _$attributes_790 = __overrideAll_790(__attrs_790, 'calc', 'nested'); +var _$attributes_852 = __overrideAll_852(__attrs_852, 'calc', 'nested'); 'use strict' -/* removed: var _$browser_238 = require('glslify') */; +/* removed: var _$browser_295 = require('glslify') */; -var _$shaders_161 = { - fragment: _$browser_238(["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: _$browser_238(["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: _$browser_238(["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: _$browser_238(["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"]) +var _$shaders_218 = { + fragment: _$browser_295(["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: _$browser_295(["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: _$browser_295(["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: _$browser_295(["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"]) } "use strict" -function __compileSearch_162(funcName, predicate, reversed, extraArgs, earlyOut) { +function __compileSearch_219(funcName, predicate, reversed, extraArgs, earlyOut) { var code = [ "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), @@ -109682,10 +110482,10 @@ function __compileSearch_162(funcName, predicate, reversed, extraArgs, earlyOut) return code.join("") } -function __compileBoundsSearch_162(predicate, reversed, suffix, earlyOut) { +function __compileBoundsSearch_219(predicate, reversed, suffix, earlyOut) { var result = new Function([ - __compileSearch_162("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_162("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), + __compileSearch_219("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_219("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), "function dispatchBsearch", suffix, "(a,y,c,l,h){\ if(typeof(c)==='function'){\ return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ @@ -109696,25 +110496,25 @@ return dispatchBsearch", suffix].join("")) return result() } -var _$searchBounds_162 = { - ge: __compileBoundsSearch_162(">=", false, "GE"), - gt: __compileBoundsSearch_162(">", false, "GT"), - lt: __compileBoundsSearch_162("<", true, "LT"), - le: __compileBoundsSearch_162("<=", true, "LE"), - eq: __compileBoundsSearch_162("-", true, "EQ", true) +var _$searchBounds_219 = { + ge: __compileBoundsSearch_219(">=", false, "GE"), + gt: __compileBoundsSearch_219(">", false, "GT"), + lt: __compileBoundsSearch_219("<", true, "LT"), + le: __compileBoundsSearch_219("<=", true, "LE"), + eq: __compileBoundsSearch_219("-", true, "EQ", true) } 'use strict' -var _$createHeatmap2D_160 = createHeatmap2D +var _$createHeatmap2D_217 = createHeatmap2D -/* removed: var _$searchBounds_162 = require('binary-search-bounds') */; -/* removed: var _$iota_245 = require('iota-array') */; -/* removed: var _$pool_360 = require('typedarray-pool') */; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$createBuffer_153 = require('gl-buffer') */; +/* removed: var _$searchBounds_219 = require('binary-search-bounds') */; +/* removed: var _$iota_302 = require('iota-array') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; -/* removed: var _$shaders_161 = require('./lib/shaders') */; +/* removed: var _$shaders_218 = require('./lib/shaders') */; function GLHeatmap2D ( plot, @@ -109738,7 +110538,7 @@ function GLHeatmap2D ( this.pickOffset = 0 } -var __proto_160 = GLHeatmap2D.prototype +var __proto_217 = GLHeatmap2D.prototype var WEIGHTS = [ 0, 0, @@ -109749,7 +110549,7 @@ var WEIGHTS = [ 0, 1 ] -__proto_160.draw = (function () { +__proto_217.draw = (function () { var MATRIX = [ 1, 0, 0, 0, 1, 0, @@ -109800,7 +110600,7 @@ __proto_160.draw = (function () { } })() -__proto_160.drawPick = (function () { +__proto_217.drawPick = (function () { var MATRIX = [ 1, 0, 0, 0, 1, 0, @@ -109861,7 +110661,7 @@ __proto_160.drawPick = (function () { } })() -__proto_160.pick = function (x, y, value) { +__proto_217.pick = function (x, y, value) { var pickOffset = this.pickOffset var pointCount = this.shape[0] * this.shape[1] if (value < pickOffset || value >= pickOffset + pointCount) { @@ -109879,13 +110679,13 @@ __proto_160.pick = function (x, y, value) { } } -__proto_160.update = function (options) { +__proto_217.update = function (options) { options = options || {} var shape = options.shape || [0, 0] - var x = options.x || _$iota_245(shape[0]) - var y = options.y || _$iota_245(shape[1]) + var x = options.x || _$iota_302(shape[0]) + var y = options.y || _$iota_302(shape[1]) var z = options.z || new Float32Array(shape[0] * shape[1]) this.xData = x @@ -109913,10 +110713,10 @@ __proto_160.update = function (options) { this.numVertices = numVerts - var colors = _$pool_360.mallocUint8(numVerts * 4) - var positions = _$pool_360.mallocFloat32(numVerts * 2) - var weights = _$pool_360.mallocUint8 (numVerts * 2) - var ids = _$pool_360.mallocUint32(numVerts) + var colors = _$pool_422.mallocUint8(numVerts * 4) + var positions = _$pool_422.mallocFloat32(numVerts * 2) + var weights = _$pool_422.mallocUint8 (numVerts * 2) + var ids = _$pool_422.mallocUint32(numVerts) var ptr = 0 @@ -109932,7 +110732,7 @@ __proto_160.update = function (options) { var dy = WEIGHTS[dd + 1] var offset = (j + dy) * numX + (i + dx) var zc = z[offset] - var colorIdx = _$searchBounds_162.le(colorLevels, zc) + var colorIdx = _$searchBounds_219.le(colorLevels, zc) var r, g, b, a if (colorIdx < 0) { r = colorValues[0] @@ -109979,13 +110779,13 @@ __proto_160.update = function (options) { this.colorBuffer.update(colors) this.idBuffer.update(ids) - _$pool_360.free(positions) - _$pool_360.free(colors) - _$pool_360.free(weights) - _$pool_360.free(ids) + _$pool_422.free(positions) + _$pool_422.free(colors) + _$pool_422.free(weights) + _$pool_422.free(ids) } -__proto_160.dispose = function () { +__proto_217.dispose = function () { this.shader.dispose() this.pickShader.dispose() this.positionBuffer.dispose() @@ -109998,13 +110798,13 @@ __proto_160.dispose = function () { function createHeatmap2D (plot, options) { var gl = plot.gl - var shader = _$createShader_206(gl, _$shaders_161.vertex, _$shaders_161.fragment) - var pickShader = _$createShader_206(gl, _$shaders_161.pickVertex, _$shaders_161.pickFragment) + var shader = _$createShader_263(gl, _$shaders_218.vertex, _$shaders_218.fragment) + var pickShader = _$createShader_263(gl, _$shaders_218.pickVertex, _$shaders_218.pickFragment) - var positionBuffer = _$createBuffer_153(gl) - var weightBuffer = _$createBuffer_153(gl) - var colorBuffer = _$createBuffer_153(gl) - var idBuffer = _$createBuffer_153(gl) + var positionBuffer = _$createBuffer_210(gl) + var weightBuffer = _$createBuffer_210(gl) + var colorBuffer = _$createBuffer_210(gl) + var idBuffer = _$createBuffer_210(gl) var heatmap = new GLHeatmap2D( plot, @@ -110032,12 +110832,12 @@ function createHeatmap2D (plot, options) { 'use strict'; -/* removed: var _$createHeatmap2D_160 = require('gl-heatmap2d'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; +/* removed: var _$createHeatmap2D_217 = require('gl-heatmap2d'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; -function __Heatmap_791(scene, uid) { +function __Heatmap_853(scene, uid) { this.scene = scene; this.uid = uid; this.type = 'heatmapgl'; @@ -110062,13 +110862,13 @@ function __Heatmap_791(scene, uid) { colorValues: [0, 0, 0, 1] }; - this.heatmap = _$createHeatmap2D_160(scene.glplot, this.options); + this.heatmap = _$createHeatmap2D_217(scene.glplot, this.options); this.heatmap._trace = this; } -var __proto_791 = __Heatmap_791.prototype; +var __proto_853 = __Heatmap_853.prototype; -__proto_791.handlePick = function(pickResult) { +__proto_853.handlePick = function(pickResult) { var options = this.options, shape = options.shape, index = pickResult.pointId, @@ -110091,7 +110891,7 @@ __proto_791.handlePick = function(pickResult) { }; }; -__proto_791.update = function(fullTrace, calcTrace) { +__proto_853.update = function(fullTrace, calcTrace) { var calcPt = calcTrace[0]; this.index = fullTrace.index; @@ -110118,11 +110918,11 @@ __proto_791.update = function(fullTrace, calcTrace) { this.heatmap.update(this.options); - _$axes_584.expand(this.scene.xaxis, calcPt.x); - _$axes_584.expand(this.scene.yaxis, calcPt.y); + _$axes_647.expand(this.scene.xaxis, calcPt.x); + _$axes_647.expand(this.scene.yaxis, calcPt.y); }; -__proto_791.dispose = function() { +__proto_853.dispose = function() { this.heatmap.dispose(); }; @@ -110137,7 +110937,7 @@ function convertColorscale(fullTrace) { for(var i = 0; i < N; i++) { var si = scl[i]; - var color = _$str2RgbaArray_561(si[1]); + var color = _$str2RgbaArray_624(si[1]); domain[i] = zmin + si[0] * (zmax - zmin); @@ -110153,12 +110953,12 @@ function convertColorscale(fullTrace) { } function createHeatmap(scene, fullTrace, calcTrace) { - var plot = new __Heatmap_791(scene, fullTrace.uid); + var plot = new __Heatmap_853(scene, fullTrace.uid); plot.update(fullTrace, calcTrace); return plot; } -var _$createHeatmap_791 = createHeatmap; +var _$createHeatmap_853 = createHeatmap; /** * Copyright 2012-2018, Plotly, Inc. @@ -110173,22 +110973,22 @@ var _$createHeatmap_791 = createHeatmap; var HeatmapGl = {}; -HeatmapGl.attributes = _$attributes_790; -HeatmapGl.supplyDefaults = _$supplyDefaults_778; -HeatmapGl.colorbar = _$colorbar_776; +HeatmapGl.attributes = _$attributes_852; +HeatmapGl.supplyDefaults = _$supplyDefaults_840; +HeatmapGl.colorbar = _$colorbar_838; -HeatmapGl.calc = _$calc_774; -HeatmapGl.plot = _$createHeatmap_791; +HeatmapGl.calc = _$calc_836; +HeatmapGl.plot = _$createHeatmap_853; HeatmapGl.moduleType = 'trace'; HeatmapGl.name = 'heatmapgl'; -HeatmapGl.basePlotModule = _$gl2d_624; +HeatmapGl.basePlotModule = _$gl2d_686; HeatmapGl.categories = ['gl', 'gl2d', '2dMap']; HeatmapGl.meta = { }; -var _$HeatmapGl_792 = HeatmapGl; +var _$HeatmapGl_854 = HeatmapGl; /** * Copyright 2012-2018, Plotly, Inc. @@ -110200,7 +111000,7 @@ var _$HeatmapGl_792 = HeatmapGl; 'use strict'; -var _$heatmapgl_16 = _$HeatmapGl_792; +var _$heatmapgl_16 = _$HeatmapGl_854; /** * Copyright 2012-2018, Plotly, Inc. @@ -110212,9 +111012,9 @@ var _$heatmapgl_16 = _$HeatmapGl_792; 'use strict'; -/* removed: var _$attributes_678 = require('../bar/attributes'); */; +/* removed: var _$attributes_741 = require('../bar/attributes'); */; -var _$attributes_793 = { +var _$attributes_855 = { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -110226,8 +111026,8 @@ var _$attributes_793 = { }, - text: _$attributes_678.text, - orientation: _$attributes_678.orientation, + text: _$attributes_741.text, + orientation: _$attributes_741.orientation, histfunc: { valType: 'enumerated', @@ -110319,13 +111119,13 @@ var _$attributes_793 = { }, ybins: makeBinsAttr('y'), - marker: _$attributes_678.marker, + marker: _$attributes_741.marker, - selected: _$attributes_678.selected, - unselected: _$attributes_678.unselected, + selected: _$attributes_741.selected, + unselected: _$attributes_741.unselected, _deprecated: { - bardir: _$attributes_678._deprecated.bardir + bardir: _$attributes_741._deprecated.bardir } }; @@ -110376,20 +111176,20 @@ function makeBinsAttr(axLetter) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$arraysToCalcdata_677 = require('../bar/arrays_to_calcdata'); */; -/* removed: var _$bin_functions_796 = require('./bin_functions'); */; -/* removed: var _$norm_functions_804 = require('./norm_functions'); */; -/* removed: var _$doAvg_794 = require('./average'); */; -/* removed: var _$cleanBins_799 = require('./clean_bins'); */; -var __oneMonth_798 = _$numerical_517.ONEAVGMONTH; -/* removed: var _$getBinSpanLabelRound_797 = require('./bin_label_vals'); */; +/* removed: var _$arraysToCalcdata_740 = require('../bar/arrays_to_calcdata'); */; +/* removed: var _$bin_functions_858 = require('./bin_functions'); */; +/* removed: var _$norm_functions_866 = require('./norm_functions'); */; +/* removed: var _$doAvg_856 = require('./average'); */; +/* removed: var _$cleanBins_861 = require('./clean_bins'); */; +var __oneMonth_860 = _$numerical_578.ONEAVGMONTH; +/* removed: var _$getBinSpanLabelRound_859 = require('./bin_label_vals'); */; -var _$calc_798 = function calc(gd, trace) { +var _$calc_860 = function calc(gd, trace) { // ignore as much processing as possible (and including in autorange) if bar is not visible if(trace.visible !== true) return; @@ -110397,7 +111197,7 @@ var _$calc_798 = function calc(gd, trace) { // note: this logic for choosing orientation is duplicated in graph_obj->setstyles var pos = []; var size = []; - var pa = _$axes_584.getFromId(gd, trace.orientation === 'h' ? + var pa = _$axes_647.getFromId(gd, trace.orientation === 'h' ? (trace.yaxis || 'y') : (trace.xaxis || 'x')); var mainData = trace.orientation === 'h' ? 'y' : 'x'; var counterData = {x: 'y', y: 'x'}[mainData]; @@ -110405,7 +111205,7 @@ var _$calc_798 = function calc(gd, trace) { var cumulativeSpec = trace.cumulative; var i; - _$cleanBins_799(trace, pa, mainData); + _$cleanBins_861(trace, pa, mainData); var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData); var binSpec = binsAndPos[0]; @@ -110433,16 +111233,16 @@ var _$calc_798 = function calc(gd, trace) { var extremeFunc = func === 'max' || func === 'min'; var sizeInit = extremeFunc ? null : 0; - var binFunc = _$bin_functions_796.count; - var normFunc = _$norm_functions_804[norm]; + var binFunc = _$bin_functions_858.count; + var normFunc = _$norm_functions_866[norm]; var isAvg = false; var pr2c = function(v) { return pa.r2c(v, 0, calendar); }; var rawCounterData; - if(_$lib_539.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { + if(_$lib_601.isArrayOrTypedArray(trace[counterData]) && func !== 'count') { rawCounterData = trace[counterData]; isAvg = func === 'avg'; - binFunc = _$bin_functions_796[func]; + binFunc = _$bin_functions_858[func]; } // create the bins (and any extra arrays needed) @@ -110450,10 +111250,10 @@ var _$calc_798 = function calc(gd, trace) { i = pr2c(binSpec.start); // decrease end a little in case of rounding errors - binEnd = pr2c(binSpec.end) + (i - _$axes_584.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; + binEnd = pr2c(binSpec.end) + (i - _$axes_647.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; while(i < binEnd && pos.length < 1e6) { - i2 = _$axes_584.tickIncrement(i, binSpec.size, false, calendar); + i2 = _$axes_647.tickIncrement(i, binSpec.size, false, calendar); pos.push((i + i2) / 2); size.push(sizeInit); inputPoints.push([]); @@ -110488,7 +111288,7 @@ var _$calc_798 = function calc(gd, trace) { var ptNumber2cdIndex = {}; for(i = 0; i < pos0.length; i++) { var posi = pos0[i]; - n = _$lib_539.findBin(posi, bins); + n = _$lib_601.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]]) { @@ -110504,11 +111304,11 @@ var _$calc_798 = function calc(gd, trace) { var roundFn; if(!uniqueValsPerBin) { - roundFn = _$getBinSpanLabelRound_797(leftGap, rightGap, binEdges, pa, calendar); + roundFn = _$getBinSpanLabelRound_859(leftGap, rightGap, binEdges, pa, calendar); } // average and/or normalize the data, if needed - if(isAvg) total = _$doAvg_794(size, counts); + if(isAvg) total = _$doAvg_856(size, counts); if(normFunc) normFunc(size, total, inc); // after all normalization etc, now we can accumulate if desired @@ -110536,7 +111336,7 @@ var _$calc_798 = function calc(gd, trace) { // create the "calculated data" to plot for(i = firstNonzero; i <= lastNonzero; i++) { - if((_$fastIsnumeric_139(pos[i]) && _$fastIsnumeric_139(size[i]))) { + if((_$fastIsnumeric_196(pos[i]) && _$fastIsnumeric_196(size[i]))) { var cdi = { p: pos[i], s: size[i], @@ -110561,13 +111361,13 @@ var _$calc_798 = function calc(gd, trace) { 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_584.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; + cd[0].width1 = _$axes_647.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; } - _$arraysToCalcdata_677(cd, trace); + _$arraysToCalcdata_740(cd, trace); - if(_$lib_539.isArrayOrTypedArray(trace.selectedpoints)) { - _$lib_539.tagSelected(cd, trace, ptNumber2cdIndex); + if(_$lib_601.isArrayOrTypedArray(trace.selectedpoints)) { + _$lib_601.tagSelected(cd, trace, ptNumber2cdIndex); } return cd; @@ -110616,7 +111416,7 @@ function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { calendar = tracei[mainData + 'calendar']; var cumulativeSpec = tracei.cumulative; - binSpec = _$axes_584.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); + binSpec = _$axes_647.autoBin(pos0, pa, tracei['nbins' + mainData], false, calendar); // Edge case: single-valued histogram overlaying others // Use them all together to calculate the bin size for the single-valued one @@ -110670,7 +111470,7 @@ function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { // do what we can to match the auto bins to the first manual bins // but only if sizes are all numeric - if(firstManual && _$fastIsnumeric_139(firstManual.size) && _$fastIsnumeric_139(minSize)) { + if(firstManual && _$fastIsnumeric_196(firstManual.size) && _$fastIsnumeric_196(minSize)) { // first need to ensure the bin size is the same as or an integer fraction // of the first manual bin // allow the bin size to increase just under the autobin step size to match, @@ -110767,7 +111567,7 @@ function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) { // 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_539.distinctVals(dataVals).minDiff; + minSize = _$lib_601.distinctVals(dataVals).minDiff; } // now apply the min size we found to all single-valued traces @@ -110825,9 +111625,9 @@ function getMinSize(size1, size2) { } function numericSize(size) { - if(_$fastIsnumeric_139(size)) return size; + if(_$fastIsnumeric_196(size)) return size; if(typeof size === 'string' && size.charAt(0) === 'M') { - return __oneMonth_798 * +(size.substr(1)); + return __oneMonth_860 * +(size.substr(1)); } return Infinity; } @@ -110896,7 +111696,7 @@ function cdf(size, direction, currentBin) { 'use strict'; -var _$handleBinDefaults_795 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { +var _$handleBinDefaults_857 = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) { coerce('histnorm'); binDirections.forEach(function(binDirection) { @@ -110928,17 +111728,17 @@ var _$handleBinDefaults_795 = function handleBinDefaults(traceIn, traceOut, coer 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$handleBinDefaults_795 = require('./bin_defaults'); */; -/* removed: var _$handleStyleDefaults_690 = require('../bar/style_defaults'); */; -/* removed: var _$attributes_793 = require('./attributes'); */; +/* removed: var _$handleBinDefaults_857 = require('./bin_defaults'); */; +/* removed: var _$handleStyleDefaults_753 = require('../bar/style_defaults'); */; +/* removed: var _$attributes_855 = require('./attributes'); */; -var _$supplyDefaults_800 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_862 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_793, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_855, attr, dflt); } var x = coerce('x'), @@ -110960,23 +111760,23 @@ var _$supplyDefaults_800 = function supplyDefaults(traceIn, traceOut, defaultCol return; } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); var hasAggregationData = traceOut[orientation === 'h' ? 'x' : 'y']; if(hasAggregationData) coerce('histfunc'); var binDirections = (orientation === 'h') ? ['y'] : ['x']; - _$handleBinDefaults_795(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_857(traceIn, traceOut, coerce, binDirections); - _$handleStyleDefaults_690(traceIn, traceOut, coerce, defaultColor, layout); + _$handleStyleDefaults_753(traceIn, traceOut, coerce, defaultColor, layout); // override defaultColor for error bars with defaultLine - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, _$color_411.defaultLine, {axis: 'x', inherit: 'y'}); + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, _$color_473.defaultLine, {axis: 'x', inherit: 'y'}); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -110989,7 +111789,7 @@ var _$supplyDefaults_800 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_801 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_863 = 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; @@ -111035,11 +111835,11 @@ var _$eventData_801 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_681 = require('../bar/hover'); */; -var hoverLabelText = _$axes_584.hoverLabelText; +/* removed: var _$hoverPoints_744 = require('../bar/hover'); */; +var hoverLabelText = _$axes_647.hoverLabelText; -var _$hoverPoints_802 = function hoverPoints(pointData, xval, yval, hovermode) { - var pts = _$hoverPoints_681(pointData, xval, yval, hovermode); +var _$hoverPoints_864 = function hoverPoints(pointData, xval, yval, hovermode) { + var pts = _$hoverPoints_744(pointData, xval, yval, hovermode); if(!pts) return; @@ -111083,28 +111883,28 @@ var _$hoverPoints_802 = function hoverPoints(pointData, xval, yval, hovermode) { var Histogram = {}; -Histogram.attributes = _$attributes_793; -Histogram.layoutAttributes = _$layout_attributes_683; -Histogram.supplyDefaults = _$supplyDefaults_800; -Histogram.supplyLayoutDefaults = _$layout_defaults_684; -Histogram.calc = _$calc_798; -Histogram.setPositions = _$setPositions_687; -Histogram.plot = _$plot_685; -Histogram.style = _$style_689; -Histogram.colorbar = _$colorbar_866; -Histogram.hoverPoints = _$hoverPoints_802; -Histogram.selectPoints = _$selectPoints_686; -Histogram.eventData = _$eventData_801; +Histogram.attributes = _$attributes_855; +Histogram.layoutAttributes = _$layout_attributes_746; +Histogram.supplyDefaults = _$supplyDefaults_862; +Histogram.supplyLayoutDefaults = _$layout_defaults_747; +Histogram.calc = _$calc_860; +Histogram.setPositions = _$setPositions_750; +Histogram.plot = _$plot_748; +Histogram.style = _$style_752; +Histogram.colorbar = _$colorbar_931; +Histogram.hoverPoints = _$hoverPoints_864; +Histogram.selectPoints = _$selectPoints_749; +Histogram.eventData = _$eventData_863; Histogram.moduleType = 'trace'; Histogram.name = 'histogram'; -Histogram.basePlotModule = _$cartesian_595; -Histogram.categories = ['cartesian', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; +Histogram.basePlotModule = _$cartesian_658; +Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend']; Histogram.meta = { }; -var _$Histogram_803 = Histogram; +var _$Histogram_865 = Histogram; /** * Copyright 2012-2018, Plotly, Inc. @@ -111116,7 +111916,7 @@ var _$Histogram_803 = Histogram; 'use strict'; -var _$histogram_17 = _$Histogram_803; +var _$histogram_17 = _$Histogram_865; /** * Copyright 2012-2018, Plotly, Inc. @@ -111128,17 +111928,17 @@ var _$histogram_17 = _$Histogram_803; 'use strict'; -/* removed: var _$attributes_793 = require('../histogram/attributes'); */; -/* removed: var _$attributes_773 = require('../heatmap/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_855 = require('../histogram/attributes'); */; +/* removed: var _$attributes_835 = require('../heatmap/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_805 = _$extend_528.extendFlat; +var __extendFlat_867 = _$extend_590.extendFlat; -var _$attributes_805 = __extendFlat_805({}, +var _$attributes_867 = __extendFlat_867({}, { - x: _$attributes_793.x, - y: _$attributes_793.y, + x: _$attributes_855.x, + y: _$attributes_855.y, z: { valType: 'data_array', @@ -111154,23 +111954,23 @@ var _$attributes_805 = __extendFlat_805({}, editType: 'calc' }, - histnorm: _$attributes_793.histnorm, - histfunc: _$attributes_793.histfunc, - autobinx: _$attributes_793.autobinx, - nbinsx: _$attributes_793.nbinsx, - xbins: _$attributes_793.xbins, - autobiny: _$attributes_793.autobiny, - nbinsy: _$attributes_793.nbinsy, - ybins: _$attributes_793.ybins, - - xgap: _$attributes_773.xgap, - ygap: _$attributes_773.ygap, - zsmooth: _$attributes_773.zsmooth, - zhoverformat: _$attributes_773.zhoverformat - }, - _$attributes_417, - { autocolorscale: __extendFlat_805({}, _$attributes_417.autocolorscale, {dflt: false}) }, - { colorbar: _$attributes_412 } + histnorm: _$attributes_855.histnorm, + histfunc: _$attributes_855.histfunc, + autobinx: _$attributes_855.autobinx, + nbinsx: _$attributes_855.nbinsx, + xbins: _$attributes_855.xbins, + autobiny: _$attributes_855.autobiny, + nbinsy: _$attributes_855.nbinsy, + ybins: _$attributes_855.ybins, + + xgap: _$attributes_835.xgap, + ygap: _$attributes_835.ygap, + zsmooth: _$attributes_835.zsmooth, + zhoverformat: _$attributes_835.zhoverformat + }, + _$attributes_479, + { autocolorscale: __extendFlat_867({}, _$attributes_479.autocolorscale, {dflt: false}) }, + { colorbar: _$attributes_474 } ); /** @@ -111184,11 +111984,11 @@ var _$attributes_805 = __extendFlat_805({}, 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$handleBinDefaults_795 = require('../histogram/bin_defaults'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$handleBinDefaults_857 = require('../histogram/bin_defaults'); */; -var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut, coerce, layout) { +var _$handleSampleDefaults_872 = function handleSampleDefaults(traceIn, traceOut, coerce, layout) { var x = coerce('x'), y = coerce('y'); @@ -111200,7 +112000,7 @@ var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut return; } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout); // if marker.color is an array, we can use it in aggregation instead of z @@ -111209,7 +112009,7 @@ var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut if(hasAggregationData) coerce('histfunc'); var binDirections = ['x', 'y']; - _$handleBinDefaults_795(traceIn, traceOut, coerce, binDirections); + _$handleBinDefaults_857(traceIn, traceOut, coerce, binDirections); }; /** @@ -111223,24 +112023,24 @@ var _$handleSampleDefaults_810 = function handleSampleDefaults(traceIn, traceOut 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleSampleDefaults_810 = require('./sample_defaults'); */; -/* removed: var _$handleStyleDefaults_788 = require('../heatmap/style_defaults'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_805 = require('./attributes'); */; +/* removed: var _$handleSampleDefaults_872 = require('./sample_defaults'); */; +/* removed: var _$handleStyleDefaults_850 = require('../heatmap/style_defaults'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_867 = require('./attributes'); */; -var _$supplyDefaults_807 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_869 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_805, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_867, attr, dflt); } - _$handleSampleDefaults_810(traceIn, traceOut, coerce, layout); + _$handleSampleDefaults_872(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; - _$handleStyleDefaults_788(traceIn, traceOut, coerce, layout); - _$colorScaleDefaults_421( + _$handleStyleDefaults_850(traceIn, traceOut, coerce, layout); + _$colorScaleDefaults_483( traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'} ); }; @@ -111256,11 +112056,11 @@ var _$supplyDefaults_807 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$hoverPoints_781 = require('../heatmap/hover'); */; -var __hoverLabelText_808 = _$axes_584.hoverLabelText; +/* removed: var _$hoverPoints_843 = require('../heatmap/hover'); */; +var __hoverLabelText_870 = _$axes_647.hoverLabelText; -var _$hoverPoints_808 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { - var pts = _$hoverPoints_781(pointData, xval, yval, hovermode, hoverLayer, contour); +var _$hoverPoints_870 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) { + var pts = _$hoverPoints_843(pointData, xval, yval, hovermode, hoverLayer, contour); if(!pts) return; @@ -111272,8 +112072,8 @@ var _$hoverPoints_808 = function hoverPoints(pointData, xval, yval, hovermode, h var xRange = cd0.xRanges[nx]; var yRange = cd0.yRanges[ny]; - pointData.xLabel = __hoverLabelText_808(pointData.xa, xRange[0], xRange[1]); - pointData.yLabel = __hoverLabelText_808(pointData.ya, yRange[0], yRange[1]); + pointData.xLabel = __hoverLabelText_870(pointData.xa, xRange[0], xRange[1]); + pointData.yLabel = __hoverLabelText_870(pointData.ya, yRange[0], yRange[1]); return pts; }; @@ -111291,25 +112091,25 @@ var _$hoverPoints_808 = function hoverPoints(pointData, xval, yval, hovermode, h var Histogram2D = {}; -Histogram2D.attributes = _$attributes_805; -Histogram2D.supplyDefaults = _$supplyDefaults_807; -Histogram2D.calc = _$calc_774; -Histogram2D.plot = _$plot_786; -Histogram2D.colorbar = _$colorbar_776; -Histogram2D.style = _$style_787; -Histogram2D.hoverPoints = _$hoverPoints_808; -Histogram2D.eventData = _$eventData_801; +Histogram2D.attributes = _$attributes_867; +Histogram2D.supplyDefaults = _$supplyDefaults_869; +Histogram2D.calc = _$calc_836; +Histogram2D.plot = _$plot_848; +Histogram2D.colorbar = _$colorbar_838; +Histogram2D.style = _$style_849; +Histogram2D.hoverPoints = _$hoverPoints_870; +Histogram2D.eventData = _$eventData_863; Histogram2D.moduleType = 'trace'; Histogram2D.name = 'histogram2d'; -Histogram2D.basePlotModule = _$cartesian_595; -Histogram2D.categories = ['cartesian', '2dMap', 'histogram']; +Histogram2D.basePlotModule = _$cartesian_658; +Histogram2D.categories = ['cartesian', 'svg', '2dMap', 'histogram']; Histogram2D.meta = { }; -var _$Histogram2D_809 = Histogram2D; +var _$Histogram2D_871 = Histogram2D; /** * Copyright 2012-2018, Plotly, Inc. @@ -111321,7 +112121,7 @@ var _$Histogram2D_809 = Histogram2D; 'use strict'; -var _$histogram2d_18 = _$Histogram2D_809; +var _$histogram2d_18 = _$Histogram2D_871; /** * Copyright 2012-2018, Plotly, Inc. @@ -111333,39 +112133,39 @@ var _$histogram2d_18 = _$Histogram2D_809; 'use strict'; -/* removed: var _$attributes_805 = require('../histogram2d/attributes'); */; -/* removed: var _$attributes_744 = require('../contour/attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_867 = require('../histogram2d/attributes'); */; +/* removed: var _$attributes_806 = require('../contour/attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_811 = _$extend_528.extendFlat; +var __extendFlat_873 = _$extend_590.extendFlat; -var _$attributes_811 = __extendFlat_811({ - x: _$attributes_805.x, - y: _$attributes_805.y, - z: _$attributes_805.z, - marker: _$attributes_805.marker, +var _$attributes_873 = __extendFlat_873({ + x: _$attributes_867.x, + y: _$attributes_867.y, + z: _$attributes_867.z, + marker: _$attributes_867.marker, - histnorm: _$attributes_805.histnorm, - histfunc: _$attributes_805.histfunc, - autobinx: _$attributes_805.autobinx, - nbinsx: _$attributes_805.nbinsx, - xbins: _$attributes_805.xbins, - autobiny: _$attributes_805.autobiny, - nbinsy: _$attributes_805.nbinsy, - ybins: _$attributes_805.ybins, + histnorm: _$attributes_867.histnorm, + histfunc: _$attributes_867.histfunc, + autobinx: _$attributes_867.autobinx, + nbinsx: _$attributes_867.nbinsx, + xbins: _$attributes_867.xbins, + autobiny: _$attributes_867.autobiny, + nbinsy: _$attributes_867.nbinsy, + ybins: _$attributes_867.ybins, - autocontour: _$attributes_744.autocontour, - ncontours: _$attributes_744.ncontours, - contours: _$attributes_744.contours, - line: _$attributes_744.line, - zhoverformat: _$attributes_805.zhoverformat + autocontour: _$attributes_806.autocontour, + ncontours: _$attributes_806.ncontours, + contours: _$attributes_806.contours, + line: _$attributes_806.line, + zhoverformat: _$attributes_867.zhoverformat }, - _$attributes_417, { - zmin: __extendFlat_811({}, _$attributes_417.zmin, {editType: 'calc'}), - zmax: __extendFlat_811({}, _$attributes_417.zmax, {editType: 'calc'}) + _$attributes_479, { + zmin: __extendFlat_873({}, _$attributes_479.zmin, {editType: 'calc'}), + zmax: __extendFlat_873({}, _$attributes_479.zmax, {editType: 'calc'}) }, - { colorbar: _$attributes_412 } + { colorbar: _$attributes_474 } ); /** @@ -111379,28 +112179,28 @@ var _$attributes_811 = __extendFlat_811({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleSampleDefaults_810 = require('../histogram2d/sample_defaults'); */; -/* removed: var _$handleContourDefaults_751 = require('../contour/contours_defaults'); */; -/* removed: var _$handleStyleDefaults_765 = require('../contour/style_defaults'); */; -/* removed: var _$attributes_811 = require('./attributes'); */; +/* removed: var _$handleSampleDefaults_872 = require('../histogram2d/sample_defaults'); */; +/* removed: var _$handleContourDefaults_813 = require('../contour/contours_defaults'); */; +/* removed: var _$handleStyleDefaults_827 = require('../contour/style_defaults'); */; +/* removed: var _$attributes_873 = require('./attributes'); */; -var _$supplyDefaults_812 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_874 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_811, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_873, attr, dflt); } function coerce2(attr) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_811, attr); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_873, attr); } - _$handleSampleDefaults_810(traceIn, traceOut, coerce, layout); + _$handleSampleDefaults_872(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; - _$handleContourDefaults_751(traceIn, traceOut, coerce, coerce2); - _$handleStyleDefaults_765(traceIn, traceOut, coerce, layout); + _$handleContourDefaults_813(traceIn, traceOut, coerce, coerce2); + _$handleStyleDefaults_827(traceIn, traceOut, coerce, layout); }; /** @@ -111416,24 +112216,24 @@ var _$supplyDefaults_812 = function supplyDefaults(traceIn, traceOut, defaultCol var Histogram2dContour = {}; -Histogram2dContour.attributes = _$attributes_811; -Histogram2dContour.supplyDefaults = _$supplyDefaults_812; -Histogram2dContour.calc = _$calc_745; -Histogram2dContour.plot = _$plot_762.plot; -Histogram2dContour.style = _$style_764; -Histogram2dContour.colorbar = _$colorbar_747; -Histogram2dContour.hoverPoints = _$hoverPoints_757; +Histogram2dContour.attributes = _$attributes_873; +Histogram2dContour.supplyDefaults = _$supplyDefaults_874; +Histogram2dContour.calc = _$calc_807; +Histogram2dContour.plot = _$plot_824.plot; +Histogram2dContour.style = _$style_826; +Histogram2dContour.colorbar = _$colorbar_809; +Histogram2dContour.hoverPoints = _$hoverPoints_819; Histogram2dContour.moduleType = 'trace'; Histogram2dContour.name = 'histogram2dcontour'; -Histogram2dContour.basePlotModule = _$cartesian_595; -Histogram2dContour.categories = ['cartesian', '2dMap', 'contour', 'histogram']; +Histogram2dContour.basePlotModule = _$cartesian_658; +Histogram2dContour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'histogram']; Histogram2dContour.meta = { }; -var _$Histogram2dContour_813 = Histogram2dContour; +var _$Histogram2dContour_875 = Histogram2dContour; /** * Copyright 2012-2018, Plotly, Inc. @@ -111445,7 +112245,7 @@ var _$Histogram2dContour_813 = Histogram2dContour; 'use strict'; -var _$histogram2dcontour_19 = _$Histogram2dContour_813; +var _$histogram2dcontour_19 = _$Histogram2dContour_875; /** * Copyright 2012-2018, Plotly, Inc. @@ -111458,7 +112258,7 @@ var _$histogram2dcontour_19 = _$Histogram2dContour_813; 'use strict'; -var _$attributes_628 = { +var _$attributes_690 = { scene: { valType: 'subplotid', @@ -111478,14 +112278,14 @@ var _$attributes_628 = { 'use strict'; -/* removed: var _$color_411 = require('../../../components/color'); */; -/* removed: var _$layout_attributes_596 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_629 = _$extend_528.extendFlat; -var __overrideAll_629 = _$edit_types_569.overrideAll; +/* removed: var _$color_473 = require('../../../components/color'); */; +/* removed: var _$layout_attributes_659 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_691 = _$extend_590.extendFlat; +var __overrideAll_691 = _$edit_types_632.overrideAll; -var _$axis_attributes_629 = __overrideAll_629({ - visible: _$layout_attributes_596.visible, +var _$axis_attributes_691 = __overrideAll_691({ + visible: _$layout_attributes_659.visible, showspikes: { valType: 'boolean', @@ -111508,7 +112308,7 @@ var _$axis_attributes_629 = __overrideAll_629({ spikecolor: { valType: 'color', - dflt: _$color_411.defaultLine, + dflt: _$color_473.defaultLine, }, showbackground: { @@ -111529,51 +112329,51 @@ var _$axis_attributes_629 = __overrideAll_629({ dflt: true, }, - color: _$layout_attributes_596.color, - categoryorder: _$layout_attributes_596.categoryorder, - categoryarray: _$layout_attributes_596.categoryarray, - title: _$layout_attributes_596.title, - titlefont: _$layout_attributes_596.titlefont, - type: _$layout_attributes_596.type, - autorange: _$layout_attributes_596.autorange, - rangemode: _$layout_attributes_596.rangemode, - range: _$layout_attributes_596.range, + color: _$layout_attributes_659.color, + categoryorder: _$layout_attributes_659.categoryorder, + categoryarray: _$layout_attributes_659.categoryarray, + title: _$layout_attributes_659.title, + titlefont: _$layout_attributes_659.titlefont, + type: _$layout_attributes_659.type, + autorange: _$layout_attributes_659.autorange, + rangemode: _$layout_attributes_659.rangemode, + range: _$layout_attributes_659.range, // ticks - tickmode: _$layout_attributes_596.tickmode, - nticks: _$layout_attributes_596.nticks, - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: _$layout_attributes_596.ticks, - mirror: _$layout_attributes_596.mirror, - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - tickfont: _$layout_attributes_596.tickfont, - tickangle: _$layout_attributes_596.tickangle, - tickprefix: _$layout_attributes_596.tickprefix, - showtickprefix: _$layout_attributes_596.showtickprefix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showticksuffix: _$layout_attributes_596.showticksuffix, - showexponent: _$layout_attributes_596.showexponent, - exponentformat: _$layout_attributes_596.exponentformat, - separatethousands: _$layout_attributes_596.separatethousands, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - hoverformat: _$layout_attributes_596.hoverformat, + tickmode: _$layout_attributes_659.tickmode, + nticks: _$layout_attributes_659.nticks, + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: _$layout_attributes_659.ticks, + mirror: _$layout_attributes_659.mirror, + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + tickfont: _$layout_attributes_659.tickfont, + tickangle: _$layout_attributes_659.tickangle, + tickprefix: _$layout_attributes_659.tickprefix, + showtickprefix: _$layout_attributes_659.showtickprefix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showticksuffix: _$layout_attributes_659.showticksuffix, + showexponent: _$layout_attributes_659.showexponent, + exponentformat: _$layout_attributes_659.exponentformat, + separatethousands: _$layout_attributes_659.separatethousands, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + hoverformat: _$layout_attributes_659.hoverformat, // lines and grids - showline: _$layout_attributes_596.showline, - linecolor: _$layout_attributes_596.linecolor, - linewidth: _$layout_attributes_596.linewidth, - showgrid: _$layout_attributes_596.showgrid, - gridcolor: __extendFlat_629({}, _$layout_attributes_596.gridcolor, // shouldn't this be on-par with 2D? + showline: _$layout_attributes_659.showline, + linecolor: _$layout_attributes_659.linecolor, + linewidth: _$layout_attributes_659.linewidth, + showgrid: _$layout_attributes_659.showgrid, + gridcolor: __extendFlat_691({}, _$layout_attributes_659.gridcolor, // shouldn't this be on-par with 2D? {dflt: 'rgb(204, 204, 204)'}), - gridwidth: _$layout_attributes_596.gridwidth, - zeroline: _$layout_attributes_596.zeroline, - zerolinecolor: _$layout_attributes_596.zerolinecolor, - zerolinewidth: _$layout_attributes_596.zerolinewidth + gridwidth: _$layout_attributes_659.gridwidth, + zeroline: _$layout_attributes_659.zeroline, + zerolinecolor: _$layout_attributes_659.zerolinecolor, + zerolinewidth: _$layout_attributes_659.zerolinewidth }, 'plot', 'from-root'); /** @@ -111587,29 +112387,29 @@ var _$axis_attributes_629 = __overrideAll_629({ 'use strict'; -var __colorMix_630 = _$tinycolor_352.mix; +var __colorMix_692 = _$tinycolor_414.mix; -/* removed: var _$lib_539 = require('../../../lib'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; -/* removed: var _$axis_attributes_629 = require('./axis_attributes'); */; -/* removed: var _$handleTypeDefaults_608 = require('../../cartesian/type_defaults'); */; -/* removed: var _$handleAxisDefaults_586 = require('../../cartesian/axis_defaults'); */; +/* removed: var _$axis_attributes_691 = require('./axis_attributes'); */; +/* removed: var _$handleTypeDefaults_670 = require('../../cartesian/type_defaults'); */; +/* removed: var _$handleAxisDefaults_649 = require('../../cartesian/axis_defaults'); */; -var __axesNames_630 = ['xaxis', 'yaxis', 'zaxis']; +var __axesNames_692 = ['xaxis', 'yaxis', 'zaxis']; // TODO: hard-coded lightness fraction based on gridline default colors // that differ from other subplot types. var gridLightness = 100 * (204 - 0x44) / (255 - 0x44); -var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutOut, options) { +var _$supplyLayoutDefaults_692 = function supplyLayoutDefaults(layoutIn, layoutOut, options) { var containerIn, containerOut; function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$axis_attributes_629, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$axis_attributes_691, attr, dflt); } - for(var j = 0; j < __axesNames_630.length; j++) { - var axName = __axesNames_630[j]; + for(var j = 0; j < __axesNames_692.length; j++) { + var axName = __axesNames_692[j]; containerIn = layoutIn[axName] || {}; containerOut = layoutOut[axName] = { @@ -111617,9 +112417,9 @@ var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutO _name: axName }; - _$handleTypeDefaults_608(containerIn, containerOut, coerce, options.data); + _$handleTypeDefaults_670(containerIn, containerOut, coerce, options.data); - _$handleAxisDefaults_586( + _$handleAxisDefaults_649( containerIn, containerOut, coerce, @@ -111633,10 +112433,10 @@ var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutO }, options.fullLayout); - coerce('gridcolor', __colorMix_630(containerOut.color, options.bgColor, gridLightness).toRgbString()); + coerce('gridcolor', __colorMix_692(containerOut.color, options.bgColor, gridLightness).toRgbString()); coerce('title', axName[0]); // shouldn't this be on-par with 2D? - containerOut.setScale = _$lib_539.noop; + containerOut.setScale = _$lib_601.noop; if(coerce('showspikes')) { coerce('spikesides'); @@ -111660,10 +112460,10 @@ var _$supplyLayoutDefaults_630 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$axis_attributes_629 = require('./axis_attributes'); */; -var __domainAttrs_633 = _$domain_610.attributes; -var __extendFlat_633 = _$extend_528.extendFlat; -var __counterRegex_633 = _$lib_539.counterRegex; +/* removed: var _$axis_attributes_691 = require('./axis_attributes'); */; +var __domainAttrs_695 = _$domain_672.attributes; +var __extendFlat_695 = _$extend_590.extendFlat; +var __counterRegex_695 = _$lib_601.counterRegex; function makeCameraVector(x, y, z) { return { @@ -111689,8 +112489,8 @@ function makeCameraVector(x, y, z) { }; } -var _$layout_attributes_633 = { - _arrayAttrRegexps: [__counterRegex_633('scene', '.annotations', true)], +var _$layout_attributes_695 = { + _arrayAttrRegexps: [__counterRegex_695('scene', '.annotations', true)], bgcolor: { valType: 'color', @@ -111699,18 +112499,18 @@ var _$layout_attributes_633 = { editType: 'plot' }, camera: { - up: __extendFlat_633(makeCameraVector(0, 0, 1), { + up: __extendFlat_695(makeCameraVector(0, 0, 1), { }), - center: __extendFlat_633(makeCameraVector(0, 0, 0), { + center: __extendFlat_695(makeCameraVector(0, 0, 0), { }), - eye: __extendFlat_633(makeCameraVector(1.25, 1.25, 1.25), { + eye: __extendFlat_695(makeCameraVector(1.25, 1.25, 1.25), { }), editType: 'camera' }, - domain: __domainAttrs_633({name: 'scene', editType: 'plot'}), + domain: __domainAttrs_695({name: 'scene', editType: 'plot'}), aspectmode: { valType: 'enumerated', @@ -111751,9 +112551,9 @@ var _$layout_attributes_633 = { }, - xaxis: _$axis_attributes_629, - yaxis: _$axis_attributes_629, - zaxis: _$axis_attributes_629, + xaxis: _$axis_attributes_691, + yaxis: _$axis_attributes_691, + zaxis: _$axis_attributes_691, dragmode: { valType: 'enumerated', @@ -111794,16 +112594,16 @@ var _$layout_attributes_633 = { 'use strict'; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$color_411 = require('../../../components/color'); */; -/* removed: var _$registry_668 = require('../../../registry'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$color_473 = require('../../../components/color'); */; +/* removed: var _$registry_731 = require('../../../registry'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../../subplot_defaults'); */; -/* removed: var _$supplyLayoutDefaults_630 = require('./axis_defaults'); */; -/* removed: var _$layout_attributes_633 = require('./layout_attributes'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../../subplot_defaults'); */; +/* removed: var _$supplyLayoutDefaults_692 = require('./axis_defaults'); */; +/* removed: var _$layout_attributes_695 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_632 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { +var _$supplyLayoutDefaults_694 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { var hasNon3D = layoutOut._basePlotModules.length > 1; // some layout-wide attribute are used in all scenes @@ -111811,13 +112611,13 @@ var _$supplyLayoutDefaults_632 = function supplyLayoutDefaults(layoutIn, layoutO function getDfltFromLayout(attr) { if(hasNon3D) return; - var isValid = _$lib_539.validate(layoutIn[attr], _$layout_attributes_633[attr]); + var isValid = _$lib_601.validate(layoutIn[attr], _$layout_attributes_695[attr]); if(isValid) return layoutIn[attr]; } - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'gl3d', - attributes: _$layout_attributes_633, + attributes: _$layout_attributes_695, handleDefaults: handleGl3dDefaults, fullLayout: layoutOut, font: layoutOut.font, @@ -111842,7 +112642,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { */ var bgcolor = coerce('bgcolor'), - bgColorCombined = _$color_411.combine(bgcolor, opts.paper_bgcolor); + bgColorCombined = _$color_473.combine(bgcolor, opts.paper_bgcolor); var cameraKeys = ['up', 'center', 'eye']; @@ -111882,7 +112682,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { sceneLayoutIn.aspectmode = sceneLayoutOut.aspectmode; } - _$supplyLayoutDefaults_630(sceneLayoutIn, sceneLayoutOut, { + _$supplyLayoutDefaults_692(sceneLayoutIn, sceneLayoutOut, { font: opts.font, scene: opts.id, data: opts.fullData, @@ -111891,7 +112691,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { fullLayout: opts.fullLayout }); - _$registry_668.getComponentMethod('annotations3d', 'handleDefaults')( + _$registry_731.getComponentMethod('annotations3d', 'handleDefaults')( sceneLayoutIn, sceneLayoutOut, opts ); @@ -111899,7 +112699,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { coerce('hovermode', opts.getDfltFromLayout('hovermode')); } -var _$invert_173 = invert; +var _$invert_230 = invert; /** * Inverts a mat4 @@ -111954,7 +112754,7 @@ function invert(out, a) { return out; }; -var _$identity_172 = __identity_172; +var _$identity_229 = __identity_229; /** * Set a mat4 to the identity matrix @@ -111962,7 +112762,7 @@ var _$identity_172 = __identity_172; * @param {mat4} out the receiving matrix * @returns {mat4} out */ -function __identity_172(out) { +function __identity_229(out) { out[0] = 1; out[1] = 0; out[2] = 0; @@ -111981,9 +112781,9 @@ function __identity_172(out) { out[15] = 1; return out; }; -/* removed: var _$identity_172 = require('./identity'); */; +/* removed: var _$identity_229 = require('./identity'); */; -var _$lookAt_174 = lookAt; +var _$lookAt_231 = lookAt; /** * Generates a look-at matrix with the given eye position, focal point, and up axis @@ -112009,7 +112809,7 @@ function lookAt(out, eye, center, up) { if (Math.abs(eyex - centerx) < 0.000001 && Math.abs(eyey - centery) < 0.000001 && Math.abs(eyez - centerz) < 0.000001) { - return _$identity_172(out); + return _$identity_229(out); } z0 = eyex - centerx; @@ -112071,7 +112871,7 @@ function lookAt(out, eye, center, up) { return out; }; -var _$rotateX_178 = rotateX; +var _$rotateX_235 = rotateX; /** * Rotates a matrix by the given angle around the X axis @@ -112115,7 +112915,7 @@ function rotateX(out, a, rad) { out[11] = a23 * c - a13 * s; return out; }; -var _$rotateY_179 = rotateY; +var _$rotateY_236 = rotateY; /** * Rotates a matrix by the given angle around the Y axis @@ -112159,7 +112959,7 @@ function rotateY(out, a, rad) { out[11] = a03 * s + a23 * c; return out; }; -var _$rotateZ_180 = rotateZ; +var _$rotateZ_237 = rotateZ; /** * Rotates a matrix by the given angle around the Z axis @@ -112203,7 +113003,7 @@ function rotateZ(out, a, rad) { out[7] = a13 * c - a03 * s; return out; }; -var _$scale_181 = scale; +var _$scale_238 = scale; /** * Scales the mat4 by the dimensions in the given vec3 @@ -112234,7 +113034,7 @@ function scale(out, a, v) { out[15] = a[15]; return out; }; -var _$translate_182 = translate; +var _$translate_239 = translate; /** * Translate a mat4 by the given vector @@ -112272,7 +113072,7 @@ function translate(out, a, v) { return out; }; -var _$normalize_227 = __normalize_227; +var _$normalize_284 = __normalize_284; /** * Normalize a vec3 @@ -112281,7 +113081,7 @@ var _$normalize_227 = __normalize_227; * @param {vec3} a vector to normalize * @returns {vec3} out */ -function __normalize_227(out, a) { +function __normalize_284(out, a) { var x = a[0], y = a[1], z = a[2] @@ -112295,7 +113095,7 @@ function __normalize_227(out, a) { } return out } -var _$determinant_169 = __determinant_169; +var _$determinant_226 = __determinant_226; /** * Calculates the determinant of a mat4 @@ -112303,7 +113103,7 @@ var _$determinant_169 = __determinant_169; * @param {mat4} a the source matrix * @returns {Number} determinant of a */ -function __determinant_169(a) { +function __determinant_226(a) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], @@ -112325,7 +113125,7 @@ function __determinant_169(a) { // Calculate the determinant return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; }; -var _$lerp_226 = __lerp_226; +var _$lerp_283 = __lerp_283; /** * Performs a linear interpolation between two vec3's @@ -112336,7 +113136,7 @@ var _$lerp_226 = __lerp_226; * @param {Number} t interpolation amount between the two inputs * @returns {vec3} out */ -function __lerp_226(out, a, b, t) { +function __lerp_283(out, a, b, t) { var ax = a[0], ay = a[1], az = a[2] @@ -112345,7 +113145,7 @@ function __lerp_226(out, a, b, t) { out[2] = az + t * (b[2] - az) return out } -var _$clone_167 = clone; +var _$clone_224 = clone; /** * Creates a new mat4 initialized with values from an existing matrix @@ -112373,7 +113173,7 @@ function clone(a) { out[15] = a[15]; return out; }; -var _$create_168 = create; +var _$create_225 = create; /** * Creates a new identity mat4 @@ -112400,7 +113200,7 @@ function create() { out[15] = 1; return out; }; -var _$transpose_183 = transpose; +var _$transpose_240 = transpose; /** * Transpose the values of a mat4 @@ -112449,7 +113249,7 @@ function transpose(out, a) { return out; }; -var _$cross_223 = __cross_223; +var _$cross_280 = __cross_280; /** * Computes the cross product of two vec3's @@ -112459,7 +113259,7 @@ var _$cross_223 = __cross_223; * @param {vec3} b the second operand * @returns {vec3} out */ -function __cross_223(out, a, b) { +function __cross_280(out, a, b) { var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2] @@ -112468,7 +113268,7 @@ function __cross_223(out, a, b) { out[2] = ax * by - ay * bx return out } -var _$dot_224 = __dot_224; +var _$dot_281 = __dot_281; /** * Calculates the dot product of two vec3's @@ -112477,10 +113277,10 @@ var _$dot_224 = __dot_224; * @param {vec3} b the second operand * @returns {Number} dot product of a and b */ -function __dot_224(a, b) { +function __dot_281(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -var _$length_225 = length; +var _$length_282 = length; /** * Calculates the length of a vec3 @@ -112494,7 +113294,7 @@ function length(a) { z = a[2] return Math.sqrt(x*x + y*y + z*z) } -var _$normalize_257 = function normalize(out, mat) { +var _$normalize_314 = function normalize(out, mat) { var m44 = mat[15] // Cannot normalize. if (m44 === 0) @@ -112521,27 +113321,27 @@ https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix */ -/* removed: var _$normalize_257 = require('./normalize') */; +/* removed: var _$normalize_314 = require('./normalize') */; -/* removed: var _$create_168 = require('gl-mat4/create') */; -/* removed: var _$clone_167 = require('gl-mat4/clone') */; -/* removed: var _$determinant_169 = require('gl-mat4/determinant') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$transpose_183 = require('gl-mat4/transpose') */; +/* removed: var _$create_225 = require('gl-mat4/create') */; +/* removed: var _$clone_224 = require('gl-mat4/clone') */; +/* removed: var _$determinant_226 = require('gl-mat4/determinant') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$transpose_240 = require('gl-mat4/transpose') */; var vec3 = { - length: _$length_225, - normalize: _$normalize_227, - dot: _$dot_224, - cross: _$cross_223 + length: _$length_282, + normalize: _$normalize_284, + dot: _$dot_281, + cross: _$cross_280 } -var tmp = _$create_168() -var perspectiveMatrix = _$create_168() +var tmp = _$create_225() +var perspectiveMatrix = _$create_225() var tmpVec4 = [0, 0, 0, 0] var row = [ [0,0,0], [0,0,0], [0,0,0] ] var pdum3 = [0,0,0] -var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { +var _$decomposeMat4_313 = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { if (!translation) translation = [0,0,0] if (!scale) scale = [0,0,0] if (!skew) skew = [0,0,0] @@ -112549,12 +113349,12 @@ var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, ske if (!quaternion) quaternion = [0,0,0,1] //normalize, if not possible then bail out early - if (!_$normalize_257(tmp, matrix)) + if (!_$normalize_314(tmp, matrix)) return false // perspectiveMatrix is used to solve for perspective, but it also provides // an easy way to test for singularity of the upper 3x3 component. - _$clone_167(perspectiveMatrix, tmp) + _$clone_224(perspectiveMatrix, tmp) perspectiveMatrix[3] = 0 perspectiveMatrix[7] = 0 @@ -112563,7 +113363,7 @@ var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, ske // If the perspectiveMatrix is not invertible, we are also unable to // decompose, so we'll bail early. Constant taken from SkMatrix44::invert. - if (Math.abs(_$determinant_169(perspectiveMatrix) < 1e-8)) + if (Math.abs(_$determinant_226(perspectiveMatrix) < 1e-8)) return false var a03 = tmp[3], a13 = tmp[7], a23 = tmp[11], @@ -112579,9 +113379,9 @@ var _$decomposeMat4_256 = function decomposeMat4(matrix, translation, scale, ske // Solve the equation by inverting perspectiveMatrix and multiplying // rightHandSide by the inverse. // resuing the perspectiveMatrix here since it's no longer needed - var ret = _$invert_173(perspectiveMatrix, perspectiveMatrix) + var ret = _$invert_230(perspectiveMatrix, perspectiveMatrix) if (!ret) return false - _$transpose_183(perspectiveMatrix, perspectiveMatrix) + _$transpose_240(perspectiveMatrix, perspectiveMatrix) //multiply by transposed inverse perspective matrix, into perspective vec4 vec4multMat4(perspective, tmpVec4, perspectiveMatrix) @@ -112683,7 +113483,7 @@ function combine(out, a, b, scale1, scale2) { out[1] = a[1] * scale1 + b[1] * scale2 out[2] = a[2] * scale1 + b[2] * scale2 } -var _$fromRotationTranslation_171 = fromRotationTranslation; +var _$fromRotationTranslation_228 = fromRotationTranslation; /** * Creates a matrix from a quaternion rotation and vector translation @@ -112736,7 +113536,7 @@ function fromRotationTranslation(out, q, v) { return out; }; -var _$multiply_175 = __multiply_175; +var _$multiply_232 = __multiply_232; /** * Multiplies two mat4's @@ -112746,7 +113546,7 @@ var _$multiply_175 = __multiply_175; * @param {mat4} b the second operand * @returns {mat4} out */ -function __multiply_175(out, a, b) { +function __multiply_232(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], @@ -112790,18 +113590,18 @@ From: http://www.w3.org/TR/css3-transforms/#recomposing-to-a-3d-matrix */ var mat4 = { - identity: _$identity_172, - translate: _$translate_182, - multiply: _$multiply_175, - create: _$create_168, - scale: _$scale_181, - fromRotationTranslation: _$fromRotationTranslation_171 + identity: _$identity_229, + translate: _$translate_239, + multiply: _$multiply_232, + create: _$create_225, + scale: _$scale_238, + fromRotationTranslation: _$fromRotationTranslation_228 } var rotationMatrix = mat4.create() var temp = mat4.create() -var _$recomposeMat4_259 = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { +var _$recomposeMat4_316 = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) { mat4.identity(matrix) //apply translation & rotation @@ -112838,7 +113638,7 @@ var _$recomposeMat4_259 = function recomposeMat4(matrix, translation, scale, ske mat4.scale(matrix, matrix, scale) return matrix } -var _$slerp_199 = slerp +var _$slerp_256 = slerp /** * Performs a spherical linear interpolation between two quat @@ -112890,53 +113690,53 @@ function slerp (out, a, b, t) { return out } -var _$quatSlerp_305 = _$slerp_199 -/* removed: var _$lerp_226 = require('gl-vec3/lerp') */; +var _$quatSlerp_367 = _$slerp_256 +/* removed: var _$lerp_283 = require('gl-vec3/lerp') */; -/* removed: var _$recomposeMat4_259 = require('mat4-recompose') */; -/* removed: var _$decomposeMat4_256 = require('mat4-decompose') */; -/* removed: var _$determinant_169 = require('gl-mat4/determinant') */; -/* removed: var _$quatSlerp_305 = require('quat-slerp') */; +/* removed: var _$recomposeMat4_316 = require('mat4-recompose') */; +/* removed: var _$decomposeMat4_313 = require('mat4-decompose') */; +/* removed: var _$determinant_226 = require('gl-mat4/determinant') */; +/* removed: var _$quatSlerp_367 = require('quat-slerp') */; var state0 = state() var state1 = state() -var __tmp_258 = state() +var __tmp_315 = state() -var _$interpolate_258 = interpolate +var _$interpolate_315 = interpolate function interpolate(out, start, end, alpha) { - if (_$determinant_169(start) === 0 || _$determinant_169(end) === 0) + if (_$determinant_226(start) === 0 || _$determinant_226(end) === 0) return false //decompose the start and end matrices into individual components - var r0 = _$decomposeMat4_256(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) - var r1 = _$decomposeMat4_256(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) + var r0 = _$decomposeMat4_313(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) + var r1 = _$decomposeMat4_313(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) if (!r0 || !r1) return false //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) - _$lerp_226(__tmp_258.translate, state0.translate, state1.translate, alpha) - _$lerp_226(__tmp_258.skew, state0.skew, state1.skew, alpha) - _$lerp_226(__tmp_258.scale, state0.scale, state1.scale, alpha) - _$lerp_226(__tmp_258.perspective, state0.perspective, state1.perspective, alpha) - _$quatSlerp_305(__tmp_258.quaternion, state0.quaternion, state1.quaternion, alpha) + _$lerp_283(__tmp_315.translate, state0.translate, state1.translate, alpha) + _$lerp_283(__tmp_315.skew, state0.skew, state1.skew, alpha) + _$lerp_283(__tmp_315.scale, state0.scale, state1.scale, alpha) + _$lerp_283(__tmp_315.perspective, state0.perspective, state1.perspective, alpha) + _$quatSlerp_367(__tmp_315.quaternion, state0.quaternion, state1.quaternion, alpha) //and recompose into our 'out' matrix - _$recomposeMat4_259(out, __tmp_258.translate, __tmp_258.scale, __tmp_258.skew, __tmp_258.perspective, __tmp_258.quaternion) + _$recomposeMat4_316(out, __tmp_315.translate, __tmp_315.scale, __tmp_315.skew, __tmp_315.perspective, __tmp_315.quaternion) return true } function state() { return { - translate: __vec3_258(), - scale: __vec3_258(1), - skew: __vec3_258(), + translate: __vec3_315(), + scale: __vec3_315(1), + skew: __vec3_315(), perspective: vec4(), quaternion: vec4() } } -function __vec3_258(n) { +function __vec3_315(n) { return [n||0,n||0,n||0] } @@ -112945,20 +113745,20 @@ function vec4() { } 'use strict' -/* removed: var _$searchBounds_71 = require('binary-search-bounds') */; -/* removed: var _$interpolate_258 = require('mat4-interpolate') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$rotateX_178 = require('gl-mat4/rotateX') */; -/* removed: var _$rotateY_179 = require('gl-mat4/rotateY') */; -/* removed: var _$rotateZ_180 = require('gl-mat4/rotateZ') */; -/* removed: var _$lookAt_174 = require('gl-mat4/lookAt') */; -/* removed: var _$translate_182 = require('gl-mat4/translate') */; -/* removed: var _$scale_181 = require('gl-mat4/scale') */; -/* removed: var _$normalize_227 = require('gl-vec3/normalize') */; +/* removed: var _$searchBounds_72 = require('binary-search-bounds') */; +/* removed: var _$interpolate_315 = require('mat4-interpolate') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$rotateX_235 = require('gl-mat4/rotateX') */; +/* removed: var _$rotateY_236 = require('gl-mat4/rotateY') */; +/* removed: var _$rotateZ_237 = require('gl-mat4/rotateZ') */; +/* removed: var _$lookAt_231 = require('gl-mat4/lookAt') */; +/* removed: var _$translate_239 = require('gl-mat4/translate') */; +/* removed: var _$scale_238 = require('gl-mat4/scale') */; +/* removed: var _$normalize_284 = require('gl-vec3/normalize') */; var DEFAULT_CENTER = [0,0,0] -var _$createMatrixCameraController_260 = createMatrixCameraController +var _$createMatrixCameraController_318 = createMatrixCameraController function MatrixCameraController(initialMatrix) { this._components = initialMatrix.slice() @@ -112974,11 +113774,11 @@ function MatrixCameraController(initialMatrix) { this._limits = [-Infinity, Infinity] } -var __proto_260 = MatrixCameraController.prototype +var __proto_318 = MatrixCameraController.prototype -__proto_260.recalcMatrix = function(t) { +__proto_318.recalcMatrix = function(t) { var time = this._time - var tidx = _$searchBounds_71.le(time, t) + var tidx = _$searchBounds_72.le(time, t) var mat = this.computedMatrix if(tidx < 0) { return @@ -113007,7 +113807,7 @@ __proto_260.recalcMatrix = function(t) { mat[i] = prev[i] } } else { - _$interpolate_258(mat, prev, next, (t - time[tidx])/dt) + _$interpolate_315(mat, prev, next, (t - time[tidx])/dt) } } @@ -113015,10 +113815,10 @@ __proto_260.recalcMatrix = function(t) { up[0] = mat[1] up[1] = mat[5] up[2] = mat[9] - _$normalize_227(up, up) + _$normalize_284(up, up) var imat = this.computedInverse - _$invert_173(imat, mat) + _$invert_230(imat, mat) var eye = this.computedEye var w = imat[15] eye[0] = imat[12]/w @@ -113032,7 +113832,7 @@ __proto_260.recalcMatrix = function(t) { } } -__proto_260.idle = function(t) { +__proto_318.idle = function(t) { if(t < this.lastT()) { return } @@ -113044,8 +113844,8 @@ __proto_260.idle = function(t) { this._time.push(t) } -__proto_260.flush = function(t) { - var idx = _$searchBounds_71.gt(this._time, t) - 2 +__proto_318.flush = function(t) { + var idx = _$searchBounds_72.gt(this._time, t) - 2 if(idx < 0) { return } @@ -113053,16 +113853,16 @@ __proto_260.flush = function(t) { this._components.splice(0, 16*idx) } -__proto_260.lastT = function() { +__proto_318.lastT = function() { return this._time[this._time.length-1] } -__proto_260.lookAt = function(t, eye, center, up) { +__proto_318.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_174(this.computedMatrix, eye, center, up)) + this.setMatrix(t, _$lookAt_231(this.computedMatrix, eye, center, up)) var d2 = 0.0 for(var i=0; i<3; ++i) { d2 += Math.pow(center[i] - eye[i], 2) @@ -113071,38 +113871,38 @@ __proto_260.lookAt = function(t, eye, center, up) { this.computedRadius[0] = d2 } -__proto_260.rotate = function(t, yaw, pitch, roll) { +__proto_318.rotate = function(t, yaw, pitch, roll) { this.recalcMatrix(t) var mat = this.computedInverse - if(yaw) _$rotateY_179(mat, mat, yaw) - if(pitch) _$rotateX_178(mat, mat, pitch) - if(roll) _$rotateZ_180(mat, mat, roll) - this.setMatrix(t, _$invert_173(this.computedMatrix, mat)) + if(yaw) _$rotateY_236(mat, mat, yaw) + if(pitch) _$rotateX_235(mat, mat, pitch) + if(roll) _$rotateZ_237(mat, mat, roll) + this.setMatrix(t, _$invert_230(this.computedMatrix, mat)) } var tvec = [0,0,0] -__proto_260.pan = function(t, dx, dy, dz) { +__proto_318.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_182(mat, mat, tvec) - this.setMatrix(t, _$invert_173(mat, mat)) + _$translate_239(mat, mat, tvec) + this.setMatrix(t, _$invert_230(mat, mat)) } -__proto_260.translate = function(t, dx, dy, dz) { +__proto_318.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_182(mat, mat, tvec) + _$translate_239(mat, mat, tvec) this.setMatrix(t, mat) } -__proto_260.setMatrix = function(t, mat) { +__proto_318.setMatrix = function(t, mat) { if(t < this.lastT()) { return } @@ -113112,17 +113912,17 @@ __proto_260.setMatrix = function(t, mat) { } } -__proto_260.setDistance = function(t, d) { +__proto_318.setDistance = function(t, d) { this.computedRadius[0] = d } -__proto_260.setDistanceLimits = function(a,b) { +__proto_318.setDistanceLimits = function(a,b) { var lim = this._limits lim[0] = a lim[1] = b } -__proto_260.getDistanceLimits = function(out) { +__proto_318.getDistanceLimits = function(out) { var lim = this._limits if(out) { out[0] = lim[0] @@ -113142,7 +113942,7 @@ function createMatrixCameraController(options) { return new MatrixCameraController(matrix) } -var _$hermite_114 = {}; +var _$hermite_115 = {}; "use strict" function dcubicHermite(p0, v0, p1, v1, t, f) { @@ -113180,16 +113980,16 @@ function cubicHermite(p0, v0, p1, v1, t, f) { return h00*p0 + h10*v0 + h01*p1 + h11*v1 } -_$hermite_114 = cubicHermite -_$hermite_114.derivative = dcubicHermite +_$hermite_115 = cubicHermite +_$hermite_115.derivative = dcubicHermite 'use strict' -var _$createFilteredVector_140 = createFilteredVector +var _$createFilteredVector_197 = createFilteredVector -/* removed: var _$hermite_114 = require('cubic-hermite') */; -/* removed: var _$searchBounds_71 = require('binary-search-bounds') */; +/* removed: var _$hermite_115 = require('cubic-hermite') */; +/* removed: var _$searchBounds_72 = require('binary-search-bounds') */; -function __clamp_140(lo, hi, x) { +function __clamp_197(lo, hi, x) { return Math.min(hi, Math.max(lo, x)) } @@ -113206,10 +114006,10 @@ function FilteredVector(state0, velocity0, t0) { this._scratch = [ state0.slice(), state0.slice(), state0.slice(), state0.slice(), state0.slice() ] } -var __proto_140 = FilteredVector.prototype +var __proto_197 = FilteredVector.prototype -__proto_140.flush = function(t) { - var idx = _$searchBounds_71.gt(this._time, t) - 1 +__proto_197.flush = function(t) { + var idx = _$searchBounds_72.gt(this._time, t) - 1 if(idx <= 0) { return } @@ -113218,10 +114018,10 @@ __proto_140.flush = function(t) { this._velocity.splice(0, idx * this.dimension) } -__proto_140.curve = function(t) { +__proto_197.curve = function(t) { var time = this._time var n = time.length - var idx = _$searchBounds_71.le(time, t) + var idx = _$searchBounds_72.le(time, t) var result = this._scratch[0] var state = this._state var velocity = this._velocity @@ -113260,21 +114060,21 @@ __proto_140.curve = function(t) { result[i] = x0[i] } } else { - _$hermite_114(x0, v0, x1, v1, (t-t0)/dt, result) + _$hermite_115(x0, v0, x1, v1, (t-t0)/dt, result) } } var lo = bounds[0] var hi = bounds[1] for(var i=0; i=0; --i) { @@ -113332,7 +114132,7 @@ __proto_140.stable = function() { return true } -__proto_140.jump = function(t) { +__proto_197.jump = function(t) { var t0 = this.lastT() var d = this.dimension if(t < t0 || arguments.length !== d+1) { @@ -113353,12 +114153,12 @@ __proto_140.jump = function(t) { } this._time.push(t) for(var i=d; i>0; --i) { - state.push(__clamp_140(lo[i-1], hi[i-1], arguments[i])) + state.push(__clamp_197(lo[i-1], hi[i-1], arguments[i])) velocity.push(0) } } -__proto_140.push = function(t) { +__proto_197.push = function(t) { var t0 = this.lastT() var d = this.dimension if(t < t0 || arguments.length !== d+1) { @@ -113374,13 +114174,13 @@ __proto_140.push = function(t) { var sf = (dt > 1e-6) ? 1/dt : 0 this._time.push(t) for(var i=d; i>0; --i) { - var xc = __clamp_140(lo[i-1], hi[i-1], arguments[i]) + var xc = __clamp_197(lo[i-1], hi[i-1], arguments[i]) state.push(xc) velocity.push((xc - state[ptr++]) * sf) } } -__proto_140.set = function(t) { +__proto_197.set = function(t) { var d = this.dimension if(t < this.lastT() || arguments.length !== d+1) { return @@ -113392,12 +114192,12 @@ __proto_140.set = function(t) { var hi = bounds[1] this._time.push(t) for(var i=d; i>0; --i) { - state.push(__clamp_140(lo[i-1], hi[i-1], arguments[i])) + state.push(__clamp_197(lo[i-1], hi[i-1], arguments[i])) velocity.push(0) } } -__proto_140.move = function(t) { +__proto_197.move = function(t) { var t0 = this.lastT() var d = this.dimension if(t <= t0 || arguments.length !== d+1) { @@ -113414,12 +114214,12 @@ __proto_140.move = function(t) { this._time.push(t) for(var i=d; i>0; --i) { var dx = arguments[i] - state.push(__clamp_140(lo[i-1], hi[i-1], state[statePtr++] + dx)) + state.push(__clamp_197(lo[i-1], hi[i-1], state[statePtr++] + dx)) velocity.push(dx * sf) } } -__proto_140.idle = function(t) { +__proto_197.idle = function(t) { var t0 = this.lastT() if(t < t0) { return @@ -113434,7 +114234,7 @@ __proto_140.idle = function(t) { var dt = t - t0 this._time.push(t) for(var i=d-1; i>=0; --i) { - state.push(__clamp_140(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) + state.push(__clamp_197(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) velocity.push(0) statePtr += 1 } @@ -113476,7 +114276,7 @@ function createFilteredVector(initState, initVelocity, initTime) { 'use strict' -var _$quatFromFrame_282 = quatFromFrame +var _$quatFromFrame_340 = quatFromFrame function quatFromFrame( out, @@ -113517,13 +114317,13 @@ function quatFromFrame( } 'use strict' -var _$createOrbitController_283 = createOrbitController +var _$createOrbitController_341 = createOrbitController -/* removed: var _$createFilteredVector_140 = require('filtered-vector') */; -/* removed: var _$lookAt_174 = require('gl-mat4/lookAt') */; -/* removed: var _$fromQuat_170 = require('gl-mat4/fromQuat') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$quatFromFrame_282 = require('./lib/quatFromFrame') */; +/* removed: var _$createFilteredVector_197 = require('filtered-vector') */; +/* removed: var _$lookAt_231 = require('gl-mat4/lookAt') */; +/* removed: var _$fromQuat_227 = require('gl-mat4/fromQuat') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$quatFromFrame_340 = require('./lib/quatFromFrame') */; function len3(x,y,z) { return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) @@ -113551,9 +114351,9 @@ function normalize4(out, a) { } function OrbitCameraController(initQuat, initCenter, initRadius) { - this.radius = _$createFilteredVector_140([initRadius]) - this.center = _$createFilteredVector_140(initCenter) - this.rotation = _$createFilteredVector_140(initQuat) + this.radius = _$createFilteredVector_197([initRadius]) + this.center = _$createFilteredVector_197(initCenter) + this.rotation = _$createFilteredVector_197(initQuat) this.computedRadius = this.radius.curve(0) this.computedCenter = this.center.curve(0) @@ -113565,16 +114365,16 @@ function OrbitCameraController(initQuat, initCenter, initRadius) { this.recalcMatrix(0) } -var __proto_283 = OrbitCameraController.prototype +var __proto_341 = OrbitCameraController.prototype -__proto_283.lastT = function() { +__proto_341.lastT = function() { return Math.max( this.radius.lastT(), this.center.lastT(), this.rotation.lastT()) } -__proto_283.recalcMatrix = function(t) { +__proto_341.recalcMatrix = function(t) { this.radius.curve(t) this.center.curve(t) this.rotation.curve(t) @@ -113583,7 +114383,7 @@ __proto_283.recalcMatrix = function(t) { normalize4(quat, quat) var mat = this.computedMatrix - _$fromQuat_170(mat, quat) + _$fromQuat_227(mat, quat) var center = this.computedCenter var eye = this.computedEye @@ -113606,7 +114406,7 @@ __proto_283.recalcMatrix = function(t) { } } -__proto_283.getMatrix = function(t, result) { +__proto_341.getMatrix = function(t, result) { this.recalcMatrix(t) var m = this.computedMatrix if(result) { @@ -113618,19 +114418,19 @@ __proto_283.getMatrix = function(t, result) { return m } -__proto_283.idle = function(t) { +__proto_341.idle = function(t) { this.center.idle(t) this.radius.idle(t) this.rotation.idle(t) } -__proto_283.flush = function(t) { +__proto_341.flush = function(t) { this.center.flush(t) this.radius.flush(t) this.rotation.flush(t) } -__proto_283.pan = function(t, dx, dy, dz) { +__proto_341.pan = function(t, dx, dy, dz) { dx = dx || 0.0 dy = dy || 0.0 dz = dz || 0.0 @@ -113683,7 +114483,7 @@ __proto_283.pan = function(t, dx, dy, dz) { this.radius.set(t, Math.log(radius)) } -__proto_283.rotate = function(t, dx, dy, dz) { +__proto_341.rotate = function(t, dx, dy, dz) { this.recalcMatrix(t) dx = dx||0.0 @@ -113763,7 +114563,7 @@ __proto_283.rotate = function(t, dx, dy, dz) { this.rotation.set(t, cx, cy, cz, cw) } -__proto_283.lookAt = function(t, eye, center, up) { +__proto_341.lookAt = function(t, eye, center, up) { this.recalcMatrix(t) center = center || this.computedCenter @@ -113771,10 +114571,10 @@ __proto_283.lookAt = function(t, eye, center, up) { up = up || this.computedUp var mat = this.computedMatrix - _$lookAt_174(mat, eye, center, up) + _$lookAt_231(mat, eye, center, up) var rotation = this.computedRotation - _$quatFromFrame_282(rotation, + _$quatFromFrame_340(rotation, mat[0], mat[1], mat[2], mat[4], mat[5], mat[6], mat[8], mat[9], mat[10]) @@ -113790,17 +114590,17 @@ __proto_283.lookAt = function(t, eye, center, up) { this.center.set(t, center[0], center[1], center[2]) } -__proto_283.translate = function(t, dx, dy, dz) { +__proto_341.translate = function(t, dx, dy, dz) { this.center.move(t, dx||0.0, dy||0.0, dz||0.0) } -__proto_283.setMatrix = function(t, matrix) { +__proto_341.setMatrix = function(t, matrix) { var rotation = this.computedRotation - _$quatFromFrame_282(rotation, + _$quatFromFrame_340(rotation, matrix[0], matrix[1], matrix[2], matrix[4], matrix[5], matrix[6], matrix[8], matrix[9], matrix[10]) @@ -113808,7 +114608,7 @@ __proto_283.setMatrix = function(t, matrix) { this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3]) var mat = this.computedMatrix - _$invert_173(mat, matrix) + _$invert_230(mat, matrix) var w = mat[15] if(Math.abs(w) > 1e-6) { var cx = mat[12]/w @@ -113825,13 +114625,13 @@ __proto_283.setMatrix = function(t, matrix) { } } -__proto_283.setDistance = function(t, d) { +__proto_341.setDistance = function(t, d) { if(d > 0) { this.radius.set(t, Math.log(d)) } } -__proto_283.setDistanceLimits = function(lo, hi) { +__proto_341.setDistanceLimits = function(lo, hi) { if(lo > 0) { lo = Math.log(lo) } else { @@ -113847,7 +114647,7 @@ __proto_283.setDistanceLimits = function(lo, hi) { this.radius.bounds[1][0] = hi } -__proto_283.getDistanceLimits = function(out) { +__proto_341.getDistanceLimits = function(out) { var bounds = this.radius.bounds if(out) { out[0] = Math.exp(bounds[0][0]) @@ -113857,7 +114657,7 @@ __proto_283.getDistanceLimits = function(out) { return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ] } -__proto_283.toJSON = function() { +__proto_341.toJSON = function() { this.recalcMatrix(this.lastT()) return { center: this.computedCenter.slice(), @@ -113868,7 +114668,7 @@ __proto_283.toJSON = function() { } } -__proto_283.fromJSON = function(options) { +__proto_341.fromJSON = function(options) { var t = this.lastT() var c = options.center if(c) { @@ -113908,7 +114708,7 @@ function createOrbitController(options) { return result } -var _$rotate_177 = __rotate_177; +var _$rotate_234 = __rotate_234; /** * Rotates a mat4 by the given angle @@ -113919,7 +114719,7 @@ var _$rotate_177 = __rotate_177; * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ -function __rotate_177(out, a, rad, axis) { +function __rotate_234(out, a, rad, axis) { var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, @@ -113974,16 +114774,16 @@ function __rotate_177(out, a, rad, axis) { }; 'use strict' -var _$createTurntableController_357 = createTurntableController +var _$createTurntableController_419 = createTurntableController -/* removed: var _$createFilteredVector_140 = require('filtered-vector') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; -/* removed: var _$rotate_177 = require('gl-mat4/rotate') */; -/* removed: var _$cross_223 = require('gl-vec3/cross') */; -/* removed: var _$normalize_227 = require('gl-vec3/normalize') */; -/* removed: var _$dot_224 = require('gl-vec3/dot') */; +/* removed: var _$createFilteredVector_197 = require('filtered-vector') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; +/* removed: var _$rotate_234 = require('gl-mat4/rotate') */; +/* removed: var _$cross_280 = require('gl-vec3/cross') */; +/* removed: var _$normalize_284 = require('gl-vec3/normalize') */; +/* removed: var _$dot_281 = require('gl-vec3/dot') */; -function __len3_357(x, y, z) { +function __len3_419(x, y, z) { return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2)) } @@ -114014,16 +114814,16 @@ function findOrthoPair(v) { for(var i=0; i<3; ++i) { u[i] -= (uv / vv) * v[i] } - _$normalize_227(u, u) + _$normalize_284(u, u) return u } function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, phi) { - this.center = _$createFilteredVector_140(center) - this.up = _$createFilteredVector_140(up) - this.right = _$createFilteredVector_140(right) - this.radius = _$createFilteredVector_140([radius]) - this.angle = _$createFilteredVector_140([theta, phi]) + this.center = _$createFilteredVector_197(center) + this.up = _$createFilteredVector_197(up) + this.right = _$createFilteredVector_197(right) + this.radius = _$createFilteredVector_197([radius]) + this.angle = _$createFilteredVector_197([theta, phi]) this.angle.bounds = [[-Infinity,-Math.PI/2], [Infinity,Math.PI/2]] this.setDistanceLimits(zoomMin, zoomMax) @@ -114042,9 +114842,9 @@ function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, this.recalcMatrix(0) } -var __proto_357 = TurntableController.prototype +var __proto_419 = TurntableController.prototype -__proto_357.setDistanceLimits = function(minDist, maxDist) { +__proto_419.setDistanceLimits = function(minDist, maxDist) { if(minDist > 0) { minDist = Math.log(minDist) } else { @@ -114060,7 +114860,7 @@ __proto_357.setDistanceLimits = function(minDist, maxDist) { this.radius.bounds[1][0] = maxDist } -__proto_357.getDistanceLimits = function(out) { +__proto_419.getDistanceLimits = function(out) { var bounds = this.radius.bounds[0] if(out) { out[0] = Math.exp(bounds[0][0]) @@ -114070,7 +114870,7 @@ __proto_357.getDistanceLimits = function(out) { return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ] } -__proto_357.recalcMatrix = function(t) { +__proto_419.recalcMatrix = function(t) { //Recompute curves this.center.curve(t) this.up.curve(t) @@ -114101,8 +114901,8 @@ __proto_357.recalcMatrix = function(t) { //Compute toward vector var toward = this.computedToward - _$cross_223(toward, up, right) - _$normalize_227(toward, toward) + _$cross_280(toward, up, right) + _$normalize_284(toward, toward) //Compute angular parameters var radius = Math.exp(this.computedRadius[0]) @@ -114142,7 +114942,7 @@ __proto_357.recalcMatrix = function(t) { var cx = ay * bz - az * by var cy = az * bx - ax * bz var cz = ax * by - ay * bx - var cl = __len3_357(cx, cy, cz) + var cl = __len3_419(cx, cy, cz) cx /= cl cy /= cl cz /= cl @@ -114164,7 +114964,7 @@ __proto_357.recalcMatrix = function(t) { mat[15] = 1.0 } -__proto_357.getMatrix = function(t, result) { +__proto_419.getMatrix = function(t, result) { this.recalcMatrix(t) var mat = this.computedMatrix if(result) { @@ -114177,7 +114977,7 @@ __proto_357.getMatrix = function(t, result) { } var zAxis = [0,0,0] -__proto_357.rotate = function(t, dtheta, dphi, droll) { +__proto_419.rotate = function(t, dtheta, dphi, droll) { this.angle.move(t, dtheta, dphi) if(droll) { this.recalcMatrix(t) @@ -114196,7 +114996,7 @@ __proto_357.rotate = function(t, dtheta, dphi, droll) { mat[4*i+1] = right[i] mat[4*i+2] = toward[i] } - _$rotate_177(mat, mat, droll, zAxis) + _$rotate_234(mat, mat, droll, zAxis) for(var i=0; i<3; ++i) { up[i] = mat[4*i] right[i] = mat[4*i+1] @@ -114207,7 +115007,7 @@ __proto_357.rotate = function(t, dtheta, dphi, droll) { } } -__proto_357.pan = function(t, dx, dy, dz) { +__proto_419.pan = function(t, dx, dy, dz) { dx = dx || 0.0 dy = dy || 0.0 dz = dz || 0.0 @@ -114220,7 +115020,7 @@ __proto_357.pan = function(t, dx, dy, dz) { var ux = mat[1] var uy = mat[5] var uz = mat[9] - var ul = __len3_357(ux, uy, uz) + var ul = __len3_419(ux, uy, uz) ux /= ul uy /= ul uz /= ul @@ -114232,7 +115032,7 @@ __proto_357.pan = function(t, dx, dy, dz) { rx -= ux * ru ry -= uy * ru rz -= uz * ru - var rl = __len3_357(rx, ry, rz) + var rl = __len3_419(rx, ry, rz) rx /= rl ry /= rl rz /= rl @@ -114248,7 +115048,7 @@ __proto_357.pan = function(t, dx, dy, dz) { this.radius.set(t, Math.log(radius)) } -__proto_357.translate = function(t, dx, dy, dz) { +__proto_419.translate = function(t, dx, dy, dz) { this.center.move(t, dx||0.0, dy||0.0, @@ -114256,7 +115056,7 @@ __proto_357.translate = function(t, dx, dy, dz) { } //Recenters the coordinate axes -__proto_357.setMatrix = function(t, mat, axes, noSnap) { +__proto_419.setMatrix = function(t, mat, axes, noSnap) { //Get the axes for tare var ushift = 1 @@ -114280,7 +115080,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { var uy = mat[ushift+4] var uz = mat[ushift+8] if(!noSnap) { - var ul = __len3_357(ux, uy, uz) + var ul = __len3_419(ux, uy, uz) ux /= ul uy /= ul uz /= ul @@ -114308,7 +115108,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { rx -= ux * ru ry -= uy * ru rz -= uz * ru - var rl = __len3_357(rx, ry, rz) + var rl = __len3_419(rx, ry, rz) rx /= rl ry /= rl rz /= rl @@ -114316,7 +115116,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { var fx = uy * rz - uz * ry var fy = uz * rx - ux * rz var fz = ux * ry - uy * rx - var fl = __len3_357(fx, fy, fz) + var fl = __len3_419(fx, fy, fz) fx /= fl fy /= fl fz /= fl @@ -114359,7 +115159,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { var dz = mat[10] var imat = this.computedMatrix - _$invert_173(imat, mat) + _$invert_230(imat, mat) var w = imat[15] var ex = imat[12] / w var ey = imat[13] / w @@ -114369,7 +115169,7 @@ __proto_357.setMatrix = function(t, mat, axes, noSnap) { this.center.jump(t, ex-dx*gs, ey-dy*gs, ez-dz*gs) } -__proto_357.lastT = function() { +__proto_419.lastT = function() { return Math.max( this.center.lastT(), this.up.lastT(), @@ -114378,7 +115178,7 @@ __proto_357.lastT = function() { this.angle.lastT()) } -__proto_357.idle = function(t) { +__proto_419.idle = function(t) { this.center.idle(t) this.up.idle(t) this.right.idle(t) @@ -114386,7 +115186,7 @@ __proto_357.idle = function(t) { this.angle.idle(t) } -__proto_357.flush = function(t) { +__proto_419.flush = function(t) { this.center.flush(t) this.up.flush(t) this.right.flush(t) @@ -114394,13 +115194,13 @@ __proto_357.flush = function(t) { this.angle.flush(t) } -__proto_357.setDistance = function(t, d) { +__proto_419.setDistance = function(t, d) { if(d > 0) { this.radius.set(t, Math.log(d)) } } -__proto_357.lookAt = function(t, eye, center, up) { +__proto_419.lookAt = function(t, eye, center, up) { this.recalcMatrix(t) eye = eye || this.computedEye @@ -114410,7 +115210,7 @@ __proto_357.lookAt = function(t, eye, center, up) { var ux = up[0] var uy = up[1] var uz = up[2] - var ul = __len3_357(ux, uy, uz) + var ul = __len3_419(ux, uy, uz) if(ul < 1e-6) { return } @@ -114421,7 +115221,7 @@ __proto_357.lookAt = function(t, eye, center, up) { var tx = eye[0] - center[0] var ty = eye[1] - center[1] var tz = eye[2] - center[2] - var tl = __len3_357(tx, ty, tz) + var tl = __len3_419(tx, ty, tz) if(tl < 1e-6) { return } @@ -114437,13 +115237,13 @@ __proto_357.lookAt = function(t, eye, center, up) { rx -= ru * ux ry -= ru * uy rz -= ru * uz - var rl = __len3_357(rx, ry, rz) + var rl = __len3_419(rx, ry, rz) if(rl < 0.01) { rx = uy * tz - uz * ty ry = uz * tx - ux * tz rz = ux * ty - uy * tx - rl = __len3_357(rx, ry, rz) + rl = __len3_419(rx, ry, rz) if(rl < 1e-6) { return } @@ -114460,7 +115260,7 @@ __proto_357.lookAt = function(t, eye, center, up) { var fx = uy * rz - uz * ry var fy = uz * rx - ux * rz var fz = ux * ry - uy * rx - var fl = __len3_357(fx, fy, fz) + var fl = __len3_419(fx, fy, fz) fx /= fl fy /= fl fz /= fl @@ -114503,10 +115303,10 @@ function createTurntableController(options) { center = [].slice.call(center, 0, 3) up = [].slice.call(up, 0, 3) - _$normalize_227(up, up) + _$normalize_284(up, up) right = [].slice.call(right, 0, 3) - _$normalize_227(right, right) + _$normalize_284(right, right) if('eye' in options) { var eye = options.eye @@ -114515,17 +115315,17 @@ function createTurntableController(options) { eye[1]-center[1], eye[2]-center[2] ] - _$cross_223(right, toward, up) - if(__len3_357(right[0], right[1], right[2]) < 1e-6) { + _$cross_280(right, toward, up) + if(__len3_419(right[0], right[1], right[2]) < 1e-6) { right = findOrthoPair(up) } else { - _$normalize_227(right, right) + _$normalize_284(right, right) } - radius = __len3_357(toward[0], toward[1], toward[2]) + radius = __len3_419(toward[0], toward[1], toward[2]) - var ut = _$dot_224(up, toward) / radius - var rt = _$dot_224(right, toward) / radius + var ut = _$dot_281(up, toward) / radius + var rt = _$dot_281(right, toward) / radius phi = Math.acos(ut) theta = Math.acos(rt) } @@ -114546,11 +115346,11 @@ function createTurntableController(options) { } 'use strict' -var _$createViewController_40 = createViewController +var _$createViewController_41 = createViewController -/* removed: var _$createTurntableController_357 = require('turntable-camera-controller') */; -/* removed: var _$createOrbitController_283 = require('orbit-camera-controller') */; -/* removed: var _$createMatrixCameraController_260 = require('matrix-camera-controller') */; +/* removed: var _$createTurntableController_419 = require('turntable-camera-controller') */; +/* removed: var _$createOrbitController_341 = require('orbit-camera-controller') */; +/* removed: var _$createMatrixCameraController_318 = require('matrix-camera-controller') */; function ViewController(controllers, mode) { this._controllerNames = Object.keys(controllers) @@ -114571,7 +115371,7 @@ function ViewController(controllers, mode) { this.computedRadius = this._active.computedRadius } -var __proto_40 = ViewController.prototype +var __proto_41 = ViewController.prototype var COMMON_METHODS = [ ['flush', 1], @@ -114592,25 +115392,25 @@ COMMON_METHODS.forEach(function(method) { argNames.push('a'+i) } var code = 'var cc=this._controllerList;for(var i=0;i Math.abs(dy)) { view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) } else { @@ -114967,10 +115767,10 @@ function doBind(gl, elements, attributes) { } } -var _$doBind_219 = doBind +var _$doBind_276 = doBind "use strict" -/* removed: var _$doBind_219 = require("./do-bind.js") */; +/* removed: var _$doBind_276 = require("./do-bind.js") */; function VAOEmulated(gl) { this.gl = gl @@ -114980,7 +115780,7 @@ function VAOEmulated(gl) { } VAOEmulated.prototype.bind = function() { - _$doBind_219(this.gl, this._elements, this._attributes) + _$doBind_276(this.gl, this._elements, this._attributes) } VAOEmulated.prototype.update = function(attributes, elements, elementsType) { @@ -115006,10 +115806,10 @@ function createVAOEmulated(gl) { return new VAOEmulated(gl) } -var _$createVAOEmulated_220 = createVAOEmulated +var _$createVAOEmulated_277 = createVAOEmulated "use strict" -/* removed: var _$doBind_219 = require("./do-bind.js") */; +/* removed: var _$doBind_276 = require("./do-bind.js") */; function VertexAttribute(location, dimension, a, b, c, d) { this.location = location @@ -115063,7 +115863,7 @@ VAONative.prototype.dispose = function() { VAONative.prototype.update = function(attributes, elements, elementsType) { this.bind() - _$doBind_219(this.gl, elements, attributes) + _$doBind_276(this.gl, elements, attributes) this.unbind() this._attribs.length = 0 if(attributes) @@ -115093,11 +115893,11 @@ function createVAONative(gl, ext) { return new VAONative(gl, ext, ext.createVertexArrayOES()) } -var _$createVAONative_221 = createVAONative +var _$createVAONative_278 = createVAONative "use strict" -/* removed: var _$createVAONative_221 = require("./lib/vao-native.js") */; -/* removed: var _$createVAOEmulated_220 = require("./lib/vao-emulated.js") */; +/* removed: var _$createVAONative_278 = require("./lib/vao-native.js") */; +/* removed: var _$createVAOEmulated_277 = require("./lib/vao-emulated.js") */; function ExtensionShim (gl) { this.bindVertexArrayOES = gl.bindVertexArray.bind(gl) @@ -115112,17 +115912,17 @@ function createVAO(gl, attributes, elements, elementsType) { var vao if(ext) { - vao = _$createVAONative_221(gl, ext) + vao = _$createVAONative_278(gl, ext) } else { - vao = _$createVAOEmulated_220(gl) + vao = _$createVAOEmulated_277(gl) } vao.update(attributes, elements, elementsType) return vao } -var _$createVAO_222 = createVAO +var _$createVAO_279 = createVAO -var _$weakMap_369 = {}; +var _$weakMap_431 = {}; // Copyright (C) 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -115288,7 +116088,7 @@ var _$weakMap_369 = {}; doubleWeakMapCheckSilentFailure = true; // Fall through to installing our WeakMap. } else { - _$weakMap_369 = WeakMap; + _$weakMap_431 = WeakMap; return; } } @@ -115785,7 +116585,7 @@ var _$weakMap_369 = {}; }); } DoubleWeakMap.prototype = OurWeakMap.prototype; - _$weakMap_369 = DoubleWeakMap; + _$weakMap_431 = DoubleWeakMap; // define .constructor to hide OurWeakMap ctor Object.defineProperty(WeakMap.prototype, 'constructor', { @@ -115805,25 +116605,25 @@ var _$weakMap_369 = {}; Proxy = undefined; } - _$weakMap_369 = OurWeakMap; + _$weakMap_431 = OurWeakMap; } })(); 'use strict' -var __weakMap_42 = typeof WeakMap === 'undefined' ? _$weakMap_369 : WeakMap -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; +var __weakMap_43 = typeof WeakMap === 'undefined' ? _$weakMap_431 : WeakMap +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; -var TriangleCache = new __weakMap_42() +var TriangleCache = new __weakMap_43() function createABigTriangle(gl) { var triangleVAO = TriangleCache.get(gl) var handle = triangleVAO && (triangleVAO._triangleBuffer.handle || triangleVAO._triangleBuffer.buffer) if(!handle || !gl.isBuffer(handle)) { - var buf = _$createBuffer_153(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) - triangleVAO = _$createVAO_222(gl, [ + var buf = _$createBuffer_210(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) + triangleVAO = _$createVAO_279(gl, [ { buffer: buf, type: gl.FLOAT, size: 2 @@ -115837,34 +116637,34 @@ function createABigTriangle(gl) { triangleVAO.unbind() } -var _$createABigTriangle_42 = createABigTriangle +var _$createABigTriangle_43 = createABigTriangle -var _$shaders_149 = {}; +var _$shaders_206 = {}; 'use strict' -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -var lineVert = _$browser_238(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]) -var lineFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) -_$shaders_149.line = function(gl) { - return _$createShader_206(gl, lineVert, lineFrag, null, [ +var lineVert = _$browser_295(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]) +var lineFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) +_$shaders_206.line = function(gl) { + return _$createShader_263(gl, lineVert, lineFrag, null, [ {name: 'position', type: 'vec3'} ]) } -var textVert = _$browser_238(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}"]) -var textFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) -_$shaders_149.text = function(gl) { - return _$createShader_206(gl, textVert, textFrag, null, [ +var textVert = _$browser_295(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}"]) +var textFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]) +_$shaders_206.text = function(gl) { + return _$createShader_263(gl, textVert, textFrag, null, [ {name: 'position', type: 'vec3'} ]) } -var bgVert = _$browser_238(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]) -var bgFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]) -_$shaders_149.bg = function(gl) { - return _$createShader_206(gl, bgVert, bgFrag, null, [ +var bgVert = _$browser_295(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]) +var bgFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]) +_$shaders_206.bg = function(gl) { + return _$createShader_263(gl, bgVert, bgFrag, null, [ {name: 'position', type: 'vec3'}, {name: 'normal', type: 'vec3'} ]) @@ -115872,11 +116672,11 @@ _$shaders_149.bg = function(gl) { 'use strict' -var _$createBackgroundCube_146 = createBackgroundCube +var _$createBackgroundCube_203 = createBackgroundCube -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -var __createShader_146 = _$shaders_149.bg +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +var __createShader_203 = _$shaders_206.bg function BackgroundCube(gl, buffer, vao, shader) { this.gl = gl @@ -115885,9 +116685,9 @@ function BackgroundCube(gl, buffer, vao, shader) { this.shader = shader } -var __proto_146 = BackgroundCube.prototype +var __proto_203 = BackgroundCube.prototype -__proto_146.draw = function(model, view, projection, bounds, enable, colors) { +__proto_203.draw = function(model, view, projection, bounds, enable, colors) { var needsBG = false for(var i=0; i<3; ++i) { needsBG = needsBG || enable[i] @@ -115917,7 +116717,7 @@ __proto_146.draw = function(model, view, projection, bounds, enable, colors) { gl.disable(gl.POLYGON_OFFSET_FILL) } -__proto_146.dispose = function() { +__proto_203.dispose = function() { this.vao.dispose() this.buffer.dispose() this.shader.dispose() @@ -115955,9 +116755,9 @@ function createBackgroundCube(gl) { } //Allocate buffer and vertex array - var buffer = _$createBuffer_153(gl, new Float32Array(vertices)) - var elements = _$createBuffer_153(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) - var vao = _$createVAO_222(gl, [ + var buffer = _$createBuffer_210(gl, new Float32Array(vertices)) + var elements = _$createBuffer_210(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) + var vao = _$createVAO_279(gl, [ { buffer: buffer, type: gl.FLOAT, @@ -115975,7 +116775,7 @@ function createBackgroundCube(gl) { ], elements) //Create shader object - var shader = __createShader_146(gl) + var shader = __createShader_203(gl) shader.attributes.position.location = 0 shader.attributes.normal.location = 1 @@ -115984,30 +116784,30 @@ function createBackgroundCube(gl) { "use strict" -/* removed: var _$twoProduct_358 = require("two-product") */; -/* removed: var _$linearExpansionSum_328 = require("robust-sum") */; +/* removed: var _$twoProduct_420 = require("two-product") */; +/* removed: var _$linearExpansionSum_392 = require("robust-sum") */; -var _$robustDotProduct_320 = robustDotProduct +var _$robustDotProduct_384 = robustDotProduct function robustDotProduct(a, b) { - var r = _$twoProduct_358(a[0], b[0]) + var r = _$twoProduct_420(a[0], b[0]) for(var i=1; i Math.abs(dy)) { view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth); } else { @@ -118840,8 +119640,8 @@ function __createCamera_626(element, options) { 'use strict'; -/* removed: var _$convertHTMLToUnicode_537 = require('../../../lib/html2unicode'); */; -/* removed: var _$str2RgbaArray_561 = require('../../../lib/str2rgbarray'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../../lib/html2unicode'); */; +/* removed: var _$str2RgbaArray_624 = require('../../../lib/str2rgbarray'); */; var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis']; @@ -118897,9 +119697,9 @@ function AxesOptions() { this._defaultLineTickLength = this.lineTickLength.slice(); } -var __proto_631 = AxesOptions.prototype; +var __proto_693 = AxesOptions.prototype; -__proto_631.merge = function(sceneLayout) { +__proto_693.merge = function(sceneLayout) { var opts = this; for(var i = 0; i < 3; ++i) { var axes = sceneLayout[AXES_NAMES[i]]; @@ -118916,27 +119716,27 @@ __proto_631.merge = function(sceneLayout) { } // Axes labels - opts.labels[i] = _$convertHTMLToUnicode_537(axes.title); + opts.labels[i] = _$convertHTMLToUnicode_599(axes.title); if('titlefont' in axes) { - if(axes.titlefont.color) opts.labelColor[i] = _$str2RgbaArray_561(axes.titlefont.color); + if(axes.titlefont.color) opts.labelColor[i] = _$str2RgbaArray_624(axes.titlefont.color); if(axes.titlefont.family) opts.labelFont[i] = axes.titlefont.family; if(axes.titlefont.size) opts.labelSize[i] = axes.titlefont.size; } // Lines if('showline' in axes) opts.lineEnable[i] = axes.showline; - if('linecolor' in axes) opts.lineColor[i] = _$str2RgbaArray_561(axes.linecolor); + if('linecolor' in axes) opts.lineColor[i] = _$str2RgbaArray_624(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_561(axes.gridcolor); + if('gridcolor' in axes) opts.gridColor[i] = _$str2RgbaArray_624(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_561(axes.zerolinecolor); + if('zerolinecolor' in axes) opts.zeroLineColor[i] = _$str2RgbaArray_624(axes.zerolinecolor); if('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth; // tick lines @@ -118946,7 +119746,7 @@ __proto_631.merge = function(sceneLayout) { if('ticklen' in axes) { opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen; } - if('tickcolor' in axes) opts.lineTickColor[i] = _$str2RgbaArray_561(axes.tickcolor); + if('tickcolor' in axes) opts.lineTickColor[i] = _$str2RgbaArray_624(axes.tickcolor); if('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth; if('tickangle' in axes) { opts.tickAngle[i] = (axes.tickangle === 'auto') ? @@ -118956,7 +119756,7 @@ __proto_631.merge = function(sceneLayout) { // tick labels if('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels; if('tickfont' in axes) { - if(axes.tickfont.color) opts.tickColor[i] = _$str2RgbaArray_561(axes.tickfont.color); + if(axes.tickfont.color) opts.tickColor[i] = _$str2RgbaArray_624(axes.tickfont.color); if(axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family; if(axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size; } @@ -118977,7 +119777,7 @@ __proto_631.merge = function(sceneLayout) { // grid background if('showbackground' in axes && axes.showbackground !== false) { opts.backgroundEnable[i] = true; - opts.backgroundColor[i] = _$str2RgbaArray_561(axes.backgroundcolor); + opts.backgroundColor[i] = _$str2RgbaArray_624(axes.backgroundcolor); } else opts.backgroundEnable[i] = false; } }; @@ -118989,7 +119789,7 @@ function createAxesOptions(plotlyOptions) { return result; } -var _$createAxesOptions_631 = createAxesOptions; +var _$createAxesOptions_693 = createAxesOptions; /** * Copyright 2012-2018, Plotly, Inc. @@ -119002,9 +119802,9 @@ var _$createAxesOptions_631 = createAxesOptions; 'use strict'; -/* removed: var _$str2RgbaArray_561 = require('../../../lib/str2rgbarray'); */; +/* removed: var _$str2RgbaArray_624 = require('../../../lib/str2rgbarray'); */; -var __AXES_NAMES_634 = ['xaxis', 'yaxis', 'zaxis']; +var __AXES_NAMES_696 = ['xaxis', 'yaxis', 'zaxis']; function SpikeOptions() { this.enabled = [true, true, true]; @@ -119015,11 +119815,11 @@ function SpikeOptions() { this.lineWidth = [1, 1, 1]; } -var __proto_634 = SpikeOptions.prototype; +var __proto_696 = SpikeOptions.prototype; -__proto_634.merge = function(sceneLayout) { +__proto_696.merge = function(sceneLayout) { for(var i = 0; i < 3; ++i) { - var axes = sceneLayout[__AXES_NAMES_634[i]]; + var axes = sceneLayout[__AXES_NAMES_696[i]]; if(!axes.visible) { this.enabled[i] = false; @@ -119028,7 +119828,7 @@ __proto_634.merge = function(sceneLayout) { } this.enabled[i] = axes.showspikes; - this.colors[i] = _$str2RgbaArray_561(axes.spikecolor); + this.colors[i] = _$str2RgbaArray_624(axes.spikecolor); this.drawSides[i] = axes.spikesides; this.lineWidth[i] = axes.spikethickness; } @@ -119040,7 +119840,7 @@ function createSpikeOptions(layout) { return result; } -var _$createSpikeOptions_634 = createSpikeOptions; +var _$createSpikeOptions_696 = createSpikeOptions; /** * Copyright 2012-2018, Plotly, Inc. @@ -119055,13 +119855,13 @@ var _$createSpikeOptions_634 = createSpikeOptions; 'use strict'; -var _$computeTickMarks_635 = computeTickMarks; +var _$computeTickMarks_697 = computeTickMarks; -/* removed: var _$axes_584 = require('../../cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$convertHTMLToUnicode_537 = require('../../../lib/html2unicode'); */; +/* removed: var _$axes_647 = require('../../cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$convertHTMLToUnicode_599 = require('../../../lib/html2unicode'); */; -var __AXES_NAMES_635 = ['xaxis', 'yaxis', 'zaxis']; +var __AXES_NAMES_697 = ['xaxis', 'yaxis', 'zaxis']; var centerPoint = [0, 0, 0]; @@ -119086,7 +119886,7 @@ function computeTickMarks(scene) { var ticks = [[], [], []]; for(var i = 0; i < 3; ++i) { - var axes = sceneLayout[__AXES_NAMES_635[i]]; + var axes = sceneLayout[__AXES_NAMES_697[i]]; axes._length = (glRange[i].hi - glRange[i].lo) * glRange[i].pixelsPerDataUnit / scene.dataScale[i]; @@ -119110,13 +119910,13 @@ function computeTickMarks(scene) { var tickModeCached = axes.tickmode; if(axes.tickmode === 'auto') { axes.tickmode = 'linear'; - var nticks = axes.nticks || _$lib_539.constrain((axes._length / 40), 4, 9); - _$axes_584.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks); + var nticks = axes.nticks || _$lib_601.constrain((axes._length / 40), 4, 9); + _$axes_647.autoTicks(axes, Math.abs(axes.range[1] - axes.range[0]) / nticks); } - var dataTicks = _$axes_584.calcTicks(axes); + var dataTicks = _$axes_647.calcTicks(axes); for(var j = 0; j < dataTicks.length; ++j) { dataTicks[j].x = dataTicks[j].x * scene.dataScale[i]; - dataTicks[j].text = _$convertHTMLToUnicode_537(dataTicks[j].text); + dataTicks[j].text = _$convertHTMLToUnicode_599(dataTicks[j].text); } ticks[i] = dataTicks; @@ -119149,27 +119949,27 @@ function computeTickMarks(scene) { 'use strict'; -/* removed: var _$createScene_196 = require('gl-plot3d'); */; -/* removed: var _$getWebGLContext_373 = require('webgl-context'); */; -/* removed: var _$hasPassiveEvents_240 = require('has-passive-events'); */; +/* removed: var _$createScene_253 = require('gl-plot3d'); */; +/* removed: var _$getWebGLContext_435 = require('webgl-context'); */; +/* removed: var _$hasPassiveEvents_297 = require('has-passive-events'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; -/* removed: var _$showWebGlMsg_559 = require('../../lib/show_no_webgl_msg'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; +/* removed: var _$showWebGlMsg_622 = require('../../lib/show_no_webgl_msg'); */; -/* removed: var _$createCamera_626 = require('./camera'); */; -/* removed: var _$project_636 = require('./project'); */; -/* removed: var _$createAxesOptions_631 = require('./layout/convert'); */; -/* removed: var _$createSpikeOptions_634 = require('./layout/spikes'); */; -/* removed: var _$computeTickMarks_635 = require('./layout/tick_marks'); */; +/* removed: var _$createCamera_688 = require('./camera'); */; +/* removed: var _$project_698 = require('./project'); */; +/* removed: var _$createAxesOptions_693 = require('./layout/convert'); */; +/* removed: var _$createSpikeOptions_696 = require('./layout/spikes'); */; +/* removed: var _$computeTickMarks_697 = require('./layout/tick_marks'); */; -var __STATIC_CANVAS_637, __STATIC_CONTEXT_637; +var __STATIC_CANVAS_699, __STATIC_CONTEXT_699; function render(scene) { var trace; @@ -119182,7 +119982,7 @@ function render(scene) { svgContainer.setAttributeNS(null, 'width', width); svgContainer.setAttributeNS(null, 'height', height); - _$computeTickMarks_635(scene); + _$computeTickMarks_697(scene); scene.glplot.axes.update(scene.axesOptions); // check if pick has changed @@ -119201,16 +120001,16 @@ function render(scene) { function formatter(axisName, val) { var axis = scene.fullSceneLayout[axisName]; - return _$axes_584.tickText(axis, axis.d2l(val), 'hover').text; + return _$axes_647.tickText(axis, axis.d2l(val), 'hover').text; } var oldEventData; if(lastPicked !== null) { - var pdata = _$project_636(scene.glplot.cameraParams, selection.dataCoordinate); + var pdata = _$project_698(scene.glplot.cameraParams, selection.dataCoordinate); trace = lastPicked.data; var ptNumber = selection.index; - var hoverinfo = _$fx_453.castHoverinfo(trace, scene.fullLayout, ptNumber); + var hoverinfo = _$fx_515.castHoverinfo(trace, scene.fullLayout, ptNumber); var xVal = formatter('xaxis', selection.traceCoordinate[0]), yVal = formatter('yaxis', selection.traceCoordinate[1]), @@ -119226,7 +120026,7 @@ function render(scene) { } if(scene.fullSceneLayout.hovermode) { - _$fx_453.loneHover({ + _$fx_515.loneHover({ x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width, y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height, xLabel: xVal, @@ -119234,11 +120034,11 @@ function render(scene) { zLabel: zVal, text: selection.textLabel, name: lastPicked.name, - color: _$fx_453.castHoverOption(trace, ptNumber, 'bgcolor') || lastPicked.color, - borderColor: _$fx_453.castHoverOption(trace, ptNumber, 'bordercolor'), - fontFamily: _$fx_453.castHoverOption(trace, ptNumber, 'font.family'), - fontSize: _$fx_453.castHoverOption(trace, ptNumber, 'font.size'), - fontColor: _$fx_453.castHoverOption(trace, ptNumber, 'font.color') + color: _$fx_515.castHoverOption(trace, ptNumber, 'bgcolor') || lastPicked.color, + borderColor: _$fx_515.castHoverOption(trace, ptNumber, 'bordercolor'), + fontFamily: _$fx_515.castHoverOption(trace, ptNumber, 'font.family'), + fontSize: _$fx_515.castHoverOption(trace, ptNumber, 'font.size'), + fontColor: _$fx_515.castHoverOption(trace, ptNumber, 'font.color') }, { container: svgContainer, gd: scene.graphDiv @@ -119255,7 +120055,7 @@ function render(scene) { pointNumber: ptNumber }; - _$fx_453.appendArrayPointValue(pointData, trace, ptNumber); + _$fx_515.appendArrayPointValue(pointData, trace, ptNumber); var eventData = {points: [pointData]}; @@ -119269,7 +120069,7 @@ function render(scene) { oldEventData = eventData; } else { - _$fx_453.loneUnhover(svgContainer); + _$fx_515.loneUnhover(svgContainer); scene.graphDiv.emit('plotly_unhover', oldEventData); } @@ -119292,25 +120092,25 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { // for static plots, we reuse the WebGL context // as WebKit doesn't collect them reliably if(scene.staticMode) { - if(!__STATIC_CONTEXT_637) { - __STATIC_CANVAS_637 = document.createElement('canvas'); - __STATIC_CONTEXT_637 = _$getWebGLContext_373({ - canvas: __STATIC_CANVAS_637, + if(!__STATIC_CONTEXT_699) { + __STATIC_CANVAS_699 = document.createElement('canvas'); + __STATIC_CONTEXT_699 = _$getWebGLContext_435({ + canvas: __STATIC_CANVAS_699, preserveDrawingBuffer: true, premultipliedAlpha: true, antialias: true }); - if(!__STATIC_CONTEXT_637) { + if(!__STATIC_CONTEXT_699) { throw new Error('error creating static canvas/context for image server'); } } glplotOptions.pixelRatio = scene.pixelRatio; - glplotOptions.gl = __STATIC_CONTEXT_637; - glplotOptions.canvas = __STATIC_CANVAS_637; + glplotOptions.gl = __STATIC_CONTEXT_699; + glplotOptions.canvas = __STATIC_CANVAS_699; } try { - scene.glplot = _$createScene_196(glplotOptions); + scene.glplot = _$createScene_253(glplotOptions); } catch(e) { /* @@ -119319,7 +120119,7 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { * The destroy method - which will remove the container from the DOM * is overridden with a function that removes the container only. */ - _$showWebGlMsg_559(scene); + _$showWebGlMsg_622(scene); } var relayoutCallback = function(scene) { @@ -119332,18 +120132,18 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { }; scene.glplot.canvas.addEventListener('mouseup', relayoutCallback.bind(null, scene)); - scene.glplot.canvas.addEventListener('wheel', relayoutCallback.bind(null, scene), _$hasPassiveEvents_240 ? {passive: false} : false); + scene.glplot.canvas.addEventListener('wheel', relayoutCallback.bind(null, scene), _$hasPassiveEvents_297 ? {passive: false} : false); if(!scene.staticMode) { scene.glplot.canvas.addEventListener('webglcontextlost', function(ev) { - _$lib_539.warn('Lost WebGL context.'); + _$lib_601.warn('Lost WebGL context.'); ev.preventDefault(); }); } if(!scene.camera) { var cameraData = scene.fullSceneLayout.camera; - scene.camera = _$createCamera_626(scene.container, { + scene.camera = _$createCamera_688(scene.container, { center: [cameraData.center.x, cameraData.center.y, cameraData.center.z], eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z], up: [cameraData.up.x, cameraData.up.y, cameraData.up.z], @@ -119405,8 +120205,8 @@ function Scene(options, fullLayout) { /* * Move this to calc step? Why does it work here? */ - this.axesOptions = _$createAxesOptions_631(fullLayout[this.id]); - this.spikeOptions = _$createSpikeOptions_634(fullLayout[this.id]); + this.axesOptions = _$createAxesOptions_693(fullLayout[this.id]); + this.spikeOptions = _$createSpikeOptions_696(fullLayout[this.id]); this.container = sceneContainer; this.staticMode = !!options.staticPlot; this.pixelRatio = options.plotGlPixelRatio || 2; @@ -119416,15 +120216,15 @@ function Scene(options, fullLayout) { this.contourLevels = [ [], [], [] ]; - this.convertAnnotations = _$registry_668.getComponentMethod('annotations3d', 'convert'); - this.drawAnnotations = _$registry_668.getComponentMethod('annotations3d', 'draw'); + this.convertAnnotations = _$registry_731.getComponentMethod('annotations3d', 'convert'); + this.drawAnnotations = _$registry_731.getComponentMethod('annotations3d', 'draw'); if(!initializeGLPlot(this, fullLayout)) return; // todo check the necessity for this line } -var __proto_637 = Scene.prototype; +var __proto_699 = Scene.prototype; -__proto_637.recoverContext = function() { +__proto_699.recoverContext = function() { var scene = this; var gl = this.glplot.gl; var canvas = this.glplot.canvas; @@ -119436,7 +120236,7 @@ __proto_637.recoverContext = function() { return; } if(!initializeGLPlot(scene, scene.fullLayout, canvas, gl)) { - _$lib_539.error('Catastrophic and unrecoverable WebGL error. Context lost.'); + _$lib_601.error('Catastrophic and unrecoverable WebGL error. Context lost.'); return; } scene.plot.apply(scene, scene.plotArgs); @@ -119448,14 +120248,14 @@ var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ]; function coordinateBound(axis, coord, len, d, bounds, calendar) { var x; - if(!_$lib_539.isArrayOrTypedArray(coord)) { + if(!_$lib_601.isArrayOrTypedArray(coord)) { bounds[0][d] = Math.min(bounds[0][d], 0); bounds[1][d] = Math.max(bounds[1][d], len - 1); return; } for(var i = 0; i < (len || coord.length); ++i) { - if(_$lib_539.isArrayOrTypedArray(coord[i])) { + if(_$lib_601.isArrayOrTypedArray(coord[i])) { for(var j = 0; j < coord[i].length; ++j) { x = axis.d2l(coord[i][j], 0, calendar); if(!isNaN(x) && isFinite(x)) { @@ -119481,7 +120281,7 @@ function computeTraceBounds(scene, trace, bounds) { coordinateBound(sceneLayout.zaxis, trace.z, trace._zlength, 2, bounds, trace.zcalendar); } -__proto_637.plot = function(sceneData, fullLayout, layout) { +__proto_699.plot = function(sceneData, fullLayout, layout) { // Save parameters this.plotArgs = [sceneData, fullLayout, layout]; @@ -119493,7 +120293,7 @@ __proto_637.plot = function(sceneData, fullLayout, layout) { var fullSceneLayout = fullLayout[this.id]; var sceneLayout = layout[this.id]; - if(fullSceneLayout.bgcolor) this.glplot.clearColor = _$str2RgbaArray_561(fullSceneLayout.bgcolor); + if(fullSceneLayout.bgcolor) this.glplot.clearColor = _$str2RgbaArray_624(fullSceneLayout.bgcolor); else this.glplot.clearColor = [0, 0, 0, 0]; this.glplot.snapToData = true; @@ -119740,7 +120540,7 @@ __proto_637.plot = function(sceneData, fullLayout, layout) { this.glplot.redraw(); }; -__proto_637.destroy = function() { +__proto_699.destroy = function() { if(!this.glplot) return; this.camera.mouseListener.enabled = false; @@ -119772,20 +120572,20 @@ function getLayoutCamera(camera) { } // get camera position in plotly coords from 'orbit-camera' coords -__proto_637.getCamera = function getCamera() { +__proto_699.getCamera = function getCamera() { this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()); return getLayoutCamera(this.glplot.camera); }; // set camera position with a set of plotly coords -__proto_637.setCamera = function setCamera(cameraData) { +__proto_699.setCamera = function setCamera(cameraData) { this.glplot.camera.lookAt.apply(this, getOrbitCamera(cameraData)); }; // save camera to user layout (i.e. gd.layout) -__proto_637.saveCamera = function saveCamera(layout) { +__proto_699.saveCamera = function saveCamera(layout) { var cameraData = this.getCamera(), - cameraNestedProp = _$lib_539.nestedProperty(layout, this.id + '.camera'), + cameraNestedProp = _$lib_601.nestedProperty(layout, this.id + '.camera'), cameraDataLastSave = cameraNestedProp.get(), hasChanged = false; @@ -119812,7 +120612,7 @@ __proto_637.saveCamera = function saveCamera(layout) { return hasChanged; }; -__proto_637.updateFx = function(dragmode, hovermode) { +__proto_699.updateFx = function(dragmode, hovermode) { var camera = this.camera; if(camera) { @@ -119837,10 +120637,10 @@ __proto_637.updateFx = function(dragmode, hovermode) { this.fullSceneLayout.hovermode = hovermode; }; -__proto_637.toImage = function(format) { +__proto_699.toImage = function(format) { if(!format) format = 'png'; - if(this.staticMode) this.container.appendChild(__STATIC_CANVAS_637); + if(this.staticMode) this.container.appendChild(__STATIC_CANVAS_699); // Force redraw this.glplot.redraw(); @@ -119887,22 +120687,22 @@ __proto_637.toImage = function(format) { dataURL = canvas.toDataURL('image/png'); } - if(this.staticMode) this.container.removeChild(__STATIC_CANVAS_637); + if(this.staticMode) this.container.removeChild(__STATIC_CANVAS_699); return dataURL; }; -__proto_637.setConvert = function() { +__proto_699.setConvert = function() { for(var i = 0; i < 3; i++) { var ax = this.fullSceneLayout[axisProperties[i]]; - _$axes_584.setConvert(ax, this.fullLayout); - ax.setScale = _$lib_539.noop; + _$axes_647.setConvert(ax, this.fullLayout); + ax.setScale = _$lib_601.noop; } }; -var _$Scene_637 = Scene; +var _$Scene_699 = Scene; -var _$gl3d_627 = {}; +var _$gl3d_689 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -119914,49 +120714,49 @@ var _$gl3d_627 = {}; 'use strict'; -var __overrideAll_627 = _$edit_types_569.overrideAll; -/* removed: var _$layout_attributes_454 = require('../../components/fx/layout_attributes'); */; +var __overrideAll_689 = _$edit_types_632.overrideAll; +/* removed: var _$layout_attributes_516 = require('../../components/fx/layout_attributes'); */; -/* removed: var _$Scene_637 = require('./scene'); */; -var __getSubplotData_627 = _$get_data_621.getSubplotData; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$Scene_699 = require('./scene'); */; +var __getSubplotData_689 = _$get_data_683.getSubplotData; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; var GL3D = 'gl3d'; var SCENE = 'scene'; -_$gl3d_627.name = GL3D; +_$gl3d_689.name = GL3D; -_$gl3d_627.attr = SCENE; +_$gl3d_689.attr = SCENE; -_$gl3d_627.idRoot = SCENE; +_$gl3d_689.idRoot = SCENE; -_$gl3d_627.idRegex = _$gl3d_627.attrRegex = _$lib_539.counterRegex('scene'); +_$gl3d_689.idRegex = _$gl3d_689.attrRegex = _$lib_601.counterRegex('scene'); -_$gl3d_627.attributes = _$attributes_628; +_$gl3d_689.attributes = _$attributes_690; -_$gl3d_627.layoutAttributes = _$layout_attributes_633; +_$gl3d_689.layoutAttributes = _$layout_attributes_695; -_$gl3d_627.baseLayoutAttrOverrides = __overrideAll_627({ - hoverlabel: _$layout_attributes_454.hoverlabel +_$gl3d_689.baseLayoutAttrOverrides = __overrideAll_689({ + hoverlabel: _$layout_attributes_516.hoverlabel }, 'plot', 'nested'); -_$gl3d_627.supplyLayoutDefaults = _$supplyLayoutDefaults_632; +_$gl3d_689.supplyLayoutDefaults = _$supplyLayoutDefaults_694; -_$gl3d_627.plot = function plotGl3d(gd) { +_$gl3d_689.plot = function plotGl3d(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], - fullSceneData = __getSubplotData_627(fullData, GL3D, sceneId), + fullSceneData = __getSubplotData_689(fullData, GL3D, sceneId), sceneLayout = fullLayout[sceneId], scene = sceneLayout._scene; if(!scene) { - scene = new _$Scene_637({ + scene = new _$Scene_699({ id: sceneId, graphDiv: gd, container: gd.querySelector('.gl-container'), @@ -119972,14 +120772,14 @@ _$gl3d_627.plot = function plotGl3d(gd) { // save 'initial' camera settings for modebar button if(!scene.cameraInitial) { - scene.cameraInitial = _$lib_539.extendDeep({}, sceneLayout.camera); + scene.cameraInitial = _$lib_601.extendDeep({}, sceneLayout.camera); } scene.plot(fullSceneData, fullLayout, gd.layout); } }; -_$gl3d_627.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$gl3d_689.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldSceneKeys = oldFullLayout._subplots[GL3D] || []; for(var i = 0; i < oldSceneKeys.length; i++) { @@ -119997,7 +120797,7 @@ _$gl3d_627.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayo } }; -_$gl3d_627.toSVG = function(gd) { +_$gl3d_689.toSVG = function(gd) { var fullLayout = gd._fullLayout; var sceneIds = fullLayout._subplots[GL3D]; var size = fullLayout._size; @@ -120011,7 +120811,7 @@ _$gl3d_627.toSVG = function(gd) { var image = fullLayout._glimages.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, x: size.l + size.w * domain.x[0], y: size.t + size.h * (1 - domain.y[1]), @@ -120025,7 +120825,7 @@ _$gl3d_627.toSVG = function(gd) { }; // clean scene ids, 'scene1' -> 'scene' -_$gl3d_627.cleanId = function cleanId(id) { +_$gl3d_689.cleanId = function cleanId(id) { if(!id.match(/^scene[0-9]*$/)) return; var sceneNum = id.substr(5); @@ -120034,7 +120834,7 @@ _$gl3d_627.cleanId = function cleanId(id) { return SCENE + sceneNum; }; -_$gl3d_627.updateFx = function(fullLayout) { +_$gl3d_689.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots[GL3D]; for(var i = 0; i < subplotIds.length; i++) { @@ -120043,7 +120843,7 @@ _$gl3d_627.updateFx = function(fullLayout) { } }; -var _$attributes_936 = {}; +var _$attributes_1007 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -120054,13 +120854,13 @@ var _$attributes_936 = {}; 'use strict'; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; -var __extendFlat_936 = _$extend_528.extendFlat; -var __overrideAll_936 = _$edit_types_569.overrideAll; +var __extendFlat_1007 = _$extend_590.extendFlat; +var __overrideAll_1007 = _$edit_types_632.overrideAll; function makeContourProjAttr(axLetter) { return { @@ -120087,7 +120887,7 @@ function makeContourAttr(axLetter) { color: { valType: 'color', - dflt: _$color_411.defaultLine, + dflt: _$color_473.defaultLine, }, usecolormap: { @@ -120113,7 +120913,7 @@ function makeContourAttr(axLetter) { highlightcolor: { valType: 'color', - dflt: _$color_411.defaultLine, + dflt: _$color_473.defaultLine, }, highlightwidth: { @@ -120127,7 +120927,7 @@ function makeContourAttr(axLetter) { }; } -var __attrs_936 = _$attributes_936 = __overrideAll_936({ +var __attrs_1007 = _$attributes_1007 = __overrideAll_1007({ z: { valType: 'data_array', @@ -120154,15 +120954,15 @@ var __attrs_936 = _$attributes_936 = __overrideAll_936({ }, - cauto: _$attributes_417.zauto, - cmin: _$attributes_417.zmin, - cmax: _$attributes_417.zmax, - colorscale: _$attributes_417.colorscale, - autocolorscale: __extendFlat_936({}, _$attributes_417.autocolorscale, + cauto: _$attributes_479.zauto, + cmin: _$attributes_479.zmin, + cmax: _$attributes_479.zmax, + colorscale: _$attributes_479.colorscale, + autocolorscale: __extendFlat_1007({}, _$attributes_479.autocolorscale, {dflt: false}), - reversescale: _$attributes_417.reversescale, - showscale: _$attributes_417.showscale, - colorbar: _$attributes_412, + reversescale: _$attributes_479.reversescale, + showscale: _$attributes_479.showscale, + colorbar: _$attributes_474, contours: { x: makeContourAttr('x'), @@ -120256,21 +121056,21 @@ var __attrs_936 = _$attributes_936 = __overrideAll_936({ }, _deprecated: { - zauto: __extendFlat_936({}, _$attributes_417.zauto, { + zauto: __extendFlat_1007({}, _$attributes_479.zauto, { }), - zmin: __extendFlat_936({}, _$attributes_417.zmin, { + zmin: __extendFlat_1007({}, _$attributes_479.zmin, { }), - zmax: __extendFlat_936({}, _$attributes_417.zmax, { + zmax: __extendFlat_1007({}, _$attributes_479.zmax, { }) }, - hoverinfo: __extendFlat_936({}, _$attributes_581.hoverinfo) + hoverinfo: __extendFlat_1007({}, _$attributes_644.hoverinfo) }, 'calc', 'nested'); -__attrs_936.x.editType = __attrs_936.y.editType = __attrs_936.z.editType = 'calc+clearAxisTypes'; +__attrs_1007.x.editType = __attrs_1007.y.editType = __attrs_1007.z.editType = 'calc+clearAxisTypes'; /** * Copyright 2012-2018, Plotly, Inc. @@ -120282,15 +121082,15 @@ __attrs_936.x.editType = __attrs_936.y.editType = __attrs_936.z.editType = 'calc 'use strict'; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_417 = require('../../components/colorscale/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$attributes_936 = require('../surface/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_479 = require('../../components/colorscale/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_1007 = require('../surface/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; -var __extendFlat_814 = _$extend_528.extendFlat; +var __extendFlat_876 = _$extend_590.extendFlat; -var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc', false), { +var _$attributes_876 = __extendFlat_876(_$makeColorScaleAttributes_481('', 'calc', false), { x: { valType: 'data_array', editType: 'calc+clearAxisTypes', @@ -120378,7 +121178,7 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc }, // Opacity - opacity: _$attributes_936.opacity, + opacity: _$attributes_1007.opacity, // Flat shaded mode flatshading: { @@ -120390,24 +121190,24 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc }, contour: { - show: __extendFlat_814({}, _$attributes_936.contours.x.show, { + show: __extendFlat_876({}, _$attributes_1007.contours.x.show, { }), - color: _$attributes_936.contours.x.color, - width: _$attributes_936.contours.x.width, + color: _$attributes_1007.contours.x.color, + width: _$attributes_1007.contours.x.width, editType: 'calc' }, - showscale: _$attributes_417.showscale, - colorbar: _$attributes_412, + showscale: _$attributes_479.showscale, + colorbar: _$attributes_474, lightposition: { - x: __extendFlat_814({}, _$attributes_936.lightposition.x, {dflt: 1e5}), - y: __extendFlat_814({}, _$attributes_936.lightposition.y, {dflt: 1e5}), - z: __extendFlat_814({}, _$attributes_936.lightposition.z, {dflt: 0}), + x: __extendFlat_876({}, _$attributes_1007.lightposition.x, {dflt: 1e5}), + y: __extendFlat_876({}, _$attributes_1007.lightposition.y, {dflt: 1e5}), + z: __extendFlat_876({}, _$attributes_1007.lightposition.z, {dflt: 0}), editType: 'calc' }, - lighting: __extendFlat_814({ + lighting: __extendFlat_876({ vertexnormalsepsilon: { valType: 'number', @@ -120427,9 +121227,9 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc }, editType: 'calc' - }, _$attributes_936.lighting), + }, _$attributes_1007.lighting), - hoverinfo: __extendFlat_814({}, _$attributes_581.hoverinfo, {editType: 'calc'}) + hoverinfo: __extendFlat_876({}, _$attributes_644.hoverinfo, {editType: 'calc'}) }); /** @@ -120442,11 +121242,11 @@ var _$attributes_814 = __extendFlat_814(_$makeColorScaleAttributes_419('', 'calc 'use strict'; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; -var _$calc_815 = function calc(gd, trace) { +var _$calc_877 = function calc(gd, trace) { if(trace.intensity) { - _$calc_418(trace, trace.intensity, '', 'c'); + _$calc_480(trace, trace.intensity, '', 'c'); } }; @@ -120460,33 +121260,33 @@ var _$calc_815 = function calc(gd, trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_816 = function colorbar(gd, cd) { +var _$colorbar_878 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, cmin = trace.cmin, cmax = trace.cmax, vals = trace.intensity || []; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, cmin, cmax @@ -120501,7 +121301,7 @@ var _$colorbar_816 = function colorbar(gd, cd) { "use strict" -var _$compressExpansion_318 = compressExpansion +var _$compressExpansion_382 = compressExpansion function compressExpansion(e) { var m = e.length @@ -120533,17 +121333,17 @@ function compressExpansion(e) { e.length = top return e } -var _$robustDeterminant_319 = {}; +var _$robustDeterminant_383 = {}; "use strict" -/* removed: var _$twoProduct_358 = require("two-product") */; -/* removed: var _$linearExpansionSum_328 = require("robust-sum") */; -/* removed: var _$scaleLinearExpansion_325 = require("robust-scale") */; -/* removed: var _$compressExpansion_318 = require("robust-compress") */; +/* removed: var _$twoProduct_420 = require("two-product") */; +/* removed: var _$linearExpansionSum_392 = require("robust-sum") */; +/* removed: var _$scaleLinearExpansion_389 = require("robust-scale") */; +/* removed: var _$compressExpansion_382 = require("robust-compress") */; var NUM_EXPANDED = 6 -function __cofactor_319(m, c) { +function __cofactor_383(m, c) { var result = new Array(m.length-1) for(var i=1; i>1 - return ["sum(", __generateSum_319(expr.slice(0, m)), ",", __generateSum_319(expr.slice(m)), ")"].join("") + return ["sum(", __generateSum_383(expr.slice(0, m)), ",", __generateSum_383(expr.slice(m)), ")"].join("") } } -function __determinant_319(m) { +function __determinant_383(m) { if(m.length === 2) { return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") } else { var expr = [] for(var i=0; i 0) { var f = cells[ptr-1] - if(_$compareCells_107(c, f) === 0 && - _$orientation_91(f) !== o) { + if(_$compareCells_108(c, f) === 0 && + _$orientation_92(f) !== o) { ptr -= 1 continue } @@ -121566,26 +122366,26 @@ function reduceCellComplex(cells) { 'use strict' -var _$boundary_330 = __boundary_330 +var _$boundary_394 = __boundary_394 -/* removed: var _$boundary_75 = require('boundary-cells') */; -/* removed: var _$reduceCellComplex_310 = require('reduce-simplicial-complex') */; +/* removed: var _$boundary_76 = require('boundary-cells') */; +/* removed: var _$reduceCellComplex_373 = require('reduce-simplicial-complex') */; -function __boundary_330(cells) { - return _$reduceCellComplex_310(_$boundary_75(cells)) +function __boundary_394(cells) { + return _$reduceCellComplex_373(_$boundary_76(cells)) } -var _$alphaShape_47 = alphaShape +var _$alphaShape_48 = alphaShape -/* removed: var _$alphaComplex_46 = require('alpha-complex') */; -/* removed: var _$boundary_330 = require('simplicial-complex-boundary') */; +/* removed: var _$alphaComplex_47 = require('alpha-complex') */; +/* removed: var _$boundary_394 = require('simplicial-complex-boundary') */; function alphaShape(alpha, points) { - return _$boundary_330(_$alphaComplex_46(alpha, points)) + return _$boundary_394(_$alphaComplex_47(alpha, points)) } "use strict" -var _$convexHull1d_110 = convexHull1d +var _$convexHull1d_111 = convexHull1d function convexHull1d(points) { var lo = 0 @@ -121608,9 +122408,9 @@ function convexHull1d(points) { } 'use strict' -var _$monotoneConvexHull2D_261 = monotoneConvexHull2D +var _$monotoneConvexHull2D_319 = monotoneConvexHull2D -var __orient_261 = _$orientation_323[3] +var __orient_319 = _$orientation_387[3] function monotoneConvexHull2D(points) { var n = points.length @@ -121653,7 +122453,7 @@ function monotoneConvexHull2D(points) { //Insert into lower list var m = lower.length - while(m > 1 && __orient_261( + while(m > 1 && __orient_319( points[lower[m-2]], points[lower[m-1]], p) <= 0) { @@ -121664,7 +122464,7 @@ function monotoneConvexHull2D(points) { //Insert into upper list m = upper.length - while(m > 1 && __orient_261( + while(m > 1 && __orient_319( points[upper[m-2]], points[upper[m-1]], p) >= 0) { @@ -121689,12 +122489,12 @@ function monotoneConvexHull2D(points) { } 'use strict' -var _$convexHull2D_111 = convexHull2D +var _$convexHull2D_112 = convexHull2D -/* removed: var _$monotoneConvexHull2D_261 = require('monotone-convex-hull-2d') */; +/* removed: var _$monotoneConvexHull2D_319 = require('monotone-convex-hull-2d') */; function convexHull2D(points) { - var hull = _$monotoneConvexHull2D_261(points) + var hull = _$monotoneConvexHull2D_319(points) var h = hull.length if(h <= 2) { return [] @@ -121711,9 +122511,9 @@ function convexHull2D(points) { 'use strict' -var _$affineHull_45 = affineHull +var _$affineHull_46 = affineHull -/* removed: var _$orientation_323 = require('robust-orientation') */; +/* removed: var _$orientation_387 = require('robust-orientation') */; function linearlyIndependent(points, d) { var nhull = new Array(d+1) @@ -121728,7 +122528,7 @@ function linearlyIndependent(points, d) { } nhull[j] = x } - var o = _$orientation_323.apply(void 0, nhull) + var o = _$orientation_387.apply(void 0, nhull) if(o) { return true } @@ -121762,10 +122562,10 @@ function affineHull(points) { } 'use strict' -var _$convexHullnD_112 = convexHullnD +var _$convexHullnD_113 = convexHullnD -/* removed: var _$incrementalConvexHull_242 = require('incremental-convex-hull') */; -/* removed: var _$affineHull_45 = require('affine-hull') */; +/* removed: var _$incrementalConvexHull_299 = require('incremental-convex-hull') */; +/* removed: var _$affineHull_46 = require('affine-hull') */; function permute(points, front) { var n = points.length @@ -121807,26 +122607,26 @@ function invPermute(cells, front) { function convexHullnD(points, d) { try { - return _$incrementalConvexHull_242(points, true) + return _$incrementalConvexHull_299(points, true) } catch(e) { //If point set is degenerate, try to find a basis and rerun it - var ah = _$affineHull_45(points) + var ah = _$affineHull_46(points) if(ah.length <= d) { //No basis, no try return [] } var npoints = permute(points, ah) - var nhull = _$incrementalConvexHull_242(npoints, true) + var nhull = _$incrementalConvexHull_299(npoints, true) return invPermute(nhull, ah) } } "use strict" -/* removed: var _$convexHull1d_110 = require('./lib/ch1d') */; -/* removed: var _$convexHull2D_111 = require('./lib/ch2d') */; -/* removed: var _$convexHullnD_112 = require('./lib/chnd') */; +/* removed: var _$convexHull1d_111 = require('./lib/ch1d') */; +/* removed: var _$convexHull2D_112 = require('./lib/ch2d') */; +/* removed: var _$convexHullnD_113 = require('./lib/chnd') */; -var _$convexHull_109 = convexHull +var _$convexHull_110 = convexHull function convexHull(points) { var n = points.length @@ -121839,13 +122639,13 @@ function convexHull(points) { if(d === 0) { return [] } else if(d === 1) { - return _$convexHull1d_110(points) + return _$convexHull1d_111(points) } else if(d === 2) { - return _$convexHull2D_111(points) + return _$convexHull2D_112(points) } - return _$convexHullnD_112(points, d) + return _$convexHullnD_113(points, d) } -var _$colorScale_104={ +var _$colorScale_105={ "jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}], "hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}], @@ -121937,10 +122737,10 @@ var _$colorScale_104={ "cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}] }; -function __lerp_253(v0, v1, t) { +function __lerp_310(v0, v1, t) { return v0*(1-t)+v1*t } -var _$lerp_253 = __lerp_253 +var _$lerp_310 = __lerp_310 /* * Ben Postlethwaite * January 2013 @@ -121948,10 +122748,10 @@ var _$lerp_253 = __lerp_253 */ 'use strict'; -/* removed: var _$colorScale_104 = require('./colorScale'); */; -/* removed: var _$lerp_253 = require('lerp') */; +/* removed: var _$colorScale_105 = require('./colorScale'); */; +/* removed: var _$lerp_310 = require('lerp') */; -var _$createColormap_105 = createColormap; +var _$createColormap_106 = createColormap; function createColormap (spec) { /* @@ -121976,11 +122776,11 @@ function createColormap (spec) { if (typeof colormap === 'string') { colormap = colormap.toLowerCase(); - if (!_$colorScale_104[colormap]) { + if (!_$colorScale_105[colormap]) { throw Error(colormap + ' not a supported colorscale'); } - cmap = _$colorScale_104[colormap]; + cmap = _$colorScale_105[colormap]; } else if (Array.isArray(colormap)) { cmap = colormap.slice(); @@ -122048,10 +122848,10 @@ function createColormap (spec) { for (var j = 0; j < nsteps; j++) { var amt = j / nsteps colors.push([ - Math.round(_$lerp_253(fromrgba[0], torgba[0], amt)), - Math.round(_$lerp_253(fromrgba[1], torgba[1], amt)), - Math.round(_$lerp_253(fromrgba[2], torgba[2], amt)), - _$lerp_253(fromrgba[3], torgba[3], amt) + Math.round(_$lerp_310(fromrgba[0], torgba[0], amt)), + Math.round(_$lerp_310(fromrgba[1], torgba[1], amt)), + Math.round(_$lerp_310(fromrgba[2], torgba[2], amt)), + _$lerp_310(fromrgba[3], torgba[3], amt) ]) } } @@ -122091,11 +122891,11 @@ function rgbaStr (rgba) { 'use strict' -var _$barycentric_53 = barycentric +var _$barycentric_54 = barycentric -/* removed: var _$linsolve_322 = require('robust-linear-solve') */; +/* removed: var _$linsolve_386 = require('robust-linear-solve') */; -function __reduce_53(x) { +function __reduce_54(x) { var r = 0 for(var i=0; i 0.001) { return null } - return [closestIndex, __interpolate_185(simplex, weights), weights] -} -var _$shaders_186 = {}; -/* removed: var _$browser_238 = require('glslify') */; - -var triVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\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\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}"]) -var triFragSrc = _$browser_238(["precision mediump 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\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\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 = cookTorranceSpecular(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}"]) -var edgeVertSrc = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]) -var pointVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]) -var pickPointVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_238(["precision mediump 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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]) - -_$shaders_186.meshShader = { + return [closestIndex, __interpolate_242(simplex, weights), weights] +} +var _$shaders_243 = {}; +/* removed: var _$browser_295 = require('glslify') */; + +var triVertSrc = _$browser_295(["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;\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\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}\n"]) +var triFragSrc = _$browser_295(["#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\nvec3 normals(vec3 pos) {\n vec3 fdx = dFdx(pos);\n vec3 fdy = dFdy(pos);\n return normalize(cross(fdx, fdy));\n}\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\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(any(lessThan(f_data, clipBounds[0])) ||\n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n vec3 normal = normals(f_data);\n\n if (\n dot(N, normal) < 0.0\n ) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}\n"]) +var edgeVertSrc = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]) +var pointVertSrc = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]) +var pickPointVertSrc = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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 = _$browser_295(["precision mediump 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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]) + +_$shaders_243.meshShader = { vertex: triVertSrc, fragment: triFragSrc, attributes: [ @@ -122455,7 +123255,7 @@ _$shaders_186.meshShader = { {name: 'uv', type: 'vec2'} ] } -_$shaders_186.wireShader = { +_$shaders_243.wireShader = { vertex: edgeVertSrc, fragment: edgeFragSrc, attributes: [ @@ -122464,7 +123264,7 @@ _$shaders_186.wireShader = { {name: 'uv', type: 'vec2'} ] } -_$shaders_186.pointShader = { +_$shaders_243.pointShader = { vertex: pointVertSrc, fragment: pointFragSrc, attributes: [ @@ -122474,7 +123274,7 @@ _$shaders_186.pointShader = { {name: 'pointSize', type: 'float'} ] } -_$shaders_186.pickShader = { +_$shaders_243.pickShader = { vertex: pickVertSrc, fragment: pickFragSrc, attributes: [ @@ -122482,7 +123282,7 @@ _$shaders_186.pickShader = { {name: 'id', type: 'vec4'} ] } -_$shaders_186.pointPickShader = { +_$shaders_243.pointPickShader = { vertex: pickPointVertSrc, fragment: pickFragSrc, attributes: [ @@ -122491,7 +123291,7 @@ _$shaders_186.pointPickShader = { {name: 'id', type: 'vec4'} ] } -_$shaders_186.contourShader = { +_$shaders_243.contourShader = { vertex: contourVertSrc, fragment: contourFragSrc, attributes: [ @@ -122499,12 +123299,12 @@ _$shaders_186.contourShader = { ] } -var _$normals_280 = {}; +var _$normals_338 = {}; var DEFAULT_NORMALS_EPSILON = 1e-6; var DEFAULT_FACE_EPSILON = 1e-6; //Estimate the vertex normals of a mesh -_$normals_280.vertexNormals = function(faces, positions, specifiedEpsilon) { +_$normals_338.vertexNormals = function(faces, positions, specifiedEpsilon) { var N = positions.length; var normals = new Array(N); @@ -122581,7 +123381,7 @@ _$normals_280.vertexNormals = function(faces, positions, specifiedEpsilon) { } //Compute face normals of a mesh -_$normals_280.faceNormals = function(faces, positions, specifiedEpsilon) { +_$normals_338.faceNormals = function(faces, positions, specifiedEpsilon) { var N = faces.length; var normals = new Array(N); @@ -122626,28 +123426,28 @@ _$normals_280.faceNormals = function(faces, positions, specifiedEpsilon) { "use strict" -/* removed: var _$pool_360 = require("typedarray-pool") */; +/* removed: var _$pool_422 = require("typedarray-pool") */; var INSERTION_SORT_THRESHOLD = 32 function getMallocFree(dtype) { switch(dtype) { case "uint8": - return [_$pool_360.mallocUint8, _$pool_360.freeUint8] + return [_$pool_422.mallocUint8, _$pool_422.freeUint8] case "uint16": - return [_$pool_360.mallocUint16, _$pool_360.freeUint16] + return [_$pool_422.mallocUint16, _$pool_422.freeUint16] case "uint32": - return [_$pool_360.mallocUint32, _$pool_360.freeUint32] + return [_$pool_422.mallocUint32, _$pool_422.freeUint32] case "int8": - return [_$pool_360.mallocInt8, _$pool_360.freeInt8] + return [_$pool_422.mallocInt8, _$pool_422.freeInt8] case "int16": - return [_$pool_360.mallocInt16, _$pool_360.freeInt16] + return [_$pool_422.mallocInt16, _$pool_422.freeInt16] case "int32": - return [_$pool_360.mallocInt32, _$pool_360.freeInt32] + return [_$pool_422.mallocInt32, _$pool_422.freeInt32] case "float32": - return [_$pool_360.mallocFloat, _$pool_360.freeFloat] + return [_$pool_422.mallocFloat, _$pool_422.freeFloat] case "float64": - return [_$pool_360.mallocDouble, _$pool_360.freeDouble] + return [_$pool_422.mallocDouble, _$pool_422.freeDouble] default: return null } @@ -123351,31 +124151,31 @@ function compileSort(order, dtype) { return result(insertionSort, quickSort) } -var _$compileSort_274 = compileSort +var _$compileSort_332 = compileSort "use strict" -/* removed: var _$compileSort_274 = require("./lib/compile_sort.js") */; -var __CACHE_275 = {} +/* removed: var _$compileSort_332 = require("./lib/compile_sort.js") */; +var __CACHE_333 = {} function sort(array) { var order = array.order var dtype = array.dtype var typeSig = [order, dtype ] var typeName = typeSig.join(":") - var compiled = __CACHE_275[typeName] + var compiled = __CACHE_333[typeName] if(!compiled) { - __CACHE_275[typeName] = compiled = _$compileSort_274(order, dtype) + __CACHE_333[typeName] = compiled = _$compileSort_332(order, dtype) } compiled(array) return array } -var _$sort_275 = sort +var _$sort_333 = sort 'use strict' -var _$createTable_255 = createTable +var _$createTable_312 = createTable -/* removed: var _$convexHull_109 = require('convex-hull') */; +/* removed: var _$convexHull_110 = require('convex-hull') */; function constructVertex(d, a, b) { var x = new Array(d) @@ -123411,7 +124211,7 @@ function constructCell(dimension, mask) { } //Preprocess points so first d+1 points are linearly independent - var hull = _$convexHull_109(points) + var hull = _$convexHull_110(points) var faces = [] i_loop: for(var i=0; i= 1 } -__proto_187.isTransparent = function() { +__proto_244.isTransparent = function() { return this.opacity < 1 } -__proto_187.pickSlots = 1 +__proto_244.pickSlots = 1 -__proto_187.setPickBase = function(id) { +__proto_244.setPickBase = function(id) { this.pickId = id } function genColormap(param) { - var colors = _$createColormap_105({ + var colors = _$createColormap_106({ colormap: param , nshades: 256 , format: 'rgba' @@ -123854,7 +124655,7 @@ function genColormap(param) { result[4*i+3] = c[3]*255 } - return _$wrappedNDArrayCtor_277(result, [256,256,4], [4,0,1]) + return _$wrappedNDArrayCtor_335(result, [256,256,4], [4,0,1]) } function unpackIntensity(cells, numVerts, cellIntensity) { @@ -123881,17 +124682,17 @@ function takeZComponent(array) { return result } -__proto_187.highlight = function(selection) { +__proto_244.highlight = function(selection) { if(!selection || !this.contourEnable) { this.contourCount = 0 return } - var level = _$extractContour_331(this.cells, this.intensity, selection.intensity) + var level = _$extractContour_395(this.cells, this.intensity, selection.intensity) var cells = level.cells var vertexIds = level.vertexIds var vertexWeights = level.vertexWeights var numCells = cells.length - var result = _$pool_360.mallocFloat32(2 * 3 * numCells) + var result = _$pool_422.mallocFloat32(2 * 3 * numCells) var ptr = 0 for(var i=0; i 0) { - cells = _$alphaShape_47(data.alphahull, positions); + cells = _$alphaShape_48(data.alphahull, positions); } else { var d = ['x', 'y', 'z'].indexOf(data.delaunayaxis); - cells = _$triangulate_129(positions.map(function(c) { + cells = _$triangulate_132(positions.map(function(c) { return [c[(d + 1) % 3], c[(d + 2) % 3]]; })); } @@ -124841,7 +125647,7 @@ __proto_817.update = function(data) { faceNormalsEpsilon: data.lighting.facenormalsepsilon, opacity: data.opacity, contourEnable: data.contour.show, - contourColor: _$str2RgbaArray_561(data.contour.color).slice(0, 3), + contourColor: _$str2RgbaArray_624(data.contour.color).slice(0, 3), contourWidth: data.contour.width, useFacetNormals: data.flatshading }; @@ -124862,21 +125668,21 @@ __proto_817.update = function(data) { } else { this.color = data.color; - config.meshColor = _$str2RgbaArray_561(data.color); + config.meshColor = _$str2RgbaArray_624(data.color); } // Update mesh this.mesh.update(config); }; -__proto_817.dispose = function() { +__proto_879.dispose = function() { this.scene.glplot.remove(this.mesh); this.mesh.dispose(); }; function createMesh3DTrace(scene, data) { var gl = scene.glplot.gl; - var mesh = _$createSimplicialMesh_187({gl: gl}); + var mesh = _$createSimplicialMesh_244({gl: gl}); var result = new Mesh3DTrace(scene, mesh, data.uid); mesh._trace = result; result.update(data); @@ -124884,7 +125690,7 @@ function createMesh3DTrace(scene, data) { return result; } -var _$createMesh3DTrace_817 = createMesh3DTrace; +var _$createMesh3DTrace_879 = createMesh3DTrace; /** * Copyright 2012-2018, Plotly, Inc. @@ -124897,14 +125703,14 @@ var _$createMesh3DTrace_817 = createMesh3DTrace; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -/* removed: var _$attributes_814 = require('./attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +/* removed: var _$attributes_876 = require('./attributes'); */; -var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_880 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_814, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_876, attr, dflt); } // read in face/vertex properties @@ -124912,7 +125718,7 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol var ret = array.map(function(attr) { var result = coerce(attr); - if(result && _$lib_539.isArrayOrTypedArray(result)) return result; + if(result && _$lib_601.isArrayOrTypedArray(result)) return result; return null; }); @@ -124936,7 +125742,7 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol }); } - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); // Coerce remaining properties @@ -124964,7 +125770,7 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol if('intensity' in traceIn) { coerce('intensity'); - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'}); + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'c'}); } else { traceOut.showscale = false; @@ -124989,21 +125795,21 @@ var _$supplyDefaults_818 = function supplyDefaults(traceIn, traceOut, defaultCol var Mesh3D = {}; -Mesh3D.attributes = _$attributes_814; -Mesh3D.supplyDefaults = _$supplyDefaults_818; -Mesh3D.calc = _$calc_815; -Mesh3D.colorbar = _$colorbar_816; -Mesh3D.plot = _$createMesh3DTrace_817; +Mesh3D.attributes = _$attributes_876; +Mesh3D.supplyDefaults = _$supplyDefaults_880; +Mesh3D.calc = _$calc_877; +Mesh3D.colorbar = _$colorbar_878; +Mesh3D.plot = _$createMesh3DTrace_879; Mesh3D.moduleType = 'trace'; Mesh3D.name = 'mesh3d', -Mesh3D.basePlotModule = _$gl3d_627; +Mesh3D.basePlotModule = _$gl3d_689; Mesh3D.categories = ['gl3d']; Mesh3D.meta = { }; -var _$Mesh3D_819 = Mesh3D; +var _$Mesh3D_881 = Mesh3D; /** * Copyright 2012-2018, Plotly, Inc. @@ -125015,7 +125821,7 @@ var _$Mesh3D_819 = Mesh3D; 'use strict'; -var _$mesh3d_21 = _$Mesh3D_819; +var _$mesh3d_21 = _$Mesh3D_881; /** * Copyright 2012-2018, Plotly, Inc. @@ -125028,21 +125834,17 @@ var _$mesh3d_21 = _$Mesh3D_819; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$handleOHLC_825 = require('./ohlc_defaults'); */; -/* removed: var _$handleDirectionDefaults_822 = require('./direction_defaults'); */; -/* removed: var _$attributes_820 = require('./attributes'); */; -/* removed: var _$helpers_823 = require('./helpers'); */; - -var _$supplyDefaults_821 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - _$helpers_823.pushDummyTransformOpts(traceIn, traceOut); +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$handleOHLC_887 = require('./ohlc_defaults'); */; +/* removed: var _$attributes_882 = require('./attributes'); */; +var _$supplyDefaults_884 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_820, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_882, attr, dflt); } - var len = _$handleOHLC_825(traceIn, traceOut, coerce, layout); - if(len === 0) { + var len = _$handleOHLC_887(traceIn, traceOut, coerce, layout); + if(!len) { traceOut.visible = false; return; } @@ -125050,22 +125852,21 @@ var _$supplyDefaults_821 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('line.width'); coerce('line.dash'); - __handleDirection_821(traceIn, traceOut, coerce, 'increasing'); - __handleDirection_821(traceIn, traceOut, coerce, 'decreasing'); + __handleDirection_884(traceIn, traceOut, coerce, 'increasing'); + __handleDirection_884(traceIn, traceOut, coerce, 'decreasing'); coerce('text'); coerce('tickwidth'); -}; -function __handleDirection_821(traceIn, traceOut, coerce, direction) { - _$handleDirectionDefaults_822(traceIn, traceOut, coerce, direction); + layout._requestRangeslider[traceOut.xaxis] = true; +}; +function __handleDirection_884(traceIn, traceOut, coerce, direction) { coerce(direction + '.line.color'); coerce(direction + '.line.width', traceOut.line.width); coerce(direction + '.line.dash', traceOut.line.dash); } -var _$transform_826 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -125074,264 +125875,100 @@ var _$transform_826 = {}; * LICENSE file in the root directory of this source tree. */ - 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var ____826 = _$lib_539._; -/* removed: var _$helpers_823 = require('./helpers'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -_$transform_826.moduleType = 'transform'; +var _$plot_888 = function plot(gd, plotinfo, cdOHLC) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; -_$transform_826.name = 'ohlc'; + var ohlcLayer = plotinfo.plot.select('g.ohlclayer'); -_$transform_826.attributes = {}; + var traces = ohlcLayer.selectAll('g.trace') + .data(cdOHLC, function(d) { return d[0].trace.uid; }); -_$transform_826.supplyDefaults = function(transformIn, traceOut, layout, traceIn) { - _$helpers_823.clearEphemeralTransformOpts(traceIn); - _$helpers_823.copyOHLC(transformIn, traceOut); + traces.enter().append('g') + .attr('class', 'trace ohlc'); - return transformIn; -}; + traces.exit().remove(); -_$transform_826.transform = function transform(dataIn, state) { - var dataOut = []; + traces.order(); - for(var i = 0; i < dataIn.length; i++) { - var traceIn = dataIn[i]; + traces.each(function(d) { + var cd0 = d[0]; + var t = cd0.t; + var trace = cd0.trace; + var sel = _$d3_130.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; - if(traceIn.type !== 'ohlc') { - dataOut.push(traceIn); - continue; + if(trace.visible !== true || t.empty) { + sel.remove(); + return; } - dataOut.push( - __makeTrace_826(traceIn, state, 'increasing'), - __makeTrace_826(traceIn, state, 'decreasing') - ); - } - - _$helpers_823.addRangeSlider(dataOut, state.layout); - - return dataOut; -}; - -function __makeTrace_826(traceIn, state, direction) { - var traceOut = { - type: 'scatter', - mode: 'lines', - connectgaps: false, - - visible: traceIn.visible, - opacity: traceIn.opacity, - xaxis: traceIn.xaxis, - yaxis: traceIn.yaxis, - - hoverinfo: __makeHoverInfo_826(traceIn), - transforms: _$helpers_823.makeTransform(traceIn, state, direction) - }; - - // the rest of below may not have been coerced + var tickLen = t.tickLen; - var directionOpts = traceIn[direction]; + var paths = sel.selectAll('path').data(_$lib_601.identity); - if(directionOpts) { - _$lib_539.extendFlat(traceOut, { + paths.enter().append('path'); - // to make autotype catch date axes soon!! - x: traceIn.x || [0], - xcalendar: traceIn.xcalendar, + paths.exit().remove(); - // concat low and high to get correct autorange - y: [].concat(traceIn.low).concat(traceIn.high), + paths.attr('d', function(d) { + var x = xa.c2p(d.pos, true); + var xo = xa.c2p(d.pos - tickLen, true); + var xc = xa.c2p(d.pos + tickLen, true); - text: traceIn.text, + var yo = ya.c2p(d.o, true); + var yh = ya.c2p(d.h, true); + var yl = ya.c2p(d.l, true); + var yc = ya.c2p(d.c, true); - name: directionOpts.name, - showlegend: directionOpts.showlegend, - line: directionOpts.line + return 'M' + xo + ',' + yo + 'H' + x + + 'M' + x + ',' + yh + 'V' + yl + + 'M' + xc + ',' + yc + 'H' + x; }); - } - - return traceOut; -} - -// Let scatter hoverPoint format 'x' coordinates, if desired. -// -// Note that, this solution isn't perfect: it shows open and close -// values at slightly different 'x' coordinates then the rest of the -// segments, but is for more robust than calling `Axes.tickText` during -// calcTransform. -// -// A future iteration should perhaps try to add a hook for transforms in -// the hoverPoints handlers. -function __makeHoverInfo_826(traceIn) { - var hoverinfo = traceIn.hoverinfo; - - if(hoverinfo === 'all') return 'x+text+name'; - - var parts = hoverinfo.split('+'), - indexOfY = parts.indexOf('y'), - indexOfText = parts.indexOf('text'); - - if(indexOfY !== -1) { - parts.splice(indexOfY, 1); - - if(indexOfText === -1) parts.push('text'); - } - - return parts.join('+'); -} - -_$transform_826.calcTransform = function calcTransform(gd, trace, opts) { - var direction = opts.direction, - filterFn = _$helpers_823.getFilterFn(direction); - - var xa = _$axis_ids_587.getFromTrace(gd, trace, 'x'), - ya = _$axis_ids_587.getFromTrace(gd, trace, 'y'), - tickWidth = convertTickWidth(gd, xa, trace); - - var open = trace.open, - high = trace.high, - low = trace.low, - close = trace.close, - textIn = trace.text; - - var openName = ____826(gd, 'open:') + ' '; - var highName = ____826(gd, 'high:') + ' '; - var lowName = ____826(gd, 'low:') + ' '; - var closeName = ____826(gd, 'close:') + ' '; - - var len = open.length, - x = [], - y = [], - textOut = []; - - var appendX; - if(trace._fullInput.x) { - appendX = function(i) { - var xi = trace.x[i], - xcalendar = trace.xcalendar, - xcalc = xa.d2c(xi, 0, xcalendar); - - x.push( - xa.c2d(xcalc - tickWidth, 0, xcalendar), - xi, xi, xi, xi, - xa.c2d(xcalc + tickWidth, 0, xcalendar), - null); - }; - } - else { - appendX = function(i) { - x.push( - i - tickWidth, - i, i, i, i, - i + tickWidth, - null); - }; - } - - var appendY = function(o, h, l, c) { - y.push(o, o, h, l, c, c, null); - }; - - var format = function(ax, val) { - return _$axes_584.tickText(ax, ax.c2l(val), 'hover').text; - }; - - var hoverinfo = trace._fullInput.hoverinfo, - hoverParts = hoverinfo.split('+'), - hasAll = hoverinfo === 'all', - hasY = hasAll || hoverParts.indexOf('y') !== -1, - hasText = hasAll || hoverParts.indexOf('text') !== -1; - - var getTextItem = Array.isArray(textIn) ? - function(i) { return textIn[i] || ''; } : - function() { return textIn; }; - - var appendText = function(i, o, h, l, c) { - var t = []; - - if(hasY) { - t.push(openName + format(ya, o)); - t.push(highName + format(ya, h)); - t.push(lowName + format(ya, l)); - t.push(closeName + format(ya, c)); - } - - if(hasText) t.push(getTextItem(i)); - - var _t = t.join('
'); - - textOut.push(_t, _t, _t, _t, _t, _t, null); - }; - - for(var i = 0; i < len; i++) { - if(filterFn(open[i], close[i]) && _$fastIsnumeric_139(high[i]) && _$fastIsnumeric_139(low[i])) { - appendX(i); - appendY(open[i], high[i], low[i], close[i]); - appendText(i, open[i], high[i], low[i], close[i]); - } - } - - trace.x = x; - trace.y = y; - trace.text = textOut; - trace._length = x.length; + }); }; -function convertTickWidth(gd, xa, trace) { - var fullInput = trace._fullInput, - tickWidth = fullInput.tickwidth, - minDiff = fullInput._minDiff; - - if(!minDiff) { - var fullData = gd._fullData, - ohlcTracesOnThisXaxis = []; - - minDiff = Infinity; - - // find min x-coordinates difference of all traces - // attached to this x-axis and stash the result - - var i; - - for(i = 0; i < fullData.length; i++) { - var _trace = fullData[i]._fullInput; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ - if(_trace.type === 'ohlc' && - _trace.visible === true && - _trace.xaxis === xa._id - ) { - ohlcTracesOnThisXaxis.push(_trace); +'use strict'; - // - _trace.x may be undefined here, - // it is filled later in calcTransform - // - // - handle trace of length 1 separately. +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$color_473 = require('../../components/color'); */; - if(_trace.x && _trace.x.length > 1) { - var xcalc = _$lib_539.simpleMap(_trace.x, xa.d2c, 0, trace.xcalendar), - _minDiff = _$lib_539.distinctVals(xcalc).minDiff; - minDiff = Math.min(minDiff, _minDiff); - } - } - } +var _$style_890 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.ohlclayer').selectAll('g.trace'); - // if minDiff is still Infinity here, set it to 1 - if(minDiff === Infinity) minDiff = 1; + s.style('opacity', function(d) { + return d[0].trace.opacity; + }); - for(i = 0; i < ohlcTracesOnThisXaxis.length; i++) { - ohlcTracesOnThisXaxis[i]._minDiff = minDiff; - } - } + s.each(function(d) { + var trace = d[0].trace; - return minDiff * tickWidth; -} + _$d3_130.select(this).selectAll('path').each(function(di) { + var dirLine = trace[di.dir].line; + _$d3_130.select(this) + .style('fill', 'none') + .call(_$color_473.stroke, dirLine.color) + .call(_$drawing_498.dashLine, dirLine.dash, dirLine.width) + // TODO: custom selection style for OHLC + .style('opacity', trace.selectedpoints && !di.selected ? 0.3 : 1); + }); + }); +}; /** * Copyright 2012-2018, Plotly, Inc. @@ -125343,24 +125980,24 @@ function convertTickWidth(gd, xa, trace) { 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - -var _$ohlc_824 = { +var _$ohlc_886 = { moduleType: 'trace', name: 'ohlc', - basePlotModule: _$cartesian_595, - categories: ['cartesian', 'showLegend'], + basePlotModule: _$cartesian_658, + categories: ['cartesian', 'svg', 'showLegend'], meta: { }, - attributes: _$attributes_820, - supplyDefaults: _$supplyDefaults_821, + attributes: _$attributes_882, + supplyDefaults: _$supplyDefaults_884, + calc: _$calc_883.calc, + plot: _$plot_888, + style: _$style_890, + hoverPoints: _$hoverPoints_885, + selectPoints: _$selectPoints_889 }; -_$registry_668.register(_$Scatter_874); -_$registry_668.register(_$transform_826); - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -125371,7 +126008,7 @@ _$registry_668.register(_$transform_826); 'use strict'; -var _$ohlc_22 = _$ohlc_824; +var _$ohlc_22 = _$ohlc_886; /** * Copyright 2012-2018, Plotly, Inc. @@ -125383,29 +126020,29 @@ var _$ohlc_22 = _$ohlc_824; 'use strict'; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -/* removed: var _$scales_430 = require('../../components/colorscale/scales'); */; -/* removed: var _$layout_attributes_596 = require('../../plots/cartesian/layout_attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -var __domainAttrs_827 = _$domain_610.attributes; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +/* removed: var _$scales_492 = require('../../components/colorscale/scales'); */; +/* removed: var _$layout_attributes_659 = require('../../plots/cartesian/layout_attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +var __domainAttrs_891 = _$domain_672.attributes; -/* removed: var _$extend_528 = require('../../lib/extend'); */; -var __extendDeepAll_827 = _$extend_528.extendDeepAll; -var __extendFlat_827 = _$extend_528.extendFlat; +/* removed: var _$extend_590 = require('../../lib/extend'); */; +var __extendDeepAll_891 = _$extend_590.extendDeepAll; +var __extendFlat_891 = _$extend_590.extendFlat; -var _$attributes_827 = { - domain: __domainAttrs_827({name: 'parcoords', trace: true, editType: 'calc'}), +var _$attributes_891 = { + domain: __domainAttrs_891({name: 'parcoords', trace: true, editType: 'calc'}), - labelfont: _$font_attributes_611({ + labelfont: _$font_attributes_673({ editType: 'calc', }), - tickfont: _$font_attributes_611({ + tickfont: _$font_attributes_673({ editType: 'calc', }), - rangefont: _$font_attributes_611({ + rangefont: _$font_attributes_673({ editType: 'calc', }), @@ -125418,8 +126055,10 @@ var _$attributes_827 = { editType: 'calc', }, - tickvals: __extendFlat_827({}, _$layout_attributes_596.tickvals, {editType: 'calc'}), - ticktext: __extendFlat_827({}, _$layout_attributes_596.ticktext, {editType: 'calc'}), + // TODO: better way to determine ordinal vs continuous axes, + // so users can use tickvals/ticktext with a continuous axis. + tickvals: __extendFlat_891({}, _$layout_attributes_659.tickvals, {editType: 'calc'}), + ticktext: __extendFlat_891({}, _$layout_attributes_659.ticktext, {editType: 'calc'}), tickformat: { valType: 'string', dflt: '3s', @@ -125447,12 +126086,21 @@ var _$attributes_827 = { constraintrange: { valType: 'info_array', + freeLength: true, + dimensions: '1-2', items: [ {valType: 'number', editType: 'calc'}, {valType: 'number', editType: 'calc'} ], editType: 'calc', + }, + multiselect: { + valType: 'boolean', + dflt: true, + + editType: 'calc', + }, values: { valType: 'data_array', @@ -125464,14 +126112,14 @@ var _$attributes_827 = { }, - line: __extendFlat_827( + line: __extendFlat_891( // the default autocolorscale isn't quite usable for parcoords due to context ambiguity around 0 (grey, off-white) // autocolorscale therefore defaults to false too, to avoid being overridden by the blue-white-red autocolor palette - __extendDeepAll_827( - _$makeColorScaleAttributes_419('line', 'calc'), + __extendDeepAll_891( + _$makeColorScaleAttributes_481('line', 'calc'), { - colorscale: {dflt: _$scales_430.Viridis}, + colorscale: {dflt: _$scales_492.Viridis}, autocolorscale: { dflt: false, @@ -125487,14 +126135,14 @@ var _$attributes_827 = { editType: 'calc', }, - colorbar: _$attributes_412, + colorbar: _$attributes_474, editType: 'calc' } ) }; -var _$regl_315 = { exports: {} }; -(function(da,ea){"object"===typeof _$regl_315.exports&&"undefined"!=="object"?_$regl_315.exports=ea():"function"===typeof define&&define.amd?define(ea):da.createREGL=ea()})(this,function(){function da(a,b){this.id=vb++;this.type=a;this.data=b}function ea(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1= 0; i--) { + var aNext = a[i]; + + // very close to the previous - snap down to it + if(v > closeToCovering(aPrev, aNext)) return snapOvershoot(aPrev, aPrevPrev); + if(v > aNext || i === a.length - 1) return snapOvershoot(aNext, aPrev); + + aPrevPrev = aPrev; + aPrev = 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', -_$constants_896.bar.captureWidth / 2) + .attr('width', _$constants_896.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 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 = _$constants_896.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_130.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_130.select(root).selectAll('.highlight, .highlight-shadow'); + var barToStyle = tweenCallback ? bar.transition().duration(_$constants_896.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 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_130.event.preventDefault(); + if(!d.parent.inBrushDrag) { + var y = d.height - _$d3_130.mouse(this)[1] - 2 * _$constants_896.verticalPadding; + var interval = getInterval(d, y); + + var cursor = 'crosshair'; + if(interval.clickableOrdinalRange) cursor = 'pointer'; + else if(interval.region) cursor = interval.region + '-resize'; + _$d3_130.select(document.body) + .style('cursor', cursor); + } + }) + .on('mouseleave', function(d) { + if(!d.parent.inBrushDrag) clearCursor(); + }) + .call(_$d3_130.behavior.drag() + .on('dragstart', function(d) { + _$d3_130.event.sourceEvent.stopPropagation(); + var y = d.height - _$d3_130.mouse(this)[1] - 2 * _$constants_896.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] - _$constants_896.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(); + }) + .on('drag', function(d) { + _$d3_130.event.sourceEvent.stopPropagation(); + var y = d.height - _$d3_130.mouse(this)[1] - 2 * _$constants_896.verticalPadding; + var s = d.brush.svgBrush; + s.wasDragged = 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); + } + + // take care of the parcoords axis height constraint: bar can't breach it + var bottomViolation = Math.max(0, -s.newExtent[0]); + var topViolation = Math.max(0, s.newExtent[1] - 1); + s.newExtent[0] += bottomViolation; + s.newExtent[1] -= topViolation; + if(s.grabbingBar) { + // in case of bar dragging (non-resizing interaction, unlike north/south resize or new bar creation) + // the constraint adjustment must apply to the other end of the bar as well, otherwise it'd + // shorten or lengthen + s.newExtent[1] += bottomViolation; + s.newExtent[0] -= topViolation; + } + + d.brush.filterSpecified = true; + s.extent = s.stayingIntervals.concat([s.newExtent]); + s.brushCallback(d); + renderHighlight(this.parentNode); + }) + .on('dragend', function(d) { + var e = _$d3_130.event; + e.sourceEvent.stopPropagation(); + var brush = d.brush; + var filter = brush.filter; + var s = brush.svgBrush; + 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(this.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 = [ + ordinalScaleSnapLo(a, s.newExtent[0], s.stayingIntervals), + ordinalScaleSnapHi(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(this.parentNode, mergeIntervals); + } + else { + // if no new interval, don't animate, just redraw the highlight immediately + mergeIntervals(); + renderHighlight(this.parentNode); + } + } else { + mergeIntervals(); // merging intervals immediately + } + s.brushEndCallback(brush.filterSpecified ? filter.getConsolidated() : []); + }) + ); +} + +function startAsc(a, b) { return a[0] - b[0]; } + +function renderAxisBrush(axisBrush) { + + var background = axisBrush.selectAll('.background').data(__repeat_892); + + 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 ' + _$constants_896.verticalPadding + ')'); + + background + .call(attachDragBehavior) + .attr('height', function(d) { + return d.height - _$constants_896.verticalPadding; + }); + + var highlightShadow = axisBrush.selectAll('.highlight-shadow').data(__repeat_892); // we have a set here, can't call it `extent` + + highlightShadow.enter() + .append('line') + .classed('highlight-shadow', true) + .attr('x', -_$constants_896.bar.width / 2) + .attr('stroke-width', _$constants_896.bar.width + _$constants_896.bar.strokeWidth) + .attr('stroke', _$constants_896.bar.strokeColor) + .attr('opacity', _$constants_896.bar.strokeOpacity) + .attr('stroke-linecap', 'butt'); + + highlightShadow + .attr('y1', function(d) { return d.height; }) + .call(styleHighlight); + + var highlight = axisBrush.selectAll('.highlight').data(__repeat_892); // we have a set here, can't call it `extent` + + highlight.enter() + .append('line') + .classed('highlight', true) + .attr('x', -_$constants_896.bar.width / 2) + .attr('stroke-width', _$constants_896.bar.width - _$constants_896.bar.strokeWidth) + .attr('stroke', _$constants_896.bar.fillColor) + .attr('opacity', _$constants_896.bar.fillOpacity) + .attr('stroke-linecap', 'butt'); + + highlight + .attr('y1', function(d) { return d.height; }) + .call(styleHighlight); +} + +function ensureAxisBrush(axisOverlays) { + var axisBrush = axisOverlays.selectAll('.' + _$constants_896.cn.axisBrush) + .data(__repeat_892, keyFun); + + axisBrush.enter() + .append('g') + .classed(_$constants_896.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 = [[0, 1]]; +} + +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); + 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 = [ + ordinalScaleSnapLo(sortedTickVals, ri[0], []), + ordinalScaleSnapHi(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]; +} + +var _$axisbrush_892 = { + makeBrush: makeBrush, + ensureAxisBrush: ensureAxisBrush, + cleanRanges: cleanRanges +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$browser_295 = require('glslify'); */; +var vertexShaderSource = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]); +var contextShaderSource = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depth,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]); +var pickVertexShaderSource = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n fragColor = vec4(pf.rgb, 1.0);\n}\n"]); +var fragmentShaderSource = _$browser_295(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]); + +/* removed: var _$lib_601 = require('../../lib'); */; + +// don't change; otherwise near/far plane lines are lost +var depthLimitEpsilon = 1e-6; +// just enough buffer for an extra bit at single-precision floating point +// which on [0, 1] is 6e-8 (1/2^24) +var filterEpsilon = 1e-7; + +// precision of multiselect is the full range divided into this many parts +var maskHeight = 2048; var gpuDimensionCount = 64; var sectionVertexCount = 2; var vec4NumberCount = 4; +var bitsPerByte = 8; +var channelCount = gpuDimensionCount / bitsPerByte; // == 8 bytes needed to have 64 bits var contextColor = [119, 119, 119]; // middle gray to not drawn the focus; looks good on a black or white background var dummyPixel = new Uint8Array(4); var pickPixel = new Uint8Array(4); +var paletteTextureConfig = { + shape: [256, 1], + format: 'rgba', + type: 'uint8', + mag: 'nearest', + min: 'nearest' +}; + function ensureDraw(regl) { regl.read({ x: 0, @@ -125849,7 +127092,8 @@ function calcPickColor(j, rgbIndex) { return (j >>> 8 * rgbIndex) % 256 / 255; } -function makePoints(sampleCount, dimensionCount, dimensions, color) { +function makePoints(sampleCount, dimensions, color) { + var dimensionCount = dimensions.length; var points = []; for(var j = 0; j < sampleCount; j++) { @@ -125868,7 +127112,6 @@ function makePoints(sampleCount, dimensionCount, dimensions, color) { } function makeVecAttr(sampleCount, points, vecIndex) { - var i, j, k; var pointPairs = []; @@ -125886,36 +127129,26 @@ function makeVecAttr(sampleCount, points, vecIndex) { return pointPairs; } -function makeAttributes(sampleCount, points) { - - var vecIndices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; - var vectors = vecIndices.map(function(vecIndex) {return makeVecAttr(sampleCount, points, vecIndex);}); +function setAttributes(attributes, sampleCount, points) { + for(var i = 0; i < 16; i++) { + attributes['p' + i.toString(16)](makeVecAttr(sampleCount, points, i)); + } +} +function emptyAttributes(regl) { var attributes = {}; - vectors.forEach(function(v, vecIndex) { - attributes['p' + vecIndex.toString(16)] = v; - }); - + for(var i = 0; i < 16; i++) { + attributes['p' + i.toString(16)] = regl.buffer({usage: 'dynamic', type: 'float', data: null}); + } return attributes; } -function valid(i, offset, panelCount) { - return i + offset <= panelCount; -} - -var _$lines_834 = function(canvasGL, d, scatter) { - var model = d.model, - vm = d.viewModel, - domain = model.domain; +var _$lines_899 = function(canvasGL, d) { + // context & pick describe which canvas we're talking about - won't change with new data + var context = d.context; + var pick = d.pick; - var lines = model.lines, - canvasWidth = model.canvasWidth, - canvasHeight = model.canvasHeight, - initialDimensions = vm.dimensions, - initialPanels = vm.panels, - unitToColor = model.unitToColor, - context = d.context, - pick = d.pick; + var regl = d.regl; var renderState = { currentRafs: {}, @@ -125923,39 +127156,23 @@ var _$lines_834 = function(canvasGL, d, scatter) { clearOnly: false }; - var initialDims = initialDimensions.slice(); - - var dimensionCount = initialDims.length; - var sampleCount = initialDims[0] ? initialDims[0].values.length : 0; - - var focusAlphaBlending = context; + // 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 color = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color; - var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3)); - var overdrag = lines.canvasOverdrag; - - var panelCount = initialPanels.length; - - var points = makePoints(sampleCount, dimensionCount, initialDims, color); - var attributes = makeAttributes(sampleCount, points); - - var regl = d.regl; - - var paletteTexture = regl.texture({ - shape: [256, 1], - format: 'rgba', - type: 'uint8', - mag: 'nearest', - min: 'nearest', - data: palette(unitToColor, context, Math.round((context ? contextOpacity : 1) * 255)) - }); + update(d); var glAes = regl({ profile: false, blend: { - enable: focusAlphaBlending, + enable: context, func: { srcRGB: 'src alpha', dstRGB: 'one minus src alpha', @@ -125970,7 +127187,7 @@ var _$lines_834 = function(canvasGL, d, scatter) { }, depth: { - enable: !focusAlphaBlending, + enable: !context, mask: true, func: 'less', range: [0, 1] @@ -126001,7 +127218,7 @@ var _$lines_834 = function(canvasGL, d, scatter) { dither: false, - vert: pick ? pickVertexShaderSource : vertexShaderSource, + vert: pick ? pickVertexShaderSource : context ? contextShaderSource : vertexShaderSource, frag: fragmentShaderSource, @@ -126029,13 +127246,32 @@ var _$lines_834 = function(canvasGL, d, scatter) { loD: regl.prop('loD'), hiD: regl.prop('hiD'), palette: paletteTexture, - colorClamp: regl.prop('colorClamp'), - scatter: regl.prop('scatter') + mask: regl.prop('maskTexture'), + maskHeight: regl.prop('maskHeight'), + colorClamp: regl.prop('colorClamp') }, 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 = pick ? lines.color.map(function(_, i) {return i / lines.color.length;}) : lines.color; + var contextOpacity = Math.max(1 / 255, Math.pow(1 / color.length, 1 / 3)); + + var points = makePoints(sampleCount, initialDims, color); + setAttributes(attributes, sampleCount, points); + + paletteTexture = regl.texture(_$lib_601.extendFlat({ + data: palette(model.unitToColor, context, Math.round((context ? contextOpacity : 1) * 255)) + }, paletteTextureConfig)); + } + var colorClamp = [0, 1]; function setColorDomain(unitDomain) { @@ -126045,26 +127281,27 @@ var _$lines_834 = function(canvasGL, d, scatter) { var previousAxisOrder = []; - function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, scatter, I, leftmost, rightmost) { + function makeItem(i, ii, x, y, panelSizeX, canvasPanelSizeY, crossfilterDimensionIndex, I, leftmost, rightmost, constraints) { var loHi, abcd, d, index; var leftRight = [i, ii]; - var filterEpsilon = _$constants_831.verticalPadding / canvasPanelSizeY; var dims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); - var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); for(loHi = 0; loHi < 2; loHi++) { index = leftRight[loHi]; for(abcd = 0; abcd < 4; abcd++) { for(d = 0; d < 16; d++) { - var dimP = d + 16 * abcd; dims[loHi][abcd][d] = d + 16 * abcd === index ? 1 : 0; - lims[loHi][abcd][d] = (!context && valid(d, 16 * abcd, panelCount) ? initialDims[dimP === 0 ? 0 : 1 + ((dimP - 1) % (initialDims.length - 1))].filter[loHi] : loHi) + (2 * loHi - 1) * filterEpsilon; } } } - return { + var overdrag = model.lines.canvasOverdrag; + var domain = model.domain; + var canvasWidth = model.canvasWidth; + var canvasHeight = model.canvasHeight; + + var itemModel = _$lib_601.extendFlat({ key: crossfilterDimensionIndex, resolution: [canvasWidth, canvasHeight], viewBoxPosition: [x + overdrag, y], @@ -126081,17 +127318,7 @@ var _$lines_834 = function(canvasGL, d, scatter) { dim2C: dims[1][2], dim2D: dims[1][3], - loA: lims[0][0], - loB: lims[0][1], - loC: lims[0][2], - loD: lims[0][3], - hiA: lims[1][0], - hiB: lims[1][1], - hiC: lims[1][2], - hiD: lims[1][3], - colorClamp: colorClamp, - scatter: scatter || 0, scissorX: (I === leftmost ? 0 : x + overdrag) + (model.pad.l - overdrag) + model.layoutWidth * domain.x[0], scissorWidth: (I === rightmost ? canvasWidth - x + overdrag : panelSizeX + 0.5) + (I === leftmost ? x + overdrag : 0), @@ -126102,11 +127329,87 @@ var _$lines_834 = function(canvasGL, d, scatter) { viewportY: model.pad.b + model.layoutHeight * domain.y[0], viewportWidth: canvasWidth, viewportHeight: canvasHeight + }, constraints); + + return itemModel; + } + + function makeConstraints() { + var loHi, abcd, d; + + var lims = [0, 1].map(function() {return [0, 1, 2, 3].map(function() {return new Float32Array(16);});}); + + for(loHi = 0; loHi < 2; loHi++) { + for(abcd = 0; abcd < 4; abcd++) { + for(d = 0; d < 16; d++) { + var dimP = d + 16 * abcd; + var lim; + if(dimP < initialDims.length) { + lim = initialDims[dimP].brush.filter.getBounds()[loHi]; + } + else lim = loHi; + lims[loHi][abcd][d] = lim + (2 * loHi - 1) * filterEpsilon; + } + } + } + + function expandedPixelRange(dim, bounds) { + var maskHMinus = maskHeight - 1; + return [ + Math.max(0, Math.floor(bounds[0] * maskHMinus)), + Math.min(maskHMinus, Math.ceil(bounds[1] * maskHMinus)) + ]; + } + + var mask = Array.apply(null, new Array(maskHeight * channelCount)).map(function() { + return 255; + }); + for(var dimIndex = 0; dimIndex < initialDims.length; dimIndex++) { + var bitIndex = dimIndex % bitsPerByte; + var byteIndex = (dimIndex - bitIndex) / bitsPerByte; + var bitMask = Math.pow(2, bitIndex); + var dim = initialDims[dimIndex]; + var ranges = dim.brush.filter.get(); + if(ranges.length < 2) continue; // bail if the bounding box based filter is sufficient + + var prevEnd = expandedPixelRange(dim, ranges[0])[1]; + for(var ri = 1; ri < ranges.length; ri++) { + var nextRange = expandedPixelRange(dim, ranges[ri]); + for(var pi = prevEnd + 1; pi < nextRange[0]; pi++) { + mask[pi * channelCount + byteIndex] &= ~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: [channelCount, 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: lims[0][0], + loB: lims[0][1], + loC: lims[0][2], + loD: lims[0][3], + hiA: lims[1][0], + hiB: lims[1][1], + hiC: lims[1][2], + hiD: lims[1][3] }; } function renderGLParcoords(panels, setChanged, clearOnly) { - + var panelCount = panels.length; var I; var leftmost, rightmost, lowestX = Infinity, highestX = -Infinity; @@ -126124,8 +127427,9 @@ var _$lines_834 = function(canvasGL, d, scatter) { if(panelCount === 0) { // clear canvas here, as the panel iteration below will not enter the loop body - clear(regl, 0, 0, canvasWidth, canvasHeight); + clear(regl, 0, 0, model.canvasWidth, model.canvasHeight); } + var constraints = context ? {} : makeConstraints(); for(I = 0; I < panelCount; I++) { var panel = panels[I]; @@ -126140,9 +127444,9 @@ var _$lines_834 = function(canvasGL, d, scatter) { var xTo = x + panelSizeX; if(setChanged || !previousAxisOrder[i] || previousAxisOrder[i][0] !== x || previousAxisOrder[i][1] !== xTo) { previousAxisOrder[i] = [x, xTo]; - var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, scatter || dim1.scatter ? 1 : 0, I, leftmost, rightmost); + var item = makeItem(i, ii, x, y, panelSizeX, panelSizeY, dim1.crossfilterDimensionIndex, I, leftmost, rightmost, constraints); renderState.clearOnly = clearOnly; - renderBlock(regl, glAes, renderState, setChanged ? lines.blockLineCount : sampleCount, sampleCount, item); + renderBlock(regl, glAes, renderState, setChanged ? model.lines.blockLineCount : sampleCount, sampleCount, item); } } } @@ -126173,6 +127477,8 @@ var _$lines_834 = function(canvasGL, d, scatter) { function destroy() { canvasGL.style['pointer-events'] = 'none'; paletteTexture.destroy(); + if(maskTexture) maskTexture.destroy(); + for(var k in attributes) attributes[k].destroy(); } return { @@ -126180,7 +127486,8 @@ var _$lines_834 = function(canvasGL, d, scatter) { render: renderGLParcoords, readPixel: readPixel, readPixels: readPixels, - destroy: destroy + destroy: destroy, + update: update }; }; @@ -126194,21 +127501,23 @@ var _$lines_834 = function(canvasGL, d, scatter) { 'use strict'; -/* removed: var _$lines_834 = require('./lines'); */; -/* removed: var _$constants_831 = require('./constants'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -var keyFun = _$gup_536.keyFun; -var __repeat_835 = _$gup_536.repeat; -var unwrap = _$gup_536.unwrap; +/* removed: var _$lines_899 = require('./lines'); */; +/* removed: var _$constants_896 = require('./constants'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$gup_598 = require('../../lib/gup'); */; +var __keyFun_900 = _$gup_598.keyFun; +var __repeat_900 = _$gup_598.repeat; +var unwrap = _$gup_598.unwrap; +/* removed: var _$axisbrush_892 = require('./axisbrush'); */; -function visible(dimension) {return !('visible' in dimension) || dimension.visible;} +function visible(dimension) { return !('visible' in dimension) || dimension.visible; } function dimensionExtent(dimension) { - var lo = dimension.range ? dimension.range[0] : _$lib_539.aggNums(Math.min, null, dimension.values, dimension._length); - var hi = dimension.range ? dimension.range[1] : _$lib_539.aggNums(Math.max, null, dimension.values, dimension._length); + var lo = dimension.range ? dimension.range[0] : _$lib_601.aggNums(Math.min, null, dimension.values, dimension._length); + var hi = dimension.range ? dimension.range[1] : _$lib_601.aggNums(Math.max, null, dimension.values, dimension._length); if(isNaN(lo) || !isFinite(lo)) { lo = 0; @@ -126220,10 +127529,7 @@ function dimensionExtent(dimension) { // avoid a degenerate (zero-width) domain if(lo === hi) { - if(lo === void(0)) { - lo = 0; - hi = 1; - } else if(lo === 0) { + if(lo === 0) { // no use to multiplying zero, so add/subtract in this case lo -= 1; hi += 1; @@ -126237,68 +127543,63 @@ function dimensionExtent(dimension) { return [lo, hi]; } -function ordinalScaleSnap(scale, v) { - var i, a, prevDiff, prevValue, diff; - for(i = 0, a = scale.range(), prevDiff = Infinity, prevValue = a[0], diff; i < a.length; i++) { - if((diff = Math.abs(a[i] - v)) > prevDiff) { - return prevValue; - } - prevDiff = diff; - prevValue = a[i]; - } - return a[a.length - 1]; -} - function toText(formatter, texts) { - return function(v, i) { - if(texts) { + if(texts) { + return function(v, i) { var text = texts[i]; - if(text === null || text === undefined) { - return formatter(v); - } else { - return text; - } - } else { - return formatter(v); - } - }; + if(text === null || text === undefined) return formatter(v); + return text; + }; + } + return formatter; } -function domainScale(height, padding, dimension) { +function domainScale(height, padding, dimension, tickvals, ticktext) { var extent = dimensionExtent(dimension); - var texts = dimension.ticktext; - return dimension.tickvals ? - _$d3_127.scale.ordinal() - .domain(dimension.tickvals.map(toText(_$d3_127.format(dimension.tickformat), texts))) - .range(dimension.tickvals - .map(function(d) {return (d - extent[0]) / (extent[1] - extent[0]);}) - .map(function(d) {return (height - padding + d * (padding - (height - padding)));})) : - _$d3_127.scale.linear() - .domain(extent) - .range([height - padding, padding]); + if(tickvals) { + return _$d3_130.scale.ordinal() + .domain(tickvals.map(toText(_$d3_130.format(dimension.tickformat), ticktext))) + .range(tickvals + .map(function(d) { + var unitVal = (d - extent[0]) / (extent[1] - extent[0]); + return (height - padding + unitVal * (2 * padding - height)); + }) + ); + } + return _$d3_130.scale.linear() + .domain(extent) + .range([height - padding, padding]); } -function unitScale(height, padding) {return _$d3_127.scale.linear().range([height - padding, padding]);} -function domainToUnitScale(dimension) {return _$d3_127.scale.linear().domain(dimensionExtent(dimension));} +function unitToPaddedPx(height, padding) { return _$d3_130.scale.linear().range([padding, height - padding]); } + +function domainToPaddedUnitScale(dimension, padFraction) { + return _$d3_130.scale.linear() + .domain(dimensionExtent(dimension)) + .range([padFraction, 1 - padFraction]); +} function ordinalScale(dimension) { + if(!dimension.tickvals) return; + var extent = dimensionExtent(dimension); - return dimension.tickvals && _$d3_127.scale.ordinal() - .domain(dimension.tickvals) - .range(dimension.tickvals.map(function(d) {return (d - extent[0]) / (extent[1] - extent[0]);})); + return _$d3_130.scale.ordinal() + .domain(dimension.tickvals) + .range(dimension.tickvals.map(function(d) { + return (d - extent[0]) / (extent[1] - extent[0]); + })); } function unitToColorScale(cscale) { - var colorStops = cscale.map(function(d) {return d[0];}); - var colorStrings = cscale.map(function(d) {return d[1];}); - var colorTuples = colorStrings.map(function(c) {return _$d3_127.rgb(c);}); - var prop = function(n) {return function(o) {return o[n];};}; + var colorStops = cscale.map(function(d) { return d[0]; }); + var colorTuples = cscale.map(function(d) { return _$d3_130.rgb(d[1]); }); + var prop = function(n) { return function(o) { return o[n]; }; }; // We can't use d3 color interpolation as we may have non-uniform color palette raster // (various color stop distances). var polylinearUnitScales = 'rgb'.split('').map(function(key) { - return _$d3_127.scale.linear() + return _$d3_130.scale.linear() .clamp(true) .domain(colorStops) .range(colorTuples.map(prop(key))); @@ -126311,6 +127612,12 @@ function unitToColorScale(cscale) { }; } +function someFiltersActive(view) { + return view.dimensions.some(function(p) { + return p.brush.filterSpecified; + }); +} + function model(layout, d, i) { var cd0 = unwrap(d), trace = cd0.trace, @@ -126324,14 +127631,14 @@ function model(layout, d, i) { tickFont = trace.tickfont, rangeFont = trace.rangefont; - var lines = _$lib_539.extendDeep({}, line, { - color: lineColor.map(domainToUnitScale({ + var lines = _$lib_601.extendDeepNoArrays({}, line, { + color: lineColor.map(_$d3_130.scale.linear().domain(dimensionExtent({ values: lineColor, range: [line.cmin, line.cmax], _length: trace._commonLength - })), - blockLineCount: _$constants_831.blockLineCount, - canvasOverdrag: _$constants_831.overdrag * _$constants_831.canvasPixelRatio + }))), + blockLineCount: _$constants_896.blockLineCount, + canvasOverdrag: _$constants_896.overdrag * _$constants_896.canvasPixelRatio }); var groupWidth = Math.floor(width * (domain.x[1] - domain.x[0])); @@ -126345,7 +127652,7 @@ function model(layout, d, i) { key: i, colCount: dimensions.filter(visible).length, dimensions: dimensions, - tickDistance: _$constants_831.tickDistance, + tickDistance: _$constants_896.tickDistance, unitToColor: unitToColorScale(cscale), lines: lines, labelFont: labelFont, @@ -126357,15 +127664,15 @@ function model(layout, d, i) { translateX: domain.x[0] * width, translateY: layout.height - domain.y[1] * layout.height, pad: pad, - canvasWidth: rowContentWidth * _$constants_831.canvasPixelRatio + 2 * lines.canvasOverdrag, - canvasHeight: rowHeight * _$constants_831.canvasPixelRatio, + canvasWidth: rowContentWidth * _$constants_896.canvasPixelRatio + 2 * lines.canvasOverdrag, + canvasHeight: rowHeight * _$constants_896.canvasPixelRatio, width: rowContentWidth, height: rowHeight, - canvasPixelRatio: _$constants_831.canvasPixelRatio + canvasPixelRatio: _$constants_896.canvasPixelRatio }; } -function viewModel(model) { +function viewModel(state, callbacks, model) { var width = model.width; var height = model.height; @@ -126374,53 +127681,128 @@ function viewModel(model) { var xScale = function(d) {return width * d / Math.max(1, model.colCount - 1);}; - var unitPad = _$constants_831.verticalPadding / (height * canvasPixelRatio); - var unitPadScale = (1 - 2 * unitPad); - var paddedUnitScale = function(d) {return unitPad + unitPadScale * d;}; + var unitPad = _$constants_896.verticalPadding / height; + var _unitToPaddedPx = unitToPaddedPx(height, _$constants_896.verticalPadding); var viewModel = { key: model.key, xScale: xScale, - model: model + model: model, + inBrushDrag: false // consider factoring it out and putting it in a centralized global-ish gesture state object }; var uniqueKeys = {}; viewModel.dimensions = dimensions.filter(visible).map(function(dimension, i) { - var domainToUnit = domainToUnitScale(dimension); + var domainToPaddedUnit = domainToPaddedUnitScale(dimension, unitPad); var foundKey = uniqueKeys[dimension.label]; uniqueKeys[dimension.label] = (foundKey || 0) + 1; var key = dimension.label + (foundKey ? '__' + foundKey : ''); + var specifiedConstraint = dimension.constraintrange; + var filterRangeSpecified = specifiedConstraint && specifiedConstraint.length; + if(filterRangeSpecified && !Array.isArray(specifiedConstraint[0])) { + specifiedConstraint = [specifiedConstraint]; + } + var filterRange = filterRangeSpecified ? + specifiedConstraint.map(function(d) { return d.map(domainToPaddedUnit); }) : + [[0, 1]]; + var brushMove = function() { + var p = viewModel; + p.focusLayer && p.focusLayer.render(p.panels, true); + var filtersActive = someFiltersActive(p); + if(!state.contextShown() && filtersActive) { + p.contextLayer && p.contextLayer.render(p.panels, true); + state.contextShown(true); + } else if(state.contextShown() && !filtersActive) { + p.contextLayer && p.contextLayer.render(p.panels, true, true); + state.contextShown(false); + } + }; var truncatedValues = dimension.values; if(truncatedValues.length > dimension._length) { truncatedValues = truncatedValues.slice(0, dimension._length); } + var tickvals = dimension.tickvals; + var ticktext; + function makeTickItem(v, i) { return {val: v, text: ticktext[i]}; } + function sortTickItem(a, b) { return a.val - b.val; } + if(Array.isArray(tickvals) && tickvals.length) { + ticktext = dimension.ticktext; + + // ensure ticktext and tickvals have same length + if(!Array.isArray(ticktext) || !ticktext.length) { + ticktext = tickvals.map(_$d3_130.format(dimension.tickformat)); + } + else if(ticktext.length > tickvals.length) { + ticktext = ticktext.slice(0, tickvals.length); + } + else if(tickvals.length > ticktext.length) { + tickvals = tickvals.slice(0, ticktext.length); + } + + // check if we need to sort tickvals/ticktext + for(var j = 1; j < tickvals.length; j++) { + if(tickvals[j] < tickvals[j - 1]) { + var tickItems = tickvals.map(makeTickItem).sort(sortTickItem); + for(var k = 0; k < tickvals.length; k++) { + tickvals[k] = tickItems[k].val; + ticktext[k] = tickItems[k].text; + } + break; + } + } + } + else tickvals = undefined; + return { key: key, label: dimension.label, tickFormat: dimension.tickformat, - tickvals: dimension.tickvals, - ticktext: dimension.ticktext, - ordinal: !!dimension.tickvals, - scatter: _$constants_831.scatter || dimension.scatter, + tickvals: tickvals, + ticktext: ticktext, + ordinal: !!tickvals, + multiselect: dimension.multiselect, xIndex: i, crossfilterDimensionIndex: i, visibleIndex: dimension._index, height: height, values: truncatedValues, - paddedUnitValues: truncatedValues.map(domainToUnit).map(paddedUnitScale), + paddedUnitValues: truncatedValues.map(domainToPaddedUnit), + unitTickvals: tickvals && tickvals.map(domainToPaddedUnit), xScale: xScale, x: xScale(i), canvasX: xScale(i) * canvasPixelRatio, - unitScale: unitScale(height, _$constants_831.verticalPadding), - domainScale: domainScale(height, _$constants_831.verticalPadding, dimension), + unitToPaddedPx: _unitToPaddedPx, + domainScale: domainScale(height, _$constants_896.verticalPadding, dimension, tickvals, ticktext), ordinalScale: ordinalScale(dimension), - domainToUnitScale: domainToUnit, - filter: dimension.constraintrange ? dimension.constraintrange.map(domainToUnit) : [0, 1], parent: viewModel, - model: model + model: model, + brush: _$axisbrush_892.makeBrush( + state, + filterRangeSpecified, + filterRange, + function() { + state.linePickActive(false); + }, + brushMove, + function(f) { + var p = viewModel; + p.focusLayer.render(p.panels, true); + p.pickLayer && p.pickLayer.render(p.panels, true); + state.linePickActive(true); + if(callbacks && callbacks.filterChanged) { + var invScale = domainToPaddedUnit.invert; + + // update gd.data as if a Plotly.restyle were fired + var newRanges = f.map(function(r) { + return r.map(invScale).sort(_$lib_601.sorterAsc); + }).sort(function(a, b) { return a[0] - b[0]; }); + callbacks.filterChanged(p.key, dimension._index, newRanges); + } + } + ) }; }); @@ -126429,61 +127811,32 @@ function viewModel(model) { function styleExtentTexts(selection) { selection - .classed(_$constants_831.cn.axisExtentText, true) + .classed(_$constants_896.cn.axisExtentText, true) .attr('text-anchor', 'middle') .style('cursor', 'default') .style('user-select', 'none'); } -var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) { - var domainBrushing = false; +function parcoordsInteractionState() { var linePickActive = true; + var contextShown = false; + return { + linePickActive: function(val) {return arguments.length ? linePickActive = !!val : linePickActive;}, + contextShown: function(val) {return arguments.length ? contextShown = !!val : contextShown;} + }; +} - function enterSvgDefs(root) { - var defs = root.selectAll('defs') - .data(__repeat_835, keyFun); - - defs.enter() - .append('defs'); - - var filterBarPattern = defs.selectAll('#' + _$constants_831.id.filterBarPattern) - .data(__repeat_835, keyFun); - - filterBarPattern.enter() - .append('pattern') - .attr('id', _$constants_831.id.filterBarPattern) - .attr('patternUnits', 'userSpaceOnUse'); - - filterBarPattern - .attr('x', -_$constants_831.bar.width) - .attr('width', _$constants_831.bar.capturewidth) - .attr('height', function(d) {return d.model.height;}); - - var filterBarPatternGlyph = filterBarPattern.selectAll('rect') - .data(__repeat_835, keyFun); - - filterBarPatternGlyph.enter() - .append('rect') - .attr('shape-rendering', 'crispEdges'); +var _$parcoords_900 = function(root, svg, parcoordsLineLayers, styledData, layout, callbacks) { - filterBarPatternGlyph - .attr('height', function(d) {return d.model.height;}) - .attr('width', _$constants_831.bar.width) - .attr('x', _$constants_831.bar.width / 2) - .attr('fill', _$constants_831.bar.fillcolor) - .attr('fill-opacity', _$constants_831.bar.fillopacity) - .attr('stroke', _$constants_831.bar.strokecolor) - .attr('stroke-opacity', _$constants_831.bar.strokeopacity) - .attr('stroke-width', _$constants_831.bar.strokewidth); - } + var state = parcoordsInteractionState(); var vm = styledData .filter(function(d) { return unwrap(d).trace.visible; }) .map(model.bind(0, layout)) - .map(viewModel); + .map(viewModel.bind(0, state, callbacks)); parcoordsLineLayers.each(function(d, i) { - return _$lib_539.extendFlat(d, vm[i]); + return _$lib_601.extendFlat(d, vm[i]); }); var parcoordsLineLayer = parcoordsLineLayers.selectAll('.gl-canvas') @@ -126493,21 +127846,19 @@ var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layou d.model = d.viewModel ? d.viewModel.model : null; }); - var tweakables = {renderers: [], dimensions: []}; - var lastHovered = null; - parcoordsLineLayer - .filter(function(d) { - return d.pick; - }) + var pickLayer = parcoordsLineLayer.filter(function(d) {return d.pick;}); + + // emit hover / unhover event + pickLayer .style('pointer-events', 'auto') .on('mousemove', function(d) { - if(linePickActive && d.lineLayer && callbacks && callbacks.hover) { - var event = _$d3_127.event; + if(state.linePickActive() && d.lineLayer && callbacks && callbacks.hover) { + var event = _$d3_130.event; var cw = this.width; var ch = this.height; - var pointer = _$d3_127.mouse(this); + var pointer = _$d3_130.mouse(this); var x = pointer[0]; var y = pointer[1]; @@ -126541,193 +127892,145 @@ var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layou .style('opacity', function(d) {return d.pick ? 0.01 : 1;}); svg.style('background', 'rgba(255, 255, 255, 0)'); - var parcoordsControlOverlay = svg.selectAll('.' + _$constants_831.cn.parcoords) - .data(vm, keyFun); + var parcoordsControlOverlay = svg.selectAll('.' + _$constants_896.cn.parcoords) + .data(vm, __keyFun_900); parcoordsControlOverlay.exit().remove(); parcoordsControlOverlay.enter() .append('g') - .classed(_$constants_831.cn.parcoords, true) - .attr('overflow', 'visible') - .style('box-sizing', 'content-box') - .style('position', 'absolute') - .style('left', 0) - .style('overflow', 'visible') + .classed(_$constants_896.cn.parcoords, true) .style('shape-rendering', 'crispEdges') - .style('pointer-events', 'none') - .call(enterSvgDefs); + .style('pointer-events', 'none'); - parcoordsControlOverlay - .attr('width', function(d) {return d.model.width + d.model.pad.l + d.model.pad.r;}) - .attr('height', function(d) {return d.model.height + d.model.pad.t + d.model.pad.b;}) - .attr('transform', function(d) { - return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')'; - }); + parcoordsControlOverlay.attr('transform', function(d) { + return 'translate(' + d.model.translateX + ',' + d.model.translateY + ')'; + }); - var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + _$constants_831.cn.parcoordsControlView) - .data(__repeat_835, keyFun); + var parcoordsControlView = parcoordsControlOverlay.selectAll('.' + _$constants_896.cn.parcoordsControlView) + .data(__repeat_900, __keyFun_900); parcoordsControlView.enter() .append('g') - .classed(_$constants_831.cn.parcoordsControlView, true) - .style('box-sizing', 'content-box'); + .classed(_$constants_896.cn.parcoordsControlView, true); - parcoordsControlView - .attr('transform', function(d) {return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')';}); - - var yAxis = parcoordsControlView.selectAll('.' + _$constants_831.cn.yAxis) - .data(function(vm) {return vm.dimensions;}, keyFun); + parcoordsControlView.attr('transform', function(d) { + return 'translate(' + d.model.pad.l + ',' + d.model.pad.t + ')'; + }); - function someFiltersActive(view) { - return view.dimensions.some(function(p) {return p.filter[0] !== 0 || p.filter[1] !== 1;}); - } + var yAxis = parcoordsControlView.selectAll('.' + _$constants_896.cn.yAxis) + .data(function(vm) { return vm.dimensions; }, __keyFun_900); - function updatePanelLayoutParcoords(yAxis, vm) { - var panels = vm.panels || (vm.panels = []); - var yAxes = yAxis.each(function(d) {return d;})[vm.key].map(function(e) {return e.__data__;}); - var panelCount = yAxes.length - 1; - var rowCount = 1; - for(var row = 0; row < rowCount; row++) { - for(var p = 0; p < panelCount; p++) { - var panel = panels[p + row * panelCount] || (panels[p + row * panelCount] = {}); - var dim1 = yAxes[p]; - var dim2 = yAxes[p + 1]; - panel.dim1 = dim1; - panel.dim2 = dim2; - panel.canvasX = dim1.canvasX; - panel.panelSizeX = dim2.canvasX - dim1.canvasX; - panel.panelSizeY = vm.model.canvasHeight / rowCount; - panel.y = row * panel.panelSizeY; - panel.canvasY = vm.model.canvasHeight - panel.y - panel.panelSizeY; - } - } - } - - function updatePanelLayoutScatter(yAxis, vm) { + function updatePanelLayout(yAxis, vm) { var panels = vm.panels || (vm.panels = []); - var yAxes = yAxis.each(function(d) {return d;})[vm.key].map(function(e) {return e.__data__;}); - var panelCount = yAxes.length - 1; - var rowCount = panelCount; - for(var row = 0; row < panelCount; row++) { - for(var p = 0; p < panelCount; p++) { - var panel = panels[p + row * panelCount] || (panels[p + row * panelCount] = {}); - var dim1 = yAxes[p]; - var dim2 = yAxes[p + 1]; - panel.dim1 = yAxes[row + 1]; - panel.dim2 = dim2; - panel.canvasX = dim1.canvasX; - panel.panelSizeX = dim2.canvasX - dim1.canvasX; - panel.panelSizeY = vm.model.canvasHeight / rowCount; - panel.y = row * panel.panelSizeY; - panel.canvasY = vm.model.canvasHeight - panel.y - panel.panelSizeY; - } + var dimData = yAxis.data(); + var panelCount = dimData.length - 1; + for(var p = 0; p < panelCount; p++) { + var panel = panels[p] || (panels[p] = {}); + var dim1 = dimData[p]; + var dim2 = dimData[p + 1]; + panel.dim1 = dim1; + panel.dim2 = dim2; + panel.canvasX = dim1.canvasX; + panel.panelSizeX = dim2.canvasX - dim1.canvasX; + panel.panelSizeY = vm.model.canvasHeight; + panel.y = 0; + panel.canvasY = 0; } } - function updatePanelLayout(yAxis, vm) { - return (_$constants_831.scatter ? updatePanelLayoutScatter : updatePanelLayoutParcoords)(yAxis, vm); - } - yAxis.enter() .append('g') - .classed(_$constants_831.cn.yAxis, true) - .each(function(d) {tweakables.dimensions.push(d);}); + .classed(_$constants_896.cn.yAxis, true); parcoordsControlView.each(function(vm) { updatePanelLayout(yAxis, vm); }); parcoordsLineLayer - .filter(function(d) {return !!d.viewModel;}) .each(function(d) { - d.lineLayer = _$lines_834(this, d, _$constants_831.scatter); - d.viewModel[d.key] = d.lineLayer; - tweakables.renderers.push(function() {d.lineLayer.render(d.viewModel.panels, true);}); - d.lineLayer.render(d.viewModel.panels, !d.context); - }); + if(d.viewModel) { + if(d.lineLayer) d.lineLayer.update(d); + else d.lineLayer = _$lines_899(this, d); - yAxis - .attr('transform', function(d) {return 'translate(' + d.xScale(d.xIndex) + ', 0)';}); + d.viewModel[d.key] = d.lineLayer; + d.lineLayer.render(d.viewModel.panels, !d.context); + } + }); - yAxis - .call(_$d3_127.behavior.drag() - .origin(function(d) {return d;}) - .on('drag', function(d) { - var p = d.parent; - linePickActive = false; - if(domainBrushing) { - return; - } - d.x = Math.max(-_$constants_831.overdrag, Math.min(d.model.width + _$constants_831.overdrag, _$d3_127.event.x)); - d.canvasX = d.x * d.model.canvasPixelRatio; - yAxis - .sort(function(a, b) {return a.x - b.x;}) - .each(function(dd, i) { - dd.xIndex = i; - dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex); - dd.canvasX = dd.x * dd.model.canvasPixelRatio; - }); + yAxis.attr('transform', function(d) { + return 'translate(' + d.xScale(d.xIndex) + ', 0)'; + }); - updatePanelLayout(yAxis, p); + // drag column for reordering columns + yAxis.call(_$d3_130.behavior.drag() + .origin(function(d) { return d; }) + .on('drag', function(d) { + var p = d.parent; + state.linePickActive(false); + d.x = Math.max(-_$constants_896.overdrag, Math.min(d.model.width + _$constants_896.overdrag, _$d3_130.event.x)); + d.canvasX = d.x * d.model.canvasPixelRatio; + yAxis + .sort(function(a, b) { return a.x - b.x; }) + .each(function(dd, i) { + dd.xIndex = i; + dd.x = d === dd ? dd.x : dd.xScale(dd.xIndex); + dd.canvasX = dd.x * dd.model.canvasPixelRatio; + }); - yAxis.filter(function(dd) {return Math.abs(d.xIndex - dd.xIndex) !== 0;}) - .attr('transform', function(d) {return 'translate(' + d.xScale(d.xIndex) + ', 0)';}); - _$d3_127.select(this).attr('transform', 'translate(' + d.x + ', 0)'); - yAxis.each(function(dd, i, ii) {if(ii === d.parent.key) p.dimensions[i] = dd;}); - p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); - p.focusLayer.render && p.focusLayer.render(p.panels); - }) - .on('dragend', function(d) { - var p = d.parent; - if(domainBrushing) { - if(domainBrushing === 'ending') { - domainBrushing = false; - } - return; - } - d.x = d.xScale(d.xIndex); - d.canvasX = d.x * d.model.canvasPixelRatio; - updatePanelLayout(yAxis, p); - _$d3_127.select(this) - .attr('transform', function(d) {return 'translate(' + d.x + ', 0)';}); - p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); - p.focusLayer && p.focusLayer.render(p.panels); - p.pickLayer && p.pickLayer.render(p.panels, true); - linePickActive = true; + updatePanelLayout(yAxis, p); - if(callbacks && callbacks.axesMoved) { - callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;})); - } - }) - ); + yAxis.filter(function(dd) { return Math.abs(d.xIndex - dd.xIndex) !== 0; }) + .attr('transform', function(d) { return 'translate(' + d.xScale(d.xIndex) + ', 0)'; }); + _$d3_130.select(this).attr('transform', 'translate(' + d.x + ', 0)'); + yAxis.each(function(dd, i, ii) { if(ii === d.parent.key) p.dimensions[i] = dd; }); + p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); + p.focusLayer.render && p.focusLayer.render(p.panels); + }) + .on('dragend', function(d) { + var p = d.parent; + d.x = d.xScale(d.xIndex); + d.canvasX = d.x * d.model.canvasPixelRatio; + updatePanelLayout(yAxis, p); + _$d3_130.select(this) + .attr('transform', function(d) { return 'translate(' + d.x + ', 0)'; }); + p.contextLayer && p.contextLayer.render(p.panels, false, !someFiltersActive(p)); + p.focusLayer && p.focusLayer.render(p.panels); + p.pickLayer && p.pickLayer.render(p.panels, true); + state.linePickActive(true); + + if(callbacks && callbacks.axesMoved) { + callbacks.axesMoved(p.key, p.dimensions.map(function(dd) {return dd.crossfilterDimensionIndex;})); + } + }) + ); yAxis.exit() .remove(); - var axisOverlays = yAxis.selectAll('.' + _$constants_831.cn.axisOverlays) - .data(__repeat_835, keyFun); + var axisOverlays = yAxis.selectAll('.' + _$constants_896.cn.axisOverlays) + .data(__repeat_900, __keyFun_900); axisOverlays.enter() .append('g') - .classed(_$constants_831.cn.axisOverlays, true); + .classed(_$constants_896.cn.axisOverlays, true); - axisOverlays.selectAll('.' + _$constants_831.cn.axis).remove(); + axisOverlays.selectAll('.' + _$constants_896.cn.axis).remove(); - var axis = axisOverlays.selectAll('.' + _$constants_831.cn.axis) - .data(__repeat_835, keyFun); + var axis = axisOverlays.selectAll('.' + _$constants_896.cn.axis) + .data(__repeat_900, __keyFun_900); axis.enter() .append('g') - .classed(_$constants_831.cn.axis, true); + .classed(_$constants_896.cn.axis, true); axis .each(function(d) { var wantedTickCount = d.model.height / d.model.tickDistance; var scale = d.domainScale; var sdom = scale.domain(); - _$d3_127.select(this) - .call(_$d3_127.svg.axis() + _$d3_130.select(this) + .call(_$d3_130.svg.axis() .orient('left') .tickSize(4) .outerTickSize(2) @@ -126735,221 +128038,108 @@ var _$parcoords_835 = function(root, svg, parcoordsLineLayers, styledData, layou .tickValues(d.ordinal ? // and this works for ordinal scales sdom : null) - .tickFormat(d.ordinal ? function(d) {return d;} : null) + .tickFormat(d.ordinal ? function(d) { return d; } : null) .scale(scale)); - _$drawing_436.font(axis.selectAll('text'), d.model.tickFont); + _$drawing_498.font(axis.selectAll('text'), d.model.tickFont); }); - axis - .selectAll('.domain, .tick>line') + axis.selectAll('.domain, .tick>line') .attr('fill', 'none') .attr('stroke', 'black') .attr('stroke-opacity', 0.25) .attr('stroke-width', '1px'); - axis - .selectAll('text') + axis.selectAll('text') .style('text-shadow', '1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff') .style('cursor', 'default') .style('user-select', 'none'); - var axisHeading = axisOverlays.selectAll('.' + _$constants_831.cn.axisHeading) - .data(__repeat_835, keyFun); + var axisHeading = axisOverlays.selectAll('.' + _$constants_896.cn.axisHeading) + .data(__repeat_900, __keyFun_900); axisHeading.enter() .append('g') - .classed(_$constants_831.cn.axisHeading, true); + .classed(_$constants_896.cn.axisHeading, true); - var axisTitle = axisHeading.selectAll('.' + _$constants_831.cn.axisTitle) - .data(__repeat_835, keyFun); + var axisTitle = axisHeading.selectAll('.' + _$constants_896.cn.axisTitle) + .data(__repeat_900, __keyFun_900); axisTitle.enter() .append('text') - .classed(_$constants_831.cn.axisTitle, true) + .classed(_$constants_896.cn.axisTitle, true) .attr('text-anchor', 'middle') .style('cursor', 'ew-resize') .style('user-select', 'none') .style('pointer-events', 'auto'); axisTitle - .attr('transform', 'translate(0,' + -_$constants_831.axisTitleOffset + ')') - .text(function(d) {return d.label;}) - .each(function(d) {_$drawing_436.font(axisTitle, d.model.labelFont);}); + .attr('transform', 'translate(0,' + -_$constants_896.axisTitleOffset + ')') + .text(function(d) { return d.label; }) + .each(function(d) { _$drawing_498.font(_$d3_130.select(this), d.model.labelFont); }); - var axisExtent = axisOverlays.selectAll('.' + _$constants_831.cn.axisExtent) - .data(__repeat_835, keyFun); + var axisExtent = axisOverlays.selectAll('.' + _$constants_896.cn.axisExtent) + .data(__repeat_900, __keyFun_900); axisExtent.enter() .append('g') - .classed(_$constants_831.cn.axisExtent, true); + .classed(_$constants_896.cn.axisExtent, true); - var axisExtentTop = axisExtent.selectAll('.' + _$constants_831.cn.axisExtentTop) - .data(__repeat_835, keyFun); + var axisExtentTop = axisExtent.selectAll('.' + _$constants_896.cn.axisExtentTop) + .data(__repeat_900, __keyFun_900); axisExtentTop.enter() .append('g') - .classed(_$constants_831.cn.axisExtentTop, true); + .classed(_$constants_896.cn.axisExtentTop, true); axisExtentTop - .attr('transform', 'translate(' + 0 + ',' + -_$constants_831.axisExtentOffset + ')'); + .attr('transform', 'translate(' + 0 + ',' + -_$constants_896.axisExtentOffset + ')'); - var axisExtentTopText = axisExtentTop.selectAll('.' + _$constants_831.cn.axisExtentTopText) - .data(__repeat_835, keyFun); + var axisExtentTopText = axisExtentTop.selectAll('.' + _$constants_896.cn.axisExtentTopText) + .data(__repeat_900, __keyFun_900); - function formatExtreme(d) { - return d.ordinal ? function() {return '';} : _$d3_127.format(d.tickFormat); + function extremeText(d, isTop) { + if(d.ordinal) return ''; + var domain = d.domainScale.domain(); + return _$d3_130.format(d.tickFormat)(domain[isTop ? domain.length - 1 : 0]); } axisExtentTopText.enter() .append('text') - .classed(_$constants_831.cn.axisExtentTopText, true) + .classed(_$constants_896.cn.axisExtentTopText, true) .call(styleExtentTexts); axisExtentTopText - .text(function(d) {return formatExtreme(d)(d.domainScale.domain().slice(-1)[0]);}) - .each(function(d) {_$drawing_436.font(axisExtentTopText, d.model.rangeFont);}); + .text(function(d) { return extremeText(d, true); }) + .each(function(d) { _$drawing_498.font(_$d3_130.select(this), d.model.rangeFont); }); - var axisExtentBottom = axisExtent.selectAll('.' + _$constants_831.cn.axisExtentBottom) - .data(__repeat_835, keyFun); + var axisExtentBottom = axisExtent.selectAll('.' + _$constants_896.cn.axisExtentBottom) + .data(__repeat_900, __keyFun_900); axisExtentBottom.enter() .append('g') - .classed(_$constants_831.cn.axisExtentBottom, true); + .classed(_$constants_896.cn.axisExtentBottom, true); axisExtentBottom - .attr('transform', function(d) {return 'translate(' + 0 + ',' + (d.model.height + _$constants_831.axisExtentOffset) + ')';}); + .attr('transform', function(d) { + return 'translate(' + 0 + ',' + (d.model.height + _$constants_896.axisExtentOffset) + ')'; + }); - var axisExtentBottomText = axisExtentBottom.selectAll('.' + _$constants_831.cn.axisExtentBottomText) - .data(__repeat_835, keyFun); + var axisExtentBottomText = axisExtentBottom.selectAll('.' + _$constants_896.cn.axisExtentBottomText) + .data(__repeat_900, __keyFun_900); axisExtentBottomText.enter() .append('text') - .classed(_$constants_831.cn.axisExtentBottomText, true) + .classed(_$constants_896.cn.axisExtentBottomText, true) .attr('dy', '0.75em') .call(styleExtentTexts); axisExtentBottomText - .text(function(d) {return formatExtreme(d)(d.domainScale.domain()[0]);}) - .each(function(d) {_$drawing_436.font(axisExtentBottomText, d.model.rangeFont);}); - - var axisBrush = axisOverlays.selectAll('.' + _$constants_831.cn.axisBrush) - .data(__repeat_835, keyFun); + .text(function(d) { return extremeText(d); }) + .each(function(d) { _$drawing_498.font(_$d3_130.select(this), d.model.rangeFont); }); - var axisBrushEnter = axisBrush.enter() - .append('g') - .classed(_$constants_831.cn.axisBrush, true); - - axisBrush - .each(function(d) { - if(!d.brush) { - d.brush = _$d3_127.svg.brush() - .y(d.unitScale) - .on('brushstart', axisBrushStarted) - .on('brush', axisBrushMoved) - .on('brushend', axisBrushEnded); - if(d.filter[0] !== 0 || d.filter[1] !== 1) { - d.brush.extent(d.filter); - } - _$d3_127.select(this).call(d.brush); - } - }); - - axisBrushEnter - .selectAll('rect') - .attr('x', -_$constants_831.bar.capturewidth / 2) - .attr('width', _$constants_831.bar.capturewidth); - - axisBrushEnter - .selectAll('rect.extent') - .attr('fill', 'url(#' + _$constants_831.id.filterBarPattern + ')') - .style('cursor', 'ns-resize') - .filter(function(d) {return d.filter[0] === 0 && d.filter[1] === 1;}) - .attr('y', -100); // // zero-size rectangle pointer issue workaround - - axisBrushEnter - .selectAll('.resize rect') - .attr('height', _$constants_831.bar.handleheight) - .attr('opacity', 0) - .style('visibility', 'visible'); - - axisBrushEnter - .selectAll('.resize.n rect') - .style('cursor', 'n-resize') - .attr('y', _$constants_831.bar.handleoverlap - _$constants_831.bar.handleheight); - - axisBrushEnter - .selectAll('.resize.s rect') - .style('cursor', 's-resize') - .attr('y', _$constants_831.bar.handleoverlap); - - var justStarted = false; - var contextShown = false; - - function axisBrushStarted() { - justStarted = true; - domainBrushing = true; - } - - function axisBrushMoved(dimension) { - linePickActive = false; - var p = dimension.parent; - var extent = dimension.brush.extent(); - var dimensions = p.dimensions; - var filter = dimensions[dimension.xIndex].filter; - var reset = justStarted && (extent[0] === extent[1]); - if(reset) { - dimension.brush.clear(); - _$d3_127.select(this).select('rect.extent').attr('y', -100); // zero-size rectangle pointer issue workaround - } - var newExtent = reset ? [0, 1] : extent.slice(); - if(newExtent[0] !== filter[0] || newExtent[1] !== filter[1]) { - dimensions[dimension.xIndex].filter = newExtent; - p.focusLayer && p.focusLayer.render(p.panels, true); - var filtersActive = someFiltersActive(p); - if(!contextShown && filtersActive) { - p.contextLayer && p.contextLayer.render(p.panels, true); - contextShown = true; - } else if(contextShown && !filtersActive) { - p.contextLayer && p.contextLayer.render(p.panels, true, true); - contextShown = false; - } - } - justStarted = false; - } - - function axisBrushEnded(dimension) { - var p = dimension.parent; - var extent = dimension.brush.extent(); - var empty = extent[0] === extent[1]; - var dimensions = p.dimensions; - var f = dimensions[dimension.xIndex].filter; - if(!empty && dimension.ordinal) { - f[0] = ordinalScaleSnap(dimension.ordinalScale, f[0]); - f[1] = ordinalScaleSnap(dimension.ordinalScale, f[1]); - if(f[0] === f[1]) { - f[0] = Math.max(0, f[0] - 0.05); - f[1] = Math.min(1, f[1] + 0.05); - } - _$d3_127.select(this).transition().duration(150).call(dimension.brush.extent(f)); - p.focusLayer.render(p.panels, true); - } - p.pickLayer && p.pickLayer.render(p.panels, true); - linePickActive = true; - domainBrushing = 'ending'; - if(callbacks && callbacks.filterChanged) { - var invScale = dimension.domainToUnitScale.invert; - - // update gd.data as if a Plotly.restyle were fired - var newRange = f.map(invScale); - callbacks.filterChanged(p.key, dimension.visibleIndex, newRange); - } - } - - return tweakables; + _$axisbrush_892.ensureAxisBrush(axisOverlays); }; -var _$plot_836 = {}; -(function (global){ /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -126960,27 +128150,16 @@ var _$plot_836 = {}; 'use strict'; -/* removed: var _$parcoords_835 = require('./parcoords'); */; -/* removed: var _$regl_315 = require('regl'); */; +/* removed: var _$parcoords_900 = require('./parcoords'); */; +/* removed: var _$prepareRegl_614 = require('../../lib/prepare_regl'); */; -_$plot_836 = function plot(gd, cdparcoords) { +var _$plot_901 = function plot(gd, cdparcoords) { var fullLayout = gd._fullLayout; var svg = fullLayout._toppaper; var root = fullLayout._paperdiv; var container = fullLayout._glcontainer; - // make sure proper regl instances are created - fullLayout._glcanvas.each(function(d) { - if(d.regl) return; - d.regl = _$regl_315({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio - }); - }); + _$prepareRegl_614(gd); var gdDimensions = {}; var gdDimensionsOriginalOrder = {}; @@ -126992,21 +128171,28 @@ _$plot_836 = function plot(gd, cdparcoords) { gdDimensionsOriginalOrder[i] = gd.data[i].dimensions.slice(); }); - var filterChanged = function(i, originalDimensionIndex, newRange) { + var filterChanged = function(i, originalDimensionIndex, 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 gdDimension = gdDimensionsOriginalOrder[i][originalDimensionIndex]; - var gdConstraintRange = gdDimension.constraintrange; - - if(!gdConstraintRange || gdConstraintRange.length !== 2) { - gdConstraintRange = gdDimension.constraintrange = []; + var newConstraints = newRanges.map(function(r) { return r.slice(); }); + if(!newConstraints.length) { + delete gdDimension.constraintrange; + newConstraints = null; + } + else { + if(newConstraints.length === 1) newConstraints = newConstraints[0]; + gdDimension.constraintrange = newConstraints; + // wrap in another array for restyle event data + newConstraints = [newConstraints]; } - gdConstraintRange[0] = newRange[0]; - gdConstraintRange[1] = newRange[1]; - gd.emit('plotly_restyle'); + var restyleData = {}; + var aStr = 'dimensions[' + originalDimensionIndex + '].constraintrange'; + restyleData[aStr] = newConstraints; + gd.emit('plotly_restyle', [restyleData, [i]]); }; var hover = function(eventData) { @@ -127061,7 +128247,7 @@ _$plot_836 = function plot(gd, cdparcoords) { gd.emit('plotly_restyle'); }; - _$parcoords_835( + _$parcoords_900( root, svg, container, @@ -127084,8 +128270,7 @@ _$plot_836 = function plot(gd, cdparcoords) { }); }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$base_plot_828 = {}; +var _$base_plot_893 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -127096,21 +128281,21 @@ var _$base_plot_828 = {}; 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -var __getModuleCalcData_828 = _$get_data_621.getModuleCalcData; -/* removed: var _$plot_836 = require('./plot'); */; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$d3_130 = require('d3'); */; +var __getModuleCalcData_893 = _$get_data_683.getModuleCalcData; +/* removed: var _$plot_901 = require('./plot'); */; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; var PARCOORDS = 'parcoords'; -_$base_plot_828.name = PARCOORDS; +_$base_plot_893.name = PARCOORDS; -_$base_plot_828.plot = function(gd) { - var calcData = __getModuleCalcData_828(gd.calcdata, PARCOORDS); - if(calcData.length) _$plot_836(gd, calcData); +_$base_plot_893.plot = function(gd) { + var calcData = __getModuleCalcData_893(gd.calcdata, PARCOORDS)[0]; + if(calcData.length) _$plot_901(gd, calcData); }; -_$base_plot_828.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_893.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadParcoords = (oldFullLayout._has && oldFullLayout._has(PARCOORDS)); var hasParcoords = (newFullLayout._has && newFullLayout._has(PARCOORDS)); @@ -127120,9 +128305,9 @@ _$base_plot_828.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -_$base_plot_828.toSVG = function(gd) { +_$base_plot_893.toSVG = function(gd) { var imageRoot = gd._fullLayout._glimages; - var root = _$d3_127.select(gd).selectAll('.svg-container'); + var root = _$d3_130.select(gd).selectAll('.svg-container'); var canvases = root.filter(function(d, i) {return i === root.size() - 1;}) .selectAll('.gl-canvas-context, .gl-canvas-focus'); @@ -127132,7 +128317,7 @@ _$base_plot_828.toSVG = function(gd) { var image = imageRoot.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, preserveAspectRatio: 'none', x: 0, @@ -127149,7 +128334,7 @@ _$base_plot_828.toSVG = function(gd) { // on a subsequent interaction. // Firefox works fine without this workaround window.setTimeout(function() { - _$d3_127.selectAll('#filterBarPattern') + _$d3_130.selectAll('#filterBarPattern') .attr('id', 'filterBarPattern'); }, 60); }; @@ -127164,21 +128349,21 @@ _$base_plot_828.toSVG = function(gd) { 'use strict'; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __wrap_829 = _$gup_536.wrap; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __wrap_894 = _$gup_598.wrap; -var _$calc_829 = function calc(gd, trace) { - var cs = !!trace.line.colorscale && _$lib_539.isArrayOrTypedArray(trace.line.color); +var _$calc_894 = function calc(gd, trace) { + var cs = !!trace.line.colorscale && _$lib_601.isArrayOrTypedArray(trace.line.color); var color = cs ? trace.line.color : constHalf(trace._commonLength); var cscale = cs ? trace.line.colorscale : [[0, trace.line.color], [1, trace.line.color]]; - if(_$hasColorscale_425(trace, 'line')) { - _$calc_418(trace, color, 'line', 'c'); + if(_$hasColorscale_487(trace, 'line')) { + _$calc_480(trace, color, 'line', 'c'); } - return __wrap_829({ + return __wrap_894({ lineColor: color, cscale: cscale }); @@ -127203,15 +128388,15 @@ function constHalf(len) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_830 = function colorbar(gd, cd) { +var _$colorbar_895 = function colorbar(gd, cd) { var trace = cd[0].trace, line = trace.line, cbId = 'cb' + trace.uid; @@ -127219,7 +128404,7 @@ var _$colorbar_830 = function colorbar(gd, cd) { gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if((line === undefined) || !line.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } @@ -127227,12 +128412,12 @@ var _$colorbar_830 = function colorbar(gd, cd) { cmin = line.cmin, cmax = line.cmax; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( line.colorscale, cmin, cmax @@ -127255,20 +128440,21 @@ var _$colorbar_830 = function colorbar(gd, cd) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_827 = require('./attributes'); */; -/* removed: var _$hasColorscale_425 = require('../../components/colorscale/has_colorscale'); */; -/* removed: var _$colorScaleDefaults_421 = require('../../components/colorscale/defaults'); */; -var maxDimensionCount = _$constants_831.maxDimensionCount; -var __handleDomainDefaults_832 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_891 = require('./attributes'); */; +/* removed: var _$hasColorscale_487 = require('../../components/colorscale/has_colorscale'); */; +/* removed: var _$colorScaleDefaults_483 = require('../../components/colorscale/defaults'); */; +var maxDimensionCount = _$constants_896.maxDimensionCount; +var __handleDomainDefaults_897 = _$domain_672.defaults; +/* removed: var _$axisbrush_892 = require('./axisbrush'); */; -function __handleLineDefaults_832(traceIn, traceOut, defaultColor, layout, coerce) { +function __handleLineDefaults_897(traceIn, traceOut, defaultColor, layout, coerce) { var lineColor = coerce('line.color', defaultColor); - if(_$hasColorscale_425(traceIn, 'line') && _$lib_539.isArrayOrTypedArray(lineColor)) { + if(_$hasColorscale_487(traceIn, 'line') && _$lib_601.isArrayOrTypedArray(lineColor)) { if(lineColor.length) { coerce('line.colorscale'); - _$colorScaleDefaults_421(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); + _$colorScaleDefaults_483(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'}); // TODO: I think it would be better to keep showing lines beyond the last line color // but I'm not sure what color to give these lines - probably black or white // depending on the background color? @@ -127288,19 +128474,19 @@ function dimensionsDefaults(traceIn, traceOut) { var commonLength = Infinity; if(dimensionsIn.length > maxDimensionCount) { - _$lib_539.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment'); + _$lib_601.log('parcoords traces support up to ' + maxDimensionCount + ' dimensions at the moment'); dimensionsIn.splice(maxDimensionCount); } function coerce(attr, dflt) { - return _$lib_539.coerce(dimensionIn, dimensionOut, _$attributes_827.dimensions, attr, dflt); + return _$lib_601.coerce(dimensionIn, dimensionOut, _$attributes_891.dimensions, attr, dflt); } for(i = 0; i < dimensionsIn.length; i++) { dimensionIn = dimensionsIn[i]; dimensionOut = {}; - if(!_$lib_539.isPlainObject(dimensionIn)) { + if(!_$lib_601.isPlainObject(dimensionIn)) { continue; } @@ -127316,7 +128502,12 @@ function dimensionsDefaults(traceIn, traceOut) { coerce('ticktext'); coerce('tickformat'); coerce('range'); - coerce('constraintrange'); + + coerce('multiselect'); + var constraintRange = coerce('constraintrange'); + if(constraintRange) { + dimensionOut.constraintrange = _$axisbrush_892.cleanRanges(constraintRange, dimensionOut); + } commonLength = Math.min(commonLength, values.length); } @@ -127330,16 +128521,16 @@ function dimensionsDefaults(traceIn, traceOut) { return dimensionsOut; } -var _$supplyDefaults_832 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_897 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_827, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_891, attr, dflt); } var dimensions = dimensionsDefaults(traceIn, traceOut); - __handleLineDefaults_832(traceIn, traceOut, defaultColor, layout, coerce); + __handleLineDefaults_897(traceIn, traceOut, defaultColor, layout, coerce); - __handleDomainDefaults_832(traceOut, layout, coerce); + __handleDomainDefaults_897(traceOut, layout, coerce); if(!Array.isArray(dimensions) || !dimensions.length) { traceOut.visible = false; @@ -127360,9 +128551,9 @@ var _$supplyDefaults_832 = function supplyDefaults(traceIn, traceOut, defaultCol color: layout.font.color }; - _$lib_539.coerceFont(coerce, 'labelfont', fontDflt); - _$lib_539.coerceFont(coerce, 'tickfont', fontDflt); - _$lib_539.coerceFont(coerce, 'rangefont', fontDflt); + _$lib_601.coerceFont(coerce, 'labelfont', fontDflt); + _$lib_601.coerceFont(coerce, 'tickfont', fontDflt); + _$lib_601.coerceFont(coerce, 'rangefont', fontDflt); }; /** @@ -127377,21 +128568,21 @@ var _$supplyDefaults_832 = function supplyDefaults(traceIn, traceOut, defaultCol var Parcoords = {}; -Parcoords.attributes = _$attributes_827; -Parcoords.supplyDefaults = _$supplyDefaults_832; -Parcoords.calc = _$calc_829; -Parcoords.plot = _$plot_836; -Parcoords.colorbar = _$colorbar_830; +Parcoords.attributes = _$attributes_891; +Parcoords.supplyDefaults = _$supplyDefaults_897; +Parcoords.calc = _$calc_894; +Parcoords.plot = _$plot_901; +Parcoords.colorbar = _$colorbar_895; Parcoords.moduleType = 'trace'; Parcoords.name = 'parcoords'; -Parcoords.basePlotModule = _$base_plot_828; +Parcoords.basePlotModule = _$base_plot_893; Parcoords.categories = ['gl', 'regl', 'noOpacity']; Parcoords.meta = { }; -var _$Parcoords_833 = Parcoords; +var _$Parcoords_898 = Parcoords; /** * Copyright 2012-2018, Plotly, Inc. @@ -127403,7 +128594,7 @@ var _$Parcoords_833 = Parcoords; 'use strict'; -var _$parcoords_23 = _$Parcoords_833; +var _$parcoords_23 = _$Parcoords_898; /** * Copyright 2012-2018, Plotly, Inc. @@ -127415,20 +128606,20 @@ var _$parcoords_23 = _$Parcoords_833; 'use strict'; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -var __domainAttrs_837 = _$domain_610.attributes; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +var __domainAttrs_902 = _$domain_672.attributes; -var __extendFlat_837 = _$extend_528.extendFlat; +var __extendFlat_902 = _$extend_590.extendFlat; -var __textFontAttrs_837 = _$font_attributes_611({ +var __textFontAttrs_902 = _$font_attributes_673({ editType: 'calc', colorEditType: 'style', }); -var _$attributes_837 = { +var _$attributes_902 = { labels: { valType: 'data_array', editType: 'calc', @@ -127467,7 +128658,7 @@ var _$attributes_837 = { color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, arrayOk: true, editType: 'style', @@ -127521,7 +128712,7 @@ var _$attributes_837 = { editType: 'calc', }, - hoverinfo: __extendFlat_837({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_902({}, _$attributes_644.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'] }), textposition: { @@ -127534,18 +128725,18 @@ var _$attributes_837 = { }, // TODO make those arrayOk? - textfont: __extendFlat_837({}, __textFontAttrs_837, { + textfont: __extendFlat_902({}, __textFontAttrs_902, { }), - insidetextfont: __extendFlat_837({}, __textFontAttrs_837, { + insidetextfont: __extendFlat_902({}, __textFontAttrs_902, { }), - outsidetextfont: __extendFlat_837({}, __textFontAttrs_837, { + outsidetextfont: __extendFlat_902({}, __textFontAttrs_902, { }), // position and shape - domain: __domainAttrs_837({name: 'pie', trace: true, editType: 'calc'}), + domain: __domainAttrs_902({name: 'pie', trace: true, editType: 'calc'}), hole: { valType: 'number', @@ -127602,7 +128793,7 @@ var _$attributes_837 = { } }; -var _$base_plot_838 = {}; +var _$base_plot_903 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -127613,19 +128804,19 @@ var _$base_plot_838 = {}; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; - +/* removed: var _$registry_731 = require('../../registry'); */; +var __getModuleCalcData_903 = _$get_data_683.getModuleCalcData; -_$base_plot_838.name = 'pie'; +_$base_plot_903.name = 'pie'; -_$base_plot_838.plot = function(gd) { - var Pie = _$registry_668.getModule('pie'); - var cdPie = getCdModule(gd.calcdata, Pie); +_$base_plot_903.plot = function(gd) { + var Pie = _$registry_731.getModule('pie'); + var cdPie = __getModuleCalcData_903(gd.calcdata, Pie)[0]; if(cdPie.length) Pie.plot(gd, cdPie); }; -_$base_plot_838.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_903.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPie = (oldFullLayout._has && oldFullLayout._has('pie')); var hasPie = (newFullLayout._has && newFullLayout._has('pie')); @@ -127634,21 +128825,6 @@ _$base_plot_838.clean = function(newFullData, newFullLayout, oldFullData, oldFul } }; -function getCdModule(calcdata, _module) { - var cdModule = []; - - for(var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - - if((trace._module === _module) && (trace.visible === true)) { - cdModule.push(cd); - } - } - - return cdModule; -} - /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -127659,16 +128835,16 @@ function getCdModule(calcdata, _module) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __isArrayOrTypedArray_839 = _$lib_539.isArrayOrTypedArray; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __isArrayOrTypedArray_904 = _$lib_601.isArrayOrTypedArray; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$helpers_842 = require('./helpers'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$helpers_907 = require('./helpers'); */; -var _$calc_839 = function calc(gd, trace) { +var _$calc_904 = function calc(gd, trace) { var vals = trace.values; - var hasVals = __isArrayOrTypedArray_839(vals) && vals.length; + var hasVals = __isArrayOrTypedArray_904(vals) && vals.length; var labels = trace.labels; var colors = trace.marker.colors || []; var cd = []; @@ -127681,7 +128857,7 @@ var _$calc_839 = function calc(gd, trace) { var i, v, label, hidden, pt; - if(!fullLayout._piecolorway && colorWay !== _$color_411.defaults) { + if(!fullLayout._piecolorway && colorWay !== _$color_473.defaults) { fullLayout._piecolorway = generateDefaultColors(colorWay); } @@ -127695,10 +128871,10 @@ var _$calc_839 = function calc(gd, trace) { function pullColor(color, label) { if(!color) return false; - color = _$tinycolor_352(color); + color = _$tinycolor_414(color); if(!color.isValid()) return false; - color = _$color_411.addOpacity(color, color.getAlpha()); + color = _$color_473.addOpacity(color, color.getAlpha()); if(!colorMap[label]) colorMap[label] = color; return color; @@ -127709,7 +128885,7 @@ var _$calc_839 = function calc(gd, trace) { for(i = 0; i < seriesLen; i++) { if(hasVals) { v = vals[i]; - if(!_$fastIsnumeric_139(v)) continue; + if(!_$fastIsnumeric_196(v)) continue; v = +v; if(v < 0) continue; } @@ -127790,11 +128966,11 @@ var _$calc_839 = function calc(gd, trace) { pt = cd[i]; thisText = hasLabel ? [pt.label] : []; if(hasText) { - var texti = _$helpers_842.getFirstFilled(trace.text, pt.pts); + var texti = _$helpers_907.getFirstFilled(trace.text, pt.pts); if(texti) thisText.push(texti); } - if(hasValue) thisText.push(_$helpers_842.formatPieValue(pt.v, separators)); - if(hasPercent) thisText.push(_$helpers_842.formatPiePercent(pt.v / vTotal, separators)); + if(hasValue) thisText.push(_$helpers_907.formatPieValue(pt.v, separators)); + if(hasPercent) thisText.push(_$helpers_907.formatPiePercent(pt.v / vTotal, separators)); pt.text = thisText.join('
'); } } @@ -127811,7 +128987,7 @@ var pieDefaultColors; function nextDefaultColor(index, pieColorWay) { if(!pieDefaultColors) { // generate this default set on demand (but then it gets saved in the module) - var mainDefaults = _$color_411.defaults; + var mainDefaults = _$color_473.defaults; pieDefaultColors = generateDefaultColors(mainDefaults); } @@ -127825,11 +129001,11 @@ function generateDefaultColors(colorList) { var pieColors = colorList.slice(); for(i = 0; i < colorList.length; i++) { - pieColors.push(_$tinycolor_352(colorList[i]).lighten(20).toHexString()); + pieColors.push(_$tinycolor_414(colorList[i]).lighten(20).toHexString()); } for(i = 0; i < colorList.length; i++) { - pieColors.push(_$tinycolor_352(colorList[i]).darken(20).toHexString()); + pieColors.push(_$tinycolor_414(colorList[i]).darken(20).toHexString()); } return pieColors; @@ -127845,21 +129021,21 @@ function generateDefaultColors(colorList) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_837 = require('./attributes'); */; -var __handleDomainDefaults_840 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_902 = require('./attributes'); */; +var __handleDomainDefaults_905 = _$domain_672.defaults; -var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_905 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_837, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_902, attr, dflt); } - var coerceFont = _$lib_539.coerceFont; + var coerceFont = _$lib_601.coerceFont; var vals = coerce('values'); var labels = coerce('labels'); if(!Array.isArray(labels)) { - if(!_$lib_539.isArrayOrTypedArray(vals) || !vals.length) { + if(!_$lib_601.isArrayOrTypedArray(vals) || !vals.length) { // must have at least one of vals or labels traceOut.visible = false; return; @@ -127894,7 +129070,7 @@ var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultCol } } - __handleDomainDefaults_840(traceOut, layout, coerce); + __handleDomainDefaults_905(traceOut, layout, coerce); coerce('hole'); @@ -127915,7 +129091,7 @@ var _$supplyDefaults_840 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$layout_attributes_844 = { +var _$layout_attributes_909 = { /** * hiddenlabels is the pie chart analog of visible:'legendonly' * but it can contain many labels, and can hide slices @@ -127937,13 +129113,13 @@ var _$layout_attributes_844 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$layout_attributes_844 = require('./layout_attributes'); */; +/* removed: var _$layout_attributes_909 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_845 = function supplyLayoutDefaults(layoutIn, layoutOut) { +var _$supplyLayoutDefaults_910 = function supplyLayoutDefaults(layoutIn, layoutOut) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_844, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_909, attr, dflt); } coerce('hiddenlabels'); }; @@ -127959,13 +129135,13 @@ var _$supplyLayoutDefaults_845 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -var appendArrayMultiPointValues = _$helpers_450.appendArrayMultiPointValues; +var appendArrayMultiPointValues = _$helpers_512.appendArrayMultiPointValues; // Note: like other eventData routines, this creates the data for hover/unhover/click events // but it has a different API and goes through a totally different pathway. // So to ensure it doesn't get misused, it's not attached to the Pie module. -var _$eventData_841 = function eventData(pt, trace) { +var _$eventData_906 = function eventData(pt, trace) { var out = { curveNumber: trace.index, pointNumbers: pt.pts, @@ -128000,17 +129176,18 @@ var _$eventData_841 = function eventData(pt, trace) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$svg_text_utils_562 = require('../../lib/svg_text_utils'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$svg_text_utils_625 = require('../../lib/svg_text_utils'); */; -/* removed: var _$helpers_842 = require('./helpers'); */; -/* removed: var _$eventData_841 = require('./event_data'); */; +/* removed: var _$helpers_907 = require('./helpers'); */; +/* removed: var _$eventData_906 = require('./event_data'); */; -var _$plot_846 = function plot(gd, cdpie) { +var _$plot_911 = function plot(gd, cdpie) { var fullLayout = gd._fullLayout; scalePies(cdpie, fullLayout._size); @@ -128027,14 +129204,14 @@ var _$plot_846 = function plot(gd, cdpie) { pieGroups.order(); pieGroups.each(function(cd) { - var pieGroup = _$d3_127.select(this); + var pieGroup = _$d3_130.select(this); var cd0 = cd[0]; var trace = cd0.trace; setCoords(cd); pieGroup.each(function() { - var slices = _$d3_127.select(this).selectAll('g.slice').data(cd); + var slices = _$d3_130.select(this).selectAll('g.slice').data(cd); slices.enter().append('g') .classed('slice', true); @@ -128048,7 +129225,7 @@ var _$plot_846 = function plot(gd, cdpie) { slices.each(function(pt) { if(pt.hidden) { - _$d3_127.select(this).selectAll('path,g').remove(); + _$d3_130.select(this).selectAll('path,g').remove(); return; } @@ -128060,7 +129237,7 @@ var _$plot_846 = function plot(gd, cdpie) { var cx = cd0.cx; var cy = cd0.cy; - var sliceTop = _$d3_127.select(this); + var sliceTop = _$d3_130.select(this); var slicePath = sliceTop.selectAll('path.surface').data([pt]); // hover state vars @@ -128086,8 +129263,8 @@ var _$plot_846 = function plot(gd, cdpie) { // and call castHoverinfo on that. // TODO: do we want to have Fx.castHoverinfo somehow handle this? // it already takes an array for index, for 2D, so this seems tricky. - hoverinfo = _$fx_453.castHoverinfo({ - hoverinfo: [_$helpers_842.castOption(hoverinfo, pt.pts)], + hoverinfo = _$fx_515.castHoverinfo({ + hoverinfo: [_$helpers_907.castOption(hoverinfo, pt.pts)], _module: trace._module }, fullLayout2, 0); } @@ -128105,27 +129282,27 @@ var _$plot_846 = function plot(gd, cdpie) { if(hoverinfo.indexOf('label') !== -1) thisText.push(pt.label); if(hoverinfo.indexOf('text') !== -1) { - var texti = _$helpers_842.castOption(trace2.hovertext || trace2.text, pt.pts); + var texti = _$helpers_907.castOption(trace2.hovertext || trace2.text, pt.pts); if(texti) thisText.push(texti); } - if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_842.formatPieValue(pt.v, separators)); - if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_842.formatPiePercent(pt.v / cd0.vTotal, separators)); + if(hoverinfo.indexOf('value') !== -1) thisText.push(_$helpers_907.formatPieValue(pt.v, separators)); + if(hoverinfo.indexOf('percent') !== -1) thisText.push(_$helpers_907.formatPiePercent(pt.v / cd0.vTotal, separators)); var hoverLabel = trace.hoverlabel; var hoverFont = hoverLabel.font; - _$fx_453.loneHover({ + _$fx_515.loneHover({ x0: hoverCenterX - rInscribed * cd0.r, x1: hoverCenterX + rInscribed * cd0.r, y: hoverCenterY, text: thisText.join('
'), name: hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined, idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right', - color: _$helpers_842.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, - borderColor: _$helpers_842.castOption(hoverLabel.bordercolor, pt.pts), - fontFamily: _$helpers_842.castOption(hoverFont.family, pt.pts), - fontSize: _$helpers_842.castOption(hoverFont.size, pt.pts), - fontColor: _$helpers_842.castOption(hoverFont.color, pt.pts) + color: _$helpers_907.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, + borderColor: _$helpers_907.castOption(hoverLabel.bordercolor, pt.pts), + fontFamily: _$helpers_907.castOption(hoverFont.family, pt.pts), + fontSize: _$helpers_907.castOption(hoverFont.size, pt.pts), + fontColor: _$helpers_907.castOption(hoverFont.color, pt.pts) }, { container: fullLayout2._hoverlayer.node(), outerContainer: fullLayout2._paper.node(), @@ -128136,8 +129313,8 @@ var _$plot_846 = function plot(gd, cdpie) { } gd.emit('plotly_hover', { - points: [_$eventData_841(pt, trace2)], - event: _$d3_127.event + points: [_$eventData_906(pt, trace2)], + event: _$d3_130.event }); hasHoverEvent = true; } @@ -128147,16 +129324,16 @@ var _$plot_846 = function plot(gd, cdpie) { var trace2 = gd._fullData[trace.index]; if(hasHoverEvent) { - evt.originalEvent = _$d3_127.event; + evt.originalEvent = _$d3_130.event; gd.emit('plotly_unhover', { - points: [_$eventData_841(pt, trace2)], - event: _$d3_127.event + points: [_$eventData_906(pt, trace2)], + event: _$d3_130.event }); hasHoverEvent = false; } if(hasHoverLabel) { - _$fx_453.loneUnhover(fullLayout2._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout2._hoverlayer.node()); hasHoverLabel = false; } } @@ -128172,8 +129349,8 @@ var _$plot_846 = function plot(gd, cdpie) { if(gd._dragging || fullLayout2.hovermode === false) return; - gd._hoverdata = [_$eventData_841(pt, trace2)]; - _$fx_453.click(gd, _$d3_127.event); + gd._hoverdata = [_$eventData_906(pt, trace2)]; + _$fx_515.click(gd, _$d3_130.event); } slicePath.enter().append('path') @@ -128188,7 +129365,7 @@ var _$plot_846 = function plot(gd, cdpie) { .on('click', handleClick); if(trace.pull) { - var pull = +_$helpers_842.castOption(trace.pull, pt.pts) || 0; + var pull = +_$helpers_907.castOption(trace.pull, pt.pts) || 0; if(pull > 0) { cx += pull * pt.pxmid[0]; cy += pull * pt.pxmid[1]; @@ -128239,7 +129416,7 @@ var _$plot_846 = function plot(gd, cdpie) { } // add text - var textPosition = _$helpers_842.castOption(trace.textposition, pt.pts); + var textPosition = _$helpers_907.castOption(trace.textposition, pt.pts); var sliceTextGroup = sliceTop.selectAll('g.slicetext') .data(pt.text && (textPosition !== 'none') ? [0] : []); @@ -128248,13 +129425,11 @@ var _$plot_846 = function plot(gd, cdpie) { sliceTextGroup.exit().remove(); sliceTextGroup.each(function() { - var sliceText = _$d3_127.select(this).selectAll('text').data([0]); - - sliceText.enter().append('text') + var sliceText = _$lib_601.ensureSingle(_$d3_130.select(this), 'text', '', function(s) { // prohibit tex interpretation until we can handle // tex and regular text together - .attr('data-notex', 1); - sliceText.exit().remove(); + s.attr('data-notex', 1); + }); sliceText.text(pt.text) .attr({ @@ -128262,12 +129437,12 @@ var _$plot_846 = function plot(gd, cdpie) { transform: '', 'text-anchor': 'middle' }) - .call(_$drawing_436.font, textPosition === 'outside' ? + .call(_$drawing_498.font, textPosition === 'outside' ? trace.outsidetextfont : trace.insidetextfont) - .call(_$svg_text_utils_562.convertToTspans, gd); + .call(_$svg_text_utils_625.convertToTspans, gd); // position the text relative to the slice - var textBB = _$drawing_436.bBox(sliceText.node()); + var textBB = _$drawing_498.bBox(sliceText.node()); var transform; if(textPosition === 'outside') { @@ -128275,10 +129450,10 @@ var _$plot_846 = function plot(gd, cdpie) { } else { transform = transformInsideText(textBB, pt, cd0); if(textPosition === 'auto' && transform.scale < 1) { - sliceText.call(_$drawing_436.font, trace.outsidetextfont); + sliceText.call(_$drawing_498.font, trace.outsidetextfont); if(trace.outsidetextfont.family !== trace.insidetextfont.family || trace.outsidetextfont.size !== trace.insidetextfont.size) { - textBB = _$drawing_436.bBox(sliceText.node()); + textBB = _$drawing_498.bBox(sliceText.node()); } transform = transformOutsideText(textBB, pt); } @@ -128313,7 +129488,7 @@ var _$plot_846 = function plot(gd, cdpie) { slices.each(function(pt) { if(pt.labelExtraX || pt.labelExtraY) { // first move the text to its new location - var sliceTop = _$d3_127.select(this); + var sliceTop = _$d3_130.select(this); var sliceText = sliceTop.select('g.slicetext text'); sliceText.attr('transform', 'translate(' + pt.labelExtraX + ',' + pt.labelExtraY + ')' + @@ -128346,7 +129521,7 @@ var _$plot_846 = function plot(gd, cdpie) { sliceTop.append('path') .classed('textline', true) - .call(_$color_411.stroke, trace.outsidetextfont.color) + .call(_$color_473.stroke, trace.outsidetextfont.color) .attr({ 'stroke-width': Math.min(2, trace.outsidetextfont.size / 8), d: textLinePath, @@ -128365,7 +129540,7 @@ var _$plot_846 = function plot(gd, cdpie) { // it gets the initial draw correct but on redraw it gets confused. setTimeout(function() { pieGroups.selectAll('tspan').each(function() { - var s = _$d3_127.select(this); + var s = _$d3_130.select(this); if(s.attr('dy')) s.attr('dy', s.attr('dy')); }); }, 0); @@ -128485,8 +129660,8 @@ function scootLabels(quadrants, trace) { // overlap can only happen if the other point is pulled more than this one if(otherPt === thisPt || ( - (_$helpers_842.castOption(trace.pull, thisPt.pts) || 0) >= - (_$helpers_842.castOption(trace.pull, otherPt.pts) || 0)) + (_$helpers_907.castOption(trace.pull, thisPt.pts) || 0) >= + (_$helpers_907.castOption(trace.pull, otherPt.pts) || 0)) ) { continue; } @@ -128671,20 +129846,20 @@ function setCoords(cd) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$styleOne_848 = require('./style_one'); */; +/* removed: var _$styleOne_913 = require('./style_one'); */; -var _$style_847 = function style(gd) { +var _$style_912 = function style(gd) { gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) { var cd0 = cd[0]; var trace = cd0.trace; - var traceSelection = _$d3_127.select(this); + var traceSelection = _$d3_130.select(this); traceSelection.style({opacity: trace.opacity}); traceSelection.selectAll('path.surface').each(function(pt) { - _$d3_127.select(this).call(_$styleOne_848, pt, trace); + _$d3_130.select(this).call(_$styleOne_913, pt, trace); }); }); }; @@ -128701,24 +129876,24 @@ var _$style_847 = function style(gd) { var Pie = {}; -Pie.attributes = _$attributes_837; -Pie.supplyDefaults = _$supplyDefaults_840; -Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_845; -Pie.layoutAttributes = _$layout_attributes_844; -Pie.calc = _$calc_839; -Pie.plot = _$plot_846; -Pie.style = _$style_847; -Pie.styleOne = _$styleOne_848; +Pie.attributes = _$attributes_902; +Pie.supplyDefaults = _$supplyDefaults_905; +Pie.supplyLayoutDefaults = _$supplyLayoutDefaults_910; +Pie.layoutAttributes = _$layout_attributes_909; +Pie.calc = _$calc_904; +Pie.plot = _$plot_911; +Pie.style = _$style_912; +Pie.styleOne = _$styleOne_913; Pie.moduleType = 'trace'; Pie.name = 'pie'; -Pie.basePlotModule = _$base_plot_838; +Pie.basePlotModule = _$base_plot_903; Pie.categories = ['pie', 'showLegend']; Pie.meta = { }; -var _$Pie_843 = Pie; +var _$Pie_908 = Pie; /** * Copyright 2012-2018, Plotly, Inc. @@ -128730,7 +129905,7 @@ var _$Pie_843 = Pie; 'use strict'; -var _$pie_24 = _$Pie_843; +var _$pie_24 = _$Pie_908; /** * Copyright 2012-2018, Plotly, Inc. @@ -128742,11 +129917,11 @@ var _$pie_24 = _$Pie_843; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; -var _$attributes_849 = { - x: _$attributes_862.x, - y: _$attributes_862.y, +var _$attributes_914 = { + x: _$attributes_927.x, + y: _$attributes_927.y, xy: { valType: 'data_array', editType: 'calc', @@ -128767,7 +129942,7 @@ var _$attributes_849 = { editType: 'calc', }, - text: _$attributes_862.text, + text: _$attributes_927.text, marker: { color: { valType: 'color', @@ -128833,24 +130008,24 @@ var _$attributes_849 = { } }; -var _$shader_197 = {}; -/* removed: var _$browser_238 = require('glslify') */; +var _$shader_254 = {}; +/* removed: var _$browser_295 = require('glslify') */; -_$shader_197.pointVertex = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]) -_$shader_197.pointFragment = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]) -_$shader_197.pickVertex = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]) -_$shader_197.pickFragment = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]) +_$shader_254.pointVertex = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]) +_$shader_254.pointFragment = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]) +_$shader_254.pickVertex = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]) +_$shader_254.pickFragment = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]) 'use strict' -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$createBuffer_153 = require('gl-buffer') */; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; -/* removed: var _$pool_360 = require('typedarray-pool') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; -/* removed: var _$shader_197 = require('./lib/shader') */; +/* removed: var _$shader_254 = require('./lib/shader') */; -var _$createPointcloud2D_198 = createPointcloud2D +var _$createPointcloud2D_255 = createPointcloud2D function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) { this.plot = plot @@ -128870,9 +130045,9 @@ function Pointcloud2D(plot, offsetBuffer, pickBuffer, shader, pickShader) { this.points = null } -var __proto_198 = Pointcloud2D.prototype +var __proto_255 = Pointcloud2D.prototype -__proto_198.dispose = function() { +__proto_255.dispose = function() { this.shader.dispose() this.pickShader.dispose() this.offsetBuffer.dispose() @@ -128880,7 +130055,7 @@ __proto_198.dispose = function() { this.plot.removeObject(this) } -__proto_198.update = function(options) { +__proto_255.update = function(options) { var i @@ -128910,8 +130085,8 @@ __proto_198.update = function(options) { var idStraightThrough = options.idToIndex instanceof Int32Array && options.idToIndex.length >= pointCount // permit larger to help reuse var data = options.positions - var packed = dataStraightThrough ? data : _$pool_360.mallocFloat32(data.length) - var packedId = idStraightThrough ? options.idToIndex : _$pool_360.mallocInt32(pointCount) + var packed = dataStraightThrough ? data : _$pool_422.mallocFloat32(data.length) + var packedId = idStraightThrough ? options.idToIndex : _$pool_422.mallocInt32(pointCount) if(!dataStraightThrough) { packed.set(data) @@ -128930,18 +130105,18 @@ __proto_198.update = function(options) { this.pickBuffer.update(packedId) if(!dataStraightThrough) { - _$pool_360.free(packed) + _$pool_422.free(packed) } if(!idStraightThrough) { - _$pool_360.free(packedId) + _$pool_422.free(packedId) } this.pointCount = pointCount this.pickOffset = 0 } -function __count_198(points, dataBox) { +function __count_255(points, dataBox) { var visiblePointCountEstimate = 0 var length = points.length >>> 1 var i @@ -128954,7 +130129,7 @@ function __count_198(points, dataBox) { return visiblePointCountEstimate } -__proto_198.unifiedDraw = (function() { +__proto_255.unifiedDraw = (function() { var MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1] @@ -128973,7 +130148,7 @@ return function(pickOffset) { var dataX = dataBox[2] - dataBox[0] var dataY = dataBox[3] - dataBox[1] - var visiblePointCountEstimate = __count_198(this.points, dataBox) + var visiblePointCountEstimate = __count_255(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 @@ -129026,10 +130201,10 @@ return function(pickOffset) { } })() -__proto_198.draw = __proto_198.unifiedDraw -__proto_198.drawPick = __proto_198.unifiedDraw +__proto_255.draw = __proto_255.unifiedDraw +__proto_255.drawPick = __proto_255.unifiedDraw -__proto_198.pick = function(x, y, value) { +__proto_255.pick = function(x, y, value) { var pickOffset = this.pickOffset var pointCount = this.pointCount if(value < pickOffset || value >= pickOffset + pointCount) { @@ -129046,10 +130221,10 @@ __proto_198.pick = function(x, y, value) { function createPointcloud2D(plot, options) { var gl = plot.gl - var buffer = _$createBuffer_153(gl) - var pickBuffer = _$createBuffer_153(gl) - var shader = _$createShader_206(gl, _$shader_197.pointVertex, _$shader_197.pointFragment) - var pickShader = _$createShader_206(gl, _$shader_197.pickVertex, _$shader_197.pickFragment) + var buffer = _$createBuffer_210(gl) + var pickBuffer = _$createBuffer_210(gl) + var shader = _$createShader_263(gl, _$shader_254.pointVertex, _$shader_254.pointFragment) + var pickShader = _$createShader_263(gl, _$shader_254.pickVertex, _$shader_254.pickFragment) var result = new Pointcloud2D(plot, buffer, pickBuffer, shader, pickShader) result.update(options) @@ -129070,11 +130245,11 @@ function createPointcloud2D(plot, options) { 'use strict'; -/* removed: var _$createPointcloud2D_198 = require('gl-pointcloud2d'); */; +/* removed: var _$createPointcloud2D_255 = require('gl-pointcloud2d'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; -var expandAxis = _$autorange_583.expand; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; +var expandAxis = _$autorange_646.expand; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; function Pointcloud(scene, uid) { this.scene = scene; @@ -129102,13 +130277,13 @@ function Pointcloud(scene, uid) { areaRatio: 1, borderColor: [0, 0, 0, 1] }; - this.pointcloud = _$createPointcloud2D_198(scene.glplot, this.pointcloudOptions); + this.pointcloud = _$createPointcloud2D_255(scene.glplot, this.pointcloudOptions); this.pointcloud._trace = this; // scene2d requires this prop } -var __proto_850 = Pointcloud.prototype; +var __proto_915 = Pointcloud.prototype; -__proto_850.handlePick = function(pickResult) { +__proto_915.handlePick = function(pickResult) { var index = this.idToIndex[pickResult.pointId]; // prefer the readout from XY, if present @@ -129128,7 +130303,7 @@ __proto_850.handlePick = function(pickResult) { }; }; -__proto_850.update = function(options) { +__proto_915.update = function(options) { this.index = options.index; this.textLabels = options.text; this.name = options.name; @@ -129137,10 +130312,10 @@ __proto_850.update = function(options) { this.updateFast(options); - this.color = _$getTraceColor_872(options, {}); + this.color = _$getTraceColor_937(options, {}); }; -__proto_850.updateFast = function(options) { +__proto_915.updateFast = function(options) { var x = this.xData = this.pickXData = options.x; var y = this.yData = this.pickYData = options.y; var xy = this.pickXYData = options.xy; @@ -129229,8 +130404,8 @@ __proto_850.updateFast = function(options) { this.pointcloudOptions.positions = positions; - var markerColor = _$str2RgbaArray_561(options.marker.color), - borderColor = _$str2RgbaArray_561(options.marker.border.color), + var markerColor = _$str2RgbaArray_624(options.marker.color), + borderColor = _$str2RgbaArray_624(options.marker.border.color), opacity = options.opacity * options.marker.opacity; markerColor[3] *= opacity; @@ -129260,14 +130435,14 @@ __proto_850.updateFast = function(options) { this.expandAxesFast(bounds, markerSizeMax / 2); // avoid axis reexpand just because of the adaptive point size }; -__proto_850.expandAxesFast = function(bounds, markerSize) { +__proto_915.expandAxesFast = function(bounds, markerSize) { var pad = markerSize || 0.5; expandAxis(this.scene.xaxis, [bounds[0], bounds[2]], {ppad: pad}); expandAxis(this.scene.yaxis, [bounds[1], bounds[3]], {ppad: pad}); }; -__proto_850.dispose = function() { +__proto_915.dispose = function() { this.pointcloud.dispose(); }; @@ -129277,7 +130452,7 @@ function createPointcloud(scene, data) { return plot; } -var _$createPointcloud_850 = createPointcloud; +var _$createPointcloud_915 = createPointcloud; /** * Copyright 2012-2018, Plotly, Inc. @@ -129290,13 +130465,13 @@ var _$createPointcloud_850 = createPointcloud; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$attributes_849 = require('./attributes'); */; +/* removed: var _$attributes_914 = require('./attributes'); */; -var _$supplyDefaults_851 = function supplyDefaults(traceIn, traceOut, defaultColor) { +var _$supplyDefaults_916 = function supplyDefaults(traceIn, traceOut, defaultColor) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_849, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_914, attr, dflt); } coerce('x'); @@ -129333,8 +130508,8 @@ var _$supplyDefaults_851 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; /** @@ -129342,11 +130517,11 @@ var _$supplyDefaults_851 = function supplyDefaults(traceIn, traceOut, defaultCol * calcdata the way Scatter.plot does, so that legends and * popovers know what to do with them. */ -var _$calc_888 = function calc(gd, trace) { +var _$calc_953 = function calc(gd, trace) { var cd = [{x: false, y: false, trace: trace, t: {}}]; - _$arraysToCalcdata_861(cd, trace); - _$calcMarkerColorscale_867(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcMarkerColorscale_932(trace); return cd; }; @@ -129363,22 +130538,22 @@ var _$calc_888 = function calc(gd, trace) { var pointcloud = {}; -pointcloud.attributes = _$attributes_849; -pointcloud.supplyDefaults = _$supplyDefaults_851; +pointcloud.attributes = _$attributes_914; +pointcloud.supplyDefaults = _$supplyDefaults_916; // reuse the Scatter3D 'dummy' calc step so that legends know what to do -pointcloud.calc = _$calc_888; -pointcloud.plot = _$createPointcloud_850; +pointcloud.calc = _$calc_953; +pointcloud.plot = _$createPointcloud_915; pointcloud.moduleType = 'trace'; pointcloud.name = 'pointcloud'; -pointcloud.basePlotModule = _$gl2d_624; +pointcloud.basePlotModule = _$gl2d_686; pointcloud.categories = ['gl', 'gl2d', 'showLegend']; pointcloud.meta = { }; -var _$pointcloud_852 = pointcloud; +var _$pointcloud_917 = pointcloud; /** * Copyright 2012-2018, Plotly, Inc. @@ -129390,7 +130565,7 @@ var _$pointcloud_852 = pointcloud; 'use strict'; -var _$pointcloud_25 = _$pointcloud_852; +var _$pointcloud_25 = _$pointcloud_917; /** * Copyright 2012-2018, Plotly, Inc. @@ -129402,22 +130577,22 @@ var _$pointcloud_25 = _$pointcloud_852; 'use strict'; -/* removed: var _$font_attributes_611 = require('../../plots/font_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$attributes_445 = require('../../components/fx/attributes'); */; -var __domainAttrs_853 = _$domain_610.attributes; +/* removed: var _$font_attributes_673 = require('../../plots/font_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$attributes_507 = require('../../components/fx/attributes'); */; +var __domainAttrs_918 = _$domain_672.attributes; -var __extendFlat_853 = _$extend_528.extendFlat; -var __overrideAll_853 = _$edit_types_569.overrideAll; +var __extendFlat_918 = _$extend_590.extendFlat; +var __overrideAll_918 = _$edit_types_632.overrideAll; -var _$attributes_853 = __overrideAll_853({ - hoverinfo: __extendFlat_853({}, _$attributes_581.hoverinfo, { +var _$attributes_918 = __overrideAll_918({ + hoverinfo: __extendFlat_918({}, _$attributes_644.hoverinfo, { flags: ['label', 'text', 'value', 'percent', 'name'], }), - hoverlabel: _$attributes_445.hoverlabel, // needs editType override + hoverlabel: _$attributes_507.hoverlabel, // needs editType override - domain: __domainAttrs_853({name: 'sankey', trace: true}), + domain: __domainAttrs_918({name: 'sankey', trace: true}), orientation: { valType: 'enumerated', @@ -129449,7 +130624,7 @@ var _$attributes_853 = __overrideAll_853({ }, - textfont: _$font_attributes_611({ + textfont: _$font_attributes_673({ }), @@ -129470,7 +130645,7 @@ var _$attributes_853 = __overrideAll_853({ color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, arrayOk: true, }, @@ -129519,7 +130694,7 @@ var _$attributes_853 = __overrideAll_853({ color: { valType: 'color', - dflt: _$attributes_410.defaultLine, + dflt: _$attributes_472.defaultLine, arrayOk: true, }, @@ -129564,7 +130739,7 @@ var _$attributes_853 = __overrideAll_853({ 'use strict'; -var _$constants_856 = { +var _$constants_921 = { nodeTextOffsetHorizontal: 4, nodeTextOffsetVertical: 3, nodePadAcross: 10, @@ -129588,10 +130763,10 @@ var _$constants_856 = { } }; -var _$d3Array_119 = { exports: {} }; +var _$d3Array_122 = { exports: {} }; // https://d3js.org/d3-array/ Version 1.2.1. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Array_119.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Array_119.exports) : + typeof _$d3Array_122.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Array_122.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -130180,11 +131355,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Array_119 = _$d3Array_119.exports -var _$d3Collection_120 = { exports: {} }; +_$d3Array_122 = _$d3Array_122.exports +var _$d3Collection_123 = { exports: {} }; // https://d3js.org/d3-collection/ Version 1.0.4. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Collection_120.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Collection_120.exports) : + typeof _$d3Collection_123.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Collection_123.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -130400,11 +131575,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Collection_120 = _$d3Collection_120.exports -var _$d3Color_121 = { exports: {} }; +_$d3Collection_123 = _$d3Collection_123.exports +var _$d3Color_124 = { exports: {} }; // https://d3js.org/d3-color/ Version 1.0.3. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Color_121.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Color_121.exports) : + typeof _$d3Color_124.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Color_124.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -130926,11 +132101,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Color_121 = _$d3Color_121.exports -var _$d3Interpolate_124 = { exports: {} }; +_$d3Color_124 = _$d3Color_124.exports +var _$d3Interpolate_127 = { exports: {} }; // https://d3js.org/d3-interpolate/ Version 1.1.6. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Interpolate_124.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Interpolate_124.exports, _$d3Color_121) : + typeof _$d3Interpolate_127.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Interpolate_127.exports, _$d3Color_124) : typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) : (factory((global.d3 = global.d3 || {}),global.d3)); }(this, (function (exports,d3Color) { 'use strict'; @@ -131474,11 +132649,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Interpolate_124 = _$d3Interpolate_124.exports -var _$d3Sankey_41 = { exports: {} }; +_$d3Interpolate_127 = _$d3Interpolate_127.exports +var _$d3Sankey_42 = { exports: {} }; // https://github.com/d3/d3-sankey Version 0.5.0. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Sankey_41.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Sankey_41.exports, _$d3Array_119, _$d3Collection_120, _$d3Interpolate_124) : + typeof _$d3Sankey_42.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Sankey_42.exports, _$d3Array_122, _$d3Collection_123, _$d3Interpolate_127) : typeof define === 'function' && define.amd ? define(['exports', 'd3-array', 'd3-collection', 'd3-interpolate'], factory) : (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3)); }(this, (function (exports,d3Array,d3Collection,d3Interpolate) { 'use strict'; @@ -131792,11 +132967,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Sankey_41 = _$d3Sankey_41.exports -var _$d3Dispatch_122 = { exports: {} }; +_$d3Sankey_42 = _$d3Sankey_42.exports +var _$d3Dispatch_125 = { exports: {} }; // https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Dispatch_122.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Dispatch_122.exports) : + typeof _$d3Dispatch_125.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Dispatch_125.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -131890,11 +133065,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Dispatch_122 = _$d3Dispatch_122.exports -var _$d3Quadtree_125 = { exports: {} }; +_$d3Dispatch_125 = _$d3Dispatch_125.exports +var _$d3Quadtree_128 = { exports: {} }; // https://d3js.org/d3-quadtree/ Version 1.0.3. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Quadtree_125.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Quadtree_125.exports) : + typeof _$d3Quadtree_128.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Quadtree_128.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -132328,11 +133503,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Quadtree_125 = _$d3Quadtree_125.exports -var _$d3Timer_126 = { exports: {} }; +_$d3Quadtree_128 = _$d3Quadtree_128.exports +var _$d3Timer_129 = { exports: {} }; // https://d3js.org/d3-timer/ Version 1.0.7. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Timer_126.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Timer_126.exports) : + typeof _$d3Timer_129.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Timer_129.exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3 = global.d3 || {}))); }(this, (function (exports) { 'use strict'; @@ -132480,11 +133655,11 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Timer_126 = _$d3Timer_126.exports -var _$d3Force_123 = { exports: {} }; +_$d3Timer_129 = _$d3Timer_129.exports +var _$d3Force_126 = { exports: {} }; // https://d3js.org/d3-force/ Version 1.1.0. Copyright 2017 Mike Bostock. (function (global, factory) { - typeof _$d3Force_123.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Force_123.exports, _$d3Quadtree_125, _$d3Collection_120, _$d3Dispatch_122, _$d3Timer_126) : + typeof _$d3Force_126.exports === 'object' && "object" !== 'undefined' ? factory(_$d3Force_126.exports, _$d3Quadtree_128, _$d3Collection_123, _$d3Dispatch_125, _$d3Timer_129) : typeof define === 'function' && define.amd ? define(['exports', 'd3-quadtree', 'd3-collection', 'd3-dispatch', 'd3-timer'], factory) : (factory((global.d3 = global.d3 || {}),global.d3,global.d3,global.d3,global.d3)); }(this, (function (exports,d3Quadtree,d3Collection,d3Dispatch,d3Timer) { 'use strict'; @@ -133143,7 +134318,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); -_$d3Force_123 = _$d3Force_123.exports +_$d3Force_126 = _$d3Force_126.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -133154,17 +134329,17 @@ _$d3Force_123 = _$d3Force_123.exports 'use strict'; -/* removed: var _$constants_856 = require('./constants'); */; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -var d3sankey = _$d3Sankey_41.sankey; -/* removed: var _$d3Force_123 = require('d3-force'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __keyFun_860 = _$gup_536.keyFun; -var __repeat_860 = _$gup_536.repeat; -var __unwrap_860 = _$gup_536.unwrap; +/* removed: var _$constants_921 = require('./constants'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +var d3sankey = _$d3Sankey_42.sankey; +/* removed: var _$d3Force_126 = require('d3-force'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __keyFun_925 = _$gup_598.keyFun; +var __repeat_925 = _$gup_598.repeat; +var __unwrap_925 = _$gup_598.unwrap; // basic data utilities @@ -133210,7 +134385,7 @@ function switchToSankeyFormat(nodes) { // view models function sankeyModel(layout, d, i) { - var trace = __unwrap_860(d).trace, + var trace = __unwrap_925(d).trace, domain = trace.domain, nodeSpec = trace.node, linkSpec = trace.link, @@ -133233,7 +134408,7 @@ function sankeyModel(layout, d, i) { return { pointNumber: i, label: l, - color: _$lib_539.isArrayOrTypedArray(nodeSpec.color) ? nodeSpec.color[i] : nodeSpec.color + color: _$lib_601.isArrayOrTypedArray(nodeSpec.color) ? nodeSpec.color[i] : nodeSpec.color }; }); @@ -133241,7 +134416,7 @@ function sankeyModel(layout, d, i) { return { pointNumber: i, label: linkSpec.label[i], - color: _$lib_539.isArrayOrTypedArray(linkSpec.color) ? linkSpec.color[i] : linkSpec.color, + color: _$lib_601.isArrayOrTypedArray(linkSpec.color) ? linkSpec.color[i] : linkSpec.color, source: linkSpec.source[i], target: linkSpec.target[i], value: d @@ -133254,7 +134429,7 @@ function sankeyModel(layout, d, i) { .nodePadding(nodePad) .nodes(nodes) .links(links) - .layout(_$constants_856.sankeyIterations); + .layout(_$constants_921.sankeyIterations); var node, sankeyNodes = sankey.nodes(); for(var n = 0; n < sankeyNodes.length; n++) { @@ -133297,7 +134472,7 @@ function sankeyModel(layout, d, i) { } function linkModel(uniqueKeys, d, l) { - var tc = _$tinycolor_352(l.color); + var tc = _$tinycolor_414(l.color); var basicKey = l.source.label + '|' + l.target.label; var foundKey = uniqueKeys[basicKey]; uniqueKeys[basicKey] = (foundKey || 0) + 1; @@ -133311,7 +134486,7 @@ function linkModel(uniqueKeys, d, l) { key: key, traceId: d.key, link: l, - tinyColorHue: _$color_411.tinyRGB(tc), + tinyColorHue: _$color_473.tinyRGB(tc), tinyColorAlpha: tc.getAlpha(), linkLineColor: d.linkLineColor, linkLineWidth: d.linkLineWidth, @@ -133323,8 +134498,8 @@ function linkModel(uniqueKeys, d, l) { } function nodeModel(uniqueKeys, d, n) { - var tc = _$tinycolor_352(n.color), - zoneThicknessPad = _$constants_856.nodePadAcross, + var tc = _$tinycolor_414(n.color), + zoneThicknessPad = _$constants_921.nodePadAcross, zoneLengthPad = d.nodePad / 2, visibleThickness = n.dx, visibleLength = Math.max(0.5, n.dy); @@ -133359,7 +134534,7 @@ function nodeModel(uniqueKeys, d, n) { forceLayouts: d.forceLayouts, horizontal: d.horizontal, darkBackground: tc.getBrightness() <= 128, - tinyColorHue: _$color_411.tinyRGB(tc), + tinyColorHue: _$color_473.tinyRGB(tc), tinyColorAlpha: tc.getAlpha(), valueFormat: d.valueFormat, valueSuffix: d.valueSuffix, @@ -133413,9 +134588,9 @@ function nodeCentering(d) { } function textGuidePath(d) { - return _$d3_127.svg.line()([ - [d.horizontal ? (d.left ? -d.sizeAcross : d.visibleWidth + _$constants_856.nodeTextOffsetHorizontal) : _$constants_856.nodeTextOffsetHorizontal, 0], - [d.horizontal ? (d.left ? - _$constants_856.nodeTextOffsetHorizontal : d.sizeAcross) : d.visibleHeight - _$constants_856.nodeTextOffsetHorizontal, 0] + return _$d3_130.svg.line()([ + [d.horizontal ? (d.left ? -d.sizeAcross : d.visibleWidth + _$constants_921.nodeTextOffsetHorizontal) : _$constants_921.nodeTextOffsetHorizontal, 0], + [d.horizontal ? (d.left ? - _$constants_921.nodeTextOffsetHorizontal : d.sizeAcross) : d.visibleHeight - _$constants_921.nodeTextOffsetHorizontal, 0] ]);} function sankeyInverseTransform(d) {return d.horizontal ? 'matrix(1 0 0 1 0 0)' : 'matrix(0 1 1 0 0 0)';} @@ -133459,13 +134634,13 @@ function attachPointerEvents(selection, sankey, eventSet) { function attachDragHandler(sankeyNode, sankeyLink, callbacks) { - var dragBehavior = _$d3_127.behavior.drag() + var dragBehavior = _$d3_130.behavior.drag() .origin(function(d) {return d.node;}) .on('dragstart', function(d) { if(d.arrangement === 'fixed') return; - _$lib_539.raiseToTop(this); + _$lib_601.raiseToTop(this); d.interactionState.dragInProgress = d.node; saveCurrentDragPosition(d.node); if(d.interactionState.hovered) { @@ -133485,8 +134660,8 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks) { .on('drag', function(d) { if(d.arrangement === 'fixed') return; - var x = _$d3_127.event.x; - var y = _$d3_127.event.y; + var x = _$d3_130.event.x; + var y = _$d3_130.event.y; if(d.arrangement === 'snap') { d.node.x = x; d.node.y = y; @@ -133514,19 +134689,19 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks) { function attachForce(sankeyNode, forceKey, d) { var nodes = d.sankey.nodes().filter(function(n) {return n.originalX === d.node.originalX;}); - d.forceLayouts[forceKey] = _$d3Force_123.forceSimulation(nodes) + d.forceLayouts[forceKey] = _$d3Force_126.forceSimulation(nodes) .alphaDecay(0) - .force('collide', _$d3Force_123.forceCollide() + .force('collide', _$d3Force_126.forceCollide() .radius(function(n) {return n.dy / 2 + d.nodePad / 2;}) .strength(1) - .iterations(_$constants_856.forceIterations)) + .iterations(_$constants_921.forceIterations)) .force('constrain', snappingForce(sankeyNode, forceKey, nodes, d)) .stop(); } function startForce(sankeyNode, sankeyLink, d, forceKey) { window.requestAnimationFrame(function faster() { - for(var i = 0; i < _$constants_856.forceTicksPerFrame; i++) { + for(var i = 0; i < _$constants_921.forceTicksPerFrame; i++) { d.forceLayouts[forceKey].tick(); } d.sankey.relayout(); @@ -133546,7 +134721,7 @@ function snappingForce(sankeyNode, forceKey, nodes, d) { n.x = n.lastDraggedX; n.y = n.lastDraggedY; } else { - n.vx = (n.originalX - n.x) / _$constants_856.forceTicksPerFrame; // snap to layer + n.vx = (n.originalX - n.x) / _$constants_921.forceTicksPerFrame; // snap to layer n.y = Math.min(d.size - n.dy / 2, Math.max(n.dy / 2, n.y)); // constrain to extent } maxVelocity = Math.max(maxVelocity, Math.abs(n.vx), Math.abs(n.vy)); @@ -133558,19 +134733,19 @@ function snappingForce(sankeyNode, forceKey, nodes, d) { } // scene graph -var _$render_860 = function(svg, styledData, layout, callbacks) { - var sankey = svg.selectAll('.' + _$constants_856.cn.sankey) +var _$render_925 = function(svg, styledData, layout, callbacks) { + var sankey = svg.selectAll('.' + _$constants_921.cn.sankey) .data(styledData - .filter(function(d) {return __unwrap_860(d).trace.visible;}) + .filter(function(d) {return __unwrap_925(d).trace.visible;}) .map(sankeyModel.bind(null, layout)), - __keyFun_860); + __keyFun_925); sankey.exit() .remove(); sankey.enter() .append('g') - .classed(_$constants_856.cn.sankey, true) + .classed(_$constants_921.cn.sankey, true) .style('box-sizing', 'content-box') .style('position', 'absolute') .style('left', 0) @@ -133580,57 +134755,57 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .attr('transform', sankeyTransform); sankey.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('transform', sankeyTransform); - var sankeyLinks = sankey.selectAll('.' + _$constants_856.cn.sankeyLinks) - .data(__repeat_860, __keyFun_860); + var sankeyLinks = sankey.selectAll('.' + _$constants_921.cn.sankeyLinks) + .data(__repeat_925, __keyFun_925); sankeyLinks.enter() .append('g') - .classed(_$constants_856.cn.sankeyLinks, true) + .classed(_$constants_921.cn.sankeyLinks, true) .style('fill', 'none'); - var sankeyLink = sankeyLinks.selectAll('.' + _$constants_856.cn.sankeyLink) + var sankeyLink = sankeyLinks.selectAll('.' + _$constants_921.cn.sankeyLink) .data(function(d) { var uniqueKeys = {}; return d.sankey.links() .filter(function(l) {return l.value;}) .map(linkModel.bind(null, uniqueKeys, d)); - }, __keyFun_860); + }, __keyFun_925); sankeyLink.enter() .append('path') - .classed(_$constants_856.cn.sankeyLink, true) + .classed(_$constants_921.cn.sankeyLink, true) .attr('d', linkPath) .call(attachPointerEvents, sankey, callbacks.linkEvents); sankeyLink .style('stroke', function(d) { - return salientEnough(d) ? _$color_411.tinyRGB(_$tinycolor_352(d.linkLineColor)) : d.tinyColorHue; + return salientEnough(d) ? _$color_473.tinyRGB(_$tinycolor_414(d.linkLineColor)) : d.tinyColorHue; }) .style('stroke-opacity', function(d) { - return salientEnough(d) ? _$color_411.opacity(d.linkLineColor) : d.tinyColorAlpha; + return salientEnough(d) ? _$color_473.opacity(d.linkLineColor) : d.tinyColorAlpha; }) .style('stroke-width', function(d) {return salientEnough(d) ? d.linkLineWidth : 1;}) .style('fill', function(d) {return d.tinyColorHue;}) .style('fill-opacity', function(d) {return d.tinyColorAlpha;}); sankeyLink.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('d', linkPath); sankeyLink.exit().transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .style('opacity', 0) .remove(); - var sankeyNodeSet = sankey.selectAll('.' + _$constants_856.cn.sankeyNodeSet) - .data(__repeat_860, __keyFun_860); + var sankeyNodeSet = sankey.selectAll('.' + _$constants_921.cn.sankeyNodeSet) + .data(__repeat_925, __keyFun_925); sankeyNodeSet.enter() .append('g') - .classed(_$constants_856.cn.sankeyNodeSet, true); + .classed(_$constants_921.cn.sankeyNodeSet, true); sankeyNodeSet .style('cursor', function(d) { @@ -133641,7 +134816,7 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { } }); - var sankeyNode = sankeyNodeSet.selectAll('.' + _$constants_856.cn.sankeyNode) + var sankeyNode = sankeyNodeSet.selectAll('.' + _$constants_921.cn.sankeyNode) .data(function(d) { var nodes = d.sankey.nodes(); var uniqueKeys = {}; @@ -133649,11 +134824,11 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { return nodes .filter(function(n) {return n.value;}) .map(nodeModel.bind(null, uniqueKeys, d)); - }, __keyFun_860); + }, __keyFun_925); sankeyNode.enter() .append('g') - .classed(_$constants_856.cn.sankeyNode, true) + .classed(_$constants_921.cn.sankeyNode, true) .call(updateNodePositions) .call(attachPointerEvents, sankey, callbacks.nodeEvents); @@ -133661,39 +134836,39 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .call(attachDragHandler, sankeyLink, callbacks); // has to be here as it binds sankeyLink sankeyNode.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .call(updateNodePositions); sankeyNode.exit().transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .style('opacity', 0) .remove(); - var nodeRect = sankeyNode.selectAll('.' + _$constants_856.cn.nodeRect) - .data(__repeat_860); + var nodeRect = sankeyNode.selectAll('.' + _$constants_921.cn.nodeRect) + .data(__repeat_925); nodeRect.enter() .append('rect') - .classed(_$constants_856.cn.nodeRect, true) + .classed(_$constants_921.cn.nodeRect, true) .call(sizeNode); nodeRect .style('stroke-width', function(d) {return d.nodeLineWidth;}) - .style('stroke', function(d) {return _$color_411.tinyRGB(_$tinycolor_352(d.nodeLineColor));}) - .style('stroke-opacity', function(d) {return _$color_411.opacity(d.nodeLineColor);}) + .style('stroke', function(d) {return _$color_473.tinyRGB(_$tinycolor_414(d.nodeLineColor));}) + .style('stroke-opacity', function(d) {return _$color_473.opacity(d.nodeLineColor);}) .style('fill', function(d) {return d.tinyColorHue;}) .style('fill-opacity', function(d) {return d.tinyColorAlpha;}); nodeRect.transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .call(sizeNode); - var nodeCapture = sankeyNode.selectAll('.' + _$constants_856.cn.nodeCapture) - .data(__repeat_860); + var nodeCapture = sankeyNode.selectAll('.' + _$constants_921.cn.nodeCapture) + .data(__repeat_925); nodeCapture.enter() .append('rect') - .classed(_$constants_856.cn.nodeCapture, true) + .classed(_$constants_921.cn.nodeCapture, true) .style('fill-opacity', 0); nodeCapture @@ -133702,41 +134877,41 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .attr('width', function(d) {return d.zoneWidth;}) .attr('height', function(d) {return d.zoneHeight;}); - var nodeCentered = sankeyNode.selectAll('.' + _$constants_856.cn.nodeCentered) - .data(__repeat_860); + var nodeCentered = sankeyNode.selectAll('.' + _$constants_921.cn.nodeCentered) + .data(__repeat_925); nodeCentered.enter() .append('g') - .classed(_$constants_856.cn.nodeCentered, true) + .classed(_$constants_921.cn.nodeCentered, true) .attr('transform', nodeCentering); nodeCentered .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('transform', nodeCentering); - var nodeLabelGuide = nodeCentered.selectAll('.' + _$constants_856.cn.nodeLabelGuide) - .data(__repeat_860); + var nodeLabelGuide = nodeCentered.selectAll('.' + _$constants_921.cn.nodeLabelGuide) + .data(__repeat_925); nodeLabelGuide.enter() .append('path') - .classed(_$constants_856.cn.nodeLabelGuide, true) + .classed(_$constants_921.cn.nodeLabelGuide, true) .attr('id', function(d) {return d.uniqueNodeLabelPathId;}) .attr('d', textGuidePath) .attr('transform', sankeyInverseTransform); nodeLabelGuide .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('d', textGuidePath) .attr('transform', sankeyInverseTransform); - var nodeLabel = nodeCentered.selectAll('.' + _$constants_856.cn.nodeLabel) - .data(__repeat_860); + var nodeLabel = nodeCentered.selectAll('.' + _$constants_921.cn.nodeLabel) + .data(__repeat_925); nodeLabel.enter() .append('text') - .classed(_$constants_856.cn.nodeLabel, true) + .classed(_$constants_921.cn.nodeLabel, true) .attr('transform', textFlip) .style('user-select', 'none') .style('cursor', 'default') @@ -133746,19 +134921,19 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { .style('text-shadow', function(d) { return d.horizontal ? '-1px 1px 1px #fff, 1px 1px 1px #fff, 1px -1px 1px #fff, -1px -1px 1px #fff' : 'none'; }) - .each(function(d) {_$drawing_436.font(nodeLabel, d.textFont);}); + .each(function(d) {_$drawing_498.font(nodeLabel, d.textFont);}); nodeLabel .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('transform', textFlip); - var nodeLabelTextPath = nodeLabel.selectAll('.' + _$constants_856.cn.nodeLabelTextPath) - .data(__repeat_860); + var nodeLabelTextPath = nodeLabel.selectAll('.' + _$constants_921.cn.nodeLabelTextPath) + .data(__repeat_925); nodeLabelTextPath.enter() .append('textPath') - .classed(_$constants_856.cn.nodeLabelTextPath, true) + .classed(_$constants_921.cn.nodeLabelTextPath, true) .attr('alignment-baseline', 'middle') .attr('xlink:href', function(d) {return '#' + d.uniqueNodeLabelPathId;}) .attr('startOffset', nodeTextOffset) @@ -133770,7 +134945,7 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { nodeLabelTextPath .transition() - .ease(_$constants_856.ease).duration(_$constants_856.duration) + .ease(_$constants_921.ease).duration(_$constants_921.duration) .attr('startOffset', nodeTextOffset) .style('fill', nodeTextColor); }; @@ -133785,14 +134960,14 @@ var _$render_860 = function(svg, styledData, layout, callbacks) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$render_860 = require('./render'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __cn_859 = _$constants_856.cn; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$render_925 = require('./render'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __cn_924 = _$constants_921.cn; -var ____859 = _$lib_539._; +var ____924 = _$lib_601._; function renderableValuePresent(d) {return d !== '';} @@ -133801,16 +134976,16 @@ function ownTrace(selection, d) { } function makeTranslucent(element, alpha) { - _$d3_127.select(element) + _$d3_130.select(element) .select('path') .style('fill-opacity', alpha); - _$d3_127.select(element) + _$d3_130.select(element) .select('rect') .style('fill-opacity', alpha); } function makeTextContrasty(element) { - _$d3_127.select(element) + _$d3_130.select(element) .select('text.name') .style('fill', 'black'); } @@ -133830,7 +135005,7 @@ function relatedNodes(l) { function nodeHoveredStyle(sankeyNode, d, sankey) { if(d && sankey) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(relatedLinks(d)) .call(linkHoveredStyle.bind(0, d, sankey, false)); } @@ -133839,7 +135014,7 @@ function nodeHoveredStyle(sankeyNode, d, sankey) { function nodeNonHoveredStyle(sankeyNode, d, sankey) { if(d && sankey) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(relatedLinks(d)) .call(linkNonHoveredStyle.bind(0, d, sankey, false)); } @@ -133853,14 +135028,14 @@ function linkHoveredStyle(d, sankey, visitNodes, sankeyLink) { if(label) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(function(l) {return l.link.label === label;}) .style('fill-opacity', 0.4); } if(visitNodes) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyNode) + .selectAll('.' + __cn_924.sankeyNode) .filter(relatedNodes(d)) .call(nodeHoveredStyle); } @@ -133874,50 +135049,50 @@ function linkNonHoveredStyle(d, sankey, visitNodes, sankeyLink) { if(label) { ownTrace(sankey, d) - .selectAll('.' + __cn_859.sankeyLink) + .selectAll('.' + __cn_924.sankeyLink) .filter(function(l) {return l.link.label === label;}) .style('fill-opacity', function(d) {return d.tinyColorAlpha;}); } if(visitNodes) { ownTrace(sankey, d) - .selectAll(__cn_859.sankeyNode) + .selectAll(__cn_924.sankeyNode) .filter(relatedNodes(d)) .call(nodeNonHoveredStyle); } } // does not support array values for now -function __castHoverOption_859(trace, attr) { +function __castHoverOption_924(trace, attr) { var labelOpts = trace.hoverlabel || {}; - var val = _$lib_539.nestedProperty(labelOpts, attr).get(); + var val = _$lib_601.nestedProperty(labelOpts, attr).get(); return Array.isArray(val) ? false : val; } -var _$plot_859 = function plot(gd, calcData) { +var _$plot_924 = function plot(gd, calcData) { var fullLayout = gd._fullLayout; var svg = fullLayout._paper; var size = fullLayout._size; var linkSelect = function(element, d) { var evt = d.link; - evt.originalEvent = _$d3_127.event; + evt.originalEvent = _$d3_130.event; gd._hoverdata = [evt]; - _$fx_453.click(gd, { target: true }); + _$fx_515.click(gd, { target: true }); }; var linkHover = function(element, d, sankey) { - _$d3_127.select(element).call(linkHoveredStyle.bind(0, d, sankey, true)); + _$d3_130.select(element).call(linkHoveredStyle.bind(0, d, sankey, true)); gd.emit('plotly_hover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.link] }); }; - var sourceLabel = ____859(gd, 'source:') + ' '; - var targetLabel = ____859(gd, 'target:') + ' '; - var incomingLabel = ____859(gd, 'incoming flow count:') + ' '; - var outgoingLabel = ____859(gd, 'outgoing flow count:') + ' '; + var sourceLabel = ____924(gd, 'source:') + ' '; + var targetLabel = ____924(gd, 'target:') + ' '; + var incomingLabel = ____924(gd, 'incoming flow count:') + ' '; + var outgoingLabel = ____924(gd, 'outgoing flow count:') + ' '; var linkHoverFollow = function(element, d) { var trace = d.link.trace; @@ -133926,21 +135101,21 @@ var _$plot_859 = function plot(gd, calcData) { var hoverCenterX = boundingBox.left + boundingBox.width / 2; var hoverCenterY = boundingBox.top + boundingBox.height / 2; - var tooltip = _$fx_453.loneHover({ + var tooltip = _$fx_515.loneHover({ x: hoverCenterX - rootBBox.left, y: hoverCenterY - rootBBox.top, - name: _$d3_127.format(d.valueFormat)(d.link.value) + d.valueSuffix, + name: _$d3_130.format(d.valueFormat)(d.link.value) + d.valueSuffix, text: [ d.link.label || '', sourceLabel + d.link.source.label, targetLabel + d.link.target.label ].filter(renderableValuePresent).join('
'), - color: __castHoverOption_859(trace, 'bgcolor') || _$color_411.addOpacity(d.tinyColorHue, 1), - borderColor: __castHoverOption_859(trace, 'bordercolor'), - fontFamily: __castHoverOption_859(trace, 'font.family'), - fontSize: __castHoverOption_859(trace, 'font.size'), - fontColor: __castHoverOption_859(trace, 'font.color'), - idealAlign: _$d3_127.event.x < hoverCenterX ? 'right' : 'left' + color: __castHoverOption_924(trace, 'bgcolor') || _$color_473.addOpacity(d.tinyColorHue, 1), + borderColor: __castHoverOption_924(trace, 'bordercolor'), + fontFamily: __castHoverOption_924(trace, 'font.family'), + fontSize: __castHoverOption_924(trace, 'font.size'), + fontColor: __castHoverOption_924(trace, 'font.color'), + idealAlign: _$d3_130.event.x < hoverCenterX ? 'right' : 'left' }, { container: fullLayout._hoverlayer.node(), outerContainer: fullLayout._paper.node(), @@ -133952,55 +135127,55 @@ var _$plot_859 = function plot(gd, calcData) { }; var linkUnhover = function(element, d, sankey) { - _$d3_127.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true)); + _$d3_130.select(element).call(linkNonHoveredStyle.bind(0, d, sankey, true)); gd.emit('plotly_unhover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.link] }); - _$fx_453.loneUnhover(fullLayout._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout._hoverlayer.node()); }; var nodeSelect = function(element, d, sankey) { var evt = d.node; - evt.originalEvent = _$d3_127.event; + evt.originalEvent = _$d3_130.event; gd._hoverdata = [evt]; - _$d3_127.select(element).call(nodeNonHoveredStyle, d, sankey); - _$fx_453.click(gd, { target: true }); + _$d3_130.select(element).call(nodeNonHoveredStyle, d, sankey); + _$fx_515.click(gd, { target: true }); }; var nodeHover = function(element, d, sankey) { - _$d3_127.select(element).call(nodeHoveredStyle, d, sankey); + _$d3_130.select(element).call(nodeHoveredStyle, d, sankey); gd.emit('plotly_hover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.node] }); }; var nodeHoverFollow = function(element, d) { var trace = d.node.trace; - var nodeRect = _$d3_127.select(element).select('.' + __cn_859.nodeRect); + var nodeRect = _$d3_130.select(element).select('.' + __cn_924.nodeRect); var rootBBox = gd._fullLayout._paperdiv.node().getBoundingClientRect(); var boundingBox = nodeRect.node().getBoundingClientRect(); var hoverCenterX0 = boundingBox.left - 2 - rootBBox.left; var hoverCenterX1 = boundingBox.right + 2 - rootBBox.left; var hoverCenterY = boundingBox.top + boundingBox.height / 4 - rootBBox.top; - var tooltip = _$fx_453.loneHover({ + var tooltip = _$fx_515.loneHover({ x0: hoverCenterX0, x1: hoverCenterX1, y: hoverCenterY, - name: _$d3_127.format(d.valueFormat)(d.node.value) + d.valueSuffix, + name: _$d3_130.format(d.valueFormat)(d.node.value) + d.valueSuffix, text: [ d.node.label, incomingLabel + d.node.targetLinks.length, outgoingLabel + d.node.sourceLinks.length ].filter(renderableValuePresent).join('
'), - color: __castHoverOption_859(trace, 'bgcolor') || d.tinyColorHue, - borderColor: __castHoverOption_859(trace, 'bordercolor'), - fontFamily: __castHoverOption_859(trace, 'font.family'), - fontSize: __castHoverOption_859(trace, 'font.size'), - fontColor: __castHoverOption_859(trace, 'font.color'), + color: __castHoverOption_924(trace, 'bgcolor') || d.tinyColorHue, + borderColor: __castHoverOption_924(trace, 'bordercolor'), + fontFamily: __castHoverOption_924(trace, 'font.family'), + fontSize: __castHoverOption_924(trace, 'font.size'), + fontColor: __castHoverOption_924(trace, 'font.color'), idealAlign: 'left' }, { container: fullLayout._hoverlayer.node(), @@ -134013,16 +135188,16 @@ var _$plot_859 = function plot(gd, calcData) { }; var nodeUnhover = function(element, d, sankey) { - _$d3_127.select(element).call(nodeNonHoveredStyle, d, sankey); + _$d3_130.select(element).call(nodeNonHoveredStyle, d, sankey); gd.emit('plotly_unhover', { - event: _$d3_127.event, + event: _$d3_130.event, points: [d.node] }); - _$fx_453.loneUnhover(fullLayout._hoverlayer.node()); + _$fx_515.loneUnhover(fullLayout._hoverlayer.node()); }; - _$render_860( + _$render_925( svg, calcData, { @@ -134052,7 +135227,7 @@ var _$plot_859 = function plot(gd, calcData) { ); }; -var _$base_plot_854 = {}; +var _$base_plot_919 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -134063,25 +135238,25 @@ var _$base_plot_854 = {}; 'use strict'; -var __overrideAll_854 = _$edit_types_569.overrideAll; -var __getModuleCalcData_854 = _$get_data_621.getModuleCalcData; -/* removed: var _$plot_859 = require('./plot'); */; -/* removed: var _$layout_attributes_454 = require('../../components/fx/layout_attributes'); */; +var __overrideAll_919 = _$edit_types_632.overrideAll; +var __getModuleCalcData_919 = _$get_data_683.getModuleCalcData; +/* removed: var _$plot_924 = require('./plot'); */; +/* removed: var _$layout_attributes_516 = require('../../components/fx/layout_attributes'); */; var SANKEY = 'sankey'; -_$base_plot_854.name = SANKEY; +_$base_plot_919.name = SANKEY; -_$base_plot_854.baseLayoutAttrOverrides = __overrideAll_854({ - hoverlabel: _$layout_attributes_454.hoverlabel +_$base_plot_919.baseLayoutAttrOverrides = __overrideAll_919({ + hoverlabel: _$layout_attributes_516.hoverlabel }, 'plot', 'nested'); -_$base_plot_854.plot = function(gd) { - var calcData = __getModuleCalcData_854(gd.calcdata, SANKEY); - _$plot_859(gd, calcData); +_$base_plot_919.plot = function(gd) { + var calcData = __getModuleCalcData_919(gd.calcdata, SANKEY)[0]; + _$plot_924(gd, calcData); }; -_$base_plot_854.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_919.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadPlot = (oldFullLayout._has && oldFullLayout._has(SANKEY)); var hasPlot = (newFullLayout._has && newFullLayout._has(SANKEY)); @@ -134092,7 +135267,7 @@ _$base_plot_854.clean = function(newFullData, newFullLayout, oldFullData, oldFul "use strict" -var _$stronglyConnectedComponents_344 = stronglyConnectedComponents +var _$stronglyConnectedComponents_406 = stronglyConnectedComponents function stronglyConnectedComponents(adjList) { var numVertices = adjList.length; @@ -134215,9 +135390,9 @@ function stronglyConnectedComponents(adjList) { 'use strict'; -/* removed: var _$stronglyConnectedComponents_344 = require('strongly-connected-components'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __wrap_855 = _$gup_536.wrap; +/* removed: var _$stronglyConnectedComponents_406 = require('strongly-connected-components'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __wrap_920 = _$gup_598.wrap; function circularityPresent(nodeList, sources, targets) { @@ -134230,7 +135405,7 @@ function circularityPresent(nodeList, sources, targets) { nodes[sources[i]].push(targets[i]); } - var scc = _$stronglyConnectedComponents_344(nodes); + var scc = _$stronglyConnectedComponents_406(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 @@ -134239,10 +135414,10 @@ function circularityPresent(nodeList, sources, targets) { }); } -var _$calc_855 = function calc(gd, trace) { +var _$calc_920 = function calc(gd, trace) { if(circularityPresent(trace.node.label, trace.link.source, trace.link.target)) { - _$lib_539.error('Circularity is present in the Sankey data. Removing all nodes and links.'); + _$lib_601.error('Circularity is present in the Sankey data. Removing all nodes and links.'); trace.link.label = []; trace.link.source = []; trace.link.target = []; @@ -134252,7 +135427,7 @@ var _$calc_855 = function calc(gd, trace) { trace.node.color = []; } - return __wrap_855({ + return __wrap_920({ link: trace.link, node: trace.node }); @@ -134268,15 +135443,15 @@ var _$calc_855 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_853 = require('./attributes'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; -var __handleDomainDefaults_857 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_918 = require('./attributes'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; +var __handleDomainDefaults_922 = _$domain_672.defaults; -var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_853, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_918, attr, dflt); } coerce('node.label'); @@ -134290,7 +135465,7 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol var defaultNodePalette = function(i) {return colors[i % colors.length];}; coerce('node.color', traceOut.node.label.map(function(d, i) { - return _$color_411.addOpacity(defaultNodePalette(i), 0.8); + return _$color_473.addOpacity(defaultNodePalette(i), 0.8); })); coerce('link.label'); @@ -134301,19 +135476,19 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('link.line.width'); coerce('link.color', traceOut.link.value.map(function() { - return _$tinycolor_352(layout.paper_bgcolor).getLuminance() < 0.333 ? + return _$tinycolor_414(layout.paper_bgcolor).getLuminance() < 0.333 ? 'rgba(255, 255, 255, 0.6)' : 'rgba(0, 0, 0, 0.2)'; })); - __handleDomainDefaults_857(traceOut, layout, coerce); + __handleDomainDefaults_922(traceOut, layout, coerce); coerce('orientation'); coerce('valueformat'); coerce('valuesuffix'); coerce('arrangement'); - _$lib_539.coerceFont(coerce, 'textfont', _$lib_539.extendFlat({}, layout.font)); + _$lib_601.coerceFont(coerce, 'textfont', _$lib_601.extendFlat({}, layout.font)); var missing = function(n, i) { return traceOut.link.source.indexOf(i) === -1 && @@ -134321,7 +135496,7 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol }; if(traceOut.node.label.some(missing)) { - _$lib_539.warn('Some of the nodes are neither sources nor targets, they will not be displayed.'); + _$lib_601.warn('Some of the nodes are neither sources nor targets, they will not be displayed.'); } }; @@ -134337,20 +135512,20 @@ var _$supplyDefaults_857 = function supplyDefaults(traceIn, traceOut, defaultCol var Plot = {}; -Plot.attributes = _$attributes_853; -Plot.supplyDefaults = _$supplyDefaults_857; -Plot.calc = _$calc_855; -Plot.plot = _$plot_859; +Plot.attributes = _$attributes_918; +Plot.supplyDefaults = _$supplyDefaults_922; +Plot.calc = _$calc_920; +Plot.plot = _$plot_924; Plot.moduleType = 'trace'; Plot.name = 'sankey'; -Plot.basePlotModule = _$base_plot_854; +Plot.basePlotModule = _$base_plot_919; Plot.categories = ['noOpacity']; Plot.meta = { }; -var _$Plot_858 = Plot; +var _$Plot_923 = Plot; /** * Copyright 2012-2018, Plotly, Inc. @@ -134362,7 +135537,7 @@ var _$Plot_858 = Plot; 'use strict'; -var _$sankey_26 = _$Plot_858; +var _$sankey_26 = _$Plot_923; /** * Copyright 2012-2018, Plotly, Inc. @@ -134375,7 +135550,7 @@ var _$sankey_26 = _$Plot_858; 'use strict'; -var _$gl3d_markers_515 = { +var _$gl3d_markers_576 = { circle: '●', 'circle-open': '○', square: '■', @@ -134397,7 +135572,7 @@ var _$gl3d_markers_515 = { 'use strict'; -var _$gl3d_dashes_514 = { +var _$gl3d_dashes_575 = { solid: [[], 0], dot: [[0.5, 1], 200], dash: [[0.5, 1], 50], @@ -134406,7 +135581,7 @@ var _$gl3d_dashes_514 = { longdashdot: [[0.5, 0.7, 0.8, 1], 10] }; -var _$attributes_887 = {}; +var _$attributes_952 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -134417,18 +135592,18 @@ var _$attributes_887 = {}; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$gl3d_dashes_514 = require('../../constants/gl3d_dashes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$gl3d_dashes_575 = require('../../constants/gl3d_dashes'); */; -/* removed: var _$gl3d_markers_515 = require('../../constants/gl3d_markers'); */; -var __extendFlat_887 = _$extend_528.extendFlat; -var __overrideAll_887 = _$edit_types_569.overrideAll; +/* removed: var _$gl3d_markers_576 = require('../../constants/gl3d_markers'); */; +var __extendFlat_952 = _$extend_590.extendFlat; +var __overrideAll_952 = _$edit_types_632.overrideAll; -var __scatterLineAttrs_887 = _$attributes_862.line; -var __scatterMarkerAttrs_887 = _$attributes_862.marker; -var __scatterMarkerLineAttrs_887 = __scatterMarkerAttrs_887.line; +var __scatterLineAttrs_952 = _$attributes_927.line; +var __scatterMarkerAttrs_952 = _$attributes_927.marker; +var __scatterMarkerLineAttrs_952 = __scatterMarkerAttrs_952.line; function makeProjectionAttr(axLetter) { return { @@ -134457,22 +135632,22 @@ function makeProjectionAttr(axLetter) { }; } -var __attrs_887 = _$attributes_887 = __overrideAll_887({ - x: _$attributes_862.x, - y: _$attributes_862.y, +var __attrs_952 = _$attributes_952 = __overrideAll_952({ + x: _$attributes_927.x, + y: _$attributes_927.y, z: { valType: 'data_array', }, - text: __extendFlat_887({}, _$attributes_862.text, { + text: __extendFlat_952({}, _$attributes_927.text, { }), - hovertext: __extendFlat_887({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_952({}, _$attributes_927.hovertext, { }), - mode: __extendFlat_887({}, _$attributes_862.mode, // shouldn't this be on-par with 2D? + mode: __extendFlat_952({}, _$attributes_927.mode, // shouldn't this be on-par with 2D? {dflt: 'lines+markers'}), surfaceaxis: { valType: 'enumerated', @@ -134491,12 +135666,12 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ y: makeProjectionAttr('y'), z: makeProjectionAttr('z') }, - connectgaps: _$attributes_862.connectgaps, - line: __extendFlat_887({ - width: __scatterLineAttrs_887.width, + connectgaps: _$attributes_927.connectgaps, + line: __extendFlat_952({ + width: __scatterLineAttrs_952.width, dash: { valType: 'enumerated', - values: Object.keys(_$gl3d_dashes_514), + values: Object.keys(_$gl3d_dashes_575), dflt: 'solid', @@ -134508,55 +135683,55 @@ var __attrs_887 = _$attributes_887 = __overrideAll_887({ } }, - _$makeColorScaleAttributes_419('line') + _$makeColorScaleAttributes_481('line') ), - marker: __extendFlat_887({ // Parity with scatter.js? + marker: __extendFlat_952({ // Parity with scatter.js? symbol: { valType: 'enumerated', - values: Object.keys(_$gl3d_markers_515), + values: Object.keys(_$gl3d_markers_576), dflt: 'circle', arrayOk: true, }, - size: __extendFlat_887({}, __scatterMarkerAttrs_887.size, {dflt: 8}), - sizeref: __scatterMarkerAttrs_887.sizeref, - sizemin: __scatterMarkerAttrs_887.sizemin, - sizemode: __scatterMarkerAttrs_887.sizemode, - opacity: __extendFlat_887({}, __scatterMarkerAttrs_887.opacity, { + size: __extendFlat_952({}, __scatterMarkerAttrs_952.size, {dflt: 8}), + sizeref: __scatterMarkerAttrs_952.sizeref, + sizemin: __scatterMarkerAttrs_952.sizemin, + sizemode: __scatterMarkerAttrs_952.sizemode, + opacity: __extendFlat_952({}, __scatterMarkerAttrs_952.opacity, { arrayOk: false, }), - showscale: __scatterMarkerAttrs_887.showscale, - colorbar: __scatterMarkerAttrs_887.colorbar, + showscale: __scatterMarkerAttrs_952.showscale, + colorbar: __scatterMarkerAttrs_952.colorbar, - line: __extendFlat_887({ - width: __extendFlat_887({}, __scatterMarkerLineAttrs_887.width, {arrayOk: false}) + line: __extendFlat_952({ + width: __extendFlat_952({}, __scatterMarkerLineAttrs_952.width, {arrayOk: false}) }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ) }, - _$makeColorScaleAttributes_419('marker') + _$makeColorScaleAttributes_481('marker') ), - textposition: __extendFlat_887({}, _$attributes_862.textposition, {dflt: 'top center'}), - textfont: _$attributes_862.textfont, + textposition: __extendFlat_952({}, _$attributes_927.textposition, {dflt: 'top center'}), + textfont: _$attributes_927.textfont, - hoverinfo: __extendFlat_887({}, _$attributes_581.hoverinfo) + hoverinfo: __extendFlat_952({}, _$attributes_644.hoverinfo) }, 'calc', 'nested'); -__attrs_887.x.editType = __attrs_887.y.editType = __attrs_887.z.editType = 'calc+clearAxisTypes'; +__attrs_952.x.editType = __attrs_952.y.editType = __attrs_952.z.editType = 'calc+clearAxisTypes'; 'use strict' -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -var __vertSrc_157 = _$browser_238(["precision mediump 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_157 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}"]) +var __vertSrc_214 = _$browser_295(["precision mediump 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_214 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}"]) -var _$shaders_157 = function(gl) { - return _$createShader_206(gl, __vertSrc_157, __fragSrc_157, null, [ +var _$shaders_214 = function(gl) { + return _$createShader_263(gl, __vertSrc_214, __fragSrc_214, null, [ {name: 'position', type: 'vec3'}, {name: 'color', type: 'vec4'}, {name: 'offset', type: 'vec3'} @@ -134565,11 +135740,11 @@ var _$shaders_157 = function(gl) { 'use strict' -var _$createErrorBars_156 = createErrorBars +var _$createErrorBars_213 = createErrorBars -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -/* removed: var _$shaders_157 = require('./shaders/index') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +/* removed: var _$shaders_214 = require('./shaders/index') */; var IDENTITY = [1,0,0,0, 0,1,0,0, @@ -134591,17 +135766,17 @@ function ErrorBars(gl, buffer, vao, shader) { this.opacity = 1 } -var __proto_156 = ErrorBars.prototype +var __proto_213 = ErrorBars.prototype -__proto_156.isOpaque = function() { +__proto_213.isOpaque = function() { return this.opacity >= 1 } -__proto_156.isTransparent = function() { +__proto_213.isTransparent = function() { return this.opacity < 1 } -__proto_156.drawTransparent = __proto_156.draw = function(cameraParams) { +__proto_213.drawTransparent = __proto_213.draw = function(cameraParams) { var gl = this.gl var uniforms = this.shader.uniforms @@ -134666,7 +135841,7 @@ function emitFace(verts, x, c, d) { return offsets.length } -__proto_156.update = function(options) { +__proto_213.update = function(options) { options = options || {} if('lineWidth' in options) { @@ -134757,7 +135932,7 @@ i_loop: } } -__proto_156.dispose = function() { +__proto_213.dispose = function() { this.shader.dispose() this.buffer.dispose() this.vao.dispose() @@ -134765,8 +135940,8 @@ __proto_156.dispose = function() { function createErrorBars(options) { var gl = options.gl - var buffer = _$createBuffer_153(gl) - var vao = _$createVAO_222(gl, [ + var buffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { buffer: buffer, type: gl.FLOAT, @@ -134790,7 +135965,7 @@ function createErrorBars(options) { } ]) - var shader = _$shaders_157(gl) + var shader = _$shaders_214(gl) shader.attributes.position.location = 0 shader.attributes.color.location = 1 shader.attributes.offset.location = 2 @@ -134800,13 +135975,13 @@ function createErrorBars(options) { return result } -var _$shaders_163 = {}; -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$createShader_206 = require('gl-shader') */; +var _$shaders_220 = {}; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$createShader_263 = require('gl-shader') */; -var __vertSrc_163 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]) -var forwardFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]) -var pickFrag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]) +var __vertSrc_220 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]) +var forwardFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]) +var pickFrag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]) var ATTRIBUTES = [ {name: 'position', type: 'vec3'}, @@ -134816,15 +135991,15 @@ var ATTRIBUTES = [ {name: 'color', type: 'vec4'} ] -_$shaders_163.createShader = function(gl) { - return _$createShader_206(gl, __vertSrc_163, forwardFrag, null, ATTRIBUTES) +_$shaders_220.createShader = function(gl) { + return _$createShader_263(gl, __vertSrc_220, forwardFrag, null, ATTRIBUTES) } -_$shaders_163.createPickShader = function(gl) { - return _$createShader_206(gl, __vertSrc_163, pickFrag, null, ATTRIBUTES) +_$shaders_220.createPickShader = function(gl) { + return _$createShader_263(gl, __vertSrc_220, pickFrag, null, ATTRIBUTES) } -var _$decodeFloat_229 = decodeFloat +var _$decodeFloat_286 = decodeFloat var UINT8_VIEW = new Uint8Array(4) var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) @@ -134839,20 +136014,20 @@ function decodeFloat(x, y, z, w) { 'use strict' -var _$createLinePlot_164 = createLinePlot +var _$createLinePlot_221 = createLinePlot -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -/* removed: var _$createTexture2D_218 = require('gl-texture2d') */; -/* removed: var _$decodeFloat_229 = require('glsl-read-float') */; -/* removed: var _$searchBounds_71 = require('binary-search-bounds') */; -/* removed: var _$wrappedNDArrayCtor_277 = require('ndarray') */; -/* removed: var _$shaders_163 = require('./lib/shaders') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +/* removed: var _$createTexture2D_275 = require('gl-texture2d') */; +/* removed: var _$decodeFloat_286 = require('glsl-read-float') */; +/* removed: var _$searchBounds_72 = require('binary-search-bounds') */; +/* removed: var _$wrappedNDArrayCtor_335 = require('ndarray') */; +/* removed: var _$shaders_220 = require('./lib/shaders') */; -var __createShader_164 = _$shaders_163.createShader -var __createPickShader_164 = _$shaders_163.createPickShader +var __createShader_221 = _$shaders_220.createShader +var __createPickShader_221 = _$shaders_220.createPickShader -var __identity_164 = [1, 0, 0, 0, +var __identity_221 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] @@ -134904,31 +136079,31 @@ function LinePlot (gl, shader, pickShader, buffer, vao, texture) { this.pixelRatio = 1 } -var __proto_164 = LinePlot.prototype +var __proto_221 = LinePlot.prototype -__proto_164.isTransparent = function () { +__proto_221.isTransparent = function () { return this.opacity < 1 } -__proto_164.isOpaque = function () { +__proto_221.isOpaque = function () { return this.opacity >= 1 } -__proto_164.pickSlots = 1 +__proto_221.pickSlots = 1 -__proto_164.setPickBase = function (id) { +__proto_221.setPickBase = function (id) { this.pickId = id } -__proto_164.drawTransparent = __proto_164.draw = function (camera) { +__proto_221.drawTransparent = __proto_221.draw = function (camera) { var gl = this.gl var shader = this.shader var vao = this.vao shader.bind() shader.uniforms = { - model: camera.model || __identity_164, - view: camera.view || __identity_164, - projection: camera.projection || __identity_164, + model: camera.model || __identity_221, + view: camera.view || __identity_221, + projection: camera.projection || __identity_221, clipBounds: filterClipBounds(this.clipBounds), dashTexture: this.texture.bind(), dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], @@ -134941,15 +136116,15 @@ __proto_164.drawTransparent = __proto_164.draw = function (camera) { vao.unbind() } -__proto_164.drawPick = function (camera) { +__proto_221.drawPick = function (camera) { var gl = this.gl var shader = this.pickShader var vao = this.vao shader.bind() shader.uniforms = { - model: camera.model || __identity_164, - view: camera.view || __identity_164, - projection: camera.projection || __identity_164, + model: camera.model || __identity_221, + view: camera.view || __identity_221, + projection: camera.projection || __identity_221, pickId: this.pickId, clipBounds: filterClipBounds(this.clipBounds), screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], @@ -134960,7 +136135,7 @@ __proto_164.drawPick = function (camera) { vao.unbind() } -__proto_164.update = function (options) { +__proto_221.update = function (options) { var i, j this.dirty = true @@ -135084,12 +136259,12 @@ __proto_164.update = function (options) { prefixSum[i] = prefixSum[i - 1] + prefixSum[i] } - var dashTexture = _$wrappedNDArrayCtor_277(new Array(256 * 4), [256, 1, 4]) + var dashTexture = _$wrappedNDArrayCtor_335(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 (_$searchBounds_71.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { + if (_$searchBounds_72.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { dashTexture.set(i, 0, 0, 0) } else { dashTexture.set(i, 0, 0, 255) @@ -135100,25 +136275,25 @@ __proto_164.update = function (options) { } } -__proto_164.dispose = function () { +__proto_221.dispose = function () { this.shader.dispose() this.vao.dispose() this.buffer.dispose() } -__proto_164.pick = function (selection) { +__proto_221.pick = function (selection) { if (!selection) { return null } if (selection.id !== this.pickId) { return null } - var tau = _$decodeFloat_229( + var tau = _$decodeFloat_286( selection.value[0], selection.value[1], selection.value[2], 0) - var index = _$searchBounds_71.le(this.arcLength, tau) + var index = _$searchBounds_72.le(this.arcLength, tau) if (index < 0) { return null } @@ -135147,22 +136322,22 @@ __proto_164.pick = function (selection) { function createLinePlot (options) { var gl = options.gl || (options.scene && options.scene.gl) - var shader = __createShader_164(gl) + var shader = __createShader_221(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_164(gl) + var pickShader = __createPickShader_221(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_153(gl) - var vao = _$createVAO_222(gl, [ + var buffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { 'buffer': buffer, 'size': 3, @@ -135196,11 +136371,11 @@ function createLinePlot (options) { ]) // Create texture for dash pattern - var defaultTexture = _$wrappedNDArrayCtor_277(new Array(256 * 4), [256, 1, 4]) + var defaultTexture = _$wrappedNDArrayCtor_335(new Array(256 * 4), [256, 1, 4]) for (var i = 0; i < 256 * 4; ++i) { defaultTexture.data[i] = 255 } - var texture = _$createTexture2D_218(gl, defaultTexture) + var texture = _$createTexture2D_275(gl, defaultTexture) texture.wrap = gl.REPEAT var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) @@ -135210,9 +136385,9 @@ function createLinePlot (options) { "use strict" -/* removed: var _$createText_367 = require("vectorize-text") */; +/* removed: var _$createText_429 = require("vectorize-text") */; -var _$getGlyph_200 = getGlyph +var _$getGlyph_257 = getGlyph var GLYPH_CACHE = {} @@ -135226,13 +136401,13 @@ function getGlyph(symbol, font) { } //Get line and triangle meshes for glyph - var lineSymbol = _$createText_367(symbol, { + var lineSymbol = _$createText_429(symbol, { textAlign: "center", textBaseline: "middle", lineHeight: 1.0, font: font }) - var triSymbol = _$createText_367(symbol, { + var triSymbol = _$createText_429(symbol, { triangles: true, textAlign: "center", textBaseline: "middle", @@ -135253,56 +136428,56 @@ function getGlyph(symbol, font) { //Save cached symbol return fontCache[symbol] = [triSymbol, lineSymbol, bounds] } -var _$shaders_201 = {}; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$browser_238 = require('glslify') */; +var _$shaders_258 = {}; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; -var perspectiveVertSrc = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n"]) -var __pickFragSrc_201 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}"]) +var perspectiveVertSrc = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n"]) +var __pickFragSrc_258 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}"]) -var __ATTRIBUTES_201 = [ +var __ATTRIBUTES_258 = [ {name: 'position', type: 'vec3'}, {name: 'color', type: 'vec4'}, {name: 'glyph', type: 'vec2'}, {name: 'id', type: 'vec4'} ] -var __perspective_201 = { +var __perspective_258 = { vertex: perspectiveVertSrc, fragment: drawFragSrc, - attributes: __ATTRIBUTES_201 + attributes: __ATTRIBUTES_258 }, ortho = { vertex: orthographicVertSrc, fragment: drawFragSrc, - attributes: __ATTRIBUTES_201 + attributes: __ATTRIBUTES_258 }, - __project_201 = { + __project_258 = { vertex: projectionVertSrc, fragment: drawFragSrc, - attributes: __ATTRIBUTES_201 + attributes: __ATTRIBUTES_258 }, pickPerspective = { vertex: perspectiveVertSrc, - fragment: __pickFragSrc_201, - attributes: __ATTRIBUTES_201 + fragment: __pickFragSrc_258, + attributes: __ATTRIBUTES_258 }, pickOrtho = { vertex: orthographicVertSrc, - fragment: __pickFragSrc_201, - attributes: __ATTRIBUTES_201 + fragment: __pickFragSrc_258, + attributes: __ATTRIBUTES_258 }, pickProject = { vertex: projectionVertSrc, - fragment: __pickFragSrc_201, - attributes: __ATTRIBUTES_201 + fragment: __pickFragSrc_258, + attributes: __ATTRIBUTES_258 } -function __createShader_201(gl, src) { - var shader = _$createShader_206(gl, src) +function __createShader_258(gl, src) { + var shader = _$createShader_263(gl, src) var attr = shader.attributes attr.position.location = 0 attr.color.location = 1 @@ -135311,42 +136486,42 @@ function __createShader_201(gl, src) { return shader } -_$shaders_201.createPerspective = function(gl) { - return __createShader_201(gl, __perspective_201) +_$shaders_258.createPerspective = function(gl) { + return __createShader_258(gl, __perspective_258) } -_$shaders_201.createOrtho = function(gl) { - return __createShader_201(gl, ortho) +_$shaders_258.createOrtho = function(gl) { + return __createShader_258(gl, ortho) } -_$shaders_201.createProject = function(gl) { - return __createShader_201(gl, __project_201) +_$shaders_258.createProject = function(gl) { + return __createShader_258(gl, __project_258) } -_$shaders_201.createPickPerspective = function(gl) { - return __createShader_201(gl, pickPerspective) +_$shaders_258.createPickPerspective = function(gl) { + return __createShader_258(gl, pickPerspective) } -_$shaders_201.createPickOrtho = function(gl) { - return __createShader_201(gl, pickOrtho) +_$shaders_258.createPickOrtho = function(gl) { + return __createShader_258(gl, pickOrtho) } -_$shaders_201.createPickProject = function(gl) { - return __createShader_201(gl, pickProject) +_$shaders_258.createPickProject = function(gl) { + return __createShader_258(gl, pickProject) } 'use strict' -/* removed: var _$createBuffer_153 = require('gl-buffer') */; -/* removed: var _$createVAO_222 = require('gl-vao') */; -/* removed: var _$pool_360 = require('typedarray-pool') */; -/* removed: var _$multiply_175 = require('gl-mat4/multiply') */; -/* removed: var _$shaders_201 = require('./lib/shaders') */; -/* removed: var _$getGlyph_200 = require('./lib/glyphs') */; +/* removed: var _$createBuffer_210 = require('gl-buffer') */; +/* removed: var _$createVAO_279 = require('gl-vao') */; +/* removed: var _$pool_422 = require('typedarray-pool') */; +/* removed: var _$multiply_232 = require('gl-mat4/multiply') */; +/* removed: var _$shaders_258 = require('./lib/shaders') */; +/* removed: var _$getGlyph_257 = require('./lib/glyphs') */; -var __IDENTITY_202 = [1,0,0,0, +var __IDENTITY_259 = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] -var _$createPointCloud_202 = createPointCloud +var _$createPointCloud_259 = createPointCloud -function __transformMat4_202(x, m) { +function __transformMat4_259(x, m) { var x0 = x[0] var x1 = x[1] var x2 = x[2] @@ -135358,10 +136533,10 @@ function __transformMat4_202(x, m) { return x } -function __project_202(p, v, m, x) { - __transformMat4_202(x, x, m) - __transformMat4_202(x, x, v) - return __transformMat4_202(x, x, p) +function __project_259(p, v, m, x) { + __transformMat4_259(x, x, m) + __transformMat4_259(x, x, v) + return __transformMat4_259(x, x, p) } function clampVec(v) { @@ -135439,15 +136614,15 @@ function PointCloud( this.dirty = true } -var __proto_202 = PointCloud.prototype +var __proto_259 = PointCloud.prototype -__proto_202.pickSlots = 1 +__proto_259.pickSlots = 1 -__proto_202.setPickBase = function(pickBase) { +__proto_259.setPickBase = function(pickBase) { this.pickId = pickBase } -__proto_202.isTransparent = function() { +__proto_259.isTransparent = function() { if(this.opacity < 1) { return true } @@ -135459,7 +136634,7 @@ __proto_202.isTransparent = function() { return false } -__proto_202.isOpaque = function() { +__proto_259.isOpaque = function() { if(this.opacity >= 1) { return true } @@ -135476,11 +136651,11 @@ var U_VEC = [0,0,0] var V_VEC = [0,0,0] var MU_VEC = [0,0,0,1] var MV_VEC = [0,0,0,1] -var SCRATCH_MATRIX = __IDENTITY_202.slice() +var SCRATCH_MATRIX = __IDENTITY_259.slice() var SCRATCH_VEC = [0,0,0] var CLIP_BOUNDS = [[0,0,0], [0,0,0]] -function __zeroVec_202(a) { +function __zeroVec_259(a) { a[0] = a[1] = a[2] = 0 return a } @@ -135516,9 +136691,9 @@ function drawProject(shader, points, camera, transparent, forceDraw) { var gl = points.gl var uniforms = shader.uniforms - var model = camera.model || __IDENTITY_202 - var view = camera.view || __IDENTITY_202 - var projection = camera.projection || __IDENTITY_202 + var model = camera.model || __IDENTITY_259 + var view = camera.view || __IDENTITY_259 + var projection = camera.projection || __IDENTITY_259 var bounds = points.axesBounds var clipBounds = getClipBounds(points.clipBounds) @@ -135567,20 +136742,20 @@ function drawProject(shader, points, camera, transparent, forceDraw) { } else { pmodel[12+i] = bounds[1][i] } - _$multiply_175(pmodel, model, pmodel) + _$multiply_232(pmodel, model, pmodel) uniforms.model = pmodel //Compute initial axes var u = (i+1)%3 var v = (i+2)%3 - var du = __zeroVec_202(U_VEC) - var dv = __zeroVec_202(V_VEC) + var du = __zeroVec_259(U_VEC) + var dv = __zeroVec_259(V_VEC) du[u] = 1 dv[v] = 1 //Align orientation relative to viewer - var mdu = __project_202(projection, view, model, augment(MU_VEC, du)) - var mdv = __project_202(projection, view, model, augment(MV_VEC, dv)) + var mdu = __project_259(projection, view, model, augment(MU_VEC, du)) + var mdv = __project_259(projection, view, model, augment(MV_VEC, dv)) if(Math.abs(mdu[1]) > Math.abs(mdv[1])) { var tmp = mdu mdu = mdv @@ -135638,9 +136813,9 @@ function drawFull(shader, pshader, points, camera, transparent, forceDraw) { shader.bind() var uniforms = shader.uniforms - uniforms.model = camera.model || __IDENTITY_202 - uniforms.view = camera.view || __IDENTITY_202 - uniforms.projection = camera.projection || __IDENTITY_202 + uniforms.model = camera.model || __IDENTITY_259 + uniforms.view = camera.view || __IDENTITY_259 + uniforms.projection = camera.projection || __IDENTITY_259 VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight @@ -135672,22 +136847,22 @@ function drawFull(shader, pshader, points, camera, transparent, forceDraw) { points.vao.unbind() } -__proto_202.draw = function(camera) { +__proto_259.draw = function(camera) { var shader = this.useOrtho ? this.orthoShader : this.shader drawFull(shader, this.projectShader, this, camera, false, false) } -__proto_202.drawTransparent = function(camera) { +__proto_259.drawTransparent = function(camera) { var shader = this.useOrtho ? this.orthoShader : this.shader drawFull(shader, this.projectShader, this, camera, true, false) } -__proto_202.drawPick = function(camera) { +__proto_259.drawPick = function(camera) { var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader drawFull(shader, this.pickProjectShader, this, camera, false, true) } -__proto_202.pick = function(selected) { +__proto_259.pick = function(selected) { if(!selected) { return null } @@ -135709,7 +136884,7 @@ __proto_202.pick = function(selected) { return result } -__proto_202.highlight = function(selection) { +__proto_259.highlight = function(selection) { if(!selection) { this.highlightId = [1,1,1,1] } else { @@ -135721,7 +136896,7 @@ __proto_202.highlight = function(selection) { } } -__proto_202.update = function(options) { +__proto_259.update = function(options) { options = options || {} @@ -135807,11 +136982,11 @@ count_loop: var glyphData if(Array.isArray(glyphs)) { - glyphData = _$getGlyph_200(glyphs[i], font) + glyphData = _$getGlyph_257(glyphs[i], font) } else if(glyphs) { - glyphData = _$getGlyph_200(glyphs, font) + glyphData = _$getGlyph_257(glyphs, font) } else { - glyphData = _$getGlyph_200('●', font) + glyphData = _$getGlyph_257('●', font) } var glyphMesh = glyphData[0] var glyphLines = glyphData[1] @@ -135824,10 +136999,10 @@ count_loop: //Preallocate data var vertexCount = triVertexCount + lineVertexCount - var positionArray = _$pool_360.mallocFloat(3*vertexCount) - var colorArray = _$pool_360.mallocFloat(4*vertexCount) - var glyphArray = _$pool_360.mallocFloat(2*vertexCount) - var idArray = _$pool_360.mallocUint32(vertexCount) + var positionArray = _$pool_422.mallocFloat(3*vertexCount) + var colorArray = _$pool_422.mallocFloat(4*vertexCount) + var glyphArray = _$pool_422.mallocFloat(2*vertexCount) + var idArray = _$pool_422.mallocUint32(vertexCount) var textOffset = [0,alignment[1]] @@ -135854,11 +137029,11 @@ fill_loop: var glyphData if(Array.isArray(glyphs)) { - glyphData = _$getGlyph_200(glyphs[i], font) + glyphData = _$getGlyph_257(glyphs[i], font) } else if(glyphs) { - glyphData = _$getGlyph_200(glyphs, font) + glyphData = _$getGlyph_257(glyphs, font) } else { - glyphData = _$getGlyph_200('●', font) + glyphData = _$getGlyph_257('●', font) } var glyphMesh = glyphData[0] var glyphLines = glyphData[1] @@ -136000,10 +137175,10 @@ fill_loop: this.glyphBuffer.update(glyphArray) this.idBuffer.update(new Uint32Array(idArray)) - _$pool_360.free(positionArray) - _$pool_360.free(colorArray) - _$pool_360.free(glyphArray) - _$pool_360.free(idArray) + _$pool_422.free(positionArray) + _$pool_422.free(colorArray) + _$pool_422.free(glyphArray) + _$pool_422.free(idArray) //Update bounds this.bounds = [lowerBound, upperBound] @@ -136015,7 +137190,7 @@ fill_loop: this.pointCount = points.length } -__proto_202.dispose = function() { +__proto_259.dispose = function() { //Shaders this.shader.dispose() this.orthoShader.dispose() @@ -136035,18 +137210,18 @@ __proto_202.dispose = function() { function createPointCloud(options) { var gl = options.gl - var shader = _$shaders_201.createPerspective(gl) - var orthoShader = _$shaders_201.createOrtho(gl) - var projectShader = _$shaders_201.createProject(gl) - var pickPerspectiveShader = _$shaders_201.createPickPerspective(gl) - var pickOrthoShader = _$shaders_201.createPickOrtho(gl) - var pickProjectShader = _$shaders_201.createPickProject(gl) - - var pointBuffer = _$createBuffer_153(gl) - var colorBuffer = _$createBuffer_153(gl) - var glyphBuffer = _$createBuffer_153(gl) - var idBuffer = _$createBuffer_153(gl) - var vao = _$createVAO_222(gl, [ + var shader = _$shaders_258.createPerspective(gl) + var orthoShader = _$shaders_258.createOrtho(gl) + var projectShader = _$shaders_258.createProject(gl) + var pickPerspectiveShader = _$shaders_258.createPickPerspective(gl) + var pickOrthoShader = _$shaders_258.createPickOrtho(gl) + var pickProjectShader = _$shaders_258.createPickProject(gl) + + var pointBuffer = _$createBuffer_210(gl) + var colorBuffer = _$createBuffer_210(gl) + var glyphBuffer = _$createBuffer_210(gl) + var idBuffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { buffer: pointBuffer, size: 3, @@ -136100,13 +137275,13 @@ function createPointCloud(options) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -/* removed: var _$normalize_99 = require('color-normalize'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +/* removed: var _$normalize_100 = require('color-normalize'); */; -/* removed: var _$colorscale_426 = require('../components/colorscale'); */; -var colorDflt = _$attributes_410.defaultLine; +/* removed: var _$colorscale_488 = require('../components/colorscale'); */; +var colorDflt = _$attributes_472.defaultLine; -var colorDfltRgba = _$normalize_99(colorDflt); +var colorDfltRgba = _$normalize_100(colorDflt); var opacityDflt = 1; function calculateColor(colorIn, opacityIn) { @@ -136116,15 +137291,15 @@ function calculateColor(colorIn, opacityIn) { } function validateColor(colorIn) { - if(_$fastIsnumeric_139(colorIn)) return colorDfltRgba; + if(_$fastIsnumeric_196(colorIn)) return colorDfltRgba; - var colorOut = _$normalize_99(colorIn); + var colorOut = _$normalize_100(colorIn); return colorOut.length ? colorOut : colorDfltRgba; } function validateOpacity(opacityIn) { - return _$fastIsnumeric_139(opacityIn) ? opacityIn : opacityDflt; + return _$fastIsnumeric_196(opacityIn) ? opacityIn : opacityDflt; } function formatColor(containerIn, opacityIn, len) { @@ -136136,8 +137311,8 @@ function formatColor(containerIn, opacityIn, len) { var sclFunc, getColor, getOpacity, colori, opacityi; if(containerIn.colorscale !== undefined) { - sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( containerIn.colorscale, containerIn.cmin, containerIn.cmax @@ -136151,7 +137326,7 @@ function formatColor(containerIn, opacityIn, len) { if(isArrayColorIn) { getColor = function(c, i) { // FIXME: there is double work, considering that sclFunc does the opposite - return c[i] === undefined ? colorDfltRgba : _$normalize_99(sclFunc(c[i])); + return c[i] === undefined ? colorDfltRgba : _$normalize_100(sclFunc(c[i])); }; } else getColor = validateColor; @@ -136170,12 +137345,12 @@ function formatColor(containerIn, opacityIn, len) { colorOut[i] = calculateColor(colori, opacityi); } } - else colorOut = calculateColor(_$normalize_99(colorIn), opacityIn); + else colorOut = calculateColor(_$normalize_100(colorIn), opacityIn); return colorOut; } -var _$formatColor_535 = formatColor; +var _$formatColor_597 = formatColor; /** * Copyright 2012-2018, Plotly, Inc. @@ -136188,12 +137363,12 @@ var _$formatColor_535 = formatColor; 'use strict'; -/* removed: var _$makeComputeError_440 = require('../../components/errorbars/compute_error'); */; +/* removed: var _$makeComputeError_502 = require('../../components/errorbars/compute_error'); */; function calculateAxisErrors(data, params, scaleFactor) { if(!params || !params.visible) return null; - var computeError = _$makeComputeError_440(params); + var computeError = _$makeComputeError_502(params); var result = new Array(data.length); for(var i = 0; i < data.length; i++) { @@ -136244,7 +137419,7 @@ function calculateErrors(data, scaleFactor) { return errorBounds; } -var _$calculateErrors_889 = calculateErrors; +var _$calculateErrors_954 = calculateErrors; /** * Copyright 2012-2018, Plotly, Inc. @@ -136257,20 +137432,20 @@ var _$calculateErrors_889 = calculateErrors; 'use strict'; -/* removed: var _$createLinePlot_164 = require('gl-line3d'); */; -/* removed: var _$createPointCloud_202 = require('gl-scatter3d'); */; -/* removed: var _$createErrorBars_156 = require('gl-error3d'); */; -/* removed: var _$createSimplicialMesh_187 = require('gl-mesh3d'); */; -/* removed: var _$triangulate_129 = require('delaunay-triangulate'); */; +/* removed: var _$createLinePlot_221 = require('gl-line3d'); */; +/* removed: var _$createPointCloud_259 = require('gl-scatter3d'); */; +/* removed: var _$createErrorBars_213 = require('gl-error3d'); */; +/* removed: var _$createSimplicialMesh_244 = require('gl-mesh3d'); */; +/* removed: var _$triangulate_132 = require('delaunay-triangulate'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$str2RgbaArray_561 = require('../../lib/str2rgbarray'); */; -/* removed: var _$formatColor_535 = require('../../lib/gl_format_color'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$gl3d_dashes_514 = require('../../constants/gl3d_dashes'); */; -/* removed: var _$gl3d_markers_515 = require('../../constants/gl3d_markers'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$str2RgbaArray_624 = require('../../lib/str2rgbarray'); */; +/* removed: var _$formatColor_597 = require('../../lib/gl_format_color'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../scatter/make_bubble_size_func'); */; +/* removed: var _$gl3d_dashes_575 = require('../../constants/gl3d_dashes'); */; +/* removed: var _$gl3d_markers_576 = require('../../constants/gl3d_markers'); */; -/* removed: var _$calculateErrors_889 = require('./calc_errors'); */; +/* removed: var _$calculateErrors_954 = require('./calc_errors'); */; function LineWithMarkers(scene, uid) { this.scene = scene; @@ -136291,9 +137466,9 @@ function LineWithMarkers(scene, uid) { this.data = null; } -var __proto_890 = LineWithMarkers.prototype; +var __proto_955 = LineWithMarkers.prototype; -__proto_890.handlePick = function(selection) { +__proto_955.handlePick = function(selection) { if(selection.object && (selection.object === this.linePlot || selection.object === this.delaunayMesh || @@ -136342,7 +137517,7 @@ function constructDelaunay(points, color, axis) { filteredPoints.push([p[u], p[v]]); filteredIds.push(i); } - var cells = _$triangulate_129(filteredPoints); + var cells = _$triangulate_132(filteredPoints); for(i = 0; i < cells.length; ++i) { var c = cells[i]; for(var j = 0; j < c.length; ++j) { @@ -136368,7 +137543,7 @@ function calculateErrorParams(errors) { if(!e) continue; capSize[i] = e.width / 2; // ballpark rescaling - color[i] = _$str2RgbaArray_561(e.color); + color[i] = _$str2RgbaArray_624(e.color); lineWidth = e.thickness; } @@ -136394,13 +137569,13 @@ function calculateSize(sizeIn, sizeFn) { } function calculateSymbol(symbolIn) { - return _$gl3d_markers_515[symbolIn]; + return _$gl3d_markers_576[symbolIn]; } function formatParam(paramIn, len, calculate, dflt, extraFn) { var paramOut = null; - if(_$lib_539.isArrayOrTypedArray(paramIn)) { + if(_$lib_601.isArrayOrTypedArray(paramIn)) { paramOut = []; for(var i = 0; i < len; i++) { @@ -136409,7 +137584,7 @@ function formatParam(paramIn, len, calculate, dflt, extraFn) { } } - else paramOut = calculate(paramIn, _$lib_539.identity); + else paramOut = calculate(paramIn, _$lib_601.identity); return paramOut; } @@ -136459,26 +137634,26 @@ function convertPlotlyOptions(scene, data) { }; if('line' in data) { - params.lineColor = _$formatColor_535(line, 1, len); + params.lineColor = _$formatColor_597(line, 1, len); params.lineWidth = line.width; params.lineDashes = line.dash; } if('marker' in data) { - var sizeFn = _$makeBubbleSizeFn_879(data); + var sizeFn = _$makeBubbleSizeFn_944(data); - params.scatterColor = _$formatColor_535(marker, 1, len); + params.scatterColor = _$formatColor_597(marker, 1, len); params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn); params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, '●'); params.scatterLineWidth = marker.line.width; // arrayOk === false - params.scatterLineColor = _$formatColor_535(marker.line, 1, len); + params.scatterLineColor = _$formatColor_597(marker.line, 1, len); params.scatterAngle = 0; } if('textposition' in data) { params.textOffset = calculateTextOffset(data.textposition); // arrayOk === false - params.textColor = _$formatColor_535(data.textfont, 1, len); - params.textSize = formatParam(data.textfont.size, len, _$lib_539.identity, 12); + params.textColor = _$formatColor_597(data.textfont, 1, len); + params.textSize = formatParam(data.textfont.size, len, _$lib_601.identity, 12); params.textFont = data.textfont.family; // arrayOk === false params.textAngle = 0; } @@ -136495,7 +137670,7 @@ function convertPlotlyOptions(scene, data) { } } - params.errorBounds = _$calculateErrors_889(data, scaleFactor); + params.errorBounds = _$calculateErrors_954(data, scaleFactor); var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]); params.errorColor = errorParams.color; @@ -136503,7 +137678,7 @@ function convertPlotlyOptions(scene, data) { params.errorCapSize = errorParams.capSize; params.delaunayAxis = data.surfaceaxis; - params.delaunayColor = _$str2RgbaArray_561(data.surfacecolor); + params.delaunayColor = _$str2RgbaArray_624(data.surfacecolor); return params; } @@ -136522,13 +137697,13 @@ function arrayToColor(color) { return null; } -__proto_890.update = function(data) { +__proto_955.update = function(data) { var gl = this.scene.glplot.gl, lineOptions, scatterOptions, errorOptions, textOptions, - dashPattern = _$gl3d_dashes_514.solid; + dashPattern = _$gl3d_dashes_575.solid; // Save data this.data = data; @@ -136540,8 +137715,8 @@ __proto_890.update = function(data) { this.mode = options.mode; } if('lineDashes' in options) { - if(options.lineDashes in _$gl3d_dashes_514) { - dashPattern = _$gl3d_dashes_514[options.lineDashes]; + if(options.lineDashes in _$gl3d_dashes_575) { + dashPattern = _$gl3d_dashes_575[options.lineDashes]; } } @@ -136565,7 +137740,7 @@ __proto_890.update = function(data) { if(this.mode.indexOf('lines') !== -1) { if(this.linePlot) this.linePlot.update(lineOptions); else { - this.linePlot = _$createLinePlot_164(lineOptions); + this.linePlot = _$createLinePlot_221(lineOptions); this.linePlot._trace = this; this.scene.glplot.add(this.linePlot); } @@ -136597,7 +137772,7 @@ __proto_890.update = function(data) { if(this.mode.indexOf('markers') !== -1) { if(this.scatterPlot) this.scatterPlot.update(scatterOptions); else { - this.scatterPlot = _$createPointCloud_202(scatterOptions); + this.scatterPlot = _$createPointCloud_259(scatterOptions); this.scatterPlot._trace = this; this.scatterPlot.highlightScale = 1; this.scene.glplot.add(this.scatterPlot); @@ -136628,7 +137803,7 @@ __proto_890.update = function(data) { if(this.mode.indexOf('text') !== -1) { if(this.textMarkers) this.textMarkers.update(textOptions); else { - this.textMarkers = _$createPointCloud_202(textOptions); + this.textMarkers = _$createPointCloud_259(textOptions); this.textMarkers._trace = this; this.textMarkers.highlightScale = 1; this.scene.glplot.add(this.textMarkers); @@ -136657,7 +137832,7 @@ __proto_890.update = function(data) { this.errorBars = null; } } else if(options.errorBounds) { - this.errorBars = _$createErrorBars_156(errorOptions); + this.errorBars = _$createErrorBars_213(errorOptions); this.errorBars._trace = this; this.scene.glplot.add(this.errorBars); } @@ -136674,7 +137849,7 @@ __proto_890.update = function(data) { this.delaunayMesh.update(delaunayOptions); } else { delaunayOptions.gl = gl; - this.delaunayMesh = _$createSimplicialMesh_187(delaunayOptions); + this.delaunayMesh = _$createSimplicialMesh_244(delaunayOptions); this.delaunayMesh._trace = this; this.scene.glplot.add(this.delaunayMesh); } @@ -136685,7 +137860,7 @@ __proto_890.update = function(data) { } }; -__proto_890.dispose = function() { +__proto_955.dispose = function() { if(this.linePlot) { this.scene.glplot.remove(this.linePlot); this.linePlot.dispose(); @@ -136714,7 +137889,7 @@ function createLineWithMarkers(scene, data) { return plot; } -var _$createLineWithMarkers_890 = createLineWithMarkers; +var _$createLineWithMarkers_955 = createLineWithMarkers; /** * Copyright 2012-2018, Plotly, Inc. @@ -136727,23 +137902,23 @@ var _$createLineWithMarkers_890 = createLineWithMarkers; 'use strict'; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; -/* removed: var _$attributes_887 = require('./attributes'); */; +/* removed: var _$attributes_952 = require('./attributes'); */; -var _$supplyDefaults_891 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_956 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_887, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_952, attr, dflt); } - var len = __handleXYZDefaults_891(traceIn, traceOut, coerce, layout); + var len = __handleXYZDefaults_956(traceIn, traceOut, coerce, layout); if(!len) { traceOut.visible = false; return; @@ -136753,17 +137928,17 @@ var _$supplyDefaults_891 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_884.hasLines(traceOut)) { + if(_$subtypes_949.hasLines(traceOut)) { coerce('connectgaps'); - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {noSelect: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce, {noSelect: true}); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce, {noSelect: true}); } var lineColor = (traceOut.line || {}).color, @@ -136779,19 +137954,19 @@ var _$supplyDefaults_891 = function supplyDefaults(traceIn, traceOut, defaultCol } } - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'z'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y', inherit: 'z'}); errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'z'}); }; -function __handleXYZDefaults_891(traceIn, traceOut, coerce, layout) { +function __handleXYZDefaults_956(traceIn, traceOut, coerce, layout) { var len = 0, x = coerce('x'), y = coerce('y'), z = coerce('z'); - var handleCalendarDefaults = _$registry_668.getComponentMethod('calendars', 'handleTraceDefaults'); + var handleCalendarDefaults = _$registry_731.getComponentMethod('calendars', 'handleTraceDefaults'); handleCalendarDefaults(traceIn, traceOut, ['x', 'y', 'z'], layout); if(x && y && z) { @@ -136815,23 +137990,23 @@ function __handleXYZDefaults_891(traceIn, traceOut, coerce, layout) { var Scatter3D = {}; -Scatter3D.plot = _$createLineWithMarkers_890; -Scatter3D.attributes = _$attributes_887; -Scatter3D.markerSymbols = _$gl3d_markers_515; -Scatter3D.supplyDefaults = _$supplyDefaults_891; -Scatter3D.colorbar = _$colorbar_866; -Scatter3D.calc = _$calc_888; +Scatter3D.plot = _$createLineWithMarkers_955; +Scatter3D.attributes = _$attributes_952; +Scatter3D.markerSymbols = _$gl3d_markers_576; +Scatter3D.supplyDefaults = _$supplyDefaults_956; +Scatter3D.colorbar = _$colorbar_931; +Scatter3D.calc = _$calc_953; Scatter3D.moduleType = 'trace'; Scatter3D.name = 'scatter3d'; -Scatter3D.basePlotModule = _$gl3d_627; +Scatter3D.basePlotModule = _$gl3d_689; Scatter3D.categories = ['gl3d', 'symbols', 'markerColorscale', 'showLegend']; Scatter3D.meta = { }; -var _$Scatter3D_892 = Scatter3D; +var _$Scatter3D_957 = Scatter3D; /** * Copyright 2012-2018, Plotly, Inc. @@ -136843,7 +138018,7 @@ var _$Scatter3D_892 = Scatter3D; 'use strict'; -var _$scatter3d_27 = _$Scatter3D_892; +var _$scatter3d_27 = _$Scatter3D_957; /** * Copyright 2012-2018, Plotly, Inc. @@ -136855,18 +138030,18 @@ var _$scatter3d_27 = _$Scatter3D_892; 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_893 = _$extend_528.extendFlat; +var __extendFlat_958 = _$extend_590.extendFlat; -var __scatterMarkerAttrs_893 = _$attributes_862.marker, - __scatterLineAttrs_893 = _$attributes_862.line, - __scatterMarkerLineAttrs_893 = __scatterMarkerAttrs_893.line; +var __scatterMarkerAttrs_958 = _$attributes_927.marker, + __scatterLineAttrs_958 = _$attributes_927.line, + __scatterMarkerLineAttrs_958 = __scatterMarkerAttrs_958.line; -var _$attributes_893 = { +var _$attributes_958 = { carpet: { valType: 'string', @@ -136883,56 +138058,56 @@ var _$attributes_893 = { editType: 'calc', }, - mode: __extendFlat_893({}, _$attributes_862.mode, {dflt: 'markers'}), - text: __extendFlat_893({}, _$attributes_862.text, { + mode: __extendFlat_958({}, _$attributes_927.mode, {dflt: 'markers'}), + text: __extendFlat_958({}, _$attributes_927.text, { }), line: { - color: __scatterLineAttrs_893.color, - width: __scatterLineAttrs_893.width, - dash: __scatterLineAttrs_893.dash, - shape: __extendFlat_893({}, __scatterLineAttrs_893.shape, + color: __scatterLineAttrs_958.color, + width: __scatterLineAttrs_958.width, + dash: __scatterLineAttrs_958.dash, + shape: __extendFlat_958({}, __scatterLineAttrs_958.shape, {values: ['linear', 'spline']}), - smoothing: __scatterLineAttrs_893.smoothing, + smoothing: __scatterLineAttrs_958.smoothing, editType: 'calc' }, - connectgaps: _$attributes_862.connectgaps, - fill: __extendFlat_893({}, _$attributes_862.fill, { + connectgaps: _$attributes_927.connectgaps, + fill: __extendFlat_958({}, _$attributes_927.fill, { values: ['none', 'toself', 'tonext'], }), - fillcolor: _$attributes_862.fillcolor, - marker: __extendFlat_893({ - symbol: __scatterMarkerAttrs_893.symbol, - opacity: __scatterMarkerAttrs_893.opacity, - maxdisplayed: __scatterMarkerAttrs_893.maxdisplayed, - size: __scatterMarkerAttrs_893.size, - sizeref: __scatterMarkerAttrs_893.sizeref, - sizemin: __scatterMarkerAttrs_893.sizemin, - sizemode: __scatterMarkerAttrs_893.sizemode, - line: __extendFlat_893({ - width: __scatterMarkerLineAttrs_893.width, + fillcolor: _$attributes_927.fillcolor, + marker: __extendFlat_958({ + symbol: __scatterMarkerAttrs_958.symbol, + opacity: __scatterMarkerAttrs_958.opacity, + maxdisplayed: __scatterMarkerAttrs_958.maxdisplayed, + size: __scatterMarkerAttrs_958.size, + sizeref: __scatterMarkerAttrs_958.sizeref, + sizemin: __scatterMarkerAttrs_958.sizemin, + sizemode: __scatterMarkerAttrs_958.sizemode, + line: __extendFlat_958({ + width: __scatterMarkerLineAttrs_958.width, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker'.line) + _$makeColorScaleAttributes_481('marker'.line) ), - gradient: __scatterMarkerAttrs_893.gradient, + gradient: __scatterMarkerAttrs_958.gradient, editType: 'calc' - }, _$makeColorScaleAttributes_419('marker'), { - showscale: __scatterMarkerAttrs_893.showscale, - colorbar: _$attributes_412 + }, _$makeColorScaleAttributes_481('marker'), { + showscale: __scatterMarkerAttrs_958.showscale, + colorbar: _$attributes_474 }), - textfont: _$attributes_862.textfont, - textposition: _$attributes_862.textposition, + textfont: _$attributes_927.textfont, + textposition: _$attributes_927.textposition, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected, + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected, - hoverinfo: __extendFlat_893({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_958({}, _$attributes_644.hoverinfo, { flags: ['a', 'b', 'text', 'name'] }), - hoveron: _$attributes_862.hoveron, + hoveron: _$attributes_927.hoveron, }; /** @@ -136946,16 +138121,16 @@ var _$attributes_893 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_894 = _$calc_863.calcMarkerSize; -/* removed: var _$lookup_carpetid_726 = require('../carpet/lookup_carpetid'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_959 = _$calc_928.calcMarkerSize; +/* removed: var _$lookup_carpetid_789 = require('../carpet/lookup_carpetid'); */; -var _$calc_894 = function calc(gd, trace) { - var carpet = trace.carpetTrace = _$lookup_carpetid_726(gd, trace); +var _$calc_959 = function calc(gd, trace) { + var carpet = trace._carpetTrace = _$lookup_carpetid_789(gd, trace); if(!carpet || !carpet.visible || carpet.visible === 'legendonly') return; var i; @@ -136972,7 +138147,7 @@ var _$calc_894 = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { a = trace.a[i]; b = trace.b[i]; - if(_$fastIsnumeric_139(a) && _$fastIsnumeric_139(b)) { + if(_$fastIsnumeric_196(a) && _$fastIsnumeric_196(b)) { var xy = carpet.ab2xy(+a, +b, true); var visible = carpet.isVisible(+a, +b); if(!visible) needsCull = true; @@ -136986,10 +138161,10 @@ var _$calc_894 = function calc(gd, trace) { cd[0].carpet = carpet; cd[0].trace = trace; - __calcMarkerSize_894(trace, serieslen); - _$calcMarkerColorscale_867(trace); - _$arraysToCalcdata_861(cd, trace); - _$calcSelection_864(cd, trace); + __calcMarkerSize_959(trace, serieslen); + _$calcMarkerColorscale_932(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcSelection_929(cd, trace); return cd; }; @@ -137005,21 +138180,21 @@ var _$calc_894 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$constants_868 = require('../scatter/constants'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$constants_933 = require('../scatter/constants'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_893 = require('./attributes'); */; +/* removed: var _$attributes_958 = require('./attributes'); */; -var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_960 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_893, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_958, attr, dflt); } coerce('carpet'); @@ -137045,34 +138220,34 @@ var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); - var defaultMode = len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'; + var defaultMode = len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'; coerce('mode', defaultMode); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -137080,7 +138255,7 @@ var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -137093,7 +138268,7 @@ var _$supplyDefaults_895 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_896 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_961 = function eventData(out, pt, trace, cd, pointNumber) { var cdi = cd[pointNumber]; out.a = cdi.a; @@ -137113,10 +138288,10 @@ var _$eventData_896 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_873 = require('../scatter/hover'); */; +/* removed: var _$hoverPoints_938 = require('../scatter/hover'); */; -var _$hoverPoints_897 = function hoverPoints(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_873(pointData, xval, yval, hovermode); +var _$hoverPoints_962 = function hoverPoints(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_938(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -137198,23 +138373,23 @@ var _$hoverPoints_897 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -/* removed: var _$plot_881 = require('../scatter/plot'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; +/* removed: var _$plot_946 = require('../scatter/plot'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; -var _$plot_899 = function plot(gd, plotinfoproxy, data) { +var _$plot_964 = function plot(gd, plotinfoproxy, data) { var i, trace, node; var carpet = data[0][0].carpet; // mimic cartesian plotinfo var plotinfo = { - xaxis: _$axes_584.getFromId(gd, carpet.xaxis || 'x'), - yaxis: _$axes_584.getFromId(gd, carpet.yaxis || 'y'), + xaxis: _$axes_647.getFromId(gd, carpet.xaxis || 'x'), + yaxis: _$axes_647.getFromId(gd, carpet.yaxis || 'y'), plot: plotinfoproxy.plot }; - _$plot_881(gd, plotinfo, data); + _$plot_946(gd, plotinfo, data); for(i = 0; i < data.length; i++) { trace = data[i][0].trace; @@ -137227,7 +138402,7 @@ var _$plot_899 = function plot(gd, plotinfoproxy, data) { // separately to all scattercarpet traces, but that would require // lots of reorganization of scatter traces that is otherwise not // necessary. That makes this a potential optimization. - _$drawing_436.setClipUrl(node, carpet._clipPathId); + _$drawing_498.setClipUrl(node, carpet._clipPathId); } }; @@ -137243,26 +138418,26 @@ var _$plot_899 = function plot(gd, plotinfoproxy, data) { var ScatterCarpet = {}; -ScatterCarpet.attributes = _$attributes_893; -ScatterCarpet.supplyDefaults = _$supplyDefaults_895; -ScatterCarpet.colorbar = _$colorbar_866; -ScatterCarpet.calc = _$calc_894; -ScatterCarpet.plot = _$plot_899; -ScatterCarpet.style = _$style_883.style; -ScatterCarpet.hoverPoints = _$hoverPoints_897; -ScatterCarpet.selectPoints = _$selectPoints_882; -ScatterCarpet.eventData = _$eventData_896; +ScatterCarpet.attributes = _$attributes_958; +ScatterCarpet.supplyDefaults = _$supplyDefaults_960; +ScatterCarpet.colorbar = _$colorbar_931; +ScatterCarpet.calc = _$calc_959; +ScatterCarpet.plot = _$plot_964; +ScatterCarpet.style = _$style_948.style; +ScatterCarpet.hoverPoints = _$hoverPoints_962; +ScatterCarpet.selectPoints = _$selectPoints_947; +ScatterCarpet.eventData = _$eventData_961; ScatterCarpet.moduleType = 'trace'; ScatterCarpet.name = 'scattercarpet'; -ScatterCarpet.basePlotModule = _$cartesian_595; -ScatterCarpet.categories = ['carpet', 'symbols', 'markerColorscale', 'showLegend', 'carpetDependent']; +ScatterCarpet.basePlotModule = _$cartesian_658; +ScatterCarpet.categories = ['svg', 'carpet', 'symbols', 'markerColorscale', 'showLegend', 'carpetDependent', 'draggedPts']; ScatterCarpet.meta = { }; -var _$ScatterCarpet_898 = ScatterCarpet; +var _$ScatterCarpet_963 = ScatterCarpet; /** * Copyright 2012-2018, Plotly, Inc. @@ -137274,7 +138449,7 @@ var _$ScatterCarpet_898 = ScatterCarpet; 'use strict'; -var _$scattercarpet_28 = _$ScatterCarpet_898; +var _$scattercarpet_28 = _$ScatterCarpet_963; /** * Copyright 2012-2018, Plotly, Inc. @@ -137287,16 +138462,16 @@ var _$scattercarpet_28 = _$ScatterCarpet_898; 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __BADNUM_901 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __BADNUM_966 = _$numerical_578.BADNUM; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; -var ____901 = _$lib_539._; +var ____966 = _$lib_601._; -var _$calc_901 = function calc(gd, trace) { +var _$calc_966 = function calc(gd, trace) { var hasLocationData = Array.isArray(trace.locations); var len = hasLocationData ? trace.locations.length : trace._length; var calcTrace = new Array(len); @@ -137311,20 +138486,20 @@ var _$calc_901 = function calc(gd, trace) { var lon = trace.lon[i]; var lat = trace.lat[i]; - if(_$fastIsnumeric_139(lon) && _$fastIsnumeric_139(lat)) calcPt.lonlat = [+lon, +lat]; - else calcPt.lonlat = [__BADNUM_901, __BADNUM_901]; + if(_$fastIsnumeric_196(lon) && _$fastIsnumeric_196(lat)) calcPt.lonlat = [+lon, +lat]; + else calcPt.lonlat = [__BADNUM_966, __BADNUM_966]; } } - _$arraysToCalcdata_861(calcTrace, trace); - _$calcMarkerColorscale_867(trace); - _$calcSelection_864(calcTrace, trace); + _$arraysToCalcdata_926(calcTrace, trace); + _$calcMarkerColorscale_932(trace); + _$calcSelection_929(calcTrace, trace); if(len) { calcTrace[0].t = { labels: { - lat: ____901(gd, 'lat:') + ' ', - lon: ____901(gd, 'lon:') + ' ' + lat: ____966(gd, 'lat:') + ' ', + lon: ____966(gd, 'lon:') + ' ' } }; } @@ -137343,20 +138518,20 @@ var _$calc_901 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_900 = require('./attributes'); */; +/* removed: var _$attributes_965 = require('./attributes'); */; -var _$supplyDefaults_902 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_967 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_900, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_965, attr, dflt); } var len = handleLonLatLocDefaults(traceIn, traceOut, coerce); @@ -137369,22 +138544,22 @@ var _$supplyDefaults_902 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); } }; @@ -137420,7 +138595,7 @@ function handleLonLatLocDefaults(traceIn, traceOut, coerce) { 'use strict'; -var _$eventData_903 = function eventData(out, pt) { +var _$eventData_968 = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; out.location = pt.loc ? pt.loc : null; @@ -137439,15 +138614,15 @@ var _$eventData_903 = function eventData(out, pt) { 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __BADNUM_904 = _$numerical_517.BADNUM; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __BADNUM_969 = _$numerical_578.BADNUM; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; -/* removed: var _$attributes_900 = require('./attributes'); */; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; +/* removed: var _$attributes_965 = require('./attributes'); */; -var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_969 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -137460,7 +138635,7 @@ var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { function distFn(d) { var lonlat = d.lonlat; - if(lonlat[0] === __BADNUM_904) return Infinity; + if(lonlat[0] === __BADNUM_969) return Infinity; if(isLonLatOverEdges(lonlat)) return Infinity; var pt = project(lonlat); @@ -137475,7 +138650,7 @@ var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad); } - _$fx_453.getClosest(cd, distFn, pointData); + _$fx_515.getClosest(cd, distFn, pointData); // skip the rest (for this trace) if we didn't find a close point if(pointData.index === false) return; @@ -137494,7 +138669,7 @@ var _$hoverPoints_904 = function hoverPoints(pointData, xval, yval) { pointData.lon = lonlat[0]; pointData.lat = lonlat[1]; - pointData.color = _$getTraceColor_872(trace, di); + pointData.color = _$getTraceColor_937(trace, di); pointData.extraText = getExtraText(trace, di, geo.mockAxis, cd[0].t.labels); return [pointData]; @@ -137504,7 +138679,7 @@ function getExtraText(trace, pt, axis, labels) { var hoverinfo = pt.hi || trace.hoverinfo; var parts = hoverinfo === 'all' ? - _$attributes_900.hoverinfo.flags : + _$attributes_965.hoverinfo.flags : hoverinfo.split('+'); var hasLocation = parts.indexOf('location') !== -1 && Array.isArray(trace.locations); @@ -137514,7 +138689,7 @@ function getExtraText(trace, pt, axis, labels) { var text = []; function format(val) { - return _$axes_584.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0'; + return _$axes_647.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0'; } if(hasLocation) { @@ -137528,13 +138703,13 @@ function getExtraText(trace, pt, axis, labels) { } if(hasText) { - _$fillHoverText_870(pt, trace, text); + _$fillHoverText_935(pt, trace, text); } return text.join('
'); } -var _$geojson_utils_532 = {}; +var _$geojson_utils_594 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -137546,7 +138721,7 @@ var _$geojson_utils_532 = {}; 'use strict'; -var __BADNUM_532 = _$numerical_517.BADNUM; +var __BADNUM_594 = _$numerical_578.BADNUM; /** * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays @@ -137559,7 +138734,7 @@ var __BADNUM_532 = _$numerical_517.BADNUM; * return line coords array (or array of arrays) * */ -_$geojson_utils_532.calcTraceToLineCoords = function(calcTrace) { +_$geojson_utils_594.calcTraceToLineCoords = function(calcTrace) { var trace = calcTrace[0].trace; var connectgaps = trace.connectgaps; @@ -137570,7 +138745,7 @@ _$geojson_utils_532.calcTraceToLineCoords = function(calcTrace) { var calcPt = calcTrace[i]; var lonlat = calcPt.lonlat; - if(lonlat[0] !== __BADNUM_532) { + if(lonlat[0] !== __BADNUM_594) { lineString.push(lonlat); } else if(!connectgaps && lineString.length > 0) { coords.push(lineString); @@ -137595,7 +138770,7 @@ _$geojson_utils_532.calcTraceToLineCoords = function(calcTrace) { * GeoJSON object * */ -_$geojson_utils_532.makeLine = function(coords) { +_$geojson_utils_594.makeLine = function(coords) { if(coords.length === 1) { return { type: 'LineString', @@ -137617,7 +138792,7 @@ _$geojson_utils_532.makeLine = function(coords) { * @return {object} out * GeoJSON object */ -_$geojson_utils_532.makePolygon = function(coords) { +_$geojson_utils_594.makePolygon = function(coords) { if(coords.length === 1) { return { type: 'Polygon', @@ -137644,7 +138819,7 @@ _$geojson_utils_532.makePolygon = function(coords) { * Blank GeoJSON object * */ -_$geojson_utils_532.makeBlank = function() { +_$geojson_utils_594.makeBlank = function() { return { type: 'Point', coordinates: [] @@ -137661,37 +138836,37 @@ _$geojson_utils_532.makeBlank = function() { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -var __stylePoints_908 = _$style_883.stylePoints; +var __stylePoints_973 = _$style_948.stylePoints; -var _$style_908 = function style(gd, calcTrace) { - if(calcTrace) __styleTrace_908(gd, calcTrace); +var _$style_973 = function style(gd, calcTrace) { + if(calcTrace) __styleTrace_973(gd, calcTrace); }; -function __styleTrace_908(gd, calcTrace) { +function __styleTrace_973(gd, calcTrace) { var trace = calcTrace[0].trace; var s = calcTrace[0].node3; s.style('opacity', calcTrace[0].trace.opacity); - __stylePoints_908(s, trace, gd); + __stylePoints_973(s, trace, gd); // this part is incompatible with Drawing.lineGroupStyle s.selectAll('path.js-line') .style('fill', 'none') .each(function(d) { - var path = _$d3_127.select(this); + var path = _$d3_130.select(this); var trace = d.trace; var line = trace.line || {}; - path.call(_$color_411.stroke, line.color) - .call(_$drawing_436.dashLine, line.dash || '', line.width || 0); + path.call(_$color_473.stroke, line.color) + .call(_$drawing_498.dashLine, line.dash || '', line.width || 0); if(trace.fill !== 'none') { - path.call(_$color_411.fill, trace.fillcolor); + path.call(_$color_473.fill, trace.fillcolor); } }); } @@ -137707,26 +138882,26 @@ function __styleTrace_908(gd, calcTrace) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; +/* removed: var _$d3_130 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_906 = _$numerical_517.BADNUM; -var __getTopojsonFeatures_906 = _$topojson_utils_565.getTopojsonFeatures; -var __locationToFeature_906 = _$geo_location_utils_531.locationToFeature; -/* removed: var _$geojson_utils_532 = require('../../lib/geojson_utils'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$style_908 = require('./style'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_971 = _$numerical_578.BADNUM; +var __getTopojsonFeatures_971 = _$topojson_utils_628.getTopojsonFeatures; +var __locationToFeature_971 = _$geo_location_utils_593.locationToFeature; +/* removed: var _$geojson_utils_594 = require('../../lib/geojson_utils'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$style_973 = require('./style'); */; -var _$plot_906 = function plot(gd, geo, calcData) { +var _$plot_971 = function plot(gd, geo, calcData) { for(var i = 0; i < calcData.length; i++) { - __calcGeoJSON_906(calcData[i], geo.topojson); + __calcGeoJSON_971(calcData[i], geo.topojson); } function keyFunc(d) { return d[0].trace.uid; } function removeBADNUM(d, node) { - if(d.lonlat[0] === __BADNUM_906) { - _$d3_127.select(node).remove(); + if(d.lonlat[0] === __BADNUM_971) { + _$d3_130.select(node).remove(); } } @@ -137743,15 +138918,15 @@ var _$plot_906 = function plot(gd, geo, calcData) { gTraces.selectAll('*').remove(); gTraces.each(function(calcTrace) { - var s = calcTrace[0].node3 = _$d3_127.select(this); + var s = calcTrace[0].node3 = _$d3_130.select(this); var trace = calcTrace[0].trace; - if(_$subtypes_884.hasLines(trace) || trace.fill !== 'none') { - var lineCoords = _$geojson_utils_532.calcTraceToLineCoords(calcTrace); + if(_$subtypes_949.hasLines(trace) || trace.fill !== 'none') { + var lineCoords = _$geojson_utils_594.calcTraceToLineCoords(calcTrace); var lineData = (trace.fill !== 'none') ? - _$geojson_utils_532.makePolygon(lineCoords) : - _$geojson_utils_532.makeLine(lineCoords); + _$geojson_utils_594.makePolygon(lineCoords) : + _$geojson_utils_594.makeLine(lineCoords); s.selectAll('path.js-line') .data([{geojson: lineData, trace: trace}]) @@ -137760,40 +138935,40 @@ var _$plot_906 = function plot(gd, geo, calcData) { .style('stroke-miterlimit', 2); } - if(_$subtypes_884.hasMarkers(trace)) { + if(_$subtypes_949.hasMarkers(trace)) { s.selectAll('path.point') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .classed('point', true) .each(function(calcPt) { removeBADNUM(calcPt, this); }); } - if(_$subtypes_884.hasText(trace)) { + if(_$subtypes_949.hasText(trace)) { s.selectAll('g') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('g') .append('text') .each(function(calcPt) { removeBADNUM(calcPt, this); }); } // call style here within topojson request callback - _$style_908(gd, calcTrace); + _$style_973(gd, calcTrace); }); }; -function __calcGeoJSON_906(calcTrace, topojson) { +function __calcGeoJSON_971(calcTrace, topojson) { var trace = calcTrace[0].trace; if(!Array.isArray(trace.locations)) return; - var features = __getTopojsonFeatures_906(trace, topojson); + var features = __getTopojsonFeatures_971(trace, topojson); var locationmode = trace.locationmode; for(var i = 0; i < calcTrace.length; i++) { var calcPt = calcTrace[i]; - var feature = __locationToFeature_906(locationmode, calcPt.loc, features); + var feature = __locationToFeature_971(locationmode, calcPt.loc, features); - calcPt.lonlat = feature ? feature.properties.ct : [__BADNUM_906, __BADNUM_906]; + calcPt.lonlat = feature ? feature.properties.ct : [__BADNUM_971, __BADNUM_971]; } } @@ -137807,9 +138982,9 @@ function __calcGeoJSON_906(calcTrace, topojson) { 'use strict'; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; -var _$selectPoints_907 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_972 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -137818,7 +138993,7 @@ var _$selectPoints_907 = function selectPoints(searchInfo, polygon) { var di, lonlat, x, y, i; - var hasOnlyLines = (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)); + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); if(hasOnlyLines) return []; if(polygon === false) { @@ -137861,26 +139036,26 @@ var _$selectPoints_907 = function selectPoints(searchInfo, polygon) { var ScatterGeo = {}; -ScatterGeo.attributes = _$attributes_900; -ScatterGeo.supplyDefaults = _$supplyDefaults_902; -ScatterGeo.colorbar = _$colorbar_866; -ScatterGeo.calc = _$calc_901; -ScatterGeo.plot = _$plot_906; -ScatterGeo.style = _$style_908; -ScatterGeo.hoverPoints = _$hoverPoints_904; -ScatterGeo.eventData = _$eventData_903; -ScatterGeo.selectPoints = _$selectPoints_907; +ScatterGeo.attributes = _$attributes_965; +ScatterGeo.supplyDefaults = _$supplyDefaults_967; +ScatterGeo.colorbar = _$colorbar_931; +ScatterGeo.calc = _$calc_966; +ScatterGeo.plot = _$plot_971; +ScatterGeo.style = _$style_973; +ScatterGeo.hoverPoints = _$hoverPoints_969; +ScatterGeo.eventData = _$eventData_968; +ScatterGeo.selectPoints = _$selectPoints_972; ScatterGeo.moduleType = 'trace'; ScatterGeo.name = 'scattergeo'; -ScatterGeo.basePlotModule = _$geo_615; +ScatterGeo.basePlotModule = _$geo_677; ScatterGeo.categories = ['geo', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like']; ScatterGeo.meta = { }; -var _$ScatterGeo_905 = ScatterGeo; +var _$ScatterGeo_970 = ScatterGeo; /** * Copyright 2012-2018, Plotly, Inc. @@ -137892,10 +139067,10 @@ var _$ScatterGeo_905 = ScatterGeo; 'use strict'; -var _$scattergeo_29 = _$ScatterGeo_905; +var _$scattergeo_29 = _$ScatterGeo_970; -var _$newArray_50 = function newArray(start, end) { +var _$newArray_51 = function newArray(start, end) { var n0 = typeof start === 'number', n1 = typeof end === 'number' @@ -137918,199 +139093,11 @@ var _$newArray_50 = function newArray(start, end) { a[i] = c return a } -/** - * @module kdgrass - * - * Static kdbush - */ - 'use strict' -var _$KDTree_252 = KDTree - -//optimized kdbush -function KDTree(points, nodeSize) { - if (!(this instanceof KDTree)) return new KDTree(points, nodeSize) - - this.nodeSize = nodeSize || 64; - - this.coords = points.slice(); - - var l = Math.floor(points.length / 2) - this.ids = Array(l); - - for (var i = 0; i < l; i++) { - this.ids[i] = i; - } - - sortKD(this.ids, this.coords, this.nodeSize, 0, this.ids.length - 1, 0); -} - - -KDTree.prototype.range = function range(minX, minY, maxX, maxY) { - var ids = this.ids, coords = this.coords, nodeSize = this.nodeSize - var stack = [0, ids.length - 1, 0]; - var result = []; - var x, y; - - while (stack.length) { - var axis = stack.pop(); - var right = stack.pop(); - var left = stack.pop(); - - if (right - left <= nodeSize) { - for (var i = left; i <= right; i++) { - x = coords[2 * i]; - y = coords[2 * i + 1]; - if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]); - } - continue; - } - - var m = Math.floor((left + right) / 2); - - x = coords[2 * m]; - y = coords[2 * m + 1]; - - if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]); - - var nextAxis = (axis + 1) % 2; - - if (axis === 0 ? minX <= x : minY <= y) { - stack.push(left); - stack.push(m - 1); - stack.push(nextAxis); - } - if (axis === 0 ? maxX >= x : maxY >= y) { - stack.push(m + 1); - stack.push(right); - stack.push(nextAxis); - } - } - - return result; -} - - -KDTree.prototype.within = function within(qx, qy, r) { - var ids = this.ids, coords = this.coords, nodeSize = this.nodeSize - var stack = [0, ids.length - 1, 0]; - var result = []; - var r2 = r * r; - - while (stack.length) { - var axis = stack.pop(); - var right = stack.pop(); - var left = stack.pop(); - - if (right - left <= nodeSize) { - for (var i = left; i <= right; i++) { - if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]); - } - continue; - } - - var m = Math.floor((left + right) / 2); - - var x = coords[2 * m]; - var y = coords[2 * m + 1]; - - if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]); - - var nextAxis = (axis + 1) % 2; - - if (axis === 0 ? qx - r <= x : qy - r <= y) { - stack.push(left); - stack.push(m - 1); - stack.push(nextAxis); - } - if (axis === 0 ? qx + r >= x : qy + r >= y) { - stack.push(m + 1); - stack.push(right); - stack.push(nextAxis); - } - } - - return result; -} - -function sqDist(ax, ay, bx, by) { - var dx = ax - bx; - var dy = ay - by; - return dx * dx + dy * dy; -} - - -function sortKD(ids, coords, nodeSize, left, right, depth) { - if (right - left <= nodeSize) return; - - var m = Math.floor((left + right) / 2); - - __select_252(ids, coords, m, left, right, depth % 2); - - sortKD(ids, coords, nodeSize, left, m - 1, depth + 1); - sortKD(ids, coords, nodeSize, m + 1, right, depth + 1); -} - -function __select_252(ids, coords, k, left, right, inc) { - - while (right > left) { - if (right - left > 600) { - var n = right - left + 1; - var m = k - left + 1; - var z = Math.log(n); - var s = 0.5 * Math.exp(2 * z / 3); - var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); - var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); - var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); - __select_252(ids, coords, k, newLeft, newRight, inc); - } - - var t = coords[2 * k + inc]; - var i = left; - var j = right; - - swapItem(ids, coords, left, k); - if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right); - - while (i < j) { - swapItem(ids, coords, i, j); - i++; - j--; - while (coords[2 * i + inc] < t) i++; - while (coords[2 * j + inc] > t) j--; - } - - if (coords[2 * left + inc] === t) swapItem(ids, coords, left, j); - else { - j++; - swapItem(ids, coords, j, right); - } - - if (j <= k) left = j + 1; - if (k <= j) right = j - 1; - } -} - -function swapItem(ids, coords, i, j) { - __swap_252(ids, i, j); - __swap_252(coords, 2 * i, 2 * j); - __swap_252(coords, 2 * i + 1, 2 * j + 1); -} - -function __swap_252(arr, i, j) { - var tmp = arr[i]; - arr[i] = arr[j]; - arr[j] = tmp; -} - - - -'use strict' - -var _$normalize_48 = __normalize_48; +var _$normalize_49 = __normalize_49; -function __normalize_48 (arr, dim) { +function __normalize_49 (arr, dim) { if (!arr || arr.length == null) throw Error('Argument should be an array') if (dim == null) dim = 1 @@ -138134,8 +139121,8 @@ function __normalize_48 (arr, dim) { } /*eslint new-cap:0*/ -/* removed: var _$dtype_132 = require('dtype') */; -var _$flattenVertexData_141 = flattenVertexData +/* removed: var _$dtype_135 = require('dtype') */; +var _$flattenVertexData_198 = flattenVertexData function flattenVertexData (data, output, offset) { if (!data) throw new TypeError('must specify data as first parameter') offset = +(offset || 0) | 0 @@ -138146,7 +139133,7 @@ function flattenVertexData (data, output, offset) { // no output specified, create a new typed array if (!output || typeof output === 'string') { - output = new (_$dtype_132(output || 'float32'))(length + offset) + output = new (_$dtype_135(output || 'float32'))(length + offset) } var dstLength = output.length - offset @@ -138163,7 +139150,7 @@ function flattenVertexData (data, output, offset) { } else { if (!output || typeof output === 'string') { // no output, create a new one - var Ctor = _$dtype_132(output || 'float32') + var Ctor = _$dtype_135(output || 'float32') if (offset === 0) { output = new Ctor(data) } else { @@ -138179,10 +139166,21 @@ function flattenVertexData (data, output, offset) { return output } +'use strict'; +var _$isObj_307 = function (x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); +}; + +'use strict'; +var _$mathLog2_317 = Math.log2 || function (x) { + return Math.log(x) * Math.LOG2E; +}; + 'use strict' -var _$pick_290 = function pick (src, props, keepRest) { +var _$pick_349 = function pick (src, props, keepRest) { var result = {}, prop, i if (typeof props === 'string') props = toList(props) @@ -138247,26 +139245,512 @@ var _$pick_290 = function pick (src, props, keepRest) { return result } -var __CACHE_290 = {} +var __CACHE_349 = {} function toList(arg) { - if (__CACHE_290[arg]) return __CACHE_290[arg] + if (__CACHE_349[arg]) return __CACHE_349[arg] if (typeof arg === 'string') { - arg = __CACHE_290[arg] = arg.split(/\s*,\s*|\s+/) + arg = __CACHE_349[arg] = arg.split(/\s*,\s*|\s+/) } return arg } -var _$toFloat32_353 = {}; +'use strict' + +/* removed: var _$pick_349 = require('pick-by-alias') */; + +var _$parseRect_343 = 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_349(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 +} + +"use strict" + +function __compileSearch_354(funcName, predicate, reversed, extraArgs, 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[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_354(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + __compileSearch_354("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + __compileSearch_354("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() +} + +var _$searchBounds_354 = { + ge: __compileBoundsSearch_354(">=", false, "GE"), + gt: __compileBoundsSearch_354(">", false, "GT"), + lt: __compileBoundsSearch_354("<", true, "LT"), + le: __compileBoundsSearch_354("<=", true, "LE"), + eq: __compileBoundsSearch_354("-", true, "EQ", true) +} + +/** + * @module point-cluster/quad + * + * Bucket based quad tree clustering + */ + +'use strict' + +/* removed: var _$searchBounds_354 = require('binary-search-bounds') */; +/* removed: var _$clamp_95 = require('clamp') */; +/* removed: var _$parseRect_343 = require('parse-rect') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$defined_131 = require('defined') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$isObj_307 = require('is-obj') */; +/* removed: var _$dtype_135 = require('dtype') */; +/* removed: var _$mathLog2_317 = require('math-log2') */; + + +var _$cluster_355 = function cluster (srcPoints, options) { + if (!options) { options = {} } + + srcPoints = _$flattenVertexData_198(srcPoints, 'float64') + + options = _$pick_349(options, { + bounds: 'range bounds dataBox databox', + maxDepth: 'depth maxDepth maxdepth level maxLevel maxlevel levels', + dtype: 'type dtype format out dst output destination' + // sort: 'sortBy sortby sort', + // pick: 'pick levelPoint', + // nodeSize: 'node nodeSize minNodeSize minSize size' + }) + + // let nodeSize = defined(options.nodeSize, 1) + var maxDepth = _$defined_131(options.maxDepth, 255) + var bounds = _$defined_131(options.bounds, _$normalize_49(srcPoints, 2)) + if (bounds[0] === bounds[2]) { bounds[2]++ } + if (bounds[1] === bounds[3]) { bounds[3]++ } + + var points = __normalize_355(srcPoints, bounds) + + // init variables + var n = srcPoints.length >>> 1 + var ids + if (!options.dtype) { options.dtype = 'array' } + + if (typeof options.dtype === 'string') { + ids = new (_$dtype_135(options.dtype))(n) + } + else if (options.dtype) { + ids = options.dtype + if (Array.isArray(ids)) { ids.length = n } + } + for (var i = 0; i < n; ++i) { + ids[i] = i + } + + // point indexes for levels [0: [a,b,c,d], 1: [a,b,c,d,e,f,...], ...] + var levels = [] + + // starting indexes of subranges in sub levels, levels.length * 4 + var sublevels = [] + + // unique group ids, sorted in z-curve fashion within levels + var groups = [] + + // level offsets in `ids` + var offsets = [] + + + // sort points + sort(0, 0, 1, ids, 0, 1) + + + // return reordered ids with provided methods + // save level offsets in output buffer + var offset = 0 + for (var level = 0; level < levels.length; level++) { + var levelItems = levels[level] + if (ids.set) { ids.set(levelItems, offset) } + else { + for (var i$1 = 0, l = levelItems.length; i$1 < l; i$1++) { + ids[i$1 + offset] = levelItems[i$1] + } + } + var nextOffset = offset + levels[level].length + offsets[level] = [offset, nextOffset] + offset = nextOffset + } + + ids.range = range + + return ids + + + + // FIXME: it is possible to create one typed array heap and reuse that to avoid memory blow + function sort (x, y, diam, ids, level, group) { + if (!ids.length) { return null } + + // save first point as level representative + var levelItems = levels[level] || (levels[level] = []) + var levelGroups = groups[level] || (groups[level] = []) + var sublevel = sublevels[level] || (sublevels[level] = []) + var offset = levelItems.length + + level++ + + // max depth reached - put all items into a first group + if (level > maxDepth) { + for (var i = 0; i < ids.length; i++) { + levelItems.push(ids[i]) + levelGroups.push(group) + sublevel.push(null, null, null, null) + } + + return offset + } + + levelItems.push(ids[0]) + levelGroups.push(group) + + if (ids.length <= 1) { + sublevel.push(null, null, null, null) + return offset + } + + + var d2 = diam * .5 + var cx = x + d2, cy = y + d2 + + // distribute points by 4 buckets + var lolo = [], lohi = [], hilo = [], hihi = [] + + for (var i$1 = 1, l = ids.length; i$1 < l; i$1++) { + var idx = ids[i$1], + x$1 = points[idx * 2], + y$1 = points[idx * 2 + 1] + x$1 < cx ? (y$1 < cy ? lolo.push(idx) : lohi.push(idx)) : (y$1 < cy ? hilo.push(idx) : hihi.push(idx)) + } + + group <<= 2 + sublevel.push( + sort(x, y, d2, lolo, level, group), + sort(x, cy, d2, lohi, level, group + 1), + sort(cx, y, d2, hilo, level, group + 2), + sort(cx, cy, d2, hihi, level, group + 3) + ) + + return offset + } + + // get all points within the passed range + function range () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var options + + if (_$isObj_307(args[args.length - 1])) { + var arg = args.pop() + + // detect if that was a rect object + if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) { + args = [arg] + options = {} + } + + options = _$pick_349(arg, { + level: 'level maxLevel', + d: 'd diam diameter r radius px pxSize pixel pixelSize maxD size minSize', + lod: 'lod details ranges offsets' + }) + } + else { + options = {} + } + + if (!args.length) { args = bounds } + + var box = _$parseRect_343.apply( void 0, args ) + + var ref = [ + Math.min(box.x, box.x + box.width), + Math.min(box.y, box.y + box.height), + Math.max(box.x, box.x + box.width), + Math.max(box.y, box.y + box.height) + ]; + var minX = ref[0]; + var minY = ref[1]; + var maxX = ref[2]; + var maxY = ref[3]; + + var ref$1 = __normalize_355([minX, minY, maxX, maxY], bounds ); + var nminX = ref$1[0]; + var nminY = ref$1[1]; + var nmaxX = ref$1[2]; + var nmaxY = ref$1[3]; + + var maxLevel = _$defined_131(options.level, levels.length) + + // limit maxLevel by px size + if (options.d != null) { + var d + if (typeof options.d === 'number') { d = [options.d, options.d] } + else if (options.d.length) { d = options.d } + + maxLevel = Math.min( + Math.ceil(-_$mathLog2_317(Math.abs(d[0]) / (bounds[2] - bounds[0]))), + Math.ceil(-_$mathLog2_317(Math.abs(d[1]) / (bounds[3] - bounds[1]))), + maxLevel + ) + } + + // return levels of details + if (options.lod) { + return lod(nminX, nminY, nmaxX, nmaxY, maxLevel) + } + + + + // do selection ids + var selection = [] + + // FIXME: probably we can do LOD here beforehead + select( 0, 0, 1, 0, 0, 1) + + function select ( lox, loy, d, level, from, to ) { + if (from === null || to === null) { return } + + var hix = lox + d + var hiy = loy + d + + // if box does not intersect level - ignore + if ( nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy ) { return } + if ( level >= maxLevel ) { return } + if ( from === to ) { return } + + // if points fall into box range - take it + var levelItems = levels[level] + + if (to === undefined) { to = levelItems.length } + + for (var i = from; i < to; i++) { + var id = levelItems[i] + + var px = srcPoints[ id * 2 ] + var py = srcPoints[ id * 2 + 1 ] + + if ( px >= minX && px <= maxX && py >= minY && py <= maxY ) {selection.push(id) + } + } + + // for every subsection do select + var offsets = sublevels[ level ] + var off0 = offsets[ from * 4 + 0 ] + var off1 = offsets[ from * 4 + 1 ] + var off2 = offsets[ from * 4 + 2 ] + var off3 = offsets[ from * 4 + 3 ] + var end = nextOffset(offsets, from + 1) + + var d2 = d * .5 + var nextLevel = level + 1 + select( lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end) + select( lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end) + select( lox + d2, loy, d2, nextLevel, off2, off3 || end) + select( lox + d2, loy + d2, d2, nextLevel, off3, end) + } + + function nextOffset(offsets, from) { + var offset = null, i = 0 + while(offset === null) { + offset = offsets[ from * 4 + i ] + i++ + if (i > offsets.length) { return null } + } + return offset + } + + return selection + } + + // get range offsets within levels to render lods appropriate for zoom level + // TODO: it is possible to store minSize of a point to optimize neede level calc + function lod (lox, loy, hix, hiy, maxLevel) { + var ranges = [] + + for (var level = 0; level < maxLevel; level++) { + var levelGroups = groups[level] + var from = offsets[level][0] + + var levelGroupStart = group(lox, loy, level) + var levelGroupEnd = group(hix, hiy, level) + + // FIXME: utilize sublevels to speed up search range here + var startOffset = _$searchBounds_354.ge(levelGroups, levelGroupStart) + var endOffset = _$searchBounds_354.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1) + + ranges[level] = [startOffset + from, endOffset + from] + } + + return ranges + } + + // get group id closest to the x,y coordinate, corresponding to a level + function group (x, y, level) { + var group = 1 + + var cx = .5, cy = .5 + var diam = .5 + + for (var i = 0; i < level; i++) { + group <<= 2 + + group += x < cx ? (y < cy ? 0 : 1) : (y < cy ? 2 : 3) + + diam *= .5 + + cx += x < cx ? -diam : diam + cy += y < cy ? -diam : diam + } + + return group + } +} + + +// normalize points by bounds +function __normalize_355 (pts, bounds) { + var lox = bounds[0]; + var loy = bounds[1]; + var hix = bounds[2]; + var hiy = bounds[3]; + var scaleX = 1.0 / (hix - lox) + var scaleY = 1.0 / (hiy - loy) + var result = new Array(pts.length) + + for (var i = 0, n = pts.length / 2; i < n; i++) { + result[2*i] = _$clamp_95((pts[2*i] - lox) * scaleX, 0, 1) + result[2*i+1] = _$clamp_95((pts[2*i+1] - loy) * scaleY, 0, 1) + } + + return result +} +'use strict' + +var _$pointCluster_353 = _$cluster_355 +var _$toFloat32_415 = {}; /* @module to-float32 */ 'use strict' -_$toFloat32_353 = float32 -_$toFloat32_353.float32 = -_$toFloat32_353.float = float32 -_$toFloat32_353.fract32 = -_$toFloat32_353.fract = fract32 +_$toFloat32_415 = float32 +_$toFloat32_415.float32 = +_$toFloat32_415.float = float32 +_$toFloat32_415.fract32 = +_$toFloat32_415.fract = fract32 // return fractional part of float32 array function fract32 (arr) { @@ -138299,7 +139783,7 @@ function float32 (arr) { 'use strict' -var _$updateDiff_363 = function updateDiff (obj, diff, mappers) { +var _$updateDiff_425 = function updateDiff (obj, diff, mappers) { if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2) for (var i = 0, l = mappers.length; i < l; i++) { @@ -138327,19 +139811,19 @@ var _$updateDiff_363 = function updateDiff (obj, diff, mappers) { 'use strict' -/* removed: var _$normalize_48 = require('array-bounds') */; -/* removed: var _$normalize_99 = require('color-normalize') */; -/* removed: var _$updateDiff_363 = require('update-diff') */; -/* removed: var _$pick_290 = require('pick-by-alias') */; -/* removed: var _$objectAssign_281 = require('object-assign') */; -/* removed: var _$flattenVertexData_141 = require('flatten-vertex-data') */; -/* removed: var _$toFloat32_353 = require('to-float32'); */; -var __float32_311 = _$toFloat32_353.float32; -var __fract32_311 = _$toFloat32_353.fract32; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$normalize_100 = require('color-normalize') */; +/* removed: var _$updateDiff_425 = require('update-diff') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$toFloat32_415 = require('to-float32'); */; +var __float32_374 = _$toFloat32_415.float32; +var __fract32_374 = _$toFloat32_415.fract32; -var _$Error2D_311 = Error2D +var _$Error2D_374 = Error2D -var __WEIGHTS_311 = [ +var __WEIGHTS_374 = [ //direction, lineWidth shift, capSize shift // x-error bar @@ -138457,7 +139941,7 @@ function Error2D (regl, options) { meshBuffer = regl.buffer({ usage: 'static', type: 'float', - data: __WEIGHTS_311 + data: __WEIGHTS_374 }) update(options) @@ -138550,11 +140034,11 @@ function Error2D (regl, options) { stencil: false, instances: regl.prop('count'), - count: __WEIGHTS_311.length + count: __WEIGHTS_374.length }) //expose API - _$objectAssign_281(error2d, { + _$objectAssign_339(error2d, { update: update, draw: draw, destroy: destroy, @@ -138649,7 +140133,7 @@ function Error2D (regl, options) { else if (typeof options[0] === 'number') { options = {positions: options} } //copy options to avoid mutation & handle aliases - options = _$pick_290(options, { + options = _$pick_349(options, { color: 'color colors fill', capSize: 'capSize cap capsize cap-size', lineWidth: 'lineWidth line-width width line thickness', @@ -138669,23 +140153,23 @@ function Error2D (regl, options) { translateFract: null, draw: true } - options = _$objectAssign_281({}, defaults, options) + options = _$objectAssign_339({}, defaults, options) } - _$updateDiff_363(group, options, [{ + _$updateDiff_425(group, options, [{ lineWidth: function (v) { return +v * .5; }, capSize: function (v) { return +v * .5; }, opacity: parseFloat, errors: function (errors) { - errors = _$flattenVertexData_141(errors) + errors = _$flattenVertexData_198(errors) errorCount += errors.length return errors }, positions: function (positions, state) { - positions = _$flattenVertexData_141(positions, 'float64') + positions = _$flattenVertexData_198(positions, 'float64') state.count = Math.floor(positions.length / 2) - state.bounds = _$normalize_48(positions, 2) + state.bounds = _$normalize_49(positions, 2) state.offset = pointCount pointCount += state.count @@ -138713,7 +140197,7 @@ function Error2D (regl, options) { //convert colors to float arrays for (var i$1 = 0; i$1 < count; i$1++) { - var c = _$normalize_99(colors[i$1], 'uint8') + var c = _$normalize_100(colors[i$1], 'uint8') colorData.set(c, i$1 * 4) } @@ -138727,8 +140211,8 @@ function Error2D (regl, options) { state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] state.translate = [-range[0], -range[1]] - state.scaleFract = __fract32_311(state.scale) - state.translateFract = __fract32_311(state.translate) + state.scaleFract = __fract32_374(state.scale) + state.translateFract = __fract32_374(state.translate) return range }, @@ -138794,8 +140278,8 @@ function Error2D (regl, options) { positionData.set(positions, offset * 2) }) - positionBuffer(__float32_311(positionData)) - positionFractBuffer(__fract32_311(positionData)) + positionBuffer(__float32_374(positionData)) + positionFractBuffer(__fract32_374(positionData)) colorBuffer(colorData) errorBuffer(errorData) } @@ -138812,15 +140296,15 @@ function Error2D (regl, options) { } 'use strict' -/* removed: var _$normalize_48 = require('array-bounds') */; +/* removed: var _$normalize_49 = require('array-bounds') */; -var _$normalize_49 = __normalize_49; +var _$normalize_50 = __normalize_50; -function __normalize_49 (arr, dim, bounds) { +function __normalize_50 (arr, dim, bounds) { if (!arr || arr.length == null) throw Error('Argument should be an array') if (dim == null) dim = 1 - if (bounds == null) bounds = _$normalize_48(arr, dim) + if (bounds == null) bounds = _$normalize_49(arr, dim) for (var offset = 0; offset < dim; offset++) { var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length; @@ -138851,11 +140335,11 @@ function __normalize_49 (arr, dim, bounds) { return arr; } -var _$earcut_134 = {}; +var _$earcut_137 = {}; 'use strict'; -_$earcut_134 = earcut; -_$earcut_134.default = earcut; +_$earcut_137 = earcut; +_$earcut_137.default = earcut; function earcut(data, holeIndices, dim) { @@ -139097,7 +140581,7 @@ function splitEarcut(start, triangles, dim, minX, minY, invSize) { while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { // split the polygon in two by the diagonal - var c = __splitPolygon_134(a, b); + var c = __splitPolygon_137(a, b); // filter colinear points around the cuts a = filterPoints(a, a.next); @@ -139146,7 +140630,7 @@ function compareX(a, b) { function eliminateHole(hole, outerNode) { outerNode = findHoleBridge(hole, outerNode); if (outerNode) { - var b = __splitPolygon_134(outerNode, hole); + var b = __splitPolygon_137(outerNode, hole); filterPoints(b, b.next); } } @@ -139360,168 +140844,1301 @@ function locallyInside(a, b) { 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); +// 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_137(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) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice 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; +}; + +'use strict'; + +var _$isImplemented_191 = function () { + var weakMap, x; + if (typeof WeakMap !== 'function') return false; + try { + // WebKit doesn't support arguments and crashes + weakMap = new WeakMap([[x = {}, '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(x) !== 'one') return false; + + return true; +}; + +"use strict"; + +var _$isImplemented_153 = 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"; +}; + +"use strict"; + +var _$isImplemented_162 = function () { + try { + Object.keys("primitive"); + return true; + } catch (e) { + return false; +} +}; + +"use strict"; + +// eslint-disable-next-line no-empty-function +var _$noop_145 = function () {}; + +"use strict"; + +var _undefined = _$noop_145(); // Support ES3 engines + +var _$isValue_160 = function (val) { + return (val !== _undefined) && (val !== null); +}; + +"use strict"; + +/* removed: var _$isValue_160 = require("../is-value"); */; + +var keys = Object.keys; + +var _$shim_163 = function (object) { + return keys(_$isValue_160(object) ? Object(object) : object); +}; + +"use strict"; + +var _$keys_161 = _$isImplemented_162() + ? Object.keys + : _$shim_163; + +"use strict"; + +/* removed: var _$isValue_160 = require("./is-value"); */; + +var _$validValue_171 = function (value) { + if (!_$isValue_160(value)) throw new TypeError("Cannot use null or undefined"); + return value; +}; + +"use strict"; + +var __dummy_154$0 = 0 + , __dummy_154$1 = 0 + , max = Math.max; + +var _$shim_154 = function (dest, src /*, …srcn*/) { + var error, i, length = max(arguments.length, 2), assign; + dest = Object(_$validValue_171(dest)); + assign = function (key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + _$keys_161(src).forEach(assign); + } + if (error !== undefined) throw error; + return dest; +}; + +"use strict"; + +var _$assign_152 = _$isImplemented_153() + ? Object.assign + : _$shim_154; + +// Deprecated + +"use strict"; + +var _$isCallable_158 = function (obj) { + return typeof obj === "function"; +}; + +"use strict"; + +/* removed: var _$isValue_160 = require("./is-value"); */; + +var forEach = Array.prototype.forEach, __create_165 = Object.create; + +var __process_165 = function (src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; + +// eslint-disable-next-line no-unused-vars +var _$normalizeOptions_165 = function (opts1 /*, …options*/) { + var result = __create_165(null); + forEach.call(arguments, function (options) { + if (!_$isValue_160(options)) return; + __process_165(Object(options), result); + }); + return result; +}; + +"use strict"; + +var str = "razdwatrzy"; + +var _$isImplemented_173 = function () { + if (typeof str.contains !== "function") return false; + return (str.contains("dwa") === true) && (str.contains("foo") === false); +}; + +"use strict"; + +var indexOf = String.prototype.indexOf; + +var _$shim_174 = function (searchString/*, position*/) { + return indexOf.call(this, searchString, arguments[1]) > -1; +}; + +"use strict"; + +var _$contains_172 = _$isImplemented_173() + ? String.prototype.contains + : _$shim_174; + +var _$d_121 = {}; +'use strict'; + +var __dummy_121$0 = 0 + , __dummy_121$1 = 0 + , __dummy_121$2 = 0 + , __dummy_121$3 = 0 + + , d; + +d = _$d_121 = function (dscr, value/*, options*/) { + var c, e, w, options, desc; + if ((arguments.length < 2) || (typeof dscr !== 'string')) { + options = value; + value = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (dscr == null) { + c = w = true; + e = false; + } else { + c = _$contains_172.call(dscr, 'c'); + e = _$contains_172.call(dscr, 'e'); + w = _$contains_172.call(dscr, 'w'); + } + + desc = { value: value, configurable: c, enumerable: e, writable: w }; + return !options ? desc : _$assign_152(_$normalizeOptions_165(options), desc); +}; + +d.gs = function (dscr, get, set/*, options*/) { + var c, e, options, desc; + if (typeof dscr !== 'string') { + options = set; + set = get; + get = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (get == null) { + get = undefined; + } else if (!_$isCallable_158(get)) { + options = get; + get = set = undefined; + } else if (set == null) { + set = undefined; + } else if (!_$isCallable_158(set)) { + options = set; + set = undefined; + } + if (dscr == null) { + c = true; + e = false; + } else { + c = _$contains_172.call(dscr, 'c'); + e = _$contains_172.call(dscr, 'e'); + } + + desc = { get: get, set: set, configurable: c, enumerable: e }; + return !options ? desc : _$assign_152(_$normalizeOptions_165(options), desc); +}; + +"use strict"; + +var __create_167 = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; + +var _$isImplemented_167 = function (/* CustomCreate*/) { + var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || __create_167; + if (typeof setPrototypeOf !== "function") return false; + return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject; +}; + +"use strict"; + +/* removed: var _$isValue_160 = require("./is-value"); */; + +var __map_159 = { function: true, object: true }; + +var _$isObject_159 = function (value) { + return (_$isValue_160(value) && __map_159[typeof value]) || false; +}; + +"use strict"; + +var _$setPrototypeOf_166 = _$isImplemented_167() + ? Object.setPrototypeOf + : _$shim_168({}); + +"use strict"; + +/* removed: var _$isObject_159 = require("./is-object"); */; + +var _$validObject_170 = function (value) { + if (!_$isObject_159(value)) throw new TypeError(value + " is not an Object"); + return value; +}; + +"use strict"; + +var generated = Object.create(null), random = Math.random; + +var _$randomUniq_176 = function () { + var str; + do { + str = random() + .toString(36) + .slice(2); + } while (generated[str]); + return str; +}; + +"use strict"; + +var objToString = Object.prototype.toString + , id = objToString.call( + (function () { + return arguments; + })() +); + +var _$isArguments_143 = function (value) { + return objToString.call(value) === id; +}; + +"use strict"; + +var _$validCallable_169 = function (fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; +}; + +"use strict"; + +var __objToString_175 = Object.prototype.toString, __id_175 = __objToString_175.call(""); + +var _$isString_175 = function (value) { + return ( + typeof value === "string" || + (value && + typeof value === "object" && + (value instanceof String || __objToString_175.call(value) === __id_175)) || + false + ); +}; + +"use strict"; + +var _$isImplemented_141 = 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")); +}; + +"use strict"; + +var __objToString_144 = Object.prototype.toString, __id_144 = __objToString_144.call(_$noop_145); + +var _$isFunction_144 = function (value) { + return typeof value === "function" && __objToString_144.call(value) === __id_144; +}; + +"use strict"; + +var _$isImplemented_147 = function () { + var sign = Math.sign; + if (typeof sign !== "function") return false; + return (sign(10) === 1) && (sign(-20) === -1); +}; + +"use strict"; + +var _$shim_148 = function (value) { + value = Number(value); + if (isNaN(value) || (value === 0)) return value; + return value > 0 ? 1 : -1; +}; + +"use strict"; + +var _$sign_146 = _$isImplemented_147() + ? Math.sign + : _$shim_148; + +"use strict"; + +var __dummy_149$0 = 0 + + , abs = Math.abs, floor = Math.floor; + +var _$toInteger_149 = function (value) { + if (isNaN(value)) return 0; + value = Number(value); + if ((value === 0) || !isFinite(value)) return value; + return _$sign_146(value) * floor(abs(value)); +}; + +"use strict"; + +var __dummy_150$0 = 0 + + , __max_150 = Math.max; + +var _$toPosInteger_150 = function (value) { + return __max_150(0, _$toInteger_149(value)); +}; + +'use strict'; + +var validTypes = { object: true, symbol: true }; + +var _$isImplemented_186 = function () { + var symbol; + if (typeof Symbol !== 'function') return false; + symbol = Symbol('test symbol'); + try { String(symbol); } catch (e) { return false; } + + // Return 'true' also for polyfills + if (!validTypes[typeof Symbol.iterator]) return false; + if (!validTypes[typeof Symbol.toPrimitive]) return false; + if (!validTypes[typeof Symbol.toStringTag]) return false; + + return true; +}; + +'use strict'; + +var _$isSymbol_187 = function (x) { + if (!x) return false; + if (typeof x === 'symbol') return true; + if (!x.constructor) return false; + if (x.constructor.name !== 'Symbol') return false; + return (x[x.constructor.toStringTag] === 'Symbol'); +}; + +'use strict'; + +/* removed: var _$isSymbol_187 = require('./is-symbol'); */; + +var _$validateSymbol_189 = function (value) { + if (!_$isSymbol_187(value)) throw new TypeError(value + " is not a symbol"); + return value; +}; + +// ES2015 Symbol polyfill for environments that do not (or partially) support it + +'use strict'; + +var __dummy_188$0 = 0 + , __dummy_188$1 = 0 + + , __create_188 = Object.create, defineProperties = Object.defineProperties + , __defineProperty_188 = Object.defineProperty, objPrototype = Object.prototype + , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = __create_188(null) + , isNativeSafe; + +if (typeof Symbol === 'function') { + NativeSymbol = Symbol; + try { + String(NativeSymbol()); + isNativeSafe = true; + } catch (ignore) {} +} + +var generateName = (function () { + var created = __create_188(null); + return function (desc) { + var postfix = 0, name, ie11BugWorkaround; + while (created[desc + (postfix || '')]) ++postfix; + desc += (postfix || ''); + created[desc] = true; + name = '@@' + desc; + __defineProperty_188(objPrototype, name, _$d_121.gs(null, function (value) { + // For IE11 issue see: + // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ + // ie11-broken-getters-on-dom-objects + // https://github.com/medikoo/es6-symbol/issues/12 + if (ie11BugWorkaround) return; + ie11BugWorkaround = true; + __defineProperty_188(this, name, _$d_121(value)); + ie11BugWorkaround = false; + })); + return name; + }; +}()); + +// Internal constructor (not one exposed) for creating Symbol instances. +// This one is used to ensure that `someSymbol instanceof Symbol` always return false +HiddenSymbol = function Symbol(description) { + if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor'); + return SymbolPolyfill(description); +}; + +// Exposed `Symbol` constructor +// (returns instances of HiddenSymbol) +var _$polyfill_188 = SymbolPolyfill = function Symbol(description) { + var symbol; + if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor'); + if (isNativeSafe) return NativeSymbol(description); + symbol = __create_188(HiddenSymbol.prototype); + description = (description === undefined ? '' : String(description)); + return defineProperties(symbol, { + __description__: _$d_121('', description), + __name__: _$d_121('', generateName(description)) + }); +}; +defineProperties(SymbolPolyfill, { + for: _$d_121(function (key) { + if (globalSymbols[key]) return globalSymbols[key]; + return (globalSymbols[key] = SymbolPolyfill(String(key))); + }), + keyFor: _$d_121(function (s) { + var key; + _$validateSymbol_189(s); + for (key in globalSymbols) if (globalSymbols[key] === s) return key; + }), + + // To ensure proper interoperability with other native functions (e.g. Array.from) + // fallback to eventual native implementation of given symbol + hasInstance: _$d_121('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')), + isConcatSpreadable: _$d_121('', (NativeSymbol && NativeSymbol.isConcatSpreadable) || + SymbolPolyfill('isConcatSpreadable')), + iterator: _$d_121('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')), + match: _$d_121('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')), + replace: _$d_121('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')), + search: _$d_121('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')), + species: _$d_121('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')), + split: _$d_121('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')), + toPrimitive: _$d_121('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')), + toStringTag: _$d_121('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')), + unscopables: _$d_121('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables')) +}); + +// Internal tweaks for real symbol producer +defineProperties(HiddenSymbol.prototype, { + constructor: _$d_121(SymbolPolyfill), + toString: _$d_121('', function () { return this.__name__; }) +}); + +// Proper implementation of methods exposed on Symbol.prototype +// They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype +defineProperties(SymbolPolyfill.prototype, { + toString: _$d_121(function () { return 'Symbol (' + _$validateSymbol_189(this).__description__ + ')'; }), + valueOf: _$d_121(function () { return _$validateSymbol_189(this); }) +}); +__defineProperty_188(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, _$d_121('', function () { + var symbol = _$validateSymbol_189(this); + if (typeof symbol === 'symbol') return symbol; + return symbol.toString(); +})); +__defineProperty_188(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, _$d_121('c', 'Symbol')); + +// Proper implementaton of toPrimitive and toStringTag for returned symbol instances +__defineProperty_188(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, + _$d_121('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); + +// Note: It's important to define `toPrimitive` as last one, as some implementations +// implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) +// And that may invoke error in definition flow: +// See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 +__defineProperty_188(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, + _$d_121('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); + +'use strict'; + +var _$es6Symbol_185 = _$isImplemented_186() ? Symbol : _$polyfill_188; + +"use strict"; + +var iteratorSymbol = _$es6Symbol_185.iterator + , __dummy_142$0 = 0 + , __dummy_142$1 = 0 + , __dummy_142$2 = 0 + , __dummy_142$3 = 0 + , __dummy_142$4 = 0 + , __dummy_142$5 = 0 + , __dummy_142$6 = 0 + , __isArray_142 = Array.isArray + , call = Function.prototype.call + , desc = { configurable: true, enumerable: true, writable: true, value: null } + , __defineProperty_142 = Object.defineProperty; + +// eslint-disable-next-line complexity +var _$shim_142 = function (arrayLike /*, mapFn, thisArg*/) { + var mapFn = arguments[1] + , thisArg = arguments[2] + , Context + , i + , j + , arr + , length + , code + , iterator + , result + , getIterator + , value; + + arrayLike = Object(_$validValue_171(arrayLike)); + + if (_$isValue_160(mapFn)) _$validCallable_169(mapFn); + if (!this || this === Array || !_$isFunction_144(this)) { + // Result: Plain array + if (!mapFn) { + if (_$isArguments_143(arrayLike)) { + // Source: Arguments + length = arrayLike.length; + if (length !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (__isArray_142(arrayLike)) { + // Source: Array + arr = new Array(length = arrayLike.length); + for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + // Result: Non plain array + Context = this; + } + + if (!__isArray_142(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { + // Source: Iterator + iterator = _$validCallable_169(getIterator).call(arrayLike); + if (Context) arr = new Context(); + result = iterator.next(); + i = 0; + while (!result.done) { + value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; + if (Context) { + desc.value = value; + __defineProperty_142(arr, i, desc); + } else { + arr[i] = value; + } + result = iterator.next(); + ++i; + } + length = i; + } else if (_$isString_175(arrayLike)) { + // Source: String + length = arrayLike.length; + if (Context) arr = new Context(); + for (i = 0, j = 0; i < length; ++i) { + value = arrayLike[i]; + if (i + 1 < length) { + code = value.charCodeAt(0); + // eslint-disable-next-line max-depth + if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; + } + value = mapFn ? call.call(mapFn, thisArg, value, j) : value; + if (Context) { + desc.value = value; + __defineProperty_142(arr, j, desc); + } else { + arr[j] = value; + } + ++j; + } + length = j; + } + } + if (length === undefined) { + // Source: array or array-like + length = _$toPosInteger_150(arrayLike.length); + if (Context) arr = new Context(length); + for (i = 0; i < length; ++i) { + value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (Context) { + desc.value = value; + __defineProperty_142(arr, i, desc); + } else { + arr[i] = value; + } + } + } + if (Context) { + desc.value = null; + arr.length = length; + } + return arr; +}; + +"use strict"; + +var _$from_140 = _$isImplemented_141() + ? Array.from + : _$shim_142; + +"use strict"; + +var __dummy_155$0 = 0 + , __dummy_155$1 = 0 + , __dummy_155$2 = 0; + +var _$copy_155 = function (obj/*, propertyNames, options*/) { + var copy = Object(_$validValue_171(obj)), propertyNames = arguments[1], options = Object(arguments[2]); + if (copy !== obj && !propertyNames) return copy; + var result = {}; + if (propertyNames) { + _$from_140(propertyNames, function (propertyName) { + if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; + }); + } else { + _$assign_152(result, obj); + } + return result; +}; + +// Internal method, used by iteration functions. +// Calls a function for each key-value pair found in object +// Optionally takes compareFn to iterate object in specific order + +"use strict"; + +var __dummy_151$0 = 0 + , __dummy_151$1 = 0 + , bind = Function.prototype.bind + , __call_151 = Function.prototype.call + , __keys_151 = Object.keys + , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; + +var _$_iterate_151 = function (method, defVal) { + return function (obj, cb /*, thisArg, compareFn*/) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(_$validValue_171(obj)); + _$validCallable_169(cb); + + list = __keys_151(obj); + if (compareFn) { + list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); + } + if (typeof method !== "function") method = list[method]; + return __call_151.call(method, list, function (key, index) { + if (!objPropertyIsEnumerable.call(obj, key)) return defVal; + return __call_151.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; + +"use strict"; + +var _$forEach_157 = _$_iterate_151("forEach"); + +"use strict"; + +var __dummy_164$0 = 0 + , __dummy_164$1 = 0 + , __call_164 = Function.prototype.call; + +var _$map_164 = function (obj, cb /*, thisArg*/) { + var result = {}, thisArg = arguments[2]; + _$validCallable_169(cb); + _$forEach_157(obj, function (value, key, targetObj, index) { + result[key] = __call_164.call(cb, thisArg, value, key, targetObj, index); + }); + return result; +}; + +'use strict'; + +var __dummy_120$0 = 0 + , __dummy_120$1 = 0 + , __dummy_120$2 = 0 + , __dummy_120$3 = 0 + , __dummy_120$4 = 0 + , __dummy_120$5 = 0 + + , __bind_120 = Function.prototype.bind, __defineProperty_120 = Object.defineProperty + , __hasOwnProperty_120 = Object.prototype.hasOwnProperty + , define; + +define = function (name, desc, options) { + var value = _$validValue_171(desc) && _$validCallable_169(desc.value), dgs; + dgs = _$copy_155(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function () { + if (!options.overwriteDefinition && __hasOwnProperty_120.call(this, name)) return value; + desc.value = __bind_120.call(value, options.resolveContext ? options.resolveContext(this) : this); + __defineProperty_120(this, name, desc); + return this[name]; + }; + return dgs; +}; + +var _$autoBind_120 = function (props/*, options*/) { + var options = _$normalizeOptions_165(arguments[1]); + if (options.resolveContext != null) _$validCallable_169(options.resolveContext); + return _$map_164(props, function (desc, name) { return define(name, desc, options); }); +}; + +// Inspired by Google Closure: +// http://closure-library.googlecode.com/svn/docs/ +// closure_goog_array_array.js.html#goog.array.clear + +"use strict"; + +/* removed: var _$validValue_171 = require("../../object/valid-value"); */; + +var _$clear_139 = function () { + _$validValue_171(this).length = 0; + return this; +}; + +"use strict"; + +var __dummy_180$0 = 0 + , __dummy_180$1 = 0 + , __dummy_180$2 = 0 + , __dummy_180$3 = 0 + , __dummy_180$4 = 0 + , __dummy_180$5 = 0 + , __dummy_180$6 = 0; + +var __defineProperty_180 = Object.defineProperty, __defineProperties_180 = Object.defineProperties, Iterator; + +var _$es6Iterator_180 = Iterator = function (list, context) { + if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); + __defineProperties_180(this, { + __list__: _$d_121("w", _$validValue_171(list)), + __context__: _$d_121("w", context), + __nextIndex__: _$d_121("w", 0) + }); + if (!context) return; + _$validCallable_169(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_180( + Iterator.prototype, + _$assign_152( + { + _next: _$d_121(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_121(function () { + return this._createResult(this._next()); + }), + _createResult: _$d_121(function (i) { + if (i === undefined) return { done: true, value: undefined }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: _$d_121(function (i) { + return this.__list__[i]; + }), + _unBind: _$d_121(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_121(function () { + return "[object " + (this[_$es6Symbol_185.toStringTag] || "Object") + "]"; + }) + }, + _$autoBind_120({ + _onAdd: _$d_121(function (index) { + if (index >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + __defineProperty_180(this, "__redo__", _$d_121("c", [index])); + return; + } + this.__redo__.forEach(function (redo, i) { + if (redo >= index) this.__redo__[i] = ++redo; + }, this); + this.__redo__.push(index); + }), + _onDelete: _$d_121(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_121(function () { + if (this.__redo__) _$clear_139.call(this.__redo__); + this.__nextIndex__ = 0; + }) + }) + ) +); + +__defineProperty_180( + Iterator.prototype, + _$es6Symbol_185.iterator, + _$d_121(function () { + return this; + }) +); + +var _$array_177 = {}; +"use strict"; + +var __dummy_177$0 = 0 + , __dummy_177$1 = 0 + , __dummy_177$2 = 0 + , __dummy_177$3 = 0 + , __dummy_177$4 = 0; + +var __defineProperty_177 = Object.defineProperty, ArrayIterator; + +ArrayIterator = _$array_177 = function (arr, kind) { + if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); + _$es6Iterator_180.call(this, arr); + if (!kind) kind = "value"; + else if (_$contains_172.call(kind, "key+value")) kind = "key+value"; + else if (_$contains_172.call(kind, "key")) kind = "key"; + else kind = "value"; + __defineProperty_177(this, "__kind__", _$d_121("", kind)); +}; +if (_$setPrototypeOf_166) _$setPrototypeOf_166(ArrayIterator, _$es6Iterator_180); + +// Internal %ArrayIteratorPrototype% doesn't expose its constructor +delete ArrayIterator.prototype.constructor; + +ArrayIterator.prototype = Object.create(_$es6Iterator_180.prototype, { + _resolve: _$d_121(function (i) { + if (this.__kind__ === "value") return this.__list__[i]; + if (this.__kind__ === "key+value") return [i, this.__list__[i]]; + return i; + }) +}); +__defineProperty_177(ArrayIterator.prototype, _$es6Symbol_185.toStringTag, _$d_121("c", "Array Iterator")); + +var _$string_182 = {}; +// Thanks @mathiasbynens +// http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols + +"use strict"; + +var __dummy_182$0 = 0 + , __dummy_182$1 = 0 + , __dummy_182$2 = 0 + , __dummy_182$3 = 0; + +var __defineProperty_182 = Object.defineProperty, StringIterator; + +StringIterator = _$string_182 = function (str) { + if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); + str = String(str); + _$es6Iterator_180.call(this, str); + __defineProperty_182(this, "__length__", _$d_121("", str.length)); +}; +if (_$setPrototypeOf_166) _$setPrototypeOf_166(StringIterator, _$es6Iterator_180); + +// Internal %ArrayIteratorPrototype% doesn't expose its constructor +delete StringIterator.prototype.constructor; + +StringIterator.prototype = Object.create(_$es6Iterator_180.prototype, { + _next: _$d_121(function () { + if (!this.__list__) return undefined; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + return undefined; + }), + _resolve: _$d_121(function (i) { + var char = this.__list__[i], code; + if (this.__nextIndex__ === this.__length__) return char; + code = char.charCodeAt(0); + if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++]; + return char; + }) +}); +__defineProperty_182(StringIterator.prototype, _$es6Symbol_185.toStringTag, _$d_121("c", "String Iterator")); - return inside; -} +"use strict"; -// 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_134(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; +var __dummy_181$0 = 0 + , __dummy_181$1 = 0 + , __dummy_181$2 = 0; - a.next = b; - b.prev = a; +var __iteratorSymbol_181 = _$es6Symbol_185.iterator + , __isArray_181 = Array.isArray; - a2.next = an; - an.prev = a2; +var _$isIterable_181 = function (value) { + if (!_$isValue_160(value)) return false; + if (__isArray_181(value)) return true; + if (_$isString_175(value)) return true; + if (_$isArguments_143(value)) return true; + return typeof value[__iteratorSymbol_181] === "function"; +}; - b2.next = a2; - a2.prev = b2; +"use strict"; - bp.next = b2; - b2.prev = bp; +/* removed: var _$isIterable_181 = require("./is-iterable"); */; - return b2; -} +var _$validIterable_183 = function (value) { + if (!_$isIterable_181(value)) throw new TypeError(value + " is not iterable"); + return value; +}; -// 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); +"use strict"; - if (!last) { - p.prev = p; - p.next = p; +var __dummy_179$0 = 0 + , __dummy_179$1 = 0 + , __dummy_179$2 = 0 + , __dummy_179$3 = 0 + , __dummy_179$4 = 0 + , __iteratorSymbol_179 = _$es6Symbol_185.iterator; - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} +var _$get_179 = function (obj) { + if (typeof _$validIterable_183(obj)[__iteratorSymbol_179] === "function") return obj[__iteratorSymbol_179](); + if (_$isArguments_143(obj)) return new _$array_177(obj); + if (_$isString_175(obj)) return new _$string_182(obj); + return new _$array_177(obj); +}; -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; +"use strict"; - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} +var __dummy_178$0 = 0 + , __dummy_178$1 = 0 + , __dummy_178$2 = 0 + , __dummy_178$3 = 0; -function Node(i, x, y) { - // vertice index in coordinates array - this.i = i; +var __isArray_178 = Array.isArray, __call_178 = Function.prototype.call, some = Array.prototype.some; - // vertex coordinates - this.x = x; - this.y = y; +var _$forOf_178 = function (iterable, cb /*, thisArg*/) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code; + if (__isArray_178(iterable) || _$isArguments_143(iterable)) mode = "array"; + else if (_$isString_175(iterable)) mode = "string"; + else iterable = _$get_179(iterable); - // previous and next vertice nodes in a polygon ring - this.prev = null; - this.next = null; + _$validCallable_169(cb); + doBreak = function () { + broken = true; + }; + if (mode === "array") { + some.call(iterable, function (value) { + __call_178.call(cb, thisArg, value, doBreak); + return broken; + }); + return; + } + if (mode === "string") { + length = iterable.length; + for (i = 0; i < length; ++i) { + char = iterable[i]; + if (i + 1 < length) { + code = char.charCodeAt(0); + if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i]; + } + __call_178.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); - // z-order curve value - this.z = null; + while (!result.done) { + __call_178.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } +}; - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; +// Exports true if environment provides native `WeakMap` implementation, whatever that is. - // indicates whether this is a steiner point - this.steiner = false; -} +'use strict'; -// 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 _$isNativeImplemented_192 = (function () { + if (typeof WeakMap !== 'function') return false; + return (Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'); +}()); - 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)); - } - } +'use strict'; - 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])); - } +var __dummy_193$0 = 0 + , __dummy_193$1 = 0 + , __dummy_193$2 = 0 + , __dummy_193$3 = 0 + , __dummy_193$4 = 0 + , __dummy_193$5 = 0 + , __dummy_193$6 = 0 + , toStringTagSymbol = _$es6Symbol_185.toStringTag + , __dummy_193$7 = 0 - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); + , __isArray_193 = Array.isArray, __defineProperty_193 = Object.defineProperty + , __hasOwnProperty_193 = Object.prototype.hasOwnProperty, __getPrototypeOf_193 = Object.getPrototypeOf + , WeakMapPoly; + +var _$polyfill_193 = WeakMapPoly = function (/*iterable*/) { + var iterable = arguments[0], self; + if (!(this instanceof WeakMapPoly)) throw new TypeError('Constructor requires \'new\''); + if (_$isNativeImplemented_192 && _$setPrototypeOf_166 && (WeakMap !== WeakMapPoly)) { + self = _$setPrototypeOf_166(new WeakMap(), __getPrototypeOf_193(this)); + } else { + self = this; + } + if (iterable != null) { + if (!__isArray_193(iterable)) iterable = _$get_179(iterable); + } + __defineProperty_193(self, '__weakMapData__', _$d_121('c', '$weakMap$' + _$randomUniq_176())); + if (!iterable) return self; + _$forOf_178(iterable, function (val) { + _$validValue_171(val); + self.set(val[0], val[1]); + }); + return self; }; -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; +if (_$isNativeImplemented_192) { + if (_$setPrototypeOf_166) _$setPrototypeOf_166(WeakMapPoly, WeakMap); + WeakMapPoly.prototype = Object.create(WeakMap.prototype, { + constructor: _$d_121(WeakMapPoly) + }); } -// 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; +Object.defineProperties(WeakMapPoly.prototype, { + delete: _$d_121(function (key) { + if (__hasOwnProperty_193.call(_$validObject_170(key), this.__weakMapData__)) { + delete key[this.__weakMapData__]; + return true; + } + return false; + }), + get: _$d_121(function (key) { + if (__hasOwnProperty_193.call(_$validObject_170(key), this.__weakMapData__)) { + return key[this.__weakMapData__]; + } + }), + has: _$d_121(function (key) { + return __hasOwnProperty_193.call(_$validObject_170(key), this.__weakMapData__); + }), + set: _$d_121(function (key, value) { + __defineProperty_193(_$validObject_170(key), this.__weakMapData__, _$d_121('c', value)); + return this; + }), + toString: _$d_121(function () { return '[object WeakMap]'; }) +}); +__defineProperty_193(WeakMapPoly.prototype, toStringTagSymbol, _$d_121('c', 'WeakMap')); - 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; -}; +'use strict'; + +var _$es6WeakMap_190 = _$isImplemented_191() ? WeakMap : _$polyfill_193; 'use strict' -/* removed: var _$normalize_99 = require('color-normalize') */; -/* removed: var _$normalize_48 = require('array-bounds') */; -/* removed: var _$objectAssign_281 = require('object-assign') */; -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$pick_290 = require('pick-by-alias') */; -/* removed: var _$updateDiff_363 = require('update-diff') */; -/* removed: var _$flattenVertexData_141 = require('flatten-vertex-data') */; -/* removed: var _$earcut_134 = require('earcut') */; -/* removed: var _$normalize_49 = require('array-normalize') */; -var _$createLine_312 = __createLine_312 +/* removed: var _$normalize_100 = require('color-normalize') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$earcut_137 = require('earcut') */; +/* removed: var _$normalize_50 = require('array-normalize') */; +/* removed: var _$toFloat32_415 = require('to-float32'); */; +var __float32_375 = _$toFloat32_415.float32; +var __fract32_375 = _$toFloat32_415.fract32; +/* removed: var _$es6WeakMap_190 = require('es6-weak-map') */; +/* removed: var _$parseRect_343 = require('parse-rect') */; -var MAX_SCALE = 1e10; +var _$Line2D_375 = Line2D -function __createLine_312 (regl, options) { +/** @constructor */ +function Line2D (regl, options) { + if (!(this instanceof Line2D)) { return new Line2D(regl, options) } + if (typeof regl === 'function') { if (!options) { options = {} } options.regl = regl @@ -139537,63 +142154,39 @@ function __createLine_312 (regl, options) { } // persistent variables - var gl = regl._gl, drawMiterLine, drawRectLine, drawFill, colorBuffer, offsetBuffer, positionBuffer, positionFractBuffer, dashTexture, - - // used to for new lines instances - defaults = { - positions: [], - dashes: null, - join: null, - miterLimit: 1, - thickness: 10, - cap: 'square', - color: 'black', - opacity: 1, - overlay: false, - viewport: null, - range: null, - close: null, - fill: null - }, + this.gl = regl._gl + this.regl = regl - // list of options for lines - lines = [] + // list of options for lines + this.passes = [] - var dashMult = 2, maxPatternLength = 256, maxLinesNumber = 2048, precisionThreshold = 3e6, maxPoints = 1e4 + // cached shaders instance + this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl) - // color per-point - colorBuffer = regl.buffer({ - usage: 'dynamic', - type: 'uint8', - data: null - }) - offsetBuffer = regl.buffer({ + // init defaults + this.update(options) +} + + +Line2D.dashMult = 2 +Line2D.maxPatternLength = 256 +Line2D.precisionThreshold = 3e6 +Line2D.maxPoints = 1e4 + + + +// cache of created draw calls per-regl instance +Line2D.shaders = new _$es6WeakMap_190() + + +// create static shaders once +Line2D.createShaders = function (regl) { + var offsetBuffer = regl.buffer({ usage: 'static', type: 'float', data: [0,1, 0,0, 1,1, 1,0] }) - positionBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - positionFractBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - dashTexture = regl.texture({ - channels: 1, - data: new Uint8Array(maxPatternLength * maxLinesNumber), - width: maxPatternLength, - height: maxLinesNumber, - mag: 'linear', - min: 'linear' - }) - - // init defaults - update(options) var shaderOptions = { primitive: 'triangle strip', @@ -139609,13 +142202,11 @@ function __createLine_312 (regl, options) { translateFract: regl.prop('translateFract'), translate: regl.prop('translate'), thickness: regl.prop('thickness'), - dashPattern: dashTexture, - dashLength: regl.prop('dashLength'), - dashShape: [maxPatternLength, maxLinesNumber], + dashPattern: regl.prop('dashTexture'), opacity: regl.prop('opacity'), pixelRatio: regl.context('pixelRatio'), id: regl.prop('id'), - scaleRatio: regl.prop('scaleRatio'), + dashSize: regl.prop('dashLength'), viewport: function (ctx, prop) { return [prop.viewport.x, prop.viewport.y, ctx.viewportWidth, ctx.viewportHeight]; } }, @@ -139634,141 +142225,157 @@ function __createLine_312 (regl, options) { } }, depth: { + // FIXME: that fills up stencil buffer enable: function (ctx, prop) { return !prop.overlay } }, + stencil: {enable: false}, scissor: { enable: true, box: regl.prop('viewport') }, - stencil: false, viewport: regl.prop('viewport') } - // create regl draw - drawMiterLine = regl(_$objectAssign_281({ - // culling removes polygon creasing - cull: { - enable: true, - face: 'back' - }, - - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, dashLength, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIST = 1.;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevDirection = normalize(prevDiff);\n\tvec2 currDirection = normalize(currDiff);\n\tvec2 nextDirection = normalize(nextDiff);\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tif (prevDirection == currDirection) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (nextDirection == currDirection) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]), - frag: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), - - attributes: { - lineEnd: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 0 - }, - lineTop: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 4 - }, - aColor: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4; }, - divisor: 1 - }, - bColor: { - buffer: colorBuffer, - stride: 4, - offset: function (ctx, prop) { return prop.offset * 4 + 4; }, - divisor: 1 - }, - prevCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return prop.offset * 8; }, - divisor: 1 - }, - aCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, - divisor: 1 - }, - bCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, - divisor: 1 - }, - nextCoord: { - buffer: positionBuffer, - stride: 8, - offset: function (ctx, prop) { return 24 + prop.offset * 8; }, - divisor: 1 - } - } - }, shaderOptions)) // simplified rectangular line shader - drawRectLine = regl(_$objectAssign_281({ - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\t// vec2 scaleRatio = scale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scaleRatio);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), - frag: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + var drawRectLine = regl(_$objectAssign_339({ + vert: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), + frag: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), attributes: { + // if point is at the end of segment lineEnd: { buffer: offsetBuffer, divisor: 0, stride: 8, offset: 0 }, + // if point is at the top of segment lineTop: { buffer: offsetBuffer, divisor: 0, stride: 8, offset: 4 }, + // beginning of line coordinate aCoord: { - buffer: positionBuffer, + buffer: regl.prop('positionBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, + offset: 8, divisor: 1 }, + // end of line coordinate bCoord: { - buffer: positionBuffer, + buffer: regl.prop('positionBuffer'), stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, + offset: 16, divisor: 1 }, aCoordFract: { - buffer: positionFractBuffer, + buffer: regl.prop('positionFractBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; }, + offset: 8, divisor: 1 }, bCoordFract: { - buffer: positionFractBuffer, + buffer: regl.prop('positionFractBuffer'), stride: 8, - offset: function (ctx, prop) { return 16 + prop.offset * 8; }, + offset: 16, divisor: 1 }, color: { - buffer: colorBuffer, + buffer: regl.prop('colorBuffer'), stride: 4, - offset: function (ctx, prop) { return prop.offset * 4; }, + offset: 0, divisor: 1 } } }, shaderOptions)) + // create regl draw + var drawMiterLine + + try { + drawMiterLine = regl(_$objectAssign_339({ + // culling removes polygon creasing + cull: { + enable: true, + face: 'back' + }, + + vert: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n\t// adjust scale for horizontal bars\n\tvec2 scale = max(scale, MIN_DIFF);\n\tvec2 scaleRatio = scale * viewport.zw;\n\n\tvec2 normalWidth = thickness / (scale * viewport.zw);\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]), + frag: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]), + + attributes: { + // is line end + lineEnd: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 0 + }, + // is line top + lineTop: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 4 + }, + // left color + aColor: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 0, + divisor: 1 + }, + // right color + bColor: { + buffer: regl.prop('colorBuffer'), + stride: 4, + offset: 4, + divisor: 1 + }, + prevCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 0, + divisor: 1 + }, + aCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 8, + divisor: 1 + }, + bCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 16, + divisor: 1 + }, + nextCoord: { + buffer: regl.prop('positionBuffer'), + stride: 8, + offset: 24, + divisor: 1 + } + } + }, shaderOptions)) + } catch (e) { + // IE/bad Webkit fallback + drawMiterLine = drawRectLine + } // fill shader - drawFill = regl({ + var drawFill = regl({ primitive: 'triangle', elements: function (ctx, prop) { return prop.triangles; }, offset: 0, - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]), - frag: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= opacity;\n}\n"]), + vert: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]), + frag: _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]), uniforms: { scale: regl.prop('scale'), @@ -139784,494 +142391,456 @@ function __createLine_312 (regl, options) { attributes: { position: { - buffer: positionBuffer, + buffer: regl.prop('positionBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; } + offset: 8 }, positionFract: { - buffer: positionFractBuffer, + buffer: regl.prop('positionFractBuffer'), stride: 8, - offset: function (ctx, prop) { return 8 + prop.offset * 8; } + offset: 8 } }, blend: shaderOptions.blend, - depth: { - enable: false - }, + depth: { enable: false }, scissor: shaderOptions.scissor, stencil: shaderOptions.stencil, viewport: shaderOptions.viewport }) - // expose API - _$objectAssign_281(line2d, { - update: update, - draw: draw, - destroy: destroy, - regl: regl, - gl: gl, - canvas: gl.canvas, - lines: lines - }) + return { + fill: drawFill, rect: drawRectLine, miter: drawMiterLine + } +} - function line2d (opts) { - // update - if (opts) { - update(opts) - } - // destroy - else if (opts === null) { - destroy() - } +// used to for new lines instances +Line2D.defaults = { + dashes: null, + join: 'miter', + miterLimit: 1, + thickness: 10, + cap: 'square', + color: 'black', + opacity: 1, + overlay: false, + viewport: null, + range: null, + close: false, + fill: null +} - draw() + +Line2D.prototype.render = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (args.length) { + (ref = this).update.apply(ref, args) } - function draw (options) { - if (typeof options === 'number') { return drawLine(options) } + this.draw() + var ref; +} - // make options a batch - if (options && !Array.isArray(options)) { options = [options] } - // render multiple polylines via regl batch - lines.forEach(function (s, i) { - drawLine(i) - }) - } +Line2D.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - // draw single line by id - function drawLine (s) { - if (typeof s === 'number') { s = lines[s] } + // render multiple polylines via regl batch + (args.length ? args : this.passes).forEach(function (s, i) { + // render array pass as a list of passes + if (s && Array.isArray(s)) { return (ref = this$1).draw.apply(ref, s) } - if (!(s && s.count && s.opacity && s.positions && s.positions.length > 2)) { return } + if (typeof s === 'number') { s = this$1.passes[s] } - regl._refresh() + if (!(s && s.count > 1 && s.opacity)) { return } + + this$1.regl._refresh() if (s.fill && s.triangles && s.triangles.length > 2) { - drawFill(s) + this$1.shaders.fill(s) } - if (!s.thickness || !s.color) { return } - - s.scaleRatio = [ - s.scale[0] * s.viewport.width, - s.scale[1] * s.viewport.height - ] + if (!s.thickness) { return } // high scale is only available for rect mode with precision - if (s.scaleRatio[0] > precisionThreshold || s.scaleRatio[1] > precisionThreshold) { - drawRectLine(s) + if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) { + this$1.shaders.rect(s) } - // thin lines or too many points are rendered as simplified rect shader - else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.positions.length >= maxPoints))) { - drawRectLine(s) + // thin this.passes or too many points are rendered as simplified rect shader + else if (s.join === 'rect' || (!s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints))) { + this$1.shaders.rect(s) } else { - drawMiterLine(s) - } - - if (s.after) { s.after(s) } - } - - function update (options) { - if (!options) { return } - - if (options.length != null) { - if (typeof options[0] === 'number') { options = [{positions: options}] } - } - - // make options a batch - else if (!Array.isArray(options)) { options = [options] } + this$1.shaders.miter(s) + } + var ref; + }) - // global count of points - var pointCount = 0 + return this +} - // process per-line settings - line2d.lines = lines = options.map(function (options, i) { - var state = lines[i] - if (options === undefined) { return state } +Line2D.prototype.update = function (options) { + var this$1 = this; - // null-argument resets positions - if (options === null) { options = { positions: null } } - else if (typeof options === 'function') { options = {after: options} } - else if (typeof options[0] === 'number') { options = {positions: options} } + if (!options) { return } - // reduce by aliases - options = _$pick_290(options, { - positions: 'positions points data coords', - thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth', - join: 'lineJoin linejoin join type mode', - miterLimit: 'miterlimit miterLimit', - dashes: 'dash dashes dasharray dash-array dashArray', - color: 'color stroke colors stroke-color strokeColor', - fill: 'fill fill-color fillColor', - opacity: 'alpha opacity', - overlay: 'overlay crease overlap intersect', - close: 'closed close closed-path closePath', - range: 'range dataBox', - viewport: 'viewport viewBox', - hole: 'holes hole hollow', - after: 'after callback done pass' - }) + if (options.length != null) { + if (typeof options[0] === 'number') { options = [{positions: options}] } + } - // reset positions - if (options.positions === null) { options.positions = [] } + // make options a batch + else if (!Array.isArray(options)) { options = [options] } - if (!state) { - lines[i] = state = { - id: i, - scale: null, - scaleFract: null, - translate: null, - translateFract: null, - count: 0, - offset: 0, - dashLength: 0, - hole: true - } - options = _$objectAssign_281({}, defaults, options) - } + var ref = this; + var regl = ref.regl; + var gl = ref.gl; + // process per-line settings + options.forEach(function (o, i) { + var state = this$1.passes[i] - // calculate state values - _$updateDiff_363(state, options, [{ - thickness: parseFloat, - opacity: parseFloat, - miterLimit: parseFloat, - overlay: Boolean, - join: function (j) { return j; }, - after: function (fn) { return fn; }, - hole: function (h) { return h || []; }, + if (o === undefined) { return } - positions: function (positions, state, options) { - positions = _$flattenVertexData_141(positions, 'float64') + // null-argument removes pass + if (o === null) { + this$1.passes[i] = null + return + } - var count = Math.floor(positions.length / 2) - var bounds = _$normalize_48(positions, 2) + if (typeof o[0] === 'number') { o = {positions: o} } + + // handle aliases + o = _$pick_349(o, { + positions: 'positions points data coords', + thickness: 'thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth', + join: 'lineJoin linejoin join type mode', + miterLimit: 'miterlimit miterLimit', + dashes: 'dash dashes dasharray dash-array dashArray', + color: 'color colour stroke colors colours stroke-color strokeColor', + fill: 'fill fill-color fillColor', + opacity: 'alpha opacity', + overlay: 'overlay crease overlap intersect', + close: 'closed close closed-path closePath', + range: 'range dataBox', + viewport: 'viewport viewBox', + hole: 'holes hole hollow' + }) - // FIXME: make it dynamic - if (!state.range && !options.range) { - options.range = bounds - } + // init state + if (!state) { + this$1.passes[i] = state = { + id: i, + scale: null, + scaleFract: null, + translate: null, + translateFract: null, + count: 0, + hole: [], + + dashLength: 1, + dashTexture: regl.texture({ + channels: 1, + data: new Uint8Array([255]), + width: 1, + height: 1, + mag: 'linear', + min: 'linear' + }), + + colorBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8', + data: null + }), + positionBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }), + positionFractBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }) + } - state.count = count - state.bounds = bounds + o = _$objectAssign_339({}, Line2D.defaults, o) + } + if (o.thickness != null) { state.thickness = parseFloat(o.thickness) } + if (o.opacity != null) { state.opacity = parseFloat(o.opacity) } + if (o.miterLimit != null) { state.miterLimit = parseFloat(o.miterLimit) } + if (o.overlay != null) { state.overlay = !!o.overlay } + if (o.join != null) { state.join = o.join } + if (o.hole != null) { state.hole = o.hole } + if (o.fill != null) { state.fill = !o.fill ? null : _$normalize_100(o.fill, 'uint8') } + if (o.viewport != null) { state.viewport = _$parseRect_343(o.viewport) } + + if (!state.viewport) { + state.viewport = _$parseRect_343([ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]) + } - pointCount += count + if (o.close != null) { state.close = o.close } + + // reset positions + if (o.positions === null) { o.positions = [] } + if (o.positions) { + var positions, count + + // if positions are an object with x/y + if (o.positions.x && o.positions.y) { + var xPos = o.positions.x + var yPos = o.positions.y + count = state.count = Math.max( + xPos.length, + yPos.length + ) + positions = new Float64Array(count * 2) + for (var i$1 = 0; i$1 < count; i$1++) { + positions[i$1 * 2] = xPos[i$1] + positions[i$1 * 2 + 1] = yPos[i$1] + } + } + else { + positions = _$flattenVertexData_198(o.positions, 'float64') + count = state.count = Math.floor(positions.length / 2) + } - return positions - }, + var bounds = state.bounds = _$normalize_49(positions, 2) - fill: function (c) { - return !c ? null : _$normalize_99(c, 'uint8') - }, + // create fill positions + // FIXME: fill positions can be set only along with positions + if (state.fill) { + var pos = [] - dashes: function (dashes, state, options) { - var dashLength = state.dashLength, - dashData + // filter bad vertices and remap triangles to ensure shape + var ids = {} + var lastId = 0 - if (!dashes || dashes.length < 2) { - dashLength = 1. - dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]) + for (var i$2 = 0, ptr = 0, l = state.count; i$2 < l; i$2++) { + var x = positions[i$2*2] + var y = positions[i$2*2 + 1] + if (isNaN(x) || isNaN(y) || x == null || y == null) { + x = positions[lastId*2] + y = positions[lastId*2 + 1] + ids[i$2] = lastId } - else { - dashLength = 0.; - for(var i = 0; i < dashes.length; ++i) { - dashLength += dashes[i] - } - dashData = new Uint8Array(dashLength * dashMult) - var ptr = 0 - var fillColor = 255 - - // repeat texture two times to provide smooth 0-step - for (var k = 0; k < 2; k++) { - for(var i$1 = 0; i$1 < dashes.length; ++i$1) { - for(var j = 0, l = dashes[i$1] * dashMult * .5; j < l; ++j) { - dashData[ptr++] = fillColor - } - fillColor ^= 255 - } - } + lastId = i$2 } - - dashTexture.subimage({ - // channels: 1, - data: dashData, - width: dashData.length, - height: 1 - }, 0, state.id) - - state.dashLength = dashLength - - return dashData + pos[ptr++] = x + pos[ptr++] = y } - }, - // dependent properties & complement actions - { - close: function (close, state, options) { - if (close != null) { return close } - if (state.positions.length >= 4 && - state.positions[0] === state.positions[state.positions.length - 2] && - state.positions[1] === state.positions[state.positions.length - 1]) { - return true - } - return false - }, - - positions: function (p, state, options) { - if (state.fill && p.length) { - var pos = [] - - // filter bad vertices and remap triangles to ensure shape - var ids = {} - var lastId = 0 - - for (var i = 0, ptr = 0, l = state.count; i < l; i++) { - var x = state.positions[i*2] - var y = state.positions[i*2 + 1] - if (Number.isNaN(x) || Number.isNaN(y)) { - x = state.positions[lastId*2] - y = state.positions[lastId*2 + 1] - ids[i] = lastId - } - else { - lastId = i - } - pos[ptr++] = x - pos[ptr++] = y - } - - var triangles = _$earcut_134(pos, state.hole) - - for (var i$1 = 0, l$1 = triangles.length; i$1 < l$1; i$1++) { - if (ids[triangles[i$1]] != null) { triangles[i$1] = ids[triangles[i$1]] } - } - - state.triangles = triangles - } - return state.positions - }, - - color: function (colors, state, options) { - var count = state.count + var triangles = _$earcut_137(pos, state.hole || []) - if (!colors) { colors = 'transparent' } + for (var i$3 = 0, l$1 = triangles.length; i$3 < l$1; i$3++) { + if (ids[triangles[i$3]] != null) { triangles[i$3] = ids[triangles[i$3]] } + } - // 'black' or [0,0,0,0] case - if (!Array.isArray(colors) || typeof colors[0] === 'number') { - var color = colors; - colors = Array(count); - for (var i = 0; i < count; i++) { - colors[i] = color - } - } + state.triangles = triangles + } - if (colors.length < count) { throw Error('Not enough colors') } + // update position buffers + var npos = new Float64Array(positions) + _$normalize_50(npos, 2, bounds) - var colorData = new Uint8Array(count * 4 + 4) + var positionData = new Float64Array(count * 2 + 6) - // convert colors to float arrays - for (var i$1 = 0; i$1 < count; i$1++) { - var c = _$normalize_99(colors[i$1], 'uint8') - colorData.set(c, i$1 * 4) - } + // rotate first segment join + if (state.close) { + if (positions[0] === positions[count*2 - 2] && + positions[1] === positions[count*2 - 1]) { + positionData[0] = npos[count*2 - 4] + positionData[1] = npos[count*2 - 3] + } + else { + positionData[0] = npos[count*2 - 2] + positionData[1] = npos[count*2 - 1] + } + } + else { + positionData[0] = npos[0] + positionData[1] = npos[1] + } - return colorData - }, + positionData.set(npos, 2) - range: function (range, state, options) { - if (!state.count) { return null } + // add last segment + if (state.close) { + // ignore coinciding start/end + if (positions[0] === positions[count*2 - 2] && + positions[1] === positions[count*2 - 1]) { + positionData[count*2 + 2] = npos[2] + positionData[count*2 + 3] = npos[3] + state.count -= 1 + } + else { + positionData[count*2 + 2] = npos[0] + positionData[count*2 + 3] = npos[1] + positionData[count*2 + 4] = npos[2] + positionData[count*2 + 5] = npos[3] + } + } + // add stub + else { + positionData[count*2 + 2] = npos[count*2 - 2] + positionData[count*2 + 3] = npos[count*2 - 1] + positionData[count*2 + 4] = npos[count*2 - 2] + positionData[count*2 + 5] = npos[count*2 - 1] + } - var bounds = state.bounds - if (!range) { range = bounds } + state.positionBuffer(__float32_375(positionData)) + state.positionFractBuffer(__fract32_375(positionData)) + } - var boundsW = bounds[2] - bounds[0], - boundsH = bounds[3] - bounds[1] + if (o.range) { + state.range = o.range + } else if (!state.range) { + state.range = state.bounds + } - var rangeW = range[2] - range[0], - rangeH = range[3] - range[1] + if ((o.range || o.positions) && state.count) { + var bounds$1 = state.bounds - state.scale = [ - boundsW / rangeW, - boundsH / rangeH - ] - state.translate = [ - -range[0] / rangeW + bounds[0] / rangeW || 0, - -range[1] / rangeH + bounds[1] / rangeH || 0 - ] + var boundsW = bounds$1[2] - bounds$1[0], + boundsH = bounds$1[3] - bounds$1[1] - state.scaleFract = __fract32_312(state.scale) - state.translateFract = __fract32_312(state.translate) + var rangeW = state.range[2] - state.range[0], + rangeH = state.range[3] - state.range[1] - return range - }, + state.scale = [ + boundsW / rangeW, + boundsH / rangeH + ] + state.translate = [ + -state.range[0] / rangeW + bounds$1[0] / rangeW || 0, + -state.range[1] / rangeH + bounds$1[1] / rangeH || 0 + ] - viewport: function (vp) { - var viewport + state.scaleFract = __fract32_375(state.scale) + state.translateFract = __fract32_375(state.translate) + } - if (Array.isArray(vp)) { - viewport = { - x: vp[0], - y: vp[1], - width: vp[2] - vp[0], - height: vp[3] - vp[1] - } - } - else if (vp) { - viewport = { - x: vp.x || vp.left || 0, - y: vp.y || vp.top || 0 - } + if (o.dashes) { + var dashLength = 0., dashData - if (vp.right) { viewport.width = vp.right - viewport.x } - else { viewport.width = vp.w || vp.width || 0 } + if (!o.dashes || o.dashes.length < 2) { + dashLength = 1. + dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]) + } - if (vp.bottom) { viewport.height = vp.bottom - viewport.y } - else { viewport.height = vp.h || vp.height || 0 } - } - else { - viewport = { - x: 0, y: 0, - width: gl.drawingBufferWidth, - height: gl.drawingBufferHeight + else { + dashLength = 0.; + for(var i$4 = 0; i$4 < o.dashes.length; ++i$4) { + dashLength += o.dashes[i$4] + } + dashData = new Uint8Array(dashLength * Line2D.dashMult) + var ptr$1 = 0 + var fillColor = 255 + + // repeat texture two times to provide smooth 0-step + for (var k = 0; k < 2; k++) { + for(var i$5 = 0; i$5 < o.dashes.length; ++i$5) { + for(var j = 0, l$2 = o.dashes[i$5] * Line2D.dashMult * .5; j < l$2; ++j) { + dashData[ptr$1++] = fillColor } + fillColor ^= 255 } - - return viewport } - }]) + } - return state - }) + state.dashLength = dashLength + state.dashTexture({ + channels: 1, + data: dashData, + width: dashData.length, + height: 1, + mag: 'linear', + min: 'linear' + }, 0, 0) + } - // put collected data into buffers - // FIXME: possible optimization is updating only segment subdata - if (pointCount) { - var len = pointCount * 2 + lines.length * 6; - var positionData = new Float64Array(len) - var offset = 0 - var colorData = new Uint8Array(len * 2) + if (o.color) { + var count$1 = state.count + var colors = o.color - lines.forEach(function (state, i) { - if (!state) { return } + if (!colors) { colors = 'transparent' } - var positions = state.positions; - var count = state.count; - var color = state.color; - state.offset = offset + var colorData = new Uint8Array(count$1 * 4 + 4) - if (!count) { return } + // convert colors to typed arrays + if (!Array.isArray(colors) || typeof colors[0] === 'number') { + var c = _$normalize_100(colors, 'uint8') - // provide normalized positions - var npos = new Float64Array(positions.length) - npos.set(positions) - _$normalize_49(npos, 2, state.bounds) - - // rotate first segment join - if (state.close) { - if (positions[0] === positions[count*2 - 2] && - positions[1] === positions[count*2 - 1]) { - positionData[offset*2 + 0] = npos[count*2 - 4] - positionData[offset*2 + 1] = npos[count*2 - 3] - } - else { - positionData[offset*2 + 0] = npos[count*2 - 2] - positionData[offset*2 + 1] = npos[count*2 - 1] - } - } - else { - positionData[offset*2 + 0] = npos[0] - positionData[offset*2 + 1] = npos[1] - } - colorData[offset*4 + 0] = color[0] - colorData[offset*4 + 1] = color[1] - colorData[offset*4 + 2] = color[2] - colorData[offset*4 + 3] = color[3] - - positionData.set(npos, offset * 2 + 2) - colorData.set(color, offset * 4 + 4) - - // add last segment - if (state.close) { - // ignore coinciding start/end - if (positions[0] === positions[count*2 - 2] && - positions[1] === positions[count*2 - 1]) { - positionData[offset*2 + count*2 + 2] = npos[2] - positionData[offset*2 + count*2 + 3] = npos[3] - offset += count + 2 - state.count -= 1 - } - else { - positionData[offset*2 + count*2 + 2] = npos[0] - positionData[offset*2 + count*2 + 3] = npos[1] - positionData[offset*2 + count*2 + 4] = npos[2] - positionData[offset*2 + count*2 + 5] = npos[3] - offset += count + 3 - } + for (var i$6 = 0; i$6 < count$1 + 1; i$6++) { + colorData.set(c, i$6 * 4) } - // add stub - else { - positionData[offset*2 + count*2 + 2] = npos[count*2 - 2] - positionData[offset*2 + count*2 + 3] = npos[count*2 - 1] - positionData[offset*2 + count*2 + 4] = npos[count*2 - 2] - positionData[offset*2 + count*2 + 5] = npos[count*2 - 1] - offset += count + 3 + } else { + for (var i$7 = 0; i$7 < count$1; i$7++) { + var c$1 = _$normalize_100(colors[i$7], 'uint8') + colorData.set(c$1, i$7 * 4) } - }) + colorData.set(_$normalize_100(colors[0], 'uint8'), count$1 * 4) + } - colorBuffer(colorData) - positionBuffer(__float32_312(positionData)) - positionFractBuffer(__fract32_312(positionData)) + state.colorBuffer({ + usage: 'dynamic', + type: 'uint8', + data: colorData + }) } + }) - return line2d + // remove unmentioned passes + if (options.length < this.passes.length) { + for (var i = options.length; i < this.passes.length; i++) { + var pass = this$1.passes[i] + if (!pass) { continue } + pass.colorBuffer.destroy() + pass.positionBuffer.destroy() + pass.dashTexture.destroy() + } + this.passes.length = options.length } - function destroy () { - lines.length = 0 - colorBuffer.destroy() - offsetBuffer.destroy() - positionBuffer.destroy() - dashTexture.destroy() - } + // remove null items + this.passes = this.passes.filter(Boolean) - return line2d + return this } +Line2D.prototype.destroy = function () { + this.passes.forEach(function (pass) { + pass.colorBuffer.destroy() + pass.positionBuffer.destroy() + pass.dashTexture.destroy() + }) -// return fractional part of float32 array -function __fract32_312 (arr) { - var fract = new Float32Array(arr.length) - fract.set(arr) - for (var i = 0, l = fract.length; i < l; i++) { - fract[i] = arr[i] - fract[i] - } - return fract -} -function __float32_312 (arr) { - if (arr instanceof Float32Array) { return arr } + this.passes.length = 0 - var float = new Float32Array(arr) - float.set(arr) - return float + return this } -var _$colorId_97 = {}; +var _$colorId_98 = {}; /** @module color-id */ 'use strict' -/* removed: var _$clamp_94 = require('clamp') */; +/* removed: var _$clamp_95 = require('clamp') */; -_$colorId_97 = toNumber -_$colorId_97.to = toNumber -_$colorId_97.from = fromNumber +_$colorId_98 = toNumber +_$colorId_98.to = toNumber +_$colorId_98.from = fromNumber function toNumber (rgba, normalized) { if(normalized == null) normalized = true @@ -140287,10 +142856,10 @@ function toNumber (rgba, normalized) { a *= 255 } - r = _$clamp_94(r, 0, 255) & 0xFF - g = _$clamp_94(g, 0, 255) & 0xFF - b = _$clamp_94(b, 0, 255) & 0xFF - a = _$clamp_94(a, 0, 255) & 0xFF + r = _$clamp_95(r, 0, 255) & 0xFF + g = _$clamp_95(g, 0, 255) & 0xFF + b = _$clamp_95(b, 0, 255) & 0xFF + a = _$clamp_95(a, 0, 255) & 0xFF //hi-order shift converts to -1, so we can't use <<24 var n = (r * 0x01000000) + (g << 16) + (b << 8) + (a) @@ -140312,597 +142881,35 @@ function fromNumber (n, normalized) { } 'use strict'; -var _$isIexplorer_248 = typeof navigator !== 'undefined' && +var _$isIexplorer_305 = typeof navigator !== 'undefined' && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); 'use strict' -/* removed: var _$pick_290 = require('pick-by-alias') */; - -var _$parseRect_285 = 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) - } - - // 0, 0, 100, 100 - array-like - if (arg.length && typeof arg[0] === 'number') { - if (arg.length === 2) { - rect = { - width: arg[0], - height: arg[1], - x: 0, - y: 0 - } - } - else { - rect = { - x: arg[0], - y: arg[1], - width: (arg[2] - arg[0]) || 0, - height: (arg[3] - arg[1]) || 0 - } - } - } - else if (arg) { - arg = _$pick_290(arg, { - left: 'x l left Left', - top: 'y t top Top', - width: 'w width', - height: 'h height', - bottom: 'b bottom', - right: 'r 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 -} - -"use strict" - -function __compileSearch_314(funcName, predicate, reversed, extraArgs, 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[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_314(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - __compileSearch_314("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - __compileSearch_314("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() -} - -var _$searchBounds_314 = { - ge: __compileBoundsSearch_314(">=", false, "GE"), - gt: __compileBoundsSearch_314(">", false, "GT"), - lt: __compileBoundsSearch_314("<", true, "LT"), - le: __compileBoundsSearch_314("<=", true, "LE"), - eq: __compileBoundsSearch_314("-", true, "EQ", true) -} - -'use strict' - -var _$sortLevels_340 = sortLevels - -var __INSERT_SORT_CUTOFF_340 = 32 - -function sortLevels(data_levels, data_points, data_ids, data_weights, n0) { - if (n0 <= 4*__INSERT_SORT_CUTOFF_340) { - __insertionSort_340(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } -} - -function __insertionSort_340(left, right, data_levels, data_points, data_ids, data_weights) { - for(var i=left+1; i<=right; ++i) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - var j = i - while(j > left) { - var b_level = data_levels[j-1] - var b_x = data_points[2*(j-1)] - if(((b_level - a_level) || (a_x - b_x)) >= 0) { - break - } - data_levels[j] = b_level - data_points[2*j] = b_x - data_points[2*j+1] = data_points[2*j-1] - data_ids[j] = data_ids[j-1] - data_weights[j] = data_weights[j-1] - j -= 1 - } - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight - } -} - -function __swap_340(i, j, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} - -function __move_340(i, j, data_levels, data_points, data_ids, data_weights) { - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] -} - -function __rotate_340(i, j, k, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = data_levels[k] - data_points[2*j] = data_points[2*k] - data_points[2*j+1] = data_points[2*k+1] - data_ids[j] = data_ids[k] - data_weights[j] = data_weights[k] - - data_levels[k] = a_level - data_points[2*k] = a_x - data_points[2*k+1] = a_y - data_ids[k] = a_id - data_weights[k] = a_weight -} - -function __shufflePivot_340( - i, j, - a_level, a_x, a_y, a_id, a_weight, - data_levels, data_points, data_ids, data_weights) { - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} - -function __compare_340(i, j, data_levels, data_points, data_ids) { - return ((data_levels[i] - data_levels[j]) || - (data_points[2*j] - data_points[2*i]) || - (data_ids[i] - data_ids[j])) < 0 -} - -function __comparePivot_340(i, level, x, y, id, data_levels, data_points, data_ids) { - return ((level - data_levels[i]) || - (data_points[2*i] - x) || - (id - data_ids[i])) < 0 -} - -function __quickSort_340(left, right, data_levels, data_points, data_ids, data_weights) { - 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_340(el1, el2, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el2 - el2 = tmp - } - if(__compare_340(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - if(__compare_340(el1, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el3 - el3 = tmp - } - if(__compare_340(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(__compare_340(el1, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el4 - el4 = tmp - } - if(__compare_340(el3, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el3 - el3 = el4 - el4 = tmp - } - if(__compare_340(el2, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el5 - el5 = tmp - } - if(__compare_340(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(__compare_340(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - - var pivot1_level = data_levels[el2] - var pivot1_x = data_points[2*el2] - var pivot1_y = data_points[2*el2+1] - var pivot1_id = data_ids[el2] - var pivot1_weight = data_weights[el2] - - var pivot2_level = data_levels[el4] - var pivot2_x = data_points[2*el4] - var pivot2_y = data_points[2*el4+1] - var pivot2_id = data_ids[el4] - var pivot2_weight = data_weights[el4] - - var ptr0 = el1 - var ptr2 = el3 - var ptr4 = el5 - var ptr5 = index1 - var ptr6 = index3 - var ptr7 = index5 - - var level_x = data_levels[ptr0] - var level_y = data_levels[ptr2] - var level_z = data_levels[ptr4] - data_levels[ptr5] = level_x - data_levels[ptr6] = level_y - data_levels[ptr7] = level_z - - for (var i1 = 0; i1 < 2; ++i1) { - var x = data_points[2*ptr0+i1] - var y = data_points[2*ptr2+i1] - var z = data_points[2*ptr4+i1] - data_points[2*ptr5+i1] = x - data_points[2*ptr6+i1] = y - data_points[2*ptr7+i1] = z - } - - var id_x = data_ids[ptr0] - var id_y = data_ids[ptr2] - var id_z = data_ids[ptr4] - data_ids[ptr5] = id_x - data_ids[ptr6] = id_y - data_ids[ptr7] = id_z - - var weight_x = data_weights[ptr0] - var weight_y = data_weights[ptr2] - var weight_z = data_weights[ptr4] - data_weights[ptr5] = weight_x - data_weights[ptr6] = weight_y - data_weights[ptr7] = weight_z - - __move_340(index2, left, data_levels, data_points, data_ids, data_weights) - __move_340(index4, right, data_levels, data_points, data_ids, data_weights) - for (var k = less; k <= great; ++k) { - if (__comparePivot_340(k, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - if (k !== less) { - __swap_340(k, less, data_levels, data_points, data_ids, data_weights) - } - ++less; - } else { - if (!__comparePivot_340(k, - pivot2_level, pivot2_x, pivot2_y, pivot2_id, - data_levels, data_points, data_ids)) { - while (true) { - if (!__comparePivot_340(great, - pivot2_level, pivot2_x, pivot2_y, pivot2_id, - data_levels, data_points, data_ids)) { - if (--great < k) { - break; - } - continue; - } else { - if (__comparePivot_340(great, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - __rotate_340(k, less, great, data_levels, data_points, data_ids, data_weights) - ++less; - --great; - } else { - __swap_340(k, great, data_levels, data_points, data_ids, data_weights) - --great; - } - break; - } - } - } - } - } - __shufflePivot_340(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) - __shufflePivot_340(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) - if (less - 2 - left <= __INSERT_SORT_CUTOFF_340) { - __insertionSort_340(left, less - 2, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(left, less - 2, data_levels, data_points, data_ids, data_weights) - } - if (right - (great + 2) <= __INSERT_SORT_CUTOFF_340) { - __insertionSort_340(great + 2, right, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(great + 2, right, data_levels, data_points, data_ids, data_weights) - } - if (great - less <= __INSERT_SORT_CUTOFF_340) { - __insertionSort_340(less, great, data_levels, data_points, data_ids, data_weights) - } else { - __quickSort_340(less, great, data_levels, data_points, data_ids, data_weights) - } -} - -'use strict' - -/* removed: var _$sortLevels_340 = require('./lib/sort') */; -/* removed: var _$normalize_48 = require('array-bounds') */; - -var _$snapPoints_341 = snapPoints - -function partition(points, ids, start, end, lox, loy, hix, hiy) { - var mid = start - for(var i=start; i>> 1 - if(n < 1) { - return [] - } - - if (!ids) ids = Array(n) - if (!weights) weights = Array(n) - if (!bounds) bounds = [] - - for(var i=0; i= bounds[2] || bounds[1] >= bounds[3]) { - var b = _$normalize_48(points, 2) - - if(b[0] === b[2]) { - b[2] += 1 - } - if(b[1] === b[3]) { - b[3] += 1 - } - - bounds[0] = b[0] - bounds[1] = b[1] - bounds[2] = b[2] - bounds[3] = b[3] - } +/* removed: var _$normalize_100 = require('color-normalize') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$colorId_98 = require('color-id') */; +/* removed: var _$pointCluster_353 = require('point-cluster') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; +/* removed: var _$browser_295 = require('glslify') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$updateDiff_425 = require('update-diff') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$isIexplorer_305 = require('is-iexplorer') */; +/* removed: var _$toFloat32_415 = require('to-float32'); */; +var __float32_377 = _$toFloat32_415.float32; +var __fract32_377 = _$toFloat32_415.fract32; +/* removed: var _$parseRect_343 = require('parse-rect') */; - var lox = bounds[0] - var loy = bounds[1] - var hix = bounds[2] - var hiy = bounds[3] - - //Calculate diameter - var scaleX = 1.0 / (hix - lox) - var scaleY = 1.0 / (hiy - loy) - var diam = Math.max(hix - lox, hiy - loy) - - - - var levels = new Int32Array(n) - var ptr = 0 - - function snapRec(x, y, diam, start, end, level) { - var diam_2 = diam * 0.5 - var offset = start + 1 - var count = end - start - weights[ptr] = count - levels[ptr++] = level - for(var i=0; i<2; ++i) { - for(var j=0; j<2; ++j) { - var nx = x+i*diam_2 - var ny = y+j*diam_2 - var nextOffset = partition( - points - , ids - , offset - , end - , nx, ny - , nx+diam_2, ny+diam_2) - if(nextOffset === offset) { - continue - } - if(nextOffset - offset >= Math.max(0.9 * count, 32)) { - var mid = (end + start)>>>1 - snapRec(nx, ny, diam_2, offset, mid, level+1) - offset = mid - } - snapRec(nx, ny, diam_2, offset, nextOffset, level+1) - offset = nextOffset - } - } - } - snapRec(lox, loy, diam, 0, n, 0) - _$sortLevels_340(levels, points, ids, weights, n) - - var lod = [] - var lastLevel = 0 - var prevOffset = n - for(var ptr=n-1; ptr>=0; --ptr) { - points[2*ptr] = (points[2*ptr] - lox) * scaleX - points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY - - var level = levels[ptr] - if(level === lastLevel) { - continue - } - lod.push(new SnapInterval( - diam * Math.pow(0.5, level), - ptr+1, - prevOffset - (ptr+1) - )) - prevOffset = ptr+1 +var _$Scatter_377 = __Scatter_377 - lastLevel = level - } - lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) +function __Scatter_377 (regl, options) { + var this$1 = this; - return lod -} - -'use strict' + if (!(this instanceof __Scatter_377)) { return new __Scatter_377(regl, options) } -/* removed: var _$normalize_99 = require('color-normalize') */; -/* removed: var _$normalize_48 = require('array-bounds') */; -/* removed: var _$colorId_97 = require('color-id') */; -/* removed: var _$snapPoints_341 = require('snap-points-2d') */; -/* removed: var _$objectAssign_281 = require('object-assign') */; -/* removed: var _$browser_238 = require('glslify') */; -/* removed: var _$searchBounds_314 = require('binary-search-bounds') */; -/* removed: var _$pick_290 = require('pick-by-alias') */; -/* removed: var _$updateDiff_363 = require('update-diff') */; -/* removed: var _$flattenVertexData_141 = require('flatten-vertex-data') */; -/* removed: var _$isIexplorer_248 = require('is-iexplorer') */; -/* removed: var _$toFloat32_353 = require('to-float32'); */; -var __float32_313 = _$toFloat32_353.float32; -var __fract32_313 = _$toFloat32_353.fract32; -/* removed: var _$newArray_50 = require('array-range') */; -/* removed: var _$parseRect_285 = require('parse-rect') */; - -var _$Scatter_313 = __Scatter_313 - - -function __Scatter_313 (regl, options) { if (typeof regl === 'function') { if (!options) { options = {} } options.regl = regl @@ -140913,29 +142920,11 @@ function __Scatter_313 (regl, options) { } if (options && options.length) { options.positions = options } + regl = options.regl // persistent variables - var gl = regl._gl, - drawMarker, drawCircle, - sizeBuffer, positionBuffer, positionFractBuffer, colorBuffer, - paletteTexture, palette = [], paletteIds = {}, - defaults = { - color: 'black', - borderColor: 'transparent', - borderSize: 1, - size: 12, - opacity: 1, - marker: undefined, - viewport: null, - range: null, - pixelSize: null, - offset: 0, - count: 0, - bounds: null, - positions: [], - snap: 1e4 - }, + var gl = regl._gl, paletteTexture, palette = [], paletteIds = {}, // state groups = [], @@ -140944,7 +142933,11 @@ function __Scatter_313 (regl, options) { markerTextures = [null], markerCache = [null] - var maxColors = 4096, maxSize = 100 + var maxColors = 255, maxSize = 100 + + // direct color buffer mode + // IE does not support palette anyways + this.tooManyColors = _$isIexplorer_305 // texture with color palette paletteTexture = regl.texture({ @@ -140959,110 +142952,94 @@ function __Scatter_313 (regl, options) { min: 'nearest' }) - // buffers to reuse - sizeBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - colorBuffer = regl.buffer({ - usage: 'dynamic', - type: 'uint16', - data: null - }) - positionBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null - }) - positionFractBuffer = regl.buffer({ - usage: 'dynamic', - type: 'float', - data: null + _$objectAssign_339(this, { + regl: regl, + gl: gl, + groups: groups, + markerCache: markerCache, + markerTextures: markerTextures, + palette: palette, + paletteIds: paletteIds, + paletteTexture: paletteTexture, + maxColors: maxColors, + maxSize: maxSize, + canvas: gl.canvas }) - // fast-create from existing regl-scatter instance - if (options.clone) { - groups = options.clone.groups.map(function (group) { - group = _$objectAssign_281({}, group) - if (group.markerIds) { - group.markerIds = group.markerIds.map(function (ids) { - // recreate regl elements here - var newIds = ids.slice() - newIds.lod = ids.lod - newIds.snap = ids.snap - newIds.data = ids.data - newIds.id = ids.id - newIds.x = ids.x - newIds.w = ids.w - newIds.elements = regl.elements({ - primitive: 'points', - type: 'uint32', - data: ids.data - }) - return newIds - }) - } - return group - }) - - // create marker textures - options.clone.markers.forEach(function (markers) { - addMarker(markers) - }) - // clone palette texture - updatePalette(options.clone.palette) - updateBuffers({point: true, color: true, size: true}) - } - // full create from options - else { - update(options) - } - + this.update(options) // common shader options var shaderOptions = { uniforms: { pixelRatio: regl.context('pixelRatio'), palette: paletteTexture, - paletteSize: function (ctx, prop) { return [maxColors, paletteTexture.height]; }, + paletteSize: function (ctx, prop) { return [this$1.tooManyColors ? 0 : maxColors, paletteTexture.height]; }, scale: regl.prop('scale'), scaleFract: regl.prop('scaleFract'), translate: regl.prop('translate'), translateFract: regl.prop('translateFract'), opacity: regl.prop('opacity'), - marker: regl.prop('marker'), + marker: regl.prop('markerTexture'), }, attributes: { - position: positionBuffer, - positionFract: positionFractBuffer, + // FIXME: optimize these parts + x: function (ctx, prop) { return prop.xAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 0 + }; }, + y: function (ctx, prop) { return prop.yAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 4 + }; }, + xFract: function (ctx, prop) { return prop.xAttr ? { constant: [0, 0] } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 0 + }; }, + yFract: function (ctx, prop) { return prop.yAttr ? { constant: [0, 0] } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 4 + }; }, size: function (ctx, prop) { return prop.size.length ? { - buffer: sizeBuffer, + buffer: prop.sizeBuffer, stride: 2, offset: 0 - } : {constant: [Math.round(prop.size * 255 / maxSize)]}; }, + } : { + constant: [ Math.round(prop.size * 255 / this$1.maxSize) ] + }; }, borderSize: function (ctx, prop) { return prop.borderSize.length ? { - buffer: sizeBuffer, + buffer: prop.sizeBuffer, stride: 2, offset: 1 - } : {constant: [Math.round(prop.borderSize * 255 / maxSize)]}; }, + } : { + constant: [ Math.round(prop.borderSize * 255 / this$1.maxSize) ] + }; }, colorId: function (ctx, prop) { return prop.color.length ? { - buffer: colorBuffer, - stride: 8, + buffer: prop.colorBuffer, + stride: this$1.tooManyColors ? 8 : 4, offset: 0 - } : {constant: [prop.color]}; }, + } : { + constant: this$1.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [ prop.color ] + }; }, borderColorId: function (ctx, prop) { return prop.borderColor.length ? { - buffer: colorBuffer, - stride: 8, - offset: 4 - } : {constant: [prop.borderColor]}; } + buffer: prop.colorBuffer, + stride: this$1.tooManyColors ? 8 : 4, + offset: this$1.tooManyColors ? 4 : 2 + } : { + constant: this$1.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [ prop.borderColor ] + }; }, + isActive: function (ctx, prop) { return prop.activation === true ? { constant: [1] } : prop.activation ? prop.activation : { constant: [0] }; } }, - blend: { enable: true, color: [0,0,0,1], + + // photoshop blending func: { srcRGB: 'src alpha', dstRGB: 'one minus src alpha', @@ -141080,7 +143057,6 @@ function __Scatter_313 (regl, options) { stencil: {enable: false}, depth: {enable: false}, - elements: regl.prop('elements'), count: regl.prop('count'), offset: regl.prop('offset'), @@ -141088,673 +143064,896 @@ function __Scatter_313 (regl, options) { primitive: 'points' } - // IE11 shader workaround - if (_$isIexplorer_248) { - drawCircle = regl(_$objectAssign_281({}, shaderOptions, { - frag: _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n\n float centerFraction = fragBorderSize == 0. ? 2. : fragSize / (fragSize + fragBorderSize + 1.25);\n\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, 1.);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"]), - vert: _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nvoid main() {\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n fragBorderSize = borderSize;\n fragSize = size;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragWidth = 1. / gl_PointSize;\n}\n"]), - uniforms: { - // FIXME: generate attribute color data - color: function (ctx, p) { - var id = p.color.length ? p.color[0] : p.color; - return palette.slice(id * 4, id * 4 + 4).map(function (v) { return v / 255; }) - }, - borderColor: function (ctx, p) { - var id = p.borderColor.length ? p.borderColor[0] : p.borderColor; - return palette.slice(id * 4, id * 4 + 4).map(function (v) { return v / 255; }) - }, - pixelRatio: regl.context('pixelRatio'), - palette: paletteTexture, - paletteSize: function (ctx, prop) { return [maxColors, paletteTexture.height]; }, - scale: regl.prop('scale'), - scaleFract: regl.prop('scaleFract'), - translate: regl.prop('translate'), - translateFract: regl.prop('translateFract'), - opacity: regl.prop('opacity'), - marker: regl.prop('marker') - }, - attributes: { - position: positionBuffer, - positionFract: positionFractBuffer, - size: shaderOptions.attributes.size, - borderSize: shaderOptions.attributes.borderSize - } - })) - } - else { - // draw sdf-marker - var markerOptions = _$objectAssign_281({}, shaderOptions) - markerOptions.frag = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n //max-distance alpha\n if (dist < 0.003) discard;\n\n //null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]) - markerOptions.vert = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n\t\tfragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]) - - drawMarker = regl(markerOptions) - - // draw circle - var circleOptions = _$objectAssign_281({}, shaderOptions) - circleOptions.frag = _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif(radius > 1.0 + delta) {\n\t\tdiscard;\n\t\treturn;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]) - circleOptions.vert = _$browser_238(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]) + // draw sdf-marker + var markerOptions = _$objectAssign_339({}, shaderOptions) + markerOptions.frag = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]) + markerOptions.vert = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n fragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]) - drawCircle = regl(circleOptions) + try { + this.drawMarker = regl(markerOptions) + } catch (e) { } - // expose API - _$objectAssign_281(scatter2d, { - update: update, - draw: draw, - destroy: destroy, - regl: regl, - gl: gl, - canvas: gl.canvas, - groups: groups, - markers: markerCache, - palette: palette - }) - - - // main update/draw function - function scatter2d (opts) { - // update - if (opts) { - update(opts) - } + // draw circle + var circleOptions = _$objectAssign_339({}, shaderOptions) + circleOptions.frag = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]) + circleOptions.vert = _$browser_295(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]) - // destroy - else if (opts === null) { - destroy() - } + // polyfill IE + if (_$isIexplorer_305) { circleOptions.frag = circleOptions.frag.replace('smoothstep', 'smoothStep') } - draw() - } + this.drawCircle = regl(circleOptions) +} - // draw all groups or only indicated ones - function draw (opts) { - if (typeof opts === 'number') { return drawGroup(opts) } +// single pass defaults +__Scatter_377.defaults = { + color: 'black', + borderColor: 'transparent', + borderSize: 0, + size: 12, + opacity: 1, + marker: undefined, + viewport: null, + range: null, + pixelSize: null, + count: 0, + offset: 0, + bounds: null, + positions: [], + snap: 1e4 +} - // highlight elements - if (Array.isArray(opts)) { - opts.forEach(function (els, i) { - if (els == null) { return } - if (els.length) { return drawGroup(els, i) } - return drawGroup(els) - }) - return - } - // make options a batch - groups.forEach(function (group, i) { - if (!group) { return } +// update & redraw +__Scatter_377.prototype.render = function () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - drawGroup(i) - }) + if (args.length) { + (ref = this).update.apply(ref, args) } - // draw specific scatter group - function drawGroup (group, id) { - if (typeof group === 'number') { group = groups[group] } + this.draw() - var els + return this + var ref; +} - if (Array.isArray(group)) { - els = group - group = groups[id] - } - if (!(group && group.count && group.opacity)) { return } +// draw all groups or only indicated ones +__Scatter_377.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; - // if subset of elements to redraw passed - form a whitelist - var whitelist - if (els) { - whitelist = Array(group.count); + var ref = this; + var groups = ref.groups; - for (var i = 0; i < els.length; i++) { - whitelist[els[i]] = true - } + // if directly array passed - treat as passes + if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) { + args = args[0] + } + + if (args.length) { + for (var i = 0; i < args.length; i++) { + this$1.drawItem(i, args[i]) } + } + // draw all passes + else { + groups.forEach(function (group, i) { + this$1.drawItem(i) + }) + } - // draw circles - // FIXME remove regl._refresh hooks once regl issue #427 is fixed - if (group.markerIds[0]) { - regl._refresh() + return this +} - var opts = getMarkerDrawOptions(group.markerIds[0], group, whitelist) +// draw specific scatter group +__Scatter_377.prototype.drawItem = function (id, els) { + var this$1 = this; + + var ref = this; + var groups = ref.groups; + var group = groups[id] + + // debug viewport + // let { viewport } = group + // gl.enable(gl.SCISSOR_TEST); + // gl.scissor(viewport.x, viewport.y, viewport.width, viewport.height); + // gl.clearColor(0, 0, 0, .5); + // gl.clear(gl.COLOR_BUFFER_BIT); + + if (typeof els === 'number') { + id = els + group = groups[els] + els = null + } - drawCircle(opts) - } + if (!(group && group.count && group.opacity)) { return } - // draw all other available markers - var batch = [] - for (var i$1 = 1; i$1 < group.markerIds.length; i$1++) { - var ids = group.markerIds[i$1] + // draw circles + if (group.activation[0]) { + // TODO: optimize this performance by making groups and regl.this props + this.drawCircle(this.getMarkerDrawOptions(0, group, els)) + } - if (!ids || !ids.length) { continue } + // draw all other available markers + var batch = [] - [].push.apply(batch, getMarkerDrawOptions(ids, group, whitelist)) - } + for (var i = 1; i < group.activation.length; i++) { + if (!group.activation[i] || (group.activation[i] !== true && !group.activation[i].data.length)) { continue } - if (batch.length) { - regl._refresh() - drawMarker(batch) - } + batch.push.apply(batch, this$1.getMarkerDrawOptions(i, group, els)) } - // get options for the marker ids - function getMarkerDrawOptions(ids, group, whitelist) { - var range = group.range; - var offset = group.offset; - // unsnapped options - if (!ids.snap) { - var elements = whitelist ? filter(ids.data, whitelist) : ids.elements; + if (batch.length) { + this.drawMarker(batch) + } +} - return [_$objectAssign_281({}, group, { +// get options for the marker ids +__Scatter_377.prototype.getMarkerDrawOptions = function(markerId, group, elements) { + var this$1 = this; + + var range = group.range; + var tree = group.tree; + var viewport = group.viewport; + var activation = group.activation; + var selectionBuffer = group.selectionBuffer; + var count = group.count; + var ref = this; + var regl = ref.regl; + + // direct points + if (!tree) { + // if elements array - draw unclustered points + if (elements) { + return [_$objectAssign_339({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + count: elements.length, elements: elements, - offset: 0, - count: whitelist ? elements.length : ids.length, - marker: markerTextures[ids.id] + offset: 0 })] } - // scales batch - var batch = [] - var lod = ids.lod; - var x = ids.x; - var id = ids.id; - - var pixelSize = Math.min((range[2] - range[0]) / group.viewport.width, (range[3] - range[1]) / group.viewport.height) + return [ _$objectAssign_339({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + offset: 0 + }) ] + } - for (var scaleNum = lod.length; scaleNum--;) { - var level = lod[scaleNum] + // clustered points + var batch = [] + + var lod = tree.range(range, { lod: true, px: [ + (range[2] - range[0]) / viewport.width, + (range[3] - range[1]) / viewport.height + ]}) + + // enable elements by using selection buffer + if (elements) { + var markerActivation = activation[markerId] + var mask = markerActivation.data + var data = new Uint8Array(count) + for (var i = 0; i < elements.length; i++) { + var id = elements[i] + data[id] = mask ? mask[id] : 1 + } + selectionBuffer.subdata(data) + } - // FIXME: use minSize-adaptive coeff here, if makes sense, mb we need dist tho - if (level.pixelSize && level.pixelSize < pixelSize && scaleNum > 1) { - continue - } + for (var l = lod.length; l--;) { + var ref$1 = lod[l]; + var from = ref$1[0]; + var to = ref$1[1]; - var intervalStart = level.offset - var intervalEnd = level.count + intervalStart + batch.push(_$objectAssign_339({}, group, { + markerTexture: this$1.markerTextures[markerId], + activation: elements ? selectionBuffer : activation[markerId], + offset: from, + count: to - from, - var startOffset = _$searchBounds_314.ge(x, range[0], intervalStart, intervalEnd - 1) - var endOffset = _$searchBounds_314.lt(x, range[2], startOffset, intervalEnd - 1) + 1 + // send tree elements + elements: group.elements + })) + } - if (endOffset <= startOffset) { continue } + return batch +} - // whitelisted level requires subelements from the range - if (whitelist) { - var elements$1 = filter(ids.data.subarray(startOffset, endOffset), whitelist) +// update groups options +__Scatter_377.prototype.update = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { return } + + // passes are as single array + if (args.length === 1 && Array.isArray(args[0])) { args = args[0] } + + var ref = this; + var groups = ref.groups; + var gl = ref.gl; + var regl = ref.regl; + var maxSize = ref.maxSize; + var maxColors = ref.maxColors; + var palette = ref.palette; + + this.groups = groups = args.map(function (options, i) { + var group = groups[i] + + if (options === undefined) { return group } + + if (options === null) { options = { positions: null } } + else if (typeof options === 'function') { options = { ondraw: options } } + else if (typeof options[0] === 'number') { options = { positions: options } } + + // copy options to avoid mutation & handle aliases + options = _$pick_349(options, { + positions: 'positions data points', + snap: 'snap cluster lod tree', + size: 'sizes size radius', + borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline', + color: 'colors color fill fill-color fillColor', + borderColor: 'borderColors borderColor stroke stroke-color strokeColor', + marker: 'markers marker shape', + range: 'range dataBox databox', + viewport: 'viewport viewPort viewBox viewbox', + opacity: 'opacity alpha transparency', + bounds: 'bound bounds boundaries limits' + }) - batch.push(_$objectAssign_281({}, group, { - elements: elements$1, - marker: markerTextures[id], - offset: 0, - count: elements$1.length - })) - } - else { - batch.push(_$objectAssign_281({}, group, { - elements: ids.elements, - marker: markerTextures[id], - offset: startOffset, - count: endOffset - startOffset - })) + if (options.positions === null) { options.positions = [] } + + if (!group) { + groups[i] = group = { + id: i, + scale: null, + translate: null, + scaleFract: null, + translateFract: null, + + // buffers for active markers + activation: [], + + // buffer for filtered markers + selectionBuffer: regl.buffer({ + usage: 'stream', + type: 'uint8' + }), + + // buffers with data: it is faster to switch them per-pass + // than provide one congregate buffer + sizeBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8' + }), + colorBuffer: regl.buffer({ + usage: 'dynamic', + type: 'uint8' + }), + positionBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float' + }), + positionFractBuffer: regl.buffer({ + usage: 'dynamic', + type: 'float' + }) } + options = _$objectAssign_339({}, __Scatter_377.defaults, options) } - function filter(offsets, whitelist) { - var subEls = [] - for (var i = 0, l = offsets.length; i < l; i++) { - var el = offsets[i] - var id = el - offset - if (whitelist[id]) { - subEls.push(el) - } - } - return subEls + // force update triggers + if (options.positions && !('marker' in options)) { + options.marker = group.marker + delete group.marker } - return batch - } - - // update groups options - function update (options) { - if (!options) { return } - - // direct points argument - if (options.length != null) { - if (typeof options[0] === 'number') { options = [{positions: options}] } + // updating markers cause recalculating snapping + if (options.marker && !('positions' in options)) { + options.positions = group.positions + delete group.positions } - // make options a batch - else if (!Array.isArray(options)) { options = [options] } // global count of points - var pointCount = 0, sizeCount = 0, colorCount = 0 - - scatter2d.groups = groups = options.map(function (options, i) { - var group = groups[i] - - if (options === undefined) { return group } - - if (options === null) { options = { positions: null } } - else if (typeof options === 'function') { options = {after: options} } - else if (typeof options[0] === 'number') { options = {positions: options} } - - // copy options to avoid mutation & handle aliases - options = _$pick_290(options, { - positions: 'positions data points', - snap: 'snap cluster', - size: 'sizes size radius', - borderSize: 'borderSizes borderSize stroke-width strokeWidth outline', - color: 'colors color fill fill-color fillColor', - borderColor: 'borderColors borderColor stroke stroke-color strokeColor', - palette: 'palette swatch', - marker: 'markers marker shape', - range: 'range dataBox', - viewport: 'viewport viewBox', - opacity: 'opacity alpha' - }) + var hasSize = 0, hasColor = 0 + + _$updateDiff_425(group, options, [{ + snap: true, + size: function (s, group) { + if (s == null) { s = __Scatter_377.defaults.size } + hasSize += s && s.length ? 1 : 0 + return s + }, + borderSize: function (s, group) { + if (s == null) { s = __Scatter_377.defaults.borderSize } + hasSize += s && s.length ? 1 : 0 + return s + }, + opacity: parseFloat, + + // add colors to palette, save references + color: function (c, group) { + if (c == null) { c = __Scatter_377.defaults.color } + c = this$1.updateColor(c) + hasColor++ + return c + }, + borderColor: function (c, group) { + if (c == null) { c = __Scatter_377.defaults.borderColor } + c = this$1.updateColor(c) + hasColor++ + return c + }, - if (options.positions === null) { options.positions = [] } + bounds: function (bounds, group, options) { + if (!('range' in options)) { options.range = null } + return bounds + }, - if (!group) { - groups[i] = group = { - id: i, - scale: null, - translate: null, - scaleFract: null, - translateFract: null, + positions: function (positions, group, options) { + var snap = options.snap; + var positionBuffer = group.positionBuffer; + var positionFractBuffer = group.positionFractBuffer; + var selectionBuffer = group.selectionBuffer; + + // separate buffers for x/y coordinates + if (positions.x || positions.y) { + if (positions.x.length) { + group.xAttr = { + buffer: regl.buffer(positions.x), + offset: 0, + stride: 4, + count: positions.x.length + } + } + else { + group.xAttr = { + buffer: positions.x.buffer, + offset: positions.x.offset * 4 || 0, + stride: (positions.x.stride || 1) * 4, + count: positions.x.count + } + } + if (positions.y.length) { + group.yAttr = { + buffer: regl.buffer(positions.y), + offset: 0, + stride: 4, + count: positions.y.length + } + } + else { + group.yAttr = { + buffer: positions.y.buffer, + offset: positions.y.offset * 4 || 0, + stride: (positions.y.stride || 1) * 4, + count: positions.y.count + } + } + group.count = Math.max(group.xAttr.count, group.yAttr.count) - // list of ids corresponding to markers, with inner props - markerIds: [] + return positions } - options = _$objectAssign_281({}, defaults, options) - } - - // force update triggers - if (options.positions && !('marker' in options)) { - options.marker = group.marker - delete group.marker - } - // updating markers cause recalculating snapping - if (options.marker && !('positions' in options)) { - options.positions = group.positions - delete group.positions - } + positions = _$flattenVertexData_198(positions, 'float64') - _$updateDiff_363(group, options, [{ - snap: true, - size: function (s) { - sizeCount += s.length ? 1 : 0 - return s - }, - borderSize: function (s) { - sizeCount += s.length ? 1 : 0 - return s - }, - opacity: parseFloat, + var count = group.count = Math.floor(positions.length / 2) + var bounds = group.bounds = count ? _$normalize_49(positions, 2) : null - // add colors to palette, save references - color: function (c) { - c = updateColor(c) - colorCount++ - return c - }, - borderColor: function (c) { - c = updateColor(c) - colorCount++ - return c - }, + // if range is not provided updated - recalc it + if (!options.range && !group.range) { + delete group.range + options.range = bounds + } - positions: function (positions, group, options) { - positions = _$flattenVertexData_141(positions, 'float64') + // reset marker + if (!options.marker && !group.marker) { + delete group.marker; + options.marker = null; + } - var count = group.count = Math.floor(positions.length / 2) - var bounds = group.bounds = count ? _$normalize_48(positions, 2) : null + // build cluster tree if required + if (snap && (snap === true || count > snap)) { + group.tree = _$pointCluster_353(positions, { bounds: bounds }) + } + // existing tree instance + else if (snap && snap.length) { + group.tree = snap + } - // if range is not provided updated - recalc it - if (!options.range && !group.range) { - delete group.range - options.range = bounds + if (group.tree) { + var opts = { + primitive: 'points', + usage: 'static', + data: group.tree, + type: 'uint32' } + if (group.elements) { group.elements(opts) } + else { group.elements = regl.elements(opts) } + } - group.offset = pointCount - pointCount += count + // update position buffers + positionBuffer({ + data: __float32_377(positions), + usage: 'dynamic' + }) + positionFractBuffer({ + data: __fract32_377(positions), + usage: 'dynamic' + }) - // reset marker - if (!options.marker && !group.marker) { - delete group.marker; - options.marker = null; - } + // expand selectionBuffer + selectionBuffer({ + data: new Uint8Array(count), + type: 'uint8', + usage: 'stream' + }) - return positions + return positions + } + }, { + // create marker ids corresponding to known marker textures + marker: function (markers, group, options) { + var activation = group.activation; + + // reset marker elements + activation.forEach(function (buffer) { return buffer && buffer.destroy && buffer.destroy(); }) + activation.length = 0 + + // single sdf marker + if (!markers || typeof markers[0] === 'number') { + var id = this$1.addMarker(markers) + activation[id] = true } - }, { - // create marker ids corresponding to known marker textures - marker: function (markers, group, options) { - // reset marker elements - group.markerIds.length = 0 - // single sdf marker - if (!markers || typeof markers[0] === 'number') { - var id = addMarker(markers) + // per-point markers use mask buffers to enable markers in vert shader + else { + var markerMasks = [] - var elements = _$newArray_50(group.count) + for (var i = 0, l = Math.min(markers.length, group.count); i < l; i++) { + var id$1 = this$1.addMarker(markers[i]) - group.markerIds[id] = elements - } - // per-point markers - else { - for (var i = 0, l = markers.length; i < l; i++) { - var id$1 = addMarker(markers[i]) + if (!markerMasks[id$1]) { markerMasks[id$1] = new Uint8Array(group.count) } - if (!group.markerIds[id$1]) { group.markerIds[id$1] = [] } - group.markerIds[id$1].push(i) - } + // enable marker by default + markerMasks[id$1][i] = 1 } - return markers - } - }, { - // recalculate per-marker snapping - // first, it is faster to snap 100 points 100 times than 10000 points once (practically, not theoretically) - // second, it is easier to subset render per-marker than per-generic set - positions: function (positions, group) { - var markerIds = group.markerIds; - var snap = group.snap; - var bounds = group.bounds; - var offset = group.offset; - - for (var i = 0; i < markerIds.length; i++) { - var ids = markerIds[i] - if (!ids || !ids.length) { continue } - - var l = ids.length, els = (void 0) - - ids.id = i; - - if (snap && (snap === true || l > snap)) { - ids.snap = true - var x = ids.x = Array(l) - var w = ids.w = Array(l) - var markerPoints = (void 0) - - // multimarker snapping is computationally more intense - if (markerIds.length > 1) { - markerPoints = Array(l * 2) - - for (var i$1 = 0; i$1 < l; i$1++) { - var id = ids[i$1] - markerPoints[i$1 * 2] = positions[id * 2] - markerPoints[i$1 * 2 + 1] = positions[id * 2 + 1] - } - } - else { - markerPoints = new Float64Array(positions.length) - markerPoints.set(positions) - } - - // shuffled_id: real_id - var i2id = new Uint32Array(l) - - ids.lod = _$snapPoints_341(markerPoints, i2id, w, bounds) - - els = new Uint32Array(l) - for (var i$2 = 0; i$2 < l; i$2++) { - var id$1 = i2id[i$2], iid = ids[id$1] - els[i$2] = iid + offset - x[i$2] = positions[iid * 2] - } + for (var id$2 = 0; id$2 < markerMasks.length; id$2++) { + if (!markerMasks[id$2]) { continue } + + var opts = { + data: markerMasks[id$2], + type: 'uint8', + usage: 'static' + } + if (!activation[id$2]) { + activation[id$2] = regl.buffer(opts) } else { - els = new Uint32Array(l) - for (var i$3 = 0; i$3 < l; i$3++) { - els[i$3] = ids[i$3] + offset - } + activation[id$2](opts) } - ids.data = els; - ids.elements = regl.elements({ - primitive: 'points', - type: 'uint32', - data: els - }) + activation[id$2].data = markerMasks[id$2] } - }, - - range: function (range, group, options) { - var bounds = group.bounds - - if (!bounds) { return } - if (!range) { range = bounds } - - group.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] - group.translate = [-range[0], -range[1]] - - group.scaleFract = __fract32_313(group.scale) - group.translateFract = __fract32_313(group.translate) - - return range - }, - - viewport: function (vp) { - return _$parseRect_285(vp || [ - gl.drawingBufferWidth, - gl.drawingBufferHeight - ]) } - }]) - - return group - }) - updateBuffers({ - point: pointCount, - size: sizeCount, - color: colorCount - }) - } + return markers + }, - // update buffers data based on existing groups - function updateBuffers(ref) { - var point = ref.point; - var size = ref.size; - var color = ref.color; + range: function (range, group, options) { + var bounds = group.bounds - // put point/color data into buffers, if updated any of them - var len = groups.reduce(function (acc, group, i) { - return acc + (group ? group.count : 0) - }, 0) + // FIXME: why do we need this? + if (!bounds) { return } + if (!range) { range = bounds } - if (point) { - var positionData = new Float32Array(len * 2) - var positionFractData = new Float32Array(len * 2) + group.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])] + group.translate = [-range[0], -range[1]] - groups.forEach(function (group, i) { - if (!group) { return } - var positions = group.positions; - var count = group.count; - var offset = group.offset; - if (!count) { return } - positionData.set(__float32_313(positions), offset * 2) - positionFractData.set(__fract32_313(positions), offset * 2) - }) + group.scaleFract = __fract32_377(group.scale) + group.translateFract = __fract32_377(group.translate) - positionBuffer(positionData) - positionFractBuffer(positionFractData) - } + return range + }, - if (size) { - var sizeData = new Uint8Array(len * 2) + viewport: function (vp) { + var rect = _$parseRect_343(vp || [ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]) - groups.forEach(function (group, i) { - if (!group) { return } - var count = group.count; - var offset = group.offset; - var size = group.size; - var borderSize = group.borderSize; - if (!count) { return } + // normalize viewport to the canvas coordinates + // rect.y = gl.drawingBufferHeight - rect.height - rect.y - if (size.length || borderSize.length) { - var sizes = new Uint8Array(count*2) - for (var i$1 = 0; i$1 < count; i$1++) { - // we downscale size to allow for fractions - sizes[i$1*2] = Math.round((size[i$1] == null ? size : size[i$1]) * 255 / maxSize) - sizes[i$1*2 + 1] = Math.round((borderSize[i$1] == null ? borderSize : borderSize[i$1]) * 255 / maxSize) - } - sizeData.set(sizes, offset * 2) + return rect + } + }]) + + // update size buffer, if needed + if (hasSize) { + var count = group.count; + var size = group.size; + var borderSize = group.borderSize; + var sizeBuffer = group.sizeBuffer; + + var sizes = new Uint8Array(count*2) + if (size.length || borderSize.length) { + for (var i$1 = 0; i$1 < count; i$1++) { + // we downscale size to allow for fractions + sizes[i$1*2] = Math.round((size[i$1] == null ? size : size[i$1]) * 255 / maxSize) + sizes[i$1*2 + 1] = Math.round((borderSize[i$1] == null ? borderSize : borderSize[i$1]) * 255 / maxSize) } + } + sizeBuffer({ + data: sizes, + usage: 'dynamic' }) - sizeBuffer(sizeData) } - if (color) { - var colorData = new Uint16Array(len * 4) + // update color buffer if needed + if (hasColor) { + var count$1 = group.count; + var color = group.color; + var borderColor = group.borderColor; + var colorBuffer = group.colorBuffer; + var colors - groups.forEach(function (group, i) { - if (!group) { return } - var count = group.count; - var offset = group.offset; - var color = group.color; - var borderColor = group.borderColor; - if (!count) { return } + // if too many colors - put colors to buffer directly + if (this$1.tooManyColors) { + if (color.length || borderColor.length) { + colors = new Uint8Array(count$1 * 8) + for (var i$2 = 0; i$2 < count$1; i$2++) { + var colorId = color[i$2] + colors[i$2*8] = palette[colorId*4] + colors[i$2*8 + 1] = palette[colorId*4 + 1] + colors[i$2*8 + 2] = palette[colorId*4 + 2] + colors[i$2*8 + 3] = palette[colorId*4 + 3] + + var borderColorId = borderColor[i$2] + colors[i$2*8 + 4] = palette[borderColorId*4] + colors[i$2*8 + 5] = palette[borderColorId*4 + 1] + colors[i$2*8 + 6] = palette[borderColorId*4 + 2] + colors[i$2*8 + 7] = palette[borderColorId*4 + 3] + } + } + } + // if limited amount of colors - keep palette color picking + // that saves significant memory + else { if (color.length || borderColor.length) { - var colorIds = new Uint16Array(count * 4) - for (var i$1 = 0; i$1 < count; i$1++) { - if (color[i$1] != null) { - colorIds[i$1*4] = color[i$1] % maxColors - colorIds[i$1*4 + 1] = Math.floor(color[i$1] / maxColors) + // we need slight data increase by 2 due to vec4 borderId in shader + colors = new Uint8Array(count$1 * 4 + 2) + for (var i$3 = 0; i$3 < count$1; i$3++) { + // put color coords in palette texture + if (color[i$3] != null) { + colors[i$3*4] = color[i$3] % maxColors + colors[i$3*4 + 1] = Math.floor(color[i$3] / maxColors) } - if (borderColor[i$1] != null) { - colorIds[i$1*4 + 2] = borderColor[i$1] % maxColors - colorIds[i$1*4 + 3] = Math.floor(borderColor[i$1] / maxColors) + if (borderColor[i$3] != null) { + colors[i$3*4 + 2] = borderColor[i$3] % maxColors + colors[i$3*4 + 3] = Math.floor(borderColor[i$3] / maxColors) } } - - colorData.set(colorIds, offset * 4) } + } + + colorBuffer({ + data: colors, + type: 'uint8', + usage: 'dynamic' }) + } + return group + }) +} - colorBuffer(colorData) + +// get (and create) marker texture id +__Scatter_377.prototype.addMarker = function (sdf) { + var ref = this; + var markerTextures = ref.markerTextures; + var regl = ref.regl; + var markerCache = ref.markerCache; + + var pos = sdf == null ? 0 : markerCache.indexOf(sdf) + + if (pos >= 0) { return pos } + + // convert sdf to 0..255 range + var distArr + if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { + distArr = sdf + } + else { + distArr = new Uint8Array(sdf.length) + for (var i = 0, l = sdf.length; i < l; i++) { + distArr[i] = sdf[i] * 255 } } - // get (and create) marker texture id - function addMarker (sdf) { - var pos = sdf == null ? 0 : markerCache.indexOf(sdf) + var radius = Math.floor(Math.sqrt(distArr.length)) + + pos = markerTextures.length + + markerCache.push(sdf) + markerTextures.push(regl.texture({ + channels: 1, + data: distArr, + radius: radius, + mag: 'linear', + min: 'linear' + })) + + return pos +} + +// register color to palette, return it's index or list of indexes +__Scatter_377.prototype.updateColor = function (colors) { + var ref = this; + var paletteIds = ref.paletteIds; + var palette = ref.palette; + var maxColors = ref.maxColors; + + if (!Array.isArray(colors)) { + colors = [colors] + } + + var idx = [] - if (pos >= 0) { return pos } + // if color groups - flatten them + if (typeof colors[0] === 'number') { + var grouped = [] - // convert sdf to 0..255 range - var distArr - if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { - distArr = sdf + if (Array.isArray(colors)) { + for (var i = 0; i < colors.length; i+=4) { + grouped.push(colors.slice(i, i+4)) + } } else { - distArr = new Uint8Array(sdf.length) - for (var i = 0, l = sdf.length; i < l; i++) { - distArr[i] = sdf[i] * 255 + for (var i$1 = 0; i$1 < colors.length; i$1+=4) { + grouped.push(colors.subarray(i$1, i$1+4)) } } - var radius = Math.floor(Math.sqrt(distArr.length)) + colors = grouped + } - pos = markerTextures.length + for (var i$2 = 0; i$2 < colors.length; i$2++) { + var color = colors[i$2] - markerCache.push(sdf) - markerTextures.push(regl.texture({ - channels: 1, - data: distArr, - radius: radius, - mag: 'linear', - min: 'linear' - })) + color = _$normalize_100(color, 'uint8') - return pos - } + var id = _$colorId_98(color, false) - // register color to palette, return it's index or list of indexes - function updateColor (colors) { - if (!Array.isArray(colors)) { - colors = [colors] + // if new color - save it + if (paletteIds[id] == null) { + var pos = palette.length + paletteIds[id] = Math.floor(pos / 4) + palette[pos] = color[0] + palette[pos+1] = color[1] + palette[pos+2] = color[2] + palette[pos+3] = color[3] } - var idx = [] + idx[i$2] = paletteIds[id] + } + + // detect if too many colors in palette + if (!this.tooManyColors && palette.length > maxColors * maxColors * 4) { this.tooManyColors = true } - for (var i = 0; i < colors.length; i++) { - var color = colors[i] + // limit max color + this.updatePalette(palette) - // idx colors directly - if (typeof color === 'number') { - idx[i] = color - continue - } + // keep static index for single-color property + return idx.length === 1 ? idx[0] : idx +} - color = _$normalize_99(color, 'uint8') +__Scatter_377.prototype.updatePalette = function (palette) { + if (this.tooManyColors) { return } - var id = _$colorId_97(color, false) + var ref = this; + var maxColors = ref.maxColors; + var paletteTexture = ref.paletteTexture; - // if new color - save it - if (paletteIds[id] == null) { - var pos = palette.length - paletteIds[id] = Math.floor(pos / 4) - palette[pos] = color[0] - palette[pos+1] = color[1] - palette[pos+2] = color[2] - palette[pos+3] = color[3] - } + var requiredHeight = Math.ceil(palette.length * .25 / maxColors) - idx[i] = paletteIds[id] + // pad data + if (requiredHeight > 1) { + palette = palette.slice() + for (var i = (palette.length * .25) % maxColors; i < requiredHeight * maxColors; i++) { + palette.push(0, 0, 0, 0) } + } - // limit max color - updatePalette(palette) - - // keep static index for single-color property - return idx.length === 1 ? idx[0] : idx + // ensure height + if (paletteTexture.height < requiredHeight) { + paletteTexture.resize(maxColors, requiredHeight) } - function updatePalette(palette) { - var requiredHeight = Math.ceil(palette.length * .25 / maxColors) + // update full data + paletteTexture.subimage({ + width: Math.min(palette.length * .25, maxColors), + height: requiredHeight, + data: palette + }, 0, 0) +} - // pad data - if (requiredHeight > 1) { - palette = palette.slice() - for (var i = (palette.length * .25) % maxColors; i < requiredHeight * maxColors; i++) { - palette.push(0, 0, 0, 0) - } - } +// remove unused stuff +__Scatter_377.prototype.destroy = function () { + this.groups.forEach(function (group) { + group.sizeBuffer.destroy() + group.positionBuffer.destroy() + group.positionFractBuffer.destroy() + group.colorBuffer.destroy() + group.activation.forEach(function (b) { return b && b.destroy && b.destroy(); }) + group.selectionBuffer.destroy() + + if (group.elements) { group.elements.destroy() } + }) + this.groups.length = 0 - // ensure height - if (paletteTexture.height < requiredHeight) { - paletteTexture.resize(maxColors, requiredHeight) - } + this.paletteTexture.destroy() - // update full data - paletteTexture.subimage({ - width: Math.min(palette.length * .25, maxColors), - height: requiredHeight, - data: palette - }, 0, 0) - } + this.markerTextures.forEach(function (txt) { return txt && txt.destroy && txt.destroy(); }) - // remove unused stuff - function destroy () { - groups.length = 0 + return this +} +'use strict' - sizeBuffer.destroy() - positionBuffer.destroy() - positionFractBuffer.destroy() - colorBuffer.destroy() - paletteTexture.destroy() - } +/* removed: var _$Scatter_377 = require('./scatter') */; +/* removed: var _$objectAssign_339 = require('object-assign') */; + +var _$reglScatter2d_376 = function (regl, options) { + var scatter = new _$Scatter_377(regl, options) + + var render = scatter.render.bind(scatter) + + // expose API + _$objectAssign_339(render, { + render: render, + update: scatter.update.bind(scatter), + draw: scatter.draw.bind(scatter), + destroy: scatter.destroy.bind(scatter), + regl: scatter.regl, + gl: scatter.gl, + canvas: scatter.gl.canvas, + groups: scatter.groups, + markers: scatter.markerCache, + palette: scatter.palette + }) - return scatter2d + return render } +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var SYMBOL_SIZE = 20; + +var _$constants_975 = { + TOO_MANY_POINTS: 1e5, + + SYMBOL_SDF_SIZE: 200, + SYMBOL_SIZE: SYMBOL_SIZE, + SYMBOL_STROKE: SYMBOL_SIZE / 20, + + DOT_RE: /-dot/, + OPEN_RE: /-open/, + + DASHES: { + solid: [1], + dot: [1, 1], + dash: [4, 1], + longdash: [8, 1], + dashdot: [4, 1, 1, 1], + longdashdot: [8, 1, 1, 1] + } +}; + +var _$attributes_974 = {}; +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; + +var __extendFlat_974 = _$extend_590.extendFlat; +var __overrideAll_974 = _$edit_types_632.overrideAll; +var __DASHES_974 = _$constants_975.DASHES; + +var __scatterLineAttrs_974 = _$attributes_927.line; +var __scatterMarkerAttrs_974 = _$attributes_927.marker; +var __scatterMarkerLineAttrs_974 = __scatterMarkerAttrs_974.line; + +var __attrs_974 = _$attributes_974 = __overrideAll_974({ + x: _$attributes_927.x, + x0: _$attributes_927.x0, + dx: _$attributes_927.dx, + y: _$attributes_927.y, + y0: _$attributes_927.y0, + dy: _$attributes_927.dy, + + text: __extendFlat_974({}, _$attributes_927.text, { + + }), + mode: { + valType: 'flaglist', + flags: ['lines', 'markers'], + extras: ['none'], + + + }, + line: { + color: __scatterLineAttrs_974.color, + width: __scatterLineAttrs_974.width, + dash: { + valType: 'enumerated', + values: Object.keys(__DASHES_974), + dflt: 'solid', + + + } + }, + marker: __extendFlat_974({}, _$makeColorScaleAttributes_481('marker'), { + symbol: __scatterMarkerAttrs_974.symbol, + size: __scatterMarkerAttrs_974.size, + sizeref: __scatterMarkerAttrs_974.sizeref, + sizemin: __scatterMarkerAttrs_974.sizemin, + sizemode: __scatterMarkerAttrs_974.sizemode, + opacity: __scatterMarkerAttrs_974.opacity, + showscale: __scatterMarkerAttrs_974.showscale, + colorbar: __scatterMarkerAttrs_974.colorbar, + line: __extendFlat_974({}, _$makeColorScaleAttributes_481('marker.line'), { + width: __scatterMarkerLineAttrs_974.width + }) + }), + connectgaps: _$attributes_927.connectgaps, + fill: _$attributes_927.fill, + fillcolor: _$attributes_927.fillcolor, + + hoveron: _$attributes_927.hoveron, + + selected: { + marker: _$attributes_927.selected.marker + }, + unselected: { + marker: _$attributes_927.unselected.marker + }, + + opacity: _$attributes_644.opacity + +}, 'calc', 'nested'); + +__attrs_974.x.editType = __attrs_974.y.editType = __attrs_974.x0.editType = __attrs_974.y0.editType = 'calc+clearAxisTypes'; + 'use strict' -/* removed: var _$clamp_94 = require('clamp') */; +/* removed: var _$clamp_95 = require('clamp') */; -var _$calcSDF_73 = calcSDF +var _$calcSDF_74 = calcSDF var INF = 1e20; @@ -141835,7 +144034,7 @@ function calcSDF(src, options) { var dist = window.Float32Array ? new Float32Array(w * h) : new Array(w * h) for (i = 0, l = w*h; i < l; i++) { - dist[i] = _$clamp_94(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1) + dist[i] = _$clamp_95(1 - ( (gridOuter[i] - gridInner[i]) / radius + cutoff), 0, 1) } return dist @@ -141888,7 +144087,7 @@ function edt1d(f, d, v, z, n) { } -var _$absolutize_43 = absolutize +var _$absolutize_44 = absolutize /** * redefine `path` with absolute coordinates @@ -141957,9 +144156,9 @@ function absolutize(path){ var π = Math.PI -var _120 = __radians_279(120) +var _120 = __radians_337(120) -var _$normalize_279 = __normalize_279 +var _$normalize_337 = __normalize_337 /** * describe `path` in terms of cubic bézier @@ -141969,7 +144168,7 @@ var _$normalize_279 = __normalize_279 * @return {Array} */ -function __normalize_279(path){ +function __normalize_337(path){ // init state var prev var result = [] @@ -141991,7 +144190,7 @@ function __normalize_279(path){ startY = seg[2] break case 'A': - seg = arc(x, y,seg[1],seg[2],__radians_279(seg[3]),seg[4],seg[5],seg[6],seg[7]) + seg = arc(x, y,seg[1],seg[2],__radians_337(seg[3]),seg[4],seg[5],seg[6],seg[7]) // split multi part seg.unshift('C') if (seg.length > 7) { @@ -142078,10 +144277,10 @@ function quadratic(x1, y1, cx, cy, x2, y2){ function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { if (!recursive) { - var xy = __rotate_279(x1, y1, -angle) + var xy = __rotate_337(x1, y1, -angle) x1 = xy.x y1 = xy.y - xy = __rotate_279(x2, y2, -angle) + xy = __rotate_337(x2, y2, -angle) x2 = xy.x y2 = xy.y var x = (x1 - x2) / 2 @@ -142138,37 +144337,37 @@ function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursiv if (recursive) return curve if (res) curve = curve.concat(res) for (var i = 0; i < curve.length;) { - var rot = __rotate_279(curve[i], curve[i+1], angle) + var rot = __rotate_337(curve[i], curve[i+1], angle) curve[i++] = rot.x curve[i++] = rot.y } return curve } -function __rotate_279(x, y, rad){ +function __rotate_337(x, y, rad){ return { x: x * Math.cos(rad) - y * Math.sin(rad), y: x * Math.sin(rad) + y * Math.cos(rad) } } -function __radians_279(degress){ +function __radians_337(degress){ return degress * (π / 180) } -/* removed: var _$absolutize_43 = require('abs-svg-path') */; -/* removed: var _$normalize_279 = require('normalize-svg-path') */; +/* removed: var _$absolutize_44 = require('abs-svg-path') */; +/* removed: var _$normalize_337 = require('normalize-svg-path') */; var methods = { 'M': 'moveTo', 'C': 'bezierCurveTo' } -var _$drawSvgPath_131 = function(context, segments) { +var _$drawSvgPath_134 = function(context, segments) { context.beginPath() // Make path easy to reproduce. - _$normalize_279(_$absolutize_43(segments)).forEach( + _$normalize_337(_$absolutize_44(segments)).forEach( function(segment) { var command = segment[0] var args = segment.slice(1) @@ -142183,7 +144382,7 @@ var _$drawSvgPath_131 = function(context, segments) { 'use strict' -var _$isPath_251 = function isPath(str) { +var _$isPath_309 = function isPath(str) { if (typeof str !== 'string') return false str = str.trim() @@ -142195,14 +144394,14 @@ var _$isPath_251 = function isPath(str) { } -var _$parse_286 = __parse_286 +var _$parse_344 = __parse_344 /** * expected argument lengths * @type {Object} */ -var __length_286 = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} +var __length_344 = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0} /** * segment pattern @@ -142220,7 +144419,7 @@ var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig * @return {Array} */ -function __parse_286(path) { +function __parse_344(path) { var data = [] path.replace(segment, function(_, command, args){ var type = command.toLowerCase() @@ -142234,12 +144433,12 @@ function __parse_286(path) { } while (true) { - if (args.length == __length_286[type]) { + if (args.length == __length_344[type]) { args.unshift(command) return data.push(args) } - if (args.length < __length_286[type]) throw new Error('malformed path data') - data.push([command].concat(args.splice(0, __length_286[type]))) + if (args.length < __length_344[type]) throw new Error('malformed path data') + data.push([command].concat(args.splice(0, __length_344[type]))) } }) return data @@ -142252,10 +144451,10 @@ function parseValues(args) { return numbers ? numbers.map(Number) : [] } -var _$inherits_browser_364 = {}; +var _$inherits_browser_426 = {}; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module - _$inherits_browser_364 = function inherits(ctor, superCtor) { + _$inherits_browser_426 = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { @@ -142268,7 +144467,7 @@ if (typeof Object.create === 'function') { }; } else { // old school shim for old browsers - _$inherits_browser_364 = function inherits(ctor, superCtor) { + _$inherits_browser_426 = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype @@ -142277,13 +144476,13 @@ if (typeof Object.create === 'function') { } } -var _$isBuffer_365 = function isBuffer(arg) { +var _$isBuffer_427 = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -var _$util_366 = {}; +var _$util_428 = {}; (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -142307,7 +144506,7 @@ var _$util_366 = {}; // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; -_$util_366.format = function(f) { +_$util_428.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { @@ -142349,11 +144548,11 @@ _$util_366.format = function(f) { // 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. -_$util_366.deprecate = function(fn, msg) { +_$util_428.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { - return _$util_366.deprecate(fn, msg).apply(this, arguments); + return _$util_428.deprecate(fn, msg).apply(this, arguments); }; } @@ -142382,7 +144581,7 @@ _$util_366.deprecate = function(fn, msg) { var debugs = {}; var debugEnviron; -_$util_366.debuglog = function(set) { +_$util_428.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); @@ -142390,7 +144589,7 @@ _$util_366.debuglog = function(set) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { - var msg = _$util_366.format.apply(_$util_366, arguments); + var msg = _$util_428.format.apply(_$util_428, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { @@ -142423,7 +144622,7 @@ function inspect(obj, opts) { ctx.showHidden = opts; } else if (opts) { // got an "options" object - _$util_366._extend(ctx, opts); + _$util_428._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; @@ -142433,7 +144632,7 @@ function inspect(obj, opts) { if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } -_$util_366.inspect = inspect; +_$util_428.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics @@ -142502,7 +144701,7 @@ function formatValue(ctx, value, recurseTimes) { value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special - value.inspect !== _$util_366.inspect && + value.inspect !== _$util_428.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); @@ -142737,68 +144936,68 @@ function reduceToSingleString(output, base, braces) { function isArray(ar) { return Array.isArray(ar); } -_$util_366.isArray = isArray; +_$util_428.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } -_$util_366.isBoolean = isBoolean; +_$util_428.isBoolean = isBoolean; function isNull(arg) { return arg === null; } -_$util_366.isNull = isNull; +_$util_428.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } -_$util_366.isNullOrUndefined = isNullOrUndefined; +_$util_428.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } -_$util_366.isNumber = isNumber; +_$util_428.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } -_$util_366.isString = isString; +_$util_428.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } -_$util_366.isSymbol = isSymbol; +_$util_428.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } -_$util_366.isUndefined = isUndefined; +_$util_428.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } -_$util_366.isRegExp = isRegExp; +_$util_428.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } -_$util_366.isObject = isObject; +_$util_428.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } -_$util_366.isDate = isDate; +_$util_428.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } -_$util_366.isError = isError; +_$util_428.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } -_$util_366.isFunction = isFunction; +_$util_428.isFunction = isFunction; function isPrimitive(arg) { return arg === null || @@ -142808,9 +145007,9 @@ function isPrimitive(arg) { typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } -_$util_366.isPrimitive = isPrimitive; +_$util_428.isPrimitive = isPrimitive; -_$util_366.isBuffer = _$isBuffer_365; +_$util_428.isBuffer = _$isBuffer_427; function objectToString(o) { return Object.prototype.toString.call(o); @@ -142836,8 +145035,8 @@ function timestamp() { // log is just a thin wrapper to console.log that prepends a timestamp -_$util_366.log = function() { - console.log('%s - %s', timestamp(), _$util_366.format.apply(_$util_366, arguments)); +_$util_428.log = function() { + console.log('%s - %s', timestamp(), _$util_428.format.apply(_$util_428, arguments)); }; @@ -142854,9 +145053,9 @@ _$util_366.log = function() { * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ -_$util_366.inherits = _$inherits_browser_364; +_$util_428.inherits = _$inherits_browser_426; -_$util_366._extend = function(origin, add) { +_$util_428._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; @@ -142872,8 +145071,8 @@ function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } -}).call(this,_$browser_304,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$assert_51 = {}; +}).call(this,_$browser_366,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +var _$assert_52 = {}; (function (global){ 'use strict'; @@ -142943,7 +145142,7 @@ function isBuffer(b) { // 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. -/* removed: var _$util_366 = require('util/'); */; +/* removed: var _$util_428 = require('util/'); */; var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { @@ -142977,7 +145176,7 @@ function isView(arrbuf) { // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. -var assert = _$assert_51 = ok; +var assert = _$assert_52 = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, @@ -142987,7 +145186,7 @@ var assert = _$assert_51 = ok; var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { - if (!_$util_366.isFunction(func)) { + if (!_$util_428.isFunction(func)) { return; } if (functionsHaveNames) { @@ -143034,7 +145233,7 @@ assert.AssertionError = function AssertionError(options) { }; // assert.AssertionError instanceof Error -_$util_366.inherits(assert.AssertionError, Error); +_$util_428.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { @@ -143044,8 +145243,8 @@ function truncate(s, n) { } } function inspect(something) { - if (functionsHaveNames || !_$util_366.isFunction(something)) { - return _$util_366.inspect(something); + if (functionsHaveNames || !_$util_428.isFunction(something)) { + return _$util_428.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; @@ -143134,13 +145333,13 @@ function _deepEqual(actual, expected, strict, memos) { // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. - } else if (_$util_366.isDate(actual) && _$util_366.isDate(expected)) { + } else if (_$util_428.isDate(actual) && _$util_428.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (_$util_366.isRegExp(actual) && _$util_366.isRegExp(expected)) { + } else if (_$util_428.isRegExp(actual) && _$util_428.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && @@ -143199,7 +145398,7 @@ function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same - if (_$util_366.isPrimitive(a) || _$util_366.isPrimitive(b)) + if (_$util_428.isPrimitive(a) || _$util_428.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; @@ -143328,7 +145527,7 @@ function _throws(shouldThrow, block, expected, message) { } var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && _$util_366.isError(actual); + var isUnwantedException = !shouldThrow && _$util_428.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && @@ -143367,10 +145566,10 @@ var objectKeys = Object.keys || function (obj) { }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -var _$cjs_347 = {}; +var _$cjs_409 = {}; "use strict"; -Object.defineProperty(_$cjs_347, "__esModule", { +Object.defineProperty(_$cjs_409, "__esModule", { value: true }); @@ -143546,15 +145745,15 @@ var arcToBezier = function arcToBezier(_ref2) { }); }; -_$cjs_347.default = arcToBezier; -_$cjs_347 = _$cjs_347["default"]; +_$cjs_409.default = arcToBezier; +_$cjs_409 = _$cjs_409["default"]; 'use strict' -var _$normalize_349 = __normalize_349 +var _$normalize_411 = __normalize_411 -/* removed: var _$cjs_347 = require('svg-arc-to-cubic-bezier') */; +/* removed: var _$cjs_409 = require('svg-arc-to-cubic-bezier') */; -function __normalize_349(path){ +function __normalize_411(path){ // init state var prev var result = [] @@ -143577,7 +145776,7 @@ function __normalize_349(path){ startY = seg[2] break case 'A': - var curves = _$cjs_347({ + var curves = _$cjs_409({ px: x, py: y, cx: seg[6], @@ -143617,24 +145816,24 @@ function __normalize_349(path){ quadX = x quadY = y } - seg = __quadratic_349(x, y, quadX, quadY, seg[1], seg[2]) + seg = __quadratic_411(x, y, quadX, quadY, seg[1], seg[2]) break case 'Q': quadX = seg[1] quadY = seg[2] - seg = __quadratic_349(x, y, seg[1], seg[2], seg[3], seg[4]) + seg = __quadratic_411(x, y, seg[1], seg[2], seg[3], seg[4]) break case 'L': - seg = __line_349(x, y, seg[1], seg[2]) + seg = __line_411(x, y, seg[1], seg[2]) break case 'H': - seg = __line_349(x, y, seg[1], y) + seg = __line_411(x, y, seg[1], y) break case 'V': - seg = __line_349(x, y, x, seg[1]) + seg = __line_411(x, y, x, seg[1]) break case 'Z': - seg = __line_349(x, y, startX, startY) + seg = __line_411(x, y, startX, startY) break } @@ -143655,11 +145854,11 @@ function __normalize_349(path){ return result } -function __line_349(x1, y1, x2, y2){ +function __line_411(x1, y1, x2, y2){ return ['C', x1, y1, x2, y2, x2, y2] } -function __quadratic_349(x1, y1, cx, cy, x2, y2){ +function __quadratic_411(x1, y1, cx, cy, x2, y2){ return [ 'C', x1/3 + (2/3) * cx, @@ -143673,13 +145872,13 @@ function __quadratic_349(x1, y1, cx, cy, x2, y2){ 'use strict' -/* removed: var _$parse_286 = require('parse-svg-path') */; -/* removed: var _$absolutize_43 = require('abs-svg-path') */; -/* removed: var _$normalize_349 = require('normalize-svg-path') */; -/* removed: var _$isPath_251 = require('is-svg-path') */; -/* removed: var _$assert_51 = require('assert') */; +/* removed: var _$parse_344 = require('parse-svg-path') */; +/* removed: var _$absolutize_44 = require('abs-svg-path') */; +/* removed: var _$normalize_411 = require('normalize-svg-path') */; +/* removed: var _$isPath_309 = require('is-svg-path') */; +/* removed: var _$assert_52 = require('assert') */; -var _$pathBounds_348 = pathBounds +var _$pathBounds_410 = pathBounds function pathBounds(path) { @@ -143688,14 +145887,14 @@ function pathBounds(path) { // svg path string if (typeof path === 'string') { - _$assert_51(_$isPath_251(path), 'String is not an SVG path.') - path = _$parse_286(path) + _$assert_52(_$isPath_309(path), 'String is not an SVG path.') + path = _$parse_344(path) } - _$assert_51(Array.isArray(path), 'Argument should be a string or an array of path segments.') + _$assert_52(Array.isArray(path), 'Argument should be a string or an array of path segments.') - path = _$absolutize_43(path) - path = _$normalize_349(path) + path = _$absolutize_44(path) + path = _$normalize_411(path) if (!path.length) return [0, 0, 0, 0] @@ -143715,24 +145914,24 @@ function pathBounds(path) { return bounds } -var _$pathSdf_350 = {}; +var _$pathSdf_412 = {}; (function (global){ 'use strict' -/* removed: var _$pathBounds_348 = require('svg-path-bounds') */; -/* removed: var _$parse_286 = require('parse-svg-path') */; -/* removed: var _$drawSvgPath_131 = require('draw-svg-path') */; -/* removed: var _$isPath_251 = require('is-svg-path') */; -/* removed: var _$calcSDF_73 = require('bitmap-sdf') */; +/* removed: var _$pathBounds_410 = require('svg-path-bounds') */; +/* removed: var _$parse_344 = require('parse-svg-path') */; +/* removed: var _$drawSvgPath_134 = require('draw-svg-path') */; +/* removed: var _$isPath_309 = require('is-svg-path') */; +/* removed: var _$calcSDF_74 = require('bitmap-sdf') */; var canvas = document.createElement('canvas') var ctx = canvas.getContext('2d') -_$pathSdf_350 = pathSdf +_$pathSdf_412 = pathSdf function pathSdf (path, options) { - if (!_$isPath_251(path)) throw Error('Argument should be valid svg path string') + if (!_$isPath_309(path)) throw Error('Argument should be valid svg path string') if (!options) options = {} @@ -143749,7 +145948,7 @@ function pathSdf (path, options) { var stroke = options.stroke || 0 - var viewbox = options.viewbox || options.viewBox || _$pathBounds_348(path) + var viewbox = options.viewbox || options.viewBox || _$pathBounds_410(path) var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])] var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2 @@ -143782,15 +145981,15 @@ function pathSdf (path, options) { } //fallback to bezier-curves else { - var segments = _$parse_286(path) - _$drawSvgPath_131(ctx, segments) + var segments = _$parse_344(path) + _$drawSvgPath_134(ctx, segments) ctx.fill() stroke && ctx.stroke() } ctx.setTransform(1, 0, 0, 1, 0, 0); - var data = _$calcSDF_73(ctx, { + var data = _$calcSDF_74(ctx, { cutoff: options.cutoff != null ? options.cutoff : .5, radius: options.radius != null ? options.radius : size * .5 }) @@ -143807,824 +146006,270 @@ function pathSdf (path, options) { * LICENSE file in the root directory of this source tree. */ - 'use strict'; -var _$gl2d_dashes_513 = { - solid: [1], - dot: [1, 1], - dash: [4, 1], - longdash: [8, 1], - dashdot: [4, 1, 1, 1], - longdashdot: [8, 1, 1, 1] -}; +/* removed: var _$pathSdf_412 = require('svg-path-sdf'); */; +/* removed: var _$normalize_100 = require('color-normalize'); */; -var _$attributes_909 = {}; -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$gl2d_dashes_513 = require('../../constants/gl2d_dashes'); */; -var __extendFlat_909 = _$extend_528.extendFlat; -var __overrideAll_909 = _$edit_types_569.overrideAll; +/* removed: var _$formatColor_597 = require('../../lib/gl_format_color'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../scatter/make_bubble_size_func'); */; -var __scatterLineAttrs_909 = _$attributes_862.line, - __scatterMarkerAttrs_909 = _$attributes_862.marker, - __scatterMarkerLineAttrs_909 = __scatterMarkerAttrs_909.line; +/* removed: var _$constants_975 = require('./constants'); */; +var __DESELECTDIM_976 = _$interactions_577.DESELECTDIM; -var __attrs_909 = _$attributes_909 = __overrideAll_909({ - x: _$attributes_862.x, - x0: _$attributes_862.x0, - dx: _$attributes_862.dx, - y: _$attributes_862.y, - y0: _$attributes_862.y0, - dy: _$attributes_862.dy, - - text: __extendFlat_909({}, _$attributes_862.text, { - - }), - mode: { - valType: 'flaglist', - flags: ['lines', 'markers'], - extras: ['none'], - - - }, - line: { - color: __scatterLineAttrs_909.color, - width: __scatterLineAttrs_909.width, - dash: { - valType: 'enumerated', - values: Object.keys(_$gl2d_dashes_513), - dflt: 'solid', - - - } - }, - marker: __extendFlat_909({}, _$makeColorScaleAttributes_419('marker'), { - symbol: __scatterMarkerAttrs_909.symbol, - size: __scatterMarkerAttrs_909.size, - sizeref: __scatterMarkerAttrs_909.sizeref, - sizemin: __scatterMarkerAttrs_909.sizemin, - sizemode: __scatterMarkerAttrs_909.sizemode, - opacity: __scatterMarkerAttrs_909.opacity, - showscale: __scatterMarkerAttrs_909.showscale, - colorbar: __scatterMarkerAttrs_909.colorbar, - line: __extendFlat_909({}, _$makeColorScaleAttributes_419('marker.line'), { - width: __scatterMarkerLineAttrs_909.width - }) - }), - connectgaps: _$attributes_862.connectgaps, - fill: _$attributes_862.fill, - fillcolor: _$attributes_862.fillcolor, - - hoveron: _$attributes_862.hoveron, - - selected: { - marker: _$attributes_862.selected.marker - }, - unselected: { - marker: _$attributes_862.unselected.marker - }, - - opacity: _$attributes_581.opacity - -}, 'calc', 'nested'); - -__attrs_909.x.editType = __attrs_909.y.editType = __attrs_909.x0.editType = __attrs_909.y0.editType = 'calc+clearAxisTypes'; - -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$registry_668 = require('../../registry'); */; - -/* removed: var _$attributes_909 = require('./attributes'); */; -/* removed: var _$constants_868 = require('../scatter/constants'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$handleXYDefaults_886 = require('../scatter/xy_defaults'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; - -var _$supplyDefaults_910 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_909, attr, dflt); - } - - var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false; - var isBubble = _$subtypes_884.isBubble(traceIn); - - var len = _$handleXYDefaults_886(traceIn, traceOut, layout, coerce); - if(!len) { - traceOut.visible = false; - return; - } - - coerce('text'); - coerce('mode', len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'); - - if(_$subtypes_884.hasLines(traceOut)) { - coerce('connectgaps'); - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - } +function convertStyle(gd, trace) { + var i; - var dfltHoverOn = []; + var opts = { + marker: undefined, + line: undefined, + fill: undefined, + errorX: undefined, + errorY: undefined, + selected: undefined, + unselected: undefined + }; - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce); - coerce('marker.line.width', isOpen || isBubble ? 1 : 0); - dfltHoverOn.push('points'); - } + if(trace.visible !== true) return opts; - coerce('fill'); - if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - } + if(_$subtypes_949.hasMarkers(trace)) { + opts.marker = convertMarkerStyle(trace); + opts.selected = convertMarkerSelection(trace, trace.selected); + opts.unselected = convertMarkerSelection(trace, trace.unselected); - if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { - dfltHoverOn.push('fills'); + if(!trace.unselected && Array.isArray(trace.marker.opacity)) { + var mo = trace.marker.opacity; + opts.unselected.opacity = new Array(mo.length); + for(i = 0; i < mo.length; i++) { + opts.unselected.opacity[i] = __DESELECTDIM_976 * mo[i]; + } + } } - coerce('hoveron', dfltHoverOn.join('+') || 'points'); - - var errorBarsSupplyDefaults = _$registry_668.getComponentMethod('errorbars', 'supplyDefaults'); - errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); - errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); - - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); -}; - -var _$scattergl_911 = {}; -(function (global){ -/** -* Copyright 2012-2018, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -/* removed: var _$regl_315 = require('regl'); */; -/* removed: var _$Scatter_313 = require('regl-scatter2d'); */; -/* removed: var _$createLine_312 = require('regl-line2d'); */; -/* removed: var _$Error2D_311 = require('regl-error2d'); */; -/* removed: var _$KDTree_252 = require('kdgrass'); */; -/* removed: var _$normalize_99 = require('color-normalize'); */; -/* removed: var _$pathSdf_350 = require('svg-path-sdf'); */; -/* removed: var _$newArray_50 = require('array-range'); */; - -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axis_ids_587 = require('../../plots/cartesian/axis_ids'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$formatColor_535 = require('../../lib/gl_format_color'); */; - -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -var calcMarkerSize = _$calc_863.calcMarkerSize; -var calcAxisExpansion = _$calc_863.calcAxisExpansion; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$linkTraces_878 = require('../scatter/link_traces'); */; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; - -/* removed: var _$gl2d_dashes_513 = require('../../constants/gl2d_dashes'); */; -var BADNUM = _$numerical_517.BADNUM; -var SYMBOL_SDF_SIZE = 200; -var SYMBOL_SIZE = 20; -var SYMBOL_STROKE = SYMBOL_SIZE / 20; -var SYMBOL_SDF = {}; -var SYMBOL_SVG_CIRCLE = _$drawing_436.symbolFuncs[0](SYMBOL_SIZE * 0.05); -var TOO_MANY_POINTS = 1e5; -var DOT_RE = /-dot/; -var OPEN_RE = /-open/; - -function calc(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = _$axis_ids_587.getFromId(gd, trace.xaxis); - var ya = _$axis_ids_587.getFromId(gd, trace.yaxis); - var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; - var count = trace._length; - var count2 = count * 2; - var stash = {}; - var i, xx, yy; - - var x = xa.makeCalcdata(trace, 'x'); - var y = ya.makeCalcdata(trace, 'y'); - - // we need hi-precision for scatter2d, - // regl-scatter2d uses NaNs for bad/missing values - var positions = new Array(count2); - for(i = 0; i < count; i++) { - xx = x[i]; - yy = y[i]; - positions[i * 2] = xx === BADNUM ? NaN : xx; - positions[i * 2 + 1] = yy === BADNUM ? NaN : yy; - } + if(_$subtypes_949.hasLines(trace)) { + opts.line = { + overlay: true, + thickness: trace.line.width, + color: trace.line.color, + opacity: trace.opacity + }; - if(xa.type === 'log') { - for(i = 0; i < count2; i += 2) { - positions[i] = xa.c2l(positions[i]); - } - } - if(ya.type === 'log') { - for(i = 1; i < count2; i += 2) { - positions[i] = ya.c2l(positions[i]); + var dashes = (_$constants_975.DASHES[trace.line.dash] || [1]).slice(); + for(i = 0; i < dashes.length; ++i) { + dashes[i] *= trace.line.width; } + opts.line.dashes = dashes; } - // we don't build a tree for log axes since it takes long to convert log2px - // and it is also - if(xa.type !== 'log' && ya.type !== 'log') { - // FIXME: delegate this to webworker - stash.tree = _$KDTree_252(positions, 512); - } else { - var ids = stash.ids = new Array(count); - for(i = 0; i < count; i++) { - ids[i] = i; - } + if(trace.error_x && trace.error_x.visible) { + opts.errorX = convertErrorBarStyle(trace, trace.error_x); } - // create scene options and scene - _$calcMarkerColorscale_867(trace); - var options = sceneOptions(gd, subplot, trace, positions); - var markerOptions = options.marker; - var scene = sceneUpdate(gd, subplot); - var ppad; - - // Re-use SVG scatter axis expansion routine except - // for graph with very large number of points where it - // performs poorly. - // In big data case, fake Axes.expand outputs with data bounds, - // and an average size for array marker.size inputs. - if(count < TOO_MANY_POINTS) { - ppad = calcMarkerSize(trace, count); - } else if(markerOptions) { - ppad = 2 * (markerOptions.sizeAvg || Math.max(markerOptions.size, 3)); + if(trace.error_y && trace.error_y.visible) { + opts.errorY = convertErrorBarStyle(trace, trace.error_y); } - calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); - // set flags to create scene renderers - if(options.fill && !scene.fill2d) scene.fill2d = true; - if(options.marker && !scene.scatter2d) scene.scatter2d = true; - if(options.line && !scene.line2d) scene.line2d = true; - if((options.errorX || options.errorY) && !scene.error2d) scene.error2d = true; - - // save scene options batch - scene.lineOptions.push(options.line); - scene.errorXOptions.push(options.errorX); - scene.errorYOptions.push(options.errorY); - scene.fillOptions.push(options.fill); - scene.markerOptions.push(options.marker); - scene.selectedOptions.push(options.selected); - scene.unselectedOptions.push(options.unselected); - scene.count++; - - // stash scene ref - stash.scene = scene; - stash.index = scene.count - 1; - stash.x = x; - stash.y = y; - stash.positions = positions; - stash.count = count; + if(!!trace.fill && trace.fill !== 'none') { + opts.fill = { + closed: true, + fill: trace.fillcolor, + thickness: 0 + }; + } - gd.firstscatter = false; - return [{x: false, y: false, t: stash, trace: trace}]; + return opts; } -// create scene options -function sceneOptions(gd, subplot, trace, positions) { - var fullLayout = gd._fullLayout; - var count = positions.length / 2; - var markerOpts = trace.marker; +function convertMarkerStyle(trace) { + var count = trace._length || trace._commonLength; + var optsIn = trace.marker; + var optsOut = {}; var i; - var hasLines, hasErrorX, hasErrorY, hasMarkers, hasFill; - - if(trace.visible !== true) { - hasLines = false; - hasErrorX = false; - hasErrorY = false; - hasMarkers = false; - hasFill = false; - } else { - hasLines = _$subtypes_884.hasLines(trace) && positions.length > 1; - hasErrorX = trace.error_x && trace.error_x.visible === true; - hasErrorY = trace.error_y && trace.error_y.visible === true; - hasMarkers = _$subtypes_884.hasMarkers(trace); - hasFill = !!trace.fill && trace.fill !== 'none'; - } - - var lineOptions, markerOptions, fillOptions; - var errorXOptions, errorYOptions; - var selectedOptions, unselectedOptions; - var linePositions; + var multiSymbol = Array.isArray(optsIn.symbol); + var multiColor = _$lib_601.isArrayOrTypedArray(optsIn.color); + var multiLineColor = _$lib_601.isArrayOrTypedArray(optsIn.line.color); + var multiOpacity = _$lib_601.isArrayOrTypedArray(optsIn.opacity); + var multiSize = _$lib_601.isArrayOrTypedArray(optsIn.size); + var multiLineWidth = _$lib_601.isArrayOrTypedArray(optsIn.line.width); - if(hasErrorX || hasErrorY) { - var calcFromTrace = _$registry_668.getComponentMethod('errorbars', 'calcFromTrace'); - var errorVals = calcFromTrace(trace, fullLayout); - - if(hasErrorX) { - errorXOptions = makeErrorOptions('x', trace.error_x, errorVals); - } - if(hasErrorY) { - errorYOptions = makeErrorOptions('y', trace.error_y, errorVals); - } - } + var isOpen; + if(!multiSymbol) isOpen = _$constants_975.OPEN_RE.test(optsIn.symbol); - if(hasLines) { - lineOptions = {}; - lineOptions.thickness = trace.line.width; - lineOptions.color = trace.line.color; - lineOptions.opacity = trace.opacity; - lineOptions.overlay = true; + // prepare colors + if(multiSymbol || multiColor || multiLineColor || multiOpacity) { + optsOut.colors = new Array(count); + optsOut.borderColors = new Array(count); - var dashes = (_$gl2d_dashes_513[trace.line.dash] || [1]).slice(); - for(i = 0; i < dashes.length; ++i) dashes[i] *= lineOptions.thickness; - lineOptions.dashes = dashes; + var colors = _$formatColor_597(optsIn, optsIn.opacity, count); + var borderColors = _$formatColor_597(optsIn.line, optsIn.opacity, count); - if(trace.line.shape === 'hv') { - linePositions = []; - for(i = 0; i < Math.floor(positions.length / 2) - 1; i++) { - if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - } - else { - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 1]); - linePositions.push(positions[i * 2 + 2]); - linePositions.push(positions[i * 2 + 1]); - } - } - linePositions.push(positions[positions.length - 2]); - linePositions.push(positions[positions.length - 1]); - } - else if(trace.line.shape === 'vh') { - linePositions = []; - for(i = 0; i < Math.floor(positions.length / 2) - 1; i++) { - if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - linePositions.push(NaN); - } - else { - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 1]); - linePositions.push(positions[i * 2]); - linePositions.push(positions[i * 2 + 3]); - } + if(!Array.isArray(borderColors[0])) { + var borderColor = borderColors; + borderColors = Array(count); + for(i = 0; i < count; i++) { + borderColors[i] = borderColor; } - linePositions.push(positions[positions.length - 2]); - linePositions.push(positions[positions.length - 1]); - } - else { - linePositions = positions; } - - // If we have data with gaps, we ought to use rect joins - // FIXME: get rid of this - var hasNaN = false; - for(i = 0; i < linePositions.length; i++) { - if(isNaN(linePositions[i])) { - hasNaN = true; - break; + if(!Array.isArray(colors[0])) { + var color = colors; + colors = Array(count); + for(i = 0; i < count; i++) { + colors[i] = color; } } - lineOptions.join = (hasNaN || linePositions.length > TOO_MANY_POINTS) ? 'rect' : - hasMarkers ? 'rect' : 'round'; + optsOut.colors = colors; + optsOut.borderColors = borderColors; - // fill gaps - if(hasNaN && trace.connectgaps) { - var lastX = linePositions[0], lastY = linePositions[1]; - for(i = 0; i < linePositions.length; i += 2) { - if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { - linePositions[i] = lastX; - linePositions[i + 1] = lastY; - } - else { - lastX = linePositions[i]; - lastY = linePositions[i + 1]; - } + for(i = 0; i < count; i++) { + if(multiSymbol) { + var symbol = optsIn.symbol[i]; + isOpen = _$constants_975.OPEN_RE.test(symbol); + } + if(isOpen) { + borderColors[i] = colors[i].slice(); + colors[i] = colors[i].slice(); + colors[i][3] = 0; } } - lineOptions.positions = linePositions; - } - - if(hasFill) { - fillOptions = {}; - fillOptions.fill = trace.fillcolor; - fillOptions.thickness = 0; - fillOptions.closed = true; - } - - if(hasMarkers) { - markerOptions = makeMarkerOptions(markerOpts); - selectedOptions = makeSelectedOptions(trace.selected, markerOpts); - unselectedOptions = makeSelectedOptions(trace.unselected, markerOpts); - markerOptions.positions = positions; - } - - function makeErrorOptions(axLetter, errorOpts, vals) { - var options = {}; - options.positions = positions; - - var ax = _$axis_ids_587.getFromId(gd, trace[axLetter + 'axis']); - var errors = options.errors = new Float64Array(4 * count); - var pOffset = {x: 0, y: 1}[axLetter]; - var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter]; - - for(var i = 0, p = 0; i < count; i++, p += 4) { - errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0; - errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0; - errors[p + eOffset[2]] = 0; - errors[p + eOffset[3]] = 0; - } - - if(errorOpts.copy_ystyle) { - errorOpts = trace.error_y; + optsOut.opacity = trace.opacity; + } else { + if(isOpen) { + optsOut.color = _$normalize_100(optsIn.color, 'uint8'); + optsOut.color[3] = 0; + optsOut.borderColor = _$normalize_100(optsIn.color, 'uint8'); + } else { + optsOut.color = _$normalize_100(optsIn.color, 'uint8'); + optsOut.borderColor = _$normalize_100(optsIn.line.color, 'uint8'); } - options.capSize = errorOpts.width * 2; - options.lineWidth = errorOpts.thickness; - options.color = errorOpts.color; - - return options; + optsOut.opacity = trace.opacity * optsIn.opacity; } - function makeSelectedOptions(selected, markerOpts) { - var options = {}; - - if(!selected) return options; - - if(selected.marker && selected.marker.symbol) { - options = makeMarkerOptions(_$lib_539.extendFlat({}, markerOpts, selected.marker)); - } - - // shortcut simple selection logic - else { - options = {}; - if(selected.marker.size) options.sizes = selected.marker.size; - if(selected.marker.color) options.colors = selected.marker.color; - if(selected.marker.opacity !== undefined) options.opacity = selected.marker.opacity; + // prepare symbols + if(multiSymbol) { + optsOut.markers = new Array(count); + for(i = 0; i < count; i++) { + optsOut.markers[i] = getSymbolSdf(optsIn.symbol[i]); } - - return options; + } else { + optsOut.marker = getSymbolSdf(optsIn.symbol); } - function makeMarkerOptions(markerOpts) { - var markerOptions = {}; - var i; - - var multiSymbol = Array.isArray(markerOpts.symbol); - var multiColor = _$lib_539.isArrayOrTypedArray(markerOpts.color); - var multiLineColor = _$lib_539.isArrayOrTypedArray(markerOpts.line.color); - var multiOpacity = _$lib_539.isArrayOrTypedArray(markerOpts.opacity); - var multiSize = _$lib_539.isArrayOrTypedArray(markerOpts.size); - var multiLineWidth = _$lib_539.isArrayOrTypedArray(markerOpts.line.width); - - var isOpen; - if(!multiSymbol) isOpen = OPEN_RE.test(markerOpts.symbol); - - // prepare colors - if(multiSymbol || multiColor || multiLineColor || multiOpacity) { - markerOptions.colors = new Array(count); - markerOptions.borderColors = new Array(count); - var colors = _$formatColor_535(markerOpts, markerOpts.opacity, count); - var borderColors = _$formatColor_535(markerOpts.line, markerOpts.opacity, count); - - if(!Array.isArray(borderColors[0])) { - var borderColor = borderColors; - borderColors = Array(count); - for(i = 0; i < count; i++) { - borderColors[i] = borderColor; - } - } - if(!Array.isArray(colors[0])) { - var color = colors; - colors = Array(count); - for(i = 0; i < count; i++) { - colors[i] = color; - } - } + // prepare sizes + var markerSizeFunc = _$makeBubbleSizeFn_944(trace); + var s; - markerOptions.colors = colors; - markerOptions.borderColors = borderColors; + if(multiSize || multiLineWidth) { + var sizes = optsOut.sizes = new Array(count); + var borderSizes = optsOut.borderSizes = new Array(count); + var sizeTotal = 0; + var sizeAvg; + if(multiSize) { for(i = 0; i < count; i++) { - if(multiSymbol) { - var symbol = markerOpts.symbol[i]; - isOpen = OPEN_RE.test(symbol); - } - if(isOpen) { - borderColors[i] = colors[i].slice(); - colors[i] = colors[i].slice(); - colors[i][3] = 0; - } + sizes[i] = markerSizeFunc(optsIn.size[i]); + sizeTotal += sizes[i]; } - - markerOptions.opacity = trace.opacity; - } - else { - if(isOpen) { - markerOptions.color = _$normalize_99(markerOpts.color, 'uint8'); - markerOptions.color[3] = 0; - markerOptions.borderColor = _$normalize_99(markerOpts.color, 'uint8'); - } else { - markerOptions.color = _$normalize_99(markerOpts.color, 'uint8'); - markerOptions.borderColor = _$normalize_99(markerOpts.line.color, 'uint8'); + sizeAvg = sizeTotal / count; + } else { + s = markerSizeFunc(optsIn.size); + for(i = 0; i < count; i++) { + sizes[i] = s; } - - markerOptions.opacity = trace.opacity * markerOpts.opacity; } - // prepare symbols - if(multiSymbol) { - markerOptions.markers = new Array(count); + // See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798 + if(multiLineWidth) { for(i = 0; i < count; i++) { - markerOptions.markers[i] = getSymbolSdf(markerOpts.symbol[i]); + borderSizes[i] = markerSizeFunc(optsIn.line.width[i]); } } else { - markerOptions.marker = getSymbolSdf(markerOpts.symbol); - } - - // prepare sizes - var markerSizeFunc = _$makeBubbleSizeFn_879(trace); - var s; - - if(multiSize || multiLineWidth) { - var sizes = markerOptions.sizes = new Array(count); - var borderSizes = markerOptions.borderSizes = new Array(count); - var sizeTotal = 0; - var sizeAvg; - - if(multiSize) { - for(i = 0; i < count; i++) { - sizes[i] = markerSizeFunc(markerOpts.size[i]); - sizeTotal += sizes[i]; - } - sizeAvg = sizeTotal / count; - } else { - s = markerSizeFunc(markerOpts.size); - for(i = 0; i < count; i++) { - sizes[i] = s; - } - } - - // See https://github.com/plotly/plotly.js/pull/1781#discussion_r121820798 - if(multiLineWidth) { - for(i = 0; i < count; i++) { - borderSizes[i] = markerSizeFunc(markerOpts.line.width[i]); - } - } else { - s = markerSizeFunc(markerOpts.line.width); - for(i = 0; i < count; i++) { - borderSizes[i] = s; - } + s = markerSizeFunc(optsIn.line.width); + for(i = 0; i < count; i++) { + borderSizes[i] = s; } - - markerOptions.sizeAvg = sizeAvg; - } else { - markerOptions.size = markerSizeFunc(markerOpts && markerOpts.size || 10); - markerOptions.borderSizes = markerSizeFunc(markerOpts.line.width); } - return markerOptions; + optsOut.sizeAvg = sizeAvg; + } else { + optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10); + optsOut.borderSizes = markerSizeFunc(optsIn.line.width); } - return { - line: lineOptions, - marker: markerOptions, - errorX: errorXOptions, - errorY: errorYOptions, - fill: fillOptions, - selected: selectedOptions, - unselected: unselectedOptions - }; + return optsOut; } -// make sure scene exists on subplot, return it -function sceneUpdate(gd, subplot) { - var scene = subplot._scene; - var fullLayout = gd._fullLayout; - - var reset = { - // 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: [], - selectedOptions: [], - unselectedOptions: [], - errorXOptions: [], - errorYOptions: [] - }; - - var first = { - selectBatch: null, - unselectBatch: null, - // regl- component stubs, initialized in dirty plot call - fill2d: false, - scatter2d: false, - error2d: false, - line2d: false, - select2d: null - }; - - if(!subplot._scene) { - scene = subplot._scene = _$lib_539.extendFlat({}, reset, first); - - // apply new option to all regl components (used on drag) - scene.update = function update(opt) { - var opts = new Array(scene.count); - for(var i = 0; i < scene.count; i++) { - opts[i] = opt; - } - - 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); - - scene.draw(); - }; - - // draw traces in proper order - scene.draw = function draw() { - var i; - for(i = 0; i < scene.count; i++) { - if(scene.fill2d && scene.fillOptions[i]) { - // must do all fills first - scene.fill2d.draw(i); - } - } - for(i = 0; i < scene.count; i++) { - if(scene.line2d && scene.lineOptions[i]) { - scene.line2d.draw(i); - } - if(scene.error2d && scene.errorXOptions[i]) { - scene.error2d.draw(i); - } - if(scene.error2d && scene.errorYOptions[i]) { - scene.error2d.draw(i + scene.count); - } - if(scene.scatter2d && scene.markerOptions[i] && (!scene.selectBatch || !scene.selectBatch[i])) { - // traces in no-selection mode - scene.scatter2d.draw(i); - } - } - - // draw traces in selection mode - if(scene.scatter2d && scene.select2d && scene.selectBatch) { - scene.select2d.draw(scene.selectBatch); - scene.scatter2d.draw(scene.unselectBatch); - } - - scene.dirty = false; - }; - - // make sure canvas is clear - scene.clear = function clear() { - var vpSize = fullLayout._size; - var width = fullLayout.width; - var height = fullLayout.height; - var xaxis = subplot.xaxis; - var yaxis = subplot.yaxis; - var vp, gl, regl; - - // multisubplot case - if(xaxis && xaxis.domain && yaxis && yaxis.domain) { - vp = [ - vpSize.l + xaxis.domain[0] * vpSize.w, - vpSize.b + yaxis.domain[0] * vpSize.h, - (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, - (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h - ]; - } - else { - vp = [ - vpSize.l, - vpSize.b, - (width - vpSize.r), - (height - vpSize.t) - ]; - } - - if(scene.select2d) { - regl = scene.select2d.regl; - gl = regl._gl; - gl.enable(gl.SCISSOR_TEST); - gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - - if(scene.scatter2d) { - regl = scene.scatter2d.regl; - gl = regl._gl; - gl.enable(gl.SCISSOR_TEST); - gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); - gl.clearColor(0, 0, 0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - }; +function convertMarkerSelection(trace, target) { + var optsIn = trace.marker; + var optsOut = {}; - // remove selection - scene.clearSelect = function clearSelect() { - if(!scene.selectBatch) return; - scene.selectBatch = null; - scene.unselectBatch = null; - scene.scatter2d.update(scene.markerOptions); - scene.clear(); - scene.draw(); - }; + if(!target) return optsOut; - // remove scene resources - scene.destroy = function destroy() { - if(scene.fill2d) scene.fill2d.destroy(); - if(scene.scatter2d) scene.scatter2d.destroy(); - if(scene.error2d) scene.error2d.destroy(); - if(scene.line2d) scene.line2d.destroy(); - if(scene.select2d) scene.select2d.destroy(); + if(target.marker && target.marker.symbol) { + optsOut = convertMarkerStyle(_$lib_601.extendFlat({}, optsIn, target.marker)); + } else if(target.marker) { + if(target.marker.size) optsOut.sizes = target.marker.size; + if(target.marker.color) optsOut.colors = target.marker.color; + if(target.marker.opacity !== undefined) optsOut.opacity = target.marker.opacity; + } - scene.lineOptions = null; - scene.fillOptions = null; - scene.markerOptions = null; - scene.selectedOptions = null; - scene.unselectedOptions = null; - scene.errorXOptions = null; - scene.errorYOptions = null; - scene.selectBatch = null; - scene.unselectBatch = null; + return optsOut; +} - // 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; - }; - } +function convertErrorBarStyle(trace, target) { + var optsOut = { + capSize: target.width * 2, + lineWidth: target.thickness, + color: target.color + }; - // In case if we have scene from the last calc - reset data - if(!scene.dirty) { - _$lib_539.extendFlat(scene, reset); + if(target.copy_ystyle) { + optsOut = trace.error_y; } - return scene; + return optsOut; } +var SYMBOL_SDF_SIZE = _$constants_975.SYMBOL_SDF_SIZE; +var __SYMBOL_SIZE_976 = _$constants_975.SYMBOL_SIZE; +var SYMBOL_STROKE = _$constants_975.SYMBOL_STROKE; +var SYMBOL_SDF = {}; +var SYMBOL_SVG_CIRCLE = _$drawing_498.symbolFuncs[0](__SYMBOL_SIZE_976 * 0.05); + function getSymbolSdf(symbol) { if(symbol === 'circle') return null; var symbolPath, symbolSdf; - var symbolNumber = _$drawing_436.symbolNumber(symbol); - var symbolFunc = _$drawing_436.symbolFuncs[symbolNumber % 100]; - var symbolNoDot = !!_$drawing_436.symbolNoDot[symbolNumber % 100]; - var symbolNoFill = !!_$drawing_436.symbolNoFill[symbolNumber % 100]; + var symbolNumber = _$drawing_498.symbolNumber(symbol); + var symbolFunc = _$drawing_498.symbolFuncs[symbolNumber % 100]; + var symbolNoDot = !!_$drawing_498.symbolNoDot[symbolNumber % 100]; + var symbolNoFill = !!_$drawing_498.symbolNoFill[symbolNumber % 100]; - var isDot = DOT_RE.test(symbol); + var isDot = _$constants_975.DOT_RE.test(symbol); // get symbol sdf from cache or generate it if(SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol]; if(isDot && !symbolNoDot) { - symbolPath = symbolFunc(SYMBOL_SIZE * 1.1) + SYMBOL_SVG_CIRCLE; + symbolPath = symbolFunc(__SYMBOL_SIZE_976 * 1.1) + SYMBOL_SVG_CIRCLE; } else { - symbolPath = symbolFunc(SYMBOL_SIZE); + symbolPath = symbolFunc(__SYMBOL_SIZE_976); } - symbolSdf = _$pathSdf_350(symbolPath, { + symbolSdf = _$pathSdf_412(symbolPath, { w: SYMBOL_SDF_SIZE, h: SYMBOL_SDF_SIZE, - viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE], + viewBox: [-__SYMBOL_SIZE_976, -__SYMBOL_SIZE_976, __SYMBOL_SIZE_976, __SYMBOL_SIZE_976], stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE }); SYMBOL_SDF[symbol] = symbolSdf; @@ -144632,11 +146277,524 @@ function getSymbolSdf(symbol) { return symbolSdf || null; } -function plot(gd, subplot, cdata) { +function convertLinePositions(gd, trace, positions) { + var count = positions.length / 2; + var linePositions; + var i; + + if(_$subtypes_949.hasLines(trace) && count) { + if(trace.line.shape === 'hv') { + linePositions = []; + for(i = 0; i < count - 1; i++) { + if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + } + else { + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 1]); + linePositions.push(positions[i * 2 + 2]); + linePositions.push(positions[i * 2 + 1]); + } + } + linePositions.push(positions[positions.length - 2]); + linePositions.push(positions[positions.length - 1]); + } else if(trace.line.shape === 'vh') { + linePositions = []; + for(i = 0; i < count - 1; i++) { + if(isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + linePositions.push(NaN); + } + else { + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 1]); + linePositions.push(positions[i * 2]); + linePositions.push(positions[i * 2 + 3]); + } + } + linePositions.push(positions[positions.length - 2]); + linePositions.push(positions[positions.length - 1]); + } else { + linePositions = positions; + } + } + + // If we have data with gaps, we ought to use rect joins + // FIXME: get rid of this + var hasNaN = false; + for(i = 0; i < linePositions.length; i++) { + if(isNaN(linePositions[i])) { + hasNaN = true; + break; + } + } + + var join = (hasNaN || linePositions.length > _$constants_975.TOO_MANY_POINTS) ? 'rect' : + _$subtypes_949.hasMarkers(trace) ? 'rect' : 'round'; + + // fill gaps + if(hasNaN && trace.connectgaps) { + var lastX = linePositions[0]; + var lastY = linePositions[1]; + + for(i = 0; i < linePositions.length; i += 2) { + if(isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { + linePositions[i] = lastX; + linePositions[i + 1] = lastY; + } + else { + lastX = linePositions[i]; + lastY = linePositions[i + 1]; + } + } + } + + return { + join: join, + positions: linePositions + }; +} + +function convertErrorBarPositions(gd, trace, positions) { + var calcFromTrace = _$registry_731.getComponentMethod('errorbars', 'calcFromTrace'); + var vals = calcFromTrace(trace, gd._fullLayout); + var count = positions.length / 2; + var out = {}; + + function put(axLetter) { + var errors = new Float64Array(4 * count); + var ax = _$axis_ids_650.getFromId(gd, trace[axLetter + 'axis']); + var pOffset = {x: 0, y: 1}[axLetter]; + var eOffset = {x: [0, 1, 2, 3], y: [2, 3, 0, 1]}[axLetter]; + + for(var i = 0, p = 0; i < count; i++, p += 4) { + errors[p + eOffset[0]] = positions[i * 2 + pOffset] - ax.d2l(vals[i][axLetter + 's']) || 0; + errors[p + eOffset[1]] = ax.d2l(vals[i][axLetter + 'h']) - positions[i * 2 + pOffset] || 0; + errors[p + eOffset[2]] = 0; + errors[p + eOffset[3]] = 0; + } + + return errors; + } + + + if(trace.error_x && trace.error_x.visible) { + out.x = { + positions: positions, + errors: put('x') + }; + } + if(trace.error_y && trace.error_y.visible) { + out.y = { + positions: positions, + errors: put('y') + }; + } + + return out; +} + +var _$convert_976 = { + convertStyle: convertStyle, + convertMarkerStyle: convertMarkerStyle, + convertMarkerSelection: convertMarkerSelection, + convertLinePositions: convertLinePositions, + convertErrorBarPositions: convertErrorBarPositions +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$registry_731 = require('../../registry'); */; + +/* removed: var _$attributes_974 = require('./attributes'); */; +/* removed: var _$constants_933 = require('../scatter/constants'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$handleXYDefaults_951 = require('../scatter/xy_defaults'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; + +var _$supplyDefaults_977 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_974, attr, dflt); + } + + var isOpen = traceIn.marker ? /-open/.test(traceIn.marker.symbol) : false; + var isBubble = _$subtypes_949.isBubble(traceIn); + + var len = _$handleXYDefaults_951(traceIn, traceOut, layout, coerce); + if(!len) { + traceOut.visible = false; + return; + } + + coerce('text'); + coerce('mode', len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'); + + if(_$subtypes_949.hasLines(traceOut)) { + coerce('connectgaps'); + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + } + + var dfltHoverOn = []; + + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce); + coerce('marker.line.width', isOpen || isBubble ? 1 : 0); + dfltHoverOn.push('points'); + } + + coerce('fill'); + if(traceOut.fill !== 'none') { + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + } + + if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { + dfltHoverOn.push('fills'); + } + + coerce('hoveron', dfltHoverOn.join('+') || 'points'); + + var errorBarsSupplyDefaults = _$registry_731.getComponentMethod('errorbars', 'supplyDefaults'); + errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'}); + errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); + + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$reglScatter2d_376 = require('regl-scatter2d'); */; +/* removed: var _$Line2D_375 = require('regl-line2d'); */; +/* removed: var _$Error2D_374 = require('regl-error2d'); */; +/* removed: var _$pointCluster_353 = require('point-cluster'); */; +/* removed: var _$newArray_51 = require('array-range'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$prepareRegl_614 = require('../../lib/prepare_regl'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +var __calcMarkerSize_978 = _$calc_928.calcMarkerSize; +var __calcAxisExpansion_978 = _$calc_928.calcAxisExpansion; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$linkTraces_943 = require('../scatter/link_traces'); */; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; + +var __convertStyle_978 = _$convert_976.convertStyle; +var __convertLinePositions_978 = _$convert_976.convertLinePositions; +var __convertErrorBarPositions_978 = _$convert_976.convertErrorBarPositions; + +var __BADNUM_978 = _$numerical_578.BADNUM; +var TOO_MANY_POINTS = _$constants_975.TOO_MANY_POINTS; + +function __calc_978(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = _$axis_ids_650.getFromId(gd, trace.xaxis); + var ya = _$axis_ids_650.getFromId(gd, trace.yaxis); + var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; + var count = trace._length; + var count2 = count * 2; + var stash = {}; + var i, xx, yy; + + var x = xa.makeCalcdata(trace, 'x'); + var y = ya.makeCalcdata(trace, 'y'); + + // we need hi-precision for scatter2d, + // regl-scatter2d uses NaNs for bad/missing values + var positions = new Array(count2); + for(i = 0; i < count; i++) { + xx = x[i]; + yy = y[i]; + positions[i * 2] = xx === __BADNUM_978 ? NaN : xx; + positions[i * 2 + 1] = yy === __BADNUM_978 ? NaN : yy; + } + + if(xa.type === 'log') { + for(i = 0; i < count2; i += 2) { + positions[i] = xa.c2l(positions[i]); + } + } + if(ya.type === 'log') { + for(i = 1; i < count2; i += 2) { + positions[i] = ya.c2l(positions[i]); + } + } + + // we don't build a tree for log axes since it takes long to convert log2px + // and it is also + if(xa.type !== 'log' && ya.type !== 'log') { + // FIXME: delegate this to webworker + stash.tree = _$pointCluster_353(positions); + } else { + var ids = stash.ids = new Array(count); + for(i = 0; i < count; i++) { + ids[i] = i; + } + } + + // create scene options and scene + _$calcMarkerColorscale_932(trace); + var opts = sceneOptions(gd, subplot, trace, positions); + var scene = sceneUpdate(gd, subplot); + + // Re-use SVG scatter axis expansion routine except + // for graph with very large number of points where it + // performs poorly. + // In big data case, fake Axes.expand outputs with data bounds, + // and an average size for array marker.size inputs. + var ppad; + if(count < TOO_MANY_POINTS) { + ppad = __calcMarkerSize_978(trace, count); + } else if(opts.marker) { + ppad = 2 * (opts.marker.sizeAvg || Math.max(opts.marker.size, 3)); + } + __calcAxisExpansion_978(gd, trace, xa, ya, x, y, ppad); + + // set flags to create scene renderers + if(opts.fill && !scene.fill2d) scene.fill2d = true; + if(opts.marker && !scene.scatter2d) scene.scatter2d = true; + if(opts.line && !scene.line2d) scene.line2d = true; + if((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true; + + // FIXME: organize it in a more appropriate manner, probably in sceneOptions + // put point-cluster instance for optimized regl calc + if(opts.marker && count >= TOO_MANY_POINTS) { + opts.marker.cluster = stash.tree; + } + + // save scene opts batch + scene.lineOptions.push(opts.line); + scene.errorXOptions.push(opts.errorX); + scene.errorYOptions.push(opts.errorY); + scene.fillOptions.push(opts.fill); + scene.markerOptions.push(opts.marker); + scene.selectedOptions.push(opts.selected); + scene.unselectedOptions.push(opts.unselected); + scene.count++; + + // stash scene ref + stash._scene = scene; + stash.index = scene.count - 1; + stash.x = x; + stash.y = y; + stash.positions = positions; + stash.count = count; + + gd.firstscatter = false; + return [{x: false, y: false, t: stash, trace: trace}]; +} + +// create scene options +function sceneOptions(gd, subplot, trace, positions) { + var opts = __convertStyle_978(gd, trace); + + if(opts.marker) { + opts.marker.positions = positions; + } + + if(opts.line && positions.length > 1) { + _$lib_601.extendFlat( + opts.line, + __convertLinePositions_978(gd, trace, positions) + ); + } + + if(opts.errorX || opts.errorY) { + var errors = __convertErrorBarPositions_978(gd, trace, positions); + + if(opts.errorX) { + _$lib_601.extendFlat(opts.errorX, errors.x); + } + if(opts.errorY) { + _$lib_601.extendFlat(opts.errorY, errors.y); + } + } + + return opts; +} + +// make sure scene exists on subplot, return it +function sceneUpdate(gd, subplot) { + var scene = subplot._scene; + var fullLayout = gd._fullLayout; + + var reset = { + // 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: [], + selectedOptions: [], + unselectedOptions: [], + errorXOptions: [], + errorYOptions: [] + }; + + var first = { + selectBatch: null, + unselectBatch: null, + // regl- component stubs, initialized in dirty plot call + fill2d: false, + scatter2d: false, + error2d: false, + line2d: false, + select2d: null + }; + + if(!subplot._scene) { + scene = subplot._scene = _$lib_601.extendFlat({}, reset, first); + + // apply new option to all regl components (used on drag) + scene.update = function update(opt) { + var opts = new Array(scene.count); + for(var i = 0; i < scene.count; i++) { + opts[i] = opt; + } + + 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); + + scene.draw(); + }; + + // draw traces in proper order + scene.draw = function draw() { + var i; + for(i = 0; i < scene.count; i++) { + if(scene.fill2d && scene.fillOptions[i]) { + // must do all fills first + scene.fill2d.draw(i); + } + } + for(i = 0; i < scene.count; i++) { + if(scene.line2d && scene.lineOptions[i]) { + scene.line2d.draw(i); + } + if(scene.error2d && scene.errorXOptions[i]) { + scene.error2d.draw(i); + } + if(scene.error2d && scene.errorYOptions[i]) { + scene.error2d.draw(i + scene.count); + } + if(scene.scatter2d && scene.markerOptions[i] && (!scene.selectBatch || !scene.selectBatch[i])) { + // traces in no-selection mode + scene.scatter2d.draw(i); + } + } + + // draw traces in selection mode + if(scene.scatter2d && scene.select2d && scene.selectBatch) { + scene.select2d.draw(scene.selectBatch); + scene.scatter2d.draw(scene.unselectBatch); + } + + scene.dirty = false; + }; + + // make sure canvas is clear + scene.clear = function clear() { + var vpSize = fullLayout._size; + var width = fullLayout.width; + var height = fullLayout.height; + var xaxis = subplot.xaxis; + var yaxis = subplot.yaxis; + var vp = [ + vpSize.l + xaxis.domain[0] * vpSize.w, + vpSize.b + yaxis.domain[0] * vpSize.h, + (width - vpSize.r) - (1 - xaxis.domain[1]) * vpSize.w, + (height - vpSize.t) - (1 - yaxis.domain[1]) * vpSize.h + ]; + + var gl, regl; + + if(scene.select2d) { + regl = scene.select2d.regl; + gl = regl._gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + + if(scene.scatter2d) { + regl = scene.scatter2d.regl; + gl = regl._gl; + gl.enable(gl.SCISSOR_TEST); + gl.scissor(vp[0], vp[1], vp[2] - vp[0], vp[3] - vp[1]); + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + }; + + // remove scene resources + scene.destroy = function destroy() { + if(scene.fill2d) scene.fill2d.destroy(); + if(scene.scatter2d) scene.scatter2d.destroy(); + if(scene.error2d) scene.error2d.destroy(); + if(scene.line2d) scene.line2d.destroy(); + if(scene.select2d) scene.select2d.destroy(); + + scene.lineOptions = null; + scene.fillOptions = null; + scene.markerOptions = null; + scene.selectedOptions = null; + scene.unselectedOptions = null; + scene.errorXOptions = null; + scene.errorYOptions = 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_601.extendFlat(scene, reset); + } + + return scene; +} + +function __plot_978(gd, subplot, cdata) { if(!cdata.length) return; var fullLayout = gd._fullLayout; - var scene = cdata[0][0].t.scene; + var scene = cdata[0][0].t._scene; var dragmode = fullLayout.dragmode; // we may have more subplots than initialized data due to Axes.getSubplots method @@ -144646,38 +146804,25 @@ function plot(gd, subplot, cdata) { var width = fullLayout.width; var height = fullLayout.height; - // make sure proper regl instances are created - fullLayout._glcanvas.each(function(d) { - if(d.regl || d.pick) return; - d.regl = _$regl_315({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - extensions: ['ANGLE_instanced_arrays', 'OES_element_index_uint'], - pixelRatio: gd._context.plotGlPixelRatio || global.devicePixelRatio - }); - }); - + _$prepareRegl_614(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']); var regl = fullLayout._glcanvas.data()[0].regl; // that is needed for fills - _$linkTraces_878(gd, subplot, cdata); + _$linkTraces_943(gd, subplot, cdata); if(scene.dirty) { // make sure scenes are created if(scene.error2d === true) { - scene.error2d = _$Error2D_311(regl); + scene.error2d = _$Error2D_374(regl); } if(scene.line2d === true) { - scene.line2d = _$createLine_312(regl); + scene.line2d = _$Line2D_375(regl); } if(scene.scatter2d === true) { - scene.scatter2d = _$Scatter_313(regl); + scene.scatter2d = _$reglScatter2d_376(regl); } if(scene.fill2d === true) { - scene.fill2d = _$createLine_312(regl); + scene.fill2d = _$Line2D_375(regl); } // update main marker options @@ -144784,6 +146929,8 @@ function plot(gd, subplot, cdata) { } var selectMode = dragmode === 'lasso' || dragmode === 'select'; + scene.selectBatch = null; + scene.unselectBatch = null; // provide viewport and range var vpRange = cdata.map(function(cdscatter) { @@ -144795,8 +146942,8 @@ function plot(gd, subplot, cdata) { var x = stash.x; var y = stash.y; - var xaxis = subplot.xaxis || _$axis_ids_587.getFromId(gd, trace.xaxis || 'x'); - var yaxis = subplot.yaxis || _$axis_ids_587.getFromId(gd, trace.yaxis || 'y'); + var xaxis = subplot.xaxis || _$axis_ids_650.getFromId(gd, trace.xaxis || 'x'); + var yaxis = subplot.yaxis || _$axis_ids_650.getFromId(gd, trace.yaxis || 'y'); var i; var range = [ @@ -144816,8 +146963,10 @@ function plot(gd, subplot, cdata) { if(trace.selectedpoints || selectMode) { if(!selectMode) selectMode = true; - if(!scene.selectBatch) scene.selectBatch = []; - if(!scene.unselectBatch) scene.unselectBatch = []; + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } // regenerate scene batch, if traces number changed during selection if(trace.selectedpoints) { @@ -144859,7 +147008,7 @@ function plot(gd, subplot, cdata) { // create select2d if(!scene.select2d) { // create scatter instance by cloning scatter2d - scene.select2d = _$Scatter_313(fullLayout._glcanvas.data()[1].regl, {clone: scene.scatter2d}); + scene.select2d = _$reglScatter2d_376(fullLayout._glcanvas.data()[1].regl); } if(scene.scatter2d && scene.selectBatch && scene.selectBatch.length) { @@ -144897,7 +147046,7 @@ function plot(gd, subplot, cdata) { return; } -function hoverPoints(pointData, xval, yval, hovermode) { +function __hoverPoints_978(pointData, xval, yval, hovermode) { var cd = pointData.cd; var stash = cd[0].t; var trace = cd[0].trace; @@ -144937,9 +147086,9 @@ function hoverPoints(pointData, xval, yval, hovermode) { // pick the id closest to the point // note that point possibly may not be found - var minDist = maxDistance; var id, ptx, pty, i, dx, dy, dist, dxy; + var minDist = maxDistance; if(hovermode === 'x') { for(i = 0; i < ids.length; i++) { ptx = x[ids[i]]; @@ -144968,9 +147117,24 @@ function hoverPoints(pointData, xval, yval, hovermode) { } pointData.index = id; + pointData.distance = minDist; + pointData.dxy = dxy; if(id === undefined) return [pointData]; + calcHover(pointData, x, y, trace); + + return [pointData]; +} + + +function calcHover(pointData, x, y, trace) { + var xa = pointData.xa; + var ya = pointData.ya; + var minDist = pointData.distance; + var dxy = pointData.dxy; + var id = pointData.index; + // the closest data point var di = { pointNumber: id, @@ -144993,16 +147157,16 @@ function hoverPoints(pointData, xval, yval, hovermode) { var marker = trace.marker; if(marker) { - di.ms = _$lib_539.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size; - di.mo = _$lib_539.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity; + di.ms = _$lib_601.isArrayOrTypedArray(marker.size) ? marker.size[id] : marker.size; + di.mo = _$lib_601.isArrayOrTypedArray(marker.opacity) ? marker.opacity[id] : marker.opacity; di.mx = Array.isArray(marker.symbol) ? marker.symbol[id] : marker.symbol; - di.mc = _$lib_539.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color; + di.mc = _$lib_601.isArrayOrTypedArray(marker.color) ? marker.color[id] : marker.color; } var line = marker && marker.line; if(line) { di.mlc = Array.isArray(line.color) ? line.color[id] : line.color; - di.mlw = _$lib_539.isArrayOrTypedArray(line.width) ? line.width[id] : line.width; + di.mlw = _$lib_601.isArrayOrTypedArray(line.width) ? line.width[id] : line.width; } var grad = marker && marker.gradient; @@ -145033,8 +147197,8 @@ function hoverPoints(pointData, xval, yval, hovermode) { var fakeCd = {}; fakeCd[pointData.index] = di; - _$lib_539.extendFlat(pointData, { - color: _$getTraceColor_872(trace, di), + _$lib_601.extendFlat(pointData, { + color: _$getTraceColor_937(trace, di), x0: xp - rad, x1: xp + rad, @@ -145053,12 +147217,13 @@ function hoverPoints(pointData, xval, yval, hovermode) { else if(di.tx) pointData.text = di.tx; else if(trace.text) pointData.text = trace.text; - _$fillHoverText_870(di, trace, pointData); - _$registry_668.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); + _$fillHoverText_935(di, trace, pointData); + _$registry_731.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData); - return [pointData]; + return pointData; } + function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var selection = []; @@ -145066,11 +147231,11 @@ function selectPoints(searchInfo, polygon) { var stash = cd[0].t; var x = stash.x; var y = stash.y; - var scene = stash.scene; + var scene = stash._scene; if(!scene) return selection; - var hasOnlyLines = (!_$subtypes_884.hasMarkers(trace) && !_$subtypes_884.hasText(trace)); + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); if(trace.visible !== true || hasOnlyLines) return selection; // degenerate polygon does not enable selection @@ -145094,7 +147259,7 @@ function selectPoints(searchInfo, polygon) { } } } else { - unels = _$newArray_50(stash.count); + unels = _$newArray_51(stash.count); } // make sure selectBatch is created @@ -145119,33 +147284,40 @@ function selectPoints(searchInfo, polygon) { return selection; } -function style(gd, cd) { - if(cd) { - var stash = cd[0].t; - var scene = stash.scene; +function __style_978(gd, cds) { + if(!cds) return; + + var stash = cds[0][0].t; + var scene = stash._scene; + + // don't clear the subplot if there are splom traces + // on the graph + if(!gd._fullLayout._has('splom')) { scene.clear(); - scene.draw(); } + + scene.draw(); } -_$scattergl_911 = { +var _$scattergl_978 = { moduleType: 'trace', name: 'scattergl', - basePlotModule: _$cartesian_595, + basePlotModule: _$cartesian_658, categories: ['gl', 'regl', 'cartesian', 'symbols', 'errorBarsOK', 'markerColorscale', 'showLegend', 'scatter-like'], - attributes: _$attributes_909, - supplyDefaults: _$supplyDefaults_910, - cleanData: _$cleanData_865, - colorbar: _$colorbar_866, - calc: calc, - plot: plot, - hoverPoints: hoverPoints, - style: style, + attributes: _$attributes_974, + supplyDefaults: _$supplyDefaults_977, + cleanData: _$cleanData_930, + colorbar: _$colorbar_931, + calc: __calc_978, + plot: __plot_978, + hoverPoints: __hoverPoints_978, + style: __style_978, selectPoints: selectPoints, sceneOptions: sceneOptions, sceneUpdate: sceneUpdate, + calcHover: calcHover, meta: { @@ -145153,7 +147325,6 @@ _$scattergl_911 = { } }; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -145164,13 +147335,13 @@ _$scattergl_911 = { 'use strict'; -var _$scattergl_30 = _$scattergl_911; +var _$scattergl_30 = _$scattergl_978; -var _$mapboxGl_254 = { exports: {} }; +var _$mapboxGl_311 = { exports: {} }; (function (global){ 'use strict';(function (f) { - if (typeof _$mapboxGl_254.exports === 'object' && "object" !== 'undefined') { - _$mapboxGl_254.exports = f(); + if (typeof _$mapboxGl_311.exports === 'object' && "object" !== 'undefined') { + _$mapboxGl_311.exports = f(); } else if (typeof define === 'function' && define.amd) { define([], f); } else { @@ -170147,7 +172318,7 @@ var _$mapboxGl_254 = { exports: {} }; }, {}, [73])(73); })); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -_$mapboxGl_254 = _$mapboxGl_254.exports +_$mapboxGl_311 = _$mapboxGl_311.exports /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -170160,7 +172331,7 @@ _$mapboxGl_254 = _$mapboxGl_254.exports var requiredVersion = '0.44.1'; -var _$constants_639 = { +var _$constants_701 = { requiredVersion: requiredVersion, styleUrlPrefix: 'mapbox://styles/mapbox/', @@ -170201,22 +172372,22 @@ var _$constants_639 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -var __defaultLine_643 = _$color_411.defaultLine; -var __domainAttrs_643 = _$domain_610.attributes; -/* removed: var _$font_attributes_611 = require('../font_attributes'); */; -var textposition = _$attributes_862.textposition; -var __overrideAll_643 = _$edit_types_569.overrideAll; +/* removed: var _$lib_601 = require('../../lib'); */; +var __defaultLine_705 = _$color_473.defaultLine; +var __domainAttrs_705 = _$domain_672.attributes; +/* removed: var _$font_attributes_673 = require('../font_attributes'); */; +var textposition = _$attributes_927.textposition; +var __overrideAll_705 = _$edit_types_632.overrideAll; -var fontAttr = _$font_attributes_611({ +var fontAttr = _$font_attributes_673({ }); fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular'; -var _$layout_attributes_643 = __overrideAll_643({ - _arrayAttrRegexps: [_$lib_539.counterRegex('mapbox', '.layers', true)], +var _$layout_attributes_705 = __overrideAll_705({ + _arrayAttrRegexps: [_$lib_601.counterRegex('mapbox', '.layers', true)], - domain: __domainAttrs_643({name: 'mapbox'}), + domain: __domainAttrs_705({name: 'mapbox'}), accesstoken: { valType: 'string', @@ -170307,7 +172478,7 @@ var _$layout_attributes_643 = __overrideAll_643({ }, color: { valType: 'color', - dflt: __defaultLine_643, + dflt: __defaultLine_705, }, @@ -170342,7 +172513,7 @@ var _$layout_attributes_643 = __overrideAll_643({ fill: { outlinecolor: { valType: 'color', - dflt: __defaultLine_643, + dflt: __defaultLine_705, } @@ -170368,7 +172539,7 @@ var _$layout_attributes_643 = __overrideAll_643({ }, textfont: fontAttr, - textposition: _$lib_539.extendFlat({}, textposition, { arrayOk: false }) + textposition: _$lib_601.extendFlat({}, textposition, { arrayOk: false }) } } }, 'plot', 'from-root'); @@ -170384,23 +172555,23 @@ var _$layout_attributes_643 = __overrideAll_643({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../subplot_defaults'); */; -/* removed: var _$layout_attributes_643 = require('./layout_attributes'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../subplot_defaults'); */; +/* removed: var _$layout_attributes_705 = require('./layout_attributes'); */; -var _$supplyLayoutDefaults_644 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_706 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'mapbox', - attributes: _$layout_attributes_643, - handleDefaults: __handleDefaults_644, + attributes: _$layout_attributes_705, + handleDefaults: __handleDefaults_706, partition: 'y', accessToken: layoutOut._mapboxAccessToken }); }; -function __handleDefaults_644(containerIn, containerOut, coerce, opts) { +function __handleDefaults_706(containerIn, containerOut, coerce, opts) { coerce('accesstoken', opts.accessToken); coerce('style'); coerce('center.lon'); @@ -170422,14 +172593,14 @@ function handleLayerDefaults(containerIn, containerOut) { var layerIn, layerOut; function coerce(attr, dflt) { - return _$lib_539.coerce(layerIn, layerOut, _$layout_attributes_643.layers, attr, dflt); + return _$lib_601.coerce(layerIn, layerOut, _$layout_attributes_705.layers, attr, dflt); } for(var i = 0; i < layersIn.length; i++) { layerIn = layersIn[i]; layerOut = {}; - if(!_$lib_539.isPlainObject(layerIn)) continue; + if(!_$lib_601.isPlainObject(layerIn)) continue; var sourceType = coerce('sourcetype'); coerce('source'); @@ -170460,7 +172631,7 @@ function handleLayerDefaults(containerIn, containerOut) { coerce('symbol.iconsize'); coerce('symbol.text'); - _$lib_539.coerceFont(coerce, 'symbol.textfont'); + _$lib_601.coerceFont(coerce, 'symbol.textfont'); coerce('symbol.textposition'); } @@ -170480,7 +172651,7 @@ function handleLayerDefaults(containerIn, containerOut) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; /** * Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset' @@ -170493,13 +172664,13 @@ function handleLayerDefaults(containerIn, containerOut) { * - anchor * - offset */ -var _$convertTextOpts_640 = function convertTextOpts(textposition, iconSize) { +var _$convertTextOpts_702 = function convertTextOpts(textposition, iconSize) { var parts = textposition.split(' '), vPos = parts[0], hPos = parts[1]; // ballpack values - var factor = _$lib_539.isArrayOrTypedArray(iconSize) ? _$lib_539.mean(iconSize) : iconSize, + var factor = _$lib_601.isArrayOrTypedArray(iconSize) ? _$lib_601.mean(iconSize) : iconSize, xInc = 0.5 + (factor / 100), yInc = 1.5 + (factor / 100); @@ -170551,8 +172722,8 @@ var _$convertTextOpts_640 = function convertTextOpts(textposition, iconSize) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$convertTextOpts_640 = require('./convert_text_opts'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$convertTextOpts_702 = require('./convert_text_opts'); */; function MapboxLayer(mapbox, index) { this.mapbox = mapbox; @@ -170573,9 +172744,9 @@ function MapboxLayer(mapbox, index) { this.visible = false; } -var __proto_642 = MapboxLayer.prototype; +var __proto_704 = MapboxLayer.prototype; -__proto_642.update = function update(opts) { +__proto_704.update = function update(opts) { if(!this.visible) { // IMPORTANT: must create source before layer to not cause errors this.updateSource(opts); @@ -170593,7 +172764,7 @@ __proto_642.update = function update(opts) { this.visible = isVisible(opts); }; -__proto_642.needsNewSource = function(opts) { +__proto_704.needsNewSource = function(opts) { // for some reason changing layer to 'fill' or 'symbol' // w/o changing the source throws an exception in mapbox-gl 0.18 ; // stay safe and make new source on type changes @@ -170604,14 +172775,14 @@ __proto_642.needsNewSource = function(opts) { ); }; -__proto_642.needsNewLayer = function(opts) { +__proto_704.needsNewLayer = function(opts) { return ( this.layerType !== opts.type || this.below !== opts.below ); }; -__proto_642.updateSource = function(opts) { +__proto_704.updateSource = function(opts) { var map = this.map; if(map.getSource(this.idSource)) map.removeSource(this.idSource); @@ -170626,7 +172797,7 @@ __proto_642.updateSource = function(opts) { map.addSource(this.idSource, sourceOpts); }; -__proto_642.updateLayer = function(opts) { +__proto_704.updateLayer = function(opts) { var map = this.map; var convertedOpts = convertOpts(opts); @@ -170646,7 +172817,7 @@ __proto_642.updateLayer = function(opts) { } }; -__proto_642.updateStyle = function(opts) { +__proto_704.updateStyle = function(opts) { if(isVisible(opts)) { var convertedOpts = convertOpts(opts); this.mapbox.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout); @@ -170654,7 +172825,7 @@ __proto_642.updateStyle = function(opts) { } }; -__proto_642.dispose = function dispose() { +__proto_704.dispose = function dispose() { var map = this.map; map.removeLayer(this.idLayer); map.removeSource(this.idSource); @@ -170664,7 +172835,7 @@ function isVisible(opts) { var source = opts.source; return ( - _$lib_539.isPlainObject(source) || + _$lib_601.isPlainObject(source) || (typeof source === 'string' && source.length > 0) ); } @@ -170676,7 +172847,7 @@ function convertOpts(opts) { switch(opts.type) { case 'circle': - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'circle-radius': opts.circle.radius, 'circle-color': opts.color, 'circle-opacity': opts.opacity @@ -170684,7 +172855,7 @@ function convertOpts(opts) { break; case 'line': - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'line-width': opts.line.width, 'line-color': opts.color, 'line-opacity': opts.opacity @@ -170692,7 +172863,7 @@ function convertOpts(opts) { break; case 'fill': - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'fill-color': opts.color, 'fill-outline-color': opts.fill.outlinecolor, 'fill-opacity': opts.opacity @@ -170703,9 +172874,9 @@ function convertOpts(opts) { case 'symbol': var symbol = opts.symbol, - textOpts = _$convertTextOpts_640(symbol.textposition, symbol.iconsize); + textOpts = _$convertTextOpts_702(symbol.textposition, symbol.iconsize); - _$lib_539.extendFlat(layout, { + _$lib_601.extendFlat(layout, { 'icon-image': symbol.icon + '-15', 'icon-size': symbol.iconsize / 10, @@ -170718,7 +172889,7 @@ function convertOpts(opts) { // 'text-font': symbol.textfont.family.split(', '), }); - _$lib_539.extendFlat(paint, { + _$lib_601.extendFlat(paint, { 'icon-color': opts.color, 'text-color': symbol.textfont.color, 'text-opacity': opts.opacity @@ -170745,7 +172916,7 @@ function convertSourceOpts(opts) { return sourceOpts; } -var _$createMapboxLayer_642 = function createMapboxLayer(mapbox, index, opts) { +var _$createMapboxLayer_704 = function createMapboxLayer(mapbox, index, opts) { var mapboxLayer = new MapboxLayer(mapbox, index); mapboxLayer.update(opts); @@ -170764,15 +172935,15 @@ var _$createMapboxLayer_642 = function createMapboxLayer(mapbox, index, opts) { 'use strict'; -/* removed: var _$mapboxGl_254 = require('mapbox-gl'); */; +/* removed: var _$mapboxGl_311 = require('mapbox-gl'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; -/* removed: var _$constants_639 = require('./constants'); */; -/* removed: var _$layout_attributes_643 = require('./layout_attributes'); */; -/* removed: var _$createMapboxLayer_642 = require('./layers'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +var __prepSelect_707 = _$select_664.prepSelect; +/* removed: var _$constants_701 = require('./constants'); */; +/* removed: var _$layout_attributes_705 = require('./layout_attributes'); */; +/* removed: var _$createMapboxLayer_704 = require('./layers'); */; function Mapbox(opts) { this.id = opts.id; @@ -170802,13 +172973,13 @@ function Mapbox(opts) { this.layerList = []; } -var __proto_645 = Mapbox.prototype; +var __proto_707 = Mapbox.prototype; -var _$createMapbox_645 = function createMapbox(opts) { +var _$createMapbox_707 = function createMapbox(opts) { return new Mapbox(opts); }; -__proto_645.plot = function(calcData, fullLayout, promises) { +__proto_707.plot = function(calcData, fullLayout, promises) { var self = this; // feed in new mapbox options @@ -170838,7 +173009,7 @@ __proto_645.plot = function(calcData, fullLayout, promises) { promises.push(promise); }; -__proto_645.createMap = function(calcData, fullLayout, resolve, reject) { +__proto_707.createMap = function(calcData, fullLayout, resolve, reject) { var self = this; var gd = self.gd; var opts = self.opts; @@ -170850,7 +173021,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { self.accessToken = opts.accesstoken; // create the map! - var map = self.map = new _$mapboxGl_254.Map({ + var map = self.map = new _$mapboxGl_311.Map({ container: self.div, style: styleObj.style, @@ -170867,7 +173038,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { }); // clear navigation container - var className = _$constants_639.controlContainerClassName; + var className = _$constants_701.controlContainerClassName; var controlContainer = self.div.getElementsByClassName(className)[0]; self.div.removeChild(controlContainer); @@ -170906,7 +173077,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { if(eventData.originalEvent) { var update = {}; - update[self.id] = _$lib_539.extendFlat({}, view); + update[self.id] = _$lib_601.extendFlat({}, view); gd.emit('plotly_relayout', update); } }); @@ -170923,7 +173094,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { self.xaxis.p2c = function() { return evt.lngLat.lng; }; self.yaxis.p2c = function() { return evt.lngLat.lat; }; - _$fx_453.hover(gd, evt, self.id); + _$fx_515.hover(gd, evt, self.id); }); map.on('click', function(evt) { @@ -170932,11 +173103,11 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { // 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_453.click(gd, evt.originalEvent); + _$fx_515.click(gd, evt.originalEvent); }); function unhover() { - _$fx_453.loneUnhover(fullLayout._toppaper); + _$fx_515.loneUnhover(fullLayout._toppaper); } map.on('dragstart', unhover); @@ -170967,7 +173138,7 @@ __proto_645.createMap = function(calcData, fullLayout, resolve, reject) { }; }; -__proto_645.updateMap = function(calcData, fullLayout, resolve, reject) { +__proto_707.updateMap = function(calcData, fullLayout, resolve, reject) { var self = this; var map = self.map; @@ -170994,7 +173165,7 @@ __proto_645.updateMap = function(calcData, fullLayout, resolve, reject) { } }; -__proto_645.updateData = function(calcData) { +__proto_707.updateData = function(calcData) { var traceHash = this.traceHash; var traceObj, trace, i, j; @@ -171029,7 +173200,7 @@ __proto_645.updateData = function(calcData) { } }; -__proto_645.updateLayout = function(fullLayout) { +__proto_707.updateLayout = function(fullLayout) { var map = this.map, opts = this.opts; @@ -171044,7 +173215,7 @@ __proto_645.updateLayout = function(fullLayout) { this.map.resize(); }; -__proto_645.resolveOnRender = function(resolve) { +__proto_707.resolveOnRender = function(resolve) { var map = this.map; map.on('render', function onRender() { @@ -171056,11 +173227,11 @@ __proto_645.resolveOnRender = function(resolve) { }); }; -__proto_645.rejectOnError = function(reject) { +__proto_707.rejectOnError = function(reject) { var map = this.map; function handler() { - reject(new Error(_$constants_639.mapOnErrorMsg)); + reject(new Error(_$constants_701.mapOnErrorMsg)); } map.once('error', handler); @@ -171070,7 +173241,7 @@ __proto_645.rejectOnError = function(reject) { map.once('layer.error', handler); }; -__proto_645.createFramework = function(fullLayout) { +__proto_707.createFramework = function(fullLayout) { var self = this; var div = self.div = document.createElement('div'); @@ -171091,7 +173262,7 @@ __proto_645.createFramework = function(fullLayout) { self.updateFramework(fullLayout); }; -__proto_645.updateFx = function(fullLayout) { +__proto_707.updateFx = function(fullLayout) { var self = this; var map = self.map; var gd = self.gd; @@ -171139,10 +173310,10 @@ __proto_645.updateFx = function(fullLayout) { }; dragOptions.prepFn = function(e, startX, startY) { - _$prepSelect_602(e, startX, startY, dragOptions, dragMode); + __prepSelect_707(e, startX, startY, dragOptions, dragMode); }; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); } else { map.dragPan.enable(); map.off('zoomstart', self.clearSelect); @@ -171150,7 +173321,7 @@ __proto_645.updateFx = function(fullLayout) { } }; -__proto_645.updateFramework = function(fullLayout) { +__proto_707.updateFramework = function(fullLayout) { var domain = fullLayout[this.id].domain; var size = fullLayout._size; @@ -171167,7 +173338,7 @@ __proto_645.updateFramework = function(fullLayout) { this.yaxis._length = size.h * (domain.y[1] - domain.y[0]); }; -__proto_645.updateLayers = function() { +__proto_707.updateLayers = function() { var opts = this.opts; var layers = opts.layers; var layerList = this.layerList; @@ -171185,7 +173356,7 @@ __proto_645.updateLayers = function() { layerList = this.layerList = []; for(i = 0; i < layers.length; i++) { - layerList.push(_$createMapboxLayer_642(this, i, layers[i])); + layerList.push(_$createMapboxLayer_704(this, i, layers[i])); } } else { for(i = 0; i < layers.length; i++) { @@ -171194,7 +173365,7 @@ __proto_645.updateLayers = function() { } }; -__proto_645.destroy = function() { +__proto_707.destroy = function() { if(this.map) { this.map.remove(); this.map = null; @@ -171202,26 +173373,26 @@ __proto_645.destroy = function() { } }; -__proto_645.toImage = function() { +__proto_707.toImage = function() { this.map.stop(); return this.map.getCanvas().toDataURL(); }; // convenience wrapper to create set multiple layer // 'layout' or 'paint options at once. -__proto_645.setOptions = function(id, methodName, opts) { +__proto_707.setOptions = function(id, methodName, opts) { for(var k in opts) { this.map[methodName](id, k, opts[k]); } }; // convenience method to project a [lon, lat] array to pixel coords -__proto_645.project = function(v) { - return this.map.project(new _$mapboxGl_254.LngLat(v[0], v[1])); +__proto_707.project = function(v) { + return this.map.project(new _$mapboxGl_311.LngLat(v[0], v[1])); }; // get map's current view values in plotly.js notation -__proto_645.getView = function() { +__proto_707.getView = function() { var map = this.map; var mapCenter = map.getCenter(); @@ -171236,11 +173407,11 @@ __proto_645.getView = function() { }; function getStyleObj(val) { - var styleValues = _$layout_attributes_643.style.values; - var styleDflt = _$layout_attributes_643.style.dflt; + var styleValues = _$layout_attributes_705.style.values; + var styleDflt = _$layout_attributes_705.style.dflt; var styleObj = {}; - if(_$lib_539.isPlainObject(val)) { + if(_$lib_601.isPlainObject(val)) { styleObj.id = val.id; styleObj.style = val; } else if(typeof val === 'string') { @@ -171260,14 +173431,14 @@ function getStyleObj(val) { // if style is part of the 'official' mapbox values, add URL prefix and suffix function convertStyleVal(val) { - return _$constants_639.styleUrlPrefix + val + '-' + _$constants_639.styleUrlSuffix; + return _$constants_701.styleUrlPrefix + val + '-' + _$constants_701.styleUrlSuffix; } function convertCenter(center) { return [center.lon, center.lat]; } -var _$mapbox_641 = {}; +var _$mapbox_703 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -171278,30 +173449,30 @@ var _$mapbox_641 = {}; 'use strict'; -/* removed: var _$mapboxGl_254 = require('mapbox-gl'); */; +/* removed: var _$mapboxGl_311 = require('mapbox-gl'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __getSubplotCalcData_641 = _$get_data_621.getSubplotCalcData; -/* removed: var _$xmlns_namespaces_519 = require('../../constants/xmlns_namespaces'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __getSubplotCalcData_703 = _$get_data_683.getSubplotCalcData; +/* removed: var _$xmlns_namespaces_580 = require('../../constants/xmlns_namespaces'); */; -/* removed: var _$createMapbox_645 = require('./mapbox'); */; -/* removed: var _$constants_639 = require('./constants'); */; +/* removed: var _$createMapbox_707 = require('./mapbox'); */; +/* removed: var _$constants_701 = require('./constants'); */; var MAPBOX = 'mapbox'; -for(var __k_641 in _$constants_639.styleRules) { - _$lib_539.addStyleRule('.mapboxgl-' + __k_641, _$constants_639.styleRules[__k_641]); +for(var __k_703 in _$constants_701.styleRules) { + _$lib_601.addStyleRule('.mapboxgl-' + __k_703, _$constants_701.styleRules[__k_703]); } -_$mapbox_641.name = MAPBOX; +_$mapbox_703.name = MAPBOX; -_$mapbox_641.attr = 'subplot'; +_$mapbox_703.attr = 'subplot'; -_$mapbox_641.idRoot = MAPBOX; +_$mapbox_703.idRoot = MAPBOX; -_$mapbox_641.idRegex = _$mapbox_641.attrRegex = _$lib_539.counterRegex(MAPBOX); +_$mapbox_703.idRegex = _$mapbox_703.attrRegex = _$lib_601.counterRegex(MAPBOX); -_$mapbox_641.attributes = { +_$mapbox_703.attributes = { subplot: { valType: 'subplotid', @@ -171311,30 +173482,30 @@ _$mapbox_641.attributes = { } }; -_$mapbox_641.layoutAttributes = _$layout_attributes_643; +_$mapbox_703.layoutAttributes = _$layout_attributes_705; -_$mapbox_641.supplyLayoutDefaults = _$supplyLayoutDefaults_644; +_$mapbox_703.supplyLayoutDefaults = _$supplyLayoutDefaults_706; -_$mapbox_641.plot = function plotMapbox(gd) { +_$mapbox_703.plot = function plotMapbox(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var mapboxIds = fullLayout._subplots[MAPBOX]; - if(_$mapboxGl_254.version !== _$constants_639.requiredVersion) { - throw new Error(_$constants_639.wrongVersionErrorMsg); + if(_$mapboxGl_311.version !== _$constants_701.requiredVersion) { + throw new Error(_$constants_701.wrongVersionErrorMsg); } var accessToken = findAccessToken(gd, mapboxIds); - _$mapboxGl_254.accessToken = accessToken; + _$mapboxGl_311.accessToken = accessToken; for(var i = 0; i < mapboxIds.length; i++) { var id = mapboxIds[i], - subplotCalcData = __getSubplotCalcData_641(calcData, MAPBOX, id), + subplotCalcData = __getSubplotCalcData_703(calcData, MAPBOX, id), opts = fullLayout[id], mapbox = opts._subplot; if(!mapbox) { - mapbox = _$createMapbox_645({ + mapbox = _$createMapbox_707({ gd: gd, container: fullLayout._glcontainer.node(), id: id, @@ -171347,7 +173518,7 @@ _$mapbox_641.plot = function plotMapbox(gd) { if(!mapbox.viewInitial) { mapbox.viewInitial = { - center: _$lib_539.extendFlat({}, opts.center), + center: _$lib_601.extendFlat({}, opts.center), zoom: opts.zoom, bearing: opts.bearing, pitch: opts.pitch @@ -171358,7 +173529,7 @@ _$mapbox_641.plot = function plotMapbox(gd) { } }; -_$mapbox_641.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$mapbox_703.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || []; for(var i = 0; i < oldMapboxKeys.length; i++) { @@ -171370,7 +173541,7 @@ _$mapbox_641.clean = function(newFullData, newFullLayout, oldFullData, oldFullLa } }; -_$mapbox_641.toSVG = function(gd) { +_$mapbox_703.toSVG = function(gd) { var fullLayout = gd._fullLayout; var subplotIds = fullLayout._subplots[MAPBOX]; var size = fullLayout._size; @@ -171384,7 +173555,7 @@ _$mapbox_641.toSVG = function(gd) { var image = fullLayout._glimages.append('svg:image'); image.attr({ - xmlns: _$xmlns_namespaces_519.svg, + xmlns: _$xmlns_namespaces_580.svg, 'xlink:href': imageData, x: size.l + size.w * domain.x[0], y: size.t + size.h * (1 - domain.y[1]), @@ -171414,10 +173585,10 @@ function findAccessToken(gd, mapboxIds) { } } - throw new Error(_$constants_639.noAccessTokenErrorMsg); + throw new Error(_$constants_701.noAccessTokenErrorMsg); } -_$mapbox_641.updateFx = function(fullLayout) { +_$mapbox_703.updateFx = function(fullLayout) { var subplotIds = fullLayout._subplots[MAPBOX]; for(var i = 0; i < subplotIds.length; i++) { @@ -171436,46 +173607,46 @@ _$mapbox_641.updateFx = function(fullLayout) { 'use strict'; -/* removed: var _$attributes_900 = require('../scattergeo/attributes'); */; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$layout_attributes_643 = require('../../plots/mapbox/layout_attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; +/* removed: var _$attributes_965 = require('../scattergeo/attributes'); */; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$layout_attributes_705 = require('../../plots/mapbox/layout_attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; -var __extendFlat_912 = _$extend_528.extendFlat; -var __overrideAll_912 = _$edit_types_569.overrideAll; +var __extendFlat_979 = _$extend_590.extendFlat; +var __overrideAll_979 = _$edit_types_632.overrideAll; -var __lineAttrs_912 = _$attributes_900.line; -var markerAttrs = _$attributes_900.marker; +var __lineAttrs_979 = _$attributes_965.line; +var markerAttrs = _$attributes_965.marker; -var _$attributes_912 = __overrideAll_912({ - lon: _$attributes_900.lon, - lat: _$attributes_900.lat, +var _$attributes_979 = __overrideAll_979({ + lon: _$attributes_965.lon, + lat: _$attributes_965.lat, // locations // locationmode - mode: __extendFlat_912({}, _$attributes_862.mode, { + mode: __extendFlat_979({}, _$attributes_927.mode, { dflt: 'markers', }), - text: __extendFlat_912({}, _$attributes_862.text, { + text: __extendFlat_979({}, _$attributes_927.text, { }), - hovertext: __extendFlat_912({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_979({}, _$attributes_927.hovertext, { }), line: { - color: __lineAttrs_912.color, - width: __lineAttrs_912.width + color: __lineAttrs_979.color, + width: __lineAttrs_979.width // TODO // dash: dash }, - connectgaps: _$attributes_862.connectgaps, + connectgaps: _$attributes_927.connectgaps, marker: { symbol: { @@ -171498,25 +173669,25 @@ var _$attributes_912 = __overrideAll_912({ autocolorscale: markerAttrs.autocolorscale, reversescale: markerAttrs.reversescale, showscale: markerAttrs.showscale, - colorbar: _$attributes_412, + colorbar: _$attributes_474, // line }, - fill: _$attributes_900.fill, - fillcolor: _$attributes_862.fillcolor, + fill: _$attributes_965.fill, + fillcolor: _$attributes_927.fillcolor, - textfont: _$layout_attributes_643.layers.symbol.textfont, - textposition: _$layout_attributes_643.layers.symbol.textposition, + textfont: _$layout_attributes_705.layers.symbol.textfont, + textposition: _$layout_attributes_705.layers.symbol.textposition, selected: { - marker: _$attributes_862.selected.marker + marker: _$attributes_927.selected.marker }, unselected: { - marker: _$attributes_862.unselected.marker + marker: _$attributes_927.unselected.marker }, - hoverinfo: __extendFlat_912({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_979({}, _$attributes_644.hoverinfo, { flags: ['lon', 'lat', 'text', 'name'] }) }, 'calc', 'nested'); @@ -171531,18 +173702,18 @@ var _$attributes_912 = __overrideAll_912({ 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_912 = require('./attributes'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$attributes_979 = require('./attributes'); */; -var _$supplyDefaults_914 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_981 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_912, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_979, attr, dflt); } var len = handleLonLatDefaults(traceIn, traceOut, coerce); @@ -171555,13 +173726,13 @@ var _$supplyDefaults_914 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('hovertext'); coerce('mode'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true}); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true}); // array marker.size and marker.color are only supported with circles @@ -171570,21 +173741,21 @@ var _$supplyDefaults_914 = function supplyDefaults(traceIn, traceOut, defaultCol marker.line = {width: 0}; if(marker.symbol !== 'circle') { - if(_$lib_539.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0]; - if(_$lib_539.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0]; + if(_$lib_601.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0]; + if(_$lib_601.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0]; } } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce, {noSelect: true}); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce, {noSelect: true}); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); } - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; function handleLonLatDefaults(traceIn, traceOut, coerce) { @@ -171608,7 +173779,7 @@ function handleLonLatDefaults(traceIn, traceOut, coerce) { 'use strict'; -var _$eventData_915 = function eventData(out, pt) { +var _$eventData_982 = function eventData(out, pt) { out.lon = pt.lon; out.lat = pt.lat; @@ -171626,13 +173797,13 @@ var _$eventData_915 = function eventData(out, pt) { 'use strict'; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$getTraceColor_872 = require('../scatter/get_trace_color'); */; -/* removed: var _$fillHoverText_870 = require('../scatter/fill_hover_text'); */; -var __BADNUM_916 = _$numerical_517.BADNUM; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$getTraceColor_937 = require('../scatter/get_trace_color'); */; +/* removed: var _$fillHoverText_935 = require('../scatter/fill_hover_text'); */; +var __BADNUM_983 = _$numerical_578.BADNUM; -var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { +var _$hoverPoints_983 = function hoverPoints(pointData, xval, yval) { var cd = pointData.cd; var trace = cd[0].trace; var xa = pointData.xa; @@ -171650,9 +173821,9 @@ var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { function distFn(d) { var lonlat = d.lonlat; - if(lonlat[0] === __BADNUM_916) return Infinity; + if(lonlat[0] === __BADNUM_983) return Infinity; - var lon = _$lib_539.wrap180(lonlat[0]); + var lon = _$lib_601.wrap180(lonlat[0]); var lat = lonlat[1]; var pt = subplot.project([lon, lat]); var dx = pt.x - xa.c2p([xval2, lat]); @@ -171662,14 +173833,14 @@ var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad); } - _$fx_453.getClosest(cd, distFn, pointData); + _$fx_515.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_539.wrap180(lonlat[0]) + lonShift, lonlat[1]]; + var lonlatShifted = [_$lib_601.wrap180(lonlat[0]) + lonShift, lonlat[1]]; // shift labels back to original winded globe var xc = xa.c2p(lonlatShifted); @@ -171681,13 +173852,13 @@ var _$hoverPoints_916 = function hoverPoints(pointData, xval, yval) { pointData.y0 = yc - rad; pointData.y1 = yc + rad; - pointData.color = _$getTraceColor_872(trace, di); - pointData.extraText = __getExtraText_916(trace, di, cd[0].t.labels); + pointData.color = _$getTraceColor_937(trace, di); + pointData.extraText = __getExtraText_983(trace, di, cd[0].t.labels); return [pointData]; }; -function __getExtraText_916(trace, di, labels) { +function __getExtraText_983(trace, di, labels) { var hoverinfo = di.hi || trace.hoverinfo; var parts = hoverinfo.split('+'); var isAll = parts.indexOf('all') !== -1; @@ -171711,7 +173882,7 @@ function __getExtraText_916(trace, di, labels) { } if(isAll || parts.indexOf('text') !== -1) { - _$fillHoverText_870(di, trace, text); + _$fillHoverText_935(di, trace, text); } return text.join('
'); @@ -171727,26 +173898,26 @@ function __getExtraText_916(trace, di, labels) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var __BADNUM_913 = _$numerical_517.BADNUM; -/* removed: var _$geojson_utils_532 = require('../../lib/geojson_utils'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var __BADNUM_980 = _$numerical_578.BADNUM; +/* removed: var _$geojson_utils_594 = require('../../lib/geojson_utils'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$makeBubbleSizeFn_879 = require('../scatter/make_bubble_size_func'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$convertTextOpts_640 = require('../../plots/mapbox/convert_text_opts'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$makeBubbleSizeFn_944 = require('../scatter/make_bubble_size_func'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$convertTextOpts_702 = require('../../plots/mapbox/convert_text_opts'); */; -var _$convert_913 = function convert(calcTrace) { +var _$convert_980 = function convert(calcTrace) { var trace = calcTrace[0].trace; var isVisible = (trace.visible === true); var hasFill = (trace.fill !== 'none'); - var hasLines = _$subtypes_884.hasLines(trace); - var hasMarkers = _$subtypes_884.hasMarkers(trace); - var hasText = _$subtypes_884.hasText(trace); + var hasLines = _$subtypes_949.hasLines(trace); + var hasMarkers = _$subtypes_949.hasMarkers(trace); + var hasText = _$subtypes_949.hasText(trace); var hasCircles = (hasMarkers && trace.marker.symbol === 'circle'); var hasSymbols = (hasMarkers && trace.marker.symbol !== 'circle'); @@ -171768,23 +173939,23 @@ var _$convert_913 = function convert(calcTrace) { // fill layer and line layer use the same coords var lineCoords; if(hasFill || hasLines) { - lineCoords = _$geojson_utils_532.calcTraceToLineCoords(calcTrace); + lineCoords = _$geojson_utils_594.calcTraceToLineCoords(calcTrace); } if(hasFill) { - fill.geojson = _$geojson_utils_532.makePolygon(lineCoords); + fill.geojson = _$geojson_utils_594.makePolygon(lineCoords); fill.layout.visibility = 'visible'; - _$lib_539.extendFlat(fill.paint, { + _$lib_601.extendFlat(fill.paint, { 'fill-color': trace.fillcolor }); } if(hasLines) { - line.geojson = _$geojson_utils_532.makeLine(lineCoords); + line.geojson = _$geojson_utils_594.makeLine(lineCoords); line.layout.visibility = 'visible'; - _$lib_539.extendFlat(line.paint, { + _$lib_601.extendFlat(line.paint, { 'line-width': trace.line.width, 'line-color': trace.line.color, 'line-opacity': trace.opacity @@ -171798,7 +173969,7 @@ var _$convert_913 = function convert(calcTrace) { circle.geojson = circleOpts.geojson; circle.layout.visibility = 'visible'; - _$lib_539.extendFlat(circle.paint, { + _$lib_601.extendFlat(circle.paint, { 'circle-color': circleOpts.mcc, 'circle-radius': circleOpts.mrc, 'circle-opacity': circleOpts.mo @@ -171808,18 +173979,18 @@ var _$convert_913 = function convert(calcTrace) { if(hasSymbols || hasText) { symbol.geojson = makeSymbolGeoJSON(calcTrace); - _$lib_539.extendFlat(symbol.layout, { + _$lib_601.extendFlat(symbol.layout, { visibility: 'visible', 'icon-image': '{symbol}-15', 'text-field': '{text}' }); if(hasSymbols) { - _$lib_539.extendFlat(symbol.layout, { + _$lib_601.extendFlat(symbol.layout, { 'icon-size': trace.marker.size / 10 }); - _$lib_539.extendFlat(symbol.paint, { + _$lib_601.extendFlat(symbol.paint, { 'icon-opacity': trace.opacity * trace.marker.opacity, // TODO does not work ?? @@ -171829,11 +174000,11 @@ var _$convert_913 = function convert(calcTrace) { if(hasText) { var iconSize = (trace.marker || {}).size, - textOpts = _$convertTextOpts_640(trace.textposition, iconSize); + textOpts = _$convertTextOpts_702(trace.textposition, iconSize); // all data-driven below !! - _$lib_539.extendFlat(symbol.layout, { + _$lib_601.extendFlat(symbol.layout, { 'text-size': trace.textfont.size, 'text-anchor': textOpts.anchor, 'text-offset': textOpts.offset @@ -171842,7 +174013,7 @@ var _$convert_913 = function convert(calcTrace) { // 'text-font': symbol.textfont.family.split(', '), }); - _$lib_539.extendFlat(symbol.paint, { + _$lib_601.extendFlat(symbol.paint, { 'text-color': trace.textfont.color, 'text-opacity': trace.opacity }); @@ -171854,7 +174025,7 @@ var _$convert_913 = function convert(calcTrace) { function initContainer() { return { - geojson: _$geojson_utils_532.makeBlank(), + geojson: _$geojson_utils_594.makeBlank(), layout: { visibility: 'none' }, paint: {} }; @@ -171864,9 +174035,9 @@ function makeCircleOpts(calcTrace) { var trace = calcTrace[0].trace; var marker = trace.marker; var selectedpoints = trace.selectedpoints; - var arrayColor = _$lib_539.isArrayOrTypedArray(marker.color); - var arraySize = _$lib_539.isArrayOrTypedArray(marker.size); - var arrayOpacity = _$lib_539.isArrayOrTypedArray(marker.opacity); + var arrayColor = _$lib_601.isArrayOrTypedArray(marker.color); + var arraySize = _$lib_601.isArrayOrTypedArray(marker.size); + var arrayOpacity = _$lib_601.isArrayOrTypedArray(marker.opacity); var i; function addTraceOpacity(o) { return trace.opacity * o; } @@ -171875,24 +174046,24 @@ function makeCircleOpts(calcTrace) { var colorFn; if(arrayColor) { - if(_$colorscale_426.hasColorscale(trace, 'marker')) { - colorFn = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale(marker.colorscale, marker.cmin, marker.cmax) + if(_$colorscale_488.hasColorscale(trace, 'marker')) { + colorFn = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale(marker.colorscale, marker.cmin, marker.cmax) ); } else { - colorFn = _$lib_539.identity; + colorFn = _$lib_601.identity; } } var sizeFn; if(arraySize) { - sizeFn = _$makeBubbleSizeFn_879(trace); + sizeFn = _$makeBubbleSizeFn_944(trace); } var opacityFn; if(arrayOpacity) { opacityFn = function(mo) { - var mo2 = _$fastIsnumeric_139(mo) ? +_$lib_539.constrain(mo, 0, 1) : 0; + var mo2 = _$fastIsnumeric_196(mo) ? +_$lib_601.constrain(mo, 0, 1) : 0; return addTraceOpacity(mo2); }; } @@ -171919,7 +174090,7 @@ function makeCircleOpts(calcTrace) { var fns; if(selectedpoints) { - fns = _$drawing_436.makeSelectedPointStyleFns(trace); + fns = _$drawing_498.makeSelectedPointStyleFns(trace); for(i = 0; i < features.length; i++) { var d = features[i].properties; @@ -171967,7 +174138,7 @@ function makeSymbolGeoJSON(calcTrace) { getFillFunc(symbol) : blankFillFunc; - var fillText = _$subtypes_884.hasText(trace) ? + var fillText = _$subtypes_949.hasText(trace) ? getFillFunc(text) : blankFillFunc; @@ -171998,7 +174169,7 @@ function makeSymbolGeoJSON(calcTrace) { } function getFillFunc(attr) { - if(_$lib_539.isArrayOrTypedArray(attr)) { + if(_$lib_601.isArrayOrTypedArray(attr)) { return function(v) { return v; }; } else if(attr) { @@ -172013,7 +174184,7 @@ function blankFillFunc() { return ''; } // only need to check lon (OR lat) function isBADNUM(lonlat) { - return lonlat[0] === __BADNUM_913; + return lonlat[0] === __BADNUM_980; } /** @@ -172026,7 +174197,7 @@ function isBADNUM(lonlat) { 'use strict'; -/* removed: var _$convert_913 = require('./convert'); */; +/* removed: var _$convert_980 = require('./convert'); */; function ScatterMapbox(subplot, uid) { this.subplot = subplot; @@ -172053,22 +174224,22 @@ function ScatterMapbox(subplot, uid) { // for up-to 4 sources per 'scattermapbox' traces becomes a problem. } -var __proto_918 = ScatterMapbox.prototype; +var __proto_985 = ScatterMapbox.prototype; -__proto_918.addSource = function(k, opts) { +__proto_985.addSource = function(k, opts) { this.subplot.map.addSource(this.sourceIds[k], { type: 'geojson', data: opts.geojson }); }; -__proto_918.setSourceData = function(k, opts) { +__proto_985.setSourceData = function(k, opts) { this.subplot.map .getSource(this.sourceIds[k]) .setData(opts.geojson); }; -__proto_918.addLayer = function(k, opts) { +__proto_985.addLayer = function(k, opts) { this.subplot.map.addLayer({ type: k, id: this.layerIds[k], @@ -172078,9 +174249,9 @@ __proto_918.addLayer = function(k, opts) { }); }; -__proto_918.update = function update(calcTrace) { +__proto_985.update = function update(calcTrace) { var subplot = this.subplot; - var optsAll = _$convert_913(calcTrace); + var optsAll = _$convert_980(calcTrace); for(var i = 0; i < this.order.length; i++) { var k = this.order[i]; @@ -172098,7 +174269,7 @@ __proto_918.update = function update(calcTrace) { calcTrace[0].trace._glTrace = this; }; -__proto_918.dispose = function dispose() { +__proto_985.dispose = function dispose() { var map = this.subplot.map; for(var i = 0; i < this.order.length; i++) { @@ -172108,10 +174279,10 @@ __proto_918.dispose = function dispose() { } }; -var _$createScatterMapbox_918 = function createScatterMapbox(subplot, calcTrace) { +var _$createScatterMapbox_985 = function createScatterMapbox(subplot, calcTrace) { var trace = calcTrace[0].trace; var scatterMapbox = new ScatterMapbox(subplot, trace.uid); - var optsAll = _$convert_913(calcTrace); + var optsAll = _$convert_980(calcTrace); for(var i = 0; i < scatterMapbox.order.length; i++) { var k = scatterMapbox.order[i]; @@ -172137,10 +174308,11 @@ var _$createScatterMapbox_918 = function createScatterMapbox(subplot, calcTrace) 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +var __BADNUM_986 = _$numerical_578.BADNUM; -var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { +var _$selectPoints_986 = function selectPoints(searchInfo, polygon) { var cd = searchInfo.cd; var xa = searchInfo.xaxis; var ya = searchInfo.yaxis; @@ -172148,7 +174320,7 @@ var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { var trace = cd[0].trace; var i; - if(!_$subtypes_884.hasMarkers(trace)) return []; + if(!_$subtypes_949.hasMarkers(trace)) return []; if(polygon === false) { for(i = 0; i < cd.length; i++) { @@ -172158,18 +174330,21 @@ var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { for(i = 0; i < cd.length; i++) { var di = cd[i]; var lonlat = di.lonlat; - var lonlat2 = [_$lib_539.wrap180(lonlat[0]), lonlat[1]]; - var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)]; - if(polygon.contains(xy)) { - selection.push({ - pointNumber: i, - lon: lonlat[0], - lat: lonlat[1] - }); - di.selected = 1; - } else { - di.selected = 0; + if(lonlat[0] !== __BADNUM_986) { + var lonlat2 = [_$lib_601.wrap180(lonlat[0]), lonlat[1]]; + var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)]; + + if(polygon.contains(xy)) { + selection.push({ + pointNumber: i, + lon: lonlat[0], + lat: lonlat[1] + }); + di.selected = 1; + } else { + di.selected = 0; + } } } } @@ -172188,34 +174363,34 @@ var _$selectPoints_919 = function selectPoints(searchInfo, polygon) { 'use strict'; -var __ScatterMapbox_917 = {}; +var __ScatterMapbox_984 = {}; -__ScatterMapbox_917.attributes = _$attributes_912; -__ScatterMapbox_917.supplyDefaults = _$supplyDefaults_914; -__ScatterMapbox_917.colorbar = _$colorbar_866; -__ScatterMapbox_917.calc = _$calc_901; -__ScatterMapbox_917.plot = _$createScatterMapbox_918; -__ScatterMapbox_917.hoverPoints = _$hoverPoints_916; -__ScatterMapbox_917.eventData = _$eventData_915; -__ScatterMapbox_917.selectPoints = _$selectPoints_919; +__ScatterMapbox_984.attributes = _$attributes_979; +__ScatterMapbox_984.supplyDefaults = _$supplyDefaults_981; +__ScatterMapbox_984.colorbar = _$colorbar_931; +__ScatterMapbox_984.calc = _$calc_966; +__ScatterMapbox_984.plot = _$createScatterMapbox_985; +__ScatterMapbox_984.hoverPoints = _$hoverPoints_983; +__ScatterMapbox_984.eventData = _$eventData_982; +__ScatterMapbox_984.selectPoints = _$selectPoints_986; -__ScatterMapbox_917.style = function(_, cd) { +__ScatterMapbox_984.style = function(_, cd) { if(cd) { var trace = cd[0].trace; trace._glTrace.update(cd); } }; -__ScatterMapbox_917.moduleType = 'trace'; -__ScatterMapbox_917.name = 'scattermapbox'; -__ScatterMapbox_917.basePlotModule = _$mapbox_641; -__ScatterMapbox_917.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike']; -__ScatterMapbox_917.meta = { +__ScatterMapbox_984.moduleType = 'trace'; +__ScatterMapbox_984.name = 'scattermapbox'; +__ScatterMapbox_984.basePlotModule = _$mapbox_703; +__ScatterMapbox_984.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike']; +__ScatterMapbox_984.meta = { }; -var _$ScatterMapbox_917 = __ScatterMapbox_917; +var _$ScatterMapbox_984 = __ScatterMapbox_984; /** * Copyright 2012-2018, Plotly, Inc. @@ -172227,7 +174402,7 @@ var _$ScatterMapbox_917 = __ScatterMapbox_917; 'use strict'; -var _$scattermapbox_31 = _$ScatterMapbox_917; +var _$scattermapbox_31 = _$ScatterMapbox_984; /** * Copyright 2012-2018, Plotly, Inc. @@ -172239,7 +174414,7 @@ var _$scattermapbox_31 = _$ScatterMapbox_917; 'use strict'; -var _$constants_648 = { +var _$constants_710 = { attr: 'subplot', name: 'polar', @@ -172283,20 +174458,20 @@ var _$constants_648 = { 'use strict'; -/* removed: var _$attributes_410 = require('../../components/color/attributes'); */; -/* removed: var _$layout_attributes_596 = require('../cartesian/layout_attributes'); */; -var __domainAttrs_651 = _$domain_610.attributes; -var __extendFlat_651 = _$lib_539.extendFlat; -var __overrideAll_651 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_472 = require('../../components/color/attributes'); */; +/* removed: var _$layout_attributes_659 = require('../cartesian/layout_attributes'); */; +var __domainAttrs_713 = _$domain_672.attributes; +var __extendFlat_713 = _$lib_601.extendFlat; +var __overrideAll_713 = _$edit_types_632.overrideAll; -var axisLineGridAttr = __overrideAll_651({ - color: _$layout_attributes_596.color, - showline: __extendFlat_651({}, _$layout_attributes_596.showline, {dflt: true}), - linecolor: _$layout_attributes_596.linecolor, - linewidth: _$layout_attributes_596.linewidth, - showgrid: __extendFlat_651({}, _$layout_attributes_596.showgrid, {dflt: true}), - gridcolor: _$layout_attributes_596.gridcolor, - gridwidth: _$layout_attributes_596.gridwidth +var axisLineGridAttr = __overrideAll_713({ + color: _$layout_attributes_659.color, + showline: __extendFlat_713({}, _$layout_attributes_659.showline, {dflt: true}), + linecolor: _$layout_attributes_659.linecolor, + linewidth: _$layout_attributes_659.linewidth, + showgrid: __extendFlat_713({}, _$layout_attributes_659.showgrid, {dflt: true}), + gridcolor: _$layout_attributes_659.gridcolor, + gridwidth: _$layout_attributes_659.gridwidth // TODO add spike* attributes down the road @@ -172304,37 +174479,37 @@ var axisLineGridAttr = __overrideAll_651({ }, 'plot', 'from-root'); -var axisTickAttrs = __overrideAll_651({ - tickmode: _$layout_attributes_596.tickmode, - nticks: _$layout_attributes_596.nticks, - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: _$layout_attributes_596.ticks, - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - showtickprefix: _$layout_attributes_596.showtickprefix, - tickprefix: _$layout_attributes_596.tickprefix, - showticksuffix: _$layout_attributes_596.showticksuffix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showexponent: _$layout_attributes_596.showexponent, - exponentformat: _$layout_attributes_596.exponentformat, - separatethousands: _$layout_attributes_596.separatethousands, - tickfont: _$layout_attributes_596.tickfont, - tickangle: _$layout_attributes_596.tickangle, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - layer: _$layout_attributes_596.layer +var axisTickAttrs = __overrideAll_713({ + tickmode: _$layout_attributes_659.tickmode, + nticks: _$layout_attributes_659.nticks, + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: _$layout_attributes_659.ticks, + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + showtickprefix: _$layout_attributes_659.showtickprefix, + tickprefix: _$layout_attributes_659.tickprefix, + showticksuffix: _$layout_attributes_659.showticksuffix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showexponent: _$layout_attributes_659.showexponent, + exponentformat: _$layout_attributes_659.exponentformat, + separatethousands: _$layout_attributes_659.separatethousands, + tickfont: _$layout_attributes_659.tickfont, + tickangle: _$layout_attributes_659.tickangle, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + layer: _$layout_attributes_659.layer }, 'plot', 'from-root'); var radialAxisAttrs = { - visible: __extendFlat_651({}, _$layout_attributes_596.visible, {dflt: true}), - type: _$layout_attributes_596.type, + visible: __extendFlat_713({}, _$layout_attributes_659.visible, {dflt: true}), + type: _$layout_attributes_659.type, - autorange: _$layout_attributes_596.autorange, + autorange: _$layout_attributes_659.autorange, rangemode: { valType: 'enumerated', values: ['tozero', 'nonnegative', 'normal'], @@ -172343,10 +174518,10 @@ var radialAxisAttrs = { editType: 'calc', }, - range: _$layout_attributes_596.range, + range: _$layout_attributes_659.range, - categoryorder: _$layout_attributes_596.categoryorder, - categoryarray: _$layout_attributes_596.categoryarray, + categoryorder: _$layout_attributes_659.categoryorder, + categoryarray: _$layout_attributes_659.categoryarray, angle: { valType: 'angle', @@ -172366,11 +174541,11 @@ var radialAxisAttrs = { }, - title: __extendFlat_651({}, _$layout_attributes_596.title, {editType: 'plot', dflt: ''}), - titlefont: __overrideAll_651(_$layout_attributes_596.titlefont, 'plot', 'from-root'), + title: __extendFlat_713({}, _$layout_attributes_659.title, {editType: 'plot', dflt: ''}), + titlefont: __overrideAll_713(_$layout_attributes_659.titlefont, 'plot', 'from-root'), // might need a 'titleside' and even 'titledirection' down the road - hoverformat: _$layout_attributes_596.hoverformat, + hoverformat: _$layout_attributes_659.hoverformat, // More attributes: @@ -172390,7 +174565,7 @@ var radialAxisAttrs = { editType: 'calc' }; -__extendFlat_651( +__extendFlat_713( radialAxisAttrs, // N.B. radialaxis grid lines are circular, @@ -172400,7 +174575,7 @@ __extendFlat_651( ); var angularAxisAttrs = { - visible: __extendFlat_651({}, _$layout_attributes_596.visible, {dflt: true}), + visible: __extendFlat_713({}, _$layout_attributes_659.visible, {dflt: true}), type: { valType: 'enumerated', // 'linear' should maybe be called 'angle' or 'angular' here @@ -172416,8 +174591,8 @@ var angularAxisAttrs = { }, - categoryorder: _$layout_attributes_596.categoryorder, - categoryarray: _$layout_attributes_596.categoryarray, + categoryorder: _$layout_attributes_659.categoryorder, + categoryarray: _$layout_attributes_659.categoryarray, thetaunit: { valType: 'enumerated', @@ -172462,12 +174637,12 @@ var angularAxisAttrs = { }, - hoverformat: _$layout_attributes_596.hoverformat, + hoverformat: _$layout_attributes_659.hoverformat, editType: 'calc' }; -__extendFlat_651( +__extendFlat_713( angularAxisAttrs, // N.B. angular grid lines are straight lines from circle center to outer bound @@ -172478,13 +174653,13 @@ __extendFlat_651( axisTickAttrs ); -var _$layout_attributes_651 = { +var _$layout_attributes_713 = { // TODO for x/y/zoom system for paper-based zooming: // x: {}, // y: {}, // zoom: {}, - domain: __domainAttrs_651({name: 'polar', editType: 'plot'}), + domain: __domainAttrs_713({name: 'polar', editType: 'plot'}), sector: { valType: 'info_array', @@ -172502,7 +174677,7 @@ var _$layout_attributes_651 = { valType: 'color', editType: 'plot', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, }, @@ -172515,7 +174690,7 @@ var _$layout_attributes_651 = { editType: 'calc' }; -var _$helpers_649 = {}; +var _$helpers_711 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -172526,11 +174701,11 @@ var _$helpers_649 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -_$helpers_649.setConvertAngular = function setConvertAngular(ax) { +_$helpers_711.setConvertAngular = function setConvertAngular(ax) { var dir = {clockwise: -1, counterclockwise: 1}[ax.direction]; - var rot = _$lib_539.deg2rad(ax.rotation); + var rot = _$lib_601.deg2rad(ax.rotation); var _c2rad; var _rad2c; @@ -172542,11 +174717,11 @@ _$helpers_649.setConvertAngular = function setConvertAngular(ax) { if(ax.type === 'linear') { _c2rad = function(v, unit) { - if(unit === 'degrees') return _$lib_539.deg2rad(v); + if(unit === 'degrees') return _$lib_601.deg2rad(v); return v; }; _rad2c = function(v, unit) { - if(unit === 'degrees') return _$lib_539.rad2deg(v); + if(unit === 'degrees') return _$lib_601.rad2deg(v); return v; }; } @@ -172574,8 +174749,8 @@ _$helpers_649.setConvertAngular = function setConvertAngular(ax) { ax.c2rad = function(v, unit) { return transformRad(_c2rad(v, unit)); }; ax.rad2c = function(v, unit) { return _rad2c(unTransformRad(v), unit); }; - ax.c2deg = function(v, unit) { return _$lib_539.rad2deg(ax.c2rad(v, unit)); }; - ax.deg2c = function(v, unit) { return ax.rad2c(_$lib_539.deg2rad(v), unit); }; + ax.c2deg = function(v, unit) { return _$lib_601.rad2deg(ax.c2rad(v, unit)); }; + ax.deg2c = function(v, unit) { return ax.rad2c(_$lib_601.deg2rad(v), unit); }; }; /** @@ -172588,33 +174763,32 @@ _$helpers_649.setConvertAngular = function setConvertAngular(ax) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../subplot_defaults'); */; -var __getSubplotData_652 = _$get_data_621.getSubplotData; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../subplot_defaults'); */; +var __getSubplotData_714 = _$get_data_683.getSubplotData; -/* removed: var _$handleTickValueDefaults_606 = require('../cartesian/tick_value_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('../cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../cartesian/tick_label_defaults'); */; -/* removed: var _$handleCategoryOrderDefaults_588 = require('../cartesian/category_order_defaults'); */; -/* removed: var _$handleLineGridDefaults_598 = require('../cartesian/line_grid_defaults'); */; -/* removed: var _$autoType_585 = require('../cartesian/axis_autotype'); */; -/* removed: var _$orderedCategories_599 = require('../cartesian/ordered_categories'); */; -/* removed: var _$setConvert_603 = require('../cartesian/set_convert'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../cartesian/tick_value_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('../cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../cartesian/tick_label_defaults'); */; +/* removed: var _$handleCategoryOrderDefaults_651 = require('../cartesian/category_order_defaults'); */; +/* removed: var _$handleLineGridDefaults_661 = require('../cartesian/line_grid_defaults'); */; +/* removed: var _$autoType_648 = require('../cartesian/axis_autotype'); */; +/* removed: var _$setConvert_665 = require('../cartesian/set_convert'); */; -var setConvertAngular = _$helpers_649.setConvertAngular; -/* removed: var _$layout_attributes_651 = require('./layout_attributes'); */; -/* removed: var _$constants_648 = require('./constants'); */; -var axisNames = _$constants_648.axisNames; +var setConvertAngular = _$helpers_711.setConvertAngular; +/* removed: var _$layout_attributes_713 = require('./layout_attributes'); */; +/* removed: var _$constants_710 = require('./constants'); */; +var axisNames = _$constants_710.axisNames; -function __handleDefaults_652(contIn, contOut, coerce, opts) { +function __handleDefaults_714(contIn, contOut, coerce, opts) { var bgColor = coerce('bgcolor'); - opts.bgColor = _$color_411.combine(bgColor, opts.paper_bgcolor); + opts.bgColor = _$color_473.combine(bgColor, opts.paper_bgcolor); var sector = coerce('sector'); // could optimize, subplotData is not always needed! - var subplotData = __getSubplotData_652(opts.fullData, _$constants_648.name, opts.id); + var subplotData = __getSubplotData_714(opts.fullData, _$constants_710.name, opts.id); var layoutOut = opts.layoutOut; var axName; @@ -172625,7 +174799,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { for(var i = 0; i < axisNames.length; i++) { axName = axisNames[i]; - if(!_$lib_539.isPlainObject(contIn[axName])) { + if(!_$lib_601.isPlainObject(contIn[axName])) { contIn[axName] = {}; } @@ -172633,16 +174807,16 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { var axOut = contOut[axName] = {}; axOut._id = axOut._name = axName; - var dataAttr = _$constants_648.axisName2dataArray[axName]; + var dataAttr = _$constants_710.axisName2dataArray[axName]; var axType = handleAxisTypeDefaults(axIn, axOut, coerceAxis, subplotData, dataAttr); - _$handleCategoryOrderDefaults_588(axIn, axOut, coerceAxis); - axOut._initialCategories = axType === 'category' ? - _$orderedCategories_599(dataAttr, axOut.categoryorder, axOut.categoryarray, subplotData) : - []; + _$handleCategoryOrderDefaults_651(axIn, axOut, coerceAxis, { + axData: subplotData, + dataAttr: dataAttr + }); var visible = coerceAxis('visible'); - _$setConvert_603(axOut, layoutOut); + _$setConvert_665(axOut, layoutOut); var dfltColor; var dfltFontColor; @@ -172679,7 +174853,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { coerceAxis('angle', sector[0]); coerceAxis('title'); - _$lib_539.coerceFont(coerceAxis, 'titlefont', { + _$lib_601.coerceFont(coerceAxis, 'titlefont', { family: opts.font.family, size: Math.round(opts.font.size * 1.2), color: dfltFontColor @@ -172697,7 +174871,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { // when we do add support for data angular axes, the new // behavior won't conflict with existing behavior if(axType === 'date') { - _$lib_539.log('Polar plots do not support date angular axes yet.'); + _$lib_601.log('Polar plots do not support date angular axes yet.'); for(var j = 0; j < subplotData.length; j++) { subplotData[j].visible = false; @@ -172722,15 +174896,15 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { } if(visible) { - _$handleTickValueDefaults_606(axIn, axOut, coerceAxis, axOut.type); - _$handleTickLabelDefaults_604(axIn, axOut, coerceAxis, axOut.type, { + _$handleTickValueDefaults_668(axIn, axOut, coerceAxis, axOut.type); + _$handleTickLabelDefaults_666(axIn, axOut, coerceAxis, axOut.type, { tickSuffixDflt: axOut.thetaunit === 'degrees' ? '°' : undefined }); - _$handleTickDefaults_605(axIn, axOut, coerceAxis, {outerTicks: true}); + _$handleTickDefaults_667(axIn, axOut, coerceAxis, {outerTicks: true}); var showTickLabels = coerceAxis('showticklabels'); if(showTickLabels) { - _$lib_539.coerceFont(coerceAxis, 'tickfont', { + _$lib_601.coerceFont(coerceAxis, 'tickfont', { family: opts.font.family, size: opts.font.size, color: dfltFontColor @@ -172739,7 +174913,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { coerceAxis('tickformat'); } - _$handleLineGridDefaults_598(axIn, axOut, coerceAxis, { + _$handleLineGridDefaults_661(axIn, axOut, coerceAxis, { dfltColor: dfltColor, bgColor: opts.bgColor, // default grid color is darker here (60%, vs cartesian default ~91%) @@ -172748,7 +174922,7 @@ function __handleDefaults_652(contIn, contOut, coerce, opts) { showLine: true, showGrid: true, noZeroLine: true, - attributes: _$layout_attributes_651[axName] + attributes: _$layout_attributes_713[axName] }); coerceAxis('layer'); @@ -172774,7 +174948,7 @@ function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) { } if(trace) { - axOut.type = _$autoType_585(trace[dataAttr], 'gregorian'); + axOut.type = _$autoType_648(trace[dataAttr], 'gregorian'); } if(axOut.type === '-') { @@ -172791,11 +174965,11 @@ function handleAxisTypeDefaults(axIn, axOut, coerce, subplotData, dataAttr) { return axOut.type; } -var _$supplyLayoutDefaults_652 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { - type: _$constants_648.name, - attributes: _$layout_attributes_651, - handleDefaults: __handleDefaults_652, +var _$supplyLayoutDefaults_714 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { + type: _$constants_710.name, + attributes: _$layout_attributes_713, + handleDefaults: __handleDefaults_714, font: layoutOut.font, paper_bgcolor: layoutOut.paper_bgcolor, fullData: fullData, @@ -172813,35 +174987,36 @@ var _$supplyLayoutDefaults_652 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$plots_647 = require('../plots'); */; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; -var __doAutoRange_659 = _$autorange_583.doAutoRange; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$dragbox_592 = require('../cartesian/dragbox'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$titles_504 = require('../../components/titles'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; -/* removed: var _$setCursor_558 = require('../../lib/setcursor'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$plots_709 = require('../plots'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; +var __doAutoRange_721 = _$autorange_646.doAutoRange; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +/* removed: var _$dragbox_655 = require('../cartesian/dragbox'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$titles_566 = require('../../components/titles'); */; +var __prepSelect_721 = _$select_664.prepSelect; +var __clearSelect_721 = _$select_664.clearSelect; +/* removed: var _$setCursor_621 = require('../../lib/setcursor'); */; -var __MID_SHIFT_659 = _$alignment_511.MID_SHIFT; +var __MID_SHIFT_721 = _$alignment_573.MID_SHIFT; -var ____659 = _$lib_539._; -var deg2rad = _$lib_539.deg2rad; -var rad2deg = _$lib_539.rad2deg; -var wrap360 = _$lib_539.wrap360; -var __wrap180_659 = _$lib_539.wrap180; +var ____721 = _$lib_601._; +var deg2rad = _$lib_601.deg2rad; +var rad2deg = _$lib_601.rad2deg; +var wrap360 = _$lib_601.wrap360; +var __wrap180_721 = _$lib_601.wrap180; -var __setConvertAngular_659 = _$helpers_649.setConvertAngular; -/* removed: var _$constants_648 = require('./constants'); */; +var __setConvertAngular_721 = _$helpers_711.setConvertAngular; +/* removed: var _$constants_710 = require('./constants'); */; -function __Polar_659(gd, id) { +function __Polar_721(gd, id) { this.id = id; this.gd = gd; @@ -172869,13 +175044,13 @@ function __Polar_659(gd, id) { this.angularTickLayout = null; } -var __proto_659 = __Polar_659.prototype; +var __proto_721 = __Polar_721.prototype; -var _$createPolar_659 = function createPolar(gd, id) { - return new __Polar_659(gd, id); +var _$createPolar_721 = function createPolar(gd, id) { + return new __Polar_721(gd, id); }; -__proto_659.plot = function(polarCalcData, fullLayout) { +__proto_721.plot = function(polarCalcData, fullLayout) { var _this = this; var polarLayout = fullLayout[_this.id]; @@ -172890,16 +175065,16 @@ __proto_659.plot = function(polarCalcData, fullLayout) { _this.updateLayers(fullLayout, polarLayout); _this.updateLayout(fullLayout, polarLayout); - _$plots_647.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout); + _$plots_709.generalUpdatePerTraceModule(_this.gd, _this, polarCalcData, polarLayout); _this.updateFx(fullLayout, polarLayout); }; -__proto_659.updateLayers = function(fullLayout, polarLayout) { +__proto_721.updateLayers = function(fullLayout, polarLayout) { var _this = this; var layers = _this.layers; var radialLayout = polarLayout.radialaxis; var angularLayout = polarLayout.angularaxis; - var layerNames = _$constants_648.layerNames; + var layerNames = _$constants_710.layerNames; var frontPlotIndex = layerNames.indexOf('frontplot'); var layerData = layerNames.slice(0, frontPlotIndex); @@ -172924,7 +175099,7 @@ __proto_659.updateLayers = function(fullLayout, polarLayout) { join.enter().append('g') .attr('class', function(d) { return 'polarsublayer ' + d;}) .each(function(d) { - var sel = layers[d] = _$d3_127.select(this); + var sel = layers[d] = _$d3_130.select(this); switch(d) { case 'frontplot': @@ -172956,7 +175131,7 @@ __proto_659.updateLayers = function(fullLayout, polarLayout) { join.order(); }; -__proto_659.updateLayout = function(fullLayout, polarLayout) { +__proto_721.updateLayout = function(fullLayout, polarLayout) { var _this = this; var layers = _this.layers; var gs = fullLayout._size; @@ -173024,7 +175199,7 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { range: [sectorBBox[0] * rSpan, sectorBBox[2] * rSpan], domain: xDomain2 }; - _$axes_584.setConvert(xaxis, fullLayout); + _$axes_647.setConvert(xaxis, fullLayout); xaxis.setScale(); var yaxis = _this.yaxis = { @@ -173033,7 +175208,7 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { range: [sectorBBox[1] * rSpan, sectorBBox[3] * rSpan], domain: yDomain2 }; - _$axes_584.setConvert(yaxis, fullLayout); + _$axes_647.setConvert(yaxis, fullLayout); yaxis.setScale(); xaxis.isPtWithinRange = function(d) { return _this.isPtWithinSector(d); }; @@ -173041,13 +175216,13 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { layers.frontplot .attr('transform', strTranslate(xOffset2, yOffset2)) - .call(_$drawing_436.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.circle); + .call(_$drawing_498.setClipUrl, _this._hasClipOnAxisFalse ? null : _this.clipIds.circle); layers.bgcircle.attr({ d: pathSectorClosed(radius, sector), transform: strTranslate(cx, cy) }) - .call(_$color_411.fill, polarLayout.bgcolor); + .call(_$color_473.fill, polarLayout.bgcolor); _this.clipPaths.circle.select('path') .attr('d', pathSectorClosed(radius, sector)) @@ -173058,7 +175233,7 @@ __proto_659.updateLayout = function(fullLayout, polarLayout) { _this.framework.selectAll('.crisp').classed('crisp', 0); }; -__proto_659.updateRadialAxis = function(fullLayout, polarLayout) { +__proto_721.updateRadialAxis = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -173072,7 +175247,7 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { _this.fillViewInitialKey('radialaxis.angle', radialLayout.angle); - var ax = _this.radialAxis = _$lib_539.extendFlat({}, radialLayout, { + var ax = _this.radialAxis = _$lib_601.extendFlat({}, radialLayout, { _axislayer: layers['radial-axis'], _gridlayer: layers['radial-grid'], @@ -173098,7 +175273,7 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { }); setScale(ax, radialLayout, fullLayout); - __doAutoRange_659(ax); + __doAutoRange_721(ax); radialLayout.range = ax.range.slice(); radialLayout._input.range = ax.range.slice(); _this.fillViewInitialKey('radialaxis.range', ax.range.slice()); @@ -173128,7 +175303,7 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { _this.radialTickLayout = newTickLayout; } - _$axes_584.doTicks(gd, ax, true); + _$axes_647.doTicks(gd, ax, true); updateElement(layers['radial-axis'], radialLayout.showticklabels || radialLayout.ticks, { transform: strTranslate(cx, cy) + strRotate(-radialLayout.angle) @@ -173149,10 +175324,10 @@ __proto_659.updateRadialAxis = function(fullLayout, polarLayout) { transform: strTranslate(cx, cy) + strRotate(-radialLayout.angle) }) .attr('stroke-width', radialLayout.linewidth) - .call(_$color_411.stroke, radialLayout.linecolor); + .call(_$color_473.stroke, radialLayout.linecolor); }; -__proto_659.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { +__proto_721.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { var _this = this; var gd = _this.gd; var radius = _this.radius; @@ -173168,17 +175343,17 @@ __proto_659.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { var pad = 0; if(radialLayout.title) { - var h = _$drawing_436.bBox(_this.layers['radial-axis'].node()).height; + var h = _$drawing_498.bBox(_this.layers['radial-axis'].node()).height; var ts = radialLayout.titlefont.size; pad = radialLayout.side === 'counterclockwise' ? -h - ts * 0.4 : h + ts * 0.8; } - _this.layers['radial-axis-title'] = _$titles_504.draw(gd, titleClass, { + _this.layers['radial-axis-title'] = _$titles_566.draw(gd, titleClass, { propContainer: radialLayout, propName: _this.id + '.radialaxis.title', - placeholder: ____659(gd, 'Click to enter radial axis title'), + placeholder: ____721(gd, 'Click to enter radial axis title'), attributes: { x: cx + (radius / 2) * cosa + pad * sina, y: cy - (radius / 2) * sina + pad * cosa, @@ -173188,7 +175363,7 @@ __proto_659.updateRadialAxisTitle = function(fullLayout, polarLayout, _angle) { }); }; -__proto_659.updateAngularAxis = function(fullLayout, polarLayout) { +__proto_721.updateAngularAxis = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -173201,7 +175376,7 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { _this.fillViewInitialKey('angularaxis.rotation', angularLayout.rotation); - var ax = _this.angularAxis = _$lib_539.extendFlat({}, angularLayout, { + var ax = _this.angularAxis = _$lib_601.extendFlat({}, angularLayout, { _axislayer: layers['angular-axis'], _gridlayer: layers['angular-grid'], @@ -173280,7 +175455,7 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { var out = strTranslate(cx + xy[0], cy - xy[1]); // must also rotate ticks, but don't rotate labels and grid lines - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); if(sel && sel.node() && sel.classed('ticks')) { out += strRotate(-rad2deg(rad)); } @@ -173315,7 +175490,7 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { var labelShift = ax._labelShift; var pad = ax._pad; - var offset4tx = d.dy + d.fontSize * __MID_SHIFT_659 - labelShift; + var offset4tx = d.dy + d.fontSize * __MID_SHIFT_721 - labelShift; var offset4tick = -Math.sin(rad) * (labelStandoff + pad + offset4fontsize * d.fontSize); return offset4tx + offset4tick; @@ -173334,17 +175509,17 @@ __proto_659.updateAngularAxis = function(fullLayout, polarLayout) { _this.angularTickLayout = newTickLayout; } - _$axes_584.doTicks(gd, ax, true); + _$axes_647.doTicks(gd, ax, true); updateElement(layers['angular-line'].select('path'), angularLayout.showline, { d: pathSectorClosed(radius, sector), transform: strTranslate(cx, cy) }) .attr('stroke-width', angularLayout.linewidth) - .call(_$color_411.stroke, angularLayout.linecolor); + .call(_$color_473.stroke, angularLayout.linecolor); }; -__proto_659.updateFx = function(fullLayout, polarLayout) { +__proto_721.updateFx = function(fullLayout, polarLayout) { if(!this.gd._context.staticPlot) { this.updateAngularDrag(fullLayout, polarLayout); this.updateRadialDrag(fullLayout, polarLayout); @@ -173352,13 +175527,13 @@ __proto_659.updateFx = function(fullLayout, polarLayout) { } }; -__proto_659.updateMainDrag = function(fullLayout, polarLayout) { +__proto_721.updateMainDrag = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; var zoomlayer = fullLayout._zoomlayer; - var MINZOOM = _$constants_648.MINZOOM; - var OFFEDGE = _$constants_648.OFFEDGE; + var MINZOOM = _$constants_710.MINZOOM; + var OFFEDGE = _$constants_710.OFFEDGE; var radius = _this.radius; var cx = _this.cx; var cy = _this.cy; @@ -173366,9 +175541,9 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { var cyy = _this.cyy; var sector = polarLayout.sector; - var mainDrag = _$dragbox_592.makeDragger(layers, 'path', 'maindrag', 'crosshair'); + var mainDrag = _$dragbox_655.makeDragger(layers, 'path', 'maindrag', 'crosshair'); - _$d3_127.select(mainDrag) + _$d3_130.select(mainDrag) .attr('d', pathSectorClosed(radius, sector)) .attr('transform', strTranslate(cx, cy)); @@ -173408,8 +175583,8 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { } function pathCorner(r, a) { - var clen = _$constants_648.cornerLen; - var chw = _$constants_648.cornerHalfWidth; + var clen = _$constants_710.cornerLen; + var chw = _$constants_710.cornerHalfWidth; if(r === 0) return pathSectorClosed(2 * chw, sector); @@ -173434,12 +175609,12 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { dimmed = false; var polarLayoutNow = gd._fullLayout[_this.id]; - lum = _$tinycolor_352(polarLayoutNow.bgcolor).getLuminance(); + lum = _$tinycolor_414(polarLayoutNow.bgcolor).getLuminance(); - zb = _$dragbox_592.makeZoombox(zoomlayer, lum, cx, cy, path0); + zb = _$dragbox_655.makeZoombox(zoomlayer, lum, cx, cy, path0); zb.attr('fill-rule', 'evenodd'); - corners = _$dragbox_592.makeCorners(zoomlayer, cx, cy); - _$dragbox_592.clearSelect(zoomlayer); + corners = _$dragbox_655.makeCorners(zoomlayer, cx, cy); + __clearSelect_721(zoomlayer); } function zoomMove(dx, dy) { @@ -173483,16 +175658,16 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { zb.attr('d', path1); corners.attr('d', cpath); - _$dragbox_592.transitionZoombox(zb, corners, dimmed, lum); + _$dragbox_655.transitionZoombox(zb, corners, dimmed, lum); dimmed = true; } function zoomDone() { - _$dragbox_592.removeZoombox(gd); + _$dragbox_655.removeZoombox(gd); if(r0 === null || r1 === null) return; - _$dragbox_592.showDoubleClickNotifier(gd); + _$dragbox_655.showDoubleClickNotifier(gd); var radialAxis = _this.radialAxis; var radialRange = radialAxis.range; @@ -173503,7 +175678,7 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { radialRange[0] + r1 * drange / radius ]; - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); } dragOpts.prepFn = function(evt, startX, startY) { @@ -173521,13 +175696,13 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { break; case 'select': case 'lasso': - _$prepSelect_602(evt, startX, startY, dragOpts, dragModeNow); + __prepSelect_721(evt, startX, startY, dragOpts, dragModeNow); break; } }; dragOpts.clickFn = function(numClicks, evt) { - _$dragbox_592.removeZoombox(gd); + _$dragbox_655.removeZoombox(gd); // TODO double once vs twice logic (autorange vs fixed range) if(numClicks === 2) { @@ -173537,27 +175712,27 @@ __proto_659.updateMainDrag = function(fullLayout, polarLayout) { } gd.emit('plotly_doubleclick', null); - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); } - _$fx_453.click(gd, evt, _this.id); + _$fx_515.click(gd, evt, _this.id); }; mainDrag.onmousemove = function(evt) { - _$fx_453.hover(gd, evt, _this.id); + _$fx_515.hover(gd, evt, _this.id); gd._fullLayout._lasthover = mainDrag; gd._fullLayout._hoversubplot = _this.id; }; mainDrag.onmouseout = function(evt) { if(gd._dragging) return; - _$dragelement_433.unhover(gd, evt); + _$dragelement_495.unhover(gd, evt); }; - _$dragelement_433.init(dragOpts); + _$dragelement_495.init(dragOpts); }; -__proto_659.updateRadialDrag = function(fullLayout, polarLayout) { +__proto_721.updateRadialDrag = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -173569,17 +175744,17 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { var angle0 = deg2rad(radialLayout.angle); var range0 = radialAxis.range.slice(); var drange = range0[1] - range0[0]; - var bl = _$constants_648.radialDragBoxSize; + var bl = _$constants_710.radialDragBoxSize; var bl2 = bl / 2; if(!radialLayout.visible) return; - var radialDrag = _$dragbox_592.makeRectDragger(layers, 'radialdrag', 'crosshair', -bl2, -bl2, bl, bl); + var radialDrag = _$dragbox_655.makeRectDragger(layers, 'radialdrag', 'crosshair', -bl2, -bl2, bl, bl); var dragOpts = {element: radialDrag, gd: gd}; var tx = cx + (radius + bl2) * Math.cos(angle0); var ty = cy - (radius + bl2) * Math.sin(angle0); - _$d3_127.select(radialDrag) + _$d3_130.select(radialDrag) .attr('transform', strTranslate(tx, ty)); // move function (either rotate or re-range flavor) @@ -173595,7 +175770,7 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { } else { var dvec = [dx, -dy]; var rvec = [Math.cos(angle0), Math.sin(angle0)]; - var comp = Math.abs(_$lib_539.dot(dvec, rvec) / Math.sqrt(_$lib_539.dot(dvec, dvec))); + var comp = Math.abs(_$lib_601.dot(dvec, rvec) / Math.sqrt(_$lib_601.dot(dvec, dvec))); // mostly perpendicular motions rotate, // mostly parallel motions re-range @@ -173607,9 +175782,9 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { function doneFn() { if(angle1 !== null) { - _$registry_668.call('relayout', gd, _this.id + '.radialaxis.angle', angle1); + _$registry_731.call('relayout', gd, _this.id + '.radialaxis.angle', angle1); } else if(rng1 !== null) { - _$registry_668.call('relayout', gd, _this.id + '.radialaxis.range[1]', rng1); + _$registry_731.call('relayout', gd, _this.id + '.radialaxis.range[1]', rng1); } } @@ -173630,14 +175805,14 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { function rerangeMove(dx, dy) { // project (dx, dy) unto unit radial axis vector - var dr = _$lib_539.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]); + var dr = _$lib_601.dot([dx, -dy], [Math.cos(angle0), Math.sin(angle0)]); var rprime = range0[1] - drange * dr / radius * 0.75; // make sure new range[1] does not change the range[0] -> range[1] sign if((drange > 0) !== (rprime > range0[0])) return; rng1 = radialAxis.range[1] = rprime; - _$axes_584.doTicks(gd, _this.radialAxis, true); + _$axes_647.doTicks(gd, _this.radialAxis, true); layers['radial-grid'] .attr('transform', strTranslate(cx, cy)) .selectAll('path').attr('transform', null); @@ -173651,13 +175826,13 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { for(var k in _this.traceHash) { var moduleCalcData = _this.traceHash[k]; - var moduleCalcDataVisible = _$lib_539.filterVisible(moduleCalcData); + var moduleCalcDataVisible = _$lib_601.filterVisible(moduleCalcData); var _module = moduleCalcData[0][0].trace._module; var polarLayoutNow = gd._fullLayout[_this.id]; _module.plot(gd, _this, moduleCalcDataVisible, polarLayoutNow); - if(!_$registry_668.traceIs(k, 'gl')) { + if(!_$registry_731.traceIs(k, 'gl')) { for(var i = 0; i < moduleCalcDataVisible.length; i++) { _module.style(gd, moduleCalcDataVisible[i]); } @@ -173673,21 +175848,21 @@ __proto_659.updateRadialDrag = function(fullLayout, polarLayout) { dragOpts.moveFn = moveFn; dragOpts.doneFn = doneFn; - _$dragbox_592.clearSelect(fullLayout._zoomlayer); + __clearSelect_721(fullLayout._zoomlayer); }; dragOpts.clampFn = function(dx, dy) { - if(Math.sqrt(dx * dx + dy * dy) < _$constants_648.MINDRAG) { + if(Math.sqrt(dx * dx + dy * dy) < _$constants_710.MINDRAG) { dx = 0; dy = 0; } return [dx, dy]; }; - _$dragelement_433.init(dragOpts); + _$dragelement_495.init(dragOpts); }; -__proto_659.updateAngularDrag = function(fullLayout, polarLayout) { +__proto_721.updateAngularDrag = function(fullLayout, polarLayout) { var _this = this; var gd = _this.gd; var layers = _this.layers; @@ -173697,15 +175872,15 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { var cxx = _this.cxx; var cyy = _this.cyy; var sector = polarLayout.sector; - var dbs = _$constants_648.angularDragBoxSize; + var dbs = _$constants_710.angularDragBoxSize; - var angularDrag = _$dragbox_592.makeDragger(layers, 'path', 'angulardrag', 'move'); + var angularDrag = _$dragbox_655.makeDragger(layers, 'path', 'angulardrag', 'move'); var dragOpts = {element: angularDrag, gd: gd}; - _$d3_127.select(angularDrag) + _$d3_130.select(angularDrag) .attr('d', pathAnnulus(radius, radius + dbs, sector)) .attr('transform', strTranslate(cx, cy)) - .call(_$setCursor_558, 'move'); + .call(_$setCursor_621, 'move'); function xy2a(x, y) { return Math.atan2(cyy + dbs - y, x - cxx - dbs); @@ -173742,20 +175917,20 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { // 'un-rotate' marker and text points scatterPoints.each(function() { - var sel = _$d3_127.select(this); - var xy = _$drawing_436.getTranslate(sel); + var sel = _$d3_130.select(this); + var xy = _$drawing_498.getTranslate(sel); sel.attr('transform', strTranslate(xy.x, xy.y) + strRotate([da])); }); scatterTextPoints.each(function() { - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var tx = sel.select('text'); - var xy = _$drawing_436.getTranslate(sel); + var xy = _$drawing_498.getTranslate(sel); // N.B rotate -> translate ordering matters sel.attr('transform', strRotate([da, tx.attr('x'), tx.attr('y')]) + strTranslate(xy.x, xy.y)); }); var angularAxis = _this.angularAxis; - angularAxis.rotation = __wrap180_659(rot1); + angularAxis.rotation = __wrap180_721(rot1); if(angularAxis.type === 'linear' && !isFullCircle(sector)) { angularAxis.range = sector0 @@ -173764,19 +175939,19 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { .map(rad2deg); } - __setConvertAngular_659(angularAxis); - _$axes_584.doTicks(gd, angularAxis, true); + __setConvertAngular_721(angularAxis); + _$axes_647.doTicks(gd, angularAxis, true); if(_this._hasClipOnAxisFalse && !isFullCircle(sector)) { // mutate sector to trick isPtWithinSector _this.sector = [sector0[0] - da, sector0[1] - da]; - scatterTraces.call(_$drawing_436.hideOutsideRangePoints, _this); + scatterTraces.call(_$drawing_498.hideOutsideRangePoints, _this); } for(var k in _this.traceHash) { - if(_$registry_668.traceIs(k, 'gl')) { + if(_$registry_731.traceIs(k, 'gl')) { var moduleCalcData = _this.traceHash[k]; - var moduleCalcDataVisible = _$lib_539.filterVisible(moduleCalcData); + var moduleCalcDataVisible = _$lib_601.filterVisible(moduleCalcData); var _module = moduleCalcData[0][0].trace._module; var polarLayoutNow = gd._fullLayout[_this.id]; @@ -173789,7 +175964,7 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { scatterTextPoints.select('text').attr('transform', null); var updateObj = {}; updateObj[_this.id + '.angularaxis.rotation'] = rot1; - _$registry_668.call('relayout', gd, updateObj); + _$registry_731.call('relayout', gd, updateObj); } dragOpts.prepFn = function(evt, startX, startY) { @@ -173805,13 +175980,13 @@ __proto_659.updateAngularDrag = function(fullLayout, polarLayout) { dragOpts.moveFn = moveFn; dragOpts.doneFn = doneFn; - _$dragbox_592.clearSelect(fullLayout._zoomlayer); + __clearSelect_721(fullLayout._zoomlayer); }; - _$dragelement_433.init(dragOpts); + _$dragelement_495.init(dragOpts); }; -__proto_659.isPtWithinSector = function(d) { +__proto_721.isPtWithinSector = function(d) { var sector = this.sector; var radialAxis = this.radialAxis; var radialRange = radialAxis.range; @@ -173842,14 +176017,14 @@ __proto_659.isPtWithinSector = function(d) { ); }; -__proto_659.fillViewInitialKey = function(key, val) { +__proto_721.fillViewInitialKey = function(key, val) { if(!(key in this.viewInitial)) { this.viewInitial[key] = val; } }; function setScale(ax, axLayout, fullLayout) { - _$axes_584.setConvert(ax, fullLayout); + _$axes_647.setConvert(ax, fullLayout); // _min and _max are filled in during Axes.expand // and cleared during Axes.setConvert @@ -173922,7 +176097,7 @@ function computeSectorBBox(sector) { function pathSector(r, sector) { if(isFullCircle(sector)) { - return _$drawing_436.symbolFuncs[0](r); + return _$drawing_498.symbolFuncs[0](r); } var xs = r * Math.cos(deg2rad(sector[0])); @@ -174005,17 +176180,17 @@ function strRotate(angle) { // because Math.sign(Math.cos(Math.PI / 2)) === 1 // oh javascript ;) -function __sign_659(v) { +function __sign_721(v) { return Math.abs(v) < 1e-10 ? 0 : v > 0 ? 1 : -1; } function signCos(v) { - return __sign_659(Math.cos(v)); + return __sign_721(Math.cos(v)); } function signSin(v) { - return __sign_659(Math.sin(v)); + return __sign_721(Math.sin(v)); } /** @@ -174028,37 +176203,37 @@ function signSin(v) { 'use strict'; -var __getSubplotCalcData_650 = _$get_data_621.getSubplotCalcData; -var __counterRegex_650 = _$lib_539.counterRegex; +var __getSubplotCalcData_712 = _$get_data_683.getSubplotCalcData; +var __counterRegex_712 = _$lib_601.counterRegex; -/* removed: var _$createPolar_659 = require('./polar'); */; -/* removed: var _$constants_648 = require('./constants'); */; +/* removed: var _$createPolar_721 = require('./polar'); */; +/* removed: var _$constants_710 = require('./constants'); */; -var attr = _$constants_648.attr; -var __name_650 = _$constants_648.name; -var counter = __counterRegex_650(__name_650); +var attr = _$constants_710.attr; +var __name_712 = _$constants_710.name; +var counter = __counterRegex_712(__name_712); -var __attributes_650 = {}; -__attributes_650[attr] = { +var __attributes_712 = {}; +__attributes_712[attr] = { valType: 'subplotid', - dflt: __name_650, + dflt: __name_712, editType: 'calc', }; -function __plot_650(gd) { +function __plot_712(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; - var subplotIds = fullLayout._subplots[__name_650]; + var subplotIds = fullLayout._subplots[__name_712]; for(var i = 0; i < subplotIds.length; i++) { var id = subplotIds[i]; - var subplotCalcData = __getSubplotCalcData_650(calcData, __name_650, id); + var subplotCalcData = __getSubplotCalcData_712(calcData, __name_712, id); var subplot = fullLayout[id]._subplot; if(!subplot) { - subplot = _$createPolar_659(gd, id); + subplot = _$createPolar_721(gd, id); fullLayout[id]._subplot = subplot; } @@ -174067,7 +176242,7 @@ function __plot_650(gd) { } function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldIds = oldFullLayout._subplots[__name_650] || []; + var oldIds = oldFullLayout._subplots[__name_712] || []; for(var i = 0; i < oldIds.length; i++) { var id = oldIds[i]; @@ -174084,18 +176259,18 @@ function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) { } } -var _$polar_650 = { +var _$polar_712 = { attr: attr, - name: __name_650, - idRoot: __name_650, + name: __name_712, + idRoot: __name_712, idRegex: counter, attrRegex: counter, - attributes: __attributes_650, - layoutAttributes: _$layout_attributes_651, - supplyLayoutDefaults: _$supplyLayoutDefaults_652, - plot: __plot_650, + attributes: __attributes_712, + layoutAttributes: _$layout_attributes_713, + supplyLayoutDefaults: _$supplyLayoutDefaults_714, + plot: __plot_712, clean: clean, - toSVG: _$cartesian_595.toSVG + toSVG: _$cartesian_658.toSVG }; /** @@ -174108,13 +176283,13 @@ var _$polar_650 = { 'use strict'; -var __extendFlat_920 = _$extend_528.extendFlat; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -var __lineAttrs_920 = _$attributes_862.line; +var __extendFlat_987 = _$extend_590.extendFlat; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +var __lineAttrs_987 = _$attributes_927.line; -var _$attributes_920 = { - mode: _$attributes_862.mode, +var _$attributes_987 = { + mode: _$attributes_927.mode, r: { valType: 'data_array', @@ -174137,45 +176312,45 @@ var _$attributes_920 = { }, - text: _$attributes_862.text, - hovertext: _$attributes_862.hovertext, + text: _$attributes_927.text, + hovertext: _$attributes_927.hovertext, line: { - color: __lineAttrs_920.color, - width: __lineAttrs_920.width, - dash: __lineAttrs_920.dash, - shape: __extendFlat_920({}, __lineAttrs_920.shape, { + color: __lineAttrs_987.color, + width: __lineAttrs_987.width, + dash: __lineAttrs_987.dash, + shape: __extendFlat_987({}, __lineAttrs_987.shape, { values: ['linear', 'spline'] }), - smoothing: __lineAttrs_920.smoothing, + smoothing: __lineAttrs_987.smoothing, editType: 'calc' }, - connectgaps: _$attributes_862.connectgaps, + connectgaps: _$attributes_927.connectgaps, - marker: _$attributes_862.marker, - cliponaxis: __extendFlat_920({}, _$attributes_862.cliponaxis, {dflt: false}), + marker: _$attributes_927.marker, + cliponaxis: __extendFlat_987({}, _$attributes_927.cliponaxis, {dflt: false}), - textposition: _$attributes_862.textposition, - textfont: _$attributes_862.textfont, + textposition: _$attributes_927.textposition, + textfont: _$attributes_927.textfont, - fill: __extendFlat_920({}, _$attributes_862.fill, { + fill: __extendFlat_987({}, _$attributes_927.fill, { values: ['none', 'toself', 'tonext'], }), - fillcolor: _$attributes_862.fillcolor, + fillcolor: _$attributes_927.fillcolor, // TODO error bars // https://stackoverflow.com/a/26597487/4068492 // error_x (error_r, error_theta) // error_y - hoverinfo: __extendFlat_920({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_987({}, _$attributes_644.hoverinfo, { flags: ['r', 'theta', 'text', 'name'] }), - hoveron: _$attributes_862.hoveron, + hoveron: _$attributes_927.hoveron, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected }; /** @@ -174189,17 +176364,17 @@ var _$attributes_920 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; -var __BADNUM_921 = _$numerical_517.BADNUM; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; +var __BADNUM_988 = _$numerical_578.BADNUM; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_921 = _$calc_863.calcMarkerSize; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_988 = _$calc_928.calcMarkerSize; -var _$calc_921 = function calc(gd, trace) { +var _$calc_988 = function calc(gd, trace) { var fullLayout = gd._fullLayout; var subplotId = trace.subplot; var radialAxis = fullLayout[subplotId].radialaxis; @@ -174218,21 +176393,21 @@ var _$calc_921 = function calc(gd, trace) { var theta = thetaArray[i]; var cdi = cd[i] = {}; - if(_$fastIsnumeric_139(r) && _$fastIsnumeric_139(theta)) { + if(_$fastIsnumeric_196(r) && _$fastIsnumeric_196(theta)) { cdi.r = r; cdi.theta = theta; cdi.rad = c2rad(theta); } else { - cdi.r = __BADNUM_921; + cdi.r = __BADNUM_988; } } - var ppad = __calcMarkerSize_921(trace, len); - _$axes_584.expand(radialAxis, rArray, {ppad: ppad}); + var ppad = __calcMarkerSize_988(trace, len); + _$axes_647.expand(radialAxis, rArray, {ppad: ppad}); - _$calcMarkerColorscale_867(trace); - _$arraysToCalcdata_861(cd, trace); - _$calcSelection_864(cd, trace); + _$calcMarkerColorscale_932(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcSelection_929(cd, trace); return cd; }; @@ -174247,21 +176422,21 @@ var _$calc_921 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; -var PTS_LINESONLY = _$constants_868.PTS_LINESONLY; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; +var PTS_LINESONLY = _$constants_933.PTS_LINESONLY; -/* removed: var _$attributes_920 = require('./attributes'); */; +/* removed: var _$attributes_987 = require('./attributes'); */; -var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_989 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_920, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_987, attr, dflt); } var r = coerce('r'); @@ -174280,23 +176455,23 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('hovertext'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -174305,8 +176480,8 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -174314,7 +176489,7 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -174327,12 +176502,12 @@ var _$supplyDefaults_922 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$hoverPoints_873 = require('../scatter/hover'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$hoverPoints_938 = require('../scatter/hover'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -function __hoverPoints_923(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_873(pointData, xval, yval, hovermode); +function __hoverPoints_990(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_938(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -174370,13 +176545,13 @@ function makeHoverPointText(cdi, trace, subplot) { // show theta value in unit of angular axis var theta; if(angularAxis.type === 'linear' && trace.thetaunit !== angularAxis.thetaunit) { - theta = angularAxis.thetaunit === 'degrees' ? _$lib_539.rad2deg(rad) : rad; + theta = angularAxis.thetaunit === 'degrees' ? _$lib_601.rad2deg(rad) : rad; } else { theta = cdi.theta; } function textPart(ax, val) { - text.push(ax._hovertitle + ': ' + _$axes_584.tickText(ax, val, 'hover').text); + text.push(ax._hovertitle + ': ' + _$axes_647.tickText(ax, val, 'hover').text); } if(parts.indexOf('all') !== -1) parts = ['r', 'theta']; @@ -174386,8 +176561,8 @@ function makeHoverPointText(cdi, trace, subplot) { return text.join('
'); } -var _$hover_923 = { - hoverPoints: __hoverPoints_923, +var _$hover_990 = { + hoverPoints: __hoverPoints_990, makeHoverPointText: makeHoverPointText }; @@ -174401,10 +176576,10 @@ var _$hover_923 = { 'use strict'; -/* removed: var _$plot_881 = require('../scatter/plot'); */; -var __BADNUM_925 = _$numerical_517.BADNUM; +/* removed: var _$plot_946 = require('../scatter/plot'); */; +var __BADNUM_992 = _$numerical_578.BADNUM; -var _$plot_925 = function plot(gd, subplot, moduleCalcData) { +var _$plot_992 = function plot(gd, subplot, moduleCalcData) { var i, j; var plotinfo = { @@ -174432,7 +176607,7 @@ var _$plot_925 = function plot(gd, subplot, moduleCalcData) { var cdi = moduleCalcData[i][j]; var r = cdi.r; - if(r !== __BADNUM_925) { + if(r !== __BADNUM_992) { // convert to 'r' data to fit with mocked polar x/y axis // which are always `type: 'linear'` var rr = radialAxis.c2r(r) - radialRange[0]; @@ -174448,12 +176623,12 @@ var _$plot_925 = function plot(gd, subplot, moduleCalcData) { } } - cdi.x = __BADNUM_925; - cdi.y = __BADNUM_925; + cdi.x = __BADNUM_992; + cdi.y = __BADNUM_992; } } - _$plot_881(gd, plotinfo, moduleCalcData); + _$plot_946(gd, plotinfo, moduleCalcData); }; /** @@ -174466,19 +176641,19 @@ var _$plot_925 = function plot(gd, subplot, moduleCalcData) { 'use strict'; -var _$scatterpolar_924 = { +var _$scatterpolar_991 = { moduleType: 'trace', name: 'scatterpolar', - basePlotModule: _$polar_650, + basePlotModule: _$polar_712, categories: ['polar', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], - attributes: _$attributes_920, - supplyDefaults: _$supplyDefaults_922, - calc: _$calc_921, - plot: _$plot_925, - style: _$style_883.style, - hoverPoints: _$hover_923.hoverPoints, - selectPoints: _$selectPoints_882, + attributes: _$attributes_987, + supplyDefaults: _$supplyDefaults_989, + calc: _$calc_988, + plot: _$plot_992, + style: _$style_948.style, + hoverPoints: _$hover_990.hoverPoints, + selectPoints: _$selectPoints_947, meta: { @@ -174496,7 +176671,7 @@ var _$scatterpolar_924 = { 'use strict'; -var _$scatterpolar_32 = _$scatterpolar_924; +var _$scatterpolar_32 = _$scatterpolar_991; /** * Copyright 2012-2018, Plotly, Inc. @@ -174508,32 +176683,32 @@ var _$scatterpolar_32 = _$scatterpolar_924; 'use strict'; -/* removed: var _$attributes_920 = require('../scatterpolar/attributes'); */; -/* removed: var _$attributes_909 = require('../scattergl/attributes'); */; +/* removed: var _$attributes_987 = require('../scatterpolar/attributes'); */; +/* removed: var _$attributes_974 = require('../scattergl/attributes'); */; -var _$attributes_926 = { - mode: _$attributes_920.mode, - r: _$attributes_920.r, - theta: _$attributes_920.theta, - thetaunit: _$attributes_920.thetaunit, +var _$attributes_993 = { + mode: _$attributes_987.mode, + r: _$attributes_987.r, + theta: _$attributes_987.theta, + thetaunit: _$attributes_987.thetaunit, - text: _$attributes_920.text, + text: _$attributes_987.text, // no hovertext - line: _$attributes_909.line, - connectgaps: _$attributes_909.connectgaps, + line: _$attributes_974.line, + connectgaps: _$attributes_974.connectgaps, - marker: _$attributes_909.marker, + marker: _$attributes_974.marker, // no cliponaxis - fill: _$attributes_909.fill, - fillcolor: _$attributes_909.fillcolor, + fill: _$attributes_974.fill, + fillcolor: _$attributes_974.fillcolor, - hoverinfo: _$attributes_920.hoverinfo, - hoveron: _$attributes_920.hoveron, + hoverinfo: _$attributes_987.hoverinfo, + hoveron: _$attributes_987.hoveron, - selected: _$attributes_920.selected, - unselected: _$attributes_920.unselected + selected: _$attributes_987.selected, + unselected: _$attributes_987.unselected }; /** @@ -174546,19 +176721,19 @@ var _$attributes_926 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; -var __PTS_LINESONLY_927 = _$constants_868.PTS_LINESONLY; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; +var __PTS_LINESONLY_994 = _$constants_933.PTS_LINESONLY; -/* removed: var _$attributes_926 = require('./attributes'); */; +/* removed: var _$attributes_993 = require('./attributes'); */; -var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_994 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_926, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_993, attr, dflt); } var r = coerce('r'); @@ -174573,24 +176748,24 @@ var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultCol traceOut._length = len; coerce('thetaunit'); - coerce('mode', len < __PTS_LINESONLY_927 ? 'lines+markers' : 'lines'); + coerce('mode', len < __PTS_LINESONLY_994 ? 'lines+markers' : 'lines'); coerce('text'); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); coerce('connectgaps'); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce); dfltHoverOn.push('points'); } coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -174598,7 +176773,7 @@ var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -174611,16 +176786,18 @@ var _$supplyDefaults_927 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$KDTree_252 = require('kdgrass'); */; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$pointCluster_353 = require('point-cluster'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$scattergl_911 = require('../scattergl'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -var __makeHoverPointText_928 = _$hover_923.makeHoverPointText; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; +/* removed: var _$scattergl_978 = require('../scattergl'); */; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +var __makeHoverPointText_995 = _$hover_990.makeHoverPointText; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; -function __calc_928(container, trace) { +var __TOO_MANY_POINTS_995 = _$constants_975.TOO_MANY_POINTS; + +function __calc_995(container, trace) { var layout = container._fullLayout; var subplotId = trace.subplot; var radialAxis = layout[subplotId].radialaxis; @@ -174632,28 +176809,28 @@ function __calc_928(container, trace) { if(trace._length < rArray.length) rArray = rArray.slice(0, trace._length); if(trace._length < thetaArray.length) thetaArray = thetaArray.slice(0, trace._length); - _$calcMarkerColorscale_867(trace); + _$calcMarkerColorscale_932(trace); stash.r = rArray; stash.theta = thetaArray; - _$axes_584.expand(radialAxis, rArray, {tozero: true}); + _$axes_647.expand(radialAxis, rArray, {tozero: true}); if(angularAxis.type !== 'linear') { angularAxis.autorange = true; - _$axes_584.expand(angularAxis, thetaArray); + _$axes_647.expand(angularAxis, thetaArray); delete angularAxis.autorange; } return [{x: false, y: false, t: stash, trace: trace}]; } -function __plot_928(container, subplot, cdata) { +function __plot_995(container, subplot, cdata) { var radialAxis = subplot.radialAxis; var angularAxis = subplot.angularAxis; var rRange = radialAxis.range; - var scene = _$scattergl_911.sceneUpdate(container, subplot); + var scene = _$scattergl_978.sceneUpdate(container, subplot); scene.clear(); cdata.forEach(function(cdscatter, traceIndex) { @@ -174690,7 +176867,7 @@ function __plot_928(container, subplot, cdata) { r = subRArray[i]; theta = subThetaArray[i]; - if(_$fastIsnumeric_139(r) && _$fastIsnumeric_139(theta) && r >= 0) { + if(_$fastIsnumeric_196(r) && _$fastIsnumeric_196(theta) && r >= 0) { rr = radialAxis.c2r(r) - rRange[0]; rad = c2rad(theta); @@ -174701,7 +176878,7 @@ function __plot_928(container, subplot, cdata) { } } - var options = _$scattergl_911.sceneOptions(container, subplot, trace, positions); + var options = _$scattergl_978.sceneOptions(container, subplot, trace, positions); // set flags to create scene renderers if(options.fill && !scene.fill2d) scene.fill2d = true; @@ -174709,8 +176886,15 @@ function __plot_928(container, subplot, cdata) { if(options.line && !scene.line2d) scene.line2d = true; if((options.errorX || options.errorY) && !scene.error2d) scene.error2d = true; + stash.tree = _$pointCluster_353(positions); + + // FIXME: see scattergl.js#109 + if(options.marker && count >= __TOO_MANY_POINTS_995) { + options.marker.cluster = stash.tree; + } + // bring positions to selected/unselected options - if(_$subtypes_884.hasMarkers(trace)) { + if(_$subtypes_949.hasMarkers(trace)) { options.selected.positions = options.unselected.positions = options.marker.positions; } @@ -174725,7 +176909,7 @@ function __plot_928(container, subplot, cdata) { scene.count = cdata.length; // stash scene ref - stash.scene = scene; + stash._scene = scene; stash.index = traceIndex; stash.x = x; stash.y = y; @@ -174735,19 +176919,18 @@ function __plot_928(container, subplot, cdata) { stash.theta = thetaArray; stash.positions = positions; stash.count = count; - stash.tree = _$KDTree_252(positions, 512); }); - return _$scattergl_911.plot(container, subplot, cdata); + return _$scattergl_978.plot(container, subplot, cdata); } -function __hoverPoints_928(pointData, xval, yval, hovermode) { +function __hoverPoints_995(pointData, xval, yval, hovermode) { var cd = pointData.cd; var stash = cd[0].t; var rArray = stash.r; var thetaArray = stash.theta; - var scatterPointData = _$scattergl_911.hoverPoints(pointData, xval, yval, hovermode); + var scatterPointData = _$scattergl_978.hoverPoints(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -174770,25 +176953,25 @@ function __hoverPoints_928(pointData, xval, yval, hovermode) { newPointData.xLabelVal = undefined; newPointData.yLabelVal = undefined; - newPointData.extraText = __makeHoverPointText_928(cdi, trace, subplot); + newPointData.extraText = __makeHoverPointText_995(cdi, trace, subplot); return scatterPointData; } -var _$scatterpolargl_928 = { +var _$scatterpolargl_995 = { moduleType: 'trace', name: 'scatterpolargl', - basePlotModule: _$polar_650, + basePlotModule: _$polar_712, categories: ['gl', 'regl', 'polar', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], - attributes: _$attributes_926, - supplyDefaults: _$supplyDefaults_927, + attributes: _$attributes_993, + supplyDefaults: _$supplyDefaults_994, - calc: __calc_928, - plot: __plot_928, - hoverPoints: __hoverPoints_928, - style: _$scattergl_911.style, - selectPoints: _$scattergl_911.selectPoints, + calc: __calc_995, + plot: __plot_995, + hoverPoints: __hoverPoints_995, + style: _$scattergl_978.style, + selectPoints: _$scattergl_978.selectPoints, meta: { @@ -174806,7 +176989,7 @@ var _$scatterpolargl_928 = { 'use strict'; -var _$scatterpolargl_33 = _$scatterpolargl_928; +var _$scatterpolargl_33 = _$scatterpolargl_995; /** * Copyright 2012-2018, Plotly, Inc. @@ -174819,7 +177002,7 @@ var _$scatterpolargl_33 = _$scatterpolargl_928; 'use strict'; -var _$attributes_662 = { +var _$attributes_725 = { subplot: { valType: 'subplotid', @@ -174840,46 +177023,46 @@ var _$attributes_662 = { 'use strict'; -/* removed: var _$layout_attributes_596 = require('../../cartesian/layout_attributes'); */; -var __extendFlat_663 = _$extend_528.extendFlat; +/* removed: var _$layout_attributes_659 = require('../../cartesian/layout_attributes'); */; +var __extendFlat_726 = _$extend_590.extendFlat; -var _$axis_attributes_663 = { - title: _$layout_attributes_596.title, - titlefont: _$layout_attributes_596.titlefont, - color: _$layout_attributes_596.color, +var _$axis_attributes_726 = { + title: _$layout_attributes_659.title, + titlefont: _$layout_attributes_659.titlefont, + color: _$layout_attributes_659.color, // ticks - tickmode: _$layout_attributes_596.tickmode, - nticks: __extendFlat_663({}, _$layout_attributes_596.nticks, {dflt: 6, min: 1}), - tick0: _$layout_attributes_596.tick0, - dtick: _$layout_attributes_596.dtick, - tickvals: _$layout_attributes_596.tickvals, - ticktext: _$layout_attributes_596.ticktext, - ticks: _$layout_attributes_596.ticks, - ticklen: _$layout_attributes_596.ticklen, - tickwidth: _$layout_attributes_596.tickwidth, - tickcolor: _$layout_attributes_596.tickcolor, - showticklabels: _$layout_attributes_596.showticklabels, - showtickprefix: _$layout_attributes_596.showtickprefix, - tickprefix: _$layout_attributes_596.tickprefix, - showticksuffix: _$layout_attributes_596.showticksuffix, - ticksuffix: _$layout_attributes_596.ticksuffix, - showexponent: _$layout_attributes_596.showexponent, - exponentformat: _$layout_attributes_596.exponentformat, - separatethousands: _$layout_attributes_596.separatethousands, - tickfont: _$layout_attributes_596.tickfont, - tickangle: _$layout_attributes_596.tickangle, - tickformat: _$layout_attributes_596.tickformat, - tickformatstops: _$layout_attributes_596.tickformatstops, - hoverformat: _$layout_attributes_596.hoverformat, + tickmode: _$layout_attributes_659.tickmode, + nticks: __extendFlat_726({}, _$layout_attributes_659.nticks, {dflt: 6, min: 1}), + tick0: _$layout_attributes_659.tick0, + dtick: _$layout_attributes_659.dtick, + tickvals: _$layout_attributes_659.tickvals, + ticktext: _$layout_attributes_659.ticktext, + ticks: _$layout_attributes_659.ticks, + ticklen: _$layout_attributes_659.ticklen, + tickwidth: _$layout_attributes_659.tickwidth, + tickcolor: _$layout_attributes_659.tickcolor, + showticklabels: _$layout_attributes_659.showticklabels, + showtickprefix: _$layout_attributes_659.showtickprefix, + tickprefix: _$layout_attributes_659.tickprefix, + showticksuffix: _$layout_attributes_659.showticksuffix, + ticksuffix: _$layout_attributes_659.ticksuffix, + showexponent: _$layout_attributes_659.showexponent, + exponentformat: _$layout_attributes_659.exponentformat, + separatethousands: _$layout_attributes_659.separatethousands, + tickfont: _$layout_attributes_659.tickfont, + tickangle: _$layout_attributes_659.tickangle, + tickformat: _$layout_attributes_659.tickformat, + tickformatstops: _$layout_attributes_659.tickformatstops, + hoverformat: _$layout_attributes_659.hoverformat, // lines and grids - showline: __extendFlat_663({}, _$layout_attributes_596.showline, {dflt: true}), - linecolor: _$layout_attributes_596.linecolor, - linewidth: _$layout_attributes_596.linewidth, - showgrid: __extendFlat_663({}, _$layout_attributes_596.showgrid, {dflt: true}), - gridcolor: _$layout_attributes_596.gridcolor, - gridwidth: _$layout_attributes_596.gridwidth, - layer: _$layout_attributes_596.layer, + showline: __extendFlat_726({}, _$layout_attributes_659.showline, {dflt: true}), + linecolor: _$layout_attributes_659.linecolor, + linewidth: _$layout_attributes_659.linewidth, + showgrid: __extendFlat_726({}, _$layout_attributes_659.showgrid, {dflt: true}), + gridcolor: _$layout_attributes_659.gridcolor, + gridwidth: _$layout_attributes_659.gridwidth, + layer: _$layout_attributes_659.layer, // range min: { valType: 'number', @@ -174900,16 +177083,16 @@ var _$axis_attributes_663 = { 'use strict'; -/* removed: var _$lib_539 = require('../../../lib'); */; -/* removed: var _$axis_attributes_663 = require('./axis_attributes'); */; -/* removed: var _$handleTickLabelDefaults_604 = require('../../cartesian/tick_label_defaults'); */; -/* removed: var _$handleTickDefaults_605 = require('../../cartesian/tick_mark_defaults'); */; -/* removed: var _$handleTickValueDefaults_606 = require('../../cartesian/tick_value_defaults'); */; -/* removed: var _$handleLineGridDefaults_598 = require('../../cartesian/line_grid_defaults'); */; +/* removed: var _$lib_601 = require('../../../lib'); */; +/* removed: var _$axis_attributes_726 = require('./axis_attributes'); */; +/* removed: var _$handleTickLabelDefaults_666 = require('../../cartesian/tick_label_defaults'); */; +/* removed: var _$handleTickDefaults_667 = require('../../cartesian/tick_mark_defaults'); */; +/* removed: var _$handleTickValueDefaults_668 = require('../../cartesian/tick_value_defaults'); */; +/* removed: var _$handleLineGridDefaults_661 = require('../../cartesian/line_grid_defaults'); */; -var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, containerOut, options) { +var _$supplyLayoutDefaults_727 = function supplyLayoutDefaults(containerIn, containerOut, options) { function coerce(attr, dflt) { - return _$lib_539.coerce(containerIn, containerOut, _$axis_attributes_663, attr, dflt); + return _$lib_601.coerce(containerIn, containerOut, _$axis_attributes_726, attr, dflt); } containerOut.type = 'linear'; // no other types allowed for ternary @@ -174926,7 +177109,7 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont var title = coerce('title', dfltTitle); containerOut._hovertitle = title === dfltTitle ? title : letterUpper; - _$lib_539.coerceFont(coerce, 'titlefont', { + _$lib_601.coerceFont(coerce, 'titlefont', { family: options.font.family, size: Math.round(options.font.size * 1.2), color: dfltFontColor @@ -174935,14 +177118,14 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont // range is just set by 'min' - max is determined by the other axes mins coerce('min'); - _$handleTickValueDefaults_606(containerIn, containerOut, coerce, 'linear'); - _$handleTickLabelDefaults_604(containerIn, containerOut, coerce, 'linear', {}); - _$handleTickDefaults_605(containerIn, containerOut, coerce, + _$handleTickValueDefaults_668(containerIn, containerOut, coerce, 'linear'); + _$handleTickLabelDefaults_666(containerIn, containerOut, coerce, 'linear', {}); + _$handleTickDefaults_667(containerIn, containerOut, coerce, { outerTicks: true }); var showTickLabels = coerce('showticklabels'); if(showTickLabels) { - _$lib_539.coerceFont(coerce, 'tickfont', { + _$lib_601.coerceFont(coerce, 'tickfont', { family: options.font.family, size: options.font.size, color: dfltFontColor @@ -174951,7 +177134,7 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont coerce('tickformat'); } - _$handleLineGridDefaults_598(containerIn, containerOut, coerce, { + _$handleLineGridDefaults_661(containerIn, containerOut, coerce, { dfltColor: dfltColor, bgColor: options.bgColor, // default grid color is darker here (60%, vs cartesian default ~91%) @@ -174960,7 +177143,7 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont showLine: true, showGrid: true, noZeroLine: true, - attributes: _$axis_attributes_663 + attributes: _$axis_attributes_726 }); coerce('hoverformat'); @@ -174977,18 +177160,18 @@ var _$supplyLayoutDefaults_664 = function supplyLayoutDefaults(containerIn, cont 'use strict'; -/* removed: var _$attributes_410 = require('../../../components/color/attributes'); */; -var __domainAttrs_666 = _$domain_610.attributes; -/* removed: var _$axis_attributes_663 = require('./axis_attributes'); */; -var __overrideAll_666 = _$edit_types_569.overrideAll; +/* removed: var _$attributes_472 = require('../../../components/color/attributes'); */; +var __domainAttrs_729 = _$domain_672.attributes; +/* removed: var _$axis_attributes_726 = require('./axis_attributes'); */; +var __overrideAll_729 = _$edit_types_632.overrideAll; -var _$layout_attributes_666 = __overrideAll_666({ - domain: __domainAttrs_666({name: 'ternary'}), +var _$layout_attributes_729 = __overrideAll_729({ + domain: __domainAttrs_729({name: 'ternary'}), bgcolor: { valType: 'color', - dflt: _$attributes_410.background, + dflt: _$attributes_472.background, }, sum: { @@ -174998,9 +177181,9 @@ var _$layout_attributes_666 = __overrideAll_666({ min: 0, }, - aaxis: _$axis_attributes_663, - baxis: _$axis_attributes_663, - caxis: _$axis_attributes_663 + aaxis: _$axis_attributes_726, + baxis: _$axis_attributes_726, + caxis: _$axis_attributes_726 }, 'plot', 'from-root'); /** @@ -175014,18 +177197,18 @@ var _$layout_attributes_666 = __overrideAll_666({ 'use strict'; -/* removed: var _$color_411 = require('../../../components/color'); */; +/* removed: var _$color_473 = require('../../../components/color'); */; -/* removed: var _$handleSubplotDefaults_660 = require('../../subplot_defaults'); */; -/* removed: var _$layout_attributes_666 = require('./layout_attributes'); */; -/* removed: var _$supplyLayoutDefaults_664 = require('./axis_defaults'); */; +/* removed: var _$handleSubplotDefaults_723 = require('../../subplot_defaults'); */; +/* removed: var _$layout_attributes_729 = require('./layout_attributes'); */; +/* removed: var _$supplyLayoutDefaults_727 = require('./axis_defaults'); */; -var __axesNames_665 = ['aaxis', 'baxis', 'caxis']; +var __axesNames_728 = ['aaxis', 'baxis', 'caxis']; -var _$supplyLayoutDefaults_665 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { - _$handleSubplotDefaults_660(layoutIn, layoutOut, fullData, { +var _$supplyLayoutDefaults_728 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { + _$handleSubplotDefaults_723(layoutIn, layoutOut, fullData, { type: 'ternary', - attributes: _$layout_attributes_666, + attributes: _$layout_attributes_729, handleDefaults: handleTernaryDefaults, font: layoutOut.font, paper_bgcolor: layoutOut.paper_bgcolor @@ -175035,18 +177218,18 @@ var _$supplyLayoutDefaults_665 = function supplyLayoutDefaults(layoutIn, layoutO function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) { var bgColor = coerce('bgcolor'); var sum = coerce('sum'); - options.bgColor = _$color_411.combine(bgColor, options.paper_bgcolor); + options.bgColor = _$color_473.combine(bgColor, options.paper_bgcolor); var axName, containerIn, containerOut; // TODO: allow most (if not all) axis attributes to be set // in the outer container and used as defaults in the individual axes? - for(var j = 0; j < __axesNames_665.length; j++) { - axName = __axesNames_665[j]; + for(var j = 0; j < __axesNames_728.length; j++) { + axName = __axesNames_728[j]; containerIn = ternaryLayoutIn[axName] || {}; containerOut = ternaryLayoutOut[axName] = {_name: axName, type: 'linear'}; - _$supplyLayoutDefaults_664(containerIn, containerOut, options); + _$supplyLayoutDefaults_727(containerIn, containerOut, options); } // if the min values contradict each other, set them all to default (0) @@ -175076,23 +177259,24 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$tinycolor_352 = require('tinycolor2'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$tinycolor_414 = require('tinycolor2'); */; -/* removed: var _$registry_668 = require('../../registry'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -var ____667 = _$lib_539._; -/* removed: var _$color_411 = require('../../components/color'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$setConvert_603 = require('../cartesian/set_convert'); */; -var __extendFlat_667 = _$extend_528.extendFlat; -/* removed: var _$plots_647 = require('../plots'); */; -/* removed: var _$axes_584 = require('../cartesian/axes'); */; -/* removed: var _$dragelement_433 = require('../../components/dragelement'); */; -/* removed: var _$fx_453 = require('../../components/fx'); */; -/* removed: var _$titles_504 = require('../../components/titles'); */; -/* removed: var _$prepSelect_602 = require('../cartesian/select'); */; -/* removed: var _$constants_589 = require('../cartesian/constants'); */; +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +var ____730 = _$lib_601._; +/* removed: var _$color_473 = require('../../components/color'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$setConvert_665 = require('../cartesian/set_convert'); */; +var __extendFlat_730 = _$extend_590.extendFlat; +/* removed: var _$plots_709 = require('../plots'); */; +/* removed: var _$axes_647 = require('../cartesian/axes'); */; +/* removed: var _$dragelement_495 = require('../../components/dragelement'); */; +/* removed: var _$fx_515 = require('../../components/fx'); */; +/* removed: var _$titles_566 = require('../../components/titles'); */; +var __prepSelect_730 = _$select_664.prepSelect; +var __clearSelect_730 = _$select_664.clearSelect; +/* removed: var _$constants_652 = require('../cartesian/constants'); */; function Ternary(options, fullLayout) { this.id = options.id; @@ -175101,11 +177285,11 @@ function Ternary(options, fullLayout) { this.makeFramework(fullLayout); } -var _$Ternary_667 = Ternary; +var _$Ternary_730 = Ternary; -var __proto_667 = Ternary.prototype; +var __proto_730 = Ternary.prototype; -__proto_667.init = function(fullLayout) { +__proto_730.init = function(fullLayout) { this.container = fullLayout._ternarylayer; this.defs = fullLayout._defs; this.layoutId = fullLayout._uid; @@ -175113,7 +177297,7 @@ __proto_667.init = function(fullLayout) { this.layers = {}; }; -__proto_667.plot = function(ternaryCalcData, fullLayout) { +__proto_730.plot = function(ternaryCalcData, fullLayout) { var _this = this; var ternaryLayout = fullLayout[_this.id]; var graphSize = fullLayout._size; @@ -175130,41 +177314,36 @@ __proto_667.plot = function(ternaryCalcData, fullLayout) { _this.updateLayers(ternaryLayout); _this.adjustLayout(ternaryLayout, graphSize); - _$plots_647.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout); - _this.layers.plotbg.select('path').call(_$color_411.fill, ternaryLayout.bgcolor); + _$plots_709.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout); + _this.layers.plotbg.select('path').call(_$color_473.fill, ternaryLayout.bgcolor); }; -__proto_667.makeFramework = function(fullLayout) { +__proto_730.makeFramework = function(fullLayout) { var _this = this; 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 = fullLayout._clips.selectAll('#' + clipId) - .data([0]); - _this.clipDef.enter().append('clipPath').attr('id', clipId) - .append('path').attr('d', 'M0,0Z'); + _this.clipDef = _$lib_601.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) { + s.append('path').attr('d', 'M0,0Z'); + }); // 'relative' clippath (i.e. no translation) for this ternary subplot - var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id; - _this.clipDefRelative = fullLayout._clips.selectAll('#' + clipIdRelative) - .data([0]); - _this.clipDefRelative.enter().append('clipPath').attr('id', clipIdRelative) - .append('path').attr('d', 'M0,0Z'); + _this.clipDefRelative = _$lib_601.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function(s) { + s.append('path').attr('d', 'M0,0Z'); + }); // container for everything in this ternary subplot - _this.plotContainer = _this.container.selectAll('g.' + _this.id) - .data([0]); - _this.plotContainer.enter().append('g') - .classed(_this.id, true); - + _this.plotContainer = _$lib_601.ensureSingle(_this.container, 'g', _this.id); _this.updateLayers(ternaryLayout); - _$drawing_436.setClipUrl(_this.layers.backplot, clipId); - _$drawing_436.setClipUrl(_this.layers.grids, clipId); + _$drawing_498.setClipUrl(_this.layers.backplot, clipId); + _$drawing_498.setClipUrl(_this.layers.grids, clipId); }; -__proto_667.updateLayers = function(ternaryLayout) { +__proto_730.updateLayers = function(ternaryLayout) { var _this = this; var layers = _this.layers; @@ -175203,7 +177382,7 @@ __proto_667.updateLayers = function(ternaryLayout) { toplevel.enter().append('g') .attr('class', function(d) { return 'toplevel ' + d; }) .each(function(d) { - var s = _$d3_127.select(this); + var s = _$d3_130.select(this); layers[d] = s; // containers for different trace types. @@ -175234,7 +177413,7 @@ __proto_667.updateLayers = function(ternaryLayout) { var w_over_h = Math.sqrt(4 / 3); -__proto_667.adjustLayout = function(ternaryLayout, graphSize) { +__proto_730.adjustLayout = function(ternaryLayout, graphSize) { var _this = this, domain = ternaryLayout.domain, xDomainCenter = (domain.x[0] + domain.x[1]) / 2, @@ -175281,7 +177460,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { ], _id: 'x' }; - _$setConvert_603(_this.xaxis, _this.graphDiv._fullLayout); + _$setConvert_665(_this.xaxis, _this.graphDiv._fullLayout); _this.xaxis.setScale(); _this.xaxis.isPtWithinRange = function(d) { return ( @@ -175303,7 +177482,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { ], _id: 'y' }; - _$setConvert_603(_this.yaxis, _this.graphDiv._fullLayout); + _$setConvert_665(_this.yaxis, _this.graphDiv._fullLayout); _this.yaxis.setScale(); _this.yaxis.isPtWithinRange = function() { return true; }; @@ -175313,7 +177492,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { // 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_667({}, ternaryLayout.aaxis, { + var aaxis = _this.aaxis = __extendFlat_730({}, ternaryLayout.aaxis, { visible: true, range: [amin, sum - bmin - cmin], side: 'left', @@ -175330,12 +177509,12 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _gridpath: 'M0,0l' + h + ',-' + (w / 2), automargin: false // don't use automargins routine for labels }); - _$setConvert_603(aaxis, _this.graphDiv._fullLayout); + _$setConvert_665(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_667({}, ternaryLayout.baxis, { + var baxis = _this.baxis = __extendFlat_730({}, ternaryLayout.baxis, { visible: true, range: [sum - amin - cmin, bmin], side: 'bottom', @@ -175350,13 +177529,13 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _gridpath: 'M0,0l-' + (w / 2) + ',-' + h, automargin: false // don't use automargins routine for labels }); - _$setConvert_603(baxis, _this.graphDiv._fullLayout); + _$setConvert_665(baxis, _this.graphDiv._fullLayout); baxis.setScale(); aaxis._counteraxis = baxis; // caxis goes down the right side. Set it up as a y axis, with // post-transformation similar to aaxis - var caxis = _this.caxis = __extendFlat_667({}, ternaryLayout.caxis, { + var caxis = _this.caxis = __extendFlat_730({}, ternaryLayout.caxis, { visible: true, range: [sum - amin - bmin, cmin], side: 'right', @@ -175372,7 +177551,7 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _gridpath: 'M0,0l-' + h + ',' + (w / 2), automargin: false // don't use automargins routine for labels }); - _$setConvert_603(caxis, _this.graphDiv._fullLayout); + _$setConvert_665(caxis, _this.graphDiv._fullLayout); caxis.setScale(); var triangleClip = 'M' + x0 + ',' + (y0 + h) + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z'; @@ -175415,30 +177594,30 @@ __proto_667.adjustLayout = function(ternaryLayout, graphSize) { _this.layers.aline.select('path') .attr('d', aaxis.showline ? 'M' + x0 + ',' + (y0 + h) + 'l' + (w / 2) + ',-' + h : 'M0,0') - .call(_$color_411.stroke, aaxis.linecolor || '#000') + .call(_$color_473.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_411.stroke, baxis.linecolor || '#000') + .call(_$color_473.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_411.stroke, caxis.linecolor || '#000') + .call(_$color_473.stroke, caxis.linecolor || '#000') .style('stroke-width', (caxis.linewidth || 0) + 'px'); if(!_this.graphDiv._context.staticPlot) { _this.initInteractions(); } - _$drawing_436.setClipUrl( + _$drawing_498.setClipUrl( _this.layers.frontplot, _this._hasClipOnAxisFalse ? null : _this.clipId ); }; -__proto_667.drawAxes = function(doTitles) { +__proto_730.drawAxes = function(doTitles) { var _this = this, gd = _this.graphDiv, titlesuffix = _this.id.substr(7) + 'title', @@ -175447,18 +177626,18 @@ __proto_667.drawAxes = function(doTitles) { caxis = _this.caxis; // 3rd arg true below skips titles, so we can configure them // correctly later on. - _$axes_584.doTicks(gd, aaxis, true); - _$axes_584.doTicks(gd, baxis, true); - _$axes_584.doTicks(gd, caxis, true); + _$axes_647.doTicks(gd, aaxis, true); + _$axes_647.doTicks(gd, baxis, true); + _$axes_647.doTicks(gd, caxis, true); 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)); - _this.layers['a-title'] = _$titles_504.draw(gd, 'a' + titlesuffix, { + _this.layers['a-title'] = _$titles_566.draw(gd, 'a' + titlesuffix, { propContainer: aaxis, propName: _this.id + '.aaxis.title', - placeholder: ____667(gd, 'Click to enter Component A title'), + placeholder: ____730(gd, 'Click to enter Component A title'), attributes: { x: _this.x0 + _this.w / 2, y: _this.y0 - aaxis.titlefont.size / 3 - apad, @@ -175470,10 +177649,10 @@ __proto_667.drawAxes = function(doTitles) { var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) + (baxis.ticks === 'outside' ? baxis.ticklen : 0) + 3; - _this.layers['b-title'] = _$titles_504.draw(gd, 'b' + titlesuffix, { + _this.layers['b-title'] = _$titles_566.draw(gd, 'b' + titlesuffix, { propContainer: baxis, propName: _this.id + '.baxis.title', - placeholder: ____667(gd, 'Click to enter Component B title'), + placeholder: ____730(gd, 'Click to enter Component B title'), attributes: { x: _this.x0 - bpad, y: _this.y0 + _this.h + baxis.titlefont.size * 0.83 + bpad, @@ -175481,10 +177660,10 @@ __proto_667.drawAxes = function(doTitles) { } }); - _this.layers['c-title'] = _$titles_504.draw(gd, 'c' + titlesuffix, { + _this.layers['c-title'] = _$titles_566.draw(gd, 'c' + titlesuffix, { propContainer: caxis, propName: _this.id + '.caxis.title', - placeholder: ____667(gd, 'Click to enter Component C title'), + placeholder: ____730(gd, 'Click to enter Component C title'), attributes: { x: _this.x0 + _this.w + bpad, y: _this.y0 + _this.h + caxis.titlefont.size * 0.83 + bpad, @@ -175496,7 +177675,7 @@ __proto_667.drawAxes = function(doTitles) { // hard coded paths for zoom corners // uses the same sizing as cartesian, length is MINZOOM/2, width is 3px -var CLEN = _$constants_589.MINZOOM / 2 + 0.87; +var CLEN = _$constants_652.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'; @@ -175510,9 +177689,9 @@ var TOPPATH = 'm0,1l' + (CLEN / 2) + ',' + (CLEN * 0.87) + 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_667 = true; +var __SHOWZOOMOUTTIP_730 = true; -__proto_667.initInteractions = function() { +__proto_730.initInteractions = function() { var _this = this, dragger = _this.layers.plotbg.select('path').node(), gd = _this.graphDiv, @@ -175550,14 +177729,14 @@ __proto_667.initInteractions = function() { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragDone; panPrep(); - clearSelect(); + __clearSelect_730(zoomContainer); } else if(dragModeNow === 'select' || dragModeNow === 'lasso') { - _$prepSelect_602(e, startX, startY, dragOptions, dragModeNow); + __prepSelect_730(e, startX, startY, dragOptions, dragModeNow); } }, clickFn: function(numClicks, evt) { - __removeZoombox_667(gd); + __removeZoombox_730(gd); if(numClicks === 2) { var attrs = {}; @@ -175565,9 +177744,9 @@ __proto_667.initInteractions = function() { attrs[_this.id + '.baxis.min'] = 0; attrs[_this.id + '.caxis.min'] = 0; gd.emit('plotly_doubleclick', null); - _$registry_668.call('relayout', gd, attrs); + _$registry_731.call('relayout', gd, attrs); } - _$fx_453.click(gd, evt, _this.id); + _$fx_515.click(gd, evt, _this.id); } }; @@ -175584,7 +177763,7 @@ __proto_667.initInteractions = function() { }; mins = mins0; span0 = _this.aaxis.range[1] - mins0.a; - lum = _$tinycolor_352(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance(); + lum = _$tinycolor_414(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance(); path0 = 'M0,' + _this.h + 'L' + (_this.w / 2) + ', 0L' + _this.w + ',' + _this.h + 'Z'; dimmed = false; @@ -175601,14 +177780,14 @@ __proto_667.initInteractions = function() { .attr('class', 'zoombox-corners') .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')') .style({ - fill: _$color_411.background, - stroke: _$color_411.defaultLine, + fill: _$color_473.background, + stroke: _$color_473.defaultLine, 'stroke-width': 1, opacity: 0 }) .attr('d', 'M0,0Z'); - clearSelect(); + __clearSelect_730(zoomContainer); } function getAFrac(x, y) { return 1 - (y / _this.h); } @@ -175628,7 +177807,7 @@ __proto_667.initInteractions = function() { yBottom = (1 - afrac) * _this.h, yTop = yBottom - xSpan / w_over_h; - if(xSpan < _$constants_589.MINZOOM) { + if(xSpan < _$constants_652.MINZOOM) { mins = mins0; zb.attr('d', path0); corners.attr('d', 'M0,0Z'); @@ -175661,7 +177840,7 @@ __proto_667.initInteractions = function() { } function zoomDone() { - __removeZoombox_667(gd); + __removeZoombox_730(gd); if(mins === mins0) return; @@ -175670,11 +177849,11 @@ __proto_667.initInteractions = function() { attrs[_this.id + '.baxis.min'] = mins.b; attrs[_this.id + '.caxis.min'] = mins.c; - _$registry_668.call('relayout', gd, attrs); + _$registry_731.call('relayout', gd, attrs); - if(__SHOWZOOMOUTTIP_667 && gd.data && gd._context.showTips) { - _$lib_539.notifier(____667(gd, 'Double-click to zoom back out'), 'long'); - __SHOWZOOMOUTTIP_667 = false; + if(__SHOWZOOMOUTTIP_730 && gd.data && gd._context.showTips) { + _$lib_601.notifier(____730(gd, 'Double-click to zoom back out'), 'long'); + __SHOWZOOMOUTTIP_730 = false; } } @@ -175739,7 +177918,7 @@ __proto_667.initInteractions = function() { if(_this._hasClipOnAxisFalse) { _this.plotContainer .select('.scatterlayer').selectAll('.trace') - .call(_$drawing_436.hideOutsideRangePoints, _this); + .call(_$drawing_498.hideOutsideRangePoints, _this); } } @@ -175749,21 +177928,14 @@ __proto_667.initInteractions = function() { attrs[_this.id + '.baxis.min'] = mins.b; attrs[_this.id + '.caxis.min'] = mins.c; - _$registry_668.call('relayout', gd, attrs); - } - - function clearSelect() { - // until we get around to persistent selections, remove the outline - // here. The selection itself will be removed when the plot redraws - // at the end. - zoomContainer.selectAll('.select-outline').remove(); + _$registry_731.call('relayout', gd, attrs); } // 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_453.hover(gd, evt, _this.id); + _$fx_515.hover(gd, evt, _this.id); gd._fullLayout._lasthover = dragger; gd._fullLayout._hoversubplot = _this.id; }; @@ -175771,19 +177943,19 @@ __proto_667.initInteractions = function() { dragger.onmouseout = function(evt) { if(gd._dragging) return; - _$dragelement_433.unhover(gd, evt); + _$dragelement_495.unhover(gd, evt); }; - _$dragelement_433.init(dragOptions); + _$dragelement_495.init(dragOptions); }; -function __removeZoombox_667(gd) { - _$d3_127.select(gd) +function __removeZoombox_730(gd) { + _$d3_130.select(gd) .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners') .remove(); } -var _$ternary_661 = {}; +var _$ternary_724 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -175795,39 +177967,39 @@ var _$ternary_661 = {}; 'use strict'; -/* removed: var _$Ternary_667 = require('./ternary'); */; +/* removed: var _$Ternary_730 = require('./ternary'); */; -var __getSubplotCalcData_661 = _$get_data_621.getSubplotCalcData; -var __counterRegex_661 = _$lib_539.counterRegex; +var __getSubplotCalcData_724 = _$get_data_683.getSubplotCalcData; +var __counterRegex_724 = _$lib_601.counterRegex; var TERNARY = 'ternary'; -_$ternary_661.name = TERNARY; +_$ternary_724.name = TERNARY; -_$ternary_661.attr = 'subplot'; +_$ternary_724.attr = 'subplot'; -_$ternary_661.idRoot = TERNARY; +_$ternary_724.idRoot = TERNARY; -_$ternary_661.idRegex = _$ternary_661.attrRegex = __counterRegex_661(TERNARY); +_$ternary_724.idRegex = _$ternary_724.attrRegex = __counterRegex_724(TERNARY); -_$ternary_661.attributes = _$attributes_662; +_$ternary_724.attributes = _$attributes_725; -_$ternary_661.layoutAttributes = _$layout_attributes_666; +_$ternary_724.layoutAttributes = _$layout_attributes_729; -_$ternary_661.supplyLayoutDefaults = _$supplyLayoutDefaults_665; +_$ternary_724.supplyLayoutDefaults = _$supplyLayoutDefaults_728; -_$ternary_661.plot = function plotTernary(gd) { +_$ternary_724.plot = function plotTernary(gd) { var fullLayout = gd._fullLayout; var calcData = gd.calcdata; var ternaryIds = fullLayout._subplots[TERNARY]; for(var i = 0; i < ternaryIds.length; i++) { var ternaryId = ternaryIds[i], - ternaryCalcData = __getSubplotCalcData_661(calcData, TERNARY, ternaryId), + ternaryCalcData = __getSubplotCalcData_724(calcData, TERNARY, ternaryId), ternary = fullLayout[ternaryId]._subplot; // If ternary is not instantiated, create one! if(!ternary) { - ternary = new _$Ternary_667({ + ternary = new _$Ternary_730({ id: ternaryId, graphDiv: gd, container: fullLayout._ternarylayer.node() @@ -175842,7 +178014,7 @@ _$ternary_661.plot = function plotTernary(gd) { } }; -_$ternary_661.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$ternary_724.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || []; for(var i = 0; i < oldTernaryKeys.length; i++) { @@ -175870,19 +178042,19 @@ _$ternary_661.clean = function(newFullData, newFullLayout, oldFullData, oldFullL 'use strict'; -/* removed: var _$attributes_862 = require('../scatter/attributes'); */; -/* removed: var _$attributes_581 = require('../../plots/attributes'); */; -/* removed: var _$makeColorScaleAttributes_419 = require('../../components/colorscale/color_attributes'); */; -/* removed: var _$attributes_412 = require('../../components/colorbar/attributes'); */; -var __dash_929 = _$attributes_435.dash; +/* removed: var _$attributes_927 = require('../scatter/attributes'); */; +/* removed: var _$attributes_644 = require('../../plots/attributes'); */; +/* removed: var _$makeColorScaleAttributes_481 = require('../../components/colorscale/color_attributes'); */; +/* removed: var _$attributes_474 = require('../../components/colorbar/attributes'); */; +var __dash_996 = _$attributes_497.dash; -var __extendFlat_929 = _$extend_528.extendFlat; +var __extendFlat_996 = _$extend_590.extendFlat; -var __scatterMarkerAttrs_929 = _$attributes_862.marker, - __scatterLineAttrs_929 = _$attributes_862.line, - __scatterMarkerLineAttrs_929 = __scatterMarkerAttrs_929.line; +var __scatterMarkerAttrs_996 = _$attributes_927.marker, + __scatterLineAttrs_996 = _$attributes_927.line, + __scatterMarkerLineAttrs_996 = __scatterMarkerAttrs_996.line; -var _$attributes_929 = { +var _$attributes_996 = { a: { valType: 'data_array', editType: 'calc', @@ -175906,60 +178078,60 @@ var _$attributes_929 = { editType: 'calc', }, - mode: __extendFlat_929({}, _$attributes_862.mode, {dflt: 'markers'}), - text: __extendFlat_929({}, _$attributes_862.text, { + mode: __extendFlat_996({}, _$attributes_927.mode, {dflt: 'markers'}), + text: __extendFlat_996({}, _$attributes_927.text, { }), - hovertext: __extendFlat_929({}, _$attributes_862.hovertext, { + hovertext: __extendFlat_996({}, _$attributes_927.hovertext, { }), line: { - color: __scatterLineAttrs_929.color, - width: __scatterLineAttrs_929.width, - dash: __dash_929, - shape: __extendFlat_929({}, __scatterLineAttrs_929.shape, + color: __scatterLineAttrs_996.color, + width: __scatterLineAttrs_996.width, + dash: __dash_996, + shape: __extendFlat_996({}, __scatterLineAttrs_996.shape, {values: ['linear', 'spline']}), - smoothing: __scatterLineAttrs_929.smoothing, + smoothing: __scatterLineAttrs_996.smoothing, editType: 'calc' }, - connectgaps: _$attributes_862.connectgaps, - cliponaxis: _$attributes_862.cliponaxis, - fill: __extendFlat_929({}, _$attributes_862.fill, { + connectgaps: _$attributes_927.connectgaps, + cliponaxis: _$attributes_927.cliponaxis, + fill: __extendFlat_996({}, _$attributes_927.fill, { values: ['none', 'toself', 'tonext'], }), - fillcolor: _$attributes_862.fillcolor, - marker: __extendFlat_929({ - symbol: __scatterMarkerAttrs_929.symbol, - opacity: __scatterMarkerAttrs_929.opacity, - maxdisplayed: __scatterMarkerAttrs_929.maxdisplayed, - size: __scatterMarkerAttrs_929.size, - sizeref: __scatterMarkerAttrs_929.sizeref, - sizemin: __scatterMarkerAttrs_929.sizemin, - sizemode: __scatterMarkerAttrs_929.sizemode, - line: __extendFlat_929({ - width: __scatterMarkerLineAttrs_929.width, + fillcolor: _$attributes_927.fillcolor, + marker: __extendFlat_996({ + symbol: __scatterMarkerAttrs_996.symbol, + opacity: __scatterMarkerAttrs_996.opacity, + maxdisplayed: __scatterMarkerAttrs_996.maxdisplayed, + size: __scatterMarkerAttrs_996.size, + sizeref: __scatterMarkerAttrs_996.sizeref, + sizemin: __scatterMarkerAttrs_996.sizemin, + sizemode: __scatterMarkerAttrs_996.sizemode, + line: __extendFlat_996({ + width: __scatterMarkerLineAttrs_996.width, editType: 'calc' }, - _$makeColorScaleAttributes_419('marker.line') + _$makeColorScaleAttributes_481('marker.line') ), - gradient: __scatterMarkerAttrs_929.gradient, + gradient: __scatterMarkerAttrs_996.gradient, editType: 'calc' - }, _$makeColorScaleAttributes_419('marker'), { - showscale: __scatterMarkerAttrs_929.showscale, - colorbar: _$attributes_412 + }, _$makeColorScaleAttributes_481('marker'), { + showscale: __scatterMarkerAttrs_996.showscale, + colorbar: _$attributes_474 }), - textfont: _$attributes_862.textfont, - textposition: _$attributes_862.textposition, + textfont: _$attributes_927.textfont, + textposition: _$attributes_927.textposition, - selected: _$attributes_862.selected, - unselected: _$attributes_862.unselected, + selected: _$attributes_927.selected, + unselected: _$attributes_927.unselected, - hoverinfo: __extendFlat_929({}, _$attributes_581.hoverinfo, { + hoverinfo: __extendFlat_996({}, _$attributes_644.hoverinfo, { flags: ['a', 'b', 'c', 'text', 'name'] }), - hoveron: _$attributes_862.hoveron, + hoveron: _$attributes_927.hoveron, }; /** @@ -175973,17 +178145,17 @@ var _$attributes_929 = { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$calcMarkerColorscale_867 = require('../scatter/colorscale_calc'); */; -/* removed: var _$arraysToCalcdata_861 = require('../scatter/arrays_to_calcdata'); */; -/* removed: var _$calcSelection_864 = require('../scatter/calc_selection'); */; -var __calcMarkerSize_930 = _$calc_863.calcMarkerSize; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +/* removed: var _$arraysToCalcdata_926 = require('../scatter/arrays_to_calcdata'); */; +/* removed: var _$calcSelection_929 = require('../scatter/calc_selection'); */; +var __calcMarkerSize_997 = _$calc_928.calcMarkerSize; var dataArrays = ['a', 'b', 'c']; var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']}; -var _$calc_930 = function calc(gd, trace) { +var _$calc_997 = function calc(gd, trace) { var ternary = gd._fullLayout[trace.subplot]; var displaySum = ternary.sum; var normSum = trace.sum || displaySum; @@ -176013,7 +178185,7 @@ var _$calc_930 = function calc(gd, trace) { a = arrays.a[i]; b = arrays.b[i]; c = arrays.c[i]; - if(_$fastIsnumeric_139(a) && _$fastIsnumeric_139(b) && _$fastIsnumeric_139(c)) { + if(_$fastIsnumeric_196(a) && _$fastIsnumeric_196(b) && _$fastIsnumeric_196(c)) { a = +a; b = +b; c = +c; @@ -176035,10 +178207,10 @@ var _$calc_930 = function calc(gd, trace) { else cd[i] = {x: false, y: false}; } - __calcMarkerSize_930(trace, serieslen); - _$calcMarkerColorscale_867(trace); - _$arraysToCalcdata_861(cd, trace); - _$calcSelection_864(cd, trace); + __calcMarkerSize_997(trace, serieslen); + _$calcMarkerColorscale_932(trace); + _$arraysToCalcdata_926(cd, trace); + _$calcSelection_929(cd, trace); return cd; }; @@ -176054,22 +178226,22 @@ var _$calc_930 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; -/* removed: var _$constants_868 = require('../scatter/constants'); */; -/* removed: var _$subtypes_884 = require('../scatter/subtypes'); */; -/* removed: var _$markerDefaults_880 = require('../scatter/marker_defaults'); */; -/* removed: var _$lineDefaults_875 = require('../scatter/line_defaults'); */; -/* removed: var _$handleLineShapeDefaults_877 = require('../scatter/line_shape_defaults'); */; -/* removed: var _$text_defaults_885 = require('../scatter/text_defaults'); */; -/* removed: var _$fillColorDefaults_871 = require('../scatter/fillcolor_defaults'); */; +/* removed: var _$constants_933 = require('../scatter/constants'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +/* removed: var _$lineDefaults_940 = require('../scatter/line_defaults'); */; +/* removed: var _$handleLineShapeDefaults_942 = require('../scatter/line_shape_defaults'); */; +/* removed: var _$text_defaults_950 = require('../scatter/text_defaults'); */; +/* removed: var _$fillColorDefaults_936 = require('../scatter/fillcolor_defaults'); */; -/* removed: var _$attributes_929 = require('./attributes'); */; +/* removed: var _$attributes_996 = require('./attributes'); */; -var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_998 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_929, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_996, attr, dflt); } var a = coerce('a'), @@ -176107,26 +178279,26 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('text'); coerce('hovertext'); - var defaultMode = len < _$constants_868.PTS_LINESONLY ? 'lines+markers' : 'lines'; + var defaultMode = len < _$constants_933.PTS_LINESONLY ? 'lines+markers' : 'lines'; coerce('mode', defaultMode); - if(_$subtypes_884.hasLines(traceOut)) { - _$lineDefaults_875(traceIn, traceOut, defaultColor, layout, coerce); - _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + if(_$subtypes_949.hasLines(traceOut)) { + _$lineDefaults_940(traceIn, traceOut, defaultColor, layout, coerce); + _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); coerce('connectgaps'); } - if(_$subtypes_884.hasMarkers(traceOut)) { - _$markerDefaults_880(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); + if(_$subtypes_949.hasMarkers(traceOut)) { + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true}); } - if(_$subtypes_884.hasText(traceOut)) { - _$text_defaults_885(traceIn, traceOut, layout, coerce); + if(_$subtypes_949.hasText(traceOut)) { + _$text_defaults_950(traceIn, traceOut, layout, coerce); } var dfltHoverOn = []; - if(_$subtypes_884.hasMarkers(traceOut) || _$subtypes_884.hasText(traceOut)) { + if(_$subtypes_949.hasMarkers(traceOut) || _$subtypes_949.hasText(traceOut)) { coerce('cliponaxis'); coerce('marker.maxdisplayed'); dfltHoverOn.push('points'); @@ -176134,8 +178306,8 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('fill'); if(traceOut.fill !== 'none') { - _$fillColorDefaults_871(traceIn, traceOut, defaultColor, coerce); - if(!_$subtypes_884.hasLines(traceOut)) _$handleLineShapeDefaults_877(traceIn, traceOut, coerce); + _$fillColorDefaults_936(traceIn, traceOut, defaultColor, coerce); + if(!_$subtypes_949.hasLines(traceOut)) _$handleLineShapeDefaults_942(traceIn, traceOut, coerce); } if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') { @@ -176143,7 +178315,7 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol } coerce('hoveron', dfltHoverOn.join('+') || 'points'); - _$lib_539.coerceSelectionMarkerOpacity(traceOut, coerce); + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); }; /** @@ -176156,7 +178328,7 @@ var _$supplyDefaults_931 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -var _$eventData_932 = function eventData(out, pt, trace, cd, pointNumber) { +var _$eventData_999 = function eventData(out, pt, trace, cd, pointNumber) { if(pt.xa) out.xaxis = pt.xa; if(pt.ya) out.yaxis = pt.ya; @@ -176188,12 +178360,12 @@ var _$eventData_932 = function eventData(out, pt, trace, cd, pointNumber) { 'use strict'; -/* removed: var _$hoverPoints_873 = require('../scatter/hover'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hoverPoints_938 = require('../scatter/hover'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; -var _$hoverPoints_933 = function hoverPoints(pointData, xval, yval, hovermode) { - var scatterPointData = _$hoverPoints_873(pointData, xval, yval, hovermode); +var _$hoverPoints_1000 = function hoverPoints(pointData, xval, yval, hovermode) { + var scatterPointData = _$hoverPoints_938(pointData, xval, yval, hovermode); if(!scatterPointData || scatterPointData[0].index === false) return; var newPointData = scatterPointData[0]; @@ -176235,7 +178407,7 @@ var _$hoverPoints_933 = function hoverPoints(pointData, xval, yval, hovermode) { var text = []; function textPart(ax, val) { - text.push(ax._hovertitle + ': ' + _$axes_584.tickText(ax, val, 'hover').text); + text.push(ax._hovertitle + ': ' + _$axes_647.tickText(ax, val, 'hover').text); } if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'c']; @@ -176259,9 +178431,9 @@ var _$hoverPoints_933 = function hoverPoints(pointData, xval, yval, hovermode) { 'use strict'; -/* removed: var _$plot_881 = require('../scatter/plot'); */; +/* removed: var _$plot_946 = require('../scatter/plot'); */; -var _$plot_935 = function plot(gd, ternary, moduleCalcData) { +var _$plot_1002 = function plot(gd, ternary, moduleCalcData) { var plotContainer = ternary.plotContainer; // remove all nodes inside the scatter layer @@ -176275,7 +178447,7 @@ var _$plot_935 = function plot(gd, ternary, moduleCalcData) { layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null }; - _$plot_881(gd, plotinfo, moduleCalcData); + _$plot_946(gd, plotinfo, moduleCalcData); }; /** @@ -176290,26 +178462,26 @@ var _$plot_935 = function plot(gd, ternary, moduleCalcData) { var ScatterTernary = {}; -ScatterTernary.attributes = _$attributes_929; -ScatterTernary.supplyDefaults = _$supplyDefaults_931; -ScatterTernary.colorbar = _$colorbar_866; -ScatterTernary.calc = _$calc_930; -ScatterTernary.plot = _$plot_935; -ScatterTernary.style = _$style_883.style; -ScatterTernary.hoverPoints = _$hoverPoints_933; -ScatterTernary.selectPoints = _$selectPoints_882; -ScatterTernary.eventData = _$eventData_932; +ScatterTernary.attributes = _$attributes_996; +ScatterTernary.supplyDefaults = _$supplyDefaults_998; +ScatterTernary.colorbar = _$colorbar_931; +ScatterTernary.calc = _$calc_997; +ScatterTernary.plot = _$plot_1002; +ScatterTernary.style = _$style_948.style; +ScatterTernary.hoverPoints = _$hoverPoints_1000; +ScatterTernary.selectPoints = _$selectPoints_947; +ScatterTernary.eventData = _$eventData_999; ScatterTernary.moduleType = 'trace'; ScatterTernary.name = 'scatterternary'; -ScatterTernary.basePlotModule = _$ternary_661; +ScatterTernary.basePlotModule = _$ternary_724; ScatterTernary.categories = ['ternary', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like']; ScatterTernary.meta = { }; -var _$ScatterTernary_934 = ScatterTernary; +var _$ScatterTernary_1001 = ScatterTernary; /** * Copyright 2012-2018, Plotly, Inc. @@ -176321,9 +178493,9 @@ var _$ScatterTernary_934 = ScatterTernary; 'use strict'; -var _$scatterternary_34 = _$ScatterTernary_934; +var _$scatterternary_34 = _$ScatterTernary_1001; -var _$sort_966 = {}; +var _$sort_1037 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -176334,15 +178506,15 @@ var _$sort_966 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../lib'); */; -/* removed: var _$axes_584 = require('../plots/cartesian/axes'); */; -var __pointsAccessorFunction_966 = _$helpers_965.pointsAccessorFunction; +/* removed: var _$lib_601 = require('../lib'); */; +/* removed: var _$axes_647 = require('../plots/cartesian/axes'); */; +var __pointsAccessorFunction_1037 = _$helpers_1036.pointsAccessorFunction; -_$sort_966.moduleType = 'transform'; +_$sort_1037.moduleType = 'transform'; -_$sort_966.name = 'sort'; +_$sort_1037.name = 'sort'; -_$sort_966.attributes = { +_$sort_1037.attributes = { enabled: { valType: 'boolean', dflt: true, @@ -176371,11 +178543,11 @@ _$sort_966.attributes = { editType: 'calc' }; -_$sort_966.supplyDefaults = function(transformIn) { +_$sort_1037.supplyDefaults = function(transformIn) { var transformOut = {}; function coerce(attr, dflt) { - return _$lib_539.coerce(transformIn, transformOut, _$sort_966.attributes, attr, dflt); + return _$lib_601.coerce(transformIn, transformOut, _$sort_1037.attributes, attr, dflt); } var enabled = coerce('enabled'); @@ -176388,23 +178560,23 @@ _$sort_966.supplyDefaults = function(transformIn) { return transformOut; }; -_$sort_966.calcTransform = function(gd, trace, opts) { +_$sort_1037.calcTransform = function(gd, trace, opts) { if(!opts.enabled) return; - var targetArray = _$lib_539.getTargetArray(trace, opts); + var targetArray = _$lib_601.getTargetArray(trace, opts); if(!targetArray) return; var target = opts.target; var len = targetArray.length; var arrayAttrs = trace._arrayAttrs; - var d2c = _$axes_584.getDataToCoordFunc(gd, trace, target, targetArray); + var d2c = _$axes_647.getDataToCoordFunc(gd, trace, target, targetArray); var indices = getIndices(opts, targetArray, d2c); - var originalPointsAccessor = __pointsAccessorFunction_966(trace.transforms, opts); + var originalPointsAccessor = __pointsAccessorFunction_1037(trace.transforms, opts); var indexToPoints = {}; var i, j; for(i = 0; i < arrayAttrs.length; i++) { - var np = _$lib_539.nestedProperty(trace, arrayAttrs[i]); + var np = _$lib_601.nestedProperty(trace, arrayAttrs[i]); var arrayOld = np.get(); var arrayNew = new Array(len); @@ -176469,7 +178641,1581 @@ function getSortFunc(opts, d2c) { 'use strict'; -var _$sort_35 = _$sort_966; +var _$sort_35 = _$sort_1037; + +var _$performanceNow_346 = {}; +(function (process){ +// Generated by CoffeeScript 1.12.2 +(function() { + var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; + + if ((typeof performance !== "undefined" && performance !== null) && performance.now) { + _$performanceNow_346 = function() { + return performance.now(); + }; + } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { + _$performanceNow_346 = 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) { + _$performanceNow_346 = function() { + return Date.now() - loadTime; + }; + loadTime = Date.now(); + } else { + _$performanceNow_346 = function() { + return new Date().getTime() - loadTime; + }; + loadTime = new Date().getTime(); + } + +}).call(this); + +//# sourceMappingURL=performance-now.js.map + +}).call(this,_$browser_366) +var _$raf_368 = {}; +(function (global){ +var __dummy_368$0 = 0 + , root = typeof window === 'undefined' ? global : window + , vendors = ['moz', 'webkit'] + , suffix = 'AnimationFrame' + , raf = root['request' + suffix] + , caf = root['cancel' + suffix] || root['cancelRequest' + suffix] + +for(var i = 0; !raf && i < vendors.length; i++) { + raf = root[vendors[i] + 'Request' + suffix] + caf = root[vendors[i] + 'Cancel' + suffix] + || root[vendors[i] + 'CancelRequest' + suffix] +} + +// Some versions of FF have rAF but not cAF +if(!raf || !caf) { + var last = 0 + , id = 0 + , queue = [] + , frameDuration = 1000 / 60 + + raf = function(callback) { + if(queue.length === 0) { + var _now = _$performanceNow_346() + , next = Math.max(0, frameDuration - (_now - last)) + last = next + _now + setTimeout(function() { + var cp = queue.slice(0) + // Clear queue here to prevent + // callbacks from appending listeners + // to the current frame's queue + queue.length = 0 + for(var i = 0; i < cp.length; i++) { + if(!cp[i].cancelled) { + try{ + cp[i].callback(last) + } catch(e) { + setTimeout(function() { throw e }, 0) + } + } + } + }, Math.round(next)) + } + queue.push({ + handle: ++id, + callback: callback, + cancelled: false + }) + return id + } + + caf = function(handle) { + for(var i = 0; i < queue.length; i++) { + if(queue[i].handle === handle) { + queue[i].cancelled = true + } + } + } +} + +_$raf_368 = function(fn) { + // Wrap in a new function to prevent + // `cancel` potentially being assigned + // to the native rAF function + return raf.call(root, fn) +} +_$raf_368.cancel = function() { + caf.apply(root, arguments) +} +_$raf_368.polyfill = function(object) { + if (!object) { + object = root; + } + object.requestAnimationFrame = raf + object.cancelAnimationFrame = caf +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +'use strict' + + +/* removed: var _$Scatter_377 = require('regl-scatter2d/scatter') */; +/* removed: var _$flattenVertexData_198 = require('flatten-vertex-data') */; +/* removed: var _$pick_349 = require('pick-by-alias') */; +/* removed: var _$normalize_49 = require('array-bounds') */; +/* removed: var _$raf_368 = require('raf') */; +/* removed: var _$newArray_51 = require('array-range') */; +/* removed: var _$parseRect_343 = require('parse-rect') */; + + +var _$SPLOM_378 = SPLOM + + +// @constructor +function SPLOM (regl, options) { + if (!(this instanceof SPLOM)) { return new SPLOM(regl, options) } + + // render passes + this.traces = [] + + // passes for scatter, combined across traces + this.passes = {} + + this.regl = regl + + // main scatter drawing instance + this.scatter = _$Scatter_377(regl) + + this.canvas = this.scatter.canvas +} + + +// update & draw passes once per frame +SPLOM.prototype.render = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (args.length) { + (ref = this).update.apply(ref, args) + } + + if (this.regl.attributes.preserveDrawingBuffer) { return this.draw() } + + // make sure draw is not called more often than once a frame + if (this.dirty) { + if (this.planned == null) { + this.planned = _$raf_368(function () { + this$1.draw() + this$1.dirty = true + this$1.planned = null + }) + } + } + else { + this.draw() + this.dirty = true + _$raf_368(function () { + this$1.dirty = false + }) + } + + return this + var ref; +} + + +// update passes +SPLOM.prototype.update = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { return } + + for (var i = 0; i < args.length; i++) { + this$1.updateItem(i, args[i]) + } + + // remove nulled passes + this.traces = this.traces.filter(Boolean) + + // FIXME: update passes independently + var passes = [] + var offset = 0 + for (var i$1 = 0; i$1 < this.traces.length; i$1++) { + var trace = this$1.traces[i$1] + var tracePasses = this$1.traces[i$1].passes + for (var j = 0; j < tracePasses.length; j++) { + passes.push(this$1.passes[tracePasses[j]]) + } + // save offset of passes + trace.passOffset = offset + offset += trace.passes.length + } + + (ref = this.scatter).update.apply(ref, passes) + + return this + var ref; +} + + +// update trace by index, not supposed to be called directly +SPLOM.prototype.updateItem = function (i, options) { + var this$1 = this; + + var ref = this; + var regl = ref.regl; + + // remove pass if null + if (options === null) { + this.traces[i] = null + return this + } + + if (!options) { return this } + + var o = _$pick_349(options, { + data: 'data items columns rows values dimensions samples x', + snap: 'snap cluster', + size: 'sizes size radius', + color: 'colors color fill fill-color fillColor', + opacity: 'opacity alpha transparency opaque', + borderSize: 'borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline', + borderColor: 'borderColors borderColor bordercolor stroke stroke-color strokeColor', + marker: 'markers marker shape', + range: 'range ranges databox dataBox', + viewport: 'viewport viewBox viewbox', + domain: 'domain domains area areas', + padding: 'pad padding paddings pads margin margins', + transpose: 'transpose transposed', + diagonal: 'diagonal diag showDiagonal', + upper: 'upper up top upperhalf upperHalf showupperhalf showUpper showUpperHalf', + lower: 'lower low bottom lowerhalf lowerHalf showlowerhalf showLowerHalf showLower' + }) + + // we provide regl buffer per-trace, since trace data can be changed + var trace = (this.traces[i] || (this.traces[i] = { + id: i, + buffer: regl.buffer({ + usage: 'dynamic', + type: 'float', + data: null + }), + color: 'black', + marker: null, + size: 12, + borderColor: 'transparent', + borderSize: 1, + viewport: _$parseRect_343([regl._gl.drawingBufferWidth, regl._gl.drawingBufferHeight]), + padding: [0, 0, 0, 0], + opacity: 1, + diagonal: true, + upper: true, + lower: true + })) + + + // save styles + if (o.color != null) { + trace.color = o.color + } + if (o.size != null) { + trace.size = o.size + } + if (o.marker != null) { + trace.marker = o.marker + } + if (o.borderColor != null) { + trace.borderColor = o.borderColor + } + if (o.borderSize != null) { + trace.borderSize = o.borderSize + } + if (o.opacity != null) { + trace.opacity = o.opacity + } + if (o.viewport) { + trace.viewport = _$parseRect_343(o.viewport) + } + if (o.diagonal != null) { trace.diagonal = o.diagonal } + if (o.upper != null) { trace.upper = o.upper } + if (o.lower != null) { trace.lower = o.lower } + + // put flattened data into buffer + if (o.data) { + trace.buffer(_$flattenVertexData_198(o.data)) + trace.columns = o.data.length + trace.count = o.data[0].length + + // detect bounds per-column + trace.bounds = [] + + for (var i$1 = 0; i$1 < trace.columns; i$1++) { + trace.bounds[i$1] = _$normalize_49(o.data[i$1], 1) + } + } + + // add proper range updating markers + var multirange + if (o.range) { + trace.range = o.range + multirange = trace.range && typeof trace.range[0] !== 'number' + } + + if (o.domain) { + trace.domain = o.domain + } + var multipadding = false + if (o.padding != null) { + // multiple paddings + if (Array.isArray(o.padding) && o.padding.length === trace.columns && typeof o.padding[o.padding.length - 1] === 'number') { + trace.padding = o.padding.map(getPad) + multipadding = true + } + // single padding + else { + trace.padding = getPad(o.padding) + } + } + + // create passes + var m = trace.columns + var n = trace.count + + var w = trace.viewport.width + var h = trace.viewport.height + var left = trace.viewport.x + var top = trace.viewport.y + var iw = w / m + var ih = h / m + + trace.passes = [] + + for (var i$2 = 0; i$2 < m; i$2++) { + for (var j = 0; j < m; j++) { + if (!trace.diagonal && j === i$2) { continue } + if (!trace.upper && i$2 > j) { continue } + if (!trace.lower && i$2 < j) { continue } + + var key = passId(trace.id, i$2, j) + + var pass = this$1.passes[key] || (this$1.passes[key] = {}) + + if (o.data) { + if (o.transpose) { + pass.positions = { + x: {buffer: trace.buffer, offset: j, count: n, stride: m}, + y: {buffer: trace.buffer, offset: i$2, count: n, stride: m} + } + } + else { + pass.positions = { + x: {buffer: trace.buffer, offset: j * n, count: n}, + y: {buffer: trace.buffer, offset: i$2 * n, count: n} + } + } + + pass.bounds = getBox(trace.bounds, i$2, j) + } + + if (o.domain || o.viewport || o.data) { + var pad = multipadding ? getBox(trace.padding, i$2, j) : trace.padding + if (trace.domain) { + var ref$1 = getBox(trace.domain, i$2, j); + var lox = ref$1[0]; + var loy = ref$1[1]; + var hix = ref$1[2]; + var hiy = ref$1[3]; + + pass.viewport = [ + left + lox * w + pad[0], + top + loy * h + pad[1], + left + hix * w - pad[2], + top + hiy * h - pad[3] + ] + } + // consider auto-domain equipartial + else { + pass.viewport = [ + left + j * iw + iw * pad[0], + top + i$2 * ih + ih * pad[1], + left + (j + 1) * iw - iw * pad[2], + top + (i$2 + 1) * ih - ih * pad[3] + ] + } + } + + if (o.color) { pass.color = trace.color } + if (o.size) { pass.size = trace.size } + if (o.marker) { pass.marker = trace.marker } + if (o.borderSize) { pass.borderSize = trace.borderSize } + if (o.borderColor) { pass.borderColor = trace.borderColor } + if (o.opacity) { pass.opacity = trace.opacity } + + if (o.range) { + pass.range = multirange ? getBox(trace.range, i$2, j) : trace.range || pass.bounds + } + + trace.passes.push(key) + } + } + + return this +} + + +// draw all or passed passes +SPLOM.prototype.draw = function () { + var this$1 = this; + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + if (!args.length) { + this.scatter.draw() + } + else { + var idx = [] + for (var i = 0; i < args.length; i++) { + // draw(0, 2, 5) - draw traces + if (typeof args[i] === 'number' ) { + var ref = this$1.traces[args[i]]; + var passes = ref.passes; + var passOffset = ref.passOffset; + idx.push.apply(idx, _$newArray_51(passOffset, passOffset + passes.length)) + } + // draw([0, 1, 2 ...], [3, 4, 5]) - draw points + else if (args[i].length) { + var els = args[i] + var ref$1 = this$1.traces[i]; + var passes$1 = ref$1.passes; + var passOffset$1 = ref$1.passOffset; + passes$1 = passes$1.map(function (passId, i) { + idx[passOffset$1 + i] = els + }) + } + } + (ref$2 = this.scatter).draw.apply(ref$2, idx) + } + + return this + var ref$2; +} + + +// dispose resources +SPLOM.prototype.destroy = function () { + this.traces.forEach(function (trace) { + if (trace.buffer && trace.buffer.destroy) { trace.buffer.destroy() } + }) + this.traces = null + this.passes = null + + this.scatter.destroy() + + return this +} + + +// return pass corresponding to trace i- j- square +function passId (trace, i, j) { + var id = (trace.id != null ? trace.id : trace) + var n = i + var m = j + var key = id << 16 | (n & 0xff) << 8 | m & 0xff + + return key +} + + +// return bounding box corresponding to a pass +function getBox (items, i, j) { + var ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy + var iitem = items[i], jitem = items[j] + + if (iitem.length > 2) { + ilox = iitem[0] + ihix = iitem[2] + iloy = iitem[1] + ihiy = iitem[3] + } + else if (iitem.length) { + ilox = iloy = iitem[0] + ihix = ihiy = iitem[1] + } + else { + ilox = iitem.x + iloy = iitem.y + ihix = iitem.x + iitem.width + ihiy = iitem.y + iitem.height + } + + if (jitem.length > 2) { + jlox = jitem[0] + jhix = jitem[2] + jloy = jitem[1] + jhiy = jitem[3] + } + else if (jitem.length) { + jlox = jloy = jitem[0] + jhix = jhiy = jitem[1] + } + else { + jlox = jitem.x + jloy = jitem.y + jhix = jitem.x + jitem.width + jhiy = jitem.y + jitem.height + } + + return [ jlox, iloy, jhix, ihiy ] +} + + +function getPad (arg) { + if (typeof arg === 'number') { return [arg, arg, arg, arg] } + else if (arg.length === 2) { return [arg[0], arg[1], arg[0], arg[1]] } + else { + var box = _$parseRect_343(arg) + return [box.x, box.y, box.x + box.width, box.y + box.height] + } +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$attributes_974 = require('../scattergl/attributes'); */; +var __cartesianIdRegex_1003 = _$constants_652.idRegex; + +function makeAxesValObject(axLetter) { + return { + valType: 'info_array', + freeLength: true, + + editType: 'calc', + items: { + valType: 'subplotid', + regex: __cartesianIdRegex_1003[axLetter], + editType: 'plot' + }, + + }; +} + +var _$attributes_1003 = { + dimensions: { + _isLinkedToArray: 'dimension', + + visible: { + valType: 'boolean', + + dflt: true, + editType: 'calc', + + }, + label: { + valType: 'string', + + editType: 'calc', + + }, + values: { + valType: 'data_array', + + 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: _$attributes_974.text, + marker: _$attributes_974.marker, + + 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: _$attributes_974.selected.marker, + editType: 'calc' + }, + unselected: { + marker: _$attributes_974.unselected.marker, + editType: 'calc' + }, + + opacity: _$attributes_974.opacity +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$Line2D_375 = require('regl-line2d'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$prepareRegl_614 = require('../../lib/prepare_regl'); */; +var __getModuleCalcData_1004 = _$get_data_683.getModuleCalcData; +/* removed: var _$cartesian_658 = require('../../plots/cartesian'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +var __SPLOM_1004 = 'splom'; + +function __plot_1004(gd) { + var fullLayout = gd._fullLayout; + var _module = _$registry_731.getModule(__SPLOM_1004); + var splomCalcData = __getModuleCalcData_1004(gd.calcdata, _module)[0]; + + _$prepareRegl_614(gd, ['ANGLE_instanced_arrays', 'OES_element_index_uint']); + + if(fullLayout._hasOnlyLargeSploms) { + drawGrid(gd); + } + + _module.plot(gd, {}, splomCalcData); +} + +function drag(gd) { + var cd = gd.calcdata; + var fullLayout = gd._fullLayout; + + if(fullLayout._hasOnlyLargeSploms) { + drawGrid(gd); + } + + for(var i = 0; i < cd.length; i++) { + var cd0 = cd[i][0]; + var trace = cd0.trace; + var scene = cd0.t._scene; + + if(trace.type === 'splom' && scene && scene.matrix) { + dragOne(gd, trace, scene); + } + } +} + +function dragOne(gd, trace, scene) { + var dimensions = trace.dimensions; + var visibleLength = scene.matrixOptions.data.length; + var ranges = new Array(visibleLength); + + for(var i = 0, k = 0; i < dimensions.length; i++) { + if(dimensions[i].visible) { + var rng = ranges[k] = new Array(4); + + var xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]); + if(xa) { + rng[0] = xa.r2l(xa.range[0]); + rng[2] = xa.r2l(xa.range[1]); + } + + var ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]); + if(ya) { + rng[1] = ya.r2l(ya.range[0]); + rng[3] = ya.r2l(ya.range[1]); + } + + k++; + } + } + + if(scene.selectBatch) { + scene.matrix.update({ranges: ranges}, {ranges: ranges}); + scene.matrix.draw(scene.unselectBatch, scene.selectBatch); + } else { + scene.matrix.update({ranges: ranges}); + scene.matrix.draw(); + } +} + +function drawGrid(gd) { + var fullLayout = gd._fullLayout; + var regl = fullLayout._glcanvas.data()[0].regl; + var splomGrid = fullLayout._splomGrid; + + if(!splomGrid) { + splomGrid = fullLayout._splomGrid = _$Line2D_375(regl); + } + + splomGrid.update(makeGridData(gd)); + splomGrid.draw(); +} + +function makeGridData(gd) { + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var fullView = [0, 0, fullLayout.width, fullLayout.height]; + var lookup = {}; + var k; + + function push(prefix, ax, x0, x1, y0, y1) { + var lcolor = ax[prefix + 'color']; + var lwidth = ax[prefix + 'width']; + var key = String(lcolor + lwidth); + + if(key in lookup) { + lookup[key].data.push(NaN, NaN, x0, x1, y0, y1); + } else { + lookup[key] = { + data: [x0, x1, y0, y1], + join: 'rect', + thickness: lwidth, + color: lcolor, + viewport: fullView, + range: fullView, + overlay: false + }; + } + } + + for(k in fullLayout._splomSubplots) { + var sp = fullLayout._plots[k]; + var xa = sp.xaxis; + var ya = sp.yaxis; + var xVals = xa._vals; + var yVals = ya._vals; + // ya.l2p assumes top-to-bottom coordinate system (a la SVG), + // we need to compute bottom-to-top offsets and slopes: + var yOffset = gs.b + ya.domain[0] * gs.h; + var ym = -ya._m; + var yb = -ym * ya.r2l(ya.range[0], ya.calendar); + var x, y; + + if(xa.showgrid) { + for(k = 0; k < xVals.length; k++) { + x = xa._offset + xa.l2p(xVals[k].x); + push('grid', xa, x, yOffset, x, yOffset + ya._length); + } + } + if(showZeroLine(xa)) { + x = xa._offset + xa.l2p(0); + push('zeroline', xa, x, yOffset, x, yOffset + ya._length); + } + if(ya.showgrid) { + for(k = 0; k < yVals.length; k++) { + y = yOffset + yb + ym * yVals[k].x; + push('grid', ya, xa._offset, y, xa._offset + xa._length, y); + } + } + if(showZeroLine(ya)) { + y = yOffset + yb + 0; + push('zeroline', ya, xa._offset, y, xa._offset + xa._length, y); + } + } + + var gridBatches = []; + for(k in lookup) { + gridBatches.push(lookup[k]); + } + + return gridBatches; +} + +// just like in Axes.doTicks but without the loop over traces +function showZeroLine(ax) { + var rng = _$lib_601.simpleMap(ax.range, ax.r2l); + var p0 = ax.l2p(0); + + return ( + ax.zeroline && + ax._vals && ax._vals.length && + (rng[0] * rng[1] <= 0) && + (ax.type === 'linear' || ax.type === '-') && + ((p0 > 1 && p0 < ax._length - 1) || !ax.showline) + ); +} + +function __clean_1004(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) { + var oldModules = oldFullLayout._modules || []; + var newModules = newFullLayout._modules || []; + + var hadSplom, hasSplom; + var i; + + for(i = 0; i < oldModules.length; i++) { + if(oldModules[i].name === 'splom') { + hadSplom = true; + break; + } + } + for(i = 0; i < newModules.length; i++) { + if(newModules[i].name === 'splom') { + hasSplom = true; + break; + } + } + + if(hadSplom && !hasSplom) { + for(i = 0; i < oldCalcdata.length; i++) { + var cd0 = oldCalcdata[i][0]; + var trace = cd0.trace; + var scene = cd0.t._scene; + + if(trace.type === 'splom' && scene && scene.matrix) { + scene.matrix.destroy(); + cd0.t._scene = null; + } + } + } + + if(oldFullLayout._splomGrid && + (!newFullLayout._hasOnlyLargeSploms && oldFullLayout._hasOnlyLargeSploms)) { + oldFullLayout._splomGrid.destroy(); + oldFullLayout._splomGrid = null; + } + + _$cartesian_658.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); +} + +var _$base_plot_1004 = { + name: __SPLOM_1004, + attr: _$cartesian_658.attr, + attrRegex: _$cartesian_658.attrRegex, + layoutAttributes: _$cartesian_658.layoutAttributes, + supplyLayoutDefaults: _$cartesian_658.supplyLayoutDefaults, + drawFramework: _$cartesian_658.drawFramework, + plot: __plot_1004, + drag: drag, + clean: __clean_1004, + updateFx: _$cartesian_658.updateFx, + toSVG: _$cartesian_658.toSVG +}; + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$lib_601 = require('../../lib'); */; + +/* removed: var _$attributes_1003 = require('./attributes'); */; +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +/* removed: var _$markerDefaults_945 = require('../scatter/marker_defaults'); */; +var OPEN_RE = /-open/; + +var _$supplyDefaults_1005 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce(attr, dflt) { + return _$lib_601.coerce(traceIn, traceOut, _$attributes_1003, attr, dflt); + } + + var dimLength = handleDimensionsDefaults(traceIn, traceOut); + + var showDiag = coerce('diagonal.visible'); + var showUpper = coerce('showupperhalf'); + var showLower = coerce('showlowerhalf'); + + if(!dimLength || (!showDiag && !showUpper && !showLower)) { + traceOut.visible = false; + return; + } + + coerce('text'); + + _$markerDefaults_945(traceIn, traceOut, defaultColor, layout, coerce); + + var isOpen = OPEN_RE.test(traceOut.marker.symbol); + var isBubble = _$subtypes_949.isBubble(traceOut); + coerce('marker.line.width', isOpen || isBubble ? 1 : 0); + + __handleAxisDefaults_1005(traceIn, traceOut, layout, coerce); + + _$lib_601.coerceSelectionMarkerOpacity(traceOut, coerce); +}; + +function handleDimensionsDefaults(traceIn, traceOut) { + var dimensionsIn = traceIn.dimensions; + if(!Array.isArray(dimensionsIn)) return 0; + + var dimLength = dimensionsIn.length; + var commonLength = 0; + var dimensionsOut = traceOut.dimensions = new Array(dimLength); + var dimIn; + var dimOut; + var i; + + function coerce(attr, dflt) { + return _$lib_601.coerce(dimIn, dimOut, _$attributes_1003.dimensions, attr, dflt); + } + + for(i = 0; i < dimLength; i++) { + dimIn = dimensionsIn[i]; + dimOut = dimensionsOut[i] = {}; + + // coerce label even if dimensions may be `visible: false`, + // to fill in axis title defaults + coerce('label'); + + // wait until plot step to filter out visible false dimensions + var visible = coerce('visible'); + if(!visible) continue; + + var values = coerce('values'); + if(!values || !values.length) { + dimOut.visible = false; + continue; + } + + commonLength = Math.max(commonLength, values.length); + dimOut._index = i; + } + + for(i = 0; i < dimLength; i++) { + dimOut = dimensionsOut[i]; + if(dimOut.visible) dimOut._length = commonLength; + } + + traceOut._commonLength = commonLength; + + return dimensionsOut.length; +} + +function __handleAxisDefaults_1005(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; + + // N.B. one less x axis AND one less y axis when hiding one half and the diagonal + var axDfltLength = !showDiag && (!showUpper || !showLower) ? dimLength - 1 : dimLength; + + var xaxes = coerce('xaxes', fillAxisIdArray('x', axDfltLength)); + var yaxes = coerce('yaxes', fillAxisIdArray('y', axDfltLength)); + + // to avoid costly indexOf + traceOut._xaxes = arrayToHashObject(xaxes); + traceOut._yaxes = arrayToHashObject(yaxes); + + // allow users to under-specify number of axes + var axLength = Math.min(axDfltLength, xaxes.length, yaxes.length); + + // fill in splom subplot keys + for(i = 0; i < axLength; i++) { + for(j = 0; j < axLength; j++) { + var id = [xaxes[i] + yaxes[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; + } + } + } + + // 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); + + // cases where showDiag and showLower or showUpper are false + // no special treatment as the xaxes and yaxes items no longer match + // the dimensions items 1-to-1 + var xShift = !showDiag && !showLower ? -1 : 0; + var yShift = !showDiag && !showUpper ? -1 : 0; + + for(i = 0; i < dimLength; i++) { + var dim = dimensions[i]; + var xa = xaxes[i + xShift]; + var ya = yaxes[i + yShift]; + + fillAxisStash(layout, xa, dim); + fillAxisStash(layout, ya, dim); + + // note that some the entries here may be undefined + diag[i] = [xa, ya]; + } +} + +function fillAxisIdArray(axLetter, len) { + var out = new Array(len); + + for(var i = 0; i < len; i++) { + out[i] = axLetter + (i ? i + 1 : ''); + } + + return out; +} + +function fillAxisStash(layout, axId, dim) { + if(!axId) return; + + var axLetter = axId.charAt(0); + var stash = layout._splomAxes[axLetter]; + + if(!(axId in stash)) { + stash[axId] = (dim || {}).label || ''; + } +} + +function arrayToHashObject(arr) { + var obj = {}; + for(var i = 0; i < arr.length; i++) { + obj[arr[i]] = 1; + } + return obj; +} + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +/* removed: var _$SPLOM_378 = require('regl-splom'); */; +/* removed: var _$newArray_51 = require('array-range'); */; + +/* removed: var _$registry_731 = require('../../registry'); */; +/* removed: var _$grid_519 = require('../../components/grid'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axis_ids_650 = require('../../plots/cartesian/axis_ids'); */; + +/* removed: var _$subtypes_949 = require('../scatter/subtypes'); */; +var __calcMarkerSize_1006 = _$calc_928.calcMarkerSize; +var __calcAxisExpansion_1006 = _$calc_928.calcAxisExpansion; +/* removed: var _$calcMarkerColorscale_932 = require('../scatter/colorscale_calc'); */; +var __convertMarkerSelection_1006 = _$convert_976.convertMarkerSelection; +var __convertMarkerStyle_1006 = _$convert_976.convertMarkerStyle; +var __calcHover_1006 = _$scattergl_978.calcHover; + +var __BADNUM_1006 = _$numerical_578.BADNUM; +var __TOO_MANY_POINTS_1006 = _$constants_975.TOO_MANY_POINTS; + +function __calc_1006(gd, trace) { + var dimensions = trace.dimensions; + var commonLength = trace._commonLength; + var stash = {}; + var opts = {}; + // 'c' for calculated, 'l' for linear, + // only differ here for log axes, pass ldata to createMatrix as 'data' + var cdata = opts.cdata = []; + var ldata = opts.data = []; + var i, k, dim; + + for(i = 0; i < dimensions.length; i++) { + dim = dimensions[i]; + + if(dim.visible) { + var axId = trace._diag[i][0] || trace._diag[i][1]; + var ax = _$axis_ids_650.getFromId(gd, axId); + if(ax) { + var ccol = makeCalcdata(ax, trace, dim); + var lcol = ax.type === 'log' ? _$lib_601.simpleMap(ccol, ax.c2l) : ccol; + cdata.push(ccol); + ldata.push(lcol); + } + } + } + + _$calcMarkerColorscale_932(trace); + _$lib_601.extendFlat(opts, __convertMarkerStyle_1006(trace)); + + var visibleLength = cdata.length; + var hasTooManyPoints = (visibleLength * commonLength) > __TOO_MANY_POINTS_1006; + + for(i = 0, k = 0; i < dimensions.length; i++) { + dim = dimensions[i]; + + if(dim.visible) { + var xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]) || {}; + var ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]) || {}; + + // Re-use SVG scatter axis expansion routine except + // for graph with very large number of points where it + // performs poorly. + // In big data case, fake Axes.expand outputs with data bounds, + // and an average size for array marker.size inputs. + var ppad; + if(hasTooManyPoints) { + ppad = 2 * (opts.sizeAvg || Math.max(opts.size, 3)); + } else { + ppad = __calcMarkerSize_1006(trace, commonLength); + } + + __calcAxisExpansion_1006(gd, trace, xa, ya, cdata[k], cdata[k], ppad); + k++; + } + } + + var scene = stash._scene = __sceneUpdate_1006(gd, stash); + if(!scene.matrix) scene.matrix = true; + scene.matrixOptions = opts; + + scene.selectedOptions = __convertMarkerSelection_1006(trace, trace.selected); + scene.unselectedOptions = __convertMarkerSelection_1006(trace, trace.unselected); + + return [{x: false, y: false, t: stash, trace: trace}]; +} + +function makeCalcdata(ax, trace, dim) { + // call makeCalcdata with fake input + var ccol = ax.makeCalcdata({ + v: dim.values, + vcalendar: trace.calendar + }, 'v'); + + for(var i = 0; i < ccol.length; i++) { + ccol[i] = ccol[i] === __BADNUM_1006 ? NaN : ccol[i]; + } + + return ccol; +} + +function __sceneUpdate_1006(gd, stash) { + var scene = stash._scene; + + var reset = { + dirty: true + }; + + var first = { + selectBatch: null, + unselectBatch: null, + matrix: false, + select: null + }; + + if(!scene) { + scene = stash._scene = _$lib_601.extendFlat({}, reset, first); + + scene.draw = function draw() { + // draw traces in selection mode + if(scene.matrix && scene.selectBatch) { + scene.matrix.draw(scene.unselectBatch, scene.selectBatch); + } + + else if(scene.matrix) { + scene.matrix.draw(); + } + + scene.dirty = false; + }; + + // remove scene resources + scene.destroy = function destroy() { + if(scene.matrix) scene.matrix.destroy(); + + scene.matrixOptions = null; + scene.selectBatch = null; + scene.unselectBatch = null; + + stash._scene = null; + }; + } + + // In case if we have scene from the last calc - reset data + if(!scene.dirty) { + _$lib_601.extendFlat(scene, reset); + } + + return scene; +} + +function __plot_1006(gd, _, splomCalcData) { + if(!splomCalcData.length) return; + + for(var i = 0; i < splomCalcData.length; i++) { + __plotOne_1006(gd, splomCalcData[i][0]); + } +} + +function __plotOne_1006(gd, cd0) { + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var trace = cd0.trace; + var stash = cd0.t; + var scene = stash._scene; + var matrixOpts = scene.matrixOptions; + var cdata = matrixOpts.cdata; + var regl = fullLayout._glcanvas.data()[0].regl; + var dragmode = fullLayout.dragmode; + var xa, ya; + var i, j, k; + + if(cdata.length === 0) return; + + // augment options with proper upper/lower halves + // regl-splom's default grid starts from bottom-left + matrixOpts.lower = trace.showupperhalf; + matrixOpts.upper = trace.showlowerhalf; + matrixOpts.diagonal = trace.diagonal.visible; + + var dimensions = trace.dimensions; + var visibleLength = cdata.length; + var viewOpts = {}; + viewOpts.ranges = new Array(visibleLength); + viewOpts.domains = new Array(visibleLength); + + for(i = 0, k = 0; i < dimensions.length; i++) { + if(trace.dimensions[i].visible) { + var rng = viewOpts.ranges[k] = new Array(4); + var dmn = viewOpts.domains[k] = new Array(4); + + xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]); + if(xa) { + rng[0] = xa._rl[0]; + rng[2] = xa._rl[1]; + dmn[0] = xa.domain[0]; + dmn[2] = xa.domain[1]; + } + + ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]); + if(ya) { + rng[1] = ya._rl[0]; + rng[3] = ya._rl[1]; + dmn[1] = ya.domain[0]; + dmn[3] = ya.domain[1]; + } + + k++; + } + } + + viewOpts.viewport = [gs.l, gs.b, gs.w + gs.l, gs.h + gs.b]; + + if(scene.matrix === true) { + scene.matrix = _$SPLOM_378(regl); + } + + var selectMode = dragmode === 'lasso' || dragmode === 'select' || !!trace.selectedpoints; + scene.selectBatch = null; + scene.unselectBatch = null; + + if(selectMode) { + var commonLength = trace._commonLength; + + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } + + // regenerate scene batch, if traces number changed during selection + if(trace.selectedpoints) { + scene.selectBatch = trace.selectedpoints; + + var selPts = trace.selectedpoints; + var selDict = {}; + for(i = 0; i < selPts.length; i++) { + selDict[selPts[i]] = true; + } + var unselPts = []; + for(i = 0; i < commonLength; i++) { + if(!selDict[i]) unselPts.push(i); + } + scene.unselectBatch = unselPts; + } + + // precalculate px coords since we are not going to pan during select + var xpx = stash.xpx = new Array(visibleLength); + var ypx = stash.ypx = new Array(visibleLength); + + for(i = 0, k = 0; i < dimensions.length; i++) { + if(trace.dimensions[i].visible) { + xa = _$axis_ids_650.getFromId(gd, trace._diag[i][0]); + if(xa) { + xpx[k] = new Array(commonLength); + for(j = 0; j < commonLength; j++) { + xpx[k][j] = xa.c2p(cdata[k][j]); + } + } + + ya = _$axis_ids_650.getFromId(gd, trace._diag[i][1]); + if(ya) { + ypx[k] = new Array(commonLength); + for(j = 0; j < commonLength; j++) { + ypx[k][j] = ya.c2p(cdata[k][j]); + } + } + + k++; + } + } + + if(scene.selectBatch) { + scene.matrix.update(matrixOpts, matrixOpts); + scene.matrix.update(scene.unselectedOptions, scene.selectedOptions); + scene.matrix.update(viewOpts, viewOpts); + } + else { + // delete selection pass + scene.matrix.update(viewOpts, null); + } + } + else { + scene.matrix.update(matrixOpts); + scene.matrix.update(viewOpts); + stash.xpx = stash.ypx = null; + } + + scene.draw(); +} + +function __hoverPoints_1006(pointData, xval, yval) { + var cd = pointData.cd; + var trace = cd[0].trace; + var stash = cd[0].t; + var scene = stash._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 = getDimIndex(trace, xa); + var yi = 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]; + + __calcHover_1006(pointData, x, y, trace); + + return [pointData]; +} + +function __selectPoints_1006(searchInfo, polygon) { + var cd = searchInfo.cd; + var trace = cd[0].trace; + var stash = cd[0].t; + var scene = stash._scene; + var cdata = scene.matrixOptions.cdata; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + + if(!scene) return selection; + + var hasOnlyLines = (!_$subtypes_949.hasMarkers(trace) && !_$subtypes_949.hasText(trace)); + if(trace.visible !== true || hasOnlyLines) return selection; + + var xi = getDimIndex(trace, xa); + var yi = 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]; + + // degenerate polygon does not enable selection + // filter out points by visible scatter ones + var els = null; + var unels = null; + if(polygon !== false && !polygon.degenerate) { + els = [], unels = []; + for(i = 0; i < x.length; i++) { + if(polygon.contains([xpx[i], ypx[i]])) { + els.push(i); + selection.push({ + pointNumber: i, + x: x[i], + y: y[i] + }); + } + else { + unels.push(i); + } + } + } else { + unels = _$newArray_51(stash.count); + } + + // make sure selectBatch is created + if(!scene.selectBatch) { + scene.selectBatch = []; + scene.unselectBatch = []; + } + + if(!scene.selectBatch) { + // enter every trace select mode + for(i = 0; i < scene.count; i++) { + scene.selectBatch = []; + scene.unselectBatch = []; + } + // we should turn scatter2d into unselected once we have any points selected + scene.matrix.update(scene.unselectedOptions, scene.selectedOptions); + } + + scene.selectBatch = els; + scene.unselectBatch = unels; + + + return selection; +} + +function __style_1006(gd, cds) { + if(!cds) return; + + var fullLayout = gd._fullLayout; + var cd0 = cds[0]; + var scene0 = cd0[0].t._scene; + scene0.matrix.regl.clear({color: true, depth: true}); + + if(fullLayout._splomGrid) { + fullLayout._splomGrid.draw(); + } + + for(var i = 0; i < cds.length; i++) { + var scene = cds[i][0].t._scene; + scene.draw(); + } + + // redraw all subplot with scattergl traces, + // as we cleared the whole canvas above + if(fullLayout._has('cartesian')) { + for(var k in fullLayout._plots) { + var sp = fullLayout._plots[k]; + if(sp._scene) sp._scene.draw(); + } + } +} + +function getDimIndex(trace, ax) { + var axId = ax._id; + var axLetter = axId.charAt(0); + var ind = {x: 0, y: 1}[axLetter]; + var dimensions = trace.dimensions; + + for(var i = 0, k = 0; i < dimensions.length; i++) { + if(dimensions[i].visible) { + if(trace._diag[i][ind] === axId) return k; + k++; + } + } + return false; +} + +var _$splom_1006 = { + moduleType: 'trace', + name: 'splom', + + basePlotModule: _$base_plot_1004, + categories: ['gl', 'regl', 'cartesian', 'symbols', 'markerColorscale', 'showLegend', 'scatter-like'], + + attributes: _$attributes_1003, + supplyDefaults: _$supplyDefaults_1005, + + calc: __calc_1006, + plot: __plot_1006, + hoverPoints: __hoverPoints_1006, + selectPoints: __selectPoints_1006, + style: __style_1006, + + meta: { + + } +}; + +// splom traces use the 'grid' component to generate their axes, +// register it here +_$registry_731.register(_$grid_519); + +/** +* Copyright 2012-2018, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var _$splom_36 = _$splom_1006; /** * Copyright 2012-2018, Plotly, Inc. @@ -176482,15 +180228,15 @@ var _$sort_35 = _$sort_966; 'use strict'; -/* removed: var _$calc_418 = require('../../components/colorscale/calc'); */; +/* removed: var _$calc_480 = require('../../components/colorscale/calc'); */; // Compute auto-z and autocolorscale if applicable -var _$calc_937 = function calc(gd, trace) { +var _$calc_1008 = function calc(gd, trace) { if(trace.surfacecolor) { - _$calc_418(trace, trace.surfacecolor, '', 'c'); + _$calc_480(trace, trace.surfacecolor, '', 'c'); } else { - _$calc_418(trace, trace.z, '', 'c'); + _$calc_480(trace, trace.z, '', 'c'); } }; @@ -176505,34 +180251,34 @@ var _$calc_937 = function calc(gd, trace) { 'use strict'; -/* removed: var _$fastIsnumeric_139 = require('fast-isnumeric'); */; +/* removed: var _$fastIsnumeric_196 = require('fast-isnumeric'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$plots_647 = require('../../plots/plots'); */; -/* removed: var _$colorscale_426 = require('../../components/colorscale'); */; -/* removed: var _$draw_415 = require('../../components/colorbar/draw'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$plots_709 = require('../../plots/plots'); */; +/* removed: var _$colorscale_488 = require('../../components/colorscale'); */; +/* removed: var _$draw_477 = require('../../components/colorbar/draw'); */; -var _$colorbar_938 = function colorbar(gd, cd) { +var _$colorbar_1009 = function colorbar(gd, cd) { var trace = cd[0].trace, cbId = 'cb' + trace.uid, cmin = trace.cmin, cmax = trace.cmax, vals = trace.surfacecolor || trace.z; - if(!_$fastIsnumeric_139(cmin)) cmin = _$lib_539.aggNums(Math.min, null, vals); - if(!_$fastIsnumeric_139(cmax)) cmax = _$lib_539.aggNums(Math.max, null, vals); + if(!_$fastIsnumeric_196(cmin)) cmin = _$lib_601.aggNums(Math.min, null, vals); + if(!_$fastIsnumeric_196(cmax)) cmax = _$lib_601.aggNums(Math.max, null, vals); gd._fullLayout._infolayer.selectAll('.' + cbId).remove(); if(!trace.showscale) { - _$plots_647.autoMargin(gd, cbId); + _$plots_709.autoMargin(gd, cbId); return; } - var cb = cd[0].t.cb = _$draw_415(gd, cbId); - var sclFunc = _$colorscale_426.makeColorScaleFunc( - _$colorscale_426.extractScale( + var cb = cd[0].t.cb = _$draw_477(gd, cbId); + var sclFunc = _$colorscale_488.makeColorScaleFunc( + _$colorscale_488.extractScale( trace.colorscale, cmin, cmax @@ -176545,17 +180291,17 @@ var _$colorbar_938 = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -var _$shaders_216 = {}; -/* removed: var _$createShader_206 = require('gl-shader') */; -/* removed: var _$browser_238 = require('glslify') */; +var _$shaders_273 = {}; +/* removed: var _$createShader_263 = require('gl-shader') */; +/* removed: var _$browser_295 = require('glslify') */; -var __vertSrc_216 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\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 worldCoordinate = vec3(uv.zw, f.x);\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_216 = _$browser_238(["precision mediump 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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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_216 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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 = _$browser_238(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]) +var __vertSrc_273 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\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 worldCoordinate = vec3(uv.zw, f.x);\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_273 = _$browser_295(["precision mediump 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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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_273 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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 = _$browser_295(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]) -_$shaders_216.createShader = function (gl) { - var shader = _$createShader_206(gl, __vertSrc_216, __fragSrc_216, null, [ +_$shaders_273.createShader = function (gl) { + var shader = _$createShader_263(gl, __vertSrc_273, __fragSrc_273, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'vec3'}, {name: 'normal', type: 'vec3'} @@ -176565,8 +180311,8 @@ _$shaders_216.createShader = function (gl) { shader.attributes.normal.location = 2 return shader } -_$shaders_216.createPickShader = function (gl) { - var shader = _$createShader_206(gl, __vertSrc_216, pickSrc, null, [ +_$shaders_273.createPickShader = function (gl) { + var shader = _$createShader_263(gl, __vertSrc_273, pickSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'vec3'}, {name: 'normal', type: 'vec3'} @@ -176576,8 +180322,8 @@ _$shaders_216.createPickShader = function (gl) { shader.attributes.normal.location = 2 return shader } -_$shaders_216.createContourShader = function (gl) { - var shader = _$createShader_206(gl, __contourVertSrc_216, __fragSrc_216, null, [ +_$shaders_273.createContourShader = function (gl) { + var shader = _$createShader_263(gl, __contourVertSrc_273, __fragSrc_273, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'float'} ]) @@ -176585,8 +180331,8 @@ _$shaders_216.createContourShader = function (gl) { shader.attributes.f.location = 1 return shader } -_$shaders_216.createPickContourShader = function (gl) { - var shader = _$createShader_206(gl, __contourVertSrc_216, pickSrc, null, [ +_$shaders_273.createPickContourShader = function (gl) { + var shader = _$createShader_263(gl, __contourVertSrc_273, pickSrc, null, [ {name: 'uv', type: 'vec4'}, {name: 'f', type: 'float'} ]) @@ -176597,25 +180343,25 @@ _$shaders_216.createPickContourShader = function (gl) { 'use strict' -var _$gradient_268 = __gradient_268 +var _$gradient_326 = __gradient_326 -/* removed: var _$dupe_133 = require('dup') */; -/* removed: var _$compileCwise_115 = require('cwise-compiler') */; +/* removed: var _$dupe_136 = require('dup') */; +/* removed: var _$compileCwise_116 = require('cwise-compiler') */; var TEMPLATE_CACHE = {} var GRADIENT_CACHE = {} -var __EmptyProc_268 = { +var __EmptyProc_326 = { body: "", args: [], thisVars: [], localVars: [] } -var centralDiff = _$compileCwise_115({ +var centralDiff = _$compileCwise_116({ args: [ 'array', 'array', 'array' ], - pre: __EmptyProc_268, - post: __EmptyProc_268, + pre: __EmptyProc_326, + post: __EmptyProc_326, body: { args: [ { name: 'out', @@ -176640,10 +180386,10 @@ var centralDiff = _$compileCwise_115({ funcName: 'cdiff' }) -var zeroOut = _$compileCwise_115({ +var zeroOut = _$compileCwise_116({ args: [ 'array' ], - pre: __EmptyProc_268, - post: __EmptyProc_268, + pre: __EmptyProc_326, + post: __EmptyProc_326, body: { args: [ { name: 'out', @@ -176671,7 +180417,7 @@ function generateTemplate(d) { for(var i=0; i= 1) { return true } @@ -177108,9 +180854,9 @@ __proto_217.isOpaque = function () { return false } -__proto_217.pickSlots = 1 +__proto_274.pickSlots = 1 -__proto_217.setPickBase = function (id) { +__proto_274.setPickBase = function (id) { this.pickId = id } @@ -177119,7 +180865,7 @@ var ZERO_VEC = [0, 0, 0] var PROJECT_DATA = { showSurface: false, showContour: false, - projections: [__IDENTITY_217.slice(), __IDENTITY_217.slice(), __IDENTITY_217.slice()], + projections: [__IDENTITY_274.slice(), __IDENTITY_274.slice(), __IDENTITY_274.slice()], clipBounds: [ [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]], @@ -177153,7 +180899,7 @@ function computeProjectionData (camera, obj) { } axisSquish[5 * i] = 0 axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] - _$multiply_175(axisSquish, camera.model, axisSquish) + _$multiply_232(axisSquish, camera.model, axisSquish) var nclipBounds = PROJECT_DATA.clipBounds[i] for (k = 0; k < 2; ++k) { @@ -177172,10 +180918,10 @@ function computeProjectionData (camera, obj) { } var UNIFORMS = { - model: __IDENTITY_217, - view: __IDENTITY_217, - projection: __IDENTITY_217, - inverseModel: __IDENTITY_217.slice(), + model: __IDENTITY_274, + view: __IDENTITY_274, + projection: __IDENTITY_274, + inverseModel: __IDENTITY_274.slice(), lowerBound: [0, 0, 0], upperBound: [0, 0, 0], colorMap: 0, @@ -177196,7 +180942,7 @@ var UNIFORMS = { vertexColor: 0 } -var MATRIX_INVERSE = __IDENTITY_217.slice() +var MATRIX_INVERSE = __IDENTITY_274.slice() var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] function drawCore (params, transparent) { @@ -177208,14 +180954,14 @@ function drawCore (params, transparent) { this._colorMap.bind(0) var uniforms = UNIFORMS - uniforms.model = params.model || __IDENTITY_217 - uniforms.view = params.view || __IDENTITY_217 - uniforms.projection = params.projection || __IDENTITY_217 + uniforms.model = params.model || __IDENTITY_274 + uniforms.view = params.view || __IDENTITY_274 + uniforms.projection = params.projection || __IDENTITY_274 uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] uniforms.contourColor = this.contourColor[0] - uniforms.inverseModel = _$invert_173(uniforms.inverseModel, uniforms.model) + uniforms.inverseModel = _$invert_230(uniforms.inverseModel, uniforms.model) for (var i = 0; i < 2; ++i) { var clipClamped = uniforms.clipBounds[i] @@ -177239,9 +180985,9 @@ function drawCore (params, transparent) { // Compute camera matrix inverse var invCameraMatrix = MATRIX_INVERSE - _$multiply_175(invCameraMatrix, uniforms.view, uniforms.model) - _$multiply_175(invCameraMatrix, uniforms.projection, invCameraMatrix) - _$invert_173(invCameraMatrix, invCameraMatrix) + _$multiply_232(invCameraMatrix, uniforms.view, uniforms.model) + _$multiply_232(invCameraMatrix, uniforms.projection, invCameraMatrix) + _$invert_230(invCameraMatrix, invCameraMatrix) for (i = 0; i < 3; ++i) { uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15] @@ -177383,19 +181129,19 @@ function drawCore (params, transparent) { } } -__proto_217.draw = function (params) { +__proto_274.draw = function (params) { return drawCore.call(this, params, false) } -__proto_217.drawTransparent = function (params) { +__proto_274.drawTransparent = function (params) { return drawCore.call(this, params, true) } var PICK_UNIFORMS = { - model: __IDENTITY_217, - view: __IDENTITY_217, - projection: __IDENTITY_217, - inverseModel: __IDENTITY_217, + model: __IDENTITY_274, + view: __IDENTITY_274, + projection: __IDENTITY_274, + inverseModel: __IDENTITY_274, clipBounds: [[0, 0, 0], [0, 0, 0]], height: 0.0, shape: [0, 0], @@ -177408,15 +181154,15 @@ var PICK_UNIFORMS = { eyePosition: [0, 0, 0] } -__proto_217.drawPick = function (params) { +__proto_274.drawPick = function (params) { params = params || {} var gl = this.gl gl.disable(gl.CULL_FACE) var uniforms = PICK_UNIFORMS - uniforms.model = params.model || __IDENTITY_217 - uniforms.view = params.view || __IDENTITY_217 - uniforms.projection = params.projection || __IDENTITY_217 + uniforms.model = params.model || __IDENTITY_274 + uniforms.view = params.view || __IDENTITY_274 + uniforms.projection = params.projection || __IDENTITY_274 uniforms.shape = this._field[2].shape uniforms.pickId = this.pickId / 255.0 uniforms.lowerBound = this.bounds[0] @@ -177499,7 +181245,7 @@ __proto_217.drawPick = function (params) { } } -__proto_217.pick = function (selection) { +__proto_274.pick = function (selection) { if (!selection) { return null } @@ -177545,7 +181291,7 @@ __proto_217.pick = function (selection) { // Find closest level var levelIndex = this._pickResult.level for (var j = 0; j < 3; ++j) { - levelIndex[j] = _$searchBounds_71.le(this.contourLevels[j], pos[j]) + levelIndex[j] = _$searchBounds_72.le(this.contourLevels[j], pos[j]) if (levelIndex[j] < 0) { if (this.contourLevels[j].length > 0) { levelIndex[j] = 0 @@ -177577,16 +181323,16 @@ function padField (nfield, field) { var nshape = nfield.shape.slice() // Center - _$ndarrayOps_271.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) + _$ndarrayOps_329.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) // Edges - _$ndarrayOps_271.assign(nfield.lo(1).hi(shape[0], 1), + _$ndarrayOps_329.assign(nfield.lo(1).hi(shape[0], 1), field.hi(shape[0], 1)) - _$ndarrayOps_271.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), + _$ndarrayOps_329.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), field.lo(0, shape[1] - 1).hi(shape[0], 1)) - _$ndarrayOps_271.assign(nfield.lo(0, 1).hi(1, shape[1]), + _$ndarrayOps_329.assign(nfield.lo(0, 1).hi(1, shape[1]), field.hi(1)) - _$ndarrayOps_271.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), + _$ndarrayOps_329.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), field.lo(shape[0] - 1)) // Corners nfield.set(0, 0, field.get(0, 0)) @@ -177629,7 +181375,7 @@ function handleColor (param) { } } -__proto_217.update = function (params) { +__proto_274.update = function (params) { params = params || {} this.dirty = true @@ -177693,12 +181439,12 @@ __proto_217.update = function (params) { // Resize if necessary if (fsize > this._field[2].data.length) { - _$pool_360.freeFloat(this._field[2].data) - this._field[2].data = _$pool_360.mallocFloat(_$twiddle_72.nextPow2(fsize)) + _$pool_422.freeFloat(this._field[2].data) + this._field[2].data = _$pool_422.mallocFloat(_$twiddle_73.nextPow2(fsize)) } // Pad field - this._field[2] = _$wrappedNDArrayCtor_277(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) + this._field[2] = _$wrappedNDArrayCtor_335(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) padField(this._field[2], field) // Save shape of field @@ -177708,10 +181454,10 @@ __proto_217.update = function (params) { // Resize coordinate fields if necessary for (var i = 0; i < 2; ++i) { if (this._field[2].size > this._field[i].data.length) { - _$pool_360.freeFloat(this._field[i].data) - this._field[i].data = _$pool_360.mallocFloat(this._field[2].size) + _$pool_422.freeFloat(this._field[i].data) + this._field[i].data = _$pool_422.mallocFloat(this._field[2].size) } - this._field[i] = _$wrappedNDArrayCtor_277(this._field[i].data, [shape[0] + 2, shape[1] + 2]) + this._field[i] = _$wrappedNDArrayCtor_335(this._field[i].data, [shape[0] + 2, shape[1] + 2]) } // Generate x/y coordinates @@ -177737,13 +181483,13 @@ __proto_217.update = function (params) { for (i = 0; i < 2; ++i) { var tick = ticks[i] if (Array.isArray(tick) || tick.length) { - tick = _$wrappedNDArrayCtor_277(tick) + tick = _$wrappedNDArrayCtor_335(tick) } if (tick.shape[0] !== shape[i]) { throw new Error('gl-surface: invalid tick length') } // Make a copy view of the tick array - var tick2 = _$wrappedNDArrayCtor_277(tick.data, shape) + var tick2 = _$wrappedNDArrayCtor_335(tick.data, shape) tick2.stride[i] = tick.stride[0] tick2.stride[i ^ 1] = 0 @@ -177754,7 +181500,7 @@ __proto_217.update = function (params) { for (i = 0; i < 2; ++i) { var offset = [0, 0] offset[i] = 1 - this._field[i] = _$wrappedNDArrayCtor_277(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) + this._field[i] = _$wrappedNDArrayCtor_335(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) } this._field[0].set(0, 0, 0) for (var j = 0; j < shape[0]; ++j) { @@ -177772,11 +181518,11 @@ __proto_217.update = function (params) { var fields = this._field // Compute surface normals - var dfields = _$wrappedNDArrayCtor_277(_$pool_360.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) + var dfields = _$wrappedNDArrayCtor_335(_$pool_422.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) for (i = 0; i < 3; ++i) { - _$gradient_268(dfields.pick(i), fields[i], 'mirror') + _$gradient_326(dfields.pick(i), fields[i], 'mirror') } - var normals = _$wrappedNDArrayCtor_277(_$pool_360.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) + var normals = _$wrappedNDArrayCtor_335(_$pool_422.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) for (i = 0; i < shape[0] + 2; ++i) { for (j = 0; j < shape[1] + 2; ++j) { var dxdu = dfields.get(0, i, j, 0) @@ -177809,7 +181555,7 @@ __proto_217.update = function (params) { normals.set(i, j, 2, nz * nl) } } - _$pool_360.free(dfields.data) + _$pool_422.free(dfields.data) // Initialize surface var lo = [ Infinity, Infinity, Infinity ] @@ -177817,7 +181563,7 @@ __proto_217.update = function (params) { var lo_intensity = Infinity var hi_intensity = -Infinity var count = (shape[0] - 1) * (shape[1] - 1) * 6 - var tverts = _$pool_360.mallocFloat(_$twiddle_72.nextPow2(10 * count)) + var tverts = _$pool_422.mallocFloat(_$twiddle_73.nextPow2(10 * count)) var tptr = 0 var vertexCount = 0 for (i = 0; i < shape[0] - 1; ++i) { @@ -177888,8 +181634,8 @@ __proto_217.update = function (params) { this._vertexCount = vertexCount this._coordinateBuffer.update(tverts.subarray(0, tptr)) - _$pool_360.freeFloat(tverts) - _$pool_360.free(normals.data) + _$pool_422.freeFloat(tverts) + _$pool_422.free(normals.data) // Update bounds this.bounds = [lo, hi] @@ -177950,7 +181696,7 @@ __proto_217.update = function (params) { var parts = [0, 0, 0] for (i = 0; i < levels.length; ++i) { - var graph = _$surfaceNets_346(this._field[dim], levels[i]) + var graph = _$surfaceNets_408(this._field[dim], levels[i]) levelOffsets.push((contourVerts.length / 5) | 0) vertexCount = 0 @@ -178019,20 +181765,20 @@ __proto_217.update = function (params) { this._contourCounts[dim] = levelCounts } - var floatBuffer = _$pool_360.mallocFloat(contourVerts.length) + var floatBuffer = _$pool_422.mallocFloat(contourVerts.length) for (i = 0; i < contourVerts.length; ++i) { floatBuffer[i] = contourVerts[i] } this._contourBuffer.update(floatBuffer) - _$pool_360.freeFloat(floatBuffer) + _$pool_422.freeFloat(floatBuffer) } if (params.colormap) { - this._colorMap.setPixels(__genColormap_217(params.colormap)) + this._colorMap.setPixels(__genColormap_274(params.colormap)) } } -__proto_217.dispose = function () { +__proto_274.dispose = function () { this._shader.dispose() this._vao.dispose() this._coordinateBuffer.dispose() @@ -178044,11 +181790,11 @@ __proto_217.dispose = function () { this._dynamicBuffer.dispose() this._dynamicVAO.dispose() for (var i = 0; i < 3; ++i) { - _$pool_360.freeFloat(this._field[i].data) + _$pool_422.freeFloat(this._field[i].data) } } -__proto_217.highlight = function (selection) { +__proto_274.highlight = function (selection) { if (!selection) { this._dynamicCounts = [0, 0, 0] this.dyanamicLevel = [NaN, NaN, NaN] @@ -178078,7 +181824,7 @@ __proto_217.highlight = function (selection) { var vertexCount = 0 var shape = this.shape - var scratchBuffer = _$pool_360.mallocFloat(12 * shape[0] * shape[1]) + var scratchBuffer = _$pool_422.mallocFloat(12 * shape[0] * shape[1]) for (var d = 0; d < 3; ++d) { if (!this.enableDynamic[d]) { @@ -178097,7 +181843,7 @@ __proto_217.highlight = function (selection) { var h = this._field[v] var intensity = this.intensity - var graph = _$surfaceNets_346(f, levels[d]) + var graph = _$surfaceNets_408(f, levels[d]) var edges = graph.cells var positions = graph.positions @@ -178153,18 +181899,18 @@ __proto_217.highlight = function (selection) { } this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) - _$pool_360.freeFloat(scratchBuffer) + _$pool_422.freeFloat(scratchBuffer) } function createSurfacePlot (params) { var gl = params.gl - var shader = __createShader_217(gl) - var pickShader = __createPickShader_217(gl) - var contourShader = __createContourShader_217(gl) + var shader = __createShader_274(gl) + var pickShader = __createPickShader_274(gl) + var contourShader = __createContourShader_274(gl) var contourPickShader = createPickContourShader(gl) - var coordinateBuffer = _$createBuffer_153(gl) - var vao = _$createVAO_222(gl, [ + var coordinateBuffer = _$createBuffer_210(gl) + var vao = _$createVAO_279(gl, [ { buffer: coordinateBuffer, size: 4, stride: SURFACE_VERTEX_SIZE, @@ -178183,8 +181929,8 @@ function createSurfacePlot (params) { } ]) - var contourBuffer = _$createBuffer_153(gl) - var contourVAO = _$createVAO_222(gl, [ + var contourBuffer = _$createBuffer_210(gl) + var contourVAO = _$createVAO_279(gl, [ { buffer: contourBuffer, size: 4, @@ -178199,15 +181945,15 @@ function createSurfacePlot (params) { } ]) - var dynamicBuffer = _$createBuffer_153(gl) - var dynamicVAO = _$createVAO_222(gl, [ + var dynamicBuffer = _$createBuffer_210(gl) + var dynamicVAO = _$createVAO_279(gl, [ { buffer: dynamicBuffer, size: 2, type: gl.FLOAT }]) - var cmap = _$createTexture2D_218(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) + var cmap = _$createTexture2D_275(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) cmap.minFilter = gl.LINEAR cmap.magFilter = gl.LINEAR @@ -178245,14 +181991,14 @@ function createSurfacePlot (params) { -var fill = _$wrapper_118({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}","args":[{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) +var fill = _$wrapper_119({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}","args":[{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) -var _$ndarrayFill_267 = function(array, f) { +var _$ndarrayFill_325 = function(array, f) { fill(array, f) return array } -var _$invert_165 = __invert_165 +var _$invert_222 = __invert_222 /** * Inverts a mat2 @@ -178262,7 +182008,7 @@ var _$invert_165 = __invert_165 * @param {mat2} a the source matrix * @returns {mat2} out */ -function __invert_165(out, a) { +function __invert_222(out, a) { var a0 = a[0] var a1 = a[1] var a2 = a[2] @@ -178280,7 +182026,7 @@ function __invert_165(out, a) { return out } -var _$invert_166 = __invert_166 +var _$invert_223 = __invert_223 /** * Inverts a mat3 @@ -178290,7 +182036,7 @@ var _$invert_166 = __invert_166 * @param {mat3} a the source matrix * @returns {mat3} out */ -function __invert_166(out, a) { +function __invert_223(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2] var a10 = a[3], a11 = a[4], a12 = a[5] var a20 = a[6], a21 = a[7], a22 = a[8] @@ -178320,13 +182066,13 @@ function __invert_166(out, a) { 'use strict' -var _$invert_184 = __invert_184 +var _$invert_241 = __invert_241 -/* removed: var _$invert_165 = require('gl-mat2/invert') */; -/* removed: var _$invert_166 = require('gl-mat3/invert') */; -/* removed: var _$invert_173 = require('gl-mat4/invert') */; +/* removed: var _$invert_222 = require('gl-mat2/invert') */; +/* removed: var _$invert_223 = require('gl-mat3/invert') */; +/* removed: var _$invert_230 = require('gl-mat4/invert') */; -function __invert_184(out, M) { +function __invert_241(out, M) { switch(M.length) { case 0: break @@ -178334,13 +182080,13 @@ function __invert_184(out, M) { out[0] = 1.0 / M[0] break case 4: - _$invert_165(out, M) + _$invert_222(out, M) break case 9: - _$invert_166(out, M) + _$invert_223(out, M) break case 16: - _$invert_173(out, M) + _$invert_230(out, M) break default: throw new Error('currently supports matrices up to 4x4') @@ -178348,7 +182094,7 @@ function __invert_184(out, M) { } return out } -var _$interp_270 = {}; +var _$interp_328 = {}; "use strict" function interp1d(arr, x) { @@ -178361,7 +182107,7 @@ function interp1d(arr, x) { return (1.0-fx)*w0 + fx*w1 } -function __interp2d_270(arr, x, y) { +function __interp2d_328(arr, x, y) { var ix = Math.floor(x) , fx = x - ix , s0 = 0 <= ix && ix < arr.shape[0] @@ -178440,51 +182186,51 @@ i_loop: return r } -function __interpolate_270(arr, x, y, z) { +function __interpolate_328(arr, x, y, z) { switch(arr.shape.length) { case 0: return 0.0 case 1: return interp1d(arr, x) case 2: - return __interp2d_270(arr, x, y) + return __interp2d_328(arr, x, y) case 3: return interp3d(arr, x, y, z) default: return interpNd.apply(undefined, arguments) } } -_$interp_270 = __interpolate_270 -_$interp_270.d1 = interp1d -_$interp_270.d2 = __interp2d_270 -_$interp_270.d3 = interp3d +_$interp_328 = __interpolate_328 +_$interp_328.d1 = interp1d +_$interp_328.d2 = __interp2d_328 +_$interp_328.d3 = interp3d 'use strict' -/* removed: var _$interp_270 = require('ndarray-linear-interpolate') */; +/* removed: var _$interp_328 = require('ndarray-linear-interpolate') */; -var do_warp = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_3_arg4_)}","args":[{"name":"_inline_3_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_4_arg2_(this_warped,_inline_4_arg0_),_inline_4_arg1_=_inline_4_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_4_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_4_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg4_","lvalue":false,"rvalue":false,"count":0}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64}) +var do_warp = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_3_arg4_)}","args":[{"name":"_inline_3_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_3_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_4_arg2_(this_warped,_inline_4_arg0_),_inline_4_arg1_=_inline_4_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_4_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_4_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg4_","lvalue":false,"rvalue":false,"count":0}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64}) -var do_warp_1 = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_(_inline_7_arg4_,this_warped[0])}","args":[{"name":"_inline_7_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_7_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64}) +var do_warp_1 = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_(_inline_7_arg4_,this_warped[0])}","args":[{"name":"_inline_7_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_7_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64}) -var do_warp_2 = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_10_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_10_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64}) +var do_warp_2 = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_10_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_10_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64}) -var do_warp_3 = _$wrapper_118({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_13_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_13_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64}) +var do_warp_3 = _$wrapper_119({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_13_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_13_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64}) -var _$warp_276 = function warp(dest, src, func) { +var _$warp_334 = function warp(dest, src, func) { switch(src.shape.length) { case 1: - do_warp_1(dest, func, _$interp_270.d1, src) + do_warp_1(dest, func, _$interp_328.d1, src) break case 2: - do_warp_2(dest, func, _$interp_270.d2, src) + do_warp_2(dest, func, _$interp_328.d2, src) break case 3: - do_warp_3(dest, func, _$interp_270.d3, src) + do_warp_3(dest, func, _$interp_328.d3, src) break default: - do_warp(dest, func, _$interp_270.bind(undefined, src), src.shape.length) + do_warp(dest, func, _$interp_328.bind(undefined, src), src.shape.length) break } return dest @@ -178492,15 +182238,15 @@ var _$warp_276 = function warp(dest, src, func) { 'use strict' -/* removed: var _$warp_276 = require('ndarray-warp') */; -/* removed: var _$invert_184 = require('gl-matrix-invert') */; +/* removed: var _$warp_334 = require('ndarray-warp') */; +/* removed: var _$invert_241 = require('gl-matrix-invert') */; -var _$applyHomography_269 = applyHomography +var _$applyHomography_327 = applyHomography function applyHomography(dest, src, Xi) { var n = src.dimension - var X = _$invert_184([], Xi) - _$warp_276(dest, src, function(out_c, inp_c) { + var X = _$invert_241([], Xi) + _$warp_334(dest, src, function(out_c, inp_c) { for(var i=0; i and doesn't seem to cause a speed difference columnBoundaryClippath.enter() .append('clipPath') - .classed(_$constants_945.cn.columnBoundaryClippath, true); + .classed(_$constants_1016.cn.columnBoundaryClippath, true); columnBoundaryClippath .attr('id', function(d) {return columnBoundaryClipKey(gd, d);}); - var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + _$constants_945.cn.columnBoundaryRect) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var columnBoundaryRect = columnBoundaryClippath.selectAll('.' + _$constants_1016.cn.columnBoundaryRect) + .data(_$gup_598.repeat, _$gup_598.keyFun); columnBoundaryRect.enter() .append('rect') - .classed(_$constants_945.cn.columnBoundaryRect, true) + .classed(_$constants_1016.cn.columnBoundaryRect, true) .attr('fill', 'none'); columnBoundaryRect - .attr('width', function(d) {return d.columnWidth;}) - .attr('height', function(d) {return d.calcdata.height + _$constants_945.uplift;}); + .attr('width', function(d) { return d.columnWidth + 2 * roundHalfWidth(d); }) + .attr('height', function(d) {return d.calcdata.height + 2 * roundHalfWidth(d) + _$constants_1016.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; } @@ -179765,12 +183570,12 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { return firstRowAnchor(blocks, blocks.length - 1) + (blocks.length ? rowsHeight(blocks[blocks.length - 1], Infinity) : 1); } - var scrollbarKit = tableControlView.selectAll('.' + _$constants_945.cn.scrollbarKit) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarKit = tableControlView.selectAll('.' + _$constants_1016.cn.scrollbarKit) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarKit.enter() .append('g') - .classed(_$constants_945.cn.scrollbarKit, true) + .classed(_$constants_1016.cn.scrollbarKit, true) .style('shape-rendering', 'geometricPrecision'); scrollbarKit @@ -179780,7 +183585,7 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { 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, _$constants_945.goldenRatio * _$constants_945.scrollbarWidth); + s.barLength = Math.max(s.ratio * s.currentlyVisibleHeight, _$constants_1016.goldenRatio * _$constants_1016.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; @@ -179788,43 +183593,43 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { s.dragMultiplier = s.wiggleRoom / s.barWiggleRoom; }) .attr('transform', function(d) { - var xPosition = d.width + _$constants_945.scrollbarWidth / 2 + _$constants_945.scrollbarOffset; + var xPosition = d.width + _$constants_1016.scrollbarWidth / 2 + _$constants_1016.scrollbarOffset; return 'translate(' + xPosition + ' ' + headerHeight(d) + ')'; }); - var scrollbar = scrollbarKit.selectAll('.' + _$constants_945.cn.scrollbar) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbar = scrollbarKit.selectAll('.' + _$constants_1016.cn.scrollbar) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbar.enter() .append('g') - .classed(_$constants_945.cn.scrollbar, true); + .classed(_$constants_1016.cn.scrollbar, true); - var scrollbarSlider = scrollbar.selectAll('.' + _$constants_945.cn.scrollbarSlider) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarSlider = scrollbar.selectAll('.' + _$constants_1016.cn.scrollbarSlider) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarSlider.enter() .append('g') - .classed(_$constants_945.cn.scrollbarSlider, true); + .classed(_$constants_1016.cn.scrollbarSlider, true); scrollbarSlider .attr('transform', function(d) { return 'translate(0 ' + (d.scrollbarState.topY || 0) + ')'; }); - var scrollbarGlyph = scrollbarSlider.selectAll('.' + _$constants_945.cn.scrollbarGlyph) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarGlyph = scrollbarSlider.selectAll('.' + _$constants_1016.cn.scrollbarGlyph) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarGlyph.enter() .append('line') - .classed(_$constants_945.cn.scrollbarGlyph, true) + .classed(_$constants_1016.cn.scrollbarGlyph, true) .attr('stroke', 'black') - .attr('stroke-width', _$constants_945.scrollbarWidth) + .attr('stroke-width', _$constants_1016.scrollbarWidth) .attr('stroke-linecap', 'round') - .attr('y1', _$constants_945.scrollbarWidth / 2); + .attr('y1', _$constants_1016.scrollbarWidth / 2); scrollbarGlyph .attr('y2', function(d) { - return d.scrollbarState.barLength - _$constants_945.scrollbarWidth / 2; + return d.scrollbarState.barLength - _$constants_1016.scrollbarWidth / 2; }) .attr('stroke-opacity', function(d) { return d.columnDragInProgress || !d.scrollbarState.barWiggleRoom || bypassVisibleBar ? 0 : 0.4; @@ -179835,33 +183640,33 @@ function renderScrollbarKit(tableControlView, gd, bypassVisibleBar) { .transition().delay(0).duration(0); scrollbarGlyph - .transition().delay(_$constants_945.scrollbarHideDelay).duration(_$constants_945.scrollbarHideDuration) + .transition().delay(_$constants_1016.scrollbarHideDelay).duration(_$constants_1016.scrollbarHideDuration) .attr('stroke-opacity', 0); - var scrollbarCaptureZone = scrollbar.selectAll('.' + _$constants_945.cn.scrollbarCaptureZone) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var scrollbarCaptureZone = scrollbar.selectAll('.' + _$constants_1016.cn.scrollbarCaptureZone) + .data(_$gup_598.repeat, _$gup_598.keyFun); scrollbarCaptureZone.enter() .append('line') - .classed(_$constants_945.cn.scrollbarCaptureZone, true) + .classed(_$constants_1016.cn.scrollbarCaptureZone, true) .attr('stroke', 'white') .attr('stroke-opacity', 0.01) // some browser might get rid of a 0 opacity element - .attr('stroke-width', _$constants_945.scrollbarCaptureWidth) + .attr('stroke-width', _$constants_1016.scrollbarCaptureWidth) .attr('stroke-linecap', 'butt') .attr('y1', 0) .on('mousedown', function(d) { - var y = _$d3_127.event.y; + var y = _$d3_130.event.y; var bbox = this.getBoundingClientRect(); var s = d.scrollbarState; var pixelVal = y - bbox.top; - var inverseScale = _$d3_127.scale.linear().domain([0, s.scrollableAreaHeight]).range([0, s.totalHeight]).clamp(true); + var inverseScale = _$d3_130.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_127.behavior.drag() + .call(_$d3_130.behavior.drag() .origin(function(d) { - _$d3_127.event.stopPropagation(); + _$d3_130.event.stopPropagation(); d.scrollbarState.scrollbarScrollInProgress = true; return d; }) @@ -179905,12 +183710,12 @@ function renderColumnCellTree(gd, tableControlView, columnBlock, allColumnBlock) function renderColumnCells(columnBlock) { - var columnCells = columnBlock.selectAll('.' + _$constants_945.cn.columnCells) - .data(_$gup_536.repeat, _$gup_536.keyFun); + var columnCells = columnBlock.selectAll('.' + _$constants_1016.cn.columnCells) + .data(_$gup_598.repeat, _$gup_598.keyFun); columnCells.enter() .append('g') - .classed(_$constants_945.cn.columnCells, true); + .classed(_$constants_1016.cn.columnCells, true); columnCells.exit() .remove(); @@ -179920,12 +183725,12 @@ function renderColumnCells(columnBlock) { function renderColumnCell(columnCells) { - var columnCell = columnCells.selectAll('.' + _$constants_945.cn.columnCell) - .data(_$data_split_helpers_947.splitToCells, function(d) {return d.keyWithinBlock;}); + var columnCell = columnCells.selectAll('.' + _$constants_1016.cn.columnCell) + .data(_$data_split_helpers_1018.splitToCells, function(d) {return d.keyWithinBlock;}); columnCell.enter() .append('g') - .classed(_$constants_945.cn.columnCell, true); + .classed(_$constants_1016.cn.columnCell, true); columnCell.exit() .remove(); @@ -179935,38 +183740,38 @@ function renderColumnCell(columnCells) { function renderCellRect(columnCell) { - var cellRect = columnCell.selectAll('.' + _$constants_945.cn.cellRect) - .data(_$gup_536.repeat, function(d) {return d.keyWithinBlock;}); + var cellRect = columnCell.selectAll('.' + _$constants_1016.cn.cellRect) + .data(_$gup_598.repeat, function(d) {return d.keyWithinBlock;}); cellRect.enter() .append('rect') - .classed(_$constants_945.cn.cellRect, true); + .classed(_$constants_1016.cn.cellRect, true); return cellRect; } function renderCellText(cellTextHolder) { - var cellText = cellTextHolder.selectAll('.' + _$constants_945.cn.cellText) - .data(_$gup_536.repeat, function(d) {return d.keyWithinBlock;}); + var cellText = cellTextHolder.selectAll('.' + _$constants_1016.cn.cellText) + .data(_$gup_598.repeat, function(d) {return d.keyWithinBlock;}); cellText.enter() .append('text') - .classed(_$constants_945.cn.cellText, true) + .classed(_$constants_1016.cn.cellText, true) .style('cursor', function() {return 'auto';}) - .on('mousedown', function() {_$d3_127.event.stopPropagation();}); + .on('mousedown', function() {_$d3_130.event.stopPropagation();}); return cellText; } function renderCellTextHolder(columnCell) { - var cellTextHolder = columnCell.selectAll('.' + _$constants_945.cn.cellTextHolder) - .data(_$gup_536.repeat, function(d) {return d.keyWithinBlock;}); + var cellTextHolder = columnCell.selectAll('.' + _$constants_1016.cn.cellTextHolder) + .data(_$gup_598.repeat, function(d) {return d.keyWithinBlock;}); cellTextHolder.enter() .append('g') - .classed(_$constants_945.cn.cellTextHolder, true) + .classed(_$constants_1016.cn.cellTextHolder, true) .style('shape-rendering', 'geometricPrecision'); return cellTextHolder; @@ -179992,7 +183797,7 @@ function supplyStylingValues(columnCell) { function setFont(cellText) { cellText .each(function(d) { - _$drawing_436.font(_$d3_127.select(this), d.font); + _$drawing_498.font(_$d3_130.select(this), d.font); }); } @@ -180001,9 +183806,9 @@ function sizeAndStyleRect(cellRect) { .attr('width', function(d) {return d.column.columnWidth;}) .attr('stroke-width', function(d) {return d.cellBorderWidth;}) .each(function(d) { - var atomicSelection = _$d3_127.select(this); - _$color_411.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber)); - _$color_411.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber)); + var atomicSelection = _$d3_130.select(this); + _$color_473.stroke(atomicSelection, gridPick(d.calcdata.cells.line.color, d.column.specIndex, d.rowNumber)); + _$color_473.fill(atomicSelection, gridPick(d.calcdata.cells.fill.color, d.column.specIndex, d.rowNumber)); }); } @@ -180027,7 +183832,7 @@ function populateCellText(cellText, tableControlView, allColumnBlock, gd) { 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_127.format(format)(d.value) : d.value) + suffix; + var prefixSuffixedText = prefix + (format ? _$d3_130.format(format)(d.value) : d.value) + suffix; var hasWrapSplitCharacter; d.wrappingNeeded = !d.wrapped && !userBrokenText && !latex && (hasWrapSplitCharacter = hasWrapCharacter(prefixSuffixedText)); @@ -180036,12 +183841,12 @@ function populateCellText(cellText, tableControlView, allColumnBlock, gd) { var textToRender; if(d.wrappingNeeded) { - var hrefPreservedText = _$constants_945.wrapSplitCharacter === ' ' ? prefixSuffixedText.replace(/
rowLengthLimit) { - d.value += currentRow.join(_$constants_945.wrapSpacer) + _$constants_945.lineBreaker; + d.value += currentRow.join(_$constants_1016.wrapSpacer) + _$constants_1016.lineBreaker; currentRow = []; currentRowLength = 0; } @@ -180261,7 +184066,7 @@ function wrapTextMaker(columnBlock, element, tableControlView) { currentRowLength += currentAdditionLength; } if(currentRowLength) { - d.value += currentRow.join(_$constants_945.wrapSpacer); + d.value += currentRow.join(_$constants_1016.wrapSpacer); } d.wrapped = true; }); @@ -180270,21 +184075,21 @@ function wrapTextMaker(columnBlock, element, tableControlView) { cellTextHolder.selectAll('tspan.line').remove(); // resupply text, now wrapped - populateCellText(cellTextHolder.select('.' + _$constants_945.cn.cellText), tableControlView, columnBlock); - _$d3_127.select(element.parentNode.parentNode).call(setCellHeightAndPositionY); + populateCellText(cellTextHolder.select('.' + _$constants_1016.cn.cellText), tableControlView, columnBlock); + _$d3_130.select(element.parentNode.parentNode).call(setCellHeightAndPositionY); }; } function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { return function updateYPosition() { if(d.settledY) return; - var cellTextHolder = _$d3_127.select(element.parentNode); + var cellTextHolder = _$d3_130.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 * _$constants_945.cellPad : declaredRowHeight; + var requiredHeight = d.cellHeightMayIncrease ? element.parentNode.getBoundingClientRect().height + 2 * _$constants_1016.cellPad : declaredRowHeight; var finalHeight = Math.max(requiredHeight, declaredRowHeight); var increase = finalHeight - l.rows[rowIndex].rowHeight; @@ -180295,7 +184100,7 @@ function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { l.rows[rowIndex].rowHeight = finalHeight; columnBlock - .selectAll('.' + _$constants_945.cn.columnCell) + .selectAll('.' + _$constants_1016.cn.columnCell) .call(setCellHeightAndPositionY); updateBlockYPosition(null, columnBlock.filter(cellsBlock), 0); @@ -180312,10 +184117,10 @@ function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { var element = this; var columnCellElement = element.parentNode; var box = columnCellElement.getBoundingClientRect(); - var rectBox = _$d3_127.select(element.parentNode).select('.' + _$constants_945.cn.cellRect).node().getBoundingClientRect(); + var rectBox = _$d3_130.select(element.parentNode).select('.' + _$constants_1016.cn.cellRect).node().getBoundingClientRect(); var currentTransform = element.transform.baseVal.consolidate(); - var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : _$constants_945.cellPad); - return 'translate(' + xPosition(d, _$d3_127.select(element.parentNode).select('.' + _$constants_945.cn.cellTextHolder).node().getBoundingClientRect().width) + ' ' + yPosition + ')'; + var yPosition = rectBox.top - box.top + (currentTransform ? currentTransform.matrix.f : _$constants_1016.cellPad); + return 'translate(' + xPosition(d, _$d3_130.select(element.parentNode).select('.' + _$constants_1016.cn.cellTextHolder).node().getBoundingClientRect().width) + ' ' + yPosition + ')'; }); d.settledY = true; @@ -180324,10 +184129,10 @@ function updateYPositionMaker(columnBlock, element, tableControlView, gd, d) { function xPosition(d, optionalWidth) { switch(d.align) { - case 'left': return _$constants_945.cellPad; - case 'right': return d.column.columnWidth - (optionalWidth || 0) - _$constants_945.cellPad; + case 'left': return _$constants_1016.cellPad; + case 'right': return d.column.columnWidth - (optionalWidth || 0) - _$constants_1016.cellPad; case 'center': return (d.column.columnWidth - (optionalWidth || 0)) / 2; - default: return _$constants_945.cellPad; + default: return _$constants_1016.cellPad; } } @@ -180340,7 +184145,7 @@ function setCellHeightAndPositionY(columnCell) { var yOffset = rowAnchor + headerHeight; return 'translate(0 ' + yOffset + ')'; }) - .selectAll('.' + _$constants_945.cn.cellRect) + .selectAll('.' + _$constants_1016.cn.cellRect) .attr('height', function(d) {return getRow(getBlock(d), d.key).rowHeight;}); } @@ -180379,7 +184184,7 @@ function allRowsHeight(rowBlock) { function getBlock(d) {return d.rowBlocks[d.page];} function getRow(l, i) {return l.rows[i - l.firstRowIndex];} -var _$base_plot_943 = {}; +var _$base_plot_1014 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -180390,19 +184195,19 @@ var _$base_plot_943 = {}; 'use strict'; -var __getModuleCalcData_943 = _$get_data_621.getModuleCalcData; -/* removed: var _$plot_950 = require('./plot'); */; +var __getModuleCalcData_1014 = _$get_data_683.getModuleCalcData; +/* removed: var _$plot_1021 = require('./plot'); */; var TABLE = 'table'; -_$base_plot_943.name = TABLE; +_$base_plot_1014.name = TABLE; -_$base_plot_943.plot = function(gd) { - var calcData = __getModuleCalcData_943(gd.calcdata, TABLE); - if(calcData.length) _$plot_950(gd, calcData); +_$base_plot_1014.plot = function(gd) { + var calcData = __getModuleCalcData_1014(gd.calcdata, TABLE)[0]; + if(calcData.length) _$plot_1021(gd, calcData); }; -_$base_plot_943.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { +_$base_plot_1014.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { var hadTable = (oldFullLayout._has && oldFullLayout._has(TABLE)); var hasTable = (newFullLayout._has && newFullLayout._has(TABLE)); @@ -180421,10 +184226,12 @@ _$base_plot_943.clean = function(newFullData, newFullLayout, oldFullData, oldFul 'use strict'; -var __wrap_944 = _$gup_536.wrap; +var __wrap_1015 = _$gup_598.wrap; -var _$calc_944 = function calc(gd, trace) { - return __wrap_944(trace); +var _$calc_1015 = 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_1015({}); }; /** @@ -180437,9 +184244,9 @@ var _$calc_944 = function calc(gd, trace) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$attributes_942 = require('./attributes'); */; -var __handleDomainDefaults_948 = _$domain_610.defaults; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$attributes_1013 = require('./attributes'); */; +var __handleDomainDefaults_1019 = _$domain_672.defaults; function defaultColumnOrder(traceOut, coerce) { var specifiedColumnOrder = traceOut.columnorder || []; @@ -180453,12 +184260,12 @@ function defaultColumnOrder(traceOut, coerce) { coerce('columnorder', oneStepped); } -var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_1019 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_942, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_1013, attr, dflt); } - __handleDomainDefaults_948(traceOut, layout, coerce); + __handleDomainDefaults_1019(traceOut, layout, coerce); coerce('columnwidth'); @@ -180472,7 +184279,7 @@ var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('header.line.width'); coerce('header.line.color'); coerce('header.fill.color'); - _$lib_539.coerceFont(coerce, 'header.font', _$lib_539.extendFlat({}, layout.font)); + _$lib_601.coerceFont(coerce, 'header.font', _$lib_601.extendFlat({}, layout.font)); defaultColumnOrder(traceOut, coerce); @@ -180485,7 +184292,7 @@ var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultCol coerce('cells.line.width'); coerce('cells.line.color'); coerce('cells.fill.color'); - _$lib_539.coerceFont(coerce, 'cells.font', _$lib_539.extendFlat({}, layout.font)); + _$lib_601.coerceFont(coerce, 'cells.font', _$lib_601.extendFlat({}, layout.font)); }; /** @@ -180500,20 +184307,20 @@ var _$supplyDefaults_948 = function supplyDefaults(traceIn, traceOut, defaultCol var Table = {}; -Table.attributes = _$attributes_942; -Table.supplyDefaults = _$supplyDefaults_948; -Table.calc = _$calc_944; -Table.plot = _$plot_950; +Table.attributes = _$attributes_1013; +Table.supplyDefaults = _$supplyDefaults_1019; +Table.calc = _$calc_1015; +Table.plot = _$plot_1021; Table.moduleType = 'trace'; Table.name = 'table'; -Table.basePlotModule = _$base_plot_943; +Table.basePlotModule = _$base_plot_1014; Table.categories = ['noOpacity']; Table.meta = { }; -var _$Table_949 = Table; +var _$Table_1020 = Table; /** * Copyright 2012-2018, Plotly, Inc. @@ -180525,7 +184332,7 @@ var _$Table_949 = Table; 'use strict'; -var _$table_37 = _$Table_949; +var _$table_38 = _$Table_1020; /** * Copyright 2012-2018, Plotly, Inc. @@ -180537,16 +184344,16 @@ var _$table_37 = _$Table_949; 'use strict'; -/* removed: var _$attributes_691 = require('../box/attributes'); */; -var __extendFlat_951 = _$extend_528.extendFlat; +/* removed: var _$attributes_754 = require('../box/attributes'); */; +var __extendFlat_1022 = _$extend_590.extendFlat; -var _$attributes_951 = { - y: _$attributes_691.y, - x: _$attributes_691.x, - x0: _$attributes_691.x0, - y0: _$attributes_691.y0, - name: _$attributes_691.name, - orientation: __extendFlat_951({}, _$attributes_691.orientation, { +var _$attributes_1022 = { + y: _$attributes_754.y, + x: _$attributes_754.x, + x0: _$attributes_754.x0, + y0: _$attributes_754.y0, + name: _$attributes_754.name, + orientation: __extendFlat_1022({}, _$attributes_754.orientation, { }), @@ -180610,19 +184417,19 @@ var _$attributes_951 = { }, editType: 'plot' }, - fillcolor: _$attributes_691.fillcolor, + fillcolor: _$attributes_754.fillcolor, - points: __extendFlat_951({}, _$attributes_691.boxpoints, { + points: __extendFlat_1022({}, _$attributes_754.boxpoints, { }), - jitter: __extendFlat_951({}, _$attributes_691.jitter, { + jitter: __extendFlat_1022({}, _$attributes_754.jitter, { }), - pointpos: __extendFlat_951({}, _$attributes_691.pointpos, { + pointpos: __extendFlat_1022({}, _$attributes_754.pointpos, { }), - marker: _$attributes_691.marker, - text: _$attributes_691.text, + marker: _$attributes_754.marker, + text: _$attributes_754.text, box: { visible: { @@ -180699,8 +184506,8 @@ var _$attributes_951 = { }, - selected: _$attributes_691.selected, - unselected: _$attributes_691.unselected, + selected: _$attributes_754.selected, + unselected: _$attributes_754.unselected, hoveron: { valType: 'flaglist', @@ -180713,7 +184520,7 @@ var _$attributes_951 = { } }; -var _$helpers_954 = {}; +var _$helpers_1025 = {}; /** * Copyright 2012-2018, Plotly, Inc. * All rights reserved. @@ -180724,7 +184531,7 @@ var _$helpers_954 = {}; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; +/* removed: var _$lib_601 = require('../../lib'); */; // Maybe add kernels more down the road, // but note that the default `spanmode: 'soft'` bounds might have @@ -180735,7 +184542,7 @@ var kernels = { } }; -_$helpers_954.makeKDE = function(calcItem, trace, vals) { +_$helpers_1025.makeKDE = function(calcItem, trace, vals) { var len = vals.length; var kernel = kernels.gaussian; var bandwidth = calcItem.bandwidth; @@ -180751,7 +184558,7 @@ _$helpers_954.makeKDE = function(calcItem, trace, vals) { }; }; -_$helpers_954.getPositionOnKdePath = function(calcItem, trace, valuePx) { +_$helpers_1025.getPositionOnKdePath = function(calcItem, trace, valuePx) { var posLetter, valLetter; if(trace.orientation === 'h') { @@ -180762,7 +184569,7 @@ _$helpers_954.getPositionOnKdePath = function(calcItem, trace, valuePx) { valLetter = 'y'; } - var pointOnPath = _$lib_539.findPointOnPath( + var pointOnPath = _$lib_601.findPointOnPath( calcItem.path, valuePx, valLetter, @@ -180778,13 +184585,13 @@ _$helpers_954.getPositionOnKdePath = function(calcItem, trace, valuePx) { return [posOnPath0, posOnPath1]; }; -_$helpers_954.getKdeValue = function(calcItem, trace, valueDist) { - var vals = calcItem.pts.map(_$helpers_954.extractVal); - var kde = _$helpers_954.makeKDE(calcItem, trace, vals); +_$helpers_1025.getKdeValue = function(calcItem, trace, valueDist) { + var vals = calcItem.pts.map(_$helpers_1025.extractVal); + var kde = _$helpers_1025.makeKDE(calcItem, trace, vals); return kde(valueDist) / calcItem.posDensityScale; }; -_$helpers_954.extractVal = function(o) { return o.v; }; +_$helpers_1025.extractVal = function(o) { return o.v; }; /** * Copyright 2012-2018, Plotly, Inc. @@ -180796,19 +184603,19 @@ _$helpers_954.extractVal = function(o) { return o.v; }; 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$calc_692 = require('../box/calc'); */; -/* removed: var _$helpers_954 = require('./helpers'); */; -var __BADNUM_952 = _$numerical_517.BADNUM; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$calc_755 = require('../box/calc'); */; +/* removed: var _$helpers_1025 = require('./helpers'); */; +var __BADNUM_1023 = _$numerical_578.BADNUM; -var _$calc_952 = function calc(gd, trace) { - var cd = _$calc_692(gd, trace); +var _$calc_1023 = function calc(gd, trace) { + var cd = _$calc_755(gd, trace); if(cd[0].t.empty) return cd; var fullLayout = gd._fullLayout; - var valAxis = _$axes_584.getFromId( + var valAxis = _$axes_647.getFromId( gd, trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis'] ); @@ -180825,11 +184632,11 @@ var _$calc_952 = function calc(gd, trace) { for(var i = 0; i < cd.length; i++) { var cdi = cd[i]; - var vals = cdi.pts.map(_$helpers_954.extractVal); + var vals = cdi.pts.map(_$helpers_1025.extractVal); var len = vals.length; // sample standard deviation - var ssd = _$lib_539.stdev(vals, len - 1, cdi.mean); + var ssd = _$lib_601.stdev(vals, len - 1, cdi.mean); var bandwidthDflt = ruleOfThumbBandwidth(vals, ssd, cdi.q3 - cdi.q1); var bandwidth = cdi.bandwidth = trace.bandwidth || bandwidthDflt; var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth); @@ -180840,12 +184647,12 @@ var _$calc_952 = function calc(gd, trace) { var step = dist / n; if(!isFinite(step) || !isFinite(n)) { - _$lib_539.error('Something went wrong with computing the violin span'); + _$lib_601.error('Something went wrong with computing the violin span'); cd[0].t.empty = true; return cd; } - var kde = _$helpers_954.makeKDE(cdi, trace, vals); + var kde = _$helpers_1025.makeKDE(cdi, trace, vals); cdi.density = new Array(n); for(var k = 0, t = span[0]; t < (span[1] + step / 2); k++, t += step) { @@ -180854,11 +184661,11 @@ var _$calc_952 = function calc(gd, trace) { cdi.density[k] = {v: v, t: t}; } - _$axes_584.expand(valAxis, span, {padded: true}); + _$axes_647.expand(valAxis, span, {padded: true}); groupStats.maxCount = Math.max(groupStats.maxCount, vals.length); } - cd[0].t.labels.kde = _$lib_539._(gd, 'kde:'); + cd[0].t.labels.kde = _$lib_601._(gd, 'kde:'); return cd; }; @@ -180882,7 +184689,7 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { function calcSpanItem(index) { var s = spanIn[index]; var sc = valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']); - return sc === __BADNUM_952 ? spanLoose[index] : sc; + return sc === __BADNUM_1023 ? spanLoose[index] : sc; } if(spanmode === 'soft') { @@ -180898,7 +184705,7 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { type: 'linear', range: spanOut }; - _$axes_584.setConvert(dummyAx); + _$axes_647.setConvert(dummyAx); dummyAx.cleanRange(); return spanOut; @@ -180914,21 +184721,21 @@ function calcSpan(trace, cdi, valAxis, bandwidth) { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$color_411 = require('../../components/color'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$color_473 = require('../../components/color'); */; -/* removed: var _$defaults_693 = require('../box/defaults'); */; -/* removed: var _$attributes_951 = require('./attributes'); */; +/* removed: var _$defaults_756 = require('../box/defaults'); */; +/* removed: var _$attributes_1022 = require('./attributes'); */; -var _$supplyDefaults_953 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { +var _$supplyDefaults_1024 = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { - return _$lib_539.coerce(traceIn, traceOut, _$attributes_951, attr, dflt); + return _$lib_601.coerce(traceIn, traceOut, _$attributes_1022, attr, dflt); } function coerce2(attr, dflt) { - return _$lib_539.coerce2(traceIn, traceOut, _$attributes_951, attr, dflt); + return _$lib_601.coerce2(traceIn, traceOut, _$attributes_1022, attr, dflt); } - _$defaults_693.handleSampleDefaults(traceIn, traceOut, coerce, layout); + _$defaults_756.handleSampleDefaults(traceIn, traceOut, coerce, layout); if(traceOut.visible === false) return; coerce('bandwidth'); @@ -180943,9 +184750,9 @@ var _$supplyDefaults_953 = function supplyDefaults(traceIn, traceOut, defaultCol var lineColor = coerce('line.color', (traceIn.marker || {}).color || defaultColor); var lineWidth = coerce('line.width'); - var fillColor = coerce('fillcolor', _$color_411.addOpacity(traceOut.line.color, 0.5)); + var fillColor = coerce('fillcolor', _$color_473.addOpacity(traceOut.line.color, 0.5)); - _$defaults_693.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''}); + _$defaults_756.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''}); var boxWidth = coerce2('box.width'); var boxFillColor = coerce2('box.fillcolor', fillColor); @@ -180970,12 +184777,12 @@ var _$supplyDefaults_953 = function supplyDefaults(traceIn, traceOut, defaultCol 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$axes_584 = require('../../plots/cartesian/axes'); */; -/* removed: var _$hover_694 = require('../box/hover'); */; -/* removed: var _$helpers_954 = require('./helpers'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$axes_647 = require('../../plots/cartesian/axes'); */; +/* removed: var _$hover_757 = require('../box/hover'); */; +/* removed: var _$helpers_1025 = require('./helpers'); */; -var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { +var _$hoverPoints_1026 = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) { var cd = pointData.cd; var trace = cd[0].trace; var hoveron = trace.hoveron; @@ -180986,7 +184793,7 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h var violinLineAttrs; if(hasHoveronViolins || hasHoveronKDE) { - var closeBoxData = _$hover_694.hoverOnBoxes(pointData, xval, yval, hovermode); + var closeBoxData = _$hover_757.hoverOnBoxes(pointData, xval, yval, hovermode); if(hasHoveronViolins) { closeData = closeData.concat(closeBoxData); @@ -181014,17 +184821,17 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h var di = cd[pointData.index]; if(vVal >= di.span[0] && vVal <= di.span[1]) { - var kdePointData = _$lib_539.extendFlat({}, pointData); + var kdePointData = _$lib_601.extendFlat({}, pointData); var vValPx = vAxis.c2p(vVal, true); - var kdeVal = _$helpers_954.getKdeValue(di, trace, vVal); - var pOnPath = _$helpers_954.getPositionOnKdePath(di, trace, vValPx); + var kdeVal = _$helpers_1025.getKdeValue(di, trace, vVal); + var pOnPath = _$helpers_1025.getPositionOnKdePath(di, trace, vValPx); var paOffset = pAxis._offset; var paLength = pAxis._length; kdePointData[pLetter + '0'] = pOnPath[0]; kdePointData[pLetter + '1'] = pOnPath[1]; kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx; - kdePointData[vLetter + 'Label'] = vLetter + ': ' + _$axes_584.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3); + kdePointData[vLetter + 'Label'] = vLetter + ': ' + _$axes_647.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3); // move the spike to the KDE point kdePointData.spikeDistance = closeBoxData[0].spikeDistance; @@ -181036,15 +184843,15 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h closeData.push(kdePointData); violinLineAttrs = {stroke: pointData.color}; - violinLineAttrs[pLetter + '1'] = _$lib_539.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength); - violinLineAttrs[pLetter + '2'] = _$lib_539.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength); + violinLineAttrs[pLetter + '1'] = _$lib_601.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength); + violinLineAttrs[pLetter + '2'] = _$lib_601.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength); violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx; } } } if(hoveron.indexOf('points') !== -1) { - closePtData = _$hover_694.hoverOnPoints(pointData, xval, yval); + closePtData = _$hover_757.hoverOnPoints(pointData, xval, yval); } // update violin line (if any) @@ -181078,17 +184885,17 @@ var _$hoverPoints_955 = function hoverPoints(pointData, xval, yval, hovermode, h 'use strict'; -/* removed: var _$layout_attributes_696 = require('../box/layout_attributes'); */; -var __extendFlat_957 = _$lib_539.extendFlat; +/* removed: var _$layout_attributes_759 = require('../box/layout_attributes'); */; +var __extendFlat_1028 = _$lib_601.extendFlat; -var _$layout_attributes_957 = { - violinmode: __extendFlat_957({}, _$layout_attributes_696.boxmode, { +var _$layout_attributes_1028 = { + violinmode: __extendFlat_1028({}, _$layout_attributes_759.boxmode, { }), - violingap: __extendFlat_957({}, _$layout_attributes_696.boxgap, { + violingap: __extendFlat_1028({}, _$layout_attributes_759.boxgap, { }), - violingroupgap: __extendFlat_957({}, _$layout_attributes_696.boxgroupgap, { + violingroupgap: __extendFlat_1028({}, _$layout_attributes_759.boxgroupgap, { }) }; @@ -181103,15 +184910,15 @@ var _$layout_attributes_957 = { 'use strict'; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$layout_attributes_957 = require('./layout_attributes'); */; -/* removed: var _$layout_defaults_697 = require('../box/layout_defaults'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$layout_attributes_1028 = require('./layout_attributes'); */; +/* removed: var _$layout_defaults_760 = require('../box/layout_defaults'); */; -var _$supplyLayoutDefaults_958 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { +var _$supplyLayoutDefaults_1029 = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { function coerce(attr, dflt) { - return _$lib_539.coerce(layoutIn, layoutOut, _$layout_attributes_957, attr, dflt); + return _$lib_601.coerce(layoutIn, layoutOut, _$layout_attributes_1028, attr, dflt); } - _$layout_defaults_697._supply(layoutIn, layoutOut, fullData, coerce, 'violin'); + _$layout_defaults_760._supply(layoutIn, layoutOut, fullData, coerce, 'violin'); }; /** @@ -181124,20 +184931,20 @@ var _$supplyLayoutDefaults_958 = function supplyLayoutDefaults(layoutIn, layoutO 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$lib_539 = require('../../lib'); */; -/* removed: var _$drawing_436 = require('../../components/drawing'); */; -/* removed: var _$plot_698 = require('../box/plot'); */; -/* removed: var _$linePoints_876 = require('../scatter/line_points'); */; -/* removed: var _$helpers_954 = require('./helpers'); */; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$lib_601 = require('../../lib'); */; +/* removed: var _$drawing_498 = require('../../components/drawing'); */; +/* removed: var _$plot_761 = require('../box/plot'); */; +/* removed: var _$linePoints_941 = require('../scatter/line_points'); */; +/* removed: var _$helpers_1025 = require('./helpers'); */; -var _$plot_959 = function plot(gd, plotinfo, cd) { +var _$plot_1030 = function plot(gd, plotinfo, cd) { var fullLayout = gd._fullLayout; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; function makePath(pts) { - var segments = _$linePoints_876(pts, { + var segments = _$linePoints_941(pts, { xaxis: xa, yaxis: ya, connectGaps: true, @@ -181145,7 +184952,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { shape: 'spline', simplify: true }); - return _$drawing_436.smoothopen(segments[0], 1); + return _$drawing_498.smoothopen(segments[0], 1); } var traces = plotinfo.plot.select('.violinlayer') @@ -181158,16 +184965,21 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { var cd0 = d[0]; var t = cd0.t; var trace = cd0.trace; - var sel = cd0.node3 = _$d3_127.select(this); + var sel = _$d3_130.select(this); + if(!plotinfo.isRangePlot) cd0.node3 = sel; var numViolins = fullLayout._numViolins; var group = (fullLayout.violinmode === 'group' && numViolins > 1); + var groupFraction = 1 - fullLayout.violingap; // violin max half width - var bdPos = t.bdPos = t.dPos * (1 - fullLayout.violingap) * (1 - fullLayout.violingroupgap) / (group ? numViolins : 1); + var bdPos = t.bdPos = t.dPos * groupFraction * (1 - fullLayout.violingroupgap) / (group ? numViolins : 1); // violin center offset - var bPos = t.bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numViolins) * (1 - fullLayout.violingap) : 0; + var bPos = t.bPos = group ? 2 * t.dPos * (-0.5 + (t.num + 0.5) / numViolins) * groupFraction : 0; + // half-width within which to accept hover for this violin + // always split the distance to the closest violin + t.wHover = t.dPos * (group ? groupFraction / numViolins : 1); if(trace.visible !== true || t.empty) { - _$d3_127.select(this).remove(); + _$d3_130.select(this).remove(); return; } @@ -181181,12 +184993,12 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup]; sel.selectAll('path.violin') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .style('vector-effect', 'non-scaling-stroke') .attr('class', 'violin') .each(function(d) { - var pathSel = _$d3_127.select(this); + var pathSel = _$d3_130.select(this); var density = d.density; var len = density.length; var posCenter = d.pos + bPos; @@ -181273,7 +185085,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { // do not draw whiskers on inner boxes trace.whiskerwidth = 0; - _$plot_698.plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, { + _$plot_761.plotBoxAndWhiskers(sel, {pos: posAxis, val: valAxis}, trace, { bPos: bPos, bdPos: bdPosScaled, bPosPxOffset: bPosPxOffset @@ -181281,7 +185093,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { // if both box and meanline are visible, show mean line inside box if(hasMeanLine) { - _$plot_698.plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, { + _$plot_761.plotBoxMean(sel, {pos: posAxis, val: valAxis}, trace, { bPos: bPos, bdPos: bdPosScaled, bPosPxOffset: bPosPxOffset @@ -181291,7 +185103,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { else { if(hasMeanLine) { sel.selectAll('path.mean') - .data(_$lib_539.identity) + .data(_$lib_601.identity) .enter().append('path') .attr('class', 'mean') .style({ @@ -181300,9 +185112,9 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { }) .each(function(d) { var v = valAxis.c2p(d.mean, true); - var p = _$helpers_954.getPositionOnKdePath(d, trace, v); + var p = _$helpers_1025.getPositionOnKdePath(d, trace, v); - _$d3_127.select(this).attr('d', + _$d3_130.select(this).attr('d', trace.orientation === 'h' ? 'M' + v + ',' + p[0] + 'V' + p[1] : 'M' + p[0] + ',' + v + 'H' + p[1] @@ -181312,7 +185124,7 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { } if(trace.points) { - _$plot_698.plotPoints(sel, {x: xa, y: ya}, trace, t); + _$plot_761.plotPoints(sel, {x: xa, y: ya}, trace, t); } }); }; @@ -181327,16 +185139,16 @@ var _$plot_959 = function plot(gd, plotinfo, cd) { 'use strict'; -var __setPositionOffset_960 = _$set_positions_700.setPositionOffset; -var __orientations_960 = ['v', 'h']; +var __setPositionOffset_1031 = _$set_positions_763.setPositionOffset; +var __orientations_1031 = ['v', 'h']; -var _$setPositions_960 = function setPositions(gd, plotinfo) { +var _$setPositions_1031 = function setPositions(gd, plotinfo) { var calcdata = gd.calcdata; var xa = plotinfo.xaxis; var ya = plotinfo.yaxis; - for(var i = 0; i < __orientations_960.length; i++) { - var orientation = __orientations_960[i]; + for(var i = 0; i < __orientations_1031.length; i++) { + var orientation = __orientations_1031[i]; var posAxis = orientation === 'h' ? ya : xa; var violinList = []; var minPad = 0; @@ -181362,7 +185174,7 @@ var _$setPositions_960 = function setPositions(gd, plotinfo) { } } - __setPositionOffset_960('violin', gd, violinList, posAxis, [minPad, maxPad]); + __setPositionOffset_1031('violin', gd, violinList, posAxis, [minPad, maxPad]); } }; @@ -181376,18 +185188,18 @@ var _$setPositions_960 = function setPositions(gd, plotinfo) { 'use strict'; -/* removed: var _$d3_127 = require('d3'); */; -/* removed: var _$color_411 = require('../../components/color'); */; -var __stylePoints_961 = _$style_883.stylePoints; +/* removed: var _$d3_130 = require('d3'); */; +/* removed: var _$color_473 = require('../../components/color'); */; +var __stylePoints_1032 = _$style_948.stylePoints; -var _$style_961 = function style(gd, cd) { - var s = cd ? cd[0].node3 : _$d3_127.select(gd).selectAll('g.trace.violins'); +var _$style_1032 = function style(gd, cd) { + var s = cd ? cd[0].node3 : _$d3_130.select(gd).selectAll('g.trace.violins'); s.style('opacity', function(d) { return d[0].trace.opacity; }); s.each(function(d) { var trace = d[0].trace; - var sel = _$d3_127.select(this); + var sel = _$d3_130.select(this); var box = trace.box || {}; var boxLine = box.line || {}; var meanline = trace.meanline || {}; @@ -181395,22 +185207,22 @@ var _$style_961 = function style(gd, cd) { sel.selectAll('path.violin') .style('stroke-width', trace.line.width + 'px') - .call(_$color_411.stroke, trace.line.color) - .call(_$color_411.fill, trace.fillcolor); + .call(_$color_473.stroke, trace.line.color) + .call(_$color_473.fill, trace.fillcolor); sel.selectAll('path.box') .style('stroke-width', boxLine.width + 'px') - .call(_$color_411.stroke, boxLine.color) - .call(_$color_411.fill, box.fillcolor); + .call(_$color_473.stroke, boxLine.color) + .call(_$color_473.fill, box.fillcolor); sel.selectAll('path.mean') .style({ 'stroke-width': meanLineWidth + 'px', 'stroke-dasharray': (2 * meanLineWidth) + 'px,' + meanLineWidth + 'px' }) - .call(_$color_411.stroke, meanline.color); + .call(_$color_473.stroke, meanline.color); - __stylePoints_961(sel, trace, gd); + __stylePoints_1032(sel, trace, gd); }); }; @@ -181424,22 +185236,22 @@ var _$style_961 = function style(gd, cd) { 'use strict'; -var _$violin_956 = { - attributes: _$attributes_951, - layoutAttributes: _$layout_attributes_957, - supplyDefaults: _$supplyDefaults_953, - supplyLayoutDefaults: _$supplyLayoutDefaults_958, - calc: _$calc_952, - setPositions: _$setPositions_960, - plot: _$plot_959, - style: _$style_961, - hoverPoints: _$hoverPoints_955, - selectPoints: _$selectPoints_699, +var _$violin_1027 = { + attributes: _$attributes_1022, + layoutAttributes: _$layout_attributes_1028, + supplyDefaults: _$supplyDefaults_1024, + supplyLayoutDefaults: _$supplyLayoutDefaults_1029, + calc: _$calc_1023, + setPositions: _$setPositions_1031, + plot: _$plot_1030, + style: _$style_1032, + hoverPoints: _$hoverPoints_1026, + selectPoints: _$selectPoints_762, moduleType: 'trace', name: 'violin', - basePlotModule: _$cartesian_595, - categories: ['cartesian', 'symbols', 'oriented', 'box-violin', 'showLegend'], + basePlotModule: _$cartesian_658, + categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'draggedPts', 'violinLayout'], meta: { } @@ -181455,7 +185267,7 @@ var _$violin_956 = { 'use strict'; -var _$violin_38 = _$violin_956; +var _$violin_39 = _$violin_1027; /** * Copyright 2012-2018, Plotly, Inc. @@ -181480,16 +185292,18 @@ _$core_12.register([ _$pie_24, _$contour_10, _$scatterternary_34, - _$violin_38, + _$violin_39, _$scatter3d_27, - _$surface_36, + _$surface_37, _$mesh3d_21, _$scattergeo_29, _$choropleth_9, _$scattergl_30, + _$splom_36, + _$pointcloud_25, _$heatmapgl_16, _$parcoords_23, @@ -181498,7 +185312,7 @@ _$core_12.register([ _$sankey_26, - _$table_37, + _$table_38, _$carpet_8, _$scattercarpet_28, diff --git a/dist/plotly.min.js b/dist/plotly.min.js index c4743479b5a..849ce54c45a 100644 --- a/dist/plotly.min.js +++ b/dist/plotly.min.js @@ -1,7 +1,7 @@ /** -* plotly.js v1.35.2 +* plotly.js v1.36.0 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){var t={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},e={exports:{}};!function(){var t={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},i=this.document;function a(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(i)try{n(i.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),i)try{i.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var s=this.Element.prototype,l=s.setAttribute,u=s.setAttributeNS,c=this.CSSStyleDeclaration.prototype,h=c.setProperty;s.setAttribute=function(t,e){l.call(this,t,e+"")},s.setAttributeNS=function(t,e,r){u.call(this,t,e,r+"")},c.setProperty=function(t,e,r){h.call(this,t,e+"",r)}}function f(t,e){return te?1:t>=e?0:NaN}function p(t){return null===t?NaN:+t}function d(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}t.ascending=f,t.descending=function(t,e){return et?1:e>=t?0:NaN},t.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},t.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},t.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),i=n){r=i=n;break}for(;++an&&(r=n),i1)return o/(l-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(f);function m(t){return t.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(t){return g(1===t.length?function(e,r){return f(t(e),r)}:t)},t.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=i.length)return r?r.call(n,a):e?a.sort(e):a;for(var l,u,c,h,f=-1,p=a.length,d=i[s++],g=new b;++f=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(V,"\\$&")};var V=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,U={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function q(t){return U(t,Y),t}var H=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},W=function(t,e){var r=t.matches||t[I(t,"matchesSelector")];return(W=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(H=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,W=Sizzle.matchesSelector),t.selection=function(){return t.select(i.documentElement)};var Y=t.selection.prototype=[];function X(t){return"function"==typeof t?t:function(){return H(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}Y.select=function(t){var e,r,n,i,a=[];t=X(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},Y.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each(Q(r,e[r]));return this}return this.each(Q(e,r))},Y.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},Y.sort=function(t){t=function(t){arguments.length||(t=f);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(e=e.slice(0,o));var l=dt.get(e);function u(){var t=this[a];t&&(this.removeEventListener(e,t,t.$),delete this[a])}return l&&(e=l,s=vt),o?r?function(){var t=s(r,n(arguments));u.call(this),this.addEventListener(e,this[a]=t,t.$=i),t._=r}:u:r?O:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}t.selection.enter=ht,t.selection.enter.prototype=ft,ft.append=Y.append,ft.empty=Y.empty,ft.node=Y.node,ft.call=Y.call,ft.size=Y.size,ft.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s=n&&(n=e+1);!(o=s[n])&&++n0?1:t<0?-1:0}function Pt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function It(t){return t>1?0:t<-1?kt:Math.acos(t)}function Dt(t){return t>1?Et:t<-1?-Et:Math.asin(t)}function Ot(t){return((t=Math.exp(t))+1/t)/2}function Rt(t){return(t=Math.sin(t/2))*t}var Ft=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,h=l-a,f=c*c+h*h;if(f0&&(e=e.transition().duration(g)),e.call(w.event)}function S(){u&&u.domain(l.range().map(function(t){return(t-f.x)/f.k}).map(l.invert)),h&&h.domain(c.range().map(function(t){return(t-f.y)/f.k}).map(c.invert))}function E(t){v++||t({type:"zoomstart"})}function C(t){S(),t({type:"zoom",scale:f.k,translate:[f.x,f.y]})}function L(t){--v||(t({type:"zoomend"}),r=null)}function z(){var e=this,r=_.of(e,arguments),n=0,i=t.select(o(e)).on(y,function(){n=1,k(t.mouse(e),a),C(r)}).on(x,function(){i.on(y,null).on(x,null),s(n),L(r)}),a=M(t.mouse(e)),s=xt(e);ss.call(e),E(r)}function P(){var e,r=this,n=_.of(r,arguments),i={},a=0,o=".zoom-"+t.event.changedTouches[0].identifier,l="touchmove"+o,u="touchend"+o,c=[],h=t.select(r),p=xt(r);function d(){var n=t.touches(r);return e=f.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=M(t))}),n}function g(){var e=t.event.target;t.select(e).on(l,v).on(u,y),c.push(e);for(var n=t.event.changedTouches,o=0,h=n.length;o1){m=p[0];var x=p[1],b=m[0]-x[0],_=m[1]-x[1];a=b*b+_*_}}function v(){var o,l,u,c,h=t.touches(r);ss.call(r);for(var f=0,p=h.length;f360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Xt?e.l:(e=fe((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}qt.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Ut(this.h,this.s,this.l/t)},qt.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Ut(this.h,this.s,t*this.l)},qt.rgb=function(){return Ht(this.h,this.s,this.l)},t.hcl=Gt;var Wt=Gt.prototype=new Vt;function Yt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Xt(r,Math.cos(t*=Ct)*e,Math.sin(t)*e)}function Xt(t,e,r){return this instanceof Xt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Xt?new Xt(t.l,t.a,t.b):t instanceof Gt?Yt(t.h,t.c,t.l):fe((t=ae(t)).r,t.g,t.b):new Xt(t,e,r)}Wt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Wt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Wt.rgb=function(){return Yt(this.h,this.c,this.l).rgb()},t.lab=Xt;var Zt=18,Jt=.95047,Kt=1,Qt=1.08883,$t=Xt.prototype=new Vt;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*Jt)-1.5371385*(n=re(n)*Kt)-.4985314*(a=re(a)*Qt)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ce(""+t,ae,Ht):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}$t.brighter=function(t){return new Xt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},$t.darker=function(t){return new Xt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},$t.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ae;var le=ae.prototype=new Vt;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(de(i[0]),de(i[1]),de(i[2]))}return(a=ge.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function he(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e0&&l<1?0:n),new Ut(n,i,l)}function fe(t,e,r){var n=ne((.4124564*(t=pe(t))+.3575761*(e=pe(e))+.1804375*(r=pe(r)))/Jt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Xt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/Qt)))}function pe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function de(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(o,u)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(e)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=h:u.onreadystatechange=function(){u.readyState>3&&h()},u.onprogress=function(e){var r=t.event;t.event=e;try{s.progress.call(o,u)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(t,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),u.open(t,e,!0),null==r||"accept"in l||(l.accept=r+",*/*"),u.setRequestHeader)for(var a in l)u.setRequestHeader(a,l[a]);return null!=r&&u.overrideMimeType&&u.overrideMimeType(r),null!=c&&(u.responseType=c),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,u),u.send(null==n?null:n),o},o.abort=function(){return u.abort(),o},t.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}ge.forEach(function(t,e){ge.set(t,oe(e))}),t.functor=ve,t.xhr=me(z),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ye(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,u=0,c=0;function h(){if(u>=l)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(ke,e)),_e=0):(_e=1,Me(ke))}function Te(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Se(){for(var t,e=xe,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ee(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Ce[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,ze=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Ee(e,r))).toFixed(Math.max(0,Math.min(20,Ee(e*(1+1e-15),r))))}});function Pe(t){return t+""}var Ie=t.time={},De=Date;function Oe(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Oe.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(){Re.setUTCDate.apply(this._,arguments)},setDay:function(){Re.setUTCDay.apply(this._,arguments)},setFullYear:function(){Re.setUTCFullYear.apply(this._,arguments)},setHours:function(){Re.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Re.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Re.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Re.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Re.setUTCSeconds.apply(this._,arguments)},setTime:function(){Re.setTime.apply(this._,arguments)}};var Re=Date.prototype;function Fe(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r1)for(;o68?1900:2e3),r+i[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function $e(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,i=y(e)%60;return r+Ue(n,"0",2)+Ue(i,"0",2)}function ar(t,e,r){Ve.lastIndex=0;var n=Ve.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:z;return function(e){var n=Le.exec(e),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",u=n[4]||"",c=n[5],h=+n[6],f=n[7],p=n[8],d=n[9],g=1,v="",m="",y=!1,x=!0;switch(p&&(p=+p.substring(1)),(c||"0"===i&&"="===s)&&(c=i="0",s="="),d){case"n":f=!0,d="g";break;case"%":g=100,m="%",d="f";break;case"p":g=100,m="%",d="r";break;case"b":case"o":case"x":case"X":"#"===u&&(v="0"+d.toLowerCase());case"c":x=!1;case"d":y=!0,p=0;break;case"s":g=-1,d="r"}"$"===u&&(v=a[0],m=a[1]),"r"!=d||p||(d="g"),null!=p&&("g"==d?p=Math.max(1,Math.min(21,p)):"e"!=d&&"f"!=d||(p=Math.max(0,Math.min(20,p)))),d=ze.get(d)||Pe;var b=c&&f;return function(e){var n=m;if(y&&e%1)return"";var a=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===l?"":l;if(g<0){var u=t.formatPrefix(e,p);e=u.scale(e),n=u.symbol+m}else e*=g;var _,w,M=(e=d(e,p)).lastIndexOf(".");if(M<0){var A=x?e.lastIndexOf("e"):-1;A<0?(_=e,w=""):(_=e.substring(0,A),w=e.substring(A))}else _=e.substring(0,M),w=r+e.substring(M+1);!c&&f&&(_=o(_,1/0));var k=v.length+_.length+w.length+(b?0:a.length),T=k"===s?T+a+e:"^"===s?T.substring(0,k>>=1)+a+e+T.substring(k):a+(b?e:T+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,i=e.time,a=e.periods,o=e.days,s=e.shortDays,l=e.months,u=e.shortMonths;function c(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s=u)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in Ne?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(De=Oe);return r._=t,e(r)}finally{De=Date}}return r.parse=function(t){try{De=Oe;var r=e.parse(t);return r&&r._}finally{De=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var f=t.map(),p=qe(o),d=He(o),g=qe(s),v=He(s),m=qe(l),y=He(l),x=qe(u),b=He(u);a.forEach(function(t,e){f.set(t.toLowerCase(),e)});var _={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:c(r),d:function(t,e){return Ue(t.getDate(),e,2)},e:function(t,e){return Ue(t.getDate(),e,2)},H:function(t,e){return Ue(t.getHours(),e,2)},I:function(t,e){return Ue(t.getHours()%12||12,e,2)},j:function(t,e){return Ue(1+Ie.dayOfYear(t),e,3)},L:function(t,e){return Ue(t.getMilliseconds(),e,3)},m:function(t,e){return Ue(t.getMonth()+1,e,2)},M:function(t,e){return Ue(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return Ue(t.getSeconds(),e,2)},U:function(t,e){return Ue(Ie.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ue(Ie.mondayOfYear(t),e,2)},x:c(n),X:c(i),y:function(t,e){return Ue(t.getFullYear()%100,e,2)},Y:function(t,e){return Ue(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){p.lastIndex=0;var n=p.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return h(t,_.c.toString(),e,r)},d:Qe,e:Qe,H:tr,I:tr,j:$e,L:nr,m:Ke,M:er,p:function(t,e,r){var n=f.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:We,w:Ge,W:Ye,x:function(t,e,r){return h(t,_.x.toString(),e,r)},X:function(t,e,r){return h(t,_.X.toString(),e,r)},y:Ze,Y:Xe,Z:Je,"%":ar};return c}(e)}};var sr=t.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"]});function lr(){}t.format=sr.numberFormat,t.geo={},lr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new lr;function cr(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function hr(t,e){t&&pr.hasOwnProperty(t.type)&&pr[t.type](t,e)}t.geo.stream=function(t,e){t&&fr.hasOwnProperty(t.type)?fr[t.type](t,e):hr(t,e)};var fr={Feature:function(t,e){hr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=o*a,l=Math.cos(e),u=Math.sin(e),c=i*u,h=n*l+c*Math.cos(s),f=c*o*Math.sin(s);Er.add(Math.atan2(f,h)),r=t,n=l,i=u}Cr.point=function(o,s){Cr.point=a,r=(t=o)*Ct,n=Math.cos(s=(e=s)*Ct/2+kt/4),i=Math.sin(s)},Cr.lineEnd=function(){a(t,e)}}function zr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Pr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Ir(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Dr(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Or(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Rr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Fr(t){return[Math.atan2(t[1],t[0]),Dt(t[2])]}function Br(t,e){return y(t[0]-e[0])Mt?i=90:u<-Mt&&(r=-90),h[0]=e,h[1]=n}};function p(t,a){c.push(h=[e=t,n=t]),ai&&(i=a)}function d(t,o){var s=zr([t*Ct,o*Ct]);if(l){var u=Ir(l,s),c=Ir([u[1],-u[0],0],u);Rr(c),c=Fr(c);var h=t-a,f=h>0?1:-1,d=c[0]*Lt*f,g=y(h)>180;if(g^(f*ai&&(i=v);else if(g^(f*a<(d=(d+360)%360-180)&&di&&(i=o);g?t_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(tn&&(n=t)):t>a?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else p(t,o);l=s,a=t}function g(){f.point=d}function v(){h[0]=e,h[1]=n,f.point=p,l=null}function m(t,e){if(l){var r=t-a;u+=y(r)>180?r+(r>0?360:-360):r}else o=t,s=e;Cr.point(t,e),d(t,e)}function x(){Cr.lineStart()}function b(){m(o,s),Cr.lineEnd(),y(u)>Mt&&(e=-(n=180)),h[0]=e,h[1]=n,l=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function M(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(g[0],g[1])&&(g[1]=p[1]),_(p[0],g[1])>_(g[0],g[1])&&(g[0]=p[0])):s.push(g=p);for(var l,u,p,d=-1/0,g=(o=0,s[u=s.length-1]);o<=u;g=p,++o)p=s[o],(l=_(g[1],p[0]))>d&&(d=l,e=p[0],n=g[1])}return c=h=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,i]]}}(),t.geo.centroid=function(e){mr=yr=xr=br=_r=wr=Mr=Ar=kr=Tr=Sr=0,t.geo.stream(e,Nr);var r=kr,n=Tr,i=Sr,a=r*r+n*n+i*i;return a=0;--s)i.point((h=c[s])[0],h[1]);else n(p.x,p.p.x,-1,i);p=p.p}c=(p=p.o).z,d=!d}while(!p.v);i.lineEnd()}}}function Xr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,M=w*_,A=M>kt,k=d*x;if(Er.add(Math.atan2(k*w*Math.sin(M),g*b+k*Math.cos(M))),a+=A?_+w*Tt:_,A^f>=r^m>=r){var T=Ir(zr(h),zr(t));Rr(T);var S=Ir(i,T);Rr(S);var E=(A^_>=0?-1:1)*Dt(S[2]);(n>E||n===E&&(T[0]||T[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;f=m,d=x,g=b,h=t}}return(a<-Mt||a0){for(x||(o.polygonStart(),x=!0),o.lineStart();++a1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return c}}function Kr(t){return t.length>1}function Qr(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:O,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function $r(t,e){return((t=t.x)[0]<0?t[1]-Et-Mt:Et-t[1])-((e=e.x)[0]<0?e[1]-Et-Mt:Et-e[1])}var tn=Jr(Wr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?kt:-kt,l=y(a-r);y(l-kt)0?Et:-Et),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=kt&&(y(r-i)Mt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Et,n.point(-kt,i),n.point(0,i),n.point(kt,i),n.point(kt,0),n.point(kt,-i),n.point(0,-i),n.point(-kt,-i),n.point(-kt,0),n.point(-kt,i);else if(y(t[0]-e[0])>Mt){var a=t[0]0)){if(a/=f,f<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=r-l,f||!(a<0)){if(a/=f,f<0){if(a>h)return;a>c&&(c=a)}else if(f>0){if(a0)){if(a/=p,p<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=n-u,p||!(a<0)){if(a/=p,p<0){if(a>h)return;a>c&&(c=a)}else if(p>0){if(a0&&(i.a={x:l+c*f,y:u+c*p}),h<1&&(i.b={x:l+h*f,y:u+h*p}),i}}}}}}var rn=1e9;function nn(e,r,n,i){return function(l){var u,c,h,f,p,d,g,v,m,y,x,b=l,_=Qr(),w=en(e,r,n,i),M={point:T,lineStart:function(){M.point=S,c&&c.push(h=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){u&&(S(f,p),d&&m&&_.rejoin(),u.push(_.buffer()));M.point=T,m&&l.lineEnd()},polygonStart:function(){l=_,u=[],c=[],x=!0},polygonEnd:function(){l=b,u=t.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],i=0;in&&Pt(u,a,t)>0&&++e:a[1]<=n&&Pt(u,a,t)<0&&--e,u=a;return 0!==e}([e,i]),n=x&&r,a=u.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),A(null,null,1,l),l.lineEnd()),a&&Yr(u,o,r,A,l),l.polygonEnd()),u=c=h=null}};function A(t,o,l,u){var c=0,h=0;if(null==t||(c=a(t,l))!==(h=a(o,l))||s(t,o)<0^l>0)do{u.point(0===c||3===c?e:n,c>1?i:r)}while((c=(c+l+4)%4)!==h);else u.point(o[0],o[1])}function k(t,a){return e<=t&&t<=n&&r<=a&&a<=i}function T(t,e){k(t,e)&&l.point(t,e)}function S(t,e){var r=k(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&h.push([t,e]),y)f=t,p=e,d=r,y=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&m)l.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),x=!1):r&&(l.lineStart(),l.point(t,e),x=!1)}g=t,v=e,m=r}return M};function a(t,i){return y(t[0]-e)0?0:3:y(t[0]-n)0?2:1:y(t[1]-r)0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=kt/3,n=Sn(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*kt/180,r=t[1]*kt/180):[e/kt*180,r/kt*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,Dt((i-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,i,a=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};function u(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}return u.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},u.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),u):a.precision()},u.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),u.translate(a.translate())):a.scale()},u.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),c=+t[0],h=+t[1];return r=a.translate(t).clipExtent([[c-.455*e,h-.238*e],[c+.455*e,h+.238*e]]).stream(l).point,n=o.translate([c-.307*e,h+.201*e]).clipExtent([[c-.425*e+Mt,h+.12*e+Mt],[c-.214*e-Mt,h+.234*e-Mt]]).stream(l).point,i=s.translate([c-.205*e,h+.212*e]).clipExtent([[c-.214*e+Mt,h+.166*e+Mt],[c-.115*e-Mt,h+.234*e-Mt]]).stream(l).point,u},u.scale(1070)};var sn,ln,un,cn,hn,fn,pn={point:O,lineStart:O,lineEnd:O,polygonStart:function(){ln=0,pn.lineStart=dn},polygonEnd:function(){pn.lineStart=pn.lineEnd=pn.point=O,sn+=y(ln/2)}};function dn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}pn.point=function(a,o){pn.point=i,t=r=a,e=n=o},pn.lineEnd=function(){i(t,e)}}var gn={point:function(t,e){thn&&(hn=t);efn&&(fn=e)},lineStart:O,lineEnd:O,polygonStart:O,polygonEnd:O};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,yn={point:xn,lineStart:bn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=xn,yn.lineStart=bn,yn.lineEnd=_n}};function xn(t,e){xr+=t,br+=e,++_r}function bn(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,Mr+=o*(e+n)/2,Ar+=o,xn(t=r,e=n)}yn.point=function(n,i){yn.point=r,xn(t=n,e=i)}}function _n(){yn.point=xn}function wn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,Mr+=o*(n+e)/2,Ar+=o,kr+=(o=n*t-r*e)*(r+t),Tr+=o*(n+e),Sr+=3*o,xn(r=t,n=e)}yn.point=function(a,o){yn.point=i,xn(t=r=a,e=n=o)},yn.lineEnd=function(){i(t,e)}}function Mn(t){var e=.5,r=Math.cos(30*Ct),n=16;function i(e){return(n?function(e){var r,i,o,s,l,u,c,h,f,p,d,g,v={point:m,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){h=NaN,v.point=x,e.lineStart()}function x(r,i){var o=zr([r,i]),s=t(r,i);a(h,f,c,p,d,g,h=s[0],f=s[1],c=r,p=o[0],d=o[1],g=o[2],n,e),e.point(h,f)}function b(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=M}function w(t,e){x(r=t,e),i=h,o=f,s=p,l=d,u=g,v.point=x}function M(){a(h,f,c,p,d,g,i,o,r,s,l,u,n,e),v.lineEnd=b,b()}return v}:function(e){return kn(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,u,c,h,f,p,d,g,v,m){var x=c-n,b=h-i,_=x*x+b*b;if(_>4*e&&v--){var w=s+p,M=l+d,A=u+g,k=Math.sqrt(w*w+M*M+A*A),T=Math.asin(A/=k),S=y(y(A)-1)e||y((x*z+b*P)/_-.5)>.3||s*p+l*d+u*g0&&16,i):Math.sqrt(e)},i}function An(t){this.stream=t}function kn(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Tn(t){return Sn(function(){return t})()}function Sn(e){var r,n,i,a,o,s,l=Mn(function(t,e){return[(t=r(t,e))[0]*u+a,o-t[1]*u]}),u=150,c=480,h=250,f=0,p=0,d=0,g=0,v=0,m=tn,x=z,b=null,_=null;function w(t){return[(t=i(t[0]*Ct,t[1]*Ct))[0]*u+a,o-t[1]*u]}function M(t){return(t=i.invert((t[0]-a)/u,(o-t[1])/u))&&[t[0]*Lt,t[1]*Lt]}function A(){i=Gr(n=zn(d,g,v),r);var t=r(f,p);return a=c-t[0]*u,o=h+t[1]*u,k()}function k(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=En(m(n,l(x(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(m=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>Mt;return Jr(i,function(t){var e,s,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(h,f){var p,d=[h,f],g=i(h,f),v=r?g?0:o(h,f):g?o(h+(h<0?kt:-kt),f):0;if(!e&&(u=l=g)&&t.lineStart(),g!==l&&(p=a(e,d),(Br(e,p)||Br(d,p))&&(d[0]+=Mt,d[1]+=Mt,g=i(d[0],d[1]))),g!==l)c=0,g?(t.lineStart(),p=a(d,e),t.point(p[0],p[1])):(p=a(e,d),t.point(p[0],p[1]),t.lineEnd()),e=p;else if(n&&e&&r^g){var m;v&s||!(m=a(d,e,!0))||(c=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&Br(e,d)||t.point(d[0],d[1]),e=d,l=g,s=v},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return c|(u&&l)<<1}}},On(t,6*Ct),r?[0,-t]:[-kt,t-kt]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Ir(zr(t),zr(r)),o=Pr(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var u=e*o/l,c=-e*s/l,h=Ir(i,a),f=Or(i,u);Dr(f,Or(a,c));var p=h,d=Pr(f,p),g=Pr(p,p),v=d*d-g*(Pr(f,f)-1);if(!(v<0)){var m=Math.sqrt(v),x=Or(p,(-d-m)/g);if(Dr(x,f),x=Fr(x),!n)return x;var b,_=t[0],w=r[0],M=t[1],A=r[1];w<_&&(b=_,_=w,w=b);var k=w-_,T=y(k-kt)0^x[1]<(y(x[0]-_)kt^(_<=x[0]&&x[0]<=w)){var S=Or(p,(-d+m)/g);return Dr(S,f),[x,Fr(S)]}}}function o(e,n){var i=r?t:kt-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((b=+t)*Ct),k()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):z,k()):_},w.scale=function(t){return arguments.length?(u=+t,A()):u},w.translate=function(t){return arguments.length?(c=+t[0],h=+t[1],A()):[c,h]},w.center=function(t){return arguments.length?(f=t[0]%360*Ct,p=t[1]%360*Ct,A()):[f*Lt,p*Lt]},w.rotate=function(t){return arguments.length?(d=t[0]%360*Ct,g=t[1]%360*Ct,v=t.length>2?t[2]%360*Ct:0,A()):[d*Lt,g*Lt,v*Lt]},t.rebind(w,l,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&M,A()}}function En(t){return kn(t,function(e,r){t.point(e*Ct,r*Ct)})}function Cn(t,e){return[t,e]}function Ln(t,e){return[t>kt?t-Tt:t<-kt?t+Tt:t,e]}function zn(t,e,r){return t?e||r?Gr(In(t),Dn(e,r)):In(t):e||r?Dn(e,r):Ln}function Pn(t){return function(e,r){return[(e+=t)>kt?e-Tt:e<-kt?e+Tt:e,r]}}function In(t){var e=Pn(t);return e.invert=Pn(-t),e}function Dn(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*r+s*n;return[Math.atan2(l*i-c*a,s*r-u*n),Dt(c*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*i-l*a;return[Math.atan2(l*i+u*a,s*r+c*n),Dt(c*r-s*n)]},o}function On(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Rn(r,i),a=Rn(r,a),(o>0?ia)&&(i+=o*Tt)):(i=t+o*Tt,a=t-.5*l);for(var u,c=i;o>0?c>a:c2?t[2]*Ct:0),e.invert=function(e){return(e=t.invert(e[0]*Ct,e[1]*Ct))[0]*=Lt,e[1]*=Lt,e},e},Ln.invert=Cn,t.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=zn(-t[0]*Ct,-t[1]*Ct,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=On((t=+r)*Ct,n*Ct),i):t},i.precision=function(r){return arguments.length?(e=On(t*Ct,(n=+r)*Ct),i):n},i.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ct,i=t[1]*Ct,a=e[1]*Ct,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((r=h*o)*r+(r=u*c-l*h*s)*r),l*c+u*h*s)},t.geo.graticule=function(){var e,r,n,i,a,o,s,l,u,c,h,f,p=10,d=p,g=90,v=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(i/g)*g,n,g).map(h).concat(t.range(Math.ceil(l/v)*v,s,v).map(f)).concat(t.range(Math.ceil(r/p)*p,e,p).filter(function(t){return y(t%g)>Mt}).map(u)).concat(t.range(Math.ceil(o/d)*d,a,d).filter(function(t){return y(t%v)>Mt}).map(c))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(f(s).slice(1),h(n).reverse().slice(1),f(l).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),x.precision(m)):[[i,l],[n,s]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),o>a&&(t=o,o=a,a=t),x.precision(m)):[[r,o],[e,a]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],x):[g,v]},x.minorStep=function(t){return arguments.length?(p=+t[0],d=+t[1],x):[p,d]},x.precision=function(t){return arguments.length?(m=+t,u=Fn(o,a,90),c=Bn(r,e,m),h=Fn(l,s,90),f=Bn(i,n,m),x):m},x.majorExtent([[-180,-90+Mt],[180,90-Mt]]).minorExtent([[-180,-80-Mt],[180,80+Mt]])},t.geo.greatArc=function(){var e,r,n=Nn,i=jn;function a(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},t.geo.interpolate=function(t,e){return r=t[0]*Ct,n=t[1]*Ct,i=e[0]*Ct,a=e[1]*Ct,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),u=Math.sin(a),c=o*Math.cos(r),h=o*Math.sin(r),f=l*Math.cos(i),p=l*Math.sin(i),d=2*Math.asin(Math.sqrt(Rt(a-n)+o*l*Rt(i-r))),g=1/Math.sin(d),(v=d?function(t){var e=Math.sin(t*=d)*g,r=Math.sin(d-t)*g,n=r*c+e*f,i=r*h+e*p,a=r*s+e*u;return[Math.atan2(i,n)*Lt,Math.atan2(a,Math.sqrt(n*n+i*i))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=d,v;var r,n,i,a,o,s,l,u,c,h,f,p,d,g,v},t.geo.length=function(e){return mn=0,t.geo.stream(e,Vn),mn};var Vn={sphere:O,point:O,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=Ct),o=Math.cos(i),s=y((n*=Ct)-t),l=Math.cos(s);mn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}Vn.point=function(i,a){t=i*Ct,e=Math.sin(a*=Ct),r=Math.cos(a),Vn.point=n},Vn.lineEnd=function(){Vn.point=Vn.lineEnd=O}},lineEnd:O,polygonStart:O,polygonEnd:O};function Un(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var qn=Un(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return Tn(qn)}).raw=qn;var Hn=Un(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},z);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(kt/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return Xn;function o(t,e){a>0?e<-Et+Mt&&(e=-Et+Mt):e>Et-Mt&&(e=Et-Mt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=zt(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-Et]},o}function Wn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(y(n)1&&Pt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return Tn(Kn)}).raw=Kn,Qn.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Et]},(t.geo.transverseMercator=function(){var t=Zn(Qn),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=Qn,t.geom={},t.geom.hull=function(t){var e=$n,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=ve(e),a=ve(r),o=t.length,s=[],l=[];for(n=0;n=0;--n)p.push(t[s[u[n]][2]]);for(n=+h;nMt)s=s.L;else{if(!((i=a-xi(s,o))>Mt)){n>-Mt?(e=s.P,r=s):i>-Mt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=di(t);if(ui.insert(e,l),e||r){if(e===r)return Mi(e),r=di(e.site),ui.insert(l,r),l.edge=r.edge=Ti(e.site,l.site),wi(e),void wi(r);if(r){Mi(e),Mi(r);var u=e.site,c=u.x,h=u.y,f=t.x-c,p=t.y-h,d=r.site,g=d.x-c,v=d.y-h,m=2*(f*v-p*g),y=f*f+p*p,x=g*g+v*v,b={x:(v*y-p*x)/m+c,y:(f*x-g*y)/m+h};Si(r.edge,u,d,b),l.edge=Ti(u,t,null,b),r.edge=Ti(t,d,null,b),wi(e),wi(r)}else l.edge=Ti(e.site,l.site)}}function yi(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,u=l-e;if(!u)return s;var c=s-n,h=1/a-1/u,f=c/u;return h?(-f+Math.sqrt(f*f-2*h*(c*c/(-2*u)-l+u/2+i-a/2)))/h+n:(n+s)/2}function xi(t,e){var r=t.N;if(r)return yi(r,e);var n=t.site;return n.y===e?n.x:1/0}function bi(t){this.site=t,this.edges=[]}function _i(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,u=n.y-s,c=a.x-o,h=2*(l*(v=a.y-s)-u*c);if(!(h>=-At)){var f=l*l+u*u,p=c*c+v*v,d=(v*f-u*p)/h,g=(l*p-c*f)/h,v=g+s,m=pi.pop()||new function(){Li(this),this.x=this.y=this.arc=this.site=this.cy=null};m.arc=t,m.site=i,m.x=d+o,m.y=v+Math.sqrt(d*d+g*g),m.cy=v,t.circle=m;for(var y=null,x=hi._;x;)if(m.y=s)return;if(f>d){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.y1)if(f>d){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.y=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xMt||y(i-r)>Mt)&&(s.splice(o,0,new Ei((m=a.site,x=c,b=y(n-h)Mt?{x:h,y:y(e-h)Mt?{x:y(r-d)Mt?{x:f,y:y(e-f)Mt?{x:y(r-p)=r&&u.x<=i&&u.y>=n&&u.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/Mt)*Mt,y:Math.round(i(t,e)/Mt)*Mt,i:e}})}return o.links=function(t){return Di(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Di(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,u=r.edges.sort(_i),c=-1,h=u.length,f=u[h-1].edge,p=f.l===l?f.r:f.l;++ca&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Vi(r,n)})),a=Hi.lastIndex;return ag&&(g=l.x),l.y>v&&(v=l.y),u.push(l.x),c.push(l.y);else for(h=0;hg&&(g=b),_>v&&(v=_),u.push(b),c.push(_)}var w=g-p,M=v-d;function A(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,u=t.y;if(null!=l)if(y(l-r)+y(u-n)<.01)k(t,e,r,n,i,a,o,s);else{var c=t.point;t.x=t.y=t.point=null,k(t,c,l,u,i,a,o,s),k(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else k(t,e,r,n,i,a,o,s)}function k(t,e,r,n,i,a,o,s){var l=.5*(i+o),u=.5*(a+s),c=r>=l,h=n>=u,f=h<<1|c;t.leaf=!1,t=t.nodes[f]||(t.nodes[f]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(T,t,+m(t,++h),+x(t,h),p,d,g,v)}}),c?i=l:o=l,h?a=u:s=u,A(t,e,r,n,i,a,o,s)}w>M?v=d+w:g=p+M;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){A(T,t,+m(t,++h),+x(t,h),p,d,g,v)}};if(T.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),u=r.nodes;u[0]&&t(e,u[0],n,i,s,l),u[1]&&t(e,u[1],s,i,a,l),u[2]&&t(e,u[2],n,l,s,o),u[3]&&t(e,u[3],s,l,a,o)}}(t,T,p,d,g,v)},T.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(u,c,h,f,p){if(!(c>a||h>o||f=_)<<1|e>=b,M=w+4;w=0&&!(n=t.interpolators[i](e,r)););return n}function Wi(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ea(t){return 1-Math.cos(t*Et)}function ra(t){return Math.pow(2,10*(t-1))}function na(t){return 1-Math.sqrt(1-t*t)}function ia(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}function aa(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oa(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=la(i),s=sa(i,a),l=la(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Xi.get(i)||Yi,a=Zi.get(a)||z,e=a(i.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,i=e.c,a=e.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Yt(n+o*t,i+s*t,a+l*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,i=e.s,a=e.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Ht(n+o*t,i+s*t,a+l*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,i=e.a,a=e.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},t.interpolateRound=aa,t.transform=function(e){var r=i.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oa(e?e.matrix:ua)})(e)},oa.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ua={a:1,b:0,c:0,d:1,e:0,f:0};function ca(t){return t.length?t.pop()+",":""}function ha(e,r){var n=[],i=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ca(r)+"rotate(",null,")")-2,x:Vi(t,e)})):e&&r.push(ca(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(ca(r)+"skewX(",null,")")-2,x:Vi(t,e)}):e&&r.push(ca(r)+"skewX("+e+")")}(e.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(ca(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ca(r)+"scale("+e+")")}(e.scale,r.scale,n,i),e=r=null,function(t){for(var e,r=-1,a=i.length;++r0?n=t:(e.c=null,e.t=NaN,e=null,l.end({type:"end",alpha:n=0})):t>0&&(l.start({type:"start",alpha:n=t}),e=Ae(s.tick)),s):n},s.start=function(){var t,e,r,n=m.length,l=y.length,c=u[0],d=u[1];for(t=0;t=0;)r.push(i[n])}function ka(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;r&&(a.value=0),a.children=u}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return ka(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Aa(t,function(t){t.children&&(t.value=0)}),ka(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var i=e.call(this,t,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++us&&(s=n),o.push(n)}for(r=0;ri&&(n=r,i=e);return n}function Na(t){return t.reduce(ja,0)}function ja(t,e){return t+e[1]}function Va(t,e){return Ua(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Ua(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function qa(e){return[t.min(e),t.max(e)]}function Ha(t,e){return t.value-e.value}function Ga(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Wa(t,e){t._pack_next=e,e._pack_prev=t}function Ya(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Xa(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,u=1/0,c=-1/0,h=1/0,f=-1/0;if(e.forEach(Za),(r=e[0]).x=-r.r,r.y=0,x(r),l>1&&((n=e[1]).x=n.r,n.y=0,x(n),l>2))for(Ka(r,n,i=e[2]),x(i),Ga(r,i),r._pack_prev=i,Ga(i,n),n=r._pack_next,a=3;a0)for(o=-1;++o=h[0]&&l<=h[1]&&((s=u[t.bisect(f,l,1,d)-1]).y+=g,s.push(a[o]));return u}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=ve(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Ua(e,t)}:ve(t),a):i},a.frequency=function(t){return arguments.length?(e=!!t,a):e},a},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Ha),n=0,i=[1,1];function a(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,ka(s,function(t){t.r=+c(t.value)}),ka(s,Xa),n){var h=n*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;ka(s,function(t){t.r+=h}),ka(s,Xa),ka(s,function(t){t.r-=h})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++op.x&&(p=t),t.depth>d.depth&&(d=t)});var g=r(f,p)/2-f.x,v=n[0]/(p.x+r(p,f)/2+g),m=n[1]/(d.depth||1);Aa(c,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return u}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],u=a.m,c=o.m,h=s.m,f=l.m;s=to(s),a=$a(a),s&&a;)l=$a(l),(o=to(o)).a=t,(i=s.z+h-a.z-u+r(s._,a._))>0&&(eo(ro(s,t,n),t,i),u+=i,c+=i),h+=s.m,u+=a.m,f+=l.m,c+=o.m;s&&!to(o)&&(o.t=s,o.m+=h-c),a&&!$a(l)&&(l.t=a,l.m+=u-f,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},Ma(a,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=Qa,n=[1,1],i=!1;function a(a,o){var s,l=e.call(this,a,o),u=l[0],c=0;ka(u,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=s?c+=r(e,s):0,e.y=0,s=e)});var h=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),f=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),p=h.x-r(h,f)/2,d=f.x+r(f,h)/2;return ka(u,i?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-p)/(d-p)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},Ma(a,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=no,s=!1,l="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,i=-1,a=t.length;++i0;)s.push(r=u[i-1]),s.area+=r.area,"squarify"!==l||(n=p(s,g))<=f?(u.pop(),f=n):(s.area-=s.pop().area,d(s,g,a,!1),g=Math.min(a.dx,a.dy),s.length=s.area=0,f=1/0);s.length&&(d(s,g,a,!0),s.length=s.area=0),e.forEach(h)}}function f(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(c(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(d(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(f)}}function p(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++oi&&(i=r));return e*=e,(n*=n)?Math.max(e*i*u/n,n/(e*a*u)):1/0}function d(t,e,r,i){var a,o=-1,s=t.length,l=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((i||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?ho:so,s=i?pa:fa;return a=t(e,r,s,n),o=t(r,e,s,Gi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(aa)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return vo(e,t)};l.tickFormat=function(t,r){return mo(e,t,r)};l.nice=function(t){return po(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Gi,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function xo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=lo(a.map(o),i?Math:_o);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=ao(a),e=[],r=t[0],l=t[1],u=Math.floor(o(r)),c=Math.ceil(o(l)),h=n%1?2:n;if(isFinite(c-u)){if(i){for(;u0;f--)e.push(s(u)*f);for(u=0;e[u]l;c--);e=e.slice(u,c)}return e};l.tickFormat=function(e,r){if(!arguments.length)return bo;arguments.length<2?r=bo:"function"!=typeof r&&(r=t.format(r));var i=Math.max(1,n*e/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n0?i[t-1]:r[0],th?0:1;if(u=St)return l(u,p)+(s?l(s,1-p):"")+"Z";var d,g,v,m,y,x,b,_,w,M,A,k,T=0,S=0,E=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Eo?Math.sqrt(s*s+u*u):+n.apply(this,arguments),p||(S*=-1),u&&(S=Dt(v/u*Math.sin(m))),s&&(T=Dt(v/s*Math.sin(m)))),u){y=u*Math.cos(c+S),x=u*Math.sin(c+S),b=u*Math.cos(h-S),_=u*Math.sin(h-S);var C=Math.abs(h-c-2*S)<=kt?0:1;if(S&&Do(y,x,b,_)===p^C){var L=(c+h)/2;y=u*Math.cos(L),x=u*Math.sin(L),b=_=null}}else y=x=0;if(s){w=s*Math.cos(h-T),M=s*Math.sin(h-T),A=s*Math.cos(c+T),k=s*Math.sin(c+T);var z=Math.abs(c-h+2*T)<=kt?0:1;if(T&&Do(w,M,A,k)===1-p^z){var P=(c+h)/2;w=s*Math.cos(P),M=s*Math.sin(P),A=k=null}}else w=M=0;if(f>Mt&&(d=Math.min(Math.abs(u-s)/2,+r.apply(this,arguments)))>.001){g=s0?0:1}function Oo(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,h=t[1]+u,f=e[0]+l,p=e[1]+u,d=(c+f)/2,g=(h+p)/2,v=f-c,m=p-h,y=v*v+m*m,x=r-n,b=c*p-f*h,_=(m<0?-1:1)*Math.sqrt(Math.max(0,x*x*y-b*b)),w=(b*m-v*_)/y,M=(-b*v-m*_)/y,A=(b*m+v*_)/y,k=(-b*v+m*_)/y,T=w-d,S=M-g,E=A-d,C=k-g;return T*T+S*S>E*E+C*C&&(w=A,M=k),[[w-l,M-u],[w*r/x,M*r/x]]}function Ro(t){var e=$n,r=ti,n=Wr,i=Bo,a=i.key,o=.7;function s(a){var s,l=[],u=[],c=-1,h=a.length,f=ve(e),p=ve(r);function d(){l.push("M",i(t(u),o))}for(;++c1&&i.push("H",n[0]);return i.join("")},"step-before":jo,"step-after":Vo,basis:Ho,"basis-open":function(t){if(t.length<4)return Bo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Go(Xo,a)+","+Go(Xo,o)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Bo(t){return t.length>1?t.join("L"):t+"Z"}function No(t){return t.join("L")+"Z"}function jo(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;ukt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=ve(t),a):r},a.source=function(e){return arguments.length?(t=ve(e),a):t},a.target=function(t){return arguments.length?(e=ve(t),a):e},a.startAngle=function(t){return arguments.length?(n=ve(t),a):n},a.endAngle=function(t){return arguments.length?(i=ve(t),a):i},a},t.svg.diagonal=function(){var t=Nn,e=jn,r=ts;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=ts,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Et;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var is=t.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*os)),r=e*os;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=is.keys();var as=Math.sqrt(3),os=Math.tan(30*Ct);Y.transition=function(t){for(var e,r,n=cs||++ps,i=vs(t),a=[],o=hs||{time:Date.now(),ease:ta,delay:0,duration:250},s=-1,l=this.length;++s0;)u[--f].call(t,o);if(a>=1)return h.event&&h.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}h||(a=i.time,o=Ae(function(t){var e=h.delay;if(o.t=e+a,e<=t)return f(t-e);o.c=f},0,a),h=c[n]={tween:new b,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++c.count)}fs.call=Y.call,fs.empty=Y.empty,fs.node=Y.node,fs.size=Y.size,t.transition=function(e,r){return e&&e.transition?cs?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=fs,fs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=X(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function g(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function v(){var h,v,m=this,y=t.select(t.event.target),x=n.of(m,arguments),b=t.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&i,M=!/^(e|w)$/.test(_)&&a,A=y.classed("extent"),k=xt(m),T=t.mouse(m),S=t.select(o(m)).on("keydown.brush",function(){32==t.event.keyCode&&(A||(h=null,T[0]-=s[1],T[1]-=l[1],A=2),B())}).on("keyup.brush",function(){32==t.event.keyCode&&2==A&&(T[0]+=s[1],T[1]+=l[1],A=0,B())});if(t.event.changedTouches?S.on("touchmove.brush",L).on("touchend.brush",P):S.on("mousemove.brush",L).on("mouseup.brush",P),b.interrupt().selectAll("*").interrupt(),A)T[0]=s[0]-T[0],T[1]=l[0]-T[1];else if(_){var E=+/w$/.test(_),C=+/^n/.test(_);v=[s[1-E]-T[0],l[1-C]-T[1]],T[0]=s[E],T[1]=l[C]}else t.event.altKey&&(h=T.slice());function L(){var e=t.mouse(m),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),A||(t.event.altKey?(h||(h=[(s[0]+s[1])/2,(l[0]+l[1])/2]),T[0]=s[+(e[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=Cs(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=Cs(+e+1);return e}}:t))},i.ticks=function(t,e){var r=ao(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Cs(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Es(e.copy(),r,n)},fo(i,e)}function Cs(t){return new Date(t)}As.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ss:Ts,Ss.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Ss.toString=Ts.toString,Ie.second=Fe(function(t){return new De(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),Ie.seconds=Ie.second.range,Ie.seconds.utc=Ie.second.utc.range,Ie.minute=Fe(function(t){return new De(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),Ie.minutes=Ie.minute.range,Ie.minutes.utc=Ie.minute.utc.range,Ie.hour=Fe(function(t){var e=t.getTimezoneOffset()/60;return new De(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),Ie.hours=Ie.hour.range,Ie.hours.utc=Ie.hour.utc.range,Ie.month=Fe(function(t){return(t=Ie.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),Ie.months=Ie.month.range,Ie.months.utc=Ie.month.utc.range;var Ls=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],zs=[[Ie.second,1],[Ie.second,5],[Ie.second,15],[Ie.second,30],[Ie.minute,1],[Ie.minute,5],[Ie.minute,15],[Ie.minute,30],[Ie.hour,1],[Ie.hour,3],[Ie.hour,6],[Ie.hour,12],[Ie.day,1],[Ie.day,2],[Ie.week,1],[Ie.month,1],[Ie.month,3],[Ie.year,1]],Ps=As.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Wr]]),Is={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Cs)},floor:z,ceil:z};zs.year=Ie.year,Ie.scale=function(){return Es(t.scale.linear(),zs,Ps)};var Ds=zs.map(function(t){return[t[0].utc,t[1]]}),Os=ks.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Wr]]);function Rs(t){return JSON.parse(t.responseText)}function Fs(t){var e=i.createRange();return e.selectNode(i.body),e.createContextualFragment(t.responseText)}Ds.year=Ie.year.utc,Ie.scale.utc=function(){return Es(t.scale.linear(),Ds,Os)},t.text=me(function(t){return t.responseText}),t.json=function(t,e){return ye(t,"application/json",Rs,e)},t.html=function(t,e){return ye(t,"text/html",Fs,e)},t.xml=me(function(t){return t.responseXML}),e.exports?e.exports=t:this.d3=t}(),e=e.exports;var r=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},n={},i=Math.PI;n.deg2rad=function(t){return t/180*i},n.rad2deg=function(t){return t/i*180},n.wrap360=function(t){var e=t%360;return e<0?e+360:e},n.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var a=t.BADNUM,o=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,s={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,i=t.round,a=t.min,o=t.max,l=t.random;function u(s,l){if(s=s||"",l=l||{},s instanceof u)return s;if(!(this instanceof u))return new u(s,l);var c=function(n){var i={r:0,g:0,b:0},s=1,l=null,u=null,c=null,h=!1,f=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,i=!1;if(S[t])t=S[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=j.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=j.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=j.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=j.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=j.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=j.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=j.hex8.exec(t))return{r:P(n[1]),g:P(n[2]),b:P(n[3]),a:R(n[4]),format:i?"name":"hex8"};if(n=j.hex6.exec(t))return{r:P(n[1]),g:P(n[2]),b:P(n[3]),format:i?"name":"hex"};if(n=j.hex4.exec(t))return{r:P(n[1]+""+n[1]),g:P(n[2]+""+n[2]),b:P(n[3]+""+n[3]),a:R(n[4]+""+n[4]),format:i?"name":"hex8"};if(n=j.hex3.exec(t))return{r:P(n[1]+""+n[1]),g:P(n[2]+""+n[2]),b:P(n[3]+""+n[3]),format:i?"name":"hex"};return!1}(n));"object"==typeof n&&(V(n.r)&&V(n.g)&&V(n.b)?(p=n.r,d=n.g,g=n.b,i={r:255*L(p,255),g:255*L(d,255),b:255*L(g,255)},h=!0,f="%"===String(n.r).substr(-1)?"prgb":"rgb"):V(n.h)&&V(n.s)&&V(n.v)?(l=D(n.s),u=D(n.v),i=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var i=t.floor(e),a=e-i,o=n*(1-r),s=n*(1-a*r),l=n*(1-(1-a)*r),u=i%6;return{r:255*[n,s,o,o,l,n][u],g:255*[l,n,n,s,o,o][u],b:255*[o,o,l,n,n,s][u]}}(n.h,l,u),h=!0,f="hsv"):V(n.h)&&V(n.s)&&V(n.l)&&(l=D(n.s),c=D(n.l),i=function(t,e,r){var n,i,a;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(n.h,l,c),h=!0,f="hsl"),n.hasOwnProperty("a")&&(s=n.a));var p,d,g;return s=C(s),{ok:h,format:n.format||f,r:a(255,o(i.r,0)),g:a(255,o(i.g,0)),b:a(255,o(i.b,0)),a:s}}(s);this._originalInput=s,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=i(100*this._a)/100,this._format=l.format||c.format,this._gradientType=l.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=c.ok,this._tc_id=n++}function c(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,i,s=o(t,e,r),l=a(t,e,r),u=(s+l)/2;if(s==l)n=i=0;else{var c=s-l;switch(i=u>.5?c/(2-s-l):c/(s+l),s){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(u(n));return a}function T(t,e){e=e||6;for(var r=u(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(u({h:n,s:i,v:a})),a=(a+s)%1;return o}u.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=C(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=h(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=h(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=c(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=c(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return f(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[I(i(t).toString(16)),I(i(e).toString(16)),I(i(r).toString(16)),I(O(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*L(this._r,255))+"%",g:i(100*L(this._g,255))+"%",b:i(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%)":"rgba("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(E[f(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+p(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=u(t);r="#"+p(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return u(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(d,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(k,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(A,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(M,arguments)}},u.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:D(t[n]));t=r}return u(t,e)},u.equals=function(t,e){return!(!t||!e)&&u(t).toRgbString()==u(e).toRgbString()},u.random=function(){return u.fromRatio({r:l(),g:l(),b:l()})},u.mix=function(t,e,r){r=0===r?0:r||50;var n=u(t).toRgb(),i=u(e).toRgb(),a=r/100;return u({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},u.readability=function(e,r){var n=u(e),i=u(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},u.isReadable=function(t,e,r){var n,i,a=u.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},u.mostReadable=function(t,e,r){var n,i,a,o,s=null,l=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var c=0;cl&&(l=n,s=u(e[c]));return u.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,u.mostReadable(t,["#fff","#000"],r))};var S=u.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"},E=u.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(S);function C(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=a(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function z(t){return a(1,o(0,t))}function P(t){return parseInt(t,16)}function I(t){return 1==t.length?"0"+t:""+t}function D(t){return t<=1&&(t=100*t+"%"),t}function O(e){return t.round(255*parseFloat(e)).toString(16)}function R(t){return P(t)/255}var F,B,N,j=(B="[\\s|\\(]+("+(F="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+F+")[,|\\s]+("+F+")\\s*\\)?",N="[\\s|\\(]+("+F+")[,|\\s]+("+F+")[,|\\s]+("+F+")[,|\\s]+("+F+")\\s*\\)?",{CSS_UNIT:new RegExp(F),rgb:new RegExp("rgb"+B),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+B),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+B),hsva:new RegExp("hsva"+N),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})$/});function V(t){return!!j.CSS_UNIT.exec(t)}s.exports?s.exports=u:window.tinycolor=u}(Math),s=s.exports;var l={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},u=l.RdBu,c=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],i=t[e][1],o=!1,G(n))for(r=n.length-1;r>=0;r--)Z(n[r],K(i,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)Z(n[a[r]],K(i,a[r]))?delete n[a[r]]:o=!0;if(o)return}}(l)):o[e[a]]=n}}function K(t,e){var n=e;return r(e)?n="["+e+"]":t&&(n="."+e),t+n}function Q(t,e,r,n){var i,a=G(r),o=!0,s=r,l=n.replace("-1",0),u=!a&&Z(r,l),c=e[0];for(i=0;ii.max?e.set(n):e.set(+t)}},integer:{coerceFunction:function(t,e,n,i){t%1||!r(t)||void 0!==i.min&&ti.max?e.set(n):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){s(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return s(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(h(t,r))}},angle:{coerceFunction:function(t,e,n){"auto"===t?e.set("auto"):r(t)?e.set(it(+t)):e.set(n)}},subplotid:{coerceFunction:function(t,e,r){"string"==typeof t&&rt(r).test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!rt(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a=ot&&t<=st?t:ct;if("string"!=typeof t&&"number"!=typeof t)return ct;t=String(t);var r=bt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var i=r&&"chinese"===e.substr(0,7),a=t.match(i?yt:mt);if(!a)return ct;var o=a[1],s=a[3]||"1",l=Number(a[5]||1),u=Number(a[7]||0),c=Number(a[9]||0),h=Number(a[11]||0);if(r){if(2===o.length)return ct;var f;o=Number(o);try{var p=P.getComponentMethod("calendars","getCal")(e);if(i){var d="i"===s.charAt(s.length-1);s=parseInt(s,10),f=p.newDate(o,p.toMonthIndex(o,s,d),l)}else f=p.newDate(o,Number(s),l)}catch(t){return ct}return f?(f.toJD()-gt)*ht+u*ft+c*pt+h*dt:ct}o=2===o.length?(Number(o)+2e3-xt)%100+xt:Number(o),s-=1;var g=new Date(Date.UTC(2e3,s,l,u,c));return g.setUTCFullYear(o),g.getUTCMonth()!==s?ct:g.getUTCDate()!==l?ct:g.getTime()+h*dt},ot=ut.MIN_MS=ut.dateTime2ms("-9999"),st=ut.MAX_MS=ut.dateTime2ms("9999-12-31 23:59:59.9999"),ut.isDateTime=function(t,e){return ut.dateTime2ms(t,e)!==ct};var wt=90*ht,Mt=3*ft,At=5*pt;function kt(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+_t(e,2)+":"+_t(r,2),(n||i)&&(t+=":"+_t(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+_t(i,a)}return t}ut.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ot&&t<=st))return ct;e||(e=0);var n,i,a,o,s,l,u=Math.floor(10*lt(t+.05,1)),c=Math.round(t-u/10);if(bt(r)){var h=Math.floor(c/ht)+gt,f=Math.floor(lt(t,ht));try{n=P.getComponentMethod("calendars","getCal")(r).fromJD(h).formatDate("yyyy-mm-dd")}catch(t){n=vt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;i=e=ot+ht&&t<=st-ht))return ct;var r=Math.floor(10*lt(t+.05,1)),n=new Date(Math.round(t-r/10));return kt(e.time.format("%Y-%m-%d")(n),n.getHours(),n.getMinutes(),n.getSeconds(),10*n.getUTCMilliseconds()+r)},ut.cleanDate=function(t,e,r){if(ut.isJSDate(t)||"number"==typeof t){if(bt(r))return _.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ut.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ut.isDateTime(t,r))return _.error("unrecognized date",t),e;return t};var Tt=/%\d?f/g;function St(t,e,r,n){t=t.replace(Tt,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(bt(n))try{t=P.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var Et=[59,59.9,59.99,59.999,59.9999];ut.formatDate=function(t,e,n,i,a,o){if(a=bt(a)&&a,!e)if("y"===n)e=o.year;else if("m"===n)e=o.month;else{if("d"!==n)return function(t,e){var n=lt(t+.05,ht),i=_t(Math.floor(n/ft),2)+":"+_t(lt(Math.floor(n/pt),60),2);if("M"!==e){r(e)||(e=0);var a=(100+Math.min(lt(t/dt,60),Et[e])).toFixed(e).substr(1);e>0&&(a=a.replace(/0+$/,"").replace(/[\.]$/,"")),i+=":"+a}return i}(t,n)+"\n"+St(o.dayMonthYear,t,i,a);e=o.dayMonth+"\n"+o.year}return St(e,t,i,a)};var Ct=3*ht;ut.incrementMonth=function(t,e,r){r=bt(r)&&r;var n=lt(t,ht);if(t=Math.round(t-n),r)try{var i=Math.round(t/ht)+gt,a=P.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-gt)*ht+n}catch(e){_.error("invalid ms "+t+" in calendar "+r)}var s=new Date(t+Ct);return s.setUTCMonth(s.getUTCMonth()+e)+n-Ct},ut.findExactDates=function(t,e){for(var n,i,a=0,o=0,s=0,l=0,u=bt(e)&&P.getComponentMethod("calendars","getCal")(e),c=0;c1||g<0||g>1?null:{x:t+l*g,y:e+h*g}}function Ft(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}Ot.segmentsIntersect=Rt,Ot.segmentDistance=function(t,e,r,n,i,a,o,s){if(Rt(t,e,r,n,i,a,o,s))return 0;var l=r-t,u=n-e,c=o-i,h=s-a,f=l*l+u*u,p=c*c+h*h,d=Math.min(Ft(l,u,f,i-t,a-e),Ft(l,u,f,o-t,s-e),Ft(c,h,p,t-i,e-a),Ft(c,h,p,r-i,n-a));return Math.sqrt(d)},Ot.getTextLocation=function(t,e,r,n){if(t===It&&n===Dt||(Pt={},It=t,Dt=n),Pt[r])return Pt[r];var i=t.getPointAtLength(lt(r-n/2,e)),a=t.getPointAtLength(lt(r+n/2,e)),o=Math.atan((a.y-i.y)/(a.x-i.x)),s=t.getPointAtLength(lt(r,e)),l={x:(4*s.x+i.x+a.x)/6,y:(4*s.y+i.y+a.y)/6,theta:o};return Pt[r]=l,l},Ot.clearLocationCache=function(){It=null},Ot.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,u=0,c=t.getTotalLength(),h=c;function f(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(i=r);var u=r.xo?r.x-o:0,h=r.yl?r.y-l:0;return Math.sqrt(u*u+h*h)}for(var p=f(u);p;){if((u+=p+r)>h)return;p=f(u)}for(p=f(h);p;){if(u>(h-=p+r))return;p=f(h)}return{min:u,max:h,len:h-u,total:c,isClosed:0===u&&h===c&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},Ot.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,h=0,f=0,p=s;h0?p=i:f=i,h++}return a};var Bt=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},Nt=function(t){return t},jt=/^\w*$/,Vt={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function Jt(t,e){return t>=e}Wt.findBin=function(t,e,n){if(r(e.start))return n?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var i,a,o=0,s=e.length,l=0,u=s>1?(e[s-1]-e[0])/(s-1):1;for(a=u>=0?n?Yt:Xt:n?Jt:Zt,t+=1e-9*u*(n?-1:1)*(u>=0?1:-1);o90&&_.log("Long binary search..."),o-1},Wt.sorterAsc=function(t,e){return t-e},Wt.sorterDes=function(t,e){return e-t},Wt.distinctVals=function(t){var e=t.slice();e.sort(Wt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,i=n/(r||1)/1e4,a=[e[0]],o=0;oe[o]+i&&(n=Math.min(n,e[o+1]-e[o]),a.push(e[o+1]));return{vals:a,minDiff:n}},Wt.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;in.length)&&(i=n.length),r(e)||(e=!1),Qt(n[0])){for(o=new Array(i),a=0;at.length-1)return t[t.length-1];var n=e%1;return n*t[Math.ceil(e)]+(1-n)*t[Math.floor(e)]};var $t={},te={};function ee(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}$t.throttle=function(t,e,r){var n=te[t],i=Date.now();if(!n){for(var a in te)te[a].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},$t.done=function(t){var e=te[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},$t.clear=function(t){if(t)ee(te[t]),delete te[t];else for(var e in te)$t.clear(e)};var re=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var n=Math.log(Math.min(e[0],e[1]))/Math.LN10;return r(n)||(n=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),n},ne={},ie=t.FP_SAFE,ae=t.BADNUM,oe=ne={};oe.nestedProperty=W,oe.keyedContainer=function(t,e,r,n){var i,a;r=r||"name",n=n||"value";var o={};a=e&&e.length?W(t,e).get():t,e=e||"",a=a||[];var s={};for(i=0;i2)return o[e]=2|o[e],u.set(t,null);if(l){for(i=e;i/g),s=0;sie?ae:r(t)?Number(t):ae:ae},oe.noop=A,oe.identity=Nt,oe.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},oe.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},oe.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):s},oe.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},oe.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},oe.syncOrAsync=function(t,e,r){var n;function i(){return oe.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,oe.promiseError);return r&&r(e)},oe.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},oe.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n=0&&a%1==0){var d=i?i[p]:p,g=n?n[d]:d;h(g)&&(t[g].selected=1)}}},oe.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=oe.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},oe.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l};var ue=/%{([^\s%{}]*)}/g,ce=/^\w*$/;oe.templateString=function(t,e){var r={};return t.replace(ue,function(t,n){return ce.test(n)?e[n]||"":(r[n]=r[n]||oe.nestedProperty(e,n).get,r[n]()||"")})};oe.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a=48&&o<=57,u=s>=48&&s<=57;if(l&&(n=10*n+o-48),u&&(i=10*i+s-48),!l||!u){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n};var he=2e9;oe.seedPseudoRandom=function(){he=2e9},oe.pseudoRandom=function(){var t=he;return he=(69069*he+1)%4294967296,Math.abs(he-t)<429496729?oe.pseudoRandom():he/4294967296};var fe=ne.extendFlat,pe=ne.isPlainObject,de={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},ge={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","margins","layoutstyle","modebar","camera","arraydraw"]},ve=de.flags.slice().concat(["clearCalc","fullReplot"]),me=ge.flags.slice().concat("layoutReplot"),ye={traces:de,layout:ge,traceFlags:function(){return xe(ve)},layoutFlags:function(){return xe(me)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i=0))return t;if(3===o)i[o]>1&&(i[o]=1);else if(i[o]>=1)return t}var s=Math.round(255*i[0])+", "+Math.round(255*i[1])+", "+Math.round(255*i[2]);return a?"rgba("+s+", "+i[3]+")":"rgb("+s+")"}Re.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},Re.rgb=function(t){return Re.tinyRGB(s(t))},Re.opacity=function(t){return t?s(t).getAlpha():0},Re.addOpacity=function(t,e){var r=s(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},Re.combine=function(t,e){var r=s(t).toRgb();if(1===r.a)return s(t).toRgbString();var n=s(e||Be).toRgb(),i=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},a={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return s(a).toRgbString()},Re.contrast=function(t,e,r){var n=s(t);return 1!==n.getAlpha()&&(n=s(Re.combine(t,Be))),(n.isDark()?e?n.lighten(e):Be:r?n.darken(r):Fe).toString()},Re.stroke=function(t,e){var r=s(e);t.style({stroke:Re.tinyRGB(r),"stroke-opacity":r.getAlpha()})},Re.fill=function(t,e){var r=s(e);t.style({fill:Re.tinyRGB(r),"fill-opacity":r.getAlpha()})},Re.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,a=Object.keys(t);for(e=0;e=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n},Ve=function(t,e,r,n){var i,a;r?(i=ne.nestedProperty(t,r).get(),a=ne.nestedProperty(t._input,r).get()):(i=t,a=t._input);var o=n+"auto",s=n+"min",u=n+"max",c=i[o],h=i[s],f=i[u],p=i.colorscale;!1===c&&void 0!==h||(h=ne.aggNums(Math.min,null,e)),!1===c&&void 0!==f||(f=ne.aggNums(Math.max,null,e)),h===f&&(h-=.5,f+=.5),i[s]=h,i[u]=f,a[s]=h,a[u]=f,a[o]=!1!==c||void 0===h&&void 0===f,i.autocolorscale&&(p=h*f<0?l.RdBu:h>=0?l.Reds:l.Blues,a.colorscale=p,i.reversescale&&(p=je(p)),i.colorscale=p)},Ue=function(t,e,r,n,i){var a=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",a),r("ticksuffix",i.tickSuffixDflt)&&r("showticksuffix",a),r("showticklabels")){var o=i.font||{},s=e.color===t.color?e.color:o.color;if(ne.coerceFont(r,"tickfont",{family:o.family,size:o.size,color:s}),r("tickangle"),"category"!==n){var l=r("tickformat");!function(t,e){var r,n,i=t.tickformatstops,a=e.tickformatstops=[];if(!Array.isArray(i))return;function o(t,e){return ne.coerce(r,n,Ce.tickformatstops,t,e)}for(var s=0;s0?Number(l):s;else if("string"!=typeof l)e.dtick=s;else{var u=l.charAt(0),c=l.substr(1);((c=r(c)?Number(c):0)<=0||!("date"===i&&"M"===u&&c===Math.round(c)||"log"===i&&"L"===u||"log"===i&&"D"===u&&(1===c||2===c)))&&(e.dtick=s)}var h="date"===i?ne.dateTick0(e.calendar):0,f=n("tick0",h);"date"===i?e.tick0=ne.cleanDate(f,h):r(f)&&"D1"!==l&&"D2"!==l?e.tick0=Number(f):e.tick0=h}else{void 0===n("tickvals")?e.tickmode="auto":n("ticktext")}},We=function(t){return void 0!==l[t]||c(t)},Ye=function(t,e,n,i,a){var o,s=a.prefix,l=a.cLetter,u=s.slice(0,s.length-1),c=s?ne.nestedProperty(t,u).get()||{}:t,h=s?ne.nestedProperty(e,u).get()||{}:e,f=c[l+"min"],p=c[l+"max"],d=c.colorscale;i(s+l+"auto",!(r(f)&&r(p)&&f","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},er={},rr=Qe.LINE_SPACING;function nr(t,e){return t.node().getBoundingClientRect()[e]}var ir=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;er.convertToTspans=function(t,r,n){var i=t.text(),a=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&i.match(ir),o=e.select(t.node().parentNode);if(!o.empty()){var s=t.attr("class")?t.attr("class").split(" ")[0]:"text";return s+="-math",o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove(),t.style("display",null).attr({"data-unformatted":i,"data-math":"N"}),a?(r&&r._promises||[]).push(new Promise(function(r){t.style("display","none");var u=parseInt(t.node().style.fontSize,10),c={fontSize:u};!function(t,r,n){var i="math-output-"+ne.randstr([],64),a=e.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":r.fontSize+"px"}).text((o=t,o.replace(ar,"\\lt ").replace(or,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var r=e.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())ne.log("There was an error in the tex syntax.",t),n();else{var i=a.select("svg").node().getBoundingClientRect();n(a.select(".MathJax_SVG"),r,i)}a.remove()})}(a[2],c,function(e,a,c){o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove();var h=e&&e.select("svg");if(!h||!h.node())return l(),void r();var f=o.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":i,"data-math":"Y"});f.node().appendChild(h.node()),a&&a.node()&&h.node().insertBefore(a.node().cloneNode(!0),h.node().firstChild),h.attr({class:s,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var p=t.node().style.fill||"black";h.select("g").attr({fill:p,stroke:p});var d=nr(h,"width"),g=nr(h,"height"),v=+t.attr("x")-d*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],m=-(u||nr(t,"height"))/4;"y"===s[0]?(f.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-d/2,m-g/2]+")"}),h.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===s[0]?h.attr({x:t.attr("x"),y:m-g/2}):"a"===s[0]?h.attr({x:0,y:m}):h.attr({x:v,y:+t.attr("y")+m-g/2}),n&&n.call(t,f),r(f)})})):l(),t}function l(){o.empty()||(s=t.attr("class")+"-math",o.select("svg."+s).remove()),t.text("").style("white-space","pre"),function(t,r){r=(n=r,function(t,e){if(!t)return"";for(var r=0;r1)for(var a=1;a doesnt match end tag <"+t+">. Pretending it did match.",r),i=o[o.length-1].node}else ne.log("Ignoring unexpected end tag .",r)}mr.test(r)?l():(i=t,o=[{node:t}]);for(var f=r.split(gr),p=0;p|>|>)/g;var sr={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"},lr={sub:"0.3em",sup:"-0.6em"},ur={sub:"-0.21em",sup:"0.42em"},cr="\u200b",hr=["http:","https:","mailto:","",void 0,":"],fr=new RegExp("]*)?/?>","g"),pr=Object.keys(tr.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:tr.entityToUnicode[t]}}),dr=/(\r\n?|\n)/g,gr=/(<[^<>]*>)/,vr=/<(\/?)([^ >]*)(\s+(.*))?>/i,mr=//i,yr=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,xr=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,br=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,_r=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function wr(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var Mr=/(^|;)\s*color:/;function Ar(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}er.plainText=function(t){return(t||"").replace(fr," ")},er.lineCount=function(t){return t.selectAll("tspan.line").size()||1},er.positionText=function(t,r,n){return t.each(function(){var t=e.select(this);function i(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var a=i("x",r),o=i("y",n);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:a,y:o})})},er.makeEditable=function(t,r){var n=r.gd,i=r.delegate,a=e.dispatch("edit","input","cancel"),o=i||t;if(t.style({"pointer-events":i?"none":"all"}),1!==t.size())throw new Error("boo");function s(){var i,s,u,c;i=e.select(n).select(".svg-container"),s=i.append("div"),u=t.node().style,c=parseFloat(u.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:r.fill||u.fill||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||t.attr("data-unformatted")).call(Ar(t,i,r)).on("blur",function(){n._editing=!1,t.text(this.textContent).style({opacity:1});var r,i=e.select(this).attr("class");(r=i?"."+i.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(r).style({opacity:0});var o=this.textContent;e.select(this).transition().duration(0).remove(),e.select(document).on("mouseup",null),a.edit.call(t,o)}).on("focus",function(){var t=this;n._editing=!0,e.select(document).on("mouseup",function(){if(e.event.target===t)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===e.event.which?(n._editing=!1,t.style({opacity:1}),e.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(t,this.textContent)):(a.input.call(t,this.textContent),e.select(this).call(Ar(t,i,r)))}).on("keydown",function(){13===e.event.which&&this.blur()}).call(l),t.style({opacity:0});var h,f=o.attr("class");(h=f?"."+f.split(" ")[0]+"-math-group":"[class*=-math-group]")&&e.select(t.node().parentNode).select(h).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return r.immediate?s():o.on("click",s),e.rebind(t,a,"on")};var kr=function(t){var e=t.marker,n=e.sizeref||1,i=e.sizemin||0,a="area"===e.sizemode?function(t){return Math.sqrt(t/n)}:function(t){return t/n};return function(t){var e=a(t/2);return r(e)&&e>0?Math.max(e,i):0}},Tr={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("markers")},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return ne.isPlainObject(t.marker)&&ne.isArrayOrTypedArray(t.marker.size)}},Sr={},Er=Qe.LINE_SPACING,Cr=f.DESELECTDIM,Lr=Sr={};Lr.font=function(t,e,r,n){ne.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Oe.fill,n)},Lr.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},Lr.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},Lr.setRect=function(t,e,r,n,i){t.call(Lr.setPosition,e,r).call(Lr.setSize,n,i)},Lr.translatePoint=function(t,e,n,i){var a=n.c2p(t.x),o=i.c2p(t.y);return!!(r(a)&&r(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",a).attr("y",o):e.attr("transform","translate("+a+","+o+")"),!0)},Lr.translatePoints=function(t,r,n){t.each(function(t){var i=e.select(this);Lr.translatePoint(t,i,r,n)})},Lr.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},Lr.hideOutsideRangePoints=function(t,r,n){if(r._hasClipOnAxisFalse){n=n||".point,.textpoint";var i=r.xaxis,a=r.yaxis;t.each(function(r){var o=r[0].trace,s=o.xcalendar,l=o.ycalendar;t.selectAll(n).each(function(t){Lr.hideOutsideRangePoint(t,e.select(this),i,a,s,l)})})}},Lr.crispRound=function(t,e,n){return e&&r(e)?t._context.staticPlot?e:e<1?1:Math.round(e):n||0},Lr.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";Oe.stroke(e,n||a.color),Lr.dashLine(e,s,o)},Lr.lineGroupStyle=function(t,r,n,i){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";e.select(this).call(Oe.stroke,n||a.color).call(Lr.dashLine,s,o)})},Lr.dashLine=function(t,e,r){r=+r||0,e=Lr.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},Lr.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},Lr.singleFillStyle=function(t){var r=(((e.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;r&&t.call(Oe.fill,r)},Lr.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(r){var n=e.select(this);try{n.call(Oe.fill,r[0].trace.fillcolor)}catch(e){ne.error(e,t),n.remove()}})},Lr.symbolNames=[],Lr.symbolFuncs=[],Lr.symbolNeedLines={},Lr.symbolNoDot={},Lr.symbolNoFill={},Lr.symbolList=[],Object.keys(Ke).forEach(function(t){var e=Ke[t];Lr.symbolList=Lr.symbolList.concat([e.n,t,e.n+100,t+"-open"]),Lr.symbolNames[e.n]=t,Lr.symbolFuncs[e.n]=e.f,e.needLine&&(Lr.symbolNeedLines[e.n]=!0),e.noDot?Lr.symbolNoDot[e.n]=!0:Lr.symbolList=Lr.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(Lr.symbolNoFill[e.n]=!0)});var zr=Lr.symbolNames.length,Pr="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Ir(t,e){var r=t%100;return Lr.symbolFuncs[r](e)+(t>=200?Pr:"")}Lr.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=Lr.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=zr||t>=400?0:Math.floor(Math.max(t,0))};var Dr={x1:1,x2:0,y1:0,y2:0},Or={x1:0,x2:0,y1:1,y2:0};Lr.gradient=function(t,r,n,i,a,o){var l=r._fullLayout._defs.select(".gradients").selectAll("#"+n).data([i+a+o],ne.identity);l.exit().remove(),l.enter().append("radial"===i?"radialGradient":"linearGradient").each(function(){var t=e.select(this);"horizontal"===i?t.attr(Dr):"vertical"===i&&t.attr(Or),t.attr("id",n);var r=s(a),l=s(o);t.append("stop").attr({offset:"0%","stop-color":Oe.tinyRGB(l),"stop-opacity":l.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":Oe.tinyRGB(r),"stop-opacity":r.getAlpha()})}),t.style({fill:"url(#"+n+")","fill-opacity":null})},Lr.initGradients=function(t){var e=t._fullLayout._defs.selectAll(".gradients").data([0]);e.enter().append("g").classed("gradients",!0),e.selectAll("linearGradient,radialGradient").remove()},Lr.singlePointStyle=function(t,e,r,n,i,a){var o=r.marker;!function(t,e,r,n,i,a,o,s){if(P.traceIs(r,"symbols")){var l=kr(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===a.size?3:Tr.isBubble(r)?l(t.ms):(a.size||6)/2,t.mrc=e;var n=Lr.symbolNumber(t.mx||a.symbol)||0;return t.om=n%200>=100,Ir(n,e)})}e.style("opacity",function(t){return(t.mo+1||a.opacity+1)-1});var u,c,h,f=!1;if(t.so?(h=o.outlierwidth,c=o.outliercolor,u=a.outliercolor):(h=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=i(t.mlc):ne.isArrayOrTypedArray(o.color)?Oe.defaultLine:o.color,ne.isArrayOrTypedArray(a.color)&&(u=Oe.defaultLine,f=!0),u="mc"in t?t.mcc=n(t.mc):a.color||"rgba(0,0,0,0)"),t.om)e.call(Oe.stroke,u).style({"stroke-width":(h||1)+"px",fill:"none"});else{e.style("stroke-width",h+"px");var p=a.gradient,d=t.mgt;if(d?f=!0:d=p&&p.type,d&&"none"!==d){var g=t.mgc;g?f=!0:g=p.color;var v="g"+s._fullLayout._uid+"-"+r.uid;f&&(v+="-"+t.i),e.call(Lr.gradient,s,v,d,u,g)}else e.call(Oe.fill,u);h&&e.call(Oe.stroke,c)}}(t,e,r,n,i,o,o.line,a)},Lr.pointStyle=function(t,r,n){if(t.size()){var i=r.marker,a=Lr.tryColorscale(i,""),o=Lr.tryColorscale(i,"line");t.each(function(t){Lr.singlePointStyle(t,e.select(this),r,a,o,n)})}},Lr.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},a=r.marker||{},o=n.marker||{},s=i.opacity,l=a.opacity,u=o.opacity,c=void 0!==l,h=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||h){if(!t.selected)return h?u:Cr*(r?e:s);if(c)return l}};var f=a.color,p=o.color;(f||p)&&(e.colorFn=function(t){if(t.selected){if(f)return f}else if(p)return p});var d=a.size,g=o.size,v=void 0!==d,m=void 0!==g;return(v||m)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?v?d/2:e:m?g/2:e}),e},Lr.selectedPointStyle=function(t,r){if(t.size()&&r.selectedpoints){var n=Lr.makeSelectedPointStyleFns(r),i=r.marker||{};t.each(function(t){var r=e.select(this),i=n.opacityFn(t);void 0!==i&&r.style("opacity",i)}),n.colorFn&&t.each(function(t){var r=e.select(this),i=n.colorFn(t);i&&Oe.fill(r,i)}),P.traceIs(r,"symbols")&&n.sizeFn&&t.each(function(t){var r=e.select(this),a=t.mx||i.symbol||0,o=n.sizeFn(t);r.attr("d",Ir(Lr.symbolNumber(a),o)),t.mrc2=o})}},Lr.tryColorscale=function(t,e){var r=e?ne.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&ne.isArrayOrTypedArray(i)?Je.makeColorScaleFunc(Je.extractScale(n,r.cmin,r.cmax)):ne.identity};var Rr={start:1,end:-1,middle:0,bottom:1,top:-1};function Fr(t,r,n,i){var a=e.select(t.node().parentNode),o=-1!==r.indexOf("top")?"top":-1!==r.indexOf("bottom")?"bottom":"middle",s=-1!==r.indexOf("left")?"end":-1!==r.indexOf("right")?"start":"middle",l=i?i/.8+1:0,u=(er.lineCount(t)-1)*Er+1,c=Rr[s]*l,h=.75*n+Rr[o]*l+(Rr[o]-1)*u*n/2;t.attr("text-anchor",s),a.attr("transform","translate("+c+","+h+")")}function Br(t,e){var n=t.ts||e.textfont.size;return r(n)&&n>0?n:0}Lr.textPointStyle=function(t,r,n){t.each(function(t){var i=e.select(this),a=ne.extractOption(t,r,"tx","text");if(a){var o=t.tp||r.textposition,s=Br(t,r);i.call(Lr.font,t.tf||r.textfont.family,s,t.tc||r.textfont.color).text(a).call(er.convertToTspans,n).call(Fr,o,s,t.mrc)}else i.remove()})},Lr.selectedTextStyle=function(t,r){if(t.size()&&r.selectedpoints){var n=r.selected||{},i=r.unselected||{};t.each(function(t){var a,o=e.select(this),s=t.tc||r.textfont.color,l=t.tp||r.textposition,u=Br(t,r),c=(n.textfont||{}).color,h=(i.textfont||{}).color;t.selected?c&&(a=c):h?a=h:c||(a=Oe.addOpacity(s,Cr)),a&&Oe.fill(o,a),Fr(o,l,u,t.mrc2||t.mrc)})}};var Nr=.5;function jr(t,r,n,i){var a=t[0]-r[0],o=t[1]-r[1],s=n[0]-r[0],l=n[1]-r[1],u=Math.pow(a*a+o*o,Nr/2),c=Math.pow(s*s+l*l,Nr/2),h=(c*c*a-u*u*s)*i,f=(c*c*o-u*u*l)*i,p=3*c*(u+c),d=3*u*(u+c);return[[e.round(r[0]+(p&&h/p),2),e.round(r[1]+(p&&f/p),2)],[e.round(r[0]-(d&&h/d),2),e.round(r[1]-(d&&f/d),2)]]}Lr.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(Lr.savedBBoxes={},qr=0),n&&(Lr.savedBBoxes[n]=d),qr++,ne.extendFlat({},d)},Lr.setClipUrl=function(t,r){if(r){var n="#"+r,i=e.select("base");i.size()&&i.attr("href")&&(n=window.location.href.split("#")[0]+n),t.attr("clip-path","url("+n+")")}else t.attr("clip-path",null)},Lr.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},Lr.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},Lr.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},Lr.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a},Lr.setPointGroupScale=function(t,e,r){var n,i,a;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",a=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(a,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var Gr=/translate\([^)]*\)\s*$/;Lr.setTextPointsScale=function(t,r,n){t.each(function(){var t,i=e.select(this),a=i.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(i.attr("transform")||"").match(Gr);t=1===r&&1===n?[]:["translate("+o+","+s+")","scale("+r+","+n+")","translate("+-o+","+-s+")"],l&&t.push(l),i.attr("transform",t.join(" "))}})};var Wr={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20},Yr=Ae.dash,Xr=m.extendFlat,Zr={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:Xr({},Yr,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:Xr({symbol:{valType:"enumerated",values:Sr.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},showscale:{valType:"boolean",dflt:!1,editType:"calc"},colorbar:ze,line:Xr({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},De()),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},De()),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:T({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}},Jr=Zr.marker,Kr={r:Zr.r,t:Zr.t,marker:{color:Jr.color,size:Jr.size,symbol:Jr.symbol,opacity:Jr.opacity,editType:"calc"}},Qr=m.extendFlat,$r=ye.overrideAll,tn=Qr({},Ce.domain,{});function en(t,e){return Qr({},e,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}var rn=$r({radialaxis:en(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:tn,orientation:{valType:"number"}}),angularaxis:en(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:tn}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested"),nn={},an=ne.extendFlat,on=ne.extendDeepAll,sn="_isSubplotObj",ln="_isLinkedToArray",un=[sn,ln,"_arrayAttrRegexps","_deprecated"];function cn(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(hn(e[r]))r++;else if(r=a.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!hn(o))return!1;t=a[i][o]}else t=a[i]}else t=a}}return t}function hn(t){return t===Math.round(t)&&t>=0}function fn(t){return function(t){nn.crawl(t,function(t,e,r){nn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):ne.isPlainObject(t)&&(t.role="object")})}(t),function(t){nn.crawl(t,function(t,e,r){if(!t)return;var n=t[ln];if(!n)return;delete t[ln],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),t}function pn(t,e,r){var n=ne.nestedProperty(t,r),i=on({},e.layoutAttributes);i[sn]=!0,n.set(i)}function dn(t,e,r){var n=ne.nestedProperty(t,r);n.set(on(n.get()||{},e))}nn.IS_SUBPLOT_OBJ=sn,nn.IS_LINKED_TO_ARRAY=ln,nn.DEPRECATED="_deprecated",nn.UNDERSCORE_ATTRS=un,nn.get=function(){var t={};P.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:Kr},r={}):(e=P.modules[t]._module,r=e.basePlotModule);var n={type:null};on(n,E),on(n,e.attributes),r.attributes&&on(n,r.attributes);n.type=t;var i={meta:e.meta||{},attributes:fn(n)};if(e.layoutAttributes){var a={};on(a,e.layoutAttributes),i.layoutAttributes=fn(a)}return i}(e)});var e,r={};return Object.keys(P.transformsRegistry).forEach(function(t){r[t]=function(t){var e=P.transformsRegistry[t],r=on({},e.attributes);return Object.keys(P.componentsRegistry).forEach(function(e){var n=P.componentsRegistry[e];n.schema&&n.schema.transforms&&n.schema.transforms[t]&&Object.keys(n.schema.transforms[t]).forEach(function(e){dn(r,n.schema.transforms[t][e],e)})}),{attributes:fn(r)}}(t)}),{defs:{valObjects:ne.valObjectMeta,metaKeys:un.concat(["description","role","editType","impliedEdits"]),editType:{traces:ye.traces,layout:ye.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in on(r,z),P.subplotsRegistry)if((e=P.subplotsRegistry[t]).layoutAttributes)if("cartesian"===e.name)pn(r,e,"xaxis"),pn(r,e,"yaxis");else{var n="subplot"===e.attr?e.name:e.attr;pn(r,e,n)}for(t in r=function(t){return an(t,{radialaxis:rn.radialaxis,angularaxis:rn.angularaxis}),an(t,rn.layout),t}(r),P.componentsRegistry){var i=(e=P.componentsRegistry[t]).schema;if(i&&(i.subplots||i.layout)){var a=i.subplots;if(a&&a.xaxis&&!a.yaxis)for(var o in a.xaxis)delete r.yaxis[o]}else e.layoutAttributes&&dn(r,e.layoutAttributes,e.name)}return{layoutAttributes:fn(r)}}(),transforms:r,frames:(e={frames:ne.extendDeepAll({},Me)},fn(e),e.frames),animation:fn(we)}},nn.crawl=function(t,e,r,n){var i=r||0;n=n||"",Object.keys(t).forEach(function(r){var a=t[r];if(-1===un.indexOf(r)){var o=(n?n+".":"")+r;e(a,r,t,i,o),nn.isValObject(a)||ne.isPlainObject(a)&&"impliedEdits"!==r&&nn.crawl(a,e,i+1,o)}})},nn.isValObject=function(t){return t&&void 0!==t.valType},nn.findArrayAttributes=function(t){var e=[],r=[];function n(n,i,a,o){if(r=r.slice(0,o).concat([i]),n&&("data_array"===n.valType||!0===n.arrayOk)&&!("colorbar"===r[o-1]&&("ticktext"===i||"tickvals"===i))){var s=function(t){return t.join(".")}(r),l=ne.nestedProperty(t,s).get();ne.isArrayOrTypedArray(l)&&e.push(s)}}if(nn.crawl(E,n),t._module&&t._module.attributes&&nn.crawl(t._module.attributes,n),t.transforms)for(var i=t.transforms,a=0;a=t.transforms.length)return!1;n=(r=(P.transformsRegistry[t.transforms[o].type]||{}).attributes)&&r[e[2]],a=3}else if("area"===t.type)n=Kr[i];else{var s=t._module;if(s||(s=(P.modules[t.type||E.type.dflt]||{})._module),!s)return!1;if(!(n=(r=s.attributes)&&r[i])){var l=s.basePlotModule;l&&l.attributes&&(n=l.attributes[i])}n||(n=E[i])}return cn(n,e,a)},nn.getLayoutValObject=function(t,e){return cn(function(t,e){var r,n,i,a,o=t._basePlotModules;if(o){var s;for(r=0;rn?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},vn={};function mn(t,e,r){var n,i,a,o=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=ne.nestedProperty(n,e.prop).get(),(a=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&a[e.prop]!==i&&(o=!0),a[e.prop]=i,{changed:o,value:i}}function yn(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!ne.isPlainObject(n))return r;i=n}return bn(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function xn(t,e){var r,n,i,a,o=[];if(n=e[0],i=e[1],r=e[2],a={},"string"==typeof n)a[n]=i;else{if(!ne.isPlainObject(n))return o;a=n,void 0===r&&(r=i)}return void 0===r&&(r=null),bn(a,function(e,n,i){var a;if(Array.isArray(i)){var s=Math.min(i.length,t.data.length);r&&(s=Math.min(s,r.length)),a=[];for(var l=0;l0?".":"")+i;ne.isPlainObject(a)?bn(a,e,o,n+1):e(o,i,a)}})}vn.manageCommandObserver=function(t,e,r,n){var i={},a=!0;e&&e._commandObserver&&(i=e._commandObserver),i.cache||(i.cache={}),i.lookupTable={};var o=vn.hasSimpleAPICommandBindings(t,r,i.lookupTable);if(e&&e._commandObserver){if(o)return i;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,i}if(o){mn(t,o,i.cache),i.check=function(){if(a){var e=mn(t,o,i.cache);return e.changed&&n&&void 0!==i.lookupTable[e.value]&&(i.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:i.lookupTable[e.value]})).then(i.enable,i.enable)),e.changed}};for(var s=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],l=0;l=r.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=r._paper.attr("width")-7),n.attr(a);var o=n.select(".js-link-to-tool"),s=n.select(".js-link-spacer"),l=n.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){An.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(t,o),s.text(o.text()&&l.text()?" - ":"")}},An.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var r=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",n=e.select(t).append("div").attr("id","hiddenform").style("display","none"),i=n.append("form").attr({action:r+"/external",method:"post",target:"_blank"});return i.append("input").attr({type:"text",name:"data"}).node().value=An.graphJson(t,!1,"keepdata"),i.node().submit(),n.remove(),t.emit("plotly_afterexport"),!1};var Sn,En=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Cn=["year","month","dayMonth","dayMonthYear"];function Ln(t,e){var r,n,i=t.trace,a=i._arrayAttrs,o={};for(r=0;r=0)return!0}return!1},An.cleanPlot=function(t,e,r,n){var i,a,o=n._basePlotModules||[];for(i=0;i0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,h=u.bottom+u.top,f=1-2*s,p=n._container&&n._container.node?n._container.node().getBoundingClientRect():{width:n.width,height:n.height};i=Math.round(f*(p.width-c)),a=Math.round(f*(p.height-h))}else{var d=l?window.getComputedStyle(t):{};i=parseFloat(d.width)||n.width,a=parseFloat(d.height)||n.height}var g=An.layoutAttributes.width.min,v=An.layoutAttributes.height.min;i1,y=!e.height&&Math.abs(n.height-a)>1;(y||m)&&(m&&(n.width=i),y&&(n.height=a)),t._initialAutoSize||(t._initialAutoSize={width:i,height:a}),An.sanitizeMargins(n)},An.supplyLayoutModuleDefaults=function(t,e,r,n){var i,a,o,s=P.componentsRegistry,l=e._basePlotModules,u=P.subplotsRegistry.cartesian;for(i in s)(o=s[i]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in l.length||l.push(u),e._has("cartesian")&&(P.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(ne.subplotSort);for(a=0;a.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||An.doAutoMargin(t)}},An.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var n=e._size,i=JSON.stringify(n),a=Math.max(e.margin.l||0,0),o=Math.max(e.margin.r||0,0),s=Math.max(e.margin.t||0,0),l=Math.max(e.margin.b||0,0),u=e._pushmargin;if(!1!==e.margin.autoexpand)for(var c in u.base={l:{val:0,size:a},r:{val:1,size:o},t:{val:1,size:s},b:{val:0,size:l}},u){var h=u[c].l||{},f=u[c].b||{},p=h.val,d=h.size,g=f.val,v=f.size;for(var m in u){if(r(d)&&u[m].r){var y=u[m].r.val,x=u[m].r.size;if(y>p){var b=(d*y+(x-e.width)*p)/(y-p),_=(x*(1-p)+(d-e.width)*(1-y))/(y-p);b>=0&&_>=0&&b+_>a+o&&(a=b,o=_)}}if(r(v)&&u[m].t){var w=u[m].t.val,M=u[m].t.size;if(w>g){var A=(v*w+(M-e.height)*g)/(w-g),k=(M*(1-g)+(v-e.height)*(1-w))/(w-g);A>=0&&k>=0&&A+k>l+s&&(l=A,s=k)}}}}if(n.l=Math.round(a),n.r=Math.round(o),n.t=Math.round(s),n.b=Math.round(l),n.p=Math.round(e.margin.pad),n.w=Math.round(e.width)-n.l-n.r,n.h=Math.round(e.height)-n.t-n.b,!e._replotting&&"{}"!==i&&i!==JSON.stringify(e._size))return P.call("plot",t)},An.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&An.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(ne.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!ne.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):ne.isJSDate(t)?ne.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},An.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){h=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return P.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,s=0,l=0;function u(){return s++,function(){var r;h||++l!==s||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return P.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var f=t._fullLayout._basePlotModules,p=!1;if(r)for(o=0;o=0;a--)if(g[a].enabled){r._indexToPoints=g[a]._indexToPoints;break}n&&n.calc&&(d=n.calc(t,r))}Array.isArray(d)&&d[0]||(d=[{x:Mn,y:Mn}]),d[0].t||(d[0].t={}),d[0].trace=r,u[i]=d}P.getComponentMethod("fx","calc")(t)},An.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},An.generalUpdatePerTraceModule=function(t,e,r,n){var i,a=e.traceHash,o={};for(i=0;i0||h<0){var d={left:[-i,0],right:[i,0],top:[0,-i],bottom:[0,i]}[c.side];n.attr("transform","translate("+d+")")}}}k.call(T),M&&(w?k.on(".opacity",null):(b=0,_=!0,k.text(l).on("mouseover.opacity",function(){e.select(this).transition().duration(f.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){e.select(this).transition().duration(f.HIDE_PLACEHOLDER).style("opacity",0)})),k.call(er.makeEditable,{gd:t}).on("edit",function(e){void 0!==u?P.call("restyle",t,s,e,u):P.call("relayout",t,s,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(T)}).on("input",function(t){this.text(t||" ").call(er.positionText,h.x,h.y)}));return k.classed("js-placeholder",_),d}},On=/ [XY][0-9]* /;var Rn=t.FP_SAFE,Fn=Vn,Bn=Un,Nn=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=Vn(t),t._r=t.range.slice(),t._rl=ne.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?Vn(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=ne.extendFlat({},n)}},jn=function(t,e,n){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!e)return;t._min||(t._min=[]);t._max||(t._max=[]);n||(n={});t._m||t.setScale();var i,a,o,s,l,u,c,h,f,p,d,g,v=e.length,m=n.padded||!1,y=n.tozero&&("linear"===t.type||"-"===t.type),x="log"===t.type,b=!1;function _(t){if(Array.isArray(t))return b=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=_((t._m>0?n.ppadplus:n.ppadminus)||n.ppad||0),M=_((t._m>0?n.ppadminus:n.ppadplus)||n.ppad||0),A=_(n.vpadplus||n.vpad),k=_(n.vpadminus||n.vpad);if(!b){if(d=1/0,g=-1/0,x)for(i=0;i0&&(d=s),s>g&&s-Rn&&(d=s),s>g&&s=b&&(s.extrapad||!m)){p=!1;break}_(i,s.val)&&s.pad<=b&&(m||!s.extrapad)&&(v.splice(a,1),a--)}if(p){var T=y&&0===i;v.push({val:i,pad:T?0:b,extrapad:!T&&m})}}}}var S=Math.min(6,v);for(i=0;i=S;i--)T(i)};function Vn(t){var e,r,n,i,a,o,s,l,u=[],c=t._min[0].val,h=t._max[0].val,f=0,p=!1,d=Un(t);for(e=1;e0&&s>0&&l/s>f&&(a=n,o=i,f=l/s);if(c===h){var v=c-1,m=c+1;u="tozero"===t.rangemode?c<0?[v,0]:[0,m]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,m)]:[v,m]}else f&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(a.val>=0&&(a={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(a.val-f*d(a)<0&&(a={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),f=(o.val-a.val)/(t._length-d(a)-d(o))),u=[a.val-f*d(a),o.val+f*d(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),p&&u.reverse(),ne.simpleMap(u,t.l2r||Number)}function Un(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function qn(t){return r(t)&&Math.abs(t)=e}var Wn=t.BADNUM,Yn=function(t,e){return function(t,e){for(var n,i=0,a=0,o=Math.max(1,(t.length-1)/1e3),s=0;s2*a}(t,e)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}(t)?"category":function(t){if(!t)return!1;for(var e=0;e0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*a*Math.abs(n-i))}return $n}function s(e,n,i){var a=Jn(e,i||t.calendar);if(a===$n){if(!r(e))return $n;a=Jn(new Date(+e))}return a}function l(e,r,n){return Zn(e,r,n||t.calendar)}function u(e){return t._categories[Math.round(e)]}function c(e){if(t._categoriesMap){var n=t._categoriesMap[e];if(void 0!==n)return n}if(r(e))return+e}function h(n){return r(n)?e.round(t._b+t._m*n,2):$n}function f(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:Kn,t.l2c="log"===t.type?ti:Kn,t.l2p=h,t.p2l=f,t.c2p="log"===t.type?function(t,e){return h(o(t,e))}:h,t.p2c="log"===t.type?function(t){return ti(f(t))}:f,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=Xn,t.c2d=t.c2r=t.l2d=t.l2r=Kn,t.d2p=t.r2p=function(e){return t.l2p(Xn(e))},t.p2d=t.p2r=f,t.cleanPos=Kn):"log"===t.type?(t.d2r=t.d2l=function(t,e){return o(Xn(t),e)},t.r2d=t.r2c=function(t){return ti(Xn(t))},t.d2c=t.r2l=Xn,t.c2d=t.l2r=Kn,t.c2r=o,t.l2d=ti,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return ti(f(t))},t.r2p=function(e){return t.l2p(Xn(e))},t.p2r=f,t.cleanPos=Kn):"date"===t.type?(t.d2r=t.r2d=ne.identity,t.d2c=t.r2c=t.d2l=t.r2l=s,t.c2d=t.c2r=t.l2d=t.l2r=l,t.d2p=t.r2p=function(e,r,n){return t.l2p(s(e,0,n))},t.p2d=t.p2r=function(t,e,r){return l(f(t),e,r)},t.cleanPos=function(e){return ne.cleanDate(e,$n,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return $n},t.r2d=t.c2d=t.l2d=u,t.d2r=t.d2l_noadd=c,t.r2c=function(e){var r=c(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=Kn,t.r2l=c,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return u(f(t))},t.r2p=t.d2p,t.p2r=f,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:Kn(t)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var a,o,s=ne.nestedProperty(t,e).get();if(o=(o="date"===t.type?ne.dfltRange(t.calendar):"y"===i?Te.DFLTRANGEY:n.dfltRange||Te.DFLTRANGEX).slice(),s&&2===s.length)for("date"===t.type&&(s[0]=ne.cleanDate(s[0],$n,t.calendar),s[1]=ne.cleanDate(s[1],$n,t.calendar)),a=0;a<2;a++)if("date"===t.type){if(!ne.isDateTime(s[a],t.calendar)){t[e]=o;break}if(t.r2l(s[0])===t.r2l(s[1])){var l=ne.constrain(t.r2l(s[0]),ne.MIN_MS+1e3,ne.MAX_MS-1e3);s[0]=t.l2r(l-1e3),s[1]=t.l2r(l+1e3);break}}else{if(!r(s[a])){if(!r(s[1-a])){t[e]=o;break}s[a]=s[1-a]*(a?10:.1)}if(s[a]<-Qn?s[a]=-Qn:s[a]>Qn&&(s[a]=Qn),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else ne.nestedProperty(t,e).set(o)},t.setScale=function(e){var r=n._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var a=gn.getFromId({_fullLayout:n},t.overlaying);t.domain=a.domain}var o=e&&t._r?"_r":"range",s=t.calendar;t.cleanRange(o);var l=t.r2l(t[o][0],s),u=t.r2l(t[o][1],s);if("y"===i?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(l-u),t._b=-t._m*u):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(u-l),t._b=-t._m*l),!isFinite(t._m)||!isFinite(t._b))throw n._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,i,a,o,s=t.type,l="date"===s&&e[r+"calendar"];if(r in e){if(n=e[r],o=e._length||n.length,ne.isTypedArray(n)&&("linear"===s||"log"===s)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(i=new Array(o),a=0;a=t.r2l(t.range[0])&&n<=t.r2l(t.range[1])},t.clearCalc=function(){t._min=[],t._max=[],t._categories=(t._initialCategories||[]).slice(),t._categoriesMap={};for(var e=0;e2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},pi.saveRangeInitial=function(t,e){for(var r=pi.list(t,"",!0),n=!1,i=0;i.3*f||c(i)||c(a))){var p=n.dtick/2;t+=t+p.8){var o=Number(r.substr(1));a.exactYears>.8&&o%12==0?t=pi.tickIncrement(t,"M6","reverse")+1.5*ai:a.exactMonths>.8?t=pi.tickIncrement(t,"M1","reverse")+15.5*ai:t-=ai/2;var s=pi.tickIncrement(t,r);if(s<=n)return s}return t}(d,t,s.dtick,l,a)),p=d,0;p<=u;)p=pi.tickIncrement(p,s.dtick,!1,a),0;return{start:e.c2r(d,0,a),end:e.c2r(p,0,a),size:s.dtick,_dataSpan:u-l}},pi.prepTicks=function(t){var e=ne.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=ne.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),pi.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),ki(t)},pi.calcTicks=function(t){pi.prepTicks(t);var e=ne.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),o=ne.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],l=1.0001*o[1]-1e-4*o[0],u=Math.min(s,l),c=Math.max(s,l),h=0;Array.isArray(i)||(i=[]);var f="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:l<=n)&&!(a.length>s||l===o);l=pi.tickIncrement(l,t.dtick,i,t.calendar))o=l,a.push(l);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(a.length),c=0;c10||"01-01"!==i.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=ai&&a<=10||e>=15*ai)t._tickround="d";else if(e>=si&&a<=16||e>=oi)t._tickround="M";else if(e>=li&&a<=19||e>=si)t._tickround="S";else{var o=t.l2r(n+e).replace(/^-/,"").length;t._tickround=Math.max(a,o)-20}}else if(r(e)||"L"===e.charAt(0)){var s=t.range.map(t.r2d||Number);r(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),u=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(u)>3&&(Ei(t.exponentformat)&&!Ci(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function Ti(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}pi.autoTicks=function(t,e){var n;function i(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=ne.dateTick0(t.calendar);var a=2*e;a>ni?(e/=ni,n=i(10),t.dtick="M"+12*Ai(e,n,mi)):a>ii?(e/=ii,t.dtick="M"+Ai(e,1,yi)):a>ai?(t.dtick=Ai(e,ai,bi),t.tick0=ne.dateTick0(t.calendar,!0)):a>oi?t.dtick=Ai(e,oi,yi):a>si?t.dtick=Ai(e,si,xi):a>li?t.dtick=Ai(e,li,xi):(n=i(10),t.dtick=Ai(e,n,mi))}else if("log"===t.type){t.tick0=0;var o=ne.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/e);e=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,n=i(10),t.dtick="L"+Ai(e,n,mi)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):"angular"===t._id?(t.tick0=0,n=1,t.dtick=Ai(e,n,Mi)):(t.tick0=0,n=i(10),t.dtick=Ai(e,n,mi));if(0===t.dtick&&(t.dtick=1),!r(t.dtick)&&"string"!=typeof t.dtick){var l=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(l)}},pi.tickIncrement=function(t,n,i,a){var o=i?-1:1;if(r(n))return t+o*n;var s=n.charAt(0),l=o*Number(n.substr(1));if("M"===s)return ne.incrementMonth(t,l,a);if("L"===s)return Math.log(Math.pow(10,t)+l)/Math.LN10;if("D"===s){var u="D2"===n?wi:_i,c=t+.01*o,h=ne.roundUp(ne.mod(c,1),u,i);return Math.floor(c)+Math.log(e.round(Math.pow(10,h),1))/Math.LN10}throw"unrecognized dtick "+String(n)},pi.tickFirst=function(t){var n=t.r2l||Number,i=ne.simpleMap(t.range,n),a=i[1]"+s,t._prevDateHead=s));e.text=l}(t,o,n,l):"log"===t.type?function(t,e,n,i,a){var o=t.dtick,s=e.x,l=t.tickformat;"never"===a&&(a="");!i||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(l||"string"==typeof o&&"L"===o.charAt(0))e.text=Li(Math.pow(10,s),t,a,i);else if(r(o)||"D"===o.charAt(0)&&ne.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||Ei(t.exponentformat)&&Ci(u)?(e.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+ui+-u+"",e.fontSize*=1.25):(e.text=Li(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);e.text=String(Math.round(Math.pow(10,ne.mod(s,1)))),e.fontSize*=.75}if("D1"===t.dtick){var c=String(e.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(s<0?.5:.25)))}}(t,o,0,l,i):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=Li(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(o[1]>=100)e.text=Li(ne.deg2rad(e.x),t,i,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),s&&(e.text=ui+e.text)}}}}(t,o,n,l,i):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=Li(e.x,t,i,n)}(t,o,0,l,i),t.tickprefix&&!f(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!f(t.showticksuffix)&&(o.text+=t.ticksuffix),o},pi.hoverLabelText=function(t,e,r){if(r!==ci&&r!==e)return pi.hoverLabelText(t,e)+" - "+pi.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=pi.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":ui+i:i};var Si=["f","p","n","\u03bc","m","","k","M","G","T"];function Ei(t){return"SI"===t||"B"===t}function Ci(t){return t>14||t<-15}function Li(t,e,n,i){var a=t<0,o=e._tickround,s=n||e.exponentformat||"B",l=e._tickexponent,u=pi.getTickFormat(e),c=e.separatethousands;if(i){var h={exponentformat:s,dtick:"none"===e.showexponent?e.dtick:r(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};ki(h),o=(Number(h._tickround)||0)+4,l=h._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,ui);var f,p=Math.pow(10,-o)/2;if("none"===s&&(l=0),(t=Math.abs(t))"+f+"":"B"===s&&9===l?t+="B":Ei(s)&&(t+=Si[l/3+5]));return a?ui+t:t}function zi(t,e){for(var r=0;r=0,a=u(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=a(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;na&&(a=u,o=l)}}return a?i(o):Fi};case"rms":return function(t,e){for(var r=0,a=0,o=0;o0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}},Yi=s.mix,Xi=C.lightFraction,Zi=function(t,e,r,n){var i=(n=n||{}).dfltColor;function a(r,i){return ne.coerce2(t,e,n.attributes,r,i)}var o=a("linecolor",i),s=a("linewidth");r("showline",n.showLine||!!o||!!s)||(delete e.linecolor,delete e.linewidth);var l=a("gridcolor",Yi(i,n.bgColor,n.blend||Xi).toRgbString()),u=a("gridwidth");if(r("showgrid",n.showGrid||!!l||!!u)||(delete e.gridcolor,delete e.gridwidth),!n.noZeroLine){var c=a("zerolinecolor",i),h=a("zerolinewidth");r("zeroline",n.showGrid||!!c||!!h)||(delete e.zerolinecolor,delete e.zerolinewidth)}};function Ji(t,r,n){var i,a,o,s,l,u=[],c=n.map(function(e){return e[t]}),h=e.bisector(r).left;for(i=0;id[1]-.01&&(e.domain=o),ne.noneOrAll(t.domain,e.domain,o)}return n("layer"),e},ra=gn.name2id,na=function(t,e,r,n,i){i&&(e._name=i,e._id=ra(i)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var i=function(t,e,r){for(var n=0;n rect").call(Sr.setTranslate,0,0).call(Sr.setScale,1,1),t.plot.call(Sr.setTranslate,e._offset,r._offset).call(Sr.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(Sr.setPointGroupScale,1,1),n.selectAll(".textpoint").call(Sr.setTextPointsScale,1,1),n.call(Sr.hideOutsideRangePoints,t)}function g(e,r){var n,i,o,s=h[e.xaxis._id],l=h[e.yaxis._id],u=[];if(s){i=(n=t._fullLayout[s.axisName])._r,o=s.to,u[0]=(i[0]*(1-r)+r*o[0]-i[0])/(i[1]-i[0])*e.xaxis._length;var c=i[1]-i[0],f=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[2]=e.xaxis._length*(1-r+r*f/c)}else u[0]=0,u[2]=e.xaxis._length;if(l){i=(n=t._fullLayout[l.axisName])._r,o=l.to,u[1]=(i[1]*(1-r)+r*o[1]-i[1])/(i[0]-i[1])*e.yaxis._length;var p=i[1]-i[0],d=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[3]=e.yaxis._length*(1-r+r*d/p)}else u[1]=0,u[3]=e.yaxis._length;!function(e,r){var n,i=[];for(i=[e._id,r._id],n=0;n rect").call(Sr.setTranslate,_,w).call(Sr.setScale,1/x,1/b),e.plot.call(Sr.setTranslate,k,T).call(Sr.setScale,x,b).selectAll(".points").selectAll(".point").call(Sr.setPointGroupScale,1/x,1/b),e.plot.selectAll(".points").selectAll(".textpoint").call(Sr.setTextPointsScale,1/x,1/b)}i&&(s=i());var v=e.ease(n.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(c),c=null,function(){for(var e={},r=0;rn.duration?(function(){for(var e={},r=0;r0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},Ia.prototype.on=Ia.prototype.addListener,Ia.prototype.once=function(t,e){if(!Oa(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},Ia.prototype.removeListener=function(t,e){var r,n,i,a;if(!Oa(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=(r=this._events[t]).length,n=-1,r===e||Oa(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(Ra(r)){for(a=i;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},Ia.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(Oa(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},Ia.prototype.listeners=function(t){return this._events&&this._events[t]?Oa(this._events[t])?[this._events[t]]:this._events[t].slice():[]},Ia.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(Oa(e))return 1;if(e)return e.length}return 0},Ia.listenerCount=function(t,e){return t.listenerCount(e)};var Ba,Na=Da.EventEmitter,ja={init:function(t){if(t._ev instanceof Na)return t;var e=new Na,r=new Na;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;l4/3-s?o:s},qa.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:ne.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:ne.constrain(Math.floor(3*e),0,2),za[e][t]},qa.unhover=Ba.wrapped,qa.unhoverRaw=Ba.raw,qa.init=function(t){var e,r,n,i,a,o,s,l,u=t.gd,c=1,h=f.DBLCLICKDELAY,p=t.element;u._mouseDownTime||(u._mouseDownTime=0),p.style.pointerEvents="all",p.onmousedown=g,Ea?(p._ontouchstart&&p.removeEventListener("touchstart",p._ontouchstart),p._ontouchstart=g,p.addEventListener("touchstart",g,{passive:!1})):p.ontouchstart=g;var d=t.clampFn||function(t,e,r){return Math.abs(t)h&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!l){var r;try{r=new MouseEvent("click",e)}catch(t){var n=Ga(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}s.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&P.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},qa.coverSlip=Ha;function Wa(t,e,r,n){n=n||ne.identity,Array.isArray(t)&&(e[0][r]=n(t))}var Ya={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},flat:function(t,e){for(var r=new Array(t.length),n=0;n=0&&r.index-1&&s.length>d&&(s=d>3?s.substr(0,d-3)+"...":s.substr(0,d))}void 0!==t.extraText&&(l+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(l+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(l+="y: "+t.yLabel+"
"),l+=(l?"z: ":"")+t.zLabel):w&&t[i+"Label"]===v?l=t[("x"===i?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(l=t.yLabel):l=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(l+=(l?"
":"")+t.text),""===l&&(""===s&&r.remove(),l=s);var g=r.select("text.nums").call(Sr.font,t.fontFamily||c,t.fontSize||h,t.fontColor||p).text(l).attr("data-notex",1).call(er.positionText,0,0).call(er.convertToTspans,n),m=r.select("text.name"),y=0;s&&s!==l?(m.call(Sr.font,t.fontFamily||c,t.fontSize||h,f).text(s).attr("data-notex",1).call(er.positionText,0,0).call(er.convertToTspans,n),y=m.node().getBoundingClientRect().width+2*so):(m.remove(),r.select("rect").remove()),r.select("path").style({fill:f,stroke:p});var M,A,k=g.node().getBoundingClientRect(),T=t.xa._offset+(t.x0+t.x1)/2,S=t.ya._offset+(t.y0+t.y1)/2,E=Math.abs(t.x1-t.x0),C=Math.abs(t.y1-t.y0),L=k.width+oo+so+y;t.ty0=x-k.top,t.bx=k.width+2*so,t.by=k.height+2*so,t.anchor="start",t.txwidth=k.width,t.tx2width=y,t.offset=0,a?(t.pos=T,M=S+C/2+L<=_,A=S-C/2-L>=0,"top"!==t.idealAlign&&M||!A?M?(S+=C/2,t.anchor="start"):t.anchor="middle":(S-=C/2,t.anchor="end")):(t.pos=S,M=T+E/2+L<=b,A=T-E/2-L>=0,"left"!==t.idealAlign&&M||!A?M?(T+=E/2,t.anchor="start"):t.anchor="middle":(T-=E/2,t.anchor="end")),g.attr("text-anchor",t.anchor),y&&m.attr("text-anchor",t.anchor),r.attr("transform","translate("+T+","+S+")"+(a?"rotate("+eo+")":""))}),E}function uo(t,r){t.each(function(t){var n=e.select(this);if(t.del)n.remove();else{var i="end"===t.anchor?-1:1,a=n.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],s=o*(oo+so),l=s+o*(t.txwidth+so),u=0,c=t.offset;"middle"===t.anchor&&(s-=t.tx2width/2,l+=t.txwidth/2+so),r&&(c*=-ao,u=t.offset*io),n.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(c-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(i*oo+u)+","+(oo+c)+"v"+(t.by/2-oo)+"h"+i*t.bx+"v-"+t.by+"H"+(i*oo+u)+"V"+(c-oo)+"Z"),a.call(er.positionText,s+u,c+t.ty0-t.by/2+so),t.tx2width&&(n.select("text.name").call(er.positionText,l+o*so+u,c+t.ty0-t.by/2+so),n.select("rect").call(Sr.setRect,l+(o-1)*t.tx2width/2+u,c-t.by/2-1,t.tx2width,t.by+2))}})}function co(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return ne.castOption(i,r,t)||ne.extractOption({},n,"",e)}:function(t,e){return ne.extractOption(a,n,t,e)};function s(e,r,n){var i=o(r,n);i&&(t[e]=i)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=ne.constrain(t.x0,0,t.xa._length),t.x1=ne.constrain(t.x1,0,t.xa._length),t.y0=ne.constrain(t.y0,0,t.ya._length),t.y1=ne.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:ri.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:ri.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var l=ri.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+l+" / -"+ri.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+l,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=ri.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+ri.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function ho(t,e){var r,n,i=e.container,a=e.fullLayout,o=e.event,l=!!t.hLinePoint,u=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),u||l){var c=Oe.combine(a.plot_bgcolor,a.paper_bgcolor);if(l){var h,f,p=t.hLinePoint;r=p&&p.xa,"cursor"===(n=p&&p.ya).spikesnap?(h=o.pointerX,f=o.pointerY):(h=r._offset+p.x,f=n._offset+p.y);var d,g,v=s.readability(p.color,c)<1.5?Oe.contrast(c):p.color,m=n.spikemode,y=n.spikethickness,x=n.spikecolor||v,b=n._boundingBox,_=(b.left+b.right)/2q.width||V<0||V>q.height)return Ua.unhoverRaw(t,n);n.pointerX=n.offsetX,n.pointerY=n.offsetY}if(_="xval"in n?Ya.flat(o,n.xval):Ya.p2c(p,j),w="yval"in n?Ya.flat(o,n.yval):Ya.p2c(d,V),!r(_[0])||!r(w[0]))return ne.warn("Fx.hover failed",n,t),Ua.unhoverRaw(t,n)}var H=1/0;for(A=0;AD&&(F.splice(0,D),H=F[0].distance),c&&0!==R&&0===F.length){I.distance=R,I.index=!1;var Z=T._module.hoverPoints(I,L,z,"closest",s._hoverlayer);if(Z&&(Z=Z.filter(function(t){return t.spikeDistance<=R})),Z&&Z.length){var J,K=Z.filter(function(t){return t.xa.showspikes});if(K.length){var Q=K[0];r(Q.x0)&&r(Q.y0)&&(J=rt(Q),(!N.vLinePoint||N.vLinePoint.spikeDistance>J.spikeDistance)&&(N.vLinePoint=J))}var $=Z.filter(function(t){return t.ya.showspikes});if($.length){var tt=$[0];r(tt.x0)&&r(tt.y0)&&(J=rt(tt),(!N.hLinePoint||N.hLinePoint.spikeDistance>J.spikeDistance)&&(N.hLinePoint=J))}}}}function et(t,e){for(var r,n=null,i=1/0,a=0;a1,gt=Oe.combine(s.plot_bgcolor||Oe.background,s.paper_bgcolor),vt={hovermode:b,rotateLabels:dt,bgColor:gt,container:s._hoverlayer,outerContainer:s._paperdiv,commonLabelOpts:s.hoverlabel,hoverdistance:s.hoverdistance},mt=lo(F,vt,t);if(function(t,e,r){var n,i,a,o,s,l,u,c=0,h=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?no:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function f(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(s=d.length-1;s>=0;s--)d[s].dp+=i;for(p.push.apply(p,d),h.splice(o+1,1),u=0,s=p.length-1;s>=0;s--)u+=p[s].dp;for(a=u/p.length,s=p.length-1;s>=0;s--)p[s].dp-=a;n=!1}else o++}h.forEach(f)}for(o=h.length-1;o>=0;o--){var m=h[o];for(s=m.length-1;s>=0;s--){var y=m[s],x=t[y.i];x.offset=y.dp,x.del=y.del}}}(F,dt?"xa":"ya",s),uo(mt,dt),n.target&&n.target.tagName){var yt=P.getComponentMethod("annotations","hasClickToShow")(t,ft);$a(e.select(n.target),yt?"pointer":"")}if(!n.target||a||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}(t,0,ht))return;ht&&t.emit("plotly_unhover",{event:n,points:ht});t.emit("plotly_hover",{event:n,points:t._hoverdata,xaxes:p,yaxes:d,xvals:_,yvals:w})}(t,n,i,a)})},to.loneHover=function(t,r){var n={color:t.color||Oe.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},i=e.select(r.container),a=r.outerContainer?e.select(r.outerContainer):i,o={hovermode:"closest",rotateLabels:!1,bgColor:r.bgColor||Oe.background,container:i,outerContainer:a},s=lo([n],o,r.gd);return uo(s,o.rotateLabels),s.node()};var po=to.hover,go=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),ne.coerceFont(r,"hoverlabel.font",n.font)},vo=T({editType:"none"});vo.family.dflt=Pa.HOVERFONT,vo.size.dflt=Pa.HOVERFONTSIZE;var mo={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:vo,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"}};var yo={moduleType:"component",name:"fx",constants:Pa,schema:{layout:mo},attributes:S,layoutAttributes:mo,supplyLayoutGlobalDefaults:function(t,e){go(0,0,function(r,n){return ne.coerce(t,e,mo,r,n)})},supplyDefaults:function(t,e,r,n){go(0,0,function(r,n){return ne.coerce(t,e,S,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return ne.coerce(t,e,mo,r,n)}var i;n("dragmode"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r.01?k:function(t,e){return Math.abs(t-e)>=2?k(t):t>e?Math.ceil(t):Math.floor(t)};d=M(d,p=M(p,d)),v=M(v,g=M(g,v))}var A=e.select(this);A.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+p+","+g+"V"+v+"H"+d+"V"+g+"Z").call(Sr.setClipUrl,n.layerClipId),function(t,e,r,n,i,a,o,s){var l;function u(e,r,n){var i=e.append("text").text(r).attr({class:"bartext bartext-"+l,transform:"","text-anchor":"middle","data-notex":1}).call(Sr.font,n).call(er.convertToTspans,t);return i}var c=r[0].trace,h=c.orientation,f=function(t,e){var r=Io(t.text,e);return Do(Ao,r)}(c,n);if(!f)return;if("none"===(l=function(t,e){var r=Io(t.textposition,e);return function(t,e,r){return t.coerceNumber&&(e=+e),-1!==t.values.indexOf(e)?e:void 0!==r?r:t.dflt}(ko,r)}(c,n)))return;var p,d,g,v,m,y,x=function(t,e,r){return Po(To,t.textfont,e,r)}(c,n,t._fullLayout.font),b=function(t,e,r){return Po(So,t.insidetextfont,e,r)}(c,n,x),_=function(t,e,r){return Po(Eo,t.outsidetextfont,e,r)}(c,n,x),w=t._fullLayout.barmode,M="stack"===w||"relative"===w,A=r[n],k=!M||A._outmost,T=Math.abs(a-i)-2*Co,S=Math.abs(s-o)-2*Co;"outside"===l&&(k||(l="inside"));if("auto"===l)if(k){l="inside",p=u(e,f,b),d=Sr.bBox(p.node()),g=d.width,v=d.height;var E=g>0&&v>0,C=g<=T&&v<=S,L=g<=S&&v<=T,z="h"===h?T>=g*(S/v):S>=v*(T/g);E&&(C||L||z)?l="inside":(l="outside",p.remove(),p=null)}else l="inside";if(!p&&(p=u(e,f,"outside"===l?_:b),d=Sr.bBox(p.node()),g=d.width,v=d.height,g<=0||v<=0))return void p.remove();"outside"===l?(y="both"===c.constraintext||"outside"===c.constraintext,m=function(t,e,r,n,i,a,o){var s,l="h"===a?Math.abs(n-r):Math.abs(e-t);l>2*Co&&(s=Co);var u=1;o&&(u="h"===a?Math.min(1,l/i.height):Math.min(1,l/i.width));var c,h,f,p,d=(i.left+i.right)/2,g=(i.top+i.bottom)/2;c=u*i.width,h=u*i.height,"h"===a?er?(f=(t+e)/2,p=n+s+h/2):(f=(t+e)/2,p=n-s-h/2);return zo(d,g,f,p,u,!1)}(i,a,o,s,d,h,y)):(y="both"===c.constraintext||"inside"===c.constraintext,m=function(t,e,r,n,i,a,o){var s,l,u,c,h,f,p,d=i.width,g=i.height,v=(i.left+i.right)/2,m=(i.top+i.bottom)/2,y=Math.abs(e-t),x=Math.abs(n-r);y>2*Co&&x>2*Co?(y-=2*(h=Co),x-=2*h):h=0;d<=y&&g<=x?(f=!1,p=1):d<=x&&g<=y?(f=!0,p=1):dr?(u=(t+e)/2,c=n-h-l/2):(u=(t+e)/2,c=n+h+l/2);return zo(v,m,u,c,p,f)}(i,a,o,s,d,h,y));p.attr("transform",m)}(t,A,i,u,p,d,g,v),n.layerClipId&&Sr.hideOutsideRangePoint(i[u],A.select("text"),a,o,c.xcalendar,c.ycalendar)}else e.select(this).remove();function k(t){return 0===s.bargap&&0===s.bargroupgap?e.round(Math.round(t)-w,2):t}})}),P.getComponentMethod("errorbars","plot")(l,n),l.each(function(t){var r=!1===t[0].trace.cliponaxis;Sr.setClipUrl(e.select(this),r?null:n.layerClipId)})};function zo(t,e,r,n,i,a){var o;return i<1?o="scale("+i+") ":(i=1,o=""),"translate("+(r-i*t)+" "+(n-i*e)+")"+o+(a?"rotate("+a+" "+t+" "+e+") ":"")}function Po(t,e,n,i){var a=Io((e=e||{}).family,n),o=Io(e.size,n),l=Io(e.color,n);return{family:Do(t.family,a,i.family),size:function(t,e,n){if(r(e)){e=+e;var i=t.min,a=t.max,o=void 0!==i&&ea;if(!o)return e}return void 0!==n?n:t.dflt}(t.size,o,i.size),color:function(t,e,r){return s(e).isValid()?e:void 0!==r?r:t.dflt}(t.color,l,i.color)}}function Io(t,e){var r;return Array.isArray(t)?eu+s||!r(l))&&(h=!0,Xo(c,t))}for(var p=0;p1||0===a.bargap&&0===a.bargroupgap&&!t[0].trace.marker.line.width)&&e.select(this).attr("shape-rendering","crispEdges")}),n.selectAll("g.points").each(function(r){var n=e.select(this),i=n.selectAll("path"),a=n.selectAll("text"),o=r[0].trace;Sr.pointStyle(i,o,t),Sr.selectedPointStyle(i,o),a.each(function(t){var r,n=e.select(this);function i(e){var n=r[e];return Array.isArray(n)?n[t.i]:n}n.classed("bartext-inside")?r=o.insidetextfont:n.classed("bartext-outside")&&(r=o.outsidetextfont),r||(r=o.textfont),Sr.font(n,i("family"),i("size"),i("color"))}),Sr.selectedTextStyle(a,o)}),P.getComponentMethod("errorbars","style")(n)},ts=m.extendFlat,es=Qe.LINE_SPACING,rs={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},ns=function(t,r){var n={};function i(){var o=t._fullLayout,l=o._size;if("function"==typeof n.fillcolor||"function"==typeof n.line.color){var u,c,h=e.extent(("function"==typeof n.fillcolor?n.fillcolor:n.line.color).domain()),f=[],p=[],d="function"==typeof n.line.color?n.line.color:function(){return n.line.color},g="function"==typeof n.fillcolor?n.fillcolor:function(){return n.fillcolor},v=n.levels.end+n.levels.size/100,m=n.levels.size,y=1.001*h[0]-.001*h[1],x=1.001*h[1]-.001*h[0];for(c=0;c<1e5&&(u=n.levels.start+c*m,!(m>0?u>=v:u<=v));c++)u>y&&u0?u>=v:u<=v));c++)u>h[0]&&u1){var U=Math.pow(10,Math.floor(Math.log(V)/Math.LN10));N*=U*ne.roundUp(V/U,[2,5,10]),(Math.abs(n.levels.start)/n.levels.size+1e-6)%1<2e-6&&(F.tick0=0)}F.dtick=N}F.domain=[I+C,I+T-C],F.setScale();var q=o._infolayer.selectAll("g."+r).data([0]);q.enter().append("g").classed(r,!0).classed(rs.colorbar,!0).each(function(){var t=e.select(this);t.append("rect").classed(rs.cbbg,!0),t.append("g").classed(rs.cbfills,!0),t.append("g").classed(rs.cblines,!0),t.append("g").classed(rs.cbaxis,!0).classed(rs.crisp,!0),t.append("g").classed(rs.cbtitleunshift,!0).append("g").classed(rs.cbtitle,!0),t.append("rect").classed(rs.cboutline,!0),t.select(".cbtitle").datum(0)}),q.attr("transform","translate("+Math.round(l.l)+","+Math.round(l.t)+")");var H=q.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(l.l)+",-"+Math.round(l.t)+")");F._axislayer=q.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(n.titleside)){var W,Y=l.l+(n.x+S)*l.w,X=F.titlefont.size;W="top"===n.titleside?(1-(I+T-C))*l.h+l.t+3+.75*X:(1-(I+C))*l.h+l.t-3-.25*X,tt(F._id+"title",{attributes:{x:Y,y:W,"text-anchor":"start"}})}var Z,J,K,Q=ne.syncOrAsync([_n.previousPromises,function(){if(-1!==["top","bottom"].indexOf(n.titleside)){var r=q.select(".cbtitle"),i=r.select("text"),a=[-n.outlinewidth/2,n.outlinewidth/2],u=r.select(".h"+F._id+"title-math-group").node(),c=15.6;if(i.node()&&(c=parseInt(i.node().style.fontSize,10)*es),u?(G=Sr.bBox(u).height)>c&&(a[1]-=(G-c)/2):i.node()&&!i.classed(rs.jsPlaceholder)&&(G=Sr.bBox(i.node()).height),G){if(G+=5,"top"===n.titleside)F.domain[1]-=G/l.h,a[1]*=-1;else{F.domain[0]+=G/l.h;var v=er.lineCount(i);a[1]+=(1-v)*c}r.attr("transform","translate("+a+")"),F.setScale()}}q.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(l.h*(1-F.domain[1]))+")"),F._axislayer.attr("transform","translate(0,"+Math.round(-l.t)+")");var m=q.select(".cbfills").selectAll("rect.cbfill").data(p);m.enter().append("rect").classed(rs.cbfill,!0).style("stroke","none"),m.exit().remove(),m.each(function(t,r){var n=[0===r?h[0]:(p[r]+p[r-1])/2,r===p.length-1?h[1]:(p[r]+p[r+1])/2].map(F.c2p).map(Math.round);r!==p.length-1&&(n[1]+=n[1]>n[0]?1:-1);var i=g(t).replace("e-",""),a=s(i).toHexString();e.select(this).attr({x:L,width:Math.max(M,2),y:e.min(n),height:Math.max(e.max(n)-e.min(n),2),fill:a})});var y=q.select(".cblines").selectAll("path.cbline").data(n.line.color&&n.line.width?f:[]);return y.enter().append("path").classed(rs.cbline,!0),y.exit().remove(),y.each(function(t){e.select(this).attr("d","M"+L+","+(Math.round(F.c2p(t))+n.line.width/2%1)+"h"+M).call(Sr.lineGroupStyle,n.line.width,d(t),n.line.dash)}),F._axislayer.selectAll("g."+F._id+"tick,path").remove(),F._pos=L+M+(n.outlinewidth||0)/2-("outside"===n.ticks?1:0),F.side="right",ne.syncOrAsync([function(){return ri.doTicks(t,F,!0)},function(){if(-1===["top","bottom"].indexOf(n.titleside)){var r=F.titlefont.size,i=F._offset+F._length/2,a=l.l+(F.position||0)*l.w+("right"===F.side?10+r*(F.showticklabels?1:.5):-10-r*(F.showticklabels?.5:0));tt("h"+F._id+"title",{avoid:{selection:e.select(t).selectAll("g."+F._id+"tick"),side:n.titleside,offsetLeft:l.l,offsetTop:0,maxShift:o.width},attributes:{x:a,y:i,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},_n.previousPromises,function(){var e=M+n.outlinewidth/2+Sr.bBox(F._axislayer.node()).width;if((b=H.select("text")).node()&&!b.classed(rs.jsPlaceholder)){var i,a=H.select(".h"+F._id+"title-math-group").node();i=a&&-1!==["top","bottom"].indexOf(n.titleside)?Sr.bBox(a).width:Sr.bBox(H.node()).right-L-l.l,e=Math.max(e,i)}var o=2*n.xpad+e+n.borderwidth+n.outlinewidth/2,s=D-O;q.select(".cbbg").attr({x:L-n.xpad-(n.borderwidth+n.outlinewidth)/2,y:O-E,width:Math.max(o,2),height:Math.max(s+2*E,2)}).call(Oe.fill,n.bgcolor).call(Oe.stroke,n.bordercolor).style({"stroke-width":n.borderwidth}),q.selectAll(".cboutline").attr({x:L,y:O+n.ypad+("top"===n.titleside?G:0),width:Math.max(M,2),height:Math.max(s-2*n.ypad-G,2)}).call(Oe.stroke,n.outlinecolor).style({fill:"None","stroke-width":n.outlinewidth});var u=({center:.5,right:1}[n.xanchor]||0)*o;q.attr("transform","translate("+(l.l-u)+","+l.t+")"),_n.autoMargin(t,r,{x:n.x,y:n.y,l:o*({right:1,center:.5}[n.xanchor]||0),r:o*({left:1,center:.5}[n.xanchor]||0),t:s*({bottom:1,middle:.5}[n.yanchor]||0),b:s*({top:1,middle:.5}[n.yanchor]||0)})}],t);if(Q&&Q.then&&(t._promises||[]).push(Q),t._context.edits.colorbarPosition)Ua.init({element:q.node(),gd:t,prepFn:function(){Z=q.attr("transform"),Ka(q)},moveFn:function(t,e){q.attr("transform",Z+" translate("+t+","+e+")"),J=Ua.align(z+t/l.w,A,0,1,n.xanchor),K=Ua.align(I-e/l.h,T,0,1,n.yanchor);var r=Ua.getCursor(J,K,n.xanchor,n.yanchor);Ka(q,r)},doneFn:function(){Ka(q),void 0!==J&&void 0!==K&&P.call("restyle",t,{"colorbar.x":J,"colorbar.y":K},a().index)}});return Q}function $(t,e){return ne.coerce(R,F,Ce,t,e)}function tt(e,r){var n,i=a();n=P.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var s={propContainer:F,propName:n,traceIndex:i.index,placeholder:o._dfltTitle.colorbar,containerGroup:q.select(".cbtitle")},l="h"===e.charAt(0)?e.substr(1):"h"+e;q.selectAll("."+l+",."+l+"-math-group").remove(),Dn.draw(t,e,ts(s,r||{}))}o._infolayer.selectAll("g."+r).remove()}function a(){var e,n,i=r.substr(2);for(e=0;e=0&&M0){var k=_[n].sort(ds),T=k.map(gs),S=T.length,E={pos:v[n],pts:k};E.min=T[0],E.max=T[S-1],E.mean=ne.mean(T,S),E.sd=ne.stdev(T,S,E.mean),E.q1=ne.interp(T,.25),E.med=ne.interp(T,.5),E.q3=ne.interp(T,.75),E.lf=Math.min(E.q1,T[Math.min(ne.findBin(2.5*E.q1-1.5*E.q3,T,!0)+1,S-1)]),E.uf=Math.max(E.q3,T[Math.max(ne.findBin(2.5*E.q3-1.5*E.q1,T),0)]),E.lo=4*E.q1-3*E.q3,E.uo=4*E.q3-3*E.q1;var C=1.57*(E.q3-E.q1)/Math.sqrt(S);E.ln=E.med-C,E.un=E.med+C,h.push(E)}return function(t,e){if(ne.isArrayOrTypedArray(e.selectedpoints))for(var r=0;r0?(h[0].t={num:l[f],dPos:m,posLetter:s,valLetter:a,labels:{med:hs(t,"median:"),min:hs(t,"min:"),q1:hs(t,"q1:"),q3:hs(t,"q3:"),max:hs(t,"max:"),mean:"sd"===e.boxmean?hs(t,"mean \xb1 \u03c3:"):hs(t,"mean:"),lf:hs(t,"lower fence:"),uf:hs(t,"upper fence:")}},e._fullInput&&"candlestick"===e._fullInput.type&&delete h[0].t.labels,l[f]++,h):[{t:{empty:!0}}]};function ps(t,e,r){var n={text:"tx"};for(var i in n)Array.isArray(e[i])&&(t[n[i]]=e[i][r])}function ds(t,e){return t.v-e.v}function gs(t){return t.v}function vs(t,e,r,n){var i,a=r("y"),o=r("x");if(a&&a.length)i="v",o||r("x0");else{if(!o||!o.length)return void(e.visible=!1);i="h",r("y0")}P.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],n),r("orientation",i)}function ms(t,e,r,n){var i=n.prefix,a=ne.coerce2(t,e,cs,"marker.outliercolor"),o=r("marker.line.outliercolor"),s=r(i+"points",a||o?"suspectedoutliers":void 0);s?(r("jitter","all"===s?.3:0),r("pointpos","all"===s?-1.5:0),r("marker.symbol"),r("marker.opacity"),r("marker.size"),r("marker.color",e.line.color),r("marker.line.color"),r("marker.line.width"),"suspectedoutliers"===s&&(r("marker.line.outliercolor",e.marker.color),r("marker.line.outlierwidth")),r("selected.marker.color"),r("unselected.marker.color"),r("selected.marker.size"),r("unselected.marker.size"),r("text")):delete e.marker,r("hoveron"),ne.coerceSelectionMarkerOpacity(e,r)}var ys={supplyDefaults:function(t,e,r,n){function i(r,n){return ne.coerce(t,e,cs,r,n)}vs(t,e,i,n),!1!==e.visible&&(i("line.color",(t.marker||{}).color||r),i("line.width"),i("fillcolor",Oe.addOpacity(e.line.color,.5)),i("whiskerwidth"),i("boxmean"),i("notched",void 0!==t.notchwidth)&&i("notchwidth"),ms(t,e,i,{prefix:"box"}))},handleSampleDefaults:vs,handlePointsDefaults:ms};function xs(t,e,r,n){var i,a,o,s,l,u,c,h,f,p,d,g,v=t.cd,m=t.xa,y=t.ya,x=v[0].trace,b=v[0].t,_="violin"===x.type,w=[],M=b.bdPos,A=function(t){return t.pos+b.bPos-u};_&&"both"!==x.side?("positive"===x.side&&(f=function(t){var e=A(t);return yo.inbox(e,e+M,p)}),"negative"===x.side&&(f=function(t){var e=A(t);return yo.inbox(e-M,e,p)})):f=function(t){var e=A(t);return yo.inbox(e-M,e+M,p)},g=_?function(t){return yo.inbox(t.span[0]-l,t.span[1]-l,p)}:function(t){return yo.inbox(t.min-l,t.max-l,p)},"h"===x.orientation?(l=e,u=r,c=g,h=f,i="y",o=y,a="x",s=m):(l=r,u=e,c=f,h=g,i="x",o=m,a="y",s=y);var k=Math.min(1,M/Math.abs(o.r2c(o.range[1])-o.r2c(o.range[0])));function T(t){return(c(t)+h(t))/2}p=t.maxHoverDistance-k,d=t.maxSpikeDistance-k;var S=yo.getDistanceFunction(n,c,h,T);if(yo.getClosest(v,S,t),!1===t.index)return[];var E=v[t.index],C=x.line.color,L=(x.marker||{}).color;Oe.opacity(C)&&x.line.width?t.color=C:Oe.opacity(L)&&x.boxpoints?t.color=L:t.color=x.fillcolor,t[i+"0"]=o.c2p(E.pos+b.bPos-b.bdPos,!0),t[i+"1"]=o.c2p(E.pos+b.bPos+b.bdPos,!0),ri.tickText(o,o.c2l(E.pos),"hover").text,t[i+"LabelVal"]=E.pos;var z=i+"Spike";t.spikeDistance=T(E)*d/p,t[z]=o.c2p(E.pos,!0);var P={},I=["med","min","q1","q3","max"];(x.boxmean||(x.meanline||{}).visible)&&I.push("mean"),(x.boxpoints||x.points)&&I.push("lf","uf");for(var D=0;Dt.uf}),a=Math.max((t.max-t.min)/10,t.q3-t.q1),u=1e-9*a,c=a*Ts,h=[],f=0;if(r.jitter){if(0===a)for(f=1,h=new Array(i.length),e=0;et.lo&&(y.so=!0)}return i}).enter().append("path").classed("point",!0).call(Sr.translatePoints,i,a)}function Cs(t,r,n,i){var a,o,s=r.pos,l=r.val,u=i.bPos,c=i.bPosPxOffset||0;Array.isArray(i.bdPos)?(a=i.bdPos[0],o=i.bdPos[1]):(a=i.bdPos,o=i.bdPos),t.selectAll("path.mean").data(ne.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var r=s.c2p(t.pos+u,!0)+c,i=s.c2p(t.pos+u-a,!0)+c,h=s.c2p(t.pos+u+o,!0)+c,f=l.c2p(t.mean,!0),p=l.c2p(t.mean-t.sd,!0),d=l.c2p(t.mean+t.sd,!0);"h"===n.orientation?e.select(this).attr("d","M"+f+","+i+"V"+h+("sd"===n.boxmean?"m0,0L"+p+","+r+"L"+f+","+i+"L"+d+","+r+"Z":"")):e.select(this).attr("d","M"+i+","+f+"H"+h+("sd"===n.boxmean?"m0,0L"+r+","+p+"L"+i+","+f+"L"+r+","+d+"Z":""))})}var Ls={plot:function(t,r,n){var i=t._fullLayout,a=r.xaxis,o=r.yaxis;r.plot.select(".boxlayer").selectAll("g.trace.boxes").data(n).enter().append("g").attr("class","trace boxes").each(function(t){var r,n,s=t[0],l=s.t,u=s.trace,c=s.node3=e.select(this),h=i._numBoxes,f="group"===i.boxmode&&h>1,p=l.dPos*(1-i.boxgap)*(1-i.boxgroupgap)/(f?h:1),d=f?2*l.dPos*((l.num+.5)/h-.5)*(1-i.boxgap):0,g=p*u.whiskerwidth;!0!==u.visible||l.empty?e.select(this).remove():("h"===u.orientation?(r=o,n=a):(r=a,n=o),l.bPos=d,l.bdPos=p,l.wdPos=g,Ss(c,{pos:r,val:n},u,l),u.boxpoints&&Es(c,{x:a,y:o},u,l),u.boxmean&&Cs(c,{pos:r,val:n},u,l))})},plotBoxAndWhiskers:Ss,plotPoints:Es,plotBoxMean:Cs},zs=function(t,e){var r,n,i=t.cd,a=t.xaxis,o=t.yaxis,s=[];if(!1===e)for(r=0;r0;){var a=r%10;n=(0===a?"":t[a]+e[i])+n,i++,r=Math.floor(r/10)}return 0===n.indexOf(t[1]+e[1])&&(n=n.substr(1)),n||t[0]}}}),Us(Gs.prototype,{newDate:function(t,e,r){return this._calendar.newDate(null==t?this:t,e,r)},year:function(t){return 0===arguments.length?this._year:this.set(t,"y")},month:function(t){return 0===arguments.length?this._month:this.set(t,"m")},day:function(t){return 0===arguments.length?this._day:this.set(t,"d")},date:function(t,e,r){if(!this._calendar.isValid(t,e,r))throw(Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate).replace(/\{0\}/,this._calendar.local.name);return this._year=t,this._month=e,this._day=r,this},leapYear:function(){return this._calendar.leapYear(this)},epoch:function(){return this._calendar.epoch(this)},formatYear:function(){return this._calendar.formatYear(this)},monthOfYear:function(){return this._calendar.monthOfYear(this)},weekOfYear:function(){return this._calendar.weekOfYear(this)},daysInYear:function(){return this._calendar.daysInYear(this)},dayOfYear:function(){return this._calendar.dayOfYear(this)},daysInMonth:function(){return this._calendar.daysInMonth(this)},dayOfWeek:function(){return this._calendar.dayOfWeek(this)},weekDay:function(){return this._calendar.weekDay(this)},extraInfo:function(){return this._calendar.extraInfo(this)},add:function(t,e){return this._calendar.add(this,t,e)},set:function(t,e){return this._calendar.set(this,t,e)},compareTo:function(t){if(this._calendar.name!==t._calendar.name)throw(Zs.local.differentCalendars||Zs.regionalOptions[""].differentCalendars).replace(/\{0\}/,this._calendar.local.name).replace(/\{1\}/,t._calendar.local.name);var e=this._year!==t._year?this._year-t._year:this._month!==t._month?this.monthOfYear()-t.monthOfYear():this._day-t._day;return 0===e?0:e<0?-1:1},calendar:function(){return this._calendar},toJD:function(){return this._calendar.toJD(this)},fromJD:function(t){return this._calendar.fromJD(t)},toJSDate:function(){return this._calendar.toJSDate(this)},fromJSDate:function(t){return this._calendar.fromJSDate(t)},toString:function(){return(this.year()<0?"-":"")+Ws(Math.abs(this.year()),4)+"-"+Ws(this.month(),2)+"-"+Ws(this.day(),2)}}),Us(Ys.prototype,{_validateLevel:0,newDate:function(t,e,r){return null==t?this.today():(t.year&&(this._validate(t,e,r,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate),r=t.day(),e=t.month(),t=t.year()),new Gs(this,t,e,r))},today:function(){return this.fromJSDate(new Date)},epoch:function(t){return this._validate(t,this.minMonth,this.minDay,Zs.local.invalidYear||Zs.regionalOptions[""].invalidYear).year()<0?this.local.epochs[0]:this.local.epochs[1]},formatYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,Zs.local.invalidYear||Zs.regionalOptions[""].invalidYear);return(e.year()<0?"-":"")+Ws(Math.abs(e.year()),4)},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,Zs.local.invalidYear||Zs.regionalOptions[""].invalidYear),12},monthOfYear:function(t,e){var r=this._validate(t,e,this.minDay,Zs.local.invalidMonth||Zs.regionalOptions[""].invalidMonth);return(r.month()+this.monthsInYear(r)-this.firstMonth)%this.monthsInYear(r)+this.minMonth},fromMonthOfYear:function(t,e){var r=(e+this.firstMonth-2*this.minMonth)%this.monthsInYear(t)+this.minMonth;return this._validate(t,r,this.minDay,Zs.local.invalidMonth||Zs.regionalOptions[""].invalidMonth),r},daysInYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,Zs.local.invalidYear||Zs.regionalOptions[""].invalidYear);return this.leapYear(e)?366:365},dayOfYear:function(t,e,r){var n=this._validate(t,e,r,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate);return n.toJD()-this.newDate(n.year(),this.fromMonthOfYear(n.year(),this.minMonth),this.minDay).toJD()+1},daysInWeek:function(){return 7},dayOfWeek:function(t,e,r){var n=this._validate(t,e,r,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate);return(Math.floor(this.toJD(n))+2)%this.daysInWeek()},extraInfo:function(t,e,r){return this._validate(t,e,r,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate),{}},add:function(t,e,r){return this._validate(t,this.minMonth,this.minDay,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate),this._correctAdd(t,this._add(t,e,r),e,r)},_add:function(t,e,r){if(this._validateLevel++,"d"===r||"w"===r){var n=t.toJD()+e*("w"===r?this.daysInWeek():1),i=t.calendar().fromJD(n);return this._validateLevel--,[i.year(),i.month(),i.day()]}try{var a=t.year()+("y"===r?e:0),o=t.monthOfYear()+("m"===r?e:0);i=t.day();"y"===r?(t.month()!==this.fromMonthOfYear(a,o)&&(o=this.newDate(a,t.month(),this.minDay).monthOfYear()),o=Math.min(o,this.monthsInYear(a)),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o)))):"m"===r&&(!function(t){for(;oe-1+t.minMonth;)a++,o-=e,e=t.monthsInYear(a)}(this),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o))));var s=[a,this.fromMonthOfYear(a,o),i];return this._validateLevel--,s}catch(t){throw this._validateLevel--,t}},_correctAdd:function(t,e,r,n){if(!(this.hasYearZero||"y"!==n&&"m"!==n||0!==e[0]&&t.year()>0==e[0]>0)){var i={y:[1,1,"y"],m:[1,this.monthsInYear(-1),"m"],w:[this.daysInWeek(),this.daysInYear(-1),"d"],d:[1,this.daysInYear(-1),"d"]}[n],a=r<0?-1:1;e=this._add(t,r*i[0]+a*i[1],i[2])}return t.date(e[0],e[1],e[2])},set:function(t,e,r){this._validate(t,this.minMonth,this.minDay,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate);var n="y"===r?e:t.year(),i="m"===r?e:t.month(),a="d"===r?e:t.day();return"y"!==r&&"m"!==r||(a=Math.min(a,this.daysInMonth(n,i))),t.date(n,i,a)},isValid:function(t,e,r){this._validateLevel++;var n=this.hasYearZero||0!==t;if(n){var i=this.newDate(t,e,this.minDay);n=e>=this.minMonth&&e-this.minMonth=this.minDay&&r-this.minDay13.5?13:1),u=i-(l>2.5?4716:4715);return u<=0&&u--,this.newDate(u,l,s)},toJSDate:function(t,e,r){var n=this._validate(t,e,r,Zs.local.invalidDate||Zs.regionalOptions[""].invalidDate),i=new Date(n.year(),n.month()-1,n.day());return i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.setHours(i.getHours()>12?i.getHours()+2:0),i},fromJSDate:function(t){return this.newDate(t.getFullYear(),t.getMonth()+1,t.getDate())}});var Zs=qs=new Hs;Zs.cdate=Gs,Zs.baseCalendar=Ys,Zs.calendars.gregorian=Xs;var Js=qs.instance();function Ks(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Ks.prototype=new qs.baseCalendar,Us(Ks.prototype,{name:"Chinese",jdEpoch:1721425.5,hasYearZero:!1,minMonth:0,firstMonth:0,minDay:1,regionalOptions:{"":{name:"Chinese",epochs:["BEC","EC"],monthNumbers:function(t,e){if("string"==typeof t){var r=t.match($s);return r?r[0]:""}var n=this._validateYear(t),i=t.month(),a=""+this.toChineseMonth(n,i);return e&&a.length<2&&(a="0"+a),this.isIntercalaryMonth(n,i)&&(a+="i"),a},monthNames:function(t){if("string"==typeof t){var e=t.match(tl);return e?e[0]:""}var r=this._validateYear(t),n=t.month(),i=["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"][this.toChineseMonth(r,n)-1];return this.isIntercalaryMonth(r,n)&&(i="\u95f0"+i),i},monthNamesShort:function(t){if("string"==typeof t){var e=t.match(el);return e?e[0]:""}var r=this._validateYear(t),n=t.month(),i=["\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u5341\u4e00","\u5341\u4e8c"][this.toChineseMonth(r,n)-1];return this.isIntercalaryMonth(r,n)&&(i="\u95f0"+i),i},parseMonth:function(t,e){t=this._validateYear(t);var r,n=parseInt(e);if(isNaN(n))"\u95f0"===e[0]&&(r=!0,e=e.substring(1)),"\u6708"===e[e.length-1]&&(e=e.substring(0,e.length-1)),n=1+["\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u5341\u4e00","\u5341\u4e8c"].indexOf(e);else{var i=e[e.length-1];r="i"===i||"I"===i}return this.toMonthIndex(t,n,r)},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:!1}},_validateYear:function(t,e){if(t.year&&(t=t.year()),"number"!=typeof t||t<1888||t>2111)throw e.replace(/\{0\}/,this.local.name);return t},toMonthIndex:function(t,e,r){var n=this.intercalaryMonth(t);if(r&&e!==n||e<1||e>12)throw qs.local.invalidMonth.replace(/\{0\}/,this.local.name);return n?!r&&e<=n?e-1:e:e-1},toChineseMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);if(e<0||e>(r?12:11))throw qs.local.invalidMonth.replace(/\{0\}/,this.local.name);return r?e>13},isIntercalaryMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);return!!r&&r===e},leapYear:function(t){return 0!==this.intercalaryMonth(t)},weekOfYear:function(t,e,r){var n,i=this._validateYear(t,qs.local.invalidyear),a=nl[i-nl[0]],o=a>>9&4095,s=a>>5&15,l=31&a;(n=Js.newDate(o,s,l)).add(4-(n.dayOfWeek()||7),"d");var u=this.toJD(t,e,r)-n.toJD();return 1+Math.floor(u/7)},monthsInYear:function(t){return this.leapYear(t)?13:12},daysInMonth:function(t,e){t.year&&(e=t.month(),t=t.year()),t=this._validateYear(t);var r=rl[t-rl[0]];if(e>(r>>13?12:11))throw qs.local.invalidMonth.replace(/\{0\}/,this.local.name);return r&1<<12-e?30:29},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,a,r,qs.local.invalidDate);t=this._validateYear(n.year()),e=n.month(),r=n.day();var i=this.isIntercalaryMonth(t,e),a=this.toChineseMonth(t,e),o=function(t,e,r,n,i){var a,o,s;if("object"==typeof t)o=t,a=e||{};else{var l="number"==typeof t&&t>=1888&&t<=2111;if(!l)throw new Error("Lunar year outside range 1888-2111");var u="number"==typeof e&&e>=1&&e<=12;if(!u)throw new Error("Lunar month outside range 1 - 12");var c,h="number"==typeof r&&r>=1&&r<=30;if(!h)throw new Error("Lunar day outside range 1 - 30");"object"==typeof n?(c=!1,a=n):(c=!!n,a=i||{}),o={year:t,month:e,day:r,isIntercalary:c}}s=o.day-1;var f,p=rl[o.year-rl[0]],d=p>>13;f=d?o.month>d?o.month:o.isIntercalary?o.month:o.month-1:o.month-1;for(var g=0;g>9&4095,(m>>5&15)-1,(31&m)+s);return a.year=y.getFullYear(),a.month=1+y.getMonth(),a.day=y.getDate(),a}(t,a,r,i);return Js.toJD(o.year,o.month,o.day)},fromJD:function(t){var e=Js.fromJD(t),r=function(t,e,r,n){var i,a;if("object"==typeof t)i=t,a=e||{};else{var o="number"==typeof t&&t>=1888&&t<=2111;if(!o)throw new Error("Solar year outside range 1888-2111");var s="number"==typeof e&&e>=1&&e<=12;if(!s)throw new Error("Solar month outside range 1 - 12");var l="number"==typeof r&&r>=1&&r<=31;if(!l)throw new Error("Solar day outside range 1 - 31");i={year:t,month:e,day:r},a=n||{}}var u=nl[i.year-nl[0]],c=i.year<<9|i.month<<5|i.day;a.year=c>=u?i.year:i.year-1,u=nl[a.year-nl[0]];var h,f=new Date(u>>9&4095,(u>>5&15)-1,31&u),p=new Date(i.year,i.month-1,i.day);h=Math.round((p-f)/864e5);var d,g=rl[a.year-rl[0]];for(d=0;d<13;d++){var v=g&1<<12-d?30:29;if(h>13;!m||d=2&&n<=6},extraInfo:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return{century:ol[Math.floor((n.year()-1)/100)+1]||""}},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return t=n.year()+(n.year()<0?1:0),e=n.month(),(r=n.day())+(e>1?16:0)+(e>2?32*(e-2):0)+400*(t-1)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t+.5)-Math.floor(this.jdEpoch)-1;var e=Math.floor(t/400)+1;t-=400*(e-1),t+=t>15?16:0;var r=Math.floor(t/32)+1,n=t-32*(r-1)+1;return this.newDate(e<=0?e-1:e,r,n)}});var ol={20:"Fruitbat",21:"Anchovy"};qs.calendars.discworld=al;function sl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}sl.prototype=new qs.baseCalendar,Us(sl.prototype,{name:"Ethiopian",jdEpoch:1724220.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Ethiopian",epochs:["BEE","EE"],monthNames:["Meskerem","Tikemet","Hidar","Tahesas","Tir","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehase","Pagume"],monthNamesShort:["Mes","Tik","Hid","Tah","Tir","Yek","Meg","Mia","Gen","Sen","Ham","Neh","Pag"],dayNames:["Ehud","Segno","Maksegno","Irob","Hamus","Arb","Kidame"],dayNamesShort:["Ehu","Seg","Mak","Iro","Ham","Arb","Kid"],dayNamesMin:["Eh","Se","Ma","Ir","Ha","Ar","Ki"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);return(t=e.year()+(e.year()<0?1:0))%4==3||t%4==-1},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear||qs.regionalOptions[""].invalidYear),13},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(13===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return(t=n.year())<0&&t++,n.day()+30*(n.month()-1)+365*(t-1)+Math.floor(t/4)+this.jdEpoch-1},fromJD:function(t){var e=Math.floor(t)+.5-this.jdEpoch,r=Math.floor((e-Math.floor((e+366)/1461))/365)+1;r<=0&&r--,e=Math.floor(t)+.5-this.newDate(r,1,1).toJD();var n=Math.floor(e/30)+1,i=e-30*(n-1)+1;return this.newDate(r,n,i)}}),qs.calendars.ethiopian=sl;function ll(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function ul(t,e){return t-e*Math.floor(t/e)}ll.prototype=new qs.baseCalendar,Us(ll.prototype,{name:"Hebrew",jdEpoch:347995.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29,29],hasYearZero:!1,minMonth:1,firstMonth:7,minDay:1,regionalOptions:{"":{name:"Hebrew",epochs:["BAM","AM"],monthNames:["Nisan","Iyar","Sivan","Tammuz","Av","Elul","Tishrei","Cheshvan","Kislev","Tevet","Shevat","Adar","Adar II"],monthNamesShort:["Nis","Iya","Siv","Tam","Av","Elu","Tis","Che","Kis","Tev","She","Ada","Ad2"],dayNames:["Yom Rishon","Yom Sheni","Yom Shlishi","Yom Revi'i","Yom Chamishi","Yom Shishi","Yom Shabbat"],dayNamesShort:["Ris","She","Shl","Rev","Cha","Shi","Sha"],dayNamesMin:["Ri","She","Shl","Re","Ch","Shi","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);return this._leapYear(e.year())},_leapYear:function(t){return ul(7*(t=t<0?t+1:t)+1,19)<7},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear),this._leapYear(t.year?t.year():t)?13:12},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return t=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear).year(),this.toJD(-1===t?1:t+1,7,1)-this.toJD(t,7,1)},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,qs.local.invalidMonth),12===e&&this.leapYear(t)?30:8===e&&5===ul(this.daysInYear(t),10)?30:9===e&&3===ul(this.daysInYear(t),10)?29:this.daysPerMonth[e-1]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},extraInfo:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return{yearType:(this.leapYear(n)?"embolismic":"common")+" "+["deficient","regular","complete"][this.daysInYear(n)%10-3]}},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);t=n.year(),e=n.month(),r=n.day();var i=t<=0?t+1:t,a=this.jdEpoch+this._delay1(i)+this._delay2(i)+r+1;if(e<7){for(var o=7;o<=this.monthsInYear(t);o++)a+=this.daysInMonth(t,o);for(o=1;o=this.toJD(-1===e?1:e+1,7,1);)e++;for(var r=tthis.toJD(e,r,this.daysInMonth(e,r));)r++;var n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),qs.calendars.hebrew=ll;function cl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}cl.prototype=new qs.baseCalendar,Us(cl.prototype,{name:"Islamic",jdEpoch:1948439.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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\u012bs","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:!1}},leapYear:function(t){return(11*this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear).year()+14)%30<11},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return this.leapYear(t)?355:354},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return t=n.year(),e=n.month(),r=n.day(),t=t<=0?t+1:t,r+Math.ceil(29.5*(e-1))+354*(t-1)+Math.floor((3+11*t)/30)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t)+.5;var e=Math.floor((30*(t-this.jdEpoch)+10646)/10631);e=e<=0?e-1:e;var r=Math.min(12,Math.ceil((t-29-this.toJD(e,1,1))/29.5)+1),n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),qs.calendars.islamic=cl;function hl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}hl.prototype=new qs.baseCalendar,Us(hl.prototype,{name:"Julian",jdEpoch:1721423.5,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Julian",epochs:["BC","AD"],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:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);return(t=e.year()<0?e.year()+1:e.year())%4==0},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(4-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return t=n.year(),e=n.month(),r=n.day(),t<0&&t++,e<=2&&(t--,e+=12),Math.floor(365.25*(t+4716))+Math.floor(30.6001*(e+1))+r-1524.5},fromJD:function(t){var e=Math.floor(t+.5)+1524,r=Math.floor((e-122.1)/365.25),n=Math.floor(365.25*r),i=Math.floor((e-n)/30.6001),a=i-Math.floor(i<14?1:13),o=r-Math.floor(a>2?4716:4715),s=e-n-Math.floor(30.6001*i);return o<=0&&o--,this.newDate(o,a,s)}}),qs.calendars.julian=hl;function fl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function pl(t,e){return t-e*Math.floor(t/e)}function dl(t,e){return pl(t-1,e)+1}fl.prototype=new qs.baseCalendar,Us(fl.prototype,{name:"Mayan",jdEpoch:584282.5,hasYearZero:!0,minMonth:0,firstMonth:0,minDay:0,regionalOptions:{"":{name:"Mayan",epochs:["",""],monthNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],monthNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],dayNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesMin:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],digits:null,dateFormat:"YYYY.m.d",firstDay:0,isRTL:!1,haabMonths:["Pop","Uo","Zip","Zotz","Tzec","Xul","Yaxkin","Mol","Chen","Yax","Zac","Ceh","Mac","Kankin","Muan","Pax","Kayab","Cumku","Uayeb"],tzolkinMonths:["Imix","Ik","Akbal","Kan","Chicchan","Cimi","Manik","Lamat","Muluc","Oc","Chuen","Eb","Ben","Ix","Men","Cib","Caban","Etznab","Cauac","Ahau"]}},leapYear:function(t){return this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear),!1},formatYear:function(t){t=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear).year();var e=Math.floor(t/400);return t%=400,t+=t<0?400:0,e+"."+Math.floor(t/20)+"."+t%20},forYear:function(t){if((t=t.split(".")).length<3)throw"Invalid Mayan year";for(var e=0,r=0;r19||r>0&&n<0)throw"Invalid Mayan year";e=20*e+n}return e},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear),18},weekOfYear:function(t,e,r){return this._validate(t,e,r,qs.local.invalidDate),0},daysInYear:function(t){return this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear),360},daysInMonth:function(t,e){return this._validate(t,e,this.minDay,qs.local.invalidMonth),20},daysInWeek:function(){return 5},dayOfWeek:function(t,e,r){return this._validate(t,e,r,qs.local.invalidDate).day()},weekDay:function(t,e,r){return this._validate(t,e,r,qs.local.invalidDate),!0},extraInfo:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate).toJD(),i=this._toHaab(n),a=this._toTzolkin(n);return{haabMonthName:this.local.haabMonths[i[0]-1],haabMonth:i[0],haabDay:i[1],tzolkinDayName:this.local.tzolkinMonths[a[0]-1],tzolkinDay:a[0],tzolkinTrecena:a[1]}},_toHaab:function(t){var e=pl((t-=this.jdEpoch)+8+340,365);return[Math.floor(e/20)+1,pl(e,20)]},_toTzolkin:function(t){return[dl((t-=this.jdEpoch)+20,20),dl(t+4,13)]},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);return n.day()+20*n.month()+360*n.year()+this.jdEpoch},fromJD:function(t){t=Math.floor(t)+.5-this.jdEpoch;var e=Math.floor(t/360);t%=360,t+=t<0?360:0;var r=Math.floor(t/20),n=t%20;return this.newDate(e,r,n)}}),qs.calendars.mayan=fl;function vl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}vl.prototype=new qs.baseCalendar;var ml=qs.instance("gregorian");Us(vl.prototype,{name:"Nanakshahi",jdEpoch:2257673.5,daysPerMonth:[31,31,31,31,31,30,30,30,30,30,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Nanakshahi",epochs:["BN","AN"],monthNames:["Chet","Vaisakh","Jeth","Harh","Sawan","Bhadon","Assu","Katak","Maghar","Poh","Magh","Phagun"],monthNamesShort:["Che","Vai","Jet","Har","Saw","Bha","Ass","Kat","Mgr","Poh","Mgh","Pha"],dayNames:["Somvaar","Mangalvar","Budhvaar","Veervaar","Shukarvaar","Sanicharvaar","Etvaar"],dayNamesShort:["Som","Mangal","Budh","Veer","Shukar","Sanichar","Et"],dayNamesMin:["So","Ma","Bu","Ve","Sh","Sa","Et"],digits:null,dateFormat:"dd-mm-yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear||qs.regionalOptions[""].invalidYear);return ml.leapYear(e.year()+(e.year()<1?1:0)+1469)},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(1-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidMonth);(t=n.year())<0&&t++;for(var i=n.day(),a=1;a=this.toJD(e+1,1,1);)e++;for(var r=t-Math.floor(this.toJD(e,1,1)+.5)+1,n=1;r>this.daysInMonth(e,n);)r-=this.daysInMonth(e,n),n++;return this.newDate(e,n,r)}}),qs.calendars.nanakshahi=vl;function yl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}yl.prototype=new qs.baseCalendar,Us(yl.prototype,{name:"Nepali",jdEpoch:1700709.5,daysPerMonth:[31,31,32,32,31,30,30,29,30,29,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,daysPerYear:365,regionalOptions:{"":{name:"Nepali",epochs:["BBS","ABS"],monthNames:["Baisakh","Jestha","Ashadh","Shrawan","Bhadra","Ashwin","Kartik","Mangsir","Paush","Mangh","Falgun","Chaitra"],monthNamesShort:["Bai","Je","As","Shra","Bha","Ash","Kar","Mang","Pau","Ma","Fal","Chai"],dayNames:["Aaitabaar","Sombaar","Manglbaar","Budhabaar","Bihibaar","Shukrabaar","Shanibaar"],dayNamesShort:["Aaita","Som","Mangl","Budha","Bihi","Shukra","Shani"],dayNamesMin:["Aai","So","Man","Bu","Bi","Shu","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:1,isRTL:!1}},leapYear:function(t){return this.daysInYear(t)!==this.daysPerYear},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){if(t=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear).year(),void 0===this.NEPALI_CALENDAR_DATA[t])return this.daysPerYear;for(var e=0,r=this.minMonth;r<=12;r++)e+=this.NEPALI_CALENDAR_DATA[t][r];return e},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,qs.local.invalidMonth),void 0===this.NEPALI_CALENDAR_DATA[t]?this.daysPerMonth[e-1]:this.NEPALI_CALENDAR_DATA[t][e]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);t=n.year(),e=n.month(),r=n.day();var i=qs.instance(),a=0,o=e,s=t;this._createMissingCalendarData(t);var l=t-(o>9||9===o&&r>=this.NEPALI_CALENDAR_DATA[s][0]?56:57);for(9!==e&&(a=r,o--);9!==o;)o<=0&&(o=12,s--),a+=this.NEPALI_CALENDAR_DATA[s][o],o--;return 9===e?(a+=r-this.NEPALI_CALENDAR_DATA[s][0])<0&&(a+=i.daysInYear(l)):a+=this.NEPALI_CALENDAR_DATA[s][9]-this.NEPALI_CALENDAR_DATA[s][0],i.newDate(l,1,1).add(a,"d").toJD()},fromJD:function(t){var e=qs.instance().fromJD(t),r=e.year(),n=e.dayOfYear(),i=r+56;this._createMissingCalendarData(i);for(var a=9,o=this.NEPALI_CALENDAR_DATA[i][0],s=this.NEPALI_CALENDAR_DATA[i][a]-o+1;n>s;)++a>12&&(a=1,i++),s+=this.NEPALI_CALENDAR_DATA[i][a];var l=this.NEPALI_CALENDAR_DATA[i][a]-(s-n);return this.newDate(i,a,l)},_createMissingCalendarData:function(t){var e=this.daysPerMonth.slice(0);e.unshift(17);for(var r=t-1;r0?474:473))%2820+474+38)%2816<682},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-(n.dayOfWeek()+1)%7,"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);t=n.year(),e=n.month(),r=n.day();var i=t-(t>=0?474:473),a=474+bl(i,2820);return r+(e<=7?31*(e-1):30*(e-1)+6)+Math.floor((682*a-110)/2816)+365*(a-1)+1029983*Math.floor(i/2820)+this.jdEpoch-1},fromJD:function(t){var e=(t=Math.floor(t)+.5)-this.toJD(475,1,1),r=Math.floor(e/1029983),n=bl(e,1029983),i=2820;if(1029982!==n){var a=Math.floor(n/366),o=bl(n,366);i=Math.floor((2134*a+2816*o+2815)/1028522)+a+1}var s=i+2820*r+474;s=s<=0?s-1:s;var l=t-this.toJD(s,1,1)+1,u=l<=186?Math.ceil(l/31):Math.ceil((l-6)/30),c=t-this.toJD(s,u,1)+1;return this.newDate(s,u,c)}}),qs.calendars.persian=xl,qs.calendars.jalali=xl;var _l=qs.instance();function wl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}wl.prototype=new qs.baseCalendar,Us(wl.prototype,{name:"Taiwan",jdEpoch:2419402.5,yearsOffset:1911,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);t=this._t2gYear(e.year());return _l.leapYear(t)},weekOfYear:function(t,e,r){var n=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);t=this._t2gYear(n.year());return _l.weekOfYear(t,n.month(),n.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);t=this._t2gYear(n.year());return _l.toJD(t,n.month(),n.day())},fromJD:function(t){var e=_l.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)},_g2tYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)}}),qs.calendars.taiwan=wl;var Ml=qs.instance();function Al(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Al.prototype=new qs.baseCalendar,Us(Al.prototype,{name:"Thai",jdEpoch:1523098.5,yearsOffset:543,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);t=this._t2gYear(e.year());return Ml.leapYear(t)},weekOfYear:function(t,e,r){var n=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);t=this._t2gYear(n.year());return Ml.weekOfYear(t,n.month(),n.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,qs.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate);t=this._t2gYear(n.year());return Ml.toJD(t,n.month(),n.day())},fromJD:function(t){var e=Ml.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)},_g2tYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)}}),qs.calendars.thai=Al;function kl(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}kl.prototype=new qs.baseCalendar,Us(kl.prototype,{name:"UmmAlQura",hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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\u0101th\u0101\u2019","Yawm al-Arba\u2018\u0101\u2019","Yawm al-Kham\u012bs","Yawm al-Jum\u2018a","Yawm al-Sabt"],dayNamesMin:["Ah","Ith","Th","Ar","Kh","Ju","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!0}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,qs.local.invalidYear);return 355===this.daysInYear(e.year())},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){for(var e=0,r=1;r<=12;r++)e+=this.daysInMonth(t,r);return e},daysInMonth:function(t,e){for(var r=this._validate(t,e,this.minDay,qs.local.invalidMonth).toJD()-24e5+.5,n=0,i=0;ir)return Tl[n]-Tl[n-1];n++}return 30},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,qs.local.invalidDate),i=12*(n.year()-1)+n.month()-15292;return n.day()+Tl[i-1]-1+24e5-.5},fromJD:function(t){for(var e=t-24e5+.5,r=0,n=0;ne);n++)r++;var i=r+15292,a=Math.floor((i-1)/12),o=a+1,s=i-12*a,l=e-Tl[r-1]+1;return this.newDate(o,s,l)},isValid:function(t,e,r){var n=qs.baseCalendar.prototype.isValid.apply(this,arguments);return n&&(n=(t=null!=t.year?t.year:t)>=1276&&t<=1500),n},_validate:function(t,e,r,n){var i=qs.baseCalendar.prototype._validate.apply(this,arguments);if(i.year<1276||i.year>1500)throw n.replace(/\{0\}/,this.local.name);return i}}),qs.calendars.ummalqura=kl;var Tl=[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,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,68e3,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];Us(qs.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"}),qs.local=qs.regionalOptions[""],Us(qs.cdate.prototype,{formatDate:function(t,e){return"string"!=typeof t&&(e=t,t=""),this._calendar.formatDate(t||"",this,e)}}),Us(qs.baseCalendar.prototype,{UNIX_EPOCH:qs.instance().newDate(1970,1,1).toJD(),SECS_PER_DAY:86400,TICKS_EPOCH:qs.instance().jdEpoch,TICKS_PER_DAY:864e9,ATOM:"yyyy-mm-dd",COOKIE:"D, dd M yyyy",FULL:"DD, MM d, yyyy",ISO_8601:"yyyy-mm-dd",JULIAN:"J",RFC_822:"D, d M yy",RFC_850:"DD, dd-M-yy",RFC_1036:"D, d M yy",RFC_1123:"D, d M yyyy",RFC_2822:"D, d M yyyy",RSS:"D, d M yy",TICKS:"!",TIMESTAMP:"@",W3C:"yyyy-mm-dd",formatDate:function(t,e,r){if("string"!=typeof t&&(r=e,e=t,t=""),!e)return"";if(e.calendar()!==this)throw qs.local.invalidFormat||qs.regionalOptions[""].invalidFormat;t=t||this.local.dateFormat;for(var n,i,a,o,s=(r=r||{}).dayNamesShort||this.local.dayNamesShort,l=r.dayNames||this.local.dayNames,u=r.monthNumbers||this.local.monthNumbers,c=r.monthNamesShort||this.local.monthNamesShort,h=r.monthNames||this.local.monthNames,f=(r.calculateWeek||this.local.calculateWeek,function(e,r){for(var n=1;_+n1}),p=function(t,e,r,n){var i=""+e;if(f(t,n))for(;i.length1},y=function(t,r){var n=m(t,r),i=[2,3,n?4:2,n?4:2,10,11,20]["oyYJ@!".indexOf(t)+1],a=new RegExp("^-?\\d{1,"+i+"}"),o=e.substring(A).match(a);if(!o)throw(qs.local.missingNumberAt||qs.regionalOptions[""].missingNumberAt).replace(/\{0\}/,A);return A+=o[0].length,parseInt(o[0],10)},x=this,b=function(){if("function"==typeof s){m("m");var t=s.call(x,e.substring(A));return A+=t.length,t}return y("m")},_=function(t,r,n,i){for(var a=m(t,i)?n:r,o=0;o-1){f=1,p=d;for(var S=this.daysInMonth(h,f);p>S;S=this.daysInMonth(h,f))f++,p-=S}return c>-1?this.fromJD(c):this.newDate(h,f,p)},determineDate:function(t,e,r,n,i){r&&"object"!=typeof r&&(i=n,n=r,r=null),"string"!=typeof n&&(i=n,n="");var a=this;return e=e?e.newDate():null,t=null==t?e:"string"==typeof t?function(t){try{return a.parseDate(n,t,i)}catch(t){}for(var e=((t=t.toLowerCase()).match(/^c/)&&r?r.newDate():null)||a.today(),o=/([+-]?[0-9]+)\s*(d|w|m|y)?/g,s=o.exec(t);s;)e.add(parseInt(s[1],10),s[2]||"d"),s=o.exec(t);return e}(t):"number"==typeof t?isNaN(t)||t===1/0||t===-1/0?e:a.today().add(t,"d"):a.newDate(t)}});var Sl=qs,El=t.EPOCHJD,Cl=t.ONEDAY,Ll={valType:"enumerated",values:Object.keys(Sl.calendars),editType:"calc",dflt:"gregorian"},zl=function(t,e,r,n){var i={};return i[r]=Ll,ne.coerce(t,e,i,r,n)},Pl="##",Il={d:{0:"dd","-":"d"},e:{0:"d","-":"d"},a:{0:"D","-":"D"},A:{0:"DD","-":"DD"},j:{0:"oo","-":"o"},W:{0:"ww","-":"w"},m:{0:"mm","-":"m"},b:{0:"M","-":"M"},B:{0:"MM","-":"MM"},y:{0:"yy","-":"yy"},Y:{0:"yyyy","-":"yyyy"},U:Pl,w:Pl,c:{0:"D M d %X yyyy","-":"D M d %X yyyy"},x:{0:"mm/dd/yyyy","-":"mm/dd/yyyy"}};var Dl={};function Ol(t){var e=Dl[t];return e||(e=Dl[t]=Sl.instance(t))}function Rl(t){return ne.extendFlat({},Ll,{description:t})}function Fl(t){return"Sets the calendar system to use with `"+t+"` date data."}var Bl={xcalendar:Rl(Fl("x"))},Nl=ne.extendFlat({},Bl,{ycalendar:Rl(Fl("y"))}),jl=ne.extendFlat({},Nl,{zcalendar:Rl(Fl("z"))}),Vl=Rl(["Sets the calendar system to use for `range` and `tick0`","if this is a date axis. This does not set the calendar for","interpreting data on this axis, that's specified in the trace","or via the global `layout.calendar`"].join(" ")),Ul={moduleType:"component",name:"calendars",schema:{traces:{scatter:Nl,bar:Nl,box:Nl,heatmap:Nl,contour:Nl,histogram:Nl,histogram2d:Nl,histogram2dcontour:Nl,scatter3d:jl,surface:jl,mesh3d:jl,scattergl:Nl,ohlc:Bl,candlestick:Bl},layout:{calendar:Rl(["Sets the default calendar system to use for interpreting and","displaying dates throughout the plot."].join(" "))},subplots:{xaxis:{calendar:Vl},yaxis:{calendar:Vl},scene:{xaxis:{calendar:Vl},yaxis:{calendar:Vl},zaxis:{calendar:Vl}},polar:{radialaxis:{calendar:Vl}}},transforms:{filter:{valuecalendar:Rl(["Sets the calendar system to use for `value`, if it is a date."].join(" ")),targetcalendar:Rl(["Sets the calendar system to use for `target`, if it is an","array of dates. If `target` is a string (eg *x*) we use the","corresponding trace attribute (eg `xcalendar`) if it exists,","even if `targetcalendar` is provided."].join(" "))}}},layoutAttributes:Ll,handleDefaults:zl,handleTraceDefaults:function(t,e,r,n){for(var i=0;in?e=!0:r=10)return null;var n=1/0;var i=-1/0;var a=e.length;for(var o=0;o0&&(p=t.dxydi([],i-1,o,0,s),m.push(l[0]+p[0]/3),y.push(l[1]+p[1]/3),d=t.dxydi([],i-1,o,1,s),m.push(f[0]-d[0]/3),y.push(f[1]-d[1]/3)),m.push(f[0]),y.push(f[1]),l=f;else for(i=t.a2i(e),u=Math.floor(Math.max(0,Math.min(C-2,i))),c=i-u,b.length=C,b.crossLength=L,b.xy=function(e){return t.evalxy([],i,e)},b.dxy=function(e,r){return t.dxydj([],u,e,c,r)},a=0;a0&&(g=t.dxydj([],u,a-1,c,0),m.push(l[0]+g[0]/3),y.push(l[1]+g[1]/3),v=t.dxydj([],u,a-1,c,1),m.push(f[0]-v[0]/3),y.push(f[1]-v[1]/3)),m.push(f[0]),y.push(f[1]),l=f;return b.axisLetter=r,b.axis=x,b.crossAxis=A,b.value=e,b.constvar=n,b.index=h,b.x=m,b.y=y,b.smoothing=A.smoothing,b}function I(e){var i,a,o,s,l,u=[],c=[],h={};if(h.length=y.length,h.crossLength=M.length,"b"===r)for(o=Math.max(0,Math.min(L-2,e)),l=Math.min(1,Math.max(0,e-o)),h.xy=function(r){return t.evalxy([],r,e)},h.dxy=function(e,r){return t.dxydi([],e,o,r,l)},i=0;iy.length-1||b.push(hu(I(a),{color:x.gridcolor,width:x.gridwidth}));for(h=u;hy.length-1||d<0||d>y.length-1))for(g=y[o],v=y[d],i=0;iy[y.length-1]||_.push(hu(P(p),{color:x.minorgridcolor,width:x.minorgridwidth}));x.startline&&w.push(hu(I(0),{color:x.startlinecolor,width:x.startlinewidth})),x.endline&&w.push(hu(I(y.length-1),{color:x.endlinecolor,width:x.endlinewidth}))}else{for(s=5e-15,u=(l=[Math.floor((y[y.length-1]-x.tick0)/x.dtick*(1+s)),Math.ceil((y[0]-x.tick0)/x.dtick/(1+s))].sort(function(t,e){return t-e}))[0],c=l[1],h=u;h<=c;h++)f=x.tick0+x.dtick*h,b.push(hu(P(f),{color:x.gridcolor,width:x.gridwidth}));for(h=u-1;hy[y.length-1]||_.push(hu(P(p),{color:x.minorgridcolor,width:x.minorgridwidth}));x.startline&&w.push(hu(P(y[0]),{color:x.startlinecolor,width:x.startlinewidth})),x.endline&&w.push(hu(P(y[y.length-1]),{color:x.endlinecolor,width:x.endlinewidth}))}},pu=m.extendFlat,du=function(t,e){var r,n,i,a=e._labels=[],o=e._gridlines;for(r=0;re.length&&(t=t.slice(0,e.length)):t=[],n=0;ne.length&&(t[n]=t[n].slice(0,e.length)):t[n]=[],i=0;i0&&void 0!==(n=t[r][e-1])&&(a++,i+=n),e0&&void 0!==(n=t[r-1][e])&&(a++,i+=n),r0&&i0&&n1e-5);return ne.log("Smoother converged to",M,"after",A,"iterations"),t},xu=function(t,e){var n,i,a,o,s,l;function u(t){if(r(t))return+t}if(e){for(n=0,s=0;ss&&tu&&el||ec},a.c2p=function(t){return t},o.c2p=function(t){return t},t.setScale=function(){var e,r,s,l=t._x,u=t._y,c=function(t,e,r,n,i,a){var o,s,l,u,c,h,f,p,d,g,v=r[0].length,m=r.length,y=i?3*v-2:v,x=a?3*m-2:m;for(t=Au(t,x),e=Au(e,x),l=0;le[n-1]|or[i-1]))return[!1,!1];var l=t.a2i(a),u=t.b2j(o),c=t.evalxy([],l,u);if(s){var h,f,p,d,g=0,v=0,m=[];ae[n-1]?(h=n-2,f=1,g=(a-e[n-1])/(e[n-1]-e[n-2])):f=l-(h=Math.max(0,Math.min(n-2,Math.floor(l)))),or[i-1]?(p=i-2,d=1,v=(o-r[i-1])/(r[i-1]-r[i-2])):d=u-(p=Math.max(0,Math.min(i-2,Math.floor(u)))),g&&(t.dxydi(m,h,p,f,d),c[0]+=m[0]*g,c[1]+=m[1]*g),v&&(t.dxydj(m,h,p,f,d),c[0]+=m[0]*v,c[1]+=m[1]*v)}return c},t.c2p=function(t,e,r){return[e.c2p(t[0]),r.c2p(t[1])]},t.p2x=function(t,e,r){return[e.p2c(t[0]),r.p2c(t[1])]},t.dadi=function(t){var r=Math.max(0,Math.min(e.length-2,t));return e[r+1]-e[r]},t.dbdj=function(t){var e=Math.max(0,Math.min(r.length-2,t));return r[e+1]-r[e]},t.dxyda=function(e,r,n,i){var a=t.dxydi(null,e,r,n,i),o=t.dadi(e,n);return[a[0]/o,a[1]/o]},t.dxydb=function(e,r,n,i){var a=t.dxydj(null,e,r,n,i),o=t.dbdj(r,i);return[a[0]/o,a[1]/o]},t.dxyda_rough=function(e,r,n){var i=h*(n||.1),a=t.ab2xy(e+i,r,!0),o=t.ab2xy(e-i,r,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dxydb_rough=function(e,r,n){var i=f*(n||.1),a=t.ab2xy(e,r+i,!0),o=t.ab2xy(e,r-i,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dpdx=function(t){return t._m},t.dpdy=function(t){return t._m}},Cu=ne.isArrayOrTypedArray,Lu=function(t){return Cu(t[0])},zu=t.BADNUM,Pu=function(t,e,r,n,i,a){n=n||"x",i=i||"y",a=a||["z"];var o,s,l,u=t[n].slice(),c=t[i].slice(),h=t.text,f=Math.min(u.length,c.length),p=void 0!==h&&!Array.isArray(h[0]),d=t[n+"calendar"],g=t[i+"calendar"];for(o=0;oe.length&&(t=t.slice(0,e.length)):t=[],n=0;n90&&(p-=180,l=-l),{angle:p,flip:l,p:t.c2p(n,e,r),offsetMultplier:u}};function Fu(t,e,r){var n=t.selectAll(e+"."+r).data([0]);return n.enter().append(e).classed(r,!0),n}function Bu(t,e,r){var n=r[0],i=r[0].trace,a=e.xaxis,o=e.yaxis,s=i.aaxis,l=i.baxis,u=t._fullLayout,c=e.plot.selectAll(".carpetlayer"),h=u._clips,f=Fu(c,"g","carpet"+i.uid).classed("trace",!0),p=Fu(f,"g","minorlayer"),d=Fu(f,"g","majorlayer"),g=Fu(f,"g","boundarylayer"),v=Fu(f,"g","labellayer");f.style("opacity",i.opacity),Nu(a,o,d,s,"a",s._gridlines),Nu(a,o,d,l,"b",l._gridlines),Nu(a,o,p,s,"a",s._minorgridlines),Nu(a,o,p,l,"b",l._minorgridlines),Nu(a,o,g,s,"a-boundary",s._boundarylines),Nu(a,o,g,l,"b-boundary",l._boundarylines),function(t,e,r,n,i,a,o,s){var l,u,c,h;l=.5*(r.a[0]+r.a[r.a.length-1]),u=r.b[0],c=r.ab2xy(l,u,!0),h=r.dxyda_rough(l,u),void 0===o.angle&&ne.extendFlat(o,Ru(r,i,a,c,r.dxydb_rough(l,u)));qu(t,e,r,n,c,h,r.aaxis,i,a,o,"a-title"),l=r.a[0],u=.5*(r.b[0]+r.b[r.b.length-1]),c=r.ab2xy(l,u,!0),h=r.dxydb_rough(l,u),void 0===s.angle&&ne.extendFlat(s,Ru(r,i,a,c,r.dxyda_rough(l,u)));qu(t,e,r,n,c,h,r.baxis,i,a,s,"b-title")}(t,v,i,n,a,o,ju(t,a,o,i,n,v,s._labels,"a-label"),ju(t,a,o,i,n,v,l._labels,"b-label")),function(t,e,r,n,i){var a,o,s,l,u=r.select("#"+t._clipPathId);u.size()||(u=r.append("clipPath").classed("carpetclip",!0));var c=Fu(u,"path","carpetboundary"),h=e.clipsegments,f=[];for(l=0;l0?"start":"end","data-notex":1}).call(Sr.font,a.font).text(a.text).call(er.convertToTspans,t),p=Sr.bBox(this);f.attr("transform","translate("+s.p[0]+","+s.p[1]+") rotate("+s.angle+")translate("+a.axis.labelpadding*u+","+.3*p.height+")"),c=Math.max(c,p.width+a.axis.labelpadding)}),u.exit().remove(),h.maxExtent=c,h}var Vu=Qe.LINE_SPACING,Uu=(1-Qe.MID_SHIFT)/Vu+1;function qu(t,r,n,i,a,o,s,l,u,c,h){var f=[];s.title&&f.push(s.title);var p=r.selectAll("text."+h).data(f),d=c.maxExtent;p.enter().append("text").classed(h,!0),p.each(function(){var r=Ru(n,l,u,a,o);-1===["start","both"].indexOf(s.showticklabels)&&(d=0);var i=s.titlefont.size;d+=i+s.titleoffset;var h=(c.angle+(c.flip<0?180:0)-r.angle+450)%360,f=h>90&&h<270,p=e.select(this);p.text(s.title||"").call(er.convertToTspans,t),f&&(d=(-er.lineCount(p)+Uu)*Vu*i-d),p.attr("transform","translate("+r.p[0]+","+r.p[1]+") rotate("+r.angle+") translate(0,"+d+")").classed("user-select-none",!0).attr("text-anchor","middle").call(Sr.font,s.titlefont)}),p.exit().remove()}var Hu={};Hu.attributes=lu,Hu.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,lu,r,n)}e._clipPathId="clip"+e.uid+"carpet";var a=i("color",C.defaultLine);if(ne.coerceFont(i,"font"),i("carpet"),wu(t,e,n,i,a),e.a&&e.b){e.a.length<3&&(e.aaxis.smoothing=0),e.b.length<3&&(e.baxis.smoothing=0);var o=function(t,e,r){var n=[],i=r("x");i&&!Lu(i)&&n.push("x"),e._cheater=!i;var a=r("y");if(a&&!Lu(a)&&n.push("y"),i||a)return n.length&&Pu(e,e.aaxis,e.baxis,"a","b",n),!0}(0,e,i);Eu(e),e._cheater&&i("cheaterslope"),o||(e.visible=!1)}else e.visible=!1},Hu.plot=function(t,e,r){for(var n=0;n=0;i--)a[c-i]=t[h][i],o[c-i]=e[h][i];for(s.push({x:a,y:o,bicubic:l}),i=h,a=[],o=[];i>=0;i--)a[h-i]=t[i][0],o[h-i]=e[i][0];return s.push({x:a,y:o,bicubic:u}),s}(e.xctrl,e.yctrl,a,o),u.x=r,u.y=c,u.a=s,u.b=l,[u]},Hu.animatable=!0,Hu.moduleType="trace",Hu.name="carpet",Hu.basePlotModule=ua,Hu.categories=["cartesian","carpet","carpetAxis","notLegendIsolatable"],Hu.meta={};var Gu=Hu,Wu={exports:{}};!function(t,e){"object"==typeof Wu.exports?e(Wu.exports):e(t.topojson=t.topojson||{})}(this,function(t){"use strict";var e=function(t){return t},r=function(t){if(null==(r=t.transform))return e;var r,n,i,a=r.scale[0],o=r.scale[1],s=r.translate[0],l=r.translate[1];return function(t,e){return e||(n=i=0),t[0]=(n+=t[0])*a+s,t[1]=(i+=t[1])*o+l,t}},n=function(t){var e=t.bbox;function n(t){l[0]=t[0],l[1]=t[1],s(l),l[0]h&&(h=l[0]),l[1]f&&(f=l[1])}function i(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(i);break;case"Point":n(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(n)}}if(!e){var a,o,s=r(t),l=new Array(2),u=1/0,c=u,h=-u,f=-u;for(o in t.arcs.forEach(function(t){for(var e=-1,r=t.length;++eh&&(h=l[0]),l[1]f&&(f=l[1])}),t.objects)i(t.objects[o]);e=t.bbox=[u,c,h,f]}return e},i=function(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r};function a(t,e){var r=e.id,n=e.bbox,i=null==e.properties?{}:e.properties,a=o(t,e);return null==r&&null==n?{type:"Feature",properties:i,geometry:a}:null==n?{type:"Feature",id:r,properties:i,geometry:a}:{type:"Feature",id:r,bbox:n,properties:i,geometry:a}}function o(t,e){var n=r(t),a=t.arcs;function o(t,e){e.length&&e.pop();for(var r=a[t<0?~t:t],o=0,s=r.length;o1)n=function(t,e,r){var n,i=[],a=[];function o(t){var e=t<0?~t:t;(a[e]||(a[e]=[])).push({i:t,g:n})}function s(t){t.forEach(o)}function l(t){t.forEach(s)}return function t(e){switch(n=e,e.type){case"GeometryCollection":e.geometries.forEach(t);break;case"LineString":s(e.arcs);break;case"MultiLineString":case"Polygon":l(e.arcs);break;case"MultiPolygon":e.arcs.forEach(l)}}(e),a.forEach(null==r?function(t){i.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&i.push(t[0].i)}),i}(0,e,r);else for(i=0,n=new Array(a=t.arcs.length);i1)for(var a,o,u=1,c=l(i[0]);uc&&(o=i[0],i[0]=i[u],i[u]=o,c=a);return i})}}var c=function(t,e){for(var r=0,n=t.length;r>>1;t[i]=2))throw new Error("n must be \u22652");if(t.transform)throw new Error("already quantized");var r,i=n(t),a=i[0],o=(i[2]-a)/(e-1)||1,s=i[1],l=(i[3]-s)/(e-1)||1;function u(t){t[0]=Math.round((t[0]-a)/o),t[1]=Math.round((t[1]-s)/l)}function c(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(c);break;case"Point":u(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(u)}}for(r in t.arcs.forEach(function(t){for(var e,r,n,i=1,u=1,c=t.length,h=t[0],f=h[0]=Math.round((h[0]-a)/o),p=h[1]=Math.round((h[1]-s)/l);i0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,l=i.end,u=a.start,c=a.end;r&&r.checkIntersection(i,a);var h=e.linesIntersect(o,l,u,c);if(!1===h){if(!e.pointsCollinear(o,l,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(l,u))return!1;var f=e.pointsSame(o,u),p=e.pointsSame(l,c);if(f&&p)return n;var d=!f&&e.pointBetween(o,u,c),g=!p&&e.pointBetween(l,u,c);if(f)return g?s(n,l):s(t,c),n;d&&(p||(g?s(n,l):s(t,c)),s(n,o))}else 0===h.alongA&&(-1===h.alongB?s(t,u):0===h.alongB?s(t,h.pt):1===h.alongB&&s(t,c)),0===h.alongB&&(-1===h.alongA?s(n,o):0===h.alongA?s(n,h.pt):1===h.alongA&&s(n,l));return!1}for(var c=[];!i.isEmpty();){var h=i.getHead();if(r&&r.vert(h.pt[0]),h.isStart){r&&r.segmentNew(h.seg,h.primary);var f=l(h),p=f.before?f.before.ev:null,d=f.after?f.after.ev:null;function g(){if(p){var t=u(h,p);if(t)return t}return!!d&&u(h,d)}r&&r.tempStatus(h.seg,!!p&&p.seg,!!d&&d.seg);var v,m,y=g();if(y)t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below)&&(y.seg.myFill.above=!y.seg.myFill.above):y.seg.otherFill=h.seg.myFill,r&&r.segmentUpdate(y.seg),h.other.remove(),h.remove();if(i.getHead()!==h){r&&r.rewind(h.seg);continue}t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below,h.seg.myFill.below=d?d.seg.myFill.above:n,h.seg.myFill.above=m?!h.seg.myFill.below:h.seg.myFill.below):null===h.seg.otherFill&&(v=d?h.primary===d.primary?d.seg.otherFill.above:d.seg.myFill.above:h.primary?a:n,h.seg.otherFill={above:v,below:v}),r&&r.status(h.seg,!!p&&p.seg,!!d&&d.seg),h.other.status=f.insert(tc.node({ev:h}))}else{var x=h.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&u(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!h.primary){var b=h.seg.myFill;h.seg.myFill=h.seg.otherFill,h.seg.otherFill=b}c.push(h.seg)}i.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,i,a,s=t[t.length-1],l=0;l=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-i>t&&(a-u)*(i-c)/(o-c)+u-n>t&&(s=!s),a=u,o=c}return s}};return e}();function lc(t,e,r){var n=ic.segments(t),i=ic.segments(e),a=r(ic.combine(n,i));return ic.polygon(a)}ic={buildLog:function(t){return!0===t?oc=Qu():!1===t&&(oc=!1),!1!==oc&&oc.list},epsilon:function(t){return sc.epsilon(t)},segments:function(t){var e=ec(!0,sc,oc);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:ec(!1,sc,oc).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:ac.union(t.combined,oc),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:ac.intersect(t.combined,oc),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:ac.difference(t.combined,oc),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:ac.differenceRev(t.combined,oc),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:ac.xor(t.combined,oc),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:rc(t.segments,sc,oc),inverted:t.inverted}},polygonFromGeoJSON:function(t){return $u.toPolygon(ic,t)},polygonToGeoJSON:function(t){return $u.fromPolygon(ic,sc,t)},union:function(t,e){return lc(t,e,ic.selectUnion)},intersect:function(t,e){return lc(t,e,ic.selectIntersect)},difference:function(t,e){return lc(t,e,ic.selectDifference)},differenceRev:function(t,e){return lc(t,e,ic.selectDifferenceRev)},xor:function(t,e){return lc(t,e,ic.selectXor)}},"object"==typeof window&&(window.PolyBool=ic);var uc=ic,cc={},hc=Vt.dot,fc=t.BADNUM,pc=cc={};pc.tester=function(t){if(Array.isArray(t[0][0]))return pc.multitester(t);var e,r=t.slice(),n=r[0][0],i=n,a=r[0][1],o=a;for(r.push(r[0]),e=1;ei||l===fc||lo||e&&s(t))}:function(t,e){var s=t[0],l=t[1];if(s===fc||si||l===fc||lo)return!1;var u,c,h,f,p,d=r.length,g=r[0][0],v=r[0][1],m=0;for(u=1;uMath.max(c,g)||l>Math.max(h,v)))if(lu||Math.abs(hc(a,h))>n)return!0;return!1};pc.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var o=r.length,s=n;r.splice(i+1);for(var l=s+1;l1&&a(t.pop());return{addPt:a,raw:t,filtered:r}};var gc=Ya.makeEventData,vc=cc.filter,mc=cc.tester,yc=cc.multitester,xc=Te.MINSELECT;function bc(t){return t._id}var _c=function(t,e,r,n,i){var a,o,s,l,u=n.gd,c=u._fullLayout,h=c._zoomlayer,f=n.element.getBoundingClientRect(),p=n.plotinfo,d=p.xaxis._offset,g=p.yaxis._offset,v=e-f.left,m=r-f.top,y=v,x=m,b="M"+v+","+m,_=n.xaxes[0]._length,w=n.yaxes[0]._length,M=n.xaxes.map(bc),A=n.yaxes.map(bc),k=n.xaxes.concat(n.yaxes),T=t.altKey;(t.shiftKey||t.altKey)&&p.selection&&p.selection.polygons&&!n.polygons?(n.polygons=p.selection.polygons,n.mergedPolygons=p.selection.mergedPolygons):(!t.shiftKey&&!t.altKey||(t.shiftKey||t.altKey)&&!p.selection)&&(p.selection={},p.selection.polygons=n.polygons=[],p.selection.mergedPolygons=n.mergedPolygons=[]),"lasso"===i&&(a=vc([[v,m]],Te.BENDPX));var S=h.selectAll("path.select-outline-"+p.id).data([1,2]);S.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+p.id}).attr("transform","translate("+d+", "+g+")").attr("d",b+"Z");var E,C,L,z,P,I,D=h.append("path").attr("class","zoombox-corners").style({fill:Oe.background,stroke:Oe.defaultLine,"stroke-width":1}).attr("transform","translate("+d+", "+g+")").attr("d","M0,0Z"),O=[],R=c._uid+Te.SELECTID,F=[];for(E=0;En^p>n&&r<(f-u)*(n-c)/(p-c)+u&&(i=!i)}return i}(t[0],r))return t.push(e),!0})||t.push([e])}),a=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},u={Point:o,MultiPoint:o,LineString:s,MultiLineString:s,Polygon:l,MultiPolygon:l,Sphere:l};function c(){}var h=1e-6,f=h*h,p=Math.PI,d=p/2,g=(Math.sqrt(p),p/180),v=180/p;function m(t){return t>1?d:t<-1?-d:Math.asin(t)}function y(t){return t>1?0:t<-1?p:Math.acos(t)}var x=t.geo.projection,b=t.geo.projectionMutator;function _(t,e){var r=(2+d)*Math.sin(e);e/=2;for(var n=0,i=1/0;n<10&&Math.abs(i)>h;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(p*(4+p))*t*(1+Math.cos(e)),2*Math.sqrt(p/(4+p))*Math.sin(e)]}t.geo.interrupt=function(e){var r,n=[[[[-p,0],[0,d],[p,0]]],[[[-p,0],[0,-d],[p,0]]]];function i(t,r){for(var i=r<0?-1:1,a=n[+(r<0)],o=0,s=a.length-1;oa[o][2][0];++o);var l=e(t-a[o][1][0],r);return l[0]+=e(a[o][1][0],i*r>i*a[o][0][1]?a[o][0][1]:r)[0],l}e.invert&&(i.invert=function(t,a){for(var o=r[+(a<0)],s=n[+(a<0)],u=0,c=o.length;u=0;--i){var o=n[1][i],l=180*o[0][0]/p,u=180*o[0][1]/p,c=180*o[1][1]/p,h=180*o[2][0]/p,f=180*o[2][1]/p;r.push(s([[h-e,f-e],[h-e,c+e],[l+e,c+e],[l+e,u-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}(),l)},i},a.lobes=function(t){return arguments.length?(n=t.map(function(t){return t.map(function(t){return[[t[0][0]*p/180,t[0][1]*p/180],[t[1][0]*p/180,t[1][1]*p/180],[t[2][0]*p/180,t[2][1]*p/180]]})}),r=n.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})}),a):n.map(function(t){return t.map(function(t){return[[180*t[0][0]/p,180*t[0][1]/p],[180*t[1][0]/p,180*t[1][1]/p],[180*t[2][0]/p,180*t[2][1]/p]]})})},a},_.invert=function(t,e){var r=.5*e*Math.sqrt((4+p)/p),n=m(r),i=Math.cos(n);return[t/(2/Math.sqrt(p*(4+p))*(1+i)),m((n+r*(i+2))/(2+d))]},(t.geo.eckert4=function(){return x(_)}).raw=_;var w=t.geo.azimuthalEqualArea.raw;function M(t,e){if(arguments.length<2&&(e=t),1===e)return w;if(e===1/0)return A;function r(r,n){var i=w(r/e,n);return i[0]*=t,i}return r.invert=function(r,n){var i=w.invert(r/t,n);return i[0]*=e,i},r}function A(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function k(t,e){return[3*t/(2*p)*Math.sqrt(p*p/3-e*e),e]}function T(t,e){return[t,1.25*Math.log(Math.tan(p/4+.4*e))]}function S(t){return function(e){var r,n=t*Math.sin(e),i=30;do{e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e))}while(Math.abs(r)>h&&--i>0);return e/2}}A.invert=function(t,e){var r=2*m(e/2);return[t*Math.cos(r/2)/Math.cos(r),r]},(t.geo.hammer=function(){var t=2,e=b(M),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}).raw=M,k.invert=function(t,e){return[2/3*p*t/Math.sqrt(p*p/3-e*e),e]},(t.geo.kavrayskiy7=function(){return x(k)}).raw=k,T.invert=function(t,e){return[t,2.5*Math.atan(Math.exp(.8*e))-.625*p]},(t.geo.miller=function(){return x(T)}).raw=T,S(p);var E=function(t,e,r){var n=S(r);function i(r,i){return[t*r*Math.cos(i=n(i)),e*Math.sin(i)]}return i.invert=function(n,i){var a=m(i/e);return[n/(t*Math.cos(a)),m((2*a+Math.sin(2*a))/r)]},i}(Math.SQRT2/d,Math.SQRT2,p);function C(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(n*(.003971*r-.001529*n)-.013791)),e*(1.007226+r*(.015085+n*(.028874*r-.044475-.005916*n)))]}(t.geo.mollweide=function(){return x(E)}).raw=E,C.invert=function(t,e){var r,n=e,i=25;do{var a=n*n,o=a*a;n-=r=(n*(1.007226+a*(.015085+o*(.028874*a-.044475-.005916*o)))-e)/(1.007226+a*(.045255+o*(.259866*a-.311325-.005916*11*o)))}while(Math.abs(r)>h&&--i>0);return[t/(.8707+(a=n*n)*(a*(a*a*a*(.003971-.001529*a)-.013791)-.131979)),n]},(t.geo.naturalEarth=function(){return x(C)}).raw=C;var L=[[.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]];function z(t,e){var r,n=Math.min(18,36*Math.abs(e)/p),i=Math.floor(n),a=n-i,o=(r=L[i])[0],s=r[1],l=(r=L[++i])[0],u=r[1],c=(r=L[Math.min(19,++i)])[0],h=r[1];return[t*(l+a*(c-o)/2+a*a*(c-2*l+o)/2),(e>0?d:-d)*(u+a*(h-s)/2+a*a*(h-2*u+s)/2)]}function P(t,e){return[t*Math.cos(e),e]}function I(t,e){var r,n=Math.cos(e),i=(r=y(n*Math.cos(t/=2)))?r/Math.sin(r):1;return[2*n*Math.sin(t)*i,Math.sin(e)*i]}function D(t,e){var r=I(t,e);return[(r[0]+t/d)/2,(r[1]+e)/2]}L.forEach(function(t){t[1]*=1.0144}),z.invert=function(t,e){var r=e/d,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=L[a][1],s=L[a+1][1],l=L[Math.min(19,a+2)][1],u=l-o,c=l-2*s+o,h=2*(Math.abs(r)-s)/u,p=c/u,m=h*(1-p*h*(1-2*p*h));if(m>=0||1===a){n=(e>=0?5:-5)*(m+i);var y,x=50;do{m=(i=Math.min(18,Math.abs(n)/5))-(a=Math.floor(i)),o=L[a][1],s=L[a+1][1],l=L[Math.min(19,a+2)][1],n-=(y=(e>=0?d:-d)*(s+m*(l-o)/2+m*m*(l-2*s+o)/2)-e)*v}while(Math.abs(y)>f&&--x>0);break}}while(--a>=0);var b=L[a][0],_=L[a+1][0],w=L[Math.min(19,a+2)][0];return[t/(_+m*(w-b)/2+m*m*(w-2*_+b)/2),n*g]},(t.geo.robinson=function(){return x(z)}).raw=z,P.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return x(P)}).raw=P,I.invert=function(t,e){if(!(t*t+4*e*e>p*p+h)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),l=Math.cos(r/2),u=Math.sin(n),c=Math.cos(n),f=Math.sin(2*n),d=u*u,g=c*c,v=s*s,m=1-g*l*l,x=m?y(c*l)*Math.sqrt(a=1/m):a=0,b=2*x*c*s-t,_=x*u-e,w=a*(g*v+x*c*l*d),M=a*(.5*o*f-2*x*u*s),A=.25*a*(f*s-x*u*g*o),k=a*(d*l+x*v*c),T=M*A-k*w;if(!T)break;var S=(_*M-b*k)/T,E=(b*A-_*w)/T;r-=S,n-=E}while((Math.abs(S)>h||Math.abs(E)>h)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return x(I)}).raw=I,D.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),l=Math.sin(2*n),u=s*s,c=o*o,f=Math.sin(r),p=Math.cos(r/2),g=Math.sin(r/2),v=g*g,m=1-c*p*p,x=m?y(o*p)*Math.sqrt(a=1/m):a=0,b=.5*(2*x*o*g+r/d)-t,_=.5*(x*s+n)-e,w=.5*a*(c*v+x*o*p*u)+.5/d,M=a*(f*l/4-x*s*g),A=.125*a*(l*g-x*s*c*f),k=.5*a*(u*p+x*v*o)+.5,T=M*A-k*w,S=(_*M-b*k)/T,E=(b*A-_*w)/T;r-=S,n-=E}while((Math.abs(S)>h||Math.abs(E)>h)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return x(D)}).raw=D},kc=Math.PI/180,Tc=180/Math.PI,Sc={cursor:"pointer"},Ec={cursor:"auto"};var Cc=function(t,e){var r=t.projection;return(e._isScoped?Pc:e._isClipped?Dc:Ic)(t,r)};function Lc(t,r){return e.behavior.zoom().translate(r.translate()).scale(r.scale())}function zc(t,e,r){var n=t.id,i=t.graphDiv,a=i.layout[n],o=i._fullLayout[n],s={};function l(t,e){var r=ne.nestedProperty(o,t);r.get()!==e&&(r.set(e),ne.nestedProperty(a,t).set(e),s[n+"."+t]=e)}r(l),l("projection.scale",e.scale()/t.fitScale),i.emit("plotly_relayout",s)}function Pc(t,r){var n=Lc(0,r);function i(e){var n=r.invert(t.midPt);e("center.lon",n[0]),e("center.lat",n[1])}return n.on("zoomstart",function(){e.select(this).style(Sc)}).on("zoom",function(){r.scale(e.event.scale).translate(e.event.translate),t.render()}).on("zoomend",function(){e.select(this).style(Ec),zc(t,r,i)}),n}function Ic(t,r){var n,i,a,o,s,l,u,c,h=Lc(0,r),f=2;function p(t){return r.invert(t)}function d(e){var n=r.rotate(),i=r.invert(t.midPt);e("projection.rotation.lon",-n[0]),e("center.lon",i[0]),e("center.lat",i[1])}return h.on("zoomstart",function(){e.select(this).style(Sc),n=e.mouse(this),i=r.rotate(),a=r.translate(),o=i,s=p(n)}).on("zoom",function(){if(l=e.mouse(this),g=r(p(d=n)),Math.abs(g[0]-d[0])>f||Math.abs(g[1]-d[1])>f)return h.scale(r.scale()),void h.translate(r.translate());var d,g;r.scale(e.event.scale),r.translate([a[0],e.event.translate[1]]),s?p(l)&&(c=p(l),u=[o[0]+(c[0]-s[0]),i[1],i[2]],r.rotate(u),o=u):s=p(n=l),t.render()}).on("zoomend",function(){e.select(this).style(Ec),zc(t,r,d)}),h}function Dc(t,r){var n,i={r:r.rotate(),k:r.scale()},a=Lc(0,r),o=function(t){var r=0,n=arguments.length,i=[];for(;++rp?(a=(c>0?90:-90)-f,i=0):(a=Math.asin(c/p)*Tc-f,i=Math.sqrt(p*p-c*c));var d=180-a-2*f,g=(Math.atan2(h,u)-Math.atan2(l,i))*Tc,v=(Math.atan2(h,u)-Math.atan2(l,-i))*Tc,m=Rc(r[0],r[1],a,g),y=Rc(r[0],r[1],d,v);return m<=y?[a,g,r[2]]:[d,v,r[2]]}(y,n,_);isFinite(A[0])&&isFinite(A[1])&&isFinite(A[2])||(A=_),r.rotate(A),_=A}}else n=Oc(r,x=g);o.of(this,arguments)({type:"zoom"})}),y=o.of(this,arguments),s++||y({type:"zoomstart"})}).on("zoomend",function(){var n;e.select(this).style(Ec),l.call(a,"zoom",null),n=o.of(this,arguments),--s||n({type:"zoomend"}),zc(t,r,u)}).on("zoom.redraw",function(){t.render()}),e.rebind(a,o,"on")}function Oc(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&function(t){var e=t[0]*kc,r=t[1]*kc,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}(r)}function Rc(t,e,r,n){var i=Fc(r-t),a=Fc(n-e);return Math.sqrt(i*i+a*a)}function Fc(t){return(t%360+540)%360-180}function Bc(t,e,r){var n=r*kc,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function Nc(t,e){for(var r=0,n=0,i=t.length;ni*Math.PI/180}return!1},n.getPath=function(){return e.geo.path().projection(n)},n.getBounds=function(t){return n.getPath().bounds(t)},n.fitExtent=function(t,e){var r=t[1][0]-t[0][0],i=t[1][1]-t[0][1],a=n.clipExtent&&n.clipExtent();n.scale(150).translate([0,0]),a&&n.clipExtent(null);var o=n.getBounds(e),s=Math.min(r/(o[1][0]-o[0][0]),i/(o[1][1]-o[0][1])),l=+t[0][0]+(r-s*(o[1][0]+o[0][0]))/2,u=+t[0][1]+(i-s*(o[1][1]+o[0][1]))/2;return a&&n.clipExtent(a),n.scale(150*s).translate([l,u])},n.precision(Yu.precision),i&&n.clipAngle(i-Yu.clipPad);return n}(r);l.center([s.lon-o.lon,s.lat-o.lat]).rotate([-o.lon,-o.lat,o.roll]).parallels(a.parallels);var u=[[n.l+n.w*i.x[0],n.t+n.h*(1-i.y[1])],[n.l+n.w*i.x[1],n.t+n.h*(1-i.y[0])]],c=r.lonaxis,h=r.lataxis,f=function(t,e){var r=Yu.clipPad,n=t[0]+r,i=t[1]-r,a=e[0]+r,o=e[1]-r;n>0&&i<0&&(i+=360);var s=(i-n)/4;return{type:"Polygon",coordinates:[[[n,a],[n,o],[n+s,o],[n+2*s,o],[n+3*s,o],[i,o],[i,a],[i-s,a],[i-2*s,a],[i-3*s,a],[n,a]]]}}(c.range,h.range);l.fitExtent(u,f);var p=this.bounds=l.getBounds(f),d=this.fitScale=l.scale(),g=l.translate();if(!isFinite(p[0][0])||!isFinite(p[0][1])||!isFinite(p[1][0])||!isFinite(p[1][1])||isNaN(g[0])||isNaN(g[0])){for(var v=this.graphDiv,m=["projection.rotation","center","lonaxis.range","lataxis.range"],y="Invalid geo settings, relayout'ing to default view.",x={},b=0;b0&&b<0&&(b+=360);var _,w,M,A=(x+b)/2;if(!s){var k=l?a.projRotate:[A,0,0];_=r("projection.rotation.lon",k[0]),r("projection.rotation.lat",k[1]),r("projection.rotation.roll",k[2]),r("showcoastlines",!l)&&(r("coastlinecolor"),r("coastlinewidth")),r("showocean")&&r("oceancolor")}(s?(w=-96.6,M=38.7):(w=l?A:_,M=(y[0]+y[1])/2),r("center.lon",w),r("center.lat",M),u)&&r("projection.parallels",a.projParallels||[0,60]);r("projection.scale"),r("showland")&&r("landcolor"),r("showlakes")&&r("lakecolor"),r("showrivers")&&(r("rivercolor"),r("riverwidth")),r("showcountries",l&&"usa"!==i)&&(r("countrycolor"),r("countrywidth")),("usa"===i||"north america"===i&&50===n)&&(r("showsubunits",!0),r("subunitcolor"),r("subunitwidth")),l||r("showframe",!0)&&(r("framecolor"),r("framewidth")),r("bgcolor")}var $c={},th=sa.getSubplotCalcData,eh=ne.counterRegex,rh="geo";$c.name=rh,$c.attr=rh,$c.idRoot=rh,$c.idRegex=$c.attrRegex=eh(rh),$c.attributes={geo:{valType:"subplotid",dflt:"geo",editType:"calc"}},$c.layoutAttributes=Xc,$c.supplyLayoutDefaults=function(t,e,r){Jc(t,e,0,{type:"geo",attributes:Xc,handleDefaults:Qc,partition:"y"})},$c.plot=function(t){var e=t._fullLayout,r=t.calcdata,n=e._subplots.geo;void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var i=0;i0&&t[e+1][0]<0)return e;return null}switch(e="RUS"===s||"FJI"===s?function(t){var e;if(null===u(t))e=t;else for(e=new Array(t.length),i=0;ie?r[n++]=[t[i][0]+360,t[i][1]]:i===e?(r[n++]=t[i],r[n++]=[t[i][0],-90]):r[n++]=t[i];var a=cc.tester(r);a.pts.pop(),l.push(a)}:function(t){l.push(cc.tester(t))},a.type){case"MultiPolygon":for(r=0;ra&&(e.z=s.slice(0,a)),i("locationmode"),i("text"),i("marker.line.color"),i("marker.line.width"),i("marker.opacity"),Ye(t,e,n,i,{prefix:"",cLetter:"z"}),ne.coerceSelectionMarkerOpacity(e,i)):e.visible=!1}else e.visible=!1},Th.colorbar=kh,Th.calc=function(t,e){for(var n=e.locations.length,i=new Array(n),a=0;a")}(t,l,n,u.mockAxis),[t]},Th.eventData=function(t,e){return t.location=e.location,t.z=e.z,t},Th.selectPoints=function(t,e){var r,n,i,a,o,s=t.cd,l=t.xaxis,u=t.yaxis,c=[];if(!1===e)for(r=0;r=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}},Ch=m.extendFlat,Lh=Ch({},{z:{valType:"data_array",editType:"calc"},x:Ch({},Zr.x,{impliedEdits:{xtype:"array"}}),x0:Ch({},Zr.x0,{impliedEdits:{xtype:"scaled"}}),dx:Ch({},Zr.dx,{impliedEdits:{xtype:"scaled"}}),y:Ch({},Zr.y,{impliedEdits:{ytype:"array"}}),y0:Ch({},Zr.y0,{impliedEdits:{ytype:"scaled"}}),dy:Ch({},Zr.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,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",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,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"}},Pe,{autocolorscale:Ch({},Pe.autocolorscale,{dflt:!1})},{colorbar:ze}),zh=Ae.dash,Ph=m.extendFlat,Ih=Eh.COMPARISON_OPS2,Dh=Eh.INTERVAL_OPS,Oh=Zr.line,Rh=Ph({z:Lh.z,x:Lh.x,x0:Lh.x0,dx:Lh.dx,y:Lh.y,y0:Lh.y0,dy:Lh.dy,text:Lh.text,transpose:Lh.transpose,xtype:Lh.xtype,ytype:Lh.ytype,zhoverformat:Lh.zhoverformat,connectgaps:Lh.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},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":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:T({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(Ih).concat(Dh),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:Ph({},Oh.color,{editType:"style+colorbars"}),width:Ph({},Oh.width,{editType:"style+colorbars"}),dash:zh,smoothing:Ph({},Oh.smoothing,{}),editType:"plot"}},Pe,{autocolorscale:Ph({},Pe.autocolorscale,{dflt:!1}),zmin:Ph({},Pe.zmin,{editType:"calc"}),zmax:Ph({},Pe.zmax,{editType:"calc"})},{colorbar:ze}),Fh=ne.extendFlat,Bh=function(t){var e=t.contours;if(t.autocontour){var r=Nh(t.zmin,t.zmax,t.ncontours);e.size=r.dtick,e.start=ri.tickFirst(r),r.range.reverse(),e.end=ri.tickFirst(r),e.start===t.zmin&&(e.start+=e.size),e.end===t.zmax&&(e.end-=e.size),e.start>e.end&&(e.start=e.end=(e.start+e.end)/2),t._input.contours||(t._input.contours={}),Fh(t._input.contours,{start:e.start,end:e.end,size:e.size}),t._input.autocontour=!0}else if("constraint"!==e.type){var n,i=e.start,a=e.end,o=t._input.contours;if(i>a&&(e.start=o.start=a,a=e.end=o.end=i,i=e.start),!(e.size>0))n=i===a?1:Nh(i,a,t.ncontours).dtick,o.size=e.size=n}};function Nh(t,e,r){var n={type:"linear",range:[t,e]};return ri.autoTicks(n,(e-t)/(r||15)),n}var jh=function(t){for(var e=0,r=0;r=0;a--)(o=((c[[(r=(i=h[a])[0])-1,n=i[1]]]||d)[2]+(c[[r+1,n]]||d)[2]+(c[[r,n-1]]||d)[2]+(c[[r,n+1]]||d)[2])/20)&&(s[i]=[r,n,o],h.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)c[i]=s[i],u.push(s[i])}return u.sort(function(t,e){return e[2]-t[2]})},Uh=ne.isArrayOrTypedArray,qh=function(t){return!Uh(t.z[0])},Hh=[[-1,0],[1,0],[0,-1],[0,1]];function Gh(t){return.5-.25*Math.min(1,.5*t)}var Wh=function(t,e,r){var n,i,a=1;if(Array.isArray(r))for(n=0;n.01;n++)a=Yh(t,e,Gh(a));return a>.01&&ne.log("interp2d didn't converge quickly",a),t};function Yh(t,e,r){var n,i,a,o,s,l,u,c,h,f,p,d,g,v=0;for(o=0;od&&(v=Math.max(v,Math.abs(t[i][a]-p)/(g-d))))}return v}var Xh=ne.isArrayOrTypedArray,Zh=function(t,e,r,n,i,a){var o,s,l,u=[],c=P.traceIs(t,"contour"),h=P.traceIs(t,"histogram"),f=P.traceIs(t,"gl2d");if(Xh(e)&&e.length>1&&!h&&"category"!==a.type){var p=e.length;if(!(p<=i))return c?e.slice(0,i):e.slice(0,i+1);if(c||f)u=e.slice(0,i);else if(1===i)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],l=1;la){var o=a-n[t];return n[t]=a,o}}return 0},max:function(t,e,n,i){var a=i[e];if(r(a)){if(a=Number(a),!r(n[t]))return n[t]=a,a;if(n[t]p&&ptf){var d=a===Qh?1:6,g=a===Qh?"M12":"M1";return function(e,r){var a=n.c2d(e,Qh,i),s=a.indexOf("-",d);s>0&&(a=a.substr(0,s));var l=n.d2c(a,0,i);if(lnf?t>tf?t>1.1*Qh?Qh:t>1.1*$h?$h:tf:t>ef?ef:t>rf?rf:nf:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function uf(t,e,r,n,i,a){if(n&&t>tf){var o=cf(e,i,a),s=cf(r,i,a),l=t===Qh?0:1;return o[l]!==s[l]}return Math.floor(r/t)-Math.floor(e/t)>.1}function cf(t,e,r){var n=e.c2d(t,Qh,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}var hf=ne.cleanDate,ff=t.ONEDAY,pf=t.BADNUM,df=function(t,e,n){var i=e.type,a=n+"bins",o=t[a];o||(o=t[a]={});var s="date"===i?function(t){return t||0===t?hf(t,pf,o.calendar):null}:function(t){return r(t)?Number(t):null};o.start=s(o.start),o.end=s(o.end);var l="date"===i?ff:1,u=o.size;if(r(u))o.size=u>0?Number(u):l;else if("string"!=typeof u)o.size=l;else{var c=u.charAt(0),h=u.substr(1);((h=r(h)?Number(h):0)<=0||"date"!==i||"M"!==c||h!==Math.round(h))&&(o.size=l)}var f="autobin"+n;"boolean"!=typeof t[f]&&(t[f]=t._fullInput[f]=t._input[f]=!((o.start||0===o.start)&&(o.end||0===o.end))),t[f]||(delete t["nbins"+n],delete t._fullInput["nbins"+n])},gf={percent:function(t,e){for(var r=t.length,n=100/e,i=0;iv&&s.splice(v,s.length-v),u.length>v&&u.splice(v,u.length-v),vf(e,"x",s,o,f,d,c),vf(e,"y",u,l,p,g,h);var m=[],y=[],x=[],b="string"==typeof e.xbins.size,_="string"==typeof e.ybins.size,w=[],M=[],A=b?w:e.xbins,k=_?M:e.ybins,T=0,S=[],E=[],C=e.histnorm,L=e.histfunc,z=-1!==C.indexOf("density"),P="max"===L||"min"===L?null:0,I=Kh.count,D=gf[C],O=!1,R=[],F=[],B="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";B&&"count"!==L&&(O="avg"===L,I=Kh[L]);var N=e.xbins,j=f(N.start),V=f(N.end)+(j-ri.tickIncrement(j,N.size,!1,c))/1e6;for(r=j;r=0&&i=0&&ax){m("x scale is not linear");break}}if(a.length&&"fast"===v){var b=(a[a.length-1]-a[0])/(a.length-1),_=Math.abs(b/100);for(u=0;u_){m("y scale is not linear");break}}}var w=jh(l),M="scaled"===e.xtype?"":r,A=Zh(e,M,n,i,w,h),k="scaled"===e.ytype?"":a,T=Zh(e,k,o,s,l.length,f);g||(ri.expand(h,A),ri.expand(f,T));var S={x:A,y:T,z:l,text:e.text};if(M&&M.length===A.length-1&&(S.xCenter=M),k&&k.length===T.length-1&&(S.yCenter=k),d&&(S.xRanges=c.xRanges,S.yRanges=c.yRanges,S.pts=c.pts),p&&"constraint"===e.contours.type||Ve(e,l,"","z"),p&&e.contours&&"heatmap"===e.contours.coloring){var E={type:"contour"===e.type?"heatmap":"histogram2d",xcalendar:e.xcalendar,ycalendar:e.ycalendar};S.xfill=Zh(E,M,n,i,w,h),S.yfill=Zh(E,k,o,s,l.length,f)}return[S]},_f=function(t,e){var r=bf(t,e);return Bh(e),r},wf=function(t){return t.end+t.size/1e6},Mf=function(t){var r=t.contours,n=r.start,i=wf(r),a=r.size||1,o=Math.floor((i-n)/a)+1,s="lines"===r.coloring?0:1;isFinite(a)||(a=1,o=1);var l,u,c=t.colorscale,h=c.length,f=new Array(h),p=new Array(h);if("heatmap"===r.coloring){for(t.zauto&&!1===t.autocontour&&(t.zmin=n-a/2,t.zmax=t.zmin+o*a),u=0;u2?e.value=e.value.slice(2):0===e.length?e.value=[0,1]:e.length<2?(n=parseFloat(e.value[0]),e.value=[n,n+1]):e.value=[parseFloat(e.value[0]),parseFloat(e.value[1])]:r(e.value)&&(n=parseFloat(e.value),e.value=[n,n+1])):(t("contours.value",0),r(e.value)||(Array.isArray(e.value)?e.value=parseFloat(e.value[0]):e.value=0))}(n,c),"="===h?s=c.showlines=!0:(s=n("contours.showlines"),u=n("fillcolor",Tf((t.line||{}).color||a,.5))),s)&&(l=n("line.color",u&&Sf(u)?Tf(e.fillcolor,1):a),n("line.width",2),n("line.dash"));n("line.smoothing"),kf(n,i,l,o)};var zf=function(t,e,r,n){var i=n("contours.start"),a=n("contours.end"),o=!1===i||!1===a,s=r("contours.size");!(o?e.autocontour=!0:r("autocontour",!1))&&s||r("ncontours")},Pf=function(t,e,r,n,i){var a,o=r("contours.coloring"),s="";"fill"===o&&(a=r("contours.showlines")),!1!==a&&("lines"!==o&&(s=r("line.color","#000")),r("line.width",.5),r("line.dash")),"none"!==o&&Ye(t,e,n,r,{prefix:"",cLetter:"z"}),r("line.smoothing"),kf(r,n,s,i)},If=ne.isArrayOrTypedArray,Df=function(t,e,n,i,a,o){var s,l,u=n("z");if(a=a||"x",o=o||"y",void 0===u||!u.length)return 0;if(qh(t)){if(s=n(a),l=n(o),!s||!l)return 0}else{if(s=Of(a,n),l=Of(o,n),!function(t){for(var e,n=!0,i=!1,a=!1,o=0;o0&&(i=!0);for(var s=0;s=v[0].length||u<0||u>v.length)return}else{if(yo.inbox(e-d[0],e-d[d.length-1],0)>0||yo.inbox(r-g[0],r-g[g.length-1],0)>0)return;if(a){var A;for(w=[2*d[0]-d[1]],A=1;A":h.value>f&&(s.prefixBoundary=!0);break;case"<":h.valuef)&&(s.prefixBoundary=!0);break;case"][":a=Math.min.apply(null,h.value),o=Math.max.apply(null,h.value),af&&(s.prefixBoundary=!0)}},Nf={BOTTOMSTART:[1,9,13,104,713],TOPSTART:[4,6,7,104,713],LEFTSTART:[8,12,14,208,1114],RIGHTSTART:[2,3,11,208,1114],NEWDELTA:[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],CHOOSESADDLE:{104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},SADDLEREMAINDER:{1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11},LABELDISTANCE:2,LABELINCREASE:10,LABELMIN:3,LABELMAX:10,LABELOPTIMIZER:{EDGECOST:1,ANGLECOST:1,NEIGHBORCOST:5,SAMELEVELFACTOR:10,SAMELEVELDISTANCE:5,MAXCOST:100,INITIALSEARCHPOINTS:10,ITERATIONS:5}},jf=function(t,e){var r,n,i,a=function(t){return t.reverse()},o=function(t){return t};switch(e){case"=":case"<":return t;case">":for(1!==t.length&&ne.warn("Contour data invalid for the specified inequality operation."),n=t[0],r=0;r":Gf(">"),"<":Gf("<"),"=":Gf("=")};function qf(t,e){var n,i=Array.isArray(e);function a(t){return r(t)?+t:null}return-1!==Eh.COMPARISON_OPS2.indexOf(t)?n=a(i?e[0]:e):-1!==Eh.INTERVAL_OPS.indexOf(t)?n=i?[a(e[0]),a(e[1])]:[a(e),a(e)]:-1!==Eh.SET_OPS.indexOf(t)&&(n=i?e.map(a):[a(e)]),n}function Hf(t){return function(e){e=qf(t,e);var r=Math.min(e[0],e[1]),n=Math.max(e[0],e[1]);return{start:r,end:n,size:n-r}}}function Gf(t){return function(e){return{start:e=qf(t,e),end:1/0,size:1/0}}}var Wf=function(t,e,r){for(var n="constraint"===t.type?Uf[t._operation](t.value):t,i=n.size,a=[],o=wf(n),s=r.trace.carpetTrace,l=s?{xaxis:s.aaxis,yaxis:s.baxis,x:r.a,y:r.b}:{xaxis:e.xaxis,yaxis:e.yaxis,x:r.x,y:r.y},u=n.start;u1e3){ne.warn("Too many contours, clipping at 1000",t);break}return a},Yf=function(t,e,r){var n,i,a,o;for(e=e||.01,r=r||.01,i=0;i20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==Nf.BOTTOMSTART.indexOf(t)?i=1:-1!==Nf.LEFTSTART.indexOf(t)?n=1:-1!==Nf.TOPSTART.indexOf(t)?i=-1:n=-1;return[n,i]}(l,r,e),c=[Jf(t,e,[-u[0],-u[1]])],h=u.join(","),f=t.z.length,p=t.z[0].length;for(a=0;a<1e4;a++){if(l>20?(l=Nf.CHOOSESADDLE[l][(u[0]||u[1])<0?0:1],t.crossings[s]=Nf.SADDLEREMAINDER[l]):delete t.crossings[s],!(u=Nf.NEWDELTA[l])){ne.log("Found bad marching index:",l,e,t.level);break}c.push(Jf(t,e,u)),e[0]+=u[0],e[1]+=u[1],Xf(c[c.length-1],c[c.length-2],n,i)&&c.pop(),s=e.join(",");var d=u[0]&&(e[0]<0||e[0]>p-2)||u[1]&&(e[1]<0||e[1]>f-2);if(s===o&&u.join(",")===h||r&&d)break;l=t.crossings[s]}1e4===a&&ne.log("Infinite loop in contour?");var g,v,m,y,x,b,_,w,M,A,k,T,S,E,C,L=Xf(c[0],c[c.length-1],n,i),z=0,P=.2*t.smoothing,I=[],D=0;for(a=1;a=D;a--)if((g=I[a])=D&&g+I[v]w&&M--,t.edgepaths[M]=k.concat(c,A));break}B||(t.edgepaths[w]=c.concat(A))}for(w=0;wt?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);return 5===r||10===r?t>(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4?5===r?713:1114:5===r?104:208:15===r?0:r}var $f=function(t,e,r){for(var n=0;n0;)f=o.c2p(y[v]),v--;for(f0;)g=l.c2p(x[v]),v--;if(gt.level}return r?"M"+e.join("L")+"Z":""}(t,e),c=0,h=t.edgepaths.map(function(t,e){return e}),f=!0;function p(t){return Math.abs(t[1]-e[2][1])<.01}function d(t){return Math.abs(t[0]-e[0][0])<.01}function g(t){return Math.abs(t[0]-e[2][0])<.01}for(;h.length;){for(s=Sr.smoothopen(t.edgepaths[c],t.smoothing),u+=f?s:s.replace(/^M/,"L"),h.splice(h.indexOf(c),1),r=t.edgepaths[c][t.edgepaths[c].length-1],a=-1,i=0;i<4;i++){if(!r){ne.log("Missing end?",c,t);break}for(l=r,Math.abs(l[1]-e[0][1])<.01&&!g(r)?n=e[1]:d(r)?n=e[0]:p(r)?n=e[3]:g(r)&&(n=e[2]),o=0;o=0&&(n=v,a=o):Math.abs(r[1]-n[1])<.01?Math.abs(r[1]-v[1])<.01&&(v[0]-r[0])*(n[0]-v[0])>=0&&(n=v,a=o):ne.log("endpt to newendpt is not vert. or horz.",r,n,v)}if(r=n,a>=0)break;u+="L"+n}if(a===t.edgepaths.length){ne.log("unclosed perimeter path");break}c=a,(f=-1===h.indexOf(c))&&(c=h[0],u+="Z")}for(c=0;cn.center?n.right-o:o-n.left)/(u+Math.abs(Math.sin(l)*a)),f=(s>n.middle?n.bottom-s:s-n.top)/(Math.abs(c)+Math.cos(l)*a);if(h<1||f<1)return 1/0;var p=ap.EDGECOST*(1/(h-1)+1/(f-1));p+=ap.ANGLECOST*l*l;for(var d=o-u,g=s-c,v=o+u,m=s+c,y=0;y2*ap.MAXCOST)break;f&&(o/=2),s=(a=l-o/2)+1.5*o}if(h<=ap.MAXCOST)return u},ip.addLabelData=function(t,e,r,n){var i=e.width/2,a=e.height/2,o=t.x,s=t.y,l=t.theta,u=Math.sin(l),c=Math.cos(l),h=i*c,f=a*u,p=i*u,d=-a*c,g=[[o-h-f,s-p-d],[o+h-f,s+p-d],[o+h+f,s+p+d],[o-h+f,s-p+d]];r.push({text:e.text,x:o,y:s,dy:e.dy,theta:l,level:e.level,width:e.width,height:e.height}),n.push(g)},ip.drawLabels=function(t,r,n,i,a){var o=t.selectAll("text").data(r,function(t){return t.text+","+t.x+","+t.y+","+t.theta});if(o.exit().remove(),o.enter().append("text").attr({"data-notex":1,"text-anchor":"middle"}).each(function(t){var r=t.x+Math.sin(t.theta)*t.dy,i=t.y-Math.cos(t.theta)*t.dy;e.select(this).text(t.text).attr({x:r,y:i,transform:"rotate("+180*t.theta/Math.PI+" "+r+" "+i+")"}).call(er.convertToTspans,n)}),a){for(var s="",l=0;l0?Math.floor:Math.ceil,z=E>0?Math.ceil:Math.floor,P=E>0?Math.min:Math.max,I=E>0?Math.max:Math.min,D=L(T+C),O=z(S-C),R=[[c=k(T)]];for(i=D;i*E=0&&(c=T,f=p):Math.abs(u[1]-c[1])=0&&(c=T,f=p):ne.log("endpt to newendpt is not vert. or horz.",u,c,T)}if(f>=0)break;g+=A(u,c),u=c}if(f===e.edgepaths.length){ne.log("unclosed perimeter path");break}l=f,(m=-1===v.indexOf(l))&&(l=v[0],g+=A(u,c)+"Z",u=null)}for(l=0;l=0;T--)M=o.clipsegments[T],A=Ou([],M.x,h.c2p),k=Ou([],M.y,f.c2p),A.reverse(),k.reverse(),E.push(Iu(A,k,M.bicubic));var C="M"+E.join("L")+"Z";!function(t,e,r,n,i,a){var o,s,l,u,c=t.selectAll("g.contourbg").data([0]);c.enter().append("g").classed("contourbg",!0);var h=c.selectAll("path").data("fill"!==a||i?[]:[0]);h.enter().append("path"),h.exit().remove();var f=[];for(u=0;uv&&(n.max=v);n.len=n.max-n.min}(this,e,t,n,s,r.height),!(n.len<(r.width+r.height)*Nf.LABELMIN)))for(var i=Math.min(Math.ceil(n.len/k),Nf.LABELMAX),a=0;a1)for(var r=1;r=0,d=r.indexOf("end")>=0,g=u.backoff*h+n.standoff,v=c.backoff*f+n.startstandoff;if("line"===l.nodeName){i={x:+t.attr("x1"),y:+t.attr("y1")},a={x:+t.attr("x2"),y:+t.attr("y2")};var m=i.x-a.x,y=i.y-a.y;if(s=(o=Math.atan2(y,m))+Math.PI,g&&v&&g+v>Math.sqrt(m*m+y*y))return void C();if(g){if(g*g>m*m+y*y)return void C();var x=g*Math.cos(o),b=g*Math.sin(o);a.x+=x,a.y+=b,t.attr({x2:a.x,y2:a.y})}if(v){if(v*v>m*m+y*y)return void C();var _=v*Math.cos(o),w=v*Math.sin(o);i.x-=_,i.y-=w,t.attr({x1:i.x,y1:i.y})}}else if("path"===l.nodeName){var M=l.getTotalLength(),A="";if(M2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}r._w=E,r._h=C;for(var D=!1,O=["x","y"],R=0;R1)&&(H===q?(($=G.r2fraction(r["a"+U]))<0||$>1)&&(D=!0):D=!0,D))continue;F=G._offset+G.r2p(r[U]),j=.5}else"x"===U?(N=r[U],F=c.l+c.w*N):(N=1-r[U],F=c.t+c.h*N),j=r.showarrow?.5:N;if(r.showarrow){Q.head=F;var tt=r["a"+U];V=Y*I(.5,r.xanchor)-X*I(.5,r.yanchor),H===q?(Q.tail=G._offset+G.r2p(tt),B=V):(Q.tail=F+tt,B=V+tt),Q.text=Q.tail+V;var et=u["x"===U?"width":"height"];if("paper"===q&&(Q.head=ne.constrain(Q.head,1,et-1)),"pixel"===H){var rt=-Math.max(Q.tail-3,Q.text),nt=Math.min(Q.tail+3,Q.text)-et;rt>0?(Q.tail+=rt,Q.text+=rt):nt>0&&(Q.tail-=nt,Q.text-=nt)}Q.tail+=K,Q.head+=K}else B=V=Z*I(j,J),Q.text=F+V;Q.text+=K,V+=K,B+=K,r["_"+U+"padplus"]=Z/2+B,r["_"+U+"padminus"]=Z/2-B,r["_"+U+"size"]=Z,r["_"+U+"shift"]=V}if(D)x.remove();else{var it=0,at=0;if("left"!==r.align&&(it=(E-_)*("center"===r.align?.5:1)),"top"!==r.valign&&(at=(C-T)*("middle"===r.valign?.5:1)),s)n.select("svg").attr({x:w+it-1,y:w+at}).call(Sr.setClipUrl,A?f:null);else{var ot=w+at-y.top,st=w+it-y.left;S.call(er.positionText,st,ot).call(Sr.setClipUrl,A?f:null)}k.select("rect").call(Sr.setRect,w,w,E,C),M.call(Sr.setRect,b/2,b/2,L-b,z-b),x.call(Sr.setTranslate,Math.round(p.x.text-L/2),Math.round(p.y.text-z/2)),v.attr({transform:"rotate("+d+","+p.x.text+","+p.y.text+")"});var lt,ut,ct=function(e,n){g.selectAll(".annotation-arrow-g").remove();var s=p.x.head,u=p.y.head,f=p.x.tail+e,m=p.y.tail+n,y=p.x.text+e,b=p.y.text+n,_=ne.rotationXYMatrix(d,y,b),w=ne.apply2DTransform(_),A=ne.apply2DTransform2(_),k=+M.attr("width"),T=+M.attr("height"),S=y-.5*k,E=S+k,C=b-.5*T,L=C+T,z=[[S,C,S,L],[S,L,E,L],[E,L,E,C],[E,C,S,C]].map(A);if(!z.reduce(function(t,e){return t^!!ne.segmentsIntersect(s,u,s+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){z.forEach(function(t){var e=ne.segmentsIntersect(f,m,s,u,t[0],t[1],t[2],t[3]);e&&(f=e.x,m=e.y)});var I=r.arrowwidth,D=r.arrowcolor,O=r.arrowside,R=g.append("g").style({opacity:Oe.opacity(D)}).classed("annotation-arrow-g",!0),F=R.append("path").attr("d","M"+f+","+m+"L"+s+","+u).style("stroke-width",I+"px").call(Oe.stroke,Oe.rgb(D));if(Kp(F,O,r),h.annotationPosition&&F.node().parentNode&&!i){var B=s,N=u;if(r.standoff){var j=Math.sqrt(Math.pow(s-f,2)+Math.pow(u-m,2));B+=r.standoff*(f-s)/j,N+=r.standoff*(m-u)/j}var V,U,q,H=R.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(f-B)+","+(m-N),transform:"translate("+B+","+N+")"}).style("stroke-width",I+6+"px").call(Oe.stroke,"rgba(0,0,0,0)").call(Oe.fill,"rgba(0,0,0,0)");Ua.init({element:H.node(),gd:t,prepFn:function(){var t=Sr.getTranslate(x);U=t.x,q=t.y,V={},a&&a.autorange&&(V[a._name+".autorange"]=!0),o&&o.autorange&&(V[o._name+".autorange"]=!0)},moveFn:function(t,e){var n=w(U,q),i=n[0]+t,s=n[1]+e;x.call(Sr.setTranslate,i,s),V[l+".x"]=a?a.p2r(a.r2p(r.x)+t):r.x+t/c.w,V[l+".y"]=o?o.p2r(o.r2p(r.y)+e):r.y-e/c.h,r.axref===r.xref&&(V[l+".ax"]=a.p2r(a.r2p(r.ax)+t)),r.ayref===r.yref&&(V[l+".ay"]=o.p2r(o.r2p(r.ay)+e)),R.attr("transform","translate("+t+","+e+")"),v.attr({transform:"rotate("+d+","+i+","+s+")"})},doneFn:function(){P.call("relayout",t,V);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(r.showarrow&&ct(0,0),m)Ua.init({element:x.node(),gd:t,prepFn:function(){ut=v.attr("transform"),lt={}},moveFn:function(t,e){var n="pointer";if(r.showarrow)r.axref===r.xref?lt[l+".ax"]=a.p2r(a.r2p(r.ax)+t):lt[l+".ax"]=r.ax+t,r.ayref===r.yref?lt[l+".ay"]=o.p2r(o.r2p(r.ay)+e):lt[l+".ay"]=r.ay+e,ct(t,e);else{if(i)return;if(a)lt[l+".x"]=a.p2r(a.r2p(r.x)+t);else{var s=r._xsize/c.w,u=r.x+(r._xshift-r.xshift)/c.w-s/2;lt[l+".x"]=Ua.align(u+t/c.w,s,0,1,r.xanchor)}if(o)lt[l+".y"]=o.p2r(o.r2p(r.y)+e);else{var h=r._ysize/c.h,f=r.y-(r._yshift+r.yshift)/c.h-h/2;lt[l+".y"]=Ua.align(f-e/c.h,h,0,1,r.yanchor)}a&&o||(n=Ua.getCursor(a?.5:lt[l+".x"],o?.5:lt[l+".y"],r.xanchor,r.yanchor))}v.attr({transform:"translate("+t+","+e+")"+ut}),Ka(x,n)},doneFn:function(){Ka(x),P.call("relayout",t,lt);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var ed=Qp.draw;function rd(t){var e=t._fullLayout;ne.filterVisible(e.annotations).forEach(function(e){var r,n,i,a,o=ri.getFromId(t,e.xref),s=ri.getFromId(t,e.yref),l=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=l+e.xshift,n=l-e.xshift,i=u+e.xshift,a=u-e.xshift,e.axref===e.xref?(ri.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),ri.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,a)})):(i=e.ax?i+e.ax:i,a=e.ax?a-e.ax:a,ri.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,a)}))),s&&s.autorange&&(r=l-e.yshift,n=l+e.yshift,i=u-e.yshift,a=u+e.yshift,e.ayref===e.yref?(ri.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),ri.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,a)})):(i=e.ay?i+e.ay:i,a=e.ay?a-e.ay:a,ri.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,a)})))})}var nd={hasClickToShow:function(t,e){var r=id(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=id(t,e),i=n.on,a=n.off.concat(n.explicitOff),o={};if(!i.length&&!a.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+i+'"]').remove():(a._pdata=gd(t.glplot.cameraParams,[e.xaxis.r2l(a.x)*r[0],e.yaxis.r2l(a.y)*r[1],e.zaxis.r2l(a.z)*r[2]]),vd(t.graphDiv,a,i,t.id,a._xa,a._ya))}}};var xd={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},bd=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+n[e],a=+i[e];return isNaN(r)&&isNaN(a)?[NaN,NaN]:[a||0,r||0]}}var a=_d(e,t.value),o=_d(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=a(t);return[e,e]}:function(t){return[o(t),a(t)]}};function _d(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var wd=function(t){for(var e=t.calcdata,r=0;r0;t.each(function(t){var l,u=t[0].trace,c=u.error_x||{},h=u.error_y||{};u.ids&&(l=function(t){return t.id});var f=Tr.hasMarkers(u)&&u.marker.maxdisplayed>0;h.visible||c.visible||(t=[]);var p=e.select(this).selectAll("g.errorbar").data(t,l);if(p.exit().remove(),t.length){c.visible||p.selectAll("path.xerror").remove(),h.visible||p.selectAll("path.yerror").remove(),p.style("opacity",1);var d=p.enter().append("g").classed("errorbar",!0);s&&d.style("opacity",0).transition().duration(i.duration).style("opacity",1),Sr.setClipUrl(p,n.layerClipId),p.each(function(t){var n=e.select(this),l=function(t,e,n){var i={x:e.c2p(t.x),y:n.c2p(t.y)};return void 0!==t.yh&&(i.yh=n.c2p(t.yh),i.ys=n.c2p(t.ys),r(i.ys)||(i.noYS=!0,i.ys=n.c2p(t.ys,!0))),void 0!==t.xh&&(i.xh=e.c2p(t.xh),i.xs=e.c2p(t.xs),r(i.xs)||(i.noXS=!0,i.xs=e.c2p(t.xs,!0))),i}(t,a,o);if(!f||t.vis){var u,p=n.select("path.yerror");if(h.visible&&r(l.x)&&r(l.yh)&&r(l.ys)){var d=h.width;u="M"+(l.x-d)+","+l.yh+"h"+2*d+"m-"+d+",0V"+l.ys,l.noYS||(u+="m-"+d+",0h"+2*d),p.size()?s&&(p=p.transition().duration(i.duration).ease(i.easing)):p=n.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),p.attr("d",u)}else p.remove();var g=n.select("path.xerror");if(c.visible&&r(l.y)&&r(l.xh)&&r(l.xs)){var v=(c.copy_ystyle?h:c).width;u="M"+l.xh+","+(l.y-v)+"v"+2*v+"m0,-"+v+"H"+l.xs,l.noXS||(u+="m0,-"+v+"v"+2*v),g.size()?s&&(g=g.transition().duration(i.duration).ease(i.easing)):g=n.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",u)}else g.remove()}})}})},style:function(t){t.each(function(t){var r=t[0].trace,n=r.error_y||{},i=r.error_x||{},a=e.select(this);a.selectAll("path.yerror").style("stroke-width",n.thickness+"px").call(Oe.stroke,n.color),i.copy_ystyle&&(i=n),a.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(Oe.stroke,i.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var Ed=tt.counter,Cd=qc.attributes,Ld=Te.idRegex,zd={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:!0,dimensions:2,items:{valType:"enumerated",values:[Ed("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[Ld.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[Ld.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:Cd({name:"grid",editType:"plot",noGridCell:!0},{}),xside:{valType:"enumerated",values:["bottom","bottom plot","top plot","top"],dflt:"bottom plot",editType:"ticks"},yside:{valType:"enumerated",values:["left","left plot","right plot","right"],dflt:"left plot",editType:"ticks"},editType:"plot"};function Pd(t,e,r,n,i){var a=e(t+"gap",r),o=e("domain."+t);e(t+"side");for(var s=new Array(n),l=o[0],u=(o[1]-l)/(n-a),c=u*(1-a),h=0;h1){a||o||s||"independent"===f("pattern")&&(a=!0),l._hasSubplotGrid=a;var h="top to bottom"===f("roworder");l._domains={x:Pd("x",f,a?.2:.1,c),y:Pd("y",f,a?.3:.1,u,h)}}}function f(t,e){return ne.coerce(r,l,zd,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,a,o,s,l,u,c=t.grid,h=e._subplots,f=r._hasSubplotGrid,p=r.rows,d=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(f){var m=c.subplots||[];l=r.subplots=new Array(p);var y=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},Ud={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},qd=!0,Hd=function(t,e,r){if(!e._dragged&&!e._editing){var n,i,a,o,s,l=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,h=u.trace,f=h.legendgroup,p={},d=[],g=[],v=[];if(1===r&&qd&&e.data&&e._context.showTips?(ne.notifier(ne._(e,"Double-click on legend to isolate one trace"),"long"),qd=!1):qd=!1,P.traceIs(h,"pie")){var m=u.label,y=l.indexOf(m);1===r?-1===y?l.push(m):l.splice(y,1):2===r&&(l=[],e.calcdata[0].forEach(function(t){m!==t.label&&l.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===l.length&&-1===y&&(l=[])),P.call("relayout",e,"hiddenlabels",l)}else{var x,b=f&&f.length,_=[];if(b)for(n=0;nr[1])return r[1]}return i}function h(t){return t[0]}if(s||l||u){var f={},p={};s&&(f.mc=c("marker.color",h),f.mo=c("marker.opacity",ne.mean,[.2,1]),f.ms=c("marker.size",ne.mean,[2,16]),f.mlc=c("marker.line.color",h),f.mlw=c("marker.line.width",ne.mean,[0,5]),p.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(p.line={width:c("line.width",h,[0,10])}),l&&(f.tx="Aa",f.tp=c("textposition",h),f.ts=10,f.tc=c("textfont.color",h),f.tf=c("textfont.family",h)),n=[ne.minExtend(a,f)],i=ne.minExtend(o,p)}var d=e.select(this).select("g.legendpoints"),g=d.selectAll("path.scatterpts").data(s?n:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Sr.pointStyle,i,r),s&&(n[0].mrc=3);var v=d.selectAll("g.pointtext").data(l?n:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Sr.textPointStyle,i,r)})},Zd=Qe.LINE_SPACING,Jd=Qe.FROM_TL,Kd=Qe.FROM_BR,Qd=f.DBLCLICKDELAY;function $d(t,e){var r=t.data()[0][0],n=e._fullLayout,i=r.trace,a=P.traceIs(i,"pie"),o=i.index,s=a?r.label:i.name,l=t.selectAll("text.legendtext").data([0]);function u(r){er.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*Zd;if(o){var l=Sr.bBox(o);n=l.height,i=l.width,Sr.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),c=er.lineCount(u),h=u.node();n=s*c,i=h?Sr.bBox(h).width:0;var f=s*(.3+(1-c)/2);er.positionText(u,40,f)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}l.enter().append("text").classed("legendtext",!0),l.attr("text-anchor","start").classed("user-select-none",!0).call(Sr.font,n.legend.font).text(s),e._context.edits.legendText&&!a?l.call(er.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n,i=t;this.text()||(t=" ");var a=r.trace._fullInput||{},s={};if(-1!==["ohlc","candlestick"].indexOf(a.type))s[(n=r.trace.transforms)[n.length-1].direction+".name"]=t;else if(P.hasTransform(a,"groupby")){var l=P.getTransformIndices(a,"groupby"),c=l[l.length-1],h=ne.keyedContainer(a,"transforms["+c+"].styles","target","value.name");""===i?h.remove(r.trace._group):h.set(r.trace._group,t),s=h.constructUpdate()}else s.name=t;return P.call("restyle",e,s,o)}):u(l)}function tg(t,e){var r,n=1,i=t.selectAll("rect").data([0]);i.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(Oe.fill,"rgba(0,0,0,0)"),i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimeQd&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Hd(t,e,n)},Qd):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,Hd(t,e,n))}})}function eg(t,r,n){var i=t._fullLayout,a=i.legend,o=a.borderwidth,s=jd.isGrouped(a),l=0;if(a._width=0,a._height=0,jd.isVertical(a))s&&r.each(function(t,e){Sr.setTranslate(this,0,e*a.tracegroupgap)}),n.each(function(t){var e=t[0],r=e.height,n=e.width;Sr.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],c=r.data(),h=0,f=c.length;ho+b-_,n.each(function(t){var e=t[0],r=g?40+t[0].width:y;o+x+_+r>i.width-(i.margin.r+i.margin.l)&&(x=0,v+=m,a._height=a._height+m,m=0),Sr.setTranslate(this,o+x,5+o+e.height/2+v),a._width+=_+r,a._height=Math.max(a._height,e.height),x+=_+r,m=Math.max(e.height,m)}),a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height),n.each(function(r){var n=r[0],i=e.select(this).select(".legendtoggle");Sr.setRect(i,0,-n.height/2,(t._context.edits.legendText?0:a._width)+l,n.height)})}function rg(t){var e=t._fullLayout.legend,r="left";Vd.isRightAnchor(e)?r="right":Vd.isCenterAnchor(e)&&(r="center");var n="top";Vd.isBottomAnchor(e)?n="bottom":Vd.isMiddleAnchor(e)&&(n="middle"),_n.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*Jd[r],r:e._width*Kd[r],b:e._height*Kd[n],t:e._height*Jd[n]})}var ng={moduleType:"component",name:"legend",layoutAttributes:Nd,supplyLayoutDefaults:function(t,e,r){for(var n,i,a,o,s=t.legend||{},l={},u=0,c="normal",h=0;h1)){if(e.legend=l,p("bgcolor",e.paper_bgcolor),p("bordercolor"),p("borderwidth"),ne.coerceFont(p,"font",e.font),p("orientation"),"h"===l.orientation){var d=t.xaxis;d&&d.rangeslider&&d.rangeslider.visible?(n=0,a="left",i=1.1,o="bottom"):(n=0,a="left",i=-.1,o="top")}p("traceorder",c),jd.isGrouped(e.legend)&&p("tracegroupgap"),p("x",n),p("xanchor",a),p("y",i),p("yanchor",o),ne.noneOrAll(s,l,["x","y"])}},draw:function(t){var r=t._fullLayout,n="legend"+r._uid;if(r._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var i=r.legend,a=r.showlegend&&function(t,e){var r,n,i={},a=[],o=!1,s={},l=0;function u(t,r){if(""!==t&&jd.isGrouped(e))-1===a.indexOf(t)?(a.push(t),o=!0,i[t]=[[r]]):i[t].push([r]);else{var n="~~i"+l;a.push(n),i[n]=[[r]],l++}}for(r=0;rg?function(t){var e=t._fullLayout.legend,r="left";Vd.isRightAnchor(e)?r="right":Vd.isCenterAnchor(e)&&(r="center"),_n.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*Jd[r],r:e._width*Kd[r],b:0,t:0})}(t):rg(t);var v=r._size,m=v.l+v.w*i.x,y=v.t+v.h*(1-i.y);Vd.isRightAnchor(i)?m-=i._width:Vd.isCenterAnchor(i)&&(m-=i._width/2),Vd.isBottomAnchor(i)?y-=i._height:Vd.isMiddleAnchor(i)&&(y-=i._height/2);var x=i._width,b=v.w;x>b?(m=v.l,x=b):(m+x>d&&(m=d-x),m<0&&(m=0),x=Math.min(d-m,i._width));var _,w,M,A,k=i._height,T=v.h;if(k>T?(y=v.t,k=T):(y+k>g&&(y=g-k),y<0&&(y=0),k=Math.min(g-y,i._height)),Sr.setTranslate(s,m,y),h.on(".drag",null),s.on("wheel",null),i._height<=k||t._context.staticPlot)u.attr({width:x-i.borderwidth,height:k-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),Sr.setTranslate(c,0,0),l.select("rect").attr({width:x-2*i.borderwidth,height:k-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth}),Sr.setClipUrl(c,n),Sr.setRect(h,0,0,0,0),delete i._scrollY;else{var S,E,C=Math.max(Ud.scrollBarMinHeight,k*k/i._height),L=k-C-2*Ud.scrollBarMargin,z=i._height-k,I=L/z,D=Math.min(i._scrollY||0,z);u.attr({width:x-2*i.borderwidth+Ud.scrollBarWidth+Ud.scrollBarMargin,height:k-i.borderwidth,x:i.borderwidth/2,y:i.borderwidth/2}),l.select("rect").attr({width:x-2*i.borderwidth+Ud.scrollBarWidth+Ud.scrollBarMargin,height:k-2*i.borderwidth,x:i.borderwidth,y:i.borderwidth+D}),Sr.setClipUrl(c,n),R(D,C,I),s.on("wheel",function(){R(D=ne.constrain(i._scrollY+e.event.deltaY/L*z,0,z),C,I),0!==D&&D!==z&&e.event.preventDefault()});var O=e.behavior.drag().on("dragstart",function(){S=e.event.sourceEvent.clientY,E=D}).on("drag",function(){var t=e.event.sourceEvent;2===t.buttons||t.ctrlKey||R(D=ne.constrain((t.clientY-S)/I+E,0,z),C,I)});h.call(O)}t._context.edits.legendPosition&&(s.classed("cursor-move",!0),Ua.init({element:s.node(),gd:t,prepFn:function(){var t=Sr.getTranslate(s);M=t.x,A=t.y},moveFn:function(t,e){var r=M+t,n=A+e;Sr.setTranslate(s,r,n),_=Ua.align(r,0,v.l,v.l+v.w,i.xanchor),w=Ua.align(n,0,v.t+v.h,v.t,i.yanchor)},doneFn:function(){void 0!==_&&void 0!==w&&P.call("relayout",t,{"legend.x":_,"legend.y":w})},clickFn:function(e,n){var i=r._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===e?s._clickTimeout=setTimeout(function(){Hd(i,t,e)},Qd):2===e&&(s._clickTimeout&&clearTimeout(s._clickTimeout),Hd(i,t,e)))}}))}function R(e,r,n){i._scrollY=t._fullLayout.legend._scrollY=e,Sr.setTranslate(c,0,-e),Sr.setRect(h,x,Ud.scrollBarMargin+e*n,Ud.scrollBarWidth,r),l.select("rect").attr({y:i.borderwidth+e})}},style:Xd},ig={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},ag=m.extendFlat,og={visible:{valType:"boolean",editType:"plot"},buttons:ig=ag(ig,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:T({editType:"plot"}),bgcolor:{valType:"color",dflt:C.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:C.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},sg={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var lg=function(t,r){var n=t._name,i={};if("all"===r.step)i[n+".autorange"]=!0;else{var a=function(t,r){var n,i=t.range,a=new Date(t.r2l(i[1])),o=r.step,s=r.count;switch(r.stepmode){case"backward":n=t.l2r(+e.time[o].utc.offset(a,-s));break;case"todate":var l=e.time[o].utc.offset(a,-s);n=t.l2r(+e.time[o].utc.ceil(l))}var u=i[1];return[n,u]}(t,r);i[n+".range[0]"]=a[0],i[n+".range[1]"]=a[1]}return i};var ug=Qe.LINE_SPACING,cg=Qe.FROM_TL,hg=Qe.FROM_BR;function fg(t){return t._id}function pg(t,e,r){var n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("selector-rect",!0),n.attr("shape-rendering","crispEdges"),n.attr({rx:sg.rx,ry:sg.ry}),n.call(Oe.stroke,e.bordercolor).call(Oe.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function dg(t,e,r,n){var i,a=t.selectAll("text").data([0]);a.enter().append("text").classed("selector-text",!0).classed("user-select-none",!0),a.attr("text-anchor","middle"),a.call(Sr.font,e.font).text((i=r,i.label?i.label:"all"===i.step?"all":i.count+i.step.charAt(0))).call(function(t){er.convertToTspans(t,n)})}var gg={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:og}}},layoutAttributes:og,handleDefaults:function(t,e,r,n,i){var a=t.rangeselector||{},o=e.rangeselector={};function s(t,e){return ne.coerce(a,o,og,t,e)}if(s("visible",function(t,e,r){var n,i,a=t.buttons||[],o=e.buttons=[];function s(t,e){return ne.coerce(n,i,ig,t,e)}for(var l=0;l0)){var l=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;ah&&(h=u)));return h>=c?[c,h]:void 0}}var Og=function(t,e,r,n,i){function a(r,n){return ne.coerce(t,e,zg,r,n)}if(n=n||{},!a("visible",!(i=i||{}).itemIsNotPlainObject))return e;a("layer"),a("opacity"),a("fillcolor"),a("line.color"),a("line.width"),a("line.dash");for(var o=a("type",t.path?"path":"rect"),s=["x","y"],l=0;l<2;l++){var u=s[l],c={_fullLayout:r},h=ri.coerceRef(t,e,c,u,"","paper");if("path"!==o){var f,p,d;"paper"!==h?(f=ri.getFromId(c,h),d=Ig.rangeToShapePosition(f),p=Ig.shapePositionToRange(f)):p=d=ne.identity;var g=u+"0",v=u+"1",m=t[g],y=t[v];t[g]=p(t[g],!0),t[v]=p(t[v],!0),ri.coercePosition(e,c,a,h,g,.25),ri.coercePosition(e,c,a,h,v,.75),e[g]=d(e[g]),e[v]=d(e[v]),t[g]=m,t[v]=y}}return"path"===o?a("path"):ne.noneOrAll(t,e,["x0","x1","y0","y1"]),e},Rg={draw:function(t){var e=t._fullLayout;e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._shapeSubplotLayers.selectAll("path").remove();for(var r=0;rO&&n>R&&!t.shiftKey?Ua.getCursor(i/r,1-a/n):"move";Ka(e,o),D=o.split("-")[0]}function j(n,p){if("path"===r.type){var d=function(t){return z(C(t)+n)};S&&"date"===S.type&&(d=Ig.encodeDate(d));var g=function(t){return I(L(t)+p)};E&&"date"===E.type&&(g=Ig.encodeDate(g)),r.path=Ng(k,d,g),i[T]=r.path}else i[u]=r.x0=z(a+n),i[c]=r.y0=I(o+p),i[h]=r.x1=z(s+n),i[f]=r.y1=I(l+p);e.attr("d",Bg(t,r))}function V(n,a){if("path"===r.type){var o=function(t){return z(C(t)+n)};S&&"date"===S.type&&(o=Ig.encodeDate(o));var s=function(t){return I(L(t)+a)};E&&"date"===E.type&&(s=Ig.encodeDate(s)),r.path=Ng(k,o,s),i[T]=r.path}else{var l=~D.indexOf("n")?p+a:p,u=~D.indexOf("s")?d+a:d,c=~D.indexOf("w")?g+n:g,h=~D.indexOf("e")?v+n:v;u-l>R&&(i[m]=r[_]=I(l),i[y]=r[w]=I(u)),h-c>O&&(i[x]=r[M]=z(c),i[b]=r[A]=z(h))}e.attr("d",Bg(t,r))}Ua.init(F),e.node().onmousemove=N}(t,o,n,e)}}function Bg(t,e){var r,n,i,a,o=e.type,s=ri.getFromId(t,e.xref),l=ri.getFromId(t,e.yref),u=t._fullLayout._size;if(s?(r=Ig.shapePositionToRange(s),n=function(t){return s._offset+s.r2p(r(t,!0))}):n=function(t){return u.l+u.w*t},l?(i=Ig.shapePositionToRange(l),a=function(t){return l._offset+l.r2p(i(t,!0))}):a=function(t){return u.t+u.h*(1-t)},"path"===o)return s&&"date"===s.type&&(n=Ig.decodeDate(n)),l&&"date"===l.type&&(a=Ig.decodeDate(a)),function(t,e,r){return t.replace(Pg.segmentRE,function(t){var n=0,i=t.charAt(0),a=Pg.paramIsX[i],o=Pg.paramIsY[i],s=Pg.numParams[i],l=t.substr(1).replace(Pg.paramRE,function(t){return a[n]?t=e(t):o[n]&&(t=r(t)),++n>s&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),ne.log("Ignoring extra params in segment "+t)),i+l})}(e.path,n,a);var c=n(e.x0),h=n(e.x1),f=a(e.y0),p=a(e.y1);if("line"===o)return"M"+c+","+f+"L"+h+","+p;if("rect"===o)return"M"+c+","+f+"H"+h+"V"+p+"H"+c+"Z";var d=(c+h)/2,g=(f+p)/2,v=Math.abs(d-c),m=Math.abs(g-f),y="A"+v+","+m,x=d+v+","+g;return"M"+x+y+" 0 1,1 "+(d+","+(g-m))+y+" 0 0,1 "+x+"Z"}function Ng(t,e,r){return t.replace(Pg.segmentRE,function(t){var n=0,i=t.charAt(0),a=Pg.paramIsX[i],o=Pg.paramIsY[i],s=Pg.numParams[i];return i+t.substr(1).replace(Pg.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var jg={moduleType:"component",name:"shapes",layoutAttributes:zg,supplyLayoutDefaults:function(t,e){ld(t,e,{name:"shapes",handleItemDefaults:Og})},includeBasePlot:ud("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=ne.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),ne.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),ne.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),ne.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var Xg=Qe.LINE_SPACING,Zg=Qe.FROM_TL,Jg=Qe.FROM_BR;function Kg(t){return t._index}function Qg(t,r){var n=Sr.tester.selectAll("g."+Vg.labelGroupClass).data(r.steps);n.enter().append("g").classed(Vg.labelGroupClass,!0);var i=0,a=0;n.each(function(t){var n=ev(e.select(this),{step:t},r).node();if(n){var o=Sr.bBox(n);a=Math.max(a,o.height),i=Math.max(i,o.width)}}),n.remove();var o=r._dims={};o.inputAreaWidth=Math.max(Vg.railWidth,Vg.gripHeight);var s=t._fullLayout._size;o.lx=s.l+s.w*r.x,o.ly=s.t+s.h*(1-r.y),"fraction"===r.lenmode?o.outerLength=Math.round(s.w*r.len):o.outerLength=r.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-r.pad.l-r.pad.r);var l=(o.inputAreaLength-2*Vg.stepInset)/(r.steps.length-1),u=i+Vg.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/l)),o.labelHeight=a,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,r.currentvalue.visible){var c=Sr.tester.append("g");n.each(function(t){var e=$g(c,r,t.label),n=e.node()&&Sr.bBox(e.node())||{width:0,height:0},i=er.lineCount(e);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,i)}),o.currentValueTotalHeight=o.currentValueHeight+r.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+Vg.tickOffset+r.ticklen+Vg.labelOffset+o.labelHeight+r.pad.t+r.pad.b;var h="left";Vd.isRightAnchor(r)&&(o.lx-=o.outerLength,h="right"),Vd.isCenterAnchor(r)&&(o.lx-=o.outerLength/2,h="center");var f="top";Vd.isBottomAnchor(r)&&(o.ly-=o.height,f="bottom"),Vd.isMiddleAnchor(r)&&(o.ly-=o.height/2,f="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),_n.autoMargin(t,Vg.autoMarginIdRoot+r._index,{x:r.x,y:r.y,l:o.outerLength*Zg[h],r:o.outerLength*Jg[h],b:o.height*Jg[f],t:o.height*Zg[f]})}function $g(t,e,r){if(e.currentvalue.visible){var n,i,a=t.selectAll("text").data([0]),o=e._dims;switch(e.currentvalue.xanchor){case"right":n=o.inputAreaLength-Vg.currentValueInset-o.currentValueMaxWidth,i="left";break;case"center":n=.5*o.inputAreaLength,i="middle";break;default:n=Vg.currentValueInset,i="left"}a.enter().append("text").classed(Vg.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1});var s=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)s+=r;else s+=e.steps[e.active].label;e.currentvalue.suffix&&(s+=e.currentvalue.suffix),a.call(Sr.font,e.currentvalue.font).text(s).call(er.convertToTspans,e._gd);var l=er.lineCount(a),u=(o.currentValueMaxLines+1-l)*e.currentvalue.font.size*Xg;return er.positionText(a,n,u),a}}function tv(t,e,r){var n=t.selectAll("rect."+Vg.gripRectClass).data([0]);n.enter().append("rect").classed(Vg.gripRectClass,!0).call(av,e,t,r).style("pointer-events","all"),n.attr({width:Vg.gripWidth,height:Vg.gripHeight,rx:Vg.gripRadius,ry:Vg.gripRadius}).call(Oe.stroke,r.bordercolor).call(Oe.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function ev(t,e,r){var n=t.selectAll("text").data([0]);return n.enter().append("text").classed(Vg.labelClass,!0).classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1}),n.call(Sr.font,r.font).text(e.step.label).call(er.convertToTspans,r._gd),n}function rv(t,r){var n=t.selectAll("g."+Vg.labelsClass).data([0]),i=r._dims;n.enter().append("g").classed(Vg.labelsClass,!0);var a=n.selectAll("g."+Vg.labelGroupClass).data(i.labelSteps);a.enter().append("g").classed(Vg.labelGroupClass,!0),a.exit().remove(),a.each(function(t){var n=e.select(this);n.call(ev,t,r),Sr.setTranslate(n,lv(r,t.fraction),Vg.tickOffset+r.ticklen+r.font.size*Xg+Vg.labelOffset+i.currentValueTotalHeight)})}function nv(t,e,r,n,i){var a=Math.round(n*(r.steps.length-1));a!==r.active&&iv(t,e,r,a,!0,i)}function iv(t,e,r,n,i,a){var o=r.active;r._input.active=r.active=n;var s=r.steps[r.active];e.call(sv,r,r.active/(r.steps.length-1),a),e.call($g,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:o}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=a):(e._nextMethod={step:s,doCallback:i,doTransition:a},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&_n.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function av(t,r,n){var i=n.node(),a=e.select(r);function o(){return n.data()[0]}t.on("mousedown",function(){var t=o();r.emit("plotly_sliderstart",{slider:t});var s=n.select("."+Vg.gripRectClass);e.event.stopPropagation(),e.event.preventDefault(),s.call(Oe.fill,t.activebgcolor);var l=uv(t,e.mouse(i)[0]);nv(r,n,t,l,!0),t._dragging=!0,a.on("mousemove",function(){var t=o(),a=uv(t,e.mouse(i)[0]);nv(r,n,t,a,!1)}),a.on("mouseup",function(){var t=o();t._dragging=!1,s.call(Oe.fill,t.bgcolor),a.on("mouseup",null),a.on("mousemove",null),r.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function ov(t,r){var n=t.selectAll("rect."+Vg.tickRectClass).data(r.steps),i=r._dims;n.enter().append("rect").classed(Vg.tickRectClass,!0),n.exit().remove(),n.attr({width:r.tickwidth+"px","shape-rendering":"crispEdges"}),n.each(function(t,n){var a=n%i.labelStride==0,o=e.select(this);o.attr({height:a?r.ticklen:r.minorticklen}).call(Oe.fill,r.tickcolor),Sr.setTranslate(o,lv(r,n/(r.steps.length-1))-.5*r.tickwidth,(a?Vg.tickOffset:Vg.minorTickOffset)+i.currentValueTotalHeight)})}function sv(t,e,r,n){var i=t.select("rect."+Vg.gripRectClass),a=lv(e,r);if(!e._invokingCommand){var o=i;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(a-.5*Vg.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function lv(t,e){var r=t._dims;return r.inputAreaStart+Vg.stepInset+(r.inputAreaLength-2*Vg.stepInset)*Math.min(1,Math.max(0,e))}function uv(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-Vg.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*Vg.stepInset-2*r.inputAreaStart)))}function cv(t,e,r){var n=t.selectAll("rect."+Vg.railTouchRectClass).data([0]),i=r._dims;n.enter().append("rect").classed(Vg.railTouchRectClass,!0).call(av,e,t,r).style("pointer-events","all"),n.attr({width:i.inputAreaLength,height:Math.max(i.inputAreaWidth,Vg.tickOffset+r.ticklen+i.labelHeight)}).call(Oe.fill,r.bgcolor).attr("opacity",0),Sr.setTranslate(n,0,i.currentValueTotalHeight)}function hv(t,e){var r=t.selectAll("rect."+Vg.railRectClass).data([0]),n=e._dims;r.enter().append("rect").classed(Vg.railRectClass,!0);var i=n.inputAreaLength-2*Vg.railInset;r.attr({width:i,height:Vg.railWidth,rx:Vg.railRadius,ry:Vg.railRadius,"shape-rendering":"crispEdges"}).call(Oe.stroke,e.bordercolor).call(Oe.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),Sr.setTranslate(r,Vg.railInset,.5*(n.inputAreaWidth-Vg.railWidth)+n.currentValueTotalHeight)}var fv={moduleType:"component",name:Vg.name,layoutAttributes:Hg,supplyLayoutDefaults:function(t,e){ld(t,e,{name:Gg,handleItemDefaults:Yg})},draw:function(t){var r=t._fullLayout,n=function(t,e){for(var r=t[Vg.name],n=[],i=0;i0?[0]:[]);if(i.enter().append("g").classed(Vg.containerClassName,!0).style("cursor","ew-resize"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call($g,r).call(hv,r).call(rv,r).call(ov,r).call(cv,t,r).call(tv,t,r);var n=r._dims;Sr.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(sv,r,r.active/(r.steps.length-1),!1),e.call($g,r)}(t,e.select(this),r)}})}}},pv=m.extendFlat,dv=(0,ye.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:pv({},Ug,{}),font:T({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:C.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),gv={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},vv=gv.name,mv=dv.buttons;function yv(t,e,r){function n(r,n){return ne.coerce(t,e,dv,r,n)}n("visible",function(t,e){var r,n,i=t.buttons||[],a=e.buttons=[];function o(t,e){return ne.coerce(r,n,mv,t,e)}for(var s=0;s0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),ne.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),ne.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var xv=bv;function bv(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}bv.barWidth=2,bv.barLength=20,bv.barRadius=2,bv.barPad=1,bv.barColor="#808BA4",bv.prototype.enable=function(t,r,n){var i=this.gd._fullLayout,a=i.width,o=i.height;this.position=t;var s,l,u,c,h=this.position.l,f=this.position.w,p=this.position.t,d=this.position.h,g=this.position.direction,v="down"===g,m="left"===g,y="up"===g,x=f,b=d;v||m||"right"===g||y||(this.position.direction="down",v=!0),v||y?(l=(s=h)+x,v?(u=p,b=(c=Math.min(u+b,o))-u):b=(c=p+b)-(u=Math.max(c-b,0))):(c=(u=p)+b,m?x=(l=h+x)-(s=Math.max(l-x,0)):(s=h,x=(l=Math.min(s+x,a))-s)),this._box={l:s,t:u,w:x,h:b};var _=f>x,w=bv.barLength+2*bv.barPad,M=bv.barWidth+2*bv.barPad,A=h,k=p+d;k+M>o&&(k=o-M);var T=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);T.exit().on(".drag",null).remove(),T.enter().append("rect").classed("scrollbar-horizontal",!0).call(Oe.fill,bv.barColor),_?(this.hbar=T.attr({rx:bv.barRadius,ry:bv.barRadius,x:A,y:k,width:w,height:M}),this._hbarXMin=A+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var S=d>b,E=bv.barWidth+2*bv.barPad,C=bv.barLength+2*bv.barPad,L=h+f,z=p;L+E>a&&(L=a-E);var P=this.container.selectAll("rect.scrollbar-vertical").data(S?[0]:[]);P.exit().on(".drag",null).remove(),P.enter().append("rect").classed("scrollbar-vertical",!0).call(Oe.fill,bv.barColor),S?(this.vbar=P.attr({rx:bv.barRadius,ry:bv.barRadius,x:L,y:z,width:E,height:C}),this._vbarYMin=z+C/2,this._vbarTranslateMax=b-C):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var I=this.id,D=s-.5,O=S?l+E+.5:l+.5,R=u-.5,F=_?c+M+.5:c+.5,B=i._topdefs.selectAll("#"+I).data(_||S?[0]:[]);if(B.exit().remove(),B.enter().append("clipPath").attr("id",I).append("rect"),_||S?(this._clipRect=B.select("rect").attr({x:Math.floor(D),y:Math.floor(R),width:Math.ceil(O)-Math.floor(D),height:Math.ceil(F)-Math.floor(R)}),this.container.call(Sr.setClipUrl,I),this.bg.attr({x:h,y:p,width:f,height:d})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Sr.setClipUrl,null),delete this._clipRect),_||S){var N=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(N);var j=e.behavior.drag().on("dragstart",function(){e.event.sourceEvent.preventDefault(),e.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),S&&this.vbar.on(".drag",null).call(j)}this.setTranslate(r,n)},bv.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Sr.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},bv.prototype._onBoxDrag=function(){var t=this.translateX,r=this.translateY;this.hbar&&(t-=e.event.dx),this.vbar&&(r-=e.event.dy),this.setTranslate(t,r)},bv.prototype._onBoxWheel=function(){var t=this.translateX,r=this.translateY;this.hbar&&(t+=e.event.deltaY),this.vbar&&(r+=e.event.deltaY),this.setTranslate(t,r)},bv.prototype._onBarDrag=function(){var t=this.translateX,r=this.translateY;if(this.hbar){var n=t+this._hbarXMin,i=n+this._hbarTranslateMax;t=(ne.constrain(e.event.x,n,i)-n)/(i-n)*(this.position.w-this._box.w)}if(this.vbar){var a=r+this._vbarYMin,o=a+this._vbarTranslateMax;r=(ne.constrain(e.event.y,a,o)-a)/(o-a)*(this.position.h-this._box.h)}this.setTranslate(t,r)},bv.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=ne.constrain(t||0,0,r),e=ne.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(Sr.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(Sr.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var a=e/n;this.vbar.call(Sr.setTranslate,t,e+a*this._vbarTranslateMax)}};var _v=Qe.LINE_SPACING;function wv(t){return t._index}function Mv(t,e){return+t.attr(gv.menuIndexAttrName)===e._index}function Av(t,e,r,n,i,a,o,s){e._input.active=e.active=o,"buttons"===e.type?Tv(t,n,null,null,e):"dropdown"===e.type&&(i.attr(gv.menuIndexAttrName,"-1"),kv(t,n,i,a,e),s||Tv(t,n,i,a,e))}function kv(t,e,r,n,i){var a=e.selectAll("g."+gv.headerClassName).data([0]),o=i._dims;a.enter().append("g").classed(gv.headerClassName,!0).style("pointer-events","all");var s=i.active,l=i.buttons[s]||gv.blankHeaderOpts,u={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};a.call(Sv,i,l,t).call(Dv,i,u,c);var h=e.selectAll("text."+gv.headerArrowClassName).data([0]);h.enter().append("text").classed(gv.headerArrowClassName,!0).classed("user-select-none",!0).attr("text-anchor","end").call(Sr.font,i.font).text(gv.arrowSymbol[i.direction]),h.attr({x:o.headerWidth-gv.arrowOffsetX+i.pad.l,y:o.headerHeight/2+gv.textOffsetY+i.pad.t}),a.on("click",function(){r.call(Ov),r.attr(gv.menuIndexAttrName,Mv(r,i)?-1:String(i._index)),Tv(t,e,r,n,i)}),a.on("mouseover",function(){a.call(zv)}),a.on("mouseout",function(){a.call(Pv,i)}),Sr.setTranslate(e,o.lx,o.ly)}function Tv(t,r,n,i,a){n||(n=r).attr("pointer-events","all");var o=function(t){return-1==+t.attr(gv.menuIndexAttrName)}(n)&&"buttons"!==a.type?[]:a.buttons,s="dropdown"===a.type?gv.dropdownButtonClassName:gv.buttonClassName,l=n.selectAll("g."+s).data(o),u=l.enter().append("g").classed(s,!0),c=l.exit();"dropdown"===a.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var h=0,f=0,p=a._dims,d=-1!==["up","down"].indexOf(a.direction);"dropdown"===a.type&&(d?f=p.headerHeight+gv.gapButtonHeader:h=p.headerWidth+gv.gapButtonHeader),"dropdown"===a.type&&"up"===a.direction&&(f=-gv.gapButtonHeader+gv.gapButton-p.openHeight),"dropdown"===a.type&&"left"===a.direction&&(h=-gv.gapButtonHeader+gv.gapButton-p.openWidth);var g={x:p.lx+h+a.pad.l,y:p.ly+f+a.pad.t,yPad:gv.gapButton,xPad:gv.gapButton,index:0},v={l:g.x+a.borderwidth,t:g.y+a.borderwidth};l.each(function(o,s){var u=e.select(this);u.call(Sv,a,o,t).call(Dv,a,g),u.on("click",function(){e.event.defaultPrevented||(Av(t,a,0,r,n,i,s),o.execute&&_n.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:a,button:o,active:a.active}))}),u.on("mouseover",function(){u.call(zv)}),u.on("mouseout",function(){u.call(Pv,a),l.call(Lv,a)})}),l.call(Lv,a),d?(v.w=Math.max(p.openWidth,p.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(p.openHeight,p.headerHeight)),v.direction=a.direction,i&&(l.size()?function(t,e,r,n,i,a){var o,s,l,u=i.direction,c="up"===u||"down"===u,h=i._dims,f=i.active;if(c)for(s=0,l=0;l0?[0]:[]);if(i.enter().append("g").classed(gv.containerClassName,!0).style("cursor","pointer"),i.exit().remove(),i.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nb.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&ne.log("Clearing previous rejected promises from queue."),t._promises=[]},Vv.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(_n.subplotsRegistry.cartesian||{}).attrRegex,i=(_n.subplotsRegistry.gl3d||{}).attrRegex,a=Object.keys(t);for(e=0;e3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Oe.clean(t),t},Vv.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),i=0;i0)return t.substr(0,e)}Vv.hasParent=function(t,e){for(var r=Xv(e);r;){if(r in t)return!0;r=Xv(r)}return!1};var Zv=["x","y","z"];Vv.clearAxisTypes=function(t,e,r){for(var n=0;n1&&_.warn("Full array edits are incompatible with other edits",i);var h=r[""][""];if($v(h))e.set(null);else{if(!Array.isArray(h))return _.warn("Unrecognized full array edit value",i,h),!0;e.set(h)}return!l&&(a(u,c),o(t),!0)}var f,p,d,g,v,m,y,x=Object.keys(r).map(Number).sort(Kv),b=e.get(),w=b||[],M=W(c,i).get(),k=[],T=-1,S=w.length;for(f=0;fw.length-(y?0:1))_.warn("index out of range",i,d);else if(void 0!==m)v.length>1&&_.warn("Insertion & removal are incompatible with edits to the same index.",i,d),$v(m)?k.push(d):y?("add"===m&&(m={}),w.splice(d,0,m),M&&M.splice(d,0,{})):_.warn("Unrecognized full object edit value",i,d,m),-1===T&&(T=d);else for(p=0;p=0;f--)w.splice(k[f],1),M&&M.splice(k[f],1);if(w.length?b||e.set(w):e.set(null),l)return!1;if(a(u,c),s!==A){var E;if(-1===T)E=x;else{for(S=Math.max(w.length,S),E=[],f=0;f=T);f++)E.push(d);for(f=T;f1?(m=["toggleHover"],y=["resetViews"]):s?(v=["zoomInGeo","zoomOutGeo"],m=["hoverClosestGeo"],y=["resetGeo"]):o?(m=["hoverClosest3d"],y=["resetCameraDefault3d","resetCameraLastSave3d"]):h?(m=["toggleHover"],y=["resetViewMapbox"]):m=u?["hoverClosestGl2d"]:l?["hoverClosestPie"]:["toggleHover"],a&&(m=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!a&&!u||p||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==y[0]&&(y=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(a||u)&&!p||c?x=["zoom2d","pan2d"]:h||s?x=["pan2d"]:f&&(x=["zoom2d"]),function(t){for(var e=!1,r=0;r=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function Em(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function Cm(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Oe.background,stroke:Oe.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function Lm(t){t.selectAll(".select-outline").remove()}function zm(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),Pm(t,e,i,a)}function Pm(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function Im(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function Dm(t){_m&&t.data&&t._context.showTips&&(ne.notifier(ne._(t,"Double-click to zoom back out"),"long"),_m=!1)}function Om(t){return"lasso"===t||"select"===t}function Rm(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,bm)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function Fm(t,e){if(Ea){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}var Bm={makeDragBox:function(t,r,n,i,a,o,l,u){var c,h,f,p,d,g,v,m,y,x,b,_,w,M=t._fullLayout,A=t._fullLayout._zoomlayer,k=l+u==="nsew",T=1===(l+u).length;function S(){h=[r.xaxis],f=[r.yaxis];var e=h[0],n=f[0];g=e._length,v=n._length;var i,a,o=M._axisConstraintGroups,s=[e._id],A=[n._id];c=[r].concat(l&&u?r.overlays:[]);for(var k=1;kbm||o>bm?(F="xy",a/g>o/v?(o=a*v/g,z>i?I.t=z-o:I.b=z+o):(a=o*g/v,L>n?I.l=L-a:I.r=L+a),N.attr("d",Rm(I))):s():!y||o rect").call(Sr.setTranslate,i,a).call(Sr.setScale,r,n);var P=x.plot.selectAll(".scatterlayer .trace, .boxlayer .trace, .violinlayer .trace");x.plot.call(Sr.setTranslate,L,z).call(Sr.setScale,1/r,1/n),P.selectAll(".point").call(Sr.setPointGroupScale,r,n),P.selectAll(".textpoint").call(Sr.setTextPointsScale,r,n),P.call(Sr.hideOutsideRangePoints,x),x.plot.selectAll(".barlayer .trace").call(Sr.hideOutsideRangePoints,x,".bartext")}}}return l.length*u.length!=1&&Fm(E,function(e){if(t._context.scrollZoom||M._enablescrollzoom){if(null===G&&Lm(A),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var r=t.querySelector(".plotly");if(S(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(G);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var i,a=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=Y.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,c=(o.bottom-e.clientY)/o.height;if(u||b){for(u||(s=.5),i=0;i=t[1]||i[1]<=t[0])&&a[0]e[0])return!0}return!1}(r,i,p)?(f.push(t),p.push([r,i])):a=[0];var o=e.plotgroup.selectAll(".bg").data(a);o.enter().append("rect").classed("bg",!0),o.exit().remove(),o.each(function(){e.bg=o;var t=e.plotgroup.node();t.insertBefore(this,t.childNodes[0])})});var d=n._bgLayer.selectAll(".bg").data(f);return d.enter().append("rect").classed("bg",!0),d.exit().remove(),d.each(function(t){n._plots[t].bg=e.select(this)}),h.each(function(t){var e=n._plots[t],i=e.xaxis,u=e.yaxis;e.bg&&s&&e.bg.call(Sr.setRect,i._offset-a,u._offset-a,i._length+2*a,u._length+2*a).call(Oe.fill,n.plot_bgcolor).style("stroke-width",0),e.clipId="clip"+n._uid+t+"plot";var c,h,f=n._clips.selectAll("#"+e.clipId).data([0]);for(f.enter().append("clipPath").attr({class:"plotclip",id:e.clipId}).append("rect"),f.selectAll("rect").attr({width:i._length,height:u._length}),Sr.setTranslate(e.plot,i._offset,u._offset),e._hasClipOnAxisFalse?(c=null,h=e.clipId):(c=e.clipId,h=null),Sr.setClipUrl(e.plot,c),r=0;rXm*p)||m)for(r=0;rS&&Lk&&(k=L);s/=(k-A)/(2*T),A=i.l2r(A),k=i.l2r(k),i.range=i._input.range=_=0?u.angularAxis.domain:e.extent(x),A=Math.abs(x[1]-x[0]);_&&!b&&(A=0);var k=M.slice();w&&b&&(k[1]+=A);var T=u.angularAxis.ticksCount||4;T>8&&(T=T/(T/8)+T%8),u.angularAxis.ticksStep&&(T=(k[1]-k[0])/T);var S=u.angularAxis.ticksStep||(k[1]-k[0])/(T*(u.minorTicks+1));y&&(S=Math.max(Math.round(S),1)),k[2]||(k[2]=S);var E=e.range.apply(this,k);if(E=E.map(function(t,e){return parseFloat(t.toPrecision(12))}),i=e.scale.linear().domain(k.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),s.layout.angularAxis.domain=i.domain(),s.layout.angularAxis.endPadding=w?A:0,void 0===(t=e.select(this).select("svg.chart-root"))||t.empty()){var C=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),L=this.appendChild(this.ownerDocument.importNode(C.documentElement,!0));t=e.select(L)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var z,P=t.select(".chart-group"),I={fill:"none",stroke:u.tickColor},D={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){z=t.select(".legend-group").attr({transform:"translate("+[g,u.margin.top]+")"}).style({display:"block"});var O=c.map(function(t,e){var r=ty.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});ty.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:Qm({},ty.Legend.defaultConfig().legendConfig,{container:z,elements:O,reverseOrder:u.legend.reverseOrder})})();var R=z.node().getBBox();g=Math.min(u.width-R.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,g=Math.max(10,g),m=[u.margin.left+g,u.margin.top+g],n.range([0,g]),s.layout.radialAxis.domain=n.domain(),z.attr("transform","translate("+[m[0]+g,m[1]-g]+")")}else z=t.select(".legend-group").style({display:"none"});t.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),P.attr("transform","translate("+m+")").style({cursor:"crosshair"});var F=[(u.width-(u.margin.left+u.margin.right+2*g+(R?R.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*g))/2];if(F[0]=Math.max(0,F[0]),F[1]=Math.max(0,F[1]),t.select(".outer-group").attr("transform","translate("+F+")"),u.title){var B=t.select("g.title-group text").style(D).text(u.title),N=B.node().getBBox();B.attr({x:m[0]-N.width/2,y:m[1]-g-20})}var j=t.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var V=j.selectAll("circle.grid-circle").data(n.ticks(5));V.enter().append("circle").attr({class:"grid-circle"}).style(I),V.attr("r",n),V.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(I);var U=t.select("circle.background-circle").attr({r:g}).style({fill:u.backgroundColor,stroke:u.stroke});function q(t,e){return i(t)%360+u.orientation}if(u.radialAxis.visible){var H=e.svg.axis().scale(n).ticks(5).tickSize(5);j.call(H).attr({transform:"rotate("+u.radialAxis.orientation+")"}),j.selectAll(".domain").style(I),j.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(D).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,D["font-size"]]+")":"translate("+[0,D["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(E),W=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(t,e){return"rotate("+q(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),G.exit().remove(),W.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(I),W.selectAll(".minor").style({stroke:u.minorTickColor}),G.select("line.grid-line").attr({x1:u.tickLength?g-u.tickLength:0,x2:g}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),W.append("text").classed("axis-text",!0).style(D);var Y=G.select("text.axis-text").attr({x:g+u.labelOffset,dy:$m+"em",transform:function(t,e){var r=q(t),n=g+u.labelOffset,i=u.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":y?y[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(D);u.angularAxis.rewriteTicks&&Y.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var X=e.max(P.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));z.attr({transform:"translate("+[g+X,u.margin.top]+")"});var Z=t.select("g.geometry-group").selectAll("g").size()>0,J=t.select("g.geometry-group").selectAll("g.geometry").data(c);if(J.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),J.exit().remove(),c[0]||Z){var K=[];c.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=i,r.container=J.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=u.orientation,r.direction=u.direction,r.index=e,K.push({data:t,geometryConfig:r})});var Q=[];e.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(K).forEach(function(t,e){"unstacked"===t.key?Q=Q.concat(t.values.map(function(t,e){return[t]})):Q.push(t.values)}),Q.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return Qm(ty[r].defaultConfig(),t)});ty[r]().config(n)()})}var $,tt,et=t.select(".guides-group"),rt=t.select(".tooltips-group"),nt=ty.tooltipPanel().config({container:rt,fontSize:8})(),it=ty.tooltipPanel().config({container:rt,fontSize:8})(),at=ty.tooltipPanel().config({container:rt,hasTick:!0})();if(!b){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});P.on("mousemove.angular-guide",function(t,e){var r=ty.util.getMousePos(U).angle;ot.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-u.orientation)%360;$=i.invert(n);var a=ty.util.convertToCartesian(g+12,r+180);nt.text(ty.util.round($)).move([a[0]+m[0],a[1]+m[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var st=et.select("circle").style({stroke:"grey",fill:"none"});P.on("mousemove.radial-guide",function(t,e){var r=ty.util.getMousePos(U).radius;st.attr({r:r}).style({opacity:.5}),tt=n.invert(ty.util.getMousePos(U).radius);var i=ty.util.convertToCartesian(r,u.radialAxis.orientation);it.text(ty.util.round(tt)).move([i[0]+m[0],i[1]+m[1]])}).on("mouseout.radial-guide",function(t,e){st.style({opacity:0}),at.hide(),nt.hide(),it.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(r,n){var i=e.select(this),a=this.style.fill,o="black",s=this.style.opacity||1;if(i.attr({"data-opacity":s}),a&&"none"!==a){i.attr({"data-fill":a}),o=e.hsl(a).darker().toString(),i.style({fill:o,opacity:1});var l={t:ty.util.round(r[0]),r:ty.util.round(r[1])};b&&(l.t=y[r[0]]);var u="t: "+l.t+", r: "+l.r,c=this.getBoundingClientRect(),h=t.node().getBoundingClientRect(),f=[c.left+c.width/2-F[0]-h.left,c.top+c.height/2-F[1]-h.top];at.config({color:o}).text(u),at.move(f)}else a=this.style.stroke||"black",i.attr({"data-stroke":a}),o=e.hsl(a).darker().toString(),i.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,r){if(0!=e.event.which)return!1;e.select(this).attr("data-fill")&&at.show()}).on("mouseout.tooltip",function(t,r){at.hide();var n=e.select(this),i=n.attr("data-fill");i?n.style({fill:i,opacity:n.attr("data-opacity")}):n.style({stroke:n.attr("data-stroke"),opacity:n.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return a;var e=ty.util.cloneJson(t);return e.data.forEach(function(t,e){a.data[e]||(a.data[e]={}),Qm(a.data[e],ty.Axis.defaultConfig().data[0]),Qm(a.data[e],t)}),Qm(a.layout,ty.Axis.defaultConfig().layout),Qm(a.layout,e.layout),this},u.getLiveConfig=function(){return s},u.getinputConfig=function(){return o},u.radialScale=function(t){return n},u.angularScale=function(t){return i},u.svg=function(){return t},e.rebind(u,l,"on"),u},ty.Axis.defaultConfig=function(t,r){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:e.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},ty.util={},ty.DATAEXTENT="dataExtent",ty.AREA="AreaChart",ty.LINE="LinePlot",ty.DOT="DotPlot",ty.BAR="BarChart",ty.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},ty.util._extend=function(t,e){for(var r in t)e[r]=t[r]},ty.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},ty.util.dataFromEquation2=function(t,r){var n=r||6;return e.range(0,360+n,n).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},ty.util.dataFromEquation=function(t,r,n){var i=r||6,a=[],o=[];e.range(0,360+i,i).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return n&&(s.name=n),s},ty.util.ensureArray=function(t,r){if(void 0===t)return null;var n=[].concat(t);return e.range(r).map(function(t,e){return n[e]||n[0]})},ty.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=ty.util.ensureArray(t[e],r)}),t},ty.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},ty.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},ty.util.sumArrays=function(t,r){return e.zip(t,r).map(function(t,r){return e.sum(t)})},ty.util.arrayLast=function(t){return t[t.length-1]},ty.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},ty.util.flattenArray=function(t){for(var e=[];!ty.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},ty.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},ty.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},ty.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},ty.util.getMousePos=function(t){var r=e.mouse(t.node()),n=r[0],i=r[1],a={};return a.x=n,a.y=i,a.pos=r,a.angle=180*(Math.atan2(i,n)+Math.PI)/Math.PI,a.radius=Math.sqrt(n*n+i*i),a},ty.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i0)){var l=e.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:c(s),transform:function(t,e){return"rotate("+(r.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return d.fill(n,i,a)},"fill-opacity":0,stroke:function(t,e){return d.stroke(n,i,a)},"stroke-width":function(t,e){return d["stroke-width"](n,i,a)},"stroke-dasharray":function(t,e){return d["stroke-dasharray"](n,i,a)},opacity:function(t,e){return d.opacity(n,i,a)},display:function(t,e){return d.display(n,i,a)}})}};var h=r.angularScale.range(),f=Math.abs(h[1]-h[0])/o[0].length*Math.PI/180,p=e.svg.arc().startAngle(function(t){return-f/2}).endAngle(function(t){return f/2}).innerRadius(function(t){return r.radialScale(l+(t[2]||0))}).outerRadius(function(t){return r.radialScale(l+(t[2]||0))+r.radialScale(t[1])});u.arc=function(t,n,i){e.select(this).attr({class:"mark arc",d:p,transform:function(t,e){return"rotate("+(r.orientation+s(t[0])+90)+")"}})};var d={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,r,i){return n[t[i].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return void 0===t[n].data.visible||t[n].data.visible?"block":"none"}},g=e.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(d).each(u[r.geometryType]),v.exit().remove(),g.exit().remove()})}return i.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),Qm(t[r],ty.PolyChart.defaultConfig()),Qm(t[r],e)}),this):t},i.getColorScale=function(){},e.rebind(i,r,"on"),i},ty.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:e.scale.category20()}}},ty.BarChart=function(){return ty.PolyChart()},ty.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},ty.AreaChart=function(){return ty.PolyChart()},ty.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},ty.DotPlot=function(){return ty.PolyChart()},ty.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},ty.LinePlot=function(){return ty.PolyChart()},ty.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},ty.Legend=function(){var t=ty.Legend.defaultConfig(),r=e.dispatch("hover");function n(){var r=t.legendConfig,i=t.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=Qm({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=e.merge(i);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||void 0===r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var o=r.container;("string"==typeof o||o.nodeName)&&(o=e.select(o));var s=a.map(function(t,e){return t.color}),l=r.fontSize,u=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,c=u?r.height:l*a.length,h=o.classed("legend-group",!0).selectAll("svg").data([0]),f=h.enter().append("svg").attr({width:300,height:c+l,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});f.append("g").classed("legend-axis",!0),f.append("g").classed("legend-marks",!0);var p=e.range(a.length),d=e.scale[u?"linear":"ordinal"]().domain(p).range(s),g=e.scale[u?"linear":"ordinal"]().domain(p)[u?"range":"rangePoints"]([0,c]);if(u){var v=h.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),h.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var m=h.select(".legend-marks").selectAll("path.legend-mark").data(a);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[l/2,g(e)+l/2]+")"},d:function(t,r){var n,i,a,o=t.symbol;return a=3*(i=l),"line"===(n=o)?"M"+[[-i/2,-i/12],[i/2,-i/12],[i/2,i/12],[-i/2,i/12]]+"Z":-1!=e.svg.symbolTypes.indexOf(n)?e.svg.symbol().type(n).size(a)():e.svg.symbol().type("square").size(a)()},fill:function(t,e){return d(e)}}),m.exit().remove()}var y=e.svg.axis().scale(g).orient("right"),x=h.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:l,l/2]+")"}).call(y);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),x.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),n}return n.config=function(e){return arguments.length?(Qm(t,e),this):t},e.rebind(n,r,"on"),n},ty.Legend.defaultConfig=function(t,e){return{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:!1}}},ty.tooltipPanel=function(){var t,r,n,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},a="tooltip-"+ty.tooltipPanel.uid++,o=10,s=function(){var e=(t=i.container.selectAll("g."+a).data([0])).enter().append("g").classed(a,!0).style({"pointer-events":"none",display:"none"});return n=e.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),r=e.append("text").attr({dx:i.padding+o,dy:.3*+i.fontSize}),s};return s.text=function(a){var l=e.hsl(i.color).l,u=l>=.5?"#aaa":"white",c=l>=.5?"black":"white",h=a||"";r.style({fill:c,"font-size":i.fontSize+"px"}).text(h);var f=i.padding,p=r.node().getBBox(),d={fill:i.color,stroke:u,"stroke-width":"2px"},g=p.width+2*f+o,v=p.height+2*f;return n.attr({d:"M"+[[o,-v/2],[o,-v/4],[i.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(d),t.attr({transform:"translate("+[o,-v/2+2*f]+")"}),t.style({display:"block"}),s},s.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),s},s.hide=function(){if(t)return t.style({display:"none"}),s},s.show=function(){if(t)return t.style({display:"block"}),s},s.config=function(t){return Qm(i,t),s},s},ty.tooltipPanel.uid=1,ty.adapter={},ty.adapter.plotly=function(){var t={convert:function(t,r){var n={};if(t.data&&(n.data=t.data.map(function(t,e){var n=Qm({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,e){ty.util.translator.apply(null,t.concat(r))}),r||delete n.marker,r&&delete n.groupId,r?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!r&&t.layout&&"stack"===t.layout.barmode)){var i=ty.util.duplicates(n.data.map(function(t,e){return t.geometry}));n.data.forEach(function(t,e){var r=i.indexOf(t.geometry);-1!=r&&(n.data[e].groupId=r)})}if(t.layout){var a=Qm({},t.layout);if([[a,["plot_bgcolor"],["backgroundColor"]],[a,["showlegend"],["showLegend"]],[a,["radialaxis"],["radialAxis"]],[a,["angularaxis"],["angularAxis"]],[a.angularaxis,["showline"],["gridLinesVisible"]],[a.angularaxis,["showticklabels"],["labelsVisible"]],[a.angularaxis,["nticks"],["ticksCount"]],[a.angularaxis,["tickorientation"],["tickOrientation"]],[a.angularaxis,["ticksuffix"],["ticksSuffix"]],[a.angularaxis,["range"],["domain"]],[a.angularaxis,["endpadding"],["endPadding"]],[a.radialaxis,["showline"],["gridLinesVisible"]],[a.radialaxis,["tickorientation"],["tickOrientation"]],[a.radialaxis,["ticksuffix"],["ticksSuffix"]],[a.radialaxis,["range"],["domain"]],[a.angularAxis,["showline"],["gridLinesVisible"]],[a.angularAxis,["showticklabels"],["labelsVisible"]],[a.angularAxis,["nticks"],["ticksCount"]],[a.angularAxis,["tickorientation"],["tickOrientation"]],[a.angularAxis,["ticksuffix"],["ticksSuffix"]],[a.angularAxis,["range"],["domain"]],[a.angularAxis,["endpadding"],["endPadding"]],[a.radialAxis,["showline"],["gridLinesVisible"]],[a.radialAxis,["tickorientation"],["tickOrientation"]],[a.radialAxis,["ticksuffix"],["ticksSuffix"]],[a.radialAxis,["range"],["domain"]],[a.font,["outlinecolor"],["outlineColor"]],[a.legend,["traceorder"],["reverseOrder"]],[a,["labeloffset"],["labelOffset"]],[a,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,e){ty.util.translator.apply(null,t.concat(r))}),r?(void 0!==a.tickLength&&(a.angularaxis.ticklen=a.tickLength,delete a.tickLength),a.tickColor&&(a.angularaxis.tickcolor=a.tickColor,delete a.tickColor)):(a.angularAxis&&void 0!==a.angularAxis.ticklen&&(a.tickLength=a.angularAxis.ticklen),a.angularAxis&&void 0!==a.angularAxis.tickcolor&&(a.tickColor=a.angularAxis.tickcolor)),a.legend&&"boolean"!=typeof a.legend.reverseOrder&&(a.legend.reverseOrder="normal"!=a.legend.reverseOrder),a.legend&&"boolean"==typeof a.legend.traceorder&&(a.legend.traceorder=a.legend.traceorder?"reversed":"normal",delete a.legend.reverseOrder),a.margin&&void 0!==a.margin.t){var o=["t","r","b","l","pad"],s=["top","right","bottom","left","pad"],l={};e.entries(a.margin).forEach(function(t,e){l[s[o.indexOf(t.key)]]=t.value}),a.margin=l}r&&(delete a.needsEndSpacing,delete a.minorTickColor,delete a.minorTicks,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksStep,delete a.angularaxis.rewriteTicks,delete a.angularaxis.nticks,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksStep,delete a.radialaxis.rewriteTicks,delete a.radialaxis.nticks),n.layout=a}return n}};return t};var ey,ry=ne.extendDeepAll,ny=ey={};ny.framework=function(t){var r,n,i,a,o,s=new function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),r=r?ry(r,n):n,i||(i=Km.Axis()),a=Km.adapter.plotly().convert(r),i.config(a).render(o),t.data=r.data,t.layout=r.layout,ny.fillLayout(t),r}return l.isPolar=!0,l.svg=function(){return i.svg()},l.getConfig=function(){return r},l.getLiveConfig=function(){return Km.adapter.plotly().convert(i.getLiveConfig(),!0)},l.getLiveScales=function(){return{t:i.angularScale(),r:i.radialScale()}},l.setUndoPoint=function(){var t,e,i=this,a=Km.util.cloneJson(r);t=a,e=n,s.add({undo:function(){e&&i(e)},redo:function(){i(t)}}),n=Km.util.cloneJson(a)},l.undo=function(){s.undo()},l.redo=function(){s.redo()},l},ny.fillLayout=function(t){var r=e.select(t).selectAll(".plot-container"),n=r.selectAll(".svg-container"),i=t.framework&&t.framework.svg&&t.framework.svg(),a={width:800,height:600,paper_bgcolor:Oe.background,_container:r,_paperdiv:n,_paper:i};t._fullLayout=ry(a,t.layout)};var iy={};(iy=Km).manager=ey;var ay={},oy=Gm.enforce,sy=Gm.clean,ly=Nn,uy=0;function cy(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){ne.error(t)}}function hy(t,e){cy(t,Oe.combine(e,"white"))}function fy(t,e){t._context||(t._context=ne.extendDeep({},b));var r,n,i,a=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function gy(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),dy(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&dy(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function vy(t,e,n,i,a){!function(t,e,r,n){var i=ne.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!ne.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var a in dy(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,n,i);for(var o=function(t,e,n,i){var a,o,s,l,u,c=ne.isPlainObject(i),h=[];for(var f in Array.isArray(n)||(n=[n]),n=py(n,t.data.length-1),e)for(var p=0;p0&&"string"!=typeof _.parts[M-1];)A--;var k=_.parts[A],T=_.parts[A-1]+"."+k,S=_.parts.slice(0,A).join("."),E=ne.nestedProperty(t.layout,S).get(),C=ne.nestedProperty(o,S).get(),L=_.get();if(void 0!==w){d[b]=w,g[b]="reverse"===k?w:yy(L);var z=nn.getLayoutValObject(o,_.parts);if(z&&z.impliedEdits&&null!==w)for(var I in z.impliedEdits)v(ne.relativeAttr(b,I),z.impliedEdits[I]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=t._initialAutoSize[b];else if(T.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(T),ne.nestedProperty(o,S+"._inputRange").set(null);else if(T.match(/^[xyz]axis[0-9]*\.autorange$/)){x(T),ne.nestedProperty(o,S+"._inputRange").set(null);var D=ne.nestedProperty(o,S).get();D._inputDomain&&(D._input.domain=D._inputDomain.slice())}else T.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&ne.nestedProperty(o,S+"._inputDomain").set(null);if("type"===k){var O=E,R="linear"===C.type&&"log"===w,F="log"===C.type&&"linear"===w;if(R||F){if(O&&O.range)if(C.autorange)R&&(O.range=O.range[1]>O.range[0]?[1,2]:[2,1]);else{var B=O.range[0],N=O.range[1];R?(B<=0&&N<=0&&v(S+".autorange",!0),B<=0?B=N/1e6:N<=0&&(N=B/1e6),v(S+".range[0]",Math.log(B)/Math.LN10),v(S+".range[1]",Math.log(N)/Math.LN10)):(v(S+".range[0]",Math.pow(10,B)),v(S+".range[1]",Math.pow(10,N)))}else v(S+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],P.getComponentMethod("annotations","convertCoords")(t,C,w,v),P.getComponentMethod("images","convertCoords")(t,C,w,v)}else v(S+".autorange",!0),v(S+".range",null);ne.nestedProperty(o,S+"._inputRange").set(null)}else if(k.match(Te.AX_NAME_PATTERN)){var j=ne.nestedProperty(o,b).get(),V=(w||{}).type;V&&"-"!==V||(V="linear"),P.getComponentMethod("annotations","convertCoords")(t,j,V,v),P.getComponentMethod("images","convertCoords")(t,j,V,v)}var U=Jv.containerArrayMatch(b);if(U){r=U.array,n=U.index;var q=U.property,H=(ne.nestedProperty(a,r)||[])[n]||{},G=H,W=z||{editType:"calc"},Y=-1!==W.editType.indexOf("calcIfAutorange");""===n?(Y?p.calc=!0:ye.update(p,W),Y=!1):""===q&&(G=w,Jv.isAddVal(w)?g[b]=null:Jv.isRemoveVal(w)?(g[b]=H,G=H):ne.warn("unrecognized full object value",e)),Y&&(wy(t,G,"x")||wy(t,G,"y"))?p.calc=!0:ye.update(p,W),u[r]||(u[r]={});var X=u[r][n];X||(X=u[r][n]={}),X[q]=w,delete e[b]}else"reverse"===k?(E.range?E.range.reverse():(v(S+".autorange",!0),E.range=[1,0]),C.autorange?p.calc=!0:p.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==L&&"select"!==L?p.plot=!0:z?ye.update(p,z):p.calc=!0,_.set(w))}}for(r in u){Jv.applyContainerArrayChanges(t,ne.nestedProperty(a,r),u[r],p)||(p.plot=!0)}var Z=o._axisConstraintGroups||[];for(m in y)for(n=0;n=0&&r=0&&r=i.length?i[0]:i[t]:i}function s(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function l(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,_n.transition(t,e.frame.data,e.frame.layout,Vv.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function h(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var f,p,d=0;function g(t){return Array.isArray(i)?d>=i.length?t.transitionOpts=i[d]:t.transitionOpts=i[0]:t.transitionOpts=i,d++,t}var v=[],m=void 0===e||null===e,y=Array.isArray(e);if(!m&&!y&&ne.isPlainObject(e))v.push({type:"object",data:g(ne.extendFlat({},e))});else if(m||-1!==["string","number"].indexOf(typeof e))for(f=0;f0&&__)&&w.push(p);v=w}}v.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(ne.isPlainObject(e[n])){var f=e[n].name,p=(l[f]||h[f]||{}).name,d=e[n].name,g=l[p]||h[p];p&&d&&"number"==typeof d&&g&&uy<5&&(uy++,ne.warn('addFrames: overwriting frame "'+(l[p]||h[p]).name+'" with a frame whose name of type "number" also equates to "'+p+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===uy&&ne.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),h[f]={name:f},c.push({frame:_n.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=c[n].frame).name&&ne.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;l[i.name="frame "+t._transitionData._counter++];);if(l[i.name]){for(a=0;a=0;r--)n=e[r],a.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:i[n]});var s=_n.modifyFrames,l=_n.modifyFrames,u=[t,o],c=[t,a];return Nv&&Nv.add(t,s,u,l,c),_n.modifyFrames(t,a)},ay.purge=function(t){var e=(t=ne.getGraphDiv(t))._fullLayout||{},r=t._fullData||[];return _n.cleanPlot([],{},r,e),_n.purge(t),ja.purge(t),e._container&&e._container.remove(),delete t._context,t};var ky={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},Ty=Da.EventEmitter;var Sy=function(t){var e=t.emitter||new Ty,r=new Promise(function(n,i){var a=window.Image,o=t.svg,s=t.format||"png";if(ne.isIE()&&"svg"!==s){var l=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(l),t.promise?r:e.emit("error",l)}var u=t.canvas,c=t.scale||1,h=c*(t.width||300),f=c*(t.height||150),p=u.getContext("2d"),d=new a,g="data:image/svg+xml,"+encodeURIComponent(o);u.width=h,u.height=f,d.onload=function(){var r;switch("svg"!==s&&p.drawImage(d,0,0,h,f),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=g;break;default:var a="Image format is not jpeg, png, svg or webp.";if(i(new Error(a)),!t.promise)return e.emit("error",a)}n(r),t.promise||e.emit("success",r)},d.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},d.src=g});return t.promise?r:e},Ey=/"/g,Cy=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var Ly=function(t,r,n){var i,a=t._fullLayout,o=a._paper,s=a._toppaper,l=a.width,u=a.height;o.insert("rect",":first-child").call(Sr.setRect,0,0,l,u).call(Oe.fill,a.paper_bgcolor);var c=a._basePlotModules||[];for(i=0;i")?"":r.html(t).text()});return r.remove(),n}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace(Cy,"'"),ne.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},zy={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},Py=/^data:image\/\w+;base64,/;var Iy=function(t,e){var r,n,i;function a(t){return!(t in e)||ne.validate(e[t],zy[t])}if(e=e||{},ne.isPlainObject(t)?(r=t.data||[],n=t.layout||{},i=t.config||{}):(t=ne.getGraphDiv(t),r=ne.extendDeep([],t.data),n=ne.extendDeep({},t.layout),i=t._context),!a("width")||!a("height"))throw new Error("Height and width should be pixel values.");if(!a("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function s(t,r){return ne.coerce(e,o,zy,t,r)}var l=s("format"),u=s("width"),c=s("height"),h=s("scale"),f=s("setBackground"),p=s("imageDataOnly"),d=document.createElement("div");d.style.position="absolute",d.style.left="-5000px",document.body.appendChild(d);var g=ne.extendFlat({},n);u&&(g.width=u),c&&(g.height=c);var v=ne.extendFlat({},i,{staticPlot:!0,setBackground:f}),m=ky.getRedrawFunc(d);function y(){return new Promise(function(t){setTimeout(t,ky.getDelay(d._fullLayout))})}function x(){return new Promise(function(t,e){var r=Ly(d,l,h),n=d._fullLayout.width,i=d._fullLayout.height;if(ay.purge(d),document.body.removeChild(d),"svg"===l)return t(p?r:"data:image/svg+xml,"+encodeURIComponent(r));var a=document.createElement("canvas");a.id=ne.randstr(),Sy({format:l,width:n,height:i,scale:h,canvas:a,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){ay.plot(d,r,g,v).then(m).then(y).then(x).then(function(e){t(function(t){return p?t.replace(Py,""):t}(e))}).catch(function(t){e(t)})})},Dy=ne.isPlainObject,Oy=Array.isArray,Ry=ne.isArrayOrTypedArray;function Fy(t,e,r,n,i,a){a=a||[];for(var o=Object.keys(t),s=0;sh.length&&n.push(jy("unused",i,u.concat(h.length)));var v,m,y,x,b,_=h.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===f.dimensions)for(m=0;m<_;m++)if(Oy(c[m])){c[m].length>h[m].length&&n.push(jy("unused",i,u.concat(m,h[m].length)));var M=h[m].length;for(v=0;v<(w?Math.min(M,g[m].length):M);v++)y=w?g[m][v]:g,x=c[m][v],b=h[m][v],ne.validate(x,y)?b!==x&&b!==+x&&n.push(jy("dynamic",i,u.concat(m,v),x,b)):n.push(jy("value",i,u.concat(m,v),x))}else n.push(jy("array",i,u.concat(m),c[m]));else for(m=0;m<_;m++)y=w?g[m]:g,x=c[m],b=h[m],ne.validate(x,y)?b!==x&&b!==+x&&n.push(jy("dynamic",i,u.concat(m),x,b)):n.push(jy("value",i,u.concat(m),x))}else if(f.items&&!p&&Oy(c)){var A,k,T=g[Object.keys(g)[0]],S=[];for(A=0;A1&&a.push(jy("object","layout"))),_n.supplyDefaults(o);for(var s=o._fullData,l=r.length,u=0;u-1&&(s[u[r]].title="");for(r=0;r=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}},cx=ne.isArrayOrTypedArray,hx=function(t,e,r,n){var i=!1;if(e.marker){var a=e.marker.color,o=(e.marker.line||{}).color;a&&!cx(a)?i=a:o&&!cx(o)&&(i=o)}n("fillcolor",Oe.addOpacity((e.line||{}).color||i||r,.5))},fx=ne.isArrayOrTypedArray,px=function(t,e,r,n,i,a){var o=(t.marker||{}).color;(i("line.color",r),Xe(t,"line"))?Ye(t,e,n,i,{prefix:"line.",cLetter:"c"}):i("line.color",!fx(o)&&o||r);i("line.width"),(a||{}).noDash||i("line.dash")},dx=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")},gx=function(t,e,r,n,i,a){var o=Tr.isBubble(t),s=(t.line||{}).color;(a=a||{},s&&(r=s),i("marker.symbol"),i("marker.opacity",o?.7:1),i("marker.size"),i("marker.color",r),Xe(t,"marker")&&Ye(t,e,n,i,{prefix:"marker.",cLetter:"c"}),a.noSelect||(i("selected.marker.color"),i("unselected.marker.color"),i("selected.marker.size"),i("unselected.marker.size")),a.noLine||(i("marker.line.color",s&&!Array.isArray(s)&&e.marker.color!==s?s:o?Oe.background:Oe.defaultLine),Xe(t,"marker.line")&&Ye(t,e,n,i,{prefix:"marker.line.",cLetter:"c"}),i("marker.line.width",o?1:0)),o&&(i("marker.sizeref"),i("marker.sizemin"),i("marker.sizemode")),a.gradient)&&("none"!==i("marker.gradient.type")&&i("marker.gradient.color"))},vx=function(t,e,r,n,i){i=i||{},n("textposition"),ne.coerceFont(n,"textfont",r.font),i.noSelect||(n("selected.textfont.color"),n("unselected.textfont.color"))},mx=function(t,e){var r,n;if("lines"===t.mode)return(r=t.line.color)&&Oe.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var i=e.mcc||(t.marker||{}).color,a=e.mlcc||((t.marker||{}).line||{}).color;return(n=i&&Oe.opacity(i)?i:a&&Oe.opacity(a)&&(e.mlw||((t.marker||{}).line||{}).width)?a:"")?Oe.opacity(n)<.3?Oe.addOpacity(n,.3):n:(r=(t.line||{}).color)&&Oe.opacity(r)&&Tr.hasLines(t)&&t.line.width?r:t.fillcolor},yx=function(t,e,r,n){var i=t.cd,a=i[0].trace,o=t.xa,s=t.ya,l=o.c2p(e),u=s.c2p(r),c=[l,u],h=a.hoveron||"",f=-1!==a.mode.indexOf("markers")?3:.5;if(-1!==h.indexOf("points")){var p=function(t){var e=Math.max(f,t.mrc||0),r=o.c2p(t.x)-l,n=s.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-f/e)},d=yo.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-l);return nR!=(S=w[b][1])>=R&&(A=w[b-1][0],k=w[b][0],S-T&&(M=A+(k-A)*(R-T)/(S-T),z=Math.min(z,M),I=Math.max(I,M)));z=Math.max(z,0),I=Math.min(I,o._length);var F=Oe.defaultLine;return Oe.opacity(a.fillcolor)?F=a.fillcolor:Oe.opacity((a.line||{}).color)&&(F=a.line.color),ne.extendFlat(t,{distance:t.maxHoverDistance,x0:z,x1:I,y0:R,y1:R,color:F}),delete t.index,a.text&&!Array.isArray(a.text)?t.text=String(a.text):t.text=a.name,[t]}}},xx=t.BADNUM,bx=ne.segmentsIntersect,_x=ne.constrain,wx=function(t,e){var r,n,i,a,o,s,l,u,c,h,f,p,d,g,v,m,y=e.xaxis,x=e.yaxis,b=e.simplify,_=e.connectGaps,w=e.baseTolerance,M=e.shape,A="linear"===M,k=[],T=Wr.minTolerance,S=new Array(t.length),E=0;function C(e){var r=t[e],n=y.c2p(r.x),i=x.c2p(r.y);return n===xx||i===xx?r.intoCenter||!1:[n,i]}function L(t){var e=t[0]/y._length,r=t[1]/x._length;return(1+Wr.toleranceGrowth*Math.max(0,-e,e-1,-r,r-1))*w}function z(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}b||(w=T=-1);var P,I,D,O,R,F,B,N=Wr.maxScreensAway,j=-y._length*N,V=y._length*(1+N),U=-x._length*N,q=x._length*(1+N),H=[[j,U,V,U],[V,U,V,q],[V,q,j,q],[j,q,j,U]];function G(t){if(t[0]V||t[1]q)return[_x(t[0],j,V),_x(t[1],U,q)]}function W(t,e){return t[0]===e[0]&&(t[0]===j||t[0]===V)||(t[1]===e[1]&&(t[1]===U||t[1]===q)||void 0)}function Y(t,e,r){return function(n,i){var a=G(n),o=G(i),s=[];if(a&&o&&W(a,o))return s;a&&s.push(a),o&&s.push(o);var l=2*ne.constrain((n[t]+i[t])/2,e,r)-((a||n)[t]+(o||i)[t]);l&&((a&&o?l>0==a[t]>o[t]?a:o:a||o)[t]+=l);return s}}function X(t){var e=t[0],r=t[1],n=e===S[E-1][0],i=r===S[E-1][1];if(!n||!i)if(E>1){var a=e===S[E-2][0],o=r===S[E-2][1];n&&(e===j||e===V)&&a?o?E--:S[E-1]=t:i&&(r===U||r===q)&&o?a?E--:S[E-1]=t:S[E++]=t}else S[E++]=t}function Z(t){S[E-1][0]!==t[0]&&S[E-1][1]!==t[1]&&X([D,O]),X(t),R=null,D=O=0}function J(t){if(P=t[0]V?V:0,I=t[1]q?q:0,P||I){if(E)if(R){var e=B(R,t);e.length>1&&(Z(e[0]),S[E++]=e[1])}else F=B(S[E-1],t)[0],S[E++]=F;else S[E++]=[P||t[0],I||t[1]];var r=S[E-1];P&&I&&(r[0]!==P||r[1]!==I)?(R&&(D!==P&&O!==I?X(D&&O?(n=R,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?j:V,q]:[o>0?V:j,U]):[D||P,O||I]):D&&O&&X([D,O])),X([P,I])):D-P&&O-I&&X([P||D,I||O]),R=t,D=P,O=I}else R&&Z(B(R,t)[0]),S[E++]=t;var n,i,a,o}for("linear"===M||"spline"===M?B=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var a=H[i],o=bx(t[0],t[1],e[0],e[1],a[0],a[1],a[2],a[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&z(o,t)L(s))break;i=s,(d=c[0]*u[0]+c[1]*u[1])>f?(f=d,a=s,l=!1):d=t.length||!s)break;J(s),n=s}}else J(a)}R&&X([D||R[0],O||R[1]]),k.push(S.slice(0,E))}return k},Mx=function(t,e,r){var n,i,a=null;for(i=0;i0;for((l=c.selectAll("g.trace").data(n,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),Mx(t,r,n),function(t,r,n){var i;r.selectAll("g.trace").each(function(t){var r=e.select(this);if((i=t[0].trace)._nexttrace){if(i._nextFill=r.select(".js-fill.js-tonext"),!i._nextFill.size()){var a=":first-child";r.select(".js-fill.js-tozero").size()&&(a+=" + *"),i._nextFill=r.insert("path",a).attr("class","js-fill js-tonext")}}else r.selectAll(".js-fill.js-tonext").remove(),i._nextFill=null;i.fill&&("tozero"===i.fill.substr(0,6)||"toself"===i.fill||"to"===i.fill.substr(0,2)&&!i._prevtrace)?(i._ownFill=r.select(".js-fill.js-tozero"),i._ownFill.size()||(i._ownFill=r.insert("path",":first-child").attr("class","js-fill js-tozero"))):(r.selectAll(".js-fill.js-tozero").remove(),i._ownFill=null),r.selectAll(".js-fill").call(Sr.setClipUrl,n.layerClipId)})}(0,c,r),o=0,s={};os[e[0].trace.uid]?1:-1}),f)?(a&&(u=a()),e.transition().duration(i.duration).ease(i.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(e,a){Tx(t,a,r,e,n,this,i)})})):c.selectAll("g.trace").each(function(e,a){Tx(t,a,r,e,n,this,i)});h&&l.exit().remove(),c.selectAll("path:not([d])").remove()};function Tx(t,r,n,i,a,o,s){var l,u;!function(t,r,n,i,a){var o=n.xaxis,s=n.yaxis,l=e.extent(ne.simpleMap(o.range,o.r2c)),u=e.extent(ne.simpleMap(s.range,s.r2c)),c=i[0].trace;if(!Tr.hasMarkers(c))return;var h=c.marker.maxdisplayed;if(0===h)return;var f=i.filter(function(t){return t.x>=l[0]&&t.x<=l[1]&&t.y>=u[0]&&t.y<=u[1]}),p=Math.ceil(f.length/h),d=0;a.forEach(function(t,e){var n=t[0].trace;Tr.hasMarkers(n)&&n.marker.maxdisplayed>0&&e0;function h(t){return c?t.transition():t}var f=n.xaxis,p=n.yaxis,d=i[0].trace,g=d.line,v=e.select(o);if(P.getComponentMethod("errorbars","plot")(v,n,s),!0===d.visible){var m,y;h(v).style("opacity",d.opacity);var x=d.fill.charAt(d.fill.length-1);"x"!==x&&"y"!==x&&(x=""),i[0].node3=v;var b="",_=[],w=d._prevtrace;w&&(b=w._prevRevpath||"",y=w._nextFill,_=w._polygons);var M,A,k,T,S,E,C,L,z,I="",D="",O=[],R=ne.noop;if(m=d._ownFill,Tr.hasLines(d)||"none"!==d.fill){for(y&&y.datum(i),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(k=Sr.steps(g.shape),T=Sr.steps(g.shape.split("").reverse().join(""))):k=T="spline"===g.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?Sr.smoothclosed(t.slice(1),g.smoothing):Sr.smoothopen(t,g.smoothing)}:function(t){return"M"+t.join("L")},S=function(t){return T(t.reverse())},O=wx(i,{xaxis:f,yaxis:p,connectGaps:d.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),z=d._polygons=new Array(O.length),u=0;u1){var n=e.select(this);if(n.datum(i),t)h(n.style("opacity",0).attr("d",M).call(Sr.lineGroupStyle)).style("opacity",1);else{var a=h(n);a.attr("d",M),Sr.singleLineStyle(i,a)}}}}}var F=v.selectAll(".js-line").data(O);h(F.exit()).style("opacity",0).remove(),F.each(R(!1)),F.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Sr.lineGroupStyle).each(R(!0)),Sr.setClipUrl(F,n.layerClipId),O.length?(m?E&&L&&(x?("y"===x?E[1]=L[1]=p.c2p(0,!0):"x"===x&&(E[0]=L[0]=f.c2p(0,!0)),h(m).attr("d","M"+L+"L"+E+"L"+I.substr(1)).call(Sr.singleFillStyle)):h(m).attr("d",I+"Z").call(Sr.singleFillStyle)):y&&("tonext"===d.fill.substr(0,6)&&I&&b?("tonext"===d.fill?h(y).attr("d",I+"Z"+b+"Z").call(Sr.singleFillStyle):h(y).attr("d",I+"L"+b.substr(1)+"Z").call(Sr.singleFillStyle),d._polygons=d._polygons.concat(_)):(N(y),d._polygons=null)),d._prevRevpath=D,d._prevPolygons=z):(m?N(m):y&&N(y),d._polygons=d._prevRevpath=d._prevPolygons=null);var B=v.selectAll(".points");l=B.data([i]),B.each(H),l.enter().append("g").classed("points",!0).each(H),l.exit().remove(),l.each(function(t){var r=!1===t[0].trace.cliponaxis;Sr.setClipUrl(e.select(this),r?null:n.layerClipId)})}function N(t){h(t).attr("d","M0,0Z")}function j(t){return t.filter(function(t){return t.vis})}function V(t){return t.id}function U(t){if(t.ids)return V}function q(){return!1}function H(r){var i,a=r[0].trace,o=e.select(this),s=Tr.hasMarkers(a),l=Tr.hasText(a),u=U(a),d=q,g=q;s&&(d=a.marker.maxdisplayed||a._needsCull?j:ne.identity),l&&(g=a.marker.maxdisplayed||a._needsCull?j:ne.identity);var v=(i=o.selectAll("path.point").data(d,u)).enter().append("path").classed("point",!0);c&&v.call(Sr.pointStyle,a,t).call(Sr.translatePoints,f,p).style("opacity",0).transition().style("opacity",1);var m=s&&Sr.tryColorscale(a.marker,""),y=s&&Sr.tryColorscale(a.marker,"line");i.order(),i.each(function(r){var i=e.select(this),o=h(i);Sr.translatePoint(r,o,f,p)?(Sr.singlePointStyle(r,o,a,m,y,t),n.layerClipId&&Sr.hideOutsideRangePoint(r,o,f,p,a.xcalendar,a.ycalendar),a.customdata&&i.classed("plotly-customdata",null!==r.data&&void 0!==r.data)):o.remove()}),c?i.exit().transition().style("opacity",0).remove():i.exit().remove(),(i=o.selectAll("g").data(g,u)).enter().append("g").classed("textpoint",!0).append("text"),i.order(),i.each(function(t){var r=e.select(this),i=h(r.select("text"));Sr.translatePoint(t,i,f,p)?n.layerClipId&&Sr.hideOutsideRangePoint(t,r,f,p,a.xcalendar,a.ycalendar):r.remove()}),i.selectAll("text").call(Sr.textPointStyle,a,t).each(function(t){var r=f.c2p(t.x),n=p.c2p(t.y);e.select(this).selectAll("tspan.line").each(function(){h(e.select(this)).attr({x:r,y:n})})}),i.exit().remove()}}var Sx=function(t,e){var r,n,i,a,o=t.cd,s=t.xaxis,l=t.yaxis,u=[],c=o[0].trace;if(!Tr.hasMarkers(c)&&!Tr.hasText(c))return[];if(!1===e)for(r=0;r":return function(t){return u(t)>s};case">=":return function(t){return u(t)>=s};case"[]":return function(t){var e=u(t);return e>=s[0]&&e<=s[1]};case"()":return function(t){var e=u(t);return e>s[0]&&e=s[0]&&es[0]&&e<=s[1]};case"][":return function(t){var e=u(t);return e<=s[0]||e>=s[1]};case")(":return function(t){var e=u(t);return es[1]};case"](":return function(t){var e=u(t);return e<=s[0]||e>s[1]};case")[":return function(t){var e=u(t);return e=s[1]};case"{}":return function(t){return-1!==s.indexOf(u(t))};case"}{":return function(t){return-1===s.indexOf(u(t))}}}(r,ri.getDataToCoordFunc(t,e,i,n),o),f={},p={},d=0;r.preservegaps?(u=function(t){f[t.astr]=ne.extendDeep([],t.get()),t.set(new Array(a))},c=function(t,e){var r=f[t.astr][e];t.get()[e]=r}):(u=function(t){f[t.astr]=ne.extendDeep([],t.get()),t.set([])},c=function(t,e){var r=f[t.astr][e];t.get().push(r)}),m(u);for(var g=Nx(e.transforms,r),v=0;v1?"%{group} (%{trace})":"%{group}");var o=t.styles,s=i.styles=[];if(o)for(n=0;n0,l=[],u=[],c=0,h=0;for(n=0;n0&&l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"0&&l.push(["index[",h,"]-=s",h].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function tb(t,e,r){for(var n=t.body,i=[],a=[],o=0;o0&&g.push("shape=SS.slice(0)"),t.indexArgs.length>0){var v=new Array(r);for(a=0;a0&&d.push("var "+g.join(",")),a=0;a3&&d.push(tb(t.pre,t,i));var b=tb(t.body,t,i),_=function(t){for(var e=0,r=t[0].length;e0,l=[],u=0;u0;){"].join("")),l.push(["if(j",u,"<",o,"){"].join("")),l.push(["s",e[u],"=j",u].join("")),l.push(["j",u,"=0"].join("")),l.push(["}else{s",e[u],"=",o].join("")),l.push(["j",u,"-=",o,"}"].join("")),s&&l.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&d.push(tb(t.post,t,i)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+d.join("\n")+"\n----------");var w=[t.funcName||"unnamed","_cwise_loop_",n[0].join("s"),"m",_,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(i)].join("");return new Function(["function ",w,"(",p.join(","),"){",d.join("\n"),"} return ",w].join(""))()};var rb=function(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var i=[],a=[],o=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],s=[],l=[],u=0;u0&&(s.push("array"+t.arrayArgs[0]+".shape.length===array"+c+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),l.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+c+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u0)throw new Error("cwise: pre() block may not reference array args");if(n0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===i)e.scalarArgs.push(n),e.shimArgs.push("scalar"+n);else if("index"===i){if(e.indexArgs.push(n),n0)throw new Error("cwise: pre() block may not reference array index");if(n0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===i){if(e.shapeArgs.push(n),nr.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,rb(e)},ib={},ab={body:"",args:[],thisVars:[],localVars:[]};function ob(t){if(!t)return ab;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in lb){var e=lb[t];ib[t]=sb({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),ib[t+"eq"]=sb({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),ib[t+"s"]=sb({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),ib[t+"seq"]=sb({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var ub={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in ub){var e=ub[t];ib[t]=sb({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),ib[t+"eq"]=sb({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var cb={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in cb){var e=cb[t];ib[t]=sb({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),ib[t+"s"]=sb({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),ib[t+"eq"]=sb({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),ib[t+"seq"]=sb({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var hb=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_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"}),ib.norm1=nb({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,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"}),ib.sup=nb({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:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),ib.inf=nb({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:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),ib.random=sb({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),ib.assign=sb({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),ib.assigns=sb({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),ib.equals=nb({args:["array","array"],pre:ab,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"});var db=function(t){for(var e=new Array(t),r=0;rMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&i.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):i.push("ORDER})")),i.push("proto.set=function "+r+"_set("+o.join(",")+",v){"),n?i.push("return this.data.set("+s+",v)}"):i.push("return this.data["+s+"]=v}"),i.push("proto.get=function "+r+"_get("+o.join(",")+"){"),n?i.push("return this.data.get("+s+")}"):i.push("return this.data["+s+"]}"),i.push("proto.index=function "+r+"_index(",o.join(),"){return "+s+"}"),i.push("proto.hi=function "+r+"_hi("+o.join(",")+"){return new "+r+"(this.data,"+a.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+a.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var c=a.map(function(t){return"a"+t+"=this.shape["+t+"]"}),h=a.map(function(t){return"c"+t+"=this.stride["+t+"]"});i.push("proto.lo=function "+r+"_lo("+o.join(",")+"){var b=this.offset,d=0,"+c.join(",")+","+h.join(","));for(var f=0;f=0){d=i"+f+"|0;b+=c"+f+"*d;a"+f+"-=d}");i.push("return new "+r+"(this.data,"+a.map(function(t){return"a"+t}).join(",")+","+a.map(function(t){return"c"+t}).join(",")+",b)}"),i.push("proto.step=function "+r+"_step("+o.join(",")+"){var "+a.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+a.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(f=0;f=0){c=(c+this.stride["+f+"]*i"+f+")|0}else{a.push(this.shape["+f+"]);b.push(this.stride["+f+"])}");return i.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),i.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+a.map(function(t){return"shape["+t+"]"}).join(",")+","+a.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",i.join("\n"))(_b[t],xb)}var _b={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};var wb=function(t,e,r,n){if(void 0===t)return(0,_b.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var i=e.length;if(void 0===r){r=new Array(i);for(var a=i-1,o=1;a>=0;--a)r[a]=o,o*=e[a]}if(void 0===n)for(n=0,a=0;a0)-(t<0)},Mb.abs=function(t){var e=t>>31;return(t^e)-e},Mb.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Mb.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Mb.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Mb.countTrailingZeros=Ab,Mb.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Mb.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Mb.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var kb=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|kb[t>>>16&255]<<8|kb[t>>>24&255]},Mb.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Mb.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Mb.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Mb.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Mb.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Ab(t)+1};for(var Tb={byteLength:function(t){return 3*t.length/4-Ib(t)},toByteArray:function(t){var e,r,n,i,a,o=t.length;i=Ib(t),a=new Cb(3*o/4-i),r=i>0?o-4:o;var s=0;for(e=0;e>16&255,a[s++]=n>>8&255,a[s++]=255&n;2===i?(n=Eb[t.charCodeAt(e)]<<2|Eb[t.charCodeAt(e+1)]>>4,a[s++]=255&n):1===i&&(n=Eb[t.charCodeAt(e)]<<10|Eb[t.charCodeAt(e+1)]<<4|Eb[t.charCodeAt(e+2)]>>2,a[s++]=n>>8&255,a[s++]=255&n);return a},fromByteArray:function(t){for(var e,r=t.length,n=r%3,i="",a=[],o=0,s=r-n;os?s:o+16383));1===n?(e=t[r-1],i+=Sb[e>>2],i+=Sb[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=Sb[e>>10],i+=Sb[e>>4&63],i+=Sb[e<<2&63],i+="=");return a.push(i),a.join("")}},Sb=[],Eb=[],Cb="undefined"!=typeof Uint8Array?Uint8Array:Array,Lb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",zb=0,Pb=Lb.length;zb0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function Db(t,e,r){for(var n,i,a=[],o=e;o>18&63]+Sb[i>>12&63]+Sb[i>>6&63]+Sb[63&i]);return a.join("")}Eb["-".charCodeAt(0)]=62,Eb["_".charCodeAt(0)]=63;var Ob={read:function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,f=r?-1:1,p=t[e+h];for(h+=f,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)},write:function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}},Rb={};Rb.Buffer=Nb,Rb.SlowBuffer=function(t){+t!=t&&(t=0);return Nb.alloc(+t)},Rb.INSPECT_MAX_BYTES=50;var Fb=2147483647;function Bb(t){if(t>Fb)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=Nb.prototype,e}function Nb(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return Ub(t)}return jb(t,e,r)}function jb(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return y_(t)||t&&y_(t.buffer)?function(t,e,r){if(e<0||t.byteLength=Fb)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Fb.toString(16)+" bytes");return 0|t}function Gb(t,e){if(Nb.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||y_(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return g_(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return v_(t).length;default:if(n)return g_(t).length;e=(""+e).toLowerCase(),n=!0}}function Wb(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function Yb(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),x_(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=Nb.from(e,n)),Nb.isBuffer(e))return 0===e.length?-1:Xb(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Xb(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Xb(t,e,r,n,i){var a,o=1,s=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,s/=2,l/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var c=-1;for(a=r;as&&(r=s-l),a=r;a>=0;a--){for(var h=!0,f=0;fi&&(n=i):n=i;var a=e.length;n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(e,t.length-r),t,r,n)}function e_(t,e,r){return 0===e&&r===t.length?Tb.fromByteArray(t):Tb.fromByteArray(t.slice(e,r))}function r_(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(c=u);break;case 2:128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)>127&&(c=l);break;case 3:a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&(l=(15&u)<<12|(63&a)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(c=l)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=h}return function(t){var e=t.length;if(e<=n_)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return o_(this,e,r);case"utf8":case"utf-8":return r_(this,e,r);case"ascii":return i_(this,e,r);case"latin1":case"binary":return a_(this,e,r);case"base64":return e_(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s_(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},Nb.prototype.toLocaleString=Nb.prototype.toString,Nb.prototype.equals=function(t){if(!Nb.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Nb.compare(this,t)},Nb.prototype.inspect=function(){var t="",e=Rb.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},Nb.prototype.compare=function(t,e,r,n,i){if(!Nb.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,o=r-e,s=Math.min(a,o),l=this.slice(n,i),u=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return Zb(this,t,e,r);case"utf8":case"utf-8":return Jb(this,t,e,r);case"ascii":return Kb(this,t,e,r);case"latin1":case"binary":return Qb(this,t,e,r);case"base64":return $b(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return t_(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},Nb.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var n_=4096;function i_(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",a=e;ar)throw new RangeError("Trying to access beyond buffer length")}function u_(t,e,r,n,i,a){if(!Nb.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function c_(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function h_(t,e,r,n,i){return e=+e,r>>>=0,i||c_(t,0,r,4),Ob.write(t,e,r,n,23,4),r+4}function f_(t,e,r,n,i){return e=+e,r>>>=0,i||c_(t,0,r,8),Ob.write(t,e,r,n,52,8),r+8}Nb.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||l_(t,e,this.length);for(var n=this[t],i=1,a=0;++a>>=0,e>>>=0,r||l_(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},Nb.prototype.readUInt8=function(t,e){return t>>>=0,e||l_(t,1,this.length),this[t]},Nb.prototype.readUInt16LE=function(t,e){return t>>>=0,e||l_(t,2,this.length),this[t]|this[t+1]<<8},Nb.prototype.readUInt16BE=function(t,e){return t>>>=0,e||l_(t,2,this.length),this[t]<<8|this[t+1]},Nb.prototype.readUInt32LE=function(t,e){return t>>>=0,e||l_(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Nb.prototype.readUInt32BE=function(t,e){return t>>>=0,e||l_(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Nb.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||l_(t,e,this.length);for(var n=this[t],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*e)),n},Nb.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||l_(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*e)),a},Nb.prototype.readInt8=function(t,e){return t>>>=0,e||l_(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Nb.prototype.readInt16LE=function(t,e){t>>>=0,e||l_(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Nb.prototype.readInt16BE=function(t,e){t>>>=0,e||l_(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Nb.prototype.readInt32LE=function(t,e){return t>>>=0,e||l_(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Nb.prototype.readInt32BE=function(t,e){return t>>>=0,e||l_(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Nb.prototype.readFloatLE=function(t,e){return t>>>=0,e||l_(t,4,this.length),Ob.read(this,t,!0,23,4)},Nb.prototype.readFloatBE=function(t,e){return t>>>=0,e||l_(t,4,this.length),Ob.read(this,t,!1,23,4)},Nb.prototype.readDoubleLE=function(t,e){return t>>>=0,e||l_(t,8,this.length),Ob.read(this,t,!0,52,8)},Nb.prototype.readDoubleBE=function(t,e){return t>>>=0,e||l_(t,8,this.length),Ob.read(this,t,!1,52,8)},Nb.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||u_(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,n)||u_(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},Nb.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,1,255,0),this[e]=255&t,e+1},Nb.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},Nb.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},Nb.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},Nb.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Nb.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);u_(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},Nb.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);u_(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},Nb.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},Nb.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},Nb.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},Nb.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},Nb.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||u_(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},Nb.prototype.writeFloatLE=function(t,e,r){return h_(this,t,e,!0,r)},Nb.prototype.writeFloatBE=function(t,e,r){return h_(this,t,e,!1,r)},Nb.prototype.writeDoubleLE=function(t,e,r){return f_(this,t,e,!0,r)},Nb.prototype.writeDoubleBE=function(t,e,r){return f_(this,t,e,!1,r)},Nb.prototype.copy=function(t,e,r,n){if(!Nb.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},Nb.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Nb.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function v_(t){return Tb.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(p_,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function m_(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function y_(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function x_(t){return t!=t}var b_=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n0?r.pop():new ArrayBuffer(t)}function l(t){return new Uint8Array(s(t),0,t)}function u(t){return new Uint16Array(s(2*t),0,t)}function c(t){return new Uint32Array(s(4*t),0,t)}function h(t){return new Int8Array(s(t),0,t)}function f(t){return new Int16Array(s(2*t),0,t)}function p(t){return new Int32Array(s(4*t),0,t)}function d(t){return new Float32Array(s(4*t),0,t)}function g(t){return new Float64Array(s(8*t),0,t)}function v(t){return r?new Uint8ClampedArray(s(t),0,t):l(t)}function m(t){return new DataView(s(t),0,t)}function y(t){t=Mb.nextPow2(t);var r=Mb.log2(t),n=a[r];return n.length>0?n.pop():new e(t)}__.free=function(t){if(e.isBuffer(t))a[Mb.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var r=t.length||t.byteLength,n=0|Mb.log2(r);i[n].push(t)}},__.freeUint8=__.freeUint16=__.freeUint32=__.freeInt8=__.freeInt16=__.freeInt32=__.freeFloat32=__.freeFloat=__.freeFloat64=__.freeDouble=__.freeUint8Clamped=__.freeDataView=function(t){o(t.buffer)},__.freeArrayBuffer=o,__.freeBuffer=function(t){a[Mb.log2(t.length)].push(t)},__.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return s(t);switch(e){case"uint8":return l(t);case"uint16":return u(t);case"uint32":return c(t);case"int8":return h(t);case"int16":return f(t);case"int32":return p(t);case"float":case"float32":return d(t);case"double":case"float64":return g(t);case"uint8_clamped":return v(t);case"buffer":return y(t);case"data":case"dataview":return m(t);default:return null}return null},__.mallocArrayBuffer=s,__.mallocUint8=l,__.mallocUint16=u,__.mallocUint32=c,__.mallocInt8=h,__.mallocInt16=f,__.mallocInt32=p,__.mallocFloat32=__.mallocFloat=d,__.mallocFloat64=__.mallocDouble=g,__.mallocUint8Clamped=v,__.mallocDataView=m,__.mallocBuffer=y,__.clearCache=function(){for(var t=0;t<32;++t)n.UINT8[t].length=0,n.UINT16[t].length=0,n.UINT32[t].length=0,n.INT8[t].length=0,n.INT16[t].length=0,n.INT32[t].length=0,n.FLOAT[t].length=0,n.DOUBLE[t].length=0,n.UINT8C[t].length=0,i[t].length=0,a[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Rb.Buffer);var w_=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function M_(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}var A_=M_.prototype;function k_(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(a<0)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function T_(t,e){for(var r=__.malloc(t.length,e),n=t.length,i=0;i=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=k_(this.gl,this.type,this.length,this.usage,t.data,e):this.length=k_(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var n=__.malloc(t.size,r),i=wb(n,t.shape);ib.assign(i,t),this.length=k_(this.gl,this.type,this.length,this.usage,e<0?n:n.subarray(0,t.size),e),__.free(n)}}else if(Array.isArray(t)){var a;a=this.type===this.gl.ELEMENT_ARRAY_BUFFER?T_(t,"uint16"):T_(t,"float32"),this.length=k_(this.gl,this.type,this.length,this.usage,e<0?a:a.subarray(0,t.length),e),__.free(a)}else if("object"==typeof t&&"number"==typeof t.length)this.length=k_(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}};var S_=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var i=new M_(t,r,t.createBuffer(),0,n);return i.update(e),i},E_=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;n=0){var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new P_("","Invalid data type for attribute "+l+": "+u);R_(t,e,c[0],n,h,i,l)}else{if(!(u.indexOf("mat")>=0))throw new P_("","Unknown data type for attribute "+l+": "+u);var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new P_("","Invalid data type for attribute "+l+": "+u);F_(t,e,c,n,h,i,l)}}}return i};function D_(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}var O_=D_.prototype;function R_(t,e,r,n,i,a,o){for(var s=["gl","v"],l=[],u=0;u1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;u4)throw new P_("","Invalid uniform dimension type for matrix "+Rd+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new P_("","Unknown uniform data type for "+Rd+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(i<2||i>4)throw new P_("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new P_("","Unrecognized data type for vector "+Rd+": "+r)}}}function a(e){for(var a=["return function updateProperty(obj){"],o=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var i in r){var a=r[i],o=e;parseInt(i)+""===i?o+="["+i+"]":o+="."+i,"object"==typeof a?n.push.apply(n,t(o,a)):n.push([o,a])}return n}("",e),s=0;s4)throw new P_("","Invalid data type");return"b"===t.charAt(0)?V_(r,!1):V_(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new P_("","Invalid uniform dimension type for matrix "+Rd+": "+t);return V_(r*r,0)}throw new P_("","Unknown uniform data type for "+Rd+": "+t)}}(r[l].type);var c}function s(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1)for(var s=0;s=r)return Y_.substr(0,r);for(;r>Y_.length&&e>1;)1&e&&(Y_+=t),e>>=1,t+=t;return Y_=(Y_+=t).substr(0,r)};var Z_=function(t,e,r){return X_(r=void 0!==r?r+"":" ",e)+t},J_=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),i=String(n.length+e-1).length;return n.map(function(t,n){var a=n+e,o=String(a).length,s=Z_(a,i-o);return s+r+t}).join("\n")};var K_={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},Q_=function(t){return K_[t]},$_=function(t){return atob(t)},tw=["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"],ew=(tw=tw.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)})).concat(["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","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"]),rw=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","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","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"],nw=rw.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),iw=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],aw=function(t){var e,r,n,i=0,a=0,o=ow,s=[],l=[],u=1,c=0,h=0,f=!1,p=!1,d="",g=tw,v=rw;"300 es"===(t=t||{}).version&&(g=ew,v=nw);return function(t){return l=[],null!==t?function(t){var r;i=0,n=(d+=t).length;for(;e=d[i],i0)continue;r=t.slice(0,1).join("")}return m(r),h+=r.length,(s=s.slice(r.length)).length}}function A(){return/[^a-fA-F0-9]/.test(e)?(m(s.join("")),o=ow,i):(s.push(e),r=e,i+1)}function k(){return"."===e?(s.push(e),o=pw,r=e,i+1):/[eE]/.test(e)?(s.push(e),o=pw,r=e,i+1):"x"===e&&1===s.length&&"0"===s[0]?(o=xw,s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=ow,i):(s.push(e),r=e,i+1)}function T(){return"f"===e&&(s.push(e),r=e,i+=1),/[eE]/.test(e)?(s.push(e),r=e,i+1):"-"===e&&/[eE]/.test(r)?(s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=ow,i):(s.push(e),r=e,i+1)}function S(){if(/[^\d\w_]/.test(e)){var t=s.join("");return o=v.indexOf(t)>-1?vw:g.indexOf(t)>-1?gw:dw,m(s.join("")),o=ow,i}return s.push(e),r=e,i+1}},ow=999,sw=9999,lw=0,uw=1,cw=2,hw=3,fw=4,pw=5,dw=6,gw=7,vw=8,mw=9,yw=10,xw=11,bw=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];var _w=function(t,e){var r=aw(e),n=[];return n=(n=n.concat(r(t))).concat(r(null))};var ww=function(t){for(var e=Array.isArray(t)?t:_w(t),r=0;r=0),s[8]){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,s[6]?parseInt(s[6]):0);break;case"e":i=s[7]?parseFloat(i).toExponential(s[7]):parseFloat(i).toExponential();break;case"f":i=s[7]?parseFloat(i).toFixed(s[7]):parseFloat(i);break;case"g":i=s[7]?String(Number(i.toPrecision(s[7]))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=s[7]?i.substring(0,s[7]):i;break;case"t":i=String(!!i),i=s[7]?i.substring(0,s[7]):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=s[7]?i.substring(0,s[7]):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=s[7]?i.substring(0,s[7]):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(s[8])?g+=i:(!t.number.test(s[8])||h&&!s[3]?f="":(f=h?"+":"-",i=i.toString().replace(t.sign,"")),u=s[4]?"0"===s[4]?"0":s[4].charAt(1):" ",c=s[6]-(f+i).length,l=s[6]&&c>0?u.repeat(c):"",g+=s[5]?f+i+l:"0"===u?f+l+i:l+f+i)}return g}(function(e){if(n[e])return n[e];var r,i=e,a=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))a.push(r[0]);else if(null!==(r=t.modulo.exec(i)))a.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var s=[],l=r[2],u=[];if(null===(u=t.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(l=l.substring(u[0].length));)if(null!==(u=t.key_access.exec(l)))s.push(u[1]);else{if(null===(u=t.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}r[2]=s}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a.push(r)}i=i.substring(r[0].length)}return n[e]=a}(r),arguments)}function r(t,r){return e.apply(null,[t].concat(r||[]))}var n=Object.create(null);void 0!==Mw&&(Mw.sprintf=e,Mw.vsprintf=r),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=r)}();var Aw=Mw.sprintf,kw=function(t,e,r){"use strict";var n=ww(e)||"of unknown name (see npm glsl-shader-name)",i="unknown type";void 0!==r&&(i=r===Q_.FRAGMENT_SHADER?"fragment":"vertex");for(var a=Aw("Error compiling %s shader %s:\n",i,n),o=Aw("%s%s",a,t),s=t.split("\n"),l={},u=0;ur)for(t=r;te)for(t=e;t=0){for(var v=0|g.type.charAt(g.type.length-1),m=new Array(v),y=0;y=0;)x+=1;d[h]=x}var b=new Array(r.length);function _(){a.program=Ew.program(o,a._vref,a._fref,p,d);for(var t=0;t>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function Gw(t,e,r,n){return new Function([Hw("A","x"+t+"y",e,["y"],n),Hw("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}qw.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},qw.drawBox=(Vw=[0,0],Uw=[0,0],function(t,e,r,n,i){var a=this.plot,o=this.shader,s=a.gl;Vw[0]=t,Vw[1]=e,Uw[0]=r,Uw[1]=n,o.uniforms.lo=Vw,o.uniforms.hi=Uw,o.uniforms.color=i,s.drawArrays(s.TRIANGLE_STRIP,0,4)}),qw.dispose=function(){this.vbo.dispose(),this.shader.dispose()};var Ww={ge:Gw(">=",!1,"GE"),gt:Gw(">",!1,"GT"),lt:Gw("<",!0,"LT"),le:Gw("<=",!0,"LE"),eq:Gw("-",!0,"EQ",!0)};function Yw(t,e,r,n,i){var a=["function ",t,"(a,l,h,",n.join(","),"){",i?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function Xw(t,e,r,n){return new Function([Yw("A","x"+t+"y",e,["y"],n),Yw("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var Zw={ge:Xw(">=",!1,"GE"),gt:Xw(">",!1,"GT"),lt:Xw("<",!0,"LT"),le:Xw("<=",!0,"LE"),eq:Xw("-",!0,"EQ",!0)},Jw=function(t){var e=t.gl,r=S_(e),n=Bw(e,L_.gridVert,L_.gridFrag),i=Bw(e,L_.tickVert,L_.gridFrag);return new Kw(t,r,n,i)};function Kw(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function Qw(t,e){return t-e}var $w,tM,eM,rM,nM,iM=Kw.prototype;iM.draw=($w=[0,0],tM=[0,0],eM=[0,0],function(){for(var t=this.plot,e=this.vbo,r=this.shader,n=this.ticks,i=t.gl,a=t._tickBounds,o=t.dataBox,s=t.viewBox,l=t.gridLineWidth,u=t.gridLineColor,c=t.gridLineEnable,h=t.pixelRatio,f=0;f<2;++f){var p=a[f],d=a[f+2]-p,g=.5*(o[f+2]+o[f]),v=o[f+2]-o[f];tM[f]=2*d/v,$w[f]=2*(p-g)/v}r.bind(),e.bind(),r.attributes.dataCoord.pointer(),r.uniforms.dataShift=$w,r.uniforms.dataScale=tM;var m=0;for(f=0;f<2;++f){eM[0]=eM[1]=0,eM[f]=1,r.uniforms.dataAxis=eM,r.uniforms.lineWidth=l[f]/(s[f+2]-s[f])*h,r.uniforms.color=u[f];var y=6*n[f].length;c[f]&&y&&i.drawArrays(i.TRIANGLES,m,y),m+=y}}),iM.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],i=[0,0],a=[0,0];return function(){for(var o=this.plot,s=this.vbo,l=this.tickShader,u=this.ticks,c=o.gl,h=o._tickBounds,f=o.dataBox,p=o.viewBox,d=o.pixelRatio,g=o.screenBox,v=g[2]-g[0],m=g[3]-g[1],y=p[2]-p[0],x=p[3]-p[1],b=0;b<2;++b){var _=h[b],w=h[b+2]-_,M=.5*(f[b+2]+f[b]),A=f[b+2]-f[b];e[b]=2*w/A,t[b]=2*(_-M)/A}e[0]*=y/v,t[0]*=y/v,e[1]*=x/m,t[1]*=x/m,l.bind(),s.bind(),l.attributes.dataCoord.pointer();var k=l.uniforms;k.dataShift=t,k.dataScale=e;var T=o.tickMarkLength,S=o.tickMarkWidth,E=o.tickMarkColor,C=6*u[0].length,L=Math.min(Zw.ge(u[0],(f[0]-h[0])/(h[2]-h[0]),Qw),u[0].length),z=Math.min(Zw.gt(u[0],(f[2]-h[0])/(h[2]-h[0]),Qw),u[0].length),P=0+6*L,I=6*Math.max(0,z-L),D=Math.min(Zw.ge(u[1],(f[1]-h[1])/(h[3]-h[1]),Qw),u[1].length),O=Math.min(Zw.gt(u[1],(f[3]-h[1])/(h[3]-h[1]),Qw),u[1].length),R=C+6*D,F=6*Math.max(0,O-D);i[0]=2*(p[0]-T[1])/v-1,i[1]=(p[3]+p[1])/m-1,a[0]=T[1]*d/v,a[1]=S[1]*d/m,F&&(k.color=E[1],k.tickScale=a,k.dataAxis=n,k.screenOffset=i,c.drawArrays(c.TRIANGLES,R,F)),i[0]=(p[2]+p[0])/v-1,i[1]=2*(p[1]-T[0])/m-1,a[0]=S[0]*d/v,a[1]=T[0]*d/m,I&&(k.color=E[0],k.tickScale=a,k.dataAxis=r,k.screenOffset=i,c.drawArrays(c.TRIANGLES,P,I)),i[0]=2*(p[2]+T[3])/v-1,i[1]=(p[3]+p[1])/m-1,a[0]=T[3]*d/v,a[1]=S[3]*d/m,F&&(k.color=E[3],k.tickScale=a,k.dataAxis=n,k.screenOffset=i,c.drawArrays(c.TRIANGLES,R,F)),i[0]=(p[2]+p[0])/v-1,i[1]=2*(p[3]+T[2])/m-1,a[0]=S[2]*d/v,a[1]=T[2]*d/m,I&&(k.color=E[2],k.tickScale=a,k.dataAxis=r,k.screenOffset=i,c.drawArrays(c.TRIANGLES,P,I))}}(),iM.update=(rM=[1,1,-1,-1,1,-1],nM=[1,-1,1,1,-1,-1],function(t){for(var e=t.ticks,r=t.bounds,n=new Float32Array(18*(e[0].length+e[1].length)),i=(this.plot.zeroLineEnable,0),a=[[],[]],o=0;o<2;++o)for(var s=a[o],l=e[o],u=r[o],c=r[o+2],h=0;h=n?(i=h,(l+=1)=n?(i=h,(l+=1)>1;return["sum(",xM(t.slice(0,e)),",",xM(t.slice(e)),")"].join("")}function bM(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return bM(e,t)}function _M(t){if(2===t.length)return[["diff(",bM(t[0][0],t[1][1]),",",bM(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0;){for(var l=r.pop(),a=r.pop(),u=-1,c=-1,o=i[a],f=1;f=0||(e.flip(a,l),SM(t,e,r,u,a,c),SM(t,e,r,a,c,u),SM(t,e,r,c,l,u),SM(t,e,r,l,u,c)))}};function SM(t,e,r,n,i,a){var o=e.opposite(n,i);if(!(o<0)){if(i0||o.length>0;){for(;a.length>0;){var h=a.pop();if(s[h]!==-i){s[h]=i;l[h];for(var f=0;f<3;++f){var p=c[3*h+f];p>=0&&0===s[p]&&(u[3*h+f]?o.push(p):(a.push(p),s[p]=i))}}}var d=o;o=a,a=d,o.length=0,i=-i}var g=function(t,e,r){for(var n=0,i=0;i>1;return["sum(",OM(t.slice(0,e)),",",OM(t.slice(e)),")"].join("")}function RM(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(a<=0)return o;n=i+a}else{if(!(i<0))return o;if(a>=0)return o;n=-(i+a)}var s=3.3306690738754716e-16*n;return o>=s||o<=-s?o:BM(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],h=e[2]-n[2],f=r[2]-n[2],p=a*u,d=o*l,g=o*s,v=i*u,m=i*l,y=a*s,x=c*(p-d)+h*(g-v)+f*(m-y),b=7.771561172376103e-16*((Math.abs(p)+Math.abs(d))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(h)+(Math.abs(m)+Math.abs(y))*Math.abs(f));return x>b||-x>b?x:NM(t,e,r,n)}];!function(){for(;jM.length<=IM;)jM.push(FM(jM.length));for(var t=[],e=["slow"],r=0;r<=IM;++r)t.push("a"+r),e.push("o"+r);var n=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(r=2;r<=IM;++r)n.push("case ",r,":return o",r,"(",t.slice(0,r).join(),");");n.push("}var s=new Array(arguments.length);for(var i=0;il[0]&&i.push(new YM(l,s,HM,a),new YM(s,l,qM,a))}i.sort(XM);for(var u=i[0].a[0]-(1+Math.abs(i[0].a[0]))*Math.pow(2,-52),c=[new WM([u,1],[u,0],-1,[],[],[],[])],h=[],a=0,f=i.length;a1&&VM(r[u[c-2]],r[u[c-1]],n)>0;)t.push([u[c-1],u[c-2],i]),c-=1;u.length=c,u.push(i);var h=l.upperIds;for(c=h.length;c>1&&VM(r[h[c-2]],r[h[c-1]],n)<0;)t.push([h[c-2],h[c-1],i]),c-=1;h.length=c,h.push(i)}}function KM(t,e){var r;return(r=t.a[0]=0}}(),rA.removeTriangle=function(t,e,r){var n=this.stars;nA(n[t],e,r),nA(n[e],r,t),nA(n[r],t,e)},rA.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},rA.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;n=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function s(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;o=49?s-49+10:s>=17?s-17+10:s}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[a]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);else if("le"===n)for(i=0,a=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)i=o(t,r,r+6),this.words[n]|=i<>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==e&&(i=o(t,e,r+6),this.words[n]|=i<>>26-a&4194303),this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,o=a%n,l=Math.min(a,a-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var l=["","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"],u=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],a=0|e.words[0],o=i*a,s=67108863&o,l=o/67108864|0;r.words[0]=s;for(var u=1;u>>26,h=67108863&l,f=Math.min(u,e.length-1),p=Math.max(0,u-t.length+1);p<=f;p++){var d=u-p|0;c+=(o=(i=0|t.words[d])*(a=0|e.words[p])+h)/67108864|0,h=67108863&o}r.words[u]=0|h,l=0|c}return 0!==l?r.words[u]=0|l:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var i=0,a=0,o=0;o>>24-i&16777215)||o!==this.length-1?l[6-h.length]+h+n:h+n,(i+=2)>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var f=u[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:l[f-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==a),this.toArrayLike(a,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),a=n||Math.max(1,i);r(i<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var o,s,l="le"===e,u=new t(a),c=this.clone();if(l){for(s=0;!c.isZero();s++)o=c.andln(255),c.iushrn(8),u[s]=o;for(;s=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26;for(;0!==i&&a>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==a&&o>26,this.words[o]=67108863&e;if(0===a&&o>>13,p=0|o[1],d=8191&p,g=p>>>13,v=0|o[2],m=8191&v,y=v>>>13,x=0|o[3],b=8191&x,_=x>>>13,w=0|o[4],M=8191&w,A=w>>>13,k=0|o[5],T=8191&k,S=k>>>13,E=0|o[6],C=8191&E,L=E>>>13,z=0|o[7],P=8191&z,I=z>>>13,D=0|o[8],O=8191&D,R=D>>>13,F=0|o[9],B=8191&F,N=F>>>13,j=0|s[0],V=8191&j,U=j>>>13,q=0|s[1],H=8191&q,G=q>>>13,W=0|s[2],Y=8191&W,X=W>>>13,Z=0|s[3],J=8191&Z,K=Z>>>13,Q=0|s[4],$=8191&Q,tt=Q>>>13,et=0|s[5],rt=8191&et,nt=et>>>13,it=0|s[6],at=8191&it,ot=it>>>13,st=0|s[7],lt=8191&st,ut=st>>>13,ct=0|s[8],ht=8191&ct,ft=ct>>>13,pt=0|s[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(u+(n=Math.imul(h,V))|0)+((8191&(i=(i=Math.imul(h,U))+Math.imul(f,V)|0))<<13)|0;u=((a=Math.imul(f,U))+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(d,V),i=(i=Math.imul(d,U))+Math.imul(g,V)|0,a=Math.imul(g,U);var mt=(u+(n=n+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(f,H)|0))<<13)|0;u=((a=a+Math.imul(f,G)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,V),i=(i=Math.imul(m,U))+Math.imul(y,V)|0,a=Math.imul(y,U),n=n+Math.imul(d,H)|0,i=(i=i+Math.imul(d,G)|0)+Math.imul(g,H)|0,a=a+Math.imul(g,G)|0;var yt=(u+(n=n+Math.imul(h,Y)|0)|0)+((8191&(i=(i=i+Math.imul(h,X)|0)+Math.imul(f,Y)|0))<<13)|0;u=((a=a+Math.imul(f,X)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(b,V),i=(i=Math.imul(b,U))+Math.imul(_,V)|0,a=Math.imul(_,U),n=n+Math.imul(m,H)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,G)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,X)|0)+Math.imul(g,Y)|0,a=a+Math.imul(g,X)|0;var xt=(u+(n=n+Math.imul(h,J)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,K)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(M,V),i=(i=Math.imul(M,U))+Math.imul(A,V)|0,a=Math.imul(A,U),n=n+Math.imul(b,H)|0,i=(i=i+Math.imul(b,G)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,G)|0,n=n+Math.imul(m,Y)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(y,Y)|0,a=a+Math.imul(y,X)|0,n=n+Math.imul(d,J)|0,i=(i=i+Math.imul(d,K)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,K)|0;var bt=(u+(n=n+Math.imul(h,$)|0)|0)+((8191&(i=(i=i+Math.imul(h,tt)|0)+Math.imul(f,$)|0))<<13)|0;u=((a=a+Math.imul(f,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,V),i=(i=Math.imul(T,U))+Math.imul(S,V)|0,a=Math.imul(S,U),n=n+Math.imul(M,H)|0,i=(i=i+Math.imul(M,G)|0)+Math.imul(A,H)|0,a=a+Math.imul(A,G)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,X)|0)+Math.imul(_,Y)|0,a=a+Math.imul(_,X)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,K)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,K)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,$)|0,a=a+Math.imul(g,tt)|0;var _t=(u+(n=n+Math.imul(h,rt)|0)|0)+((8191&(i=(i=i+Math.imul(h,nt)|0)+Math.imul(f,rt)|0))<<13)|0;u=((a=a+Math.imul(f,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(C,V),i=(i=Math.imul(C,U))+Math.imul(L,V)|0,a=Math.imul(L,U),n=n+Math.imul(T,H)|0,i=(i=i+Math.imul(T,G)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,G)|0,n=n+Math.imul(M,Y)|0,i=(i=i+Math.imul(M,X)|0)+Math.imul(A,Y)|0,a=a+Math.imul(A,X)|0,n=n+Math.imul(b,J)|0,i=(i=i+Math.imul(b,K)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,K)|0,n=n+Math.imul(m,$)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(y,$)|0,a=a+Math.imul(y,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,a=a+Math.imul(g,nt)|0;var wt=(u+(n=n+Math.imul(h,at)|0)|0)+((8191&(i=(i=i+Math.imul(h,ot)|0)+Math.imul(f,at)|0))<<13)|0;u=((a=a+Math.imul(f,ot)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(P,V),i=(i=Math.imul(P,U))+Math.imul(I,V)|0,a=Math.imul(I,U),n=n+Math.imul(C,H)|0,i=(i=i+Math.imul(C,G)|0)+Math.imul(L,H)|0,a=a+Math.imul(L,G)|0,n=n+Math.imul(T,Y)|0,i=(i=i+Math.imul(T,X)|0)+Math.imul(S,Y)|0,a=a+Math.imul(S,X)|0,n=n+Math.imul(M,J)|0,i=(i=i+Math.imul(M,K)|0)+Math.imul(A,J)|0,a=a+Math.imul(A,K)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,$)|0,a=a+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,a=a+Math.imul(y,nt)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ot)|0)+Math.imul(g,at)|0,a=a+Math.imul(g,ot)|0;var Mt=(u+(n=n+Math.imul(h,lt)|0)|0)+((8191&(i=(i=i+Math.imul(h,ut)|0)+Math.imul(f,lt)|0))<<13)|0;u=((a=a+Math.imul(f,ut)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(O,V),i=(i=Math.imul(O,U))+Math.imul(R,V)|0,a=Math.imul(R,U),n=n+Math.imul(P,H)|0,i=(i=i+Math.imul(P,G)|0)+Math.imul(I,H)|0,a=a+Math.imul(I,G)|0,n=n+Math.imul(C,Y)|0,i=(i=i+Math.imul(C,X)|0)+Math.imul(L,Y)|0,a=a+Math.imul(L,X)|0,n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,K)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,K)|0,n=n+Math.imul(M,$)|0,i=(i=i+Math.imul(M,tt)|0)+Math.imul(A,$)|0,a=a+Math.imul(A,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,a=a+Math.imul(_,nt)|0,n=n+Math.imul(m,at)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(y,at)|0,a=a+Math.imul(y,ot)|0,n=n+Math.imul(d,lt)|0,i=(i=i+Math.imul(d,ut)|0)+Math.imul(g,lt)|0,a=a+Math.imul(g,ut)|0;var At=(u+(n=n+Math.imul(h,ht)|0)|0)+((8191&(i=(i=i+Math.imul(h,ft)|0)+Math.imul(f,ht)|0))<<13)|0;u=((a=a+Math.imul(f,ft)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(B,V),i=(i=Math.imul(B,U))+Math.imul(N,V)|0,a=Math.imul(N,U),n=n+Math.imul(O,H)|0,i=(i=i+Math.imul(O,G)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,G)|0,n=n+Math.imul(P,Y)|0,i=(i=i+Math.imul(P,X)|0)+Math.imul(I,Y)|0,a=a+Math.imul(I,X)|0,n=n+Math.imul(C,J)|0,i=(i=i+Math.imul(C,K)|0)+Math.imul(L,J)|0,a=a+Math.imul(L,K)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(S,$)|0,a=a+Math.imul(S,tt)|0,n=n+Math.imul(M,rt)|0,i=(i=i+Math.imul(M,nt)|0)+Math.imul(A,rt)|0,a=a+Math.imul(A,nt)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ot)|0)+Math.imul(_,at)|0,a=a+Math.imul(_,ot)|0,n=n+Math.imul(m,lt)|0,i=(i=i+Math.imul(m,ut)|0)+Math.imul(y,lt)|0,a=a+Math.imul(y,ut)|0,n=n+Math.imul(d,ht)|0,i=(i=i+Math.imul(d,ft)|0)+Math.imul(g,ht)|0,a=a+Math.imul(g,ft)|0;var kt=(u+(n=n+Math.imul(h,dt)|0)|0)+((8191&(i=(i=i+Math.imul(h,gt)|0)+Math.imul(f,dt)|0))<<13)|0;u=((a=a+Math.imul(f,gt)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(B,H),i=(i=Math.imul(B,G))+Math.imul(N,H)|0,a=Math.imul(N,G),n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,X)|0)+Math.imul(R,Y)|0,a=a+Math.imul(R,X)|0,n=n+Math.imul(P,J)|0,i=(i=i+Math.imul(P,K)|0)+Math.imul(I,J)|0,a=a+Math.imul(I,K)|0,n=n+Math.imul(C,$)|0,i=(i=i+Math.imul(C,tt)|0)+Math.imul(L,$)|0,a=a+Math.imul(L,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(S,rt)|0,a=a+Math.imul(S,nt)|0,n=n+Math.imul(M,at)|0,i=(i=i+Math.imul(M,ot)|0)+Math.imul(A,at)|0,a=a+Math.imul(A,ot)|0,n=n+Math.imul(b,lt)|0,i=(i=i+Math.imul(b,ut)|0)+Math.imul(_,lt)|0,a=a+Math.imul(_,ut)|0,n=n+Math.imul(m,ht)|0,i=(i=i+Math.imul(m,ft)|0)+Math.imul(y,ht)|0,a=a+Math.imul(y,ft)|0;var Tt=(u+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;u=((a=a+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(B,Y),i=(i=Math.imul(B,X))+Math.imul(N,Y)|0,a=Math.imul(N,X),n=n+Math.imul(O,J)|0,i=(i=i+Math.imul(O,K)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,K)|0,n=n+Math.imul(P,$)|0,i=(i=i+Math.imul(P,tt)|0)+Math.imul(I,$)|0,a=a+Math.imul(I,tt)|0,n=n+Math.imul(C,rt)|0,i=(i=i+Math.imul(C,nt)|0)+Math.imul(L,rt)|0,a=a+Math.imul(L,nt)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ot)|0)+Math.imul(S,at)|0,a=a+Math.imul(S,ot)|0,n=n+Math.imul(M,lt)|0,i=(i=i+Math.imul(M,ut)|0)+Math.imul(A,lt)|0,a=a+Math.imul(A,ut)|0,n=n+Math.imul(b,ht)|0,i=(i=i+Math.imul(b,ft)|0)+Math.imul(_,ht)|0,a=a+Math.imul(_,ft)|0;var St=(u+(n=n+Math.imul(m,dt)|0)|0)+((8191&(i=(i=i+Math.imul(m,gt)|0)+Math.imul(y,dt)|0))<<13)|0;u=((a=a+Math.imul(y,gt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(B,J),i=(i=Math.imul(B,K))+Math.imul(N,J)|0,a=Math.imul(N,K),n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(R,$)|0,a=a+Math.imul(R,tt)|0,n=n+Math.imul(P,rt)|0,i=(i=i+Math.imul(P,nt)|0)+Math.imul(I,rt)|0,a=a+Math.imul(I,nt)|0,n=n+Math.imul(C,at)|0,i=(i=i+Math.imul(C,ot)|0)+Math.imul(L,at)|0,a=a+Math.imul(L,ot)|0,n=n+Math.imul(T,lt)|0,i=(i=i+Math.imul(T,ut)|0)+Math.imul(S,lt)|0,a=a+Math.imul(S,ut)|0,n=n+Math.imul(M,ht)|0,i=(i=i+Math.imul(M,ft)|0)+Math.imul(A,ht)|0,a=a+Math.imul(A,ft)|0;var Et=(u+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;u=((a=a+Math.imul(_,gt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(B,$),i=(i=Math.imul(B,tt))+Math.imul(N,$)|0,a=Math.imul(N,tt),n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(R,rt)|0,a=a+Math.imul(R,nt)|0,n=n+Math.imul(P,at)|0,i=(i=i+Math.imul(P,ot)|0)+Math.imul(I,at)|0,a=a+Math.imul(I,ot)|0,n=n+Math.imul(C,lt)|0,i=(i=i+Math.imul(C,ut)|0)+Math.imul(L,lt)|0,a=a+Math.imul(L,ut)|0,n=n+Math.imul(T,ht)|0,i=(i=i+Math.imul(T,ft)|0)+Math.imul(S,ht)|0,a=a+Math.imul(S,ft)|0;var Ct=(u+(n=n+Math.imul(M,dt)|0)|0)+((8191&(i=(i=i+Math.imul(M,gt)|0)+Math.imul(A,dt)|0))<<13)|0;u=((a=a+Math.imul(A,gt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(B,rt),i=(i=Math.imul(B,nt))+Math.imul(N,rt)|0,a=Math.imul(N,nt),n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ot)|0)+Math.imul(R,at)|0,a=a+Math.imul(R,ot)|0,n=n+Math.imul(P,lt)|0,i=(i=i+Math.imul(P,ut)|0)+Math.imul(I,lt)|0,a=a+Math.imul(I,ut)|0,n=n+Math.imul(C,ht)|0,i=(i=i+Math.imul(C,ft)|0)+Math.imul(L,ht)|0,a=a+Math.imul(L,ft)|0;var Lt=(u+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(S,dt)|0))<<13)|0;u=((a=a+Math.imul(S,gt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(B,at),i=(i=Math.imul(B,ot))+Math.imul(N,at)|0,a=Math.imul(N,ot),n=n+Math.imul(O,lt)|0,i=(i=i+Math.imul(O,ut)|0)+Math.imul(R,lt)|0,a=a+Math.imul(R,ut)|0,n=n+Math.imul(P,ht)|0,i=(i=i+Math.imul(P,ft)|0)+Math.imul(I,ht)|0,a=a+Math.imul(I,ft)|0;var zt=(u+(n=n+Math.imul(C,dt)|0)|0)+((8191&(i=(i=i+Math.imul(C,gt)|0)+Math.imul(L,dt)|0))<<13)|0;u=((a=a+Math.imul(L,gt)|0)+(i>>>13)|0)+(zt>>>26)|0,zt&=67108863,n=Math.imul(B,lt),i=(i=Math.imul(B,ut))+Math.imul(N,lt)|0,a=Math.imul(N,ut),n=n+Math.imul(O,ht)|0,i=(i=i+Math.imul(O,ft)|0)+Math.imul(R,ht)|0,a=a+Math.imul(R,ft)|0;var Pt=(u+(n=n+Math.imul(P,dt)|0)|0)+((8191&(i=(i=i+Math.imul(P,gt)|0)+Math.imul(I,dt)|0))<<13)|0;u=((a=a+Math.imul(I,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(B,ht),i=(i=Math.imul(B,ft))+Math.imul(N,ht)|0,a=Math.imul(N,ft);var It=(u+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(R,dt)|0))<<13)|0;u=((a=a+Math.imul(R,gt)|0)+(i>>>13)|0)+(It>>>26)|0,It&=67108863;var Dt=(u+(n=Math.imul(B,dt))|0)+((8191&(i=(i=Math.imul(B,gt))+Math.imul(N,dt)|0))<<13)|0;return u=((a=Math.imul(N,gt))+(i>>>13)|0)+(Dt>>>26)|0,Dt&=67108863,l[0]=vt,l[1]=mt,l[2]=yt,l[3]=xt,l[4]=bt,l[5]=_t,l[6]=wt,l[7]=Mt,l[8]=At,l[9]=kt,l[10]=Tt,l[11]=St,l[12]=Et,l[13]=Ct,l[14]=Lt,l[15]=zt,l[16]=Pt,l[17]=It,l[18]=Dt,0!==u&&(l[19]=u,r.length++),r};function p(t,e,r){return(new d).mulp(t,e,r)}function d(t,e){this.x=t,this.y=e}Math.imul||(f=h),i.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?f(this,t,e):r<63?h(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,a=0;a>>26)|0)>>>26,o&=67108863}r.words[a]=s,n=o,o=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,t,e):p(this,t,e)},d.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},d.prototype.permute=function(t,e,r,n,i,a){for(var o=0;o>>=1)i++;return 1<>>=13,n[2*o+1]=8191&a,a>>>=13;for(o=2*e;o>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,a=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(e=0;e>>26-n}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=i);u--){var h=0|this.words[u];this.words[u]=c<<26-a|h>>>a,c=h&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(l/67108864|0),this.words[i+n]=67108863&a}for(;i>26,this.words[i+n]=67108863&a;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),a=t,o=0|a.words[a.length-1];0!==(r=26-this._countBits(o))&&(a=a.ushln(r),n.iushln(r),o=0|a.words[a.length-1]);var s,l=n.length-a.length;if("mod"!==e){(s=new i(null)).length=l+1,s.words=new Array(s.length);for(var u=0;u=0;h--){var f=67108864*(0|n.words[a.length+h])+(0|n.words[a.length+h-1]);for(f=Math.min(f/o|0,67108863),n._ishlnsubmul(a,f,h);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(a,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(a=s.div.neg()),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.iadd(t)),{div:a,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(a=s.div.neg()),{div:a,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var a,o,s},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++u;for(var c=n.clone(),h=e.clone();!e.isZero();){for(var f=0,p=1;0==(e.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(e.iushrn(f);f-- >0;)(a.isOdd()||o.isOdd())&&(a.iadd(c),o.isub(h)),a.iushrn(1),o.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(s.isOdd()||l.isOdd())&&(s.iadd(c),l.isub(h)),s.iushrn(1),l.iushrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.iushln(u)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a,o=new i(1),s=new i(0),l=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);for(var h=0,f=1;0==(n.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(n.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(s)):(n.isub(e),s.isub(o))}return(a=0===e.cmpn(1)?o:s).cmpn(0)<0&&a.iadd(t),a},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,s&=67108863,this.words[o]=s}return 0!==a&&(this.words[o]=a,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function x(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function b(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function w(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,i=a}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new y;else if("p192"===t)e=new x;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new b}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var a=this.m.subn(1),o=0;!a.isZero()&&0===a.andln(1);)o++,a.iushrn(1);r(!a.isZero());var s=new i(1).toRed(this),l=s.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,u).cmp(l);)c.redIAdd(l);for(var h=this.pow(c,a),f=this.pow(t,a.addn(1).iushrn(1)),p=this.pow(t,a),d=o;0!==p.cmp(s);){for(var g=p,v=0;0!==g.cmp(s);v++)g=g.redSqr();r(v=0;n--){for(var u=e.words[n],c=l-1;c>=0;c--){var h=u>>c&1;a!==r[0]&&(a=this.sqr(a)),0!==h||0!==o?(o<<=1,o|=h,(4===++s||0===n&&0===c)&&(a=this.mul(a,r[o]),s=0,o=0)):s=0}l=26}return a},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new w(t)},n(w,_),w.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},w.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},w.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},w.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).iushrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},w.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(cA,this),cA=cA.exports;var hA=function(t){return t.cmp(new cA(0))};var fA={};(function(t){var e=!1;if("undefined"!=typeof Float64Array){var r=new Float64Array(1),n=new Uint32Array(r.buffer);if(r[0]=1,e=!0,1072693248===n[1]){(fA=function(t){return r[0]=t,[n[0],n[1]]}).pack=function(t,e){return n[0]=t,n[1]=e,r[0]},fA.lo=function(t){return r[0]=t,n[0]},fA.hi=function(t){return r[0]=t,n[1]}}else if(1072693248===n[0]){(fA=function(t){return r[0]=t,[n[1],n[0]]}).pack=function(t,e){return n[1]=t,n[0]=e,r[0]},fA.lo=function(t){return r[0]=t,n[1]},fA.hi=function(t){return r[0]=t,n[0]}}else e=!1}if(!e){var i=new t(8);(fA=function(t){return i.writeDoubleLE(t,0,!0),[i.readUInt32LE(0,!0),i.readUInt32LE(4,!0)]}).pack=function(t,e){return i.writeUInt32LE(t,0,!0),i.writeUInt32LE(e,4,!0),i.readDoubleLE(0,!0)},fA.lo=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(0,!0)},fA.hi=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(4,!0)}}fA.sign=function(t){return fA.hi(t)>>>31},fA.exponent=function(t){return(fA.hi(t)<<1>>>21)-1023},fA.fraction=function(t){var e=fA.lo(t),r=fA.hi(t),n=1048575&r;return 2146435072&r&&(n+=1<<20),[e,n]},fA.denormalized=function(t){return!(2146435072&fA.hi(t))}}).call(this,Rb.Buffer);var pA=function(t){var e=fA.exponent(t);return e<52?new cA(t):new cA(t*Math.pow(2,52-e)).ushln(e-52)};var dA=function(t,e){var r=hA(t),n=hA(e);if(0===r)return[pA(0),pA(1)];if(0===n)return[pA(0),pA(0)];n<0&&(t=t.neg(),e=e.neg());var i=t.gcd(e);if(i.cmpn(1))return[t.div(i),e.div(i)];return[t,e]};var gA=function(t,e){return dA(t[0].mul(e[1]),t[1].mul(e[0]))};var vA=function(t){return t&&"object"==typeof t&&Boolean(t.words)};var mA=function(t){return Array.isArray(t)&&2===t.length&&vA(t[0])&&vA(t[1])};var yA=function(t){return new cA(t)};var xA=function t(e,r){if(mA(e))return r?gA(e,t(r)):[e[0].clone(),e[1].clone()];var n=0;var i,a;if(vA(e))i=e.clone();else if("string"==typeof e)i=yA(e);else{if(0===e)return[pA(0),pA(1)];if(e===Math.floor(e))i=pA(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),n-=256;i=pA(e)}}if(mA(r))i.mul(r[1]),a=r[0].clone();else if(vA(r))a=r.clone();else if("string"==typeof r)a=yA(r);else if(r)if(r===Math.floor(r))a=pA(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),n+=256;a=pA(r)}else a=pA(1);n>0?i=i.ushln(n):n<0&&(a=a.ushln(-n));return dA(i,a)};var bA=function(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var i=0;i20)return 52;return r+32};var MA=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.abs().divmod(r.abs()),i=n.div,a=bA(i),o=n.mod,s=e.negative!==r.negative?-1:1;if(0===o.cmpn(0))return s*a;if(a){var l=wA(a)+4,u=bA(o.ushln(l).divRound(r));return s*(a+u*Math.pow(2,-l))}var c=r.bitLength()-o.bitLength()+53,u=bA(o.ushln(c).divRound(r));return c<1023?s*u*Math.pow(2,-c):(u*=Math.pow(2,-1023),s*u*Math.pow(2,1023-c))};var AA={},kA="d",TA="ax",SA="vv",EA="fp",CA="es",LA="rs",zA="re",PA="rb",IA="ri",DA="rp",OA="bs",RA="be",FA="bb",BA="bi",NA="bp",jA="rv",VA="Q",UA=[kA,TA,SA,LA,zA,PA,IA,OA,RA,FA,BA];function qA(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],n=UA.slice();t||n.splice(3,0,EA);var i=["function "+e+"("+n.join()+"){"];function a(e,n){var a=function(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",UA.join(),"){","var ",CA,"=2*",kA,";"],a="for(var i="+LA+","+DA+"="+CA+"*"+LA+";i<"+zA+";++i,"+DA+"+="+CA+"){var x0="+PA+"["+TA+"+"+DA+"],x1="+PA+"["+TA+"+"+DA+"+"+kA+"],xi="+IA+"[i];",o="for(var j="+OA+","+NA+"="+CA+"*"+OA+";j<"+RA+";++j,"+NA+"+="+CA+"){var y0="+FA+"["+TA+"+"+NA+"],"+(r?"y1="+FA+"["+TA+"+"+NA+"+"+kA+"],":"")+"yi="+BA+"[j];";return t?i.push(a,VA,":",o):i.push(o,VA,":",a),r?i.push("if(y1"+RA+"-"+OA+"){"),t?(a(!0,!1),i.push("}else{"),a(!1,!1)):(i.push("if("+EA+"){"),a(!0,!0),i.push("}else{"),a(!0,!1),i.push("}}else{if("+EA+"){"),a(!1,!0),i.push("}else{"),a(!1,!1),i.push("}")),i.push("}}return "+e);var o=r.join("")+i.join("");return new Function(o)()}AA.partial=qA(!1),AA.full=qA(!0);var HA=function(t,e){var r="abcdef".split("").concat(e),n=[];t.indexOf("lo")>=0&&n.push("lo=e[k+n]");t.indexOf("hi")>=0&&n.push("hi=e[k+o]");return r.push(GA.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)},GA="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m";var WA=function(t,e,r,n,i,a){if(n<=r+1)return r;var o=r,s=n,l=n+r>>>1,u=2*t,c=l,h=i[u*l+e];for(;o=v?(c=g,h=v):d>=y?(c=p,h=d):(c=m,h=y):v>=y?(c=g,h=v):y>=d?(c=p,h=d):(c=m,h=y);for(var x=u*(s-1),b=u*c,_=0;_r&&i[h+e]>u;--c,h-=o){for(var f=h,p=h+o,d=0;d>1,l=s-i,u=s+i,c=a,h=l,f=s,p=u,d=o,g=e+1,v=r-1,m=0;nk(c,h,n)&&(m=c,c=h,h=m);nk(p,d,n)&&(m=p,p=d,d=m);nk(c,f,n)&&(m=c,c=f,f=m);nk(h,f,n)&&(m=h,h=f,f=m);nk(c,p,n)&&(m=c,c=p,p=m);nk(f,p,n)&&(m=f,f=p,p=m);nk(h,d,n)&&(m=h,h=d,d=m);nk(h,f,n)&&(m=h,h=f,f=m);nk(p,d,n)&&(m=p,p=d,d=m);var y=n[2*h];var x=n[2*h+1];var b=n[2*p];var _=n[2*p+1];var w=2*c;var M=2*f;var A=2*d;var k=2*a;var T=2*s;var S=2*o;for(var E=0;E<2;++E){var C=n[w+E],L=n[M+E],z=n[A+E];n[k+E]=C,n[T+E]=L,n[S+E]=z}tk(l,e,n);tk(u,r,n);for(var P=g;P<=v;++P)if(ik(P,y,x,n))P!==g&&$A(P,g,n),++g;else if(!ik(P,b,_,n))for(;;){if(ik(v,b,_,n)){ik(v,y,x,n)?(ek(P,g,v,n),++g,--v):($A(P,v,n),--v);break}if(--vt;){var u=r[l-2],c=r[l-1];if(ur[e+1])}function ik(t,e,r,n){var i=n[t*=2];return i>>1;JA(pk,y);for(var x=0,b=0,d=0;d=ok)dk(uk,ck,b--,_=_-ok|0);else if(_>=0)dk(sk,lk,x--,_);else if(_<=-ok){_=-_-ok|0;for(var w=0;w>>1;JA(pk,y);for(var x=0,b=0,_=0,d=0;d>1==pk[2*d+3]>>1&&(M=2,d+=1),w<0){for(var A=-(w>>1)-1,k=0;k<_;++k){var T=e(hk[k],A);if(void 0!==T)return T}if(0!==M)for(var k=0;k>1)-1;0===M?dk(sk,lk,x--,A):1===M?dk(uk,ck,b--,A):2===M&&dk(hk,fk,_--,A)}}},scanBipartite:function(t,e,r,n,i,a,o,s,l,u,c,h){var f=0,p=2*t,d=e,g=e+t,v=1,m=1;n?m=ok:v=ok;for(var y=i;y>>1;JA(pk,w);for(var M=0,y=0;y=ok?(k=!n,x-=ok):(k=!!n,x-=1),k)gk(sk,lk,M++,x);else{var T=h[x],S=p*x,E=c[S+e+1],C=c[S+e+1+t];t:for(var L=0;L>>1;JA(pk,x);for(var b=0,g=0;g=ok)sk[b++]=v-ok;else{var w=c[v-=1],M=f*v,A=u[M+e+1],k=u[M+e+1+t];t:for(var T=0;T=0;--T)if(sk[T]===v){for(var L=T+1;L0;){var f=(c-=1)*Ek,p=Lk[f],d=Lk[f+1],g=Lk[f+2],v=Lk[f+3],m=Lk[f+4],y=Lk[f+5],x=c*Ck,b=zk[x],_=zk[x+1],w=1&y,M=!!(16&y),A=i,k=a,T=s,S=l;if(w&&(A=s,k=l,T=i,S=a),!(2&y&&(g=Ak(t,p,d,g,A,k,_),d>=g)||4&y&&(d=kk(t,p,d,g,A,k,b))>=g)){var E=g-d,C=m-v;if(M){if(t*E*(E+C)<_k){if(void 0!==(u=ak.scanComplete(t,p,e,d,g,A,k,v,m,T,S)))return u;continue}}else{if(t*Math.min(E,C)=p0)&&!(p1>=hi)",["p0","p1"]),Mk=HA("lo===p0",["p0"]),Ak=HA("lo>>1;if(!(o<=0)){var s,l=__.mallocDouble(2*o*i),u=__.mallocInt32(i);if((i=Bk(t,o,l,u))>0){if(1===o&&n)ak.init(i),s=ak.sweepComplete(o,r,0,i,l,u,0,i,l,u);else{var c=__.mallocDouble(2*o*a),h=__.mallocInt32(a);(a=Bk(e,o,c,h))>0&&(ak.init(i+a),s=1===o?ak.sweepBipartite(o,r,0,i,l,u,0,a,c,h):vk(o,r,n,i,l,u,a,c,h),__.free(c),__.free(h))}__.free(l),__.free(u)}return s}}}function jk(t,e){Ok.push([t,e])}var Vk=function(t,e){return dA(t[0].mul(e[0]),t[1].mul(e[1]))};var Uk=function(t){return hA(t[0])*hA(t[1])};var qk=function(t,e){return dA(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))};var Hk=function(t,e){return dA(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))};var Gk=function(t,e){for(var r=t.length,n=new Array(r),i=0;i>>0,Qk=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-Jk:Jk;var r=fA.hi(t),n=fA.lo(t);e>t==t>0?n===Kk?(r+=1,n=0):n+=1:0===n?(n=Kk,r-=1):n-=1;return fA.pack(n,r)};var $k=function(t){for(var e=new Array(t.length),r=0;r0&&a>0||i<0&&a<0)return!1;var o=eT(r,t,e),s=eT(n,t,e);if(o>0&&s>0||o<0&&s<0)return!1;if(0===i&&0===a&&0===o&&0===s)return function(t,e,r,n){for(var i=0;i<2;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],h=Math.min(u,c),f=Math.max(u,c);if(fe[2]?1:0)}function hT(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--a){var d=e[o=(w=n[a])[0]],g=d[0],v=d[1],m=t[g],y=t[v];if((m[0]-y[0]||m[1]-y[1])<0){var x=g;g=v,v=x}d[0]=g;var b,_=d[1]=w[1];for(i&&(b=d[2]);a>0&&n[a-1][0]===o;){var w,M=(w=n[--a])[1];i?e.push([_,M,b]):e.push([_,M]),_=M}i?e.push([_,v,b]):e.push([_,v])}return s}(t,e,i,o,r));return hT(e,s,r),!!s||(i.length>0||o.length>0)}var pT=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;n0?1:0},vT=function(t,e,r,n){var i=PM(e,r,n);if(0===i){var a=gT(PM(t,e,r)),o=gT(PM(t,e,n));if(a===o){if(0===a){var s=mT(t,e,r),l=mT(t,e,n);return s===l?0:s?1:-1}return 0}return 0===o?a>0?-1:mT(t,e,n)?-1:1:0===a?o>0?1:mT(t,e,r)?1:-1:gT(o-a)}var u=PM(t,e,r);if(u>0)return i>0&&PM(t,e,n)>0?1:-1;if(u<0)return i>0||PM(t,e,n)>0?1:-1;var c=PM(t,e,n);return c>0?1:mT(t,e,r)?1:-1};function mT(t,e,r){var n=fM(t[0],-e[0]),i=fM(t[1],-e[1]),a=fM(r[0],-e[0]),o=fM(r[1],-e[1]),s=gM(dT(n,a),dT(i,o));return s[s.length-1]>=0}var yT=function(t,e){for(var r=0|e.length,n=t.length,i=[new Array(r),new Array(r)],a=0;a0){a=i[u][r][0],s=u;break}o=a[1^s];for(var c=0;c<2;++c)for(var h=i[c][r],f=0;f0&&(a=p,o=d,s=c)}return n?o:(a&&l(a,s),o)}function c(t,r){var n=i[r][t][0],a=[t];l(n,r);for(var o=n[1^r];;){for(;o!==t;)a.push(o),o=u(a[a.length-2],o,!1);if(i[0][t].length+i[1][t].length===0)break;var s=a[a.length-1],c=t,h=a[1],f=u(s,c,!0);if(vT(e[s],e[c],e[h],e[f])<0)break;a.push(t),o=u(s,c)}return a}function h(t,e){return e[1]===e[e.length-1]}for(var a=0;a0;){i[0][a].length;var d=c(a,f);h(p,d)?p.push.apply(p,d):(p.length>0&&s.push(p),p=d)}p.length>0&&s.push(p)}return s};var xT=function(t,e){for(var r=pT(t,e.length),n=new Array(e.length),i=new Array(e.length),a=[],o=0;o0;){var l=a.pop();n[l]=!1;for(var u=r[l],o=0;o>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function _T(t,e,r,n){return new Function([bT("A","x"+t+"y",e,["y"],!1,n),bT("B","x"+t+"y",e,["y"],!0,n),bT("P","c(x,y)"+t+"0",e,["y","c"],!1,n),bT("Q","c(x,y)"+t+"0",e,["y","c"],!0,n),"function dispatchBsearch",r,"(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",r].join(""))()}var wT={ge:_T(">=",!1,"GE"),gt:_T(">",!1,"GT"),lt:_T("<",!0,"LT"),le:_T("<=",!0,"LE"),eq:_T("-",!0,"EQ",!0)},MT=0,AT=1,kT=function(t){if(!t||0===t.length)return new NT(null);return new NT(BT(t))};function TT(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}var ST=TT.prototype;function ET(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function CT(t,e){var r=BT(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function LT(t,e){var r=t.intervals([]);r.push(e),CT(t,r)}function zT(t,e){var r=t.intervals([]),n=r.indexOf(e);return n<0?MT:(r.splice(n,1),CT(t,r),AT)}function PT(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function DT(t,e){for(var r=0;r>1],i=[],a=[],o=[];for(r=0;r3*(e+1)?LT(this,t):this.left.insert(t):this.left=BT([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?LT(this,t):this.right.insert(t):this.right=BT([t]);else{var r=wT.ge(this.leftPoints,t,RT),n=wT.ge(this.rightPoints,t,FT);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},ST.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?zT(this,t):2===(a=this.left.remove(t))?(this.left=null,this.count-=1,AT):(a===AT&&(this.count-=1),a):MT}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:MT;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,n=this.left;n.right;)r=n,n=n.right;if(r===this)n.right=this.right;else{var i=this.left;a=this.right;r.count-=n.count,r.right=n.left,n.left=i,n.right=a}ET(this,n),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?ET(this,this.left):ET(this,this.right);return AT}for(i=wT.ge(this.leftPoints,t,RT);i3*(e-1)?zT(this,t):2===(a=this.right.remove(t))?(this.right=null,this.count-=1,AT):(a===AT&&(this.count-=1),a):MT;var a}},ST.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return IT(this.rightPoints,t,e)}return DT(this.leftPoints,e)},ST.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?IT(this.rightPoints,t,r):DT(this.leftPoints,r)};var jT=NT.prototype;jT.insert=function(t){this.root?this.root.insert(t):this.root=new TT(t[0],null,null,[t],[t])},jT.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==MT}return!1},jT.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},jT.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(jT,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(jT,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}});var VT=function(t){return new XT(t||$T,null)},UT=0,qT=1;function HT(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function GT(t){return new HT(t._color,t.key,t.value,t.left,t.right,t._count)}function WT(t,e){return new HT(t,e.key,e.value,e.left,e.right,e._count)}function YT(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function XT(t,e){this._compare=t,this.root=e}var ZT=XT.prototype;function JT(t,e){this.tree=t,this._stack=e}Object.defineProperty(ZT,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(ZT,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(ZT,"length",{get:function(){return this.root?this.root._count:0}}),ZT.insert=function(t,e){for(var r=this._compare,n=this.root,i=[],a=[];n;){var o=r(t,n.key);i.push(n),a.push(o),n=o<=0?n.left:n.right}i.push(new HT(UT,t,e,null,null,1));for(var s=i.length-2;s>=0;--s){n=i[s];a[s]<=0?i[s]=new HT(n._color,n.key,n.value,i[s+1],n.right,n._count+1):i[s]=new HT(n._color,n.key,n.value,n.left,i[s+1],n._count+1)}for(s=i.length-1;s>1;--s){var l=i[s-1];n=i[s];if(l._color===qT||n._color===qT)break;var u=i[s-2];if(u.left===l)if(l.left===n){if(!(c=u.right)||c._color!==UT){if(u._color=UT,u.left=l.right,l._color=qT,l.right=u,i[s-2]=l,i[s-1]=n,YT(u),YT(l),s>=3)(h=i[s-3]).left===u?h.left=l:h.right=l;break}l._color=qT,u.right=WT(qT,c),u._color=UT,s-=1}else{if(!(c=u.right)||c._color!==UT){if(l.right=n.left,u._color=UT,u.left=n.right,n._color=qT,n.left=l,n.right=u,i[s-2]=n,i[s-1]=l,YT(u),YT(l),YT(n),s>=3)(h=i[s-3]).left===u?h.left=n:h.right=n;break}l._color=qT,u.right=WT(qT,c),u._color=UT,s-=1}else if(l.right===n){if(!(c=u.left)||c._color!==UT){if(u._color=UT,u.right=l.left,l._color=qT,l.left=u,i[s-2]=l,i[s-1]=n,YT(u),YT(l),s>=3)(h=i[s-3]).right===u?h.right=l:h.left=l;break}l._color=qT,u.left=WT(qT,c),u._color=UT,s-=1}else{var c;if(!(c=u.left)||c._color!==UT){var h;if(l.left=n.right,u._color=UT,u.right=n.left,n._color=qT,n.right=l,n.left=u,i[s-2]=n,i[s-1]=l,YT(u),YT(l),YT(n),s>=3)(h=i[s-3]).right===u?h.right=n:h.left=n;break}l._color=qT,u.left=WT(qT,c),u._color=UT,s-=1}}return i[0]._color=qT,new XT(r,i[0])},ZT.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,i){if(r(e,i.key)<=0){var a;if(i.left&&(a=t(e,r,n,i.left)))return a;if(a=n(i.key,i.value))return a}if(i.right)return t(e,r,n,i.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,i,a){var o,s=n(e,a.key),l=n(r,a.key);if(s<=0){if(a.left&&(o=t(e,r,n,i,a.left)))return o;if(l>0&&(o=i(a.key,a.value)))return o}if(l>0&&a.right)return t(e,r,n,i,a.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(ZT,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new JT(this,t)}}),Object.defineProperty(ZT,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new JT(this,t)}}),ZT.at=function(t){if(t<0)return new JT(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new JT(this,[])},ZT.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<=0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new JT(this,n)},ZT.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new JT(this,n)},ZT.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new JT(this,n)},ZT.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new JT(this,n)},ZT.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new JT(this,n);r=i<=0?r.left:r.right}return new JT(this,[])},ZT.remove=function(t){var e=this.find(t);return e?e.remove():this},ZT.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var KT=JT.prototype;function QT(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function $T(t,e){return te?1:0}Object.defineProperty(KT,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(KT,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),KT.clone=function(){return new JT(this.tree,this._stack.slice())},KT.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new HT(r._color,r.key,r.value,r.left,r.right,r._count);for(var n=t.length-2;n>=0;--n){(r=t[n]).left===t[n+1]?e[n]=new HT(r._color,r.key,r.value,e[n+1],r.right,r._count):e[n]=new HT(r._color,r.key,r.value,r.left,e[n+1],r._count)}if((r=e[e.length-1]).left&&r.right){var i=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var a=e[i-1];e.push(new HT(r._color,a.key,a.value,r.left,r.right,r._count)),e[i-1].key=r.key,e[i-1].value=r.value;for(n=e.length-2;n>=i;--n)r=e[n],e[n]=new HT(r._color,r.key,r.value,r.left,e[n+1],r._count);e[i-1].left=e[i]}if((r=e[e.length-1])._color===UT){var o=e[e.length-2];o.left===r?o.left=null:o.right===r&&(o.right=null),e.pop();for(n=0;n=0;--a){if(e=t[a],0===a)return void(e._color=qT);if((r=t[a-1]).left===e){if((n=r.right).right&&n.right._color===UT)return i=(n=r.right=GT(n)).right=GT(n.right),r.right=n.left,n.left=r,n.right=i,n._color=r._color,e._color=qT,r._color=qT,i._color=qT,YT(r),YT(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),void(t[a-1]=n);if(n.left&&n.left._color===UT)return i=(n=r.right=GT(n)).left=GT(n.left),r.right=i.left,n.left=i.right,i.left=r,i.right=n,i._color=r._color,r._color=qT,n._color=qT,e._color=qT,YT(r),YT(n),YT(i),a>1&&((o=t[a-2]).left===r?o.left=i:o.right=i),void(t[a-1]=i);if(n._color===qT){if(r._color===UT)return r._color=qT,void(r.right=WT(UT,n));r.right=WT(UT,n);continue}n=GT(n),r.right=n.left,n.left=r,n._color=r._color,r._color=UT,YT(r),YT(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),t[a-1]=n,t[a]=r,a+11&&((o=t[a-2]).right===r?o.right=n:o.left=n),void(t[a-1]=n);if(n.right&&n.right._color===UT)return i=(n=r.left=GT(n)).right=GT(n.right),r.left=i.right,n.right=i.left,i.right=r,i.left=n,i._color=r._color,r._color=qT,n._color=qT,e._color=qT,YT(r),YT(n),YT(i),a>1&&((o=t[a-2]).right===r?o.right=i:o.left=i),void(t[a-1]=i);if(n._color===qT){if(r._color===UT)return r._color=qT,void(r.left=WT(UT,n));r.left=WT(UT,n);continue}var o;n=GT(n),r.left=n.right,n.right=r,n._color=r._color,r._color=UT,YT(r),YT(n),a>1&&((o=t[a-2]).right===r?o.right=n:o.left=n),t[a-1]=n,t[a]=r,a+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(KT,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(KT,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),KT.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(KT,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),KT.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new HT(n._color,n.key,t,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i)(n=e[i]).left===e[i+1]?r[i]=new HT(n._color,n.key,n.value,r[i+1],n.right,n._count):r[i]=new HT(n._color,n.key,n.value,n.left,r[i+1],n._count);return new XT(this.tree._compare,r[0])},KT.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(KT,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}});var tS=function(t,e){var r,n,i,a;if(e[0][0]e[1][0]))return eS(e,t);r=e[1],n=e[0]}if(t[0][0]t[1][0]))return-eS(t,e);i=t[1],a=t[0]}var o=PM(r,n,a),s=PM(r,n,i);if(o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;if(o=PM(a,i,n),s=PM(a,i,r),o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;return n[0]-a[0]};function eS(t,e){var r,n,i,a;if(e[0][0]e[1][0])){var o=Math.min(t[0][1],t[1][1]),s=Math.max(t[0][1],t[1][1]),l=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return su?o-u:s-u}r=e[1],n=e[0]}t[0][1]0)if(e[0]!==a[1][0])r=t,t=t.right;else{if(s=aS(t.right,e))return s;t=t.left}else{if(e[0]!==a[1][0])return t;var s;if(s=aS(t.right,e))return s;t=t.left}}return r}function oS(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function sS(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}nS.prototype.castUp=function(t){var e=wT.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=aS(this.slabs[e],t),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var i=null;if(r&&(i=r.key),e>0){var a=aS(this.slabs[e-1],t);a&&(i?tS(a.key,i)>0&&(i=a.key,n=a.value):(n=a.value,i=a.key))}var o=this.horizontal[e];if(o.length>0){var s=wT.ge(o,t[1],iS);if(s=o.length)return n;l=o[s]}}if(l.start)if(i){var u=PM(i[0],i[1],[t[0],l.y]);i[0][0]>i[1][0]&&(u=-u),u>0&&(n=l.index)}else n=l.index;else l.y!==t[1]&&(n=l.index)}}}return n};var lS=function(t){for(var e=t.length,r=[],n=[],i=0;i0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=uS(r,o[0],o[1]);if(o[0][0]0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(s<0))return 0;a=1,i=i.right}}return a}}(f.slabs,f.coordinates);return 0===n.length?p:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(hS(n),p)},uS=PM[3];function cS(){return!0}function hS(t){for(var e={},r=0;r0})).length,l=new Array(s),u=new Array(s),a=0;a0;){var z=C.pop(),P=_[z];Qx(P,function(t,e){return t-e});var I,D=P.length,O=L[z];if(0===O){var g=o[z];I=[g]}for(var a=0;a=0)&&(L[R]=1^O,C.push(R),0===O)){var g=o[R];E(g)||(g.reverse(),I.push(g))}}0===O&&r.push(I)}return r};function dS(t,e){for(var r=new Array(t),n=0;n>1,o=vS(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function _S(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==vS(t[p],a)););}return r}function wS(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return yS(e)},gS.skeleton=wS,gS.boundary=function(t){for(var e=[],r=0,n=t.length;r0)-(t<0)},MS.abs=function(t){var e=t>>31;return(t^e)-e},MS.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},MS.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},MS.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},MS.countTrailingZeros=AS,MS.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},MS.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},MS.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var kS=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|kS[t>>>16&255]<<8|kS[t>>>24&255]},MS.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},MS.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},MS.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},MS.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},MS.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>AS(t)+1};var TS=SS;function SS(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e>1,o=CS(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function DS(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==CS(t[p],a)););}return r}function OS(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return zS(e)},ES.skeleton=OS,ES.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function m(t){for(var e=g(t);;){var r=e,n=2*t+1,i=2*(t+1),a=t;if(n0;){var r=v(t);if(r>=0){var n=g(r);if(e0){var t=w[0];return d(0,k-1),k-=1,m(0),t}return-1}function b(t,e){var r=w[t];return s[r]===e?t:(s[r]=-1/0,y(t),x(),s[r]=e,y((k+=1)-1))}function _(t){if(!l[t]){l[t]=!0;var e=a[t],r=o[t];a[r]>=0&&(a[r]=e),o[e]>=0&&(o[e]=r),M[e]>=0&&b(M[e],p(e)),M[r]>=0&&b(M[r],p(r))}}for(var w=[],M=new Array(n),u=0;u>1;u>=0;--u)m(u);for(;;){var T=x();if(T<0||s[T]>r)break;_(T)}for(var S=[],u=0;u=0&&r>=0&&e!==r){var n=M[e],i=M[r];n!==i&&C.push([n,i])}}),ES.unique(ES.normalize(C)),{positions:S,edges:C}};var FS=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;n<1&&e("Must have at least one array argument");var i=t.scalarArguments||0;i<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;s=0?o[s]=!0:o[s]=!1;return function(t,e,r,n,i,a){var o=a.length,s=i.length;if(s<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var l="extractContour"+i.join("_"),u=[],c=[],h=[],f=0;f0&&v.push(US(f,i[p-1])+"*"+VS(i[p-1])),c.push(XS(f,i[p])+"=("+v.join("-")+")|0")}for(var f=0;f=0;--f)m.push(VS(i[f]));c.push(rE+"=("+m.join("*")+")|0",tE+"=mallocUint32("+rE+")",$S+"=mallocUint32("+rE+")",nE+"=0"),c.push(ZS(0)+"=0");for(var p=1;p<1<0;v=v-1&p)g.push($S+"["+nE+"+"+KS(v)+"]");g.push(QS(0));for(var v=0;v=0;--e)w(e,0);for(var r=[],e=0;e0){",YS(i[e]),"=1;");t(e-1,r|1<0;--r)e+=uE[r]/(t+r);var n=t+lE+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}(oE=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(cE(e));e-=1;for(var r=sE[0],n=1;n<9;n++)r+=sE[n]/(e+n);var i=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(i,e+.5)*Math.exp(-i)*r}).log=cE;var hE=function(t){var e=t.length;if(e0;--i)n=o[i],r=a[i],a[i]=a[n],a[n]=r,o[i]=o[r],o[r]=n,s=(s+r)*i;return __.freeUint32(o),__.freeUint32(a),s},dE.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,i,a,o=1;for((r=r||new Array(t))[0]=0,a=1;a0;--a)e=e-(n=e/o|0)*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r};var gE=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(oE(t+1)),r=[],n=0;n= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"}),mE=function(t,e){var r=[];return e=+e||0,vE(t.hi(t.shape[0]-1),r,e),r};var yE=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=mE(t,e),n=r.length,i=new Array(n),a=new Array(n),o=0;o c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],o=[],s=0;s>>7){");for(var s=0;s<1<<(1<128&&s%128==0){u.length>0&&c.push("}}");var h="vExtra"+u.length;n.push("case ",s>>>7,":",h,"(m&0x7f,",o.join(),");break;"),c=["function ",h,"(m,",o.join(),"){switch(m){"],u.push(c)}c.push("case ",127&s,":");for(var f=new Array(r),p=new Array(r),d=new Array(r),g=new Array(r),v=0,m=0;mm)&&!(s&1<0&&(M="+"+d[y]+"*c");var A=f[y].length/v*.5,k=.5+g[y]/v*.5;w.push("d"+y+"-"+k+"-"+A+"*("+f[y].join("+")+M+")/("+p[y].join("+")+")")}c.push("a.push([",w.join(),"]);","break;")}n.push("}},"),u.length>0&&c.push("}}");for(var T=[],s=0;s<1<8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height0&&(c+=.02);for(var f=new Float32Array(u),p=0,d=-.5*c,h=0;hs[M]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=g[n],a.uniforms.angle=v[n],l.drawArrays(l.TRIANGLES,s[M],s[A]-s[M]))),m[n]&&w&&(e[1^n]-=k*f*y[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=b[n],l.drawArrays(l.TRIANGLES,_,w)),e[1^n]=k*u[2+(1^n)]-1,p[n+2]&&(e[1^n]+=k*f*d[n+2],Ms[M]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=g[n+2],a.uniforms.angle=v[n+2],l.drawArrays(l.TRIANGLES,s[M],s[A]-s[M]))),m[n+2]&&w&&(e[1^n]+=k*f*y[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=b[n+2],l.drawArrays(l.TRIANGLES,_,w))}}(),CE.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,u=r.pixelRatio;if(this.titleCount){for(var c=0;c<2;++c)e[c]=2*(o[c]*u-a[c])/(a[2+c]-a[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),CE.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var u=0;u<2;++u){var c=a[u],h=a[u+2]-c,f=.5*(o[u+2]+o[u]),p=o[u+2]-o[u],d=l[u],g=l[u+2]-d,v=s[u],m=s[u+2]-v;e[u]=2*h/p*g/m,t[u]=2*(c-f)/p*g/m}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),CE.update=function(t){var e,r,n,i,a,o=[],s=t.ticks,l=t.bounds;for(a=0;a<2;++a){var u=[Math.floor(o.length/3)],c=[-1/0],h=s[a];for(e=0;ei||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var a=jE(n,e.stride.slice()),o=0;"float32"===r?o=t.FLOAT:"float64"===r?(o=t.FLOAT,a=!1,r="float32"):"uint8"===r?o=t.UNSIGNED_BYTE:(o=t.UNSIGNED_BYTE,a=!1,r="uint8");var s,l,u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=wb(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}o!==t.FLOAT||t.getExtension("OES_texture_float")||(o=t.UNSIGNED_BYTE,a=!1);var c=e.size;if(a)s=0===e.offset&&e.data.length===c?e.data:e.data.subarray(e.offset,e.offset+c);else{var h=[n[2],n[2]*n[0],1];l=__.malloc(c,r);var f=wb(l,n,h,0);"float32"!==r&&"float64"!==r||o!==t.UNSIGNED_BYTE?ib.assign(f,e):RE(f,e),s=l.subarray(0,c)}var p=VE(t);t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,o,s),a||__.free(l);return new BE(t,p,n[0],n[1],u,o)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")},PE=null,IE=null,DE=null;function OE(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var RE=function(t,e){ib.muls(t,e,255)};function FE(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function BE(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}var NE=BE.prototype;function jE(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function VE(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function UE(t,e,r,n,i){var a=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=VE(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new BE(t,o,e,r,n,i)}Object.defineProperties(NE,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&PE.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),IE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&PE.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),IE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),DE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),DE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(DE.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return FE(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return FE(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,FE(this,this._shape[0],t),t}}}),NE.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},NE.dispose=function(){this.gl.deleteTexture(this.handle)},NE.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},NE.setPixels=function(t,e,r,n){var i=this.gl;this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0;var a=OE(t)?t:t.raw;if(a){this._mipLevels.indexOf(n)<0?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,a),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,a)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,n,i,a,o,s){var l=s.dtype,u=s.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var c=0,h=0,f=jE(u,s.stride.slice());"float32"===l?c=t.FLOAT:"float64"===l?(c=t.FLOAT,f=!1,l="float32"):"uint8"===l?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,f=!1,l="uint8");if(2===u.length)h=t.LUMINANCE,u=[u[0],u[1],1],s=wb(s.data,u,[s.stride[0],s.stride[1],1],s.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])h=t.ALPHA;else if(2===u[2])h=t.LUMINANCE_ALPHA;else if(3===u[2])h=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}u[2]}h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i);if(h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var p=s.size,d=o.indexOf(n)<0;d&&o.push(n);if(c===a&&f)0===s.offset&&s.data.length===p?d?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data):d?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data.subarray(s.offset,s.offset+p)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data.subarray(s.offset,s.offset+p));else{var g;g=a===t.FLOAT?__.mallocFloat32(p):__.mallocUint8(p);var v=wb(g,u,[u[2],u[2]*u[0],1]);c===t.FLOAT&&a===t.UNSIGNED_BYTE?RE(v,s):ib.assign(v,s),d?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,g.subarray(0,p)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,g.subarray(0,p)),a===t.FLOAT?__.freeFloat32(g):__.freeUint8(g)}}(i,e,r,n,this.format,this.type,this._mipLevels,t)}};var qE,HE,GE,WE,YE=function(t,e,r,n){qE||(qE=t.FRAMEBUFFER_UNSUPPORTED,HE=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,GE=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,WE=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var i=t.getExtension("WEBGL_draw_buffers");!XE&&i&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);XE=new Array(r+1);for(var n=0;n<=r;++n){for(var i=new Array(r),a=0;aa||r<0||r>a)throw new Error("gl-fbo: Parameters are too large for FBO");var o=1;if("color"in(n=n||{})){if((o=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(o>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(o>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+o+" draw buffers")}}var s=t.UNSIGNED_BYTE,l=t.getExtension("OES_texture_float");if(n.float&&o>0){if(!l)throw new Error("gl-fbo: Context does not support floating point textures");s=t.FLOAT}else n.preferFloat&&o>0&&l&&(s=t.FLOAT);var u=!0;"depth"in n&&(u=!!n.depth);var c=!1;"stencil"in n&&(c=!!n.stencil);return new tC(t,e,r,s,o,u,c,i)},XE=null;function ZE(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function JE(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function KE(t){switch(t){case qE:throw new Error("gl-fbo: Framebuffer unsupported");case HE:throw new Error("gl-fbo: Framebuffer incomplete attachment");case GE:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case WE:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function QE(t,e,r,n,i,a){if(!n)return null;var o=zE(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function $E(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function tC(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var l=0;l1&&s.drawBuffersWEBGL(XE[o]);var f=r.getExtension("WEBGL_depth_texture");f?l?t.depth=QE(r,i,a,f.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u&&(t.depth=QE(r,i,a,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):u&&l?t._depth_rb=$E(r,i,a,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u?t._depth_rb=$E(r,i,a,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):l&&(t._depth_rb=$E(r,i,a,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var p=r.checkFramebufferStatus(r.FRAMEBUFFER);if(p!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),h=0;hi||r<0||r>i)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var a=ZE(n),o=0;othis.buffer.length){__.free(this.buffer);for(var n=this.buffer=__.mallocUint8(iC(r*e*4)),i=0;i=0){var g=e[d]-n[d]*(e[d+2]-e[d])/(n[d+2]-n[d]);0===d?o.drawLine(g,e[1],g,e[3],p[d],f[d]):o.drawLine(e[0],g,e[2],g,p[d],f[d])}}for(d=0;d=0;--t)this.objects[t].dispose();this.objects.length=0;for(t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},cC.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},cC.removeObject=function(t){for(var e=this.objects,r=0;r0){var m=r*c;o.drawBox(h-m,f-m,p+m,f+m,a),o.drawBox(h-m,d-m,p+m,d+m,a),o.drawBox(h-m,f-m,h+m,d+m,a),o.drawBox(p-m,f-m,p+m,d+m,a)}}}},vC.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},vC.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)};var mC=function(t,e){var r=new yC(t);return r.update(e),t.addOverlay(r),r};function yC(t){this.plot=t,this.enable=[!0,!0,!1,!1],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=[1/0,1/0]}var xC=yC.prototype;xC.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},xC.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),u=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,u,s[0],u,e[0],r[0]),t[1]&&a.drawLine(l,u,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,u,s[2],u,e[2],r[2]),t[3]&&a.drawLine(l,u,l,s[3],e[3],r[3])}},xC.dispose=function(){this.plot.removeOverlay(this)};var bC=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,i=e;try{var a=[t];0===t.indexOf("webgl")&&a.push("experimental-"+t);for(var o=0;o=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))},kC=function(){},TC=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=kC);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=Oe.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1},SC={};function EC(t){return t.target||t.srcElement||window}SC.buttons=function(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){if(2===(e=t.which))return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1<Math.abs(l)?(n.boxEnd[1]=n.boxStart[1]+Math.abs(s)*b*(l>=0?1:-1),n.boxEnd[1]u[3]&&(n.boxEnd[1]=u[3],n.boxEnd[0]=n.boxStart[0]+(u[3]-n.boxStart[1])/Math.abs(b))):(n.boxEnd[0]=n.boxStart[0]+Math.abs(l)/b*(s>=0?1:-1),n.boxEnd[0]u[2]&&(n.boxEnd[0]=u[2],n.boxEnd[1]=n.boxStart[1]+(u[2]-n.boxStart[0])*Math.abs(b)))}}else n.boxEnabled?(s=n.boxStart[0]!==n.boxEnd[0],l=n.boxStart[1]!==n.boxEnd[1],s||l?(s&&(g(0,n.boxStart[0],n.boxEnd[0]),t.xaxis.autorange=!1),l&&(g(1,n.boxStart[1],n.boxEnd[1]),t.yaxis.autorange=!1),t.relayoutCallback()):t.glplot.setDirty(),n.boxEnabled=!1,n.boxInited=!1):n.boxInited&&(n.boxInited=!1);break;case"pan":n.boxEnabled=!1,n.boxInited=!1,e?(n.panning||(n.dragStart[0]=a,n.dragStart[1]=o),Math.abs(n.dragStart[0]-a)r?r:t:te?e:t};var BC={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]},NC=function(){for(var t=0;t10&&/[0-9](?:\s|\/)/.test(r)&&(a=r.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),i=r.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof r)i="rgb",a=[r>>>16,(65280&r)>>>8,255&r];else if(VC(r)){var h=NC(r.r,r.red,r.R,null);null!==h?(i="rgb",a=[h,NC(r.g,r.green,r.G),NC(r.b,r.blue,r.B)]):(i="hsl",a=[NC(r.h,r.hue,r.H),NC(r.s,r.saturation,r.S),NC(r.l,r.lightness,r.L,r.b,r.brightness)]),o=NC(r.a,r.alpha,r.opacity,1),null!=r.opacity&&(o/=100)}else(Array.isArray(r)||t.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(r))&&(a=[r[0],r[1],r[2]],i="rgb",o=4===r.length?r[3]:1);return{space:i,values:a,alpha:o}};var e={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var qC=function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[a=255*l,a,a];e=2*l-(r=l<.5?l*(1+s):l+s-l*s),i=[0,0,0];for(var u=0;u<3;u++)(n=o+1/3*-(u-1))<0?n++:n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[u]=255*a;return i},HC=function(t){switch(t){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}},GC=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=HC(e),n=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(n.set(t),n);var i="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:255,i&&(n[0]/=255,n[1]/=255,n[2]/=255,n[3]/=255),n):(t.length&&"string"!=typeof t||((t=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=UC(t);return r.space?((e=Array(3))[0]=FC(r.values[0],0,255),e[1]=FC(r.values[1],0,255),e[2]=FC(r.values[2],0,255),"h"===r.space[0]&&(e=qC(e)),e.push(FC(r.alpha,0,1)),e):[]}(t))[0]/=255,t[1]/=255,t[2]/=255),i?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:1):(n[0]=FC(Math.round(255*t[0]),0,255),n[1]=FC(Math.round(255*t[1]),0,255),n[2]=FC(Math.round(255*t[2]),0,255),n[3]=null==t[3]?255:FC(Math.floor(255*t[3]),0,255)),n)};var WC=function(t){return t?GC(t):[0,0,0,1]};function YC(t){this.scene=t,this.gl=t.gl,this.pixelRatio=t.pixelRatio,this.screenBox=[0,0,1,1],this.viewBox=[0,0,1,1],this.dataBox=[-1,-1,1,1],this.borderLineEnable=[!1,!1,!1,!1],this.borderLineWidth=[1,1,1,1],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.ticks=[[],[]],this.tickEnable=[!0,!0,!1,!1],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labels=["x","y"],this.labelEnable=[!0,!0,!1,!1],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelPad=[15,15,15,15],this.labelSize=[12,12],this.labelFont=["sans-serif","sans-serif"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.title="",this.titleEnable=!0,this.titleCenter=[0,0,0,0],this.titleAngle=0,this.titleColor=[0,0,0,1],this.titleFont="sans-serif",this.titleSize=18,this.gridLineEnable=[!0,!0],this.gridLineColor=[[0,0,0,.5],[0,0,0,.5]],this.gridLineWidth=[1,1],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[1,1],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderColor=!1,this.backgroundColor=[0,0,0,0],this.static=this.scene.staticPlot}var XC=YC.prototype,ZC=["xaxis","yaxis"];XC.merge=function(t){var e,r,n,i,a,o,s,l,u,c,h;for(this.titleEnable=!1,this.backgroundColor=WC(t.plot_bgcolor),c=0;c<2;++c){var f=(e=ZC[c]).charAt(0);for(n=(r=t[this.scene[e]._name]).title===this.scene.fullLayout._dfltTitle[f]?"":r.title,h=0;h<=2;h+=2)this.labelEnable[c+h]=!1,this.labels[c+h]=AC(n),this.labelColor[c+h]=WC(r.titlefont.color),this.labelFont[c+h]=r.titlefont.family,this.labelSize[c+h]=r.titlefont.size,this.labelPad[c+h]=this.getLabelPad(e,r),this.tickEnable[c+h]=!1,this.tickColor[c+h]=WC((r.tickfont||{}).color),this.tickAngle[c+h]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[c+h]=this.getTickPad(r),this.tickMarkLength[c+h]=0,this.tickMarkWidth[c+h]=r.tickwidth||0,this.tickMarkColor[c+h]=WC(r.tickcolor),this.borderLineEnable[c+h]=!1,this.borderLineColor[c+h]=WC(r.linecolor),this.borderLineWidth[c+h]=r.linewidth||0;s=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!s,o=this.hasAxisInAltrPos(e,r)&&!s,i=r.mirror||!1,l=s?-1!==String(i).indexOf("all"):!!i,u=s?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[c]=!0:o&&(this.labelEnable[c+2]=!0),a?this.tickEnable[c]=r.showticklabels:o&&(this.tickEnable[c+2]=r.showticklabels),(a||l)&&(this.borderLineEnable[c]=r.showline),(o||l)&&(this.borderLineEnable[c+2]=r.showline),(a||u)&&(this.tickMarkLength[c]=this.getTickMarkLength(r)),(o||u)&&(this.tickMarkLength[c+2]=this.getTickMarkLength(r)),this.gridLineEnable[c]=r.showgrid,this.gridLineColor[c]=WC(r.gridcolor),this.gridLineWidth[c]=r.gridwidth,this.zeroLineEnable[c]=r.zeroline,this.zeroLineColor[c]=WC(r.zerolinecolor),this.zeroLineWidth[c]=r.zerolinewidth}},XC.hasSharedAxis=function(t){var e=this.scene,r=e.fullLayout._subplots.gl2d;return 0!==ri.findSubplotsWithAxis(r,t).indexOf(e.id)},XC.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},XC.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},XC.getLabelPad=function(t,e){var r=e.titlefont.size,n=e.showticklabels;return"xaxis"===t?"top"===e.side?r*(1.5+(n?1:0))-10:r*(1.5+(n?.5:0))-10:"yaxis"===t?"right"===e.side?10+r*(1.5+(n?1:.5)):10+r*(1.5+(n?.5:0)):void 0},XC.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},XC.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e};var JC,KC,QC=function(t){return new YC(t)},$C=Gm.enforce,tL=Gm.clean,eL=Nn,rL=["xaxis","yaxis"],nL=Te.SUBPLOT_PATTERN;function iL(t,e){this.container=t.container,this.graphDiv=t.graphDiv,this.pixelRatio=t.plotGlPixelRatio||window.devicePixelRatio,this.id=t.id,this.staticPlot=!!t.staticPlot,this.scrollZoom=this.graphDiv._context.scrollZoom,this.fullData=null,this.updateRefs(e),this.makeFramework(),this.glplotOptions=QC(this),this.glplotOptions.merge(e),this.glplot=lC(this.glplotOptions),this.camera=RC(this),this.traces={},this.spikes=mC(this.glplot),this.selectBox=dC(this.glplot,{innerFill:!1,outerFill:!0}),this.lastButtonState=0,this.pickResult=null,this.isMouseOver=!0,this.stopped=!1,this.redraw=this.draw.bind(this),this.redraw()}var aL=iL,oL=iL.prototype;oL.makeFramework=function(){if(this.staticPlot){if(!(KC||(JC=document.createElement("canvas"),KC=_C({canvas:JC,preserveDrawingBuffer:!1,premultipliedAlpha:!0,antialias:!0}))))throw new Error("Error creating static canvas/context for image server");this.canvas=JC,this.gl=KC}else{var t=this.container.querySelector(".gl-canvas-focus"),e=_C({canvas:t,preserveDrawingBuffer:!0,premultipliedAlpha:!0});e||TC(this),this.canvas=t,this.gl=e}var r=this.canvas;r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style["pointer-events"]="none",this.updateSize(r),r.className+=" user-select-none";var n=this.svgContainer=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.top=n.style.left="0px",n.style.width=n.style.height="100%",n.style["z-index"]=20,n.style["pointer-events"]="none";var i=this.mouseContainer=document.createElement("div");i.style.position="absolute",i.style["pointer-events"]="auto",this.pickCanvas=this.container.querySelector(".gl-canvas-pick");var a=this.container;a.appendChild(n),a.appendChild(i);var o=this;i.addEventListener("mouseout",function(){o.isMouseOver=!1,o.unhover()}),i.addEventListener("mouseover",function(){o.isMouseOver=!0})},oL.toImage=function(t){t||(t="png"),this.stopped=!0,this.staticPlot&&this.container.appendChild(JC),this.updateSize(this.canvas);var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.clearColor(1,1,1,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),this.glplot.setDirty(),this.glplot.draw(),e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;a>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function xL(t,e,r,n){return new Function([yL("A","x"+t+"y",e,["y"],n),yL("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var bL={ge:xL(">=",!1,"GE"),gt:xL(">",!1,"GT"),lt:xL("<",!0,"LT"),le:xL("<=",!0,"LE"),eq:xL("-",!0,"EQ",!0)},_L=function(t,e){var r=t.gl,n=Bw(r,mL.vertex,mL.fragment),i=Bw(r,mL.pickVertex,mL.pickFragment),a=S_(r),o=S_(r),s=S_(r),l=S_(r),u=new wL(t,n,i,a,o,s,l);return u.update(e),t.addObject(u),u};function wL(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.weightBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.xData=[],this.yData=[],this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.pickOffset=0}var ML,AL=wL.prototype,kL=[0,0,1,0,0,1,1,0,1,1,0,1];function TL(t,e){this.scene=t,this.uid=e,this.type="heatmapgl",this.name="",this.hoverinfo="all",this.xData=[],this.yData=[],this.zData=[],this.textLabels=[],this.idToIndex=[],this.bounds=[0,0,0,0],this.options={z:[],x:[],y:[],shape:[0,0],colorLevels:[0],colorValues:[0,0,0,1]},this.heatmap=_L(t.glplot,this.options),this.heatmap._trace=this}AL.draw=(ML=[1,0,0,0,1,0,0,0,1],function(){var t=this.plot,e=this.shader,r=this.bounds,n=this.numVertices;if(!(n<=0)){var i=t.gl,a=t.dataBox,o=r[2]-r[0],s=r[3]-r[1],l=a[2]-a[0],u=a[3]-a[1];ML[0]=2*o/l,ML[4]=2*s/u,ML[6]=2*(r[0]-a[0])/l-1,ML[7]=2*(r[1]-a[1])/u-1,e.bind();var c=e.uniforms;c.viewTransform=ML,c.shape=this.shape;var h=e.attributes;this.positionBuffer.bind(),h.position.pointer(),this.weightBuffer.bind(),h.weight.pointer(i.UNSIGNED_BYTE,!1),this.colorBuffer.bind(),h.color.pointer(i.UNSIGNED_BYTE,!0),i.drawArrays(i.TRIANGLES,0,n)}}),AL.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.bounds,o=this.numVertices;if(!(o<=0)){var s=n.gl,l=n.dataBox,u=a[2]-a[0],c=a[3]-a[1],h=l[2]-l[0],f=l[3]-l[1];t[0]=2*u/h,t[4]=2*c/f,t[6]=2*(a[0]-l[0])/h-1,t[7]=2*(a[1]-l[1])/f-1;for(var p=0;p<4;++p)e[p]=r>>8*p&255;this.pickOffset=r,i.bind();var d=i.uniforms;d.viewTransform=t,d.pickOffset=e,d.shape=this.shape;var g=i.attributes;return this.positionBuffer.bind(),g.position.pointer(),this.weightBuffer.bind(),g.weight.pointer(s.UNSIGNED_BYTE,!1),this.idBuffer.bind(),g.pickId.pointer(s.UNSIGNED_BYTE,!1),s.drawArrays(s.TRIANGLES,0,o),r+this.shape[0]*this.shape[1]}}}(),AL.pick=function(t,e,r){var n=this.pickOffset,i=this.shape[0]*this.shape[1];if(r=n+i)return null;var a=r-n,o=this.xData,s=this.yData;return{object:this,pointId:a,dataCoord:[o[a%this.shape[0]],s[a/this.shape[0]|0]]}},AL.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||db(e[0]),n=t.y||db(e[1]),i=t.z||new Float32Array(e[0]*e[1]);this.xData=r,this.yData=n;var a=t.colorLevels||[0],o=t.colorValues||[0,0,0,1],s=a.length,l=this.bounds,u=l[0]=r[0],c=l[1]=n[0],h=1/((l[2]=r[r.length-1])-u),f=1/((l[3]=n[n.length-1])-c),p=e[0],d=e[1];this.shape=[p,d];var g=(p-1)*(d-1)*(kL.length>>>1);this.numVertices=g;for(var v=__.mallocUint8(4*g),m=__.mallocFloat32(2*g),y=__.mallocUint8(2*g),x=__.mallocUint32(g),b=0,_=0;_u.size/1.9?u.size:u.size/Math.ceil(u.size/g);var _=u.start+(u.size-g)/2;v=_-g*Math.ceil((_-v)/g)}for(o=0;o=0&&p=0;n--)s(n);else if("increasing"===e){for(n=1;n=0;n--)t[n]+=t[n+1];"exclude"===r&&(t.push(0),t.shift())}}(a,c.direction,c.currentbin);var j=Math.min(i.length,a.length),V=[],U=0,q=j-1;for(n=0;n=U;n--)if(a[n]){q=n;break}for(n=U;n<=q;n++)if(r(i[n])&&r(a[n])){var H={p:i[n],s:a[n],b:0};c.enabled||(H.pts=w[n],O?H.p0=H.p1=w[n].length?v[w[n][0]]:i[n]:(H.p0=I(y[n]),H.p1=I(y[n+1],!0))),V.push(H)}return 1===V.length&&(V[0].width1=ri.tickIncrement(V[0].p,g.size,!1,u)-V[0].p),ma(V,e),ne.isArrayOrTypedArray(e.selectedpoints)&&ne.tagSelected(V,e,B),V}},UL.setPositions=Vo,UL.plot=Lo,UL.style=$o,UL.colorbar=is,UL.hoverPoints=function(t,e,r,n){var i=_o(t,e,r,n);if(i){var a=(t=i[0]).cd[t.index],o=t.cd[0].trace;if(!o.cumulative.enabled){var s="h"===o.orientation?"y":"x";t[s+"Label"]=VL(t[s+"a"],a.p0,a.p1)}return i}},UL.selectPoints=Oo,UL.eventData=jL,UL.moduleType="trace",UL.name="histogram",UL.basePlotModule=ua,UL.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],UL.meta={};var qL=UL,HL=m.extendFlat,GL=HL({},{x:zL.x,y:zL.y,z:{valType:"data_array",editType:"calc"},marker:{color:{valType:"data_array",editType:"calc"},editType:"calc"},histnorm:zL.histnorm,histfunc:zL.histfunc,autobinx:zL.autobinx,nbinsx:zL.nbinsx,xbins:zL.xbins,autobiny:zL.autobiny,nbinsy:zL.nbinsy,ybins:zL.ybins,xgap:Lh.xgap,ygap:Lh.ygap,zsmooth:Lh.zsmooth,zhoverformat:Lh.zhoverformat},Pe,{autocolorscale:HL({},Pe.autocolorscale,{dflt:!1})},{colorbar:ze}),WL=function(t,e,r,n){var i=r("x"),a=r("y");if(i&&i.length&&a&&a.length){P.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],n),(r("z")||r("marker.color"))&&r("histfunc");NL(0,e,r,["x","y"])}else e.visible=!1},YL=ri.hoverLabelText,XL={};XL.attributes=GL,XL.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,GL,r,n)}WL(t,e,i,n),!1!==e.visible&&(Xx(0,0,i),Ye(t,e,n,i,{prefix:"",cLetter:"z"}))},XL.calc=bf,XL.plot=$f,XL.colorbar=kh,XL.style=up,XL.hoverPoints=function(t,e,r,n,i,a){var o=Rf(t,e,r,0,0,a);if(o){var s=(t=o[0]).index,l=s[0],u=s[1],c=t.cd[0],h=c.xRanges[u],f=c.yRanges[l];return t.xLabel=YL(t.xa,h[0],h[1]),t.yLabel=YL(t.ya,f[0],f[1]),o}},XL.eventData=jL,XL.moduleType="trace",XL.name="histogram2d",XL.basePlotModule=ua,XL.categories=["cartesian","2dMap","histogram"],XL.meta={};var ZL=XL,JL=m.extendFlat,KL=JL({x:GL.x,y:GL.y,z:GL.z,marker:GL.marker,histnorm:GL.histnorm,histfunc:GL.histfunc,autobinx:GL.autobinx,nbinsx:GL.nbinsx,xbins:GL.xbins,autobiny:GL.autobiny,nbinsy:GL.nbinsy,ybins:GL.ybins,autocontour:Rh.autocontour,ncontours:Rh.ncontours,contours:Rh.contours,line:Rh.line,zhoverformat:GL.zhoverformat},Pe,{zmin:JL({},Pe.zmin,{editType:"calc"}),zmax:JL({},Pe.zmax,{editType:"calc"})},{colorbar:ze}),QL={};QL.attributes=KL,QL.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,KL,r,n)}WL(t,e,i,n),!1!==e.visible&&(zf(0,e,i,function(r){return ne.coerce2(t,e,KL,r)}),Pf(t,e,i,n))},QL.calc=_f,QL.plot=ip.plot,QL.style=cp,QL.colorbar=Af,QL.hoverPoints=Ff,QL.moduleType="trace",QL.name="histogram2dcontour",QL.basePlotModule=ua,QL.categories=["cartesian","2dMap","contour","histogram"],QL.meta={};var $L=QL,tz=m.extendFlat,ez=(0,ye.overrideAll)({visible:Ce.visible,showspikes:{valType:"boolean",dflt:!0},spikesides:{valType:"boolean",dflt:!0},spikethickness:{valType:"number",min:0,dflt:2},spikecolor:{valType:"color",dflt:Oe.defaultLine},showbackground:{valType:"boolean",dflt:!1},backgroundcolor:{valType:"color",dflt:"rgba(204, 204, 204, 0.5)"},showaxeslabels:{valType:"boolean",dflt:!0},color:Ce.color,categoryorder:Ce.categoryorder,categoryarray:Ce.categoryarray,title:Ce.title,titlefont:Ce.titlefont,type:Ce.type,autorange:Ce.autorange,rangemode:Ce.rangemode,range:Ce.range,tickmode:Ce.tickmode,nticks:Ce.nticks,tick0:Ce.tick0,dtick:Ce.dtick,tickvals:Ce.tickvals,ticktext:Ce.ticktext,ticks:Ce.ticks,mirror:Ce.mirror,ticklen:Ce.ticklen,tickwidth:Ce.tickwidth,tickcolor:Ce.tickcolor,showticklabels:Ce.showticklabels,tickfont:Ce.tickfont,tickangle:Ce.tickangle,tickprefix:Ce.tickprefix,showtickprefix:Ce.showtickprefix,ticksuffix:Ce.ticksuffix,showticksuffix:Ce.showticksuffix,showexponent:Ce.showexponent,exponentformat:Ce.exponentformat,separatethousands:Ce.separatethousands,tickformat:Ce.tickformat,tickformatstops:Ce.tickformatstops,hoverformat:Ce.hoverformat,showline:Ce.showline,linecolor:Ce.linecolor,linewidth:Ce.linewidth,showgrid:Ce.showgrid,gridcolor:tz({},Ce.gridcolor,{dflt:"rgb(204, 204, 204)"}),gridwidth:Ce.gridwidth,zeroline:Ce.zeroline,zerolinecolor:Ce.zerolinecolor,zerolinewidth:Ce.zerolinewidth},"plot","from-root"),rz=s.mix,nz=["xaxis","yaxis","zaxis"],iz=function(t,e,r){var n,i;function a(t,e){return ne.coerce(n,i,ez,t,e)}for(var o=0;o0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a);return t};var xz=function(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],h=t[10],f=t[11],p=t[12],d=t[13],g=t[14],v=t[15];return(e*o-r*a)*(h*v-f*g)-(e*s-n*a)*(c*v-f*d)+(e*l-i*a)*(c*g-h*d)+(r*s-n*o)*(u*v-f*p)-(r*l-i*o)*(u*g-h*p)+(n*l-i*s)*(u*d-c*p)};var bz=function(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t};var _z=function(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e};var wz=function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t};var Mz=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t};var Az=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t};var kz=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]};var Tz={length:function(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)},normalize:yz,dot:kz,cross:Az},Sz=wz(),Ez=wz(),Cz=[0,0,0,0],Lz=[[0,0,0],[0,0,0],[0,0,0]],zz=[0,0,0],Pz=function(t,e,r,n,i,a){if(e||(e=[0,0,0]),r||(r=[0,0,0]),n||(n=[0,0,0]),i||(i=[0,0,0,1]),a||(a=[0,0,0,1]),!function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;i<16;i++)t[i]=e[i]*n;return!0}(Sz,t))return!1;if(_z(Ez,Sz),Ez[3]=0,Ez[7]=0,Ez[11]=0,Ez[15]=1,Math.abs(xz(Ez)<1e-8))return!1;var o,s,l,u,c,h,f,p=Sz[3],d=Sz[7],g=Sz[11],v=Sz[12],m=Sz[13],y=Sz[14],x=Sz[15];if(0!==p||0!==d||0!==g){if(Cz[0]=p,Cz[1]=d,Cz[2]=g,Cz[3]=x,!cz(Ez,Ez))return!1;Mz(Ez,Ez),o=i,l=Ez,u=(s=Cz)[0],c=s[1],h=s[2],f=s[3],o[0]=l[0]*u+l[4]*c+l[8]*h+l[12]*f,o[1]=l[1]*u+l[5]*c+l[9]*h+l[13]*f,o[2]=l[2]*u+l[6]*c+l[10]*h+l[14]*f,o[3]=l[3]*u+l[7]*c+l[11]*h+l[15]*f}else i[0]=i[1]=i[2]=0,i[3]=1;if(e[0]=v,e[1]=m,e[2]=y,function(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}(Lz,Sz),r[0]=Tz.length(Lz[0]),Tz.normalize(Lz[0],Lz[0]),n[0]=Tz.dot(Lz[0],Lz[1]),Iz(Lz[1],Lz[1],Lz[0],1,-n[0]),r[1]=Tz.length(Lz[1]),Tz.normalize(Lz[1],Lz[1]),n[0]/=r[1],n[1]=Tz.dot(Lz[0],Lz[2]),Iz(Lz[2],Lz[2],Lz[0],1,-n[1]),n[2]=Tz.dot(Lz[1],Lz[2]),Iz(Lz[2],Lz[2],Lz[1],1,-n[2]),r[2]=Tz.length(Lz[2]),Tz.normalize(Lz[2],Lz[2]),n[1]/=r[2],n[2]/=r[2],Tz.cross(zz,Lz[1],Lz[2]),Tz.dot(Lz[0],zz)<0)for(var b=0;b<3;b++)r[b]*=-1,Lz[b][0]*=-1,Lz[b][1]*=-1,Lz[b][2]*=-1;return a[0]=.5*Math.sqrt(Math.max(1+Lz[0][0]-Lz[1][1]-Lz[2][2],0)),a[1]=.5*Math.sqrt(Math.max(1-Lz[0][0]+Lz[1][1]-Lz[2][2],0)),a[2]=.5*Math.sqrt(Math.max(1-Lz[0][0]-Lz[1][1]+Lz[2][2],0)),a[3]=.5*Math.sqrt(Math.max(1+Lz[0][0]+Lz[1][1]+Lz[2][2],0)),Lz[2][1]>Lz[1][2]&&(a[0]=-a[0]),Lz[0][2]>Lz[2][0]&&(a[1]=-a[1]),Lz[1][0]>Lz[0][1]&&(a[2]=-a[2]),!0};function Iz(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var Dz=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],p=e[10],d=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=r[0],b=r[1],_=r[2],w=r[3];return t[0]=x*n+b*s+_*h+w*g,t[1]=x*i+b*l+_*f+w*v,t[2]=x*a+b*u+_*p+w*m,t[3]=x*o+b*c+_*d+w*y,x=r[4],b=r[5],_=r[6],w=r[7],t[4]=x*n+b*s+_*h+w*g,t[5]=x*i+b*l+_*f+w*v,t[6]=x*a+b*u+_*p+w*m,t[7]=x*o+b*c+_*d+w*y,x=r[8],b=r[9],_=r[10],w=r[11],t[8]=x*n+b*s+_*h+w*g,t[9]=x*i+b*l+_*f+w*v,t[10]=x*a+b*u+_*p+w*m,t[11]=x*o+b*c+_*d+w*y,x=r[12],b=r[13],_=r[14],w=r[15],t[12]=x*n+b*s+_*h+w*g,t[13]=x*i+b*l+_*f+w*v,t[14]=x*a+b*u+_*p+w*m,t[15]=x*o+b*c+_*d+w*y,t};var Oz={identity:hz,translate:mz,multiply:Dz,create:wz,scale:vz,fromRotationTranslation:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,h=n*l,f=n*u,p=i*l,d=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(p+g),t[1]=h+y,t[2]=f-m,t[3]=0,t[4]=h-y,t[5]=1-(c+g),t[6]=d+v,t[7]=0,t[8]=f+m,t[9]=d-v,t[10]=1-(c+p),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}},Rz=(Oz.create(),Oz.create()),Fz=function(t,e,r,n,i,a){return Oz.identity(t),Oz.fromRotationTranslation(t,a,e),t[3]=i[0],t[7]=i[1],t[11]=i[2],t[15]=i[3],Oz.identity(Rz),0!==n[2]&&(Rz[9]=n[2],Oz.multiply(t,t,Rz)),0!==n[1]&&(Rz[9]=0,Rz[8]=n[1],Oz.multiply(t,t,Rz)),0!==n[0]&&(Rz[8]=0,Rz[4]=n[0],Oz.multiply(t,t,Rz)),Oz.scale(t,t,r),t};var Bz=function(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],h=e[2],f=e[3],p=r[0],d=r[1],g=r[2],v=r[3];(a=u*p+c*d+h*g+f*v)<0&&(a=-a,p=-p,d=-d,g=-g,v=-v);1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n);return t[0]=s*u+l*p,t[1]=s*c+l*d,t[2]=s*h+l*g,t[3]=s*f+l*v,t},Nz=qz(),jz=qz(),Vz=qz(),Uz=function(t,e,r,n){if(0===xz(e)||0===xz(r))return!1;var i=Pz(e,Nz.translate,Nz.scale,Nz.skew,Nz.perspective,Nz.quaternion),a=Pz(r,jz.translate,jz.scale,jz.skew,jz.perspective,jz.quaternion);return!(!i||!a||(bz(Vz.translate,Nz.translate,jz.translate,n),bz(Vz.skew,Nz.skew,jz.skew,n),bz(Vz.scale,Nz.scale,jz.scale,n),bz(Vz.perspective,Nz.perspective,jz.perspective,n),Bz(Vz.quaternion,Nz.quaternion,jz.quaternion,n),Fz(t,Vz.translate,Vz.scale,Vz.skew,Vz.perspective,Vz.quaternion),0))};function qz(){return{translate:Hz(),scale:Hz(1),skew:Hz(),perspective:[0,0,0,1],quaternion:[0,0,0,1]}}function Hz(t){return[t||0,t||0,t||0]}var Gz=[0,0,0],Wz=function(t){return new Yz((t=t||{}).matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])};function Yz(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-1/0,1/0]}var Xz=Yz.prototype;Xz.recalcMatrix=function(t){var e=this._time,r=wT.le(e,t),n=this.computedMatrix;if(!(r<0)){var i=this._components;if(r===e.length-1)for(var a=16*r,o=0;o<16;++o)n[o]=i[a++];else{var s=e[r+1]-e[r],l=(a=16*r,this.prevMatrix),u=!0;for(o=0;o<16;++o)l[o]=i[a++];var c=this.nextMatrix;for(o=0;o<16;++o)c[o]=i[a++],u=u&&l[o]===c[o];if(s<1e-6||u)for(o=0;o<16;++o)n[o]=l[o];else Uz(n,l,c,(t-e[r])/s)}var h=this.computedUp;h[0]=n[1],h[1]=n[5],h[2]=n[9],yz(h,h);var f=this.computedInverse;cz(f,n);var p=this.computedEye,d=f[15];p[0]=f[12]/d,p[1]=f[13]/d,p[2]=f[14]/d;var g=this.computedCenter,v=Math.exp(this.computedRadius[0]);for(o=0;o<3;++o)g[o]=p[o]-n[2+4*o]*v}},Xz.idle=function(t){if(!(t=0;--p)a[p]=u*t[p]+c*e[p]+h*r[p]+f*n[p];return a}return u*t+c*e+h*r+f*n}).derivative=function(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n};var Kz=function(t,e,r){switch(arguments.length){case 0:return new $z([0],[0],0);case 1:if("number"==typeof t){var n=eP(t);return new $z(n,n,0)}return new $z(t,eP(t.length),0);case 2:if("number"==typeof e){var n=eP(t.length);return new $z(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new $z(t,e,r)}};function Qz(t,e,r){return Math.min(e,Math.max(t,r))}function $z(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n=r-1){u=a.length-1;var h=t-e[r-1];for(c=0;c=r-1)for(var l=a.length-1,u=(e[r-1],0);u=0;--r)if(t[--e])return!1;return!0},tP.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(t0;--c)n.push(Qz(s[c-1],l[c-1],arguments[c])),i.push(0)}},tP.push=function(t){var e=this.lastT(),r=this.dimension;if(!(t1e-6?1/o:0;this._time.push(t);for(var h=r;h>0;--h){var f=Qz(l[h-1],u[h-1],arguments[h]);n.push(f),i.push((f-n[a++])*c)}}},tP.set=function(t){var e=this.dimension;if(!(t0;--s)r.push(Qz(a[s-1],o[s-1],arguments[s])),n.push(0)}},tP.move=function(t){var e=this.lastT(),r=this.dimension;if(!(t<=e||arguments.length!==r+1)){var n=this._state,i=this._velocity,a=n.length-this.dimension,o=this.bounds,s=o[0],l=o[1],u=t-e,c=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var f=arguments[h];n.push(Qz(s[h-1],l[h-1],n[a++]+f)),i.push(f*c)}}},tP.idle=function(t){var e=this.lastT();if(!(t=0;--c)n.push(Qz(s[c],l[c],n[a]+u*i[a])),i.push(0),a+=1}};var rP=function(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(h>0){var h=Math.sqrt(c+1);t[0]=.5*(o-l)/h,t[1]=.5*(s-n)/h,t[2]=.5*(r-a)/h,t[3]=.5*h}else{var f=Math.max(e,a,u),h=Math.sqrt(2*f-c+1);e>=f?(t[0]=.5*h,t[1]=.5*(i+r)/h,t[2]=.5*(s+n)/h,t[3]=.5*(o-l)/h):a>=f?(t[0]=.5*(r+i)/h,t[1]=.5*h,t[2]=.5*(l+o)/h,t[3]=.5*(s-n)/h):(t[0]=.5*(n+s)/h,t[1]=.5*(o+l)/h,t[2]=.5*h,t[3]=.5*(r-i)/h)}return t};var nP=function(t){var e=(t=t||{}).center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),oP(r=[].slice.call(r,0,4),r);var i=new sP(r,e,Math.log(n));i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up);return i};function iP(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function aP(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function oP(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=aP(r,n,i,a);o>1e-6?(t[0]=r/o,t[1]=n/o,t[2]=i/o,t[3]=a/o):(t[0]=t[1]=t[2]=0,t[3]=1)}function sP(t,e,r){this.radius=Kz([r]),this.center=Kz(e),this.rotation=Kz(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}var lP=sP.prototype;lP.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},lP.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;oP(e,e);var r=this.computedMatrix;jv(r,e);var n=this.computedCenter,i=this.computedEye,a=this.computedUp,o=Math.exp(this.computedRadius[0]);i[0]=n[0]+o*r[2],i[1]=n[1]+o*r[6],i[2]=n[2]+o*r[10],a[0]=r[1],a[1]=r[5],a[2]=r[9];for(var s=0;s<3;++s){for(var l=0,u=0;u<3;++u)l+=r[s+4*u]*i[u];r[12+s]=-l}},lP.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r},lP.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},lP.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},lP.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=i[1],o=i[5],s=i[9],l=iP(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,p=iP(u-=a*f,c-=o*f,h-=s*f);u/=p,c/=p,h/=p;var d=i[2],g=i[6],v=i[10],m=d*a+g*o+v*s,y=d*u+g*c+v*h,x=iP(d-=m*a+y*u,g-=m*o+y*c,v-=m*s+y*h);d/=x,g/=x,v/=x;var b=u*e+a*r,_=c*e+o*r,w=h*e+s*r;this.center.move(t,b,_,w);var M=Math.exp(this.computedRadius[0]);M=Math.max(1e-4,M+n),this.radius.set(t,Math.log(M))},lP.rotate=function(t,e,r,n){this.recalcMatrix(t),e=e||0,r=r||0;var i=this.computedMatrix,a=i[0],o=i[4],s=i[8],l=i[1],u=i[5],c=i[9],h=i[2],f=i[6],p=i[10],d=e*a+r*l,g=e*o+r*u,v=e*s+r*c,m=-(f*v-p*g),y=-(p*d-h*v),x=-(h*g-f*d),b=Math.sqrt(Math.max(0,1-Math.pow(m,2)-Math.pow(y,2)-Math.pow(x,2))),_=aP(m,y,x,b);_>1e-6?(m/=_,y/=_,x/=_,b/=_):(m=y=x=0,b=1);var w=this.computedRotation,M=w[0],A=w[1],k=w[2],T=w[3],S=M*b+T*m+A*x-k*y,E=A*b+T*y+k*m-M*x,C=k*b+T*x+M*y-A*m,L=T*b-M*m-A*y-k*x;if(n){m=h,y=f,x=p;var z=Math.sin(n)/iP(m,y,x);m*=z,y*=z,x*=z,L=L*(b=Math.cos(e))-(S=S*b+L*m+E*x-C*y)*m-(E=E*b+L*y+C*m-S*x)*y-(C=C*b+L*x+S*y-E*m)*x}var P=aP(S,E,C,L);P>1e-6?(S/=P,E/=P,C/=P,L/=P):(S=E=C=0,L=1),this.rotation.set(t,S,E,C,L)},lP.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;fz(i,e,r,n);var a=this.computedRotation;rP(a,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),oP(a,a),this.rotation.set(t,a[0],a[1],a[2],a[3]);for(var o=0,s=0;s<3;++s)o+=Math.pow(r[s]-e[s],2);this.radius.set(t,.5*Math.log(Math.max(o,1e-6))),this.center.set(t,r[0],r[1],r[2])},lP.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},lP.setMatrix=function(t,e){var r=this.computedRotation;rP(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),oP(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;cz(n,e);var i=n[15];if(Math.abs(i)>1e-6){var a=n[12]/i,o=n[13]/i,s=n[14]/i;this.recalcMatrix(t);var l=Math.exp(this.computedRadius[0]);this.center.set(t,a-n[2]*l,o-n[6]*l,s-n[10]*l),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},lP.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},lP.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},lP.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},lP.toJSON=function(){return this.recalcMatrix(this.lastT()),{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]}},lP.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)};var uP=function(t,e,r,n){var i,a,o,s,l,u,c,h,f,p,d,g,v,m,y,x,b,_,w,M,A,k,T,S,E=n[0],C=n[1],L=n[2],z=Math.sqrt(E*E+C*C+L*L);if(Math.abs(z)<1e-6)return null;E*=z=1/z,C*=z,L*=z,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],h=e[4],f=e[5],p=e[6],d=e[7],g=e[8],v=e[9],m=e[10],y=e[11],x=E*E*o+a,b=C*E*o+L*i,_=L*E*o-C*i,w=E*C*o-L*i,M=C*C*o+a,A=L*C*o+E*i,k=E*L*o+C*i,T=C*L*o-E*i,S=L*L*o+a,t[0]=s*x+h*b+g*_,t[1]=l*x+f*b+v*_,t[2]=u*x+p*b+m*_,t[3]=c*x+d*b+y*_,t[4]=s*w+h*M+g*A,t[5]=l*w+f*M+v*A,t[6]=u*w+p*M+m*A,t[7]=c*w+d*M+y*A,t[8]=s*k+h*T+g*S,t[9]=l*k+f*T+v*S,t[10]=u*k+p*T+m*S,t[11]=c*k+d*T+y*S,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t};var cP=function(t){var e=(t=t||{}).center||[0,0,0],r=t.up||[0,1,0],n=t.right||pP(r),i=t.radius||1,a=t.theta||0,o=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),yz(r,r),n=[].slice.call(n,0,3),yz(n,n),"eye"in t){var s=t.eye,l=[s[0]-e[0],s[1]-e[1],s[2]-e[2]];Az(n,l,r),hP(n[0],n[1],n[2])<1e-6?n=pP(r):yz(n,n),i=hP(l[0],l[1],l[2]);var u=kz(r,l)/i,c=kz(n,l)/i;o=Math.acos(u),a=Math.acos(c)}return i=Math.log(i),new dP(t.zoomMin,t.zoomMax,e,r,n,i,a,o)};function hP(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function fP(t){return Math.min(1,Math.max(-1,t))}function pP(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;s<3;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(s=0;s<3;++s)i[s]-=o/a*t[s];return yz(i,i),i}function dP(t,e,r,n,i,a,o,s){this.center=Kz(r),this.up=Kz(n),this.right=Kz(i),this.radius=Kz([a]),this.angle=Kz([o,s]),this.angle.bounds=[[-1/0,-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var l=0;l<16;++l)this.computedMatrix[l]=.5;this.recalcMatrix(0)}var gP=dP.prototype;gP.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},gP.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},gP.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,n=0,i=0,a=0;a<3;++a)i+=e[a]*r[a],n+=e[a]*e[a];var o=Math.sqrt(n),s=0;for(a=0;a<3;++a)r[a]-=e[a]*i/n,s+=r[a]*r[a],e[a]/=o;var l=Math.sqrt(s);for(a=0;a<3;++a)r[a]/=l;var u=this.computedToward;Az(u,e,r),yz(u,u);var c=Math.exp(this.computedRadius[0]),h=this.computedAngle[0],f=this.computedAngle[1],p=Math.cos(h),d=Math.sin(h),g=Math.cos(f),v=Math.sin(f),m=this.computedCenter,y=p*g,x=d*g,b=v,_=-p*v,w=-d*v,M=g,A=this.computedEye,k=this.computedMatrix;for(a=0;a<3;++a){var T=y*r[a]+x*u[a]+b*e[a];k[4*a+1]=_*r[a]+w*u[a]+M*e[a],k[4*a+2]=T,k[4*a+3]=0}var S=k[1],E=k[5],C=k[9],L=k[2],z=k[6],P=k[10],I=E*P-C*z,D=C*L-S*P,O=S*z-E*L,R=hP(I,D,O);I/=R,D/=R,O/=R,k[0]=I,k[4]=D,k[8]=O;for(a=0;a<3;++a)A[a]=m[a]+k[2+4*a]*c;for(a=0;a<3;++a){s=0;for(var F=0;F<3;++F)s+=k[a+4*F]*A[F];k[12+a]=-s}k[15]=1},gP.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r};var vP=[0,0,0];gP.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;vP[0]=i[2],vP[1]=i[6],vP[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;l<3;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];uP(i,i,n,vP);for(l=0;l<3;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},gP.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=(Math.exp(this.computedRadius[0]),i[1]),o=i[5],s=i[9],l=hP(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,p=hP(u-=a*f,c-=o*f,h-=s*f),d=(u/=p)*e+a*r,g=(c/=p)*e+o*r,v=(h/=p)*e+s*r;this.center.move(t,d,g,v);var m=Math.exp(this.computedRadius[0]);m=Math.max(1e-4,m+n),this.radius.set(t,Math.log(m))},gP.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},gP.setMatrix=function(t,e,r,n){var i=1;"number"==typeof r&&(i=0|r),(i<0||i>3)&&(i=1);var a=(i+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var o=e[i],s=e[i+4],l=e[i+8];if(n){var u=Math.abs(o),c=Math.abs(s),h=Math.abs(l),f=Math.max(u,c,h);u===f?(o=o<0?-1:1,s=l=0):h===f?(l=l<0?-1:1,o=s=0):(s=s<0?-1:1,o=l=0)}else{var p=hP(o,s,l);o/=p,s/=p,l/=p}var d,g,v=e[a],m=e[a+4],y=e[a+8],x=v*o+m*s+y*l,b=hP(v-=o*x,m-=s*x,y-=l*x),_=s*(y/=b)-l*(m/=b),w=l*(v/=b)-o*y,M=o*m-s*v,A=hP(_,w,M);if(_/=A,w/=A,M/=A,this.center.jump(t,V,U,q),this.radius.idle(t),this.up.jump(t,o,s,l),this.right.jump(t,v,m,y),2===i){var k=e[1],T=e[5],S=e[9],E=k*v+T*m+S*y,C=k*_+T*w+S*M;d=I<0?-Math.PI/2:Math.PI/2,g=Math.atan2(C,E)}else{var L=e[2],z=e[6],P=e[10],I=L*o+z*s+P*l,D=L*v+z*m+P*y,O=L*_+z*w+P*M;d=Math.asin(fP(I)),g=Math.atan2(O,D)}this.angle.jump(t,g,d),this.recalcMatrix(t);var R=e[2],F=e[6],B=e[10],N=this.computedMatrix;cz(N,e);var j=N[15],V=N[12]/j,U=N[13]/j,q=N[14]/j,H=Math.exp(this.computedRadius[0]);this.center.jump(t,V-R*H,U-F*H,q-B*H)},gP.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},gP.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},gP.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},gP.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},gP.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter;var i=(n=n||this.computedUp)[0],a=n[1],o=n[2],s=hP(i,a,o);if(!(s<1e-6)){i/=s,a/=s,o/=s;var l=e[0]-r[0],u=e[1]-r[1],c=e[2]-r[2],h=hP(l,u,c);if(!(h<1e-6)){l/=h,u/=h,c/=h;var f=this.computedRight,p=f[0],d=f[1],g=f[2],v=i*p+a*d+o*g,m=hP(p-=v*i,d-=v*a,g-=v*o);if(!(m<.01&&(m=hP(p=a*c-o*u,d=o*l-i*c,g=i*u-a*l))<1e-6)){p/=m,d/=m,g/=m,this.up.set(t,i,a,o),this.right.set(t,p,d,g),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(h));var y=a*g-o*d,x=o*p-i*g,b=i*d-a*p,_=hP(y,x,b),w=i*l+a*u+o*c,M=p*l+d*u+g*c,A=(y/=_)*l+(x/=_)*u+(b/=_)*c,k=Math.asin(fP(w)),T=Math.atan2(A,M),S=this.angle._state,E=S[S.length-1],C=S[S.length-2];E%=2*Math.PI;var L=Math.abs(E+2*Math.PI-T),z=Math.abs(E-T),P=Math.abs(E-2*Math.PI-T);LMath.abs(e))n.rotate(s,0,0,-t*i*Math.PI*l.rotateSpeed/window.innerWidth);else{var u=l.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,a*(Math.exp(u)-1))}},!0),l};var wP=function(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i=0?e[a]:i})},has___:{value:y(function(e){var n=m(e);return n?r in n:t.indexOf(e)>=0})},set___:{value:y(function(n,i){var a,o=m(n);return o?o[r]=i:(a=t.indexOf(n))>=0?e[a]=i:(a=t.length,e[a]=i,t[a]=n),this})},delete___:{value:y(function(n){var i,a,o=m(n);return o?r in o&&delete o[r]:!((i=t.indexOf(n))<0||(a=t.length-1,t[i]=void 0,e[i]=e[a],t[i]=t[a],t.length=a,e.length=a,0))})}})};d.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},delete:{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof e?function(){function r(){this instanceof d||x();var r,n=new e,i=void 0,a=!1;return r=t?function(t,e){return n.set(t,e),n.has(t)||(i||(i=new d),i.set(t,e)),this}:function(t,e){if(a)try{n.set(t,e)}catch(r){i||(i=new d),i.set___(t,e)}else n.set(t,e);return this},Object.create(d.prototype,{get___:{value:y(function(t,e){return i?n.has(t)?n.get(t):i.get___(t,e):n.get(t,e)})},has___:{value:y(function(t){return n.has(t)||!!i&&i.has___(t)})},set___:{value:y(r)},delete___:{value:y(function(t){var e=!!n.delete(t);return i&&i.delete___(t)||e})},permitHostObjects___:{value:y(function(t){if(t!==g)throw new Error("bogus call to permitHostObjects___");a=!0})}})}t&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=d.prototype,CP=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),CP=d)}function g(t){t.permitHostObjects___&&t.permitHostObjects___(g)}function v(t){return!(t.substr(0,s.length)==s&&"___"===t.substr(t.length-3))}function m(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[l];if(e&&e.key===t)return e;if(o(t)){e={key:t};try{return a(t,l,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(t){return}}}function y(t){return t.prototype=null,Object.freeze(t)}function x(){f||"undefined"==typeof console||(f=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}}();var LP=new("undefined"==typeof WeakMap?CP:WeakMap);var zP=function(t){var e=LP.get(t),r=e&&(e._triangleBuffer.handle||e._triangleBuffer.buffer);if(!r||!t.isBuffer(r)){var n=S_(t,new Float32Array([-1,-1,-1,4,4,-1]));(e=EP(t,[{buffer:n,type:t.FLOAT,size:2}]))._triangleBuffer=n,LP.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()},PP={},IP=E_(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]),DP=E_(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]);PP.line=function(t){return Bw(t,IP,DP,null,[{name:"position",type:"vec3"}])};var OP=E_(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}"]),RP=E_(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]);PP.text=function(t){return Bw(t,OP,RP,null,[{name:"position",type:"vec3"}])};var FP=E_(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]),BP=E_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]);PP.bg=function(t){return Bw(t,FP,BP,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])};var NP=function(t){for(var e=[],r=[],n=0,i=0;i<3;++i)for(var a=(i+1)%3,o=(i+2)%3,s=[0,0,0],l=[0,0,0],u=-1;u<=1;u+=2){r.push(n,n+2,n+1,n+1,n+2,n+3),s[i]=u,l[i]=u;for(var c=-1;c<=1;c+=2){s[a]=c;for(var h=-1;h<=1;h+=2)s[o]=h,e.push(s[0],s[1],s[2],l[0],l[1],l[2]),n+=1}var f=a;a=o,o=f}var p=S_(t,new Float32Array(e)),d=S_(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),g=EP(t,[{buffer:p,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:p,type:t.FLOAT,size:3,offset:12,stride:24}],d),v=jP(t);return v.attributes.position.location=0,v.attributes.normal.location=1,new VP(t,p,g,v)},jP=PP.bg;function VP(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}var UP=VP.prototype;UP.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;s<3;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),this.vao.unbind(),l.disable(l.POLYGON_OFFSET_FILL)}},UP.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()};var qP=function(t,e){for(var r=cM(t[0],e[0]),n=1;n1&&(i=1);for(var a=1-i,o=t.length,s=new Array(o),l=0;l0||i>0&&l<0){var u=WP(a,l,o,i);r.push(u),n.push(u.slice())}l<0?n.push(o.slice()):l>0?r.push(o.slice()):(r.push(o.slice()),n.push(o.slice())),i=l}return{positive:r,negative:n}}).positive=function(t,e){for(var r=[],n=GP(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(WP(i,s,a,n)),s>=0&&r.push(a.slice()),n=s}return r},HP.negative=function(t,e){for(var r=[],n=GP(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(WP(i,s,a,n)),s<=0&&r.push(a.slice()),n=s}return r};var YP=function(t,e,r,n){Dz(XP,e,t),Dz(XP,r,XP);for(var i=0,a=0;a<2;++a){KP[2]=n[a][2];for(var o=0;o<2;++o){KP[1]=n[o][1];for(var s=0;s<2;++s)KP[0]=n[s][0],$P(ZP[i],KP,XP),i+=1}}for(var l=-1,a=0;a<8;++a){for(var u=ZP[a][3],c=0;c<3;++c)JP[a][c]=ZP[a][c]/u;u<0&&(l<0?l=a:JP[a][2]d&&(l|=1<d&&(l|=1<JP[a][1]&&(w=a));for(var M=-1,a=0;a<3;++a){var A=w^1<JP[k][0]&&(k=A)}}var T=rI;T[0]=T[1]=T[2]=0,T[Mb.log2(M^w)]=w&M,T[Mb.log2(w^k)]=w&k;var S=7^k;S===l||S===_?(S=7^M,T[Mb.log2(k^S)]=S&k):T[Mb.log2(M^S)]=S&M;for(var E=nI,C=l,h=0;h<3;++h)E[h]=C&1<=0;--d){var g=u[p[d]];o.push(l*g[0],-l*g[1],t)}}for(var l=[0,0,0],u=[0,0,0],c=[0,0,0],h=[0,0,0],f=0;f<3;++f){c[f]=o.length/3|0,s(.5*(t[0][f]+t[1][f]),e[f],r),h[f]=(o.length/3|0)-c[f],l[f]=o.length/3|0;for(var p=0;p=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;o<0?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u|=0);var c=""+l;if(o<0&&(c="-"+c),i){for(var h=""+u;h.length=t[0][n];--a)i.push({x:a*e[n],text:yI(e[n],a)});r.push(i)}return r},mI.equal=function(t,e){for(var r=0;r<3;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n0?(p[c]=-1,d[c]=0):(p[c]=0,d[c]=1)}}var SI=[0,0,0],EI={model:bI,view:bI,projection:bI};MI.isOpaque=function(){return!0},MI.isTransparent=function(){return!1},MI.drawTransparent=function(t){};var CI=[0,0,0],LI=[0,0,0],zI=[0,0,0];MI.draw=function(t){t=t||EI;for(var e=this.gl,r=t.model||bI,n=t.view||bI,i=t.projection||bI,a=this.bounds,o=YP(r,n,i,a),s=o.cubeEdges,l=o.axis,u=n[12],c=n[13],h=n[14],f=n[15],p=this.pixelRatio*(i[3]*u+i[7]*c+i[11]*h+i[15]*f)/e.drawingBufferHeight,d=0;d<3;++d)this.lastCubeProps.cubeEdges[d]=s[d],this.lastCubeProps.axis[d]=l[d];var g=kI;for(d=0;d<3;++d)TI(kI[d],d,this.bounds,s,l);e=this.gl;var v=SI;for(d=0;d<3;++d)this.backgroundEnable[d]?v[d]=l[d]:v[d]=0;this._background.draw(r,n,i,a,v,this.backgroundColor),this._lines.bind(r,n,i,this);for(d=0;d<3;++d){var m=[0,0,0];l[d]>0?m[d]=a[1][d]:m[d]=a[0][d];for(var y=0;y<2;++y){var x=(d+1+y)%3,b=(d+1+(1^y))%3;this.gridEnable[x]&&this._lines.drawGrid(x,b,this.bounds,m,this.gridColor[x],this.gridWidth[x]*this.pixelRatio)}for(y=0;y<2;++y){x=(d+1+y)%3,b=(d+1+(1^y))%3;this.zeroEnable[b]&&a[0][b]<=0&&a[1][b]>=0&&this._lines.drawZero(x,b,this.bounds,m,this.zeroLineColor[b],this.zeroLineWidth[b]*this.pixelRatio)}}for(d=0;d<3;++d){this.lineEnable[d]&&this._lines.drawAxisLine(d,this.bounds,g[d].primalOffset,this.lineColor[d],this.lineWidth[d]*this.pixelRatio),this.lineMirror[d]&&this._lines.drawAxisLine(d,this.bounds,g[d].mirrorOffset,this.lineColor[d],this.lineWidth[d]*this.pixelRatio);var _=_I(CI,g[d].primalMinor),w=_I(LI,g[d].mirrorMinor),M=this.lineTickLength;for(y=0;y<3;++y){var A=p/r[5*y];_[y]*=M[y]*A,w[y]*=M[y]*A}this.lineTickEnable[d]&&this._lines.drawAxisTicks(d,g[d].primalOffset,_,this.lineTickColor[d],this.lineTickWidth[d]*this.pixelRatio),this.lineTickMirror[d]&&this._lines.drawAxisTicks(d,g[d].mirrorOffset,w,this.lineTickColor[d],this.lineTickWidth[d]*this.pixelRatio)}this._lines.unbind(),this._text.bind(r,n,i,this.pixelRatio);for(d=0;d<3;++d){var k=g[d].primalMinor,T=_I(zI,g[d].primalOffset);for(y=0;y<3;++y)this.lineTickEnable[d]&&(T[y]+=p*k[y]*Math.max(this.lineTickLength[y],0)/r[5*y]);if(this.tickEnable[d]){for(y=0;y<3;++y)T[y]+=p*k[y]*this.tickPad[y]/r[5*y];this._text.drawTicks(d,this.tickSize[d],this.tickAngle[d],T,this.tickColor[d])}if(this.labelEnable[d]){for(y=0;y<3;++y)T[y]+=p*k[y]*this.labelPad[y]/r[5*y];T[d]+=.5*(a[0][d]+a[1][d]),this._text.drawLabel(d,this.labelSize[d],this.labelAngle[d],T,this.labelColor[d])}}this._text.unbind()},MI.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null};var PI=function(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]};var II=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t};var DI=function(t,e,r,n,i){var a=e.model||OI,o=e.view||OI,s=e.projection||OI,l=t.bounds,u=(i=i||YP(a,o,s,l)).axis;i.edges;Dz(RI,o,a),Dz(RI,s,RI);for(var c=VI,h=0;h<3;++h)c[h].lo=1/0,c[h].hi=-1/0,c[h].pixelsPerDataUnit=1/0;var f=PI(Mz(RI,RI));Mz(RI,RI);for(var p=0;p<3;++p){var d=(p+1)%3,g=(p+2)%3,v=UI;t:for(var h=0;h<2;++h){var m=[];if(u[p]<0!=!!h){v[p]=l[h][p];for(var y=0;y<2;++y){v[d]=l[y^h][d];for(var x=0;x<2;++x)v[g]=l[x^y^h][g],m.push(v.slice())}for(var y=0;y0&&0===v[e-1];)v.pop(),m.pop().dispose()}window.addEventListener("resize",T),A.update=function(t){e||(t=t||{},y=!0,x=!0)},A.add=function(t){e||(t.axes=h,d.push(t),g.push(-1),y=!0,x=!0,S())},A.remove=function(t){if(!e){var r=d.indexOf(t);r<0||(d.splice(r,1),g.pop(),y=!0,x=!0,S())}},A.dispose=function(){if(!e&&(e=!0,window.removeEventListener("resize",T),r.removeEventListener("webglcontextlost",L),A.mouseListener.enabled=!1,!A.contextLost)){h.dispose(),p.dispose();for(var t=0;to.distance)continue;for(var h=0;h0){r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function oD(t){return"boolean"!=typeof t||t}var sD=function(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]);"zoomMin"in e&&(r[0]=e.zoomMin);"zoomMax"in e&&(r[1]=e.zoomMax);var n=mP({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0,o=t.clientWidth,s=t.clientHeight,l={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=bP(),r=this.delay,l=e-2*r;n.idle(e-r),n.recalcMatrix(l),n.flush(e-(100+2*r));for(var u=!0,c=n.computedMatrix,h=0;h<16;++h)u=u&&i[h]===c[h],i[h]=c[h];var f=t.clientWidth===o&&t.clientHeight===s;return o=t.clientWidth,s=t.clientHeight,u?!f:(a=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(l,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),i=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var a=bP();n._active.lookAt(a,r,i,e),n._active.lookAt(a+500,r,i,[0,0,1]),n._active.flush(a)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return a},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var u=0,c=0,h={shift:!1,control:!1,alt:!1,meta:!1};function f(e,r,i,o){var s=l.keyBindingMode;if(!1!==s){var f="rotate"===s,p="pan"===s,d="zoom"===s,g=!!o.control,v=!!o.alt,m=!!o.shift,y=!!(1&e),x=!!(2&e),b=!!(4&e),_=1/t.clientHeight,w=_*(r-u),M=_*(i-c),A=l.flipX?1:-1,k=l.flipY?1:-1,T=bP(),S=Math.PI*l.rotateSpeed;if((f&&y&&!g&&!v&&!m||y&&!g&&!v&&m)&&n.rotate(T,A*S*w,-k*S*M,0),(p&&y&&!g&&!v&&!m||x||y&&g&&!v&&!m)&&n.pan(T,-l.translateSpeed*w*a,l.translateSpeed*M*a,0),d&&y&&!g&&!v&&!m||b||y&&!g&&v&&!m){var E=-l.zoomSpeed*M/window.innerHeight*(T-n.lastT())*100;n.pan(T,0,0,a*(Math.exp(E)-1))}return u=r,c=i,h=o,!0}}return l.mouseListener=CC(t,f),t.addEventListener("touchstart",function(e){var r=La(e.changedTouches[0],t);f(0,r[0],r[1],h),f(1,r[0],r[1],h),e.preventDefault()},!!Ea&&{passive:!1}),t.addEventListener("touchmove",function(e){var r=La(e.changedTouches[0],t);f(1,r[0],r[1],h),e.preventDefault()},!!Ea&&{passive:!1}),t.addEventListener("touchend",function(t){f(0,u,c,h),t.preventDefault()},!!Ea&&{passive:!1}),l.wheelListener=OC(t,function(t,e){if(!1!==l.keyBindingMode){var r=l.flipX?1:-1,i=l.flipY?1:-1,o=bP();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*l.rotateSpeed/window.innerWidth);else{var s=-l.zoomSpeed*i*e/window.innerHeight*(o-n.lastT())/20;n.pan(o,0,0,a*(Math.exp(s)-1))}}},!0),l};var lD=["xaxis","yaxis","zaxis"];function uD(){this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.tickEnable=[!0,!0,!0],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=[!0,!0,!0],this.labelFont=["Open Sans","Open Sans","Open Sans"],this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[30,30,30],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],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=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!0,!0,!0],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._defaultTickPad=this.tickPad.slice(),this._defaultLabelPad=this.labelPad.slice(),this._defaultLineTickLength=this.lineTickLength.slice()}uD.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[lD[e]];r.visible?(this.labels[e]=AC(r.title),"titlefont"in r&&(r.titlefont.color&&(this.labelColor[e]=WC(r.titlefont.color)),r.titlefont.family&&(this.labelFont[e]=r.titlefont.family),r.titlefont.size&&(this.labelSize[e]=r.titlefont.size)),"showline"in r&&(this.lineEnable[e]=r.showline),"linecolor"in r&&(this.lineColor[e]=WC(r.linecolor)),"linewidth"in r&&(this.lineWidth[e]=r.linewidth),"showgrid"in r&&(this.gridEnable[e]=r.showgrid),"gridcolor"in r&&(this.gridColor[e]=WC(r.gridcolor)),"gridwidth"in r&&(this.gridWidth[e]=r.gridwidth),"log"===r.type?this.zeroEnable[e]=!1:"zeroline"in r&&(this.zeroEnable[e]=r.zeroline),"zerolinecolor"in r&&(this.zeroLineColor[e]=WC(r.zerolinecolor)),"zerolinewidth"in r&&(this.zeroLineWidth[e]=r.zerolinewidth),"ticks"in r&&r.ticks?this.lineTickEnable[e]=!0:this.lineTickEnable[e]=!1,"ticklen"in r&&(this.lineTickLength[e]=this._defaultLineTickLength[e]=r.ticklen),"tickcolor"in r&&(this.lineTickColor[e]=WC(r.tickcolor)),"tickwidth"in r&&(this.lineTickWidth[e]=r.tickwidth),"tickangle"in r&&(this.tickAngle[e]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180),"showticklabels"in r&&(this.tickEnable[e]=r.showticklabels),"tickfont"in r&&(r.tickfont.color&&(this.tickColor[e]=WC(r.tickfont.color)),r.tickfont.family&&(this.tickFont[e]=r.tickfont.family),r.tickfont.size&&(this.tickSize[e]=r.tickfont.size)),"mirror"in r?-1!==["ticks","all","allticks"].indexOf(r.mirror)?(this.lineTickMirror[e]=!0,this.lineMirror[e]=!0):!0===r.mirror?(this.lineTickMirror[e]=!1,this.lineMirror[e]=!0):(this.lineTickMirror[e]=!1,this.lineMirror[e]=!1):this.lineMirror[e]=!1,"showbackground"in r&&!1!==r.showbackground?(this.backgroundEnable[e]=!0,this.backgroundColor[e]=WC(r.backgroundcolor)):this.backgroundEnable[e]=!1):(this.tickEnable[e]=!1,this.labelEnable[e]=!1,this.lineEnable[e]=!1,this.lineTickEnable[e]=!1,this.gridEnable[e]=!1,this.zeroEnable[e]=!1,this.backgroundEnable[e]=!1)}};var cD=function(t){var e=new uD;return e.merge(t),e},hD=["xaxis","yaxis","zaxis"];function fD(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}fD.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[hD[e]];r.visible?(this.enabled[e]=r.showspikes,this.colors[e]=WC(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness):(this.enabled[e]=!1,this.drawSides[e]=!1)}};var pD,dD,gD=function(t){var e=new fD;return e.merge(t),e},vD=function(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,n=t.fullSceneLayout,i=[[],[],[]],a=0;a<3;++a){var o=n[mD[a]];if(o._length=(r[a].hi-r[a].lo)*r[a].pixelsPerDataUnit/t.dataScale[a],Math.abs(o._length)===1/0)i[a]=[];else{o._input_range=o.range.slice(),o.range[0]=r[a].lo/t.dataScale[a],o.range[1]=r[a].hi/t.dataScale[a],o._m=1/(t.dataScale[a]*r[a].pixelsPerDataUnit),o.range[0]===o.range[1]&&(o.range[0]-=1,o.range[1]+=1);var s=o.tickmode;if("auto"===o.tickmode){o.tickmode="linear";var l=o.nticks||ne.constrain(o._length/40,4,9);ri.autoTicks(o,Math.abs(o.range[1]-o.range[0])/l)}for(var u=ri.calcTicks(o),c=0;ch[1][o]?f[o]=1:h[1][o]===h[0][o]?f[o]=1:f[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=f,this.convertAnnotations(this),a=0;ad[1][a])d[0][a]=-1,d[1][a]=1;else{var M=d[1][a]-d[0][a];d[0][a]-=M/32,d[1][a]+=M/32}}else{var A=s.range;d[0][a]=s.r2l(A[0]),d[1][a]=s.r2l(A[1])}d[0][a]===d[1][a]&&(d[0][a]-=1,d[1][a]+=1),g[a]=d[1][a]-d[0][a],this.glplot.bounds[0][a]=d[0][a]*f[a],this.glplot.bounds[1][a]=d[1][a]*f[a]}var k=[1,1,1];for(a=0;a<3;++a){var T=v[l=(s=u[wD[a]]).type];k[a]=Math.pow(T.acc,1/T.count)/f[a]}var S;if("auto"===u.aspectmode)S=Math.max.apply(null,k)/Math.min.apply(null,k)<=4?k:[1,1,1];else if("cube"===u.aspectmode)S=[1,1,1];else if("data"===u.aspectmode)S=k;else{if("manual"!==u.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var E=u.aspectratio;S=[E.x,E.y,E.z]}u.aspectratio.x=c.aspectratio.x=S[0],u.aspectratio.y=c.aspectratio.y=S[1],u.aspectratio.z=c.aspectratio.z=S[2],this.glplot.aspect=S;var C=u.domain||null,L=e._size||null;if(C&&L){var z=this.container.style;z.position="absolute",z.left=L.l+C.x[0]*L.w+"px",z.top=L.t+(1-C.y[1])*L.h+"px",z.width=L.w*(C.x[1]-C.x[0])+"px",z.height=L.h*(C.y[1]-C.y[0])+"px"}this.glplot.redraw()}},_D.destroy=function(){this.glplot&&(this.camera.mouseListener.enabled=!1,this.container.removeEventListener("wheel",this.camera.wheelListener),this.camera=this.glplot.camera=null,this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null)},_D.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),kD(this.glplot.camera)},_D.setCamera=function(t){var e;this.glplot.camera.lookAt.apply(this,[[(e=t).eye.x,e.eye.y,e.eye.z],[e.center.x,e.center.y,e.center.z],[e.up.x,e.up.y,e.up.z]])},_D.saveCamera=function(t){var e=this.getCamera(),r=ne.nestedProperty(t,this.id+".camera"),n=r.get(),i=!1;function a(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}if(void 0===n)i=!0;else for(var o=0;o<3;o++)for(var s=0;s<3;s++)if(!a(e,n,o,s)){i=!0;break}return i&&r.set(e),i},_D.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},_D.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(pD),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;a1;Jc(t,e,0,{type:"gl3d",attributes:lz,handleDefaults:uz,fullLayout:e,font:e.font,fullData:r,getDfltFromLayout:function(e){if(!n)return ne.validate(t[e],lz[e])?t[e]:void 0},paper_bgcolor:e.paper_bgcolor,calendar:e.calendar})},SD.plot=function(t){for(var e=t._fullLayout,r=t._fullData,n=e._subplots.gl3d,i=0;i=0;--i){var a=r,o=t[i],s=(r=a+o)-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;i>1;return["sum(",t(e.slice(0,r)),",",t(e.slice(r)),")"].join("")}(e);var n}function UD(t){return new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",VD(function(t){for(var e=new Array(t),r=0;r0&&r.push(","),r.push("[");for(var a=0;a0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(t<6?BD[t]:BD)}var YD=[function(){return[0]},function(t,e){return[[e[0]],[t[0][0]]]}];function XD(t,e){for(var r=0,n=t.length,i=0;i0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=PM[t+1];return i||(i=PM),n(i)}(t)),this.orient=i}var oO=aO.prototype;oO.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){(t=o.pop()).vertices;for(var s=t.adjacent,l=0;l<=r;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,h=0;h<=r;++h){var f=c[h];i[h]=f<0?e:a[f]}var p=this.orient();if(p>0)return u;u.lastVisited=-n,0===p&&o.push(u)}}}return null},oO.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;c<=n;++c)a[c]=i[l[c]];s.lastVisited=r;for(c=0;c<=n;++c){var h=u[c];if(!(h.lastVisited>=r)){var f=a[c];a[c]=t;var p=this.orient();if(a[c]=f,p<0){s=h;continue t}h.boundary?h.lastVisited=-r:h.lastVisited=r}}return}return s},oO.addPeaks=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=this.interior,s=this.simplices,l=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,o.push(e);for(var u=[];l.length>0;){var c=(e=l.pop()).vertices,h=e.adjacent,f=c.indexOf(r);if(!(f<0))for(var p=0;p<=n;++p)if(p!==f){var d=h[p];if(d.boundary&&!(d.lastVisited>=r)){var g=d.vertices;if(d.lastVisited!==-r){for(var v=0,m=0;m<=n;++m)g[m]<0?(v=m,a[m]=t):a[m]=i[g[m]];if(this.orient()>0){g[v]=r,d.boundary=!1,o.push(d),l.push(d),d.lastVisited=r;continue}d.lastVisited=-r}var y=d.adjacent,x=c.slice(),b=h.slice(),_=new eO(x,b,!0);s.push(_);var w=y.indexOf(e);if(!(w<0)){y[w]=_,b[f]=d,x[p]=-1,b[p]=e,h[p]=_,_.flip();for(m=0;m<=n;++m){var M=x[m];if(!(M<0||M===r)){for(var A=new Array(n-1),k=0,T=0;T<=n;++T){var S=x[T];S<0||T===m||(A[k++]=S)}u.push(new rO(A,_,m))}}}}}}u.sort(nO);for(p=0;p+1=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var h=o[0];o[0]=o[1],o[1]=h}e.push(o)}}return e};var sO=function(t,e){var r=t.length;if(0===r)return[];var n=t[0].length;if(n<1)return[];if(1===n)return function(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;a=2)return!1;t[r]=i}return!0}):m.filter(function(t){for(var e=0;e<=n;++e){var r=p[t[e]];if(r<0)return!1;t[e]=r}return!0});if(1&n)for(var o=0;o0){var o=t[r-1];if(0===pO(i,o)&&fO(o)!==a){r-=1;continue}}t[r++]=i}}return t.length=r,t};var yO=function(t){return mO(hO(t))};var xO=function(t,e){return yO(cO(t,e))};var bO=function(t){for(var e=0,r=0,n=1;nt[r][0]&&(r=n);return er?[[r],[e]]:[[e]]};var _O=function(t){var e=t.length;if(e<3){for(var r=new Array(e),n=0;n1&&wO(t[a[u-2]],t[a[u-1]],l)<=0;)u-=1,a.pop();for(a.push(s),u=o.length;u>1&&wO(t[o[u-2]],t[o[u-1]],l)>=0;)u-=1,o.pop();o.push(s)}for(var r=new Array(o.length+a.length-2),c=0,n=0,h=a.length;n0;--f)r[c++]=o[f];return r},wO=PM[3];var MO=function(t){var e=_O(t),r=e.length;if(r<=2)return[];for(var n=new Array(r),i=e[r-1],a=0;a=e[l]&&(s+=1);a[o]=s}}return t}(i,r)}};var SO=function(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;if(0===r)return[];if(1===r)return bO(t);if(2===r)return MO(t);return TO(t,r)};var EO={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:1,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13,rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]};var CO=function(t,e,r){return t*(1-r)+e*r},LO=function(t){var e,r,n,i,a,o,s,l,u,c;t||(t={});l=(t.nshades||72)-1,s=t.format||"hex",(o=t.colormap)||(o="jet");if("string"==typeof o){if(o=o.toLowerCase(),!EO[o])throw Error(o+" not a supported colorscale");a=EO[o]}else{if(!Array.isArray(o))throw Error("unsupported colormap option",o);a=o.slice()}if(a.length>l)throw new Error(o+" map requires nshades to be at least size "+a.length);u=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:t.alpha.slice():"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1];e=a.map(function(t){return Math.round(t.index*l)}),u[0]=Math.min(Math.max(u[0],0),1),u[1]=Math.min(Math.max(u[1],0),1);var h=a.map(function(t,e){var r=a[e].index,n=a[e].rgb.slice();return 4===n.length&&n[3]>=0&&n[3]<=1?n:(n[3]=u[0]+(u[1]-u[0])*r,n)}),f=[];for(c=0;c=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h):(_=0,c>=0?(w=0,g=h):-c>=l?(w=1,g=l+2*c+h):g=c*(w=-c/l)+h);else if(w<0)w=0,u>=0?(_=0,g=h):-u>=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h;else{var M=1/b;g=(_*=M)*(o*_+s*(w*=M)+2*u)+w*(s*_+l*w+2*c)+h}else _<0?(m=l+c)>(v=s+u)?(y=m-v)>=(x=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/x)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h:(_=0,m<=0?(w=1,g=l+2*c+h):c>=0?(w=0,g=h):g=c*(w=-c/l)+h):w<0?(m=o+u)>(v=s+c)?(y=m-v)>=(x=o-2*s+l)?(w=1,_=0,g=l+2*c+h):g=(_=1-(w=y/x))*(o*_+s*w+2*u)+w*(s*_+l*w+2*c)+h:(w=0,m<=0?(_=1,g=o+2*u+h):u>=0?(_=0,g=h):g=u*(_=-u/o)+h):(y=l+c-s-u)<=0?(_=0,w=1,g=l+2*c+h):y>=(x=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/x)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h;var A=1-_-w;for(a=0;a1.0001)return null;p+=f[s]}if(Math.abs(p-1)>.001)return null;return[l,function(t,e){for(var r=[0,0,0],n=0;n 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),JO=E_(["precision mediump 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}"]),KO=E_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]),QO=E_(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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}"]),$O=E_(["precision mediump 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}"]),tR=E_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]);qO.meshShader={vertex:HO,fragment:GO,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},qO.wireShader={vertex:WO,fragment:YO,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},qO.pointShader={vertex:XO,fragment:ZO,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},qO.pickShader={vertex:JO,fragment:KO,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},qO.pointPickShader={vertex:QO,fragment:KO,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},qO.contourShader={vertex:$O,fragment:tR,attributes:[{name:"position",type:"vec3"}]};var eR={};eR.vertexNormals=function(t,e,r){for(var n=e.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa){var b=i[u],_=1/Math.sqrt(v*y);for(x=0;x<3;++x){var w=(x+1)%3,M=(x+2)%3;b[x]+=_*(m[w]*g[M]-m[M]*g[w])}}}for(o=0;oa)for(_=1/Math.sqrt(A),x=0;x<3;++x)b[x]*=_;else for(x=0;x<3;++x)b[x]=0}return i},eR.faceNormals=function(t,e,r){for(var n=t.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa?1/Math.sqrt(p):0;for(u=0;u<3;++u)f[u]*=p;i[o]=f}return i};var rR=32;function nR(t){switch(t){case"uint8":return[__.mallocUint8,__.freeUint8];case"uint16":return[__.mallocUint16,__.freeUint16];case"uint32":return[__.mallocUint32,__.freeUint32];case"int8":return[__.mallocInt8,__.freeInt8];case"int16":return[__.mallocInt16,__.freeInt16];case"int32":return[__.mallocInt32,__.freeInt32];case"float32":return[__.mallocFloat,__.freeFloat];case"float64":return[__.mallocDouble,__.freeDouble];default:return null}}function iR(t){for(var e=[],r=0;r0?i.push(["d",h,"=s",h,"-d",l,"*n",l].join("")):i.push(["d",h,"=s",h].join("")),l=h),0!=(c=t.length-1-a)&&(u>0?i.push(["e",c,"=s",c,"-e",u,"*n",u,",f",c,"=",o[c],"-f",u,"*n",u].join("")):i.push(["e",c,"=s",c,",f",c,"=",o[c]].join("")),u=c)}r.push("var "+i.join(","));var f=["0","n0-1","data","offset"].concat(iR(t.length));r.push(["if(n0<=",rR,"){","insertionSort(",f.join(","),")}else{","quickSort(",f.join(","),")}"].join("")),r.push("}return "+n);var p=new Function("insertionSort","quickSort",r.join("\n")),d=function(t,e){var r=["'use strict'"],n=["ndarrayInsertionSort",t.join("d"),e].join(""),i=["left","right","data","offset"].concat(iR(t.length)),a=nR(e),o=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var s=[],l=1;l1){for(r.push("dptr=0;sptr=ptr"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"b){break __l}"].join("")),l=t.length-1;l>=1;--l)r.push("sptr+=e"+l,"dptr+=f"+l,"}");for(r.push("dptr=cptr;sptr=cptr-s0"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"scratch)){",c("cptr",u("cptr-s0")),"cptr-=s0","}",c("cptr","scratch"));return r.push("}"),t.length>1&&a&&r.push("free(scratch)"),r.push("} return "+n),a?new Function("malloc","free",r.join("\n"))(a[0],a[1]):new Function(r.join("\n"))()}(t,e);return p(d,function(t,e,r){var n=["'use strict'"],i=["ndarrayQuickSort",t.join("d"),e].join(""),a=["left","right","data","offset"].concat(iR(t.length)),o=nR(e),s=0;n.push(["function ",i,"(",a.join(","),"){"].join(""));var l=["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","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var u=[],c=1;c=0;--a)0!==(o=t[a])&&n.push(["for(i",o,"=0;i",o,"1)for(a=0;a1?n.push("ptr_shift+=d"+o):n.push("ptr0+=d"+o),n.push("}"))}}function g(e,r,i,a){if(1===r.length)n.push("ptr0="+h(r[0]));else{for(var o=0;o1)for(o=0;o=1;--o)i&&n.push("pivot_ptr+=f"+o),r.length>1?n.push("ptr_shift+=e"+o):n.push("ptr0+=e"+o),n.push("}")}function v(){t.length>1&&o&&n.push("free(pivot1)","free(pivot2)")}function m(e,r){var i="el"+e,a="el"+r;if(t.length>1){var o="__l"+ ++s;g(o,[i,a],!1,["comp=",f("ptr0"),"-",f("ptr1"),"\n","if(comp>0){tmp0=",i,";",i,"=",a,";",a,"=tmp0;break ",o,"}\n","if(comp<0){break ",o,"}"].join(""))}else n.push(["if(",f(h(i)),">",f(h(a)),"){tmp0=",i,";",i,"=",a,";",a,"=tmp0}"].join(""))}function y(e,r){t.length>1?d([e,r],!1,p("ptr0",f("ptr1"))):n.push(p(h(e),f(h(r))))}function x(e,r,i){if(t.length>1){var a="__l"+ ++s;g(a,[r],!0,[e,"=",f("ptr0"),"-pivot",i,"[pivot_ptr]\n","if(",e,"!==0){break ",a,"}"].join(""))}else n.push([e,"=",f(h(r)),"-pivot",i].join(""))}function b(e,r){t.length>1?d([e,r],!1,["tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1","tmp")].join("")):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1","tmp")].join(""))}function _(e,r,i){t.length>1?(d([e,r,i],!1,["tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1",f("ptr2")),"\n",p("ptr2","tmp")].join("")),n.push("++"+r,"--"+i)):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","ptr2=",h(i),"\n","++",r,"\n","--",i,"\n","tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1",f("ptr2")),"\n",p("ptr2","tmp")].join(""))}function w(t,e){b(t,e),n.push("--"+e)}function M(e,r,i){t.length>1?d([e,r],!0,[p("ptr0",f("ptr1")),"\n",p("ptr1",["pivot",i,"[pivot_ptr]"].join(""))].join("")):n.push(p(h(e),f(h(r))),p(h(r),"pivot"+i))}function A(e,r){n.push(["if((",r,"-",e,")<=",rR,"){\n","insertionSort(",e,",",r,",data,offset,",iR(t.length).join(","),")\n","}else{\n",i,"(",e,",",r,",data,offset,",iR(t.length).join(","),")\n","}"].join(""))}function k(e,r,i){t.length>1?(n.push(["__l",++s,":while(true){"].join("")),d([e],!0,["if(",f("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",s,"}"].join("")),n.push(i,"}")):n.push(["while(",f(h(e)),"===pivot",r,"){",i,"}"].join(""))}return n.push("var "+l.join(",")),m(1,2),m(4,5),m(1,3),m(2,3),m(1,4),m(3,4),m(2,5),m(2,3),m(4,5),t.length>1?d(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",f("ptr1"),"\n","pivot2[pivot_ptr]=",f("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",f("ptr0"),"\n","y=",f("ptr2"),"\n","z=",f("ptr4"),"\n",p("ptr5","x"),"\n",p("ptr6","y"),"\n",p("ptr7","z")].join("")):n.push(["pivot1=",f(h("el2")),"\n","pivot2=",f(h("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",f(h("el1")),"\n","y=",f(h("el3")),"\n","z=",f(h("el5")),"\n",p(h("index1"),"x"),"\n",p(h("index3"),"y"),"\n",p(h("index5"),"z")].join("")),y("index2","left"),y("index4","right"),n.push("if(pivots_are_equal){"),n.push("for(k=less;k<=great;++k){"),x("comp","k",1),n.push("if(comp===0){continue}"),n.push("if(comp<0){"),n.push("if(k!==less){"),b("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),n.push("while(true){"),x("comp","great",1),n.push("if(comp>0){"),n.push("great--"),n.push("}else if(comp<0){"),_("k","less","great"),n.push("break"),n.push("}else{"),w("k","great"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}else{"),n.push("for(k=less;k<=great;++k){"),x("comp_pivot1","k",1),n.push("if(comp_pivot1<0){"),n.push("if(k!==less){"),b("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),x("comp_pivot2","k",2),n.push("if(comp_pivot2>0){"),n.push("while(true){"),x("comp","great",2),n.push("if(comp>0){"),n.push("if(--greatindex5){"),k("less",1,"++less"),k("great",2,"--great"),n.push("for(k=less;k<=great;++k){"),x("comp_pivot1","k",1),n.push("if(comp_pivot1===0){"),n.push("if(k!==less){"),b("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),x("comp_pivot2","k",2),n.push("if(comp_pivot2===0){"),n.push("while(true){"),x("comp","great",2),n.push("if(comp===0){"),n.push("if(--great1&&o?new Function("insertionSort","malloc","free",n.join("\n"))(r,o[0],o[1]):new Function("insertionSort",n.join("\n"))(r)}(t,e,d))},oR={};var sR=function(t){var e=t.order,r=t.dtype,n=[e,r].join(":"),i=oR[n];return i||(oR[n]=i=aR(e,r)),i(t),t},lR=function(t){for(var e=1<>1,v=E[2*m+1];","if(v===b){return m}","if(b0&&o.push(","),o.push("[");for(var n=0;n0&&o.push(","),o.push("B(C,E,c[",i[0],"],c[",i[1],"])")}o.push("]")}o.push(");")}}for(var n=t+1;n>1;--n){n=1},wR.isTransparent=function(){return this.opacity<1},wR.pickSlots=1,wR.setPickBase=function(t){this.pickId=t},wR.highlight=function(t){if(t&&this.contourEnable){for(var e=pR(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=__.mallocFloat32(6*a),s=0,l=0;l0&&((u=this.triShader).bind(),u.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind());this.edgeCount>0&&this.lineWidth>0&&((u=this.lineShader).bind(),u.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind());this.pointCount>0&&((u=this.pointShader).bind(),u.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind());this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0&&((u=this.contourShader).bind(),u.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind())},wR.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||bR,n=t.view||bR,i=t.projection||bR,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s,l={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255};((s=this.pickShader).bind(),s.uniforms=l,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0)&&((s=this.pointPickShader).bind(),s.uniforms=l,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind())},wR.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;a0)i=xO(t.alphahull,a);else{var o=["x","y","z"].indexOf(t.delaunayaxis);i=sO(a.map(function(t){return[t[(o+1)%3],t[(o+2)%3]]}))}var l={positions:a,cells:i,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:WC(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",l.vertexIntensity=t.intensity,l.vertexIntensityBounds=[t.cmin,t.cmax],l.colormap=t.colorscale.map(function(t){var e=t[0],r=s(t[1]).toRgb();return{index:e,rgb:[r.r,r.g,r.b,1]}})):t.vertexcolor?(this.color=t.vertexcolor[0],l.vertexColors=LR(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],l.cellColors=LR(t.facecolor)):(this.color=t.color,l.meshColor=WC(t.color)),this.mesh.update(l)},CR.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()};var PR=function(t,e){var r=t.glplot.gl,n=SR({gl:r}),i=new ER(t,n,e.uid);return n._trace=i,i.update(e),t.glplot.add(n),i},IR={};IR.attributes=RD,IR.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,RD,r,n)}function a(t){var e=t.map(function(t){var e=i(t);return e&&ne.isArrayOrTypedArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var o=a(["x","y","z"]),s=a(["i","j","k"]);o?(s&&s.forEach(function(t){for(var e=0;e1)){var c=ne.simpleMap(u.x,e.d2c,0,r.xcalendar),h=ne.distinctVals(c).minDiff;a=Math.min(a,h)}}for(a===1/0&&(a=1),o=0;o");w.push(o,o,o,o,o,o,null)},O=0;O>>=e))<<3,(e|=r=(15<(t>>>=r))<<2)|(r=(3<(t>>>=r))<<1)|t>>>r>>1}function l(t){t:{for(var e=16;268435456>=e;e*=16)if(t<=e){t=e;break t}t=0}return 0<(e=Y[s(t)>>2]).length?e.pop():new ArrayBuffer(t)}function u(t){Y[s(t.byteLength)>>2].push(t)}function c(t,e,r,n,i,a){for(var o=0;o(i=l)&&(i=n.buffer.byteLength,5123===h?i>>=1:5125===h&&(i>>=2)),n.vertCount=i,i=s,0>s&&(i=4,1===(s=n.buffer.dimension)&&(i=0),2===s&&(i=1),3===s&&(i=4)),n.primType=i}function s(t){n.elementsCount--,delete l[t.id],t.buffer.destroy(),t.buffer=null}var l={},u=0,c={uint8:5121,uint16:5123};e.oes_element_index_uint&&(c.uint32=5125),i.prototype.bind=function(){this.buffer.bind()};var h=[];return{create:function(t,e){function l(t){if(t)if("number"==typeof t)u(t),h.primType=4,h.vertCount=0|t,h.type=5121;else{var e=null,r=35044,n=-1,i=-1,s=0,f=0;Array.isArray(t)||G(t)||a(t)?e=t:("data"in t&&(e=t.data),"usage"in t&&(r=Q[t.usage]),"primitive"in t&&(n=rt[t.primitive]),"count"in t&&(i=0|t.count),"type"in t&&(f=c[t.type]),"length"in t?s=0|t.length:(s=i,5123===f||5122===f?s*=2:5125!==f&&5124!==f||(s*=4))),o(h,e,r,n,i,s,f)}else u(),h.primType=4,h.vertCount=0,h.type=5121;return l}var u=r.create(null,34963,!0),h=new i(u._buffer);return n.elementsCount++,l(t),l._reglType="elements",l._elements=h,l.subdata=function(t,e){return u.subdata(t,e),l},l.destroy=function(){s(h)},l},createStream:function(t){var e=h.pop();return e||(e=new i(r.create(null,34963,!0,!1)._buffer)),o(e,t,35040,-1,-1,0,0),e},destroyStream:function(t){h.push(t)},getElements:function(t){return"function"==typeof t&&t._elements instanceof i?t._elements:null},clear:function(){W(l).forEach(s)}}}function v(t){for(var e=X.allocType(5123,t.length),r=0;r>>31<<15,i=(a<<1>>>24)-127,a=a>>13&1023;e[r]=-24>i?n:-14>i?n+(a+1024>>-14-i):15>=i,r.height>>=i,p(r,n[i]),t.mipmask|=1<e;++e)t.images[e]=null;return t}function C(t){for(var e=t.images,r=0;re){for(var r=0;r=--this.refCount&&R(this)}}),s.profile&&(o.getTotalTextureSize=function(){var t=0;return Object.keys(ht).forEach(function(e){t+=ht[e].stats.size}),t}),{create2D:function(e,r){function n(t,e){var r=i.texInfo;L.call(r);var a=E();return"number"==typeof t?k(a,0|t,"number"==typeof e?0|e:0|t):t?(z(r,t),T(a,t)):k(a,1,1),r.genMipmaps&&(a.mipmask=(a.width<<1)-1),i.mipmask=a.mipmask,u(i,a),i.internalformat=a.internalformat,n.width=a.width,n.height=a.height,D(i),S(a,3553),P(r,3553),O(),C(a),s.profile&&(i.stats.size=M(i.internalformat,i.type,a.width,a.height,r.genMipmaps,!1)),n.format=$[i.internalformat],n.type=tt[i.type],n.mag=et[r.magFilter],n.min=rt[r.minFilter],n.wrapS=nt[r.wrapS],n.wrapT=nt[r.wrapT],n}var i=new I(3553);return ht[i.id]=i,o.textureCount++,n(e,r),n.subimage=function(t,e,r,a){e|=0,r|=0,a|=0;var o=g();return u(o,i),o.width=0,o.height=0,p(o,t),o.width=o.width||(i.width>>a)-e,o.height=o.height||(i.height>>a)-r,D(i),d(o,3553,e,r,a),O(),A(o),n},n.resize=function(e,r){var a=0|e,o=0|r||a;if(a===i.width&&o===i.height)return n;n.width=i.width=a,n.height=i.height=o,D(i);for(var l=0;i.mipmask>>l;++l)t.texImage2D(3553,l,i.format,a>>l,o>>l,0,i.format,i.type,null);return O(),s.profile&&(i.stats.size=M(i.internalformat,i.type,a,o,!1,!1)),n},n._reglType="texture2d",n._texture=i,s.profile&&(n.stats=i.stats),n.destroy=function(){i.decRef()},n},createCube:function(e,r,n,i,a,l){function h(t,e,r,n,i,a){var o,l=f.texInfo;for(L.call(l),o=0;6>o;++o)v[o]=E();if("number"!=typeof t&&t){if("object"==typeof t)if(e)T(v[0],t),T(v[1],e),T(v[2],r),T(v[3],n),T(v[4],i),T(v[5],a);else if(z(l,t),c(f,t),"faces"in t)for(t=t.faces,o=0;6>o;++o)u(v[o],f),T(v[o],t[o]);else for(o=0;6>o;++o)T(v[o],t)}else for(t=0|t||1,o=0;6>o;++o)k(v[o],t,t);for(u(f,v[0]),f.mipmask=l.genMipmaps?(v[0].width<<1)-1:v[0].mipmask,f.internalformat=v[0].internalformat,h.width=v[0].width,h.height=v[0].height,D(f),o=0;6>o;++o)S(v[o],34069+o);for(P(l,34067),O(),s.profile&&(f.stats.size=M(f.internalformat,f.type,h.width,h.height,l.genMipmaps,!0)),h.format=$[f.internalformat],h.type=tt[f.type],h.mag=et[l.magFilter],h.min=rt[l.minFilter],h.wrapS=nt[l.wrapS],h.wrapT=nt[l.wrapT],o=0;6>o;++o)C(v[o]);return h}var f=new I(34067);ht[f.id]=f,o.cubeCount++;var v=Array(6);return h(e,r,n,i,a,l),h.subimage=function(t,e,r,n,i){r|=0,n|=0,i|=0;var a=g();return u(a,f),a.width=0,a.height=0,p(a,e),a.width=a.width||(f.width>>i)-r,a.height=a.height||(f.height>>i)-n,D(f),d(a,34069+t,r,n,i),O(),A(a),h},h.resize=function(e){if((e|=0)!==f.width){h.width=f.width=e,h.height=f.height=e,D(f);for(var r=0;6>r;++r)for(var n=0;f.mipmask>>n;++n)t.texImage2D(34069+r,n,f.format,e>>n,e>>n,0,f.format,f.type,null);return O(),s.profile&&(f.stats.size=M(f.internalformat,f.type,h.width,h.height,!1,!0)),h}},h._reglType="textureCube",h._texture=f,s.profile&&(h.stats=f.stats),h.destroy=function(){f.decRef()},h},clear:function(){for(var e=0;er;++r)if(0!=(e.mipmask&1<>r,e.height>>r,0,e.internalformat,e.type,null);else for(var n=0;6>n;++n)t.texImage2D(34069+n,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);P(e.texInfo,e.target)})}}}function k(t,e,r,n,i,a){function o(t,e,r){this.target=t,this.texture=e,this.renderbuffer=r;var n=t=0;e?(t=e.width,n=e.height):r&&(t=r.width,n=r.height),this.width=t,this.height=n}function s(t){t&&(t.texture&&t.texture._texture.decRef(),t.renderbuffer&&t.renderbuffer._renderbuffer.decRef())}function l(t,e,r){t&&(t.texture?t.texture._texture.refCount+=1:t.renderbuffer._renderbuffer.refCount+=1)}function u(e,r){r&&(r.texture?t.framebufferTexture2D(36160,e,r.target,r.texture._texture.texture,0):t.framebufferRenderbuffer(36160,e,36161,r.renderbuffer._renderbuffer.renderbuffer))}function c(t){var e=3553,r=null,n=null,i=t;return"object"==typeof t&&(i=t.data,"target"in t&&(e=0|t.target)),"texture2d"===(t=i._reglType)?r=i:"textureCube"===t?r=i:"renderbuffer"===t&&(n=i,e=36161),new o(e,r,n)}function h(t,e,r,a,s){return r?((t=n.create2D({width:t,height:e,format:a,type:s}))._texture.refCount=0,new o(3553,t,null)):((t=i.create({width:t,height:e,format:a}))._renderbuffer.refCount=0,new o(36161,null,t))}function f(t){return t&&(t.texture||t.renderbuffer)}function p(t,e,r){t&&(t.texture?t.texture.resize(e,r):t.renderbuffer&&t.renderbuffer.resize(e,r))}function d(){this.id=M++,A[this.id]=this,this.framebuffer=t.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function g(t){t.colorAttachments.forEach(s),s(t.depthAttachment),s(t.stencilAttachment),s(t.depthStencilAttachment)}function v(e){t.deleteFramebuffer(e.framebuffer),e.framebuffer=null,a.framebufferCount--,delete A[e.id]}function m(e){var n;t.bindFramebuffer(36160,e.framebuffer);var i=e.colorAttachments;for(n=0;ni;++i){for(u=0;ut;++t)r[t].resize(n);return e.width=e.height=n,e},_reglType:"framebufferCube",destroy:function(){r.forEach(function(t){t.destroy()})}})},clear:function(){W(A).forEach(v)},restore:function(){W(A).forEach(function(e){e.framebuffer=t.createFramebuffer(),m(e)})}})}function T(){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 S(t,e,r,n){function i(t,e,r,n){this.name=t,this.id=e,this.location=r,this.info=n}function a(t,e){for(var r=0;rt&&(t=e.stats.uniformsCount)}),t},r.getMaxAttributesCount=function(){var t=0;return f.forEach(function(e){e.stats.attributesCount>t&&(t=e.stats.attributesCount)}),t}),{clear:function(){var e=t.deleteShader.bind(t);W(u).forEach(e),u={},W(c).forEach(e),c={},f.forEach(function(e){t.deleteProgram(e.program)}),f.length=0,h={},r.shaderCount=0},program:function(t,e,n){var i=h[e];i||(i=h[e]={});var a=i[t];return a||(a=new s(e,t),r.shaderCount++,l(a),i[t]=a,f.push(a)),a},restore:function(){u={},c={};for(var t=0;t="+e+"?"+i+".constant["+e+"]:0;"}).join(""),"}}else{","if(",o,"(",i,".buffer)){",c,"=",s,".createStream(",34962,",",i,".buffer);","}else{",c,"=",s,".getBuffer(",i,".buffer);","}",h,'="type" in ',i,"?",a.glTypes,"[",i,".type]:",c,".dtype;",l.normalized,"=!!",i,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",l.isStream,"){",s,".destroyStream(",c,");","}"),l})}),o}function k(t,e,r,n,i){var a=_(t),s=function(t,e,r){function n(t){if(t in i){var r=i[t];t=!0;var n,o,s=0|r.x,l=0|r.y;return"width"in r?n=0|r.width:t=!1,"height"in r?o=0|r.height:t=!1,new D(!t&&e&&e.thisDep,!t&&e&&e.contextDep,!t&&e&&e.propDep,function(t,e){var i=t.shared.context,a=n;"width"in r||(a=e.def(i,".","framebufferWidth","-",s));var u=o;return"height"in r||(u=e.def(i,".","framebufferHeight","-",l)),[s,l,a,u]})}if(t in a){var u=a[t];return t=F(u,function(t,e){var r=t.invoke(e,u),n=t.shared.context,i=e.def(r,".x|0"),a=e.def(r,".y|0");return[i,a,e.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",i,")"),r=e.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",a,")")]}),e&&(t.thisDep=t.thisDep||e.thisDep,t.contextDep=t.contextDep||e.contextDep,t.propDep=t.propDep||e.propDep),t}return e?new D(e.thisDep,e.contextDep,e.propDep,function(t,e){var r=t.shared.context;return[0,0,e.def(r,".","framebufferWidth"),e.def(r,".","framebufferHeight")]}):null}var i=t.static,a=t.dynamic;if(t=n("viewport")){var o=t;t=new D(t.thisDep,t.contextDep,t.propDep,function(t,e){var r=o.append(t,e),n=t.shared.context;return e.set(n,".viewportWidth",r[2]),e.set(n,".viewportHeight",r[3]),r})}return{viewport:t,scissor_box:n("scissor.box")}}(t,a),l=M(t),u=function(t,e){var r=t.static,n=t.dynamic,i={};return nt.forEach(function(t){function e(e,o){if(t in r){var s=e(r[t]);i[a]=R(function(){return s})}else if(t in n){var l=n[t];i[a]=F(l,function(t,e){return o(t,e,t.invoke(e,l))})}}var a=v(t);switch(t){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return e(function(t){return t},function(t,e,r){return r});case"depth.func":return e(function(t){return yt[t]},function(t,e,r){return e.def(t.constants.compareFuncs,"[",r,"]")});case"depth.range":return e(function(t){return t},function(t,e,r){return[e.def("+",r,"[0]"),e=e.def("+",r,"[1]")]});case"blend.func":return e(function(t){return[mt["srcRGB"in t?t.srcRGB:t.src],mt["dstRGB"in t?t.dstRGB:t.dst],mt["srcAlpha"in t?t.srcAlpha:t.src],mt["dstAlpha"in t?t.dstAlpha:t.dst]]},function(t,e,r){function n(t,n){return e.def('"',t,n,'" in ',r,"?",r,".",t,n,":",r,".",t)}t=t.constants.blendFuncs;var i=n("src","RGB"),a=n("dst","RGB"),o=(i=e.def(t,"[",i,"]"),e.def(t,"[",n("src","Alpha"),"]"));return[i,a=e.def(t,"[",a,"]"),o,t=e.def(t,"[",n("dst","Alpha"),"]")]});case"blend.equation":return e(function(t){return"string"==typeof t?[J[t],J[t]]:"object"==typeof t?[J[t.rgb],J[t.alpha]]:void 0},function(t,e,r){var n=t.constants.blendEquations,i=e.def(),a=e.def();return(t=t.cond("typeof ",r,'==="string"')).then(i,"=",a,"=",n,"[",r,"];"),t.else(i,"=",n,"[",r,".rgb];",a,"=",n,"[",r,".alpha];"),e(t),[i,a]});case"blend.color":return e(function(t){return o(4,function(e){return+t[e]})},function(t,e,r){return o(4,function(t){return e.def("+",r,"[",t,"]")})});case"stencil.mask":return e(function(t){return 0|t},function(t,e,r){return e.def(r,"|0")});case"stencil.func":return e(function(t){return[yt[t.cmp||"keep"],t.ref||0,"mask"in t?t.mask:-1]},function(t,e,r){return[t=e.def('"cmp" in ',r,"?",t.constants.compareFuncs,"[",r,".cmp]",":",7680),e.def(r,".ref|0"),e=e.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return e(function(e){return["stencil.opBack"===t?1029:1028,xt[e.fail||"keep"],xt[e.zfail||"keep"],xt[e.zpass||"keep"]]},function(e,r,n){function i(t){return r.def('"',t,'" in ',n,"?",a,"[",n,".",t,"]:",7680)}var a=e.constants.stencilOps;return["stencil.opBack"===t?1029:1028,i("fail"),i("zfail"),i("zpass")]});case"polygonOffset.offset":return e(function(t){return[0|t.factor,0|t.units]},function(t,e,r){return[e.def(r,".factor|0"),e=e.def(r,".units|0")]});case"cull.face":return e(function(t){var e=0;return"front"===t?e=1028:"back"===t&&(e=1029),e},function(t,e,r){return e.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return e(function(t){return t},function(t,e,r){return r});case"frontFace":return e(function(t){return bt[t]},function(t,e,r){return e.def(r+'==="cw"?2304:2305')});case"colorMask":return e(function(t){return t.map(function(t){return!!t})},function(t,e,r){return o(4,function(t){return"!!"+r+"["+t+"]"})});case"sample.coverage":return e(function(t){return["value"in t?t.value:1,!!t.invert]},function(t,e,r){return[e.def('"value" in ',r,"?+",r,".value:1"),e=e.def("!!",r,".invert")]})}}),i}(t),c=w(t),h=s.viewport;return h&&(u.viewport=h),(s=s[h=v("scissor.box")])&&(u[h]=s),(a={framebuffer:a,draw:l,shader:c,state:u,dirty:s=0>1)",s],");")}function e(){r(l,".drawArraysInstancedANGLE(",[d,g,v,s],");")}p?y?t():(r("if(",p,"){"),t(),r("}else{"),e(),r("}")):e()}function o(){function t(){r(c+".drawElements("+[d,v,m,g+"<<(("+m+"-5121)>>1)"]+");")}function e(){r(c+".drawArrays("+[d,g,v]+");")}p?y?t():(r("if(",p,"){"),t(),r("}else{"),e(),r("}")):e()}var s,l,u=t.shared,c=u.gl,h=u.draw,f=n.draw,p=function(){var i=f.elements,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(h,".","elements"),i&&a("if("+i+")"+c+".bindBuffer(34963,"+i+".buffer.buffer);"),i}(),d=i("primitive"),g=i("offset"),v=function(){var i=f.count,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(h,".","count"),i}();if("number"==typeof v){if(0===v)return}else r("if(",v,"){"),r.exit("}");Q&&(s=i("instances"),l=t.instancing);var m=p+".type",y=f.elements&&O(f.elements);Q&&("number"!=typeof s||0<=s)?"string"==typeof s?(r("if(",s,">0){"),a(),r("}else if(",s,"<0){"),o(),r("}")):a():o()}function q(t,e,r,n,i){return i=(e=b()).proc("body",i),Q&&(e.instancing=i.def(e.shared.extensions,".angle_instanced_arrays")),t(e,i,r,n),e.compile().body}function H(t,e,r,n){L(t,e),N(t,e,r,n.attributes,function(){return!0}),j(t,e,r,n.uniforms,function(){return!0}),V(t,e,e,r)}function G(t,e,r,n){function i(){return!0}t.batchId="a1",L(t,e),N(t,e,r,n.attributes,i),j(t,e,r,n.uniforms,i),V(t,e,e,r)}function W(t,e,r,n){function i(t){return t.contextDep&&o||t.propDep}function a(t){return!i(t)}L(t,e);var o=r.contextDep,s=e.def(),l=e.def();t.shared.props=l,t.batchId=s;var u=t.scope(),c=t.scope();e(u.entry,"for(",s,"=0;",s,"<","a1",";++",s,"){",l,"=","a0","[",s,"];",c,"}",u.exit),r.needsContext&&T(t,c,r.context),r.needsFramebuffer&&S(t,c,r.framebuffer),C(t,c,r.state,i),r.profile&&i(r.profile)&&B(t,c,r,!1,!0),n?(N(t,u,r,n.attributes,a),N(t,c,r,n.attributes,i),j(t,u,r,n.uniforms,a),j(t,c,r,n.uniforms,i),V(t,u,c,r)):(e=t.global.def("{}"),n=r.shader.progVar.append(t,c),l=c.def(n,".id"),u=c.def(e,"[",l,"]"),c(t.shared.gl,".useProgram(",n,".program);","if(!",u,"){",u,"=",e,"[",l,"]=",t.link(function(e){return q(G,t,r,e,2)}),"(",n,");}",u,".call(this,a0[",s,"],",s,");"))}function Y(t,r){function n(e){var n=r.shader[e];n&&i.set(a.shader,"."+e,n.append(t,i))}var i=t.proc("scope",3);t.batchId="a2";var a=t.shared,o=a.current;T(t,i,r.context),r.framebuffer&&r.framebuffer.append(t,i),I(Object.keys(r.state)).forEach(function(e){var n=r.state[e].append(t,i);m(n)?n.forEach(function(r,n){i.set(t.next[e],"["+n+"]",r)}):i.set(a.next,"."+e,n)}),B(t,i,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(e){var n=r.draw[e];n&&i.set(a.draw,"."+e,""+n.append(t,i))}),Object.keys(r.uniforms).forEach(function(n){i.set(a.uniforms,"["+e.id(n)+"]",r.uniforms[n].append(t,i))}),Object.keys(r.attributes).forEach(function(e){var n=r.attributes[e].append(t,i),a=t.scopeAttrib(e);Object.keys(new Z).forEach(function(t){i.set(a,"."+t,n[t])})}),n("vert"),n("frag"),0=--this.refCount&&o(this)},i.profile&&(n.getTotalRenderbufferSize=function(){var t=0;return Object.keys(c).forEach(function(e){t+=c[e].stats.size}),t}),{create:function(e,r){function o(e,r){var n=0,a=0,c=32854;if("object"==typeof e&&e?("shape"in e?(n=0|(a=e.shape)[0],a=0|a[1]):("radius"in e&&(n=a=0|e.radius),"width"in e&&(n=0|e.width),"height"in e&&(a=0|e.height)),"format"in e&&(c=s[e.format])):"number"==typeof e?(n=0|e,a="number"==typeof r?0|r:n):e||(n=a=1),n!==u.width||a!==u.height||c!==u.format)return o.width=u.width=n,o.height=u.height=a,u.format=c,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,c,n,a),i.profile&&(u.stats.size=ht[u.format]*u.width*u.height),o.format=l[u.format],o}var u=new a(t.createRenderbuffer());return c[u.id]=u,n.renderbufferCount++,o(e,r),o.resize=function(e,r){var n=0|e,a=0|r||n;return n===u.width&&a===u.height?o:(o.width=u.width=n,o.height=u.height=a,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,u.format,n,a),i.profile&&(u.stats.size=ht[u.format]*u.width*u.height),o)},o._reglType="renderbuffer",o._renderbuffer=u,i.profile&&(o.stats=u.stats),o.destroy=function(){u.decRef()},o},clear:function(){W(c).forEach(o)},restore:function(){W(c).forEach(function(e){e.renderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,e.renderbuffer),t.renderbufferStorage(36161,e.format,e.width,e.height)}),t.bindRenderbuffer(36161,null)}}},pt=[];pt[6408]=4;var dt=[];dt[5121]=1,dt[5126]=4,dt[36193]=2;var gt=["x","y","z","w"],vt="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),mt={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},yt={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},xt={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},bt={cw:2304,ccw:2305},_t=new D(!1,!1,!1,function(){});return function(t){function e(){if(0===X.length)w&&w.update(),Q=null;else{Q=q.next(e),h();for(var t=X.length-1;0<=t;--t){var r=X[t];r&&r(z,null,0)}v.flush(),w&&w.update()}}function r(){!Q&&0=X.length&&n()}}}}function c(){var t=W.viewport,e=W.scissor_box;t[0]=t[1]=e[0]=e[1]=0,z.viewportWidth=z.framebufferWidth=z.drawingBufferWidth=t[2]=e[2]=v.drawingBufferWidth,z.viewportHeight=z.framebufferHeight=z.drawingBufferHeight=t[3]=e[3]=v.drawingBufferHeight}function h(){z.tick+=1,z.time=p(),c(),G.procs.poll()}function f(){c(),G.procs.refresh(),w&&w.update()}function p(){return(H()-M)/1e3}if(!(t=i(t)))return null;var v=t.gl,m=v.getContextAttributes();v.isContextLost();var y=function(t,e){function r(e){var r;e=e.toLowerCase();try{r=n[e]=t.getExtension(e)}catch(t){}return!!r}for(var n={},i=0;ie;++e)$(j({framebuffer:t.framebuffer.faces[e]},t),l);else $(t,l);else l(0,t)},prop:U.define.bind(null,1),context:U.define.bind(null,2),this:U.define.bind(null,3),draw:s({}),buffer:function(t){return I.create(t,34962,!1,!1)},elements:function(t){return D.create(t,!1)},texture:R.create2D,cube:R.createCube,renderbuffer:F.create,framebuffer:V.create,framebufferCube:V.createCube,attributes:m,frame:u,on:function(t,e){var r;switch(t){case"frame":return u(e);case"lost":r=Z;break;case"restore":r=J;break;case"destroy":r=K}return r.push(e),{cancel:function(){for(var t=0;t>>8*e)%256/255}function cF(t,e){var r={};return[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].map(function(r){return function(t,e,r){var n,i,a,o=[];for(i=0;i=eF-4?uF(o,eF-2-s):.5);return a}(m,v,g,x),A=cF(m,M),k=e.regl,T=k.texture({shape:[256,1],format:"rgba",type:"uint8",mag:"nearest",min:"nearest",data:function(t,e,r){for(var n=[],i=0;i<256;i++){var a=t(i/255);n.push((e?iF:a).concat(r))}return n}(h,f,Math.round(255*(f?b:1)))}),S=k({profile:!1,blend:{enable:y,func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:1,dstAlpha:1},equation:{rgb:"add",alpha:"add"},color:[0,0,0,0]},depth:{enable:!y,mask:!0,func:"less",range:[0,1]},cull:{enable:!0,face:"back"},scissor:{enable:!0,box:{x:k.prop("scissorX"),y:k.prop("scissorY"),width:k.prop("scissorWidth"),height:k.prop("scissorHeight")}},viewport:{x:k.prop("viewportX"),y:k.prop("viewportY"),width:k.prop("viewportWidth"),height:k.prop("viewportHeight")},dither:!1,vert:p?QR:KR,frag:$R,primitive:"lines",lineWidth:1,attributes:A,uniforms:{resolution:k.prop("resolution"),viewBoxPosition:k.prop("viewBoxPosition"),viewBoxSize:k.prop("viewBoxSize"),dim1A:k.prop("dim1A"),dim2A:k.prop("dim2A"),dim1B:k.prop("dim1B"),dim2B:k.prop("dim2B"),dim1C:k.prop("dim1C"),dim2C:k.prop("dim2C"),dim1D:k.prop("dim1D"),dim2D:k.prop("dim2D"),loA:k.prop("loA"),hiA:k.prop("hiA"),loB:k.prop("loB"),hiB:k.prop("hiB"),loC:k.prop("loC"),hiC:k.prop("hiC"),loD:k.prop("loD"),hiD:k.prop("hiD"),palette:T,colorClamp:k.prop("colorClamp"),scatter:k.prop("scatter")},offset:k.prop("offset"),count:k.prop("count")}),E=[0,1];var C=[];function L(t,e,r,i,o,u,c,h,p,d,v){var m,y,x,b,M=[t,e],A=JR.verticalPadding/u,k=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})}),T=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(m=0;m<2;m++)for(b=M[m],y=0;y<4;y++)for(x=0;x<16;x++){var S=x+16*y;k[m][y][x]=x+16*y===b?1:0,T[m][y][x]=(!f&&hF(x,16*y,w)?g[0===S?0:1+(S-1)%(g.length-1)].filter[m]:m)+(2*m-1)*A}return{key:c,resolution:[s,l],viewBoxPosition:[r+_,i],viewBoxSize:[o,u],i:t,ii:e,dim1A:k[0][0],dim1B:k[0][1],dim1C:k[0][2],dim1D:k[0][3],dim2A:k[1][0],dim2B:k[1][1],dim2C:k[1][2],dim2D:k[1][3],loA:T[0][0],loB:T[0][1],loC:T[0][2],loD:T[0][3],hiA:T[1][0],hiB:T[1][1],hiC:T[1][2],hiD:T[1][3],colorClamp:E,scatter:h||0,scissorX:(p===d?0:r+_)+(n.pad.l-_)+n.layoutWidth*a.x[0],scissorWidth:(p===v?s-r+_:o+.5)+(p===d?r+_:0),scissorY:i+n.pad.b+n.layoutHeight*a.y[0],scissorHeight:u,viewportX:n.pad.l-_+n.layoutWidth*a.x[0],viewportY:n.pad.b+n.layoutHeight*a.y[0],viewportWidth:s,viewportHeight:l}}return{setColorDomain:function(t){E[0]=t[0],E[1]=t[1]},render:function(t,e,n){var i,a,u,c=1/0,h=-1/0;for(i=0;ih&&(h=t[i].dim2.canvasX,u=i),t[i].dim1.canvasXi)return a;i=o,a=n[r]}return n[n.length-1]}function xF(t){return e.scale.linear().domain(mF(t))}function bF(t,r,n){var i=gF(r),a=i.trace,o=i.lineColor,s=i.cscale,l=a.line,u=a.domain,c=a.dimensions,h=t.width,f=a.labelfont,p=a.tickfont,d=a.rangefont,g=ne.extendDeep({},l,{color:o.map(xF({values:o,range:[l.cmin,l.cmax],_length:a._commonLength})),blockLineCount:JR.blockLineCount,canvasOverdrag:JR.overdrag*JR.canvasPixelRatio}),v=Math.floor(h*(u.x[1]-u.x[0])),m=Math.floor(t.height*(u.y[1]-u.y[0])),y=t.margin||{l:80,r:80,t:100,b:80},x=v,b=m;return{key:n,colCount:c.filter(vF).length,dimensions:c,tickDistance:JR.tickDistance,unitToColor:function(t){var r=t.map(function(t){return t[0]}),n=t.map(function(t){return t[1]}).map(function(t){return e.rgb(t)}),i="rgb".split("").map(function(t){return e.scale.linear().clamp(!0).domain(r).range(n.map((i=t,function(t){return t[i]})));var i});return function(t){return i.map(function(e){return e(t)})}}(s),lines:g,labelFont:f,tickFont:p,rangeFont:d,layoutWidth:h,layoutHeight:t.height,domain:u,translateX:u.x[0]*h,translateY:t.height-u.y[1]*t.height,pad:y,canvasWidth:x*JR.canvasPixelRatio+2*g.canvasOverdrag,canvasHeight:b*JR.canvasPixelRatio,width:x,height:b,canvasPixelRatio:JR.canvasPixelRatio}}function _F(t){var r=t.width,n=t.height,i=t.dimensions,a=t.canvasPixelRatio,o=function(e){return r*e/Math.max(1,t.colCount-1)},s=JR.verticalPadding/(n*a),l=1-2*s,u=function(t){return s+l*t},c={key:t.key,xScale:o,model:t},h={};return c.dimensions=i.filter(vF).map(function(r,i){var s=xF(r),l=h[r.label];h[r.label]=(l||0)+1;var f=r.label+(l?"__"+l:""),p=r.values;return p.length>r._length&&(p=p.slice(0,r._length)),{key:f,label:r.label,tickFormat:r.tickformat,tickvals:r.tickvals,ticktext:r.ticktext,ordinal:!!r.tickvals,scatter:JR.scatter||r.scatter,xIndex:i,crossfilterDimensionIndex:i,visibleIndex:r._index,height:n,values:p,paddedUnitValues:p.map(s).map(u),xScale:o,x:o(i),canvasX:o(i)*a,unitScale:function(t,r){return e.scale.linear().range([t-r,r])}(n,JR.verticalPadding),domainScale:function(t,r,n){var i=mF(n),a=n.ticktext;return n.tickvals?e.scale.ordinal().domain(n.tickvals.map(function(t,e){return function(r,n){if(e){var i=e[n];return null===i||void 0===i?t(r):i}return t(r)}}(e.format(n.tickformat),a))).range(n.tickvals.map(function(t){return(t-i[0])/(i[1]-i[0])}).map(function(e){return t-r+e*(r-(t-r))})):e.scale.linear().domain(i).range([t-r,r])}(n,JR.verticalPadding,r),ordinalScale:function(t){var r=mF(t);return t.tickvals&&e.scale.ordinal().domain(t.tickvals).range(t.tickvals.map(function(t){return(t-r[0])/(r[1]-r[0])}))}(r),domainToUnitScale:s,filter:r.constraintrange?r.constraintrange.map(s):[0,1],parent:c,model:t}}),c}function wF(t){t.classed(JR.cn.axisExtentText,!0).attr("text-anchor","middle").style("cursor","default").style("user-select","none")}var MF={};(function(t){"use strict";MF=function(r,n){var i=r._fullLayout,a=i._toppaper,o=(i._paperdiv,i._glcontainer);i._glcanvas.each(function(e){e.regl||(e.regl=YR({canvas:this,attributes:{antialias:!e.pick,preserveDrawingBuffer:!0},pixelRatio:r._context.plotGlPixelRatio||t.devicePixelRatio}))});var s={},l={},u=i._size;n.forEach(function(t,e){s[e]=r.data[e].dimensions,l[e]=r.data[e].dimensions.slice()});!function(t,r,n,i,a,o){var s=!1,l=!0;var u=i.filter(function(t){return gF(t).trace.visible}).map(bF.bind(0,a)).map(_F);n.each(function(t,e){return ne.extendFlat(t,u[e])});var c=n.selectAll(".gl-canvas").each(function(t){t.viewModel=u[0],t.model=t.viewModel?t.viewModel.model:null}),h={renderers:[],dimensions:[]},f=null;c.filter(function(t){return t.pick}).style("pointer-events","auto").on("mousemove",function(t){if(l&&t.lineLayer&&o&&o.hover){var r=e.event,n=this.width,i=this.height,a=e.mouse(this),s=a[0],u=a[1];if(s<0||u<0||s>=n||u>=i)return;var c=t.lineLayer.readPixel(s,i-1-u),h=0!==c[3],p=h?c[2]+256*(c[1]+256*c[0]):null,d={x:s,y:u,clientX:r.clientX,clientY:r.clientY,dataIndex:t.model.key,curveNumber:p};p!==f&&(h?o.hover(d):o.unhover&&o.unhover(d),f=p)}}),c.style("opacity",function(t){return t.pick?.01:1}),r.style("background","rgba(255, 255, 255, 0)");var p=r.selectAll("."+JR.cn.parcoords).data(u,pF);p.exit().remove(),p.enter().append("g").classed(JR.cn.parcoords,!0).attr("overflow","visible").style("box-sizing","content-box").style("position","absolute").style("left",0).style("overflow","visible").style("shape-rendering","crispEdges").style("pointer-events","none").call(function(t){var e=t.selectAll("defs").data(dF,pF);e.enter().append("defs");var r=e.selectAll("#"+JR.id.filterBarPattern).data(dF,pF);r.enter().append("pattern").attr("id",JR.id.filterBarPattern).attr("patternUnits","userSpaceOnUse"),r.attr("x",-JR.bar.width).attr("width",JR.bar.capturewidth).attr("height",function(t){return t.model.height});var n=r.selectAll("rect").data(dF,pF);n.enter().append("rect").attr("shape-rendering","crispEdges"),n.attr("height",function(t){return t.model.height}).attr("width",JR.bar.width).attr("x",JR.bar.width/2).attr("fill",JR.bar.fillcolor).attr("fill-opacity",JR.bar.fillopacity).attr("stroke",JR.bar.strokecolor).attr("stroke-opacity",JR.bar.strokeopacity).attr("stroke-width",JR.bar.strokewidth)}),p.attr("width",function(t){return t.model.width+t.model.pad.l+t.model.pad.r}).attr("height",function(t){return t.model.height+t.model.pad.t+t.model.pad.b}).attr("transform",function(t){return"translate("+t.model.translateX+","+t.model.translateY+")"});var d=p.selectAll("."+JR.cn.parcoordsControlView).data(dF,pF);d.enter().append("g").classed(JR.cn.parcoordsControlView,!0).style("box-sizing","content-box"),d.attr("transform",function(t){return"translate("+t.model.pad.l+","+t.model.pad.t+")"});var g=d.selectAll("."+JR.cn.yAxis).data(function(t){return t.dimensions},pF);function v(t){return t.dimensions.some(function(t){return 0!==t.filter[0]||1!==t.filter[1]})}function m(t,e){return(JR.scatter?function(t,e){for(var r=e.panels||(e.panels=[]),n=t.each(function(t){return t})[e.key].map(function(t){return t.__data__}),i=n.length-1,a=i,o=0;oline").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.25).attr("stroke-width","1px"),x.selectAll("text").style("text-shadow","1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff").style("cursor","default").style("user-select","none");var b=y.selectAll("."+JR.cn.axisHeading).data(dF,pF);b.enter().append("g").classed(JR.cn.axisHeading,!0);var _=b.selectAll("."+JR.cn.axisTitle).data(dF,pF);_.enter().append("text").classed(JR.cn.axisTitle,!0).attr("text-anchor","middle").style("cursor","ew-resize").style("user-select","none").style("pointer-events","auto"),_.attr("transform","translate(0,"+-JR.axisTitleOffset+")").text(function(t){return t.label}).each(function(t){Sr.font(_,t.model.labelFont)});var w=y.selectAll("."+JR.cn.axisExtent).data(dF,pF);w.enter().append("g").classed(JR.cn.axisExtent,!0);var M=w.selectAll("."+JR.cn.axisExtentTop).data(dF,pF);M.enter().append("g").classed(JR.cn.axisExtentTop,!0),M.attr("transform","translate(0,"+-JR.axisExtentOffset+")");var A=M.selectAll("."+JR.cn.axisExtentTopText).data(dF,pF);function k(t){return t.ordinal?function(){return""}:e.format(t.tickFormat)}A.enter().append("text").classed(JR.cn.axisExtentTopText,!0).call(wF),A.text(function(t){return k(t)(t.domainScale.domain().slice(-1)[0])}).each(function(t){Sr.font(A,t.model.rangeFont)});var T=w.selectAll("."+JR.cn.axisExtentBottom).data(dF,pF);T.enter().append("g").classed(JR.cn.axisExtentBottom,!0),T.attr("transform",function(t){return"translate(0,"+(t.model.height+JR.axisExtentOffset)+")"});var S=T.selectAll("."+JR.cn.axisExtentBottomText).data(dF,pF);S.enter().append("text").classed(JR.cn.axisExtentBottomText,!0).attr("dy","0.75em").call(wF),S.text(function(t){return k(t)(t.domainScale.domain()[0])}).each(function(t){Sr.font(S,t.model.rangeFont)});var E=y.selectAll("."+JR.cn.axisBrush).data(dF,pF),C=E.enter().append("g").classed(JR.cn.axisBrush,!0);E.each(function(t){t.brush||(t.brush=e.svg.brush().y(t.unitScale).on("brushstart",P).on("brush",I).on("brushend",D),0===t.filter[0]&&1===t.filter[1]||t.brush.extent(t.filter),e.select(this).call(t.brush))}),C.selectAll("rect").attr("x",-JR.bar.capturewidth/2).attr("width",JR.bar.capturewidth),C.selectAll("rect.extent").attr("fill","url(#"+JR.id.filterBarPattern+")").style("cursor","ns-resize").filter(function(t){return 0===t.filter[0]&&1===t.filter[1]}).attr("y",-100),C.selectAll(".resize rect").attr("height",JR.bar.handleheight).attr("opacity",0).style("visibility","visible"),C.selectAll(".resize.n rect").style("cursor","n-resize").attr("y",JR.bar.handleoverlap-JR.bar.handleheight),C.selectAll(".resize.s rect").style("cursor","s-resize").attr("y",JR.bar.handleoverlap);var L=!1,z=!1;function P(){L=!0,s=!0}function I(t){l=!1;var r=t.parent,n=t.brush.extent(),i=r.dimensions,a=i[t.xIndex].filter,o=L&&n[0]===n[1];o&&(t.brush.clear(),e.select(this).select("rect.extent").attr("y",-100));var s=o?[0,1]:n.slice();if(s[0]!==a[0]||s[1]!==a[1]){i[t.xIndex].filter=s,r.focusLayer&&r.focusLayer.render(r.panels,!0);var u=v(r);!z&&u?(r.contextLayer&&r.contextLayer.render(r.panels,!0),z=!0):z&&!u&&(r.contextLayer&&r.contextLayer.render(r.panels,!0,!0),z=!1)}L=!1}function D(t){var r=t.parent,n=t.brush.extent(),i=n[0]===n[1],a=r.dimensions[t.xIndex].filter;if(!i&&t.ordinal&&(a[0]=yF(t.ordinalScale,a[0]),a[1]=yF(t.ordinalScale,a[1]),a[0]===a[1]&&(a[0]=Math.max(0,a[0]-.05),a[1]=Math.min(1,a[1]+.05)),e.select(this).transition().duration(150).call(t.brush.extent(a)),r.focusLayer.render(r.panels,!0)),r.pickLayer&&r.pickLayer.render(r.panels,!0),l=!0,s="ending",o&&o.filterChanged){var u=t.domainToUnitScale.invert,c=a.map(u);o.filterChanged(r.key,t.visibleIndex,c)}}}(0,a,o,n,{width:u.w,height:u.h,margin:{t:u.t,r:u.r,b:u.b,l:u.l}},{filterChanged:function(t,e,n){var i=l[t][e],a=i.constraintrange;a&&2===a.length||(a=i.constraintrange=[]),a[0]=n[0],a[1]=n[1],r.emit("plotly_restyle")},hover:function(t){r.emit("plotly_hover",t)},unhover:function(t){r.emit("plotly_unhover",t)},axesMoved:function(t,e){function n(t){return!("visible"in t)||t.visible}function i(t,e,r){var n=e.indexOf(r),i=t.indexOf(n);return-1===i&&(i+=e.length),i}var a=function(t){return function(r,n){return i(e,t,r)-i(e,t,n)}}(l[t].filter(n));s[t].sort(a),l[t].filter(function(t){return!n(t)}).sort(function(e){return l[t].indexOf(e)}).forEach(function(e){s[t].splice(s[t].indexOf(e),1),s[t].splice(l[t].indexOf(e),0,e)}),r.emit("plotly_restyle")}})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var AF={},kF=sa.getModuleCalcData;AF.name="parcoords",AF.plot=function(t){var e=kF(t.calcdata,"parcoords");e.length&&MF(t,e)},AF.clean=function(t,e,r,n){var i=n._has&&n._has("parcoords"),a=e._has&&e._has("parcoords");i&&!a&&(n._paperdiv.selectAll(".parcoords").remove(),n._glimages.selectAll("*").remove())},AF.toSVG=function(t){var r=t._fullLayout._glimages,n=e.select(t).selectAll(".svg-container");n.filter(function(t,e){return e===n.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");r.append("svg:image").attr({xmlns:$e.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})}),window.setTimeout(function(){e.selectAll("#filterBarPattern").attr("id","filterBarPattern")},60)};var TF=ZR.wrap;var SF=JR.maxDimensionCount,EF=qc.defaults;var CF={};CF.attributes=WR,CF.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,WR,r,n)}var a=function(t,e){var r,n,i,a=t.dimensions||[],o=e.dimensions=[],s=1/0;function l(t,e){return ne.coerce(r,n,WR.dimensions,t,e)}for(a.length>SF&&(ne.log("parcoords traces support up to "+SF+" dimensions at the moment"),a.splice(SF)),i=0;i0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}var WF={};WF.attributes=DF,WF.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,DF,r,n)}var a=ne.coerceFont,o=i("values"),s=i("labels");if(!Array.isArray(s)){if(!ne.isArrayOrTypedArray(o)||!o.length)return void(e.visible=!1);i("label0"),i("dlabel")}i("marker.line.width")&&i("marker.line.color"),i("marker.colors"),i("scalegroup");var l=i("text"),u=i("textinfo",Array.isArray(l)?"text+percent":"percent");if(i("hovertext"),u&&"none"!==u){var c=i("textposition"),h=Array.isArray(c)||"auto"===c,f=h||"inside"===c,p=h||"outside"===c;if(f||p){var d=a(i,"textfont",n.font);f&&a(i,"insidetextfont",d),p&&a(i,"outsidetextfont",d)}}jF(e,n,i),i("hole"),i("sort"),i("direction"),i("rotation"),i("pull")},WF.supplyLayoutDefaults=function(t,e){var r,n;r="hiddenlabels",ne.coerce(t,e,VF,r,n)},WF.layoutAttributes=VF,WF.calc=function(t,e){var n,i,a,o,l,u=e.values,c=FF(u)&&u.length,h=e.labels,f=e.marker.colors||[],p=[],d=t._fullLayout,g=d.colorway,v=d._piecolormap,m={},y=0,x=d.hiddenlabels||[];if(d._piecolorway||g===Oe.defaults||(d._piecolorway=NF(g)),e.dlabel)for(h=new Array(u.length),n=0;n")}}return p},WF.plot=function(t,r){var n=t._fullLayout;!function(t,e){var r,n,i,a,o,s,l,u,c,h=[];for(i=0;il&&(l=s.pull[a]);o.r=Math.min(r,n)/(2+2*l),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===h.indexOf(s.scalegroup)&&h.push(s.scalegroup)}for(a=0;ai.vTotal/2?1:0)}(r),i.each(function(){var i=e.select(this).selectAll("g.slice").data(r);i.enter().append("g").classed("slice",!0),i.exit().remove();var s=[[[],[]],[[],[]]],l=!1;i.each(function(r){if(r.hidden)e.select(this).selectAll("path,g").remove();else{r.pointNumber=r.i,r.curveNumber=o.index,s[r.pxmid[1]<0?0:1][r.pxmid[0]<0?0:1].push(r);var i=a.cx,u=a.cy,c=e.select(this),h=c.selectAll("path.surface").data([r]),f=!1,p=!1;if(h.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),c.select("path.textline").remove(),c.on("mouseover",function(){var s=t._fullLayout,l=t._fullData[o.index];if(!t._dragging&&!1!==s.hovermode){var c=l.hoverinfo;if(Array.isArray(c)&&(c=yo.castHoverinfo({hoverinfo:[Gd.castOption(c,r.pts)],_module:o._module},s,0)),"all"===c&&(c="label+text+value+percent+name"),"none"!==c&&"skip"!==c&&c){var h=HF(r,a),d=i+r.pxmid[0]*(1-h),g=u+r.pxmid[1]*(1-h),v=n.separators,m=[];if(-1!==c.indexOf("label")&&m.push(r.label),-1!==c.indexOf("text")){var y=Gd.castOption(l.hovertext||l.text,r.pts);y&&m.push(y)}-1!==c.indexOf("value")&&m.push(Gd.formatPieValue(r.v,v)),-1!==c.indexOf("percent")&&m.push(Gd.formatPiePercent(r.v/a.vTotal,v));var x=o.hoverlabel,b=x.font;yo.loneHover({x0:d-h*a.r,x1:d+h*a.r,y:g,text:m.join("
"),name:-1!==c.indexOf("name")?l.name:void 0,idealAlign:r.pxmid[0]<0?"left":"right",color:Gd.castOption(x.bgcolor,r.pts)||r.color,borderColor:Gd.castOption(x.bordercolor,r.pts),fontFamily:Gd.castOption(b.family,r.pts),fontSize:Gd.castOption(b.size,r.pts),fontColor:Gd.castOption(b.color,r.pts)},{container:s._hoverlayer.node(),outerContainer:s._paper.node(),gd:t}),f=!0}t.emit("plotly_hover",{points:[qF(r,l)],event:e.event}),p=!0}}).on("mouseout",function(n){var i=t._fullLayout,a=t._fullData[o.index];p&&(n.originalEvent=e.event,t.emit("plotly_unhover",{points:[qF(r,a)],event:e.event}),p=!1),f&&(yo.loneUnhover(i._hoverlayer.node()),f=!1)}).on("click",function(){var n=t._fullLayout,i=t._fullData[o.index];t._dragging||!1===n.hovermode||(t._hoverdata=[qF(r,i)],yo.click(t,e.event))}),o.pull){var d=+Gd.castOption(o.pull,r.pts)||0;d>0&&(i+=d*r.pxmid[0],u+=d*r.pxmid[1])}r.cxFinal=i,r.cyFinal=u;var g=o.hole;if(r.v===a.vTotal){var v="M"+(i+r.px0[0])+","+(u+r.px0[1])+_(r.px0,r.pxmid,!0,1)+_(r.pxmid,r.px0,!0,1)+"Z";g?h.attr("d","M"+(i+g*r.px0[0])+","+(u+g*r.px0[1])+_(r.px0,r.pxmid,!1,g)+_(r.pxmid,r.px0,!1,g)+"Z"+v):h.attr("d",v)}else{var m=_(r.px0,r.px1,!0,1);if(g){var y=1-g;h.attr("d","M"+(i+g*r.px1[0])+","+(u+g*r.px1[1])+_(r.px1,r.px0,!1,g)+"l"+y*r.px0[0]+","+y*r.px0[1]+m+"Z")}else h.attr("d","M"+i+","+u+"l"+r.px0[0]+","+r.px0[1]+m+"Z")}var x=Gd.castOption(o.textposition,r.pts),b=c.selectAll("g.slicetext").data(r.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var n=e.select(this).selectAll("text").data([0]);n.enter().append("text").attr("data-notex",1),n.exit().remove(),n.text(r.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Sr.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(er.convertToTspans,t);var s,c=Sr.bBox(n.node());"outside"===x?s=GF(c,r):(s=function(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),i=t.width/t.height,a=Math.PI*Math.min(e.v/r.vTotal,.5),o=1-r.trace.hole,s=HF(e,r),l={scale:s*r.r*2/n,rCenter:1-s,rotate:0};if(l.scale>=1)return l;var u=i+1/(2*Math.tan(a)),c=r.r*Math.min(1/(Math.sqrt(u*u+.5)+u),o/(Math.sqrt(i*i+o/2)+i)),h={scale:2*c/t.height,rCenter:Math.cos(c/r.r)-c*i/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},f=1/i,p=f+1/(2*Math.tan(a)),d=r.r*Math.min(1/(Math.sqrt(p*p+.5)+p),o/(Math.sqrt(f*f+o/2)+f)),g={scale:2*d/t.width,rCenter:Math.cos(d/r.r)-d/i/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},v=g.scale>h.scale?g:h;return l.scale<1&&v.scale>l.scale?v:l}(c,r,a),"auto"===x&&s.scale<1&&(n.call(Sr.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(c=Sr.bBox(n.node())),s=GF(c,r)));var h=i+r.pxmid[0]*s.rCenter+(s.x||0),f=u+r.pxmid[1]*s.rCenter+(s.y||0);s.outside&&(r.yLabelMin=f-c.height/2,r.yLabelMid=f,r.yLabelMax=f+c.height/2,r.labelExtraX=0,r.labelExtraY=0,l=!0),n.attr("transform","translate("+h+","+f+")"+(s.scale<1?"scale("+s.scale+")":"")+(s.rotate?"rotate("+s.rotate+")":"")+"translate("+-(c.left+c.right)/2+","+-(c.top+c.bottom)/2+")")})}function _(t,e,n,i){return"a"+i*a.r+","+i*a.r+" 0 "+r.largeArc+(n?" 1 ":" 0 ")+i*(e[0]-t[0])+","+i*(e[1]-t[1])}}),l&&function(t,e){var r,n,i,a,o,s,l,u,c,h,f,p,d;function g(t,e){return t.pxmid[1]-e.pxmid[1]}function v(t,e){return e.pxmid[1]-t.pxmid[1]}function m(t,r){r||(r={});var i,u,c,f,p,d,g=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),v=n?t.yLabelMin:t.yLabelMax,m=n?t.yLabelMax:t.yLabelMin,y=t.cyFinal+o(t.px0[1],t.px1[1]),x=g-v;if(x*l>0&&(t.labelExtraY=x),Array.isArray(e.pull))for(u=0;u=(Gd.castOption(e.pull,c.pts)||0)||((t.pxmid[1]-c.pxmid[1])*l>0?(f=c.cyFinal+o(c.px0[1],c.px1[1]),(x=f-v-t.labelExtraY)*l>0&&(t.labelExtraY+=x)):(m+t.labelExtraY-y)*l>0&&(i=3*s*Math.abs(u-h.indexOf(t)),p=c.cxFinal+a(c.px0[0],c.px1[0]),(d=p+i-(t.cxFinal+t.pxmid[0])-t.labelExtraX)*s>0&&(t.labelExtraX+=d)))}for(n=0;n<2;n++)for(i=n?g:v,o=n?Math.max:Math.min,l=n?1:-1,r=0;r<2;r++){for(a=r?Math.max:Math.min,s=r?1:-1,(u=t[n][r]).sort(i),c=t[1-n][r],h=c.concat(u),p=[],f=0;fMath.abs(u)?a+="l"+u*t.pxmid[0]/t.pxmid[1]+","+u+"H"+(i+t.labelExtraX+s):a+="l"+t.labelExtraX+","+l+"v"+(u-l)+"h"+s}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+s;r.append("path").classed("textline",!0).call(Oe.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){i.selectAll("tspan").each(function(){var t=e.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},WF.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var r=t[0].trace,n=e.select(this);n.style({opacity:r.opacity}),n.selectAll("path.surface").each(function(t){e.select(this).call(Yd,t,r)})})},WF.styleOne=Yd,WF.moduleType="trace",WF.name="pie",WF.basePlotModule=OF,WF.categories=["pie","showLegend"],WF.meta={};var YF=WF,XF={x:Zr.x,y:Zr.y,xy:{valType:"data_array",editType:"calc"},indices:{valType:"data_array",editType:"calc"},xbounds:{valType:"data_array",editType:"calc"},ybounds:{valType:"data_array",editType:"calc"},text:Zr.text,marker:{color:{valType:"color",arrayOk:!1,editType:"calc"},opacity:{valType:"number",min:0,max:1,dflt:1,arrayOk:!1,editType:"calc"},blend:{valType:"boolean",dflt:null,editType:"calc"},sizemin:{valType:"number",min:.1,max:2,dflt:.5,editType:"calc"},sizemax:{valType:"number",min:.1,dflt:20,editType:"calc"},border:{color:{valType:"color",arrayOk:!1,editType:"calc"},arearatio:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},editType:"calc"},editType:"calc"}},ZF={};ZF.pointVertex=E_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]),ZF.pointFragment=E_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]),ZF.pickVertex=E_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]),ZF.pickFragment=E_(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]);var JF=function(t,e){var r=t.gl,n=S_(r),i=S_(r),a=Bw(r,ZF.pointVertex,ZF.pointFragment),o=Bw(r,ZF.pickVertex,ZF.pickFragment),s=new KF(t,n,i,a,o);return s.update(e),t.addObject(s),s};function KF(t,e,r,n,i){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.shader=n,this.pickShader=i,this.sizeMin=.5,this.sizeMinCap=2,this.sizeMax=20,this.areaRatio=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.blend=!1,this.pickOffset=0,this.points=null}var QF=KF.prototype;QF.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.plot.removeObject(this)},QF.update=function(t){var e;function r(e,r){return e in t?t[e]:r}t=t||{},this.sizeMin=r("sizeMin",.5),this.sizeMax=r("sizeMax",20),this.color=r("color",[1,0,0,1]).slice(),this.areaRatio=r("areaRatio",1),this.borderColor=r("borderColor",[0,0,0,1]).slice(),this.blend=r("blend",!1);var n=t.positions.length>>>1,i=t.positions instanceof Float32Array,a=t.idToIndex instanceof Int32Array&&t.idToIndex.length>=n,o=t.positions,s=i?o:__.mallocFloat32(o.length),l=a?t.idToIndex:__.mallocInt32(n);if(i||s.set(o),!a)for(s.set(o),e=0;e>>1;for(r=0;r=e[0]&&a<=e[2]&&o>=e[1]&&o<=e[3]&&n++}return n}(this.points,o),c=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(u,.33333)));t[0]=2/s,t[4]=2/l,t[6]=-2*o[0]/s-1,t[7]=-2*o[1]/l-1,this.offsetBuffer.bind(),i.bind(),i.attributes.position.pointer(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointCloud=c<5,i.uniforms.pointSize=c,i.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio))),n&&(e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,this.pickBuffer.bind(),i.attributes.pickId.pointer(a.UNSIGNED_BYTE),i.uniforms.pickOffset=e,this.pickOffset=r);var h=a.getParameter(a.BLEND),f=a.getParameter(a.DITHER);return h&&!this.blend&&a.disable(a.BLEND),f&&a.disable(a.DITHER),a.drawArrays(a.POINTS,0,this.pointCount),h&&!this.blend&&a.enable(a.BLEND),f&&a.enable(a.DITHER),r+this.pointCount}}(),QF.draw=QF.unifiedDraw,QF.drawPick=QF.unifiedDraw,QF.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(r=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}};var $F=jn;function tB(t,e){this.scene=t,this.uid=e,this.type="pointcloud",this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=new Int32Array(0),this.bounds=[0,0,0,0],this.pointcloudOptions={positions:new Float32Array(0),idToIndex:this.idToIndex,sizemin:.5,sizemax:12,color:[0,0,0,1],areaRatio:1,borderColor:[0,0,0,1]},this.pointcloud=JF(t.glplot,this.pointcloudOptions),this.pointcloud._trace=this}var eB=tB.prototype;eB.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:this.pickXYData?[this.pickXYData[2*e],this.pickXYData[2*e+1]]:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:this.color,name:this.name,pointIndex:e,hoverinfo:this.hoverinfo}},eB.update=function(t){this.index=t.index,this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-1/0,-1/0],this.updateFast(t),this.color=mx(t,{})},eB.updateFast=function(t){var e,r,n,i,a,o,s=this.xData=this.pickXData=t.x,l=this.yData=this.pickYData=t.y,u=this.pickXYData=t.xy,c=t.xbounds&&t.ybounds,h=t.indices,f=this.bounds;if(u){if(n=u,e=u.length>>>1,c)f[0]=t.xbounds[0],f[2]=t.xbounds[1],f[1]=t.ybounds[0],f[3]=t.ybounds[1];else for(o=0;of[2]&&(f[2]=i),af[3]&&(f[3]=a);if(h)r=h;else for(r=new Int32Array(e),o=0;of[2]&&(f[2]=i),af[3]&&(f[3]=a);this.idToIndex=r,this.pointcloudOptions.idToIndex=r,this.pointcloudOptions.positions=n;var p=WC(t.marker.color),d=WC(t.marker.border.color),g=t.opacity*t.marker.opacity;p[3]*=g,this.pointcloudOptions.color=p;var v=t.marker.blend;if(null===v){v=s.length<100||l.length<100}this.pointcloudOptions.blend=v,d[3]*=g,this.pointcloudOptions.borderColor=d;var m=t.marker.sizemin,y=Math.max(t.marker.sizemax,t.marker.sizemin);this.pointcloudOptions.sizeMin=m,this.pointcloudOptions.sizeMax=y,this.pointcloudOptions.areaRatio=t.marker.border.arearatio,this.pointcloud.update(this.pointcloudOptions),this.expandAxesFast(f,y/2)},eB.expandAxesFast=function(t,e){var r=e||.5;$F(this.scene.xaxis,[t[0],t[2]],{ppad:r}),$F(this.scene.yaxis,[t[1],t[3]],{ppad:r})},eB.dispose=function(){this.pointcloud.dispose()};var rB=function(t,e){var r=new tB(t,e.uid);return r.update(e),r},nB=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return dh(r,e),ex(e),r},iB={};iB.attributes=XF,iB.supplyDefaults=function(t,e,r){function n(r,n){return ne.coerce(t,e,XF,r,n)}n("x"),n("y"),n("xbounds"),n("ybounds"),t.xy&&t.xy instanceof Float32Array&&(e.xy=t.xy),t.indices&&t.indices instanceof Int32Array&&(e.indices=t.indices),n("text"),n("marker.color",r),n("marker.opacity"),n("marker.blend"),n("marker.sizemin"),n("marker.sizemax"),n("marker.border.color",r),n("marker.border.arearatio")},iB.calc=nB,iB.plot=rB,iB.moduleType="trace",iB.name="pointcloud",iB.basePlotModule=sL,iB.categories=["gl","gl2d","showLegend"],iB.meta={};var aB=iB,oB=qc.attributes,sB=m.extendFlat,lB=(0,ye.overrideAll)({hoverinfo:sB({},E.hoverinfo,{flags:["label","text","value","percent","name"]}),hoverlabel:S.hoverlabel,domain:oB({name:"sankey",trace:!0}),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:T({}),node:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:C.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:.5,arrayOk:!0}},pad:{valType:"number",arrayOk:!1,min:0,dflt:20},thickness:{valType:"number",arrayOk:!1,min:1,dflt:20}},link:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:C.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:0,arrayOk:!0}},source:{valType:"data_array",dflt:[]},target:{valType:"data_array",dflt:[]},value:{valType:"data_array",dflt:[]}}},"calc","nested"),uB={nodeTextOffsetHorizontal:4,nodeTextOffsetVertical:3,nodePadAcross:10,sankeyIterations:50,forceIterations:5,forceTicksPerFrame:10,duration:500,ease:"cubic-in-out",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"}},cB={exports:{}};!function(t,e){"object"==typeof cB.exports?e(cB.exports):e(t.d3=t.d3||{})}(this,function(t){"use strict";var e=function(t,e){return te?1:t>=e?0:NaN},r=function(t){var r;return 1===t.length&&(r=t,t=function(t,n){return e(r(t),n)}),{left:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}};var n=r(e),i=n.right,a=n.left;function o(t,e){return[t,e]}var s=function(t){return null===t?NaN:+t},l=function(t,e){var r,n,i=t.length,a=0,o=-1,l=0,u=0;if(null==e)for(;++o1)return u/(a-1)},u=function(t,e){var r=l(t,e);return r?Math.sqrt(r):r},c=function(t,e){var r,n,i,a=t.length,o=-1;if(null==e){for(;++o=r)for(n=i=r;++or&&(n=r),i=r)for(n=i=r;++or&&(n=r),i=0?(a>=m?10:a>=y?5:a>=x?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=m?10:a>=y?5:a>=x?2:1)}function _(t,e,r){var n=Math.abs(e-t)/Math.max(0,r),i=Math.pow(10,Math.floor(Math.log(n)/Math.LN10)),a=n/i;return a>=m?i*=10:a>=y?i*=5:a>=x&&(i*=2),e=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,a=Math.floor(i),o=+r(t[a],a,t);return o+(+r(t[a+1],a+1,t)-o)*(i-a)}},A=function(t,e){var r,n,i=t.length,a=-1;if(null==e){for(;++a=r)for(n=r;++ar&&(n=r)}else for(;++a=r)for(n=r;++ar&&(n=r);return n},k=function(t){if(!(i=t.length))return[];for(var e=-1,r=A(t,T),n=new Array(r);++et?1:e>=t?0:NaN},t.deviation=u,t.extent=c,t.histogram=function(){var t=g,e=c,r=w;function n(n){var a,o,s=n.length,l=new Array(s);for(a=0;ah;)f.pop(),--p;var d,g=new Array(p+1);for(a=0;a<=p;++a)(d=g[a]=[]).x0=a>0?f[a-1]:c,d.x1=a=r)for(n=r;++an&&(n=r)}else for(;++a=r)for(n=r;++an&&(n=r);return n},t.mean=function(t,e){var r,n=t.length,i=n,a=-1,o=0;if(null==e)for(;++a=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r},t.min=A,t.pairs=function(t,e){null==e&&(e=o);for(var r=0,n=t.length-1,i=t[0],a=new Array(n<0?0:n);r0)return[t];if((n=e0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++s=l.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var s,u,h,f=-1,p=n.length,d=l[i++],g=r(),v=a();++fl.length)return r;var i,a=u[n-1];return null!=e&&n>=l.length?i=r.entries():(i=[],r.each(function(e,r){i.push({key:r,values:t(e,n)})})),null!=a?i.sort(function(t,e){return a(t.key,e.key)}):i}(c(t,0,a,o),0)},key:function(t){return l.push(t),s},sortKeys:function(t){return u[l.length-1]=t,s},sortValues:function(e){return t=e,s},rollup:function(t){return e=t,s}}},t.set=u,t.map=r,t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},Object.defineProperty(t,"__esModule",{value:!0})}),hB=hB.exports;var fB={exports:{}};!function(t,e){"object"==typeof fB.exports?e(fB.exports):e(t.d3=t.d3||{})}(this,function(t){"use strict";var e=function(t,e,r){t.prototype=e.prototype=r,r.constructor=t};function r(t,e){var r=Object.create(t.prototype);for(var n in e)r[n]=e[n];return r}function n(){}var i="\\s*([+-]?\\d+)\\s*",a="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",o="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",s=/^#([0-9a-f]{3})$/,l=/^#([0-9a-f]{6})$/,u=new RegExp("^rgb\\("+[i,i,i]+"\\)$"),c=new RegExp("^rgb\\("+[o,o,o]+"\\)$"),h=new RegExp("^rgba\\("+[i,i,i,a]+"\\)$"),f=new RegExp("^rgba\\("+[o,o,o,a]+"\\)$"),p=new RegExp("^hsl\\("+[a,o,o]+"\\)$"),d=new RegExp("^hsla\\("+[a,o,o,a]+"\\)$"),g={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};function v(t){var e;return t=(t+"").trim().toLowerCase(),(e=s.exec(t))?new _((e=parseInt(e[1],16))>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):(e=l.exec(t))?m(parseInt(e[1],16)):(e=u.exec(t))?new _(e[1],e[2],e[3],1):(e=c.exec(t))?new _(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=h.exec(t))?y(e[1],e[2],e[3],e[4]):(e=f.exec(t))?y(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=p.exec(t))?w(e[1],e[2]/100,e[3]/100,1):(e=d.exec(t))?w(e[1],e[2]/100,e[3]/100,e[4]):g.hasOwnProperty(t)?m(g[t]):"transparent"===t?new _(NaN,NaN,NaN,0):null}function m(t){return new _(t>>16&255,t>>8&255,255&t,1)}function y(t,e,r,n){return n<=0&&(t=e=r=NaN),new _(t,e,r,n)}function x(t){return t instanceof n||(t=v(t)),t?new _((t=t.rgb()).r,t.g,t.b,t.opacity):new _}function b(t,e,r,n){return 1===arguments.length?x(t):new _(t,e,r,null==n?1:n)}function _(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}function w(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new A(t,e,r,n)}function M(t,e,r,i){return 1===arguments.length?function(t){if(t instanceof A)return new A(t.h,t.s,t.l,t.opacity);if(t instanceof n||(t=v(t)),!t)return new A;if(t instanceof A)return t;var e=(t=t.rgb()).r/255,r=t.g/255,i=t.b/255,a=Math.min(e,r,i),o=Math.max(e,r,i),s=NaN,l=o-a,u=(o+a)/2;return l?(s=e===o?(r-i)/l+6*(r0&&u<1?0:s,new A(s,l,u,t.opacity)}(t):new A(t,e,r,null==i?1:i)}function A(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}function k(t,e,r){return 255*(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)}e(n,v,{displayable:function(){return this.rgb().displayable()},toString:function(){return this.rgb()+""}}),e(_,b,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return 0<=this.r&&this.r<=255&&0<=this.g&&this.g<=255&&0<=this.b&&this.b<=255&&0<=this.opacity&&this.opacity<=1},toString:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}})),e(A,M,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new A(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new A(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new _(k(t>=240?t-240:t+120,i,n),k(t,i,n),k(t<120?t+240:t-120,i,n),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1}}));var T=Math.PI/180,S=180/Math.PI,E=.95047,C=1,L=1.08883,z=4/29,P=6/29,I=3*P*P,D=P*P*P;function O(t){if(t instanceof F)return new F(t.l,t.a,t.b,t.opacity);if(t instanceof q){var e=t.h*T;return new F(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}t instanceof _||(t=x(t));var r=V(t.r),n=V(t.g),i=V(t.b),a=B((.4124564*r+.3575761*n+.1804375*i)/E),o=B((.2126729*r+.7151522*n+.072175*i)/C);return new F(116*o-16,500*(a-o),200*(o-B((.0193339*r+.119192*n+.9503041*i)/L)),t.opacity)}function R(t,e,r,n){return 1===arguments.length?O(t):new F(t,e,r,null==n?1:n)}function F(t,e,r,n){this.l=+t,this.a=+e,this.b=+r,this.opacity=+n}function B(t){return t>D?Math.pow(t,1/3):t/I+z}function N(t){return t>P?t*t*t:I*(t-z)}function j(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function V(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function U(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof q)return new q(t.h,t.c,t.l,t.opacity);t instanceof F||(t=O(t));var e=Math.atan2(t.b,t.a)*S;return new q(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}(t):new q(t,e,r,null==n?1:n)}function q(t,e,r,n){this.h=+t,this.c=+e,this.l=+r,this.opacity=+n}e(F,R,r(n,{brighter:function(t){return new F(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new F(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return t=C*N(t),new _(j(3.2404542*(e=E*N(e))-1.5371385*t-.4985314*(r=L*N(r))),j(-.969266*e+1.8760108*t+.041556*r),j(.0556434*e-.2040259*t+1.0572252*r),this.opacity)}})),e(q,U,r(n,{brighter:function(t){return new q(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new q(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return O(this).rgb()}}));var H=-.14861,G=1.78277,W=-.29227,Y=-.90649,X=1.97294,Z=X*Y,J=X*G,K=G*W-Y*H;function Q(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof $)return new $(t.h,t.s,t.l,t.opacity);t instanceof _||(t=x(t));var e=t.r/255,r=t.g/255,n=t.b/255,i=(K*n+Z*e-J*r)/(K+Z-J),a=n-i,o=(X*(r-i)-W*a)/Y,s=Math.sqrt(o*o+a*a)/(X*i*(1-i)),l=s?Math.atan2(o,a)*S-120:NaN;return new $(l<0?l+360:l,s,i,t.opacity)}(t):new $(t,e,r,null==n?1:n)}function $(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}e($,Q,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new $(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new $(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*T,e=+this.l,r=isNaN(this.s)?0:this.s*e*(1-e),n=Math.cos(t),i=Math.sin(t);return new _(255*(e+r*(H*n+G*i)),255*(e+r*(W*n+Y*i)),255*(e+r*(X*n)),this.opacity)}})),t.color=v,t.rgb=b,t.hsl=M,t.lab=R,t.hcl=U,t.cubehelix=Q,Object.defineProperty(t,"__esModule",{value:!0})}),fB=fB.exports;var pB={exports:{}};!function(t,e){"object"==typeof pB.exports?e(pB.exports,fB):e(t.d3=t.d3||{},t.d3)}(this,function(t,e){"use strict";function r(t,e,r,n,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*r+(1+3*t+3*a-3*o)*n+o*i)/6}var n=function(t){var e=t.length-1;return function(n){var i=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),a=t[i],o=t[i+1],s=i>0?t[i-1]:2*a-o,l=i180||r<-180?r-360*Math.round(r/360):r):a(isNaN(t)?e:t)}function l(t){return 1==(t=+t)?u:function(e,r){return r-e?function(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}(e,r,t):a(isNaN(e)?r:e)}}function u(t,e){var r=e-t;return r?o(t,r):a(isNaN(t)?e:t)}var c=function t(r){var n=l(r);function i(t,r){var i=n((t=e.rgb(t)).r,(r=e.rgb(r)).r),a=n(t.g,r.g),o=n(t.b,r.b),s=u(t.opacity,r.opacity);return function(e){return t.r=i(e),t.g=a(e),t.b=o(e),t.opacity=s(e),t+""}}return i.gamma=t,i}(1);function h(t){return function(r){var n,i,a=r.length,o=new Array(a),s=new Array(a),l=new Array(a);for(n=0;na&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:v(r,n)})),a=x.lastIndex;return a180?e+=360:e-t>180&&(t+=360),a.push({i:r.push(i(r)+"rotate(",null,n)-2,x:v(t,e)})):e&&r.push(i(r)+"rotate("+e+n)}(a.rotate,o.rotate,s,l),function(t,e,r,a){t!==e?a.push({i:r.push(i(r)+"skewX(",null,n)-2,x:v(t,e)}):e&&r.push(i(r)+"skewX("+e+n)}(a.skewX,o.skewX,s,l),function(t,e,r,n,a,o){if(t!==r||e!==n){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:v(t,r)},{i:s-2,x:v(e,n)})}else 1===r&&1===n||a.push(i(a)+"scale("+r+","+n+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,l),a=o=null,function(t){for(var e,r=-1,n=l.length;++r0;--t)p(u*=.99),d(),f(u),d();function f(t){function r(t){return c(t.source)*t.value}i.forEach(function(n){n.forEach(function(n){if(n.targetLinks.length){var i=e.sum(n.targetLinks,r)/e.sum(n.targetLinks,h);n.y+=(i-c(n))*t}})})}function p(t){function r(t){return c(t.target)*t.value}i.slice().reverse().forEach(function(n){n.forEach(function(n){if(n.sourceLinks.length){var i=e.sum(n.sourceLinks,r)/e.sum(n.sourceLinks,h);n.y+=(i-c(n))*t}})})}function d(){i.forEach(function(t){var e,r,n,i=0,s=t.length;for(t.sort(g),n=0;n0&&(e.y+=r),i=e.y+e.dy+a;if((r=i-a-o[1])>0)for(i=e.y-=r,n=s-2;n>=0;--n)e=t[n],(r=e.y+e.dy+a-i)>0&&(e.y-=r),i=e.y})}function g(t,e){return t.y-e.y}}(n),u(),t},t.relayout=function(){return u(),t},t.link=function(){var t=.5;function e(e){var r=e.source.x+e.source.dx,i=e.target.x,a=n.interpolateNumber(r,i),o=a(t),s=a(1-t),l=e.source.y+e.sy,u=l+e.dy,c=e.target.y+e.ty,h=c+e.dy;return"M"+r+","+l+"C"+o+","+l+" "+s+","+c+" "+i+","+c+"L"+i+","+h+"C"+s+","+h+" "+o+","+u+" "+r+","+u+"Z"}return e.curvature=function(r){return arguments.length?(t=+r,e):t},e},t},Object.defineProperty(t,"__esModule",{value:!0})}),dB=dB.exports;var gB={exports:{}};!function(t,e){"object"==typeof gB.exports?e(gB.exports):e(t.d3=t.d3||{})}(this,function(t){"use strict";var e={value:function(){}};function r(){for(var t,e=0,r=arguments.length,i={};e=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}})),l=-1,u=s.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++l0)for(var r,n,i=new Array(r),a=0;a=(a=(g+m)/2))?g=a:m=a,(c=r>=(o=(v+y)/2))?v=o:y=o,i=p,!(p=p[h=c<<1|u]))return i[h]=d,t;if(s=+t._x.call(null,p.data),l=+t._y.call(null,p.data),e===s&&r===l)return d.next=p,i?i[h]=d:t._root=d,t;do{i=i?i[h]=new Array(4):t._root=new Array(4),(u=e>=(a=(g+m)/2))?g=a:m=a,(c=r>=(o=(v+y)/2))?v=o:y=o}while((h=c<<1|u)==(f=(l>=o)<<1|s>=a));return i[f]=p,i[h]=d,t}var r=function(t,e,r,n,i){this.node=t,this.x0=e,this.y0=r,this.x1=n,this.y1=i};function n(t){return t[0]}function i(t){return t[1]}function a(t,e,r){var a=new o(null==e?n:e,null==r?i:r,NaN,NaN,NaN,NaN);return null==t?a:a.addAll(t)}function o(t,e,r,n,i,a){this._x=t,this._y=e,this._x0=r,this._y0=n,this._x1=i,this._y1=a,this._root=void 0}function s(t){for(var e={data:t.data},r=e;t=t.next;)r=r.next={data:t.data};return e}var l=a.prototype=o.prototype;l.copy=function(){var t,e,r=new o(this._x,this._y,this._x0,this._y0,this._x1,this._y1),n=this._root;if(!n)return r;if(!n.length)return r._root=s(n),r;for(t=[{source:n,target:r._root=new Array(4)}];n=t.pop();)for(var i=0;i<4;++i)(e=n.source[i])&&(e.length?t.push({source:e,target:n.target[i]=new Array(4)}):n.target[i]=s(e));return r},l.add=function(t){var r=+this._x.call(null,t),n=+this._y.call(null,t);return e(this.cover(r,n),r,n,t)},l.addAll=function(t){var r,n,i,a,o=t.length,s=new Array(o),l=new Array(o),u=1/0,c=1/0,h=-1/0,f=-1/0;for(n=0;nh&&(h=i),af&&(f=a));for(ht||t>i||n>e||e>a))return this;var o,s,l=i-r,u=this._root;switch(s=(e<(n+a)/2)<<1|t<(r+i)/2){case 0:do{(o=new Array(4))[s]=u,u=o}while(a=n+(l*=2),t>(i=r+l)||e>a);break;case 1:do{(o=new Array(4))[s]=u,u=o}while(a=n+(l*=2),(r=i-l)>t||e>a);break;case 2:do{(o=new Array(4))[s]=u,u=o}while(n=a-(l*=2),t>(i=r+l)||n>e);break;case 3:do{(o=new Array(4))[s]=u,u=o}while(n=a-(l*=2),(r=i-l)>t||n>e)}this._root&&this._root.length&&(this._root=u)}return this._x0=r,this._y0=n,this._x1=i,this._y1=a,this},l.data=function(){var t=[];return this.visit(function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)}),t},l.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},l.find=function(t,e,n){var i,a,o,s,l,u,c,h=this._x0,f=this._y0,p=this._x1,d=this._y1,g=[],v=this._root;for(v&&g.push(new r(v,h,f,p,d)),null==n?n=1/0:(h=t-n,f=e-n,p=t+n,d=e+n,n*=n);u=g.pop();)if(!(!(v=u.node)||(a=u.x0)>p||(o=u.y0)>d||(s=u.x1)=y)<<1|t>=m)&&(u=g[g.length-1],g[g.length-1]=g[g.length-1-c],g[g.length-1-c]=u)}else{var x=t-+this._x.call(null,v.data),b=e-+this._y.call(null,v.data),_=x*x+b*b;if(_=(s=(d+v)/2))?d=s:v=s,(c=o>=(l=(g+m)/2))?g=l:m=l,e=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(e[h+1&3]||e[h+2&3]||e[h+3&3])&&(r=e,f=h)}for(;p.data!==t;)if(n=p,!(p=p.next))return this;return(i=p.next)&&delete p.next,n?(i?n.next=i:delete n.next,this):e?(i?e[h]=i:delete e[h],(p=e[0]||e[1]||e[2]||e[3])&&p===(e[3]||e[2]||e[1]||e[0])&&!p.length&&(r?r[f]=p:this._root=p),this):(this._root=i,this)},l.removeAll=function(t){for(var e=0,r=t.length;e=0&&r._call.call(null,t),r=r._next;--n}function m(){l=(s=c.now())+u,n=i=0;try{v()}finally{n=0,function(){var t,n,i=e,a=1/0;for(;i;)i._call?(a>i._time&&(a=i._time),t=i,i=i._next):(n=i._next,i._next=null,i=t?t._next=n:e=n);r=t,x(a)}(),l=0}}function y(){var t=c.now(),e=t-s;e>o&&(u-=e,s=t)}function x(t){n||(i&&(i=clearTimeout(i)),t-l>24?(t<1/0&&(i=setTimeout(m,t-c.now()-u)),a&&(a=clearInterval(a))):(a||(s=c.now(),a=setInterval(y,o)),n=1,h(m)))}d.prototype=g.prototype={constructor:d,restart:function(t,n,i){if("function"!=typeof t)throw new TypeError("callback is not a function");i=(null==i?f():+i)+(null==n?0:+n),this._next||r===this||(r?r._next=this:e=this,r=this),this._call=t,this._time=i,x()},stop:function(){this._call&&(this._call=null,this._time=1/0,x())}};t.now=f,t.timer=g,t.timerFlush=v,t.timeout=function(t,e,r){var n=new d;return e=null==e?0:+e,n.restart(function(r){n.stop(),t(r+e)},e,r),n},t.interval=function(t,e,r){var n=new d,i=e;return null==e?(n.restart(t,e,r),n):(e=+e,r=null==r?f():+r,n.restart(function a(o){o+=i,n.restart(a,i+=e,r),t(o)},e,r),n)},Object.defineProperty(t,"__esModule",{value:!0})}),mB=mB.exports;var yB={exports:{}};!function(t,e){"object"==typeof yB.exports?e(yB.exports,vB,hB,gB,mB):e(t.d3=t.d3||{},t.d3,t.d3,t.d3,t.d3)}(this,function(t,e,r,n,i){"use strict";var a=function(t){return function(){return t}},o=function(){return 1e-6*(Math.random()-.5)};function s(t){return t.x+t.vx}function l(t){return t.y+t.vy}function u(t){return t.index}function c(t,e){var r=t.get(e);if(!r)throw new Error("missing: "+e);return r}function h(t){return t.x}function f(t){return t.y}var p=10,d=Math.PI*(3-Math.sqrt(5));t.forceCenter=function(t,e){var r;function n(){var n,i,a=r.length,o=0,s=0;for(n=0;nf+u||np+u||ac.index){var h=f-s.x-s.vx,v=p-s.y-s.vy,m=h*h+v*v;mt.r&&(t.r=t[e].r)}function f(){if(r){var e,i,a=r.length;for(n=new Array(a),e=0;e=u)){(t.data!==r||t.next)&&(0===h&&(d+=(h=o())*h),0===f&&(d+=(f=o())*f),d1?(null==r?c.remove(t):c.set(t,y(r)),e):c.get(t)},find:function(e,r,n){var i,a,o,s,l,u=0,c=t.length;for(null==n?n=1/0:n*=n,u=0;u1?(f.on(t,r),e):f.on(t)}}},t.forceX=function(t){var e,r,n,i=a(.1);function o(t){for(var i,a=0,o=e.length;a1||t.linkLineWidth>0}function PB(t){return"translate("+t.translateX+","+t.translateY+")"+(t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)")}function IB(t){return"translate("+(t.horizontal?0:t.labelY)+" "+(t.horizontal?t.labelY:0)+")"}function DB(t){return e.svg.line()([[t.horizontal?t.left?-t.sizeAcross:t.visibleWidth+uB.nodeTextOffsetHorizontal:uB.nodeTextOffsetHorizontal,0],[t.horizontal?t.left?-uB.nodeTextOffsetHorizontal:t.sizeAcross:t.visibleHeight-uB.nodeTextOffsetHorizontal,0]])}function OB(t){return t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)"}function RB(t){return t.horizontal?"scale(1 1)":"scale(-1 1)"}function FB(t){return t.darkBackground&&!t.horizontal?"rgb(255,255,255)":"rgb(0,0,0)"}function BB(t){return t.horizontal&&t.left?"100%":"0%"}function NB(t,e,r){t.on(".basic",null).on("mouseover.basic",function(t){t.interactionState.dragInProgress||(r.hover(this,t,e),t.interactionState.hovered=[this,t])}).on("mousemove.basic",function(t){t.interactionState.dragInProgress||(r.follow(this,t),t.interactionState.hovered=[this,t])}).on("mouseout.basic",function(t){t.interactionState.dragInProgress||(r.unhover(this,t,e),t.interactionState.hovered=!1)}).on("click.basic",function(t){t.interactionState.hovered&&(r.unhover(this,t,e),t.interactionState.hovered=!1),t.interactionState.dragInProgress||r.select(this,t,e)})}function jB(t,r,n){var i=e.behavior.drag().origin(function(t){return t.node}).on("dragstart",function(e){if("fixed"!==e.arrangement&&(ne.raiseToTop(this),e.interactionState.dragInProgress=e.node,MB(e.node),e.interactionState.hovered&&(n.nodeEvents.unhover.apply(0,e.interactionState.hovered),e.interactionState.hovered=!1),"snap"===e.arrangement)){var i=e.traceId+"|"+Math.floor(e.node.originalX);e.forceLayouts[i]?e.forceLayouts[i].alpha(1):function(t,e,r){var n=r.sankey.nodes().filter(function(t){return t.originalX===r.node.originalX});r.forceLayouts[e]=yB.forceSimulation(n).alphaDecay(0).force("collide",yB.forceCollide().radius(function(t){return t.dy/2+r.nodePad/2}).strength(1).iterations(uB.forceIterations)).force("constrain",function(t,e,r,n){return function(){for(var t=0,i=0;i0&&n.forceLayouts[e].alpha(0)}}(0,e,n,r)).stop()}(0,i,e),function(t,e,r,n){window.requestAnimationFrame(function i(){for(var a=0;a0&&window.requestAnimationFrame(i)})}(t,r,e,i)}}).on("drag",function(n){if("fixed"!==n.arrangement){var i=e.event.x,a=e.event.y;"snap"===n.arrangement?(n.node.x=i,n.node.y=a):("freeform"===n.arrangement&&(n.node.x=i),n.node.y=Math.max(n.node.dy/2,Math.min(n.size-n.node.dy/2,a))),MB(n.node),"snap"!==n.arrangement&&(n.sankey.relayout(),CB(t.filter(AB(n)),r))}}).on("dragend",function(t){t.interactionState.dragInProgress=!1});t.on(".drag",null).call(i)}var VB=function(t,e,r,n){var i=t.selectAll("."+uB.cn.sankey).data(e.filter(function(t){return wB(t).trace.visible}).map(function(t,e,r){for(var n,i=wB(e).trace,a=i.domain,o=i.node,s=i.link,l=i.arrangement,u="h"===i.orientation,c=i.node.pad,h=i.node.thickness,f=i.node.line.color,p=i.node.line.width,d=i.link.line.color,g=i.link.line.width,v=i.valueformat,m=i.valuesuffix,y=i.textfont,x=t.width*(a.x[1]-a.x[0]),b=t.height*(a.y[1]-a.y[0]),_=o.label.map(function(t,e){return{pointNumber:e,label:t,color:ne.isArrayOrTypedArray(o.color)?o.color[e]:o.color}}),w=s.value.map(function(t,e){return{pointNumber:e,label:s.label[e],color:ne.isArrayOrTypedArray(s.color)?s.color[e]:s.color,source:s.source[e],target:s.target[e],value:t}}),M=xB().size(u?[x,b]:[b,x]).nodeWidth(h).nodePadding(c).nodes(_).links(w).layout(uB.sankeyIterations),A=M.nodes(),k=0;k5?t.node.label:""}).attr("text-anchor",function(t){return t.horizontal&&t.left?"end":"start"}),g.transition().ease(uB.ease).duration(uB.duration).attr("startOffset",BB).style("fill",FB)},UB=uB.cn,qB=ne._;function HB(t){return""!==t}function GB(t,e){return t.filter(function(t){return t.key===e.traceId})}function WB(t,r){e.select(t).select("path").style("fill-opacity",r),e.select(t).select("rect").style("fill-opacity",r)}function YB(t){e.select(t).select("text.name").style("fill","black")}function XB(t){return function(e){return-1!==t.node.sourceLinks.indexOf(e.link)||-1!==t.node.targetLinks.indexOf(e.link)}}function ZB(t){return function(e){return-1!==e.node.sourceLinks.indexOf(t.link)||-1!==e.node.targetLinks.indexOf(t.link)}}function JB(t,e,r){e&&r&&GB(r,e).selectAll("."+UB.sankeyLink).filter(XB(e)).call(QB.bind(0,e,r,!1))}function KB(t,e,r){e&&r&&GB(r,e).selectAll("."+UB.sankeyLink).filter(XB(e)).call($B.bind(0,e,r,!1))}function QB(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",.4),i&&GB(e,t).selectAll("."+UB.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",.4),r&&GB(e,t).selectAll("."+UB.sankeyNode).filter(ZB(t)).call(JB)}function $B(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",function(t){return t.tinyColorAlpha}),i&&GB(e,t).selectAll("."+UB.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",function(t){return t.tinyColorAlpha}),r&&GB(e,t).selectAll(UB.sankeyNode).filter(ZB(t)).call(KB)}function tN(t,e){var r=t.hoverlabel||{},n=ne.nestedProperty(r,e).get();return!Array.isArray(n)&&n}var eN=function(t,r){var n=t._fullLayout,i=n._paper,a=n._size,o=qB(t,"source:")+" ",s=qB(t,"target:")+" ",l=qB(t,"incoming flow count:")+" ",u=qB(t,"outgoing flow count:")+" ";VB(i,r,{width:a.w,height:a.h,margin:{t:a.t,r:a.r,b:a.b,l:a.l}},{linkEvents:{hover:function(r,n,i){e.select(r).call(QB.bind(0,n,i,!0)),t.emit("plotly_hover",{event:e.event,points:[n.link]})},follow:function(r,i){var a=i.link.trace,l=t._fullLayout._paperdiv.node().getBoundingClientRect(),u=r.getBoundingClientRect(),c=u.left+u.width/2,h=u.top+u.height/2,f=yo.loneHover({x:c-l.left,y:h-l.top,name:e.format(i.valueFormat)(i.link.value)+i.valueSuffix,text:[i.link.label||"",o+i.link.source.label,s+i.link.target.label].filter(HB).join("
"),color:tN(a,"bgcolor")||Oe.addOpacity(i.tinyColorHue,1),borderColor:tN(a,"bordercolor"),fontFamily:tN(a,"font.family"),fontSize:tN(a,"font.size"),fontColor:tN(a,"font.color"),idealAlign:e.event.x"),color:tN(a,"bgcolor")||i.tinyColorHue,borderColor:tN(a,"bordercolor"),fontFamily:tN(a,"font.family"),fontSize:tN(a,"font.size"),fontColor:tN(a,"font.color"),idealAlign:"left"},{container:n._hoverlayer.node(),outerContainer:n._paper.node(),gd:t});WB(d,.85),YB(d)},unhover:function(r,i,a){e.select(r).call(KB,i,a),t.emit("plotly_unhover",{event:e.event,points:[i.node]}),yo.loneUnhover(n._hoverlayer.node())},select:function(r,n,i){var a=n.node;a.originalEvent=e.event,t._hoverdata=[a],e.select(r).call(KB,n,i),yo.click(t,{target:!0})}}})},rN={},nN=ye.overrideAll,iN=sa.getModuleCalcData;rN.name="sankey",rN.baseLayoutAttrOverrides=nN({hoverlabel:mo.hoverlabel},"plot","nested"),rN.plot=function(t){var e=iN(t.calcdata,"sankey");eN(t,e)},rN.clean=function(t,e,r,n){var i=n._has&&n._has("sankey"),a=e._has&&e._has("sankey");i&&!a&&n._paperdiv.selectAll(".sankey").remove()};var aN=function(t){for(var e=t.length,r=new Array(e),n=new Array(e),i=new Array(e),a=new Array(e),o=new Array(e),s=new Array(e),l=0;l0;){e=u[u.length-1];var p=t[e];if(a[e]=0&&s[e].push(o[g])}a[e]=d}else{if(n[e]===r[e]){for(var v=[],m=[],y=0,d=l.length-1;d>=0;--d){var x=l[d];if(i[x]=!1,v.push(x),m.push(s[x]),y+=s[x].length,o[x]=h.length,x===e){l.length=d;break}}h.push(v);for(var b=new Array(y),d=0;d1})}(e.node.label,e.link.source,e.link.target)&&(ne.error("Circularity is present in the Sankey data. Removing all nodes and links."),e.link.label=[],e.link.source=[],e.link.target=[],e.link.value=[],e.link.color=[],e.node.label=[],e.node.color=[]),oN({link:e.link,node:e.node})},lN.plot=eN,lN.moduleType="trace",lN.name="sankey",lN.basePlotModule=rN,lN.categories=["noOpacity"],lN.meta={};var uN=lN,cN={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"},hN={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]},fN={},pN=m.extendFlat,dN=ye.overrideAll,gN=Zr.line,vN=Zr.marker,mN=vN.line;var yN=fN=dN({x:Zr.x,y:Zr.y,z:{valType:"data_array"},text:pN({},Zr.text,{}),hovertext:pN({},Zr.hovertext,{}),mode:pN({},Zr.mode,{dflt:"lines+markers"}),surfaceaxis:{valType:"enumerated",values:[-1,0,1,2],dflt:-1},surfacecolor:{valType:"color"},projection:{x:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}},y:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}},z:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}}},connectgaps:Zr.connectgaps,line:pN({width:gN.width,dash:{valType:"enumerated",values:Object.keys(hN),dflt:"solid"},showscale:{valType:"boolean",dflt:!1}},De()),marker:pN({symbol:{valType:"enumerated",values:Object.keys(cN),dflt:"circle",arrayOk:!0},size:pN({},vN.size,{dflt:8}),sizeref:vN.sizeref,sizemin:vN.sizemin,sizemode:vN.sizemode,opacity:pN({},vN.opacity,{arrayOk:!1}),showscale:vN.showscale,colorbar:vN.colorbar,line:pN({width:pN({},mN.width,{arrayOk:!1})},De())},De()),textposition:pN({},Zr.textposition,{dflt:"top center"}),textfont:Zr.textfont,hoverinfo:pN({},E.hoverinfo)},"calc","nested");yN.x.editType=yN.y.editType=yN.z.editType="calc+clearAxisTypes";var xN=E_(["precision mediump 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}"]),bN=E_(["precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}"]),_N=function(t){return Bw(t,xN,bN,null,[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"offset",type:"vec3"}])},wN=function(t){var e=t.gl,r=S_(e),n=EP(e,[{buffer:r,type:e.FLOAT,size:3,offset:0,stride:40},{buffer:r,type:e.FLOAT,size:4,offset:12,stride:40},{buffer:r,type:e.FLOAT,size:3,offset:28,stride:40}]),i=_N(e);i.attributes.position.location=0,i.attributes.color.location=1,i.attributes.offset.location=2;var a=new AN(e,r,n,i);return a.update(t),a},MN=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function AN(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}var kN=AN.prototype;function TN(t,e){for(var r=0;r<3;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}kN.isOpaque=function(){return this.opacity>=1},kN.isTransparent=function(){return this.opacity<1},kN.drawTransparent=kN.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||MN,i=r.projection=t.projection||MN;r.model=t.model||MN,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var c=0;c<3;++c)e.lineWidth(this.lineWidth[c]),r.capSize=this.capSize[c]*u,this.lineCount[c]&&e.drawArrays(e.LINES,this.lineOffset[c],this.lineCount[c]);this.vao.unbind()};var SN=function(){for(var t=new Array(3),e=0;e<3;++e){for(var r=[],n=1;n<=2;++n)for(var i=-1;i<=1;i+=2){var a=[0,0,0];a[(n+e)%3]=i,r.push(a)}t[e]=r}return t}();function EN(t,e,r,n){for(var i=SN[n],a=0;a0)(p=u.slice())[s]+=h[1][s],i.push(u[0],u[1],u[2],f[0],f[1],f[2],f[3],0,0,0,p[0],p[1],p[2],f[0],f[1],f[2],f[3],0,0,0),TN(this.bounds,p),o+=2+EN(i,p,f,s)}}this.lineCount[s]=o-this.lineOffset[s]}this.buffer.update(i)}},kN.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()};var CN={},LN=E_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]),zN=E_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]),PN=E_(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]),IN=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];CN.createShader=function(t){return Bw(t,LN,zN,null,IN)},CN.createPickShader=function(t){return Bw(t,LN,PN,null,IN)};var DN=function(t,e,r,n){return ON[0]=n,ON[1]=r,ON[2]=e,ON[3]=t,RN[0]},ON=new Uint8Array(4),RN=new Float32Array(ON.buffer);var FN=function(t){var e=t.gl||t.scene&&t.scene.gl,r=BN(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=NN(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=S_(e),a=EP(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),o=wb(new Array(1024),[256,1,4]),s=0;s<1024;++s)o.data[s]=255;var l=zE(e,o);l.wrap=e.REPEAT;var u=new HN(e,r,n,i,a,l);return u.update(t),u},BN=CN.createShader,NN=CN.createPickShader,jN=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function VN(t,e){for(var r=0,n=0;n<3;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function UN(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;r<3;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function qN(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function HN(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}var GN=HN.prototype;GN.isTransparent=function(){return this.opacity<1},GN.isOpaque=function(){return this.opacity>=1},GN.pickSlots=1,GN.setPickBase=function(t){this.pickId=t},GN.drawTransparent=GN.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||jN,view:t.view||jN,projection:t.projection||jN,clipBounds:UN(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},GN.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||jN,view:t.view||jN,projection:t.projection||jN,pickId:this.pickId,clipBounds:UN(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},GN.update=function(t){var e,r;this.dirty=!0;var n=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var i=t.position||t.positions;if(i){var a=t.color||t.colors||[0,0,0,1],o=t.lineWidth||1,s=[],l=[],u=[],c=0,h=0,f=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],p=!1;t:for(e=1;e0){for(var x=0;x<24;++x)s.push(s[s.length-12]);h+=2,p=!0}continue t}f[0][r]=Math.min(f[0][r],m[r],y[r]),f[1][r]=Math.max(f[1][r],m[r],y[r])}Array.isArray(a[0])?(d=a[e-1],g=a[e]):d=g=a,3===d.length&&(d=[d[0],d[1],d[2],1]),3===g.length&&(g=[g[0],g[1],g[2],1]),v=Array.isArray(o)?o[e-1]:o;var b=c;if(c+=VN(m,y),p){for(r=0;r<2;++r)s.push(m[0],m[1],m[2],y[0],y[1],y[2],b,v,d[0],d[1],d[2],d[3]);h+=2,p=!1}s.push(m[0],m[1],m[2],y[0],y[1],y[2],b,v,d[0],d[1],d[2],d[3],m[0],m[1],m[2],y[0],y[1],y[2],b,-v,d[0],d[1],d[2],d[3],y[0],y[1],y[2],m[0],m[1],m[2],c,-v,g[0],g[1],g[2],g[3],y[0],y[1],y[2],m[0],m[1],m[2],c,v,g[0],g[1],g[2],g[3]),h+=4}if(this.buffer.update(s),l.push(c),u.push(i[i.length-1].slice()),this.bounds=f,this.vertexCount=h,this.points=u,this.arcLength=l,"dashes"in t){var _=t.dashes.slice();for(_.unshift(0),e=1;e<_.length;++e)_[e]=_[e-1]+_[e];var w=wb(new Array(1024),[256,1,4]);for(e=0;e<256;++e){for(r=0;r<4;++r)w.set(e,0,r,0);1&wT.le(_,_[_.length-1]*e/255)?w.set(e,0,0,0):w.set(e,0,0,255)}this.texture.setPixels(w)}}},GN.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},GN.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=DN(t.value[0],t.value[1],t.value[2],0),r=wT.le(this.arcLength,e);if(r<0)return null;if(r===this.arcLength.length-1)return new qN(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],a=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),o=1-a,s=[0,0,0],l=0;l<3;++l)s[l]=o*n[l]+a*i[l];var u=Math.min(a<.5?r:r+1,this.points.length-1);return new qN(e,s,u,this.points[u])};var WN=function(t,e){var r=YN[e];r||(r=YN[e]={});if(t in r)return r[t];for(var n=ME(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),i=ME(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),a=[[1/0,1/0],[-1/0,-1/0]],o=0;o=1)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var dj=[0,0],gj=[0,0,0],vj=[0,0,0],mj=[0,0,0,1],yj=[0,0,0,1],xj=lj.slice(),bj=[0,0,0],_j=[[0,0,0],[0,0,0]];function wj(t){return t[0]=t[1]=t[2]=0,t}function Mj(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function Aj(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function kj(t,e,r,n,i){var a,o=e.axesProject,s=e.gl,l=t.uniforms,u=r.model||lj,c=r.view||lj,h=r.projection||lj,f=e.axesBounds,p=function(t){for(var e=_j,r=0;r<2;++r)for(var n=0;n<3;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}(e.clipBounds);a=e.axes&&e.axes.lastCubeProps?e.axes.lastCubeProps.axis:[1,1,1],dj[0]=2/s.drawingBufferWidth,dj[1]=2/s.drawingBufferHeight,t.bind(),l.view=c,l.projection=h,l.screenSize=dj,l.highlightId=e.highlightId,l.highlightScale=e.highlightScale,l.clipBounds=p,l.pickGroup=e.pickId/255,l.pixelRatio=e.pixelRatio;for(var d=0;d<3;++d)if(o[d]&&e.projectOpacity[d]<1===n){l.scale=e.projectScale[d],l.opacity=e.projectOpacity[d];for(var g=xj,v=0;v<16;++v)g[v]=0;for(v=0;v<4;++v)g[5*v]=1;g[5*d]=0,a[d]<0?g[12+d]=f[0][d]:g[12+d]=f[1][d],Dz(g,u,g),l.model=g;var m=(d+1)%3,y=(d+2)%3,x=wj(gj),b=wj(vj);x[m]=1,b[y]=1;var _=hj(0,0,0,Mj(mj,x)),w=hj(0,0,0,Mj(yj,b));if(Math.abs(_[1])>Math.abs(w[1])){var M=_;_=w,w=M,M=x,x=b,b=M;var A=m;m=y,y=A}_[0]<0&&(x[m]=-1),w[1]>0&&(b[y]=-1);var k=0,T=0;for(v=0;v<4;++v)k+=Math.pow(u[4*m+v],2),T+=Math.pow(u[4*y+v],2);x[m]/=Math.sqrt(k),b[y]/=Math.sqrt(T),l.axes[0]=x,l.axes[1]=b,l.fragClipBounds[0]=Aj(bj,p[0],d,-1e8),l.fragClipBounds[1]=Aj(bj,p[1],d,1e8),e.vao.draw(s.TRIANGLES,e.vertexCount),e.lineWidth>0&&(s.lineWidth(e.lineWidth),e.vao.draw(s.LINES,e.lineVertexCount,e.vertexCount))}}var Tj=[[-1e8,-1e8,-1e8],[1e8,1e8,1e8]];function Sj(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||lj,s.view=n.view||lj,s.projection=n.projection||lj,dj[0]=2/o.drawingBufferWidth,dj[1]=2/o.drawingBufferHeight,s.screenSize=dj,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=Tj,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}kj(e,r,n,i),r.vao.unbind()}pj.draw=function(t){Sj(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!1,!1)},pj.drawTransparent=function(t){Sj(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!0,!1)},pj.drawPick=function(t){Sj(this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader,this.pickProjectShader,this,t,!1,!0)},pj.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||e<0)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;i<3;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},pj.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},pj.update=function(t){if("perspective"in(t=t||{})&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0],l=t.glyph,u=t.color,c=t.size,h=t.angle,f=t.lineColor,p=0,d=0,g=0,v=n.length;t:for(var m=0;m0&&(E[0]=-a[0]*(1+w[0][0]));var V=b.cells,U=b.positions;for(x=0;x=0&&(u[1]+=1),l.indexOf("top")>=0&&(u[1]-=1),l.indexOf("left")>=0&&(u[0]-=1),l.indexOf("right")>=0&&(u[0]+=1),u)),r.textColor=Dj(e.textfont,1,_),r.textSize=Vj(e.textfont.size,_,ne.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var T=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;n<3;++n){var S=e.projection[T[n]];(r.project[n]=S.show)&&(r.projectOpacity[n]=S.opacity,r.projectScale[n]=S.scale)}r.errorBounds=Rj(e,f);var E=function(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[0,0,0],i=0;i<3;i++){var a=t[i];a&&!1!==a.copy_zstyle&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=WC(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}([e.error_x,e.error_y,e.error_z]);return r.errorColor=E.color,r.errorLineWidth=E.lineWidth,r.errorCapSize=E.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=WC(e.surfacecolor),r}function qj(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}Bj.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels?void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel=this.textLabels:t.textLabel="";var e=t.index=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},Bj.update=function(t){var e,r,n,i,a=this.scene.glplot.gl,o=hN.solid;this.data=t;var s=Uj(this.scene,t);"mode"in s&&(this.mode=s.mode),"lineDashes"in s&&s.lineDashes in hN&&(o=hN[s.lineDashes]),this.color=qj(s.scatterColor)||qj(s.lineColor),this.dataPoints=s.position,e={gl:a,position:s.position,color:s.lineColor,lineWidth:s.lineWidth||1,dashes:o[0],dashScale:o[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=FN(e),this.linePlot._trace=this,this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var l=t.opacity;if(t.marker&&t.marker.opacity&&(l*=t.marker.opacity),r={gl:a,position:s.position,color:s.scatterColor,size:s.scatterSize,glyph:s.scatterMarker,opacity:l,orthographic:!0,lineWidth:s.scatterLineWidth,lineColor:s.scatterLineColor,project:s.project,projectScale:s.projectScale,projectOpacity:s.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=uj(r),this.scatterPlot._trace=this,this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),i={gl:a,position:s.position,glyph:s.text,color:s.textColor,size:s.textSize,angle:s.textAngle,alignment:s.textOffset,font:s.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=t.hovertext||t.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(i):(this.textMarkers=uj(i),this.textMarkers._trace=this,this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:a,position:s.position,color:s.errorColor,error:s.errorBounds,lineWidth:s.errorLineWidth,capSize:s.errorCapSize,opacity:t.opacity},this.errorBars?s.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):s.errorBounds&&(this.errorBars=wN(n),this.errorBars._trace=this,this.scene.glplot.add(this.errorBars)),s.delaunayAxis>=0){var u=function(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;n=0&&i("surfacecolor",a||o);for(var s=["x","y","z"],l=0;l<3;++l){var u="projection."+s[l];i(u+".show")&&(i(u+".opacity"),i(u+".scale"))}var c=P.getComponentMethod("errorbars","supplyDefaults");c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}else e.visible=!1},Gj.colorbar=is,Gj.calc=nB,Gj.moduleType="trace",Gj.name="scatter3d",Gj.basePlotModule=SD,Gj.categories=["gl3d","symbols","markerColorscale","showLegend"],Gj.meta={};var Wj=Gj,Yj=m.extendFlat,Xj=Zr.marker,Zj=Zr.line,Jj=Xj.line,Kj={carpet:{valType:"string",editType:"calc"},a:{valType:"data_array",editType:"calc"},b:{valType:"data_array",editType:"calc"},mode:Yj({},Zr.mode,{dflt:"markers"}),text:Yj({},Zr.text,{}),line:{color:Zj.color,width:Zj.width,dash:Zj.dash,shape:Yj({},Zj.shape,{values:["linear","spline"]}),smoothing:Zj.smoothing,editType:"calc"},connectgaps:Zr.connectgaps,fill:Yj({},Zr.fill,{values:["none","toself","tonext"]}),fillcolor:Zr.fillcolor,marker:Yj({symbol:Xj.symbol,opacity:Xj.opacity,maxdisplayed:Xj.maxdisplayed,size:Xj.size,sizeref:Xj.sizeref,sizemin:Xj.sizemin,sizemode:Xj.sizemode,line:Yj({width:Jj.width,editType:"calc"},De()),gradient:Xj.gradient,editType:"calc"},De(),{showscale:Xj.showscale,colorbar:ze}),textfont:Zr.textfont,textposition:Zr.textposition,selected:Zr.selected,unselected:Zr.unselected,hoverinfo:Yj({},E.hoverinfo,{flags:["a","b","text","name"]}),hoveron:Zr.hoveron},Qj=sx,$j={};$j.attributes=Kj,$j.supplyDefaults=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,Kj,r,n)}i("carpet"),e.xaxis="x",e.yaxis="y";var a,o=i("a"),s=i("b");if(a=Math.min(o.length,s.length)){o&&a"),i}function _(t,e){var r;r=t.labelprefix&&t.labelprefix.length>0?t.labelprefix.replace(/ = $/,""):t._hovertitle,d.push(r+": "+e.toFixed(3)+t.labelsuffix)}},$j.selectPoints=Sx,$j.eventData=function(t,e,r,n,i){var a=n[i];return t.a=a.a,t.b=a.b,t},$j.moduleType="trace",$j.name="scattercarpet",$j.basePlotModule=ua,$j.categories=["carpet","symbols","markerColorscale","showLegend","carpetDependent"],$j.meta={};var tV=$j,eV=t.BADNUM,rV=ne._,nV=function(t,e){for(var n=Array.isArray(e.locations),i=n?e.locations.length:e._length,a=new Array(i),o=0;o0&&(r.push(n),n=[])}return n.length>0&&r.push(n),r},aV.makeLine=function(t){return 1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t}},aV.makePolygon=function(t){if(1===t.length)return{type:"Polygon",coordinates:t};for(var e=new Array(t.length),r=0;r")}(i,c,s.mockAxis,n[0].t.labels),[t]}},pV.eventData=function(t,e){return t.lon=e.lon,t.lat=e.lat,t.location=e.loc?e.loc:null,t},pV.selectPoints=function(t,e){var r,n,i,a,o,s=t.cd,l=t.xaxis,u=t.yaxis,c=[],h=s[0].trace;if(!Tr.hasMarkers(h)&&!Tr.hasText(h))return[];if(!1===e)for(o=0;oi;){if(a-i>600){var s=a-i+1,l=n-i+1,u=Math.log(s),c=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*c*(s-c)/s)*(l-s/2<0?-1:1),f=Math.max(i,Math.floor(n-l*c/s+h)),p=Math.min(a,Math.floor(n+(s-l)*c/s+h));t(e,r,n,f,p,o)}var d=r[2*n+o],g=i,v=a;for(xV(e,r,i,n),r[2*a+o]>d&&xV(e,r,i,a);gd;)v--}r[2*i+o]===d?xV(e,r,i,v):xV(e,r,++v,a),v<=n&&(i=v+1),n<=v&&(a=v-1)}}(e,r,s,i,a,o%2);t(e,r,n,i,s-1,o+1);t(e,r,n,s+1,a,o+1)}(this.ids,this.coords,this.nodeSize,0,this.ids.length-1,0)}function yV(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}function xV(t,e,r,n){bV(t,r,n),bV(e,2*r,2*n),bV(e,2*r+1,2*n+1)}function bV(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}mV.prototype.range=function(t,e,r,n){for(var i,a,o=this.ids,s=this.coords,l=this.nodeSize,u=[0,o.length-1,0],c=[];u.length;){var h=u.pop(),f=u.pop(),p=u.pop();if(f-p<=l)for(var d=p;d<=f;d++)i=s[2*d],a=s[2*d+1],i>=t&&i<=r&&a>=e&&a<=n&&c.push(o[d]);else{var g=Math.floor((p+f)/2);i=s[2*g],a=s[2*g+1],i>=t&&i<=r&&a>=e&&a<=n&&c.push(o[g]);var v=(h+1)%2;(0===h?t<=i:e<=a)&&(u.push(p),u.push(g-1),u.push(v)),(0===h?r>=i:n>=a)&&(u.push(g+1),u.push(f),u.push(v))}}return c},mV.prototype.within=function(t,e,r){for(var n=this.ids,i=this.coords,a=this.nodeSize,o=[0,n.length-1,0],s=[],l=r*r;o.length;){var u=o.pop(),c=o.pop(),h=o.pop();if(c-h<=a)for(var f=h;f<=c;f++)yV(i[2*f],i[2*f+1],t,e)<=l&&s.push(n[f]);else{var p=Math.floor((h+c)/2),d=i[2*p],g=i[2*p+1];yV(d,g,t,e)<=l&&s.push(n[p]);var v=(u+1)%2;(0===u?t-r<=d:e-r<=g)&&(o.push(h),o.push(p-1),o.push(v)),(0===u?t+r>=d:e+r>=g)&&(o.push(p+1),o.push(c),o.push(v))}}return s};var _V=function(t,e){if(!t||null==t.length)throw Error("Argument should be an array");e=null==e?1:Math.floor(e);for(var r=Array(2*e),n=0;ni&&(i=t[o]),t[o]1&&(t.scaleRatio=[t.scale[0]*t.viewport.width,t.scale[1]*t.viewport.height],r(t),t.after&&t.after(t))}function d(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0,r=0;if(c=t.map(function(t,n){var i=c[n];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=MV(t,{color:"color colors fill",capSize:"capSize cap capsize cap-size",lineWidth:"lineWidth line-width width line thickness",opacity:"opacity alpha",range:"range dataBox",viewport:"viewport viewBox",errors:"errors error",positions:"positions position data points"}),i||(c[n]=i={id:n,scale:null,translate:null,scaleFract:null,translateFract:null,draw:!0},t=Us({},u,t)),EV(i,t,[{lineWidth:function(t){return.5*+t},capSize:function(t){return.5*+t},opacity:parseFloat,errors:function(t){return t=wV(t),r+=t.length,t},positions:function(t,r){return t=wV(t,"float64"),r.count=Math.floor(t.length/2),r.bounds=_V(t,2),r.offset=e,e+=r.count,t}},{color:function(t,e){var r=e.count;if(t||(t="transparent"),!Array.isArray(t)||"number"==typeof t[0]){var n=t;t=Array(r);for(var i=0;i80*r){n=a=t[0],i=o=t[1];for(var d=r;da&&(a=s),l>o&&(o=l);u=0!==(u=Math.max(a-n,o-i))?1/u:0}return BV(f,p,r,n,i,u),p}function RV(t,e,r,n,i){var a,o;if(i===nU(t,e,r,n)>0)for(a=e;a=e;a-=n)o=tU(a,t[a],t[a+1],o);return o&&JV(o,o.next)&&(eU(o),o=o.next),o}function FV(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!JV(n,n.next)&&0!==ZV(n.prev,n,n.next))n=n.next;else{if(eU(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function BV(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=GV(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,u=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,u*=2}while(o>1)}(i)}(t,n,i,a);for(var s,l,u=t;t.prev!==t.next;)if(s=t.prev,l=t.next,a?jV(t,n,i,a):NV(t))e.push(s.i/r),e.push(t.i/r),e.push(l.i/r),eU(t),t=l.next,u=l.next;else if((t=l)===u){o?1===o?BV(t=VV(t,e,r),e,r,n,i,a,2):2===o&&UV(t,e,r,n,i,a):BV(FV(t),e,r,n,i,a,1);break}}}function NV(t){var e=t.prev,r=t,n=t.next;if(ZV(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(YV(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&ZV(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function jV(t,e,r,n){var i=t.prev,a=t,o=t.next;if(ZV(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,c=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,h=GV(s,l,e,r,n),f=GV(u,c,e,r,n),p=t.prevZ,d=t.nextZ;p&&p.z>=h&&d&&d.z<=f;){if(p!==t.prev&&p!==t.next&&YV(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&ZV(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,d!==t.prev&&d!==t.next&&YV(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&ZV(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(;p&&p.z>=h;){if(p!==t.prev&&p!==t.next&&YV(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&ZV(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&YV(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&ZV(d.prev,d,d.next)>=0)return!1;d=d.nextZ}return!0}function VV(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!JV(i,a)&&KV(i,n,n.next,a)&&QV(i,a)&&QV(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),eU(n),eU(n.next),n=t=a),n=n.next}while(n!==t);return n}function UV(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&XV(o,s)){var l=$V(o,s);return o=FV(o,o.next),l=FV(l,l.next),BV(o,e,r,n,i,a),void BV(l,e,r,n,i,a)}s=s.next}o=o.next}while(o!==t)}function qV(t,e){return t.x-e.x}function HV(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&i!==n.x&&YV(ar.x)&&QV(n,t)&&(r=n,f=l),n=n.next;return r}(t,e)){var r=$V(e,t);FV(r,r.next)}}function GV(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function WV(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function XV(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&KV(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&QV(t,e)&&QV(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function ZV(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function JV(t,e){return t.x===e.x&&t.y===e.y}function KV(t,e,r,n){return!!(JV(t,e)&&JV(r,n)||JV(t,n)&&JV(r,e))||ZV(t,e,r)>0!=ZV(t,e,n)>0&&ZV(r,n,t)>0!=ZV(r,n,e)>0}function QV(t,e){return ZV(t.prev,t,t.next)<0?ZV(t,e,t.next)>=0&&ZV(t,t.prev,e)>=0:ZV(t,e,t.prev)<0||ZV(t,t.next,e)<0}function $V(t,e){var r=new rU(t.i,t.x,t.y),n=new rU(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function tU(t,e,r,n){var i=new rU(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function eU(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function rU(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function nU(t,e,r,n){for(var i=0,a=e,o=r-n;a0&&(n+=t[i-1].length,r.holes.push(n))}return r};var iU=function(t,e){"function"==typeof t?(e||(e={}),e.regl=t):e=t;e.length&&(e.positions=e);if(!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");var r,n,i,a,o,s,l,u,c=t._gl,h={positions:[],dashes:null,join:null,miterLimit:1,thickness:10,cap:"square",color:"black",opacity:1,overlay:!1,viewport:null,range:null,close:null,fill:null},f=[],p=2,d=3e6,g=1e4;a=t.buffer({usage:"dynamic",type:"uint8",data:null}),o=t.buffer({usage:"static",type:"float",data:[0,1,0,0,1,1,1,0]}),s=t.buffer({usage:"dynamic",type:"float",data:null}),l=t.buffer({usage:"dynamic",type:"float",data:null}),u=t.texture({channels:1,data:new Uint8Array(524288),width:256,height:2048,mag:"linear",min:"linear"}),b(e);var v={primitive:"triangle strip",instances:t.prop("count"),count:4,offset:0,uniforms:{miterMode:function(t,e){return"round"===e.join?2:1},miterLimit:t.prop("miterLimit"),scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),thickness:t.prop("thickness"),dashPattern:u,dashLength:t.prop("dashLength"),dashShape:[256,2048],opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),scaleRatio:t.prop("scaleRatio"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:function(t,e){return!e.overlay}},scissor:{enable:!0,box:t.prop("viewport")},stencil:!1,viewport:t.prop("viewport")};function m(t){t?b(t):null===t&&_(),y()}function y(t){if("number"==typeof t)return x(t);t&&!Array.isArray(t)&&(t=[t]),f.forEach(function(t,e){x(e)})}function x(e){"number"==typeof e&&(e=f[e]),e&&e.count&&e.opacity&&e.positions&&e.positions.length>2&&(t._refresh(),e.fill&&e.triangles&&e.triangles.length>2&&i(e),e.thickness&&e.color&&(e.scaleRatio=[e.scale[0]*e.viewport.width,e.scale[1]*e.viewport.height],e.scaleRatio[0]>d||e.scaleRatio[1]>d?n(e):"rect"===e.join||!e.join&&(e.thickness<=2||e.positions.length>=g)?n(e):r(e),e.after&&e.after(e)))}function b(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0;if(m.lines=f=t.map(function(t,r){var n=f[r];return void 0===t?n:(null===t?t={positions:null}:"function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),null===(t=MV(t,{positions:"positions points data coords",thickness:"thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",join:"lineJoin linejoin join type mode",miterLimit:"miterlimit miterLimit",dashes:"dash dashes dasharray dash-array dashArray",color:"color stroke colors stroke-color strokeColor",fill:"fill fill-color fillColor",opacity:"alpha opacity",overlay:"overlay crease overlap intersect",close:"closed close closed-path closePath",range:"range dataBox",viewport:"viewport viewBox",hole:"holes hole hollow",after:"after callback done pass"})).positions&&(t.positions=[]),n||(f[r]=n={id:r,scale:null,scaleFract:null,translate:null,translateFract:null,count:0,offset:0,dashLength:0,hole:!0},t=Us({},h,t)),EV(n,t,[{thickness:parseFloat,opacity:parseFloat,miterLimit:parseFloat,overlay:Boolean,join:function(t){return t},after:function(t){return t},hole:function(t){return t||[]},positions:function(t,r,n){t=wV(t,"float64");var i=Math.floor(t.length/2),a=_V(t,2);return r.range||n.range||(n.range=a),r.count=i,r.bounds=a,e+=i,t},fill:function(t){return t?GC(t,"uint8"):null},dashes:function(t,e,r){var n,i=e.dashLength;if(!t||t.length<2)i=1,n=new Uint8Array([255,255,255,255,255,255,255,255]);else{i=0;for(var a=0;a=4&&e.positions[0]===e.positions[e.positions.length-2]&&e.positions[1]===e.positions[e.positions.length-1]},positions:function(t,e,r){if(e.fill&&t.length){for(var n=[],i={},a=0,o=0,s=0,l=e.count;o 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),frag:E_(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:o,divisor:0,stride:8,offset:0},lineTop:{buffer:o,divisor:0,stride:8,offset:4},aColor:{buffer:a,stride:4,offset:function(t,e){return 4*e.offset},divisor:1},bColor:{buffer:a,stride:4,offset:function(t,e){return 4*e.offset+4},divisor:1},prevCoord:{buffer:s,stride:8,offset:function(t,e){return 8*e.offset},divisor:1},aCoord:{buffer:s,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoord:{buffer:s,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},nextCoord:{buffer:s,stride:8,offset:function(t,e){return 24+8*e.offset},divisor:1}}},v)),n=t(Us({vert:E_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\t// vec2 scaleRatio = scale * viewport.zw;\n\tvec2 normalWidth = thickness / scaleRatio;\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scaleRatio);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:E_(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform vec2 dashShape;\nuniform float dashLength, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t * dashLength * 2. / dashShape.x, (id + .5) / dashShape.y)).r;\n\n\tgl_FragColor = fragColor * dash;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:o,divisor:0,stride:8,offset:0},lineTop:{buffer:o,divisor:0,stride:8,offset:4},aCoord:{buffer:s,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoord:{buffer:s,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},aCoordFract:{buffer:l,stride:8,offset:function(t,e){return 8+8*e.offset},divisor:1},bCoordFract:{buffer:l,stride:8,offset:function(t,e){return 16+8*e.offset},divisor:1},color:{buffer:a,stride:4,offset:function(t,e){return 4*e.offset},divisor:1}}},v)),i=t({primitive:"triangle",elements:function(t,e){return e.triangles},offset:0,vert:E_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract, scaleRatio;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:E_(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= opacity;\n}\n"]),uniforms:{scale:t.prop("scale"),color:t.prop("fill"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{position:{buffer:s,stride:8,offset:function(t,e){return 8+8*e.offset}},positionFract:{buffer:l,stride:8,offset:function(t,e){return 8+8*e.offset}}},blend:v.blend,depth:{enable:!1},scissor:v.scissor,stencil:v.stencil,viewport:v.viewport}),Us(m,{update:b,draw:y,destroy:_,regl:t,gl:c,canvas:c.canvas,lines:f}),m};function aU(t){var e=new Float32Array(t.length);e.set(t);for(var r=0,n=e.length;r>>24,n=(16711680&t)>>>16,i=(65280&t)>>>8,a=255&t;return!1===e?[r,n,i,a]:[r/255,n/255,i/255,a/255]};var lU="undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)),uU=function(t){var e;arguments.length>1&&(t=arguments);"string"==typeof t&&(t=t.split(/\s/).map(parseFloat));t.length&&"number"==typeof t[0]?e=2===t.length?{width:t[0],height:t[1],x:0,y:0}:{x:t[0],y:t[1],width:t[2]-t[0]||0,height:t[3]-t[1]||0}:t&&(t=MV(t,{left:"x l left Left",top:"y t top Top",width:"w width",height:"h height",bottom:"b bottom",right:"r right"}),e={x:t.left||0,y:t.top||0},null==t.width?t.right?e.width=t.right-e.x:e.width=0:e.width=t.width,null==t.height?t.bottom?e.height=t.bottom-e.y:e.height=0:e.height=t.height);return e};function cU(t,e,r,n,i){var a=["function ",t,"(a,l,h,",n.join(","),"){",i?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function hU(t,e,r,n){return new Function([cU("A","x"+t+"y",e,["y"],n),cU("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var fU={ge:hU(">=",!1,"GE"),gt:hU(">",!1,"GT"),lt:hU("<",!0,"LT"),le:hU("<=",!0,"LE"),eq:hU("-",!0,"EQ",!0)},pU=function(t,e,r,n,i){i<=4*dU?gU(0,i-1,t,e,r,n):function t(e,r,n,i,a,o){var s=(r-e+1)/6|0,l=e+s,u=r-s,c=e+r>>1,h=c-s,f=c+s,p=l,d=h,g=c,v=f,m=u,y=e+1,x=r-1,b=0;bU(p,d,n,i,a)&&(b=p,p=d,d=b);bU(v,m,n,i,a)&&(b=v,v=m,m=b);bU(p,g,n,i,a)&&(b=p,p=g,g=b);bU(d,g,n,i,a)&&(b=d,d=g,g=b);bU(p,v,n,i,a)&&(b=p,p=v,v=b);bU(g,v,n,i,a)&&(b=g,g=v,v=b);bU(d,m,n,i,a)&&(b=d,d=m,m=b);bU(d,g,n,i,a)&&(b=d,d=g,g=b);bU(v,m,n,i,a)&&(b=v,v=m,m=b);var _=n[d];var w=i[2*d];var M=i[2*d+1];var A=a[d];var k=o[d];var T=n[v];var S=i[2*v];var E=i[2*v+1];var C=a[v];var L=o[v];var z=p;var P=g;var I=m;var D=l;var O=c;var R=u;var F=n[z];var B=n[P];var N=n[I];n[D]=F;n[O]=B;n[R]=N;for(var j=0;j<2;++j){var V=i[2*z+j],U=i[2*P+j],q=i[2*I+j];i[2*D+j]=V,i[2*O+j]=U,i[2*R+j]=q}var H=a[z];var G=a[P];var W=a[I];a[D]=H;a[O]=G;a[R]=W;var Y=o[z];var X=o[P];var Z=o[I];o[D]=Y;o[O]=X;o[R]=Z;mU(h,e,n,i,a,o);mU(f,r,n,i,a,o);for(var J=y;J<=x;++J)if(_U(J,_,w,M,A,n,i,a))J!==y&&vU(J,y,n,i,a,o),++y;else if(!_U(J,T,S,E,C,n,i,a))for(;;){if(_U(x,T,S,E,C,n,i,a)){_U(x,_,w,M,A,n,i,a)?(yU(J,y,x,n,i,a,o),++y,--x):(vU(J,x,n,i,a,o),--x);break}if(--xt;){var p=r[f-1],d=n[2*(f-1)];if((p-s||l-d)>=0)break;r[f]=p,n[2*f]=d,n[2*f+1]=n[2*f-1],i[f]=i[f-1],a[f]=a[f-1],f-=1}r[f]=s,n[2*f]=l,n[2*f+1]=u,i[f]=c,a[f]=h}}function vU(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],u=i[t],c=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=u,a[e]=c}function mU(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function yU(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],u=i[2*t+1],c=a[t],h=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=u,a[r]=c,o[r]=h}function xU(t,e,r,n,i,a,o,s,l,u,c){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],u[t]=u[e],c[t]=c[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,u[e]=a,c[e]=o}function bU(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function _U(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}var wU=function(t,e,r,n){var i=t.length>>>1;if(i<1)return[];e||(e=Array(i));r||(r=Array(i));n||(n=[]);for(var a=0;a=n[2]||n[1]>=n[3]){var o=_V(t,2);o[0]===o[2]&&(o[2]+=1),o[1]===o[3]&&(o[3]+=1),n[0]=o[0],n[1]=o[1],n[2]=o[2],n[3]=o[3]}var s=n[0],l=n[1],u=n[2],c=n[3],h=1/(u-s),f=1/(c-l),p=Math.max(u-s,c-l),d=new Int32Array(i),g=0;(function n(i,a,o,s,l,u){var c=.5*o;var h=s+1;var f=l-s;r[g]=f;d[g++]=u;for(var p=0;p<2;++p)for(var v=0;v<2;++v){var m=i+p*c,y=a+v*c,x=MU(t,e,h,l,m,y,m+c,y+c);if(x!==h){if(x-h>=Math.max(.9*f,32)){var b=l+s>>>1;n(m,y,c,h,b,u+1),h=b}n(m,y,c,h,x,u+1),h=x}}})(s,l,p,0,i,0),pU(d,t,e,r,i);for(var v=[],m=0,y=i,g=i-1;g>=0;--g){t[2*g]=(t[2*g]-s)*h,t[2*g+1]=(t[2*g+1]-l)*f;var x=d[g];x!==m&&(v.push(new AU(p*Math.pow(.5,x),g+1,y-(g+1))),y=g+1,m=x)}return v.push(new AU(p*Math.pow(.5,x+1),0,y)),v};function MU(t,e,r,n,i,a,o,s){for(var l=r,u=r;u 1.0) {\n discard;\n }\n\n float centerFraction = fragBorderSize == 0. ? 2. : fragSize / (fragSize + fragBorderSize + 1.25);\n\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, 1.);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"]),vert:E_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth, fragBorderSize, fragSize;\n\nvoid main() {\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n fragBorderSize = borderSize;\n fragSize = size;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragWidth = 1. / gl_PointSize;\n}\n"]),uniforms:{color:function(t,e){var r=e.color.length?e.color[0]:e.color;return c.slice(4*r,4*r+4).map(function(t){return t/255})},borderColor:function(t,e){var r=e.borderColor.length?e.borderColor[0]:e.borderColor;return c.slice(4*r,4*r+4).map(function(t){return t/255})},pixelRatio:t.context("pixelRatio"),palette:l,paletteSize:function(t,e){return[v,l.height]},scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translate:t.prop("translate"),translateFract:t.prop("translateFract"),opacity:t.prop("opacity"),marker:t.prop("marker")},attributes:{position:a,positionFract:o,size:y.attributes.size,borderSize:y.attributes.borderSize}}));else{var x=Us({},y);x.frag=E_(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n //max-distance alpha\n if (dist < 0.003) discard;\n\n //null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]),x.vert=E_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n\t\tfragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]),r=t(x);var b=Us({},y);b.frag=E_(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif(radius > 1.0 + delta) {\n\t\tdiscard;\n\t\treturn;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]),b.vert=E_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\nattribute float size, borderSize;\nattribute vec2 colorId, borderColorId;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvoid main() {\n vec4 color = texture2D(palette, paletteCoord(colorId));\n vec4 borderColor = texture2D(palette, paletteCoord(borderColorId));\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n\t\t\t+ (positionFract + translateFract) * scale\n\t\t\t+ (position + translate) * scaleFract\n\t\t\t+ (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = borderSize == 0. ? 2. : 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]),n=t(b)}function _(t){t?k(t):null===t&&L(),w()}function w(t){if("number"==typeof t)return M(t);Array.isArray(t)?t.forEach(function(t,e){if(null!=t)return t.length?M(t,e):M(t)}):p.forEach(function(t,e){t&&M(e)})}function M(e,i){var a;if("number"==typeof e&&(e=p[e]),Array.isArray(e)&&(a=e,e=p[i]),e&&e.count&&e.opacity){var o;if(a){o=Array(e.count);for(var s=0;s1)){var p=f.offset,g=f.count+p,v=fU.ge(l,n[0],p,g-1),m=fU.lt(l,n[2],v,g-1)+1;if(!(m<=v))if(r){var y=x(t.data.subarray(v,m),r);o.push(Us({},e,{elements:y,marker:d[u],offset:0,count:y.length}))}else o.push(Us({},e,{elements:t.elements,marker:d[u],offset:v,count:m-v}))}}function x(t,e){for(var r=[],n=0,a=t.length;ni)){l.snap=!0;var h=l.x=Array(u),f=l.w=Array(u),p=void 0;if(n.length>1){p=Array(2*u);for(var d=0;d=0)return n;if(e instanceof Uint8Array||e instanceof Uint8ClampedArray)r=e;else{r=new Uint8Array(e.length);for(var i=0,a=e.length;i1)for(var r=.25*(t=t.slice()).length%v;r7&&(r.push(p.splice(0,7)),p.unshift("C"));break;case"S":var g=u,v=c;"C"!=e&&"S"!=e||(g+=g-n,v+=v-i),p=["C",g,v,p[1],p[2],p[3],p[4]];break;case"T":"Q"==e||"T"==e?(s=2*u-s,l=2*c-l):(s=u,l=c),p=FU(u,c,s,l,p[1],p[2]);break;case"Q":s=p[1],l=p[2],p=FU(u,c,p[1],p[2],p[3],p[4]);break;case"L":p=RU(u,c,p[1],p[2]);break;case"H":p=RU(u,c,p[1],c);break;case"V":p=RU(u,c,u,p[1]);break;case"Z":p=RU(u,c,a,o)}e=d,u=p[p.length-2],c=p[p.length-1],p.length>4?(n=p[p.length-4],i=p[p.length-3]):(n=u,i=c),r.push(p)}return r};function RU(t,e,r,n){return["C",t,e,r,n,r,n]}function FU(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}function BU(t,e,r,n,i,a,o,s,l,u){if(u)x=u[0],b=u[1],m=u[2],y=u[3];else{var c=NU(t,e,-i);t=c.x,e=c.y;var h=(t-(s=(c=NU(s,l,-i)).x))/2,f=(e-(l=c.y))/2,p=h*h/(r*r)+f*f/(n*n);p>1&&(r*=p=Math.sqrt(p),n*=p);var d=r*r,g=n*n,v=(a==o?-1:1)*Math.sqrt(Math.abs((d*g-d*f*f-g*h*h)/(d*f*f+g*h*h)));v==1/0&&(v=1);var m=v*r*f/n+(t+s)/2,y=v*-n*h/r+(e+l)/2,x=Math.asin(((e-y)/n).toFixed(9)),b=Math.asin(((l-y)/n).toFixed(9));x=tb&&(x-=2*IU),!o&&b>x&&(b-=2*IU)}if(Math.abs(b-x)>DU){var _=b,w=s,M=l;b=x+DU*(o&&b>x?1:-1);var A=BU(s=m+r*Math.cos(b),l=y+n*Math.sin(b),r,n,i,0,o,w,M,[b,_,m,y])}var k=Math.tan((b-x)/4),T=4/3*r*k,S=4/3*n*k,E=[2*t-(t+T*Math.sin(x)),2*e-(e-S*Math.cos(x)),s+T*Math.sin(b),l-S*Math.cos(b),s,l];if(u)return E;A&&(E=E.concat(A));for(var C=0;C4))},HU=function(t){var e=[];return t.replace(WU,function(t,r,n){var i=r.toLowerCase();for(n=function(t){var e=t.match(YU);return e?e.map(Number):[]}(n),"m"==i&&n.length>2&&(e.push([r].concat(n.splice(0,2))),i="l",r="m"==r?"l":"L");;){if(n.length==GU[i])return n.unshift(r),e.push(n);if(n.length=o)return t;switch(t){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return t}}),l=i[n];n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),f(e)?r.showHidden=e:e&&JU._extend(r,e),v(r.showHidden)&&(r.showHidden=!1),v(r.depth)&&(r.depth=2),v(r.colors)&&(r.colors=!1),v(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),l(r,t,r.depth)}function o(t,e){var r=a.styles[e];return r?"\x1b["+a.colors[r][0]+"m"+t+"\x1b["+a.colors[r][1]+"m":t}function s(t,e){return t}function l(t,e,r){if(t.customInspect&&e&&_(e.inspect)&&e.inspect!==JU.inspect&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return g(n)||(n=l(t,n,r)),n}var i=function(t,e){if(v(e))return t.stylize("undefined","undefined");if(g(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(d(e))return t.stylize(""+e,"number");if(f(e))return t.stylize(""+e,"boolean");if(p(e))return t.stylize("null","null")}(t,e);if(i)return i;var a=Object.keys(e),o=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(e)),b(e)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return u(e);if(0===a.length){if(_(e)){var s=e.name?": "+e.name:"";return t.stylize("[Function"+s+"]","special")}if(m(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(x(e))return t.stylize(Date.prototype.toString.call(e),"date");if(b(e))return u(e)}var y,w="",M=!1,A=["{","}"];(h(e)&&(M=!0,A=["[","]"]),_(e))&&(w=" [Function"+(e.name?": "+e.name:"")+"]");return m(e)&&(w=" "+RegExp.prototype.toString.call(e)),x(e)&&(w=" "+Date.prototype.toUTCString.call(e)),b(e)&&(w=" "+u(e)),0!==a.length||M&&0!=e.length?r<0?m(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),y=M?function(t,e,r,n,i){for(var a=[],o=0,s=e.length;o=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(y,w,A)):A[0]+w+A[1]}function u(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,e,r,n,i,a){var o,s,u;if((u=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?s=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(s=t.stylize("[Setter]","special")),k(n,i)||(o="["+i+"]"),s||(t.seen.indexOf(u.value)<0?(s=p(r)?l(t,u.value,null):l(t,u.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n")):s=t.stylize("[Circular]","special")),v(o)){if(a&&i.match(/^\d+$/))return s;(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+s}function h(t){return Array.isArray(t)}function f(t){return"boolean"==typeof t}function p(t){return null===t}function d(t){return"number"==typeof t}function g(t){return"string"==typeof t}function v(t){return void 0===t}function m(t){return y(t)&&"[object RegExp]"===w(t)}function y(t){return"object"==typeof t&&null!==t}function x(t){return y(t)&&"[object Date]"===w(t)}function b(t){return y(t)&&("[object Error]"===w(t)||t instanceof Error)}function _(t){return"function"==typeof t}function w(t){return Object.prototype.toString.call(t)}function M(t){return t<10?"0"+t.toString(10):t.toString(10)}JU.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!i[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var r=t.pid;i[e]=function(){var t=JU.format.apply(JU,arguments);console.error("%s %d: %s",e,r,t)}}else i[e]=function(){};return i[e]},JU.inspect=a,a.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]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},JU.isArray=h,JU.isBoolean=f,JU.isNull=p,JU.isNullOrUndefined=function(t){return null==t},JU.isNumber=d,JU.isString=g,JU.isSymbol=function(t){return"symbol"==typeof t},JU.isUndefined=v,JU.isRegExp=m,JU.isObject=y,JU.isDate=x,JU.isError=b,JU.isFunction=_,JU.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},JU.isBuffer=ZU;var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}JU.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[M(t.getHours()),M(t.getMinutes()),M(t.getSeconds())].join(":"),[t.getDate(),A[t.getMonth()],e].join(" ")),JU.format.apply(JU,arguments))},JU.inherits=XU,JU._extend=function(t,e){if(!e||!y(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,Pp,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var KU={};(function(t){"use strict";function e(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);i=0;l--)if(u[l]!==c[l])return!1;for(l=u.length-1;l>=0;l--)if(s=u[l],!g(t[s],e[s],r,n))return!1;return!0}(t,n,a,l))}return a?t===n:t==n}function v(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function m(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function y(t,e,r,n){var i;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&p(i,r,"Missing expected exception"+n);var a="string"==typeof n,o=!t&&JU.isError(i),s=!t&&i&&!r;if((o&&a&&m(i,r)||s)&&p(i,r,"Got unwanted exception"+n),t&&i&&r&&!m(i,r)||!t&&i)throw i}l.AssertionError=function(t){var e;this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=h(f((e=this).actual),128)+" "+e.operator+" "+h(f(e.expected),128),this.generatedMessage=!0);var r=t.stackStartFunction||p;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,a=c(r),o=i.indexOf("\n"+a);if(o>=0){var s=i.indexOf("\n",o+1);i=i.substring(s+1)}this.stack=i}}},JU.inherits(l.AssertionError,Error),l.fail=p,l.ok=d,l.equal=function(t,e,r){t!=e&&p(t,e,r,"==",l.equal)},l.notEqual=function(t,e,r){t==e&&p(t,e,r,"!=",l.notEqual)},l.deepEqual=function(t,e,r){g(t,e,!1)||p(t,e,r,"deepEqual",l.deepEqual)},l.deepStrictEqual=function(t,e,r){g(t,e,!0)||p(t,e,r,"deepStrictEqual",l.deepStrictEqual)},l.notDeepEqual=function(t,e,r){g(t,e,!1)&&p(t,e,r,"notDeepEqual",l.notDeepEqual)},l.notDeepStrictEqual=function t(e,r,n){g(e,r,!0)&&p(e,r,n,"notDeepStrictEqual",t)},l.strictEqual=function(t,e,r){t!==e&&p(t,e,r,"===",l.strictEqual)},l.notStrictEqual=function(t,e,r){t===e&&p(t,e,r,"!==",l.notStrictEqual)},l.throws=function(t,e,r){y(!0,t,e,r)},l.doesNotThrow=function(t,e,r){y(!1,t,e,r)},l.ifError=function(t){if(t)throw t};var x=Object.keys||function(t){var e=[];for(var r in t)n.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var QU={};Object.defineProperty(QU,"__esModule",{value:!0});var $U=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){i=!0,a=t}finally{try{!n&&s.return&&s.return()}finally{if(i)throw a}}return r}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),tq=2*Math.PI,eq=function(t,e,r,n,i,a,o){var s=t.x,l=t.y;return{x:n*(s*=e)-i*(l*=r)+a,y:i*s+n*l+o}},rq=function(t,e){var r=4/3*Math.tan(e/4),n=Math.cos(t),i=Math.sin(t),a=Math.cos(t+e),o=Math.sin(t+e);return[{x:n-i*r,y:i+n*r},{x:a+o*r,y:o-a*r},{x:a,y:o}]},nq=function(t,e,r,n){var i=t*n-e*r<0?-1:1,a=(t*r+e*n)/(Math.sqrt(t*t+e*e)*Math.sqrt(t*t+e*e));return a>1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)};QU.default=function(t){var e=t.px,r=t.py,n=t.cx,i=t.cy,a=t.rx,o=t.ry,s=t.xAxisRotation,l=void 0===s?0:s,u=t.largeArcFlag,c=void 0===u?0:u,h=t.sweepFlag,f=void 0===h?0:h,p=[];if(0===a||0===o)return[];var d=Math.sin(l*tq/360),g=Math.cos(l*tq/360),v=g*(e-n)/2+d*(r-i)/2,m=-d*(e-n)/2+g*(r-i)/2;if(0===v&&0===m)return[];a=Math.abs(a),o=Math.abs(o);var y=Math.pow(v,2)/Math.pow(a,2)+Math.pow(m,2)/Math.pow(o,2);y>1&&(a*=Math.sqrt(y),o*=Math.sqrt(y));var x=function(t,e,r,n,i,a,o,s,l,u,c,h){var f=Math.pow(i,2),p=Math.pow(a,2),d=Math.pow(c,2),g=Math.pow(h,2),v=f*p-f*g-p*d;v<0&&(v=0),v/=f*g+p*d;var m=(v=Math.sqrt(v)*(o===s?-1:1))*i/a*h,y=v*-a/i*c,x=u*m-l*y+(t+r)/2,b=l*m+u*y+(e+n)/2,_=(c-m)/i,w=(h-y)/a,M=(-c-m)/i,A=(-h-y)/a,k=nq(1,0,_,w),T=nq(_,w,M,A);return 0===s&&T>0&&(T-=tq),1===s&&T<0&&(T+=tq),[x,b,k,T]}(e,r,n,i,a,o,c,f,d,g,v,m),b=$U(x,4),_=b[0],w=b[1],M=b[2],A=b[3],k=Math.max(Math.ceil(Math.abs(A)/(tq/4)),1);A/=k;for(var T=0;T4?(n=p[p.length-4],i=p[p.length-3]):(n=u,i=c),r.push(p)}return r};function aq(t,e,r,n){return["C",t,e,r,n,r,n]}function oq(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}var sq=function(t){Array.isArray(t)&&1===t.length&&"string"==typeof t[0]&&(t=t[0]);"string"==typeof t&&(KU(qU(t),"String is not an SVG path."),t=HU(t));if(KU(Array.isArray(t),"Argument should be a string or an array of path segments."),t=PU(t),!(t=iq(t)).length)return[0,0,0,0];for(var e=[1/0,1/0,-1/0,-1/0],r=0,n=t.length;re[2]&&(e[2]=i[a+0]),i[a+1]>e[3]&&(e[3]=i[a+1]);return e};var lq={};(function(t){"use strict";var e=document.createElement("canvas"),r=e.getContext("2d");lq=function(n,i){if(!qU(n))throw Error("Argument should be valid svg path string");i||(i={});var a,o;i.shape?(a=i.shape[0],o=i.shape[1]):(a=e.width=i.w||i.width||200,o=e.height=i.h||i.height||200);var s=Math.min(a,o),l=i.stroke||0,u=i.viewbox||i.viewBox||sq(n),c=[a/(u[2]-u[0]),o/(u[3]-u[1])],h=Math.min(c[0]||0,c[1]||0)/2;r.fillStyle="black",r.fillRect(0,0,a,o),r.fillStyle="white",l&&("number"!=typeof l&&(l=1),r.strokeStyle=l>0?"white":"black",r.lineWidth=Math.abs(l));if(r.translate(.5*a,.5*o),r.scale(h,h),t.Path2D){var f=new Path2D(n);r.fill(f),l&&r.stroke(f)}else{var p=HU(n);UU(r,p),r.fill(),l&&r.stroke()}return r.setTransform(1,0,0,1,0,0),EU(r,{cutoff:null!=i.cutoff?i.cutoff:.5,radius:null!=i.radius?i.radius:.5*s})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var uq={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]},cq={},hq=m.extendFlat,fq=ye.overrideAll,pq=Zr.line,dq=Zr.marker,gq=dq.line,vq=cq=fq({x:Zr.x,x0:Zr.x0,dx:Zr.dx,y:Zr.y,y0:Zr.y0,dy:Zr.dy,text:hq({},Zr.text,{}),mode:{valType:"flaglist",flags:["lines","markers"],extras:["none"]},line:{color:pq.color,width:pq.width,dash:{valType:"enumerated",values:Object.keys(uq),dflt:"solid"}},marker:hq({},De(),{symbol:dq.symbol,size:dq.size,sizeref:dq.sizeref,sizemin:dq.sizemin,sizemode:dq.sizemode,opacity:dq.opacity,showscale:dq.showscale,colorbar:dq.colorbar,line:hq({},De(),{width:gq.width})}),connectgaps:Zr.connectgaps,fill:Zr.fill,fillcolor:Zr.fillcolor,hoveron:Zr.hoveron,selected:{marker:Zr.selected.marker},unselected:{marker:Zr.unselected.marker},opacity:E.opacity},"calc","nested");vq.x.editType=vq.y.editType=vq.x0.editType=vq.y0.editType="calc+clearAxisTypes";var mq=function(t,e,r,n){function i(r,n){return ne.coerce(t,e,cq,r,n)}var a=!!t.marker&&/-open/.test(t.marker.symbol),o=Tr.isBubble(t),s=Ta(t,e,n,i);if(s){i("text"),i("mode",s1,o=r.error_x&&!0===r.error_x.visible,s=r.error_y&&!0===r.error_y.visible,l=Tr.hasMarkers(r),u=!!r.fill&&"none"!==r.fill),o||s){var A=P.getComponentMethod("errorbars","calcFromTrace")(r,_);o&&(v=C("x",r.error_x,A)),s&&(m=C("y",r.error_y,A))}if(a){(h={}).thickness=r.line.width,h.color=r.line.color,h.opacity=r.opacity,h.overlay=!0;var k=(uq[r.line.dash]||[1]).slice();for(i=0;ic?"rect":l?"rect":"round",T&&r.connectgaps){var S=b[0],E=b[1];for(i=0;i0){e+=Math.abs(i(t[0]));for(var r=1;r2){for(l=0;li.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(o=i.maxw*i.maxh-t*r)a.free)){if(r===a.h)return this.allocShelf(s,t,r,n);r>a.h||rc)&&(h=2*Math.max(t,c)),(ll)&&(u=2*Math.max(r,l)),this.resize(h,u),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;rthis.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,a,o){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=a||n,this.maxh=o||i,this.refcount=0}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t},"object"==typeof r&&void 0!==e?e.exports=i():n.ShelfPack=i()},{}],6:[function(t,e,r){function n(t,e,r,n,i,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=i||"sans-serif",this.fontWeight=a||"normal",this.radius=r||8;var o=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=o,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(o*o),this.gridInner=new Float64Array(o*o),this.f=new Float64Array(o),this.d=new Float64Array(o),this.z=new Float64Array(o+1),this.v=new Int16Array(o),this.middle=Math.round(o/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1))}function i(t,e,r,n,i,o,s){for(var l=0;ln)return n;for(;ra?r=i:n=i,i=.5*(n-r)+r}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},{}],8:[function(t,e,r){e.exports.VectorTile=t("./lib/vectortile.js"),e.exports.VectorTileFeature=t("./lib/vectortilefeature.js"),e.exports.VectorTileLayer=t("./lib/vectortilelayer.js")},{"./lib/vectortile.js":9,"./lib/vectortilefeature.js":10,"./lib/vectortilelayer.js":11}],9:[function(t,e,r){function n(t,e,r){if(3===t){var n=new i(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n)}}var i=t("./vectortilelayer");e.exports=function(t,e){this.layers=t.readFields(n,{},e)}},{"./vectortilelayer":11}],10:[function(t,e,r){function n(t,e,r,n,a){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=a,t.readFields(i,this,e)}function i(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3}if(i--,1===n||2===n)a+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&l.push(e),e=[]),e.push(new o(a,s));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone())}}return e&&l.push(e),l},n.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,l=1/0,u=-1/0;t.pos>3}if(n--,1===r||2===r)i+=t.readSVarint(),a+=t.readSVarint(),is&&(s=i),au&&(u=a);else if(7!==r)throw new Error("unknown command "+r)}return[o,l,s,u]},n.prototype.toGeoJSON=function(t,e,r){function i(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}var a=t("./vectortilefeature.js");e.exports=n,n.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new a(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":10}],12:[function(t,e,r){var n;n=this,function(t){function e(t,e,n){var i=r(256*t,256*(e=Math.pow(2,n)-e-1),n),a=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+a[0]+","+a[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return[t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}t.getURL=function(t,r,n,i,a,o){return o=o||{},t+"?"+["bbox="+e(n,i,a),"format="+(o.format||"image/png"),"service="+(o.service||"WMS"),"version="+(o.version||"1.1.1"),"request="+(o.request||"GetMap"),"srs="+(o.srs||"EPSG:3857"),"width="+(o.width||256),"height="+(o.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.WhooTS=n.WhooTS||{})},{}],13:[function(t,e,r){function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return function(t){return t<0?0:t>1?1:t}("%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}var s={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};try{r.parseCSSColor=function(t){var e,r=t.replace(/ /g,"").toLowerCase();if(r in s)return s[r].slice();if("#"===r[0])return 4===r.length?(e=parseInt(r.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===r.length&&(e=parseInt(r.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var l=r.indexOf("("),u=r.indexOf(")");if(-1!==l&&u+1===r.length){var c=r.substr(0,l),h=r.substr(l+1,u-(l+1)).split(","),f=1;switch(c){case"rgba":if(4!==h.length)return null;f=a(h.pop());case"rgb":return 3!==h.length?null:[i(h[0]),i(h[1]),i(h[2]),f];case"hsla":if(4!==h.length)return null;f=a(h.pop());case"hsl":if(3!==h.length)return null;var p=(parseFloat(h[0])%360+360)%360/360,d=a(h[1]),g=a(h[2]),v=g<=.5?g*(d+1):g+d-g*d,m=2*g-v;return[n(255*o(m,v,p+1/3)),n(255*o(m,v,p)),n(255*o(m,v,p-1/3)),f];default:return null}}return null}}catch(t){}},{}],14:[function(t,e,r){function n(t,e,r){r=r||2;var n,s,l,u,c,p,g,v=e&&e.length,m=v?e[0]*r:t.length,y=i(t,0,m,r,!0),x=[];if(!y)return x;if(v&&(y=function(t,e,r,n){var o,s,l,u,c,p=[];for(o=0,s=e.length;o80*r){n=l=t[0],s=u=t[1];for(var b=r;bl&&(l=c),p>u&&(u=p);g=0!==(g=Math.max(l-n,u-s))?1/g:0}return o(y,x,r,n,s,g),x}function i(t,e,r,n,i){var a,o;if(i===k(t,e,r,n)>0)for(a=e;a=e;a-=n)o=w(a,t[a],t[a+1],o);return o&&y(o,o.next)&&(M(o),o=o.next),o}function a(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(M(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function o(t,e,r,n,i,h,f){if(t){!f&&h&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=p(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,u=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,u*=2}while(o>1)}(i)}(t,n,i,h);for(var d,g,v=t;t.prev!==t.next;)if(d=t.prev,g=t.next,h?l(t,n,i,h):s(t))e.push(d.i/r),e.push(t.i/r),e.push(g.i/r),M(t),t=g.next,v=g.next;else if((t=g)===v){f?1===f?o(t=u(t,e,r),e,r,n,i,h,2):2===f&&c(t,e,r,n,i,h):o(a(t),e,r,n,i,h,1);break}}}function s(t){var e=t.prev,r=t,n=t.next;if(m(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(g(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&m(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function l(t,e,r,n){var i=t.prev,a=t,o=t.next;if(m(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,c=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,h=p(s,l,e,r,n),f=p(u,c,e,r,n),d=t.prevZ,v=t.nextZ;d&&d.z>=h&&v&&v.z<=f;){if(d!==t.prev&&d!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&m(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,v!==t.prev&&v!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;d&&d.z>=h;){if(d!==t.prev&&d!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&m(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;v&&v.z<=f;){if(v!==t.prev&&v!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function u(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!y(i,a)&&x(i,n,n.next,a)&&b(i,a)&&b(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),M(n),M(n.next),n=t=a),n=n.next}while(n!==t);return n}function c(t,e,r,n,i,s){var l=t;do{for(var u=l.next.next;u!==l.prev;){if(l.i!==u.i&&v(l,u)){var c=_(l,u);return l=a(l,l.next),c=a(c,c.next),o(l,e,r,n,i,s),void o(c,e,r,n,i,s)}u=u.next}l=l.next}while(l!==t)}function h(t,e){return t.x-e.x}function f(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&i!==n.x&&g(ar.x)&&b(n,t)&&(r=n,f=l),n=n.next;return r}(t,e)){var r=_(e,t);a(r,r.next)}}function p(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&x(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&b(t,e)&&b(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function m(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,r,n){return!!(y(t,e)&&y(r,n)||y(t,n)&&y(r,e))||m(t,e,r)>0!=m(t,e,n)>0&&m(r,n,t)>0!=m(r,n,e)>0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function _(t,e){var r=new A(t.i,t.x,t.y),n=new A(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function w(t,e,r,n){var i=new A(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function M(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function A(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function k(t,e,r,n){for(var i=0,a=e,o=r-n;a0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],15:[function(t,e,r){function n(t,e){return function(r){return t(r,e)}}function i(t,e){e=!!e,t[0]=a(t[0],e);for(var r=1;r=0}(t)===e?t:t.reverse()}var o=t("@mapbox/geojson-area");e.exports=function t(e,r){switch(e&&e.type||null){case"FeatureCollection":return e.features=e.features.map(n(t,r)),e;case"Feature":return e.geometry=t(e.geometry,r),e;case"Polygon":case"MultiPolygon":return function(t,e){return"Polygon"===t.type?t.coordinates=i(t.coordinates,e):"MultiPolygon"===t.type&&(t.coordinates=t.coordinates.map(n(i,e))),t}(e,r);default:return e}}},{"@mapbox/geojson-area":1}],16:[function(t,e,r){function n(t,e,r,n,i){for(var a=0;a=r&&o<=n&&(e.push(t[a]),e.push(t[a+1]),e.push(t[a+2]))}}function i(t,e,r,n,i,a){for(var u=[],c=0===i?s:l,h=0;h=r&&c(u,f,p,g,v,r):m>n?y<=n&&c(u,f,p,g,v,n):o(u,f,p,d),y=r&&(c(u,f,p,g,v,r),x=!0),y>n&&m<=n&&(c(u,f,p,g,v,n),x=!0),!a&&x&&(u.size=t.size,e.push(u),u=[])}var b=t.length-3;f=t[b],p=t[b+1],d=t[b+2],(m=0===i?f:p)>=r&&m<=n&&o(u,f,p,d),b=u.length-3,a&&b>=3&&(u[b]!==u[0]||u[b+1]!==u[1])&&o(u,u[0],u[1],u[2]),u.length&&(u.size=t.size,e.push(u))}function a(t,e,r,n,a,o){for(var s=0;s=(r/=e)&&c<=o)return t;if(l>o||c=r&&m<=o)h.push(p);else if(!(v>o||m0&&(o+=n?(i*f-h*a)/2:Math.sqrt(Math.pow(h-i,2)+Math.pow(f-a,2))),i=h,a=f}var p=e.length-3;e[2]=1,u(e,0,p,r),e[p+2]=1,e.size=Math.abs(o)}function o(t,e,r,n){for(var i=0;i1?1:r}e.exports=function(t,e){var r=[];if("FeatureCollection"===t.type)for(var i=0;i24)throw new Error("maxZoom should be in the 0-24 range");var n=1<1&&console.time("creation"),g=this.tiles[d]=u(t,p,r,n,v,e===h.maxZoom),this.tileCoords.push({z:e,x:r,y:n}),f)){f>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,g.numFeatures,g.numPoints,g.numSimplified),console.timeEnd("creation"));var m="z"+e;this.stats[m]=(this.stats[m]||0)+1,this.total++}if(g.source=t,a){if(e===h.maxZoom||e===a)continue;var y=1<1&&console.time("clipping");var x,b,_,w,M,A,k=.5*h.buffer/h.extent,T=.5-k,S=.5+k,E=1+k;x=b=_=w=null,M=s(t,p,r-k,r+S,0,g.minX,g.maxX),A=s(t,p,r+T,r+E,0,g.minX,g.maxX),t=null,M&&(x=s(M,p,n-k,n+S,1,g.minY,g.maxY),b=s(M,p,n+T,n+E,1,g.minY,g.maxY),M=null),A&&(_=s(A,p,n-k,n+S,1,g.minY,g.maxY),w=s(A,p,n+T,n+E,1,g.minY,g.maxY),A=null),f>1&&console.timeEnd("clipping"),c.push(x||[],e+1,2*r,2*n),c.push(b||[],e+1,2*r,2*n+1),c.push(_||[],e+1,2*r+1,2*n),c.push(w||[],e+1,2*r+1,2*n+1)}}},n.prototype.getTile=function(t,e,r){var n=this.options,a=n.extent,s=n.debug;if(t<0||t>24)return null;var l=1<1&&console.log("drilling down to z%d-%d-%d",t,e,r);for(var c,h=t,f=e,p=r;!c&&h>0;)h--,f=Math.floor(f/2),p=Math.floor(p/2),c=this.tiles[i(h,f,p)];return c&&c.source?(s>1&&console.log("found parent tile z%d-%d-%d",h,f,p),s>1&&console.time("drilling down"),this.splitTile(c.source,h,f,p,t,e,r),s>1&&console.timeEnd("drilling down"),this.tiles[u]?o.tile(this.tiles[u],a):null):null}},{"./clip":16,"./convert":17,"./tile":21,"./transform":22,"./wrap":23}],20:[function(t,e,r){function n(t,e,r,n,i,a){var o=i-r,s=a-n;if(0!==o||0!==s){var l=((t-r)*o+(e-n)*s)/(o*o+s*s);l>1?(r=i,n=a):l>0&&(r+=o*l,n+=s*l)}return(o=t-r)*o+(s=e-n)*s}e.exports=function t(e,r,i,a){for(var o,s=a,l=e[r],u=e[r+1],c=e[i],h=e[i+1],f=r+3;fs&&(o=f,s=p)}s>a&&(o-r>3&&t(e,r,o,a),e[o+2]=s,i-o>3&&t(e,o,i,a))}},{}],21:[function(t,e,r){function n(t,e,r,n){var a=e.geometry,o=e.type,s=[];if("Point"===o||"MultiPoint"===o)for(var l=0;ls)&&(r.numSimplified++,l.push(e[u]),l.push(e[u+1])),r.numPoints++;a&&function(t,e){for(var r=0,n=0,i=t.length,a=i-2;n0===e)for(n=0,i=t.length;ns.maxX&&(s.maxX=h),f>s.maxY&&(s.maxY=f)}return s}},{}],22:[function(t,e,r){function n(t,e,r,n,i,a){return[Math.round(r*(t*n-i)),Math.round(r*(e*n-a))]}r.tile=function(t,e){if(t.transformed)return t;var r,i,a,o=t.z2,s=t.x,l=t.y;for(r=0;r=u[f+0]&&n>=u[f+1]?(o[h]=!0,a.push(l[h])):o[h]=!1}}},n.prototype._forEachCell=function(t,e,r,n,i,a,o){for(var s=this._convertToCellCoord(t),l=this._convertToCellCoord(e),u=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=s;h<=u;h++)for(var f=l;f<=c;f++){var p=this.d*f+h;if(i.call(this,t,e,r,n,p,a,o))return}},n.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},n.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=i+this.cells.length+1+1,r=0,n=0;n>1,c=-7,h=r?i-1:0,f=r?-1:1,p=t[e+h];for(h+=f,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}},{}],26:[function(t,e,r){function n(t,e,r,n,s){e=e||i,r=r||a,s=s||Array,this.nodeSize=n||64,this.points=t,this.ids=new s(t.length),this.coords=new s(2*t.length);for(var l=0;l=r&&s<=i&&l>=n&&l<=a&&c.push(t[d]);else{var g=Math.floor((p+f)/2);s=e[2*g],l=e[2*g+1],s>=r&&s<=i&&l>=n&&l<=a&&c.push(t[g]);var v=(h+1)%2;(0===h?r<=s:n<=l)&&(u.push(p),u.push(g-1),u.push(v)),(0===h?i>=s:a>=l)&&(u.push(g+1),u.push(f),u.push(v))}}return c}},{}],28:[function(t,e,r){function n(t,e,r,n){i(t,r,n),i(e,2*r,2*n),i(e,2*r+1,2*n+1)}function i(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}e.exports=function t(e,r,i,a,o,s){if(!(o-a<=i)){var l=Math.floor((a+o)/2);(function t(e,r,i,a,o,s){for(;o>a;){if(o-a>600){var l=o-a+1,u=i-a+1,c=Math.log(l),h=.5*Math.exp(2*c/3),f=.5*Math.sqrt(c*h*(l-h)/l)*(u-l/2<0?-1:1);t(e,r,i,Math.max(a,Math.floor(i-u*h/l+f)),Math.min(o,Math.floor(i+(l-u)*h/l+f)),s)}var p=r[2*i+s],d=a,g=o;for(n(e,r,a,i),r[2*o+s]>p&&n(e,r,a,o);dp;)g--}r[2*a+s]===p?n(e,r,a,g):n(e,r,++g,o),g<=i&&(a=g+1),i<=g&&(o=g-1)}})(e,r,l,a,o,s%2),t(e,r,i,a,l-1,s+1),t(e,r,i,l+1,o,s+1)}}},{}],29:[function(t,e,r){function n(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}e.exports=function(t,e,r,i,a,o){for(var s=[0,t.length-1,0],l=[],u=a*a;s.length;){var c=s.pop(),h=s.pop(),f=s.pop();if(h-f<=o)for(var p=f;p<=h;p++)n(e[2*p],e[2*p+1],r,i)<=u&&l.push(t[p]);else{var d=Math.floor((f+h)/2),g=e[2*d],v=e[2*d+1];n(g,v,r,i)<=u&&l.push(t[d]);var m=(c+1)%2;(0===c?r-a<=g:i-a<=v)&&(s.push(f),s.push(d-1),s.push(m)),(0===c?r+a>=g:i+a>=v)&&(s.push(d+1),s.push(h),s.push(m))}}return l}},{}],30:[function(t,e,r){function n(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}function i(t){return t.type===n.Bytes?t.readVarint()+t.pos:t.pos+1}function a(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function o(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}function s(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24}function y(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}e.exports=n;var x=t("ieee754");n.Varint=0,n.Fixed64=1,n.Bytes=2,n.Fixed32=5;n.prototype={destroy:function(){this.buf=null},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=y(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=v(this.buf,this.pos)+4294967296*v(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=v(this.buf,this.pos)+4294967296*y(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=x.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=x.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,o=r.buf;if(n=(112&(i=o[r.pos++]))>>4,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<3,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<10,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<17,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<24,i<128)return a(t,n,e);if(n|=(1&(i=o[r.pos++]))<<31,i<128)return a(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(a=t[i+1]))&&(u=(31&l)<<6|63&a)<=127&&(u=null):3===c?(a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&((u=(15&l)<<12|(63&a)<<6|63&o)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&((u=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=i(this);for(t=t||[];this.pos127;);else if(e===n.Bytes)this.pos=this.readVarint()+this.pos;else if(e===n.Fixed32)this.pos+=4;else{if(e!==n.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128)}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&o(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(t){this.realloc(4),x.write(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),x.write(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&o(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,n.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){this.writeMessage(t,s,e)},writePackedSVarint:function(t,e){this.writeMessage(t,l,e)},writePackedBoolean:function(t,e){this.writeMessage(t,h,e)},writePackedFloat:function(t,e){this.writeMessage(t,u,e)},writePackedDouble:function(t,e){this.writeMessage(t,c,e)},writePackedFixed32:function(t,e){this.writeMessage(t,f,e)},writePackedSFixed32:function(t,e){this.writeMessage(t,p,e)},writePackedFixed64:function(t,e){this.writeMessage(t,d,e)},writePackedSFixed64:function(t,e){this.writeMessage(t,g,e)},writeBytesField:function(t,e){this.writeTag(t,n.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,n.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,n.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,n.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}}},{ieee754:25}],31:[function(t,e,r){function n(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function i(t,e){return te?1:0}e.exports=function t(e,r,a,o,s){for(a=a||0,o=o||e.length-1,s=s||i;o>a;){if(o-a>600){var l=o-a+1,u=r-a+1,c=Math.log(l),h=.5*Math.exp(2*c/3),f=.5*Math.sqrt(c*h*(l-h)/l)*(u-l/2<0?-1:1);t(e,r,Math.max(a,Math.floor(r-u*h/l+f)),Math.min(o,Math.floor(r+(l-u)*h/l+f)),s)}var p=e[r],d=a,g=o;for(n(e,a,r),s(e[o],p)>0&&n(e,a,o);d0;)g--}0===s(e[a],p)?n(e,a,g):n(e,++g,o),g<=r&&(a=g+1),r<=g&&(o=g-1)}}},{}],32:[function(t,e,r){function n(t){this.options=c(Object.create(this.options),t),this.trees=new Array(this.options.maxZoom+1)}function i(t,e,r,n,i){return{x:t,y:e,zoom:1/0,id:n,properties:i,parentId:-1,numPoints:r}}function a(t,e){var r=t.geometry.coordinates;return{x:l(r[0]),y:u(r[1]),zoom:1/0,id:e,parentId:-1}}function o(t){return{type:"Feature",properties:s(t),geometry:{type:"Point",coordinates:[function(t){return 360*(t-.5)}(t.x),function(t){var e=(180-360*t)*Math.PI/180;return 360*Math.atan(Math.exp(e))/Math.PI-90}(t.y)]}}}function s(t){var e=t.numPoints,r=e>=1e4?Math.round(e/1e3)+"k":e>=1e3?Math.round(e/100)/10+"k":e;return c(c({},t.properties),{cluster:!0,cluster_id:t.id,point_count:e,point_count_abbreviated:r})}function l(t){return t/360+.5}function u(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function c(t,e){for(var r in e)t[r]=e[r];return t}function h(t){return t.x}function f(t){return t.y}var p=t("kdbush");e.exports=function(t){return new n(t)},n.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(t){return t}},load:function(t){var e=this.options.log;e&&console.time("total time");var r="prepare "+t.length+" points";e&&console.time(r),this.points=t;var n=t.map(a);e&&console.timeEnd(r);for(var i=this.options.maxZoom;i>=this.options.minZoom;i--){var o=+Date.now();this.trees[i+1]=p(n,h,f,this.options.nodeSize,Float32Array),n=this._cluster(n,i),e&&console.log("z%d: %d clusters in %dms",i,n.length,+Date.now()-o)}return this.trees[this.options.minZoom]=p(n,h,f,this.options.nodeSize,Float32Array),e&&console.timeEnd("total time"),this},getClusters:function(t,e){for(var r=this.trees[this._limitZoom(e)],n=r.range(l(t[0]),u(t[3]),l(t[2]),u(t[1])),i=[],a=0;a0)for(var r=this.length>>1;r>=0;r--)this._down(r)}function i(t,e){return te?1:0}e.exports=n,n.prototype={push:function(t){this.data.push(t),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var t=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),t}},peek:function(){return this.data[0]},_up:function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i}e[t]=n},_down:function(t){for(var e=this.data,r=this.compare,n=this.length,i=n>>1,a=e[t];t=0)break;e[t]=l,t=o}e[t]=a}}},{}],34:[function(t,e,r){function n(t){var e=new h;return function(t,e){for(var r in t.layers)e.writeMessage(3,i,t.layers[r])}(t,e),e.finish()}function i(t,e){e.writeVarintField(15,t.version||1),e.writeStringField(1,t.name||""),e.writeVarintField(5,t.extent||4096);var r,n={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function u(t,e){for(var r=t.loadGeometry(),n=t.type,i=0,a=0,o=r.length,u=0;u=c||h<0||h>=c)){var f=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray),p=f.vertexLength;n(r.layoutVertexArray,u,h,-1,-1),n(r.layoutVertexArray,u,h,1,-1),n(r.layoutVertexArray,u,h,1,1),n(r.layoutVertexArray,u,h,-1,1),r.indexArray.emplaceBack(p,p+1,p+2),r.indexArray.emplaceBack(p,p+3,p+2),f.vertexLength+=4,f.primitiveLength+=2}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},h("CircleBucket",f,{omit:["layers"]}),e.exports=f},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./circle_attributes":41}],43:[function(t,e,r){arguments[4][41][0].apply(r,arguments)},{"../../util/struct_array":271,dup:41}],44:[function(t,e,r){var n=t("../array_types").FillLayoutArray,i=t("./fill_attributes").members,a=t("../segment").SegmentVector,o=t("../program_configuration").ProgramConfigurationSet,s=t("../index_array_type"),l=s.LineIndexArray,u=s.TriangleIndexArray,c=t("../load_geometry"),h=t("earcut"),f=t("../../util/classify_rings"),p=t("../../util/web_worker_transfer").register,d=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new n,this.indexArray=new u,this.indexArray2=new l,this.programConfigurations=new o(i,t.layers,t.zoom),this.segments=new a,this.segments2=new a};d.prototype.populate=function(t,e){for(var r=this,n=0,i=t;nd)||t.y===e.y&&(t.y<0||t.y>d)}function a(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>d})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>d})}var o=t("../array_types").FillExtrusionLayoutArray,s=t("./fill_extrusion_attributes").members,l=t("../segment"),u=l.SegmentVector,c=l.MAX_VERTEX_ARRAY_LENGTH,h=t("../program_configuration").ProgramConfigurationSet,f=t("../index_array_type").TriangleIndexArray,p=t("../load_geometry"),d=t("../extent"),g=t("earcut"),v=t("../../util/classify_rings"),m=t("../../util/web_worker_transfer").register,y=Math.pow(2,13),x=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new o,this.indexArray=new f,this.programConfigurations=new h(s,t.layers,t.zoom),this.segments=new u};x.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=1){var w=y[b-1];if(!i(_,w)){p.vertexLength+4>c&&(p=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray));var M=_.sub(w)._perp()._unit(),A=w.dist(_);x+A>32768&&(x=0),n(r.layoutVertexArray,_.x,_.y,M.x,M.y,0,0,x),n(r.layoutVertexArray,_.x,_.y,M.x,M.y,0,1,x),x+=A,n(r.layoutVertexArray,w.x,w.y,M.x,M.y,0,0,x),n(r.layoutVertexArray,w.x,w.y,M.x,M.y,0,1,x);var k=p.vertexLength;r.indexArray.emplaceBack(k,k+1,k+2),r.indexArray.emplaceBack(k+1,k+2,k+3),p.vertexLength+=4,p.primitiveLength+=2}}}}p.vertexLength+u>c&&(p=r.segments.prepareSegment(u,r.layoutVertexArray,r.indexArray));for(var T=[],S=[],E=p.vertexLength,C=0,L=l;C>6)}var i=t("../array_types").LineLayoutArray,a=t("./line_attributes").members,o=t("../segment").SegmentVector,s=t("../program_configuration").ProgramConfigurationSet,l=t("../index_array_type").TriangleIndexArray,u=t("../load_geometry"),c=t("../extent"),h=t("@mapbox/vector-tile").VectorTileFeature.types,f=t("../../util/web_worker_transfer").register,p=63,d=Math.cos(Math.PI/180*37.5),g=.5,v=Math.pow(2,14)/g,m=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new i,this.indexArray=new l,this.programConfigurations=new s(a,t.layers,t.zoom),this.segments=new o};m.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=2&&t[l-1].equals(t[l-2]);)l--;for(var u=0;uu){var z=v.dist(w);if(z>2*f){var P=v.sub(v.sub(w)._mult(f/z)._round());o.distance+=P.dist(w),o.addCurrentVertex(P,o.distance,A.mult(1),0,0,!1,g),w=P}}var I=w&&M,D=I?r:M?x:b;if(I&&"round"===D&&(Ci&&(D="bevel"),"bevel"===D&&(C>2&&(D="flipbevel"),C100)S=k.clone().mult(-1);else{var O=A.x*k.y-A.y*k.x>0?-1:1,R=C*A.add(k).mag()/A.sub(k).mag();S._perp()._mult(R*O)}o.addCurrentVertex(v,o.distance,S,0,0,!1,g),o.addCurrentVertex(v,o.distance,S.mult(-1),0,0,!1,g)}else if("bevel"===D||"fakeround"===D){var F=A.x*k.y-A.y*k.x>0,B=-Math.sqrt(C*C-1);if(F?(y=0,m=B):(m=0,y=B),_||o.addCurrentVertex(v,o.distance,A,m,y,!1,g),"fakeround"===D){for(var N=Math.floor(8*(.5-(E-.5))),j=void 0,V=0;V=0;U--)j=A.mult((U+1)/(N+1))._add(k)._unit(),o.addPieSliceVertex(v,o.distance,j,F,g)}M&&o.addCurrentVertex(v,o.distance,k,-m,-y,!1,g)}else"butt"===D?(_||o.addCurrentVertex(v,o.distance,A,0,0,!1,g),M&&o.addCurrentVertex(v,o.distance,k,0,0,!1,g)):"square"===D?(_||(o.addCurrentVertex(v,o.distance,A,1,1,!1,g),o.e1=o.e2=-1),M&&o.addCurrentVertex(v,o.distance,k,-1,-1,!1,g)):"round"===D&&(_||(o.addCurrentVertex(v,o.distance,A,0,0,!1,g),o.addCurrentVertex(v,o.distance,A,1,1,!0,g),o.e1=o.e2=-1),M&&(o.addCurrentVertex(v,o.distance,k,-1,-1,!0,g),o.addCurrentVertex(v,o.distance,k,0,0,!1,g)));if(L&&T2*f){var H=v.add(M.sub(v)._mult(f/q)._round());o.distance+=H.dist(v),o.addCurrentVertex(H,o.distance,k.mult(1),0,0,!1,g),v=H}}_=!1}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e)}},m.prototype.addCurrentVertex=function(t,e,r,i,a,o,s){var l,u=this.layoutVertexArray,c=this.indexArray;l=r.clone(),i&&l._sub(r.perp()._mult(i)),n(u,t,l,o,!1,i,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,l=r.mult(-1),a&&l._sub(r.perp()._mult(a)),n(u,t,l,o,!0,-a,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>v/2&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,i,a,o,s))},m.prototype.addPieSliceVertex=function(t,e,r,i,a){r=r.mult(i?-1:1);var o=this.layoutVertexArray,s=this.indexArray;n(o,t,r,!1,i,0,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),i?this.e2=this.e3:this.e1=this.e3},f("LineBucket",m,{omit:["layers"]}),e.exports=m},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./line_attributes":48,"@mapbox/vector-tile":8}],50:[function(t,e,r){var n=t("../../util/struct_array").createLayout,i={symbolLayoutAttributes:n([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),dynamicLayoutAttributes:n([{name:"a_projected_pos",components:3,type:"Float32"}],4),placementOpacityAttributes:n([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),collisionVertexAttributes:n([{name:"a_placed",components:2,type:"Uint8"}],4),collisionBox:n([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),collisionBoxLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),collisionCircleLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),placement:n([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),glyphOffset:n([{type:"Float32",name:"offsetX"}]),lineVertex:n([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}])};e.exports=i},{"../../util/struct_array":271}],51:[function(t,e,r){function n(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,Math.round(64*n),Math.round(64*i),a,o,s?s[0]:0,s?s[1]:0)}function i(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r)}var a=t("./symbol_attributes"),o=a.symbolLayoutAttributes,s=a.collisionVertexAttributes,l=a.collisionBoxLayout,u=a.collisionCircleLayout,c=a.dynamicLayoutAttributes,h=t("../array_types"),f=h.SymbolLayoutArray,p=h.SymbolDynamicLayoutArray,d=h.SymbolOpacityArray,g=h.CollisionBoxLayoutArray,v=h.CollisionCircleLayoutArray,m=h.CollisionVertexArray,y=h.PlacedSymbolArray,x=h.GlyphOffsetArray,b=h.SymbolLineVertexArray,_=t("@mapbox/point-geometry"),w=t("../segment").SegmentVector,M=t("../program_configuration").ProgramConfigurationSet,A=t("../index_array_type"),k=A.TriangleIndexArray,T=A.LineIndexArray,S=t("../../symbol/transform_text"),E=t("../../symbol/mergelines"),C=t("../../util/script_detection"),L=t("../load_geometry"),z=t("@mapbox/vector-tile").VectorTileFeature.types,P=t("../../util/verticalize_punctuation"),I=(t("../../symbol/anchor"),t("../../symbol/symbol_size").getSizeData),D=t("../../util/web_worker_transfer").register,O=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}],R=function(t){this.layoutVertexArray=new f,this.indexArray=new k,this.programConfigurations=t,this.segments=new w,this.dynamicLayoutVertexArray=new p,this.opacityVertexArray=new d,this.placedSymbolArray=new y};R.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,o.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,c.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,O,!0),this.opacityVertexBuffer.itemSize=1},R.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy())},D("SymbolBuffers",R);var F=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new w,this.collisionVertexArray=new m};F.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,s.members,!0)},F.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy())},D("CollisionBuffers",F);var B=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=I(this.zoom,e["text-size"]),this.iconSizeData=I(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")};B.prototype.createArrays=function(){this.text=new R(new M(o.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new R(new M(o.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new F(g,l.members,T),this.collisionCircle=new F(v,u.members,k),this.glyphOffsetArray=new x,this.lineVertexArray=new b},B.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),a=n.get("text-field"),o=n.get("icon-image"),s=("constant"!==a.value.kind||a.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),l="constant"!==o.value.kind||o.value.value&&o.value.value.length>0;if(this.features=[],s||l){for(var u=e.iconDependencies,c=e.glyphDependencies,h={zoom:this.zoom},f=0,p=t;f=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var l=0;l0;t.addCollisionDebugVertices(l,u,c,h,f?t.collisionCircle:t.collisionBox,s.anchorPoint,n,f)}}}},B.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var a={},o=e;o0},B.prototype.hasIconData=function(){return this.icon.segments.get().length>0},B.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},B.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},B.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},a("Level",o);var s=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new o(256,512),this.loaded=!!r};s.prototype.loadFromImage=function(t){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");for(var e=this.level=new o(t.width,t.width/2),r=t.data,n=0;no.max||u.yo.max)&&i.warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return r}},{"../util/util":275,"./extent":53}],57:[function(t,e,r){var n=t("../util/struct_array").createLayout;e.exports=n([{name:"a_pos",type:"Int16",components:2}])},{"../util/struct_array":271}],58:[function(t,e,r){function n(t){return[a(255*t.r,255*t.g),a(255*t.b,255*t.a)]}function i(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}var a=t("../shaders/encode_attribute").packUint8ToFloat,o=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),s=t("../style/properties").PossiblyEvaluatedPropertyValue,l=t("./array_types"),u=l.StructArrayLayout1f4,c=l.StructArrayLayout2f8,h=l.StructArrayLayout4f16,f=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0}};f.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},f.prototype.populatePaintArray=function(){},f.prototype.upload=function(){},f.prototype.destroy=function(){},f.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),a=t.gl;"color"===this.type?a.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):a.uniform1f(e.uniforms["u_"+this.name],i)};var p=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?c:u;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n};p.prototype.defines=function(){return[]},p.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,i=r.length;r.reserve(t);var a=this.expression.evaluate({zoom:0},e);if("color"===this.type)for(var o=n(a),s=i;sa&&n("Max vertices per segment is "+a+": bucket requested "+t),(!o||o.vertexLength+t>e.exports.MAX_VERTEX_ARRAY_LENGTH)&&(o={vertexOffset:r.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0},this.segments.push(o)),o},o.prototype.get=function(){return this.segments},o.prototype.destroy=function(){for(var t=0,e=this.segments;t90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};i.prototype.wrap=function(){return new i(n(this.lng,-180,180),this.lat)},i.prototype.toArray=function(){return[this.lng,this.lat]},i.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},i.prototype.toBounds=function(e){var r=360*e/40075017,n=r/Math.cos(Math.PI/180*this.lat);return new(t("./lng_lat_bounds"))(new i(this.lng-n,this.lat-r),new i(this.lng+n,this.lat+r))},i.convert=function(t){if(t instanceof i)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new i(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new i(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, or an array of [, ]")},e.exports=i},{"../util/util":275,"./lng_lat_bounds":63}],63:[function(t,e,r){var n=t("./lng_lat"),i=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]))};i.prototype.setNorthEast=function(t){return this._ne=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.setSouthWest=function(t){return this._sw=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.extend=function(t){var e,r,a=this._sw,o=this._ne;if(t instanceof n)e=t,r=t;else{if(!(t instanceof i))return Array.isArray(t)?t.every(Array.isArray)?this.extend(i.convert(t)):this.extend(n.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return a||o?(a.lng=Math.min(e.lng,a.lng),a.lat=Math.min(e.lat,a.lat),o.lng=Math.max(r.lng,o.lng),o.lat=Math.max(r.lat,o.lat)):(this._sw=new n(e.lng,e.lat),this._ne=new n(r.lng,r.lat)),this},i.prototype.getCenter=function(){return new n((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},i.prototype.getSouthWest=function(){return this._sw},i.prototype.getNorthEast=function(){return this._ne},i.prototype.getNorthWest=function(){return new n(this.getWest(),this.getNorth())},i.prototype.getSouthEast=function(){return new n(this.getEast(),this.getSouth())},i.prototype.getWest=function(){return this._sw.lng},i.prototype.getSouth=function(){return this._sw.lat},i.prototype.getEast=function(){return this._ne.lng},i.prototype.getNorth=function(){return this._ne.lat},i.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},i.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},i.prototype.isEmpty=function(){return!(this._sw&&this._ne)},i.convert=function(t){return!t||t instanceof i?t:new i(t)},e.exports=i},{"./lng_lat":62}],64:[function(t,e,r){var n=t("./lng_lat"),i=t("@mapbox/point-geometry"),a=t("./coordinate"),o=t("../util/util"),s=t("../style-spec/util/interpolate").number,l=t("../util/tile_cover"),u=t("../source/tile_id"),c=(u.CanonicalTileID,u.UnwrappedTileID),h=t("../data/extent"),f=t("@mapbox/gl-matrix"),p=f.vec4,d=f.mat4,g=f.mat2,v=function(t,e,r){this.tileSize=512,this._renderWorldCopies=void 0===r||r,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new n(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={}},m={minZoom:{},maxZoom:{},renderWorldCopies:{},worldSize:{},centerPoint:{},size:{},bearing:{},pitch:{},fov:{},zoom:{},center:{},unmodified:{},x:{},y:{},point:{}};v.prototype.clone=function(){var t=new v(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},m.minZoom.get=function(){return this._minZoom},m.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))},m.maxZoom.get=function(){return this._maxZoom},m.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))},m.renderWorldCopies.get=function(){return this._renderWorldCopies},m.worldSize.get=function(){return this.tileSize*this.scale},m.centerPoint.get=function(){return this.size._div(2)},m.size.get=function(){return new i(this.width,this.height)},m.bearing.get=function(){return-this.angle/Math.PI*180},m.bearing.set=function(t){var e=-o.wrap(t,-180,180)*Math.PI/180;this.angle!==e&&(this._unmodified=!1,this.angle=e,this._calcMatrices(),this.rotationMatrix=g.create(),g.rotate(this.rotationMatrix,this.rotationMatrix,this.angle))},m.pitch.get=function(){return this._pitch/Math.PI*180},m.pitch.set=function(t){var e=o.clamp(t,0,60)/180*Math.PI;this._pitch!==e&&(this._unmodified=!1,this._pitch=e,this._calcMatrices())},m.fov.get=function(){return this._fov/Math.PI*180},m.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices())},m.zoom.get=function(){return this._zoom},m.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices())},m.center.get=function(){return this._center},m.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices())},v.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},v.prototype.getVisibleUnwrappedCoordinates=function(t){var e=this.pointCoordinate(new i(0,0),0),r=this.pointCoordinate(new i(this.width,0),0),n=Math.floor(e.column),a=Math.floor(r.column),o=[new c(0,t)];if(this._renderWorldCopies)for(var s=n;s<=a;s++)0!==s&&o.push(new c(s,t));return o},v.prototype.coveringTiles=function(t){var e=this.coveringZoomLevel(t),r=e;if(void 0!==t.minzoom&&et.maxzoom&&(e=t.maxzoom);var n=this.pointCoordinate(this.centerPoint,e),a=new i(n.column-.5,n.row-.5),o=[this.pointCoordinate(new i(0,0),e),this.pointCoordinate(new i(this.width,0),e),this.pointCoordinate(new i(this.width,this.height),e),this.pointCoordinate(new i(0,this.height),e)];return l(e,o,t.reparseOverscaled?r:e,this._renderWorldCopies).sort(function(t,e){return a.dist(t.canonical)-a.dist(e.canonical)})},v.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices()},m.unmodified.get=function(){return this._unmodified},v.prototype.zoomScale=function(t){return Math.pow(2,t)},v.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},v.prototype.project=function(t){return new i(this.lngX(t.lng),this.latY(t.lat))},v.prototype.unproject=function(t){return new n(this.xLng(t.x),this.yLat(t.y))},m.x.get=function(){return this.lngX(this.center.lng)},m.y.get=function(){return this.latY(this.center.lat)},m.point.get=function(){return new i(this.x,this.y)},v.prototype.lngX=function(t){return(180+t)*this.worldSize/360},v.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},v.prototype.xLng=function(t){return 360*t/this.worldSize-180},v.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},v.prototype.setLocationAtPoint=function(t,e){var r=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(r)),this._renderWorldCopies&&(this.center=this.center.wrap())},v.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},v.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},v.prototype.locationCoordinate=function(t){return new a(this.lngX(t.lng)/this.tileSize,this.latY(t.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},v.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new n(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},v.prototype.pointCoordinate=function(t,e){void 0===e&&(e=this.tileZoom);var r=[t.x,t.y,0,1],n=[t.x,t.y,1,1];p.transformMat4(r,r,this.pixelMatrixInverse),p.transformMat4(n,n,this.pixelMatrixInverse);var i=r[3],o=n[3],l=r[1]/i,u=n[1]/o,c=r[2]/i,h=n[2]/o,f=c===h?0:(0-c)/(h-c);return new a(s(r[0]/i,n[0]/o,f)/this.tileSize,s(l,u,f)/this.tileSize,this.zoom)._zoomTo(e)},v.prototype.coordinatePoint=function(t){var e=t.zoomTo(this.zoom),r=[e.column*this.tileSize,e.row*this.tileSize,0,1];return p.transformMat4(r,r,this.pixelMatrix),new i(r[0]/r[3],r[1]/r[3])},v.prototype.calculatePosMatrix=function(t,e){void 0===e&&(e=!1);var r=t.key,n=e?this._alignedPosMatrixCache:this._posMatrixCache;if(n[r])return n[r];var i=t.canonical,a=this.worldSize/this.zoomScale(i.z),o=i.x+Math.pow(2,i.z)*t.wrap,s=d.identity(new Float64Array(16));return d.translate(s,s,[o*a,i.y*a,0]),d.scale(s,s,[a/h,a/h,1]),d.multiply(s,e?this.alignedProjMatrix:this.projMatrix,s),n[r]=new Float32Array(s),n[r]},v.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var t,e,r,n,a=-90,o=90,s=-180,l=180,u=this.size,c=this._unmodified;if(this.latRange){var h=this.latRange;a=this.latY(h[1]),t=(o=this.latY(h[0]))-ao&&(n=o-g)}if(this.lngRange){var v=this.x,m=u.x/2;v-ml&&(r=l-m)}void 0===r&&void 0===n||(this.center=this.unproject(new i(void 0!==r?r:this.x,void 0!==n?n:this.y))),this._unmodified=c,this._constraining=!1}},v.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,r=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,i=this.y,a=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),o=new Float64Array(16);d.perspective(o,this._fov,this.width/this.height,1,a),d.scale(o,o,[1,-1,1]),d.translate(o,o,[0,0,-this.cameraToCenterDistance]),d.rotateX(o,o,this._pitch),d.rotateZ(o,o,this.angle),d.translate(o,o,[-n,-i,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));d.scale(o,o,[1,1,s,1]),this.projMatrix=o;var l=this.width%2/2,u=this.height%2/2,c=Math.cos(this.angle),h=Math.sin(this.angle),f=n-Math.round(n)+c*l+h*u,p=i-Math.round(i)+c*u+h*l,g=new Float64Array(o);if(d.translate(g,g,[f>.5?f-1:f,p>.5?p-1:p,0]),this.alignedProjMatrix=g,o=d.create(),d.scale(o,o,[this.width/2,-this.height/2,1]),d.translate(o,o,[1,-1,0]),this.pixelMatrix=d.multiply(new Float64Array(16),o,this.projMatrix),!(o=d.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=o,this._posMatrixCache={},this._alignedPosMatrixCache={}}},Object.defineProperties(v.prototype,m),e.exports=v},{"../data/extent":53,"../source/tile_id":114,"../style-spec/util/interpolate":158,"../util/tile_cover":273,"../util/util":275,"./coordinate":61,"./lng_lat":62,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],65:[function(t,e,r){var n=t("../style-spec/util/color"),i=function(t,e,r){this.blendFunction=t,this.blendColor=e,this.mask=r};i.disabled=new i(i.Replace=[1,0],n.transparent,[!1,!1,!1,!1]),i.unblended=new i(i.Replace,n.transparent,[!0,!0,!0,!0]),i.alphaBlended=new i([1,771],n.transparent,[!0,!0,!0,!0]),e.exports=i},{"../style-spec/util/color":153}],66:[function(t,e,r){var n=t("./index_buffer"),i=t("./vertex_buffer"),a=t("./framebuffer"),o=(t("./depth_mode"),t("./stencil_mode"),t("./color_mode")),s=t("../util/util"),l=t("./value"),u=l.ClearColor,c=l.ClearDepth,h=l.ClearStencil,f=l.ColorMask,p=l.DepthMask,d=l.StencilMask,g=l.StencilFunc,v=l.StencilOp,m=l.StencilTest,y=l.DepthRange,x=l.DepthTest,b=l.DepthFunc,_=l.Blend,w=l.BlendFunc,M=l.BlendColor,A=l.Program,k=l.LineWidth,T=l.ActiveTextureUnit,S=l.Viewport,E=l.BindFramebuffer,C=l.BindRenderbuffer,L=l.BindTexture,z=l.BindVertexBuffer,P=l.BindElementBuffer,I=l.BindVertexArrayOES,D=l.PixelStoreUnpack,O=l.PixelStoreUnpackPremultiplyAlpha,R=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new u(this),this.clearDepth=new c(this),this.clearStencil=new h(this),this.colorMask=new f(this),this.depthMask=new p(this),this.stencilMask=new d(this),this.stencilFunc=new g(this),this.stencilOp=new v(this),this.stencilTest=new m(this),this.depthRange=new y(this),this.depthTest=new x(this),this.depthFunc=new b(this),this.blend=new _(this),this.blendFunc=new w(this),this.blendColor=new M(this),this.program=new A(this),this.lineWidth=new k(this),this.activeTexture=new T(this),this.viewport=new S(this),this.bindFramebuffer=new E(this),this.bindRenderbuffer=new C(this),this.bindTexture=new L(this),this.bindVertexBuffer=new z(this),this.bindElementBuffer=new P(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new I(this),this.pixelStoreUnpack=new D(this),this.pixelStoreUnpackPremultiplyAlpha=new O(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear")};R.prototype.createIndexBuffer=function(t,e){return new n(this,t,e)},R.prototype.createVertexBuffer=function(t,e,r){return new i(this,t,e,r)},R.prototype.createRenderbuffer=function(t,e,r){var n=this.gl,i=n.createRenderbuffer();return this.bindRenderbuffer.set(i),n.renderbufferStorage(n.RENDERBUFFER,t,e,r),this.bindRenderbuffer.set(null),i},R.prototype.createFramebuffer=function(t,e){return new a(this,t,e)},R.prototype.clear=function(t){var e=t.color,r=t.depth,n=this.gl,i=0;e&&(i|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==r&&(i|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(r),this.depthMask.set(!0)),n.clear(i)},R.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1)},R.prototype.setStencilMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1)},R.prototype.setColorMode=function(t){s.deepEqual(t.blendFunction,o.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(t.blendFunction),this.blendColor.set(t.blendColor)),this.colorMask.set(t.mask)},e.exports=R},{"../util/util":275,"./color_mode":65,"./depth_mode":67,"./framebuffer":68,"./index_buffer":69,"./stencil_mode":70,"./value":71,"./vertex_buffer":72}],67:[function(t,e,r){var n=function(t,e,r){this.func=t,this.mask=e,this.range=r};n.ReadOnly=!1,n.ReadWrite=!0,n.disabled=new n(519,n.ReadOnly,[0,1]),e.exports=n},{}],68:[function(t,e,r){var n=t("./value"),i=n.ColorAttachment,a=n.DepthAttachment,o=function(t,e,r){this.context=t,this.width=e,this.height=r;var n=t.gl,o=this.framebuffer=n.createFramebuffer();this.colorAttachment=new i(t,o),this.depthAttachment=new a(t,o)};o.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var r=this.depthAttachment.get();r&&t.deleteRenderbuffer(r),t.deleteFramebuffer(this.framebuffer)},e.exports=o},{"./value":71}],69:[function(t,e,r){var n=function(t,e,r){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(r),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};n.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null)},n.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer)},n.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)},n.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer)},e.exports=n},{}],70:[function(t,e,r){var n=function(t,e,r,n,i,a){this.test=t,this.ref=e,this.mask=r,this.fail=n,this.depthFail=i,this.pass=a};n.disabled=new n({func:519,mask:0},0,0,7680,7680,7680),e.exports=n},{}],71:[function(t,e,r){var n=t("../style-spec/util/color"),i=t("../util/util"),a=function(t){this.context=t,this.current=n.transparent};a.prototype.get=function(){return this.current},a.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t)};var o=function(t){this.context=t,this.current=1};o.prototype.get=function(){return this.current},o.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t)};var s=function(t){this.context=t,this.current=0};s.prototype.get=function(){return this.current},s.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t)};var l=function(t){this.context=t,this.current=[!0,!0,!0,!0]};l.prototype.get=function(){return this.current},l.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t)};var u=function(t){this.context=t,this.current=!0};u.prototype.get=function(){return this.current},u.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t)};var c=function(t){this.context=t,this.current=255};c.prototype.get=function(){return this.current},c.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t)};var h=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255}};h.prototype.get=function(){return this.current},h.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t)};var f=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP]};f.prototype.get=function(){return this.current},f.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t)};var p=function(t){this.context=t,this.current=!1};p.prototype.get=function(){return this.current},p.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t}};var d=function(t){this.context=t,this.current=[0,1]};d.prototype.get=function(){return this.current},d.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t)};var g=function(t){this.context=t,this.current=!1};g.prototype.get=function(){return this.current},g.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t}};var v=function(t){this.context=t,this.current=t.gl.LESS};v.prototype.get=function(){return this.current},v.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t)};var m=function(t){this.context=t,this.current=!1};m.prototype.get=function(){return this.current},m.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t}};var y=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO]};y.prototype.get=function(){return this.current},y.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t)};var x=function(t){this.context=t,this.current=n.transparent};x.prototype.get=function(){return this.current},x.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t)};var b=function(t){this.context=t,this.current=null};b.prototype.get=function(){return this.current},b.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t)};var _=function(t){this.context=t,this.current=1};_.prototype.get=function(){return this.current},_.prototype.set=function(t){var e=this.context.lineWidthRange,r=i.clamp(t,e[0],e[1]);this.current!==r&&(this.context.gl.lineWidth(r),this.current=t)};var w=function(t){this.context=t,this.current=t.gl.TEXTURE0};w.prototype.get=function(){return this.current},w.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t)};var M=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight]};M.prototype.get=function(){return this.current},M.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t)};var A=function(t){this.context=t,this.current=null};A.prototype.get=function(){return this.current},A.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t}};var k=function(t){this.context=t,this.current=null};k.prototype.get=function(){return this.current},k.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t}};var T=function(t){this.context=t,this.current=null};T.prototype.get=function(){return this.current},T.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t}};var S=function(t){this.context=t,this.current=null};S.prototype.get=function(){return this.current},S.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t}};var E=function(t){this.context=t,this.current=null};E.prototype.get=function(){return this.current},E.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t};var C=function(t){this.context=t,this.current=null};C.prototype.get=function(){return this.current},C.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t)};var L=function(t){this.context=t,this.current=4};L.prototype.get=function(){return this.current},L.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t}};var z=function(t){this.context=t,this.current=!1};z.prototype.get=function(){return this.current},z.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t}};var P=function(t,e){this.context=t,this.current=null,this.parent=e};P.prototype.get=function(){return this.current};var I=function(t){function e(e,r){t.call(this,e,r),this.dirty=!1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1}},e.prototype.setDirty=function(){this.dirty=!0},e}(P),D=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t}},e}(P);e.exports={ClearColor:a,ClearDepth:o,ClearStencil:s,ColorMask:l,DepthMask:u,StencilMask:c,StencilFunc:h,StencilOp:f,StencilTest:p,DepthRange:d,DepthTest:g,DepthFunc:v,Blend:m,BlendFunc:y,BlendColor:x,Program:b,LineWidth:_,ActiveTextureUnit:w,Viewport:M,BindFramebuffer:A,BindRenderbuffer:k,BindTexture:T,BindVertexBuffer:S,BindElementBuffer:E,BindVertexArrayOES:C,PixelStoreUnpack:L,PixelStoreUnpackPremultiplyAlpha:z,ColorAttachment:I,DepthAttachment:D}},{"../style-spec/util/color":153,"../util/util":275}],72:[function(t,e,r){var n={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},i=function(t,e,r,n){this.length=e.length,this.attributes=r,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var i=t.gl;this.buffer=i.createBuffer(),t.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};i.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer)},i.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer)},i.prototype.enableAttributes=function(t,e){for(var r=0;r":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]}},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../util/browser":252,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],78:[function(t,e,r){function n(t,e,r,n,i){if(!s.isPatternMissing(r.paint.get("fill-pattern"),t))for(var a=!0,o=0,l=n;o0){var l=o.now(),u=(l-t.timeAdded)/s,c=e?(l-e.timeAdded)/s:-1,h=r.getSource(),f=a.coveringZoomLevel({tileSize:h.tileSize,roundZoom:h.roundZoom}),p=!e||Math.abs(e.tileID.overscaledZ-f)>Math.abs(t.tileID.overscaledZ-f),d=p&&t.refreshedUponExpiration?1:i.clamp(p?u:1-c,0,1);return t.refreshedUponExpiration&&u>=1&&(t.refreshedUponExpiration=!1),e?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return{opacity:1,mix:0}}var i=t("../util/util"),a=t("../source/image_source"),o=t("../util/browser"),s=t("../gl/stencil_mode"),l=t("../gl/depth_mode");e.exports=function(t,e,r,i){if("translucent"===t.renderPass&&0!==r.paint.get("raster-opacity")){var o=t.context,u=o.gl,c=e.getSource(),h=t.useProgram("raster");o.setStencilMode(s.disabled),o.setColorMode(t.colorModeForRenderPass()),u.uniform1f(h.uniforms.u_brightness_low,r.paint.get("raster-brightness-min")),u.uniform1f(h.uniforms.u_brightness_high,r.paint.get("raster-brightness-max")),u.uniform1f(h.uniforms.u_saturation_factor,function(t){return t>0?1-1/(1.001-t):-t}(r.paint.get("raster-saturation"))),u.uniform1f(h.uniforms.u_contrast_factor,function(t){return t>0?1/(1-t):1+t}(r.paint.get("raster-contrast"))),u.uniform3fv(h.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),r=Math.cos(t);return[(2*r+1)/3,(-Math.sqrt(3)*e-r+1)/3,(Math.sqrt(3)*e-r+1)/3]}(r.paint.get("raster-hue-rotate"))),u.uniform1f(h.uniforms.u_buffer_scale,1),u.uniform1i(h.uniforms.u_image0,0),u.uniform1i(h.uniforms.u_image1,1);for(var f=i.length&&i[0].overscaledZ,p=0,d=i;p65535)e(new Error("glyphs > 65535 not supported"));else{var u=o.requests[l];u||(u=o.requests[l]=[],n(i,l,r.url,r.requestTransform,function(t,e){if(e)for(var r in e)o.glyphs[+r]=e[+r];for(var n=0,i=u;nthis.height)return n.warnOnce("LineAtlas out of space"),null;for(var o=0,s=0;s=0;this.currentLayer--){var v=r.style._layers[o[r.currentLayer]];v.source!==(d&&d.id)&&(g=[],(d=r.style.sourceCaches[v.source])&&(r.clearStencil(),g=d.getVisibleCoordinates(),d.getSource().isTileClipped&&r._renderTileClippingMasks(g))),r.renderLayer(r,d,v,g)}this.renderPass="translucent";var m,y=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer0?e.pop():null},T.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var r=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[r]||(this.cache[r]=new y(this.context,m[t],e,this._showOverdrawInspector)),this.cache[r]},T.prototype.useProgram=function(t,e){var r=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(r.program),r},e.exports=T},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../data/program_configuration":58,"../data/raster_bounds_attributes":59,"../gl/color_mode":65,"../gl/context":66,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../shaders":97,"../source/pixels_to_tile_units":104,"../source/source_cache":111,"../style-spec/util/color":153,"../symbol/cross_tile_symbol_index":218,"../util/browser":252,"../util/util":275,"./draw_background":74,"./draw_circle":75,"./draw_debug":77,"./draw_fill":78,"./draw_fill_extrusion":79,"./draw_heatmap":80,"./draw_hillshade":81,"./draw_line":82,"./draw_raster":83,"./draw_symbol":84,"./program":92,"./texture":93,"./tile_mask":94,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],91:[function(t,e,r){var n=t("../source/pixels_to_tile_units");r.isPatternMissing=function(t,e){if(!t)return!1;var r=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!r||!n},r.prepare=function(t,e,r){var n=e.context,i=n.gl,a=e.imageManager.getPattern(t.from),o=e.imageManager.getPattern(t.to);i.uniform1i(r.uniforms.u_image,0),i.uniform2fv(r.uniforms.u_pattern_tl_a,a.tl),i.uniform2fv(r.uniforms.u_pattern_br_a,a.br),i.uniform2fv(r.uniforms.u_pattern_tl_b,o.tl),i.uniform2fv(r.uniforms.u_pattern_br_b,o.br);var s=e.imageManager.getPixelSize(),l=s.width,u=s.height;i.uniform2fv(r.uniforms.u_texsize,[l,u]),i.uniform1f(r.uniforms.u_mix,t.t),i.uniform2fv(r.uniforms.u_pattern_size_a,a.displaySize),i.uniform2fv(r.uniforms.u_pattern_size_b,o.displaySize),i.uniform1f(r.uniforms.u_scale_a,t.fromScale),i.uniform1f(r.uniforms.u_scale_b,t.toScale),n.activeTexture.set(i.TEXTURE0),e.imageManager.bind(e.context)},r.setTile=function(t,e,r){var i=e.context.gl;i.uniform1f(r.uniforms.u_tile_units_to_pixels,1/n(t,1,e.transform.tileZoom));var a=Math.pow(2,t.tileID.overscaledZ),o=t.tileSize*Math.pow(2,e.transform.tileZoom)/a,s=o*(t.tileID.canonical.x+t.tileID.wrap*a),l=o*t.tileID.canonical.y;i.uniform2f(r.uniforms.u_pixel_coord_upper,s>>16,l>>16),i.uniform2f(r.uniforms.u_pixel_coord_lower,65535&s,65535&l)}},{"../source/pixels_to_tile_units":104}],92:[function(t,e,r){var n=t("../util/browser"),i=t("../shaders"),a=(t("../data/program_configuration").ProgramConfiguration,t("./vertex_array_object")),o=(t("../gl/context"),function(t,e,r,a){var o=this,s=t.gl;this.program=s.createProgram();var l=r.defines().concat("#define DEVICE_PIXEL_RATIO "+n.devicePixelRatio.toFixed(1));a&&l.push("#define OVERDRAW_INSPECTOR;");var u=l.concat(i.prelude.fragmentSource,e.fragmentSource).join("\n"),c=l.concat(i.prelude.vertexSource,e.vertexSource).join("\n"),h=s.createShader(s.FRAGMENT_SHADER);s.shaderSource(h,u),s.compileShader(h),s.attachShader(this.program,h);var f=s.createShader(s.VERTEX_SHADER);s.shaderSource(f,c),s.compileShader(f),s.attachShader(this.program,f);for(var p=r.layoutAttributes||[],d=0;d 0.5) {\n gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n gl_FragColor *= .1;\n }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n float alpha = 0.5;\n\n // Red = collision, hide label\n vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n // Blue = no collision, label is showing\n if (v_placed > 0.5) {\n color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n color *= .2;\n }\n\n float extrude_scale_length = length(v_extrude_scale);\n float extrude_length = length(v_extrude) * extrude_scale_length;\n float stroke_width = 15.0 * extrude_scale_length;\n float radius = v_radius * extrude_scale_length;\n\n float distance_to_edge = abs(extrude_length - radius);\n float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n v_extrude = a_extrude * padding_factor;\n v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n // find distance to outline for alpha interpolation\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n vec3 normal = a_normal_ed.xyz;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n\n gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n // Relative luminance (how dark/bright is the surface color?)\n float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n // Add slight ambient lighting so no extrusions are totally black\n vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n color += ambientlight;\n\n // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n // Adjust directional so that\n // the range of values for highlight/shading is narrower\n // with lower light intensity\n // and with lighter/brighter surface colors\n directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n // Add gradient along z axis of side surfaces\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n // with lower bounds adjusted to hue of light\n // so that shading is tinted with the complementary (opposite) color to the light color\n v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n vec4 mixedColor = mix(color1, color2, u_mix);\n\n gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec3 normal = a_normal_ed.xyz;\n float edgedistance = a_normal_ed.w;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n float z = t > 0.0 ? height : base;\n\n gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n ? a_pos // extrusion top\n : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n v_pos.x = a_pos.x;\n v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\n\nfloat getElevation(vec2 coord, float bias) {\n // Convert encoded elevation value to meters\n vec4 data = texture2D(u_image, coord) * 255.0;\n return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n vec2 epsilon = 1.0 / u_dimension;\n\n // queried pixels:\n // +-----------+\n // | | | |\n // | a | b | c |\n // | | | |\n // +-----------+\n // | | | |\n // | d | e | f |\n // | | | |\n // +-----------+\n // | | | |\n // | g | h | i |\n // | | | |\n // +-----------+\n\n float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n float e = getElevation(v_pos, 0.0);\n float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n // here we divide the x and y slopes by 8 * pixel size\n // where pixel size (aka meters/pixel) is:\n // circumference of the world / (pixels per tile * number of tiles)\n // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n // we want to vertically exaggerate the hillshading though, because otherwise\n // it is barely noticeable at low zooms. to do this, we multiply this by some\n // scale factor pow(2, (u_zoom - 14) * a) where a is an arbitrary value and 14 is the\n // maxzoom of the tile source. here we use a=0.3 which works out to the\n // expression below. see nickidlugash's awesome breakdown for more info\n // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n vec2 deriv = vec2(\n (c + f + f + i) - (a + d + d + g),\n (g + h + h + i) - (a + b + b + c)\n ) / pow(2.0, (u_zoom - 14.0) * exaggeration + 19.2562 - u_zoom);\n\n gl_FragColor = clamp(vec4(\n deriv.x / 2.0 + 0.5,\n deriv.y / 2.0 + 0.5,\n 1.0,\n 1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n vec4 pixel = texture2D(u_image, v_pos);\n\n vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n // to account for mercator projection distortion. see #4807 for details\n float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n // We also multiply the slope by an arbitrary z-factor of 1.25\n float slope = atan(1.25 * length(deriv) / scaleFactor);\n float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n float intensity = u_light.x;\n // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n float azimuth = u_light.y + PI;\n\n // We scale the slope exponentially based on intensity, using a calculation similar to\n // the exponential interpolation function in the style spec:\n // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n // so that higher intensity values create more opaque hillshading.\n float base = 1.875 - intensity * 1.75;\n float maxValue = 0.5 * PI;\n float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n // so that the accent color's rate of change eases in while the shade color's eases out.\n float accent = cos(scaledSlope);\n // We multiply both the accent and shade color by a clamped intensity value\n // so that intensities >= 0.5 do not additionally affect the color values\n // while intensity values < 0.5 make the overall color more transparent.\n vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n float y_a = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_a.y);\n float y_b = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_b.y);\n vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_linesofar = a_linesofar;\n v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float sdfdist_a = texture2D(u_image, v_tex_a).a;\n float sdfdist_b = texture2D(u_image, v_tex_b).a;\n float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist =outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n // read and cross-fade colors from the main and parent tiles\n vec4 color0 = texture2D(u_image0, v_pos0);\n vec4 color1 = texture2D(u_image1, v_pos1);\n if (color0.a > 0.0) {\n color0.rgb = color0.rgb / color0.a;\n }\n if (color1.a > 0.0) {\n color1.rgb = color1.rgb / color1.a;\n }\n vec4 color = mix(color0, color1, u_fade_t);\n color.a *= u_opacity;\n vec3 rgb = color.rgb;\n\n // spin\n rgb = vec3(\n dot(rgb, u_spin_weights.xyz),\n dot(rgb, u_spin_weights.zxy),\n dot(rgb, u_spin_weights.yzx));\n\n // saturation\n float average = (color.r + color.g + color.b) / 3.0;\n rgb += (average - rgb) * u_saturation_factor;\n\n // contrast\n rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n // brightness\n vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n // We are using Int16 for texture position coordinates to give us enough precision for\n // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n // as an arbitrarily high number to preserve adequate precision when rendering.\n // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n // so math for modifying either is consistent.\n v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n lowp float alpha = opacity * v_fade_opacity;\n gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n\n float size;\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // See comments in symbol_sdf.vertex\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // See comments in symbol_sdf.vertex\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n\n v_tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 tex = v_data0.xy;\n float gamma_scale = v_data1.x;\n float size = v_data1.y;\n float fade_opacity = v_data1[2];\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n lowp vec4 color = fill_color;\n highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n lowp float buff = (256.0 - 64.0) / 256.0;\n if (u_is_halo) {\n color = halo_color;\n gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n buff = (6.0 - halo_width / fontScale) / SDF_PX;\n }\n\n lowp float dist = texture2D(u_texture, tex).a;\n highp float gamma_scaled = gamma * gamma_scale;\n highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n// text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n float size;\n\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // If the label is pitched with the map, layout is done in pitched space,\n // which makes labels in the distance smaller relative to viewport space.\n // We counteract part of that effect by multiplying by the perspective ratio.\n // If the label isn't pitched with the map, we do layout in viewport space,\n // which makes labels in the distance larger relative to the features around\n // them. We counteract part of that effect by dividing by the perspective ratio.\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n // To figure out that angle in projected space, we draw a short horizontal line in tile\n // space, project it, and measure its angle in projected space.\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n float gamma_scale = gl_Position.w;\n\n vec2 tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n v_data0 = vec2(tex.x, tex.y);\n v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,a=function(t){var e=n[t],r={};e.fragmentSource=e.fragmentSource.replace(i,function(t,e,n,i,a){return r[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(i,function(t,e,n,i,a){var o="float"===i?"vec2":"vec4";return r[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+n+" "+i+" "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"})};for(var o in n)a(o);e.exports=n},{}],98:[function(t,e,r){var n=t("./image_source"),i=t("../util/window"),a=t("../data/raster_bounds_attributes"),o=t("../render/vertex_array_object"),s=t("../render/texture"),l=function(t){function e(e,r,n,i){t.call(this,e,r,n,i),this.options=r,this.animate=void 0===r.animate||r.animate}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.load=function(){this.canvas=this.canvas||i.document.getElementById(this.options.canvas),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire("error",new Error("Canvas dimensions cannot be less than or equal to zero.")):(this.play=function(){this._playing=!0,this.map._rerender()},this.pause=function(){this._playing=!1},this._finishLoading())},e.prototype.getCanvas=function(){return this.canvas},e.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()},e.prototype.onRemove=function(){this.pause()},e.prototype.prepare=function(){var t=this,e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var r=this.map.painter.context,n=r.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=r.createVertexBuffer(this._boundsArray,a.members)),this.boundsVAO||(this.boundsVAO=new o),this.texture?e?this.texture.update(this.canvas):this._playing&&(this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.canvas)):(this.texture=new s(r,this.canvas,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE)),t.tiles){var l=t.tiles[i];"loaded"!==l.state&&(l.state="loaded",l.texture=t.texture)}}},e.prototype.serialize=function(){return{type:"canvas",canvas:this.canvas,coordinates:this.coordinates}},e.prototype.hasTransition=function(){return this._playing},e.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t0&&(r.resourceTiming=t._resourceTiming,t._resourceTiming=[]),t.fire("data",r)}})},e.prototype.onAdd=function(t){this.map=t,this.load()},e.prototype.setData=function(t){var e=this;return this._data=t,this.fire("dataloading",{dataType:"source"}),this._updateWorkerData(function(t){if(t)return e.fire("error",{error:t});var r={dataType:"source",sourceDataType:"content"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(r.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire("data",r)}),this},e.prototype._updateWorkerData=function(t){var e=this,r=i.extend({},this.workerOptions),n=this._data;"string"==typeof n?(r.request=this.map._transformRequest(function(t){var e=a.document.createElement("a");return e.href=t,e.href}(n),s.Source),r.request.collectResourceTiming=this._collectResourceTiming):r.data=JSON.stringify(n),this.workerID=this.dispatcher.send(this.type+".loadData",r,function(r,n){e._loaded=!0,n&&n.resourceTiming&&n.resourceTiming[e.id]&&(e._resourceTiming=n.resourceTiming[e.id].slice(0)),t(r)},this.workerID)},e.prototype.loadTile=function(t,e){var r=this,n=void 0===t.workerID||"expired"===t.state?"loadTile":"reloadTile",i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:l.devicePixelRatio,overscaling:t.tileID.overscaleFactor(),showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,i,function(i,a){return t.unloadVectorData(),t.aborted?e(null):i?e(i):(t.loadVectorData(a,r.map.painter,"reloadTile"===n),e(null))},this.workerID)},e.prototype.abortTile=function(t){t.aborted=!0},e.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID)},e.prototype.onRemove=function(){this.dispatcher.broadcast("removeSource",{type:this.type,source:this.id})},e.prototype.serialize=function(){return i.extend({},this._options,{type:this.type,data:this._data})},e.prototype.hasTransition=function(){return!1},e}(n);e.exports=u},{"../data/extent":53,"../util/ajax":251,"../util/browser":252,"../util/evented":260,"../util/util":275,"../util/window":254}],100:[function(t,e,r){function n(t,e){var r=t.source,n=t.tileID.canonical;if(!this._geoJSONIndexes[r])return e(null,null);var i=this._geoJSONIndexes[r].getTile(n.z,n.x,n.y);if(!i)return e(null,null);var a=new s(i.features),o=l(a);0===o.byteOffset&&o.byteLength===o.buffer.byteLength||(o=new Uint8Array(o)),e(null,{vectorTile:a,rawData:o.buffer})}var i=t("../util/ajax"),a=t("../util/performance"),o=t("geojson-rewind"),s=t("./geojson_wrapper"),l=t("vt-pbf"),u=t("supercluster"),c=t("geojson-vt"),h=function(t){function e(e,r,i){t.call(this,e,r,n),i&&(this.loadGeoJSON=i),this._geoJSONIndexes={}}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.loadData=function(t,e){var r=this;this.loadGeoJSON(t,function(n,i){if(n||!i)return e(n);if("object"!=typeof i)return e(new Error("Input data is not a valid GeoJSON object."));o(i,!0);try{r._geoJSONIndexes[t.source]=t.cluster?u(t.superclusterOptions).load(i.features):c(i,t.geojsonVtOptions)}catch(n){return e(n)}r.loaded[t.source]={};var s={};if(t.request&&t.request.collectResourceTiming){var l=a.getEntriesByName(t.request.url);l&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(l)))}e(null,s)})},e.prototype.reloadTile=function(e,r){var n=this.loaded[e.source],i=e.uid;return n&&n[i]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},e.prototype.loadGeoJSON=function(t,e){if(t.request)i.getJSON(t.request,e);else{if("string"!=typeof t.data)return e(new Error("Input data is not a valid GeoJSON object."));try{return e(null,JSON.parse(t.data))}catch(t){return e(new Error("Input data is not a valid GeoJSON object."))}}},e.prototype.removeSource=function(t,e){this._geoJSONIndexes[t.source]&&delete this._geoJSONIndexes[t.source],e()},e}(t("./vector_tile_worker_source"));e.exports=h},{"../util/ajax":251,"../util/performance":268,"./geojson_wrapper":101,"./vector_tile_worker_source":116,"geojson-rewind":15,"geojson-vt":19,supercluster:32,"vt-pbf":34}],101:[function(t,e,r){var n=t("@mapbox/point-geometry"),i=t("@mapbox/vector-tile").VectorTileFeature.prototype.toGeoJSON,a=t("../data/extent"),o=function(t){this._feature=t,this.extent=a,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10))};o.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],e=0,r=this._feature.geometry;e0&&(l[new s(t.overscaledZ,i,e.z,n,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,t.wrap,e.z,e.x,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,o,e.z,a,e.y-1).key]={backfilled:!1}),e.y+11||(Math.abs(r)>1&&(1===Math.abs(r+i)?r+=i:1===Math.abs(r-i)&&(r-=i)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,r,n),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)))}for(var r=this.getRenderableIds(),n=0;ne)){var s=Math.pow(2,o.tileID.canonical.z-t.canonical.z);if(Math.floor(o.tileID.canonical.x/s)===t.canonical.x&&Math.floor(o.tileID.canonical.y/s)===t.canonical.y)for(r[a]=o.tileID,i=!0;o&&o.tileID.overscaledZ-1>t.overscaledZ;){var l=o.tileID.scaledTo(o.tileID.overscaledZ-1);if(!l)break;(o=n._tiles[l.key])&&o.hasData()&&(delete r[a],r[l.key]=l)}}}return i},e.prototype.findLoadedParent=function(t,e,r){for(var n=this,i=t.overscaledZ-1;i>=e;i--){var a=t.scaledTo(i);if(!a)return;var o=String(a.key),s=n._tiles[o];if(s&&s.hasData())return r[o]=a,s;if(n._cache.has(o))return r[o]=a,n._cache.get(o)}},e.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),r=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)},e.prototype.update=function(t){var r=this;if(this.transform=t,this._sourceLoaded&&!this._paused){var n;this.updateCacheSize(t),this._coveredTiles={},this.used?this._source.tileID?n=t.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(t){return new d(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y)}):(n=t.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(n=n.filter(function(t){return r._source.hasTile(t)}))):n=[];var a,o=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(t)),s=Math.max(o-e.maxOverzooming,this._source.minzoom),l=Math.max(o+e.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(n,o),h={};if(i(this._source.type))for(var f=Object.keys(u),g=0;g=p.now())){r._findLoadedChildren(m,l,u)&&(u[v]=m);var x=r.findLoadedParent(m,s,h);x&&r._addTile(x.tileID)}}for(a in h)u[a]||(r._coveredTiles[a]=!0);for(a in h)u[a]=h[a];for(var b=c.keysDifference(this._tiles,u),_=0;_n._source.maxzoom){var p=u.children(n._source.maxzoom)[0],d=n.getTile(p);d&&d.hasData()?i[p.key]=p:f=!1}else{n._findLoadedChildren(u,s,i);for(var g=u.children(n._source.maxzoom),v=0;v=o;--m){var y=u.scaledTo(m);if(a[y.key])break;if(a[y.key]=!0,!(c=n.getTile(y))&&h&&(c=n._addTile(y)),c&&(i[y.key]=y,h=c.wasRequested(),c.hasData()))break}}}return i},e.prototype._addTile=function(t){var e=this._tiles[t.key];if(e)return e;(e=this._cache.getAndRemove(t.key))&&this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,e));var r=Boolean(e);return r||(e=new o(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(e,this._tileLoaded.bind(this,e,t.key,e.state))),e?(e.uses++,this._tiles[t.key]=e,r||this._source.fire("dataloading",{tile:e,coord:e.tileID,dataType:"source"}),e):null},e.prototype._setTileReloadTimer=function(t,e){var r=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){r._reloadTile(t,"expired"),delete r._timers[t]},n))},e.prototype._setCacheInvalidationTimer=function(t,e){var r=this;t in this._cacheTimers&&(clearTimeout(this._cacheTimers[t]),delete this._cacheTimers[t]);var n=e.getExpiryTimeout();n&&(this._cacheTimers[t]=setTimeout(function(){r._cache.remove(t),delete r._cacheTimers[t]},n))},e.prototype._removeTile=function(t){var e=this._tiles[t];if(e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),!(e.uses>0)))if(e.hasData()){e.tileID=e.tileID.wrapped();var r=e.tileID.key;this._cache.add(r,e),this._setCacheInvalidationTimer(r,e)}else e.aborted=!0,this._abortTile(e),this._unloadTile(e)},e.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._resetCache()},e.prototype._resetCache=function(){for(var t in this._cacheTimers)clearTimeout(this._cacheTimers[t]);this._cacheTimers={},this._cache.reset()},e.prototype.tilesIn=function(t){for(var e=[],r=this.getIds(),i=1/0,a=1/0,o=-1/0,s=-1/0,l=t[0].zoom,c=0;c=0&&v[1].y>=0){for(var m=[],y=0;y=p.now())return!0}return!1},e}(s);g.maxOverzooming=10,g.maxUnderzooming=3,e.exports=g},{"../data/extent":53,"../geo/coordinate":61,"../gl/context":66,"../util/browser":252,"../util/evented":260,"../util/lru_cache":266,"../util/util":275,"./source":110,"./tile":112,"./tile_id":114,"@mapbox/point-geometry":4}],112:[function(t,e,r){var n=t("../util/util"),i=t("../data/bucket").deserialize,a=(t("../data/feature_index"),t("@mapbox/vector-tile")),o=t("pbf"),s=t("../util/vectortile_to_geojson"),l=t("../style-spec/feature_filter"),u=(t("../symbol/collision_index"),t("../data/bucket/symbol_bucket")),c=t("../data/array_types"),h=c.RasterBoundsArray,f=c.CollisionBoxArray,p=t("../data/raster_bounds_attributes"),d=t("../data/extent"),g=t("@mapbox/point-geometry"),v=t("../render/texture"),m=t("../data/segment").SegmentVector,y=t("../data/index_array_type").TriangleIndexArray,x=t("../util/browser"),b=function(t,e){this.tileID=t,this.uid=n.uniqueId(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.expiredRequestCount=0,this.state="loading"};b.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e>s.z,u=new g(s.x*l,s.y*l),c=new g(u.x+l,u.y+l),f=this.segments.prepareSegment(4,r,i);r.emplaceBack(u.x,u.y,u.x,u.y),r.emplaceBack(c.x,u.y,c.x,u.y),r.emplaceBack(u.x,c.y,u.x,c.y),r.emplaceBack(c.x,c.y,c.x,c.y);var v=f.vertexLength;i.emplaceBack(v,v+1,v+2),i.emplaceBack(v+1,v+2,v+3),f.vertexLength+=4,f.primitiveLength+=2}this.maskedBoundsBuffer=e.createVertexBuffer(r,p.members),this.maskedIndexBuffer=e.createIndexBuffer(i)}},b.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},b.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=n.parseCacheControl(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"])}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var i=Date.now(),a=!1;if(this.expirationTime>i)a=!1;else if(e)if(this.expirationTime=e&&t.x=r&&t.y0;a--)i+=(e&(n=1<this.canonical.z?new u(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new u(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},u.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e},u.prototype.children=function(t){if(this.overscaledZ>=t)return[new u(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new u(e,this.wrap,e,r,n),new u(e,this.wrap,e,r+1,n),new u(e,this.wrap,e,r,n+1),new u(e,this.wrap,e,r+1,n+1)]},u.prototype.isLessThan=function(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=C.maxzoom||"none"===C.visibility||(n(E,d.zoom),(m[C.id]=C.createBucket({index:v.bucketLayerIDs.length,layers:E,zoom:d.zoom,pixelRatio:d.pixelRatio,overscaling:d.overscaling,collisionBoxArray:d.collisionBoxArray})).populate(M,y),v.bucketLayerIDs.push(E.map(function(t){return t.id})))}}}var L,z,P,I=u.mapObject(y.glyphDependencies,function(t){return Object.keys(t).map(Number)});Object.keys(I).length?r.send("getGlyphs",{uid:this.uid,stacks:I},function(t,e){L||(L=t,z=e,p.call(d))}):z={};var D=Object.keys(y.iconDependencies);D.length?r.send("getImages",{icons:D},function(t,e){L||(L=t,P=e,p.call(d))}):P={},p.call(this)},e.exports=d},{"../data/array_types":39,"../data/bucket/symbol_bucket":51,"../data/feature_index":54,"../render/glyph_atlas":85,"../render/image_atlas":87,"../style/evaluation_parameters":182,"../symbol/symbol_layout":227,"../util/dictionary_coder":257,"../util/util":275,"./tile_id":114}],120:[function(t,e,r){function n(t,e){var r={};for(var n in t)"ref"!==n&&(r[n]=t[n]);return i.forEach(function(t){t in e&&(r[t]=e[t])}),r}var i=t("./util/ref_properties");e.exports=function(t){t=t.slice();for(var e=Object.create(null),r=0;r4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in p))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=p[i]}else r=o;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2]}var s=a(r,n),l=e.parse(t[t.length-1],t.length-1,o);return l?new d(s,l):null},d.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(c(this.type,h(e)))throw new f("Expected value to be of type "+i(this.type)+", but found "+i(h(e))+" instead.");return e},d.prototype.eachChild=function(t){t(this.input)},d.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},e.exports=d},{"../runtime_error":143,"../types":146,"../values":147}],125:[function(t,e,r){var n=t("../types"),i=n.ObjectType,a=n.ValueType,o=n.StringType,s=n.NumberType,l=n.BooleanType,u=t("../runtime_error"),c=t("../types"),h=c.checkSubtype,f=c.toString,p=t("../values").typeOf,d={string:o,number:s,boolean:l,object:i},g=function(t,e){this.type=t,this.args=e};g.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=d[r],i=[],o=1;o=r.length)throw new s("Array index out of bounds: "+e+" > "+r.length+".");if(e!==Math.floor(e))throw new s("Array index must be an integer, but found "+e+" instead.");return r[e]},l.prototype.eachChild=function(t){t(this.index),t(this.input)},l.prototype.possibleOutputs=function(){return[void 0]},e.exports=l},{"../runtime_error":143,"../types":146}],127:[function(t,e,r){var n=t("../types").BooleanType,i=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r};i.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var a=[],o=1;o4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":u(e[0],e[1],e[2],e[3])))return new l(e[0]/255,e[1]/255,e[2]/255,e[3]);throw new c(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var o=null,s=0,h=this.args;sn.evaluate(t)}function u(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function c(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}var h=t("../types"),f=h.NumberType,p=h.StringType,d=h.BooleanType,g=h.ColorType,v=h.ObjectType,m=h.ValueType,y=h.ErrorType,x=h.array,b=h.toString,_=t("../values"),w=_.typeOf,M=_.Color,A=_.validateRGBA,k=t("../compound_expression"),T=k.CompoundExpression,S=k.varargs,E=t("../runtime_error"),C=t("./let"),L=t("./var"),z=t("./literal"),P=t("./assertion"),I=t("./array"),D=t("./coercion"),O=t("./at"),R=t("./match"),F=t("./case"),B=t("./step"),N=t("./interpolate"),j=t("./coalesce"),V=t("./equals"),U={"==":V.Equals,"!=":V.NotEquals,array:I,at:O,boolean:P,case:F,coalesce:j,interpolate:N,let:C,literal:z,match:R,number:P,object:P,step:B,string:P,"to-color":D,"to-number":D,var:L};T.register(U,{error:[y,[p],function(t,e){var r=e[0];throw new E(r.evaluate(t))}],typeof:[p,[m],function(t,e){var r=e[0];return b(w(r.evaluate(t)))}],"to-string":[p,[m],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r||"string"===n||"number"===n||"boolean"===n?String(r):r instanceof M?r.toString():JSON.stringify(r)}],"to-boolean":[d,[m],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[x(f,4),[g],function(t,e){var r=e[0].evaluate(t),n=r.r,i=r.g,a=r.b,o=r.a;return[255*n/o,255*i/o,255*a/o,o]}],rgb:[g,[f,f,f],n],rgba:[g,[f,f,f,f],n],length:{type:f,overloads:[[[p],o],[[x(m)],o]]},has:{type:d,overloads:[[[p],function(t,e){return i(e[0].evaluate(t),t.properties())}],[[p,v],function(t,e){var r=e[0],n=e[1];return i(r.evaluate(t),n.evaluate(t))}]]},get:{type:m,overloads:[[[p],function(t,e){return a(e[0].evaluate(t),t.properties())}],[[p,v],function(t,e){var r=e[0],n=e[1];return a(r.evaluate(t),n.evaluate(t))}]]},properties:[v,[],function(t){return t.properties()}],"geometry-type":[p,[],function(t){return t.geometryType()}],id:[m,[],function(t){return t.id()}],zoom:[f,[],function(t){return t.globals.zoom}],"heatmap-density":[f,[],function(t){return t.globals.heatmapDensity||0}],"+":[f,S(f),function(t,e){for(var r=0,n=0,i=e;n":[d,[p,m],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[d,[m],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[d,[p,m],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[d,[m],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[d,[p,m],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[d,[m],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[d,[m],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[d,[],function(t){return null!==t.id()}],"filter-type-in":[d,[x(p)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[d,[x(m)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[d,[p,x(m)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[d,[p,x(m)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:d,overloads:[[[f,f],l],[[p,p],l]]},"<":{type:d,overloads:[[[f,f],s],[[p,p],s]]},">=":{type:d,overloads:[[[f,f],c],[[p,p],c]]},"<=":{type:d,overloads:[[[f,f],u],[[p,p],u]]},all:{type:d,overloads:[[[d,d],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[S(d),function(t,e){for(var r=0,n=e;r1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:o}}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,l)))return null;var u=[],h=null;e.expectedType&&"value"!==e.expectedType.kind&&(h=e.expectedType);for(var f=0;f=p)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',g);var m=e.parse(d,v,h);if(!m)return null;h=h||m.type,u.push([p,m])}return"number"===h.kind||"color"===h.kind||"array"===h.kind&&"number"===h.itemType.kind&&"number"==typeof h.N?new c(h,r,n,u):e.error("Type "+s(h)+" is not interpolatable.")},c.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var o=u(e,n),s=e[o],l=e[o+1],h=c.interpolationFactor(this.interpolation,n,s,l),f=r[o].evaluate(t),p=r[o+1].evaluate(t);return a[this.type.kind.toLowerCase()](f,p,h)},c.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;eNumber.MAX_SAFE_INTEGER)return h.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof d&&Math.floor(d)!==d)return h.error("Numeric branch labels must be integer values.");if(r){if(h.checkSubtype(r,n(d)))return null}else r=n(d);if(void 0!==o[String(d)])return h.error("Branch labels must be unique.");o[String(d)]=s.length}var g=e.parse(c,l,a);if(!g)return null;a=a||g.type,s.push(g)}var v=e.parse(t[1],1,r);if(!v)return null;var m=e.parse(t[t.length-1],t.length-1,a);return m?new i(r,a,v,o,s,m):null},i.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},i.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)},i.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t},e.exports=i},{"../values":147}],136:[function(t,e,r){var n=t("../types").NumberType,i=t("../stops").findStopLessThanOrEqualTo,a=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n=u)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',h);var p=e.parse(c,f,s);if(!p)return null;s=s||p.type,o.push([u,p])}return new a(s,r,o)},a.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var a=e.length;return n>=e[a-1]?r[a-1].evaluate(t):r[i(e,n)].evaluate(t)},a.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e0&&"string"==typeof t[0]&&t[0]in g}function i(t,e,r){void 0===r&&(r={});var n=new l(g,[],function(t){var e={color:z,string:P,number:I,enum:P,boolean:D};return"array"===t.type?R(e[t.value]||O,t.length):e[t.type]||null}(e)),i=n.parse(t);return i?x(!1===r.handleErrors?new _(i):new w(i,e)):b(n.errors)}function a(t,e,r){if(void 0===r&&(r={}),"error"===(t=i(t,e,r)).result)return t;var n=t.value.expression,a=v.isFeatureConstant(n);if(!a&&!e["property-function"])return b([new s("","property expressions not supported")]);var o=v.isGlobalPropertyConstant(n,["zoom"]);if(!o&&!1===e["zoom-function"])return b([new s("","zoom expressions not supported")]);var l=function t(e){var r=null;if(e instanceof d)r=t(e.result);else if(e instanceof p)for(var n=0,i=e.args;n=0)return!1;var i=!0;return e.eachChild(function(e){i&&!t(e,r)&&(i=!1)}),i}}},{"./compound_expression":123}],141:[function(t,e,r){var n=t("./scope"),i=t("./types").checkSubtype,a=t("./parsing_error"),o=t("./definitions/literal"),s=t("./definitions/assertion"),l=t("./definitions/array"),u=t("./definitions/coercion"),c=function(t,e,r,i,a){void 0===e&&(e=[]),void 0===i&&(i=new n),void 0===a&&(a=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=i,this.errors=a,this.expectedType=r};c.prototype.parse=function(e,r,n,i,a){void 0===a&&(a={});var c=this;if(r&&(c=c.concat(r,n,i)),null!==e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e||(e=["literal",e]),Array.isArray(e)){if(0===e.length)return c.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var h=e[0];if("string"!=typeof h)return c.error("Expression name must be a string, but found "+typeof h+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var f=c.registry[h];if(f){var p=f.parse(e,c);if(!p)return null;if(c.expectedType){var d=c.expectedType,g=p.type;if("string"!==d.kind&&"number"!==d.kind&&"boolean"!==d.kind||"value"!==g.kind)if("array"===d.kind&&"value"===g.kind)a.omitTypeAnnotations||(p=new l(d,p));else if("color"!==d.kind||"value"!==g.kind&&"string"!==g.kind){if(c.checkSubtype(c.expectedType,p.type))return null}else a.omitTypeAnnotations||(p=new u(d,[p]));else a.omitTypeAnnotations||(p=new s(d,[p]))}if(!(p instanceof o)&&function(e){var r=t("./compound_expression").CompoundExpression,n=t("./is_constant"),i=n.isGlobalPropertyConstant,a=n.isFeatureConstant;if(e instanceof t("./definitions/var"))return!1;if(e instanceof r&&"error"===e.name)return!1;var s=!0;return e.eachChild(function(t){t instanceof o||(s=!1)}),!!s&&a(e)&&i(e,["zoom","heatmap-density"])}(p)){var v=new(t("./evaluation_context"));try{p=new o(p.type,p.evaluate(v))}catch(e){return c.error(e.message),null}}return p}return c.error('Unknown expression "'+h+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===e?c.error("'undefined' value invalid. Use null instead."):"object"==typeof e?c.error('Bare objects invalid. Use ["literal", {...}] instead.'):c.error("Expected an array, but found "+typeof e+" instead.")},c.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new c(this.registry,n,e||null,i,this.errors)},c.prototype.error=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];var i=""+this.key+r.map(function(t){return"["+t+"]"}).join("");this.errors.push(new a(i,t))},c.prototype.checkSubtype=function(t,e){var r=i(t,e);return r&&this.error(r),r},e.exports=c},{"./compound_expression":123,"./definitions/array":124,"./definitions/assertion":125,"./definitions/coercion":129,"./definitions/literal":134,"./definitions/var":137,"./evaluation_context":138,"./is_constant":140,"./parsing_error":142,"./scope":144,"./types":146}],142:[function(t,e,r){var n=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);e.exports=n},{}],143:[function(t,e,r){var n=function(t){this.name="ExpressionEvaluationError",this.message=t};n.prototype.toJSON=function(){return this.message},e.exports=n},{}],144:[function(t,e,r){var n=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;rr&&ee))throw new n("Input is not a number.");o=s-1}}return Math.max(s-1,0)}}},{"./runtime_error":143}],146:[function(t,e,r){function n(t,e){return{kind:"array",itemType:t,N:e}}function i(t){if("array"===t.kind){var e=i(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var a={kind:"null"},o={kind:"number"},s={kind:"string"},l={kind:"boolean"},u={kind:"color"},c={kind:"object"},h={kind:"value"},f=[a,o,s,l,u,c,n(h)];e.exports={NullType:a,NumberType:o,StringType:s,BooleanType:l,ColorType:u,ObjectType:c,ValueType:h,array:n,ErrorType:{kind:"error"},toString:i,checkSubtype:function t(e,r){if("error"===r.kind)return null;if("array"===e.kind){if("array"===r.kind&&!t(e.itemType,r.itemType)&&("number"!=typeof e.N||e.N===r.N))return null}else{if(e.kind===r.kind)return null;if("value"===e.kind)for(var n=0,a=f;n=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."},isValue:function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof n)return!0;if(Array.isArray(e)){for(var r=0,i=e;r=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);ee?1:0}function a(t){if(!t)return!0;var e=t[0];return t.length<=1?"any"!==e:"=="===e?o(t[1],t[2],"=="):"!="===e?u(o(t[1],t[2],"==")):"<"===e||">"===e||"<="===e||">="===e?o(t[1],t[2],e):"any"===e?function(t){return["any"].concat(t.map(a))}(t.slice(1)):"all"===e?["all"].concat(t.slice(1).map(a)):"none"===e?["all"].concat(t.slice(1).map(a).map(u)):"in"===e?s(t[1],t.slice(2)):"!in"===e?u(s(t[1],t.slice(2))):"has"===e?l(t[1]):"!has"!==e||u(l(t[1]))}function o(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function s(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(i)]]:["filter-in-small",t,["literal",e]]}}function l(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function u(t){return["!",t]}var c=t("../expression").createExpression;e.exports=function(t){if(!t)return function(){return!0};n(t)||(t=a(t));var e=c(t,h);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}},e.exports.isExpressionFilter=n;var h={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0}},{"../expression":139}],149:[function(t,e,r){function n(t){return t}function i(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function a(t,e,r,n,a){return i(typeof r===a?n[r]:void 0,t.default,e.default)}function o(t,e,r){if("number"!==p(r))return i(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var a=u(t.stops,r);return t.stops[a][1]}function s(t,e,r){var a=void 0!==t.base?t.base:1;if("number"!==p(r))return i(t.default,e.default);var o=t.stops.length;if(1===o)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[o-1][0])return t.stops[o-1][1];var s=u(t.stops,r),l=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,a,t.stops[s][0],t.stops[s+1][0]),h=t.stops[s][1],f=t.stops[s+1][1],g=d[e.type]||n;if(t.colorSpace&&"rgb"!==t.colorSpace){var v=c[t.colorSpace];g=function(t,e){return v.reverse(v.interpolate(v.forward(t),v.forward(e),l))}}return"function"==typeof h.evaluate?{evaluate:function(){for(var t=arguments,e=[],r=arguments.length;r--;)e[r]=t[r];var n=h.evaluate.apply(void 0,e),i=f.evaluate.apply(void 0,e);if(void 0!==n&&void 0!==i)return g(n,i,l)}}:g(h,f,l)}function l(t,e,r){return"color"===e.type?r=h.parse(r):p(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),i(r,t.default,e.default)}function u(t,e){for(var r,n,i=0,a=t.length-1,o=0;i<=a;){if(r=t[o=Math.floor((i+a)/2)][0],n=t[o+1][0],e===r||e>r&&ee&&(a=o-1)}return Math.max(o-1,0)}var c=t("../util/color_spaces"),h=t("../util/color"),f=t("../util/extend"),p=t("../util/get_type"),d=t("../util/interpolate"),g=t("../expression/definitions/interpolate");e.exports={createFunction:function t(e,r){var n,u,p,d="color"===r.type,v=e.stops&&"object"==typeof e.stops[0][0],m=v||void 0!==e.property,y=v||!m,x=e.type||("interpolated"===r.function?"exponential":"interval");if(d&&((e=f({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],h.parse(t[1])]})),e.default?e.default=h.parse(e.default):e.default=h.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!c[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===x)n=s;else if("interval"===x)n=o;else if("categorical"===x){n=a,u=Object.create(null);for(var b=0,_=e.stops;b<_.length;b+=1){var w=_[b];u[w[0]]=w[1]}p=typeof e.stops[0][0]}else{if("identity"!==x)throw new Error('Unknown function type "'+x+'"');n=l}if(v){for(var M={},A=[],k=0;k":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}}}},{}],153:[function(t,e,r){var n=t("csscolorparser").parseCSSColor,i=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n};i.parse=function(t){if(t){if(t instanceof i)return t;if("string"==typeof t){var e=n(t);if(e)return new i(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},i.prototype.toString=function(){var t=this;return"rgba("+[this.r,this.g,this.b].map(function(e){return Math.round(255*e/t.a)}).concat(this.a).join(",")+")"},i.black=new i(0,0,0,1),i.white=new i(1,1,1,1),i.transparent=new i(0,0,0,0),e.exports=i},{csscolorparser:13}],154:[function(t,e,r){function n(t){return t>m?Math.pow(t,1/3):t/v+d}function i(t){return t>g?t*t*t:v*(t-d)}function a(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function o(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function s(t){var e=o(t.r),r=o(t.g),i=o(t.b),a=n((.4124564*e+.3575761*r+.1804375*i)/h),s=n((.2126729*e+.7151522*r+.072175*i)/f);return{l:116*s-16,a:500*(a-s),b:200*(s-n((.0193339*e+.119192*r+.9503041*i)/p)),alpha:t.a}}function l(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=f*i(e),r=h*i(r),n=p*i(n),new u(a(3.2404542*r-1.5371385*e-.4985314*n),a(-.969266*r+1.8760108*e+.041556*n),a(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var u=t("./color"),c=t("./interpolate").number,h=.95047,f=1,p=1.08883,d=4/29,g=6/29,v=3*g*g,m=g*g*g,y=Math.PI/180,x=180/Math.PI;e.exports={lab:{forward:s,reverse:l,interpolate:function(t,e,r){return{l:c(t.l,e.l,r),a:c(t.a,e.a,r),b:c(t.b,e.b,r),alpha:c(t.alpha,e.alpha,r)}}},hcl:{forward:function(t){var e=s(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*x;return{h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*y,r=t.c;return l({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:c(t.c,e.c,r),l:c(t.l,e.l,r),alpha:c(t.alpha,e.alpha,r)}}}}},{"./color":153,"./interpolate":158}],155:[function(t,e,r){e.exports=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n0;)r[n]=e[n+1];for(var i=0,a=r;i":case">=":r.length>=2&&"$type"===s(r[1])&&c.push(new n(i,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&c.push(new n(i,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(l=o(r[1]))&&c.push(new n(i+"[1]",r[1],"string expected, "+l+" found"));for(var h=2;hu(s[0].zoom))return[new n(c,s[0].zoom,"stop zoom values must appear in ascending order")];u(s[0].zoom)!==f&&(f=u(s[0].zoom),h=void 0,g={}),e=e.concat(o({key:c+"[0]",value:s[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:l,value:r}}))}else e=e.concat(r({key:c+"[0]",value:s[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},s));return e.concat(a({key:c+"[1]",value:s[1],valueSpec:p,style:t.style,styleSpec:t.styleSpec}))}function r(t,e){var r=i(t.value),a=u(t.value),o=null!==t.value?t.value:e;if(c){if(r!==c)return[new n(t.key,o,r+" stop domain type must match previous stop domain type "+c)]}else c=r;if("number"!==r&&"string"!==r&&"boolean"!==r)return[new n(t.key,o,"stop domain value must be a number, string, or boolean")];if("number"!==r&&"categorical"!==d){var s="number expected, "+r+" found";return p["property-function"]&&void 0===d&&(s+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new n(t.key,o,s)]}return"categorical"!==d||"number"!==r||isFinite(a)&&Math.floor(a)===a?"categorical"!==d&&"number"===r&&void 0!==h&&a=8&&(m&&!t.valueSpec["property-function"]?x.push(new n(t.key,t.value,"property functions not supported")):v&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&x.push(new n(t.key,t.value,"zoom functions not supported"))),"categorical"!==d&&!y||void 0!==t.value.property||x.push(new n(t.key,t.value,'"property" property is required')),x}},{"../error/validation_error":122,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162,"./validate_array":163,"./validate_number":175,"./validate_object":176}],171:[function(t,e,r){var n=t("../error/validation_error"),i=t("./validate_string");e.exports=function(t){var e=t.value,r=t.key,a=i(t);return a.length?a:(-1===e.indexOf("{fontstack}")&&a.push(new n(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&a.push(new n(r,e,'"glyphs" url must include a "{range}" token')),a)}},{"../error/validation_error":122,"./validate_string":180}],172:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_filter"),s=t("./validate_paint_property"),l=t("./validate_layout_property"),u=t("./validate"),c=t("../util/extend");e.exports=function(t){var e=[],r=t.value,h=t.key,f=t.style,p=t.styleSpec;r.type||r.ref||e.push(new n(h,r,'either "type" or "ref" is required'));var d,g=i(r.type),v=i(r.ref);if(r.id)for(var m=i(r.id),y=0;ya.maximum?[new i(e,r,r+" is greater than the maximum value "+a.maximum)]:[]}},{"../error/validation_error":122,"../util/get_type":157}],176:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/get_type"),a=t("./validate");e.exports=function(t){var e=t.key,r=t.value,o=t.valueSpec||{},s=t.objectElementValidators||{},l=t.style,u=t.styleSpec,c=[],h=i(r);if("object"!==h)return[new n(e,r,"object expected, "+h+" found")];for(var f in r){var p=f.split(".")[0],d=o[p]||o["*"],g=void 0;if(s[p])g=s[p];else if(o[p])g=a;else if(s["*"])g=s["*"];else{if(!o["*"]){c.push(new n(e,r[f],'unknown property "'+f+'"'));continue}g=a}c=c.concat(g({key:(e?e+".":e)+f,value:r[f],valueSpec:d,style:l,styleSpec:u,object:r,objectKey:f},r))}for(var v in o)s[v]||o[v].required&&void 0===o[v].default&&void 0===r[v]&&c.push(new n(e,r,'missing required property "'+v+'"'));return c}},{"../error/validation_error":122,"../util/get_type":157,"./validate":162}],177:[function(t,e,r){var n=t("./validate_property");e.exports=function(t){return n(t,"paint")}},{"./validate_property":178}],178:[function(t,e,r){var n=t("./validate"),i=t("../error/validation_error"),a=t("../util/get_type"),o=t("../function").isFunction,s=t("../util/unbundle_jsonlint");e.exports=function(t,e){var r=t.key,l=t.style,u=t.styleSpec,c=t.value,h=t.objectKey,f=u[e+"_"+t.layerType];if(!f)return[];var p=h.match(/^(.*)-transition$/);if("paint"===e&&p&&f[p[1]]&&f[p[1]].transition)return n({key:r,value:c,valueSpec:u.transition,style:l,styleSpec:u});var d,g=t.valueSpec||f[h];if(!g)return[new i(r,c,'unknown property "'+h+'"')];if("string"===a(c)&&g["property-function"]&&!g.tokens&&(d=/^{([^}]+)}$/.exec(c)))return[new i(r,c,'"'+h+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(d[1])+" }`.")];var v=[];return"symbol"===t.layerType&&("text-field"===h&&l&&!l.glyphs&&v.push(new i(r,c,'use of "text-field" requires a style "glyphs" property')),"text-font"===h&&o(s.deep(c))&&"identity"===s(c.type)&&v.push(new i(r,c,'"text-font" does not support identity functions'))),v.concat(n({key:t.key,value:c,valueSpec:g,style:l,styleSpec:u,expressionContext:"property",propertyKey:h}))}},{"../error/validation_error":122,"../function":149,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162}],179:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_enum");e.exports=function(t){var e=t.value,r=t.key,s=t.styleSpec,l=t.style;if(!e.type)return[new n(r,e,'"type" is required')];var u=i(e.type),c=[];switch(u){case"vector":case"raster":case"raster-dem":if(c=c.concat(a({key:r,value:e,valueSpec:s["source_"+u.replace("-","_")],style:t.style,styleSpec:s})),"url"in e)for(var h in e)["type","url","tileSize"].indexOf(h)<0&&c.push(new n(r+"."+h,e[h],'a source with a "url" property may not include a "'+h+'" property'));return c;case"geojson":return a({key:r,value:e,valueSpec:s.source_geojson,style:l,styleSpec:s});case"video":return a({key:r,value:e,valueSpec:s.source_video,style:l,styleSpec:s});case"image":return a({key:r,value:e,valueSpec:s.source_image,style:l,styleSpec:s});case"canvas":return a({key:r,value:e,valueSpec:s.source_canvas,style:l,styleSpec:s});default:return o({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image","canvas"]},style:l,styleSpec:s})}}},{"../error/validation_error":122,"../util/unbundle_jsonlint":161,"./validate_enum":167,"./validate_object":176}],180:[function(t,e,r){var n=t("../util/get_type"),i=t("../error/validation_error");e.exports=function(t){var e=t.value,r=t.key,a=n(e);return"string"!==a?[new i(r,e,"string expected, "+a+" found")]:[]}},{"../error/validation_error":122,"../util/get_type":157}],181:[function(t,e,r){function n(t,e){e=e||l;var r=[];return r=r.concat(s({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:u,"*":function(){return[]}}})),t.constants&&(r=r.concat(o({key:"constants",value:t.constants,style:t,styleSpec:e}))),i(r)}function i(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function a(t){return function(){return i(t.apply(this,arguments))}}var o=t("./validate/validate_constants"),s=t("./validate/validate"),l=t("./reference/latest"),u=t("./validate/validate_glyphs_url");n.source=a(t("./validate/validate_source")),n.light=a(t("./validate/validate_light")),n.layer=a(t("./validate/validate_layer")),n.filter=a(t("./validate/validate_filter")),n.paintProperty=a(t("./validate/validate_paint_property")),n.layoutProperty=a(t("./validate/validate_layout_property")),e.exports=n},{"./reference/latest":151,"./validate/validate":162,"./validate/validate_constants":166,"./validate/validate_filter":169,"./validate/validate_glyphs_url":171,"./validate/validate_layer":172,"./validate/validate_layout_property":173,"./validate/validate_light":174,"./validate/validate_paint_property":177,"./validate/validate_source":179}],182:[function(t,e,r){var n=t("./zoom_history"),i=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new n,this.transition={})};i.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},e.exports=i},{"./zoom_history":212}],183:[function(t,e,r){var n=t("../style-spec/reference/latest"),i=t("../util/util"),a=t("../util/evented"),o=t("./validate_style"),s=t("../util/util").sphericalToCartesian,l=(t("../style-spec/util/color"),t("../style-spec/util/interpolate")),u=t("./properties"),c=u.Properties,h=u.Transitionable,f=(u.Transitioning,u.PossiblyEvaluated,u.DataConstantProperty),p=function(){this.specification=n.light.position};p.prototype.possiblyEvaluate=function(t,e){return s(t.expression.evaluate(e))},p.prototype.interpolate=function(t,e,r){return{x:l.number(t.x,e.x,r),y:l.number(t.y,e.y,r),z:l.number(t.z,e.z,r)}};var d=new c({anchor:new f(n.light.anchor),position:new p,color:new f(n.light.color),intensity:new f(n.light.intensity)}),g=function(t){function e(e){t.call(this),this._transitionable=new h(d),this.setLight(e),this._transitioning=this._transitionable.untransitioned()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLight=function(){return this._transitionable.serialize()},e.prototype.setLight=function(t){if(!this._validate(o.light,t))for(var e in t){var r=t[e];i.endsWith(e,"-transition")?this._transitionable.setTransition(e.slice(0,-"-transition".length),r):this._transitionable.setValue(e,r)}},e.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning)},e.prototype.hasTransition=function(){return this._transitioning.hasTransition()},e.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t)},e.prototype._validate=function(t,e){return o.emitErrors(this,t.call(o,i.extend({value:e,style:{glyphs:!0,sprite:!0},styleSpec:n})))},e}(a);e.exports=g},{"../style-spec/reference/latest":151,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/evented":260,"../util/util":275,"./properties":188,"./validate_style":211}],184:[function(t,e,r){var n=t("../util/mapbox").normalizeGlyphsURL,i=t("../util/ajax"),a=t("./parse_glyph_pbf");e.exports=function(t,e,r,o,s){var l=256*e,u=l+255,c=o(n(r).replace("{fontstack}",t).replace("{range}",l+"-"+u),i.ResourceType.Glyphs);i.getArrayBuffer(c,function(t,e){if(t)s(t);else if(e){for(var r={},n=0,i=a(e.data);n1?"@2x":"";n.getJSON(e(a(t,h,".json"),n.ResourceType.SpriteJSON),function(t,e){c||(c=t,l=e,s())}),n.getImage(e(a(t,h,".png"),n.ResourceType.SpriteImage),function(t,e){c||(c=t,u=e,s())})}},{"../util/ajax":251,"../util/browser":252,"../util/image":263,"../util/mapbox":267}],186:[function(t,e,r){function n(t,e,r){1===t&&r.readMessage(i,e)}function i(t,e,r){if(3===t){var n=r.readMessage(a,{}),i=n.id,s=n.bitmap,u=n.width,c=n.height,h=n.left,f=n.top,p=n.advance;e.push({id:i,bitmap:new o({width:u+2*l,height:c+2*l},s),metrics:{width:u,height:c,left:h,top:f,advance:p}})}}function a(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint())}var o=t("../util/image").AlphaImage,s=t("pbf"),l=3;e.exports=function(t){return new s(t).readFields(n,[])},e.exports.GLYPH_PBF_BORDER=l},{"../util/image":263,pbf:30}],187:[function(t,e,r){var n=t("../util/browser"),i=t("../symbol/placement"),a=function(){this._currentTileIndex=0,this._seenCrossTileIDs={}};a.prototype.continuePlacement=function(t,e,r,n,i){for(var a=this;this._currentTileIndex2};this._currentPlacementIndex>=0;){var l=e[t[i._currentPlacementIndex]],u=i.placement.collisionIndex.transform.zoom;if("symbol"===l.type&&(!l.minzoom||l.minzoom<=u)&&(!l.maxzoom||l.maxzoom>u)){if(i._inProgressLayer||(i._inProgressLayer=new a),i._inProgressLayer.continuePlacement(r[l.source],i.placement,i._showCollisionBoxes,l,s))return;delete i._inProgressLayer}i._currentPlacementIndex--}this._done=!0},o.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement},e.exports=o},{"../symbol/placement":223,"../util/browser":252}],188:[function(t,e,r){var n=t("../util/util"),i=n.clone,a=n.extend,o=n.easeCubicInOut,s=t("../style-spec/util/interpolate"),l=t("../style-spec/expression").normalizePropertyExpression,u=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),c=function(t,e){this.property=t,this.value=e,this.expression=l(void 0===e?t.specification.default:e,t.specification)};c.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},c.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var h=function(t){this.property=t,this.value=new c(t,void 0)};h.prototype.transitioned=function(t,e){return new p(this.property,this.value,e,a({},t.transition,this.transition),t.now)},h.prototype.untransitioned=function(){return new p(this.property,this.value,null,{},0)};var f=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)};f.prototype.getValue=function(t){return i(this._values[t].value.value)},f.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new h(this._values[t].property)),this._values[t].value=new c(this._values[t].property,null===e?void 0:i(e))},f.prototype.getTransition=function(t){return i(this._values[t].transition)},f.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new h(this._values[t].property)),this._values[t].transition=i(e)||void 0},f.prototype.serialize=function(){for(var t=this,e={},r=0,n=Object.keys(t._values);rthis.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(en.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:a+(1-a)*o}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-o)*a}},b.prototype.interpolate=function(t){return t};var _=function(t){this.specification=t};_.prototype.possiblyEvaluate=function(){},_.prototype.interpolate=function(){};u("DataDrivenProperty",x),u("DataConstantProperty",y),u("CrossFadedProperty",b),u("HeatmapColorProperty",_),e.exports={PropertyValue:c,Transitionable:f,Transitioning:d,Layout:g,PossiblyEvaluatedPropertyValue:v,PossiblyEvaluated:m,DataConstantProperty:y,DataDrivenProperty:x,CrossFadedProperty:b,HeatmapColorProperty:_,Properties:function(t){var e=this;for(var r in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var n=t[r],i=e.defaultPropertyValues[r]=new c(n,void 0),a=e.defaultTransitionablePropertyValues[r]=new h(n);e.defaultTransitioningPropertyValues[r]=a.untransitioned(),e.defaultPossiblyEvaluatedValues[r]=i.possiblyEvaluate({})}}}},{"../style-spec/expression":139,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/util":275,"../util/web_worker_transfer":278}],189:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports={getMaximumPaintValue:function(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max},translateDistance:function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},translate:function(t,e,r,i,a){if(!e[0]&&!e[1])return t;var o=n.convert(e);"viewport"===r&&o._rotate(-i);for(var s=[],l=0;l0)throw new Error("Unimplemented: "+n.map(function(t){return t.command}).join(", ")+".");return r.forEach(function(t){"setTransition"!==t.command&&e[t.command].apply(e,t.args)}),this.stylesheet=t,!0},e.prototype.addImage=function(t,e){if(this.getImage(t))return this.fire("error",{error:new Error("An image with this name already exists.")});this.imageManager.addImage(t,e),this.fire("data",{dataType:"style"})},e.prototype.getImage=function(t){return this.imageManager.getImage(t)},e.prototype.removeImage=function(t){if(!this.getImage(t))return this.fire("error",{error:new Error("No image with this name exists.")});this.imageManager.removeImage(t),this.fire("data",{dataType:"style"})},e.prototype.addSource=function(t,e,r){var n=this;if(this._checkLoaded(),void 0!==this.sourceCaches[t])throw new Error("There is already a source with this ID");if(!e.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(e).join(", ")+".");if(!(["vector","raster","geojson","video","image","canvas"].indexOf(e.type)>=0&&this._validate(g.source,"sources."+t,e,null,r))){this.map&&this.map._collectResourceTiming&&(e.collectResourceTiming=!0);var i=this.sourceCaches[t]=new x(t,e,this.dispatcher);i.style=this,i.setEventedParent(this,function(){return{isSourceLoaded:n.loaded(),source:i.serialize(),sourceId:t}}),i.onAdd(this.map),this._changed=!0}},e.prototype.removeSource=function(t){var e=this;if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error("There is no source with this ID");for(var r in e._layers)if(e._layers[r].source===t)return e.fire("error",{error:new Error('Source "'+t+'" cannot be removed while layer "'+r+'" is using it.')});var n=this.sourceCaches[t];delete this.sourceCaches[t],delete this._updatedSources[t],n.fire("data",{sourceDataType:"metadata",dataType:"source",sourceId:t}),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0},e.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0},e.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},e.prototype.addLayer=function(t,e,r){this._checkLoaded();var n=t.id;if("object"==typeof t.source&&(this.addSource(n,t.source),t=c.clone(t),t=c.extend(t,{source:n})),!this._validate(g.layer,"layers."+n,t,{arrayIndex:-1},r)){var a=i.create(t);this._validateLayer(a),a.setEventedParent(this,{layer:{id:n}});var o=e?this._order.indexOf(e):this._order.length;if(e&&-1===o)return void this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')});if(this._order.splice(o,0,n),this._layerOrderChanged=!0,this._layers[n]=a,this._removedLayers[n]&&a.source){var s=this._removedLayers[n];delete this._removedLayers[n],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause())}this._updateLayer(a)}},e.prototype.moveLayer=function(t,e){if(this._checkLoaded(),this._changed=!0,this._layers[t]){var r=this._order.indexOf(t);this._order.splice(r,1);var n=e?this._order.indexOf(e):this._order.length;e&&-1===n?this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')}):(this._order.splice(n,0,t),this._layerOrderChanged=!0)}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be moved.")})},e.prototype.removeLayer=function(t){this._checkLoaded();var e=this._layers[t];if(e){e.setEventedParent(null);var r=this._order.indexOf(t);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[t]=e,delete this._layers[t],delete this._updatedLayers[t],delete this._updatedPaintProps[t]}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be removed.")})},e.prototype.getLayer=function(t){return this._layers[t]},e.prototype.setLayerZoomRange=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?n.minzoom===e&&n.maxzoom===r||(null!=e&&(n.minzoom=e),null!=r&&(n.maxzoom=r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot have zoom extent.")})},e.prototype.setFilter=function(t,e){this._checkLoaded();var r=this.getLayer(t);if(r)return c.deepEqual(r.filter,e)?void 0:null===e||void 0===e?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(g.filter,"layers."+r.id+".filter",e)||(r.filter=c.clone(e),this._updateLayer(r)));this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be filtered.")})},e.prototype.getFilter=function(t){return c.clone(this.getLayer(t).filter)},e.prototype.setLayoutProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?c.deepEqual(n.getLayoutProperty(e),r)||(n.setLayoutProperty(e,r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},e.prototype.setPaintProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);if(n){if(!c.deepEqual(n.getPaintProperty(e),r)){var i=n._transitionablePaint._values[e].value.isDataDriven();n.setPaintProperty(e,r),(n._transitionablePaint._values[e].value.isDataDriven()||i)&&this._updateLayer(n),this._changed=!0,this._updatedPaintProps[t]=!0}}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},e.prototype.getTransition=function(){return c.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},e.prototype.serialize=function(){var t=this;return c.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:c.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(e){return t._layers[e].serialize()})},function(t){return void 0!==t})},e.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0},e.prototype._flattenRenderedFeatures=function(t){for(var e=[],r=this._order.length-1;r>=0;r--)for(var n=this._order[r],i=0,a=t;i=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t)},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),n.filterObject(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,o){return(!o||!1!==o.validate)&&a.emitErrors(this,t.call(a,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:i,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(o));e.exports=c;var h={circle:t("./style_layer/circle_style_layer"),heatmap:t("./style_layer/heatmap_style_layer"),hillshade:t("./style_layer/hillshade_style_layer"),fill:t("./style_layer/fill_style_layer"),"fill-extrusion":t("./style_layer/fill_extrusion_style_layer"),line:t("./style_layer/line_style_layer"),symbol:t("./style_layer/symbol_style_layer"),background:t("./style_layer/background_style_layer"),raster:t("./style_layer/raster_style_layer")};c.create=function(t){return new h[t.type](t)}},{"../style-spec/reference/latest":151,"../util/evented":260,"../util/util":275,"./properties":188,"./style_layer/background_style_layer":192,"./style_layer/circle_style_layer":194,"./style_layer/fill_extrusion_style_layer":196,"./style_layer/fill_style_layer":198,"./style_layer/heatmap_style_layer":200,"./style_layer/hillshade_style_layer":202,"./style_layer/line_style_layer":204,"./style_layer/raster_style_layer":206,"./style_layer/symbol_style_layer":208,"./validate_style":211}],192:[function(t,e,r){var n=t("../style_layer"),i=t("./background_style_layer_properties"),a=t("../properties"),o=(a.Transitionable,a.Transitioning,a.PossiblyEvaluated,function(t){function e(e){t.call(this,e,i)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(n));e.exports=o},{"../properties":188,"../style_layer":191,"./background_style_layer_properties":193}],193:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=(i.DataDrivenProperty,i.CrossFadedProperty),l=(i.HeatmapColorProperty,new a({"background-color":new o(n.paint_background["background-color"]),"background-pattern":new s(n.paint_background["background-pattern"]),"background-opacity":new o(n.paint_background["background-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],194:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/circle_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiPoint,o=t("../query_utils"),s=o.getMaximumPaintValue,l=o.translateDistance,u=o.translate,c=t("./circle_style_layer_properties"),h=t("../properties"),f=(h.Transitionable,h.Transitioning,h.PossiblyEvaluated,function(t){function e(e){t.call(this,e,c)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(t){var e=t;return s("circle-radius",this,e)+s("circle-stroke-width",this,e)+l(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=u(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i,o),l=this.paint.get("circle-radius").evaluate(e)*o,c=this.paint.get("circle-stroke-width").evaluate(e)*o;return a(s,r,l+c)},e}(n));e.exports=f},{"../../data/bucket/circle_bucket":42,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./circle_style_layer_properties":195}],195:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=(i.CrossFadedProperty,i.HeatmapColorProperty,new a({"circle-radius":new s(n.paint_circle["circle-radius"]),"circle-color":new s(n.paint_circle["circle-color"]),"circle-blur":new s(n.paint_circle["circle-blur"]),"circle-opacity":new s(n.paint_circle["circle-opacity"]),"circle-translate":new o(n.paint_circle["circle-translate"]),"circle-translate-anchor":new o(n.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new o(n.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new o(n.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new s(n.paint_circle["circle-stroke-width"]),"circle-stroke-color":new s(n.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new s(n.paint_circle["circle-stroke-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],196:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_extrusion_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,o=t("../query_utils"),s=o.translateDistance,l=o.translate,u=t("./fill_extrusion_style_layer_properties"),c=t("../properties"),h=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=l(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i,o);return a(s,r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null)},e}(n));e.exports=h},{"../../data/bucket/fill_extrusion_bucket":46,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_extrusion_style_layer_properties":197}],197:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new a({"fill-extrusion-opacity":new o(n["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new s(n["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new o(n["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new o(n["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new l(n["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new s(n["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new s(n["paint_fill-extrusion"]["fill-extrusion-base"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],198:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,o=t("../query_utils"),s=o.translateDistance,l=o.translate,u=t("./fill_style_layer_properties"),c=t("../properties"),h=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t),void 0===this._transitionablePaint.getValue("fill-outline-color")&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])},e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=l(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i,o);return a(s,r)},e}(n));e.exports=h},{"../../data/bucket/fill_bucket":44,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_style_layer_properties":199}],199:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new a({"fill-antialias":new o(n.paint_fill["fill-antialias"]),"fill-opacity":new s(n.paint_fill["fill-opacity"]),"fill-color":new s(n.paint_fill["fill-color"]),"fill-outline-color":new s(n.paint_fill["fill-outline-color"]),"fill-translate":new o(n.paint_fill["fill-translate"]),"fill-translate-anchor":new o(n.paint_fill["fill-translate-anchor"]),"fill-pattern":new l(n.paint_fill["fill-pattern"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],200:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/heatmap_bucket"),a=t("../../util/image").RGBAImage,o=t("./heatmap_style_layer_properties"),s=t("../properties"),l=(s.Transitionable,s.Transitioning,s.PossiblyEvaluated,function(t){function e(e){t.call(this,e,o),this._updateColorRamp()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp()},e.prototype._updateColorRamp=function(){for(var t=this._transitionablePaint._values["heatmap-color"].value.expression,e=new Uint8Array(1024),r=e.length,n=4;n0?e+2*t:t}var i=t("@mapbox/point-geometry"),a=t("../style_layer"),o=t("../../data/bucket/line_bucket"),s=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiLine,l=t("../query_utils"),u=l.getMaximumPaintValue,c=l.translateDistance,h=l.translate,f=t("./line_style_layer_properties"),p=t("../../util/util").extend,d=t("../evaluation_parameters"),g=t("../properties"),v=(g.Transitionable,g.Transitioning,g.Layout,g.PossiblyEvaluated,new(function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new d(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(g.DataDrivenProperty))(f.paint.properties["line-width"].specification));v.useIntegerZoom=!0;var m=function(t){function e(e){t.call(this,e,f)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=v.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)},e.prototype.createBucket=function(t){return new o(t)},e.prototype.queryRadius=function(t){var e=t,r=n(u("line-width",this,e),u("line-gap-width",this,e)),i=u("line-offset",this,e);return r/2+Math.abs(i)+c(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,a,o,l){var u=h(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o,l),c=l/2*n(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),f=this.paint.get("line-offset").evaluate(e);return f&&(r=function(t,e){for(var r=[],n=new i(0,0),a=0;ar?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom-r/2;){if(--o<0)return!1;s-=t[o].dist(a),a=t[o]}s+=t[o].dist(t[o+1]),o++;for(var l=[],u=0;sn;)u-=l.shift().angleDelta;if(u>i)return!1;o++,s+=h.dist(f)}return!0}},{}],215:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports=function(t,e,r,i,a){for(var o=[],s=0;s=i&&f.x>=i||(h.x>=i?h=new n(i,h.y+(f.y-h.y)*((i-h.x)/(f.x-h.x)))._round():f.x>=i&&(f=new n(i,h.y+(f.y-h.y)*((i-h.x)/(f.x-h.x)))._round()),h.y>=a&&f.y>=a||(h.y>=a?h=new n(h.x+(f.x-h.x)*((a-h.y)/(f.y-h.y)),a)._round():f.y>=a&&(f=new n(h.x+(f.x-h.x)*((a-h.y)/(f.y-h.y)),a)._round()),u&&h.equals(u[u.length-1])||(u=[h],o.push(u)),u.push(f)))))}return o}},{"@mapbox/point-geometry":4}],216:[function(t,e,r){var n=function(t,e,r,n,i,a,o,s,l,u,c){var h=o.top*s-l,f=o.bottom*s+l,p=o.left*s-l,d=o.right*s+l;if(this.boxStartIndex=t.length,u){var g=f-h,v=d-p;g>0&&(g=Math.max(10*s,g),this._addLineCollisionCircles(t,e,r,r.segment,v,g,n,i,a,c))}else t.emplaceBack(r.x,r.y,p,h,d,f,n,i,a,0,0);this.boxEndIndex=t.length};n.prototype._addLineCollisionCircles=function(t,e,r,n,i,a,o,s,l,u){var c=a/2,h=Math.floor(i/c),f=1+.4*Math.log(u)/Math.LN2,p=Math.floor(h*f/2),d=-a/2,g=r,v=n+1,m=d,y=-i/2,x=y-i/4;do{if(--v<0){if(m>y)return;v=0;break}m-=e[v].dist(g),g=e[v]}while(m>x);for(var b=e[v].dist(e[v+1]),_=-p;_i&&(M+=w-i),!(M=e.length)return;b=e[v].dist(e[v+1])}var A=M-m,k=e[v],T=e[v+1].sub(k)._unit()._mult(A)._add(k)._round(),S=Math.abs(M-d)L)n(t,z,!1);else{var R=v.projectPoint(f,P,I),F=D*S;if(m.length>0){var B=R.x-m[m.length-4],N=R.y-m[m.length-3];if(F*F*2>B*B+N*N&&z+8-C&&j=this.screenRightBoundary||n<100||e>this.screenBottomBoundary},e.exports=l},{"../symbol/projection":224,"../util/intersection_tests":264,"./grid_index":220,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],218:[function(t,e,r){var n=t("../data/extent"),i=512/n/2,a=function(t,e,r){var n=this;this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=r;for(var i=0,a=e;it.overscaledZ)for(var u in l){var c=l[u];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,o)}else{var h=l[t.scaledTo(Number(s)).key];h&&h.findMatches(e.symbolInstances,t,o)}}for(var f=0,p=e.symbolInstances;f=0&&k=0&&T=0&&m+p<=d){var S=new i(k,T,M,x);S._round(),s&&!a(e,S,u,s,l)||y.push(S)}}v+=w}return h||y.length||c||(y=t(e,v/2,o,s,l,u,c,!0,f)),y}(t,d?e/2*c%e:(p/2+2*l)*u*c%e,e,f,r,p*u,d,!1,h)}},{"../style-spec/util/interpolate":158,"../symbol/anchor":213,"./check_max_angle":214}],220:[function(t,e,r){var n=function(t,e,r){var n=this.boxCells=[],i=this.circleCells=[];this.xCellCount=Math.ceil(t/r),this.yCellCount=Math.ceil(e/r);for(var a=0;athis.width||n<0||e>this.height)return!i&&[];var a=[];if(t<=0&&e<=0&&this.width<=r&&this.height<=n)a=Array.prototype.slice.call(this.boxKeys).concat(this.circleKeys);else{var o={hitTest:i,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,r,n,this._queryCell,a,o)}return i?a.length>0:a},n.prototype._queryCircle=function(t,e,r,n){var i=t-r,a=t+r,o=e-r,s=e+r;if(a<0||i>this.width||s<0||o>this.height)return!n&&[];var l=[],u={hitTest:n,circle:{x:t,y:e,radius:r},seenUids:{box:{},circle:{}}};return this._forEachCell(i,o,a,s,this._queryCellCircle,l,u),n?l.length>0:l},n.prototype.query=function(t,e,r,n){return this._query(t,e,r,n,!1)},n.prototype.hitTest=function(t,e,r,n){return this._query(t,e,r,n,!0)},n.prototype.hitTestCircle=function(t,e,r){return this._queryCircle(t,e,r,!0)},n.prototype._queryCell=function(t,e,r,n,i,a,o){var s=this,l=o.seenUids,u=this.boxCells[i];if(null!==u)for(var c=this.bboxes,h=0,f=u;h=c[d+0]&&n>=c[d+1]){if(o.hitTest)return a.push(!0),!0;a.push(s.boxKeys[p])}}}var g=this.circleCells[i];if(null!==g)for(var v=this.circles,m=0,y=g;mo*o+s*s},n.prototype._circleAndRectCollide=function(t,e,r,n,i,a,o){var s=(a-n)/2,l=Math.abs(t-(n+s));if(l>s+r)return!1;var u=(o-i)/2,c=Math.abs(e-(i+u));if(c>u+r)return!1;if(l<=s||c<=u)return!0;var h=l-s,f=c-u;return h*h+f*f<=r*r},e.exports=n},{}],221:[function(t,e,r){e.exports=function(t){function e(e){s.push(t[e]),l++}function r(t,e,r){var n=o[t];return delete o[t],o[e]=n,s[n].geometry[0].pop(),s[n].geometry[0]=s[n].geometry[0].concat(r[0]),n}function n(t,e,r){var n=a[e];return delete a[e],a[t]=n,s[n].geometry[0].shift(),s[n].geometry[0]=r[0].concat(s[n].geometry[0]),n}function i(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var a={},o={},s=[],l=0,u=0;u0,A=A&&k.offscreen);var E=_.collisionArrays.textCircles;if(E){var C=t.text.placedSymbolArray.get(_.placedTextSymbolIndices[0]),L=s.evaluateSizeForFeature(t.textSizeData,v,C);T=d.collisionIndex.placeCollisionCircles(E,g.get("text-allow-overlap"),i,a,_.key,C,t.lineVertexArray,t.glyphOffsetArray,L,e,r,o,"map"===g.get("text-pitch-alignment")),w=g.get("text-allow-overlap")||T.circles.length>0,A=A&&T.offscreen}_.collisionArrays.iconBox&&(M=(S=d.collisionIndex.placeCollisionBox(_.collisionArrays.iconBox,g.get("icon-allow-overlap"),a,e)).box.length>0,A=A&&S.offscreen),m||y?y?m||(M=M&&w):w=M&&w:M=w=M&&w,w&&k&&d.collisionIndex.insertCollisionBox(k.box,g.get("text-ignore-placement"),h,f,t.bucketInstanceId,_.textBoxStartIndex),M&&S&&d.collisionIndex.insertCollisionBox(S.box,g.get("icon-ignore-placement"),h,f,t.bucketInstanceId,_.iconBoxStartIndex),w&&T&&d.collisionIndex.insertCollisionCircles(T.circles,g.get("text-ignore-placement"),h,f,t.bucketInstanceId,_.textBoxStartIndex),d.placements[_.crossTileID]=new p(w,M,A||t.justReloaded),l[_.crossTileID]=!0}}t.justReloaded=!1},d.prototype.commit=function(t,e){var r=this;this.commitTime=e;var n=!1,i=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,a=t?t.opacities:{};for(var o in r.placements){var s=r.placements[o],l=a[o];l?(r.opacities[o]=new f(l,i,s.text,s.icon),n=n||s.text!==l.text.placed||s.icon!==l.icon.placed):(r.opacities[o]=new f(null,i,s.text,s.icon,s.skipFade),n=n||s.text||s.icon)}for(var u in a){var c=a[u];if(!r.opacities[u]){var h=new f(c,i,!1,!1);h.isHidden()||(r.opacities[u]=h,n=n||c.text.placed||c.icon.placed)}}n?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)},d.prototype.updateLayerOpacities=function(t,e){for(var r={},n=0,i=e;n0||l.numVerticalGlyphVertices>0,p=l.numIconVertices>0;if(h){for(var d=i(c.text),g=(l.numGlyphVertices+l.numVerticalGlyphVertices)/4,v=0;vt},d.prototype.setStale=function(){this.stale=!0};var g=Math.pow(2,25),v=Math.pow(2,24),m=Math.pow(2,17),y=Math.pow(2,16),x=Math.pow(2,9),b=Math.pow(2,8),_=Math.pow(2,1);e.exports=d},{"../data/extent":53,"../source/pixels_to_tile_units":104,"../style/style_layer/symbol_style_layer_properties":209,"./collision_index":217,"./projection":224,"./symbol_size":228}],224:[function(t,e,r){function n(t,e){var r=[t.x,t.y,0,1];h(r,r,e);var n=r[3];return{point:new f(r[0]/n,r[1]/n),signedDistanceFromCamera:n}}function i(t,e){var r=t[0]/t[3],n=t[1]/t[3];return r>=-e[0]&&r<=e[0]&&n>=-e[1]&&n<=e[1]}function a(t,e,r,n,i,a,o,s,l,c,h,f){var p=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,g=s.lineStartIndex+s.lineLength,v=e.getoffsetX(s.glyphStartIndex),m=e.getoffsetX(p-1),y=u(t*v,r,n,i,a,o,s.segment,d,g,l,c,h,f);if(!y)return null;var x=u(t*m,r,n,i,a,o,s.segment,d,g,l,c,h,f);return x?{first:y,last:x}:null}function o(t,e,r,n){return t===x.horizontal&&Math.abs(r.y-e.y)>Math.abs(r.x-e.x)*n?{useVertical:!0}:(t===x.vertical?e.yr.x)?{needsFlipping:!0}:null}function s(t,e,r,i,s,c,h,p,d,g,v,y,x,b){var _,w=e/24,M=t.lineOffsetX*e,A=t.lineOffsetY*e;if(t.numGlyphs>1){var k=t.glyphStartIndex+t.numGlyphs,T=t.lineStartIndex,S=t.lineStartIndex+t.lineLength,E=a(w,p,M,A,r,v,y,t,d,c,x,!1);if(!E)return{notEnoughRoom:!0};var C=n(E.first.point,h).point,L=n(E.last.point,h).point;if(i&&!r){var z=o(t.writingMode,C,L,b);if(z)return z}_=[E.first];for(var P=t.glyphStartIndex+1;P0?R.point:l(y,O,I,1,s),B=o(t.writingMode,I,F,b);if(B)return B}var N=u(w*p.getoffsetX(t.glyphStartIndex),M,A,r,v,y,t.segment,t.lineStartIndex,t.lineStartIndex+t.lineLength,d,c,x,!1);if(!N)return{notEnoughRoom:!0};_=[N]}for(var j=0,V=_;j0?1:-1,y=0;i&&(m*=-1,y=Math.PI),m<0&&(y+=Math.PI);for(var x=m>0?u+s:u+s+1,b=x,_=a,w=a,M=0,A=0,k=Math.abs(v);M+A<=k;){if((x+=m)=c)return null;if(w=_,void 0===(_=d[x])){var T=new f(h.getx(x),h.gety(x)),S=n(T,p);if(S.signedDistanceFromCamera>0)_=d[x]=S.point;else{var E=x-m;_=l(0===M?o:new f(h.getx(E),h.gety(E)),T,w,k-M+1,p)}}M+=A,A=w.dist(_)}var C=(k-M)/A,L=_.sub(w),z=L.mult(C)._add(w);return z._add(L._unit()._perp()._mult(r*m)),{point:z,angle:y+Math.atan2(_.y-w.y,_.x-w.x),tileDistance:g?{prevTileDistance:x-m===b?0:h.gettileUnitDistanceFromAnchor(x-m),lastSegmentViewportDistance:k-M}:null}}function c(t,e){for(var r=0;r=w||o.y<0||o.y>=w||t.symbolInstances.push(function(t,e,r,n,a,o,s,l,c,h,f,d,g,x,b,_,w,A,k,T,S,E){var C,L,z=t.addToLineVertexArray(e,r),P=0,I=0,D=0,O=n.horizontal?n.horizontal.text:"",R=[];n.horizontal&&(C=new m(s,r,e,l,c,h,n.horizontal,f,d,g,t.overscaling),I+=i(t,e,n.horizontal,o,g,k,T,x,z,n.vertical?p.horizontal:p.horizontalOnly,R,S,E),n.vertical&&(D+=i(t,e,n.vertical,o,g,k,T,x,z,p.vertical,R,S,E)));var F=C?C.boxStartIndex:t.collisionBoxArray.length,B=C?C.boxEndIndex:t.collisionBoxArray.length;if(a){var N=v(e,a,o,w,n.horizontal,k,T);L=new m(s,r,e,l,c,h,a,b,_,!1,t.overscaling),P=4*N.length;var j=t.iconSizeData,V=null;"source"===j.functionType?V=[10*o.layout.get("icon-size").evaluate(T)]:"composite"===j.functionType&&(V=[10*E.compositeIconSizes[0].evaluate(T),10*E.compositeIconSizes[1].evaluate(T)]),t.addSymbols(t.icon,N,V,A,w,T,!1,e,z.lineStartIndex,z.lineLength)}var U=L?L.boxStartIndex:t.collisionBoxArray.length,q=L?L.boxEndIndex:t.collisionBoxArray.length;return t.glyphOffsetArray.length>=M.MAX_GLYPHS&&y.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),{key:O,textBoxStartIndex:F,textBoxEndIndex:B,iconBoxStartIndex:U,iconBoxEndIndex:q,textOffset:x,iconOffset:A,anchor:e,line:r,featureIndex:l,feature:T,numGlyphVertices:I,numVerticalGlyphVertices:D,numIconVertices:P,textOpacityState:new u,iconOpacityState:new u,isDuplicate:!1,placedTextSymbolIndices:R,crossTileID:0}}(t,o,a,r,n,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,S,z,D,A,C,P,O,k,{zoom:t.zoom},e,c,h))};if("line"===x.get("symbol-placement"))for(var B=0,N=l(e.geometry,0,0,w,w);B=0;o--)if(n.dist(a[o])1||(f?(clearTimeout(f),f=null,o("dblclick",e)):f=setTimeout(r,300))},!1),l.addEventListener("touchend",function(t){s("touchend",t)},!1),l.addEventListener("touchmove",function(t){s("touchmove",t)},!1),l.addEventListener("touchcancel",function(t){s("touchcancel",t)},!1),l.addEventListener("click",function(t){n.mousePos(l,t).equals(h)&&o("click",t)},!1),l.addEventListener("dblclick",function(t){o("dblclick",t),t.preventDefault()},!1),l.addEventListener("contextmenu",function(e){var r=t.dragRotate&&t.dragRotate.isActive();c||r?c&&(u=e):o("contextmenu",e),e.preventDefault()},!1)}},{"../util/dom":259,"./handler/box_zoom":239,"./handler/dblclick_zoom":240,"./handler/drag_pan":241,"./handler/drag_rotate":242,"./handler/keyboard":243,"./handler/scroll_zoom":244,"./handler/touch_zoom_rotate":245,"@mapbox/point-geometry":4}],231:[function(t,e,r){var n=t("../util/util"),i=t("../style-spec/util/interpolate").number,a=t("../util/browser"),o=t("../geo/lng_lat"),s=t("../geo/lng_lat_bounds"),l=t("@mapbox/point-geometry"),u=function(t){function e(e,r){t.call(this),this.moving=!1,this.transform=e,this._bearingSnap=r.bearingSnap}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getCenter=function(){return this.transform.center},e.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},e.prototype.panBy=function(t,e,r){return t=l.convert(t).mult(-1),this.panTo(this.transform.center,n.extend({offset:t},e),r)},e.prototype.panTo=function(t,e,r){return this.easeTo(n.extend({center:t},e),r)},e.prototype.getZoom=function(){return this.transform.zoom},e.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},e.prototype.zoomTo=function(t,e,r){return this.easeTo(n.extend({zoom:t},e),r)},e.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},e.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},e.prototype.getBearing=function(){return this.transform.bearing},e.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},e.prototype.rotateTo=function(t,e,r){return this.easeTo(n.extend({bearing:t},e),r)},e.prototype.resetNorth=function(t,e){return this.rotateTo(0,n.extend({duration:1e3},t),e),this},e.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())e?1:0}),["bottom","left","right","top"]))return n.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;t=s.convert(t);var a=[(e.padding.left-e.padding.right)/2,(e.padding.top-e.padding.bottom)/2],o=Math.min(e.padding.right,e.padding.left),u=Math.min(e.padding.top,e.padding.bottom);e.offset=[e.offset[0]+a[0],e.offset[1]+a[1]];var c=l.convert(e.offset),h=this.transform,f=h.project(t.getNorthWest()),p=h.project(t.getSouthEast()),d=p.sub(f),g=(h.width-2*o-2*Math.abs(c.x))/d.x,v=(h.height-2*u-2*Math.abs(c.y))/d.y;return v<0||g<0?(n.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(e.center=h.unproject(f.add(p).div(2)),e.zoom=Math.min(h.scaleZoom(h.scale*Math.min(g,v)),e.maxZoom),e.bearing=0,e.linear?this.easeTo(e,r):this.flyTo(e,r))},e.prototype.jumpTo=function(t,e){this.stop();var r=this.transform,n=!1,i=!1,a=!1;return"zoom"in t&&r.zoom!==+t.zoom&&(n=!0,r.zoom=+t.zoom),void 0!==t.center&&(r.center=o.convert(t.center)),"bearing"in t&&r.bearing!==+t.bearing&&(i=!0,r.bearing=+t.bearing),"pitch"in t&&r.pitch!==+t.pitch&&(a=!0,r.pitch=+t.pitch),this.fire("movestart",e).fire("move",e),n&&this.fire("zoomstart",e).fire("zoom",e).fire("zoomend",e),i&&this.fire("rotate",e),a&&this.fire("pitchstart",e).fire("pitch",e).fire("pitchend",e),this.fire("moveend",e)},e.prototype.easeTo=function(t,e){var r=this;this.stop(),!1===(t=n.extend({offset:[0,0],duration:500,easing:n.ease},t)).animate&&(t.duration=0);var a=this.transform,s=this.getZoom(),u=this.getBearing(),c=this.getPitch(),h="zoom"in t?+t.zoom:s,f="bearing"in t?this._normalizeBearing(t.bearing,u):u,p="pitch"in t?+t.pitch:c,d=a.centerPoint.add(l.convert(t.offset)),g=a.pointLocation(d),v=o.convert(t.center||g);this._normalizeCenter(v);var m,y,x=a.project(g),b=a.project(v).sub(x),_=a.zoomScale(h-s);return t.around&&(m=o.convert(t.around),y=a.locationPoint(m)),this.zooming=h!==s,this.rotating=u!==f,this.pitching=p!==c,this._prepareEase(e,t.noMoveStart),clearTimeout(this._onEaseEnd),this._ease(function(t){if(r.zooming&&(a.zoom=i(s,h,t)),r.rotating&&(a.bearing=i(u,f,t)),r.pitching&&(a.pitch=i(c,p,t)),m)a.setLocationAtPoint(m,y);else{var n=a.zoomScale(a.zoom-s),o=h>s?Math.min(2,_):Math.max(.5,_),l=Math.pow(o,1-t),g=a.unproject(x.add(b.mult(t*l)).mult(n));a.setLocationAtPoint(a.renderWorldCopies?g.wrap():g,d)}r._fireMoveEvents(e)},function(){t.delayEndEvents?r._onEaseEnd=setTimeout(function(){return r._afterEase(e)},t.delayEndEvents):r._afterEase(e)},t),this},e.prototype._prepareEase=function(t,e){this.moving=!0,e||this.fire("movestart",t),this.zooming&&this.fire("zoomstart",t),this.pitching&&this.fire("pitchstart",t)},e.prototype._fireMoveEvents=function(t){this.fire("move",t),this.zooming&&this.fire("zoom",t),this.rotating&&this.fire("rotate",t),this.pitching&&this.fire("pitch",t)},e.prototype._afterEase=function(t){var e=this.zooming,r=this.pitching;this.moving=!1,this.zooming=!1,this.rotating=!1,this.pitching=!1,e&&this.fire("zoomend",t),r&&this.fire("pitchend",t),this.fire("moveend",t)},e.prototype.flyTo=function(t,e){function r(t){var e=(k*k-A*A+(t?-1:1)*C*C*T*T)/(2*(t?k:A)*C*T);return Math.log(Math.sqrt(e*e+1)-e)}function a(t){return(Math.exp(t)-Math.exp(-t))/2}function s(t){return(Math.exp(t)+Math.exp(-t))/2}var u=this;this.stop(),t=n.extend({offset:[0,0],speed:1.2,curve:1.42,easing:n.ease},t);var c=this.transform,h=this.getZoom(),f=this.getBearing(),p=this.getPitch(),d="zoom"in t?n.clamp(+t.zoom,c.minZoom,c.maxZoom):h,g="bearing"in t?this._normalizeBearing(t.bearing,f):f,v="pitch"in t?+t.pitch:p,m=c.zoomScale(d-h),y=c.centerPoint.add(l.convert(t.offset)),x=c.pointLocation(y),b=o.convert(t.center||x);this._normalizeCenter(b);var _=c.project(x),w=c.project(b).sub(_),M=t.curve,A=Math.max(c.width,c.height),k=A/m,T=w.mag();if("minZoom"in t){var S=n.clamp(Math.min(t.minZoom,h,d),c.minZoom,c.maxZoom),E=A/c.zoomScale(S-h);M=Math.sqrt(E/T*2)}var C=M*M,L=r(0),z=function(t){return s(L)/s(L+M*t)},P=function(t){return A*((s(L)*function(t){return a(t)/s(t)}(L+M*t)-a(L))/C)/T},I=(r(1)-L)/M;if(Math.abs(T)<1e-6||!isFinite(I)){if(Math.abs(A-k)<1e-6)return this.easeTo(t,e);var D=kt.maxDuration&&(t.duration=0),this.zooming=!0,this.rotating=f!==g,this.pitching=v!==p,this._prepareEase(e,!1),this._ease(function(t){var r=t*I,n=1/z(r);c.zoom=h+c.scaleZoom(n),u.rotating&&(c.bearing=i(f,g,t)),u.pitching&&(c.pitch=i(p,v,t));var a=c.unproject(_.add(w.mult(P(r))).mult(n));c.setLocationAtPoint(c.renderWorldCopies?a.wrap():a,y),u._fireMoveEvents(e)},function(){return u._afterEase(e)},t),this},e.prototype.isEasing=function(){return!!this._isEasing},e.prototype.isMoving=function(){return this.moving},e.prototype.stop=function(){return this._onFrame&&this._finishAnimation(),this},e.prototype._ease=function(t,e,r){var n=this;!1===r.animate||0===r.duration?(t(1),e()):(this._easeStart=a.now(),this._isEasing=!0,this._easeOptions=r,this._startAnimation(function(e){var r=Math.min((a.now()-n._easeStart)/n._easeOptions.duration,1);t(n._easeOptions.easing(r)),1===r&&n.stop()},function(){n._isEasing=!1,e()}))},e.prototype._updateCamera=function(){this._onFrame&&this._onFrame(this.transform)},e.prototype._startAnimation=function(t,e){return void 0===e&&(e=function(){}),this.stop(),this._onFrame=t,this._finishFn=e,this._update(),this},e.prototype._finishAnimation=function(){delete this._onFrame;var t=this._finishFn;delete this._finishFn,t.call(this)},e.prototype._normalizeBearing=function(t,e){t=n.wrap(t,-180,180);var r=Math.abs(t-e);return Math.abs(t-360-e)180?-360:r<-180?360:0}},e}(t("../util/evented"));e.exports=u},{"../geo/lng_lat":62,"../geo/lng_lat_bounds":63,"../style-spec/util/interpolate":158,"../util/browser":252,"../util/evented":260,"../util/util":275,"@mapbox/point-geometry":4}],232:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/config"),o=function(t){this.options=t,i.bindAll(["_updateEditLink","_updateData","_updateCompact"],this)};o.prototype.getDefaultPosition=function(){return"bottom-right"},o.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0},o.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:a.ACCESS_TOKEN}];if(t){var r=e.reduce(function(t,r,n){return r.value&&(t+=r.key+"="+r.value+(n=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null}},o.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact")},e.exports=o},{"../../util/config":256,"../../util/dom":259,"../../util/util":275}],233:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=function(){this._fullscreen=!1,i.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in a.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in a.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in a.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in a.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl"};o.prototype.onAdd=function(t){return this._map=t,this._mapContainer=this._map.getContainer(),this._container=n.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",i.warnOnce("This device does not support fullscreen mode.")),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map=null,a.document.removeEventListener(this._fullscreenchange,this._changeIcon)},o.prototype._checkFullscreenSupport=function(){return!!(a.document.fullscreenEnabled||a.document.mozFullScreenEnabled||a.document.msFullscreenEnabled||a.document.webkitFullscreenEnabled)},o.prototype._setupUI=function(){var t=this._fullscreenButton=n.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);t.setAttribute("aria-label","Toggle fullscreen"),t.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),a.document.addEventListener(this._fullscreenchange,this._changeIcon)},o.prototype._isFullscreen=function(){return this._fullscreen},o.prototype._changeIcon=function(){(a.document.fullscreenElement||a.document.mozFullScreenElement||a.document.webkitFullscreenElement||a.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"))},o.prototype._onClickFullscreen=function(){this._isFullscreen()?a.document.exitFullscreen?a.document.exitFullscreen():a.document.mozCancelFullScreen?a.document.mozCancelFullScreen():a.document.msExitFullscreen?a.document.msExitFullscreen():a.document.webkitCancelFullScreen&&a.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen()},e.exports=o},{"../../util/dom":259,"../../util/util":275,"../../util/window":254}],234:[function(t,e,r){var n,i=t("../../util/evented"),a=t("../../util/dom"),o=t("../../util/window"),s=t("../../util/util"),l=t("../../geo/lng_lat"),u=t("../marker"),c={positionOptions:{enableHighAccuracy:!1,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0},h=function(t){function e(e){t.call(this),this.options=s.extend({},c,e),s.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker","_onClickGeolocate"],this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onAdd=function(t){return this._map=t,this._container=a.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),function(t){void 0!==n?t(n):void 0!==o.navigator.permissions?o.navigator.permissions.query({name:"geolocation"}).then(function(e){n="denied"!==e.state,t(n)}):(n=!!o.navigator.geolocation,t(n))}(this._setupUI),this._container},e.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(o.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),a.remove(this._container),this._map=void 0},e.prototype._onSuccess=function(t){if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire("geolocate",t),this._finish()},e.prototype._updateCamera=function(t){var e=new l(t.coords.longitude,t.coords.latitude),r=t.coords.accuracy;this._map.fitBounds(e.toBounds(r),this.options.fitBoundsOptions,{geolocateSource:!0})},e.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove()},e.prototype._onError=function(t){if(this.options.trackUserLocation)if(1===t.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire("error",t),this._finish()},e.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},e.prototype._setupUI=function(t){var e=this;!1!==t&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=a.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=a.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new u(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this._onClickGeolocate.bind(this)),this.options.trackUserLocation&&this._map.on("movestart",function(t){t.geolocateSource||"ACTIVE_LOCK"!==e._watchState||(e._watchState="BACKGROUND",e._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),e._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),e.fire("trackuserlocationend"))}))},e.prototype._onClickGeolocate=function(){if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire("trackuserlocationstart");break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire("trackuserlocationend");break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire("trackuserlocationstart")}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=o.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions))}else o.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4)},e.prototype._clearWatch=function(){o.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)},e}(i);e.exports=h},{"../../geo/lng_lat":62,"../../util/dom":259,"../../util/evented":260,"../../util/util":275,"../../util/window":254,"../marker":248}],235:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=function(){i.bindAll(["_updateLogo"],this)};a.prototype.onAdd=function(t){this._map=t,this._container=n.create("div","mapboxgl-ctrl");var e=n.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},a.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateLogo)},a.prototype.getDefaultPosition=function(){return"bottom-left"},a.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")},a.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return!0;return!1}},e.exports=a},{"../../util/dom":259,"../../util/util":275}],236:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../handler/drag_rotate"),o={showCompass:!0,showZoom:!0},s=function(t){var e=this;this.options=i.extend({},o,t),this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return e._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return e._map.zoomOut()})),this.options.showCompass&&(i.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return e._map.resetNorth()}),this._compassArrow=n.create("span","mapboxgl-ctrl-compass-arrow",this._compass))};s.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t},s.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new a(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},s.prototype.onRemove=function(){n.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map},s.prototype._createButton=function(t,e,r){var i=n.create("button",t,this._container);return i.type="button",i.setAttribute("aria-label",e),i.addEventListener("click",r),i},e.exports=s},{"../../util/dom":259,"../../util/util":275,"../handler/drag_rotate":242}],237:[function(t,e,r){function n(t,e,r){var n=r&&r.maxWidth||100,a=t._container.clientHeight/2,o=function(t,e){var r=Math.PI/180,n=t.lat*r,i=e.lat*r,a=Math.sin(n)*Math.sin(i)+Math.cos(n)*Math.cos(i)*Math.cos((e.lng-t.lng)*r);return 6371e3*Math.acos(Math.min(a,1))}(t.unproject([0,a]),t.unproject([n,a]));if(r&&"imperial"===r.unit){var s=3.2808*o;s>5280?i(e,n,s/5280,"mi"):i(e,n,s,"ft")}else if(r&&"nautical"===r.unit){i(e,n,o/1852,"nm")}else i(e,n,o,"m")}function i(t,e,r,n){var i=function(t){var e=Math.pow(10,(""+Math.floor(t)).length-1),r=t/e;return e*(r=r>=10?10:r>=5?5:r>=3?3:r>=2?2:1)}(r),a=i/r;"m"===n&&i>=1e3&&(i/=1e3,n="km"),t.style.width=e*a+"px",t.innerHTML=i+n}var a=t("../../util/dom"),o=t("../../util/util"),s=function(t){this.options=t,o.bindAll(["_onMove"],this)};s.prototype.getDefaultPosition=function(){return"bottom-left"},s.prototype._onMove=function(){n(this._map,this._container,this.options)},s.prototype.onAdd=function(t){return this._map=t,this._container=a.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},s.prototype.onRemove=function(){a.remove(this._container),this._map.off("move",this._onMove),this._map=void 0},e.exports=s},{"../../util/dom":259,"../../util/util":275}],238:[function(t,e,r){},{}],239:[function(t,e,r){var n=t("../../util/dom"),i=t("../../geo/lng_lat_bounds"),a=t("../../util/util"),o=t("../../util/window"),s=function(t){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),a.bindAll(["_onMouseDown","_onMouseMove","_onMouseUp","_onKeyDown"],this)};s.prototype.isEnabled=function(){return!!this._enabled},s.prototype.isActive=function(){return!!this._active},s.prototype.enable=function(){this.isEnabled()||(this._map.dragPan&&this._map.dragPan.disable(),this._el.addEventListener("mousedown",this._onMouseDown,!1),this._map.dragPan&&this._map.dragPan.enable(),this._enabled=!0)},s.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onMouseDown),this._enabled=!1)},s.prototype._onMouseDown=function(t){t.shiftKey&&0===t.button&&(o.document.addEventListener("mousemove",this._onMouseMove,!1),o.document.addEventListener("keydown",this._onKeyDown,!1),o.document.addEventListener("mouseup",this._onMouseUp,!1),n.disableDrag(),this._startPos=n.mousePos(this._el,t),this._active=!0)},s.prototype._onMouseMove=function(t){var e=this._startPos,r=n.mousePos(this._el,t);this._box||(this._box=n.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var i=Math.min(e.x,r.x),a=Math.max(e.x,r.x),o=Math.min(e.y,r.y),s=Math.max(e.y,r.y);n.setTransform(this._box,"translate("+i+"px,"+o+"px)"),this._box.style.width=a-i+"px",this._box.style.height=s-o+"px"},s.prototype._onMouseUp=function(t){if(0===t.button){var e=this._startPos,r=n.mousePos(this._el,t),a=(new i).extend(this._map.unproject(e)).extend(this._map.unproject(r));this._finish(),e.x===r.x&&e.y===r.y?this._fireEvent("boxzoomcancel",t):this._map.fitBounds(a,{linear:!0}).fire("boxzoomend",{originalEvent:t,boxZoomBounds:a})}},s.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t))},s.prototype._finish=function(){this._active=!1,o.document.removeEventListener("mousemove",this._onMouseMove,!1),o.document.removeEventListener("keydown",this._onKeyDown,!1),o.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag()},s.prototype._fireEvent=function(t,e){return this._map.fire(t,{originalEvent:e})},e.exports=s},{"../../geo/lng_lat_bounds":63,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],240:[function(t,e,r){var n=t("../../util/util"),i=function(t){this._map=t,n.bindAll(["_onDblClick","_onZoomEnd"],this)};i.prototype.isEnabled=function(){return!!this._enabled},i.prototype.isActive=function(){return!!this._active},i.prototype.enable=function(){this.isEnabled()||(this._map.on("dblclick",this._onDblClick),this._enabled=!0)},i.prototype.disable=function(){this.isEnabled()&&(this._map.off("dblclick",this._onDblClick),this._enabled=!1)},i.prototype._onDblClick=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t)},i.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd)},e.exports=i},{"../../util/util":275}],241:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.3,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onDown","_onMove","_onUp","_onTouchEnd","_onMouseUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._el.addEventListener("mousedown",this._onDown),this._el.addEventListener("touchstart",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._el.removeEventListener("mousedown",this._onDown),this._el.removeEventListener("touchstart",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){this._ignoreEvent(t)||this.isActive()||(t.touches?(a.document.addEventListener("touchmove",this._onMove),a.document.addEventListener("touchend",this._onTouchEnd)):(a.document.addEventListener("mousemove",this._onMove),a.document.addEventListener("mouseup",this._onMouseUp)),a.addEventListener("blur",this._onMouseUp),this._active=!1,this._previousPos=n.mousePos(this._el,t),this._inertia=[[o.now(),this._previousPos]])},l.prototype._onMove=function(t){if(!this._ignoreEvent(t)){this._lastMoveEvent=t,t.preventDefault();var e=n.mousePos(this._el,t);if(this._drainInertiaBuffer(),this._inertia.push([o.now(),e]),!this._previousPos)return void(this._previousPos=e);this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("dragstart",t),this._fireEvent("movestart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()}},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;e&&(t.setLocationAtPoint(t.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",e),this._fireEvent("move",e),this._previousPos=this._pos,delete this._lastMoveEvent)},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,delete this._pos,this._fireEvent("dragend",t),this._drainInertiaBuffer();var r=function(){e._map.moving=!1,e._fireEvent("moveend",t)},n=this._inertia;if(n.length<2)return void r();var i=n[n.length-1],a=n[0],o=i[1].sub(a[1]),l=(i[0]-a[0])/1e3;if(0===l||i[1].equals(a[1]))return void r();var u=o.mult(.3/l),c=u.mag();c>1400&&(c=1400,u._unit()._mult(c));var h=c/750,f=u.mult(-h/2);this._map.panBy(f,{duration:1e3*h,easing:s,noMoveStart:!0},{originalEvent:t})}},l.prototype._onUp=function(t){this._onDragFinished(t)},l.prototype._onMouseUp=function(t){this._ignoreEvent(t)||(this._onUp(t),a.document.removeEventListener("mousemove",this._onMove),a.document.removeEventListener("mouseup",this._onMouseUp),a.removeEventListener("blur",this._onMouseUp))},l.prototype._onTouchEnd=function(t){this._ignoreEvent(t)||(this._onUp(t),a.document.removeEventListener("touchmove",this._onMove),a.document.removeEventListener("touchend",this._onTouchEnd))},l.prototype._fireEvent=function(t,e){return this._map.fire(t,e?{originalEvent:e}:{})},l.prototype._ignoreEvent=function(t){var e=this._map;return!(!e.boxZoom||!e.boxZoom.isActive())||!(!e.dragRotate||!e.dragRotate.isActive())||(t.touches?t.touches.length>1:!!t.ctrlKey||"mousemove"!==t.type&&t.button&&0!==t.button)},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=o.now();t.length>0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],242:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.25,1),l=function(t,e){this._map=t,this._el=e.element||t.getCanvasContainer(),this._button=e.button||"right",this._bearingSnap=e.bearingSnap||0,this._pitchWithRotate=!1!==e.pitchWithRotate,i.bindAll(["_onDown","_onMove","_onUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){if(!(this._map.boxZoom&&this._map.boxZoom.isActive()||this._map.dragPan&&this._map.dragPan.isActive()||this.isActive())){if("right"===this._button){var e=t.ctrlKey?0:2,r=t.button;if(void 0!==a.InstallTrigger&&2===t.button&&t.ctrlKey&&a.navigator.platform.toUpperCase().indexOf("MAC")>=0&&(r=0),r!==e)return}else if(t.ctrlKey||0!==t.button)return;n.disableDrag(),a.document.addEventListener("mousemove",this._onMove,{capture:!0}),a.document.addEventListener("mouseup",this._onUp),a.addEventListener("blur",this._onUp),this._active=!1,this._inertia=[[o.now(),this._map.getBearing()]],this._previousPos=n.mousePos(this._el,t),this._center=this._map.transform.centerPoint,t.preventDefault()}},l.prototype._onMove=function(t){this._lastMoveEvent=t;var e=n.mousePos(this._el,t);this._previousPos?(this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()):this._previousPos=e},l.prototype._onUp=function(t){a.document.removeEventListener("mousemove",this._onMove,{capture:!0}),a.document.removeEventListener("mouseup",this._onUp),a.removeEventListener("blur",this._onUp),n.enableDrag(),this._onDragFinished(t)},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;if(e){var r=this._previousPos,n=this._pos,i=.8*(r.x-n.x),a=-.5*(r.y-n.y),s=t.bearing-i,l=t.pitch-a,u=this._inertia,c=u[u.length-1];this._drainInertiaBuffer(),u.push([o.now(),this._map._normalizeBearing(s,c[1])]),t.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",e),t.pitch=l),this._fireEvent("rotate",e),this._fireEvent("move",e),delete this._lastMoveEvent,this._previousPos=this._pos}},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,this._fireEvent("rotateend",t),this._drainInertiaBuffer();var r=this._map,n=r.getBearing(),i=this._inertia,a=function(){Math.abs(n)180&&(d=180);var g=d/180;c+=f*d*(g/2),Math.abs(r._normalizeBearing(c,0))0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],243:[function(t,e,r){function n(t){return t*(2-t)}var i=t("../../util/util"),a=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onKeyDown"],this)};a.prototype.isEnabled=function(){return!!this._enabled},a.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0)},a.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1)},a.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,r=0,i=0,a=0,o=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?r=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?r=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?i=1:(t.preventDefault(),o=-1);break;case 40:t.shiftKey?i=-1:(o=1,t.preventDefault());break;default:return}var s=this._map,l=s.getZoom(),u={duration:300,delayEndEvents:500,easing:n,zoom:e?Math.round(l)+e*(t.shiftKey?2:1):l,bearing:s.getBearing()+15*r,pitch:s.getPitch()+10*i,offset:[100*-a,100*-o],center:s.getCenter()};s.easeTo(u,{originalEvent:t})}},e.exports=a},{"../../util/util":275}],244:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/browser"),o=t("../../util/window"),s=t("../../style-spec/util/interpolate").number,l=t("../../geo/lng_lat"),u=o.navigator.userAgent.toLowerCase(),c=-1!==u.indexOf("firefox"),h=-1!==u.indexOf("safari")&&-1===u.indexOf("chrom"),f=function(t){this._map=t,this._el=t.getCanvasContainer(),this._delta=0,i.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this)};f.prototype.isEnabled=function(){return!!this._enabled},f.prototype.isActive=function(){return!!this._active},f.prototype.enable=function(t){this.isEnabled()||(this._el.addEventListener("wheel",this._onWheel,!1),this._el.addEventListener("mousewheel",this._onWheel,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},f.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("wheel",this._onWheel),this._el.removeEventListener("mousewheel",this._onWheel),this._enabled=!1)},f.prototype._onWheel=function(t){var e=0;"wheel"===t.type?(e=t.deltaY,c&&t.deltaMode===o.WheelEvent.DOM_DELTA_PIXEL&&(e/=a.devicePixelRatio),t.deltaMode===o.WheelEvent.DOM_DELTA_LINE&&(e*=40)):"mousewheel"===t.type&&(e=-t.wheelDeltaY,h&&(e/=3));var r=a.now(),n=r-(this._lastWheelEventTime||0);this._lastWheelEventTime=r,0!==e&&e%4.000244140625==0?this._type="wheel":0!==e&&Math.abs(e)<4?this._type="trackpad":n>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(n*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&(this._lastWheelEvent=t,this._delta-=e,this.isActive()||this._start(t)),t.preventDefault()},f.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t)},f.prototype._start=function(t){if(this._delta){this._active=!0,this._map.moving=!0,this._map.zooming=!0,this._map.fire("movestart",{originalEvent:t}),this._map.fire("zoomstart",{originalEvent:t}),clearTimeout(this._finishTimeout);var e=n.mousePos(this._el,t);this._around=l.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(e)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._map._startAnimation(this._onScrollFrame,this._onScrollFinished)}},f.prototype._onScrollFrame=function(t){if(this.isActive()){if(0!==this._delta){var e="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,r=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==r&&(r=1/r);var n="number"==typeof this._targetZoom?t.zoomScale(this._targetZoom):t.scale;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(n*r))),"wheel"===this._type&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}if("wheel"===this._type){var i=Math.min((a.now()-this._lastWheelEventTime)/200,1),o=this._easing(i);t.zoom=s(this._startZoom,this._targetZoom,o),1===i&&this._map.stop()}else t.zoom=this._targetZoom,this._map.stop();t.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire("move",{originalEvent:this._lastWheelEvent}),this._map.fire("zoom",{originalEvent:this._lastWheelEvent})}},f.prototype._onScrollFinished=function(){var t=this;this.isActive()&&(this._active=!1,this._finishTimeout=setTimeout(function(){t._map.moving=!1,t._map.zooming=!1,t._map.fire("zoomend"),t._map.fire("moveend"),delete t._targetZoom},200))},f.prototype._smoothOutEasing=function(t){var e=i.ease;if(this._prevEase){var r=this._prevEase,n=(a.now()-r.start)/r.duration,o=r.easing(n+.01)-r.easing(n),s=.27/Math.sqrt(o*o+1e-4)*.01,l=Math.sqrt(.0729-s*s);e=i.bezier(s,l,.25,1)}return this._prevEase={start:a.now(),duration:t,easing:e},e},e.exports=f},{"../../geo/lng_lat":62,"../../style-spec/util/interpolate":158,"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],245:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.15,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onStart","_onMove","_onEnd"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._el.addEventListener("touchstart",this._onStart,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._el.removeEventListener("touchstart",this._onStart),this._enabled=!1)},l.prototype.disableRotation=function(){this._rotationDisabled=!0},l.prototype.enableRotation=function(){this._rotationDisabled=!1},l.prototype._onStart=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]);this._startVec=e.sub(r),this._startScale=this._map.transform.scale,this._startBearing=this._map.transform.bearing,this._gestureIntent=void 0,this._inertia=[],a.document.addEventListener("touchmove",this._onMove,!1),a.document.addEventListener("touchend",this._onEnd,!1)}},l.prototype._onMove=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]),i=e.add(r).div(2),a=e.sub(r),s=a.mag()/this._startVec.mag(),l=this._rotationDisabled?0:180*a.angleWith(this._startVec)/Math.PI,u=this._map;if(this._gestureIntent){var c={duration:0,around:u.unproject(i)};"rotate"===this._gestureIntent&&(c.bearing=this._startBearing+l),"zoom"!==this._gestureIntent&&"rotate"!==this._gestureIntent||(c.zoom=u.transform.scaleZoom(this._startScale*s)),u.stop(),this._drainInertiaBuffer(),this._inertia.push([o.now(),s,i]),u.easeTo(c,{originalEvent:t})}else{var h=Math.abs(1-s)>.15;Math.abs(l)>10?this._gestureIntent="rotate":h&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._startVec=a,this._startScale=u.transform.scale,this._startBearing=u.transform.bearing)}t.preventDefault()}},l.prototype._onEnd=function(t){a.document.removeEventListener("touchmove",this._onMove),a.document.removeEventListener("touchend",this._onEnd),this._drainInertiaBuffer();var e=this._inertia,r=this._map;if(e.length<2)r.snapToNorth({},{originalEvent:t});else{var n=e[e.length-1],i=e[0],o=r.transform.scaleZoom(this._startScale*n[1]),l=r.transform.scaleZoom(this._startScale*i[1]),u=o-l,c=(n[0]-i[0])/1e3,h=n[2];if(0!==c&&o!==l){var f=.15*u/c;Math.abs(f)>2.5&&(f=f>0?2.5:-2.5);var p=1e3*Math.abs(f/(12*.15)),d=o+f*p/2e3;d<0&&(d=0),r.easeTo({zoom:d,duration:p,easing:s,around:this._aroundCenter?r.getCenter():r.unproject(h)},{originalEvent:t})}else r.snapToNorth({},{originalEvent:t})}},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=o.now();t.length>2&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],246:[function(t,e,r){var n=t("../util/util"),i=t("../util/window"),a=t("../util/throttle"),o=function(){n.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=a(this._updateHashUnthrottled.bind(this),300)};o.prototype.addTo=function(t){return this._map=t,i.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},o.prototype.remove=function(){return i.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),delete this._map,this},o.prototype.getHashString=function(t){var e=this._map.getCenter(),r=Math.round(100*this._map.getZoom())/100,n=Math.ceil((r*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.pow(10,n),a=Math.round(e.lng*i)/i,o=Math.round(e.lat*i)/i,s=this._map.getBearing(),l=this._map.getPitch(),u="";return u+=t?"#/"+a+"/"+o+"/"+r:"#"+r+"/"+o+"/"+a,(s||l)&&(u+="/"+Math.round(10*s)/10),l&&(u+="/"+Math.round(l)),u},o.prototype._onHashChange=function(){var t=i.location.hash.replace("#","").split("/");return t.length>=3&&(this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:+(t[3]||0),pitch:+(t[4]||0)}),!0)},o.prototype._updateHashUnthrottled=function(){var t=this.getHashString();i.history.replaceState("","",t)},e.exports=o},{"../util/throttle":272,"../util/util":275,"../util/window":254}],247:[function(t,e,r){function n(t){t.parentNode&&t.parentNode.removeChild(t)}var i=t("../util/util"),a=t("../util/browser"),o=t("../util/window"),s=t("../util/window"),l=s.HTMLImageElement,u=s.HTMLElement,c=t("../util/dom"),h=t("../util/ajax"),f=t("../style/style"),p=t("../style/evaluation_parameters"),d=t("../render/painter"),g=t("../geo/transform"),v=t("./hash"),m=t("./bind_handlers"),y=t("./camera"),x=t("../geo/lng_lat"),b=t("../geo/lng_lat_bounds"),_=t("@mapbox/point-geometry"),w=t("./control/attribution_control"),M=t("./control/logo_control"),A=t("@mapbox/mapbox-gl-supported"),k=t("../util/image").RGBAImage;t("./events");var T={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},S=function(t){function e(e){if(null!=(e=i.extend({},T,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var r=new g(e.minZoom,e.maxZoom,e.renderWorldCopies);t.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming;var n=e.transformRequest;if(this._transformRequest=n?function(t,e){return n(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var a=o.document.getElementById(e.container);if(!a)throw new Error("Container '"+e.container+"' not found.");this._container=a}else{if(!(e.container instanceof u))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}e.maxBounds&&this.setMaxBounds(e.maxBounds),i.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==o&&(o.addEventListener("online",this._onWindowOnline,!1),o.addEventListener("resize",this._onWindowResize,!1)),m(this,e),this._hash=e.hash&&(new v).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new w),this.addControl(new M,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet)}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={showTileBoundaries:{},showCollisionBoxes:{},showOverdrawInspector:{},repaint:{},vertices:{}};return e.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var r=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(r,n.firstChild):n.appendChild(r),this},e.prototype.removeControl=function(t){return t.onRemove(this),this},e.prototype.resize=function(){var t=this._containerDimensions(),e=t[0],r=t[1];return this._resizeCanvas(e,r),this.transform.resize(e,r),this.painter.resize(e,r),this.fire("movestart").fire("move").fire("resize").fire("moveend")},e.prototype.getBounds=function(){var t=new b(this.transform.pointLocation(new _(0,this.transform.height)),this.transform.pointLocation(new _(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(t.extend(this.transform.pointLocation(new _(this.transform.size.x,0))),t.extend(this.transform.pointLocation(new _(0,this.transform.size.y)))),t},e.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new b([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},e.prototype.setMaxBounds=function(t){if(t){var e=b.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update()}else null!==t&&void 0!==t||(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},e.prototype.setMinZoom=function(t){if((t=null===t||void 0===t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},e.prototype.getMaxZoom=function(){return this.transform.maxZoom},e.prototype.project=function(t){return this.transform.locationPoint(x.convert(t))},e.prototype.unproject=function(t){return this.transform.pointLocation(_.convert(t))},e.prototype.on=function(e,r,n){var a=this;if(void 0===n)return t.prototype.on.call(this,e,r);var o=function(){if("mouseenter"===e||"mouseover"===e){var t=!1;return{layer:r,listener:n,delegates:{mousemove:function(o){var s=a.getLayer(r)?a.queryRenderedFeatures(o.point,{layers:[r]}):[];s.length?t||(t=!0,n.call(a,i.extend({features:s},o,{type:e}))):t=!1},mouseout:function(){t=!1}}}}if("mouseleave"===e||"mouseout"===e){var o=!1;return{layer:r,listener:n,delegates:{mousemove:function(t){(a.getLayer(r)?a.queryRenderedFeatures(t.point,{layers:[r]}):[]).length?o=!0:o&&(o=!1,n.call(a,i.extend({},t,{type:e})))},mouseout:function(t){o&&(o=!1,n.call(a,i.extend({},t,{type:e})))}}}}var s;return{layer:r,listener:n,delegates:(s={},s[e]=function(t){var e=a.getLayer(r)?a.queryRenderedFeatures(t.point,{layers:[r]}):[];e.length&&n.call(a,i.extend({features:e},t))},s)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(o),o.delegates)a.on(s,o.delegates[s]);return this},e.prototype.off=function(e,r,n){if(void 0===n)return t.prototype.off.call(this,e,r);if(this._delegatedListeners&&this._delegatedListeners[e])for(var i=this._delegatedListeners[e],a=0;athis._map.transform.height-i?["bottom"]:[],t.xthis._map.transform.width-n/2&&e.push("right"),e=0===e.length?"bottom":e.join("-")}var o=t.add(r[e]).round(),l={top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},c=this._container.classList;for(var h in l)c.remove("mapboxgl-popup-anchor-"+h);c.add("mapboxgl-popup-anchor-"+e),a.setTransform(this._container,l[e]+" translate("+o.x+"px,"+o.y+"px)")}},e.prototype._onClickClose=function(){this.remove()},e}(i);e.exports=h},{"../geo/lng_lat":62,"../util/dom":259,"../util/evented":260,"../util/smart_wrap":270,"../util/util":275,"../util/window":254,"@mapbox/point-geometry":4}],250:[function(t,e,r){var n=t("./util"),i=t("./web_worker_transfer"),a=i.serialize,o=i.deserialize,s=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,n.bindAll(["receive"],this),this.target.addEventListener("message",this.receive,!1)};s.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var o=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:a(e,o)},o)},s.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var s=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"",id:String(i),error:t?String(t):null,data:a(e,n)},n)};if(""===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(new Error(n.error)):e&&e(null,o(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,o(n.data),s);else if(void 0!==n.id&&this.parent.getWorkerSource){var l=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,l[0])[l[1]](o(n.data),s)}else this.parent[n.type](o(n.data))}},s.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1)},e.exports=s},{"./util":275,"./web_worker_transfer":278}],251:[function(t,e,r){function n(t){var e=new a.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}function i(t){var e=a.document.createElement("a");return e.href=t,e.protocol===a.document.location.protocol&&e.host===a.document.location.host}var a=t("./window"),o={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};r.ResourceType=o,"function"==typeof Object.freeze&&Object.freeze(o);var s=function(t){function e(e,r){t.call(this,e),this.status=r}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);r.getJSON=function(t,e){var r=n(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var t;try{t=JSON.parse(r.response)}catch(t){return e(t)}e(null,t)}else e(new s(r.statusText,r.status))},r.send(),r},r.getArrayBuffer=function(t,e){var r=n(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){var t=r.response;if(0===t.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:t,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new s(r.statusText,r.status))},r.send(),r};r.getImage=function(t,e){return r.getArrayBuffer(t,function(t,r){if(t)e(t);else if(r){var n=new a.Image,i=a.URL||a.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src)};var o=new a.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(o):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII="}})},r.getVideo=function(t,e){var r=a.document.createElement("video");r.onloadstart=function(){e(null,r)};for(var n=0;n1)for(var h=0;h0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},o.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this},e.exports=o},{"./util":275}],261:[function(t,e,r){function n(t,e){return e.max-t.max}function i(t,e,r,n){this.p=new o(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;it.y!=h.y>t.y&&t.x<(h.x-c.x)*(t.y-c.y)/(h.y-c.y)+c.x&&(r=!r),n=Math.min(n,s(t,c,h))}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2}var a=t("tinyqueue"),o=t("@mapbox/point-geometry"),s=t("./intersection_tests").distToSegmentSquared;e.exports=function(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var s=1/0,l=1/0,u=-1/0,c=-1/0,h=t[0],f=0;fu)&&(u=p.x),(!f||p.y>c)&&(c=p.y)}var d=u-s,g=c-l,v=Math.min(d,g),m=v/2,y=new a(null,n);if(0===v)return new o(s,l);for(var x=s;x_.d||!_.d)&&(_=M,r&&console.log("found best %d after %d probes",Math.round(1e4*M.d)/1e4,w)),M.max-_.d<=e||(m=M.h/2,y.push(new i(M.p.x-m,M.p.y-m,m,t)),y.push(new i(M.p.x+m,M.p.y-m,m,t)),y.push(new i(M.p.x-m,M.p.y+m,m,t)),y.push(new i(M.p.x+m,M.p.y+m,m,t)),w+=4)}return r&&(console.log("num probes: "+w),console.log("best distance: "+_.d)),_.p}},{"./intersection_tests":264,"@mapbox/point-geometry":4,tinyqueue:33}],262:[function(t,e,r){var n,i=t("./worker_pool");e.exports=function(){return n||(n=new i),n}},{"./worker_pool":279}],263:[function(t,e,r){function n(t,e,r,n){var i=e.width,a=e.height;if(n){if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function i(t,e,r){var i=e.width,o=e.height;if(i!==t.width||o!==t.height){var s=n({},{width:i,height:o},r);a(t,s,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,i),height:Math.min(t.height,o)},r),t.width=i,t.height=o,t.data=s.data}}function a(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,l=0;l1){if(i(t,e))return!0;for(var n=0;n1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function l(t,e){for(var r,n,i,a=!1,o=0;oe.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function u(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r)}return r}var c=t("./util").isCounterClockwise;e.exports={multiPolygonIntersectsBufferedMultiPoint:function(t,e,r){for(var n=0;n=3)for(var l=0;l=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}}},{}],266:[function(t,e,r){var n=function(t,e){this.max=t,this.onRemove=e,this.reset()};n.prototype.reset=function(){var t=this;for(var e in t.data)t.onRemove(t.data[e]);return this.data={},this.order=[],this},n.prototype.add=function(t,e){if(this.has(t))this.order.splice(this.order.indexOf(t),1),this.data[t]=e,this.order.push(t);else if(this.data[t]=e,this.order.push(t),this.order.length>this.max){var r=this.getAndRemove(this.order[0]);r&&this.onRemove(r)}return this},n.prototype.has=function(t){return t in this.data},n.prototype.keys=function(){return this.order},n.prototype.getAndRemove=function(t){if(!this.has(t))return null;var e=this.data[t];return delete this.data[t],this.order.splice(this.order.indexOf(t),1),e},n.prototype.get=function(t){return this.has(t)?this.data[t]:null},n.prototype.remove=function(t){if(!this.has(t))return this;var e=this.data[t];return delete this.data[t],this.onRemove(e),this.order.splice(this.order.indexOf(t),1),this},n.prototype.setMaxSize=function(t){var e=this;for(this.max=t;this.order.length>this.max;){var r=e.getAndRemove(e.order[0]);r&&e.onRemove(r)}return this},e.exports=n},{}],267:[function(t,e,r){function n(t,e){var r=a(s.API_URL);if(t.protocol=r.protocol,t.authority=r.authority,"/"!==r.path&&(t.path=""+r.path+t.path),!s.REQUIRE_ACCESS_TOKEN)return o(t);if(!(e=e||s.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+u);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+u);return t.params.push("access_token="+e),o(t)}function i(t){return 0===t.indexOf("mapbox:")}function a(t){var e=t.match(h);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function o(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var s=t("./config"),l=t("./browser"),u="See https://www.mapbox.com/api-documentation/#access-tokens";r.isMapboxURL=i,r.normalizeStyleURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/styles/v1"+r.path,n(r,e)},r.normalizeGlyphsURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/fonts/v1"+r.path,n(r,e)},r.normalizeSourceURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),n(r,e)},r.normalizeSpriteURL=function(t,e,r,s){var l=a(t);return i(t)?(l.path="/styles/v1"+l.path+"/sprite"+e+r,n(l,s)):(l.path+=""+e+r,o(l))};var c=/(\.(png|jpg)\d*)(?=$)/;r.normalizeTileURL=function(t,e,r){if(!e||!i(e))return t;var n=a(t),u=l.devicePixelRatio>=2||512===r?"@2x":"",h=l.supportsWebp?".webp":"$1";return n.path=n.path.replace(c,""+u+h),function(t){for(var e=0;e=65097&&t<=65103)||n["CJK Compatibility Ideographs"](t)||n["CJK Compatibility"](t)||n["CJK Radicals Supplement"](t)||n["CJK Strokes"](t)||!(!n["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||n["CJK Unified Ideographs Extension A"](t)||n["CJK Unified Ideographs"](t)||n["Enclosed CJK Letters and Months"](t)||n["Hangul Compatibility Jamo"](t)||n["Hangul Jamo Extended-A"](t)||n["Hangul Jamo Extended-B"](t)||n["Hangul Jamo"](t)||n["Hangul Syllables"](t)||n.Hiragana(t)||n["Ideographic Description Characters"](t)||n.Kanbun(t)||n["Kangxi Radicals"](t)||n["Katakana Phonetic Extensions"](t)||n.Katakana(t)&&12540!==t||!(!n["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!n["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||n["Unified Canadian Aboriginal Syllabics"](t)||n["Unified Canadian Aboriginal Syllabics Extended"](t)||n["Vertical Forms"](t)||n["Yijing Hexagram Symbols"](t)||n["Yi Syllables"](t)||n["Yi Radicals"](t)))},r.charHasNeutralVerticalOrientation=function(t){return!!(n["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||n["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||n["Letterlike Symbols"](t)||n["Number Forms"](t)||n["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||n["Control Pictures"](t)&&9251!==t||n["Optical Character Recognition"](t)||n["Enclosed Alphanumerics"](t)||n["Geometric Shapes"](t)||n["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||n["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||n["CJK Symbols and Punctuation"](t)||n.Katakana(t)||n["Private Use Area"](t)||n["CJK Compatibility Forms"](t)||n["Small Form Variants"](t)||n["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)},r.charHasRotatedVerticalOrientation=function(t){return!(r.charHasUprightVerticalOrientation(t)||r.charHasNeutralVerticalOrientation(t))}},{"./is_char_in_unicode_block":265}],270:[function(t,e,r){var n=t("../geo/lng_lat");e.exports=function(t,e,r){if(t=new n(t.lng,t.lat),e){var i=new n(t.lng-360,t.lat),a=new n(t.lng+360,t.lat),o=r.locationPoint(t).distSqr(e);r.locationPoint(i).distSqr(e)180;){var s=r.locationPoint(t);if(s.x>=0&&s.y>=0&&s.x<=r.width&&s.y<=r.height)break;t.lng>r.center.lng?t.lng-=360:t.lng+=360}return t}},{"../geo/lng_lat":62}],271:[function(t,e,r){function n(t,e){return Math.ceil(t/e)*e}var i={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},a=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0)};a.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},a.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},a.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())},a.prototype.clear=function(){this.length=0},a.prototype.resize=function(t){this.reserve(t),this.length=t},a.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}},a.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")},e.exports.StructArray=a,e.exports.Struct=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8},e.exports.viewTypes=i,e.exports.createLayout=function(t,e){void 0===e&&(e=1);var r=0,a=0;return{members:t.map(function(t){var o=function(t){return i[t].BYTES_PER_ELEMENT}(t.type),s=r=n(r,Math.max(e,o)),l=t.components||1;return a=Math.max(a,o),r+=o*l,{name:t.name,type:t.type,components:l,offset:s}}),size:n(r,Math.max(a,e)),alignment:e}}},{}],272:[function(t,e,r){e.exports=function(t,e){var r=!1,n=0,i=function(){n=0,r&&(t(),n=setTimeout(i,e),r=!1)};return function(){return r=!0,n||i(),n}}},{}],273:[function(t,e,r){function n(t,e){if(t.row>e.row){var r=t;t=e,e=r}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function i(t,e,r,n,i){var a=Math.max(r,Math.floor(e.y0)),o=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx0,h=e.dx<0,f=a;fc.dy&&(l=u,u=c,c=l),u.dy>h.dy&&(l=u,u=h,h=l),c.dy>h.dy&&(l=c,c=h,h=l),u.dy&&i(h,u,a,o,s),c.dy&&i(h,c,a,o,s)}t("../geo/coordinate");var o=t("../source/tile_id").OverscaledTileID;e.exports=function(t,e,r,n){function i(e,i,a){var u,c,h;if(a>=0&&a<=s)for(u=e;u=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)},r.bezier=function(t,e,r,i){var a=new n(t,e,r,i);return function(t){return a.solve(t)}},r.ease=r.bezier(.25,.1,.25,1),r.clamp=function(t,e,r){return Math.min(r,Math.max(e,t))},r.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},r.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach(function(t,o){e(t,function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i)})})},r.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},r.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},r.extend=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];for(var i=0,a=r;i=0)return!0;return!1};var o={};r.warnOnce=function(t){o[t]||("undefined"!=typeof console&&console.warn(t),o[t]=!0)},r.isCounterClockwise=function(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)},r.calculateSignedArea=function(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r0||Math.abs(e.y-n.y)>0)&&Math.abs(r.calculateSignedArea(t))>.01},r.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},r.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r}return e}},{"../geo/coordinate":61,"../style-spec/util/deep_equal":155,"@mapbox/point-geometry":4,"@mapbox/unitbezier":7}],276:[function(t,e,r){var n=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id)},i={geometry:{}};i.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},i.geometry.set=function(t){this._geometry=t},n.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(n.prototype,i),e.exports=n},{}],277:[function(t,e,r){var n=t("./script_detection");e.exports=function(t){for(var r="",i=0;i":"\ufe40","?":"\ufe16","@":"\uff20","[":"\ufe47","\\":"\uff3c","]":"\ufe48","^":"\uff3e",_:"\ufe33","`":"\uff40","{":"\ufe37","|":"\u2015","}":"\ufe38","~":"\uff5e","\xa2":"\uffe0","\xa3":"\uffe1","\xa5":"\uffe5","\xa6":"\uffe4","\xac":"\uffe2","\xaf":"\uffe3","\u2013":"\ufe32","\u2014":"\ufe31","\u2018":"\ufe43","\u2019":"\ufe44","\u201c":"\ufe41","\u201d":"\ufe42","\u2026":"\ufe19","\u2027":"\u30fb","\u20a9":"\uffe6","\u3001":"\ufe11","\u3002":"\ufe12","\u3008":"\ufe3f","\u3009":"\ufe40","\u300a":"\ufe3d","\u300b":"\ufe3e","\u300c":"\ufe41","\u300d":"\ufe42","\u300e":"\ufe43","\u300f":"\ufe44","\u3010":"\ufe3b","\u3011":"\ufe3c","\u3014":"\ufe39","\u3015":"\ufe3a","\u3016":"\ufe17","\u3017":"\ufe18","\uff01":"\ufe15","\uff08":"\ufe35","\uff09":"\ufe36","\uff0c":"\ufe10","\uff0d":"\ufe32","\uff0e":"\u30fb","\uff1a":"\ufe13","\uff1b":"\ufe14","\uff1c":"\ufe3f","\uff1e":"\ufe40","\uff1f":"\ufe16","\uff3b":"\ufe47","\uff3d":"\ufe48","\uff3f":"\ufe33","\uff5b":"\ufe37","\uff5c":"\u2015","\uff5d":"\ufe38","\uff5f":"\ufe35","\uff60":"\ufe36","\uff61":"\ufe12","\uff62":"\ufe41","\uff63":"\ufe42"}},{"./script_detection":269}],278:[function(t,e,r){function n(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),g[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]}}var i=t("grid-index"),a=t("../style-spec/util/color"),o=t("../style-spec/expression"),s=o.StylePropertyFunction,l=o.StyleExpression,u=o.StyleExpressionWithErrorHandling,c=o.ZoomDependentExpression,h=o.ZoomConstantExpression,f=t("../style-spec/expression/compound_expression").CompoundExpression,p=t("../style-spec/expression/definitions"),d=t("./window").ImageData,g={};for(var v in n("Object",Object),i.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},i.deserialize=function(t){return new i(t)},n("Grid",i),n("Color",a),n("StylePropertyFunction",s),n("StyleExpression",l,{omit:["_evaluator"]}),n("StyleExpressionWithErrorHandling",u,{omit:["_evaluator"]}),n("ZoomDependentExpression",c),n("ZoomConstantExpression",h),n("CompoundExpression",f,{omit:["_evaluate"]}),p)p[v]._classRegistryKey||n("Expression_"+v,p[v]);e.exports={register:n,serialize:function t(e,r){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp)return e;if(e instanceof ArrayBuffer)return r&&r.push(e),e;if(ArrayBuffer.isView(e)){var n=e;return r&&r.push(n.buffer),n}if(e instanceof d)return r&&r.push(e.data.buffer),e;if(Array.isArray(e)){for(var i=[],a=0,o=e;a=0)){var f=e[h];c[h]=g[u].shallow.indexOf(h)>=0?f:t(f,r)}return{name:u,properties:c}}throw new Error("can't serialize object of type "+typeof e)},deserialize:function t(e){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof d)return e;if(Array.isArray(e))return e.map(function(e){return t(e)});if("object"==typeof e){var r=e,n=r.name,i=r.properties;if(!n)throw new Error("can't deserialize object of anonymous class");var a=g[n].klass;if(!a)throw new Error("can't deserialize unregistered class "+n);if(a.deserialize)return a.deserialize(i._serialized);for(var o=Object.create(a.prototype),s=0,l=Object.keys(i);s=0?i[u]:t(i[u])}return o}throw new Error("can't deserialize object of type "+typeof e)}}},{"../style-spec/expression":139,"../style-spec/expression/compound_expression":123,"../style-spec/expression/definitions":131,"../style-spec/util/color":153,"./window":254,"grid-index":24}],279:[function(t,e,r){var n=t("./web_worker"),i=function(){this.active={}};i.prototype.acquire=function(e){if(!this.workers){var r=t("../").workerCount;for(this.workers=[];this.workers.length0}function Iq(t){var e={},r={};switch(t.type){case"circle":ne.extendFlat(r,{"circle-radius":t.circle.radius,"circle-color":t.color,"circle-opacity":t.opacity});break;case"line":ne.extendFlat(r,{"line-width":t.line.width,"line-color":t.color,"line-opacity":t.opacity});break;case"fill":ne.extendFlat(r,{"fill-color":t.color,"fill-outline-color":t.fill.outlinecolor,"fill-opacity":t.opacity});break;case"symbol":var n=t.symbol,i=Cq(n.textposition,n.iconsize);ne.extendFlat(e,{"icon-image":n.icon+"-15","icon-size":n.iconsize/10,"text-field":n.text,"text-size":n.textfont.size,"text-anchor":i.anchor,"text-offset":i.offset}),ne.extendFlat(r,{"icon-color":t.color,"text-color":n.textfont.color,"text-opacity":t.opacity})}return{layout:e,paint:r}}zq.update=function(t){this.visible?this.needsNewSource(t)?(this.updateLayer(t),this.updateSource(t)):this.needsNewLayer(t)?this.updateLayer(t):this.updateStyle(t):(this.updateSource(t),this.updateLayer(t)),this.visible=Pq(t)},zq.needsNewSource=function(t){return this.sourceType!==t.sourcetype||this.source!==t.source||this.layerType!==t.type},zq.needsNewLayer=function(t){return this.layerType!==t.type||this.below!==t.below},zq.updateSource=function(t){var e=this.map;if(e.getSource(this.idSource)&&e.removeSource(this.idSource),this.sourceType=t.sourcetype,this.source=t.source,Pq(t)){var r=function(t){var e,r=t.sourcetype,n=t.source,i={type:r};"geojson"===r?e="data":"vector"===r&&(e="string"==typeof n?"url":"tiles");return i[e]=n,i}(t);e.addSource(this.idSource,r)}},zq.updateLayer=function(t){var e=this.map,r=Iq(t);e.getLayer(this.idLayer)&&e.removeLayer(this.idLayer),this.layerType=t.type,Pq(t)&&e.addLayer({id:this.idLayer,source:this.idSource,"source-layer":t.sourcelayer||"",type:t.type,layout:r.layout,paint:r.paint},t.below)},zq.updateStyle=function(t){if(Pq(t)){var e=Iq(t);this.mapbox.setOptions(this.idLayer,"setLayoutProperty",e.layout),this.mapbox.setOptions(this.idLayer,"setPaintProperty",e.paint)}},zq.dispose=function(){var t=this.map;t.removeLayer(this.idLayer),t.removeSource(this.idSource)};var Dq=function(t,e,r){var n=new Lq(t,e);return n.update(r),n};function Oq(t){this.id=t.id,this.gd=t.gd,this.container=t.container,this.isStatic=t.staticPlot;var e=t.fullLayout;this.uid=e._uid+"-"+this.id,this.opts=e[this.id],this.div=null,this.xaxis=null,this.yaxis=null,this.createFramework(e),this.map=null,this.accessToken=null,this.styleObj=null,this.traceHash={},this.layerList=[]}var Rq=Oq.prototype,Fq=function(t){return new Oq(t)};function Bq(t){var e=Sq.style.values,r=Sq.style.dflt,n={};return ne.isPlainObject(t)?(n.id=t.id,n.style=t):"string"==typeof t?(n.id=t,n.style=-1!==e.indexOf(t)?Nq(t):t):(n.id=r,n.style=Nq(r)),n.transition={duration:0,delay:0},n}function Nq(t){return _q.styleUrlPrefix+t+"-"+_q.styleUrlSuffix}function jq(t){return[t.lon,t.lat]}Rq.plot=function(t,e,r){var n,i=this,a=i.opts=e[this.id];i.map&&a.accesstoken!==i.accessToken&&(i.map.remove(),i.map=null,i.styleObj=null,i.traceHash=[],i.layerList={}),n=i.map?new Promise(function(r,n){i.updateMap(t,e,r,n)}):new Promise(function(r,n){i.createMap(t,e,r,n)}),r.push(n)},Rq.createMap=function(t,e,r,n){var i=this,a=i.gd,o=i.opts,s=i.styleObj=Bq(o.style);i.accessToken=o.accesstoken;var l=i.map=new bq.Map({container:i.div,style:s.style,center:jq(o.center),zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,interactive:!i.isStatic,preserveDrawingBuffer:i.isStatic,doubleClickZoom:!1,boxZoom:!1}),u=_q.controlContainerClassName,c=i.div.getElementsByClassName(u)[0];function h(){yo.loneUnhover(e._toppaper)}i.div.removeChild(c),l._canvas.style.left="0px",l._canvas.style.top="0px",i.rejectOnError(n),l.once("load",function(){i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)}),i.isStatic||(l.on("moveend",function(t){if(i.map){var e=i.getView();if(o._input.center=o.center=e.center,o._input.zoom=o.zoom=e.zoom,o._input.bearing=o.bearing=e.bearing,o._input.pitch=o.pitch=e.pitch,t.originalEvent){var r={};r[i.id]=ne.extendFlat({},e),a.emit("plotly_relayout",r)}}}),l.on("mousemove",function(t){var e=i.div.getBoundingClientRect();t.clientX=t.point.x+e.left,t.clientY=t.point.y+e.top,t.target.getBoundingClientRect=function(){return e},i.xaxis.p2c=function(){return t.lngLat.lng},i.yaxis.p2c=function(){return t.lngLat.lat},yo.hover(a,t,i.id)}),l.on("click",function(t){yo.click(a,t.originalEvent)}),l.on("dragstart",h),l.on("zoomstart",h),l.on("dblclick",function(){var t=i.viewInitial;l.setCenter(jq(t.center)),l.setZoom(t.zoom),l.setBearing(t.bearing),l.setPitch(t.pitch);var e=i.getView();o._input.center=o.center=e.center,o._input.zoom=o.zoom=e.zoom,o._input.bearing=o.bearing=e.bearing,o._input.pitch=o.pitch=e.pitch,a.emit("plotly_doubleclick",null)}),i.clearSelect=function(){a._fullLayout._zoomlayer.selectAll(".select-outline").remove()})},Rq.updateMap=function(t,e,r,n){var i=this,a=i.map;i.rejectOnError(n);var o=Bq(i.opts.style);i.styleObj.id!==o.id?(i.styleObj=o,a.setStyle(o.style),a.once("styledata",function(){i.traceHash={},i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)})):(i.updateData(t),i.updateLayout(e),i.resolveOnRender(r))},Rq.updateData=function(t){var e,r,n,i,a=this.traceHash;for(n=0;n=0?Math.floor((e+180)/360):Math.ceil((e-180)/360)),u=e-l;if(yo.getClosest(n,function(t){var e=t.lonlat;if(e[0]===Zq)return 1/0;var n=ne.wrap180(e[0]),i=e[1],l=s.project([n,i]),c=l.x-a.c2p([u,i]),h=l.y-o.c2p([n,r]),f=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(c*c+h*h)-f,1-3/f)},t),!1!==t.index){var c=n[t.index],h=c.lonlat,f=[ne.wrap180(h[0])+l,h[1]],p=a.c2p(f),d=o.c2p(f),g=c.mrc||1;return t.x0=p-g,t.x1=p+g,t.y0=d-g,t.y1=d+g,t.color=mx(i,c),t.extraText=function(t,e,r){var n=(e.hi||t.hoverinfo).split("+"),i=-1!==n.indexOf("all"),a=-1!==n.indexOf("lon"),o=-1!==n.indexOf("lat"),s=e.lonlat,l=[];function u(t){return t+"\xb0"}return i||a&&o?l.push("("+u(s[0])+", "+u(s[1])+")"):a?l.push(r.lon+u(s[0])):o&&l.push(r.lat+u(s[1])),(i||-1!==n.indexOf("text"))&&xo(e,t,l),l.join("
")}(i,c,n[0].t.labels),[t]}},iH.eventData=function(t,e){return t.lon=e.lon,t.lat=e.lat,t},iH.selectPoints=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[],s=n[0].trace;if(!Tr.hasMarkers(s))return[];if(!1===e)for(r=0;r0?1:-1}function VH(t){return jH(Math.cos(t))}function UH(t){return jH(Math.sin(t))}LH.plot=function(t,e){var r=e[this.id];this._hasClipOnAxisFalse=!1;for(var n=0;n=90||s>90&&l>=450?1:c<=0&&f<=0?0:Math.max(c,f);e=s<=180&&l>=180||s>180&&l>=540?-1:u>=0&&h>=0?0:Math.min(u,h);r=s<=270&&l>=270||s>270&&l>=630?-1:c>=0&&f>=0?0:Math.min(c,f);n=l>=360?1:u<=0&&h<=0?0:Math.max(u,h);return[e,r,n,i]}(d),v=g[2]-g[0],m=g[3]-g[1],y=p/f,x=Math.abs(m/v);y>x?(s=f,h=(p-(l=f*x))/i.h/2,u=[a[0],a[1]],c=[o[0]+h,o[1]-h]):(l=p,h=(f-(s=p/x))/i.w/2,u=[a[0]+h,a[1]-h],c=[o[0],o[1]]),r.xLength2=s,r.yLength2=l,r.xDomain2=u,r.yDomain2=c;var b=r.xOffset2=i.l+i.w*u[0],_=r.yOffset2=i.t+i.h*(1-c[1]),w=r.radius=s/v,M=r.cx=b-w*g[0],A=r.cy=_+w*g[3],k=r.cxx=M-b,T=r.cyy=A-_;r.updateRadialAxis(t,e),r.updateRadialAxisTitle(t,e),r.updateAngularAxis(t,e);var S=r.radialAxis.range,E=S[1]-S[0],C=r.xaxis={type:"linear",_id:"x",range:[g[0]*E,g[2]*E],domain:u};ri.setConvert(C,t),C.setScale();var L=r.yaxis={type:"linear",_id:"y",range:[g[1]*E,g[3]*E],domain:c};ri.setConvert(L,t),L.setScale(),C.isPtWithinRange=function(t){return r.isPtWithinSector(t)},L.isPtWithinRange=function(){return!0},n.frontplot.attr("transform",BH(b,_)).call(Sr.setClipUrl,r._hasClipOnAxisFalse?null:r.clipIds.circle),n.bgcircle.attr({d:OH(w,d),transform:BH(M,A)}).call(Oe.fill,e.bgcolor),r.clipPaths.circle.select("path").attr("d",OH(w,d)).attr("transform",BH(k,T)),r.framework.selectAll(".crisp").classed("crisp",0)},LH.updateRadialAxis=function(t,e){var r=this.gd,n=this.layers,i=this.radius,a=this.cx,o=this.cy,s=t._size,l=e.radialaxis,u=e.sector,c=TH(u[0]);this.fillViewInitialKey("radialaxis.angle",l.angle);var h=this.radialAxis=ne.extendFlat({},l,{_axislayer:n["radial-axis"],_gridlayer:n["radial-grid"],_id:"x",_pos:0,side:{counterclockwise:"top",clockwise:"bottom"}[l.side],domain:[0,i/s.w],anchor:"free",position:0,_counteraxis:!0,automargin:!1});PH(h,l,t),_H(h),l.range=h.range.slice(),l._input.range=h.range.slice(),this.fillViewInitialKey("radialaxis.range",h.range.slice()),"auto"===h.tickangle&&c>90&&c<=270&&(h.tickangle=180),h._transfn=function(t){return"translate("+h.l2p(t.x)+",0)"},h._gridpath=function(t){return DH(h.r2p(t.x),u)};var f=IH(l);this.radialTickLayout!==f&&(n["radial-axis"].selectAll(".xtick").remove(),this.radialTickLayout=f),ri.doTicks(r,h,!0),FH(n["radial-axis"],l.showticklabels||l.ticks,{transform:BH(a,o)+NH(-l.angle)}),FH(n["radial-grid"],l.showgrid,{transform:BH(a,o)}).selectAll("path").attr("transform",null),FH(n["radial-line"].select("line"),l.showline,{x1:0,y1:0,x2:i,y2:0,transform:BH(a,o)+NH(-l.angle)}).attr("stroke-width",l.linewidth).call(Oe.stroke,l.linecolor)},LH.updateRadialAxisTitle=function(t,e,r){var n=this.gd,i=this.radius,a=this.cx,o=this.cy,s=e.radialaxis,l=this.id+"title",u=void 0!==r?r:s.angle,c=AH(u),h=Math.cos(c),f=Math.sin(c),p=0;if(s.title){var d=Sr.bBox(this.layers["radial-axis"].node()).height,g=s.titlefont.size;p="counterclockwise"===s.side?-d-.4*g:d+.8*g}this.layers["radial-axis-title"]=Dn.draw(n,l,{propContainer:s,propName:this.id+".radialaxis.title",placeholder:MH(n,"Click to enter radial axis title"),attributes:{x:a+i/2*h+p*f,y:o-i/2*f+p*h,"text-anchor":"middle"},transform:{rotate:-u}})},LH.updateAngularAxis=function(t,r){var n=this,i=n.gd,a=n.layers,o=n.radius,s=n.cx,l=n.cy,u=r.angularaxis,c=r.sector,h=c.map(AH);n.fillViewInitialKey("angularaxis.rotation",u.rotation);var f=n.angularAxis=ne.extendFlat({},u,{_axislayer:a["angular-axis"],_gridlayer:a["angular-grid"],_id:"angular",_pos:0,side:"right",domain:[0,Math.PI],anchor:"free",position:0,_counteraxis:!0,automargin:!1,autorange:!1});if("linear"===f.type)RH(c)?f.range=c.slice():f.range=h.map(f.unTransformRad).map(kH),"radians"===f.thetaunit&&(f.tick0=kH(f.tick0),f.dtick=kH(f.dtick));else if("category"===f.type){var p=u.period?Math.max(u.period,u._categories.length):u._categories.length;f.range=[0,p],f._tickFilter=function(t){return n.isPtWithinSector({r:n.radialAxis.range[1],rad:f.c2rad(t.x)})}}function d(t){return f.c2rad(t.x,"degrees")}function g(t){return[o*Math.cos(t),o*Math.sin(t)]}PH(f,u,t),f._transfn=function(t){var r=d(t),n=g(r),i=BH(s+n[0],l-n[1]),a=e.select(this);return a&&a.node()&&a.classed("ticks")&&(i+=NH(-kH(r))),i},f._gridpath=function(t){var e=g(d(t));return"M0,0L"+-e[0]+","+e[1]};var v="outside"!==u.ticks?.7:.5;f._labelx=function(t){var e=d(t),r=f._labelStandoff,n=f._pad;return(0===UH(e)?0:Math.cos(e)*(r+n+v*t.fontSize))+VH(e)*(t.dx+r+n)},f._labely=function(t){var e=d(t),r=f._labelStandoff,n=f._labelShift,i=f._pad;return t.dy+t.fontSize*wH-n+-Math.sin(e)*(r+i+v*t.fontSize)},f._labelanchor=function(t,e){var r=d(e);return 0===UH(r)?VH(r)>0?"start":"end":"middle"};var m=IH(u);n.angularTickLayout!==m&&(a["angular-axis"].selectAll(".angulartick").remove(),n.angularTickLayout=m),ri.doTicks(i,f,!0),FH(a["angular-line"].select("path"),u.showline,{d:OH(o,c),transform:BH(s,l)}).attr("stroke-width",u.linewidth).call(Oe.stroke,u.linecolor)},LH.updateFx=function(t,e){this.gd._context.staticPlot||(this.updateAngularDrag(t,e),this.updateRadialDrag(t,e),this.updateMainDrag(t,e))},LH.updateMainDrag=function(t,r){var n=this,i=n.gd,a=n.layers,o=t._zoomlayer,l=oH.MINZOOM,u=oH.OFFEDGE,c=n.radius,h=n.cx,f=n.cy,p=n.cxx,d=n.cyy,g=r.sector,v=Bm.makeDragger(a,"path","maindrag","crosshair");e.select(v).attr("d",OH(c,g)).attr("transform",BH(h,f));var m,y,x,b,_,w,M,A,k,T={element:v,gd:i,subplot:n.id,plotinfo:{xaxis:n.xaxis,yaxis:n.yaxis},xaxes:[n.xaxis],yaxes:[n.yaxis]};function S(t,e){var r=t-p,n=e-d;return Math.sqrt(r*r+n*n)}function E(t,e){return Math.atan2(d-e,t-p)}function C(t,e){return[t*Math.cos(e),t*Math.sin(-e)]}function L(t,e){var r=oH.cornerLen,n=oH.cornerHalfWidth;if(0===t)return OH(2*n,g);var i=r/t/2,a=e-i,o=e+i,s=Math.max(0,Math.min(t,c)),l=s-n,u=s+n;return"M"+C(l,a)+"A"+[l,l]+" 0,0,0 "+C(l,o)+"L"+C(u,o)+"A"+[u,u]+" 0,0,1 "+C(u,a)+"Z"}function z(t,e){var r,n,i=m+t,a=y+e,o=S(m,y),s=Math.min(S(i,a),c),h=E(m,y),f=E(i,a);ol?(o0==c>f[0]){y=u.range[1]=c,ri.doTicks(i,n.radialAxis,!0),a["radial-grid"].attr("transform",BH(s,l)).selectAll("path").attr("transform",null);var d=y-f[0],g=n.sectorBBox;for(var v in n.xaxis.range=[g[0]*d,g[2]*d],n.yaxis.range=[g[1]*d,g[3]*d],n.xaxis.setScale(),n.yaxis.setScale(),n.traceHash){var m=n.traceHash[v],x=ne.filterVisible(m),b=m[0][0].trace._module,_=i._fullLayout[n.id];if(b.plot(i,n,x,_),!P.traceIs(v,"gl"))for(var w=0;wo&&(o+=360);var s,l,u=TH(kH(t.rad)),c=u+360;return n[1]>=n[0]?(s=n[0],l=n[1]):(s=n[1],l=n[0]),i>=s&&i<=l&&(RH(e)||u>=a&&u<=o||c>=a&&c<=o)},LH.fillViewInitialKey=function(t,e){t in this.viewInitial||(this.viewInitial[t]=e)};var qH=sa.getSubplotCalcData,HH=ne.counterRegex,GH=oH.attr,WH=oH.name,YH=HH(WH),XH={};XH[GH]={valType:"subplotid",dflt:WH,editType:"calc"};var ZH={attr:GH,name:WH,idRoot:WH,idRegex:YH,attrRegex:YH,attributes:XH,layoutAttributes:dH,supplyLayoutDefaults:function(t,e,r){Jc(t,e,0,{type:oH.name,attributes:dH,handleDefaults:xH,font:e.font,paper_bgcolor:e.paper_bgcolor,fullData:r,layoutOut:e})},plot:function(t){for(var e=t._fullLayout,r=t.calcdata,n=e._subplots[WH],i=0;i")}var nG={hoverPoints:function(t,e,r,n){var i=yx(t,e,r,n);if(i&&!1!==i[0].index){var a=i[0];if(void 0===a.index)return i;var o=t.subplot,s=a.cd[a.index],l=a.trace;if(o.isPtWithinSector(s))return a.xLabelVal=void 0,a.yLabelVal=void 0,a.extraText=rG(s,l,o),i}},makeHoverPointText:rG},iG=t.BADNUM,aG={moduleType:"trace",name:"scatterpolar",basePlotModule:ZH,categories:["polar","symbols","markerColorscale","showLegend","scatter-like"],attributes:QH,supplyDefaults:function(t,e,r,n){function i(r,n){return ne.coerce(t,e,QH,r,n)}var a=i("r"),o=i("theta"),s=a&&o?Math.min(a.length,o.length):0;if(s){e._length=s,i("thetaunit"),i("mode",sl[1]?function(t){return t<=0}:function(t){return t>=0},n=0;n=0?(f=i.c2r(h)-o[0],w=p,d=a.c2rad(w,v.thetaunit),k[c]=A[2*c]=f*Math.cos(d),T[c]=A[2*c+1]=f*Math.sin(d)):k[c]=T[c]=A[2*c]=A[2*c+1]=NaN;var S=yq.sceneOptions(t,e,v,A);S.fill&&!s.fill2d&&(s.fill2d=!0),S.marker&&!s.scatter2d&&(s.scatter2d=!0),S.line&&!s.line2d&&(s.line2d=!0),!S.errorX&&!S.errorY||s.error2d||(s.error2d=!0),Tr.hasMarkers(v)&&(S.selected.positions=S.unselected.positions=S.marker.positions),s.lineOptions.push(S.line),s.errorXOptions.push(S.errorX),s.errorYOptions.push(S.errorY),s.fillOptions.push(S.fill),s.markerOptions.push(S.marker),s.selectedOptions.push(S.selected),s.unselectedOptions.push(S.unselected),s.count=n.length,m.scene=s,m.index=u,m.x=k,m.y=T,m.rawx=k,m.rawy=T,m.r=y,m.theta=x,m.positions=A,m.count=M,m.tree=vV(A,512)}}),yq.plot(t,e,n)},hoverPoints:function(t,e,r,n){var i=t.cd[0].t,a=i.r,o=i.theta,s=yq.hoverPoints(t,e,r,n);if(s&&!1!==s[0].index){var l=s[0];if(void 0===l.index)return s;var u=t.subplot,c=u.angularAxis,h=l.cd[l.index],f=l.trace;if(h.r=a[l.index],h.theta=o[l.index],h.rad=c.c2rad(h.theta,f.thetaunit),u.isPtWithinSector(h))return l.xLabelVal=void 0,l.yLabelVal=void 0,l.extraText=lG(h,f,u),s}},style:yq.style,selectPoints:yq.selectPoints,meta:{}},cG=m.extendFlat,hG={title:Ce.title,titlefont:Ce.titlefont,color:Ce.color,tickmode:Ce.tickmode,nticks:cG({},Ce.nticks,{dflt:6,min:1}),tick0:Ce.tick0,dtick:Ce.dtick,tickvals:Ce.tickvals,ticktext:Ce.ticktext,ticks:Ce.ticks,ticklen:Ce.ticklen,tickwidth:Ce.tickwidth,tickcolor:Ce.tickcolor,showticklabels:Ce.showticklabels,showtickprefix:Ce.showtickprefix,tickprefix:Ce.tickprefix,showticksuffix:Ce.showticksuffix,ticksuffix:Ce.ticksuffix,showexponent:Ce.showexponent,exponentformat:Ce.exponentformat,separatethousands:Ce.separatethousands,tickfont:Ce.tickfont,tickangle:Ce.tickangle,tickformat:Ce.tickformat,tickformatstops:Ce.tickformatstops,hoverformat:Ce.hoverformat,showline:cG({},Ce.showline,{dflt:!0}),linecolor:Ce.linecolor,linewidth:Ce.linewidth,showgrid:cG({},Ce.showgrid,{dflt:!0}),gridcolor:Ce.gridcolor,gridwidth:Ce.gridwidth,layer:Ce.layer,min:{valType:"number",dflt:0,min:0}},fG=function(t,e,r){function n(r,n){return ne.coerce(t,e,hG,r,n)}e.type="linear";var i=n("color"),a=i===t.color?i:r.font.color,o=e._name.charAt(0).toUpperCase(),s="Component "+o,l=n("title",s);e._hovertitle=l===s?l:o,ne.coerceFont(n,"titlefont",{family:r.font.family,size:Math.round(1.2*r.font.size),color:a}),n("min"),Ge(t,e,n,"linear"),Ue(t,e,n,"linear",{}),qe(t,e,n,{outerTicks:!0}),n("showticklabels")&&(ne.coerceFont(n,"tickfont",{family:r.font.family,size:r.font.size,color:a}),n("tickangle"),n("tickformat")),Zi(t,e,n,{dfltColor:i,bgColor:r.bgColor,blend:60,showLine:!0,showGrid:!0,noZeroLine:!0,attributes:hG}),n("hoverformat"),n("layer")},pG=qc.attributes,dG=(0,ye.overrideAll)({domain:pG({name:"ternary"}),bgcolor:{valType:"color",dflt:C.background},sum:{valType:"number",dflt:1,min:0},aaxis:hG,baxis:hG,caxis:hG},"plot","from-root"),gG=["aaxis","baxis","caxis"];function vG(t,e,r,n){var i,a,o,s=r("bgcolor"),l=r("sum");n.bgColor=Oe.combine(s,n.paper_bgcolor);for(var u=0;u=l&&(c.min=0,h.min=0,f.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}var mG=ne._,yG=m.extendFlat;function xG(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework(e)}var bG=xG,_G=xG.prototype;_G.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={},this.layers={}},_G.plot=function(t,e){var r=e[this.id],n=e._size;this._hasClipOnAxisFalse=!1;for(var i=0;iwG*g?i=(a=g)*wG:a=(i=d)/wG,o=f*i/d,s=p*a/g,r=e.l+e.w*c-i/2,n=e.t+e.h*(1-h)-a/2,l.x0=r,l.y0=n,l.w=i,l.h=a,l.sum=v,l.xaxis={type:"linear",range:[m+2*x-v,v-m-2*y],domain:[c-o/2,c+o/2],_id:"x"},ei(l.xaxis,l.graphDiv._fullLayout),l.xaxis.setScale(),l.xaxis.isPtWithinRange=function(t){return t.a>=l.aaxis.range[0]&&t.a<=l.aaxis.range[1]&&t.b>=l.baxis.range[1]&&t.b<=l.baxis.range[0]&&t.c>=l.caxis.range[1]&&t.c<=l.caxis.range[0]},l.yaxis={type:"linear",range:[m,v-y-x],domain:[h-s/2,h+s/2],_id:"y"},ei(l.yaxis,l.graphDiv._fullLayout),l.yaxis.setScale(),l.yaxis.isPtWithinRange=function(){return!0};var b=l.yaxis.domain[0],_=l.aaxis=yG({},t.aaxis,{visible:!0,range:[m,v-y-x],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[b,b+s*wG],_axislayer:l.layers.aaxis,_gridlayer:l.layers.agrid,_pos:0,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2,automargin:!1});ei(_,l.graphDiv._fullLayout),_.setScale();var w=l.baxis=yG({},t.baxis,{visible:!0,range:[v-m-x,y],side:"bottom",_counterangle:30,domain:l.xaxis.domain,_axislayer:l.layers.baxis,_gridlayer:l.layers.bgrid,_counteraxis:l.aaxis,_pos:0,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a,automargin:!1});ei(w,l.graphDiv._fullLayout),w.setScale(),_._counteraxis=w;var M=l.caxis=yG({},t.caxis,{visible:!0,range:[v-m-y,x],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[b,b+s*wG],_axislayer:l.layers.caxis,_gridlayer:l.layers.cgrid,_counteraxis:l.baxis,_pos:0,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2,automargin:!1});ei(M,l.graphDiv._fullLayout),M.setScale();var A="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDef.select("path").attr("d",A),l.layers.plotbg.select("path").attr("d",A);var k="M0,"+a+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDefRelative.select("path").attr("d",k);var T="translate("+r+","+n+")";l.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",T),l.clipDefRelative.select("path").attr("transform",null);var S="translate("+(r-w._offset)+","+(n+a)+")";l.layers.baxis.attr("transform",S),l.layers.bgrid.attr("transform",S);var E="translate("+(r+i/2)+","+n+")rotate(30)translate(0,"+-_._offset+")";l.layers.aaxis.attr("transform",E),l.layers.agrid.attr("transform",E);var C="translate("+(r+i/2)+","+n+")rotate(-30)translate(0,"+-M._offset+")";l.layers.caxis.attr("transform",C),l.layers.cgrid.attr("transform",C),l.drawAxes(!0),l.plotContainer.selectAll(".crisp").classed("crisp",!1),l.layers.aline.select("path").attr("d",_.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(Oe.stroke,_.linecolor||"#000").style("stroke-width",(_.linewidth||0)+"px"),l.layers.bline.select("path").attr("d",w.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(Oe.stroke,w.linecolor||"#000").style("stroke-width",(w.linewidth||0)+"px"),l.layers.cline.select("path").attr("d",M.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(Oe.stroke,M.linecolor||"#000").style("stroke-width",(M.linewidth||0)+"px"),l.graphDiv._context.staticPlot||l.initInteractions(),Sr.setClipUrl(l.layers.frontplot,l._hasClipOnAxisFalse?null:l.clipId)},_G.drawAxes=function(t){var e=this.graphDiv,r=this.id.substr(7)+"title",n=this.aaxis,i=this.baxis,a=this.caxis;if(ri.doTicks(e,n,!0),ri.doTicks(e,i,!0),ri.doTicks(e,a,!0),t){var o=Math.max(n.showticklabels?n.tickfont.size/2:0,(a.showticklabels?.75*a.tickfont.size:0)+("outside"===a.ticks?.87*a.ticklen:0));this.layers["a-title"]=Dn.draw(e,"a"+r,{propContainer:n,propName:this.id+".aaxis.title",placeholder:mG(e,"Click to enter Component A title"),attributes:{x:this.x0+this.w/2,y:this.y0-n.titlefont.size/3-o,"text-anchor":"middle"}});var s=(i.showticklabels?i.tickfont.size:0)+("outside"===i.ticks?i.ticklen:0)+3;this.layers["b-title"]=Dn.draw(e,"b"+r,{propContainer:i,propName:this.id+".baxis.title",placeholder:mG(e,"Click to enter Component B title"),attributes:{x:this.x0-s,y:this.y0+this.h+.83*i.titlefont.size+s,"text-anchor":"middle"}}),this.layers["c-title"]=Dn.draw(e,"c"+r,{propContainer:a,propName:this.id+".caxis.title",placeholder:mG(e,"Click to enter Component C title"),attributes:{x:this.x0+this.w+s,y:this.y0+this.h+.83*a.titlefont.size+s,"text-anchor":"middle"}})}};var MG=Te.MINZOOM/2+.87,AG="m-0.87,.5h"+MG+"v3h-"+(MG+5.2)+"l"+(MG/2+2.6)+",-"+(.87*MG+4.5)+"l2.6,1.5l-"+MG/2+","+.87*MG+"Z",kG="m0.87,.5h-"+MG+"v3h"+(MG+5.2)+"l-"+(MG/2+2.6)+",-"+(.87*MG+4.5)+"l-2.6,1.5l"+MG/2+","+.87*MG+"Z",TG="m0,1l"+MG/2+","+.87*MG+"l2.6,-1.5l-"+(MG/2+2.6)+",-"+(.87*MG+4.5)+"l-"+(MG/2+2.6)+","+(.87*MG+4.5)+"l2.6,1.5l"+MG/2+",-"+.87*MG+"Z",SG="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",EG=!0;function CG(t){e.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}_G.initInteractions=function(){var t,e,r,n,i,a,o,l,u,c,h=this,f=h.layers.plotbg.select("path").node(),p=h.graphDiv,d=p._fullLayout._zoomlayer,g={element:f,gd:p,plotinfo:{xaxis:h.xaxis,yaxis:h.yaxis},subplot:h.id,prepFn:function(v,m,y){g.xaxes=[h.xaxis],g.yaxes=[h.yaxis];var A=p._fullLayout.dragmode;v.shiftKey&&(A="pan"===A?"zoom":"pan"),g.minDrag="lasso"===A?1:void 0,"zoom"===A?(g.moveFn=x,g.doneFn=b,function(p,g,v){var m=f.getBoundingClientRect();t=g-m.left,e=v-m.top,r={a:h.aaxis.range[0],b:h.baxis.range[1],c:h.caxis.range[1]},i=r,n=h.aaxis.range[1]-r.a,a=s(h.graphDiv._fullLayout[h.id].bgcolor).getLuminance(),o="M0,"+h.h+"L"+h.w/2+", 0L"+h.w+","+h.h+"Z",l=!1,u=d.append("path").attr("class","zoombox").attr("transform","translate("+h.x0+", "+h.y0+")").style({fill:a>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",o),c=d.append("path").attr("class","zoombox-corners").attr("transform","translate("+h.x0+", "+h.y0+")").style({fill:Oe.background,stroke:Oe.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),M()}(0,m,y)):"pan"===A?(g.moveFn=_,g.doneFn=w,r={a:h.aaxis.range[0],b:h.baxis.range[1],c:h.caxis.range[1]},i=r,M()):"select"!==A&&"lasso"!==A||_c(v,m,y,g,A)},clickFn:function(t,e){if(CG(p),2===t){var r={};r[h.id+".aaxis.min"]=0,r[h.id+".baxis.min"]=0,r[h.id+".caxis.min"]=0,p.emit("plotly_doubleclick",null),P.call("relayout",p,r)}yo.click(p,e,h.id)}};function v(t,e){return 1-e/h.h}function m(t,e){return 1-(t+(h.h-e)/Math.sqrt(3))/h.w}function y(t,e){return(t-(h.h-e)/Math.sqrt(3))/h.w}function x(s,f){var p=t+s,d=e+f,g=Math.max(0,Math.min(1,v(0,e),v(0,d))),x=Math.max(0,Math.min(1,m(t,e),m(p,d))),b=Math.max(0,Math.min(1,y(t,e),y(p,d))),_=(g/2+b)*h.w,w=(1-g/2-x)*h.w,M=(_+w)/2,A=w-_,k=(1-g)*h.h,T=k-A/wG;A.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),c.transition().style("opacity",1).duration(200),l=!0)}function b(){if(CG(p),i!==r){var t={};t[h.id+".aaxis.min"]=i.a,t[h.id+".baxis.min"]=i.b,t[h.id+".caxis.min"]=i.c,P.call("relayout",p,t),EG&&p.data&&p._context.showTips&&(ne.notifier(mG(p,"Double-click to zoom back out"),"long"),EG=!1)}}function _(t,e){var n=t/h.xaxis._m,a=e/h.yaxis._m,o=[(i={a:r.a-a,b:r.b+(n+a)/2,c:r.c-(n-a)/2}).a,i.b,i.c].sort(),s=o.indexOf(i.a),l=o.indexOf(i.b),u=o.indexOf(i.c);o[0]<0&&(o[1]+o[0]/2<0?(o[2]+=o[0]+o[1],o[0]=o[1]=0):(o[2]+=o[0]/2,o[1]+=o[0]/2,o[0]=0),i={a:o[s],b:o[l],c:o[u]},e=(r.a-i.a)*h.yaxis._m,t=(r.c-i.c-r.b+i.b)*h.xaxis._m);var c="translate("+(h.x0+t)+","+(h.y0+e)+")";h.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",c);var f="translate("+-t+","+-e+")";h.clipDefRelative.select("path").attr("transform",f),h.aaxis.range=[i.a,h.sum-i.b-i.c],h.baxis.range=[h.sum-i.a-i.c,i.b],h.caxis.range=[h.sum-i.a-i.b,i.c],h.drawAxes(!1),h.plotContainer.selectAll(".crisp").classed("crisp",!1),h._hasClipOnAxisFalse&&h.plotContainer.select(".scatterlayer").selectAll(".trace").call(Sr.hideOutsideRangePoints,h)}function w(){var t={};t[h.id+".aaxis.min"]=i.a,t[h.id+".baxis.min"]=i.b,t[h.id+".caxis.min"]=i.c,P.call("relayout",p,t)}function M(){d.selectAll(".select-outline").remove()}f.onmousemove=function(t){yo.hover(p,t,h.id),p._fullLayout._lasthover=f,p._fullLayout._hoversubplot=h.id},f.onmouseout=function(t){p._dragging||Ua.unhover(p,t)},Ua.init(g)};var LG={},zG=sa.getSubplotCalcData,PG=ne.counterRegex;LG.name="ternary",LG.attr="subplot",LG.idRoot="ternary",LG.idRegex=LG.attrRegex=PG("ternary"),LG.attributes={subplot:{valType:"subplotid",dflt:"ternary",editType:"calc"}},LG.layoutAttributes=dG,LG.supplyLayoutDefaults=function(t,e,r){Jc(t,e,0,{type:"ternary",attributes:dG,handleDefaults:vG,font:e.font,paper_bgcolor:e.paper_bgcolor})},LG.plot=function(t){for(var e=t._fullLayout,r=t.calcdata,n=e._subplots.ternary,i=0;i"),i}function g(t,e){d.push(t._hovertitle+": "+ri.tickText(t,e,"hover").text)}},UG.selectPoints=Sx,UG.eventData=function(t,e,r,n,i){if(e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),n[i]){var a=n[i];t.a=a.a,t.b=a.b,t.c=a.c}else t.a=e.a,t.b=e.b,t.c=e.c;return t},UG.moduleType="trace",UG.name="scatterternary",UG.basePlotModule=LG,UG.categories=["ternary","symbols","markerColorscale","showLegend","scatter-like"],UG.meta={};var qG=UG,HG={},GG=Di.pointsAccessorFunction;HG.moduleType="transform",HG.name="sort",HG.attributes={enabled:{valType:"boolean",dflt:!0,editType:"calc"},target:{valType:"string",strict:!0,noBlank:!0,arrayOk:!0,dflt:"x",editType:"calc"},order:{valType:"enumerated",values:["ascending","descending"],dflt:"ascending",editType:"calc"},editType:"calc"},HG.supplyDefaults=function(t){var e={};function r(r,n){return ne.coerce(t,e,HG.attributes,r,n)}return r("enabled")&&(r("target"),r("order")),e},HG.calcTransform=function(t,e,r){if(r.enabled){var n=ne.getTargetArray(e,r);if(n){var i,a,o=r.target,s=n.length,l=e._arrayAttrs,u=function(t,e,r){for(var n=e.length,i=new Array(n),a=e.slice().sort(function(t,e){switch(t.order){case"ascending":return function(t,r){return e(t)-e(r)};case"descending":return function(t,r){return e(r)-e(t)}}}(t,r)),o=0;o 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 \u2014 in vertex or in fragment\n vec4 surfaceColor = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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"]),JG=E_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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"]),KG=E_(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]);YG.createShader=function(t){var e=Bw(t,XG,ZG,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},YG.createPickShader=function(t){var e=Bw(t,XG,KG,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},YG.createContourShader=function(t){var e=Bw(t,JG,ZG,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},YG.createPickContourShader=function(t){var e=Bw(t,JG,KG,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e};var QG=function(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r=b_(e.dimension,"string"==typeof r?r:"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;n=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),a.push("1"),o.push("s["+l+"]-2"));var u=".lo("+a.join()+").hi("+o.join()+")";if(0===a.length&&(u=""),i>0){n.push("if(1");for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push("&&s[",l,"]>2");n.push("){grad",i,"(src.pick(",s.join(),")",u);for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push(",dst.pick(",s.join(),",",l,")",u);n.push(");")}for(var l=0;l1){dst.set(",s.join(),",",c,",0.5*(src.get(",f.join(),")-src.get(",p.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>1){diff(",h,",src.pick(",f.join(),")",u,",src.pick(",p.join(),")",u,");}else{zero(",h,");};");break;case"mirror":0===i?n.push("dst.set(",s.join(),",",c,",0);"):n.push("zero(",h,");");break;case"wrap":var d=s.slice(),g=s.slice();e[l]<0?(d[c]="s["+c+"]-2",g[c]="0"):(d[c]="s["+c+"]-1",g[c]="1"),0===i?n.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",d.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>2){diff(",h,",src.pick(",d.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",h,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}i>0&&n.push("};")}for(var a=0;a<1<=1)return!0;for(var t=0;t<3;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},yW.pickSlots=1,yW.setPickBase=function(t){this.pickId=t};var xW=[0,0,0],bW={showSurface:!1,showContour:!1,projections:[pW.slice(),pW.slice(),pW.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]};function _W(t,e){var r,n,i,a=e.axes&&e.axes.lastCubeProps.axis||xW,o=e.showSurface,s=e.showContour;for(r=0;r<3;++r)for(o=o||e.surfaceProject[r],n=0;n<3;++n)s=s||e.contourProject[r][n];for(r=0;r<3;++r){var l=bW.projections[r];for(n=0;n<16;++n)l[n]=0;for(n=0;n<4;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],Dz(l,t.model,l);var u=bW.clipBounds[r];for(i=0;i<2;++i)for(n=0;n<3;++n)u[i][n]=t.clipBounds[i][n];u[0][r]=-1e8,u[1][r]=1e8}return bW.showSurface=o,bW.showContour=s,bW}var wW={model:pW,view:pW,projection:pW,inverseModel:pW.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1,vertexColor:0},MW=pW.slice(),AW=[1,0,0,0,1,0,0,0,1];function kW(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=wW;n.model=t.model||pW,n.view=t.view||pW,n.projection=t.projection||pW,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=cz(n.inverseModel,n.model);for(var i=0;i<2;++i)for(var a=n.clipBounds[i],o=0;o<3;++o)a[o]=Math.min(Math.max(this.clipBounds[i][o],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=AW,n.vertexColor=this.vertexColor;var s=MW;for(Dz(s,n.view,n.model),Dz(s,n.projection,s),cz(s,s),i=0;i<3;++i)n.eyePosition[i]=s[12+i]/s[15];var l=s[15];for(i=0;i<3;++i)l+=this.lightPosition[i]*s[4*i+3];for(i=0;i<3;++i){var u=s[12+i];for(o=0;o<3;++o)u+=s[4*o+i]*this.lightPosition[o];n.lightPosition[i]=u/l}var c=_W(n,this);if(c.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;i<3;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=c.projections[i],this._shader.uniforms.clipBounds=c.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(c.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var f=this._contourVAO;for(f.bind(),i=0;i<3;++i)for(h.uniforms.permutation=gW[i],r.lineWidth(this.contourWidth[i]),o=0;o>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;c<2;++c)for(var h=c?a:1-a,f=0;f<2;++f)for(var p=i+c,d=s+f,g=h*(f?l:1-l),v=0;v<3;++v)u[v]+=this._field[v].get(p,d)*g;for(var m=this._pickResult.level,y=0;y<3;++y)if(m[y]=wT.le(this.contourLevels[y],u[y]),m[y]<0)this.contourLevels[y].length>0&&(m[y]=0);else if(m[y]Math.abs(b-u[y])&&(m[y]+=1)}for(r.index[0]=a<.5?i:i+1,r.index[1]=l<.5?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],v=0;v<3;++v)r.dataCoordinate[v]=this._field[v].get(r.index[0],r.index[1]);return r},yW.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=EW(t.contourWidth,Number)),"showContour"in t&&(this.showContour=EW(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=EW(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=LW(t.contourColor)),"contourProject"in t&&(this.contourProject=EW(t.contourProject,function(t){return EW(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=LW(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=EW(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=EW(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds),"vertexColor"in t&&(this.vertexColor=t.vertexColor?1:0);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(__.freeFloat(this._field[2].data),this._field[2].data=__.mallocFloat(Mb.nextPow2(n))),this._field[2]=wb(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),SW(this._field[2],e),this.shape=e.shape.slice();for(var i=this.shape,a=0;a<2;++a)this._field[2].size>this._field[a].data.length&&(__.freeFloat(this._field[a].data),this._field[a].data=__.mallocFloat(this._field[2].size)),this._field[a]=wb(this._field[a].data,[i[0]+2,i[1]+2]);if(t.coords){var o=t.coords;if(!Array.isArray(o)||3!==o.length)throw new Error("gl-surface: invalid coordinates for x/y");for(a=0;a<2;++a){var s=o[a];for(f=0;f<2;++f)if(s.shape[f]!==i[f])throw new Error("gl-surface: coords have incorrect shape");SW(this._field[a],s)}}else if(t.ticks){var l=t.ticks;if(!Array.isArray(l)||2!==l.length)throw new Error("gl-surface: invalid ticks");for(a=0;a<2;++a){var u=l[a];if((Array.isArray(u)||u.length)&&(u=wb(u)),u.shape[0]!==i[a])throw new Error("gl-surface: invalid tick length");var c=wb(u.data,i);c.stride[a]=u.stride[0],c.stride[1^a]=0,SW(this._field[a],c)}}else{for(a=0;a<2;++a){var h=[0,0];h[a]=1,this._field[a]=wb(this._field[a].data,[i[0]+2,i[1]+2],h,0)}this._field[0].set(0,0,0);for(var f=0;f0){for(var ct=0;ct<5;++ct)H.pop();I-=1}continue t}H.push(X[0],X[1],K[0],K[1],X[2]),I+=1}}Y.push(I)}this._contourOffsets[G]=W,this._contourCounts[G]=Y}var ht=__.mallocFloat(H.length);for(a=0;a",maxDimensionCount:60,overdrag:45,releaseTransitionDuration:120,releaseTransitionEase:"cubic-out",scrollbarCaptureWidth:18,scrollbarHideDelay:1e3,scrollbarHideDuration:1e3,scrollbarOffset:5,scrollbarWidth:8,transitionDuration:100,transitionEase:"cubic-out",uplift:5,wrapSpacer:" ",wrapSplitCharacter:" ",cn:{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",scrollbarKit:"scrollbar-kit",scrollbar:"scrollbar",scrollbarSlider:"scrollbar-slider",scrollbarGlyph:"scrollbar-glyph",scrollbarCaptureZone:"scrollbar-capture-zone"}},iY=m.extendFlat;function aY(t){return t.calcdata.columns.reduce(function(e,r){return r.xIndex=e||u===t.length-1)&&(n[i]=o,o.key=l++,o.firstRowIndex=s,o.lastRowIndex=u,o={firstRowIndex:null,lastRowIndex:null,rows:[]},i+=a,s=u+1,a=0);return n}var lY={},uY=m.extendFlat;lY.splitToPanels=function(t){var e=[0,0],r=uY({},t,{key:"header",type:"header",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!0,values:t.calcdata.headerCells.values[t.specIndex],rowBlocks:t.calcdata.headerRowBlocks,calcdata:uY({},t.calcdata,{cells:t.calcdata.headerCells})});return[uY({},t,{key:"cells1",type:"cells",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),uY({},t,{key:"cells2",type:"cells",page:1,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),r]},lY.splitToCells=function(t){var e=function(t){var e=t.rowBlocks[t.page],r=e?e.rows[0].rowIndex:0,n=e?r+e.rows.length:0;return[r,n]}(t);return(t.values||[]).slice(e[0],e[1]).map(function(r,n){return{keyWithinBlock:n+("string"==typeof r&&r.match(/[<$&> ]/)?"_keybuster_"+Math.random():""),key:e[0]+n,column:t,calcdata:t.calcdata,page:t.page,rowBlocks:t.rowBlocks,value:r}})};var cY=ne.raiseToTop,hY=ne.cancelTransition,fY=function(t,n){var i=t._fullLayout._paper.selectAll("."+nY.cn.table).data(n.map(function(e){var n=ZR.unwrap(e).trace;return function(t,e){var n=e.cells.values,i=function(t){return t.slice(e.header.values.length,t.length)},a=e.header.values.map(function(t){return Array.isArray(t)?t:[t]}).concat(i(n).map(function(){return[""]})),o=e.domain,s=Math.floor(t._fullLayout._size.w*(o.x[1]-o.x[0])),l=Math.floor(t._fullLayout._size.h*(o.y[1]-o.y[0])),u=e.header.values.length?a[0].map(function(){return e.header.height}):[nY.emptyHeaderHeight],c=n.length?n[0].map(function(){return e.cells.height}):[],h=u.reduce(function(t,e){return t+e},0),f=sY(c,l-h+nY.uplift),p=oY(sY(u,h),[]),d=oY(f,p),g={},v=e._fullInput.columnorder.concat(i(n.map(function(t,e){return e}))),m=a.map(function(t,n){var i=Array.isArray(e.columnwidth)?e.columnwidth[Math.min(n,e.columnwidth.length-1)]:e.columnwidth;return r(i)?Number(i):1}),y=m.reduce(function(t,e){return t+e},0);m=m.map(function(t){return t/y*s});var x={key:e.index,translateX:o.x[0]*t._fullLayout._size.w,translateY:t._fullLayout._size.h*(1-o.y[1]),size:t._fullLayout._size,width:s,height:l,columnOrder:v,groupHeight:l,rowBlocks:d,headerRowBlocks:p,scrollY:0,cells:e.cells,headerCells:iY({},e.header,{values:a}),gdColumns:a.map(function(t){return t[0]}),gdColumnsOriginalOrder:a.map(function(t){return t[0]}),prevPages:[0,0],scrollbarState:{scrollbarScrollInProgress:!1},columns:a.map(function(t,e){var r=g[t];return g[t]=(r||0)+1,{key:t+"__"+g[t],label:t,specIndex:e,xIndex:v[e],xScale:aY,x:void 0,calcdata:void 0,columnWidth:m[e]}})};return x.columns.forEach(function(t){t.calcdata=x,t.x=aY(t)}),x}(t,n)}),ZR.keyFun);i.exit().remove(),i.enter().append("g").classed(nY.cn.table,!0).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"),i.attr("width",function(t){return t.width+t.size.l+t.size.r}).attr("height",function(t){return t.height+t.size.t+t.size.b}).attr("transform",function(t){return"translate("+t.translateX+","+t.translateY+")"});var a=i.selectAll("."+nY.cn.tableControlView).data(ZR.repeat,ZR.keyFun);a.enter().append("g").classed(nY.cn.tableControlView,!0).style("box-sizing","content-box").on("mousemove",function(e){a.filter(function(t){return e===t}).call(vY,t)}).on("mousewheel",function(r){r.scrollbarState.wheeling||(r.scrollbarState.wheeling=!0,e.event.stopPropagation(),e.event.preventDefault(),TY(t,a,null,r.scrollY+e.event.deltaY)(r),r.scrollbarState.wheeling=!1)}).call(vY,t,!0),a.attr("transform",function(t){return"translate("+t.size.l+" "+t.size.t+")"});var o=a.selectAll("."+nY.cn.scrollBackground).data(ZR.repeat,ZR.keyFun);o.enter().append("rect").classed(nY.cn.scrollBackground,!0).attr("fill","none"),o.attr("width",function(t){return t.width}).attr("height",function(t){return t.height}),a.each(function(r){Sr.setClipUrl(e.select(this),pY(t,r))});var s=a.selectAll("."+nY.cn.yColumn).data(function(t){return t.columns},ZR.keyFun);s.enter().append("g").classed(nY.cn.yColumn,!0),s.exit().remove(),s.attr("transform",function(t){return"translate("+t.x+" 0)"}).call(e.behavior.drag().origin(function(r){return _Y(e.select(this),r,-nY.uplift),cY(this),r.calcdata.columnDragInProgress=!0,vY(a.filter(function(t){return r.calcdata.key===t.key}),t),r}).on("drag",function(t){var r=e.select(this),n=function(r){return(t===r?e.event.x:r.x)+r.columnWidth/2};t.x=Math.max(-nY.overdrag,Math.min(t.calcdata.width+nY.overdrag-t.columnWidth,e.event.x)),gY(s).filter(function(e){return e.calcdata.key===t.calcdata.key}).sort(function(t,e){return n(t)-n(e)}).forEach(function(e,r){e.xIndex=r,e.x=t===e?e.x:e.xScale(e)}),s.filter(function(e){return t!==e}).transition().ease(nY.transitionEase).duration(nY.transitionDuration).attr("transform",function(t){return"translate("+t.x+" 0)"}),r.call(hY).attr("transform","translate("+t.x+" -"+nY.uplift+" )")}).on("dragend",function(r){var n=e.select(this),i=r.calcdata;r.x=r.xScale(r),r.calcdata.columnDragInProgress=!1,_Y(n,r,0),function(t,e,r){var n=e.gdColumnsOriginalOrder;e.gdColumns.sort(function(t,e){return r[n.indexOf(t)]-r[n.indexOf(e)]}),e.columnorder=r,t.emit("plotly_restyle")}(t,i,i.columns.map(function(t){return t.xIndex}))})),s.each(function(r){Sr.setClipUrl(e.select(this),dY(t,r))});var l=s.selectAll("."+nY.cn.columnBlock).data(lY.splitToPanels,ZR.keyFun);l.enter().append("g").classed(nY.cn.columnBlock,!0).attr("id",function(t){return t.key}),l.style("cursor",function(t){return t.dragHandle?"ew-resize":t.calcdata.scrollbarState.barWiggleRoom?"ns-resize":"default"});var u=l.filter(MY),c=l.filter(wY);c.call(e.behavior.drag().origin(function(t){return e.event.stopPropagation(),t}).on("drag",TY(t,a,-1)).on("dragend",function(){})),mY(t,a,u,l),mY(t,a,c,l);var h=a.selectAll("."+nY.cn.scrollAreaClip).data(ZR.repeat,ZR.keyFun);h.enter().append("clipPath").classed(nY.cn.scrollAreaClip,!0).attr("id",function(e){return pY(t,e)});var f=h.selectAll("."+nY.cn.scrollAreaClipRect).data(ZR.repeat,ZR.keyFun);f.enter().append("rect").classed(nY.cn.scrollAreaClipRect,!0).attr("x",-nY.overdrag).attr("y",-nY.uplift).attr("fill","none"),f.attr("width",function(t){return t.width+2*nY.overdrag}).attr("height",function(t){return t.height+nY.uplift}),s.selectAll("."+nY.cn.columnBoundary).data(ZR.repeat,ZR.keyFun).enter().append("g").classed(nY.cn.columnBoundary,!0);var p=s.selectAll("."+nY.cn.columnBoundaryClippath).data(ZR.repeat,ZR.keyFun);p.enter().append("clipPath").classed(nY.cn.columnBoundaryClippath,!0),p.attr("id",function(e){return dY(t,e)});var d=p.selectAll("."+nY.cn.columnBoundaryRect).data(ZR.repeat,ZR.keyFun);d.enter().append("rect").classed(nY.cn.columnBoundaryRect,!0).attr("fill","none"),d.attr("width",function(t){return t.columnWidth}).attr("height",function(t){return t.calcdata.height+nY.uplift}),kY(null,c,a)};function pY(t,e){return"clip"+t._fullLayout._uid+"_scrollAreaBottomClip_"+e.key}function dY(t,e){return"clip"+t._fullLayout._uid+"_columnBoundaryClippath_"+e.calcdata.key+"_"+e.specIndex}function gY(t){return[].concat.apply([],t.map(function(t){return t})).map(function(t){return t.__data__})}function vY(t,r,n){var i=t.selectAll("."+nY.cn.scrollbarKit).data(ZR.repeat,ZR.keyFun);i.enter().append("g").classed(nY.cn.scrollbarKit,!0).style("shape-rendering","geometricPrecision"),i.each(function(t){var e=t.scrollbarState;e.totalHeight=function(t){var e=t.rowBlocks;return PY(e,e.length-1)+(e.length?IY(e[e.length-1],1/0):1)}(t),e.scrollableAreaHeight=t.groupHeight-AY(t),e.currentlyVisibleHeight=Math.min(e.totalHeight,e.scrollableAreaHeight),e.ratio=e.currentlyVisibleHeight/e.totalHeight,e.barLength=Math.max(e.ratio*e.currentlyVisibleHeight,nY.goldenRatio*nY.scrollbarWidth),e.barWiggleRoom=e.currentlyVisibleHeight-e.barLength,e.wiggleRoom=Math.max(0,e.totalHeight-e.scrollableAreaHeight),e.topY=0===e.barWiggleRoom?0:t.scrollY/e.wiggleRoom*e.barWiggleRoom,e.bottomY=e.topY+e.barLength,e.dragMultiplier=e.wiggleRoom/e.barWiggleRoom}).attr("transform",function(t){return"translate("+(t.width+nY.scrollbarWidth/2+nY.scrollbarOffset)+" "+AY(t)+")"});var a=i.selectAll("."+nY.cn.scrollbar).data(ZR.repeat,ZR.keyFun);a.enter().append("g").classed(nY.cn.scrollbar,!0);var o=a.selectAll("."+nY.cn.scrollbarSlider).data(ZR.repeat,ZR.keyFun);o.enter().append("g").classed(nY.cn.scrollbarSlider,!0),o.attr("transform",function(t){return"translate(0 "+(t.scrollbarState.topY||0)+")"});var s=o.selectAll("."+nY.cn.scrollbarGlyph).data(ZR.repeat,ZR.keyFun);s.enter().append("line").classed(nY.cn.scrollbarGlyph,!0).attr("stroke","black").attr("stroke-width",nY.scrollbarWidth).attr("stroke-linecap","round").attr("y1",nY.scrollbarWidth/2),s.attr("y2",function(t){return t.scrollbarState.barLength-nY.scrollbarWidth/2}).attr("stroke-opacity",function(t){return t.columnDragInProgress||!t.scrollbarState.barWiggleRoom||n?0:.4}),s.transition().delay(0).duration(0),s.transition().delay(nY.scrollbarHideDelay).duration(nY.scrollbarHideDuration).attr("stroke-opacity",0);var l=a.selectAll("."+nY.cn.scrollbarCaptureZone).data(ZR.repeat,ZR.keyFun);l.enter().append("line").classed(nY.cn.scrollbarCaptureZone,!0).attr("stroke","white").attr("stroke-opacity",.01).attr("stroke-width",nY.scrollbarCaptureWidth).attr("stroke-linecap","butt").attr("y1",0).on("mousedown",function(n){var i=e.event.y,a=this.getBoundingClientRect(),o=n.scrollbarState,s=i-a.top,l=e.scale.linear().domain([0,o.scrollableAreaHeight]).range([0,o.totalHeight]).clamp(!0);o.topY<=s&&s<=o.bottomY||TY(r,t,null,l(s-o.barLength/2))(n)}).call(e.behavior.drag().origin(function(t){return e.event.stopPropagation(),t.scrollbarState.scrollbarScrollInProgress=!0,t}).on("drag",TY(r,t)).on("dragend",function(){})),l.attr("y2",function(t){return t.scrollbarState.scrollableAreaHeight})}function mY(t,r,n,i){var a=function(t){var e=t.selectAll("."+nY.cn.columnCell).data(lY.splitToCells,function(t){return t.keyWithinBlock});return e.enter().append("g").classed(nY.cn.columnCell,!0),e.exit().remove(),e}(function(t){var e=t.selectAll("."+nY.cn.columnCells).data(ZR.repeat,ZR.keyFun);return e.enter().append("g").classed(nY.cn.columnCells,!0),e.exit().remove(),e}(n));!function(t){t.each(function(t,e){var r=t.calcdata.cells.font,n=t.column.specIndex,i={size:bY(r.size,n,e),color:bY(r.color,n,e),family:bY(r.family,n,e)};t.rowNumber=t.key,t.align=bY(t.calcdata.cells.align,n,e),t.cellBorderWidth=bY(t.calcdata.cells.line.width,n,e),t.font=i})}(a),function(t){t.attr("width",function(t){return t.column.columnWidth}).attr("stroke-width",function(t){return t.cellBorderWidth}).each(function(t){var r=e.select(this);Oe.stroke(r,bY(t.calcdata.cells.line.color,t.column.specIndex,t.rowNumber)),Oe.fill(r,bY(t.calcdata.cells.fill.color,t.column.specIndex,t.rowNumber))})}(function(t){var e=t.selectAll("."+nY.cn.cellRect).data(ZR.repeat,function(t){return t.keyWithinBlock});return e.enter().append("rect").classed(nY.cn.cellRect,!0),e}(a));var o=function(t){var r=t.selectAll("."+nY.cn.cellText).data(ZR.repeat,function(t){return t.keyWithinBlock});return r.enter().append("text").classed(nY.cn.cellText,!0).style("cursor",function(){return"auto"}).on("mousedown",function(){e.event.stopPropagation()}),r}(function(t){var e=t.selectAll("."+nY.cn.cellTextHolder).data(ZR.repeat,function(t){return t.keyWithinBlock});return e.enter().append("g").classed(nY.cn.cellTextHolder,!0).style("shape-rendering","geometricPrecision"),e}(a));!function(t){t.each(function(t){Sr.font(e.select(this),t.font)})}(o),yY(o,r,i,t),zY(a)}function yY(t,r,n,i){t.text(function(t){var r=t.column.specIndex,n=t.rowNumber,i=t.value,a="string"==typeof i,o=a&&i.match(/
/i),s=!a||o;t.mayHaveMarkup=a&&i.match(/[<&>]/);var l,u="string"==typeof(l=i)&&l.match(nY.latexCheck);t.latex=u;var c,h,f=u?"":bY(t.calcdata.cells.prefix,r,n)||"",p=u?"":bY(t.calcdata.cells.suffix,r,n)||"",d=u?null:bY(t.calcdata.cells.format,r,n)||null,g=f+(d?e.format(d)(t.value):t.value)+p;if(t.wrappingNeeded=!t.wrapped&&!s&&!u&&(c=xY(g)),t.cellHeightMayIncrease=o||u||t.mayHaveMarkup||(void 0===c?xY(g):c),t.needsConvertToTspans=t.mayHaveMarkup||t.wrappingNeeded||t.latex,t.wrappingNeeded){var v=(" "===nY.wrapSplitCharacter?g.replace(/
i&&n.push(a),i+=l}return n}(i,l,s);1===u.length&&(u[0]===i.length-1?u.unshift(u[0]-1):u.push(u[0]+1)),u[0]%2&&u.reverse(),e.each(function(t,e){t.page=u[e],t.scrollY=l}),e.attr("transform",function(t){return"translate(0 "+(PY(t.rowBlocks,t.page)-t.scrollY)+")"}),t&&(SY(t,r,e,u,n.prevPages,n,0),SY(t,r,e,u,n.prevPages,n,1),vY(r,t))}}function TY(t,r,n,i){return function(a){var o=a.calcdata?a.calcdata:a,s=r.filter(function(t){return o.key===t.key}),l=n||o.scrollbarState.dragMultiplier;o.scrollY=void 0===i?o.scrollY+l*e.event.dy:i;var u=s.selectAll("."+nY.cn.yColumn).selectAll("."+nY.cn.columnBlock).filter(wY);kY(t,u,s)}}function SY(t,e,r,n,i,a,o){n[o]!==i[o]&&(clearTimeout(a.currentRepaint[o]),a.currentRepaint[o]=setTimeout(function(){var a=r.filter(function(t,e){return e===o&&n[e]!==i[e]});mY(t,e,a,r),i[o]=n[o]}))}function EY(t,r,n){return function(){var i=e.select(r.parentNode);i.each(function(t){var e=t.fragments;i.selectAll("tspan.line").each(function(t,r){e[r].width=this.getComputedTextLength()});var r,n,a=e[e.length-1].width,o=e.slice(0,-1),s=[],l=0,u=t.column.columnWidth-2*nY.cellPad;for(t.value="";o.length;)l+(n=(r=o.shift()).width+a)>u&&(t.value+=s.join(nY.wrapSpacer)+nY.lineBreaker,s=[],l=0),s.push(r.text),l+=n;l&&(t.value+=s.join(nY.wrapSpacer)),t.wrapped=!0}),i.selectAll("tspan.line").remove(),yY(i.select("."+nY.cn.cellText),n,t),e.select(r.parentNode.parentNode).call(zY)}}function CY(t,r,n,i,a){return function(){if(!a.settledY){var o=e.select(r.parentNode),s=OY(a),l=a.key-s.firstRowIndex,u=s.rows[l].rowHeight,c=a.cellHeightMayIncrease?r.parentNode.getBoundingClientRect().height+2*nY.cellPad:u,h=Math.max(c,u);h-s.rows[l].rowHeight&&(s.rows[l].rowHeight=h,t.selectAll("."+nY.cn.columnCell).call(zY),kY(null,t.filter(wY),0),vY(n,i,!0)),o.attr("transform",function(){var t=this.parentNode.getBoundingClientRect(),r=e.select(this.parentNode).select("."+nY.cn.cellRect).node().getBoundingClientRect(),n=this.transform.baseVal.consolidate(),i=r.top-t.top+(n?n.matrix.f:nY.cellPad);return"translate("+LY(a,e.select(this.parentNode).select("."+nY.cn.cellTextHolder).node().getBoundingClientRect().width)+" "+i+")"}),a.settledY=!0}}}function LY(t,e){switch(t.align){case"left":return nY.cellPad;case"right":return t.column.columnWidth-(e||0)-nY.cellPad;case"center":return(t.column.columnWidth-(e||0))/2;default:return nY.cellPad}}function zY(t){t.attr("transform",function(t){var e=t.rowBlocks[0].auxiliaryBlocks.reduce(function(t,e){return t+IY(e,1/0)},0);return"translate(0 "+(IY(OY(t),t.key)+e)+")"}).selectAll("."+nY.cn.cellRect).attr("height",function(t){return(e=OY(t),r=t.key,e.rows[r-e.firstRowIndex]).rowHeight;var e,r})}function PY(t,e){for(var r=0,n=e-1;n>=0;n--)r+=DY(t[n]);return r}function IY(t,e){for(var r=0,n=0;n1,p=l.bdPos=l.dPos*(1-i.violingap)*(1-i.violingroupgap)/(f?h:1),d=l.bPos=f?2*l.dPos*((l.num+.5)/h-.5)*(1-i.violingap):0;if(!0!==u.visible||l.empty)e.select(this).remove();else{var g=r[l.valLetter+"axis"],v=r[l.posLetter+"axis"],m="both"===u.side,y=m||"positive"===u.side,x=m||"negative"===u.side,b=u.box&&u.box.visible,_=u.meanline&&u.meanline.visible,w=i._violinScaleGroupStats[u.scalegroup];if(c.selectAll("path.violin").data(ne.identity).enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","violin").each(function(t){var r,n,i,a,o,c,h,f,b=e.select(this),_=t.density,M=_.length,A=t.pos+d,k=v.c2p(A);switch(u.scalemode){case"width":r=w.maxWidth/p;break;case"count":r=w.maxWidth/p*(w.maxCount/t.pts.length)}if(y){for(h=new Array(M),o=0;o0){var d,g,v,m,y,x=t.xa,b=t.ya;"h"===l.orientation?(y=e,d="y",v=b,g="x",m=x):(y=r,d="x",v=x,g="y",m=b);var _=s[t.index];if(y>=_.span[0]&&y<=_.span[1]){var w=ne.extendFlat({},t),M=m.c2p(y,!0),A=HY.getKdeValue(_,l,y),k=HY.getPositionOnKdePath(_,l,M),T=v._offset,S=v._length;w[d+"0"]=k[0],w[d+"1"]=k[1],w[g+"0"]=w[g+"1"]=M,w[g+"Label"]=g+": "+ri.hoverLabelText(m,y)+", "+s[0].t.labels.kde+" "+A.toFixed(3),w.spikeDistance=p[0].spikeDistance;var E=d+"Spike";w[E]=p[0][E],p[0].spikeDistance=void 0,p[0][E]=void 0,f.push(w),(o={stroke:t.color})[d+"1"]=ne.constrain(T+k[0],T,T+S),o[d+"2"]=ne.constrain(T+k[1],T,T+S),o[g+"1"]=o[g+"2"]=m._offset+M}}}-1!==u.indexOf("points")&&(a=_s.hoverOnPoints(t,e,r));var C=i.selectAll(".violinline-"+l.uid).data(o?[0]:[]);return C.enter().append("line").classed("violinline-"+l.uid,!0).attr("stroke-width",1.5),C.exit().remove(),C.attr(o),"closest"===n?a?[a]:f:a?(f.push(a),f):f},selectPoints:zs,moduleType:"trace",name:"violin",basePlotModule:ua,categories:["cartesian","symbols","oriented","box-violin","showLegend"],meta:{}};return Fx.register([os,Bs,Kx,qL,ZL,$L,YF,fp,qG,tX,Wj,tY,DR,dV,Sh,xq,aB,LL,LF,aH,uN,VY,Gu,tV,Ep,UR,iu,aG,uG]),Fx.register([Hi,qx,Yx,WG]),Fx.register([Ul]),Fx}); \ No newline at end of file +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){var t=function(t){var e;return function(r){return e||t(e={exports:{},parent:r},e.exports),e.exports}},e=t(function(t,e){"use strict";var n,i,a,o,s=Object.prototype.isPrototypeOf,l=Object.defineProperty,u={configurable:!0,enumerable:!1,writable:!0,value:void 0};n=function(t,e){if(uq(t),null===e||Cq(e))return t;throw new TypeError("Prototype must be null or an object")},t.exports=(i=function(){var t,e=Object.create(null),r={},n=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__");if(n){try{(t=n.set).call(e,r)}catch(t){}if(Object.getPrototypeOf(e)===r)return{set:t,level:2}}return e.__proto__=r,Object.getPrototypeOf(e)===r?{level:2}:((e={}).__proto__=r,Object.getPrototypeOf(e)===r&&{level:1})}())?(2===i.level?i.set?(o=i.set,a=function(t,e){return o.call(n(t,e),e),t}):a=function(t,e){return n(t,e).__proto__=e,t}:a=function t(e,r){var i;return n(e,r),(i=s.call(t.nullPolyfill,e))&&delete t.nullPolyfill.__proto__,null===r&&(r=t.nullPolyfill),e.__proto__=r,i&&l(t.nullPolyfill,"__proto__",u),e},Object.defineProperty(a,"level",{configurable:!1,enumerable:!1,writable:!1,value:i.level})):null,r({})}),r=t(function(t,r){"use strict";var n,i,a,o,s=Object.create;Tq()||(n=e({})),t.exports=n?1!==n.level?s:(i={},a={},o={configurable:!1,enumerable:!1,writable:!0,value:void 0},Object.getOwnPropertyNames(Object.prototype).forEach(function(t){a[t]="__proto__"!==t?o:{configurable:!0,enumerable:!1,writable:!0,value:void 0}}),Object.defineProperties(i,a),Object.defineProperty(n,"nullPolyfill",{configurable:!1,enumerable:!1,writable:!1,value:i}),function(t,e){return s(null===t?i:t,e)}):s}),n={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"},i={exports:{}};!function(){var t={version:"3.5.17"},e=[].slice,r=function(t){return e.call(t)},n=this.document;function a(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(n)try{r(n.documentElement.childNodes)[0].nodeType}catch(t){r=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),n)try{n.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var s=this.Element.prototype,l=s.setAttribute,u=s.setAttributeNS,c=this.CSSStyleDeclaration.prototype,h=c.setProperty;s.setAttribute=function(t,e){l.call(this,t,e+"")},s.setAttributeNS=function(t,e,r){u.call(this,t,e,r+"")},c.setProperty=function(t,e,r){h.call(this,t,e+"",r)}}function f(t,e){return te?1:t>=e?0:NaN}function p(t){return null===t?NaN:+t}function d(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}t.ascending=f,t.descending=function(t,e){return et?1:e>=t?0:NaN},t.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},t.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},t.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),i=n){r=i=n;break}for(;++an&&(r=n),i1)return o/(l-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var v=g(f);function m(t){return t.length}t.bisectLeft=v.left,t.bisect=t.bisectRight=v.right,t.bisector=function(t){return g(1===t.length?function(e,r){return f(t(e),r)}:t)},t.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,a<2&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],i=new Array(r<0?0:r);e=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r};var y=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,i=[],a=function(t){var e=1;for(;t*e%1;)e*=10;return e}(y(r)),o=-1;if(t*=a,e*=a,(r*=a)<0)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=i.length)return r?r.call(n,a):e?a.sort(e):a;for(var l,u,c,h,f=-1,p=a.length,d=i[s++],g=new b;++f=i.length)return e;var n=[],o=a[r++];return e.forEach(function(e,i){n.push({key:e,values:t(i,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return i.push(t),n},n.sortKeys=function(t){return a[i.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new L;if(t)for(var r=0,n=t.length;r=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(V,"\\$&")};var V=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,U={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function q(t){return U(t,Y),t}var H=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},W=function(t,e){var r=t.matches||t[D(t,"matchesSelector")];return(W=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(H=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,W=Sizzle.matchesSelector),t.selection=function(){return t.select(n.documentElement)};var Y=t.selection.prototype=[];function X(t){return"function"==typeof t?t:function(){return H(t,this)}}function Z(t){return"function"==typeof t?t:function(){return G(t,this)}}Y.select=function(t){var e,r,n,i,a=[];t=X(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),K.hasOwnProperty(r)?{space:K[r],local:t}:t}},Y.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each(Q(r,e[r]));return this}return this.each(Q(e,r))},Y.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,i=-1;if(e=r.classList){for(;++i=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},Y.sort=function(t){t=function(t){arguments.length||(t=f);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e0&&(e=e.slice(0,o));var l=dt.get(e);function u(){var t=this[a];t&&(this.removeEventListener(e,t,t.$),delete this[a])}return l&&(e=l,s=vt),o?n?function(){var t=s(n,r(arguments));u.call(this),this.addEventListener(e,this[a]=t,t.$=i),t._=n}:u:n?O:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var i in this)if(r=i.match(n)){var a=this[i];this.removeEventListener(r[1],a,a.$),delete this[i]}}}t.selection.enter=ht,t.selection.enter.prototype=ft,ft.append=Y.append,ft.empty=Y.empty,ft.node=Y.node,ft.call=Y.call,ft.size=Y.size,ft.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s=n&&(n=e+1);!(o=s[n])&&++n0?1:t<0?-1:0}function zt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function Dt(t){return t>1?0:t<-1?At:Math.acos(t)}function It(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function Ot(t){return((t=Math.exp(t))+1/t)/2}function Rt(t){return(t=Math.sin(t/2))*t}var Bt=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,h=l-a,f=c*c+h*h;if(f0&&(e=e.transition().duration(g)),e.call(w.event)}function S(){u&&u.domain(l.range().map(function(t){return(t-f.x)/f.k}).map(l.invert)),h&&h.domain(c.range().map(function(t){return(t-f.y)/f.k}).map(c.invert))}function C(t){v++||t({type:"zoomstart"})}function E(t){S(),t({type:"zoom",scale:f.k,translate:[f.x,f.y]})}function L(t){--v||(t({type:"zoomend"}),r=null)}function P(){var e=this,r=_.of(e,arguments),n=0,i=t.select(o(e)).on(y,function(){n=1,A(t.mouse(e),a),E(r)}).on(x,function(){i.on(y,null).on(x,null),s(n),L(r)}),a=k(t.mouse(e)),s=xt(e);ss.call(e),C(r)}function z(){var e,r=this,n=_.of(r,arguments),i={},a=0,o=".zoom-"+t.event.changedTouches[0].identifier,l="touchmove"+o,u="touchend"+o,c=[],h=t.select(r),p=xt(r);function d(){var n=t.touches(r);return e=f.k,n.forEach(function(t){t.identifier in i&&(i[t.identifier]=k(t))}),n}function g(){var e=t.event.target;t.select(e).on(l,v).on(u,y),c.push(e);for(var n=t.event.changedTouches,o=0,h=n.length;o1){m=p[0];var x=p[1],b=m[0]-x[0],_=m[1]-x[1];a=b*b+_*_}}function v(){var o,l,u,c,h=t.touches(r);ss.call(r);for(var f=0,p=h.length;f360?t-=360:t<0&&(t+=360),t<60?n+(i-n)*t/60:t<180?i:t<240?n+(i-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(i=r<=.5?r*(1+e):r+e-r*e),new ae(a(t+120),a(t),a(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Xt?e.l:(e=fe((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}qt.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new Ut(this.h,this.s,this.l/t)},qt.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new Ut(this.h,this.s,t*this.l)},qt.rgb=function(){return Ht(this.h,this.s,this.l)},t.hcl=Gt;var Wt=Gt.prototype=new Vt;function Yt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Xt(r,Math.cos(t*=Et)*e,Math.sin(t)*e)}function Xt(t,e,r){return this instanceof Xt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Xt?new Xt(t.l,t.a,t.b):t instanceof Gt?Yt(t.h,t.c,t.l):fe((t=ae(t)).r,t.g,t.b):new Xt(t,e,r)}Wt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Zt*(arguments.length?t:1)))},Wt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Zt*(arguments.length?t:1)))},Wt.rgb=function(){return Yt(this.h,this.c,this.l).rgb()},t.lab=Xt;var Zt=18,Jt=.95047,Kt=1,Qt=1.08883,$t=Xt.prototype=new Vt;function te(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return new ae(ie(3.2404542*(i=re(i)*Jt)-1.5371385*(n=re(n)*Kt)-.4985314*(a=re(a)*Qt)),ie(-.969266*i+1.8760108*n+.041556*a),ie(.0556434*i-.2040259*n+1.0572252*a))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Lt,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ie(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ae(t,e,r){return this instanceof ae?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ae?new ae(t.r,t.g,t.b):ce(""+t,ae,Ht):new ae(t,e,r)}function oe(t){return new ae(t>>16,t>>8&255,255&t)}function se(t){return oe(t)+""}$t.brighter=function(t){return new Xt(Math.min(100,this.l+Zt*(arguments.length?t:1)),this.a,this.b)},$t.darker=function(t){return new Xt(Math.max(0,this.l-Zt*(arguments.length?t:1)),this.a,this.b)},$t.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ae;var le=ae.prototype=new Vt;function ue(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ce(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(de(i[0]),de(i[1]),de(i[2]))}return(a=ge.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o|=o>>4,s=240&a,s|=s>>4,l=15&a,l|=l<<4):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function he(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=l<.5?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(e0&&l<1?0:n),new Ut(n,i,l)}function fe(t,e,r){var n=ne((.4124564*(t=pe(t))+.3575761*(e=pe(e))+.1804375*(r=pe(r)))/Jt),i=ne((.2126729*t+.7151522*e+.072175*r)/Kt);return Xt(116*i-16,500*(n-i),200*(i-ne((.0193339*t+.119192*e+.9503041*r)/Qt)))}function pe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function de(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}le.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&e=200&&e<300||304===e){try{t=i.call(o,u)}catch(t){return void s.error.call(o,t)}s.load.call(o,t)}else s.error.call(o,u)}return!this.XDomainRequest||"withCredentials"in u||!/^(http(s)?:)?\/\//.test(e)||(u=new XDomainRequest),"onload"in u?u.onload=u.onerror=h:u.onreadystatechange=function(){u.readyState>3&&h()},u.onprogress=function(e){var r=t.event;t.event=e;try{s.progress.call(o,u)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?l[t]:(null==e?delete l[t]:l[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(n=null==t?null:t+"",o):n},o.responseType=function(t){return arguments.length?(c=t,o):c},o.response=function(t){return i=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(r(arguments)))}}),o.send=function(t,r,i){if(2===arguments.length&&"function"==typeof r&&(i=r,r=null),u.open(t,e,!0),null==n||"accept"in l||(l.accept=n+",*/*"),u.setRequestHeader)for(var a in l)u.setRequestHeader(a,l[a]);return null!=n&&u.overrideMimeType&&u.overrideMimeType(n),null!=c&&(u.responseType=c),null!=i&&o.on("error",i).on("load",function(t){i(null,t)}),s.beforesend.call(o,u),u.send(null==r?null:r),o},o.abort=function(){return u.abort(),o},t.rebind(o,s,"on"),null==a?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(a))}ge.forEach(function(t,e){ge.set(t,oe(e))}),t.functor=ve,t.xhr=me(P),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function i(t,r,n){arguments.length<3&&(n=r,r=null);var i=ye(t,e,null==r?a:o(r),n);return i.row=function(t){return arguments.length?i.response(null==(r=t)?a:o(t)):r},i}function a(t){return i.parse(t.responseText)}function o(t){return function(e){return i.parse(e.responseText,t)}}function s(e){return e.map(l).join(t)}function l(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return i.parse=function(t,e){var r;return i.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(i(t),r)}:i})},i.parseRows=function(t,e){var r,i,a={},o={},s=[],l=t.length,u=0,c=0;function h(){if(u>=l)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Ae,e)),_e=0):(_e=1,ke(Ae))}function Te(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Se(){for(var t,e=xe,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ce(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Ee[8+n/3]};var Le=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pe=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Ce(e,r))).toFixed(Math.max(0,Math.min(20,Ce(e*(1+1e-15),r))))}});function ze(t){return t+""}var De=t.time={},Ie=Date;function Oe(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Oe.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(){Re.setUTCDate.apply(this._,arguments)},setDay:function(){Re.setUTCDay.apply(this._,arguments)},setFullYear:function(){Re.setUTCFullYear.apply(this._,arguments)},setHours:function(){Re.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Re.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Re.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Re.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Re.setUTCSeconds.apply(this._,arguments)},setTime:function(){Re.setTime.apply(this._,arguments)}};var Re=Date.prototype;function Be(t,e,r){function n(e){var r=t(e),n=a(r,1);return e-r1)for(;o68?1900:2e3),r+i[0].length):-1}function Je(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Ke(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function Qe(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function $e(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){je.lastIndex=0;var n=je.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ir(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=y(e)/60|0,i=y(e)%60;return r+Ue(n,"0",2)+Ue(i,"0",2)}function ar(t,e,r){Ve.lastIndex=0;var n=Ve.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(r-=s,r+s)),!((l+=s+1)>e));)s=i[o=(o+1)%i.length];return a.reverse().join(n)}:P;return function(e){var n=Le.exec(e),i=n[1]||" ",s=n[2]||">",l=n[3]||"-",u=n[4]||"",c=n[5],h=+n[6],f=n[7],p=n[8],d=n[9],g=1,v="",m="",y=!1,x=!0;switch(p&&(p=+p.substring(1)),(c||"0"===i&&"="===s)&&(c=i="0",s="="),d){case"n":f=!0,d="g";break;case"%":g=100,m="%",d="f";break;case"p":g=100,m="%",d="r";break;case"b":case"o":case"x":case"X":"#"===u&&(v="0"+d.toLowerCase());case"c":x=!1;case"d":y=!0,p=0;break;case"s":g=-1,d="r"}"$"===u&&(v=a[0],m=a[1]),"r"!=d||p||(d="g"),null!=p&&("g"==d?p=Math.max(1,Math.min(21,p)):"e"!=d&&"f"!=d||(p=Math.max(0,Math.min(20,p)))),d=Pe.get(d)||ze;var b=c&&f;return function(e){var n=m;if(y&&e%1)return"";var a=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===l?"":l;if(g<0){var u=t.formatPrefix(e,p);e=u.scale(e),n=u.symbol+m}else e*=g;var _,w,k=(e=d(e,p)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=r+e.substring(k+1);!c&&f&&(_=o(_,1/0));var A=v.length+_.length+w.length+(b?0:a.length),T=A"===s?T+a+e:"^"===s?T.substring(0,A>>=1)+a+e+T.substring(A):a+(b?e:T+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,i=e.time,a=e.periods,o=e.days,s=e.shortDays,l=e.months,u=e.shortMonths;function c(t){var e=t.length;function r(r){for(var n,i,a,o=[],s=-1,l=0;++s=u)return-1;if(37===(i=e.charCodeAt(s++))){if(o=e.charAt(s++),!(a=w[o in Ne?e.charAt(s++):o])||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}c.utc=function(t){var e=c(t);function r(t){try{var r=new(Ie=Oe);return r._=t,e(r)}finally{Ie=Date}}return r.parse=function(t){try{Ie=Oe;var r=e.parse(t);return r&&r._}finally{Ie=Date}},r.toString=e.toString,r},c.multi=c.utc.multi=or;var f=t.map(),p=qe(o),d=He(o),g=qe(s),v=He(s),m=qe(l),y=He(l),x=qe(u),b=He(u);a.forEach(function(t,e){f.set(t.toLowerCase(),e)});var _={a:function(t){return s[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return u[t.getMonth()]},B:function(t){return l[t.getMonth()]},c:c(r),d:function(t,e){return Ue(t.getDate(),e,2)},e:function(t,e){return Ue(t.getDate(),e,2)},H:function(t,e){return Ue(t.getHours(),e,2)},I:function(t,e){return Ue(t.getHours()%12||12,e,2)},j:function(t,e){return Ue(1+De.dayOfYear(t),e,3)},L:function(t,e){return Ue(t.getMilliseconds(),e,3)},m:function(t,e){return Ue(t.getMonth()+1,e,2)},M:function(t,e){return Ue(t.getMinutes(),e,2)},p:function(t){return a[+(t.getHours()>=12)]},S:function(t,e){return Ue(t.getSeconds(),e,2)},U:function(t,e){return Ue(De.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ue(De.mondayOfYear(t),e,2)},x:c(n),X:c(i),y:function(t,e){return Ue(t.getFullYear()%100,e,2)},Y:function(t,e){return Ue(t.getFullYear()%1e4,e,4)},Z:ir,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=v.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){p.lastIndex=0;var n=p.exec(e.slice(r));return n?(t.w=d.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){m.lastIndex=0;var n=m.exec(e.slice(r));return n?(t.m=y.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return h(t,_.c.toString(),e,r)},d:Qe,e:Qe,H:tr,I:tr,j:$e,L:nr,m:Ke,M:er,p:function(t,e,r){var n=f.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:We,w:Ge,W:Ye,x:function(t,e,r){return h(t,_.x.toString(),e,r)},X:function(t,e,r){return h(t,_.X.toString(),e,r)},y:Ze,Y:Xe,Z:Je,"%":ar};return c}(e)}};var sr=t.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"]});function lr(){}t.format=sr.numberFormat,t.geo={},lr.prototype={s:0,t:0,add:function(t){cr(t,this.t,ur),cr(ur.s,this.s,this),this.s?this.t+=ur.t:this.s=ur.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ur=new lr;function cr(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function hr(t,e){t&&pr.hasOwnProperty(t.type)&&pr[t.type](t,e)}t.geo.stream=function(t,e){t&&fr.hasOwnProperty(t.type)?fr[t.type](t,e):hr(t,e)};var fr={Feature:function(t,e){hr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n=0?1:-1,s=o*a,l=Math.cos(e),u=Math.sin(e),c=i*u,h=n*l+c*Math.cos(s),f=c*o*Math.sin(s);Cr.add(Math.atan2(f,h)),r=t,n=l,i=u}Er.point=function(o,s){Er.point=a,r=(t=o)*Et,n=Math.cos(s=(e=s)*Et/2+At/4),i=Math.sin(s)},Er.lineEnd=function(){a(t,e)}}function Pr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function zr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Dr(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Ir(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Or(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Rr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Br(t){return[Math.atan2(t[1],t[0]),It(t[2])]}function Fr(t,e){return y(t[0]-e[0])kt?i=90:u<-kt&&(r=-90),h[0]=e,h[1]=n}};function p(t,a){c.push(h=[e=t,n=t]),ai&&(i=a)}function d(t,o){var s=Pr([t*Et,o*Et]);if(l){var u=Dr(l,s),c=Dr([u[1],-u[0],0],u);Rr(c),c=Br(c);var h=t-a,f=h>0?1:-1,d=c[0]*Lt*f,g=y(h)>180;if(g^(f*ai&&(i=v);else if(g^(f*a<(d=(d+360)%360-180)&&di&&(i=o);g?t_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(tn&&(n=t)):t>a?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else p(t,o);l=s,a=t}function g(){f.point=d}function v(){h[0]=e,h[1]=n,f.point=p,l=null}function m(t,e){if(l){var r=t-a;u+=y(r)>180?r+(r>0?360:-360):r}else o=t,s=e;Er.point(t,e),d(t,e)}function x(){Er.lineStart()}function b(){m(o,s),Er.lineEnd(),y(u)>kt&&(e=-(n=180)),h[0]=e,h[1]=n,l=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function k(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t_(g[0],g[1])&&(g[1]=p[1]),_(p[0],g[1])>_(g[0],g[1])&&(g[0]=p[0])):s.push(g=p);for(var l,u,p,d=-1/0,g=(o=0,s[u=s.length-1]);o<=u;g=p,++o)p=s[o],(l=_(g[1],p[0]))>d&&(d=l,e=p[0],n=g[1])}return c=h=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,i]]}}(),t.geo.centroid=function(e){mr=yr=xr=br=_r=wr=kr=Mr=Ar=Tr=Sr=0,t.geo.stream(e,Nr);var r=Ar,n=Tr,i=Sr,a=r*r+n*n+i*i;return a=0;--s)i.point((h=c[s])[0],h[1]);else n(p.x,p.p.x,-1,i);p=p.p}c=(p=p.o).z,d=!d}while(!p.v);i.lineEnd()}}}function Xr(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n=0?1:-1,k=w*_,M=k>At,A=d*x;if(Cr.add(Math.atan2(A*w*Math.sin(k),g*b+A*Math.cos(k))),a+=M?_+w*Tt:_,M^f>=r^m>=r){var T=Dr(Pr(h),Pr(t));Rr(T);var S=Dr(i,T);Rr(S);var C=(M^_>=0?-1:1)*It(S[2]);(n>C||n===C&&(T[0]||T[1]))&&(o+=M^_>=0?1:-1)}if(!v++)break;f=m,d=x,g=b,h=t}}return(a<-kt||a0){for(x||(o.polygonStart(),x=!0),o.lineStart();++a1&&2&e&&r.push(r.pop().concat(r.shift())),s.push(r.filter(Kr))}return c}}function Kr(t){return t.length>1}function Qr(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:O,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function $r(t,e){return((t=t.x)[0]<0?t[1]-Ct-kt:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-kt:Ct-e[1])}var tn=Jr(Wr,function(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?At:-At,l=y(a-r);y(l-At)0?Ct:-Ct),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=At&&(y(r-i)kt?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var i;if(null==t)i=r*Ct,n.point(-At,i),n.point(0,i),n.point(At,i),n.point(At,0),n.point(At,-i),n.point(0,-i),n.point(-At,-i),n.point(-At,0),n.point(-At,i);else if(y(t[0]-e[0])>kt){var a=t[0]0)){if(a/=f,f<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=r-l,f||!(a<0)){if(a/=f,f<0){if(a>h)return;a>c&&(c=a)}else if(f>0){if(a0)){if(a/=p,p<0){if(a0){if(a>h)return;a>c&&(c=a)}if(a=n-u,p||!(a<0)){if(a/=p,p<0){if(a>h)return;a>c&&(c=a)}else if(p>0){if(a0&&(i.a={x:l+c*f,y:u+c*p}),h<1&&(i.b={x:l+h*f,y:u+h*p}),i}}}}}}var rn=1e9;function nn(e,r,n,i){return function(l){var u,c,h,f,p,d,g,v,m,y,x,b=l,_=Qr(),w=en(e,r,n,i),k={point:T,lineStart:function(){k.point=S,c&&c.push(h=[]);y=!0,m=!1,g=v=NaN},lineEnd:function(){u&&(S(f,p),d&&m&&_.rejoin(),u.push(_.buffer()));k.point=T,m&&l.lineEnd()},polygonStart:function(){l=_,u=[],c=[],x=!0},polygonEnd:function(){l=b,u=t.merge(u);var r=function(t){for(var e=0,r=c.length,n=t[1],i=0;in&&zt(u,a,t)>0&&++e:a[1]<=n&&zt(u,a,t)<0&&--e,u=a;return 0!==e}([e,i]),n=x&&r,a=u.length;(n||a)&&(l.polygonStart(),n&&(l.lineStart(),M(null,null,1,l),l.lineEnd()),a&&Yr(u,o,r,M,l),l.polygonEnd()),u=c=h=null}};function M(t,o,l,u){var c=0,h=0;if(null==t||(c=a(t,l))!==(h=a(o,l))||s(t,o)<0^l>0)do{u.point(0===c||3===c?e:n,c>1?i:r)}while((c=(c+l+4)%4)!==h);else u.point(o[0],o[1])}function A(t,a){return e<=t&&t<=n&&r<=a&&a<=i}function T(t,e){A(t,e)&&l.point(t,e)}function S(t,e){var r=A(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(c&&h.push([t,e]),y)f=t,p=e,d=r,y=!1,r&&(l.lineStart(),l.point(t,e));else if(r&&m)l.point(t,e);else{var n={a:{x:g,y:v},b:{x:t,y:e}};w(n)?(m||(l.lineStart(),l.point(n.a.x,n.a.y)),l.point(n.b.x,n.b.y),r||l.lineEnd(),x=!1):r&&(l.lineStart(),l.point(t,e),x=!1)}g=t,v=e,m=r}return k};function a(t,i){return y(t[0]-e)0?0:3:y(t[0]-n)0?2:1:y(t[1]-r)0?1:0:i>0?3:2}function o(t,e){return s(t.x,e.x)}function s(t,e){var r=a(t,1),n=a(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=At/3,n=Sn(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*At/180,r=t[1]*At/180):[e/At*180,r/At*180]},i}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,i=1+r*(2*n-r),a=Math.sqrt(i)/n;function o(t,e){var r=Math.sqrt(i-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),a-r*Math.cos(t)]}return o.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,It((i-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),(i=a(t)).valid=!0,i},extent:function(s){return arguments.length?(a=nn(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,i,a=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};function u(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}return u.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&i<.234&&n>=-.425&&n<-.214?o:i>=.166&&i<.234&&n>=-.214&&n<-.115?s:a).invert(t)},u.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},u.precision=function(t){return arguments.length?(a.precision(t),o.precision(t),s.precision(t),u):a.precision()},u.scale=function(t){return arguments.length?(a.scale(t),o.scale(.35*t),s.scale(t),u.translate(a.translate())):a.scale()},u.translate=function(t){if(!arguments.length)return a.translate();var e=a.scale(),c=+t[0],h=+t[1];return r=a.translate(t).clipExtent([[c-.455*e,h-.238*e],[c+.455*e,h+.238*e]]).stream(l).point,n=o.translate([c-.307*e,h+.201*e]).clipExtent([[c-.425*e+kt,h+.12*e+kt],[c-.214*e-kt,h+.234*e-kt]]).stream(l).point,i=s.translate([c-.205*e,h+.212*e]).clipExtent([[c-.214*e+kt,h+.166*e+kt],[c-.115*e-kt,h+.234*e-kt]]).stream(l).point,u},u.scale(1070)};var sn,ln,un,cn,hn,fn,pn={point:O,lineStart:O,lineEnd:O,polygonStart:function(){ln=0,pn.lineStart=dn},polygonEnd:function(){pn.lineStart=pn.lineEnd=pn.point=O,sn+=y(ln/2)}};function dn(){var t,e,r,n;function i(t,e){ln+=n*t-r*e,r=t,n=e}pn.point=function(a,o){pn.point=i,t=r=a,e=n=o},pn.lineEnd=function(){i(t,e)}}var gn={point:function(t,e){thn&&(hn=t);efn&&(fn=e)},lineStart:O,lineEnd:O,polygonStart:O,polygonEnd:O};function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,yn={point:xn,lineStart:bn,lineEnd:_n,polygonStart:function(){yn.lineStart=wn},polygonEnd:function(){yn.point=xn,yn.lineStart=bn,yn.lineEnd=_n}};function xn(t,e){xr+=t,br+=e,++_r}function bn(){var t,e;function r(r,n){var i=r-t,a=n-e,o=Math.sqrt(i*i+a*a);wr+=o*(t+r)/2,kr+=o*(e+n)/2,Mr+=o,xn(t=r,e=n)}yn.point=function(n,i){yn.point=r,xn(t=n,e=i)}}function _n(){yn.point=xn}function wn(){var t,e,r,n;function i(t,e){var i=t-r,a=e-n,o=Math.sqrt(i*i+a*a);wr+=o*(r+t)/2,kr+=o*(n+e)/2,Mr+=o,Ar+=(o=n*t-r*e)*(r+t),Tr+=o*(n+e),Sr+=3*o,xn(r=t,n=e)}yn.point=function(a,o){yn.point=i,xn(t=r=a,e=n=o)},yn.lineEnd=function(){i(t,e)}}function kn(t){var e=.5,r=Math.cos(30*Et),n=16;function i(e){return(n?function(e){var r,i,o,s,l,u,c,h,f,p,d,g,v={point:m,lineStart:y,lineEnd:b,polygonStart:function(){e.polygonStart(),v.lineStart=_},polygonEnd:function(){e.polygonEnd(),v.lineStart=y}};function m(r,n){r=t(r,n),e.point(r[0],r[1])}function y(){h=NaN,v.point=x,e.lineStart()}function x(r,i){var o=Pr([r,i]),s=t(r,i);a(h,f,c,p,d,g,h=s[0],f=s[1],c=r,p=o[0],d=o[1],g=o[2],n,e),e.point(h,f)}function b(){v.point=m,e.lineEnd()}function _(){y(),v.point=w,v.lineEnd=k}function w(t,e){x(r=t,e),i=h,o=f,s=p,l=d,u=g,v.point=x}function k(){a(h,f,c,p,d,g,i,o,r,s,l,u,n,e),v.lineEnd=b,b()}return v}:function(e){return An(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function a(n,i,o,s,l,u,c,h,f,p,d,g,v,m){var x=c-n,b=h-i,_=x*x+b*b;if(_>4*e&&v--){var w=s+p,k=l+d,M=u+g,A=Math.sqrt(w*w+k*k+M*M),T=Math.asin(M/=A),S=y(y(M)-1)e||y((x*P+b*z)/_-.5)>.3||s*p+l*d+u*g0&&16,i):Math.sqrt(e)},i}function Mn(t){this.stream=t}function An(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Tn(t){return Sn(function(){return t})()}function Sn(e){var r,n,i,a,o,s,l=kn(function(t,e){return[(t=r(t,e))[0]*u+a,o-t[1]*u]}),u=150,c=480,h=250,f=0,p=0,d=0,g=0,v=0,m=tn,x=P,b=null,_=null;function w(t){return[(t=i(t[0]*Et,t[1]*Et))[0]*u+a,o-t[1]*u]}function k(t){return(t=i.invert((t[0]-a)/u,(o-t[1])/u))&&[t[0]*Lt,t[1]*Lt]}function M(){i=Gr(n=Pn(d,g,v),r);var t=r(f,p);return a=c-t[0]*u,o=h+t[1]*u,A()}function A(){return s&&(s.valid=!1,s=null),w}return w.stream=function(t){return s&&(s.valid=!1),(s=Cn(m(n,l(x(t))))).valid=!0,s},w.clipAngle=function(t){return arguments.length?(m=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=y(e)>kt;return Jr(i,function(t){var e,s,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(h,f){var p,d=[h,f],g=i(h,f),v=r?g?0:o(h,f):g?o(h+(h<0?At:-At),f):0;if(!e&&(u=l=g)&&t.lineStart(),g!==l&&(p=a(e,d),(Fr(e,p)||Fr(d,p))&&(d[0]+=kt,d[1]+=kt,g=i(d[0],d[1]))),g!==l)c=0,g?(t.lineStart(),p=a(d,e),t.point(p[0],p[1])):(p=a(e,d),t.point(p[0],p[1]),t.lineEnd()),e=p;else if(n&&e&&r^g){var m;v&s||!(m=a(d,e,!0))||(c=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||e&&Fr(e,d)||t.point(d[0],d[1]),e=d,l=g,s=v},lineEnd:function(){l&&t.lineEnd(),e=null},clean:function(){return c|(u&&l)<<1}}},On(t,6*Et),r?[0,-t]:[-At,t-At]);function i(t,r){return Math.cos(t)*Math.cos(r)>e}function a(t,r,n){var i=[1,0,0],a=Dr(Pr(t),Pr(r)),o=zr(a,a),s=a[0],l=o-s*s;if(!l)return!n&&t;var u=e*o/l,c=-e*s/l,h=Dr(i,a),f=Or(i,u);Ir(f,Or(a,c));var p=h,d=zr(f,p),g=zr(p,p),v=d*d-g*(zr(f,f)-1);if(!(v<0)){var m=Math.sqrt(v),x=Or(p,(-d-m)/g);if(Ir(x,f),x=Br(x),!n)return x;var b,_=t[0],w=r[0],k=t[1],M=r[1];w<_&&(b=_,_=w,w=b);var A=w-_,T=y(A-At)0^x[1]<(y(x[0]-_)At^(_<=x[0]&&x[0]<=w)){var S=Or(p,(-d+m)/g);return Ir(S,f),[x,Br(S)]}}}function o(e,n){var i=r?t:At-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}}((b=+t)*Et),A()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):P,A()):_},w.scale=function(t){return arguments.length?(u=+t,M()):u},w.translate=function(t){return arguments.length?(c=+t[0],h=+t[1],M()):[c,h]},w.center=function(t){return arguments.length?(f=t[0]%360*Et,p=t[1]%360*Et,M()):[f*Lt,p*Lt]},w.rotate=function(t){return arguments.length?(d=t[0]%360*Et,g=t[1]%360*Et,v=t.length>2?t[2]%360*Et:0,M()):[d*Lt,g*Lt,v*Lt]},t.rebind(w,l,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&k,M()}}function Cn(t){return An(t,function(e,r){t.point(e*Et,r*Et)})}function En(t,e){return[t,e]}function Ln(t,e){return[t>At?t-Tt:t<-At?t+Tt:t,e]}function Pn(t,e,r){return t?e||r?Gr(Dn(t),In(e,r)):Dn(t):e||r?In(e,r):Ln}function zn(t){return function(e,r){return[(e+=t)>At?e-Tt:e<-At?e+Tt:e,r]}}function Dn(t){var e=zn(t);return e.invert=zn(-t),e}function In(t,e){var r=Math.cos(t),n=Math.sin(t),i=Math.cos(e),a=Math.sin(e);function o(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*r+s*n;return[Math.atan2(l*i-c*a,s*r-u*n),It(c*i+l*a)]}return o.invert=function(t,e){var o=Math.cos(e),s=Math.cos(t)*o,l=Math.sin(t)*o,u=Math.sin(e),c=u*i-l*a;return[Math.atan2(l*i+u*a,s*r+c*n),It(c*r-s*n)]},o}function On(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=Rn(r,i),a=Rn(r,a),(o>0?ia)&&(i+=o*Tt)):(i=t+o*Tt,a=t-.5*l);for(var u,c=i;o>0?c>a:c2?t[2]*Et:0),e.invert=function(e){return(e=t.invert(e[0]*Et,e[1]*Et))[0]*=Lt,e[1]*=Lt,e},e},Ln.invert=En,t.geo.circle=function(){var t,e,r=[0,0],n=6;function i(){var t="function"==typeof r?r.apply(this,arguments):r,n=Pn(-t[0]*Et,-t[1]*Et,0).invert,i=[];return e(null,null,1,{point:function(t,e){i.push(t=n(t,e)),t[0]*=Lt,t[1]*=Lt}}),{type:"Polygon",coordinates:[i]}}return i.origin=function(t){return arguments.length?(r=t,i):r},i.angle=function(r){return arguments.length?(e=On((t=+r)*Et,n*Et),i):t},i.precision=function(r){return arguments.length?(e=On(t*Et,(n=+r)*Et),i):n},i.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Et,i=t[1]*Et,a=e[1]*Et,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((r=h*o)*r+(r=u*c-l*h*s)*r),l*c+u*h*s)},t.geo.graticule=function(){var e,r,n,i,a,o,s,l,u,c,h,f,p=10,d=p,g=90,v=360,m=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(i/g)*g,n,g).map(h).concat(t.range(Math.ceil(l/v)*v,s,v).map(f)).concat(t.range(Math.ceil(r/p)*p,e,p).filter(function(t){return y(t%g)>kt}).map(u)).concat(t.range(Math.ceil(o/d)*d,a,d).filter(function(t){return y(t%v)>kt}).map(c))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(f(s).slice(1),h(n).reverse().slice(1),f(l).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(i=+t[0][0],n=+t[1][0],l=+t[0][1],s=+t[1][1],i>n&&(t=i,i=n,n=t),l>s&&(t=l,l=s,s=t),x.precision(m)):[[i,l],[n,s]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),o>a&&(t=o,o=a,a=t),x.precision(m)):[[r,o],[e,a]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],v=+t[1],x):[g,v]},x.minorStep=function(t){return arguments.length?(p=+t[0],d=+t[1],x):[p,d]},x.precision=function(t){return arguments.length?(m=+t,u=Bn(o,a,90),c=Fn(r,e,m),h=Bn(l,s,90),f=Fn(i,n,m),x):m},x.majorExtent([[-180,-90+kt],[180,90-kt]]).minorExtent([[-180,-80-kt],[180,80+kt]])},t.geo.greatArc=function(){var e,r,n=Nn,i=jn;function a(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}return a.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},a.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,a):n},a.target=function(t){return arguments.length?(i=t,r="function"==typeof t?null:t,a):i},a.precision=function(){return arguments.length?a:0},a},t.geo.interpolate=function(t,e){return r=t[0]*Et,n=t[1]*Et,i=e[0]*Et,a=e[1]*Et,o=Math.cos(n),s=Math.sin(n),l=Math.cos(a),u=Math.sin(a),c=o*Math.cos(r),h=o*Math.sin(r),f=l*Math.cos(i),p=l*Math.sin(i),d=2*Math.asin(Math.sqrt(Rt(a-n)+o*l*Rt(i-r))),g=1/Math.sin(d),(v=d?function(t){var e=Math.sin(t*=d)*g,r=Math.sin(d-t)*g,n=r*c+e*f,i=r*h+e*p,a=r*s+e*u;return[Math.atan2(i,n)*Lt,Math.atan2(a,Math.sqrt(n*n+i*i))*Lt]}:function(){return[r*Lt,n*Lt]}).distance=d,v;var r,n,i,a,o,s,l,u,c,h,f,p,d,g,v},t.geo.length=function(e){return mn=0,t.geo.stream(e,Vn),mn};var Vn={sphere:O,point:O,lineStart:function(){var t,e,r;function n(n,i){var a=Math.sin(i*=Et),o=Math.cos(i),s=y((n*=Et)-t),l=Math.cos(s);mn+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=r*a-e*o*l)*s),e*a+r*o*l),t=n,e=a,r=o}Vn.point=function(i,a){t=i*Et,e=Math.sin(a*=Et),r=Math.cos(a),Vn.point=n},Vn.lineEnd=function(){Vn.point=Vn.lineEnd=O}},lineEnd:O,polygonStart:O,polygonEnd:O};function Un(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}var qn=Un(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return Tn(qn)}).raw=qn;var Hn=Un(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},P);function Gn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(At/4+t/2)},i=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),a=r*Math.pow(n(t),i)/i;if(!i)return Xn;function o(t,e){a>0?e<-Ct+kt&&(e=-Ct+kt):e>Ct-kt&&(e=Ct-kt);var r=a/Math.pow(n(e),i);return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}return o.invert=function(t,e){var r=a-e,n=Pt(i)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/i,2*Math.atan(Math.pow(a/n,1/i))-Ct]},o}function Wn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),i=r/n+t;if(y(n)1&&zt(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function ri(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return Tn(Kn)}).raw=Kn,Qn.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(t.geo.transverseMercator=function(){var t=Zn(Qn),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=Qn,t.geom={},t.geom.hull=function(t){var e=$n,r=ti;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,i=ve(e),a=ve(r),o=t.length,s=[],l=[];for(n=0;n=0;--n)p.push(t[s[u[n]][2]]);for(n=+h;nkt)s=s.L;else{if(!((i=a-xi(s,o))>kt)){n>-kt?(e=s.P,r=s):i>-kt?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=di(t);if(ui.insert(e,l),e||r){if(e===r)return ki(e),r=di(e.site),ui.insert(l,r),l.edge=r.edge=Ti(e.site,l.site),wi(e),void wi(r);if(r){ki(e),ki(r);var u=e.site,c=u.x,h=u.y,f=t.x-c,p=t.y-h,d=r.site,g=d.x-c,v=d.y-h,m=2*(f*v-p*g),y=f*f+p*p,x=g*g+v*v,b={x:(v*y-p*x)/m+c,y:(f*x-g*y)/m+h};Si(r.edge,u,d,b),l.edge=Ti(u,t,null,b),r.edge=Ti(t,d,null,b),wi(e),wi(r)}else l.edge=Ti(e.site,l.site)}}function yi(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-1/0;var s=(r=o.site).x,l=r.y,u=l-e;if(!u)return s;var c=s-n,h=1/a-1/u,f=c/u;return h?(-f+Math.sqrt(f*f-2*h*(c*c/(-2*u)-l+u/2+i-a/2)))/h+n:(n+s)/2}function xi(t,e){var r=t.N;if(r)return yi(r,e);var n=t.site;return n.y===e?n.x:1/0}function bi(t){this.site=t,this.edges=[]}function _i(t,e){return e.angle-t.angle}function wi(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,u=n.y-s,c=a.x-o,h=2*(l*(v=a.y-s)-u*c);if(!(h>=-Mt)){var f=l*l+u*u,p=c*c+v*v,d=(v*f-u*p)/h,g=(l*p-c*f)/h,v=g+s,m=pi.pop()||new function(){Li(this),this.x=this.y=this.arc=this.site=this.cy=null};m.arc=t,m.site=i,m.x=d+o,m.y=v+Math.sqrt(d*d+g*g),m.cy=v,t.circle=m;for(var y=null,x=hi._;x;)if(m.y=s)return;if(f>d){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.y1)if(f>d){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.y=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xkt||y(i-r)>kt)&&(s.splice(o,0,new Ci((m=a.site,x=c,b=y(n-h)kt?{x:h,y:y(e-h)kt?{x:y(r-d)kt?{x:f,y:y(e-f)kt?{x:y(r-p)=r&&u.x<=i&&u.y>=n&&u.y<=o?[[r,o],[i,o],[i,n],[r,n]]:[]).point=t[s]}),e}function s(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/kt)*kt,y:Math.round(i(t,e)/kt)*kt,i:e}})}return o.links=function(t){return Ii(s(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Ii(s(t)).cells.forEach(function(r,n){for(var i,a,o,s,l=r.site,u=r.edges.sort(_i),c=-1,h=u.length,f=u[h-1].edge,p=f.l===l?f.r:f.l;++ca&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:Vi(r,n)})),a=Hi.lastIndex;return ag&&(g=l.x),l.y>v&&(v=l.y),u.push(l.x),c.push(l.y);else for(h=0;hg&&(g=b),_>v&&(v=_),u.push(b),c.push(_)}var w=g-p,k=v-d;function M(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,u=t.y;if(null!=l)if(y(l-r)+y(u-n)<.01)A(t,e,r,n,i,a,o,s);else{var c=t.point;t.x=t.y=t.point=null,A(t,c,l,u,i,a,o,s),A(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else A(t,e,r,n,i,a,o,s)}function A(t,e,r,n,i,a,o,s){var l=.5*(i+o),u=.5*(a+s),c=r>=l,h=n>=u,f=h<<1|c;t.leaf=!1,t=t.nodes[f]||(t.nodes[f]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(T,t,+m(t,++h),+x(t,h),p,d,g,v)}}),c?i=l:o=l,h?a=u:s=u,M(t,e,r,n,i,a,o,s)}w>k?v=d+w:g=p+k;var T={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(T,t,+m(t,++h),+x(t,h),p,d,g,v)}};if(T.visit=function(t){!function t(e,r,n,i,a,o){if(!e(r,n,i,a,o)){var s=.5*(n+a),l=.5*(i+o),u=r.nodes;u[0]&&t(e,u[0],n,i,s,l),u[1]&&t(e,u[1],s,i,a,l),u[2]&&t(e,u[2],n,l,s,o),u[3]&&t(e,u[3],s,l,a,o)}}(t,T,p,d,g,v)},T.find=function(t){return function(t,e,r,n,i,a,o){var s,l=1/0;return function t(u,c,h,f,p){if(!(c>a||h>o||f=_)<<1|e>=b,k=w+4;w=0&&!(n=t.interpolators[i](e,r)););return n}function Wi(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;r=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ea(t){return 1-Math.cos(t*Ct)}function ra(t){return Math.pow(2,10*(t-1))}function na(t){return 1-Math.sqrt(1-t*t)}function ia(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}function aa(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function oa(t){var e,r,n,i=[t.a,t.b],a=[t.c,t.d],o=la(i),s=sa(i,a),l=la(((e=a)[0]+=(n=-s)*(r=i)[0],e[1]+=n*r[1],e))||0;i[0]*a[1]=0?t.slice(0,n):t,a=n>=0?t.slice(n+1):"in";return i=Xi.get(i)||Yi,a=Zi.get(a)||P,r=a(i.apply(null,e.call(arguments,1))),function(t){return t<=0?0:t>=1?1:r(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,i=e.c,a=e.l,o=r.h-n,s=r.c-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.c:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Yt(n+o*t,i+s*t,a+l*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,i=e.s,a=e.l,o=r.h-n,s=r.s-i,l=r.l-a;isNaN(s)&&(s=0,i=isNaN(i)?r.s:i);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Ht(n+o*t,i+s*t,a+l*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,i=e.a,a=e.b,o=r.l-n,s=r.a-i,l=r.b-a;return function(t){return te(n+o*t,i+s*t,a+l*t)+""}},t.interpolateRound=aa,t.transform=function(e){var r=n.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new oa(e?e.matrix:ua)})(e)},oa.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var ua={a:1,b:0,c:0,d:1,e:0,f:0};function ca(t){return t.length?t.pop()+",":""}function ha(e,r){var n=[],i=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,i),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(ca(r)+"rotate(",null,")")-2,x:Vi(t,e)})):e&&r.push(ca(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,i),function(t,e,r,n){t!==e?n.push({i:r.push(ca(r)+"skewX(",null,")")-2,x:Vi(t,e)}):e&&r.push(ca(r)+"skewX("+e+")")}(e.skew,r.skew,n,i),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(ca(r)+"scale(",null,",",null,")");n.push({i:i-4,x:Vi(t[0],e[0])},{i:i-2,x:Vi(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(ca(r)+"scale("+e+")")}(e.scale,r.scale,n,i),e=r=null,function(t){for(var e,r=-1,a=i.length;++r0?n=t:(e.c=null,e.t=NaN,e=null,l.end({type:"end",alpha:n=0})):t>0&&(l.start({type:"start",alpha:n=t}),e=Me(s.tick)),s):n},s.start=function(){var t,e,r,n=m.length,l=y.length,c=u[0],d=u[1];for(t=0;t=0;)r.push(i[n])}function Aa(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;r&&(a.value=0),a.children=u}else r&&(a.value=+r.call(n,a,a.depth)||0),delete a.children;return Aa(i,function(e){var n,i;t&&(n=e.children)&&n.sort(t),r&&(i=e.parent)&&(i.value+=e.value)}),s}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Ma(t,function(t){t.children&&(t.value=0)}),Aa(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var i=e.call(this,t,n);return function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++us&&(s=n),o.push(n)}for(r=0;ri&&(n=r,i=e);return n}function Na(t){return t.reduce(ja,0)}function ja(t,e){return t+e[1]}function Va(t,e){return Ua(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Ua(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function qa(e){return[t.min(e),t.max(e)]}function Ha(t,e){return t.value-e.value}function Ga(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Wa(t,e){t._pack_next=e,e._pack_prev=t}function Ya(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Xa(t){if((e=t.children)&&(l=e.length)){var e,r,n,i,a,o,s,l,u=1/0,c=-1/0,h=1/0,f=-1/0;if(e.forEach(Za),(r=e[0]).x=-r.r,r.y=0,x(r),l>1&&((n=e[1]).x=n.r,n.y=0,x(n),l>2))for(Ka(r,n,i=e[2]),x(i),Ga(r,i),r._pack_prev=i,Ga(i,n),n=r._pack_next,a=3;a0)for(o=-1;++o=h[0]&&l<=h[1]&&((s=u[t.bisect(f,l,1,d)-1]).y+=g,s.push(a[o]));return u}return a.value=function(t){return arguments.length?(r=t,a):r},a.range=function(t){return arguments.length?(n=ve(t),a):n},a.bins=function(t){return arguments.length?(i="number"==typeof t?function(e){return Ua(e,t)}:ve(t),a):i},a.frequency=function(t){return arguments.length?(e=!!t,a):e},a},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Ha),n=0,i=[1,1];function a(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,Aa(s,function(t){t.r=+c(t.value)}),Aa(s,Xa),n){var h=n*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;Aa(s,function(t){t.r+=h}),Aa(s,Xa),Aa(s,function(t){t.r-=h})}return function t(e,r,n,i){var a=e.children;e.x=r+=i*e.x;e.y=n+=i*e.y;e.r*=i;if(a)for(var o=-1,s=a.length;++op.x&&(p=t),t.depth>d.depth&&(d=t)});var g=r(f,p)/2-f.x,v=n[0]/(p.x+r(p,f)/2+g),m=n[1]/(d.depth||1);Ma(c,function(t){t.x=(t.x+g)*v,t.y=t.depth*m})}return u}function o(t){var e=t.children,n=t.parent.children,i=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,i=t.children,a=i.length;for(;--a>=0;)(e=i[a]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var a=(e[0].z+e[e.length-1].z)/2;i?(t.z=i.z+r(t._,i._),t.m=t.z-a):t.z=a}else i&&(t.z=i.z+r(t._,i._));t.parent.A=function(t,e,n){if(e){for(var i,a=t,o=t,s=e,l=a.parent.children[0],u=a.m,c=o.m,h=s.m,f=l.m;s=to(s),a=$a(a),s&&a;)l=$a(l),(o=to(o)).a=t,(i=s.z+h-a.z-u+r(s._,a._))>0&&(eo(ro(s,t,n),t,i),u+=i,c+=i),h+=s.m,u+=a.m,f+=l.m,c+=o.m;s&&!to(o)&&(o.t=s,o.m+=h-c),a&&!$a(l)&&(l.t=a,l.m+=u-f,n=t)}return n}(t,i,t.parent.A||n[0])}function s(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function l(t){t.x*=n[0],t.y=t.depth*n[1]}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t)?l:null,a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null==(n=t)?null:l,a):i?n:null},ka(a,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=Qa,n=[1,1],i=!1;function a(a,o){var s,l=e.call(this,a,o),u=l[0],c=0;Aa(u,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=s?c+=r(e,s):0,e.y=0,s=e)});var h=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(u),f=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(u),p=h.x-r(h,f)/2,d=f.x+r(f,h)/2;return Aa(u,i?function(t){t.x=(t.x-u.x)*n[0],t.y=(u.y-t.y)*n[1]}:function(t){t.x=(t.x-p)/(d-p)*n[0],t.y=(1-(u.y?t.y/u.y:1))*n[1]}),l}return a.separation=function(t){return arguments.length?(r=t,a):r},a.size=function(t){return arguments.length?(i=null==(n=t),a):i?null:n},a.nodeSize=function(t){return arguments.length?(i=null!=(n=t),a):i?n:null},ka(a,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,i=[1,1],a=null,o=no,s=!1,l="squarify",u=.5*(1+Math.sqrt(5));function c(t,e){for(var r,n,i=-1,a=t.length;++i0;)s.push(r=u[i-1]),s.area+=r.area,"squarify"!==l||(n=p(s,g))<=f?(u.pop(),f=n):(s.area-=s.pop().area,d(s,g,a,!1),g=Math.min(a.dx,a.dy),s.length=s.area=0,f=1/0);s.length&&(d(s,g,a,!0),s.length=s.area=0),e.forEach(h)}}function f(t){var e=t.children;if(e&&e.length){var r,n=o(t),i=e.slice(),a=[];for(c(i,n.dx*n.dy/t.value),a.area=0;r=i.pop();)a.push(r),a.area+=r.area,null!=r.z&&(d(a,r.z?n.dx:n.dy,n,!i.length),a.length=a.area=0);e.forEach(f)}}function p(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++oi&&(i=r));return e*=e,(n*=n)?Math.max(e*i*u/n,n/(e*a*u)):1/0}function d(t,e,r,i){var a,o=-1,s=t.length,l=r.x,u=r.y,c=e?n(t.area/e):0;if(e==r.dx){for((i||c>r.dy)&&(c=r.dy);++or.dx)&&(c=r.dx);++o1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r2?ho:so,s=i?pa:fa;return a=t(e,r,s,n),o=t(r,e,s,Gi),l}function l(t){return a(t)}l.invert=function(t){return o(t)};l.domain=function(t){return arguments.length?(e=t.map(Number),s()):e};l.range=function(t){return arguments.length?(r=t,s()):r};l.rangeRound=function(t){return l.range(t).interpolate(aa)};l.clamp=function(t){return arguments.length?(i=t,s()):i};l.interpolate=function(t){return arguments.length?(n=t,s()):n};l.ticks=function(t){return vo(e,t)};l.tickFormat=function(t,r){return mo(e,t,r)};l.nice=function(t){return po(e,t),s()};l.copy=function(){return t(e,r,n,i)};return s()}([0,1],[0,1],Gi,!1)};var yo={s:1,g:1,p:1,r:1,e:1};function xo(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,i,a){function o(t){return(i?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function s(t){return i?Math.pow(n,t):-Math.pow(n,-t)}function l(t){return r(o(t))}l.invert=function(t){return s(r.invert(t))};l.domain=function(t){return arguments.length?(i=t[0]>=0,r.domain((a=t.map(Number)).map(o)),l):a};l.base=function(t){return arguments.length?(n=+t,r.domain(a.map(o)),l):n};l.nice=function(){var t=lo(a.map(o),i?Math:_o);return r.domain(t),a=t.map(s),l};l.ticks=function(){var t=ao(a),e=[],r=t[0],l=t[1],u=Math.floor(o(r)),c=Math.ceil(o(l)),h=n%1?2:n;if(isFinite(c-u)){if(i){for(;u0;f--)e.push(s(u)*f);for(u=0;e[u]l;c--);e=e.slice(u,c)}return e};l.tickFormat=function(e,r){if(!arguments.length)return bo;arguments.length<2?r=bo:"function"!=typeof r&&(r=t.format(r));var i=Math.max(1,n*e/l.ticks().length);return function(t){var e=t/s(Math.round(o(t)));return e*n0?i[t-1]:r[0],th?0:1;if(u=St)return l(u,p)+(s?l(s,1-p):"")+"Z";var d,g,v,m,y,x,b,_,w,k,M,A,T=0,S=0,C=[];if((m=(+o.apply(this,arguments)||0)/2)&&(v=n===Co?Math.sqrt(s*s+u*u):+n.apply(this,arguments),p||(S*=-1),u&&(S=It(v/u*Math.sin(m))),s&&(T=It(v/s*Math.sin(m)))),u){y=u*Math.cos(c+S),x=u*Math.sin(c+S),b=u*Math.cos(h-S),_=u*Math.sin(h-S);var E=Math.abs(h-c-2*S)<=At?0:1;if(S&&Io(y,x,b,_)===p^E){var L=(c+h)/2;y=u*Math.cos(L),x=u*Math.sin(L),b=_=null}}else y=x=0;if(s){w=s*Math.cos(h-T),k=s*Math.sin(h-T),M=s*Math.cos(c+T),A=s*Math.sin(c+T);var P=Math.abs(c-h+2*T)<=At?0:1;if(T&&Io(w,k,M,A)===1-p^P){var z=(c+h)/2;w=s*Math.cos(z),k=s*Math.sin(z),M=A=null}}else w=k=0;if(f>kt&&(d=Math.min(Math.abs(u-s)/2,+r.apply(this,arguments)))>.001){g=s0?0:1}function Oo(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,h=t[1]+u,f=e[0]+l,p=e[1]+u,d=(c+f)/2,g=(h+p)/2,v=f-c,m=p-h,y=v*v+m*m,x=r-n,b=c*p-f*h,_=(m<0?-1:1)*Math.sqrt(Math.max(0,x*x*y-b*b)),w=(b*m-v*_)/y,k=(-b*v-m*_)/y,M=(b*m+v*_)/y,A=(-b*v+m*_)/y,T=w-d,S=k-g,C=M-d,E=A-g;return T*T+S*S>C*C+E*E&&(w=M,k=A),[[w-l,k-u],[w*r/x,k*r/x]]}function Ro(t){var e=$n,r=ti,n=Wr,i=Fo,a=i.key,o=.7;function s(a){var s,l=[],u=[],c=-1,h=a.length,f=ve(e),p=ve(r);function d(){l.push("M",i(t(u),o))}for(;++c1&&i.push("H",n[0]);return i.join("")},"step-before":jo,"step-after":Vo,basis:Ho,"basis-open":function(t){if(t.length<4)return Fo(t);var e,r=[],n=-1,i=t.length,a=[0],o=[0];for(;++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);r.push(Go(Xo,a)+","+Go(Xo,o)),--n;for(;++n9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));s=-1;for(;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}(t))}});function Fo(t){return t.length>1?t.join("L"):t+"Z"}function No(t){return t.join("L")+"Z"}function jo(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;uAt)+",1 "+e}function l(t,e,r,n){return"Q 0,0 "+n}return a.radius=function(t){return arguments.length?(r=ve(t),a):r},a.source=function(e){return arguments.length?(t=ve(e),a):t},a.target=function(t){return arguments.length?(e=ve(t),a):e},a.startAngle=function(t){return arguments.length?(n=ve(t),a):n},a.endAngle=function(t){return arguments.length?(i=ve(t),a):i},a},t.svg.diagonal=function(){var t=Nn,e=jn,r=ts;function n(n,i){var a=t.call(this,n,i),o=e.call(this,n,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return"M"+(l=l.map(r))[0]+"C"+l[1]+" "+l[2]+" "+l[3]}return n.source=function(e){return arguments.length?(t=ve(e),n):t},n.target=function(t){return arguments.length?(e=ve(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=ts,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=rs,e=es;function r(r,n){return(is.get(t.call(this,r,n))||ns)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ve(e),r):t},r.size=function(t){return arguments.length?(e=ve(t),r):e},r};var is=t.map({circle:ns,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*os)),r=e*os;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/as),r=e*as/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=is.keys();var as=Math.sqrt(3),os=Math.tan(30*Et);Y.transition=function(t){for(var e,r,n=cs||++ps,i=vs(t),a=[],o=hs||{time:Date.now(),ease:ta,delay:0,duration:250},s=-1,l=this.length;++s0;)u[--f].call(t,o);if(a>=1)return h.event&&h.event.end.call(t,t.__data__,e),--c.count?delete c[n]:delete t[r],1}h||(a=i.time,o=Me(function(t){var e=h.delay;if(o.t=e+a,e<=t)return f(t-e);o.c=f},0,a),h=c[n]={tween:new b,time:a,timer:o,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++c.count)}fs.call=Y.call,fs.empty=Y.empty,fs.node=Y.node,fs.size=Y.size,t.transition=function(e,r){return e&&e.transition?cs?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=fs,fs.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=X(t);for(var s=-1,l=this.length;++srect,.s>rect").attr("width",s[1]-s[0])}function g(t){t.select(".extent").attr("y",l[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",l[1]-l[0])}function v(){var h,v,m=this,y=t.select(t.event.target),x=n.of(m,arguments),b=t.select(m),_=y.datum(),w=!/^(n|s)$/.test(_)&&i,k=!/^(e|w)$/.test(_)&&a,M=y.classed("extent"),A=xt(m),T=t.mouse(m),S=t.select(o(m)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(h=null,T[0]-=s[1],T[1]-=l[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(T[0]+=s[1],T[1]+=l[1],M=0,F())});if(t.event.changedTouches?S.on("touchmove.brush",L).on("touchend.brush",z):S.on("mousemove.brush",L).on("mouseup.brush",z),b.interrupt().selectAll("*").interrupt(),M)T[0]=s[0]-T[0],T[1]=l[0]-T[1];else if(_){var C=+/w$/.test(_),E=+/^n/.test(_);v=[s[1-C]-T[0],l[1-E]-T[1]],T[0]=s[C],T[1]=l[E]}else t.event.altKey&&(h=T.slice());function L(){var e=t.mouse(m),r=!1;v&&(e[0]+=v[0],e[1]+=v[1]),M||(t.event.altKey?(h||(h=[(s[0]+s[1])/2,(l[0]+l[1])/2]),T[0]=s[+(e[0]1?{floor:function(e){for(;s(e=t.floor(e));)e=Es(e-1);return e},ceil:function(e){for(;s(e=t.ceil(e));)e=Es(+e+1);return e}}:t))},i.ticks=function(t,e){var r=ao(i.domain()),n=null==t?a(r,10):"number"==typeof t?a(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],Es(+r[1]+1),e<1?1:e)},i.tickFormat=function(){return n},i.copy=function(){return Cs(e.copy(),r,n)},fo(i,e)}function Es(t){return new Date(t)}Ms.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Ss:Ts,Ss.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Ss.toString=Ts.toString,De.second=Be(function(t){return new Ie(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),De.seconds=De.second.range,De.seconds.utc=De.second.utc.range,De.minute=Be(function(t){return new Ie(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),De.minutes=De.minute.range,De.minutes.utc=De.minute.utc.range,De.hour=Be(function(t){var e=t.getTimezoneOffset()/60;return new Ie(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),De.hours=De.hour.range,De.hours.utc=De.hour.utc.range,De.month=Be(function(t){return(t=De.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),De.months=De.month.range,De.months.utc=De.month.utc.range;var Ls=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Ps=[[De.second,1],[De.second,5],[De.second,15],[De.second,30],[De.minute,1],[De.minute,5],[De.minute,15],[De.minute,30],[De.hour,1],[De.hour,3],[De.hour,6],[De.hour,12],[De.day,1],[De.day,2],[De.week,1],[De.month,1],[De.month,3],[De.year,1]],zs=Ms.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Wr]]),Ds={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(Es)},floor:P,ceil:P};Ps.year=De.year,De.scale=function(){return Cs(t.scale.linear(),Ps,zs)};var Is=Ps.map(function(t){return[t[0].utc,t[1]]}),Os=As.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Wr]]);function Rs(t){return JSON.parse(t.responseText)}function Bs(t){var e=n.createRange();return e.selectNode(n.body),e.createContextualFragment(t.responseText)}Is.year=De.year.utc,De.scale.utc=function(){return Cs(t.scale.linear(),Is,Os)},t.text=me(function(t){return t.responseText}),t.json=function(t,e){return ye(t,"application/json",Rs,e)},t.html=function(t,e){return ye(t,"text/html",Bs,e)},t.xml=me(function(t){return t.responseXML}),"function"==typeof aH&&aH.amd?(this.d3=t,aH(t)):i.exports?i.exports=t:this.d3=t}(),i=i.exports;var a=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1},o={},s=Math.PI;o.deg2rad=function(t){return t/180*s},o.rad2deg=function(t){return t/s*180},o.wrap360=function(t){var e=t%360;return e<0?e+360:e},o.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t};var l=n.BADNUM,u=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g,c={exports:{}};!function(t){var e=/^\s+/,r=/\s+$/,n=0,i=t.round,a=t.min,o=t.max,s=t.random;function l(s,u){if(s=s||"",u=u||{},s instanceof l)return s;if(!(this instanceof l))return new l(s,u);var c=function(n){var i={r:0,g:0,b:0},s=1,l=null,u=null,c=null,h=!1,f=!1;"string"==typeof n&&(n=function(t){t=t.replace(e,"").replace(r,"").toLowerCase();var n,i=!1;if(S[t])t=S[t],i=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=j.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=j.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=j.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=j.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=j.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=j.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=j.hex8.exec(t))return{r:z(n[1]),g:z(n[2]),b:z(n[3]),a:R(n[4]),format:i?"name":"hex8"};if(n=j.hex6.exec(t))return{r:z(n[1]),g:z(n[2]),b:z(n[3]),format:i?"name":"hex"};if(n=j.hex4.exec(t))return{r:z(n[1]+""+n[1]),g:z(n[2]+""+n[2]),b:z(n[3]+""+n[3]),a:R(n[4]+""+n[4]),format:i?"name":"hex8"};if(n=j.hex3.exec(t))return{r:z(n[1]+""+n[1]),g:z(n[2]+""+n[2]),b:z(n[3]+""+n[3]),format:i?"name":"hex"};return!1}(n));"object"==typeof n&&(V(n.r)&&V(n.g)&&V(n.b)?(p=n.r,d=n.g,g=n.b,i={r:255*L(p,255),g:255*L(d,255),b:255*L(g,255)},h=!0,f="%"===String(n.r).substr(-1)?"prgb":"rgb"):V(n.h)&&V(n.s)&&V(n.v)?(l=I(n.s),u=I(n.v),i=function(e,r,n){e=6*L(e,360),r=L(r,100),n=L(n,100);var i=t.floor(e),a=e-i,o=n*(1-r),s=n*(1-a*r),l=n*(1-(1-a)*r),u=i%6;return{r:255*[n,s,o,o,l,n][u],g:255*[l,n,n,s,o,o][u],b:255*[o,o,l,n,n,s][u]}}(n.h,l,u),h=!0,f="hsv"):V(n.h)&&V(n.s)&&V(n.l)&&(l=I(n.s),c=I(n.l),i=function(t,e,r){var n,i,a;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=L(t,360),e=L(e,100),r=L(r,100),0===e)n=i=a=r;else{var s=r<.5?r*(1+e):r+e-r*e,l=2*r-s;n=o(l,s,t+1/3),i=o(l,s,t),a=o(l,s,t-1/3)}return{r:255*n,g:255*i,b:255*a}}(n.h,l,c),h=!0,f="hsl"),n.hasOwnProperty("a")&&(s=n.a));var p,d,g;return s=E(s),{ok:h,format:n.format||f,r:a(255,o(i.r,0)),g:a(255,o(i.g,0)),b:a(255,o(i.b,0)),a:s}}(s);this._originalInput=s,this._r=c.r,this._g=c.g,this._b=c.b,this._a=c.a,this._roundA=i(100*this._a)/100,this._format=u.format||c.format,this._gradientType=u.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=c.ok,this._tc_id=n++}function u(t,e,r){t=L(t,255),e=L(e,255),r=L(r,255);var n,i,s=o(t,e,r),l=a(t,e,r),u=(s+l)/2;if(s==l)n=i=0;else{var c=s-l;switch(i=u>.5?c/(2-s-l):c/(s+l),s){case t:n=(e-r)/c+(e>1)+720)%360;--e;)n.h=(n.h+i)%360,a.push(l(n));return a}function T(t,e){e=e||6;for(var r=l(t).toHsv(),n=r.h,i=r.s,a=r.v,o=[],s=1/e;e--;)o.push(l({h:n,s:i,v:a})),a=(a+s)%1;return o}l.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,i=this.toRgb();return e=i.r/255,r=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=E(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=h(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=h(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=u(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=u(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return f(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[D(i(t).toString(16)),D(i(e).toString(16)),D(i(r).toString(16)),D(O(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*L(this._r,255))+"%",g:i(100*L(this._g,255))+"%",b:i(100*L(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%)":"rgba("+i(100*L(this._r,255))+"%, "+i(100*L(this._g,255))+"%, "+i(100*L(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[f(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+p(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var i=l(t);r="#"+p(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return l(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(m,arguments)},brighten:function(){return this._applyModification(y,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(d,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(v,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(A,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(T,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},l.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:I(t[n]));t=r}return l(t,e)},l.equals=function(t,e){return!(!t||!e)&&l(t).toRgbString()==l(e).toRgbString()},l.random=function(){return l.fromRatio({r:s(),g:s(),b:s()})},l.mix=function(t,e,r){r=0===r?0:r||50;var n=l(t).toRgb(),i=l(e).toRgb(),a=r/100;return l({r:(i.r-n.r)*a+n.r,g:(i.g-n.g)*a+n.g,b:(i.b-n.b)*a+n.b,a:(i.a-n.a)*a+n.a})},l.readability=function(e,r){var n=l(e),i=l(r);return(t.max(n.getLuminance(),i.getLuminance())+.05)/(t.min(n.getLuminance(),i.getLuminance())+.05)},l.isReadable=function(t,e,r){var n,i,a=l.readability(t,e);switch(i=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":i=a>=4.5;break;case"AAlarge":i=a>=3;break;case"AAAsmall":i=a>=7}return i},l.mostReadable=function(t,e,r){var n,i,a,o,s=null,u=0;i=(r=r||{}).includeFallbackColors,a=r.level,o=r.size;for(var c=0;cu&&(u=n,s=l(e[c]));return l.isReadable(t,s,{level:a,size:o})||!i?s:(r.includeFallbackColors=!1,l.mostReadable(t,["#fff","#000"],r))};var S=l.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"},C=l.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(S);function E(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function L(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=a(r,o(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function P(t){return a(1,o(0,t))}function z(t){return parseInt(t,16)}function D(t){return 1==t.length?"0"+t:""+t}function I(t){return t<=1&&(t=100*t+"%"),t}function O(e){return t.round(255*parseFloat(e)).toString(16)}function R(t){return z(t)/255}var B,F,N,j=(F="[\\s|\\(]+("+(B="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+B+")[,|\\s]+("+B+")\\s*\\)?",N="[\\s|\\(]+("+B+")[,|\\s]+("+B+")[,|\\s]+("+B+")[,|\\s]+("+B+")\\s*\\)?",{CSS_UNIT:new RegExp(B),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+N),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})$/});function V(t){return!!j.CSS_UNIT.exec(t)}c.exports?c.exports=l:"function"==typeof aH&&aH.amd?aH(function(){return l}):window.tinycolor=l}(Math),c=c.exports;var h={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]},f=h.RdBu,p=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;e=0;e--){if(n=t[e][0],i=t[e][1],o=!1,X(n))for(r=n.length-1;r>=0;r--)Q(n[r],tt(i,r))?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)Q(n[a[r]],tt(i,a[r]))?delete n[a[r]]:o=!0;if(o)return}}(l)):o[e[a]]=n}}function tt(t,e){var r=e;return a(e)?r="["+e+"]":t&&(r="."+e),t+r}function et(t,e,r,n){var i,a=X(r),o=!0,s=r,l=n.replace("-1",0),u=!a&&Q(r,l),c=e[0];for(i=0;in.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,n){t%1||!a(t)||void 0!==n.min&&tn.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var i="number"==typeof t;!0!==n.strict&&i?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){c(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return c(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(d(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):a(t)?e.set(st(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r,n){var i=n.regex||at(r);"string"==typeof t&&i.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!at(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var i=t.split("+"),a=0;a=ut&&t<=ct?t:pt;if("string"!=typeof t&&"number"!=typeof t)return pt;t=String(t);var r=kt(e),n=t.charAt(0);!r||"G"!==n&&"g"!==n||(t=t.substr(1),e="");var i=r&&"chinese"===e.substr(0,7),a=t.match(i?_t:bt);if(!a)return pt;var o=a[1],s=a[3]||"1",l=Number(a[5]||1),u=Number(a[7]||0),c=Number(a[9]||0),h=Number(a[11]||0);if(r){if(2===o.length)return pt;var f;o=Number(o);try{var p=O.getComponentMethod("calendars","getCal")(e);if(i){var d="i"===s.charAt(s.length-1);s=parseInt(s,10),f=p.newDate(o,p.toMonthIndex(o,s,d),l)}else f=p.newDate(o,Number(s),l)}catch(t){return pt}return f?(f.toJD()-yt)*dt+u*gt+c*vt+h*mt:pt}o=2===o.length?(Number(o)+2e3-wt)%100+wt:Number(o),s-=1;var g=new Date(Date.UTC(2e3,s,l,u,c));return g.setUTCFullYear(o),g.getUTCMonth()!==s?pt:g.getUTCDate()!==l?pt:g.getTime()+h*mt},ut=ft.MIN_MS=ft.dateTime2ms("-9999"),ct=ft.MAX_MS=ft.dateTime2ms("9999-12-31 23:59:59.9999"),ft.isDateTime=function(t,e){return ft.dateTime2ms(t,e)!==pt};var At=90*dt,Tt=3*gt,St=5*vt;function Ct(t,e,r,n,i){if((e||r||n||i)&&(t+=" "+Mt(e,2)+":"+Mt(r,2),(n||i)&&(t+=":"+Mt(n,2),i))){for(var a=4;i%10==0;)a-=1,i/=10;t+="."+Mt(i,a)}return t}ft.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=ut&&t<=ct))return pt;e||(e=0);var n,i,a,o,s,l,u=Math.floor(10*ht(t+.05,1)),c=Math.round(t-u/10);if(kt(r)){var h=Math.floor(c/dt)+yt,f=Math.floor(ht(t,dt));try{n=O.getComponentMethod("calendars","getCal")(r).fromJD(h).formatDate("yyyy-mm-dd")}catch(t){n=xt("G%Y-%m-%d")(new Date(c))}if("-"===n.charAt(0))for(;n.length<11;)n="-0"+n.substr(1);else for(;n.length<10;)n="0"+n;i=e=ut+dt&&t<=ct-dt))return pt;var e=Math.floor(10*ht(t+.05,1)),r=new Date(Math.round(t-e/10));return Ct(i.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+e)},ft.cleanDate=function(t,e,r){if(ft.isJSDate(t)||"number"==typeof t){if(kt(r))return M.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=ft.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!ft.isDateTime(t,r))return M.error("unrecognized date",t),e;return t};var Et=/%\d?f/g;function Lt(t,e,r,n){t=t.replace(Et,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var i=new Date(Math.floor(e+.05));if(kt(n))try{t=O.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(i)}var Pt=[59,59.9,59.99,59.999,59.9999];ft.formatDate=function(t,e,r,n,i,o){if(i=kt(i)&&i,!e)if("y"===r)e=o.year;else if("m"===r)e=o.month;else{if("d"!==r)return function(t,e){var r=ht(t+.05,dt),n=Mt(Math.floor(r/gt),2)+":"+Mt(ht(Math.floor(r/vt),60),2);if("M"!==e){a(e)||(e=0);var i=(100+Math.min(ht(t/mt,60),Pt[e])).toFixed(e).substr(1);e>0&&(i=i.replace(/0+$/,"").replace(/[\.]$/,"")),n+=":"+i}return n}(t,r)+"\n"+Lt(o.dayMonthYear,t,n,i);e=o.dayMonth+"\n"+o.year}return Lt(e,t,n,i)};var zt=3*dt;ft.incrementMonth=function(t,e,r){r=kt(r)&&r;var n=ht(t,dt);if(t=Math.round(t-n),r)try{var i=Math.round(t/dt)+yt,a=O.getComponentMethod("calendars","getCal")(r),o=a.fromJD(i);return e%12?a.add(o,e,"m"):a.add(o,e/12,"y"),(o.toJD()-yt)*dt+n}catch(e){M.error("invalid ms "+t+" in calendar "+r)}var s=new Date(t+zt);return s.setUTCMonth(s.getUTCMonth()+e)+n-zt},ft.findExactDates=function(t,e){for(var r,n,i=0,o=0,s=0,l=0,u=kt(e)&&O.getComponentMethod("calendars","getCal")(e),c=0;c1||g<0||g>1?null:{x:t+l*g,y:e+h*g}}function jt(t,e,r,n,i){var a=n*t+i*e;if(a<0)return n*n+i*i;if(a>r){var o=n-t,s=i-e;return o*o+s*s}var l=n*e-i*t;return l*l/r}Ft.segmentsIntersect=Nt,Ft.segmentDistance=function(t,e,r,n,i,a,o,s){if(Nt(t,e,r,n,i,a,o,s))return 0;var l=r-t,u=n-e,c=o-i,h=s-a,f=l*l+u*u,p=c*c+h*h,d=Math.min(jt(l,u,f,i-t,a-e),jt(l,u,f,o-t,s-e),jt(c,h,p,t-i,e-a),jt(c,h,p,r-i,n-a));return Math.sqrt(d)},Ft.getTextLocation=function(t,e,r,n){if(t===Rt&&n===Bt||(Ot={},Rt=t,Bt=n),Ot[r])return Ot[r];var i=t.getPointAtLength(ht(r-n/2,e)),a=t.getPointAtLength(ht(r+n/2,e)),o=Math.atan((a.y-i.y)/(a.x-i.x)),s=t.getPointAtLength(ht(r,e)),l={x:(4*s.x+i.x+a.x)/6,y:(4*s.y+i.y+a.y)/6,theta:o};return Ot[r]=l,l},Ft.clearLocationCache=function(){Rt=null},Ft.getVisibleSegment=function(t,e,r){var n,i,a=e.left,o=e.right,s=e.top,l=e.bottom,u=0,c=t.getTotalLength(),h=c;function f(e){var r=t.getPointAtLength(e);0===e?n=r:e===c&&(i=r);var u=r.xo?r.x-o:0,h=r.yl?r.y-l:0;return Math.sqrt(u*u+h*h)}for(var p=f(u);p;){if((u+=p+r)>h)return;p=f(u)}for(p=f(h);p;){if(u>(h-=p+r))return;p=f(h)}return{min:u,max:h,len:h-u,total:c,isClosed:0===u&&h===c&&Math.abs(n.x-i.x)<.1&&Math.abs(n.y-i.y)<.1}},Ft.findPointOnPath=function(t,e,r,n){for(var i,a,o,s=(n=n||{}).pathLength||t.getTotalLength(),l=n.tolerance||.001,u=n.iterationLimit||30,c=t.getPointAtLength(0)[r]>t.getPointAtLength(s)[r]?-1:1,h=0,f=0,p=s;h0?p=i:f=i,h++}return a};var Vt=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t},Ut=function(t){return t},qt=/^\w*$/,Ht={init2dArray:function(t,e){for(var r=new Array(t),n=0;ne}function $t(t,e){return t>=e}Zt.findBin=function(t,e,r){if(a(e.start))return r?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var n,i,o=0,s=e.length,l=0,u=s>1?(e[s-1]-e[0])/(s-1):1;for(i=u>=0?r?Jt:Kt:r?$t:Qt,t+=1e-9*u*(r?-1:1)*(u>=0?1:-1);o90&&M.log("Long binary search..."),o-1},Zt.sorterAsc=function(t,e){return t-e},Zt.sorterDes=function(t,e){return e-t},Zt.distinctVals=function(t){var e=t.slice();e.sort(Zt.sorterAsc);for(var r=e.length-1,n=e[r]-e[0]||1,i=n/(r||1)/1e4,a=[e[0]],o=0;oe[o]+i&&(n=Math.min(n,e[o+1]-e[o]),a.push(e[o+1]));return{vals:a,minDiff:n}},Zt.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;ir.length)&&(n=r.length),a(e)||(e=!1),ee(r[0])){for(o=new Array(n),i=0;it.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]};var re={},ne={};function ie(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}re.throttle=function(t,e,r){var n=ne[t],i=Date.now();if(!n){for(var a in ne)ne[a].tsn.ts+e?o():n.timer=setTimeout(function(){o(),n.timer=null},e)},re.done=function(t){var e=ne[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},re.clear=function(t){if(t)ie(ne[t]),delete ne[t];else for(var e in ne)re.clear(e)};var ae=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var r=Math.log(Math.min(e[0],e[1]))/Math.LN10;return a(r)||(r=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),r},oe={},se=n.FP_SAFE,le=n.BADNUM,ue=oe={};ue.nestedProperty=Z,ue.keyedContainer=function(t,e,r,n){var i,a;r=r||"name",n=n||"value";var o={};a=e&&e.length?Z(t,e).get():t,e=e||"",a=a||[];var s={};for(i=0;i2)return o[e]=2|o[e],u.set(t,null);if(l){for(i=e;i/g),s=0;sse?le:a(t)?Number(t):le:le},ue.noop=S,ue.identity=Ut,ue.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var i=0;ir?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},ue.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},ue.simpleMap=function(t,e,r,n){for(var i=t.length,a=new Array(i),o=0;o-1||u!==1/0&&u>=Math.pow(2,r)?t(e,r,n):s},ue.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},ue.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;r=s&&(i-=s*Math.floor(i/s)),i<0?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},ue.syncOrAsync=function(t,e,r){var n;function i(){return ue.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(i).then(void 0,ue.promiseError);return r&&r(e)},ue.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},ue.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n=0&&i%1==0){var d=n?n[p]:p,g=r?r[d]:d;h(g)&&(t[g].selected=1)}}},ue.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=ue.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},ue.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,i,a,o=Object.keys(t);for(n=0;n1?i+o[1]:"";if(a&&(o.length>1||s.length>4||r))for(;n.test(s);)s=s.replace(n,"$1"+a+"$2");return s+l};var fe=/%{([^\s%{}]*)}/g,pe=/^\w*$/;ue.templateString=function(t,e){var r={};return t.replace(fe,function(t,n){return pe.test(n)?e[n]||"":(r[n]=r[n]||ue.nestedProperty(e,n).get,r[n]()||"")})};ue.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,i=0,a=0;a=48&&o<=57,u=s>=48&&s<=57;if(l&&(n=10*n+o-48),u&&(i=10*i+s-48),!l||!u){if(n!==i)return n-i;if(o!==s)return o-s}}return i-n};var de=2e9;ue.seedPseudoRandom=function(){de=2e9},ue.pseudoRandom=function(){var t=de;return de=(69069*de+1)%4294967296,Math.abs(de-t)<429496729?ue.pseudoRandom():de/4294967296};var ge=oe.extendFlat,ve=oe.isPlainObject,me={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},ye={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","margins","layoutstyle","modebar","camera","arraydraw"]},xe=me.flags.slice().concat(["clearCalc","fullReplot"]),be=ye.flags.slice().concat("layoutReplot"),_e={traces:me,layout:ye,traceFlags:function(){return we(xe)},layoutFlags:function(){return we(be)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),i=0;i=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}Ne.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},Ne.rgb=function(t){return Ne.tinyRGB(c(t))},Ne.opacity=function(t){return t?c(t).getAlpha():0},Ne.addOpacity=function(t,e){var r=c(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},Ne.combine=function(t,e){var r=c(t).toRgb();if(1===r.a)return c(t).toRgbString();var n=c(e||Ve).toRgb(),i=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},a={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return c(a).toRgbString()},Ne.contrast=function(t,e,r){var n=c(t);return 1!==n.getAlpha()&&(n=c(Ne.combine(t,Ve))),(n.isDark()?e?n.lighten(e):Ve:r?n.darken(r):je).toString()},Ne.stroke=function(t,e){var r=c(e);t.style({stroke:Ne.tinyRGB(r),"stroke-opacity":r.getAlpha()})},Ne.fill=function(t,e){var r=c(e);t.style({fill:Ne.tinyRGB(r),"fill-opacity":r.getAlpha()})},Ne.clean=function(t){if(t&&"object"==typeof t){var e,r,n,i,a=Object.keys(t);for(e=0;e=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n},He=function(t,e,r,n){var i,a;r?(i=oe.nestedProperty(t,r).get(),a=oe.nestedProperty(t._input,r).get()):(i=t,a=t._input);var o=n+"auto",s=n+"min",l=n+"max",u=i[o],c=i[s],f=i[l],p=i.colorscale;!1===u&&void 0!==c||(c=oe.aggNums(Math.min,null,e)),!1===u&&void 0!==f||(f=oe.aggNums(Math.max,null,e)),c===f&&(c-=.5,f+=.5),i[s]=c,i[l]=f,a[s]=c,a[l]=f,a[o]=!1!==u||void 0===c&&void 0===f,i.autocolorscale&&(p=c*f<0?h.RdBu:c>=0?h.Reds:h.Blues,a.colorscale=p,i.reversescale&&(p=qe(p)),i.colorscale=p)},Ge=function(t,e,r,n,i){var a=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",a),r("ticksuffix",i.tickSuffixDflt)&&r("showticksuffix",a),r("showticklabels")){var o=i.font||{},s=e.color===t.color?e.color:o.color;if(oe.coerceFont(r,"tickfont",{family:o.family,size:o.size,color:s}),r("tickangle"),"category"!==n){var l=r("tickformat");!function(t,e){var r,n,i=t.tickformatstops,a=e.tickformatstops=[];if(!Array.isArray(i))return;function o(t,e){return oe.coerce(r,n,ze.tickformatstops,t,e)}for(var s=0;s0?Number(l):s;else if("string"!=typeof l)e.dtick=s;else{var u=l.charAt(0),c=l.substr(1);((c=a(c)?Number(c):0)<=0||!("date"===n&&"M"===u&&c===Math.round(c)||"log"===n&&"L"===u||"log"===n&&"D"===u&&(1===c||2===c)))&&(e.dtick=s)}var h="date"===n?oe.dateTick0(e.calendar):0,f=r("tick0",h);"date"===n?e.tick0=oe.cleanDate(f,h):a(f)&&"D1"!==l&&"D2"!==l?e.tick0=Number(f):e.tick0=h}else{void 0===r("tickvals")?e.tickmode="auto":r("ticktext")}},Ze=function(t){return void 0!==h[t]||p(t)},Je=function(t,e,r,n,i){var o,s=i.prefix,l=i.cLetter,u=s.slice(0,s.length-1),c=s?oe.nestedProperty(t,u).get()||{}:t,h=s?oe.nestedProperty(e,u).get()||{}:e,f=c[l+"min"],p=c[l+"max"],d=c.colorscale;n(s+l+"auto",!(a(f)&&a(p)&&f","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}},ir={},ar=er.LINE_SPACING;function or(t,e){return t.node().getBoundingClientRect()[e]}var sr=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;ir.convertToTspans=function(t,e,r){var n=t.text(),a=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&n.match(sr),o=i.select(t.node().parentNode);if(!o.empty()){var s=t.attr("class")?t.attr("class").split(" ")[0]:"text";return s+="-math",o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove(),t.style("display",null).attr({"data-unformatted":n,"data-math":"N"}),a?(e&&e._promises||[]).push(new Promise(function(e){t.style("display","none");var u=parseInt(t.node().style.fontSize,10),c={fontSize:u};!function(t,e,r){var n="math-output-"+oe.randstr([],64),a=i.select("body").append("div").attr({id:n}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text((o=t,o.replace(lr,"\\lt ").replace(ur,"\\gt ")));var o;MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var e=i.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())oe.log("There was an error in the tex syntax.",t),r();else{var n=a.select("svg").node().getBoundingClientRect();r(a.select(".MathJax_SVG"),e,n)}a.remove()})}(a[2],c,function(i,a,c){o.selectAll("svg."+s).remove(),o.selectAll("g."+s+"-group").remove();var h=i&&i.select("svg");if(!h||!h.node())return l(),void e();var f=o.append("g").classed(s+"-group",!0).attr({"pointer-events":"none","data-unformatted":n,"data-math":"Y"});f.node().appendChild(h.node()),a&&a.node()&&h.node().insertBefore(a.node().cloneNode(!0),h.node().firstChild),h.attr({class:s,height:c.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var p=t.node().style.fill||"black";h.select("g").attr({fill:p,stroke:p});var d=or(h,"width"),g=or(h,"height"),v=+t.attr("x")-d*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],m=-(u||or(t,"height"))/4;"y"===s[0]?(f.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-d/2,m-g/2]+")"}),h.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===s[0]?h.attr({x:t.attr("x"),y:m-g/2}):"a"===s[0]?h.attr({x:0,y:m}):h.attr({x:v,y:+t.attr("y")+m-g/2}),r&&r.call(t,f),e(f)})})):l(),t}function l(){o.empty()||(s=t.attr("class")+"-math",o.select("svg."+s).remove()),t.text("").style("white-space","pre"),function(t,e){e=(r=e,function(t,e){if(!t)return"";for(var r=0;r1)for(var a=1;a doesnt match end tag <"+t+">. Pretending it did match.",e),n=o[o.length-1].node}else oe.log("Ignoring unexpected end tag .",e)}br.test(e)?l():(n=t,o=[{node:t}]);for(var f=e.split(yr),p=0;p|>|>)/g;var cr={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"},hr={sub:"0.3em",sup:"-0.6em"},fr={sub:"-0.21em",sup:"0.42em"},pr="\u200b",dr=["http:","https:","mailto:","",void 0,":"],gr=new RegExp("]*)?/?>","g"),vr=Object.keys(nr.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:nr.entityToUnicode[t]}}),mr=/(\r\n?|\n)/g,yr=/(<[^<>]*>)/,xr=/<(\/?)([^ >]*)(\s+(.*))?>/i,br=//i,_r=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,wr=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,kr=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,Mr=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function Ar(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var Tr=/(^|;)\s*color:/;function Sr(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}ir.plainText=function(t){return(t||"").replace(gr," ")},ir.lineCount=function(t){return t.selectAll("tspan.line").size()||1},ir.positionText=function(t,e,r){return t.each(function(){var t=i.select(this);function n(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var a=n("x",e),o=n("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:a,y:o})})},ir.makeEditable=function(t,e){var r=e.gd,n=e.delegate,a=i.dispatch("edit","input","cancel"),o=n||t;if(t.style({"pointer-events":n?"none":"all"}),1!==t.size())throw new Error("boo");function s(){var n,s,u,c;n=i.select(r).select(".svg-container"),s=n.append("div"),u=t.node().style,c=parseFloat(u.fontSize||12),s.classed("plugin-editable editable",!0).style({position:"absolute","font-family":u.fontFamily||"Arial","font-size":c,color:e.fill||u.fill||"black",opacity:1,"background-color":e.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(e.text||t.attr("data-unformatted")).call(Sr(t,n,e)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var e,n=i.select(this).attr("class");(e=n?"."+n.split(" ")[0]+"-math-group":"[class*=-math-group]")&&i.select(t.node().parentNode).select(e).style({opacity:0});var o=this.textContent;i.select(this).transition().duration(0).remove(),i.select(document).on("mouseup",null),a.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,i.select(document).on("mouseup",function(){if(i.event.target===t)return!1;document.activeElement===s.node()&&s.node().blur()})}).on("keyup",function(){27===i.event.which?(r._editing=!1,t.style({opacity:1}),i.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),a.cancel.call(t,this.textContent)):(a.input.call(t,this.textContent),i.select(this).call(Sr(t,n,e)))}).on("keydown",function(){13===i.event.which&&this.blur()}).call(l),t.style({opacity:0});var h,f=o.attr("class");(h=f?"."+f.split(" ")[0]+"-math-group":"[class*=-math-group]")&&i.select(t.node().parentNode).select(h).style({opacity:0})}function l(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return e.immediate?s():o.on("click",s),i.rebind(t,a,"on")};var Cr=function(t){var e=t.marker,r=e.sizeref||1,n=e.sizemin||0,i="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=i(t/2);return a(e)&&e>0?Math.max(e,n):0}},Er={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return oe.isPlainObject(t.marker)&&oe.isArrayOrTypedArray(t.marker.size)}},Lr={},Pr=er.LINE_SPACING,zr=g.DESELECTDIM,Dr=Lr={};Dr.font=function(t,e,r,n){oe.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(Fe.fill,n)},Dr.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},Dr.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},Dr.setRect=function(t,e,r,n,i){t.call(Dr.setPosition,e,r).call(Dr.setSize,n,i)},Dr.translatePoint=function(t,e,r,n){var i=r.c2p(t.x),o=n.c2p(t.y);return!!(a(i)&&a(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",i).attr("y",o):e.attr("transform","translate("+i+","+o+")"),!0)},Dr.translatePoints=function(t,e,r){t.each(function(t){var n=i.select(this);Dr.translatePoint(t,n,e,r)})},Dr.hideOutsideRangePoint=function(t,e,r,n,i,a){e.attr("display",r.isPtWithinRange(t,i)&&n.isPtWithinRange(t,a)?null:"none")},Dr.hideOutsideRangePoints=function(t,e,r){if(e._hasClipOnAxisFalse){r=r||".point,.textpoint";var n=e.xaxis,a=e.yaxis;t.each(function(e){var o=e[0].trace,s=o.xcalendar,l=o.ycalendar;t.selectAll(r).each(function(t){Dr.hideOutsideRangePoint(t,i.select(this),n,a,s,l)})})}},Dr.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:e<1?1:Math.round(e):r||0},Dr.singleLineStyle=function(t,e,r,n,i){e.style("fill","none");var a=(((t||[])[0]||{}).trace||{}).line||{},o=r||a.width||0,s=i||a.dash||"";Fe.stroke(e,n||a.color),Dr.dashLine(e,s,o)},Dr.lineGroupStyle=function(t,e,r,n){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,s=n||a.dash||"";i.select(this).call(Fe.stroke,r||a.color).call(Dr.dashLine,s,o)})},Dr.dashLine=function(t,e,r){r=+r||0,e=Dr.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},Dr.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},Dr.singleFillStyle=function(t){var e=(((i.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;e&&t.call(Fe.fill,e)},Dr.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=i.select(this);try{r.call(Fe.fill,e[0].trace.fillcolor)}catch(e){oe.error(e,t),r.remove()}})},Dr.symbolNames=[],Dr.symbolFuncs=[],Dr.symbolNeedLines={},Dr.symbolNoDot={},Dr.symbolNoFill={},Dr.symbolList=[],Object.keys(tr).forEach(function(t){var e=tr[t];Dr.symbolList=Dr.symbolList.concat([e.n,t,e.n+100,t+"-open"]),Dr.symbolNames[e.n]=t,Dr.symbolFuncs[e.n]=e.f,e.needLine&&(Dr.symbolNeedLines[e.n]=!0),e.noDot?Dr.symbolNoDot[e.n]=!0:Dr.symbolList=Dr.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(Dr.symbolNoFill[e.n]=!0)});var Ir=Dr.symbolNames.length,Or="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function Rr(t,e){var r=t%100;return Dr.symbolFuncs[r](e)+(t>=200?Or:"")}Dr.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=Dr.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=Ir||t>=400?0:Math.floor(Math.max(t,0))};var Br={x1:1,x2:0,y1:0,y2:0},Fr={x1:0,x2:0,y1:1,y2:0};Dr.gradient=function(t,e,r,n,a,o){var s=e._fullLayout._defs.select(".gradients").selectAll("#"+r).data([n+a+o],oe.identity);s.exit().remove(),s.enter().append("radial"===n?"radialGradient":"linearGradient").each(function(){var t=i.select(this);"horizontal"===n?t.attr(Br):"vertical"===n&&t.attr(Fr),t.attr("id",r);var e=c(a),s=c(o);t.append("stop").attr({offset:"0%","stop-color":Fe.tinyRGB(s),"stop-opacity":s.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":Fe.tinyRGB(e),"stop-opacity":e.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},Dr.initGradients=function(t){oe.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},Dr.singlePointStyle=function(t,e,r,n,i,a){var o=r.marker;!function(t,e,r,n,i,a,o,s){if(O.traceIs(r,"symbols")){var l=Cr(r);e.attr("d",function(t){var e;e="various"===t.ms||"various"===a.size?3:Er.isBubble(r)?l(t.ms):(a.size||6)/2,t.mrc=e;var n=Dr.symbolNumber(t.mx||a.symbol)||0;return t.om=n%200>=100,Rr(n,e)})}e.style("opacity",function(t){return(t.mo+1||a.opacity+1)-1});var u,c,h,f=!1;if(t.so?(h=o.outlierwidth,c=o.outliercolor,u=a.outliercolor):(h=(t.mlw+1||o.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,c="mlc"in t?t.mlcc=i(t.mlc):oe.isArrayOrTypedArray(o.color)?Fe.defaultLine:o.color,oe.isArrayOrTypedArray(a.color)&&(u=Fe.defaultLine,f=!0),u="mc"in t?t.mcc=n(t.mc):a.color||"rgba(0,0,0,0)"),t.om)e.call(Fe.stroke,u).style({"stroke-width":(h||1)+"px",fill:"none"});else{e.style("stroke-width",h+"px");var p=a.gradient,d=t.mgt;if(d?f=!0:d=p&&p.type,d&&"none"!==d){var g=t.mgc;g?f=!0:g=p.color;var v="g"+s._fullLayout._uid+"-"+r.uid;f&&(v+="-"+t.i),e.call(Dr.gradient,s,v,d,u,g)}else e.call(Fe.fill,u);h&&e.call(Fe.stroke,c)}}(t,e,r,n,i,o,o.line,a)},Dr.pointStyle=function(t,e,r){if(t.size()){var n=e.marker,a=Dr.tryColorscale(n,""),o=Dr.tryColorscale(n,"line");t.each(function(t){Dr.singlePointStyle(t,i.select(this),e,a,o,r)})}},Dr.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},i=t.marker||{},a=r.marker||{},o=n.marker||{},s=i.opacity,l=a.opacity,u=o.opacity,c=void 0!==l,h=void 0!==u;e.opacityFn=function(t){var e=t.mo,r=void 0!==e;if(r||c||h){if(!t.selected)return h?u:zr*(r?e:s);if(c)return l}};var f=a.color,p=o.color;(f||p)&&(e.colorFn=function(t){if(t.selected){if(f)return f}else if(p)return p});var d=a.size,g=o.size,v=void 0!==d,m=void 0!==g;return(v||m)&&(e.sizeFn=function(t){var e=t.mrc;return t.selected?v?d/2:e:m?g/2:e}),e},Dr.selectedPointStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=Dr.makeSelectedPointStyleFns(e),n=e.marker||{};t.each(function(t){var e=i.select(this),n=r.opacityFn(t);void 0!==n&&e.style("opacity",n)}),r.colorFn&&t.each(function(t){var e=i.select(this),n=r.colorFn(t);n&&Fe.fill(e,n)}),O.traceIs(e,"symbols")&&r.sizeFn&&t.each(function(t){var e=i.select(this),a=t.mx||n.symbol||0,o=r.sizeFn(t);e.attr("d",Rr(Dr.symbolNumber(a),o)),t.mrc2=o})}},Dr.tryColorscale=function(t,e){var r=e?oe.nestedProperty(t,e).get():t,n=r.colorscale,i=r.color;return n&&oe.isArrayOrTypedArray(i)?$e.makeColorScaleFunc($e.extractScale(n,r.cmin,r.cmax)):oe.identity};var Nr={start:1,end:-1,middle:0,bottom:1,top:-1};function jr(t,e,r,n){var a=i.select(t.node().parentNode),o=-1!==e.indexOf("top")?"top":-1!==e.indexOf("bottom")?"bottom":"middle",s=-1!==e.indexOf("left")?"end":-1!==e.indexOf("right")?"start":"middle",l=n?n/.8+1:0,u=(ir.lineCount(t)-1)*Pr+1,c=Nr[s]*l,h=.75*r+Nr[o]*l+(Nr[o]-1)*u*r/2;t.attr("text-anchor",s),a.attr("transform","translate("+c+","+h+")")}function Vr(t,e){var r=t.ts||e.textfont.size;return a(r)&&r>0?r:0}Dr.textPointStyle=function(t,e,r){t.each(function(t){var n=i.select(this),a=oe.extractOption(t,e,"tx","text");if(a){var o=t.tp||e.textposition,s=Vr(t,e);n.call(Dr.font,t.tf||e.textfont.family,s,t.tc||e.textfont.color).text(a).call(ir.convertToTspans,r).call(jr,o,s,t.mrc)}else n.remove()})},Dr.selectedTextStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=e.selected||{},n=e.unselected||{};t.each(function(t){var a,o=i.select(this),s=t.tc||e.textfont.color,l=t.tp||e.textposition,u=Vr(t,e),c=(r.textfont||{}).color,h=(n.textfont||{}).color;t.selected?c&&(a=c):h?a=h:c||(a=Fe.addOpacity(s,zr)),a&&Fe.fill(o,a),jr(o,l,u,t.mrc2||t.mrc)})}};var Ur=.5;function qr(t,e,r,n){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],u=Math.pow(a*a+o*o,Ur/2),c=Math.pow(s*s+l*l,Ur/2),h=(c*c*a-u*u*s)*n,f=(c*c*o-u*u*l)*n,p=3*c*(u+c),d=3*u*(u+c);return[[i.round(e[0]+(p&&h/p),2),i.round(e[1]+(p&&f/p),2)],[i.round(e[0]-(d&&h/d),2),i.round(e[1]-(d&&f/d),2)]]}Dr.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],i=[];for(r=1;r=1e4&&(Dr.savedBBoxes={},Wr=0),r&&(Dr.savedBBoxes[r]=d),Wr++,oe.extendFlat({},d)},Dr.setClipUrl=function(t,e){if(e){if(void 0===Dr.baseUrl){var r=i.select("base");r.size()&&r.attr("href")?Dr.baseUrl=window.location.href.split("#")[0]:Dr.baseUrl=""}t.attr("clip-path","url("+Dr.baseUrl+"#"+e+")")}else t.attr("clip-path",null)},Dr.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},Dr.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||0,r=r||0,a=a.replace(/(\btranslate\(.*?\);?)/,"").trim(),a=(a+=" translate("+e+", "+r+")").trim(),t[i]("transform",a),a},Dr.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},Dr.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",i=t.attr?"attr":"setAttribute",a=t[n]("transform")||"";return e=e||1,r=r||1,a=a.replace(/(\bscale\(.*?\);?)/,"").trim(),a=(a+=" scale("+e+", "+r+")").trim(),t[i]("transform",a),a},Dr.setPointGroupScale=function(t,e,r){var n,i,a;return e=e||1,r=r||1,i=1===e&&1===r?"":" scale("+e+","+r+")",a=/\s*sc.*/,t.each(function(){n=(this.getAttribute("transform")||"").replace(a,""),n=(n+=i).trim(),this.setAttribute("transform",n)}),i};var Xr=/translate\([^)]*\)\s*$/;Dr.setTextPointsScale=function(t,e,r){t.each(function(){var t,n=i.select(this),a=n.select("text");if(a.node()){var o=parseFloat(a.attr("x")||0),s=parseFloat(a.attr("y")||0),l=(n.attr("transform")||"").match(Xr);t=1===e&&1===r?[]:["translate("+o+","+s+")","scale("+e+","+r+")","translate("+-o+","+-s+")"],l&&t.push(l),n.attr("transform",t.join(" "))}})};var Zr={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20},Jr=Se.dash,Kr=b.extendFlat,Qr={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:Kr({},Jr,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:Kr({symbol:{valType:"enumerated",values:Lr.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},showscale:{valType:"boolean",dflt:!1,editType:"calc"},colorbar:Ie,line:Kr({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},Be()),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},Be()),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:E({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}},$r=Qr.marker,tn={r:Qr.r,t:Qr.t,marker:{color:$r.color,size:$r.size,symbol:$r.symbol,opacity:$r.opacity,editType:"calc"}},en=b.extendFlat,rn=_e.overrideAll,nn=en({},ze.domain,{});function an(t,e){return en({},e,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}var on=rn({radialaxis:an(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:nn,orientation:{valType:"number"}}),angularaxis:an(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:nn}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested"),sn={},ln=oe.extendFlat,un=oe.extendDeepAll,cn=oe.isPlainObject,hn="_isSubplotObj",fn="_isLinkedToArray",pn=[hn,fn,"_arrayAttrRegexps","_deprecated"];function dn(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(gn(e[r]))r++;else if(r=a.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!gn(o))return!1;t=a[i][o]}else t=a[i]}else t=a}}return t}function gn(t){return t===Math.round(t)&&t>=0}function vn(t){return function(t){sn.crawl(t,function(t,e,r){sn.isValObject(t)?"data_array"===t.valType?(t.role="data",r[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(r[e+"src"]={valType:"string",editType:"none"}):cn(t)&&(t.role="object")})}(t),function(t){sn.crawl(t,function(t,e,r){if(!t)return;var n=t[fn];if(!n)return;delete t[fn],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(cn(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n=o.length)return!1;n=(r=(O.transformsRegistry[o[s].type]||{}).attributes)&&r[e[2]],a=3}else if("area"===t.type)n=tn[i];else{var l=t._module;if(l||(l=(O.modules[t.type||P.type.dflt]||{})._module),!l)return!1;if(!(n=(r=l.attributes)&&r[i])){var u=l.basePlotModule;u&&u.attributes&&(n=u.attributes[i])}n||(n=P[i])}return dn(n,e,a)},sn.getLayoutValObject=function(t,e){return dn(function(t,e){var r,n,i,a,o=t._basePlotModules;if(o){var s;for(r=0;rn?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},bn={};function _n(t,e,r){var n,i,a,o=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=oe.nestedProperty(n,e.prop).get(),(a=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&a[e.prop]!==i&&(o=!0),a[e.prop]=i,{changed:o,value:i}}function wn(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!oe.isPlainObject(n))return r;i=n}return Mn(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function kn(t,e){var r,n,i,a,o=[];if(n=e[0],i=e[1],r=e[2],a={},"string"==typeof n)a[n]=i;else{if(!oe.isPlainObject(n))return o;a=n,void 0===r&&(r=i)}return void 0===r&&(r=null),Mn(a,function(e,n,i){var a;if(Array.isArray(i)){var s=Math.min(i.length,t.data.length);r&&(s=Math.min(s,r.length)),a=[];for(var l=0;l0?".":"")+i;oe.isPlainObject(a)?Mn(a,e,o,n+1):e(o,i,a)}})}function An(t,e){return"splom"===t?-1:"splom"===e?1:0}bn.manageCommandObserver=function(t,e,r,n){var i={},a=!0;e&&e._commandObserver&&(i=e._commandObserver),i.cache||(i.cache={}),i.lookupTable={};var o=bn.hasSimpleAPICommandBindings(t,r,i.lookupTable);if(e&&e._commandObserver){if(o)return i;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,i}if(o){_n(t,o,i.cache),i.check=function(){if(a){var e=_n(t,o,i.cache);return e.changed&&n&&void 0!==i.lookupTable[e.value]&&(i.disable(),Promise.resolve(n({value:e.value,type:o.type,prop:o.prop,traces:o.traces,index:i.lookupTable[e.value]})).then(i.enable,i.enable)),e.changed}};for(var s=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],l=0;l=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var o=r.select(".js-link-to-tool"),s=r.select(".js-link-spacer"),l=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){zn.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}(t,o),s.text(o.text()&&l.text()?" - ":"")}},zn.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=i.select(t).append("div").attr("id","hiddenform").style("display","none"),n=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"});return n.append("input").attr({type:"text",name:"data"}).node().value=zn.graphJson(t,!1,"keepdata"),n.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var In,On=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],Rn=["year","month","dayMonth","dayMonthYear"];function Bn(t,e){var r,n,i=t.trace,a=i._arrayAttrs,o={};for(r=0;r1&&_.length>1){for(O.getComponentMethod("grid","sizeDefaults")(a,n),r=0;r15&&_.length>15&&0===n.shapes.length&&0===n.images.length,n._hasCartesian=n._has("cartesian"),n._hasGeo=n._has("geo"),n._hasGL3D=n._has("gl3d"),n._hasGL2D=n._has("gl2d"),n._hasTernary=n._has("ternary"),n._hasPie=n._has("pie"),zn.cleanPlot(s,n,o,e,u),zn.linkSubplots(s,n,o,e),Ln(n,e),zn.doAutoMargin(t);var A=xn.list(t);for(r=0;r0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),c=u.left+u.right,h=u.bottom+u.top,f=1-2*s,p=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};n=Math.round(f*(p.width-c)),i=Math.round(f*(p.height-h))}else{var d=l?window.getComputedStyle(t):{};n=parseFloat(d.width)||r.width,i=parseFloat(d.height)||r.height}var g=zn.layoutAttributes.width.min,v=zn.layoutAttributes.height.min;n1,y=!e.height&&Math.abs(r.height-i)>1;(y||m)&&(m&&(r.width=n),y&&(r.height=i)),t._initialAutoSize||(t._initialAutoSize={width:n,height:i}),zn.sanitizeMargins(r)},zn.supplyLayoutModuleDefaults=function(t,e,r,n){var i,a,o,s=O.componentsRegistry,l=e._basePlotModules,u=O.subplotsRegistry.cartesian;for(i in s)(o=s[i]).includeBasePlot&&o.includeBasePlot(t,e);for(var c in l.length||l.push(u),e._has("cartesian")&&(O.getComponentMethod("grid","contentDefaults")(t,e),u.finalizeSubplots(t,e)),e._subplots)e._subplots[c].sort(oe.subplotSort);for(a=0;a.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];n._replotting||zn.doAutoMargin(t)}},zn.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),o=Math.max(e.margin.r||0,0),s=Math.max(e.margin.t||0,0),l=Math.max(e.margin.b||0,0),u=e._pushmargin;if(!1!==e.margin.autoexpand)for(var c in u.base={l:{val:0,size:i},r:{val:1,size:o},t:{val:1,size:s},b:{val:0,size:l}},u){var h=u[c].l||{},f=u[c].b||{},p=h.val,d=h.size,g=f.val,v=f.size;for(var m in u){if(a(d)&&u[m].r){var y=u[m].r.val,x=u[m].r.size;if(y>p){var b=(d*y+(x-e.width)*p)/(y-p),_=(x*(1-p)+(d-e.width)*(1-y))/(y-p);b>=0&&_>=0&&b+_>i+o&&(i=b,o=_)}}if(a(v)&&u[m].t){var w=u[m].t.val,k=u[m].t.size;if(w>g){var M=(v*w+(k-e.height)*g)/(w-g),A=(k*(1-g)+(v-e.height)*(1-w))/(w-g);M>=0&&A>=0&&M+A>l+s&&(l=M,s=A)}}}}if(r.l=Math.round(i),r.r=Math.round(o),r.t=Math.round(s),r.b=Math.round(l),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,!e._replotting&&"{}"!==n&&n!==JSON.stringify(e._size))return O.call("plot",t)},zn.graphJson=function(t,e,r,n,i){(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&zn.supplyDefaults(t);var a=i?t._fullData:t.data,o=i?t._fullLayout:t.layout,s=(t._transitionData||{})._frames;function l(t){if("function"==typeof t)return null;if(oe.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!oe.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;i[e]=l(t[e])}return i}return Array.isArray(t)?t.map(l):oe.isJSDate(t)?oe.ms2DateTimeLocal(+t):t}var u={data:(a||[]).map(function(t){var r=l(t);return e&&delete r.fit,r})};return e||(u.layout=l(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),s&&(u.frames=l(s)),"object"===n?u:JSON.stringify(u)},zn.modifyFrames=function(t,e){var r,n,i,a=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){h=!0}),i.redraw&&t._transitionData._interruptCallbacks.push(function(){return O.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,o,s=0,l=0;function u(){return s++,function(){var r;h||++l!==s||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(i.redraw)return O.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var f=t._fullLayout._basePlotModules,p=!1;if(r)for(o=0;o=0;a--)if(l[a].enabled){r._indexToPoints=l[a]._indexToPoints;break}n&&n.calc&&(o=n.calc(t,r))}Array.isArray(o)&&o[0]||(o=[{x:Cn,y:Cn}]),o[0].t||(o[0].t={}),o[0].trace=r,u[e]=o}}for(f&&jn(o),i=0;i0||h<0){var g={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[c.side];e.attr("transform","translate("+g+")")}}}A.call(T),k&&(w?A.on(".opacity",null):(b=0,_=!0,A.text(l).on("mouseover.opacity",function(){i.select(this).transition().duration(g.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){i.select(this).transition().duration(g.HIDE_PLACEHOLDER).style("opacity",0)})),A.call(ir.makeEditable,{gd:t}).on("edit",function(e){void 0!==u?O.call("restyle",t,s,e,u):O.call("relayout",t,s,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(T)}).on("input",function(t){this.text(t||" ").call(ir.positionText,h.x,h.y)}));return A.classed("js-placeholder",_),p}},Un=/ [XY][0-9]* /;var qn=n.FP_SAFE,Hn=Xn,Gn=Zn,Wn=function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=Xn(t),t._r=t.range.slice(),t._rl=oe.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?Xn(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=oe.extendFlat({},n)}},Yn=function(t,e,r){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!e)return;t._min||(t._min=[]);t._max||(t._max=[]);r||(r={});t._m||t.setScale();var n,i,o,s,l,u,c,h,f,p,d,g,v=e.length,m=r.padded||!1,y=r.tozero&&("linear"===t.type||"-"===t.type),x="log"===t.type,b=!1;function _(t){if(Array.isArray(t))return b=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var w=_((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),k=_((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),M=_(r.vpadplus||r.vpad),A=_(r.vpadminus||r.vpad);if(!b){if(d=1/0,g=-1/0,x)for(n=0;n0&&(d=s),s>g&&s-qn&&(d=s),s>g&&s=b&&(s.extrapad||!m)){p=!1;break}_(n,s.val)&&s.pad<=b&&(m||!s.extrapad)&&(v.splice(i,1),i--)}if(p){var T=y&&0===n;v.push({val:n,pad:T?0:b,extrapad:!T&&m})}}}}var S=Math.min(6,v);for(n=0;n=S;n--)T(n)};function Xn(t){var e,r,n,i,a,o,s,l,u=[],c=t._min[0].val,h=t._max[0].val,f=0,p=!1,d=Zn(t);for(e=1;e0&&s>0&&l/s>f&&(a=n,o=i,f=l/s);if(c===h){var v=c-1,m=c+1;u="tozero"===t.rangemode?c<0?[v,0]:[0,m]:"nonnegative"===t.rangemode?[Math.max(0,v),Math.max(0,m)]:[v,m]}else f&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(a.val>=0&&(a={val:0,pad:0}),o.val<=0&&(o={val:0,pad:0})):"nonnegative"===t.rangemode&&(a.val-f*d(a)<0&&(a={val:0,pad:0}),o.val<0&&(o={val:1,pad:0})),f=(o.val-a.val)/(t._length-d(a)-d(o))),u=[a.val-f*d(a),o.val+f*d(o)]);return u[0]===u[1]&&("tozero"===t.rangemode?u=u[0]<0?[u[0],0]:u[0]>0?[0,u[0]]:[0,1]:(u=[u[0]-1,u[0]+1],"nonnegative"===t.rangemode&&(u[0]=Math.max(0,u[0])))),p&&u.reverse(),oe.simpleMap(u,t.l2r||Number)}function Zn(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function Jn(t){return a(t)&&Math.abs(t)=e}var $n=n.BADNUM,ti=function(t,e){return function(t,e){for(var r,n=0,i=0,o=Math.max(1,(t.length-1)/1e3),s=0;s2*i}(t,e)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}(t)?"category":function(t){if(!t)return!1;for(var e=0;e0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var i=t.range[0],a=t.range[1];return.5*(i+a-3*n*Math.abs(i-a))}return oi}function s(e,r,n){var i=ni(e,n||t.calendar);if(i===oi){if(!a(e))return oi;i=ni(new Date(+e))}return i}function l(e,r,n){return ri(e,r,n||t.calendar)}function u(e){return t._categories[Math.round(e)]}function c(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(a(e))return+e}function h(e){return a(e)?i.round(t._b+t._m*e,2):oi}function f(e){return(e-t._b)/t._m}t.c2l="log"===t.type?o:ii,t.l2c="log"===t.type?si:ii,t.l2p=h,t.p2l=f,t.c2p="log"===t.type?function(t,e){return h(o(t,e))}:h,t.p2c="log"===t.type?function(t){return si(f(t))}:f,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=ei,t.c2d=t.c2r=t.l2d=t.l2r=ii,t.d2p=t.r2p=function(e){return t.l2p(ei(e))},t.p2d=t.p2r=f,t.cleanPos=ii):"log"===t.type?(t.d2r=t.d2l=function(t,e){return o(ei(t),e)},t.r2d=t.r2c=function(t){return si(ei(t))},t.d2c=t.r2l=ei,t.c2d=t.l2r=ii,t.c2r=o,t.l2d=si,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return si(f(t))},t.r2p=function(e){return t.l2p(ei(e))},t.p2r=f,t.cleanPos=ii):"date"===t.type?(t.d2r=t.r2d=oe.identity,t.d2c=t.r2c=t.d2l=t.r2l=s,t.c2d=t.c2r=t.l2d=t.l2r=l,t.d2p=t.r2p=function(e,r,n){return t.l2p(s(e,0,n))},t.p2d=t.p2r=function(t,e,r){return l(f(t),e,r)},t.cleanPos=function(e){return oe.cleanDate(e,oi,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!==e&&void 0!==e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return oi},t.r2d=t.c2d=t.l2d=u,t.d2r=t.d2l_noadd=c,t.r2c=function(e){var r=c(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=ii,t.r2l=c,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return u(f(t))},t.r2p=t.d2p,t.p2r=f,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:ii(t)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var i,o,s=oe.nestedProperty(t,e).get();if(o=(o="date"===t.type?oe.dfltRange(t.calendar):"y"===r?Ee.DFLTRANGEY:n.dfltRange||Ee.DFLTRANGEX).slice(),s&&2===s.length)for("date"===t.type&&(s[0]=oe.cleanDate(s[0],oi,t.calendar),s[1]=oe.cleanDate(s[1],oi,t.calendar)),i=0;i<2;i++)if("date"===t.type){if(!oe.isDateTime(s[i],t.calendar)){t[e]=o;break}if(t.r2l(s[0])===t.r2l(s[1])){var l=oe.constrain(t.r2l(s[0]),oe.MIN_MS+1e3,oe.MAX_MS-1e3);s[0]=t.l2r(l-1e3),s[1]=t.l2r(l+1e3);break}}else{if(!a(s[i])){if(!a(s[1-i])){t[e]=o;break}s[i]=s[1-i]*(i?10:.1)}if(s[i]<-ai?s[i]=-ai:s[i]>ai&&(s[i]=ai),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else oe.nestedProperty(t,e).set(o)},t.setScale=function(n){var i=e._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var a=xn.getFromId({_fullLayout:e},t.overlaying);t.domain=a.domain}var o=n&&t._r?"_r":"range",s=t.calendar;t.cleanRange(o);var l=t.r2l(t[o][0],s),u=t.r2l(t[o][1],s);if("y"===r?(t._offset=i.t+(1-t.domain[1])*i.h,t._length=i.h*(t.domain[1]-t.domain[0]),t._m=t._length/(l-u),t._b=-t._m*u):(t._offset=i.l+t.domain[0]*i.w,t._length=i.w*(t.domain[1]-t.domain[0]),t._m=t._length/(u-l),t._b=-t._m*l),!isFinite(t._m)||!isFinite(t._b))throw e._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,i,a,o,s=t.type,l="date"===s&&e[r+"calendar"];if(r in e){if(n=e[r],o=e._length||n.length,oe.isTypedArray(n)&&("linear"===s||"log"===s)){if(o===n.length)return n;if(n.subarray)return n.subarray(0,o)}for(i=new Array(o),a=0;a2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},bi.saveRangeInitial=function(t,e){for(var r=bi.list(t,"",!0),n=!1,i=0;i.3*f||c(n)||c(i))){var p=r.dtick/2;t+=t+p.8){var o=Number(r.substr(1));a.exactYears>.8&&o%12==0?t=bi.tickIncrement(t,"M6","reverse")+1.5*fi:a.exactMonths>.8?t=bi.tickIncrement(t,"M1","reverse")+15.5*fi:t-=fi/2;var s=bi.tickIncrement(t,r);if(s<=n)return s}return t}(d,t,s.dtick,l,i)),p=d,0;p<=u;)p=bi.tickIncrement(p,s.dtick,!1,i),0;return{start:e.c2r(d,0,i),end:e.c2r(p,0,i),size:s.dtick,_dataSpan:u-l}},bi.prepTicks=function(t){var e=oe.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=oe.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),bi.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),zi(t)},bi.calcTicks=function(t){bi.prepTicks(t);var e=oe.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),o=oe.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],l=1.0001*o[1]-1e-4*o[0],u=Math.min(s,l),c=Math.max(s,l),h=0;Array.isArray(i)||(i=[]);var f="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;ru&&e=n:l<=n)&&!(a.length>s||l===o);l=bi.tickIncrement(l,t.dtick,i,t.calendar))o=l,a.push(l);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&a.pop(),t._tmax=a[a.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(a.length),c=0;c10||"01-01"!==n.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=fi&&i<=10||e>=15*fi)t._tickround="d";else if(e>=di&&i<=16||e>=pi)t._tickround="M";else if(e>=gi&&i<=19||e>=di)t._tickround="S";else{var o=t.l2r(r+e).replace(/^-/,"").length;t._tickround=Math.max(i,o)-20}}else if(a(e)||"L"===e.charAt(0)){var s=t.range.map(t.r2d||Number);a(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var l=Math.max(Math.abs(s[0]),Math.abs(s[1])),u=Math.floor(Math.log(l)/Math.LN10+.01);Math.abs(u)>3&&(Oi(t.exponentformat)&&!Ri(u)?t._tickexponent=3*Math.round((u-1)/3):t._tickexponent=u)}else t._tickround=null}function Di(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}bi.autoTicks=function(t,e){var r;function n(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=oe.dateTick0(t.calendar);var i=2*e;i>ci?(e/=ci,r=n(10),t.dtick="M"+12*Pi(e,r,Mi)):i>hi?(e/=hi,t.dtick="M"+Pi(e,1,Ai)):i>fi?(t.dtick=Pi(e,fi,Si),t.tick0=oe.dateTick0(t.calendar,!0)):i>pi?t.dtick=Pi(e,pi,Ai):i>di?t.dtick=Pi(e,di,Ti):i>gi?t.dtick=Pi(e,gi,Ti):(r=n(10),t.dtick=Pi(e,r,Mi))}else if("log"===t.type){t.tick0=0;var o=oe.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/e);e=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,r=n(10),t.dtick="L"+Pi(e,r,Mi)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):"angular"===t._id?(t.tick0=0,r=1,t.dtick=Pi(e,r,Li)):(t.tick0=0,r=n(10),t.dtick=Pi(e,r,Mi));if(0===t.dtick&&(t.dtick=1),!a(t.dtick)&&"string"!=typeof t.dtick){var l=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(l)}},bi.tickIncrement=function(t,e,r,n){var o=r?-1:1;if(a(e))return t+o*e;var s=e.charAt(0),l=o*Number(e.substr(1));if("M"===s)return oe.incrementMonth(t,l,n);if("L"===s)return Math.log(Math.pow(10,t)+l)/Math.LN10;if("D"===s){var u="D2"===e?Ei:Ci,c=t+.01*o,h=oe.roundUp(oe.mod(c,1),u,r);return Math.floor(c)+Math.log(i.round(Math.pow(10,h),1))/Math.LN10}throw"unrecognized dtick "+String(e)},bi.tickFirst=function(t){var e=t.r2l||Number,r=oe.simpleMap(t.range,e),n=r[1]"+s,t._prevDateHead=s));e.text=l}(t,o,r,l):"log"===t.type?function(t,e,r,n,i){var o=t.dtick,s=e.x,l=t.tickformat;"never"===i&&(i="");!n||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(l||"string"==typeof o&&"L"===o.charAt(0))e.text=Bi(Math.pow(10,s),t,i,n);else if(a(o)||"D"===o.charAt(0)&&oe.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||Oi(t.exponentformat)&&Ri(u)?(e.text=0===u?1:1===u?"10":u>1?"10"+u+"":"10"+vi+-u+"",e.fontSize*=1.25):(e.text=Bi(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);e.text=String(Math.round(Math.pow(10,oe.mod(s,1)))),e.fontSize*=.75}if("D1"===t.dtick){var c=String(e.text).charAt(0);"0"!==c&&"1"!==c||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(s<0?.5:.25)))}}(t,o,0,l,n):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,i){if("radians"!==t.thetaunit||r)e.text=Bi(e.x,t,i,n);else{var a=e.x/180;if(0===a)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,i=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/i),Math.round(r/i)]}(a);if(o[1]>=100)e.text=Bi(oe.deg2rad(e.x),t,i,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["",o[0],"","\u2044","",o[1],"","\u03c0"].join(""),s&&(e.text=vi+e.text)}}}}(t,o,r,l,n):function(t,e,r,n,i){"never"===i?i="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide");e.text=Bi(e.x,t,i,n)}(t,o,0,l,n),t.tickprefix&&!f(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!f(t.showticksuffix)&&(o.text+=t.ticksuffix),o},bi.hoverLabelText=function(t,e,r){if(r!==mi&&r!==e)return bi.hoverLabelText(t,e)+" - "+bi.hoverLabelText(t,r);var n="log"===t.type&&e<=0,i=bi.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":vi+i:i};var Ii=["f","p","n","\u03bc","m","","k","M","G","T"];function Oi(t){return"SI"===t||"B"===t}function Ri(t){return t>14||t<-15}function Bi(t,e,r,n){var i=t<0,o=e._tickround,s=r||e.exponentformat||"B",l=e._tickexponent,u=bi.getTickFormat(e),c=e.separatethousands;if(n){var h={exponentformat:s,dtick:"none"===e.showexponent?e.dtick:a(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};zi(h),o=(Number(h._tickround)||0)+4,l=h._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,vi);var f,p=Math.pow(10,-o)/2;if("none"===s&&(l=0),(t=Math.abs(t))"+f+"":"B"===s&&9===l?t+="B":Oi(s)&&(t+=Ii[l/3+5]));return i?vi+t:t}function Fi(t,e){for(var r=0;r=0,a=u(t,e[1])<=0;return(r||i)&&(n||a)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e=a(n))){r=t.tickformatstops[e];break}break;case"log":for(e=0;e1&&e1)for(n=1;na&&(a=u,o=l)}}return a?i(o):Hi};case"rms":return function(t,e){for(var r=0,a=0,o=0;o0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},aa.prototype.on=aa.prototype.addListener,aa.prototype.once=function(t,e){if(!sa(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},aa.prototype.removeListener=function(t,e){var r,n,i,a;if(!sa(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=(r=this._events[t]).length,n=-1,r===e||sa(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(la(r)){for(a=i;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},aa.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(sa(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},aa.prototype.listeners=function(t){return this._events&&this._events[t]?sa(this._events[t])?[this._events[t]]:this._events[t].slice():[]},aa.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(sa(e))return 1;if(e)return e.length}return 0},aa.listenerCount=function(t,e){return t.listenerCount(e)};var ca,ha=oa.EventEmitter,fa={init:function(t){if(t._ev instanceof ha)return t;var e=new ha,r=new ha;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,i){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,i),e.emit(n,i),r.emit(n,i)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;l4/3-s?o:s},ga.getCursor=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:oe.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:oe.constrain(Math.floor(3*e),0,2),na[e][t]},ga.unhover=ca.wrapped,ga.unhoverRaw=ca.raw,ga.init=function(t){var e,r,n,i,a,o,s,l,u=t.gd,c=1,h=g.DBLCLICKDELAY,f=t.element;u._mouseDownTime||(u._mouseDownTime=0),f.style.pointerEvents="all",f.onmousedown=d,ta?(f._ontouchstart&&f.removeEventListener("touchstart",f._ontouchstart),f._ontouchstart=d,f.addEventListener("touchstart",d,{passive:!1})):f.ontouchstart=d;var p=t.clampFn||function(t,e,r){return Math.abs(t)h&&(c=Math.max(c-1,1)),u._dragged)t.doneFn&&t.doneFn(e);else if(t.clickFn&&t.clickFn(c,o),!l){var r;try{r=new MouseEvent("click",e)}catch(t){var n=ma(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}s.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&O.call("plot",t)}(u),u._dragged=!1}else u._dragged=!1}},ga.coverSlip=va;function ya(t,e,r,n){n=n||oe.identity,Array.isArray(t)&&(e[0][r]=n(t))}var xa={getSubplot:function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},isTraceInSubplots:function(t,e){if("splom"===t.type){for(var r=t.xaxes||[],n=t.yaxes||[],i=0;i=0&&r.index-1&&s.length>d&&(s=d>3?s.substr(0,d-3)+"...":s.substr(0,d))}void 0!==t.zLabel?(void 0!==t.xLabel&&(l+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(l+="y: "+t.yLabel+"
"),l+=(l?"z: ":"")+t.zLabel):w&&t[n+"Label"]===v?l=t[("x"===n?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(l=t.yLabel):l=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(l+=(l?"
":"")+t.text),void 0!==t.extraText&&(l+=(l?"
":"")+t.extraText),""===l&&(""===s&&e.remove(),l=s);var g=e.select("text.nums").call(Lr.font,t.fontFamily||c,t.fontSize||h,t.fontColor||p).text(l).attr("data-notex",1).call(ir.positionText,0,0).call(ir.convertToTspans,r),m=e.select("text.name"),y=0;s&&s!==l?(m.call(Lr.font,t.fontFamily||c,t.fontSize||h,f).text(s).attr("data-notex",1).call(ir.positionText,0,0).call(ir.convertToTspans,r),y=m.node().getBoundingClientRect().width+2*Da):(m.remove(),e.select("rect").remove()),e.select("path").style({fill:f,stroke:p});var k,M,A=g.node().getBoundingClientRect(),T=t.xa._offset+(t.x0+t.x1)/2,S=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),E=Math.abs(t.y1-t.y0),L=A.width+za+Da+y;t.ty0=x-A.top,t.bx=A.width+2*Da,t.by=A.height+2*Da,t.anchor="start",t.txwidth=A.width,t.tx2width=y,t.offset=0,a?(t.pos=T,k=S+E/2+L<=_,M=S-E/2-L>=0,"top"!==t.idealAlign&&k||!M?k?(S+=E/2,t.anchor="start"):t.anchor="middle":(S-=E/2,t.anchor="end")):(t.pos=S,k=T+C/2+L<=b,M=T-C/2-L>=0,"left"!==t.idealAlign&&k||!M?k?(T+=C/2,t.anchor="start"):t.anchor="middle":(T-=C/2,t.anchor="end")),g.attr("text-anchor",t.anchor),y&&m.attr("text-anchor",t.anchor),e.attr("transform","translate("+T+","+S+")"+(a?"rotate("+Sa+")":""))}),C}function Oa(t,e){t.each(function(t){var r=i.select(this);if(t.del)r.remove();else{var n="end"===t.anchor?-1:1,a=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],s=o*(za+Da),l=s+o*(t.txwidth+Da),u=0,c=t.offset;"middle"===t.anchor&&(s-=t.tx2width/2,l+=t.txwidth/2+Da),e&&(c*=-Pa,u=t.offset*La),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(c-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(n*za+u)+","+(za+c)+"v"+(t.by/2-za)+"h"+n*t.bx+"v-"+t.by+"H"+(n*za+u)+"V"+(c-za)+"Z"),a.call(ir.positionText,s+u,c+t.ty0-t.by/2+Da),t.tx2width&&(r.select("text.name").call(ir.positionText,l+o*Da+u,c+t.ty0-t.by/2+Da),r.select("rect").call(Lr.setRect,l+(o-1)*t.tx2width/2+u,c-t.by/2-1,t.tx2width,t.by+2))}})}function Ra(t,e){var r=t.index,n=t.trace||{},i=t.cd[0],a=t.cd[r]||{},o=Array.isArray(r)?function(t,e){return oe.castOption(i,r,t)||oe.extractOption({},n,"",e)}:function(t,e){return oe.extractOption(a,n,t,e)};function s(e,r,n){var i=o(r,n);i&&(t[e]=i)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=oe.constrain(t.x0,0,t.xa._length),t.x1=oe.constrain(t.x1,0,t.xa._length),t.y0=oe.constrain(t.y0,0,t.ya._length),t.y1=oe.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:ui.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:ui.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var l=ui.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+l+" / -"+ui.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+l,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=ui.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+ui.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var c=t.hoverinfo||t.trace.hoverinfo;return"all"!==c&&(-1===(c=Array.isArray(c)?c:c.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===c.indexOf("y")&&(t.yLabel=void 0),-1===c.indexOf("z")&&(t.zLabel=void 0),-1===c.indexOf("text")&&(t.text=void 0),-1===c.indexOf("name")&&(t.name=void 0)),t}function Ba(t,e){var r,n,i=e.container,a=e.fullLayout,o=e.event,s=!!t.hLinePoint,l=!!t.vLinePoint;if(i.selectAll(".spikeline").remove(),l||s){var u=Fe.combine(a.plot_bgcolor,a.paper_bgcolor);if(s){var h,f,p=t.hLinePoint;r=p&&p.xa,"cursor"===(n=p&&p.ya).spikesnap?(h=o.pointerX,f=o.pointerY):(h=r._offset+p.x,f=n._offset+p.y);var d,g,v=c.readability(p.color,u)<1.5?Fe.contrast(u):p.color,m=n.spikemode,y=n.spikethickness,x=n.spikecolor||v,b=n._boundingBox,_=(b.left+b.right)/2q.width||V<0||V>q.height)return da.unhoverRaw(t,e);e.pointerX=e.offsetX,e.pointerY=e.offsetY}if(_="xval"in e?xa.flat(o,e.xval):xa.p2c(p,j),w="yval"in e?xa.flat(o,e.yval):xa.p2c(d,V),!a(_[0])||!a(w[0]))return oe.warn("Fx.hover failed",e,t),da.unhoverRaw(t,e)}var H=1/0;for(M=0;MD&&(B.splice(0,D),H=B[0].distance),c&&0!==R&&0===B.length){z.distance=R,z.index=!1;var Z=T._module.hoverPoints(z,L,P,"closest",s._hoverlayer);if(Z&&(Z=Z.filter(function(t){return t.spikeDistance<=R})),Z&&Z.length){var J,K=Z.filter(function(t){return t.xa.showspikes});if(K.length){var Q=K[0];a(Q.x0)&&a(Q.y0)&&(J=rt(Q),(!N.vLinePoint||N.vLinePoint.spikeDistance>J.spikeDistance)&&(N.vLinePoint=J))}var $=Z.filter(function(t){return t.ya.showspikes});if($.length){var tt=$[0];a(tt.x0)&&a(tt.y0)&&(J=rt(tt),(!N.hLinePoint||N.hLinePoint.spikeDistance>J.spikeDistance)&&(N.hLinePoint=J))}}}}function et(t,e){for(var r,n=null,i=1/0,a=0;a1,gt=Fe.combine(s.plot_bgcolor||Fe.background,s.paper_bgcolor),vt={hovermode:b,rotateLabels:dt,bgColor:gt,container:s._hoverlayer,outerContainer:s._paperdiv,commonLabelOpts:s.hoverlabel,hoverdistance:s.hoverdistance},mt=Ia(B,vt,t);if(function(t,e,r){var n,i,a,o,s,l,u,c=0,h=t.map(function(t,n){var i=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===i._id.charAt(0)?Ea:1)/2,pmin:0,pmax:"x"===i._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function f(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(a<.01)){if(i<-.01){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(u<=0);o--)(l=t[o]).pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(;!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&g.pmin===v.pmin&&g.pmax===v.pmax){for(s=d.length-1;s>=0;s--)d[s].dp+=i;for(p.push.apply(p,d),h.splice(o+1,1),u=0,s=p.length-1;s>=0;s--)u+=p[s].dp;for(a=u/p.length,s=p.length-1;s>=0;s--)p[s].dp-=a;n=!1}else o++}h.forEach(f)}for(o=h.length-1;o>=0;o--){var m=h[o];for(s=m.length-1;s>=0;s--){var y=m[s],x=t[y.i];x.offset=y.dp,x.del=y.del}}}(B,dt?"xa":"ya",s),Oa(mt,dt),e.target&&e.target.tagName){var yt=O.getComponentMethod("annotations","hasClickToShow")(t,ft);Aa(i.select(e.target),yt?"pointer":"")}if(!e.target||n||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}(t,0,ht))return;ht&&t.emit("plotly_unhover",{event:e,points:ht});t.emit("plotly_hover",{event:e,points:t._hoverdata,xaxes:p,yaxes:d,xvals:_,yvals:w})}(t,e,r,n)})},Ta.loneHover=function(t,e){var r={color:t.color||Fe.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},n=i.select(e.container),a=e.outerContainer?i.select(e.outerContainer):n,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||Fe.background,container:n,outerContainer:a},s=Ia([r],o,e.gd);return Oa(s,o.rotateLabels),s.node()};var Na=Ta.hover,ja=function(t,e,r,n){r("hoverlabel.bgcolor",(n=n||{}).bgcolor),r("hoverlabel.bordercolor",n.bordercolor),r("hoverlabel.namelength",n.namelength),oe.coerceFont(r,"hoverlabel.font",n.font)},Va=E({editType:"none"});Va.family.dflt=ia.HOVERFONT,Va.size.dflt=ia.HOVERFONTSIZE;var Ua={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:Va,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}};var qa={moduleType:"component",name:"fx",constants:ia,schema:{layout:Ua},attributes:L,layoutAttributes:Ua,supplyLayoutGlobalDefaults:function(t,e){ja(0,0,function(r,n){return oe.coerce(t,e,Ua,r,n)})},supplyDefaults:function(t,e,r,n){ja(0,0,function(r,n){return oe.coerce(t,e,L,r,n)},n.hoverlabel)},supplyLayoutDefaults:function(t,e,r){function n(r,n){return oe.coerce(t,e,Ua,r,n)}var i;"select"===n("dragmode")&&n("selectdirection"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r0})}function u(t,n){var i=t.seg,a=n.seg,o=i.start,l=i.end,u=a.start,c=a.end;r&&r.checkIntersection(i,a);var h=e.linesIntersect(o,l,u,c);if(!1===h){if(!e.pointsCollinear(o,l,u))return!1;if(e.pointsSame(o,c)||e.pointsSame(l,u))return!1;var f=e.pointsSame(o,u),p=e.pointsSame(l,c);if(f&&p)return n;var d=!f&&e.pointBetween(o,u,c),g=!p&&e.pointBetween(l,u,c);if(f)return g?s(n,l):s(t,c),n;d&&(p||(g?s(n,l):s(t,c)),s(n,o))}else 0===h.alongA&&(-1===h.alongB?s(t,u):0===h.alongB?s(t,h.pt):1===h.alongB&&s(t,c)),0===h.alongB&&(-1===h.alongA?s(n,o):0===h.alongA?s(n,h.pt):1===h.alongA&&s(n,l));return!1}for(var c=[];!i.isEmpty();){var h=i.getHead();if(r&&r.vert(h.pt[0]),h.isStart){r&&r.segmentNew(h.seg,h.primary);var f=l(h),p=f.before?f.before.ev:null,d=f.after?f.after.ev:null;function g(){if(p){var t=u(h,p);if(t)return t}return!!d&&u(h,d)}r&&r.tempStatus(h.seg,!!p&&p.seg,!!d&&d.seg);var v,m,y=g();if(y)t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below)&&(y.seg.myFill.above=!y.seg.myFill.above):y.seg.otherFill=h.seg.myFill,r&&r.segmentUpdate(y.seg),h.other.remove(),h.remove();if(i.getHead()!==h){r&&r.rewind(h.seg);continue}t?(m=null===h.seg.myFill.below||h.seg.myFill.above!==h.seg.myFill.below,h.seg.myFill.below=d?d.seg.myFill.above:n,h.seg.myFill.above=m?!h.seg.myFill.below:h.seg.myFill.below):null===h.seg.otherFill&&(v=d?h.primary===d.primary?d.seg.otherFill.above:d.seg.myFill.above:h.primary?a:n,h.seg.otherFill={above:v,below:v}),r&&r.status(h.seg,!!p&&p.seg,!!d&&d.seg),h.other.status=f.insert(Za.node({ev:h}))}else{var x=h.status;if(null===x)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(o.exists(x.prev)&&o.exists(x.next)&&u(x.prev.ev,x.next.ev),r&&r.statusRemove(x.ev.seg),x.remove(),!h.primary){var b=h.seg.myFill;h.seg.myFill=h.seg.otherFill,h.seg.otherFill=b}c.push(h.seg)}i.getHead().remove()}return r&&r.done(),c}return t?{addRegion:function(t){for(var n,i,a,s=t[t.length-1],l=0;l=-t},pointBetween:function(e,r,n){var i=e[1]-r[1],a=n[0]-r[0],o=e[0]-r[0],s=n[1]-r[1],l=o*a+i*s;return!(l-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])t!=o-i>t&&(a-u)*(i-c)/(o-c)+u-n>t&&(s=!s),a=u,o=c}return s}};return e}();function no(t,e,r){var n=$a.segments(t),i=$a.segments(e),a=r($a.combine(n,i));return $a.polygon(a)}$a={buildLog:function(t){return!0===t?eo=Ya():!1===t&&(eo=!1),!1!==eo&&eo.list},epsilon:function(t){return ro.epsilon(t)},segments:function(t){var e=Ja(!0,ro,eo);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:Ja(!1,ro,eo).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:to.union(t.combined,eo),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:to.intersect(t.combined,eo),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:to.difference(t.combined,eo),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:to.differenceRev(t.combined,eo),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:to.xor(t.combined,eo),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:Ka(t.segments,ro,eo),inverted:t.inverted}},polygonFromGeoJSON:function(t){return Xa.toPolygon($a,t)},polygonToGeoJSON:function(t){return Xa.fromPolygon($a,ro,t)},union:function(t,e){return no(t,e,$a.selectUnion)},intersect:function(t,e){return no(t,e,$a.selectIntersect)},difference:function(t,e){return no(t,e,$a.selectDifference)},differenceRev:function(t,e){return no(t,e,$a.selectDifferenceRev)},xor:function(t,e){return no(t,e,$a.selectXor)}},"object"==typeof window&&(window.PolyBool=$a);var io=$a,ao={},oo=Ht.dot,so=n.BADNUM,lo=ao={};lo.tester=function(t){if(Array.isArray(t[0][0]))return lo.multitester(t);var e,r=t.slice(),n=r[0][0],i=n,a=r[0][1],o=a;for(r.push(r[0]),e=1;ei||l===so||lo||e&&s(t))}:function(t,e){var s=t[0],l=t[1];if(s===so||si||l===so||lo)return!1;var u,c,h,f,p,d=r.length,g=r[0][0],v=r[0][1],m=0;for(u=1;uMath.max(c,g)||l>Math.max(h,v)))if(lu||Math.abs(oo(a,h))>n)return!0;return!1};lo.filter=function(t,e){var r=[t[0]],n=0,i=0;function a(a){t.push(a);var o=r.length,s=n;r.splice(i+1);for(var l=s+1;l1&&a(t.pop());return{addPt:a,raw:t,filtered:r}};var co=xa.makeEventData,ho=xn.getFromId,fo=Tn,po=Ee.MINSELECT,go=ao.filter,vo=ao.tester,mo=ao.multitester;function yo(t){return t._id}function xo(t,e,r){var n,i,a,o;if(r){var s=r.points||[];for(n=0;n=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function Fo(t,e,r,n,i){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",i+"Z")}function No(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:Fe.background,stroke:Fe.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function jo(t,e,r,n,i,a){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),Vo(t,e,i,a)}function Vo(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function Uo(t){i.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function qo(t){Po&&t.data&&t._context.showTips&&(oe.notifier(oe._(t,"Double-click to zoom back out"),"long"),Po=!1)}function Ho(t){return"lasso"===t||"select"===t}function Go(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,Lo)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function Wo(t,e){if(ta){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function Yo(t){var e=[];for(var r in t)e.push(t[r]);return e}var Xo={makeDragBox:function(t,e,r,n,a,o,s,l){var u,h,f,p,d,g,v,m,y,x,b,_,w,k,M,A,T,S=t._fullLayout._zoomlayer,C=s+l==="nsew",E=1===(s+l).length;function L(){if(u=e.xaxis,h=e.yaxis,y=u._length,x=h._length,v=u._offset,m=h._offset,(f={})[u._id]=u,(p={})[h._id]=h,s&&l)for(var r=e.overlays,n=0;nLo||o>Lo?(j="xy",a/y>o/x?(o=a*x/y,I>i?R.t=I-o:R.b=I+o):(a=o*y/x,D>n?R.l=D-a:R.r=D+a),U.attr("d",Go(R))):s():!w||o10||r.scrollWidth-r.clientWidth>10)){clearTimeout(X);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var i,a=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=J.draglayer.select(".nsewdrag").node().getBoundingClientRect(),u=(e.clientX-o.left)/o.width,c=(o.bottom-e.clientY)/o.height;if(A){for(l||(u=.5),i=0;i0;o&&(i="array");var s,l=r("categoryorder",i);"array"===l&&(s=r("categoryarray")),o||"array"!==l||(l=e.categoryorder="trace"),"trace"===l?e._initialCategories=[]:"array"===l?e._initialCategories=s.slice():(s=function(t,e){var r,n,i,a=e.dataAttr||t._id.charAt(0),o={};if(e.axData)r=e.axData;else for(r=[],n=0;nd[1]-.01&&(e.domain=o),oe.noneOrAll(t.domain,e.domain,o)}return r("layer"),e},os=xn.name2id,ss=function(t,e,r,n,i){i&&(e._name=i,e._id=os(i)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var i=function(t,e,r){for(var n=0;n0&&i["_"+r+"axes"][e])return i;if((i[r+"axis"]||r)===e){if(us(i,r))return i;if((i[r]||[]).length||i[r+"0"])return i}}}(e,r,n);if(!i)return;if("histogram"===i.type&&n==={v:"y",h:"x"}[i.orientation||"v"])return void(t.type="linear");var a,o=n+"calendar",s=i[o];if(us(i,n)){var l=ls(i),u=[];for(a=0;a rect").call(Lr.setTranslate,0,0).call(Lr.setScale,1,1),t.plot.call(Lr.setTranslate,e._offset,r._offset).call(Lr.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(Lr.setPointGroupScale,1,1),n.selectAll(".textpoint").call(Lr.setTextPointsScale,1,1),n.call(Lr.hideOutsideRangePoints,t)}function g(e,r){var n,i,o,s=h[e.xaxis._id],l=h[e.yaxis._id],u=[];if(s){i=(n=t._fullLayout[s.axisName])._r,o=s.to,u[0]=(i[0]*(1-r)+r*o[0]-i[0])/(i[1]-i[0])*e.xaxis._length;var c=i[1]-i[0],f=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[2]=e.xaxis._length*(1-r+r*f/c)}else u[0]=0,u[2]=e.xaxis._length;if(l){i=(n=t._fullLayout[l.axisName])._r,o=l.to,u[1]=(i[1]*(1-r)+r*o[1]-i[1])/(i[0]-i[1])*e.yaxis._length;var p=i[1]-i[0],d=o[1]-o[0];n.range[0]=i[0]*(1-r)+r*o[0],n.range[1]=i[1]*(1-r)+r*o[1],u[3]=e.yaxis._length*(1-r+r*d/p)}else u[1]=0,u[3]=e.yaxis._length;!function(e,r){var n,i=[];for(i=[e._id,r._id],n=0;nr.duration?(function(){for(var e={},r=0;r.01?A:function(t,e){return Math.abs(t-e)>=2?A(t):t>e?Math.ceil(t):Math.floor(t)};d=k(d,p=k(p,d)),v=k(v,g=k(g,v))}var M=i.select(this);M.append("path").style("vector-effect","non-scaling-stroke").attr("d","M"+p+","+g+"V"+v+"H"+d+"V"+g+"Z").call(Lr.setClipUrl,e.layerClipId),function(t,e,r,n,i,a,o,s){var l;function u(e,r,n){var i=e.append("text").text(r).attr({class:"bartext bartext-"+l,transform:"","text-anchor":"middle","data-notex":1}).call(Lr.font,n).call(ir.convertToTspans,t);return i}var c=r[0].trace,h=c.orientation,f=function(t,e){var r=Ws(t.text,e);return Ys(Bs,r)}(c,n);if(!f)return;if("none"===(l=function(t,e){var r=Ws(t.textposition,e);return function(t,e,r){return t.coerceNumber&&(e=+e),-1!==t.values.indexOf(e)?e:void 0!==r?r:t.dflt}(Fs,r)}(c,n)))return;var p,d,g,v,m,y,x=function(t,e,r){return Gs(Ns,t.textfont,e,r)}(c,n,t._fullLayout.font),b=function(t,e,r){return Gs(js,t.insidetextfont,e,r)}(c,n,x),_=function(t,e,r){return Gs(Vs,t.outsidetextfont,e,r)}(c,n,x),w=t._fullLayout.barmode,k="stack"===w||"relative"===w,M=r[n],A=!k||M._outmost,T=Math.abs(a-i)-2*Us,S=Math.abs(s-o)-2*Us;"outside"===l&&(A||(l="inside"));if("auto"===l)if(A){l="inside",p=u(e,f,b),d=Lr.bBox(p.node()),g=d.width,v=d.height;var C=g>0&&v>0,E=g<=T&&v<=S,L=g<=S&&v<=T,P="h"===h?T>=g*(S/v):S>=v*(T/g);C&&(E||L||P)?l="inside":(l="outside",p.remove(),p=null)}else l="inside";if(!p&&(p=u(e,f,"outside"===l?_:b),d=Lr.bBox(p.node()),g=d.width,v=d.height,g<=0||v<=0))return void p.remove();"outside"===l?(y="both"===c.constraintext||"outside"===c.constraintext,m=function(t,e,r,n,i,a,o){var s,l="h"===a?Math.abs(n-r):Math.abs(e-t);l>2*Us&&(s=Us);var u=1;o&&(u="h"===a?Math.min(1,l/i.height):Math.min(1,l/i.width));var c,h,f,p,d=(i.left+i.right)/2,g=(i.top+i.bottom)/2;c=u*i.width,h=u*i.height,"h"===a?er?(f=(t+e)/2,p=n+s+h/2):(f=(t+e)/2,p=n-s-h/2);return Hs(d,g,f,p,u,!1)}(i,a,o,s,d,h,y)):(y="both"===c.constraintext||"inside"===c.constraintext,m=function(t,e,r,n,i,a,o){var s,l,u,c,h,f,p,d=i.width,g=i.height,v=(i.left+i.right)/2,m=(i.top+i.bottom)/2,y=Math.abs(e-t),x=Math.abs(n-r);y>2*Us&&x>2*Us?(y-=2*(h=Us),x-=2*h):h=0;d<=y&&g<=x?(f=!1,p=1):d<=x&&g<=y?(f=!0,p=1):dr?(u=(t+e)/2,c=n-h-l/2):(u=(t+e)/2,c=n+h+l/2);return Hs(v,m,u,c,p,f)}(i,a,o,s,d,h,y));p.attr("transform",m)}(t,M,r,u,p,d,g,v),e.layerClipId&&Lr.hideOutsideRangePoint(r[u],M.select("text"),n,o,c.xcalendar,c.ycalendar)}else i.select(this).remove();function A(t){return 0===s.bargap&&0===s.bargroupgap?i.round(Math.round(t)-w,2):t}})}),O.getComponentMethod("errorbars","plot")(l,e),l.each(function(t){var r=!1===t[0].trace.cliponaxis;Lr.setClipUrl(i.select(this),r?null:e.layerClipId)})};function Hs(t,e,r,n,i,a){var o;return i<1?o="scale("+i+") ":(i=1,o=""),"translate("+(r-i*t)+" "+(n-i*e)+")"+o+(a?"rotate("+a+" "+t+" "+e+") ":"")}function Gs(t,e,r,n){var i=Ws((e=e||{}).family,r),o=Ws(e.size,r),s=Ws(e.color,r);return{family:Ys(t.family,i,n.family),size:function(t,e,r){if(a(e)){e=+e;var n=t.min,i=t.max,o=void 0!==n&&ei;if(!o)return e}return void 0!==r?r:t.dflt}(t.size,o,n.size),color:function(t,e,r){return c(e).isValid()?e:void 0!==r?r:t.dflt}(t.color,s,n.color)}}function Ws(t,e){var r;return Array.isArray(t)?eu+s||!a(l))&&(h=!0,sl(c,t))}for(var p=0;p1||0===a.bargap&&0===a.bargroupgap&&!t[0].trace.marker.line.width)&&i.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(e){var r=i.select(this),n=r.selectAll("path"),a=r.selectAll("text"),o=e[0].trace;Lr.pointStyle(n,o,t),Lr.selectedPointStyle(n,o),a.each(function(t){var e,r=i.select(this);function n(r){var n=e[r];return Array.isArray(n)?n[t.i]:n}r.classed("bartext-inside")?e=o.insidetextfont:r.classed("bartext-outside")&&(e=o.outsidetextfont),e||(e=o.textfont),Lr.font(r,n("family"),n("size"),n("color"))}),Lr.selectedTextStyle(a,o)}),O.getComponentMethod("errorbars","style")(r)},pl=b.extendFlat,dl=er.LINE_SPACING,vl={colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"},ml=function(t,e){var r={};function n(){var o=t._fullLayout,s=o._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var l,u,h=i.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),f=[],p=[],d="function"==typeof r.line.color?r.line.color:function(){return r.line.color},g="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},v=r.levels.end+r.levels.size/100,m=r.levels.size,y=1.001*h[0]-.001*h[1],x=1.001*h[1]-.001*h[0];for(u=0;u<1e5&&(l=r.levels.start+u*m,!(m>0?l>=v:l<=v));u++)l>y&&l0?l>=v:l<=v));u++)l>h[0]&&l1){var U=Math.pow(10,Math.floor(Math.log(V)/Math.LN10));N*=U*oe.roundUp(V/U,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(B.tick0=0)}B.dtick=N}B.domain=[z+E,z+T-E],B.setScale();var q=oe.ensureSingle(o._infolayer,"g",e,function(t){t.classed(vl.colorbar,!0).each(function(){var t=i.select(this);t.append("rect").classed(vl.cbbg,!0),t.append("g").classed(vl.cbfills,!0),t.append("g").classed(vl.cblines,!0),t.append("g").classed(vl.cbaxis,!0).classed(vl.crisp,!0),t.append("g").classed(vl.cbtitleunshift,!0).append("g").classed(vl.cbtitle,!0),t.append("rect").classed(vl.cboutline,!0),t.select(".cbtitle").datum(0)})});q.attr("transform","translate("+Math.round(s.l)+","+Math.round(s.t)+")");var H=q.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(s.l)+",-"+Math.round(s.t)+")");B._axislayer=q.select(".cbaxis");var G=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var W,Y=s.l+(r.x+S)*s.w,X=B.titlefont.size;W="top"===r.titleside?(1-(z+T-E))*s.h+s.t+3+.75*X:(1-(z+E))*s.h+s.t-3-.25*X,tt(B._id+"title",{attributes:{x:Y,y:W,"text-anchor":"start"}})}var Z,J,K,Q=oe.syncOrAsync([Sn.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var e=q.select(".cbtitle"),n=e.select("text"),a=[-r.outlinewidth/2,r.outlinewidth/2],l=e.select(".h"+B._id+"title-math-group").node(),u=15.6;if(n.node()&&(u=parseInt(n.node().style.fontSize,10)*dl),l?(G=Lr.bBox(l).height)>u&&(a[1]-=(G-u)/2):n.node()&&!n.classed(vl.jsPlaceholder)&&(G=Lr.bBox(n.node()).height),G){if(G+=5,"top"===r.titleside)B.domain[1]-=G/s.h,a[1]*=-1;else{B.domain[0]+=G/s.h;var v=ir.lineCount(n);a[1]+=(1-v)*u}e.attr("transform","translate("+a+")"),B.setScale()}}q.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(s.h*(1-B.domain[1]))+")"),B._axislayer.attr("transform","translate(0,"+Math.round(-s.t)+")");var m=q.select(".cbfills").selectAll("rect.cbfill").data(p);m.enter().append("rect").classed(vl.cbfill,!0).style("stroke","none"),m.exit().remove(),m.each(function(t,e){var r=[0===e?h[0]:(p[e]+p[e-1])/2,e===p.length-1?h[1]:(p[e]+p[e+1])/2].map(B.c2p).map(Math.round);e!==p.length-1&&(r[1]+=r[1]>r[0]?1:-1);var n=g(t).replace("e-",""),a=c(n).toHexString();i.select(this).attr({x:L,width:Math.max(k,2),y:i.min(r),height:Math.max(i.max(r)-i.min(r),2),fill:a})});var y=q.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?f:[]);return y.enter().append("path").classed(vl.cbline,!0),y.exit().remove(),y.each(function(t){i.select(this).attr("d","M"+L+","+(Math.round(B.c2p(t))+r.line.width/2%1)+"h"+k).call(Lr.lineGroupStyle,r.line.width,d(t),r.line.dash)}),B._axislayer.selectAll("g."+B._id+"tick,path").remove(),B._pos=L+k+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),B.side="right",oe.syncOrAsync([function(){return ui.doTicks(t,B,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var e=B.titlefont.size,n=B._offset+B._length/2,a=s.l+(B.position||0)*s.w+("right"===B.side?10+e*(B.showticklabels?1:.5):-10-e*(B.showticklabels?.5:0));tt("h"+B._id+"title",{avoid:{selection:i.select(t).selectAll("g."+B._id+"tick"),side:r.titleside,offsetLeft:s.l,offsetTop:0,maxShift:o.width},attributes:{x:a,y:n,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},Sn.previousPromises,function(){var n=k+r.outlinewidth/2+Lr.bBox(B._axislayer.node()).width;if((b=H.select("text")).node()&&!b.classed(vl.jsPlaceholder)){var i,a=H.select(".h"+B._id+"title-math-group").node();i=a&&-1!==["top","bottom"].indexOf(r.titleside)?Lr.bBox(a).width:Lr.bBox(H.node()).right-L-s.l,n=Math.max(n,i)}var o=2*r.xpad+n+r.borderwidth+r.outlinewidth/2,l=D-I;q.select(".cbbg").attr({x:L-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:I-C,width:Math.max(o,2),height:Math.max(l+2*C,2)}).call(Fe.fill,r.bgcolor).call(Fe.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),q.selectAll(".cboutline").attr({x:L,y:I+r.ypad+("top"===r.titleside?G:0),width:Math.max(k,2),height:Math.max(l-2*r.ypad-G,2)}).call(Fe.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var u=({center:.5,right:1}[r.xanchor]||0)*o;q.attr("transform","translate("+(s.l-u)+","+s.t+")"),Sn.autoMargin(t,e,{x:r.x,y:r.y,l:o*({right:1,center:.5}[r.xanchor]||0),r:o*({left:1,center:.5}[r.xanchor]||0),t:l*({bottom:1,middle:.5}[r.yanchor]||0),b:l*({top:1,middle:.5}[r.yanchor]||0)})}],t);if(Q&&Q.then&&(t._promises||[]).push(Q),t._context.edits.colorbarPosition)da.init({element:q.node(),gd:t,prepFn:function(){Z=q.attr("transform"),ka(q)},moveFn:function(t,e){q.attr("transform",Z+" translate("+t+","+e+")"),J=da.align(P+t/s.w,M,0,1,r.xanchor),K=da.align(z-e/s.h,T,0,1,r.yanchor);var n=da.getCursor(J,K,r.xanchor,r.yanchor);ka(q,n)},doneFn:function(){ka(q),void 0!==J&&void 0!==K&&O.call("restyle",t,{"colorbar.x":J,"colorbar.y":K},a().index)}});return Q}function $(t,e){return oe.coerce(R,B,ze,t,e)}function tt(e,r){var n,i=a();n=O.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var s={propContainer:B,propName:n,traceIndex:i.index,placeholder:o._dfltTitle.colorbar,containerGroup:q.select(".cbtitle")},l="h"===e.charAt(0)?e.substr(1):"h"+e;q.selectAll("."+l+",."+l+"-math-group").remove(),Vn.draw(t,e,pl(s,r||{}))}o._infolayer.selectAll("g."+e).remove()}function a(){var r,n,i=e.substr(2);for(r=0;r=0&&k0){var A=_[r].sort(Cl),T=A.map(El),S=T.length,C={pos:v[r],pts:A};C.min=T[0],C.max=T[S-1],C.mean=oe.mean(T,S),C.sd=oe.stdev(T,S,C.mean),C.q1=oe.interp(T,.25),C.med=oe.interp(T,.5),C.q3=oe.interp(T,.75),C.lf=Math.min(C.q1,T[Math.min(oe.findBin(2.5*C.q1-1.5*C.q3,T,!0)+1,S-1)]),C.uf=Math.max(C.q3,T[Math.max(oe.findBin(2.5*C.q3-1.5*C.q1,T),0)]),C.lo=4*C.q1-3*C.q3,C.uo=4*C.q3-3*C.q1;var E=1.57*(C.q3-C.q1)/Math.sqrt(S);C.ln=C.med-E,C.un=C.med+E,h.push(C)}return function(t,e){if(oe.isArrayOrTypedArray(e.selectedpoints))for(var r=0;r0?(h[0].t={num:l[f],dPos:m,posLetter:s,valLetter:i,labels:{med:Al(t,"median:"),min:Al(t,"min:"),q1:Al(t,"q1:"),q3:Al(t,"q3:"),max:Al(t,"max:"),mean:"sd"===e.boxmean?Al(t,"mean \xb1 \u03c3:"):Al(t,"mean:"),lf:Al(t,"lower fence:"),uf:Al(t,"upper fence:")}},l[f]++,h):[{t:{empty:!0}}]};function Sl(t,e,r){var n={text:"tx"};for(var i in n)Array.isArray(e[i])&&(t[n[i]]=e[i][r])}function Cl(t,e){return t.v-e.v}function El(t){return t.v}function Ll(t,e,r,n){var i,a=r("y"),o=r("x");if(a&&a.length)i="v",o||r("x0");else{if(!o||!o.length)return void(e.visible=!1);i="h",r("y0")}O.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],n),r("orientation",i)}function Pl(t,e,r,n){var i=n.prefix,a=oe.coerce2(t,e,Ml,"marker.outliercolor"),o=r("marker.line.outliercolor"),s=r(i+"points",a||o?"suspectedoutliers":void 0);s?(r("jitter","all"===s?.3:0),r("pointpos","all"===s?-1.5:0),r("marker.symbol"),r("marker.opacity"),r("marker.size"),r("marker.color",e.line.color),r("marker.line.color"),r("marker.line.width"),"suspectedoutliers"===s&&(r("marker.line.outliercolor",e.marker.color),r("marker.line.outlierwidth")),r("selected.marker.color"),r("unselected.marker.color"),r("selected.marker.size"),r("unselected.marker.size"),r("text")):delete e.marker,r("hoveron"),oe.coerceSelectionMarkerOpacity(e,r)}var zl={supplyDefaults:function(t,e,r,n){function i(r,n){return oe.coerce(t,e,Ml,r,n)}Ll(t,e,i,n),!1!==e.visible&&(i("line.color",(t.marker||{}).color||r),i("line.width"),i("fillcolor",Fe.addOpacity(e.line.color,.5)),i("whiskerwidth"),i("boxmean"),i("notched",void 0!==t.notchwidth)&&i("notchwidth"),Pl(t,e,i,{prefix:"box"}))},handleSampleDefaults:Ll,handlePointsDefaults:Pl};function Dl(t,e,r,n){var i,a,o,s,l,u,c,h,f,p,d,g,v=t.cd,m=t.xa,y=t.ya,x=v[0].trace,b=v[0].t,_="violin"===x.type,w=[],k=b.bdPos,M=b.wHover,A=function(t){return t.pos+b.bPos-u};_&&"both"!==x.side?("positive"===x.side&&(f=function(t){var e=A(t);return qa.inbox(e,e+M,p)}),"negative"===x.side&&(f=function(t){var e=A(t);return qa.inbox(e-M,e,p)})):f=function(t){var e=A(t);return qa.inbox(e-M,e+M,p)},g=_?function(t){return qa.inbox(t.span[0]-l,t.span[1]-l,p)}:function(t){return qa.inbox(t.min-l,t.max-l,p)},"h"===x.orientation?(l=e,u=r,c=g,h=f,i="y",o=y,a="x",s=m):(l=r,u=e,c=f,h=g,i="x",o=m,a="y",s=y);var T=Math.min(1,k/Math.abs(o.r2c(o.range[1])-o.r2c(o.range[0])));function S(t){return(c(t)+h(t))/2}p=t.maxHoverDistance-T,d=t.maxSpikeDistance-T;var C=qa.getDistanceFunction(n,c,h,S);if(qa.getClosest(v,C,t),!1===t.index)return[];var E=v[t.index],L=x.line.color,P=(x.marker||{}).color;Fe.opacity(L)&&x.line.width?t.color=L:Fe.opacity(P)&&x.boxpoints?t.color=P:t.color=x.fillcolor,t[i+"0"]=o.c2p(E.pos+b.bPos-k,!0),t[i+"1"]=o.c2p(E.pos+b.bPos+k,!0),t[i+"LabelVal"]=E.pos;var z=i+"Spike";t.spikeDistance=S(E)*d/p,t[z]=o.c2p(E.pos,!0);var D={},I=["med","min","q1","q3","max"];(x.boxmean||(x.meanline||{}).visible)&&I.push("mean"),(x.boxpoints||x.points)&&I.push("lf","uf");for(var O=0;Ot.uf}),a=Math.max((t.max-t.min)/10,t.q3-t.q1),u=1e-9*a,c=a*jl,h=[],f=0;if(r.jitter){if(0===a)for(f=1,h=new Array(i.length),e=0;et.lo&&(y.so=!0)}return i}).enter().append("path").classed("point",!0).call(Lr.translatePoints,i,a)}function ql(t,e,r,n){var a,o,s=e.pos,l=e.val,u=n.bPos,c=n.bPosPxOffset||0;Array.isArray(n.bdPos)?(a=n.bdPos[0],o=n.bdPos[1]):(a=n.bdPos,o=n.bdPos),t.selectAll("path.mean").data(oe.identity).enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}).each(function(t){var e=s.c2p(t.pos+u,!0)+c,n=s.c2p(t.pos+u-a,!0)+c,h=s.c2p(t.pos+u+o,!0)+c,f=l.c2p(t.mean,!0),p=l.c2p(t.mean-t.sd,!0),d=l.c2p(t.mean+t.sd,!0);"h"===r.orientation?i.select(this).attr("d","M"+f+","+n+"V"+h+("sd"===r.boxmean?"m0,0L"+p+","+e+"L"+f+","+n+"L"+d+","+e+"Z":"")):i.select(this).attr("d","M"+n+","+f+"H"+h+("sd"===r.boxmean?"m0,0L"+e+","+p+"L"+n+","+f+"L"+e+","+d+"Z":""))})}var Hl={plot:function(t,e,r){var n=t._fullLayout,a=e.xaxis,o=e.yaxis;e.plot.select(".boxlayer").selectAll("g.trace.boxes").data(r).enter().append("g").attr("class","trace boxes").each(function(t){var r=t[0],s=r.t,l=r.trace,u=i.select(this);e.isRangePlot||(r.node3=u);var c,h,f=n._numBoxes,p=1-n.boxgap,d="group"===n.boxmode&&f>1,g=s.dPos*p*(1-n.boxgroupgap)/(d?f:1),v=d?2*s.dPos*((s.num+.5)/f-.5)*p:0,m=g*l.whiskerwidth;!0!==l.visible||s.empty?u.remove():("h"===l.orientation?(c=o,h=a):(c=a,h=o),s.bPos=v,s.bdPos=g,s.wdPos=m,s.wHover=s.dPos*(d?p/f:1),Vl(u,{pos:c,val:h},l,s),l.boxpoints&&Ul(u,{x:a,y:o},l,s),l.boxmean&&ql(u,{pos:c,val:h},l,s))})},plotBoxAndWhiskers:Vl,plotPoints:Ul,plotBoxMean:ql},Gl=function(t,e){var r,n,i=t.cd,a=t.xaxis,o=t.yaxis,s=[];if(!1===e)for(r=0;r0;){var a=r%10;n=(0===a?"":t[a]+e[i])+n,i++,r=Math.floor(r/10)}return 0===n.indexOf(t[1]+e[1])&&(n=n.substr(1)),n||t[0]}}}),eu(iu.prototype,{newDate:function(t,e,r){return this._calendar.newDate(null==t?this:t,e,r)},year:function(t){return 0===arguments.length?this._year:this.set(t,"y")},month:function(t){return 0===arguments.length?this._month:this.set(t,"m")},day:function(t){return 0===arguments.length?this._day:this.set(t,"d")},date:function(t,e,r){if(!this._calendar.isValid(t,e,r))throw(lu.local.invalidDate||lu.regionalOptions[""].invalidDate).replace(/\{0\}/,this._calendar.local.name);return this._year=t,this._month=e,this._day=r,this},leapYear:function(){return this._calendar.leapYear(this)},epoch:function(){return this._calendar.epoch(this)},formatYear:function(){return this._calendar.formatYear(this)},monthOfYear:function(){return this._calendar.monthOfYear(this)},weekOfYear:function(){return this._calendar.weekOfYear(this)},daysInYear:function(){return this._calendar.daysInYear(this)},dayOfYear:function(){return this._calendar.dayOfYear(this)},daysInMonth:function(){return this._calendar.daysInMonth(this)},dayOfWeek:function(){return this._calendar.dayOfWeek(this)},weekDay:function(){return this._calendar.weekDay(this)},extraInfo:function(){return this._calendar.extraInfo(this)},add:function(t,e){return this._calendar.add(this,t,e)},set:function(t,e){return this._calendar.set(this,t,e)},compareTo:function(t){if(this._calendar.name!==t._calendar.name)throw(lu.local.differentCalendars||lu.regionalOptions[""].differentCalendars).replace(/\{0\}/,this._calendar.local.name).replace(/\{1\}/,t._calendar.local.name);var e=this._year!==t._year?this._year-t._year:this._month!==t._month?this.monthOfYear()-t.monthOfYear():this._day-t._day;return 0===e?0:e<0?-1:1},calendar:function(){return this._calendar},toJD:function(){return this._calendar.toJD(this)},fromJD:function(t){return this._calendar.fromJD(t)},toJSDate:function(){return this._calendar.toJSDate(this)},fromJSDate:function(t){return this._calendar.fromJSDate(t)},toString:function(){return(this.year()<0?"-":"")+au(Math.abs(this.year()),4)+"-"+au(this.month(),2)+"-"+au(this.day(),2)}}),eu(ou.prototype,{_validateLevel:0,newDate:function(t,e,r){return null==t?this.today():(t.year&&(this._validate(t,e,r,lu.local.invalidDate||lu.regionalOptions[""].invalidDate),r=t.day(),e=t.month(),t=t.year()),new iu(this,t,e,r))},today:function(){return this.fromJSDate(new Date)},epoch:function(t){return this._validate(t,this.minMonth,this.minDay,lu.local.invalidYear||lu.regionalOptions[""].invalidYear).year()<0?this.local.epochs[0]:this.local.epochs[1]},formatYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,lu.local.invalidYear||lu.regionalOptions[""].invalidYear);return(e.year()<0?"-":"")+au(Math.abs(e.year()),4)},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,lu.local.invalidYear||lu.regionalOptions[""].invalidYear),12},monthOfYear:function(t,e){var r=this._validate(t,e,this.minDay,lu.local.invalidMonth||lu.regionalOptions[""].invalidMonth);return(r.month()+this.monthsInYear(r)-this.firstMonth)%this.monthsInYear(r)+this.minMonth},fromMonthOfYear:function(t,e){var r=(e+this.firstMonth-2*this.minMonth)%this.monthsInYear(t)+this.minMonth;return this._validate(t,r,this.minDay,lu.local.invalidMonth||lu.regionalOptions[""].invalidMonth),r},daysInYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,lu.local.invalidYear||lu.regionalOptions[""].invalidYear);return this.leapYear(e)?366:365},dayOfYear:function(t,e,r){var n=this._validate(t,e,r,lu.local.invalidDate||lu.regionalOptions[""].invalidDate);return n.toJD()-this.newDate(n.year(),this.fromMonthOfYear(n.year(),this.minMonth),this.minDay).toJD()+1},daysInWeek:function(){return 7},dayOfWeek:function(t,e,r){var n=this._validate(t,e,r,lu.local.invalidDate||lu.regionalOptions[""].invalidDate);return(Math.floor(this.toJD(n))+2)%this.daysInWeek()},extraInfo:function(t,e,r){return this._validate(t,e,r,lu.local.invalidDate||lu.regionalOptions[""].invalidDate),{}},add:function(t,e,r){return this._validate(t,this.minMonth,this.minDay,lu.local.invalidDate||lu.regionalOptions[""].invalidDate),this._correctAdd(t,this._add(t,e,r),e,r)},_add:function(t,e,r){if(this._validateLevel++,"d"===r||"w"===r){var n=t.toJD()+e*("w"===r?this.daysInWeek():1),i=t.calendar().fromJD(n);return this._validateLevel--,[i.year(),i.month(),i.day()]}try{var a=t.year()+("y"===r?e:0),o=t.monthOfYear()+("m"===r?e:0);i=t.day();"y"===r?(t.month()!==this.fromMonthOfYear(a,o)&&(o=this.newDate(a,t.month(),this.minDay).monthOfYear()),o=Math.min(o,this.monthsInYear(a)),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o)))):"m"===r&&(!function(t){for(;oe-1+t.minMonth;)a++,o-=e,e=t.monthsInYear(a)}(this),i=Math.min(i,this.daysInMonth(a,this.fromMonthOfYear(a,o))));var s=[a,this.fromMonthOfYear(a,o),i];return this._validateLevel--,s}catch(t){throw this._validateLevel--,t}},_correctAdd:function(t,e,r,n){if(!(this.hasYearZero||"y"!==n&&"m"!==n||0!==e[0]&&t.year()>0==e[0]>0)){var i={y:[1,1,"y"],m:[1,this.monthsInYear(-1),"m"],w:[this.daysInWeek(),this.daysInYear(-1),"d"],d:[1,this.daysInYear(-1),"d"]}[n],a=r<0?-1:1;e=this._add(t,r*i[0]+a*i[1],i[2])}return t.date(e[0],e[1],e[2])},set:function(t,e,r){this._validate(t,this.minMonth,this.minDay,lu.local.invalidDate||lu.regionalOptions[""].invalidDate);var n="y"===r?e:t.year(),i="m"===r?e:t.month(),a="d"===r?e:t.day();return"y"!==r&&"m"!==r||(a=Math.min(a,this.daysInMonth(n,i))),t.date(n,i,a)},isValid:function(t,e,r){this._validateLevel++;var n=this.hasYearZero||0!==t;if(n){var i=this.newDate(t,e,this.minDay);n=e>=this.minMonth&&e-this.minMonth=this.minDay&&r-this.minDay13.5?13:1),u=i-(l>2.5?4716:4715);return u<=0&&u--,this.newDate(u,l,s)},toJSDate:function(t,e,r){var n=this._validate(t,e,r,lu.local.invalidDate||lu.regionalOptions[""].invalidDate),i=new Date(n.year(),n.month()-1,n.day());return i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setMilliseconds(0),i.setHours(i.getHours()>12?i.getHours()+2:0),i},fromJSDate:function(t){return this.newDate(t.getFullYear(),t.getMonth()+1,t.getDate())}});var lu=ru=new nu;lu.cdate=iu,lu.baseCalendar=ou,lu.calendars.gregorian=su;var uu=ru.instance();function cu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}cu.prototype=new ru.baseCalendar,eu(cu.prototype,{name:"Chinese",jdEpoch:1721425.5,hasYearZero:!1,minMonth:0,firstMonth:0,minDay:1,regionalOptions:{"":{name:"Chinese",epochs:["BEC","EC"],monthNumbers:function(t,e){if("string"==typeof t){var r=t.match(fu);return r?r[0]:""}var n=this._validateYear(t),i=t.month(),a=""+this.toChineseMonth(n,i);return e&&a.length<2&&(a="0"+a),this.isIntercalaryMonth(n,i)&&(a+="i"),a},monthNames:function(t){if("string"==typeof t){var e=t.match(pu);return e?e[0]:""}var r=this._validateYear(t),n=t.month(),i=["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"][this.toChineseMonth(r,n)-1];return this.isIntercalaryMonth(r,n)&&(i="\u95f0"+i),i},monthNamesShort:function(t){if("string"==typeof t){var e=t.match(du);return e?e[0]:""}var r=this._validateYear(t),n=t.month(),i=["\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u5341\u4e00","\u5341\u4e8c"][this.toChineseMonth(r,n)-1];return this.isIntercalaryMonth(r,n)&&(i="\u95f0"+i),i},parseMonth:function(t,e){t=this._validateYear(t);var r,n=parseInt(e);if(isNaN(n))"\u95f0"===e[0]&&(r=!0,e=e.substring(1)),"\u6708"===e[e.length-1]&&(e=e.substring(0,e.length-1)),n=1+["\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d","\u4e03","\u516b","\u4e5d","\u5341","\u5341\u4e00","\u5341\u4e8c"].indexOf(e);else{var i=e[e.length-1];r="i"===i||"I"===i}return this.toMonthIndex(t,n,r)},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:!1}},_validateYear:function(t,e){if(t.year&&(t=t.year()),"number"!=typeof t||t<1888||t>2111)throw e.replace(/\{0\}/,this.local.name);return t},toMonthIndex:function(t,e,r){var n=this.intercalaryMonth(t);if(r&&e!==n||e<1||e>12)throw ru.local.invalidMonth.replace(/\{0\}/,this.local.name);return n?!r&&e<=n?e-1:e:e-1},toChineseMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);if(e<0||e>(r?12:11))throw ru.local.invalidMonth.replace(/\{0\}/,this.local.name);return r?e>13},isIntercalaryMonth:function(t,e){t.year&&(e=(t=t.year()).month());var r=this.intercalaryMonth(t);return!!r&&r===e},leapYear:function(t){return 0!==this.intercalaryMonth(t)},weekOfYear:function(t,e,r){var n,i=this._validateYear(t,ru.local.invalidyear),a=vu[i-vu[0]],o=a>>9&4095,s=a>>5&15,l=31&a;(n=uu.newDate(o,s,l)).add(4-(n.dayOfWeek()||7),"d");var u=this.toJD(t,e,r)-n.toJD();return 1+Math.floor(u/7)},monthsInYear:function(t){return this.leapYear(t)?13:12},daysInMonth:function(t,e){t.year&&(e=t.month(),t=t.year()),t=this._validateYear(t);var r=gu[t-gu[0]];if(e>(r>>13?12:11))throw ru.local.invalidMonth.replace(/\{0\}/,this.local.name);return r&1<<12-e?30:29},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,a,r,ru.local.invalidDate);t=this._validateYear(n.year()),e=n.month(),r=n.day();var i=this.isIntercalaryMonth(t,e),a=this.toChineseMonth(t,e),o=function(t,e,r,n,i){var a,o,s;if("object"==typeof t)o=t,a=e||{};else{var l="number"==typeof t&&t>=1888&&t<=2111;if(!l)throw new Error("Lunar year outside range 1888-2111");var u="number"==typeof e&&e>=1&&e<=12;if(!u)throw new Error("Lunar month outside range 1 - 12");var c,h="number"==typeof r&&r>=1&&r<=30;if(!h)throw new Error("Lunar day outside range 1 - 30");"object"==typeof n?(c=!1,a=n):(c=!!n,a=i||{}),o={year:t,month:e,day:r,isIntercalary:c}}s=o.day-1;var f,p=gu[o.year-gu[0]],d=p>>13;f=d?o.month>d?o.month:o.isIntercalary?o.month:o.month-1:o.month-1;for(var g=0;g>9&4095,(m>>5&15)-1,(31&m)+s);return a.year=y.getFullYear(),a.month=1+y.getMonth(),a.day=y.getDate(),a}(t,a,r,i);return uu.toJD(o.year,o.month,o.day)},fromJD:function(t){var e=uu.fromJD(t),r=function(t,e,r,n){var i,a;if("object"==typeof t)i=t,a=e||{};else{var o="number"==typeof t&&t>=1888&&t<=2111;if(!o)throw new Error("Solar year outside range 1888-2111");var s="number"==typeof e&&e>=1&&e<=12;if(!s)throw new Error("Solar month outside range 1 - 12");var l="number"==typeof r&&r>=1&&r<=31;if(!l)throw new Error("Solar day outside range 1 - 31");i={year:t,month:e,day:r},a=n||{}}var u=vu[i.year-vu[0]],c=i.year<<9|i.month<<5|i.day;a.year=c>=u?i.year:i.year-1,u=vu[a.year-vu[0]];var h,f=new Date(u>>9&4095,(u>>5&15)-1,31&u),p=new Date(i.year,i.month-1,i.day);h=Math.round((p-f)/864e5);var d,g=gu[a.year-gu[0]];for(d=0;d<13;d++){var v=g&1<<12-d?30:29;if(h>13;!m||d=2&&n<=6},extraInfo:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return{century:xu[Math.floor((n.year()-1)/100)+1]||""}},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return t=n.year()+(n.year()<0?1:0),e=n.month(),(r=n.day())+(e>1?16:0)+(e>2?32*(e-2):0)+400*(t-1)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t+.5)-Math.floor(this.jdEpoch)-1;var e=Math.floor(t/400)+1;t-=400*(e-1),t+=t>15?16:0;var r=Math.floor(t/32)+1,n=t-32*(r-1)+1;return this.newDate(e<=0?e-1:e,r,n)}});var xu={20:"Fruitbat",21:"Anchovy"};ru.calendars.discworld=yu;function bu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}bu.prototype=new ru.baseCalendar,eu(bu.prototype,{name:"Ethiopian",jdEpoch:1724220.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Ethiopian",epochs:["BEE","EE"],monthNames:["Meskerem","Tikemet","Hidar","Tahesas","Tir","Yekatit","Megabit","Miazia","Genbot","Sene","Hamle","Nehase","Pagume"],monthNamesShort:["Mes","Tik","Hid","Tah","Tir","Yek","Meg","Mia","Gen","Sen","Ham","Neh","Pag"],dayNames:["Ehud","Segno","Maksegno","Irob","Hamus","Arb","Kidame"],dayNamesShort:["Ehu","Seg","Mak","Iro","Ham","Arb","Kid"],dayNamesMin:["Eh","Se","Ma","Ir","Ha","Ar","Ki"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);return(t=e.year()+(e.year()<0?1:0))%4==3||t%4==-1},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear||ru.regionalOptions[""].invalidYear),13},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(13===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return(t=n.year())<0&&t++,n.day()+30*(n.month()-1)+365*(t-1)+Math.floor(t/4)+this.jdEpoch-1},fromJD:function(t){var e=Math.floor(t)+.5-this.jdEpoch,r=Math.floor((e-Math.floor((e+366)/1461))/365)+1;r<=0&&r--,e=Math.floor(t)+.5-this.newDate(r,1,1).toJD();var n=Math.floor(e/30)+1,i=e-30*(n-1)+1;return this.newDate(r,n,i)}}),ru.calendars.ethiopian=bu;function _u(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function wu(t,e){return t-e*Math.floor(t/e)}_u.prototype=new ru.baseCalendar,eu(_u.prototype,{name:"Hebrew",jdEpoch:347995.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29,29],hasYearZero:!1,minMonth:1,firstMonth:7,minDay:1,regionalOptions:{"":{name:"Hebrew",epochs:["BAM","AM"],monthNames:["Nisan","Iyar","Sivan","Tammuz","Av","Elul","Tishrei","Cheshvan","Kislev","Tevet","Shevat","Adar","Adar II"],monthNamesShort:["Nis","Iya","Siv","Tam","Av","Elu","Tis","Che","Kis","Tev","She","Ada","Ad2"],dayNames:["Yom Rishon","Yom Sheni","Yom Shlishi","Yom Revi'i","Yom Chamishi","Yom Shishi","Yom Shabbat"],dayNamesShort:["Ris","She","Shl","Rev","Cha","Shi","Sha"],dayNamesMin:["Ri","She","Shl","Re","Ch","Shi","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);return this._leapYear(e.year())},_leapYear:function(t){return wu(7*(t=t<0?t+1:t)+1,19)<7},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear),this._leapYear(t.year?t.year():t)?13:12},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return t=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear).year(),this.toJD(-1===t?1:t+1,7,1)-this.toJD(t,7,1)},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,ru.local.invalidMonth),12===e&&this.leapYear(t)?30:8===e&&5===wu(this.daysInYear(t),10)?30:9===e&&3===wu(this.daysInYear(t),10)?29:this.daysPerMonth[e-1]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},extraInfo:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return{yearType:(this.leapYear(n)?"embolismic":"common")+" "+["deficient","regular","complete"][this.daysInYear(n)%10-3]}},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);t=n.year(),e=n.month(),r=n.day();var i=t<=0?t+1:t,a=this.jdEpoch+this._delay1(i)+this._delay2(i)+r+1;if(e<7){for(var o=7;o<=this.monthsInYear(t);o++)a+=this.daysInMonth(t,o);for(o=1;o=this.toJD(-1===e?1:e+1,7,1);)e++;for(var r=tthis.toJD(e,r,this.daysInMonth(e,r));)r++;var n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),ru.calendars.hebrew=_u;function ku(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}ku.prototype=new ru.baseCalendar,eu(ku.prototype,{name:"Islamic",jdEpoch:1948439.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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\u012bs","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:!1}},leapYear:function(t){return(11*this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear).year()+14)%30<11},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){return this.leapYear(t)?355:354},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return t=n.year(),e=n.month(),r=n.day(),t=t<=0?t+1:t,r+Math.ceil(29.5*(e-1))+354*(t-1)+Math.floor((3+11*t)/30)+this.jdEpoch-1},fromJD:function(t){t=Math.floor(t)+.5;var e=Math.floor((30*(t-this.jdEpoch)+10646)/10631);e=e<=0?e-1:e;var r=Math.min(12,Math.ceil((t-29-this.toJD(e,1,1))/29.5)+1),n=t-this.toJD(e,r,1)+1;return this.newDate(e,r,n)}}),ru.calendars.islamic=ku;function Mu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Mu.prototype=new ru.baseCalendar,eu(Mu.prototype,{name:"Julian",jdEpoch:1721423.5,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Julian",epochs:["BC","AD"],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:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);return(t=e.year()<0?e.year()+1:e.year())%4==0},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(4-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return t=n.year(),e=n.month(),r=n.day(),t<0&&t++,e<=2&&(t--,e+=12),Math.floor(365.25*(t+4716))+Math.floor(30.6001*(e+1))+r-1524.5},fromJD:function(t){var e=Math.floor(t+.5)+1524,r=Math.floor((e-122.1)/365.25),n=Math.floor(365.25*r),i=Math.floor((e-n)/30.6001),a=i-Math.floor(i<14?1:13),o=r-Math.floor(a>2?4716:4715),s=e-n-Math.floor(30.6001*i);return o<=0&&o--,this.newDate(o,a,s)}}),ru.calendars.julian=Mu;function Au(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}function Tu(t,e){return t-e*Math.floor(t/e)}function Su(t,e){return Tu(t-1,e)+1}Au.prototype=new ru.baseCalendar,eu(Au.prototype,{name:"Mayan",jdEpoch:584282.5,hasYearZero:!0,minMonth:0,firstMonth:0,minDay:0,regionalOptions:{"":{name:"Mayan",epochs:["",""],monthNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],monthNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"],dayNames:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesShort:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],dayNamesMin:["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],digits:null,dateFormat:"YYYY.m.d",firstDay:0,isRTL:!1,haabMonths:["Pop","Uo","Zip","Zotz","Tzec","Xul","Yaxkin","Mol","Chen","Yax","Zac","Ceh","Mac","Kankin","Muan","Pax","Kayab","Cumku","Uayeb"],tzolkinMonths:["Imix","Ik","Akbal","Kan","Chicchan","Cimi","Manik","Lamat","Muluc","Oc","Chuen","Eb","Ben","Ix","Men","Cib","Caban","Etznab","Cauac","Ahau"]}},leapYear:function(t){return this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear),!1},formatYear:function(t){t=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear).year();var e=Math.floor(t/400);return t%=400,t+=t<0?400:0,e+"."+Math.floor(t/20)+"."+t%20},forYear:function(t){if((t=t.split(".")).length<3)throw"Invalid Mayan year";for(var e=0,r=0;r19||r>0&&n<0)throw"Invalid Mayan year";e=20*e+n}return e},monthsInYear:function(t){return this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear),18},weekOfYear:function(t,e,r){return this._validate(t,e,r,ru.local.invalidDate),0},daysInYear:function(t){return this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear),360},daysInMonth:function(t,e){return this._validate(t,e,this.minDay,ru.local.invalidMonth),20},daysInWeek:function(){return 5},dayOfWeek:function(t,e,r){return this._validate(t,e,r,ru.local.invalidDate).day()},weekDay:function(t,e,r){return this._validate(t,e,r,ru.local.invalidDate),!0},extraInfo:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate).toJD(),i=this._toHaab(n),a=this._toTzolkin(n);return{haabMonthName:this.local.haabMonths[i[0]-1],haabMonth:i[0],haabDay:i[1],tzolkinDayName:this.local.tzolkinMonths[a[0]-1],tzolkinDay:a[0],tzolkinTrecena:a[1]}},_toHaab:function(t){var e=Tu((t-=this.jdEpoch)+8+340,365);return[Math.floor(e/20)+1,Tu(e,20)]},_toTzolkin:function(t){return[Su((t-=this.jdEpoch)+20,20),Su(t+4,13)]},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);return n.day()+20*n.month()+360*n.year()+this.jdEpoch},fromJD:function(t){t=Math.floor(t)+.5-this.jdEpoch;var e=Math.floor(t/360);t%=360,t+=t<0?360:0;var r=Math.floor(t/20),n=t%20;return this.newDate(e,r,n)}}),ru.calendars.mayan=Au;function Cu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Cu.prototype=new ru.baseCalendar;var Eu=ru.instance("gregorian");eu(Cu.prototype,{name:"Nanakshahi",jdEpoch:2257673.5,daysPerMonth:[31,31,31,31,31,30,30,30,30,30,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{name:"Nanakshahi",epochs:["BN","AN"],monthNames:["Chet","Vaisakh","Jeth","Harh","Sawan","Bhadon","Assu","Katak","Maghar","Poh","Magh","Phagun"],monthNamesShort:["Che","Vai","Jet","Har","Saw","Bha","Ass","Kat","Mgr","Poh","Mgh","Pha"],dayNames:["Somvaar","Mangalvar","Budhvaar","Veervaar","Shukarvaar","Sanicharvaar","Etvaar"],dayNamesShort:["Som","Mangal","Budh","Veer","Shukar","Sanichar","Et"],dayNamesMin:["So","Ma","Bu","Ve","Sh","Sa","Et"],digits:null,dateFormat:"dd-mm-yyyy",firstDay:0,isRTL:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear||ru.regionalOptions[""].invalidYear);return Eu.leapYear(e.year()+(e.year()<1?1:0)+1469)},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(1-(n.dayOfWeek()||7),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidMonth);(t=n.year())<0&&t++;for(var i=n.day(),a=1;a=this.toJD(e+1,1,1);)e++;for(var r=t-Math.floor(this.toJD(e,1,1)+.5)+1,n=1;r>this.daysInMonth(e,n);)r-=this.daysInMonth(e,n),n++;return this.newDate(e,n,r)}}),ru.calendars.nanakshahi=Cu;function Lu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Lu.prototype=new ru.baseCalendar,eu(Lu.prototype,{name:"Nepali",jdEpoch:1700709.5,daysPerMonth:[31,31,32,32,31,30,30,29,30,29,30,30],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,daysPerYear:365,regionalOptions:{"":{name:"Nepali",epochs:["BBS","ABS"],monthNames:["Baisakh","Jestha","Ashadh","Shrawan","Bhadra","Ashwin","Kartik","Mangsir","Paush","Mangh","Falgun","Chaitra"],monthNamesShort:["Bai","Je","As","Shra","Bha","Ash","Kar","Mang","Pau","Ma","Fal","Chai"],dayNames:["Aaitabaar","Sombaar","Manglbaar","Budhabaar","Bihibaar","Shukrabaar","Shanibaar"],dayNamesShort:["Aaita","Som","Mangl","Budha","Bihi","Shukra","Shani"],dayNamesMin:["Aai","So","Man","Bu","Bi","Shu","Sha"],digits:null,dateFormat:"dd/mm/yyyy",firstDay:1,isRTL:!1}},leapYear:function(t){return this.daysInYear(t)!==this.daysPerYear},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){if(t=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear).year(),void 0===this.NEPALI_CALENDAR_DATA[t])return this.daysPerYear;for(var e=0,r=this.minMonth;r<=12;r++)e+=this.NEPALI_CALENDAR_DATA[t][r];return e},daysInMonth:function(t,e){return t.year&&(e=t.month(),t=t.year()),this._validate(t,e,this.minDay,ru.local.invalidMonth),void 0===this.NEPALI_CALENDAR_DATA[t]?this.daysPerMonth[e-1]:this.NEPALI_CALENDAR_DATA[t][e]},weekDay:function(t,e,r){return 6!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);t=n.year(),e=n.month(),r=n.day();var i=ru.instance(),a=0,o=e,s=t;this._createMissingCalendarData(t);var l=t-(o>9||9===o&&r>=this.NEPALI_CALENDAR_DATA[s][0]?56:57);for(9!==e&&(a=r,o--);9!==o;)o<=0&&(o=12,s--),a+=this.NEPALI_CALENDAR_DATA[s][o],o--;return 9===e?(a+=r-this.NEPALI_CALENDAR_DATA[s][0])<0&&(a+=i.daysInYear(l)):a+=this.NEPALI_CALENDAR_DATA[s][9]-this.NEPALI_CALENDAR_DATA[s][0],i.newDate(l,1,1).add(a,"d").toJD()},fromJD:function(t){var e=ru.instance().fromJD(t),r=e.year(),n=e.dayOfYear(),i=r+56;this._createMissingCalendarData(i);for(var a=9,o=this.NEPALI_CALENDAR_DATA[i][0],s=this.NEPALI_CALENDAR_DATA[i][a]-o+1;n>s;)++a>12&&(a=1,i++),s+=this.NEPALI_CALENDAR_DATA[i][a];var l=this.NEPALI_CALENDAR_DATA[i][a]-(s-n);return this.newDate(i,a,l)},_createMissingCalendarData:function(t){var e=this.daysPerMonth.slice(0);e.unshift(17);for(var r=t-1;r0?474:473))%2820+474+38)%2816<682},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-(n.dayOfWeek()+1)%7,"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(12===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);t=n.year(),e=n.month(),r=n.day();var i=t-(t>=0?474:473),a=474+zu(i,2820);return r+(e<=7?31*(e-1):30*(e-1)+6)+Math.floor((682*a-110)/2816)+365*(a-1)+1029983*Math.floor(i/2820)+this.jdEpoch-1},fromJD:function(t){var e=(t=Math.floor(t)+.5)-this.toJD(475,1,1),r=Math.floor(e/1029983),n=zu(e,1029983),i=2820;if(1029982!==n){var a=Math.floor(n/366),o=zu(n,366);i=Math.floor((2134*a+2816*o+2815)/1028522)+a+1}var s=i+2820*r+474;s=s<=0?s-1:s;var l=t-this.toJD(s,1,1)+1,u=l<=186?Math.ceil(l/31):Math.ceil((l-6)/30),c=t-this.toJD(s,u,1)+1;return this.newDate(s,u,c)}}),ru.calendars.persian=Pu,ru.calendars.jalali=Pu;var Du=ru.instance();function Iu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Iu.prototype=new ru.baseCalendar,eu(Iu.prototype,{name:"Taiwan",jdEpoch:2419402.5,yearsOffset:1911,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);t=this._t2gYear(e.year());return Du.leapYear(t)},weekOfYear:function(t,e,r){var n=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);t=this._t2gYear(n.year());return Du.weekOfYear(t,n.month(),n.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);t=this._t2gYear(n.year());return Du.toJD(t,n.month(),n.day())},fromJD:function(t){var e=Du.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)},_g2tYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)}}),ru.calendars.taiwan=Iu;var Ou=ru.instance();function Ru(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Ru.prototype=new ru.baseCalendar,eu(Ru.prototype,{name:"Thai",jdEpoch:1523098.5,yearsOffset:543,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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:!1}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);t=this._t2gYear(e.year());return Ou.leapYear(t)},weekOfYear:function(t,e,r){var n=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);t=this._t2gYear(n.year());return Ou.weekOfYear(t,n.month(),n.day())},daysInMonth:function(t,e){var r=this._validate(t,e,this.minDay,ru.local.invalidMonth);return this.daysPerMonth[r.month()-1]+(2===r.month()&&this.leapYear(r.year())?1:0)},weekDay:function(t,e,r){return(this.dayOfWeek(t,e,r)||7)<6},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate);t=this._t2gYear(n.year());return Ou.toJD(t,n.month(),n.day())},fromJD:function(t){var e=Ou.fromJD(t),r=this._g2tYear(e.year());return this.newDate(r,e.month(),e.day())},_t2gYear:function(t){return t-this.yearsOffset-(t>=1&&t<=this.yearsOffset?1:0)},_g2tYear:function(t){return t+this.yearsOffset+(t>=-this.yearsOffset&&t<=-1?1:0)}}),ru.calendars.thai=Ru;function Bu(t){this.local=this.regionalOptions[t||""]||this.regionalOptions[""]}Bu.prototype=new ru.baseCalendar,eu(Bu.prototype,{name:"UmmAlQura",hasYearZero:!1,minMonth:1,firstMonth:1,minDay:1,regionalOptions:{"":{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\u0101th\u0101\u2019","Yawm al-Arba\u2018\u0101\u2019","Yawm al-Kham\u012bs","Yawm al-Jum\u2018a","Yawm al-Sabt"],dayNamesMin:["Ah","Ith","Th","Ar","Kh","Ju","Sa"],digits:null,dateFormat:"yyyy/mm/dd",firstDay:6,isRTL:!0}},leapYear:function(t){var e=this._validate(t,this.minMonth,this.minDay,ru.local.invalidYear);return 355===this.daysInYear(e.year())},weekOfYear:function(t,e,r){var n=this.newDate(t,e,r);return n.add(-n.dayOfWeek(),"d"),Math.floor((n.dayOfYear()-1)/7)+1},daysInYear:function(t){for(var e=0,r=1;r<=12;r++)e+=this.daysInMonth(t,r);return e},daysInMonth:function(t,e){for(var r=this._validate(t,e,this.minDay,ru.local.invalidMonth).toJD()-24e5+.5,n=0,i=0;ir)return Fu[n]-Fu[n-1];n++}return 30},weekDay:function(t,e,r){return 5!==this.dayOfWeek(t,e,r)},toJD:function(t,e,r){var n=this._validate(t,e,r,ru.local.invalidDate),i=12*(n.year()-1)+n.month()-15292;return n.day()+Fu[i-1]-1+24e5-.5},fromJD:function(t){for(var e=t-24e5+.5,r=0,n=0;ne);n++)r++;var i=r+15292,a=Math.floor((i-1)/12),o=a+1,s=i-12*a,l=e-Fu[r-1]+1;return this.newDate(o,s,l)},isValid:function(t,e,r){var n=ru.baseCalendar.prototype.isValid.apply(this,arguments);return n&&(n=(t=null!=t.year?t.year:t)>=1276&&t<=1500),n},_validate:function(t,e,r,n){var i=ru.baseCalendar.prototype._validate.apply(this,arguments);if(i.year<1276||i.year>1500)throw n.replace(/\{0\}/,this.local.name);return i}}),ru.calendars.ummalqura=Bu;var Fu=[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,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,68e3,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];eu(ru.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"}),ru.local=ru.regionalOptions[""],eu(ru.cdate.prototype,{formatDate:function(t,e){return"string"!=typeof t&&(e=t,t=""),this._calendar.formatDate(t||"",this,e)}}),eu(ru.baseCalendar.prototype,{UNIX_EPOCH:ru.instance().newDate(1970,1,1).toJD(),SECS_PER_DAY:86400,TICKS_EPOCH:ru.instance().jdEpoch,TICKS_PER_DAY:864e9,ATOM:"yyyy-mm-dd",COOKIE:"D, dd M yyyy",FULL:"DD, MM d, yyyy",ISO_8601:"yyyy-mm-dd",JULIAN:"J",RFC_822:"D, d M yy",RFC_850:"DD, dd-M-yy",RFC_1036:"D, d M yy",RFC_1123:"D, d M yyyy",RFC_2822:"D, d M yyyy",RSS:"D, d M yy",TICKS:"!",TIMESTAMP:"@",W3C:"yyyy-mm-dd",formatDate:function(t,e,r){if("string"!=typeof t&&(r=e,e=t,t=""),!e)return"";if(e.calendar()!==this)throw ru.local.invalidFormat||ru.regionalOptions[""].invalidFormat;t=t||this.local.dateFormat;for(var n,i,a,o,s=(r=r||{}).dayNamesShort||this.local.dayNamesShort,l=r.dayNames||this.local.dayNames,u=r.monthNumbers||this.local.monthNumbers,c=r.monthNamesShort||this.local.monthNamesShort,h=r.monthNames||this.local.monthNames,f=(r.calculateWeek||this.local.calculateWeek,function(e,r){for(var n=1;_+n1}),p=function(t,e,r,n){var i=""+e;if(f(t,n))for(;i.length1},y=function(t,r){var n=m(t,r),i=[2,3,n?4:2,n?4:2,10,11,20]["oyYJ@!".indexOf(t)+1],a=new RegExp("^-?\\d{1,"+i+"}"),o=e.substring(M).match(a);if(!o)throw(ru.local.missingNumberAt||ru.regionalOptions[""].missingNumberAt).replace(/\{0\}/,M);return M+=o[0].length,parseInt(o[0],10)},x=this,b=function(){if("function"==typeof s){m("m");var t=s.call(x,e.substring(M));return M+=t.length,t}return y("m")},_=function(t,r,n,i){for(var a=m(t,i)?n:r,o=0;o-1){f=1,p=d;for(var S=this.daysInMonth(h,f);p>S;S=this.daysInMonth(h,f))f++,p-=S}return c>-1?this.fromJD(c):this.newDate(h,f,p)},determineDate:function(t,e,r,n,i){r&&"object"!=typeof r&&(i=n,n=r,r=null),"string"!=typeof n&&(i=n,n="");var a=this;return e=e?e.newDate():null,t=null==t?e:"string"==typeof t?function(t){try{return a.parseDate(n,t,i)}catch(t){}for(var e=((t=t.toLowerCase()).match(/^c/)&&r?r.newDate():null)||a.today(),o=/([+-]?[0-9]+)\s*(d|w|m|y)?/g,s=o.exec(t);s;)e.add(parseInt(s[1],10),s[2]||"d"),s=o.exec(t);return e}(t):"number"==typeof t?isNaN(t)||t===1/0||t===-1/0?e:a.today().add(t,"d"):a.newDate(t)}});var Nu=ru,ju=n.EPOCHJD,Vu=n.ONEDAY,Uu={valType:"enumerated",values:Object.keys(Nu.calendars),editType:"calc",dflt:"gregorian"},qu=function(t,e,r,n){var i={};return i[r]=Uu,oe.coerce(t,e,i,r,n)},Hu="##",Gu={d:{0:"dd","-":"d"},e:{0:"d","-":"d"},a:{0:"D","-":"D"},A:{0:"DD","-":"DD"},j:{0:"oo","-":"o"},W:{0:"ww","-":"w"},m:{0:"mm","-":"m"},b:{0:"M","-":"M"},B:{0:"MM","-":"MM"},y:{0:"yy","-":"yy"},Y:{0:"yyyy","-":"yyyy"},U:Hu,w:Hu,c:{0:"D M d %X yyyy","-":"D M d %X yyyy"},x:{0:"mm/dd/yyyy","-":"mm/dd/yyyy"}};var Wu={};function Yu(t){var e=Wu[t];return e||(e=Wu[t]=Nu.instance(t))}function Xu(t){return oe.extendFlat({},Uu,{description:t})}function Zu(t){return"Sets the calendar system to use with `"+t+"` date data."}var Ju={xcalendar:Xu(Zu("x"))},Ku=oe.extendFlat({},Ju,{ycalendar:Xu(Zu("y"))}),Qu=oe.extendFlat({},Ku,{zcalendar:Xu(Zu("z"))}),$u=Xu(["Sets the calendar system to use for `range` and `tick0`","if this is a date axis. This does not set the calendar for","interpreting data on this axis, that's specified in the trace","or via the global `layout.calendar`"].join(" ")),tc={moduleType:"component",name:"calendars",schema:{traces:{scatter:Ku,bar:Ku,box:Ku,heatmap:Ku,contour:Ku,histogram:Ku,histogram2d:Ku,histogram2dcontour:Ku,scatter3d:Qu,surface:Qu,mesh3d:Qu,scattergl:Ku,ohlc:Ju,candlestick:Ju},layout:{calendar:Xu(["Sets the default calendar system to use for interpreting and","displaying dates throughout the plot."].join(" "))},subplots:{xaxis:{calendar:$u},yaxis:{calendar:$u},scene:{xaxis:{calendar:$u},yaxis:{calendar:$u},zaxis:{calendar:$u}},polar:{radialaxis:{calendar:$u}}},transforms:{filter:{valuecalendar:Xu(["Sets the calendar system to use for `value`, if it is a date."].join(" ")),targetcalendar:Xu(["Sets the calendar system to use for `target`, if it is an","array of dates. If `target` is a string (eg *x*) we use the","corresponding trace attribute (eg `xcalendar`) if it exists,","even if `targetcalendar` is provided."].join(" "))}}},layoutAttributes:Uu,handleDefaults:qu,handleTraceDefaults:function(t,e,r,n){for(var i=0;ih):c=y>g,h=y;var x=i(g,v,m,y);x.pos=d,x.yc=(g+y)/2,x.i=p,x.dir=c?"increasing":"decreasing",u&&(x.tx=e.text[p]),f.push(x)}}return ui.expand(n,s.concat(o),{padded:!0}),f.length&&(f[0].t={labels:{open:uc(t,"open:")+" ",high:uc(t,"high:")+" ",low:uc(t,"low:")+" ",close:uc(t,"close:")+" "}}),f}var pc={calc:function(t,e){var r=ui.getFromId(t,e.xaxis),n=ui.getFromId(t,e.yaxis),i=function(t,e,r){var n=r._minDiff;if(!n){var i,a=t._fullData,o=[];for(n=1/0,i=0;i"),t.y0=t.y1=o.c2p(k.yc,!0),[t]},bc=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[],s=n[0].t.bPos||0;if(!1===e)for(r=0;r=10)return null;var n=1/0;var i=-1/0;var a=e.length;for(var o=0;o0&&(p=t.dxydi([],i-1,o,0,s),m.push(l[0]+p[0]/3),x.push(l[1]+p[1]/3),d=t.dxydi([],i-1,o,1,s),m.push(f[0]-d[0]/3),x.push(f[1]-d[1]/3)),m.push(f[0]),x.push(f[1]),l=f;else for(i=t.a2i(n),u=Math.floor(Math.max(0,Math.min(C-2,i))),h=i-u,b.length=C,b.crossLength=E,b.xy=function(e){return t.evalxy([],i,e)},b.dxy=function(e,r){return t.dxydj([],u,e,h,r)},a=0;a0&&(g=t.dxydj([],u,a-1,h,0),m.push(l[0]+g[0]/3),x.push(l[1]+g[1]/3),v=t.dxydj([],u,a-1,h,1),m.push(f[0]-v[0]/3),x.push(f[1]-v[1]/3)),m.push(f[0]),x.push(f[1]),l=f;return b.axisLetter=e,b.axis=y,b.crossAxis=k,b.value=n,b.constvar=r,b.index=c,b.x=m,b.y=x,b.smoothing=k.smoothing,b}function z(n){var i,a,o,s,l,u=[],c=[],h={};if(h.length=m.length,h.crossLength=w.length,"b"===e)for(o=Math.max(0,Math.min(E-2,n)),l=Math.min(1,Math.max(0,n-o)),h.xy=function(e){return t.evalxy([],e,n)},h.dxy=function(e,r){return t.dxydi([],e,o,r,l)},i=0;im.length-1||x.push(Cc(z(i),{color:y.gridcolor,width:y.gridwidth}));for(c=l;cm.length-1||p<0||p>m.length-1))for(d=m[a],g=m[p],n=0;nm[m.length-1]||b.push(Cc(P(f),{color:y.minorgridcolor,width:y.minorgridwidth}));y.startline&&_.push(Cc(z(0),{color:y.startlinecolor,width:y.startlinewidth})),y.endline&&_.push(Cc(z(m.length-1),{color:y.endlinecolor,width:y.endlinewidth}))}else{for(o=5e-15,l=(s=[Math.floor((m[m.length-1]-y.tick0)/y.dtick*(1+o)),Math.ceil((m[0]-y.tick0)/y.dtick/(1+o))].sort(function(t,e){return t-e}))[0],u=s[1],c=l;c<=u;c++)h=y.tick0+y.dtick*c,x.push(Cc(P(h),{color:y.gridcolor,width:y.gridwidth}));for(c=l-1;cm[m.length-1]||b.push(Cc(P(f),{color:y.minorgridcolor,width:y.minorgridwidth}));y.startline&&_.push(Cc(P(m[0]),{color:y.startlinecolor,width:y.startlinewidth})),y.endline&&_.push(Cc(P(m[m.length-1]),{color:y.endlinecolor,width:y.endlinewidth}))}},Lc=b.extendFlat,Pc=function(t,e){var r,n,i,a=e._labels=[],o=e._gridlines;for(r=0;rs&&tu&&el||ec},t.setScale=function(){var e,r,s,l=t._x,u=t._y,c=function(t,e,r,n,i,a){var o,s,l,u,c,h,f,p,d,g,v=r[0].length,m=r.length,y=i?3*v-2:v,x=a?3*m-2:m;for(t=Rc(t,x),e=Rc(e,x),l=0;le[n-1]|or[i-1]))return[!1,!1];var l=t.a2i(a),u=t.b2j(o),c=t.evalxy([],l,u);if(s){var h,f,p,d,g=0,v=0,m=[];ae[n-1]?(h=n-2,f=1,g=(a-e[n-1])/(e[n-1]-e[n-2])):f=l-(h=Math.max(0,Math.min(n-2,Math.floor(l)))),or[i-1]?(p=i-2,d=1,v=(o-r[i-1])/(r[i-1]-r[i-2])):d=u-(p=Math.max(0,Math.min(i-2,Math.floor(u)))),g&&(t.dxydi(m,h,p,f,d),c[0]+=m[0]*g,c[1]+=m[1]*g),v&&(t.dxydj(m,h,p,f,d),c[0]+=m[0]*v,c[1]+=m[1]*v)}return c},t.c2p=function(t,e,r){return[e.c2p(t[0]),r.c2p(t[1])]},t.p2x=function(t,e,r){return[e.p2c(t[0]),r.p2c(t[1])]},t.dadi=function(t){var r=Math.max(0,Math.min(e.length-2,t));return e[r+1]-e[r]},t.dbdj=function(t){var e=Math.max(0,Math.min(r.length-2,t));return r[e+1]-r[e]},t.dxyda=function(e,r,n,i){var a=t.dxydi(null,e,r,n,i),o=t.dadi(e,n);return[a[0]/o,a[1]/o]},t.dxydb=function(e,r,n,i){var a=t.dxydj(null,e,r,n,i),o=t.dbdj(r,i);return[a[0]/o,a[1]/o]},t.dxyda_rough=function(e,r,n){var i=h*(n||.1),a=t.ab2xy(e+i,r,!0),o=t.ab2xy(e-i,r,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dxydb_rough=function(e,r,n){var i=f*(n||.1),a=t.ab2xy(e,r+i,!0),o=t.ab2xy(e,r-i,!0);return[.5*(a[0]-o[0])/i,.5*(a[1]-o[1])/i]},t.dpdx=function(t){return t._m},t.dpdy=function(t){return t._m}},Vc=function(t,e,r){var n,i,a,o=[],s=[],l=t[0].length,u=t.length;function c(e,r){var n,i=0,a=0;return e>0&&void 0!==(n=t[r][e-1])&&(a++,i+=n),e0&&void 0!==(n=t[r-1][e])&&(a++,i+=n),r0&&i0&&n1e-5);return oe.log("Smoother converged to",k,"after",M,"iterations"),t},Uc=function(t,e){var r,n,i,o,s,l;function u(t){if(a(t))return+t}if(e){for(r=0,s=0;se.length&&(t=t.slice(0,e.length)):t=[],n=0;n90&&(p-=180,l=-l),{angle:p,flip:l,p:t.c2p(n,e,r),offsetMultplier:u}};function Qc(t,e,r){var n=r[0],i=r[0].trace,a=e.xaxis,o=e.yaxis,s=i.aaxis,l=i.baxis,u=t._fullLayout,c=e.plot.selectAll(".carpetlayer"),h=u._clips,f=oe.ensureSingle(c,"g","carpet"+i.uid).classed("trace",!0),p=oe.ensureSingle(f,"g","minorlayer"),d=oe.ensureSingle(f,"g","majorlayer"),g=oe.ensureSingle(f,"g","boundarylayer"),v=oe.ensureSingle(f,"g","labellayer");f.style("opacity",i.opacity),$c(a,o,d,s,"a",s._gridlines),$c(a,o,d,l,"b",l._gridlines),$c(a,o,p,s,"a",s._minorgridlines),$c(a,o,p,l,"b",l._minorgridlines),$c(a,o,g,s,"a-boundary",s._boundarylines),$c(a,o,g,l,"b-boundary",l._boundarylines),function(t,e,r,n,i,a,o,s){var l,u,c,h;l=.5*(r.a[0]+r.a[r.a.length-1]),u=r.b[0],c=r.ab2xy(l,u,!0),h=r.dxyda_rough(l,u),void 0===o.angle&&oe.extendFlat(o,Kc(r,i,a,c,r.dxydb_rough(l,u)));nh(t,e,r,n,c,h,r.aaxis,i,a,o,"a-title"),l=r.a[0],u=.5*(r.b[0]+r.b[r.b.length-1]),c=r.ab2xy(l,u,!0),h=r.dxydb_rough(l,u),void 0===s.angle&&oe.extendFlat(s,Kc(r,i,a,c,r.dxyda_rough(l,u)));nh(t,e,r,n,c,h,r.baxis,i,a,s,"b-title")}(t,v,i,n,a,o,th(t,a,o,i,n,v,s._labels,"a-label"),th(t,a,o,i,n,v,l._labels,"b-label")),function(t,e,r,n,i){var a,o,s,l,u=r.select("#"+t._clipPathId);u.size()||(u=r.append("clipPath").classed("carpetclip",!0));var c=oe.ensureSingle(u,"path","carpetboundary"),h=e.clipsegments,f=[];for(l=0;l0?"start":"end","data-notex":1}).call(Lr.font,a.font).text(a.text).call(ir.convertToTspans,t),p=Lr.bBox(this);f.attr("transform","translate("+s.p[0]+","+s.p[1]+") rotate("+s.angle+")translate("+a.axis.labelpadding*u+","+.3*p.height+")"),c=Math.max(c,p.width+a.axis.labelpadding)}),u.exit().remove(),h.maxExtent=c,h}var eh=er.LINE_SPACING,rh=(1-er.MID_SHIFT)/eh+1;function nh(t,e,r,n,a,o,s,l,u,c,h){var f=[];s.title&&f.push(s.title);var p=e.selectAll("text."+h).data(f),d=c.maxExtent;p.enter().append("text").classed(h,!0),p.each(function(){var e=Kc(r,l,u,a,o);-1===["start","both"].indexOf(s.showticklabels)&&(d=0);var n=s.titlefont.size;d+=n+s.titleoffset;var h=(c.angle+(c.flip<0?180:0)-e.angle+450)%360,f=h>90&&h<270,p=i.select(this);p.text(s.title||"").call(ir.convertToTspans,t),f&&(d=(-ir.lineCount(p)+rh)*eh*n-d),p.attr("transform","translate("+e.p[0]+","+e.p[1]+") rotate("+e.angle+") translate(0,"+d+")").classed("user-select-none",!0).attr("text-anchor","middle").call(Lr.font,s.titlefont)}),p.exit().remove()}var ih={};ih.attributes=Ac,ih.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,Ac,r,n)}e._clipPathId="clip"+e.uid+"carpet";var a=i("color",z.defaultLine);if(oe.coerceFont(i,"font"),i("carpet"),Yc(t,e,n,i,a),e.a&&e.b){e.a.length<3&&(e.aaxis.smoothing=0),e.b.length<3&&(e.baxis.smoothing=0);var o=function(t,e,r){var n=r("x"),i=r("y");return e._cheater=!n,!!n||!!i}(0,e,i);e._cheater&&i("cheaterslope"),o||(e.visible=!1)}else e.visible=!1},ih.plot=function(t,e,r){for(var n=0;n=0;i--)a[c-i]=t[h][i],o[c-i]=e[h][i];for(s.push({x:a,y:o,bicubic:l}),i=h,a=[],o=[];i>=0;i--)a[h-i]=t[i][0],o[h-i]=e[i][0];return s.push({x:a,y:o,bicubic:u}),s}(e._xctrl,e._yctrl,i,a),h.x=o,h.y=s,h.a=u,h.b=c,[h]},ih.animatable=!0,ih.isContainer=!0,ih.moduleType="trace",ih.name="carpet",ih.basePlotModule=ps,ih.categories=["cartesian","svg","carpet","carpetAxis","notLegendIsolatable"],ih.meta={};var ah=ih,oh={exports:{}};!function(t,e){"object"==typeof oh.exports?e(oh.exports):"function"==typeof aH&&aH.amd?aH(["exports"],e):e(t.topojson=t.topojson||{})}(this,function(t){"use strict";var e=function(t){return t},r=function(t){if(null==(r=t.transform))return e;var r,n,i,a=r.scale[0],o=r.scale[1],s=r.translate[0],l=r.translate[1];return function(t,e){return e||(n=i=0),t[0]=(n+=t[0])*a+s,t[1]=(i+=t[1])*o+l,t}},n=function(t){var e=t.bbox;function n(t){l[0]=t[0],l[1]=t[1],s(l),l[0]h&&(h=l[0]),l[1]f&&(f=l[1])}function i(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(i);break;case"Point":n(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(n)}}if(!e){var a,o,s=r(t),l=new Array(2),u=1/0,c=u,h=-u,f=-u;for(o in t.arcs.forEach(function(t){for(var e=-1,r=t.length;++eh&&(h=l[0]),l[1]f&&(f=l[1])}),t.objects)i(t.objects[o]);e=t.bbox=[u,c,h,f]}return e},i=function(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r};function a(t,e){var r=e.id,n=e.bbox,i=null==e.properties?{}:e.properties,a=o(t,e);return null==r&&null==n?{type:"Feature",properties:i,geometry:a}:null==n?{type:"Feature",id:r,properties:i,geometry:a}:{type:"Feature",id:r,bbox:n,properties:i,geometry:a}}function o(t,e){var n=r(t),a=t.arcs;function o(t,e){e.length&&e.pop();for(var r=a[t<0?~t:t],o=0,s=r.length;o1)n=function(t,e,r){var n,i=[],a=[];function o(t){var e=t<0?~t:t;(a[e]||(a[e]=[])).push({i:t,g:n})}function s(t){t.forEach(o)}function l(t){t.forEach(s)}return function t(e){switch(n=e,e.type){case"GeometryCollection":e.geometries.forEach(t);break;case"LineString":s(e.arcs);break;case"MultiLineString":case"Polygon":l(e.arcs);break;case"MultiPolygon":e.arcs.forEach(l)}}(e),a.forEach(null==r?function(t){i.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&i.push(t[0].i)}),i}(0,e,r);else for(i=0,n=new Array(a=t.arcs.length);i1)for(var a,o,u=1,c=l(i[0]);uc&&(o=i[0],i[0]=i[u],i[u]=o,c=a);return i})}}var c=function(t,e){for(var r=0,n=t.length;r>>1;t[i]=2))throw new Error("n must be \u22652");if(t.transform)throw new Error("already quantized");var r,i=n(t),a=i[0],o=(i[2]-a)/(e-1)||1,s=i[1],l=(i[3]-s)/(e-1)||1;function u(t){t[0]=Math.round((t[0]-a)/o),t[1]=Math.round((t[1]-s)/l)}function c(t){switch(t.type){case"GeometryCollection":t.geometries.forEach(c);break;case"Point":u(t.coordinates);break;case"MultiPoint":t.coordinates.forEach(u)}}for(r in t.arcs.forEach(function(t){for(var e,r,n,i=1,u=1,c=t.length,h=t[0],f=h[0]=Math.round((h[0]-a)/o),p=h[1]=Math.round((h[1]-s)/l);in^p>n&&r<(f-u)*(n-c)/(p-c)+u&&(i=!i)}return i}(t[0],r))return t.push(e),!0})||t.push([e])}),a=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},u={Point:o,MultiPoint:o,LineString:s,MultiLineString:s,Polygon:l,MultiPolygon:l,Sphere:l};function c(){}var h=1e-6,f=h*h,p=Math.PI,d=p/2,g=(Math.sqrt(p),p/180),v=180/p;function m(t){return t>1?d:t<-1?-d:Math.asin(t)}function y(t){return t>1?0:t<-1?p:Math.acos(t)}var x=t.geo.projection,b=t.geo.projectionMutator;function _(t,e){var r=(2+d)*Math.sin(e);e/=2;for(var n=0,i=1/0;n<10&&Math.abs(i)>h;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(p*(4+p))*t*(1+Math.cos(e)),2*Math.sqrt(p/(4+p))*Math.sin(e)]}t.geo.interrupt=function(e){var r,n=[[[[-p,0],[0,d],[p,0]]],[[[-p,0],[0,-d],[p,0]]]];function i(t,r){for(var i=r<0?-1:1,a=n[+(r<0)],o=0,s=a.length-1;oa[o][2][0];++o);var l=e(t-a[o][1][0],r);return l[0]+=e(a[o][1][0],i*r>i*a[o][0][1]?a[o][0][1]:r)[0],l}e.invert&&(i.invert=function(t,a){for(var o=r[+(a<0)],s=n[+(a<0)],u=0,c=o.length;u=0;--i){var o=n[1][i],l=180*o[0][0]/p,u=180*o[0][1]/p,c=180*o[1][1]/p,h=180*o[2][0]/p,f=180*o[2][1]/p;r.push(s([[h-e,f-e],[h-e,c+e],[l+e,c+e],[l+e,u-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}(),l)},i},a.lobes=function(t){return arguments.length?(n=t.map(function(t){return t.map(function(t){return[[t[0][0]*p/180,t[0][1]*p/180],[t[1][0]*p/180,t[1][1]*p/180],[t[2][0]*p/180,t[2][1]*p/180]]})}),r=n.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})}),a):n.map(function(t){return t.map(function(t){return[[180*t[0][0]/p,180*t[0][1]/p],[180*t[1][0]/p,180*t[1][1]/p],[180*t[2][0]/p,180*t[2][1]/p]]})})},a},_.invert=function(t,e){var r=.5*e*Math.sqrt((4+p)/p),n=m(r),i=Math.cos(n);return[t/(2/Math.sqrt(p*(4+p))*(1+i)),m((n+r*(i+2))/(2+d))]},(t.geo.eckert4=function(){return x(_)}).raw=_;var w=t.geo.azimuthalEqualArea.raw;function k(t,e){if(arguments.length<2&&(e=t),1===e)return w;if(e===1/0)return M;function r(r,n){var i=w(r/e,n);return i[0]*=t,i}return r.invert=function(r,n){var i=w.invert(r/t,n);return i[0]*=e,i},r}function M(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function A(t,e){return[3*t/(2*p)*Math.sqrt(p*p/3-e*e),e]}function T(t,e){return[t,1.25*Math.log(Math.tan(p/4+.4*e))]}function S(t){return function(e){var r,n=t*Math.sin(e),i=30;do{e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e))}while(Math.abs(r)>h&&--i>0);return e/2}}M.invert=function(t,e){var r=2*m(e/2);return[t*Math.cos(r/2)/Math.cos(r),r]},(t.geo.hammer=function(){var t=2,e=b(k),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}).raw=k,A.invert=function(t,e){return[2/3*p*t/Math.sqrt(p*p/3-e*e),e]},(t.geo.kavrayskiy7=function(){return x(A)}).raw=A,T.invert=function(t,e){return[t,2.5*Math.atan(Math.exp(.8*e))-.625*p]},(t.geo.miller=function(){return x(T)}).raw=T,S(p);var C=function(t,e,r){var n=S(r);function i(r,i){return[t*r*Math.cos(i=n(i)),e*Math.sin(i)]}return i.invert=function(n,i){var a=m(i/e);return[n/(t*Math.cos(a)),m((2*a+Math.sin(2*a))/r)]},i}(Math.SQRT2/d,Math.SQRT2,p);function E(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(n*(.003971*r-.001529*n)-.013791)),e*(1.007226+r*(.015085+n*(.028874*r-.044475-.005916*n)))]}(t.geo.mollweide=function(){return x(C)}).raw=C,E.invert=function(t,e){var r,n=e,i=25;do{var a=n*n,o=a*a;n-=r=(n*(1.007226+a*(.015085+o*(.028874*a-.044475-.005916*o)))-e)/(1.007226+a*(.045255+o*(.259866*a-.311325-.005916*11*o)))}while(Math.abs(r)>h&&--i>0);return[t/(.8707+(a=n*n)*(a*(a*a*a*(.003971-.001529*a)-.013791)-.131979)),n]},(t.geo.naturalEarth=function(){return x(E)}).raw=E;var L=[[.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]];function P(t,e){var r,n=Math.min(18,36*Math.abs(e)/p),i=Math.floor(n),a=n-i,o=(r=L[i])[0],s=r[1],l=(r=L[++i])[0],u=r[1],c=(r=L[Math.min(19,++i)])[0],h=r[1];return[t*(l+a*(c-o)/2+a*a*(c-2*l+o)/2),(e>0?d:-d)*(u+a*(h-s)/2+a*a*(h-2*u+s)/2)]}function z(t,e){return[t*Math.cos(e),e]}function D(t,e){var r,n=Math.cos(e),i=(r=y(n*Math.cos(t/=2)))?r/Math.sin(r):1;return[2*n*Math.sin(t)*i,Math.sin(e)*i]}function I(t,e){var r=D(t,e);return[(r[0]+t/d)/2,(r[1]+e)/2]}L.forEach(function(t){t[1]*=1.0144}),P.invert=function(t,e){var r=e/d,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=L[a][1],s=L[a+1][1],l=L[Math.min(19,a+2)][1],u=l-o,c=l-2*s+o,h=2*(Math.abs(r)-s)/u,p=c/u,m=h*(1-p*h*(1-2*p*h));if(m>=0||1===a){n=(e>=0?5:-5)*(m+i);var y,x=50;do{m=(i=Math.min(18,Math.abs(n)/5))-(a=Math.floor(i)),o=L[a][1],s=L[a+1][1],l=L[Math.min(19,a+2)][1],n-=(y=(e>=0?d:-d)*(s+m*(l-o)/2+m*m*(l-2*s+o)/2)-e)*v}while(Math.abs(y)>f&&--x>0);break}}while(--a>=0);var b=L[a][0],_=L[a+1][0],w=L[Math.min(19,a+2)][0];return[t/(_+m*(w-b)/2+m*m*(w-2*_+b)/2),n*g]},(t.geo.robinson=function(){return x(P)}).raw=P,z.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return x(z)}).raw=z,D.invert=function(t,e){if(!(t*t+4*e*e>p*p+h)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),l=Math.cos(r/2),u=Math.sin(n),c=Math.cos(n),f=Math.sin(2*n),d=u*u,g=c*c,v=s*s,m=1-g*l*l,x=m?y(c*l)*Math.sqrt(a=1/m):a=0,b=2*x*c*s-t,_=x*u-e,w=a*(g*v+x*c*l*d),k=a*(.5*o*f-2*x*u*s),M=.25*a*(f*s-x*u*g*o),A=a*(d*l+x*v*c),T=k*M-A*w;if(!T)break;var S=(_*k-b*A)/T,C=(b*M-_*w)/T;r-=S,n-=C}while((Math.abs(S)>h||Math.abs(C)>h)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return x(D)}).raw=D,I.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),l=Math.sin(2*n),u=s*s,c=o*o,f=Math.sin(r),p=Math.cos(r/2),g=Math.sin(r/2),v=g*g,m=1-c*p*p,x=m?y(o*p)*Math.sqrt(a=1/m):a=0,b=.5*(2*x*o*g+r/d)-t,_=.5*(x*s+n)-e,w=.5*a*(c*v+x*o*p*u)+.5/d,k=a*(f*l/4-x*s*g),M=.125*a*(l*g-x*s*c*f),A=.5*a*(u*p+x*v*o)+.5,T=k*M-A*w,S=(_*k-b*A)/T,C=(b*M-_*w)/T;r-=S,n-=C}while((Math.abs(S)>h||Math.abs(C)>h)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return x(I)}).raw=I},ph=Math.PI/180,dh=180/Math.PI,gh={cursor:"pointer"},vh={cursor:"auto"};var mh=function(t,e){var r=t.projection;return(e._isScoped?bh:e._isClipped?wh:_h)(t,r)};function yh(t,e){return i.behavior.zoom().translate(e.translate()).scale(e.scale())}function xh(t,e,r){var n=t.id,i=t.graphDiv,a=i.layout[n],o=i._fullLayout[n],s={};function l(t,e){var r=oe.nestedProperty(o,t);r.get()!==e&&(r.set(e),oe.nestedProperty(a,t).set(e),s[n+"."+t]=e)}r(l),l("projection.scale",e.scale()/t.fitScale),i.emit("plotly_relayout",s)}function bh(t,e){var r=yh(0,e);function n(r){var n=e.invert(t.midPt);r("center.lon",n[0]),r("center.lat",n[1])}return r.on("zoomstart",function(){i.select(this).style(gh)}).on("zoom",function(){e.scale(i.event.scale).translate(i.event.translate),t.render()}).on("zoomend",function(){i.select(this).style(vh),xh(t,e,n)}),r}function _h(t,e){var r,n,a,o,s,l,u,c,h=yh(0,e),f=2;function p(t){return e.invert(t)}function d(r){var n=e.rotate(),i=e.invert(t.midPt);r("projection.rotation.lon",-n[0]),r("center.lon",i[0]),r("center.lat",i[1])}return h.on("zoomstart",function(){i.select(this).style(gh),r=i.mouse(this),n=e.rotate(),a=e.translate(),o=n,s=p(r)}).on("zoom",function(){if(l=i.mouse(this),g=e(p(d=r)),Math.abs(g[0]-d[0])>f||Math.abs(g[1]-d[1])>f)return h.scale(e.scale()),void h.translate(e.translate());var d,g;e.scale(i.event.scale),e.translate([a[0],i.event.translate[1]]),s?p(l)&&(c=p(l),u=[o[0]+(c[0]-s[0]),n[1],n[2]],e.rotate(u),o=u):s=p(r=l),t.render()}).on("zoomend",function(){i.select(this).style(vh),xh(t,e,d)}),h}function wh(t,e){var r,n={r:e.rotate(),k:e.scale()},a=yh(0,e),o=function(t){var e=0,r=arguments.length,n=[];for(;++ep?(a=(c>0?90:-90)-f,i=0):(a=Math.asin(c/p)*dh-f,i=Math.sqrt(p*p-c*c));var d=180-a-2*f,g=(Math.atan2(h,u)-Math.atan2(l,i))*dh,v=(Math.atan2(h,u)-Math.atan2(l,-i))*dh,m=Mh(r[0],r[1],a,g),y=Mh(r[0],r[1],d,v);return m<=y?[a,g,r[2]]:[d,v,r[2]]}(y,r,_);isFinite(M[0])&&isFinite(M[1])&&isFinite(M[2])||(M=_),e.rotate(M),_=M}}else r=kh(e,x=g);o.of(this,arguments)({type:"zoom"})}),y=o.of(this,arguments),s++||y({type:"zoomstart"})}).on("zoomend",function(){var r;i.select(this).style(vh),l.call(a,"zoom",null),r=o.of(this,arguments),--s||r({type:"zoomend"}),xh(t,e,u)}).on("zoom.redraw",function(){t.render()}),i.rebind(a,o,"on")}function kh(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&function(t){var e=t[0]*ph,r=t[1]*ph,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}(r)}function Mh(t,e,r,n){var i=Ah(r-t),a=Ah(n-e);return Math.sqrt(i*i+a*a)}function Ah(t){return(t%360+540)%360-180}function Th(t,e,r){var n=r*ph,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function Sh(t,e){for(var r=0,n=0,i=t.length;nn*Math.PI/180}return!1},r.getPath=function(){return i.geo.path().projection(r)},r.getBounds=function(t){return r.getPath().bounds(t)},r.fitExtent=function(t,e){var n=t[1][0]-t[0][0],i=t[1][1]-t[0][1],a=r.clipExtent&&r.clipExtent();r.scale(150).translate([0,0]),a&&r.clipExtent(null);var o=r.getBounds(e),s=Math.min(n/(o[1][0]-o[0][0]),i/(o[1][1]-o[0][1])),l=+t[0][0]+(n-s*(o[1][0]+o[0][0]))/2,u=+t[0][1]+(i-s*(o[1][1]+o[0][1]))/2;return a&&r.clipExtent(a),r.scale(150*s).translate([l,u])},r.precision(sh.precision),n&&r.clipAngle(n-sh.clipPad);return r}(e);l.center([s.lon-o.lon,s.lat-o.lat]).rotate([-o.lon,-o.lat,o.roll]).parallels(a.parallels);var u=[[r.l+r.w*n.x[0],r.t+r.h*(1-n.y[1])],[r.l+r.w*n.x[1],r.t+r.h*(1-n.y[0])]],c=e.lonaxis,h=e.lataxis,f=function(t,e){var r=sh.clipPad,n=t[0]+r,i=t[1]-r,a=e[0]+r,o=e[1]-r;n>0&&i<0&&(i+=360);var s=(i-n)/4;return{type:"Polygon",coordinates:[[[n,a],[n,o],[n+s,o],[n+2*s,o],[n+3*s,o],[i,o],[i,a],[i-s,a],[i-2*s,a],[i-3*s,a],[n,a]]]}}(c.range,h.range);l.fitExtent(u,f);var p=this.bounds=l.getBounds(f),d=this.fitScale=l.scale(),g=l.translate();if(!isFinite(p[0][0])||!isFinite(p[0][1])||!isFinite(p[1][0])||!isFinite(p[1][1])||isNaN(g[0])||isNaN(g[0])){for(var v=this.graphDiv,m=["projection.rotation","center","lonaxis.range","lataxis.range"],y="Invalid geo settings, relayout'ing to default view.",x={},b=0;b0&&b<0&&(b+=360);var _,w,k,M=(x+b)/2;if(!s){var A=l?a.projRotate:[M,0,0];_=r("projection.rotation.lon",A[0]),r("projection.rotation.lat",A[1]),r("projection.rotation.roll",A[2]),r("showcoastlines",!l)&&(r("coastlinecolor"),r("coastlinewidth")),r("showocean")&&r("oceancolor")}(s?(w=-96.6,k=38.7):(w=l?M:_,k=(y[0]+y[1])/2),r("center.lon",w),r("center.lat",k),u)&&r("projection.parallels",a.projParallels||[0,60]);r("projection.scale"),r("showland")&&r("landcolor"),r("showlakes")&&r("lakecolor"),r("showrivers")&&(r("rivercolor"),r("riverwidth")),r("showcountries",l&&"usa"!==i)&&(r("countrycolor"),r("countrywidth")),("usa"===i||"north america"===i&&50===n)&&(r("showsubunits",!0),r("subunitcolor"),r("subunitwidth")),l||r("showframe",!0)&&(r("framecolor"),r("framewidth")),r("bgcolor")}var Uh={},qh=hs.getSubplotCalcData,Hh=oe.counterRegex,Gh="geo";Uh.name=Gh,Uh.attr=Gh,Uh.idRoot=Gh,Uh.idRegex=Uh.attrRegex=Hh(Gh),Uh.attributes={geo:{valType:"subplotid",dflt:"geo",editType:"calc"}},Uh.layoutAttributes=Bh,Uh.supplyLayoutDefaults=function(t,e,r){Nh(t,e,0,{type:"geo",attributes:Bh,handleDefaults:Vh,partition:"y"})},Uh.plot=function(t){var e=t._fullLayout,r=t.calcdata,n=e._subplots.geo;void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var i=0;i0&&t[e+1][0]<0)return e;return null}switch(e="RUS"===s||"FJI"===s?function(t){var e;if(null===u(t))e=t;else for(e=new Array(t.length),i=0;ie?r[n++]=[t[i][0]+360,t[i][1]]:i===e?(r[n++]=t[i],r[n++]=[t[i][0],-90]):r[n++]=t[i];var a=ao.tester(r);a.pts.pop(),l.push(a)}:function(t){l.push(ao.tester(t))},a.type){case"MultiPolygon":for(r=0;ra&&(e.z=s.slice(0,a)),i("locationmode"),i("text"),i("marker.line.color"),i("marker.line.width"),i("marker.opacity"),Je(t,e,n,i,{prefix:"",cLetter:"z"}),oe.coerceSelectionMarkerOpacity(e,i)):e.visible=!1}else e.visible=!1},vf.colorbar=gf,vf.calc=function(t,e){for(var r=e.locations.length,n=new Array(r),i=0;i")}(t,l,n,u.mockAxis),[t]},vf.eventData=function(t,e){return t.location=e.location,t.z=e.z,t},vf.selectPoints=function(t,e){var r,n,i,a,o,s=t.cd,l=t.xaxis,u=t.yaxis,c=[];if(!1===e)for(r=0;r=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}},xf=b.extendFlat,bf=xf({},{z:{valType:"data_array",editType:"calc"},x:xf({},Qr.x,{impliedEdits:{xtype:"array"}}),x0:xf({},Qr.x0,{impliedEdits:{xtype:"scaled"}}),dx:xf({},Qr.dx,{impliedEdits:{xtype:"scaled"}}),y:xf({},Qr.y,{impliedEdits:{ytype:"array"}}),y0:xf({},Qr.y0,{impliedEdits:{ytype:"scaled"}}),dy:xf({},Qr.dy,{impliedEdits:{ytype:"scaled"}}),text:{valType:"data_array",editType:"calc"},transpose:{valType:"boolean",dflt:!1,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",!1],dflt:!1,editType:"calc"},connectgaps:{valType:"boolean",dflt:!1,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"}},Oe,{autocolorscale:xf({},Oe.autocolorscale,{dflt:!1})},{colorbar:Ie}),_f=Se.dash,wf=b.extendFlat,kf=yf.COMPARISON_OPS2,Mf=yf.INTERVAL_OPS,Af=Qr.line,Tf=wf({z:bf.z,x:bf.x,x0:bf.x0,dx:bf.dx,y:bf.y,y0:bf.y0,dy:bf.dy,text:bf.text,transpose:bf.transpose,xtype:bf.xtype,ytype:bf.ytype,zhoverformat:bf.zhoverformat,connectgaps:bf.connectgaps,fillcolor:{valType:"color",editType:"calc"},autocontour:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"contours.start":void 0,"contours.end":void 0,"contours.size":void 0}},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":!1}},end:{valType:"number",dflt:null,editType:"plot",impliedEdits:{"^autocontour":!1}},size:{valType:"number",dflt:null,min:0,editType:"plot",impliedEdits:{"^autocontour":!1}},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill",editType:"calc"},showlines:{valType:"boolean",dflt:!0,editType:"plot"},showlabels:{valType:"boolean",dflt:!1,editType:"plot"},labelfont:E({editType:"plot",colorEditType:"style"}),labelformat:{valType:"string",dflt:"",editType:"plot"},operation:{valType:"enumerated",values:[].concat(kf).concat(Mf),dflt:"=",editType:"calc"},value:{valType:"any",dflt:0,editType:"calc"},editType:"calc",impliedEdits:{autocontour:!1}},line:{color:wf({},Af.color,{editType:"style+colorbars"}),width:wf({},Af.width,{editType:"style+colorbars"}),dash:_f,smoothing:wf({},Af.smoothing,{}),editType:"plot"}},Oe,{autocolorscale:wf({},Oe.autocolorscale,{dflt:!1}),zmin:wf({},Oe.zmin,{editType:"calc"}),zmax:wf({},Oe.zmax,{editType:"calc"})},{colorbar:Ie}),Sf=oe.extendFlat,Cf=function(t){var e=t.contours;if(t.autocontour){var r=Ef(t.zmin,t.zmax,t.ncontours);e.size=r.dtick,e.start=ui.tickFirst(r),r.range.reverse(),e.end=ui.tickFirst(r),e.start===t.zmin&&(e.start+=e.size),e.end===t.zmax&&(e.end-=e.size),e.start>e.end&&(e.start=e.end=(e.start+e.end)/2),t._input.contours||(t._input.contours={}),Sf(t._input.contours,{start:e.start,end:e.end,size:e.size}),t._input.autocontour=!0}else if("constraint"!==e.type){var n,i=e.start,a=e.end,o=t._input.contours;if(i>a&&(e.start=o.start=a,a=e.end=o.end=i,i=e.start),!(e.size>0))n=i===a?1:Ef(i,a,t.ncontours).dtick,o.size=e.size=n}};function Ef(t,e,r){var n={type:"linear",range:[t,e]};return ui.autoTicks(n,(e-t)/(r||15)),n}var Lf=function(t){for(var e=0,r=0;r=0;a--)(o=((c[[(r=(i=h[a])[0])-1,n=i[1]]]||d)[2]+(c[[r+1,n]]||d)[2]+(c[[r,n-1]]||d)[2]+(c[[r,n+1]]||d)[2])/20)&&(s[i]=[r,n,o],h.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)c[i]=s[i],u.push(s[i])}return u.sort(function(t,e){return e[2]-t[2]})},zf=oe.isArrayOrTypedArray,Df=function(t){return!zf(t.z[0])},If=[[-1,0],[1,0],[0,-1],[0,1]];function Of(t){return.5-.25*Math.min(1,.5*t)}var Rf=function(t,e,r){var n,i,a=1;if(Array.isArray(r))for(n=0;n.01;n++)a=Bf(t,e,Of(a));return a>.01&&oe.log("interp2d didn't converge quickly",a),t};function Bf(t,e,r){var n,i,a,o,s,l,u,c,h,f,p,d,g,v=0;for(o=0;od&&(v=Math.max(v,Math.abs(t[i][a]-p)/(g-d))))}return v}var Ff=oe.isArrayOrTypedArray,Nf=function(t,e,r,n,i,a){var o,s,l,u=[],c=O.traceIs(t,"contour"),h=O.traceIs(t,"histogram"),f=O.traceIs(t,"gl2d");if(Ff(e)&&e.length>1&&!h&&"category"!==a.type){var p=e.length;if(!(p<=i))return c?e.slice(0,i):e.slice(0,i+1);if(c||f)u=e.slice(0,i);else if(1===i)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],l=1;li){var o=i-r[t];return r[t]=i,o}}return 0},max:function(t,e,r,n){var i=n[e];if(a(i)){if(i=Number(i),!a(r[t]))return r[t]=i,i;if(r[t]p&&pHf){var d=a===Uf?1:6,g=a===Uf?"M12":"M1";return function(e,r){var a=n.c2d(e,Uf,i),s=a.indexOf("-",d);s>0&&(a=a.substr(0,s));var l=n.d2c(a,0,i);if(lYf?t>Hf?t>1.1*Uf?Uf:t>1.1*qf?qf:Hf:t>Gf?Gf:t>Wf?Wf:Yf:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function Qf(t,e,r,n,i,a){if(n&&t>Hf){var o=$f(e,i,a),s=$f(r,i,a),l=t===Uf?0:1;return o[l]!==s[l]}return Math.floor(r/t)-Math.floor(e/t)>.1}function $f(t,e,r){var n=e.c2d(t,Uf,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}var tp=oe.cleanDate,ep=n.ONEDAY,rp=n.BADNUM,np=function(t,e,r){var n=e.type,i=r+"bins",o=t[i];o||(o=t[i]={});var s="date"===n?function(t){return t||0===t?tp(t,rp,o.calendar):null}:function(t){return a(t)?Number(t):null};o.start=s(o.start),o.end=s(o.end);var l="date"===n?ep:1,u=o.size;if(a(u))o.size=u>0?Number(u):l;else if("string"!=typeof u)o.size=l;else{var c=u.charAt(0),h=u.substr(1);((h=a(h)?Number(h):0)<=0||"date"!==n||"M"!==c||h!==Math.round(h))&&(o.size=l)}var f="autobin"+r;"boolean"!=typeof t[f]&&(t[f]=t._fullInput[f]=t._input[f]=!((o.start||0===o.start)&&(o.end||0===o.end))),t[f]||(delete t["nbins"+r],delete t._fullInput["nbins"+r])},ip={percent:function(t,e){for(var r=t.length,n=100/e,i=0;iv&&s.splice(v,s.length-v),u.length>v&&u.splice(v,u.length-v),ap(e,"x",s,o,f,d,c),ap(e,"y",u,l,p,g,h);var m=[],y=[],x=[],b="string"==typeof e.xbins.size,_="string"==typeof e.ybins.size,w=[],k=[],M=b?w:e.xbins,A=_?k:e.ybins,T=0,S=[],C=[],E=e.histnorm,L=e.histfunc,P=-1!==E.indexOf("density"),z="max"===L||"min"===L?null:0,D=Vf.count,I=ip[E],O=!1,R=[],B=[],F="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";F&&"count"!==L&&(O="avg"===L,D=Vf[L]);var N=e.xbins,j=f(N.start),V=f(N.end)+(j-ui.tickIncrement(j,N.size,!1,c))/1e6;for(r=j;r=0&&i=0&&ab){y("x scale is not linear");break}}if(a.length&&"fast"===v){var _=(a[a.length-1]-a[0])/(a.length-1),w=Math.abs(_/100);for(u=0;uw){y("y scale is not linear");break}}}var k=Lf(l),M="scaled"===e.xtype?"":r,A=Nf(e,M,n,i,k,h),T="scaled"===e.ytype?"":a,S=Nf(e,T,o,s,l.length,f);g||(ui.expand(h,A),ui.expand(f,S));var C={x:A,y:S,z:l,text:e._text||e.text};if(M&&M.length===A.length-1&&(C.xCenter=M),T&&T.length===S.length-1&&(C.yCenter=T),d&&(C.xRanges=c.xRanges,C.yRanges=c.yRanges,C.pts=c.pts),p&&"constraint"===e.contours.type||He(e,l,"","z"),p&&e.contours&&"heatmap"===e.contours.coloring){var E={type:"contour"===e.type?"heatmap":"histogram2d",xcalendar:e.xcalendar,ycalendar:e.ycalendar};C.xfill=Nf(E,M,n,i,k,h),C.yfill=Nf(E,T,o,s,l.length,f)}return[C]},cp=function(t,e){var r=up(t,e);return Cf(e),r},hp=function(t){return t.end+t.size/1e6},fp=function(t){var e=t.contours,r=e.start,n=hp(e),a=e.size||1,o=Math.floor((n-r)/a)+1,s="lines"===e.coloring?0:1;isFinite(a)||(a=1,o=1);var l,u,c=t.colorscale,h=c.length,f=new Array(h),p=new Array(h);if("heatmap"===e.coloring){for(t.zauto&&!1===t.autocontour&&(t.zmin=r-a/2,t.zmax=t.zmin+o*a),u=0;u2?e.value=e.value.slice(2):0===e.length?e.value=[0,1]:e.length<2?(r=parseFloat(e.value[0]),e.value=[r,r+1]):e.value=[parseFloat(e.value[0]),parseFloat(e.value[1])]:a(e.value)&&(r=parseFloat(e.value),e.value=[r,r+1])):(t("contours.value",0),a(e.value)||(Array.isArray(e.value)?e.value=parseFloat(e.value[0]):e.value=0))}(r,c),"="===h?s=c.showlines=!0:(s=r("contours.showlines"),u=r("fillcolor",gp((t.line||{}).color||i,.5))),s)&&(l=r("line.color",u&&vp(u)?gp(e.fillcolor,1):i),r("line.width",2),r("line.dash"));r("line.smoothing"),dp(r,n,l,o)};var bp=function(t,e,r,n){var i=n("contours.start"),a=n("contours.end"),o=!1===i||!1===a,s=r("contours.size");!(o?e.autocontour=!0:r("autocontour",!1))&&s||r("ncontours")},_p=function(t,e,r,n,i){var a,o=r("contours.coloring"),s="";"fill"===o&&(a=r("contours.showlines")),!1!==a&&("lines"!==o&&(s=r("line.color","#000")),r("line.width",.5),r("line.dash")),"none"!==o&&Je(t,e,n,r,{prefix:"",cLetter:"z"}),r("line.smoothing"),dp(r,n,s,i)},wp=oe.isArrayOrTypedArray,kp=function(t,e,r,n,i,o){var s,l,u=r("z");if(i=i||"x",o=o||"y",void 0===u||!u.length)return 0;if(Df(t)){if(s=r(i),l=r(o),!s||!l)return 0}else{if(s=Mp(i,r),l=Mp(o,r),!function(t){for(var e,r=!0,n=!1,i=!1,o=0;o0&&(n=!0);for(var s=0;s=v[0].length||u<0||u>v.length)return}else{if(qa.inbox(e-d[0],e-d[d.length-1],0)>0||qa.inbox(r-g[0],r-g[g.length-1],0)>0)return;if(a){var M;for(w=[2*d[0]-d[1]],M=1;M":h.value>f&&(s.prefixBoundary=!0);break;case"<":h.valuef)&&(s.prefixBoundary=!0);break;case"][":a=Math.min.apply(null,h.value),o=Math.max.apply(null,h.value),af&&(s.prefixBoundary=!0)}},Cp={BOTTOMSTART:[1,9,13,104,713],TOPSTART:[4,6,7,104,713],LEFTSTART:[8,12,14,208,1114],RIGHTSTART:[2,3,11,208,1114],NEWDELTA:[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],CHOOSESADDLE:{104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},SADDLEREMAINDER:{1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11},LABELDISTANCE:2,LABELINCREASE:10,LABELMIN:3,LABELMAX:10,LABELOPTIMIZER:{EDGECOST:1,ANGLECOST:1,NEIGHBORCOST:5,SAMELEVELFACTOR:10,SAMELEVELDISTANCE:5,MAXCOST:100,INITIALSEARCHPOINTS:10,ITERATIONS:5}},Ep=function(t,e){var r,n,i,a=function(t){return t.reverse()},o=function(t){return t};switch(e){case"=":case"<":return t;case">":for(1!==t.length&&oe.warn("Contour data invalid for the specified inequality operation."),n=t[0],r=0;r":Ip(">"),"<":Ip("<"),"=":Ip("=")};function zp(t,e){var r,n=Array.isArray(e);function i(t){return a(t)?+t:null}return-1!==yf.COMPARISON_OPS2.indexOf(t)?r=i(n?e[0]:e):-1!==yf.INTERVAL_OPS.indexOf(t)?r=n?[i(e[0]),i(e[1])]:[i(e),i(e)]:-1!==yf.SET_OPS.indexOf(t)&&(r=n?e.map(i):[i(e)]),r}function Dp(t){return function(e){e=zp(t,e);var r=Math.min(e[0],e[1]),n=Math.max(e[0],e[1]);return{start:r,end:n,size:n-r}}}function Ip(t){return function(e){return{start:e=zp(t,e),end:1/0,size:1/0}}}var Op=function(t,e,r){for(var n="constraint"===t.type?Pp[t._operation](t.value):t,i=n.size,a=[],o=hp(n),s=r.trace._carpetTrace,l=s?{xaxis:s.aaxis,yaxis:s.baxis,x:r.a,y:r.b}:{xaxis:e.xaxis,yaxis:e.yaxis,x:r.x,y:r.y},u=n.start;u1e3){oe.warn("Too many contours, clipping at 1000",t);break}return a},Rp=function(t,e,r){var n,i,a,o;for(e=e||.01,r=r||.01,i=0;i20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==Cp.BOTTOMSTART.indexOf(t)?i=1:-1!==Cp.LEFTSTART.indexOf(t)?n=1:-1!==Cp.TOPSTART.indexOf(t)?i=-1:n=-1;return[n,i]}(l,r,e),c=[Np(t,e,[-u[0],-u[1]])],h=u.join(","),f=t.z.length,p=t.z[0].length;for(a=0;a<1e4;a++){if(l>20?(l=Cp.CHOOSESADDLE[l][(u[0]||u[1])<0?0:1],t.crossings[s]=Cp.SADDLEREMAINDER[l]):delete t.crossings[s],!(u=Cp.NEWDELTA[l])){oe.log("Found bad marching index:",l,e,t.level);break}c.push(Np(t,e,u)),e[0]+=u[0],e[1]+=u[1],Bp(c[c.length-1],c[c.length-2],n,i)&&c.pop(),s=e.join(",");var d=u[0]&&(e[0]<0||e[0]>p-2)||u[1]&&(e[1]<0||e[1]>f-2);if(s===o&&u.join(",")===h||r&&d)break;l=t.crossings[s]}1e4===a&&oe.log("Infinite loop in contour?");var g,v,m,y,x,b,_,w,k,M,A,T,S,C,E,L=Bp(c[0],c[c.length-1],n,i),P=0,z=.2*t.smoothing,D=[],I=0;for(a=1;a=I;a--)if((g=D[a])=I&&g+D[v]w&&k--,t.edgepaths[k]=A.concat(c,M));break}F||(t.edgepaths[w]=c.concat(M))}for(w=0;wt?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);return 5===r||10===r?t>(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4?5===r?713:1114:5===r?104:208:15===r?0:r}var Up=function(t,e,r){for(var n=0;n0;)f=o.c2p(y[v]),v--;for(f0;)g=s.c2p(x[v]),v--;if(gt.level}return r?"M"+e.join("L")+"Z":""}(t,e),c=0,h=t.edgepaths.map(function(t,e){return e}),f=!0;function p(t){return Math.abs(t[1]-e[2][1])<.01}function d(t){return Math.abs(t[0]-e[0][0])<.01}function g(t){return Math.abs(t[0]-e[2][0])<.01}for(;h.length;){for(s=Lr.smoothopen(t.edgepaths[c],t.smoothing),u+=f?s:s.replace(/^M/,"L"),h.splice(h.indexOf(c),1),r=t.edgepaths[c][t.edgepaths[c].length-1],a=-1,i=0;i<4;i++){if(!r){oe.log("Missing end?",c,t);break}for(l=r,Math.abs(l[1]-e[0][1])<.01&&!g(r)?n=e[1]:d(r)?n=e[0]:p(r)?n=e[3]:g(r)&&(n=e[2]),o=0;o=0&&(n=v,a=o):Math.abs(r[1]-n[1])<.01?Math.abs(r[1]-v[1])<.01&&(v[0]-r[0])*(n[0]-v[0])>=0&&(n=v,a=o):oe.log("endpt to newendpt is not vert. or horz.",r,n,v)}if(r=n,a>=0)break;u+="L"+n}if(a===t.edgepaths.length){oe.log("unclosed perimeter path");break}c=a,(f=-1===h.indexOf(c))&&(c=h[0],u+="Z")}for(c=0;cn.center?n.right-o:o-n.left)/(u+Math.abs(Math.sin(l)*a)),f=(s>n.middle?n.bottom-s:s-n.top)/(Math.abs(c)+Math.cos(l)*a);if(h<1||f<1)return 1/0;var p=Xp.EDGECOST*(1/(h-1)+1/(f-1));p+=Xp.ANGLECOST*l*l;for(var d=o-u,g=s-c,v=o+u,m=s+c,y=0;y2*Xp.MAXCOST)break;f&&(o/=2),s=(a=l-o/2)+1.5*o}if(h<=Xp.MAXCOST)return u},Yp.addLabelData=function(t,e,r,n){var i=e.width/2,a=e.height/2,o=t.x,s=t.y,l=t.theta,u=Math.sin(l),c=Math.cos(l),h=i*c,f=a*u,p=i*u,d=-a*c,g=[[o-h-f,s-p-d],[o+h-f,s+p-d],[o+h+f,s+p+d],[o-h+f,s-p+d]];r.push({text:e.text,x:o,y:s,dy:e.dy,theta:l,level:e.level,width:e.width,height:e.height}),n.push(g)},Yp.drawLabels=function(t,e,r,n,a){var o=t.selectAll("text").data(e,function(t){return t.text+","+t.x+","+t.y+","+t.theta});if(o.exit().remove(),o.enter().append("text").attr({"data-notex":1,"text-anchor":"middle"}).each(function(t){var e=t.x+Math.sin(t.theta)*t.dy,n=t.y-Math.cos(t.theta)*t.dy;i.select(this).text(t.text).attr({x:e,y:n,transform:"rotate("+180*t.theta/Math.PI+" "+e+" "+n+")"}).call(ir.convertToTspans,r)}),a){for(var s="",l=0;l0?Math.floor:Math.ceil,P=C>0?Math.ceil:Math.floor,z=C>0?Math.min:Math.max,D=C>0?Math.max:Math.min,I=L(T+E),O=P(S-E),R=[[c=A(T)]];for(i=I;i*C=0&&(c=T,f=p):Math.abs(u[1]-c[1])=0&&(c=T,f=p):oe.log("endpt to newendpt is not vert. or horz.",u,c,T)}if(f>=0)break;g+=M(u,c),u=c}if(f===e.edgepaths.length){oe.log("unclosed perimeter path");break}l=f,(m=-1===v.indexOf(l))&&(l=v[0],g+=M(u,c)+"Z",u=null)}for(l=0;l=0;T--)k=o.clipsegments[T],M=Jc([],k.x,h.c2p),A=Jc([],k.y,f.c2p),M.reverse(),A.reverse(),C.push(Xc(M,A,k.bicubic));var E="M"+C.join("L")+"Z";!function(t,e,r,n,i,a){var o,s,l,u,c=oe.ensureSingle(t,"g","contourbg").selectAll("path").data("fill"!==a||i?[]:[0]);c.enter().append("path"),c.exit().remove();var h=[];for(u=0;uv&&(n.max=v);n.len=n.max-n.min}(this,r,t,n,s,e.height),!(n.len<(e.width+e.height)*Cp.LABELMIN)))for(var i=Math.min(Math.ceil(n.len/A),Cp.LABELMAX),a=0;a1)for(var r=1;r=0,d=e.indexOf("end")>=0,g=u.backoff*h+r.standoff,v=c.backoff*f+r.startstandoff;if("line"===l.nodeName){n={x:+t.attr("x1"),y:+t.attr("y1")},a={x:+t.attr("x2"),y:+t.attr("y2")};var m=n.x-a.x,y=n.y-a.y;if(s=(o=Math.atan2(y,m))+Math.PI,g&&v&&g+v>Math.sqrt(m*m+y*y))return void E();if(g){if(g*g>m*m+y*y)return void E();var x=g*Math.cos(o),b=g*Math.sin(o);a.x+=x,a.y+=b,t.attr({x2:a.x,y2:a.y})}if(v){if(v*v>m*m+y*y)return void E();var _=v*Math.cos(o),w=v*Math.sin(o);n.x-=_,n.y-=w,t.attr({x1:n.x,y1:n.y})}}else if("path"===l.nodeName){var k=l.getTotalLength(),M="";if(k2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}e._w=C,e._h=E;for(var D=!1,I=["x","y"],R=0;R1)&&(H===q?(($=G.r2fraction(e["a"+U]))<0||$>1)&&(D=!0):D=!0,D))continue;B=G._offset+G.r2p(e[U]),j=.5}else"x"===U?(N=e[U],B=c.l+c.w*N):(N=1-e[U],B=c.t+c.h*N),j=e.showarrow?.5:N;if(e.showarrow){Q.head=B;var tt=e["a"+U];V=Y*z(.5,e.xanchor)-X*z(.5,e.yanchor),H===q?(Q.tail=G._offset+G.r2p(tt),F=V):(Q.tail=B+tt,F=V+tt),Q.text=Q.tail+V;var et=u["x"===U?"width":"height"];if("paper"===q&&(Q.head=oe.constrain(Q.head,1,et-1)),"pixel"===H){var rt=-Math.max(Q.tail-3,Q.text),nt=Math.min(Q.tail+3,Q.text)-et;rt>0?(Q.tail+=rt,Q.text+=rt):nt>0&&(Q.tail-=nt,Q.text-=nt)}Q.tail+=K,Q.head+=K}else F=V=Z*z(j,J),Q.text=B+V;Q.text+=K,V+=K,F+=K,e["_"+U+"padplus"]=Z/2+F,e["_"+U+"padminus"]=Z/2-F,e["_"+U+"size"]=Z,e["_"+U+"shift"]=V}if(D)x.remove();else{var it=0,at=0;if("left"!==e.align&&(it=(C-_)*("center"===e.align?.5:1)),"top"!==e.valign&&(at=(E-T)*("middle"===e.valign?.5:1)),s)i.select("svg").attr({x:w+it-1,y:w+at}).call(Lr.setClipUrl,M?f:null);else{var ot=w+at-y.top,st=w+it-y.left;S.call(ir.positionText,st,ot).call(Lr.setClipUrl,M?f:null)}A.select("rect").call(Lr.setRect,w,w,C,E),k.call(Lr.setRect,b/2,b/2,L-b,P-b),x.call(Lr.setTranslate,Math.round(p.x.text-L/2),Math.round(p.y.text-P/2)),v.attr({transform:"rotate("+d+","+p.x.text+","+p.y.text+")"});var lt,ut,ct=function(r,i){g.selectAll(".annotation-arrow-g").remove();var s=p.x.head,u=p.y.head,f=p.x.tail+r,m=p.y.tail+i,y=p.x.text+r,b=p.y.text+i,_=oe.rotationXYMatrix(d,y,b),w=oe.apply2DTransform(_),M=oe.apply2DTransform2(_),A=+k.attr("width"),T=+k.attr("height"),S=y-.5*A,C=S+A,E=b-.5*T,L=E+T,P=[[S,E,S,L],[S,L,C,L],[C,L,C,E],[C,E,S,E]].map(M);if(!P.reduce(function(t,e){return t^!!oe.segmentsIntersect(s,u,s+1e6,u+1e6,e[0],e[1],e[2],e[3])},!1)){P.forEach(function(t){var e=oe.segmentsIntersect(f,m,s,u,t[0],t[1],t[2],t[3]);e&&(f=e.x,m=e.y)});var z=e.arrowwidth,D=e.arrowcolor,I=e.arrowside,R=g.append("g").style({opacity:Fe.opacity(D)}).classed("annotation-arrow-g",!0),B=R.append("path").attr("d","M"+f+","+m+"L"+s+","+u).style("stroke-width",z+"px").call(Fe.stroke,Fe.rgb(D));if(jd(B,I,e),h.annotationPosition&&B.node().parentNode&&!n){var F=s,N=u;if(e.standoff){var j=Math.sqrt(Math.pow(s-f,2)+Math.pow(u-m,2));F+=e.standoff*(f-s)/j,N+=e.standoff*(m-u)/j}var V,U,q,H=R.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(f-F)+","+(m-N),transform:"translate("+F+","+N+")"}).style("stroke-width",z+6+"px").call(Fe.stroke,"rgba(0,0,0,0)").call(Fe.fill,"rgba(0,0,0,0)");da.init({element:H.node(),gd:t,prepFn:function(){var t=Lr.getTranslate(x);U=t.x,q=t.y,V={},a&&a.autorange&&(V[a._name+".autorange"]=!0),o&&o.autorange&&(V[o._name+".autorange"]=!0)},moveFn:function(t,r){var n=w(U,q),i=n[0]+t,s=n[1]+r;x.call(Lr.setTranslate,i,s),V[l+".x"]=a?a.p2r(a.r2p(e.x)+t):e.x+t/c.w,V[l+".y"]=o?o.p2r(o.r2p(e.y)+r):e.y-r/c.h,e.axref===e.xref&&(V[l+".ax"]=a.p2r(a.r2p(e.ax)+t)),e.ayref===e.yref&&(V[l+".ay"]=o.p2r(o.r2p(e.ay)+r)),R.attr("transform","translate("+t+","+r+")"),v.attr({transform:"rotate("+d+","+i+","+s+")"})},doneFn:function(){O.call("relayout",t,V);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(e.showarrow&&ct(0,0),m)da.init({element:x.node(),gd:t,prepFn:function(){ut=v.attr("transform"),lt={}},moveFn:function(t,r){var i="pointer";if(e.showarrow)e.axref===e.xref?lt[l+".ax"]=a.p2r(a.r2p(e.ax)+t):lt[l+".ax"]=e.ax+t,e.ayref===e.yref?lt[l+".ay"]=o.p2r(o.r2p(e.ay)+r):lt[l+".ay"]=e.ay+r,ct(t,r);else{if(n)return;if(a)lt[l+".x"]=a.p2r(a.r2p(e.x)+t);else{var s=e._xsize/c.w,u=e.x+(e._xshift-e.xshift)/c.w-s/2;lt[l+".x"]=da.align(u+t/c.w,s,0,1,e.xanchor)}if(o)lt[l+".y"]=o.p2r(o.r2p(e.y)+r);else{var h=e._ysize/c.h,f=e.y-(e._yshift+e.yshift)/c.h-h/2;lt[l+".y"]=da.align(f-r/c.h,h,0,1,e.yanchor)}a&&o||(i=da.getCursor(a?.5:lt[l+".x"],o?.5:lt[l+".y"],e.xanchor,e.yanchor))}v.attr({transform:"translate("+t+","+r+")"+ut}),ka(x,i)},doneFn:function(){ka(x),O.call("relayout",t,lt);var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}var Hd=Vd.draw;function Gd(t){var e=t._fullLayout;oe.filterVisible(e.annotations).forEach(function(e){var r,n,i,a,o=ui.getFromId(t,e.xref),s=ui.getFromId(t,e.yref),l=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;o&&o.autorange&&(r=l+e.xshift,n=l-e.xshift,i=u+e.xshift,a=u-e.xshift,e.axref===e.xref?(ui.expand(o,[o.r2c(e.x)],{ppadplus:r,ppadminus:n}),ui.expand(o,[o.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,a)})):(i=e.ax?i+e.ax:i,a=e.ax?a-e.ax:a,ui.expand(o,[o.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,a)}))),s&&s.autorange&&(r=l-e.yshift,n=l+e.yshift,i=u-e.yshift,a=u+e.yshift,e.ayref===e.yref?(ui.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),ui.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,a)})):(i=e.ay?i+e.ay:i,a=e.ay?a-e.ay:a,ui.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,a)})))})}var Wd={hasClickToShow:function(t,e){var r=Yd(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,n=Yd(t,e),i=n.on,a=n.off.concat(n.explicitOff),o={};if(!i.length&&!a.length)return;for(r=0;r1){o=!0;break}}o?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+i+'"]').remove():(a._pdata=ig(t.glplot.cameraParams,[e.xaxis.r2l(a.x)*r[0],e.yaxis.r2l(a.y)*r[1],e.zaxis.r2l(a.z)*r[2]]),ag(t.graphDiv,a,i,t.id,a._xa,a._ya))}}};var lg={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}},ug=function(t){var e=t.type,r=t.symmetric;if("data"===e){var n=t.array||[];if(r)return function(t,e){var r=+n[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+n[e],a=+i[e];return isNaN(r)&&isNaN(a)?[NaN,NaN]:[a||0,r||0]}}var a=cg(e,t.value),o=cg(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=a(t);return[e,e]}:function(t){return[o(t),a(t)]}};function cg(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}var hg=function(t){for(var e=t.calcdata,r=0;r0;t.each(function(t){var l,u=t[0].trace,c=u.error_x||{},h=u.error_y||{};u.ids&&(l=function(t){return t.id});var f=Er.hasMarkers(u)&&u.marker.maxdisplayed>0;h.visible||c.visible||(t=[]);var p=i.select(this).selectAll("g.errorbar").data(t,l);if(p.exit().remove(),t.length){c.visible||p.selectAll("path.xerror").remove(),h.visible||p.selectAll("path.yerror").remove(),p.style("opacity",1);var d=p.enter().append("g").classed("errorbar",!0);s&&d.style("opacity",0).transition().duration(r.duration).style("opacity",1),Lr.setClipUrl(p,e.layerClipId),p.each(function(t){var e=i.select(this),l=function(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}(t,n,o);if(!f||t.vis){var u,p=e.select("path.yerror");if(h.visible&&a(l.x)&&a(l.yh)&&a(l.ys)){var d=h.width;u="M"+(l.x-d)+","+l.yh+"h"+2*d+"m-"+d+",0V"+l.ys,l.noYS||(u+="m-"+d+",0h"+2*d),p.size()?s&&(p=p.transition().duration(r.duration).ease(r.easing)):p=e.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0),p.attr("d",u)}else p.remove();var g=e.select("path.xerror");if(c.visible&&a(l.y)&&a(l.xh)&&a(l.xs)){var v=(c.copy_ystyle?h:c).width;u="M"+l.xh+","+(l.y-v)+"v"+2*v+"m0,-"+v+"H"+l.xs,l.noXS||(u+="m0,-"+v+"v"+2*v),g.size()?s&&(g=g.transition().duration(r.duration).ease(r.easing)):g=e.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0),g.attr("d",u)}else g.remove()}})}})},style:function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},n=e.error_x||{},a=i.select(this);a.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(Fe.stroke,r.color),n.copy_ystyle&&(n=r),a.selectAll("path.xerror").style("stroke-width",n.thickness+"px").call(Fe.stroke,n.color)})},hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}};var mg=nt.counter,yg=zh.attributes,xg=Ee.idRegex,bg={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:!0,dimensions:2,items:{valType:"enumerated",values:[mg("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[xg.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[xg.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:yg({name:"grid",editType:"plot",noGridCell:!0},{}),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 _g(t,e,r){var n=e[r+"axes"],i=Object.keys((t._splomAxes||{})[r]||{});return Array.isArray(n)?n:i.length?i:void 0}function wg(t,e,r,n,i,a){var o=e(t+"gap",r),s=e("domain."+t);e(t+"side",n);for(var l=new Array(i),u=s[0],c=(s[1]-u)/(i-o),h=c*(1-o),f=0;f1){s||l||u||"independent"===x("pattern")&&(s=!0),h._hasSubplotGrid=s;var d,g,v="top to bottom"===x("roworder"),m=s?.2:.1,y=s?.3:.1;c&&(d="bottom",g="left"),h._domains={x:wg("x",x,m,d,p),y:wg("y",x,y,g,f,v)}}}function x(t,e){return oe.coerce(r,h,bg,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,i,a,o,s,l,u,c=t.grid||{},h=e._subplots,f=r._hasSubplotGrid,p=r.rows,d=r.columns,g="independent"===r.pattern,v=r._axisMap={};if(f){var m=c.subplots||[];l=r.subplots=new Array(p);var y=1;for(n=0;n=2/3},isCenterAnchor:function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},isBottomAnchor:function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},isMiddleAnchor:function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},zg={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4},Dg=!0,Ig=function(t,e,r){if(!e._dragged&&!e._editing){var n,i,a,o,s,l=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],u=t.data()[0][0],c=e._fullData,h=u.trace,f=h.legendgroup,p={},d=[],g=[],v=[];if(1===r&&Dg&&e.data&&e._context.showTips?(oe.notifier(oe._(e,"Double-click on legend to isolate one trace"),"long"),Dg=!1):Dg=!1,O.traceIs(h,"pie")){var m=u.label,y=l.indexOf(m);1===r?-1===y?l.push(m):l.splice(y,1):2===r&&(l=[],e.calcdata[0].forEach(function(t){m!==t.label&&l.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===l.length&&-1===y&&(l=[])),O.call("relayout",e,"hiddenlabels",l)}else{var x,b=f&&f.length,_=[];if(b)for(n=0;nr[1])return r[1]}return i}function h(t){return t[0]}if(s||l||u){var f={},p={};s&&(f.mc=c("marker.color",h),f.mo=c("marker.opacity",oe.mean,[.2,1]),f.ms=c("marker.size",oe.mean,[2,16]),f.mlc=c("marker.line.color",h),f.mlw=c("marker.line.width",oe.mean,[0,5]),p.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),u&&(p.line={width:c("line.width",h,[0,10])}),l&&(f.tx="Aa",f.tp=c("textposition",h),f.ts=10,f.tc=c("textfont.color",h),f.tf=c("textfont.family",h)),r=[oe.minExtend(a,f)],n=oe.minExtend(o,p)}var d=i.select(this).select("g.legendpoints"),g=d.selectAll("path.scatterpts").data(s?r:[]);g.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),g.exit().remove(),g.call(Lr.pointStyle,n,e),s&&(r[0].mrc=3);var v=d.selectAll("g.pointtext").data(l?r:[]);v.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),v.exit().remove(),v.selectAll("text").call(Lr.textPointStyle,n,e)}).each(function(t){var e=t[0].trace,r=i.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var n=e[r?"increasing":"decreasing"],a=n.line.width,o=i.select(this);o.style("stroke-width",a+"px").call(Fe.fill,n.fillcolor),a&&Fe.stroke(o,n.line.color)})}).each(function(t){var e=t[0].trace,r=i.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var n=e[r?"increasing":"decreasing"],a=n.line.width,o=i.select(this);o.style("fill","none").call(Lr.dashLine,n.line.dash,a),a&&Fe.stroke(o,n.line.color)})})},Ng=er.LINE_SPACING,jg=er.FROM_TL,Vg=er.FROM_BR,Ug=g.DBLCLICKDELAY;function qg(t,e){var r=t.data()[0][0],n=e._fullLayout,i=r.trace,a=O.traceIs(i,"pie"),o=i.index,s=a?r.label:i.name,l=oe.ensureSingle(t,"text","legendtext");function u(r){ir.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,i,a=t.select("g[class*=math-group]"),o=a.node(),s=e._fullLayout.legend.font.size*Ng;if(o){var l=Lr.bBox(o);n=l.height,i=l.width,Lr.setTranslate(a,0,n/4)}else{var u=t.select(".legendtext"),c=ir.lineCount(u),h=u.node();n=s*c,i=h?Lr.bBox(h).width:0;var f=s*(.3+(1-c)/2);ir.positionText(u,40,f)}n=Math.max(n,16)+3,r.height=n,r.width=i}(t,e)})}l.attr("text-anchor","start").classed("user-select-none",!0).call(Lr.font,n.legend.font).text(s),e._context.edits.legendText&&!a?l.call(ir.makeEditable,{gd:e}).call(u).on("edit",function(t){this.text(t).call(u);var n=t;this.text()||(t=" ");var i=r.trace._fullInput||{},a={};if(O.hasTransform(i,"groupby")){var s=O.getTransformIndices(i,"groupby"),l=s[s.length-1],c=oe.keyedContainer(i,"transforms["+l+"].styles","target","value.name");""===n?c.remove(r.trace._group):c.set(r.trace._group,t),a=c.constructUpdate()}else a.name=t;return O.call("restyle",e,a,o)}):u(l)}function Hg(t,e){var r,n=1,i=oe.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call(Fe.fill,"rgba(0,0,0,0)")});i.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTimeUg&&(n=Math.max(n-1,1)),1===n?r._clickTimeout=setTimeout(function(){Ig(t,e,n)},Ug):2===n&&(r._clickTimeout&&clearTimeout(r._clickTimeout),e._legendMouseDownTime=0,Ig(t,e,n))}})}function Gg(t,e,r){var n=t._fullLayout,a=n.legend,o=a.borderwidth,s=Lg.isGrouped(a),l=0;if(a._width=0,a._height=0,Lg.isVertical(a))s&&e.each(function(t,e){Lr.setTranslate(this,0,e*a.tracegroupgap)}),r.each(function(t){var e=t[0],r=e.height,n=e.width;Lr.setTranslate(this,o,5+o+a._height+r/2),a._height+=r,a._width=Math.max(a._width,n)}),a._width+=45+2*o,a._height+=10+2*o,s&&(a._height+=(a._lgroupsLength-1)*a.tracegroupgap),l=40;else if(s){for(var u=[a._width],c=e.data(),h=0,f=c.length;ho+b-_,r.each(function(t){var e=t[0],r=g?40+t[0].width:y;o+x+_+r>n.width-(n.margin.r+n.margin.l)&&(x=0,v+=m,a._height=a._height+m,m=0),Lr.setTranslate(this,o+x,5+o+e.height/2+v),a._width+=_+r,a._height=Math.max(a._height,e.height),x+=_+r,m=Math.max(e.height,m)}),a._width+=2*o,a._height+=10+2*o}a._width=Math.ceil(a._width),a._height=Math.ceil(a._height),r.each(function(e){var r=e[0],n=i.select(this).select(".legendtoggle");Lr.setRect(n,0,-r.height/2,(t._context.edits.legendText?0:a._width)+l,r.height)})}function Wg(t){var e=t._fullLayout.legend,r="left";Pg.isRightAnchor(e)?r="right":Pg.isCenterAnchor(e)&&(r="center");var n="top";Pg.isBottomAnchor(e)?n="bottom":Pg.isMiddleAnchor(e)&&(n="middle"),Sn.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*jg[r],r:e._width*Vg[r],b:e._height*Vg[n],t:e._height*jg[n]})}var Yg={moduleType:"component",name:"legend",layoutAttributes:Eg,supplyLayoutDefaults:function(t,e,r){for(var n,i,a,o,s=t.legend||{},l={},u=0,c="normal",h=0;h1)){if(e.legend=l,p("bgcolor",e.paper_bgcolor),p("bordercolor"),p("borderwidth"),oe.coerceFont(p,"font",e.font),p("orientation"),"h"===l.orientation){var d=t.xaxis;d&&d.rangeslider&&d.rangeslider.visible?(n=0,a="left",i=1.1,o="bottom"):(n=0,a="left",i=-.1,o="top")}p("traceorder",c),Lg.isGrouped(e.legend)&&p("tracegroupgap"),p("x",n),p("xanchor",a),p("y",i),p("yanchor",o),oe.noneOrAll(s,l,["x","y"])}},draw:function(t){var e=t._fullLayout,r="legend"+e._uid;if(e._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var n=e.legend,a=e.showlegend&&function(t,e){var r,n,i={},a=[],o=!1,s={},l=0;function u(t,r){if(""!==t&&Lg.isGrouped(e))-1===a.indexOf(t)?(a.push(t),o=!0,i[t]=[[r]]):i[t].push([r]);else{var n="~~i"+l;a.push(n),i[n]=[[r]],l++}}for(r=0;rv?function(t){var e=t._fullLayout.legend,r="left";Pg.isRightAnchor(e)?r="right":Pg.isCenterAnchor(e)&&(r="center"),Sn.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*jg[r],r:e._width*Vg[r],b:0,t:0})}(t):Wg(t);var m=e._size,y=m.l+m.w*n.x,x=m.t+m.h*(1-n.y);Pg.isRightAnchor(n)?y-=n._width:Pg.isCenterAnchor(n)&&(y-=n._width/2),Pg.isBottomAnchor(n)?x-=n._height:Pg.isMiddleAnchor(n)&&(x-=n._height/2);var b=n._width,_=m.w;b>_?(y=m.l,b=_):(y+b>g&&(y=g-b),y<0&&(y=0),b=Math.min(g-y,n._width));var w,k,M,A,T=n._height,S=m.h;if(T>S?(x=m.t,T=S):(x+T>v&&(x=v-T),x<0&&(x=0),T=Math.min(v-x,n._height)),Lr.setTranslate(l,y,x),f.on(".drag",null),l.on("wheel",null),n._height<=T||t._context.staticPlot)c.attr({width:b-n.borderwidth,height:T-n.borderwidth,x:n.borderwidth/2,y:n.borderwidth/2}),Lr.setTranslate(h,0,0),u.select("rect").attr({width:b-2*n.borderwidth,height:T-2*n.borderwidth,x:n.borderwidth,y:n.borderwidth}),Lr.setClipUrl(h,r),Lr.setRect(f,0,0,0,0),delete n._scrollY;else{var C,E,L=Math.max(zg.scrollBarMinHeight,T*T/n._height),P=T-L-2*zg.scrollBarMargin,z=n._height-T,D=P/z,I=Math.min(n._scrollY||0,z);c.attr({width:b-2*n.borderwidth+zg.scrollBarWidth+zg.scrollBarMargin,height:T-n.borderwidth,x:n.borderwidth/2,y:n.borderwidth/2}),u.select("rect").attr({width:b-2*n.borderwidth+zg.scrollBarWidth+zg.scrollBarMargin,height:T-2*n.borderwidth,x:n.borderwidth,y:n.borderwidth+I}),Lr.setClipUrl(h,r),B(I,L,D),l.on("wheel",function(){B(I=oe.constrain(n._scrollY+i.event.deltaY/P*z,0,z),L,D),0!==I&&I!==z&&i.event.preventDefault()});var R=i.behavior.drag().on("dragstart",function(){C=i.event.sourceEvent.clientY,E=I}).on("drag",function(){var t=i.event.sourceEvent;2===t.buttons||t.ctrlKey||B(I=oe.constrain((t.clientY-C)/D+E,0,z),L,D)});f.call(R)}t._context.edits.legendPosition&&(l.classed("cursor-move",!0),da.init({element:l.node(),gd:t,prepFn:function(){var t=Lr.getTranslate(l);M=t.x,A=t.y},moveFn:function(t,e){var r=M+t,i=A+e;Lr.setTranslate(l,r,i),w=da.align(r,0,m.l,m.l+m.w,n.xanchor),k=da.align(i,0,m.t+m.h,m.t,n.yanchor)},doneFn:function(){void 0!==w&&void 0!==k&&O.call("relayout",t,{"legend.x":w,"legend.y":k})},clickFn:function(r,n){var i=e._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});i.size()>0&&(1===r?l._clickTimeout=setTimeout(function(){Ig(i,t,r)},Ug):2===r&&(l._clickTimeout&&clearTimeout(l._clickTimeout),Ig(i,t,r)))}}))}function B(e,r,i){n._scrollY=t._fullLayout.legend._scrollY=e,Lr.setTranslate(h,0,-e),Lr.setRect(f,b,zg.scrollBarMargin+e*i,zg.scrollBarWidth,r),u.select("rect").attr({y:n.borderwidth+e})}},style:Fg},Xg={step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"},Zg=b.extendFlat,Jg={visible:{valType:"boolean",editType:"plot"},buttons:Xg=Zg(Xg,{_isLinkedToArray:"button"}),x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:E({editType:"plot"}),bgcolor:{valType:"color",dflt:z.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:z.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"},Kg={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10};var Qg=function(t,e){var r=t._name,n={};if("all"===e.step)n[r+".autorange"]=!0;else{var a=function(t,e){var r,n=t.range,a=new Date(t.r2l(n[1])),o=e.step,s=e.count;switch(e.stepmode){case"backward":r=t.l2r(+i.time[o].utc.offset(a,-s));break;case"todate":var l=i.time[o].utc.offset(a,-s);r=t.l2r(+i.time[o].utc.ceil(l))}var u=n[1];return[r,u]}(t,e);n[r+".range[0]"]=a[0],n[r+".range[1]"]=a[1]}return n};var $g=er.LINE_SPACING,tv=er.FROM_TL,ev=er.FROM_BR;function rv(t){return t._id}function nv(t,e,r){var n=oe.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:Kg.rx,ry:Kg.ry}),n.call(Fe.stroke,e.bordercolor).call(Fe.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function iv(t,e,r,n){var i;oe.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(Lr.font,e.font).text((i=r,i.label?i.label:"all"===i.step?"all":i.count+i.step.charAt(0))).call(function(t){ir.convertToTspans(t,n)})}var av={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:Jg}}},layoutAttributes:Jg,handleDefaults:function(t,e,r,n,i){var a=t.rangeselector||{},o=e.rangeselector={};function s(t,e){return oe.coerce(a,o,Jg,t,e)}if(s("visible",function(t,e,r){var n,i,a=t.buttons||[],o=e.buttons=[];function s(t,e){return oe.coerce(n,i,Xg,t,e)}for(var l=0;l0)){var l=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),i=0,a=0;a0?u+o:o;return{ppad:o,ppadplus:s?h:f,ppadminus:s?f:h}}return{ppad:o}}function Sv(t,e,r,n,i){var a="category"===t.type?t.r2c:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var o,s,l,u,c=1/0,h=-1/0,f=n.match(wv.segmentRE);for("date"===t.type&&(a=kv.decodeDate(a)),o=0;oh&&(h=u)));return h>=c?[c,h]:void 0}}var Cv=function(t,e,r,n,i){function a(r,n){return oe.coerce(t,e,_v,r,n)}if(n=n||{},!a("visible",!(i=i||{}).itemIsNotPlainObject))return e;a("layer"),a("opacity"),a("fillcolor"),a("line.color"),a("line.width"),a("line.dash");for(var o=a("type",t.path?"path":"rect"),s=a("xsizemode"),l=a("ysizemode"),u=["x","y"],c=0;c<2;c++){var h,f,p,d=u[c],g=d+"anchor",v="x"===d?s:l,m={_fullLayout:r},y=ui.coerceRef(t,e,m,d,"","paper");if("paper"!==y?(h=ui.getFromId(m,y),p=kv.rangeToShapePosition(h),f=kv.shapePositionToRange(h)):f=p=oe.identity,"path"!==o){var x=d+"0",b=d+"1",_=t[x],w=t[b];t[x]=f(t[x],!0),t[b]=f(t[b],!0),"pixel"===v?(a(x,0),a(b,10)):(ui.coercePosition(e,m,a,y,x,.25),ui.coercePosition(e,m,a,y,b,.75)),e[x]=p(e[x]),e[b]=p(e[b]),t[x]=_,t[b]=w}if("pixel"===v){var k=t[g];t[g]=f(t[g],!0),ui.coercePosition(e,m,a,y,g,.25),e[g]=p(e[g]),t[g]=k}}return"path"===o?a("path"):oe.noneOrAll(t,e,["x0","x1","y0","y1"]),e},Ev={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var i=0;il?(m=o,_=O+".y0",A="y0",y=l,w=O+".y1",T="y1"):(m=l,_=O+".y1",A="y1",y=o,w=O+".y0",T="y0");i={},H(e),q.moveFn="move"===F?G:W},doneFn:function(){ka(e),O.call("relayout",t,i)}};function H(t){var r=q.element.getBoundingClientRect(),n=r.right-r.left,i=r.bottom-r.top,a=t.clientX-r.left,o=t.clientY-r.top,s=n>N&&i>j&&!t.shiftKey?da.getCursor(a/n,1-o/i):"move";ka(e,s),F=s.split("-")[0]}function G(n,m){if("path"===r.type){var y=function(t){return t},x=y,b=y;V?i[g]=r.xanchor=R(u+n):(x=function(t){return R(D(t)+n)},P&&"date"===P.type&&(x=kv.encodeDate(x))),U?i[v]=r.yanchor=B(c+m):(b=function(t){return B(I(t)+m)},z&&"date"===z.type&&(b=kv.encodeDate(b))),r.path=zv(E,x,b),i[L]=r.path}else V?i[g]=r.xanchor=R(u+n):(i[h]=r.x0=R(a+n),i[p]=r.x1=R(s+n)),U?i[v]=r.yanchor=B(c+m):(i[f]=r.y0=B(o+m),i[d]=r.y1=B(l+m));e.attr("d",Pv(t,r))}function W(n,a){if("path"===r.type){var o=function(t){return t},s=o,l=o;V?i[g]=r.xanchor=R(u+n):(s=function(t){return R(D(t)+n)},P&&"date"===P.type&&(s=kv.encodeDate(s))),U?i[v]=r.yanchor=B(c+a):(l=function(t){return B(I(t)+a)},z&&"date"===z.type&&(l=kv.encodeDate(l))),r.path=zv(E,s,l),i[L]=r.path}else{var h=~F.indexOf("n")?m+a:m,f=~F.indexOf("s")?y+a:y,p=~F.indexOf("w")?x+n:x,d=~F.indexOf("e")?b+n:b;~F.indexOf("n")&&U&&(h=m-a),~F.indexOf("s")&&U&&(f=y-a),(!U&&f-h>j||U&&h-f>j)&&(i[_]=r[A]=U?h:B(h),i[w]=r[T]=U?f:B(f)),d-p>N&&(i[k]=r[S]=V?p:R(p),i[M]=r[C]=V?d:R(d))}e.attr("d",Pv(t,r))}da.init(q),e.node().onmousemove=H}(t,o,n,e)}}function Pv(t,e){var r,n,i,a,o,s,l,u,c=e.type,h=ui.getFromId(t,e.xref),f=ui.getFromId(t,e.yref),p=t._fullLayout._size;if(h?(r=kv.shapePositionToRange(h),n=function(t){return h._offset+h.r2p(r(t,!0))}):n=function(t){return p.l+p.w*t},f?(i=kv.shapePositionToRange(f),a=function(t){return f._offset+f.r2p(i(t,!0))}):a=function(t){return p.t+p.h*(1-t)},"path"===c)return h&&"date"===h.type&&(n=kv.decodeDate(n)),f&&"date"===f.type&&(a=kv.decodeDate(a)),function(t,e,r){var n=t.path,i=t.xsizemode,a=t.ysizemode,o=t.xanchor,s=t.yanchor;return n.replace(wv.segmentRE,function(t){var n=0,l=t.charAt(0),u=wv.paramIsX[l],c=wv.paramIsY[l],h=wv.numParams[l],f=t.substr(1).replace(wv.paramRE,function(t){return u[n]?t="pixel"===i?e(o)+Number(t):e(t):c[n]&&(t="pixel"===a?r(s)-Number(t):r(t)),++n>h&&(t="X"),t});return n>h&&(f=f.replace(/[\s,]*X.*/,""),oe.log("Ignoring extra params in segment "+t)),l+f})}(e,n,a);if("pixel"===e.xsizemode){var d=n(e.xanchor);o=d+e.x0,s=d+e.x1}else o=n(e.x0),s=n(e.x1);if("pixel"===e.ysizemode){var g=a(e.yanchor);l=g-e.y0,u=g-e.y1}else l=a(e.y0),u=a(e.y1);if("line"===c)return"M"+o+","+l+"L"+s+","+u;if("rect"===c)return"M"+o+","+l+"H"+s+"V"+u+"H"+o+"Z";var v=(o+s)/2,m=(l+u)/2,y=Math.abs(v-o),x=Math.abs(m-l),b="A"+y+","+x,_=v+y+","+m;return"M"+_+b+" 0 1,1 "+(v+","+(m-x))+b+" 0 0,1 "+_+"Z"}function zv(t,e,r){return t.replace(wv.segmentRE,function(t){var n=0,i=t.charAt(0),a=wv.paramIsX[i],o=wv.paramIsY[i],s=wv.numParams[i];return i+t.substr(1).replace(wv.paramRE,function(t){return n>=s?t:(a[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}var Dv={moduleType:"component",name:"shapes",layoutAttributes:_v,supplyLayoutDefaults:function(t,e){Kd(t,e,{name:"shapes",handleItemDefaults:Cv})},includeBasePlot:Qd("shapes"),calcAutorange:function(t){var e=t._fullLayout,r=oe.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var n=0;n0)&&(n("active"),n("x"),n("y"),oe.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("len"),n("lenmode"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),oe.coerceFont(n,"font",r.font),n("currentvalue.visible")&&(n("currentvalue.xanchor"),n("currentvalue.prefix"),n("currentvalue.suffix"),n("currentvalue.offset"),oe.coerceFont(n,"currentvalue.font",e.font)),n("transition.duration"),n("transition.easing"),n("bgcolor"),n("activebgcolor"),n("bordercolor"),n("borderwidth"),n("ticklen"),n("tickwidth"),n("tickcolor"),n("minorticklen"))}var Vv=er.LINE_SPACING,Uv=er.FROM_TL,qv=er.FROM_BR;function Hv(t){return t._index}function Gv(t,e){var r=Lr.tester.selectAll("g."+Iv.labelGroupClass).data(e.steps);r.enter().append("g").classed(Iv.labelGroupClass,!0);var n=0,a=0;r.each(function(t){var r=Xv(i.select(this),{step:t},e).node();if(r){var o=Lr.bBox(r);a=Math.max(a,o.height),n=Math.max(n,o.width)}}),r.remove();var o=e._dims={};o.inputAreaWidth=Math.max(Iv.railWidth,Iv.gripHeight);var s=t._fullLayout._size;o.lx=s.l+s.w*e.x,o.ly=s.t+s.h*(1-e.y),"fraction"===e.lenmode?o.outerLength=Math.round(s.w*e.len):o.outerLength=e.len,o.inputAreaStart=0,o.inputAreaLength=Math.round(o.outerLength-e.pad.l-e.pad.r);var l=(o.inputAreaLength-2*Iv.stepInset)/(e.steps.length-1),u=n+Iv.labelPadding;if(o.labelStride=Math.max(1,Math.ceil(u/l)),o.labelHeight=a,o.currentValueMaxWidth=0,o.currentValueHeight=0,o.currentValueTotalHeight=0,o.currentValueMaxLines=1,e.currentvalue.visible){var c=Lr.tester.append("g");r.each(function(t){var r=Wv(c,e,t.label),n=r.node()&&Lr.bBox(r.node())||{width:0,height:0},i=ir.lineCount(r);o.currentValueMaxWidth=Math.max(o.currentValueMaxWidth,Math.ceil(n.width)),o.currentValueHeight=Math.max(o.currentValueHeight,Math.ceil(n.height)),o.currentValueMaxLines=Math.max(o.currentValueMaxLines,i)}),o.currentValueTotalHeight=o.currentValueHeight+e.currentvalue.offset,c.remove()}o.height=o.currentValueTotalHeight+Iv.tickOffset+e.ticklen+Iv.labelOffset+o.labelHeight+e.pad.t+e.pad.b;var h="left";Pg.isRightAnchor(e)&&(o.lx-=o.outerLength,h="right"),Pg.isCenterAnchor(e)&&(o.lx-=o.outerLength/2,h="center");var f="top";Pg.isBottomAnchor(e)&&(o.ly-=o.height,f="bottom"),Pg.isMiddleAnchor(e)&&(o.ly-=o.height/2,f="middle"),o.outerLength=Math.ceil(o.outerLength),o.height=Math.ceil(o.height),o.lx=Math.round(o.lx),o.ly=Math.round(o.ly),Sn.autoMargin(t,Iv.autoMarginIdRoot+e._index,{x:e.x,y:e.y,l:o.outerLength*Uv[h],r:o.outerLength*qv[h],b:o.height*qv[f],t:o.height*Uv[f]})}function Wv(t,e,r){if(e.currentvalue.visible){var n,i,a=e._dims;switch(e.currentvalue.xanchor){case"right":n=a.inputAreaLength-Iv.currentValueInset-a.currentValueMaxWidth,i="left";break;case"center":n=.5*a.inputAreaLength,i="middle";break;default:n=Iv.currentValueInset,i="left"}var o=oe.ensureSingle(t,"text",Iv.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":i,"data-notex":1})}),s=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)s+=r;else s+=e.steps[e.active].label;e.currentvalue.suffix&&(s+=e.currentvalue.suffix),o.call(Lr.font,e.currentvalue.font).text(s).call(ir.convertToTspans,e._gd);var l=ir.lineCount(o),u=(a.currentValueMaxLines+1-l)*e.currentvalue.font.size*Vv;return ir.positionText(o,n,u),o}}function Yv(t,e,r){oe.ensureSingle(t,"rect",Iv.gripRectClass,function(n){n.call(Qv,e,t,r).style("pointer-events","all")}).attr({width:Iv.gripWidth,height:Iv.gripHeight,rx:Iv.gripRadius,ry:Iv.gripRadius}).call(Fe.stroke,r.bordercolor).call(Fe.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function Xv(t,e,r){var n=oe.ensureSingle(t,"text",Iv.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return n.call(Lr.font,r.font).text(e.step.label).call(ir.convertToTspans,r._gd),n}function Zv(t,e){var r=oe.ensureSingle(t,"g",Iv.labelsClass),n=e._dims,a=r.selectAll("g."+Iv.labelGroupClass).data(n.labelSteps);a.enter().append("g").classed(Iv.labelGroupClass,!0),a.exit().remove(),a.each(function(t){var r=i.select(this);r.call(Xv,t,e),Lr.setTranslate(r,em(e,t.fraction),Iv.tickOffset+e.ticklen+e.font.size*Vv+Iv.labelOffset+n.currentValueTotalHeight)})}function Jv(t,e,r,n,i){var a=Math.round(n*(r.steps.length-1));a!==r.active&&Kv(t,e,r,a,!0,i)}function Kv(t,e,r,n,i,a){var o=r.active;r._input.active=r.active=n;var s=r.steps[r.active];e.call(tm,r,r.active/(r.steps.length-1),a),e.call(Wv,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:o}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=a):(e._nextMethod={step:s,doCallback:i,doTransition:a},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&Sn.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function Qv(t,e,r){var n=r.node(),a=i.select(e);function o(){return r.data()[0]}t.on("mousedown",function(){var t=o();e.emit("plotly_sliderstart",{slider:t});var s=r.select("."+Iv.gripRectClass);i.event.stopPropagation(),i.event.preventDefault(),s.call(Fe.fill,t.activebgcolor);var l=rm(t,i.mouse(n)[0]);Jv(e,r,t,l,!0),t._dragging=!0,a.on("mousemove",function(){var t=o(),a=rm(t,i.mouse(n)[0]);Jv(e,r,t,a,!1)}),a.on("mouseup",function(){var t=o();t._dragging=!1,s.call(Fe.fill,t.bgcolor),a.on("mouseup",null),a.on("mousemove",null),e.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function $v(t,e){var r=t.selectAll("rect."+Iv.tickRectClass).data(e.steps),n=e._dims;r.enter().append("rect").classed(Iv.tickRectClass,!0),r.exit().remove(),r.attr({width:e.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var a=r%n.labelStride==0,o=i.select(this);o.attr({height:a?e.ticklen:e.minorticklen}).call(Fe.fill,e.tickcolor),Lr.setTranslate(o,em(e,r/(e.steps.length-1))-.5*e.tickwidth,(a?Iv.tickOffset:Iv.minorTickOffset)+n.currentValueTotalHeight)})}function tm(t,e,r,n){var i=t.select("rect."+Iv.gripRectClass),a=em(e,r);if(!e._invokingCommand){var o=i;n&&e.transition.duration>0&&(o=o.transition().duration(e.transition.duration).ease(e.transition.easing)),o.attr("transform","translate("+(a-.5*Iv.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function em(t,e){var r=t._dims;return r.inputAreaStart+Iv.stepInset+(r.inputAreaLength-2*Iv.stepInset)*Math.min(1,Math.max(0,e))}function rm(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-Iv.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*Iv.stepInset-2*r.inputAreaStart)))}function nm(t,e,r){var n=r._dims,i=oe.ensureSingle(t,"rect",Iv.railTouchRectClass,function(n){n.call(Qv,e,t,r).style("pointer-events","all")});i.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,Iv.tickOffset+r.ticklen+n.labelHeight)}).call(Fe.fill,r.bgcolor).attr("opacity",0),Lr.setTranslate(i,0,n.currentValueTotalHeight)}function im(t,e){var r=e._dims,n=r.inputAreaLength-2*Iv.railInset,i=oe.ensureSingle(t,"rect",Iv.railRectClass);i.attr({width:n,height:Iv.railWidth,rx:Iv.railRadius,ry:Iv.railRadius,"shape-rendering":"crispEdges"}).call(Fe.stroke,e.bordercolor).call(Fe.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),Lr.setTranslate(i,Iv.railInset,.5*(r.inputAreaWidth-Iv.railWidth)+r.currentValueTotalHeight)}var am={moduleType:"component",name:Iv.name,layoutAttributes:Bv,supplyLayoutDefaults:function(t,e){Kd(t,e,{name:Fv,handleItemDefaults:jv})},draw:function(t){var e=t._fullLayout,r=function(t,e){for(var r=t[Iv.name],n=[],i=0;i0?[0]:[]);if(n.enter().append("g").classed(Iv.containerClassName,!0).style("cursor","ew-resize"),n.exit().remove(),n.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;n=r.steps.length&&(r.active=0),e.call(Wv,r).call(im,r).call(Zv,r).call($v,r).call(nm,t,r).call(Yv,t,r);var n=r._dims;Lr.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(tm,r,r.active/(r.steps.length-1),!1),e.call(Wv,r)}(t,i.select(this),e)}})}}},om=b.extendFlat,sm=(0,_e.overrideAll)({_isLinkedToArray:"updatemenu",_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:{_isLinkedToArray:"button",method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}},x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:om({},Ov,{}),font:E({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:z.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}},"arraydraw","from-root"),lm={name:"updatemenus",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",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}},um=lm.name,cm=sm.buttons;function hm(t,e,r){function n(r,n){return oe.coerce(t,e,sm,r,n)}n("visible",function(t,e){var r,n,i=t.buttons||[],a=e.buttons=[];function o(t,e){return oe.coerce(r,n,cm,t,e)}for(var s=0;s0)&&(n("active"),n("direction"),n("type"),n("showactive"),n("x"),n("y"),oe.noneOrAll(t,e,["x","y"]),n("xanchor"),n("yanchor"),n("pad.t"),n("pad.r"),n("pad.b"),n("pad.l"),oe.coerceFont(n,"font",r.font),n("bgcolor",r.paper_bgcolor),n("bordercolor"),n("borderwidth"))}var fm=pm;function pm(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}pm.barWidth=2,pm.barLength=20,pm.barRadius=2,pm.barPad=1,pm.barColor="#808BA4",pm.prototype.enable=function(t,e,r){var n=this.gd._fullLayout,a=n.width,o=n.height;this.position=t;var s,l,u,c,h=this.position.l,f=this.position.w,p=this.position.t,d=this.position.h,g=this.position.direction,v="down"===g,m="left"===g,y="up"===g,x=f,b=d;v||m||"right"===g||y||(this.position.direction="down",v=!0),v||y?(l=(s=h)+x,v?(u=p,b=(c=Math.min(u+b,o))-u):b=(c=p+b)-(u=Math.max(c-b,0))):(c=(u=p)+b,m?x=(l=h+x)-(s=Math.max(l-x,0)):(s=h,x=(l=Math.min(s+x,a))-s)),this._box={l:s,t:u,w:x,h:b};var _=f>x,w=pm.barLength+2*pm.barPad,k=pm.barWidth+2*pm.barPad,M=h,A=p+d;A+k>o&&(A=o-k);var T=this.container.selectAll("rect.scrollbar-horizontal").data(_?[0]:[]);T.exit().on(".drag",null).remove(),T.enter().append("rect").classed("scrollbar-horizontal",!0).call(Fe.fill,pm.barColor),_?(this.hbar=T.attr({rx:pm.barRadius,ry:pm.barRadius,x:M,y:A,width:w,height:k}),this._hbarXMin=M+w/2,this._hbarTranslateMax=x-w):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var S=d>b,C=pm.barWidth+2*pm.barPad,E=pm.barLength+2*pm.barPad,L=h+f,P=p;L+C>a&&(L=a-C);var z=this.container.selectAll("rect.scrollbar-vertical").data(S?[0]:[]);z.exit().on(".drag",null).remove(),z.enter().append("rect").classed("scrollbar-vertical",!0).call(Fe.fill,pm.barColor),S?(this.vbar=z.attr({rx:pm.barRadius,ry:pm.barRadius,x:L,y:P,width:C,height:E}),this._vbarYMin=P+E/2,this._vbarTranslateMax=b-E):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var D=this.id,I=s-.5,O=S?l+C+.5:l+.5,R=u-.5,B=_?c+k+.5:c+.5,F=n._topdefs.selectAll("#"+D).data(_||S?[0]:[]);if(F.exit().remove(),F.enter().append("clipPath").attr("id",D).append("rect"),_||S?(this._clipRect=F.select("rect").attr({x:Math.floor(I),y:Math.floor(R),width:Math.ceil(O)-Math.floor(I),height:Math.ceil(B)-Math.floor(R)}),this.container.call(Lr.setClipUrl,D),this.bg.attr({x:h,y:p,width:f,height:d})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Lr.setClipUrl,null),delete this._clipRect),_||S){var N=i.behavior.drag().on("dragstart",function(){i.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(N);var j=i.behavior.drag().on("dragstart",function(){i.event.sourceEvent.preventDefault(),i.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));_&&this.hbar.on(".drag",null).call(j),S&&this.vbar.on(".drag",null).call(j)}this.setTranslate(e,r)},pm.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(Lr.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},pm.prototype._onBoxDrag=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t-=i.event.dx),this.vbar&&(e-=i.event.dy),this.setTranslate(t,e)},pm.prototype._onBoxWheel=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t+=i.event.deltaY),this.vbar&&(e+=i.event.deltaY),this.setTranslate(t,e)},pm.prototype._onBarDrag=function(){var t=this.translateX,e=this.translateY;if(this.hbar){var r=t+this._hbarXMin,n=r+this._hbarTranslateMax;t=(oe.constrain(i.event.x,r,n)-r)/(n-r)*(this.position.w-this._box.w)}if(this.vbar){var a=e+this._vbarYMin,o=a+this._vbarTranslateMax;e=(oe.constrain(i.event.y,a,o)-a)/(o-a)*(this.position.h-this._box.h)}this.setTranslate(t,e)},pm.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=oe.constrain(t||0,0,r),e=oe.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(Lr.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var i=t/r;this.hbar.call(Lr.setTranslate,t+i*this._hbarTranslateMax,e)}if(this.vbar){var a=e/n;this.vbar.call(Lr.setTranslate,t,e+a*this._vbarTranslateMax)}};var dm=er.LINE_SPACING;function gm(t){return t._index}function vm(t,e){return+t.attr(lm.menuIndexAttrName)===e._index}function mm(t,e,r,n,i,a,o,s){e._input.active=e.active=o,"buttons"===e.type?xm(t,n,null,null,e):"dropdown"===e.type&&(i.attr(lm.menuIndexAttrName,"-1"),ym(t,n,i,a,e),s||xm(t,n,i,a,e))}function ym(t,e,r,n,i){var a=oe.ensureSingle(e,"g",lm.headerClassName,function(t){t.style("pointer-events","all")}),o=i._dims,s=i.active,l=i.buttons[s]||lm.blankHeaderOpts,u={y:i.pad.t,yPad:0,x:i.pad.l,xPad:0,index:0},c={width:o.headerWidth,height:o.headerHeight};a.call(bm,i,l,t).call(Sm,i,u,c),oe.ensureSingle(e,"text",lm.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(Lr.font,i.font).text(lm.arrowSymbol[i.direction])}).attr({x:o.headerWidth-lm.arrowOffsetX+i.pad.l,y:o.headerHeight/2+lm.textOffsetY+i.pad.t}),a.on("click",function(){r.call(Cm),r.attr(lm.menuIndexAttrName,vm(r,i)?-1:String(i._index)),xm(t,e,r,n,i)}),a.on("mouseover",function(){a.call(Mm)}),a.on("mouseout",function(){a.call(Am,i)}),Lr.setTranslate(e,o.lx,o.ly)}function xm(t,e,r,n,a){r||(r=e).attr("pointer-events","all");var o=function(t){return-1==+t.attr(lm.menuIndexAttrName)}(r)&&"buttons"!==a.type?[]:a.buttons,s="dropdown"===a.type?lm.dropdownButtonClassName:lm.buttonClassName,l=r.selectAll("g."+s).data(o),u=l.enter().append("g").classed(s,!0),c=l.exit();"dropdown"===a.type?(u.attr("opacity","0").transition().attr("opacity","1"),c.transition().attr("opacity","0").remove()):c.remove();var h=0,f=0,p=a._dims,d=-1!==["up","down"].indexOf(a.direction);"dropdown"===a.type&&(d?f=p.headerHeight+lm.gapButtonHeader:h=p.headerWidth+lm.gapButtonHeader),"dropdown"===a.type&&"up"===a.direction&&(f=-lm.gapButtonHeader+lm.gapButton-p.openHeight),"dropdown"===a.type&&"left"===a.direction&&(h=-lm.gapButtonHeader+lm.gapButton-p.openWidth);var g={x:p.lx+h+a.pad.l,y:p.ly+f+a.pad.t,yPad:lm.gapButton,xPad:lm.gapButton,index:0},v={l:g.x+a.borderwidth,t:g.y+a.borderwidth};l.each(function(o,s){var u=i.select(this);u.call(bm,a,o,t).call(Sm,a,g),u.on("click",function(){i.event.defaultPrevented||(mm(t,a,0,e,r,n,s),o.execute&&Sn.executeAPICommand(t,o.method,o.args),t.emit("plotly_buttonclicked",{menu:a,button:o,active:a.active}))}),u.on("mouseover",function(){u.call(Mm)}),u.on("mouseout",function(){u.call(Am,a),l.call(km,a)})}),l.call(km,a),d?(v.w=Math.max(p.openWidth,p.headerWidth),v.h=g.y-v.t):(v.w=g.x-v.l,v.h=Math.max(p.openHeight,p.headerHeight)),v.direction=a.direction,n&&(l.size()?function(t,e,r,n,i,a){var o,s,l,u=i.direction,c="up"===u||"down"===u,h=i._dims,f=i.active;if(c)for(s=0,l=0;l0?[0]:[]);if(n.enter().append("g").classed(lm.containerClassName,!0).style("cursor","pointer"),n.exit().remove(),n.exit().size()&&function(t){for(var e=t._fullLayout._pushmargin||{},r=Object.keys(e),n=0;nk.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r0&&oe.log("Clearing previous rejected promises from queue."),t._promises=[]},Im.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(Sn.subplotsRegistry.cartesian||{}).attrRegex,i=(Sn.subplotsRegistry.gl3d||{}).attrRegex,a=Object.keys(t);for(e=0;e3?(x.x=1.02,x.xanchor="left"):x.x<-2&&(x.x=-.02,x.xanchor="right"),x.y>3?(x.y=1.02,x.yanchor="bottom"):x.y<-2&&(x.y=-.02,x.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),Fe.clean(t),t},Im.cleanData=function(t,e){for(var r=[],n=t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid}),i=0;i0)return t.substr(0,e)}Im.hasParent=function(t,e){for(var r=qm(e);r;){if(r in t)return!0;r=qm(r)}return!1};var Hm=["x","y","z"];Im.clearAxisTypes=function(t,e,r){for(var n=0;n1&&M.warn("Full array edits are incompatible with other edits",i);var h=r[""][""];if(Xm(h))e.set(null);else{if(!Array.isArray(h))return M.warn("Unrecognized full array edit value",i,h),!0;e.set(h)}return!l&&(a(u,c),o(t),!0)}var f,p,d,g,v,m,y,x=Object.keys(r).map(Number).sort(Wm),b=e.get(),_=b||[],w=Z(c,i).get(),k=[],A=-1,T=_.length;for(f=0;f_.length-(y?0:1))M.warn("index out of range",i,d);else if(void 0!==m)v.length>1&&M.warn("Insertion & removal are incompatible with edits to the same index.",i,d),Xm(m)?k.push(d):y?("add"===m&&(m={}),_.splice(d,0,m),w&&w.splice(d,0,{})):M.warn("Unrecognized full object edit value",i,d,m),-1===A&&(A=d);else for(p=0;p=0;f--)_.splice(k[f],1),w&&w.splice(k[f],1);if(_.length?b||e.set(_):e.set(null),l)return!1;if(a(u,c),s!==S){var C;if(-1===A)C=x;else{for(T=Math.max(_.length,T),C=[],f=0;f=A);f++)C.push(d);for(f=A;f1?(m=["toggleHover"],y=["resetViews"]):s?(v=["zoomInGeo","zoomOutGeo"],m=["hoverClosestGeo"],y=["resetGeo"]):o?(m=["hoverClosest3d"],y=["resetCameraDefault3d","resetCameraLastSave3d"]):h?(m=["toggleHover"],y=["resetViewMapbox"]):m=u?["hoverClosestGl2d"]:l?["hoverClosestPie"]:["toggleHover"],a&&(m=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]),!a&&!u||p||(v=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==y[0]&&(y=["resetScale2d"])),o?x=["zoom3d","pan3d","orbitRotation","tableRotation"]:(a||u)&&!p||c?x=["zoom2d","pan2d"]:h||s?x=["pan2d"]:f&&(x=["zoom2d"]),function(t){for(var e=!1,r=0;rfy*p)||m)for(r=0;rS&&LA&&(A=L);s/=(A-M)/(2*T),M=i.l2r(M),A=i.l2r(A),i.range=i._input.range=_=t[1]||i[1]<=t[0])&&a[0]e[0])return!0}return!1}(n,i,p)){var o=a.node(),s=e.bg=oe.ensureSingle(a,"rect","bg");o.insertBefore(s.node(),o.childNodes[0])}else a.select("rect.bg").remove(),f.push(t),p.push([n,i])});var d=r._bgLayer.selectAll(".bg").data(f);return d.enter().append("rect").classed("bg",!0),d.exit().remove(),d.each(function(t){r._plots[t].bg=i.select(this)}),h.each(function(t){var n=r._plots[t],i=n.xaxis,u=n.yaxis;n.bg&&s&&n.bg.call(Lr.setRect,i._offset-a,u._offset-a,i._length+2*a,u._length+2*a).call(Fe.fill,r.plot_bgcolor).style("stroke-width",0);var c,h,f=n.clipId="clip"+r._uid+t+"plot",p=oe.ensureSingleById(r._clips,"clipPath",f,function(t){t.classed("plotclip",!0).append("rect")});for(n.clipRect=p.select("rect").attr({width:i._length,height:u._length}),Lr.setTranslate(n.plot,i._offset,u._offset),n._hasClipOnAxisFalse?(c=null,h=f):(c=f,h=null),Lr.setClipUrl(n.plot,c),e=0;e=0?u.angularAxis.domain:i.extent(x),M=Math.abs(x[1]-x[0]);_&&!b&&(M=0);var A=k.slice();w&&b&&(A[1]+=M);var T=u.angularAxis.ticksCount||4;T>8&&(T=T/(T/8)+T%8),u.angularAxis.ticksStep&&(T=(A[1]-A[0])/T);var S=u.angularAxis.ticksStep||(A[1]-A[0])/(T*(u.minorTicks+1));y&&(S=Math.max(Math.round(S),1)),A[2]||(A[2]=S);var C=i.range.apply(this,A);if(C=C.map(function(t,e){return parseFloat(t.toPrecision(12))}),n=i.scale.linear().domain(A.slice(0,2)).range("clockwise"===u.direction?[0,360]:[360,0]),s.layout.angularAxis.domain=n.domain(),s.layout.angularAxis.endPadding=w?M:0,void 0===(t=i.select(this).select("svg.chart-root"))||t.empty()){var E=(new DOMParser).parseFromString("' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '","application/xml"),L=this.appendChild(this.ownerDocument.importNode(E.documentElement,!0));t=i.select(L)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var P,z=t.select(".chart-group"),D={fill:"none",stroke:u.tickColor},I={"font-size":u.font.size,"font-family":u.font.family,fill:u.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+u.font.outlineColor}).join(",")};if(u.showLegend){P=t.select(".legend-group").attr({transform:"translate("+[g,u.margin.top]+")"}).style({display:"block"});var O=c.map(function(t,e){var r=Ay.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend=void 0===t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});Ay.Legend().config({data:c.map(function(t,e){return t.name||"Element"+e}),legendConfig:ky({},Ay.Legend.defaultConfig().legendConfig,{container:P,elements:O,reverseOrder:u.legend.reverseOrder})})();var R=P.node().getBBox();g=Math.min(u.width-R.width-u.margin.left-u.margin.right,u.height-u.margin.top-u.margin.bottom)/2,g=Math.max(10,g),m=[u.margin.left+g,u.margin.top+g],r.range([0,g]),s.layout.radialAxis.domain=r.domain(),P.attr("transform","translate("+[m[0]+g,m[1]-g]+")")}else P=t.select(".legend-group").style({display:"none"});t.attr({width:u.width,height:u.height}).style({opacity:u.opacity}),z.attr("transform","translate("+m+")").style({cursor:"crosshair"});var B=[(u.width-(u.margin.left+u.margin.right+2*g+(R?R.width:0)))/2,(u.height-(u.margin.top+u.margin.bottom+2*g))/2];if(B[0]=Math.max(0,B[0]),B[1]=Math.max(0,B[1]),t.select(".outer-group").attr("transform","translate("+B+")"),u.title){var F=t.select("g.title-group text").style(I).text(u.title),N=F.node().getBBox();F.attr({x:m[0]-N.width/2,y:m[1]-g-20})}var j=t.select(".radial.axis-group");if(u.radialAxis.gridLinesVisible){var V=j.selectAll("circle.grid-circle").data(r.ticks(5));V.enter().append("circle").attr({class:"grid-circle"}).style(D),V.attr("r",r),V.exit().remove()}j.select("circle.outside-circle").attr({r:g}).style(D);var U=t.select("circle.background-circle").attr({r:g}).style({fill:u.backgroundColor,stroke:u.stroke});function q(t,e){return n(t)%360+u.orientation}if(u.radialAxis.visible){var H=i.svg.axis().scale(r).ticks(5).tickSize(5);j.call(H).attr({transform:"rotate("+u.radialAxis.orientation+")"}),j.selectAll(".domain").style(D),j.selectAll("g>text").text(function(t,e){return this.textContent+u.radialAxis.ticksSuffix}).style(I).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===u.radialAxis.tickOrientation?"rotate("+-u.radialAxis.orientation+") translate("+[0,I["font-size"]]+")":"translate("+[0,I["font-size"]]+")"}}),j.selectAll("g>line").style({stroke:"black"})}var G=t.select(".angular.axis-group").selectAll("g.angular-tick").data(C),W=G.enter().append("g").classed("angular-tick",!0);G.attr({transform:function(t,e){return"rotate("+q(t)+")"}}).style({display:u.angularAxis.visible?"block":"none"}),G.exit().remove(),W.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(u.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(u.minorTicks+1)==0)}).style(D),W.selectAll(".minor").style({stroke:u.minorTickColor}),G.select("line.grid-line").attr({x1:u.tickLength?g-u.tickLength:0,x2:g}).style({display:u.angularAxis.gridLinesVisible?"block":"none"}),W.append("text").classed("axis-text",!0).style(I);var Y=G.select("text.axis-text").attr({x:g+u.labelOffset,dy:My+"em",transform:function(t,e){var r=q(t),n=g+u.labelOffset,i=u.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:u.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(u.minorTicks+1)!=0?"":y?y[t]+u.angularAxis.ticksSuffix:t+u.angularAxis.ticksSuffix}).style(I);u.angularAxis.rewriteTicks&&Y.text(function(t,e){return e%(u.minorTicks+1)!=0?"":u.angularAxis.rewriteTicks(this.textContent,e)});var X=i.max(z.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));P.attr({transform:"translate("+[g+X,u.margin.top]+")"});var Z=t.select("g.geometry-group").selectAll("g").size()>0,J=t.select("g.geometry-group").selectAll("g.geometry").data(c);if(J.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),J.exit().remove(),c[0]||Z){var K=[];c.forEach(function(t,e){var i={};i.radialScale=r,i.angularScale=n,i.container=J.filter(function(t,r){return r==e}),i.geometry=t.geometry,i.orientation=u.orientation,i.direction=u.direction,i.index=e,K.push({data:t,geometryConfig:i})});var Q=[];i.nest().key(function(t,e){return void 0!==t.data.groupId||"unstacked"}).entries(K).forEach(function(t,e){"unstacked"===t.key?Q=Q.concat(t.values.map(function(t,e){return[t]})):Q.push(t.values)}),Q.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return ky(Ay[r].defaultConfig(),t)});Ay[r]().config(n)()})}var $,tt,et=t.select(".guides-group"),rt=t.select(".tooltips-group"),nt=Ay.tooltipPanel().config({container:rt,fontSize:8})(),it=Ay.tooltipPanel().config({container:rt,fontSize:8})(),at=Ay.tooltipPanel().config({container:rt,hasTick:!0})();if(!b){var ot=et.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});z.on("mousemove.angular-guide",function(t,e){var r=Ay.util.getMousePos(U).angle;ot.attr({x2:-g,transform:"rotate("+r+")"}).style({opacity:.5});var i=(r+180+360-u.orientation)%360;$=n.invert(i);var a=Ay.util.convertToCartesian(g+12,r+180);nt.text(Ay.util.round($)).move([a[0]+m[0],a[1]+m[1]])}).on("mouseout.angular-guide",function(t,e){et.select("line").style({opacity:0})})}var st=et.select("circle").style({stroke:"grey",fill:"none"});z.on("mousemove.radial-guide",function(t,e){var n=Ay.util.getMousePos(U).radius;st.attr({r:n}).style({opacity:.5}),tt=r.invert(Ay.util.getMousePos(U).radius);var i=Ay.util.convertToCartesian(n,u.radialAxis.orientation);it.text(Ay.util.round(tt)).move([i[0]+m[0],i[1]+m[1]])}).on("mouseout.radial-guide",function(t,e){st.style({opacity:0}),at.hide(),nt.hide(),it.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(e,r){var n=i.select(this),a=this.style.fill,o="black",s=this.style.opacity||1;if(n.attr({"data-opacity":s}),a&&"none"!==a){n.attr({"data-fill":a}),o=i.hsl(a).darker().toString(),n.style({fill:o,opacity:1});var l={t:Ay.util.round(e[0]),r:Ay.util.round(e[1])};b&&(l.t=y[e[0]]);var u="t: "+l.t+", r: "+l.r,c=this.getBoundingClientRect(),h=t.node().getBoundingClientRect(),f=[c.left+c.width/2-B[0]-h.left,c.top+c.height/2-B[1]-h.top];at.config({color:o}).text(u),at.move(f)}else a=this.style.stroke||"black",n.attr({"data-stroke":a}),o=i.hsl(a).darker().toString(),n.style({stroke:o,opacity:1})}).on("mousemove.tooltip",function(t,e){if(0!=i.event.which)return!1;i.select(this).attr("data-fill")&&at.show()}).on("mouseout.tooltip",function(t,e){at.hide();var r=i.select(this),n=r.attr("data-fill");n?r.style({fill:n,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(o),this},u.config=function(t){if(!arguments.length)return a;var e=Ay.util.cloneJson(t);return e.data.forEach(function(t,e){a.data[e]||(a.data[e]={}),ky(a.data[e],Ay.Axis.defaultConfig().data[0]),ky(a.data[e],t)}),ky(a.layout,Ay.Axis.defaultConfig().layout),ky(a.layout,e.layout),this},u.getLiveConfig=function(){return s},u.getinputConfig=function(){return o},u.radialScale=function(t){return r},u.angularScale=function(t){return n},u.svg=function(){return t},i.rebind(u,l,"on"),u},Ay.Axis.defaultConfig=function(t,e){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:i.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:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},Ay.util={},Ay.DATAEXTENT="dataExtent",Ay.AREA="AreaChart",Ay.LINE="LinePlot",Ay.DOT="DotPlot",Ay.BAR="BarChart",Ay.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},Ay.util._extend=function(t,e){for(var r in t)e[r]=t[r]},Ay.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},Ay.util.dataFromEquation2=function(t,e){var r=e||6;return i.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},Ay.util.dataFromEquation=function(t,e,r){var n=e||6,a=[],o=[];i.range(0,360+n,n).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},Ay.util.ensureArray=function(t,e){if(void 0===t)return null;var r=[].concat(t);return i.range(e).map(function(t,e){return r[e]||r[0]})},Ay.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=Ay.util.ensureArray(t[e],r)}),t},Ay.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},Ay.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},Ay.util.sumArrays=function(t,e){return i.zip(t,e).map(function(t,e){return i.sum(t)})},Ay.util.arrayLast=function(t){return t[t.length-1]},Ay.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},Ay.util.flattenArray=function(t){for(var e=[];!Ay.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},Ay.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},Ay.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},Ay.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},Ay.util.getMousePos=function(t){var e=i.mouse(t.node()),r=e[0],n=e[1],a={};return a.x=r,a.y=n,a.pos=e,a.angle=180*(Math.atan2(n,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+n*n),a},Ay.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;i0)){var l=i.select(this.parentNode).selectAll("path.line").data([0]);l.enter().insert("path"),l.attr({class:"line",d:c(s),transform:function(t,r){return"rotate("+(e.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return d.fill(r,n,a)},"fill-opacity":0,stroke:function(t,e){return d.stroke(r,n,a)},"stroke-width":function(t,e){return d["stroke-width"](r,n,a)},"stroke-dasharray":function(t,e){return d["stroke-dasharray"](r,n,a)},opacity:function(t,e){return d.opacity(r,n,a)},display:function(t,e){return d.display(r,n,a)}})}};var h=e.angularScale.range(),f=Math.abs(h[1]-h[0])/o[0].length*Math.PI/180,p=i.svg.arc().startAngle(function(t){return-f/2}).endAngle(function(t){return f/2}).innerRadius(function(t){return e.radialScale(l+(t[2]||0))}).outerRadius(function(t){return e.radialScale(l+(t[2]||0))+e.radialScale(t[1])});u.arc=function(t,r,n){i.select(this).attr({class:"mark arc",d:p,transform:function(t,r){return"rotate("+(e.orientation+s(t[0])+90)+")"}})};var d={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,n,i){return r[t[i].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return void 0===t[n].data.visible||t[n].data.visible?"block":"none"}},g=i.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var v=g.selectAll("path.mark").data(function(t,e){return t});v.enter().append("path").attr({class:"mark"}),v.style(d).each(u[e.geometryType]),v.exit().remove(),g.exit().remove()})}return n.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),ky(t[r],Ay.PolyChart.defaultConfig()),ky(t[r],e)}),this):t},n.getColorScale=function(){},i.rebind(n,e,"on"),n},Ay.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:i.scale.category20()}}},Ay.BarChart=function(){return Ay.PolyChart()},Ay.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},Ay.AreaChart=function(){return Ay.PolyChart()},Ay.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},Ay.DotPlot=function(){return Ay.PolyChart()},Ay.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},Ay.LinePlot=function(){return Ay.PolyChart()},Ay.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},Ay.Legend=function(){var t=Ay.Legend.defaultConfig(),e=i.dispatch("hover");function r(){var e=t.legendConfig,n=t.data.map(function(t,r){return[].concat(t).map(function(t,n){var i=ky({},e.elements[r]);return i.name=t,i.color=[].concat(e.elements[r].color)[n],i})}),a=i.merge(n);a=a.filter(function(t,r){return e.elements[r]&&(e.elements[r].visibleInLegend||void 0===e.elements[r].visibleInLegend)}),e.reverseOrder&&(a=a.reverse());var o=e.container;("string"==typeof o||o.nodeName)&&(o=i.select(o));var s=a.map(function(t,e){return t.color}),l=e.fontSize,u=null==e.isContinuous?"number"==typeof a[0]:e.isContinuous,c=u?e.height:l*a.length,h=o.classed("legend-group",!0).selectAll("svg").data([0]),f=h.enter().append("svg").attr({width:300,height:c+l,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});f.append("g").classed("legend-axis",!0),f.append("g").classed("legend-marks",!0);var p=i.range(a.length),d=i.scale[u?"linear":"ordinal"]().domain(p).range(s),g=i.scale[u?"linear":"ordinal"]().domain(p)[u?"range":"rangePoints"]([0,c]);if(u){var v=h.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),h.append("rect").classed("legend-mark",!0).attr({height:e.height,width:e.colorBandWidth,fill:"url(#grad1)"})}else{var m=h.select(".legend-marks").selectAll("path.legend-mark").data(a);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[l/2,g(e)+l/2]+")"},d:function(t,e){var r,n,a,o=t.symbol;return a=3*(n=l),"line"===(r=o)?"M"+[[-n/2,-n/12],[n/2,-n/12],[n/2,n/12],[-n/2,n/12]]+"Z":-1!=i.svg.symbolTypes.indexOf(r)?i.svg.symbol().type(r).size(a)():i.svg.symbol().type("square").size(a)()},fill:function(t,e){return d(e)}}),m.exit().remove()}var y=i.svg.axis().scale(g).orient("right"),x=h.select("g.legend-axis").attr({transform:"translate("+[u?e.colorBandWidth:l,l/2]+")"}).call(y);return x.selectAll(".domain").style({fill:"none",stroke:"none"}),x.selectAll("line").style({fill:"none",stroke:u?e.textColor:"none"}),x.selectAll("text").style({fill:e.textColor,"font-size":e.fontSize}).text(function(t,e){return a[e].name}),r}return r.config=function(e){return arguments.length?(ky(t,e),this):t},i.rebind(r,e,"on"),r},Ay.Legend.defaultConfig=function(t,e){return{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:!1}}},Ay.tooltipPanel=function(){var t,e,r,n={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},a="tooltip-"+Ay.tooltipPanel.uid++,o=10,s=function(){var i=(t=n.container.selectAll("g."+a).data([0])).enter().append("g").classed(a,!0).style({"pointer-events":"none",display:"none"});return r=i.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=i.append("text").attr({dx:n.padding+o,dy:.3*+n.fontSize}),s};return s.text=function(a){var l=i.hsl(n.color).l,u=l>=.5?"#aaa":"white",c=l>=.5?"black":"white",h=a||"";e.style({fill:c,"font-size":n.fontSize+"px"}).text(h);var f=n.padding,p=e.node().getBBox(),d={fill:n.color,stroke:u,"stroke-width":"2px"},g=p.width+2*f+o,v=p.height+2*f;return r.attr({d:"M"+[[o,-v/2],[o,-v/4],[n.hasTick?0:o,0],[o,v/4],[o,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(d),t.attr({transform:"translate("+[o,-v/2+2*f]+")"}),t.style({display:"block"}),s},s.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),s},s.hide=function(){if(t)return t.style({display:"none"}),s},s.show=function(){if(t)return t.style({display:"block"}),s},s.config=function(t){return ky(n,t),s},s},Ay.tooltipPanel.uid=1,Ay.adapter={},Ay.adapter.plotly=function(){var t={convert:function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=ky({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,r){Ay.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var n=Ay.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var i=n.indexOf(t.geometry);-1!=i&&(r.data[e].groupId=i)})}if(t.layout){var a=ky({},t.layout);if([[a,["plot_bgcolor"],["backgroundColor"]],[a,["showlegend"],["showLegend"]],[a,["radialaxis"],["radialAxis"]],[a,["angularaxis"],["angularAxis"]],[a.angularaxis,["showline"],["gridLinesVisible"]],[a.angularaxis,["showticklabels"],["labelsVisible"]],[a.angularaxis,["nticks"],["ticksCount"]],[a.angularaxis,["tickorientation"],["tickOrientation"]],[a.angularaxis,["ticksuffix"],["ticksSuffix"]],[a.angularaxis,["range"],["domain"]],[a.angularaxis,["endpadding"],["endPadding"]],[a.radialaxis,["showline"],["gridLinesVisible"]],[a.radialaxis,["tickorientation"],["tickOrientation"]],[a.radialaxis,["ticksuffix"],["ticksSuffix"]],[a.radialaxis,["range"],["domain"]],[a.angularAxis,["showline"],["gridLinesVisible"]],[a.angularAxis,["showticklabels"],["labelsVisible"]],[a.angularAxis,["nticks"],["ticksCount"]],[a.angularAxis,["tickorientation"],["tickOrientation"]],[a.angularAxis,["ticksuffix"],["ticksSuffix"]],[a.angularAxis,["range"],["domain"]],[a.angularAxis,["endpadding"],["endPadding"]],[a.radialAxis,["showline"],["gridLinesVisible"]],[a.radialAxis,["tickorientation"],["tickOrientation"]],[a.radialAxis,["ticksuffix"],["ticksSuffix"]],[a.radialAxis,["range"],["domain"]],[a.font,["outlinecolor"],["outlineColor"]],[a.legend,["traceorder"],["reverseOrder"]],[a,["labeloffset"],["labelOffset"]],[a,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,r){Ay.util.translator.apply(null,t.concat(e))}),e?(void 0!==a.tickLength&&(a.angularaxis.ticklen=a.tickLength,delete a.tickLength),a.tickColor&&(a.angularaxis.tickcolor=a.tickColor,delete a.tickColor)):(a.angularAxis&&void 0!==a.angularAxis.ticklen&&(a.tickLength=a.angularAxis.ticklen),a.angularAxis&&void 0!==a.angularAxis.tickcolor&&(a.tickColor=a.angularAxis.tickcolor)),a.legend&&"boolean"!=typeof a.legend.reverseOrder&&(a.legend.reverseOrder="normal"!=a.legend.reverseOrder),a.legend&&"boolean"==typeof a.legend.traceorder&&(a.legend.traceorder=a.legend.traceorder?"reversed":"normal",delete a.legend.reverseOrder),a.margin&&void 0!==a.margin.t){var o=["t","r","b","l","pad"],s=["top","right","bottom","left","pad"],l={};i.entries(a.margin).forEach(function(t,e){l[s[o.indexOf(t.key)]]=t.value}),a.margin=l}e&&(delete a.needsEndSpacing,delete a.minorTickColor,delete a.minorTicks,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksCount,delete a.angularaxis.ticksStep,delete a.angularaxis.rewriteTicks,delete a.angularaxis.nticks,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksCount,delete a.radialaxis.ticksStep,delete a.radialaxis.rewriteTicks,delete a.radialaxis.nticks),r.layout=a}return r}};return t};var Ty,Sy=oe.extendDeepAll,Cy=Ty={};Cy.framework=function(t){var e,r,n,a,o,s=new function(){var t,e=[],r=-1,n=!1;function i(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(i(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(i(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r*:not(.chart-root)").remove(),e=e?Sy(e,r):r,n||(n=wy.Axis()),a=wy.adapter.plotly().convert(e),n.config(a).render(o),t.data=e.data,t.layout=e.layout,Cy.fillLayout(t),e}return l.isPolar=!0,l.svg=function(){return n.svg()},l.getConfig=function(){return e},l.getLiveConfig=function(){return wy.adapter.plotly().convert(n.getLiveConfig(),!0)},l.getLiveScales=function(){return{t:n.angularScale(),r:n.radialScale()}},l.setUndoPoint=function(){var t,n,i=this,a=wy.util.cloneJson(e);t=a,n=r,s.add({undo:function(){n&&i(n)},redo:function(){i(t)}}),r=wy.util.cloneJson(a)},l.undo=function(){s.undo()},l.redo=function(){s.redo()},l},Cy.fillLayout=function(t){var e=i.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),n=t.framework&&t.framework.svg&&t.framework.svg(),a={width:800,height:600,paper_bgcolor:Fe.background,_container:e,_paperdiv:r,_paper:n};t._fullLayout=Sy(a,t.layout)};var Ey={};(Ey=wy).manager=Ty;var Ly={},Py=Zo.initInteractions,zy=Ee.AX_NAME_PATTERN,Dy=0;function Iy(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){oe.error(t)}}function Oy(t,e){Iy(t,Fe.combine(e,"white"))}function Ry(t,e){t._context||(t._context=oe.extendDeep({},k));var r,n,i,a=t._context;if(e){for(n=Object.keys(e),r=0;r=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||i<0&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function Ny(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if(void 0===e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),Fy(t,e,"currentIndices"),void 0===r||Array.isArray(r)||(r=[r]),void 0!==r&&Fy(t,r,"newIndices"),void 0!==r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function jy(t,e,r,n,i){!function(t,e,r,n){var i=oe.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!oe.isPlainObject(e))throw new Error("update must be a key:value object");if(void 0===r)throw new Error("indices must be an integer or array of integers");for(var a in Fy(t,r,"indices"),e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,r,n);for(var o=function(t,e,r,n){var i,o,s,l,u,c=oe.isPlainObject(n),h=[];for(var f in Array.isArray(r)||(r=[r]),r=By(r,t.data.length-1),e)for(var p=0;p0&&"string"!=typeof _.parts[k-1];)M--;var A=_.parts[M],T=_.parts[M-1]+"."+A,S=_.parts.slice(0,M).join("."),C=oe.nestedProperty(t.layout,S).get(),E=oe.nestedProperty(o,S).get(),L=_.get();if(void 0!==w){d[b]=w,g[b]="reverse"===A?w:Uy(L);var P=sn.getLayoutValObject(o,_.parts);if(P&&P.impliedEdits&&null!==w)for(var z in P.impliedEdits)v(oe.relativeAttr(b,z),P.impliedEdits[z]);if(-1!==["width","height"].indexOf(b)&&null===w)o[b]=t._initialAutoSize[b];else if(T.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/))x(T),oe.nestedProperty(o,S+"._inputRange").set(null);else if(T.match(/^[xyz]axis[0-9]*\.autorange$/)){x(T),oe.nestedProperty(o,S+"._inputRange").set(null);var D=oe.nestedProperty(o,S).get();D._inputDomain&&(D._input.domain=D._inputDomain.slice())}else T.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)&&oe.nestedProperty(o,S+"._inputDomain").set(null);if("type"===A){var I=C,R="linear"===E.type&&"log"===w,B="log"===E.type&&"linear"===w;if(R||B){if(I&&I.range)if(E.autorange)R&&(I.range=I.range[1]>I.range[0]?[1,2]:[2,1]);else{var F=I.range[0],N=I.range[1];R?(F<=0&&N<=0&&v(S+".autorange",!0),F<=0?F=N/1e6:N<=0&&(N=F/1e6),v(S+".range[0]",Math.log(F)/Math.LN10),v(S+".range[1]",Math.log(N)/Math.LN10)):(v(S+".range[0]",Math.pow(10,F)),v(S+".range[1]",Math.pow(10,N)))}else v(S+".autorange",!0);Array.isArray(o._subplots.polar)&&o._subplots.polar.length&&o[_.parts[0]]&&"radialaxis"===_.parts[1]&&delete o[_.parts[0]]._subplot.viewInitial["radialaxis.range"],O.getComponentMethod("annotations","convertCoords")(t,E,w,v),O.getComponentMethod("images","convertCoords")(t,E,w,v)}else v(S+".autorange",!0),v(S+".range",null);oe.nestedProperty(o,S+"._inputRange").set(null)}else if(A.match(zy)){var j=oe.nestedProperty(o,b).get(),V=(w||{}).type;V&&"-"!==V||(V="linear"),O.getComponentMethod("annotations","convertCoords")(t,j,V,v),O.getComponentMethod("images","convertCoords")(t,j,V,v)}var U=Gm.containerArrayMatch(b);if(U){r=U.array,n=U.index;var q=U.property,H=(oe.nestedProperty(a,r)||[])[n]||{},G=H,W=P||{editType:"calc"},Y=-1!==W.editType.indexOf("calcIfAutorange");""===n?(Y?p.calc=!0:_e.update(p,W),Y=!1):""===q&&(G=w,Gm.isAddVal(w)?g[b]=null:Gm.isRemoveVal(w)?(g[b]=H,G=H):oe.warn("unrecognized full object value",e)),Y&&(Wy(t,G,"x")||Wy(t,G,"y"))?p.calc=!0:_e.update(p,W),u[r]||(u[r]={});var X=u[r][n];X||(X=u[r][n]={}),X[q]=w,delete e[b]}else"reverse"===A?(C.range?C.range.reverse():(v(S+".autorange",!0),C.range=[1,0]),E.autorange?p.calc=!0:p.plot=!0):(o._has("scatter-like")&&o._has("regl")&&"dragmode"===b&&("lasso"===w||"select"===w)&&"lasso"!==L&&"select"!==L?p.plot=!0:P?_e.update(p,P):p.calc=!0,_.set(w))}}for(r in u){Gm.applyContainerArrayChanges(t,oe.nestedProperty(a,r),u[r],p)||(p.plot=!0)}var Z=o._axisConstraintGroups||[];for(m in y)for(n=0;n=0&&r=0&&r=i.length?i[0]:i[t]:i}function s(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function l(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(a,u){function c(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,Sn.transition(t,e.frame.data,e.frame.layout,Im.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function h(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&c()};e()}var f,p,d=0;function g(t){return Array.isArray(i)?d>=i.length?t.transitionOpts=i[d]:t.transitionOpts=i[0]:t.transitionOpts=i,d++,t}var v=[],m=void 0===e||null===e,y=Array.isArray(e);if(!m&&!y&&oe.isPlainObject(e))v.push({type:"object",data:g(oe.extendFlat({},e))});else if(m||-1!==["string","number"].indexOf(typeof e))for(f=0;f0&&__)&&w.push(p);v=w}}v.length>0?function(e){if(0!==e.length){for(var i=0;i=0;n--)if(oe.isPlainObject(e[n])){var f=e[n].name,p=(l[f]||h[f]||{}).name,d=e[n].name,g=l[p]||h[p];p&&d&&"number"==typeof d&&g&&Dy<5&&(Dy++,oe.warn('addFrames: overwriting frame "'+(l[p]||h[p]).name+'" with a frame whose name of type "number" also equates to "'+p+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===Dy&&oe.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),h[f]={name:f},c.push({frame:Sn.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:u+n})}c.sort(function(t,e){return t.index>e.index?-1:t.index=0;n--){if("number"==typeof(i=c[n].frame).name&&oe.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!i.name)for(;l[i.name="frame "+t._transitionData._counter++];);if(l[i.name]){for(a=0;a=0;r--)n=e[r],a.push({type:"delete",index:n}),o.unshift({type:"insert",index:n,value:i[n]});var s=Sn.modifyFrames,l=Sn.modifyFrames,u=[t,o],c=[t,a];return zm&&zm.add(t,s,u,l,c),Sn.modifyFrames(t,a)},Ly.purge=function(t){var e=(t=oe.getGraphDiv(t))._fullLayout||{},r=t._fullData||[],n=t.calcdata||[];return Sn.cleanPlot([],{},r,e,n),Sn.purge(t),fa.purge(t),e._container&&e._container.remove(),delete t._context,t};var Zy={getDelay:function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},getRedrawFunc:function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},Jy=oa.EventEmitter;var Ky=function(t){var e=t.emitter||new Jy,r=new Promise(function(n,i){var a=window.Image,o=t.svg,s=t.format||"png";if(oe.isIE()&&"svg"!==s){var l=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(l),t.promise?r:e.emit("error",l)}var u=t.canvas,c=t.scale||1,h=c*(t.width||300),f=c*(t.height||150),p=u.getContext("2d"),d=new a,g="data:image/svg+xml,"+encodeURIComponent(o);u.width=h,u.height=f,d.onload=function(){var r;switch("svg"!==s&&p.drawImage(d,0,0,h,f),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=g;break;default:var a="Image format is not jpeg, png, svg or webp.";if(i(new Error(a)),!t.promise)return e.emit("error",a)}n(r),t.promise||e.emit("success",r)},d.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},d.src=g});return t.promise?r:e},Qy=/"/g,$y=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");var tx=function(t,e,r){var n,a=t._fullLayout,o=a._paper,s=a._toppaper,l=a.width,u=a.height;o.insert("rect",":first-child").call(Lr.setRect,0,0,l,u).call(Fe.fill,a.paper_bgcolor);var c=a._basePlotModules||[];for(n=0;n")?"":e.html(t).text()});return e.remove(),r}(g),g=(g=g.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")).replace($y,"'"),oe.isIE()&&(g=(g=(g=g.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),g},ex={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},rx=/^data:image\/\w+;base64,/;var nx=function(t,e){var r,n,i;function a(t){return!(t in e)||oe.validate(e[t],ex[t])}if(e=e||{},oe.isPlainObject(t)?(r=t.data||[],n=t.layout||{},i=t.config||{}):(t=oe.getGraphDiv(t),r=oe.extendDeep([],t.data),n=oe.extendDeep({},t.layout),i=t._context),!a("width")||!a("height"))throw new Error("Height and width should be pixel values.");if(!a("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var o={};function s(t,r){return oe.coerce(e,o,ex,t,r)}var l=s("format"),u=s("width"),c=s("height"),h=s("scale"),f=s("setBackground"),p=s("imageDataOnly"),d=document.createElement("div");d.style.position="absolute",d.style.left="-5000px",document.body.appendChild(d);var g=oe.extendFlat({},n);u&&(g.width=u),c&&(g.height=c);var v=oe.extendFlat({},i,{staticPlot:!0,setBackground:f}),m=Zy.getRedrawFunc(d);function y(){return new Promise(function(t){setTimeout(t,Zy.getDelay(d._fullLayout))})}function x(){return new Promise(function(t,e){var r=tx(d,l,h),n=d._fullLayout.width,i=d._fullLayout.height;if(Ly.purge(d),document.body.removeChild(d),"svg"===l)return t(p?r:"data:image/svg+xml,"+encodeURIComponent(r));var a=document.createElement("canvas");a.id=oe.randstr(),Ky({format:l,width:n,height:i,scale:h,canvas:a,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){Ly.plot(d,r,g,v).then(m).then(y).then(x).then(function(e){t(function(t){return p?t.replace(rx,""):t}(e))}).catch(function(t){e(t)})})},ix=oe.isPlainObject,ax=Array.isArray,ox=oe.isArrayOrTypedArray;function sx(t,e,r,n,i,a){a=a||[];for(var o=Object.keys(t),s=0;sh.length&&n.push(cx("unused",i,u.concat(h.length)));var v,m,y,x,b,_=h.length,w=Array.isArray(g);if(w&&(_=Math.min(_,g.length)),2===f.dimensions)for(m=0;m<_;m++)if(ax(c[m])){c[m].length>h[m].length&&n.push(cx("unused",i,u.concat(m,h[m].length)));var k=h[m].length;for(v=0;v<(w?Math.min(k,g[m].length):k);v++)y=w?g[m][v]:g,x=c[m][v],b=h[m][v],oe.validate(x,y)?b!==x&&b!==+x&&n.push(cx("dynamic",i,u.concat(m,v),x,b)):n.push(cx("value",i,u.concat(m,v),x))}else n.push(cx("array",i,u.concat(m),c[m]));else for(m=0;m<_;m++)y=w?g[m]:g,x=c[m],b=h[m],oe.validate(x,y)?b!==x&&b!==+x&&n.push(cx("dynamic",i,u.concat(m),x,b)):n.push(cx("value",i,u.concat(m),x))}else if(f.items&&!p&&ax(c)){var M,A,T=g[Object.keys(g)[0]],S=[];for(M=0;M1&&a.push(cx("object","layout"))),Sn.supplyDefaults(o);for(var s=o._fullData,l=r.length,u=0;u-1&&(s[u[r]].title="");for(r=0;r=0;i--){var a=t[i];if("scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}}}},Ix=oe.isArrayOrTypedArray,Ox=function(t,e,r,n){var i=!1;if(e.marker){var a=e.marker.color,o=(e.marker.line||{}).color;a&&!Ix(a)?i=a:o&&!Ix(o)&&(i=o)}n("fillcolor",Fe.addOpacity((e.line||{}).color||i||r,.5))},Rx=oe.isArrayOrTypedArray,Bx=function(t,e,r,n,i,a){var o=(t.marker||{}).color;(i("line.color",r),Ke(t,"line"))?Je(t,e,n,i,{prefix:"line.",cLetter:"c"}):i("line.color",!Rx(o)&&o||r);i("line.width"),(a||{}).noDash||i("line.dash")},Fx=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")},Nx=function(t,e,r,n,i,a){var o=Er.isBubble(t),s=(t.line||{}).color;(a=a||{},s&&(r=s),i("marker.symbol"),i("marker.opacity",o?.7:1),i("marker.size"),i("marker.color",r),Ke(t,"marker")&&Je(t,e,n,i,{prefix:"marker.",cLetter:"c"}),a.noSelect||(i("selected.marker.color"),i("unselected.marker.color"),i("selected.marker.size"),i("unselected.marker.size")),a.noLine||(i("marker.line.color",s&&!Array.isArray(s)&&e.marker.color!==s?s:o?Fe.background:Fe.defaultLine),Ke(t,"marker.line")&&Je(t,e,n,i,{prefix:"marker.line.",cLetter:"c"}),i("marker.line.width",o?1:0)),o&&(i("marker.sizeref"),i("marker.sizemin"),i("marker.sizemode")),a.gradient)&&("none"!==i("marker.gradient.type")&&i("marker.gradient.color"))},jx=function(t,e,r,n,i){i=i||{},n("textposition"),oe.coerceFont(n,"textfont",r.font),i.noSelect||(n("selected.textfont.color"),n("unselected.textfont.color"))},Vx=function(t,e){var r,n;if("lines"===t.mode)return(r=t.line.color)&&Fe.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var i=e.mcc||(t.marker||{}).color,a=e.mlcc||((t.marker||{}).line||{}).color;return(n=i&&Fe.opacity(i)?i:a&&Fe.opacity(a)&&(e.mlw||((t.marker||{}).line||{}).width)?a:"")?Fe.opacity(n)<.3?Fe.addOpacity(n,.3):n:(r=(t.line||{}).color)&&Fe.opacity(r)&&Er.hasLines(t)&&t.line.width?r:t.fillcolor},Ux=function(t,e,r,n){var i=t.cd,a=i[0].trace,o=t.xa,s=t.ya,l=o.c2p(e),u=s.c2p(r),c=[l,u],h=a.hoveron||"",f=-1!==a.mode.indexOf("markers")?3:.5;if(-1!==h.indexOf("points")){var p=function(t){var e=Math.max(f,t.mrc||0),r=o.c2p(t.x)-l,n=s.c2p(t.y)-u;return Math.max(Math.sqrt(r*r+n*n)-e,1-f/e)},d=qa.getDistanceFunction(n,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(o.c2p(t.x)-l);return nR!=(S=w[b][1])>=R&&(M=w[b-1][0],A=w[b][0],S-T&&(k=M+(A-M)*(R-T)/(S-T),P=Math.min(P,k),z=Math.max(z,k)));P=Math.max(P,0),z=Math.min(z,o._length);var B=Fe.defaultLine;return Fe.opacity(a.fillcolor)?B=a.fillcolor:Fe.opacity((a.line||{}).color)&&(B=a.line.color),oe.extendFlat(t,{distance:t.maxHoverDistance,x0:P,x1:z,y0:R,y1:R,color:B}),delete t.index,a.text&&!Array.isArray(a.text)?t.text=String(a.text):t.text=a.name,[t]}}},qx=n.BADNUM,Hx=oe.segmentsIntersect,Gx=oe.constrain,Wx=function(t,e){var r,n,i,a,o,s,l,u,c,h,f,p,d,g,v,m,y=e.xaxis,x=e.yaxis,b=e.simplify,_=e.connectGaps,w=e.baseTolerance,k=e.shape,M="linear"===k,A=[],T=Zr.minTolerance,S=new Array(t.length),C=0;function E(e){var r=t[e],n=y.c2p(r.x),i=x.c2p(r.y);return n===qx||i===qx?r.intoCenter||!1:[n,i]}function L(t){var e=t[0]/y._length,r=t[1]/x._length;return(1+Zr.toleranceGrowth*Math.max(0,-e,e-1,-r,r-1))*w}function P(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}b||(w=T=-1);var z,D,I,O,R,B,F,N=Zr.maxScreensAway,j=-y._length*N,V=y._length*(1+N),U=-x._length*N,q=x._length*(1+N),H=[[j,U,V,U],[V,U,V,q],[V,q,j,q],[j,q,j,U]];function G(t){if(t[0]V||t[1]q)return[Gx(t[0],j,V),Gx(t[1],U,q)]}function W(t,e){return t[0]===e[0]&&(t[0]===j||t[0]===V)||(t[1]===e[1]&&(t[1]===U||t[1]===q)||void 0)}function Y(t,e,r){return function(n,i){var a=G(n),o=G(i),s=[];if(a&&o&&W(a,o))return s;a&&s.push(a),o&&s.push(o);var l=2*oe.constrain((n[t]+i[t])/2,e,r)-((a||n)[t]+(o||i)[t]);l&&((a&&o?l>0==a[t]>o[t]?a:o:a||o)[t]+=l);return s}}function X(t){var e=t[0],r=t[1],n=e===S[C-1][0],i=r===S[C-1][1];if(!n||!i)if(C>1){var a=e===S[C-2][0],o=r===S[C-2][1];n&&(e===j||e===V)&&a?o?C--:S[C-1]=t:i&&(r===U||r===q)&&o?a?C--:S[C-1]=t:S[C++]=t}else S[C++]=t}function Z(t){S[C-1][0]!==t[0]&&S[C-1][1]!==t[1]&&X([I,O]),X(t),R=null,I=O=0}function J(t){if(z=t[0]V?V:0,D=t[1]q?q:0,z||D){if(C)if(R){var e=F(R,t);e.length>1&&(Z(e[0]),S[C++]=e[1])}else B=F(S[C-1],t)[0],S[C++]=B;else S[C++]=[z||t[0],D||t[1]];var r=S[C-1];z&&D&&(r[0]!==z||r[1]!==D)?(R&&(I!==z&&O!==D?X(I&&O?(n=R,a=(i=t)[0]-n[0],o=(i[1]-n[1])/a,(n[1]*i[0]-i[1]*n[0])/a>0?[o>0?j:V,q]:[o>0?V:j,U]):[I||z,O||D]):I&&O&&X([I,O])),X([z,D])):I-z&&O-D&&X([z||I,D||O]),R=t,I=z,O=D}else R&&Z(F(R,t)[0]),S[C++]=t;var n,i,a,o}for("linear"===k||"spline"===k?F=function(t,e){for(var r=[],n=0,i=0;i<4;i++){var a=H[i],o=Hx(t[0],t[1],e[0],e[1],a[0],a[1],a[2],a[3]);o&&(!n||Math.abs(o.x-r[0][0])>1||Math.abs(o.y-r[0][1])>1)&&(o=[o.x,o.y],n&&P(o,t)L(s))break;i=s,(d=c[0]*u[0]+c[1]*u[1])>f?(f=d,a=s,l=!1):d=t.length||!s)break;J(s),n=s}}else J(a)}R&&X([I||R[0],O||R[1]]),A.push(S.slice(0,C))}return A},Yx=function(t,e,r){var n,i,a=null;for(i=0;i0;for((l=c.selectAll("g.trace").data(r,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),Yx(t,e,r),function(t,e,r){var n;e.selectAll("g.trace").each(function(t){var e=i.select(this);if((n=t[0].trace)._nexttrace){if(n._nextFill=e.select(".js-fill.js-tonext"),!n._nextFill.size()){var a=":first-child";e.select(".js-fill.js-tozero").size()&&(a+=" + *"),n._nextFill=e.insert("path",a).attr("class","js-fill js-tonext")}}else e.selectAll(".js-fill.js-tonext").remove(),n._nextFill=null;n.fill&&("tozero"===n.fill.substr(0,6)||"toself"===n.fill||"to"===n.fill.substr(0,2)&&!n._prevtrace)?(n._ownFill=e.select(".js-fill.js-tozero"),n._ownFill.size()||(n._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),n._ownFill=null),e.selectAll(".js-fill").call(Lr.setClipUrl,r.layerClipId)})}(0,c,e),o=0,s={};os[e[0].trace.uid]?1:-1}),f)?(a&&(u=a()),i.transition().duration(n.duration).ease(n.easing).each("end",function(){u&&u()}).each("interrupt",function(){u&&u()}).each(function(){c.selectAll("g.trace").each(function(i,a){Jx(t,a,e,i,r,this,n)})})):c.selectAll("g.trace").each(function(i,a){Jx(t,a,e,i,r,this,n)});h&&l.exit().remove(),c.selectAll("path:not([d])").remove()};function Jx(t,e,r,n,a,o,s){var l,u;!function(t,e,r,n,a){var o=r.xaxis,s=r.yaxis,l=i.extent(oe.simpleMap(o.range,o.r2c)),u=i.extent(oe.simpleMap(s.range,s.r2c)),c=n[0].trace;if(!Er.hasMarkers(c))return;var h=c.marker.maxdisplayed;if(0===h)return;var f=n.filter(function(t){return t.x>=l[0]&&t.x<=l[1]&&t.y>=u[0]&&t.y<=u[1]}),p=Math.ceil(f.length/h),d=0;a.forEach(function(t,r){var n=t[0].trace;Er.hasMarkers(n)&&n.marker.maxdisplayed>0&&r0;function h(t){return c?t.transition():t}var f=r.xaxis,p=r.yaxis,d=n[0].trace,g=d.line,v=i.select(o);if(O.getComponentMethod("errorbars","plot")(v,r,s),!0===d.visible){var m,y;h(v).style("opacity",d.opacity);var x=d.fill.charAt(d.fill.length-1);"x"!==x&&"y"!==x&&(x=""),r.isRangePlot||(n[0].node3=v);var b="",_=[],w=d._prevtrace;w&&(b=w._prevRevpath||"",y=w._nextFill,_=w._polygons);var k,M,A,T,S,C,E,L,P,z="",D="",I=[],R=oe.noop;if(m=d._ownFill,Er.hasLines(d)||"none"!==d.fill){for(y&&y.datum(n),-1!==["hv","vh","hvh","vhv"].indexOf(g.shape)?(A=Lr.steps(g.shape),T=Lr.steps(g.shape.split("").reverse().join(""))):A=T="spline"===g.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?Lr.smoothclosed(t.slice(1),g.smoothing):Lr.smoothopen(t,g.smoothing)}:function(t){return"M"+t.join("L")},S=function(t){return T(t.reverse())},I=Wx(n,{xaxis:f,yaxis:p,connectGaps:d.connectgaps,baseTolerance:Math.max(g.width||1,3)/4,shape:g.shape,simplify:g.simplify}),P=d._polygons=new Array(I.length),u=0;u1){var r=i.select(this);if(r.datum(n),t)h(r.style("opacity",0).attr("d",k).call(Lr.lineGroupStyle)).style("opacity",1);else{var a=h(r);a.attr("d",k),Lr.singleLineStyle(n,a)}}}}}var B=v.selectAll(".js-line").data(I);h(B.exit()).style("opacity",0).remove(),B.each(R(!1)),B.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(Lr.lineGroupStyle).each(R(!0)),Lr.setClipUrl(B,r.layerClipId),I.length?(m?C&&L&&(x?("y"===x?C[1]=L[1]=p.c2p(0,!0):"x"===x&&(C[0]=L[0]=f.c2p(0,!0)),h(m).attr("d","M"+L+"L"+C+"L"+z.substr(1)).call(Lr.singleFillStyle)):h(m).attr("d",z+"Z").call(Lr.singleFillStyle)):y&&("tonext"===d.fill.substr(0,6)&&z&&b?("tonext"===d.fill?h(y).attr("d",z+"Z"+b+"Z").call(Lr.singleFillStyle):h(y).attr("d",z+"L"+b.substr(1)+"Z").call(Lr.singleFillStyle),d._polygons=d._polygons.concat(_)):(N(y),d._polygons=null)),d._prevRevpath=D,d._prevPolygons=P):(m?N(m):y&&N(y),d._polygons=d._prevRevpath=d._prevPolygons=null);var F=v.selectAll(".points");l=F.data([n]),F.each(H),l.enter().append("g").classed("points",!0).each(H),l.exit().remove(),l.each(function(t){var e=!1===t[0].trace.cliponaxis;Lr.setClipUrl(i.select(this),e?null:r.layerClipId)})}function N(t){h(t).attr("d","M0,0Z")}function j(t){return t.filter(function(t){return t.vis})}function V(t){return t.id}function U(t){if(t.ids)return V}function q(){return!1}function H(e){var n,a=e[0].trace,o=i.select(this),s=Er.hasMarkers(a),l=Er.hasText(a),u=U(a),d=q,g=q;s&&(d=a.marker.maxdisplayed||a._needsCull?j:oe.identity),l&&(g=a.marker.maxdisplayed||a._needsCull?j:oe.identity);var v=(n=o.selectAll("path.point").data(d,u)).enter().append("path").classed("point",!0);c&&v.call(Lr.pointStyle,a,t).call(Lr.translatePoints,f,p).style("opacity",0).transition().style("opacity",1);var m=s&&Lr.tryColorscale(a.marker,""),y=s&&Lr.tryColorscale(a.marker,"line");n.order(),n.each(function(e){var n=i.select(this),o=h(n);Lr.translatePoint(e,o,f,p)?(Lr.singlePointStyle(e,o,a,m,y,t),r.layerClipId&&Lr.hideOutsideRangePoint(e,o,f,p,a.xcalendar,a.ycalendar),a.customdata&&n.classed("plotly-customdata",null!==e.data&&void 0!==e.data)):o.remove()}),c?n.exit().transition().style("opacity",0).remove():n.exit().remove(),(n=o.selectAll("g").data(g,u)).enter().append("g").classed("textpoint",!0).append("text"),n.order(),n.each(function(t){var e=i.select(this),n=h(e.select("text"));Lr.translatePoint(t,n,f,p)?r.layerClipId&&Lr.hideOutsideRangePoint(t,e,f,p,a.xcalendar,a.ycalendar):e.remove()}),n.selectAll("text").call(Lr.textPointStyle,a,t).each(function(t){var e=f.c2p(t.x),r=p.c2p(t.y);i.select(this).selectAll("tspan.line").each(function(){h(i.select(this)).attr({x:e,y:r})})}),n.exit().remove()}}var Kx=function(t,e){var r,n,i,a,o=t.cd,s=t.xaxis,l=t.yaxis,u=[],c=o[0].trace;if(!Er.hasMarkers(c)&&!Er.hasText(c))return[];if(!1===e)for(r=0;r":return function(t){return u(t)>s};case">=":return function(t){return u(t)>=s};case"[]":return function(t){var e=u(t);return e>=s[0]&&e<=s[1]};case"()":return function(t){var e=u(t);return e>s[0]&&e=s[0]&&es[0]&&e<=s[1]};case"][":return function(t){var e=u(t);return e<=s[0]||e>=s[1]};case")(":return function(t){var e=u(t);return es[1]};case"](":return function(t){var e=u(t);return e<=s[0]||e>s[1]};case")[":return function(t){var e=u(t);return e=s[1]};case"{}":return function(t){return-1!==s.indexOf(u(t))};case"}{":return function(t){return-1===s.indexOf(u(t))}}}(r,ui.getDataToCoordFunc(t,e,i,n),o),f={},p={},d=0;r.preservegaps?(u=function(t){f[t.astr]=oe.extendDeep([],t.get()),t.set(new Array(a))},c=function(t,e){var r=f[t.astr][e];t.get()[e]=r}):(u=function(t){f[t.astr]=oe.extendDeep([],t.get()),t.set([])},c=function(t,e){var r=f[t.astr][e];t.get().push(r)}),m(u);for(var g=ub(e.transforms,r),v=0;v1?"%{group} (%{trace})":"%{group}");var o=t.styles,s=i.styles=[];if(o)for(n=0;n0,l=[],u=[],c=0,h=0;for(n=0;n0&&l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"0&&l.push(["index[",h,"]-=s",h].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function Mb(t,e,r){for(var n=t.body,i=[],a=[],o=0;o0&&g.push("shape=SS.slice(0)"),t.indexArgs.length>0){var v=new Array(r);for(a=0;a0&&d.push("var "+g.join(",")),a=0;a3&&d.push(Mb(t.pre,t,i));var b=Mb(t.body,t,i),_=function(t){for(var e=0,r=t[0].length;e0,l=[],u=0;u0;){"].join("")),l.push(["if(j",u,"<",o,"){"].join("")),l.push(["s",e[u],"=j",u].join("")),l.push(["j",u,"=0"].join("")),l.push(["}else{s",e[u],"=",o].join("")),l.push(["j",u,"-=",o,"}"].join("")),s&&l.push(["index[",e[u],"]=j",u].join(""));for(u=0;u3&&d.push(Mb(t.post,t,i)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+d.join("\n")+"\n----------");var w=[t.funcName||"unnamed","_cwise_loop_",n[0].join("s"),"m",_,function(t){for(var e=new Array(t.length),r=!0,n=0;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}(i)].join("");return new Function(["function ",w,"(",p.join(","),"){",d.join("\n"),"} return ",w].join(""))()};var Tb=function(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var i=[],a=[],o=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],s=[],l=[],u=0;u0&&(s.push("array"+t.arrayArgs[0]+".shape.length===array"+c+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),l.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+c+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}for(t.arrayArgs.length>1&&(e.push("if (!("+s.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex--\x3e0;) {"),e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}")),u=0;u0)throw new Error("cwise: pre() block may not reference array args");if(n0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===i)e.scalarArgs.push(n),e.shimArgs.push("scalar"+n);else if("index"===i){if(e.indexArgs.push(n),n0)throw new Error("cwise: pre() block may not reference array index");if(n0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===i){if(e.shapeArgs.push(n),nr.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,Tb(e)},Cb={},Eb={body:"",args:[],thisVars:[],localVars:[]};function Lb(t){if(!t)return Eb;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in zb){var e=zb[t];Cb[t]=Pb({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),Cb[t+"eq"]=Pb({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),Cb[t+"s"]=Pb({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),Cb[t+"seq"]=Pb({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var Db={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in Db){var e=Db[t];Cb[t]=Pb({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),Cb[t+"eq"]=Pb({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var Ib={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in Ib){var e=Ib[t];Cb[t]=Pb({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),Cb[t+"s"]=Pb({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),Cb[t+"eq"]=Pb({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),Cb[t+"seq"]=Pb({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var Ob=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_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"}),Cb.norm1=Sb({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,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"}),Cb.sup=Sb({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:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),Cb.inf=Sb({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:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),Cb.random=Pb({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),Cb.assign=Pb({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),Cb.assigns=Pb({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),Cb.equals=Sb({args:["array","array"],pre:Eb,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"});var Fb=function(t){for(var e=new Array(t),r=0;rMath.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&i.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):i.push("ORDER})")),i.push("proto.set=function "+r+"_set("+o.join(",")+",v){"),n?i.push("return this.data.set("+s+",v)}"):i.push("return this.data["+s+"]=v}"),i.push("proto.get=function "+r+"_get("+o.join(",")+"){"),n?i.push("return this.data.get("+s+")}"):i.push("return this.data["+s+"]}"),i.push("proto.index=function "+r+"_index(",o.join(),"){return "+s+"}"),i.push("proto.hi=function "+r+"_hi("+o.join(",")+"){return new "+r+"(this.data,"+a.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+a.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var c=a.map(function(t){return"a"+t+"=this.shape["+t+"]"}),h=a.map(function(t){return"c"+t+"=this.stride["+t+"]"});i.push("proto.lo=function "+r+"_lo("+o.join(",")+"){var b=this.offset,d=0,"+c.join(",")+","+h.join(","));for(var f=0;f=0){d=i"+f+"|0;b+=c"+f+"*d;a"+f+"-=d}");i.push("return new "+r+"(this.data,"+a.map(function(t){return"a"+t}).join(",")+","+a.map(function(t){return"c"+t}).join(",")+",b)}"),i.push("proto.step=function "+r+"_step("+o.join(",")+"){var "+a.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+a.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(f=0;f=0){c=(c+this.stride["+f+"]*i"+f+")|0}else{a.push(this.shape["+f+"]);b.push(this.stride["+f+"])}");return i.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),i.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+a.map(function(t){return"shape["+t+"]"}).join(",")+","+a.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}"),new Function("CTOR_LIST","ORDER",i.join("\n"))(Gb[t],qb)}var Gb={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};var Wb=function(t,e,r,n){if(void 0===t)return(0,Gb.array[0])([]);"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var i=e.length;if(void 0===r){r=new Array(i);for(var a=i-1,o=1;a>=0;--a)r[a]=o,o*=e[a]}if(void 0===n)for(n=0,a=0;a0)-(t<0)},Yb.abs=function(t){var e=t>>31;return(t^e)-e},Yb.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},Yb.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},Yb.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},Yb.countTrailingZeros=Xb,Yb.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},Yb.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},Yb.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var Zb=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|Zb[t>>>16&255]<<8|Zb[t>>>24&255]},Yb.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},Yb.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},Yb.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},Yb.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},Yb.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>Xb(t)+1};for(var Jb={byteLength:function(t){return 3*t.length/4-n_(t)},toByteArray:function(t){var e,r,n,i,a,o=t.length;i=n_(t),a=new $b(3*o/4-i),r=i>0?o-4:o;var s=0;for(e=0;e>16&255,a[s++]=n>>8&255,a[s++]=255&n;2===i?(n=Qb[t.charCodeAt(e)]<<2|Qb[t.charCodeAt(e+1)]>>4,a[s++]=255&n):1===i&&(n=Qb[t.charCodeAt(e)]<<10|Qb[t.charCodeAt(e+1)]<<4|Qb[t.charCodeAt(e+2)]>>2,a[s++]=n>>8&255,a[s++]=255&n);return a},fromByteArray:function(t){for(var e,r=t.length,n=r%3,i="",a=[],o=0,s=r-n;os?s:o+16383));1===n?(e=t[r-1],i+=Kb[e>>2],i+=Kb[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=Kb[e>>10],i+=Kb[e>>4&63],i+=Kb[e<<2&63],i+="=");return a.push(i),a.join("")}},Kb=[],Qb=[],$b="undefined"!=typeof Uint8Array?Uint8Array:Array,t_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e_=0,r_=t_.length;e_0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function i_(t,e,r){for(var n,i,a=[],o=e;o>18&63]+Kb[i>>12&63]+Kb[i>>6&63]+Kb[63&i]);return a.join("")}Qb["-".charCodeAt(0)]=62,Qb["_".charCodeAt(0)]=63;var a_={read:function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,f=r?-1:1,p=t[e+h];for(h+=f,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)},write:function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}},o_={};o_.Buffer=u_,o_.SlowBuffer=function(t){+t!=t&&(t=0);return u_.alloc(+t)},o_.INSPECT_MAX_BYTES=50;var s_=2147483647;function l_(t){if(t>s_)throw new RangeError("Invalid typed array length");var e=new Uint8Array(t);return e.__proto__=u_.prototype,e}function u_(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return f_(t)}return c_(t,e,r)}function c_(t,e,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return U_(t)||t&&U_(t.buffer)?function(t,e,r){if(e<0||t.byteLength=s_)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s_.toString(16)+" bytes");return 0|t}function g_(t,e){if(u_.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||U_(t))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return N_(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return j_(t).length;default:if(n)return N_(t).length;e=(""+e).toLowerCase(),n=!0}}function v_(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function m_(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),q_(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=u_.from(e,n)),u_.isBuffer(e))return 0===e.length?-1:y_(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):y_(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function y_(t,e,r,n,i){var a,o=1,s=t.length,l=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;o=2,s/=2,l/=2,r/=2}function u(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(i){var c=-1;for(a=r;as&&(r=s-l),a=r;a>=0;a--){for(var h=!0,f=0;fi&&(n=i):n=i;var a=e.length;n>a/2&&(n=a/2);for(var o=0;o>8,i=r%256,a.push(i),a.push(n);return a}(e,t.length-r),t,r,n)}function A_(t,e,r){return 0===e&&r===t.length?Jb.fromByteArray(t):Jb.fromByteArray(t.slice(e,r))}function T_(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(c=u);break;case 2:128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)>127&&(c=l);break;case 3:a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&(l=(15&u)<<12|(63&a)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&(l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)>65535&&l<1114112&&(c=l)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=h}return function(t){var e=t.length;if(e<=S_)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return L_(this,e,r);case"utf8":case"utf-8":return T_(this,e,r);case"ascii":return C_(this,e,r);case"latin1":case"binary":return E_(this,e,r);case"base64":return A_(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P_(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},u_.prototype.toLocaleString=u_.prototype.toString,u_.prototype.equals=function(t){if(!u_.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===u_.compare(this,t)},u_.prototype.inspect=function(){var t="",e=o_.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},u_.prototype.compare=function(t,e,r,n,i){if(!u_.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,o=r-e,s=Math.min(a,o),l=this.slice(n,i),u=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return x_(this,t,e,r);case"utf8":case"utf-8":return b_(this,t,e,r);case"ascii":return __(this,t,e,r);case"latin1":case"binary":return w_(this,t,e,r);case"base64":return k_(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M_(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},u_.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var S_=4096;function C_(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",a=e;ar)throw new RangeError("Trying to access beyond buffer length")}function D_(t,e,r,n,i,a){if(!u_.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function I_(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function O_(t,e,r,n,i){return e=+e,r>>>=0,i||I_(t,0,r,4),a_.write(t,e,r,n,23,4),r+4}function R_(t,e,r,n,i){return e=+e,r>>>=0,i||I_(t,0,r,8),a_.write(t,e,r,n,52,8),r+8}u_.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||z_(t,e,this.length);for(var n=this[t],i=1,a=0;++a>>=0,e>>>=0,r||z_(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},u_.prototype.readUInt8=function(t,e){return t>>>=0,e||z_(t,1,this.length),this[t]},u_.prototype.readUInt16LE=function(t,e){return t>>>=0,e||z_(t,2,this.length),this[t]|this[t+1]<<8},u_.prototype.readUInt16BE=function(t,e){return t>>>=0,e||z_(t,2,this.length),this[t]<<8|this[t+1]},u_.prototype.readUInt32LE=function(t,e){return t>>>=0,e||z_(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u_.prototype.readUInt32BE=function(t,e){return t>>>=0,e||z_(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u_.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||z_(t,e,this.length);for(var n=this[t],i=1,a=0;++a=(i*=128)&&(n-=Math.pow(2,8*e)),n},u_.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||z_(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return a>=(i*=128)&&(a-=Math.pow(2,8*e)),a},u_.prototype.readInt8=function(t,e){return t>>>=0,e||z_(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u_.prototype.readInt16LE=function(t,e){t>>>=0,e||z_(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u_.prototype.readInt16BE=function(t,e){t>>>=0,e||z_(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u_.prototype.readInt32LE=function(t,e){return t>>>=0,e||z_(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u_.prototype.readInt32BE=function(t,e){return t>>>=0,e||z_(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u_.prototype.readFloatLE=function(t,e){return t>>>=0,e||z_(t,4,this.length),a_.read(this,t,!0,23,4)},u_.prototype.readFloatBE=function(t,e){return t>>>=0,e||z_(t,4,this.length),a_.read(this,t,!1,23,4)},u_.prototype.readDoubleLE=function(t,e){return t>>>=0,e||z_(t,8,this.length),a_.read(this,t,!0,52,8)},u_.prototype.readDoubleBE=function(t,e){return t>>>=0,e||z_(t,8,this.length),a_.read(this,t,!1,52,8)},u_.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||D_(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,a=0;for(this[e]=255&t;++a>>=0,r>>>=0,n)||D_(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},u_.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,1,255,0),this[e]=255&t,e+1},u_.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},u_.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},u_.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},u_.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u_.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);D_(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++a>0)-s&255;return e+r},u_.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);D_(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)t<0&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},u_.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},u_.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},u_.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},u_.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},u_.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||D_(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},u_.prototype.writeFloatLE=function(t,e,r){return O_(this,t,e,!0,r)},u_.prototype.writeFloatBE=function(t,e,r){return O_(this,t,e,!1,r)},u_.prototype.writeDoubleLE=function(t,e,r){return R_(this,t,e,!0,r)},u_.prototype.writeDoubleBE=function(t,e,r){return R_(this,t,e,!1,r)},u_.prototype.copy=function(t,e,r,n){if(!u_.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--a)t[a+e]=this[a+r];else Uint8Array.prototype.set.call(t,this.subarray(r,n),e);return i},u_.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u_.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t&&(t&=255);if(e<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(a=e;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;a.push(r)}else if(r<2048){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function j_(t){return Jb.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(B_,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function V_(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function U_(t){return t instanceof ArrayBuffer||null!=t&&null!=t.constructor&&"ArrayBuffer"===t.constructor.name&&"number"==typeof t.byteLength}function q_(t){return t!=t}var H_=function(t,e){switch(void 0===e&&(e=0),typeof t){case"number":if(t>0)return function(t,e){var r,n;for(r=new Array(t),n=0;n0?r.pop():new ArrayBuffer(t)}function l(t){return new Uint8Array(s(t),0,t)}function u(t){return new Uint16Array(s(2*t),0,t)}function c(t){return new Uint32Array(s(4*t),0,t)}function h(t){return new Int8Array(s(t),0,t)}function f(t){return new Int16Array(s(2*t),0,t)}function p(t){return new Int32Array(s(4*t),0,t)}function d(t){return new Float32Array(s(4*t),0,t)}function g(t){return new Float64Array(s(8*t),0,t)}function v(t){return r?new Uint8ClampedArray(s(t),0,t):l(t)}function m(t){return new DataView(s(t),0,t)}function y(t){t=Yb.nextPow2(t);var r=Yb.log2(t),n=a[r];return n.length>0?n.pop():new e(t)}G_.free=function(t){if(e.isBuffer(t))a[Yb.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var r=t.length||t.byteLength,n=0|Yb.log2(r);i[n].push(t)}},G_.freeUint8=G_.freeUint16=G_.freeUint32=G_.freeInt8=G_.freeInt16=G_.freeInt32=G_.freeFloat32=G_.freeFloat=G_.freeFloat64=G_.freeDouble=G_.freeUint8Clamped=G_.freeDataView=function(t){o(t.buffer)},G_.freeArrayBuffer=o,G_.freeBuffer=function(t){a[Yb.log2(t.length)].push(t)},G_.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return s(t);switch(e){case"uint8":return l(t);case"uint16":return u(t);case"uint32":return c(t);case"int8":return h(t);case"int16":return f(t);case"int32":return p(t);case"float":case"float32":return d(t);case"double":case"float64":return g(t);case"uint8_clamped":return v(t);case"buffer":return y(t);case"data":case"dataview":return m(t);default:return null}return null},G_.mallocArrayBuffer=s,G_.mallocUint8=l,G_.mallocUint16=u,G_.mallocUint32=c,G_.mallocInt8=h,G_.mallocInt16=f,G_.mallocInt32=p,G_.mallocFloat32=G_.mallocFloat=d,G_.mallocFloat64=G_.mallocDouble=g,G_.mallocUint8Clamped=v,G_.mallocDataView=m,G_.mallocBuffer=y,G_.clearCache=function(){for(var t=0;t<32;++t)n.UINT8[t].length=0,n.UINT16[t].length=0,n.UINT32[t].length=0,n.INT8[t].length=0,n.INT16[t].length=0,n.INT32[t].length=0,n.FLOAT[t].length=0,n.DOUBLE[t].length=0,n.UINT8C[t].length=0,i[t].length=0,a[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},o_.Buffer);var W_=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"];function Y_(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}var X_=Y_.prototype;function Z_(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(a<0)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function J_(t,e){for(var r=G_.malloc(t.length,e),n=t.length,i=0;i=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=Z_(this.gl,this.type,this.length,this.usage,t.data,e):this.length=Z_(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var n=G_.malloc(t.size,r),i=Wb(n,t.shape);Cb.assign(i,t),this.length=Z_(this.gl,this.type,this.length,this.usage,e<0?n:n.subarray(0,t.size),e),G_.free(n)}}else if(Array.isArray(t)){var a;a=this.type===this.gl.ELEMENT_ARRAY_BUFFER?J_(t,"uint16"):J_(t,"float32"),this.length=Z_(this.gl,this.type,this.length,this.usage,e<0?a:a.subarray(0,t.length),e),G_.free(a)}else if("object"==typeof t&&"number"==typeof t.length)this.length=Z_(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");(t|=0)<=0&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}};var K_=function(t,e,r,n){if(r=r||t.ARRAY_BUFFER,n=n||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(n!==t.DYNAMIC_DRAW&&n!==t.STATIC_DRAW&&n!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var i=new Y_(t,r,t.createBuffer(),0,n);return i.update(e),i},Q_=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;n=0){var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new rw("","Invalid data type for attribute "+l+": "+u);ow(t,e,c[0],n,h,i,l)}else{if(!(u.indexOf("mat")>=0))throw new rw("","Unknown data type for attribute "+l+": "+u);var h=u.charCodeAt(u.length-1)-48;if(h<2||h>4)throw new rw("","Invalid data type for attribute "+l+": "+u);sw(t,e,c,n,h,i,l)}}}return i};function iw(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}var aw=iw.prototype;function ow(t,e,r,n,i,a,o){for(var s=["gl","v"],l=[],u=0;u1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;u4)throw new rw("","Invalid uniform dimension type for matrix "+Tg+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new rw("","Unknown uniform data type for "+Tg+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(i<2||i>4)throw new rw("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new rw("","Unrecognized data type for vector "+Tg+": "+r)}}}function a(e){for(var a=["return function updateProperty(obj){"],o=function t(e,r){if("object"!=typeof r)return[[e,r]];var n=[];for(var i in r){var a=r[i],o=e;parseInt(i)+""===i?o+="["+i+"]":o+="."+i,"object"==typeof a?n.push.apply(n,t(o,a)):n.push([o,a])}return n}("",e),s=0;s4)throw new rw("","Invalid data type");return"b"===t.charAt(0)?hw(r,!1):hw(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(r<2||r>4)throw new rw("","Invalid uniform dimension type for matrix "+Tg+": "+t);return hw(r*r,0)}throw new rw("","Unknown uniform data type for "+Tg+": "+t)}}(r[l].type);var c}function s(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1)for(var s=0;s=r)return mw.substr(0,r);for(;r>mw.length&&e>1;)1&e&&(mw+=t),e>>=1,t+=t;return mw=(mw+=t).substr(0,r)};var xw=function(t,e,r){return yw(r=void 0!==r?r+"":" ",e)+t},bw=function(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),i=String(n.length+e-1).length;return n.map(function(t,n){var a=n+e,o=String(a).length,s=xw(a,i-o);return s+r+t}).join("\n")};var _w={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34000:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"},ww=function(t){return _w[t]},kw=function(t){return atob(t)},Mw=["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"],Aw=(Mw=Mw.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)})).concat(["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","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"]),Tw=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","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","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"],Sw=Tw.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),Cw=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"],Ew=function(t){var e,r,n,i=0,a=0,o=Lw,s=[],l=[],u=1,c=0,h=0,f=!1,p=!1,d="",g=Mw,v=Tw;"300 es"===(t=t||{}).version&&(g=Aw,v=Sw);return function(t){return l=[],null!==t?function(t){var r;i=0,n=(d+=t).length;for(;e=d[i],i0)continue;r=t.slice(0,1).join("")}return m(r),h+=r.length,(s=s.slice(r.length)).length}}function M(){return/[^a-fA-F0-9]/.test(e)?(m(s.join("")),o=Lw,i):(s.push(e),r=e,i+1)}function A(){return"."===e?(s.push(e),o=Bw,r=e,i+1):/[eE]/.test(e)?(s.push(e),o=Bw,r=e,i+1):"x"===e&&1===s.length&&"0"===s[0]?(o=qw,s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=Lw,i):(s.push(e),r=e,i+1)}function T(){return"f"===e&&(s.push(e),r=e,i+=1),/[eE]/.test(e)?(s.push(e),r=e,i+1):"-"===e&&/[eE]/.test(r)?(s.push(e),r=e,i+1):/[^\d]/.test(e)?(m(s.join("")),o=Lw,i):(s.push(e),r=e,i+1)}function S(){if(/[^\d\w_]/.test(e)){var t=s.join("");return o=v.indexOf(t)>-1?jw:g.indexOf(t)>-1?Nw:Fw,m(s.join("")),o=Lw,i}return s.push(e),r=e,i+1}},Lw=999,Pw=9999,zw=0,Dw=1,Iw=2,Ow=3,Rw=4,Bw=5,Fw=6,Nw=7,jw=8,Vw=9,Uw=10,qw=11,Hw=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];var Gw=function(t,e){var r=Ew(e),n=[];return n=(n=n.concat(r(t))).concat(r(null))};var Ww=function(t){for(var e=Array.isArray(t)?t:Gw(t),r=0;r=0),s[8]){case"b":i=parseInt(i,10).toString(2);break;case"c":i=String.fromCharCode(parseInt(i,10));break;case"d":case"i":i=parseInt(i,10);break;case"j":i=JSON.stringify(i,null,s[6]?parseInt(s[6]):0);break;case"e":i=s[7]?parseFloat(i).toExponential(s[7]):parseFloat(i).toExponential();break;case"f":i=s[7]?parseFloat(i).toFixed(s[7]):parseFloat(i);break;case"g":i=s[7]?String(Number(i.toPrecision(s[7]))):parseFloat(i);break;case"o":i=(parseInt(i,10)>>>0).toString(8);break;case"s":i=String(i),i=s[7]?i.substring(0,s[7]):i;break;case"t":i=String(!!i),i=s[7]?i.substring(0,s[7]):i;break;case"T":i=Object.prototype.toString.call(i).slice(8,-1).toLowerCase(),i=s[7]?i.substring(0,s[7]):i;break;case"u":i=parseInt(i,10)>>>0;break;case"v":i=i.valueOf(),i=s[7]?i.substring(0,s[7]):i;break;case"x":i=(parseInt(i,10)>>>0).toString(16);break;case"X":i=(parseInt(i,10)>>>0).toString(16).toUpperCase()}t.json.test(s[8])?g+=i:(!t.number.test(s[8])||h&&!s[3]?f="":(f=h?"+":"-",i=i.toString().replace(t.sign,"")),u=s[4]?"0"===s[4]?"0":s[4].charAt(1):" ",c=s[6]-(f+i).length,l=s[6]&&c>0?u.repeat(c):"",g+=s[5]?f+i+l:"0"===u?f+l+i:l+f+i)}return g}(function(e){if(n[e])return n[e];var r,i=e,a=[],o=0;for(;i;){if(null!==(r=t.text.exec(i)))a.push(r[0]);else if(null!==(r=t.modulo.exec(i)))a.push("%");else{if(null===(r=t.placeholder.exec(i)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){o|=1;var s=[],l=r[2],u=[];if(null===(u=t.key.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(l=l.substring(u[0].length));)if(null!==(u=t.key_access.exec(l)))s.push(u[1]);else{if(null===(u=t.index_access.exec(l)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}r[2]=s}else o|=2;if(3===o)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");a.push(r)}i=i.substring(r[0].length)}return n[e]=a}(r),arguments)}function r(t,r){return e.apply(null,[t].concat(r||[]))}var n=Object.create(null);void 0!==Yw&&(Yw.sprintf=e,Yw.vsprintf=r),"undefined"!=typeof window&&(window.sprintf=e,window.vsprintf=r,"function"==typeof aH&&aH.amd&&aH(function(){return{sprintf:e,vsprintf:r}}))}();var Xw=Yw.sprintf,Zw=function(t,e,r){"use strict";var n=Ww(e)||"of unknown name (see npm glsl-shader-name)",i="unknown type";void 0!==r&&(i=r===ww.FRAGMENT_SHADER?"fragment":"vertex");for(var a=Xw("Error compiling %s shader %s:\n",i,n),o=Xw("%s%s",a,t),s=t.split("\n"),l={},u=0;ur)for(t=r;te)for(t=e;t=0){for(var v=0|g.type.charAt(g.type.length-1),m=new Array(v),y=0;y=0;)x+=1;d[h]=x}var b=new Array(r.length);function _(){a.program=Qw.program(o,a._vref,a._fref,p,d);for(var t=0;t>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function gk(t,e,r,n){return new Function([dk("A","x"+t+"y",e,["y"],n),dk("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}pk.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},pk.drawBox=(hk=[0,0],fk=[0,0],function(t,e,r,n,i){var a=this.plot,o=this.shader,s=a.gl;hk[0]=t,hk[1]=e,fk[0]=r,fk[1]=n,o.uniforms.lo=hk,o.uniforms.hi=fk,o.uniforms.color=i,s.drawArrays(s.TRIANGLE_STRIP,0,4)}),pk.dispose=function(){this.vbo.dispose(),this.shader.dispose()};var vk={ge:gk(">=",!1,"GE"),gt:gk(">",!1,"GT"),lt:gk("<",!0,"LT"),le:gk("<=",!0,"LE"),eq:gk("-",!0,"EQ",!0)};function mk(t,e,r,n,i){var a=["function ",t,"(a,l,h,",n.join(","),"){",i?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function yk(t,e,r,n){return new Function([mk("A","x"+t+"y",e,["y"],n),mk("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var xk={ge:yk(">=",!1,"GE"),gt:yk(">",!1,"GT"),lt:yk("<",!0,"LT"),le:yk("<=",!0,"LE"),eq:yk("-",!0,"EQ",!0)},bk=function(t){var e=t.gl,r=K_(e),n=lk(e,tw.gridVert,tw.gridFrag),i=lk(e,tw.tickVert,tw.gridFrag);return new _k(t,r,n,i)};function _k(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function wk(t,e){return t-e}var kk,Mk,Ak,Tk,Sk,Ck=_k.prototype;Ck.draw=(kk=[0,0],Mk=[0,0],Ak=[0,0],function(){for(var t=this.plot,e=this.vbo,r=this.shader,n=this.ticks,i=t.gl,a=t._tickBounds,o=t.dataBox,s=t.viewBox,l=t.gridLineWidth,u=t.gridLineColor,c=t.gridLineEnable,h=t.pixelRatio,f=0;f<2;++f){var p=a[f],d=a[f+2]-p,g=.5*(o[f+2]+o[f]),v=o[f+2]-o[f];Mk[f]=2*d/v,kk[f]=2*(p-g)/v}r.bind(),e.bind(),r.attributes.dataCoord.pointer(),r.uniforms.dataShift=kk,r.uniforms.dataScale=Mk;var m=0;for(f=0;f<2;++f){Ak[0]=Ak[1]=0,Ak[f]=1,r.uniforms.dataAxis=Ak,r.uniforms.lineWidth=l[f]/(s[f+2]-s[f])*h,r.uniforms.color=u[f];var y=6*n[f].length;c[f]&&y&&i.drawArrays(i.TRIANGLES,m,y),m+=y}}),Ck.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],i=[0,0],a=[0,0];return function(){for(var o=this.plot,s=this.vbo,l=this.tickShader,u=this.ticks,c=o.gl,h=o._tickBounds,f=o.dataBox,p=o.viewBox,d=o.pixelRatio,g=o.screenBox,v=g[2]-g[0],m=g[3]-g[1],y=p[2]-p[0],x=p[3]-p[1],b=0;b<2;++b){var _=h[b],w=h[b+2]-_,k=.5*(f[b+2]+f[b]),M=f[b+2]-f[b];e[b]=2*w/M,t[b]=2*(_-k)/M}e[0]*=y/v,t[0]*=y/v,e[1]*=x/m,t[1]*=x/m,l.bind(),s.bind(),l.attributes.dataCoord.pointer();var A=l.uniforms;A.dataShift=t,A.dataScale=e;var T=o.tickMarkLength,S=o.tickMarkWidth,C=o.tickMarkColor,E=6*u[0].length,L=Math.min(xk.ge(u[0],(f[0]-h[0])/(h[2]-h[0]),wk),u[0].length),P=Math.min(xk.gt(u[0],(f[2]-h[0])/(h[2]-h[0]),wk),u[0].length),z=0+6*L,D=6*Math.max(0,P-L),I=Math.min(xk.ge(u[1],(f[1]-h[1])/(h[3]-h[1]),wk),u[1].length),O=Math.min(xk.gt(u[1],(f[3]-h[1])/(h[3]-h[1]),wk),u[1].length),R=E+6*I,B=6*Math.max(0,O-I);i[0]=2*(p[0]-T[1])/v-1,i[1]=(p[3]+p[1])/m-1,a[0]=T[1]*d/v,a[1]=S[1]*d/m,B&&(A.color=C[1],A.tickScale=a,A.dataAxis=n,A.screenOffset=i,c.drawArrays(c.TRIANGLES,R,B)),i[0]=(p[2]+p[0])/v-1,i[1]=2*(p[1]-T[0])/m-1,a[0]=S[0]*d/v,a[1]=T[0]*d/m,D&&(A.color=C[0],A.tickScale=a,A.dataAxis=r,A.screenOffset=i,c.drawArrays(c.TRIANGLES,z,D)),i[0]=2*(p[2]+T[3])/v-1,i[1]=(p[3]+p[1])/m-1,a[0]=T[3]*d/v,a[1]=S[3]*d/m,B&&(A.color=C[3],A.tickScale=a,A.dataAxis=n,A.screenOffset=i,c.drawArrays(c.TRIANGLES,R,B)),i[0]=(p[2]+p[0])/v-1,i[1]=2*(p[3]+T[2])/m-1,a[0]=S[2]*d/v,a[1]=T[2]*d/m,D&&(A.color=C[2],A.tickScale=a,A.dataAxis=r,A.screenOffset=i,c.drawArrays(c.TRIANGLES,z,D))}}(),Ck.update=(Tk=[1,1,-1,-1,1,-1],Sk=[1,-1,1,1,-1,-1],function(t){for(var e=t.ticks,r=t.bounds,n=new Float32Array(18*(e[0].length+e[1].length)),i=(this.plot.zeroLineEnable,0),a=[[],[]],o=0;o<2;++o)for(var s=a[o],l=e[o],u=r[o],c=r[o+2],h=0;h=n?(i=h,(l+=1)=n?(i=h,(l+=1)>1;return["sum(",qk(t.slice(0,e)),",",qk(t.slice(e)),")"].join("")}function Hk(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return Hk(e,t)}function Gk(t){if(2===t.length)return[["diff(",Hk(t[0][0],t[1][1]),",",Hk(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r0;){for(var l=r.pop(),a=r.pop(),u=-1,c=-1,o=i[a],f=1;f=0||(e.flip(a,l),Kk(t,e,r,u,a,c),Kk(t,e,r,a,c,u),Kk(t,e,r,c,l,u),Kk(t,e,r,l,u,c)))}};function Kk(t,e,r,n,i,a){var o=e.opposite(n,i);if(!(o<0)){if(i0||o.length>0;){for(;a.length>0;){var h=a.pop();if(s[h]!==-i){s[h]=i;l[h];for(var f=0;f<3;++f){var p=c[3*h+f];p>=0&&0===s[p]&&(u[3*h+f]?o.push(p):(a.push(p),s[p]=i))}}}var d=o;o=a,a=d,o.length=0,i=-i}var g=function(t,e,r){for(var n=0,i=0;i>1;return["sum(",aM(t.slice(0,e)),",",aM(t.slice(e)),")"].join("")}function oM(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r0){if(a<=0)return o;n=i+a}else{if(!(i<0))return o;if(a>=0)return o;n=-(i+a)}var s=3.3306690738754716e-16*n;return o>=s||o<=-s?o:lM(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],h=e[2]-n[2],f=r[2]-n[2],p=a*u,d=o*l,g=o*s,v=i*u,m=i*l,y=a*s,x=c*(p-d)+h*(g-v)+f*(m-y),b=7.771561172376103e-16*((Math.abs(p)+Math.abs(d))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(h)+(Math.abs(m)+Math.abs(y))*Math.abs(f));return x>b||-x>b?x:uM(t,e,r,n)}];!function(){for(;cM.length<=nM;)cM.push(sM(cM.length));for(var t=[],e=["slow"],r=0;r<=nM;++r)t.push("a"+r),e.push("o"+r);var n=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"];for(r=2;r<=nM;++r)n.push("case ",r,":return o",r,"(",t.slice(0,r).join(),");");n.push("}var s=new Array(arguments.length);for(var i=0;il[0]&&i.push(new mM(l,s,dM,a),new mM(s,l,pM,a))}i.sort(yM);for(var u=i[0].a[0]-(1+Math.abs(i[0].a[0]))*Math.pow(2,-52),c=[new vM([u,1],[u,0],-1,[],[],[],[])],h=[],a=0,f=i.length;a1&&hM(r[u[c-2]],r[u[c-1]],n)>0;)t.push([u[c-1],u[c-2],i]),c-=1;u.length=c,u.push(i);var h=l.upperIds;for(c=h.length;c>1&&hM(r[h[c-2]],r[h[c-1]],n)<0;)t.push([h[c-2],h[c-1],i]),c-=1;h.length=c,h.push(i)}}function _M(t,e){var r;return(r=t.a[0]=0}}(),TM.removeTriangle=function(t,e,r){var n=this.stars;SM(n[t],e,r),SM(n[e],r,t),SM(n[r],t,e)},TM.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},TM.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;n=49&&o<=54?o-49+10:o>=17&&o<=22?o-17+10:15&o}return n}function s(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;o=49?s-49+10:s>=17?s-17+10:s}return i}i.isBN=function(t){return t instanceof i||null!==t&&"object"==typeof t&&t.constructor.wordSize===i.wordSize&&Array.isArray(t.words)},i.max=function(t,e){return t.cmp(e)>0?t:e},i.min=function(t,e){return t.cmp(e)<0?t:e},i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&e<=36);var i=0;"-"===(t=t.toString().replace(/\s+/g,""))[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.negative=1),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){t<0&&(this.negative=1,t=-t),t<67108864?(this.words=[67108863&t],this.length=1):t<4503599627370496?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(t<9007199254740992),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)o=t[i]|t[i-1]<<8|t[i-2]<<16,this.words[a]|=o<>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);else if("le"===n)for(i=0,a=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,a++);return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6)i=o(t,r,r+6),this.words[n]|=i<>>26-a&4194303,(a+=24)>=26&&(a-=26,n++);r+6!==e&&(i=o(t,e,r+6),this.words[n]|=i<>>26-a&4194303),this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,o=a%n,l=Math.min(a,a-o)+r,u=0,c=r;c1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?""};var l=["","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"],u=[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],c=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function h(t,e,r){r.negative=e.negative^t.negative;var n=t.length+e.length|0;r.length=n,n=n-1|0;var i=0|t.words[0],a=0|e.words[0],o=i*a,s=67108863&o,l=o/67108864|0;r.words[0]=s;for(var u=1;u>>26,h=67108863&l,f=Math.min(u,e.length-1),p=Math.max(0,u-t.length+1);p<=f;p++){var d=u-p|0;c+=(o=(i=0|t.words[d])*(a=0|e.words[p])+h)/67108864|0,h=67108863&o}r.words[u]=0|h,l=0|c}return 0!==l?r.words[u]=0|l:r.length--,r.strip()}i.prototype.toString=function(t,e){var n;if(t=t||10,e=0|e||1,16===t||"hex"===t){n="";for(var i=0,a=0,o=0;o>>24-i&16777215)||o!==this.length-1?l[6-h.length]+h+n:h+n,(i+=2)>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(t===(0|t)&&t>=2&&t<=36){var f=u[t],p=c[t];n="";var d=this.clone();for(d.negative=0;!d.isZero();){var g=d.modn(p).toString(t);n=(d=d.idivn(p)).isZero()?g+n:l[f-g.length]+g+n}for(this.isZero()&&(n="0"+n);n.length%e!=0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var t=this.words[0];return 2===this.length?t+=67108864*this.words[1]:3===this.length&&1===this.words[2]?t+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-t:t},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(t,e){return r(void 0!==a),this.toArrayLike(a,t,e)},i.prototype.toArray=function(t,e){return this.toArrayLike(Array,t,e)},i.prototype.toArrayLike=function(t,e,n){var i=this.byteLength(),a=n||Math.max(1,i);r(i<=a,"byte array longer than desired length"),r(a>0,"Requested array length <= 0"),this.strip();var o,s,l="le"===e,u=new t(a),c=this.clone();if(l){for(s=0;!c.isZero();s++)o=c.andln(255),c.iushrn(8),u[s]=o;for(;s=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0==(8191&e)&&(r+=13,e>>>=13),0==(127&e)&&(r+=7,e>>>=7),0==(15&e)&&(r+=4,e>>>=4),0==(3&e)&&(r+=2,e>>>=2),0==(1&e)&&r++,r},i.prototype.bitLength=function(){var t=this.words[this.length-1],e=this._countBits(t);return 26*(this.length-1)+e},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.uor=function(t){return this.length>t.length?this.clone().iuor(t):t.clone().iuor(this)},i.prototype.iuand=function(t){var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.uand=function(t){return this.length>t.length?this.clone().iuand(t):t.clone().iuand(this)},i.prototype.iuxor=function(t){var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.uxor=function(t){return this.length>t.length?this.clone().iuxor(t):t.clone().iuxor(this)},i.prototype.inotn=function(t){r("number"==typeof t&&t>=0);var e=0|Math.ceil(t/26),n=t%26;this._expand(e),n>0&&e--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-n),this.strip()},i.prototype.notn=function(t){return this.clone().inotn(t)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);var n=t/26|0,i=t%26;return this._expand(n+1),this.words[n]=e?this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26;for(;0!==i&&a>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(0!==t.negative){t.negative=0;var e=this.iadd(t);return t.negative=1,e._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(t),this.negative=1,this._normSign();var r,n,i=this.cmp(t);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=t):(r=t,n=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e;for(;0!==a&&o>26,this.words[o]=67108863&e;if(0===a&&o>>13,p=0|o[1],d=8191&p,g=p>>>13,v=0|o[2],m=8191&v,y=v>>>13,x=0|o[3],b=8191&x,_=x>>>13,w=0|o[4],k=8191&w,M=w>>>13,A=0|o[5],T=8191&A,S=A>>>13,C=0|o[6],E=8191&C,L=C>>>13,P=0|o[7],z=8191&P,D=P>>>13,I=0|o[8],O=8191&I,R=I>>>13,B=0|o[9],F=8191&B,N=B>>>13,j=0|s[0],V=8191&j,U=j>>>13,q=0|s[1],H=8191&q,G=q>>>13,W=0|s[2],Y=8191&W,X=W>>>13,Z=0|s[3],J=8191&Z,K=Z>>>13,Q=0|s[4],$=8191&Q,tt=Q>>>13,et=0|s[5],rt=8191&et,nt=et>>>13,it=0|s[6],at=8191&it,ot=it>>>13,st=0|s[7],lt=8191&st,ut=st>>>13,ct=0|s[8],ht=8191&ct,ft=ct>>>13,pt=0|s[9],dt=8191&pt,gt=pt>>>13;r.negative=t.negative^e.negative,r.length=19;var vt=(u+(n=Math.imul(h,V))|0)+((8191&(i=(i=Math.imul(h,U))+Math.imul(f,V)|0))<<13)|0;u=((a=Math.imul(f,U))+(i>>>13)|0)+(vt>>>26)|0,vt&=67108863,n=Math.imul(d,V),i=(i=Math.imul(d,U))+Math.imul(g,V)|0,a=Math.imul(g,U);var mt=(u+(n=n+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(f,H)|0))<<13)|0;u=((a=a+Math.imul(f,G)|0)+(i>>>13)|0)+(mt>>>26)|0,mt&=67108863,n=Math.imul(m,V),i=(i=Math.imul(m,U))+Math.imul(y,V)|0,a=Math.imul(y,U),n=n+Math.imul(d,H)|0,i=(i=i+Math.imul(d,G)|0)+Math.imul(g,H)|0,a=a+Math.imul(g,G)|0;var yt=(u+(n=n+Math.imul(h,Y)|0)|0)+((8191&(i=(i=i+Math.imul(h,X)|0)+Math.imul(f,Y)|0))<<13)|0;u=((a=a+Math.imul(f,X)|0)+(i>>>13)|0)+(yt>>>26)|0,yt&=67108863,n=Math.imul(b,V),i=(i=Math.imul(b,U))+Math.imul(_,V)|0,a=Math.imul(_,U),n=n+Math.imul(m,H)|0,i=(i=i+Math.imul(m,G)|0)+Math.imul(y,H)|0,a=a+Math.imul(y,G)|0,n=n+Math.imul(d,Y)|0,i=(i=i+Math.imul(d,X)|0)+Math.imul(g,Y)|0,a=a+Math.imul(g,X)|0;var xt=(u+(n=n+Math.imul(h,J)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(f,J)|0))<<13)|0;u=((a=a+Math.imul(f,K)|0)+(i>>>13)|0)+(xt>>>26)|0,xt&=67108863,n=Math.imul(k,V),i=(i=Math.imul(k,U))+Math.imul(M,V)|0,a=Math.imul(M,U),n=n+Math.imul(b,H)|0,i=(i=i+Math.imul(b,G)|0)+Math.imul(_,H)|0,a=a+Math.imul(_,G)|0,n=n+Math.imul(m,Y)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(y,Y)|0,a=a+Math.imul(y,X)|0,n=n+Math.imul(d,J)|0,i=(i=i+Math.imul(d,K)|0)+Math.imul(g,J)|0,a=a+Math.imul(g,K)|0;var bt=(u+(n=n+Math.imul(h,$)|0)|0)+((8191&(i=(i=i+Math.imul(h,tt)|0)+Math.imul(f,$)|0))<<13)|0;u=((a=a+Math.imul(f,tt)|0)+(i>>>13)|0)+(bt>>>26)|0,bt&=67108863,n=Math.imul(T,V),i=(i=Math.imul(T,U))+Math.imul(S,V)|0,a=Math.imul(S,U),n=n+Math.imul(k,H)|0,i=(i=i+Math.imul(k,G)|0)+Math.imul(M,H)|0,a=a+Math.imul(M,G)|0,n=n+Math.imul(b,Y)|0,i=(i=i+Math.imul(b,X)|0)+Math.imul(_,Y)|0,a=a+Math.imul(_,X)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,K)|0)+Math.imul(y,J)|0,a=a+Math.imul(y,K)|0,n=n+Math.imul(d,$)|0,i=(i=i+Math.imul(d,tt)|0)+Math.imul(g,$)|0,a=a+Math.imul(g,tt)|0;var _t=(u+(n=n+Math.imul(h,rt)|0)|0)+((8191&(i=(i=i+Math.imul(h,nt)|0)+Math.imul(f,rt)|0))<<13)|0;u=((a=a+Math.imul(f,nt)|0)+(i>>>13)|0)+(_t>>>26)|0,_t&=67108863,n=Math.imul(E,V),i=(i=Math.imul(E,U))+Math.imul(L,V)|0,a=Math.imul(L,U),n=n+Math.imul(T,H)|0,i=(i=i+Math.imul(T,G)|0)+Math.imul(S,H)|0,a=a+Math.imul(S,G)|0,n=n+Math.imul(k,Y)|0,i=(i=i+Math.imul(k,X)|0)+Math.imul(M,Y)|0,a=a+Math.imul(M,X)|0,n=n+Math.imul(b,J)|0,i=(i=i+Math.imul(b,K)|0)+Math.imul(_,J)|0,a=a+Math.imul(_,K)|0,n=n+Math.imul(m,$)|0,i=(i=i+Math.imul(m,tt)|0)+Math.imul(y,$)|0,a=a+Math.imul(y,tt)|0,n=n+Math.imul(d,rt)|0,i=(i=i+Math.imul(d,nt)|0)+Math.imul(g,rt)|0,a=a+Math.imul(g,nt)|0;var wt=(u+(n=n+Math.imul(h,at)|0)|0)+((8191&(i=(i=i+Math.imul(h,ot)|0)+Math.imul(f,at)|0))<<13)|0;u=((a=a+Math.imul(f,ot)|0)+(i>>>13)|0)+(wt>>>26)|0,wt&=67108863,n=Math.imul(z,V),i=(i=Math.imul(z,U))+Math.imul(D,V)|0,a=Math.imul(D,U),n=n+Math.imul(E,H)|0,i=(i=i+Math.imul(E,G)|0)+Math.imul(L,H)|0,a=a+Math.imul(L,G)|0,n=n+Math.imul(T,Y)|0,i=(i=i+Math.imul(T,X)|0)+Math.imul(S,Y)|0,a=a+Math.imul(S,X)|0,n=n+Math.imul(k,J)|0,i=(i=i+Math.imul(k,K)|0)+Math.imul(M,J)|0,a=a+Math.imul(M,K)|0,n=n+Math.imul(b,$)|0,i=(i=i+Math.imul(b,tt)|0)+Math.imul(_,$)|0,a=a+Math.imul(_,tt)|0,n=n+Math.imul(m,rt)|0,i=(i=i+Math.imul(m,nt)|0)+Math.imul(y,rt)|0,a=a+Math.imul(y,nt)|0,n=n+Math.imul(d,at)|0,i=(i=i+Math.imul(d,ot)|0)+Math.imul(g,at)|0,a=a+Math.imul(g,ot)|0;var kt=(u+(n=n+Math.imul(h,lt)|0)|0)+((8191&(i=(i=i+Math.imul(h,ut)|0)+Math.imul(f,lt)|0))<<13)|0;u=((a=a+Math.imul(f,ut)|0)+(i>>>13)|0)+(kt>>>26)|0,kt&=67108863,n=Math.imul(O,V),i=(i=Math.imul(O,U))+Math.imul(R,V)|0,a=Math.imul(R,U),n=n+Math.imul(z,H)|0,i=(i=i+Math.imul(z,G)|0)+Math.imul(D,H)|0,a=a+Math.imul(D,G)|0,n=n+Math.imul(E,Y)|0,i=(i=i+Math.imul(E,X)|0)+Math.imul(L,Y)|0,a=a+Math.imul(L,X)|0,n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,K)|0)+Math.imul(S,J)|0,a=a+Math.imul(S,K)|0,n=n+Math.imul(k,$)|0,i=(i=i+Math.imul(k,tt)|0)+Math.imul(M,$)|0,a=a+Math.imul(M,tt)|0,n=n+Math.imul(b,rt)|0,i=(i=i+Math.imul(b,nt)|0)+Math.imul(_,rt)|0,a=a+Math.imul(_,nt)|0,n=n+Math.imul(m,at)|0,i=(i=i+Math.imul(m,ot)|0)+Math.imul(y,at)|0,a=a+Math.imul(y,ot)|0,n=n+Math.imul(d,lt)|0,i=(i=i+Math.imul(d,ut)|0)+Math.imul(g,lt)|0,a=a+Math.imul(g,ut)|0;var Mt=(u+(n=n+Math.imul(h,ht)|0)|0)+((8191&(i=(i=i+Math.imul(h,ft)|0)+Math.imul(f,ht)|0))<<13)|0;u=((a=a+Math.imul(f,ft)|0)+(i>>>13)|0)+(Mt>>>26)|0,Mt&=67108863,n=Math.imul(F,V),i=(i=Math.imul(F,U))+Math.imul(N,V)|0,a=Math.imul(N,U),n=n+Math.imul(O,H)|0,i=(i=i+Math.imul(O,G)|0)+Math.imul(R,H)|0,a=a+Math.imul(R,G)|0,n=n+Math.imul(z,Y)|0,i=(i=i+Math.imul(z,X)|0)+Math.imul(D,Y)|0,a=a+Math.imul(D,X)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,K)|0)+Math.imul(L,J)|0,a=a+Math.imul(L,K)|0,n=n+Math.imul(T,$)|0,i=(i=i+Math.imul(T,tt)|0)+Math.imul(S,$)|0,a=a+Math.imul(S,tt)|0,n=n+Math.imul(k,rt)|0,i=(i=i+Math.imul(k,nt)|0)+Math.imul(M,rt)|0,a=a+Math.imul(M,nt)|0,n=n+Math.imul(b,at)|0,i=(i=i+Math.imul(b,ot)|0)+Math.imul(_,at)|0,a=a+Math.imul(_,ot)|0,n=n+Math.imul(m,lt)|0,i=(i=i+Math.imul(m,ut)|0)+Math.imul(y,lt)|0,a=a+Math.imul(y,ut)|0,n=n+Math.imul(d,ht)|0,i=(i=i+Math.imul(d,ft)|0)+Math.imul(g,ht)|0,a=a+Math.imul(g,ft)|0;var At=(u+(n=n+Math.imul(h,dt)|0)|0)+((8191&(i=(i=i+Math.imul(h,gt)|0)+Math.imul(f,dt)|0))<<13)|0;u=((a=a+Math.imul(f,gt)|0)+(i>>>13)|0)+(At>>>26)|0,At&=67108863,n=Math.imul(F,H),i=(i=Math.imul(F,G))+Math.imul(N,H)|0,a=Math.imul(N,G),n=n+Math.imul(O,Y)|0,i=(i=i+Math.imul(O,X)|0)+Math.imul(R,Y)|0,a=a+Math.imul(R,X)|0,n=n+Math.imul(z,J)|0,i=(i=i+Math.imul(z,K)|0)+Math.imul(D,J)|0,a=a+Math.imul(D,K)|0,n=n+Math.imul(E,$)|0,i=(i=i+Math.imul(E,tt)|0)+Math.imul(L,$)|0,a=a+Math.imul(L,tt)|0,n=n+Math.imul(T,rt)|0,i=(i=i+Math.imul(T,nt)|0)+Math.imul(S,rt)|0,a=a+Math.imul(S,nt)|0,n=n+Math.imul(k,at)|0,i=(i=i+Math.imul(k,ot)|0)+Math.imul(M,at)|0,a=a+Math.imul(M,ot)|0,n=n+Math.imul(b,lt)|0,i=(i=i+Math.imul(b,ut)|0)+Math.imul(_,lt)|0,a=a+Math.imul(_,ut)|0,n=n+Math.imul(m,ht)|0,i=(i=i+Math.imul(m,ft)|0)+Math.imul(y,ht)|0,a=a+Math.imul(y,ft)|0;var Tt=(u+(n=n+Math.imul(d,dt)|0)|0)+((8191&(i=(i=i+Math.imul(d,gt)|0)+Math.imul(g,dt)|0))<<13)|0;u=((a=a+Math.imul(g,gt)|0)+(i>>>13)|0)+(Tt>>>26)|0,Tt&=67108863,n=Math.imul(F,Y),i=(i=Math.imul(F,X))+Math.imul(N,Y)|0,a=Math.imul(N,X),n=n+Math.imul(O,J)|0,i=(i=i+Math.imul(O,K)|0)+Math.imul(R,J)|0,a=a+Math.imul(R,K)|0,n=n+Math.imul(z,$)|0,i=(i=i+Math.imul(z,tt)|0)+Math.imul(D,$)|0,a=a+Math.imul(D,tt)|0,n=n+Math.imul(E,rt)|0,i=(i=i+Math.imul(E,nt)|0)+Math.imul(L,rt)|0,a=a+Math.imul(L,nt)|0,n=n+Math.imul(T,at)|0,i=(i=i+Math.imul(T,ot)|0)+Math.imul(S,at)|0,a=a+Math.imul(S,ot)|0,n=n+Math.imul(k,lt)|0,i=(i=i+Math.imul(k,ut)|0)+Math.imul(M,lt)|0,a=a+Math.imul(M,ut)|0,n=n+Math.imul(b,ht)|0,i=(i=i+Math.imul(b,ft)|0)+Math.imul(_,ht)|0,a=a+Math.imul(_,ft)|0;var St=(u+(n=n+Math.imul(m,dt)|0)|0)+((8191&(i=(i=i+Math.imul(m,gt)|0)+Math.imul(y,dt)|0))<<13)|0;u=((a=a+Math.imul(y,gt)|0)+(i>>>13)|0)+(St>>>26)|0,St&=67108863,n=Math.imul(F,J),i=(i=Math.imul(F,K))+Math.imul(N,J)|0,a=Math.imul(N,K),n=n+Math.imul(O,$)|0,i=(i=i+Math.imul(O,tt)|0)+Math.imul(R,$)|0,a=a+Math.imul(R,tt)|0,n=n+Math.imul(z,rt)|0,i=(i=i+Math.imul(z,nt)|0)+Math.imul(D,rt)|0,a=a+Math.imul(D,nt)|0,n=n+Math.imul(E,at)|0,i=(i=i+Math.imul(E,ot)|0)+Math.imul(L,at)|0,a=a+Math.imul(L,ot)|0,n=n+Math.imul(T,lt)|0,i=(i=i+Math.imul(T,ut)|0)+Math.imul(S,lt)|0,a=a+Math.imul(S,ut)|0,n=n+Math.imul(k,ht)|0,i=(i=i+Math.imul(k,ft)|0)+Math.imul(M,ht)|0,a=a+Math.imul(M,ft)|0;var Ct=(u+(n=n+Math.imul(b,dt)|0)|0)+((8191&(i=(i=i+Math.imul(b,gt)|0)+Math.imul(_,dt)|0))<<13)|0;u=((a=a+Math.imul(_,gt)|0)+(i>>>13)|0)+(Ct>>>26)|0,Ct&=67108863,n=Math.imul(F,$),i=(i=Math.imul(F,tt))+Math.imul(N,$)|0,a=Math.imul(N,tt),n=n+Math.imul(O,rt)|0,i=(i=i+Math.imul(O,nt)|0)+Math.imul(R,rt)|0,a=a+Math.imul(R,nt)|0,n=n+Math.imul(z,at)|0,i=(i=i+Math.imul(z,ot)|0)+Math.imul(D,at)|0,a=a+Math.imul(D,ot)|0,n=n+Math.imul(E,lt)|0,i=(i=i+Math.imul(E,ut)|0)+Math.imul(L,lt)|0,a=a+Math.imul(L,ut)|0,n=n+Math.imul(T,ht)|0,i=(i=i+Math.imul(T,ft)|0)+Math.imul(S,ht)|0,a=a+Math.imul(S,ft)|0;var Et=(u+(n=n+Math.imul(k,dt)|0)|0)+((8191&(i=(i=i+Math.imul(k,gt)|0)+Math.imul(M,dt)|0))<<13)|0;u=((a=a+Math.imul(M,gt)|0)+(i>>>13)|0)+(Et>>>26)|0,Et&=67108863,n=Math.imul(F,rt),i=(i=Math.imul(F,nt))+Math.imul(N,rt)|0,a=Math.imul(N,nt),n=n+Math.imul(O,at)|0,i=(i=i+Math.imul(O,ot)|0)+Math.imul(R,at)|0,a=a+Math.imul(R,ot)|0,n=n+Math.imul(z,lt)|0,i=(i=i+Math.imul(z,ut)|0)+Math.imul(D,lt)|0,a=a+Math.imul(D,ut)|0,n=n+Math.imul(E,ht)|0,i=(i=i+Math.imul(E,ft)|0)+Math.imul(L,ht)|0,a=a+Math.imul(L,ft)|0;var Lt=(u+(n=n+Math.imul(T,dt)|0)|0)+((8191&(i=(i=i+Math.imul(T,gt)|0)+Math.imul(S,dt)|0))<<13)|0;u=((a=a+Math.imul(S,gt)|0)+(i>>>13)|0)+(Lt>>>26)|0,Lt&=67108863,n=Math.imul(F,at),i=(i=Math.imul(F,ot))+Math.imul(N,at)|0,a=Math.imul(N,ot),n=n+Math.imul(O,lt)|0,i=(i=i+Math.imul(O,ut)|0)+Math.imul(R,lt)|0,a=a+Math.imul(R,ut)|0,n=n+Math.imul(z,ht)|0,i=(i=i+Math.imul(z,ft)|0)+Math.imul(D,ht)|0,a=a+Math.imul(D,ft)|0;var Pt=(u+(n=n+Math.imul(E,dt)|0)|0)+((8191&(i=(i=i+Math.imul(E,gt)|0)+Math.imul(L,dt)|0))<<13)|0;u=((a=a+Math.imul(L,gt)|0)+(i>>>13)|0)+(Pt>>>26)|0,Pt&=67108863,n=Math.imul(F,lt),i=(i=Math.imul(F,ut))+Math.imul(N,lt)|0,a=Math.imul(N,ut),n=n+Math.imul(O,ht)|0,i=(i=i+Math.imul(O,ft)|0)+Math.imul(R,ht)|0,a=a+Math.imul(R,ft)|0;var zt=(u+(n=n+Math.imul(z,dt)|0)|0)+((8191&(i=(i=i+Math.imul(z,gt)|0)+Math.imul(D,dt)|0))<<13)|0;u=((a=a+Math.imul(D,gt)|0)+(i>>>13)|0)+(zt>>>26)|0,zt&=67108863,n=Math.imul(F,ht),i=(i=Math.imul(F,ft))+Math.imul(N,ht)|0,a=Math.imul(N,ft);var Dt=(u+(n=n+Math.imul(O,dt)|0)|0)+((8191&(i=(i=i+Math.imul(O,gt)|0)+Math.imul(R,dt)|0))<<13)|0;u=((a=a+Math.imul(R,gt)|0)+(i>>>13)|0)+(Dt>>>26)|0,Dt&=67108863;var It=(u+(n=Math.imul(F,dt))|0)+((8191&(i=(i=Math.imul(F,gt))+Math.imul(N,dt)|0))<<13)|0;return u=((a=Math.imul(N,gt))+(i>>>13)|0)+(It>>>26)|0,It&=67108863,l[0]=vt,l[1]=mt,l[2]=yt,l[3]=xt,l[4]=bt,l[5]=_t,l[6]=wt,l[7]=kt,l[8]=Mt,l[9]=At,l[10]=Tt,l[11]=St,l[12]=Ct,l[13]=Et,l[14]=Lt,l[15]=Pt,l[16]=zt,l[17]=Dt,l[18]=It,0!==u&&(l[19]=u,r.length++),r};function p(t,e,r){return(new d).mulp(t,e,r)}function d(t,e){this.x=t,this.y=e}Math.imul||(f=h),i.prototype.mulTo=function(t,e){var r=this.length+t.length;return 10===this.length&&10===t.length?f(this,t,e):r<63?h(this,t,e):r<1024?function(t,e,r){r.negative=e.negative^t.negative,r.length=t.length+e.length;for(var n=0,i=0,a=0;a>>26)|0)>>>26,o&=67108863}r.words[a]=s,n=o,o=i}return 0!==n?r.words[a]=n:r.length--,r.strip()}(this,t,e):p(this,t,e)},d.prototype.makeRBT=function(t){for(var e=new Array(t),r=i.prototype._countBits(t)-1,n=0;n>=1;return n},d.prototype.permute=function(t,e,r,n,i,a){for(var o=0;o>>=1)i++;return 1<>>=13,n[2*o+1]=8191&a,a>>>=13;for(o=2*e;o>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(t){var e=function(t){for(var e=new Array(t.bitLength()),r=0;r>>i}return e}(t);if(0===e.length)return new i(1);for(var r=this,n=0;n=0);var e,n=t%26,i=(t-n)/26,a=67108863>>>26-n<<26-n;if(0!==n){var o=0;for(e=0;e>>26-n}o&&(this.words[e]=o,this.length++)}if(0!==i){for(e=this.length-1;e>=0;e--)this.words[e+i]=this.words[e];for(e=0;e=0),i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<o)for(this.length-=o,u=0;u=0&&(0!==c||u>=i);u--){var h=0|this.words[u];this.words[u]=c<<26-a|h>>>a,c=h&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(t,e,n){return r(0===this.negative),this.iushrn(t,e,n)},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.ushln=function(t){return this.clone().iushln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.ushrn=function(t){return this.clone().iushrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),r(t<67108864),t<0)return this.iaddn(-t);if(0!==this.negative)return this.negative=0,this.iaddn(t),this.negative=1,this;if(this.words[0]-=t,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var e=0;e>26)-(l/67108864|0),this.words[i+n]=67108863&a}for(;i>26,this.words[i+n]=67108863&a;if(0===s)return this.strip();for(r(-1===s),s=0,i=0;i>26,this.words[i]=67108863&a;return this.negative=1,this.strip()},i.prototype._wordDiv=function(t,e){var r=(this.length,t.length),n=this.clone(),a=t,o=0|a.words[a.length-1];0!==(r=26-this._countBits(o))&&(a=a.ushln(r),n.iushln(r),o=0|a.words[a.length-1]);var s,l=n.length-a.length;if("mod"!==e){(s=new i(null)).length=l+1,s.words=new Array(s.length);for(var u=0;u=0;h--){var f=67108864*(0|n.words[a.length+h])+(0|n.words[a.length+h-1]);for(f=Math.min(f/o|0,67108863),n._ishlnsubmul(a,f,h);0!==n.negative;)f--,n.negative=0,n._ishlnsubmul(a,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=f)}return s&&s.strip(),n.strip(),"div"!==e&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},i.prototype.divmod=function(t,e,n){return r(!t.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===t.negative?(s=this.neg().divmod(t,e),"mod"!==e&&(a=s.div.neg()),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.iadd(t)),{div:a,mod:o}):0===this.negative&&0!==t.negative?(s=this.divmod(t.neg(),e),"mod"!==e&&(a=s.div.neg()),{div:a,mod:s.mod}):0!=(this.negative&t.negative)?(s=this.neg().divmod(t.neg(),e),"div"!==e&&(o=s.mod.neg(),n&&0!==o.negative&&o.isub(t)),{div:s.div,mod:o}):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e);var a,o,s},i.prototype.div=function(t){return this.divmod(t,"div",!1).div},i.prototype.mod=function(t){return this.divmod(t,"mod",!1).mod},i.prototype.umod=function(t){return this.divmod(t,"mod",!0).mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(e.mod.isZero())return e.div;var r=0!==e.div.negative?e.mod.isub(t):e.mod,n=t.ushrn(1),i=t.andln(1),a=r.cmp(n);return a<0||1===i&&0===a?e.div:0!==e.div.negative?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(t<=67108863);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+(0|this.words[i]))%t;return n},i.prototype.idivn=function(t){r(t<=67108863);for(var e=0,n=this.length-1;n>=0;n--){var i=(0|this.words[n])+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.iushrn(1),n.iushrn(1),++u;for(var c=n.clone(),h=e.clone();!e.isZero();){for(var f=0,p=1;0==(e.words[0]&p)&&f<26;++f,p<<=1);if(f>0)for(e.iushrn(f);f-- >0;)(a.isOdd()||o.isOdd())&&(a.iadd(c),o.isub(h)),a.iushrn(1),o.iushrn(1);for(var d=0,g=1;0==(n.words[0]&g)&&d<26;++d,g<<=1);if(d>0)for(n.iushrn(d);d-- >0;)(s.isOdd()||l.isOdd())&&(s.iadd(c),l.isub(h)),s.iushrn(1),l.iushrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.iushln(u)}},i.prototype._invmp=function(t){r(0===t.negative),r(!t.isZero());var e=this,n=t.clone();e=0!==e.negative?e.umod(t):e.clone();for(var a,o=new i(1),s=new i(0),l=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(var u=0,c=1;0==(e.words[0]&c)&&u<26;++u,c<<=1);if(u>0)for(e.iushrn(u);u-- >0;)o.isOdd()&&o.iadd(l),o.iushrn(1);for(var h=0,f=1;0==(n.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(n.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(l),s.iushrn(1);e.cmp(n)>=0?(e.isub(n),o.isub(s)):(n.isub(e),s.isub(o))}return(a=0===e.cmpn(1)?o:s).cmpn(0)<0&&a.iadd(t),a},i.prototype.gcd=function(t){if(this.isZero())return t.abs();if(t.isZero())return this.abs();var e=this.clone(),r=t.clone();e.negative=0,r.negative=0;for(var n=0;e.isEven()&&r.isEven();n++)e.iushrn(1),r.iushrn(1);for(;;){for(;e.isEven();)e.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=e.cmp(r);if(i<0){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.iushln(n)},i.prototype.invm=function(t){return this.egcd(t).a.umod(t)},i.prototype.isEven=function(){return 0==(1&this.words[0])},i.prototype.isOdd=function(){return 1==(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<>>26,s&=67108863,this.words[o]=s}return 0!==a&&(this.words[o]=a,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(t){var e,n=t<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this.strip(),this.length>1)e=1;else{n&&(t=-t),r(t<=67108863,"Number is too big");var i=0|this.words[0];e=i===t?0:it.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|t.words[r];if(n!==i){ni&&(e=1);break}}return e},i.prototype.gtn=function(t){return 1===this.cmpn(t)},i.prototype.gt=function(t){return 1===this.cmp(t)},i.prototype.gten=function(t){return this.cmpn(t)>=0},i.prototype.gte=function(t){return this.cmp(t)>=0},i.prototype.ltn=function(t){return-1===this.cmpn(t)},i.prototype.lt=function(t){return-1===this.cmp(t)},i.prototype.lten=function(t){return this.cmpn(t)<=0},i.prototype.lte=function(t){return this.cmp(t)<=0},i.prototype.eqn=function(t){return 0===this.cmpn(t)},i.prototype.eq=function(t){return 0===this.cmp(t)},i.red=function(t){return new _(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var g={k256:null,p224:null,p192:null,p25519:null};function v(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function m(){v.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function y(){v.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function x(){v.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function b(){v.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function _(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else r(t.gtn(1),"modulus must be greater than 1"),this.m=t,this.prime=null}function w(t){_.call(this,t),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}v.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},v.prototype.ireduce=function(t){var e,r=t;do{this.split(r,this.tmp),e=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},v.prototype.split=function(t,e){t.iushrn(this.n,0,e)},v.prototype.imulK=function(t){return t.imul(this.k)},n(m,v),m.prototype.split=function(t,e){for(var r=Math.min(t.length,9),n=0;n>>22,i=a}i>>>=22,t.words[n-10]=i,0===i&&t.length>10?t.length-=10:t.length-=9},m.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e=0,r=0;r>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function(t){if(g[t])return g[t];var e;if("k256"===t)e=new m;else if("p224"===t)e=new y;else if("p192"===t)e=new x;else{if("p25519"!==t)throw new Error("Unknown prime "+t);e=new b}return g[t]=e,e},_.prototype._verify1=function(t){r(0===t.negative,"red works only with positives"),r(t.red,"red works only with red numbers")},_.prototype._verify2=function(t,e){r(0==(t.negative|e.negative),"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},_.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.umod(this.m)._forceRed(this)},_.prototype.neg=function(t){return t.isZero()?t.clone():this.m.sub(t)._forceRed(this)},_.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},_.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},_.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},_.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},_.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.ushln(e))},_.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},_.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},_.prototype.isqr=function(t){return this.imul(t,t.clone())},_.prototype.sqr=function(t){return this.mul(t,t)},_.prototype.sqrt=function(t){if(t.isZero())return t.clone();var e=this.m.andln(3);if(r(e%2==1),3===e){var n=this.m.add(new i(1)).iushrn(2);return this.pow(t,n)}for(var a=this.m.subn(1),o=0;!a.isZero()&&0===a.andln(1);)o++,a.iushrn(1);r(!a.isZero());var s=new i(1).toRed(this),l=s.redNeg(),u=this.m.subn(1).iushrn(1),c=this.m.bitLength();for(c=new i(2*c*c).toRed(this);0!==this.pow(c,u).cmp(l);)c.redIAdd(l);for(var h=this.pow(c,a),f=this.pow(t,a.addn(1).iushrn(1)),p=this.pow(t,a),d=o;0!==p.cmp(s);){for(var g=p,v=0;0!==g.cmp(s);v++)g=g.redSqr();r(v=0;n--){for(var u=e.words[n],c=l-1;c>=0;c--){var h=u>>c&1;a!==r[0]&&(a=this.sqr(a)),0!==h||0!==o?(o<<=1,o|=h,(4===++s||0===n&&0===c)&&(a=this.mul(a,r[o]),s=0,o=0)):s=0}l=26}return a},_.prototype.convertTo=function(t){var e=t.umod(this.m);return e===t?e.clone():e},_.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new w(t)},n(w,_),w.prototype.convertTo=function(t){return this.imod(t.ushln(this.shift))},w.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},w.prototype.imul=function(t,e){if(t.isZero()||e.isZero())return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},w.prototype.mul=function(t,e){if(t.isZero()||e.isZero())return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).iushrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},w.prototype.invm=function(t){return this.imod(t._invmp(this.m).mul(this.r2))._forceRed(this)}}(IM,this),IM=IM.exports;var OM=function(t){return t.cmp(new IM(0))};var RM={};(function(t){var e=!1;if("undefined"!=typeof Float64Array){var r=new Float64Array(1),n=new Uint32Array(r.buffer);if(r[0]=1,e=!0,1072693248===n[1]){(RM=function(t){return r[0]=t,[n[0],n[1]]}).pack=function(t,e){return n[0]=t,n[1]=e,r[0]},RM.lo=function(t){return r[0]=t,n[0]},RM.hi=function(t){return r[0]=t,n[1]}}else if(1072693248===n[0]){(RM=function(t){return r[0]=t,[n[1],n[0]]}).pack=function(t,e){return n[1]=t,n[0]=e,r[0]},RM.lo=function(t){return r[0]=t,n[1]},RM.hi=function(t){return r[0]=t,n[0]}}else e=!1}if(!e){var i=new t(8);(RM=function(t){return i.writeDoubleLE(t,0,!0),[i.readUInt32LE(0,!0),i.readUInt32LE(4,!0)]}).pack=function(t,e){return i.writeUInt32LE(t,0,!0),i.writeUInt32LE(e,4,!0),i.readDoubleLE(0,!0)},RM.lo=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(0,!0)},RM.hi=function(t){return i.writeDoubleLE(t,0,!0),i.readUInt32LE(4,!0)}}RM.sign=function(t){return RM.hi(t)>>>31},RM.exponent=function(t){return(RM.hi(t)<<1>>>21)-1023},RM.fraction=function(t){var e=RM.lo(t),r=RM.hi(t),n=1048575&r;return 2146435072&r&&(n+=1<<20),[e,n]},RM.denormalized=function(t){return!(2146435072&RM.hi(t))}}).call(this,o_.Buffer);var BM=function(t){var e=RM.exponent(t);return e<52?new IM(t):new IM(t*Math.pow(2,52-e)).ushln(e-52)};var FM=function(t,e){var r=OM(t),n=OM(e);if(0===r)return[BM(0),BM(1)];if(0===n)return[BM(0),BM(0)];n<0&&(t=t.neg(),e=e.neg());var i=t.gcd(e);if(i.cmpn(1))return[t.div(i),e.div(i)];return[t,e]};var NM=function(t,e){return FM(t[0].mul(e[1]),t[1].mul(e[0]))};var jM=function(t){return t&&"object"==typeof t&&Boolean(t.words)};var VM=function(t){return Array.isArray(t)&&2===t.length&&jM(t[0])&&jM(t[1])};var UM=function(t){return new IM(t)};var qM=function t(e,r){if(VM(e))return r?NM(e,t(r)):[e[0].clone(),e[1].clone()];var n=0;var i,a;if(jM(e))i=e.clone();else if("string"==typeof e)i=UM(e);else{if(0===e)return[BM(0),BM(1)];if(e===Math.floor(e))i=BM(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),n-=256;i=BM(e)}}if(VM(r))i.mul(r[1]),a=r[0].clone();else if(jM(r))a=r.clone();else if("string"==typeof r)a=UM(r);else if(r)if(r===Math.floor(r))a=BM(r);else{for(;r!==Math.floor(r);)r*=Math.pow(2,256),n+=256;a=BM(r)}else a=BM(1);n>0?i=i.ushln(n):n<0&&(a=a.ushln(-n));return FM(i,a)};var HM=function(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var i=0;i20)return 52;return r+32};var YM=function(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.abs().divmod(r.abs()),i=n.div,a=HM(i),o=n.mod,s=e.negative!==r.negative?-1:1;if(0===o.cmpn(0))return s*a;if(a){var l=WM(a)+4,u=HM(o.ushln(l).divRound(r));return s*(a+u*Math.pow(2,-l))}var c=r.bitLength()-o.bitLength()+53,u=HM(o.ushln(c).divRound(r));return c<1023?s*u*Math.pow(2,-c):(u*=Math.pow(2,-1023),s*u*Math.pow(2,1023-c))};var XM={},ZM="d",JM="ax",KM="vv",QM="fp",$M="es",tA="rs",eA="re",rA="rb",nA="ri",iA="rp",aA="bs",oA="be",sA="bb",lA="bi",uA="bp",cA="rv",hA="Q",fA=[ZM,JM,KM,tA,eA,rA,nA,aA,oA,sA,lA];function pA(t){var e="bruteForce"+(t?"Full":"Partial"),r=[],n=fA.slice();t||n.splice(3,0,QM);var i=["function "+e+"("+n.join()+"){"];function a(e,n){var a=function(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",fA.join(),"){","var ",$M,"=2*",ZM,";"],a="for(var i="+tA+","+iA+"="+$M+"*"+tA+";i<"+eA+";++i,"+iA+"+="+$M+"){var x0="+rA+"["+JM+"+"+iA+"],x1="+rA+"["+JM+"+"+iA+"+"+ZM+"],xi="+nA+"[i];",o="for(var j="+aA+","+uA+"="+$M+"*"+aA+";j<"+oA+";++j,"+uA+"+="+$M+"){var y0="+sA+"["+JM+"+"+uA+"],"+(r?"y1="+sA+"["+JM+"+"+uA+"+"+ZM+"],":"")+"yi="+lA+"[j];";return t?i.push(a,hA,":",o):i.push(o,hA,":",a),r?i.push("if(y1"+oA+"-"+aA+"){"),t?(a(!0,!1),i.push("}else{"),a(!1,!1)):(i.push("if("+QM+"){"),a(!0,!0),i.push("}else{"),a(!0,!1),i.push("}}else{if("+QM+"){"),a(!1,!0),i.push("}else{"),a(!1,!1),i.push("}")),i.push("}}return "+e);var o=r.join("")+i.join("");return new Function(o)()}XM.partial=pA(!1),XM.full=pA(!0);var dA=function(t,e){var r="abcdef".split("").concat(e),n=[];t.indexOf("lo")>=0&&n.push("lo=e[k+n]");t.indexOf("hi")>=0&&n.push("hi=e[k+o]");return r.push(gA.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)},gA="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m";var vA=function(t,e,r,n,i,a){if(n<=r+1)return r;var o=r,s=n,l=n+r>>>1,u=2*t,c=l,h=i[u*l+e];for(;o=v?(c=g,h=v):d>=y?(c=p,h=d):(c=m,h=y):v>=y?(c=g,h=v):y>=d?(c=p,h=d):(c=m,h=y);for(var x=u*(s-1),b=u*c,_=0;_r&&i[h+e]>u;--c,h-=o){for(var f=h,p=h+o,d=0;d>1,l=s-i,u=s+i,c=a,h=l,f=s,p=u,d=o,g=e+1,v=r-1,m=0;SA(c,h,n)&&(m=c,c=h,h=m);SA(p,d,n)&&(m=p,p=d,d=m);SA(c,f,n)&&(m=c,c=f,f=m);SA(h,f,n)&&(m=h,h=f,f=m);SA(c,p,n)&&(m=c,c=p,p=m);SA(f,p,n)&&(m=f,f=p,p=m);SA(h,d,n)&&(m=h,h=d,d=m);SA(h,f,n)&&(m=h,h=f,f=m);SA(p,d,n)&&(m=p,p=d,d=m);var y=n[2*h];var x=n[2*h+1];var b=n[2*p];var _=n[2*p+1];var w=2*c;var k=2*f;var M=2*d;var A=2*a;var T=2*s;var S=2*o;for(var C=0;C<2;++C){var E=n[w+C],L=n[k+C],P=n[M+C];n[A+C]=E,n[T+C]=L,n[S+C]=P}MA(l,e,n);MA(u,r,n);for(var z=g;z<=v;++z)if(CA(z,y,x,n))z!==g&&kA(z,g,n),++g;else if(!CA(z,b,_,n))for(;;){if(CA(v,b,_,n)){CA(v,y,x,n)?(AA(z,g,v,n),++g,--v):(kA(z,v,n),--v);break}if(--vt;){var u=r[l-2],c=r[l-1];if(ur[e+1])}function CA(t,e,r,n){var i=n[t*=2];return i>>1;bA(BA,y);for(var x=0,b=0,d=0;d=LA)FA(DA,IA,b--,_=_-LA|0);else if(_>=0)FA(PA,zA,x--,_);else if(_<=-LA){_=-_-LA|0;for(var w=0;w>>1;bA(BA,y);for(var x=0,b=0,_=0,d=0;d>1==BA[2*d+3]>>1&&(k=2,d+=1),w<0){for(var M=-(w>>1)-1,A=0;A<_;++A){var T=e(OA[A],M);if(void 0!==T)return T}if(0!==k)for(var A=0;A>1)-1;0===k?FA(PA,zA,x--,M):1===k?FA(DA,IA,b--,M):2===k&&FA(OA,RA,_--,M)}}},scanBipartite:function(t,e,r,n,i,a,o,s,l,u,c,h){var f=0,p=2*t,d=e,g=e+t,v=1,m=1;n?m=LA:v=LA;for(var y=i;y>>1;bA(BA,w);for(var k=0,y=0;y=LA?(A=!n,x-=LA):(A=!!n,x-=1),A)NA(PA,zA,k++,x);else{var T=h[x],S=p*x,C=c[S+e+1],E=c[S+e+1+t];t:for(var L=0;L>>1;bA(BA,x);for(var b=0,g=0;g=LA)PA[b++]=v-LA;else{var w=c[v-=1],k=f*v,M=u[k+e+1],A=u[k+e+1+t];t:for(var T=0;T=0;--T)if(PA[T]===v){for(var L=T+1;L0;){var f=(c-=1)*QA,p=tT[f],d=tT[f+1],g=tT[f+2],v=tT[f+3],m=tT[f+4],y=tT[f+5],x=c*$A,b=eT[x],_=eT[x+1],w=1&y,k=!!(16&y),M=i,A=a,T=s,S=l;if(w&&(M=s,A=l,T=i,S=a),!(2&y&&(g=XA(t,p,d,g,M,A,_),d>=g)||4&y&&(d=ZA(t,p,d,g,M,A,b))>=g)){var C=g-d,E=m-v;if(k){if(t*C*(C+E)=p0)&&!(p1>=hi)",["p0","p1"]),YA=dA("lo===p0",["p0"]),XA=dA("lo>>1;if(!(o<=0)){var s,l=G_.mallocDouble(2*o*i),u=G_.mallocInt32(i);if((i=lT(t,o,l,u))>0){if(1===o&&n)EA.init(i),s=EA.sweepComplete(o,r,0,i,l,u,0,i,l,u);else{var c=G_.mallocDouble(2*o*a),h=G_.mallocInt32(a);(a=lT(e,o,c,h))>0&&(EA.init(i+a),s=1===o?EA.sweepBipartite(o,r,0,i,l,u,0,a,c,h):jA(o,r,n,i,l,u,a,c,h),G_.free(c),G_.free(h))}G_.free(l),G_.free(u)}return s}}}function cT(t,e){aT.push([t,e])}var hT=function(t,e){return FM(t[0].mul(e[0]),t[1].mul(e[1]))};var fT=function(t){return OM(t[0])*OM(t[1])};var pT=function(t,e){return FM(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))};var dT=function(t,e){return FM(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))};var gT=function(t,e){for(var r=t.length,n=new Array(r),i=0;i>>0,wT=function(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return e<0?-bT:bT;var r=RM.hi(t),n=RM.lo(t);e>t==t>0?n===_T?(r+=1,n=0):n+=1:0===n?(n=_T,r-=1):n-=1;return RM.pack(n,r)};var kT=function(t){for(var e=new Array(t.length),r=0;r0&&a>0||i<0&&a<0)return!1;var o=AT(r,t,e),s=AT(n,t,e);if(o>0&&s>0||o<0&&s<0)return!1;if(0===i&&0===a&&0===o&&0===s)return function(t,e,r,n){for(var i=0;i<2;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],h=Math.min(u,c),f=Math.max(u,c);if(fe[2]?1:0)}function OT(t,e,r){if(0!==t.length){if(e)for(var n=0;n=0;--a){var d=e[o=(w=n[a])[0]],g=d[0],v=d[1],m=t[g],y=t[v];if((m[0]-y[0]||m[1]-y[1])<0){var x=g;g=v,v=x}d[0]=g;var b,_=d[1]=w[1];for(i&&(b=d[2]);a>0&&n[a-1][0]===o;){var w,k=(w=n[--a])[1];i?e.push([_,k,b]):e.push([_,k]),_=k}i?e.push([_,v,b]):e.push([_,v])}return s}(t,e,i,o,r));return OT(e,s,r),!!s||(i.length>0||o.length>0)}var BT=function(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;n0?1:0},jT=function(t,e,r,n){var i=rM(e,r,n);if(0===i){var a=NT(rM(t,e,r)),o=NT(rM(t,e,n));if(a===o){if(0===a){var s=VT(t,e,r),l=VT(t,e,n);return s===l?0:s?1:-1}return 0}return 0===o?a>0?-1:VT(t,e,n)?-1:1:0===a?o>0?1:VT(t,e,r)?1:-1:NT(o-a)}var u=rM(t,e,r);if(u>0)return i>0&&rM(t,e,n)>0?1:-1;if(u<0)return i>0||rM(t,e,n)>0?1:-1;var c=rM(t,e,n);return c>0?1:VT(t,e,r)?1:-1};function VT(t,e,r){var n=Rk(t[0],-e[0]),i=Rk(t[1],-e[1]),a=Rk(r[0],-e[0]),o=Rk(r[1],-e[1]),s=Nk(FT(n,a),FT(i,o));return s[s.length-1]>=0}var UT=function(t,e){for(var r=0|e.length,n=t.length,i=[new Array(r),new Array(r)],a=0;a0){a=i[u][r][0],s=u;break}o=a[1^s];for(var c=0;c<2;++c)for(var h=i[c][r],f=0;f0&&(a=p,o=d,s=c)}return n?o:(a&&l(a,s),o)}function c(t,r){var n=i[r][t][0],a=[t];l(n,r);for(var o=n[1^r];;){for(;o!==t;)a.push(o),o=u(a[a.length-2],o,!1);if(i[0][t].length+i[1][t].length===0)break;var s=a[a.length-1],c=t,h=a[1],f=u(s,c,!0);if(jT(e[s],e[c],e[h],e[f])<0)break;a.push(t),o=u(s,c)}return a}function h(t,e){return e[1]===e[e.length-1]}for(var a=0;a0;){i[0][a].length;var d=c(a,f);h(p,d)?p.push.apply(p,d):(p.length>0&&s.push(p),p=d)}p.length>0&&s.push(p)}return s};var qT=function(t,e){for(var r=BT(t,e.length),n=new Array(e.length),i=new Array(e.length),a=[],o=0;o0;){var l=a.pop();n[l]=!1;for(var u=r[l],o=0;o>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function GT(t,e,r,n){return new Function([HT("A","x"+t+"y",e,["y"],!1,n),HT("B","x"+t+"y",e,["y"],!0,n),HT("P","c(x,y)"+t+"0",e,["y","c"],!1,n),HT("Q","c(x,y)"+t+"0",e,["y","c"],!0,n),"function dispatchBsearch",r,"(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",r].join(""))()}var WT={ge:GT(">=",!1,"GE"),gt:GT(">",!1,"GT"),lt:GT("<",!0,"LT"),le:GT("<=",!0,"LE"),eq:GT("-",!0,"EQ",!0)},YT=0,XT=1,ZT=function(t){if(!t||0===t.length)return new uS(null);return new uS(lS(t))};function JT(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}var KT=JT.prototype;function QT(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function $T(t,e){var r=lS(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function tS(t,e){var r=t.intervals([]);r.push(e),$T(t,r)}function eS(t,e){var r=t.intervals([]),n=r.indexOf(e);return n<0?YT:(r.splice(n,1),$T(t,r),XT)}function rS(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function iS(t,e){for(var r=0;r>1],i=[],a=[],o=[];for(r=0;r3*(e+1)?tS(this,t):this.left.insert(t):this.left=lS([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?tS(this,t):this.right.insert(t):this.right=lS([t]);else{var r=WT.ge(this.leftPoints,t,oS),n=WT.ge(this.rightPoints,t,sS);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},KT.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1)?eS(this,t):2===(a=this.left.remove(t))?(this.left=null,this.count-=1,XT):(a===XT&&(this.count-=1),a):YT}else{if(!(t[0]>this.mid)){if(1===this.count)return this.leftPoints[0]===t?2:YT;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var r=this,n=this.left;n.right;)r=n,n=n.right;if(r===this)n.right=this.right;else{var i=this.left;a=this.right;r.count-=n.count,r.right=n.left,n.left=i,n.right=a}QT(this,n),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?QT(this,this.left):QT(this,this.right);return XT}for(i=WT.ge(this.leftPoints,t,oS);i3*(e-1)?eS(this,t):2===(a=this.right.remove(t))?(this.right=null,this.count-=1,XT):(a===XT&&(this.count-=1),a):YT;var a}},KT.queryPoint=function(t,e){if(tthis.mid){var r;if(this.right)if(r=this.right.queryPoint(t,e))return r;return nS(this.rightPoints,t,e)}return iS(this.leftPoints,e)},KT.queryInterval=function(t,e,r){var n;if(tthis.mid&&this.right&&(n=this.right.queryInterval(t,e,r)))return n;return ethis.mid?nS(this.rightPoints,t,r):iS(this.leftPoints,r)};var cS=uS.prototype;cS.insert=function(t){this.root?this.root.insert(t):this.root=new JT(t[0],null,null,[t],[t])},cS.remove=function(t){if(this.root){var e=this.root.remove(t);return 2===e&&(this.root=null),e!==YT}return!1},cS.queryPoint=function(t,e){if(this.root)return this.root.queryPoint(t,e)},cS.queryInterval=function(t,e,r){if(t<=e&&this.root)return this.root.queryInterval(t,e,r)},Object.defineProperty(cS,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(cS,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}});var hS=function(t){return new yS(t||kS,null)},fS=0,pS=1;function dS(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function gS(t){return new dS(t._color,t.key,t.value,t.left,t.right,t._count)}function vS(t,e){return new dS(t,e.key,e.value,e.left,e.right,e._count)}function mS(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function yS(t,e){this._compare=t,this.root=e}var xS=yS.prototype;function bS(t,e){this.tree=t,this._stack=e}Object.defineProperty(xS,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(xS,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(xS,"length",{get:function(){return this.root?this.root._count:0}}),xS.insert=function(t,e){for(var r=this._compare,n=this.root,i=[],a=[];n;){var o=r(t,n.key);i.push(n),a.push(o),n=o<=0?n.left:n.right}i.push(new dS(fS,t,e,null,null,1));for(var s=i.length-2;s>=0;--s){n=i[s];a[s]<=0?i[s]=new dS(n._color,n.key,n.value,i[s+1],n.right,n._count+1):i[s]=new dS(n._color,n.key,n.value,n.left,i[s+1],n._count+1)}for(s=i.length-1;s>1;--s){var l=i[s-1];n=i[s];if(l._color===pS||n._color===pS)break;var u=i[s-2];if(u.left===l)if(l.left===n){if(!(c=u.right)||c._color!==fS){if(u._color=fS,u.left=l.right,l._color=pS,l.right=u,i[s-2]=l,i[s-1]=n,mS(u),mS(l),s>=3)(h=i[s-3]).left===u?h.left=l:h.right=l;break}l._color=pS,u.right=vS(pS,c),u._color=fS,s-=1}else{if(!(c=u.right)||c._color!==fS){if(l.right=n.left,u._color=fS,u.left=n.right,n._color=pS,n.left=l,n.right=u,i[s-2]=n,i[s-1]=l,mS(u),mS(l),mS(n),s>=3)(h=i[s-3]).left===u?h.left=n:h.right=n;break}l._color=pS,u.right=vS(pS,c),u._color=fS,s-=1}else if(l.right===n){if(!(c=u.left)||c._color!==fS){if(u._color=fS,u.right=l.left,l._color=pS,l.left=u,i[s-2]=l,i[s-1]=n,mS(u),mS(l),s>=3)(h=i[s-3]).right===u?h.right=l:h.left=l;break}l._color=pS,u.left=vS(pS,c),u._color=fS,s-=1}else{var c;if(!(c=u.left)||c._color!==fS){var h;if(l.left=n.right,u._color=fS,u.right=n.left,n._color=pS,n.right=l,n.left=u,i[s-2]=n,i[s-1]=l,mS(u),mS(l),mS(n),s>=3)(h=i[s-3]).right===u?h.right=n:h.left=n;break}l._color=pS,u.left=vS(pS,c),u._color=fS,s-=1}}return i[0]._color=pS,new yS(r,i[0])},xS.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return function t(e,r){var n;if(r.left&&(n=t(e,r.left)))return n;return(n=e(r.key,r.value))||(r.right?t(e,r.right):void 0)}(t,this.root);case 2:return function t(e,r,n,i){if(r(e,i.key)<=0){var a;if(i.left&&(a=t(e,r,n,i.left)))return a;if(a=n(i.key,i.value))return a}if(i.right)return t(e,r,n,i.right)}(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return function t(e,r,n,i,a){var o,s=n(e,a.key),l=n(r,a.key);if(s<=0){if(a.left&&(o=t(e,r,n,i,a.left)))return o;if(l>0&&(o=i(a.key,a.value)))return o}if(l>0&&a.right)return t(e,r,n,i,a.right)}(e,r,this._compare,t,this.root)}},Object.defineProperty(xS,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new bS(this,t)}}),Object.defineProperty(xS,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new bS(this,t)}}),xS.at=function(t){if(t<0)return new bS(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new bS(this,[])},xS.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<=0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new bS(this,n)},xS.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a<0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new bS(this,n)},xS.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=a<=0?r.left:r.right}return n.length=i,new bS(this,n)},xS.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=a<0?r.left:r.right}return n.length=i,new bS(this,n)},xS.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new bS(this,n);r=i<=0?r.left:r.right}return new bS(this,[])},xS.remove=function(t){var e=this.find(t);return e?e.remove():this},xS.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=n<=0?r.left:r.right}};var _S=bS.prototype;function wS(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function kS(t,e){return te?1:0}Object.defineProperty(_S,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(_S,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),_S.clone=function(){return new bS(this.tree,this._stack.slice())},_S.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new dS(r._color,r.key,r.value,r.left,r.right,r._count);for(var n=t.length-2;n>=0;--n){(r=t[n]).left===t[n+1]?e[n]=new dS(r._color,r.key,r.value,e[n+1],r.right,r._count):e[n]=new dS(r._color,r.key,r.value,r.left,e[n+1],r._count)}if((r=e[e.length-1]).left&&r.right){var i=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var a=e[i-1];e.push(new dS(r._color,a.key,a.value,r.left,r.right,r._count)),e[i-1].key=r.key,e[i-1].value=r.value;for(n=e.length-2;n>=i;--n)r=e[n],e[n]=new dS(r._color,r.key,r.value,r.left,e[n+1],r._count);e[i-1].left=e[i]}if((r=e[e.length-1])._color===fS){var o=e[e.length-2];o.left===r?o.left=null:o.right===r&&(o.right=null),e.pop();for(n=0;n=0;--a){if(e=t[a],0===a)return void(e._color=pS);if((r=t[a-1]).left===e){if((n=r.right).right&&n.right._color===fS)return i=(n=r.right=gS(n)).right=gS(n.right),r.right=n.left,n.left=r,n.right=i,n._color=r._color,e._color=pS,r._color=pS,i._color=pS,mS(r),mS(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),void(t[a-1]=n);if(n.left&&n.left._color===fS)return i=(n=r.right=gS(n)).left=gS(n.left),r.right=i.left,n.left=i.right,i.left=r,i.right=n,i._color=r._color,r._color=pS,n._color=pS,e._color=pS,mS(r),mS(n),mS(i),a>1&&((o=t[a-2]).left===r?o.left=i:o.right=i),void(t[a-1]=i);if(n._color===pS){if(r._color===fS)return r._color=pS,void(r.right=vS(fS,n));r.right=vS(fS,n);continue}n=gS(n),r.right=n.left,n.left=r,n._color=r._color,r._color=fS,mS(r),mS(n),a>1&&((o=t[a-2]).left===r?o.left=n:o.right=n),t[a-1]=n,t[a]=r,a+11&&((o=t[a-2]).right===r?o.right=n:o.left=n),void(t[a-1]=n);if(n.right&&n.right._color===fS)return i=(n=r.left=gS(n)).right=gS(n.right),r.left=i.right,n.right=i.left,i.right=r,i.left=n,i._color=r._color,r._color=pS,n._color=pS,e._color=pS,mS(r),mS(n),mS(i),a>1&&((o=t[a-2]).right===r?o.right=i:o.left=i),void(t[a-1]=i);if(n._color===pS){if(r._color===fS)return r._color=pS,void(r.left=vS(fS,n));r.left=vS(fS,n);continue}var o;n=gS(n),r.left=n.right,n.right=r,n._color=r._color,r._color=fS,mS(r),mS(n),a>1&&((o=t[a-2]).right===r?o.right=n:o.left=n),t[a-1]=n,t[a]=r,a+10)return this._stack[this._stack.length-1].key},enumerable:!0}),Object.defineProperty(_S,"value",{get:function(){if(this._stack.length>0)return this._stack[this._stack.length-1].value},enumerable:!0}),Object.defineProperty(_S,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),_S.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(_S,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),_S.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),n=e[e.length-1];r[r.length-1]=new dS(n._color,n.key,t,n.left,n.right,n._count);for(var i=e.length-2;i>=0;--i)(n=e[i]).left===e[i+1]?r[i]=new dS(n._color,n.key,n.value,r[i+1],n.right,n._count):r[i]=new dS(n._color,n.key,n.value,n.left,r[i+1],n._count);return new yS(this.tree._compare,r[0])},_S.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(_S,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}});var MS=function(t,e){var r,n,i,a;if(e[0][0]e[1][0]))return AS(e,t);r=e[1],n=e[0]}if(t[0][0]t[1][0]))return-AS(t,e);i=t[1],a=t[0]}var o=rM(r,n,a),s=rM(r,n,i);if(o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;if(o=rM(a,i,n),s=rM(a,i,r),o<0){if(s<=0)return o}else if(o>0){if(s>=0)return o}else if(s)return s;return n[0]-a[0]};function AS(t,e){var r,n,i,a;if(e[0][0]e[1][0])){var o=Math.min(t[0][1],t[1][1]),s=Math.max(t[0][1],t[1][1]),l=Math.min(e[0][1],e[1][1]),u=Math.max(e[0][1],e[1][1]);return su?o-u:s-u}r=e[1],n=e[0]}t[0][1]0)if(e[0]!==a[1][0])r=t,t=t.right;else{if(s=ES(t.right,e))return s;t=t.left}else{if(e[0]!==a[1][0])return t;var s;if(s=ES(t.right,e))return s;t=t.left}}return r}function LS(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function PS(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}SS.prototype.castUp=function(t){var e=WT.le(this.coordinates,t[0]);if(e<0)return-1;this.slabs[e];var r=ES(this.slabs[e],t),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var i=null;if(r&&(i=r.key),e>0){var a=ES(this.slabs[e-1],t);a&&(i?MS(a.key,i)>0&&(i=a.key,n=a.value):(n=a.value,i=a.key))}var o=this.horizontal[e];if(o.length>0){var s=WT.ge(o,t[1],CS);if(s=o.length)return n;l=o[s]}}if(l.start)if(i){var u=rM(i[0],i[1],[t[0],l.y]);i[0][0]>i[1][0]&&(u=-u),u>0&&(n=l.index)}else n=l.index;else l.y!==t[1]&&(n=l.index)}}}return n};var zS=function(t){for(var e=t.length,r=[],n=[],i=0;i0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=DS(r,o[0],o[1]);if(o[0][0]0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(s<0))return 0;a=1,i=i.right}}return a}}(f.slabs,f.coordinates);return 0===n.length?p:function(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}(OS(n),p)},DS=rM[3];function IS(){return!0}function OS(t){for(var e={},r=0;r0})).length,l=new Array(s),u=new Array(s),a=0;a0;){var P=E.pop(),z=_[P];wb(z,function(t,e){return t-e});var D,I=z.length,O=L[P];if(0===O){var g=o[P];D=[g]}for(var a=0;a=0)&&(L[R]=1^O,E.push(R),0===O)){var g=o[R];C(g)||(g.reverse(),D.push(g))}}0===O&&r.push(D)}return r};function FS(t,e){for(var r=new Array(t),n=0;n>1,o=jS(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function GS(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==jS(t[p],a)););}return r}function WS(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return US(e)},NS.skeleton=WS,NS.boundary=function(t){for(var e=[],r=0,n=t.length;r0)-(t<0)},YS.abs=function(t){var e=t>>31;return(t^e)-e},YS.min=function(t,e){return e^(t^e)&-(t65535)<<4,e|=r=((t>>>=e)>255)<<3,e|=r=((t>>>=r)>15)<<2,(e|=r=((t>>>=r)>3)<<1)|(t>>>=r)>>1},YS.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},YS.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},YS.countTrailingZeros=XS,YS.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},YS.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},YS.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var ZS=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|ZS[t>>>16&255]<<8|ZS[t>>>24&255]},YS.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},YS.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},YS.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},YS.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},YS.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>XS(t)+1};var JS=KS;function KS(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;e>1,o=$S(t[a],e);o<=0?(0===o&&(i=a),r=a+1):o>0&&(n=a-1)}return i}function iC(t,e){for(var r=new Array(t.length),n=0,i=r.length;n=t.length||0!==$S(t[p],a)););}return r}function aC(t,e){if(e<0)return[];for(var r=[],n=(1<>>u&1&&l.push(i[u]);e.push(l)}return eC(e)},QS.skeleton=aC,QS.boundary=function(t){for(var e=[],r=0,n=t.length;r>1:(t>>1)-1}function m(t){for(var e=g(t);;){var r=e,n=2*t+1,i=2*(t+1),a=t;if(n0;){var r=v(t);if(r>=0){var n=g(r);if(e0){var t=w[0];return d(0,A-1),A-=1,m(0),t}return-1}function b(t,e){var r=w[t];return s[r]===e?t:(s[r]=-1/0,y(t),x(),s[r]=e,y((A+=1)-1))}function _(t){if(!l[t]){l[t]=!0;var e=a[t],r=o[t];a[r]>=0&&(a[r]=e),o[e]>=0&&(o[e]=r),k[e]>=0&&b(k[e],p(e)),k[r]>=0&&b(k[r],p(r))}}for(var w=[],k=new Array(n),u=0;u>1;u>=0;--u)m(u);for(;;){var T=x();if(T<0||s[T]>r)break;_(T)}for(var S=[],u=0;u=0&&r>=0&&e!==r){var n=k[e],i=k[r];n!==i&&E.push([n,i])}}),QS.unique(QS.normalize(E)),{positions:S,edges:E}};var sC=function(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;n<1&&e("Must have at least one array argument");var i=t.scalarArguments||0;i<0&&e("Scalar arg count must be > 0");"function"!=typeof t.vertex&&e("Must specify vertex creation function");"function"!=typeof t.cell&&e("Must specify cell creation function");"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;s=0?o[s]=!0:o[s]=!1;return function(t,e,r,n,i,a){var o=a.length,s=i.length;if(s<2)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var l="extractContour"+i.join("_"),u=[],c=[],h=[],f=0;f0&&v.push(fC(f,i[p-1])+"*"+hC(i[p-1])),c.push(yC(f,i[p])+"=("+v.join("-")+")|0")}for(var f=0;f=0;--f)m.push(hC(i[f]));c.push(TC+"=("+m.join("*")+")|0",MC+"=mallocUint32("+TC+")",kC+"=mallocUint32("+TC+")",SC+"=0"),c.push(xC(0)+"=0");for(var p=1;p<1<0;v=v-1&p)g.push(kC+"["+SC+"+"+_C(v)+"]");g.push(wC(0));for(var v=0;v=0;--e)w(e,0);for(var r=[],e=0;e0){",mC(i[e]),"=1;");t(e-1,r|1<0;--r)e+=DC[r]/(t+r);var n=t+zC+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}(LC=function t(e){if(e<.5)return Math.PI/(Math.sin(Math.PI*e)*t(1-e));if(e>100)return Math.exp(IC(e));e-=1;for(var r=PC[0],n=1;n<9;n++)r+=PC[n]/(e+n);var i=e+7+.5;return Math.sqrt(2*Math.PI)*Math.pow(i,e+.5)*Math.exp(-i)*r}).log=IC;var OC=function(t){var e=t.length;if(e0;--i)n=o[i],r=a[i],a[i]=a[n],a[n]=r,o[i]=o[r],o[r]=n,s=(s+r)*i;return G_.freeUint32(o),G_.freeUint32(a),s},FC.unrank=function(t,e,r){switch(t){case 0:return r||[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}var n,i,a,o=1;for((r=r||new Array(t))[0]=0,a=1;a0;--a)e=e-(n=e/o|0)*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r};var NC=function(t){if(t<0)return[];if(0===t)return[[0]];for(var e=0|Math.round(LC(t+1)),r=[],n=0;n= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"}),VC=function(t,e){var r=[];return e=+e||0,jC(t.hi(t.shape[0]-1),r,e),r};var UC=function(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return function(t,e){for(var r=VC(t,e),n=r.length,i=new Array(n),a=new Array(n),o=0;o c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],o=[],s=0;s>>7){");for(var s=0;s<1<<(1<128&&s%128==0){u.length>0&&c.push("}}");var h="vExtra"+u.length;n.push("case ",s>>>7,":",h,"(m&0x7f,",o.join(),");break;"),c=["function ",h,"(m,",o.join(),"){switch(m){"],u.push(c)}c.push("case ",127&s,":");for(var f=new Array(r),p=new Array(r),d=new Array(r),g=new Array(r),v=0,m=0;mm)&&!(s&1<0&&(k="+"+d[y]+"*c");var M=f[y].length/v*.5,A=.5+g[y]/v*.5;w.push("d"+y+"-"+A+"-"+M+"*("+f[y].join("+")+k+")/("+p[y].join("+")+")")}c.push("a.push([",w.join(),"]);","break;")}n.push("}},"),u.length>0&&c.push("}}");for(var T=[],s=0;s<1<8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height0&&(c+=.02);for(var f=new Float32Array(u),p=0,d=-.5*c,h=0;hs[k]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=g[n],a.uniforms.angle=v[n],l.drawArrays(l.TRIANGLES,s[k],s[M]-s[k]))),m[n]&&w&&(e[1^n]-=A*f*y[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=b[n],l.drawArrays(l.TRIANGLES,_,w)),e[1^n]=A*u[2+(1^n)]-1,p[n+2]&&(e[1^n]+=A*f*d[n+2],ks[k]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=g[n+2],a.uniforms.angle=v[n+2],l.drawArrays(l.TRIANGLES,s[k],s[M]-s[k]))),m[n+2]&&w&&(e[1^n]+=A*f*y[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=b[n+2],l.drawArrays(l.TRIANGLES,_,w))}}(),$C.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,u=r.pixelRatio;if(this.titleCount){for(var c=0;c<2;++c)e[c]=2*(o[c]*u-a[c])/(a[2+c]-a[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),$C.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var u=0;u<2;++u){var c=a[u],h=a[u+2]-c,f=.5*(o[u+2]+o[u]),p=o[u+2]-o[u],d=l[u],g=l[u+2]-d,v=s[u],m=s[u+2]-v;e[u]=2*h/p*g/m,t[u]=2*(c-f)/p*g/m}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),$C.update=function(t){var e,r,n,i,a,o=[],s=t.ticks,l=t.bounds;for(a=0;a<2;++a){var u=[Math.floor(o.length/3)],c=[-1/0],h=s[a];for(e=0;ei||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var a=cE(n,e.stride.slice()),o=0;"float32"===r?o=t.FLOAT:"float64"===r?(o=t.FLOAT,a=!1,r="float32"):"uint8"===r?o=t.UNSIGNED_BYTE:(o=t.UNSIGNED_BYTE,a=!1,r="uint8");var s,l,u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=Wb(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}o!==t.FLOAT||t.getExtension("OES_texture_float")||(o=t.UNSIGNED_BYTE,a=!1);var c=e.size;if(a)s=0===e.offset&&e.data.length===c?e.data:e.data.subarray(e.offset,e.offset+c);else{var h=[n[2],n[2]*n[0],1];l=G_.malloc(c,r);var f=Wb(l,n,h,0);"float32"!==r&&"float64"!==r||o!==t.UNSIGNED_BYTE?Cb.assign(f,e):oE(f,e),s=l.subarray(0,c)}var p=hE(t);t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,o,s),a||G_.free(l);return new lE(t,p,n[0],n[1],u,o)}(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")},rE=null,nE=null,iE=null;function aE(t){return"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof ImageData&&t instanceof ImageData}var oE=function(t,e){Cb.muls(t,e,255)};function sE(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(e<0||e>i||r<0||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function lE(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}var uE=lE.prototype;function cE(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function hE(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function fE(t,e,r,n,i){var a=t.getParameter(t.MAX_TEXTURE_SIZE);if(e<0||e>a||r<0||r>a)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var o=hE(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new lE(t,o,e,r,n,i)}Object.defineProperties(uE,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&rE.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),nE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&rE.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),nE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=this.gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),iE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),iE.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;e<2;++e)if(iE.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return sE(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return sE(this,t|=0,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t|=0,sE(this,this._shape[0],t),t}}}),uE.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},uE.dispose=function(){this.gl.deleteTexture(this.handle)},uE.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},uE.setPixels=function(t,e,r,n){var i=this.gl;this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0;var a=aE(t)?t:t.raw;if(a){this._mipLevels.indexOf(n)<0?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,a),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,a)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||e<0||r<0)throw new Error("gl-texture2d: Texture dimensions are out of bounds");!function(t,e,r,n,i,a,o,s){var l=s.dtype,u=s.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var c=0,h=0,f=cE(u,s.stride.slice());"float32"===l?c=t.FLOAT:"float64"===l?(c=t.FLOAT,f=!1,l="float32"):"uint8"===l?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,f=!1,l="uint8");if(2===u.length)h=t.LUMINANCE,u=[u[0],u[1],1],s=Wb(s.data,u,[s.stride[0],s.stride[1],1],s.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])h=t.ALPHA;else if(2===u[2])h=t.LUMINANCE_ALPHA;else if(3===u[2])h=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}u[2]}h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i);if(h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var p=s.size,d=o.indexOf(n)<0;d&&o.push(n);if(c===a&&f)0===s.offset&&s.data.length===p?d?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data):d?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,s.data.subarray(s.offset,s.offset+p)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,s.data.subarray(s.offset,s.offset+p));else{var g;g=a===t.FLOAT?G_.mallocFloat32(p):G_.mallocUint8(p);var v=Wb(g,u,[u[2],u[2]*u[0],1]);c===t.FLOAT&&a===t.UNSIGNED_BYTE?oE(v,s):Cb.assign(v,s),d?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,g.subarray(0,p)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,g.subarray(0,p)),a===t.FLOAT?G_.freeFloat32(g):G_.freeUint8(g)}}(i,e,r,n,this.format,this.type,this._mipLevels,t)}};var pE,dE,gE,vE,mE=function(t,e,r,n){pE||(pE=t.FRAMEBUFFER_UNSUPPORTED,dE=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,gE=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,vE=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var i=t.getExtension("WEBGL_draw_buffers");!yE&&i&&function(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);yE=new Array(r+1);for(var n=0;n<=r;++n){for(var i=new Array(r),a=0;aa||r<0||r>a)throw new Error("gl-fbo: Parameters are too large for FBO");var o=1;if("color"in(n=n||{})){if((o=Math.max(0|n.color,0))<0)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(o>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(o>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+o+" draw buffers")}}var s=t.UNSIGNED_BYTE,l=t.getExtension("OES_texture_float");if(n.float&&o>0){if(!l)throw new Error("gl-fbo: Context does not support floating point textures");s=t.FLOAT}else n.preferFloat&&o>0&&l&&(s=t.FLOAT);var u=!0;"depth"in n&&(u=!!n.depth);var c=!1;"stencil"in n&&(c=!!n.stencil);return new ME(t,e,r,s,o,u,c,i)},yE=null;function xE(t){return[t.getParameter(t.FRAMEBUFFER_BINDING),t.getParameter(t.RENDERBUFFER_BINDING),t.getParameter(t.TEXTURE_BINDING_2D)]}function bE(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function _E(t){switch(t){case pE:throw new Error("gl-fbo: Framebuffer unsupported");case dE:throw new Error("gl-fbo: Framebuffer incomplete attachment");case gE:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case vE:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function wE(t,e,r,n,i,a){if(!n)return null;var o=eE(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function kE(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function ME(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var l=0;l1&&s.drawBuffersWEBGL(yE[o]);var f=r.getExtension("WEBGL_depth_texture");f?l?t.depth=wE(r,i,a,f.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u&&(t.depth=wE(r,i,a,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):u&&l?t._depth_rb=kE(r,i,a,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):u?t._depth_rb=kE(r,i,a,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):l&&(t._depth_rb=kE(r,i,a,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var p=r.checkFramebufferStatus(r.FRAMEBUFFER);if(p!==r.FRAMEBUFFER_COMPLETE){for(t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null),h=0;hi||r<0||r>i)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var a=xE(n),o=0;othis.buffer.length){G_.free(this.buffer);for(var n=this.buffer=G_.mallocUint8(CE(r*e*4)),i=0;i=0){var g=e[d]-n[d]*(e[d+2]-e[d])/(n[d+2]-n[d]);0===d?o.drawLine(g,e[1],g,e[3],p[d],f[d]):o.drawLine(e[0],g,e[2],g,p[d],f[d])}}for(d=0;d=0;--t)this.objects[t].dispose();this.objects.length=0;for(t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},IE.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},IE.removeObject=function(t){for(var e=this.objects,r=0;r0){var m=r*c;o.drawBox(h-m,f-m,p+m,f+m,a),o.drawBox(h-m,d-m,p+m,d+m,a),o.drawBox(h-m,f-m,h+m,d+m,a),o.drawBox(p-m,f-m,p+m,d+m,a)}}}},jE.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},jE.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)};var VE=function(t,e){var r=new UE(t);return r.update(e),t.addOverlay(r),r};function UE(t){this.plot=t,this.enable=[!0,!0,!1,!1],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=[1/0,1/0]}var qE=UE.prototype;qE.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},qE.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),u=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,u,s[0],u,e[0],r[0]),t[1]&&a.drawLine(l,u,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,u,s[2],u,e[2],r[2]),t[3]&&a.drawLine(l,u,l,s[3],e[3],r[3])}},qE.dispose=function(){this.plot.removeOverlay(this)};var HE=function(t,e){if("string"!=typeof t)throw new TypeError("must specify type string");if(e=e||{},"undefined"==typeof document&&!e.canvas)return null;var r=e.canvas||document.createElement("canvas");"number"==typeof e.width&&(r.width=e.width);"number"==typeof e.height&&(r.height=e.height);var n,i=e;try{var a=[t];0===t.indexOf("webgl")&&a.push("experimental-"+t);for(var o=0;o=0;){var n=t.indexOf(";",r);if(n/g,"")}(function(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(r/g,"\n"))))},ZE=function(){},JE=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=ZE);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=Fe.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1},KE={};function QE(t){return t.target||t.srcElement||window}KE.buttons=function(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){if(2===(e=t.which))return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1<Math.abs(l)?(n.boxEnd[1]=n.boxStart[1]+Math.abs(s)*b*(l>=0?1:-1),n.boxEnd[1]u[3]&&(n.boxEnd[1]=u[3],n.boxEnd[0]=n.boxStart[0]+(u[3]-n.boxStart[1])/Math.abs(b))):(n.boxEnd[0]=n.boxStart[0]+Math.abs(l)/b*(s>=0?1:-1),n.boxEnd[0]u[2]&&(n.boxEnd[0]=u[2],n.boxEnd[1]=n.boxStart[1]+(u[2]-n.boxStart[0])*Math.abs(b)))}}else n.boxEnabled?(s=n.boxStart[0]!==n.boxEnd[0],l=n.boxStart[1]!==n.boxEnd[1],s||l?(s&&(g(0,n.boxStart[0],n.boxEnd[0]),t.xaxis.autorange=!1),l&&(g(1,n.boxStart[1],n.boxEnd[1]),t.yaxis.autorange=!1),t.relayoutCallback()):t.glplot.setDirty(),n.boxEnabled=!1,n.boxInited=!1):n.boxInited&&(n.boxInited=!1);break;case"pan":n.boxEnabled=!1,n.boxInited=!1,e?(n.panning||(n.dragStart[0]=a,n.dragStart[1]=o),Math.abs(n.dragStart[0]-a)r?r:t:te?e:t};var lL={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]},uL=function(){for(var t=0;t10&&/[0-9](?:\s|\/)/.test(r)&&(a=r.match(/([0-9]+)/g).map(function(t){return parseFloat(t)}),i=r.match(/([a-z])/gi).join("").toLowerCase());else if("number"==typeof r)i="rgb",a=[r>>>16,(65280&r)>>>8,255&r];else if(hL(r)){var h=uL(r.r,r.red,r.R,null);null!==h?(i="rgb",a=[h,uL(r.g,r.green,r.G),uL(r.b,r.blue,r.B)]):(i="hsl",a=[uL(r.h,r.hue,r.H),uL(r.s,r.saturation,r.S),uL(r.l,r.lightness,r.L,r.b,r.brightness)]),o=uL(r.a,r.alpha,r.opacity,1),null!=r.opacity&&(o/=100)}else(Array.isArray(r)||t.ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(r))&&(a=[r[0],r[1],r[2]],i="rgb",o=4===r.length?r[3]:1);return{space:i,values:a,alpha:o}};var e={red:0,orange:60,yellow:120,green:180,blue:240,purple:300}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var pL=function(t){var e,r,n,i,a,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[a=255*l,a,a];e=2*l-(r=l<.5?l*(1+s):l+s-l*s),i=[0,0,0];for(var u=0;u<3;u++)(n=o+1/3*-(u-1))<0?n++:n>1&&n--,a=6*n<1?e+6*(r-e)*n:2*n<1?r:3*n<2?e+(r-e)*(2/3-n)*6:e,i[u]=255*a;return i},dL=function(t){switch(t){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}},gL=function(t,e){"float"!==e&&e||(e="array"),"uint"===e&&(e="uint8"),"uint_clamped"===e&&(e="uint8_clamped");var r=dL(e),n=new r(4);if(t instanceof r)return Array.isArray(t)?t.slice():(n.set(t),n);var i="uint8"!==e&&"uint8_clamped"!==e;return t instanceof Uint8Array||t instanceof Uint8ClampedArray?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:255,i&&(n[0]/=255,n[1]/=255,n[2]/=255,n[3]/=255),n):(t.length&&"string"!=typeof t||((t=function(t){var e;if("string"!=typeof t)throw Error("Argument should be a string");var r=fL(t);return r.space?((e=Array(3))[0]=sL(r.values[0],0,255),e[1]=sL(r.values[1],0,255),e[2]=sL(r.values[2],0,255),"h"===r.space[0]&&(e=pL(e)),e.push(sL(r.alpha,0,1)),e):[]}(t))[0]/=255,t[1]/=255,t[2]/=255),i?(n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=null!=t[3]?t[3]:1):(n[0]=sL(Math.round(255*t[0]),0,255),n[1]=sL(Math.round(255*t[1]),0,255),n[2]=sL(Math.round(255*t[2]),0,255),n[3]=null==t[3]?255:sL(Math.floor(255*t[3]),0,255)),n)};var vL=function(t){return t?gL(t):[0,0,0,1]};function mL(t){this.scene=t,this.gl=t.gl,this.pixelRatio=t.pixelRatio,this.screenBox=[0,0,1,1],this.viewBox=[0,0,1,1],this.dataBox=[-1,-1,1,1],this.borderLineEnable=[!1,!1,!1,!1],this.borderLineWidth=[1,1,1,1],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.ticks=[[],[]],this.tickEnable=[!0,!0,!1,!1],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labels=["x","y"],this.labelEnable=[!0,!0,!1,!1],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelPad=[15,15,15,15],this.labelSize=[12,12],this.labelFont=["sans-serif","sans-serif"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.title="",this.titleEnable=!0,this.titleCenter=[0,0,0,0],this.titleAngle=0,this.titleColor=[0,0,0,1],this.titleFont="sans-serif",this.titleSize=18,this.gridLineEnable=[!0,!0],this.gridLineColor=[[0,0,0,.5],[0,0,0,.5]],this.gridLineWidth=[1,1],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[1,1],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderColor=!1,this.backgroundColor=[0,0,0,0],this.static=this.scene.staticPlot}var yL=mL.prototype,xL=["xaxis","yaxis"];yL.merge=function(t){var e,r,n,i,a,o,s,l,u,c,h;for(this.titleEnable=!1,this.backgroundColor=vL(t.plot_bgcolor),c=0;c<2;++c){var f=(e=xL[c]).charAt(0);for(n=(r=t[this.scene[e]._name]).title===this.scene.fullLayout._dfltTitle[f]?"":r.title,h=0;h<=2;h+=2)this.labelEnable[c+h]=!1,this.labels[c+h]=XE(n),this.labelColor[c+h]=vL(r.titlefont.color),this.labelFont[c+h]=r.titlefont.family,this.labelSize[c+h]=r.titlefont.size,this.labelPad[c+h]=this.getLabelPad(e,r),this.tickEnable[c+h]=!1,this.tickColor[c+h]=vL((r.tickfont||{}).color),this.tickAngle[c+h]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[c+h]=this.getTickPad(r),this.tickMarkLength[c+h]=0,this.tickMarkWidth[c+h]=r.tickwidth||0,this.tickMarkColor[c+h]=vL(r.tickcolor),this.borderLineEnable[c+h]=!1,this.borderLineColor[c+h]=vL(r.linecolor),this.borderLineWidth[c+h]=r.linewidth||0;s=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!s,o=this.hasAxisInAltrPos(e,r)&&!s,i=r.mirror||!1,l=s?-1!==String(i).indexOf("all"):!!i,u=s?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[c]=!0:o&&(this.labelEnable[c+2]=!0),a?this.tickEnable[c]=r.showticklabels:o&&(this.tickEnable[c+2]=r.showticklabels),(a||l)&&(this.borderLineEnable[c]=r.showline),(o||l)&&(this.borderLineEnable[c+2]=r.showline),(a||u)&&(this.tickMarkLength[c]=this.getTickMarkLength(r)),(o||u)&&(this.tickMarkLength[c+2]=this.getTickMarkLength(r)),this.gridLineEnable[c]=r.showgrid,this.gridLineColor[c]=vL(r.gridcolor),this.gridLineWidth[c]=r.gridwidth,this.zeroLineEnable[c]=r.zeroline,this.zeroLineColor[c]=vL(r.zerolinecolor),this.zeroLineWidth[c]=r.zerolinewidth}},yL.hasSharedAxis=function(t){var e=this.scene,r=e.fullLayout._subplots.gl2d;return 0!==ui.findSubplotsWithAxis(r,t).indexOf(e.id)},yL.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},yL.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},yL.getLabelPad=function(t,e){var r=e.titlefont.size,n=e.showticklabels;return"xaxis"===t?"top"===e.side?r*(1.5+(n?1:0))-10:r*(1.5+(n?.5:0))-10:"yaxis"===t?"right"===e.side?10+r*(1.5+(n?1:.5)):10+r*(1.5+(n?.5:0)):void 0},yL.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},yL.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e};var bL,_L,wL=function(t){return new mL(t)},kL=uy.enforce,ML=uy.clean,AL=Wn,TL=["xaxis","yaxis"],SL=Ee.SUBPLOT_PATTERN;function CL(t,e){this.container=t.container,this.graphDiv=t.graphDiv,this.pixelRatio=t.plotGlPixelRatio||window.devicePixelRatio,this.id=t.id,this.staticPlot=!!t.staticPlot,this.scrollZoom=this.graphDiv._context.scrollZoom,this.fullData=null,this.updateRefs(e),this.makeFramework(),this.glplotOptions=wL(this),this.glplotOptions.merge(e),this.glplot=zE(this.glplotOptions),this.camera=oL(this),this.traces={},this.spikes=VE(this.glplot),this.selectBox=FE(this.glplot,{innerFill:!1,outerFill:!0}),this.lastButtonState=0,this.pickResult=null,this.isMouseOver=!0,this.stopped=!1,this.redraw=this.draw.bind(this),this.redraw()}var EL=CL,LL=CL.prototype;LL.makeFramework=function(){if(this.staticPlot){if(!(_L||(bL=document.createElement("canvas"),_L=GE({canvas:bL,preserveDrawingBuffer:!1,premultipliedAlpha:!0,antialias:!0}))))throw new Error("Error creating static canvas/context for image server");this.canvas=bL,this.gl=_L}else{var t=this.container.querySelector(".gl-canvas-focus"),e=GE({canvas:t,preserveDrawingBuffer:!0,premultipliedAlpha:!0});e||JE(this),this.canvas=t,this.gl=e}var r=this.canvas;r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style["pointer-events"]="none",this.updateSize(r),r.className+=" user-select-none";var n=this.svgContainer=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.position="absolute",n.style.top=n.style.left="0px",n.style.width=n.style.height="100%",n.style["z-index"]=20,n.style["pointer-events"]="none";var i=this.mouseContainer=document.createElement("div");i.style.position="absolute",i.style["pointer-events"]="auto",this.pickCanvas=this.container.querySelector(".gl-canvas-pick");var a=this.container;a.appendChild(n),a.appendChild(i);var o=this;i.addEventListener("mouseout",function(){o.isMouseOver=!1,o.unhover()}),i.addEventListener("mouseover",function(){o.isMouseOver=!0})},LL.toImage=function(t){t||(t="png"),this.stopped=!0,this.staticPlot&&this.container.appendChild(bL),this.updateSize(this.canvas);var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.clearColor(1,1,1,0),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),this.glplot.setDirty(),this.glplot.draw(),e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;a>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function qL(t,e,r,n){return new Function([UL("A","x"+t+"y",e,["y"],n),UL("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var HL={ge:qL(">=",!1,"GE"),gt:qL(">",!1,"GT"),lt:qL("<",!0,"LT"),le:qL("<=",!0,"LE"),eq:qL("-",!0,"EQ",!0)},GL=function(t,e){var r=t.gl,n=lk(r,VL.vertex,VL.fragment),i=lk(r,VL.pickVertex,VL.pickFragment),a=K_(r),o=K_(r),s=K_(r),l=K_(r),u=new WL(t,n,i,a,o,s,l);return u.update(e),t.addObject(u),u};function WL(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.weightBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.xData=[],this.yData=[],this.shape=[0,0],this.bounds=[1/0,1/0,-1/0,-1/0],this.pickOffset=0}var YL,XL=WL.prototype,ZL=[0,0,1,0,0,1,1,0,1,1,0,1];function JL(t,e){this.scene=t,this.uid=e,this.type="heatmapgl",this.name="",this.hoverinfo="all",this.xData=[],this.yData=[],this.zData=[],this.textLabels=[],this.idToIndex=[],this.bounds=[0,0,0,0],this.options={z:[],x:[],y:[],shape:[0,0],colorLevels:[0],colorValues:[0,0,0,1]},this.heatmap=GL(t.glplot,this.options),this.heatmap._trace=this}XL.draw=(YL=[1,0,0,0,1,0,0,0,1],function(){var t=this.plot,e=this.shader,r=this.bounds,n=this.numVertices;if(!(n<=0)){var i=t.gl,a=t.dataBox,o=r[2]-r[0],s=r[3]-r[1],l=a[2]-a[0],u=a[3]-a[1];YL[0]=2*o/l,YL[4]=2*s/u,YL[6]=2*(r[0]-a[0])/l-1,YL[7]=2*(r[1]-a[1])/u-1,e.bind();var c=e.uniforms;c.viewTransform=YL,c.shape=this.shape;var h=e.attributes;this.positionBuffer.bind(),h.position.pointer(),this.weightBuffer.bind(),h.weight.pointer(i.UNSIGNED_BYTE,!1),this.colorBuffer.bind(),h.color.pointer(i.UNSIGNED_BYTE,!0),i.drawArrays(i.TRIANGLES,0,n)}}),XL.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.bounds,o=this.numVertices;if(!(o<=0)){var s=n.gl,l=n.dataBox,u=a[2]-a[0],c=a[3]-a[1],h=l[2]-l[0],f=l[3]-l[1];t[0]=2*u/h,t[4]=2*c/f,t[6]=2*(a[0]-l[0])/h-1,t[7]=2*(a[1]-l[1])/f-1;for(var p=0;p<4;++p)e[p]=r>>8*p&255;this.pickOffset=r,i.bind();var d=i.uniforms;d.viewTransform=t,d.pickOffset=e,d.shape=this.shape;var g=i.attributes;return this.positionBuffer.bind(),g.position.pointer(),this.weightBuffer.bind(),g.weight.pointer(s.UNSIGNED_BYTE,!1),this.idBuffer.bind(),g.pickId.pointer(s.UNSIGNED_BYTE,!1),s.drawArrays(s.TRIANGLES,0,o),r+this.shape[0]*this.shape[1]}}}(),XL.pick=function(t,e,r){var n=this.pickOffset,i=this.shape[0]*this.shape[1];if(r=n+i)return null;var a=r-n,o=this.xData,s=this.yData;return{object:this,pointId:a,dataCoord:[o[a%this.shape[0]],s[a/this.shape[0]|0]]}},XL.update=function(t){var e=(t=t||{}).shape||[0,0],r=t.x||Fb(e[0]),n=t.y||Fb(e[1]),i=t.z||new Float32Array(e[0]*e[1]);this.xData=r,this.yData=n;var a=t.colorLevels||[0],o=t.colorValues||[0,0,0,1],s=a.length,l=this.bounds,u=l[0]=r[0],c=l[1]=n[0],h=1/((l[2]=r[r.length-1])-u),f=1/((l[3]=n[n.length-1])-c),p=e[0],d=e[1];this.shape=[p,d];var g=(p-1)*(d-1)*(ZL.length>>>1);this.numVertices=g;for(var v=G_.mallocUint8(4*g),m=G_.mallocFloat32(2*g),y=G_.mallocUint8(2*g),x=G_.mallocUint32(g),b=0,_=0;_u.size/1.9?u.size:u.size/Math.ceil(u.size/g);var _=u.start+(u.size-g)/2;v=_-g*Math.ceil((_-v)/g)}for(o=0;o=0&&p=0;n--)s(n);else if("increasing"===e){for(n=1;n=0;n--)t[n]+=t[n+1];"exclude"===r&&(t.push(0),t.shift())}}(i,c.direction,c.currentbin);var j=Math.min(n.length,i.length),V=[],U=0,q=j-1;for(r=0;r=U;r--)if(i[r]){q=r;break}for(r=U;r<=q;r++)if(a(n[r])&&a(i[r])){var H={p:n[r],s:i[r],b:0};c.enabled||(H.pts=w[r],O?H.p0=H.p1=w[r].length?v[w[r][0]]:n[r]:(H.p0=D(y[r]),H.p1=D(y[r+1],!0))),V.push(H)}return 1===V.length&&(V[0].width1=ui.tickIncrement(V[0].p,g.size,!1,u)-V[0].p),ws(V,e),oe.isArrayOrTypedArray(e.selectedpoints)&&oe.tagSelected(V,e,F),V}},fP.setPositions=tl,fP.plot=qs,fP.style=fl,fP.colorbar=yl,fP.hoverPoints=function(t,e,r,n){var i=Is(t,e,r,n);if(i){var a=(t=i[0]).cd[t.index],o=t.cd[0].trace;if(!o.cumulative.enabled){var s="h"===o.orientation?"y":"x";t[s+"Label"]=hP(t[s+"a"],a.p0,a.p1)}return i}},fP.selectPoints=Xs,fP.eventData=cP,fP.moduleType="trace",fP.name="histogram",fP.basePlotModule=ps,fP.categories=["cartesian","svg","bar","histogram","oriented","errorBarsOK","showLegend"],fP.meta={};var pP=fP,dP=b.extendFlat,gP=dP({},{x:eP.x,y:eP.y,z:{valType:"data_array",editType:"calc"},marker:{color:{valType:"data_array",editType:"calc"},editType:"calc"},histnorm:eP.histnorm,histfunc:eP.histfunc,autobinx:eP.autobinx,nbinsx:eP.nbinsx,xbins:eP.xbins,autobiny:eP.autobiny,nbinsy:eP.nbinsy,ybins:eP.ybins,xgap:bf.xgap,ygap:bf.ygap,zsmooth:bf.zsmooth,zhoverformat:bf.zhoverformat},Oe,{autocolorscale:dP({},Oe.autocolorscale,{dflt:!1})},{colorbar:Ie}),vP=function(t,e,r,n){var i=r("x"),a=r("y");if(i&&i.length&&a&&a.length){O.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],n),(r("z")||r("marker.color"))&&r("histfunc");uP(0,e,r,["x","y"])}else e.visible=!1},mP=ui.hoverLabelText,yP={};yP.attributes=gP,yP.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,gP,r,n)}vP(t,e,i,n),!1!==e.visible&&(yb(0,0,i),Je(t,e,n,i,{prefix:"",cLetter:"z"}))},yP.calc=up,yP.plot=Up,yP.colorbar=gf,yP.style=Qp,yP.hoverPoints=function(t,e,r,n,i,a){var o=Ap(t,e,r,0,0,a);if(o){var s=(t=o[0]).index,l=s[0],u=s[1],c=t.cd[0],h=c.xRanges[u],f=c.yRanges[l];return t.xLabel=mP(t.xa,h[0],h[1]),t.yLabel=mP(t.ya,f[0],f[1]),o}},yP.eventData=cP,yP.moduleType="trace",yP.name="histogram2d",yP.basePlotModule=ps,yP.categories=["cartesian","svg","2dMap","histogram"],yP.meta={};var xP=yP,bP=b.extendFlat,_P=bP({x:gP.x,y:gP.y,z:gP.z,marker:gP.marker,histnorm:gP.histnorm,histfunc:gP.histfunc,autobinx:gP.autobinx,nbinsx:gP.nbinsx,xbins:gP.xbins,autobiny:gP.autobiny,nbinsy:gP.nbinsy,ybins:gP.ybins,autocontour:Tf.autocontour,ncontours:Tf.ncontours,contours:Tf.contours,line:Tf.line,zhoverformat:gP.zhoverformat},Oe,{zmin:bP({},Oe.zmin,{editType:"calc"}),zmax:bP({},Oe.zmax,{editType:"calc"})},{colorbar:Ie}),wP={};wP.attributes=_P,wP.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,_P,r,n)}vP(t,e,i,n),!1!==e.visible&&(bp(0,e,i,function(r){return oe.coerce2(t,e,_P,r)}),_p(t,e,i,n))},wP.calc=cp,wP.plot=Yp.plot,wP.style=$p,wP.colorbar=pp,wP.hoverPoints=Tp,wP.moduleType="trace",wP.name="histogram2dcontour",wP.basePlotModule=ps,wP.categories=["cartesian","svg","2dMap","contour","histogram"],wP.meta={};var kP=wP,MP=b.extendFlat,AP=(0,_e.overrideAll)({visible:ze.visible,showspikes:{valType:"boolean",dflt:!0},spikesides:{valType:"boolean",dflt:!0},spikethickness:{valType:"number",min:0,dflt:2},spikecolor:{valType:"color",dflt:Fe.defaultLine},showbackground:{valType:"boolean",dflt:!1},backgroundcolor:{valType:"color",dflt:"rgba(204, 204, 204, 0.5)"},showaxeslabels:{valType:"boolean",dflt:!0},color:ze.color,categoryorder:ze.categoryorder,categoryarray:ze.categoryarray,title:ze.title,titlefont:ze.titlefont,type:ze.type,autorange:ze.autorange,rangemode:ze.rangemode,range:ze.range,tickmode:ze.tickmode,nticks:ze.nticks,tick0:ze.tick0,dtick:ze.dtick,tickvals:ze.tickvals,ticktext:ze.ticktext,ticks:ze.ticks,mirror:ze.mirror,ticklen:ze.ticklen,tickwidth:ze.tickwidth,tickcolor:ze.tickcolor,showticklabels:ze.showticklabels,tickfont:ze.tickfont,tickangle:ze.tickangle,tickprefix:ze.tickprefix,showtickprefix:ze.showtickprefix,ticksuffix:ze.ticksuffix,showticksuffix:ze.showticksuffix,showexponent:ze.showexponent,exponentformat:ze.exponentformat,separatethousands:ze.separatethousands,tickformat:ze.tickformat,tickformatstops:ze.tickformatstops,hoverformat:ze.hoverformat,showline:ze.showline,linecolor:ze.linecolor,linewidth:ze.linewidth,showgrid:ze.showgrid,gridcolor:MP({},ze.gridcolor,{dflt:"rgb(204, 204, 204)"}),gridwidth:ze.gridwidth,zeroline:ze.zeroline,zerolinecolor:ze.zerolinecolor,zerolinewidth:ze.zerolinewidth},"plot","from-root"),TP=c.mix,SP=["xaxis","yaxis","zaxis"],CP=function(t,e,r){var n,i;function a(t,e){return oe.coerce(n,i,AP,t,e)}for(var o=0;o0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a);return t};var qP=function(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],h=t[10],f=t[11],p=t[12],d=t[13],g=t[14],v=t[15];return(e*o-r*a)*(h*v-f*g)-(e*s-n*a)*(c*v-f*d)+(e*l-i*a)*(c*g-h*d)+(r*s-n*o)*(u*v-f*p)-(r*l-i*o)*(u*g-h*p)+(n*l-i*s)*(u*d-c*p)};var HP=function(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t};var GP=function(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e};var WP=function(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t};var YP=function(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t};var XP=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t};var ZP=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]};var JP={length:function(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)},normalize:UP,dot:ZP,cross:XP},KP=WP(),QP=WP(),$P=[0,0,0,0],tz=[[0,0,0],[0,0,0],[0,0,0]],ez=[0,0,0],rz=function(t,e,r,n,i,a){if(e||(e=[0,0,0]),r||(r=[0,0,0]),n||(n=[0,0,0]),i||(i=[0,0,0,1]),a||(a=[0,0,0,1]),!function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;i<16;i++)t[i]=e[i]*n;return!0}(KP,t))return!1;if(GP(QP,KP),QP[3]=0,QP[7]=0,QP[11]=0,QP[15]=1,Math.abs(qP(QP)<1e-8))return!1;var o,s,l,u,c,h,f,p=KP[3],d=KP[7],g=KP[11],v=KP[12],m=KP[13],y=KP[14],x=KP[15];if(0!==p||0!==d||0!==g){if($P[0]=p,$P[1]=d,$P[2]=g,$P[3]=x,!IP(QP,QP))return!1;YP(QP,QP),o=i,l=QP,u=(s=$P)[0],c=s[1],h=s[2],f=s[3],o[0]=l[0]*u+l[4]*c+l[8]*h+l[12]*f,o[1]=l[1]*u+l[5]*c+l[9]*h+l[13]*f,o[2]=l[2]*u+l[6]*c+l[10]*h+l[14]*f,o[3]=l[3]*u+l[7]*c+l[11]*h+l[15]*f}else i[0]=i[1]=i[2]=0,i[3]=1;if(e[0]=v,e[1]=m,e[2]=y,function(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}(tz,KP),r[0]=JP.length(tz[0]),JP.normalize(tz[0],tz[0]),n[0]=JP.dot(tz[0],tz[1]),nz(tz[1],tz[1],tz[0],1,-n[0]),r[1]=JP.length(tz[1]),JP.normalize(tz[1],tz[1]),n[0]/=r[1],n[1]=JP.dot(tz[0],tz[2]),nz(tz[2],tz[2],tz[0],1,-n[1]),n[2]=JP.dot(tz[1],tz[2]),nz(tz[2],tz[2],tz[1],1,-n[2]),r[2]=JP.length(tz[2]),JP.normalize(tz[2],tz[2]),n[1]/=r[2],n[2]/=r[2],JP.cross(ez,tz[1],tz[2]),JP.dot(tz[0],ez)<0)for(var b=0;b<3;b++)r[b]*=-1,tz[b][0]*=-1,tz[b][1]*=-1,tz[b][2]*=-1;return a[0]=.5*Math.sqrt(Math.max(1+tz[0][0]-tz[1][1]-tz[2][2],0)),a[1]=.5*Math.sqrt(Math.max(1-tz[0][0]+tz[1][1]-tz[2][2],0)),a[2]=.5*Math.sqrt(Math.max(1-tz[0][0]-tz[1][1]+tz[2][2],0)),a[3]=.5*Math.sqrt(Math.max(1+tz[0][0]+tz[1][1]+tz[2][2],0)),tz[2][1]>tz[1][2]&&(a[0]=-a[0]),tz[0][2]>tz[2][0]&&(a[1]=-a[1]),tz[1][0]>tz[0][1]&&(a[2]=-a[2]),!0};function nz(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var iz=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],p=e[10],d=e[11],g=e[12],v=e[13],m=e[14],y=e[15],x=r[0],b=r[1],_=r[2],w=r[3];return t[0]=x*n+b*s+_*h+w*g,t[1]=x*i+b*l+_*f+w*v,t[2]=x*a+b*u+_*p+w*m,t[3]=x*o+b*c+_*d+w*y,x=r[4],b=r[5],_=r[6],w=r[7],t[4]=x*n+b*s+_*h+w*g,t[5]=x*i+b*l+_*f+w*v,t[6]=x*a+b*u+_*p+w*m,t[7]=x*o+b*c+_*d+w*y,x=r[8],b=r[9],_=r[10],w=r[11],t[8]=x*n+b*s+_*h+w*g,t[9]=x*i+b*l+_*f+w*v,t[10]=x*a+b*u+_*p+w*m,t[11]=x*o+b*c+_*d+w*y,x=r[12],b=r[13],_=r[14],w=r[15],t[12]=x*n+b*s+_*h+w*g,t[13]=x*i+b*l+_*f+w*v,t[14]=x*a+b*u+_*p+w*m,t[15]=x*o+b*c+_*d+w*y,t};var az={identity:OP,translate:VP,multiply:iz,create:WP,scale:jP,fromRotationTranslation:function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,h=n*l,f=n*u,p=i*l,d=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(p+g),t[1]=h+y,t[2]=f-m,t[3]=0,t[4]=h-y,t[5]=1-(c+g),t[6]=d+v,t[7]=0,t[8]=f+m,t[9]=d-v,t[10]=1-(c+p),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}},oz=(az.create(),az.create()),sz=function(t,e,r,n,i,a){return az.identity(t),az.fromRotationTranslation(t,a,e),t[3]=i[0],t[7]=i[1],t[11]=i[2],t[15]=i[3],az.identity(oz),0!==n[2]&&(oz[9]=n[2],az.multiply(t,t,oz)),0!==n[1]&&(oz[9]=0,oz[8]=n[1],az.multiply(t,t,oz)),0!==n[0]&&(oz[8]=0,oz[4]=n[0],az.multiply(t,t,oz)),az.scale(t,t,r),t};var lz=function(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],h=e[2],f=e[3],p=r[0],d=r[1],g=r[2],v=r[3];(a=u*p+c*d+h*g+f*v)<0&&(a=-a,p=-p,d=-d,g=-g,v=-v);1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n);return t[0]=s*u+l*p,t[1]=s*c+l*d,t[2]=s*h+l*g,t[3]=s*f+l*v,t},uz=pz(),cz=pz(),hz=pz(),fz=function(t,e,r,n){if(0===qP(e)||0===qP(r))return!1;var i=rz(e,uz.translate,uz.scale,uz.skew,uz.perspective,uz.quaternion),a=rz(r,cz.translate,cz.scale,cz.skew,cz.perspective,cz.quaternion);return!(!i||!a||(HP(hz.translate,uz.translate,cz.translate,n),HP(hz.skew,uz.skew,cz.skew,n),HP(hz.scale,uz.scale,cz.scale,n),HP(hz.perspective,uz.perspective,cz.perspective,n),lz(hz.quaternion,uz.quaternion,cz.quaternion,n),sz(t,hz.translate,hz.scale,hz.skew,hz.perspective,hz.quaternion),0))};function pz(){return{translate:dz(),scale:dz(1),skew:dz(),perspective:[0,0,0,1],quaternion:[0,0,0,1]}}function dz(t){return[t||0,t||0,t||0]}var gz=[0,0,0],vz=function(t){return new mz((t=t||{}).matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])};function mz(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-1/0,1/0]}var yz=mz.prototype;yz.recalcMatrix=function(t){var e=this._time,r=WT.le(e,t),n=this.computedMatrix;if(!(r<0)){var i=this._components;if(r===e.length-1)for(var a=16*r,o=0;o<16;++o)n[o]=i[a++];else{var s=e[r+1]-e[r],l=(a=16*r,this.prevMatrix),u=!0;for(o=0;o<16;++o)l[o]=i[a++];var c=this.nextMatrix;for(o=0;o<16;++o)c[o]=i[a++],u=u&&l[o]===c[o];if(s<1e-6||u)for(o=0;o<16;++o)n[o]=l[o];else fz(n,l,c,(t-e[r])/s)}var h=this.computedUp;h[0]=n[1],h[1]=n[5],h[2]=n[9],UP(h,h);var f=this.computedInverse;IP(f,n);var p=this.computedEye,d=f[15];p[0]=f[12]/d,p[1]=f[13]/d,p[2]=f[14]/d;var g=this.computedCenter,v=Math.exp(this.computedRadius[0]);for(o=0;o<3;++o)g[o]=p[o]-n[2+4*o]*v}},yz.idle=function(t){if(!(t=0;--p)a[p]=u*t[p]+c*e[p]+h*r[p]+f*n[p];return a}return u*t+c*e+h*r+f*n}).derivative=function(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n};var _z=function(t,e,r){switch(arguments.length){case 0:return new kz([0],[0],0);case 1:if("number"==typeof t){var n=Az(t);return new kz(n,n,0)}return new kz(t,Az(t.length),0);case 2:if("number"==typeof e){var n=Az(t.length);return new kz(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new kz(t,e,r)}};function wz(t,e,r){return Math.min(e,Math.max(t,r))}function kz(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n=r-1){u=a.length-1;var h=t-e[r-1];for(c=0;c=r-1)for(var l=a.length-1,u=(e[r-1],0);u=0;--r)if(t[--e])return!1;return!0},Mz.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(t0;--c)n.push(wz(s[c-1],l[c-1],arguments[c])),i.push(0)}},Mz.push=function(t){var e=this.lastT(),r=this.dimension;if(!(t1e-6?1/o:0;this._time.push(t);for(var h=r;h>0;--h){var f=wz(l[h-1],u[h-1],arguments[h]);n.push(f),i.push((f-n[a++])*c)}}},Mz.set=function(t){var e=this.dimension;if(!(t0;--s)r.push(wz(a[s-1],o[s-1],arguments[s])),n.push(0)}},Mz.move=function(t){var e=this.lastT(),r=this.dimension;if(!(t<=e||arguments.length!==r+1)){var n=this._state,i=this._velocity,a=n.length-this.dimension,o=this.bounds,s=o[0],l=o[1],u=t-e,c=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var f=arguments[h];n.push(wz(s[h-1],l[h-1],n[a++]+f)),i.push(f*c)}}},Mz.idle=function(t){var e=this.lastT();if(!(t=0;--c)n.push(wz(s[c],l[c],n[a]+u*i[a])),i.push(0),a+=1}};var Tz=function(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(h>0){var h=Math.sqrt(c+1);t[0]=.5*(o-l)/h,t[1]=.5*(s-n)/h,t[2]=.5*(r-a)/h,t[3]=.5*h}else{var f=Math.max(e,a,u),h=Math.sqrt(2*f-c+1);e>=f?(t[0]=.5*h,t[1]=.5*(i+r)/h,t[2]=.5*(s+n)/h,t[3]=.5*(o-l)/h):a>=f?(t[0]=.5*(r+i)/h,t[1]=.5*h,t[2]=.5*(l+o)/h,t[3]=.5*(s-n)/h):(t[0]=.5*(n+s)/h,t[1]=.5*(o+l)/h,t[2]=.5*h,t[3]=.5*(r-i)/h)}return t};var Sz=function(t){var e=(t=t||{}).center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),Lz(r=[].slice.call(r,0,4),r);var i=new Pz(r,e,Math.log(n));i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up);return i};function Cz(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function Ez(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function Lz(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=Ez(r,n,i,a);o>1e-6?(t[0]=r/o,t[1]=n/o,t[2]=i/o,t[3]=a/o):(t[0]=t[1]=t[2]=0,t[3]=1)}function Pz(t,e,r){this.radius=_z([r]),this.center=_z(e),this.rotation=_z(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}var zz=Pz.prototype;zz.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},zz.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;Lz(e,e);var r=this.computedMatrix;Dm(r,e);var n=this.computedCenter,i=this.computedEye,a=this.computedUp,o=Math.exp(this.computedRadius[0]);i[0]=n[0]+o*r[2],i[1]=n[1]+o*r[6],i[2]=n[2]+o*r[10],a[0]=r[1],a[1]=r[5],a[2]=r[9];for(var s=0;s<3;++s){for(var l=0,u=0;u<3;++u)l+=r[s+4*u]*i[u];r[12+s]=-l}},zz.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r},zz.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},zz.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},zz.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=i[1],o=i[5],s=i[9],l=Cz(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,p=Cz(u-=a*f,c-=o*f,h-=s*f);u/=p,c/=p,h/=p;var d=i[2],g=i[6],v=i[10],m=d*a+g*o+v*s,y=d*u+g*c+v*h,x=Cz(d-=m*a+y*u,g-=m*o+y*c,v-=m*s+y*h);d/=x,g/=x,v/=x;var b=u*e+a*r,_=c*e+o*r,w=h*e+s*r;this.center.move(t,b,_,w);var k=Math.exp(this.computedRadius[0]);k=Math.max(1e-4,k+n),this.radius.set(t,Math.log(k))},zz.rotate=function(t,e,r,n){this.recalcMatrix(t),e=e||0,r=r||0;var i=this.computedMatrix,a=i[0],o=i[4],s=i[8],l=i[1],u=i[5],c=i[9],h=i[2],f=i[6],p=i[10],d=e*a+r*l,g=e*o+r*u,v=e*s+r*c,m=-(f*v-p*g),y=-(p*d-h*v),x=-(h*g-f*d),b=Math.sqrt(Math.max(0,1-Math.pow(m,2)-Math.pow(y,2)-Math.pow(x,2))),_=Ez(m,y,x,b);_>1e-6?(m/=_,y/=_,x/=_,b/=_):(m=y=x=0,b=1);var w=this.computedRotation,k=w[0],M=w[1],A=w[2],T=w[3],S=k*b+T*m+M*x-A*y,C=M*b+T*y+A*m-k*x,E=A*b+T*x+k*y-M*m,L=T*b-k*m-M*y-A*x;if(n){m=h,y=f,x=p;var P=Math.sin(n)/Cz(m,y,x);m*=P,y*=P,x*=P,L=L*(b=Math.cos(e))-(S=S*b+L*m+C*x-E*y)*m-(C=C*b+L*y+E*m-S*x)*y-(E=E*b+L*x+S*y-C*m)*x}var z=Ez(S,C,E,L);z>1e-6?(S/=z,C/=z,E/=z,L/=z):(S=C=E=0,L=1),this.rotation.set(t,S,C,E,L)},zz.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;RP(i,e,r,n);var a=this.computedRotation;Tz(a,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),Lz(a,a),this.rotation.set(t,a[0],a[1],a[2],a[3]);for(var o=0,s=0;s<3;++s)o+=Math.pow(r[s]-e[s],2);this.radius.set(t,.5*Math.log(Math.max(o,1e-6))),this.center.set(t,r[0],r[1],r[2])},zz.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},zz.setMatrix=function(t,e){var r=this.computedRotation;Tz(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),Lz(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;IP(n,e);var i=n[15];if(Math.abs(i)>1e-6){var a=n[12]/i,o=n[13]/i,s=n[14]/i;this.recalcMatrix(t);var l=Math.exp(this.computedRadius[0]);this.center.set(t,a-n[2]*l,o-n[6]*l,s-n[10]*l),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},zz.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},zz.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},zz.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},zz.toJSON=function(){return this.recalcMatrix(this.lastT()),{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]}},zz.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)};var Dz=function(t,e,r,n){var i,a,o,s,l,u,c,h,f,p,d,g,v,m,y,x,b,_,w,k,M,A,T,S,C=n[0],E=n[1],L=n[2],P=Math.sqrt(C*C+E*E+L*L);if(Math.abs(P)<1e-6)return null;C*=P=1/P,E*=P,L*=P,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],h=e[4],f=e[5],p=e[6],d=e[7],g=e[8],v=e[9],m=e[10],y=e[11],x=C*C*o+a,b=E*C*o+L*i,_=L*C*o-E*i,w=C*E*o-L*i,k=E*E*o+a,M=L*E*o+C*i,A=C*L*o+E*i,T=E*L*o-C*i,S=L*L*o+a,t[0]=s*x+h*b+g*_,t[1]=l*x+f*b+v*_,t[2]=u*x+p*b+m*_,t[3]=c*x+d*b+y*_,t[4]=s*w+h*k+g*M,t[5]=l*w+f*k+v*M,t[6]=u*w+p*k+m*M,t[7]=c*w+d*k+y*M,t[8]=s*A+h*T+g*S,t[9]=l*A+f*T+v*S,t[10]=u*A+p*T+m*S,t[11]=c*A+d*T+y*S,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]);return t};var Iz=function(t){var e=(t=t||{}).center||[0,0,0],r=t.up||[0,1,0],n=t.right||Bz(r),i=t.radius||1,a=t.theta||0,o=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),UP(r,r),n=[].slice.call(n,0,3),UP(n,n),"eye"in t){var s=t.eye,l=[s[0]-e[0],s[1]-e[1],s[2]-e[2]];XP(n,l,r),Oz(n[0],n[1],n[2])<1e-6?n=Bz(r):UP(n,n),i=Oz(l[0],l[1],l[2]);var u=ZP(r,l)/i,c=ZP(n,l)/i;o=Math.acos(u),a=Math.acos(c)}return i=Math.log(i),new Fz(t.zoomMin,t.zoomMax,e,r,n,i,a,o)};function Oz(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function Rz(t){return Math.min(1,Math.max(-1,t))}function Bz(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;s<3;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(s=0;s<3;++s)i[s]-=o/a*t[s];return UP(i,i),i}function Fz(t,e,r,n,i,a,o,s){this.center=_z(r),this.up=_z(n),this.right=_z(i),this.radius=_z([a]),this.angle=_z([o,s]),this.angle.bounds=[[-1/0,-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var l=0;l<16;++l)this.computedMatrix[l]=.5;this.recalcMatrix(0)}var Nz=Fz.prototype;Nz.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-1/0,e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},Nz.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},Nz.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,n=0,i=0,a=0;a<3;++a)i+=e[a]*r[a],n+=e[a]*e[a];var o=Math.sqrt(n),s=0;for(a=0;a<3;++a)r[a]-=e[a]*i/n,s+=r[a]*r[a],e[a]/=o;var l=Math.sqrt(s);for(a=0;a<3;++a)r[a]/=l;var u=this.computedToward;XP(u,e,r),UP(u,u);var c=Math.exp(this.computedRadius[0]),h=this.computedAngle[0],f=this.computedAngle[1],p=Math.cos(h),d=Math.sin(h),g=Math.cos(f),v=Math.sin(f),m=this.computedCenter,y=p*g,x=d*g,b=v,_=-p*v,w=-d*v,k=g,M=this.computedEye,A=this.computedMatrix;for(a=0;a<3;++a){var T=y*r[a]+x*u[a]+b*e[a];A[4*a+1]=_*r[a]+w*u[a]+k*e[a],A[4*a+2]=T,A[4*a+3]=0}var S=A[1],C=A[5],E=A[9],L=A[2],P=A[6],z=A[10],D=C*z-E*P,I=E*L-S*z,O=S*P-C*L,R=Oz(D,I,O);D/=R,I/=R,O/=R,A[0]=D,A[4]=I,A[8]=O;for(a=0;a<3;++a)M[a]=m[a]+A[2+4*a]*c;for(a=0;a<3;++a){s=0;for(var B=0;B<3;++B)s+=A[a+4*B]*M[B];A[12+a]=-s}A[15]=1},Nz.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;n<16;++n)e[n]=r[n];return e}return r};var jz=[0,0,0];Nz.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;jz[0]=i[2],jz[1]=i[6],jz[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;l<3;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];Dz(i,i,n,jz);for(l=0;l<3;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},Nz.pan=function(t,e,r,n){e=e||0,r=r||0,n=n||0,this.recalcMatrix(t);var i=this.computedMatrix,a=(Math.exp(this.computedRadius[0]),i[1]),o=i[5],s=i[9],l=Oz(a,o,s);a/=l,o/=l,s/=l;var u=i[0],c=i[4],h=i[8],f=u*a+c*o+h*s,p=Oz(u-=a*f,c-=o*f,h-=s*f),d=(u/=p)*e+a*r,g=(c/=p)*e+o*r,v=(h/=p)*e+s*r;this.center.move(t,d,g,v);var m=Math.exp(this.computedRadius[0]);m=Math.max(1e-4,m+n),this.radius.set(t,Math.log(m))},Nz.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},Nz.setMatrix=function(t,e,r,n){var i=1;"number"==typeof r&&(i=0|r),(i<0||i>3)&&(i=1);var a=(i+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var o=e[i],s=e[i+4],l=e[i+8];if(n){var u=Math.abs(o),c=Math.abs(s),h=Math.abs(l),f=Math.max(u,c,h);u===f?(o=o<0?-1:1,s=l=0):h===f?(l=l<0?-1:1,o=s=0):(s=s<0?-1:1,o=l=0)}else{var p=Oz(o,s,l);o/=p,s/=p,l/=p}var d,g,v=e[a],m=e[a+4],y=e[a+8],x=v*o+m*s+y*l,b=Oz(v-=o*x,m-=s*x,y-=l*x),_=s*(y/=b)-l*(m/=b),w=l*(v/=b)-o*y,k=o*m-s*v,M=Oz(_,w,k);if(_/=M,w/=M,k/=M,this.center.jump(t,V,U,q),this.radius.idle(t),this.up.jump(t,o,s,l),this.right.jump(t,v,m,y),2===i){var A=e[1],T=e[5],S=e[9],C=A*v+T*m+S*y,E=A*_+T*w+S*k;d=D<0?-Math.PI/2:Math.PI/2,g=Math.atan2(E,C)}else{var L=e[2],P=e[6],z=e[10],D=L*o+P*s+z*l,I=L*v+P*m+z*y,O=L*_+P*w+z*k;d=Math.asin(Rz(D)),g=Math.atan2(O,I)}this.angle.jump(t,g,d),this.recalcMatrix(t);var R=e[2],B=e[6],F=e[10],N=this.computedMatrix;IP(N,e);var j=N[15],V=N[12]/j,U=N[13]/j,q=N[14]/j,H=Math.exp(this.computedRadius[0]);this.center.jump(t,V-R*H,U-B*H,q-F*H)},Nz.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},Nz.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},Nz.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},Nz.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},Nz.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter;var i=(n=n||this.computedUp)[0],a=n[1],o=n[2],s=Oz(i,a,o);if(!(s<1e-6)){i/=s,a/=s,o/=s;var l=e[0]-r[0],u=e[1]-r[1],c=e[2]-r[2],h=Oz(l,u,c);if(!(h<1e-6)){l/=h,u/=h,c/=h;var f=this.computedRight,p=f[0],d=f[1],g=f[2],v=i*p+a*d+o*g,m=Oz(p-=v*i,d-=v*a,g-=v*o);if(!(m<.01&&(m=Oz(p=a*c-o*u,d=o*l-i*c,g=i*u-a*l))<1e-6)){p/=m,d/=m,g/=m,this.up.set(t,i,a,o),this.right.set(t,p,d,g),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(h));var y=a*g-o*d,x=o*p-i*g,b=i*d-a*p,_=Oz(y,x,b),w=i*l+a*u+o*c,k=p*l+d*u+g*c,M=(y/=_)*l+(x/=_)*u+(b/=_)*c,A=Math.asin(Rz(w)),T=Math.atan2(M,k),S=this.angle._state,C=S[S.length-1],E=S[S.length-2];C%=2*Math.PI;var L=Math.abs(C+2*Math.PI-T),P=Math.abs(C-T),z=Math.abs(C-2*Math.PI-T);LMath.abs(e))n.rotate(s,0,0,-t*i*Math.PI*l.rotateSpeed/window.innerWidth);else{var u=l.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,a*(Math.exp(u)-1))}},!0),l};var Wz=function(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i=0?e[a]:i})},has___:{value:y(function(e){var n=m(e);return n?r in n:t.indexOf(e)>=0})},set___:{value:y(function(n,i){var a,o=m(n);return o?o[r]=i:(a=t.indexOf(n))>=0?e[a]=i:(a=t.length,e[a]=i,t[a]=n),this})},delete___:{value:y(function(n){var i,a,o=m(n);return o?r in o&&delete o[r]:!((i=t.indexOf(n))<0||(a=t.length-1,t[i]=void 0,e[i]=e[a],t[i]=t[a],t.length=a,e.length=a,0))})}})};d.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},delete:{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof e?function(){function r(){this instanceof d||x();var r,n=new e,i=void 0,a=!1;return r=t?function(t,e){return n.set(t,e),n.has(t)||(i||(i=new d),i.set(t,e)),this}:function(t,e){if(a)try{n.set(t,e)}catch(r){i||(i=new d),i.set___(t,e)}else n.set(t,e);return this},Object.create(d.prototype,{get___:{value:y(function(t,e){return i?n.has(t)?n.get(t):i.get___(t,e):n.get(t,e)})},has___:{value:y(function(t){return n.has(t)||!!i&&i.has___(t)})},set___:{value:y(r)},delete___:{value:y(function(t){var e=!!n.delete(t);return i&&i.delete___(t)||e})},permitHostObjects___:{value:y(function(t){if(t!==g)throw new Error("bogus call to permitHostObjects___");a=!0})}})}t&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=d.prototype,$z=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),$z=d)}function g(t){t.permitHostObjects___&&t.permitHostObjects___(g)}function v(t){return!(t.substr(0,s.length)==s&&"___"===t.substr(t.length-3))}function m(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[l];if(e&&e.key===t)return e;if(o(t)){e={key:t};try{return a(t,l,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(t){return}}}function y(t){return t.prototype=null,Object.freeze(t)}function x(){f||"undefined"==typeof console||(f=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}}();var tD=new("undefined"==typeof WeakMap?$z:WeakMap);var eD=function(t){var e=tD.get(t),r=e&&(e._triangleBuffer.handle||e._triangleBuffer.buffer);if(!r||!t.isBuffer(r)){var n=K_(t,new Float32Array([-1,-1,-1,4,4,-1]));(e=Qz(t,[{buffer:n,type:t.FLOAT,size:2}]))._triangleBuffer=n,tD.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()},rD={},nD=Q_(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"]),iD=Q_(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]);rD.line=function(t){return lk(t,nD,iD,null,[{name:"position",type:"vec3"}])};var aD=Q_(["#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}"]),oD=Q_(["precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}"]);rD.text=function(t){return lk(t,aD,oD,null,[{name:"position",type:"vec3"}])};var sD=Q_(["#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}"]),lD=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}"]);rD.bg=function(t){return lk(t,sD,lD,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])};var uD=function(t){for(var e=[],r=[],n=0,i=0;i<3;++i)for(var a=(i+1)%3,o=(i+2)%3,s=[0,0,0],l=[0,0,0],u=-1;u<=1;u+=2){r.push(n,n+2,n+1,n+1,n+2,n+3),s[i]=u,l[i]=u;for(var c=-1;c<=1;c+=2){s[a]=c;for(var h=-1;h<=1;h+=2)s[o]=h,e.push(s[0],s[1],s[2],l[0],l[1],l[2]),n+=1}var f=a;a=o,o=f}var p=K_(t,new Float32Array(e)),d=K_(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),g=Qz(t,[{buffer:p,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:p,type:t.FLOAT,size:3,offset:12,stride:24}],d),v=cD(t);return v.attributes.position.location=0,v.attributes.normal.location=1,new hD(t,p,g,v)},cD=rD.bg;function hD(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}var fD=hD.prototype;fD.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;s<3;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),this.vao.unbind(),l.disable(l.POLYGON_OFFSET_FILL)}},fD.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()};var pD=function(t,e){for(var r=Ik(t[0],e[0]),n=1;n1&&(i=1);for(var a=1-i,o=t.length,s=new Array(o),l=0;l0||i>0&&l<0){var u=vD(a,l,o,i);r.push(u),n.push(u.slice())}l<0?n.push(o.slice()):l>0?r.push(o.slice()):(r.push(o.slice()),n.push(o.slice())),i=l}return{positive:r,negative:n}}).positive=function(t,e){for(var r=[],n=gD(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(vD(i,s,a,n)),s>=0&&r.push(a.slice()),n=s}return r},dD.negative=function(t,e){for(var r=[],n=gD(t[t.length-1],e),i=t[t.length-1],a=t[0],o=0;o0||n>0&&s<0)&&r.push(vD(i,s,a,n)),s<=0&&r.push(a.slice()),n=s}return r};var mD=function(t,e,r,n){iz(yD,e,t),iz(yD,r,yD);for(var i=0,a=0;a<2;++a){_D[2]=n[a][2];for(var o=0;o<2;++o){_D[1]=n[o][1];for(var s=0;s<2;++s)_D[0]=n[s][0],kD(xD[i],_D,yD),i+=1}}for(var l=-1,a=0;a<8;++a){for(var u=xD[a][3],c=0;c<3;++c)bD[a][c]=xD[a][c]/u;u<0&&(l<0?l=a:bD[a][2]d&&(l|=1<d&&(l|=1<bD[a][1]&&(w=a));for(var k=-1,a=0;a<3;++a){var M=w^1<bD[A][0]&&(A=M)}}var T=TD;T[0]=T[1]=T[2]=0,T[Yb.log2(k^w)]=w&k,T[Yb.log2(w^A)]=w&A;var S=7^A;S===l||S===_?(S=7^k,T[Yb.log2(A^S)]=S&A):T[Yb.log2(k^S)]=S&k;for(var C=SD,E=l,h=0;h<3;++h)C[h]=E&1<=0;--d){var g=u[p[d]];o.push(l*g[0],-l*g[1],t)}}for(var l=[0,0,0],u=[0,0,0],c=[0,0,0],h=[0,0,0],f=0;f<3;++f){c[f]=o.length/3|0,s(.5*(t[0][f]+t[1][f]),e[f],r),h[f]=(o.length/3|0)-c[f],l[f]=o.length/3|0;for(var p=0;p=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;o<0?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u|=0);var c=""+l;if(o<0&&(c="-"+c),i){for(var h=""+u;h.length=t[0][n];--a)i.push({x:a*e[n],text:UD(e[n],a)});r.push(i)}return r},VD.equal=function(t,e){for(var r=0;r<3;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n0?(p[c]=-1,d[c]=0):(p[c]=0,d[c]=1)}}var KD=[0,0,0],QD={model:HD,view:HD,projection:HD};YD.isOpaque=function(){return!0},YD.isTransparent=function(){return!1},YD.drawTransparent=function(t){};var $D=[0,0,0],tI=[0,0,0],eI=[0,0,0];YD.draw=function(t){t=t||QD;for(var e=this.gl,r=t.model||HD,n=t.view||HD,i=t.projection||HD,a=this.bounds,o=mD(r,n,i,a),s=o.cubeEdges,l=o.axis,u=n[12],c=n[13],h=n[14],f=n[15],p=this.pixelRatio*(i[3]*u+i[7]*c+i[11]*h+i[15]*f)/e.drawingBufferHeight,d=0;d<3;++d)this.lastCubeProps.cubeEdges[d]=s[d],this.lastCubeProps.axis[d]=l[d];var g=ZD;for(d=0;d<3;++d)JD(ZD[d],d,this.bounds,s,l);e=this.gl;var v=KD;for(d=0;d<3;++d)this.backgroundEnable[d]?v[d]=l[d]:v[d]=0;this._background.draw(r,n,i,a,v,this.backgroundColor),this._lines.bind(r,n,i,this);for(d=0;d<3;++d){var m=[0,0,0];l[d]>0?m[d]=a[1][d]:m[d]=a[0][d];for(var y=0;y<2;++y){var x=(d+1+y)%3,b=(d+1+(1^y))%3;this.gridEnable[x]&&this._lines.drawGrid(x,b,this.bounds,m,this.gridColor[x],this.gridWidth[x]*this.pixelRatio)}for(y=0;y<2;++y){x=(d+1+y)%3,b=(d+1+(1^y))%3;this.zeroEnable[b]&&a[0][b]<=0&&a[1][b]>=0&&this._lines.drawZero(x,b,this.bounds,m,this.zeroLineColor[b],this.zeroLineWidth[b]*this.pixelRatio)}}for(d=0;d<3;++d){this.lineEnable[d]&&this._lines.drawAxisLine(d,this.bounds,g[d].primalOffset,this.lineColor[d],this.lineWidth[d]*this.pixelRatio),this.lineMirror[d]&&this._lines.drawAxisLine(d,this.bounds,g[d].mirrorOffset,this.lineColor[d],this.lineWidth[d]*this.pixelRatio);var _=GD($D,g[d].primalMinor),w=GD(tI,g[d].mirrorMinor),k=this.lineTickLength;for(y=0;y<3;++y){var M=p/r[5*y];_[y]*=k[y]*M,w[y]*=k[y]*M}this.lineTickEnable[d]&&this._lines.drawAxisTicks(d,g[d].primalOffset,_,this.lineTickColor[d],this.lineTickWidth[d]*this.pixelRatio),this.lineTickMirror[d]&&this._lines.drawAxisTicks(d,g[d].mirrorOffset,w,this.lineTickColor[d],this.lineTickWidth[d]*this.pixelRatio)}this._lines.unbind(),this._text.bind(r,n,i,this.pixelRatio);for(d=0;d<3;++d){var A=g[d].primalMinor,T=GD(eI,g[d].primalOffset);for(y=0;y<3;++y)this.lineTickEnable[d]&&(T[y]+=p*A[y]*Math.max(this.lineTickLength[y],0)/r[5*y]);if(this.tickEnable[d]){for(y=0;y<3;++y)T[y]+=p*A[y]*this.tickPad[y]/r[5*y];this._text.drawTicks(d,this.tickSize[d],this.tickAngle[d],T,this.tickColor[d])}if(this.labelEnable[d]){for(y=0;y<3;++y)T[y]+=p*A[y]*this.labelPad[y]/r[5*y];T[d]+=.5*(a[0][d]+a[1][d]),this._text.drawLabel(d,this.labelSize[d],this.labelAngle[d],T,this.labelColor[d])}}this._text.unbind()},YD.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null};var rI=function(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]};var nI=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t};var iI=function(t,e,r,n,i){var a=e.model||aI,o=e.view||aI,s=e.projection||aI,l=t.bounds,u=(i=i||mD(a,o,s,l)).axis;i.edges;iz(oI,o,a),iz(oI,s,oI);for(var c=hI,h=0;h<3;++h)c[h].lo=1/0,c[h].hi=-1/0,c[h].pixelsPerDataUnit=1/0;var f=rI(YP(oI,oI));YP(oI,oI);for(var p=0;p<3;++p){var d=(p+1)%3,g=(p+2)%3,v=fI;t:for(var h=0;h<2;++h){var m=[];if(u[p]<0!=!!h){v[p]=l[h][p];for(var y=0;y<2;++y){v[d]=l[y^h][d];for(var x=0;x<2;++x)v[g]=l[x^y^h][g],m.push(v.slice())}for(var y=0;y0&&0===v[e-1];)v.pop(),m.pop().dispose()}window.addEventListener("resize",T),M.update=function(t){e||(t=t||{},y=!0,x=!0)},M.add=function(t){e||(t.axes=h,d.push(t),g.push(-1),y=!0,x=!0,S())},M.remove=function(t){if(!e){var r=d.indexOf(t);r<0||(d.splice(r,1),g.pop(),y=!0,x=!0,S())}},M.dispose=function(){if(!e&&(e=!0,window.removeEventListener("resize",T),r.removeEventListener("webglcontextlost",L),M.mouseListener.enabled=!1,!M.contextLost)){h.dispose(),p.dispose();for(var t=0;to.distance)continue;for(var h=0;h0){r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function LI(t){return"boolean"!=typeof t||t}var PI=function(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]);"zoomMin"in e&&(r[0]=e.zoomMin);"zoomMax"in e&&(r[1]=e.zoomMax);var n=Vz({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=0,o=t.clientWidth,s=t.clientHeight,l={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=Hz(),r=this.delay,l=e-2*r;n.idle(e-r),n.recalcMatrix(l),n.flush(e-(100+2*r));for(var u=!0,c=n.computedMatrix,h=0;h<16;++h)u=u&&i[h]===c[h],i[h]=c[h];var f=t.clientWidth===o&&t.clientHeight===s;return o=t.clientWidth,s=t.clientHeight,u?!f:(a=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(l,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),i=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var a=Hz();n._active.lookAt(a,r,i,e),n._active.lookAt(a+500,r,i,[0,0,1]),n._active.flush(a)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return a},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var u=0,c=0,h={shift:!1,control:!1,alt:!1,meta:!1};function f(e,r,i,o){var s=l.keyBindingMode;if(!1!==s){var f="rotate"===s,p="pan"===s,d="zoom"===s,g=!!o.control,v=!!o.alt,m=!!o.shift,y=!!(1&e),x=!!(2&e),b=!!(4&e),_=1/t.clientHeight,w=_*(r-u),k=_*(i-c),M=l.flipX?1:-1,A=l.flipY?1:-1,T=Hz(),S=Math.PI*l.rotateSpeed;if((f&&y&&!g&&!v&&!m||y&&!g&&!v&&m)&&n.rotate(T,M*S*w,-A*S*k,0),(p&&y&&!g&&!v&&!m||x||y&&g&&!v&&!m)&&n.pan(T,-l.translateSpeed*w*a,l.translateSpeed*k*a,0),d&&y&&!g&&!v&&!m||b||y&&!g&&v&&!m){var C=-l.zoomSpeed*k/window.innerHeight*(T-n.lastT())*100;n.pan(T,0,0,a*(Math.exp(C)-1))}return u=r,c=i,h=o,!0}}return l.mouseListener=$E(t,f),t.addEventListener("touchstart",function(e){var r=ra(e.changedTouches[0],t);f(0,r[0],r[1],h),f(1,r[0],r[1],h),e.preventDefault()},!!ta&&{passive:!1}),t.addEventListener("touchmove",function(e){var r=ra(e.changedTouches[0],t);f(1,r[0],r[1],h),e.preventDefault()},!!ta&&{passive:!1}),t.addEventListener("touchend",function(t){f(0,u,c,h),t.preventDefault()},!!ta&&{passive:!1}),l.wheelListener=aL(t,function(t,e){if(!1!==l.keyBindingMode){var r=l.flipX?1:-1,i=l.flipY?1:-1,o=Hz();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*l.rotateSpeed/window.innerWidth);else{var s=-l.zoomSpeed*i*e/window.innerHeight*(o-n.lastT())/20;n.pan(o,0,0,a*(Math.exp(s)-1))}}},!0),l};var zI=["xaxis","yaxis","zaxis"];function DI(){this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.tickEnable=[!0,!0,!0],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=[!0,!0,!0],this.labelFont=["Open Sans","Open Sans","Open Sans"],this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[30,30,30],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],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=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!0,!0,!0],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._defaultTickPad=this.tickPad.slice(),this._defaultLabelPad=this.labelPad.slice(),this._defaultLineTickLength=this.lineTickLength.slice()}DI.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[zI[e]];r.visible?(this.labels[e]=XE(r.title),"titlefont"in r&&(r.titlefont.color&&(this.labelColor[e]=vL(r.titlefont.color)),r.titlefont.family&&(this.labelFont[e]=r.titlefont.family),r.titlefont.size&&(this.labelSize[e]=r.titlefont.size)),"showline"in r&&(this.lineEnable[e]=r.showline),"linecolor"in r&&(this.lineColor[e]=vL(r.linecolor)),"linewidth"in r&&(this.lineWidth[e]=r.linewidth),"showgrid"in r&&(this.gridEnable[e]=r.showgrid),"gridcolor"in r&&(this.gridColor[e]=vL(r.gridcolor)),"gridwidth"in r&&(this.gridWidth[e]=r.gridwidth),"log"===r.type?this.zeroEnable[e]=!1:"zeroline"in r&&(this.zeroEnable[e]=r.zeroline),"zerolinecolor"in r&&(this.zeroLineColor[e]=vL(r.zerolinecolor)),"zerolinewidth"in r&&(this.zeroLineWidth[e]=r.zerolinewidth),"ticks"in r&&r.ticks?this.lineTickEnable[e]=!0:this.lineTickEnable[e]=!1,"ticklen"in r&&(this.lineTickLength[e]=this._defaultLineTickLength[e]=r.ticklen),"tickcolor"in r&&(this.lineTickColor[e]=vL(r.tickcolor)),"tickwidth"in r&&(this.lineTickWidth[e]=r.tickwidth),"tickangle"in r&&(this.tickAngle[e]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180),"showticklabels"in r&&(this.tickEnable[e]=r.showticklabels),"tickfont"in r&&(r.tickfont.color&&(this.tickColor[e]=vL(r.tickfont.color)),r.tickfont.family&&(this.tickFont[e]=r.tickfont.family),r.tickfont.size&&(this.tickSize[e]=r.tickfont.size)),"mirror"in r?-1!==["ticks","all","allticks"].indexOf(r.mirror)?(this.lineTickMirror[e]=!0,this.lineMirror[e]=!0):!0===r.mirror?(this.lineTickMirror[e]=!1,this.lineMirror[e]=!0):(this.lineTickMirror[e]=!1,this.lineMirror[e]=!1):this.lineMirror[e]=!1,"showbackground"in r&&!1!==r.showbackground?(this.backgroundEnable[e]=!0,this.backgroundColor[e]=vL(r.backgroundcolor)):this.backgroundEnable[e]=!1):(this.tickEnable[e]=!1,this.labelEnable[e]=!1,this.lineEnable[e]=!1,this.lineTickEnable[e]=!1,this.gridEnable[e]=!1,this.zeroEnable[e]=!1,this.backgroundEnable[e]=!1)}};var II=function(t){var e=new DI;return e.merge(t),e},OI=["xaxis","yaxis","zaxis"];function RI(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}RI.prototype.merge=function(t){for(var e=0;e<3;++e){var r=t[OI[e]];r.visible?(this.enabled[e]=r.showspikes,this.colors[e]=vL(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness):(this.enabled[e]=!1,this.drawSides[e]=!1)}};var BI,FI,NI=function(t){var e=new RI;return e.merge(t),e},jI=function(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,n=t.fullSceneLayout,i=[[],[],[]],a=0;a<3;++a){var o=n[VI[a]];if(o._length=(r[a].hi-r[a].lo)*r[a].pixelsPerDataUnit/t.dataScale[a],Math.abs(o._length)===1/0)i[a]=[];else{o._input_range=o.range.slice(),o.range[0]=r[a].lo/t.dataScale[a],o.range[1]=r[a].hi/t.dataScale[a],o._m=1/(t.dataScale[a]*r[a].pixelsPerDataUnit),o.range[0]===o.range[1]&&(o.range[0]-=1,o.range[1]+=1);var s=o.tickmode;if("auto"===o.tickmode){o.tickmode="linear";var l=o.nticks||oe.constrain(o._length/40,4,9);ui.autoTicks(o,Math.abs(o.range[1]-o.range[0])/l)}for(var u=ui.calcTicks(o),c=0;ch[1][o]?f[o]=1:h[1][o]===h[0][o]?f[o]=1:f[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=f,this.convertAnnotations(this),a=0;ad[1][a])d[0][a]=-1,d[1][a]=1;else{var k=d[1][a]-d[0][a];d[0][a]-=k/32,d[1][a]+=k/32}}else{var M=s.range;d[0][a]=s.r2l(M[0]),d[1][a]=s.r2l(M[1])}d[0][a]===d[1][a]&&(d[0][a]-=1,d[1][a]+=1),g[a]=d[1][a]-d[0][a],this.glplot.bounds[0][a]=d[0][a]*f[a],this.glplot.bounds[1][a]=d[1][a]*f[a]}var A=[1,1,1];for(a=0;a<3;++a){var T=v[l=(s=u[WI[a]]).type];A[a]=Math.pow(T.acc,1/T.count)/f[a]}var S;if("auto"===u.aspectmode)S=Math.max.apply(null,A)/Math.min.apply(null,A)<=4?A:[1,1,1];else if("cube"===u.aspectmode)S=[1,1,1];else if("data"===u.aspectmode)S=A;else{if("manual"!==u.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var C=u.aspectratio;S=[C.x,C.y,C.z]}u.aspectratio.x=c.aspectratio.x=S[0],u.aspectratio.y=c.aspectratio.y=S[1],u.aspectratio.z=c.aspectratio.z=S[2],this.glplot.aspect=S;var E=u.domain||null,L=e._size||null;if(E&&L){var P=this.container.style;P.position="absolute",P.left=L.l+E.x[0]*L.w+"px",P.top=L.t+(1-E.y[1])*L.h+"px",P.width=L.w*(E.x[1]-E.x[0])+"px",P.height=L.h*(E.y[1]-E.y[0])+"px"}this.glplot.redraw()}},GI.destroy=function(){this.glplot&&(this.camera.mouseListener.enabled=!1,this.container.removeEventListener("wheel",this.camera.wheelListener),this.camera=this.glplot.camera=null,this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null)},GI.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),ZI(this.glplot.camera)},GI.setCamera=function(t){var e;this.glplot.camera.lookAt.apply(this,[[(e=t).eye.x,e.eye.y,e.eye.z],[e.center.x,e.center.y,e.center.z],[e.up.x,e.up.y,e.up.z]])},GI.saveCamera=function(t){var e=this.getCamera(),r=oe.nestedProperty(t,this.id+".camera"),n=r.get(),i=!1;function a(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}if(void 0===n)i=!0;else for(var o=0;o<3;o++)for(var s=0;s<3;s++)if(!a(e,n,o,s)){i=!0;break}return i&&r.set(e),i},GI.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},GI.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(BI),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;a1;Nh(t,e,0,{type:"gl3d",attributes:zP,handleDefaults:DP,fullLayout:e,font:e.font,fullData:r,getDfltFromLayout:function(e){if(!n)return oe.validate(t[e],zP[e])?t[e]:void 0},paper_bgcolor:e.paper_bgcolor,calendar:e.calendar})},KI.plot=function(t){for(var e=t._fullLayout,r=t._fullData,n=e._subplots.gl3d,i=0;i=0;--i){var a=r,o=t[i],s=(r=a+o)-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;i>1;return["sum(",t(e.slice(0,r)),",",t(e.slice(r)),")"].join("")}(e);var n}function fO(t){return new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",hO(function(t){for(var e=new Array(t),r=0;r0&&r.push(","),r.push("[");for(var a=0;a0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(t<6?lO[t]:lO)}var mO=[function(){return[0]},function(t,e){return[[e[0]],[t[0][0]]]}];function yO(t,e){for(var r=0,n=t.length,i=0;i0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=rM[t+1];return i||(i=rM),n(i)}(t)),this.orient=i}var LO=EO.prototype;LO.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){(t=o.pop()).vertices;for(var s=t.adjacent,l=0;l<=r;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,h=0;h<=r;++h){var f=c[h];i[h]=f<0?e:a[f]}var p=this.orient();if(p>0)return u;u.lastVisited=-n,0===p&&o.push(u)}}}return null},LO.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;c<=n;++c)a[c]=i[l[c]];s.lastVisited=r;for(c=0;c<=n;++c){var h=u[c];if(!(h.lastVisited>=r)){var f=a[c];a[c]=t;var p=this.orient();if(a[c]=f,p<0){s=h;continue t}h.boundary?h.lastVisited=-r:h.lastVisited=r}}return}return s},LO.addPeaks=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=this.interior,s=this.simplices,l=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,o.push(e);for(var u=[];l.length>0;){var c=(e=l.pop()).vertices,h=e.adjacent,f=c.indexOf(r);if(!(f<0))for(var p=0;p<=n;++p)if(p!==f){var d=h[p];if(d.boundary&&!(d.lastVisited>=r)){var g=d.vertices;if(d.lastVisited!==-r){for(var v=0,m=0;m<=n;++m)g[m]<0?(v=m,a[m]=t):a[m]=i[g[m]];if(this.orient()>0){g[v]=r,d.boundary=!1,o.push(d),l.push(d),d.lastVisited=r;continue}d.lastVisited=-r}var y=d.adjacent,x=c.slice(),b=h.slice(),_=new AO(x,b,!0);s.push(_);var w=y.indexOf(e);if(!(w<0)){y[w]=_,b[f]=d,x[p]=-1,b[p]=e,h[p]=_,_.flip();for(m=0;m<=n;++m){var k=x[m];if(!(k<0||k===r)){for(var M=new Array(n-1),A=0,T=0;T<=n;++T){var S=x[T];S<0||T===m||(M[A++]=S)}u.push(new TO(M,_,m))}}}}}}u.sort(SO);for(p=0;p+1=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var h=o[0];o[0]=o[1],o[1]=h}e.push(o)}}return e};var PO=function(t,e){var r=t.length;if(0===r)return[];var n=t[0].length;if(n<1)return[];if(1===n)return function(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;a=2)return!1;t[r]=i}return!0}):m.filter(function(t){for(var e=0;e<=n;++e){var r=p[t[e]];if(r<0)return!1;t[e]=r}return!0});if(1&n)for(var o=0;o0){var o=t[r-1];if(0===BO(i,o)&&RO(o)!==a){r-=1;continue}}t[r++]=i}}return t.length=r,t};var UO=function(t){return VO(OO(t))};var qO=function(t,e){return UO(IO(t,e))};var HO=function(t){for(var e=0,r=0,n=1;nt[r][0]&&(r=n);return er?[[r],[e]]:[[e]]};var GO=function(t){var e=t.length;if(e<3){for(var r=new Array(e),n=0;n1&&WO(t[a[u-2]],t[a[u-1]],l)<=0;)u-=1,a.pop();for(a.push(s),u=o.length;u>1&&WO(t[o[u-2]],t[o[u-1]],l)>=0;)u-=1,o.pop();o.push(s)}for(var r=new Array(o.length+a.length-2),c=0,n=0,h=a.length;n0;--f)r[c++]=o[f];return r},WO=rM[3];var YO=function(t){var e=GO(t),r=e.length;if(r<=2)return[];for(var n=new Array(r),i=e[r-1],a=0;a=e[l]&&(s+=1);a[o]=s}}return t}(i,r)}};var KO=function(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;if(0===r)return[];if(1===r)return HO(t);if(2===r)return YO(t);return JO(t,r)};var QO={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:1,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13,rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]};var $O=function(t,e,r){return t*(1-r)+e*r},tR=function(t){var e,r,n,i,a,o,s,l,u,c;t||(t={});l=(t.nshades||72)-1,s=t.format||"hex",(o=t.colormap)||(o="jet");if("string"==typeof o){if(o=o.toLowerCase(),!QO[o])throw Error(o+" not a supported colorscale");a=QO[o]}else{if(!Array.isArray(o))throw Error("unsupported colormap option",o);a=o.slice()}if(a.length>l)throw new Error(o+" map requires nshades to be at least size "+a.length);u=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:t.alpha.slice():"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1];e=a.map(function(t){return Math.round(t.index*l)}),u[0]=Math.min(Math.max(u[0],0),1),u[1]=Math.min(Math.max(u[1],0),1);var h=a.map(function(t,e){var r=a[e].index,n=a[e].rgb.slice();return 4===n.length&&n[3]>=0&&n[3]<=1?n:(n[3]=u[0]+(u[1]-u[0])*r,n)}),f=[];for(c=0;c=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h):(_=0,c>=0?(w=0,g=h):-c>=l?(w=1,g=l+2*c+h):g=c*(w=-c/l)+h);else if(w<0)w=0,u>=0?(_=0,g=h):-u>=o?(_=1,g=o+2*u+h):g=u*(_=-u/o)+h;else{var k=1/b;g=(_*=k)*(o*_+s*(w*=k)+2*u)+w*(s*_+l*w+2*c)+h}else _<0?(m=l+c)>(v=s+u)?(y=m-v)>=(x=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/x)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h:(_=0,m<=0?(w=1,g=l+2*c+h):c>=0?(w=0,g=h):g=c*(w=-c/l)+h):w<0?(m=o+u)>(v=s+c)?(y=m-v)>=(x=o-2*s+l)?(w=1,_=0,g=l+2*c+h):g=(_=1-(w=y/x))*(o*_+s*w+2*u)+w*(s*_+l*w+2*c)+h:(w=0,m<=0?(_=1,g=o+2*u+h):u>=0?(_=0,g=h):g=u*(_=-u/o)+h):(y=l+c-s-u)<=0?(_=0,w=1,g=l+2*c+h):y>=(x=o-2*s+l)?(_=1,w=0,g=o+2*u+h):g=(_=y/x)*(o*_+s*(w=1-_)+2*u)+w*(s*_+l*w+2*c)+h;var M=1-_-w;for(a=0;a1.0001)return null;p+=f[s]}if(Math.abs(p-1)>.001)return null;return[l,function(t,e){for(var r=[0,0,0],n=0;n 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]),bR=Q_(["precision mediump 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}"]),_R=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]),wR=Q_(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(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}"]),kR=Q_(["precision mediump 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}"]),MR=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n"]);pR.meshShader={vertex:dR,fragment:gR,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},pR.wireShader={vertex:vR,fragment:mR,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},pR.pointShader={vertex:yR,fragment:xR,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},pR.pickShader={vertex:bR,fragment:_R,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},pR.pointPickShader={vertex:wR,fragment:_R,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},pR.contourShader={vertex:kR,fragment:MR,attributes:[{name:"position",type:"vec3"}]};var AR={};AR.vertexNormals=function(t,e,r){for(var n=e.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa){var b=i[u],_=1/Math.sqrt(v*y);for(x=0;x<3;++x){var w=(x+1)%3,k=(x+2)%3;b[x]+=_*(m[w]*g[k]-m[k]*g[w])}}}for(o=0;oa)for(_=1/Math.sqrt(M),x=0;x<3;++x)b[x]*=_;else for(x=0;x<3;++x)b[x]=0}return i},AR.faceNormals=function(t,e,r){for(var n=t.length,i=new Array(n),a=void 0===r?1e-6:r,o=0;oa?1/Math.sqrt(p):0;for(u=0;u<3;++u)f[u]*=p;i[o]=f}return i};var TR=32;function SR(t){switch(t){case"uint8":return[G_.mallocUint8,G_.freeUint8];case"uint16":return[G_.mallocUint16,G_.freeUint16];case"uint32":return[G_.mallocUint32,G_.freeUint32];case"int8":return[G_.mallocInt8,G_.freeInt8];case"int16":return[G_.mallocInt16,G_.freeInt16];case"int32":return[G_.mallocInt32,G_.freeInt32];case"float32":return[G_.mallocFloat,G_.freeFloat];case"float64":return[G_.mallocDouble,G_.freeDouble];default:return null}}function CR(t){for(var e=[],r=0;r0?i.push(["d",h,"=s",h,"-d",l,"*n",l].join("")):i.push(["d",h,"=s",h].join("")),l=h),0!=(c=t.length-1-a)&&(u>0?i.push(["e",c,"=s",c,"-e",u,"*n",u,",f",c,"=",o[c],"-f",u,"*n",u].join("")):i.push(["e",c,"=s",c,",f",c,"=",o[c]].join("")),u=c)}r.push("var "+i.join(","));var f=["0","n0-1","data","offset"].concat(CR(t.length));r.push(["if(n0<=",TR,"){","insertionSort(",f.join(","),")}else{","quickSort(",f.join(","),")}"].join("")),r.push("}return "+n);var p=new Function("insertionSort","quickSort",r.join("\n")),d=function(t,e){var r=["'use strict'"],n=["ndarrayInsertionSort",t.join("d"),e].join(""),i=["left","right","data","offset"].concat(CR(t.length)),a=SR(e),o=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var s=[],l=1;l1){for(r.push("dptr=0;sptr=ptr"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"b){break __l}"].join("")),l=t.length-1;l>=1;--l)r.push("sptr+=e"+l,"dptr+=f"+l,"}");for(r.push("dptr=cptr;sptr=cptr-s0"),l=t.length-1;l>=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"=0;--l)0!==(h=t[l])&&r.push(["for(i",h,"=0;i",h,"scratch)){",c("cptr",u("cptr-s0")),"cptr-=s0","}",c("cptr","scratch"));return r.push("}"),t.length>1&&a&&r.push("free(scratch)"),r.push("} return "+n),a?new Function("malloc","free",r.join("\n"))(a[0],a[1]):new Function(r.join("\n"))()}(t,e);return p(d,function(t,e,r){var n=["'use strict'"],i=["ndarrayQuickSort",t.join("d"),e].join(""),a=["left","right","data","offset"].concat(CR(t.length)),o=SR(e),s=0;n.push(["function ",i,"(",a.join(","),"){"].join(""));var l=["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","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var u=[],c=1;c=0;--a)0!==(o=t[a])&&n.push(["for(i",o,"=0;i",o,"1)for(a=0;a1?n.push("ptr_shift+=d"+o):n.push("ptr0+=d"+o),n.push("}"))}}function g(e,r,i,a){if(1===r.length)n.push("ptr0="+h(r[0]));else{for(var o=0;o1)for(o=0;o=1;--o)i&&n.push("pivot_ptr+=f"+o),r.length>1?n.push("ptr_shift+=e"+o):n.push("ptr0+=e"+o),n.push("}")}function v(){t.length>1&&o&&n.push("free(pivot1)","free(pivot2)")}function m(e,r){var i="el"+e,a="el"+r;if(t.length>1){var o="__l"+ ++s;g(o,[i,a],!1,["comp=",f("ptr0"),"-",f("ptr1"),"\n","if(comp>0){tmp0=",i,";",i,"=",a,";",a,"=tmp0;break ",o,"}\n","if(comp<0){break ",o,"}"].join(""))}else n.push(["if(",f(h(i)),">",f(h(a)),"){tmp0=",i,";",i,"=",a,";",a,"=tmp0}"].join(""))}function y(e,r){t.length>1?d([e,r],!1,p("ptr0",f("ptr1"))):n.push(p(h(e),f(h(r))))}function x(e,r,i){if(t.length>1){var a="__l"+ ++s;g(a,[r],!0,[e,"=",f("ptr0"),"-pivot",i,"[pivot_ptr]\n","if(",e,"!==0){break ",a,"}"].join(""))}else n.push([e,"=",f(h(r)),"-pivot",i].join(""))}function b(e,r){t.length>1?d([e,r],!1,["tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1","tmp")].join("")):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1","tmp")].join(""))}function _(e,r,i){t.length>1?(d([e,r,i],!1,["tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1",f("ptr2")),"\n",p("ptr2","tmp")].join("")),n.push("++"+r,"--"+i)):n.push(["ptr0=",h(e),"\n","ptr1=",h(r),"\n","ptr2=",h(i),"\n","++",r,"\n","--",i,"\n","tmp=",f("ptr0"),"\n",p("ptr0",f("ptr1")),"\n",p("ptr1",f("ptr2")),"\n",p("ptr2","tmp")].join(""))}function w(t,e){b(t,e),n.push("--"+e)}function k(e,r,i){t.length>1?d([e,r],!0,[p("ptr0",f("ptr1")),"\n",p("ptr1",["pivot",i,"[pivot_ptr]"].join(""))].join("")):n.push(p(h(e),f(h(r))),p(h(r),"pivot"+i))}function M(e,r){n.push(["if((",r,"-",e,")<=",TR,"){\n","insertionSort(",e,",",r,",data,offset,",CR(t.length).join(","),")\n","}else{\n",i,"(",e,",",r,",data,offset,",CR(t.length).join(","),")\n","}"].join(""))}function A(e,r,i){t.length>1?(n.push(["__l",++s,":while(true){"].join("")),d([e],!0,["if(",f("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",s,"}"].join("")),n.push(i,"}")):n.push(["while(",f(h(e)),"===pivot",r,"){",i,"}"].join(""))}return n.push("var "+l.join(",")),m(1,2),m(4,5),m(1,3),m(2,3),m(1,4),m(3,4),m(2,5),m(2,3),m(4,5),t.length>1?d(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",f("ptr1"),"\n","pivot2[pivot_ptr]=",f("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",f("ptr0"),"\n","y=",f("ptr2"),"\n","z=",f("ptr4"),"\n",p("ptr5","x"),"\n",p("ptr6","y"),"\n",p("ptr7","z")].join("")):n.push(["pivot1=",f(h("el2")),"\n","pivot2=",f(h("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",f(h("el1")),"\n","y=",f(h("el3")),"\n","z=",f(h("el5")),"\n",p(h("index1"),"x"),"\n",p(h("index3"),"y"),"\n",p(h("index5"),"z")].join("")),y("index2","left"),y("index4","right"),n.push("if(pivots_are_equal){"),n.push("for(k=less;k<=great;++k){"),x("comp","k",1),n.push("if(comp===0){continue}"),n.push("if(comp<0){"),n.push("if(k!==less){"),b("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),n.push("while(true){"),x("comp","great",1),n.push("if(comp>0){"),n.push("great--"),n.push("}else if(comp<0){"),_("k","less","great"),n.push("break"),n.push("}else{"),w("k","great"),n.push("break"),n.push("}"),n.push("}"),n.push("}"),n.push("}"),n.push("}else{"),n.push("for(k=less;k<=great;++k){"),x("comp_pivot1","k",1),n.push("if(comp_pivot1<0){"),n.push("if(k!==less){"),b("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),x("comp_pivot2","k",2),n.push("if(comp_pivot2>0){"),n.push("while(true){"),x("comp","great",2),n.push("if(comp>0){"),n.push("if(--greatindex5){"),A("less",1,"++less"),A("great",2,"--great"),n.push("for(k=less;k<=great;++k){"),x("comp_pivot1","k",1),n.push("if(comp_pivot1===0){"),n.push("if(k!==less){"),b("k","less"),n.push("}"),n.push("++less"),n.push("}else{"),x("comp_pivot2","k",2),n.push("if(comp_pivot2===0){"),n.push("while(true){"),x("comp","great",2),n.push("if(comp===0){"),n.push("if(--great1&&o?new Function("insertionSort","malloc","free",n.join("\n"))(r,o[0],o[1]):new Function("insertionSort",n.join("\n"))(r)}(t,e,d))},LR={};var PR=function(t){var e=t.order,r=t.dtype,n=[e,r].join(":"),i=LR[n];return i||(LR[n]=i=ER(e,r)),i(t),t},zR=function(t){for(var e=1<>1,v=E[2*m+1];","if(v===b){return m}","if(b0&&o.push(","),o.push("[");for(var n=0;n0&&o.push(","),o.push("B(C,E,c[",i[0],"],c[",i[1],"])")}o.push("]")}o.push(");")}}for(var n=t+1;n>1;--n){n=1},WR.isTransparent=function(){return this.opacity<1},WR.pickSlots=1,WR.setPickBase=function(t){this.pickId=t},WR.highlight=function(t){if(t&&this.contourEnable){for(var e=BR(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=G_.mallocFloat32(6*a),s=0,l=0;l0&&((u=this.triShader).bind(),u.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind());this.edgeCount>0&&this.lineWidth>0&&((u=this.lineShader).bind(),u.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind());this.pointCount>0&&((u=this.pointShader).bind(),u.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind());this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0&&((u=this.contourShader).bind(),u.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind())},WR.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||HR,n=t.view||HR,i=t.projection||HR,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;o<3;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s,l={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255};((s=this.pickShader).bind(),s.uniforms=l,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0)&&((s=this.pointPickShader).bind(),s.uniforms=l,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind())},WR.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;a0)i=qO(t.alphahull,a);else{var o=["x","y","z"].indexOf(t.delaunayaxis);i=PO(a.map(function(t){return[t[(o+1)%3],t[(o+2)%3]]}))}var s={positions:a,cells:i,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:vL(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",s.vertexIntensity=t.intensity,s.vertexIntensityBounds=[t.cmin,t.cmax],s.colormap=t.colorscale.map(function(t){var e=t[0],r=c(t[1]).toRgb();return{index:e,rgb:[r.r,r.g,r.b,1]}})):t.vertexcolor?(this.color=t.vertexcolor[0],s.vertexColors=tB(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],s.cellColors=tB(t.facecolor)):(this.color=t.color,s.meshColor=vL(t.color)),this.mesh.update(s)},$R.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()};var rB=function(t,e){var r=t.glplot.gl,n=KR({gl:r}),i=new QR(t,n,e.uid);return n._trace=i,i.update(e),t.glplot.add(n),i},nB={};nB.attributes=oO,nB.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,oO,r,n)}function a(t){var e=t.map(function(t){var e=i(t);return e&&oe.isArrayOrTypedArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var o=a(["x","y","z"]),s=a(["i","j","k"]);o?(s&&s.forEach(function(t){for(var e=0;e>>=e))<<3,(e|=r=(15<(t>>>=r))<<2)|(r=(3<(t>>>=r))<<1)|t>>>r>>1}function l(t){t:{for(var e=16;268435456>=e;e*=16)if(t<=e){t=e;break t}t=0}return 0<(e=Y[s(t)>>2]).length?e.pop():new ArrayBuffer(t)}function u(t){Y[s(t.byteLength)>>2].push(t)}function c(t,e,r,n,i,a){for(var o=0;o(i=l)&&(i=n.buffer.byteLength,5123===h?i>>=1:5125===h&&(i>>=2)),n.vertCount=i,i=s,0>s&&(i=4,1===(s=n.buffer.dimension)&&(i=0),2===s&&(i=1),3===s&&(i=4)),n.primType=i}function s(t){n.elementsCount--,delete l[t.id],t.buffer.destroy(),t.buffer=null}var l={},u=0,c={uint8:5121,uint16:5123};e.oes_element_index_uint&&(c.uint32=5125),i.prototype.bind=function(){this.buffer.bind()};var h=[];return{create:function(t,e){function l(t){if(t)if("number"==typeof t)u(t),h.primType=4,h.vertCount=0|t,h.type=5121;else{var e=null,r=35044,n=-1,i=-1,s=0,f=0;Array.isArray(t)||G(t)||a(t)?e=t:("data"in t&&(e=t.data),"usage"in t&&(r=Q[t.usage]),"primitive"in t&&(n=rt[t.primitive]),"count"in t&&(i=0|t.count),"type"in t&&(f=c[t.type]),"length"in t?s=0|t.length:(s=i,5123===f||5122===f?s*=2:5125!==f&&5124!==f||(s*=4))),o(h,e,r,n,i,s,f)}else u(),h.primType=4,h.vertCount=0,h.type=5121;return l}var u=r.create(null,34963,!0),h=new i(u._buffer);return n.elementsCount++,l(t),l._reglType="elements",l._elements=h,l.subdata=function(t,e){return u.subdata(t,e),l},l.destroy=function(){s(h)},l},createStream:function(t){var e=h.pop();return e||(e=new i(r.create(null,34963,!0,!1)._buffer)),o(e,t,35040,-1,-1,0,0),e},destroyStream:function(t){h.push(t)},getElements:function(t){return"function"==typeof t&&t._elements instanceof i?t._elements:null},clear:function(){W(l).forEach(s)}}}function v(t){for(var e=X.allocType(5123,t.length),r=0;r>>31<<15,i=(a<<1>>>24)-127,a=a>>13&1023;e[r]=-24>i?n:-14>i?n+(a+1024>>-14-i):15>=i,r.height>>=i,p(r,n[i]),t.mipmask|=1<e;++e)t.images[e]=null;return t}function E(t){for(var e=t.images,r=0;re){for(var r=0;r=--this.refCount&&R(this)}}),s.profile&&(o.getTotalTextureSize=function(){var t=0;return Object.keys(ht).forEach(function(e){t+=ht[e].stats.size}),t}),{create2D:function(e,r){function n(t,e){var r=i.texInfo;L.call(r);var a=C();return"number"==typeof t?A(a,0|t,"number"==typeof e?0|e:0|t):t?(P(r,t),T(a,t)):A(a,1,1),r.genMipmaps&&(a.mipmask=(a.width<<1)-1),i.mipmask=a.mipmask,u(i,a),i.internalformat=a.internalformat,n.width=a.width,n.height=a.height,I(i),S(a,3553),z(r,3553),O(),E(a),s.profile&&(i.stats.size=k(i.internalformat,i.type,a.width,a.height,r.genMipmaps,!1)),n.format=$[i.internalformat],n.type=tt[i.type],n.mag=et[r.magFilter],n.min=rt[r.minFilter],n.wrapS=nt[r.wrapS],n.wrapT=nt[r.wrapT],n}var i=new D(3553);return ht[i.id]=i,o.textureCount++,n(e,r),n.subimage=function(t,e,r,a){e|=0,r|=0,a|=0;var o=g();return u(o,i),o.width=0,o.height=0,p(o,t),o.width=o.width||(i.width>>a)-e,o.height=o.height||(i.height>>a)-r,I(i),d(o,3553,e,r,a),O(),M(o),n},n.resize=function(e,r){var a=0|e,o=0|r||a;if(a===i.width&&o===i.height)return n;n.width=i.width=a,n.height=i.height=o,I(i);for(var l=0;i.mipmask>>l;++l)t.texImage2D(3553,l,i.format,a>>l,o>>l,0,i.format,i.type,null);return O(),s.profile&&(i.stats.size=k(i.internalformat,i.type,a,o,!1,!1)),n},n._reglType="texture2d",n._texture=i,s.profile&&(n.stats=i.stats),n.destroy=function(){i.decRef()},n},createCube:function(e,r,n,i,a,l){function h(t,e,r,n,i,a){var o,l=f.texInfo;for(L.call(l),o=0;6>o;++o)v[o]=C();if("number"!=typeof t&&t){if("object"==typeof t)if(e)T(v[0],t),T(v[1],e),T(v[2],r),T(v[3],n),T(v[4],i),T(v[5],a);else if(P(l,t),c(f,t),"faces"in t)for(t=t.faces,o=0;6>o;++o)u(v[o],f),T(v[o],t[o]);else for(o=0;6>o;++o)T(v[o],t)}else for(t=0|t||1,o=0;6>o;++o)A(v[o],t,t);for(u(f,v[0]),f.mipmask=l.genMipmaps?(v[0].width<<1)-1:v[0].mipmask,f.internalformat=v[0].internalformat,h.width=v[0].width,h.height=v[0].height,I(f),o=0;6>o;++o)S(v[o],34069+o);for(z(l,34067),O(),s.profile&&(f.stats.size=k(f.internalformat,f.type,h.width,h.height,l.genMipmaps,!0)),h.format=$[f.internalformat],h.type=tt[f.type],h.mag=et[l.magFilter],h.min=rt[l.minFilter],h.wrapS=nt[l.wrapS],h.wrapT=nt[l.wrapT],o=0;6>o;++o)E(v[o]);return h}var f=new D(34067);ht[f.id]=f,o.cubeCount++;var v=Array(6);return h(e,r,n,i,a,l),h.subimage=function(t,e,r,n,i){r|=0,n|=0,i|=0;var a=g();return u(a,f),a.width=0,a.height=0,p(a,e),a.width=a.width||(f.width>>i)-r,a.height=a.height||(f.height>>i)-n,I(f),d(a,34069+t,r,n,i),O(),M(a),h},h.resize=function(e){if((e|=0)!==f.width){h.width=f.width=e,h.height=f.height=e,I(f);for(var r=0;6>r;++r)for(var n=0;f.mipmask>>n;++n)t.texImage2D(34069+r,n,f.format,e>>n,e>>n,0,f.format,f.type,null);return O(),s.profile&&(f.stats.size=k(f.internalformat,f.type,h.width,h.height,!1,!0)),h}},h._reglType="textureCube",h._texture=f,s.profile&&(h.stats=f.stats),h.destroy=function(){f.decRef()},h},clear:function(){for(var e=0;er;++r)if(0!=(e.mipmask&1<>r,e.height>>r,0,e.internalformat,e.type,null);else for(var n=0;6>n;++n)t.texImage2D(34069+n,r,e.internalformat,e.width>>r,e.height>>r,0,e.internalformat,e.type,null);z(e.texInfo,e.target)})}}}function A(t,e,r,n,i,a){function o(t,e,r){this.target=t,this.texture=e,this.renderbuffer=r;var n=t=0;e?(t=e.width,n=e.height):r&&(t=r.width,n=r.height),this.width=t,this.height=n}function s(t){t&&(t.texture&&t.texture._texture.decRef(),t.renderbuffer&&t.renderbuffer._renderbuffer.decRef())}function l(t,e,r){t&&(t.texture?t.texture._texture.refCount+=1:t.renderbuffer._renderbuffer.refCount+=1)}function u(e,r){r&&(r.texture?t.framebufferTexture2D(36160,e,r.target,r.texture._texture.texture,0):t.framebufferRenderbuffer(36160,e,36161,r.renderbuffer._renderbuffer.renderbuffer))}function c(t){var e=3553,r=null,n=null,i=t;return"object"==typeof t&&(i=t.data,"target"in t&&(e=0|t.target)),"texture2d"===(t=i._reglType)?r=i:"textureCube"===t?r=i:"renderbuffer"===t&&(n=i,e=36161),new o(e,r,n)}function h(t,e,r,a,s){return r?((t=n.create2D({width:t,height:e,format:a,type:s}))._texture.refCount=0,new o(3553,t,null)):((t=i.create({width:t,height:e,format:a}))._renderbuffer.refCount=0,new o(36161,null,t))}function f(t){return t&&(t.texture||t.renderbuffer)}function p(t,e,r){t&&(t.texture?t.texture.resize(e,r):t.renderbuffer&&t.renderbuffer.resize(e,r))}function d(){this.id=k++,M[this.id]=this,this.framebuffer=t.createFramebuffer(),this.height=this.width=0,this.colorAttachments=[],this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function g(t){t.colorAttachments.forEach(s),s(t.depthAttachment),s(t.stencilAttachment),s(t.depthStencilAttachment)}function v(e){t.deleteFramebuffer(e.framebuffer),e.framebuffer=null,a.framebufferCount--,delete M[e.id]}function m(e){var n;t.bindFramebuffer(36160,e.framebuffer);var i=e.colorAttachments;for(n=0;ni;++i){for(u=0;ut;++t)r[t].resize(n);return e.width=e.height=n,e},_reglType:"framebufferCube",destroy:function(){r.forEach(function(t){t.destroy()})}})},clear:function(){W(M).forEach(v)},restore:function(){W(M).forEach(function(e){e.framebuffer=t.createFramebuffer(),m(e)})}})}function T(){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 S(t,e,r,n){function i(t,e,r,n){this.name=t,this.id=e,this.location=r,this.info=n}function a(t,e){for(var r=0;rt&&(t=e.stats.uniformsCount)}),t},r.getMaxAttributesCount=function(){var t=0;return f.forEach(function(e){e.stats.attributesCount>t&&(t=e.stats.attributesCount)}),t}),{clear:function(){var e=t.deleteShader.bind(t);W(u).forEach(e),u={},W(c).forEach(e),c={},f.forEach(function(e){t.deleteProgram(e.program)}),f.length=0,h={},r.shaderCount=0},program:function(t,e,n){var i=h[e];i||(i=h[e]={});var a=i[t];return a||(a=new s(e,t),r.shaderCount++,l(a),i[t]=a,f.push(a)),a},restore:function(){u={},c={};for(var t=0;t="+e+"?"+i+".constant["+e+"]:0;"}).join(""),"}}else{","if(",o,"(",i,".buffer)){",c,"=",s,".createStream(",34962,",",i,".buffer);","}else{",c,"=",s,".getBuffer(",i,".buffer);","}",h,'="type" in ',i,"?",a.glTypes,"[",i,".type]:",c,".dtype;",l.normalized,"=!!",i,".normalized;"),n("size"),n("offset"),n("stride"),n("divisor"),r("}}"),r.exit("if(",l.isStream,"){",s,".destroyStream(",c,");","}"),l})}),o}function A(t,e,r,n,i){var a=_(t),s=function(t,e,r){function n(t){if(t in i){var r=i[t];t=!0;var n,o,s=0|r.x,l=0|r.y;return"width"in r?n=0|r.width:t=!1,"height"in r?o=0|r.height:t=!1,new I(!t&&e&&e.thisDep,!t&&e&&e.contextDep,!t&&e&&e.propDep,function(t,e){var i=t.shared.context,a=n;"width"in r||(a=e.def(i,".","framebufferWidth","-",s));var u=o;return"height"in r||(u=e.def(i,".","framebufferHeight","-",l)),[s,l,a,u]})}if(t in a){var u=a[t];return t=B(u,function(t,e){var r=t.invoke(e,u),n=t.shared.context,i=e.def(r,".x|0"),a=e.def(r,".y|0");return[i,a,e.def('"width" in ',r,"?",r,".width|0:","(",n,".","framebufferWidth","-",i,")"),r=e.def('"height" in ',r,"?",r,".height|0:","(",n,".","framebufferHeight","-",a,")")]}),e&&(t.thisDep=t.thisDep||e.thisDep,t.contextDep=t.contextDep||e.contextDep,t.propDep=t.propDep||e.propDep),t}return e?new I(e.thisDep,e.contextDep,e.propDep,function(t,e){var r=t.shared.context;return[0,0,e.def(r,".","framebufferWidth"),e.def(r,".","framebufferHeight")]}):null}var i=t.static,a=t.dynamic;if(t=n("viewport")){var o=t;t=new I(t.thisDep,t.contextDep,t.propDep,function(t,e){var r=o.append(t,e),n=t.shared.context;return e.set(n,".viewportWidth",r[2]),e.set(n,".viewportHeight",r[3]),r})}return{viewport:t,scissor_box:n("scissor.box")}}(t,a),l=k(t),u=function(t,e){var r=t.static,n=t.dynamic,i={};return nt.forEach(function(t){function e(e,o){if(t in r){var s=e(r[t]);i[a]=R(function(){return s})}else if(t in n){var l=n[t];i[a]=B(l,function(t,e){return o(t,e,t.invoke(e,l))})}}var a=v(t);switch(t){case"cull.enable":case"blend.enable":case"dither":case"stencil.enable":case"depth.enable":case"scissor.enable":case"polygonOffset.enable":case"sample.alpha":case"sample.enable":case"depth.mask":return e(function(t){return t},function(t,e,r){return r});case"depth.func":return e(function(t){return yt[t]},function(t,e,r){return e.def(t.constants.compareFuncs,"[",r,"]")});case"depth.range":return e(function(t){return t},function(t,e,r){return[e.def("+",r,"[0]"),e=e.def("+",r,"[1]")]});case"blend.func":return e(function(t){return[mt["srcRGB"in t?t.srcRGB:t.src],mt["dstRGB"in t?t.dstRGB:t.dst],mt["srcAlpha"in t?t.srcAlpha:t.src],mt["dstAlpha"in t?t.dstAlpha:t.dst]]},function(t,e,r){function n(t,n){return e.def('"',t,n,'" in ',r,"?",r,".",t,n,":",r,".",t)}t=t.constants.blendFuncs;var i=n("src","RGB"),a=n("dst","RGB"),o=(i=e.def(t,"[",i,"]"),e.def(t,"[",n("src","Alpha"),"]"));return[i,a=e.def(t,"[",a,"]"),o,t=e.def(t,"[",n("dst","Alpha"),"]")]});case"blend.equation":return e(function(t){return"string"==typeof t?[J[t],J[t]]:"object"==typeof t?[J[t.rgb],J[t.alpha]]:void 0},function(t,e,r){var n=t.constants.blendEquations,i=e.def(),a=e.def();return(t=t.cond("typeof ",r,'==="string"')).then(i,"=",a,"=",n,"[",r,"];"),t.else(i,"=",n,"[",r,".rgb];",a,"=",n,"[",r,".alpha];"),e(t),[i,a]});case"blend.color":return e(function(t){return o(4,function(e){return+t[e]})},function(t,e,r){return o(4,function(t){return e.def("+",r,"[",t,"]")})});case"stencil.mask":return e(function(t){return 0|t},function(t,e,r){return e.def(r,"|0")});case"stencil.func":return e(function(t){return[yt[t.cmp||"keep"],t.ref||0,"mask"in t?t.mask:-1]},function(t,e,r){return[t=e.def('"cmp" in ',r,"?",t.constants.compareFuncs,"[",r,".cmp]",":",7680),e.def(r,".ref|0"),e=e.def('"mask" in ',r,"?",r,".mask|0:-1")]});case"stencil.opFront":case"stencil.opBack":return e(function(e){return["stencil.opBack"===t?1029:1028,xt[e.fail||"keep"],xt[e.zfail||"keep"],xt[e.zpass||"keep"]]},function(e,r,n){function i(t){return r.def('"',t,'" in ',n,"?",a,"[",n,".",t,"]:",7680)}var a=e.constants.stencilOps;return["stencil.opBack"===t?1029:1028,i("fail"),i("zfail"),i("zpass")]});case"polygonOffset.offset":return e(function(t){return[0|t.factor,0|t.units]},function(t,e,r){return[e.def(r,".factor|0"),e=e.def(r,".units|0")]});case"cull.face":return e(function(t){var e=0;return"front"===t?e=1028:"back"===t&&(e=1029),e},function(t,e,r){return e.def(r,'==="front"?',1028,":",1029)});case"lineWidth":return e(function(t){return t},function(t,e,r){return r});case"frontFace":return e(function(t){return bt[t]},function(t,e,r){return e.def(r+'==="cw"?2304:2305')});case"colorMask":return e(function(t){return t.map(function(t){return!!t})},function(t,e,r){return o(4,function(t){return"!!"+r+"["+t+"]"})});case"sample.coverage":return e(function(t){return["value"in t?t.value:1,!!t.invert]},function(t,e,r){return[e.def('"value" in ',r,"?+",r,".value:1"),e=e.def("!!",r,".invert")]})}}),i}(t),c=w(t),h=s.viewport;return h&&(u.viewport=h),(s=s[h=v("scissor.box")])&&(u[h]=s),(a={framebuffer:a,draw:l,shader:c,state:u,dirty:s=0>1)",s],");")}function e(){r(l,".drawArraysInstancedANGLE(",[d,g,v,s],");")}p?y?t():(r("if(",p,"){"),t(),r("}else{"),e(),r("}")):e()}function o(){function t(){r(c+".drawElements("+[d,v,m,g+"<<(("+m+"-5121)>>1)"]+");")}function e(){r(c+".drawArrays("+[d,g,v]+");")}p?y?t():(r("if(",p,"){"),t(),r("}else{"),e(),r("}")):e()}var s,l,u=t.shared,c=u.gl,h=u.draw,f=n.draw,p=function(){var i=f.elements,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(h,".","elements"),i&&a("if("+i+")"+c+".bindBuffer(34963,"+i+".buffer.buffer);"),i}(),d=i("primitive"),g=i("offset"),v=function(){var i=f.count,a=e;return i?((i.contextDep&&n.contextDynamic||i.propDep)&&(a=r),i=i.append(t,a)):i=a.def(h,".","count"),i}();if("number"==typeof v){if(0===v)return}else r("if(",v,"){"),r.exit("}");Q&&(s=i("instances"),l=t.instancing);var m=p+".type",y=f.elements&&O(f.elements);Q&&("number"!=typeof s||0<=s)?"string"==typeof s?(r("if(",s,">0){"),a(),r("}else if(",s,"<0){"),o(),r("}")):a():o()}function q(t,e,r,n,i){return i=(e=b()).proc("body",i),Q&&(e.instancing=i.def(e.shared.extensions,".angle_instanced_arrays")),t(e,i,r,n),e.compile().body}function H(t,e,r,n){L(t,e),N(t,e,r,n.attributes,function(){return!0}),j(t,e,r,n.uniforms,function(){return!0}),V(t,e,e,r)}function G(t,e,r,n){function i(){return!0}t.batchId="a1",L(t,e),N(t,e,r,n.attributes,i),j(t,e,r,n.uniforms,i),V(t,e,e,r)}function W(t,e,r,n){function i(t){return t.contextDep&&o||t.propDep}function a(t){return!i(t)}L(t,e);var o=r.contextDep,s=e.def(),l=e.def();t.shared.props=l,t.batchId=s;var u=t.scope(),c=t.scope();e(u.entry,"for(",s,"=0;",s,"<","a1",";++",s,"){",l,"=","a0","[",s,"];",c,"}",u.exit),r.needsContext&&T(t,c,r.context),r.needsFramebuffer&&S(t,c,r.framebuffer),E(t,c,r.state,i),r.profile&&i(r.profile)&&F(t,c,r,!1,!0),n?(N(t,u,r,n.attributes,a),N(t,c,r,n.attributes,i),j(t,u,r,n.uniforms,a),j(t,c,r,n.uniforms,i),V(t,u,c,r)):(e=t.global.def("{}"),n=r.shader.progVar.append(t,c),l=c.def(n,".id"),u=c.def(e,"[",l,"]"),c(t.shared.gl,".useProgram(",n,".program);","if(!",u,"){",u,"=",e,"[",l,"]=",t.link(function(e){return q(G,t,r,e,2)}),"(",n,");}",u,".call(this,a0[",s,"],",s,");"))}function Y(t,r){function n(e){var n=r.shader[e];n&&i.set(a.shader,"."+e,n.append(t,i))}var i=t.proc("scope",3);t.batchId="a2";var a=t.shared,o=a.current;T(t,i,r.context),r.framebuffer&&r.framebuffer.append(t,i),D(Object.keys(r.state)).forEach(function(e){var n=r.state[e].append(t,i);m(n)?n.forEach(function(r,n){i.set(t.next[e],"["+n+"]",r)}):i.set(a.next,"."+e,n)}),F(t,i,r,!0,!0),["elements","offset","count","instances","primitive"].forEach(function(e){var n=r.draw[e];n&&i.set(a.draw,"."+e,""+n.append(t,i))}),Object.keys(r.uniforms).forEach(function(n){i.set(a.uniforms,"["+e.id(n)+"]",r.uniforms[n].append(t,i))}),Object.keys(r.attributes).forEach(function(e){var n=r.attributes[e].append(t,i),a=t.scopeAttrib(e);Object.keys(new Z).forEach(function(t){i.set(a,"."+t,n[t])})}),n("vert"),n("frag"),0=--this.refCount&&o(this)},i.profile&&(n.getTotalRenderbufferSize=function(){var t=0;return Object.keys(c).forEach(function(e){t+=c[e].stats.size}),t}),{create:function(e,r){function o(e,r){var n=0,a=0,c=32854;if("object"==typeof e&&e?("shape"in e?(n=0|(a=e.shape)[0],a=0|a[1]):("radius"in e&&(n=a=0|e.radius),"width"in e&&(n=0|e.width),"height"in e&&(a=0|e.height)),"format"in e&&(c=s[e.format])):"number"==typeof e?(n=0|e,a="number"==typeof r?0|r:n):e||(n=a=1),n!==u.width||a!==u.height||c!==u.format)return o.width=u.width=n,o.height=u.height=a,u.format=c,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,c,n,a),i.profile&&(u.stats.size=ht[u.format]*u.width*u.height),o.format=l[u.format],o}var u=new a(t.createRenderbuffer());return c[u.id]=u,n.renderbufferCount++,o(e,r),o.resize=function(e,r){var n=0|e,a=0|r||n;return n===u.width&&a===u.height?o:(o.width=u.width=n,o.height=u.height=a,t.bindRenderbuffer(36161,u.renderbuffer),t.renderbufferStorage(36161,u.format,n,a),i.profile&&(u.stats.size=ht[u.format]*u.width*u.height),o)},o._reglType="renderbuffer",o._renderbuffer=u,i.profile&&(o.stats=u.stats),o.destroy=function(){u.decRef()},o},clear:function(){W(c).forEach(o)},restore:function(){W(c).forEach(function(e){e.renderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(36161,e.renderbuffer),t.renderbufferStorage(36161,e.format,e.width,e.height)}),t.bindRenderbuffer(36161,null)}}},pt=[];pt[6408]=4;var dt=[];dt[5121]=1,dt[5126]=4,dt[36193]=2;var gt=["x","y","z","w"],vt="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),mt={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},yt={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},xt={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386},bt={cw:2304,ccw:2305},_t=new I(!1,!1,!1,function(){});return function(t){function e(){if(0===X.length)w&&w.update(),Q=null;else{Q=q.next(e),h();for(var t=X.length-1;0<=t;--t){var r=X[t];r&&r(P,null,0)}v.flush(),w&&w.update()}}function r(){!Q&&0=X.length&&n()}}}}function c(){var t=W.viewport,e=W.scissor_box;t[0]=t[1]=e[0]=e[1]=0,P.viewportWidth=P.framebufferWidth=P.drawingBufferWidth=t[2]=e[2]=v.drawingBufferWidth,P.viewportHeight=P.framebufferHeight=P.drawingBufferHeight=t[3]=e[3]=v.drawingBufferHeight}function h(){P.tick+=1,P.time=p(),c(),G.procs.poll()}function f(){c(),G.procs.refresh(),w&&w.update()}function p(){return(H()-k)/1e3}if(!(t=i(t)))return null;var v=t.gl,m=v.getContextAttributes();v.isContextLost();var y=function(t,e){function r(e){var r;e=e.toLowerCase();try{r=n[e]=t.getExtension(e)}catch(t){}return!!r}for(var n={},i=0;ie;++e)$(j({framebuffer:t.framebuffer.faces[e]},t),l);else $(t,l);else l(0,t)},prop:U.define.bind(null,1),context:U.define.bind(null,2),this:U.define.bind(null,3),draw:s({}),buffer:function(t){return D.create(t,34962,!1,!1)},elements:function(t){return I.create(t,!1)},texture:R.create2D,cube:R.createCube,renderbuffer:B.create,framebuffer:V.create,framebufferCube:V.createCube,attributes:m,frame:u,on:function(t,e){var r;switch(t){case"frame":return u(e);case"lost":r=Z;break;case"restore":r=J;break;case"destroy":r=K}return r.push(e),{cancel:function(){for(var t=0;t=0;a--){var o=t[a];if(e>MB(n,o))return wB(n,i);if(e>o||a===t.length-1)return wB(o,n);i=n,n=o}}function SB(t,e){for(var r=0;r=e[r][0]&&t<=e[r][1])return!0;return!1}function CB(t){t.attr("x",-mB.bar.captureWidth/2).attr("width",mB.bar.captureWidth)}function EB(t){t.attr("visibility","visible").style("visibility","visible").attr("fill","yellow").attr("opacity",0)}function LB(t){if(!t.brush.filterSpecified)return"0,"+t.height;for(var e,r,n,i=PB(t.brush.filter.getConsolidated(),t.height),a=[0],o=i.length?i[0][0]:null,s=0;se){h=r;break}}if(i=u,isNaN(i)&&(i=isNaN(c)||isNaN(h)?isNaN(c)?h:c:e-l[c][1]t[1]+r||e=.9*t[1]+.1*t[0]?"n":e<=.9*t[0]+.1*t[1]?"s":"ns"}(p,e);d&&(a.interval=s[i],a.intervalPix=p,a.region=d)}}if(t.ordinal&&!a.region){var g=t.unitTickvals,v=t.unitToPaddedPx.invert(e);for(r=0;r=m[0]&&v<=m[1]){a.clickableOrdinalRange=m;break}}}return a}function RB(t){t.on("mousemove",function(t){if(i.event.preventDefault(),!t.parent.inBrushDrag){var e=OB(t,t.height-i.mouse(this)[1]-2*mB.verticalPadding),r="crosshair";e.clickableOrdinalRange?r="pointer":e.region&&(r=e.region+"-resize"),i.select(document.body).style("cursor",r)}}).on("mouseleave",function(t){t.parent.inBrushDrag||zB()}).call(i.behavior.drag().on("dragstart",function(t){i.event.sourceEvent.stopPropagation();var e=t.height-i.mouse(this)[1]-2*mB.verticalPadding,r=t.unitToPaddedPx.invert(e),n=t.brush,a=OB(t,e),o=a.interval,s=n.svgBrush;if(s.wasDragged=!1,s.grabbingBar="ns"===a.region,s.grabbingBar){var l=o.map(t.unitToPaddedPx);s.grabPoint=e-l[0]-mB.verticalPadding,s.barLength=l[1]-l[0]}s.clickableOrdinalRange=a.clickableOrdinalRange,s.stayingIntervals=t.multiselect&&n.filterSpecified?n.filter.getConsolidated():[],o&&(s.stayingIntervals=s.stayingIntervals.filter(function(t){return t[0]!==o[0]&&t[1]!==o[1]})),s.startExtent=a.region?o["s"===a.region?1:0]:r,t.parent.inBrushDrag=!0,s.brushStartCallback()}).on("drag",function(t){i.event.sourceEvent.stopPropagation();var e=t.height-i.mouse(this)[1]-2*mB.verticalPadding,r=t.brush.svgBrush;r.wasDragged=!0,r.grabbingBar?r.newExtent=[e-r.grabPoint,e+r.barLength-r.grabPoint].map(t.unitToPaddedPx.invert):r.newExtent=[r.startExtent,t.unitToPaddedPx.invert(e)].sort(bB);var n=Math.max(0,-r.newExtent[0]),a=Math.max(0,r.newExtent[1]-1);r.newExtent[0]+=n,r.newExtent[1]-=a,r.grabbingBar&&(r.newExtent[1]+=n,r.newExtent[0]-=a),t.brush.filterSpecified=!0,r.extent=r.stayingIntervals.concat([r.newExtent]),r.brushCallback(t),IB(this.parentNode)}).on("dragend",function(t){i.event.sourceEvent.stopPropagation();var e=t.brush,r=e.filter,n=e.svgBrush,a=n.grabbingBar;if(n.grabbingBar=!1,n.grabLocation=void 0,t.parent.inBrushDrag=!1,zB(),!n.wasDragged)return n.wasDragged=void 0,n.clickableOrdinalRange?e.filterSpecified&&t.multiselect?n.extent.push(n.clickableOrdinalRange):(n.extent=[n.clickableOrdinalRange],e.filterSpecified=!0):a?(n.extent=n.stayingIntervals,0===n.extent.length&&FB(e)):FB(e),n.brushCallback(t),IB(this.parentNode),void n.brushEndCallback(e.filterSpecified?r.getConsolidated():[]);var o=function(){r.set(r.getConsolidated())};if(t.ordinal){var s=t.unitTickvals;s[s.length-1]n.newExtent[0];n.extent=n.stayingIntervals.concat(l?[n.newExtent]:[]),n.extent.length||FB(e),n.brushCallback(t),l?IB(this.parentNode,o):(o(),IB(this.parentNode))}else o();n.brushEndCallback(e.filterSpecified?r.getConsolidated():[])}))}function BB(t,e){return t[0]-e[0]}function FB(t){t.filterSpecified=!1,t.svgBrush.extent=[[0,1]]}function NB(t){for(var e,r=t.slice(),n=[],i=r.shift();i;){for(e=i.slice();(i=r.shift())&&i[0]<=e[1];)e[1]=Math.max(e[1],i[1]);n.push(e)}return n}var jB={makeBrush:function(t,e,r,n,i,a){var o,s=function(){var t,e,r=[];return{set:function(n){r=n.map(function(t){return t.slice().sort(bB)}).sort(BB),t=NB(r),e=r.reduce(function(t,e){return[Math.min(t[0],e[0]),Math.max(t[1],e[1])]},[1/0,-1/0])},get:function(){return r.slice()},getConsolidated:function(){return t},getBounds:function(){return e}}}();return s.set(r),{filter:s,filterSpecified:e,svgBrush:{extent:[],brushStartCallback:n,brushCallback:(o=i,function(t){var e=t.brush,r=function(t){return t.svgBrush.extent.map(function(t){return t.slice()})}(e).slice();e.filter.set(r),o()}),brushEndCallback:a}}},ensureAxisBrush:function(t){var e=t.selectAll("."+mB.cn.axisBrush).data(xB,yB);e.enter().append("g").classed(mB.cn.axisBrush,!0),function(t){var e=t.selectAll(".background").data(xB);e.enter().append("rect").classed("background",!0).call(CB).call(EB).style("pointer-events","auto").attr("transform","translate(0 "+mB.verticalPadding+")"),e.call(RB).attr("height",function(t){return t.height-mB.verticalPadding});var r=t.selectAll(".highlight-shadow").data(xB);r.enter().append("line").classed("highlight-shadow",!0).attr("x",-mB.bar.width/2).attr("stroke-width",mB.bar.width+mB.bar.strokeWidth).attr("stroke",mB.bar.strokeColor).attr("opacity",mB.bar.strokeOpacity).attr("stroke-linecap","butt"),r.attr("y1",function(t){return t.height}).call(DB);var n=t.selectAll(".highlight").data(xB);n.enter().append("line").classed("highlight",!0).attr("x",-mB.bar.width/2).attr("stroke-width",mB.bar.width-mB.bar.strokeWidth).attr("stroke",mB.bar.fillColor).attr("opacity",mB.bar.fillOpacity).attr("stroke-linecap","butt"),n.attr("y1",function(t){return t.height}).call(DB)}(e)},cleanRanges:function(t,e){if(Array.isArray(t[0])?(t=t.map(function(t){return t.sort(bB)}),t=e.multiselect?NB(t.sort(BB)):[t[0]]):t=[t.sort(bB)],e.tickvals){var r=e.tickvals.slice().sort(bB);if(!(t=t.map(function(t){var e=[AB(r,t[0],[]),TB(r,t[1],[])];if(e[1]>e[0])return e}).filter(function(t){return t})).length)return}return t.length>1?t:t[0]}},VB=Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),UB=Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D palette;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec2 xyProjection = vec2(1, 1);\n\nvec4 unit = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit, unit);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depth,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D\n );\n\n float clampedColorIndex = clamp((prominence - colorClamp[0]) / (colorClamp[1] - colorClamp[0]), 0.0, 1.0);\n fragColor = texture2D(palette, vec2((clampedColorIndex * 255.0 + 0.5) / 256.0, 0.5));\n}\n"]),qB=Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec4 p0, p1, p2, p3,\n p4, p5, p6, p7,\n p8, p9, pa, pb,\n pc, pd, pe;\n\nattribute vec4 pf;\n\nuniform mat4 dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD;\n\nuniform vec2 resolution,\n viewBoxPosition,\n viewBoxSize;\n\nuniform sampler2D mask;\nuniform float maskHeight;\n\nuniform vec2 colorClamp;\n\nvarying vec4 fragColor;\n\nvec4 unit_1 = vec4(1, 1, 1, 1);\n\nfloat val(mat4 p, mat4 v) {\n return dot(matrixCompMult(p, v) * unit_1, unit_1);\n}\n\nfloat axisY(\n float x,\n mat4 d[4],\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D\n ) {\n\n float y1 = val(d[0], dim1A) + val(d[1], dim1B) + val(d[2], dim1C) + val(d[3], dim1D);\n float y2 = val(d[0], dim2A) + val(d[1], dim2B) + val(d[2], dim2C) + val(d[3], dim2D);\n return y1 * (1.0 - x) + y2 * x;\n}\n\nconst int bitsPerByte = 8;\n\nint mod2(int a) {\n return a - 2 * (a / 2);\n}\n\nint mod8(int a) {\n return a - 8 * (a / 8);\n}\n\nvec4 zero = vec4(0, 0, 0, 0);\nvec4 unit_0 = vec4(1, 1, 1, 1);\nvec2 xyProjection = vec2(1, 1);\n\nmat4 mclamp(mat4 m, mat4 lo, mat4 hi) {\n return mat4(clamp(m[0], lo[0], hi[0]),\n clamp(m[1], lo[1], hi[1]),\n clamp(m[2], lo[2], hi[2]),\n clamp(m[3], lo[3], hi[3]));\n}\n\nbool mshow(mat4 p, mat4 lo, mat4 hi) {\n return mclamp(p, lo, hi) == p;\n}\n\nbool withinBoundingBox(\n mat4 d[4],\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD\n ) {\n\n return mshow(d[0], loA, hiA) &&\n mshow(d[1], loB, hiB) &&\n mshow(d[2], loC, hiC) &&\n mshow(d[3], loD, hiD);\n}\n\nbool withinRasterMask(mat4 d[4], sampler2D mask, float height) {\n bool result = true;\n int bitInByteStepper;\n float valY, valueY, scaleX;\n int hit, bitmask, valX;\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 bitInByteStepper = mod8(j * 4 + k);\n valX = i * 2 + j / 2;\n valY = d[i][j][k];\n valueY = valY * (height - 1.0) + 0.5;\n scaleX = (float(valX) + 0.5) / 8.0;\n hit = int(texture2D(mask, vec2(scaleX, (valueY + 0.5) / height))[3] * 255.0) / int(pow(2.0, float(bitInByteStepper)));\n result = result && mod2(hit) == 1;\n }\n }\n }\n return result;\n}\n\nvec4 position(\n float depth,\n vec2 resolution, vec2 viewBoxPosition, vec2 viewBoxSize,\n mat4 dims[4],\n float signum,\n mat4 dim1A, mat4 dim2A, mat4 dim1B, mat4 dim2B, mat4 dim1C, mat4 dim2C, mat4 dim1D, mat4 dim2D,\n mat4 loA, mat4 hiA, mat4 loB, mat4 hiB, mat4 loC, mat4 hiC, mat4 loD, mat4 hiD,\n sampler2D mask, float maskHeight\n ) {\n\n float x = 0.5 * signum + 0.5;\n float y = axisY(x, dims, dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D);\n\n float show = float(\n withinBoundingBox(dims, loA, hiA, loB, hiB, loC, hiC, loD, hiD)\n && withinRasterMask(dims, mask, maskHeight)\n );\n\n vec2 viewBoxXY = viewBoxPosition + viewBoxSize * vec2(x, y);\n float depthOrHide = depth + 2.0 * (1.0 - show);\n\n return vec4(\n xyProjection * (2.0 * viewBoxXY / resolution - 1.0),\n depthOrHide,\n 1.0\n );\n}\n\nvoid main() {\n\n float prominence = abs(pf[3]);\n\n mat4 p[4];\n p[0] = mat4(p0, p1, p2, p3);\n p[1] = mat4(p4, p5, p6, p7);\n p[2] = mat4(p8, p9, pa, pb);\n p[3] = mat4(pc, pd, pe, abs(pf));\n\n gl_Position = position(\n 1.0 - prominence,\n resolution, viewBoxPosition, viewBoxSize,\n p,\n sign(pf[3]),\n dim1A, dim2A, dim1B, dim2B, dim1C, dim2C, dim1D, dim2D,\n loA, hiA, loB, hiB, loC, hiC, loD, hiD,\n mask, maskHeight\n );\n\n fragColor = vec4(pf.rgb, 1.0);\n}\n"]),HB=Q_(["precision lowp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}\n"]),GB=1e-6,WB=1e-7,YB=2048,XB=64,ZB=2,JB=4,KB=8,QB=XB/KB,$B=[119,119,119],tF=new Uint8Array(4),eF=new Uint8Array(4),rF={shape:[256,1],format:"rgba",type:"uint8",mag:"nearest",min:"nearest"};function nF(t,e,r,n,i){var a=t._gl;a.enable(a.SCISSOR_TEST),a.scissor(e,r,n,i),t.clear({color:[0,0,0,0],depth:1})}function iF(t,e,r,n,i,a){var o=a.key;r.drawCompleted||(!function(t){t.read({x:0,y:0,width:1,height:1,data:tF})}(t),r.drawCompleted=!0),function s(l){var u;u=Math.min(n,i-l*n),a.offset=ZB*l*n,a.count=ZB*u,0===l&&(window.cancelAnimationFrame(r.currentRafs[o]),delete r.currentRafs[o],nF(t,a.scissorX,a.scissorY,a.scissorWidth,a.viewBoxSize[1])),r.clearOnly||(e(a),l*n+u>>8*e)%256/255}function oF(t,e,r){var n,i,a,o=[];for(i=0;i=XB-4?aF(o,XB-2-s):.5);return a}(a,i,o);!function(t,e,r){for(var n=0;n<16;n++)t["p"+n.toString(16)](oF(e,r,n))}(h,a,p),f=u.texture(oe.extendFlat({data:function(t,e,r){for(var n=[],i=0;i<256;i++){var a=t(i/255);n.push((e?$B:a).concat(r))}return n}(r.unitToColor,s,Math.round(255*(s?c:1)))},rF))}var g=[0,1];var v=[];function m(t,e,n,i,a,o,s,l,u,c,h){var f,p,d,v,m=[t,e],y=[0,1].map(function(){return[0,1,2,3].map(function(){return new Float32Array(16)})});for(f=0;f<2;f++)for(v=m[f],p=0;p<4;p++)for(d=0;d<16;d++)y[f][p][d]=d+16*p===v?1:0;var x=r.lines.canvasOverdrag,b=r.domain,_=r.canvasWidth,w=r.canvasHeight;return oe.extendFlat({key:s,resolution:[_,w],viewBoxPosition:[n+x,i],viewBoxSize:[a,o],i:t,ii:e,dim1A:y[0][0],dim1B:y[0][1],dim1C:y[0][2],dim1D:y[0][3],dim2A:y[1][0],dim2B:y[1][1],dim2C:y[1][2],dim2D:y[1][3],colorClamp:g,scissorX:(l===u?0:n+x)+(r.pad.l-x)+r.layoutWidth*b.x[0],scissorWidth:(l===c?_-n+x:a+.5)+(l===u?n+x:0),scissorY:i+r.pad.b+r.layoutHeight*b.y[0],scissorHeight:o,viewportX:r.pad.l-x+r.layoutWidth*b.x[0],viewportY:r.pad.b+r.layoutHeight*b.y[0],viewportWidth:_,viewportHeight:w},h)}return{setColorDomain:function(t){g[0]=t[0],g[1]=t[1]},render:function(t,e,n){var l,h,f,d=t.length,g=1/0,y=-1/0;for(l=0;ly&&(y=t[l].dim2.canvasX,f=l),t[l].dim1.canvasXn._length&&(x=x.slice(0,n._length));var b,_=n.tickvals;function w(t,e){return{val:t,text:b[e]}}function k(t,e){return t.val-e.val}if(Array.isArray(_)&&_.length){b=n.ticktext,Array.isArray(b)&&b.length?b.length>_.length?b=b.slice(0,_.length):_.length>b.length&&(_=_.slice(0,b.length)):b=_.map(i.format(n.tickformat));for(var M=1;M<_.length;M++)if(_[M]<_[M-1]){for(var A=_.map(w).sort(k),T=0;T<_.length;T++)_[T]=A[T].val,b[T]=A[T].text;break}}else _=void 0;return{key:g,label:n.label,tickFormat:n.tickformat,tickvals:_,ticktext:b,ordinal:!!_,multiselect:n.multiselect,xIndex:o,crossfilterDimensionIndex:o,visibleIndex:n._index,height:a,values:x,paddedUnitValues:x.map(p),unitTickvals:_&&_.map(p),xScale:l,x:l(o),canvasX:l(o)*s,unitToPaddedPx:c,domainScale:function(t,e,r,n,a){var o,s,l=fF(r);return n?i.scale.ordinal().domain(n.map((o=i.format(r.tickformat),s=a,s?function(t,e){var r=s[e];return null===r||void 0===r?o(t):r}:o))).range(n.map(function(r){var n=(r-l[0])/(l[1]-l[0]);return t-e+n*(2*e-t)})):i.scale.linear().domain(l).range([t-e,e])}(a,mB.verticalPadding,n,_,b),ordinalScale:function(t){if(t.tickvals){var e=fF(t);return i.scale.ordinal().domain(t.tickvals).range(t.tickvals.map(function(t){return(t-e[0])/(e[1]-e[0])}))}}(n),parent:h,model:r,brush:jB.makeBrush(t,m,y,function(){t.linePickActive(!1)},function(){var e=h;e.focusLayer&&e.focusLayer.render(e.panels,!0);var r=pF(e);!t.contextShown()&&r?(e.contextLayer&&e.contextLayer.render(e.panels,!0),t.contextShown(!0)):t.contextShown()&&!r&&(e.contextLayer&&e.contextLayer.render(e.panels,!0,!0),t.contextShown(!1))},function(r){var i=h;if(i.focusLayer.render(i.panels,!0),i.pickLayer&&i.pickLayer.render(i.panels,!0),t.linePickActive(!0),e&&e.filterChanged){var a=p.invert,o=r.map(function(t){return t.map(a).sort(oe.sorterAsc)}).sort(function(t,e){return t[0]-e[0]});e.filterChanged(i.key,n._index,o)}})}}),h}function vF(t){t.classed(mB.cn.axisExtentText,!0).attr("text-anchor","middle").style("cursor","default").style("user-select","none")}var mF=function(t,e){var r=t._fullLayout,n=r._toppaper,a=(r._paperdiv,r._glcontainer);dB(t);var o={},s={},l=r._size;e.forEach(function(e,r){o[r]=t.data[r].dimensions,s[r]=t.data[r].dimensions.slice()});!function(t,e,r,n,a,o){var s,l,u=(s=!0,l=!1,{linePickActive:function(t){return arguments.length?s=!!t:s},contextShown:function(t){return arguments.length?l=!!t:l}}),c=n.filter(function(t){return cF(t).trace.visible}).map(dF.bind(0,a)).map(gF.bind(0,u,o));r.each(function(t,e){return oe.extendFlat(t,c[e])});var h=r.selectAll(".gl-canvas").each(function(t){t.viewModel=c[0],t.model=t.viewModel?t.viewModel.model:null}),f=null;h.filter(function(t){return t.pick}).style("pointer-events","auto").on("mousemove",function(t){if(u.linePickActive()&&t.lineLayer&&o&&o.hover){var e=i.event,r=this.width,n=this.height,a=i.mouse(this),s=a[0],l=a[1];if(s<0||l<0||s>=r||l>=n)return;var c=t.lineLayer.readPixel(s,n-1-l),h=0!==c[3],p=h?c[2]+256*(c[1]+256*c[0]):null,d={x:s,y:l,clientX:e.clientX,clientY:e.clientY,dataIndex:t.model.key,curveNumber:p};p!==f&&(h?o.hover(d):o.unhover&&o.unhover(d),f=p)}}),h.style("opacity",function(t){return t.pick?.01:1}),e.style("background","rgba(255, 255, 255, 0)");var p=e.selectAll("."+mB.cn.parcoords).data(c,lF);p.exit().remove(),p.enter().append("g").classed(mB.cn.parcoords,!0).style("shape-rendering","crispEdges").style("pointer-events","none"),p.attr("transform",function(t){return"translate("+t.model.translateX+","+t.model.translateY+")"});var d=p.selectAll("."+mB.cn.parcoordsControlView).data(uF,lF);d.enter().append("g").classed(mB.cn.parcoordsControlView,!0),d.attr("transform",function(t){return"translate("+t.model.pad.l+","+t.model.pad.t+")"});var g=d.selectAll("."+mB.cn.yAxis).data(function(t){return t.dimensions},lF);function v(t,e){for(var r=e.panels||(e.panels=[]),n=t.data(),i=n.length-1,a=0;aline").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.25).attr("stroke-width","1px"),y.selectAll("text").style("text-shadow","1px 1px 1px #fff, -1px -1px 1px #fff, 1px -1px 1px #fff, -1px 1px 1px #fff").style("cursor","default").style("user-select","none");var x=m.selectAll("."+mB.cn.axisHeading).data(uF,lF);x.enter().append("g").classed(mB.cn.axisHeading,!0);var b=x.selectAll("."+mB.cn.axisTitle).data(uF,lF);b.enter().append("text").classed(mB.cn.axisTitle,!0).attr("text-anchor","middle").style("cursor","ew-resize").style("user-select","none").style("pointer-events","auto"),b.attr("transform","translate(0,"+-mB.axisTitleOffset+")").text(function(t){return t.label}).each(function(t){Lr.font(i.select(this),t.model.labelFont)});var _=m.selectAll("."+mB.cn.axisExtent).data(uF,lF);_.enter().append("g").classed(mB.cn.axisExtent,!0);var w=_.selectAll("."+mB.cn.axisExtentTop).data(uF,lF);w.enter().append("g").classed(mB.cn.axisExtentTop,!0),w.attr("transform","translate(0,"+-mB.axisExtentOffset+")");var k=w.selectAll("."+mB.cn.axisExtentTopText).data(uF,lF);function M(t,e){if(t.ordinal)return"";var r=t.domainScale.domain();return i.format(t.tickFormat)(r[e?r.length-1:0])}k.enter().append("text").classed(mB.cn.axisExtentTopText,!0).call(vF),k.text(function(t){return M(t,!0)}).each(function(t){Lr.font(i.select(this),t.model.rangeFont)});var A=_.selectAll("."+mB.cn.axisExtentBottom).data(uF,lF);A.enter().append("g").classed(mB.cn.axisExtentBottom,!0),A.attr("transform",function(t){return"translate(0,"+(t.model.height+mB.axisExtentOffset)+")"});var T=A.selectAll("."+mB.cn.axisExtentBottomText).data(uF,lF);T.enter().append("text").classed(mB.cn.axisExtentBottomText,!0).attr("dy","0.75em").call(vF),T.text(function(t){return M(t)}).each(function(t){Lr.font(i.select(this),t.model.rangeFont)}),jB.ensureAxisBrush(m)}(0,n,a,e,{width:l.w,height:l.h,margin:{t:l.t,r:l.r,b:l.b,l:l.l}},{filterChanged:function(e,r,n){var i=s[e][r],a=n.map(function(t){return t.slice()});a.length?(1===a.length&&(a=a[0]),i.constraintrange=a,a=[a]):(delete i.constraintrange,a=null);var o={};o["dimensions["+r+"].constraintrange"]=a,t.emit("plotly_restyle",[o,[e]])},hover:function(e){t.emit("plotly_hover",e)},unhover:function(e){t.emit("plotly_unhover",e)},axesMoved:function(e,r){function n(t){return!("visible"in t)||t.visible}function i(t,e,r){var n=e.indexOf(r),i=t.indexOf(n);return-1===i&&(i+=e.length),i}var a=function(t){return function(e,n){return i(r,t,e)-i(r,t,n)}}(s[e].filter(n));o[e].sort(a),s[e].filter(function(t){return!n(t)}).sort(function(t){return s[e].indexOf(t)}).forEach(function(t){o[e].splice(o[e].indexOf(t),1),o[e].splice(s[e].indexOf(t),0,t)}),t.emit("plotly_restyle")}})},yF={},xF=hs.getModuleCalcData;yF.name="parcoords",yF.plot=function(t){var e=xF(t.calcdata,"parcoords")[0];e.length&&mF(t,e)},yF.clean=function(t,e,r,n){var i=n._has&&n._has("parcoords"),a=e._has&&e._has("parcoords");i&&!a&&(n._paperdiv.selectAll(".parcoords").remove(),n._glimages.selectAll("*").remove())},yF.toSVG=function(t){var e=t._fullLayout._glimages,r=i.select(t).selectAll(".svg-container");r.filter(function(t,e){return e===r.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");e.append("svg:image").attr({xmlns:rr.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})}),window.setTimeout(function(){i.selectAll("#filterBarPattern").attr("id","filterBarPattern")},60)};var bF=vB.wrap;var _F=mB.maxDimensionCount,wF=zh.defaults;var kF={};kF.attributes=fB,kF.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,fB,r,n)}var a=function(t,e){var r,n,i,a=t.dimensions||[],o=e.dimensions=[],s=1/0;function l(t,e){return oe.coerce(r,n,fB.dimensions,t,e)}for(a.length>_F&&(oe.log("parcoords traces support up to "+_F+" dimensions at the moment"),a.splice(_F)),i=0;i0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}var VF={};VF.attributes=CF,VF.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,CF,r,n)}var a=oe.coerceFont,o=i("values"),s=i("labels");if(!Array.isArray(s)){if(!oe.isArrayOrTypedArray(o)||!o.length)return void(e.visible=!1);i("label0"),i("dlabel")}i("marker.line.width")&&i("marker.line.color"),i("marker.colors"),i("scalegroup");var l=i("text"),u=i("textinfo",Array.isArray(l)?"text+percent":"percent");if(i("hovertext"),u&&"none"!==u){var c=i("textposition"),h=Array.isArray(c)||"auto"===c,f=h||"inside"===c,p=h||"outside"===c;if(f||p){var d=a(i,"textfont",n.font);f&&a(i,"insidetextfont",d),p&&a(i,"outsidetextfont",d)}}OF(e,n,i),i("hole"),i("sort"),i("direction"),i("rotation"),i("pull")},VF.supplyLayoutDefaults=function(t,e){var r,n;r="hiddenlabels",oe.coerce(t,e,RF,r,n)},VF.layoutAttributes=RF,VF.calc=function(t,e){var r,n,i,o,s,l=e.values,u=zF(l)&&l.length,h=e.labels,f=e.marker.colors||[],p=[],d=t._fullLayout,g=d.colorway,v=d._piecolormap,m={},y=0,x=d.hiddenlabels||[];if(d._piecolorway||g===Fe.defaults||(d._piecolorway=IF(g)),e.dlabel)for(h=new Array(l.length),r=0;r")}}return p},VF.plot=function(t,e){var r=t._fullLayout;!function(t,e){var r,n,i,a,o,s,l,u,c,h=[];for(i=0;il&&(l=s.pull[a]);o.r=Math.min(r,n)/(2+2*l),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===h.indexOf(s.scalegroup)&&h.push(s.scalegroup)}for(a=0;ai.vTotal/2?1:0)}(e),n.each(function(){var n=i.select(this).selectAll("g.slice").data(e);n.enter().append("g").classed("slice",!0),n.exit().remove();var s=[[[],[]],[[],[]]],l=!1;n.each(function(e){if(e.hidden)i.select(this).selectAll("path,g").remove();else{e.pointNumber=e.i,e.curveNumber=o.index,s[e.pxmid[1]<0?0:1][e.pxmid[0]<0?0:1].push(e);var n=a.cx,u=a.cy,c=i.select(this),h=c.selectAll("path.surface").data([e]),f=!1,p=!1;if(h.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),c.select("path.textline").remove(),c.on("mouseover",function(){var s=t._fullLayout,l=t._fullData[o.index];if(!t._dragging&&!1!==s.hovermode){var c=l.hoverinfo;if(Array.isArray(c)&&(c=qa.castHoverinfo({hoverinfo:[Og.castOption(c,e.pts)],_module:o._module},s,0)),"all"===c&&(c="label+text+value+percent+name"),"none"!==c&&"skip"!==c&&c){var h=NF(e,a),d=n+e.pxmid[0]*(1-h),g=u+e.pxmid[1]*(1-h),v=r.separators,m=[];if(-1!==c.indexOf("label")&&m.push(e.label),-1!==c.indexOf("text")){var y=Og.castOption(l.hovertext||l.text,e.pts);y&&m.push(y)}-1!==c.indexOf("value")&&m.push(Og.formatPieValue(e.v,v)),-1!==c.indexOf("percent")&&m.push(Og.formatPiePercent(e.v/a.vTotal,v));var x=o.hoverlabel,b=x.font;qa.loneHover({x0:d-h*a.r,x1:d+h*a.r,y:g,text:m.join("
"),name:-1!==c.indexOf("name")?l.name:void 0,idealAlign:e.pxmid[0]<0?"left":"right",color:Og.castOption(x.bgcolor,e.pts)||e.color,borderColor:Og.castOption(x.bordercolor,e.pts),fontFamily:Og.castOption(b.family,e.pts),fontSize:Og.castOption(b.size,e.pts),fontColor:Og.castOption(b.color,e.pts)},{container:s._hoverlayer.node(),outerContainer:s._paper.node(),gd:t}),f=!0}t.emit("plotly_hover",{points:[FF(e,l)],event:i.event}),p=!0}}).on("mouseout",function(r){var n=t._fullLayout,a=t._fullData[o.index];p&&(r.originalEvent=i.event,t.emit("plotly_unhover",{points:[FF(e,a)],event:i.event}),p=!1),f&&(qa.loneUnhover(n._hoverlayer.node()),f=!1)}).on("click",function(){var r=t._fullLayout,n=t._fullData[o.index];t._dragging||!1===r.hovermode||(t._hoverdata=[FF(e,n)],qa.click(t,i.event))}),o.pull){var d=+Og.castOption(o.pull,e.pts)||0;d>0&&(n+=d*e.pxmid[0],u+=d*e.pxmid[1])}e.cxFinal=n,e.cyFinal=u;var g=o.hole;if(e.v===a.vTotal){var v="M"+(n+e.px0[0])+","+(u+e.px0[1])+_(e.px0,e.pxmid,!0,1)+_(e.pxmid,e.px0,!0,1)+"Z";g?h.attr("d","M"+(n+g*e.px0[0])+","+(u+g*e.px0[1])+_(e.px0,e.pxmid,!1,g)+_(e.pxmid,e.px0,!1,g)+"Z"+v):h.attr("d",v)}else{var m=_(e.px0,e.px1,!0,1);if(g){var y=1-g;h.attr("d","M"+(n+g*e.px1[0])+","+(u+g*e.px1[1])+_(e.px1,e.px0,!1,g)+"l"+y*e.px0[0]+","+y*e.px0[1]+m+"Z")}else h.attr("d","M"+n+","+u+"l"+e.px0[0]+","+e.px0[1]+m+"Z")}var x=Og.castOption(o.textposition,e.pts),b=c.selectAll("g.slicetext").data(e.text&&"none"!==x?[0]:[]);b.enter().append("g").classed("slicetext",!0),b.exit().remove(),b.each(function(){var r=oe.ensureSingle(i.select(this),"text","",function(t){t.attr("data-notex",1)});r.text(e.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Lr.font,"outside"===x?o.outsidetextfont:o.insidetextfont).call(ir.convertToTspans,t);var s,c=Lr.bBox(r.node());"outside"===x?s=jF(c,e):(s=function(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),i=t.width/t.height,a=Math.PI*Math.min(e.v/r.vTotal,.5),o=1-r.trace.hole,s=NF(e,r),l={scale:s*r.r*2/n,rCenter:1-s,rotate:0};if(l.scale>=1)return l;var u=i+1/(2*Math.tan(a)),c=r.r*Math.min(1/(Math.sqrt(u*u+.5)+u),o/(Math.sqrt(i*i+o/2)+i)),h={scale:2*c/t.height,rCenter:Math.cos(c/r.r)-c*i/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},f=1/i,p=f+1/(2*Math.tan(a)),d=r.r*Math.min(1/(Math.sqrt(p*p+.5)+p),o/(Math.sqrt(f*f+o/2)+f)),g={scale:2*d/t.width,rCenter:Math.cos(d/r.r)-d/i/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},v=g.scale>h.scale?g:h;return l.scale<1&&v.scale>l.scale?v:l}(c,e,a),"auto"===x&&s.scale<1&&(r.call(Lr.font,o.outsidetextfont),o.outsidetextfont.family===o.insidetextfont.family&&o.outsidetextfont.size===o.insidetextfont.size||(c=Lr.bBox(r.node())),s=jF(c,e)));var h=n+e.pxmid[0]*s.rCenter+(s.x||0),f=u+e.pxmid[1]*s.rCenter+(s.y||0);s.outside&&(e.yLabelMin=f-c.height/2,e.yLabelMid=f,e.yLabelMax=f+c.height/2,e.labelExtraX=0,e.labelExtraY=0,l=!0),r.attr("transform","translate("+h+","+f+")"+(s.scale<1?"scale("+s.scale+")":"")+(s.rotate?"rotate("+s.rotate+")":"")+"translate("+-(c.left+c.right)/2+","+-(c.top+c.bottom)/2+")")})}function _(t,r,n,i){return"a"+i*a.r+","+i*a.r+" 0 "+e.largeArc+(n?" 1 ":" 0 ")+i*(r[0]-t[0])+","+i*(r[1]-t[1])}}),l&&function(t,e){var r,n,i,a,o,s,l,u,c,h,f,p,d;function g(t,e){return t.pxmid[1]-e.pxmid[1]}function v(t,e){return e.pxmid[1]-t.pxmid[1]}function m(t,r){r||(r={});var i,u,c,f,p,d,g=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),v=n?t.yLabelMin:t.yLabelMax,m=n?t.yLabelMax:t.yLabelMin,y=t.cyFinal+o(t.px0[1],t.px1[1]),x=g-v;if(x*l>0&&(t.labelExtraY=x),Array.isArray(e.pull))for(u=0;u=(Og.castOption(e.pull,c.pts)||0)||((t.pxmid[1]-c.pxmid[1])*l>0?(f=c.cyFinal+o(c.px0[1],c.px1[1]),(x=f-v-t.labelExtraY)*l>0&&(t.labelExtraY+=x)):(m+t.labelExtraY-y)*l>0&&(i=3*s*Math.abs(u-h.indexOf(t)),p=c.cxFinal+a(c.px0[0],c.px1[0]),(d=p+i-(t.cxFinal+t.pxmid[0])-t.labelExtraX)*s>0&&(t.labelExtraX+=d)))}for(n=0;n<2;n++)for(i=n?g:v,o=n?Math.max:Math.min,l=n?1:-1,r=0;r<2;r++){for(a=r?Math.max:Math.min,s=r?1:-1,(u=t[n][r]).sort(i),c=t[1-n][r],h=c.concat(u),p=[],f=0;fMath.abs(u)?a+="l"+u*t.pxmid[0]/t.pxmid[1]+","+u+"H"+(n+t.labelExtraX+s):a+="l"+t.labelExtraX+","+l+"v"+(u-l)+"h"+s}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+s;e.append("path").classed("textline",!0).call(Fe.stroke,o.outsidetextfont.color).attr({"stroke-width":Math.min(2,o.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){n.selectAll("tspan").each(function(){var t=i.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)},VF.style=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0].trace,r=i.select(this);r.style({opacity:e.opacity}),r.selectAll("path.surface").each(function(t){i.select(this).call(Bg,t,e)})})},VF.styleOne=Bg,VF.moduleType="trace",VF.name="pie",VF.basePlotModule=EF,VF.categories=["pie","showLegend"],VF.meta={};var UF=VF,qF={x:Qr.x,y:Qr.y,xy:{valType:"data_array",editType:"calc"},indices:{valType:"data_array",editType:"calc"},xbounds:{valType:"data_array",editType:"calc"},ybounds:{valType:"data_array",editType:"calc"},text:Qr.text,marker:{color:{valType:"color",arrayOk:!1,editType:"calc"},opacity:{valType:"number",min:0,max:1,dflt:1,arrayOk:!1,editType:"calc"},blend:{valType:"boolean",dflt:null,editType:"calc"},sizemin:{valType:"number",min:.1,max:2,dflt:.5,editType:"calc"},sizemax:{valType:"number",min:.1,dflt:20,editType:"calc"},border:{color:{valType:"color",arrayOk:!1,editType:"calc"},arearatio:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},editType:"calc"},editType:"calc"}},HF={};HF.pointVertex=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform float pointCloud;\n\nhighp float rand(vec2 co) {\n highp float a = 12.9898;\n highp float b = 78.233;\n highp float c = 43758.5453;\n highp float d = dot(co.xy, vec2(a, b));\n highp float e = mod(d, 3.14);\n return fract(sin(e) * c);\n}\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n // if we don't jitter the point size a bit, overall point cloud\n // saturation 'jumps' on zooming, which is disturbing and confusing\n gl_PointSize = pointSize * ((19.5 + rand(position)) / 20.0);\n if(pointCloud != 0.0) { // pointCloud is truthy\n // get the same square surface as circle would be\n gl_PointSize *= 0.886;\n }\n}"]),HF.pointFragment=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\nuniform float pointCloud;\n\nvoid main() {\n float radius;\n vec4 baseColor;\n if(pointCloud != 0.0) { // pointCloud is truthy\n if(centerFraction == 1.0) {\n gl_FragColor = color;\n } else {\n gl_FragColor = mix(borderColor, color, centerFraction);\n }\n } else {\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n baseColor = mix(borderColor, color, step(radius, centerFraction));\n gl_FragColor = vec4(baseColor.rgb * baseColor.a, baseColor.a);\n }\n}\n"]),HF.pickVertex=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n"]),HF.pickFragment=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0 * gl_PointCoord.xy - 1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n"]);var GF=function(t,e){var r=t.gl,n=K_(r),i=K_(r),a=lk(r,HF.pointVertex,HF.pointFragment),o=lk(r,HF.pickVertex,HF.pickFragment),s=new WF(t,n,i,a,o);return s.update(e),t.addObject(s),s};function WF(t,e,r,n,i){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.shader=n,this.pickShader=i,this.sizeMin=.5,this.sizeMinCap=2,this.sizeMax=20,this.areaRatio=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.blend=!1,this.pickOffset=0,this.points=null}var YF=WF.prototype;YF.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.plot.removeObject(this)},YF.update=function(t){var e;function r(e,r){return e in t?t[e]:r}t=t||{},this.sizeMin=r("sizeMin",.5),this.sizeMax=r("sizeMax",20),this.color=r("color",[1,0,0,1]).slice(),this.areaRatio=r("areaRatio",1),this.borderColor=r("borderColor",[0,0,0,1]).slice(),this.blend=r("blend",!1);var n=t.positions.length>>>1,i=t.positions instanceof Float32Array,a=t.idToIndex instanceof Int32Array&&t.idToIndex.length>=n,o=t.positions,s=i?o:G_.mallocFloat32(o.length),l=a?t.idToIndex:G_.mallocInt32(n);if(i||s.set(o),!a)for(s.set(o),e=0;e>>1;for(r=0;r=e[0]&&a<=e[2]&&o>=e[1]&&o<=e[3]&&n++}return n}(this.points,o),c=this.plot.pickPixelRatio*Math.max(Math.min(this.sizeMinCap,this.sizeMin),Math.min(this.sizeMax,this.sizeMax/Math.pow(u,.33333)));t[0]=2/s,t[4]=2/l,t[6]=-2*o[0]/s-1,t[7]=-2*o[1]/l-1,this.offsetBuffer.bind(),i.bind(),i.attributes.position.pointer(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointCloud=c<5,i.uniforms.pointSize=c,i.uniforms.centerFraction=Math.min(1,Math.max(0,Math.sqrt(1-this.areaRatio))),n&&(e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,this.pickBuffer.bind(),i.attributes.pickId.pointer(a.UNSIGNED_BYTE),i.uniforms.pickOffset=e,this.pickOffset=r);var h=a.getParameter(a.BLEND),f=a.getParameter(a.DITHER);return h&&!this.blend&&a.disable(a.BLEND),f&&a.disable(a.DITHER),a.drawArrays(a.POINTS,0,this.pointCount),h&&!this.blend&&a.enable(a.BLEND),f&&a.enable(a.DITHER),r+this.pointCount}}(),YF.draw=YF.unifiedDraw,YF.drawPick=YF.unifiedDraw,YF.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(r=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}};var XF=Yn;function ZF(t,e){this.scene=t,this.uid=e,this.type="pointcloud",this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=new Int32Array(0),this.bounds=[0,0,0,0],this.pointcloudOptions={positions:new Float32Array(0),idToIndex:this.idToIndex,sizemin:.5,sizemax:12,color:[0,0,0,1],areaRatio:1,borderColor:[0,0,0,1]},this.pointcloud=GF(t.glplot,this.pointcloudOptions),this.pointcloud._trace=this}var JF=ZF.prototype;JF.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:this.pickXYData?[this.pickXYData[2*e],this.pickXYData[2*e+1]]:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:this.color,name:this.name,pointIndex:e,hoverinfo:this.hoverinfo}},JF.update=function(t){this.index=t.index,this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-1/0,-1/0],this.updateFast(t),this.color=Vx(t,{})},JF.updateFast=function(t){var e,r,n,i,a,o,s=this.xData=this.pickXData=t.x,l=this.yData=this.pickYData=t.y,u=this.pickXYData=t.xy,c=t.xbounds&&t.ybounds,h=t.indices,f=this.bounds;if(u){if(n=u,e=u.length>>>1,c)f[0]=t.xbounds[0],f[2]=t.xbounds[1],f[1]=t.ybounds[0],f[3]=t.ybounds[1];else for(o=0;of[2]&&(f[2]=i),af[3]&&(f[3]=a);if(h)r=h;else for(r=new Int32Array(e),o=0;of[2]&&(f[2]=i),af[3]&&(f[3]=a);this.idToIndex=r,this.pointcloudOptions.idToIndex=r,this.pointcloudOptions.positions=n;var p=vL(t.marker.color),d=vL(t.marker.border.color),g=t.opacity*t.marker.opacity;p[3]*=g,this.pointcloudOptions.color=p;var v=t.marker.blend;if(null===v){v=s.length<100||l.length<100}this.pointcloudOptions.blend=v,d[3]*=g,this.pointcloudOptions.borderColor=d;var m=t.marker.sizemin,y=Math.max(t.marker.sizemax,t.marker.sizemin);this.pointcloudOptions.sizeMin=m,this.pointcloudOptions.sizeMax=y,this.pointcloudOptions.areaRatio=t.marker.border.arearatio,this.pointcloud.update(this.pointcloudOptions),this.expandAxesFast(f,y/2)},JF.expandAxesFast=function(t,e){var r=e||.5;XF(this.scene.xaxis,[t[0],t[2]],{ppad:r}),XF(this.scene.yaxis,[t[1],t[3]],{ppad:r})},JF.dispose=function(){this.pointcloud.dispose()};var KF=function(t,e){var r=new ZF(t,e.uid);return r.update(e),r},QF=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return nf(r,e),Ax(e),r},$F={};$F.attributes=qF,$F.supplyDefaults=function(t,e,r){function n(r,n){return oe.coerce(t,e,qF,r,n)}n("x"),n("y"),n("xbounds"),n("ybounds"),t.xy&&t.xy instanceof Float32Array&&(e.xy=t.xy),t.indices&&t.indices instanceof Int32Array&&(e.indices=t.indices),n("text"),n("marker.color",r),n("marker.opacity"),n("marker.blend"),n("marker.sizemin"),n("marker.sizemax"),n("marker.border.color",r),n("marker.border.arearatio")},$F.calc=QF,$F.plot=KF,$F.moduleType="trace",$F.name="pointcloud",$F.basePlotModule=PL,$F.categories=["gl","gl2d","showLegend"],$F.meta={};var tN=$F,eN=zh.attributes,rN=b.extendFlat,nN=(0,_e.overrideAll)({hoverinfo:rN({},P.hoverinfo,{flags:["label","text","value","percent","name"]}),hoverlabel:L.hoverlabel,domain:eN({name:"sankey",trace:!0}),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:E({}),node:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:z.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:.5,arrayOk:!0}},pad:{valType:"number",arrayOk:!1,min:0,dflt:20},thickness:{valType:"number",arrayOk:!1,min:1,dflt:20}},link:{label:{valType:"data_array",dflt:[]},color:{valType:"color",arrayOk:!0},line:{color:{valType:"color",dflt:z.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:0,arrayOk:!0}},source:{valType:"data_array",dflt:[]},target:{valType:"data_array",dflt:[]},value:{valType:"data_array",dflt:[]}}},"calc","nested"),iN={nodeTextOffsetHorizontal:4,nodeTextOffsetVertical:3,nodePadAcross:10,sankeyIterations:50,forceIterations:5,forceTicksPerFrame:10,duration:500,ease:"cubic-in-out",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"}},aN={exports:{}};!function(t,e){"object"==typeof aN.exports?e(aN.exports):"function"==typeof aH&&aH.amd?aH(["exports"],e):e(t.d3=t.d3||{})}(this,function(t){"use strict";var e=function(t,e){return te?1:t>=e?0:NaN},r=function(t){var r;return 1===t.length&&(r=t,t=function(t,n){return e(r(t),n)}),{left:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(null==n&&(n=0),null==i&&(i=e.length);n>>1;t(e[a],r)>0?i=a:n=a+1}return n}}};var n=r(e),i=n.right,a=n.left;function o(t,e){return[t,e]}var s=function(t){return null===t?NaN:+t},l=function(t,e){var r,n,i=t.length,a=0,o=-1,l=0,u=0;if(null==e)for(;++o1)return u/(a-1)},u=function(t,e){var r=l(t,e);return r?Math.sqrt(r):r},c=function(t,e){var r,n,i,a=t.length,o=-1;if(null==e){for(;++o=r)for(n=i=r;++or&&(n=r),i=r)for(n=i=r;++or&&(n=r),i=0?(a>=m?10:a>=y?5:a>=x?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=m?10:a>=y?5:a>=x?2:1)}function _(t,e,r){var n=Math.abs(e-t)/Math.max(0,r),i=Math.pow(10,Math.floor(Math.log(n)/Math.LN10)),a=n/i;return a>=m?i*=10:a>=y?i*=5:a>=x&&(i*=2),e=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,a=Math.floor(i),o=+r(t[a],a,t);return o+(+r(t[a+1],a+1,t)-o)*(i-a)}},M=function(t,e){var r,n,i=t.length,a=-1;if(null==e){for(;++a=r)for(n=r;++ar&&(n=r)}else for(;++a=r)for(n=r;++ar&&(n=r);return n},A=function(t){if(!(i=t.length))return[];for(var e=-1,r=M(t,T),n=new Array(r);++et?1:e>=t?0:NaN},t.deviation=u,t.extent=c,t.histogram=function(){var t=g,e=c,r=w;function n(n){var a,o,s=n.length,l=new Array(s);for(a=0;ah;)f.pop(),--p;var d,g=new Array(p+1);for(a=0;a<=p;++a)(d=g[a]=[]).x0=a>0?f[a-1]:c,d.x1=a=r)for(n=r;++an&&(n=r)}else for(;++a=r)for(n=r;++an&&(n=r);return n},t.mean=function(t,e){var r,n=t.length,i=n,a=-1,o=0;if(null==e)for(;++a=0;)for(e=(n=t[i]).length;--e>=0;)r[--o]=n[e];return r},t.min=M,t.pairs=function(t,e){null==e&&(e=o);for(var r=0,n=t.length-1,i=t[0],a=new Array(n<0?0:n);r0)return[t];if((n=e0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++s=l.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var s,u,h,f=-1,p=n.length,d=l[i++],g=r(),v=a();++fl.length)return r;var i,a=u[n-1];return null!=e&&n>=l.length?i=r.entries():(i=[],r.each(function(e,r){i.push({key:r,values:t(e,n)})})),null!=a?i.sort(function(t,e){return a(t.key,e.key)}):i}(c(t,0,a,o),0)},key:function(t){return l.push(t),s},sortKeys:function(t){return u[l.length-1]=t,s},sortValues:function(e){return t=e,s},rollup:function(t){return e=t,s}}},t.set=u,t.map=r,t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},Object.defineProperty(t,"__esModule",{value:!0})}),oN=oN.exports;var sN={exports:{}};!function(t,e){"object"==typeof sN.exports?e(sN.exports):"function"==typeof aH&&aH.amd?aH(["exports"],e):e(t.d3=t.d3||{})}(this,function(t){"use strict";var e=function(t,e,r){t.prototype=e.prototype=r,r.constructor=t};function r(t,e){var r=Object.create(t.prototype);for(var n in e)r[n]=e[n];return r}function n(){}var i="\\s*([+-]?\\d+)\\s*",a="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",o="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",s=/^#([0-9a-f]{3})$/,l=/^#([0-9a-f]{6})$/,u=new RegExp("^rgb\\("+[i,i,i]+"\\)$"),c=new RegExp("^rgb\\("+[o,o,o]+"\\)$"),h=new RegExp("^rgba\\("+[i,i,i,a]+"\\)$"),f=new RegExp("^rgba\\("+[o,o,o,a]+"\\)$"),p=new RegExp("^hsl\\("+[a,o,o]+"\\)$"),d=new RegExp("^hsla\\("+[a,o,o,a]+"\\)$"),g={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};function v(t){var e;return t=(t+"").trim().toLowerCase(),(e=s.exec(t))?new _((e=parseInt(e[1],16))>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):(e=l.exec(t))?m(parseInt(e[1],16)):(e=u.exec(t))?new _(e[1],e[2],e[3],1):(e=c.exec(t))?new _(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=h.exec(t))?y(e[1],e[2],e[3],e[4]):(e=f.exec(t))?y(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=p.exec(t))?w(e[1],e[2]/100,e[3]/100,1):(e=d.exec(t))?w(e[1],e[2]/100,e[3]/100,e[4]):g.hasOwnProperty(t)?m(g[t]):"transparent"===t?new _(NaN,NaN,NaN,0):null}function m(t){return new _(t>>16&255,t>>8&255,255&t,1)}function y(t,e,r,n){return n<=0&&(t=e=r=NaN),new _(t,e,r,n)}function x(t){return t instanceof n||(t=v(t)),t?new _((t=t.rgb()).r,t.g,t.b,t.opacity):new _}function b(t,e,r,n){return 1===arguments.length?x(t):new _(t,e,r,null==n?1:n)}function _(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}function w(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new M(t,e,r,n)}function k(t,e,r,i){return 1===arguments.length?function(t){if(t instanceof M)return new M(t.h,t.s,t.l,t.opacity);if(t instanceof n||(t=v(t)),!t)return new M;if(t instanceof M)return t;var e=(t=t.rgb()).r/255,r=t.g/255,i=t.b/255,a=Math.min(e,r,i),o=Math.max(e,r,i),s=NaN,l=o-a,u=(o+a)/2;return l?(s=e===o?(r-i)/l+6*(r0&&u<1?0:s,new M(s,l,u,t.opacity)}(t):new M(t,e,r,null==i?1:i)}function M(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}function A(t,e,r){return 255*(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)}e(n,v,{displayable:function(){return this.rgb().displayable()},toString:function(){return this.rgb()+""}}),e(_,b,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new _(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return 0<=this.r&&this.r<=255&&0<=this.g&&this.g<=255&&0<=this.b&&this.b<=255&&0<=this.opacity&&this.opacity<=1},toString:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}})),e(M,k,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new M(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new M(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new _(A(t>=240?t-240:t+120,i,n),A(t,i,n),A(t<120?t+240:t-120,i,n),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1}}));var T=Math.PI/180,S=180/Math.PI,C=.95047,E=1,L=1.08883,P=4/29,z=6/29,D=3*z*z,I=z*z*z;function O(t){if(t instanceof B)return new B(t.l,t.a,t.b,t.opacity);if(t instanceof q){var e=t.h*T;return new B(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}t instanceof _||(t=x(t));var r=V(t.r),n=V(t.g),i=V(t.b),a=F((.4124564*r+.3575761*n+.1804375*i)/C),o=F((.2126729*r+.7151522*n+.072175*i)/E);return new B(116*o-16,500*(a-o),200*(o-F((.0193339*r+.119192*n+.9503041*i)/L)),t.opacity)}function R(t,e,r,n){return 1===arguments.length?O(t):new B(t,e,r,null==n?1:n)}function B(t,e,r,n){this.l=+t,this.a=+e,this.b=+r,this.opacity=+n}function F(t){return t>I?Math.pow(t,1/3):t/D+P}function N(t){return t>z?t*t*t:D*(t-P)}function j(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function V(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function U(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof q)return new q(t.h,t.c,t.l,t.opacity);t instanceof B||(t=O(t));var e=Math.atan2(t.b,t.a)*S;return new q(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}(t):new q(t,e,r,null==n?1:n)}function q(t,e,r,n){this.h=+t,this.c=+e,this.l=+r,this.opacity=+n}e(B,R,r(n,{brighter:function(t){return new B(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new B(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return t=E*N(t),new _(j(3.2404542*(e=C*N(e))-1.5371385*t-.4985314*(r=L*N(r))),j(-.969266*e+1.8760108*t+.041556*r),j(.0556434*e-.2040259*t+1.0572252*r),this.opacity)}})),e(q,U,r(n,{brighter:function(t){return new q(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new q(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return O(this).rgb()}}));var H=-.14861,G=1.78277,W=-.29227,Y=-.90649,X=1.97294,Z=X*Y,J=X*G,K=G*W-Y*H;function Q(t,e,r,n){return 1===arguments.length?function(t){if(t instanceof $)return new $(t.h,t.s,t.l,t.opacity);t instanceof _||(t=x(t));var e=t.r/255,r=t.g/255,n=t.b/255,i=(K*n+Z*e-J*r)/(K+Z-J),a=n-i,o=(X*(r-i)-W*a)/Y,s=Math.sqrt(o*o+a*a)/(X*i*(1-i)),l=s?Math.atan2(o,a)*S-120:NaN;return new $(l<0?l+360:l,s,i,t.opacity)}(t):new $(t,e,r,null==n?1:n)}function $(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}e($,Q,r(n,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new $(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new $(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*T,e=+this.l,r=isNaN(this.s)?0:this.s*e*(1-e),n=Math.cos(t),i=Math.sin(t);return new _(255*(e+r*(H*n+G*i)),255*(e+r*(W*n+Y*i)),255*(e+r*(X*n)),this.opacity)}})),t.color=v,t.rgb=b,t.hsl=k,t.lab=R,t.hcl=U,t.cubehelix=Q,Object.defineProperty(t,"__esModule",{value:!0})}),sN=sN.exports;var lN={exports:{}};!function(t,e){"object"==typeof lN.exports?e(lN.exports,sN):"function"==typeof aH&&aH.amd?aH(["exports","d3-color"],e):e(t.d3=t.d3||{},t.d3)}(this,function(t,e){"use strict";function r(t,e,r,n,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*r+(1+3*t+3*a-3*o)*n+o*i)/6}var n=function(t){var e=t.length-1;return function(n){var i=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),a=t[i],o=t[i+1],s=i>0?t[i-1]:2*a-o,l=i180||r<-180?r-360*Math.round(r/360):r):a(isNaN(t)?e:t)}function l(t){return 1==(t=+t)?u:function(e,r){return r-e?function(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}(e,r,t):a(isNaN(e)?r:e)}}function u(t,e){var r=e-t;return r?o(t,r):a(isNaN(t)?e:t)}var c=function t(r){var n=l(r);function i(t,r){var i=n((t=e.rgb(t)).r,(r=e.rgb(r)).r),a=n(t.g,r.g),o=n(t.b,r.b),s=u(t.opacity,r.opacity);return function(e){return t.r=i(e),t.g=a(e),t.b=o(e),t.opacity=s(e),t+""}}return i.gamma=t,i}(1);function h(t){return function(r){var n,i,a=r.length,o=new Array(a),s=new Array(a),l=new Array(a);for(n=0;na&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:v(r,n)})),a=x.lastIndex;return a180?e+=360:e-t>180&&(t+=360),a.push({i:r.push(i(r)+"rotate(",null,n)-2,x:v(t,e)})):e&&r.push(i(r)+"rotate("+e+n)}(a.rotate,o.rotate,s,l),function(t,e,r,a){t!==e?a.push({i:r.push(i(r)+"skewX(",null,n)-2,x:v(t,e)}):e&&r.push(i(r)+"skewX("+e+n)}(a.skewX,o.skewX,s,l),function(t,e,r,n,a,o){if(t!==r||e!==n){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:v(t,r)},{i:s-2,x:v(e,n)})}else 1===r&&1===n||a.push(i(a)+"scale("+r+","+n+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,l),a=o=null,function(t){for(var e,r=-1,n=l.length;++r0;--t)p(u*=.99),d(),f(u),d();function f(t){function r(t){return c(t.source)*t.value}i.forEach(function(n){n.forEach(function(n){if(n.targetLinks.length){var i=e.sum(n.targetLinks,r)/e.sum(n.targetLinks,h);n.y+=(i-c(n))*t}})})}function p(t){function r(t){return c(t.target)*t.value}i.slice().reverse().forEach(function(n){n.forEach(function(n){if(n.sourceLinks.length){var i=e.sum(n.sourceLinks,r)/e.sum(n.sourceLinks,h);n.y+=(i-c(n))*t}})})}function d(){i.forEach(function(t){var e,r,n,i=0,s=t.length;for(t.sort(g),n=0;n0&&(e.y+=r),i=e.y+e.dy+a;if((r=i-a-o[1])>0)for(i=e.y-=r,n=s-2;n>=0;--n)e=t[n],(r=e.y+e.dy+a-i)>0&&(e.y-=r),i=e.y})}function g(t,e){return t.y-e.y}}(n),u(),t},t.relayout=function(){return u(),t},t.link=function(){var t=.5;function e(e){var r=e.source.x+e.source.dx,i=e.target.x,a=n.interpolateNumber(r,i),o=a(t),s=a(1-t),l=e.source.y+e.sy,u=l+e.dy,c=e.target.y+e.ty,h=c+e.dy;return"M"+r+","+l+"C"+o+","+l+" "+s+","+c+" "+i+","+c+"L"+i+","+h+"C"+s+","+h+" "+o+","+u+" "+r+","+u+"Z"}return e.curvature=function(r){return arguments.length?(t=+r,e):t},e},t},Object.defineProperty(t,"__esModule",{value:!0})}),uN=uN.exports;var cN={exports:{}};!function(t,e){"object"==typeof cN.exports?e(cN.exports):"function"==typeof aH&&aH.amd?aH(["exports"],e):e(t.d3=t.d3||{})}(this,function(t){"use strict";var e={value:function(){}};function r(){for(var t,e=0,r=arguments.length,i={};e=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}})),l=-1,u=s.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++l0)for(var r,n,i=new Array(r),a=0;a=(a=(g+m)/2))?g=a:m=a,(c=r>=(o=(v+y)/2))?v=o:y=o,i=p,!(p=p[h=c<<1|u]))return i[h]=d,t;if(s=+t._x.call(null,p.data),l=+t._y.call(null,p.data),e===s&&r===l)return d.next=p,i?i[h]=d:t._root=d,t;do{i=i?i[h]=new Array(4):t._root=new Array(4),(u=e>=(a=(g+m)/2))?g=a:m=a,(c=r>=(o=(v+y)/2))?v=o:y=o}while((h=c<<1|u)==(f=(l>=o)<<1|s>=a));return i[f]=p,i[h]=d,t}var r=function(t,e,r,n,i){this.node=t,this.x0=e,this.y0=r,this.x1=n,this.y1=i};function n(t){return t[0]}function i(t){return t[1]}function a(t,e,r){var a=new o(null==e?n:e,null==r?i:r,NaN,NaN,NaN,NaN);return null==t?a:a.addAll(t)}function o(t,e,r,n,i,a){this._x=t,this._y=e,this._x0=r,this._y0=n,this._x1=i,this._y1=a,this._root=void 0}function s(t){for(var e={data:t.data},r=e;t=t.next;)r=r.next={data:t.data};return e}var l=a.prototype=o.prototype;l.copy=function(){var t,e,r=new o(this._x,this._y,this._x0,this._y0,this._x1,this._y1),n=this._root;if(!n)return r;if(!n.length)return r._root=s(n),r;for(t=[{source:n,target:r._root=new Array(4)}];n=t.pop();)for(var i=0;i<4;++i)(e=n.source[i])&&(e.length?t.push({source:e,target:n.target[i]=new Array(4)}):n.target[i]=s(e));return r},l.add=function(t){var r=+this._x.call(null,t),n=+this._y.call(null,t);return e(this.cover(r,n),r,n,t)},l.addAll=function(t){var r,n,i,a,o=t.length,s=new Array(o),l=new Array(o),u=1/0,c=1/0,h=-1/0,f=-1/0;for(n=0;nh&&(h=i),af&&(f=a));for(ht||t>i||n>e||e>a))return this;var o,s,l=i-r,u=this._root;switch(s=(e<(n+a)/2)<<1|t<(r+i)/2){case 0:do{(o=new Array(4))[s]=u,u=o}while(a=n+(l*=2),t>(i=r+l)||e>a);break;case 1:do{(o=new Array(4))[s]=u,u=o}while(a=n+(l*=2),(r=i-l)>t||e>a);break;case 2:do{(o=new Array(4))[s]=u,u=o}while(n=a-(l*=2),t>(i=r+l)||n>e);break;case 3:do{(o=new Array(4))[s]=u,u=o}while(n=a-(l*=2),(r=i-l)>t||n>e)}this._root&&this._root.length&&(this._root=u)}return this._x0=r,this._y0=n,this._x1=i,this._y1=a,this},l.data=function(){var t=[];return this.visit(function(e){if(!e.length)do{t.push(e.data)}while(e=e.next)}),t},l.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},l.find=function(t,e,n){var i,a,o,s,l,u,c,h=this._x0,f=this._y0,p=this._x1,d=this._y1,g=[],v=this._root;for(v&&g.push(new r(v,h,f,p,d)),null==n?n=1/0:(h=t-n,f=e-n,p=t+n,d=e+n,n*=n);u=g.pop();)if(!(!(v=u.node)||(a=u.x0)>p||(o=u.y0)>d||(s=u.x1)=y)<<1|t>=m)&&(u=g[g.length-1],g[g.length-1]=g[g.length-1-c],g[g.length-1-c]=u)}else{var x=t-+this._x.call(null,v.data),b=e-+this._y.call(null,v.data),_=x*x+b*b;if(_=(s=(d+v)/2))?d=s:v=s,(c=o>=(l=(g+m)/2))?g=l:m=l,e=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(e[h+1&3]||e[h+2&3]||e[h+3&3])&&(r=e,f=h)}for(;p.data!==t;)if(n=p,!(p=p.next))return this;return(i=p.next)&&delete p.next,n?(i?n.next=i:delete n.next,this):e?(i?e[h]=i:delete e[h],(p=e[0]||e[1]||e[2]||e[3])&&p===(e[3]||e[2]||e[1]||e[0])&&!p.length&&(r?r[f]=p:this._root=p),this):(this._root=i,this)},l.removeAll=function(t){for(var e=0,r=t.length;e=0&&r._call.call(null,t),r=r._next;--n}function m(){l=(s=c.now())+u,n=i=0;try{v()}finally{n=0,function(){var t,n,i=e,a=1/0;for(;i;)i._call?(a>i._time&&(a=i._time),t=i,i=i._next):(n=i._next,i._next=null,i=t?t._next=n:e=n);r=t,x(a)}(),l=0}}function y(){var t=c.now(),e=t-s;e>o&&(u-=e,s=t)}function x(t){n||(i&&(i=clearTimeout(i)),t-l>24?(t<1/0&&(i=setTimeout(m,t-c.now()-u)),a&&(a=clearInterval(a))):(a||(s=c.now(),a=setInterval(y,o)),n=1,h(m)))}d.prototype=g.prototype={constructor:d,restart:function(t,n,i){if("function"!=typeof t)throw new TypeError("callback is not a function");i=(null==i?f():+i)+(null==n?0:+n),this._next||r===this||(r?r._next=this:e=this,r=this),this._call=t,this._time=i,x()},stop:function(){this._call&&(this._call=null,this._time=1/0,x())}};t.now=f,t.timer=g,t.timerFlush=v,t.timeout=function(t,e,r){var n=new d;return e=null==e?0:+e,n.restart(function(r){n.stop(),t(r+e)},e,r),n},t.interval=function(t,e,r){var n=new d,i=e;return null==e?(n.restart(t,e,r),n):(e=+e,r=null==r?f():+r,n.restart(function a(o){o+=i,n.restart(a,i+=e,r),t(o)},e,r),n)},Object.defineProperty(t,"__esModule",{value:!0})}),fN=fN.exports;var pN={exports:{}};!function(t,e){"object"==typeof pN.exports?e(pN.exports,hN,oN,cN,fN):"function"==typeof aH&&aH.amd?aH(["exports","d3-quadtree","d3-collection","d3-dispatch","d3-timer"],e):e(t.d3=t.d3||{},t.d3,t.d3,t.d3,t.d3)}(this,function(t,e,r,n,i){"use strict";var a=function(t){return function(){return t}},o=function(){return 1e-6*(Math.random()-.5)};function s(t){return t.x+t.vx}function l(t){return t.y+t.vy}function u(t){return t.index}function c(t,e){var r=t.get(e);if(!r)throw new Error("missing: "+e);return r}function h(t){return t.x}function f(t){return t.y}var p=10,d=Math.PI*(3-Math.sqrt(5));t.forceCenter=function(t,e){var r;function n(){var n,i,a=r.length,o=0,s=0;for(n=0;nf+u||np+u||ac.index){var h=f-s.x-s.vx,v=p-s.y-s.vy,m=h*h+v*v;mt.r&&(t.r=t[e].r)}function f(){if(r){var e,i,a=r.length;for(n=new Array(a),e=0;e=u)){(t.data!==r||t.next)&&(0===h&&(d+=(h=o())*h),0===f&&(d+=(f=o())*f),d1?(null==r?c.remove(t):c.set(t,y(r)),e):c.get(t)},find:function(e,r,n){var i,a,o,s,l,u=0,c=t.length;for(null==n?n=1/0:n*=n,u=0;u1?(f.on(t,r),e):f.on(t)}}},t.forceX=function(t){var e,r,n,i=a(.1);function o(t){for(var i,a=0,o=e.length;a1||t.linkLineWidth>0}function SN(t){return"translate("+t.translateX+","+t.translateY+")"+(t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)")}function CN(t){return"translate("+(t.horizontal?0:t.labelY)+" "+(t.horizontal?t.labelY:0)+")"}function EN(t){return i.svg.line()([[t.horizontal?t.left?-t.sizeAcross:t.visibleWidth+iN.nodeTextOffsetHorizontal:iN.nodeTextOffsetHorizontal,0],[t.horizontal?t.left?-iN.nodeTextOffsetHorizontal:t.sizeAcross:t.visibleHeight-iN.nodeTextOffsetHorizontal,0]])}function LN(t){return t.horizontal?"matrix(1 0 0 1 0 0)":"matrix(0 1 1 0 0 0)"}function PN(t){return t.horizontal?"scale(1 1)":"scale(-1 1)"}function zN(t){return t.darkBackground&&!t.horizontal?"rgb(255,255,255)":"rgb(0,0,0)"}function DN(t){return t.horizontal&&t.left?"100%":"0%"}function IN(t,e,r){t.on(".basic",null).on("mouseover.basic",function(t){t.interactionState.dragInProgress||(r.hover(this,t,e),t.interactionState.hovered=[this,t])}).on("mousemove.basic",function(t){t.interactionState.dragInProgress||(r.follow(this,t),t.interactionState.hovered=[this,t])}).on("mouseout.basic",function(t){t.interactionState.dragInProgress||(r.unhover(this,t,e),t.interactionState.hovered=!1)}).on("click.basic",function(t){t.interactionState.hovered&&(r.unhover(this,t,e),t.interactionState.hovered=!1),t.interactionState.dragInProgress||r.select(this,t,e)})}function ON(t,e,r){var n=i.behavior.drag().origin(function(t){return t.node}).on("dragstart",function(n){if("fixed"!==n.arrangement&&(oe.raiseToTop(this),n.interactionState.dragInProgress=n.node,yN(n.node),n.interactionState.hovered&&(r.nodeEvents.unhover.apply(0,n.interactionState.hovered),n.interactionState.hovered=!1),"snap"===n.arrangement)){var i=n.traceId+"|"+Math.floor(n.node.originalX);n.forceLayouts[i]?n.forceLayouts[i].alpha(1):function(t,e,r){var n=r.sankey.nodes().filter(function(t){return t.originalX===r.node.originalX});r.forceLayouts[e]=pN.forceSimulation(n).alphaDecay(0).force("collide",pN.forceCollide().radius(function(t){return t.dy/2+r.nodePad/2}).strength(1).iterations(iN.forceIterations)).force("constrain",function(t,e,r,n){return function(){for(var t=0,i=0;i0&&n.forceLayouts[e].alpha(0)}}(0,e,n,r)).stop()}(0,i,n),function(t,e,r,n){window.requestAnimationFrame(function i(){for(var a=0;a0&&window.requestAnimationFrame(i)})}(t,e,n,i)}}).on("drag",function(r){if("fixed"!==r.arrangement){var n=i.event.x,a=i.event.y;"snap"===r.arrangement?(r.node.x=n,r.node.y=a):("freeform"===r.arrangement&&(r.node.x=n),r.node.y=Math.max(r.node.dy/2,Math.min(r.size-r.node.dy/2,a))),yN(r.node),"snap"!==r.arrangement&&(r.sankey.relayout(),MN(t.filter(xN(r)),e))}}).on("dragend",function(t){t.interactionState.dragInProgress=!1});t.on(".drag",null).call(n)}var RN=function(t,e,r,n){var i=t.selectAll("."+iN.cn.sankey).data(e.filter(function(t){return mN(t).trace.visible}).map(function(t,e,r){for(var n,i=mN(e).trace,a=i.domain,o=i.node,s=i.link,l=i.arrangement,u="h"===i.orientation,c=i.node.pad,h=i.node.thickness,f=i.node.line.color,p=i.node.line.width,d=i.link.line.color,g=i.link.line.width,v=i.valueformat,m=i.valuesuffix,y=i.textfont,x=t.width*(a.x[1]-a.x[0]),b=t.height*(a.y[1]-a.y[0]),_=o.label.map(function(t,e){return{pointNumber:e,label:t,color:oe.isArrayOrTypedArray(o.color)?o.color[e]:o.color}}),w=s.value.map(function(t,e){return{pointNumber:e,label:s.label[e],color:oe.isArrayOrTypedArray(s.color)?s.color[e]:s.color,source:s.source[e],target:s.target[e],value:t}}),k=dN().size(u?[x,b]:[b,x]).nodeWidth(h).nodePadding(c).nodes(_).links(w).layout(iN.sankeyIterations),M=k.nodes(),A=0;A5?t.node.label:""}).attr("text-anchor",function(t){return t.horizontal&&t.left?"end":"start"}),g.transition().ease(iN.ease).duration(iN.duration).attr("startOffset",DN).style("fill",zN)},BN=iN.cn,FN=oe._;function NN(t){return""!==t}function jN(t,e){return t.filter(function(t){return t.key===e.traceId})}function VN(t,e){i.select(t).select("path").style("fill-opacity",e),i.select(t).select("rect").style("fill-opacity",e)}function UN(t){i.select(t).select("text.name").style("fill","black")}function qN(t){return function(e){return-1!==t.node.sourceLinks.indexOf(e.link)||-1!==t.node.targetLinks.indexOf(e.link)}}function HN(t){return function(e){return-1!==e.node.sourceLinks.indexOf(t.link)||-1!==e.node.targetLinks.indexOf(t.link)}}function GN(t,e,r){e&&r&&jN(r,e).selectAll("."+BN.sankeyLink).filter(qN(e)).call(YN.bind(0,e,r,!1))}function WN(t,e,r){e&&r&&jN(r,e).selectAll("."+BN.sankeyLink).filter(qN(e)).call(XN.bind(0,e,r,!1))}function YN(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",.4),i&&jN(e,t).selectAll("."+BN.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",.4),r&&jN(e,t).selectAll("."+BN.sankeyNode).filter(HN(t)).call(GN)}function XN(t,e,r,n){var i=n.datum().link.label;n.style("fill-opacity",function(t){return t.tinyColorAlpha}),i&&jN(e,t).selectAll("."+BN.sankeyLink).filter(function(t){return t.link.label===i}).style("fill-opacity",function(t){return t.tinyColorAlpha}),r&&jN(e,t).selectAll(BN.sankeyNode).filter(HN(t)).call(WN)}function ZN(t,e){var r=t.hoverlabel||{},n=oe.nestedProperty(r,e).get();return!Array.isArray(n)&&n}var JN=function(t,e){var r=t._fullLayout,n=r._paper,a=r._size,o=FN(t,"source:")+" ",s=FN(t,"target:")+" ",l=FN(t,"incoming flow count:")+" ",u=FN(t,"outgoing flow count:")+" ";RN(n,e,{width:a.w,height:a.h,margin:{t:a.t,r:a.r,b:a.b,l:a.l}},{linkEvents:{hover:function(e,r,n){i.select(e).call(YN.bind(0,r,n,!0)),t.emit("plotly_hover",{event:i.event,points:[r.link]})},follow:function(e,n){var a=n.link.trace,l=t._fullLayout._paperdiv.node().getBoundingClientRect(),u=e.getBoundingClientRect(),c=u.left+u.width/2,h=u.top+u.height/2,f=qa.loneHover({x:c-l.left,y:h-l.top,name:i.format(n.valueFormat)(n.link.value)+n.valueSuffix,text:[n.link.label||"",o+n.link.source.label,s+n.link.target.label].filter(NN).join("
"),color:ZN(a,"bgcolor")||Fe.addOpacity(n.tinyColorHue,1),borderColor:ZN(a,"bordercolor"),fontFamily:ZN(a,"font.family"),fontSize:ZN(a,"font.size"),fontColor:ZN(a,"font.color"),idealAlign:i.event.x"),color:ZN(a,"bgcolor")||n.tinyColorHue,borderColor:ZN(a,"bordercolor"),fontFamily:ZN(a,"font.family"),fontSize:ZN(a,"font.size"),fontColor:ZN(a,"font.color"),idealAlign:"left"},{container:r._hoverlayer.node(),outerContainer:r._paper.node(),gd:t});VN(d,.85),UN(d)},unhover:function(e,n,a){i.select(e).call(WN,n,a),t.emit("plotly_unhover",{event:i.event,points:[n.node]}),qa.loneUnhover(r._hoverlayer.node())},select:function(e,r,n){var a=r.node;a.originalEvent=i.event,t._hoverdata=[a],i.select(e).call(WN,r,n),qa.click(t,{target:!0})}}})},KN={},QN=_e.overrideAll,$N=hs.getModuleCalcData;KN.name="sankey",KN.baseLayoutAttrOverrides=QN({hoverlabel:Ua.hoverlabel},"plot","nested"),KN.plot=function(t){var e=$N(t.calcdata,"sankey")[0];JN(t,e)},KN.clean=function(t,e,r,n){var i=n._has&&n._has("sankey"),a=e._has&&e._has("sankey");i&&!a&&n._paperdiv.selectAll(".sankey").remove()};var tj=function(t){for(var e=t.length,r=new Array(e),n=new Array(e),i=new Array(e),a=new Array(e),o=new Array(e),s=new Array(e),l=0;l0;){e=u[u.length-1];var p=t[e];if(a[e]=0&&s[e].push(o[g])}a[e]=d}else{if(n[e]===r[e]){for(var v=[],m=[],y=0,d=l.length-1;d>=0;--d){var x=l[d];if(i[x]=!1,v.push(x),m.push(s[x]),y+=s[x].length,o[x]=h.length,x===e){l.length=d;break}}h.push(v);for(var b=new Array(y),d=0;d1})}(e.node.label,e.link.source,e.link.target)&&(oe.error("Circularity is present in the Sankey data. Removing all nodes and links."),e.link.label=[],e.link.source=[],e.link.target=[],e.link.value=[],e.link.color=[],e.node.label=[],e.node.color=[]),ej({link:e.link,node:e.node})},nj.plot=JN,nj.moduleType="trace",nj.name="sankey",nj.basePlotModule=KN,nj.categories=["noOpacity"],nj.meta={};var ij=nj,aj={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"},oj={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]},sj={},lj=b.extendFlat,uj=_e.overrideAll,cj=Qr.line,hj=Qr.marker,fj=hj.line;var pj=sj=uj({x:Qr.x,y:Qr.y,z:{valType:"data_array"},text:lj({},Qr.text,{}),hovertext:lj({},Qr.hovertext,{}),mode:lj({},Qr.mode,{dflt:"lines+markers"}),surfaceaxis:{valType:"enumerated",values:[-1,0,1,2],dflt:-1},surfacecolor:{valType:"color"},projection:{x:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}},y:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}},z:{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}}},connectgaps:Qr.connectgaps,line:lj({width:cj.width,dash:{valType:"enumerated",values:Object.keys(oj),dflt:"solid"},showscale:{valType:"boolean",dflt:!1}},Be()),marker:lj({symbol:{valType:"enumerated",values:Object.keys(aj),dflt:"circle",arrayOk:!0},size:lj({},hj.size,{dflt:8}),sizeref:hj.sizeref,sizemin:hj.sizemin,sizemode:hj.sizemode,opacity:lj({},hj.opacity,{arrayOk:!1}),showscale:hj.showscale,colorbar:hj.colorbar,line:lj({width:lj({},fj.width,{arrayOk:!1})},Be())},Be()),textposition:lj({},Qr.textposition,{dflt:"top center"}),textfont:Qr.textfont,hoverinfo:lj({},P.hoverinfo)},"calc","nested");pj.x.editType=pj.y.editType=pj.z.editType="calc+clearAxisTypes";var dj=Q_(["precision mediump 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}"]),gj=Q_(["precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}"]),vj=function(t){return lk(t,dj,gj,null,[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"offset",type:"vec3"}])},mj=function(t){var e=t.gl,r=K_(e),n=Qz(e,[{buffer:r,type:e.FLOAT,size:3,offset:0,stride:40},{buffer:r,type:e.FLOAT,size:4,offset:12,stride:40},{buffer:r,type:e.FLOAT,size:3,offset:28,stride:40}]),i=vj(e);i.attributes.position.location=0,i.attributes.color.location=1,i.attributes.offset.location=2;var a=new xj(e,r,n,i);return a.update(t),a},yj=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function xj(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}var bj=xj.prototype;function _j(t,e){for(var r=0;r<3;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}bj.isOpaque=function(){return this.opacity>=1},bj.isTransparent=function(){return this.opacity<1},bj.drawTransparent=bj.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||yj,i=r.projection=t.projection||yj;r.model=t.model||yj,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var c=0;c<3;++c)e.lineWidth(this.lineWidth[c]),r.capSize=this.capSize[c]*u,this.lineCount[c]&&e.drawArrays(e.LINES,this.lineOffset[c],this.lineCount[c]);this.vao.unbind()};var wj=function(){for(var t=new Array(3),e=0;e<3;++e){for(var r=[],n=1;n<=2;++n)for(var i=-1;i<=1;i+=2){var a=[0,0,0];a[(n+e)%3]=i,r.push(a)}t[e]=r}return t}();function kj(t,e,r,n){for(var i=wj[n],a=0;a0)(p=u.slice())[s]+=h[1][s],i.push(u[0],u[1],u[2],f[0],f[1],f[2],f[3],0,0,0,p[0],p[1],p[2],f[0],f[1],f[2],f[3],0,0,0),_j(this.bounds,p),o+=2+kj(i,p,f,s)}}this.lineCount[s]=o-this.lineOffset[s]}this.buffer.update(i)}},bj.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()};var Mj={},Aj=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n"]),Tj=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n"]),Sj=Q_(["precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1540259130(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1540259130(pixelArcLength).xyz);\n}"]),Cj=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];Mj.createShader=function(t){return lk(t,Aj,Tj,null,Cj)},Mj.createPickShader=function(t){return lk(t,Aj,Sj,null,Cj)};var Ej=function(t,e,r,n){return Lj[0]=n,Lj[1]=r,Lj[2]=e,Lj[3]=t,Pj[0]},Lj=new Uint8Array(4),Pj=new Float32Array(Lj.buffer);var zj=function(t){var e=t.gl||t.scene&&t.scene.gl,r=Dj(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=Ij(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=K_(e),a=Qz(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),o=Wb(new Array(1024),[256,1,4]),s=0;s<1024;++s)o.data[s]=255;var l=eE(e,o);l.wrap=e.REPEAT;var u=new Nj(e,r,n,i,a,l);return u.update(t),u},Dj=Mj.createShader,Ij=Mj.createPickShader,Oj=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function Rj(t,e){for(var r=0,n=0;n<3;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function Bj(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;r<3;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function Fj(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function Nj(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-1/0,-1/0,-1/0],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}var jj=Nj.prototype;jj.isTransparent=function(){return this.opacity<1},jj.isOpaque=function(){return this.opacity>=1},jj.pickSlots=1,jj.setPickBase=function(t){this.pickId=t},jj.drawTransparent=jj.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||Oj,view:t.view||Oj,projection:t.projection||Oj,clipBounds:Bj(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},jj.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||Oj,view:t.view||Oj,projection:t.projection||Oj,pickId:this.pickId,clipBounds:Bj(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount),n.unbind()},jj.update=function(t){var e,r;this.dirty=!0;var n=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var i=t.position||t.positions;if(i){var a=t.color||t.colors||[0,0,0,1],o=t.lineWidth||1,s=[],l=[],u=[],c=0,h=0,f=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]],p=!1;t:for(e=1;e0){for(var x=0;x<24;++x)s.push(s[s.length-12]);h+=2,p=!0}continue t}f[0][r]=Math.min(f[0][r],m[r],y[r]),f[1][r]=Math.max(f[1][r],m[r],y[r])}Array.isArray(a[0])?(d=a[e-1],g=a[e]):d=g=a,3===d.length&&(d=[d[0],d[1],d[2],1]),3===g.length&&(g=[g[0],g[1],g[2],1]),v=Array.isArray(o)?o[e-1]:o;var b=c;if(c+=Rj(m,y),p){for(r=0;r<2;++r)s.push(m[0],m[1],m[2],y[0],y[1],y[2],b,v,d[0],d[1],d[2],d[3]);h+=2,p=!1}s.push(m[0],m[1],m[2],y[0],y[1],y[2],b,v,d[0],d[1],d[2],d[3],m[0],m[1],m[2],y[0],y[1],y[2],b,-v,d[0],d[1],d[2],d[3],y[0],y[1],y[2],m[0],m[1],m[2],c,-v,g[0],g[1],g[2],g[3],y[0],y[1],y[2],m[0],m[1],m[2],c,v,g[0],g[1],g[2],g[3]),h+=4}if(this.buffer.update(s),l.push(c),u.push(i[i.length-1].slice()),this.bounds=f,this.vertexCount=h,this.points=u,this.arcLength=l,"dashes"in t){var _=t.dashes.slice();for(_.unshift(0),e=1;e<_.length;++e)_[e]=_[e-1]+_[e];var w=Wb(new Array(1024),[256,1,4]);for(e=0;e<256;++e){for(r=0;r<4;++r)w.set(e,0,r,0);1&WT.le(_,_[_.length-1]*e/255)?w.set(e,0,0,0):w.set(e,0,0,255)}this.texture.setPixels(w)}}},jj.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},jj.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=Ej(t.value[0],t.value[1],t.value[2],0),r=WT.le(this.arcLength,e);if(r<0)return null;if(r===this.arcLength.length-1)return new Fj(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],a=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),o=1-a,s=[0,0,0],l=0;l<3;++l)s[l]=o*n[l]+a*i[l];var u=Math.min(a<.5?r:r+1,this.points.length-1);return new Fj(e,s,u,this.points[u])};var Vj=function(t,e){var r=Uj[e];r||(r=Uj[e]={});if(t in r)return r[t];for(var n=YC(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),i=YC(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),a=[[1/0,1/0],[-1/0,-1/0]],o=0;o=1)return!0;for(var t=0;t<3;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var uV=[0,0],cV=[0,0,0],hV=[0,0,0],fV=[0,0,0,1],pV=[0,0,0,1],dV=nV.slice(),gV=[0,0,0],vV=[[0,0,0],[0,0,0]];function mV(t){return t[0]=t[1]=t[2]=0,t}function yV(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function xV(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function bV(t,e,r,n,i){var a,o=e.axesProject,s=e.gl,l=t.uniforms,u=r.model||nV,c=r.view||nV,h=r.projection||nV,f=e.axesBounds,p=function(t){for(var e=vV,r=0;r<2;++r)for(var n=0;n<3;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}(e.clipBounds);a=e.axes&&e.axes.lastCubeProps?e.axes.lastCubeProps.axis:[1,1,1],uV[0]=2/s.drawingBufferWidth,uV[1]=2/s.drawingBufferHeight,t.bind(),l.view=c,l.projection=h,l.screenSize=uV,l.highlightId=e.highlightId,l.highlightScale=e.highlightScale,l.clipBounds=p,l.pickGroup=e.pickId/255,l.pixelRatio=e.pixelRatio;for(var d=0;d<3;++d)if(o[d]&&e.projectOpacity[d]<1===n){l.scale=e.projectScale[d],l.opacity=e.projectOpacity[d];for(var g=dV,v=0;v<16;++v)g[v]=0;for(v=0;v<4;++v)g[5*v]=1;g[5*d]=0,a[d]<0?g[12+d]=f[0][d]:g[12+d]=f[1][d],iz(g,u,g),l.model=g;var m=(d+1)%3,y=(d+2)%3,x=mV(cV),b=mV(hV);x[m]=1,b[y]=1;var _=oV(0,0,0,yV(fV,x)),w=oV(0,0,0,yV(pV,b));if(Math.abs(_[1])>Math.abs(w[1])){var k=_;_=w,w=k,k=x,x=b,b=k;var M=m;m=y,y=M}_[0]<0&&(x[m]=-1),w[1]>0&&(b[y]=-1);var A=0,T=0;for(v=0;v<4;++v)A+=Math.pow(u[4*m+v],2),T+=Math.pow(u[4*y+v],2);x[m]/=Math.sqrt(A),b[y]/=Math.sqrt(T),l.axes[0]=x,l.axes[1]=b,l.fragClipBounds[0]=xV(gV,p[0],d,-1e8),l.fragClipBounds[1]=xV(gV,p[1],d,1e8),e.vao.draw(s.TRIANGLES,e.vertexCount),e.lineWidth>0&&(s.lineWidth(e.lineWidth),e.vao.draw(s.LINES,e.lineVertexCount,e.vertexCount))}}var _V=[[-1e8,-1e8,-1e8],[1e8,1e8,1e8]];function wV(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||nV,s.view=n.view||nV,s.projection=n.projection||nV,uV[0]=2/o.drawingBufferWidth,uV[1]=2/o.drawingBufferHeight,s.screenSize=uV,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=_V,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}bV(e,r,n,i),r.vao.unbind()}lV.draw=function(t){wV(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!1,!1)},lV.drawTransparent=function(t){wV(this.useOrtho?this.orthoShader:this.shader,this.projectShader,this,t,!0,!1)},lV.drawPick=function(t){wV(this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader,this.pickProjectShader,this,t,!1,!0)},lV.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||e<0)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;i<3;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},lV.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},lV.update=function(t){if("perspective"in(t=t||{})&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0],l=t.glyph,u=t.color,c=t.size,h=t.angle,f=t.lineColor,p=0,d=0,g=0,v=n.length;t:for(var m=0;m0&&(C[0]=-a[0]*(1+w[0][0]));var V=b.cells,U=b.positions;for(x=0;x=0&&(u[1]+=1),l.indexOf("top")>=0&&(u[1]-=1),l.indexOf("left")>=0&&(u[0]-=1),l.indexOf("right")>=0&&(u[0]+=1),u)),r.textColor=EV(e.textfont,1,_),r.textSize=RV(e.textfont.size,_,oe.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var T=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;n<3;++n){var S=e.projection[T[n]];(r.project[n]=S.show)&&(r.projectOpacity[n]=S.opacity,r.projectScale[n]=S.scale)}r.errorBounds=PV(e,f);var C=function(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[0,0,0],i=0;i<3;i++){var a=t[i];a&&!1!==a.copy_zstyle&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=vL(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}([e.error_x,e.error_y,e.error_z]);return r.errorColor=C.color,r.errorLineWidth=C.lineWidth,r.errorCapSize=C.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=vL(e.surfacecolor),r}function FV(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}DV.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels?void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel=this.textLabels:t.textLabel="";var e=t.index=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},DV.update=function(t){var e,r,n,i,a=this.scene.glplot.gl,o=oj.solid;this.data=t;var s=BV(this.scene,t);"mode"in s&&(this.mode=s.mode),"lineDashes"in s&&s.lineDashes in oj&&(o=oj[s.lineDashes]),this.color=FV(s.scatterColor)||FV(s.lineColor),this.dataPoints=s.position,e={gl:a,position:s.position,color:s.lineColor,lineWidth:s.lineWidth||1,dashes:o[0],dashScale:o[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=zj(e),this.linePlot._trace=this,this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var l=t.opacity;if(t.marker&&t.marker.opacity&&(l*=t.marker.opacity),r={gl:a,position:s.position,color:s.scatterColor,size:s.scatterSize,glyph:s.scatterMarker,opacity:l,orthographic:!0,lineWidth:s.scatterLineWidth,lineColor:s.scatterLineColor,project:s.project,projectScale:s.projectScale,projectOpacity:s.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=iV(r),this.scatterPlot._trace=this,this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),i={gl:a,position:s.position,glyph:s.text,color:s.textColor,size:s.textSize,angle:s.textAngle,alignment:s.textOffset,font:s.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=t.hovertext||t.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(i):(this.textMarkers=iV(i),this.textMarkers._trace=this,this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:a,position:s.position,color:s.errorColor,error:s.errorBounds,lineWidth:s.errorLineWidth,capSize:s.errorCapSize,opacity:t.opacity},this.errorBars?s.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):s.errorBounds&&(this.errorBars=mj(n),this.errorBars._trace=this,this.scene.glplot.add(this.errorBars)),s.delaunayAxis>=0){var u=function(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;n=0&&i("surfacecolor",a||o);for(var s=["x","y","z"],l=0;l<3;++l){var u="projection."+s[l];i(u+".show")&&(i(u+".opacity"),i(u+".scale"))}var c=O.getComponentMethod("errorbars","supplyDefaults");c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}else e.visible=!1},jV.colorbar=yl,jV.calc=QF,jV.moduleType="trace",jV.name="scatter3d",jV.basePlotModule=KI,jV.categories=["gl3d","symbols","markerColorscale","showLegend"],jV.meta={};var VV=jV,UV=b.extendFlat,qV=Qr.marker,HV=Qr.line,GV=qV.line,WV={carpet:{valType:"string",editType:"calc"},a:{valType:"data_array",editType:"calc"},b:{valType:"data_array",editType:"calc"},mode:UV({},Qr.mode,{dflt:"markers"}),text:UV({},Qr.text,{}),line:{color:HV.color,width:HV.width,dash:HV.dash,shape:UV({},HV.shape,{values:["linear","spline"]}),smoothing:HV.smoothing,editType:"calc"},connectgaps:Qr.connectgaps,fill:UV({},Qr.fill,{values:["none","toself","tonext"]}),fillcolor:Qr.fillcolor,marker:UV({symbol:qV.symbol,opacity:qV.opacity,maxdisplayed:qV.maxdisplayed,size:qV.size,sizeref:qV.sizeref,sizemin:qV.sizemin,sizemode:qV.sizemode,line:UV({width:GV.width,editType:"calc"},Be()),gradient:qV.gradient,editType:"calc"},Be(),{showscale:qV.showscale,colorbar:Ie}),textfont:Qr.textfont,textposition:Qr.textposition,selected:Qr.selected,unselected:Qr.unselected,hoverinfo:UV({},P.hoverinfo,{flags:["a","b","text","name"]}),hoveron:Qr.hoveron},YV=Px,XV={};XV.attributes=WV,XV.supplyDefaults=function(t,e,r,n){function i(r,n){return oe.coerce(t,e,WV,r,n)}i("carpet"),e.xaxis="x",e.yaxis="y";var a,o=i("a"),s=i("b");if(a=Math.min(o.length,s.length)){o&&a"),i}function _(t,e){var r;r=t.labelprefix&&t.labelprefix.length>0?t.labelprefix.replace(/ = $/,""):t._hovertitle,d.push(r+": "+e.toFixed(3)+t.labelsuffix)}},XV.selectPoints=Kx,XV.eventData=function(t,e,r,n,i){var a=n[i];return t.a=a.a,t.b=a.b,t},XV.moduleType="trace",XV.name="scattercarpet",XV.basePlotModule=ps,XV.categories=["svg","carpet","symbols","markerColorscale","showLegend","carpetDependent","draggedPts"],XV.meta={};var ZV=XV,JV=n.BADNUM,KV=oe._,QV=function(t,e){for(var r=Array.isArray(e.locations),n=r?e.locations.length:e._length,i=new Array(n),o=0;o0&&(r.push(n),n=[])}return n.length>0&&r.push(n),r},tU.makeLine=function(t){return 1===t.length?{type:"LineString",coordinates:t[0]}:{type:"MultiLineString",coordinates:t}},tU.makePolygon=function(t){if(1===t.length)return{type:"Polygon",coordinates:t};for(var e=new Array(t.length),r=0;r")}(i,c,s.mockAxis,n[0].t.labels),[t]}},lU.eventData=function(t,e){return t.lon=e.lon,t.lat=e.lat,t.location=e.loc?e.loc:null,t},lU.selectPoints=function(t,e){var r,n,i,a,o,s=t.cd,l=t.xaxis,u=t.yaxis,c=[],h=s[0].trace;if(!Er.hasMarkers(h)&&!Er.hasText(h))return[];if(!1===e)for(o=0;oi&&(i=t[o]),t[o]1&&(t=arguments);"string"==typeof t?t=t.split(/\s/).map(parseFloat):"number"==typeof t&&(t=[t]);t.length&&"number"==typeof t[0]?e=1===t.length?{width:t[0],height:t[0],x:0,y:0}:2===t.length?{width:t[0],height:t[1],x:0,y:0}:{x:t[0],y:t[1],width:t[2]-t[0]||0,height:t[3]-t[1]||0}:t&&(t=gU(t,{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"}),e={x:t.left||0,y:t.top||0},null==t.width?t.right?e.width=t.right-e.x:e.width=0:e.width=t.width,null==t.height?t.bottom?e.height=t.bottom-e.y:e.height=0:e.height=t.height);return e};function xU(t,e,r,n,i){var a=["function ",t,"(a,l,h,",n.join(","),"){",i?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function bU(t,e,r,n){return new Function([xU("A","x"+t+"y",e,["y"],n),xU("P","c(x,y)"+t+"0",e,["y","c"],n),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""))()}var _U={ge:bU(">=",!1,"GE"),gt:bU(">",!1,"GT"),lt:bU("<",!0,"LT"),le:bU("<=",!0,"LE"),eq:bU("-",!0,"EQ",!0)};function wU(t,e){for(var r=e[0],n=e[1],i=1/(e[2]-r),a=1/(e[3]-n),o=new Array(t.length),s=0,l=t.length/2;s>>1;e.dtype||(e.dtype="array"),"string"==typeof e.dtype?i=new(dL(e.dtype))(o):e.dtype&&(i=e.dtype,Array.isArray(i)&&(i.length=o));for(var s=0;sr){for(var v=0;vc||b>h||_=k||o===s)){var f=l[a];void 0===s&&(s=f.length);for(var m=o;m=p&&A<=g&&T>=d&&T<=v&&M.push(y)}var S=u[a],C=S[4*o+0],E=S[4*o+1],L=S[4*o+2],P=S[4*o+3],z=function(t,e){for(var r=null,n=0;null===r;)if(r=t[4*e+n],++n>t.length)return null;return r}(S,o+1),D=.5*i,I=a+1;e(r,n,D,I,C,E||L||P||z),e(r,n+D,D,I,E,L||P||z),e(r+D,n,D,I,L,P||z),e(r+D,n+D,D,I,P,z)}}}(0,0,1,0,0,1),M},i;function y(t,e,r){for(var n=1,i=.5,a=.5,o=.5,s=0;s1&&(t.scaleRatio=[t.scale[0]*t.viewport.width,t.scale[1]*t.viewport.height],r(t),t.after&&t.after(t))}function d(t){if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var e=0,r=0;if(c=t.map(function(t,n){var i=c[n];return t?("function"==typeof t?t={after:t}:"number"==typeof t[0]&&(t={positions:t}),t=gU(t,{color:"color colors fill",capSize:"capSize cap capsize cap-size",lineWidth:"lineWidth line-width width line thickness",opacity:"opacity alpha",range:"range dataBox",viewport:"viewport viewBox",errors:"errors error",positions:"positions position data points"}),i||(c[n]=i={id:n,scale:null,translate:null,scaleFract:null,translateFract:null,draw:!0},t=eu({},u,t)),TU(i,t,[{lineWidth:function(t){return.5*+t},capSize:function(t){return.5*+t},opacity:parseFloat,errors:function(t){return t=fU(t),r+=t.length,t},positions:function(t,r){return t=fU(t,"float64"),r.count=Math.floor(t.length/2),r.bounds=hU(t,2),r.offset=e,e+=r.count,t}},{color:function(t,e){var r=e.count;if(t||(t="transparent"),!Array.isArray(t)||"number"==typeof t[0]){var n=t;t=Array(r);for(var i=0;i80*r){n=a=t[0],i=o=t[1];for(var d=r;da&&(a=s),l>o&&(o=l);u=0!==(u=Math.max(a-n,o-i))?1/u:0}return RU(f,p,r,n,i,u),p}function IU(t,e,r,n,i){var a,o;if(i===eq(t,e,r,n)>0)for(a=e;a=e;a-=n)o=QU(a,t[a],t[a+1],o);return o&&XU(o,o.next)&&($U(o),o=o.next),o}function OU(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!XU(n,n.next)&&0!==YU(n.prev,n,n.next))n=n.next;else{if($U(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function RU(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=qU(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,u=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,u*=2}while(o>1)}(i)}(t,n,i,a);for(var s,l,u=t;t.prev!==t.next;)if(s=t.prev,l=t.next,a?FU(t,n,i,a):BU(t))e.push(s.i/r),e.push(t.i/r),e.push(l.i/r),$U(t),t=l.next,u=l.next;else if((t=l)===u){o?1===o?RU(t=NU(t,e,r),e,r,n,i,a,2):2===o&&jU(t,e,r,n,i,a):RU(OU(t),e,r,n,i,a,1);break}}}function BU(t){var e=t.prev,r=t,n=t.next;if(YU(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(GU(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&YU(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function FU(t,e,r,n){var i=t.prev,a=t,o=t.next;if(YU(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,c=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,h=qU(s,l,e,r,n),f=qU(u,c,e,r,n),p=t.prevZ,d=t.nextZ;p&&p.z>=h&&d&&d.z<=f;){if(p!==t.prev&&p!==t.next&&GU(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&YU(p.prev,p,p.next)>=0)return!1;if(p=p.prevZ,d!==t.prev&&d!==t.next&&GU(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&YU(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(;p&&p.z>=h;){if(p!==t.prev&&p!==t.next&&GU(i.x,i.y,a.x,a.y,o.x,o.y,p.x,p.y)&&YU(p.prev,p,p.next)>=0)return!1;p=p.prevZ}for(;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&GU(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&YU(d.prev,d,d.next)>=0)return!1;d=d.nextZ}return!0}function NU(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!XU(i,a)&&ZU(i,n,n.next,a)&&JU(i,a)&&JU(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),$U(n),$U(n.next),n=t=a),n=n.next}while(n!==t);return n}function jU(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&WU(o,s)){var l=KU(o,s);return o=OU(o,o.next),l=OU(l,l.next),RU(o,e,r,n,i,a),void RU(l,e,r,n,i,a)}s=s.next}o=o.next}while(o!==t)}function VU(t,e){return t.x-e.x}function UU(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&i!==n.x&&GU(ar.x)&&JU(n,t)&&(r=n,f=l),n=n.next;return r}(t,e)){var r=KU(e,t);OU(r,r.next)}}function qU(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function HU(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function WU(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&ZU(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&JU(t,e)&&JU(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function YU(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function XU(t,e){return t.x===e.x&&t.y===e.y}function ZU(t,e,r,n){return!!(XU(t,e)&&XU(r,n)||XU(t,n)&&XU(r,e))||YU(t,e,r)>0!=YU(t,e,n)>0&&YU(r,n,t)>0!=YU(r,n,e)>0}function JU(t,e){return YU(t.prev,t,t.next)<0?YU(t,e,t.next)>=0&&YU(t,t.prev,e)>=0:YU(t,e,t.prev)<0||YU(t,t.next,e)<0}function KU(t,e){var r=new tq(t.i,t.x,t.y),n=new tq(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function QU(t,e,r,n){var i=new tq(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function $U(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function tq(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function eq(t,e,r,n){for(var i=0,a=e,o=r-n;a0&&(n+=t[i-1].length,r.holes.push(n))}return r};var rq,nq,iq,aq=function(){},oq=function(t){return void 0!==t&&null!==t},sq=Object.keys,lq=function(){try{return Object.keys("primitive"),!0}catch(t){return!1}}()?Object.keys:function(t){return sq(oq(t)?Object(t):t)},uq=function(t){if(!oq(t))throw new TypeError("Cannot use null or undefined");return t},cq=Math.max,hq="function"==typeof(nq=Object.assign)&&(nq(rq={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),rq.foo+rq.bar+rq.trzy==="razdwatrzy")?Object.assign:function(t,e){var r,n,i,a=cq(arguments.length,2);for(t=Object(uq(t)),i=function(n){try{t[n]=e[n]}catch(t){r||(r=t)}},n=1;n-1};(iq=function(t,e){var r,n,i,a,o;return arguments.length<2||"string"!=typeof t?(a=e,e=t,t=null):a=arguments[2],null==t?(r=i=!0,n=!1):(r=yq.call(t,"c"),n=yq.call(t,"e"),i=yq.call(t,"w")),o={value:e,configurable:r,enumerable:n,writable:i},a?hq(gq(a),o):o}).gs=function(t,e,r){var n,i,a,o;return"string"!=typeof t?(a=r,r=e,e=t,t=null):a=arguments[3],null==e?e=void 0:fq(e)?null==r?r=void 0:fq(r)||(a=r,r=void 0):(a=e,e=r=void 0),null==t?(n=!0,i=!1):(n=yq.call(t,"c"),i=yq.call(t,"e")),o={get:e,set:r,configurable:n,enumerable:i},a?hq(gq(a),o):o};var xq,bq,_q,wq,kq=Object.create,Mq=Object.getPrototypeOf,Aq={},Tq=function(){var t=Object.setPrototypeOf,e=arguments[0]||kq;return"function"==typeof t&&Mq(t(e(null),Aq))===Aq},Sq={function:!0,object:!0},Cq=function(t){return oq(t)&&Sq[typeof t]||!1},Eq=Tq()?Object.setPrototypeOf:e({}),Lq=function(t){if(!Cq(t))throw new TypeError(t+" is not an Object");return t},Pq=Object.create(null),zq=Math.random,Dq=Object.prototype.toString,Iq=Dq.call(function(){return arguments}()),Oq=function(t){return Dq.call(t)===Iq},Rq=function(t){if("function"!=typeof t)throw new TypeError(t+" is not a function");return t},Bq=Object.prototype.toString,Fq=Bq.call(""),Nq=function(t){return"string"==typeof t||t&&"object"==typeof t&&(t instanceof String||Bq.call(t)===Fq)||!1},jq=Object.prototype.toString,Vq=jq.call(aq),Uq=function(){var t=Math.sign;return"function"==typeof t&&1===t(10)&&-1===t(-20)}()?Math.sign:function(t){return t=Number(t),isNaN(t)||0===t?t:t>0?1:-1},qq=Math.abs,Hq=Math.floor,Gq=Math.max,Wq=function(t){return Gq(0,function(t){return isNaN(t)?0:0!==(t=Number(t))&&isFinite(t)?Uq(t)*Hq(qq(t)):t}(t))},Yq={object:!0,symbol:!0},Xq=function(t){if(!(e=t)||!("symbol"==typeof e||e.constructor&&"Symbol"===e.constructor.name&&"Symbol"===e[e.constructor.toStringTag]))throw new TypeError(t+" is not a symbol");var e;return t},Zq=Object.create,Jq=Object.defineProperties,Kq=Object.defineProperty,Qq=Object.prototype,$q=Zq(null);if("function"==typeof Symbol){xq=Symbol;try{String(xq()),wq=!0}catch(t){}}var tH,eH=(tH=Zq(null),function(t){for(var e,r,n=0;tH[t+(n||"")];)++n;return tH[t+=n||""]=!0,Kq(Qq,e="@@"+t,iq.gs(null,function(t){r||(r=!0,Kq(this,e,iq(t)),r=!1)})),e});_q=function(t){if(this instanceof _q)throw new TypeError("Symbol is not a constructor");return bq(t)};var rH=bq=function t(e){var r;if(this instanceof t)throw new TypeError("Symbol is not a constructor");return wq?xq(e):(r=Zq(_q.prototype),e=void 0===e?"":String(e),Jq(r,{__description__:iq("",e),__name__:iq("",eH(e))}))};Jq(bq,{for:iq(function(t){return $q[t]?$q[t]:$q[t]=bq(String(t))}),keyFor:iq(function(t){var e;for(e in Xq(t),$q)if($q[e]===t)return e}),hasInstance:iq("",xq&&xq.hasInstance||bq("hasInstance")),isConcatSpreadable:iq("",xq&&xq.isConcatSpreadable||bq("isConcatSpreadable")),iterator:iq("",xq&&xq.iterator||bq("iterator")),match:iq("",xq&&xq.match||bq("match")),replace:iq("",xq&&xq.replace||bq("replace")),search:iq("",xq&&xq.search||bq("search")),species:iq("",xq&&xq.species||bq("species")),split:iq("",xq&&xq.split||bq("split")),toPrimitive:iq("",xq&&xq.toPrimitive||bq("toPrimitive")),toStringTag:iq("",xq&&xq.toStringTag||bq("toStringTag")),unscopables:iq("",xq&&xq.unscopables||bq("unscopables"))}),Jq(_q.prototype,{constructor:iq(bq),toString:iq("",function(){return this.__name__})}),Jq(bq.prototype,{toString:iq(function(){return"Symbol ("+Xq(this).__description__+")"}),valueOf:iq(function(){return Xq(this)})}),Kq(bq.prototype,bq.toPrimitive,iq("",function(){var t=Xq(this);return"symbol"==typeof t?t:t.toString()})),Kq(bq.prototype,bq.toStringTag,iq("c","Symbol")),Kq(_q.prototype,bq.toStringTag,iq("c",bq.prototype[bq.toStringTag])),Kq(_q.prototype,bq.toPrimitive,iq("c",bq.prototype[bq.toPrimitive]));var nH,iH,aH,oH=function(){var t;if("function"!=typeof Symbol)return!1;t=Symbol("test symbol");try{String(t)}catch(t){return!1}return!!Yq[typeof Symbol.iterator]&&!!Yq[typeof Symbol.toPrimitive]&&!!Yq[typeof Symbol.toStringTag]}()?Symbol:rH,sH=oH.iterator,lH=Array.isArray,uH=Function.prototype.call,cH={configurable:!0,enumerable:!0,writable:!0,value:null},hH=Object.defineProperty,fH=function(){var t,e,r=Array.from;return"function"==typeof r&&(e=r(t=["raz","dwa"]),Boolean(e&&e!==t&&"dwa"===e[1]))}()?Array.from:function(t){var e,r,n,i,a,o,s,l,u,c,h=arguments[1],f=arguments[2];if(t=Object(uq(t)),oq(h)&&Rq(h),this&&this!==Array&&function(t){return"function"==typeof t&&jq.call(t)===Vq}(this))e=this;else{if(!h){if(Oq(t))return 1!==(a=t.length)?Array.apply(null,t):((i=new Array(1))[0]=t[0],i);if(lH(t)){for(i=new Array(a=t.length),r=0;r=55296&&o<=56319&&(c+=t[++r]),c=h?uH.call(h,f,c,n):c,e?(cH.value=c,hH(i,n,cH)):i[n]=c,++n;a=n}if(void 0===a)for(a=Wq(t.length),e&&(i=new e(a)),r=0;r=this.__nextIndex__||(++this.__nextIndex__,this.__redo__?(this.__redo__.forEach(function(e,r){e>=t&&(this.__redo__[r]=++e)},this),this.__redo__.push(t)):kH(this,"__redo__",iq("c",[t])))}),_onDelete:iq(function(t){var e;t>=this.__nextIndex__||(--this.__nextIndex__,this.__redo__&&(-1!==(e=this.__redo__.indexOf(t))&&this.__redo__.splice(e,1),this.__redo__.forEach(function(e,r){e>t&&(this.__redo__[r]=--e)},this)))}),_onClear:iq(function(){this.__redo__&&function(){return uq(this).length=0,this}.call(this.__redo__),this.__nextIndex__=0})}))),kH(wH.prototype,oH.iterator,iq(function(){return this}));var TH,SH,CH=Object.defineProperty;SH=TH=function(t,e){if(!(this instanceof SH))throw new TypeError("Constructor requires 'new'");AH.call(this,t),e=e?yq.call(e,"key+value")?"key+value":yq.call(e,"key")?"key":"value":"value",CH(this,"__kind__",iq("",e))},Eq&&Eq(SH,AH),delete SH.prototype.constructor,SH.prototype=Object.create(AH.prototype,{_resolve:iq(function(t){return"value"===this.__kind__?this.__list__[t]:"key+value"===this.__kind__?[t,this.__list__[t]]:t})}),CH(SH.prototype,oH.toStringTag,iq("c","Array Iterator"));var EH,LH,PH=Object.defineProperty;LH=EH=function(t){if(!(this instanceof LH))throw new TypeError("Constructor requires 'new'");t=String(t),AH.call(this,t),PH(this,"__length__",iq("",t.length))},Eq&&Eq(LH,AH),delete LH.prototype.constructor,LH.prototype=Object.create(AH.prototype,{_next:iq(function(){if(this.__list__)return this.__nextIndex__=55296&&e<=56319?r+this.__list__[this.__nextIndex__++]:r})}),PH(LH.prototype,oH.toStringTag,iq("c","String Iterator"));var zH,DH=oH.iterator,IH=Array.isArray,OH=function(t){if(!function(t){return!(!oq(t)||!IH(t)&&!Nq(t)&&!Oq(t)&&"function"!=typeof t[DH])}(t))throw new TypeError(t+" is not iterable");return t},RH=oH.iterator,BH=function(t){return"function"==typeof OH(t)[RH]?t[RH]():Oq(t)?new TH(t):Nq(t)?new EH(t):new TH(t)},FH=Array.isArray,NH=Function.prototype.call,jH=Array.prototype.some,VH="function"==typeof WeakMap&&"[object WeakMap]"===Object.prototype.toString.call(new WeakMap),UH=oH.toStringTag,qH=Array.isArray,HH=Object.defineProperty,GH=Object.prototype.hasOwnProperty,WH=Object.getPrototypeOf,YH=zH=function(){var t,e=arguments[0];if(!(this instanceof zH))throw new TypeError("Constructor requires 'new'");return t=VH&&Eq&&WeakMap!==zH?Eq(new WeakMap,WH(this)):this,null!=e&&(qH(e)||(e=BH(e))),HH(t,"__weakMapData__",iq("c","$weakMap$"+function(){var t;do{t=zq().toString(36).slice(2)}while(Pq[t]);return t}())),e?(function(t,e){var r,n,i,a,o,s,l,u,c=arguments[2];if(FH(t)||Oq(t)?r="array":Nq(t)?r="string":t=BH(t),Rq(e),i=function(){a=!0},"array"!==r)if("string"!==r)for(n=t.next();!n.done;){if(NH.call(e,c,n.value,i),a)return;n=t.next()}else for(s=t.length,o=0;o=55296&&u<=56319&&(l+=t[++o]),NH.call(e,c,l,i),!a);++o);else jH.call(t,function(t){return NH.call(e,c,t,i),a})}(e,function(e){uq(e),t.set(e[0],e[1])}),t):t};VH&&(Eq&&Eq(zH,WeakMap),zH.prototype=Object.create(WeakMap.prototype,{constructor:iq(zH)})),Object.defineProperties(zH.prototype,{delete:iq(function(t){return!!GH.call(Lq(t),this.__weakMapData__)&&(delete t[this.__weakMapData__],!0)}),get:iq(function(t){if(GH.call(Lq(t),this.__weakMapData__))return t[this.__weakMapData__]}),has:iq(function(t){return GH.call(Lq(t),this.__weakMapData__)}),set:iq(function(t,e){return HH(Lq(t),this.__weakMapData__,iq("c",e)),this}),toString:iq(function(){return"[object WeakMap]"})}),HH(zH.prototype,UH,iq("c","WeakMap"));var XH=function(){var t,e;if("function"!=typeof WeakMap)return!1;try{t=new WeakMap([[e={},"one"],[{},"two"],[{},"three"]])}catch(t){return!1}return"[object WeakMap]"===String(t)&&"function"==typeof t.set&&t.set({},1)===t&&"function"==typeof t.delete&&"function"==typeof t.has&&"one"===t.get(e)}()?WeakMap:YH,ZH=MU.float32,JH=MU.fract32,KH=QH;function QH(t,e){if(!(this instanceof QH))return new QH(t,e);if("function"==typeof t?(e||(e={}),e.regl=t):e=t,e.length&&(e.positions=e),!(t=e.regl).hasExtension("ANGLE_instanced_arrays"))throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled");this.gl=t._gl,this.regl=t,this.passes=[],this.shaders=QH.shaders.has(t)?QH.shaders.get(t):QH.shaders.set(t,QH.createShaders(t)).get(t),this.update(e)}QH.dashMult=2,QH.maxPatternLength=256,QH.precisionThreshold=3e6,QH.maxPoints=1e4,QH.shaders=new XH,QH.createShaders=function(t){var e,r=t.buffer({usage:"static",type:"float",data:[0,1,0,0,1,1,1,0]}),n={primitive:"triangle strip",instances:t.prop("count"),count:4,offset:0,uniforms:{miterMode:function(t,e){return"round"===e.join?2:1},miterLimit:t.prop("miterLimit"),scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),thickness:t.prop("thickness"),dashPattern:t.prop("dashTexture"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),dashSize:t.prop("dashLength"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},blend:{enable:!0,color:[0,0,0,0],equation:{rgb:"add",alpha:"add"},func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},depth:{enable:function(t,e){return!e.overlay}},stencil:{enable:!1},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport")},i=t(eu({vert:Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, aCoordFract, bCoordFract;\nattribute vec4 color;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nconst float MAX_LINES = 256.;\n\nvec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) {\n\t// the order is important\n\treturn position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n}\n\nvoid main() {\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineOffset = lineTop * 2. - 1.;\n\tfloat depth = (MAX_LINES - 1. - id) / (MAX_LINES);\n\n\tvec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract);\n\ttangent = normalize(diff * scale * viewport.zw);\n\tvec2 normal = vec2(-tangent.y, tangent.x);\n\n\tvec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart\n\t\t+ project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd\n\n\t\t+ thickness * normal * .5 * lineOffset / viewport.zw;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n}\n"]),frag:Q_(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\n\nuniform float dashSize, pixelRatio, thickness, opacity, id;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\n\nvoid main() {\n\tfloat alpha = 1.;\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:r,divisor:0,stride:8,offset:0},lineTop:{buffer:r,divisor:0,stride:8,offset:4},aCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:8,divisor:1},bCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:16,divisor:1},aCoordFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:8,divisor:1},bCoordFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:16,divisor:1},color:{buffer:t.prop("colorBuffer"),stride:4,offset:0,divisor:1}}},n));try{e=t(eu({cull:{enable:!0,face:"back"},vert:Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 aCoord, bCoord, nextCoord, prevCoord;\nattribute vec4 aColor, bColor;\nattribute float lineEnd, lineTop;\n\nuniform vec2 scale, translate;\nuniform float thickness, pixelRatio, id;\nuniform vec4 viewport;\nuniform float miterLimit, miterMode;\n\nvarying vec4 fragColor;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 tangent;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nconst float MAX_LINES = 256.;\nconst float REVERSE_THRESHOLD = -.875;\nconst float MIN_DIFF = 1e-6;\n\n//TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead\n//TODO: precalculate dot products, normalize things beforehead etc.\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nbool isNaN( float val ){\n return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true;\n}\n\nvoid main() {\n\tvec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord;\n\n\t// adjust scale for horizontal bars\n\tvec2 scale = max(scale, MIN_DIFF);\n\tvec2 scaleRatio = scale * viewport.zw;\n\n\tvec2 normalWidth = thickness / (scale * viewport.zw);\n\n\tfloat lineStart = 1. - lineEnd;\n\tfloat lineBot = 1. - lineTop;\n\tfloat depth = (MAX_LINES - 1. - id) / MAX_LINES;\n\n\tfragColor = (lineStart * aColor + lineEnd * bColor) / 255.;\n\n\tif (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return;\n\n\tif (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord);\n\tif (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord);\n\n\tvec2 prevDiff = aCoord - prevCoord;\n\tvec2 currDiff = bCoord - aCoord;\n\tvec2 nextDiff = nextCoord - bCoord;\n\n\tvec2 prevTangent = normalize(prevDiff * scaleRatio);\n\tvec2 currTangent = normalize(currDiff * scaleRatio);\n\tvec2 nextTangent = normalize(nextDiff * scaleRatio);\n\n\tvec2 prevNormal = vec2(-prevTangent.y, prevTangent.x);\n\tvec2 currNormal = vec2(-currTangent.y, currTangent.x);\n\tvec2 nextNormal = vec2(-nextTangent.y, nextTangent.x);\n\n\tvec2 startJoinDirection = normalize(prevTangent - currTangent);\n\tvec2 endJoinDirection = normalize(currTangent - nextTangent);\n\n\t//collapsed/unidirectional segment cases\n\tvec2 prevTanDiff = abs(prevTangent - currTangent);\n\tvec2 nextTanDiff = abs(nextTangent - currTangent);\n\tif (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) {\n\t\tstartJoinDirection = currNormal;\n\t}\n\tif (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) {\n\t\tendJoinDirection = currNormal;\n\t}\n\tif (aCoord == bCoord) {\n\t\tendJoinDirection = startJoinDirection;\n\t\tcurrNormal = prevNormal;\n\t\tcurrTangent = prevTangent;\n\t}\n\n\ttangent = currTangent;\n\n\t//calculate join shifts relative to normals\n\tfloat startJoinShift = dot(currNormal, startJoinDirection);\n\tfloat endJoinShift = dot(currNormal, endJoinDirection);\n\n\tfloat startMiterRatio = abs(1. / startJoinShift);\n\tfloat endMiterRatio = abs(1. / endJoinShift);\n\n\tvec2 startJoin = startJoinDirection * startMiterRatio;\n\tvec2 endJoin = endJoinDirection * endMiterRatio;\n\n\tvec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin;\n\tstartTopJoin = sign(startJoinShift) * startJoin * .5;\n\tstartBotJoin = -startTopJoin;\n\n\tendTopJoin = sign(endJoinShift) * endJoin * .5;\n\tendBotJoin = -endTopJoin;\n\n\tvec2 aTopCoord = aCoord + normalWidth * startTopJoin;\n\tvec2 bTopCoord = bCoord + normalWidth * endTopJoin;\n\tvec2 aBotCoord = aCoord + normalWidth * startBotJoin;\n\tvec2 bBotCoord = bCoord + normalWidth * endBotJoin;\n\n\t//miter anti-clipping\n\tfloat baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x)));\n\tfloat abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x)));\n\n\t//prevent close to reverse direction switch\n\tbool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal);\n\tbool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal);\n\n\tif (prevReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.);\n\t\taBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\taTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) {\n\t\t//handle miter clipping\n\t\tbTopCoord -= normalWidth * endTopJoin;\n\t\tbTopCoord += normalize(endTopJoin * normalWidth) * baClipping;\n\t}\n\n\tif (nextReverse) {\n\t\t//make join rectangular\n\t\tvec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5;\n\t\tfloat normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.);\n\t\tbBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5;\n\t\tbTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5;\n\t}\n\telse if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) {\n\t\t//handle miter clipping\n\t\taBotCoord -= normalWidth * startBotJoin;\n\t\taBotCoord += normalize(startBotJoin * normalWidth) * abClipping;\n\t}\n\n\tvec2 aTopPosition = (aTopCoord) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + translate;\n\n\t//position is normalized 0..1 coord on the screen\n\tvec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd;\n\n\tstartCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\tendCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tenableStartMiter = step(dot(currTangent, prevTangent), .5);\n\tenableEndMiter = step(dot(currTangent, nextTangent), .5);\n\n\t//bevel miter cutoffs\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n\n\t//round miter cutoffs\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tvec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5;\n\t\t\tstartCutoff = vec4(aCoord, aCoord);\n\t\t\tstartCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio;\n\t\t\tstartCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tstartCutoff += viewport.xyxy;\n\t\t\tstartCutoff += startMiterWidth.xyxy;\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tvec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5;\n\t\t\tendCutoff = vec4(bCoord, bCoord);\n\t\t\tendCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio;\n\t\t\tendCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw;\n\t\t\tendCutoff += viewport.xyxy;\n\t\t\tendCutoff += endMiterWidth.xyxy;\n\t\t}\n\t}\n}\n"]),frag:Q_(["precision highp float;\n#define GLSLIFY 1\n\nuniform sampler2D dashPattern;\nuniform float dashSize, pixelRatio, thickness, opacity, id, miterMode;\n\nvarying vec4 fragColor;\nvarying vec2 tangent;\nvarying vec4 startCutoff, endCutoff;\nvarying vec2 startCoord, endCoord;\nvarying float enableStartMiter, enableEndMiter;\n\nfloat distToLine(vec2 p, vec2 a, vec2 b) {\n\tvec2 diff = b - a;\n\tvec2 perp = normalize(vec2(-diff.y, diff.x));\n\treturn dot(p - a, perp);\n}\n\nvoid main() {\n\tfloat alpha = 1., distToStart, distToEnd;\n\tfloat cutoff = thickness * .5;\n\n\t//bevel miter\n\tif (miterMode == 1.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToStart + 1., 0.), 1.);\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < -1.) {\n\t\t\t\tdiscard;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\talpha *= min(max(distToEnd + 1., 0.), 1.);\n\t\t}\n\t}\n\n\t// round miter\n\telse if (miterMode == 2.) {\n\t\tif (enableStartMiter == 1.) {\n\t\t\tdistToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw);\n\t\t\tif (distToStart < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - startCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\n\t\tif (enableEndMiter == 1.) {\n\t\t\tdistToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw);\n\t\t\tif (distToEnd < 0.) {\n\t\t\t\tfloat radius = length(gl_FragCoord.xy - endCoord);\n\n\t\t\t\tif(radius > cutoff + .5) {\n\t\t\t\t\tdiscard;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\talpha -= smoothstep(cutoff - .5, cutoff + .5, radius);\n\t\t\t}\n\t\t}\n\t}\n\n\tfloat t = fract(dot(tangent, gl_FragCoord.xy) / dashSize) * .5 + .25;\n\tfloat dash = texture2D(dashPattern, vec2(t, .5)).r;\n\n\tgl_FragColor = fragColor;\n\tgl_FragColor.a *= alpha * opacity * dash;\n}\n"]),attributes:{lineEnd:{buffer:r,divisor:0,stride:8,offset:0},lineTop:{buffer:r,divisor:0,stride:8,offset:4},aColor:{buffer:t.prop("colorBuffer"),stride:4,offset:0,divisor:1},bColor:{buffer:t.prop("colorBuffer"),stride:4,offset:4,divisor:1},prevCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:0,divisor:1},aCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:8,divisor:1},bCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:16,divisor:1},nextCoord:{buffer:t.prop("positionBuffer"),stride:8,offset:24,divisor:1}}},n))}catch(t){e=i}return{fill:t({primitive:"triangle",elements:function(t,e){return e.triangles},offset:0,vert:Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec2 position, positionFract;\n\nuniform vec4 color;\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio, id;\nuniform vec4 viewport;\nuniform float opacity;\n\nvarying vec4 fragColor;\n\nconst float MAX_LINES = 256.;\n\nvoid main() {\n\tfloat depth = (MAX_LINES - 4. - id) / (MAX_LINES);\n\n\tvec2 position = position * scale + translate\n + positionFract * scale + translateFract\n + position * scaleFract\n + positionFract * scaleFract;\n\n\tgl_Position = vec4(position * 2.0 - 1.0, depth, 1);\n\n\tfragColor = color / 255.;\n\tfragColor.a *= opacity;\n}\n"]),frag:Q_(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n\tgl_FragColor = fragColor;\n}\n"]),uniforms:{scale:t.prop("scale"),color:t.prop("fill"),scaleFract:t.prop("scaleFract"),translateFract:t.prop("translateFract"),translate:t.prop("translate"),opacity:t.prop("opacity"),pixelRatio:t.context("pixelRatio"),id:t.prop("id"),viewport:function(t,e){return[e.viewport.x,e.viewport.y,t.viewportWidth,t.viewportHeight]}},attributes:{position:{buffer:t.prop("positionBuffer"),stride:8,offset:8},positionFract:{buffer:t.prop("positionFractBuffer"),stride:8,offset:8}},blend:n.blend,depth:{enable:!1},scissor:n.scissor,stencil:n.stencil,viewport:n.viewport}),rect:i,miter:e}},QH.defaults={dashes:null,join:"miter",miterLimit:1,thickness:10,cap:"square",color:"black",opacity:1,overlay:!1,viewport:null,range:null,close:!1,fill:null},QH.prototype.render=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];e.length&&(t=this).update.apply(t,e),this.draw()},QH.prototype.draw=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];return(e.length?e:this.passes).forEach(function(e,r){if(e&&Array.isArray(e))return(n=t).draw.apply(n,e);var n;("number"==typeof e&&(e=t.passes[e]),e&&e.count>1&&e.opacity)&&(t.regl._refresh(),e.fill&&e.triangles&&e.triangles.length>2&&t.shaders.fill(e),e.thickness&&(e.scale[0]*e.viewport.width>QH.precisionThreshold||e.scale[1]*e.viewport.height>QH.precisionThreshold?t.shaders.rect(e):"rect"===e.join||!e.join&&(e.thickness<=2||e.count>=QH.maxPoints)?t.shaders.rect(e):t.shaders.miter(e)))}),this},QH.prototype.update=function(t){var e=this;if(t){null!=t.length?"number"==typeof t[0]&&(t=[{positions:t}]):Array.isArray(t)||(t=[t]);var r=this.regl,n=this.gl;if(t.forEach(function(t,i){var a=e.passes[i];if(void 0!==t)if(null!==t){if("number"==typeof t[0]&&(t={positions:t}),t=gU(t,{positions:"positions points data coords",thickness:"thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth",join:"lineJoin linejoin join type mode",miterLimit:"miterlimit miterLimit",dashes:"dash dashes dasharray dash-array dashArray",color:"color colour stroke colors colours stroke-color strokeColor",fill:"fill fill-color fillColor",opacity:"alpha opacity",overlay:"overlay crease overlap intersect",close:"closed close closed-path closePath",range:"range dataBox",viewport:"viewport viewBox",hole:"holes hole hollow"}),a||(e.passes[i]=a={id:i,scale:null,scaleFract:null,translate:null,translateFract:null,count:0,hole:[],dashLength:1,dashTexture:r.texture({channels:1,data:new Uint8Array([255]),width:1,height:1,mag:"linear",min:"linear"}),colorBuffer:r.buffer({usage:"dynamic",type:"uint8",data:null}),positionBuffer:r.buffer({usage:"dynamic",type:"float",data:null}),positionFractBuffer:r.buffer({usage:"dynamic",type:"float",data:null})},t=eu({},QH.defaults,t)),null!=t.thickness&&(a.thickness=parseFloat(t.thickness)),null!=t.opacity&&(a.opacity=parseFloat(t.opacity)),null!=t.miterLimit&&(a.miterLimit=parseFloat(t.miterLimit)),null!=t.overlay&&(a.overlay=!!t.overlay),null!=t.join&&(a.join=t.join),null!=t.hole&&(a.hole=t.hole),null!=t.fill&&(a.fill=t.fill?gL(t.fill,"uint8"):null),null!=t.viewport&&(a.viewport=yU(t.viewport)),a.viewport||(a.viewport=yU([n.drawingBufferWidth,n.drawingBufferHeight])),null!=t.close&&(a.close=t.close),null===t.positions&&(t.positions=[]),t.positions){var o,s;if(t.positions.x&&t.positions.y){var l=t.positions.x,u=t.positions.y;s=a.count=Math.max(l.length,u.length),o=new Float64Array(2*s);for(var c=0;c>>24,n=(16711680&t)>>>16,i=(65280&t)>>>8,a=255&t;return!1===e?[r,n,i,a]:[r/255,n/255,i/255,a/255]};var eG="undefined"!=typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)),rG=MU.float32,nG=MU.fract32,iG=aG;function aG(t,e){var r=this;if(!(this instanceof aG))return new aG(t,e);"function"==typeof t?(e||(e={}),e.regl=t):(e=t,t=null),e&&e.length&&(e.positions=e);var n,i=(t=e.regl)._gl,a=[];this.tooManyColors=eG,n=t.texture({data:new Uint8Array(1020),width:255,height:1,type:"uint8",format:"rgba",wrapS:"clamp",wrapT:"clamp",mag:"nearest",min:"nearest"}),eu(this,{regl:t,gl:i,groups:[],markerCache:[null],markerTextures:[null],palette:a,paletteIds:{},paletteTexture:n,maxColors:255,maxSize:100,canvas:i.canvas}),this.update(e);var o={uniforms:{pixelRatio:t.context("pixelRatio"),palette:n,paletteSize:function(t,e){return[r.tooManyColors?0:255,n.height]},scale:t.prop("scale"),scaleFract:t.prop("scaleFract"),translate:t.prop("translate"),translateFract:t.prop("translateFract"),opacity:t.prop("opacity"),marker:t.prop("markerTexture")},attributes:{x:function(t,e){return e.xAttr||{buffer:e.positionBuffer,stride:8,offset:0}},y:function(t,e){return e.yAttr||{buffer:e.positionBuffer,stride:8,offset:4}},xFract:function(t,e){return e.xAttr?{constant:[0,0]}:{buffer:e.positionFractBuffer,stride:8,offset:0}},yFract:function(t,e){return e.yAttr?{constant:[0,0]}:{buffer:e.positionFractBuffer,stride:8,offset:4}},size:function(t,e){return e.size.length?{buffer:e.sizeBuffer,stride:2,offset:0}:{constant:[Math.round(255*e.size/r.maxSize)]}},borderSize:function(t,e){return e.borderSize.length?{buffer:e.sizeBuffer,stride:2,offset:1}:{constant:[Math.round(255*e.borderSize/r.maxSize)]}},colorId:function(t,e){return e.color.length?{buffer:e.colorBuffer,stride:r.tooManyColors?8:4,offset:0}:{constant:r.tooManyColors?a.slice(4*e.color,4*e.color+4):[e.color]}},borderColorId:function(t,e){return e.borderColor.length?{buffer:e.colorBuffer,stride:r.tooManyColors?8:4,offset:r.tooManyColors?4:2}:{constant:r.tooManyColors?a.slice(4*e.borderColor,4*e.borderColor+4):[e.borderColor]}},isActive:function(t,e){return!0===e.activation?{constant:[1]}:e.activation?e.activation:{constant:[0]}}},blend:{enable:!0,color:[0,0,0,1],func:{srcRGB:"src alpha",dstRGB:"one minus src alpha",srcAlpha:"one minus dst alpha",dstAlpha:"one"}},scissor:{enable:!0,box:t.prop("viewport")},viewport:t.prop("viewport"),stencil:{enable:!1},depth:{enable:!1},elements:t.prop("elements"),count:t.prop("count"),offset:t.prop("offset"),primitive:"points"},s=eu({},o);s.frag=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nuniform sampler2D marker;\nuniform float pixelRatio, opacity;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(marker, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n return;\n }\n\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n}\n"]),s.vert=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform float pixelRatio;\nuniform sampler2D palette;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius,\n fragWidth, fragBorderColorLevel, fragColorLevel;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pixelRatio;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]);try{this.drawMarker=t(s)}catch(t){}var l=eu({},o);l.frag=Q_(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\n\nuniform float opacity;\nvarying float fragBorderRadius, fragWidth;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n\tfloat t;\n\tt = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n\treturn t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n\tfloat radius, alpha = 1.0, delta = fragWidth;\n\n\tradius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n\tif (radius > 1.0 + delta) {\n\t\tdiscard;\n\t}\n\n\talpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n\tfloat borderRadius = fragBorderRadius;\n\tfloat ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n\tvec4 color = mix(fragColor, fragBorderColor, ratio);\n\tcolor.a *= alpha * opacity;\n\tgl_FragColor = color;\n}\n"]),l.vert=Q_(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\nuniform vec2 scale, scaleFract, translate, translateFract;\nuniform float pixelRatio;\nuniform sampler2D palette;\nuniform vec2 paletteSize;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0, 1);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]),eG&&(l.frag=l.frag.replace("smoothstep","smoothStep")),this.drawCircle=t(l)}aG.defaults={color:"black",borderColor:"transparent",borderSize:0,size:12,opacity:1,marker:void 0,viewport:null,range:null,pixelSize:null,count:0,offset:0,bounds:null,positions:[],snap:1e4},aG.prototype.render=function(){for(var t,e=[],r=arguments.length;r--;)e[r]=arguments[r];return e.length&&(t=this).update.apply(t,e),this.draw(),this},aG.prototype.draw=function(){for(var t=this,e=[],r=arguments.length;r--;)e[r]=arguments[r];var n=this.groups;if(1===e.length&&Array.isArray(e[0])&&(null===e[0][0]||Array.isArray(e[0][0]))&&(e=e[0]),e.length)for(var i=0;in)?e.tree=kU(t,{bounds:u}):n&&n.length&&(e.tree=n),e.tree){var c={primitive:"points",usage:"static",data:e.tree,type:"uint32"};e.elements?e.elements(c):e.elements=a.elements(c)}return i({data:rG(t),usage:"dynamic"}),o({data:nG(t),usage:"dynamic"}),s({data:new Uint8Array(l),type:"uint8",usage:"stream"}),t}},{marker:function(e,r,n){var i=r.activation;if(i.forEach(function(t){return t&&t.destroy&&t.destroy()}),i.length=0,e&&"number"!=typeof e[0]){for(var o=[],s=0,l=Math.min(e.length,r.count);s=0)return a;if(t instanceof Uint8Array||t instanceof Uint8ClampedArray)e=t;else{e=new Uint8Array(t.length);for(var o=0,s=t.length;on*n*4&&(this.tooManyColors=!0),this.updatePalette(r),1===i.length?i[0]:i},aG.prototype.updatePalette=function(t){if(!this.tooManyColors){var e=this.maxColors,r=this.paletteTexture,n=Math.ceil(.25*t.length/e);if(n>1)for(var i=.25*(t=t.slice()).length%e;i7&&(r.push(p.splice(0,7)),p.unshift("C"));break;case"S":var g=u,v=c;"C"!=e&&"S"!=e||(g+=g-n,v+=v-i),p=["C",g,v,p[1],p[2],p[3],p[4]];break;case"T":"Q"==e||"T"==e?(s=2*u-s,l=2*c-l):(s=u,l=c),p=AG(u,c,s,l,p[1],p[2]);break;case"Q":s=p[1],l=p[2],p=AG(u,c,p[1],p[2],p[3],p[4]);break;case"L":p=MG(u,c,p[1],p[2]);break;case"H":p=MG(u,c,p[1],c);break;case"V":p=MG(u,c,u,p[1]);break;case"Z":p=MG(u,c,a,o)}e=d,u=p[p.length-2],c=p[p.length-1],p.length>4?(n=p[p.length-4],i=p[p.length-3]):(n=u,i=c),r.push(p)}return r};function MG(t,e,r,n){return["C",t,e,r,n,r,n]}function AG(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}function TG(t,e,r,n,i,a,o,s,l,u){if(u)x=u[0],b=u[1],m=u[2],y=u[3];else{var c=SG(t,e,-i);t=c.x,e=c.y;var h=(t-(s=(c=SG(s,l,-i)).x))/2,f=(e-(l=c.y))/2,p=h*h/(r*r)+f*f/(n*n);p>1&&(r*=p=Math.sqrt(p),n*=p);var d=r*r,g=n*n,v=(a==o?-1:1)*Math.sqrt(Math.abs((d*g-d*f*f-g*h*h)/(d*f*f+g*h*h)));v==1/0&&(v=1);var m=v*r*f/n+(t+s)/2,y=v*-n*h/r+(e+l)/2,x=Math.asin(((e-y)/n).toFixed(9)),b=Math.asin(((l-y)/n).toFixed(9));x=tb&&(x-=2*_G),!o&&b>x&&(b-=2*_G)}if(Math.abs(b-x)>wG){var _=b,w=s,k=l;b=x+wG*(o&&b>x?1:-1);var M=TG(s=m+r*Math.cos(b),l=y+n*Math.sin(b),r,n,i,0,o,w,k,[b,_,m,y])}var A=Math.tan((b-x)/4),T=4/3*r*A,S=4/3*n*A,C=[2*t-(t+T*Math.sin(x)),2*e-(e-S*Math.cos(x)),s+T*Math.sin(b),l-S*Math.cos(b),s,l];if(u)return C;M&&(C=C.concat(M));for(var E=0;E4))},zG=function(t){var e=[];return t.replace(IG,function(t,r,n){var i=r.toLowerCase();for(n=function(t){var e=t.match(OG);return e?e.map(Number):[]}(n),"m"==i&&n.length>2&&(e.push([r].concat(n.splice(0,2))),i="l",r="m"==r?"l":"L");;){if(n.length==DG[i])return n.unshift(r),e.push(n);if(n.length=o)return t;switch(t){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return t}}),l=i[n];n=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),f(e)?r.showHidden=e:e&&FG._extend(r,e),v(r.showHidden)&&(r.showHidden=!1),v(r.depth)&&(r.depth=2),v(r.colors)&&(r.colors=!1),v(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),l(r,t,r.depth)}function o(t,e){var r=a.styles[e];return r?"\x1b["+a.colors[r][0]+"m"+t+"\x1b["+a.colors[r][1]+"m":t}function s(t,e){return t}function l(t,e,r){if(t.customInspect&&e&&_(e.inspect)&&e.inspect!==FG.inspect&&(!e.constructor||e.constructor.prototype!==e)){var n=e.inspect(r,t);return g(n)||(n=l(t,n,r)),n}var i=function(t,e){if(v(e))return t.stylize("undefined","undefined");if(g(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(d(e))return t.stylize(""+e,"number");if(f(e))return t.stylize(""+e,"boolean");if(p(e))return t.stylize("null","null")}(t,e);if(i)return i;var a=Object.keys(e),o=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(e)),b(e)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return u(e);if(0===a.length){if(_(e)){var s=e.name?": "+e.name:"";return t.stylize("[Function"+s+"]","special")}if(m(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(x(e))return t.stylize(Date.prototype.toString.call(e),"date");if(b(e))return u(e)}var y,w="",k=!1,M=["{","}"];(h(e)&&(k=!0,M=["[","]"]),_(e))&&(w=" [Function"+(e.name?": "+e.name:"")+"]");return m(e)&&(w=" "+RegExp.prototype.toString.call(e)),x(e)&&(w=" "+Date.prototype.toUTCString.call(e)),b(e)&&(w=" "+u(e)),0!==a.length||k&&0!=e.length?r<0?m(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),y=k?function(t,e,r,n,i){for(var a=[],o=0,s=e.length;o=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(y,w,M)):M[0]+w+M[1]}function u(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,e,r,n,i,a){var o,s,u;if((u=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?s=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(s=t.stylize("[Setter]","special")),A(n,i)||(o="["+i+"]"),s||(t.seen.indexOf(u.value)<0?(s=p(r)?l(t,u.value,null):l(t,u.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return" "+t}).join("\n")):s=t.stylize("[Circular]","special")),v(o)){if(a&&i.match(/^\d+$/))return s;(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=t.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=t.stylize(o,"string"))}return o+": "+s}function h(t){return Array.isArray(t)}function f(t){return"boolean"==typeof t}function p(t){return null===t}function d(t){return"number"==typeof t}function g(t){return"string"==typeof t}function v(t){return void 0===t}function m(t){return y(t)&&"[object RegExp]"===w(t)}function y(t){return"object"==typeof t&&null!==t}function x(t){return y(t)&&"[object Date]"===w(t)}function b(t){return y(t)&&("[object Error]"===w(t)||t instanceof Error)}function _(t){return"function"==typeof t}function w(t){return Object.prototype.toString.call(t)}function k(t){return t<10?"0"+t.toString(10):t.toString(10)}FG.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!i[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var r=t.pid;i[e]=function(){var t=FG.format.apply(FG,arguments);console.error("%s %d: %s",e,r,t)}}else i[e]=function(){};return i[e]},FG.inspect=a,a.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]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},FG.isArray=h,FG.isBoolean=f,FG.isNull=p,FG.isNullOrUndefined=function(t){return null==t},FG.isNumber=d,FG.isString=g,FG.isSymbol=function(t){return"symbol"==typeof t},FG.isUndefined=v,FG.isRegExp=m,FG.isObject=y,FG.isDate=x,FG.isError=b,FG.isFunction=_,FG.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},FG.isBuffer=BG;var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function A(t,e){return Object.prototype.hasOwnProperty.call(t,e)}FG.log=function(){var t,e;console.log("%s - %s",(t=new Date,e=[k(t.getHours()),k(t.getMinutes()),k(t.getSeconds())].join(":"),[t.getDate(),M[t.getMonth()],e].join(" ")),FG.format.apply(FG,arguments))},FG.inherits=RG,FG._extend=function(t,e){if(!e||!y(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,_d,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var NG={};(function(t){"use strict";function e(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);i=0;l--)if(u[l]!==c[l])return!1;for(l=u.length-1;l>=0;l--)if(s=u[l],!g(t[s],e[s],r,n))return!1;return!0}(t,n,a,l))}return a?t===n:t==n}function v(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function m(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function y(t,e,r,n){var i;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&p(i,r,"Missing expected exception"+n);var a="string"==typeof n,o=!t&&FG.isError(i),s=!t&&i&&!r;if((o&&a&&m(i,r)||s)&&p(i,r,"Got unwanted exception"+n),t&&i&&r&&!m(i,r)||!t&&i)throw i}l.AssertionError=function(t){var e;this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=h(f((e=this).actual),128)+" "+e.operator+" "+h(f(e.expected),128),this.generatedMessage=!0);var r=t.stackStartFunction||p;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,a=c(r),o=i.indexOf("\n"+a);if(o>=0){var s=i.indexOf("\n",o+1);i=i.substring(s+1)}this.stack=i}}},FG.inherits(l.AssertionError,Error),l.fail=p,l.ok=d,l.equal=function(t,e,r){t!=e&&p(t,e,r,"==",l.equal)},l.notEqual=function(t,e,r){t==e&&p(t,e,r,"!=",l.notEqual)},l.deepEqual=function(t,e,r){g(t,e,!1)||p(t,e,r,"deepEqual",l.deepEqual)},l.deepStrictEqual=function(t,e,r){g(t,e,!0)||p(t,e,r,"deepStrictEqual",l.deepStrictEqual)},l.notDeepEqual=function(t,e,r){g(t,e,!1)&&p(t,e,r,"notDeepEqual",l.notDeepEqual)},l.notDeepStrictEqual=function t(e,r,n){g(e,r,!0)&&p(e,r,n,"notDeepStrictEqual",t)},l.strictEqual=function(t,e,r){t!==e&&p(t,e,r,"===",l.strictEqual)},l.notStrictEqual=function(t,e,r){t===e&&p(t,e,r,"!==",l.notStrictEqual)},l.throws=function(t,e,r){y(!0,t,e,r)},l.doesNotThrow=function(t,e,r){y(!1,t,e,r)},l.ifError=function(t){if(t)throw t};var x=Object.keys||function(t){var e=[];for(var r in t)n.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var jG={};Object.defineProperty(jG,"__esModule",{value:!0});var VG=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=t[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!e||r.length!==e);n=!0);}catch(t){i=!0,a=t}finally{try{!n&&s.return&&s.return()}finally{if(i)throw a}}return r}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),UG=2*Math.PI,qG=function(t,e,r,n,i,a,o){var s=t.x,l=t.y;return{x:n*(s*=e)-i*(l*=r)+a,y:i*s+n*l+o}},HG=function(t,e){var r=4/3*Math.tan(e/4),n=Math.cos(t),i=Math.sin(t),a=Math.cos(t+e),o=Math.sin(t+e);return[{x:n-i*r,y:i+n*r},{x:a+o*r,y:o-a*r},{x:a,y:o}]},GG=function(t,e,r,n){var i=t*n-e*r<0?-1:1,a=(t*r+e*n)/(Math.sqrt(t*t+e*e)*Math.sqrt(t*t+e*e));return a>1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)};jG.default=function(t){var e=t.px,r=t.py,n=t.cx,i=t.cy,a=t.rx,o=t.ry,s=t.xAxisRotation,l=void 0===s?0:s,u=t.largeArcFlag,c=void 0===u?0:u,h=t.sweepFlag,f=void 0===h?0:h,p=[];if(0===a||0===o)return[];var d=Math.sin(l*UG/360),g=Math.cos(l*UG/360),v=g*(e-n)/2+d*(r-i)/2,m=-d*(e-n)/2+g*(r-i)/2;if(0===v&&0===m)return[];a=Math.abs(a),o=Math.abs(o);var y=Math.pow(v,2)/Math.pow(a,2)+Math.pow(m,2)/Math.pow(o,2);y>1&&(a*=Math.sqrt(y),o*=Math.sqrt(y));var x=function(t,e,r,n,i,a,o,s,l,u,c,h){var f=Math.pow(i,2),p=Math.pow(a,2),d=Math.pow(c,2),g=Math.pow(h,2),v=f*p-f*g-p*d;v<0&&(v=0),v/=f*g+p*d;var m=(v=Math.sqrt(v)*(o===s?-1:1))*i/a*h,y=v*-a/i*c,x=u*m-l*y+(t+r)/2,b=l*m+u*y+(e+n)/2,_=(c-m)/i,w=(h-y)/a,k=(-c-m)/i,M=(-h-y)/a,A=GG(1,0,_,w),T=GG(_,w,k,M);return 0===s&&T>0&&(T-=UG),1===s&&T<0&&(T+=UG),[x,b,A,T]}(e,r,n,i,a,o,c,f,d,g,v,m),b=VG(x,4),_=b[0],w=b[1],k=b[2],M=b[3],A=Math.max(Math.ceil(Math.abs(M)/(UG/4)),1);M/=A;for(var T=0;T4?(n=p[p.length-4],i=p[p.length-3]):(n=u,i=c),r.push(p)}return r};function YG(t,e,r,n){return["C",t,e,r,n,r,n]}function XG(t,e,r,n,i,a){return["C",t/3+2/3*r,e/3+2/3*n,i/3+2/3*r,a/3+2/3*n,i,a]}var ZG=function(t){Array.isArray(t)&&1===t.length&&"string"==typeof t[0]&&(t=t[0]);"string"==typeof t&&(NG(PG(t),"String is not an SVG path."),t=zG(t));if(NG(Array.isArray(t),"Argument should be a string or an array of path segments."),t=bG(t),!(t=WG(t)).length)return[0,0,0,0];for(var e=[1/0,1/0,-1/0,-1/0],r=0,n=t.length;re[2]&&(e[2]=i[a+0]),i[a+1]>e[3]&&(e[3]=i[a+1]);return e};var JG={};(function(t){"use strict";var e=document.createElement("canvas"),r=e.getContext("2d");JG=function(n,i){if(!PG(n))throw Error("Argument should be valid svg path string");i||(i={});var a,o;i.shape?(a=i.shape[0],o=i.shape[1]):(a=e.width=i.w||i.width||200,o=e.height=i.h||i.height||200);var s=Math.min(a,o),l=i.stroke||0,u=i.viewbox||i.viewBox||ZG(n),c=[a/(u[2]-u[0]),o/(u[3]-u[1])],h=Math.min(c[0]||0,c[1]||0)/2;r.fillStyle="black",r.fillRect(0,0,a,o),r.fillStyle="white",l&&("number"!=typeof l&&(l=1),r.strokeStyle=l>0?"white":"black",r.lineWidth=Math.abs(l));if(r.translate(.5*a,.5*o),r.scale(h,h),t.Path2D){var f=new Path2D(n);r.fill(f),l&&r.stroke(f)}else{var p=zG(n);LG(r,p),r.fill(),l&&r.stroke()}return r.setTransform(1,0,0,1,0,0),vG(r,{cutoff:null!=i.cutoff?i.cutoff:.5,radius:null!=i.radius?i.radius:.5*s})}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var KG=g.DESELECTDIM;function QG(t){var e,r,n=t._length||t._commonLength,i=t.marker,a={},o=Array.isArray(i.symbol),s=oe.isArrayOrTypedArray(i.color),l=oe.isArrayOrTypedArray(i.line.color),u=oe.isArrayOrTypedArray(i.opacity),c=oe.isArrayOrTypedArray(i.size),h=oe.isArrayOrTypedArray(i.line.width);if(o||(r=sG.OPEN_RE.test(i.symbol)),o||s||l||u){a.colors=new Array(n),a.borderColors=new Array(n);var f=EV(i,i.opacity,n),p=EV(i.line,i.opacity,n);if(!Array.isArray(p[0])){var d=p;for(p=Array(n),e=0;esG.TOO_MANY_POINTS?"rect":Er.hasMarkers(e)?"rect":"round";if(o&&e.connectgaps){var l=n[0],u=n[1];for(i=0;i1&&oe.extendFlat(i.line,fW(t,r,n)),i.errorX||i.errorY){var a=pW(t,r,n);i.errorX&&oe.extendFlat(i.errorX,a.x),i.errorY&&oe.extendFlat(i.errorY,a.y)}return i}function mW(t,e){var r=e._scene,n=t._fullLayout,i={count:0,dirty:!0,lineOptions:[],fillOptions:[],markerOptions:[],selectedOptions:[],unselectedOptions:[],errorXOptions:[],errorYOptions:[]};return e._scene||((r=e._scene=oe.extendFlat({},i,{selectBatch:null,unselectBatch:null,fill2d:!1,scatter2d:!1,error2d:!1,line2d:!1,select2d:null})).update=function(t){for(var e=new Array(r.count),n=0;n=gW&&(m.marker.cluster=h.tree),y.lineOptions.push(m.line),y.errorXOptions.push(m.errorX),y.errorYOptions.push(m.errorY),y.fillOptions.push(m.fill),y.markerOptions.push(m.marker),y.selectedOptions.push(m.selected),y.unselectedOptions.push(m.unselected),y.count++,h._scene=y,h.index=y.count-1,h.x=f,h.y=p,h.positions=d,h.count=u,t.firstscatter=!1,[{x:!1,y:!1,t:h,trace:e}]},plot:function(t,e,r){if(r.length){var n=t._fullLayout,i=r[0][0].t._scene,a=n.dragmode;if(i){var o=n._size,s=n.width,l=n.height;dB(t,["ANGLE_instanced_arrays","OES_element_index_uint"]);var u=n._glcanvas.data()[0].regl;if(Yx(t,e,r),i.dirty){if(!0===i.error2d&&(i.error2d=EU(u)),!0===i.line2d&&(i.line2d=KH(u)),!0===i.scatter2d&&(i.scatter2d=oG(u)),!0===i.fill2d&&(i.fill2d=KH(u)),i.line2d&&i.line2d.update(i.lineOptions),i.error2d){var c=(i.errorXOptions||[]).concat(i.errorYOptions||[]);i.error2d.update(c)}i.scatter2d&&i.scatter2d.update(i.markerOptions),i.fill2d&&(i.fillOptions=i.fillOptions.map(function(t,e){var n=r[e];if(!(t&&n&&n[0]&&n[0].trace))return null;var a,o,s=n[0],l=s.trace,u=s.t,c=i.lineOptions[e],h=[],f=c&&c.positions||u.positions;if("tozeroy"===l.fill)(h=(h=[f[0],0]).concat(f)).push(f[f.length-2]),h.push(0);else if("tozerox"===l.fill)(h=(h=[0,f[1]]).concat(f)).push(0),h.push(f[f.length-1]);else if("toself"===l.fill||"tonext"===l.fill){for(h=[],a=0,o=0;o0){e+=Math.abs(i(t[0]));for(var r=1;r2){for(l=0;li.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(o=i.maxw*i.maxh-t*r)a.free)){if(r===a.h)return this.allocShelf(s,t,r,n);r>a.h||rc)&&(h=2*Math.max(t,c)),(ll)&&(u=2*Math.max(r,l)),this.resize(h,u),this.packOne(t,r,n)):null},t.prototype.allocFreebin=function(t,e,r,n){var i=this.freebins.splice(t,1)[0];return i.id=n,i.w=e,i.h=r,i.refcount=0,this.bins[n]=i,this.ref(i),i},t.prototype.allocShelf=function(t,e,r,n){var i=this.shelves[t].alloc(e,r,n);return this.bins[n]=i,this.ref(i),i},t.prototype.shrink=function(){if(this.shelves.length>0){for(var t=0,e=0,r=0;rthis.free||e>this.h)return null;var n=this.x;return this.x+=t,this.free-=t,new function(t,e,r,n,i,a,o){this.id=t,this.x=e,this.y=r,this.w=n,this.h=i,this.maxw=a||n,this.maxh=o||i,this.refcount=0}(r,n,this.y,t,e,t,this.h)},e.prototype.resize=function(t){return this.free+=t-this.w,this.w=t,!0},t},"object"==typeof r&&void 0!==e?e.exports=i():n.ShelfPack=i()},{}],6:[function(t,e,r){function n(t,e,r,n,i,a){this.fontSize=t||24,this.buffer=void 0===e?3:e,this.cutoff=n||.25,this.fontFamily=i||"sans-serif",this.fontWeight=a||"normal",this.radius=r||8;var o=this.size=this.fontSize+2*this.buffer;this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=o,this.ctx=this.canvas.getContext("2d"),this.ctx.font=this.fontWeight+" "+this.fontSize+"px "+this.fontFamily,this.ctx.textBaseline="middle",this.ctx.fillStyle="black",this.gridOuter=new Float64Array(o*o),this.gridInner=new Float64Array(o*o),this.f=new Float64Array(o),this.d=new Float64Array(o),this.z=new Float64Array(o+1),this.v=new Int16Array(o),this.middle=Math.round(o/2*(navigator.userAgent.indexOf("Gecko/")>=0?1.2:1))}function i(t,e,r,n,i,o,s){for(var l=0;ln)return n;for(;ra?r=i:n=i,i=.5*(n-r)+r}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},{}],8:[function(t,e,r){e.exports.VectorTile=t("./lib/vectortile.js"),e.exports.VectorTileFeature=t("./lib/vectortilefeature.js"),e.exports.VectorTileLayer=t("./lib/vectortilelayer.js")},{"./lib/vectortile.js":9,"./lib/vectortilefeature.js":10,"./lib/vectortilelayer.js":11}],9:[function(t,e,r){function n(t,e,r){if(3===t){var n=new i(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n)}}var i=t("./vectortilelayer");e.exports=function(t,e){this.layers=t.readFields(n,{},e)}},{"./vectortilelayer":11}],10:[function(t,e,r){function n(t,e,r,n,a){this.properties={},this.extent=r,this.type=0,this._pbf=t,this._geometry=-1,this._keys=n,this._values=a,t.readFields(i,this,e)}function i(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3}if(i--,1===n||2===n)a+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&l.push(e),e=[]),e.push(new o(a,s));else{if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone())}}return e&&l.push(e),l},n.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,l=1/0,u=-1/0;t.pos>3}if(n--,1===r||2===r)i+=t.readSVarint(),a+=t.readSVarint(),is&&(s=i),au&&(u=a);else if(7!==r)throw new Error("unknown command "+r)}return[o,l,s,u]},n.prototype.toGeoJSON=function(t,e,r){function i(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null}return e}(r))}var a=t("./vectortilefeature.js");e.exports=n,n.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new a(this._pbf,e,this.extent,this._keys,this._values)}},{"./vectortilefeature.js":10}],12:[function(t,e,r){var n;n=this,function(t){function e(t,e,n){var i=r(256*t,256*(e=Math.pow(2,n)-e-1),n),a=r(256*(t+1),256*(e+1),n);return i[0]+","+i[1]+","+a[0]+","+a[1]}function r(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return[t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}t.getURL=function(t,r,n,i,a,o){return o=o||{},t+"?"+["bbox="+e(n,i,a),"format="+(o.format||"image/png"),"service="+(o.service||"WMS"),"version="+(o.version||"1.1.1"),"request="+(o.request||"GetMap"),"srs="+(o.srs||"EPSG:3857"),"width="+(o.width||256),"height="+(o.height||256),"layers="+r].join("&")},t.getTileBBox=e,t.getMercCoords=r,Object.defineProperty(t,"__esModule",{value:!0})}("object"==typeof r&&void 0!==e?r:n.WhooTS=n.WhooTS||{})},{}],13:[function(t,e,r){function n(t){return(t=Math.round(t))<0?0:t>255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return function(t){return t<0?0:t>1?1:t}("%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}var s={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};try{r.parseCSSColor=function(t){var e,r=t.replace(/ /g,"").toLowerCase();if(r in s)return s[r].slice();if("#"===r[0])return 4===r.length?(e=parseInt(r.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===r.length&&(e=parseInt(r.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var l=r.indexOf("("),u=r.indexOf(")");if(-1!==l&&u+1===r.length){var c=r.substr(0,l),h=r.substr(l+1,u-(l+1)).split(","),f=1;switch(c){case"rgba":if(4!==h.length)return null;f=a(h.pop());case"rgb":return 3!==h.length?null:[i(h[0]),i(h[1]),i(h[2]),f];case"hsla":if(4!==h.length)return null;f=a(h.pop());case"hsl":if(3!==h.length)return null;var p=(parseFloat(h[0])%360+360)%360/360,d=a(h[1]),g=a(h[2]),v=g<=.5?g*(d+1):g+d-g*d,m=2*g-v;return[n(255*o(m,v,p+1/3)),n(255*o(m,v,p)),n(255*o(m,v,p-1/3)),f];default:return null}}return null}}catch(t){}},{}],14:[function(t,e,r){function n(t,e,r){r=r||2;var n,s,l,u,c,p,g,v=e&&e.length,m=v?e[0]*r:t.length,y=i(t,0,m,r,!0),x=[];if(!y)return x;if(v&&(y=function(t,e,r,n){var o,s,l,u,c,p=[];for(o=0,s=e.length;o80*r){n=l=t[0],s=u=t[1];for(var b=r;bl&&(l=c),p>u&&(u=p);g=0!==(g=Math.max(l-n,u-s))?1/g:0}return o(y,x,r,n,s,g),x}function i(t,e,r,n,i){var a,o;if(i===A(t,e,r,n)>0)for(a=e;a=e;a-=n)o=w(a,t[a],t[a+1],o);return o&&y(o,o.next)&&(k(o),o=o.next),o}function a(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!y(n,n.next)&&0!==m(n.prev,n,n.next))n=n.next;else{if(k(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function o(t,e,r,n,i,h,f){if(t){!f&&h&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=p(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,l,u=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||l>0&&n;)0!==s&&(0===l||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,l--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n}a.nextZ=null,u*=2}while(o>1)}(i)}(t,n,i,h);for(var d,g,v=t;t.prev!==t.next;)if(d=t.prev,g=t.next,h?l(t,n,i,h):s(t))e.push(d.i/r),e.push(t.i/r),e.push(g.i/r),k(t),t=g.next,v=g.next;else if((t=g)===v){f?1===f?o(t=u(t,e,r),e,r,n,i,h,2):2===f&&c(t,e,r,n,i,h):o(a(t),e,r,n,i,h,1);break}}}function s(t){var e=t.prev,r=t,n=t.next;if(m(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(g(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&m(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function l(t,e,r,n){var i=t.prev,a=t,o=t.next;if(m(i,a,o)>=0)return!1;for(var s=i.xa.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,c=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,h=p(s,l,e,r,n),f=p(u,c,e,r,n),d=t.prevZ,v=t.nextZ;d&&d.z>=h&&v&&v.z<=f;){if(d!==t.prev&&d!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&m(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,v!==t.prev&&v!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;d&&d.z>=h;){if(d!==t.prev&&d!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,d.x,d.y)&&m(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;v&&v.z<=f;){if(v!==t.prev&&v!==t.next&&g(i.x,i.y,a.x,a.y,o.x,o.y,v.x,v.y)&&m(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function u(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!y(i,a)&&x(i,n,n.next,a)&&b(i,a)&&b(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),k(n),k(n.next),n=t=a),n=n.next}while(n!==t);return n}function c(t,e,r,n,i,s){var l=t;do{for(var u=l.next.next;u!==l.prev;){if(l.i!==u.i&&v(l,u)){var c=_(l,u);return l=a(l,l.next),c=a(c,c.next),o(l,e,r,n,i,s),void o(c,e,r,n,i,s)}u=u.next}l=l.next}while(l!==t)}function h(t,e){return t.x-e.x}function f(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=c&&i!==n.x&&g(ar.x)&&b(n,t)&&(r=n,f=l),n=n.next;return r}(t,e)){var r=_(e,t);a(r,r.next)}}function p(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,r=t;do{e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function v(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&x(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(t,e)&&b(t,e)&&b(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}(t,e)}function m(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function y(t,e){return t.x===e.x&&t.y===e.y}function x(t,e,r,n){return!!(y(t,e)&&y(r,n)||y(t,n)&&y(r,e))||m(t,e,r)>0!=m(t,e,n)>0&&m(r,n,t)>0!=m(r,n,e)>0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function _(t,e){var r=new M(t.i,t.x,t.y),n=new M(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function w(t,e,r,n){var i=new M(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function k(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function M(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,a=e,o=r-n;a0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],15:[function(t,e,r){function n(t,e){return function(r){return t(r,e)}}function i(t,e){e=!!e,t[0]=a(t[0],e);for(var r=1;r=0}(t)===e?t:t.reverse()}var o=t("@mapbox/geojson-area");e.exports=function t(e,r){switch(e&&e.type||null){case"FeatureCollection":return e.features=e.features.map(n(t,r)),e;case"Feature":return e.geometry=t(e.geometry,r),e;case"Polygon":case"MultiPolygon":return function(t,e){return"Polygon"===t.type?t.coordinates=i(t.coordinates,e):"MultiPolygon"===t.type&&(t.coordinates=t.coordinates.map(n(i,e))),t}(e,r);default:return e}}},{"@mapbox/geojson-area":1}],16:[function(t,e,r){function n(t,e,r,n,i){for(var a=0;a=r&&o<=n&&(e.push(t[a]),e.push(t[a+1]),e.push(t[a+2]))}}function i(t,e,r,n,i,a){for(var u=[],c=0===i?s:l,h=0;h=r&&c(u,f,p,g,v,r):m>n?y<=n&&c(u,f,p,g,v,n):o(u,f,p,d),y=r&&(c(u,f,p,g,v,r),x=!0),y>n&&m<=n&&(c(u,f,p,g,v,n),x=!0),!a&&x&&(u.size=t.size,e.push(u),u=[])}var b=t.length-3;f=t[b],p=t[b+1],d=t[b+2],(m=0===i?f:p)>=r&&m<=n&&o(u,f,p,d),b=u.length-3,a&&b>=3&&(u[b]!==u[0]||u[b+1]!==u[1])&&o(u,u[0],u[1],u[2]),u.length&&(u.size=t.size,e.push(u))}function a(t,e,r,n,a,o){for(var s=0;s=(r/=e)&&c<=o)return t;if(l>o||c=r&&m<=o)h.push(p);else if(!(v>o||m0&&(o+=n?(i*f-h*a)/2:Math.sqrt(Math.pow(h-i,2)+Math.pow(f-a,2))),i=h,a=f}var p=e.length-3;e[2]=1,u(e,0,p,r),e[p+2]=1,e.size=Math.abs(o)}function o(t,e,r,n){for(var i=0;i1?1:r}e.exports=function(t,e){var r=[];if("FeatureCollection"===t.type)for(var i=0;i24)throw new Error("maxZoom should be in the 0-24 range");var n=1<1&&console.time("creation"),g=this.tiles[d]=u(t,p,r,n,v,e===h.maxZoom),this.tileCoords.push({z:e,x:r,y:n}),f)){f>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",e,r,n,g.numFeatures,g.numPoints,g.numSimplified),console.timeEnd("creation"));var m="z"+e;this.stats[m]=(this.stats[m]||0)+1,this.total++}if(g.source=t,a){if(e===h.maxZoom||e===a)continue;var y=1<1&&console.time("clipping");var x,b,_,w,k,M,A=.5*h.buffer/h.extent,T=.5-A,S=.5+A,C=1+A;x=b=_=w=null,k=s(t,p,r-A,r+S,0,g.minX,g.maxX),M=s(t,p,r+T,r+C,0,g.minX,g.maxX),t=null,k&&(x=s(k,p,n-A,n+S,1,g.minY,g.maxY),b=s(k,p,n+T,n+C,1,g.minY,g.maxY),k=null),M&&(_=s(M,p,n-A,n+S,1,g.minY,g.maxY),w=s(M,p,n+T,n+C,1,g.minY,g.maxY),M=null),f>1&&console.timeEnd("clipping"),c.push(x||[],e+1,2*r,2*n),c.push(b||[],e+1,2*r,2*n+1),c.push(_||[],e+1,2*r+1,2*n),c.push(w||[],e+1,2*r+1,2*n+1)}}},n.prototype.getTile=function(t,e,r){var n=this.options,a=n.extent,s=n.debug;if(t<0||t>24)return null;var l=1<1&&console.log("drilling down to z%d-%d-%d",t,e,r);for(var c,h=t,f=e,p=r;!c&&h>0;)h--,f=Math.floor(f/2),p=Math.floor(p/2),c=this.tiles[i(h,f,p)];return c&&c.source?(s>1&&console.log("found parent tile z%d-%d-%d",h,f,p),s>1&&console.time("drilling down"),this.splitTile(c.source,h,f,p,t,e,r),s>1&&console.timeEnd("drilling down"),this.tiles[u]?o.tile(this.tiles[u],a):null):null}},{"./clip":16,"./convert":17,"./tile":21,"./transform":22,"./wrap":23}],20:[function(t,e,r){function n(t,e,r,n,i,a){var o=i-r,s=a-n;if(0!==o||0!==s){var l=((t-r)*o+(e-n)*s)/(o*o+s*s);l>1?(r=i,n=a):l>0&&(r+=o*l,n+=s*l)}return(o=t-r)*o+(s=e-n)*s}e.exports=function t(e,r,i,a){for(var o,s=a,l=e[r],u=e[r+1],c=e[i],h=e[i+1],f=r+3;fs&&(o=f,s=p)}s>a&&(o-r>3&&t(e,r,o,a),e[o+2]=s,i-o>3&&t(e,o,i,a))}},{}],21:[function(t,e,r){function n(t,e,r,n){var a=e.geometry,o=e.type,s=[];if("Point"===o||"MultiPoint"===o)for(var l=0;ls)&&(r.numSimplified++,l.push(e[u]),l.push(e[u+1])),r.numPoints++;a&&function(t,e){for(var r=0,n=0,i=t.length,a=i-2;n0===e)for(n=0,i=t.length;ns.maxX&&(s.maxX=h),f>s.maxY&&(s.maxY=f)}return s}},{}],22:[function(t,e,r){function n(t,e,r,n,i,a){return[Math.round(r*(t*n-i)),Math.round(r*(e*n-a))]}r.tile=function(t,e){if(t.transformed)return t;var r,i,a,o=t.z2,s=t.x,l=t.y;for(r=0;r=u[f+0]&&n>=u[f+1]?(o[h]=!0,a.push(l[h])):o[h]=!1}}},n.prototype._forEachCell=function(t,e,r,n,i,a,o){for(var s=this._convertToCellCoord(t),l=this._convertToCellCoord(e),u=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=s;h<=u;h++)for(var f=l;f<=c;f++){var p=this.d*f+h;if(i.call(this,t,e,r,n,p,a,o))return}},n.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},n.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=i+this.cells.length+1+1,r=0,n=0;n>1,c=-7,h=r?i-1:0,f=r?-1:1,p=t[e+h];for(h+=f,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+h>=1?f/l:f*Math.pow(2,1-h))*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}},{}],26:[function(t,e,r){function n(t,e,r,n,s){e=e||i,r=r||a,s=s||Array,this.nodeSize=n||64,this.points=t,this.ids=new s(t.length),this.coords=new s(2*t.length);for(var l=0;l=r&&s<=i&&l>=n&&l<=a&&c.push(t[d]);else{var g=Math.floor((p+f)/2);s=e[2*g],l=e[2*g+1],s>=r&&s<=i&&l>=n&&l<=a&&c.push(t[g]);var v=(h+1)%2;(0===h?r<=s:n<=l)&&(u.push(p),u.push(g-1),u.push(v)),(0===h?i>=s:a>=l)&&(u.push(g+1),u.push(f),u.push(v))}}return c}},{}],28:[function(t,e,r){function n(t,e,r,n){i(t,r,n),i(e,2*r,2*n),i(e,2*r+1,2*n+1)}function i(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}e.exports=function t(e,r,i,a,o,s){if(!(o-a<=i)){var l=Math.floor((a+o)/2);(function t(e,r,i,a,o,s){for(;o>a;){if(o-a>600){var l=o-a+1,u=i-a+1,c=Math.log(l),h=.5*Math.exp(2*c/3),f=.5*Math.sqrt(c*h*(l-h)/l)*(u-l/2<0?-1:1);t(e,r,i,Math.max(a,Math.floor(i-u*h/l+f)),Math.min(o,Math.floor(i+(l-u)*h/l+f)),s)}var p=r[2*i+s],d=a,g=o;for(n(e,r,a,i),r[2*o+s]>p&&n(e,r,a,o);dp;)g--}r[2*a+s]===p?n(e,r,a,g):n(e,r,++g,o),g<=i&&(a=g+1),i<=g&&(o=g-1)}})(e,r,l,a,o,s%2),t(e,r,i,a,l-1,s+1),t(e,r,i,l+1,o,s+1)}}},{}],29:[function(t,e,r){function n(t,e,r,n){var i=t-r,a=e-n;return i*i+a*a}e.exports=function(t,e,r,i,a,o){for(var s=[0,t.length-1,0],l=[],u=a*a;s.length;){var c=s.pop(),h=s.pop(),f=s.pop();if(h-f<=o)for(var p=f;p<=h;p++)n(e[2*p],e[2*p+1],r,i)<=u&&l.push(t[p]);else{var d=Math.floor((f+h)/2),g=e[2*d],v=e[2*d+1];n(g,v,r,i)<=u&&l.push(t[d]);var m=(c+1)%2;(0===c?r-a<=g:i-a<=v)&&(s.push(f),s.push(d-1),s.push(m)),(0===c?r+a>=g:i+a>=v)&&(s.push(d+1),s.push(h),s.push(m))}}return l}},{}],30:[function(t,e,r){function n(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}function i(t){return t.type===n.Bytes?t.readVarint()+t.pos:t.pos+1}function a(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function o(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.ceil(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i]}function s(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24}function y(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}e.exports=n;var x=t("ieee754");n.Varint=0,n.Fixed64=1,n.Bytes=2,n.Fixed32=5;n.prototype={destroy:function(){this.buf=null},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=y(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=v(this.buf,this.pos)+4294967296*v(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=v(this.buf,this.pos)+4294967296*y(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=x.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=x.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,o=r.buf;if(n=(112&(i=o[r.pos++]))>>4,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<3,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<10,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<17,i<128)return a(t,n,e);if(n|=(127&(i=o[r.pos++]))<<24,i<128)return a(t,n,e);if(n|=(1&(i=o[r.pos++]))<<31,i<128)return a(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(a=t[i+1]))&&(u=(31&l)<<6|63&a)<=127&&(u=null):3===c?(a=t[i+1],o=t[i+2],128==(192&a)&&128==(192&o)&&((u=(15&l)<<12|(63&a)<<6|63&o)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+1],o=t[i+2],s=t[i+3],128==(192&a)&&128==(192&o)&&128==(192&s)&&((u=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c}return n}(this.buf,this.pos,t);return this.pos=t,e},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){var r=i(this);for(t=t||[];this.pos127;);else if(e===n.Bytes)this.pos=this.readVarint()+this.pos;else if(e===n.Fixed32)this.pos+=4;else{if(e!==n.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos]=127&t}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))))}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128)}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&o(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r},writeFloat:function(t){this.realloc(4),x.write(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),x.write(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&o(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,r){this.writeTag(t,n.Bytes),this.writeRawMessage(e,r)},writePackedVarint:function(t,e){this.writeMessage(t,s,e)},writePackedSVarint:function(t,e){this.writeMessage(t,l,e)},writePackedBoolean:function(t,e){this.writeMessage(t,h,e)},writePackedFloat:function(t,e){this.writeMessage(t,u,e)},writePackedDouble:function(t,e){this.writeMessage(t,c,e)},writePackedFixed32:function(t,e){this.writeMessage(t,f,e)},writePackedSFixed32:function(t,e){this.writeMessage(t,p,e)},writePackedFixed64:function(t,e){this.writeMessage(t,d,e)},writePackedSFixed64:function(t,e){this.writeMessage(t,g,e)},writeBytesField:function(t,e){this.writeTag(t,n.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,n.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,n.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,n.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,n.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,n.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,n.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}}},{ieee754:25}],31:[function(t,e,r){function n(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function i(t,e){return te?1:0}e.exports=function t(e,r,a,o,s){for(a=a||0,o=o||e.length-1,s=s||i;o>a;){if(o-a>600){var l=o-a+1,u=r-a+1,c=Math.log(l),h=.5*Math.exp(2*c/3),f=.5*Math.sqrt(c*h*(l-h)/l)*(u-l/2<0?-1:1);t(e,r,Math.max(a,Math.floor(r-u*h/l+f)),Math.min(o,Math.floor(r+(l-u)*h/l+f)),s)}var p=e[r],d=a,g=o;for(n(e,a,r),s(e[o],p)>0&&n(e,a,o);d0;)g--}0===s(e[a],p)?n(e,a,g):n(e,++g,o),g<=r&&(a=g+1),r<=g&&(o=g-1)}}},{}],32:[function(t,e,r){function n(t){this.options=c(Object.create(this.options),t),this.trees=new Array(this.options.maxZoom+1)}function i(t,e,r,n,i){return{x:t,y:e,zoom:1/0,id:n,properties:i,parentId:-1,numPoints:r}}function a(t,e){var r=t.geometry.coordinates;return{x:l(r[0]),y:u(r[1]),zoom:1/0,id:e,parentId:-1}}function o(t){return{type:"Feature",properties:s(t),geometry:{type:"Point",coordinates:[function(t){return 360*(t-.5)}(t.x),function(t){var e=(180-360*t)*Math.PI/180;return 360*Math.atan(Math.exp(e))/Math.PI-90}(t.y)]}}}function s(t){var e=t.numPoints,r=e>=1e4?Math.round(e/1e3)+"k":e>=1e3?Math.round(e/100)/10+"k":e;return c(c({},t.properties),{cluster:!0,cluster_id:t.id,point_count:e,point_count_abbreviated:r})}function l(t){return t/360+.5}function u(t){var e=Math.sin(t*Math.PI/180),r=.5-.25*Math.log((1+e)/(1-e))/Math.PI;return r<0?0:r>1?1:r}function c(t,e){for(var r in e)t[r]=e[r];return t}function h(t){return t.x}function f(t){return t.y}var p=t("kdbush");e.exports=function(t){return new n(t)},n.prototype={options:{minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,reduce:null,initial:function(){return{}},map:function(t){return t}},load:function(t){var e=this.options.log;e&&console.time("total time");var r="prepare "+t.length+" points";e&&console.time(r),this.points=t;var n=t.map(a);e&&console.timeEnd(r);for(var i=this.options.maxZoom;i>=this.options.minZoom;i--){var o=+Date.now();this.trees[i+1]=p(n,h,f,this.options.nodeSize,Float32Array),n=this._cluster(n,i),e&&console.log("z%d: %d clusters in %dms",i,n.length,+Date.now()-o)}return this.trees[this.options.minZoom]=p(n,h,f,this.options.nodeSize,Float32Array),e&&console.timeEnd("total time"),this},getClusters:function(t,e){for(var r=this.trees[this._limitZoom(e)],n=r.range(l(t[0]),u(t[3]),l(t[2]),u(t[1])),i=[],a=0;a0)for(var r=this.length>>1;r>=0;r--)this._down(r)}function i(t,e){return te?1:0}e.exports=n,n.prototype={push:function(t){this.data.push(t),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var t=this.data[0];return this.length--,this.length>0&&(this.data[0]=this.data[this.length],this._down(0)),this.data.pop(),t}},peek:function(){return this.data[0]},_up:function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i}e[t]=n},_down:function(t){for(var e=this.data,r=this.compare,n=this.length,i=n>>1,a=e[t];t=0)break;e[t]=l,t=o}e[t]=a}}},{}],34:[function(t,e,r){function n(t){var e=new h;return function(t,e){for(var r in t.layers)e.writeMessage(3,i,t.layers[r])}(t,e),e.finish()}function i(t,e){e.writeVarintField(15,t.version||1),e.writeStringField(1,t.name||""),e.writeVarintField(5,t.extent||4096);var r,n={keys:[],values:[],keycache:{},valuecache:{}};for(r=0;r>31}function u(t,e){for(var r=t.loadGeometry(),n=t.type,i=0,a=0,o=r.length,u=0;u=c||h<0||h>=c)){var f=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray),p=f.vertexLength;n(r.layoutVertexArray,u,h,-1,-1),n(r.layoutVertexArray,u,h,1,-1),n(r.layoutVertexArray,u,h,1,1),n(r.layoutVertexArray,u,h,-1,1),r.indexArray.emplaceBack(p,p+1,p+2),r.indexArray.emplaceBack(p,p+3,p+2),f.vertexLength+=4,f.primitiveLength+=2}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t)},h("CircleBucket",f,{omit:["layers"]}),e.exports=f},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./circle_attributes":41}],43:[function(t,e,r){arguments[4][41][0].apply(r,arguments)},{"../../util/struct_array":271,dup:41}],44:[function(t,e,r){var n=t("../array_types").FillLayoutArray,i=t("./fill_attributes").members,a=t("../segment").SegmentVector,o=t("../program_configuration").ProgramConfigurationSet,s=t("../index_array_type"),l=s.LineIndexArray,u=s.TriangleIndexArray,c=t("../load_geometry"),h=t("earcut"),f=t("../../util/classify_rings"),p=t("../../util/web_worker_transfer").register,d=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new n,this.indexArray=new u,this.indexArray2=new l,this.programConfigurations=new o(i,t.layers,t.zoom),this.segments=new a,this.segments2=new a};d.prototype.populate=function(t,e){for(var r=this,n=0,i=t;nd)||t.y===e.y&&(t.y<0||t.y>d)}function a(t){return t.every(function(t){return t.x<0})||t.every(function(t){return t.x>d})||t.every(function(t){return t.y<0})||t.every(function(t){return t.y>d})}var o=t("../array_types").FillExtrusionLayoutArray,s=t("./fill_extrusion_attributes").members,l=t("../segment"),u=l.SegmentVector,c=l.MAX_VERTEX_ARRAY_LENGTH,h=t("../program_configuration").ProgramConfigurationSet,f=t("../index_array_type").TriangleIndexArray,p=t("../load_geometry"),d=t("../extent"),g=t("earcut"),v=t("../../util/classify_rings"),m=t("../../util/web_worker_transfer").register,y=Math.pow(2,13),x=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new o,this.indexArray=new f,this.programConfigurations=new h(s,t.layers,t.zoom),this.segments=new u};x.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=1){var w=y[b-1];if(!i(_,w)){p.vertexLength+4>c&&(p=r.segments.prepareSegment(4,r.layoutVertexArray,r.indexArray));var k=_.sub(w)._perp()._unit(),M=w.dist(_);x+M>32768&&(x=0),n(r.layoutVertexArray,_.x,_.y,k.x,k.y,0,0,x),n(r.layoutVertexArray,_.x,_.y,k.x,k.y,0,1,x),x+=M,n(r.layoutVertexArray,w.x,w.y,k.x,k.y,0,0,x),n(r.layoutVertexArray,w.x,w.y,k.x,k.y,0,1,x);var A=p.vertexLength;r.indexArray.emplaceBack(A,A+1,A+2),r.indexArray.emplaceBack(A+1,A+2,A+3),p.vertexLength+=4,p.primitiveLength+=2}}}}p.vertexLength+u>c&&(p=r.segments.prepareSegment(u,r.layoutVertexArray,r.indexArray));for(var T=[],S=[],C=p.vertexLength,E=0,L=l;E>6)}var i=t("../array_types").LineLayoutArray,a=t("./line_attributes").members,o=t("../segment").SegmentVector,s=t("../program_configuration").ProgramConfigurationSet,l=t("../index_array_type").TriangleIndexArray,u=t("../load_geometry"),c=t("../extent"),h=t("@mapbox/vector-tile").VectorTileFeature.types,f=t("../../util/web_worker_transfer").register,p=63,d=Math.cos(Math.PI/180*37.5),g=.5,v=Math.pow(2,14)/g,m=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.layoutVertexArray=new i,this.indexArray=new l,this.programConfigurations=new s(a,t.layers,t.zoom),this.segments=new o};m.prototype.populate=function(t,e){for(var r=this,n=0,i=t;n=2&&t[l-1].equals(t[l-2]);)l--;for(var u=0;uu){var P=v.dist(w);if(P>2*f){var z=v.sub(v.sub(w)._mult(f/P)._round());o.distance+=z.dist(w),o.addCurrentVertex(z,o.distance,M.mult(1),0,0,!1,g),w=z}}var D=w&&k,I=D?r:k?x:b;if(D&&"round"===I&&(Ei&&(I="bevel"),"bevel"===I&&(E>2&&(I="flipbevel"),E100)S=A.clone().mult(-1);else{var O=M.x*A.y-M.y*A.x>0?-1:1,R=E*M.add(A).mag()/M.sub(A).mag();S._perp()._mult(R*O)}o.addCurrentVertex(v,o.distance,S,0,0,!1,g),o.addCurrentVertex(v,o.distance,S.mult(-1),0,0,!1,g)}else if("bevel"===I||"fakeround"===I){var B=M.x*A.y-M.y*A.x>0,F=-Math.sqrt(E*E-1);if(B?(y=0,m=F):(m=0,y=F),_||o.addCurrentVertex(v,o.distance,M,m,y,!1,g),"fakeround"===I){for(var N=Math.floor(8*(.5-(C-.5))),j=void 0,V=0;V=0;U--)j=M.mult((U+1)/(N+1))._add(A)._unit(),o.addPieSliceVertex(v,o.distance,j,B,g)}k&&o.addCurrentVertex(v,o.distance,A,-m,-y,!1,g)}else"butt"===I?(_||o.addCurrentVertex(v,o.distance,M,0,0,!1,g),k&&o.addCurrentVertex(v,o.distance,A,0,0,!1,g)):"square"===I?(_||(o.addCurrentVertex(v,o.distance,M,1,1,!1,g),o.e1=o.e2=-1),k&&o.addCurrentVertex(v,o.distance,A,-1,-1,!1,g)):"round"===I&&(_||(o.addCurrentVertex(v,o.distance,M,0,0,!1,g),o.addCurrentVertex(v,o.distance,M,1,1,!0,g),o.e1=o.e2=-1),k&&(o.addCurrentVertex(v,o.distance,A,-1,-1,!0,g),o.addCurrentVertex(v,o.distance,A,0,0,!1,g)));if(L&&T2*f){var H=v.add(k.sub(v)._mult(f/q)._round());o.distance+=H.dist(v),o.addCurrentVertex(H,o.distance,A.mult(1),0,0,!1,g),v=H}}_=!1}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e)}},m.prototype.addCurrentVertex=function(t,e,r,i,a,o,s){var l,u=this.layoutVertexArray,c=this.indexArray;l=r.clone(),i&&l._sub(r.perp()._mult(i)),n(u,t,l,o,!1,i,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,l=r.mult(-1),a&&l._sub(r.perp()._mult(a)),n(u,t,l,o,!0,-a,e),this.e3=s.vertexLength++,this.e1>=0&&this.e2>=0&&(c.emplaceBack(this.e1,this.e2,this.e3),s.primitiveLength++),this.e1=this.e2,this.e2=this.e3,e>v/2&&(this.distance=0,this.addCurrentVertex(t,this.distance,r,i,a,o,s))},m.prototype.addPieSliceVertex=function(t,e,r,i,a){r=r.mult(i?-1:1);var o=this.layoutVertexArray,s=this.indexArray;n(o,t,r,!1,i,0,e),this.e3=a.vertexLength++,this.e1>=0&&this.e2>=0&&(s.emplaceBack(this.e1,this.e2,this.e3),a.primitiveLength++),i?this.e2=this.e3:this.e1=this.e3},f("LineBucket",m,{omit:["layers"]}),e.exports=m},{"../../util/web_worker_transfer":278,"../array_types":39,"../extent":53,"../index_array_type":55,"../load_geometry":56,"../program_configuration":58,"../segment":60,"./line_attributes":48,"@mapbox/vector-tile":8}],50:[function(t,e,r){var n=t("../../util/struct_array").createLayout,i={symbolLayoutAttributes:n([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"}]),dynamicLayoutAttributes:n([{name:"a_projected_pos",components:3,type:"Float32"}],4),placementOpacityAttributes:n([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),collisionVertexAttributes:n([{name:"a_placed",components:2,type:"Uint8"}],4),collisionBox:n([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"},{type:"Int16",name:"radius"},{type:"Int16",name:"signedDistanceFromAnchor"}]),collisionBoxLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),collisionCircleLayout:n([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),placement:n([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"hidden"}]),glyphOffset:n([{type:"Float32",name:"offsetX"}]),lineVertex:n([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}])};e.exports=i},{"../../util/struct_array":271}],51:[function(t,e,r){function n(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,Math.round(64*n),Math.round(64*i),a,o,s?s[0]:0,s?s[1]:0)}function i(t,e,r){t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r),t.emplaceBack(e.x,e.y,r)}var a=t("./symbol_attributes"),o=a.symbolLayoutAttributes,s=a.collisionVertexAttributes,l=a.collisionBoxLayout,u=a.collisionCircleLayout,c=a.dynamicLayoutAttributes,h=t("../array_types"),f=h.SymbolLayoutArray,p=h.SymbolDynamicLayoutArray,d=h.SymbolOpacityArray,g=h.CollisionBoxLayoutArray,v=h.CollisionCircleLayoutArray,m=h.CollisionVertexArray,y=h.PlacedSymbolArray,x=h.GlyphOffsetArray,b=h.SymbolLineVertexArray,_=t("@mapbox/point-geometry"),w=t("../segment").SegmentVector,k=t("../program_configuration").ProgramConfigurationSet,M=t("../index_array_type"),A=M.TriangleIndexArray,T=M.LineIndexArray,S=t("../../symbol/transform_text"),C=t("../../symbol/mergelines"),E=t("../../util/script_detection"),L=t("../load_geometry"),P=t("@mapbox/vector-tile").VectorTileFeature.types,z=t("../../util/verticalize_punctuation"),D=(t("../../symbol/anchor"),t("../../symbol/symbol_size").getSizeData),I=t("../../util/web_worker_transfer").register,O=[{name:"a_fade_opacity",components:1,type:"Uint8",offset:0}],R=function(t){this.layoutVertexArray=new f,this.indexArray=new A,this.programConfigurations=t,this.segments=new w,this.dynamicLayoutVertexArray=new p,this.opacityVertexArray=new d,this.placedSymbolArray=new y};R.prototype.upload=function(t,e){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,o.members),this.indexBuffer=t.createIndexBuffer(this.indexArray,e),this.programConfigurations.upload(t),this.dynamicLayoutVertexBuffer=t.createVertexBuffer(this.dynamicLayoutVertexArray,c.members,!0),this.opacityVertexBuffer=t.createVertexBuffer(this.opacityVertexArray,O,!0),this.opacityVertexBuffer.itemSize=1},R.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy())},I("SymbolBuffers",R);var B=function(t,e,r){this.layoutVertexArray=new t,this.layoutAttributes=e,this.indexArray=new r,this.segments=new w,this.collisionVertexArray=new m};B.prototype.upload=function(t){this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=t.createVertexBuffer(this.collisionVertexArray,s.members,!0)},B.prototype.destroy=function(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy())},I("CollisionBuffers",B);var F=function(t){this.collisionBoxArray=t.collisionBoxArray,this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map(function(t){return t.id}),this.index=t.index,this.pixelRatio=t.pixelRatio;var e=this.layers[0]._unevaluatedLayout._values;this.textSizeData=D(this.zoom,e["text-size"]),this.iconSizeData=D(this.zoom,e["icon-size"]);var r=this.layers[0].layout;this.sortFeaturesByY=r.get("text-allow-overlap")||r.get("icon-allow-overlap")||r.get("text-ignore-placement")||r.get("icon-ignore-placement")};F.prototype.createArrays=function(){this.text=new R(new k(o.members,this.layers,this.zoom,function(t){return/^text/.test(t)})),this.icon=new R(new k(o.members,this.layers,this.zoom,function(t){return/^icon/.test(t)})),this.collisionBox=new B(g,l.members,T),this.collisionCircle=new B(v,u.members,A),this.glyphOffsetArray=new x,this.lineVertexArray=new b},F.prototype.populate=function(t,e){var r=this.layers[0],n=r.layout,i=n.get("text-font"),a=n.get("text-field"),o=n.get("icon-image"),s=("constant"!==a.value.kind||a.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),l="constant"!==o.value.kind||o.value.value&&o.value.value.length>0;if(this.features=[],s||l){for(var u=e.iconDependencies,c=e.glyphDependencies,h={zoom:this.zoom},f=0,p=t;f=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var l=0;l0;t.addCollisionDebugVertices(l,u,c,h,f?t.collisionCircle:t.collisionBox,s.anchorPoint,n,f)}}}},F.prototype.deserializeCollisionBoxes=function(t,e,r,n,i){for(var a={},o=e;o0},F.prototype.hasIconData=function(){return this.icon.segments.get().length>0},F.prototype.hasCollisionBoxData=function(){return this.collisionBox.segments.get().length>0},F.prototype.hasCollisionCircleData=function(){return this.collisionCircle.segments.get().length>0},F.prototype.sortFeatures=function(t){var e=this;if(this.sortFeaturesByY&&this.sortedAngle!==t&&(this.sortedAngle=t,!(this.text.segments.get().length>1||this.icon.segments.get().length>1))){for(var r=[],n=0;n=this.dim+this.border||e<-this.border||e>=this.dim+this.border)throw new RangeError("out of range source coordinates for DEM data");return(e+this.border)*this.stride+(t+this.border)},a("Level",o);var s=function(t,e,r){this.uid=t,this.scale=e||1,this.level=r||new o(256,512),this.loaded=!!r};s.prototype.loadFromImage=function(t){if(t.height!==t.width)throw new RangeError("DEM tiles must be square");for(var e=this.level=new o(t.width,t.width/2),r=t.data,n=0;no.max||u.yo.max)&&i.warnOnce("Geometry exceeds allowed extent, reduce your vector tile buffer size")}return r}},{"../util/util":275,"./extent":53}],57:[function(t,e,r){var n=t("../util/struct_array").createLayout;e.exports=n([{name:"a_pos",type:"Int16",components:2}])},{"../util/struct_array":271}],58:[function(t,e,r){function n(t){return[a(255*t.r,255*t.g),a(255*t.b,255*t.a)]}function i(t,e){return{"text-opacity":"opacity","icon-opacity":"opacity","text-color":"fill_color","icon-color":"fill_color","text-halo-color":"halo_color","icon-halo-color":"halo_color","text-halo-blur":"halo_blur","icon-halo-blur":"halo_blur","text-halo-width":"halo_width","icon-halo-width":"halo_width","line-gap-width":"gapwidth"}[t]||t.replace(e+"-","").replace(/-/g,"_")}var a=t("../shaders/encode_attribute").packUint8ToFloat,o=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),s=t("../style/properties").PossiblyEvaluatedPropertyValue,l=t("./array_types"),u=l.StructArrayLayout1f4,c=l.StructArrayLayout2f8,h=l.StructArrayLayout4f16,f=function(t,e,r){this.value=t,this.name=e,this.type=r,this.statistics={max:-1/0}};f.prototype.defines=function(){return["#define HAS_UNIFORM_u_"+this.name]},f.prototype.populatePaintArray=function(){},f.prototype.upload=function(){},f.prototype.destroy=function(){},f.prototype.setUniforms=function(t,e,r,n){var i=n.constantOr(this.value),a=t.gl;"color"===this.type?a.uniform4f(e.uniforms["u_"+this.name],i.r,i.g,i.b,i.a):a.uniform1f(e.uniforms["u_"+this.name],i)};var p=function(t,e,r){this.expression=t,this.name=e,this.type=r,this.statistics={max:-1/0};var n="color"===r?c:u;this.paintVertexAttributes=[{name:"a_"+e,type:"Float32",components:"color"===r?2:1,offset:0}],this.paintVertexArray=new n};p.prototype.defines=function(){return[]},p.prototype.populatePaintArray=function(t,e){var r=this.paintVertexArray,i=r.length;r.reserve(t);var a=this.expression.evaluate({zoom:0},e);if("color"===this.type)for(var o=n(a),s=i;sa&&n("Max vertices per segment is "+a+": bucket requested "+t),(!o||o.vertexLength+t>e.exports.MAX_VERTEX_ARRAY_LENGTH)&&(o={vertexOffset:r.length,primitiveOffset:i.length,vertexLength:0,primitiveLength:0},this.segments.push(o)),o},o.prototype.get=function(){return this.segments},o.prototype.destroy=function(){for(var t=0,e=this.segments;t90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};i.prototype.wrap=function(){return new i(n(this.lng,-180,180),this.lat)},i.prototype.toArray=function(){return[this.lng,this.lat]},i.prototype.toString=function(){return"LngLat("+this.lng+", "+this.lat+")"},i.prototype.toBounds=function(e){var r=360*e/40075017,n=r/Math.cos(Math.PI/180*this.lat);return new(t("./lng_lat_bounds"))(new i(this.lng-n,this.lat-r),new i(this.lng+n,this.lat+r))},i.convert=function(t){if(t instanceof i)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new i(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new i(Number(t.lng),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, or an array of [, ]")},e.exports=i},{"../util/util":275,"./lng_lat_bounds":63}],63:[function(t,e,r){var n=t("./lng_lat"),i=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]))};i.prototype.setNorthEast=function(t){return this._ne=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.setSouthWest=function(t){return this._sw=t instanceof n?new n(t.lng,t.lat):n.convert(t),this},i.prototype.extend=function(t){var e,r,a=this._sw,o=this._ne;if(t instanceof n)e=t,r=t;else{if(!(t instanceof i))return Array.isArray(t)?t.every(Array.isArray)?this.extend(i.convert(t)):this.extend(n.convert(t)):this;if(e=t._sw,r=t._ne,!e||!r)return this}return a||o?(a.lng=Math.min(e.lng,a.lng),a.lat=Math.min(e.lat,a.lat),o.lng=Math.max(r.lng,o.lng),o.lat=Math.max(r.lat,o.lat)):(this._sw=new n(e.lng,e.lat),this._ne=new n(r.lng,r.lat)),this},i.prototype.getCenter=function(){return new n((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},i.prototype.getSouthWest=function(){return this._sw},i.prototype.getNorthEast=function(){return this._ne},i.prototype.getNorthWest=function(){return new n(this.getWest(),this.getNorth())},i.prototype.getSouthEast=function(){return new n(this.getEast(),this.getSouth())},i.prototype.getWest=function(){return this._sw.lng},i.prototype.getSouth=function(){return this._sw.lat},i.prototype.getEast=function(){return this._ne.lng},i.prototype.getNorth=function(){return this._ne.lat},i.prototype.toArray=function(){return[this._sw.toArray(),this._ne.toArray()]},i.prototype.toString=function(){return"LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},i.prototype.isEmpty=function(){return!(this._sw&&this._ne)},i.convert=function(t){return!t||t instanceof i?t:new i(t)},e.exports=i},{"./lng_lat":62}],64:[function(t,e,r){var n=t("./lng_lat"),i=t("@mapbox/point-geometry"),a=t("./coordinate"),o=t("../util/util"),s=t("../style-spec/util/interpolate").number,l=t("../util/tile_cover"),u=t("../source/tile_id"),c=(u.CanonicalTileID,u.UnwrappedTileID),h=t("../data/extent"),f=t("@mapbox/gl-matrix"),p=f.vec4,d=f.mat4,g=f.mat2,v=function(t,e,r){this.tileSize=512,this._renderWorldCopies=void 0===r||r,this._minZoom=t||0,this._maxZoom=e||22,this.latRange=[-85.05113,85.05113],this.width=0,this.height=0,this._center=new n(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._posMatrixCache={},this._alignedPosMatrixCache={}},m={minZoom:{},maxZoom:{},renderWorldCopies:{},worldSize:{},centerPoint:{},size:{},bearing:{},pitch:{},fov:{},zoom:{},center:{},unmodified:{},x:{},y:{},point:{}};v.prototype.clone=function(){var t=new v(this._minZoom,this._maxZoom,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._calcMatrices(),t},m.minZoom.get=function(){return this._minZoom},m.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t))},m.maxZoom.get=function(){return this._maxZoom},m.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t))},m.renderWorldCopies.get=function(){return this._renderWorldCopies},m.worldSize.get=function(){return this.tileSize*this.scale},m.centerPoint.get=function(){return this.size._div(2)},m.size.get=function(){return new i(this.width,this.height)},m.bearing.get=function(){return-this.angle/Math.PI*180},m.bearing.set=function(t){var e=-o.wrap(t,-180,180)*Math.PI/180;this.angle!==e&&(this._unmodified=!1,this.angle=e,this._calcMatrices(),this.rotationMatrix=g.create(),g.rotate(this.rotationMatrix,this.rotationMatrix,this.angle))},m.pitch.get=function(){return this._pitch/Math.PI*180},m.pitch.set=function(t){var e=o.clamp(t,0,60)/180*Math.PI;this._pitch!==e&&(this._unmodified=!1,this._pitch=e,this._calcMatrices())},m.fov.get=function(){return this._fov/Math.PI*180},m.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices())},m.zoom.get=function(){return this._zoom},m.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices())},m.center.get=function(){return this._center},m.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices())},v.prototype.coveringZoomLevel=function(t){return(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize))},v.prototype.getVisibleUnwrappedCoordinates=function(t){var e=this.pointCoordinate(new i(0,0),0),r=this.pointCoordinate(new i(this.width,0),0),n=Math.floor(e.column),a=Math.floor(r.column),o=[new c(0,t)];if(this._renderWorldCopies)for(var s=n;s<=a;s++)0!==s&&o.push(new c(s,t));return o},v.prototype.coveringTiles=function(t){var e=this.coveringZoomLevel(t),r=e;if(void 0!==t.minzoom&&et.maxzoom&&(e=t.maxzoom);var n=this.pointCoordinate(this.centerPoint,e),a=new i(n.column-.5,n.row-.5),o=[this.pointCoordinate(new i(0,0),e),this.pointCoordinate(new i(this.width,0),e),this.pointCoordinate(new i(this.width,this.height),e),this.pointCoordinate(new i(0,this.height),e)];return l(e,o,t.reparseOverscaled?r:e,this._renderWorldCopies).sort(function(t,e){return a.dist(t.canonical)-a.dist(e.canonical)})},v.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices()},m.unmodified.get=function(){return this._unmodified},v.prototype.zoomScale=function(t){return Math.pow(2,t)},v.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},v.prototype.project=function(t){return new i(this.lngX(t.lng),this.latY(t.lat))},v.prototype.unproject=function(t){return new n(this.xLng(t.x),this.yLat(t.y))},m.x.get=function(){return this.lngX(this.center.lng)},m.y.get=function(){return this.latY(this.center.lat)},m.point.get=function(){return new i(this.x,this.y)},v.prototype.lngX=function(t){return(180+t)*this.worldSize/360},v.prototype.latY=function(t){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))*this.worldSize/360},v.prototype.xLng=function(t){return 360*t/this.worldSize-180},v.prototype.yLat=function(t){var e=180-360*t/this.worldSize;return 360/Math.PI*Math.atan(Math.exp(e*Math.PI/180))-90},v.prototype.setLocationAtPoint=function(t,e){var r=this.pointCoordinate(e)._sub(this.pointCoordinate(this.centerPoint));this.center=this.coordinateLocation(this.locationCoordinate(t)._sub(r)),this._renderWorldCopies&&(this.center=this.center.wrap())},v.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},v.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},v.prototype.locationCoordinate=function(t){return new a(this.lngX(t.lng)/this.tileSize,this.latY(t.lat)/this.tileSize,this.zoom).zoomTo(this.tileZoom)},v.prototype.coordinateLocation=function(t){var e=t.zoomTo(this.zoom);return new n(this.xLng(e.column*this.tileSize),this.yLat(e.row*this.tileSize))},v.prototype.pointCoordinate=function(t,e){void 0===e&&(e=this.tileZoom);var r=[t.x,t.y,0,1],n=[t.x,t.y,1,1];p.transformMat4(r,r,this.pixelMatrixInverse),p.transformMat4(n,n,this.pixelMatrixInverse);var i=r[3],o=n[3],l=r[1]/i,u=n[1]/o,c=r[2]/i,h=n[2]/o,f=c===h?0:(0-c)/(h-c);return new a(s(r[0]/i,n[0]/o,f)/this.tileSize,s(l,u,f)/this.tileSize,this.zoom)._zoomTo(e)},v.prototype.coordinatePoint=function(t){var e=t.zoomTo(this.zoom),r=[e.column*this.tileSize,e.row*this.tileSize,0,1];return p.transformMat4(r,r,this.pixelMatrix),new i(r[0]/r[3],r[1]/r[3])},v.prototype.calculatePosMatrix=function(t,e){void 0===e&&(e=!1);var r=t.key,n=e?this._alignedPosMatrixCache:this._posMatrixCache;if(n[r])return n[r];var i=t.canonical,a=this.worldSize/this.zoomScale(i.z),o=i.x+Math.pow(2,i.z)*t.wrap,s=d.identity(new Float64Array(16));return d.translate(s,s,[o*a,i.y*a,0]),d.scale(s,s,[a/h,a/h,1]),d.multiply(s,e?this.alignedProjMatrix:this.projMatrix,s),n[r]=new Float32Array(s),n[r]},v.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var t,e,r,n,a=-90,o=90,s=-180,l=180,u=this.size,c=this._unmodified;if(this.latRange){var h=this.latRange;a=this.latY(h[1]),t=(o=this.latY(h[0]))-ao&&(n=o-g)}if(this.lngRange){var v=this.x,m=u.x/2;v-ml&&(r=l-m)}void 0===r&&void 0===n||(this.center=this.unproject(new i(void 0!==r?r:this.x,void 0!==n?n:this.y))),this._unmodified=c,this._constraining=!1}},v.prototype._calcMatrices=function(){if(this.height){this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var t=this._fov/2,e=Math.PI/2+this._pitch,r=Math.sin(t)*this.cameraToCenterDistance/Math.sin(Math.PI-e-t),n=this.x,i=this.y,a=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),o=new Float64Array(16);d.perspective(o,this._fov,this.width/this.height,1,a),d.scale(o,o,[1,-1,1]),d.translate(o,o,[0,0,-this.cameraToCenterDistance]),d.rotateX(o,o,this._pitch),d.rotateZ(o,o,this.angle),d.translate(o,o,[-n,-i,0]);var s=this.worldSize/(2*Math.PI*6378137*Math.abs(Math.cos(this.center.lat*(Math.PI/180))));d.scale(o,o,[1,1,s,1]),this.projMatrix=o;var l=this.width%2/2,u=this.height%2/2,c=Math.cos(this.angle),h=Math.sin(this.angle),f=n-Math.round(n)+c*l+h*u,p=i-Math.round(i)+c*u+h*l,g=new Float64Array(o);if(d.translate(g,g,[f>.5?f-1:f,p>.5?p-1:p,0]),this.alignedProjMatrix=g,o=d.create(),d.scale(o,o,[this.width/2,-this.height/2,1]),d.translate(o,o,[1,-1,0]),this.pixelMatrix=d.multiply(new Float64Array(16),o,this.projMatrix),!(o=d.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=o,this._posMatrixCache={},this._alignedPosMatrixCache={}}},Object.defineProperties(v.prototype,m),e.exports=v},{"../data/extent":53,"../source/tile_id":114,"../style-spec/util/interpolate":158,"../util/tile_cover":273,"../util/util":275,"./coordinate":61,"./lng_lat":62,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],65:[function(t,e,r){var n=t("../style-spec/util/color"),i=function(t,e,r){this.blendFunction=t,this.blendColor=e,this.mask=r};i.disabled=new i(i.Replace=[1,0],n.transparent,[!1,!1,!1,!1]),i.unblended=new i(i.Replace,n.transparent,[!0,!0,!0,!0]),i.alphaBlended=new i([1,771],n.transparent,[!0,!0,!0,!0]),e.exports=i},{"../style-spec/util/color":153}],66:[function(t,e,r){var n=t("./index_buffer"),i=t("./vertex_buffer"),a=t("./framebuffer"),o=(t("./depth_mode"),t("./stencil_mode"),t("./color_mode")),s=t("../util/util"),l=t("./value"),u=l.ClearColor,c=l.ClearDepth,h=l.ClearStencil,f=l.ColorMask,p=l.DepthMask,d=l.StencilMask,g=l.StencilFunc,v=l.StencilOp,m=l.StencilTest,y=l.DepthRange,x=l.DepthTest,b=l.DepthFunc,_=l.Blend,w=l.BlendFunc,k=l.BlendColor,M=l.Program,A=l.LineWidth,T=l.ActiveTextureUnit,S=l.Viewport,C=l.BindFramebuffer,E=l.BindRenderbuffer,L=l.BindTexture,P=l.BindVertexBuffer,z=l.BindElementBuffer,D=l.BindVertexArrayOES,I=l.PixelStoreUnpack,O=l.PixelStoreUnpackPremultiplyAlpha,R=function(t){this.gl=t,this.extVertexArrayObject=this.gl.getExtension("OES_vertex_array_object"),this.lineWidthRange=t.getParameter(t.ALIASED_LINE_WIDTH_RANGE),this.clearColor=new u(this),this.clearDepth=new c(this),this.clearStencil=new h(this),this.colorMask=new f(this),this.depthMask=new p(this),this.stencilMask=new d(this),this.stencilFunc=new g(this),this.stencilOp=new v(this),this.stencilTest=new m(this),this.depthRange=new y(this),this.depthTest=new x(this),this.depthFunc=new b(this),this.blend=new _(this),this.blendFunc=new w(this),this.blendColor=new k(this),this.program=new M(this),this.lineWidth=new A(this),this.activeTexture=new T(this),this.viewport=new S(this),this.bindFramebuffer=new C(this),this.bindRenderbuffer=new E(this),this.bindTexture=new L(this),this.bindVertexBuffer=new P(this),this.bindElementBuffer=new z(this),this.bindVertexArrayOES=this.extVertexArrayObject&&new D(this),this.pixelStoreUnpack=new I(this),this.pixelStoreUnpackPremultiplyAlpha=new O(this),this.extTextureFilterAnisotropic=t.getExtension("EXT_texture_filter_anisotropic")||t.getExtension("MOZ_EXT_texture_filter_anisotropic")||t.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=t.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)),this.extTextureHalfFloat=t.getExtension("OES_texture_half_float"),this.extTextureHalfFloat&&t.getExtension("OES_texture_half_float_linear")};R.prototype.createIndexBuffer=function(t,e){return new n(this,t,e)},R.prototype.createVertexBuffer=function(t,e,r){return new i(this,t,e,r)},R.prototype.createRenderbuffer=function(t,e,r){var n=this.gl,i=n.createRenderbuffer();return this.bindRenderbuffer.set(i),n.renderbufferStorage(n.RENDERBUFFER,t,e,r),this.bindRenderbuffer.set(null),i},R.prototype.createFramebuffer=function(t,e){return new a(this,t,e)},R.prototype.clear=function(t){var e=t.color,r=t.depth,n=this.gl,i=0;e&&(i|=n.COLOR_BUFFER_BIT,this.clearColor.set(e),this.colorMask.set([!0,!0,!0,!0])),void 0!==r&&(i|=n.DEPTH_BUFFER_BIT,this.clearDepth.set(r),this.depthMask.set(!0)),n.clear(i)},R.prototype.setDepthMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.depthTest.set(!0),this.depthFunc.set(t.func),this.depthMask.set(t.mask),this.depthRange.set(t.range)):this.depthTest.set(!1)},R.prototype.setStencilMode=function(t){t.func!==this.gl.ALWAYS||t.mask?(this.stencilTest.set(!0),this.stencilMask.set(t.mask),this.stencilOp.set([t.fail,t.depthFail,t.pass]),this.stencilFunc.set({func:t.test.func,ref:t.ref,mask:t.test.mask})):this.stencilTest.set(!1)},R.prototype.setColorMode=function(t){s.deepEqual(t.blendFunction,o.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(t.blendFunction),this.blendColor.set(t.blendColor)),this.colorMask.set(t.mask)},e.exports=R},{"../util/util":275,"./color_mode":65,"./depth_mode":67,"./framebuffer":68,"./index_buffer":69,"./stencil_mode":70,"./value":71,"./vertex_buffer":72}],67:[function(t,e,r){var n=function(t,e,r){this.func=t,this.mask=e,this.range=r};n.ReadOnly=!1,n.ReadWrite=!0,n.disabled=new n(519,n.ReadOnly,[0,1]),e.exports=n},{}],68:[function(t,e,r){var n=t("./value"),i=n.ColorAttachment,a=n.DepthAttachment,o=function(t,e,r){this.context=t,this.width=e,this.height=r;var n=t.gl,o=this.framebuffer=n.createFramebuffer();this.colorAttachment=new i(t,o),this.depthAttachment=new a(t,o)};o.prototype.destroy=function(){var t=this.context.gl,e=this.colorAttachment.get();e&&t.deleteTexture(e);var r=this.depthAttachment.get();r&&t.deleteRenderbuffer(r),t.deleteFramebuffer(this.framebuffer)},e.exports=o},{"./value":71}],69:[function(t,e,r){var n=function(t,e,r){this.context=t;var n=t.gl;this.buffer=n.createBuffer(),this.dynamicDraw=Boolean(r),this.unbindVAO(),t.bindElementBuffer.set(this.buffer),n.bufferData(n.ELEMENT_ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?n.DYNAMIC_DRAW:n.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};n.prototype.unbindVAO=function(){this.context.extVertexArrayObject&&this.context.bindVertexArrayOES.set(null)},n.prototype.bind=function(){this.context.bindElementBuffer.set(this.buffer)},n.prototype.updateData=function(t){var e=this.context.gl;this.unbindVAO(),this.bind(),e.bufferSubData(e.ELEMENT_ARRAY_BUFFER,0,t.arrayBuffer)},n.prototype.destroy=function(){var t=this.context.gl;this.buffer&&(t.deleteBuffer(this.buffer),delete this.buffer)},e.exports=n},{}],70:[function(t,e,r){var n=function(t,e,r,n,i,a){this.test=t,this.ref=e,this.mask=r,this.fail=n,this.depthFail=i,this.pass=a};n.disabled=new n({func:519,mask:0},0,0,7680,7680,7680),e.exports=n},{}],71:[function(t,e,r){var n=t("../style-spec/util/color"),i=t("../util/util"),a=function(t){this.context=t,this.current=n.transparent};a.prototype.get=function(){return this.current},a.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.clearColor(t.r,t.g,t.b,t.a),this.current=t)};var o=function(t){this.context=t,this.current=1};o.prototype.get=function(){return this.current},o.prototype.set=function(t){this.current!==t&&(this.context.gl.clearDepth(t),this.current=t)};var s=function(t){this.context=t,this.current=0};s.prototype.get=function(){return this.current},s.prototype.set=function(t){this.current!==t&&(this.context.gl.clearStencil(t),this.current=t)};var l=function(t){this.context=t,this.current=[!0,!0,!0,!0]};l.prototype.get=function(){return this.current},l.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.colorMask(t[0],t[1],t[2],t[3]),this.current=t)};var u=function(t){this.context=t,this.current=!0};u.prototype.get=function(){return this.current},u.prototype.set=function(t){this.current!==t&&(this.context.gl.depthMask(t),this.current=t)};var c=function(t){this.context=t,this.current=255};c.prototype.get=function(){return this.current},c.prototype.set=function(t){this.current!==t&&(this.context.gl.stencilMask(t),this.current=t)};var h=function(t){this.context=t,this.current={func:t.gl.ALWAYS,ref:0,mask:255}};h.prototype.get=function(){return this.current},h.prototype.set=function(t){var e=this.current;t.func===e.func&&t.ref===e.ref&&t.mask===e.mask||(this.context.gl.stencilFunc(t.func,t.ref,t.mask),this.current=t)};var f=function(t){this.context=t;var e=this.context.gl;this.current=[e.KEEP,e.KEEP,e.KEEP]};f.prototype.get=function(){return this.current},f.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]||(this.context.gl.stencilOp(t[0],t[1],t[2]),this.current=t)};var p=function(t){this.context=t,this.current=!1};p.prototype.get=function(){return this.current},p.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this.current=t}};var d=function(t){this.context=t,this.current=[0,1]};d.prototype.get=function(){return this.current},d.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.depthRange(t[0],t[1]),this.current=t)};var g=function(t){this.context=t,this.current=!1};g.prototype.get=function(){return this.current},g.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this.current=t}};var v=function(t){this.context=t,this.current=t.gl.LESS};v.prototype.get=function(){return this.current},v.prototype.set=function(t){this.current!==t&&(this.context.gl.depthFunc(t),this.current=t)};var m=function(t){this.context=t,this.current=!1};m.prototype.get=function(){return this.current},m.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;t?e.enable(e.BLEND):e.disable(e.BLEND),this.current=t}};var y=function(t){this.context=t;var e=this.context.gl;this.current=[e.ONE,e.ZERO]};y.prototype.get=function(){return this.current},y.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]||(this.context.gl.blendFunc(t[0],t[1]),this.current=t)};var x=function(t){this.context=t,this.current=n.transparent};x.prototype.get=function(){return this.current},x.prototype.set=function(t){var e=this.current;t.r===e.r&&t.g===e.g&&t.b===e.b&&t.a===e.a||(this.context.gl.blendColor(t.r,t.g,t.b,t.a),this.current=t)};var b=function(t){this.context=t,this.current=null};b.prototype.get=function(){return this.current},b.prototype.set=function(t){this.current!==t&&(this.context.gl.useProgram(t),this.current=t)};var _=function(t){this.context=t,this.current=1};_.prototype.get=function(){return this.current},_.prototype.set=function(t){var e=this.context.lineWidthRange,r=i.clamp(t,e[0],e[1]);this.current!==r&&(this.context.gl.lineWidth(r),this.current=t)};var w=function(t){this.context=t,this.current=t.gl.TEXTURE0};w.prototype.get=function(){return this.current},w.prototype.set=function(t){this.current!==t&&(this.context.gl.activeTexture(t),this.current=t)};var k=function(t){this.context=t;var e=this.context.gl;this.current=[0,0,e.drawingBufferWidth,e.drawingBufferHeight]};k.prototype.get=function(){return this.current},k.prototype.set=function(t){var e=this.current;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(this.context.gl.viewport(t[0],t[1],t[2],t[3]),this.current=t)};var M=function(t){this.context=t,this.current=null};M.prototype.get=function(){return this.current},M.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindFramebuffer(e.FRAMEBUFFER,t),this.current=t}};var A=function(t){this.context=t,this.current=null};A.prototype.get=function(){return this.current},A.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindRenderbuffer(e.RENDERBUFFER,t),this.current=t}};var T=function(t){this.context=t,this.current=null};T.prototype.get=function(){return this.current},T.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindTexture(e.TEXTURE_2D,t),this.current=t}};var S=function(t){this.context=t,this.current=null};S.prototype.get=function(){return this.current},S.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.bindBuffer(e.ARRAY_BUFFER,t),this.current=t}};var C=function(t){this.context=t,this.current=null};C.prototype.get=function(){return this.current},C.prototype.set=function(t){var e=this.context.gl;e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t),this.current=t};var E=function(t){this.context=t,this.current=null};E.prototype.get=function(){return this.current},E.prototype.set=function(t){this.current!==t&&this.context.extVertexArrayObject&&(this.context.extVertexArrayObject.bindVertexArrayOES(t),this.current=t)};var L=function(t){this.context=t,this.current=4};L.prototype.get=function(){return this.current},L.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_ALIGNMENT,t),this.current=t}};var P=function(t){this.context=t,this.current=!1};P.prototype.get=function(){return this.current},P.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t),this.current=t}};var z=function(t,e){this.context=t,this.current=null,this.parent=e};z.prototype.get=function(){return this.current};var D=function(t){function e(e,r){t.call(this,e,r),this.dirty=!1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.dirty||this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0),this.current=t,this.dirty=!1}},e.prototype.setDirty=function(){this.dirty=!0},e}(z),I=function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.set=function(t){if(this.current!==t){var e=this.context.gl;this.context.bindFramebuffer.set(this.parent),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,t),this.current=t}},e}(z);e.exports={ClearColor:a,ClearDepth:o,ClearStencil:s,ColorMask:l,DepthMask:u,StencilMask:c,StencilFunc:h,StencilOp:f,StencilTest:p,DepthRange:d,DepthTest:g,DepthFunc:v,Blend:m,BlendFunc:y,BlendColor:x,Program:b,LineWidth:_,ActiveTextureUnit:w,Viewport:k,BindFramebuffer:M,BindRenderbuffer:A,BindTexture:T,BindVertexBuffer:S,BindElementBuffer:C,BindVertexArrayOES:E,PixelStoreUnpack:L,PixelStoreUnpackPremultiplyAlpha:P,ColorAttachment:D,DepthAttachment:I}},{"../style-spec/util/color":153,"../util/util":275}],72:[function(t,e,r){var n={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"},i=function(t,e,r,n){this.length=e.length,this.attributes=r,this.itemSize=e.bytesPerElement,this.dynamicDraw=n,this.context=t;var i=t.gl;this.buffer=i.createBuffer(),t.bindVertexBuffer.set(this.buffer),i.bufferData(i.ARRAY_BUFFER,e.arrayBuffer,this.dynamicDraw?i.DYNAMIC_DRAW:i.STATIC_DRAW),this.dynamicDraw||delete e.arrayBuffer};i.prototype.bind=function(){this.context.bindVertexBuffer.set(this.buffer)},i.prototype.updateData=function(t){var e=this.context.gl;this.bind(),e.bufferSubData(e.ARRAY_BUFFER,0,t.arrayBuffer)},i.prototype.enableAttributes=function(t,e){for(var r=0;r":[24,[4,18,20,9,4,0]],"?":[18,[3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2]],"@":[27,[18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5]],A:[18,[9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7]],B:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0]],C:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5]],D:[21,[4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0]],E:[19,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0]],F:[18,[4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11]],G:[21,[18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8]],H:[22,[4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11]],I:[8,[4,21,4,0]],J:[16,[12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7]],K:[21,[4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0]],L:[17,[4,21,4,0,-1,-1,4,0,16,0]],M:[24,[4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0]],N:[22,[4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0]],O:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21]],P:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10]],Q:[22,[9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,18,-2]],R:[21,[4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,-1,-1,11,11,18,0]],S:[20,[17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3]],T:[16,[8,21,8,0,-1,-1,1,21,15,21]],U:[22,[4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21]],V:[18,[1,21,9,0,-1,-1,17,21,9,0]],W:[24,[2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0]],X:[20,[3,21,17,0,-1,-1,17,21,3,0]],Y:[18,[1,21,9,11,9,0,-1,-1,17,21,9,11]],Z:[20,[17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0]],"[":[14,[4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7]],"\\":[14,[0,21,14,-3]],"]":[14,[9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7]],"^":[16,[6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0]],_:[16,[0,-2,16,-2]],"`":[10,[6,21,5,20,4,18,4,16,5,15,6,16,5,17]],a:[19,[15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],b:[19,[4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],c:[18,[15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],d:[19,[15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],e:[18,[3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],f:[12,[10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14]],g:[19,[15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],h:[19,[4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],i:[8,[3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0]],j:[10,[5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7]],k:[17,[4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0]],l:[8,[4,21,4,0]],m:[30,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,10,18,13,20,14,23,14,25,13,26,10,26,0]],n:[19,[4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0]],o:[19,[8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14]],p:[19,[4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3]],q:[19,[15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3]],r:[13,[4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14]],s:[17,[14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3]],t:[12,[5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14]],u:[19,[4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0]],v:[16,[2,14,8,0,-1,-1,14,14,8,0]],w:[22,[3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0]],x:[17,[3,14,14,0,-1,-1,14,14,3,0]],y:[16,[2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7]],z:[17,[14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0]],"{":[14,[9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7]],"|":[8,[4,25,4,-7]],"}":[14,[5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7]],"~":[24,[3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]]}},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../util/browser":252,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],78:[function(t,e,r){function n(t,e,r,n,i){if(!s.isPatternMissing(r.paint.get("fill-pattern"),t))for(var a=!0,o=0,l=n;o0){var l=o.now(),u=(l-t.timeAdded)/s,c=e?(l-e.timeAdded)/s:-1,h=r.getSource(),f=a.coveringZoomLevel({tileSize:h.tileSize,roundZoom:h.roundZoom}),p=!e||Math.abs(e.tileID.overscaledZ-f)>Math.abs(t.tileID.overscaledZ-f),d=p&&t.refreshedUponExpiration?1:i.clamp(p?u:1-c,0,1);return t.refreshedUponExpiration&&u>=1&&(t.refreshedUponExpiration=!1),e?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return{opacity:1,mix:0}}var i=t("../util/util"),a=t("../source/image_source"),o=t("../util/browser"),s=t("../gl/stencil_mode"),l=t("../gl/depth_mode");e.exports=function(t,e,r,i){if("translucent"===t.renderPass&&0!==r.paint.get("raster-opacity")){var o=t.context,u=o.gl,c=e.getSource(),h=t.useProgram("raster");o.setStencilMode(s.disabled),o.setColorMode(t.colorModeForRenderPass()),u.uniform1f(h.uniforms.u_brightness_low,r.paint.get("raster-brightness-min")),u.uniform1f(h.uniforms.u_brightness_high,r.paint.get("raster-brightness-max")),u.uniform1f(h.uniforms.u_saturation_factor,function(t){return t>0?1-1/(1.001-t):-t}(r.paint.get("raster-saturation"))),u.uniform1f(h.uniforms.u_contrast_factor,function(t){return t>0?1/(1-t):1+t}(r.paint.get("raster-contrast"))),u.uniform3fv(h.uniforms.u_spin_weights,function(t){t*=Math.PI/180;var e=Math.sin(t),r=Math.cos(t);return[(2*r+1)/3,(-Math.sqrt(3)*e-r+1)/3,(Math.sqrt(3)*e-r+1)/3]}(r.paint.get("raster-hue-rotate"))),u.uniform1f(h.uniforms.u_buffer_scale,1),u.uniform1i(h.uniforms.u_image0,0),u.uniform1i(h.uniforms.u_image1,1);for(var f=i.length&&i[0].overscaledZ,p=0,d=i;p65535)e(new Error("glyphs > 65535 not supported"));else{var u=o.requests[l];u||(u=o.requests[l]=[],n(i,l,r.url,r.requestTransform,function(t,e){if(e)for(var r in e)o.glyphs[+r]=e[+r];for(var n=0,i=u;nthis.height)return n.warnOnce("LineAtlas out of space"),null;for(var o=0,s=0;s=0;this.currentLayer--){var v=r.style._layers[o[r.currentLayer]];v.source!==(d&&d.id)&&(g=[],(d=r.style.sourceCaches[v.source])&&(r.clearStencil(),g=d.getVisibleCoordinates(),d.getSource().isTileClipped&&r._renderTileClippingMasks(g))),r.renderLayer(r,d,v,g)}this.renderPass="translucent";var m,y=[];for(this.currentLayer=0,this.currentLayer;this.currentLayer0?e.pop():null},T.prototype._createProgramCached=function(t,e){this.cache=this.cache||{};var r=""+t+(e.cacheKey||"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[r]||(this.cache[r]=new y(this.context,m[t],e,this._showOverdrawInspector)),this.cache[r]},T.prototype.useProgram=function(t,e){var r=this._createProgramCached(t,e||this.emptyProgramConfiguration);return this.context.program.set(r.program),r},e.exports=T},{"../data/array_types":39,"../data/extent":53,"../data/pos_attributes":57,"../data/program_configuration":58,"../data/raster_bounds_attributes":59,"../gl/color_mode":65,"../gl/context":66,"../gl/depth_mode":67,"../gl/stencil_mode":70,"../shaders":97,"../source/pixels_to_tile_units":104,"../source/source_cache":111,"../style-spec/util/color":153,"../symbol/cross_tile_symbol_index":218,"../util/browser":252,"../util/util":275,"./draw_background":74,"./draw_circle":75,"./draw_debug":77,"./draw_fill":78,"./draw_fill_extrusion":79,"./draw_heatmap":80,"./draw_hillshade":81,"./draw_line":82,"./draw_raster":83,"./draw_symbol":84,"./program":92,"./texture":93,"./tile_mask":94,"./vertex_array_object":95,"@mapbox/gl-matrix":2}],91:[function(t,e,r){var n=t("../source/pixels_to_tile_units");r.isPatternMissing=function(t,e){if(!t)return!1;var r=e.imageManager.getPattern(t.from),n=e.imageManager.getPattern(t.to);return!r||!n},r.prepare=function(t,e,r){var n=e.context,i=n.gl,a=e.imageManager.getPattern(t.from),o=e.imageManager.getPattern(t.to);i.uniform1i(r.uniforms.u_image,0),i.uniform2fv(r.uniforms.u_pattern_tl_a,a.tl),i.uniform2fv(r.uniforms.u_pattern_br_a,a.br),i.uniform2fv(r.uniforms.u_pattern_tl_b,o.tl),i.uniform2fv(r.uniforms.u_pattern_br_b,o.br);var s=e.imageManager.getPixelSize(),l=s.width,u=s.height;i.uniform2fv(r.uniforms.u_texsize,[l,u]),i.uniform1f(r.uniforms.u_mix,t.t),i.uniform2fv(r.uniforms.u_pattern_size_a,a.displaySize),i.uniform2fv(r.uniforms.u_pattern_size_b,o.displaySize),i.uniform1f(r.uniforms.u_scale_a,t.fromScale),i.uniform1f(r.uniforms.u_scale_b,t.toScale),n.activeTexture.set(i.TEXTURE0),e.imageManager.bind(e.context)},r.setTile=function(t,e,r){var i=e.context.gl;i.uniform1f(r.uniforms.u_tile_units_to_pixels,1/n(t,1,e.transform.tileZoom));var a=Math.pow(2,t.tileID.overscaledZ),o=t.tileSize*Math.pow(2,e.transform.tileZoom)/a,s=o*(t.tileID.canonical.x+t.tileID.wrap*a),l=o*t.tileID.canonical.y;i.uniform2f(r.uniforms.u_pixel_coord_upper,s>>16,l>>16),i.uniform2f(r.uniforms.u_pixel_coord_lower,65535&s,65535&l)}},{"../source/pixels_to_tile_units":104}],92:[function(t,e,r){var n=t("../util/browser"),i=t("../shaders"),a=(t("../data/program_configuration").ProgramConfiguration,t("./vertex_array_object")),o=(t("../gl/context"),function(t,e,r,a){var o=this,s=t.gl;this.program=s.createProgram();var l=r.defines().concat("#define DEVICE_PIXEL_RATIO "+n.devicePixelRatio.toFixed(1));a&&l.push("#define OVERDRAW_INSPECTOR;");var u=l.concat(i.prelude.fragmentSource,e.fragmentSource).join("\n"),c=l.concat(i.prelude.vertexSource,e.vertexSource).join("\n"),h=s.createShader(s.FRAGMENT_SHADER);s.shaderSource(h,u),s.compileShader(h),s.attachShader(this.program,h);var f=s.createShader(s.VERTEX_SHADER);s.shaderSource(f,c),s.compileShader(f),s.attachShader(this.program,f);for(var p=r.layoutAttributes||[],d=0;d 0.5) {\n gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n gl_FragColor *= .1;\n }\n}",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n}\n"},collisionCircle:{fragmentSource:"\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n float alpha = 0.5;\n\n // Red = collision, hide label\n vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n // Blue = no collision, label is showing\n if (v_placed > 0.5) {\n color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n }\n\n if (v_notUsed > 0.5) {\n // This box not used, fade it out\n color *= .2;\n }\n\n float extrude_scale_length = length(v_extrude_scale);\n float extrude_length = length(v_extrude) * extrude_scale_length;\n float stroke_width = 15.0 * extrude_scale_length;\n float radius = v_radius * extrude_scale_length;\n\n float distance_to_edge = abs(extrude_length - radius);\n float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n gl_FragColor = opacity_t * color;\n}\n",vertexSource:"attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n v_placed = a_placed.x;\n v_notUsed = a_placed.y;\n v_radius = abs(a_extrude.y); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n v_extrude = a_extrude * padding_factor;\n v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n"},debug:{fragmentSource:"uniform highp vec4 u_color;\n\nvoid main() {\n gl_FragColor = u_color;\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fill:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n"},fillOutline:{fragmentSource:"#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 outline_color\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillOutlinePattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n // find distance to outline for alpha interpolation\n\n float dist = length(v_pos - gl_FragCoord.xy);\n float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n"},fillPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n"},fillExtrusion:{fragmentSource:"varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n #pragma mapbox: initialize highp vec4 color\n\n vec3 normal = a_normal_ed.xyz;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n\n gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n // Relative luminance (how dark/bright is the surface color?)\n float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n // Add slight ambient lighting so no extrusions are totally black\n vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n color += ambientlight;\n\n // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n // Adjust directional so that\n // the range of values for highlight/shading is narrower\n // with lower light intensity\n // and with lighter/brighter surface colors\n directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n // Add gradient along z axis of side surfaces\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n // with lower bounds adjusted to hue of light\n // so that shading is tinted with the complementary (opposite) color to the light color\n v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n"},fillExtrusionPattern:{fragmentSource:"uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec2 imagecoord = mod(v_pos_a, 1.0);\n vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n vec4 color1 = texture2D(u_image, pos);\n\n vec2 imagecoord_b = mod(v_pos_b, 1.0);\n vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n vec4 color2 = texture2D(u_image, pos2);\n\n vec4 mixedColor = mix(color1, color2, u_mix);\n\n gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n #pragma mapbox: initialize lowp float base\n #pragma mapbox: initialize lowp float height\n\n vec3 normal = a_normal_ed.xyz;\n float edgedistance = a_normal_ed.w;\n\n base = max(0.0, base);\n height = max(0.0, height);\n\n float t = mod(normal.x, 2.0);\n float z = t > 0.0 ? height : base;\n\n gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n ? a_pos // extrusion top\n : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n if (normal.y != 0.0) {\n directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n }\n\n v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n"},extrusionTexture:{fragmentSource:"uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(0.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n v_pos.x = a_pos.x;\n v_pos.y = 1.0 - a_pos.y;\n}\n"},hillshadePrepare:{fragmentSource:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\n\nfloat getElevation(vec2 coord, float bias) {\n // Convert encoded elevation value to meters\n vec4 data = texture2D(u_image, coord) * 255.0;\n return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n vec2 epsilon = 1.0 / u_dimension;\n\n // queried pixels:\n // +-----------+\n // | | | |\n // | a | b | c |\n // | | | |\n // +-----------+\n // | | | |\n // | d | e | f |\n // | | | |\n // +-----------+\n // | | | |\n // | g | h | i |\n // | | | |\n // +-----------+\n\n float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n float e = getElevation(v_pos, 0.0);\n float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n // here we divide the x and y slopes by 8 * pixel size\n // where pixel size (aka meters/pixel) is:\n // circumference of the world / (pixels per tile * number of tiles)\n // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n // we want to vertically exaggerate the hillshading though, because otherwise\n // it is barely noticeable at low zooms. to do this, we multiply this by some\n // scale factor pow(2, (u_zoom - 14) * a) where a is an arbitrary value and 14 is the\n // maxzoom of the tile source. here we use a=0.3 which works out to the\n // expression below. see nickidlugash's awesome breakdown for more info\n // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n vec2 deriv = vec2(\n (c + f + f + i) - (a + d + d + g),\n (g + h + h + i) - (a + b + b + c)\n ) / pow(2.0, (u_zoom - 14.0) * exaggeration + 19.2562 - u_zoom);\n\n gl_FragColor = clamp(vec4(\n deriv.x / 2.0 + 0.5,\n deriv.y / 2.0 + 0.5,\n 1.0,\n 1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n"},hillshade:{fragmentSource:"uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n vec4 pixel = texture2D(u_image, v_pos);\n\n vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude\n // to account for mercator projection distortion. see #4807 for details\n float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n // We also multiply the slope by an arbitrary z-factor of 1.25\n float slope = atan(1.25 * length(deriv) / scaleFactor);\n float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n float intensity = u_light.x;\n // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal\n // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n float azimuth = u_light.y + PI;\n\n // We scale the slope exponentially based on intensity, using a calculation similar to\n // the exponential interpolation function in the style spec:\n // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n // so that higher intensity values create more opaque hillshading.\n float base = 1.875 - intensity * 1.75;\n float maxValue = 0.5 * PI;\n float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n // so that the accent color's rate of change eases in while the shade color's eases out.\n float accent = cos(scaledSlope);\n // We multiply both the accent and shade color by a clamped intensity value\n // so that intensities >= 0.5 do not additionally affect the color values\n // while intensity values < 0.5 make the overall color more transparent.\n vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n v_pos = a_texture_pos / 8192.0;\n}\n"},line:{fragmentSource:"#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_width2 = vec2(outset, inset);\n}\n"},linePattern:{fragmentSource:"uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n float y_a = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_a.y);\n float y_b = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_b.y);\n vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize mediump float width\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist = outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_linesofar = a_linesofar;\n v_width2 = vec2(outset, inset);\n}\n"},lineSDF:{fragmentSource:"\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n // Calculate the distance of the pixel from the line in pixels.\n float dist = length(v_normal) * v_width2.s;\n\n // Calculate the antialiasing fade factor. This is either when fading in\n // the line in case of an offset line (v_width2.t) or when fading out\n // (v_width2.s)\n float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n float sdfdist_a = texture2D(u_image, v_tex_a).a;\n float sdfdist_b = texture2D(u_image, v_tex_b).a;\n float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also \"special\" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 color\n #pragma mapbox: initialize lowp float blur\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize mediump float gapwidth\n #pragma mapbox: initialize lowp float offset\n #pragma mapbox: initialize mediump float width\n #pragma mapbox: initialize lowp float floorwidth\n\n vec2 a_extrude = a_data.xy - 128.0;\n float a_direction = mod(a_data.z, 4.0) - 1.0;\n float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n vec2 pos = a_pos_normal.xy;\n\n // x is 1 if it's a round cap, 0 otherwise\n // y is 1 if the normal points up, and -1 if it points down\n mediump vec2 normal = a_pos_normal.zw;\n v_normal = normal;\n\n // these transformations used to be applied in the JS and native code bases.\n // moved them into the shader for clarity and simplicity.\n gapwidth = gapwidth / 2.0;\n float halfwidth = width / 2.0;\n offset = -1.0 * offset;\n\n float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n // Scale the extrusion vector down to a normal and then up by the line width\n // of this vertex.\n mediump vec2 dist =outset * a_extrude * scale;\n\n // Calculate the offset when drawing a line that is to the side of the actual line.\n // We do this by creating a vector that points towards the extrude, but rotate\n // it when we're drawing round end points (a_direction = -1 or 1) since their\n // extrude vector points in another direction.\n mediump float u = 0.5 * a_direction;\n mediump float t = 1.0 - abs(u);\n mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n // calculate how much the perspective view squishes or stretches the extrude\n float extrude_length_without_perspective = length(dist);\n float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n v_width2 = vec2(outset, inset);\n}\n"},raster:{fragmentSource:"uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n // read and cross-fade colors from the main and parent tiles\n vec4 color0 = texture2D(u_image0, v_pos0);\n vec4 color1 = texture2D(u_image1, v_pos1);\n if (color0.a > 0.0) {\n color0.rgb = color0.rgb / color0.a;\n }\n if (color1.a > 0.0) {\n color1.rgb = color1.rgb / color1.a;\n }\n vec4 color = mix(color0, color1, u_fade_t);\n color.a *= u_opacity;\n vec3 rgb = color.rgb;\n\n // spin\n rgb = vec3(\n dot(rgb, u_spin_weights.xyz),\n dot(rgb, u_spin_weights.zxy),\n dot(rgb, u_spin_weights.yzx));\n\n // saturation\n float average = (color.r + color.g + color.b) / 3.0;\n rgb += (average - rgb) * u_saturation_factor;\n\n // contrast\n rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n // brightness\n vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n gl_Position = u_matrix * vec4(a_pos, 0, 1);\n // We are using Int16 for texture position coordinates to give us enough precision for\n // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n // as an arbitrarily high number to preserve adequate precision when rendering.\n // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n // so math for modifying either is consistent.\n v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n"},symbolIcon:{fragmentSource:"uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n lowp float alpha = opacity * v_fade_opacity;\n gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n #pragma mapbox: initialize lowp float opacity\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n\n float size;\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // See comments in symbol_sdf.vertex\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // See comments in symbol_sdf.vertex\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n\n v_tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n"},symbolSDF:{fragmentSource:"#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 tex = v_data0.xy;\n float gamma_scale = v_data1.x;\n float size = v_data1.y;\n float fade_opacity = v_data1[2];\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n lowp vec4 color = fill_color;\n highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n lowp float buff = (256.0 - 64.0) / 256.0;\n if (u_is_halo) {\n color = halo_color;\n gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n buff = (6.0 - halo_width / fontScale) / SDF_PX;\n }\n\n lowp float dist = texture2D(u_texture, tex).a;\n highp float gamma_scaled = gamma * gamma_scale;\n highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n gl_FragColor = vec4(1.0);\n#endif\n}\n",vertexSource:"const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n// text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n #pragma mapbox: initialize highp vec4 fill_color\n #pragma mapbox: initialize highp vec4 halo_color\n #pragma mapbox: initialize lowp float opacity\n #pragma mapbox: initialize lowp float halo_width\n #pragma mapbox: initialize lowp float halo_blur\n\n vec2 a_pos = a_pos_offset.xy;\n vec2 a_offset = a_pos_offset.zw;\n\n vec2 a_tex = a_data.xy;\n vec2 a_size = a_data.zw;\n\n highp float segment_angle = -a_projected_pos[2];\n float size;\n\n if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n size = a_size[0] / 10.0;\n } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n size = u_size;\n } else {\n size = u_size;\n }\n\n vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n highp float camera_to_anchor_distance = projectedPoint.w;\n // If the label is pitched with the map, layout is done in pitched space,\n // which makes labels in the distance smaller relative to viewport space.\n // We counteract part of that effect by multiplying by the perspective ratio.\n // If the label isn't pitched with the map, we do layout in viewport space,\n // which makes labels in the distance larger relative to the features around\n // them. We counteract part of that effect by dividing by the perspective ratio.\n highp float distance_ratio = u_pitch_with_map ?\n camera_to_anchor_distance / u_camera_to_center_distance :\n u_camera_to_center_distance / camera_to_anchor_distance;\n highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n size *= perspective_ratio;\n\n float fontScale = u_is_text ? size / 24.0 : size;\n\n highp float symbol_rotation = 0.0;\n if (u_rotate_symbol) {\n // Point labels with 'rotation-alignment: map' are horizontal with respect to tile units\n // To figure out that angle in projected space, we draw a short horizontal line in tile\n // space, project it, and measure its angle in projected space.\n vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n vec2 a = projectedPoint.xy / projectedPoint.w;\n vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n }\n\n highp float angle_sin = sin(segment_angle + symbol_rotation);\n highp float angle_cos = cos(segment_angle + symbol_rotation);\n mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n float gamma_scale = gl_Position.w;\n\n vec2 tex = a_tex / u_texsize;\n vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n v_data0 = vec2(tex.x, tex.y);\n v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n"}},i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,a=function(t){var e=n[t],r={};e.fragmentSource=e.fragmentSource.replace(i,function(t,e,n,i,a){return r[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"}),e.vertexSource=e.vertexSource.replace(i,function(t,e,n,i,a){var o="float"===i?"vec2":"vec4";return r[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\nvarying "+n+" "+i+" "+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float a_"+a+"_t;\nattribute "+n+" "+o+" a_"+a+";\n#else\nuniform "+n+" "+i+" u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+n+" "+i+" "+a+" = unpack_mix_"+o+"(a_"+a+", a_"+a+"_t);\n#else\n "+n+" "+i+" "+a+" = u_"+a+";\n#endif\n"})};for(var o in n)a(o);e.exports=n},{}],98:[function(t,e,r){var n=t("./image_source"),i=t("../util/window"),a=t("../data/raster_bounds_attributes"),o=t("../render/vertex_array_object"),s=t("../render/texture"),l=function(t){function e(e,r,n,i){t.call(this,e,r,n,i),this.options=r,this.animate=void 0===r.animate||r.animate}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.load=function(){this.canvas=this.canvas||i.document.getElementById(this.options.canvas),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire("error",new Error("Canvas dimensions cannot be less than or equal to zero.")):(this.play=function(){this._playing=!0,this.map._rerender()},this.pause=function(){this._playing=!1},this._finishLoading())},e.prototype.getCanvas=function(){return this.canvas},e.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play()},e.prototype.onRemove=function(){this.pause()},e.prototype.prepare=function(){var t=this,e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var r=this.map.painter.context,n=r.gl;for(var i in this.boundsBuffer||(this.boundsBuffer=r.createVertexBuffer(this._boundsArray,a.members)),this.boundsVAO||(this.boundsVAO=new o),this.texture?e?this.texture.update(this.canvas):this._playing&&(this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,this.canvas)):(this.texture=new s(r,this.canvas,n.RGBA),this.texture.bind(n.LINEAR,n.CLAMP_TO_EDGE)),t.tiles){var l=t.tiles[i];"loaded"!==l.state&&(l.state="loaded",l.texture=t.texture)}}},e.prototype.serialize=function(){return{type:"canvas",canvas:this.canvas,coordinates:this.coordinates}},e.prototype.hasTransition=function(){return this._playing},e.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];t0&&(r.resourceTiming=t._resourceTiming,t._resourceTiming=[]),t.fire("data",r)}})},e.prototype.onAdd=function(t){this.map=t,this.load()},e.prototype.setData=function(t){var e=this;return this._data=t,this.fire("dataloading",{dataType:"source"}),this._updateWorkerData(function(t){if(t)return e.fire("error",{error:t});var r={dataType:"source",sourceDataType:"content"};e._collectResourceTiming&&e._resourceTiming&&e._resourceTiming.length>0&&(r.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire("data",r)}),this},e.prototype._updateWorkerData=function(t){var e=this,r=i.extend({},this.workerOptions),n=this._data;"string"==typeof n?(r.request=this.map._transformRequest(function(t){var e=a.document.createElement("a");return e.href=t,e.href}(n),s.Source),r.request.collectResourceTiming=this._collectResourceTiming):r.data=JSON.stringify(n),this.workerID=this.dispatcher.send(this.type+".loadData",r,function(r,n){e._loaded=!0,n&&n.resourceTiming&&n.resourceTiming[e.id]&&(e._resourceTiming=n.resourceTiming[e.id].slice(0)),t(r)},this.workerID)},e.prototype.loadTile=function(t,e){var r=this,n=void 0===t.workerID||"expired"===t.state?"loadTile":"reloadTile",i={type:this.type,uid:t.uid,tileID:t.tileID,zoom:t.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:l.devicePixelRatio,overscaling:t.tileID.overscaleFactor(),showCollisionBoxes:this.map.showCollisionBoxes};t.workerID=this.dispatcher.send(n,i,function(i,a){return t.unloadVectorData(),t.aborted?e(null):i?e(i):(t.loadVectorData(a,r.map.painter,"reloadTile"===n),e(null))},this.workerID)},e.prototype.abortTile=function(t){t.aborted=!0},e.prototype.unloadTile=function(t){t.unloadVectorData(),this.dispatcher.send("removeTile",{uid:t.uid,type:this.type,source:this.id},null,t.workerID)},e.prototype.onRemove=function(){this.dispatcher.broadcast("removeSource",{type:this.type,source:this.id})},e.prototype.serialize=function(){return i.extend({},this._options,{type:this.type,data:this._data})},e.prototype.hasTransition=function(){return!1},e}(n);e.exports=u},{"../data/extent":53,"../util/ajax":251,"../util/browser":252,"../util/evented":260,"../util/util":275,"../util/window":254}],100:[function(t,e,r){function n(t,e){var r=t.source,n=t.tileID.canonical;if(!this._geoJSONIndexes[r])return e(null,null);var i=this._geoJSONIndexes[r].getTile(n.z,n.x,n.y);if(!i)return e(null,null);var a=new s(i.features),o=l(a);0===o.byteOffset&&o.byteLength===o.buffer.byteLength||(o=new Uint8Array(o)),e(null,{vectorTile:a,rawData:o.buffer})}var i=t("../util/ajax"),a=t("../util/performance"),o=t("geojson-rewind"),s=t("./geojson_wrapper"),l=t("vt-pbf"),u=t("supercluster"),c=t("geojson-vt"),h=function(t){function e(e,r,i){t.call(this,e,r,n),i&&(this.loadGeoJSON=i),this._geoJSONIndexes={}}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.loadData=function(t,e){var r=this;this.loadGeoJSON(t,function(n,i){if(n||!i)return e(n);if("object"!=typeof i)return e(new Error("Input data is not a valid GeoJSON object."));o(i,!0);try{r._geoJSONIndexes[t.source]=t.cluster?u(t.superclusterOptions).load(i.features):c(i,t.geojsonVtOptions)}catch(n){return e(n)}r.loaded[t.source]={};var s={};if(t.request&&t.request.collectResourceTiming){var l=a.getEntriesByName(t.request.url);l&&(s.resourceTiming={},s.resourceTiming[t.source]=JSON.parse(JSON.stringify(l)))}e(null,s)})},e.prototype.reloadTile=function(e,r){var n=this.loaded[e.source],i=e.uid;return n&&n[i]?t.prototype.reloadTile.call(this,e,r):this.loadTile(e,r)},e.prototype.loadGeoJSON=function(t,e){if(t.request)i.getJSON(t.request,e);else{if("string"!=typeof t.data)return e(new Error("Input data is not a valid GeoJSON object."));try{return e(null,JSON.parse(t.data))}catch(t){return e(new Error("Input data is not a valid GeoJSON object."))}}},e.prototype.removeSource=function(t,e){this._geoJSONIndexes[t.source]&&delete this._geoJSONIndexes[t.source],e()},e}(t("./vector_tile_worker_source"));e.exports=h},{"../util/ajax":251,"../util/performance":268,"./geojson_wrapper":101,"./vector_tile_worker_source":116,"geojson-rewind":15,"geojson-vt":19,supercluster:32,"vt-pbf":34}],101:[function(t,e,r){var n=t("@mapbox/point-geometry"),i=t("@mapbox/vector-tile").VectorTileFeature.prototype.toGeoJSON,a=t("../data/extent"),o=function(t){this._feature=t,this.extent=a,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10))};o.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],e=0,r=this._feature.geometry;e0&&(l[new s(t.overscaledZ,i,e.z,n,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,t.wrap,e.z,e.x,e.y-1).key]={backfilled:!1},l[new s(t.overscaledZ,o,e.z,a,e.y-1).key]={backfilled:!1}),e.y+11||(Math.abs(r)>1&&(1===Math.abs(r+i)?r+=i:1===Math.abs(r-i)&&(r-=i)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,r,n),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)))}for(var r=this.getRenderableIds(),n=0;ne)){var s=Math.pow(2,o.tileID.canonical.z-t.canonical.z);if(Math.floor(o.tileID.canonical.x/s)===t.canonical.x&&Math.floor(o.tileID.canonical.y/s)===t.canonical.y)for(r[a]=o.tileID,i=!0;o&&o.tileID.overscaledZ-1>t.overscaledZ;){var l=o.tileID.scaledTo(o.tileID.overscaledZ-1);if(!l)break;(o=n._tiles[l.key])&&o.hasData()&&(delete r[a],r[l.key]=l)}}}return i},e.prototype.findLoadedParent=function(t,e,r){for(var n=this,i=t.overscaledZ-1;i>=e;i--){var a=t.scaledTo(i);if(!a)return;var o=String(a.key),s=n._tiles[o];if(s&&s.hasData())return r[o]=a,s;if(n._cache.has(o))return r[o]=a,n._cache.get(o)}},e.prototype.updateCacheSize=function(t){var e=(Math.ceil(t.width/this._source.tileSize)+1)*(Math.ceil(t.height/this._source.tileSize)+1),r=Math.floor(5*e),n="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,r):r;this._cache.setMaxSize(n)},e.prototype.update=function(t){var r=this;if(this.transform=t,this._sourceLoaded&&!this._paused){var n;this.updateCacheSize(t),this._coveredTiles={},this.used?this._source.tileID?n=t.getVisibleUnwrappedCoordinates(this._source.tileID).map(function(t){return new d(t.canonical.z,t.wrap,t.canonical.z,t.canonical.x,t.canonical.y)}):(n=t.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(n=n.filter(function(t){return r._source.hasTile(t)}))):n=[];var a,o=(this._source.roundZoom?Math.round:Math.floor)(this.getZoom(t)),s=Math.max(o-e.maxOverzooming,this._source.minzoom),l=Math.max(o+e.maxUnderzooming,this._source.minzoom),u=this._updateRetainedTiles(n,o),h={};if(i(this._source.type))for(var f=Object.keys(u),g=0;g=p.now())){r._findLoadedChildren(m,l,u)&&(u[v]=m);var x=r.findLoadedParent(m,s,h);x&&r._addTile(x.tileID)}}for(a in h)u[a]||(r._coveredTiles[a]=!0);for(a in h)u[a]=h[a];for(var b=c.keysDifference(this._tiles,u),_=0;_n._source.maxzoom){var p=u.children(n._source.maxzoom)[0],d=n.getTile(p);d&&d.hasData()?i[p.key]=p:f=!1}else{n._findLoadedChildren(u,s,i);for(var g=u.children(n._source.maxzoom),v=0;v=o;--m){var y=u.scaledTo(m);if(a[y.key])break;if(a[y.key]=!0,!(c=n.getTile(y))&&h&&(c=n._addTile(y)),c&&(i[y.key]=y,h=c.wasRequested(),c.hasData()))break}}}return i},e.prototype._addTile=function(t){var e=this._tiles[t.key];if(e)return e;(e=this._cache.getAndRemove(t.key))&&this._cacheTimers[t.key]&&(clearTimeout(this._cacheTimers[t.key]),delete this._cacheTimers[t.key],this._setTileReloadTimer(t.key,e));var r=Boolean(e);return r||(e=new o(t,this._source.tileSize*t.overscaleFactor()),this._loadTile(e,this._tileLoaded.bind(this,e,t.key,e.state))),e?(e.uses++,this._tiles[t.key]=e,r||this._source.fire("dataloading",{tile:e,coord:e.tileID,dataType:"source"}),e):null},e.prototype._setTileReloadTimer=function(t,e){var r=this;t in this._timers&&(clearTimeout(this._timers[t]),delete this._timers[t]);var n=e.getExpiryTimeout();n&&(this._timers[t]=setTimeout(function(){r._reloadTile(t,"expired"),delete r._timers[t]},n))},e.prototype._setCacheInvalidationTimer=function(t,e){var r=this;t in this._cacheTimers&&(clearTimeout(this._cacheTimers[t]),delete this._cacheTimers[t]);var n=e.getExpiryTimeout();n&&(this._cacheTimers[t]=setTimeout(function(){r._cache.remove(t),delete r._cacheTimers[t]},n))},e.prototype._removeTile=function(t){var e=this._tiles[t];if(e&&(e.uses--,delete this._tiles[t],this._timers[t]&&(clearTimeout(this._timers[t]),delete this._timers[t]),!(e.uses>0)))if(e.hasData()){e.tileID=e.tileID.wrapped();var r=e.tileID.key;this._cache.add(r,e),this._setCacheInvalidationTimer(r,e)}else e.aborted=!0,this._abortTile(e),this._unloadTile(e)},e.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._resetCache()},e.prototype._resetCache=function(){for(var t in this._cacheTimers)clearTimeout(this._cacheTimers[t]);this._cacheTimers={},this._cache.reset()},e.prototype.tilesIn=function(t){for(var e=[],r=this.getIds(),i=1/0,a=1/0,o=-1/0,s=-1/0,l=t[0].zoom,c=0;c=0&&v[1].y>=0){for(var m=[],y=0;y=p.now())return!0}return!1},e}(s);g.maxOverzooming=10,g.maxUnderzooming=3,e.exports=g},{"../data/extent":53,"../geo/coordinate":61,"../gl/context":66,"../util/browser":252,"../util/evented":260,"../util/lru_cache":266,"../util/util":275,"./source":110,"./tile":112,"./tile_id":114,"@mapbox/point-geometry":4}],112:[function(t,e,r){var n=t("../util/util"),i=t("../data/bucket").deserialize,a=(t("../data/feature_index"),t("@mapbox/vector-tile")),o=t("pbf"),s=t("../util/vectortile_to_geojson"),l=t("../style-spec/feature_filter"),u=(t("../symbol/collision_index"),t("../data/bucket/symbol_bucket")),c=t("../data/array_types"),h=c.RasterBoundsArray,f=c.CollisionBoxArray,p=t("../data/raster_bounds_attributes"),d=t("../data/extent"),g=t("@mapbox/point-geometry"),v=t("../render/texture"),m=t("../data/segment").SegmentVector,y=t("../data/index_array_type").TriangleIndexArray,x=t("../util/browser"),b=function(t,e){this.tileID=t,this.uid=n.uniqueId(),this.uses=0,this.tileSize=e,this.buckets={},this.expirationTime=null,this.expiredRequestCount=0,this.state="loading"};b.prototype.registerFadeDuration=function(t){var e=t+this.timeAdded;e>s.z,u=new g(s.x*l,s.y*l),c=new g(u.x+l,u.y+l),f=this.segments.prepareSegment(4,r,i);r.emplaceBack(u.x,u.y,u.x,u.y),r.emplaceBack(c.x,u.y,c.x,u.y),r.emplaceBack(u.x,c.y,u.x,c.y),r.emplaceBack(c.x,c.y,c.x,c.y);var v=f.vertexLength;i.emplaceBack(v,v+1,v+2),i.emplaceBack(v+1,v+2,v+3),f.vertexLength+=4,f.primitiveLength+=2}this.maskedBoundsBuffer=e.createVertexBuffer(r,p.members),this.maskedIndexBuffer=e.createIndexBuffer(i)}},b.prototype.hasData=function(){return"loaded"===this.state||"reloading"===this.state||"expired"===this.state},b.prototype.setExpiryData=function(t){var e=this.expirationTime;if(t.cacheControl){var r=n.parseCacheControl(t.cacheControl);r["max-age"]&&(this.expirationTime=Date.now()+1e3*r["max-age"])}else t.expires&&(this.expirationTime=new Date(t.expires).getTime());if(this.expirationTime){var i=Date.now(),a=!1;if(this.expirationTime>i)a=!1;else if(e)if(this.expirationTime=e&&t.x=r&&t.y0;a--)i+=(e&(n=1<this.canonical.z?new u(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new u(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},u.prototype.isChildOf=function(t){var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e},u.prototype.children=function(t){if(this.overscaledZ>=t)return[new u(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return[new u(e,this.wrap,e,r,n),new u(e,this.wrap,e,r+1,n),new u(e,this.wrap,e,r,n+1),new u(e,this.wrap,e,r+1,n+1)]},u.prototype.isLessThan=function(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=E.maxzoom||"none"===E.visibility||(n(C,d.zoom),(m[E.id]=E.createBucket({index:v.bucketLayerIDs.length,layers:C,zoom:d.zoom,pixelRatio:d.pixelRatio,overscaling:d.overscaling,collisionBoxArray:d.collisionBoxArray})).populate(k,y),v.bucketLayerIDs.push(C.map(function(t){return t.id})))}}}var L,P,z,D=u.mapObject(y.glyphDependencies,function(t){return Object.keys(t).map(Number)});Object.keys(D).length?r.send("getGlyphs",{uid:this.uid,stacks:D},function(t,e){L||(L=t,P=e,p.call(d))}):P={};var I=Object.keys(y.iconDependencies);I.length?r.send("getImages",{icons:I},function(t,e){L||(L=t,z=e,p.call(d))}):z={},p.call(this)},e.exports=d},{"../data/array_types":39,"../data/bucket/symbol_bucket":51,"../data/feature_index":54,"../render/glyph_atlas":85,"../render/image_atlas":87,"../style/evaluation_parameters":182,"../symbol/symbol_layout":227,"../util/dictionary_coder":257,"../util/util":275,"./tile_id":114}],120:[function(t,e,r){function n(t,e){var r={};for(var n in t)"ref"!==n&&(r[n]=t[n]);return i.forEach(function(t){t in e&&(r[t]=e[t])}),r}var i=t("./util/ref_properties");e.exports=function(t){t=t.slice();for(var e=Object.create(null),r=0;r4)return e.error("Expected 1, 2, or 3 arguments, but found "+(t.length-1)+" instead.");var r,n;if(t.length>2){var i=t[1];if("string"!=typeof i||!(i in p))return e.error('The item type argument of "array" must be one of string, number, boolean',1);r=p[i]}else r=o;if(t.length>3){if("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2]))return e.error('The length argument to "array" must be a positive integer literal',2);n=t[2]}var s=a(r,n),l=e.parse(t[t.length-1],t.length-1,o);return l?new d(s,l):null},d.prototype.evaluate=function(t){var e=this.input.evaluate(t);if(c(this.type,h(e)))throw new f("Expected value to be of type "+i(this.type)+", but found "+i(h(e))+" instead.");return e},d.prototype.eachChild=function(t){t(this.input)},d.prototype.possibleOutputs=function(){return this.input.possibleOutputs()},e.exports=d},{"../runtime_error":143,"../types":146,"../values":147}],125:[function(t,e,r){var n=t("../types"),i=n.ObjectType,a=n.ValueType,o=n.StringType,s=n.NumberType,l=n.BooleanType,u=t("../runtime_error"),c=t("../types"),h=c.checkSubtype,f=c.toString,p=t("../values").typeOf,d={string:o,number:s,boolean:l,object:i},g=function(t,e){this.type=t,this.args=e};g.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");for(var r=t[0],n=d[r],i=[],o=1;o=r.length)throw new s("Array index out of bounds: "+e+" > "+r.length+".");if(e!==Math.floor(e))throw new s("Array index must be an integer, but found "+e+" instead.");return r[e]},l.prototype.eachChild=function(t){t(this.index),t(this.input)},l.prototype.possibleOutputs=function(){return[void 0]},e.exports=l},{"../runtime_error":143,"../types":146}],127:[function(t,e,r){var n=t("../types").BooleanType,i=function(t,e,r){this.type=t,this.branches=e,this.otherwise=r};i.parse=function(t,e){if(t.length<4)return e.error("Expected at least 3 arguments, but found only "+(t.length-1)+".");if(t.length%2!=0)return e.error("Expected an odd number of arguments.");var r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);for(var a=[],o=1;o4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":u(e[0],e[1],e[2],e[3])))return new l(e[0]/255,e[1]/255,e[2]/255,e[3]);throw new c(r||"Could not parse color from value '"+("string"==typeof e?e:JSON.stringify(e))+"'")}for(var o=null,s=0,h=this.args;sn.evaluate(t)}function u(t,e){var r=e[0],n=e[1];return r.evaluate(t)<=n.evaluate(t)}function c(t,e){var r=e[0],n=e[1];return r.evaluate(t)>=n.evaluate(t)}var h=t("../types"),f=h.NumberType,p=h.StringType,d=h.BooleanType,g=h.ColorType,v=h.ObjectType,m=h.ValueType,y=h.ErrorType,x=h.array,b=h.toString,_=t("../values"),w=_.typeOf,k=_.Color,M=_.validateRGBA,A=t("../compound_expression"),T=A.CompoundExpression,S=A.varargs,C=t("../runtime_error"),E=t("./let"),L=t("./var"),P=t("./literal"),z=t("./assertion"),D=t("./array"),I=t("./coercion"),O=t("./at"),R=t("./match"),B=t("./case"),F=t("./step"),N=t("./interpolate"),j=t("./coalesce"),V=t("./equals"),U={"==":V.Equals,"!=":V.NotEquals,array:D,at:O,boolean:z,case:B,coalesce:j,interpolate:N,let:E,literal:P,match:R,number:z,object:z,step:F,string:z,"to-color":I,"to-number":I,var:L};T.register(U,{error:[y,[p],function(t,e){var r=e[0];throw new C(r.evaluate(t))}],typeof:[p,[m],function(t,e){var r=e[0];return b(w(r.evaluate(t)))}],"to-string":[p,[m],function(t,e){var r=e[0],n=typeof(r=r.evaluate(t));return null===r||"string"===n||"number"===n||"boolean"===n?String(r):r instanceof k?r.toString():JSON.stringify(r)}],"to-boolean":[d,[m],function(t,e){var r=e[0];return Boolean(r.evaluate(t))}],"to-rgba":[x(f,4),[g],function(t,e){var r=e[0].evaluate(t),n=r.r,i=r.g,a=r.b,o=r.a;return[255*n/o,255*i/o,255*a/o,o]}],rgb:[g,[f,f,f],n],rgba:[g,[f,f,f,f],n],length:{type:f,overloads:[[[p],o],[[x(m)],o]]},has:{type:d,overloads:[[[p],function(t,e){return i(e[0].evaluate(t),t.properties())}],[[p,v],function(t,e){var r=e[0],n=e[1];return i(r.evaluate(t),n.evaluate(t))}]]},get:{type:m,overloads:[[[p],function(t,e){return a(e[0].evaluate(t),t.properties())}],[[p,v],function(t,e){var r=e[0],n=e[1];return a(r.evaluate(t),n.evaluate(t))}]]},properties:[v,[],function(t){return t.properties()}],"geometry-type":[p,[],function(t){return t.geometryType()}],id:[m,[],function(t){return t.id()}],zoom:[f,[],function(t){return t.globals.zoom}],"heatmap-density":[f,[],function(t){return t.globals.heatmapDensity||0}],"+":[f,S(f),function(t,e){for(var r=0,n=0,i=e;n":[d,[p,m],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[d,[m],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[d,[p,m],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[d,[m],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[d,[p,m],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[d,[m],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[d,[m],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[d,[],function(t){return null!==t.id()}],"filter-type-in":[d,[x(p)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[d,[x(m)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[d,[p,x(m)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[d,[p,x(m)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return!0;e[i]>t?n=i-1:r=i+1}return!1}(t.properties()[r.value],n.value,0,n.value.length-1)}],">":{type:d,overloads:[[[f,f],l],[[p,p],l]]},"<":{type:d,overloads:[[[f,f],s],[[p,p],s]]},">=":{type:d,overloads:[[[f,f],c],[[p,p],c]]},"<=":{type:d,overloads:[[[f,f],u],[[p,p],u]]},all:{type:d,overloads:[[[d,d],function(t,e){var r=e[0],n=e[1];return r.evaluate(t)&&n.evaluate(t)}],[S(d),function(t,e){for(var r=0,n=e;r1}))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);r={name:"cubic-bezier",controlPoints:o}}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(n=e.parse(n,2,l)))return null;var u=[],h=null;e.expectedType&&"value"!==e.expectedType.kind&&(h=e.expectedType);for(var f=0;f=p)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',g);var m=e.parse(d,v,h);if(!m)return null;h=h||m.type,u.push([p,m])}return"number"===h.kind||"color"===h.kind||"array"===h.kind&&"number"===h.itemType.kind&&"number"==typeof h.N?new c(h,r,n,u):e.error("Type "+s(h)+" is not interpolatable.")},c.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var o=u(e,n),s=e[o],l=e[o+1],h=c.interpolationFactor(this.interpolation,n,s,l),f=r[o].evaluate(t),p=r[o+1].evaluate(t);return a[this.type.kind.toLowerCase()](f,p,h)},c.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;eNumber.MAX_SAFE_INTEGER)return h.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof d&&Math.floor(d)!==d)return h.error("Numeric branch labels must be integer values.");if(r){if(h.checkSubtype(r,n(d)))return null}else r=n(d);if(void 0!==o[String(d)])return h.error("Branch labels must be unique.");o[String(d)]=s.length}var g=e.parse(c,l,a);if(!g)return null;a=a||g.type,s.push(g)}var v=e.parse(t[1],1,r);if(!v)return null;var m=e.parse(t[t.length-1],t.length-1,a);return m?new i(r,a,v,o,s,m):null},i.prototype.evaluate=function(t){var e=this.input.evaluate(t);return(this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},i.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise)},i.prototype.possibleOutputs=function(){return(t=[]).concat.apply(t,this.outputs.map(function(t){return t.possibleOutputs()})).concat(this.otherwise.possibleOutputs());var t},e.exports=i},{"../values":147}],136:[function(t,e,r){var n=t("../types").NumberType,i=t("../stops").findStopLessThanOrEqualTo,a=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n=u)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',h);var p=e.parse(c,f,s);if(!p)return null;s=s||p.type,o.push([u,p])}return new a(s,r,o)},a.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var a=e.length;return n>=e[a-1]?r[a-1].evaluate(t):r[i(e,n)].evaluate(t)},a.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e0&&"string"==typeof t[0]&&t[0]in g}function i(t,e,r){void 0===r&&(r={});var n=new l(g,[],function(t){var e={color:P,string:z,number:D,enum:z,boolean:I};return"array"===t.type?R(e[t.value]||O,t.length):e[t.type]||null}(e)),i=n.parse(t);return i?x(!1===r.handleErrors?new _(i):new w(i,e)):b(n.errors)}function a(t,e,r){if(void 0===r&&(r={}),"error"===(t=i(t,e,r)).result)return t;var n=t.value.expression,a=v.isFeatureConstant(n);if(!a&&!e["property-function"])return b([new s("","property expressions not supported")]);var o=v.isGlobalPropertyConstant(n,["zoom"]);if(!o&&!1===e["zoom-function"])return b([new s("","zoom expressions not supported")]);var l=function t(e){var r=null;if(e instanceof d)r=t(e.result);else if(e instanceof p)for(var n=0,i=e.args;n=0)return!1;var i=!0;return e.eachChild(function(e){i&&!t(e,r)&&(i=!1)}),i}}},{"./compound_expression":123}],141:[function(t,e,r){var n=t("./scope"),i=t("./types").checkSubtype,a=t("./parsing_error"),o=t("./definitions/literal"),s=t("./definitions/assertion"),l=t("./definitions/array"),u=t("./definitions/coercion"),c=function(t,e,r,i,a){void 0===e&&(e=[]),void 0===i&&(i=new n),void 0===a&&(a=[]),this.registry=t,this.path=e,this.key=e.map(function(t){return"["+t+"]"}).join(""),this.scope=i,this.errors=a,this.expectedType=r};c.prototype.parse=function(e,r,n,i,a){void 0===a&&(a={});var c=this;if(r&&(c=c.concat(r,n,i)),null!==e&&"string"!=typeof e&&"boolean"!=typeof e&&"number"!=typeof e||(e=["literal",e]),Array.isArray(e)){if(0===e.length)return c.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var h=e[0];if("string"!=typeof h)return c.error("Expression name must be a string, but found "+typeof h+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var f=c.registry[h];if(f){var p=f.parse(e,c);if(!p)return null;if(c.expectedType){var d=c.expectedType,g=p.type;if("string"!==d.kind&&"number"!==d.kind&&"boolean"!==d.kind||"value"!==g.kind)if("array"===d.kind&&"value"===g.kind)a.omitTypeAnnotations||(p=new l(d,p));else if("color"!==d.kind||"value"!==g.kind&&"string"!==g.kind){if(c.checkSubtype(c.expectedType,p.type))return null}else a.omitTypeAnnotations||(p=new u(d,[p]));else a.omitTypeAnnotations||(p=new s(d,[p]))}if(!(p instanceof o)&&function(e){var r=t("./compound_expression").CompoundExpression,n=t("./is_constant"),i=n.isGlobalPropertyConstant,a=n.isFeatureConstant;if(e instanceof t("./definitions/var"))return!1;if(e instanceof r&&"error"===e.name)return!1;var s=!0;return e.eachChild(function(t){t instanceof o||(s=!1)}),!!s&&a(e)&&i(e,["zoom","heatmap-density"])}(p)){var v=new(t("./evaluation_context"));try{p=new o(p.type,p.evaluate(v))}catch(e){return c.error(e.message),null}}return p}return c.error('Unknown expression "'+h+'". If you wanted a literal array, use ["literal", [...]].',0)}return void 0===e?c.error("'undefined' value invalid. Use null instead."):"object"==typeof e?c.error('Bare objects invalid. Use ["literal", {...}] instead.'):c.error("Expected an array, but found "+typeof e+" instead.")},c.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new c(this.registry,n,e||null,i,this.errors)},c.prototype.error=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];var i=""+this.key+r.map(function(t){return"["+t+"]"}).join("");this.errors.push(new a(i,t))},c.prototype.checkSubtype=function(t,e){var r=i(t,e);return r&&this.error(r),r},e.exports=c},{"./compound_expression":123,"./definitions/array":124,"./definitions/assertion":125,"./definitions/coercion":129,"./definitions/literal":134,"./definitions/var":137,"./evaluation_context":138,"./is_constant":140,"./parsing_error":142,"./scope":144,"./types":146}],142:[function(t,e,r){var n=function(t){function e(e,r){t.call(this,r),this.message=r,this.key=e}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);e.exports=n},{}],143:[function(t,e,r){var n=function(t){this.name="ExpressionEvaluationError",this.message=t};n.prototype.toJSON=function(){return this.message},e.exports=n},{}],144:[function(t,e,r){var n=function(t,e){void 0===e&&(e=[]),this.parent=t,this.bindings={};for(var r=0,n=e;rr&&ee))throw new n("Input is not a number.");o=s-1}}return Math.max(s-1,0)}}},{"./runtime_error":143}],146:[function(t,e,r){function n(t,e){return{kind:"array",itemType:t,N:e}}function i(t){if("array"===t.kind){var e=i(t.itemType);return"number"==typeof t.N?"array<"+e+", "+t.N+">":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var a={kind:"null"},o={kind:"number"},s={kind:"string"},l={kind:"boolean"},u={kind:"color"},c={kind:"object"},h={kind:"value"},f=[a,o,s,l,u,c,n(h)];e.exports={NullType:a,NumberType:o,StringType:s,BooleanType:l,ColorType:u,ObjectType:c,ValueType:h,array:n,ErrorType:{kind:"error"},toString:i,checkSubtype:function t(e,r){if("error"===r.kind)return null;if("array"===e.kind){if("array"===r.kind&&!t(e.itemType,r.itemType)&&("number"!=typeof e.N||e.N===r.N))return null}else{if(e.kind===r.kind)return null;if("value"===e.kind)for(var n=0,a=f;n=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."},isValue:function t(e){if(null===e)return!0;if("string"==typeof e)return!0;if("boolean"==typeof e)return!0;if("number"==typeof e)return!0;if(e instanceof n)return!0;if(Array.isArray(e)){for(var r=0,i=e;r=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3===t.length&&(Array.isArray(t[1])||Array.isArray(t[2]));case"any":case"all":for(var e=0,r=t.slice(1);ee?1:0}function a(t){if(!t)return!0;var e=t[0];return t.length<=1?"any"!==e:"=="===e?o(t[1],t[2],"=="):"!="===e?u(o(t[1],t[2],"==")):"<"===e||">"===e||"<="===e||">="===e?o(t[1],t[2],e):"any"===e?function(t){return["any"].concat(t.map(a))}(t.slice(1)):"all"===e?["all"].concat(t.slice(1).map(a)):"none"===e?["all"].concat(t.slice(1).map(a).map(u)):"in"===e?s(t[1],t.slice(2)):"!in"===e?u(s(t[1],t.slice(2))):"has"===e?l(t[1]):"!has"!==e||u(l(t[1]))}function o(t,e,r){switch(t){case"$type":return["filter-type-"+r,e];case"$id":return["filter-id-"+r,e];default:return["filter-"+r,t,e]}}function s(t,e){if(0===e.length)return!1;switch(t){case"$type":return["filter-type-in",["literal",e]];case"$id":return["filter-id-in",["literal",e]];default:return e.length>200&&!e.some(function(t){return typeof t!=typeof e[0]})?["filter-in-large",t,["literal",e.sort(i)]]:["filter-in-small",t,["literal",e]]}}function l(t){switch(t){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",t]}}function u(t){return["!",t]}var c=t("../expression").createExpression;e.exports=function(t){if(!t)return function(){return!0};n(t)||(t=a(t));var e=c(t,h);if("error"===e.result)throw new Error(e.value.map(function(t){return t.key+": "+t.message}).join(", "));return function(t,r){return e.value.evaluate(t,r)}},e.exports.isExpressionFilter=n;var h={type:"boolean",default:!1,function:!0,"property-function":!0,"zoom-function":!0}},{"../expression":139}],149:[function(t,e,r){function n(t){return t}function i(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function a(t,e,r,n,a){return i(typeof r===a?n[r]:void 0,t.default,e.default)}function o(t,e,r){if("number"!==p(r))return i(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var a=u(t.stops,r);return t.stops[a][1]}function s(t,e,r){var a=void 0!==t.base?t.base:1;if("number"!==p(r))return i(t.default,e.default);var o=t.stops.length;if(1===o)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[o-1][0])return t.stops[o-1][1];var s=u(t.stops,r),l=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,a,t.stops[s][0],t.stops[s+1][0]),h=t.stops[s][1],f=t.stops[s+1][1],g=d[e.type]||n;if(t.colorSpace&&"rgb"!==t.colorSpace){var v=c[t.colorSpace];g=function(t,e){return v.reverse(v.interpolate(v.forward(t),v.forward(e),l))}}return"function"==typeof h.evaluate?{evaluate:function(){for(var t=arguments,e=[],r=arguments.length;r--;)e[r]=t[r];var n=h.evaluate.apply(void 0,e),i=f.evaluate.apply(void 0,e);if(void 0!==n&&void 0!==i)return g(n,i,l)}}:g(h,f,l)}function l(t,e,r){return"color"===e.type?r=h.parse(r):p(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),i(r,t.default,e.default)}function u(t,e){for(var r,n,i=0,a=t.length-1,o=0;i<=a;){if(r=t[o=Math.floor((i+a)/2)][0],n=t[o+1][0],e===r||e>r&&ee&&(a=o-1)}return Math.max(o-1,0)}var c=t("../util/color_spaces"),h=t("../util/color"),f=t("../util/extend"),p=t("../util/get_type"),d=t("../util/interpolate"),g=t("../expression/definitions/interpolate");e.exports={createFunction:function t(e,r){var n,u,p,d="color"===r.type,v=e.stops&&"object"==typeof e.stops[0][0],m=v||void 0!==e.property,y=v||!m,x=e.type||("interpolated"===r.function?"exponential":"interval");if(d&&((e=f({},e)).stops&&(e.stops=e.stops.map(function(t){return[t[0],h.parse(t[1])]})),e.default?e.default=h.parse(e.default):e.default=h.parse(r.default)),e.colorSpace&&"rgb"!==e.colorSpace&&!c[e.colorSpace])throw new Error("Unknown color space: "+e.colorSpace);if("exponential"===x)n=s;else if("interval"===x)n=o;else if("categorical"===x){n=a,u=Object.create(null);for(var b=0,_=e.stops;b<_.length;b+=1){var w=_[b];u[w[0]]=w[1]}p=typeof e.stops[0][0]}else{if("identity"!==x)throw new Error('Unknown function type "'+x+'"');n=l}if(v){for(var k={},M=[],A=0;A":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:22,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},transition:!1,"zoom-function":!0,"property-function":!1,function:"piecewise-constant"},position:{type:"array",default:[1.15,210,30],length:3,value:"number",transition:!0,function:"interpolated","zoom-function":!0,"property-function":!1},color:{type:"color",default:"#ffffff",function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},intensity:{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",function:"piecewise-constant","zoom-function":!0,default:!0},"fill-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"fill-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"}]},"fill-outline-color":{type:"color",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}]},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-translate"]},"fill-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!1,default:1,minimum:0,maximum:1,transition:!0},"fill-extrusion-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"fill-extrusion-pattern"}]},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"fill-extrusion-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"]},"fill-extrusion-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"fill-extrusion-height":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0},"fill-extrusion-base":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"]}},paint_line:{"line-opacity":{type:"number",function:"interpolated","zoom-function":!0,"property-function":!0,default:1,minimum:0,maximum:1,transition:!0},"line-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:[{"!":"line-pattern"}]},"line-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"line-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["line-translate"]},"line-width":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-gap-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-offset":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"line-dasharray":{type:"array",value:"number",function:"piecewise-constant","zoom-function":!0,minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}]},"line-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-blur":{type:"number",default:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels"},"circle-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["circle-translate"]},"circle-pitch-scale":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map"},"circle-pitch-alignment":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"circle-stroke-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"circle-stroke-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels"},"heatmap-weight":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!1},"heatmap-intensity":{type:"number",default:1,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],function:"interpolated","zoom-function":!1,"property-function":!1,transition:!1},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!1,transition:!0}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["icon-image"]},"icon-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["icon-image"]},"icon-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"]},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,requires:["text-field"]},"text-halo-width":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-halo-blur":{type:"number",default:0,minimum:0,function:"interpolated","zoom-function":!0,"property-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate":{type:"array",value:"number",length:2,default:[0,0],function:"interpolated","zoom-function":!0,transition:!0,units:"pixels",requires:["text-field"]},"text-translate-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"]}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-hue-rotate":{type:"number",default:0,period:360,function:"interpolated","zoom-function":!0,transition:!0,units:"degrees"},"raster-brightness-min":{type:"number",function:"interpolated","zoom-function":!0,default:0,minimum:0,maximum:1,transition:!0},"raster-brightness-max":{type:"number",function:"interpolated","zoom-function":!0,default:1,minimum:0,maximum:1,transition:!0},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"raster-fade-duration":{type:"number",default:300,minimum:0,function:"interpolated","zoom-function":!0,transition:!1,units:"milliseconds"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,function:"interpolated","zoom-function":!0,transition:!1},"hillshade-illumination-anchor":{type:"enum",function:"piecewise-constant","zoom-function":!0,values:{map:{},viewport:{}},default:"viewport"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0},"hillshade-shadow-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",function:"interpolated","zoom-function":!0,transition:!0},"hillshade-accent-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0}},paint_background:{"background-color":{type:"color",default:"#000000",function:"interpolated","zoom-function":!0,transition:!0,requires:[{"!":"background-pattern"}]},"background-pattern":{type:"string",function:"piecewise-constant","zoom-function":!0,transition:!0},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,function:"interpolated","zoom-function":!0,transition:!0}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}}}},{}],153:[function(t,e,r){var n=t("csscolorparser").parseCSSColor,i=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n};i.parse=function(t){if(t){if(t instanceof i)return t;if("string"==typeof t){var e=n(t);if(e)return new i(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},i.prototype.toString=function(){var t=this;return"rgba("+[this.r,this.g,this.b].map(function(e){return Math.round(255*e/t.a)}).concat(this.a).join(",")+")"},i.black=new i(0,0,0,1),i.white=new i(1,1,1,1),i.transparent=new i(0,0,0,0),e.exports=i},{csscolorparser:13}],154:[function(t,e,r){function n(t){return t>m?Math.pow(t,1/3):t/v+d}function i(t){return t>g?t*t*t:v*(t-d)}function a(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function o(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function s(t){var e=o(t.r),r=o(t.g),i=o(t.b),a=n((.4124564*e+.3575761*r+.1804375*i)/h),s=n((.2126729*e+.7151522*r+.072175*i)/f);return{l:116*s-16,a:500*(a-s),b:200*(s-n((.0193339*e+.119192*r+.9503041*i)/p)),alpha:t.a}}function l(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=f*i(e),r=h*i(r),n=p*i(n),new u(a(3.2404542*r-1.5371385*e-.4985314*n),a(-.969266*r+1.8760108*e+.041556*n),a(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}var u=t("./color"),c=t("./interpolate").number,h=.95047,f=1,p=1.08883,d=4/29,g=6/29,v=3*g*g,m=g*g*g,y=Math.PI/180,x=180/Math.PI;e.exports={lab:{forward:s,reverse:l,interpolate:function(t,e,r){return{l:c(t.l,e.l,r),a:c(t.a,e.a,r),b:c(t.b,e.b,r),alpha:c(t.alpha,e.alpha,r)}}},hcl:{forward:function(t){var e=s(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*x;return{h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*y,r=t.c;return l({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return{h:function(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}(t.h,e.h,r),c:c(t.c,e.c,r),l:c(t.l,e.l,r),alpha:c(t.alpha,e.alpha,r)}}}}},{"./color":153,"./interpolate":158}],155:[function(t,e,r){e.exports=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return!1;for(var n=0;n0;)r[n]=e[n+1];for(var i=0,a=r;i":case">=":r.length>=2&&"$type"===s(r[1])&&c.push(new n(i,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&c.push(new n(i,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(l=o(r[1]))&&c.push(new n(i+"[1]",r[1],"string expected, "+l+" found"));for(var h=2;hu(s[0].zoom))return[new n(c,s[0].zoom,"stop zoom values must appear in ascending order")];u(s[0].zoom)!==f&&(f=u(s[0].zoom),h=void 0,g={}),e=e.concat(o({key:c+"[0]",value:s[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:l,value:r}}))}else e=e.concat(r({key:c+"[0]",value:s[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},s));return e.concat(a({key:c+"[1]",value:s[1],valueSpec:p,style:t.style,styleSpec:t.styleSpec}))}function r(t,e){var r=i(t.value),a=u(t.value),o=null!==t.value?t.value:e;if(c){if(r!==c)return[new n(t.key,o,r+" stop domain type must match previous stop domain type "+c)]}else c=r;if("number"!==r&&"string"!==r&&"boolean"!==r)return[new n(t.key,o,"stop domain value must be a number, string, or boolean")];if("number"!==r&&"categorical"!==d){var s="number expected, "+r+" found";return p["property-function"]&&void 0===d&&(s+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new n(t.key,o,s)]}return"categorical"!==d||"number"!==r||isFinite(a)&&Math.floor(a)===a?"categorical"!==d&&"number"===r&&void 0!==h&&a=8&&(m&&!t.valueSpec["property-function"]?x.push(new n(t.key,t.value,"property functions not supported")):v&&!t.valueSpec["zoom-function"]&&"heatmap-color"!==t.objectKey&&x.push(new n(t.key,t.value,"zoom functions not supported"))),"categorical"!==d&&!y||void 0!==t.value.property||x.push(new n(t.key,t.value,'"property" property is required')),x}},{"../error/validation_error":122,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162,"./validate_array":163,"./validate_number":175,"./validate_object":176}],171:[function(t,e,r){var n=t("../error/validation_error"),i=t("./validate_string");e.exports=function(t){var e=t.value,r=t.key,a=i(t);return a.length?a:(-1===e.indexOf("{fontstack}")&&a.push(new n(r,e,'"glyphs" url must include a "{fontstack}" token')),-1===e.indexOf("{range}")&&a.push(new n(r,e,'"glyphs" url must include a "{range}" token')),a)}},{"../error/validation_error":122,"./validate_string":180}],172:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_filter"),s=t("./validate_paint_property"),l=t("./validate_layout_property"),u=t("./validate"),c=t("../util/extend");e.exports=function(t){var e=[],r=t.value,h=t.key,f=t.style,p=t.styleSpec;r.type||r.ref||e.push(new n(h,r,'either "type" or "ref" is required'));var d,g=i(r.type),v=i(r.ref);if(r.id)for(var m=i(r.id),y=0;ya.maximum?[new i(e,r,r+" is greater than the maximum value "+a.maximum)]:[]}},{"../error/validation_error":122,"../util/get_type":157}],176:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/get_type"),a=t("./validate");e.exports=function(t){var e=t.key,r=t.value,o=t.valueSpec||{},s=t.objectElementValidators||{},l=t.style,u=t.styleSpec,c=[],h=i(r);if("object"!==h)return[new n(e,r,"object expected, "+h+" found")];for(var f in r){var p=f.split(".")[0],d=o[p]||o["*"],g=void 0;if(s[p])g=s[p];else if(o[p])g=a;else if(s["*"])g=s["*"];else{if(!o["*"]){c.push(new n(e,r[f],'unknown property "'+f+'"'));continue}g=a}c=c.concat(g({key:(e?e+".":e)+f,value:r[f],valueSpec:d,style:l,styleSpec:u,object:r,objectKey:f},r))}for(var v in o)s[v]||o[v].required&&void 0===o[v].default&&void 0===r[v]&&c.push(new n(e,r,'missing required property "'+v+'"'));return c}},{"../error/validation_error":122,"../util/get_type":157,"./validate":162}],177:[function(t,e,r){var n=t("./validate_property");e.exports=function(t){return n(t,"paint")}},{"./validate_property":178}],178:[function(t,e,r){var n=t("./validate"),i=t("../error/validation_error"),a=t("../util/get_type"),o=t("../function").isFunction,s=t("../util/unbundle_jsonlint");e.exports=function(t,e){var r=t.key,l=t.style,u=t.styleSpec,c=t.value,h=t.objectKey,f=u[e+"_"+t.layerType];if(!f)return[];var p=h.match(/^(.*)-transition$/);if("paint"===e&&p&&f[p[1]]&&f[p[1]].transition)return n({key:r,value:c,valueSpec:u.transition,style:l,styleSpec:u});var d,g=t.valueSpec||f[h];if(!g)return[new i(r,c,'unknown property "'+h+'"')];if("string"===a(c)&&g["property-function"]&&!g.tokens&&(d=/^{([^}]+)}$/.exec(c)))return[new i(r,c,'"'+h+'" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": '+JSON.stringify(d[1])+" }`.")];var v=[];return"symbol"===t.layerType&&("text-field"===h&&l&&!l.glyphs&&v.push(new i(r,c,'use of "text-field" requires a style "glyphs" property')),"text-font"===h&&o(s.deep(c))&&"identity"===s(c.type)&&v.push(new i(r,c,'"text-font" does not support identity functions'))),v.concat(n({key:t.key,value:c,valueSpec:g,style:l,styleSpec:u,expressionContext:"property",propertyKey:h}))}},{"../error/validation_error":122,"../function":149,"../util/get_type":157,"../util/unbundle_jsonlint":161,"./validate":162}],179:[function(t,e,r){var n=t("../error/validation_error"),i=t("../util/unbundle_jsonlint"),a=t("./validate_object"),o=t("./validate_enum");e.exports=function(t){var e=t.value,r=t.key,s=t.styleSpec,l=t.style;if(!e.type)return[new n(r,e,'"type" is required')];var u=i(e.type),c=[];switch(u){case"vector":case"raster":case"raster-dem":if(c=c.concat(a({key:r,value:e,valueSpec:s["source_"+u.replace("-","_")],style:t.style,styleSpec:s})),"url"in e)for(var h in e)["type","url","tileSize"].indexOf(h)<0&&c.push(new n(r+"."+h,e[h],'a source with a "url" property may not include a "'+h+'" property'));return c;case"geojson":return a({key:r,value:e,valueSpec:s.source_geojson,style:l,styleSpec:s});case"video":return a({key:r,value:e,valueSpec:s.source_video,style:l,styleSpec:s});case"image":return a({key:r,value:e,valueSpec:s.source_image,style:l,styleSpec:s});case"canvas":return a({key:r,value:e,valueSpec:s.source_canvas,style:l,styleSpec:s});default:return o({key:r+".type",value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image","canvas"]},style:l,styleSpec:s})}}},{"../error/validation_error":122,"../util/unbundle_jsonlint":161,"./validate_enum":167,"./validate_object":176}],180:[function(t,e,r){var n=t("../util/get_type"),i=t("../error/validation_error");e.exports=function(t){var e=t.value,r=t.key,a=n(e);return"string"!==a?[new i(r,e,"string expected, "+a+" found")]:[]}},{"../error/validation_error":122,"../util/get_type":157}],181:[function(t,e,r){function n(t,e){e=e||l;var r=[];return r=r.concat(s({key:"",value:t,valueSpec:e.$root,styleSpec:e,style:t,objectElementValidators:{glyphs:u,"*":function(){return[]}}})),t.constants&&(r=r.concat(o({key:"constants",value:t.constants,style:t,styleSpec:e}))),i(r)}function i(t){return[].concat(t).sort(function(t,e){return t.line-e.line})}function a(t){return function(){return i(t.apply(this,arguments))}}var o=t("./validate/validate_constants"),s=t("./validate/validate"),l=t("./reference/latest"),u=t("./validate/validate_glyphs_url");n.source=a(t("./validate/validate_source")),n.light=a(t("./validate/validate_light")),n.layer=a(t("./validate/validate_layer")),n.filter=a(t("./validate/validate_filter")),n.paintProperty=a(t("./validate/validate_paint_property")),n.layoutProperty=a(t("./validate/validate_layout_property")),e.exports=n},{"./reference/latest":151,"./validate/validate":162,"./validate/validate_constants":166,"./validate/validate_filter":169,"./validate/validate_glyphs_url":171,"./validate/validate_layer":172,"./validate/validate_layout_property":173,"./validate/validate_light":174,"./validate/validate_paint_property":177,"./validate/validate_source":179}],182:[function(t,e,r){var n=t("./zoom_history"),i=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new n,this.transition={})};i.prototype.crossFadingFactor=function(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)},e.exports=i},{"./zoom_history":212}],183:[function(t,e,r){var n=t("../style-spec/reference/latest"),i=t("../util/util"),a=t("../util/evented"),o=t("./validate_style"),s=t("../util/util").sphericalToCartesian,l=(t("../style-spec/util/color"),t("../style-spec/util/interpolate")),u=t("./properties"),c=u.Properties,h=u.Transitionable,f=(u.Transitioning,u.PossiblyEvaluated,u.DataConstantProperty),p=function(){this.specification=n.light.position};p.prototype.possiblyEvaluate=function(t,e){return s(t.expression.evaluate(e))},p.prototype.interpolate=function(t,e,r){return{x:l.number(t.x,e.x,r),y:l.number(t.y,e.y,r),z:l.number(t.z,e.z,r)}};var d=new c({anchor:new f(n.light.anchor),position:new p,color:new f(n.light.color),intensity:new f(n.light.intensity)}),g=function(t){function e(e){t.call(this),this._transitionable=new h(d),this.setLight(e),this._transitioning=this._transitionable.untransitioned()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getLight=function(){return this._transitionable.serialize()},e.prototype.setLight=function(t){if(!this._validate(o.light,t))for(var e in t){var r=t[e];i.endsWith(e,"-transition")?this._transitionable.setTransition(e.slice(0,-"-transition".length),r):this._transitionable.setValue(e,r)}},e.prototype.updateTransitions=function(t){this._transitioning=this._transitionable.transitioned(t,this._transitioning)},e.prototype.hasTransition=function(){return this._transitioning.hasTransition()},e.prototype.recalculate=function(t){this.properties=this._transitioning.possiblyEvaluate(t)},e.prototype._validate=function(t,e){return o.emitErrors(this,t.call(o,i.extend({value:e,style:{glyphs:!0,sprite:!0},styleSpec:n})))},e}(a);e.exports=g},{"../style-spec/reference/latest":151,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/evented":260,"../util/util":275,"./properties":188,"./validate_style":211}],184:[function(t,e,r){var n=t("../util/mapbox").normalizeGlyphsURL,i=t("../util/ajax"),a=t("./parse_glyph_pbf");e.exports=function(t,e,r,o,s){var l=256*e,u=l+255,c=o(n(r).replace("{fontstack}",t).replace("{range}",l+"-"+u),i.ResourceType.Glyphs);i.getArrayBuffer(c,function(t,e){if(t)s(t);else if(e){for(var r={},n=0,i=a(e.data);n1?"@2x":"";n.getJSON(e(a(t,h,".json"),n.ResourceType.SpriteJSON),function(t,e){c||(c=t,l=e,s())}),n.getImage(e(a(t,h,".png"),n.ResourceType.SpriteImage),function(t,e){c||(c=t,u=e,s())})}},{"../util/ajax":251,"../util/browser":252,"../util/image":263,"../util/mapbox":267}],186:[function(t,e,r){function n(t,e,r){1===t&&r.readMessage(i,e)}function i(t,e,r){if(3===t){var n=r.readMessage(a,{}),i=n.id,s=n.bitmap,u=n.width,c=n.height,h=n.left,f=n.top,p=n.advance;e.push({id:i,bitmap:new o({width:u+2*l,height:c+2*l},s),metrics:{width:u,height:c,left:h,top:f,advance:p}})}}function a(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint())}var o=t("../util/image").AlphaImage,s=t("pbf"),l=3;e.exports=function(t){return new s(t).readFields(n,[])},e.exports.GLYPH_PBF_BORDER=l},{"../util/image":263,pbf:30}],187:[function(t,e,r){var n=t("../util/browser"),i=t("../symbol/placement"),a=function(){this._currentTileIndex=0,this._seenCrossTileIDs={}};a.prototype.continuePlacement=function(t,e,r,n,i){for(var a=this;this._currentTileIndex2};this._currentPlacementIndex>=0;){var l=e[t[i._currentPlacementIndex]],u=i.placement.collisionIndex.transform.zoom;if("symbol"===l.type&&(!l.minzoom||l.minzoom<=u)&&(!l.maxzoom||l.maxzoom>u)){if(i._inProgressLayer||(i._inProgressLayer=new a),i._inProgressLayer.continuePlacement(r[l.source],i.placement,i._showCollisionBoxes,l,s))return;delete i._inProgressLayer}i._currentPlacementIndex--}this._done=!0},o.prototype.commit=function(t,e){return this.placement.commit(t,e),this.placement},e.exports=o},{"../symbol/placement":223,"../util/browser":252}],188:[function(t,e,r){var n=t("../util/util"),i=n.clone,a=n.extend,o=n.easeCubicInOut,s=t("../style-spec/util/interpolate"),l=t("../style-spec/expression").normalizePropertyExpression,u=(t("../style-spec/util/color"),t("../util/web_worker_transfer").register),c=function(t,e){this.property=t,this.value=e,this.expression=l(void 0===e?t.specification.default:e,t.specification)};c.prototype.isDataDriven=function(){return"source"===this.expression.kind||"composite"===this.expression.kind},c.prototype.possiblyEvaluate=function(t){return this.property.possiblyEvaluate(this,t)};var h=function(t){this.property=t,this.value=new c(t,void 0)};h.prototype.transitioned=function(t,e){return new p(this.property,this.value,e,a({},t.transition,this.transition),t.now)},h.prototype.untransitioned=function(){return new p(this.property,this.value,null,{},0)};var f=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues)};f.prototype.getValue=function(t){return i(this._values[t].value.value)},f.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new h(this._values[t].property)),this._values[t].value=new c(this._values[t].property,null===e?void 0:i(e))},f.prototype.getTransition=function(t){return i(this._values[t].transition)},f.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new h(this._values[t].property)),this._values[t].transition=i(e)||void 0},f.prototype.serialize=function(){for(var t=this,e={},r=0,n=Object.keys(t._values);rthis.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(en.zoomHistory.lastIntegerZoom?{from:t,to:e,fromScale:2,toScale:1,t:a+(1-a)*o}:{from:r,to:e,fromScale:.5,toScale:1,t:1-(1-o)*a}},b.prototype.interpolate=function(t){return t};var _=function(t){this.specification=t};_.prototype.possiblyEvaluate=function(){},_.prototype.interpolate=function(){};u("DataDrivenProperty",x),u("DataConstantProperty",y),u("CrossFadedProperty",b),u("HeatmapColorProperty",_),e.exports={PropertyValue:c,Transitionable:f,Transitioning:d,Layout:g,PossiblyEvaluatedPropertyValue:v,PossiblyEvaluated:m,DataConstantProperty:y,DataDrivenProperty:x,CrossFadedProperty:b,HeatmapColorProperty:_,Properties:function(t){var e=this;for(var r in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},t){var n=t[r],i=e.defaultPropertyValues[r]=new c(n,void 0),a=e.defaultTransitionablePropertyValues[r]=new h(n);e.defaultTransitioningPropertyValues[r]=a.untransitioned(),e.defaultPossiblyEvaluatedValues[r]=i.possiblyEvaluate({})}}}},{"../style-spec/expression":139,"../style-spec/util/color":153,"../style-spec/util/interpolate":158,"../util/util":275,"../util/web_worker_transfer":278}],189:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports={getMaximumPaintValue:function(t,e,r){var n=e.paint.get(t).value;return"constant"===n.kind?n.value:r.programConfigurations.get(e.id).binders[t].statistics.max},translateDistance:function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},translate:function(t,e,r,i,a){if(!e[0]&&!e[1])return t;var o=n.convert(e);"viewport"===r&&o._rotate(-i);for(var s=[],l=0;l0)throw new Error("Unimplemented: "+n.map(function(t){return t.command}).join(", ")+".");return r.forEach(function(t){"setTransition"!==t.command&&e[t.command].apply(e,t.args)}),this.stylesheet=t,!0},e.prototype.addImage=function(t,e){if(this.getImage(t))return this.fire("error",{error:new Error("An image with this name already exists.")});this.imageManager.addImage(t,e),this.fire("data",{dataType:"style"})},e.prototype.getImage=function(t){return this.imageManager.getImage(t)},e.prototype.removeImage=function(t){if(!this.getImage(t))return this.fire("error",{error:new Error("No image with this name exists.")});this.imageManager.removeImage(t),this.fire("data",{dataType:"style"})},e.prototype.addSource=function(t,e,r){var n=this;if(this._checkLoaded(),void 0!==this.sourceCaches[t])throw new Error("There is already a source with this ID");if(!e.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(e).join(", ")+".");if(!(["vector","raster","geojson","video","image","canvas"].indexOf(e.type)>=0&&this._validate(g.source,"sources."+t,e,null,r))){this.map&&this.map._collectResourceTiming&&(e.collectResourceTiming=!0);var i=this.sourceCaches[t]=new x(t,e,this.dispatcher);i.style=this,i.setEventedParent(this,function(){return{isSourceLoaded:n.loaded(),source:i.serialize(),sourceId:t}}),i.onAdd(this.map),this._changed=!0}},e.prototype.removeSource=function(t){var e=this;if(this._checkLoaded(),void 0===this.sourceCaches[t])throw new Error("There is no source with this ID");for(var r in e._layers)if(e._layers[r].source===t)return e.fire("error",{error:new Error('Source "'+t+'" cannot be removed while layer "'+r+'" is using it.')});var n=this.sourceCaches[t];delete this.sourceCaches[t],delete this._updatedSources[t],n.fire("data",{sourceDataType:"metadata",dataType:"source",sourceId:t}),n.setEventedParent(null),n.clearTiles(),n.onRemove&&n.onRemove(this.map),this._changed=!0},e.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0},e.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},e.prototype.addLayer=function(t,e,r){this._checkLoaded();var n=t.id;if("object"==typeof t.source&&(this.addSource(n,t.source),t=c.clone(t),t=c.extend(t,{source:n})),!this._validate(g.layer,"layers."+n,t,{arrayIndex:-1},r)){var a=i.create(t);this._validateLayer(a),a.setEventedParent(this,{layer:{id:n}});var o=e?this._order.indexOf(e):this._order.length;if(e&&-1===o)return void this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')});if(this._order.splice(o,0,n),this._layerOrderChanged=!0,this._layers[n]=a,this._removedLayers[n]&&a.source){var s=this._removedLayers[n];delete this._removedLayers[n],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause())}this._updateLayer(a)}},e.prototype.moveLayer=function(t,e){if(this._checkLoaded(),this._changed=!0,this._layers[t]){var r=this._order.indexOf(t);this._order.splice(r,1);var n=e?this._order.indexOf(e):this._order.length;e&&-1===n?this.fire("error",{error:new Error('Layer with id "'+e+'" does not exist on this map.')}):(this._order.splice(n,0,t),this._layerOrderChanged=!0)}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be moved.")})},e.prototype.removeLayer=function(t){this._checkLoaded();var e=this._layers[t];if(e){e.setEventedParent(null);var r=this._order.indexOf(t);this._order.splice(r,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[t]=e,delete this._layers[t],delete this._updatedLayers[t],delete this._updatedPaintProps[t]}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be removed.")})},e.prototype.getLayer=function(t){return this._layers[t]},e.prototype.setLayerZoomRange=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?n.minzoom===e&&n.maxzoom===r||(null!=e&&(n.minzoom=e),null!=r&&(n.maxzoom=r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot have zoom extent.")})},e.prototype.setFilter=function(t,e){this._checkLoaded();var r=this.getLayer(t);if(r)return c.deepEqual(r.filter,e)?void 0:null===e||void 0===e?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(g.filter,"layers."+r.id+".filter",e)||(r.filter=c.clone(e),this._updateLayer(r)));this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be filtered.")})},e.prototype.getFilter=function(t){return c.clone(this.getLayer(t).filter)},e.prototype.setLayoutProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);n?c.deepEqual(n.getLayoutProperty(e),r)||(n.setLayoutProperty(e,r),this._updateLayer(n)):this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getLayoutProperty=function(t,e){return this.getLayer(t).getLayoutProperty(e)},e.prototype.setPaintProperty=function(t,e,r){this._checkLoaded();var n=this.getLayer(t);if(n){if(!c.deepEqual(n.getPaintProperty(e),r)){var i=n._transitionablePaint._values[e].value.isDataDriven();n.setPaintProperty(e,r),(n._transitionablePaint._values[e].value.isDataDriven()||i)&&this._updateLayer(n),this._changed=!0,this._updatedPaintProps[t]=!0}}else this.fire("error",{error:new Error("The layer '"+t+"' does not exist in the map's style and cannot be styled.")})},e.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},e.prototype.getTransition=function(){return c.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},e.prototype.serialize=function(){var t=this;return c.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:c.mapObject(this.sourceCaches,function(t){return t.serialize()}),layers:this._order.map(function(e){return t._layers[e].serialize()})},function(t){return void 0!==t})},e.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0},e.prototype._flattenRenderedFeatures=function(t){for(var e=[],r=this._order.length-1;r>=0;r--)for(var n=this._order[r],i=0,a=t;i=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint)},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t)),this.paint=this._transitioningPaint.possiblyEvaluate(t)},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return"none"===this.visibility&&(t.layout=t.layout||{},t.layout.visibility="none"),n.filterObject(t,function(t,e){return!(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)})},e.prototype._validate=function(t,e,r,n,o){return(!o||!1!==o.validate)&&a.emitErrors(this,t.call(a,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:i,style:{glyphs:!0,sprite:!0}}))},e.prototype.hasOffscreenPass=function(){return!1},e.prototype.resize=function(){},e}(o));e.exports=c;var h={circle:t("./style_layer/circle_style_layer"),heatmap:t("./style_layer/heatmap_style_layer"),hillshade:t("./style_layer/hillshade_style_layer"),fill:t("./style_layer/fill_style_layer"),"fill-extrusion":t("./style_layer/fill_extrusion_style_layer"),line:t("./style_layer/line_style_layer"),symbol:t("./style_layer/symbol_style_layer"),background:t("./style_layer/background_style_layer"),raster:t("./style_layer/raster_style_layer")};c.create=function(t){return new h[t.type](t)}},{"../style-spec/reference/latest":151,"../util/evented":260,"../util/util":275,"./properties":188,"./style_layer/background_style_layer":192,"./style_layer/circle_style_layer":194,"./style_layer/fill_extrusion_style_layer":196,"./style_layer/fill_style_layer":198,"./style_layer/heatmap_style_layer":200,"./style_layer/hillshade_style_layer":202,"./style_layer/line_style_layer":204,"./style_layer/raster_style_layer":206,"./style_layer/symbol_style_layer":208,"./validate_style":211}],192:[function(t,e,r){var n=t("../style_layer"),i=t("./background_style_layer_properties"),a=t("../properties"),o=(a.Transitionable,a.Transitioning,a.PossiblyEvaluated,function(t){function e(e){t.call(this,e,i)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(n));e.exports=o},{"../properties":188,"../style_layer":191,"./background_style_layer_properties":193}],193:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=(i.DataDrivenProperty,i.CrossFadedProperty),l=(i.HeatmapColorProperty,new a({"background-color":new o(n.paint_background["background-color"]),"background-pattern":new s(n.paint_background["background-pattern"]),"background-opacity":new o(n.paint_background["background-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],194:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/circle_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiPoint,o=t("../query_utils"),s=o.getMaximumPaintValue,l=o.translateDistance,u=o.translate,c=t("./circle_style_layer_properties"),h=t("../properties"),f=(h.Transitionable,h.Transitioning,h.PossiblyEvaluated,function(t){function e(e){t.call(this,e,c)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(t){var e=t;return s("circle-radius",this,e)+s("circle-stroke-width",this,e)+l(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=u(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),i,o),l=this.paint.get("circle-radius").evaluate(e)*o,c=this.paint.get("circle-stroke-width").evaluate(e)*o;return a(s,r,l+c)},e}(n));e.exports=f},{"../../data/bucket/circle_bucket":42,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./circle_style_layer_properties":195}],195:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=(i.CrossFadedProperty,i.HeatmapColorProperty,new a({"circle-radius":new s(n.paint_circle["circle-radius"]),"circle-color":new s(n.paint_circle["circle-color"]),"circle-blur":new s(n.paint_circle["circle-blur"]),"circle-opacity":new s(n.paint_circle["circle-opacity"]),"circle-translate":new o(n.paint_circle["circle-translate"]),"circle-translate-anchor":new o(n.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new o(n.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new o(n.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new s(n.paint_circle["circle-stroke-width"]),"circle-stroke-color":new s(n.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new s(n.paint_circle["circle-stroke-opacity"])}));e.exports={paint:l}},{"../../style-spec/reference/latest":151,"../properties":188}],196:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_extrusion_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,o=t("../query_utils"),s=o.translateDistance,l=o.translate,u=t("./fill_extrusion_style_layer_properties"),c=t("../properties"),h=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-extrusion-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=l(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),i,o);return a(s,r)},e.prototype.hasOffscreenPass=function(){return 0!==this.paint.get("fill-extrusion-opacity")&&"none"!==this.visibility},e.prototype.resize=function(){this.viewportFrame&&(this.viewportFrame.destroy(),this.viewportFrame=null)},e}(n));e.exports=h},{"../../data/bucket/fill_extrusion_bucket":46,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_extrusion_style_layer_properties":197}],197:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new a({"fill-extrusion-opacity":new o(n["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new s(n["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new o(n["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new o(n["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new l(n["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new s(n["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new s(n["paint_fill-extrusion"]["fill-extrusion-base"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],198:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/fill_bucket"),a=t("../../util/intersection_tests").multiPolygonIntersectsMultiPolygon,o=t("../query_utils"),s=o.translateDistance,l=o.translate,u=t("./fill_style_layer_properties"),c=t("../properties"),h=(c.Transitionable,c.Transitioning,c.PossiblyEvaluated,function(t){function e(e){t.call(this,e,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(t){this.paint=this._transitioningPaint.possiblyEvaluate(t),void 0===this._transitionablePaint.getValue("fill-outline-color")&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])},e.prototype.createBucket=function(t){return new i(t)},e.prototype.queryRadius=function(){return s(this.paint.get("fill-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,o){var s=l(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),i,o);return a(s,r)},e}(n));e.exports=h},{"../../data/bucket/fill_bucket":44,"../../util/intersection_tests":264,"../properties":188,"../query_utils":189,"../style_layer":191,"./fill_style_layer_properties":199}],199:[function(t,e,r){var n=t("../../style-spec/reference/latest"),i=t("../properties"),a=i.Properties,o=i.DataConstantProperty,s=i.DataDrivenProperty,l=i.CrossFadedProperty,u=(i.HeatmapColorProperty,new a({"fill-antialias":new o(n.paint_fill["fill-antialias"]),"fill-opacity":new s(n.paint_fill["fill-opacity"]),"fill-color":new s(n.paint_fill["fill-color"]),"fill-outline-color":new s(n.paint_fill["fill-outline-color"]),"fill-translate":new o(n.paint_fill["fill-translate"]),"fill-translate-anchor":new o(n.paint_fill["fill-translate-anchor"]),"fill-pattern":new l(n.paint_fill["fill-pattern"])}));e.exports={paint:u}},{"../../style-spec/reference/latest":151,"../properties":188}],200:[function(t,e,r){var n=t("../style_layer"),i=t("../../data/bucket/heatmap_bucket"),a=t("../../util/image").RGBAImage,o=t("./heatmap_style_layer_properties"),s=t("../properties"),l=(s.Transitionable,s.Transitioning,s.PossiblyEvaluated,function(t){function e(e){t.call(this,e,o),this._updateColorRamp()}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.createBucket=function(t){return new i(t)},e.prototype.setPaintProperty=function(e,r,n){t.prototype.setPaintProperty.call(this,e,r,n),"heatmap-color"===e&&this._updateColorRamp()},e.prototype._updateColorRamp=function(){for(var t=this._transitionablePaint._values["heatmap-color"].value.expression,e=new Uint8Array(1024),r=e.length,n=4;n0?e+2*t:t}var i=t("@mapbox/point-geometry"),a=t("../style_layer"),o=t("../../data/bucket/line_bucket"),s=t("../../util/intersection_tests").multiPolygonIntersectsBufferedMultiLine,l=t("../query_utils"),u=l.getMaximumPaintValue,c=l.translateDistance,h=l.translate,f=t("./line_style_layer_properties"),p=t("../../util/util").extend,d=t("../evaluation_parameters"),g=t("../properties"),v=(g.Transitionable,g.Transitioning,g.Layout,g.PossiblyEvaluated,new(function(t){function e(){t.apply(this,arguments)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new d(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n)},e}(g.DataDrivenProperty))(f.paint.properties["line-width"].specification));v.useIntegerZoom=!0;var m=function(t){function e(e){t.call(this,e,f)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.recalculate=function(e){t.prototype.recalculate.call(this,e),this.paint._values["line-floorwidth"]=v.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e)},e.prototype.createBucket=function(t){return new o(t)},e.prototype.queryRadius=function(t){var e=t,r=n(u("line-width",this,e),u("line-gap-width",this,e)),i=u("line-offset",this,e);return r/2+Math.abs(i)+c(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,a,o,l){var u=h(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o,l),c=l/2*n(this.paint.get("line-width").evaluate(e),this.paint.get("line-gap-width").evaluate(e)),f=this.paint.get("line-offset").evaluate(e);return f&&(r=function(t,e){for(var r=[],n=new i(0,0),a=0;ar?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom-r/2;){if(--o<0)return!1;s-=t[o].dist(a),a=t[o]}s+=t[o].dist(t[o+1]),o++;for(var l=[],u=0;sn;)u-=l.shift().angleDelta;if(u>i)return!1;o++,s+=h.dist(f)}return!0}},{}],215:[function(t,e,r){var n=t("@mapbox/point-geometry");e.exports=function(t,e,r,i,a){for(var o=[],s=0;s=i&&f.x>=i||(h.x>=i?h=new n(i,h.y+(f.y-h.y)*((i-h.x)/(f.x-h.x)))._round():f.x>=i&&(f=new n(i,h.y+(f.y-h.y)*((i-h.x)/(f.x-h.x)))._round()),h.y>=a&&f.y>=a||(h.y>=a?h=new n(h.x+(f.x-h.x)*((a-h.y)/(f.y-h.y)),a)._round():f.y>=a&&(f=new n(h.x+(f.x-h.x)*((a-h.y)/(f.y-h.y)),a)._round()),u&&h.equals(u[u.length-1])||(u=[h],o.push(u)),u.push(f)))))}return o}},{"@mapbox/point-geometry":4}],216:[function(t,e,r){var n=function(t,e,r,n,i,a,o,s,l,u,c){var h=o.top*s-l,f=o.bottom*s+l,p=o.left*s-l,d=o.right*s+l;if(this.boxStartIndex=t.length,u){var g=f-h,v=d-p;g>0&&(g=Math.max(10*s,g),this._addLineCollisionCircles(t,e,r,r.segment,v,g,n,i,a,c))}else t.emplaceBack(r.x,r.y,p,h,d,f,n,i,a,0,0);this.boxEndIndex=t.length};n.prototype._addLineCollisionCircles=function(t,e,r,n,i,a,o,s,l,u){var c=a/2,h=Math.floor(i/c),f=1+.4*Math.log(u)/Math.LN2,p=Math.floor(h*f/2),d=-a/2,g=r,v=n+1,m=d,y=-i/2,x=y-i/4;do{if(--v<0){if(m>y)return;v=0;break}m-=e[v].dist(g),g=e[v]}while(m>x);for(var b=e[v].dist(e[v+1]),_=-p;_i&&(k+=w-i),!(k=e.length)return;b=e[v].dist(e[v+1])}var M=k-m,A=e[v],T=e[v+1].sub(A)._unit()._mult(M)._add(A)._round(),S=Math.abs(k-d)L)n(t,P,!1);else{var R=v.projectPoint(f,z,D),B=I*S;if(m.length>0){var F=R.x-m[m.length-4],N=R.y-m[m.length-3];if(B*B*2>F*F+N*N&&P+8-E&&j=this.screenRightBoundary||n<100||e>this.screenBottomBoundary},e.exports=l},{"../symbol/projection":224,"../util/intersection_tests":264,"./grid_index":220,"@mapbox/gl-matrix":2,"@mapbox/point-geometry":4}],218:[function(t,e,r){var n=t("../data/extent"),i=512/n/2,a=function(t,e,r){var n=this;this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=r;for(var i=0,a=e;it.overscaledZ)for(var u in l){var c=l[u];c.tileID.isChildOf(t)&&c.findMatches(e.symbolInstances,t,o)}else{var h=l[t.scaledTo(Number(s)).key];h&&h.findMatches(e.symbolInstances,t,o)}}for(var f=0,p=e.symbolInstances;f=0&&A=0&&T=0&&m+p<=d){var S=new i(A,T,k,x);S._round(),s&&!a(e,S,u,s,l)||y.push(S)}}v+=w}return h||y.length||c||(y=t(e,v/2,o,s,l,u,c,!0,f)),y}(t,d?e/2*c%e:(p/2+2*l)*u*c%e,e,f,r,p*u,d,!1,h)}},{"../style-spec/util/interpolate":158,"../symbol/anchor":213,"./check_max_angle":214}],220:[function(t,e,r){var n=function(t,e,r){var n=this.boxCells=[],i=this.circleCells=[];this.xCellCount=Math.ceil(t/r),this.yCellCount=Math.ceil(e/r);for(var a=0;athis.width||n<0||e>this.height)return!i&&[];var a=[];if(t<=0&&e<=0&&this.width<=r&&this.height<=n)a=Array.prototype.slice.call(this.boxKeys).concat(this.circleKeys);else{var o={hitTest:i,seenUids:{box:{},circle:{}}};this._forEachCell(t,e,r,n,this._queryCell,a,o)}return i?a.length>0:a},n.prototype._queryCircle=function(t,e,r,n){var i=t-r,a=t+r,o=e-r,s=e+r;if(a<0||i>this.width||s<0||o>this.height)return!n&&[];var l=[],u={hitTest:n,circle:{x:t,y:e,radius:r},seenUids:{box:{},circle:{}}};return this._forEachCell(i,o,a,s,this._queryCellCircle,l,u),n?l.length>0:l},n.prototype.query=function(t,e,r,n){return this._query(t,e,r,n,!1)},n.prototype.hitTest=function(t,e,r,n){return this._query(t,e,r,n,!0)},n.prototype.hitTestCircle=function(t,e,r){return this._queryCircle(t,e,r,!0)},n.prototype._queryCell=function(t,e,r,n,i,a,o){var s=this,l=o.seenUids,u=this.boxCells[i];if(null!==u)for(var c=this.bboxes,h=0,f=u;h=c[d+0]&&n>=c[d+1]){if(o.hitTest)return a.push(!0),!0;a.push(s.boxKeys[p])}}}var g=this.circleCells[i];if(null!==g)for(var v=this.circles,m=0,y=g;mo*o+s*s},n.prototype._circleAndRectCollide=function(t,e,r,n,i,a,o){var s=(a-n)/2,l=Math.abs(t-(n+s));if(l>s+r)return!1;var u=(o-i)/2,c=Math.abs(e-(i+u));if(c>u+r)return!1;if(l<=s||c<=u)return!0;var h=l-s,f=c-u;return h*h+f*f<=r*r},e.exports=n},{}],221:[function(t,e,r){e.exports=function(t){function e(e){s.push(t[e]),l++}function r(t,e,r){var n=o[t];return delete o[t],o[e]=n,s[n].geometry[0].pop(),s[n].geometry[0]=s[n].geometry[0].concat(r[0]),n}function n(t,e,r){var n=a[e];return delete a[e],a[t]=n,s[n].geometry[0].shift(),s[n].geometry[0]=r[0].concat(s[n].geometry[0]),n}function i(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var a={},o={},s=[],l=0,u=0;u0,M=M&&A.offscreen);var C=_.collisionArrays.textCircles;if(C){var E=t.text.placedSymbolArray.get(_.placedTextSymbolIndices[0]),L=s.evaluateSizeForFeature(t.textSizeData,v,E);T=d.collisionIndex.placeCollisionCircles(C,g.get("text-allow-overlap"),i,a,_.key,E,t.lineVertexArray,t.glyphOffsetArray,L,e,r,o,"map"===g.get("text-pitch-alignment")),w=g.get("text-allow-overlap")||T.circles.length>0,M=M&&T.offscreen}_.collisionArrays.iconBox&&(k=(S=d.collisionIndex.placeCollisionBox(_.collisionArrays.iconBox,g.get("icon-allow-overlap"),a,e)).box.length>0,M=M&&S.offscreen),m||y?y?m||(k=k&&w):w=k&&w:k=w=k&&w,w&&A&&d.collisionIndex.insertCollisionBox(A.box,g.get("text-ignore-placement"),h,f,t.bucketInstanceId,_.textBoxStartIndex),k&&S&&d.collisionIndex.insertCollisionBox(S.box,g.get("icon-ignore-placement"),h,f,t.bucketInstanceId,_.iconBoxStartIndex),w&&T&&d.collisionIndex.insertCollisionCircles(T.circles,g.get("text-ignore-placement"),h,f,t.bucketInstanceId,_.textBoxStartIndex),d.placements[_.crossTileID]=new p(w,k,M||t.justReloaded),l[_.crossTileID]=!0}}t.justReloaded=!1},d.prototype.commit=function(t,e){var r=this;this.commitTime=e;var n=!1,i=t&&0!==this.fadeDuration?(this.commitTime-t.commitTime)/this.fadeDuration:1,a=t?t.opacities:{};for(var o in r.placements){var s=r.placements[o],l=a[o];l?(r.opacities[o]=new f(l,i,s.text,s.icon),n=n||s.text!==l.text.placed||s.icon!==l.icon.placed):(r.opacities[o]=new f(null,i,s.text,s.icon,s.skipFade),n=n||s.text||s.icon)}for(var u in a){var c=a[u];if(!r.opacities[u]){var h=new f(c,i,!1,!1);h.isHidden()||(r.opacities[u]=h,n=n||c.text.placed||c.icon.placed)}}n?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e)},d.prototype.updateLayerOpacities=function(t,e){for(var r={},n=0,i=e;n0||l.numVerticalGlyphVertices>0,p=l.numIconVertices>0;if(h){for(var d=i(c.text),g=(l.numGlyphVertices+l.numVerticalGlyphVertices)/4,v=0;vt},d.prototype.setStale=function(){this.stale=!0};var g=Math.pow(2,25),v=Math.pow(2,24),m=Math.pow(2,17),y=Math.pow(2,16),x=Math.pow(2,9),b=Math.pow(2,8),_=Math.pow(2,1);e.exports=d},{"../data/extent":53,"../source/pixels_to_tile_units":104,"../style/style_layer/symbol_style_layer_properties":209,"./collision_index":217,"./projection":224,"./symbol_size":228}],224:[function(t,e,r){function n(t,e){var r=[t.x,t.y,0,1];h(r,r,e);var n=r[3];return{point:new f(r[0]/n,r[1]/n),signedDistanceFromCamera:n}}function i(t,e){var r=t[0]/t[3],n=t[1]/t[3];return r>=-e[0]&&r<=e[0]&&n>=-e[1]&&n<=e[1]}function a(t,e,r,n,i,a,o,s,l,c,h,f){var p=s.glyphStartIndex+s.numGlyphs,d=s.lineStartIndex,g=s.lineStartIndex+s.lineLength,v=e.getoffsetX(s.glyphStartIndex),m=e.getoffsetX(p-1),y=u(t*v,r,n,i,a,o,s.segment,d,g,l,c,h,f);if(!y)return null;var x=u(t*m,r,n,i,a,o,s.segment,d,g,l,c,h,f);return x?{first:y,last:x}:null}function o(t,e,r,n){return t===x.horizontal&&Math.abs(r.y-e.y)>Math.abs(r.x-e.x)*n?{useVertical:!0}:(t===x.vertical?e.yr.x)?{needsFlipping:!0}:null}function s(t,e,r,i,s,c,h,p,d,g,v,y,x,b){var _,w=e/24,k=t.lineOffsetX*e,M=t.lineOffsetY*e;if(t.numGlyphs>1){var A=t.glyphStartIndex+t.numGlyphs,T=t.lineStartIndex,S=t.lineStartIndex+t.lineLength,C=a(w,p,k,M,r,v,y,t,d,c,x,!1);if(!C)return{notEnoughRoom:!0};var E=n(C.first.point,h).point,L=n(C.last.point,h).point;if(i&&!r){var P=o(t.writingMode,E,L,b);if(P)return P}_=[C.first];for(var z=t.glyphStartIndex+1;z0?R.point:l(y,O,D,1,s),F=o(t.writingMode,D,B,b);if(F)return F}var N=u(w*p.getoffsetX(t.glyphStartIndex),k,M,r,v,y,t.segment,t.lineStartIndex,t.lineStartIndex+t.lineLength,d,c,x,!1);if(!N)return{notEnoughRoom:!0};_=[N]}for(var j=0,V=_;j0?1:-1,y=0;i&&(m*=-1,y=Math.PI),m<0&&(y+=Math.PI);for(var x=m>0?u+s:u+s+1,b=x,_=a,w=a,k=0,M=0,A=Math.abs(v);k+M<=A;){if((x+=m)=c)return null;if(w=_,void 0===(_=d[x])){var T=new f(h.getx(x),h.gety(x)),S=n(T,p);if(S.signedDistanceFromCamera>0)_=d[x]=S.point;else{var C=x-m;_=l(0===k?o:new f(h.getx(C),h.gety(C)),T,w,A-k+1,p)}}k+=M,M=w.dist(_)}var E=(A-k)/M,L=_.sub(w),P=L.mult(E)._add(w);return P._add(L._unit()._perp()._mult(r*m)),{point:P,angle:y+Math.atan2(_.y-w.y,_.x-w.x),tileDistance:g?{prevTileDistance:x-m===b?0:h.gettileUnitDistanceFromAnchor(x-m),lastSegmentViewportDistance:A-k}:null}}function c(t,e){for(var r=0;r=w||o.y<0||o.y>=w||t.symbolInstances.push(function(t,e,r,n,a,o,s,l,c,h,f,d,g,x,b,_,w,M,A,T,S,C){var E,L,P=t.addToLineVertexArray(e,r),z=0,D=0,I=0,O=n.horizontal?n.horizontal.text:"",R=[];n.horizontal&&(E=new m(s,r,e,l,c,h,n.horizontal,f,d,g,t.overscaling),D+=i(t,e,n.horizontal,o,g,A,T,x,P,n.vertical?p.horizontal:p.horizontalOnly,R,S,C),n.vertical&&(I+=i(t,e,n.vertical,o,g,A,T,x,P,p.vertical,R,S,C)));var B=E?E.boxStartIndex:t.collisionBoxArray.length,F=E?E.boxEndIndex:t.collisionBoxArray.length;if(a){var N=v(e,a,o,w,n.horizontal,A,T);L=new m(s,r,e,l,c,h,a,b,_,!1,t.overscaling),z=4*N.length;var j=t.iconSizeData,V=null;"source"===j.functionType?V=[10*o.layout.get("icon-size").evaluate(T)]:"composite"===j.functionType&&(V=[10*C.compositeIconSizes[0].evaluate(T),10*C.compositeIconSizes[1].evaluate(T)]),t.addSymbols(t.icon,N,V,M,w,T,!1,e,P.lineStartIndex,P.lineLength)}var U=L?L.boxStartIndex:t.collisionBoxArray.length,q=L?L.boxEndIndex:t.collisionBoxArray.length;return t.glyphOffsetArray.length>=k.MAX_GLYPHS&&y.warnOnce("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),{key:O,textBoxStartIndex:B,textBoxEndIndex:F,iconBoxStartIndex:U,iconBoxEndIndex:q,textOffset:x,iconOffset:M,anchor:e,line:r,featureIndex:l,feature:T,numGlyphVertices:D,numVerticalGlyphVertices:I,numIconVertices:z,textOpacityState:new u,iconOpacityState:new u,isDuplicate:!1,placedTextSymbolIndices:R,crossTileID:0}}(t,o,a,r,n,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,S,P,I,M,E,z,O,A,{zoom:t.zoom},e,c,h))};if("line"===x.get("symbol-placement"))for(var F=0,N=l(e.geometry,0,0,w,w);F=0;o--)if(n.dist(a[o])1||(f?(clearTimeout(f),f=null,o("dblclick",e)):f=setTimeout(r,300))},!1),l.addEventListener("touchend",function(t){s("touchend",t)},!1),l.addEventListener("touchmove",function(t){s("touchmove",t)},!1),l.addEventListener("touchcancel",function(t){s("touchcancel",t)},!1),l.addEventListener("click",function(t){n.mousePos(l,t).equals(h)&&o("click",t)},!1),l.addEventListener("dblclick",function(t){o("dblclick",t),t.preventDefault()},!1),l.addEventListener("contextmenu",function(e){var r=t.dragRotate&&t.dragRotate.isActive();c||r?c&&(u=e):o("contextmenu",e),e.preventDefault()},!1)}},{"../util/dom":259,"./handler/box_zoom":239,"./handler/dblclick_zoom":240,"./handler/drag_pan":241,"./handler/drag_rotate":242,"./handler/keyboard":243,"./handler/scroll_zoom":244,"./handler/touch_zoom_rotate":245,"@mapbox/point-geometry":4}],231:[function(t,e,r){var n=t("../util/util"),i=t("../style-spec/util/interpolate").number,a=t("../util/browser"),o=t("../geo/lng_lat"),s=t("../geo/lng_lat_bounds"),l=t("@mapbox/point-geometry"),u=function(t){function e(e,r){t.call(this),this.moving=!1,this.transform=e,this._bearingSnap=r.bearingSnap}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.getCenter=function(){return this.transform.center},e.prototype.setCenter=function(t,e){return this.jumpTo({center:t},e)},e.prototype.panBy=function(t,e,r){return t=l.convert(t).mult(-1),this.panTo(this.transform.center,n.extend({offset:t},e),r)},e.prototype.panTo=function(t,e,r){return this.easeTo(n.extend({center:t},e),r)},e.prototype.getZoom=function(){return this.transform.zoom},e.prototype.setZoom=function(t,e){return this.jumpTo({zoom:t},e),this},e.prototype.zoomTo=function(t,e,r){return this.easeTo(n.extend({zoom:t},e),r)},e.prototype.zoomIn=function(t,e){return this.zoomTo(this.getZoom()+1,t,e),this},e.prototype.zoomOut=function(t,e){return this.zoomTo(this.getZoom()-1,t,e),this},e.prototype.getBearing=function(){return this.transform.bearing},e.prototype.setBearing=function(t,e){return this.jumpTo({bearing:t},e),this},e.prototype.rotateTo=function(t,e,r){return this.easeTo(n.extend({bearing:t},e),r)},e.prototype.resetNorth=function(t,e){return this.rotateTo(0,n.extend({duration:1e3},t),e),this},e.prototype.snapToNorth=function(t,e){return Math.abs(this.getBearing())e?1:0}),["bottom","left","right","top"]))return n.warnOnce("options.padding must be a positive number, or an Object with keys 'bottom', 'left', 'right', 'top'"),this;t=s.convert(t);var a=[(e.padding.left-e.padding.right)/2,(e.padding.top-e.padding.bottom)/2],o=Math.min(e.padding.right,e.padding.left),u=Math.min(e.padding.top,e.padding.bottom);e.offset=[e.offset[0]+a[0],e.offset[1]+a[1]];var c=l.convert(e.offset),h=this.transform,f=h.project(t.getNorthWest()),p=h.project(t.getSouthEast()),d=p.sub(f),g=(h.width-2*o-2*Math.abs(c.x))/d.x,v=(h.height-2*u-2*Math.abs(c.y))/d.y;return v<0||g<0?(n.warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset."),this):(e.center=h.unproject(f.add(p).div(2)),e.zoom=Math.min(h.scaleZoom(h.scale*Math.min(g,v)),e.maxZoom),e.bearing=0,e.linear?this.easeTo(e,r):this.flyTo(e,r))},e.prototype.jumpTo=function(t,e){this.stop();var r=this.transform,n=!1,i=!1,a=!1;return"zoom"in t&&r.zoom!==+t.zoom&&(n=!0,r.zoom=+t.zoom),void 0!==t.center&&(r.center=o.convert(t.center)),"bearing"in t&&r.bearing!==+t.bearing&&(i=!0,r.bearing=+t.bearing),"pitch"in t&&r.pitch!==+t.pitch&&(a=!0,r.pitch=+t.pitch),this.fire("movestart",e).fire("move",e),n&&this.fire("zoomstart",e).fire("zoom",e).fire("zoomend",e),i&&this.fire("rotate",e),a&&this.fire("pitchstart",e).fire("pitch",e).fire("pitchend",e),this.fire("moveend",e)},e.prototype.easeTo=function(t,e){var r=this;this.stop(),!1===(t=n.extend({offset:[0,0],duration:500,easing:n.ease},t)).animate&&(t.duration=0);var a=this.transform,s=this.getZoom(),u=this.getBearing(),c=this.getPitch(),h="zoom"in t?+t.zoom:s,f="bearing"in t?this._normalizeBearing(t.bearing,u):u,p="pitch"in t?+t.pitch:c,d=a.centerPoint.add(l.convert(t.offset)),g=a.pointLocation(d),v=o.convert(t.center||g);this._normalizeCenter(v);var m,y,x=a.project(g),b=a.project(v).sub(x),_=a.zoomScale(h-s);return t.around&&(m=o.convert(t.around),y=a.locationPoint(m)),this.zooming=h!==s,this.rotating=u!==f,this.pitching=p!==c,this._prepareEase(e,t.noMoveStart),clearTimeout(this._onEaseEnd),this._ease(function(t){if(r.zooming&&(a.zoom=i(s,h,t)),r.rotating&&(a.bearing=i(u,f,t)),r.pitching&&(a.pitch=i(c,p,t)),m)a.setLocationAtPoint(m,y);else{var n=a.zoomScale(a.zoom-s),o=h>s?Math.min(2,_):Math.max(.5,_),l=Math.pow(o,1-t),g=a.unproject(x.add(b.mult(t*l)).mult(n));a.setLocationAtPoint(a.renderWorldCopies?g.wrap():g,d)}r._fireMoveEvents(e)},function(){t.delayEndEvents?r._onEaseEnd=setTimeout(function(){return r._afterEase(e)},t.delayEndEvents):r._afterEase(e)},t),this},e.prototype._prepareEase=function(t,e){this.moving=!0,e||this.fire("movestart",t),this.zooming&&this.fire("zoomstart",t),this.pitching&&this.fire("pitchstart",t)},e.prototype._fireMoveEvents=function(t){this.fire("move",t),this.zooming&&this.fire("zoom",t),this.rotating&&this.fire("rotate",t),this.pitching&&this.fire("pitch",t)},e.prototype._afterEase=function(t){var e=this.zooming,r=this.pitching;this.moving=!1,this.zooming=!1,this.rotating=!1,this.pitching=!1,e&&this.fire("zoomend",t),r&&this.fire("pitchend",t),this.fire("moveend",t)},e.prototype.flyTo=function(t,e){function r(t){var e=(A*A-M*M+(t?-1:1)*E*E*T*T)/(2*(t?A:M)*E*T);return Math.log(Math.sqrt(e*e+1)-e)}function a(t){return(Math.exp(t)-Math.exp(-t))/2}function s(t){return(Math.exp(t)+Math.exp(-t))/2}var u=this;this.stop(),t=n.extend({offset:[0,0],speed:1.2,curve:1.42,easing:n.ease},t);var c=this.transform,h=this.getZoom(),f=this.getBearing(),p=this.getPitch(),d="zoom"in t?n.clamp(+t.zoom,c.minZoom,c.maxZoom):h,g="bearing"in t?this._normalizeBearing(t.bearing,f):f,v="pitch"in t?+t.pitch:p,m=c.zoomScale(d-h),y=c.centerPoint.add(l.convert(t.offset)),x=c.pointLocation(y),b=o.convert(t.center||x);this._normalizeCenter(b);var _=c.project(x),w=c.project(b).sub(_),k=t.curve,M=Math.max(c.width,c.height),A=M/m,T=w.mag();if("minZoom"in t){var S=n.clamp(Math.min(t.minZoom,h,d),c.minZoom,c.maxZoom),C=M/c.zoomScale(S-h);k=Math.sqrt(C/T*2)}var E=k*k,L=r(0),P=function(t){return s(L)/s(L+k*t)},z=function(t){return M*((s(L)*function(t){return a(t)/s(t)}(L+k*t)-a(L))/E)/T},D=(r(1)-L)/k;if(Math.abs(T)<1e-6||!isFinite(D)){if(Math.abs(M-A)<1e-6)return this.easeTo(t,e);var I=At.maxDuration&&(t.duration=0),this.zooming=!0,this.rotating=f!==g,this.pitching=v!==p,this._prepareEase(e,!1),this._ease(function(t){var r=t*D,n=1/P(r);c.zoom=h+c.scaleZoom(n),u.rotating&&(c.bearing=i(f,g,t)),u.pitching&&(c.pitch=i(p,v,t));var a=c.unproject(_.add(w.mult(z(r))).mult(n));c.setLocationAtPoint(c.renderWorldCopies?a.wrap():a,y),u._fireMoveEvents(e)},function(){return u._afterEase(e)},t),this},e.prototype.isEasing=function(){return!!this._isEasing},e.prototype.isMoving=function(){return this.moving},e.prototype.stop=function(){return this._onFrame&&this._finishAnimation(),this},e.prototype._ease=function(t,e,r){var n=this;!1===r.animate||0===r.duration?(t(1),e()):(this._easeStart=a.now(),this._isEasing=!0,this._easeOptions=r,this._startAnimation(function(e){var r=Math.min((a.now()-n._easeStart)/n._easeOptions.duration,1);t(n._easeOptions.easing(r)),1===r&&n.stop()},function(){n._isEasing=!1,e()}))},e.prototype._updateCamera=function(){this._onFrame&&this._onFrame(this.transform)},e.prototype._startAnimation=function(t,e){return void 0===e&&(e=function(){}),this.stop(),this._onFrame=t,this._finishFn=e,this._update(),this},e.prototype._finishAnimation=function(){delete this._onFrame;var t=this._finishFn;delete this._finishFn,t.call(this)},e.prototype._normalizeBearing=function(t,e){t=n.wrap(t,-180,180);var r=Math.abs(t-e);return Math.abs(t-360-e)180?-360:r<-180?360:0}},e}(t("../util/evented"));e.exports=u},{"../geo/lng_lat":62,"../geo/lng_lat_bounds":63,"../style-spec/util/interpolate":158,"../util/browser":252,"../util/evented":260,"../util/util":275,"@mapbox/point-geometry":4}],232:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/config"),o=function(t){this.options=t,i.bindAll(["_updateEditLink","_updateData","_updateCompact"],this)};o.prototype.getDefaultPosition=function(){return"bottom-right"},o.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0},o.prototype._updateEditLink=function(){var t=this._editLink;t||(t=this._editLink=this._container.querySelector(".mapbox-improve-map"));var e=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:a.ACCESS_TOKEN}];if(t){var r=e.reduce(function(t,r,n){return r.value&&(t+=r.key+"="+r.value+(n=0)return!1;return!0})).length?(this._container.innerHTML=t.join(" | "),this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null}},o.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact")},e.exports=o},{"../../util/config":256,"../../util/dom":259,"../../util/util":275}],233:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=function(){this._fullscreen=!1,i.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in a.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in a.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in a.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in a.document&&(this._fullscreenchange="MSFullscreenChange"),this._className="mapboxgl-ctrl"};o.prototype.onAdd=function(t){return this._map=t,this._mapContainer=this._map.getContainer(),this._container=n.create("div",this._className+" mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._container.style.display="none",i.warnOnce("This device does not support fullscreen mode.")),this._container},o.prototype.onRemove=function(){n.remove(this._container),this._map=null,a.document.removeEventListener(this._fullscreenchange,this._changeIcon)},o.prototype._checkFullscreenSupport=function(){return!!(a.document.fullscreenEnabled||a.document.mozFullScreenEnabled||a.document.msFullscreenEnabled||a.document.webkitFullscreenEnabled)},o.prototype._setupUI=function(){var t=this._fullscreenButton=n.create("button",this._className+"-icon "+this._className+"-fullscreen",this._container);t.setAttribute("aria-label","Toggle fullscreen"),t.type="button",this._fullscreenButton.addEventListener("click",this._onClickFullscreen),a.document.addEventListener(this._fullscreenchange,this._changeIcon)},o.prototype._isFullscreen=function(){return this._fullscreen},o.prototype._changeIcon=function(){(a.document.fullscreenElement||a.document.mozFullScreenElement||a.document.webkitFullscreenElement||a.document.msFullscreenElement)===this._mapContainer!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle(this._className+"-shrink"),this._fullscreenButton.classList.toggle(this._className+"-fullscreen"))},o.prototype._onClickFullscreen=function(){this._isFullscreen()?a.document.exitFullscreen?a.document.exitFullscreen():a.document.mozCancelFullScreen?a.document.mozCancelFullScreen():a.document.msExitFullscreen?a.document.msExitFullscreen():a.document.webkitCancelFullScreen&&a.document.webkitCancelFullScreen():this._mapContainer.requestFullscreen?this._mapContainer.requestFullscreen():this._mapContainer.mozRequestFullScreen?this._mapContainer.mozRequestFullScreen():this._mapContainer.msRequestFullscreen?this._mapContainer.msRequestFullscreen():this._mapContainer.webkitRequestFullscreen&&this._mapContainer.webkitRequestFullscreen()},e.exports=o},{"../../util/dom":259,"../../util/util":275,"../../util/window":254}],234:[function(t,e,r){var n,i=t("../../util/evented"),a=t("../../util/dom"),o=t("../../util/window"),s=t("../../util/util"),l=t("../../geo/lng_lat"),u=t("../marker"),c={positionOptions:{enableHighAccuracy:!1,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showUserLocation:!0},h=function(t){function e(e){t.call(this),this.options=s.extend({},c,e),s.bindAll(["_onSuccess","_onError","_finish","_setupUI","_updateCamera","_updateMarker","_onClickGeolocate"],this)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.onAdd=function(t){return this._map=t,this._container=a.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),function(t){void 0!==n?t(n):void 0!==o.navigator.permissions?o.navigator.permissions.query({name:"geolocation"}).then(function(e){n="denied"!==e.state,t(n)}):(n=!!o.navigator.geolocation,t(n))}(this._setupUI),this._container},e.prototype.onRemove=function(){void 0!==this._geolocationWatchID&&(o.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker.remove(),a.remove(this._container),this._map=void 0},e.prototype._onSuccess=function(t){if(this.options.trackUserLocation)switch(this._lastKnownPosition=t,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(t),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(t),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire("geolocate",t),this._finish()},e.prototype._updateCamera=function(t){var e=new l(t.coords.longitude,t.coords.latitude),r=t.coords.accuracy;this._map.fitBounds(e.toBounds(r),this.options.fitBoundsOptions,{geolocateSource:!0})},e.prototype._updateMarker=function(t){t?this._userLocationDotMarker.setLngLat([t.coords.longitude,t.coords.latitude]).addTo(this._map):this._userLocationDotMarker.remove()},e.prototype._onError=function(t){if(this.options.trackUserLocation)if(1===t.code)this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),void 0!==this._geolocationWatchID&&this._clearWatch();else switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire("error",t),this._finish()},e.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},e.prototype._setupUI=function(t){var e=this;!1!==t&&(this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this._geolocateButton=a.create("button","mapboxgl-ctrl-icon mapboxgl-ctrl-geolocate",this._container),this._geolocateButton.type="button",this._geolocateButton.setAttribute("aria-label","Geolocate"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=a.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new u(this._dotElement),this.options.trackUserLocation&&(this._watchState="OFF")),this._geolocateButton.addEventListener("click",this._onClickGeolocate.bind(this)),this.options.trackUserLocation&&this._map.on("movestart",function(t){t.geolocateSource||"ACTIVE_LOCK"!==e._watchState||(e._watchState="BACKGROUND",e._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),e._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),e.fire("trackuserlocationend"))}))},e.prototype._onClickGeolocate=function(){if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire("trackuserlocationstart");break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire("trackuserlocationend");break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire("trackuserlocationstart")}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}"OFF"===this._watchState&&void 0!==this._geolocationWatchID?this._clearWatch():void 0===this._geolocationWatchID&&(this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._geolocationWatchID=o.navigator.geolocation.watchPosition(this._onSuccess,this._onError,this.options.positionOptions))}else o.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4)},e.prototype._clearWatch=function(){o.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)},e}(i);e.exports=h},{"../../geo/lng_lat":62,"../../util/dom":259,"../../util/evented":260,"../../util/util":275,"../../util/window":254,"../marker":248}],235:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=function(){i.bindAll(["_updateLogo"],this)};a.prototype.onAdd=function(t){this._map=t,this._container=n.create("div","mapboxgl-ctrl");var e=n.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.href="https://www.mapbox.com/",e.setAttribute("aria-label","Mapbox logo"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._container},a.prototype.onRemove=function(){n.remove(this._container),this._map.off("sourcedata",this._updateLogo)},a.prototype.getDefaultPosition=function(){return"bottom-left"},a.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none")},a.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return!0;return!1}},e.exports=a},{"../../util/dom":259,"../../util/util":275}],236:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../handler/drag_rotate"),o={showCompass:!0,showZoom:!0},s=function(t){var e=this;this.options=i.extend({},o,t),this._container=n.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",function(t){return t.preventDefault()}),this.options.showZoom&&(this._zoomInButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in","Zoom In",function(){return e._map.zoomIn()}),this._zoomOutButton=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out","Zoom Out",function(){return e._map.zoomOut()})),this.options.showCompass&&(i.bindAll(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-icon mapboxgl-ctrl-compass","Reset North",function(){return e._map.resetNorth()}),this._compassArrow=n.create("span","mapboxgl-ctrl-compass-arrow",this._compass))};s.prototype._rotateCompassArrow=function(){var t="rotate("+this._map.transform.angle*(180/Math.PI)+"deg)";this._compassArrow.style.transform=t},s.prototype.onAdd=function(t){return this._map=t,this.options.showCompass&&(this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new a(t,{button:"left",element:this._compass}),this._handler.enable()),this._container},s.prototype.onRemove=function(){n.remove(this._container),this.options.showCompass&&(this._map.off("rotate",this._rotateCompassArrow),this._handler.disable(),delete this._handler),delete this._map},s.prototype._createButton=function(t,e,r){var i=n.create("button",t,this._container);return i.type="button",i.setAttribute("aria-label",e),i.addEventListener("click",r),i},e.exports=s},{"../../util/dom":259,"../../util/util":275,"../handler/drag_rotate":242}],237:[function(t,e,r){function n(t,e,r){var n=r&&r.maxWidth||100,a=t._container.clientHeight/2,o=function(t,e){var r=Math.PI/180,n=t.lat*r,i=e.lat*r,a=Math.sin(n)*Math.sin(i)+Math.cos(n)*Math.cos(i)*Math.cos((e.lng-t.lng)*r);return 6371e3*Math.acos(Math.min(a,1))}(t.unproject([0,a]),t.unproject([n,a]));if(r&&"imperial"===r.unit){var s=3.2808*o;s>5280?i(e,n,s/5280,"mi"):i(e,n,s,"ft")}else if(r&&"nautical"===r.unit){i(e,n,o/1852,"nm")}else i(e,n,o,"m")}function i(t,e,r,n){var i=function(t){var e=Math.pow(10,(""+Math.floor(t)).length-1),r=t/e;return e*(r=r>=10?10:r>=5?5:r>=3?3:r>=2?2:1)}(r),a=i/r;"m"===n&&i>=1e3&&(i/=1e3,n="km"),t.style.width=e*a+"px",t.innerHTML=i+n}var a=t("../../util/dom"),o=t("../../util/util"),s=function(t){this.options=t,o.bindAll(["_onMove"],this)};s.prototype.getDefaultPosition=function(){return"bottom-left"},s.prototype._onMove=function(){n(this._map,this._container,this.options)},s.prototype.onAdd=function(t){return this._map=t,this._container=a.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},s.prototype.onRemove=function(){a.remove(this._container),this._map.off("move",this._onMove),this._map=void 0},e.exports=s},{"../../util/dom":259,"../../util/util":275}],238:[function(t,e,r){},{}],239:[function(t,e,r){var n=t("../../util/dom"),i=t("../../geo/lng_lat_bounds"),a=t("../../util/util"),o=t("../../util/window"),s=function(t){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),a.bindAll(["_onMouseDown","_onMouseMove","_onMouseUp","_onKeyDown"],this)};s.prototype.isEnabled=function(){return!!this._enabled},s.prototype.isActive=function(){return!!this._active},s.prototype.enable=function(){this.isEnabled()||(this._map.dragPan&&this._map.dragPan.disable(),this._el.addEventListener("mousedown",this._onMouseDown,!1),this._map.dragPan&&this._map.dragPan.enable(),this._enabled=!0)},s.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onMouseDown),this._enabled=!1)},s.prototype._onMouseDown=function(t){t.shiftKey&&0===t.button&&(o.document.addEventListener("mousemove",this._onMouseMove,!1),o.document.addEventListener("keydown",this._onKeyDown,!1),o.document.addEventListener("mouseup",this._onMouseUp,!1),n.disableDrag(),this._startPos=n.mousePos(this._el,t),this._active=!0)},s.prototype._onMouseMove=function(t){var e=this._startPos,r=n.mousePos(this._el,t);this._box||(this._box=n.create("div","mapboxgl-boxzoom",this._container),this._container.classList.add("mapboxgl-crosshair"),this._fireEvent("boxzoomstart",t));var i=Math.min(e.x,r.x),a=Math.max(e.x,r.x),o=Math.min(e.y,r.y),s=Math.max(e.y,r.y);n.setTransform(this._box,"translate("+i+"px,"+o+"px)"),this._box.style.width=a-i+"px",this._box.style.height=s-o+"px"},s.prototype._onMouseUp=function(t){if(0===t.button){var e=this._startPos,r=n.mousePos(this._el,t),a=(new i).extend(this._map.unproject(e)).extend(this._map.unproject(r));this._finish(),e.x===r.x&&e.y===r.y?this._fireEvent("boxzoomcancel",t):this._map.fitBounds(a,{linear:!0}).fire("boxzoomend",{originalEvent:t,boxZoomBounds:a})}},s.prototype._onKeyDown=function(t){27===t.keyCode&&(this._finish(),this._fireEvent("boxzoomcancel",t))},s.prototype._finish=function(){this._active=!1,o.document.removeEventListener("mousemove",this._onMouseMove,!1),o.document.removeEventListener("keydown",this._onKeyDown,!1),o.document.removeEventListener("mouseup",this._onMouseUp,!1),this._container.classList.remove("mapboxgl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag()},s.prototype._fireEvent=function(t,e){return this._map.fire(t,{originalEvent:e})},e.exports=s},{"../../geo/lng_lat_bounds":63,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],240:[function(t,e,r){var n=t("../../util/util"),i=function(t){this._map=t,n.bindAll(["_onDblClick","_onZoomEnd"],this)};i.prototype.isEnabled=function(){return!!this._enabled},i.prototype.isActive=function(){return!!this._active},i.prototype.enable=function(){this.isEnabled()||(this._map.on("dblclick",this._onDblClick),this._enabled=!0)},i.prototype.disable=function(){this.isEnabled()&&(this._map.off("dblclick",this._onDblClick),this._enabled=!1)},i.prototype._onDblClick=function(t){this._active=!0,this._map.on("zoomend",this._onZoomEnd),this._map.zoomTo(this._map.getZoom()+(t.originalEvent.shiftKey?-1:1),{around:t.lngLat},t)},i.prototype._onZoomEnd=function(){this._active=!1,this._map.off("zoomend",this._onZoomEnd)},e.exports=i},{"../../util/util":275}],241:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.3,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onDown","_onMove","_onUp","_onTouchEnd","_onMouseUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-drag-pan"),this._el.addEventListener("mousedown",this._onDown),this._el.addEventListener("touchstart",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-drag-pan"),this._el.removeEventListener("mousedown",this._onDown),this._el.removeEventListener("touchstart",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){this._ignoreEvent(t)||this.isActive()||(t.touches?(a.document.addEventListener("touchmove",this._onMove),a.document.addEventListener("touchend",this._onTouchEnd)):(a.document.addEventListener("mousemove",this._onMove),a.document.addEventListener("mouseup",this._onMouseUp)),a.addEventListener("blur",this._onMouseUp),this._active=!1,this._previousPos=n.mousePos(this._el,t),this._inertia=[[o.now(),this._previousPos]])},l.prototype._onMove=function(t){if(!this._ignoreEvent(t)){this._lastMoveEvent=t,t.preventDefault();var e=n.mousePos(this._el,t);if(this._drainInertiaBuffer(),this._inertia.push([o.now(),e]),!this._previousPos)return void(this._previousPos=e);this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("dragstart",t),this._fireEvent("movestart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()}},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;e&&(t.setLocationAtPoint(t.pointLocation(this._previousPos),this._pos),this._fireEvent("drag",e),this._fireEvent("move",e),this._previousPos=this._pos,delete this._lastMoveEvent)},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,delete this._pos,this._fireEvent("dragend",t),this._drainInertiaBuffer();var r=function(){e._map.moving=!1,e._fireEvent("moveend",t)},n=this._inertia;if(n.length<2)return void r();var i=n[n.length-1],a=n[0],o=i[1].sub(a[1]),l=(i[0]-a[0])/1e3;if(0===l||i[1].equals(a[1]))return void r();var u=o.mult(.3/l),c=u.mag();c>1400&&(c=1400,u._unit()._mult(c));var h=c/750,f=u.mult(-h/2);this._map.panBy(f,{duration:1e3*h,easing:s,noMoveStart:!0},{originalEvent:t})}},l.prototype._onUp=function(t){this._onDragFinished(t)},l.prototype._onMouseUp=function(t){this._ignoreEvent(t)||(this._onUp(t),a.document.removeEventListener("mousemove",this._onMove),a.document.removeEventListener("mouseup",this._onMouseUp),a.removeEventListener("blur",this._onMouseUp))},l.prototype._onTouchEnd=function(t){this._ignoreEvent(t)||(this._onUp(t),a.document.removeEventListener("touchmove",this._onMove),a.document.removeEventListener("touchend",this._onTouchEnd))},l.prototype._fireEvent=function(t,e){return this._map.fire(t,e?{originalEvent:e}:{})},l.prototype._ignoreEvent=function(t){var e=this._map;return!(!e.boxZoom||!e.boxZoom.isActive())||!(!e.dragRotate||!e.dragRotate.isActive())||(t.touches?t.touches.length>1:!!t.ctrlKey||"mousemove"!==t.type&&t.button&&0!==t.button)},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=o.now();t.length>0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],242:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.25,1),l=function(t,e){this._map=t,this._el=e.element||t.getCanvasContainer(),this._button=e.button||"right",this._bearingSnap=e.bearingSnap||0,this._pitchWithRotate=!1!==e.pitchWithRotate,i.bindAll(["_onDown","_onMove","_onUp","_onDragFrame","_onDragFinished"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.isActive=function(){return!!this._active},l.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("mousedown",this._onDown),this._enabled=!0)},l.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("mousedown",this._onDown),this._enabled=!1)},l.prototype._onDown=function(t){if(!(this._map.boxZoom&&this._map.boxZoom.isActive()||this._map.dragPan&&this._map.dragPan.isActive()||this.isActive())){if("right"===this._button){var e=t.ctrlKey?0:2,r=t.button;if(void 0!==a.InstallTrigger&&2===t.button&&t.ctrlKey&&a.navigator.platform.toUpperCase().indexOf("MAC")>=0&&(r=0),r!==e)return}else if(t.ctrlKey||0!==t.button)return;n.disableDrag(),a.document.addEventListener("mousemove",this._onMove,{capture:!0}),a.document.addEventListener("mouseup",this._onUp),a.addEventListener("blur",this._onUp),this._active=!1,this._inertia=[[o.now(),this._map.getBearing()]],this._previousPos=n.mousePos(this._el,t),this._center=this._map.transform.centerPoint,t.preventDefault()}},l.prototype._onMove=function(t){this._lastMoveEvent=t;var e=n.mousePos(this._el,t);this._previousPos?(this._pos=e,this.isActive()||(this._active=!0,this._map.moving=!0,this._fireEvent("rotatestart",t),this._fireEvent("movestart",t),this._pitchWithRotate&&this._fireEvent("pitchstart",t),this._map._startAnimation(this._onDragFrame,this._onDragFinished)),this._map._update()):this._previousPos=e},l.prototype._onUp=function(t){a.document.removeEventListener("mousemove",this._onMove,{capture:!0}),a.document.removeEventListener("mouseup",this._onUp),a.removeEventListener("blur",this._onUp),n.enableDrag(),this._onDragFinished(t)},l.prototype._onDragFrame=function(t){var e=this._lastMoveEvent;if(e){var r=this._previousPos,n=this._pos,i=.8*(r.x-n.x),a=-.5*(r.y-n.y),s=t.bearing-i,l=t.pitch-a,u=this._inertia,c=u[u.length-1];this._drainInertiaBuffer(),u.push([o.now(),this._map._normalizeBearing(s,c[1])]),t.bearing=s,this._pitchWithRotate&&(this._fireEvent("pitch",e),t.pitch=l),this._fireEvent("rotate",e),this._fireEvent("move",e),delete this._lastMoveEvent,this._previousPos=this._pos}},l.prototype._onDragFinished=function(t){var e=this;if(this.isActive()){this._active=!1,delete this._lastMoveEvent,delete this._previousPos,this._fireEvent("rotateend",t),this._drainInertiaBuffer();var r=this._map,n=r.getBearing(),i=this._inertia,a=function(){Math.abs(n)180&&(d=180);var g=d/180;c+=f*d*(g/2),Math.abs(r._normalizeBearing(c,0))0&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],243:[function(t,e,r){function n(t){return t*(2-t)}var i=t("../../util/util"),a=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onKeyDown"],this)};a.prototype.isEnabled=function(){return!!this._enabled},a.prototype.enable=function(){this.isEnabled()||(this._el.addEventListener("keydown",this._onKeyDown,!1),this._enabled=!0)},a.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("keydown",this._onKeyDown),this._enabled=!1)},a.prototype._onKeyDown=function(t){if(!(t.altKey||t.ctrlKey||t.metaKey)){var e=0,r=0,i=0,a=0,o=0;switch(t.keyCode){case 61:case 107:case 171:case 187:e=1;break;case 189:case 109:case 173:e=-1;break;case 37:t.shiftKey?r=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?r=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?i=1:(t.preventDefault(),o=-1);break;case 40:t.shiftKey?i=-1:(o=1,t.preventDefault());break;default:return}var s=this._map,l=s.getZoom(),u={duration:300,delayEndEvents:500,easing:n,zoom:e?Math.round(l)+e*(t.shiftKey?2:1):l,bearing:s.getBearing()+15*r,pitch:s.getPitch()+10*i,offset:[100*-a,100*-o],center:s.getCenter()};s.easeTo(u,{originalEvent:t})}},e.exports=a},{"../../util/util":275}],244:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/browser"),o=t("../../util/window"),s=t("../../style-spec/util/interpolate").number,l=t("../../geo/lng_lat"),u=o.navigator.userAgent.toLowerCase(),c=-1!==u.indexOf("firefox"),h=-1!==u.indexOf("safari")&&-1===u.indexOf("chrom"),f=function(t){this._map=t,this._el=t.getCanvasContainer(),this._delta=0,i.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this)};f.prototype.isEnabled=function(){return!!this._enabled},f.prototype.isActive=function(){return!!this._active},f.prototype.enable=function(t){this.isEnabled()||(this._el.addEventListener("wheel",this._onWheel,!1),this._el.addEventListener("mousewheel",this._onWheel,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},f.prototype.disable=function(){this.isEnabled()&&(this._el.removeEventListener("wheel",this._onWheel),this._el.removeEventListener("mousewheel",this._onWheel),this._enabled=!1)},f.prototype._onWheel=function(t){var e=0;"wheel"===t.type?(e=t.deltaY,c&&t.deltaMode===o.WheelEvent.DOM_DELTA_PIXEL&&(e/=a.devicePixelRatio),t.deltaMode===o.WheelEvent.DOM_DELTA_LINE&&(e*=40)):"mousewheel"===t.type&&(e=-t.wheelDeltaY,h&&(e/=3));var r=a.now(),n=r-(this._lastWheelEventTime||0);this._lastWheelEventTime=r,0!==e&&e%4.000244140625==0?this._type="wheel":0!==e&&Math.abs(e)<4?this._type="trackpad":n>400?(this._type=null,this._lastValue=e,this._timeout=setTimeout(this._onTimeout,40,t)):this._type||(this._type=Math.abs(n*e)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,e+=this._lastValue)),t.shiftKey&&e&&(e/=4),this._type&&(this._lastWheelEvent=t,this._delta-=e,this.isActive()||this._start(t)),t.preventDefault()},f.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this.isActive()||this._start(t)},f.prototype._start=function(t){if(this._delta){this._active=!0,this._map.moving=!0,this._map.zooming=!0,this._map.fire("movestart",{originalEvent:t}),this._map.fire("zoomstart",{originalEvent:t}),clearTimeout(this._finishTimeout);var e=n.mousePos(this._el,t);this._around=l.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(e)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._map._startAnimation(this._onScrollFrame,this._onScrollFinished)}},f.prototype._onScrollFrame=function(t){if(this.isActive()){if(0!==this._delta){var e="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?1/450:.01,r=2/(1+Math.exp(-Math.abs(this._delta*e)));this._delta<0&&0!==r&&(r=1/r);var n="number"==typeof this._targetZoom?t.zoomScale(this._targetZoom):t.scale;this._targetZoom=Math.min(t.maxZoom,Math.max(t.minZoom,t.scaleZoom(n*r))),"wheel"===this._type&&(this._startZoom=t.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}if("wheel"===this._type){var i=Math.min((a.now()-this._lastWheelEventTime)/200,1),o=this._easing(i);t.zoom=s(this._startZoom,this._targetZoom,o),1===i&&this._map.stop()}else t.zoom=this._targetZoom,this._map.stop();t.setLocationAtPoint(this._around,this._aroundPoint),this._map.fire("move",{originalEvent:this._lastWheelEvent}),this._map.fire("zoom",{originalEvent:this._lastWheelEvent})}},f.prototype._onScrollFinished=function(){var t=this;this.isActive()&&(this._active=!1,this._finishTimeout=setTimeout(function(){t._map.moving=!1,t._map.zooming=!1,t._map.fire("zoomend"),t._map.fire("moveend"),delete t._targetZoom},200))},f.prototype._smoothOutEasing=function(t){var e=i.ease;if(this._prevEase){var r=this._prevEase,n=(a.now()-r.start)/r.duration,o=r.easing(n+.01)-r.easing(n),s=.27/Math.sqrt(o*o+1e-4)*.01,l=Math.sqrt(.0729-s*s);e=i.bezier(s,l,.25,1)}return this._prevEase={start:a.now(),duration:t,easing:e},e},e.exports=f},{"../../geo/lng_lat":62,"../../style-spec/util/interpolate":158,"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],245:[function(t,e,r){var n=t("../../util/dom"),i=t("../../util/util"),a=t("../../util/window"),o=t("../../util/browser"),s=i.bezier(0,0,.15,1),l=function(t){this._map=t,this._el=t.getCanvasContainer(),i.bindAll(["_onStart","_onMove","_onEnd"],this)};l.prototype.isEnabled=function(){return!!this._enabled},l.prototype.enable=function(t){this.isEnabled()||(this._el.classList.add("mapboxgl-touch-zoom-rotate"),this._el.addEventListener("touchstart",this._onStart,!1),this._enabled=!0,this._aroundCenter=t&&"center"===t.around)},l.prototype.disable=function(){this.isEnabled()&&(this._el.classList.remove("mapboxgl-touch-zoom-rotate"),this._el.removeEventListener("touchstart",this._onStart),this._enabled=!1)},l.prototype.disableRotation=function(){this._rotationDisabled=!0},l.prototype.enableRotation=function(){this._rotationDisabled=!1},l.prototype._onStart=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]);this._startVec=e.sub(r),this._startScale=this._map.transform.scale,this._startBearing=this._map.transform.bearing,this._gestureIntent=void 0,this._inertia=[],a.document.addEventListener("touchmove",this._onMove,!1),a.document.addEventListener("touchend",this._onEnd,!1)}},l.prototype._onMove=function(t){if(2===t.touches.length){var e=n.mousePos(this._el,t.touches[0]),r=n.mousePos(this._el,t.touches[1]),i=e.add(r).div(2),a=e.sub(r),s=a.mag()/this._startVec.mag(),l=this._rotationDisabled?0:180*a.angleWith(this._startVec)/Math.PI,u=this._map;if(this._gestureIntent){var c={duration:0,around:u.unproject(i)};"rotate"===this._gestureIntent&&(c.bearing=this._startBearing+l),"zoom"!==this._gestureIntent&&"rotate"!==this._gestureIntent||(c.zoom=u.transform.scaleZoom(this._startScale*s)),u.stop(),this._drainInertiaBuffer(),this._inertia.push([o.now(),s,i]),u.easeTo(c,{originalEvent:t})}else{var h=Math.abs(1-s)>.15;Math.abs(l)>10?this._gestureIntent="rotate":h&&(this._gestureIntent="zoom"),this._gestureIntent&&(this._startVec=a,this._startScale=u.transform.scale,this._startBearing=u.transform.bearing)}t.preventDefault()}},l.prototype._onEnd=function(t){a.document.removeEventListener("touchmove",this._onMove),a.document.removeEventListener("touchend",this._onEnd),this._drainInertiaBuffer();var e=this._inertia,r=this._map;if(e.length<2)r.snapToNorth({},{originalEvent:t});else{var n=e[e.length-1],i=e[0],o=r.transform.scaleZoom(this._startScale*n[1]),l=r.transform.scaleZoom(this._startScale*i[1]),u=o-l,c=(n[0]-i[0])/1e3,h=n[2];if(0!==c&&o!==l){var f=.15*u/c;Math.abs(f)>2.5&&(f=f>0?2.5:-2.5);var p=1e3*Math.abs(f/(12*.15)),d=o+f*p/2e3;d<0&&(d=0),r.easeTo({zoom:d,duration:p,easing:s,around:this._aroundCenter?r.getCenter():r.unproject(h)},{originalEvent:t})}else r.snapToNorth({},{originalEvent:t})}},l.prototype._drainInertiaBuffer=function(){for(var t=this._inertia,e=o.now();t.length>2&&e-t[0][0]>160;)t.shift()},e.exports=l},{"../../util/browser":252,"../../util/dom":259,"../../util/util":275,"../../util/window":254}],246:[function(t,e,r){var n=t("../util/util"),i=t("../util/window"),a=t("../util/throttle"),o=function(){n.bindAll(["_onHashChange","_updateHash"],this),this._updateHash=a(this._updateHashUnthrottled.bind(this),300)};o.prototype.addTo=function(t){return this._map=t,i.addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this},o.prototype.remove=function(){return i.removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),delete this._map,this},o.prototype.getHashString=function(t){var e=this._map.getCenter(),r=Math.round(100*this._map.getZoom())/100,n=Math.ceil((r*Math.LN2+Math.log(512/360/.5))/Math.LN10),i=Math.pow(10,n),a=Math.round(e.lng*i)/i,o=Math.round(e.lat*i)/i,s=this._map.getBearing(),l=this._map.getPitch(),u="";return u+=t?"#/"+a+"/"+o+"/"+r:"#"+r+"/"+o+"/"+a,(s||l)&&(u+="/"+Math.round(10*s)/10),l&&(u+="/"+Math.round(l)),u},o.prototype._onHashChange=function(){var t=i.location.hash.replace("#","").split("/");return t.length>=3&&(this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:+(t[3]||0),pitch:+(t[4]||0)}),!0)},o.prototype._updateHashUnthrottled=function(){var t=this.getHashString();i.history.replaceState("","",t)},e.exports=o},{"../util/throttle":272,"../util/util":275,"../util/window":254}],247:[function(t,e,r){function n(t){t.parentNode&&t.parentNode.removeChild(t)}var i=t("../util/util"),a=t("../util/browser"),o=t("../util/window"),s=t("../util/window"),l=s.HTMLImageElement,u=s.HTMLElement,c=t("../util/dom"),h=t("../util/ajax"),f=t("../style/style"),p=t("../style/evaluation_parameters"),d=t("../render/painter"),g=t("../geo/transform"),v=t("./hash"),m=t("./bind_handlers"),y=t("./camera"),x=t("../geo/lng_lat"),b=t("../geo/lng_lat_bounds"),_=t("@mapbox/point-geometry"),w=t("./control/attribution_control"),k=t("./control/logo_control"),M=t("@mapbox/mapbox-gl-supported"),A=t("../util/image").RGBAImage;t("./events");var T={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:0,maxZoom:22,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,bearingSnap:7,hash:!1,attributionControl:!0,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,maxTileCacheSize:null,transformRequest:null,fadeDuration:300},S=function(t){function e(e){if(null!=(e=i.extend({},T,e)).minZoom&&null!=e.maxZoom&&e.minZoom>e.maxZoom)throw new Error("maxZoom must be greater than minZoom");var r=new g(e.minZoom,e.maxZoom,e.renderWorldCopies);t.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming;var n=e.transformRequest;if(this._transformRequest=n?function(t,e){return n(t,e)||{url:t}}:function(t){return{url:t}},"string"==typeof e.container){var a=o.document.getElementById(e.container);if(!a)throw new Error("Container '"+e.container+"' not found.");this._container=a}else{if(!(e.container instanceof u))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container}e.maxBounds&&this.setMaxBounds(e.maxBounds),i.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored","_update","_render","_onData","_onDataLoading"],this),this._setupContainer(),this._setupPainter(),this.on("move",this._update.bind(this,!1)),this.on("zoom",this._update.bind(this,!0)),void 0!==o&&(o.addEventListener("online",this._onWindowOnline,!1),o.addEventListener("resize",this._onWindowResize,!1)),m(this,e),this._hash=e.hash&&(new v).addTo(this),this._hash&&this._hash._onHashChange()||this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),this.resize(),e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new w),this.addControl(new k,e.logoPosition),this.on("style.load",function(){this.transform.unmodified&&this.jumpTo(this.style.stylesheet)}),this.on("data",this._onData),this.on("dataloading",this._onDataLoading)}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={showTileBoundaries:{},showCollisionBoxes:{},showOverdrawInspector:{},repaint:{},vertices:{}};return e.prototype.addControl=function(t,e){void 0===e&&t.getDefaultPosition&&(e=t.getDefaultPosition()),void 0===e&&(e="top-right");var r=t.onAdd(this),n=this._controlPositions[e];return-1!==e.indexOf("bottom")?n.insertBefore(r,n.firstChild):n.appendChild(r),this},e.prototype.removeControl=function(t){return t.onRemove(this),this},e.prototype.resize=function(){var t=this._containerDimensions(),e=t[0],r=t[1];return this._resizeCanvas(e,r),this.transform.resize(e,r),this.painter.resize(e,r),this.fire("movestart").fire("move").fire("resize").fire("moveend")},e.prototype.getBounds=function(){var t=new b(this.transform.pointLocation(new _(0,this.transform.height)),this.transform.pointLocation(new _(this.transform.width,0)));return(this.transform.angle||this.transform.pitch)&&(t.extend(this.transform.pointLocation(new _(this.transform.size.x,0))),t.extend(this.transform.pointLocation(new _(0,this.transform.size.y)))),t},e.prototype.getMaxBounds=function(){return this.transform.latRange&&2===this.transform.latRange.length&&this.transform.lngRange&&2===this.transform.lngRange.length?new b([this.transform.lngRange[0],this.transform.latRange[0]],[this.transform.lngRange[1],this.transform.latRange[1]]):null},e.prototype.setMaxBounds=function(t){if(t){var e=b.convert(t);this.transform.lngRange=[e.getWest(),e.getEast()],this.transform.latRange=[e.getSouth(),e.getNorth()],this.transform._constrain(),this._update()}else null!==t&&void 0!==t||(this.transform.lngRange=null,this.transform.latRange=null,this._update());return this},e.prototype.setMinZoom=function(t){if((t=null===t||void 0===t?0:t)>=0&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},e.prototype.getMaxZoom=function(){return this.transform.maxZoom},e.prototype.project=function(t){return this.transform.locationPoint(x.convert(t))},e.prototype.unproject=function(t){return this.transform.pointLocation(_.convert(t))},e.prototype.on=function(e,r,n){var a=this;if(void 0===n)return t.prototype.on.call(this,e,r);var o=function(){if("mouseenter"===e||"mouseover"===e){var t=!1;return{layer:r,listener:n,delegates:{mousemove:function(o){var s=a.getLayer(r)?a.queryRenderedFeatures(o.point,{layers:[r]}):[];s.length?t||(t=!0,n.call(a,i.extend({features:s},o,{type:e}))):t=!1},mouseout:function(){t=!1}}}}if("mouseleave"===e||"mouseout"===e){var o=!1;return{layer:r,listener:n,delegates:{mousemove:function(t){(a.getLayer(r)?a.queryRenderedFeatures(t.point,{layers:[r]}):[]).length?o=!0:o&&(o=!1,n.call(a,i.extend({},t,{type:e})))},mouseout:function(t){o&&(o=!1,n.call(a,i.extend({},t,{type:e})))}}}}var s;return{layer:r,listener:n,delegates:(s={},s[e]=function(t){var e=a.getLayer(r)?a.queryRenderedFeatures(t.point,{layers:[r]}):[];e.length&&n.call(a,i.extend({features:e},t))},s)}}();for(var s in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(o),o.delegates)a.on(s,o.delegates[s]);return this},e.prototype.off=function(e,r,n){if(void 0===n)return t.prototype.off.call(this,e,r);if(this._delegatedListeners&&this._delegatedListeners[e])for(var i=this._delegatedListeners[e],a=0;athis._map.transform.height-i?["bottom"]:[],t.xthis._map.transform.width-n/2&&e.push("right"),e=0===e.length?"bottom":e.join("-")}var o=t.add(r[e]).round(),l={top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},c=this._container.classList;for(var h in l)c.remove("mapboxgl-popup-anchor-"+h);c.add("mapboxgl-popup-anchor-"+e),a.setTransform(this._container,l[e]+" translate("+o.x+"px,"+o.y+"px)")}},e.prototype._onClickClose=function(){this.remove()},e}(i);e.exports=h},{"../geo/lng_lat":62,"../util/dom":259,"../util/evented":260,"../util/smart_wrap":270,"../util/util":275,"../util/window":254,"@mapbox/point-geometry":4}],250:[function(t,e,r){var n=t("./util"),i=t("./web_worker_transfer"),a=i.serialize,o=i.deserialize,s=function(t,e,r){this.target=t,this.parent=e,this.mapId=r,this.callbacks={},this.callbackID=0,n.bindAll(["receive"],this),this.target.addEventListener("message",this.receive,!1)};s.prototype.send=function(t,e,r,n){var i=r?this.mapId+":"+this.callbackID++:null;r&&(this.callbacks[i]=r);var o=[];this.target.postMessage({targetMapId:n,sourceMapId:this.mapId,type:t,id:String(i),data:a(e,o)},o)},s.prototype.receive=function(t){var e,r=this,n=t.data,i=n.id;if(!n.targetMapId||this.mapId===n.targetMapId){var s=function(t,e){var n=[];r.target.postMessage({sourceMapId:r.mapId,type:"",id:String(i),error:t?String(t):null,data:a(e,n)},n)};if(""===n.type)e=this.callbacks[n.id],delete this.callbacks[n.id],e&&n.error?e(new Error(n.error)):e&&e(null,o(n.data));else if(void 0!==n.id&&this.parent[n.type])this.parent[n.type](n.sourceMapId,o(n.data),s);else if(void 0!==n.id&&this.parent.getWorkerSource){var l=n.type.split(".");this.parent.getWorkerSource(n.sourceMapId,l[0])[l[1]](o(n.data),s)}else this.parent[n.type](o(n.data))}},s.prototype.remove=function(){this.target.removeEventListener("message",this.receive,!1)},e.exports=s},{"./util":275,"./web_worker_transfer":278}],251:[function(t,e,r){function n(t){var e=new a.XMLHttpRequest;for(var r in e.open("GET",t.url,!0),t.headers)e.setRequestHeader(r,t.headers[r]);return e.withCredentials="include"===t.credentials,e}function i(t){var e=a.document.createElement("a");return e.href=t,e.protocol===a.document.location.protocol&&e.host===a.document.location.host}var a=t("./window"),o={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};r.ResourceType=o,"function"==typeof Object.freeze&&Object.freeze(o);var s=function(t){function e(e,r){t.call(this,e),this.status=r}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(Error);r.getJSON=function(t,e){var r=n(t);return r.setRequestHeader("Accept","application/json"),r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){if(r.status>=200&&r.status<300&&r.response){var t;try{t=JSON.parse(r.response)}catch(t){return e(t)}e(null,t)}else e(new s(r.statusText,r.status))},r.send(),r},r.getArrayBuffer=function(t,e){var r=n(t);return r.responseType="arraybuffer",r.onerror=function(){e(new Error(r.statusText))},r.onload=function(){var t=r.response;if(0===t.byteLength&&200===r.status)return e(new Error("http status 200 returned without content."));r.status>=200&&r.status<300&&r.response?e(null,{data:t,cacheControl:r.getResponseHeader("Cache-Control"),expires:r.getResponseHeader("Expires")}):e(new s(r.statusText,r.status))},r.send(),r};r.getImage=function(t,e){return r.getArrayBuffer(t,function(t,r){if(t)e(t);else if(r){var n=new a.Image,i=a.URL||a.webkitURL;n.onload=function(){e(null,n),i.revokeObjectURL(n.src)};var o=new a.Blob([new Uint8Array(r.data)],{type:"image/png"});n.cacheControl=r.cacheControl,n.expires=r.expires,n.src=r.data.byteLength?i.createObjectURL(o):"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII="}})},r.getVideo=function(t,e){var r=a.document.createElement("video");r.onloadstart=function(){e(null,r)};for(var n=0;n1)for(var h=0;h0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},o.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this},e.exports=o},{"./util":275}],261:[function(t,e,r){function n(t,e){return e.max-t.max}function i(t,e,r,n){this.p=new o(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;it.y!=h.y>t.y&&t.x<(h.x-c.x)*(t.y-c.y)/(h.y-c.y)+c.x&&(r=!r),n=Math.min(n,s(t,c,h))}return(r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2}var a=t("tinyqueue"),o=t("@mapbox/point-geometry"),s=t("./intersection_tests").distToSegmentSquared;e.exports=function(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var s=1/0,l=1/0,u=-1/0,c=-1/0,h=t[0],f=0;fu)&&(u=p.x),(!f||p.y>c)&&(c=p.y)}var d=u-s,g=c-l,v=Math.min(d,g),m=v/2,y=new a(null,n);if(0===v)return new o(s,l);for(var x=s;x_.d||!_.d)&&(_=k,r&&console.log("found best %d after %d probes",Math.round(1e4*k.d)/1e4,w)),k.max-_.d<=e||(m=k.h/2,y.push(new i(k.p.x-m,k.p.y-m,m,t)),y.push(new i(k.p.x+m,k.p.y-m,m,t)),y.push(new i(k.p.x-m,k.p.y+m,m,t)),y.push(new i(k.p.x+m,k.p.y+m,m,t)),w+=4)}return r&&(console.log("num probes: "+w),console.log("best distance: "+_.d)),_.p}},{"./intersection_tests":264,"@mapbox/point-geometry":4,tinyqueue:33}],262:[function(t,e,r){var n,i=t("./worker_pool");e.exports=function(){return n||(n=new i),n}},{"./worker_pool":279}],263:[function(t,e,r){function n(t,e,r,n){var i=e.width,a=e.height;if(n){if(n.length!==i*a*r)throw new RangeError("mismatched image size")}else n=new Uint8Array(i*a*r);return t.width=i,t.height=a,t.data=n,t}function i(t,e,r){var i=e.width,o=e.height;if(i!==t.width||o!==t.height){var s=n({},{width:i,height:o},r);a(t,s,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,i),height:Math.min(t.height,o)},r),t.width=i,t.height=o,t.data=s.data}}function a(t,e,r,n,i,a){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,l=0;l1){if(i(t,e))return!0;for(var n=0;n1?t.distSqr(r):t.distSqr(r.sub(e)._mult(i)._add(e))}function l(t,e){for(var r,n,i,a=!1,o=0;oe.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function u(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r)}return r}var c=t("./util").isCounterClockwise;e.exports={multiPolygonIntersectsBufferedMultiPoint:function(t,e,r){for(var n=0;n=3)for(var l=0;l=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}}},{}],266:[function(t,e,r){var n=function(t,e){this.max=t,this.onRemove=e,this.reset()};n.prototype.reset=function(){var t=this;for(var e in t.data)t.onRemove(t.data[e]);return this.data={},this.order=[],this},n.prototype.add=function(t,e){if(this.has(t))this.order.splice(this.order.indexOf(t),1),this.data[t]=e,this.order.push(t);else if(this.data[t]=e,this.order.push(t),this.order.length>this.max){var r=this.getAndRemove(this.order[0]);r&&this.onRemove(r)}return this},n.prototype.has=function(t){return t in this.data},n.prototype.keys=function(){return this.order},n.prototype.getAndRemove=function(t){if(!this.has(t))return null;var e=this.data[t];return delete this.data[t],this.order.splice(this.order.indexOf(t),1),e},n.prototype.get=function(t){return this.has(t)?this.data[t]:null},n.prototype.remove=function(t){if(!this.has(t))return this;var e=this.data[t];return delete this.data[t],this.onRemove(e),this.order.splice(this.order.indexOf(t),1),this},n.prototype.setMaxSize=function(t){var e=this;for(this.max=t;this.order.length>this.max;){var r=e.getAndRemove(e.order[0]);r&&e.onRemove(r)}return this},e.exports=n},{}],267:[function(t,e,r){function n(t,e){var r=a(s.API_URL);if(t.protocol=r.protocol,t.authority=r.authority,"/"!==r.path&&(t.path=""+r.path+t.path),!s.REQUIRE_ACCESS_TOKEN)return o(t);if(!(e=e||s.ACCESS_TOKEN))throw new Error("An API access token is required to use Mapbox GL. "+u);if("s"===e[0])throw new Error("Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). "+u);return t.params.push("access_token="+e),o(t)}function i(t){return 0===t.indexOf("mapbox:")}function a(t){var e=t.match(h);if(!e)throw new Error("Unable to parse URL object");return{protocol:e[1],authority:e[2],path:e[3]||"/",params:e[4]?e[4].split("&"):[]}}function o(t){var e=t.params.length?"?"+t.params.join("&"):"";return t.protocol+"://"+t.authority+t.path+e}var s=t("./config"),l=t("./browser"),u="See https://www.mapbox.com/api-documentation/#access-tokens";r.isMapboxURL=i,r.normalizeStyleURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/styles/v1"+r.path,n(r,e)},r.normalizeGlyphsURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/fonts/v1"+r.path,n(r,e)},r.normalizeSourceURL=function(t,e){if(!i(t))return t;var r=a(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),n(r,e)},r.normalizeSpriteURL=function(t,e,r,s){var l=a(t);return i(t)?(l.path="/styles/v1"+l.path+"/sprite"+e+r,n(l,s)):(l.path+=""+e+r,o(l))};var c=/(\.(png|jpg)\d*)(?=$)/;r.normalizeTileURL=function(t,e,r){if(!e||!i(e))return t;var n=a(t),u=l.devicePixelRatio>=2||512===r?"@2x":"",h=l.supportsWebp?".webp":"$1";return n.path=n.path.replace(c,""+u+h),function(t){for(var e=0;e=65097&&t<=65103)||n["CJK Compatibility Ideographs"](t)||n["CJK Compatibility"](t)||n["CJK Radicals Supplement"](t)||n["CJK Strokes"](t)||!(!n["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||n["CJK Unified Ideographs Extension A"](t)||n["CJK Unified Ideographs"](t)||n["Enclosed CJK Letters and Months"](t)||n["Hangul Compatibility Jamo"](t)||n["Hangul Jamo Extended-A"](t)||n["Hangul Jamo Extended-B"](t)||n["Hangul Jamo"](t)||n["Hangul Syllables"](t)||n.Hiragana(t)||n["Ideographic Description Characters"](t)||n.Kanbun(t)||n["Kangxi Radicals"](t)||n["Katakana Phonetic Extensions"](t)||n.Katakana(t)&&12540!==t||!(!n["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!n["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||n["Unified Canadian Aboriginal Syllabics"](t)||n["Unified Canadian Aboriginal Syllabics Extended"](t)||n["Vertical Forms"](t)||n["Yijing Hexagram Symbols"](t)||n["Yi Syllables"](t)||n["Yi Radicals"](t)))},r.charHasNeutralVerticalOrientation=function(t){return!!(n["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||n["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||n["Letterlike Symbols"](t)||n["Number Forms"](t)||n["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||n["Control Pictures"](t)&&9251!==t||n["Optical Character Recognition"](t)||n["Enclosed Alphanumerics"](t)||n["Geometric Shapes"](t)||n["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||n["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||n["CJK Symbols and Punctuation"](t)||n.Katakana(t)||n["Private Use Area"](t)||n["CJK Compatibility Forms"](t)||n["Small Form Variants"](t)||n["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)},r.charHasRotatedVerticalOrientation=function(t){return!(r.charHasUprightVerticalOrientation(t)||r.charHasNeutralVerticalOrientation(t))}},{"./is_char_in_unicode_block":265}],270:[function(t,e,r){var n=t("../geo/lng_lat");e.exports=function(t,e,r){if(t=new n(t.lng,t.lat),e){var i=new n(t.lng-360,t.lat),a=new n(t.lng+360,t.lat),o=r.locationPoint(t).distSqr(e);r.locationPoint(i).distSqr(e)180;){var s=r.locationPoint(t);if(s.x>=0&&s.y>=0&&s.x<=r.width&&s.y<=r.height)break;t.lng>r.center.lng?t.lng-=360:t.lng+=360}return t}},{"../geo/lng_lat":62}],271:[function(t,e,r){function n(t,e){return Math.ceil(t/e)*e}var i={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},a=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0)};a.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},a.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},a.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())},a.prototype.clear=function(){this.length=0},a.prototype.resize=function(t){this.reserve(t),this.length=t},a.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e)}},a.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")},e.exports.StructArray=a,e.exports.Struct=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8},e.exports.viewTypes=i,e.exports.createLayout=function(t,e){void 0===e&&(e=1);var r=0,a=0;return{members:t.map(function(t){var o=function(t){return i[t].BYTES_PER_ELEMENT}(t.type),s=r=n(r,Math.max(e,o)),l=t.components||1;return a=Math.max(a,o),r+=o*l,{name:t.name,type:t.type,components:l,offset:s}}),size:n(r,Math.max(a,e)),alignment:e}}},{}],272:[function(t,e,r){e.exports=function(t,e){var r=!1,n=0,i=function(){n=0,r&&(t(),n=setTimeout(i,e),r=!1)};return function(){return r=!0,n||i(),n}}},{}],273:[function(t,e,r){function n(t,e){if(t.row>e.row){var r=t;t=e,e=r}return{x0:t.column,y0:t.row,x1:e.column,y1:e.row,dx:e.column-t.column,dy:e.row-t.row}}function i(t,e,r,n,i){var a=Math.max(r,Math.floor(e.y0)),o=Math.min(n,Math.ceil(e.y1));if(t.x0===e.x0&&t.y0===e.y0?t.x0+e.dy/t.dy*t.dx0,h=e.dx<0,f=a;fc.dy&&(l=u,u=c,c=l),u.dy>h.dy&&(l=u,u=h,h=l),c.dy>h.dy&&(l=c,c=h,h=l),u.dy&&i(h,u,a,o,s),c.dy&&i(h,c,a,o,s)}t("../geo/coordinate");var o=t("../source/tile_id").OverscaledTileID;e.exports=function(t,e,r,n){function i(e,i,a){var u,c,h;if(a>=0&&a<=s)for(u=e;u=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)},r.bezier=function(t,e,r,i){var a=new n(t,e,r,i);return function(t){return a.solve(t)}},r.ease=r.bezier(.25,.1,.25,1),r.clamp=function(t,e,r){return Math.min(r,Math.max(e,t))},r.wrap=function(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i},r.asyncAll=function(t,e,r){if(!t.length)return r(null,[]);var n=t.length,i=new Array(t.length),a=null;t.forEach(function(t,o){e(t,function(t,e){t&&(a=t),i[o]=e,0==--n&&r(a,i)})})},r.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},r.keysDifference=function(t,e){var r=[];for(var n in t)n in e||r.push(n);return r},r.extend=function(t){for(var e=arguments,r=[],n=arguments.length-1;n-- >0;)r[n]=e[n+1];for(var i=0,a=r;i=0)return!0;return!1};var o={};r.warnOnce=function(t){o[t]||("undefined"!=typeof console&&console.warn(t),o[t]=!0)},r.isCounterClockwise=function(t,e,r){return(r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)},r.calculateSignedArea=function(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r0||Math.abs(e.y-n.y)>0)&&Math.abs(r.calculateSignedArea(t))>.01},r.sphericalToCartesian=function(t){var e=t[0],r=t[1],n=t[2];return r+=90,r*=Math.PI/180,n*=Math.PI/180,{x:e*Math.cos(r)*Math.sin(n),y:e*Math.sin(r)*Math.sin(n),z:e*Math.cos(n)}},r.parseCacheControl=function(t){var e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""}),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r}return e}},{"../geo/coordinate":61,"../style-spec/util/deep_equal":155,"@mapbox/point-geometry":4,"@mapbox/unitbezier":7}],276:[function(t,e,r){var n=function(t,e,r,n){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,null!=t.id&&(this.id=t.id)},i={geometry:{}};i.geometry.get=function(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry},i.geometry.set=function(t){this._geometry=t},n.prototype.toJSON=function(){var t={geometry:this.geometry};for(var e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t},Object.defineProperties(n.prototype,i),e.exports=n},{}],277:[function(t,e,r){var n=t("./script_detection");e.exports=function(t){for(var r="",i=0;i":"\ufe40","?":"\ufe16","@":"\uff20","[":"\ufe47","\\":"\uff3c","]":"\ufe48","^":"\uff3e",_:"\ufe33","`":"\uff40","{":"\ufe37","|":"\u2015","}":"\ufe38","~":"\uff5e","\xa2":"\uffe0","\xa3":"\uffe1","\xa5":"\uffe5","\xa6":"\uffe4","\xac":"\uffe2","\xaf":"\uffe3","\u2013":"\ufe32","\u2014":"\ufe31","\u2018":"\ufe43","\u2019":"\ufe44","\u201c":"\ufe41","\u201d":"\ufe42","\u2026":"\ufe19","\u2027":"\u30fb","\u20a9":"\uffe6","\u3001":"\ufe11","\u3002":"\ufe12","\u3008":"\ufe3f","\u3009":"\ufe40","\u300a":"\ufe3d","\u300b":"\ufe3e","\u300c":"\ufe41","\u300d":"\ufe42","\u300e":"\ufe43","\u300f":"\ufe44","\u3010":"\ufe3b","\u3011":"\ufe3c","\u3014":"\ufe39","\u3015":"\ufe3a","\u3016":"\ufe17","\u3017":"\ufe18","\uff01":"\ufe15","\uff08":"\ufe35","\uff09":"\ufe36","\uff0c":"\ufe10","\uff0d":"\ufe32","\uff0e":"\u30fb","\uff1a":"\ufe13","\uff1b":"\ufe14","\uff1c":"\ufe3f","\uff1e":"\ufe40","\uff1f":"\ufe16","\uff3b":"\ufe47","\uff3d":"\ufe48","\uff3f":"\ufe33","\uff5b":"\ufe37","\uff5c":"\u2015","\uff5d":"\ufe38","\uff5f":"\ufe35","\uff60":"\ufe36","\uff61":"\ufe12","\uff62":"\ufe41","\uff63":"\ufe42"}},{"./script_detection":269}],278:[function(t,e,r){function n(t,e,r){void 0===r&&(r={}),Object.defineProperty(e,"_classRegistryKey",{value:t,writeable:!1}),g[t]={klass:e,omit:r.omit||[],shallow:r.shallow||[]}}var i=t("grid-index"),a=t("../style-spec/util/color"),o=t("../style-spec/expression"),s=o.StylePropertyFunction,l=o.StyleExpression,u=o.StyleExpressionWithErrorHandling,c=o.ZoomDependentExpression,h=o.ZoomConstantExpression,f=t("../style-spec/expression/compound_expression").CompoundExpression,p=t("../style-spec/expression/definitions"),d=t("./window").ImageData,g={};for(var v in n("Object",Object),i.serialize=function(t,e){var r=t.toArrayBuffer();return e&&e.push(r),r},i.deserialize=function(t){return new i(t)},n("Grid",i),n("Color",a),n("StylePropertyFunction",s),n("StyleExpression",l,{omit:["_evaluator"]}),n("StyleExpressionWithErrorHandling",u,{omit:["_evaluator"]}),n("ZoomDependentExpression",c),n("ZoomConstantExpression",h),n("CompoundExpression",f,{omit:["_evaluate"]}),p)p[v]._classRegistryKey||n("Expression_"+v,p[v]);e.exports={register:n,serialize:function t(e,r){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp)return e;if(e instanceof ArrayBuffer)return r&&r.push(e),e;if(ArrayBuffer.isView(e)){var n=e;return r&&r.push(n.buffer),n}if(e instanceof d)return r&&r.push(e.data.buffer),e;if(Array.isArray(e)){for(var i=[],a=0,o=e;a=0)){var f=e[h];c[h]=g[u].shallow.indexOf(h)>=0?f:t(f,r)}return{name:u,properties:c}}throw new Error("can't serialize object of type "+typeof e)},deserialize:function t(e){if(null===e||void 0===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof d)return e;if(Array.isArray(e))return e.map(function(e){return t(e)});if("object"==typeof e){var r=e,n=r.name,i=r.properties;if(!n)throw new Error("can't deserialize object of anonymous class");var a=g[n].klass;if(!a)throw new Error("can't deserialize unregistered class "+n);if(a.deserialize)return a.deserialize(i._serialized);for(var o=Object.create(a.prototype),s=0,l=Object.keys(i);s=0?i[u]:t(i[u])}return o}throw new Error("can't deserialize object of type "+typeof e)}}},{"../style-spec/expression":139,"../style-spec/expression/compound_expression":123,"../style-spec/expression/definitions":131,"../style-spec/util/color":153,"./window":254,"grid-index":24}],279:[function(t,e,r){var n=t("./web_worker"),i=function(){this.active={}};i.prototype.acquire=function(e){if(!this.workers){var r=t("../").workerCount;for(this.workers=[];this.workers.length0}function IW(t){var e={},r={};switch(t.type){case"circle":oe.extendFlat(r,{"circle-radius":t.circle.radius,"circle-color":t.color,"circle-opacity":t.opacity});break;case"line":oe.extendFlat(r,{"line-width":t.line.width,"line-color":t.color,"line-opacity":t.opacity});break;case"fill":oe.extendFlat(r,{"fill-color":t.color,"fill-outline-color":t.fill.outlinecolor,"fill-opacity":t.opacity});break;case"symbol":var n=t.symbol,i=LW(n.textposition,n.iconsize);oe.extendFlat(e,{"icon-image":n.icon+"-15","icon-size":n.iconsize/10,"text-field":n.text,"text-size":n.textfont.size,"text-anchor":i.anchor,"text-offset":i.offset}),oe.extendFlat(r,{"icon-color":t.color,"text-color":n.textfont.color,"text-opacity":t.opacity})}return{layout:e,paint:r}}zW.update=function(t){this.visible?this.needsNewSource(t)?(this.updateLayer(t),this.updateSource(t)):this.needsNewLayer(t)?this.updateLayer(t):this.updateStyle(t):(this.updateSource(t),this.updateLayer(t)),this.visible=DW(t)},zW.needsNewSource=function(t){return this.sourceType!==t.sourcetype||this.source!==t.source||this.layerType!==t.type},zW.needsNewLayer=function(t){return this.layerType!==t.type||this.below!==t.below},zW.updateSource=function(t){var e=this.map;if(e.getSource(this.idSource)&&e.removeSource(this.idSource),this.sourceType=t.sourcetype,this.source=t.source,DW(t)){var r=function(t){var e,r=t.sourcetype,n=t.source,i={type:r};"geojson"===r?e="data":"vector"===r&&(e="string"==typeof n?"url":"tiles");return i[e]=n,i}(t);e.addSource(this.idSource,r)}},zW.updateLayer=function(t){var e=this.map,r=IW(t);e.getLayer(this.idLayer)&&e.removeLayer(this.idLayer),this.layerType=t.type,DW(t)&&e.addLayer({id:this.idLayer,source:this.idSource,"source-layer":t.sourcelayer||"",type:t.type,layout:r.layout,paint:r.paint},t.below)},zW.updateStyle=function(t){if(DW(t)){var e=IW(t);this.mapbox.setOptions(this.idLayer,"setLayoutProperty",e.layout),this.mapbox.setOptions(this.idLayer,"setPaintProperty",e.paint)}},zW.dispose=function(){var t=this.map;t.removeLayer(this.idLayer),t.removeSource(this.idSource)};var OW=function(t,e,r){var n=new PW(t,e);return n.update(r),n},RW=wo;function BW(t){this.id=t.id,this.gd=t.gd,this.container=t.container,this.isStatic=t.staticPlot;var e=t.fullLayout;this.uid=e._uid+"-"+this.id,this.opts=e[this.id],this.div=null,this.xaxis=null,this.yaxis=null,this.createFramework(e),this.map=null,this.accessToken=null,this.styleObj=null,this.traceHash={},this.layerList=[]}var FW=BW.prototype,NW=function(t){return new BW(t)};function jW(t){var e=CW.style.values,r=CW.style.dflt,n={};return oe.isPlainObject(t)?(n.id=t.id,n.style=t):"string"==typeof t?(n.id=t,n.style=-1!==e.indexOf(t)?VW(t):t):(n.id=r,n.style=VW(r)),n.transition={duration:0,delay:0},n}function VW(t){return wW.styleUrlPrefix+t+"-"+wW.styleUrlSuffix}function UW(t){return[t.lon,t.lat]}FW.plot=function(t,e,r){var n,i=this,a=i.opts=e[this.id];i.map&&a.accesstoken!==i.accessToken&&(i.map.remove(),i.map=null,i.styleObj=null,i.traceHash=[],i.layerList={}),n=i.map?new Promise(function(r,n){i.updateMap(t,e,r,n)}):new Promise(function(r,n){i.createMap(t,e,r,n)}),r.push(n)},FW.createMap=function(t,e,r,n){var i=this,a=i.gd,o=i.opts,s=i.styleObj=jW(o.style);i.accessToken=o.accesstoken;var l=i.map=new _W.Map({container:i.div,style:s.style,center:UW(o.center),zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,interactive:!i.isStatic,preserveDrawingBuffer:i.isStatic,doubleClickZoom:!1,boxZoom:!1}),u=wW.controlContainerClassName,c=i.div.getElementsByClassName(u)[0];function h(){qa.loneUnhover(e._toppaper)}i.div.removeChild(c),l._canvas.style.left="0px",l._canvas.style.top="0px",i.rejectOnError(n),l.once("load",function(){i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)}),i.isStatic||(l.on("moveend",function(t){if(i.map){var e=i.getView();if(o._input.center=o.center=e.center,o._input.zoom=o.zoom=e.zoom,o._input.bearing=o.bearing=e.bearing,o._input.pitch=o.pitch=e.pitch,t.originalEvent){var r={};r[i.id]=oe.extendFlat({},e),a.emit("plotly_relayout",r)}}}),l.on("mousemove",function(t){var e=i.div.getBoundingClientRect();t.clientX=t.point.x+e.left,t.clientY=t.point.y+e.top,t.target.getBoundingClientRect=function(){return e},i.xaxis.p2c=function(){return t.lngLat.lng},i.yaxis.p2c=function(){return t.lngLat.lat},qa.hover(a,t,i.id)}),l.on("click",function(t){qa.click(a,t.originalEvent)}),l.on("dragstart",h),l.on("zoomstart",h),l.on("dblclick",function(){var t=i.viewInitial;l.setCenter(UW(t.center)),l.setZoom(t.zoom),l.setBearing(t.bearing),l.setPitch(t.pitch);var e=i.getView();o._input.center=o.center=e.center,o._input.zoom=o.zoom=e.zoom,o._input.bearing=o.bearing=e.bearing,o._input.pitch=o.pitch=e.pitch,a.emit("plotly_doubleclick",null)}),i.clearSelect=function(){a._fullLayout._zoomlayer.selectAll(".select-outline").remove()})},FW.updateMap=function(t,e,r,n){var i=this,a=i.map;i.rejectOnError(n);var o=jW(i.opts.style);i.styleObj.id!==o.id?(i.styleObj=o,a.setStyle(o.style),a.once("styledata",function(){i.traceHash={},i.updateData(t),i.updateLayout(e),i.resolveOnRender(r)})):(i.updateData(t),i.updateLayout(e),i.resolveOnRender(r))},FW.updateData=function(t){var e,r,n,i,a=this.traceHash;for(n=0;n=0?Math.floor((e+180)/360):Math.ceil((e-180)/360)),u=e-l;if(qa.getClosest(n,function(t){var e=t.lonlat;if(e[0]===KW)return 1/0;var n=oe.wrap180(e[0]),i=e[1],l=s.project([n,i]),c=l.x-a.c2p([u,i]),h=l.y-o.c2p([n,r]),f=Math.max(3,t.mrc||0);return Math.max(Math.sqrt(c*c+h*h)-f,1-3/f)},t),!1!==t.index){var c=n[t.index],h=c.lonlat,f=[oe.wrap180(h[0])+l,h[1]],p=a.c2p(f),d=o.c2p(f),g=c.mrc||1;return t.x0=p-g,t.x1=p+g,t.y0=d-g,t.y1=d+g,t.color=Vx(i,c),t.extraText=function(t,e,r){var n=(e.hi||t.hoverinfo).split("+"),i=-1!==n.indexOf("all"),a=-1!==n.indexOf("lon"),o=-1!==n.indexOf("lat"),s=e.lonlat,l=[];function u(t){return t+"\xb0"}return i||a&&o?l.push("("+u(s[0])+", "+u(s[1])+")"):a?l.push(r.lon+u(s[0])):o&&l.push(r.lat+u(s[1])),(i||-1!==n.indexOf("text"))&&zs(e,t,l),l.join("
")}(i,c,n[0].t.labels),[t]}},sY.eventData=function(t,e){return t.lon=e.lon,t.lat=e.lat,t},sY.selectPoints=function(t,e){var r,n=t.cd,i=t.xaxis,a=t.yaxis,o=[],s=n[0].trace;if(!Er.hasMarkers(s))return[];if(!1===e)for(r=0;r0?1:-1}function WY(t){return GY(Math.cos(t))}function YY(t){return GY(Math.sin(t))}OY.plot=function(t,e){var r=e[this.id];this._hasClipOnAxisFalse=!1;for(var n=0;n=90||s>90&&l>=450?1:c<=0&&f<=0?0:Math.max(c,f);e=s<=180&&l>=180||s>180&&l>=540?-1:u>=0&&h>=0?0:Math.min(u,h);r=s<=270&&l>=270||s>270&&l>=630?-1:c>=0&&f>=0?0:Math.min(c,f);n=l>=360?1:u<=0&&h<=0?0:Math.max(u,h);return[e,r,n,i]}(d),v=g[2]-g[0],m=g[3]-g[1],y=p/f,x=Math.abs(m/v);y>x?(s=f,h=(p-(l=f*x))/i.h/2,u=[a[0],a[1]],c=[o[0]+h,o[1]-h]):(l=p,h=(f-(s=p/x))/i.w/2,u=[a[0]+h,a[1]-h],c=[o[0],o[1]]),r.xLength2=s,r.yLength2=l,r.xDomain2=u,r.yDomain2=c;var b=r.xOffset2=i.l+i.w*u[0],_=r.yOffset2=i.t+i.h*(1-c[1]),w=r.radius=s/v,k=r.cx=b-w*g[0],M=r.cy=_+w*g[3],A=r.cxx=k-b,T=r.cyy=M-_;r.updateRadialAxis(t,e),r.updateRadialAxisTitle(t,e),r.updateAngularAxis(t,e);var S=r.radialAxis.range,C=S[1]-S[0],E=r.xaxis={type:"linear",_id:"x",range:[g[0]*C,g[2]*C],domain:u};ui.setConvert(E,t),E.setScale();var L=r.yaxis={type:"linear",_id:"y",range:[g[1]*C,g[3]*C],domain:c};ui.setConvert(L,t),L.setScale(),E.isPtWithinRange=function(t){return r.isPtWithinSector(t)},L.isPtWithinRange=function(){return!0},n.frontplot.attr("transform",qY(b,_)).call(Lr.setClipUrl,r._hasClipOnAxisFalse?null:r.clipIds.circle),n.bgcircle.attr({d:jY(w,d),transform:qY(k,M)}).call(Fe.fill,e.bgcolor),r.clipPaths.circle.select("path").attr("d",jY(w,d)).attr("transform",qY(A,T)),r.framework.selectAll(".crisp").classed("crisp",0)},OY.updateRadialAxis=function(t,e){var r=this.gd,n=this.layers,i=this.radius,a=this.cx,o=this.cy,s=t._size,l=e.radialaxis,u=e.sector,c=PY(u[0]);this.fillViewInitialKey("radialaxis.angle",l.angle);var h=this.radialAxis=oe.extendFlat({},l,{_axislayer:n["radial-axis"],_gridlayer:n["radial-grid"],_id:"x",_pos:0,side:{counterclockwise:"top",clockwise:"bottom"}[l.side],domain:[0,i/s.w],anchor:"free",position:0,_counteraxis:!0,automargin:!1});BY(h,l,t),MY(h),l.range=h.range.slice(),l._input.range=h.range.slice(),this.fillViewInitialKey("radialaxis.range",h.range.slice()),"auto"===h.tickangle&&c>90&&c<=270&&(h.tickangle=180),h._transfn=function(t){return"translate("+h.l2p(t.x)+",0)"},h._gridpath=function(t){return NY(h.r2p(t.x),u)};var f=FY(l);this.radialTickLayout!==f&&(n["radial-axis"].selectAll(".xtick").remove(),this.radialTickLayout=f),ui.doTicks(r,h,!0),UY(n["radial-axis"],l.showticklabels||l.ticks,{transform:qY(a,o)+HY(-l.angle)}),UY(n["radial-grid"],l.showgrid,{transform:qY(a,o)}).selectAll("path").attr("transform",null),UY(n["radial-line"].select("line"),l.showline,{x1:0,y1:0,x2:i,y2:0,transform:qY(a,o)+HY(-l.angle)}).attr("stroke-width",l.linewidth).call(Fe.stroke,l.linecolor)},OY.updateRadialAxisTitle=function(t,e,r){var n=this.gd,i=this.radius,a=this.cx,o=this.cy,s=e.radialaxis,l=this.id+"title",u=void 0!==r?r:s.angle,c=EY(u),h=Math.cos(c),f=Math.sin(c),p=0;if(s.title){var d=Lr.bBox(this.layers["radial-axis"].node()).height,g=s.titlefont.size;p="counterclockwise"===s.side?-d-.4*g:d+.8*g}this.layers["radial-axis-title"]=Vn.draw(n,l,{propContainer:s,propName:this.id+".radialaxis.title",placeholder:CY(n,"Click to enter radial axis title"),attributes:{x:a+i/2*h+p*f,y:o-i/2*f+p*h,"text-anchor":"middle"},transform:{rotate:-u}})},OY.updateAngularAxis=function(t,e){var r=this,n=r.gd,a=r.layers,o=r.radius,s=r.cx,l=r.cy,u=e.angularaxis,c=e.sector,h=c.map(EY);r.fillViewInitialKey("angularaxis.rotation",u.rotation);var f=r.angularAxis=oe.extendFlat({},u,{_axislayer:a["angular-axis"],_gridlayer:a["angular-grid"],_id:"angular",_pos:0,side:"right",domain:[0,Math.PI],anchor:"free",position:0,_counteraxis:!0,automargin:!1,autorange:!1});if("linear"===f.type)VY(c)?f.range=c.slice():f.range=h.map(f.unTransformRad).map(LY),"radians"===f.thetaunit&&(f.tick0=LY(f.tick0),f.dtick=LY(f.dtick));else if("category"===f.type){var p=u.period?Math.max(u.period,u._categories.length):u._categories.length;f.range=[0,p],f._tickFilter=function(t){return r.isPtWithinSector({r:r.radialAxis.range[1],rad:f.c2rad(t.x)})}}function d(t){return f.c2rad(t.x,"degrees")}function g(t){return[o*Math.cos(t),o*Math.sin(t)]}BY(f,u,t),f._transfn=function(t){var e=d(t),r=g(e),n=qY(s+r[0],l-r[1]),a=i.select(this);return a&&a.node()&&a.classed("ticks")&&(n+=HY(-LY(e))),n},f._gridpath=function(t){var e=g(d(t));return"M0,0L"+-e[0]+","+e[1]};var v="outside"!==u.ticks?.7:.5;f._labelx=function(t){var e=d(t),r=f._labelStandoff,n=f._pad;return(0===YY(e)?0:Math.cos(e)*(r+n+v*t.fontSize))+WY(e)*(t.dx+r+n)},f._labely=function(t){var e=d(t),r=f._labelStandoff,n=f._labelShift,i=f._pad;return t.dy+t.fontSize*SY-n+-Math.sin(e)*(r+i+v*t.fontSize)},f._labelanchor=function(t,e){var r=d(e);return 0===YY(r)?WY(r)>0?"start":"end":"middle"};var m=FY(u);r.angularTickLayout!==m&&(a["angular-axis"].selectAll(".angulartick").remove(),r.angularTickLayout=m),ui.doTicks(n,f,!0),UY(a["angular-line"].select("path"),u.showline,{d:jY(o,c),transform:qY(s,l)}).attr("stroke-width",u.linewidth).call(Fe.stroke,u.linecolor)},OY.updateFx=function(t,e){this.gd._context.staticPlot||(this.updateAngularDrag(t,e),this.updateRadialDrag(t,e),this.updateMainDrag(t,e))},OY.updateMainDrag=function(t,e){var r=this,n=r.gd,a=r.layers,o=t._zoomlayer,s=uY.MINZOOM,l=uY.OFFEDGE,u=r.radius,h=r.cx,f=r.cy,p=r.cxx,d=r.cyy,g=e.sector,v=Xo.makeDragger(a,"path","maindrag","crosshair");i.select(v).attr("d",jY(u,g)).attr("transform",qY(h,f));var m,y,x,b,_,w,k,M,A,T={element:v,gd:n,subplot:r.id,plotinfo:{xaxis:r.xaxis,yaxis:r.yaxis},xaxes:[r.xaxis],yaxes:[r.yaxis]};function S(t,e){var r=t-p,n=e-d;return Math.sqrt(r*r+n*n)}function C(t,e){return Math.atan2(d-e,t-p)}function E(t,e){return[t*Math.cos(e),t*Math.sin(-e)]}function L(t,e){var r=uY.cornerLen,n=uY.cornerHalfWidth;if(0===t)return jY(2*n,g);var i=r/t/2,a=e-i,o=e+i,s=Math.max(0,Math.min(t,u)),l=s-n,c=s+n;return"M"+E(l,a)+"A"+[l,l]+" 0,0,0 "+E(l,o)+"L"+E(c,o)+"A"+[c,c]+" 0,0,1 "+E(c,a)+"Z"}function P(t,e){var r,n,i=m+t,a=y+e,o=S(m,y),c=Math.min(S(i,a),u),h=C(m,y),f=C(i,a);os?(o0==c>f[0]){y=u.range[1]=c,ui.doTicks(n,r.radialAxis,!0),a["radial-grid"].attr("transform",qY(s,l)).selectAll("path").attr("transform",null);var d=y-f[0],g=r.sectorBBox;for(var v in r.xaxis.range=[g[0]*d,g[2]*d],r.yaxis.range=[g[1]*d,g[3]*d],r.xaxis.setScale(),r.yaxis.setScale(),r.traceHash){var m=r.traceHash[v],x=oe.filterVisible(m),b=m[0][0].trace._module,_=n._fullLayout[r.id];if(b.plot(n,r,x,_),!O.traceIs(v,"gl"))for(var w=0;wo&&(o+=360);var s,l,u=PY(LY(t.rad)),c=u+360;return n[1]>=n[0]?(s=n[0],l=n[1]):(s=n[1],l=n[0]),i>=s&&i<=l&&(VY(e)||u>=a&&u<=o||c>=a&&c<=o)},OY.fillViewInitialKey=function(t,e){t in this.viewInitial||(this.viewInitial[t]=e)};var XY=hs.getSubplotCalcData,ZY=oe.counterRegex,JY=uY.attr,KY=uY.name,QY=ZY(KY),$Y={};$Y[JY]={valType:"subplotid",dflt:KY,editType:"calc"};var tX={attr:JY,name:KY,idRoot:KY,idRegex:QY,attrRegex:QY,attributes:$Y,layoutAttributes:mY,supplyLayoutDefaults:function(t,e,r){Nh(t,e,0,{type:uY.name,attributes:mY,handleDefaults:wY,font:e.font,paper_bgcolor:e.paper_bgcolor,fullData:r,layoutOut:e})},plot:function(t){for(var e=t._fullLayout,r=t.calcdata,n=e._subplots[KY],i=0;i")}var lX={hoverPoints:function(t,e,r,n){var i=Ux(t,e,r,n);if(i&&!1!==i[0].index){var a=i[0];if(void 0===a.index)return i;var o=t.subplot,s=a.cd[a.index],l=a.trace;if(o.isPtWithinSector(s))return a.xLabelVal=void 0,a.yLabelVal=void 0,a.extraText=sX(s,l,o),i}},makeHoverPointText:sX},uX=n.BADNUM,cX={moduleType:"trace",name:"scatterpolar",basePlotModule:tX,categories:["polar","symbols","markerColorscale","showLegend","scatter-like"],attributes:nX,supplyDefaults:function(t,e,r,n){function i(r,n){return oe.coerce(t,e,nX,r,n)}var a=i("r"),o=i("theta"),s=a&&o?Math.min(a.length,o.length):0;if(s){e._length=s,i("thetaunit"),i("mode",sl[1]?function(t){return t<=0}:function(t){return t>=0},n=0;n=0?(f=n.c2r(h)-o[0],w=p,d=i.c2rad(w,v.thetaunit),A[c]=M[2*c]=f*Math.cos(d),T[c]=M[2*c+1]=f*Math.sin(d)):A[c]=T[c]=M[2*c]=M[2*c+1]=NaN;var S=xW.sceneOptions(t,e,v,M);S.fill&&!s.fill2d&&(s.fill2d=!0),S.marker&&!s.scatter2d&&(s.scatter2d=!0),S.line&&!s.line2d&&(s.line2d=!0),!S.errorX&&!S.errorY||s.error2d||(s.error2d=!0),m.tree=kU(M),S.marker&&k>=dX&&(S.marker.cluster=m.tree),Er.hasMarkers(v)&&(S.selected.positions=S.unselected.positions=S.marker.positions),s.lineOptions.push(S.line),s.errorXOptions.push(S.errorX),s.errorYOptions.push(S.errorY),s.fillOptions.push(S.fill),s.markerOptions.push(S.marker),s.selectedOptions.push(S.selected),s.unselectedOptions.push(S.unselected),s.count=r.length,m._scene=s,m.index=u,m.x=A,m.y=T,m.rawx=A,m.rawy=T,m.r=y,m.theta=x,m.positions=M,m.count=k}}),xW.plot(t,e,r)},hoverPoints:function(t,e,r,n){var i=t.cd[0].t,a=i.r,o=i.theta,s=xW.hoverPoints(t,e,r,n);if(s&&!1!==s[0].index){var l=s[0];if(void 0===l.index)return s;var u=t.subplot,c=u.angularAxis,h=l.cd[l.index],f=l.trace;if(h.r=a[l.index],h.theta=o[l.index],h.rad=c.c2rad(h.theta,f.thetaunit),u.isPtWithinSector(h))return l.xLabelVal=void 0,l.yLabelVal=void 0,l.extraText=pX(h,f,u),s}},style:xW.style,selectPoints:xW.selectPoints,meta:{}},vX=b.extendFlat,mX={title:ze.title,titlefont:ze.titlefont,color:ze.color,tickmode:ze.tickmode,nticks:vX({},ze.nticks,{dflt:6,min:1}),tick0:ze.tick0,dtick:ze.dtick,tickvals:ze.tickvals,ticktext:ze.ticktext,ticks:ze.ticks,ticklen:ze.ticklen,tickwidth:ze.tickwidth,tickcolor:ze.tickcolor,showticklabels:ze.showticklabels,showtickprefix:ze.showtickprefix,tickprefix:ze.tickprefix,showticksuffix:ze.showticksuffix,ticksuffix:ze.ticksuffix,showexponent:ze.showexponent,exponentformat:ze.exponentformat,separatethousands:ze.separatethousands,tickfont:ze.tickfont,tickangle:ze.tickangle,tickformat:ze.tickformat,tickformatstops:ze.tickformatstops,hoverformat:ze.hoverformat,showline:vX({},ze.showline,{dflt:!0}),linecolor:ze.linecolor,linewidth:ze.linewidth,showgrid:vX({},ze.showgrid,{dflt:!0}),gridcolor:ze.gridcolor,gridwidth:ze.gridwidth,layer:ze.layer,min:{valType:"number",dflt:0,min:0}},yX=function(t,e,r){function n(r,n){return oe.coerce(t,e,mX,r,n)}e.type="linear";var i=n("color"),a=i===t.color?i:r.font.color,o=e._name.charAt(0).toUpperCase(),s="Component "+o,l=n("title",s);e._hovertitle=l===s?l:o,oe.coerceFont(n,"titlefont",{family:r.font.family,size:Math.round(1.2*r.font.size),color:a}),n("min"),Xe(t,e,n,"linear"),Ge(t,e,n,"linear",{}),We(t,e,n,{outerTicks:!0}),n("showticklabels")&&(oe.coerceFont(n,"tickfont",{family:r.font.family,size:r.font.size,color:a}),n("tickangle"),n("tickformat")),es(t,e,n,{dfltColor:i,bgColor:r.bgColor,blend:60,showLine:!0,showGrid:!0,noZeroLine:!0,attributes:mX}),n("hoverformat"),n("layer")},xX=zh.attributes,bX=(0,_e.overrideAll)({domain:xX({name:"ternary"}),bgcolor:{valType:"color",dflt:z.background},sum:{valType:"number",dflt:1,min:0},aaxis:mX,baxis:mX,caxis:mX},"plot","from-root"),_X=["aaxis","baxis","caxis"];function wX(t,e,r,n){var i,a,o,s=r("bgcolor"),l=r("sum");n.bgColor=Fe.combine(s,n.paper_bgcolor);for(var u=0;u<_X.length;u++)a=t[i=_X[u]]||{},o=e[i]={_name:i,type:"linear"},yX(a,o,n);var c=e.aaxis,h=e.baxis,f=e.caxis;c.min+h.min+f.min>=l&&(c.min=0,h.min=0,f.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}var kX=oe._,MX=b.extendFlat,AX=wo,TX=ko;function SX(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework(e)}var CX=SX,EX=SX.prototype;EX.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={},this.layers={}},EX.plot=function(t,e){var r=e[this.id],n=e._size;this._hasClipOnAxisFalse=!1;for(var i=0;iLX*g?i=(a=g)*LX:a=(i=d)/LX,o=f*i/d,s=p*a/g,r=e.l+e.w*c-i/2,n=e.t+e.h*(1-h)-a/2,l.x0=r,l.y0=n,l.w=i,l.h=a,l.sum=v,l.xaxis={type:"linear",range:[m+2*x-v,v-m-2*y],domain:[c-o/2,c+o/2],_id:"x"},li(l.xaxis,l.graphDiv._fullLayout),l.xaxis.setScale(),l.xaxis.isPtWithinRange=function(t){return t.a>=l.aaxis.range[0]&&t.a<=l.aaxis.range[1]&&t.b>=l.baxis.range[1]&&t.b<=l.baxis.range[0]&&t.c>=l.caxis.range[1]&&t.c<=l.caxis.range[0]},l.yaxis={type:"linear",range:[m,v-y-x],domain:[h-s/2,h+s/2],_id:"y"},li(l.yaxis,l.graphDiv._fullLayout),l.yaxis.setScale(),l.yaxis.isPtWithinRange=function(){return!0};var b=l.yaxis.domain[0],_=l.aaxis=MX({},t.aaxis,{visible:!0,range:[m,v-y-x],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[b,b+s*LX],_axislayer:l.layers.aaxis,_gridlayer:l.layers.agrid,_pos:0,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2,automargin:!1});li(_,l.graphDiv._fullLayout),_.setScale();var w=l.baxis=MX({},t.baxis,{visible:!0,range:[v-m-x,y],side:"bottom",_counterangle:30,domain:l.xaxis.domain,_axislayer:l.layers.baxis,_gridlayer:l.layers.bgrid,_counteraxis:l.aaxis,_pos:0,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a,automargin:!1});li(w,l.graphDiv._fullLayout),w.setScale(),_._counteraxis=w;var k=l.caxis=MX({},t.caxis,{visible:!0,range:[v-m-y,x],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[b,b+s*LX],_axislayer:l.layers.caxis,_gridlayer:l.layers.cgrid,_counteraxis:l.baxis,_pos:0,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2,automargin:!1});li(k,l.graphDiv._fullLayout),k.setScale();var M="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDef.select("path").attr("d",M),l.layers.plotbg.select("path").attr("d",M);var A="M0,"+a+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDefRelative.select("path").attr("d",A);var T="translate("+r+","+n+")";l.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",T),l.clipDefRelative.select("path").attr("transform",null);var S="translate("+(r-w._offset)+","+(n+a)+")";l.layers.baxis.attr("transform",S),l.layers.bgrid.attr("transform",S);var C="translate("+(r+i/2)+","+n+")rotate(30)translate(0,"+-_._offset+")";l.layers.aaxis.attr("transform",C),l.layers.agrid.attr("transform",C);var E="translate("+(r+i/2)+","+n+")rotate(-30)translate(0,"+-k._offset+")";l.layers.caxis.attr("transform",E),l.layers.cgrid.attr("transform",E),l.drawAxes(!0),l.plotContainer.selectAll(".crisp").classed("crisp",!1),l.layers.aline.select("path").attr("d",_.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(Fe.stroke,_.linecolor||"#000").style("stroke-width",(_.linewidth||0)+"px"),l.layers.bline.select("path").attr("d",w.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(Fe.stroke,w.linecolor||"#000").style("stroke-width",(w.linewidth||0)+"px"),l.layers.cline.select("path").attr("d",k.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(Fe.stroke,k.linecolor||"#000").style("stroke-width",(k.linewidth||0)+"px"),l.graphDiv._context.staticPlot||l.initInteractions(),Lr.setClipUrl(l.layers.frontplot,l._hasClipOnAxisFalse?null:l.clipId)},EX.drawAxes=function(t){var e=this.graphDiv,r=this.id.substr(7)+"title",n=this.aaxis,i=this.baxis,a=this.caxis;if(ui.doTicks(e,n,!0),ui.doTicks(e,i,!0),ui.doTicks(e,a,!0),t){var o=Math.max(n.showticklabels?n.tickfont.size/2:0,(a.showticklabels?.75*a.tickfont.size:0)+("outside"===a.ticks?.87*a.ticklen:0));this.layers["a-title"]=Vn.draw(e,"a"+r,{propContainer:n,propName:this.id+".aaxis.title",placeholder:kX(e,"Click to enter Component A title"),attributes:{x:this.x0+this.w/2,y:this.y0-n.titlefont.size/3-o,"text-anchor":"middle"}});var s=(i.showticklabels?i.tickfont.size:0)+("outside"===i.ticks?i.ticklen:0)+3;this.layers["b-title"]=Vn.draw(e,"b"+r,{propContainer:i,propName:this.id+".baxis.title",placeholder:kX(e,"Click to enter Component B title"),attributes:{x:this.x0-s,y:this.y0+this.h+.83*i.titlefont.size+s,"text-anchor":"middle"}}),this.layers["c-title"]=Vn.draw(e,"c"+r,{propContainer:a,propName:this.id+".caxis.title",placeholder:kX(e,"Click to enter Component C title"),attributes:{x:this.x0+this.w+s,y:this.y0+this.h+.83*a.titlefont.size+s,"text-anchor":"middle"}})}};var PX=Ee.MINZOOM/2+.87,zX="m-0.87,.5h"+PX+"v3h-"+(PX+5.2)+"l"+(PX/2+2.6)+",-"+(.87*PX+4.5)+"l2.6,1.5l-"+PX/2+","+.87*PX+"Z",DX="m0.87,.5h-"+PX+"v3h"+(PX+5.2)+"l-"+(PX/2+2.6)+",-"+(.87*PX+4.5)+"l-2.6,1.5l"+PX/2+","+.87*PX+"Z",IX="m0,1l"+PX/2+","+.87*PX+"l2.6,-1.5l-"+(PX/2+2.6)+",-"+(.87*PX+4.5)+"l-"+(PX/2+2.6)+","+(.87*PX+4.5)+"l2.6,1.5l"+PX/2+",-"+.87*PX+"Z",OX="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",RX=!0;function BX(t){i.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}EX.initInteractions=function(){var t,e,r,n,i,a,o,s,l,u,h=this,f=h.layers.plotbg.select("path").node(),p=h.graphDiv,d=p._fullLayout._zoomlayer,g={element:f,gd:p,plotinfo:{xaxis:h.xaxis,yaxis:h.yaxis},subplot:h.id,prepFn:function(v,m,y){g.xaxes=[h.xaxis],g.yaxes=[h.yaxis];var k=p._fullLayout.dragmode;v.shiftKey&&(k="pan"===k?"zoom":"pan"),g.minDrag="lasso"===k?1:void 0,"zoom"===k?(g.moveFn=x,g.doneFn=b,function(p,g,v){var m=f.getBoundingClientRect();t=g-m.left,e=v-m.top,r={a:h.aaxis.range[0],b:h.baxis.range[1],c:h.caxis.range[1]},i=r,n=h.aaxis.range[1]-r.a,a=c(h.graphDiv._fullLayout[h.id].bgcolor).getLuminance(),o="M0,"+h.h+"L"+h.w/2+", 0L"+h.w+","+h.h+"Z",s=!1,l=d.append("path").attr("class","zoombox").attr("transform","translate("+h.x0+", "+h.y0+")").style({fill:a>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",o),u=d.append("path").attr("class","zoombox-corners").attr("transform","translate("+h.x0+", "+h.y0+")").style({fill:Fe.background,stroke:Fe.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),TX(d)}(0,m,y)):"pan"===k?(g.moveFn=_,g.doneFn=w,r={a:h.aaxis.range[0],b:h.baxis.range[1],c:h.caxis.range[1]},i=r,TX(d)):"select"!==k&&"lasso"!==k||AX(v,m,y,g,k)},clickFn:function(t,e){if(BX(p),2===t){var r={};r[h.id+".aaxis.min"]=0,r[h.id+".baxis.min"]=0,r[h.id+".caxis.min"]=0,p.emit("plotly_doubleclick",null),O.call("relayout",p,r)}qa.click(p,e,h.id)}};function v(t,e){return 1-e/h.h}function m(t,e){return 1-(t+(h.h-e)/Math.sqrt(3))/h.w}function y(t,e){return(t-(h.h-e)/Math.sqrt(3))/h.w}function x(c,f){var p=t+c,d=e+f,g=Math.max(0,Math.min(1,v(0,e),v(0,d))),x=Math.max(0,Math.min(1,m(t,e),m(p,d))),b=Math.max(0,Math.min(1,y(t,e),y(p,d))),_=(g/2+b)*h.w,w=(1-g/2-x)*h.w,k=(_+w)/2,M=w-_,A=(1-g)*h.h,T=A-M/LX;M.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),u.transition().style("opacity",1).duration(200),s=!0)}function b(){if(BX(p),i!==r){var t={};t[h.id+".aaxis.min"]=i.a,t[h.id+".baxis.min"]=i.b,t[h.id+".caxis.min"]=i.c,O.call("relayout",p,t),RX&&p.data&&p._context.showTips&&(oe.notifier(kX(p,"Double-click to zoom back out"),"long"),RX=!1)}}function _(t,e){var n=t/h.xaxis._m,a=e/h.yaxis._m,o=[(i={a:r.a-a,b:r.b+(n+a)/2,c:r.c-(n-a)/2}).a,i.b,i.c].sort(),s=o.indexOf(i.a),l=o.indexOf(i.b),u=o.indexOf(i.c);o[0]<0&&(o[1]+o[0]/2<0?(o[2]+=o[0]+o[1],o[0]=o[1]=0):(o[2]+=o[0]/2,o[1]+=o[0]/2,o[0]=0),i={a:o[s],b:o[l],c:o[u]},e=(r.a-i.a)*h.yaxis._m,t=(r.c-i.c-r.b+i.b)*h.xaxis._m);var c="translate("+(h.x0+t)+","+(h.y0+e)+")";h.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",c);var f="translate("+-t+","+-e+")";h.clipDefRelative.select("path").attr("transform",f),h.aaxis.range=[i.a,h.sum-i.b-i.c],h.baxis.range=[h.sum-i.a-i.c,i.b],h.caxis.range=[h.sum-i.a-i.b,i.c],h.drawAxes(!1),h.plotContainer.selectAll(".crisp").classed("crisp",!1),h._hasClipOnAxisFalse&&h.plotContainer.select(".scatterlayer").selectAll(".trace").call(Lr.hideOutsideRangePoints,h)}function w(){var t={};t[h.id+".aaxis.min"]=i.a,t[h.id+".baxis.min"]=i.b,t[h.id+".caxis.min"]=i.c,O.call("relayout",p,t)}f.onmousemove=function(t){qa.hover(p,t,h.id),p._fullLayout._lasthover=f,p._fullLayout._hoversubplot=h.id},f.onmouseout=function(t){p._dragging||da.unhover(p,t)},da.init(g)};var FX={},NX=hs.getSubplotCalcData,jX=oe.counterRegex;FX.name="ternary",FX.attr="subplot",FX.idRoot="ternary",FX.idRegex=FX.attrRegex=jX("ternary"),FX.attributes={subplot:{valType:"subplotid",dflt:"ternary",editType:"calc"}},FX.layoutAttributes=bX,FX.supplyLayoutDefaults=function(t,e,r){Nh(t,e,0,{type:"ternary",attributes:bX,handleDefaults:wX,font:e.font,paper_bgcolor:e.paper_bgcolor})},FX.plot=function(t){for(var e=t._fullLayout,r=t.calcdata,n=e._subplots.ternary,i=0;i"),i}function g(t,e){d.push(t._hovertitle+": "+ui.tickText(t,e,"hover").text)}},JX.selectPoints=Kx,JX.eventData=function(t,e,r,n,i){if(e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),n[i]){var a=n[i];t.a=a.a,t.b=a.b,t.c=a.c}else t.a=e.a,t.b=e.b,t.c=e.c;return t},JX.moduleType="trace",JX.name="scatterternary",JX.basePlotModule=FX,JX.categories=["ternary","symbols","markerColorscale","showLegend","scatter-like"],JX.meta={};var KX=JX,QX={},$X=Vi.pointsAccessorFunction;QX.moduleType="transform",QX.name="sort",QX.attributes={enabled:{valType:"boolean",dflt:!0,editType:"calc"},target:{valType:"string",strict:!0,noBlank:!0,arrayOk:!0,dflt:"x",editType:"calc"},order:{valType:"enumerated",values:["ascending","descending"],dflt:"ascending",editType:"calc"},editType:"calc"},QX.supplyDefaults=function(t){var e={};function r(r,n){return oe.coerce(t,e,QX.attributes,r,n)}return r("enabled")&&(r("target"),r("order")),e},QX.calcTransform=function(t,e,r){if(r.enabled){var n=oe.getTargetArray(e,r);if(n){var i,a,o=r.target,s=n.length,l=e._arrayAttrs,u=function(t,e,r){for(var n=e.length,i=new Array(n),a=e.slice().sort(function(t,e){switch(t.order){case"ascending":return function(t,r){return e(t)-e(r)};case"descending":return function(t,r){return e(r)-e(t)}}}(t,r)),o=0;o2?(s[0],s[2],n=s[1],i=s[3]):s.length?(n=s[0],i=s[1]):(s.x,n=s.y,s.x+s.width,i=s.y+s.height),l.length>2?(a=l[0],o=l[2],l[1],l[3]):l.length?(a=l[0],o=l[1]):(a=l.x,l.y,o=l.x+l.width,l.y+l.height),[a,n,o,i]}function sZ(t){if("number"==typeof t)return[t,t,t,t];if(2===t.length)return[t[0],t[1],t[0],t[1]];var e=yU(t);return[e.x,e.y,e.x+e.width,e.y+e.height]}iZ.prototype.render=function(){for(var t,e=this,r=[],n=arguments.length;n--;)r[n]=arguments[n];return r.length&&(t=this).update.apply(t,r),this.regl.attributes.preserveDrawingBuffer?this.draw():(this.dirty?null==this.planned&&(this.planned=rZ(function(){e.draw(),e.dirty=!0,e.planned=null})):(this.draw(),this.dirty=!0,rZ(function(){e.dirty=!1})),this)},iZ.prototype.update=function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];if(t.length){for(var r=0;rm))&&(a.lower||!(v1&&ra&&l?r._splomSubplots[g]=1:iSZ;for(r=0,n=0;r 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 \u2014 in vertex or in fragment\n vec4 surfaceColor = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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"]),RZ=Q_(["precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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"]),BZ=Q_(["precision mediump float;\n#define GLSLIFY 1\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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"]);DZ.createShader=function(t){var e=lk(t,IZ,OZ,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},DZ.createPickShader=function(t){var e=lk(t,IZ,BZ,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},DZ.createContourShader=function(t){var e=lk(t,RZ,OZ,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},DZ.createPickContourShader=function(t){var e=lk(t,RZ,BZ,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e};var FZ=function(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r=H_(e.dimension,"string"==typeof r?r:"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;n=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),a.push("1"),o.push("s["+l+"]-2"));var u=".lo("+a.join()+").hi("+o.join()+")";if(0===a.length&&(u=""),i>0){n.push("if(1");for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push("&&s[",l,"]>2");n.push("){grad",i,"(src.pick(",s.join(),")",u);for(var l=0;l=0||e.indexOf(-(l+1))>=0||n.push(",dst.pick(",s.join(),",",l,")",u);n.push(");")}for(var l=0;l1){dst.set(",s.join(),",",c,",0.5*(src.get(",f.join(),")-src.get(",p.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>1){diff(",h,",src.pick(",f.join(),")",u,",src.pick(",p.join(),")",u,");}else{zero(",h,");};");break;case"mirror":0===i?n.push("dst.set(",s.join(),",",c,",0);"):n.push("zero(",h,");");break;case"wrap":var d=s.slice(),g=s.slice();e[l]<0?(d[c]="s["+c+"]-2",g[c]="0"):(d[c]="s["+c+"]-1",g[c]="1"),0===i?n.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",d.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):n.push("if(s[",c,"]>2){diff(",h,",src.pick(",d.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",h,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}i>0&&n.push("};")}for(var a=0;a<1<=1)return!0;for(var t=0;t<3;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},iJ.pickSlots=1,iJ.setPickBase=function(t){this.pickId=t};var aJ=[0,0,0],oJ={showSurface:!1,showContour:!1,projections:[$Z.slice(),$Z.slice(),$Z.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]};function sJ(t,e){var r,n,i,a=e.axes&&e.axes.lastCubeProps.axis||aJ,o=e.showSurface,s=e.showContour;for(r=0;r<3;++r)for(o=o||e.surfaceProject[r],n=0;n<3;++n)s=s||e.contourProject[r][n];for(r=0;r<3;++r){var l=oJ.projections[r];for(n=0;n<16;++n)l[n]=0;for(n=0;n<4;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],iz(l,t.model,l);var u=oJ.clipBounds[r];for(i=0;i<2;++i)for(n=0;n<3;++n)u[i][n]=t.clipBounds[i][n];u[0][r]=-1e8,u[1][r]=1e8}return oJ.showSurface=o,oJ.showContour=s,oJ}var lJ={model:$Z,view:$Z,projection:$Z,inverseModel:$Z.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1,vertexColor:0},uJ=$Z.slice(),cJ=[1,0,0,0,1,0,0,0,1];function hJ(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=lJ;n.model=t.model||$Z,n.view=t.view||$Z,n.projection=t.projection||$Z,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=IP(n.inverseModel,n.model);for(var i=0;i<2;++i)for(var a=n.clipBounds[i],o=0;o<3;++o)a[o]=Math.min(Math.max(this.clipBounds[i][o],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=cJ,n.vertexColor=this.vertexColor;var s=uJ;for(iz(s,n.view,n.model),iz(s,n.projection,s),IP(s,s),i=0;i<3;++i)n.eyePosition[i]=s[12+i]/s[15];var l=s[15];for(i=0;i<3;++i)l+=this.lightPosition[i]*s[4*i+3];for(i=0;i<3;++i){var u=s[12+i];for(o=0;o<3;++o)u+=s[4*o+i]*this.lightPosition[o];n.lightPosition[i]=u/l}var c=sJ(n,this);if(c.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;i<3;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=c.projections[i],this._shader.uniforms.clipBounds=c.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(c.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var f=this._contourVAO;for(f.bind(),i=0;i<3;++i)for(h.uniforms.permutation=eJ[i],r.lineWidth(this.contourWidth[i]),o=0;o>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;c<2;++c)for(var h=c?a:1-a,f=0;f<2;++f)for(var p=i+c,d=s+f,g=h*(f?l:1-l),v=0;v<3;++v)u[v]+=this._field[v].get(p,d)*g;for(var m=this._pickResult.level,y=0;y<3;++y)if(m[y]=WT.le(this.contourLevels[y],u[y]),m[y]<0)this.contourLevels[y].length>0&&(m[y]=0);else if(m[y]Math.abs(b-u[y])&&(m[y]+=1)}for(r.index[0]=a<.5?i:i+1,r.index[1]=l<.5?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],v=0;v<3;++v)r.dataCoordinate[v]=this._field[v].get(r.index[0],r.index[1]);return r},iJ.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=dJ(t.contourWidth,Number)),"showContour"in t&&(this.showContour=dJ(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=dJ(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=vJ(t.contourColor)),"contourProject"in t&&(this.contourProject=dJ(t.contourProject,function(t){return dJ(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=vJ(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=dJ(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=dJ(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds),"vertexColor"in t&&(this.vertexColor=t.vertexColor?1:0);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(G_.freeFloat(this._field[2].data),this._field[2].data=G_.mallocFloat(Yb.nextPow2(n))),this._field[2]=Wb(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),pJ(this._field[2],e),this.shape=e.shape.slice();for(var i=this.shape,a=0;a<2;++a)this._field[2].size>this._field[a].data.length&&(G_.freeFloat(this._field[a].data),this._field[a].data=G_.mallocFloat(this._field[2].size)),this._field[a]=Wb(this._field[a].data,[i[0]+2,i[1]+2]);if(t.coords){var o=t.coords;if(!Array.isArray(o)||3!==o.length)throw new Error("gl-surface: invalid coordinates for x/y");for(a=0;a<2;++a){var s=o[a];for(f=0;f<2;++f)if(s.shape[f]!==i[f])throw new Error("gl-surface: coords have incorrect shape");pJ(this._field[a],s)}}else if(t.ticks){var l=t.ticks;if(!Array.isArray(l)||2!==l.length)throw new Error("gl-surface: invalid ticks");for(a=0;a<2;++a){var u=l[a];if((Array.isArray(u)||u.length)&&(u=Wb(u)),u.shape[0]!==i[a])throw new Error("gl-surface: invalid tick length");var c=Wb(u.data,i);c.stride[a]=u.stride[0],c.stride[1^a]=0,pJ(this._field[a],c)}}else{for(a=0;a<2;++a){var h=[0,0];h[a]=1,this._field[a]=Wb(this._field[a].data,[i[0]+2,i[1]+2],h,0)}this._field[0].set(0,0,0);for(var f=0;f0){for(var ct=0;ct<5;++ct)H.pop();D-=1}continue t}H.push(X[0],X[1],K[0],K[1],X[2]),D+=1}}Y.push(D)}this._contourOffsets[G]=W,this._contourCounts[G]=Y}var ht=G_.mallocFloat(H.length);for(a=0;a",maxDimensionCount:60,overdrag:45,releaseTransitionDuration:120,releaseTransitionEase:"cubic-out",scrollbarCaptureWidth:18,scrollbarHideDelay:1e3,scrollbarHideDuration:1e3,scrollbarOffset:5,scrollbarWidth:8,transitionDuration:100,transitionEase:"cubic-out",uplift:5,wrapSpacer:" ",wrapSplitCharacter:" ",cn:{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",scrollbarKit:"scrollbar-kit",scrollbar:"scrollbar",scrollbarSlider:"scrollbar-slider",scrollbarGlyph:"scrollbar-glyph",scrollbarCaptureZone:"scrollbar-capture-zone"}},HJ=b.extendFlat;function GJ(t){if(Array.isArray(t)){for(var e=0,r=0;r=e||u===t.length-1)&&(n[i]=o,o.key=l++,o.firstRowIndex=s,o.lastRowIndex=u,o={firstRowIndex:null,lastRowIndex:null,rows:[]},i+=a,s=u+1,a=0);return n}var QJ={},$J=b.extendFlat;QJ.splitToPanels=function(t){var e=[0,0],r=$J({},t,{key:"header",type:"header",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!0,values:t.calcdata.headerCells.values[t.specIndex],rowBlocks:t.calcdata.headerRowBlocks,calcdata:$J({},t.calcdata,{cells:t.calcdata.headerCells})});return[$J({},t,{key:"cells1",type:"cells",page:0,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),$J({},t,{key:"cells2",type:"cells",page:1,prevPages:e,currentRepaint:[null,null],dragHandle:!1,values:t.calcdata.cells.values[t.specIndex],rowBlocks:t.calcdata.rowBlocks}),r]},QJ.splitToCells=function(t){var e=function(t){var e=t.rowBlocks[t.page],r=e?e.rows[0].rowIndex:0,n=e?r+e.rows.length:0;return[r,n]}(t);return(t.values||[]).slice(e[0],e[1]).map(function(r,n){return{keyWithinBlock:n+("string"==typeof r&&r.match(/[<$&> ]/)?"_keybuster_"+Math.random():""),key:e[0]+n,column:t,calcdata:t.calcdata,page:t.page,rowBlocks:t.rowBlocks,value:r}})};var tK=oe.raiseToTop,eK=oe.cancelTransition,rK=function(t,e){var r=t._fullLayout._paper.selectAll("."+qJ.cn.table).data(e.map(function(e){var r=vB.unwrap(e).trace;return function(t,e){var r=YJ(e.cells.values),n=function(t){return t.slice(e.header.values.length,t.length)},i=YJ(e.header.values);i.length&&!i[0].length&&(i[0]=[""],i=YJ(i));var o=i.concat(n(r).map(function(){return XJ((i[0]||[""]).length)})),s=e.domain,l=Math.floor(t._fullLayout._size.w*(s.x[1]-s.x[0])),u=Math.floor(t._fullLayout._size.h*(s.y[1]-s.y[0])),c=e.header.values.length?o[0].map(function(){return e.header.height}):[qJ.emptyHeaderHeight],h=r.length?r[0].map(function(){return e.cells.height}):[],f=c.reduce(WJ,0),p=KJ(h,u-f+qJ.uplift),d=JJ(KJ(c,f),[]),g=JJ(p,d),v={},m=e._fullInput.columnorder.concat(n(r.map(function(t,e){return e}))),y=o.map(function(t,r){var n=Array.isArray(e.columnwidth)?e.columnwidth[Math.min(r,e.columnwidth.length-1)]:e.columnwidth;return a(n)?Number(n):1}),x=y.reduce(WJ,0);y=y.map(function(t){return t/x*l});var b=Math.max(GJ(e.header.line.width),GJ(e.cells.line.width)),_={key:e.index,translateX:s.x[0]*t._fullLayout._size.w,translateY:t._fullLayout._size.h*(1-s.y[1]),size:t._fullLayout._size,width:l,maxLineWidth:b,height:u,columnOrder:m,groupHeight:u,rowBlocks:g,headerRowBlocks:d,scrollY:0,cells:HJ({},e.cells,{values:r}),headerCells:HJ({},e.header,{values:o}),gdColumns:o.map(function(t){return t[0]}),gdColumnsOriginalOrder:o.map(function(t){return t[0]}),prevPages:[0,0],scrollbarState:{scrollbarScrollInProgress:!1},columns:o.map(function(t,e){var r=v[t];return v[t]=(r||0)+1,{key:t+"__"+v[t],label:t,specIndex:e,xIndex:m[e],xScale:ZJ,x:void 0,calcdata:void 0,columnWidth:y[e]}})};return _.columns.forEach(function(t){t.calcdata=_,t.x=ZJ(t)}),_}(t,r)}),vB.keyFun);r.exit().remove(),r.enter().append("g").classed(qJ.cn.table,!0).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"),r.attr("width",function(t){return t.width+t.size.l+t.size.r}).attr("height",function(t){return t.height+t.size.t+t.size.b}).attr("transform",function(t){return"translate("+t.translateX+","+t.translateY+")"});var n=r.selectAll("."+qJ.cn.tableControlView).data(vB.repeat,vB.keyFun);n.enter().append("g").classed(qJ.cn.tableControlView,!0).style("box-sizing","content-box").on("mousemove",function(e){n.filter(function(t){return e===t}).call(sK,t)}).on("mousewheel",function(e){e.scrollbarState.wheeling||(e.scrollbarState.wheeling=!0,i.event.stopPropagation(),i.event.preventDefault(),mK(t,n,null,e.scrollY+i.event.deltaY)(e),e.scrollbarState.wheeling=!1)}).call(sK,t,!0),n.attr("transform",function(t){return"translate("+t.size.l+" "+t.size.t+")"});var o=n.selectAll("."+qJ.cn.scrollBackground).data(vB.repeat,vB.keyFun);o.enter().append("rect").classed(qJ.cn.scrollBackground,!0).attr("fill","none"),o.attr("width",function(t){return t.width}).attr("height",function(t){return t.height}),n.each(function(e){Lr.setClipUrl(i.select(this),iK(t,e))});var s=n.selectAll("."+qJ.cn.yColumn).data(function(t){return t.columns},vB.keyFun);s.enter().append("g").classed(qJ.cn.yColumn,!0),s.exit().remove(),s.attr("transform",function(t){return"translate("+t.x+" 0)"}).call(i.behavior.drag().origin(function(e){return fK(i.select(this),e,-qJ.uplift),tK(this),e.calcdata.columnDragInProgress=!0,sK(n.filter(function(t){return e.calcdata.key===t.key}),t),e}).on("drag",function(t){var e=i.select(this),r=function(e){return(t===e?i.event.x:e.x)+e.columnWidth/2};t.x=Math.max(-qJ.overdrag,Math.min(t.calcdata.width+qJ.overdrag-t.columnWidth,i.event.x)),oK(s).filter(function(e){return e.calcdata.key===t.calcdata.key}).sort(function(t,e){return r(t)-r(e)}).forEach(function(e,r){e.xIndex=r,e.x=t===e?e.x:e.xScale(e)}),s.filter(function(e){return t!==e}).transition().ease(qJ.transitionEase).duration(qJ.transitionDuration).attr("transform",function(t){return"translate("+t.x+" 0)"}),e.call(eK).attr("transform","translate("+t.x+" -"+qJ.uplift+" )")}).on("dragend",function(e){var r=i.select(this),n=e.calcdata;e.x=e.xScale(e),e.calcdata.columnDragInProgress=!1,fK(r,e,0),function(t,e,r){var n=e.gdColumnsOriginalOrder;e.gdColumns.sort(function(t,e){return r[n.indexOf(t)]-r[n.indexOf(e)]}),e.columnorder=r,t.emit("plotly_restyle")}(t,n,n.columns.map(function(t){return t.xIndex}))})),s.each(function(e){Lr.setClipUrl(i.select(this),aK(t,e))});var l=s.selectAll("."+qJ.cn.columnBlock).data(QJ.splitToPanels,vB.keyFun);l.enter().append("g").classed(qJ.cn.columnBlock,!0).attr("id",function(t){return t.key}),l.style("cursor",function(t){return t.dragHandle?"ew-resize":t.calcdata.scrollbarState.barWiggleRoom?"ns-resize":"default"});var u=l.filter(dK),c=l.filter(pK);c.call(i.behavior.drag().origin(function(t){return i.event.stopPropagation(),t}).on("drag",mK(t,n,-1)).on("dragend",function(){})),lK(t,n,u,l),lK(t,n,c,l);var h=n.selectAll("."+qJ.cn.scrollAreaClip).data(vB.repeat,vB.keyFun);h.enter().append("clipPath").classed(qJ.cn.scrollAreaClip,!0).attr("id",function(e){return iK(t,e)});var f=h.selectAll("."+qJ.cn.scrollAreaClipRect).data(vB.repeat,vB.keyFun);f.enter().append("rect").classed(qJ.cn.scrollAreaClipRect,!0).attr("x",-qJ.overdrag).attr("y",-qJ.uplift).attr("fill","none"),f.attr("width",function(t){return t.width+2*qJ.overdrag}).attr("height",function(t){return t.height+qJ.uplift}),s.selectAll("."+qJ.cn.columnBoundary).data(vB.repeat,vB.keyFun).enter().append("g").classed(qJ.cn.columnBoundary,!0);var p=s.selectAll("."+qJ.cn.columnBoundaryClippath).data(vB.repeat,vB.keyFun);p.enter().append("clipPath").classed(qJ.cn.columnBoundaryClippath,!0),p.attr("id",function(e){return aK(t,e)});var d=p.selectAll("."+qJ.cn.columnBoundaryRect).data(vB.repeat,vB.keyFun);d.enter().append("rect").classed(qJ.cn.columnBoundaryRect,!0).attr("fill","none"),d.attr("width",function(t){return t.columnWidth+2*nK(t)}).attr("height",function(t){return t.calcdata.height+2*nK(t)+qJ.uplift}).attr("x",function(t){return-nK(t)}).attr("y",function(t){return-nK(t)}),vK(null,c,n)};function nK(t){return Math.ceil(t.calcdata.maxLineWidth/2)}function iK(t,e){return"clip"+t._fullLayout._uid+"_scrollAreaBottomClip_"+e.key}function aK(t,e){return"clip"+t._fullLayout._uid+"_columnBoundaryClippath_"+e.calcdata.key+"_"+e.specIndex}function oK(t){return[].concat.apply([],t.map(function(t){return t})).map(function(t){return t.__data__})}function sK(t,e,r){var n=t.selectAll("."+qJ.cn.scrollbarKit).data(vB.repeat,vB.keyFun);n.enter().append("g").classed(qJ.cn.scrollbarKit,!0).style("shape-rendering","geometricPrecision"),n.each(function(t){var e=t.scrollbarState;e.totalHeight=function(t){var e=t.rowBlocks;return kK(e,e.length-1)+(e.length?MK(e[e.length-1],1/0):1)}(t),e.scrollableAreaHeight=t.groupHeight-gK(t),e.currentlyVisibleHeight=Math.min(e.totalHeight,e.scrollableAreaHeight),e.ratio=e.currentlyVisibleHeight/e.totalHeight,e.barLength=Math.max(e.ratio*e.currentlyVisibleHeight,qJ.goldenRatio*qJ.scrollbarWidth),e.barWiggleRoom=e.currentlyVisibleHeight-e.barLength,e.wiggleRoom=Math.max(0,e.totalHeight-e.scrollableAreaHeight),e.topY=0===e.barWiggleRoom?0:t.scrollY/e.wiggleRoom*e.barWiggleRoom,e.bottomY=e.topY+e.barLength,e.dragMultiplier=e.wiggleRoom/e.barWiggleRoom}).attr("transform",function(t){return"translate("+(t.width+qJ.scrollbarWidth/2+qJ.scrollbarOffset)+" "+gK(t)+")"});var a=n.selectAll("."+qJ.cn.scrollbar).data(vB.repeat,vB.keyFun);a.enter().append("g").classed(qJ.cn.scrollbar,!0);var o=a.selectAll("."+qJ.cn.scrollbarSlider).data(vB.repeat,vB.keyFun);o.enter().append("g").classed(qJ.cn.scrollbarSlider,!0),o.attr("transform",function(t){return"translate(0 "+(t.scrollbarState.topY||0)+")"});var s=o.selectAll("."+qJ.cn.scrollbarGlyph).data(vB.repeat,vB.keyFun);s.enter().append("line").classed(qJ.cn.scrollbarGlyph,!0).attr("stroke","black").attr("stroke-width",qJ.scrollbarWidth).attr("stroke-linecap","round").attr("y1",qJ.scrollbarWidth/2),s.attr("y2",function(t){return t.scrollbarState.barLength-qJ.scrollbarWidth/2}).attr("stroke-opacity",function(t){return t.columnDragInProgress||!t.scrollbarState.barWiggleRoom||r?0:.4}),s.transition().delay(0).duration(0),s.transition().delay(qJ.scrollbarHideDelay).duration(qJ.scrollbarHideDuration).attr("stroke-opacity",0);var l=a.selectAll("."+qJ.cn.scrollbarCaptureZone).data(vB.repeat,vB.keyFun);l.enter().append("line").classed(qJ.cn.scrollbarCaptureZone,!0).attr("stroke","white").attr("stroke-opacity",.01).attr("stroke-width",qJ.scrollbarCaptureWidth).attr("stroke-linecap","butt").attr("y1",0).on("mousedown",function(r){var n=i.event.y,a=this.getBoundingClientRect(),o=r.scrollbarState,s=n-a.top,l=i.scale.linear().domain([0,o.scrollableAreaHeight]).range([0,o.totalHeight]).clamp(!0);o.topY<=s&&s<=o.bottomY||mK(e,t,null,l(s-o.barLength/2))(r)}).call(i.behavior.drag().origin(function(t){return i.event.stopPropagation(),t.scrollbarState.scrollbarScrollInProgress=!0,t}).on("drag",mK(e,t)).on("dragend",function(){})),l.attr("y2",function(t){return t.scrollbarState.scrollableAreaHeight})}function lK(t,e,r,n){var a=function(t){var e=t.selectAll("."+qJ.cn.columnCell).data(QJ.splitToCells,function(t){return t.keyWithinBlock});return e.enter().append("g").classed(qJ.cn.columnCell,!0),e.exit().remove(),e}(function(t){var e=t.selectAll("."+qJ.cn.columnCells).data(vB.repeat,vB.keyFun);return e.enter().append("g").classed(qJ.cn.columnCells,!0),e.exit().remove(),e}(r));!function(t){t.each(function(t,e){var r=t.calcdata.cells.font,n=t.column.specIndex,i={size:hK(r.size,n,e),color:hK(r.color,n,e),family:hK(r.family,n,e)};t.rowNumber=t.key,t.align=hK(t.calcdata.cells.align,n,e),t.cellBorderWidth=hK(t.calcdata.cells.line.width,n,e),t.font=i})}(a),function(t){t.attr("width",function(t){return t.column.columnWidth}).attr("stroke-width",function(t){return t.cellBorderWidth}).each(function(t){var e=i.select(this);Fe.stroke(e,hK(t.calcdata.cells.line.color,t.column.specIndex,t.rowNumber)),Fe.fill(e,hK(t.calcdata.cells.fill.color,t.column.specIndex,t.rowNumber))})}(function(t){var e=t.selectAll("."+qJ.cn.cellRect).data(vB.repeat,function(t){return t.keyWithinBlock});return e.enter().append("rect").classed(qJ.cn.cellRect,!0),e}(a));var o=function(t){var e=t.selectAll("."+qJ.cn.cellText).data(vB.repeat,function(t){return t.keyWithinBlock});return e.enter().append("text").classed(qJ.cn.cellText,!0).style("cursor",function(){return"auto"}).on("mousedown",function(){i.event.stopPropagation()}),e}(function(t){var e=t.selectAll("."+qJ.cn.cellTextHolder).data(vB.repeat,function(t){return t.keyWithinBlock});return e.enter().append("g").classed(qJ.cn.cellTextHolder,!0).style("shape-rendering","geometricPrecision"),e}(a));!function(t){t.each(function(t){Lr.font(i.select(this),t.font)})}(o),uK(o,e,n,t),wK(a)}function uK(t,e,r,n){t.text(function(t){var e=t.column.specIndex,r=t.rowNumber,n=t.value,a="string"==typeof n,o=a&&n.match(/
/i),s=!a||o;t.mayHaveMarkup=a&&n.match(/[<&>]/);var l,u="string"==typeof(l=n)&&l.match(qJ.latexCheck);t.latex=u;var c,h,f=u?"":hK(t.calcdata.cells.prefix,e,r)||"",p=u?"":hK(t.calcdata.cells.suffix,e,r)||"",d=u?null:hK(t.calcdata.cells.format,e,r)||null,g=f+(d?i.format(d)(t.value):t.value)+p;if(t.wrappingNeeded=!t.wrapped&&!s&&!u&&(c=cK(g)),t.cellHeightMayIncrease=o||u||t.mayHaveMarkup||(void 0===c?cK(g):c),t.needsConvertToTspans=t.mayHaveMarkup||t.wrappingNeeded||t.latex,t.wrappingNeeded){var v=(" "===qJ.wrapSplitCharacter?g.replace(/
i&&n.push(a),i+=l}return n}(i,l,s);1===u.length&&(u[0]===i.length-1?u.unshift(u[0]-1):u.push(u[0]+1)),u[0]%2&&u.reverse(),e.each(function(t,e){t.page=u[e],t.scrollY=l}),e.attr("transform",function(t){return"translate(0 "+(kK(t.rowBlocks,t.page)-t.scrollY)+")"}),t&&(yK(t,r,e,u,n.prevPages,n,0),yK(t,r,e,u,n.prevPages,n,1),sK(r,t))}}function mK(t,e,r,n){return function(a){var o=a.calcdata?a.calcdata:a,s=e.filter(function(t){return o.key===t.key}),l=r||o.scrollbarState.dragMultiplier;o.scrollY=void 0===n?o.scrollY+l*i.event.dy:n;var u=s.selectAll("."+qJ.cn.yColumn).selectAll("."+qJ.cn.columnBlock).filter(pK);vK(t,u,s)}}function yK(t,e,r,n,i,a,o){n[o]!==i[o]&&(clearTimeout(a.currentRepaint[o]),a.currentRepaint[o]=setTimeout(function(){var a=r.filter(function(t,e){return e===o&&n[e]!==i[e]});lK(t,e,a,r),i[o]=n[o]}))}function xK(t,e,r){return function(){var n=i.select(e.parentNode);n.each(function(t){var e=t.fragments;n.selectAll("tspan.line").each(function(t,r){e[r].width=this.getComputedTextLength()});var r,i,a=e[e.length-1].width,o=e.slice(0,-1),s=[],l=0,u=t.column.columnWidth-2*qJ.cellPad;for(t.value="";o.length;)l+(i=(r=o.shift()).width+a)>u&&(t.value+=s.join(qJ.wrapSpacer)+qJ.lineBreaker,s=[],l=0),s.push(r.text),l+=i;l&&(t.value+=s.join(qJ.wrapSpacer)),t.wrapped=!0}),n.selectAll("tspan.line").remove(),uK(n.select("."+qJ.cn.cellText),r,t),i.select(e.parentNode.parentNode).call(wK)}}function bK(t,e,r,n,a){return function(){if(!a.settledY){var o=i.select(e.parentNode),s=TK(a),l=a.key-s.firstRowIndex,u=s.rows[l].rowHeight,c=a.cellHeightMayIncrease?e.parentNode.getBoundingClientRect().height+2*qJ.cellPad:u,h=Math.max(c,u);h-s.rows[l].rowHeight&&(s.rows[l].rowHeight=h,t.selectAll("."+qJ.cn.columnCell).call(wK),vK(null,t.filter(pK),0),sK(r,n,!0)),o.attr("transform",function(){var t=this.parentNode.getBoundingClientRect(),e=i.select(this.parentNode).select("."+qJ.cn.cellRect).node().getBoundingClientRect(),r=this.transform.baseVal.consolidate(),n=e.top-t.top+(r?r.matrix.f:qJ.cellPad);return"translate("+_K(a,i.select(this.parentNode).select("."+qJ.cn.cellTextHolder).node().getBoundingClientRect().width)+" "+n+")"}),a.settledY=!0}}}function _K(t,e){switch(t.align){case"left":return qJ.cellPad;case"right":return t.column.columnWidth-(e||0)-qJ.cellPad;case"center":return(t.column.columnWidth-(e||0))/2;default:return qJ.cellPad}}function wK(t){t.attr("transform",function(t){var e=t.rowBlocks[0].auxiliaryBlocks.reduce(function(t,e){return t+MK(e,1/0)},0);return"translate(0 "+(MK(TK(t),t.key)+e)+")"}).selectAll("."+qJ.cn.cellRect).attr("height",function(t){return(e=TK(t),r=t.key,e.rows[r-e.firstRowIndex]).rowHeight;var e,r})}function kK(t,e){for(var r=0,n=e-1;n>=0;n--)r+=AK(t[n]);return r}function MK(t,e){for(var r=0,n=0;n1,p=1-n.violingap,d=l.bdPos=l.dPos*p*(1-n.violingroupgap)/(f?h:1),g=l.bPos=f?2*l.dPos*((l.num+.5)/h-.5)*p:0;if(l.wHover=l.dPos*(f?p/h:1),!0!==u.visible||l.empty)i.select(this).remove();else{var v=e[l.valLetter+"axis"],m=e[l.posLetter+"axis"],y="both"===u.side,x=y||"positive"===u.side,b=y||"negative"===u.side,_=u.box&&u.box.visible,w=u.meanline&&u.meanline.visible,k=n._violinScaleGroupStats[u.scalegroup];if(c.selectAll("path.violin").data(oe.identity).enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","violin").each(function(t){var e,r,n,a,o,c,h,f,p=i.select(this),_=t.density,w=_.length,M=t.pos+g,A=m.c2p(M);switch(u.scalemode){case"width":e=k.maxWidth/d;break;case"count":e=k.maxWidth/d*(k.maxCount/t.pts.length)}if(x){for(h=new Array(w),o=0;o0){var d,g,v,m,y,x=t.xa,b=t.ya;"h"===l.orientation?(y=e,d="y",v=b,g="x",m=x):(y=r,d="x",v=x,g="y",m=b);var _=s[t.index];if(y>=_.span[0]&&y<=_.span[1]){var w=oe.extendFlat({},t),k=m.c2p(y,!0),M=OK.getKdeValue(_,l,y),A=OK.getPositionOnKdePath(_,l,k),T=v._offset,S=v._length;w[d+"0"]=A[0],w[d+"1"]=A[1],w[g+"0"]=w[g+"1"]=k,w[g+"Label"]=g+": "+ui.hoverLabelText(m,y)+", "+s[0].t.labels.kde+" "+M.toFixed(3),w.spikeDistance=p[0].spikeDistance;var C=d+"Spike";w[C]=p[0][C],p[0].spikeDistance=void 0,p[0][C]=void 0,f.push(w),(o={stroke:t.color})[d+"1"]=oe.constrain(T+A[0],T,T+S),o[d+"2"]=oe.constrain(T+A[1],T,T+S),o[g+"1"]=o[g+"2"]=m._offset+k}}}-1!==u.indexOf("points")&&(a=Ol.hoverOnPoints(t,e,r));var E=i.selectAll(".violinline-"+l.uid).data(o?[0]:[]);return E.enter().append("line").classed("violinline-"+l.uid,!0).attr("stroke-width",1.5),E.exit().remove(),E.attr(o),"closest"===n?a?[a]:f:a?(f.push(a),f):f},selectPoints:Gl,moduleType:"trace",name:"violin",basePlotModule:ps,categories:["cartesian","svg","symbols","oriented","box-violin","showLegend","draggedPts","violinLayout"],meta:{}};return sb.register([bl,Kl,_b,pP,xP,kP,UF,ed,KX,GK,VV,jJ,iB,uU,mf,bW,zZ,tN,tP,MF,lY,ij,zK,ah,ZV,md,lB,_c,cX,gX]),sb.register([Ki,pb,mb,tZ]),sb.register([tc]),sb}); \ No newline at end of file diff --git a/dist/translation-keys.txt b/dist/translation-keys.txt index e71aefb2b75..797d4022574 100644 --- a/dist/translation-keys.txt +++ b/dist/translation-keys.txt @@ -1,16 +1,16 @@ Autoscale // components/modebar/buttons.js:137 Box Select // components/modebar/buttons.js:101 -Click to enter Colorscale title // plots/plots.js:317 -Click to enter Component A title // plots/ternary/ternary.js:394 -Click to enter Component B title // plots/ternary/ternary.js:409 -Click to enter Component C title // plots/ternary/ternary.js:420 -Click to enter Plot title // plot_api/plot_api.js:598 -Click to enter X axis title // plots/plots.js:315 -Click to enter Y axis title // plots/plots.js:316 -Click to enter radial axis title // plots/polar/polar.js:376 +Click to enter Colorscale title // plots/plots.js:316 +Click to enter Component A title // plots/ternary/ternary.js:390 +Click to enter Component B title // plots/ternary/ternary.js:405 +Click to enter Component C title // plots/ternary/ternary.js:416 +Click to enter Plot title // plot_api/plot_api.js:514 +Click to enter X axis title // plots/plots.js:314 +Click to enter Y axis title // plots/plots.js:315 +Click to enter radial axis title // plots/polar/polar.js:377 Compare data on hover // components/modebar/buttons.js:165 Double-click on legend to isolate one trace // components/legend/handle_click.js:89 -Double-click to zoom back out // plots/cartesian/dragbox.js:969 +Double-click to zoom back out // plots/cartesian/dragbox.js:1005 Download plot as a png // components/modebar/buttons.js:50 Edit in Chart Studio // components/modebar/buttons.js:74 IE only supports svg. Changing format to svg. // components/modebar/buttons.js:58 @@ -34,25 +34,25 @@ Turntable rotation // components/modebar/but Zoom // components/modebar/buttons.js:83 Zoom in // components/modebar/buttons.js:119 Zoom out // components/modebar/buttons.js:128 -close: // traces/ohlc/transform.js:139 -high: // traces/ohlc/transform.js:137 +close: // traces/ohlc/calc.js:104 +high: // traces/ohlc/calc.js:102 incoming flow count: // traces/sankey/plot.js:142 kde: // traces/violin/calc.js:73 lat: // traces/scattergeo/calc.js:48 lon: // traces/scattergeo/calc.js:49 -low: // traces/ohlc/transform.js:138 +low: // traces/ohlc/calc.js:103 lower fence: // traces/box/calc.js:141 max: // traces/box/calc.js:139 mean ± σ: // traces/box/calc.js:140 mean: // traces/box/calc.js:140 median: // traces/box/calc.js:135 min: // traces/box/calc.js:136 -new text // plots/plots.js:318 -open: // traces/ohlc/transform.js:136 +new text // plots/plots.js:317 +open: // traces/ohlc/calc.js:101 outgoing flow count: // traces/sankey/plot.js:143 q1: // traces/box/calc.js:137 q3: // traces/box/calc.js:138 source: // traces/sankey/plot.js:140 target: // traces/sankey/plot.js:141 -trace // plots/plots.js:320 +trace // plots/plots.js:319 upper fence: // traces/box/calc.js:142 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 949e5516b13..b5f8e1e68f3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "plotly.js", - "version": "1.35.2", + "version": "1.36.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 8fd772c6647..0ae376cdd10 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plotly.js", - "version": "1.35.2", + "version": "1.36.0", "description": "The open source javascript graphing library that powers plotly", "license": "MIT", "main": "./lib/index.js", diff --git a/src/assets/geo_assets.js b/src/assets/geo_assets.js index 5ed7f68a881..244f9415e67 100644 --- a/src/assets/geo_assets.js +++ b/src/assets/geo_assets.js @@ -12,6 +12,6 @@ var saneTopojson = require('sane-topojson'); // package version injected by `npm run preprocess` -exports.version = '1.35.2'; +exports.version = '1.36.0'; exports.topojson = saneTopojson; diff --git a/src/core.js b/src/core.js index 0445e651a10..2258fda44f0 100644 --- a/src/core.js +++ b/src/core.js @@ -9,7 +9,7 @@ 'use strict'; // package version injected by `npm run preprocess` -exports.version = '1.35.2'; +exports.version = '1.36.0'; // inject promise polyfill require('es6-promise').polyfill();